From 2bf4c772393460d1830fbed203a65197e5999a6c Mon Sep 17 00:00:00 2001 From: William Escande Date: Sat, 22 Jun 2024 15:41:53 -0700 Subject: [PATCH] Format: apply clang rules Restore SpacesBeforeTrailingComments to 2 to match current style Then run clang-format -i **/**.{c,h,cc,cpp,hpp} Then fix a bunch of typo (reported by gerrit) Then fix unnecessary multiline string Then fix whitespace for disabled clang format (reported by cpplint) This is no-op Bug: 311772251 Test: mmm packages/modules/Bluetooth Flag: Exempt Format only Change-Id: If135447803a40a2a07d4630ba2195e08ef8d250c --- .clang-format | 3 +- android/app/jni/com_android_bluetooth.h | 169 +- ...droid_bluetooth_BluetoothQualityReport.cpp | 68 +- .../app/jni/com_android_bluetooth_a2dp.cpp | 366 +- .../jni/com_android_bluetooth_a2dp_sink.cpp | 124 +- ...com_android_bluetooth_avrcp_controller.cpp | 821 +- .../com_android_bluetooth_avrcp_target.cpp | 547 +- ...oid_bluetooth_btservice_AdapterService.cpp | 1125 +- ..._bluetooth_btservice_BluetoothKeystore.cpp | 53 +- ...android_bluetooth_csip_set_coordinator.cpp | 112 +- .../app/jni/com_android_bluetooth_gatt.cpp | 2515 +- .../jni/com_android_bluetooth_hap_client.cpp | 326 +- .../jni/com_android_bluetooth_hearing_aid.cpp | 97 +- android/app/jni/com_android_bluetooth_hfp.cpp | 511 +- .../jni/com_android_bluetooth_hfpclient.cpp | 689 +- .../jni/com_android_bluetooth_hid_device.cpp | 153 +- .../jni/com_android_bluetooth_hid_host.cpp | 302 +- .../jni/com_android_bluetooth_le_audio.cpp | 1071 +- android/app/jni/com_android_bluetooth_pan.cpp | 102 +- android/app/jni/com_android_bluetooth_sdp.cpp | 301 +- android/app/jni/com_android_bluetooth_vc.cpp | 288 +- android/app/jni/jni_logging.h | 3 +- .../bluetooth/a2dp/A2dpCodecConfig.java | 2 +- .../le_audio/LeAudioCodecConfig.java | 2 +- .../bluetooth/map/BluetoothMapService.java | 4 +- .../com/android/bluetooth/sap/SapMessage.java | 4 +- flags/hfp.aconfig | 2 +- .../include/android-base/parseint.h | 28 +- .../include/android-base/properties.h | 3 +- floss/android-base/properties.cc | 3 +- floss/libflags/get_flags.cc | 10 +- .../server_configurable_flags/get_flags.h | 6 +- system/audio/asrc/asrc_resampler.cc | 210 +- system/audio/asrc/asrc_resampler.h | 14 +- system/audio/asrc/asrc_resampler_test.cc | 51 +- system/audio/asrc/asrc_tables.cc | 9 +- system/audio/asrc/asrc_tables.h | 7 +- system/audio/asrc/asrc_tables.py | 14 +- .../audio_bluetooth_hw/audio_bluetooth_hw.cc | 81 +- .../audio_bluetooth_hw/device_port_proxy.cc | 279 +- system/audio_bluetooth_hw/device_port_proxy.h | 52 +- .../device_port_proxy_hidl.cc | 273 +- .../device_port_proxy_hidl.h | 34 +- system/audio_bluetooth_hw/stream_apis.cc | 433 +- system/audio_bluetooth_hw/stream_apis.h | 43 +- system/audio_bluetooth_hw/utils.cc | 6 +- system/audio_bluetooth_hw/utils.h | 6 +- system/audio_bluetooth_hw/utils_unittest.cc | 7 +- system/audio_hal_interface/a2dp_encoding.cc | 137 +- system/audio_hal_interface/a2dp_encoding.h | 37 +- .../audio_hal_interface/a2dp_encoding_host.cc | 55 +- .../audio_hal_interface/a2dp_encoding_host.h | 6 +- .../aidl/a2dp_encoding_aidl.cc | 220 +- .../aidl/a2dp_encoding_aidl.h | 34 +- .../aidl/a2dp_provider_info.cc | 106 +- .../aidl/a2dp_provider_info.h | 47 +- .../aidl/a2dp_provider_info_unittest.cc | 434 +- .../audio_hal_interface/aidl/a2dp_transport.h | 10 +- .../audio_hal_interface/aidl/audio_ctrl_ack.h | 3 +- .../aidl/bluetooth_audio_port_impl.cc | 81 +- .../aidl/bluetooth_audio_port_impl.h | 20 +- .../aidl/client_interface_aidl.cc | 350 +- .../aidl/client_interface_aidl.h | 115 +- .../aidl/codec_status_aidl.cc | 178 +- .../aidl/codec_status_aidl.h | 28 +- .../hearing_aid_software_encoding_aidl.cc | 61 +- .../aidl/hearing_aid_software_encoding_aidl.h | 3 +- .../aidl/hfp_client_interface_aidl.cc | 89 +- .../aidl/hfp_client_interface_aidl.h | 53 +- .../aidl/le_audio_software_aidl.cc | 409 +- .../aidl/le_audio_software_aidl.h | 71 +- .../aidl/le_audio_utils.cc | 580 +- .../audio_hal_interface/aidl/le_audio_utils.h | 88 +- .../aidl/le_audio_utils_unittest.cc | 1173 +- .../audio_hal_interface/aidl/provider_info.cc | 28 +- .../audio_hal_interface/aidl/provider_info.h | 12 +- .../aidl/transport_instance.h | 38 +- system/audio_hal_interface/audio_linux.h | 126 +- .../libbt_audio_hal_a2dp_encoding_fuzzer.cpp | 25 +- ...ibbt_audio_hal_client_interface_fuzzer.cpp | 211 +- ...l_hearing_aid_software_encoding_fuzzer.cpp | 8 +- ...bbt_audio_hal_le_audio_software_fuzzer.cpp | 27 +- .../hal_version_manager.cc | 79 +- .../audio_hal_interface/hal_version_manager.h | 50 +- .../hal_version_manager_host.cc | 20 +- .../hearing_aid_software_encoding.cc | 24 +- .../hearing_aid_software_encoding.h | 3 +- .../hearing_aid_software_encoding_host.cc | 3 +- .../hfp_client_interface.cc | 138 +- .../hfp_client_interface.h | 19 +- .../hfp_client_interface_host.cc | 18 +- .../hidl/a2dp_encoding_hidl.cc | 103 +- .../hidl/a2dp_encoding_hidl.h | 2 +- .../hidl/client_interface_hidl.cc | 430 +- .../hidl/client_interface_hidl.h | 122 +- .../hidl/client_interface_hidl_unittest.cc | 546 +- .../hidl/codec_status_hidl.cc | 130 +- .../hidl/codec_status_hidl.h | 27 +- .../hearing_aid_software_encoding_hidl.cc | 70 +- .../hidl/hearing_aid_software_encoding_hidl.h | 3 +- .../hidl/le_audio_software_hidl.cc | 158 +- .../hidl/le_audio_software_hidl.h | 51 +- .../audio_hal_interface/le_audio_software.cc | 456 +- .../audio_hal_interface/le_audio_software.h | 61 +- .../le_audio_software_host.cc | 175 +- .../le_audio_software_host_transport.cc | 130 +- .../le_audio_software_host_transport.h | 36 +- .../le_audio_software_unittest.cc | 319 +- .../include/audio_hearing_aid_hw.h | 9 +- .../src/audio_hearing_aid_hw.cc | 480 +- .../test/audio_hearing_aid_hw_test.cc | 56 +- system/bta/ag/bta_ag_act.cc | 144 +- system/bta/ag/bta_ag_api.cc | 54 +- system/bta/ag/bta_ag_at.cc | 34 +- system/bta/ag/bta_ag_at.h | 9 +- system/bta/ag/bta_ag_cfg.cc | 24 +- system/bta/ag/bta_ag_cmd.cc | 479 +- system/bta/ag/bta_ag_int.h | 177 +- system/bta/ag/bta_ag_main.cc | 113 +- system/bta/ag/bta_ag_rfc.cc | 133 +- system/bta/ag/bta_ag_sco.cc | 380 +- system/bta/ag/bta_ag_sdp.cc | 127 +- system/bta/ag/bta_ag_swb_aptx.cc | 33 +- system/bta/ar/bta_ar.cc | 131 +- system/bta/ar/bta_ar_int.h | 2 +- system/bta/av/bta_av_aact.cc | 1224 +- system/bta/av/bta_av_act.cc | 701 +- system/bta/av/bta_av_api.cc | 131 +- system/bta/av/bta_av_cfg.cc | 245 +- system/bta/av/bta_av_ci.cc | 18 +- system/bta/av/bta_av_int.h | 252 +- system/bta/av/bta_av_main.cc | 368 +- system/bta/av/bta_av_ssm.cc | 36 +- system/bta/csis/csis_client.cc | 1075 +- system/bta/csis/csis_client_test.cc | 799 +- system/bta/csis/csis_types.h | 203 +- system/bta/dm/bta_dm_act.cc | 487 +- system/bta/dm/bta_dm_api.cc | 107 +- system/bta/dm/bta_dm_cfg.cc | 693 +- system/bta/dm/bta_dm_ci.cc | 10 +- system/bta/dm/bta_dm_device_search.cc | 297 +- system/bta/dm/bta_dm_device_search_int.h | 9 +- system/bta/dm/bta_dm_disc.cc | 420 +- system/bta/dm/bta_dm_disc.h | 3 +- system/bta/dm/bta_dm_disc_int.h | 15 +- system/bta/dm/bta_dm_disc_int_legacy.h | 7 +- system/bta/dm/bta_dm_disc_legacy.cc | 907 +- system/bta/dm/bta_dm_disc_legacy.h | 3 +- system/bta/dm/bta_dm_disc_sdp.cc | 189 +- system/bta/dm/bta_dm_gatt_client.cc | 125 +- system/bta/dm/bta_dm_gatt_client.h | 18 +- system/bta/dm/bta_dm_int.h | 58 +- system/bta/dm/bta_dm_pm.cc | 360 +- system/bta/dm/bta_dm_sec.cc | 347 +- system/bta/dm/bta_dm_sec_api.cc | 70 +- system/bta/dm/bta_dm_sec_int.h | 15 +- system/bta/gatt/bta_gattc_act.cc | 703 +- system/bta/gatt/bta_gattc_api.cc | 175 +- system/bta/gatt/bta_gattc_cache.cc | 404 +- system/bta/gatt/bta_gattc_db_storage.cc | 23 +- system/bta/gatt/bta_gattc_int.h | 144 +- system/bta/gatt/bta_gattc_main.cc | 317 +- system/bta/gatt/bta_gattc_queue.cc | 106 +- system/bta/gatt/bta_gattc_utils.cc | 177 +- system/bta/gatt/bta_gatts_act.cc | 199 +- system/bta/gatt/bta_gatts_api.cc | 56 +- system/bta/gatt/bta_gatts_int.h | 17 +- system/bta/gatt/bta_gatts_main.cc | 16 +- system/bta/gatt/bta_gatts_queue.cc | 19 +- system/bta/gatt/bta_gatts_utils.cc | 29 +- system/bta/gatt/database.cc | 113 +- system/bta/gatt/database.h | 10 +- system/bta/gatt/database_builder.cc | 118 +- system/bta/gatt/database_builder.h | 25 +- system/bta/groups/groups.cc | 92 +- system/bta/groups/groups_test.cc | 60 +- system/bta/has/has_client.cc | 960 +- system/bta/has/has_client_test.cc | 2839 +- system/bta/has/has_ctp.cc | 55 +- system/bta/has/has_ctp.h | 57 +- system/bta/has/has_journal.cc | 10 +- system/bta/has/has_journal.h | 14 +- system/bta/has/has_preset.cc | 16 +- system/bta/has/has_preset.h | 43 +- system/bta/has/has_types.cc | 3 +- system/bta/has/has_types.h | 84 +- system/bta/hd/bta_hd_act.cc | 61 +- system/bta/hd/bta_hd_api.cc | 39 +- system/bta/hd/bta_hd_main.cc | 7 +- system/bta/hearing_aid/hearing_aid.cc | 905 +- .../hearing_aid/hearing_aid_audio_source.cc | 78 +- system/bta/hf_client/bta_hf_client_act.cc | 57 +- system/bta/hf_client/bta_hf_client_api.cc | 19 +- system/bta/hf_client/bta_hf_client_at.cc | 489 +- system/bta/hf_client/bta_hf_client_at.h | 4 +- system/bta/hf_client/bta_hf_client_int.h | 97 +- system/bta/hf_client/bta_hf_client_main.cc | 343 +- system/bta/hf_client/bta_hf_client_rfc.cc | 80 +- system/bta/hf_client/bta_hf_client_sco.cc | 52 +- system/bta/hf_client/bta_hf_client_sdp.cc | 109 +- system/bta/hh/bta_hh_act.cc | 273 +- system/bta/hh/bta_hh_api.cc | 53 +- system/bta/hh/bta_hh_cfg.cc | 24 +- system/bta/hh/bta_hh_headtracker.cc | 73 +- system/bta/hh/bta_hh_int.h | 96 +- system/bta/hh/bta_hh_le.cc | 758 +- system/bta/hh/bta_hh_main.cc | 46 +- system/bta/hh/bta_hh_utils.cc | 88 +- system/bta/include/bta_ag_api.h | 61 +- system/bta/include/bta_ag_swb_aptx.h | 9 +- system/bta/include/bta_api.h | 182 +- system/bta/include/bta_ar_api.h | 16 +- system/bta/include/bta_av_api.h | 129 +- system/bta/include/bta_av_ci.h | 5 +- system/bta/include/bta_av_co.h | 53 +- system/bta/include/bta_csis_api.h | 16 +- system/bta/include/bta_dm_acl.h | 3 +- system/bta/include/bta_dm_ci.h | 3 +- system/bta/include/bta_gatt_api.h | 161 +- system/bta/include/bta_gatt_queue.h | 45 +- system/bta/include/bta_gatt_server_queue.h | 11 +- system/bta/include/bta_groups.h | 39 +- system/bta/include/bta_has_api.h | 22 +- system/bta/include/bta_hd_api.h | 4 +- system/bta/include/bta_hearing_aid_api.h | 21 +- system/bta/include/bta_hf_client_api.h | 127 +- system/bta/include/bta_hh_api.h | 47 +- system/bta/include/bta_hh_co.h | 17 +- system/bta/include/bta_jv_api.h | 110 +- system/bta/include/bta_jv_co.h | 3 +- system/bta/include/bta_le_audio_api.h | 43 +- .../include/bta_le_audio_broadcaster_api.h | 31 +- system/bta/include/bta_pan_api.h | 5 +- system/bta/include/bta_pan_ci.h | 9 +- system/bta/include/bta_pan_co.h | 6 +- system/bta/include/bta_ras_api.h | 40 +- system/bta/include/bta_sdp_api.h | 6 +- system/bta/include/bta_sec_api.h | 141 +- system/bta/include/bta_vc_api.h | 23 +- system/bta/include/utl.h | 5 +- system/bta/jv/bta_jv_act.cc | 640 +- system/bta/jv/bta_jv_api.cc | 155 +- system/bta/jv/bta_jv_int.h | 64 +- .../audio_hal_client/audio_hal_client.h | 99 +- .../audio_hal_client/audio_hal_client_test.cc | 310 +- .../audio_hal_client/audio_sink_hal_client.cc | 94 +- .../audio_source_hal_client.cc | 206 +- .../broadcast_configuration_provider.cc | 38 +- .../broadcast_configuration_provider.h | 364 +- .../bta/le_audio/broadcaster/broadcaster.cc | 770 +- .../le_audio/broadcaster/broadcaster_test.cc | 705 +- .../le_audio/broadcaster/broadcaster_types.cc | 136 +- .../le_audio/broadcaster/broadcaster_types.h | 168 +- .../broadcaster/mock_state_machine.cc | 32 +- .../le_audio/broadcaster/mock_state_machine.h | 170 +- .../bta/le_audio/broadcaster/state_machine.cc | 342 +- .../bta/le_audio/broadcaster/state_machine.h | 91 +- .../broadcaster/state_machine_test.cc | 1056 +- system/bta/le_audio/client.cc | 3179 +- system/bta/le_audio/client_linux.cc | 34 +- system/bta/le_audio/client_parser.cc | 392 +- system/bta/le_audio/client_parser.h | 45 +- system/bta/le_audio/client_parser_test.cc | 1311 +- system/bta/le_audio/codec_interface.cc | 118 +- system/bta/le_audio/codec_interface.h | 23 +- system/bta/le_audio/codec_manager.cc | 709 +- system/bta/le_audio/codec_manager.h | 74 +- system/bta/le_audio/codec_manager_test.cc | 1081 +- .../bta/le_audio/content_control_id_keeper.cc | 44 +- .../bta/le_audio/content_control_id_keeper.h | 4 +- .../content_control_id_keeper_test.cc | 45 +- system/bta/le_audio/device_groups.cc | 1232 +- system/bta/le_audio/device_groups.h | 241 +- system/bta/le_audio/devices.cc | 681 +- system/bta/le_audio/devices.h | 97 +- system/bta/le_audio/devices_test.cc | 1612 +- system/bta/le_audio/hal_verifier.cc | 4 +- system/bta/le_audio/le_audio_client_test.cc | 8015 +++-- system/bta/le_audio/le_audio_health_status.cc | 89 +- system/bta/le_audio/le_audio_health_status.h | 27 +- .../le_audio/le_audio_health_status_test.cc | 72 +- system/bta/le_audio/le_audio_log_history.cc | 38 +- system/bta/le_audio/le_audio_log_history.h | 10 +- .../le_audio_set_configuration_provider.h | 10 +- ...e_audio_set_configuration_provider_json.cc | 438 +- system/bta/le_audio/le_audio_types.cc | 292 +- system/bta/le_audio/le_audio_types.h | 602 +- system/bta/le_audio/le_audio_types_test.cc | 258 +- system/bta/le_audio/le_audio_utils.cc | 281 +- system/bta/le_audio/le_audio_utils.h | 51 +- system/bta/le_audio/metrics_collector.cc | 120 +- system/bta/le_audio/metrics_collector.h | 18 +- .../bta/le_audio/metrics_collector_linux.cc | 12 +- system/bta/le_audio/metrics_collector_test.cc | 260 +- system/bta/le_audio/mock_codec_interface.cc | 42 +- system/bta/le_audio/mock_codec_interface.h | 26 +- system/bta/le_audio/mock_codec_manager.cc | 114 +- system/bta/le_audio/mock_codec_manager.h | 80 +- system/bta/le_audio/mock_state_machine.cc | 9 +- system/bta/le_audio/mock_state_machine.h | 93 +- system/bta/le_audio/state_machine.cc | 1543 +- system/bta/le_audio/state_machine.h | 71 +- system/bta/le_audio/state_machine_test.cc | 4965 ++-- system/bta/le_audio/storage_helper.cc | 184 +- system/bta/le_audio/storage_helper.h | 24 +- system/bta/le_audio/storage_helper_test.cc | 347 +- system/bta/pan/bta_pan_act.cc | 99 +- system/bta/pan/bta_pan_api.cc | 45 +- system/bta/pan/bta_pan_ci.cc | 24 +- system/bta/pan/bta_pan_int.h | 29 +- system/bta/pan/bta_pan_main.cc | 84 +- system/bta/pb/bta_pbs_int.h | 12 +- system/bta/ras/ras_client.cc | 283 +- system/bta/ras/ras_server.cc | 271 +- system/bta/ras/ras_types.h | 20 +- system/bta/ras/ras_utils.cc | 3 +- system/bta/rfcomm/bta_rfcomm_scn.cc | 19 +- system/bta/sdp/bta_sdp_act.cc | 215 +- system/bta/sdp/bta_sdp_api.cc | 9 +- system/bta/sdp/bta_sdp_cfg.cc | 7 +- system/bta/sys/bta_sys.h | 127 +- system/bta/sys/bta_sys_conn.cc | 58 +- system/bta/sys/bta_sys_int.h | 20 +- system/bta/sys/bta_sys_main.cc | 19 +- system/bta/sys/utl.cc | 31 +- system/bta/test/bta_ag_sco_test.cc | 44 +- system/bta/test/bta_ag_test.cc | 137 +- system/bta/test/bta_api_test.cc | 24 +- system/bta/test/bta_av_test.cc | 31 +- system/bta/test/bta_dip_test.cc | 60 +- system/bta/test/bta_disc_test.cc | 189 +- system/bta/test/bta_dm_cust_uuid_test.cc | 18 +- system/bta/test/bta_dm_test.cc | 193 +- system/bta/test/bta_gatt_client_test.cc | 10 +- system/bta/test/bta_gatt_test.cc | 197 +- .../bta/test/bta_hf_client_add_record_test.cc | 3 +- .../bta/test/bta_hf_client_security_test.cc | 2 +- system/bta/test/bta_hf_client_test.cc | 2 +- system/bta/test/bta_hh_test.cc | 44 +- system/bta/test/bta_jv_test.cc | 196 +- system/bta/test/bta_pan_test.cc | 65 +- system/bta/test/bta_rfcomm_scn_test.cc | 4 +- system/bta/test/bta_sdp_test.cc | 7 +- system/bta/test/bta_sec_test.cc | 143 +- system/bta/test/bta_test_fixtures.h | 27 +- system/bta/test/common/bta_dm_api_mock.h | 24 +- system/bta/test/common/bta_gatt_api_mock.cc | 39 +- system/bta/test/common/bta_gatt_api_mock.h | 63 +- system/bta/test/common/bta_gatt_queue_mock.cc | 26 +- system/bta/test/common/bta_gatt_queue_mock.h | 15 +- system/bta/test/common/btif_storage_mock.cc | 90 +- system/bta/test/common/btif_storage_mock.h | 63 +- system/bta/test/common/btm_api_mock.cc | 18 +- system/bta/test/common/btm_api_mock.h | 104 +- system/bta/test/common/fake_osi.h | 1 + system/bta/test/common/mock_csis_client.cc | 8 +- system/bta/test/common/mock_csis_client.h | 14 +- system/bta/test/common/mock_device_groups.cc | 15 +- system/bta/test/common/mock_device_groups.h | 23 +- .../database_builder_sample_device_test.cc | 24 +- system/bta/test/gatt/database_builder_test.cc | 12 +- system/bta/test/gatt/database_test.cc | 139 +- system/bta/vc/device.cc | 168 +- system/bta/vc/devices.h | 69 +- system/bta/vc/devices_test.cc | 317 +- system/bta/vc/types.h | 35 +- system/bta/vc/vc.cc | 560 +- system/bta/vc/vc_test.cc | 867 +- .../fuzzer/btcore_device_class_fuzzer.cpp | 5 +- system/btcore/fuzzer/btcore_module_fuzzer.cpp | 6 +- .../btcore/fuzzer/btcore_property_fuzzer.cpp | 7 +- system/btcore/include/device_class.h | 6 +- system/btcore/include/device_features.h | 4 +- system/btcore/include/event_mask.h | 4 +- system/btcore/include/property.h | 9 +- system/btcore/src/device_class.cc | 37 +- system/btcore/src/module.cc | 33 +- system/btcore/src/osi_module.cc | 4 +- system/btcore/src/property.cc | 47 +- system/btcore/test/device_class_test.cc | 25 +- system/btcore/test/property_test.cc | 65 +- system/btif/avrcp/avrcp_service.cc | 373 +- system/btif/avrcp/avrcp_service.h | 19 +- system/btif/co/bta_av_co.cc | 746 +- system/btif/co/bta_av_co_peer.cc | 56 +- system/btif/co/bta_dm_co.cc | 7 +- system/btif/co/bta_hh_co.cc | 185 +- system/btif/co/bta_pan_co.cc | 20 +- system/btif/include/bta_av_co.h | 83 +- system/btif/include/bta_av_co_peer.h | 65 +- system/btif/include/btif_a2dp.h | 15 +- system/btif/include/btif_a2dp_sink.h | 5 +- system/btif/include/btif_a2dp_source.h | 12 +- system/btif/include/btif_api.h | 25 +- system/btif/include/btif_av.h | 41 +- system/btif/include/btif_av_co.h | 17 +- system/btif/include/btif_avrcp_audio_track.h | 6 +- system/btif/include/btif_bqr.h | 49 +- system/btif/include/btif_common.h | 66 +- system/btif/include/btif_config.h | 27 +- system/btif/include/btif_debug_btsnoop.h | 1 - system/btif/include/btif_debug_conn.h | 8 +- system/btif/include/btif_dm.h | 33 +- system/btif/include/btif_gatt_util.h | 3 +- system/btif/include/btif_hd.h | 6 +- system/btif/include/btif_hh.h | 13 +- system/btif/include/btif_jni_task.h | 5 +- system/btif/include/btif_metrics_logging.h | 56 +- system/btif/include/btif_pan_internal.h | 17 +- system/btif/include/btif_profile_queue.h | 3 +- system/btif/include/btif_profile_storage.h | 41 +- system/btif/include/btif_rc.h | 3 +- system/btif/include/btif_sock_l2cap.h | 14 +- system/btif/include/btif_sock_logging.h | 5 +- system/btif/include/btif_sock_rfc.h | 13 +- system/btif/include/btif_sock_sco.h | 3 +- system/btif/include/btif_sock_sdp.h | 3 +- system/btif/include/btif_sock_thread.h | 12 +- system/btif/include/btif_storage.h | 98 +- system/btif/include/core_callbacks.h | 64 +- system/btif/include/mock_core_callbacks.h | 126 +- system/btif/include/stack_manager_t.h | 4 +- system/btif/src/bluetooth.cc | 946 +- system/btif/src/btif_a2dp.cc | 48 +- system/btif/src/btif_a2dp_sink.cc | 194 +- system/btif/src/btif_a2dp_source.cc | 601 +- system/btif/src/btif_av.cc | 1651 +- system/btif/src/btif_avrcp_audio_track.cc | 58 +- .../btif/src/btif_avrcp_audio_track_linux.cc | 8 +- system/btif/src/btif_bqr.cc | 380 +- system/btif/src/btif_config.cc | 88 +- system/btif/src/btif_core.cc | 222 +- system/btif/src/btif_csis_client.cc | 75 +- system/btif/src/btif_debug_conn.cc | 26 +- system/btif/src/btif_dm.cc | 1328 +- system/btif/src/btif_gatt.cc | 20 +- system/btif/src/btif_gatt_client.cc | 615 +- system/btif/src/btif_gatt_server.cc | 238 +- system/btif/src/btif_gatt_util.cc | 21 +- system/btif/src/btif_has_client.cc | 115 +- system/btif/src/btif_hd.cc | 108 +- system/btif/src/btif_hearing_aid.cc | 42 +- system/btif/src/btif_hf.cc | 546 +- system/btif/src/btif_hf_client.cc | 210 +- system/btif/src/btif_hh.cc | 556 +- system/btif/src/btif_iot_config.cc | 70 +- system/btif/src/btif_jni_task.cc | 28 +- system/btif/src/btif_keystore.cc | 20 +- system/btif/src/btif_le_audio.cc | 238 +- system/btif/src/btif_le_audio_broadcaster.cc | 92 +- .../btif/src/btif_leaudio_hal_version_host.cc | 2 +- system/btif/src/btif_metrics_logging.cc | 99 +- system/btif/src/btif_pan.cc | 246 +- system/btif/src/btif_profile_queue.cc | 54 +- system/btif/src/btif_profile_storage.cc | 633 +- system/btif/src/btif_rc.cc | 1780 +- system/btif/src/btif_sdp.cc | 40 +- system/btif/src/btif_sdp_server.cc | 198 +- system/btif/src/btif_sock.cc | 120 +- system/btif/src/btif_sock_l2cap.cc | 404 +- system/btif/src/btif_sock_logging.cc | 54 +- system/btif/src/btif_sock_rfc.cc | 399 +- system/btif/src/btif_sock_sco.cc | 92 +- system/btif/src/btif_sock_sdp.cc | 175 +- system/btif/src/btif_sock_thread.cc | 81 +- system/btif/src/btif_sock_util.cc | 15 +- system/btif/src/btif_storage.cc | 542 +- system/btif/src/btif_uid.cc | 17 +- system/btif/src/btif_util.cc | 12 +- system/btif/src/btif_vc.cc | 181 +- system/btif/src/stack_manager.cc | 120 +- .../btif/test/btif_avrcp_audio_track_test.cc | 24 +- system/btif/test/btif_core_test.cc | 1066 +- system/btif/test/btif_dm_test.cc | 110 +- .../btif/test/btif_hf_client_service_test.cc | 23 +- system/btif/test/btif_hh_test.cc | 140 +- system/btif/test/btif_keystore_test.cc | 16 +- system/btif/test/btif_profile_queue_test.cc | 27 +- system/btif/test/btif_rc_test.cc | 299 +- system/btif/test/btif_storage_test.cc | 8 +- system/common/address_obfuscator.cc | 13 +- system/common/address_obfuscator.h | 4 +- system/common/address_obfuscator_unittest.cc | 69 +- system/common/base_bind_unittest.cc | 8 +- .../benchmark/thread_performance_benchmark.cc | 120 +- system/common/id_generator.h | 4 +- system/common/leaky_bonded_queue.h | 4 +- system/common/leaky_bonded_queue_unittest.cc | 4 +- system/common/lru.h | 7 +- system/common/lru_unittest.cc | 5 +- system/common/message_loop_thread.cc | 38 +- system/common/message_loop_thread.h | 13 +- system/common/message_loop_thread_unittest.cc | 86 +- system/common/metric_id_allocator.cc | 42 +- system/common/metric_id_allocator.h | 12 +- system/common/metric_id_allocator_unittest.cc | 115 +- system/common/metrics.cc | 560 +- system/common/metrics.h | 120 +- system/common/metrics_linux.cc | 126 +- system/common/metrics_unittest.cc | 386 +- system/common/repeating_timer.cc | 45 +- system/common/repeating_timer.h | 10 +- system/common/repeating_timer_unittest.cc | 87 +- system/common/state_machine.h | 34 +- system/common/state_machine_unittest.cc | 16 +- system/common/stop_watch_legacy.cc | 26 +- system/common/stop_watch_legacy.h | 4 +- system/common/test/thread_performance_test.cc | 144 +- system/common/time_util.cc | 9 +- system/common/time_util_unittest.cc | 4 +- system/conf/interop_database.conf | 2 +- system/device/fuzzer/btdevice_esco_fuzzer.cpp | 408 +- system/device/include/device_iot_conf_defs.h | 3 +- system/device/include/device_iot_config.h | 44 +- system/device/include/esco_parameters.h | 69 +- system/device/include/interop.h | 29 +- system/device/include/interop_config.h | 66 +- system/device/src/device_iot_config.cc | 194 +- system/device/src/device_iot_config_int.cc | 79 +- system/device/src/device_iot_config_int.h | 15 +- system/device/src/esco_parameters.cc | 692 +- system/device/src/interop.cc | 499 +- system/device/test/device_iot_config_test.cc | 1352 +- system/device/test/interop_test.cc | 449 +- .../encoder_for_aptx/include/aptXbtenc.h | 3 +- .../embdrv/encoder_for_aptx/src/AptxEncoder.h | 42 +- .../embdrv/encoder_for_aptx/src/AptxTables.h | 116 +- .../encoder_for_aptx/src/CodewordPacker.h | 15 +- .../encoder_for_aptx/src/DitherGenerator.h | 11 +- .../encoder_for_aptx/src/ProcessSubband.c | 21 +- system/embdrv/encoder_for_aptx/src/Qmf.h | 69 +- system/embdrv/encoder_for_aptx/src/QmfConv.c | 12 +- .../encoder_for_aptx/src/QuantiseDifference.c | 57 +- .../embdrv/encoder_for_aptx/src/Quantiser.h | 16 +- .../encoder_for_aptx/src/SubbandFunctions.h | 14 +- .../src/SubbandFunctionsCommon.h | 60 +- .../encoder_for_aptx/src/SyncInserter.h | 6 +- .../embdrv/encoder_for_aptx/src/aptXbtenc.c | 65 +- .../encoder_for_aptxhd/include/aptXHDbtenc.h | 4 +- .../encoder_for_aptxhd/src/AptxEncoder.h | 33 +- .../encoder_for_aptxhd/src/AptxTables.h | 260 +- .../encoder_for_aptxhd/src/CodewordPacker.h | 9 +- .../encoder_for_aptxhd/src/DitherGenerator.h | 9 +- .../encoder_for_aptxhd/src/ProcessSubband.c | 19 +- system/embdrv/encoder_for_aptxhd/src/Qmf.h | 59 +- .../embdrv/encoder_for_aptxhd/src/QmfConv.c | 8 +- .../src/QuantiseDifference.c | 61 +- .../embdrv/encoder_for_aptxhd/src/Quantiser.h | 16 +- .../encoder_for_aptxhd/src/SubbandFunctions.h | 14 +- .../src/SubbandFunctionsCommon.h | 58 +- .../encoder_for_aptxhd/src/SyncInserter.h | 6 +- .../encoder_for_aptxhd/src/aptXHDbtenc.c | 63 +- system/embdrv/g722/fuzzer/g722_fuzzer.cc | 16 +- system/embdrv/g722/g722_decode.cc | 620 +- system/embdrv/g722/g722_enc_dec.h | 140 +- system/embdrv/g722/g722_encode.cc | 645 +- system/embdrv/g722/g722_typedefs.h | 28 +- system/embdrv/sbc/decoder/include/oi_assert.h | 7 +- .../embdrv/sbc/decoder/include/oi_bitstream.h | 6 +- .../embdrv/sbc/decoder/include/oi_bt_spec.h | 6 +- .../embdrv/sbc/decoder/include/oi_codec_sbc.h | 53 +- .../decoder/include/oi_codec_sbc_private.h | 89 +- .../embdrv/sbc/decoder/include/oi_cpu_dep.h | 53 +- .../embdrv/sbc/decoder/include/oi_modules.h | 20 +- system/embdrv/sbc/decoder/include/oi_status.h | 1086 +- .../embdrv/sbc/decoder/include/oi_stddefs.h | 52 +- system/embdrv/sbc/decoder/include/oi_time.h | 9 +- system/embdrv/sbc/decoder/include/oi_utils.h | 15 +- system/embdrv/sbc/decoder/sbcdecoder_fuzzer.c | 18 +- system/embdrv/sbc/decoder/srce/alloc.c | 14 +- system/embdrv/sbc/decoder/srce/bitalloc-sbc.c | 24 +- system/embdrv/sbc/decoder/srce/bitalloc.c | 35 +- system/embdrv/sbc/decoder/srce/decoder-oina.c | 19 +- .../embdrv/sbc/decoder/srce/decoder-private.c | 39 +- system/embdrv/sbc/decoder/srce/decoder-sbc.c | 98 +- system/embdrv/sbc/decoder/srce/dequant.c | 103 +- system/embdrv/sbc/decoder/srce/framing-sbc.c | 15 +- system/embdrv/sbc/decoder/srce/framing.c | 82 +- .../sbc/decoder/srce/oi_codec_version.c | 6 +- .../sbc/decoder/srce/synthesis-8-generated.c | 3 +- .../embdrv/sbc/decoder/srce/synthesis-dct8.c | 5 +- .../embdrv/sbc/decoder/srce/synthesis-sbc.c | 151 +- system/embdrv/sbc/encoder/include/sbc_dct.h | 11 +- .../embdrv/sbc/encoder/include/sbc_encoder.h | 11 +- system/embdrv/sbc/encoder/srce/sbc_analysis.c | 1219 +- system/embdrv/sbc/encoder/srce/sbc_dct.c | 72 +- .../embdrv/sbc/encoder/srce/sbc_dct_coeffs.c | 135 +- .../sbc/encoder/srce/sbc_enc_bit_alloc_mono.c | 56 +- .../sbc/encoder/srce/sbc_enc_bit_alloc_ste.c | 46 +- .../embdrv/sbc/encoder/srce/sbc_enc_coeffs.c | 378 +- system/embdrv/sbc/encoder/srce/sbc_encoder.c | 149 +- system/embdrv/sbc/encoder/srce/sbc_packing.c | 29 +- system/embdrv/tests/src/aptx.cc | 14 +- system/embdrv/tests/src/aptxhd.cc | 16 +- system/gd/common/audit_log.cc | 17 +- system/gd/common/audit_log.h | 3 +- system/gd/common/bidi_queue.h | 34 +- system/gd/common/bidi_queue_unittest.cc | 40 +- system/gd/common/bind.h | 3 +- system/gd/common/blocking_queue.h | 12 +- system/gd/common/blocking_queue_unittest.cc | 27 +- system/gd/common/byte_array.h | 46 +- system/gd/common/byte_array_test.cc | 14 +- system/gd/common/circular_buffer.h | 32 +- system/gd/common/circular_buffer_test.cc | 11 +- system/gd/common/contextual_callback.h | 22 +- system/gd/common/i_postable_context.h | 4 +- system/gd/common/init_flags.h | 10 +- system/gd/common/interfaces/ILoggable.h | 4 +- system/gd/common/list_map.h | 81 +- system/gd/common/list_map_test.cc | 4 +- system/gd/common/lru_cache.h | 87 +- system/gd/common/lru_cache_test.cc | 4 +- system/gd/common/metric_id_manager.cc | 30 +- system/gd/common/metric_id_manager.h | 15 +- .../gd/common/metric_id_manager_unittest.cc | 146 +- system/gd/common/multi_priority_queue.h | 19 +- system/gd/common/multi_priority_queue_test.cc | 4 +- system/gd/common/numbers.h | 5 +- system/gd/common/numbers_test.cc | 4 +- system/gd/common/postable_context.h | 18 +- system/gd/common/stop_watch.cc | 30 +- system/gd/common/stop_watch.h | 4 +- system/gd/common/strings.cc | 26 +- system/gd/common/strings.h | 46 +- system/gd/common/strings_test.cc | 37 +- system/gd/common/sync_map_count.h | 13 +- system/gd/common/sync_map_count_test.cc | 24 +- .../testing/wired_pair_of_bidi_queues.h | 34 +- system/gd/crypto_toolbox/aes.cc | 278 +- system/gd/crypto_toolbox/aes.h | 42 +- system/gd/crypto_toolbox/aes_cmac.cc | 11 +- system/gd/crypto_toolbox/crypto_toolbox.cc | 54 +- system/gd/crypto_toolbox/crypto_toolbox.h | 72 +- .../gd/crypto_toolbox/crypto_toolbox_test.cc | 140 +- system/gd/discovery/device/bt_property.cc | 260 +- system/gd/discovery/device/bt_property.h | 108 +- .../discovery/device/bt_property_unittest.cc | 476 +- system/gd/discovery/device/data_parser.cc | 8 +- system/gd/discovery/device/data_parser.h | 4 +- .../discovery/device/data_parser_unittest.cc | 59 +- system/gd/discovery/device/eir_data.cc | 19 +- system/gd/discovery/device/eir_data.h | 2 +- .../gd/discovery/device/eir_data_unittest.cc | 14 +- .../discovery/device/eir_test_data_packets.cc | 24047 ++++++++-------- .../gd/dumpsys/bluetooth_flatbuffer_test.cc | 2 +- system/gd/dumpsys/bundler/bundler.cc | 69 +- system/gd/dumpsys/bundler/test.cc | 9 +- system/gd/dumpsys/filter.cc | 27 +- system/gd/dumpsys/filter.h | 1 + system/gd/dumpsys/filter_test.cc | 5 +- system/gd/dumpsys/internal/filter_internal.cc | 85 +- system/gd/dumpsys/internal/filter_internal.h | 21 +- .../dumpsys/internal/filter_internal_test.cc | 89 +- .../dumpsys/internal/test_data/float_bfbs.h | 29 +- .../dumpsys/internal/test_data/integer_bfbs.h | 30 +- .../dumpsys/internal/test_data/string_bfbs.h | 25 +- .../dumpsys/internal/test_data/struct_bfbs.h | 48 +- system/gd/dumpsys/reflection_schema.cc | 31 +- system/gd/dumpsys/reflection_schema.h | 4 +- system/gd/dumpsys/reflection_schema_test.cc | 2 +- system/gd/dumpsys/test_data/bar.h | 2 +- system/gd/dumpsys/test_data/baz.h | 6 +- system/gd/dumpsys/test_data/foo.h | 6 +- system/gd/dumpsys/test_data/qux.h | 6 +- system/gd/facade/facade_main.cc | 34 +- system/gd/facade/grpc_root_server.cc | 24 +- system/gd/facade/grpc_root_server.h | 4 +- system/gd/facade/read_only_property_server.cc | 17 +- system/gd/facade/read_only_property_server.h | 4 +- system/gd/fuzz/helpers.cc | 4 +- system/gd/fuzz/helpers.h | 7 +- system/gd/grpc/grpc_event_queue.h | 11 +- system/gd/grpc/grpc_module.cc | 31 +- system/gd/grpc/grpc_module.h | 8 +- system/gd/hal/facade.cc | 72 +- system/gd/hal/facade.h | 4 +- system/gd/hal/fuzz/fuzz_hci_hal.cc | 4 +- system/gd/hal/fuzz/fuzz_hci_hal.h | 10 +- system/gd/hal/hci_backend.h | 4 +- system/gd/hal/hci_backend_aidl.cc | 45 +- system/gd/hal/hci_backend_hidl.cc | 70 +- system/gd/hal/hci_hal.h | 12 +- system/gd/hal/hci_hal_android.cc | 66 +- system/gd/hal/hci_hal_android_test.cc | 36 +- system/gd/hal/hci_hal_fake.cc | 16 +- system/gd/hal/hci_hal_fake.h | 20 +- system/gd/hal/hci_hal_host.cc | 152 +- system/gd/hal/hci_hal_host.h | 20 +- system/gd/hal/hci_hal_host_rootcanal.cc | 130 +- system/gd/hal/hci_hal_host_test.cc | 25 +- system/gd/hal/link_clocker.cc | 32 +- system/gd/hal/link_clocker.h | 10 +- system/gd/hal/mgmt.cc | 16 +- system/gd/hal/mgmt.h | 2 +- system/gd/hal/ranging_hal.h | 18 +- system/gd/hal/ranging_hal_android.cc | 91 +- system/gd/hal/ranging_hal_host.cc | 30 +- system/gd/hal/snoop_logger.cc | 454 +- system/gd/hal/snoop_logger.h | 87 +- system/gd/hal/snoop_logger_common.h | 10 +- system/gd/hal/snoop_logger_socket.cc | 34 +- system/gd/hal/snoop_logger_socket.h | 8 +- system/gd/hal/snoop_logger_socket_interface.h | 2 +- system/gd/hal/snoop_logger_socket_test.cc | 145 +- system/gd/hal/snoop_logger_socket_thread.cc | 15 +- system/gd/hal/snoop_logger_socket_thread.h | 4 +- .../gd/hal/snoop_logger_socket_thread_test.cc | 9 +- system/gd/hal/snoop_logger_test.cc | 1142 +- system/gd/hal/syscall_wrapper_impl.cc | 27 +- system/gd/hal/syscall_wrapper_impl.h | 5 +- system/gd/hal/syscall_wrapper_interface.h | 6 +- system/gd/hal/syscall_wrapper_mock.h | 2 +- system/gd/hci/acl_builder_test.cc | 20 +- system/gd/hci/acl_connection_interface.h | 28 +- system/gd/hci/acl_manager.cc | 179 +- system/gd/hci/acl_manager.h | 65 +- system/gd/hci/acl_manager/acl_connection.cc | 4 +- system/gd/hci/acl_manager/acl_connection.h | 13 +- system/gd/hci/acl_manager/acl_fragmenter.h | 4 +- system/gd/hci/acl_manager/acl_scheduler.cc | 172 +- system/gd/hci/acl_manager/acl_scheduler.h | 83 +- .../gd/hci/acl_manager/acl_scheduler_test.cc | 90 +- system/gd/hci/acl_manager/assembler.h | 28 +- .../hci/acl_manager/classic_acl_connection.cc | 340 +- .../hci/acl_manager/classic_acl_connection.h | 30 +- .../classic_acl_connection_test.cc | 195 +- system/gd/hci/acl_manager/classic_impl.h | 327 +- .../gd/hci/acl_manager/classic_impl_test.cc | 62 +- .../gd/hci/acl_manager/connection_callbacks.h | 2 +- .../acl_manager/connection_callbacks_mock.h | 6 +- .../connection_management_callbacks.h | 68 +- .../connection_management_callbacks_mock.h | 78 +- .../hci/acl_manager/le_acceptlist_callbacks.h | 2 +- .../gd/hci/acl_manager/le_acl_connection.cc | 253 +- system/gd/hci/acl_manager/le_acl_connection.h | 57 +- .../hci/acl_manager/le_acl_connection_test.cc | 52 +- .../hci/acl_manager/le_connection_callbacks.h | 5 +- .../le_connection_callbacks_mock.h | 14 +- .../le_connection_management_callbacks.h | 34 +- .../le_connection_management_callbacks_mock.h | 70 +- system/gd/hci/acl_manager/le_impl.h | 606 +- system/gd/hci/acl_manager/le_impl_test.cc | 742 +- .../hci/acl_manager/round_robin_scheduler.cc | 80 +- .../hci/acl_manager/round_robin_scheduler.h | 11 +- .../acl_manager/round_robin_scheduler_test.cc | 80 +- system/gd/hci/acl_manager_mock.h | 46 +- system/gd/hci/acl_manager_test.cc | 591 +- system/gd/hci/acl_manager_unittest.cc | 280 +- system/gd/hci/address.cc | 26 +- system/gd/hci/address.h | 44 +- system/gd/hci/address_with_type.h | 56 +- system/gd/hci/address_with_type_test.cc | 189 +- system/gd/hci/class_of_device.cc | 16 +- system/gd/hci/class_of_device.h | 34 +- system/gd/hci/class_of_device_unittest.cc | 4 +- system/gd/hci/command_interface.h | 12 +- system/gd/hci/controller.cc | 495 +- system/gd/hci/controller.h | 33 +- system/gd/hci/controller_interface.h | 30 +- system/gd/hci/controller_interface_mock.h | 41 +- system/gd/hci/controller_mock.h | 36 +- system/gd/hci/controller_test.cc | 177 +- system/gd/hci/controller_unittest.cc | 28 +- .../gd/hci/distance_measurement_interface.h | 16 +- system/gd/hci/distance_measurement_manager.cc | 559 +- system/gd/hci/distance_measurement_manager.h | 56 +- .../hci/distance_measurement_manager_mock.h | 20 +- system/gd/hci/enum_helper.h | 12 +- system/gd/hci/facade/acl_manager_facade.cc | 275 +- system/gd/hci/facade/acl_manager_facade.h | 4 +- system/gd/hci/facade/controller_facade.cc | 57 +- system/gd/hci/facade/controller_facade.h | 4 +- system/gd/hci/facade/facade.cc | 124 +- system/gd/hci/facade/facade.h | 4 +- system/gd/hci/facade/le_acl_manager_facade.cc | 290 +- system/gd/hci/facade/le_acl_manager_facade.h | 4 +- .../facade/le_advertising_manager_facade.cc | 210 +- .../facade/le_advertising_manager_facade.h | 4 +- .../hci/facade/le_initiator_address_facade.cc | 47 +- .../hci/facade/le_initiator_address_facade.h | 4 +- .../hci/facade/le_scanning_manager_facade.cc | 158 +- .../hci/facade/le_scanning_manager_facade.h | 4 +- system/gd/hci/fuzz/acl_manager_fuzz_test.cc | 7 +- system/gd/hci/fuzz/fuzz_hci_layer.cc | 55 +- system/gd/hci/fuzz/fuzz_hci_layer.h | 83 +- system/gd/hci/fuzz/hci_layer_fuzz_client.cc | 29 +- system/gd/hci/fuzz/hci_layer_fuzz_client.h | 22 +- system/gd/hci/fuzz/hci_layer_fuzz_test.cc | 4 +- .../hci/fuzz/status_vs_complete_commands.cc | 3 +- system/gd/hci/hci_interface.h | 70 +- system/gd/hci/hci_layer.cc | 273 +- system/gd/hci/hci_layer.h | 85 +- system/gd/hci/hci_layer_fake.cc | 54 +- system/gd/hci/hci_layer_fake.h | 33 +- system/gd/hci/hci_layer_mock.h | 126 +- system/gd/hci/hci_layer_test.cc | 183 +- system/gd/hci/hci_layer_unittest.cc | 412 +- system/gd/hci/hci_metrics_logging.cc | 866 +- system/gd/hci/hci_metrics_logging.h | 29 +- system/gd/hci/hci_packets_fuzz_test.cc | 10 +- system/gd/hci/hci_packets_test.cc | 395 +- system/gd/hci/le_acl_connection_interface.h | 15 +- system/gd/hci/le_address_manager.cc | 234 +- system/gd/hci/le_address_manager.h | 72 +- system/gd/hci/le_address_manager_test.cc | 221 +- system/gd/hci/le_advertising_interface.h | 4 +- system/gd/hci/le_advertising_manager.cc | 989 +- system/gd/hci/le_advertising_manager.h | 108 +- system/gd/hci/le_advertising_manager_mock.h | 23 +- system/gd/hci/le_advertising_manager_test.cc | 1065 +- system/gd/hci/le_iso_interface.h | 9 +- system/gd/hci/le_periodic_sync_manager.h | 391 +- .../gd/hci/le_periodic_sync_manager_test.cc | 588 +- system/gd/hci/le_scanning_callback.h | 50 +- system/gd/hci/le_scanning_interface.h | 18 +- system/gd/hci/le_scanning_manager.cc | 917 +- system/gd/hci/le_scanning_manager.h | 58 +- system/gd/hci/le_scanning_manager_mock.h | 32 +- system/gd/hci/le_scanning_manager_test.cc | 341 +- system/gd/hci/le_scanning_reassembler.cc | 47 +- system/gd/hci/le_scanning_reassembler.h | 26 +- system/gd/hci/le_scanning_reassembler_test.cc | 442 +- system/gd/hci/le_security_interface.h | 6 +- system/gd/hci/link_key.cc | 4 +- system/gd/hci/msft.cc | 105 +- system/gd/hci/msft.h | 8 +- system/gd/hci/remote_name_request.cc | 170 +- system/gd/hci/remote_name_request.h | 23 +- system/gd/hci/remote_name_request_test.cc | 364 +- system/gd/hci/security_interface.h | 32 +- system/gd/hci/uuid.cc | 87 +- system/gd/hci/uuid.h | 17 +- system/gd/hci/uuid_unittest.cc | 68 +- .../dynamic_channel_configuration_option.h | 7 +- .../l2cap/classic/dynamic_channel_manager.cc | 45 +- .../l2cap/classic/dynamic_channel_manager.h | 73 +- .../l2cap/classic/dynamic_channel_service.cc | 9 +- .../l2cap/classic/dynamic_channel_service.h | 13 +- system/gd/l2cap/classic/facade.cc | 248 +- system/gd/l2cap/classic/facade.h | 4 +- system/gd/l2cap/classic/fixed_channel.cc | 12 +- system/gd/l2cap/classic/fixed_channel.h | 24 +- .../gd/l2cap/classic/fixed_channel_manager.cc | 20 +- .../gd/l2cap/classic/fixed_channel_manager.h | 64 +- .../classic/fixed_channel_manager_mock.h | 12 +- system/gd/l2cap/classic/fixed_channel_mock.h | 15 +- .../gd/l2cap/classic/fixed_channel_service.cc | 8 +- .../gd/l2cap/classic/fixed_channel_service.h | 7 +- .../classic/fixed_channel_service_mock.h | 11 +- .../internal/channel_configuration_state.h | 15 +- .../l2cap/classic/internal/dumpsys_helper.cc | 30 +- .../l2cap/classic/internal/dumpsys_helper.h | 16 +- .../internal/dynamic_channel_service_impl.h | 20 +- .../dynamic_channel_service_impl_mock.h | 6 +- .../dynamic_channel_service_manager_impl.cc | 32 +- .../dynamic_channel_service_manager_impl.h | 7 +- ...ynamic_channel_service_manager_impl_mock.h | 15 +- .../dynamic_channel_service_manager_test.cc | 24 +- .../classic/internal/fixed_channel_impl.cc | 23 +- .../classic/internal/fixed_channel_impl.h | 33 +- .../internal/fixed_channel_impl_mock.h | 12 +- .../internal/fixed_channel_impl_test.cc | 135 +- .../internal/fixed_channel_service_impl.h | 9 +- .../fixed_channel_service_impl_mock.h | 9 +- .../fixed_channel_service_manager_impl.cc | 37 +- .../fixed_channel_service_manager_impl.h | 7 +- .../fixed_channel_service_manager_impl_mock.h | 16 +- .../fixed_channel_service_manager_test.cc | 26 +- system/gd/l2cap/classic/internal/link.cc | 253 +- system/gd/l2cap/classic/internal/link.h | 90 +- .../gd/l2cap/classic/internal/link_manager.cc | 214 +- .../gd/l2cap/classic/internal/link_manager.h | 55 +- .../classic/internal/link_manager_test.cc | 333 +- system/gd/l2cap/classic/internal/link_mock.h | 23 +- system/gd/l2cap/classic/internal/link_test.cc | 46 +- .../classic/internal/signalling_manager.cc | 432 +- .../classic/internal/signalling_manager.h | 32 +- .../internal/signalling_manager_test.cc | 10 +- .../gd/l2cap/classic/l2cap_classic_module.cc | 61 +- .../gd/l2cap/classic/l2cap_classic_module.h | 27 +- .../l2cap/classic/l2cap_classic_module_mock.h | 6 +- .../gd/l2cap/classic/link_property_listener.h | 42 +- .../l2cap/classic/link_security_interface.h | 35 +- .../classic/security_enforcement_interface.h | 18 +- system/gd/l2cap/dynamic_channel.cc | 13 +- system/gd/l2cap/dynamic_channel.h | 26 +- system/gd/l2cap/fcs.cc | 55 +- system/gd/l2cap/fcs.h | 4 +- .../gd/l2cap/fuzz/channel_fuzz_controller.cc | 6 +- .../gd/l2cap/fuzz/channel_fuzz_controller.h | 10 +- .../l2cap/fuzz/fuzz_dynamic_channel_manager.h | 32 +- .../fuzz/fuzz_dynamic_channel_manager_impl.h | 37 +- system/gd/l2cap/fuzz/fuzz_l2cap.cc | 29 +- .../gd/l2cap/fuzz/fuzz_l2cap_classic_module.h | 15 +- system/gd/l2cap/fuzz/shim_l2cap.h | 41 +- .../basic_mode_channel_data_controller.cc | 17 +- .../basic_mode_channel_data_controller.h | 10 +- ...basic_mode_channel_data_controller_test.cc | 2 +- system/gd/l2cap/internal/channel_impl.h | 8 +- system/gd/l2cap/internal/channel_impl_mock.h | 12 +- system/gd/l2cap/internal/data_controller.h | 8 +- .../gd/l2cap/internal/data_controller_mock.h | 10 +- .../l2cap/internal/data_pipeline_manager.cc | 34 +- .../gd/l2cap/internal/data_pipeline_manager.h | 11 +- .../internal/data_pipeline_manager_mock.h | 7 +- .../internal/dynamic_channel_allocator.cc | 43 +- .../internal/dynamic_channel_allocator.h | 18 +- .../dynamic_channel_allocator_fuzz_test.cc | 16 +- .../dynamic_channel_allocator_test.cc | 10 +- .../gd/l2cap/internal/dynamic_channel_impl.cc | 28 +- .../gd/l2cap/internal/dynamic_channel_impl.h | 29 +- .../internal/dynamic_channel_impl_test.cc | 69 +- ...ansmission_mode_channel_data_controller.cc | 259 +- ...ransmission_mode_channel_data_controller.h | 27 +- ...ssion_mode_channel_data_controller_test.cc | 30 +- .../l2cap/internal/fixed_channel_allocator.h | 60 +- .../internal/fixed_channel_allocator_test.cc | 16 +- system/gd/l2cap/internal/ilink.h | 2 +- system/gd/l2cap/internal/ilink_mock.h | 6 +- ...le_credit_based_channel_data_controller.cc | 30 +- .../le_credit_based_channel_data_controller.h | 20 +- ...edit_based_channel_data_controller_test.cc | 17 +- system/gd/l2cap/internal/parameter_provider.h | 10 +- .../l2cap/internal/parameter_provider_mock.h | 6 +- system/gd/l2cap/internal/receiver.cc | 20 +- system/gd/l2cap/internal/receiver.h | 19 +- system/gd/l2cap/internal/scheduler.h | 2 +- system/gd/l2cap/internal/scheduler_fifo.cc | 21 +- system/gd/l2cap/internal/scheduler_fifo.h | 7 +- .../gd/l2cap/internal/scheduler_fifo_test.cc | 22 +- system/gd/l2cap/internal/scheduler_mock.h | 6 +- system/gd/l2cap/internal/sender.cc | 64 +- system/gd/l2cap/internal/sender.h | 21 +- system/gd/l2cap/internal/sender_test.cc | 13 +- system/gd/l2cap/l2cap_packet_fuzz_test.cc | 7 +- system/gd/l2cap/l2cap_packet_test.cc | 65 +- system/gd/l2cap/le/dynamic_channel.cc | 9 +- system/gd/l2cap/le/dynamic_channel.h | 11 +- .../le/dynamic_channel_configuration_option.h | 8 +- system/gd/l2cap/le/dynamic_channel_manager.cc | 32 +- system/gd/l2cap/le/dynamic_channel_manager.h | 54 +- system/gd/l2cap/le/dynamic_channel_service.cc | 13 +- system/gd/l2cap/le/dynamic_channel_service.h | 13 +- system/gd/l2cap/le/facade.cc | 188 +- system/gd/l2cap/le/facade.h | 4 +- system/gd/l2cap/le/fixed_channel.cc | 16 +- system/gd/l2cap/le/fixed_channel.h | 24 +- system/gd/l2cap/le/fixed_channel_manager.cc | 20 +- system/gd/l2cap/le/fixed_channel_manager.h | 65 +- system/gd/l2cap/le/fixed_channel_service.cc | 8 +- system/gd/l2cap/le/fixed_channel_service.h | 7 +- .../internal/dynamic_channel_service_impl.h | 28 +- .../dynamic_channel_service_impl_mock.h | 6 +- .../dynamic_channel_service_manager_impl.cc | 35 +- .../dynamic_channel_service_manager_impl.h | 10 +- .../dynamic_channel_service_manager_test.cc | 29 +- .../l2cap/le/internal/fixed_channel_impl.cc | 39 +- .../gd/l2cap/le/internal/fixed_channel_impl.h | 25 +- .../le/internal/fixed_channel_impl_mock.h | 9 +- .../le/internal/fixed_channel_impl_test.cc | 80 +- .../le/internal/fixed_channel_service_impl.h | 9 +- .../fixed_channel_service_impl_mock.h | 9 +- .../fixed_channel_service_manager_impl.cc | 37 +- .../fixed_channel_service_manager_impl.h | 7 +- .../fixed_channel_service_manager_impl_mock.h | 16 +- .../fixed_channel_service_manager_test.cc | 25 +- system/gd/l2cap/le/internal/link.cc | 244 +- system/gd/l2cap/le/internal/link.h | 99 +- system/gd/l2cap/le/internal/link_manager.cc | 111 +- system/gd/l2cap/le/internal/link_manager.h | 39 +- .../gd/l2cap/le/internal/link_manager_test.cc | 433 +- system/gd/l2cap/le/internal/link_mock.h | 16 +- .../l2cap/le/internal/signalling_manager.cc | 266 +- .../gd/l2cap/le/internal/signalling_manager.h | 48 +- system/gd/l2cap/le/l2cap_le_module.cc | 52 +- system/gd/l2cap/le/l2cap_le_module.h | 15 +- system/gd/l2cap/le/l2cap_le_module_mock.h | 6 +- system/gd/l2cap/le/link_options.cc | 24 +- system/gd/l2cap/le/link_options.h | 28 +- system/gd/l2cap/le/link_property_listener.h | 39 +- .../l2cap/le/security_enforcement_interface.h | 10 +- system/gd/l2cap/signal_id.h | 24 +- system/gd/l2cap/signal_id_test.cc | 5 +- system/gd/metrics/chromeos/metrics.cc | 279 +- .../gd/metrics/chromeos/metrics_allowlist.cc | 505 +- .../gd/metrics/chromeos/metrics_allowlist.h | 3 +- system/gd/metrics/chromeos/metrics_event.cc | 65 +- system/gd/metrics/chromeos/metrics_event.h | 25 +- system/gd/metrics/counter_metrics.cc | 9 +- system/gd/metrics/counter_metrics.h | 16 +- system/gd/metrics/counter_metrics_unittest.cc | 15 +- system/gd/metrics/linux/metrics.cc | 31 +- system/gd/metrics/metrics.h | 25 +- system/gd/metrics/metrics_state.cc | 63 +- system/gd/metrics/metrics_state.h | 32 +- system/gd/metrics/metrics_state_unittest.cc | 92 +- system/gd/metrics/utils.cc | 8 +- system/gd/metrics/utils.h | 6 +- system/gd/module.cc | 25 +- system/gd/module.h | 62 +- system/gd/module_dumper.cc | 12 +- system/gd/module_dumper.h | 4 +- system/gd/module_gdx_unittest.cc | 306 +- system/gd/module_gdx_unittest.h | 6 +- system/gd/module_jniloop.h | 17 +- system/gd/module_jniloop_unittest.cc | 48 +- system/gd/module_jniloop_unittest.h | 6 +- system/gd/module_mainloop.h | 29 +- system/gd/module_mainloop_unittest.cc | 40 +- system/gd/module_mainloop_unittest.h | 6 +- system/gd/module_state_dumper_unittest.cc | 30 +- system/gd/module_state_dumper_unittest.h | 6 +- system/gd/module_unittest.cc | 78 +- system/gd/module_unittest_generated.h | 14 +- system/gd/neighbor/facade/facade.cc | 22 +- system/gd/neighbor/facade/facade.h | 4 +- system/gd/neighbor/name_db.cc | 66 +- system/gd/neighbor/name_db.h | 13 +- system/gd/neighbor/scan.cc | 79 +- system/gd/neighbor/scan.h | 10 +- system/gd/os/alarm.h | 8 +- system/gd/os/alarm_benchmark.cc | 67 +- system/gd/os/android/metrics.cc | 528 +- system/gd/os/android/parameter_provider.cc | 7 +- system/gd/os/android/system_properties.cc | 16 +- system/gd/os/android/wakelock_native.cc | 19 +- system/gd/os/android/wakelock_native_test.cc | 21 +- system/gd/os/chromeos/metrics.cc | 308 +- system/gd/os/chromeos/parameter_provider.cc | 10 +- system/gd/os/chromeos/system_properties.cc | 10 +- system/gd/os/chromeos/wakelock_native.cc | 8 +- system/gd/os/fake_timer/fake_timerfd.cc | 17 +- system/gd/os/fake_timer/fake_timerfd.h | 3 +- system/gd/os/files.h | 16 +- system/gd/os/fuzz/dev_null_queue.h | 12 +- system/gd/os/fuzz/fuzz_inject_queue.h | 12 +- system/gd/os/handler.cc | 8 +- system/gd/os/handler.h | 20 +- system/gd/os/handler_unittest.cc | 46 +- system/gd/os/host/metrics.cc | 219 +- system/gd/os/host/parameter_provider.cc | 25 +- system/gd/os/host/system_properties.cc | 8 +- system/gd/os/host/wakelock_native.cc | 8 +- system/gd/os/internal/wakelock_native.h | 4 +- system/gd/os/linux/metrics.cc | 182 +- system/gd/os/linux/parameter_provider.cc | 11 +- system/gd/os/linux/system_properties.cc | 10 +- system/gd/os/linux/wakelock_native.cc | 8 +- system/gd/os/linux_generic/alarm.cc | 17 +- .../linux_generic/alarm_timerfd_unittest.cc | 55 +- system/gd/os/linux_generic/alarm_unittest.cc | 68 +- system/gd/os/linux_generic/files.cc | 16 +- system/gd/os/linux_generic/files_test.cc | 4 +- system/gd/os/linux_generic/queue_unittest.cc | 220 +- .../gd/os/linux_generic/reactive_semaphore.cc | 7 +- .../gd/os/linux_generic/reactive_semaphore.h | 4 +- system/gd/os/linux_generic/reactor.cc | 32 +- .../gd/os/linux_generic/reactor_unittest.cc | 126 +- system/gd/os/linux_generic/repeating_alarm.cc | 10 +- .../linux_generic/repeating_alarm_unittest.cc | 67 +- system/gd/os/linux_generic/thread.cc | 25 +- system/gd/os/linux_generic/thread_unittest.cc | 45 +- .../gd/os/linux_generic/wakelock_manager.cc | 9 +- .../wakelock_manager_unittest.cc | 16 +- system/gd/os/logging/log_adapter.h | 12 +- system/gd/os/logging/log_redaction.cc | 4 +- system/gd/os/metrics.h | 167 +- system/gd/os/mock_queue.h | 4 +- system/gd/os/parameter_provider.h | 2 +- system/gd/os/queue.h | 65 +- system/gd/os/queue_benchmark.cc | 56 +- system/gd/os/rand.h | 10 +- system/gd/os/reactor.h | 24 +- system/gd/os/repeating_alarm.h | 8 +- system/gd/os/system_properties.h | 22 +- system/gd/os/system_properties_common.cc | 4 +- system/gd/os/thread.h | 19 +- system/gd/os/thread_benchmark.cc | 48 +- system/gd/os/wakelock_manager.h | 24 +- system/gd/packet/base_packet_builder.h | 14 +- system/gd/packet/base_struct.h | 4 +- system/gd/packet/bit_inserter.cc | 11 +- system/gd/packet/bit_inserter.h | 4 +- system/gd/packet/bit_inserter_unittest.cc | 12 +- system/gd/packet/byte_inserter.cc | 7 +- system/gd/packet/byte_inserter.h | 6 +- system/gd/packet/byte_observer.cc | 11 +- system/gd/packet/byte_observer.h | 7 +- system/gd/packet/checksum_type_checker.h | 8 +- .../custom_field_fixed_size_interface.h | 8 +- system/gd/packet/custom_type_checker.h | 12 +- system/gd/packet/endian_inserter.h | 24 +- system/gd/packet/fragmenting_inserter.cc | 11 +- system/gd/packet/fragmenting_inserter.h | 7 +- .../packet/fragmenting_inserter_unittest.cc | 18 +- system/gd/packet/iterator.h | 8 +- system/gd/packet/packet_builder.h | 2 +- system/gd/packet/packet_builder_unittest.cc | 68 +- system/gd/packet/packet_struct.h | 2 +- system/gd/packet/packet_view.h | 6 +- system/gd/packet/packet_view_unittest.cc | 187 +- system/gd/packet/parser/checksum_def.cc | 10 +- system/gd/packet/parser/checksum_def.h | 2 +- system/gd/packet/parser/custom_field_def.cc | 17 +- system/gd/packet/parser/custom_field_def.h | 2 +- system/gd/packet/parser/declarations.h | 2 +- system/gd/packet/parser/enum_def.cc | 16 +- system/gd/packet/parser/enum_def.h | 2 +- system/gd/packet/parser/enum_gen.h | 2 +- system/gd/packet/parser/field_list.h | 46 +- system/gd/packet/parser/fields/array_field.cc | 46 +- system/gd/packet/parser/fields/array_field.h | 2 +- system/gd/packet/parser/fields/body_field.cc | 19 +- system/gd/packet/parser/fields/body_field.h | 2 +- .../gd/packet/parser/fields/checksum_field.cc | 24 +- .../gd/packet/parser/fields/checksum_field.h | 4 +- .../parser/fields/checksum_start_field.cc | 21 +- .../parser/fields/checksum_start_field.h | 4 +- system/gd/packet/parser/fields/count_field.cc | 13 +- system/gd/packet/parser/fields/count_field.h | 4 +- .../gd/packet/parser/fields/custom_field.cc | 25 +- system/gd/packet/parser/fields/custom_field.h | 4 +- .../parser/fields/custom_field_fixed_size.cc | 17 +- .../parser/fields/custom_field_fixed_size.h | 5 +- system/gd/packet/parser/fields/enum_field.cc | 16 +- system/gd/packet/parser/fields/enum_field.h | 4 +- .../packet/parser/fields/fixed_enum_field.cc | 13 +- .../packet/parser/fields/fixed_enum_field.h | 4 +- system/gd/packet/parser/fields/fixed_field.cc | 9 +- system/gd/packet/parser/fields/fixed_field.h | 4 +- .../parser/fields/fixed_scalar_field.cc | 17 +- .../packet/parser/fields/fixed_scalar_field.h | 5 +- system/gd/packet/parser/fields/group_field.cc | 16 +- system/gd/packet/parser/fields/group_field.h | 4 +- .../gd/packet/parser/fields/packet_field.cc | 38 +- system/gd/packet/parser/fields/packet_field.h | 17 +- .../gd/packet/parser/fields/padding_field.cc | 29 +- .../gd/packet/parser/fields/padding_field.h | 4 +- .../gd/packet/parser/fields/payload_field.cc | 30 +- .../gd/packet/parser/fields/payload_field.h | 2 +- .../gd/packet/parser/fields/reserved_field.cc | 25 +- .../gd/packet/parser/fields/reserved_field.h | 4 +- .../gd/packet/parser/fields/scalar_field.cc | 22 +- system/gd/packet/parser/fields/scalar_field.h | 11 +- system/gd/packet/parser/fields/size_field.cc | 17 +- system/gd/packet/parser/fields/size_field.h | 4 +- .../gd/packet/parser/fields/struct_field.cc | 25 +- system/gd/packet/parser/fields/struct_field.h | 6 +- .../fields/variable_length_struct_field.cc | 23 +- .../fields/variable_length_struct_field.h | 4 +- .../gd/packet/parser/fields/vector_field.cc | 80 +- system/gd/packet/parser/fields/vector_field.h | 2 +- system/gd/packet/parser/gen_cpp.cc | 35 +- system/gd/packet/parser/logging.h | 20 +- system/gd/packet/parser/main.cc | 32 +- system/gd/packet/parser/packet_def.cc | 79 +- system/gd/packet/parser/packet_def.h | 2 +- system/gd/packet/parser/packet_dependency.cc | 12 +- system/gd/packet/parser/packet_dependency.h | 14 +- system/gd/packet/parser/parent_def.cc | 106 +- system/gd/packet/parser/parent_def.h | 7 +- system/gd/packet/parser/parse_location.h | 8 +- system/gd/packet/parser/size.h | 35 +- system/gd/packet/parser/struct_def.cc | 70 +- system/gd/packet/parser/struct_def.h | 4 +- .../packet/parser/struct_parser_generator.cc | 12 +- .../packet/parser/struct_parser_generator.h | 6 +- .../parser/test/generated_packet_test.cc | 587 +- system/gd/packet/parser/test/simple_sum.h | 16 +- system/gd/packet/parser/test/six_bytes.cc | 4 +- system/gd/packet/parser/test/six_bytes.h | 35 +- system/gd/packet/parser/test/variable.cc | 4 +- system/gd/packet/parser/test/variable.h | 10 +- system/gd/packet/parser/type_def.h | 6 +- system/gd/packet/parser/util.h | 30 +- system/gd/packet/raw_builder.cc | 28 +- system/gd/packet/raw_builder.h | 4 +- system/gd/packet/raw_builder_unittest.cc | 8 +- system/gd/packet/view.cc | 7 +- system/gd/packet/view.h | 4 +- system/gd/rust/topshim/btav/btav_shim.cc | 262 +- system/gd/rust/topshim/btav/btav_shim.h | 10 +- .../rust/topshim/btav_sink/btav_sink_shim.cc | 34 +- .../rust/topshim/btav_sink/btav_sink_shim.h | 4 +- system/gd/rust/topshim/btif/btif_shim.cc | 4 +- system/gd/rust/topshim/btif/btif_shim.h | 8 +- .../topshim/controller/controller_shim.cc | 16 +- .../rust/topshim/controller/controller_shim.h | 4 +- system/gd/rust/topshim/csis/csis_shim.cc | 48 +- system/gd/rust/topshim/csis/csis_shim.h | 6 +- .../topshim/gatt/gatt_ble_advertiser_shim.cc | 148 +- .../topshim/gatt/gatt_ble_advertiser_shim.h | 36 +- .../topshim/gatt/gatt_ble_scanner_shim.cc | 291 +- .../rust/topshim/gatt/gatt_ble_scanner_shim.h | 76 +- system/gd/rust/topshim/gatt/gatt_shim.cc | 16 +- system/gd/rust/topshim/gatt/gatt_shim.h | 13 +- system/gd/rust/topshim/hfp/hfp_shim.cc | 235 +- system/gd/rust/topshim/hfp/hfp_shim.h | 14 +- .../gd/rust/topshim/le_audio/le_audio_shim.cc | 286 +- .../gd/rust/topshim/le_audio/le_audio_shim.h | 16 +- .../gd/rust/topshim/metrics/metrics_shim.cc | 38 +- system/gd/rust/topshim/metrics/metrics_shim.h | 23 +- system/gd/rust/topshim/vc/vc_shim.cc | 119 +- system/gd/rust/topshim/vc/vc_shim.h | 6 +- .../channel/security_manager_channel.cc | 23 +- .../channel/security_manager_channel.h | 19 +- .../security_manager_channel_unittest.cc | 73 +- system/gd/security/ecc/multprecision.cc | 72 +- system/gd/security/ecc/multprecision.h | 14 +- system/gd/security/ecc/p_256_ecc_pp.cc | 15 +- system/gd/security/ecc/p_256_ecc_pp.h | 18 +- system/gd/security/ecdh_keys.cc | 10 +- system/gd/security/ecdh_keys.h | 4 +- system/gd/security/facade.cc | 366 +- system/gd/security/facade.h | 4 +- .../gd/security/facade_configuration_api.cc | 69 +- system/gd/security/facade_configuration_api.h | 25 +- system/gd/security/initial_informations.h | 3 +- .../internal/security_manager_impl.cc | 482 +- .../security/internal/security_manager_impl.h | 102 +- .../l2cap_security_module_interface.cc | 29 +- .../l2cap_security_module_interface.h | 12 +- .../pairing/classic_pairing_handler.cc | 277 +- .../pairing/classic_pairing_handler.h | 38 +- .../classic_pairing_handler_unittest.cc | 289 +- system/gd/security/pairing/oob_data.h | 12 +- system/gd/security/pairing/pairing_handler.h | 40 +- system/gd/security/pairing_failure.h | 13 +- system/gd/security/pairing_handler_le.cc | 131 +- system/gd/security/pairing_handler_le.h | 247 +- .../gd/security/pairing_handler_le_legacy.cc | 98 +- .../pairing_handler_le_secure_connections.cc | 87 +- .../security/pairing_handler_le_unittest.cc | 199 +- system/gd/security/record/security_record.h | 47 +- .../record/security_record_database.h | 31 +- .../record/security_record_storage.cc | 61 +- .../security/record/security_record_storage.h | 4 +- .../record/security_record_storage_test.cc | 61 +- system/gd/security/security_manager.cc | 85 +- system/gd/security/security_manager.h | 30 +- .../gd/security/security_manager_listener.h | 5 +- system/gd/security/security_module.cc | 55 +- system/gd/security/security_module.h | 9 +- system/gd/security/test/ecdh_keys_test.cc | 65 +- system/gd/security/test/fake_hci_layer.h | 45 +- system/gd/security/test/fake_l2cap_test.cc | 25 +- system/gd/security/test/fake_name_db.h | 14 +- .../security/test/fake_security_interface.h | 30 +- system/gd/security/test/mocks.h | 17 +- .../test/pairing_handler_le_pair_test.cc | 520 +- system/gd/security/ui.h | 66 +- system/gd/shim/dumpsys.cc | 44 +- system/gd/shim/dumpsys.h | 15 +- system/gd/shim/dumpsys_args.cc | 15 +- system/gd/shim/dumpsys_args.h | 4 +- system/gd/shim/dumpsys_args_test.cc | 9 +- system/gd/shim/dumpsys_test.cc | 20 +- .../gd/shim/test_data/dumpsys_test_data_bin.h | 111 +- system/gd/stack_manager.cc | 40 +- system/gd/stack_manager.h | 8 +- system/gd/stack_manager_unittest.cc | 11 +- system/gd/storage/classic_device.cc | 11 +- system/gd/storage/classic_device.h | 25 +- system/gd/storage/classic_device_test.cc | 75 +- system/gd/storage/config_cache.cc | 80 +- system/gd/storage/config_cache.h | 53 +- system/gd/storage/config_cache_helper.cc | 35 +- system/gd/storage/config_cache_helper.h | 48 +- system/gd/storage/config_cache_helper_test.cc | 14 +- system/gd/storage/config_cache_test.cc | 105 +- system/gd/storage/device.cc | 35 +- system/gd/storage/device.h | 161 +- system/gd/storage/device_test.cc | 51 +- system/gd/storage/le_device.cc | 10 +- system/gd/storage/le_device.h | 37 +- system/gd/storage/le_device_test.cc | 22 +- system/gd/storage/legacy_config_file.cc | 2 +- system/gd/storage/legacy_config_file.h | 8 +- system/gd/storage/legacy_config_file_test.cc | 76 +- system/gd/storage/mutation.cc | 3 +- system/gd/storage/mutation.h | 4 +- system/gd/storage/mutation_entry.cc | 16 +- system/gd/storage/mutation_entry.h | 94 +- system/gd/storage/mutation_test.cc | 12 +- system/gd/storage/serializable.h | 6 +- system/gd/storage/storage_module.cc | 121 +- system/gd/storage/storage_module.h | 75 +- system/gd/storage/storage_module_test.cc | 94 +- system/gd/sysprops/sysprops_module.cc | 122 +- system/gd/sysprops/sysprops_module.h | 6 +- system/gd/sysprops/sysprops_module_test.cc | 24 +- system/hci/include/bt_vendor_lib.h | 3 +- system/hci/include/btsnoop.h | 10 +- system/hci/include/btsnoop_mem.h | 4 +- system/hci/include/hci_layer.h | 15 +- system/hci/include/packet_fragmenter.h | 3 +- system/hci/src/packet_fragmenter.cc | 83 +- system/hci/test/packet_fragmenter_test.cc | 133 +- system/include/abstract_message_loop.h | 12 +- system/include/abstract_observer_list.h | 3 +- system/include/hardware/avrcp/avrcp.h | 57 +- system/include/hardware/avrcp/avrcp_common.h | 23 +- .../hardware/avrcp/avrcp_logging_helper.h | 10 +- system/include/hardware/ble_advertiser.h | 85 +- system/include/hardware/ble_scanner.h | 132 +- system/include/hardware/bluetooth.h | 119 +- .../hardware/bluetooth_headset_callbacks.h | 30 +- .../hardware/bluetooth_headset_interface.h | 42 +- system/include/hardware/bt_av.h | 120 +- system/include/hardware/bt_bqr.h | 12 +- system/include/hardware/bt_common_types.h | 3 +- system/include/hardware/bt_csis.h | 16 +- system/include/hardware/bt_gatt_client.h | 141 +- system/include/hardware/bt_gatt_server.h | 59 +- system/include/hardware/bt_gatt_types.h | 9 +- system/include/hardware/bt_has.h | 40 +- system/include/hardware/bt_hd.h | 23 +- system/include/hardware/bt_hearing_aid.h | 14 +- system/include/hardware/bt_hf.h | 46 +- system/include/hardware/bt_hf_client.h | 117 +- system/include/hardware/bt_hh.h | 89 +- system/include/hardware/bt_keystore.h | 10 +- system/include/hardware/bt_le_audio.h | 166 +- system/include/hardware/bt_pan.h | 25 +- system/include/hardware/bt_rc.h | 292 +- system/include/hardware/bt_sdp.h | 9 +- system/include/hardware/bt_sock.h | 19 +- system/include/hardware/bt_vc.h | 55 +- .../hardware/distance_measurement_interface.h | 31 +- system/include/macros.h | 17 +- system/internal_include/bt_target.h | 14 +- system/internal_include/bt_trace.h | 24 +- system/log/include/bluetooth/log.h | 69 +- system/log/src/truncating_buffer.h | 2 +- system/log/src/vlog_android.cc | 28 +- system/log/src/vlog_syslog.cc | 15 +- system/log/src/vlog_test.cc | 73 +- system/main/bte_conf.cc | 36 +- system/main/shim/acl.cc | 1075 +- system/main/shim/acl.h | 66 +- system/main/shim/acl_api.cc | 245 +- system/main/shim/acl_api.h | 42 +- system/main/shim/acl_legacy_interface.cc | 113 +- system/main/shim/acl_legacy_interface.h | 104 +- system/main/shim/ble_scanner_interface_impl.h | 112 +- system/main/shim/btm_api.cc | 35 +- system/main/shim/btm_api.h | 8 +- system/main/shim/config.cc | 46 +- system/main/shim/config.h | 41 +- .../main/shim/distance_measurement_manager.cc | 192 +- system/main/shim/dumpsys.cc | 32 +- system/main/shim/dumpsys.h | 8 +- system/main/shim/entry.cc | 44 +- system/main/shim/entry.h | 2 +- system/main/shim/hci_layer.cc | 143 +- system/main/shim/helpers.h | 85 +- system/main/shim/l2c_api.h | 58 +- system/main/shim/le_advertising_manager.cc | 246 +- system/main/shim/le_scanning_manager.cc | 536 +- system/main/shim/link_connection_interface.h | 32 +- system/main/shim/metric_id_api.cc | 24 +- system/main/shim/metric_id_api.h | 9 +- system/main/shim/metrics_api.cc | 170 +- system/main/shim/metrics_api.h | 95 +- system/main/shim/shim.cc | 22 +- system/main/shim/stack.cc | 21 +- system/main/shim/stack.h | 4 +- system/main/shim/utils.cc | 36 +- system/main/shim/utils.h | 3 +- system/main/stack_config.cc | 131 +- system/main/test/common_stack_test.cc | 10 +- system/main/test/main_shim_dumpsys_test.cc | 10 +- .../main/test/main_shim_stack_dumpsys_test.cc | 264 +- .../test/main_shim_stack_lifecycle_test.cc | 340 +- system/main/test/main_shim_test.cc | 385 +- system/osi/include/alarm.h | 6 +- system/osi/include/allocator.h | 4 +- system/osi/include/config.h | 37 +- system/osi/include/fixed_queue.h | 4 +- system/osi/include/hash_map_utils.h | 4 +- system/osi/include/list.h | 3 +- system/osi/include/properties.h | 4 +- system/osi/include/reactor.h | 3 +- system/osi/include/ringbuffer.h | 3 +- system/osi/include/socket.h | 7 +- .../osi/include/socket_utils/socket_local.h | 4 +- system/osi/include/socket_utils/sockets.h | 3 +- system/osi/include/stack_power_telemetry.h | 17 +- system/osi/src/alarm.cc | 190 +- system/osi/src/allocator.cc | 18 +- system/osi/src/compat.cc | 13 +- system/osi/src/config.cc | 189 +- system/osi/src/fixed_queue.cc | 75 +- system/osi/src/future.cc | 11 +- system/osi/src/hash_map_utils.cc | 12 +- system/osi/src/internal/semaphore.cc | 36 +- system/osi/src/list.cc | 73 +- system/osi/src/mutex.cc | 4 +- system/osi/src/properties.cc | 4 +- system/osi/src/reactor.cc | 57 +- system/osi/src/ringbuffer.cc | 39 +- system/osi/src/socket.cc | 34 +- .../src/socket_utils/socket_local_client.cc | 20 +- .../src/socket_utils/socket_local_server.cc | 4 +- system/osi/src/stack_power_telemetry.cc | 396 +- system/osi/src/thread.cc | 52 +- system/osi/src/thread_scheduler.cc | 3 +- system/osi/src/wakelock.cc | 94 +- system/osi/test/alarm_mock.h | 26 +- system/osi/test/alarm_test.cc | 32 +- system/osi/test/config_test.cc | 41 +- system/osi/test/fixed_queue_test.cc | 19 +- system/osi/test/future_test.cc | 2 +- system/osi/test/fuzzers/alarm/fuzz_alarm.cc | 29 +- .../test/fuzzers/allocator/fuzz_allocator.cc | 16 +- system/osi/test/fuzzers/compat/fuzz_compat.cc | 10 +- .../fuzzers/fixed_queue/fuzz_fixed_queue.cc | 19 +- system/osi/test/fuzzers/future/fuzz_future.cc | 4 +- .../include/libosiFuzzHelperFunctions.h | 4 +- system/osi/test/fuzzers/list/fuzz_list.cc | 70 +- .../fuzzers/ringbuffer/fuzz_ringbuffer.cc | 25 +- system/osi/test/hash_map_utils_test.cc | 2 +- system/osi/test/internal/semaphore_test.cc | 9 +- system/osi/test/list_test.cc | 40 +- system/osi/test/ringbuffer_test.cc | 6 +- system/osi/test/stack_power_telemetry_test.cc | 71 +- system/osi/test/test_stubs.h | 30 +- system/osi/test/wakelock_test.cc | 12 +- system/packet/avrcp/avrcp_browse_packet.cc | 26 +- system/packet/avrcp/avrcp_browse_packet.h | 23 +- system/packet/avrcp/avrcp_packet.cc | 30 +- system/packet/avrcp/avrcp_packet.h | 35 +- system/packet/avrcp/avrcp_reject_packet.cc | 5 +- system/packet/avrcp/avrcp_reject_packet.h | 13 +- system/packet/avrcp/capabilities_packet.cc | 54 +- system/packet/avrcp/capabilities_packet.h | 42 +- system/packet/avrcp/change_path.cc | 33 +- system/packet/avrcp/change_path.h | 32 +- system/packet/avrcp/general_reject_packet.cc | 9 +- system/packet/avrcp/general_reject_packet.h | 10 +- ...urrent_player_application_setting_value.cc | 25 +- ...current_player_application_setting_value.h | 35 +- .../avrcp/get_element_attributes_packet.cc | 22 +- .../avrcp/get_element_attributes_packet.h | 19 +- system/packet/avrcp/get_folder_items.cc | 99 +- system/packet/avrcp/get_folder_items.h | 52 +- system/packet/avrcp/get_item_attributes.cc | 38 +- system/packet/avrcp/get_item_attributes.h | 21 +- system/packet/avrcp/get_play_status_packet.cc | 20 +- system/packet/avrcp/get_play_status_packet.h | 24 +- .../packet/avrcp/get_total_number_of_items.cc | 21 +- .../packet/avrcp/get_total_number_of_items.h | 15 +- ...t_player_application_setting_attributes.cc | 9 +- ...st_player_application_setting_attributes.h | 25 +- .../list_player_application_setting_values.cc | 17 +- .../list_player_application_setting_values.h | 27 +- system/packet/avrcp/pass_through_packet.cc | 19 +- system/packet/avrcp/pass_through_packet.h | 23 +- system/packet/avrcp/play_item.cc | 13 +- system/packet/avrcp/play_item.h | 16 +- .../avrcp/register_notification_packet.cc | 93 +- .../avrcp/register_notification_packet.h | 70 +- system/packet/avrcp/set_absolute_volume.cc | 21 +- system/packet/avrcp/set_absolute_volume.h | 19 +- system/packet/avrcp/set_addressed_player.cc | 13 +- system/packet/avrcp/set_addressed_player.h | 19 +- system/packet/avrcp/set_browsed_player.cc | 31 +- system/packet/avrcp/set_browsed_player.h | 22 +- .../set_player_application_setting_value.cc | 33 +- .../set_player_application_setting_value.h | 26 +- system/packet/avrcp/vendor_packet.cc | 41 +- system/packet/avrcp/vendor_packet.h | 24 +- system/packet/base/iterator.cc | 33 +- system/packet/base/iterator.h | 7 +- system/packet/base/packet.cc | 18 +- system/packet/base/packet.h | 21 +- system/packet/base/packet_builder.cc | 10 +- system/packet/base/packet_builder.h | 9 +- .../tests/avrcp/avrcp_browse_packet_test.cc | 34 +- .../packet/tests/avrcp/avrcp_packet_test.cc | 30 +- .../tests/avrcp/avrcp_reject_packet_test.cc | 8 +- .../packet/tests/avrcp/avrcp_test_packets.h | 353 +- .../tests/avrcp/change_path_packet_test.cc | 3 +- .../tests/avrcp/general_reject_packet_test.cc | 3 +- .../avrcp/get_capabilities_packet_test.cc | 16 +- ...t_player_application_setting_value_test.cc | 42 +- .../get_element_attributes_packet_test.cc | 48 +- .../avrcp/get_folder_items_packet_test.cc | 76 +- .../avrcp/get_item_attributes_packet_test.cc | 58 +- .../avrcp/get_play_status_packet_test.cc | 3 +- .../get_total_number_of_items_packet_test.cc | 19 +- ...yer_application_setting_attributes_test.cc | 18 +- ..._player_application_setting_values_test.cc | 35 +- .../tests/avrcp/pass_through_packet_test.cc | 9 +- .../register_notification_packet_test.cc | 71 +- .../avrcp/set_addressed_player_packet_test.cc | 9 +- .../avrcp/set_browsed_player_packet_test.cc | 13 +- ...t_player_application_setting_value_test.cc | 26 +- .../packet/tests/avrcp/vendor_packet_test.cc | 69 +- system/packet/tests/base/iterator_test.cc | 100 +- .../packet/tests/base/packet_builder_test.cc | 1 + system/packet/tests/base/packet_test.cc | 26 +- system/packet/tests/base/packet_test_common.h | 25 +- .../tests/fuzzers/avrcp_packet_fuzzer.cc | 15 +- .../tests/fuzzers/change_path_res_fuzzer.cc | 4 +- .../fuzzers/get_capabilities_res_fuzzer.cc | 4 +- ...et_element_attributes_req_packet_fuzzer.cc | 7 +- .../fuzzers/get_folder_items_req_fuzzer.cc | 3 +- .../fuzzers/get_folder_items_res_fuzzer.cc | 11 +- .../fuzzers/get_item_attributes_req_fuzzer.cc | 3 +- .../fuzzers/get_item_attributes_res_fuzzer.cc | 3 +- .../fuzzers/get_play_status_req_fuzzer.cc | 2 +- .../fuzzers/get_play_status_res_fuzzer.cc | 2 +- .../get_total_number_of_items_req_fuzzer.cc | 7 +- .../get_total_number_of_items_res_fuzzer.cc | 7 +- .../fuzzers/pass_through_packet_fuzzer.cc | 6 +- .../register_notification_packet_fuzzer.cc | 3 +- .../tests/fuzzers/reject_packet_fuzzer.cc | 3 +- .../set_absolute_volume_packet_fuzzer.cc | 3 +- .../set_addressed_player_packet_fuzzer.cc | 3 +- .../fuzzers/set_browsed_player_req_fuzzer.cc | 3 +- .../fuzzers/set_browsed_player_res_fuzzer.cc | 3 +- .../tests/fuzzers/vendor_packet_fuzzer.cc | 3 +- system/packet/tests/packet_test_helper.h | 83 +- system/packet/tests/test_packets.h | 62 +- system/pdl/hci/address.cc | 21 +- system/pdl/hci/class_of_device.cc | 18 +- system/pdl/hci/include/hci/address.h | 16 +- system/pdl/hci/include/hci/class_of_device.h | 12 +- system/profile/avrcp/avrcp_config.h | 8 +- system/profile/avrcp/avrcp_internal.h | 51 +- .../profile/avrcp/avrcp_message_converter.h | 12 +- system/profile/avrcp/connection_handler.cc | 168 +- system/profile/avrcp/connection_handler.h | 27 +- system/profile/avrcp/device.cc | 881 +- system/profile/avrcp/device.h | 173 +- system/profile/avrcp/media_id_map.h | 12 +- .../tests/avrcp_connection_handler_test.cc | 275 +- .../avrcp_device_fuzz/avrcp_device_fuzz.cc | 198 +- .../profile/avrcp/tests/avrcp_device_test.cc | 1277 +- .../profile/avrcp/tests/avrcp_test_helper.h | 72 +- .../profile/sdp/common/data_element_reader.cc | 28 +- .../profile/sdp/common/data_element_reader.h | 11 +- .../common/test/data_element_reader_test.cc | 452 +- system/profile/sdp/sdp_logging_helper.h | 4 +- .../src/connection/ffi/connection_shim.cc | 59 +- .../rust/src/connection/ffi/connection_shim.h | 38 +- system/rust/src/core/ffi/module.cc | 9 +- system/rust/src/core/ffi/types.h | 5 +- system/rust/src/gatt/ffi/gatt_shim.cc | 75 +- system/rust/src/gatt/ffi/gatt_shim.h | 15 +- system/stack/a2dp/a2dp_aac.cc | 639 +- system/stack/a2dp/a2dp_aac_decoder.cc | 28 +- system/stack/a2dp/a2dp_aac_decoder_linux.cc | 4 +- system/stack/a2dp/a2dp_aac_encoder.cc | 326 +- system/stack/a2dp/a2dp_aac_encoder_linux.cc | 186 +- system/stack/a2dp/a2dp_api.cc | 104 +- system/stack/a2dp/a2dp_codec_config.cc | 488 +- system/stack/a2dp/a2dp_ext.cc | 50 +- system/stack/a2dp/a2dp_int.h | 8 +- system/stack/a2dp/a2dp_sbc.cc | 587 +- system/stack/a2dp/a2dp_sbc_decoder.cc | 16 +- system/stack/a2dp/a2dp_sbc_encoder.cc | 376 +- system/stack/a2dp/a2dp_sbc_up_sample.cc | 51 +- system/stack/a2dp/a2dp_vendor.cc | 167 +- system/stack/a2dp/a2dp_vendor_aptx.cc | 363 +- system/stack/a2dp/a2dp_vendor_aptx_encoder.cc | 115 +- system/stack/a2dp/a2dp_vendor_aptx_hd.cc | 400 +- .../stack/a2dp/a2dp_vendor_aptx_hd_encoder.cc | 164 +- .../stack/a2dp/a2dp_vendor_aptx_hd_linux.cc | 70 +- system/stack/a2dp/a2dp_vendor_aptx_linux.cc | 65 +- system/stack/a2dp/a2dp_vendor_ldac.cc | 579 +- system/stack/a2dp/a2dp_vendor_ldac_decoder.cc | 90 +- system/stack/a2dp/a2dp_vendor_ldac_encoder.cc | 275 +- system/stack/a2dp/a2dp_vendor_ldac_linux.cc | 92 +- system/stack/a2dp/a2dp_vendor_opus.cc | 512 +- system/stack/a2dp/a2dp_vendor_opus_decoder.cc | 49 +- system/stack/a2dp/a2dp_vendor_opus_encoder.cc | 213 +- system/stack/a2dp/a2dp_vendor_opus_linux.cc | 96 +- system/stack/acl/acl.cc | 1 + system/stack/acl/acl.h | 137 +- system/stack/acl/ble_acl.cc | 137 +- system/stack/acl/btm_acl.cc | 742 +- system/stack/acl/btm_pm.cc | 216 +- system/stack/acl/peer_packet_types.h | 42 +- system/stack/arbiter/acl_arbiter.cc | 35 +- system/stack/arbiter/acl_arbiter.h | 15 +- system/stack/avct/avct_api.cc | 20 +- system/stack/avct/avct_bcb_act.cc | 127 +- system/stack/avct/avct_ccb.cc | 6 +- system/stack/avct/avct_defs.h | 3 +- system/stack/avct/avct_int.h | 26 +- system/stack/avct/avct_l2c.cc | 105 +- system/stack/avct/avct_l2c_br.cc | 44 +- system/stack/avct/avct_lcb.cc | 127 +- system/stack/avct/avct_lcb_act.cc | 130 +- system/stack/avdt/avdt_ad.cc | 71 +- system/stack/avdt/avdt_api.cc | 102 +- system/stack/avdt/avdt_ccb.cc | 552 +- system/stack/avdt/avdt_ccb_act.cc | 93 +- system/stack/avdt/avdt_int.h | 144 +- system/stack/avdt/avdt_l2c.cc | 63 +- system/stack/avdt/avdt_msg.cc | 427 +- system/stack/avdt/avdt_scb.cc | 1250 +- system/stack/avdt/avdt_scb_act.cc | 301 +- system/stack/avrc/avrc_api.cc | 300 +- system/stack/avrc/avrc_bld_ct.cc | 112 +- system/stack/avrc/avrc_bld_tg.cc | 237 +- system/stack/avrc/avrc_int.h | 31 +- system/stack/avrc/avrc_opt.cc | 55 +- system/stack/avrc/avrc_pars_ct.cc | 356 +- system/stack/avrc/avrc_pars_tg.cc | 215 +- system/stack/avrc/avrc_sdp.cc | 104 +- system/stack/avrc/avrc_utils.cc | 46 +- system/stack/bnep/bnep_api.cc | 214 +- system/stack/bnep/bnep_int.h | 49 +- system/stack/bnep/bnep_main.cc | 191 +- system/stack/bnep/bnep_utils.cc | 306 +- system/stack/btm/ble_scanner_hci_interface.cc | 191 +- system/stack/btm/ble_scanner_hci_interface.h | 61 +- system/stack/btm/btm_ble.cc | 44 +- system/stack/btm/btm_ble_addr.cc | 79 +- system/stack/btm/btm_ble_adv_filter.cc | 140 +- system/stack/btm/btm_ble_bgconn.cc | 45 +- system/stack/btm/btm_ble_cont_energy.cc | 20 +- system/stack/btm/btm_ble_gap.cc | 1061 +- system/stack/btm/btm_ble_int.h | 13 +- system/stack/btm/btm_ble_int_types.h | 56 +- system/stack/btm/btm_ble_privacy.cc | 132 +- system/stack/btm/btm_ble_scanner.cc | 83 +- system/stack/btm/btm_ble_sec.cc | 585 +- system/stack/btm/btm_ble_sec.h | 25 +- system/stack/btm/btm_client_interface.cc | 207 +- system/stack/btm/btm_dev.cc | 207 +- system/stack/btm/btm_devctl.cc | 113 +- system/stack/btm/btm_inq.cc | 731 +- system/stack/btm/btm_int_types.h | 54 +- system/stack/btm/btm_iot_config.cc | 23 +- system/stack/btm/btm_iso.cc | 61 +- system/stack/btm/btm_iso_impl.h | 353 +- system/stack/btm/btm_main.cc | 25 +- system/stack/btm/btm_sco.cc | 751 +- system/stack/btm/btm_sco.h | 20 +- system/stack/btm/btm_sco_hci.cc | 355 +- system/stack/btm/btm_sco_hfp_hal.cc | 20 +- system/stack/btm/btm_sco_hfp_hal.h | 3 +- system/stack/btm/btm_sco_hfp_hal_linux.cc | 97 +- system/stack/btm/btm_sec.cc | 1741 +- system/stack/btm/btm_sec.h | 88 +- system/stack/btm/btm_sec_cb.cc | 97 +- system/stack/btm/btm_sec_cb.h | 29 +- system/stack/btm/btm_sec_int_types.h | 60 +- .../btm/btm_security_client_interface.cc | 58 +- system/stack/btm/hfp_lc3_decoder.cc | 12 +- system/stack/btm/hfp_lc3_decoder_linux.cc | 12 +- system/stack/btm/hfp_lc3_encoder.cc | 6 +- system/stack/btm/hfp_lc3_encoder_linux.cc | 3 +- system/stack/btm/hfp_msbc_decoder.cc | 25 +- system/stack/btm/neighbor_inquiry.h | 35 +- system/stack/btm/power_mode.h | 46 +- system/stack/btm/sco_pkt_status.h | 8 +- system/stack/btm/security_device_record.h | 182 +- system/stack/btm/security_event_parser.cc | 105 +- system/stack/btm/security_event_parser.h | 2 +- system/stack/btu/btu_hcif.cc | 343 +- system/stack/btu/main_thread.cc | 21 +- system/stack/eatt/eatt.cc | 81 +- system/stack/eatt/eatt.h | 46 +- system/stack/eatt/eatt_impl.h | 458 +- system/stack/fuzzers/avrc_fuzzer.cc | 56 +- system/stack/fuzzers/bnep_fuzzer.cc | 81 +- system/stack/fuzzers/gatt_fuzzer.cc | 177 +- system/stack/fuzzers/l2cap_fuzzer.cc | 157 +- system/stack/fuzzers/rfcomm_fuzzer.cc | 52 +- system/stack/fuzzers/sdp_fuzzer.cc | 152 +- system/stack/fuzzers/smp_fuzzer.cc | 107 +- system/stack/gap/gap_ble.cc | 182 +- system/stack/gap/gap_conn.cc | 247 +- system/stack/gatt/att_protocol.cc | 135 +- system/stack/gatt/connection_manager.cc | 131 +- system/stack/gatt/connection_manager.h | 3 +- system/stack/gatt/gatt_api.cc | 395 +- system/stack/gatt/gatt_attr.cc | 455 +- system/stack/gatt/gatt_auth.cc | 77 +- system/stack/gatt/gatt_cl.cc | 356 +- system/stack/gatt/gatt_db.cc | 208 +- system/stack/gatt/gatt_int.h | 231 +- system/stack/gatt/gatt_main.cc | 407 +- system/stack/gatt/gatt_sr.cc | 462 +- system/stack/gatt/gatt_sr_hash.cc | 11 +- system/stack/gatt/gatt_utils.cc | 443 +- system/stack/hcic/hciblecmds.cc | 246 +- system/stack/hcic/hcicmds.cc | 116 +- system/stack/hid/hid_conn.h | 2 +- system/stack/hid/hidd_api.cc | 186 +- system/stack/hid/hidd_conn.cc | 186 +- system/stack/hid/hidd_int.h | 5 +- system/stack/hid/hidh_api.cc | 229 +- system/stack/hid/hidh_conn.cc | 342 +- system/stack/hid/hidh_int.h | 5 +- system/stack/include/a2dp_aac.h | 40 +- system/stack/include/a2dp_api.h | 12 +- system/stack/include/a2dp_codec_api.h | 114 +- system/stack/include/a2dp_ext.h | 10 +- system/stack/include/a2dp_sbc.h | 37 +- system/stack/include/a2dp_sbc_up_sample.h | 23 +- system/stack/include/a2dp_vendor.h | 24 +- system/stack/include/a2dp_vendor_aptx.h | 25 +- .../stack/include/a2dp_vendor_aptx_encoder.h | 12 +- system/stack/include/a2dp_vendor_aptx_hd.h | 28 +- .../include/a2dp_vendor_aptx_hd_encoder.h | 12 +- system/stack/include/a2dp_vendor_ldac.h | 45 +- .../stack/include/a2dp_vendor_ldac_encoder.h | 9 +- system/stack/include/a2dp_vendor_opus.h | 57 +- .../stack/include/a2dp_vendor_opus_encoder.h | 9 +- system/stack/include/acl_api.h | 73 +- system/stack/include/acl_client_callbacks.h | 7 +- system/stack/include/acl_hci_link_interface.h | 50 +- system/stack/include/advertise_data_parser.h | 38 +- system/stack/include/avct_api.h | 8 +- system/stack/include/avdt_api.h | 128 +- system/stack/include/avdtc_api.h | 18 +- system/stack/include/avrc_api.h | 46 +- system/stack/include/avrc_defs.h | 225 +- system/stack/include/ble_acl_interface.h | 41 +- system/stack/include/ble_hci_link_interface.h | 3 +- system/stack/include/ble_scanner.h | 42 +- system/stack/include/bnep_api.h | 89 +- system/stack/include/bt_dev_class.h | 25 +- system/stack/include/bt_name.h | 17 +- system/stack/include/bt_psm_types.h | 4 +- system/stack/include/bt_types.h | 132 +- system/stack/include/bt_uuid16.h | 30 +- system/stack/include/btm_api.h | 56 +- system/stack/include/btm_api_types.h | 11 +- system/stack/include/btm_ble_addr.h | 10 +- system/stack/include/btm_ble_api.h | 70 +- system/stack/include/btm_ble_api_types.h | 52 +- system/stack/include/btm_ble_privacy.h | 8 +- system/stack/include/btm_ble_sec_api.h | 23 +- system/stack/include/btm_ble_sec_api_types.h | 5 +- system/stack/include/btm_client_interface.h | 103 +- system/stack/include/btm_iso_api.h | 48 +- system/stack/include/btm_log_history.h | 14 +- system/stack/include/btm_sec_api.h | 7 +- system/stack/include/btm_sec_api_types.h | 59 +- system/stack/include/btm_status.h | 48 +- system/stack/include/btu_hcif.h | 9 +- system/stack/include/gap_api.h | 22 +- system/stack/include/gatt_api.h | 275 +- system/stack/include/hci_error_code.h | 12 +- system/stack/include/hci_evt_length.h | 516 +- system/stack/include/hcidefs.h | 121 +- system/stack/include/hcimsgs.h | 234 +- system/stack/include/hfp_lc3_decoder.h | 3 +- system/stack/include/hfp_msbc_decoder.h | 3 +- system/stack/include/hidd_api.h | 23 +- system/stack/include/hiddefs.h | 39 +- system/stack/include/hidh_api.h | 19 +- system/stack/include/inq_hci_link_interface.h | 4 +- system/stack/include/l2c_api.h | 181 +- system/stack/include/l2cap_acl_interface.h | 3 +- .../include/l2cap_controller_interface.h | 2 +- .../stack/include/l2cap_hci_link_interface.h | 24 +- system/stack/include/l2cdefs.h | 47 +- .../stack/include/ldacBT_bco_for_fluoride.h | 12 +- system/stack/include/main_thread.h | 6 +- system/stack/include/pan_api.h | 138 +- system/stack/include/port_api.h | 67 +- system/stack/include/profiles_api.h | 2 +- system/stack/include/rfcdefs.h | 35 +- system/stack/include/sco_hci_link_interface.h | 15 +- system/stack/include/sdp_api.h | 83 +- system/stack/include/sdpdefs.h | 10 +- system/stack/include/sec_hci_link_interface.h | 22 +- .../stack/include/security_client_callbacks.h | 63 +- system/stack/include/smp_api.h | 3 +- system/stack/include/smp_api_types.h | 12 +- system/stack/include/smp_status.h | 2 +- system/stack/include/srvc_api.h | 3 +- system/stack/include/stack_metrics_logging.h | 42 +- system/stack/l2cap/l2c_api.cc | 421 +- system/stack/l2cap/l2c_ble.cc | 446 +- system/stack/l2cap/l2c_ble_conn_params.cc | 200 +- system/stack/l2cap/l2c_csm.cc | 664 +- system/stack/l2cap/l2c_fcr.cc | 664 +- system/stack/l2cap/l2c_int.h | 297 +- system/stack/l2cap/l2c_link.cc | 371 +- system/stack/l2cap/l2c_main.cc | 140 +- system/stack/l2cap/l2c_utils.cc | 972 +- system/stack/metrics/stack_metrics_logging.cc | 74 +- system/stack/mmc/codec_client/codec_client.cc | 41 +- system/stack/mmc/codec_client/codec_client.h | 4 +- .../mmc/codec_server/a2dp_aac_mmc_encoder.cc | 15 +- .../mmc/codec_server/a2dp_aac_mmc_encoder.h | 4 +- .../mmc/codec_server/hfp_lc3_mmc_decoder.cc | 16 +- .../mmc/codec_server/hfp_lc3_mmc_decoder.h | 4 +- .../mmc/codec_server/hfp_lc3_mmc_encoder.cc | 10 +- .../mmc/codec_server/hfp_lc3_mmc_encoder.h | 4 +- system/stack/mmc/codec_server/lc3_utils.h | 3 +- system/stack/mmc/daemon/service.cc | 80 +- system/stack/mmc/daemon/service.h | 12 +- system/stack/mmc/main.cc | 18 +- system/stack/mmc/metrics/mmc_rtt_logger.cc | 11 +- system/stack/mmc/metrics/mmc_rtt_logger.h | 4 +- .../stack/mmc/mmc_interface/mmc_interface.h | 5 +- .../mmc/test/hfp_lc3_mmc_decoder_test.cc | 29 +- .../mmc/test/hfp_lc3_mmc_encoder_test.cc | 26 +- system/stack/mmc/test/mock/mock_embdrv_lc3.cc | 26 +- system/stack/mmc/test/mock/mock_embdrv_lc3.h | 76 +- system/stack/pan/pan_api.cc | 162 +- system/stack/pan/pan_int.h | 31 +- system/stack/pan/pan_main.cc | 217 +- system/stack/pan/pan_utils.cc | 114 +- system/stack/rfcomm/port_api.cc | 352 +- system/stack/rfcomm/port_int.h | 97 +- system/stack/rfcomm/port_rfc.cc | 270 +- system/stack/rfcomm/port_utils.cc | 113 +- system/stack/rfcomm/rfc_int.h | 76 +- system/stack/rfcomm/rfc_l2cap_if.cc | 68 +- system/stack/rfcomm/rfc_mx_fsm.cc | 144 +- system/stack/rfcomm/rfc_port_fsm.cc | 302 +- system/stack/rfcomm/rfc_port_if.cc | 54 +- system/stack/rfcomm/rfc_ts_frames.cc | 191 +- system/stack/rfcomm/rfc_utils.cc | 138 +- system/stack/rnr/remote_name_request.h | 9 +- system/stack/sdp/internal/sdp_api.h | 72 +- system/stack/sdp/sdp_api.cc | 549 +- system/stack/sdp/sdp_db.cc | 310 +- system/stack/sdp/sdp_discovery.cc | 215 +- system/stack/sdp/sdp_discovery_db.h | 19 +- system/stack/sdp/sdp_main.cc | 61 +- system/stack/sdp/sdp_server.cc | 473 +- system/stack/sdp/sdp_utils.cc | 525 +- system/stack/sdp/sdpint.h | 90 +- system/stack/smp/p_256_ecc_pp.cc | 11 +- system/stack/smp/p_256_ecc_pp.h | 1 + system/stack/smp/p_256_multprecision.cc | 64 +- system/stack/smp/p_256_multprecision.h | 2 +- system/stack/smp/smp_act.cc | 403 +- system/stack/smp/smp_api.cc | 75 +- system/stack/smp/smp_br_main.cc | 282 +- system/stack/smp/smp_int.h | 40 +- system/stack/smp/smp_keys.cc | 309 +- system/stack/smp/smp_l2c.cc | 107 +- system/stack/smp/smp_main.cc | 1108 +- system/stack/smp/smp_utils.cc | 543 +- system/stack/srvc/srvc_dis.cc | 114 +- system/stack/srvc/srvc_dis_int.h | 3 +- system/stack/srvc/srvc_eng.cc | 132 +- system/stack/test/a2dp/a2dp_aac_unittest.cc | 51 +- system/stack/test/a2dp/a2dp_opus_unittest.cc | 52 +- .../test/a2dp/a2dp_sbc_regression_tests.cc | 2 +- system/stack/test/a2dp/a2dp_sbc_unittest.cc | 52 +- .../a2dp/a2dp_vendor_ldac_decoder_test.cc | 7 +- .../test/a2dp/a2dp_vendor_ldac_unittest.cc | 49 +- .../test/a2dp/a2dp_vendor_regression_tests.cc | 2 +- system/stack/test/a2dp/misc_fake.cc | 4 +- system/stack/test/a2dp/mock_bta_av_codec.cc | 4 +- system/stack/test/a2dp/test_util.h | 4 +- system/stack/test/a2dp/wav_reader.h | 4 +- system/stack/test/a2dp/wav_reader_unittest.cc | 8 +- system/stack/test/ad_parser_unittest.cc | 91 +- system/stack/test/btm/btm_test_fixtures.h | 4 +- .../stack/test/btm/peer_packet_types_test.cc | 19 +- system/stack/test/btm/sco_hci_test.cc | 269 +- system/stack/test/btm/sco_pkt_status_test.cc | 143 +- system/stack/test/btm/stack_btm_dev_test.cc | 2 +- .../test/btm/stack_btm_dm_inq_db_test.cc | 32 +- system/stack/test/btm/stack_btm_inq_test.cc | 50 +- .../test/btm/stack_btm_power_mode_test.cc | 55 +- .../test/btm/stack_btm_regression_tests.cc | 8 +- system/stack/test/btm/stack_btm_sec_test.cc | 99 +- system/stack/test/btm/stack_btm_test.cc | 115 +- system/stack/test/btm_iso_test.cc | 2008 +- system/stack/test/common/mock_btif_config.h | 21 +- system/stack/test/common/mock_btif_storage.cc | 9 +- system/stack/test/common/mock_btif_storage.h | 7 +- .../stack/test/common/mock_btm_api_layer.cc | 20 +- system/stack/test/common/mock_btm_api_layer.h | 32 +- system/stack/test/common/mock_btm_layer.cc | 25 +- system/stack/test/common/mock_btm_layer.h | 20 +- system/stack/test/common/mock_eatt.cc | 37 +- system/stack/test/common/mock_eatt.h | 35 +- system/stack/test/common/mock_gatt_layer.cc | 12 +- system/stack/test/common/mock_gatt_layer.h | 7 +- system/stack/test/common/mock_hcic_layer.cc | 104 +- system/stack/test/common/mock_hcic_layer.h | 72 +- system/stack/test/common/mock_l2cap_layer.cc | 45 +- system/stack/test/common/mock_l2cap_layer.h | 59 +- .../stack/test/common/mock_stack_avdt_msg.cc | 31 +- .../test/common/stack_test_packet_utils.cc | 15 +- .../test/common/stack_test_packet_utils.h | 10 +- system/stack/test/eatt/eatt_test.cc | 303 +- .../test/fuzzers/a2dp/a2dpFuzzFunctions.h | 79 +- .../stack/test/fuzzers/a2dp/a2dpFuzzHelpers.h | 6 +- .../a2dp/codec/a2dpCodecConfigFuzzFunctions.h | 50 +- .../a2dp/codec/a2dpCodecConfigFuzzHelpers.h | 2 + .../a2dp/codec/a2dpCodecFuzzFunctions.h | 587 +- .../fuzzers/a2dp/codec/a2dpCodecFuzzHelpers.h | 2 + .../a2dp/codec/a2dpCodecHelperFunctions.h | 99 +- .../a2dp/codec/a2dpCodecInfoFuzzFunctions.h | 31 +- .../a2dp/codec/a2dpCodecInfoFuzzHelpers.h | 14 +- .../fuzzers/a2dp/codec/fuzz_a2dp_codec.cc | 1 + .../a2dp/codec/fuzz_a2dp_codec_config.cc | 1 + .../a2dp/codec/fuzz_a2dp_codec_info.cc | 1 + system/stack/test/fuzzers/a2dp/fuzz_a2dp.cc | 1 + system/stack/test/fuzzers/avrc/fuzz_avrc.cc | 24 +- .../test/fuzzers/common/commonFuzzHelpers.h | 14 +- system/stack/test/fuzzers/sdp/fuzz_sdp.cc | 1 + .../stack/test/fuzzers/sdp/sdpFuzzFunctions.h | 167 +- .../stack/test/fuzzers/sdp/sdpFuzzHelpers.h | 65 +- system/stack/test/gatt/gatt_api_test.cc | 14 +- system/stack/test/gatt/gatt_sr_test.cc | 324 +- system/stack/test/gatt/mock_gatt_utils_ref.cc | 36 +- system/stack/test/gatt/stack_gatt_test.cc | 224 +- .../test/gatt_connection_manager_test.cc | 76 +- system/stack/test/hci/stack_hci_test.cc | 127 +- system/stack/test/hid/stack_hid_test.cc | 22 +- .../test/rfcomm/stack_rfcomm_port_test.cc | 4 +- system/stack/test/rfcomm/stack_rfcomm_test.cc | 617 +- .../test/rfcomm/stack_rfcomm_test_main.cc | 4 +- .../test/rfcomm/stack_rfcomm_test_utils.cc | 93 +- .../test/rfcomm/stack_rfcomm_test_utils.h | 68 +- .../rfcomm/stack_rfcomm_test_utils_test.cc | 136 +- system/stack/test/sdp/sdp_packet00.h | 28 +- system/stack/test/sdp/stack_sdp_db_test.cc | 118 +- system/stack/test/sdp/stack_sdp_parse_test.cc | 105 +- system/stack/test/sdp/stack_sdp_test.cc | 142 +- system/stack/test/sdp/stack_sdp_utils_test.cc | 484 +- system/stack/test/stack_a2dp_test.cc | 565 +- system/stack/test/stack_acl_test.cc | 19 +- system/stack/test/stack_avdtp_test.cc | 61 +- system/stack/test/stack_avrcp_test.cc | 85 +- system/stack/test/stack_btu_test.cc | 9 +- system/stack/test/stack_gatt_sr_hash_test.cc | 40 +- system/stack/test/stack_include_test.cc | 2 +- system/stack/test/stack_l2cap_test.cc | 284 +- system/stack/test/stack_smp_test.cc | 213 +- system/test/common/core_interface.cc | 93 +- .../test/common/hal_version_manager_test.cc | 138 +- system/test/common/init_flags.cc | 11 +- system/test/common/jni_thread.cc | 8 +- system/test/common/main_handler.cc | 27 +- system/test/common/main_handler.h | 6 +- system/test/common/mock_functions.cc | 3 +- system/test/common/stack_config.cc | 61 +- system/test/common/sync_main_handler.cc | 2 +- system/test/fake/fake_looper.cc | 7 +- system/test/fake/fake_osi.cc | 262 +- system/test/fake/fake_osi.h | 2 +- system/test/fake/fake_thread.cc | 15 +- system/test/fake/fake_thread.h | 9 +- system/test/headless/adapter/adapter.cc | 31 +- system/test/headless/adapter/adapter.h | 5 +- system/test/headless/android_namespace.cc | 4 +- system/test/headless/bt_stack_info.cc | 12 +- system/test/headless/bt_stack_info.h | 4 +- system/test/headless/config.cc | 2 +- system/test/headless/connect/connect.cc | 58 +- system/test/headless/connect/connect.h | 5 +- system/test/headless/discovery/discovery.cc | 8 +- system/test/headless/discovery/discovery.h | 5 +- system/test/headless/dumpsys/dumpsys.cc | 2 +- system/test/headless/dumpsys/dumpsys.h | 5 +- system/test/headless/get_options.cc | 85 +- system/test/headless/get_options.h | 6 +- system/test/headless/handler.h | 4 +- system/test/headless/headless.cc | 147 +- system/test/headless/headless.h | 24 +- system/test/headless/interface.h | 101 +- system/test/headless/log.h | 57 +- system/test/headless/main.cc | 49 +- system/test/headless/messenger.cc | 22 +- system/test/headless/messenger.h | 7 +- system/test/headless/mode/mode.cc | 42 +- system/test/headless/mode/mode.h | 5 +- system/test/headless/nop/nop.cc | 2 +- system/test/headless/nop/nop.h | 5 +- system/test/headless/pairing/pairing.h | 5 +- system/test/headless/property.cc | 145 +- system/test/headless/property.h | 31 +- system/test/headless/read/name.cc | 14 +- system/test/headless/read/name.h | 5 +- system/test/headless/read/read.cc | 8 +- system/test/headless/read/read.h | 2 +- system/test/headless/scan/scan.cc | 26 +- system/test/headless/scan/scan.h | 5 +- system/test/headless/sdp/sdp.cc | 24 +- system/test/headless/sdp/sdp.h | 5 +- system/test/headless/sdp/sdp_db.cc | 3 +- system/test/headless/sdp/sdp_db.h | 4 +- system/test/headless/stopwatch.h | 15 +- .../test/headless/utils/power_mode_client.h | 120 +- system/test/mock/mock_a2dp_api.cc | 12 +- system/test/mock/mock_a2dp_codec_config.cc | 136 +- .../mock_audio_hal_interface_a2dp_encoding.cc | 82 +- .../mock_audio_hal_interface_a2dp_encoding.h | 147 +- system/test/mock/mock_bluetooth_interface.cc | 61 +- system/test/mock/mock_bta_ag_api.cc | 18 +- system/test/mock/mock_bta_ar.cc | 10 +- system/test/mock/mock_bta_av_api.cc | 55 +- system/test/mock/mock_bta_av_api.h | 200 +- system/test/mock/mock_bta_av_ci.cc | 9 +- system/test/mock/mock_bta_av_main.cc | 20 +- system/test/mock/mock_bta_csis.cc | 6 +- system/test/mock/mock_bta_dm_act.cc | 54 +- system/test/mock/mock_bta_dm_act.h | 285 +- system/test/mock/mock_bta_dm_api.cc | 83 +- system/test/mock/mock_bta_dm_api.h | 294 +- system/test/mock/mock_bta_dm_main.h | 2 +- system/test/mock/mock_bta_gattc_api.cc | 103 +- system/test/mock/mock_bta_gatts_api.cc | 34 +- system/test/mock/mock_bta_groups.cc | 3 +- system/test/mock/mock_bta_has.cc | 6 +- system/test/mock/mock_bta_hd_api.cc | 23 +- system/test/mock/mock_bta_hearing_aid.cc | 24 +- system/test/mock/mock_bta_hf_client_api.cc | 17 +- system/test/mock/mock_bta_hh_api.cc | 47 +- system/test/mock/mock_bta_hh_utils.cc | 26 +- system/test/mock/mock_bta_hh_utils.h | 88 +- system/test/mock/mock_bta_jv_api.cc | 47 +- system/test/mock/mock_bta_leaudio.cc | 32 +- .../test/mock/mock_bta_leaudio_broadcaster.cc | 5 +- system/test/mock/mock_bta_pan_api.cc | 10 +- system/test/mock/mock_bta_pan_ci.cc | 25 +- system/test/mock/mock_bta_ras_client.cc | 13 +- system/test/mock/mock_bta_ras_server.cc | 15 +- system/test/mock/mock_bta_sdp_api.cc | 3 +- system/test/mock/mock_bta_sdp_api.h | 29 +- system/test/mock/mock_bta_sys_conn.cc | 48 +- system/test/mock/mock_bta_sys_main.cc | 3 +- system/test/mock/mock_bta_sys_main.h | 37 +- system/test/mock/mock_bta_vc.cc | 5 +- system/test/mock/mock_bta_vc_device.cc | 33 +- system/test/mock/mock_btcore_module.h | 26 +- system/test/mock/mock_btif_av.cc | 47 +- system/test/mock/mock_btif_av.h | 261 +- system/test/mock/mock_btif_avrcp_service.h | 5 +- system/test/mock/mock_btif_bluetooth.cc | 21 +- system/test/mock/mock_btif_bluetooth.h | 62 +- system/test/mock/mock_btif_bta_pan_co_rx.cc | 12 +- system/test/mock/mock_btif_bta_pan_co_rx.h | 53 +- system/test/mock/mock_btif_co_bta_av_co.cc | 141 +- system/test/mock/mock_btif_co_bta_av_co.h | 247 +- system/test/mock/mock_btif_co_bta_dm_co.cc | 10 +- system/test/mock/mock_btif_co_bta_hh_co.cc | 26 +- system/test/mock/mock_btif_config.cc | 36 +- system/test/mock/mock_btif_config.h | 157 +- system/test/mock/mock_btif_core.cc | 41 +- system/test/mock/mock_btif_debug_conn.cc | 3 +- system/test/mock/mock_btif_dm.cc | 65 +- system/test/mock/mock_btif_hf.h | 5 +- system/test/mock/mock_btif_profile_queue.cc | 6 +- system/test/mock/mock_btif_profile_queue.h | 20 +- system/test/mock/mock_btif_profile_storage.cc | 188 +- system/test/mock/mock_btif_profile_storage.h | 333 +- system/test/mock/mock_btif_sock_rfc.cc | 22 +- system/test/mock/mock_btif_sock_rfc.h | 85 +- system/test/mock/mock_btif_stack_manager.cc | 4 +- system/test/mock/mock_btif_storage.cc | 152 +- system/test/mock/mock_btif_storage.h | 326 +- system/test/mock/mock_btif_util.h | 77 +- system/test/mock/mock_common_os_utils.h | 2 +- .../test/mock/mock_device_esco_parameters.h | 4 +- system/test/mock/mock_device_interop.cc | 178 +- system/test/mock/mock_device_interop.h | 347 +- system/test/mock/mock_device_iot_config.cc | 46 +- system/test/mock/mock_device_iot_config.h | 178 +- system/test/mock/mock_frameworks_libaudio.cc | 71 +- system/test/mock/mock_hci_btsnoop.cc | 22 +- system/test/mock/mock_jni_thread.cc | 8 +- system/test/mock/mock_legacy_hci_interface.h | 8 +- .../mock_main_shim_BtifConfigInterface.cc | 74 +- system/test/mock/mock_main_shim_acl.cc | 113 +- system/test/mock/mock_main_shim_acl_api.cc | 78 +- system/test/mock/mock_main_shim_acl_api.h | 170 +- .../mock_main_shim_acl_legacy_interface.cc | 80 +- system/test/mock/mock_main_shim_btm_api.cc | 10 +- ..._main_shim_distance_measurement_manager.cc | 7 +- system/test/mock/mock_main_shim_dumpsys.cc | 7 +- system/test/mock/mock_main_shim_entry.cc | 12 +- system/test/mock/mock_main_shim_hci_layer.cc | 19 +- system/test/mock/mock_main_shim_hci_layer.h | 26 +- system/test/mock/mock_main_shim_l2cap_api.h | 308 +- .../mock_main_shim_le_advertising_manager.cc | 4 +- .../mock_main_shim_le_advertising_manager.h | 52 +- .../mock_main_shim_le_scanning_manager.cc | 8 +- .../test/mock/mock_main_shim_metric_id_api.cc | 7 +- .../test/mock/mock_main_shim_metrics_api.cc | 182 +- system/test/mock/mock_main_shim_metrics_api.h | 368 +- system/test/mock/mock_main_shim_stack.cc | 7 +- system/test/mock/mock_osi_alarm.cc | 6 +- system/test/mock/mock_osi_alarm.h | 48 +- system/test/mock/mock_osi_allocator.h | 22 +- system/test/mock/mock_osi_config.cc | 48 +- system/test/mock/mock_osi_config.h | 234 +- system/test/mock/mock_osi_fixed_queue.cc | 10 +- system/test/mock/mock_osi_fixed_queue.h | 98 +- system/test/mock/mock_osi_future.h | 16 +- system/test/mock/mock_osi_list.cc | 6 +- system/test/mock/mock_osi_list.h | 99 +- system/test/mock/mock_osi_mutex.h | 4 +- system/test/mock/mock_osi_properties.cc | 7 +- system/test/mock/mock_osi_properties.h | 33 +- system/test/mock/mock_osi_ringbuffer.cc | 3 +- system/test/mock/mock_osi_ringbuffer.h | 52 +- system/test/mock/mock_osi_socket.cc | 17 +- system/test/mock/mock_osi_socket.h | 70 +- .../mock/mock_osi_stack_power_telemetry.cc | 90 +- system/test/mock/mock_osi_thread.h | 53 +- system/test/mock/mock_osi_thread_scheduler.cc | 6 +- system/test/mock/mock_osi_thread_scheduler.h | 15 +- system/test/mock/mock_osi_wakelock.h | 19 +- system/test/mock/mock_stack_a2dp_api.cc | 16 +- .../test/mock/mock_stack_a2dp_codec_config.cc | 150 +- system/test/mock/mock_stack_a2dp_sbc.cc | 59 +- system/test/mock/mock_stack_a2dp_sbc.h | 180 +- system/test/mock/mock_stack_acl.cc | 248 +- system/test/mock/mock_stack_acl.h | 703 +- system/test/mock/mock_stack_acl_ble.cc | 54 +- system/test/mock/mock_stack_acl_btm_pm.cc | 35 +- .../mock/mock_stack_arbiter_acl_arbiter.cc | 6 +- system/test/mock/mock_stack_avct_api.cc | 4 +- system/test/mock/mock_stack_avdt_api.cc | 56 +- system/test/mock/mock_stack_avrc_api.cc | 21 +- system/test/mock/mock_stack_avrc_apt.cc | 6 +- system/test/mock/mock_stack_avrc_apt.h | 34 +- system/test/mock/mock_stack_avrc_bld_tg.cc | 3 +- system/test/mock/mock_stack_avrc_pars.ct.cc | 12 +- system/test/mock/mock_stack_avrc_pars_tg.cc | 8 +- system/test/mock/mock_stack_avrc_sdp.cc | 17 +- system/test/mock/mock_stack_avrc_sdp.h | 48 +- system/test/mock/mock_stack_avrc_utils.cc | 9 +- system/test/mock/mock_stack_avrc_utils.h | 42 +- system/test/mock/mock_stack_bnep_api.cc | 30 +- system/test/mock/mock_stack_btm_ble.cc | 147 +- system/test/mock/mock_stack_btm_ble.h | 409 +- system/test/mock/mock_stack_btm_ble_addr.cc | 48 +- system/test/mock/mock_stack_btm_ble_addr.h | 73 +- .../mock/mock_stack_btm_ble_adv_filter.cc | 8 +- system/test/mock/mock_stack_btm_ble_bgconn.cc | 6 +- system/test/mock/mock_stack_btm_ble_bgconn.h | 28 +- system/test/mock/mock_stack_btm_ble_gap.cc | 83 +- .../test/mock/mock_stack_btm_ble_privacy.cc | 42 +- system/test/mock/mock_stack_btm_ble_privacy.h | 67 +- system/test/mock/mock_stack_btm_dev.cc | 34 +- system/test/mock/mock_stack_btm_dev.h | 18 +- system/test/mock/mock_stack_btm_devctl.cc | 12 +- system/test/mock/mock_stack_btm_devctl.h | 2 +- .../mock/mock_stack_btm_hfp_lc3_decoder.cc | 7 +- .../mock/mock_stack_btm_hfp_lc3_decoder.h | 14 +- .../mock/mock_stack_btm_hfp_lc3_encoder.cc | 3 +- .../mock/mock_stack_btm_hfp_lc3_encoder.h | 10 +- .../mock/mock_stack_btm_hfp_msbc_decoder.cc | 7 +- .../mock/mock_stack_btm_hfp_msbc_decoder.h | 13 +- .../mock/mock_stack_btm_hfp_msbc_encoder.cc | 3 +- .../mock/mock_stack_btm_hfp_msbc_encoder.h | 10 +- system/test/mock/mock_stack_btm_inq.cc | 32 +- system/test/mock/mock_stack_btm_inq.h | 168 +- system/test/mock/mock_stack_btm_interface.cc | 487 +- system/test/mock/mock_stack_btm_iso.cc | 106 +- system/test/mock/mock_stack_btm_iso.h | 55 +- system/test/mock/mock_stack_btm_main.cc | 18 +- system/test/mock/mock_stack_btm_sco.cc | 48 +- .../test/mock/mock_stack_btm_sco_hfp_hal.cc | 9 +- system/test/mock/mock_stack_btm_sco_hfp_hal.h | 45 +- system/test/mock/mock_stack_btm_sec.cc | 163 +- system/test/mock/mock_stack_btm_sec.h | 511 +- system/test/mock/mock_stack_btu_hcif.cc | 18 +- system/test/mock/mock_stack_gap_ble.cc | 6 +- system/test/mock/mock_stack_gap_conn.cc | 12 +- system/test/mock/mock_stack_gatt.cc | 7 +- system/test/mock/mock_stack_gatt_api.cc | 133 +- system/test/mock/mock_stack_gatt_api.h | 280 +- system/test/mock/mock_stack_gatt_attr.cc | 34 +- system/test/mock/mock_stack_gatt_auth.cc | 7 +- .../mock_stack_gatt_connection_manager.cc | 27 +- system/test/mock/mock_stack_gatt_main.cc | 41 +- .../test/mock/mock_stack_hcic_hciblecmds.cc | 271 +- system/test/mock/mock_stack_hcic_hciblecmds.h | 471 +- system/test/mock/mock_stack_hcic_hcicmds.cc | 147 +- system/test/mock/mock_stack_hcic_hcicmds.h | 355 +- system/test/mock/mock_stack_hidd_api.cc | 30 +- system/test/mock/mock_stack_hidh.cc | 19 +- system/test/mock/mock_stack_l2cap_api.cc | 103 +- system/test/mock/mock_stack_l2cap_api.h | 317 +- system/test/mock/mock_stack_l2cap_ble.cc | 114 +- system/test/mock/mock_stack_l2cap_ble.h | 256 +- system/test/mock/mock_stack_l2cap_link.cc | 27 +- system/test/mock/mock_stack_l2cap_main.cc | 11 +- system/test/mock/mock_stack_l2cap_utils.cc | 148 +- .../test/mock/mock_stack_metrics_logging.cc | 83 +- system/test/mock/mock_stack_metrics_logging.h | 190 +- system/test/mock/mock_stack_pan_api.cc | 40 +- system/test/mock/mock_stack_pan_api.h | 111 +- .../test/mock/mock_stack_rfcomm_port_api.cc | 37 +- system/test/mock/mock_stack_sdp_api.cc | 88 +- system/test/mock/mock_stack_sdp_api.h | 184 +- system/test/mock/mock_stack_sdp_db.cc | 26 +- system/test/mock/mock_stack_sdp_legacy_api.cc | 90 +- system/test/mock/mock_stack_sdp_main.cc | 4 +- system/test/mock/mock_stack_sdp_server.cc | 8 +- system/test/mock/mock_stack_smp_act.cc | 45 +- system/test/mock/mock_stack_smp_act.h | 302 +- system/test/mock/mock_stack_smp_api.cc | 21 +- system/test/mock/mock_stack_srvc_dis.cc | 12 +- system/test/mock/mock_udrv_ulinux_uipc.cc | 29 +- system/test/stub/osi.cc | 116 +- system/test/suite/adapter/adapter_unittest.cc | 63 +- system/test/suite/adapter/bluetooth_test.cc | 55 +- system/test/suite/adapter/bluetooth_test.h | 25 +- system/test/suite/gatt/gatt_test.cc | 47 +- system/test/suite/gatt/gatt_test.h | 32 +- system/test/suite/gatt/gatt_unittest.cc | 65 +- system/types/ble_address_with_type.h | 74 +- system/types/bluetooth/uuid.cc | 91 +- system/types/bluetooth/uuid.h | 10 +- system/types/hci_role.h | 7 +- system/types/raw_address.cc | 14 +- system/types/raw_address.h | 25 +- system/types/remote_version_type.h | 4 +- .../test/ble_address_with_type_unittest.cc | 17 +- system/types/test/bluetooth/uuid_unittest.cc | 27 +- system/types/test/raw_address_unittest.cc | 4 +- system/udrv/include/uipc.h | 21 +- system/udrv/ulinux/uipc.cc | 82 +- tools/rootcanal/desktop/root_canal_main.cc | 48 +- tools/rootcanal/desktop/test_environment.cc | 193 +- tools/rootcanal/desktop/test_environment.h | 69 +- tools/rootcanal/hal/bluetooth_hci.cc | 257 +- tools/rootcanal/hal/bluetooth_hci.h | 68 +- tools/rootcanal/hal/service.cc | 5 +- tools/rootcanal/include/crypto/crypto.h | 3 +- tools/rootcanal/include/hci/address.h | 25 +- .../rootcanal/include/hci/address_with_type.h | 23 +- tools/rootcanal/include/hci/pcap_filter.h | 53 +- tools/rootcanal/include/log.h | 67 +- tools/rootcanal/include/phy.h | 2 +- tools/rootcanal/lib/hci/address.cc | 11 +- tools/rootcanal/lib/hci/pcap_filter.cc | 187 +- tools/rootcanal/lib/log.cc | 38 +- .../model/controller/acl_connection.cc | 21 +- .../model/controller/acl_connection.h | 11 +- .../controller/acl_connection_handler.cc | 116 +- .../model/controller/acl_connection_handler.h | 46 +- .../model/controller/controller_properties.cc | 1371 +- .../model/controller/controller_properties.h | 5 +- .../model/controller/dual_mode_controller.cc | 3346 +-- .../model/controller/dual_mode_controller.h | 46 +- tools/rootcanal/model/controller/ffi.cc | 87 +- tools/rootcanal/model/controller/ffi.h | 14 +- .../model/controller/le_advertiser.cc | 502 +- .../model/controller/le_advertiser.h | 40 +- .../model/controller/link_layer_controller.cc | 2615 +- .../model/controller/link_layer_controller.h | 634 +- .../model/controller/sco_connection.cc | 133 +- .../model/controller/sco_connection.h | 16 +- .../controller/vendor_commands/le_apcf.cc | 372 +- .../controller/vendor_commands/le_apcf.h | 3 +- .../model/devices/baseband_sniffer.cc | 94 +- .../model/devices/baseband_sniffer.h | 13 +- tools/rootcanal/model/devices/beacon.cc | 37 +- tools/rootcanal/model/devices/beacon.h | 11 +- tools/rootcanal/model/devices/beacon_swarm.cc | 56 +- tools/rootcanal/model/devices/beacon_swarm.h | 4 +- tools/rootcanal/model/devices/device.cc | 16 +- tools/rootcanal/model/devices/device.h | 20 +- tools/rootcanal/model/devices/hci_device.cc | 98 +- tools/rootcanal/model/devices/hci_device.h | 12 +- .../model/devices/link_layer_socket_device.cc | 15 +- .../model/devices/link_layer_socket_device.h | 20 +- .../model/devices/scripted_beacon.cc | 116 +- .../rootcanal/model/devices/scripted_beacon.h | 23 +- tools/rootcanal/model/devices/sniffer.cc | 10 +- tools/rootcanal/model/devices/sniffer.h | 9 +- .../model/hci/h4_data_channel_packetizer.cc | 20 +- .../model/hci/h4_data_channel_packetizer.h | 12 +- tools/rootcanal/model/hci/h4_parser.cc | 32 +- tools/rootcanal/model/hci/h4_parser.h | 18 +- tools/rootcanal/model/hci/hci_sniffer.cc | 29 +- tools/rootcanal/model/hci/hci_sniffer.h | 20 +- .../model/hci/hci_socket_transport.cc | 54 +- .../model/hci/hci_socket_transport.h | 13 +- tools/rootcanal/model/hci/hci_transport.h | 11 +- tools/rootcanal/model/setup/async_manager.cc | 132 +- tools/rootcanal/model/setup/async_manager.h | 10 +- .../rootcanal/model/setup/device_boutique.cc | 17 +- tools/rootcanal/model/setup/device_boutique.h | 13 +- tools/rootcanal/model/setup/phy_device.cc | 22 +- tools/rootcanal/model/setup/phy_device.h | 9 +- tools/rootcanal/model/setup/phy_layer.cc | 6 +- tools/rootcanal/model/setup/phy_layer.h | 7 +- .../model/setup/test_channel_transport.cc | 38 +- .../model/setup/test_channel_transport.h | 21 +- .../model/setup/test_command_handler.cc | 58 +- .../model/setup/test_command_handler.h | 12 +- tools/rootcanal/model/setup/test_model.cc | 103 +- tools/rootcanal/model/setup/test_model.h | 71 +- tools/rootcanal/net/async_data_channel.h | 5 +- .../net/async_data_channel_connector.h | 5 +- .../rootcanal/net/async_data_channel_server.h | 12 +- .../rootcanal/net/posix/posix_async_socket.cc | 18 +- .../rootcanal/net/posix/posix_async_socket.h | 7 +- .../net/posix/posix_async_socket_connector.cc | 41 +- .../net/posix/posix_async_socket_connector.h | 7 +- .../net/posix/posix_async_socket_server.cc | 21 +- .../net/posix/posix_async_socket_server.h | 6 +- tools/rootcanal/rust/include/rootcanal_rs.h | 35 +- .../rootcanal/test/async_manager_unittest.cc | 113 +- ...e_add_device_to_filter_accept_list_test.cc | 62 +- ...device_to_periodic_advertiser_list_test.cc | 40 +- .../le_add_device_to_resolving_list_test.cc | 73 +- .../le/le_clear_filter_accept_list_test.cc | 55 +- .../le_clear_periodic_advertiser_list_test.cc | 19 +- .../le/le_clear_resolving_list_test.cc | 33 +- .../le/le_create_connection_cancel_test.cc | 28 +- .../le/le_create_connection_test.cc | 153 +- .../le/le_extended_create_connection_test.cc | 332 +- ...dic_advertising_create_sync_cancel_test.cc | 16 +- ...e_periodic_advertising_create_sync_test.cc | 62 +- ...ove_device_from_filter_accept_list_test.cc | 70 +- ...vice_from_periodic_advertiser_list_test.cc | 28 +- ..._remove_device_from_resolving_list_test.cc | 47 +- .../le/le_scanning_filter_duplicates_test.cc | 94 +- .../le_set_address_resolution_enable_test.cc | 38 +- .../le/le_set_advertising_enable_test.cc | 51 +- .../le/le_set_advertising_parameters_test.cc | 60 +- .../le_set_extended_advertising_data_test.cc | 305 +- ...le_set_extended_advertising_enable_test.cc | 284 +- ...et_extended_advertising_parameters_test.cc | 314 +- .../le/le_set_extended_scan_enable_test.cc | 120 +- .../le_set_extended_scan_parameters_test.cc | 78 +- ...le_set_extended_scan_response_data_test.cc | 345 +- .../le_set_periodic_advertising_data_test.cc | 228 +- ...le_set_periodic_advertising_enable_test.cc | 98 +- ...et_periodic_advertising_parameters_test.cc | 148 +- .../le/le_set_random_address_test.cc | 23 +- .../controller/le/le_set_scan_enable_test.cc | 51 +- .../le/le_set_scan_parameters_test.cc | 67 +- .../test/controller/le/rpa_generation_test.cc | 5 +- .../test/controller/le/test_helpers.h | 17 +- tools/rootcanal/test/h4_parser_unittest.cc | 64 +- .../test/invalid_packet_handler_unittest.cc | 36 +- tools/rootcanal/test/pcap_filter_unittest.cc | 56 +- tools/rootcanal/test/posix_socket_unittest.cc | 53 +- 2347 files changed, 128095 insertions(+), 157406 deletions(-) diff --git a/.clang-format b/.clang-format index 04c4abe1db4..d49e3528a1d 100644 --- a/.clang-format +++ b/.clang-format @@ -32,7 +32,8 @@ AccessModifierOffset: -2 # vs -1 Should be -4 when updating IndentWidth to 4 Standard: c++20 # vs Auto AllowShortIfStatementsOnASingleLine: Never # vs WithoutElse AllowShortLoopsOnASingleLine: false # vs true -SpacesBeforeTrailingComments: 1 # vs 2 +# AOSP suggest 1, but ask to follow clang-format settings. CppLint ask for 2 +# SpacesBeforeTrailingComments: 1 # vs 2 # Allow clang-format to automatically fix more things RemoveSemicolon: true diff --git a/android/app/jni/com_android_bluetooth.h b/android/app/jni/com_android_bluetooth.h index 3723a239282..abb7741671d 100644 --- a/android/app/jni/com_android_bluetooth.h +++ b/android/app/jni/com_android_bluetooth.h @@ -33,99 +33,93 @@ bool isCallbackThread(); class CallbackEnv { public: - CallbackEnv(const char *methodName) : mName(methodName) { - mCallbackEnv = getCallbackEnv(); - } + CallbackEnv(const char* methodName) : mName(methodName) { mCallbackEnv = getCallbackEnv(); } - ~CallbackEnv() { - if (mCallbackEnv && mCallbackEnv->ExceptionCheck()) { - log::error("An exception was thrown by callback '{}'.", mName); - jniLogException(mCallbackEnv, ANDROID_LOG_ERROR, LOG_TAG); - mCallbackEnv->ExceptionClear(); - } + ~CallbackEnv() { + if (mCallbackEnv && mCallbackEnv->ExceptionCheck()) { + log::error("An exception was thrown by callback '{}'.", mName); + jniLogException(mCallbackEnv, ANDROID_LOG_ERROR, LOG_TAG); + mCallbackEnv->ExceptionClear(); } + } - bool valid() const { - if (!mCallbackEnv || !isCallbackThread()) { - log::error("{}: Callback env fail", mName); - return false; - } - return true; + bool valid() const { + if (!mCallbackEnv || !isCallbackThread()) { + log::error("{}: Callback env fail", mName); + return false; } - - // stolen from art/runtime/jni/check_jni.cc - bool isValidUtf(const char* bytes) const { - while (*bytes != '\0') { - const uint8_t* utf8 = reinterpret_cast(bytes++); - // Switch on the high four bits. - switch (*utf8 >> 4) { - case 0x00: - case 0x01: - case 0x02: - case 0x03: - case 0x04: - case 0x05: - case 0x06: - case 0x07: - // Bit pattern 0xxx. No need for any extra bytes. - break; - case 0x08: - case 0x09: - case 0x0a: - case 0x0b: - // Bit patterns 10xx, which are illegal start bytes. - return false; - case 0x0f: - // Bit pattern 1111, which might be the start of a 4 byte sequence. - if ((*utf8 & 0x08) == 0) { - // Bit pattern 1111 0xxx, which is the start of a 4 byte sequence. - // We consume one continuation byte here, and fall through to - // consume two more. - utf8 = reinterpret_cast(bytes++); - if ((*utf8 & 0xc0) != 0x80) { - return false; - } - } else { - return false; - } - // Fall through to the cases below to consume two more continuation - // bytes. - FALLTHROUGH_INTENDED; - case 0x0e: - // Bit pattern 1110, so there are two additional bytes. - utf8 = reinterpret_cast(bytes++); - if ((*utf8 & 0xc0) != 0x80) { - return false; - } - // Fall through to consume one more continuation byte. - FALLTHROUGH_INTENDED; - case 0x0c: - case 0x0d: - // Bit pattern 110x, so there is one additional byte. + return true; + } + + // stolen from art/runtime/jni/check_jni.cc + bool isValidUtf(const char* bytes) const { + while (*bytes != '\0') { + const uint8_t* utf8 = reinterpret_cast(bytes++); + // Switch on the high four bits. + switch (*utf8 >> 4) { + case 0x00: + case 0x01: + case 0x02: + case 0x03: + case 0x04: + case 0x05: + case 0x06: + case 0x07: + // Bit pattern 0xxx. No need for any extra bytes. + break; + case 0x08: + case 0x09: + case 0x0a: + case 0x0b: + // Bit patterns 10xx, which are illegal start bytes. + return false; + case 0x0f: + // Bit pattern 1111, which might be the start of a 4 byte sequence. + if ((*utf8 & 0x08) == 0) { + // Bit pattern 1111 0xxx, which is the start of a 4 byte sequence. + // We consume one continuation byte here, and fall through to + // consume two more. utf8 = reinterpret_cast(bytes++); if ((*utf8 & 0xc0) != 0x80) { return false; } - break; - } + } else { + return false; + } + // Fall through to the cases below to consume two more continuation + // bytes. + FALLTHROUGH_INTENDED; + case 0x0e: + // Bit pattern 1110, so there are two additional bytes. + utf8 = reinterpret_cast(bytes++); + if ((*utf8 & 0xc0) != 0x80) { + return false; + } + // Fall through to consume one more continuation byte. + FALLTHROUGH_INTENDED; + case 0x0c: + case 0x0d: + // Bit pattern 110x, so there is one additional byte. + utf8 = reinterpret_cast(bytes++); + if ((*utf8 & 0xc0) != 0x80) { + return false; + } + break; } - return true; } + return true; + } - JNIEnv *operator-> () const { - return mCallbackEnv; - } + JNIEnv* operator->() const { return mCallbackEnv; } - JNIEnv *get() const { - return mCallbackEnv; - } + JNIEnv* get() const { return mCallbackEnv; } private: - JNIEnv *mCallbackEnv; - const char *mName; + JNIEnv* mCallbackEnv; + const char* mName; - CallbackEnv(const CallbackEnv&) = delete; - void operator=(const CallbackEnv&) = delete; + CallbackEnv(const CallbackEnv&) = delete; + void operator=(const CallbackEnv&) = delete; }; const bt_interface_t* getBluetoothInterface(); @@ -166,23 +160,22 @@ int register_com_android_bluetooth_vc(JNIEnv* env); int register_com_android_bluetooth_csip_set_coordinator(JNIEnv* env); -int register_com_android_bluetooth_btservice_BluetoothQualityReport( - JNIEnv* env); +int register_com_android_bluetooth_btservice_BluetoothQualityReport(JNIEnv* env); struct JNIJavaMethod { - const char* name; - const char* signature; - jmethodID* id; - bool is_static{false}; + const char* name; + const char* signature; + jmethodID* id; + bool is_static{false}; }; -void jniGetMethodsOrDie(JNIEnv* env, const char* className, - const JNIJavaMethod* methods, int nMethods); +void jniGetMethodsOrDie(JNIEnv* env, const char* className, const JNIJavaMethod* methods, + int nMethods); #define REGISTER_NATIVE_METHODS(env, classname, methodsArray) \ - jniRegisterNativeMethods(env, classname, methodsArray, NELEM(methodsArray)) + jniRegisterNativeMethods(env, classname, methodsArray, NELEM(methodsArray)) #define GET_JAVA_METHODS(env, classname, methodsArray) \ - jniGetMethodsOrDie(env, classname, methodsArray, NELEM(methodsArray)) + jniGetMethodsOrDie(env, classname, methodsArray, NELEM(methodsArray)) } // namespace android diff --git a/android/app/jni/com_android_bluetooth_BluetoothQualityReport.cpp b/android/app/jni/com_android_bluetooth_BluetoothQualityReport.cpp index 4af4130c592..439375aa021 100644 --- a/android/app/jni/com_android_bluetooth_BluetoothQualityReport.cpp +++ b/android/app/jni/com_android_bluetooth_BluetoothQualityReport.cpp @@ -30,41 +30,43 @@ using bluetooth::bqr::BluetoothQualityReportInterface; namespace android { static jmethodID method_bqrDeliver; -static BluetoothQualityReportInterface* sBluetoothQualityReportInterface = - nullptr; +static BluetoothQualityReportInterface* sBluetoothQualityReportInterface = nullptr; static std::shared_timed_mutex interface_mutex; static jobject mCallbacksObj = nullptr; static std::shared_timed_mutex callbacks_mutex; -class BluetoothQualityReportCallbacksImpl - : public bluetooth::bqr::BluetoothQualityReportCallbacks { - public: +class BluetoothQualityReportCallbacksImpl : public bluetooth::bqr::BluetoothQualityReportCallbacks { +public: ~BluetoothQualityReportCallbacksImpl() = default; - void bqr_delivery_callback(const RawAddress bd_addr, uint8_t lmp_ver, - uint16_t lmp_subver, uint16_t manufacturer_id, - std::vector bqr_raw_data) override { + void bqr_delivery_callback(const RawAddress bd_addr, uint8_t lmp_ver, uint16_t lmp_subver, + uint16_t manufacturer_id, std::vector bqr_raw_data) override { log::info(""); std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid()) return; - if (method_bqrDeliver == NULL) return; - if (mCallbacksObj == nullptr) return; + if (!sCallbackEnv.valid()) { + return; + } + if (method_bqrDeliver == NULL) { + return; + } + if (mCallbacksObj == nullptr) { + return; + } - ScopedLocalRef addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); + ScopedLocalRef addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); if (!addr.get()) { log::error("Error while allocation byte array for addr"); return; } - sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), - (jbyte*)bd_addr.address); + sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), (jbyte*)bd_addr.address); - ScopedLocalRef raw_data( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(bqr_raw_data.size())); + ScopedLocalRef raw_data(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(bqr_raw_data.size())); if (!raw_data.get()) { log::error("Error while allocation byte array for bqr raw data"); return; @@ -72,9 +74,8 @@ class BluetoothQualityReportCallbacksImpl sCallbackEnv->SetByteArrayRegion(raw_data.get(), 0, bqr_raw_data.size(), (jbyte*)bqr_raw_data.data()); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_bqrDeliver, addr.get(), - (jint)lmp_ver, (jint)lmp_subver, - (jint)manufacturer_id, raw_data.get()); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_bqrDeliver, addr.get(), (jint)lmp_ver, + (jint)lmp_subver, (jint)manufacturer_id, raw_data.get()); } }; @@ -91,8 +92,7 @@ static void initNative(JNIEnv* env, jobject object) { } if (sBluetoothQualityReportInterface != nullptr) { - log::info( - "Cleaning up BluetoothQualityReport Interface before initializing..."); + log::info("Cleaning up BluetoothQualityReport Interface before initializing..."); sBluetoothQualityReportInterface = nullptr; } @@ -103,13 +103,12 @@ static void initNative(JNIEnv* env, jobject object) { } if ((mCallbacksObj = env->NewGlobalRef(object)) == nullptr) { - log::error( - "Failed to allocate Global Ref for BluetoothQualityReport Callbacks"); + log::error("Failed to allocate Global Ref for BluetoothQualityReport Callbacks"); return; } sBluetoothQualityReportInterface = - (BluetoothQualityReportInterface*)btInf->get_profile_interface(BT_BQR_ID); + (BluetoothQualityReportInterface*)btInf->get_profile_interface(BT_BQR_ID); if (sBluetoothQualityReportInterface == nullptr) { log::error("Failed to get BluetoothQualityReport Interface"); return; @@ -138,27 +137,22 @@ static void cleanupNative(JNIEnv* env, jobject /* object */) { } } -int register_com_android_bluetooth_btservice_BluetoothQualityReport( - JNIEnv* env) { +int register_com_android_bluetooth_btservice_BluetoothQualityReport(JNIEnv* env) { const JNINativeMethod methods[] = { - {"initNative", "()V", (void*)initNative}, - {"cleanupNative", "()V", (void*)cleanupNative}, + {"initNative", "()V", (void*)initNative}, + {"cleanupNative", "()V", (void*)cleanupNative}, }; const int result = REGISTER_NATIVE_METHODS( - env, - "com/android/bluetooth/btservice/BluetoothQualityReportNativeInterface", - methods); + env, "com/android/bluetooth/btservice/BluetoothQualityReportNativeInterface", methods); if (result != 0) { return result; } const JNIJavaMethod javaMethods[] = { - {"bqrDeliver", "([BIII[B)V", &method_bqrDeliver}, + {"bqrDeliver", "([BIII[B)V", &method_bqrDeliver}, }; - GET_JAVA_METHODS( - env, - "com/android/bluetooth/btservice/BluetoothQualityReportNativeInterface", - javaMethods); + GET_JAVA_METHODS(env, "com/android/bluetooth/btservice/BluetoothQualityReportNativeInterface", + javaMethods); return 0; } diff --git a/android/app/jni/com_android_bluetooth_a2dp.cpp b/android/app/jni/com_android_bluetooth_a2dp.cpp index 3d9af106ed9..5d0addec081 100644 --- a/android/app/jni/com_android_bluetooth_a2dp.cpp +++ b/android/app/jni/com_android_bluetooth_a2dp.cpp @@ -57,200 +57,191 @@ static void bta2dp_connection_state_callback(const RawAddress& bd_addr, std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) return; + if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) { + return; + } - ScopedLocalRef addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); + ScopedLocalRef addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); if (!addr.get()) { log::error("Fail to new jbyteArray bd addr"); return; } - sCallbackEnv->SetByteArrayRegion( - addr.get(), 0, sizeof(RawAddress), - reinterpret_cast(bd_addr.address)); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onConnectionStateChanged, - addr.get(), (jint)state); + sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), + reinterpret_cast(bd_addr.address)); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onConnectionStateChanged, addr.get(), + (jint)state); } -static void bta2dp_audio_state_callback(const RawAddress& bd_addr, - btav_audio_state_t state) { +static void bta2dp_audio_state_callback(const RawAddress& bd_addr, btav_audio_state_t state) { log::info("{}: state: {}", bd_addr, dump_av_audio_state(state)); std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) return; + if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) { + return; + } - ScopedLocalRef addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); + ScopedLocalRef addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); if (!addr.get()) { log::error("Fail to new jbyteArray bd addr"); return; } - sCallbackEnv->SetByteArrayRegion( - addr.get(), 0, sizeof(RawAddress), - reinterpret_cast(bd_addr.address)); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onAudioStateChanged, - addr.get(), (jint)state); + sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), + reinterpret_cast(bd_addr.address)); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onAudioStateChanged, addr.get(), (jint)state); } static void bta2dp_audio_config_callback( - const RawAddress& bd_addr, btav_a2dp_codec_config_t codec_config, - std::vector codecs_local_capabilities, - std::vector codecs_selectable_capabilities) { - log::info( - "{}: codec: {}, local codecs: {}, selectable codecs: {}", bd_addr, - codec_config.CodecNameStr(), - btav_a2dp_codec_config_t::PrintCodecs(codecs_local_capabilities), - btav_a2dp_codec_config_t::PrintCodecs(codecs_selectable_capabilities)); + const RawAddress& bd_addr, btav_a2dp_codec_config_t codec_config, + std::vector codecs_local_capabilities, + std::vector codecs_selectable_capabilities) { + log::info("{}: codec: {}, local codecs: {}, selectable codecs: {}", bd_addr, + codec_config.CodecNameStr(), + btav_a2dp_codec_config_t::PrintCodecs(codecs_local_capabilities), + btav_a2dp_codec_config_t::PrintCodecs(codecs_selectable_capabilities)); std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) return; + if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) { + return; + } jobject codecConfigObj = sCallbackEnv->NewObject( - android_bluetooth_BluetoothCodecConfig.clazz, - android_bluetooth_BluetoothCodecConfig.constructor, - (jint)codec_config.codec_type, (jint)codec_config.codec_priority, - (jint)codec_config.sample_rate, (jint)codec_config.bits_per_sample, - (jint)codec_config.channel_mode, (jlong)codec_config.codec_specific_1, - (jlong)codec_config.codec_specific_2, - (jlong)codec_config.codec_specific_3, - (jlong)codec_config.codec_specific_4); + android_bluetooth_BluetoothCodecConfig.clazz, + android_bluetooth_BluetoothCodecConfig.constructor, (jint)codec_config.codec_type, + (jint)codec_config.codec_priority, (jint)codec_config.sample_rate, + (jint)codec_config.bits_per_sample, (jint)codec_config.channel_mode, + (jlong)codec_config.codec_specific_1, (jlong)codec_config.codec_specific_2, + (jlong)codec_config.codec_specific_3, (jlong)codec_config.codec_specific_4); jsize i = 0; - jobjectArray local_capabilities_array = sCallbackEnv->NewObjectArray( - (jsize)codecs_local_capabilities.size(), - android_bluetooth_BluetoothCodecConfig.clazz, nullptr); + jobjectArray local_capabilities_array = + sCallbackEnv->NewObjectArray((jsize)codecs_local_capabilities.size(), + android_bluetooth_BluetoothCodecConfig.clazz, nullptr); for (auto const& cap : codecs_local_capabilities) { jobject capObj = sCallbackEnv->NewObject( - android_bluetooth_BluetoothCodecConfig.clazz, - android_bluetooth_BluetoothCodecConfig.constructor, - (jint)cap.codec_type, (jint)cap.codec_priority, (jint)cap.sample_rate, - (jint)cap.bits_per_sample, (jint)cap.channel_mode, - (jlong)cap.codec_specific_1, (jlong)cap.codec_specific_2, - (jlong)cap.codec_specific_3, (jlong)cap.codec_specific_4); + android_bluetooth_BluetoothCodecConfig.clazz, + android_bluetooth_BluetoothCodecConfig.constructor, (jint)cap.codec_type, + (jint)cap.codec_priority, (jint)cap.sample_rate, (jint)cap.bits_per_sample, + (jint)cap.channel_mode, (jlong)cap.codec_specific_1, (jlong)cap.codec_specific_2, + (jlong)cap.codec_specific_3, (jlong)cap.codec_specific_4); sCallbackEnv->SetObjectArrayElement(local_capabilities_array, i++, capObj); sCallbackEnv->DeleteLocalRef(capObj); } i = 0; - jobjectArray selectable_capabilities_array = sCallbackEnv->NewObjectArray( - (jsize)codecs_selectable_capabilities.size(), - android_bluetooth_BluetoothCodecConfig.clazz, nullptr); + jobjectArray selectable_capabilities_array = + sCallbackEnv->NewObjectArray((jsize)codecs_selectable_capabilities.size(), + android_bluetooth_BluetoothCodecConfig.clazz, nullptr); for (auto const& cap : codecs_selectable_capabilities) { jobject capObj = sCallbackEnv->NewObject( - android_bluetooth_BluetoothCodecConfig.clazz, - android_bluetooth_BluetoothCodecConfig.constructor, - (jint)cap.codec_type, (jint)cap.codec_priority, (jint)cap.sample_rate, - (jint)cap.bits_per_sample, (jint)cap.channel_mode, - (jlong)cap.codec_specific_1, (jlong)cap.codec_specific_2, - (jlong)cap.codec_specific_3, (jlong)cap.codec_specific_4); - sCallbackEnv->SetObjectArrayElement(selectable_capabilities_array, i++, - capObj); + android_bluetooth_BluetoothCodecConfig.clazz, + android_bluetooth_BluetoothCodecConfig.constructor, (jint)cap.codec_type, + (jint)cap.codec_priority, (jint)cap.sample_rate, (jint)cap.bits_per_sample, + (jint)cap.channel_mode, (jlong)cap.codec_specific_1, (jlong)cap.codec_specific_2, + (jlong)cap.codec_specific_3, (jlong)cap.codec_specific_4); + sCallbackEnv->SetObjectArrayElement(selectable_capabilities_array, i++, capObj); sCallbackEnv->DeleteLocalRef(capObj); } - ScopedLocalRef addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(RawAddress::kLength)); + ScopedLocalRef addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(RawAddress::kLength)); if (!addr.get()) { log::error("Fail to new jbyteArray bd addr"); return; } - sCallbackEnv->SetByteArrayRegion( - addr.get(), 0, RawAddress::kLength, - reinterpret_cast(bd_addr.address)); + sCallbackEnv->SetByteArrayRegion(addr.get(), 0, RawAddress::kLength, + reinterpret_cast(bd_addr.address)); - sCallbackEnv->CallVoidMethod( - mCallbacksObj, method_onCodecConfigChanged, addr.get(), codecConfigObj, - local_capabilities_array, selectable_capabilities_array); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onCodecConfigChanged, addr.get(), + codecConfigObj, local_capabilities_array, + selectable_capabilities_array); } -static bool bta2dp_mandatory_codec_preferred_callback( - const RawAddress& bd_addr) { +static bool bta2dp_mandatory_codec_preferred_callback(const RawAddress& bd_addr) { log::info("{}", bd_addr); std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) return false; + if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) { + return false; + } - ScopedLocalRef addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(RawAddress::kLength)); + ScopedLocalRef addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(RawAddress::kLength)); if (!addr.get()) { log::error("Fail to new jbyteArray bd addr"); return false; } - sCallbackEnv->SetByteArrayRegion( - addr.get(), 0, RawAddress::kLength, - reinterpret_cast(bd_addr.address)); - return sCallbackEnv->CallBooleanMethod( - mCallbacksObj, method_isMandatoryCodecPreferred, addr.get()); + sCallbackEnv->SetByteArrayRegion(addr.get(), 0, RawAddress::kLength, + reinterpret_cast(bd_addr.address)); + return sCallbackEnv->CallBooleanMethod(mCallbacksObj, method_isMandatoryCodecPreferred, + addr.get()); } static btav_source_callbacks_t sBluetoothA2dpCallbacks = { - sizeof(sBluetoothA2dpCallbacks), - bta2dp_connection_state_callback, - bta2dp_audio_state_callback, - bta2dp_audio_config_callback, - bta2dp_mandatory_codec_preferred_callback, + sizeof(sBluetoothA2dpCallbacks), + bta2dp_connection_state_callback, + bta2dp_audio_state_callback, + bta2dp_audio_config_callback, + bta2dp_mandatory_codec_preferred_callback, }; static std::vector prepareCodecPreferences( - JNIEnv* env, jobject /* object */, jobjectArray codecConfigArray) { + JNIEnv* env, jobject /* object */, jobjectArray codecConfigArray) { std::vector codec_preferences; int numConfigs = env->GetArrayLength(codecConfigArray); for (int i = 0; i < numConfigs; i++) { jobject jcodecConfig = env->GetObjectArrayElement(codecConfigArray, i); - if (jcodecConfig == nullptr) continue; - if (!env->IsInstanceOf(jcodecConfig, - android_bluetooth_BluetoothCodecConfig.clazz)) { + if (jcodecConfig == nullptr) { + continue; + } + if (!env->IsInstanceOf(jcodecConfig, android_bluetooth_BluetoothCodecConfig.clazz)) { log::error("Invalid BluetoothCodecConfig instance"); continue; } - jint codecType = env->CallIntMethod( - jcodecConfig, android_bluetooth_BluetoothCodecConfig.getCodecType); + jint codecType = + env->CallIntMethod(jcodecConfig, android_bluetooth_BluetoothCodecConfig.getCodecType); jint codecPriority = env->CallIntMethod( - jcodecConfig, android_bluetooth_BluetoothCodecConfig.getCodecPriority); - jint sampleRate = env->CallIntMethod( - jcodecConfig, android_bluetooth_BluetoothCodecConfig.getSampleRate); + jcodecConfig, android_bluetooth_BluetoothCodecConfig.getCodecPriority); + jint sampleRate = + env->CallIntMethod(jcodecConfig, android_bluetooth_BluetoothCodecConfig.getSampleRate); jint bitsPerSample = env->CallIntMethod( - jcodecConfig, android_bluetooth_BluetoothCodecConfig.getBitsPerSample); - jint channelMode = env->CallIntMethod( - jcodecConfig, android_bluetooth_BluetoothCodecConfig.getChannelMode); + jcodecConfig, android_bluetooth_BluetoothCodecConfig.getBitsPerSample); + jint channelMode = + env->CallIntMethod(jcodecConfig, android_bluetooth_BluetoothCodecConfig.getChannelMode); jlong codecSpecific1 = env->CallLongMethod( - jcodecConfig, android_bluetooth_BluetoothCodecConfig.getCodecSpecific1); + jcodecConfig, android_bluetooth_BluetoothCodecConfig.getCodecSpecific1); jlong codecSpecific2 = env->CallLongMethod( - jcodecConfig, android_bluetooth_BluetoothCodecConfig.getCodecSpecific2); + jcodecConfig, android_bluetooth_BluetoothCodecConfig.getCodecSpecific2); jlong codecSpecific3 = env->CallLongMethod( - jcodecConfig, android_bluetooth_BluetoothCodecConfig.getCodecSpecific3); + jcodecConfig, android_bluetooth_BluetoothCodecConfig.getCodecSpecific3); jlong codecSpecific4 = env->CallLongMethod( - jcodecConfig, android_bluetooth_BluetoothCodecConfig.getCodecSpecific4); + jcodecConfig, android_bluetooth_BluetoothCodecConfig.getCodecSpecific4); btav_a2dp_codec_config_t codec_config = { - .codec_type = static_cast(codecType), - .codec_priority = - static_cast(codecPriority), - .sample_rate = static_cast(sampleRate), - .bits_per_sample = - static_cast(bitsPerSample), - .channel_mode = - static_cast(channelMode), - .codec_specific_1 = codecSpecific1, - .codec_specific_2 = codecSpecific2, - .codec_specific_3 = codecSpecific3, - .codec_specific_4 = codecSpecific4}; + .codec_type = static_cast(codecType), + .codec_priority = static_cast(codecPriority), + .sample_rate = static_cast(sampleRate), + .bits_per_sample = static_cast(bitsPerSample), + .channel_mode = static_cast(channelMode), + .codec_specific_1 = codecSpecific1, + .codec_specific_2 = codecSpecific2, + .codec_specific_3 = codecSpecific3, + .codec_specific_4 = codecSpecific4}; codec_preferences.push_back(codec_config); } return codec_preferences; } -static void initNative(JNIEnv* env, jobject object, - jint maxConnectedAudioDevices, - jobjectArray codecConfigArray, - jobjectArray codecOffloadingArray) { +static void initNative(JNIEnv* env, jobject object, jint maxConnectedAudioDevices, + jobjectArray codecConfigArray, jobjectArray codecOffloadingArray) { std::unique_lock interface_lock(interface_mutex); std::unique_lock callbacks_lock(callbacks_mutex); @@ -274,25 +265,23 @@ static void initNative(JNIEnv* env, jobject object, return; } - android_bluetooth_BluetoothCodecConfig.clazz = (jclass)env->NewGlobalRef( - env->FindClass("android/bluetooth/BluetoothCodecConfig")); + android_bluetooth_BluetoothCodecConfig.clazz = + (jclass)env->NewGlobalRef(env->FindClass("android/bluetooth/BluetoothCodecConfig")); if (android_bluetooth_BluetoothCodecConfig.clazz == nullptr) { log::error("Failed to allocate Global Ref for BluetoothCodecConfig class"); return; } std::vector codec_priorities = - prepareCodecPreferences(env, object, codecConfigArray); + prepareCodecPreferences(env, object, codecConfigArray); std::vector codec_offloading = - prepareCodecPreferences(env, object, codecOffloadingArray); + prepareCodecPreferences(env, object, codecOffloadingArray); - bt_status_t status = btif_av_source_init( - &sBluetoothA2dpCallbacks, maxConnectedAudioDevices, codec_priorities, - codec_offloading, &supported_codecs); + bt_status_t status = btif_av_source_init(&sBluetoothA2dpCallbacks, maxConnectedAudioDevices, + codec_priorities, codec_offloading, &supported_codecs); if (status != BT_STATUS_SUCCESS) { - log::error("Failed to initialize Bluetooth A2DP, status: {}", - bt_status_text(status)); + log::error("Failed to initialize Bluetooth A2DP, status: {}", bt_status_text(status)); return; } } @@ -319,24 +308,23 @@ static void cleanupNative(JNIEnv* env, jobject /* object */) { } static jobjectArray getSupportedCodecTypesNative(JNIEnv* env) { - jclass android_bluetooth_BluetoothCodecType_clazz = (jclass)env->NewGlobalRef( - env->FindClass("android/bluetooth/BluetoothCodecType")); + jclass android_bluetooth_BluetoothCodecType_clazz = + (jclass)env->NewGlobalRef(env->FindClass("android/bluetooth/BluetoothCodecType")); if (android_bluetooth_BluetoothCodecType_clazz == nullptr) { log::error("Failed to allocate Global Ref for BluetoothCodecType class"); return nullptr; } - jmethodID init = env->GetMethodID(android_bluetooth_BluetoothCodecType_clazz, - "", "(IJLjava/lang/String;)V"); + jmethodID init = env->GetMethodID(android_bluetooth_BluetoothCodecType_clazz, "", + "(IJLjava/lang/String;)V"); if (init == nullptr) { log::error("Failed to find method of BluetoothCodecType class"); return nullptr; } - jobjectArray result = - env->NewObjectArray(supported_codecs.size(), - android_bluetooth_BluetoothCodecType_clazz, nullptr); + jobjectArray result = env->NewObjectArray(supported_codecs.size(), + android_bluetooth_BluetoothCodecType_clazz, nullptr); if (result == nullptr) { log::error("Failed to allocate result array of BluetoothCodecType"); @@ -345,18 +333,16 @@ static jobjectArray getSupportedCodecTypesNative(JNIEnv* env) { for (size_t index = 0; index < supported_codecs.size(); index++) { jobject codec_type = env->NewObject( - android_bluetooth_BluetoothCodecType_clazz, init, - (jint)supported_codecs[index].codec_type, - (jlong)supported_codecs[index].codec_id, - env->NewStringUTF(supported_codecs[index].codec_name.c_str())); + android_bluetooth_BluetoothCodecType_clazz, init, + (jint)supported_codecs[index].codec_type, (jlong)supported_codecs[index].codec_id, + env->NewStringUTF(supported_codecs[index].codec_name.c_str())); env->SetObjectArrayElement(result, index, codec_type); } return result; } -static jboolean connectA2dpNative(JNIEnv* env, jobject /* object */, - jbyteArray address) { +static jboolean connectA2dpNative(JNIEnv* env, jobject /* object */, jbyteArray address) { std::shared_lock lock(interface_mutex); jbyte* addr = env->GetByteArrayElements(address, nullptr); if (!addr) { @@ -376,8 +362,7 @@ static jboolean connectA2dpNative(JNIEnv* env, jobject /* object */, return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } -static jboolean disconnectA2dpNative(JNIEnv* env, jobject /* object */, - jbyteArray address) { +static jboolean disconnectA2dpNative(JNIEnv* env, jobject /* object */, jbyteArray address) { std::shared_lock lock(interface_mutex); jbyte* addr = env->GetByteArrayElements(address, nullptr); if (!addr) { @@ -397,8 +382,8 @@ static jboolean disconnectA2dpNative(JNIEnv* env, jobject /* object */, return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } -static jboolean setSilenceDeviceNative(JNIEnv* env, jobject /* object */, - jbyteArray address, jboolean silence) { +static jboolean setSilenceDeviceNative(JNIEnv* env, jobject /* object */, jbyteArray address, + jboolean silence) { std::shared_lock lock(interface_mutex); jbyte* addr = env->GetByteArrayElements(address, nullptr); @@ -413,15 +398,13 @@ static jboolean setSilenceDeviceNative(JNIEnv* env, jobject /* object */, log::info("{}: silence={}", bd_addr, silence); bt_status_t status = btif_av_source_set_silence_device(bd_addr, silence); if (status != BT_STATUS_SUCCESS) { - log::error("Failed A2DP set_silence_device, status: {}", - bt_status_text(status)); + log::error("Failed A2DP set_silence_device, status: {}", bt_status_text(status)); } env->ReleaseByteArrayElements(address, addr, 0); return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } -static jboolean setActiveDeviceNative(JNIEnv* env, jobject /* object */, - jbyteArray address) { +static jboolean setActiveDeviceNative(JNIEnv* env, jobject /* object */, jbyteArray address) { std::shared_lock lock(interface_mutex); jbyte* addr = env->GetByteArrayElements(address, nullptr); @@ -433,15 +416,13 @@ static jboolean setActiveDeviceNative(JNIEnv* env, jobject /* object */, log::info("{}", bd_addr); bt_status_t status = btif_av_source_set_active_device(bd_addr); if (status != BT_STATUS_SUCCESS) { - log::error("Failed A2DP set_active_device, status: {}", - bt_status_text(status)); + log::error("Failed A2DP set_active_device, status: {}", bt_status_text(status)); } env->ReleaseByteArrayElements(address, addr, 0); return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } -static jboolean setCodecConfigPreferenceNative(JNIEnv* env, jobject object, - jbyteArray address, +static jboolean setCodecConfigPreferenceNative(JNIEnv* env, jobject object, jbyteArray address, jobjectArray codecConfigArray) { std::shared_lock lock(interface_mutex); jbyte* addr = env->GetByteArrayElements(address, nullptr); @@ -453,14 +434,11 @@ static jboolean setCodecConfigPreferenceNative(JNIEnv* env, jobject object, RawAddress bd_addr; bd_addr.FromOctets(reinterpret_cast(addr)); std::vector codec_preferences = - prepareCodecPreferences(env, object, codecConfigArray); - log::info("{}: {}", bd_addr, - btav_a2dp_codec_config_t::PrintCodecs(codec_preferences)); - bt_status_t status = - btif_av_source_set_codec_config_preference(bd_addr, codec_preferences); + prepareCodecPreferences(env, object, codecConfigArray); + log::info("{}: {}", bd_addr, btav_a2dp_codec_config_t::PrintCodecs(codec_preferences)); + bt_status_t status = btif_av_source_set_codec_config_preference(bd_addr, codec_preferences); if (status != BT_STATUS_SUCCESS) { - log::error("Failed codec configuration, status: {}", - bt_status_text(status)); + log::error("Failed codec configuration, status: {}", bt_status_text(status)); } env->ReleaseByteArrayElements(address, addr, 0); return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; @@ -468,66 +446,52 @@ static jboolean setCodecConfigPreferenceNative(JNIEnv* env, jobject object, int register_com_android_bluetooth_a2dp(JNIEnv* env) { const JNINativeMethod methods[] = { - {"initNative", - "(I[Landroid/bluetooth/BluetoothCodecConfig;" - "[Landroid/bluetooth/BluetoothCodecConfig;)V", - (void*)initNative}, - {"cleanupNative", "()V", (void*)cleanupNative}, - {"getSupportedCodecTypesNative", - "()[Landroid/bluetooth/BluetoothCodecType;", - (void*)getSupportedCodecTypesNative}, - {"connectA2dpNative", "([B)Z", (void*)connectA2dpNative}, - {"disconnectA2dpNative", "([B)Z", (void*)disconnectA2dpNative}, - {"setSilenceDeviceNative", "([BZ)Z", (void*)setSilenceDeviceNative}, - {"setActiveDeviceNative", "([B)Z", (void*)setActiveDeviceNative}, - {"setCodecConfigPreferenceNative", - "([B[Landroid/bluetooth/BluetoothCodecConfig;)Z", - (void*)setCodecConfigPreferenceNative}, + {"initNative", + "(I[Landroid/bluetooth/BluetoothCodecConfig;" + "[Landroid/bluetooth/BluetoothCodecConfig;)V", + (void*)initNative}, + {"cleanupNative", "()V", (void*)cleanupNative}, + {"getSupportedCodecTypesNative", "()[Landroid/bluetooth/BluetoothCodecType;", + (void*)getSupportedCodecTypesNative}, + {"connectA2dpNative", "([B)Z", (void*)connectA2dpNative}, + {"disconnectA2dpNative", "([B)Z", (void*)disconnectA2dpNative}, + {"setSilenceDeviceNative", "([BZ)Z", (void*)setSilenceDeviceNative}, + {"setActiveDeviceNative", "([B)Z", (void*)setActiveDeviceNative}, + {"setCodecConfigPreferenceNative", "([B[Landroid/bluetooth/BluetoothCodecConfig;)Z", + (void*)setCodecConfigPreferenceNative}, }; - const int result = REGISTER_NATIVE_METHODS( - env, "com/android/bluetooth/a2dp/A2dpNativeInterface", methods); + const int result = + REGISTER_NATIVE_METHODS(env, "com/android/bluetooth/a2dp/A2dpNativeInterface", methods); if (result != 0) { return result; } const JNIJavaMethod javaMethods[] = { - {"onConnectionStateChanged", "([BI)V", &method_onConnectionStateChanged}, - {"onAudioStateChanged", "([BI)V", &method_onAudioStateChanged}, - {"onCodecConfigChanged", - "([BLandroid/bluetooth/BluetoothCodecConfig;" - "[Landroid/bluetooth/BluetoothCodecConfig;" - "[Landroid/bluetooth/BluetoothCodecConfig;)V", - &method_onCodecConfigChanged}, - {"isMandatoryCodecPreferred", "([B)Z", &method_isMandatoryCodecPreferred}, + {"onConnectionStateChanged", "([BI)V", &method_onConnectionStateChanged}, + {"onAudioStateChanged", "([BI)V", &method_onAudioStateChanged}, + {"onCodecConfigChanged", + "([BLandroid/bluetooth/BluetoothCodecConfig;" + "[Landroid/bluetooth/BluetoothCodecConfig;" + "[Landroid/bluetooth/BluetoothCodecConfig;)V", + &method_onCodecConfigChanged}, + {"isMandatoryCodecPreferred", "([B)Z", &method_isMandatoryCodecPreferred}, }; - GET_JAVA_METHODS(env, "com/android/bluetooth/a2dp/A2dpNativeInterface", - javaMethods); + GET_JAVA_METHODS(env, "com/android/bluetooth/a2dp/A2dpNativeInterface", javaMethods); const JNIJavaMethod codecConfigCallbacksMethods[] = { - {"", "(IIIIIJJJJ)V", - &android_bluetooth_BluetoothCodecConfig.constructor}, - {"getCodecType", "()I", - &android_bluetooth_BluetoothCodecConfig.getCodecType}, - {"getCodecPriority", "()I", - &android_bluetooth_BluetoothCodecConfig.getCodecPriority}, - {"getSampleRate", "()I", - &android_bluetooth_BluetoothCodecConfig.getSampleRate}, - {"getBitsPerSample", "()I", - &android_bluetooth_BluetoothCodecConfig.getBitsPerSample}, - {"getChannelMode", "()I", - &android_bluetooth_BluetoothCodecConfig.getChannelMode}, - {"getCodecSpecific1", "()J", - &android_bluetooth_BluetoothCodecConfig.getCodecSpecific1}, - {"getCodecSpecific2", "()J", - &android_bluetooth_BluetoothCodecConfig.getCodecSpecific2}, - {"getCodecSpecific3", "()J", - &android_bluetooth_BluetoothCodecConfig.getCodecSpecific3}, - {"getCodecSpecific4", "()J", - &android_bluetooth_BluetoothCodecConfig.getCodecSpecific4}, + {"", "(IIIIIJJJJ)V", &android_bluetooth_BluetoothCodecConfig.constructor}, + {"getCodecType", "()I", &android_bluetooth_BluetoothCodecConfig.getCodecType}, + {"getCodecPriority", "()I", &android_bluetooth_BluetoothCodecConfig.getCodecPriority}, + {"getSampleRate", "()I", &android_bluetooth_BluetoothCodecConfig.getSampleRate}, + {"getBitsPerSample", "()I", &android_bluetooth_BluetoothCodecConfig.getBitsPerSample}, + {"getChannelMode", "()I", &android_bluetooth_BluetoothCodecConfig.getChannelMode}, + {"getCodecSpecific1", "()J", &android_bluetooth_BluetoothCodecConfig.getCodecSpecific1}, + {"getCodecSpecific2", "()J", &android_bluetooth_BluetoothCodecConfig.getCodecSpecific2}, + {"getCodecSpecific3", "()J", &android_bluetooth_BluetoothCodecConfig.getCodecSpecific3}, + {"getCodecSpecific4", "()J", &android_bluetooth_BluetoothCodecConfig.getCodecSpecific4}, }; - GET_JAVA_METHODS(env, "android/bluetooth/BluetoothCodecConfig", - codecConfigCallbacksMethods); + GET_JAVA_METHODS(env, "android/bluetooth/BluetoothCodecConfig", codecConfigCallbacksMethods); return 0; } -} +} // namespace android diff --git a/android/app/jni/com_android_bluetooth_a2dp_sink.cpp b/android/app/jni/com_android_bluetooth_a2dp_sink.cpp index 76f2a4c40db..5b883b3498b 100644 --- a/android/app/jni/com_android_bluetooth_a2dp_sink.cpp +++ b/android/app/jni/com_android_bluetooth_a2dp_sink.cpp @@ -34,18 +34,22 @@ static jmethodID method_onAudioConfigChanged; static jobject mCallbacksObj = NULL; static std::shared_timed_mutex callbacks_mutex; -static void a2dp_sink_connection_state_callback( - const RawAddress& bd_addr, btav_connection_state_t state, - const btav_error_t& /* error */) { +static void a2dp_sink_connection_state_callback(const RawAddress& bd_addr, + btav_connection_state_t state, + const btav_error_t& /* error */) { log::info(""); std::shared_lock lock(callbacks_mutex); - if (!mCallbacksObj) return; + if (!mCallbacksObj) { + return; + } CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid()) return; + if (!sCallbackEnv.valid()) { + return; + } - ScopedLocalRef addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); + ScopedLocalRef addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); if (!addr.get()) { log::error("Fail to new jbyteArray bd addr for connection state"); return; @@ -53,21 +57,24 @@ static void a2dp_sink_connection_state_callback( sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), (const jbyte*)bd_addr.address); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onConnectionStateChanged, - addr.get(), (jint)state); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onConnectionStateChanged, addr.get(), + (jint)state); } -static void a2dp_sink_audio_state_callback(const RawAddress& bd_addr, - btav_audio_state_t state) { +static void a2dp_sink_audio_state_callback(const RawAddress& bd_addr, btav_audio_state_t state) { log::info(""); std::shared_lock lock(callbacks_mutex); - if (!mCallbacksObj) return; + if (!mCallbacksObj) { + return; + } CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid()) return; + if (!sCallbackEnv.valid()) { + return; + } - ScopedLocalRef addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); + ScopedLocalRef addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); if (!addr.get()) { log::error("Fail to new jbyteArray bd addr for connection state"); return; @@ -75,22 +82,24 @@ static void a2dp_sink_audio_state_callback(const RawAddress& bd_addr, sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), (const jbyte*)bd_addr.address); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onAudioStateChanged, - addr.get(), (jint)state); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onAudioStateChanged, addr.get(), (jint)state); } -static void a2dp_sink_audio_config_callback(const RawAddress& bd_addr, - uint32_t sample_rate, +static void a2dp_sink_audio_config_callback(const RawAddress& bd_addr, uint32_t sample_rate, uint8_t channel_count) { log::info(""); std::shared_lock lock(callbacks_mutex); - if (!mCallbacksObj) return; + if (!mCallbacksObj) { + return; + } CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid()) return; + if (!sCallbackEnv.valid()) { + return; + } - ScopedLocalRef addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); + ScopedLocalRef addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); if (!addr.get()) { log::error("Fail to new jbyteArray bd addr for connection state"); return; @@ -98,20 +107,18 @@ static void a2dp_sink_audio_config_callback(const RawAddress& bd_addr, sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), (const jbyte*)bd_addr.address); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onAudioConfigChanged, - addr.get(), (jint)sample_rate, - (jint)channel_count); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onAudioConfigChanged, addr.get(), + (jint)sample_rate, (jint)channel_count); } static btav_sink_callbacks_t sBluetoothA2dpCallbacks = { - sizeof(sBluetoothA2dpCallbacks), - a2dp_sink_connection_state_callback, - a2dp_sink_audio_state_callback, - a2dp_sink_audio_config_callback, + sizeof(sBluetoothA2dpCallbacks), + a2dp_sink_connection_state_callback, + a2dp_sink_audio_state_callback, + a2dp_sink_audio_config_callback, }; -static void initNative(JNIEnv* env, jobject object, - jint maxConnectedAudioDevices) { +static void initNative(JNIEnv* env, jobject object, jint maxConnectedAudioDevices) { std::unique_lock lock(callbacks_mutex); const bt_interface_t* btInf = getBluetoothInterface(); @@ -128,11 +135,9 @@ static void initNative(JNIEnv* env, jobject object, mCallbacksObj = NULL; } - bt_status_t status = - btif_av_sink_init(&sBluetoothA2dpCallbacks, maxConnectedAudioDevices); + bt_status_t status = btif_av_sink_init(&sBluetoothA2dpCallbacks, maxConnectedAudioDevices); if (status != BT_STATUS_SUCCESS) { - log::error("Failed to initialize Bluetooth A2DP Sink, status: {}", - bt_status_text(status)); + log::error("Failed to initialize Bluetooth A2DP Sink, status: {}", bt_status_text(status)); return; } @@ -156,8 +161,7 @@ static void cleanupNative(JNIEnv* env, jobject /* object */) { } } -static jboolean connectA2dpNative(JNIEnv* env, jobject /* object */, - jbyteArray address) { +static jboolean connectA2dpNative(JNIEnv* env, jobject /* object */, jbyteArray address) { jbyte* addr = env->GetByteArrayElements(address, NULL); if (!addr) { jniThrowIOException(env, EINVAL); @@ -177,8 +181,7 @@ static jboolean connectA2dpNative(JNIEnv* env, jobject /* object */, return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } -static jboolean disconnectA2dpNative(JNIEnv* env, jobject /* object */, - jbyteArray address) { +static jboolean disconnectA2dpNative(JNIEnv* env, jobject /* object */, jbyteArray address) { jbyte* addr = env->GetByteArrayElements(address, NULL); if (!addr) { jniThrowIOException(env, EINVAL); @@ -198,18 +201,15 @@ static jboolean disconnectA2dpNative(JNIEnv* env, jobject /* object */, return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } -static void informAudioFocusStateNative(JNIEnv* /* env */, jobject /* object */, - jint focus_state) { +static void informAudioFocusStateNative(JNIEnv* /* env */, jobject /* object */, jint focus_state) { btif_av_sink_set_audio_focus_state((uint8_t)focus_state); } -static void informAudioTrackGainNative(JNIEnv* /* env */, jobject /* object */, - jfloat gain) { +static void informAudioTrackGainNative(JNIEnv* /* env */, jobject /* object */, jfloat gain) { btif_av_sink_set_audio_track_gain((float)gain); } -static jboolean setActiveDeviceNative(JNIEnv* env, jobject /* object */, - jbyteArray address) { +static jboolean setActiveDeviceNative(JNIEnv* env, jobject /* object */, jbyteArray address) { jbyte* addr = env->GetByteArrayElements(address, NULL); if (!addr) { jniThrowIOException(env, EINVAL); @@ -222,8 +222,7 @@ static jboolean setActiveDeviceNative(JNIEnv* env, jobject /* object */, log::info("{}", rawAddress); bt_status_t status = btif_av_sink_set_active_device(rawAddress); if (status != BT_STATUS_SUCCESS) { - log::error("Failed sending passthru command, status: {}", - bt_status_text(status)); + log::error("Failed sending passthru command, status: {}", bt_status_text(status)); } env->ReleaseByteArrayElements(address, addr, 0); @@ -232,30 +231,27 @@ static jboolean setActiveDeviceNative(JNIEnv* env, jobject /* object */, int register_com_android_bluetooth_a2dp_sink(JNIEnv* env) { const JNINativeMethod methods[] = { - {"initNative", "(I)V", (void*)initNative}, - {"cleanupNative", "()V", (void*)cleanupNative}, - {"connectA2dpNative", "([B)Z", (void*)connectA2dpNative}, - {"disconnectA2dpNative", "([B)Z", (void*)disconnectA2dpNative}, - {"informAudioFocusStateNative", "(I)V", - (void*)informAudioFocusStateNative}, - {"informAudioTrackGainNative", "(F)V", (void*)informAudioTrackGainNative}, - {"setActiveDeviceNative", "([B)Z", (void*)setActiveDeviceNative}, + {"initNative", "(I)V", (void*)initNative}, + {"cleanupNative", "()V", (void*)cleanupNative}, + {"connectA2dpNative", "([B)Z", (void*)connectA2dpNative}, + {"disconnectA2dpNative", "([B)Z", (void*)disconnectA2dpNative}, + {"informAudioFocusStateNative", "(I)V", (void*)informAudioFocusStateNative}, + {"informAudioTrackGainNative", "(F)V", (void*)informAudioTrackGainNative}, + {"setActiveDeviceNative", "([B)Z", (void*)setActiveDeviceNative}, }; const int result = REGISTER_NATIVE_METHODS( - env, "com/android/bluetooth/a2dpsink/A2dpSinkNativeInterface", methods); + env, "com/android/bluetooth/a2dpsink/A2dpSinkNativeInterface", methods); if (result != 0) { return result; } const JNIJavaMethod javaMethods[] = { - {"onConnectionStateChanged", "([BI)V", &method_onConnectionStateChanged}, - {"onAudioStateChanged", "([BI)V", &method_onAudioStateChanged}, - {"onAudioConfigChanged", "([BII)V", &method_onAudioConfigChanged}, + {"onConnectionStateChanged", "([BI)V", &method_onConnectionStateChanged}, + {"onAudioStateChanged", "([BI)V", &method_onAudioStateChanged}, + {"onAudioConfigChanged", "([BII)V", &method_onAudioConfigChanged}, }; - GET_JAVA_METHODS(env, - "com/android/bluetooth/a2dpsink/A2dpSinkNativeInterface", - javaMethods); + GET_JAVA_METHODS(env, "com/android/bluetooth/a2dpsink/A2dpSinkNativeInterface", javaMethods); return 0; } -} +} // namespace android diff --git a/android/app/jni/com_android_bluetooth_avrcp_controller.cpp b/android/app/jni/com_android_bluetooth_avrcp_controller.cpp index 57a80bb87de..0d29848e819 100644 --- a/android/app/jni/com_android_bluetooth_avrcp_controller.cpp +++ b/android/app/jni/com_android_bluetooth_avrcp_controller.cpp @@ -53,8 +53,8 @@ static const btrc_ctrl_interface_t* sBluetoothAvrcpInterface = NULL; static jobject sCallbacksObj = NULL; static std::shared_timed_mutex sCallbacks_mutex; -static void btavrcp_passthrough_response_callback( - const RawAddress& /* bd_addr */, int id, int pressed) { +static void btavrcp_passthrough_response_callback(const RawAddress& /* bd_addr */, int id, + int pressed) { log::verbose("id: {}, pressed: {} --- Not implemented", id, pressed); } @@ -67,56 +67,56 @@ static void btavrcp_connection_state_callback(bool rc_connect, bool br_connect, log::info("conn state: rc: {} br: {}", rc_connect, br_connect); std::shared_lock lock(sCallbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid()) return; + if (!sCallbackEnv.valid()) { + return; + } if (!sCallbacksObj) { log::error("sCallbacksObj is null"); return; } - ScopedLocalRef addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); + ScopedLocalRef addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); if (!addr.get()) { log::error("Failed to allocate a new byte array"); return; } - sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), - (jbyte*)bd_addr.address); - sCallbackEnv->CallVoidMethod(sCallbacksObj, method_onConnectionStateChanged, - (jboolean)rc_connect, (jboolean)br_connect, - addr.get()); + sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), (jbyte*)bd_addr.address); + sCallbackEnv->CallVoidMethod(sCallbacksObj, method_onConnectionStateChanged, (jboolean)rc_connect, + (jboolean)br_connect, addr.get()); } -static void btavrcp_get_rcfeatures_callback(const RawAddress& /* bd_addr */, - int /* features */) { +static void btavrcp_get_rcfeatures_callback(const RawAddress& /* bd_addr */, int /* features */) { log::verbose("--- Not implemented"); } -static void btavrcp_setplayerapplicationsetting_rsp_callback( - const RawAddress& /* bd_addr */, uint8_t /* accepted */) { +static void btavrcp_setplayerapplicationsetting_rsp_callback(const RawAddress& /* bd_addr */, + uint8_t /* accepted */) { log::verbose("--- Not implemented"); } -static void btavrcp_playerapplicationsetting_callback( - const RawAddress& bd_addr, uint8_t num_attr, - btrc_player_app_attr_t* app_attrs, uint8_t /* num_ext_attr */, - btrc_player_app_ext_attr_t* /* ext_attrs */) { +static void btavrcp_playerapplicationsetting_callback(const RawAddress& bd_addr, uint8_t num_attr, + btrc_player_app_attr_t* app_attrs, + uint8_t /* num_ext_attr */, + btrc_player_app_ext_attr_t* /* ext_attrs */) { log::info(""); std::shared_lock lock(sCallbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid()) return; + if (!sCallbackEnv.valid()) { + return; + } if (!sCallbacksObj) { log::error("sCallbacksObj is null"); return; } - ScopedLocalRef addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); + ScopedLocalRef addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); if (!addr.get()) { log::error("Failed to allocate a new byte array"); return; } - sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), - (jbyte*)&bd_addr.address); + sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), (jbyte*)&bd_addr.address); /* TODO ext attrs * Flattening defined attributes: */ @@ -127,52 +127,50 @@ static void btavrcp_playerapplicationsetting_callback( } log::verbose("arraylen {}", arraylen); - ScopedLocalRef playerattribs( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(arraylen)); + ScopedLocalRef playerattribs(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(arraylen)); if (!playerattribs.get()) { log::error("Failed to allocate a new byte array"); return; } for (int i = 0, k = 0; (i < num_attr) && (k < arraylen); i++) { - sCallbackEnv->SetByteArrayRegion(playerattribs.get(), k, 1, - (jbyte*)&(app_attrs[i].attr_id)); + sCallbackEnv->SetByteArrayRegion(playerattribs.get(), k, 1, (jbyte*)&(app_attrs[i].attr_id)); k++; - sCallbackEnv->SetByteArrayRegion(playerattribs.get(), k, 1, - (jbyte*)&(app_attrs[i].num_val)); + sCallbackEnv->SetByteArrayRegion(playerattribs.get(), k, 1, (jbyte*)&(app_attrs[i].num_val)); k++; - sCallbackEnv->SetByteArrayRegion(playerattribs.get(), k, - app_attrs[i].num_val, + sCallbackEnv->SetByteArrayRegion(playerattribs.get(), k, app_attrs[i].num_val, (jbyte*)(app_attrs[i].attr_val)); k = k + app_attrs[i].num_val; } - sCallbackEnv->CallVoidMethod(sCallbacksObj, method_handleplayerappsetting, - addr.get(), playerattribs.get(), (jint)arraylen); + sCallbackEnv->CallVoidMethod(sCallbacksObj, method_handleplayerappsetting, addr.get(), + playerattribs.get(), (jint)arraylen); } -static void btavrcp_playerapplicationsetting_changed_callback( - const RawAddress& bd_addr, const btrc_player_settings_t& vals) { +static void btavrcp_playerapplicationsetting_changed_callback(const RawAddress& bd_addr, + const btrc_player_settings_t& vals) { log::info(""); std::shared_lock lock(sCallbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid()) return; + if (!sCallbackEnv.valid()) { + return; + } if (!sCallbacksObj) { log::error("sCallbacksObj is null"); return; } - ScopedLocalRef addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); + ScopedLocalRef addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); if (!addr.get()) { log::error("Failed to allocate a new byte array"); return; } - sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), - (jbyte*)&bd_addr.address); + sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), (jbyte*)&bd_addr.address); int arraylen = vals.num_attr * 2; - ScopedLocalRef playerattribs( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(arraylen)); + ScopedLocalRef playerattribs(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(arraylen)); if (!playerattribs.get()) { log::error("Fail to new jbyteArray playerattribs"); return; @@ -181,69 +179,66 @@ static void btavrcp_playerapplicationsetting_changed_callback( * Flatening format: */ for (int i = 0, k = 0; (i < vals.num_attr) && (k < arraylen); i++) { - sCallbackEnv->SetByteArrayRegion(playerattribs.get(), k, 1, - (jbyte*)&(vals.attr_ids[i])); + sCallbackEnv->SetByteArrayRegion(playerattribs.get(), k, 1, (jbyte*)&(vals.attr_ids[i])); k++; - sCallbackEnv->SetByteArrayRegion(playerattribs.get(), k, 1, - (jbyte*)&(vals.attr_values[i])); + sCallbackEnv->SetByteArrayRegion(playerattribs.get(), k, 1, (jbyte*)&(vals.attr_values[i])); k++; } - sCallbackEnv->CallVoidMethod(sCallbacksObj, - method_handleplayerappsettingchanged, addr.get(), + sCallbackEnv->CallVoidMethod(sCallbacksObj, method_handleplayerappsettingchanged, addr.get(), playerattribs.get(), (jint)arraylen); } -static void btavrcp_set_abs_vol_cmd_callback(const RawAddress& bd_addr, - uint8_t abs_vol, uint8_t label) { +static void btavrcp_set_abs_vol_cmd_callback(const RawAddress& bd_addr, uint8_t abs_vol, + uint8_t label) { log::info(""); std::shared_lock lock(sCallbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid()) return; + if (!sCallbackEnv.valid()) { + return; + } if (!sCallbacksObj) { log::error("sCallbacksObj is null"); return; } - ScopedLocalRef addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); + ScopedLocalRef addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); if (!addr.get()) { log::error("Failed to allocate a new byte array"); return; } - sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), - (jbyte*)&bd_addr.address); - sCallbackEnv->CallVoidMethod(sCallbacksObj, method_handleSetAbsVolume, - addr.get(), (jbyte)abs_vol, (jbyte)label); + sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), (jbyte*)&bd_addr.address); + sCallbackEnv->CallVoidMethod(sCallbacksObj, method_handleSetAbsVolume, addr.get(), (jbyte)abs_vol, + (jbyte)label); } -static void btavrcp_register_notification_absvol_callback( - const RawAddress& bd_addr, uint8_t label) { +static void btavrcp_register_notification_absvol_callback(const RawAddress& bd_addr, + uint8_t label) { log::info(""); std::shared_lock lock(sCallbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid()) return; + if (!sCallbackEnv.valid()) { + return; + } if (!sCallbacksObj) { log::error("sCallbacksObj is null"); return; } - ScopedLocalRef addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); + ScopedLocalRef addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); if (!addr.get()) { log::error("Failed to allocate a new byte array"); return; } - sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), - (jbyte*)&bd_addr.address); - sCallbackEnv->CallVoidMethod(sCallbacksObj, - method_handleRegisterNotificationAbsVol, - addr.get(), (jbyte)label); + sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), (jbyte*)&bd_addr.address); + sCallbackEnv->CallVoidMethod(sCallbacksObj, method_handleRegisterNotificationAbsVol, addr.get(), + (jbyte)label); } -static void btavrcp_track_changed_callback(const RawAddress& bd_addr, - uint8_t num_attr, +static void btavrcp_track_changed_callback(const RawAddress& bd_addr, uint8_t num_attr, btrc_element_attr_val_t* p_attrs) { /* * byteArray will be formatted like this: id,len,string @@ -252,105 +247,102 @@ static void btavrcp_track_changed_callback(const RawAddress& bd_addr, log::info(""); std::shared_lock lock(sCallbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid()) return; + if (!sCallbackEnv.valid()) { + return; + } if (!sCallbacksObj) { log::error("sCallbacksObj is null"); return; } - ScopedLocalRef addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); + ScopedLocalRef addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); if (!addr.get()) { log::error("Failed to allocate a new byte array"); return; } - ScopedLocalRef attribIds(sCallbackEnv.get(), - sCallbackEnv->NewIntArray(num_attr)); + ScopedLocalRef attribIds(sCallbackEnv.get(), sCallbackEnv->NewIntArray(num_attr)); if (!attribIds.get()) { log::error("failed to set new array for attribIds"); return; } - sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), - (jbyte*)&bd_addr.address); + sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), (jbyte*)&bd_addr.address); jclass strclazz = sCallbackEnv->FindClass("java/lang/String"); ScopedLocalRef stringArray( - sCallbackEnv.get(), - sCallbackEnv->NewObjectArray((jint)num_attr, strclazz, 0)); + sCallbackEnv.get(), sCallbackEnv->NewObjectArray((jint)num_attr, strclazz, 0)); if (!stringArray.get()) { log::error("failed to get String array"); return; } for (jint i = 0; i < num_attr; i++) { - ScopedLocalRef str( - sCallbackEnv.get(), - sCallbackEnv->NewStringUTF((char*)(p_attrs[i].text))); + ScopedLocalRef str(sCallbackEnv.get(), + sCallbackEnv->NewStringUTF((char*)(p_attrs[i].text))); if (!str.get()) { log::error("Unable to get str"); return; } - sCallbackEnv->SetIntArrayRegion(attribIds.get(), i, 1, - (jint*)&(p_attrs[i].attr_id)); + sCallbackEnv->SetIntArrayRegion(attribIds.get(), i, 1, (jint*)&(p_attrs[i].attr_id)); sCallbackEnv->SetObjectArrayElement(stringArray.get(), i, str.get()); } - sCallbackEnv->CallVoidMethod(sCallbacksObj, method_handletrackchanged, - addr.get(), (jbyte)(num_attr), attribIds.get(), - stringArray.get()); + sCallbackEnv->CallVoidMethod(sCallbacksObj, method_handletrackchanged, addr.get(), + (jbyte)(num_attr), attribIds.get(), stringArray.get()); } -static void btavrcp_play_position_changed_callback(const RawAddress& bd_addr, - uint32_t song_len, +static void btavrcp_play_position_changed_callback(const RawAddress& bd_addr, uint32_t song_len, uint32_t song_pos) { log::info(""); std::shared_lock lock(sCallbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid()) return; + if (!sCallbackEnv.valid()) { + return; + } if (!sCallbacksObj) { log::error("sCallbacksObj is null"); return; } - ScopedLocalRef addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); + ScopedLocalRef addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); if (!addr.get()) { log::error("Failed to allocate a new byte array"); return; } - sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), - (jbyte*)&bd_addr.address); - sCallbackEnv->CallVoidMethod(sCallbacksObj, method_handleplaypositionchanged, - addr.get(), (jint)(song_len), (jint)song_pos); + sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), (jbyte*)&bd_addr.address); + sCallbackEnv->CallVoidMethod(sCallbacksObj, method_handleplaypositionchanged, addr.get(), + (jint)(song_len), (jint)song_pos); } -static void btavrcp_play_status_changed_callback( - const RawAddress& bd_addr, btrc_play_status_t play_status) { +static void btavrcp_play_status_changed_callback(const RawAddress& bd_addr, + btrc_play_status_t play_status) { log::info(""); std::shared_lock lock(sCallbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid()) return; + if (!sCallbackEnv.valid()) { + return; + } if (!sCallbacksObj) { log::error("sCallbacksObj is null"); return; } - ScopedLocalRef addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); + ScopedLocalRef addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); if (!addr.get()) { log::error("Failed to allocate a new byte array"); return; } - sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), - (jbyte*)&bd_addr.address); - sCallbackEnv->CallVoidMethod(sCallbacksObj, method_handleplaystatuschanged, - addr.get(), (jbyte)play_status); + sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), (jbyte*)&bd_addr.address); + sCallbackEnv->CallVoidMethod(sCallbacksObj, method_handleplaystatuschanged, addr.get(), + (jbyte)play_status); } -static void btavrcp_get_folder_items_callback( - const RawAddress& bd_addr, btrc_status_t status, - const btrc_folder_items_t* folder_items, uint8_t count) { +static void btavrcp_get_folder_items_callback(const RawAddress& bd_addr, btrc_status_t status, + const btrc_folder_items_t* folder_items, + uint8_t count) { /* Folder items are list of items that can be either BTRC_ITEM_PLAYER * BTRC_ITEM_MEDIA, BTRC_ITEM_FOLDER. Here we translate them to their java * counterparts by calling the java constructor for each of the items. @@ -358,35 +350,33 @@ static void btavrcp_get_folder_items_callback( log::verbose("count {}", count); std::shared_lock lock(sCallbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid()) return; + if (!sCallbackEnv.valid()) { + return; + } if (!sCallbacksObj) { log::error("sCallbacksObj is null"); return; } - ScopedLocalRef addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); + ScopedLocalRef addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); if (!addr.get()) { log::error("Failed to allocate a new byte array"); return; } - sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), - (jbyte*)&bd_addr.address); + sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), (jbyte*)&bd_addr.address); // Inspect if the first element is a folder/item or player listing. They are // always exclusive. - bool isPlayerListing = - count > 0 && (folder_items[0].item_type == BTRC_ITEM_PLAYER); + bool isPlayerListing = count > 0 && (folder_items[0].item_type == BTRC_ITEM_PLAYER); // Initialize arrays for Folder OR Player listing. ScopedLocalRef itemArray(sCallbackEnv.get(), NULL); if (isPlayerListing) { - itemArray.reset( - sCallbackEnv->NewObjectArray((jint)count, class_AvrcpPlayer, 0)); + itemArray.reset(sCallbackEnv->NewObjectArray((jint)count, class_AvrcpPlayer, 0)); } else { - itemArray.reset(sCallbackEnv->NewObjectArray( - (jint)count, class_AvrcpItem, 0)); + itemArray.reset(sCallbackEnv->NewObjectArray((jint)count, class_AvrcpItem, 0)); } if (!itemArray.get()) { log::error("itemArray allocation failed."); @@ -399,8 +389,7 @@ static void btavrcp_get_folder_items_callback( case BTRC_ITEM_MEDIA: { // Parse name ScopedLocalRef mediaName( - sCallbackEnv.get(), - sCallbackEnv->NewStringUTF((const char*)item->media.name)); + sCallbackEnv.get(), sCallbackEnv->NewStringUTF((const char*)item->media.name)); if (!mediaName.get()) { log::error("can't allocate media name string!"); return; @@ -408,41 +397,36 @@ static void btavrcp_get_folder_items_callback( // Parse UID long long uid = *(long long*)item->media.uid; // Parse Attrs - ScopedLocalRef attrIdArray( - sCallbackEnv.get(), - sCallbackEnv->NewIntArray(item->media.num_attrs)); + ScopedLocalRef attrIdArray(sCallbackEnv.get(), + sCallbackEnv->NewIntArray(item->media.num_attrs)); if (!attrIdArray.get()) { log::error("can't allocate attr id array!"); return; } ScopedLocalRef attrValArray( - sCallbackEnv.get(), - sCallbackEnv->NewObjectArray( - item->media.num_attrs, - sCallbackEnv->FindClass("java/lang/String"), 0)); + sCallbackEnv.get(), + sCallbackEnv->NewObjectArray(item->media.num_attrs, + sCallbackEnv->FindClass("java/lang/String"), 0)); if (!attrValArray.get()) { log::error("can't allocate attr val array!"); return; } for (int j = 0; j < item->media.num_attrs; j++) { - sCallbackEnv->SetIntArrayRegion( - attrIdArray.get(), j, 1, - (jint*)&(item->media.p_attrs[j].attr_id)); + sCallbackEnv->SetIntArrayRegion(attrIdArray.get(), j, 1, + (jint*)&(item->media.p_attrs[j].attr_id)); ScopedLocalRef attrValStr( - sCallbackEnv.get(), - sCallbackEnv->NewStringUTF((char*)(item->media.p_attrs[j].text))); - sCallbackEnv->SetObjectArrayElement(attrValArray.get(), j, - attrValStr.get()); + sCallbackEnv.get(), + sCallbackEnv->NewStringUTF((char*)(item->media.p_attrs[j].text))); + sCallbackEnv->SetObjectArrayElement(attrValArray.get(), j, attrValStr.get()); } ScopedLocalRef mediaObj( - sCallbackEnv.get(), - (jobject)sCallbackEnv->CallStaticObjectMethod( - class_AvrcpControllerNativeInterface, - method_createFromNativeMediaItem, addr.get(), uid, - (jint)item->media.type, mediaName.get(), attrIdArray.get(), - attrValArray.get())); + sCallbackEnv.get(), + (jobject)sCallbackEnv->CallStaticObjectMethod( + class_AvrcpControllerNativeInterface, method_createFromNativeMediaItem, + addr.get(), uid, (jint)item->media.type, mediaName.get(), attrIdArray.get(), + attrValArray.get())); if (!mediaObj.get()) { log::error("failed to create AvrcpItem for type ITEM_MEDIA"); return; @@ -454,8 +438,7 @@ static void btavrcp_get_folder_items_callback( case BTRC_ITEM_FOLDER: { // Parse name ScopedLocalRef folderName( - sCallbackEnv.get(), - sCallbackEnv->NewStringUTF((const char*)item->folder.name)); + sCallbackEnv.get(), sCallbackEnv->NewStringUTF((const char*)item->folder.name)); if (!folderName.get()) { log::error("can't allocate folder name string!"); return; @@ -463,18 +446,16 @@ static void btavrcp_get_folder_items_callback( // Parse UID long long uid = *(long long*)item->folder.uid; ScopedLocalRef folderObj( - sCallbackEnv.get(), - (jobject)sCallbackEnv->CallStaticObjectMethod( - class_AvrcpControllerNativeInterface, - method_createFromNativeFolderItem, addr.get(), uid, - (jint)item->folder.type, folderName.get(), - (jint)item->folder.playable)); + sCallbackEnv.get(), + (jobject)sCallbackEnv->CallStaticObjectMethod( + class_AvrcpControllerNativeInterface, method_createFromNativeFolderItem, + addr.get(), uid, (jint)item->folder.type, folderName.get(), + (jint)item->folder.playable)); if (!folderObj.get()) { log::error("failed to create AvrcpItem for type ITEM_FOLDER"); return; } - sCallbackEnv->SetObjectArrayElement(itemArray.get(), i, - folderObj.get()); + sCallbackEnv->SetObjectArrayElement(itemArray.get(), i, folderObj.get()); break; } @@ -485,37 +466,32 @@ static void btavrcp_get_folder_items_callback( jint playerType = (jint)item->player.major_type; jint playStatus = (jint)item->player.play_status; ScopedLocalRef featureBitArray( - sCallbackEnv.get(), - sCallbackEnv->NewByteArray(BTRC_FEATURE_BIT_MASK_SIZE * - sizeof(uint8_t))); + sCallbackEnv.get(), + sCallbackEnv->NewByteArray(BTRC_FEATURE_BIT_MASK_SIZE * sizeof(uint8_t))); if (!featureBitArray.get()) { log::error("failed to allocate featureBitArray"); return; } - sCallbackEnv->SetByteArrayRegion( - featureBitArray.get(), 0, - sizeof(uint8_t) * BTRC_FEATURE_BIT_MASK_SIZE, - (jbyte*)item->player.features); + sCallbackEnv->SetByteArrayRegion(featureBitArray.get(), 0, + sizeof(uint8_t) * BTRC_FEATURE_BIT_MASK_SIZE, + (jbyte*)item->player.features); ScopedLocalRef playerName( - sCallbackEnv.get(), - sCallbackEnv->NewStringUTF((const char*)item->player.name)); + sCallbackEnv.get(), sCallbackEnv->NewStringUTF((const char*)item->player.name)); if (!playerName.get()) { log::error("can't allocate player name string!"); return; } ScopedLocalRef playerObj( - sCallbackEnv.get(), - (jobject)sCallbackEnv->CallStaticObjectMethod( - class_AvrcpControllerNativeInterface, - method_createFromNativePlayerItem, addr.get(), id, - playerName.get(), featureBitArray.get(), playStatus, - playerType)); + sCallbackEnv.get(), + (jobject)sCallbackEnv->CallStaticObjectMethod( + class_AvrcpControllerNativeInterface, method_createFromNativePlayerItem, + addr.get(), id, playerName.get(), featureBitArray.get(), playStatus, + playerType)); if (!playerObj.get()) { log::error("failed to create AvrcpPlayer from ITEM_PLAYER"); return; } - sCallbackEnv->SetObjectArrayElement(itemArray.get(), i, - playerObj.get()); + sCallbackEnv->SetObjectArrayElement(itemArray.get(), i, playerObj.get()); break; } @@ -525,134 +501,131 @@ static void btavrcp_get_folder_items_callback( } if (isPlayerListing) { - sCallbackEnv->CallVoidMethod(sCallbacksObj, method_handleGetPlayerItemsRsp, - addr.get(), itemArray.get()); + sCallbackEnv->CallVoidMethod(sCallbacksObj, method_handleGetPlayerItemsRsp, addr.get(), + itemArray.get()); } else { - sCallbackEnv->CallVoidMethod(sCallbacksObj, method_handleGetFolderItemsRsp, - addr.get(), status, itemArray.get()); + sCallbackEnv->CallVoidMethod(sCallbacksObj, method_handleGetFolderItemsRsp, addr.get(), status, + itemArray.get()); } } -static void btavrcp_change_path_callback(const RawAddress& bd_addr, - uint32_t count) { +static void btavrcp_change_path_callback(const RawAddress& bd_addr, uint32_t count) { log::info("count {}", count); std::shared_lock lock(sCallbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid()) return; + if (!sCallbackEnv.valid()) { + return; + } if (!sCallbacksObj) { log::error("sCallbacksObj is null"); return; } - ScopedLocalRef addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); + ScopedLocalRef addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); if (!addr.get()) { log::error("Failed to allocate a new byte array"); return; } - sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), - (jbyte*)&bd_addr.address); + sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), (jbyte*)&bd_addr.address); - sCallbackEnv->CallVoidMethod(sCallbacksObj, method_handleChangeFolderRsp, - addr.get(), (jint)count); + sCallbackEnv->CallVoidMethod(sCallbacksObj, method_handleChangeFolderRsp, addr.get(), + (jint)count); } -static void btavrcp_set_browsed_player_callback(const RawAddress& bd_addr, - uint8_t num_items, +static void btavrcp_set_browsed_player_callback(const RawAddress& bd_addr, uint8_t num_items, uint8_t depth) { log::info("items {} depth {}", num_items, depth); std::shared_lock lock(sCallbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid()) return; + if (!sCallbackEnv.valid()) { + return; + } if (!sCallbacksObj) { log::error("sCallbacksObj is null"); return; } - ScopedLocalRef addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); + ScopedLocalRef addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); if (!addr.get()) { log::error("Failed to allocate a new byte array"); return; } - sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), - (jbyte*)&bd_addr.address); + sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), (jbyte*)&bd_addr.address); - sCallbackEnv->CallVoidMethod(sCallbacksObj, method_handleSetBrowsedPlayerRsp, - addr.get(), (jint)num_items, (jint)depth); + sCallbackEnv->CallVoidMethod(sCallbacksObj, method_handleSetBrowsedPlayerRsp, addr.get(), + (jint)num_items, (jint)depth); } -static void btavrcp_set_addressed_player_callback(const RawAddress& bd_addr, - uint8_t status) { +static void btavrcp_set_addressed_player_callback(const RawAddress& bd_addr, uint8_t status) { log::info("status {}", status); std::shared_lock lock(sCallbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid()) return; + if (!sCallbackEnv.valid()) { + return; + } if (!sCallbacksObj) { log::error("sCallbacksObj is null"); return; } - ScopedLocalRef addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); + ScopedLocalRef addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); if (!addr.get()) { log::error("Failed to allocate a new byte array"); return; } - sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), - (jbyte*)&bd_addr.address); + sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), (jbyte*)&bd_addr.address); - sCallbackEnv->CallVoidMethod(sCallbacksObj, - method_handleSetAddressedPlayerRsp, addr.get(), + sCallbackEnv->CallVoidMethod(sCallbacksObj, method_handleSetAddressedPlayerRsp, addr.get(), (jint)status); } -static void btavrcp_addressed_player_changed_callback(const RawAddress& bd_addr, - uint16_t id) { +static void btavrcp_addressed_player_changed_callback(const RawAddress& bd_addr, uint16_t id) { log::info("status {}", id); std::shared_lock lock(sCallbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid()) return; + if (!sCallbackEnv.valid()) { + return; + } if (!sCallbacksObj) { log::error("sCallbacksObj is null"); return; } - ScopedLocalRef addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); + ScopedLocalRef addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); if (!addr.get()) { log::error("Failed to allocate a new byte array"); return; } - sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), - (jbyte*)&bd_addr.address); + sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), (jbyte*)&bd_addr.address); - sCallbackEnv->CallVoidMethod( - sCallbacksObj, method_handleAddressedPlayerChanged, addr.get(), (jint)id); + sCallbackEnv->CallVoidMethod(sCallbacksObj, method_handleAddressedPlayerChanged, addr.get(), + (jint)id); } -static void btavrcp_now_playing_content_changed_callback( - const RawAddress& bd_addr) { +static void btavrcp_now_playing_content_changed_callback(const RawAddress& bd_addr) { log::info(""); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid()) return; - ScopedLocalRef addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); + if (!sCallbackEnv.valid()) { + return; + } + ScopedLocalRef addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); if (!addr.get()) { log::error("Failed to allocate a new byte array"); return; } - sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), - (jbyte*)&bd_addr.address); + sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), (jbyte*)&bd_addr.address); - sCallbackEnv->CallVoidMethod( - sCallbacksObj, method_handleNowPlayingContentChanged, addr.get()); + sCallbackEnv->CallVoidMethod(sCallbacksObj, method_handleNowPlayingContentChanged, addr.get()); } -static void btavrcp_available_player_changed_callback ( - const RawAddress& bd_addr) { +static void btavrcp_available_player_changed_callback(const RawAddress& bd_addr) { log::info(""); std::shared_lock lock(sCallbacks_mutex); CallbackEnv sCallbackEnv(__func__); @@ -660,23 +633,22 @@ static void btavrcp_available_player_changed_callback ( log::error("sCallbacksObj is null"); return; } - if (!sCallbackEnv.valid()) return; + if (!sCallbackEnv.valid()) { + return; + } - ScopedLocalRef addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); + ScopedLocalRef addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); if (!addr.get()) { log::error("Failed to allocate a new byte array"); return; } - sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), - (jbyte*)&bd_addr); - sCallbackEnv->CallVoidMethod( - sCallbacksObj, method_onAvailablePlayerChanged, addr.get()); + sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), (jbyte*)&bd_addr); + sCallbackEnv->CallVoidMethod(sCallbacksObj, method_onAvailablePlayerChanged, addr.get()); } -static void btavrcp_get_rcpsm_callback(const RawAddress& bd_addr, - uint16_t psm) { +static void btavrcp_get_rcpsm_callback(const RawAddress& bd_addr, uint16_t psm) { log::error("-> psm received of {}", psm); std::shared_lock lock(sCallbacks_mutex); CallbackEnv sCallbackEnv(__func__); @@ -684,60 +656,57 @@ static void btavrcp_get_rcpsm_callback(const RawAddress& bd_addr, log::error("sCallbacksObj is null"); return; } - if (!sCallbackEnv.valid()) return; + if (!sCallbackEnv.valid()) { + return; + } - ScopedLocalRef addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); + ScopedLocalRef addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); if (!addr.get()) { log::error("Failed to allocate a new byte array"); return; } - sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), - (jbyte*)&bd_addr.address); - sCallbackEnv->CallVoidMethod(sCallbacksObj, method_getRcPsm, addr.get(), - (jint)psm); + sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), (jbyte*)&bd_addr.address); + sCallbackEnv->CallVoidMethod(sCallbacksObj, method_getRcPsm, addr.get(), (jint)psm); } static btrc_ctrl_callbacks_t sBluetoothAvrcpCallbacks = { - sizeof(sBluetoothAvrcpCallbacks), - btavrcp_passthrough_response_callback, - btavrcp_groupnavigation_response_callback, - btavrcp_connection_state_callback, - btavrcp_get_rcfeatures_callback, - btavrcp_setplayerapplicationsetting_rsp_callback, - btavrcp_playerapplicationsetting_callback, - btavrcp_playerapplicationsetting_changed_callback, - btavrcp_set_abs_vol_cmd_callback, - btavrcp_register_notification_absvol_callback, - btavrcp_track_changed_callback, - btavrcp_play_position_changed_callback, - btavrcp_play_status_changed_callback, - btavrcp_get_folder_items_callback, - btavrcp_change_path_callback, - btavrcp_set_browsed_player_callback, - btavrcp_set_addressed_player_callback, - btavrcp_addressed_player_changed_callback, - btavrcp_now_playing_content_changed_callback, - btavrcp_available_player_changed_callback, - btavrcp_get_rcpsm_callback, + sizeof(sBluetoothAvrcpCallbacks), + btavrcp_passthrough_response_callback, + btavrcp_groupnavigation_response_callback, + btavrcp_connection_state_callback, + btavrcp_get_rcfeatures_callback, + btavrcp_setplayerapplicationsetting_rsp_callback, + btavrcp_playerapplicationsetting_callback, + btavrcp_playerapplicationsetting_changed_callback, + btavrcp_set_abs_vol_cmd_callback, + btavrcp_register_notification_absvol_callback, + btavrcp_track_changed_callback, + btavrcp_play_position_changed_callback, + btavrcp_play_status_changed_callback, + btavrcp_get_folder_items_callback, + btavrcp_change_path_callback, + btavrcp_set_browsed_player_callback, + btavrcp_set_addressed_player_callback, + btavrcp_addressed_player_changed_callback, + btavrcp_now_playing_content_changed_callback, + btavrcp_available_player_changed_callback, + btavrcp_get_rcpsm_callback, }; static void initNative(JNIEnv* env, jobject object) { std::unique_lock lock(sCallbacks_mutex); - jclass tmpAvrcpItem = - env->FindClass("com/android/bluetooth/avrcpcontroller/AvrcpItem"); + jclass tmpAvrcpItem = env->FindClass("com/android/bluetooth/avrcpcontroller/AvrcpItem"); class_AvrcpItem = (jclass)env->NewGlobalRef(tmpAvrcpItem); - jclass tmpBtPlayer = - env->FindClass("com/android/bluetooth/avrcpcontroller/AvrcpPlayer"); + jclass tmpBtPlayer = env->FindClass("com/android/bluetooth/avrcpcontroller/AvrcpPlayer"); class_AvrcpPlayer = (jclass)env->NewGlobalRef(tmpBtPlayer); - jclass tmpControllerInterface = env->FindClass( - "com/android/bluetooth/avrcpcontroller/AvrcpControllerNativeInterface"); - class_AvrcpControllerNativeInterface = - (jclass)env->NewGlobalRef(tmpControllerInterface); + jclass tmpControllerInterface = + env->FindClass("com/android/bluetooth/avrcpcontroller/AvrcpControllerNativeInterface"); + class_AvrcpControllerNativeInterface = (jclass)env->NewGlobalRef(tmpControllerInterface); const bt_interface_t* btInf = getBluetoothInterface(); if (btInf == NULL) { @@ -758,15 +727,13 @@ static void initNative(JNIEnv* env, jobject object) { } sBluetoothAvrcpInterface = - (btrc_ctrl_interface_t*)btInf->get_profile_interface( - BT_PROFILE_AV_RC_CTRL_ID); + (btrc_ctrl_interface_t*)btInf->get_profile_interface(BT_PROFILE_AV_RC_CTRL_ID); if (sBluetoothAvrcpInterface == NULL) { log::error("Failed to get Bluetooth Avrcp Controller Interface"); return; } - bt_status_t status = - sBluetoothAvrcpInterface->init(&sBluetoothAvrcpCallbacks); + bt_status_t status = sBluetoothAvrcpInterface->init(&sBluetoothAvrcpCallbacks); if (status != BT_STATUS_SUCCESS) { log::error("Failed to initialize Bluetooth Avrcp Controller, status: {}", bt_status_text(status)); @@ -797,10 +764,11 @@ static void cleanupNative(JNIEnv* env, jobject /* object */) { } } -static jboolean sendPassThroughCommandNative(JNIEnv* env, jobject /* object */, - jbyteArray address, jint key_code, - jint key_state) { - if (!sBluetoothAvrcpInterface) return JNI_FALSE; +static jboolean sendPassThroughCommandNative(JNIEnv* env, jobject /* object */, jbyteArray address, + jint key_code, jint key_state) { + if (!sBluetoothAvrcpInterface) { + return JNI_FALSE; + } log::info("sBluetoothAvrcpInterface: {}", fmt::ptr(sBluetoothAvrcpInterface)); @@ -815,22 +783,21 @@ static jboolean sendPassThroughCommandNative(JNIEnv* env, jobject /* object */, RawAddress rawAddress; rawAddress.FromOctets((uint8_t*)addr); bt_status_t status = sBluetoothAvrcpInterface->send_pass_through_cmd( - rawAddress, (uint8_t)key_code, (uint8_t)key_state); + rawAddress, (uint8_t)key_code, (uint8_t)key_state); if (status != BT_STATUS_SUCCESS) { - log::error("Failed sending passthru command, status: {}", - bt_status_text(status)); + log::error("Failed sending passthru command, status: {}", bt_status_text(status)); } env->ReleaseByteArrayElements(address, addr, 0); return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } -static jboolean sendGroupNavigationCommandNative(JNIEnv* env, - jobject /* object */, - jbyteArray address, - jint key_code, +static jboolean sendGroupNavigationCommandNative(JNIEnv* env, jobject /* object */, + jbyteArray address, jint key_code, jint key_state) { - if (!sBluetoothAvrcpInterface) return JNI_FALSE; + if (!sBluetoothAvrcpInterface) { + return JNI_FALSE; + } log::info("sBluetoothAvrcpInterface: {}", fmt::ptr(sBluetoothAvrcpInterface)); @@ -845,21 +812,22 @@ static jboolean sendGroupNavigationCommandNative(JNIEnv* env, rawAddress.FromOctets((uint8_t*)addr); bt_status_t status = sBluetoothAvrcpInterface->send_group_navigation_cmd( - rawAddress, (uint8_t)key_code, (uint8_t)key_state); + rawAddress, (uint8_t)key_code, (uint8_t)key_state); if (status != BT_STATUS_SUCCESS) { - log::error("Failed sending Grp Navigation command, status: {}", - bt_status_text(status)); + log::error("Failed sending Grp Navigation command, status: {}", bt_status_text(status)); } env->ReleaseByteArrayElements(address, addr, 0); return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } -static void setPlayerApplicationSettingValuesNative( - JNIEnv* env, jobject /* object */, jbyteArray address, jbyte num_attrib, - jbyteArray attrib_ids, jbyteArray attrib_val) { +static void setPlayerApplicationSettingValuesNative(JNIEnv* env, jobject /* object */, + jbyteArray address, jbyte num_attrib, + jbyteArray attrib_ids, jbyteArray attrib_val) { log::info("sBluetoothAvrcpInterface: {}", fmt::ptr(sBluetoothAvrcpInterface)); - if (!sBluetoothAvrcpInterface) return; + if (!sBluetoothAvrcpInterface) { + return; + } jbyte* addr = env->GetByteArrayElements(address, NULL); if (!addr) { @@ -871,8 +839,7 @@ static void setPlayerApplicationSettingValuesNative( uint8_t* pAttrsVal = new uint8_t[num_attrib]; if ((!pAttrs) || (!pAttrsVal)) { delete[] pAttrs; - log::error( - "setPlayerApplicationSettingValuesNative: not have enough memory"); + log::error("setPlayerApplicationSettingValuesNative: not have enough memory"); return; } @@ -894,10 +861,9 @@ static void setPlayerApplicationSettingValuesNative( rawAddress.FromOctets((uint8_t*)addr); bt_status_t status = sBluetoothAvrcpInterface->set_player_app_setting_cmd( - rawAddress, (uint8_t)num_attrib, pAttrs, pAttrsVal); + rawAddress, (uint8_t)num_attrib, pAttrs, pAttrsVal); if (status != BT_STATUS_SUCCESS) { - log::error("Failed sending setPlAppSettValNative command, status: {}", - bt_status_text(status)); + log::error("Failed sending setPlAppSettValNative command, status: {}", bt_status_text(status)); } delete[] pAttrs; delete[] pAttrsVal; @@ -906,9 +872,11 @@ static void setPlayerApplicationSettingValuesNative( env->ReleaseByteArrayElements(address, addr, 0); } -static void sendAbsVolRspNative(JNIEnv* env, jobject /* object */, - jbyteArray address, jint abs_vol, jint label) { - if (!sBluetoothAvrcpInterface) return; +static void sendAbsVolRspNative(JNIEnv* env, jobject /* object */, jbyteArray address, jint abs_vol, + jint label) { + if (!sBluetoothAvrcpInterface) { + return; + } jbyte* addr = env->GetByteArrayElements(address, NULL); if (!addr) { @@ -920,19 +888,19 @@ static void sendAbsVolRspNative(JNIEnv* env, jobject /* object */, RawAddress rawAddress; rawAddress.FromOctets((uint8_t*)addr); - bt_status_t status = sBluetoothAvrcpInterface->set_volume_rsp( - rawAddress, (uint8_t)abs_vol, (uint8_t)label); + bt_status_t status = + sBluetoothAvrcpInterface->set_volume_rsp(rawAddress, (uint8_t)abs_vol, (uint8_t)label); if (status != BT_STATUS_SUCCESS) { - log::error("Failed sending sendAbsVolRspNative command, status: {}", - bt_status_text(status)); + log::error("Failed sending sendAbsVolRspNative command, status: {}", bt_status_text(status)); } env->ReleaseByteArrayElements(address, addr, 0); } -static void sendRegisterAbsVolRspNative(JNIEnv* env, jobject /* object */, - jbyteArray address, jbyte rsp_type, - jint abs_vol, jint label) { - if (!sBluetoothAvrcpInterface) return; +static void sendRegisterAbsVolRspNative(JNIEnv* env, jobject /* object */, jbyteArray address, + jbyte rsp_type, jint abs_vol, jint label) { + if (!sBluetoothAvrcpInterface) { + return; + } jbyte* addr = env->GetByteArrayElements(address, NULL); if (!addr) { @@ -944,8 +912,7 @@ static void sendRegisterAbsVolRspNative(JNIEnv* env, jobject /* object */, rawAddress.FromOctets((uint8_t*)addr); bt_status_t status = sBluetoothAvrcpInterface->register_abs_vol_rsp( - rawAddress, (btrc_notification_type_t)rsp_type, (uint8_t)abs_vol, - (uint8_t)label); + rawAddress, (btrc_notification_type_t)rsp_type, (uint8_t)abs_vol, (uint8_t)label); if (status != BT_STATUS_SUCCESS) { log::error("Failed sending sendRegisterAbsVolRspNative command, status: {}", bt_status_text(status)); @@ -953,22 +920,21 @@ static void sendRegisterAbsVolRspNative(JNIEnv* env, jobject /* object */, env->ReleaseByteArrayElements(address, addr, 0); } -static void getCurrentMetadataNative(JNIEnv* env, jobject /* object */, - jbyteArray address) { - if (!sBluetoothAvrcpInterface) return; +static void getCurrentMetadataNative(JNIEnv* env, jobject /* object */, jbyteArray address) { + if (!sBluetoothAvrcpInterface) { + return; + } jbyte* addr = env->GetByteArrayElements(address, NULL); if (!addr) { jniThrowIOException(env, EINVAL); return; } - log::verbose("sBluetoothAvrcpInterface: {}", - fmt::ptr(sBluetoothAvrcpInterface)); + log::verbose("sBluetoothAvrcpInterface: {}", fmt::ptr(sBluetoothAvrcpInterface)); RawAddress rawAddress; rawAddress.FromOctets((uint8_t*)addr); - bt_status_t status = - sBluetoothAvrcpInterface->get_current_metadata_cmd(rawAddress); + bt_status_t status = sBluetoothAvrcpInterface->get_current_metadata_cmd(rawAddress); if (status != BT_STATUS_SUCCESS) { log::error("Failed sending getCurrentMetadataNative command, status: {}", bt_status_text(status)); @@ -976,44 +942,42 @@ static void getCurrentMetadataNative(JNIEnv* env, jobject /* object */, env->ReleaseByteArrayElements(address, addr, 0); } -static void getPlaybackStateNative(JNIEnv* env, jobject /* object */, - jbyteArray address) { - if (!sBluetoothAvrcpInterface) return; +static void getPlaybackStateNative(JNIEnv* env, jobject /* object */, jbyteArray address) { + if (!sBluetoothAvrcpInterface) { + return; + } jbyte* addr = env->GetByteArrayElements(address, NULL); if (!addr) { jniThrowIOException(env, EINVAL); return; } - log::verbose("sBluetoothAvrcpInterface: {}", - fmt::ptr(sBluetoothAvrcpInterface)); + log::verbose("sBluetoothAvrcpInterface: {}", fmt::ptr(sBluetoothAvrcpInterface)); RawAddress rawAddress; rawAddress.FromOctets((uint8_t*)addr); - bt_status_t status = - sBluetoothAvrcpInterface->get_playback_state_cmd(rawAddress); + bt_status_t status = sBluetoothAvrcpInterface->get_playback_state_cmd(rawAddress); if (status != BT_STATUS_SUCCESS) { - log::error("Failed sending getPlaybackStateNative command, status: {}", - bt_status_text(status)); + log::error("Failed sending getPlaybackStateNative command, status: {}", bt_status_text(status)); } env->ReleaseByteArrayElements(address, addr, 0); } -static void getNowPlayingListNative(JNIEnv* env, jobject /* object */, - jbyteArray address, jint start, jint end) { - if (!sBluetoothAvrcpInterface) return; +static void getNowPlayingListNative(JNIEnv* env, jobject /* object */, jbyteArray address, + jint start, jint end) { + if (!sBluetoothAvrcpInterface) { + return; + } jbyte* addr = env->GetByteArrayElements(address, NULL); if (!addr) { jniThrowIOException(env, EINVAL); return; } - log::verbose("sBluetoothAvrcpInterface: {}", - fmt::ptr(sBluetoothAvrcpInterface)); + log::verbose("sBluetoothAvrcpInterface: {}", fmt::ptr(sBluetoothAvrcpInterface)); RawAddress rawAddress; rawAddress.FromOctets((uint8_t*)addr); - bt_status_t status = sBluetoothAvrcpInterface->get_now_playing_list_cmd( - rawAddress, start, end); + bt_status_t status = sBluetoothAvrcpInterface->get_now_playing_list_cmd(rawAddress, start, end); if (status != BT_STATUS_SUCCESS) { log::error("Failed sending getNowPlayingListNative command, status: {}", bt_status_text(status)); @@ -1021,31 +985,32 @@ static void getNowPlayingListNative(JNIEnv* env, jobject /* object */, env->ReleaseByteArrayElements(address, addr, 0); } -static void getFolderListNative(JNIEnv* env, jobject /* object */, - jbyteArray address, jint start, jint end) { - if (!sBluetoothAvrcpInterface) return; +static void getFolderListNative(JNIEnv* env, jobject /* object */, jbyteArray address, jint start, + jint end) { + if (!sBluetoothAvrcpInterface) { + return; + } jbyte* addr = env->GetByteArrayElements(address, NULL); if (!addr) { jniThrowIOException(env, EINVAL); return; } - log::verbose("sBluetoothAvrcpInterface: {}", - fmt::ptr(sBluetoothAvrcpInterface)); + log::verbose("sBluetoothAvrcpInterface: {}", fmt::ptr(sBluetoothAvrcpInterface)); RawAddress rawAddress; rawAddress.FromOctets((uint8_t*)addr); - bt_status_t status = - sBluetoothAvrcpInterface->get_folder_list_cmd(rawAddress, start, end); + bt_status_t status = sBluetoothAvrcpInterface->get_folder_list_cmd(rawAddress, start, end); if (status != BT_STATUS_SUCCESS) { - log::error("Failed sending getFolderListNative command, status: {}", - bt_status_text(status)); + log::error("Failed sending getFolderListNative command, status: {}", bt_status_text(status)); } env->ReleaseByteArrayElements(address, addr, 0); } -static void getPlayerListNative(JNIEnv* env, jobject /* object */, - jbyteArray address, jint start, jint end) { - if (!sBluetoothAvrcpInterface) return; +static void getPlayerListNative(JNIEnv* env, jobject /* object */, jbyteArray address, jint start, + jint end) { + if (!sBluetoothAvrcpInterface) { + return; + } jbyte* addr = env->GetByteArrayElements(address, NULL); if (!addr) { jniThrowIOException(env, EINVAL); @@ -1055,19 +1020,18 @@ static void getPlayerListNative(JNIEnv* env, jobject /* object */, RawAddress rawAddress; rawAddress.FromOctets((uint8_t*)addr); - bt_status_t status = - sBluetoothAvrcpInterface->get_player_list_cmd(rawAddress, start, end); + bt_status_t status = sBluetoothAvrcpInterface->get_player_list_cmd(rawAddress, start, end); if (status != BT_STATUS_SUCCESS) { - log::error("Failed sending getPlayerListNative command, status: {}", - bt_status_text(status)); + log::error("Failed sending getPlayerListNative command, status: {}", bt_status_text(status)); } env->ReleaseByteArrayElements(address, addr, 0); } -static void changeFolderPathNative(JNIEnv* env, jobject /* object */, - jbyteArray address, jbyte direction, - jlong uid) { - if (!sBluetoothAvrcpInterface) return; +static void changeFolderPathNative(JNIEnv* env, jobject /* object */, jbyteArray address, + jbyte direction, jlong uid) { + if (!sBluetoothAvrcpInterface) { + return; + } jbyte* addr = env->GetByteArrayElements(address, NULL); if (!addr) { jniThrowIOException(env, EINVAL); @@ -1085,17 +1049,17 @@ static void changeFolderPathNative(JNIEnv* env, jobject /* object */, rawAddress.FromOctets((uint8_t*)addr); bt_status_t status = sBluetoothAvrcpInterface->change_folder_path_cmd( - rawAddress, (uint8_t)direction, (uint8_t*)&uid); + rawAddress, (uint8_t)direction, (uint8_t*)&uid); if (status != BT_STATUS_SUCCESS) { - log::error("Failed sending changeFolderPathNative command, status: {}", - bt_status_text(status)); + log::error("Failed sending changeFolderPathNative command, status: {}", bt_status_text(status)); } // env->ReleaseByteArrayElements(address, addr, 0); } -static void setBrowsedPlayerNative(JNIEnv* env, jobject /* object */, - jbyteArray address, jint id) { - if (!sBluetoothAvrcpInterface) return; +static void setBrowsedPlayerNative(JNIEnv* env, jobject /* object */, jbyteArray address, jint id) { + if (!sBluetoothAvrcpInterface) { + return; + } jbyte* addr = env->GetByteArrayElements(address, NULL); if (!addr) { jniThrowIOException(env, EINVAL); @@ -1105,18 +1069,18 @@ static void setBrowsedPlayerNative(JNIEnv* env, jobject /* object */, rawAddress.FromOctets((uint8_t*)addr); log::info("sBluetoothAvrcpInterface: {}", fmt::ptr(sBluetoothAvrcpInterface)); - bt_status_t status = sBluetoothAvrcpInterface->set_browsed_player_cmd( - rawAddress, (uint16_t)id); + bt_status_t status = sBluetoothAvrcpInterface->set_browsed_player_cmd(rawAddress, (uint16_t)id); if (status != BT_STATUS_SUCCESS) { - log::error("Failed sending setBrowsedPlayerNative command, status: {}", - bt_status_text(status)); + log::error("Failed sending setBrowsedPlayerNative command, status: {}", bt_status_text(status)); } env->ReleaseByteArrayElements(address, addr, 0); } -static void setAddressedPlayerNative(JNIEnv* env, jobject /* object */, - jbyteArray address, jint id) { - if (!sBluetoothAvrcpInterface) return; +static void setAddressedPlayerNative(JNIEnv* env, jobject /* object */, jbyteArray address, + jint id) { + if (!sBluetoothAvrcpInterface) { + return; + } jbyte* addr = env->GetByteArrayElements(address, NULL); if (!addr) { jniThrowIOException(env, EINVAL); @@ -1126,8 +1090,7 @@ static void setAddressedPlayerNative(JNIEnv* env, jobject /* object */, rawAddress.FromOctets((uint8_t*)addr); log::info("sBluetoothAvrcpInterface: {}", fmt::ptr(sBluetoothAvrcpInterface)); - bt_status_t status = sBluetoothAvrcpInterface->set_addressed_player_cmd( - rawAddress, (uint16_t)id); + bt_status_t status = sBluetoothAvrcpInterface->set_addressed_player_cmd(rawAddress, (uint16_t)id); if (status != BT_STATUS_SUCCESS) { log::error("Failed sending setAddressedPlayerNative command, status: {}", bt_status_text(status)); @@ -1135,10 +1098,11 @@ static void setAddressedPlayerNative(JNIEnv* env, jobject /* object */, env->ReleaseByteArrayElements(address, addr, 0); } -static void playItemNative(JNIEnv* env, jobject /* object */, - jbyteArray address, jbyte scope, jlong uid, - jint uidCounter) { - if (!sBluetoothAvrcpInterface) return; +static void playItemNative(JNIEnv* env, jobject /* object */, jbyteArray address, jbyte scope, + jlong uid, jint uidCounter) { + if (!sBluetoothAvrcpInterface) { + return; + } jbyte* addr = env->GetByteArrayElements(address, NULL); if (!addr) { jniThrowIOException(env, EINVAL); @@ -1155,92 +1119,75 @@ static void playItemNative(JNIEnv* env, jobject /* object */, log::info("sBluetoothAvrcpInterface: {}", fmt::ptr(sBluetoothAvrcpInterface)); bt_status_t status = sBluetoothAvrcpInterface->play_item_cmd( - rawAddress, (uint8_t)scope, (uint8_t*)&uid, (uint16_t)uidCounter); + rawAddress, (uint8_t)scope, (uint8_t*)&uid, (uint16_t)uidCounter); if (status != BT_STATUS_SUCCESS) { - log::error("Failed sending playItemNative command, status: {}", - bt_status_text(status)); + log::error("Failed sending playItemNative command, status: {}", bt_status_text(status)); } env->ReleaseByteArrayElements(address, addr, 0); } int register_com_android_bluetooth_avrcp_controller(JNIEnv* env) { const JNINativeMethod methods[] = { - {"initNative", "()V", (void*)initNative}, - {"cleanupNative", "()V", (void*)cleanupNative}, - {"sendPassThroughCommandNative", "([BII)Z", - (void*)sendPassThroughCommandNative}, - {"sendGroupNavigationCommandNative", "([BII)Z", - (void*)sendGroupNavigationCommandNative}, - {"setPlayerApplicationSettingValuesNative", "([BB[B[B)V", - (void*)setPlayerApplicationSettingValuesNative}, - {"sendAbsVolRspNative", "([BII)V", (void*)sendAbsVolRspNative}, - {"sendRegisterAbsVolRspNative", "([BBII)V", - (void*)sendRegisterAbsVolRspNative}, - {"getCurrentMetadataNative", "([B)V", (void*)getCurrentMetadataNative}, - {"getPlaybackStateNative", "([B)V", (void*)getPlaybackStateNative}, - {"getNowPlayingListNative", "([BII)V", (void*)getNowPlayingListNative}, - {"getFolderListNative", "([BII)V", (void*)getFolderListNative}, - {"getPlayerListNative", "([BII)V", (void*)getPlayerListNative}, - {"changeFolderPathNative", "([BBJ)V", (void*)changeFolderPathNative}, - {"playItemNative", "([BBJI)V", (void*)playItemNative}, - {"setBrowsedPlayerNative", "([BI)V", (void*)setBrowsedPlayerNative}, - {"setAddressedPlayerNative", "([BI)V", (void*)setAddressedPlayerNative}, + {"initNative", "()V", (void*)initNative}, + {"cleanupNative", "()V", (void*)cleanupNative}, + {"sendPassThroughCommandNative", "([BII)Z", (void*)sendPassThroughCommandNative}, + {"sendGroupNavigationCommandNative", "([BII)Z", (void*)sendGroupNavigationCommandNative}, + {"setPlayerApplicationSettingValuesNative", "([BB[B[B)V", + (void*)setPlayerApplicationSettingValuesNative}, + {"sendAbsVolRspNative", "([BII)V", (void*)sendAbsVolRspNative}, + {"sendRegisterAbsVolRspNative", "([BBII)V", (void*)sendRegisterAbsVolRspNative}, + {"getCurrentMetadataNative", "([B)V", (void*)getCurrentMetadataNative}, + {"getPlaybackStateNative", "([B)V", (void*)getPlaybackStateNative}, + {"getNowPlayingListNative", "([BII)V", (void*)getNowPlayingListNative}, + {"getFolderListNative", "([BII)V", (void*)getFolderListNative}, + {"getPlayerListNative", "([BII)V", (void*)getPlayerListNative}, + {"changeFolderPathNative", "([BBJ)V", (void*)changeFolderPathNative}, + {"playItemNative", "([BBJI)V", (void*)playItemNative}, + {"setBrowsedPlayerNative", "([BI)V", (void*)setBrowsedPlayerNative}, + {"setAddressedPlayerNative", "([BI)V", (void*)setAddressedPlayerNative}, }; const int result = REGISTER_NATIVE_METHODS( - env, - "com/android/bluetooth/avrcpcontroller/AvrcpControllerNativeInterface", - methods); + env, "com/android/bluetooth/avrcpcontroller/AvrcpControllerNativeInterface", methods); if (result != 0) { return result; } const JNIJavaMethod javaMethods[] = { - {"onConnectionStateChanged", "(ZZ[B)V", &method_onConnectionStateChanged}, - {"getRcPsm", "([BI)V", &method_getRcPsm}, - {"handlePlayerAppSetting", "([B[BI)V", &method_handleplayerappsetting}, - {"onPlayerAppSettingChanged", "([B[BI)V", - &method_handleplayerappsettingchanged}, - {"handleSetAbsVolume", "([BBB)V", &method_handleSetAbsVolume}, - {"handleRegisterNotificationAbsVol", "([BB)V", - &method_handleRegisterNotificationAbsVol}, - {"onTrackChanged", "([BB[I[Ljava/lang/String;)V", - &method_handletrackchanged}, - {"onPlayPositionChanged", "([BII)V", &method_handleplaypositionchanged}, - {"onPlayStatusChanged", "([BB)V", &method_handleplaystatuschanged}, - {"handleGetFolderItemsRsp", - "([BI[Lcom/android/bluetooth/avrcpcontroller/AvrcpItem;)V", - &method_handleGetFolderItemsRsp}, - {"handleGetPlayerItemsRsp", - "([B[Lcom/android/bluetooth/avrcpcontroller/AvrcpPlayer;)V", - &method_handleGetPlayerItemsRsp}, - {"handleChangeFolderRsp", "([BI)V", &method_handleChangeFolderRsp}, - {"handleSetBrowsedPlayerRsp", "([BII)V", - &method_handleSetBrowsedPlayerRsp}, - {"handleSetAddressedPlayerRsp", "([BI)V", - &method_handleSetAddressedPlayerRsp}, - {"handleAddressedPlayerChanged", "([BI)V", - &method_handleAddressedPlayerChanged}, - {"handleNowPlayingContentChanged", "([B)V", - &method_handleNowPlayingContentChanged}, - {"onAvailablePlayerChanged", "([B)V", &method_onAvailablePlayerChanged}, - // Fetch static method - {"createFromNativeMediaItem", - "([BJILjava/lang/String;[I[Ljava/lang/String;)" - "Lcom/android/bluetooth/avrcpcontroller/AvrcpItem;", - &method_createFromNativeMediaItem, true}, - {"createFromNativeFolderItem", - "([BJILjava/lang/String;I)" - "Lcom/android/bluetooth/avrcpcontroller/AvrcpItem;", - &method_createFromNativeFolderItem, true}, - {"createFromNativePlayerItem", - "([BILjava/lang/String;[BII)" - "Lcom/android/bluetooth/avrcpcontroller/AvrcpPlayer;", - &method_createFromNativePlayerItem, true}, + {"onConnectionStateChanged", "(ZZ[B)V", &method_onConnectionStateChanged}, + {"getRcPsm", "([BI)V", &method_getRcPsm}, + {"handlePlayerAppSetting", "([B[BI)V", &method_handleplayerappsetting}, + {"onPlayerAppSettingChanged", "([B[BI)V", &method_handleplayerappsettingchanged}, + {"handleSetAbsVolume", "([BBB)V", &method_handleSetAbsVolume}, + {"handleRegisterNotificationAbsVol", "([BB)V", &method_handleRegisterNotificationAbsVol}, + {"onTrackChanged", "([BB[I[Ljava/lang/String;)V", &method_handletrackchanged}, + {"onPlayPositionChanged", "([BII)V", &method_handleplaypositionchanged}, + {"onPlayStatusChanged", "([BB)V", &method_handleplaystatuschanged}, + {"handleGetFolderItemsRsp", "([BI[Lcom/android/bluetooth/avrcpcontroller/AvrcpItem;)V", + &method_handleGetFolderItemsRsp}, + {"handleGetPlayerItemsRsp", "([B[Lcom/android/bluetooth/avrcpcontroller/AvrcpPlayer;)V", + &method_handleGetPlayerItemsRsp}, + {"handleChangeFolderRsp", "([BI)V", &method_handleChangeFolderRsp}, + {"handleSetBrowsedPlayerRsp", "([BII)V", &method_handleSetBrowsedPlayerRsp}, + {"handleSetAddressedPlayerRsp", "([BI)V", &method_handleSetAddressedPlayerRsp}, + {"handleAddressedPlayerChanged", "([BI)V", &method_handleAddressedPlayerChanged}, + {"handleNowPlayingContentChanged", "([B)V", &method_handleNowPlayingContentChanged}, + {"onAvailablePlayerChanged", "([B)V", &method_onAvailablePlayerChanged}, + // Fetch static method + {"createFromNativeMediaItem", + "([BJILjava/lang/String;[I[Ljava/lang/String;)" + "Lcom/android/bluetooth/avrcpcontroller/AvrcpItem;", + &method_createFromNativeMediaItem, true}, + {"createFromNativeFolderItem", + "([BJILjava/lang/String;I)" + "Lcom/android/bluetooth/avrcpcontroller/AvrcpItem;", + &method_createFromNativeFolderItem, true}, + {"createFromNativePlayerItem", + "([BILjava/lang/String;[BII)" + "Lcom/android/bluetooth/avrcpcontroller/AvrcpPlayer;", + &method_createFromNativePlayerItem, true}, }; - GET_JAVA_METHODS( - env, - "com/android/bluetooth/avrcpcontroller/AvrcpControllerNativeInterface", - javaMethods); + GET_JAVA_METHODS(env, "com/android/bluetooth/avrcpcontroller/AvrcpControllerNativeInterface", + javaMethods); return 0; } } // namespace android diff --git a/android/app/jni/com_android_bluetooth_avrcp_target.cpp b/android/app/jni/com_android_bluetooth_avrcp_target.cpp index 671be393385..6f6b599667b 100644 --- a/android/app/jni/com_android_bluetooth_avrcp_target.cpp +++ b/android/app/jni/com_android_bluetooth_avrcp_target.cpp @@ -49,37 +49,29 @@ static std::vector getMediaPlayerList(); using SetBrowsedPlayerCb = MediaInterface::SetBrowsedPlayerCallback; static void setBrowsedPlayer(uint16_t player_id, SetBrowsedPlayerCb); using GetFolderItemsCb = MediaInterface::FolderItemsCallback; -static void getFolderItems(uint16_t player_id, std::string media_id, - GetFolderItemsCb cb); -static void playItem(uint16_t player_id, bool now_playing, - std::string media_id); +static void getFolderItems(uint16_t player_id, std::string media_id, GetFolderItemsCb cb); +static void playItem(uint16_t player_id, bool now_playing, std::string media_id); static void setActiveDevice(const RawAddress& address); static void volumeDeviceConnected(const RawAddress& address); -static void volumeDeviceConnected( - const RawAddress& address, - ::bluetooth::avrcp::VolumeInterface::VolumeChangedCb cb); +static void volumeDeviceConnected(const RawAddress& address, + ::bluetooth::avrcp::VolumeInterface::VolumeChangedCb cb); static void volumeDeviceDisconnected(const RawAddress& address); static void setVolume(int8_t volume); -using ListPlayerSettingsCb = - PlayerSettingsInterface::ListPlayerSettingsCallback; +using ListPlayerSettingsCb = PlayerSettingsInterface::ListPlayerSettingsCallback; static void listPlayerSettings(ListPlayerSettingsCb cb); ListPlayerSettingsCb list_player_settings_cb; -using ListPlayerSettingValuesCb = - PlayerSettingsInterface::ListPlayerSettingValuesCallback; -static void listPlayerSettingValues(PlayerAttribute setting, - ListPlayerSettingValuesCb cb); +using ListPlayerSettingValuesCb = PlayerSettingsInterface::ListPlayerSettingValuesCallback; +static void listPlayerSettingValues(PlayerAttribute setting, ListPlayerSettingValuesCb cb); ListPlayerSettingValuesCb list_player_setting_values_cb; using GetCurrentPlayerSettingValueCb = - PlayerSettingsInterface::GetCurrentPlayerSettingValueCallback; + PlayerSettingsInterface::GetCurrentPlayerSettingValueCallback; static void getPlayerSettings(std::vector attributes, GetCurrentPlayerSettingValueCb cb); GetCurrentPlayerSettingValueCb get_current_player_setting_value_cb; -using SetPlayerSettingValueCb = - PlayerSettingsInterface::SetPlayerSettingValueCallback; -static void setPlayerSettings(std::vector attributes, - std::vector values, +using SetPlayerSettingValueCb = PlayerSettingsInterface::SetPlayerSettingValueCallback; +static void setPlayerSettings(std::vector attributes, std::vector values, SetPlayerSettingValueCb cb); SetPlayerSettingValueCb set_player_setting_value_cb; @@ -89,14 +81,14 @@ SetPlayerSettingValueCb set_player_setting_value_cb; SetBrowsedPlayerCb set_browsed_player_cb; using map_entry = std::pair; std::map get_folder_items_cb_map; -std::map - volumeCallbackMap; +std::map volumeCallbackMap; template -void copyJavaArraytoCppVector(JNIEnv* env, const jbyteArray& jArray, - std::vector& cVec) { +void copyJavaArraytoCppVector(JNIEnv* env, const jbyteArray& jArray, std::vector& cVec) { size_t len = (size_t)env->GetArrayLength(jArray); - if (len == 0) return; + if (len == 0) { + return; + } jbyte* elements = env->GetByteArrayElements(jArray, nullptr); T* array = reinterpret_cast(elements); cVec.reserve(len); @@ -108,10 +100,8 @@ void copyJavaArraytoCppVector(JNIEnv* env, const jbyteArray& jArray, // all calls happen on the JNI Thread. Right now this is very difficult // as it is hard to get a handle on the JNI thread from here. class AvrcpMediaInterfaceImpl : public MediaInterface { - public: - void SendKeyEvent(uint8_t key, KeyState state) { - sendMediaKeyEvent(key, state); - } +public: + void SendKeyEvent(uint8_t key, KeyState state) { sendMediaKeyEvent(key, state); } void GetSongInfo(SongInfoCallback cb) override { auto info = getSongInfo(); @@ -140,8 +130,7 @@ class AvrcpMediaInterfaceImpl : public MediaInterface { getFolderItems(player_id, media_id, folder_cb); } - void SetBrowsedPlayer(uint16_t player_id, - SetBrowsedPlayerCallback browse_cb) override { + void SetBrowsedPlayer(uint16_t player_id, SetBrowsedPlayerCallback browse_cb) override { setBrowsedPlayer(player_id, browse_cb); } @@ -154,43 +143,33 @@ class AvrcpMediaInterfaceImpl : public MediaInterface { mServiceCallbacks = nullptr; } - void PlayItem(uint16_t player_id, bool now_playing, - std::string media_id) override { + void PlayItem(uint16_t player_id, bool now_playing, std::string media_id) override { playItem(player_id, now_playing, media_id); } - void SetActiveDevice(const RawAddress& address) override { - setActiveDevice(address); - } + void SetActiveDevice(const RawAddress& address) override { setActiveDevice(address); } }; static AvrcpMediaInterfaceImpl mAvrcpInterface; class VolumeInterfaceImpl : public VolumeInterface { - public: - void DeviceConnected(const RawAddress& bdaddr) override { - volumeDeviceConnected(bdaddr); - } +public: + void DeviceConnected(const RawAddress& bdaddr) override { volumeDeviceConnected(bdaddr); } void DeviceConnected(const RawAddress& bdaddr, VolumeChangedCb cb) override { volumeDeviceConnected(bdaddr, cb); } - void DeviceDisconnected(const RawAddress& bdaddr) override { - volumeDeviceDisconnected(bdaddr); - } + void DeviceDisconnected(const RawAddress& bdaddr) override { volumeDeviceDisconnected(bdaddr); } void SetVolume(int8_t volume) override { setVolume(volume); } }; static VolumeInterfaceImpl mVolumeInterface; class PlayerSettingsInterfaceImpl : public PlayerSettingsInterface { - public: - void ListPlayerSettings(ListPlayerSettingsCallback cb) { - listPlayerSettings(cb); - } +public: + void ListPlayerSettings(ListPlayerSettingsCallback cb) { listPlayerSettings(cb); } - void ListPlayerSettingValues(PlayerAttribute setting, - ListPlayerSettingValuesCallback cb) { + void ListPlayerSettingValues(PlayerAttribute setting, ListPlayerSettingValuesCallback cb) { listPlayerSettingValues(setting, cb); } @@ -199,8 +178,7 @@ class PlayerSettingsInterfaceImpl : public PlayerSettingsInterface { getPlayerSettings(attributes, cb); } - void SetPlayerSettings(std::vector attributes, - std::vector values, + void SetPlayerSettings(std::vector attributes, std::vector values, SetPlayerSettingValueCallback cb) { setPlayerSettings(attributes, values, cb); } @@ -239,12 +217,10 @@ static void initNative(JNIEnv* env, jobject object) { mJavaInterface = env->NewGlobalRef(object); sServiceInterface = getBluetoothInterface()->get_avrcp_service(); - sServiceInterface->Init(&mAvrcpInterface, &mVolumeInterface, - &mPlayerSettingsInterface); + sServiceInterface->Init(&mAvrcpInterface, &mVolumeInterface, &mPlayerSettingsInterface); } -static void registerBipServerNative(JNIEnv* /* env */, jobject /* object */, - jint l2cap_psm) { +static void registerBipServerNative(JNIEnv* /* env */, jobject /* object */, jint l2cap_psm) { log::debug("l2cap_psm={}", (int)l2cap_psm); std::unique_lock interface_lock(interface_mutex); if (sServiceInterface == nullptr) { @@ -264,9 +240,8 @@ static void unregisterBipServerNative(JNIEnv* /* env */, jobject /* object */) { sServiceInterface->UnregisterBipServer(); } -static void sendMediaUpdateNative(JNIEnv* /* env */, jobject /* object */, - jboolean metadata, jboolean state, - jboolean queue) { +static void sendMediaUpdateNative(JNIEnv* /* env */, jobject /* object */, jboolean metadata, + jboolean state, jboolean queue) { log::debug(""); std::unique_lock interface_lock(interface_mutex); if (mServiceCallbacks == nullptr) { @@ -274,13 +249,12 @@ static void sendMediaUpdateNative(JNIEnv* /* env */, jobject /* object */, return; } - mServiceCallbacks->SendMediaUpdate(metadata == JNI_TRUE, state == JNI_TRUE, - queue == JNI_TRUE); + mServiceCallbacks->SendMediaUpdate(metadata == JNI_TRUE, state == JNI_TRUE, queue == JNI_TRUE); } static void sendFolderUpdateNative(JNIEnv* /* env */, jobject /* object */, - jboolean available_players, - jboolean addressed_player, jboolean uids) { + jboolean available_players, jboolean addressed_player, + jboolean uids) { log::debug(""); std::unique_lock interface_lock(interface_mutex); if (mServiceCallbacks == nullptr) { @@ -288,8 +262,7 @@ static void sendFolderUpdateNative(JNIEnv* /* env */, jobject /* object */, return; } - mServiceCallbacks->SendFolderUpdate(available_players == JNI_TRUE, - addressed_player == JNI_TRUE, + mServiceCallbacks->SendFolderUpdate(available_players == JNI_TRUE, addressed_player == JNI_TRUE, uids == JNI_TRUE); } @@ -307,8 +280,7 @@ static void cleanupNative(JNIEnv* env, jobject /* object */) { sServiceInterface = nullptr; } -jboolean connectDeviceNative(JNIEnv* env, jobject /* object */, - jstring address) { +jboolean connectDeviceNative(JNIEnv* env, jobject /* object */, jstring address) { log::debug(""); std::unique_lock interface_lock(interface_mutex); if (mServiceCallbacks == nullptr) { @@ -321,14 +293,14 @@ jboolean connectDeviceNative(JNIEnv* env, jobject /* object */, bool success = RawAddress::FromString(tmp_addr, bdaddr); env->ReleaseStringUTFChars(address, tmp_addr); - if (!success) return JNI_FALSE; + if (!success) { + return JNI_FALSE; + } - return sServiceInterface->ConnectDevice(bdaddr) == true ? JNI_TRUE - : JNI_FALSE; + return sServiceInterface->ConnectDevice(bdaddr) == true ? JNI_TRUE : JNI_FALSE; } -jboolean disconnectDeviceNative(JNIEnv* env, jobject /* object */, - jstring address) { +jboolean disconnectDeviceNative(JNIEnv* env, jobject /* object */, jstring address) { log::debug(""); std::unique_lock interface_lock(interface_mutex); if (mServiceCallbacks == nullptr) { @@ -341,32 +313,35 @@ jboolean disconnectDeviceNative(JNIEnv* env, jobject /* object */, bool success = RawAddress::FromString(tmp_addr, bdaddr); env->ReleaseStringUTFChars(address, tmp_addr); - if (!success) return JNI_FALSE; + if (!success) { + return JNI_FALSE; + } - return sServiceInterface->DisconnectDevice(bdaddr) == true ? JNI_TRUE - : JNI_FALSE; + return sServiceInterface->DisconnectDevice(bdaddr) == true ? JNI_TRUE : JNI_FALSE; } static void sendMediaKeyEvent(int key, KeyState state) { log::debug(""); std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mJavaInterface) return; - sCallbackEnv->CallVoidMethod( - mJavaInterface, method_sendMediaKeyEvent, key, - state == KeyState::PUSHED ? JNI_TRUE : JNI_FALSE); + if (!sCallbackEnv.valid() || !mJavaInterface) { + return; + } + sCallbackEnv->CallVoidMethod(mJavaInterface, method_sendMediaKeyEvent, key, + state == KeyState::PUSHED ? JNI_TRUE : JNI_FALSE); } static std::string getImageHandleFromJavaObj(JNIEnv* env, jobject image) { std::string handle; - if (image == nullptr) return handle; + if (image == nullptr) { + return handle; + } jclass class_image = env->GetObjectClass(image); jmethodID method_getImageHandle = - env->GetMethodID(class_image, "getImageHandle", "()Ljava/lang/String;"); - jstring imageHandle = (jstring) env->CallObjectMethod( - image, method_getImageHandle); + env->GetMethodID(class_image, "getImageHandle", "()Ljava/lang/String;"); + jstring imageHandle = (jstring)env->CallObjectMethod(image, method_getImageHandle); if (imageHandle == nullptr) { return handle; } @@ -381,27 +356,21 @@ static std::string getImageHandleFromJavaObj(JNIEnv* env, jobject image) { static SongInfo getSongInfoFromJavaObj(JNIEnv* env, jobject metadata) { SongInfo info; - if (metadata == nullptr) return info; + if (metadata == nullptr) { + return info; + } jclass class_metadata = env->GetObjectClass(metadata); - jfieldID field_mediaId = - env->GetFieldID(class_metadata, "mediaId", "Ljava/lang/String;"); - jfieldID field_title = - env->GetFieldID(class_metadata, "title", "Ljava/lang/String;"); - jfieldID field_artist = - env->GetFieldID(class_metadata, "artist", "Ljava/lang/String;"); - jfieldID field_album = - env->GetFieldID(class_metadata, "album", "Ljava/lang/String;"); - jfieldID field_trackNum = - env->GetFieldID(class_metadata, "trackNum", "Ljava/lang/String;"); - jfieldID field_numTracks = - env->GetFieldID(class_metadata, "numTracks", "Ljava/lang/String;"); - jfieldID field_genre = - env->GetFieldID(class_metadata, "genre", "Ljava/lang/String;"); - jfieldID field_playingTime = - env->GetFieldID(class_metadata, "duration", "Ljava/lang/String;"); + jfieldID field_mediaId = env->GetFieldID(class_metadata, "mediaId", "Ljava/lang/String;"); + jfieldID field_title = env->GetFieldID(class_metadata, "title", "Ljava/lang/String;"); + jfieldID field_artist = env->GetFieldID(class_metadata, "artist", "Ljava/lang/String;"); + jfieldID field_album = env->GetFieldID(class_metadata, "album", "Ljava/lang/String;"); + jfieldID field_trackNum = env->GetFieldID(class_metadata, "trackNum", "Ljava/lang/String;"); + jfieldID field_numTracks = env->GetFieldID(class_metadata, "numTracks", "Ljava/lang/String;"); + jfieldID field_genre = env->GetFieldID(class_metadata, "genre", "Ljava/lang/String;"); + jfieldID field_playingTime = env->GetFieldID(class_metadata, "duration", "Ljava/lang/String;"); jfieldID field_image = - env->GetFieldID(class_metadata, "image", "Lcom/android/bluetooth/audio_util/Image;"); + env->GetFieldID(class_metadata, "image", "Lcom/android/bluetooth/audio_util/Image;"); jstring jstr = (jstring)env->GetObjectField(metadata, field_mediaId); if (jstr != nullptr) { @@ -414,8 +383,7 @@ static SongInfo getSongInfoFromJavaObj(JNIEnv* env, jobject metadata) { jstr = (jstring)env->GetObjectField(metadata, field_title); if (jstr != nullptr) { const char* value = env->GetStringUTFChars(jstr, nullptr); - info.attributes.insert( - AttributeEntry(Attribute::TITLE, std::string(value))); + info.attributes.insert(AttributeEntry(Attribute::TITLE, std::string(value))); env->ReleaseStringUTFChars(jstr, value); env->DeleteLocalRef(jstr); } @@ -423,8 +391,7 @@ static SongInfo getSongInfoFromJavaObj(JNIEnv* env, jobject metadata) { jstr = (jstring)env->GetObjectField(metadata, field_artist); if (jstr != nullptr) { const char* value = env->GetStringUTFChars(jstr, nullptr); - info.attributes.insert( - AttributeEntry(Attribute::ARTIST_NAME, std::string(value))); + info.attributes.insert(AttributeEntry(Attribute::ARTIST_NAME, std::string(value))); env->ReleaseStringUTFChars(jstr, value); env->DeleteLocalRef(jstr); } @@ -432,8 +399,7 @@ static SongInfo getSongInfoFromJavaObj(JNIEnv* env, jobject metadata) { jstr = (jstring)env->GetObjectField(metadata, field_album); if (jstr != nullptr) { const char* value = env->GetStringUTFChars(jstr, nullptr); - info.attributes.insert( - AttributeEntry(Attribute::ALBUM_NAME, std::string(value))); + info.attributes.insert(AttributeEntry(Attribute::ALBUM_NAME, std::string(value))); env->ReleaseStringUTFChars(jstr, value); env->DeleteLocalRef(jstr); } @@ -441,8 +407,7 @@ static SongInfo getSongInfoFromJavaObj(JNIEnv* env, jobject metadata) { jstr = (jstring)env->GetObjectField(metadata, field_trackNum); if (jstr != nullptr) { const char* value = env->GetStringUTFChars(jstr, nullptr); - info.attributes.insert( - AttributeEntry(Attribute::TRACK_NUMBER, std::string(value))); + info.attributes.insert(AttributeEntry(Attribute::TRACK_NUMBER, std::string(value))); env->ReleaseStringUTFChars(jstr, value); env->DeleteLocalRef(jstr); } @@ -450,8 +415,7 @@ static SongInfo getSongInfoFromJavaObj(JNIEnv* env, jobject metadata) { jstr = (jstring)env->GetObjectField(metadata, field_numTracks); if (jstr != nullptr) { const char* value = env->GetStringUTFChars(jstr, nullptr); - info.attributes.insert( - AttributeEntry(Attribute::TOTAL_NUMBER_OF_TRACKS, std::string(value))); + info.attributes.insert(AttributeEntry(Attribute::TOTAL_NUMBER_OF_TRACKS, std::string(value))); env->ReleaseStringUTFChars(jstr, value); env->DeleteLocalRef(jstr); } @@ -459,8 +423,7 @@ static SongInfo getSongInfoFromJavaObj(JNIEnv* env, jobject metadata) { jstr = (jstring)env->GetObjectField(metadata, field_genre); if (jstr != nullptr) { const char* value = env->GetStringUTFChars(jstr, nullptr); - info.attributes.insert( - AttributeEntry(Attribute::GENRE, std::string(value))); + info.attributes.insert(AttributeEntry(Attribute::GENRE, std::string(value))); env->ReleaseStringUTFChars(jstr, value); env->DeleteLocalRef(jstr); } @@ -468,8 +431,7 @@ static SongInfo getSongInfoFromJavaObj(JNIEnv* env, jobject metadata) { jstr = (jstring)env->GetObjectField(metadata, field_playingTime); if (jstr != nullptr) { const char* value = env->GetStringUTFChars(jstr, nullptr); - info.attributes.insert( - AttributeEntry(Attribute::PLAYING_TIME, std::string(value))); + info.attributes.insert(AttributeEntry(Attribute::PLAYING_TIME, std::string(value))); env->ReleaseStringUTFChars(jstr, value); env->DeleteLocalRef(jstr); } @@ -478,8 +440,7 @@ static SongInfo getSongInfoFromJavaObj(JNIEnv* env, jobject metadata) { if (object_image != nullptr) { std::string imageHandle = getImageHandleFromJavaObj(env, object_image); if (!imageHandle.empty()) { - info.attributes.insert( - AttributeEntry(Attribute::DEFAULT_COVER_ART, imageHandle)); + info.attributes.insert(AttributeEntry(Attribute::DEFAULT_COVER_ART, imageHandle)); } env->DeleteLocalRef(object_image); } @@ -491,11 +452,9 @@ static FolderInfo getFolderInfoFromJavaObj(JNIEnv* env, jobject folder) { FolderInfo info; jclass class_folder = env->GetObjectClass(folder); - jfieldID field_mediaId = - env->GetFieldID(class_folder, "mediaId", "Ljava/lang/String;"); + jfieldID field_mediaId = env->GetFieldID(class_folder, "mediaId", "Ljava/lang/String;"); jfieldID field_isPlayable = env->GetFieldID(class_folder, "isPlayable", "Z"); - jfieldID field_name = - env->GetFieldID(class_folder, "title", "Ljava/lang/String;"); + jfieldID field_name = env->GetFieldID(class_folder, "title", "Ljava/lang/String;"); jstring jstr = (jstring)env->GetObjectField(folder, field_mediaId); if (jstr != nullptr) { @@ -522,10 +481,11 @@ static SongInfo getSongInfo() { log::debug(""); std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mJavaInterface) return SongInfo(); + if (!sCallbackEnv.valid() || !mJavaInterface) { + return SongInfo(); + } - jobject metadata = - sCallbackEnv->CallObjectMethod(mJavaInterface, method_getCurrentSongInfo); + jobject metadata = sCallbackEnv->CallObjectMethod(mJavaInterface, method_getCurrentSongInfo); SongInfo info = getSongInfoFromJavaObj(sCallbackEnv.get(), metadata); sCallbackEnv->DeleteLocalRef(metadata); return info; @@ -535,11 +495,12 @@ static PlayStatus getCurrentPlayStatus() { log::debug(""); std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mJavaInterface) return PlayStatus(); + if (!sCallbackEnv.valid() || !mJavaInterface) { + return PlayStatus(); + } PlayStatus status; - jobject playStatus = - sCallbackEnv->CallObjectMethod(mJavaInterface, method_getPlaybackStatus); + jobject playStatus = sCallbackEnv->CallObjectMethod(mJavaInterface, method_getPlaybackStatus); if (playStatus == nullptr) { log::error("Got a null play status"); @@ -547,12 +508,9 @@ static PlayStatus getCurrentPlayStatus() { } jclass class_playStatus = sCallbackEnv->GetObjectClass(playStatus); - jfieldID field_position = - sCallbackEnv->GetFieldID(class_playStatus, "position", "J"); - jfieldID field_duration = - sCallbackEnv->GetFieldID(class_playStatus, "duration", "J"); - jfieldID field_state = - sCallbackEnv->GetFieldID(class_playStatus, "state", "B"); + jfieldID field_position = sCallbackEnv->GetFieldID(class_playStatus, "position", "J"); + jfieldID field_duration = sCallbackEnv->GetFieldID(class_playStatus, "duration", "J"); + jfieldID field_state = sCallbackEnv->GetFieldID(class_playStatus, "state", "B"); status.position = sCallbackEnv->GetLongField(playStatus, field_position); status.duration = sCallbackEnv->GetLongField(playStatus, field_duration); @@ -567,10 +525,12 @@ static std::string getCurrentMediaId() { log::debug(""); std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mJavaInterface) return ""; + if (!sCallbackEnv.valid() || !mJavaInterface) { + return ""; + } - jstring media_id = (jstring)sCallbackEnv->CallObjectMethod( - mJavaInterface, method_getCurrentMediaId); + jstring media_id = + (jstring)sCallbackEnv->CallObjectMethod(mJavaInterface, method_getCurrentMediaId); if (media_id == nullptr) { log::error("Got a null media ID"); return ""; @@ -587,18 +547,18 @@ static std::vector getNowPlayingList() { log::debug(""); std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mJavaInterface) return std::vector(); + if (!sCallbackEnv.valid() || !mJavaInterface) { + return std::vector(); + } - jobject song_list = - sCallbackEnv->CallObjectMethod(mJavaInterface, method_getNowPlayingList); + jobject song_list = sCallbackEnv->CallObjectMethod(mJavaInterface, method_getNowPlayingList); if (song_list == nullptr) { log::error("Got a null now playing list"); return std::vector(); } jclass class_list = sCallbackEnv->GetObjectClass(song_list); - jmethodID method_get = - sCallbackEnv->GetMethodID(class_list, "get", "(I)Ljava/lang/Object;"); + jmethodID method_get = sCallbackEnv->GetMethodID(class_list, "get", "(I)Ljava/lang/Object;"); jmethodID method_size = sCallbackEnv->GetMethodID(class_list, "size", "()I"); auto size = sCallbackEnv->CallIntMethod(song_list, method_size); @@ -622,23 +582,25 @@ static uint16_t getCurrentPlayerId() { log::debug(""); std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mJavaInterface) return 0u; + if (!sCallbackEnv.valid() || !mJavaInterface) { + return 0u; + } - jint id = - sCallbackEnv->CallIntMethod(mJavaInterface, method_getCurrentPlayerId); + jint id = sCallbackEnv->CallIntMethod(mJavaInterface, method_getCurrentPlayerId); - return (static_cast(id) & 0xFFFF); + return static_cast(id) & 0xFFFF; } static std::vector getMediaPlayerList() { log::debug(""); std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mJavaInterface) + if (!sCallbackEnv.valid() || !mJavaInterface) { return std::vector(); + } - jobject player_list = (jobject)sCallbackEnv->CallObjectMethod( - mJavaInterface, method_getMediaPlayerList); + jobject player_list = + (jobject)sCallbackEnv->CallObjectMethod(mJavaInterface, method_getMediaPlayerList); if (player_list == nullptr) { log::error("Got a null media player list"); @@ -646,8 +608,7 @@ static std::vector getMediaPlayerList() { } jclass class_list = sCallbackEnv->GetObjectClass(player_list); - jmethodID method_get = - sCallbackEnv->GetMethodID(class_list, "get", "(I)Ljava/lang/Object;"); + jmethodID method_get = sCallbackEnv->GetMethodID(class_list, "get", "(I)Ljava/lang/Object;"); jmethodID method_size = sCallbackEnv->GetMethodID(class_list, "size", "()I"); jint list_size = sCallbackEnv->CallIntMethod(player_list, method_size); @@ -656,15 +617,11 @@ static std::vector getMediaPlayerList() { return std::vector(); } - jobject player_info = - sCallbackEnv->CallObjectMethod(player_list, method_get, 0); + jobject player_info = sCallbackEnv->CallObjectMethod(player_list, method_get, 0); jclass class_playerInfo = sCallbackEnv->GetObjectClass(player_info); - jfieldID field_playerId = - sCallbackEnv->GetFieldID(class_playerInfo, "id", "I"); - jfieldID field_name = - sCallbackEnv->GetFieldID(class_playerInfo, "name", "Ljava/lang/String;"); - jfieldID field_browsable = - sCallbackEnv->GetFieldID(class_playerInfo, "browsable", "Z"); + jfieldID field_playerId = sCallbackEnv->GetFieldID(class_playerInfo, "id", "I"); + jfieldID field_name = sCallbackEnv->GetFieldID(class_playerInfo, "name", "Ljava/lang/String;"); + jfieldID field_browsable = sCallbackEnv->GetFieldID(class_playerInfo, "browsable", "Z"); std::vector ret_list; for (jsize i = 0; i < list_size; i++) { @@ -682,9 +639,7 @@ static std::vector getMediaPlayerList() { } temp.browsing_supported = - sCallbackEnv->GetBooleanField(player, field_browsable) == JNI_TRUE - ? true - : false; + sCallbackEnv->GetBooleanField(player, field_browsable) == JNI_TRUE ? true : false; ret_list.push_back(std::move(temp)); sCallbackEnv->DeleteLocalRef(player); @@ -700,17 +655,16 @@ static void setBrowsedPlayer(uint16_t player_id, SetBrowsedPlayerCb cb) { log::debug(""); std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mJavaInterface) return; + if (!sCallbackEnv.valid() || !mJavaInterface) { + return; + } set_browsed_player_cb = cb; - sCallbackEnv->CallVoidMethod(mJavaInterface, method_setBrowsedPlayer, - player_id); + sCallbackEnv->CallVoidMethod(mJavaInterface, method_setBrowsedPlayer, player_id); } -static void setBrowsedPlayerResponseNative(JNIEnv* env, jobject /* object */, - jint /* player_id */, - jboolean success, jstring root_id, - jint num_items) { +static void setBrowsedPlayerResponseNative(JNIEnv* env, jobject /* object */, jint /* player_id */, + jboolean success, jstring root_id, jint num_items) { log::debug(""); std::string root; @@ -723,8 +677,8 @@ static void setBrowsedPlayerResponseNative(JNIEnv* env, jobject /* object */, set_browsed_player_cb.Run(success == JNI_TRUE, root, num_items); } -static void getFolderItemsResponseNative(JNIEnv* env, jobject /* object */, - jstring parent_id, jobject list) { +static void getFolderItemsResponseNative(JNIEnv* env, jobject /* object */, jstring parent_id, + jobject list) { log::debug(""); std::string id; @@ -739,8 +693,7 @@ static void getFolderItemsResponseNative(JNIEnv* env, jobject /* object */, // that both callbacks can be handled with one lookup if a request comes // for a folder that is already trying to be looked at. if (get_folder_items_cb_map.find(id) == get_folder_items_cb_map.end()) { - log::error("Could not find response callback for the request of \"{}\"", - id); + log::error("Could not find response callback for the request of \"{}\"", id); return; } @@ -754,8 +707,7 @@ static void getFolderItemsResponseNative(JNIEnv* env, jobject /* object */, } jclass class_list = env->GetObjectClass(list); - jmethodID method_get = - env->GetMethodID(class_list, "get", "(I)Ljava/lang/Object;"); + jmethodID method_get = env->GetMethodID(class_list, "get", "(I)Ljava/lang/Object;"); jmethodID method_size = env->GetMethodID(class_list, "size", "()I"); jint list_size = env->CallIntMethod(list, method_size); @@ -767,10 +719,10 @@ static void getFolderItemsResponseNative(JNIEnv* env, jobject /* object */, jobject list_item = env->CallObjectMethod(list, method_get, 0); jclass class_listItem = env->GetObjectClass(list_item); jfieldID field_isFolder = env->GetFieldID(class_listItem, "isFolder", "Z"); - jfieldID field_folder = env->GetFieldID( - class_listItem, "folder", "Lcom/android/bluetooth/audio_util/Folder;"); - jfieldID field_song = env->GetFieldID( - class_listItem, "song", "Lcom/android/bluetooth/audio_util/Metadata;"); + jfieldID field_folder = + env->GetFieldID(class_listItem, "folder", "Lcom/android/bluetooth/audio_util/Folder;"); + jfieldID field_song = + env->GetFieldID(class_listItem, "song", "Lcom/android/bluetooth/audio_util/Metadata;"); std::vector ret_list; for (jsize i = 0; i < list_size; i++) { @@ -780,15 +732,12 @@ static void getFolderItemsResponseNative(JNIEnv* env, jobject /* object */, if (is_folder) { jobject folder = env->GetObjectField(item, field_folder); - ListItem temp = {ListItem::FOLDER, - getFolderInfoFromJavaObj(env, folder), - SongInfo()}; + ListItem temp = {ListItem::FOLDER, getFolderInfoFromJavaObj(env, folder), SongInfo()}; ret_list.push_back(temp); env->DeleteLocalRef(folder); } else { jobject song = env->GetObjectField(item, field_song); - ListItem temp = {ListItem::SONG, FolderInfo(), - getSongInfoFromJavaObj(env, song)}; + ListItem temp = {ListItem::SONG, FolderInfo(), getSongInfoFromJavaObj(env, song)}; ret_list.push_back(temp); env->DeleteLocalRef(song); } @@ -800,28 +749,29 @@ static void getFolderItemsResponseNative(JNIEnv* env, jobject /* object */, callback.Run(std::move(ret_list)); } -static void getFolderItems(uint16_t player_id, std::string media_id, - GetFolderItemsCb cb) { +static void getFolderItems(uint16_t player_id, std::string media_id, GetFolderItemsCb cb) { log::debug(""); std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mJavaInterface) return; + if (!sCallbackEnv.valid() || !mJavaInterface) { + return; + } // TODO (apanicke): Fix a potential media_id collision if two media players // use the same media_id scheme or two devices browse the same content. get_folder_items_cb_map.insert(map_entry(media_id, cb)); jstring j_media_id = sCallbackEnv->NewStringUTF(media_id.c_str()); - sCallbackEnv->CallVoidMethod(mJavaInterface, method_getFolderItemsRequest, - player_id, j_media_id); + sCallbackEnv->CallVoidMethod(mJavaInterface, method_getFolderItemsRequest, player_id, j_media_id); } -static void playItem(uint16_t player_id, bool now_playing, - std::string media_id) { +static void playItem(uint16_t player_id, bool now_playing, std::string media_id) { log::debug(""); std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mJavaInterface) return; + if (!sCallbackEnv.valid() || !mJavaInterface) { + return; + } jstring j_media_id = sCallbackEnv->NewStringUTF(media_id.c_str()); sCallbackEnv->CallVoidMethod(mJavaInterface, method_playItem, player_id, @@ -832,60 +782,65 @@ static void setActiveDevice(const RawAddress& address) { log::debug(""); std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mJavaInterface) return; + if (!sCallbackEnv.valid() || !mJavaInterface) { + return; + } jstring j_bdaddr = sCallbackEnv->NewStringUTF(address.ToString().c_str()); - sCallbackEnv->CallVoidMethod(mJavaInterface, method_setActiveDevice, - j_bdaddr); + sCallbackEnv->CallVoidMethod(mJavaInterface, method_setActiveDevice, j_bdaddr); } static void volumeDeviceConnected(const RawAddress& address) { log::debug(""); std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mJavaInterface) return; + if (!sCallbackEnv.valid() || !mJavaInterface) { + return; + } jstring j_bdaddr = sCallbackEnv->NewStringUTF(address.ToString().c_str()); - sCallbackEnv->CallVoidMethod(mJavaInterface, method_volumeDeviceConnected, - j_bdaddr, JNI_FALSE); + sCallbackEnv->CallVoidMethod(mJavaInterface, method_volumeDeviceConnected, j_bdaddr, JNI_FALSE); } -static void volumeDeviceConnected( - const RawAddress& address, - ::bluetooth::avrcp::VolumeInterface::VolumeChangedCb cb) { +static void volumeDeviceConnected(const RawAddress& address, + ::bluetooth::avrcp::VolumeInterface::VolumeChangedCb cb) { log::debug(""); std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mJavaInterface) return; + if (!sCallbackEnv.valid() || !mJavaInterface) { + return; + } volumeCallbackMap.emplace(address, cb); jstring j_bdaddr = sCallbackEnv->NewStringUTF(address.ToString().c_str()); - sCallbackEnv->CallVoidMethod(mJavaInterface, method_volumeDeviceConnected, - j_bdaddr, JNI_TRUE); + sCallbackEnv->CallVoidMethod(mJavaInterface, method_volumeDeviceConnected, j_bdaddr, JNI_TRUE); } static void volumeDeviceDisconnected(const RawAddress& address) { log::debug(""); std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mJavaInterface) return; + if (!sCallbackEnv.valid() || !mJavaInterface) { + return; + } volumeCallbackMap.erase(address); jstring j_bdaddr = sCallbackEnv->NewStringUTF(address.ToString().c_str()); - sCallbackEnv->CallVoidMethod(mJavaInterface, method_volumeDeviceDisconnected, - j_bdaddr); + sCallbackEnv->CallVoidMethod(mJavaInterface, method_volumeDeviceDisconnected, j_bdaddr); } -static void sendVolumeChangedNative(JNIEnv* env, jobject /* object */, - jstring address, jint volume) { +static void sendVolumeChangedNative(JNIEnv* env, jobject /* object */, jstring address, + jint volume) { const char* tmp_addr = env->GetStringUTFChars(address, 0); RawAddress bdaddr; bool success = RawAddress::FromString(tmp_addr, bdaddr); env->ReleaseStringUTFChars(address, tmp_addr); - if (!success) return; + if (!success) { + return; + } log::debug(""); if (volumeCallbackMap.find(bdaddr) != volumeCallbackMap.end()) { @@ -897,13 +852,15 @@ static void setVolume(int8_t volume) { log::debug(""); std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mJavaInterface) return; + if (!sCallbackEnv.valid() || !mJavaInterface) { + return; + } sCallbackEnv->CallVoidMethod(mJavaInterface, method_setVolume, volume); } -static void setBipClientStatusNative(JNIEnv* env, jobject /* object */, - jstring address, jboolean connected) { +static void setBipClientStatusNative(JNIEnv* env, jobject /* object */, jstring address, + jboolean connected) { std::unique_lock interface_lock(interface_mutex); if (mServiceCallbacks == nullptr) { log::warn("Service not loaded."); @@ -915,7 +872,9 @@ static void setBipClientStatusNative(JNIEnv* env, jobject /* object */, bool success = RawAddress::FromString(tmp_addr, bdaddr); env->ReleaseStringUTFChars(address, tmp_addr); - if (!success) return; + if (!success) { + return; + } bool status = (connected == JNI_TRUE); sServiceInterface->SetBipClientStatus(bdaddr, status); @@ -926,7 +885,9 @@ static void listPlayerSettings(ListPlayerSettingsCb cb) { log::debug(""); std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mJavaInterface) return; + if (!sCallbackEnv.valid() || !mJavaInterface) { + return; + } list_player_settings_cb = std::move(cb); sCallbackEnv->CallVoidMethod(mJavaInterface, method_listPlayerSettings); @@ -943,22 +904,20 @@ static void listPlayerSettingsResponseNative(JNIEnv* env, jobject /* object */, } // Called from native to list available values for player setting -static void listPlayerSettingValues(PlayerAttribute attribute, - ListPlayerSettingValuesCb cb) { +static void listPlayerSettingValues(PlayerAttribute attribute, ListPlayerSettingValuesCb cb) { log::debug(""); std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mJavaInterface) return; + if (!sCallbackEnv.valid() || !mJavaInterface) { + return; + } list_player_setting_values_cb = std::move(cb); - sCallbackEnv->CallVoidMethod(mJavaInterface, method_listPlayerSettingValues, - (jbyte)attribute); + sCallbackEnv->CallVoidMethod(mJavaInterface, method_listPlayerSettingValues, (jbyte)attribute); } -static void listPlayerSettingValuesResponseNative(JNIEnv* env, - jobject /* object */, - jbyte attribute, - jbyteArray values) { +static void listPlayerSettingValuesResponseNative(JNIEnv* env, jobject /* object */, + jbyte attribute, jbyteArray values) { log::debug(""); PlayerAttribute player_attribute = static_cast(attribute); std::vector values_vector; @@ -972,64 +931,60 @@ static void getPlayerSettings(std::vector attributes, log::debug(""); std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mJavaInterface) return; + if (!sCallbackEnv.valid() || !mJavaInterface) { + return; + } jbyteArray attributes_array = sCallbackEnv->NewByteArray(attributes.size()); - sCallbackEnv->SetByteArrayRegion( - attributes_array, 0, attributes.size(), - reinterpret_cast(attributes.data())); + sCallbackEnv->SetByteArrayRegion(attributes_array, 0, attributes.size(), + reinterpret_cast(attributes.data())); get_current_player_setting_value_cb = std::move(cb); - sCallbackEnv->CallVoidMethod(mJavaInterface, method_getPlayerSettings, - attributes_array); + sCallbackEnv->CallVoidMethod(mJavaInterface, method_getPlayerSettings, attributes_array); } static void getPlayerSettingsResponseNative(JNIEnv* env, jobject /* object */, - jbyteArray attributes, - jbyteArray values) { + jbyteArray attributes, jbyteArray values) { log::debug(""); std::vector attributes_vector; std::vector values_vector; copyJavaArraytoCppVector(env, attributes, attributes_vector); copyJavaArraytoCppVector(env, values, values_vector); - get_current_player_setting_value_cb.Run(std::move(attributes_vector), - std::move(values_vector)); + get_current_player_setting_value_cb.Run(std::move(attributes_vector), std::move(values_vector)); } // Called from native to set current player settings -static void setPlayerSettings(std::vector attributes, - std::vector values, +static void setPlayerSettings(std::vector attributes, std::vector values, SetPlayerSettingValueCb cb) { log::debug(""); std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mJavaInterface) return; + if (!sCallbackEnv.valid() || !mJavaInterface) { + return; + } jbyteArray attributes_array = sCallbackEnv->NewByteArray(attributes.size()); - sCallbackEnv->SetByteArrayRegion( - attributes_array, 0, attributes.size(), - reinterpret_cast(attributes.data())); + sCallbackEnv->SetByteArrayRegion(attributes_array, 0, attributes.size(), + reinterpret_cast(attributes.data())); jbyteArray values_array = sCallbackEnv->NewByteArray(values.size()); - sCallbackEnv->SetByteArrayRegion( - values_array, 0, values.size(), - reinterpret_cast(values.data())); + sCallbackEnv->SetByteArrayRegion(values_array, 0, values.size(), + reinterpret_cast(values.data())); set_player_setting_value_cb = std::move(cb); - sCallbackEnv->CallVoidMethod(mJavaInterface, method_setPlayerSettings, - attributes_array, values_array); + sCallbackEnv->CallVoidMethod(mJavaInterface, method_setPlayerSettings, attributes_array, + values_array); } -static void setPlayerSettingsResponseNative(JNIEnv* /* env */, - jobject /* object */, +static void setPlayerSettingsResponseNative(JNIEnv* /* env */, jobject /* object */, jboolean success) { log::debug(""); set_player_setting_value_cb.Run(success); } -static void sendPlayerSettingsNative(JNIEnv* env, jobject /* object */, - jbyteArray attributes, jbyteArray values) { +static void sendPlayerSettingsNative(JNIEnv* env, jobject /* object */, jbyteArray attributes, + jbyteArray values) { log::debug(""); std::unique_lock interface_lock(interface_mutex); if (mServiceCallbacks == nullptr) { @@ -1040,75 +995,61 @@ static void sendPlayerSettingsNative(JNIEnv* env, jobject /* object */, std::vector values_vector; copyJavaArraytoCppVector(env, attributes, attributes_vector); copyJavaArraytoCppVector(env, values, values_vector); - mServiceCallbacks->SendPlayerSettingsChanged(attributes_vector, - values_vector); + mServiceCallbacks->SendPlayerSettingsChanged(attributes_vector, values_vector); } int register_com_android_bluetooth_avrcp_target(JNIEnv* env) { const JNINativeMethod methods[] = { - {"initNative", "()V", (void*)initNative}, - {"registerBipServerNative", "(I)V", (void*)registerBipServerNative}, - {"unregisterBipServerNative", "()V", (void*)unregisterBipServerNative}, - {"sendMediaUpdateNative", "(ZZZ)V", (void*)sendMediaUpdateNative}, - {"sendFolderUpdateNative", "(ZZZ)V", (void*)sendFolderUpdateNative}, - {"setBrowsedPlayerResponseNative", "(IZLjava/lang/String;I)V", - (void*)setBrowsedPlayerResponseNative}, - {"getFolderItemsResponseNative", "(Ljava/lang/String;Ljava/util/List;)V", - (void*)getFolderItemsResponseNative}, - {"cleanupNative", "()V", (void*)cleanupNative}, - {"connectDeviceNative", "(Ljava/lang/String;)Z", - (void*)connectDeviceNative}, - {"disconnectDeviceNative", "(Ljava/lang/String;)Z", - (void*)disconnectDeviceNative}, - {"sendVolumeChangedNative", "(Ljava/lang/String;I)V", - (void*)sendVolumeChangedNative}, - {"setBipClientStatusNative", "(Ljava/lang/String;Z)V", - (void*)setBipClientStatusNative}, - {"listPlayerSettingsResponseNative", "([B)V", - (void*)listPlayerSettingsResponseNative}, - {"listPlayerSettingValuesResponseNative", "(B[B)V", - (void*)listPlayerSettingValuesResponseNative}, - {"getPlayerSettingsResponseNative", "([B[B)V", - (void*)getPlayerSettingsResponseNative}, - {"setPlayerSettingsResponseNative", "(Z)V", - (void*)setPlayerSettingsResponseNative}, - {"sendPlayerSettingsNative", "([B[B)V", (void*)sendPlayerSettingsNative}, + {"initNative", "()V", (void*)initNative}, + {"registerBipServerNative", "(I)V", (void*)registerBipServerNative}, + {"unregisterBipServerNative", "()V", (void*)unregisterBipServerNative}, + {"sendMediaUpdateNative", "(ZZZ)V", (void*)sendMediaUpdateNative}, + {"sendFolderUpdateNative", "(ZZZ)V", (void*)sendFolderUpdateNative}, + {"setBrowsedPlayerResponseNative", "(IZLjava/lang/String;I)V", + (void*)setBrowsedPlayerResponseNative}, + {"getFolderItemsResponseNative", "(Ljava/lang/String;Ljava/util/List;)V", + (void*)getFolderItemsResponseNative}, + {"cleanupNative", "()V", (void*)cleanupNative}, + {"connectDeviceNative", "(Ljava/lang/String;)Z", (void*)connectDeviceNative}, + {"disconnectDeviceNative", "(Ljava/lang/String;)Z", (void*)disconnectDeviceNative}, + {"sendVolumeChangedNative", "(Ljava/lang/String;I)V", (void*)sendVolumeChangedNative}, + {"setBipClientStatusNative", "(Ljava/lang/String;Z)V", (void*)setBipClientStatusNative}, + {"listPlayerSettingsResponseNative", "([B)V", (void*)listPlayerSettingsResponseNative}, + {"listPlayerSettingValuesResponseNative", "(B[B)V", + (void*)listPlayerSettingValuesResponseNative}, + {"getPlayerSettingsResponseNative", "([B[B)V", (void*)getPlayerSettingsResponseNative}, + {"setPlayerSettingsResponseNative", "(Z)V", (void*)setPlayerSettingsResponseNative}, + {"sendPlayerSettingsNative", "([B[B)V", (void*)sendPlayerSettingsNative}, }; - const int result = REGISTER_NATIVE_METHODS( - env, "com/android/bluetooth/avrcp/AvrcpNativeInterface", methods); + const int result = + REGISTER_NATIVE_METHODS(env, "com/android/bluetooth/avrcp/AvrcpNativeInterface", methods); if (result != 0) { return result; } const JNIJavaMethod javaMethods[] = { - {"getCurrentSongInfo", "()Lcom/android/bluetooth/audio_util/Metadata;", - &method_getCurrentSongInfo}, - {"getPlayStatus", "()Lcom/android/bluetooth/audio_util/PlayStatus;", - &method_getPlaybackStatus}, - {"sendMediaKeyEvent", "(IZ)V", &method_sendMediaKeyEvent}, - {"getCurrentMediaId", "()Ljava/lang/String;", &method_getCurrentMediaId}, - {"getNowPlayingList", "()Ljava/util/List;", &method_getNowPlayingList}, - {"getCurrentPlayerId", "()I", &method_getCurrentPlayerId}, - {"getMediaPlayerList", "()Ljava/util/List;", &method_getMediaPlayerList}, - {"setBrowsedPlayer", "(I)V", &method_setBrowsedPlayer}, - {"getFolderItemsRequest", "(ILjava/lang/String;)V", - &method_getFolderItemsRequest}, - {"playItem", "(IZLjava/lang/String;)V", &method_playItem}, - {"setActiveDevice", "(Ljava/lang/String;)V", &method_setActiveDevice}, - {"deviceConnected", "(Ljava/lang/String;Z)V", - &method_volumeDeviceConnected}, - {"deviceDisconnected", "(Ljava/lang/String;)V", - &method_volumeDeviceDisconnected}, - {"setVolume", "(I)V", &method_setVolume}, - {"listPlayerSettingsRequest", "()V", &method_listPlayerSettings}, - {"listPlayerSettingValuesRequest", "(B)V", - &method_listPlayerSettingValues}, - {"getCurrentPlayerSettingValuesRequest", "([B)V", - &method_getPlayerSettings}, - {"setPlayerSettingsRequest", "([B[B)V", &method_setPlayerSettings}, + {"getCurrentSongInfo", "()Lcom/android/bluetooth/audio_util/Metadata;", + &method_getCurrentSongInfo}, + {"getPlayStatus", "()Lcom/android/bluetooth/audio_util/PlayStatus;", + &method_getPlaybackStatus}, + {"sendMediaKeyEvent", "(IZ)V", &method_sendMediaKeyEvent}, + {"getCurrentMediaId", "()Ljava/lang/String;", &method_getCurrentMediaId}, + {"getNowPlayingList", "()Ljava/util/List;", &method_getNowPlayingList}, + {"getCurrentPlayerId", "()I", &method_getCurrentPlayerId}, + {"getMediaPlayerList", "()Ljava/util/List;", &method_getMediaPlayerList}, + {"setBrowsedPlayer", "(I)V", &method_setBrowsedPlayer}, + {"getFolderItemsRequest", "(ILjava/lang/String;)V", &method_getFolderItemsRequest}, + {"playItem", "(IZLjava/lang/String;)V", &method_playItem}, + {"setActiveDevice", "(Ljava/lang/String;)V", &method_setActiveDevice}, + {"deviceConnected", "(Ljava/lang/String;Z)V", &method_volumeDeviceConnected}, + {"deviceDisconnected", "(Ljava/lang/String;)V", &method_volumeDeviceDisconnected}, + {"setVolume", "(I)V", &method_setVolume}, + {"listPlayerSettingsRequest", "()V", &method_listPlayerSettings}, + {"listPlayerSettingValuesRequest", "(B)V", &method_listPlayerSettingValues}, + {"getCurrentPlayerSettingValuesRequest", "([B)V", &method_getPlayerSettings}, + {"setPlayerSettingsRequest", "([B[B)V", &method_setPlayerSettings}, }; - GET_JAVA_METHODS(env, "com/android/bluetooth/avrcp/AvrcpNativeInterface", - javaMethods); + GET_JAVA_METHODS(env, "com/android/bluetooth/avrcp/AvrcpNativeInterface", javaMethods); return 0; } diff --git a/android/app/jni/com_android_bluetooth_btservice_AdapterService.cpp b/android/app/jni/com_android_bluetooth_btservice_AdapterService.cpp index 41d295301ed..427e4490753 100644 --- a/android/app/jni/com_android_bluetooth_btservice_AdapterService.cpp +++ b/android/app/jni/com_android_bluetooth_btservice_AdapterService.cpp @@ -41,8 +41,7 @@ namespace fmt { template <> struct formatter : enum_formatter {}; template <> -struct formatter : enum_formatter { -}; +struct formatter : enum_formatter {}; } // namespace fmt static Uuid from_java_uuid(jlong uuid_msb, jlong uuid_lsb) { @@ -120,25 +119,24 @@ static void adapter_state_change_callback(bt_state_t status) { } CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid()) return; + if (!sCallbackEnv.valid()) { + return; + } log::verbose("Status is: {}", status); - sCallbackEnv->CallVoidMethod(sJniCallbacksObj, method_stateChangeCallback, - (jint)status); + sCallbackEnv->CallVoidMethod(sJniCallbacksObj, method_stateChangeCallback, (jint)status); } -static int get_properties(int num_properties, bt_property_t* properties, - jintArray* types, jobjectArray* props) { +static int get_properties(int num_properties, bt_property_t* properties, jintArray* types, + jobjectArray* props) { for (int i = 0; i < num_properties; i++) { - ScopedLocalRef propVal( - callbackEnv, callbackEnv->NewByteArray(properties[i].len)); + ScopedLocalRef propVal(callbackEnv, callbackEnv->NewByteArray(properties[i].len)); if (!propVal.get()) { log::error("Error while allocation of array"); return -1; } - callbackEnv->SetByteArrayRegion(propVal.get(), 0, properties[i].len, - (jbyte*)properties[i].val); + callbackEnv->SetByteArrayRegion(propVal.get(), 0, properties[i].len, (jbyte*)properties[i].val); callbackEnv->SetObjectArrayElement(*props, i, propVal.get()); callbackEnv->SetIntArrayRegion(*types, i, 1, (jint*)&properties[i].type); } @@ -154,40 +152,38 @@ static void adapter_properties_callback(bt_status_t status, int num_properties, } CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid()) return; + if (!sCallbackEnv.valid()) { + return; + } - log::verbose("Status is: {}, Properties: {}", bt_status_text(status), - num_properties); + log::verbose("Status is: {}, Properties: {}", bt_status_text(status), num_properties); if (status != BT_STATUS_SUCCESS) { log::error("Status {} is incorrect", bt_status_text(status)); return; } - ScopedLocalRef val( - sCallbackEnv.get(), - (jbyteArray)sCallbackEnv->NewByteArray(num_properties)); + ScopedLocalRef val(sCallbackEnv.get(), + (jbyteArray)sCallbackEnv->NewByteArray(num_properties)); if (!val.get()) { log::error("Error allocating byteArray"); return; } - ScopedLocalRef mclass(sCallbackEnv.get(), - sCallbackEnv->GetObjectClass(val.get())); + ScopedLocalRef mclass(sCallbackEnv.get(), sCallbackEnv->GetObjectClass(val.get())); /* (BT) Initialize the jobjectArray and jintArray here itself and send the initialized array pointers alone to get_properties */ ScopedLocalRef props( - sCallbackEnv.get(), - sCallbackEnv->NewObjectArray(num_properties, mclass.get(), NULL)); + sCallbackEnv.get(), sCallbackEnv->NewObjectArray(num_properties, mclass.get(), NULL)); if (!props.get()) { log::error("Error allocating object Array for properties"); return; } - ScopedLocalRef types( - sCallbackEnv.get(), (jintArray)sCallbackEnv->NewIntArray(num_properties)); + ScopedLocalRef types(sCallbackEnv.get(), + (jintArray)sCallbackEnv->NewIntArray(num_properties)); if (!types.get()) { log::error("Error allocating int Array for values"); return; @@ -199,15 +195,12 @@ static void adapter_properties_callback(bt_status_t status, int num_properties, return; } - sCallbackEnv->CallVoidMethod(sJniCallbacksObj, - method_adapterPropertyChangedCallback, - types.get(), props.get()); + sCallbackEnv->CallVoidMethod(sJniCallbacksObj, method_adapterPropertyChangedCallback, types.get(), + props.get()); } -static void remote_device_properties_callback(bt_status_t status, - RawAddress* bd_addr, - int num_properties, - bt_property_t* properties) { +static void remote_device_properties_callback(bt_status_t status, RawAddress* bd_addr, + int num_properties, bt_property_t* properties) { std::shared_lock lock(jniObjMutex); if (!sJniCallbacksObj) { log::error("JNI obj is null. Failed to call JNI callback"); @@ -215,55 +208,52 @@ static void remote_device_properties_callback(bt_status_t status, } CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid()) return; + if (!sCallbackEnv.valid()) { + return; + } - log::verbose("Device: {}, Status: {}, Properties: {}", - ADDRESS_TO_LOGGABLE_STR(*bd_addr), bt_status_text(status), - num_properties); + log::verbose("Device: {}, Status: {}, Properties: {}", ADDRESS_TO_LOGGABLE_STR(*bd_addr), + bt_status_text(status), num_properties); if (status != BT_STATUS_SUCCESS) { log::error("Status {} is incorrect", bt_status_text(status)); return; } - ScopedLocalRef val( - sCallbackEnv.get(), - (jbyteArray)sCallbackEnv->NewByteArray(num_properties)); + ScopedLocalRef val(sCallbackEnv.get(), + (jbyteArray)sCallbackEnv->NewByteArray(num_properties)); if (!val.get()) { log::error("Error allocating byteArray"); return; } - ScopedLocalRef mclass(sCallbackEnv.get(), - sCallbackEnv->GetObjectClass(val.get())); + ScopedLocalRef mclass(sCallbackEnv.get(), sCallbackEnv->GetObjectClass(val.get())); /* Initialize the jobjectArray and jintArray here itself and send the initialized array pointers alone to get_properties */ ScopedLocalRef props( - sCallbackEnv.get(), - sCallbackEnv->NewObjectArray(num_properties, mclass.get(), NULL)); + sCallbackEnv.get(), sCallbackEnv->NewObjectArray(num_properties, mclass.get(), NULL)); if (!props.get()) { log::error("Error allocating object Array for properties"); return; } - ScopedLocalRef types( - sCallbackEnv.get(), (jintArray)sCallbackEnv->NewIntArray(num_properties)); + ScopedLocalRef types(sCallbackEnv.get(), + (jintArray)sCallbackEnv->NewIntArray(num_properties)); if (!types.get()) { log::error("Error allocating int Array for values"); return; } - ScopedLocalRef addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); + ScopedLocalRef addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); if (!addr.get()) { log::error("Error while allocation byte array"); return; } - sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), - (jbyte*)bd_addr); + sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), (jbyte*)bd_addr); jintArray typesPtr = types.get(); jobjectArray propsPtr = props.get(); @@ -271,13 +261,11 @@ static void remote_device_properties_callback(bt_status_t status, return; } - sCallbackEnv->CallVoidMethod(sJniCallbacksObj, - method_devicePropertyChangedCallback, addr.get(), + sCallbackEnv->CallVoidMethod(sJniCallbacksObj, method_devicePropertyChangedCallback, addr.get(), types.get(), props.get()); } -static void device_found_callback(int num_properties, - bt_property_t* properties) { +static void device_found_callback(int num_properties, bt_property_t* properties) { std::shared_lock lock(jniObjMutex); if (!sJniCallbacksObj) { log::error("JNI obj is null. Failed to call JNI callback"); @@ -285,7 +273,9 @@ static void device_found_callback(int num_properties, } CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid()) return; + if (!sCallbackEnv.valid()) { + return; + } ScopedLocalRef addr(sCallbackEnv.get(), NULL); int addr_index; @@ -296,8 +286,7 @@ static void device_found_callback(int num_properties, log::error("Address is NULL (unable to allocate)"); return; } - sCallbackEnv->SetByteArrayRegion(addr.get(), 0, properties[i].len, - (jbyte*)properties[i].val); + sCallbackEnv->SetByteArrayRegion(addr.get(), 0, properties[i].len, (jbyte*)properties[i].val); addr_index = i; } } @@ -309,17 +298,14 @@ static void device_found_callback(int num_properties, log::verbose("Properties: {}, Address: {}", num_properties, *(RawAddress*)properties[addr_index].val); - remote_device_properties_callback(BT_STATUS_SUCCESS, - (RawAddress*)properties[addr_index].val, + remote_device_properties_callback(BT_STATUS_SUCCESS, (RawAddress*)properties[addr_index].val, num_properties, properties); - sCallbackEnv->CallVoidMethod(sJniCallbacksObj, method_deviceFoundCallback, - addr.get()); + sCallbackEnv->CallVoidMethod(sJniCallbacksObj, method_deviceFoundCallback, addr.get()); } static void bond_state_changed_callback(bt_status_t status, RawAddress* bd_addr, - bt_bond_state_t state, - int fail_reason) { + bt_bond_state_t state, int fail_reason) { std::shared_lock lock(jniObjMutex); if (!sJniCallbacksObj) { log::error("JNI obj is null. Failed to call JNI callback"); @@ -327,29 +313,28 @@ static void bond_state_changed_callback(bt_status_t status, RawAddress* bd_addr, } CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid()) return; + if (!sCallbackEnv.valid()) { + return; + } if (!bd_addr) { log::error("Address is null"); return; } - ScopedLocalRef addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); + ScopedLocalRef addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); if (!addr.get()) { log::error("Address allocation failed"); return; } - sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), - (jbyte*)bd_addr); + sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), (jbyte*)bd_addr); - sCallbackEnv->CallVoidMethod(sJniCallbacksObj, method_bondStateChangeCallback, - (jint)status, addr.get(), (jint)state, - (jint)fail_reason); + sCallbackEnv->CallVoidMethod(sJniCallbacksObj, method_bondStateChangeCallback, (jint)status, + addr.get(), (jint)state, (jint)fail_reason); } -static void address_consolidate_callback(RawAddress* main_bd_addr, - RawAddress* secondary_bd_addr) { +static void address_consolidate_callback(RawAddress* main_bd_addr, RawAddress* secondary_bd_addr) { std::shared_lock lock(jniObjMutex); if (!sJniCallbacksObj) { log::error("JNI obj is null. Failed to call JNI callback"); @@ -358,17 +343,16 @@ static void address_consolidate_callback(RawAddress* main_bd_addr, CallbackEnv sCallbackEnv(__func__); - ScopedLocalRef main_addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); + ScopedLocalRef main_addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); if (!main_addr.get()) { log::error("Address allocation failed"); return; } - sCallbackEnv->SetByteArrayRegion(main_addr.get(), 0, sizeof(RawAddress), - (jbyte*)main_bd_addr); + sCallbackEnv->SetByteArrayRegion(main_addr.get(), 0, sizeof(RawAddress), (jbyte*)main_bd_addr); - ScopedLocalRef secondary_addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); + ScopedLocalRef secondary_addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); if (!secondary_addr.get()) { log::error("Address allocation failed"); return; @@ -377,13 +361,11 @@ static void address_consolidate_callback(RawAddress* main_bd_addr, sCallbackEnv->SetByteArrayRegion(secondary_addr.get(), 0, sizeof(RawAddress), (jbyte*)secondary_bd_addr); - sCallbackEnv->CallVoidMethod(sJniCallbacksObj, - method_addressConsolidateCallback, - main_addr.get(), secondary_addr.get()); + sCallbackEnv->CallVoidMethod(sJniCallbacksObj, method_addressConsolidateCallback, main_addr.get(), + secondary_addr.get()); } -static void le_address_associate_callback(RawAddress* main_bd_addr, - RawAddress* secondary_bd_addr) { +static void le_address_associate_callback(RawAddress* main_bd_addr, RawAddress* secondary_bd_addr) { std::shared_lock lock(jniObjMutex); if (!sJniCallbacksObj) { log::error("JNI obj is null. Failed to call JNI callback"); @@ -392,17 +374,16 @@ static void le_address_associate_callback(RawAddress* main_bd_addr, CallbackEnv sCallbackEnv(__func__); - ScopedLocalRef main_addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); + ScopedLocalRef main_addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); if (!main_addr.get()) { log::error("Address allocation failed"); return; } - sCallbackEnv->SetByteArrayRegion(main_addr.get(), 0, sizeof(RawAddress), - (jbyte*)main_bd_addr); + sCallbackEnv->SetByteArrayRegion(main_addr.get(), 0, sizeof(RawAddress), (jbyte*)main_bd_addr); - ScopedLocalRef secondary_addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); + ScopedLocalRef secondary_addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); if (!secondary_addr.get()) { log::error("Address allocation failed"); return; @@ -411,17 +392,14 @@ static void le_address_associate_callback(RawAddress* main_bd_addr, sCallbackEnv->SetByteArrayRegion(secondary_addr.get(), 0, sizeof(RawAddress), (jbyte*)secondary_bd_addr); - sCallbackEnv->CallVoidMethod(sJniCallbacksObj, - method_leAddressAssociateCallback, - main_addr.get(), secondary_addr.get()); + sCallbackEnv->CallVoidMethod(sJniCallbacksObj, method_leAddressAssociateCallback, main_addr.get(), + secondary_addr.get()); } static void acl_state_changed_callback(bt_status_t status, RawAddress* bd_addr, - bt_acl_state_t state, - int transport_link_type, + bt_acl_state_t state, int transport_link_type, bt_hci_error_code_t hci_reason, - bt_conn_direction_t /* direction */, - uint16_t acl_handle) { + bt_conn_direction_t /* direction */, uint16_t acl_handle) { if (!bd_addr) { log::error("Address is null"); return; @@ -434,20 +412,20 @@ static void acl_state_changed_callback(bt_status_t status, RawAddress* bd_addr, } CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid()) return; + if (!sCallbackEnv.valid()) { + return; + } - ScopedLocalRef addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); + ScopedLocalRef addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); if (!addr.get()) { log::error("Address allocation failed"); return; } - sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), - (jbyte*)bd_addr); + sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), (jbyte*)bd_addr); - sCallbackEnv->CallVoidMethod(sJniCallbacksObj, method_aclStateChangeCallback, - (jint)status, addr.get(), (jint)state, - (jint)transport_link_type, (jint)hci_reason, + sCallbackEnv->CallVoidMethod(sJniCallbacksObj, method_aclStateChangeCallback, (jint)status, + addr.get(), (jint)state, (jint)transport_link_type, (jint)hci_reason, (jint)acl_handle); } @@ -459,16 +437,17 @@ static void discovery_state_changed_callback(bt_discovery_state_t state) { } CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid()) return; + if (!sCallbackEnv.valid()) { + return; + } log::verbose("DiscoveryState:{}", state); - sCallbackEnv->CallVoidMethod( - sJniCallbacksObj, method_discoveryStateChangeCallback, (jint)state); + sCallbackEnv->CallVoidMethod(sJniCallbacksObj, method_discoveryStateChangeCallback, (jint)state); } -static void pin_request_callback(RawAddress* bd_addr, bt_bdname_t* bdname, - uint32_t cod, bool min_16_digits) { +static void pin_request_callback(RawAddress* bd_addr, bt_bdname_t* bdname, uint32_t cod, + bool min_16_digits) { if (!bd_addr) { log::error("Address is null"); return; @@ -481,34 +460,33 @@ static void pin_request_callback(RawAddress* bd_addr, bt_bdname_t* bdname, } CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid()) return; + if (!sCallbackEnv.valid()) { + return; + } - ScopedLocalRef addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); + ScopedLocalRef addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); if (!addr.get()) { log::error("Error while allocating"); return; } - sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), - (jbyte*)bd_addr); + sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), (jbyte*)bd_addr); - ScopedLocalRef devname( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(bt_bdname_t))); + ScopedLocalRef devname(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(bt_bdname_t))); if (!devname.get()) { log::error("Error while allocating"); return; } - sCallbackEnv->SetByteArrayRegion(devname.get(), 0, sizeof(bt_bdname_t), - (jbyte*)bdname); + sCallbackEnv->SetByteArrayRegion(devname.get(), 0, sizeof(bt_bdname_t), (jbyte*)bdname); - sCallbackEnv->CallVoidMethod(sJniCallbacksObj, method_pinRequestCallback, - addr.get(), devname.get(), cod, min_16_digits); + sCallbackEnv->CallVoidMethod(sJniCallbacksObj, method_pinRequestCallback, addr.get(), + devname.get(), cod, min_16_digits); } -static void ssp_request_callback(RawAddress* bd_addr, - bt_ssp_variant_t pairing_variant, +static void ssp_request_callback(RawAddress* bd_addr, bt_ssp_variant_t pairing_variant, uint32_t pass_key) { if (!bd_addr) { log::error("Address is null"); @@ -522,20 +500,21 @@ static void ssp_request_callback(RawAddress* bd_addr, } CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid()) return; + if (!sCallbackEnv.valid()) { + return; + } - ScopedLocalRef addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); + ScopedLocalRef addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); if (!addr.get()) { log::error("Error while allocating"); return; } - sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), - (jbyte*)bd_addr); + sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), (jbyte*)bd_addr); - sCallbackEnv->CallVoidMethod(sJniCallbacksObj, method_sspRequestCallback, - addr.get(), (jint)pairing_variant, pass_key); + sCallbackEnv->CallVoidMethod(sJniCallbacksObj, method_sspRequestCallback, addr.get(), + (jint)pairing_variant, pass_key); } static jobject createClassicOobDataObject(JNIEnv* env, bt_oob_data_t oob_data) { @@ -546,43 +525,34 @@ static jobject createClassicOobDataObject(JNIEnv* env, bt_oob_data_t oob_data) { jmethodID buildMethod; const JNIJavaMethod javaMethods[] = { - {"", "([B[B[B)V", &classicBuilderConstructor}, - {"setRandomizerHash", "([B)Landroid/bluetooth/OobData$ClassicBuilder;", - &setRMethod}, - {"setDeviceName", "([B)Landroid/bluetooth/OobData$ClassicBuilder;", - &setNameMethod}, - {"build", "()Landroid/bluetooth/OobData;", &buildMethod}, + {"", "([B[B[B)V", &classicBuilderConstructor}, + {"setRandomizerHash", "([B)Landroid/bluetooth/OobData$ClassicBuilder;", &setRMethod}, + {"setDeviceName", "([B)Landroid/bluetooth/OobData$ClassicBuilder;", &setNameMethod}, + {"build", "()Landroid/bluetooth/OobData;", &buildMethod}, }; - GET_JAVA_METHODS(env, "android/bluetooth/OobData$ClassicBuilder", - javaMethods); + GET_JAVA_METHODS(env, "android/bluetooth/OobData$ClassicBuilder", javaMethods); jbyteArray confirmationHash = env->NewByteArray(OOB_C_SIZE); - env->SetByteArrayRegion(confirmationHash, 0, OOB_C_SIZE, - reinterpret_cast(oob_data.c)); + env->SetByteArrayRegion(confirmationHash, 0, OOB_C_SIZE, reinterpret_cast(oob_data.c)); jbyteArray oobDataLength = env->NewByteArray(OOB_DATA_LEN_SIZE); env->SetByteArrayRegion(oobDataLength, 0, OOB_DATA_LEN_SIZE, reinterpret_cast(oob_data.oob_data_length)); jbyteArray address = env->NewByteArray(OOB_ADDRESS_SIZE); - env->SetByteArrayRegion(address, 0, OOB_ADDRESS_SIZE, - reinterpret_cast(oob_data.address)); + env->SetByteArrayRegion(address, 0, OOB_ADDRESS_SIZE, reinterpret_cast(oob_data.address)); - jclass classicBuilderClass = - env->FindClass("android/bluetooth/OobData$ClassicBuilder"); + jclass classicBuilderClass = env->FindClass("android/bluetooth/OobData$ClassicBuilder"); - jobject oobDataClassicBuilder = - env->NewObject(classicBuilderClass, classicBuilderConstructor, - confirmationHash, oobDataLength, address); + jobject oobDataClassicBuilder = env->NewObject(classicBuilderClass, classicBuilderConstructor, + confirmationHash, oobDataLength, address); env->DeleteLocalRef(classicBuilderClass); jbyteArray randomizerHash = env->NewByteArray(OOB_R_SIZE); - env->SetByteArrayRegion(randomizerHash, 0, OOB_R_SIZE, - reinterpret_cast(oob_data.r)); + env->SetByteArrayRegion(randomizerHash, 0, OOB_R_SIZE, reinterpret_cast(oob_data.r)); - oobDataClassicBuilder = - env->CallObjectMethod(oobDataClassicBuilder, setRMethod, randomizerHash); + oobDataClassicBuilder = env->CallObjectMethod(oobDataClassicBuilder, setRMethod, randomizerHash); int name_char_count = 0; for (int i = 0; i < OOB_NAME_MAX_SIZE; i++) { @@ -596,8 +566,7 @@ static jobject createClassicOobDataObject(JNIEnv* env, bt_oob_data_t oob_data) { env->SetByteArrayRegion(deviceName, 0, name_char_count, reinterpret_cast(oob_data.device_name)); - oobDataClassicBuilder = - env->CallObjectMethod(oobDataClassicBuilder, setNameMethod, deviceName); + oobDataClassicBuilder = env->CallObjectMethod(oobDataClassicBuilder, setNameMethod, deviceName); return env->CallObjectMethod(oobDataClassicBuilder, buildMethod); } @@ -611,38 +580,32 @@ static jobject createLeOobDataObject(JNIEnv* env, bt_oob_data_t oob_data) { jmethodID buildMethod; const JNIJavaMethod javaMethods[] = { - {"", "([B[BI)V", &leBuilderConstructor}, - {"setRandomizerHash", "([B)Landroid/bluetooth/OobData$LeBuilder;", - &setRMethod}, - {"setDeviceName", "([B)Landroid/bluetooth/OobData$LeBuilder;", - &setNameMethod}, - {"build", "()Landroid/bluetooth/OobData;", &buildMethod}, + {"", "([B[BI)V", &leBuilderConstructor}, + {"setRandomizerHash", "([B)Landroid/bluetooth/OobData$LeBuilder;", &setRMethod}, + {"setDeviceName", "([B)Landroid/bluetooth/OobData$LeBuilder;", &setNameMethod}, + {"build", "()Landroid/bluetooth/OobData;", &buildMethod}, }; GET_JAVA_METHODS(env, "android/bluetooth/OobData$LeBuilder", javaMethods); jbyteArray confirmationHash = env->NewByteArray(OOB_C_SIZE); - env->SetByteArrayRegion(confirmationHash, 0, OOB_C_SIZE, - reinterpret_cast(oob_data.c)); + env->SetByteArrayRegion(confirmationHash, 0, OOB_C_SIZE, reinterpret_cast(oob_data.c)); jbyteArray address = env->NewByteArray(OOB_ADDRESS_SIZE); - env->SetByteArrayRegion(address, 0, OOB_ADDRESS_SIZE, - reinterpret_cast(oob_data.address)); + env->SetByteArrayRegion(address, 0, OOB_ADDRESS_SIZE, reinterpret_cast(oob_data.address)); jint le_role = (jint)oob_data.le_device_role; jclass leBuilderClass = env->FindClass("android/bluetooth/OobData$LeBuilder"); - jobject oobDataLeBuilder = env->NewObject( - leBuilderClass, leBuilderConstructor, confirmationHash, address, le_role); + jobject oobDataLeBuilder = + env->NewObject(leBuilderClass, leBuilderConstructor, confirmationHash, address, le_role); env->DeleteLocalRef(leBuilderClass); jbyteArray randomizerHash = env->NewByteArray(OOB_R_SIZE); - env->SetByteArrayRegion(randomizerHash, 0, OOB_R_SIZE, - reinterpret_cast(oob_data.r)); + env->SetByteArrayRegion(randomizerHash, 0, OOB_R_SIZE, reinterpret_cast(oob_data.r)); - oobDataLeBuilder = - env->CallObjectMethod(oobDataLeBuilder, setRMethod, randomizerHash); + oobDataLeBuilder = env->CallObjectMethod(oobDataLeBuilder, setRMethod, randomizerHash); int name_char_count = 0; for (int i = 0; i < OOB_NAME_MAX_SIZE; i++) { @@ -656,14 +619,12 @@ static jobject createLeOobDataObject(JNIEnv* env, bt_oob_data_t oob_data) { env->SetByteArrayRegion(deviceName, 0, name_char_count, reinterpret_cast(oob_data.device_name)); - oobDataLeBuilder = - env->CallObjectMethod(oobDataLeBuilder, setNameMethod, deviceName); + oobDataLeBuilder = env->CallObjectMethod(oobDataLeBuilder, setNameMethod, deviceName); return env->CallObjectMethod(oobDataLeBuilder, buildMethod); } -static void generate_local_oob_data_callback(tBT_TRANSPORT transport, - bt_oob_data_t oob_data) { +static void generate_local_oob_data_callback(tBT_TRANSPORT transport, bt_oob_data_t oob_data) { log::verbose(""); std::shared_lock lock(jniObjMutex); @@ -673,35 +634,32 @@ static void generate_local_oob_data_callback(tBT_TRANSPORT transport, } CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid()) return; + if (!sCallbackEnv.valid()) { + return; + } if (transport == TRANSPORT_BREDR) { sCallbackEnv->CallVoidMethod( - sJniCallbacksObj, method_oobDataReceivedCallback, (jint)transport, - ((oob_data.is_valid) - ? createClassicOobDataObject(sCallbackEnv.get(), oob_data) - : nullptr)); + sJniCallbacksObj, method_oobDataReceivedCallback, (jint)transport, + ((oob_data.is_valid) ? createClassicOobDataObject(sCallbackEnv.get(), oob_data) + : nullptr)); } else if (transport == TRANSPORT_LE) { sCallbackEnv->CallVoidMethod( - sJniCallbacksObj, method_oobDataReceivedCallback, (jint)transport, - ((oob_data.is_valid) - ? createLeOobDataObject(sCallbackEnv.get(), oob_data) - : nullptr)); + sJniCallbacksObj, method_oobDataReceivedCallback, (jint)transport, + ((oob_data.is_valid) ? createLeOobDataObject(sCallbackEnv.get(), oob_data) : nullptr)); } else { // TRANSPORT_AUTO is a concept, however, the host stack doesn't fully // implement it So passing it from the java layer is currently useless until // the implementation and concept of TRANSPORT_AUTO is fleshed out. log::error("TRANSPORT: {} not implemented", transport); - sCallbackEnv->CallVoidMethod(sJniCallbacksObj, - method_oobDataReceivedCallback, - (jint)transport, nullptr); + sCallbackEnv->CallVoidMethod(sJniCallbacksObj, method_oobDataReceivedCallback, (jint)transport, + nullptr); } } -static void link_quality_report_callback( - uint64_t timestamp, int report_id, int rssi, int snr, - int retransmission_count, int packets_not_receive_count, - int negative_acknowledgement_count) { +static void link_quality_report_callback(uint64_t timestamp, int report_id, int rssi, int snr, + int retransmission_count, int packets_not_receive_count, + int negative_acknowledgement_count) { std::shared_lock lock(jniObjMutex); if (!sJniCallbacksObj) { log::error("JNI obj is null. Failed to call JNI callback"); @@ -709,17 +667,17 @@ static void link_quality_report_callback( } CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid()) return; + if (!sCallbackEnv.valid()) { + return; + } - log::verbose("LinkQualityReportCallback: {} {} {} {} {} {}", report_id, rssi, - snr, retransmission_count, packets_not_receive_count, - negative_acknowledgement_count); + log::verbose("LinkQualityReportCallback: {} {} {} {} {} {}", report_id, rssi, snr, + retransmission_count, packets_not_receive_count, negative_acknowledgement_count); - sCallbackEnv->CallVoidMethod( - sJniCallbacksObj, method_linkQualityReportCallback, - (jlong)timestamp, (jint)report_id, (jint)rssi, (jint)snr, - (jint)retransmission_count, (jint)packets_not_receive_count, - (jint)negative_acknowledgement_count); + sCallbackEnv->CallVoidMethod(sJniCallbacksObj, method_linkQualityReportCallback, (jlong)timestamp, + (jint)report_id, (jint)rssi, (jint)snr, (jint)retransmission_count, + (jint)packets_not_receive_count, + (jint)negative_acknowledgement_count); } static void switch_buffer_size_callback(bool is_low_latency_buffer_size) { @@ -730,13 +688,14 @@ static void switch_buffer_size_callback(bool is_low_latency_buffer_size) { } CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid()) return; + if (!sCallbackEnv.valid()) { + return; + } log::verbose("SwitchBufferSizeCallback: {}", is_low_latency_buffer_size); - sCallbackEnv->CallVoidMethod( - sJniCallbacksObj, method_switchBufferSizeCallback, - (jboolean)is_low_latency_buffer_size); + sCallbackEnv->CallVoidMethod(sJniCallbacksObj, method_switchBufferSizeCallback, + (jboolean)is_low_latency_buffer_size); } static void switch_codec_callback(bool is_low_latency_buffer_size) { @@ -747,7 +706,9 @@ static void switch_codec_callback(bool is_low_latency_buffer_size) { } CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid()) return; + if (!sCallbackEnv.valid()) { + return; + } log::verbose("SwitchCodecCallback: {}", is_low_latency_buffer_size); @@ -767,19 +728,19 @@ static void key_missing_callback(const RawAddress bd_addr) { } CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid()) return; + if (!sCallbackEnv.valid()) { + return; + } - ScopedLocalRef addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); + ScopedLocalRef addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); if (!addr.get()) { log::error("Address allocation failed"); return; } - sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), - (jbyte*)&bd_addr); + sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), (jbyte*)&bd_addr); - sCallbackEnv->CallVoidMethod(sJniCallbacksObj, method_keyMissingCallback, - addr.get()); + sCallbackEnv->CallVoidMethod(sJniCallbacksObj, method_keyMissingCallback, addr.get()); } static void callback_thread_event(bt_cb_thread_evt event) { @@ -804,13 +765,10 @@ static void callback_thread_event(bt_cb_thread_evt event) { } } -static void dut_mode_recv_callback(uint16_t /* opcode */, uint8_t* /* buf */, - uint8_t /* len */) {} +static void dut_mode_recv_callback(uint16_t /* opcode */, uint8_t* /* buf */, uint8_t /* len */) {} -static void le_test_mode_recv_callback(bt_status_t status, - uint16_t packet_count) { - log::verbose("status:{} packet_count:{}", bt_status_text(status), - packet_count); +static void le_test_mode_recv_callback(bt_status_t status, uint16_t packet_count) { + log::verbose("status:{} packet_count:{}", bt_status_text(status), packet_count); } static void energy_info_recv_callback(bt_activity_energy_info* p_energy_info, @@ -822,7 +780,9 @@ static void energy_info_recv_callback(bt_activity_energy_info* p_energy_info, } CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid()) return; + if (!sCallbackEnv.valid()) { + return; + } jsize len = 0; for (bt_uid_traffic_t* data = uid_data; data->app_uid != -1; data++) { @@ -830,23 +790,22 @@ static void energy_info_recv_callback(bt_activity_energy_info* p_energy_info, } ScopedLocalRef array( - sCallbackEnv.get(), sCallbackEnv->NewObjectArray( - len, android_bluetooth_UidTraffic.clazz, NULL)); + sCallbackEnv.get(), + sCallbackEnv->NewObjectArray(len, android_bluetooth_UidTraffic.clazz, NULL)); jsize i = 0; for (bt_uid_traffic_t* data = uid_data; data->app_uid != -1; data++) { ScopedLocalRef uidObj( - sCallbackEnv.get(), - sCallbackEnv->NewObject(android_bluetooth_UidTraffic.clazz, - android_bluetooth_UidTraffic.constructor, - (jint)data->app_uid, (jlong)data->rx_bytes, - (jlong)data->tx_bytes)); + sCallbackEnv.get(), + sCallbackEnv->NewObject(android_bluetooth_UidTraffic.clazz, + android_bluetooth_UidTraffic.constructor, (jint)data->app_uid, + (jlong)data->rx_bytes, (jlong)data->tx_bytes)); sCallbackEnv->SetObjectArrayElement(array.get(), i++, uidObj.get()); } - sCallbackEnv->CallVoidMethod( - sJniCallbacksObj, method_energyInfo, p_energy_info->status, - p_energy_info->ctrl_state, p_energy_info->tx_time, p_energy_info->rx_time, - p_energy_info->idle_time, p_energy_info->energy_used, array.get()); + sCallbackEnv->CallVoidMethod(sJniCallbacksObj, method_energyInfo, p_energy_info->status, + p_energy_info->ctrl_state, p_energy_info->tx_time, + p_energy_info->rx_time, p_energy_info->idle_time, + p_energy_info->energy_used, array.get()); } static bt_callbacks_t sBluetoothCallbacks = {sizeof(sBluetoothCallbacks), @@ -873,15 +832,15 @@ static bt_callbacks_t sBluetoothCallbacks = {sizeof(sBluetoothCallbacks), key_missing_callback}; class JNIThreadAttacher { - public: +public: JNIThreadAttacher(JavaVM* vm) : vm_(vm), env_(nullptr) { status_ = vm_->GetEnv((void**)&env_, JNI_VERSION_1_6); if (status_ != JNI_OK && status_ != JNI_EDETACHED) { log::error( - "JNIThreadAttacher: unable to get environment for JNI CALL, status: " - "{}", - status_); + "JNIThreadAttacher: unable to get environment for JNI CALL, status: " + "{}", + status_); env_ = nullptr; return; } @@ -889,15 +848,13 @@ class JNIThreadAttacher { if (status_ == JNI_EDETACHED) { char name[17] = {0}; if (prctl(PR_GET_NAME, (unsigned long)name) != 0) { - log::error( - "JNIThreadAttacher: unable to grab previous thread name, error: {}", - strerror(errno)); + log::error("JNIThreadAttacher: unable to grab previous thread name, error: {}", + strerror(errno)); env_ = nullptr; return; } - JavaVMAttachArgs args = { - .version = JNI_VERSION_1_6, .name = name, .group = nullptr}; + JavaVMAttachArgs args = {.version = JNI_VERSION_1_6, .name = name, .group = nullptr}; if (vm_->AttachCurrentThread(&env_, &args) != 0) { log::error("JNIThreadAttacher: unable to attach thread to VM"); env_ = nullptr; @@ -907,12 +864,14 @@ class JNIThreadAttacher { } ~JNIThreadAttacher() { - if (status_ == JNI_EDETACHED) vm_->DetachCurrentThread(); + if (status_ == JNI_EDETACHED) { + vm_->DetachCurrentThread(); + } } JNIEnv* getEnv() { return env_; } - private: +private: JavaVM* vm_; JNIEnv* env_; jint status_; @@ -937,9 +896,11 @@ static int acquire_wake_lock_callout(const char* lock_name) { { ScopedLocalRef lock_name_jni(env, env->NewStringUTF(lock_name)); if (lock_name_jni.get()) { - bool acquired = env->CallBooleanMethod( - sJniCallbacksObj, method_acquireWakeLock, lock_name_jni.get()); - if (!acquired) ret = BT_STATUS_WAKELOCK_ERROR; + bool acquired = + env->CallBooleanMethod(sJniCallbacksObj, method_acquireWakeLock, lock_name_jni.get()); + if (!acquired) { + ret = BT_STATUS_WAKELOCK_ERROR; + } } else { log::error("unable to allocate string: {}", lock_name); ret = BT_STATUS_NOMEM; @@ -968,9 +929,11 @@ static int release_wake_lock_callout(const char* lock_name) { { ScopedLocalRef lock_name_jni(env, env->NewStringUTF(lock_name)); if (lock_name_jni.get()) { - bool released = env->CallBooleanMethod( - sJniCallbacksObj, method_releaseWakeLock, lock_name_jni.get()); - if (!released) ret = BT_STATUS_WAKELOCK_ERROR; + bool released = + env->CallBooleanMethod(sJniCallbacksObj, method_releaseWakeLock, lock_name_jni.get()); + if (!released) { + ret = BT_STATUS_WAKELOCK_ERROR; + } } else { log::error("unable to allocate string: {}", lock_name); ret = BT_STATUS_NOMEM; @@ -981,9 +944,9 @@ static int release_wake_lock_callout(const char* lock_name) { } static bt_os_callouts_t sBluetoothOsCallouts = { - sizeof(sBluetoothOsCallouts), - acquire_wake_lock_callout, - release_wake_lock_callout, + sizeof(sBluetoothOsCallouts), + acquire_wake_lock_callout, + release_wake_lock_callout, }; int hal_util_load_bt_library(const bt_interface_t** interface) { @@ -991,20 +954,18 @@ int hal_util_load_bt_library(const bt_interface_t** interface) { return 0; } -static bool initNative(JNIEnv* env, jobject obj, jboolean isGuest, - jboolean isCommonCriteriaMode, int configCompareResult, - jobjectArray initFlags, jboolean isAtvDevice, +static bool initNative(JNIEnv* env, jobject obj, jboolean isGuest, jboolean isCommonCriteriaMode, + int configCompareResult, jobjectArray initFlags, jboolean isAtvDevice, jstring userDataDirectory) { std::unique_lock lock(jniObjMutex); log::verbose(""); android_bluetooth_UidTraffic.clazz = - (jclass)env->NewGlobalRef(env->FindClass("android/bluetooth/UidTraffic")); + (jclass)env->NewGlobalRef(env->FindClass("android/bluetooth/UidTraffic")); sJniAdapterServiceObj = env->NewGlobalRef(obj); - sJniCallbacksObj = - env->NewGlobalRef(env->GetObjectField(obj, sJniCallbacksField)); + sJniCallbacksObj = env->NewGlobalRef(env->GetObjectField(obj, sJniCallbacksField)); if (!sBluetoothInterface) { return JNI_FALSE; @@ -1023,13 +984,11 @@ static bool initNative(JNIEnv* env, jobject obj, jboolean isGuest, flags[i] = env->GetStringUTFChars(flagObjs[i], NULL); } - const char* user_data_directory = - env->GetStringUTFChars(userDataDirectory, NULL); + const char* user_data_directory = env->GetStringUTFChars(userDataDirectory, NULL); - int ret = sBluetoothInterface->init( - &sBluetoothCallbacks, isGuest == JNI_TRUE ? 1 : 0, - isCommonCriteriaMode == JNI_TRUE ? 1 : 0, configCompareResult, flags, - isAtvDevice == JNI_TRUE ? 1 : 0, user_data_directory); + int ret = sBluetoothInterface->init(&sBluetoothCallbacks, isGuest == JNI_TRUE ? 1 : 0, + isCommonCriteriaMode == JNI_TRUE ? 1 : 0, configCompareResult, + flags, isAtvDevice == JNI_TRUE ? 1 : 0, user_data_directory); env->ReleaseStringUTFChars(userDataDirectory, user_data_directory); @@ -1054,8 +1013,7 @@ static bool initNative(JNIEnv* env, jobject obj, jboolean isGuest, } sBluetoothSocketInterface = - (btsock_interface_t*)sBluetoothInterface->get_profile_interface( - BT_PROFILE_SOCKETS_ID); + (btsock_interface_t*)sBluetoothInterface->get_profile_interface(BT_PROFILE_SOCKETS_ID); if (sBluetoothSocketInterface == NULL) { log::error("Error getting socket interface"); } @@ -1068,7 +1026,9 @@ static bool cleanupNative(JNIEnv* env, jobject /* obj */) { log::verbose(""); - if (!sBluetoothInterface) return JNI_FALSE; + if (!sBluetoothInterface) { + return JNI_FALSE; + } sBluetoothInterface->cleanup(); log::info("return from cleanup"); @@ -1093,16 +1053,19 @@ static bool cleanupNative(JNIEnv* env, jobject /* obj */) { static jboolean enableNative(JNIEnv* /* env */, jobject /* obj */) { log::verbose(""); - if (!sBluetoothInterface) return JNI_FALSE; + if (!sBluetoothInterface) { + return JNI_FALSE; + } int ret = sBluetoothInterface->enable(); - return (ret == BT_STATUS_SUCCESS || ret == BT_STATUS_DONE) ? JNI_TRUE - : JNI_FALSE; + return (ret == BT_STATUS_SUCCESS || ret == BT_STATUS_DONE) ? JNI_TRUE : JNI_FALSE; } static jboolean disableNative(JNIEnv* /* env */, jobject /* obj */) { log::verbose(""); - if (!sBluetoothInterface) return JNI_FALSE; + if (!sBluetoothInterface) { + return JNI_FALSE; + } int ret = sBluetoothInterface->disable(); /* Retrun JNI_FALSE only when BTIF explicitly reports @@ -1115,7 +1078,9 @@ static jboolean disableNative(JNIEnv* /* env */, jobject /* obj */) { static jboolean startDiscoveryNative(JNIEnv* /* env */, jobject /* obj */) { log::verbose(""); - if (!sBluetoothInterface) return JNI_FALSE; + if (!sBluetoothInterface) { + return JNI_FALSE; + } int ret = sBluetoothInterface->start_discovery(); return (ret == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; @@ -1124,18 +1089,21 @@ static jboolean startDiscoveryNative(JNIEnv* /* env */, jobject /* obj */) { static jboolean cancelDiscoveryNative(JNIEnv* /* env */, jobject /* obj */) { log::verbose(""); - if (!sBluetoothInterface) return JNI_FALSE; + if (!sBluetoothInterface) { + return JNI_FALSE; + } int ret = sBluetoothInterface->cancel_discovery(); return (ret == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } -static jboolean createBondNative(JNIEnv* env, jobject /* obj */, - jbyteArray address, jint addrType, +static jboolean createBondNative(JNIEnv* env, jobject /* obj */, jbyteArray address, jint addrType, jint transport) { log::verbose(""); - if (!sBluetoothInterface) return JNI_FALSE; + if (!sBluetoothInterface) { + return JNI_FALSE; + } jbyte* addr = env->GetByteArrayElements(address, NULL); if (addr == NULL) { @@ -1159,8 +1127,7 @@ static jboolean createBondNative(JNIEnv* env, jobject /* obj */, return (ret == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } -static jbyteArray callByteArrayGetter(JNIEnv* env, jobject object, - const char* className, +static jbyteArray callByteArrayGetter(JNIEnv* env, jobject object, const char* className, const char* methodName) { jclass myClass = env->FindClass(className); jmethodID myMethod = env->GetMethodID(myClass, methodName, "()[B"); @@ -1176,8 +1143,7 @@ static jint callIntGetter(JNIEnv* env, jobject object, const char* className, return env->CallIntMethod(object, myMethod); } -static jboolean set_data(JNIEnv* env, bt_oob_data_t& oob_data, jobject oobData, - jint transport) { +static jboolean set_data(JNIEnv* env, bt_oob_data_t& oob_data, jobject oobData, jint transport) { // Need both arguments to be non NULL if (oobData == NULL) { log::error("oobData is null! Nothing to do."); @@ -1186,14 +1152,13 @@ static jboolean set_data(JNIEnv* env, bt_oob_data_t& oob_data, jobject oobData, memset(&oob_data, 0, sizeof(oob_data)); - jbyteArray address = callByteArrayGetter( - env, oobData, "android/bluetooth/OobData", "getDeviceAddressWithType"); + jbyteArray address = callByteArrayGetter(env, oobData, "android/bluetooth/OobData", + "getDeviceAddressWithType"); // Check the data int len = env->GetArrayLength(address); if (len != OOB_ADDRESS_SIZE) { - log::error( - "addressBytes must be 7 bytes in length (address plus type) 6+1!"); + log::error("addressBytes must be 7 bytes in length (address plus type) 6+1!"); jniThrowIOException(env, EINVAL); return JNI_FALSE; } @@ -1208,8 +1173,8 @@ static jboolean set_data(JNIEnv* env, bt_oob_data_t& oob_data, jobject oobData, memcpy(oob_data.address, addressBytes, len); // Get the device name byte[] java object - jbyteArray deviceName = callByteArrayGetter( - env, oobData, "android/bluetooth/OobData", "getDeviceName"); + jbyteArray deviceName = + callByteArrayGetter(env, oobData, "android/bluetooth/OobData", "getDeviceName"); // Optional // Convert it to a jbyte* and copy it to the struct @@ -1219,9 +1184,9 @@ static jboolean set_data(JNIEnv* env, bt_oob_data_t& oob_data, jobject oobData, int len = env->GetArrayLength(deviceName); if (len > OOB_NAME_MAX_SIZE) { log::info( - "wrong length of deviceName, should be empty or less than or equal " - "to {} bytes.", - OOB_NAME_MAX_SIZE); + "wrong length of deviceName, should be empty or less than or equal " + "to {} bytes.", + OOB_NAME_MAX_SIZE); jniThrowIOException(env, EINVAL); env->ReleaseByteArrayElements(deviceName, deviceNameBytes, 0); return JNI_FALSE; @@ -1230,8 +1195,8 @@ static jboolean set_data(JNIEnv* env, bt_oob_data_t& oob_data, jobject oobData, env->ReleaseByteArrayElements(deviceName, deviceNameBytes, 0); } // Used by both classic and LE - jbyteArray confirmation = callByteArrayGetter( - env, oobData, "android/bluetooth/OobData", "getConfirmationHash"); + jbyteArray confirmation = + callByteArrayGetter(env, oobData, "android/bluetooth/OobData", "getConfirmationHash"); if (confirmation == NULL) { log::error("confirmation cannot be null!"); jniThrowIOException(env, EINVAL); @@ -1243,8 +1208,7 @@ static jboolean set_data(JNIEnv* env, bt_oob_data_t& oob_data, jobject oobData, confirmationBytes = env->GetByteArrayElements(confirmation, NULL); len = env->GetArrayLength(confirmation); if (confirmationBytes == NULL || len != OOB_C_SIZE) { - log::info("wrong length of Confirmation, should be empty or {} bytes.", - OOB_C_SIZE); + log::info("wrong length of Confirmation, should be empty or {} bytes.", OOB_C_SIZE); jniThrowIOException(env, EINVAL); env->ReleaseByteArrayElements(confirmation, confirmationBytes, 0); return JNI_FALSE; @@ -1253,15 +1217,14 @@ static jboolean set_data(JNIEnv* env, bt_oob_data_t& oob_data, jobject oobData, env->ReleaseByteArrayElements(confirmation, confirmationBytes, 0); // Random is supposedly optional according to the specification - jbyteArray randomizer = callByteArrayGetter( - env, oobData, "android/bluetooth/OobData", "getRandomizerHash"); + jbyteArray randomizer = + callByteArrayGetter(env, oobData, "android/bluetooth/OobData", "getRandomizerHash"); jbyte* randomizerBytes = NULL; if (randomizer != NULL) { randomizerBytes = env->GetByteArrayElements(randomizer, NULL); int len = env->GetArrayLength(randomizer); if (randomizerBytes == NULL || len != OOB_R_SIZE) { - log::info("wrong length of Random, should be empty or {} bytes.", - OOB_R_SIZE); + log::info("wrong length of Random, should be empty or {} bytes.", OOB_R_SIZE); jniThrowIOException(env, EINVAL); env->ReleaseByteArrayElements(randomizer, randomizerBytes, 0); return JNI_FALSE; @@ -1274,13 +1237,11 @@ static jboolean set_data(JNIEnv* env, bt_oob_data_t& oob_data, jobject oobData, if (transport == TRANSPORT_BREDR) { // Classic // Not optional - jbyteArray oobDataLength = callByteArrayGetter( - env, oobData, "android/bluetooth/OobData", "getClassicLength"); + jbyteArray oobDataLength = + callByteArrayGetter(env, oobData, "android/bluetooth/OobData", "getClassicLength"); jbyte* oobDataLengthBytes = NULL; - if (oobDataLength == NULL || - env->GetArrayLength(oobDataLength) != OOB_DATA_LEN_SIZE) { - log::info("wrong length of oobDataLength, should be empty or {} bytes.", - OOB_DATA_LEN_SIZE); + if (oobDataLength == NULL || env->GetArrayLength(oobDataLength) != OOB_DATA_LEN_SIZE) { + log::info("wrong length of oobDataLength, should be empty or {} bytes.", OOB_DATA_LEN_SIZE); jniThrowIOException(env, EINVAL); env->ReleaseByteArrayElements(oobDataLength, oobDataLengthBytes, 0); return JNI_FALSE; @@ -1291,15 +1252,14 @@ static jboolean set_data(JNIEnv* env, bt_oob_data_t& oob_data, jobject oobData, env->ReleaseByteArrayElements(oobDataLength, oobDataLengthBytes, 0); // Optional - jbyteArray classOfDevice = callByteArrayGetter( - env, oobData, "android/bluetooth/OobData", "getClassOfDevice"); + jbyteArray classOfDevice = + callByteArrayGetter(env, oobData, "android/bluetooth/OobData", "getClassOfDevice"); jbyte* classOfDeviceBytes = NULL; if (classOfDevice != NULL) { classOfDeviceBytes = env->GetByteArrayElements(classOfDevice, NULL); int len = env->GetArrayLength(classOfDevice); if (len != OOB_COD_SIZE) { - log::info("wrong length of classOfDevice, should be empty or {} bytes.", - OOB_COD_SIZE); + log::info("wrong length of classOfDevice, should be empty or {} bytes.", OOB_COD_SIZE); jniThrowIOException(env, EINVAL); env->ReleaseByteArrayElements(classOfDevice, classOfDeviceBytes, 0); return JNI_FALSE; @@ -1309,15 +1269,14 @@ static jboolean set_data(JNIEnv* env, bt_oob_data_t& oob_data, jobject oobData, } } else if (transport == TRANSPORT_LE) { // LE - jbyteArray temporaryKey = callByteArrayGetter( - env, oobData, "android/bluetooth/OobData", "getLeTemporaryKey"); + jbyteArray temporaryKey = + callByteArrayGetter(env, oobData, "android/bluetooth/OobData", "getLeTemporaryKey"); jbyte* temporaryKeyBytes = NULL; if (temporaryKey != NULL) { temporaryKeyBytes = env->GetByteArrayElements(temporaryKey, NULL); int len = env->GetArrayLength(temporaryKey); if (len != OOB_TK_SIZE) { - log::info("wrong length of temporaryKey, should be empty or {} bytes.", - OOB_TK_SIZE); + log::info("wrong length of temporaryKey, should be empty or {} bytes.", OOB_TK_SIZE); jniThrowIOException(env, EINVAL); env->ReleaseByteArrayElements(temporaryKey, temporaryKeyBytes, 0); return JNI_FALSE; @@ -1326,8 +1285,8 @@ static jboolean set_data(JNIEnv* env, bt_oob_data_t& oob_data, jobject oobData, env->ReleaseByteArrayElements(temporaryKey, temporaryKeyBytes, 0); } - jbyteArray leAppearance = callByteArrayGetter( - env, oobData, "android/bluetooth/OobData", "getLeAppearance"); + jbyteArray leAppearance = + callByteArrayGetter(env, oobData, "android/bluetooth/OobData", "getLeAppearance"); jbyte* leAppearanceBytes = NULL; if (leAppearance != NULL) { leAppearanceBytes = env->GetByteArrayElements(leAppearance, NULL); @@ -1343,24 +1302,22 @@ static jboolean set_data(JNIEnv* env, bt_oob_data_t& oob_data, jobject oobData, env->ReleaseByteArrayElements(leAppearance, leAppearanceBytes, 0); } - jint leRole = callIntGetter(env, oobData, "android/bluetooth/OobData", - "getLeDeviceRole"); + jint leRole = callIntGetter(env, oobData, "android/bluetooth/OobData", "getLeDeviceRole"); oob_data.le_device_role = leRole; - jint leFlag = - callIntGetter(env, oobData, "android/bluetooth/OobData", "getLeFlags"); + jint leFlag = callIntGetter(env, oobData, "android/bluetooth/OobData", "getLeFlags"); oob_data.le_flags = leFlag; } return JNI_TRUE; } -static void generateLocalOobDataNative(JNIEnv* /* env */, jobject /* obj */, - jint transport) { +static void generateLocalOobDataNative(JNIEnv* /* env */, jobject /* obj */, jint transport) { // No BT interface? Can't do anything. - if (!sBluetoothInterface) return; + if (!sBluetoothInterface) { + return; + } - if (sBluetoothInterface->generate_local_oob_data(transport) != - BT_STATUS_SUCCESS) { + if (sBluetoothInterface->generate_local_oob_data(transport) != BT_STATUS_SUCCESS) { log::error("Call to generate_local_oob_data failed!"); bt_oob_data_t oob_data; oob_data.is_valid = false; @@ -1368,11 +1325,12 @@ static void generateLocalOobDataNative(JNIEnv* /* env */, jobject /* obj */, } } -static jboolean createBondOutOfBandNative(JNIEnv* env, jobject /* obj */, - jbyteArray address, jint transport, - jobject p192Data, jobject p256Data) { +static jboolean createBondOutOfBandNative(JNIEnv* env, jobject /* obj */, jbyteArray address, + jint transport, jobject p192Data, jobject p256Data) { // No BT interface? Can't do anything. - if (!sBluetoothInterface) return JNI_FALSE; + if (!sBluetoothInterface) { + return JNI_FALSE; + } // No data? Can't do anything if (p192Data == NULL && p256Data == NULL) { @@ -1393,8 +1351,7 @@ static jboolean createBondOutOfBandNative(JNIEnv* env, jobject /* obj */, // Check the data int len = env->GetArrayLength(address); if (len != 6) { - log::error( - "addressBytes must be 6 bytes in length (address plus type) 6+1!"); + log::error("addressBytes must be 6 bytes in length (address plus type) 6+1!"); jniThrowIOException(env, EINVAL); return JNI_FALSE; } @@ -1423,18 +1380,18 @@ static jboolean createBondOutOfBandNative(JNIEnv* env, jobject /* obj */, } } - return ((sBluetoothInterface->create_bond_out_of_band( - (RawAddress*)addr, transport, &p192_data, &p256_data)) == - BT_STATUS_SUCCESS) - ? JNI_TRUE - : JNI_FALSE; + return ((sBluetoothInterface->create_bond_out_of_band((RawAddress*)addr, transport, &p192_data, + &p256_data)) == BT_STATUS_SUCCESS) + ? JNI_TRUE + : JNI_FALSE; } -static jboolean removeBondNative(JNIEnv* env, jobject /* obj */, - jbyteArray address) { +static jboolean removeBondNative(JNIEnv* env, jobject /* obj */, jbyteArray address) { log::verbose(""); - if (!sBluetoothInterface) return JNI_FALSE; + if (!sBluetoothInterface) { + return JNI_FALSE; + } jbyte* addr = env->GetByteArrayElements(address, NULL); if (addr == NULL) { @@ -1448,11 +1405,12 @@ static jboolean removeBondNative(JNIEnv* env, jobject /* obj */, return (ret == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } -static jboolean cancelBondNative(JNIEnv* env, jobject /* obj */, - jbyteArray address) { +static jboolean cancelBondNative(JNIEnv* env, jobject /* obj */, jbyteArray address) { log::verbose(""); - if (!sBluetoothInterface) return JNI_FALSE; + if (!sBluetoothInterface) { + return JNI_FALSE; + } jbyte* addr = env->GetByteArrayElements(address, NULL); if (addr == NULL) { @@ -1468,15 +1426,18 @@ static jboolean cancelBondNative(JNIEnv* env, jobject /* obj */, static jboolean pairingIsBusyNative(JNIEnv* /*env*/, jobject /* obj */) { log::verbose(""); - if (!sBluetoothInterface) return JNI_FALSE; + if (!sBluetoothInterface) { + return JNI_FALSE; + } return sBluetoothInterface->pairing_is_busy(); } -static int getConnectionStateNative(JNIEnv* env, jobject /* obj */, - jbyteArray address) { +static int getConnectionStateNative(JNIEnv* env, jobject /* obj */, jbyteArray address) { log::verbose(""); - if (!sBluetoothInterface) return JNI_FALSE; + if (!sBluetoothInterface) { + return JNI_FALSE; + } jbyte* addr = env->GetByteArrayElements(address, NULL); if (addr == NULL) { @@ -1490,12 +1451,13 @@ static int getConnectionStateNative(JNIEnv* env, jobject /* obj */, return ret; } -static jboolean pinReplyNative(JNIEnv* env, jobject /* obj */, - jbyteArray address, jboolean accept, jint len, - jbyteArray pinArray) { +static jboolean pinReplyNative(JNIEnv* env, jobject /* obj */, jbyteArray address, jboolean accept, + jint len, jbyteArray pinArray) { log::verbose(""); - if (!sBluetoothInterface) return JNI_FALSE; + if (!sBluetoothInterface) { + return JNI_FALSE; + } jbyte* addr = env->GetByteArrayElements(address, NULL); if (addr == NULL) { @@ -1513,20 +1475,20 @@ static jboolean pinReplyNative(JNIEnv* env, jobject /* obj */, } } - int ret = sBluetoothInterface->pin_reply((RawAddress*)addr, accept, len, - (bt_pin_code_t*)pinPtr); + int ret = sBluetoothInterface->pin_reply((RawAddress*)addr, accept, len, (bt_pin_code_t*)pinPtr); env->ReleaseByteArrayElements(address, addr, 0); env->ReleaseByteArrayElements(pinArray, pinPtr, 0); return (ret == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } -static jboolean sspReplyNative(JNIEnv* env, jobject /* obj */, - jbyteArray address, jint type, jboolean accept, - jint passkey) { +static jboolean sspReplyNative(JNIEnv* env, jobject /* obj */, jbyteArray address, jint type, + jboolean accept, jint passkey) { log::verbose(""); - if (!sBluetoothInterface) return JNI_FALSE; + if (!sBluetoothInterface) { + return JNI_FALSE; + } jbyte* addr = env->GetByteArrayElements(address, NULL); if (addr == NULL) { @@ -1534,28 +1496,31 @@ static jboolean sspReplyNative(JNIEnv* env, jobject /* obj */, return JNI_FALSE; } - int ret = sBluetoothInterface->ssp_reply( - (RawAddress*)addr, (bt_ssp_variant_t)type, accept, passkey); + int ret = sBluetoothInterface->ssp_reply((RawAddress*)addr, (bt_ssp_variant_t)type, accept, + passkey); env->ReleaseByteArrayElements(address, addr, 0); return (ret == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } -static jboolean setScanModeNative(JNIEnv* /* env */, jobject /* obj */, - jint mode) { +static jboolean setScanModeNative(JNIEnv* /* env */, jobject /* obj */, jint mode) { log::verbose(""); - if (!sBluetoothInterface) return JNI_FALSE; + if (!sBluetoothInterface) { + return JNI_FALSE; + } sBluetoothInterface->set_scan_mode((bt_scan_mode_t)mode); return JNI_TRUE; } -static jboolean setAdapterPropertyNative(JNIEnv* env, jobject /* obj */, - jint type, jbyteArray value) { +static jboolean setAdapterPropertyNative(JNIEnv* env, jobject /* obj */, jint type, + jbyteArray value) { log::verbose(""); - if (!sBluetoothInterface) return JNI_FALSE; + if (!sBluetoothInterface) { + return JNI_FALSE; + } jbyte* val = env->GetByteArrayElements(value, NULL); bt_property_t prop; @@ -1569,31 +1534,35 @@ static jboolean setAdapterPropertyNative(JNIEnv* env, jobject /* obj */, return (ret == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } -static jboolean getAdapterPropertiesNative(JNIEnv* /* env */, - jobject /* obj */) { +static jboolean getAdapterPropertiesNative(JNIEnv* /* env */, jobject /* obj */) { log::verbose(""); - if (!sBluetoothInterface) return JNI_FALSE; + if (!sBluetoothInterface) { + return JNI_FALSE; + } int ret = sBluetoothInterface->get_adapter_properties(); return (ret == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } -static jboolean getAdapterPropertyNative(JNIEnv* /* env */, jobject /* obj */, - jint type) { +static jboolean getAdapterPropertyNative(JNIEnv* /* env */, jobject /* obj */, jint type) { log::verbose(""); - if (!sBluetoothInterface) return JNI_FALSE; + if (!sBluetoothInterface) { + return JNI_FALSE; + } int ret = sBluetoothInterface->get_adapter_property((bt_property_type_t)type); return (ret == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } -static jboolean getDevicePropertyNative(JNIEnv* env, jobject /* obj */, - jbyteArray address, jint type) { +static jboolean getDevicePropertyNative(JNIEnv* env, jobject /* obj */, jbyteArray address, + jint type) { log::verbose(""); - if (!sBluetoothInterface) return JNI_FALSE; + if (!sBluetoothInterface) { + return JNI_FALSE; + } jbyte* addr = env->GetByteArrayElements(address, NULL); if (addr == NULL) { @@ -1601,18 +1570,19 @@ static jboolean getDevicePropertyNative(JNIEnv* env, jobject /* obj */, return JNI_FALSE; } - int ret = sBluetoothInterface->get_remote_device_property( - (RawAddress*)addr, (bt_property_type_t)type); + int ret = sBluetoothInterface->get_remote_device_property((RawAddress*)addr, + (bt_property_type_t)type); env->ReleaseByteArrayElements(address, addr, 0); return (ret == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } -static jboolean setDevicePropertyNative(JNIEnv* env, jobject /* obj */, - jbyteArray address, jint type, - jbyteArray value) { +static jboolean setDevicePropertyNative(JNIEnv* env, jobject /* obj */, jbyteArray address, + jint type, jbyteArray value) { log::verbose(""); - if (!sBluetoothInterface) return JNI_FALSE; + if (!sBluetoothInterface) { + return JNI_FALSE; + } jbyte* val = env->GetByteArrayElements(value, NULL); if (val == NULL) { @@ -1632,19 +1602,20 @@ static jboolean setDevicePropertyNative(JNIEnv* env, jobject /* obj */, prop.len = env->GetArrayLength(value); prop.val = val; - int ret = - sBluetoothInterface->set_remote_device_property((RawAddress*)addr, &prop); + int ret = sBluetoothInterface->set_remote_device_property((RawAddress*)addr, &prop); env->ReleaseByteArrayElements(value, val, 0); env->ReleaseByteArrayElements(address, addr, 0); return (ret == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } -static jboolean getRemoteServicesNative(JNIEnv* env, jobject /* obj */, - jbyteArray address, jint transport) { +static jboolean getRemoteServicesNative(JNIEnv* env, jobject /* obj */, jbyteArray address, + jint transport) { log::verbose(""); - if (!sBluetoothInterface) return JNI_FALSE; + if (!sBluetoothInterface) { + return JNI_FALSE; + } jbyte* addr = addr = env->GetByteArrayElements(address, NULL); if (addr == NULL) { @@ -1652,8 +1623,7 @@ static jboolean getRemoteServicesNative(JNIEnv* env, jobject /* obj */, return JNI_FALSE; } - int ret = - sBluetoothInterface->get_remote_services((RawAddress*)addr, transport); + int ret = sBluetoothInterface->get_remote_services((RawAddress*)addr, transport); env->ReleaseByteArrayElements(address, addr, 0); return (ret == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } @@ -1661,18 +1631,23 @@ static jboolean getRemoteServicesNative(JNIEnv* env, jobject /* obj */, static int readEnergyInfoNative() { log::verbose(""); - if (!sBluetoothInterface) return JNI_FALSE; + if (!sBluetoothInterface) { + return JNI_FALSE; + } int ret = sBluetoothInterface->read_energy_info(); return (ret == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } -static void dumpNative(JNIEnv* env, jobject /* obj */, jobject fdObj, - jobjectArray argArray) { +static void dumpNative(JNIEnv* env, jobject /* obj */, jobject fdObj, jobjectArray argArray) { log::verbose(""); - if (!sBluetoothInterface) return; + if (!sBluetoothInterface) { + return; + } int fd = jniGetFDFromFileDescriptor(env, fdObj); - if (fd < 0) return; + if (fd < 0) { + return; + } int numArgs = env->GetArrayLength(argArray); @@ -1700,28 +1675,32 @@ static void dumpNative(JNIEnv* env, jobject /* obj */, jobject fdObj, static jbyteArray dumpMetricsNative(JNIEnv* env, jobject /* obj */) { log::info(""); - if (!sBluetoothInterface) return env->NewByteArray(0); + if (!sBluetoothInterface) { + return env->NewByteArray(0); + } std::string output; sBluetoothInterface->dumpMetrics(&output); jsize output_size = output.size() * sizeof(char); jbyteArray output_bytes = env->NewByteArray(output_size); - env->SetByteArrayRegion(output_bytes, 0, output_size, - (const jbyte*)output.data()); + env->SetByteArrayRegion(output_bytes, 0, output_size, (const jbyte*)output.data()); return output_bytes; } static jboolean factoryResetNative(JNIEnv* /* env */, jobject /* obj */) { log::verbose(""); - if (!sBluetoothInterface) return JNI_FALSE; + if (!sBluetoothInterface) { + return JNI_FALSE; + } int ret = sBluetoothInterface->config_clear(); return (ret == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } -static jbyteArray obfuscateAddressNative(JNIEnv* env, jobject /* obj */, - jbyteArray address) { +static jbyteArray obfuscateAddressNative(JNIEnv* env, jobject /* obj */, jbyteArray address) { log::verbose(""); - if (!sBluetoothInterface) return env->NewByteArray(0); + if (!sBluetoothInterface) { + return env->NewByteArray(0); + } jbyte* addr = env->GetByteArrayElements(address, nullptr); if (addr == nullptr) { jniThrowIOException(env, EINVAL); @@ -1732,25 +1711,24 @@ static jbyteArray obfuscateAddressNative(JNIEnv* env, jobject /* obj */, std::string output = sBluetoothInterface->obfuscate_address(addr_obj); jsize output_size = output.size() * sizeof(char); jbyteArray output_bytes = env->NewByteArray(output_size); - env->SetByteArrayRegion(output_bytes, 0, output_size, - (const jbyte*)output.data()); + env->SetByteArrayRegion(output_bytes, 0, output_size, (const jbyte*)output.data()); return output_bytes; } -static jboolean setBufferLengthMillisNative(JNIEnv* /* env */, - jobject /* obj */, jint codec, +static jboolean setBufferLengthMillisNative(JNIEnv* /* env */, jobject /* obj */, jint codec, jint size) { log::verbose(""); - if (!sBluetoothInterface) return JNI_FALSE; + if (!sBluetoothInterface) { + return JNI_FALSE; + } int ret = sBluetoothInterface->set_dynamic_audio_buffer_size(codec, size); return (ret == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } -static jint connectSocketNative(JNIEnv* env, jobject /* obj */, - jbyteArray address, jint type, jbyteArray uuid, - jint port, jint flag, jint callingUid) { +static jint connectSocketNative(JNIEnv* env, jobject /* obj */, jbyteArray address, jint type, + jbyteArray uuid, jint port, jint flag, jint callingUid) { int socket_fd = INVALID_FD; jbyte* addr = nullptr; jbyte* uuidBytes = nullptr; @@ -1767,21 +1745,24 @@ static jint connectSocketNative(JNIEnv* env, jobject /* obj */, } btUuid = Uuid::From128BitBE((uint8_t*)uuidBytes); - if (sBluetoothSocketInterface->connect((RawAddress*)addr, (btsock_type_t)type, - &btUuid, port, &socket_fd, flag, - callingUid) != BT_STATUS_SUCCESS) { + if (sBluetoothSocketInterface->connect((RawAddress*)addr, (btsock_type_t)type, &btUuid, port, + &socket_fd, flag, callingUid) != BT_STATUS_SUCCESS) { socket_fd = INVALID_FD; } done: - if (addr) env->ReleaseByteArrayElements(address, addr, 0); - if (uuidBytes) env->ReleaseByteArrayElements(uuid, uuidBytes, 0); + if (addr) { + env->ReleaseByteArrayElements(address, addr, 0); + } + if (uuidBytes) { + env->ReleaseByteArrayElements(uuid, uuidBytes, 0); + } return socket_fd; } static jint createSocketChannelNative(JNIEnv* env, jobject /* obj */, jint type, - jstring serviceName, jbyteArray uuid, - jint port, jint flag, jint callingUid) { + jstring serviceName, jbyteArray uuid, jint port, jint flag, + jint callingUid) { int socket_fd = INVALID_FD; jbyte* uuidBytes = nullptr; Uuid btUuid; @@ -1800,21 +1781,22 @@ static jint createSocketChannelNative(JNIEnv* env, jobject /* obj */, jint type, } btUuid = Uuid::From128BitBE((uint8_t*)uuidBytes); - if (sBluetoothSocketInterface->listen((btsock_type_t)type, nativeServiceName, - &btUuid, port, &socket_fd, flag, - callingUid) != BT_STATUS_SUCCESS) { + if (sBluetoothSocketInterface->listen((btsock_type_t)type, nativeServiceName, &btUuid, port, + &socket_fd, flag, callingUid) != BT_STATUS_SUCCESS) { socket_fd = INVALID_FD; } done: - if (uuidBytes) env->ReleaseByteArrayElements(uuid, uuidBytes, 0); - if (nativeServiceName) + if (uuidBytes) { + env->ReleaseByteArrayElements(uuid, uuidBytes, 0); + } + if (nativeServiceName) { env->ReleaseStringUTFChars(serviceName, nativeServiceName); + } return socket_fd; } -static void requestMaximumTxDataLengthNative(JNIEnv* env, jobject /* obj */, - jbyteArray address) { +static void requestMaximumTxDataLengthNative(JNIEnv* env, jobject /* obj */, jbyteArray address) { if (!sBluetoothSocketInterface) { return; } @@ -1829,10 +1811,11 @@ static void requestMaximumTxDataLengthNative(JNIEnv* env, jobject /* obj */, env->ReleaseByteArrayElements(address, addr, 1); } -static int getMetricIdNative(JNIEnv* env, jobject /* obj */, - jbyteArray address) { +static int getMetricIdNative(JNIEnv* env, jobject /* obj */, jbyteArray address) { log::verbose(""); - if (!sBluetoothInterface) return 0; // 0 is invalid id + if (!sBluetoothInterface) { + return 0; // 0 is invalid id + } jbyte* addr = env->GetByteArrayElements(address, nullptr); if (addr == nullptr) { jniThrowIOException(env, EINVAL); @@ -1843,11 +1826,12 @@ static int getMetricIdNative(JNIEnv* env, jobject /* obj */, return sBluetoothInterface->get_metric_id(addr_obj); } -static jboolean allowLowLatencyAudioNative(JNIEnv* env, jobject /* obj */, - jboolean allowed, +static jboolean allowLowLatencyAudioNative(JNIEnv* env, jobject /* obj */, jboolean allowed, jbyteArray address) { log::verbose(""); - if (!sBluetoothInterface) return false; + if (!sBluetoothInterface) { + return false; + } jbyte* addr = env->GetByteArrayElements(address, nullptr); if (addr == nullptr) { jniThrowIOException(env, EINVAL); @@ -1860,11 +1844,12 @@ static jboolean allowLowLatencyAudioNative(JNIEnv* env, jobject /* obj */, return true; } -static void metadataChangedNative(JNIEnv* env, jobject /* obj */, - jbyteArray address, jint key, +static void metadataChangedNative(JNIEnv* env, jobject /* obj */, jbyteArray address, jint key, jbyteArray value) { log::verbose(""); - if (!sBluetoothInterface) return; + if (!sBluetoothInterface) { + return; + } jbyte* addr = env->GetByteArrayElements(address, nullptr); if (addr == nullptr) { jniThrowIOException(env, EINVAL); @@ -1880,7 +1865,9 @@ static void metadataChangedNative(JNIEnv* env, jobject /* obj */, uint16_t len = (uint16_t)env->GetArrayLength(value); jbyte* p_value = env->GetByteArrayElements(value, NULL); - if (p_value == NULL) return; + if (p_value == NULL) { + return; + } std::vector val_vec(reinterpret_cast(p_value), reinterpret_cast(p_value + len)); @@ -1890,14 +1877,13 @@ static void metadataChangedNative(JNIEnv* env, jobject /* obj */, return; } -static jboolean isLogRedactionEnabledNative(JNIEnv* /* env */, - jobject /* obj */) { +static jboolean isLogRedactionEnabledNative(JNIEnv* /* env */, jobject /* obj */) { log::verbose(""); return bluetooth::os::should_log_be_redacted(); } -static jboolean interopMatchAddrNative(JNIEnv* env, jclass /* clazz */, - jstring feature_name, jstring address) { +static jboolean interopMatchAddrNative(JNIEnv* env, jclass /* clazz */, jstring feature_name, + jstring address) { log::verbose(""); if (!sBluetoothInterface) { @@ -1926,15 +1912,14 @@ static jboolean interopMatchAddrNative(JNIEnv* env, jclass /* clazz */, return JNI_FALSE; } - bool matched = - sBluetoothInterface->interop_match_addr(feature_name_str, &bdaddr); + bool matched = sBluetoothInterface->interop_match_addr(feature_name_str, &bdaddr); env->ReleaseStringUTFChars(feature_name, feature_name_str); return matched ? JNI_TRUE : JNI_FALSE; } -static jboolean interopMatchNameNative(JNIEnv* env, jclass /* clazz */, - jstring feature_name, jstring name) { +static jboolean interopMatchNameNative(JNIEnv* env, jclass /* clazz */, jstring feature_name, + jstring name) { log::verbose(""); if (!sBluetoothInterface) { @@ -1955,16 +1940,14 @@ static jboolean interopMatchNameNative(JNIEnv* env, jclass /* clazz */, return JNI_FALSE; } - bool matched = - sBluetoothInterface->interop_match_name(feature_name_str, name_str); + bool matched = sBluetoothInterface->interop_match_name(feature_name_str, name_str); env->ReleaseStringUTFChars(feature_name, feature_name_str); env->ReleaseStringUTFChars(name, name_str); return matched ? JNI_TRUE : JNI_FALSE; } -static jboolean interopMatchAddrOrNameNative(JNIEnv* env, jclass /* clazz */, - jstring feature_name, +static jboolean interopMatchAddrOrNameNative(JNIEnv* env, jclass /* clazz */, jstring feature_name, jstring address) { log::verbose(""); @@ -1994,17 +1977,14 @@ static jboolean interopMatchAddrOrNameNative(JNIEnv* env, jclass /* clazz */, return JNI_FALSE; } - bool matched = sBluetoothInterface->interop_match_addr_or_name( - feature_name_str, &bdaddr); + bool matched = sBluetoothInterface->interop_match_addr_or_name(feature_name_str, &bdaddr); env->ReleaseStringUTFChars(feature_name, feature_name_str); return matched ? JNI_TRUE : JNI_FALSE; } -static void interopDatabaseAddRemoveAddrNative(JNIEnv* env, jclass /* clazz */, - jboolean do_add, - jstring feature_name, - jstring address, jint length) { +static void interopDatabaseAddRemoveAddrNative(JNIEnv* env, jclass /* clazz */, jboolean do_add, + jstring feature_name, jstring address, jint length) { log::verbose(""); if (!sBluetoothInterface) { @@ -2038,16 +2018,14 @@ static void interopDatabaseAddRemoveAddrNative(JNIEnv* env, jclass /* clazz */, return; } - sBluetoothInterface->interop_database_add_remove_addr( - (do_add == JNI_TRUE), feature_name_str, &bdaddr, (int)length); + sBluetoothInterface->interop_database_add_remove_addr((do_add == JNI_TRUE), feature_name_str, + &bdaddr, (int)length); env->ReleaseStringUTFChars(feature_name, feature_name_str); } -static void interopDatabaseAddRemoveNameNative(JNIEnv* env, jclass /* clazz */, - jboolean do_add, - jstring feature_name, - jstring name) { +static void interopDatabaseAddRemoveNameNative(JNIEnv* env, jclass /* clazz */, jboolean do_add, + jstring feature_name, jstring name) { log::verbose(""); if (!sBluetoothInterface) { @@ -2068,18 +2046,19 @@ static void interopDatabaseAddRemoveNameNative(JNIEnv* env, jclass /* clazz */, return; } - sBluetoothInterface->interop_database_add_remove_name( - (do_add == JNI_TRUE), feature_name_str, name_str); + sBluetoothInterface->interop_database_add_remove_name((do_add == JNI_TRUE), feature_name_str, + name_str); env->ReleaseStringUTFChars(feature_name, feature_name_str); env->ReleaseStringUTFChars(name, name_str); } -static int getRemotePbapPceVersionNative(JNIEnv* env, jobject /* obj */, - jstring address) { +static int getRemotePbapPceVersionNative(JNIEnv* env, jobject /* obj */, jstring address) { log::verbose(""); - if (!sBluetoothInterface) return JNI_FALSE; + if (!sBluetoothInterface) { + return JNI_FALSE; + } const char* tmp_addr = env->GetStringUTFChars(address, NULL); if (!tmp_addr) { @@ -2100,21 +2079,18 @@ static int getRemotePbapPceVersionNative(JNIEnv* env, jobject /* obj */, return sBluetoothInterface->get_remote_pbap_pce_version(&bdaddr); } -static jboolean pbapPseDynamicVersionUpgradeIsEnabledNative(JNIEnv* /* env */, - jobject /* obj */) { +static jboolean pbapPseDynamicVersionUpgradeIsEnabledNative(JNIEnv* /* env */, jobject /* obj */) { log::verbose(""); - if (!sBluetoothInterface) return JNI_FALSE; + if (!sBluetoothInterface) { + return JNI_FALSE; + } - return sBluetoothInterface->pbap_pse_dynamic_version_upgrade_is_enabled() - ? JNI_TRUE - : JNI_FALSE; + return sBluetoothInterface->pbap_pse_dynamic_version_upgrade_is_enabled() ? JNI_TRUE : JNI_FALSE; } -static jint getSocketL2capLocalChannelIdNative(JNIEnv* /* env */, - jobject /* obj */, - jlong conn_uuid_lsb, - jlong conn_uuid_msb) { +static jint getSocketL2capLocalChannelIdNative(JNIEnv* /* env */, jobject /* obj */, + jlong conn_uuid_lsb, jlong conn_uuid_msb) { log::verbose(""); if (!sBluetoothSocketInterface) { @@ -2122,17 +2098,14 @@ static jint getSocketL2capLocalChannelIdNative(JNIEnv* /* env */, } uint16_t cid; Uuid uuid = from_java_uuid(conn_uuid_msb, conn_uuid_lsb); - if (sBluetoothSocketInterface->get_l2cap_local_cid(uuid, &cid) != - BT_STATUS_SUCCESS) { + if (sBluetoothSocketInterface->get_l2cap_local_cid(uuid, &cid) != BT_STATUS_SUCCESS) { return INVALID_CID; } return (jint)cid; } -static jint getSocketL2capRemoteChannelIdNative(JNIEnv* /* env */, - jobject /* obj */, - jlong conn_uuid_lsb, - jlong conn_uuid_msb) { +static jint getSocketL2capRemoteChannelIdNative(JNIEnv* /* env */, jobject /* obj */, + jlong conn_uuid_lsb, jlong conn_uuid_msb) { log::verbose(""); if (!sBluetoothSocketInterface) { @@ -2140,8 +2113,7 @@ static jint getSocketL2capRemoteChannelIdNative(JNIEnv* /* env */, } uint16_t cid; Uuid uuid = from_java_uuid(conn_uuid_msb, conn_uuid_lsb); - if (sBluetoothSocketInterface->get_l2cap_remote_cid(uuid, &cid) != - BT_STATUS_SUCCESS) { + if (sBluetoothSocketInterface->get_l2cap_remote_cid(uuid, &cid) != BT_STATUS_SUCCESS) { return INVALID_CID; } return (jint)cid; @@ -2149,119 +2121,101 @@ static jint getSocketL2capRemoteChannelIdNative(JNIEnv* /* env */, int register_com_android_bluetooth_btservice_AdapterService(JNIEnv* env) { const JNINativeMethod methods[] = { - {"initNative", "(ZZI[Ljava/lang/String;ZLjava/lang/String;)Z", - (void*)initNative}, - {"cleanupNative", "()V", (void*)cleanupNative}, - {"enableNative", "()Z", (void*)enableNative}, - {"disableNative", "()Z", (void*)disableNative}, - {"setScanModeNative", "(I)Z", (void*)setScanModeNative}, - {"setAdapterPropertyNative", "(I[B)Z", (void*)setAdapterPropertyNative}, - {"getAdapterPropertiesNative", "()Z", (void*)getAdapterPropertiesNative}, - {"getAdapterPropertyNative", "(I)Z", (void*)getAdapterPropertyNative}, - {"getDevicePropertyNative", "([BI)Z", (void*)getDevicePropertyNative}, - {"setDevicePropertyNative", "([BI[B)Z", (void*)setDevicePropertyNative}, - {"startDiscoveryNative", "()Z", (void*)startDiscoveryNative}, - {"cancelDiscoveryNative", "()Z", (void*)cancelDiscoveryNative}, - {"createBondNative", "([BII)Z", (void*)createBondNative}, - {"createBondOutOfBandNative", - "([BILandroid/bluetooth/OobData;Landroid/bluetooth/OobData;)Z", - (void*)createBondOutOfBandNative}, - {"removeBondNative", "([B)Z", (void*)removeBondNative}, - {"cancelBondNative", "([B)Z", (void*)cancelBondNative}, - {"pairingIsBusyNative", "()Z", (void*)pairingIsBusyNative}, - {"generateLocalOobDataNative", "(I)V", (void*)generateLocalOobDataNative}, - {"getConnectionStateNative", "([B)I", (void*)getConnectionStateNative}, - {"pinReplyNative", "([BZI[B)Z", (void*)pinReplyNative}, - {"sspReplyNative", "([BIZI)Z", (void*)sspReplyNative}, - {"getRemoteServicesNative", "([BI)Z", (void*)getRemoteServicesNative}, - {"readEnergyInfoNative", "()I", (void*)readEnergyInfoNative}, - {"dumpNative", "(Ljava/io/FileDescriptor;[Ljava/lang/String;)V", - (void*)dumpNative}, - {"dumpMetricsNative", "()[B", (void*)dumpMetricsNative}, - {"factoryResetNative", "()Z", (void*)factoryResetNative}, - {"obfuscateAddressNative", "([B)[B", (void*)obfuscateAddressNative}, - {"setBufferLengthMillisNative", "(II)Z", - (void*)setBufferLengthMillisNative}, - {"getMetricIdNative", "([B)I", (void*)getMetricIdNative}, - {"connectSocketNative", "([BI[BIII)I", (void*)connectSocketNative}, - {"createSocketChannelNative", "(ILjava/lang/String;[BIII)I", - (void*)createSocketChannelNative}, - {"requestMaximumTxDataLengthNative", "([B)V", - (void*)requestMaximumTxDataLengthNative}, - {"allowLowLatencyAudioNative", "(Z[B)Z", - (void*)allowLowLatencyAudioNative}, - {"metadataChangedNative", "([BI[B)V", (void*)metadataChangedNative}, - {"isLogRedactionEnabledNative", "()Z", - (void*)isLogRedactionEnabledNative}, - {"interopMatchAddrNative", "(Ljava/lang/String;Ljava/lang/String;)Z", - (void*)interopMatchAddrNative}, - {"interopMatchNameNative", "(Ljava/lang/String;Ljava/lang/String;)Z", - (void*)interopMatchNameNative}, - {"interopMatchAddrOrNameNative", - "(Ljava/lang/String;Ljava/lang/String;)Z", - (void*)interopMatchAddrOrNameNative}, - {"interopDatabaseAddRemoveAddrNative", - "(ZLjava/lang/String;Ljava/lang/String;I)V", - (void*)interopDatabaseAddRemoveAddrNative}, - {"interopDatabaseAddRemoveNameNative", - "(ZLjava/lang/String;Ljava/lang/String;)V", - (void*)interopDatabaseAddRemoveNameNative}, - {"getRemotePbapPceVersionNative", "(Ljava/lang/String;)I", - (void*)getRemotePbapPceVersionNative}, - {"pbapPseDynamicVersionUpgradeIsEnabledNative", "()Z", - (void*)pbapPseDynamicVersionUpgradeIsEnabledNative}, - {"getSocketL2capLocalChannelIdNative", "(JJ)I", - (void*)getSocketL2capLocalChannelIdNative}, - {"getSocketL2capRemoteChannelIdNative", "(JJ)I", - (void*)getSocketL2capRemoteChannelIdNative}, + {"initNative", "(ZZI[Ljava/lang/String;ZLjava/lang/String;)Z", (void*)initNative}, + {"cleanupNative", "()V", (void*)cleanupNative}, + {"enableNative", "()Z", (void*)enableNative}, + {"disableNative", "()Z", (void*)disableNative}, + {"setScanModeNative", "(I)Z", (void*)setScanModeNative}, + {"setAdapterPropertyNative", "(I[B)Z", (void*)setAdapterPropertyNative}, + {"getAdapterPropertiesNative", "()Z", (void*)getAdapterPropertiesNative}, + {"getAdapterPropertyNative", "(I)Z", (void*)getAdapterPropertyNative}, + {"getDevicePropertyNative", "([BI)Z", (void*)getDevicePropertyNative}, + {"setDevicePropertyNative", "([BI[B)Z", (void*)setDevicePropertyNative}, + {"startDiscoveryNative", "()Z", (void*)startDiscoveryNative}, + {"cancelDiscoveryNative", "()Z", (void*)cancelDiscoveryNative}, + {"createBondNative", "([BII)Z", (void*)createBondNative}, + {"createBondOutOfBandNative", + "([BILandroid/bluetooth/OobData;Landroid/bluetooth/OobData;)Z", + (void*)createBondOutOfBandNative}, + {"removeBondNative", "([B)Z", (void*)removeBondNative}, + {"cancelBondNative", "([B)Z", (void*)cancelBondNative}, + {"pairingIsBusyNative", "()Z", (void*)pairingIsBusyNative}, + {"generateLocalOobDataNative", "(I)V", (void*)generateLocalOobDataNative}, + {"getConnectionStateNative", "([B)I", (void*)getConnectionStateNative}, + {"pinReplyNative", "([BZI[B)Z", (void*)pinReplyNative}, + {"sspReplyNative", "([BIZI)Z", (void*)sspReplyNative}, + {"getRemoteServicesNative", "([BI)Z", (void*)getRemoteServicesNative}, + {"readEnergyInfoNative", "()I", (void*)readEnergyInfoNative}, + {"dumpNative", "(Ljava/io/FileDescriptor;[Ljava/lang/String;)V", (void*)dumpNative}, + {"dumpMetricsNative", "()[B", (void*)dumpMetricsNative}, + {"factoryResetNative", "()Z", (void*)factoryResetNative}, + {"obfuscateAddressNative", "([B)[B", (void*)obfuscateAddressNative}, + {"setBufferLengthMillisNative", "(II)Z", (void*)setBufferLengthMillisNative}, + {"getMetricIdNative", "([B)I", (void*)getMetricIdNative}, + {"connectSocketNative", "([BI[BIII)I", (void*)connectSocketNative}, + {"createSocketChannelNative", "(ILjava/lang/String;[BIII)I", + (void*)createSocketChannelNative}, + {"requestMaximumTxDataLengthNative", "([B)V", (void*)requestMaximumTxDataLengthNative}, + {"allowLowLatencyAudioNative", "(Z[B)Z", (void*)allowLowLatencyAudioNative}, + {"metadataChangedNative", "([BI[B)V", (void*)metadataChangedNative}, + {"isLogRedactionEnabledNative", "()Z", (void*)isLogRedactionEnabledNative}, + {"interopMatchAddrNative", "(Ljava/lang/String;Ljava/lang/String;)Z", + (void*)interopMatchAddrNative}, + {"interopMatchNameNative", "(Ljava/lang/String;Ljava/lang/String;)Z", + (void*)interopMatchNameNative}, + {"interopMatchAddrOrNameNative", "(Ljava/lang/String;Ljava/lang/String;)Z", + (void*)interopMatchAddrOrNameNative}, + {"interopDatabaseAddRemoveAddrNative", "(ZLjava/lang/String;Ljava/lang/String;I)V", + (void*)interopDatabaseAddRemoveAddrNative}, + {"interopDatabaseAddRemoveNameNative", "(ZLjava/lang/String;Ljava/lang/String;)V", + (void*)interopDatabaseAddRemoveNameNative}, + {"getRemotePbapPceVersionNative", "(Ljava/lang/String;)I", + (void*)getRemotePbapPceVersionNative}, + {"pbapPseDynamicVersionUpgradeIsEnabledNative", "()Z", + (void*)pbapPseDynamicVersionUpgradeIsEnabledNative}, + {"getSocketL2capLocalChannelIdNative", "(JJ)I", + (void*)getSocketL2capLocalChannelIdNative}, + {"getSocketL2capRemoteChannelIdNative", "(JJ)I", + (void*)getSocketL2capRemoteChannelIdNative}, }; const int result = REGISTER_NATIVE_METHODS( - env, "com/android/bluetooth/btservice/AdapterNativeInterface", methods); + env, "com/android/bluetooth/btservice/AdapterNativeInterface", methods); if (result != 0) { return result; } jclass jniAdapterNativeInterfaceClass = - env->FindClass("com/android/bluetooth/btservice/AdapterNativeInterface"); - sJniCallbacksField = - env->GetFieldID(jniAdapterNativeInterfaceClass, "mJniCallbacks", - "Lcom/android/bluetooth/btservice/JniCallbacks;"); + env->FindClass("com/android/bluetooth/btservice/AdapterNativeInterface"); + sJniCallbacksField = env->GetFieldID(jniAdapterNativeInterfaceClass, "mJniCallbacks", + "Lcom/android/bluetooth/btservice/JniCallbacks;"); env->DeleteLocalRef(jniAdapterNativeInterfaceClass); const JNIJavaMethod javaMethods[] = { - {"oobDataReceivedCallback", "(ILandroid/bluetooth/OobData;)V", - &method_oobDataReceivedCallback}, - {"stateChangeCallback", "(I)V", &method_stateChangeCallback}, - {"adapterPropertyChangedCallback", "([I[[B)V", - &method_adapterPropertyChangedCallback}, - {"discoveryStateChangeCallback", "(I)V", - &method_discoveryStateChangeCallback}, - {"devicePropertyChangedCallback", "([B[I[[B)V", - &method_devicePropertyChangedCallback}, - {"deviceFoundCallback", "([B)V", &method_deviceFoundCallback}, - {"pinRequestCallback", "([B[BIZ)V", &method_pinRequestCallback}, - {"sspRequestCallback", "([BII)V", &method_sspRequestCallback}, - {"bondStateChangeCallback", "(I[BII)V", &method_bondStateChangeCallback}, - {"addressConsolidateCallback", "([B[B)V", - &method_addressConsolidateCallback}, - {"leAddressAssociateCallback", "([B[B)V", - &method_leAddressAssociateCallback}, - {"aclStateChangeCallback", "(I[BIIII)V", &method_aclStateChangeCallback}, - {"linkQualityReportCallback", "(JIIIIII)V", - &method_linkQualityReportCallback}, - {"switchBufferSizeCallback", "(Z)V", &method_switchBufferSizeCallback}, - {"switchCodecCallback", "(Z)V", &method_switchCodecCallback}, - {"acquireWakeLock", "(Ljava/lang/String;)Z", &method_acquireWakeLock}, - {"releaseWakeLock", "(Ljava/lang/String;)Z", &method_releaseWakeLock}, - {"energyInfoCallback", "(IIJJJJ[Landroid/bluetooth/UidTraffic;)V", - &method_energyInfo}, - {"keyMissingCallback", "([B)V", &method_keyMissingCallback}, + {"oobDataReceivedCallback", "(ILandroid/bluetooth/OobData;)V", + &method_oobDataReceivedCallback}, + {"stateChangeCallback", "(I)V", &method_stateChangeCallback}, + {"adapterPropertyChangedCallback", "([I[[B)V", &method_adapterPropertyChangedCallback}, + {"discoveryStateChangeCallback", "(I)V", &method_discoveryStateChangeCallback}, + {"devicePropertyChangedCallback", "([B[I[[B)V", &method_devicePropertyChangedCallback}, + {"deviceFoundCallback", "([B)V", &method_deviceFoundCallback}, + {"pinRequestCallback", "([B[BIZ)V", &method_pinRequestCallback}, + {"sspRequestCallback", "([BII)V", &method_sspRequestCallback}, + {"bondStateChangeCallback", "(I[BII)V", &method_bondStateChangeCallback}, + {"addressConsolidateCallback", "([B[B)V", &method_addressConsolidateCallback}, + {"leAddressAssociateCallback", "([B[B)V", &method_leAddressAssociateCallback}, + {"aclStateChangeCallback", "(I[BIIII)V", &method_aclStateChangeCallback}, + {"linkQualityReportCallback", "(JIIIIII)V", &method_linkQualityReportCallback}, + {"switchBufferSizeCallback", "(Z)V", &method_switchBufferSizeCallback}, + {"switchCodecCallback", "(Z)V", &method_switchCodecCallback}, + {"acquireWakeLock", "(Ljava/lang/String;)Z", &method_acquireWakeLock}, + {"releaseWakeLock", "(Ljava/lang/String;)Z", &method_releaseWakeLock}, + {"energyInfoCallback", "(IIJJJJ[Landroid/bluetooth/UidTraffic;)V", &method_energyInfo}, + {"keyMissingCallback", "([B)V", &method_keyMissingCallback}, }; - GET_JAVA_METHODS(env, "com/android/bluetooth/btservice/JniCallbacks", - javaMethods); + GET_JAVA_METHODS(env, "com/android/bluetooth/btservice/JniCallbacks", javaMethods); const JNIJavaMethod javaUuidTrafficMethods[] = { - {"", "(IJJ)V", &android_bluetooth_UidTraffic.constructor}, + {"", "(IJJ)V", &android_bluetooth_UidTraffic.constructor}, }; GET_JAVA_METHODS(env, "android/bluetooth/UidTraffic", javaUuidTrafficMethods); @@ -2288,24 +2242,19 @@ jint JNI_OnLoad(JavaVM* jvm, void* /* reserved */) { */ const char* stack_default_log_tag = "bluetooth"; int default_prio = ANDROID_LOG_INFO; - if (__android_log_is_loggable(ANDROID_LOG_VERBOSE, stack_default_log_tag, - default_prio)) { + if (__android_log_is_loggable(ANDROID_LOG_VERBOSE, stack_default_log_tag, default_prio)) { __android_log_set_minimum_priority(ANDROID_LOG_VERBOSE); log::info("Set stack default log level to 'VERBOSE'"); - } else if (__android_log_is_loggable(ANDROID_LOG_DEBUG, stack_default_log_tag, - default_prio)) { + } else if (__android_log_is_loggable(ANDROID_LOG_DEBUG, stack_default_log_tag, default_prio)) { __android_log_set_minimum_priority(ANDROID_LOG_DEBUG); log::info("Set stack default log level to 'DEBUG'"); - } else if (__android_log_is_loggable(ANDROID_LOG_INFO, stack_default_log_tag, - default_prio)) { + } else if (__android_log_is_loggable(ANDROID_LOG_INFO, stack_default_log_tag, default_prio)) { __android_log_set_minimum_priority(ANDROID_LOG_INFO); log::info("Set stack default log level to 'INFO'"); - } else if (__android_log_is_loggable(ANDROID_LOG_WARN, stack_default_log_tag, - default_prio)) { + } else if (__android_log_is_loggable(ANDROID_LOG_WARN, stack_default_log_tag, default_prio)) { __android_log_set_minimum_priority(ANDROID_LOG_WARN); log::info("Set stack default log level to 'WARN'"); - } else if (__android_log_is_loggable(ANDROID_LOG_ERROR, stack_default_log_tag, - default_prio)) { + } else if (__android_log_is_loggable(ANDROID_LOG_ERROR, stack_default_log_tag, default_prio)) { __android_log_set_minimum_priority(ANDROID_LOG_ERROR); log::info("Set stack default log level to 'ERROR'"); } @@ -2327,8 +2276,7 @@ jint JNI_OnLoad(JavaVM* jvm, void* /* reserved */) { return JNI_ERR; } - status = - android::register_com_android_bluetooth_btservice_BluetoothKeystore(e); + status = android::register_com_android_bluetooth_btservice_BluetoothKeystore(e); if (status < 0) { log::error("jni BluetoothKeyStore registration failure: {}", status); return JNI_ERR; @@ -2407,8 +2355,7 @@ jint JNI_OnLoad(JavaVM* jvm, void* /* reserved */) { status = android::register_com_android_bluetooth_hap_client(e); if (status < 0) { - log::error("jni le audio hearing access client registration failure: {}", - status); + log::error("jni le audio hearing access client registration failure: {}", status); return JNI_ERR; } @@ -2430,9 +2377,7 @@ jint JNI_OnLoad(JavaVM* jvm, void* /* reserved */) { return JNI_ERR; } - status = - android::register_com_android_bluetooth_btservice_BluetoothQualityReport( - e); + status = android::register_com_android_bluetooth_btservice_BluetoothQualityReport(e); if (status < 0) { log::error("jni bluetooth quality report registration failure: {}", status); return JNI_ERR; @@ -2444,12 +2389,11 @@ jint JNI_OnLoad(JavaVM* jvm, void* /* reserved */) { namespace android { /** Load the java methods or die*/ -void jniGetMethodsOrDie(JNIEnv* env, const char* className, - const JNIJavaMethod* methods, int nMethods) { +void jniGetMethodsOrDie(JNIEnv* env, const char* className, const JNIJavaMethod* methods, + int nMethods) { jclass clazz = env->FindClass(className); if (clazz == nullptr) { - log::fatal("Native registration unable to find class '{}' aborting...", - className); + log::fatal("Native registration unable to find class '{}' aborting...", className); } for (int i = 0; i < nMethods; i++) { @@ -2460,9 +2404,8 @@ void jniGetMethodsOrDie(JNIEnv* env, const char* className, *method.id = env->GetMethodID(clazz, method.name, method.signature); } if (method.id == nullptr) { - log::fatal( - "In class {}: Unable to find '{}' with signature={} is_static={}", - className, method.name, method.signature, method.is_static); + log::fatal("In class {}: Unable to find '{}' with signature={} is_static={}", className, + method.name, method.signature, method.is_static); } } diff --git a/android/app/jni/com_android_bluetooth_btservice_BluetoothKeystore.cpp b/android/app/jni/com_android_bluetooth_btservice_BluetoothKeystore.cpp index 476db3c9729..330b55703ef 100644 --- a/android/app/jni/com_android_bluetooth_btservice_BluetoothKeystore.cpp +++ b/android/app/jni/com_android_bluetooth_btservice_BluetoothKeystore.cpp @@ -16,12 +16,13 @@ #define LOG_TAG "BluetoothKeystoreServiceJni" -#include "com_android_bluetooth.h" -#include "hardware/bt_keystore.h" - #include + #include +#include "com_android_bluetooth.h" +#include "hardware/bt_keystore.h" + using bluetooth::bluetooth_keystore::BluetoothKeystoreCallbacks; using bluetooth::bluetooth_keystore::BluetoothKeystoreInterface; @@ -37,24 +38,23 @@ static std::shared_timed_mutex callbacks_mutex; class BluetoothKeystoreCallbacksImpl : public bluetooth::bluetooth_keystore::BluetoothKeystoreCallbacks { - public: +public: ~BluetoothKeystoreCallbacksImpl() = default; - void set_encrypt_key_or_remove_key( - const std::string prefixString, - const std::string decryptedString) override { + void set_encrypt_key_or_remove_key(const std::string prefixString, + const std::string decryptedString) override { log::info(""); std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) return; + if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) { + return; + } jstring j_prefixString = sCallbackEnv->NewStringUTF(prefixString.c_str()); - jstring j_decryptedString = - sCallbackEnv->NewStringUTF(decryptedString.c_str()); + jstring j_decryptedString = sCallbackEnv->NewStringUTF(decryptedString.c_str()); - sCallbackEnv->CallVoidMethod(mCallbacksObj, - method_setEncryptKeyOrRemoveKeyCallback, + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_setEncryptKeyOrRemoveKeyCallback, j_prefixString, j_decryptedString); } @@ -63,12 +63,14 @@ class BluetoothKeystoreCallbacksImpl std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) return ""; + if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) { + return ""; + } jstring j_prefixString = sCallbackEnv->NewStringUTF(prefixString.c_str()); jstring j_decrypt_str = (jstring)sCallbackEnv->CallObjectMethod( - mCallbacksObj, method_getKeyCallback, j_prefixString); + mCallbacksObj, method_getKeyCallback, j_prefixString); if (j_decrypt_str == nullptr) { log::error("Got a null decrypt_str"); @@ -112,7 +114,7 @@ static void initNative(JNIEnv* env, jobject object) { } sBluetoothKeystoreInterface = - (BluetoothKeystoreInterface*)btInf->get_profile_interface(BT_KEYSTORE_ID); + (BluetoothKeystoreInterface*)btInf->get_profile_interface(BT_KEYSTORE_ID); if (sBluetoothKeystoreInterface == nullptr) { log::error("Failed to get BluetoothKeystore Interface"); return; @@ -143,24 +145,21 @@ static void cleanupNative(JNIEnv* env, jobject /* object */) { int register_com_android_bluetooth_btservice_BluetoothKeystore(JNIEnv* env) { const JNINativeMethod methods[] = { - {"initNative", "()V", (void*)initNative}, - {"cleanupNative", "()V", (void*)cleanupNative}, + {"initNative", "()V", (void*)initNative}, + {"cleanupNative", "()V", (void*)cleanupNative}, }; - const int result = REGISTER_NATIVE_METHODS( - env, - "com/android/bluetooth/btservice/bluetoothkeystore/" - "BluetoothKeystoreNativeInterface", - methods); + const int result = REGISTER_NATIVE_METHODS(env, + "com/android/bluetooth/btservice/bluetoothkeystore/" + "BluetoothKeystoreNativeInterface", + methods); if (result != 0) { return result; } const JNIJavaMethod javaMethods[] = { - {"setEncryptKeyOrRemoveKeyCallback", - "(Ljava/lang/String;Ljava/lang/String;)V", - &method_setEncryptKeyOrRemoveKeyCallback}, - {"getKeyCallback", "(Ljava/lang/String;)Ljava/lang/String;", - &method_getKeyCallback}, + {"setEncryptKeyOrRemoveKeyCallback", "(Ljava/lang/String;Ljava/lang/String;)V", + &method_setEncryptKeyOrRemoveKeyCallback}, + {"getKeyCallback", "(Ljava/lang/String;)Ljava/lang/String;", &method_getKeyCallback}, }; GET_JAVA_METHODS(env, "com/android/bluetooth/btservice/bluetoothkeystore/" diff --git a/android/app/jni/com_android_bluetooth_csip_set_coordinator.cpp b/android/app/jni/com_android_bluetooth_csip_set_coordinator.cpp index 7a34bc5870d..f083457386f 100644 --- a/android/app/jni/com_android_bluetooth_csip_set_coordinator.cpp +++ b/android/app/jni/com_android_bluetooth_csip_set_coordinator.cpp @@ -69,50 +69,48 @@ static uint64_t uuid_msb(const Uuid& uuid) { } class CsisClientCallbacksImpl : public CsisClientCallbacks { - public: +public: ~CsisClientCallbacksImpl() = default; - void OnConnectionState(const RawAddress& bd_addr, - ConnectionState state) override { - log::info("state:{}, addr: {}", int(state), - bd_addr.ToRedactedStringForLogging()); + void OnConnectionState(const RawAddress& bd_addr, ConnectionState state) override { + log::info("state:{}, addr: {}", int(state), bd_addr.ToRedactedStringForLogging()); std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) return; + if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) { + return; + } - ScopedLocalRef addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); + ScopedLocalRef addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); if (!addr.get()) { log::error("Failed to new bd addr jbyteArray for connection state"); return; } - sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), - (jbyte*)&bd_addr); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onConnectionStateChanged, - addr.get(), (jint)state); + sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), (jbyte*)&bd_addr); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onConnectionStateChanged, addr.get(), + (jint)state); } - void OnDeviceAvailable(const RawAddress& bd_addr, int group_id, - int group_size, int rank, + void OnDeviceAvailable(const RawAddress& bd_addr, int group_id, int group_size, int rank, const bluetooth::Uuid& uuid) override { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) return; + if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) { + return; + } - ScopedLocalRef addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); + ScopedLocalRef addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); if (!addr.get()) { log::error("Failed to new bd addr jbyteArray for device available"); return; } - sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), - (jbyte*)&bd_addr); + sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), (jbyte*)&bd_addr); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onDeviceAvailable, - addr.get(), (jint)group_id, (jint)group_size, - (jint)rank, UUID_PARAMS(uuid)); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onDeviceAvailable, addr.get(), + (jint)group_id, (jint)group_size, (jint)rank, UUID_PARAMS(uuid)); } void OnSetMemberAvailable(const RawAddress& bd_addr, int group_id) override { @@ -120,33 +118,33 @@ class CsisClientCallbacksImpl : public CsisClientCallbacks { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) return; + if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) { + return; + } - ScopedLocalRef addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); + ScopedLocalRef addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); if (!addr.get()) { log::error("Failed to new jbyteArray bd addr for connection state"); return; } - sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), - (jbyte*)&bd_addr); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onSetMemberAvailable, - addr.get(), (jint)group_id); + sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), (jbyte*)&bd_addr); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onSetMemberAvailable, addr.get(), + (jint)group_id); } - void OnGroupLockChanged(int group_id, bool locked, - CsisGroupLockStatus status) override { - log::info("group_id: {}, locked: {}, status: {}", group_id, locked, - (int)status); + void OnGroupLockChanged(int group_id, bool locked, CsisGroupLockStatus status) override { + log::info("group_id: {}, locked: {}, status: {}", group_id, locked, (int)status); std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) return; + if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) { + return; + } - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onGroupLockChanged, - (jint)group_id, (jboolean)locked, - (jint)status); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onGroupLockChanged, (jint)group_id, + (jboolean)locked, (jint)status); } }; @@ -179,8 +177,8 @@ static void initNative(JNIEnv* env, jobject object) { return; } - sCsisClientInterface = (CsisClientInterface*)btInf->get_profile_interface( - BT_PROFILE_CSIS_CLIENT_ID); + sCsisClientInterface = + (CsisClientInterface*)btInf->get_profile_interface(BT_PROFILE_CSIS_CLIENT_ID); if (sCsisClientInterface == nullptr) { log::error("Failed to get Csis Client Interface"); return; @@ -210,8 +208,7 @@ static void cleanupNative(JNIEnv* env, jobject /* object */) { } } -static jboolean connectNative(JNIEnv* env, jobject /* object */, - jbyteArray address) { +static jboolean connectNative(JNIEnv* env, jobject /* object */, jbyteArray address) { std::shared_lock lock(interface_mutex); if (!sCsisClientInterface) { log::error("Failed to get the Csis Client Interface Interface"); @@ -230,8 +227,7 @@ static jboolean connectNative(JNIEnv* env, jobject /* object */, return JNI_TRUE; } -static jboolean disconnectNative(JNIEnv* env, jobject /* object */, - jbyteArray address) { +static jboolean disconnectNative(JNIEnv* env, jobject /* object */, jbyteArray address) { std::shared_lock lock(interface_mutex); if (!sCsisClientInterface) { log::error("Failed to get the Csis Client Interface"); @@ -250,8 +246,8 @@ static jboolean disconnectNative(JNIEnv* env, jobject /* object */, return JNI_TRUE; } -static void groupLockSetNative(JNIEnv* /* env */, jobject /* object */, - jint group_id, jboolean lock) { +static void groupLockSetNative(JNIEnv* /* env */, jobject /* object */, jint group_id, + jboolean lock) { log::info(""); if (!sCsisClientInterface) { @@ -264,28 +260,26 @@ static void groupLockSetNative(JNIEnv* /* env */, jobject /* object */, int register_com_android_bluetooth_csip_set_coordinator(JNIEnv* env) { const JNINativeMethod methods[] = { - {"initNative", "()V", (void*)initNative}, - {"cleanupNative", "()V", (void*)cleanupNative}, - {"connectNative", "([B)Z", (void*)connectNative}, - {"disconnectNative", "([B)Z", (void*)disconnectNative}, - {"groupLockSetNative", "(IZ)V", (void*)groupLockSetNative}, + {"initNative", "()V", (void*)initNative}, + {"cleanupNative", "()V", (void*)cleanupNative}, + {"connectNative", "([B)Z", (void*)connectNative}, + {"disconnectNative", "([B)Z", (void*)disconnectNative}, + {"groupLockSetNative", "(IZ)V", (void*)groupLockSetNative}, }; const int result = REGISTER_NATIVE_METHODS( - env, "com/android/bluetooth/csip/CsipSetCoordinatorNativeInterface", - methods); + env, "com/android/bluetooth/csip/CsipSetCoordinatorNativeInterface", methods); if (result != 0) { return result; } const JNIJavaMethod javaMethods[]{ - {"onConnectionStateChanged", "([BI)V", &method_onConnectionStateChanged}, - {"onDeviceAvailable", "([BIIIJJ)V", &method_onDeviceAvailable}, - {"onSetMemberAvailable", "([BI)V", &method_onSetMemberAvailable}, - {"onGroupLockChanged", "(IZI)V", &method_onGroupLockChanged}, + {"onConnectionStateChanged", "([BI)V", &method_onConnectionStateChanged}, + {"onDeviceAvailable", "([BIIIJJ)V", &method_onDeviceAvailable}, + {"onSetMemberAvailable", "([BI)V", &method_onSetMemberAvailable}, + {"onGroupLockChanged", "(IZI)V", &method_onGroupLockChanged}, }; - GET_JAVA_METHODS( - env, "com/android/bluetooth/csip/CsipSetCoordinatorNativeInterface", - javaMethods); + GET_JAVA_METHODS(env, "com/android/bluetooth/csip/CsipSetCoordinatorNativeInterface", + javaMethods); return 0; } diff --git a/android/app/jni/com_android_bluetooth_gatt.cpp b/android/app/jni/com_android_bluetooth_gatt.cpp index 2a0fe245527..82693185cc8 100644 --- a/android/app/jni/com_android_bluetooth_gatt.cpp +++ b/android/app/jni/com_android_bluetooth_gatt.cpp @@ -74,7 +74,9 @@ static uint64_t uuid_msb(const Uuid& uuid) { static RawAddress str2addr(JNIEnv* env, jstring address) { RawAddress bd_addr; const char* c_address = env->GetStringUTFChars(address, NULL); - if (!c_address) return bd_addr; + if (!c_address) { + return bd_addr; + } RawAddress::FromString(std::string(c_address), bd_addr); env->ReleaseStringUTFChars(address, c_address); @@ -84,9 +86,8 @@ static RawAddress str2addr(JNIEnv* env, jstring address) { static jstring bdaddr2newjstr(JNIEnv* env, const RawAddress* bda) { char c_address[32]; - snprintf(c_address, sizeof(c_address), "%02X:%02X:%02X:%02X:%02X:%02X", - bda->address[0], bda->address[1], bda->address[2], bda->address[3], - bda->address[4], bda->address[5]); + snprintf(c_address, sizeof(c_address), "%02X:%02X:%02X:%02X:%02X:%02X", bda->address[0], + bda->address[1], bda->address[2], bda->address[3], bda->address[4], bda->address[5]); return env->NewStringUTF(c_address); } @@ -215,292 +216,290 @@ static std::shared_mutex callbacks_mutex; void btgattc_register_app_cb(int status, int clientIf, const Uuid& app_uuid) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onClientRegistered, status, - clientIf, UUID_PARAMS(app_uuid)); -} - -void btgattc_scan_result_cb(uint16_t event_type, uint8_t addr_type, - RawAddress* bda, uint8_t primary_phy, - uint8_t secondary_phy, uint8_t advertising_sid, - int8_t tx_power, int8_t rssi, - uint16_t periodic_adv_int, - std::vector adv_data, - RawAddress* original_bda) { + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onClientRegistered, status, clientIf, + UUID_PARAMS(app_uuid)); +} + +void btgattc_scan_result_cb(uint16_t event_type, uint8_t addr_type, RawAddress* bda, + uint8_t primary_phy, uint8_t secondary_phy, uint8_t advertising_sid, + int8_t tx_power, int8_t rssi, uint16_t periodic_adv_int, + std::vector adv_data, RawAddress* original_bda) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mScanCallbacksObj) return; + if (!sCallbackEnv.valid() || !mScanCallbacksObj) { + return; + } - ScopedLocalRef address(sCallbackEnv.get(), - bdaddr2newjstr(sCallbackEnv.get(), bda)); - ScopedLocalRef jb(sCallbackEnv.get(), - sCallbackEnv->NewByteArray(adv_data.size())); - sCallbackEnv->SetByteArrayRegion(jb.get(), 0, adv_data.size(), - (jbyte*)adv_data.data()); + ScopedLocalRef address(sCallbackEnv.get(), bdaddr2newjstr(sCallbackEnv.get(), bda)); + ScopedLocalRef jb(sCallbackEnv.get(), sCallbackEnv->NewByteArray(adv_data.size())); + sCallbackEnv->SetByteArrayRegion(jb.get(), 0, adv_data.size(), (jbyte*)adv_data.data()); - ScopedLocalRef original_address( - sCallbackEnv.get(), bdaddr2newjstr(sCallbackEnv.get(), original_bda)); + ScopedLocalRef original_address(sCallbackEnv.get(), + bdaddr2newjstr(sCallbackEnv.get(), original_bda)); - sCallbackEnv->CallVoidMethod( - mScanCallbacksObj, method_onScanResult, event_type, addr_type, - address.get(), primary_phy, secondary_phy, advertising_sid, tx_power, - rssi, periodic_adv_int, jb.get(), original_address.get()); + sCallbackEnv->CallVoidMethod(mScanCallbacksObj, method_onScanResult, event_type, addr_type, + address.get(), primary_phy, secondary_phy, advertising_sid, tx_power, + rssi, periodic_adv_int, jb.get(), original_address.get()); } -void btgattc_open_cb(int conn_id, int status, int clientIf, - const RawAddress& bda) { +void btgattc_open_cb(int conn_id, int status, int clientIf, const RawAddress& bda) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } - ScopedLocalRef address(sCallbackEnv.get(), - bdaddr2newjstr(sCallbackEnv.get(), &bda)); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onConnected, clientIf, - conn_id, status, address.get()); + ScopedLocalRef address(sCallbackEnv.get(), bdaddr2newjstr(sCallbackEnv.get(), &bda)); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onConnected, clientIf, conn_id, status, + address.get()); } -void btgattc_close_cb(int conn_id, int status, int clientIf, - const RawAddress& bda) { +void btgattc_close_cb(int conn_id, int status, int clientIf, const RawAddress& bda) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } - ScopedLocalRef address(sCallbackEnv.get(), - bdaddr2newjstr(sCallbackEnv.get(), &bda)); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onDisconnected, clientIf, - conn_id, status, address.get()); + ScopedLocalRef address(sCallbackEnv.get(), bdaddr2newjstr(sCallbackEnv.get(), &bda)); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onDisconnected, clientIf, conn_id, status, + address.get()); } void btgattc_search_complete_cb(int conn_id, int status) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onSearchCompleted, conn_id, - status); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onSearchCompleted, conn_id, status); } -void btgattc_register_for_notification_cb(int conn_id, int registered, - int status, uint16_t handle) { +void btgattc_register_for_notification_cb(int conn_id, int registered, int status, + uint16_t handle) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onRegisterForNotifications, - conn_id, status, registered, handle); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onRegisterForNotifications, conn_id, status, + registered, handle); } void btgattc_notify_cb(int conn_id, const btgatt_notify_params_t& p_data) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } - ScopedLocalRef address( - sCallbackEnv.get(), bdaddr2newjstr(sCallbackEnv.get(), &p_data.bda)); - ScopedLocalRef jb(sCallbackEnv.get(), - sCallbackEnv->NewByteArray(p_data.len)); - sCallbackEnv->SetByteArrayRegion(jb.get(), 0, p_data.len, - (jbyte*)p_data.value); + ScopedLocalRef address(sCallbackEnv.get(), + bdaddr2newjstr(sCallbackEnv.get(), &p_data.bda)); + ScopedLocalRef jb(sCallbackEnv.get(), sCallbackEnv->NewByteArray(p_data.len)); + sCallbackEnv->SetByteArrayRegion(jb.get(), 0, p_data.len, (jbyte*)p_data.value); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onNotify, conn_id, - address.get(), p_data.handle, p_data.is_notify, - jb.get()); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onNotify, conn_id, address.get(), + p_data.handle, p_data.is_notify, jb.get()); } -void btgattc_read_characteristic_cb(int conn_id, int status, - const btgatt_read_params_t& p_data) { +void btgattc_read_characteristic_cb(int conn_id, int status, const btgatt_read_params_t& p_data) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } ScopedLocalRef jb(sCallbackEnv.get(), NULL); if (status == 0) { // Success jb.reset(sCallbackEnv->NewByteArray(p_data.value.len)); - sCallbackEnv->SetByteArrayRegion(jb.get(), 0, p_data.value.len, - (jbyte*)p_data.value.value); + sCallbackEnv->SetByteArrayRegion(jb.get(), 0, p_data.value.len, (jbyte*)p_data.value.value); } else { uint8_t value = 0; jb.reset(sCallbackEnv->NewByteArray(1)); sCallbackEnv->SetByteArrayRegion(jb.get(), 0, 1, (jbyte*)&value); } - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onReadCharacteristic, - conn_id, status, p_data.handle, jb.get()); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onReadCharacteristic, conn_id, status, + p_data.handle, jb.get()); } -void btgattc_write_characteristic_cb(int conn_id, int status, uint16_t handle, - uint16_t len, const uint8_t* value) { +void btgattc_write_characteristic_cb(int conn_id, int status, uint16_t handle, uint16_t len, + const uint8_t* value) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } ScopedLocalRef jb(sCallbackEnv.get(), NULL); jb.reset(sCallbackEnv->NewByteArray(len)); sCallbackEnv->SetByteArrayRegion(jb.get(), 0, len, (jbyte*)value); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onWriteCharacteristic, - conn_id, status, handle, jb.get()); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onWriteCharacteristic, conn_id, status, handle, + jb.get()); } void btgattc_execute_write_cb(int conn_id, int status) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onExecuteCompleted, - conn_id, status); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onExecuteCompleted, conn_id, status); } -void btgattc_read_descriptor_cb(int conn_id, int status, - const btgatt_read_params_t& p_data) { +void btgattc_read_descriptor_cb(int conn_id, int status, const btgatt_read_params_t& p_data) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } ScopedLocalRef jb(sCallbackEnv.get(), NULL); if (p_data.value.len != 0) { jb.reset(sCallbackEnv->NewByteArray(p_data.value.len)); - sCallbackEnv->SetByteArrayRegion(jb.get(), 0, p_data.value.len, - (jbyte*)p_data.value.value); + sCallbackEnv->SetByteArrayRegion(jb.get(), 0, p_data.value.len, (jbyte*)p_data.value.value); } else { jb.reset(sCallbackEnv->NewByteArray(1)); } - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onReadDescriptor, conn_id, - status, p_data.handle, jb.get()); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onReadDescriptor, conn_id, status, + p_data.handle, jb.get()); } -void btgattc_write_descriptor_cb(int conn_id, int status, uint16_t handle, - uint16_t len, const uint8_t* value) { +void btgattc_write_descriptor_cb(int conn_id, int status, uint16_t handle, uint16_t len, + const uint8_t* value) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } ScopedLocalRef jb(sCallbackEnv.get(), NULL); jb.reset(sCallbackEnv->NewByteArray(len)); sCallbackEnv->SetByteArrayRegion(jb.get(), 0, len, (jbyte*)value); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onWriteDescriptor, conn_id, - status, handle, jb.get()); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onWriteDescriptor, conn_id, status, handle, + jb.get()); } -void btgattc_remote_rssi_cb(int client_if, const RawAddress& bda, int rssi, - int status) { +void btgattc_remote_rssi_cb(int client_if, const RawAddress& bda, int rssi, int status) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } - ScopedLocalRef address(sCallbackEnv.get(), - bdaddr2newjstr(sCallbackEnv.get(), &bda)); + ScopedLocalRef address(sCallbackEnv.get(), bdaddr2newjstr(sCallbackEnv.get(), &bda)); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onReadRemoteRssi, - client_if, address.get(), rssi, status); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onReadRemoteRssi, client_if, address.get(), + rssi, status); } void btgattc_configure_mtu_cb(int conn_id, int status, int mtu) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onConfigureMTU, conn_id, - status, mtu); + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onConfigureMTU, conn_id, status, mtu); } void btgattc_congestion_cb(int conn_id, bool congested) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onClientCongestion, - conn_id, congested); + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onClientCongestion, conn_id, congested); } -void btgattc_batchscan_reports_cb(int client_if, int status, int report_format, - int num_records, std::vector data) { +void btgattc_batchscan_reports_cb(int client_if, int status, int report_format, int num_records, + std::vector data) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mScanCallbacksObj) return; - ScopedLocalRef jb(sCallbackEnv.get(), - sCallbackEnv->NewByteArray(data.size())); - sCallbackEnv->SetByteArrayRegion(jb.get(), 0, data.size(), - (jbyte*)data.data()); - - sCallbackEnv->CallVoidMethod(mScanCallbacksObj, method_onBatchScanReports, - status, client_if, report_format, num_records, - jb.get()); + if (!sCallbackEnv.valid() || !mScanCallbacksObj) { + return; + } + ScopedLocalRef jb(sCallbackEnv.get(), sCallbackEnv->NewByteArray(data.size())); + sCallbackEnv->SetByteArrayRegion(jb.get(), 0, data.size(), (jbyte*)data.data()); + + sCallbackEnv->CallVoidMethod(mScanCallbacksObj, method_onBatchScanReports, status, client_if, + report_format, num_records, jb.get()); } void btgattc_batchscan_threshold_cb(int client_if) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mScanCallbacksObj) return; - sCallbackEnv->CallVoidMethod(mScanCallbacksObj, - method_onBatchScanThresholdCrossed, client_if); + if (!sCallbackEnv.valid() || !mScanCallbacksObj) { + return; + } + sCallbackEnv->CallVoidMethod(mScanCallbacksObj, method_onBatchScanThresholdCrossed, client_if); } void btgattc_track_adv_event_cb(btgatt_track_adv_info_t* p_adv_track_info) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mScanCallbacksObj) return; + if (!sCallbackEnv.valid() || !mScanCallbacksObj) { + return; + } - ScopedLocalRef address( - sCallbackEnv.get(), - bdaddr2newjstr(sCallbackEnv.get(), &p_adv_track_info->bd_addr)); + ScopedLocalRef address(sCallbackEnv.get(), + bdaddr2newjstr(sCallbackEnv.get(), &p_adv_track_info->bd_addr)); - ScopedLocalRef jb_adv_pkt( - sCallbackEnv.get(), - sCallbackEnv->NewByteArray(p_adv_track_info->adv_pkt_len)); + ScopedLocalRef jb_adv_pkt(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(p_adv_track_info->adv_pkt_len)); ScopedLocalRef jb_scan_rsp( - sCallbackEnv.get(), - sCallbackEnv->NewByteArray(p_adv_track_info->scan_rsp_len)); + sCallbackEnv.get(), sCallbackEnv->NewByteArray(p_adv_track_info->scan_rsp_len)); - sCallbackEnv->SetByteArrayRegion(jb_adv_pkt.get(), 0, - p_adv_track_info->adv_pkt_len, + sCallbackEnv->SetByteArrayRegion(jb_adv_pkt.get(), 0, p_adv_track_info->adv_pkt_len, (jbyte*)p_adv_track_info->p_adv_pkt_data); - sCallbackEnv->SetByteArrayRegion(jb_scan_rsp.get(), 0, - p_adv_track_info->scan_rsp_len, + sCallbackEnv->SetByteArrayRegion(jb_scan_rsp.get(), 0, p_adv_track_info->scan_rsp_len, (jbyte*)p_adv_track_info->p_scan_rsp_data); ScopedLocalRef trackadv_obj( - sCallbackEnv.get(), - sCallbackEnv->CallObjectMethod( - mScanCallbacksObj, method_createOnTrackAdvFoundLostObject, - p_adv_track_info->client_if, p_adv_track_info->adv_pkt_len, - jb_adv_pkt.get(), p_adv_track_info->scan_rsp_len, jb_scan_rsp.get(), - p_adv_track_info->filt_index, p_adv_track_info->advertiser_state, - p_adv_track_info->advertiser_info_present, address.get(), - p_adv_track_info->addr_type, p_adv_track_info->tx_power, - p_adv_track_info->rssi_value, p_adv_track_info->time_stamp)); + sCallbackEnv.get(), + sCallbackEnv->CallObjectMethod( + mScanCallbacksObj, method_createOnTrackAdvFoundLostObject, + p_adv_track_info->client_if, p_adv_track_info->adv_pkt_len, jb_adv_pkt.get(), + p_adv_track_info->scan_rsp_len, jb_scan_rsp.get(), p_adv_track_info->filt_index, + p_adv_track_info->advertiser_state, p_adv_track_info->advertiser_info_present, + address.get(), p_adv_track_info->addr_type, p_adv_track_info->tx_power, + p_adv_track_info->rssi_value, p_adv_track_info->time_stamp)); if (NULL != trackadv_obj.get()) { - sCallbackEnv->CallVoidMethod(mScanCallbacksObj, method_onTrackAdvFoundLost, - trackadv_obj.get()); + sCallbackEnv->CallVoidMethod(mScanCallbacksObj, method_onTrackAdvFoundLost, trackadv_obj.get()); } } -void fillGattDbElementArray(JNIEnv* env, jobject* array, - const btgatt_db_element_t* db, int count) { +void fillGattDbElementArray(JNIEnv* env, jobject* array, const btgatt_db_element_t* db, int count) { // Because JNI uses a different class loader in the callback context, we // cannot simply get the class. // As a workaround, we have to make sure we obtain an object of the class // first, as this will cause // class loader to load it. ScopedLocalRef objectForClass( - env, env->CallObjectMethod(mCallbacksObj, method_getSampleGattDbElement)); - ScopedLocalRef gattDbElementClazz( - env, env->GetObjectClass(objectForClass.get())); + env, env->CallObjectMethod(mCallbacksObj, method_getSampleGattDbElement)); + ScopedLocalRef gattDbElementClazz(env, env->GetObjectClass(objectForClass.get())); - jmethodID gattDbElementConstructor = - env->GetMethodID(gattDbElementClazz.get(), "", "()V"); + jmethodID gattDbElementConstructor = env->GetMethodID(gattDbElementClazz.get(), "", "()V"); jmethodID arrayAdd; const JNIJavaMethod javaMethods[] = { - {"add", "(Ljava/lang/Object;)Z", &arrayAdd}, + {"add", "(Ljava/lang/Object;)Z", &arrayAdd}, }; GET_JAVA_METHODS(env, "java/util/ArrayList", javaMethods); jmethodID uuidConstructor; const JNIJavaMethod javaUuidMethods[] = { - {"", "(JJ)V", &uuidConstructor}, + {"", "(JJ)V", &uuidConstructor}, }; GET_JAVA_METHODS(env, "java/util/UUID", javaUuidMethods); @@ -508,8 +507,7 @@ void fillGattDbElementArray(JNIEnv* env, jobject* array, const btgatt_db_element_t& curr = db[i]; ScopedLocalRef element( - env, - env->NewObject(gattDbElementClazz.get(), gattDbElementConstructor)); + env, env->NewObject(gattDbElementClazz.get(), gattDbElementConstructor)); jfieldID fid = env->GetFieldID(gattDbElementClazz.get(), "id", "I"); env->SetIntField(element.get(), fid, curr.id); @@ -518,9 +516,8 @@ void fillGattDbElementArray(JNIEnv* env, jobject* array, env->SetIntField(element.get(), fid, curr.attribute_handle); ScopedLocalRef uuidClazz(env, env->FindClass("java/util/UUID")); - ScopedLocalRef uuid( - env, env->NewObject(uuidClazz.get(), uuidConstructor, - uuid_msb(curr.uuid), uuid_lsb(curr.uuid))); + ScopedLocalRef uuid(env, env->NewObject(uuidClazz.get(), uuidConstructor, + uuid_msb(curr.uuid), uuid_lsb(curr.uuid))); fid = env->GetFieldID(gattDbElementClazz.get(), "uuid", "Ljava/util/UUID;"); env->SetObjectField(element.get(), fid, uuid.get()); @@ -543,95 +540,99 @@ void fillGattDbElementArray(JNIEnv* env, jobject* array, } } -void btgattc_get_gatt_db_cb(int conn_id, const btgatt_db_element_t* db, - int count) { +void btgattc_get_gatt_db_cb(int conn_id, const btgatt_db_element_t* db, int count) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } jclass arrayListclazz = sCallbackEnv->FindClass("java/util/ArrayList"); ScopedLocalRef array( - sCallbackEnv.get(), - sCallbackEnv->NewObject( - arrayListclazz, - sCallbackEnv->GetMethodID(arrayListclazz, "", "()V"))); + sCallbackEnv.get(), + sCallbackEnv->NewObject(arrayListclazz, + sCallbackEnv->GetMethodID(arrayListclazz, "", "()V"))); jobject arrayPtr = array.get(); fillGattDbElementArray(sCallbackEnv.get(), &arrayPtr, db, count); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onGetGattDb, conn_id, - array.get()); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onGetGattDb, conn_id, array.get()); } -void btgattc_phy_updated_cb(int conn_id, uint8_t tx_phy, uint8_t rx_phy, - uint8_t status) { +void btgattc_phy_updated_cb(int conn_id, uint8_t tx_phy, uint8_t rx_phy, uint8_t status) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onClientPhyUpdate, conn_id, - tx_phy, rx_phy, status); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onClientPhyUpdate, conn_id, tx_phy, rx_phy, + status); } -void btgattc_conn_updated_cb(int conn_id, uint16_t interval, uint16_t latency, - uint16_t timeout, uint8_t status) { +void btgattc_conn_updated_cb(int conn_id, uint16_t interval, uint16_t latency, uint16_t timeout, + uint8_t status) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onClientConnUpdate, - conn_id, interval, latency, timeout, status); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onClientConnUpdate, conn_id, interval, latency, + timeout, status); } void btgattc_service_changed_cb(int conn_id) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onServiceChanged, conn_id); } -void btgattc_subrate_change_cb(int conn_id, uint16_t subrate_factor, - uint16_t latency, uint16_t cont_num, - uint16_t timeout, uint8_t status) { +void btgattc_subrate_change_cb(int conn_id, uint16_t subrate_factor, uint16_t latency, + uint16_t cont_num, uint16_t timeout, uint8_t status) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onClientSubrateChange, - conn_id, subrate_factor, latency, cont_num, - timeout, status); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onClientSubrateChange, conn_id, subrate_factor, + latency, cont_num, timeout, status); } static const btgatt_scanner_callbacks_t sGattScannerCallbacks = { - btgattc_scan_result_cb, - btgattc_batchscan_reports_cb, - btgattc_batchscan_threshold_cb, - btgattc_track_adv_event_cb, + btgattc_scan_result_cb, + btgattc_batchscan_reports_cb, + btgattc_batchscan_threshold_cb, + btgattc_track_adv_event_cb, }; static const btgatt_client_callbacks_t sGattClientCallbacks = { - btgattc_register_app_cb, - btgattc_open_cb, - btgattc_close_cb, - btgattc_search_complete_cb, - btgattc_register_for_notification_cb, - btgattc_notify_cb, - btgattc_read_characteristic_cb, - btgattc_write_characteristic_cb, - btgattc_read_descriptor_cb, - btgattc_write_descriptor_cb, - btgattc_execute_write_cb, - btgattc_remote_rssi_cb, - btgattc_configure_mtu_cb, - btgattc_congestion_cb, - btgattc_get_gatt_db_cb, - NULL, /* services_removed_cb */ - NULL, /* services_added_cb */ - btgattc_phy_updated_cb, - btgattc_conn_updated_cb, - btgattc_service_changed_cb, - btgattc_subrate_change_cb, + btgattc_register_app_cb, + btgattc_open_cb, + btgattc_close_cb, + btgattc_search_complete_cb, + btgattc_register_for_notification_cb, + btgattc_notify_cb, + btgattc_read_characteristic_cb, + btgattc_write_characteristic_cb, + btgattc_read_descriptor_cb, + btgattc_write_descriptor_cb, + btgattc_execute_write_cb, + btgattc_remote_rssi_cb, + btgattc_configure_mtu_cb, + btgattc_congestion_cb, + btgattc_get_gatt_db_cb, + NULL, /* services_removed_cb */ + NULL, /* services_added_cb */ + btgattc_phy_updated_cb, + btgattc_conn_updated_cb, + btgattc_service_changed_cb, + btgattc_subrate_change_cb, }; /** @@ -642,25 +643,26 @@ void btgatts_register_app_cb(int status, int server_if, const Uuid& uuid) { bluetooth::gatt::open_server(server_if); std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onServerRegistered, status, - server_if, UUID_PARAMS(uuid)); + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onServerRegistered, status, server_if, + UUID_PARAMS(uuid)); } -void btgatts_connection_cb(int conn_id, int server_if, int connected, - const RawAddress& bda) { +void btgatts_connection_cb(int conn_id, int server_if, int connected, const RawAddress& bda) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } - ScopedLocalRef address(sCallbackEnv.get(), - bdaddr2newjstr(sCallbackEnv.get(), &bda)); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onClientConnected, - address.get(), connected, conn_id, server_if); + ScopedLocalRef address(sCallbackEnv.get(), bdaddr2newjstr(sCallbackEnv.get(), &bda)); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onClientConnected, address.get(), connected, + conn_id, server_if); } -void btgatts_service_added_cb(int status, int server_if, - const btgatt_db_element_t* service, +void btgatts_service_added_cb(int status, int server_if, const btgatt_db_element_t* service, size_t service_count) { // mirror the database in rust, now that it's created. if (status == 0x00 /* SUCCESS */) { @@ -668,28 +670,29 @@ void btgatts_service_added_cb(int status, int server_if, for (size_t i = 0; i != service_count; ++i) { auto& curr_service = service[i]; service_records.push_back(bluetooth::gatt::GattRecord{ - curr_service.uuid, (bluetooth::gatt::GattRecordType)curr_service.type, - curr_service.attribute_handle, curr_service.properties, - curr_service.extended_properties, curr_service.permissions}); + curr_service.uuid, (bluetooth::gatt::GattRecordType)curr_service.type, + curr_service.attribute_handle, curr_service.properties, + curr_service.extended_properties, curr_service.permissions}); } bluetooth::gatt::add_service(server_if, std::move(service_records)); } std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } jclass arrayListclazz = sCallbackEnv->FindClass("java/util/ArrayList"); ScopedLocalRef array( - sCallbackEnv.get(), - sCallbackEnv->NewObject( - arrayListclazz, - sCallbackEnv->GetMethodID(arrayListclazz, "", "()V"))); + sCallbackEnv.get(), + sCallbackEnv->NewObject(arrayListclazz, + sCallbackEnv->GetMethodID(arrayListclazz, "", "()V"))); jobject arrayPtr = array.get(); fillGattDbElementArray(sCallbackEnv.get(), &arrayPtr, service, service_count); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onServiceAdded, status, - server_if, array.get()); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onServiceAdded, status, server_if, + array.get()); } void btgatts_service_stopped_cb(int status, int server_if, int srvc_handle) { @@ -697,9 +700,11 @@ void btgatts_service_stopped_cb(int status, int server_if, int srvc_handle) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onServiceStopped, status, - server_if, srvc_handle); + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onServiceStopped, status, server_if, + srvc_handle); } void btgatts_service_deleted_cb(int status, int server_if, int srvc_handle) { @@ -707,175 +712,179 @@ void btgatts_service_deleted_cb(int status, int server_if, int srvc_handle) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onServiceDeleted, status, - server_if, srvc_handle); + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onServiceDeleted, status, server_if, + srvc_handle); } -void btgatts_request_read_characteristic_cb(int conn_id, int trans_id, - const RawAddress& bda, - int attr_handle, int offset, - bool is_long) { +void btgatts_request_read_characteristic_cb(int conn_id, int trans_id, const RawAddress& bda, + int attr_handle, int offset, bool is_long) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } - ScopedLocalRef address(sCallbackEnv.get(), - bdaddr2newjstr(sCallbackEnv.get(), &bda)); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onServerReadCharacteristic, - address.get(), conn_id, trans_id, attr_handle, - offset, is_long); + ScopedLocalRef address(sCallbackEnv.get(), bdaddr2newjstr(sCallbackEnv.get(), &bda)); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onServerReadCharacteristic, address.get(), + conn_id, trans_id, attr_handle, offset, is_long); } -void btgatts_request_read_descriptor_cb(int conn_id, int trans_id, - const RawAddress& bda, int attr_handle, - int offset, bool is_long) { +void btgatts_request_read_descriptor_cb(int conn_id, int trans_id, const RawAddress& bda, + int attr_handle, int offset, bool is_long) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } - ScopedLocalRef address(sCallbackEnv.get(), - bdaddr2newjstr(sCallbackEnv.get(), &bda)); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onServerReadDescriptor, - address.get(), conn_id, trans_id, attr_handle, - offset, is_long); -} - -void btgatts_request_write_characteristic_cb(int conn_id, int trans_id, - const RawAddress& bda, - int attr_handle, int offset, - bool need_rsp, bool is_prep, - const uint8_t* value, - size_t length) { + ScopedLocalRef address(sCallbackEnv.get(), bdaddr2newjstr(sCallbackEnv.get(), &bda)); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onServerReadDescriptor, address.get(), conn_id, + trans_id, attr_handle, offset, is_long); +} + +void btgatts_request_write_characteristic_cb(int conn_id, int trans_id, const RawAddress& bda, + int attr_handle, int offset, bool need_rsp, + bool is_prep, const uint8_t* value, size_t length) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } - ScopedLocalRef address(sCallbackEnv.get(), - bdaddr2newjstr(sCallbackEnv.get(), &bda)); - ScopedLocalRef val(sCallbackEnv.get(), - sCallbackEnv->NewByteArray(length)); - if (val.get()) + ScopedLocalRef address(sCallbackEnv.get(), bdaddr2newjstr(sCallbackEnv.get(), &bda)); + ScopedLocalRef val(sCallbackEnv.get(), sCallbackEnv->NewByteArray(length)); + if (val.get()) { sCallbackEnv->SetByteArrayRegion(val.get(), 0, length, (jbyte*)value); - sCallbackEnv->CallVoidMethod( - mCallbacksObj, method_onServerWriteCharacteristic, address.get(), conn_id, - trans_id, attr_handle, offset, length, need_rsp, is_prep, val.get()); + } + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onServerWriteCharacteristic, address.get(), + conn_id, trans_id, attr_handle, offset, length, need_rsp, is_prep, + val.get()); } -void btgatts_request_write_descriptor_cb(int conn_id, int trans_id, - const RawAddress& bda, int attr_handle, - int offset, bool need_rsp, - bool is_prep, const uint8_t* value, - size_t length) { +void btgatts_request_write_descriptor_cb(int conn_id, int trans_id, const RawAddress& bda, + int attr_handle, int offset, bool need_rsp, bool is_prep, + const uint8_t* value, size_t length) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } - ScopedLocalRef address(sCallbackEnv.get(), - bdaddr2newjstr(sCallbackEnv.get(), &bda)); - ScopedLocalRef val(sCallbackEnv.get(), - sCallbackEnv->NewByteArray(length)); - if (val.get()) + ScopedLocalRef address(sCallbackEnv.get(), bdaddr2newjstr(sCallbackEnv.get(), &bda)); + ScopedLocalRef val(sCallbackEnv.get(), sCallbackEnv->NewByteArray(length)); + if (val.get()) { sCallbackEnv->SetByteArrayRegion(val.get(), 0, length, (jbyte*)value); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onServerWriteDescriptor, - address.get(), conn_id, trans_id, attr_handle, - offset, length, need_rsp, is_prep, val.get()); + } + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onServerWriteDescriptor, address.get(), + conn_id, trans_id, attr_handle, offset, length, need_rsp, is_prep, + val.get()); } -void btgatts_request_exec_write_cb(int conn_id, int trans_id, - const RawAddress& bda, int exec_write) { +void btgatts_request_exec_write_cb(int conn_id, int trans_id, const RawAddress& bda, + int exec_write) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } - ScopedLocalRef address(sCallbackEnv.get(), - bdaddr2newjstr(sCallbackEnv.get(), &bda)); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onExecuteWrite, - address.get(), conn_id, trans_id, exec_write); + ScopedLocalRef address(sCallbackEnv.get(), bdaddr2newjstr(sCallbackEnv.get(), &bda)); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onExecuteWrite, address.get(), conn_id, + trans_id, exec_write); } void btgatts_response_confirmation_cb(int status, int handle) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onResponseSendCompleted, - status, handle); + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onResponseSendCompleted, status, handle); } void btgatts_indication_sent_cb(int conn_id, int status) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onNotificationSent, - conn_id, status); + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onNotificationSent, conn_id, status); } void btgatts_congestion_cb(int conn_id, bool congested) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onServerCongestion, - conn_id, congested); + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onServerCongestion, conn_id, congested); } void btgatts_mtu_changed_cb(int conn_id, int mtu) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onServerMtuChanged, - conn_id, mtu); + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onServerMtuChanged, conn_id, mtu); } -void btgatts_phy_updated_cb(int conn_id, uint8_t tx_phy, uint8_t rx_phy, - uint8_t status) { +void btgatts_phy_updated_cb(int conn_id, uint8_t tx_phy, uint8_t rx_phy, uint8_t status) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onServerPhyUpdate, conn_id, - tx_phy, rx_phy, status); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onServerPhyUpdate, conn_id, tx_phy, rx_phy, + status); } -void btgatts_conn_updated_cb(int conn_id, uint16_t interval, uint16_t latency, - uint16_t timeout, uint8_t status) { +void btgatts_conn_updated_cb(int conn_id, uint16_t interval, uint16_t latency, uint16_t timeout, + uint8_t status) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onServerConnUpdate, - conn_id, interval, latency, timeout, status); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onServerConnUpdate, conn_id, interval, latency, + timeout, status); } -void btgatts_subrate_change_cb(int conn_id, uint16_t subrate_factor, - uint16_t latency, uint16_t cont_num, - uint16_t timeout, uint8_t status) { +void btgatts_subrate_change_cb(int conn_id, uint16_t subrate_factor, uint16_t latency, + uint16_t cont_num, uint16_t timeout, uint8_t status) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onServerSubrateChange, - conn_id, subrate_factor, latency, cont_num, - timeout, status); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onServerSubrateChange, conn_id, subrate_factor, + latency, cont_num, timeout, status); } static const btgatt_server_callbacks_t sGattServerCallbacks = { - btgatts_register_app_cb, - btgatts_connection_cb, - btgatts_service_added_cb, - btgatts_service_stopped_cb, - btgatts_service_deleted_cb, - btgatts_request_read_characteristic_cb, - btgatts_request_read_descriptor_cb, - btgatts_request_write_characteristic_cb, - btgatts_request_write_descriptor_cb, - btgatts_request_exec_write_cb, - btgatts_response_confirmation_cb, - btgatts_indication_sent_cb, - btgatts_congestion_cb, - btgatts_mtu_changed_cb, - btgatts_phy_updated_cb, - btgatts_conn_updated_cb, - btgatts_subrate_change_cb, + btgatts_register_app_cb, + btgatts_connection_cb, + btgatts_service_added_cb, + btgatts_service_stopped_cb, + btgatts_service_deleted_cb, + btgatts_request_read_characteristic_cb, + btgatts_request_read_descriptor_cb, + btgatts_request_write_characteristic_cb, + btgatts_request_write_descriptor_cb, + btgatts_request_exec_write_cb, + btgatts_response_confirmation_cb, + btgatts_indication_sent_cb, + btgatts_congestion_cb, + btgatts_mtu_changed_cb, + btgatts_phy_updated_cb, + btgatts_conn_updated_cb, + btgatts_subrate_change_cb, }; /** @@ -883,159 +892,164 @@ static const btgatt_server_callbacks_t sGattServerCallbacks = { */ static const btgatt_callbacks_t sGattCallbacks = { - sizeof(btgatt_callbacks_t), &sGattClientCallbacks, &sGattServerCallbacks, - &sGattScannerCallbacks, + sizeof(btgatt_callbacks_t), + &sGattClientCallbacks, + &sGattServerCallbacks, + &sGattScannerCallbacks, }; class JniAdvertisingCallbacks : AdvertisingCallbacks { - public: +public: static AdvertisingCallbacks* GetInstance() { static AdvertisingCallbacks* instance = new JniAdvertisingCallbacks(); return instance; } - void OnAdvertisingSetStarted(int reg_id, uint8_t advertiser_id, - int8_t tx_power, uint8_t status) { + void OnAdvertisingSetStarted(int reg_id, uint8_t advertiser_id, int8_t tx_power, uint8_t status) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mAdvertiseCallbacksObj == NULL) return; - sCallbackEnv->CallVoidMethod(mAdvertiseCallbacksObj, - method_onAdvertisingSetStarted, reg_id, + if (!sCallbackEnv.valid() || mAdvertiseCallbacksObj == NULL) { + return; + } + sCallbackEnv->CallVoidMethod(mAdvertiseCallbacksObj, method_onAdvertisingSetStarted, reg_id, advertiser_id, tx_power, status); } - void OnAdvertisingEnabled(uint8_t advertiser_id, bool enable, - uint8_t status) { + void OnAdvertisingEnabled(uint8_t advertiser_id, bool enable, uint8_t status) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mAdvertiseCallbacksObj == NULL) return; - sCallbackEnv->CallVoidMethod(mAdvertiseCallbacksObj, - method_onAdvertisingEnabled, advertiser_id, + if (!sCallbackEnv.valid() || mAdvertiseCallbacksObj == NULL) { + return; + } + sCallbackEnv->CallVoidMethod(mAdvertiseCallbacksObj, method_onAdvertisingEnabled, advertiser_id, enable, status); } void OnAdvertisingDataSet(uint8_t advertiser_id, uint8_t status) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mAdvertiseCallbacksObj == NULL) return; - sCallbackEnv->CallVoidMethod(mAdvertiseCallbacksObj, - method_onAdvertisingDataSet, advertiser_id, + if (!sCallbackEnv.valid() || mAdvertiseCallbacksObj == NULL) { + return; + } + sCallbackEnv->CallVoidMethod(mAdvertiseCallbacksObj, method_onAdvertisingDataSet, advertiser_id, status); } void OnScanResponseDataSet(uint8_t advertiser_id, uint8_t status) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mAdvertiseCallbacksObj == NULL) return; - sCallbackEnv->CallVoidMethod(mAdvertiseCallbacksObj, - method_onScanResponseDataSet, advertiser_id, - status); + if (!sCallbackEnv.valid() || mAdvertiseCallbacksObj == NULL) { + return; + } + sCallbackEnv->CallVoidMethod(mAdvertiseCallbacksObj, method_onScanResponseDataSet, + advertiser_id, status); } - void OnAdvertisingParametersUpdated(uint8_t advertiser_id, int8_t tx_power, - uint8_t status) { + void OnAdvertisingParametersUpdated(uint8_t advertiser_id, int8_t tx_power, uint8_t status) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mAdvertiseCallbacksObj == NULL) return; - sCallbackEnv->CallVoidMethod(mAdvertiseCallbacksObj, - method_onAdvertisingParametersUpdated, + if (!sCallbackEnv.valid() || mAdvertiseCallbacksObj == NULL) { + return; + } + sCallbackEnv->CallVoidMethod(mAdvertiseCallbacksObj, method_onAdvertisingParametersUpdated, advertiser_id, tx_power, status); } - void OnPeriodicAdvertisingParametersUpdated(uint8_t advertiser_id, - uint8_t status) { + void OnPeriodicAdvertisingParametersUpdated(uint8_t advertiser_id, uint8_t status) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mAdvertiseCallbacksObj == NULL) return; + if (!sCallbackEnv.valid() || mAdvertiseCallbacksObj == NULL) { + return; + } sCallbackEnv->CallVoidMethod(mAdvertiseCallbacksObj, - method_onPeriodicAdvertisingParametersUpdated, - advertiser_id, status); + method_onPeriodicAdvertisingParametersUpdated, advertiser_id, + status); } void OnPeriodicAdvertisingDataSet(uint8_t advertiser_id, uint8_t status) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mAdvertiseCallbacksObj == NULL) return; - sCallbackEnv->CallVoidMethod(mAdvertiseCallbacksObj, - method_onPeriodicAdvertisingDataSet, + if (!sCallbackEnv.valid() || mAdvertiseCallbacksObj == NULL) { + return; + } + sCallbackEnv->CallVoidMethod(mAdvertiseCallbacksObj, method_onPeriodicAdvertisingDataSet, advertiser_id, status); } - void OnPeriodicAdvertisingEnabled(uint8_t advertiser_id, bool enable, - uint8_t status) { + void OnPeriodicAdvertisingEnabled(uint8_t advertiser_id, bool enable, uint8_t status) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mAdvertiseCallbacksObj == NULL) return; - sCallbackEnv->CallVoidMethod(mAdvertiseCallbacksObj, - method_onPeriodicAdvertisingEnabled, + if (!sCallbackEnv.valid() || mAdvertiseCallbacksObj == NULL) { + return; + } + sCallbackEnv->CallVoidMethod(mAdvertiseCallbacksObj, method_onPeriodicAdvertisingEnabled, advertiser_id, enable, status); } - void OnOwnAddressRead(uint8_t advertiser_id, uint8_t address_type, - RawAddress address) { + void OnOwnAddressRead(uint8_t advertiser_id, uint8_t address_type, RawAddress address) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mAdvertiseCallbacksObj == NULL) return; + if (!sCallbackEnv.valid() || mAdvertiseCallbacksObj == NULL) { + return; + } - ScopedLocalRef addr(sCallbackEnv.get(), - bdaddr2newjstr(sCallbackEnv.get(), &address)); - sCallbackEnv->CallVoidMethod(mAdvertiseCallbacksObj, - method_onOwnAddressRead, advertiser_id, + ScopedLocalRef addr(sCallbackEnv.get(), bdaddr2newjstr(sCallbackEnv.get(), &address)); + sCallbackEnv->CallVoidMethod(mAdvertiseCallbacksObj, method_onOwnAddressRead, advertiser_id, address_type, addr.get()); } }; class JniScanningCallbacks : ScanningCallbacks { - public: +public: static ScanningCallbacks* GetInstance() { static ScanningCallbacks* instance = new JniScanningCallbacks(); return instance; } - void OnScannerRegistered(const Uuid app_uuid, uint8_t scannerId, - uint8_t status) { + void OnScannerRegistered(const Uuid app_uuid, uint8_t scannerId, uint8_t status) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mScanCallbacksObj) return; - sCallbackEnv->CallVoidMethod(mScanCallbacksObj, method_onScannerRegistered, - status, scannerId, UUID_PARAMS(app_uuid)); + if (!sCallbackEnv.valid() || !mScanCallbacksObj) { + return; + } + sCallbackEnv->CallVoidMethod(mScanCallbacksObj, method_onScannerRegistered, status, scannerId, + UUID_PARAMS(app_uuid)); } void OnSetScannerParameterComplete(uint8_t scannerId, uint8_t status) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mScanCallbacksObj) return; - sCallbackEnv->CallVoidMethod( - mScanCallbacksObj, method_onScanParamSetupCompleted, status, scannerId); + if (!sCallbackEnv.valid() || !mScanCallbacksObj) { + return; + } + sCallbackEnv->CallVoidMethod(mScanCallbacksObj, method_onScanParamSetupCompleted, status, + scannerId); } - void OnScanResult(uint16_t event_type, uint8_t addr_type, RawAddress bda, - uint8_t primary_phy, uint8_t secondary_phy, - uint8_t advertising_sid, int8_t tx_power, int8_t rssi, + void OnScanResult(uint16_t event_type, uint8_t addr_type, RawAddress bda, uint8_t primary_phy, + uint8_t secondary_phy, uint8_t advertising_sid, int8_t tx_power, int8_t rssi, uint16_t periodic_adv_int, std::vector adv_data) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mScanCallbacksObj) return; + if (!sCallbackEnv.valid() || !mScanCallbacksObj) { + return; + } - ScopedLocalRef address(sCallbackEnv.get(), - bdaddr2newjstr(sCallbackEnv.get(), &bda)); - ScopedLocalRef jb(sCallbackEnv.get(), - sCallbackEnv->NewByteArray(adv_data.size())); - sCallbackEnv->SetByteArrayRegion(jb.get(), 0, adv_data.size(), - (jbyte*)adv_data.data()); + ScopedLocalRef address(sCallbackEnv.get(), bdaddr2newjstr(sCallbackEnv.get(), &bda)); + ScopedLocalRef jb(sCallbackEnv.get(), sCallbackEnv->NewByteArray(adv_data.size())); + sCallbackEnv->SetByteArrayRegion(jb.get(), 0, adv_data.size(), (jbyte*)adv_data.data()); // TODO(optedoblivion): Figure out original address for here, use empty // for now // length of data + '\0' char empty_address[18] = "00:00:00:00:00:00"; - ScopedLocalRef fake_address( - sCallbackEnv.get(), sCallbackEnv->NewStringUTF(empty_address)); + ScopedLocalRef fake_address(sCallbackEnv.get(), + sCallbackEnv->NewStringUTF(empty_address)); - sCallbackEnv->CallVoidMethod( - mScanCallbacksObj, method_onScanResult, event_type, addr_type, - address.get(), primary_phy, secondary_phy, advertising_sid, tx_power, - rssi, periodic_adv_int, jb.get(), fake_address.get()); + sCallbackEnv->CallVoidMethod(mScanCallbacksObj, method_onScanResult, event_type, addr_type, + address.get(), primary_phy, secondary_phy, advertising_sid, + tx_power, rssi, periodic_adv_int, jb.get(), fake_address.get()); } void OnTrackAdvFoundLost(AdvertisingTrackInfo track_info) { @@ -1047,179 +1061,169 @@ class JniScanningCallbacks : ScanningCallbacks { } ScopedLocalRef address( - sCallbackEnv.get(), - bdaddr2newjstr(sCallbackEnv.get(), &track_info.advertiser_address)); + sCallbackEnv.get(), bdaddr2newjstr(sCallbackEnv.get(), &track_info.advertiser_address)); - ScopedLocalRef jb_adv_pkt( - sCallbackEnv.get(), - sCallbackEnv->NewByteArray(track_info.adv_packet_len)); + ScopedLocalRef jb_adv_pkt(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(track_info.adv_packet_len)); ScopedLocalRef jb_scan_rsp( - sCallbackEnv.get(), - sCallbackEnv->NewByteArray(track_info.scan_response_len)); + sCallbackEnv.get(), sCallbackEnv->NewByteArray(track_info.scan_response_len)); - sCallbackEnv->SetByteArrayRegion(jb_adv_pkt.get(), 0, - track_info.adv_packet_len, + sCallbackEnv->SetByteArrayRegion(jb_adv_pkt.get(), 0, track_info.adv_packet_len, (jbyte*)track_info.adv_packet.data()); - sCallbackEnv->SetByteArrayRegion(jb_scan_rsp.get(), 0, - track_info.scan_response_len, + sCallbackEnv->SetByteArrayRegion(jb_scan_rsp.get(), 0, track_info.scan_response_len, (jbyte*)track_info.scan_response.data()); ScopedLocalRef trackadv_obj( - sCallbackEnv.get(), - sCallbackEnv->CallObjectMethod( - mScanCallbacksObj, method_createOnTrackAdvFoundLostObject, - track_info.scanner_id, track_info.adv_packet_len, jb_adv_pkt.get(), - track_info.scan_response_len, jb_scan_rsp.get(), - track_info.filter_index, track_info.advertiser_state, - track_info.advertiser_info_present, address.get(), - track_info.advertiser_address_type, track_info.tx_power, - track_info.rssi, track_info.time_stamp)); + sCallbackEnv.get(), + sCallbackEnv->CallObjectMethod( + mScanCallbacksObj, method_createOnTrackAdvFoundLostObject, + track_info.scanner_id, track_info.adv_packet_len, jb_adv_pkt.get(), + track_info.scan_response_len, jb_scan_rsp.get(), track_info.filter_index, + track_info.advertiser_state, track_info.advertiser_info_present, address.get(), + track_info.advertiser_address_type, track_info.tx_power, track_info.rssi, + track_info.time_stamp)); if (NULL != trackadv_obj.get()) { - sCallbackEnv->CallVoidMethod( - mScanCallbacksObj, method_onTrackAdvFoundLost, trackadv_obj.get()); + sCallbackEnv->CallVoidMethod(mScanCallbacksObj, method_onTrackAdvFoundLost, + trackadv_obj.get()); } } - void OnBatchScanReports(int client_if, int status, int report_format, - int num_records, std::vector data) { + void OnBatchScanReports(int client_if, int status, int report_format, int num_records, + std::vector data) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mScanCallbacksObj) return; - ScopedLocalRef jb(sCallbackEnv.get(), - sCallbackEnv->NewByteArray(data.size())); - sCallbackEnv->SetByteArrayRegion(jb.get(), 0, data.size(), - (jbyte*)data.data()); + if (!sCallbackEnv.valid() || !mScanCallbacksObj) { + return; + } + ScopedLocalRef jb(sCallbackEnv.get(), sCallbackEnv->NewByteArray(data.size())); + sCallbackEnv->SetByteArrayRegion(jb.get(), 0, data.size(), (jbyte*)data.data()); - sCallbackEnv->CallVoidMethod(mScanCallbacksObj, method_onBatchScanReports, - status, client_if, report_format, num_records, - jb.get()); + sCallbackEnv->CallVoidMethod(mScanCallbacksObj, method_onBatchScanReports, status, client_if, + report_format, num_records, jb.get()); } void OnBatchScanThresholdCrossed(int client_if) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mScanCallbacksObj) return; - sCallbackEnv->CallVoidMethod(mScanCallbacksObj, - method_onBatchScanThresholdCrossed, client_if); + if (!sCallbackEnv.valid() || !mScanCallbacksObj) { + return; + } + sCallbackEnv->CallVoidMethod(mScanCallbacksObj, method_onBatchScanThresholdCrossed, client_if); } - void OnPeriodicSyncStarted(int reg_id, uint8_t status, uint16_t sync_handle, - uint8_t sid, uint8_t address_type, - RawAddress address, uint8_t phy, + void OnPeriodicSyncStarted(int reg_id, uint8_t status, uint16_t sync_handle, uint8_t sid, + uint8_t address_type, RawAddress address, uint8_t phy, uint16_t interval) override { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid()) return; + if (!sCallbackEnv.valid()) { + return; + } if (!mPeriodicScanCallbacksObj) { log::error("mPeriodicScanCallbacksObj is NULL. Return."); return; } - ScopedLocalRef addr(sCallbackEnv.get(), - bdaddr2newjstr(sCallbackEnv.get(), &address)); + ScopedLocalRef addr(sCallbackEnv.get(), bdaddr2newjstr(sCallbackEnv.get(), &address)); - sCallbackEnv->CallVoidMethod( - mPeriodicScanCallbacksObj, method_onSyncStarted, reg_id, sync_handle, - sid, address_type, addr.get(), phy, interval, status); + sCallbackEnv->CallVoidMethod(mPeriodicScanCallbacksObj, method_onSyncStarted, reg_id, + sync_handle, sid, address_type, addr.get(), phy, interval, status); } - void OnPeriodicSyncReport(uint16_t sync_handle, int8_t tx_power, int8_t rssi, - uint8_t data_status, + void OnPeriodicSyncReport(uint16_t sync_handle, int8_t tx_power, int8_t rssi, uint8_t data_status, std::vector data) override { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mPeriodicScanCallbacksObj) return; + if (!sCallbackEnv.valid() || !mPeriodicScanCallbacksObj) { + return; + } - ScopedLocalRef jb(sCallbackEnv.get(), - sCallbackEnv->NewByteArray(data.size())); - sCallbackEnv->SetByteArrayRegion(jb.get(), 0, data.size(), - (jbyte*)data.data()); + ScopedLocalRef jb(sCallbackEnv.get(), sCallbackEnv->NewByteArray(data.size())); + sCallbackEnv->SetByteArrayRegion(jb.get(), 0, data.size(), (jbyte*)data.data()); - sCallbackEnv->CallVoidMethod(mPeriodicScanCallbacksObj, method_onSyncReport, - sync_handle, tx_power, rssi, data_status, - jb.get()); + sCallbackEnv->CallVoidMethod(mPeriodicScanCallbacksObj, method_onSyncReport, sync_handle, + tx_power, rssi, data_status, jb.get()); } void OnPeriodicSyncLost(uint16_t sync_handle) override { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mPeriodicScanCallbacksObj) return; + if (!sCallbackEnv.valid() || !mPeriodicScanCallbacksObj) { + return; + } - sCallbackEnv->CallVoidMethod(mPeriodicScanCallbacksObj, method_onSyncLost, - sync_handle); + sCallbackEnv->CallVoidMethod(mPeriodicScanCallbacksObj, method_onSyncLost, sync_handle); } - void OnPeriodicSyncTransferred(int pa_source, uint8_t status, - RawAddress address) override { + void OnPeriodicSyncTransferred(int pa_source, uint8_t status, RawAddress address) override { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid()) return; + if (!sCallbackEnv.valid()) { + return; + } if (!mPeriodicScanCallbacksObj) { log::error("mPeriodicScanCallbacksObj is NULL. Return."); return; } - ScopedLocalRef addr(sCallbackEnv.get(), - bdaddr2newjstr(sCallbackEnv.get(), &address)); + ScopedLocalRef addr(sCallbackEnv.get(), bdaddr2newjstr(sCallbackEnv.get(), &address)); - sCallbackEnv->CallVoidMethod(mPeriodicScanCallbacksObj, - method_onSyncTransferredCallback, pa_source, - status, addr.get()); + sCallbackEnv->CallVoidMethod(mPeriodicScanCallbacksObj, method_onSyncTransferredCallback, + pa_source, status, addr.get()); } void OnBigInfoReport(uint16_t sync_handle, bool encrypted) { - std::shared_lock lock(callbacks_mutex); + std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid()) return; + if (!sCallbackEnv.valid()) { + return; + } if (!mPeriodicScanCallbacksObj) { log::error("mPeriodicScanCallbacksObj is NULL. Return."); return; } - sCallbackEnv->CallVoidMethod(mPeriodicScanCallbacksObj, - method_onBigInfoReport, sync_handle, encrypted); + sCallbackEnv->CallVoidMethod(mPeriodicScanCallbacksObj, method_onBigInfoReport, sync_handle, + encrypted); } }; class JniDistanceMeasurementCallbacks : DistanceMeasurementCallbacks { - public: +public: static DistanceMeasurementCallbacks* GetInstance() { - static DistanceMeasurementCallbacks* instance = - new JniDistanceMeasurementCallbacks(); + static DistanceMeasurementCallbacks* instance = new JniDistanceMeasurementCallbacks(); return instance; } void OnDistanceMeasurementStarted(RawAddress address, uint8_t method) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mDistanceMeasurementCallbacksObj) return; - ScopedLocalRef addr(sCallbackEnv.get(), - bdaddr2newjstr(sCallbackEnv.get(), &address)); + if (!sCallbackEnv.valid() || !mDistanceMeasurementCallbacksObj) { + return; + } + ScopedLocalRef addr(sCallbackEnv.get(), bdaddr2newjstr(sCallbackEnv.get(), &address)); sCallbackEnv->CallVoidMethod(mDistanceMeasurementCallbacksObj, - method_onDistanceMeasurementStarted, - addr.get(), method); + method_onDistanceMeasurementStarted, addr.get(), method); } - void OnDistanceMeasurementStartFail(RawAddress address, uint8_t reason, - uint8_t method) { + void OnDistanceMeasurementStartFail(RawAddress address, uint8_t reason, uint8_t method) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mDistanceMeasurementCallbacksObj) return; - ScopedLocalRef addr(sCallbackEnv.get(), - bdaddr2newjstr(sCallbackEnv.get(), &address)); + if (!sCallbackEnv.valid() || !mDistanceMeasurementCallbacksObj) { + return; + } + ScopedLocalRef addr(sCallbackEnv.get(), bdaddr2newjstr(sCallbackEnv.get(), &address)); sCallbackEnv->CallVoidMethod(mDistanceMeasurementCallbacksObj, - method_onDistanceMeasurementStartFail, - addr.get(), reason, method); + method_onDistanceMeasurementStartFail, addr.get(), reason, method); } - void OnDistanceMeasurementStopped(RawAddress address, uint8_t reason, - uint8_t method) { + void OnDistanceMeasurementStopped(RawAddress address, uint8_t reason, uint8_t method) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mDistanceMeasurementCallbacksObj) return; - ScopedLocalRef addr(sCallbackEnv.get(), - bdaddr2newjstr(sCallbackEnv.get(), &address)); + if (!sCallbackEnv.valid() || !mDistanceMeasurementCallbacksObj) { + return; + } + ScopedLocalRef addr(sCallbackEnv.get(), bdaddr2newjstr(sCallbackEnv.get(), &address)); sCallbackEnv->CallVoidMethod(mDistanceMeasurementCallbacksObj, - method_onDistanceMeasurementStopped, - addr.get(), reason, method); + method_onDistanceMeasurementStopped, addr.get(), reason, method); } void OnDistanceMeasurementResult(RawAddress address, uint32_t centimeter, @@ -1228,13 +1232,14 @@ class JniDistanceMeasurementCallbacks : DistanceMeasurementCallbacks { int error_altitude_angle, uint8_t method) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mDistanceMeasurementCallbacksObj) return; - ScopedLocalRef addr(sCallbackEnv.get(), - bdaddr2newjstr(sCallbackEnv.get(), &address)); - sCallbackEnv->CallVoidMethod( - mDistanceMeasurementCallbacksObj, method_onDistanceMeasurementResult, - addr.get(), centimeter, error_centimeter, azimuth_angle, - error_azimuth_angle, altitude_angle, error_altitude_angle, method); + if (!sCallbackEnv.valid() || !mDistanceMeasurementCallbacksObj) { + return; + } + ScopedLocalRef addr(sCallbackEnv.get(), bdaddr2newjstr(sCallbackEnv.get(), &address)); + sCallbackEnv->CallVoidMethod(mDistanceMeasurementCallbacksObj, + method_onDistanceMeasurementResult, addr.get(), centimeter, + error_centimeter, azimuth_angle, error_azimuth_angle, + altitude_angle, error_altitude_angle, method); } }; @@ -1245,7 +1250,9 @@ static const bt_interface_t* btIf; static void initializeNative(JNIEnv* env, jobject object) { std::unique_lock lock(callbacks_mutex); - if (btIf) return; + if (btIf) { + return; + } btIf = getBluetoothInterface(); if (btIf == NULL) { @@ -1265,8 +1272,7 @@ static void initializeNative(JNIEnv* env, jobject object) { mCallbacksObj = NULL; } - sGattIf = - (btgatt_interface_t*)btIf->get_profile_interface(BT_PROFILE_GATT_ID); + sGattIf = (btgatt_interface_t*)btIf->get_profile_interface(BT_PROFILE_GATT_ID); if (sGattIf == NULL) { log::error("Failed to get Bluetooth GATT Interface"); return; @@ -1274,8 +1280,7 @@ static void initializeNative(JNIEnv* env, jobject object) { bt_status_t status = sGattIf->init(&sGattCallbacks); if (status != BT_STATUS_SUCCESS) { - log::error("Failed to initialize Bluetooth GATT, status: {}", - bt_status_text(status)); + log::error("Failed to initialize Bluetooth GATT, status: {}", bt_status_text(status)); sGattIf = NULL; return; } @@ -1284,10 +1289,9 @@ static void initializeNative(JNIEnv* env, jobject object) { btIf->start_rust_module(); } - sGattIf->advertiser->RegisterCallbacks( - JniAdvertisingCallbacks::GetInstance()); + sGattIf->advertiser->RegisterCallbacks(JniAdvertisingCallbacks::GetInstance()); sGattIf->distance_measurement_manager->RegisterDistanceMeasurementCallbacks( - JniDistanceMeasurementCallbacks::GetInstance()); + JniDistanceMeasurementCallbacks::GetInstance()); mCallbacksObj = env->NewGlobalRef(object); } @@ -1295,7 +1299,9 @@ static void initializeNative(JNIEnv* env, jobject object) { static void cleanupNative(JNIEnv* env, jobject /* object */) { std::unique_lock lock(callbacks_mutex); - if (!btIf) return; + if (!btIf) { + return; + } if (com::android::bluetooth::flags::scan_manager_refactor()) { btIf->stop_rust_module(); @@ -1317,174 +1323,191 @@ static void cleanupNative(JNIEnv* env, jobject /* object */) { * Native Client functions */ -static int gattClientGetDeviceTypeNative(JNIEnv* env, jobject /* object */, - jstring address) { - if (!sGattIf) return 0; +static int gattClientGetDeviceTypeNative(JNIEnv* env, jobject /* object */, jstring address) { + if (!sGattIf) { + return 0; + } return sGattIf->client->get_device_type(str2addr(env, address)); } -static void gattClientRegisterAppNative(JNIEnv* /* env */, jobject /* object */, - jlong app_uuid_lsb, jlong app_uuid_msb, - jboolean eatt_support) { - if (!sGattIf) return; +static void gattClientRegisterAppNative(JNIEnv* /* env */, jobject /* object */, jlong app_uuid_lsb, + jlong app_uuid_msb, jboolean eatt_support) { + if (!sGattIf) { + return; + } Uuid uuid = from_java_uuid(app_uuid_msb, app_uuid_lsb); sGattIf->client->register_client(uuid, eatt_support); } -static void gattClientUnregisterAppNative(JNIEnv* /* env */, - jobject /* object */, jint clientIf) { - if (!sGattIf) return; +static void gattClientUnregisterAppNative(JNIEnv* /* env */, jobject /* object */, jint clientIf) { + if (!sGattIf) { + return; + } sGattIf->client->unregister_client(clientIf); } -void btgattc_register_scanner_cb(const Uuid& app_uuid, uint8_t scannerId, - uint8_t status) { +void btgattc_register_scanner_cb(const Uuid& app_uuid, uint8_t scannerId, uint8_t status) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mScanCallbacksObj) return; - sCallbackEnv->CallVoidMethod(mScanCallbacksObj, method_onScannerRegistered, - status, scannerId, UUID_PARAMS(app_uuid)); + if (!sCallbackEnv.valid() || !mScanCallbacksObj) { + return; + } + sCallbackEnv->CallVoidMethod(mScanCallbacksObj, method_onScannerRegistered, status, scannerId, + UUID_PARAMS(app_uuid)); } -static void registerScannerNative(JNIEnv* /* env */, jobject /* object */, - jlong app_uuid_lsb, jlong app_uuid_msb) { - if (!sScanner) return; +static void registerScannerNative(JNIEnv* /* env */, jobject /* object */, jlong app_uuid_lsb, + jlong app_uuid_msb) { + if (!sScanner) { + return; + } Uuid uuid = from_java_uuid(app_uuid_msb, app_uuid_lsb); - sScanner->RegisterScanner(uuid, - base::Bind(&btgattc_register_scanner_cb, uuid)); + sScanner->RegisterScanner(uuid, base::Bind(&btgattc_register_scanner_cb, uuid)); } -static void unregisterScannerNative(JNIEnv* /* env */, jobject /* object */, - jint scanner_id) { - if (!sScanner) return; +static void unregisterScannerNative(JNIEnv* /* env */, jobject /* object */, jint scanner_id) { + if (!sScanner) { + return; + } sScanner->Unregister(scanner_id); } -static void gattClientScanNative(JNIEnv* /* env */, jobject /* object */, - jboolean start) { - if (!sScanner) return; +static void gattClientScanNative(JNIEnv* /* env */, jobject /* object */, jboolean start) { + if (!sScanner) { + return; + } sScanner->Scan(start); } -static void gattClientConnectNative(JNIEnv* env, jobject /* object */, - jint clientif, jstring address, - jint addressType, jboolean isDirect, - jint transport, jboolean opportunistic, - jint initiating_phys) { - if (!sGattIf) return; +static void gattClientConnectNative(JNIEnv* env, jobject /* object */, jint clientif, + jstring address, jint addressType, jboolean isDirect, + jint transport, jboolean opportunistic, jint initiating_phys) { + if (!sGattIf) { + return; + } - sGattIf->client->connect(clientif, str2addr(env, address), addressType, - isDirect, transport, opportunistic, initiating_phys); + sGattIf->client->connect(clientif, str2addr(env, address), addressType, isDirect, transport, + opportunistic, initiating_phys); } -static void gattClientDisconnectNative(JNIEnv* env, jobject /* object */, - jint clientIf, jstring address, - jint conn_id) { - if (!sGattIf) return; +static void gattClientDisconnectNative(JNIEnv* env, jobject /* object */, jint clientIf, + jstring address, jint conn_id) { + if (!sGattIf) { + return; + } sGattIf->client->disconnect(clientIf, str2addr(env, address), conn_id); } -static void gattClientSetPreferredPhyNative(JNIEnv* env, jobject /* object */, - jint /* clientIf */, - jstring address, jint tx_phy, - jint rx_phy, jint phy_options) { - if (!sGattIf) return; - sGattIf->client->set_preferred_phy(str2addr(env, address), tx_phy, rx_phy, - phy_options); +static void gattClientSetPreferredPhyNative(JNIEnv* env, jobject /* object */, jint /* clientIf */, + jstring address, jint tx_phy, jint rx_phy, + jint phy_options) { + if (!sGattIf) { + return; + } + sGattIf->client->set_preferred_phy(str2addr(env, address), tx_phy, rx_phy, phy_options); } -static void readClientPhyCb(uint8_t clientIf, RawAddress bda, uint8_t tx_phy, - uint8_t rx_phy, uint8_t status) { +static void readClientPhyCb(uint8_t clientIf, RawAddress bda, uint8_t tx_phy, uint8_t rx_phy, + uint8_t status) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } - ScopedLocalRef address(sCallbackEnv.get(), - bdaddr2newjstr(sCallbackEnv.get(), &bda)); + ScopedLocalRef address(sCallbackEnv.get(), bdaddr2newjstr(sCallbackEnv.get(), &bda)); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onClientPhyRead, clientIf, - address.get(), tx_phy, rx_phy, status); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onClientPhyRead, clientIf, address.get(), + tx_phy, rx_phy, status); } -static void gattClientReadPhyNative(JNIEnv* env, jobject /* object */, - jint clientIf, jstring address) { - if (!sGattIf) return; +static void gattClientReadPhyNative(JNIEnv* env, jobject /* object */, jint clientIf, + jstring address) { + if (!sGattIf) { + return; + } RawAddress bda = str2addr(env, address); sGattIf->client->read_phy(bda, base::Bind(&readClientPhyCb, clientIf, bda)); } -static void gattClientRefreshNative(JNIEnv* env, jobject /* object */, - jint clientIf, jstring address) { - if (!sGattIf) return; +static void gattClientRefreshNative(JNIEnv* env, jobject /* object */, jint clientIf, + jstring address) { + if (!sGattIf) { + return; + } sGattIf->client->refresh(clientIf, str2addr(env, address)); } -static void gattClientSearchServiceNative(JNIEnv* /* env */, - jobject /* object */, jint conn_id, - jboolean search_all, - jlong service_uuid_lsb, +static void gattClientSearchServiceNative(JNIEnv* /* env */, jobject /* object */, jint conn_id, + jboolean search_all, jlong service_uuid_lsb, jlong service_uuid_msb) { - if (!sGattIf) return; + if (!sGattIf) { + return; + } Uuid uuid = from_java_uuid(service_uuid_msb, service_uuid_lsb); sGattIf->client->search_service(conn_id, search_all ? 0 : &uuid); } -static void gattClientDiscoverServiceByUuidNative(JNIEnv* /* env */, - jobject /* object */, - jint conn_id, - jlong service_uuid_lsb, +static void gattClientDiscoverServiceByUuidNative(JNIEnv* /* env */, jobject /* object */, + jint conn_id, jlong service_uuid_lsb, jlong service_uuid_msb) { - if (!sGattIf) return; + if (!sGattIf) { + return; + } Uuid uuid = from_java_uuid(service_uuid_msb, service_uuid_lsb); sGattIf->client->btif_gattc_discover_service_by_uuid(conn_id, uuid); } -static void gattClientGetGattDbNative(JNIEnv* /* env */, jobject /* object */, - jint conn_id) { - if (!sGattIf) return; +static void gattClientGetGattDbNative(JNIEnv* /* env */, jobject /* object */, jint conn_id) { + if (!sGattIf) { + return; + } sGattIf->client->get_gatt_db(conn_id); } -static void gattClientReadCharacteristicNative(JNIEnv* /* env */, - jobject /* object */, - jint conn_id, jint handle, - jint authReq) { - if (!sGattIf) return; +static void gattClientReadCharacteristicNative(JNIEnv* /* env */, jobject /* object */, + jint conn_id, jint handle, jint authReq) { + if (!sGattIf) { + return; + } sGattIf->client->read_characteristic(conn_id, handle, authReq); } -static void gattClientReadUsingCharacteristicUuidNative( - JNIEnv* /* env */, jobject /* object */, jint conn_id, jlong uuid_lsb, - jlong uuid_msb, jint s_handle, jint e_handle, jint authReq) { - if (!sGattIf) return; +static void gattClientReadUsingCharacteristicUuidNative(JNIEnv* /* env */, jobject /* object */, + jint conn_id, jlong uuid_lsb, + jlong uuid_msb, jint s_handle, + jint e_handle, jint authReq) { + if (!sGattIf) { + return; + } Uuid uuid = from_java_uuid(uuid_msb, uuid_lsb); - sGattIf->client->read_using_characteristic_uuid(conn_id, uuid, s_handle, - e_handle, authReq); + sGattIf->client->read_using_characteristic_uuid(conn_id, uuid, s_handle, e_handle, authReq); } -static void gattClientReadDescriptorNative(JNIEnv* /* env */, - jobject /* object */, jint conn_id, +static void gattClientReadDescriptorNative(JNIEnv* /* env */, jobject /* object */, jint conn_id, jint handle, jint authReq) { - if (!sGattIf) return; + if (!sGattIf) { + return; + } sGattIf->client->read_descriptor(conn_id, handle, authReq); } -static void gattClientWriteCharacteristicNative(JNIEnv* env, - jobject /* object */, - jint conn_id, jint handle, - jint write_type, jint auth_req, +static void gattClientWriteCharacteristicNative(JNIEnv* env, jobject /* object */, jint conn_id, + jint handle, jint write_type, jint auth_req, jbyteArray value) { - if (!sGattIf) return; + if (!sGattIf) { + return; + } if (value == NULL) { log::warn("gattClientWriteCharacteristicNative() ignoring NULL array"); @@ -1493,26 +1516,29 @@ static void gattClientWriteCharacteristicNative(JNIEnv* env, uint16_t len = (uint16_t)env->GetArrayLength(value); jbyte* p_value = env->GetByteArrayElements(value, NULL); - if (p_value == NULL) return; + if (p_value == NULL) { + return; + } sGattIf->client->write_characteristic(conn_id, handle, write_type, auth_req, - reinterpret_cast(p_value), - len); + reinterpret_cast(p_value), len); env->ReleaseByteArrayElements(value, p_value, 0); } -static void gattClientExecuteWriteNative(JNIEnv* /* env */, - jobject /* object */, jint conn_id, +static void gattClientExecuteWriteNative(JNIEnv* /* env */, jobject /* object */, jint conn_id, jboolean execute) { - if (!sGattIf) return; + if (!sGattIf) { + return; + } sGattIf->client->execute_write(conn_id, execute ? 1 : 0); } -static void gattClientWriteDescriptorNative(JNIEnv* env, jobject /* object */, - jint conn_id, jint handle, - jint auth_req, jbyteArray value) { - if (!sGattIf) return; +static void gattClientWriteDescriptorNative(JNIEnv* env, jobject /* object */, jint conn_id, + jint handle, jint auth_req, jbyteArray value) { + if (!sGattIf) { + return; + } if (value == NULL) { log::warn("gattClientWriteDescriptorNative() ignoring NULL array"); @@ -1521,29 +1547,36 @@ static void gattClientWriteDescriptorNative(JNIEnv* env, jobject /* object */, uint16_t len = (uint16_t)env->GetArrayLength(value); jbyte* p_value = env->GetByteArrayElements(value, NULL); - if (p_value == NULL) return; + if (p_value == NULL) { + return; + } - sGattIf->client->write_descriptor(conn_id, handle, auth_req, - reinterpret_cast(p_value), len); + sGattIf->client->write_descriptor(conn_id, handle, auth_req, reinterpret_cast(p_value), + len); env->ReleaseByteArrayElements(value, p_value, 0); } -static void gattClientRegisterForNotificationsNative( - JNIEnv* env, jobject /* object */, jint clientIf, jstring address, - jint handle, jboolean enable) { - if (!sGattIf) return; +static void gattClientRegisterForNotificationsNative(JNIEnv* env, jobject /* object */, + jint clientIf, jstring address, jint handle, + jboolean enable) { + if (!sGattIf) { + return; + } RawAddress bd_addr = str2addr(env, address); - if (enable) + if (enable) { sGattIf->client->register_for_notification(clientIf, bd_addr, handle); - else + } else { sGattIf->client->deregister_for_notification(clientIf, bd_addr, handle); + } } -static void gattClientReadRemoteRssiNative(JNIEnv* env, jobject /* object */, - jint clientif, jstring address) { - if (!sGattIf) return; +static void gattClientReadRemoteRssiNative(JNIEnv* env, jobject /* object */, jint clientif, + jstring address) { + if (!sGattIf) { + return; + } sGattIf->client->read_remote_rssi(clientif, str2addr(env, address)); } @@ -1551,34 +1584,38 @@ static void gattClientReadRemoteRssiNative(JNIEnv* env, jobject /* object */, void set_scan_params_cmpl_cb(int client_if, uint8_t status) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mScanCallbacksObj) return; - sCallbackEnv->CallVoidMethod( - mScanCallbacksObj, method_onScanParamSetupCompleted, status, client_if); + if (!sCallbackEnv.valid() || !mScanCallbacksObj) { + return; + } + sCallbackEnv->CallVoidMethod(mScanCallbacksObj, method_onScanParamSetupCompleted, status, + client_if); } -static void gattSetScanParametersNative(JNIEnv* /* env */, jobject /* object */, - jint client_if, jint scan_interval_unit, - jint scan_window_unit, jint scan_phy) { - if (!sScanner) return; - sScanner->SetScanParameters(client_if, /* use active scan */ 0x01, - scan_interval_unit, scan_window_unit, scan_phy, +static void gattSetScanParametersNative(JNIEnv* /* env */, jobject /* object */, jint client_if, + jint scan_interval_unit, jint scan_window_unit, + jint scan_phy) { + if (!sScanner) { + return; + } + sScanner->SetScanParameters(client_if, /* use active scan */ 0x01, scan_interval_unit, + scan_window_unit, scan_phy, base::Bind(&set_scan_params_cmpl_cb, client_if)); } -void scan_filter_param_cb(uint8_t client_if, uint8_t avbl_space, uint8_t action, - uint8_t status) { +void scan_filter_param_cb(uint8_t client_if, uint8_t avbl_space, uint8_t action, uint8_t status) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mScanCallbacksObj) return; - sCallbackEnv->CallVoidMethod(mScanCallbacksObj, - method_onScanFilterParamsConfigured, action, + if (!sCallbackEnv.valid() || !mScanCallbacksObj) { + return; + } + sCallbackEnv->CallVoidMethod(mScanCallbacksObj, method_onScanFilterParamsConfigured, action, status, client_if, avbl_space); } -static void gattClientScanFilterParamAddNative(JNIEnv* env, - jobject /* object */, - jobject params) { - if (!sScanner) return; +static void gattClientScanFilterParamAddNative(JNIEnv* env, jobject /* object */, jobject params) { + if (!sScanner) { + return; + } const int add_scan_filter_params_action = 0; auto filt_params = std::make_unique(); @@ -1621,54 +1658,54 @@ static void gattClientScanFilterParamAddNative(JNIEnv* env, methodId = env->GetMethodID(filtparam.get(), "getRSSILowValue", "()I"); filt_params->rssi_low_thres = env->CallIntMethod(params, methodId); - sScanner->ScanFilterParamSetup(client_if, add_scan_filter_params_action, - filt_index, std::move(filt_params), + sScanner->ScanFilterParamSetup(client_if, add_scan_filter_params_action, filt_index, + std::move(filt_params), base::Bind(&scan_filter_param_cb, client_if)); } -static void gattClientScanFilterParamDeleteNative(JNIEnv* /* env */, - jobject /* object */, - jint client_if, - jint filt_index) { - if (!sScanner) return; +static void gattClientScanFilterParamDeleteNative(JNIEnv* /* env */, jobject /* object */, + jint client_if, jint filt_index) { + if (!sScanner) { + return; + } const int delete_scan_filter_params_action = 1; - sScanner->ScanFilterParamSetup(client_if, delete_scan_filter_params_action, - filt_index, nullptr, + sScanner->ScanFilterParamSetup(client_if, delete_scan_filter_params_action, filt_index, nullptr, base::Bind(&scan_filter_param_cb, client_if)); } -static void gattClientScanFilterParamClearAllNative(JNIEnv* /* env */, - jobject /* object */, +static void gattClientScanFilterParamClearAllNative(JNIEnv* /* env */, jobject /* object */, jint client_if) { - if (!sScanner) return; + if (!sScanner) { + return; + } const int clear_scan_filter_params_action = 2; - sScanner->ScanFilterParamSetup(client_if, clear_scan_filter_params_action, - 0 /* index, unused */, nullptr, - base::Bind(&scan_filter_param_cb, client_if)); + sScanner->ScanFilterParamSetup(client_if, clear_scan_filter_params_action, 0 /* index, unused */, + nullptr, base::Bind(&scan_filter_param_cb, client_if)); } -static void scan_filter_cfg_cb(uint8_t client_if, uint8_t filt_type, - uint8_t avbl_space, uint8_t action, - uint8_t status) { +static void scan_filter_cfg_cb(uint8_t client_if, uint8_t filt_type, uint8_t avbl_space, + uint8_t action, uint8_t status) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mScanCallbacksObj) return; - sCallbackEnv->CallVoidMethod(mScanCallbacksObj, method_onScanFilterConfig, - action, status, client_if, filt_type, - avbl_space); + if (!sCallbackEnv.valid() || !mScanCallbacksObj) { + return; + } + sCallbackEnv->CallVoidMethod(mScanCallbacksObj, method_onScanFilterConfig, action, status, + client_if, filt_type, avbl_space); } -static void gattClientScanFilterAddNative(JNIEnv* env, jobject /* object */, - jint client_if, jobjectArray filters, - jint filter_index) { - if (!sScanner) return; +static void gattClientScanFilterAddNative(JNIEnv* env, jobject /* object */, jint client_if, + jobjectArray filters, jint filter_index) { + if (!sScanner) { + return; + } jmethodID uuidGetMsb; jmethodID uuidGetLsb; const JNIJavaMethod javaMethods[] = { - {"getMostSignificantBits", "()J", &uuidGetMsb}, - {"getLeastSignificantBits", "()J", &uuidGetLsb}, + {"getMostSignificantBits", "()J", &uuidGetMsb}, + {"getLeastSignificantBits", "()J", &uuidGetLsb}, }; GET_JAVA_METHODS(env, "java/util/UUID", javaMethods); @@ -1681,17 +1718,14 @@ static void gattClientScanFilterAddNative(JNIEnv* env, jobject /* object */, return; } - jclass entryClazz = - env->GetObjectClass(env->GetObjectArrayElement(filters, 0)); + jclass entryClazz = env->GetObjectClass(env->GetObjectArrayElement(filters, 0)); jfieldID typeFid = env->GetFieldID(entryClazz, "type", "B"); - jfieldID addressFid = - env->GetFieldID(entryClazz, "address", "Ljava/lang/String;"); + jfieldID addressFid = env->GetFieldID(entryClazz, "address", "Ljava/lang/String;"); jfieldID addrTypeFid = env->GetFieldID(entryClazz, "addr_type", "B"); jfieldID irkTypeFid = env->GetFieldID(entryClazz, "irk", "[B"); jfieldID uuidFid = env->GetFieldID(entryClazz, "uuid", "Ljava/util/UUID;"); - jfieldID uuidMaskFid = - env->GetFieldID(entryClazz, "uuid_mask", "Ljava/util/UUID;"); + jfieldID uuidMaskFid = env->GetFieldID(entryClazz, "uuid_mask", "Ljava/util/UUID;"); jfieldID nameFid = env->GetFieldID(entryClazz, "name", "Ljava/lang/String;"); jfieldID companyFid = env->GetFieldID(entryClazz, "company", "I"); jfieldID companyMaskFid = env->GetFieldID(entryClazz, "company_mask", "I"); @@ -1707,13 +1741,11 @@ static void gattClientScanFilterAddNative(JNIEnv* env, jobject /* object */, for (int i = 0; i < numFilters; ++i) { ApcfCommand curr{}; - ScopedLocalRef current(env, - env->GetObjectArrayElement(filters, i)); + ScopedLocalRef current(env, env->GetObjectArrayElement(filters, i)); curr.type = env->GetByteField(current.get(), typeFid); - ScopedLocalRef address( - env, (jstring)env->GetObjectField(current.get(), addressFid)); + ScopedLocalRef address(env, (jstring)env->GetObjectField(current.get(), addressFid)); if (address.get() != NULL) { curr.address = str2addr(env, address.get()); } @@ -1721,7 +1753,7 @@ static void gattClientScanFilterAddNative(JNIEnv* env, jobject /* object */, curr.addr_type = env->GetByteField(current.get(), addrTypeFid); ScopedLocalRef irkByteArray( - env, (jbyteArray)env->GetObjectField(current.get(), irkTypeFid)); + env, (jbyteArray)env->GetObjectField(current.get(), irkTypeFid)); if (irkByteArray.get() != nullptr) { int len = env->GetArrayLength(irkByteArray.get()); @@ -1741,24 +1773,21 @@ static void gattClientScanFilterAddNative(JNIEnv* env, jobject /* object */, } } - ScopedLocalRef uuid(env, - env->GetObjectField(current.get(), uuidFid)); + ScopedLocalRef uuid(env, env->GetObjectField(current.get(), uuidFid)); if (uuid.get() != NULL) { jlong uuid_msb = env->CallLongMethod(uuid.get(), uuidGetMsb); jlong uuid_lsb = env->CallLongMethod(uuid.get(), uuidGetLsb); curr.uuid = from_java_uuid(uuid_msb, uuid_lsb); } - ScopedLocalRef uuid_mask( - env, env->GetObjectField(current.get(), uuidMaskFid)); + ScopedLocalRef uuid_mask(env, env->GetObjectField(current.get(), uuidMaskFid)); if (uuid.get() != NULL) { jlong uuid_msb = env->CallLongMethod(uuid_mask.get(), uuidGetMsb); jlong uuid_lsb = env->CallLongMethod(uuid_mask.get(), uuidGetLsb); curr.uuid_mask = from_java_uuid(uuid_msb, uuid_lsb); } - ScopedLocalRef name( - env, (jstring)env->GetObjectField(current.get(), nameFid)); + ScopedLocalRef name(env, (jstring)env->GetObjectField(current.get(), nameFid)); if (name.get() != NULL) { const char* c_name = env->GetStringUTFChars(name.get(), NULL); if (c_name != NULL && strlen(c_name) != 0) { @@ -1773,8 +1802,7 @@ static void gattClientScanFilterAddNative(JNIEnv* env, jobject /* object */, curr.ad_type = env->GetIntField(current.get(), adTypeFid); - ScopedLocalRef data( - env, (jbyteArray)env->GetObjectField(current.get(), dataFid)); + ScopedLocalRef data(env, (jbyteArray)env->GetObjectField(current.get(), dataFid)); if (data.get() != NULL) { jbyte* data_array = env->GetByteArrayElements(data.get(), 0); int data_len = env->GetArrayLength(data.get()); @@ -1785,13 +1813,12 @@ static void gattClientScanFilterAddNative(JNIEnv* env, jobject /* object */, } ScopedLocalRef data_mask( - env, (jbyteArray)env->GetObjectField(current.get(), dataMaskFid)); + env, (jbyteArray)env->GetObjectField(current.get(), dataMaskFid)); if (data_mask.get() != NULL) { jbyte* data_array = env->GetByteArrayElements(data_mask.get(), 0); int data_len = env->GetArrayLength(data_mask.get()); if (data_array && data_len) { - curr.data_mask = - std::vector(data_array, data_array + data_len); + curr.data_mask = std::vector(data_array, data_array + data_len); env->ReleaseByteArrayElements(data_mask.get(), data_array, JNI_ABORT); } } @@ -1801,13 +1828,12 @@ static void gattClientScanFilterAddNative(JNIEnv* env, jobject /* object */, curr.meta_data_type = env->GetIntField(current.get(), metaDataTypeFid); ScopedLocalRef meta_data( - env, (jbyteArray)env->GetObjectField(current.get(), metaDataFid)); + env, (jbyteArray)env->GetObjectField(current.get(), metaDataFid)); if (meta_data.get() != NULL) { jbyte* data_array = env->GetByteArrayElements(meta_data.get(), 0); int data_len = env->GetArrayLength(meta_data.get()); if (data_array && data_len) { - curr.meta_data = - std::vector(data_array, data_array + data_len); + curr.meta_data = std::vector(data_array, data_array + data_len); env->ReleaseByteArrayElements(meta_data.get(), data_array, JNI_ABORT); } } @@ -1819,110 +1845,117 @@ static void gattClientScanFilterAddNative(JNIEnv* env, jobject /* object */, base::Bind(&scan_filter_cfg_cb, client_if)); } -static void gattClientScanFilterClearNative(JNIEnv* /* env */, - jobject /* object */, - jint client_if, jint filt_index) { - if (!sScanner) return; - sScanner->ScanFilterClear(filt_index, - base::Bind(&scan_filter_cfg_cb, client_if)); +static void gattClientScanFilterClearNative(JNIEnv* /* env */, jobject /* object */, jint client_if, + jint filt_index) { + if (!sScanner) { + return; + } + sScanner->ScanFilterClear(filt_index, base::Bind(&scan_filter_cfg_cb, client_if)); } void scan_enable_cb(uint8_t client_if, uint8_t action, uint8_t status) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mScanCallbacksObj) return; - sCallbackEnv->CallVoidMethod(mScanCallbacksObj, - method_onScanFilterEnableDisabled, action, - status, client_if); + if (!sCallbackEnv.valid() || !mScanCallbacksObj) { + return; + } + sCallbackEnv->CallVoidMethod(mScanCallbacksObj, method_onScanFilterEnableDisabled, action, status, + client_if); } -static void gattClientScanFilterEnableNative(JNIEnv* /* env */, - jobject /* object */, +static void gattClientScanFilterEnableNative(JNIEnv* /* env */, jobject /* object */, jint client_if, jboolean enable) { - if (!sScanner) return; + if (!sScanner) { + return; + } sScanner->ScanFilterEnable(enable, base::Bind(&scan_enable_cb, client_if)); } -static void gattClientConfigureMTUNative(JNIEnv* /* env */, - jobject /* object */, jint conn_id, +static void gattClientConfigureMTUNative(JNIEnv* /* env */, jobject /* object */, jint conn_id, jint mtu) { - if (!sGattIf) return; + if (!sGattIf) { + return; + } sGattIf->client->configure_mtu(conn_id, mtu); } -static void gattConnectionParameterUpdateNative( - JNIEnv* env, jobject /* object */, jint /* client_if */, jstring address, - jint min_interval, jint max_interval, jint latency, jint timeout, - jint min_ce_len, jint max_ce_len) { - if (!sGattIf) return; - sGattIf->client->conn_parameter_update( - str2addr(env, address), min_interval, max_interval, latency, timeout, - (uint16_t)min_ce_len, (uint16_t)max_ce_len); +static void gattConnectionParameterUpdateNative(JNIEnv* env, jobject /* object */, + jint /* client_if */, jstring address, + jint min_interval, jint max_interval, jint latency, + jint timeout, jint min_ce_len, jint max_ce_len) { + if (!sGattIf) { + return; + } + sGattIf->client->conn_parameter_update(str2addr(env, address), min_interval, max_interval, + latency, timeout, (uint16_t)min_ce_len, + (uint16_t)max_ce_len); } -static void gattSubrateRequestNative(JNIEnv* env, jobject /* object */, - jint /* client_if */, jstring address, - jint subrate_min, jint subrate_max, - jint max_latency, jint cont_num, - jint sup_timeout) { - if (!sGattIf) return; - sGattIf->client->subrate_request(str2addr(env, address), subrate_min, - subrate_max, max_latency, cont_num, - sup_timeout); +static void gattSubrateRequestNative(JNIEnv* env, jobject /* object */, jint /* client_if */, + jstring address, jint subrate_min, jint subrate_max, + jint max_latency, jint cont_num, jint sup_timeout) { + if (!sGattIf) { + return; + } + sGattIf->client->subrate_request(str2addr(env, address), subrate_min, subrate_max, max_latency, + cont_num, sup_timeout); } void batchscan_cfg_storage_cb(uint8_t client_if, uint8_t status) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mScanCallbacksObj) return; - sCallbackEnv->CallVoidMethod(mScanCallbacksObj, - method_onBatchScanStorageConfigured, status, + if (!sCallbackEnv.valid() || !mScanCallbacksObj) { + return; + } + sCallbackEnv->CallVoidMethod(mScanCallbacksObj, method_onBatchScanStorageConfigured, status, client_if); } -static void gattClientConfigBatchScanStorageNative( - JNIEnv* /* env */, jobject /* object */, jint client_if, - jint max_full_reports_percent, jint max_trunc_reports_percent, - jint notify_threshold_level_percent) { - if (!sScanner) return; - sScanner->BatchscanConfigStorage( - client_if, max_full_reports_percent, max_trunc_reports_percent, - notify_threshold_level_percent, - base::Bind(&batchscan_cfg_storage_cb, client_if)); +static void gattClientConfigBatchScanStorageNative(JNIEnv* /* env */, jobject /* object */, + jint client_if, jint max_full_reports_percent, + jint max_trunc_reports_percent, + jint notify_threshold_level_percent) { + if (!sScanner) { + return; + } + sScanner->BatchscanConfigStorage(client_if, max_full_reports_percent, max_trunc_reports_percent, + notify_threshold_level_percent, + base::Bind(&batchscan_cfg_storage_cb, client_if)); } void batchscan_enable_cb(uint8_t client_if, uint8_t status) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mScanCallbacksObj) return; - sCallbackEnv->CallVoidMethod(mScanCallbacksObj, - method_onBatchScanStartStopped, 0 /* unused */, + if (!sCallbackEnv.valid() || !mScanCallbacksObj) { + return; + } + sCallbackEnv->CallVoidMethod(mScanCallbacksObj, method_onBatchScanStartStopped, 0 /* unused */, status, client_if); } -static void gattClientStartBatchScanNative(JNIEnv* /* env */, - jobject /* object */, jint client_if, - jint scan_mode, - jint scan_interval_unit, - jint scan_window_unit, - jint addr_type, jint discard_rule) { - if (!sScanner) return; - sScanner->BatchscanEnable(scan_mode, scan_interval_unit, scan_window_unit, - addr_type, discard_rule, - base::Bind(&batchscan_enable_cb, client_if)); +static void gattClientStartBatchScanNative(JNIEnv* /* env */, jobject /* object */, jint client_if, + jint scan_mode, jint scan_interval_unit, + jint scan_window_unit, jint addr_type, + jint discard_rule) { + if (!sScanner) { + return; + } + sScanner->BatchscanEnable(scan_mode, scan_interval_unit, scan_window_unit, addr_type, + discard_rule, base::Bind(&batchscan_enable_cb, client_if)); } -static void gattClientStopBatchScanNative(JNIEnv* /* env */, - jobject /* object */, - jint client_if) { - if (!sScanner) return; +static void gattClientStopBatchScanNative(JNIEnv* /* env */, jobject /* object */, jint client_if) { + if (!sScanner) { + return; + } sScanner->BatchscanDisable(base::Bind(&batchscan_enable_cb, client_if)); } -static void gattClientReadScanReportsNative(JNIEnv* /* env */, - jobject /* object */, - jint client_if, jint scan_type) { - if (!sScanner) return; +static void gattClientReadScanReportsNative(JNIEnv* /* env */, jobject /* object */, jint client_if, + jint scan_type) { + if (!sScanner) { + return; + } sScanner->BatchscanReadReports(client_if, scan_type); } @@ -1930,79 +1963,88 @@ static void gattClientReadScanReportsNative(JNIEnv* /* env */, * Native server functions */ -static void gattServerRegisterAppNative(JNIEnv* /* env */, jobject /* object */, - jlong app_uuid_lsb, jlong app_uuid_msb, - jboolean eatt_support) { - if (!sGattIf) return; +static void gattServerRegisterAppNative(JNIEnv* /* env */, jobject /* object */, jlong app_uuid_lsb, + jlong app_uuid_msb, jboolean eatt_support) { + if (!sGattIf) { + return; + } Uuid uuid = from_java_uuid(app_uuid_msb, app_uuid_lsb); sGattIf->server->register_server(uuid, eatt_support); } -static void gattServerUnregisterAppNative(JNIEnv* /* env */, - jobject /* object */, jint serverIf) { - if (!sGattIf) return; +static void gattServerUnregisterAppNative(JNIEnv* /* env */, jobject /* object */, jint serverIf) { + if (!sGattIf) { + return; + } bluetooth::gatt::close_server(serverIf); sGattIf->server->unregister_server(serverIf); } -static void gattServerConnectNative(JNIEnv* env, jobject /* object */, - jint server_if, jstring address, - jint addr_type, jboolean is_direct, +static void gattServerConnectNative(JNIEnv* env, jobject /* object */, jint server_if, + jstring address, jint addr_type, jboolean is_direct, jint transport) { - if (!sGattIf) return; + if (!sGattIf) { + return; + } RawAddress bd_addr = str2addr(env, address); sGattIf->server->connect(server_if, bd_addr, addr_type, is_direct, transport); } -static void gattServerDisconnectNative(JNIEnv* env, jobject /* object */, - jint serverIf, jstring address, - jint conn_id) { - if (!sGattIf) return; +static void gattServerDisconnectNative(JNIEnv* env, jobject /* object */, jint serverIf, + jstring address, jint conn_id) { + if (!sGattIf) { + return; + } sGattIf->server->disconnect(serverIf, str2addr(env, address), conn_id); } -static void gattServerSetPreferredPhyNative(JNIEnv* env, jobject /* object */, - jint /* serverIf */, - jstring address, jint tx_phy, - jint rx_phy, jint phy_options) { - if (!sGattIf) return; +static void gattServerSetPreferredPhyNative(JNIEnv* env, jobject /* object */, jint /* serverIf */, + jstring address, jint tx_phy, jint rx_phy, + jint phy_options) { + if (!sGattIf) { + return; + } RawAddress bda = str2addr(env, address); sGattIf->server->set_preferred_phy(bda, tx_phy, rx_phy, phy_options); } -static void readServerPhyCb(uint8_t serverIf, RawAddress bda, uint8_t tx_phy, - uint8_t rx_phy, uint8_t status) { +static void readServerPhyCb(uint8_t serverIf, RawAddress bda, uint8_t tx_phy, uint8_t rx_phy, + uint8_t status) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } - ScopedLocalRef address(sCallbackEnv.get(), - bdaddr2newjstr(sCallbackEnv.get(), &bda)); + ScopedLocalRef address(sCallbackEnv.get(), bdaddr2newjstr(sCallbackEnv.get(), &bda)); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onServerPhyRead, serverIf, - address.get(), tx_phy, rx_phy, status); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onServerPhyRead, serverIf, address.get(), + tx_phy, rx_phy, status); } -static void gattServerReadPhyNative(JNIEnv* env, jobject /* object */, - jint serverIf, jstring address) { - if (!sGattIf) return; +static void gattServerReadPhyNative(JNIEnv* env, jobject /* object */, jint serverIf, + jstring address) { + if (!sGattIf) { + return; + } RawAddress bda = str2addr(env, address); sGattIf->server->read_phy(bda, base::Bind(&readServerPhyCb, serverIf, bda)); } -static void gattServerAddServiceNative(JNIEnv* env, jobject /* object */, - jint server_if, +static void gattServerAddServiceNative(JNIEnv* env, jobject /* object */, jint server_if, jobject gatt_db_elements) { - if (!sGattIf) return; + if (!sGattIf) { + return; + } jmethodID arrayGet; jmethodID arraySize; const JNIJavaMethod javaListMethods[] = { - {"get", "(I)Ljava/lang/Object;", &arrayGet}, - {"size", "()I", &arraySize}, + {"get", "(I)Ljava/lang/Object;", &arrayGet}, + {"size", "()I", &arraySize}, }; GET_JAVA_METHODS(env, "java/util/List", javaListMethods); @@ -2013,21 +2055,19 @@ static void gattServerAddServiceNative(JNIEnv* env, jobject /* object */, jmethodID uuidGetLsb; const JNIJavaMethod javaUuidMethods[] = { - {"getMostSignificantBits", "()J", &uuidGetMsb}, - {"getLeastSignificantBits", "()J", &uuidGetLsb}, + {"getMostSignificantBits", "()J", &uuidGetMsb}, + {"getLeastSignificantBits", "()J", &uuidGetLsb}, }; GET_JAVA_METHODS(env, "java/util/UUID", javaUuidMethods); - jobject objectForClass = - env->CallObjectMethod(mCallbacksObj, method_getSampleGattDbElement); + jobject objectForClass = env->CallObjectMethod(mCallbacksObj, method_getSampleGattDbElement); jclass gattDbElementClazz = env->GetObjectClass(objectForClass); for (int i = 0; i < count; i++) { btgatt_db_element_t curr; jint index = i; - ScopedLocalRef element( - env, env->CallObjectMethod(gatt_db_elements, arrayGet, index)); + ScopedLocalRef element(env, env->CallObjectMethod(gatt_db_elements, arrayGet, index)); jfieldID fid; @@ -2043,8 +2083,7 @@ static void gattServerAddServiceNative(JNIEnv* env, jobject /* object */, } fid = env->GetFieldID(gattDbElementClazz, "type", "I"); - curr.type = - (bt_gatt_db_attribute_type_t)env->GetIntField(element.get(), fid); + curr.type = (bt_gatt_db_attribute_type_t)env->GetIntField(element.get(), fid); fid = env->GetFieldID(gattDbElementClazz, "attributeHandle", "I"); curr.attribute_handle = env->GetIntField(element.get(), fid); @@ -2067,23 +2106,27 @@ static void gattServerAddServiceNative(JNIEnv* env, jobject /* object */, sGattIf->server->add_service(server_if, db.data(), db.size()); } -static void gattServerStopServiceNative(JNIEnv* /* env */, jobject /* object */, - jint server_if, jint svc_handle) { - if (!sGattIf) return; +static void gattServerStopServiceNative(JNIEnv* /* env */, jobject /* object */, jint server_if, + jint svc_handle) { + if (!sGattIf) { + return; + } sGattIf->server->stop_service(server_if, svc_handle); } -static void gattServerDeleteServiceNative(JNIEnv* /* env */, - jobject /* object */, jint server_if, +static void gattServerDeleteServiceNative(JNIEnv* /* env */, jobject /* object */, jint server_if, jint svc_handle) { - if (!sGattIf) return; + if (!sGattIf) { + return; + } sGattIf->server->delete_service(server_if, svc_handle); } -static void gattServerSendIndicationNative(JNIEnv* env, jobject /* object */, - jint server_if, jint attr_handle, - jint conn_id, jbyteArray val) { - if (!sGattIf) return; +static void gattServerSendIndicationNative(JNIEnv* env, jobject /* object */, jint server_if, + jint attr_handle, jint conn_id, jbyteArray val) { + if (!sGattIf) { + return; + } jbyte* array = env->GetByteArrayElements(val, 0); int val_len = env->GetArrayLength(val); @@ -2099,10 +2142,11 @@ static void gattServerSendIndicationNative(JNIEnv* env, jobject /* object */, env->ReleaseByteArrayElements(val, array, JNI_ABORT); } -static void gattServerSendNotificationNative(JNIEnv* env, jobject /* object */, - jint server_if, jint attr_handle, - jint conn_id, jbyteArray val) { - if (!sGattIf) return; +static void gattServerSendNotificationNative(JNIEnv* env, jobject /* object */, jint server_if, + jint attr_handle, jint conn_id, jbyteArray val) { + if (!sGattIf) { + return; + } jbyte* array = env->GetByteArrayElements(val, 0); int val_len = env->GetArrayLength(val); @@ -2113,12 +2157,12 @@ static void gattServerSendNotificationNative(JNIEnv* env, jobject /* object */, env->ReleaseByteArrayElements(val, array, JNI_ABORT); } -static void gattServerSendResponseNative(JNIEnv* env, jobject /* object */, - jint server_if, jint conn_id, - jint trans_id, jint status, - jint handle, jint offset, - jbyteArray val, jint auth_req) { - if (!sGattIf) return; +static void gattServerSendResponseNative(JNIEnv* env, jobject /* object */, jint server_if, + jint conn_id, jint trans_id, jint status, jint handle, + jint offset, jbyteArray val, jint auth_req) { + if (!sGattIf) { + return; + } btgatt_response_t response; @@ -2136,14 +2180,14 @@ static void gattServerSendResponseNative(JNIEnv* env, jobject /* object */, jbyte* array = env->GetByteArrayElements(val, 0); - for (int i = 0; i != response.attr_value.len; ++i) + for (int i = 0; i != response.attr_value.len; ++i) { response.attr_value.value[i] = (uint8_t)array[i]; + } env->ReleaseByteArrayElements(val, array, JNI_ABORT); } if (bluetooth::gatt::is_connection_isolated(conn_id)) { - auto data = ::rust::Slice(response.attr_value.value, - response.attr_value.len); + auto data = ::rust::Slice(response.attr_value.value, response.attr_value.len); bluetooth::gatt::send_response(server_if, conn_id, trans_id, status, data); } else { sGattIf->server->send_response(conn_id, trans_id, status, response); @@ -2203,12 +2247,24 @@ static AdvertiseParameters parseParams(JNIEnv* env, jobject i) { int8_t ownAddressType = env->CallIntMethod(i, methodId); uint16_t props = 0; - if (isConnectable) props |= 0x01; - if (isScannable) props |= 0x02; - if (isDiscoverable) props |= 0x04; - if (isLegacy) props |= 0x10; - if (isAnonymous) props |= 0x20; - if (includeTxPower) props |= 0x40; + if (isConnectable) { + props |= 0x01; + } + if (isScannable) { + props |= 0x02; + } + if (isDiscoverable) { + props |= 0x04; + } + if (isLegacy) { + props |= 0x10; + } + if (isAnonymous) { + props |= 0x20; + } + if (includeTxPower) { + props |= 0x40; + } if (interval > INTERVAL_MAX - INTERVAL_DELTA) { interval = INTERVAL_MAX - INTERVAL_DELTA; @@ -2226,8 +2282,7 @@ static AdvertiseParameters parseParams(JNIEnv* env, jobject i) { return p; } -static PeriodicAdvertisingParameters parsePeriodicParams(JNIEnv* env, - jobject i) { +static PeriodicAdvertisingParameters parsePeriodicParams(JNIEnv* env, jobject i) { PeriodicAdvertisingParameters p; if (i == NULL) { @@ -2248,54 +2303,56 @@ static PeriodicAdvertisingParameters parsePeriodicParams(JNIEnv* env, p.min_interval = interval; p.max_interval = interval + 16; /* 20ms difference betwen min and max */ uint16_t props = 0; - if (includeTxPower) props |= 0x40; + if (includeTxPower) { + props |= 0x40; + } p.periodic_advertising_properties = props; return p; } -static void ble_advertising_set_started_cb(int reg_id, int server_if, - uint8_t advertiser_id, +static void ble_advertising_set_started_cb(int reg_id, int server_if, uint8_t advertiser_id, int8_t tx_power, uint8_t status) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mAdvertiseCallbacksObj) return; + if (!sCallbackEnv.valid() || !mAdvertiseCallbacksObj) { + return; + } // tie advertiser ID to server_if, once the advertisement has started - if (status == 0 /* AdvertisingCallback::AdvertisingStatus::SUCCESS */ && - server_if != 0) { + if (status == 0 /* AdvertisingCallback::AdvertisingStatus::SUCCESS */ && server_if != 0) { bluetooth::gatt::associate_server_with_advertiser(server_if, advertiser_id); } - sCallbackEnv->CallVoidMethod(mAdvertiseCallbacksObj, - method_onAdvertisingSetStarted, reg_id, + sCallbackEnv->CallVoidMethod(mAdvertiseCallbacksObj, method_onAdvertisingSetStarted, reg_id, advertiser_id, tx_power, status); } -static void ble_advertising_set_timeout_cb(uint8_t advertiser_id, - uint8_t status) { +static void ble_advertising_set_timeout_cb(uint8_t advertiser_id, uint8_t status) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mAdvertiseCallbacksObj) return; - sCallbackEnv->CallVoidMethod(mAdvertiseCallbacksObj, - method_onAdvertisingEnabled, advertiser_id, + if (!sCallbackEnv.valid() || !mAdvertiseCallbacksObj) { + return; + } + sCallbackEnv->CallVoidMethod(mAdvertiseCallbacksObj, method_onAdvertisingEnabled, advertiser_id, false, status); } -static void startAdvertisingSetNative( - JNIEnv* env, jobject /* object */, jobject parameters, jbyteArray adv_data, - jbyteArray scan_resp, jobject periodic_parameters, jbyteArray periodic_data, - jint duration, jint maxExtAdvEvents, jint reg_id, jint server_if) { - if (!sGattIf) return; +static void startAdvertisingSetNative(JNIEnv* env, jobject /* object */, jobject parameters, + jbyteArray adv_data, jbyteArray scan_resp, + jobject periodic_parameters, jbyteArray periodic_data, + jint duration, jint maxExtAdvEvents, jint reg_id, + jint server_if) { + if (!sGattIf) { + return; + } jbyte* scan_resp_data = env->GetByteArrayElements(scan_resp, NULL); uint16_t scan_resp_len = (uint16_t)env->GetArrayLength(scan_resp); - std::vector scan_resp_vec(scan_resp_data, - scan_resp_data + scan_resp_len); + std::vector scan_resp_vec(scan_resp_data, scan_resp_data + scan_resp_len); env->ReleaseByteArrayElements(scan_resp, scan_resp_data, JNI_ABORT); AdvertiseParameters params = parseParams(env, parameters); - PeriodicAdvertisingParameters periodicParams = - parsePeriodicParams(env, periodic_parameters); + PeriodicAdvertisingParameters periodicParams = parsePeriodicParams(env, periodic_parameters); jbyte* adv_data_data = env->GetByteArrayElements(adv_data, NULL); uint16_t adv_data_len = (uint16_t)env->GetArrayLength(adv_data); @@ -2304,157 +2361,164 @@ static void startAdvertisingSetNative( jbyte* periodic_data_data = env->GetByteArrayElements(periodic_data, NULL); uint16_t periodic_data_len = (uint16_t)env->GetArrayLength(periodic_data); - std::vector periodic_data_vec( - periodic_data_data, periodic_data_data + periodic_data_len); + std::vector periodic_data_vec(periodic_data_data, + periodic_data_data + periodic_data_len); env->ReleaseByteArrayElements(periodic_data, periodic_data_data, JNI_ABORT); sGattIf->advertiser->StartAdvertisingSet( - kAdvertiserClientIdJni, reg_id, - base::Bind(&ble_advertising_set_started_cb, reg_id, server_if), params, - data_vec, scan_resp_vec, periodicParams, periodic_data_vec, duration, - maxExtAdvEvents, base::Bind(ble_advertising_set_timeout_cb)); + kAdvertiserClientIdJni, reg_id, + base::Bind(&ble_advertising_set_started_cb, reg_id, server_if), params, data_vec, + scan_resp_vec, periodicParams, periodic_data_vec, duration, maxExtAdvEvents, + base::Bind(ble_advertising_set_timeout_cb)); } -static void stopAdvertisingSetNative(JNIEnv* /* env */, jobject /* object */, - jint advertiser_id) { - if (!sGattIf) return; +static void stopAdvertisingSetNative(JNIEnv* /* env */, jobject /* object */, jint advertiser_id) { + if (!sGattIf) { + return; + } bluetooth::gatt::clear_advertiser(advertiser_id); sGattIf->advertiser->Unregister(advertiser_id); } -static void getOwnAddressCb(uint8_t advertiser_id, uint8_t address_type, - RawAddress address) { +static void getOwnAddressCb(uint8_t advertiser_id, uint8_t address_type, RawAddress address) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mAdvertiseCallbacksObj) return; + if (!sCallbackEnv.valid() || !mAdvertiseCallbacksObj) { + return; + } - ScopedLocalRef addr(sCallbackEnv.get(), - bdaddr2newjstr(sCallbackEnv.get(), &address)); - sCallbackEnv->CallVoidMethod(mAdvertiseCallbacksObj, method_onOwnAddressRead, - advertiser_id, address_type, addr.get()); + ScopedLocalRef addr(sCallbackEnv.get(), bdaddr2newjstr(sCallbackEnv.get(), &address)); + sCallbackEnv->CallVoidMethod(mAdvertiseCallbacksObj, method_onOwnAddressRead, advertiser_id, + address_type, addr.get()); } -static void getOwnAddressNative(JNIEnv* /* env */, jobject /* object */, - jint advertiser_id) { - if (!sGattIf) return; - sGattIf->advertiser->GetOwnAddress( - advertiser_id, base::Bind(&getOwnAddressCb, advertiser_id)); +static void getOwnAddressNative(JNIEnv* /* env */, jobject /* object */, jint advertiser_id) { + if (!sGattIf) { + return; + } + sGattIf->advertiser->GetOwnAddress(advertiser_id, base::Bind(&getOwnAddressCb, advertiser_id)); } -static void callJniCallback(jmethodID method, uint8_t advertiser_id, - uint8_t status) { +static void callJniCallback(jmethodID method, uint8_t advertiser_id, uint8_t status) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mAdvertiseCallbacksObj) return; - sCallbackEnv->CallVoidMethod(mAdvertiseCallbacksObj, method, advertiser_id, - status); + if (!sCallbackEnv.valid() || !mAdvertiseCallbacksObj) { + return; + } + sCallbackEnv->CallVoidMethod(mAdvertiseCallbacksObj, method, advertiser_id, status); } static void enableSetCb(uint8_t advertiser_id, bool enable, uint8_t status) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mAdvertiseCallbacksObj) return; - sCallbackEnv->CallVoidMethod(mAdvertiseCallbacksObj, - method_onAdvertisingEnabled, advertiser_id, + if (!sCallbackEnv.valid() || !mAdvertiseCallbacksObj) { + return; + } + sCallbackEnv->CallVoidMethod(mAdvertiseCallbacksObj, method_onAdvertisingEnabled, advertiser_id, enable, status); } -static void enableAdvertisingSetNative(JNIEnv* /* env */, jobject /* object */, - jint advertiser_id, jboolean enable, - jint duration, jint maxExtAdvEvents) { - if (!sGattIf) return; +static void enableAdvertisingSetNative(JNIEnv* /* env */, jobject /* object */, jint advertiser_id, + jboolean enable, jint duration, jint maxExtAdvEvents) { + if (!sGattIf) { + return; + } sGattIf->advertiser->Enable(advertiser_id, enable, - base::Bind(&enableSetCb, advertiser_id, enable), - duration, maxExtAdvEvents, - base::Bind(&enableSetCb, advertiser_id, false)); + base::Bind(&enableSetCb, advertiser_id, enable), duration, + maxExtAdvEvents, base::Bind(&enableSetCb, advertiser_id, false)); } -static void setAdvertisingDataNative(JNIEnv* env, jobject /* object */, - jint advertiser_id, jbyteArray data) { - if (!sGattIf) return; +static void setAdvertisingDataNative(JNIEnv* env, jobject /* object */, jint advertiser_id, + jbyteArray data) { + if (!sGattIf) { + return; + } sGattIf->advertiser->SetData( - advertiser_id, false, toVector(env, data), - base::Bind(&callJniCallback, method_onAdvertisingDataSet, advertiser_id)); + advertiser_id, false, toVector(env, data), + base::Bind(&callJniCallback, method_onAdvertisingDataSet, advertiser_id)); } -static void setScanResponseDataNative(JNIEnv* env, jobject /* object */, - jint advertiser_id, jbyteArray data) { - if (!sGattIf) return; +static void setScanResponseDataNative(JNIEnv* env, jobject /* object */, jint advertiser_id, + jbyteArray data) { + if (!sGattIf) { + return; + } sGattIf->advertiser->SetData( - advertiser_id, true, toVector(env, data), - base::Bind(&callJniCallback, method_onScanResponseDataSet, - advertiser_id)); + advertiser_id, true, toVector(env, data), + base::Bind(&callJniCallback, method_onScanResponseDataSet, advertiser_id)); } -static void setAdvertisingParametersNativeCb(uint8_t advertiser_id, - uint8_t status, int8_t tx_power) { +static void setAdvertisingParametersNativeCb(uint8_t advertiser_id, uint8_t status, + int8_t tx_power) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mAdvertiseCallbacksObj) return; - sCallbackEnv->CallVoidMethod(mAdvertiseCallbacksObj, - method_onAdvertisingParametersUpdated, + if (!sCallbackEnv.valid() || !mAdvertiseCallbacksObj) { + return; + } + sCallbackEnv->CallVoidMethod(mAdvertiseCallbacksObj, method_onAdvertisingParametersUpdated, advertiser_id, tx_power, status); } -static void setAdvertisingParametersNative(JNIEnv* env, jobject /* object */, - jint advertiser_id, +static void setAdvertisingParametersNative(JNIEnv* env, jobject /* object */, jint advertiser_id, jobject parameters) { - if (!sGattIf) return; + if (!sGattIf) { + return; + } AdvertiseParameters params = parseParams(env, parameters); - sGattIf->advertiser->SetParameters( - advertiser_id, params, - base::Bind(&setAdvertisingParametersNativeCb, advertiser_id)); + sGattIf->advertiser->SetParameters(advertiser_id, params, + base::Bind(&setAdvertisingParametersNativeCb, advertiser_id)); } -static void setPeriodicAdvertisingParametersNative( - JNIEnv* env, jobject /* object */, jint advertiser_id, - jobject periodic_parameters) { - if (!sGattIf) return; +static void setPeriodicAdvertisingParametersNative(JNIEnv* env, jobject /* object */, + jint advertiser_id, + jobject periodic_parameters) { + if (!sGattIf) { + return; + } - PeriodicAdvertisingParameters periodicParams = - parsePeriodicParams(env, periodic_parameters); + PeriodicAdvertisingParameters periodicParams = parsePeriodicParams(env, periodic_parameters); sGattIf->advertiser->SetPeriodicAdvertisingParameters( - advertiser_id, periodicParams, - base::Bind(&callJniCallback, - method_onPeriodicAdvertisingParametersUpdated, advertiser_id)); + advertiser_id, periodicParams, + base::Bind(&callJniCallback, method_onPeriodicAdvertisingParametersUpdated, + advertiser_id)); } -static void setPeriodicAdvertisingDataNative(JNIEnv* env, jobject /* object */, - jint advertiser_id, +static void setPeriodicAdvertisingDataNative(JNIEnv* env, jobject /* object */, jint advertiser_id, jbyteArray data) { - if (!sGattIf) return; + if (!sGattIf) { + return; + } sGattIf->advertiser->SetPeriodicAdvertisingData( - advertiser_id, toVector(env, data), - base::Bind(&callJniCallback, method_onPeriodicAdvertisingDataSet, - advertiser_id)); + advertiser_id, toVector(env, data), + base::Bind(&callJniCallback, method_onPeriodicAdvertisingDataSet, advertiser_id)); } -static void enablePeriodicSetCb(uint8_t advertiser_id, bool enable, - uint8_t status) { +static void enablePeriodicSetCb(uint8_t advertiser_id, bool enable, uint8_t status) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mAdvertiseCallbacksObj) return; - sCallbackEnv->CallVoidMethod(mAdvertiseCallbacksObj, - method_onPeriodicAdvertisingEnabled, + if (!sCallbackEnv.valid() || !mAdvertiseCallbacksObj) { + return; + } + sCallbackEnv->CallVoidMethod(mAdvertiseCallbacksObj, method_onPeriodicAdvertisingEnabled, advertiser_id, enable, status); } -static void setPeriodicAdvertisingEnableNative(JNIEnv* /* env */, - jobject /* object */, - jint advertiser_id, - jboolean enable) { - if (!sGattIf) return; +static void setPeriodicAdvertisingEnableNative(JNIEnv* /* env */, jobject /* object */, + jint advertiser_id, jboolean enable) { + if (!sGattIf) { + return; + } sGattIf->advertiser->SetPeriodicAdvertisingEnable( - advertiser_id, enable, true /*include_adi*/, - base::Bind(&enablePeriodicSetCb, advertiser_id, enable)); + advertiser_id, enable, true /*include_adi*/, + base::Bind(&enablePeriodicSetCb, advertiser_id, enable)); } static void periodicScanInitializeNative(JNIEnv* env, jobject object) { @@ -2502,45 +2566,50 @@ static void scanCleanupNative(JNIEnv* env, jobject /* object */) { } } -static void startSyncNative(JNIEnv* env, jobject /* object */, jint sid, - jstring address, jint skip, jint timeout, - jint reg_id) { - if (!sScanner) return; +static void startSyncNative(JNIEnv* env, jobject /* object */, jint sid, jstring address, jint skip, + jint timeout, jint reg_id) { + if (!sScanner) { + return; + } sScanner->StartSync(sid, str2addr(env, address), skip, timeout, reg_id); } -static void stopSyncNative(JNIEnv* /* env */, jobject /* object */, - jint sync_handle) { - if (!sScanner) return; +static void stopSyncNative(JNIEnv* /* env */, jobject /* object */, jint sync_handle) { + if (!sScanner) { + return; + } sScanner->StopSync(sync_handle); } -static void cancelSyncNative(JNIEnv* env, jobject /* object */, jint sid, - jstring address) { - if (!sScanner) return; +static void cancelSyncNative(JNIEnv* env, jobject /* object */, jint sid, jstring address) { + if (!sScanner) { + return; + } sScanner->CancelCreateSync(sid, str2addr(env, address)); } -static void syncTransferNative(JNIEnv* env, jobject /* object */, - jint pa_source, jstring addr, jint service_data, - jint sync_handle) { - if (!sScanner) return; - sScanner->TransferSync(str2addr(env, addr), service_data, sync_handle, - pa_source); +static void syncTransferNative(JNIEnv* env, jobject /* object */, jint pa_source, jstring addr, + jint service_data, jint sync_handle) { + if (!sScanner) { + return; + } + sScanner->TransferSync(str2addr(env, addr), service_data, sync_handle, pa_source); } -static void transferSetInfoNative(JNIEnv* env, jobject /* object */, - jint pa_source, jstring addr, +static void transferSetInfoNative(JNIEnv* env, jobject /* object */, jint pa_source, jstring addr, jint service_data, jint adv_handle) { - if (!sScanner) return; - sScanner->TransferSetInfo(str2addr(env, addr), service_data, adv_handle, - pa_source); + if (!sScanner) { + return; + } + sScanner->TransferSetInfo(str2addr(env, addr), service_data, adv_handle, pa_source); } -static void gattTestNative(JNIEnv* env, jobject /* object */, jint command, - jlong uuid1_lsb, jlong uuid1_msb, jstring bda1, - jint p1, jint p2, jint p3, jint p4, jint p5) { - if (!sGattIf) return; +static void gattTestNative(JNIEnv* env, jobject /* object */, jint command, jlong uuid1_lsb, + jlong uuid1_msb, jstring bda1, jint p1, jint p2, jint p3, jint p4, + jint p5) { + if (!sGattIf) { + return; + } RawAddress bt_bda1 = str2addr(env, bda1); @@ -2568,8 +2637,7 @@ static void distanceMeasurementInitializeNative(JNIEnv* env, jobject object) { mDistanceMeasurementCallbacksObj = env->NewGlobalRef(object); } -static void distanceMeasurementCleanupNative(JNIEnv* env, - jobject /* object */) { +static void distanceMeasurementCleanupNative(JNIEnv* env, jobject /* object */) { std::unique_lock lock(callbacks_mutex); if (mDistanceMeasurementCallbacksObj != NULL) { env->DeleteGlobalRef(mDistanceMeasurementCallbacksObj); @@ -2577,19 +2645,21 @@ static void distanceMeasurementCleanupNative(JNIEnv* env, } } -static void startDistanceMeasurementNative(JNIEnv* env, jobject /* object */, - jstring address, jint interval, - jint method) { - if (!sGattIf) return; - sGattIf->distance_measurement_manager->StartDistanceMeasurement( - str2addr(env, address), interval, method); +static void startDistanceMeasurementNative(JNIEnv* env, jobject /* object */, jstring address, + jint interval, jint method) { + if (!sGattIf) { + return; + } + sGattIf->distance_measurement_manager->StartDistanceMeasurement(str2addr(env, address), interval, + method); } -static void stopDistanceMeasurementNative(JNIEnv* env, jobject /* object */, - jstring address, jint method) { - if (!sGattIf) return; - sGattIf->distance_measurement_manager->StopDistanceMeasurement( - str2addr(env, address), method); +static void stopDistanceMeasurementNative(JNIEnv* env, jobject /* object */, jstring address, + jint method) { + if (!sGattIf) { + return; + } + sGattIf->distance_measurement_manager->StopDistanceMeasurement(str2addr(env, address), method); } /** @@ -2599,342 +2669,287 @@ static void stopDistanceMeasurementNative(JNIEnv* env, jobject /* object */, // JNI functions defined in ScanNativeInterface class. static int register_com_android_bluetooth_gatt_scan(JNIEnv* env) { const JNINativeMethod methods[] = { - {"initializeNative", "()V", (void*)scanInitializeNative}, - {"cleanupNative", "()V", (void*)scanCleanupNative}, - {"registerScannerNative", "(JJ)V", (void*)registerScannerNative}, - {"unregisterScannerNative", "(I)V", (void*)unregisterScannerNative}, - {"gattClientScanNative", "(Z)V", (void*)gattClientScanNative}, - // Batch scan JNI functions. - {"gattClientConfigBatchScanStorageNative", "(IIII)V", - (void*)gattClientConfigBatchScanStorageNative}, - {"gattClientStartBatchScanNative", "(IIIIII)V", - (void*)gattClientStartBatchScanNative}, - {"gattClientStopBatchScanNative", "(I)V", - (void*)gattClientStopBatchScanNative}, - {"gattClientReadScanReportsNative", "(II)V", - (void*)gattClientReadScanReportsNative}, - // Scan filter JNI functions. - {"gattClientScanFilterParamAddNative", - "(Lcom/android/bluetooth/gatt/FilterParams;)V", - (void*)gattClientScanFilterParamAddNative}, - {"gattClientScanFilterParamDeleteNative", "(II)V", - (void*)gattClientScanFilterParamDeleteNative}, - {"gattClientScanFilterParamClearAllNative", "(I)V", - (void*)gattClientScanFilterParamClearAllNative}, - {"gattClientScanFilterAddNative", - "(I[Lcom/android/bluetooth/le_scan/ScanFilterQueue$Entry;I)V", - (void*)gattClientScanFilterAddNative}, - {"gattClientScanFilterClearNative", "(II)V", - (void*)gattClientScanFilterClearNative}, - {"gattClientScanFilterEnableNative", "(IZ)V", - (void*)gattClientScanFilterEnableNative}, - {"gattSetScanParametersNative", "(IIII)V", - (void*)gattSetScanParametersNative}, + {"initializeNative", "()V", (void*)scanInitializeNative}, + {"cleanupNative", "()V", (void*)scanCleanupNative}, + {"registerScannerNative", "(JJ)V", (void*)registerScannerNative}, + {"unregisterScannerNative", "(I)V", (void*)unregisterScannerNative}, + {"gattClientScanNative", "(Z)V", (void*)gattClientScanNative}, + // Batch scan JNI functions. + {"gattClientConfigBatchScanStorageNative", "(IIII)V", + (void*)gattClientConfigBatchScanStorageNative}, + {"gattClientStartBatchScanNative", "(IIIIII)V", (void*)gattClientStartBatchScanNative}, + {"gattClientStopBatchScanNative", "(I)V", (void*)gattClientStopBatchScanNative}, + {"gattClientReadScanReportsNative", "(II)V", (void*)gattClientReadScanReportsNative}, + // Scan filter JNI functions. + {"gattClientScanFilterParamAddNative", "(Lcom/android/bluetooth/gatt/FilterParams;)V", + (void*)gattClientScanFilterParamAddNative}, + {"gattClientScanFilterParamDeleteNative", "(II)V", + (void*)gattClientScanFilterParamDeleteNative}, + {"gattClientScanFilterParamClearAllNative", "(I)V", + (void*)gattClientScanFilterParamClearAllNative}, + {"gattClientScanFilterAddNative", + "(I[Lcom/android/bluetooth/le_scan/ScanFilterQueue$Entry;I)V", + (void*)gattClientScanFilterAddNative}, + {"gattClientScanFilterClearNative", "(II)V", (void*)gattClientScanFilterClearNative}, + {"gattClientScanFilterEnableNative", "(IZ)V", (void*)gattClientScanFilterEnableNative}, + {"gattSetScanParametersNative", "(IIII)V", (void*)gattSetScanParametersNative}, }; const int result = REGISTER_NATIVE_METHODS( - env, "com/android/bluetooth/le_scan/ScanNativeInterface", methods); + env, "com/android/bluetooth/le_scan/ScanNativeInterface", methods); if (result != 0) { return result; } const JNIJavaMethod javaMethods[] = { - // Client callbacks - {"onScannerRegistered", "(IIJJ)V", &method_onScannerRegistered}, - {"onScanResult", "(IILjava/lang/String;IIIIII[BLjava/lang/String;)V", - &method_onScanResult}, - {"onScanFilterConfig", "(IIIII)V", &method_onScanFilterConfig}, - {"onScanFilterParamsConfigured", "(IIII)V", - &method_onScanFilterParamsConfigured}, - {"onScanFilterEnableDisabled", "(III)V", - &method_onScanFilterEnableDisabled}, - {"onBatchScanStorageConfigured", "(II)V", - &method_onBatchScanStorageConfigured}, - {"onBatchScanStartStopped", "(III)V", &method_onBatchScanStartStopped}, - {"onBatchScanReports", "(IIII[B)V", &method_onBatchScanReports}, - {"onBatchScanThresholdCrossed", "(I)V", - &method_onBatchScanThresholdCrossed}, - {"createOnTrackAdvFoundLostObject", - "(II[BI[BIIILjava/lang/String;IIII)" - "Lcom/android/bluetooth/le_scan/AdvtFilterOnFoundOnLostInfo;", - &method_createOnTrackAdvFoundLostObject}, - {"onTrackAdvFoundLost", - "(Lcom/android/bluetooth/le_scan/AdvtFilterOnFoundOnLostInfo;)V", - &method_onTrackAdvFoundLost}, - {"onScanParamSetupCompleted", "(II)V", &method_onScanParamSetupCompleted}, + // Client callbacks + {"onScannerRegistered", "(IIJJ)V", &method_onScannerRegistered}, + {"onScanResult", "(IILjava/lang/String;IIIIII[BLjava/lang/String;)V", + &method_onScanResult}, + {"onScanFilterConfig", "(IIIII)V", &method_onScanFilterConfig}, + {"onScanFilterParamsConfigured", "(IIII)V", &method_onScanFilterParamsConfigured}, + {"onScanFilterEnableDisabled", "(III)V", &method_onScanFilterEnableDisabled}, + {"onBatchScanStorageConfigured", "(II)V", &method_onBatchScanStorageConfigured}, + {"onBatchScanStartStopped", "(III)V", &method_onBatchScanStartStopped}, + {"onBatchScanReports", "(IIII[B)V", &method_onBatchScanReports}, + {"onBatchScanThresholdCrossed", "(I)V", &method_onBatchScanThresholdCrossed}, + {"createOnTrackAdvFoundLostObject", + "(II[BI[BIIILjava/lang/String;IIII)" + "Lcom/android/bluetooth/le_scan/AdvtFilterOnFoundOnLostInfo;", + &method_createOnTrackAdvFoundLostObject}, + {"onTrackAdvFoundLost", "(Lcom/android/bluetooth/le_scan/AdvtFilterOnFoundOnLostInfo;)V", + &method_onTrackAdvFoundLost}, + {"onScanParamSetupCompleted", "(II)V", &method_onScanParamSetupCompleted}, }; - GET_JAVA_METHODS(env, "com/android/bluetooth/le_scan/ScanNativeInterface", - javaMethods); + GET_JAVA_METHODS(env, "com/android/bluetooth/le_scan/ScanNativeInterface", javaMethods); return 0; } // JNI functions defined in AdvertiseManagerNativeInterface class. static int register_com_android_bluetooth_gatt_advertise_manager(JNIEnv* env) { const JNINativeMethod methods[] = { - {"initializeNative", "()V", (void*)advertiseInitializeNative}, - {"cleanupNative", "()V", (void*)advertiseCleanupNative}, - {"startAdvertisingSetNative", - "(Landroid/bluetooth/le/AdvertisingSetParameters;" - "[B[BLandroid/bluetooth/le/PeriodicAdvertisingParameters;[BIIII)V", - (void*)startAdvertisingSetNative}, - {"stopAdvertisingSetNative", "(I)V", (void*)stopAdvertisingSetNative}, - {"getOwnAddressNative", "(I)V", (void*)getOwnAddressNative}, - {"enableAdvertisingSetNative", "(IZII)V", - (void*)enableAdvertisingSetNative}, - {"setAdvertisingDataNative", "(I[B)V", (void*)setAdvertisingDataNative}, - {"setScanResponseDataNative", "(I[B)V", (void*)setScanResponseDataNative}, - {"setAdvertisingParametersNative", - "(ILandroid/bluetooth/le/AdvertisingSetParameters;)V", - (void*)setAdvertisingParametersNative}, - {"setPeriodicAdvertisingParametersNative", - "(ILandroid/bluetooth/le/PeriodicAdvertisingParameters;)V", - (void*)setPeriodicAdvertisingParametersNative}, - {"setPeriodicAdvertisingDataNative", "(I[B)V", - (void*)setPeriodicAdvertisingDataNative}, - {"setPeriodicAdvertisingEnableNative", "(IZ)V", - (void*)setPeriodicAdvertisingEnableNative}, + {"initializeNative", "()V", (void*)advertiseInitializeNative}, + {"cleanupNative", "()V", (void*)advertiseCleanupNative}, + {"startAdvertisingSetNative", + "(Landroid/bluetooth/le/AdvertisingSetParameters;" + "[B[BLandroid/bluetooth/le/PeriodicAdvertisingParameters;[BIIII)V", + (void*)startAdvertisingSetNative}, + {"stopAdvertisingSetNative", "(I)V", (void*)stopAdvertisingSetNative}, + {"getOwnAddressNative", "(I)V", (void*)getOwnAddressNative}, + {"enableAdvertisingSetNative", "(IZII)V", (void*)enableAdvertisingSetNative}, + {"setAdvertisingDataNative", "(I[B)V", (void*)setAdvertisingDataNative}, + {"setScanResponseDataNative", "(I[B)V", (void*)setScanResponseDataNative}, + {"setAdvertisingParametersNative", "(ILandroid/bluetooth/le/AdvertisingSetParameters;)V", + (void*)setAdvertisingParametersNative}, + {"setPeriodicAdvertisingParametersNative", + "(ILandroid/bluetooth/le/PeriodicAdvertisingParameters;)V", + (void*)setPeriodicAdvertisingParametersNative}, + {"setPeriodicAdvertisingDataNative", "(I[B)V", (void*)setPeriodicAdvertisingDataNative}, + {"setPeriodicAdvertisingEnableNative", "(IZ)V", + (void*)setPeriodicAdvertisingEnableNative}, }; const int result = REGISTER_NATIVE_METHODS( - env, "com/android/bluetooth/gatt/AdvertiseManagerNativeInterface", - methods); + env, "com/android/bluetooth/gatt/AdvertiseManagerNativeInterface", methods); if (result != 0) { return result; } const JNIJavaMethod javaMethods[] = { - {"onAdvertisingSetStarted", "(IIII)V", &method_onAdvertisingSetStarted}, - {"onOwnAddressRead", "(IILjava/lang/String;)V", &method_onOwnAddressRead}, - {"onAdvertisingEnabled", "(IZI)V", &method_onAdvertisingEnabled}, - {"onAdvertisingDataSet", "(II)V", &method_onAdvertisingDataSet}, - {"onScanResponseDataSet", "(II)V", &method_onScanResponseDataSet}, - {"onAdvertisingParametersUpdated", "(III)V", - &method_onAdvertisingParametersUpdated}, - {"onPeriodicAdvertisingParametersUpdated", "(II)V", - &method_onPeriodicAdvertisingParametersUpdated}, - {"onPeriodicAdvertisingDataSet", "(II)V", - &method_onPeriodicAdvertisingDataSet}, - {"onPeriodicAdvertisingEnabled", "(IZI)V", - &method_onPeriodicAdvertisingEnabled}, + {"onAdvertisingSetStarted", "(IIII)V", &method_onAdvertisingSetStarted}, + {"onOwnAddressRead", "(IILjava/lang/String;)V", &method_onOwnAddressRead}, + {"onAdvertisingEnabled", "(IZI)V", &method_onAdvertisingEnabled}, + {"onAdvertisingDataSet", "(II)V", &method_onAdvertisingDataSet}, + {"onScanResponseDataSet", "(II)V", &method_onScanResponseDataSet}, + {"onAdvertisingParametersUpdated", "(III)V", &method_onAdvertisingParametersUpdated}, + {"onPeriodicAdvertisingParametersUpdated", "(II)V", + &method_onPeriodicAdvertisingParametersUpdated}, + {"onPeriodicAdvertisingDataSet", "(II)V", &method_onPeriodicAdvertisingDataSet}, + {"onPeriodicAdvertisingEnabled", "(IZI)V", &method_onPeriodicAdvertisingEnabled}, }; - GET_JAVA_METHODS(env, - "com/android/bluetooth/gatt/AdvertiseManagerNativeInterface", - javaMethods); + GET_JAVA_METHODS(env, "com/android/bluetooth/gatt/AdvertiseManagerNativeInterface", javaMethods); return 0; } // JNI functions defined in PeriodicScanNativeInterface class. static int register_com_android_bluetooth_gatt_periodic_scan(JNIEnv* env) { const JNINativeMethod methods[] = { - {"initializeNative", "()V", (void*)periodicScanInitializeNative}, - {"cleanupNative", "()V", (void*)periodicScanCleanupNative}, - {"startSyncNative", "(ILjava/lang/String;III)V", (void*)startSyncNative}, - {"stopSyncNative", "(I)V", (void*)stopSyncNative}, - {"cancelSyncNative", "(ILjava/lang/String;)V", (void*)cancelSyncNative}, - {"syncTransferNative", "(ILjava/lang/String;II)V", - (void*)syncTransferNative}, - {"transferSetInfoNative", "(ILjava/lang/String;II)V", - (void*)transferSetInfoNative}, + {"initializeNative", "()V", (void*)periodicScanInitializeNative}, + {"cleanupNative", "()V", (void*)periodicScanCleanupNative}, + {"startSyncNative", "(ILjava/lang/String;III)V", (void*)startSyncNative}, + {"stopSyncNative", "(I)V", (void*)stopSyncNative}, + {"cancelSyncNative", "(ILjava/lang/String;)V", (void*)cancelSyncNative}, + {"syncTransferNative", "(ILjava/lang/String;II)V", (void*)syncTransferNative}, + {"transferSetInfoNative", "(ILjava/lang/String;II)V", (void*)transferSetInfoNative}, }; const int result = REGISTER_NATIVE_METHODS( - env, "com/android/bluetooth/le_scan/PeriodicScanNativeInterface", - methods); + env, "com/android/bluetooth/le_scan/PeriodicScanNativeInterface", methods); if (result != 0) { return result; } const JNIJavaMethod javaMethods[] = { - {"onSyncStarted", "(IIIILjava/lang/String;III)V", &method_onSyncStarted}, - {"onSyncReport", "(IIII[B)V", &method_onSyncReport}, - {"onSyncLost", "(I)V", &method_onSyncLost}, - {"onSyncTransferredCallback", "(IILjava/lang/String;)V", - &method_onSyncTransferredCallback}, - {"onBigInfoReport", "(IZ)V", &method_onBigInfoReport}, + {"onSyncStarted", "(IIIILjava/lang/String;III)V", &method_onSyncStarted}, + {"onSyncReport", "(IIII[B)V", &method_onSyncReport}, + {"onSyncLost", "(I)V", &method_onSyncLost}, + {"onSyncTransferredCallback", "(IILjava/lang/String;)V", + &method_onSyncTransferredCallback}, + {"onBigInfoReport", "(IZ)V", &method_onBigInfoReport}, }; - GET_JAVA_METHODS(env, - "com/android/bluetooth/le_scan/PeriodicScanNativeInterface", - javaMethods); + GET_JAVA_METHODS(env, "com/android/bluetooth/le_scan/PeriodicScanNativeInterface", javaMethods); return 0; } // JNI functions defined in DistanceMeasurementNativeInterface class. -static int register_com_android_bluetooth_gatt_distance_measurement( - JNIEnv* env) { +static int register_com_android_bluetooth_gatt_distance_measurement(JNIEnv* env) { const JNINativeMethod methods[] = { - {"initializeNative", "()V", (void*)distanceMeasurementInitializeNative}, - {"cleanupNative", "()V", (void*)distanceMeasurementCleanupNative}, - {"startDistanceMeasurementNative", "(Ljava/lang/String;II)V", - (void*)startDistanceMeasurementNative}, - {"stopDistanceMeasurementNative", "(Ljava/lang/String;I)V", - (void*)stopDistanceMeasurementNative}, + {"initializeNative", "()V", (void*)distanceMeasurementInitializeNative}, + {"cleanupNative", "()V", (void*)distanceMeasurementCleanupNative}, + {"startDistanceMeasurementNative", "(Ljava/lang/String;II)V", + (void*)startDistanceMeasurementNative}, + {"stopDistanceMeasurementNative", "(Ljava/lang/String;I)V", + (void*)stopDistanceMeasurementNative}, }; const int result = REGISTER_NATIVE_METHODS( - env, "com/android/bluetooth/gatt/DistanceMeasurementNativeInterface", - methods); + env, "com/android/bluetooth/gatt/DistanceMeasurementNativeInterface", methods); if (result != 0) { return result; } const JNIJavaMethod javaMethods[] = { - {"onDistanceMeasurementStarted", "(Ljava/lang/String;I)V", - &method_onDistanceMeasurementStarted}, - {"onDistanceMeasurementStartFail", "(Ljava/lang/String;II)V", - &method_onDistanceMeasurementStartFail}, - {"onDistanceMeasurementStopped", "(Ljava/lang/String;II)V", - &method_onDistanceMeasurementStopped}, - {"onDistanceMeasurementResult", "(Ljava/lang/String;IIIIIII)V", - &method_onDistanceMeasurementResult}, + {"onDistanceMeasurementStarted", "(Ljava/lang/String;I)V", + &method_onDistanceMeasurementStarted}, + {"onDistanceMeasurementStartFail", "(Ljava/lang/String;II)V", + &method_onDistanceMeasurementStartFail}, + {"onDistanceMeasurementStopped", "(Ljava/lang/String;II)V", + &method_onDistanceMeasurementStopped}, + {"onDistanceMeasurementResult", "(Ljava/lang/String;IIIIIII)V", + &method_onDistanceMeasurementResult}, }; - GET_JAVA_METHODS( - env, "com/android/bluetooth/gatt/DistanceMeasurementNativeInterface", - javaMethods); + GET_JAVA_METHODS(env, "com/android/bluetooth/gatt/DistanceMeasurementNativeInterface", + javaMethods); return 0; } // JNI functions defined in GattNativeInterface class. static int register_com_android_bluetooth_gatt_(JNIEnv* env) { const JNINativeMethod methods[] = { - {"initializeNative", "()V", (void*)initializeNative}, - {"cleanupNative", "()V", (void*)cleanupNative}, - {"gattClientGetDeviceTypeNative", "(Ljava/lang/String;)I", - (void*)gattClientGetDeviceTypeNative}, - {"gattClientRegisterAppNative", "(JJZ)V", - (void*)gattClientRegisterAppNative}, - {"gattClientUnregisterAppNative", "(I)V", - (void*)gattClientUnregisterAppNative}, - {"gattClientConnectNative", "(ILjava/lang/String;IZIZI)V", - (void*)gattClientConnectNative}, - {"gattClientDisconnectNative", "(ILjava/lang/String;I)V", - (void*)gattClientDisconnectNative}, - {"gattClientSetPreferredPhyNative", "(ILjava/lang/String;III)V", - (void*)gattClientSetPreferredPhyNative}, - {"gattClientReadPhyNative", "(ILjava/lang/String;)V", - (void*)gattClientReadPhyNative}, - {"gattClientRefreshNative", "(ILjava/lang/String;)V", - (void*)gattClientRefreshNative}, - {"gattClientSearchServiceNative", "(IZJJ)V", - (void*)gattClientSearchServiceNative}, - {"gattClientDiscoverServiceByUuidNative", "(IJJ)V", - (void*)gattClientDiscoverServiceByUuidNative}, - {"gattClientGetGattDbNative", "(I)V", (void*)gattClientGetGattDbNative}, - {"gattClientReadCharacteristicNative", "(III)V", - (void*)gattClientReadCharacteristicNative}, - {"gattClientReadUsingCharacteristicUuidNative", "(IJJIII)V", - (void*)gattClientReadUsingCharacteristicUuidNative}, - {"gattClientReadDescriptorNative", "(III)V", - (void*)gattClientReadDescriptorNative}, - {"gattClientWriteCharacteristicNative", "(IIII[B)V", - (void*)gattClientWriteCharacteristicNative}, - {"gattClientWriteDescriptorNative", "(III[B)V", - (void*)gattClientWriteDescriptorNative}, - {"gattClientExecuteWriteNative", "(IZ)V", - (void*)gattClientExecuteWriteNative}, - {"gattClientRegisterForNotificationsNative", "(ILjava/lang/String;IZ)V", - (void*)gattClientRegisterForNotificationsNative}, - {"gattClientReadRemoteRssiNative", "(ILjava/lang/String;)V", - (void*)gattClientReadRemoteRssiNative}, - {"gattClientConfigureMTUNative", "(II)V", - (void*)gattClientConfigureMTUNative}, - {"gattConnectionParameterUpdateNative", "(ILjava/lang/String;IIIIII)V", - (void*)gattConnectionParameterUpdateNative}, - {"gattServerRegisterAppNative", "(JJZ)V", - (void*)gattServerRegisterAppNative}, - {"gattServerUnregisterAppNative", "(I)V", - (void*)gattServerUnregisterAppNative}, - {"gattServerConnectNative", "(ILjava/lang/String;IZI)V", - (void*)gattServerConnectNative}, - {"gattServerDisconnectNative", "(ILjava/lang/String;I)V", - (void*)gattServerDisconnectNative}, - {"gattServerSetPreferredPhyNative", "(ILjava/lang/String;III)V", - (void*)gattServerSetPreferredPhyNative}, - {"gattServerReadPhyNative", "(ILjava/lang/String;)V", - (void*)gattServerReadPhyNative}, - {"gattServerAddServiceNative", "(ILjava/util/List;)V", - (void*)gattServerAddServiceNative}, - {"gattServerStopServiceNative", "(II)V", - (void*)gattServerStopServiceNative}, - {"gattServerDeleteServiceNative", "(II)V", - (void*)gattServerDeleteServiceNative}, - {"gattServerSendIndicationNative", "(III[B)V", - (void*)gattServerSendIndicationNative}, - {"gattServerSendNotificationNative", "(III[B)V", - (void*)gattServerSendNotificationNative}, - {"gattServerSendResponseNative", "(IIIIII[BI)V", - (void*)gattServerSendResponseNative}, - {"gattSubrateRequestNative", "(ILjava/lang/String;IIIII)V", - (void*)gattSubrateRequestNative}, - - {"gattTestNative", "(IJJLjava/lang/String;IIIII)V", - (void*)gattTestNative}, + {"initializeNative", "()V", (void*)initializeNative}, + {"cleanupNative", "()V", (void*)cleanupNative}, + {"gattClientGetDeviceTypeNative", "(Ljava/lang/String;)I", + (void*)gattClientGetDeviceTypeNative}, + {"gattClientRegisterAppNative", "(JJZ)V", (void*)gattClientRegisterAppNative}, + {"gattClientUnregisterAppNative", "(I)V", (void*)gattClientUnregisterAppNative}, + {"gattClientConnectNative", "(ILjava/lang/String;IZIZI)V", + (void*)gattClientConnectNative}, + {"gattClientDisconnectNative", "(ILjava/lang/String;I)V", + (void*)gattClientDisconnectNative}, + {"gattClientSetPreferredPhyNative", "(ILjava/lang/String;III)V", + (void*)gattClientSetPreferredPhyNative}, + {"gattClientReadPhyNative", "(ILjava/lang/String;)V", (void*)gattClientReadPhyNative}, + {"gattClientRefreshNative", "(ILjava/lang/String;)V", (void*)gattClientRefreshNative}, + {"gattClientSearchServiceNative", "(IZJJ)V", (void*)gattClientSearchServiceNative}, + {"gattClientDiscoverServiceByUuidNative", "(IJJ)V", + (void*)gattClientDiscoverServiceByUuidNative}, + {"gattClientGetGattDbNative", "(I)V", (void*)gattClientGetGattDbNative}, + {"gattClientReadCharacteristicNative", "(III)V", + (void*)gattClientReadCharacteristicNative}, + {"gattClientReadUsingCharacteristicUuidNative", "(IJJIII)V", + (void*)gattClientReadUsingCharacteristicUuidNative}, + {"gattClientReadDescriptorNative", "(III)V", (void*)gattClientReadDescriptorNative}, + {"gattClientWriteCharacteristicNative", "(IIII[B)V", + (void*)gattClientWriteCharacteristicNative}, + {"gattClientWriteDescriptorNative", "(III[B)V", (void*)gattClientWriteDescriptorNative}, + {"gattClientExecuteWriteNative", "(IZ)V", (void*)gattClientExecuteWriteNative}, + {"gattClientRegisterForNotificationsNative", "(ILjava/lang/String;IZ)V", + (void*)gattClientRegisterForNotificationsNative}, + {"gattClientReadRemoteRssiNative", "(ILjava/lang/String;)V", + (void*)gattClientReadRemoteRssiNative}, + {"gattClientConfigureMTUNative", "(II)V", (void*)gattClientConfigureMTUNative}, + {"gattConnectionParameterUpdateNative", "(ILjava/lang/String;IIIIII)V", + (void*)gattConnectionParameterUpdateNative}, + {"gattServerRegisterAppNative", "(JJZ)V", (void*)gattServerRegisterAppNative}, + {"gattServerUnregisterAppNative", "(I)V", (void*)gattServerUnregisterAppNative}, + {"gattServerConnectNative", "(ILjava/lang/String;IZI)V", (void*)gattServerConnectNative}, + {"gattServerDisconnectNative", "(ILjava/lang/String;I)V", + (void*)gattServerDisconnectNative}, + {"gattServerSetPreferredPhyNative", "(ILjava/lang/String;III)V", + (void*)gattServerSetPreferredPhyNative}, + {"gattServerReadPhyNative", "(ILjava/lang/String;)V", (void*)gattServerReadPhyNative}, + {"gattServerAddServiceNative", "(ILjava/util/List;)V", (void*)gattServerAddServiceNative}, + {"gattServerStopServiceNative", "(II)V", (void*)gattServerStopServiceNative}, + {"gattServerDeleteServiceNative", "(II)V", (void*)gattServerDeleteServiceNative}, + {"gattServerSendIndicationNative", "(III[B)V", (void*)gattServerSendIndicationNative}, + {"gattServerSendNotificationNative", "(III[B)V", (void*)gattServerSendNotificationNative}, + {"gattServerSendResponseNative", "(IIIIII[BI)V", (void*)gattServerSendResponseNative}, + {"gattSubrateRequestNative", "(ILjava/lang/String;IIIII)V", + (void*)gattSubrateRequestNative}, + + {"gattTestNative", "(IJJLjava/lang/String;IIIII)V", (void*)gattTestNative}, }; - const int result = REGISTER_NATIVE_METHODS( - env, "com/android/bluetooth/gatt/GattNativeInterface", methods); + const int result = + REGISTER_NATIVE_METHODS(env, "com/android/bluetooth/gatt/GattNativeInterface", methods); if (result != 0) { return result; } const JNIJavaMethod javaMethods[] = { - // Client callbacks - {"onClientRegistered", "(IIJJ)V", &method_onClientRegistered}, - {"onConnected", "(IIILjava/lang/String;)V", &method_onConnected}, - {"onDisconnected", "(IIILjava/lang/String;)V", &method_onDisconnected}, - {"onReadCharacteristic", "(III[B)V", &method_onReadCharacteristic}, - {"onWriteCharacteristic", "(III[B)V", &method_onWriteCharacteristic}, - {"onExecuteCompleted", "(II)V", &method_onExecuteCompleted}, - {"onSearchCompleted", "(II)V", &method_onSearchCompleted}, - {"onReadDescriptor", "(III[B)V", &method_onReadDescriptor}, - {"onWriteDescriptor", "(III[B)V", &method_onWriteDescriptor}, - {"onNotify", "(ILjava/lang/String;IZ[B)V", &method_onNotify}, - {"onRegisterForNotifications", "(IIII)V", - &method_onRegisterForNotifications}, - {"onReadRemoteRssi", "(ILjava/lang/String;II)V", - &method_onReadRemoteRssi}, - {"onConfigureMTU", "(III)V", &method_onConfigureMTU}, - {"onClientCongestion", "(IZ)V", &method_onClientCongestion}, - {"getSampleGattDbElement", "()Lcom/android/bluetooth/gatt/GattDbElement;", - &method_getSampleGattDbElement}, - {"onGetGattDb", "(ILjava/util/List;)V", &method_onGetGattDb}, - {"onClientPhyRead", "(ILjava/lang/String;III)V", &method_onClientPhyRead}, - {"onClientPhyUpdate", "(IIII)V", &method_onClientPhyUpdate}, - {"onClientConnUpdate", "(IIIII)V", &method_onClientConnUpdate}, - {"onServiceChanged", "(I)V", &method_onServiceChanged}, - {"onClientSubrateChange", "(IIIIII)V", &method_onClientSubrateChange}, - - // Server callbacks - {"onServerRegistered", "(IIJJ)V", &method_onServerRegistered}, - {"onClientConnected", "(Ljava/lang/String;ZII)V", - &method_onClientConnected}, - {"onServiceAdded", "(IILjava/util/List;)V", &method_onServiceAdded}, - {"onServiceStopped", "(III)V", &method_onServiceStopped}, - {"onServiceDeleted", "(III)V", &method_onServiceDeleted}, - {"onResponseSendCompleted", "(II)V", &method_onResponseSendCompleted}, - {"onServerReadCharacteristic", "(Ljava/lang/String;IIIIZ)V", - &method_onServerReadCharacteristic}, - {"onServerReadDescriptor", "(Ljava/lang/String;IIIIZ)V", - &method_onServerReadDescriptor}, - {"onServerWriteCharacteristic", "(Ljava/lang/String;IIIIIZZ[B)V", - &method_onServerWriteCharacteristic}, - {"onServerWriteDescriptor", "(Ljava/lang/String;IIIIIZZ[B)V", - &method_onServerWriteDescriptor}, - {"onExecuteWrite", "(Ljava/lang/String;III)V", &method_onExecuteWrite}, - {"onNotificationSent", "(II)V", &method_onNotificationSent}, - {"onServerCongestion", "(IZ)V", &method_onServerCongestion}, - {"onMtuChanged", "(II)V", &method_onServerMtuChanged}, - {"onServerPhyRead", "(ILjava/lang/String;III)V", &method_onServerPhyRead}, - {"onServerPhyUpdate", "(IIII)V", &method_onServerPhyUpdate}, - {"onServerConnUpdate", "(IIIII)V", &method_onServerConnUpdate}, - {"onServerSubrateChange", "(IIIIII)V", &method_onServerSubrateChange}, + // Client callbacks + {"onClientRegistered", "(IIJJ)V", &method_onClientRegistered}, + {"onConnected", "(IIILjava/lang/String;)V", &method_onConnected}, + {"onDisconnected", "(IIILjava/lang/String;)V", &method_onDisconnected}, + {"onReadCharacteristic", "(III[B)V", &method_onReadCharacteristic}, + {"onWriteCharacteristic", "(III[B)V", &method_onWriteCharacteristic}, + {"onExecuteCompleted", "(II)V", &method_onExecuteCompleted}, + {"onSearchCompleted", "(II)V", &method_onSearchCompleted}, + {"onReadDescriptor", "(III[B)V", &method_onReadDescriptor}, + {"onWriteDescriptor", "(III[B)V", &method_onWriteDescriptor}, + {"onNotify", "(ILjava/lang/String;IZ[B)V", &method_onNotify}, + {"onRegisterForNotifications", "(IIII)V", &method_onRegisterForNotifications}, + {"onReadRemoteRssi", "(ILjava/lang/String;II)V", &method_onReadRemoteRssi}, + {"onConfigureMTU", "(III)V", &method_onConfigureMTU}, + {"onClientCongestion", "(IZ)V", &method_onClientCongestion}, + {"getSampleGattDbElement", "()Lcom/android/bluetooth/gatt/GattDbElement;", + &method_getSampleGattDbElement}, + {"onGetGattDb", "(ILjava/util/List;)V", &method_onGetGattDb}, + {"onClientPhyRead", "(ILjava/lang/String;III)V", &method_onClientPhyRead}, + {"onClientPhyUpdate", "(IIII)V", &method_onClientPhyUpdate}, + {"onClientConnUpdate", "(IIIII)V", &method_onClientConnUpdate}, + {"onServiceChanged", "(I)V", &method_onServiceChanged}, + {"onClientSubrateChange", "(IIIIII)V", &method_onClientSubrateChange}, + + // Server callbacks + {"onServerRegistered", "(IIJJ)V", &method_onServerRegistered}, + {"onClientConnected", "(Ljava/lang/String;ZII)V", &method_onClientConnected}, + {"onServiceAdded", "(IILjava/util/List;)V", &method_onServiceAdded}, + {"onServiceStopped", "(III)V", &method_onServiceStopped}, + {"onServiceDeleted", "(III)V", &method_onServiceDeleted}, + {"onResponseSendCompleted", "(II)V", &method_onResponseSendCompleted}, + {"onServerReadCharacteristic", "(Ljava/lang/String;IIIIZ)V", + &method_onServerReadCharacteristic}, + {"onServerReadDescriptor", "(Ljava/lang/String;IIIIZ)V", &method_onServerReadDescriptor}, + {"onServerWriteCharacteristic", "(Ljava/lang/String;IIIIIZZ[B)V", + &method_onServerWriteCharacteristic}, + {"onServerWriteDescriptor", "(Ljava/lang/String;IIIIIZZ[B)V", + &method_onServerWriteDescriptor}, + {"onExecuteWrite", "(Ljava/lang/String;III)V", &method_onExecuteWrite}, + {"onNotificationSent", "(II)V", &method_onNotificationSent}, + {"onServerCongestion", "(IZ)V", &method_onServerCongestion}, + {"onMtuChanged", "(II)V", &method_onServerMtuChanged}, + {"onServerPhyRead", "(ILjava/lang/String;III)V", &method_onServerPhyRead}, + {"onServerPhyUpdate", "(IIII)V", &method_onServerPhyUpdate}, + {"onServerConnUpdate", "(IIIII)V", &method_onServerConnUpdate}, + {"onServerSubrateChange", "(IIIIII)V", &method_onServerSubrateChange}, }; - GET_JAVA_METHODS(env, "com/android/bluetooth/gatt/GattNativeInterface", - javaMethods); + GET_JAVA_METHODS(env, "com/android/bluetooth/gatt/GattNativeInterface", javaMethods); return 0; } int register_com_android_bluetooth_gatt(JNIEnv* env) { const std::array, 5> register_fns = { - register_com_android_bluetooth_gatt_scan, - register_com_android_bluetooth_gatt_advertise_manager, - register_com_android_bluetooth_gatt_periodic_scan, - register_com_android_bluetooth_gatt_distance_measurement, - register_com_android_bluetooth_gatt_, + register_com_android_bluetooth_gatt_scan, + register_com_android_bluetooth_gatt_advertise_manager, + register_com_android_bluetooth_gatt_periodic_scan, + register_com_android_bluetooth_gatt_distance_measurement, + register_com_android_bluetooth_gatt_, }; for (const auto& fn : register_fns) { diff --git a/android/app/jni/com_android_bluetooth_hap_client.cpp b/android/app/jni/com_android_bluetooth_hap_client.cpp index be1b0712ae7..fdbc7c37e51 100644 --- a/android/app/jni/com_android_bluetooth_hap_client.cpp +++ b/android/app/jni/com_android_bluetooth_hap_client.cpp @@ -67,89 +67,91 @@ static struct { } android_bluetooth_BluetoothHapPresetInfo; class HasClientCallbacksImpl : public HasClientCallbacks { - public: +public: ~HasClientCallbacksImpl() = default; - void OnConnectionState(ConnectionState state, - const RawAddress& bd_addr) override { + void OnConnectionState(ConnectionState state, const RawAddress& bd_addr) override { log::info(""); std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) return; + if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) { + return; + } - ScopedLocalRef addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); + ScopedLocalRef addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); if (!addr.get()) { log::error("Failed to new bd addr jbyteArray for connection state"); return; } - sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), - (jbyte*)&bd_addr); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onConnectionStateChanged, - (jint)state, addr.get()); + sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), (jbyte*)&bd_addr); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onConnectionStateChanged, (jint)state, + addr.get()); } void OnDeviceAvailable(const RawAddress& bd_addr, uint8_t features) override { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) return; + if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) { + return; + } - ScopedLocalRef addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); + ScopedLocalRef addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); if (!addr.get()) { log::error("Failed to new bd addr jbyteArray for device available"); return; } - sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), - (jbyte*)&bd_addr); + sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), (jbyte*)&bd_addr); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onDeviceAvailable, - addr.get(), (jint)features); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onDeviceAvailable, addr.get(), + (jint)features); } void OnFeaturesUpdate(const RawAddress& bd_addr, uint8_t features) override { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) return; + if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) { + return; + } - ScopedLocalRef addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); + ScopedLocalRef addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); if (!addr.get()) { log::error("Failed to new bd addr jbyteArray for device available"); return; } - sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), - (jbyte*)&bd_addr); + sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), (jbyte*)&bd_addr); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onFeaturesUpdate, - addr.get(), (jint)features); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onFeaturesUpdate, addr.get(), + (jint)features); } void OnActivePresetSelected(std::variant addr_or_group_id, uint8_t preset_index) override { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) return; + if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) { + return; + } if (std::holds_alternative(addr_or_group_id)) { - ScopedLocalRef addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); + ScopedLocalRef addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); if (!addr.get()) { log::error("Failed to new bd addr jbyteArray for preset selected"); return; } - sCallbackEnv->SetByteArrayRegion( - addr.get(), 0, sizeof(RawAddress), - (jbyte*)&std::get(addr_or_group_id)); + sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), + (jbyte*)&std::get(addr_or_group_id)); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onActivePresetSelected, - addr.get(), (jint)preset_index); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onActivePresetSelected, addr.get(), + (jint)preset_index); } else { - sCallbackEnv->CallVoidMethod( - mCallbacksObj, method_onGroupActivePresetSelected, - std::get(addr_or_group_id), (jint)preset_index); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onGroupActivePresetSelected, + std::get(addr_or_group_id), (jint)preset_index); } } @@ -157,40 +159,39 @@ class HasClientCallbacksImpl : public HasClientCallbacks { ErrorCode error_code) override { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) return; + if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) { + return; + } if (std::holds_alternative(addr_or_group_id)) { - ScopedLocalRef addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); + ScopedLocalRef addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); if (!addr.get()) { log::error("Failed to new bd addr jbyteArray for preset select error"); return; } - sCallbackEnv->SetByteArrayRegion( - addr.get(), 0, sizeof(RawAddress), - (jbyte*)&std::get(addr_or_group_id)); + sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), + (jbyte*)&std::get(addr_or_group_id)); - sCallbackEnv->CallVoidMethod(mCallbacksObj, - method_onActivePresetSelectError, addr.get(), + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onActivePresetSelectError, addr.get(), (jint)error_code); } else { - sCallbackEnv->CallVoidMethod( - mCallbacksObj, method_onGroupActivePresetSelectError, - std::get(addr_or_group_id), (jint)error_code); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onGroupActivePresetSelectError, + std::get(addr_or_group_id), (jint)error_code); } } - void OnPresetInfo(std::variant addr_or_group_id, - PresetInfoReason info_reason, + void OnPresetInfo(std::variant addr_or_group_id, PresetInfoReason info_reason, std::vector detail_records) override { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) return; + if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) { + return; + } jsize i = 0; jobjectArray presets_array = sCallbackEnv->NewObjectArray( - (jsize)detail_records.size(), - android_bluetooth_BluetoothHapPresetInfo.clazz, nullptr); + (jsize)detail_records.size(), android_bluetooth_BluetoothHapPresetInfo.clazz, nullptr); const char null_str[] = ""; for (auto const& info : detail_records) { @@ -200,99 +201,90 @@ class HasClientCallbacksImpl : public HasClientCallbacks { name = null_str; } - ScopedLocalRef name_str(sCallbackEnv.get(), - sCallbackEnv->NewStringUTF(name)); + ScopedLocalRef name_str(sCallbackEnv.get(), sCallbackEnv->NewStringUTF(name)); if (!name_str.get()) { log::error("Failed to new preset name String for preset name"); return; } jobject infoObj = sCallbackEnv->NewObject( - android_bluetooth_BluetoothHapPresetInfo.clazz, - android_bluetooth_BluetoothHapPresetInfo.constructor, - (jint)info.preset_index, name_str.get(), (jboolean)info.writable, - (jboolean)info.available); + android_bluetooth_BluetoothHapPresetInfo.clazz, + android_bluetooth_BluetoothHapPresetInfo.constructor, (jint)info.preset_index, + name_str.get(), (jboolean)info.writable, (jboolean)info.available); sCallbackEnv->SetObjectArrayElement(presets_array, i++, infoObj); sCallbackEnv->DeleteLocalRef(infoObj); } if (std::holds_alternative(addr_or_group_id)) { - ScopedLocalRef addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); + ScopedLocalRef addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); if (!addr.get()) { log::error("Failed to new bd addr jbyteArray for preset name"); return; } - sCallbackEnv->SetByteArrayRegion( - addr.get(), 0, sizeof(RawAddress), - (jbyte*)&std::get(addr_or_group_id)); + sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), + (jbyte*)&std::get(addr_or_group_id)); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onPresetInfo, - addr.get(), (jint)info_reason, - presets_array); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onPresetInfo, addr.get(), + (jint)info_reason, presets_array); } else { sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onGroupPresetInfo, - std::get(addr_or_group_id), - (jint)info_reason, presets_array); + std::get(addr_or_group_id), (jint)info_reason, + presets_array); } } virtual void OnPresetInfoError(std::variant addr_or_group_id, - uint8_t preset_index, - ErrorCode error_code) override { + uint8_t preset_index, ErrorCode error_code) override { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) return; + if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) { + return; + } if (std::holds_alternative(addr_or_group_id)) { - ScopedLocalRef addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); + ScopedLocalRef addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); if (!addr.get()) { - log::error( - "Failed to new bd addr jbyteArray for preset name get error"); + log::error("Failed to new bd addr jbyteArray for preset name get error"); return; } - sCallbackEnv->SetByteArrayRegion( - addr.get(), 0, sizeof(RawAddress), - (jbyte*)&std::get(addr_or_group_id)); + sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), + (jbyte*)&std::get(addr_or_group_id)); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onPresetInfoError, - addr.get(), (jint)preset_index, - (jint)error_code); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onPresetInfoError, addr.get(), + (jint)preset_index, (jint)error_code); } else { sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onGroupPresetInfoError, - std::get(addr_or_group_id), - (jint)preset_index, (jint)error_code); + std::get(addr_or_group_id), (jint)preset_index, + (jint)error_code); } } - void OnSetPresetNameError(std::variant addr_or_group_id, - uint8_t preset_index, + void OnSetPresetNameError(std::variant addr_or_group_id, uint8_t preset_index, ErrorCode error_code) override { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) return; + if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) { + return; + } if (std::holds_alternative(addr_or_group_id)) { - ScopedLocalRef addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); + ScopedLocalRef addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); if (!addr.get()) { - log::error( - "Failed to new bd addr jbyteArray for preset name set error"); + log::error("Failed to new bd addr jbyteArray for preset name set error"); return; } - sCallbackEnv->SetByteArrayRegion( - addr.get(), 0, sizeof(RawAddress), - (jbyte*)&std::get(addr_or_group_id)); + sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), + (jbyte*)&std::get(addr_or_group_id)); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onPresetNameSetError, - addr.get(), (jint)preset_index, - (jint)error_code); - } else { - sCallbackEnv->CallVoidMethod(mCallbacksObj, - method_onGroupPresetNameSetError, - std::get(addr_or_group_id), + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onPresetNameSetError, addr.get(), (jint)preset_index, (jint)error_code); + } else { + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onGroupPresetNameSetError, + std::get(addr_or_group_id), (jint)preset_index, + (jint)error_code); } } }; @@ -326,19 +318,16 @@ static void initNative(JNIEnv* env, jobject object) { return; } - android_bluetooth_BluetoothHapPresetInfo.clazz = (jclass)env->NewGlobalRef( - env->FindClass("android/bluetooth/BluetoothHapPresetInfo")); + android_bluetooth_BluetoothHapPresetInfo.clazz = + (jclass)env->NewGlobalRef(env->FindClass("android/bluetooth/BluetoothHapPresetInfo")); if (android_bluetooth_BluetoothHapPresetInfo.clazz == nullptr) { - log::error( - "Failed to allocate Global Ref for BluetoothHapPresetInfo class"); + log::error("Failed to allocate Global Ref for BluetoothHapPresetInfo class"); return; } - sHasClientInterface = (HasClientInterface*)btInf->get_profile_interface( - BT_PROFILE_HAP_CLIENT_ID); + sHasClientInterface = (HasClientInterface*)btInf->get_profile_interface(BT_PROFILE_HAP_CLIENT_ID); if (sHasClientInterface == nullptr) { - log::error( - "Failed to get Bluetooth Hearing Access Service Client Interface"); + log::error("Failed to get Bluetooth Hearing Access Service Client Interface"); return; } @@ -366,8 +355,7 @@ static void cleanupNative(JNIEnv* env, jobject /* object */) { } } -static jboolean connectHapClientNative(JNIEnv* env, jobject /* object */, - jbyteArray address) { +static jboolean connectHapClientNative(JNIEnv* env, jobject /* object */, jbyteArray address) { std::shared_lock lock(interface_mutex); if (!sHasClientInterface) { log::error("Failed to get the Bluetooth HAP Interface"); @@ -386,8 +374,7 @@ static jboolean connectHapClientNative(JNIEnv* env, jobject /* object */, return JNI_TRUE; } -static jboolean disconnectHapClientNative(JNIEnv* env, jobject /* object */, - jbyteArray address) { +static jboolean disconnectHapClientNative(JNIEnv* env, jobject /* object */, jbyteArray address) { std::shared_lock lock(interface_mutex); if (!sHasClientInterface) { log::error("Failed to get the Bluetooth HAP Interface"); @@ -406,8 +393,8 @@ static jboolean disconnectHapClientNative(JNIEnv* env, jobject /* object */, return JNI_TRUE; } -static void selectActivePresetNative(JNIEnv* env, jobject /* object */, - jbyteArray address, jint preset_index) { +static void selectActivePresetNative(JNIEnv* env, jobject /* object */, jbyteArray address, + jint preset_index) { std::shared_lock lock(interface_mutex); if (!sHasClientInterface) { log::error("Failed to get the Bluetooth HAP Interface"); @@ -425,8 +412,7 @@ static void selectActivePresetNative(JNIEnv* env, jobject /* object */, env->ReleaseByteArrayElements(address, addr, 0); } -static void groupSelectActivePresetNative(JNIEnv* /* env */, - jobject /* object */, jint group_id, +static void groupSelectActivePresetNative(JNIEnv* /* env */, jobject /* object */, jint group_id, jint preset_index) { std::shared_lock lock(interface_mutex); if (!sHasClientInterface) { @@ -437,8 +423,7 @@ static void groupSelectActivePresetNative(JNIEnv* /* env */, sHasClientInterface->SelectActivePreset(group_id, preset_index); } -static void nextActivePresetNative(JNIEnv* env, jobject /* object */, - jbyteArray address) { +static void nextActivePresetNative(JNIEnv* env, jobject /* object */, jbyteArray address) { std::shared_lock lock(interface_mutex); if (!sHasClientInterface) { log::error("Failed to get the Bluetooth HAP Interface"); @@ -456,8 +441,7 @@ static void nextActivePresetNative(JNIEnv* env, jobject /* object */, env->ReleaseByteArrayElements(address, addr, 0); } -static void groupNextActivePresetNative(JNIEnv* /* env */, jobject /* object */, - jint group_id) { +static void groupNextActivePresetNative(JNIEnv* /* env */, jobject /* object */, jint group_id) { std::shared_lock lock(interface_mutex); if (!sHasClientInterface) { log::error("Failed to get the Bluetooth HAP Interface"); @@ -467,8 +451,7 @@ static void groupNextActivePresetNative(JNIEnv* /* env */, jobject /* object */, sHasClientInterface->NextActivePreset(group_id); } -static void previousActivePresetNative(JNIEnv* env, jobject /* object */, - jbyteArray address) { +static void previousActivePresetNative(JNIEnv* env, jobject /* object */, jbyteArray address) { std::shared_lock lock(interface_mutex); if (!sHasClientInterface) { log::error("Failed to get the Bluetooth HAP Interface"); @@ -486,8 +469,7 @@ static void previousActivePresetNative(JNIEnv* env, jobject /* object */, env->ReleaseByteArrayElements(address, addr, 0); } -static void groupPreviousActivePresetNative(JNIEnv* /* env */, - jobject /* object */, +static void groupPreviousActivePresetNative(JNIEnv* /* env */, jobject /* object */, jint group_id) { std::shared_lock lock(interface_mutex); if (!sHasClientInterface) { @@ -498,8 +480,8 @@ static void groupPreviousActivePresetNative(JNIEnv* /* env */, sHasClientInterface->PreviousActivePreset(group_id); } -static void getPresetInfoNative(JNIEnv* env, jobject /* object */, - jbyteArray address, jint preset_index) { +static void getPresetInfoNative(JNIEnv* env, jobject /* object */, jbyteArray address, + jint preset_index) { std::shared_lock lock(interface_mutex); if (!sHasClientInterface) { log::error("Failed to get the Bluetooth HAP Interface"); @@ -517,9 +499,8 @@ static void getPresetInfoNative(JNIEnv* env, jobject /* object */, env->ReleaseByteArrayElements(address, addr, 0); } -static void setPresetNameNative(JNIEnv* env, jobject /* object */, - jbyteArray address, jint preset_index, - jstring name) { +static void setPresetNameNative(JNIEnv* env, jobject /* object */, jbyteArray address, + jint preset_index, jstring name) { std::shared_lock lock(interface_mutex); if (!sHasClientInterface) { log::error("Failed to get the Bluetooth HAP Interface"); @@ -540,14 +521,12 @@ static void setPresetNameNative(JNIEnv* env, jobject /* object */, } RawAddress* tmpraw = (RawAddress*)addr; - sHasClientInterface->SetPresetName(*tmpraw, preset_index, - std::move(name_str)); + sHasClientInterface->SetPresetName(*tmpraw, preset_index, std::move(name_str)); env->ReleaseByteArrayElements(address, addr, 0); } -static void groupSetPresetNameNative(JNIEnv* env, jobject /* object */, - jint group_id, jint preset_index, - jstring name) { +static void groupSetPresetNameNative(JNIEnv* env, jobject /* object */, jint group_id, + jint preset_index, jstring name) { std::shared_lock lock(interface_mutex); if (!sHasClientInterface) { log::error("Failed to get the Bluetooth HAP Interface"); @@ -561,68 +540,55 @@ static void groupSetPresetNameNative(JNIEnv* env, jobject /* object */, env->ReleaseStringUTFChars(name, value); } - sHasClientInterface->SetPresetName(group_id, preset_index, - std::move(name_str)); + sHasClientInterface->SetPresetName(group_id, preset_index, std::move(name_str)); } int register_com_android_bluetooth_hap_client(JNIEnv* env) { const JNINativeMethod methods[] = { - {"initNative", "()V", (void*)initNative}, - {"cleanupNative", "()V", (void*)cleanupNative}, - {"connectHapClientNative", "([B)Z", (void*)connectHapClientNative}, - {"disconnectHapClientNative", "([B)Z", (void*)disconnectHapClientNative}, - {"selectActivePresetNative", "([BI)V", (void*)selectActivePresetNative}, - {"groupSelectActivePresetNative", "(II)V", - (void*)groupSelectActivePresetNative}, - {"nextActivePresetNative", "([B)V", (void*)nextActivePresetNative}, - {"groupNextActivePresetNative", "(I)V", - (void*)groupNextActivePresetNative}, - {"previousActivePresetNative", "([B)V", - (void*)previousActivePresetNative}, - {"groupPreviousActivePresetNative", "(I)V", - (void*)groupPreviousActivePresetNative}, - {"getPresetInfoNative", "([BI)V", (void*)getPresetInfoNative}, - {"setPresetNameNative", "([BILjava/lang/String;)V", - (void*)setPresetNameNative}, - {"groupSetPresetNameNative", "(IILjava/lang/String;)V", - (void*)groupSetPresetNameNative}, + {"initNative", "()V", (void*)initNative}, + {"cleanupNative", "()V", (void*)cleanupNative}, + {"connectHapClientNative", "([B)Z", (void*)connectHapClientNative}, + {"disconnectHapClientNative", "([B)Z", (void*)disconnectHapClientNative}, + {"selectActivePresetNative", "([BI)V", (void*)selectActivePresetNative}, + {"groupSelectActivePresetNative", "(II)V", (void*)groupSelectActivePresetNative}, + {"nextActivePresetNative", "([B)V", (void*)nextActivePresetNative}, + {"groupNextActivePresetNative", "(I)V", (void*)groupNextActivePresetNative}, + {"previousActivePresetNative", "([B)V", (void*)previousActivePresetNative}, + {"groupPreviousActivePresetNative", "(I)V", (void*)groupPreviousActivePresetNative}, + {"getPresetInfoNative", "([BI)V", (void*)getPresetInfoNative}, + {"setPresetNameNative", "([BILjava/lang/String;)V", (void*)setPresetNameNative}, + {"groupSetPresetNameNative", "(IILjava/lang/String;)V", (void*)groupSetPresetNameNative}, }; const int result = REGISTER_NATIVE_METHODS( - env, "com/android/bluetooth/hap/HapClientNativeInterface", methods); + env, "com/android/bluetooth/hap/HapClientNativeInterface", methods); if (result != 0) { return result; } const JNIJavaMethod javaMethods[] = { - {"onConnectionStateChanged", "(I[B)V", &method_onConnectionStateChanged}, - {"onDeviceAvailable", "([BI)V", &method_onDeviceAvailable}, - {"onFeaturesUpdate", "([BI)V", &method_onFeaturesUpdate}, - {"onActivePresetSelected", "([BI)V", &method_onActivePresetSelected}, - {"onActivePresetGroupSelected", "(II)V", - &method_onGroupActivePresetSelected}, - {"onActivePresetSelectError", "([BI)V", - &method_onActivePresetSelectError}, - {"onActivePresetGroupSelectError", "(II)V", - &method_onGroupActivePresetSelectError}, - {"onPresetInfo", "([BI[Landroid/bluetooth/BluetoothHapPresetInfo;)V", - &method_onPresetInfo}, - {"onGroupPresetInfo", "(II[Landroid/bluetooth/BluetoothHapPresetInfo;)V", - &method_onGroupPresetInfo}, - {"onPresetNameSetError", "([BII)V", &method_onPresetNameSetError}, - {"onGroupPresetNameSetError", "(III)V", - &method_onGroupPresetNameSetError}, - {"onPresetInfoError", "([BII)V", &method_onPresetInfoError}, - {"onGroupPresetInfoError", "(III)V", &method_onGroupPresetInfoError}, + {"onConnectionStateChanged", "(I[B)V", &method_onConnectionStateChanged}, + {"onDeviceAvailable", "([BI)V", &method_onDeviceAvailable}, + {"onFeaturesUpdate", "([BI)V", &method_onFeaturesUpdate}, + {"onActivePresetSelected", "([BI)V", &method_onActivePresetSelected}, + {"onActivePresetGroupSelected", "(II)V", &method_onGroupActivePresetSelected}, + {"onActivePresetSelectError", "([BI)V", &method_onActivePresetSelectError}, + {"onActivePresetGroupSelectError", "(II)V", &method_onGroupActivePresetSelectError}, + {"onPresetInfo", "([BI[Landroid/bluetooth/BluetoothHapPresetInfo;)V", + &method_onPresetInfo}, + {"onGroupPresetInfo", "(II[Landroid/bluetooth/BluetoothHapPresetInfo;)V", + &method_onGroupPresetInfo}, + {"onPresetNameSetError", "([BII)V", &method_onPresetNameSetError}, + {"onGroupPresetNameSetError", "(III)V", &method_onGroupPresetNameSetError}, + {"onPresetInfoError", "([BII)V", &method_onPresetInfoError}, + {"onGroupPresetInfoError", "(III)V", &method_onGroupPresetInfoError}, }; - GET_JAVA_METHODS(env, "com/android/bluetooth/hap/HapClientNativeInterface", - javaMethods); + GET_JAVA_METHODS(env, "com/android/bluetooth/hap/HapClientNativeInterface", javaMethods); const JNIJavaMethod javaHapPresetMethods[] = { - {"", "(ILjava/lang/String;ZZ)V", - &android_bluetooth_BluetoothHapPresetInfo.constructor}, + {"", "(ILjava/lang/String;ZZ)V", + &android_bluetooth_BluetoothHapPresetInfo.constructor}, }; - GET_JAVA_METHODS(env, "android/bluetooth/BluetoothHapPresetInfo", - javaHapPresetMethods); + GET_JAVA_METHODS(env, "android/bluetooth/BluetoothHapPresetInfo", javaHapPresetMethods); return 0; } diff --git a/android/app/jni/com_android_bluetooth_hearing_aid.cpp b/android/app/jni/com_android_bluetooth_hearing_aid.cpp index 2179f52b166..edf8dc58654 100644 --- a/android/app/jni/com_android_bluetooth_hearing_aid.cpp +++ b/android/app/jni/com_android_bluetooth_hearing_aid.cpp @@ -16,15 +16,16 @@ #define LOG_TAG "BluetoothHearingAidServiceJni" -#include "com_android_bluetooth.h" -#include "hardware/bt_hearing_aid.h" - #include + #include +#include "com_android_bluetooth.h" +#include "hardware/bt_hearing_aid.h" + using bluetooth::hearing_aid::ConnectionState; -using bluetooth::hearing_aid::HearingAidInterface; using bluetooth::hearing_aid::HearingAidCallbacks; +using bluetooth::hearing_aid::HearingAidInterface; namespace android { static jmethodID method_onConnectionStateChanged; @@ -37,27 +38,27 @@ static jobject mCallbacksObj = nullptr; static std::shared_timed_mutex callbacks_mutex; class HearingAidCallbacksImpl : public HearingAidCallbacks { - public: +public: ~HearingAidCallbacksImpl() = default; - void OnConnectionState(ConnectionState state, - const RawAddress& bd_addr) override { + void OnConnectionState(ConnectionState state, const RawAddress& bd_addr) override { log::info(""); std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) return; + if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) { + return; + } - ScopedLocalRef addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); + ScopedLocalRef addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); if (!addr.get()) { log::error("Failed to new jbyteArray bd addr for connection state"); return; } - sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), - (jbyte*)&bd_addr); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onConnectionStateChanged, - (jint)state, addr.get()); + sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), (jbyte*)&bd_addr); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onConnectionStateChanged, (jint)state, + addr.get()); } void OnDeviceAvailable(uint8_t capabilities, uint64_t hi_sync_id, @@ -66,20 +67,20 @@ class HearingAidCallbacksImpl : public HearingAidCallbacks { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) return; + if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) { + return; + } - ScopedLocalRef addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); + ScopedLocalRef addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); if (!addr.get()) { log::error("Failed to new jbyteArray bd addr for connection state"); return; } - sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), - (jbyte*)&bd_addr); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onDeviceAvailable, - (jbyte)capabilities, (jlong)hi_sync_id, - addr.get()); + sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), (jbyte*)&bd_addr); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onDeviceAvailable, (jbyte)capabilities, + (jlong)hi_sync_id, addr.get()); } }; @@ -112,8 +113,8 @@ static void initNative(JNIEnv* env, jobject object) { return; } - sHearingAidInterface = (HearingAidInterface*)btInf->get_profile_interface( - BT_PROFILE_HEARING_AID_ID); + sHearingAidInterface = + (HearingAidInterface*)btInf->get_profile_interface(BT_PROFILE_HEARING_AID_ID); if (sHearingAidInterface == nullptr) { log::error("Failed to get Bluetooth Hearing Aid Interface"); return; @@ -143,11 +144,12 @@ static void cleanupNative(JNIEnv* env, jobject /* object */) { } } -static jboolean connectHearingAidNative(JNIEnv* env, jobject /* object */, - jbyteArray address) { +static jboolean connectHearingAidNative(JNIEnv* env, jobject /* object */, jbyteArray address) { log::info(""); std::shared_lock lock(interface_mutex); - if (!sHearingAidInterface) return JNI_FALSE; + if (!sHearingAidInterface) { + return JNI_FALSE; + } jbyte* addr = env->GetByteArrayElements(address, nullptr); if (!addr) { @@ -161,11 +163,12 @@ static jboolean connectHearingAidNative(JNIEnv* env, jobject /* object */, return JNI_TRUE; } -static jboolean disconnectHearingAidNative(JNIEnv* env, jobject /* object */, - jbyteArray address) { +static jboolean disconnectHearingAidNative(JNIEnv* env, jobject /* object */, jbyteArray address) { log::info(""); std::shared_lock lock(interface_mutex); - if (!sHearingAidInterface) return JNI_FALSE; + if (!sHearingAidInterface) { + return JNI_FALSE; + } jbyte* addr = env->GetByteArrayElements(address, nullptr); if (!addr) { @@ -179,10 +182,11 @@ static jboolean disconnectHearingAidNative(JNIEnv* env, jobject /* object */, return JNI_TRUE; } -static jboolean addToAcceptlistNative(JNIEnv* env, jobject /* object */, - jbyteArray address) { +static jboolean addToAcceptlistNative(JNIEnv* env, jobject /* object */, jbyteArray address) { std::shared_lock lock(interface_mutex); - if (!sHearingAidInterface) return JNI_FALSE; + if (!sHearingAidInterface) { + return JNI_FALSE; + } jbyte* addr = env->GetByteArrayElements(address, nullptr); if (!addr) { jniThrowIOException(env, EINVAL); @@ -195,8 +199,7 @@ static jboolean addToAcceptlistNative(JNIEnv* env, jobject /* object */, return JNI_TRUE; } -static void setVolumeNative(JNIEnv* /* env */, jclass /* clazz */, - jint volume) { +static void setVolumeNative(JNIEnv* /* env */, jclass /* clazz */, jint volume) { if (!sHearingAidInterface) { log::error("Failed to get the Bluetooth Hearing Aid Interface"); return; @@ -206,28 +209,24 @@ static void setVolumeNative(JNIEnv* /* env */, jclass /* clazz */, int register_com_android_bluetooth_hearing_aid(JNIEnv* env) { const JNINativeMethod methods[] = { - {"initNative", "()V", (void*)initNative}, - {"cleanupNative", "()V", (void*)cleanupNative}, - {"connectHearingAidNative", "([B)Z", (void*)connectHearingAidNative}, - {"disconnectHearingAidNative", "([B)Z", - (void*)disconnectHearingAidNative}, - {"addToAcceptlistNative", "([B)Z", (void*)addToAcceptlistNative}, - {"setVolumeNative", "(I)V", (void*)setVolumeNative}, + {"initNative", "()V", (void*)initNative}, + {"cleanupNative", "()V", (void*)cleanupNative}, + {"connectHearingAidNative", "([B)Z", (void*)connectHearingAidNative}, + {"disconnectHearingAidNative", "([B)Z", (void*)disconnectHearingAidNative}, + {"addToAcceptlistNative", "([B)Z", (void*)addToAcceptlistNative}, + {"setVolumeNative", "(I)V", (void*)setVolumeNative}, }; const int result = REGISTER_NATIVE_METHODS( - env, "com/android/bluetooth/hearingaid/HearingAidNativeInterface", - methods); + env, "com/android/bluetooth/hearingaid/HearingAidNativeInterface", methods); if (result != 0) { return result; } const JNIJavaMethod javaMethods[] = { - {"onConnectionStateChanged", "(I[B)V", &method_onConnectionStateChanged}, - {"onDeviceAvailable", "(BJ[B)V", &method_onDeviceAvailable}, + {"onConnectionStateChanged", "(I[B)V", &method_onConnectionStateChanged}, + {"onDeviceAvailable", "(BJ[B)V", &method_onDeviceAvailable}, }; - GET_JAVA_METHODS(env, - "com/android/bluetooth/hearingaid/HearingAidNativeInterface", - javaMethods); + GET_JAVA_METHODS(env, "com/android/bluetooth/hearingaid/HearingAidNativeInterface", javaMethods); return 0; } diff --git a/android/app/jni/com_android_bluetooth_hfp.cpp b/android/app/jni/com_android_bluetooth_hfp.cpp index 2407ef7273f..40b587ede3c 100644 --- a/android/app/jni/com_android_bluetooth_hfp.cpp +++ b/android/app/jni/com_android_bluetooth_hfp.cpp @@ -58,39 +58,43 @@ static std::shared_timed_mutex callbacks_mutex; static jbyteArray marshall_bda(RawAddress* bd_addr) { CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid()) return nullptr; + if (!sCallbackEnv.valid()) { + return nullptr; + } jbyteArray addr = sCallbackEnv->NewByteArray(sizeof(RawAddress)); if (!addr) { log::error("Fail to new jbyteArray bd addr"); return nullptr; } - sCallbackEnv->SetByteArrayRegion(addr, 0, sizeof(RawAddress), - (jbyte*)bd_addr); + sCallbackEnv->SetByteArrayRegion(addr, 0, sizeof(RawAddress), (jbyte*)bd_addr); return addr; } class JniHeadsetCallbacks : bluetooth::headset::Callbacks { - public: +public: static bluetooth::headset::Callbacks* GetInstance() { static bluetooth::headset::Callbacks* instance = new JniHeadsetCallbacks(); return instance; } - void ConnectionStateCallback( - bluetooth::headset::bthf_connection_state_t state, - RawAddress* bd_addr) override { + void ConnectionStateCallback(bluetooth::headset::bthf_connection_state_t state, + RawAddress* bd_addr) override { log::info("{} for {}", state, *bd_addr); std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } ScopedLocalRef addr(sCallbackEnv.get(), marshall_bda(bd_addr)); - if (!addr.get()) return; + if (!addr.get()) { + return; + } - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onConnectionStateChanged, - (jint)state, addr.get()); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onConnectionStateChanged, (jint)state, + addr.get()); } void AudioStateCallback(bluetooth::headset::bthf_audio_state_t state, @@ -99,20 +103,26 @@ class JniHeadsetCallbacks : bluetooth::headset::Callbacks { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } ScopedLocalRef addr(sCallbackEnv.get(), marshall_bda(bd_addr)); - if (!addr.get()) return; + if (!addr.get()) { + return; + } - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onAudioStateChanged, - (jint)state, addr.get()); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onAudioStateChanged, (jint)state, + addr.get()); } void VoiceRecognitionCallback(bluetooth::headset::bthf_vr_state_t state, RawAddress* bd_addr) override { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } ScopedLocalRef addr(sCallbackEnv.get(), marshall_bda(bd_addr)); if (!addr.get()) { @@ -120,14 +130,15 @@ class JniHeadsetCallbacks : bluetooth::headset::Callbacks { return; } - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onVrStateChanged, - (jint)state, addr.get()); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onVrStateChanged, (jint)state, addr.get()); } void AnswerCallCallback(RawAddress* bd_addr) override { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } ScopedLocalRef addr(sCallbackEnv.get(), marshall_bda(bd_addr)); if (!addr.get()) { @@ -135,14 +146,15 @@ class JniHeadsetCallbacks : bluetooth::headset::Callbacks { return; } - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onAnswerCall, - addr.get()); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onAnswerCall, addr.get()); } void HangupCallCallback(RawAddress* bd_addr) override { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } ScopedLocalRef addr(sCallbackEnv.get(), marshall_bda(bd_addr)); if (!addr.get()) { @@ -150,15 +162,16 @@ class JniHeadsetCallbacks : bluetooth::headset::Callbacks { return; } - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onHangupCall, - addr.get()); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onHangupCall, addr.get()); } - void VolumeControlCallback(bluetooth::headset::bthf_volume_type_t type, - int volume, RawAddress* bd_addr) override { + void VolumeControlCallback(bluetooth::headset::bthf_volume_type_t type, int volume, + RawAddress* bd_addr) override { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } ScopedLocalRef addr(sCallbackEnv.get(), marshall_bda(bd_addr)); if (!addr.get()) { @@ -166,14 +179,16 @@ class JniHeadsetCallbacks : bluetooth::headset::Callbacks { return; } - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onVolumeChanged, - (jint)type, (jint)volume, addr.get()); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onVolumeChanged, (jint)type, (jint)volume, + addr.get()); } void DialCallCallback(char* number, RawAddress* bd_addr) override { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } ScopedLocalRef addr(sCallbackEnv.get(), marshall_bda(bd_addr)); if (!addr.get()) { @@ -187,16 +202,16 @@ class JniHeadsetCallbacks : bluetooth::headset::Callbacks { number = null_str; } - ScopedLocalRef js_number(sCallbackEnv.get(), - sCallbackEnv->NewStringUTF(number)); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onDialCall, - js_number.get(), addr.get()); + ScopedLocalRef js_number(sCallbackEnv.get(), sCallbackEnv->NewStringUTF(number)); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onDialCall, js_number.get(), addr.get()); } void DtmfCmdCallback(char dtmf, RawAddress* bd_addr) override { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } ScopedLocalRef addr(sCallbackEnv.get(), marshall_bda(bd_addr)); if (!addr.get()) { @@ -205,15 +220,15 @@ class JniHeadsetCallbacks : bluetooth::headset::Callbacks { } // TBD dtmf has changed from int to char - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onSendDtmf, dtmf, - addr.get()); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onSendDtmf, dtmf, addr.get()); } - void NoiseReductionCallback(bluetooth::headset::bthf_nrec_t nrec, - RawAddress* bd_addr) override { + void NoiseReductionCallback(bluetooth::headset::bthf_nrec_t nrec, RawAddress* bd_addr) override { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } ScopedLocalRef addr(sCallbackEnv.get(), marshall_bda(bd_addr)); if (!addr.get()) { @@ -221,60 +236,64 @@ class JniHeadsetCallbacks : bluetooth::headset::Callbacks { return; } sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onNoiseReductionEnable, - nrec == bluetooth::headset::BTHF_NREC_START, - addr.get()); + nrec == bluetooth::headset::BTHF_NREC_START, addr.get()); } - void WbsCallback(bluetooth::headset::bthf_wbs_config_t wbs_config, - RawAddress* bd_addr) override { + void WbsCallback(bluetooth::headset::bthf_wbs_config_t wbs_config, RawAddress* bd_addr) override { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } ScopedLocalRef addr(sCallbackEnv.get(), marshall_bda(bd_addr)); - if (addr.get() == nullptr) return; + if (addr.get() == nullptr) { + return; + } - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onWBS, wbs_config, - addr.get()); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onWBS, wbs_config, addr.get()); } void SwbCallback(bluetooth::headset::bthf_swb_codec_t swb_codec, - bluetooth::headset::bthf_swb_config_t swb_config, - RawAddress* bd_addr) override { + bluetooth::headset::bthf_swb_config_t swb_config, RawAddress* bd_addr) override { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } ScopedLocalRef addr(sCallbackEnv.get(), marshall_bda(bd_addr)); - if (addr.get() == nullptr) return; + if (addr.get() == nullptr) { + return; + } - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onSWB, swb_codec, - swb_config, addr.get()); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onSWB, swb_codec, swb_config, addr.get()); } - void AtChldCallback(bluetooth::headset::bthf_chld_type_t chld, - RawAddress* bd_addr) override { + void AtChldCallback(bluetooth::headset::bthf_chld_type_t chld, RawAddress* bd_addr) override { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } - ScopedLocalRef addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); + ScopedLocalRef addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); if (!addr.get()) { log::error("Fail to new jbyteArray bd addr for audio state"); return; } - sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), - (jbyte*)bd_addr); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onAtChld, chld, - addr.get()); + sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), (jbyte*)bd_addr); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onAtChld, chld, addr.get()); } void AtCnumCallback(RawAddress* bd_addr) override { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } ScopedLocalRef addr(sCallbackEnv.get(), marshall_bda(bd_addr)); if (!addr.get()) { @@ -288,7 +307,9 @@ class JniHeadsetCallbacks : bluetooth::headset::Callbacks { void AtCindCallback(RawAddress* bd_addr) override { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } ScopedLocalRef addr(sCallbackEnv.get(), marshall_bda(bd_addr)); if (!addr.get()) { @@ -302,7 +323,9 @@ class JniHeadsetCallbacks : bluetooth::headset::Callbacks { void AtCopsCallback(RawAddress* bd_addr) override { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } ScopedLocalRef addr(sCallbackEnv.get(), marshall_bda(bd_addr)); if (!addr.get()) { @@ -316,7 +339,9 @@ class JniHeadsetCallbacks : bluetooth::headset::Callbacks { void AtClccCallback(RawAddress* bd_addr) override { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } ScopedLocalRef addr(sCallbackEnv.get(), marshall_bda(bd_addr)); if (!addr.get()) { @@ -330,7 +355,9 @@ class JniHeadsetCallbacks : bluetooth::headset::Callbacks { void UnknownAtCallback(char* at_string, RawAddress* bd_addr) override { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } ScopedLocalRef addr(sCallbackEnv.get(), marshall_bda(bd_addr)); if (!addr.get()) { @@ -344,16 +371,16 @@ class JniHeadsetCallbacks : bluetooth::headset::Callbacks { at_string = null_str; } - ScopedLocalRef js_at_string(sCallbackEnv.get(), - sCallbackEnv->NewStringUTF(at_string)); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onUnknownAt, - js_at_string.get(), addr.get()); + ScopedLocalRef js_at_string(sCallbackEnv.get(), sCallbackEnv->NewStringUTF(at_string)); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onUnknownAt, js_at_string.get(), addr.get()); } void KeyPressedCallback(RawAddress* bd_addr) override { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } ScopedLocalRef addr(sCallbackEnv.get(), marshall_bda(bd_addr)); if (!addr.get()) { @@ -361,17 +388,20 @@ class JniHeadsetCallbacks : bluetooth::headset::Callbacks { return; } - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onKeyPressed, - addr.get()); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onKeyPressed, addr.get()); } void AtBindCallback(char* at_string, RawAddress* bd_addr) override { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } ScopedLocalRef addr(sCallbackEnv.get(), marshall_bda(bd_addr)); - if (addr.get() == nullptr) return; + if (addr.get() == nullptr) { + return; + } char null_str[] = ""; if (!sCallbackEnv.isValidUtf(at_string)) { @@ -379,43 +409,48 @@ class JniHeadsetCallbacks : bluetooth::headset::Callbacks { at_string = null_str; } - ScopedLocalRef js_at_string(sCallbackEnv.get(), - sCallbackEnv->NewStringUTF(at_string)); + ScopedLocalRef js_at_string(sCallbackEnv.get(), sCallbackEnv->NewStringUTF(at_string)); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onAtBind, - js_at_string.get(), addr.get()); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onAtBind, js_at_string.get(), addr.get()); } - void AtBievCallback(bluetooth::headset::bthf_hf_ind_type_t ind_id, - int ind_value, RawAddress* bd_addr) override { + void AtBievCallback(bluetooth::headset::bthf_hf_ind_type_t ind_id, int ind_value, + RawAddress* bd_addr) override { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } ScopedLocalRef addr(sCallbackEnv.get(), marshall_bda(bd_addr)); - if (addr.get() == nullptr) return; + if (addr.get() == nullptr) { + return; + } - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onAtBiev, ind_id, - (jint)ind_value, addr.get()); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onAtBiev, ind_id, (jint)ind_value, + addr.get()); } void AtBiaCallback(bool service, bool roam, bool signal, bool battery, RawAddress* bd_addr) override { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || !mCallbacksObj) return; + if (!sCallbackEnv.valid() || !mCallbacksObj) { + return; + } ScopedLocalRef addr(sCallbackEnv.get(), marshall_bda(bd_addr)); - if (addr.get() == nullptr) return; + if (addr.get() == nullptr) { + return; + } - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onAtBia, service, roam, - signal, battery, addr.get()); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onAtBia, service, roam, signal, battery, + addr.get()); } void DebugDumpCallback(bool /* active */, uint16_t /* codec_id */, - int /* total_num_decoded_frames */, - double /* pkt_loss_ratio */, uint64_t /* begin_ts */, - uint64_t /* end_ts */, + int /* total_num_decoded_frames */, double /* pkt_loss_ratio */, + uint64_t /* begin_ts */, uint64_t /* end_ts */, const char* /* pkt_status_in_hex */, const char* /* pkt_status_in_binary */) override { log::error("Not implemented and shouldn't be called"); @@ -447,16 +482,14 @@ static void initializeNative(JNIEnv* env, jobject object, jint max_hf_clients, } sBluetoothHfpInterface = - (bluetooth::headset::Interface*)btInf->get_profile_interface( - BT_PROFILE_HANDSFREE_ID); + (bluetooth::headset::Interface*)btInf->get_profile_interface(BT_PROFILE_HANDSFREE_ID); if (!sBluetoothHfpInterface) { log::warn("Failed to get Bluetooth Handsfree Interface"); jniThrowIOException(env, EINVAL); return; } - bt_status_t status = - sBluetoothHfpInterface->Init(JniHeadsetCallbacks::GetInstance(), - max_hf_clients, inband_ringing_enabled); + bt_status_t status = sBluetoothHfpInterface->Init(JniHeadsetCallbacks::GetInstance(), + max_hf_clients, inband_ringing_enabled); if (status != BT_STATUS_SUCCESS) { log::error("Failed to initialize Bluetooth Handsfree Interface, status: {}", bt_status_text(status)); @@ -490,8 +523,7 @@ static void cleanupNative(JNIEnv* env, jobject /* object */) { } } -static jboolean connectHfpNative(JNIEnv* env, jobject /* object */, - jbyteArray address) { +static jboolean connectHfpNative(JNIEnv* env, jobject /* object */, jbyteArray address) { std::shared_lock lock(interface_mutex); if (!sBluetoothHfpInterface) { log::warn("sBluetoothHfpInterface is null"); @@ -512,8 +544,7 @@ static jboolean connectHfpNative(JNIEnv* env, jobject /* object */, return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } -static jboolean disconnectHfpNative(JNIEnv* env, jobject /* object */, - jbyteArray address) { +static jboolean disconnectHfpNative(JNIEnv* env, jobject /* object */, jbyteArray address) { std::shared_lock lock(interface_mutex); if (!sBluetoothHfpInterface) { log::warn("sBluetoothHfpInterface is null"); @@ -534,8 +565,7 @@ static jboolean disconnectHfpNative(JNIEnv* env, jobject /* object */, return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } -static jboolean connectAudioNative(JNIEnv* env, jobject /* object */, - jbyteArray address) { +static jboolean connectAudioNative(JNIEnv* env, jobject /* object */, jbyteArray address) { std::shared_lock lock(interface_mutex); if (!sBluetoothHfpInterface) { log::warn("sBluetoothHfpInterface is null"); @@ -548,18 +578,15 @@ static jboolean connectAudioNative(JNIEnv* env, jobject /* object */, return JNI_FALSE; } log::info("device {}", *((RawAddress*)addr)); - bt_status_t status = - sBluetoothHfpInterface->ConnectAudio((RawAddress*)addr, 0); + bt_status_t status = sBluetoothHfpInterface->ConnectAudio((RawAddress*)addr, 0); if (status != BT_STATUS_SUCCESS) { - log::error("Failed HF audio connection, status: {}", - bt_status_text(status)); + log::error("Failed HF audio connection, status: {}", bt_status_text(status)); } env->ReleaseByteArrayElements(address, addr, 0); return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } -static jboolean disconnectAudioNative(JNIEnv* env, jobject /* object */, - jbyteArray address) { +static jboolean disconnectAudioNative(JNIEnv* env, jobject /* object */, jbyteArray address) { std::shared_lock lock(interface_mutex); if (!sBluetoothHfpInterface) { log::warn("sBluetoothHfpInterface is null"); @@ -572,18 +599,15 @@ static jboolean disconnectAudioNative(JNIEnv* env, jobject /* object */, return JNI_FALSE; } log::info("device {}", *((RawAddress*)addr)); - bt_status_t status = - sBluetoothHfpInterface->DisconnectAudio((RawAddress*)addr); + bt_status_t status = sBluetoothHfpInterface->DisconnectAudio((RawAddress*)addr); if (status != BT_STATUS_SUCCESS) { - log::error("Failed HF audio disconnection, status: {}", - bt_status_text(status)); + log::error("Failed HF audio disconnection, status: {}", bt_status_text(status)); } env->ReleaseByteArrayElements(address, addr, 0); return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } -static jboolean isNoiseReductionSupportedNative(JNIEnv* env, - jobject /* object */, +static jboolean isNoiseReductionSupportedNative(JNIEnv* env, jobject /* object */, jbyteArray address) { std::shared_lock lock(interface_mutex); if (!sBluetoothHfpInterface) { @@ -596,14 +620,12 @@ static jboolean isNoiseReductionSupportedNative(JNIEnv* env, jniThrowIOException(env, EINVAL); return JNI_FALSE; } - bt_status_t status = - sBluetoothHfpInterface->isNoiseReductionSupported((RawAddress*)addr); + bt_status_t status = sBluetoothHfpInterface->isNoiseReductionSupported((RawAddress*)addr); env->ReleaseByteArrayElements(address, addr, 0); return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } -static jboolean isVoiceRecognitionSupportedNative(JNIEnv* env, - jobject /* object */, +static jboolean isVoiceRecognitionSupportedNative(JNIEnv* env, jobject /* object */, jbyteArray address) { std::shared_lock lock(interface_mutex); if (!sBluetoothHfpInterface) { @@ -616,14 +638,12 @@ static jboolean isVoiceRecognitionSupportedNative(JNIEnv* env, jniThrowIOException(env, EINVAL); return JNI_FALSE; } - bt_status_t status = - sBluetoothHfpInterface->isVoiceRecognitionSupported((RawAddress*)addr); + bt_status_t status = sBluetoothHfpInterface->isVoiceRecognitionSupported((RawAddress*)addr); env->ReleaseByteArrayElements(address, addr, 0); return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } -static jboolean startVoiceRecognitionNative(JNIEnv* env, jobject /* object */, - jbyteArray address) { +static jboolean startVoiceRecognitionNative(JNIEnv* env, jobject /* object */, jbyteArray address) { std::shared_lock lock(interface_mutex); if (!sBluetoothHfpInterface) { log::warn("sBluetoothHfpInterface is null"); @@ -635,18 +655,15 @@ static jboolean startVoiceRecognitionNative(JNIEnv* env, jobject /* object */, jniThrowIOException(env, EINVAL); return JNI_FALSE; } - bt_status_t status = - sBluetoothHfpInterface->StartVoiceRecognition((RawAddress*)addr); + bt_status_t status = sBluetoothHfpInterface->StartVoiceRecognition((RawAddress*)addr); if (status != BT_STATUS_SUCCESS) { - log::error("Failed to start voice recognition, status: {}", - bt_status_text(status)); + log::error("Failed to start voice recognition, status: {}", bt_status_text(status)); } env->ReleaseByteArrayElements(address, addr, 0); return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } -static jboolean stopVoiceRecognitionNative(JNIEnv* env, jobject /* object */, - jbyteArray address) { +static jboolean stopVoiceRecognitionNative(JNIEnv* env, jobject /* object */, jbyteArray address) { std::shared_lock lock(interface_mutex); if (!sBluetoothHfpInterface) { log::warn("sBluetoothHfpInterface is null"); @@ -658,18 +675,15 @@ static jboolean stopVoiceRecognitionNative(JNIEnv* env, jobject /* object */, jniThrowIOException(env, EINVAL); return JNI_FALSE; } - bt_status_t status = - sBluetoothHfpInterface->StopVoiceRecognition((RawAddress*)addr); + bt_status_t status = sBluetoothHfpInterface->StopVoiceRecognition((RawAddress*)addr); if (status != BT_STATUS_SUCCESS) { - log::error("Failed to stop voice recognition, status: {}", - bt_status_text(status)); + log::error("Failed to stop voice recognition, status: {}", bt_status_text(status)); } env->ReleaseByteArrayElements(address, addr, 0); return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } -static jboolean setVolumeNative(JNIEnv* env, jobject /* object */, - jint volume_type, jint volume, +static jboolean setVolumeNative(JNIEnv* env, jobject /* object */, jint volume_type, jint volume, jbyteArray address) { std::shared_lock lock(interface_mutex); if (!sBluetoothHfpInterface) { @@ -683,8 +697,7 @@ static jboolean setVolumeNative(JNIEnv* env, jobject /* object */, return JNI_FALSE; } bt_status_t status = sBluetoothHfpInterface->VolumeControl( - (bluetooth::headset::bthf_volume_type_t)volume_type, volume, - (RawAddress*)addr); + (bluetooth::headset::bthf_volume_type_t)volume_type, volume, (RawAddress*)addr); if (status != BT_STATUS_SUCCESS) { log::error("FAILED to control volume, status: {}", bt_status_text(status)); } @@ -692,9 +705,8 @@ static jboolean setVolumeNative(JNIEnv* env, jobject /* object */, return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } -static jboolean notifyDeviceStatusNative(JNIEnv* env, jobject /* object */, - jint network_state, jint service_type, - jint signal, jint battery_charge, +static jboolean notifyDeviceStatusNative(JNIEnv* env, jobject /* object */, jint network_state, + jint service_type, jint signal, jint battery_charge, jbyteArray address) { std::shared_lock lock(interface_mutex); if (!sBluetoothHfpInterface) { @@ -708,19 +720,18 @@ static jboolean notifyDeviceStatusNative(JNIEnv* env, jobject /* object */, return JNI_FALSE; } bt_status_t status = sBluetoothHfpInterface->DeviceStatusNotification( - (bluetooth::headset::bthf_network_state_t)network_state, - (bluetooth::headset::bthf_service_type_t)service_type, signal, - battery_charge, (RawAddress*)addr); + (bluetooth::headset::bthf_network_state_t)network_state, + (bluetooth::headset::bthf_service_type_t)service_type, signal, battery_charge, + (RawAddress*)addr); env->ReleaseByteArrayElements(address, addr, 0); if (status != BT_STATUS_SUCCESS) { - log::error("FAILED to notify device status, status: {}", - bt_status_text(status)); + log::error("FAILED to notify device status, status: {}", bt_status_text(status)); } return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } -static jboolean copsResponseNative(JNIEnv* env, jobject /* object */, - jstring operator_str, jbyteArray address) { +static jboolean copsResponseNative(JNIEnv* env, jobject /* object */, jstring operator_str, + jbyteArray address) { std::shared_lock lock(interface_mutex); if (!sBluetoothHfpInterface) { log::warn("sBluetoothHfpInterface is null"); @@ -733,20 +744,17 @@ static jboolean copsResponseNative(JNIEnv* env, jobject /* object */, return JNI_FALSE; } const char* operator_name = env->GetStringUTFChars(operator_str, nullptr); - bt_status_t status = - sBluetoothHfpInterface->CopsResponse(operator_name, (RawAddress*)addr); + bt_status_t status = sBluetoothHfpInterface->CopsResponse(operator_name, (RawAddress*)addr); if (status != BT_STATUS_SUCCESS) { - log::error("Failed sending cops response, status: {}", - bt_status_text(status)); + log::error("Failed sending cops response, status: {}", bt_status_text(status)); } env->ReleaseByteArrayElements(address, addr, 0); env->ReleaseStringUTFChars(operator_str, operator_name); return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } -static jboolean cindResponseNative(JNIEnv* env, jobject /* object */, - jint service, jint num_active, jint num_held, - jint call_state, jint signal, jint roam, +static jboolean cindResponseNative(JNIEnv* env, jobject /* object */, jint service, jint num_active, + jint num_held, jint call_state, jint signal, jint roam, jint battery_charge, jbyteArray address) { std::shared_lock lock(interface_mutex); if (!sBluetoothHfpInterface) { @@ -760,9 +768,8 @@ static jboolean cindResponseNative(JNIEnv* env, jobject /* object */, return JNI_FALSE; } bt_status_t status = sBluetoothHfpInterface->CindResponse( - service, num_active, num_held, - (bluetooth::headset::bthf_call_state_t)call_state, signal, roam, - battery_charge, (RawAddress*)addr); + service, num_active, num_held, (bluetooth::headset::bthf_call_state_t)call_state, signal, + roam, battery_charge, (RawAddress*)addr); if (status != BT_STATUS_SUCCESS) { log::error("failed, status: {}", bt_status_text(status)); } @@ -770,8 +777,7 @@ static jboolean cindResponseNative(JNIEnv* env, jobject /* object */, return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } -static jboolean atResponseStringNative(JNIEnv* env, jobject /* object */, - jstring response_str, +static jboolean atResponseStringNative(JNIEnv* env, jobject /* object */, jstring response_str, jbyteArray address) { std::shared_lock lock(interface_mutex); if (!sBluetoothHfpInterface) { @@ -785,20 +791,17 @@ static jboolean atResponseStringNative(JNIEnv* env, jobject /* object */, return JNI_FALSE; } const char* response = env->GetStringUTFChars(response_str, nullptr); - bt_status_t status = - sBluetoothHfpInterface->FormattedAtResponse(response, (RawAddress*)addr); + bt_status_t status = sBluetoothHfpInterface->FormattedAtResponse(response, (RawAddress*)addr); if (status != BT_STATUS_SUCCESS) { - log::error("Failed formatted AT response, status: {}", - bt_status_text(status)); + log::error("Failed formatted AT response, status: {}", bt_status_text(status)); } env->ReleaseByteArrayElements(address, addr, 0); env->ReleaseStringUTFChars(response_str, response); return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } -static jboolean atResponseCodeNative(JNIEnv* env, jobject /* object */, - jint response_code, jint cmee_code, - jbyteArray address) { +static jboolean atResponseCodeNative(JNIEnv* env, jobject /* object */, jint response_code, + jint cmee_code, jbyteArray address) { std::shared_lock lock(interface_mutex); if (!sBluetoothHfpInterface) { log::warn("sBluetoothHfpInterface is null"); @@ -811,8 +814,7 @@ static jboolean atResponseCodeNative(JNIEnv* env, jobject /* object */, return JNI_FALSE; } bt_status_t status = sBluetoothHfpInterface->AtResponse( - (bluetooth::headset::bthf_at_response_t)response_code, cmee_code, - (RawAddress*)addr); + (bluetooth::headset::bthf_at_response_t)response_code, cmee_code, (RawAddress*)addr); if (status != BT_STATUS_SUCCESS) { log::error("Failed AT response, status: {}", bt_status_text(status)); } @@ -820,9 +822,8 @@ static jboolean atResponseCodeNative(JNIEnv* env, jobject /* object */, return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } -static jboolean clccResponseNative(JNIEnv* env, jobject /* object */, - jint index, jint dir, jint callStatus, - jint mode, jboolean mpty, jstring number_str, +static jboolean clccResponseNative(JNIEnv* env, jobject /* object */, jint index, jint dir, + jint callStatus, jint mode, jboolean mpty, jstring number_str, jint type, jbyteArray address) { std::shared_lock lock(interface_mutex); if (!sBluetoothHfpInterface) { @@ -840,16 +841,14 @@ static jboolean clccResponseNative(JNIEnv* env, jobject /* object */, number = env->GetStringUTFChars(number_str, nullptr); } bt_status_t status = sBluetoothHfpInterface->ClccResponse( - index, (bluetooth::headset::bthf_call_direction_t)dir, - (bluetooth::headset::bthf_call_state_t)callStatus, - (bluetooth::headset::bthf_call_mode_t)mode, - mpty ? bluetooth::headset::BTHF_CALL_MPTY_TYPE_MULTI - : bluetooth::headset::BTHF_CALL_MPTY_TYPE_SINGLE, - number, (bluetooth::headset::bthf_call_addrtype_t)type, - (RawAddress*)addr); + index, (bluetooth::headset::bthf_call_direction_t)dir, + (bluetooth::headset::bthf_call_state_t)callStatus, + (bluetooth::headset::bthf_call_mode_t)mode, + mpty ? bluetooth::headset::BTHF_CALL_MPTY_TYPE_MULTI + : bluetooth::headset::BTHF_CALL_MPTY_TYPE_SINGLE, + number, (bluetooth::headset::bthf_call_addrtype_t)type, (RawAddress*)addr); if (status != BT_STATUS_SUCCESS) { - log::error("Failed sending CLCC response, status: {}", - bt_status_text(status)); + log::error("Failed sending CLCC response, status: {}", bt_status_text(status)); } env->ReleaseByteArrayElements(address, addr, 0); if (number) { @@ -858,11 +857,9 @@ static jboolean clccResponseNative(JNIEnv* env, jobject /* object */, return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } -static jboolean phoneStateChangeNative(JNIEnv* env, jobject /* object */, - jint num_active, jint num_held, - jint call_state, jstring number_str, - jint type, jstring name_str, - jbyteArray address) { +static jboolean phoneStateChangeNative(JNIEnv* env, jobject /* object */, jint num_active, + jint num_held, jint call_state, jstring number_str, + jint type, jstring name_str, jbyteArray address) { std::shared_lock lock(interface_mutex); if (!sBluetoothHfpInterface) { log::warn("sBluetoothHfpInterface is null"); @@ -880,12 +877,10 @@ static jboolean phoneStateChangeNative(JNIEnv* env, jobject /* object */, name = env->GetStringUTFChars(name_str, nullptr); } bt_status_t status = sBluetoothHfpInterface->PhoneStateChange( - num_active, num_held, (bluetooth::headset::bthf_call_state_t)call_state, - number, (bluetooth::headset::bthf_call_addrtype_t)type, name, - (RawAddress*)addr); + num_active, num_held, (bluetooth::headset::bthf_call_state_t)call_state, number, + (bluetooth::headset::bthf_call_addrtype_t)type, name, (RawAddress*)addr); if (status != BT_STATUS_SUCCESS) { - log::error("Failed report phone state change, status: {}", - bt_status_text(status)); + log::error("Failed report phone state change, status: {}", bt_status_text(status)); } env->ReleaseStringUTFChars(number_str, number); if (name != nullptr) { @@ -895,8 +890,7 @@ static jboolean phoneStateChangeNative(JNIEnv* env, jobject /* object */, return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } -static jboolean setScoAllowedNative(JNIEnv* /* env */, jobject /* object */, - jboolean value) { +static jboolean setScoAllowedNative(JNIEnv* /* env */, jobject /* object */, jboolean value) { std::shared_lock lock(interface_mutex); if (!sBluetoothHfpInterface) { log::warn("sBluetoothHfpInterface is null"); @@ -909,8 +903,8 @@ static jboolean setScoAllowedNative(JNIEnv* /* env */, jobject /* object */, return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } -static jboolean sendBsirNative(JNIEnv* env, jobject /* object */, - jboolean value, jbyteArray address) { +static jboolean sendBsirNative(JNIEnv* env, jobject /* object */, jboolean value, + jbyteArray address) { std::shared_lock lock(interface_mutex); if (!sBluetoothHfpInterface) { log::warn("sBluetoothHfpInterface is null"); @@ -922,18 +916,15 @@ static jboolean sendBsirNative(JNIEnv* env, jobject /* object */, jniThrowIOException(env, EINVAL); return JNI_FALSE; } - bt_status_t status = - sBluetoothHfpInterface->SendBsir(value == JNI_TRUE, (RawAddress*)addr); + bt_status_t status = sBluetoothHfpInterface->SendBsir(value == JNI_TRUE, (RawAddress*)addr); if (status != BT_STATUS_SUCCESS) { - log::error("Failed sending BSIR, value={}, status={}", value, - bt_status_text(status)); + log::error("Failed sending BSIR, value={}, status={}", value, bt_status_text(status)); } env->ReleaseByteArrayElements(address, addr, 0); return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } -static jboolean setActiveDeviceNative(JNIEnv* env, jobject /* object */, - jbyteArray address) { +static jboolean setActiveDeviceNative(JNIEnv* env, jobject /* object */, jbyteArray address) { std::shared_lock lock(interface_mutex); if (!sBluetoothHfpInterface) { log::warn("sBluetoothHfpInterface is null"); @@ -945,18 +936,15 @@ static jboolean setActiveDeviceNative(JNIEnv* env, jobject /* object */, jniThrowIOException(env, EINVAL); return JNI_FALSE; } - bt_status_t status = - sBluetoothHfpInterface->SetActiveDevice((RawAddress*)addr); + bt_status_t status = sBluetoothHfpInterface->SetActiveDevice((RawAddress*)addr); if (status != BT_STATUS_SUCCESS) { - log::error("Failed to set active device, status: {}", - bt_status_text(status)); + log::error("Failed to set active device, status: {}", bt_status_text(status)); } env->ReleaseByteArrayElements(address, addr, 0); return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } -static jboolean enableSwbNative(JNIEnv* env, jobject /* object */, - jint swbCodec, jboolean enable, +static jboolean enableSwbNative(JNIEnv* env, jobject /* object */, jint swbCodec, jboolean enable, jbyteArray address) { std::shared_lock lock(interface_mutex); if (!sBluetoothHfpInterface) { @@ -970,8 +958,7 @@ static jboolean enableSwbNative(JNIEnv* env, jobject /* object */, return JNI_FALSE; } bt_status_t ret = sBluetoothHfpInterface->EnableSwb( - (bluetooth::headset::bthf_swb_codec_t)swbCodec, (bool)enable, - (RawAddress*)addr); + (bluetooth::headset::bthf_swb_codec_t)swbCodec, (bool)enable, (RawAddress*)addr); if (ret != BT_STATUS_SUCCESS) { ALOGE("%s: Failed to %s", __func__, (enable ? "enable" : "disable")); return JNI_FALSE; @@ -982,70 +969,60 @@ static jboolean enableSwbNative(JNIEnv* env, jobject /* object */, int register_com_android_bluetooth_hfp(JNIEnv* env) { const JNINativeMethod methods[] = { - {"initializeNative", "(IZ)V", (void*)initializeNative}, - {"cleanupNative", "()V", (void*)cleanupNative}, - {"connectHfpNative", "([B)Z", (void*)connectHfpNative}, - {"disconnectHfpNative", "([B)Z", (void*)disconnectHfpNative}, - {"connectAudioNative", "([B)Z", (void*)connectAudioNative}, - {"disconnectAudioNative", "([B)Z", (void*)disconnectAudioNative}, - {"isNoiseReductionSupportedNative", "([B)Z", - (void*)isNoiseReductionSupportedNative}, - {"isVoiceRecognitionSupportedNative", "([B)Z", - (void*)isVoiceRecognitionSupportedNative}, - {"startVoiceRecognitionNative", "([B)Z", - (void*)startVoiceRecognitionNative}, - {"stopVoiceRecognitionNative", "([B)Z", - (void*)stopVoiceRecognitionNative}, - {"setVolumeNative", "(II[B)Z", (void*)setVolumeNative}, - {"notifyDeviceStatusNative", "(IIII[B)Z", - (void*)notifyDeviceStatusNative}, - {"copsResponseNative", "(Ljava/lang/String;[B)Z", - (void*)copsResponseNative}, - {"cindResponseNative", "(IIIIIII[B)Z", (void*)cindResponseNative}, - {"atResponseStringNative", "(Ljava/lang/String;[B)Z", - (void*)atResponseStringNative}, - {"atResponseCodeNative", "(II[B)Z", (void*)atResponseCodeNative}, - {"clccResponseNative", "(IIIIZLjava/lang/String;I[B)Z", - (void*)clccResponseNative}, - {"phoneStateChangeNative", - "(IIILjava/lang/String;ILjava/lang/String;[B)Z", - (void*)phoneStateChangeNative}, - {"setScoAllowedNative", "(Z)Z", (void*)setScoAllowedNative}, - {"sendBsirNative", "(Z[B)Z", (void*)sendBsirNative}, - {"setActiveDeviceNative", "([B)Z", (void*)setActiveDeviceNative}, - {"enableSwbNative", "(IZ[B)Z", (void*)enableSwbNative}, + {"initializeNative", "(IZ)V", (void*)initializeNative}, + {"cleanupNative", "()V", (void*)cleanupNative}, + {"connectHfpNative", "([B)Z", (void*)connectHfpNative}, + {"disconnectHfpNative", "([B)Z", (void*)disconnectHfpNative}, + {"connectAudioNative", "([B)Z", (void*)connectAudioNative}, + {"disconnectAudioNative", "([B)Z", (void*)disconnectAudioNative}, + {"isNoiseReductionSupportedNative", "([B)Z", (void*)isNoiseReductionSupportedNative}, + {"isVoiceRecognitionSupportedNative", "([B)Z", (void*)isVoiceRecognitionSupportedNative}, + {"startVoiceRecognitionNative", "([B)Z", (void*)startVoiceRecognitionNative}, + {"stopVoiceRecognitionNative", "([B)Z", (void*)stopVoiceRecognitionNative}, + {"setVolumeNative", "(II[B)Z", (void*)setVolumeNative}, + {"notifyDeviceStatusNative", "(IIII[B)Z", (void*)notifyDeviceStatusNative}, + {"copsResponseNative", "(Ljava/lang/String;[B)Z", (void*)copsResponseNative}, + {"cindResponseNative", "(IIIIIII[B)Z", (void*)cindResponseNative}, + {"atResponseStringNative", "(Ljava/lang/String;[B)Z", (void*)atResponseStringNative}, + {"atResponseCodeNative", "(II[B)Z", (void*)atResponseCodeNative}, + {"clccResponseNative", "(IIIIZLjava/lang/String;I[B)Z", (void*)clccResponseNative}, + {"phoneStateChangeNative", "(IIILjava/lang/String;ILjava/lang/String;[B)Z", + (void*)phoneStateChangeNative}, + {"setScoAllowedNative", "(Z)Z", (void*)setScoAllowedNative}, + {"sendBsirNative", "(Z[B)Z", (void*)sendBsirNative}, + {"setActiveDeviceNative", "([B)Z", (void*)setActiveDeviceNative}, + {"enableSwbNative", "(IZ[B)Z", (void*)enableSwbNative}, }; - const int result = REGISTER_NATIVE_METHODS( - env, "com/android/bluetooth/hfp/HeadsetNativeInterface", methods); + const int result = + REGISTER_NATIVE_METHODS(env, "com/android/bluetooth/hfp/HeadsetNativeInterface", methods); if (result != 0) { return result; } const JNIJavaMethod javaMethods[] = { - {"onConnectionStateChanged", "(I[B)V", &method_onConnectionStateChanged}, - {"onAudioStateChanged", "(I[B)V", &method_onAudioStateChanged}, - {"onVrStateChanged", "(I[B)V", &method_onVrStateChanged}, - {"onAnswerCall", "([B)V", &method_onAnswerCall}, - {"onHangupCall", "([B)V", &method_onHangupCall}, - {"onVolumeChanged", "(II[B)V", &method_onVolumeChanged}, - {"onDialCall", "(Ljava/lang/String;[B)V", &method_onDialCall}, - {"onSendDtmf", "(I[B)V", &method_onSendDtmf}, - {"onNoiseReductionEnable", "(Z[B)V", &method_onNoiseReductionEnable}, - {"onWBS", "(I[B)V", &method_onWBS}, - {"onSWB", "(II[B)V", &method_onSWB}, - {"onAtChld", "(I[B)V", &method_onAtChld}, - {"onAtCnum", "([B)V", &method_onAtCnum}, - {"onAtCind", "([B)V", &method_onAtCind}, - {"onAtCops", "([B)V", &method_onAtCops}, - {"onAtClcc", "([B)V", &method_onAtClcc}, - {"onUnknownAt", "(Ljava/lang/String;[B)V", &method_onUnknownAt}, - {"onKeyPressed", "([B)V", &method_onKeyPressed}, - {"onATBind", "(Ljava/lang/String;[B)V", &method_onAtBind}, - {"onATBiev", "(II[B)V", &method_onAtBiev}, - {"onAtBia", "(ZZZZ[B)V", &method_onAtBia}, + {"onConnectionStateChanged", "(I[B)V", &method_onConnectionStateChanged}, + {"onAudioStateChanged", "(I[B)V", &method_onAudioStateChanged}, + {"onVrStateChanged", "(I[B)V", &method_onVrStateChanged}, + {"onAnswerCall", "([B)V", &method_onAnswerCall}, + {"onHangupCall", "([B)V", &method_onHangupCall}, + {"onVolumeChanged", "(II[B)V", &method_onVolumeChanged}, + {"onDialCall", "(Ljava/lang/String;[B)V", &method_onDialCall}, + {"onSendDtmf", "(I[B)V", &method_onSendDtmf}, + {"onNoiseReductionEnable", "(Z[B)V", &method_onNoiseReductionEnable}, + {"onWBS", "(I[B)V", &method_onWBS}, + {"onSWB", "(II[B)V", &method_onSWB}, + {"onAtChld", "(I[B)V", &method_onAtChld}, + {"onAtCnum", "([B)V", &method_onAtCnum}, + {"onAtCind", "([B)V", &method_onAtCind}, + {"onAtCops", "([B)V", &method_onAtCops}, + {"onAtClcc", "([B)V", &method_onAtClcc}, + {"onUnknownAt", "(Ljava/lang/String;[B)V", &method_onUnknownAt}, + {"onKeyPressed", "([B)V", &method_onKeyPressed}, + {"onATBind", "(Ljava/lang/String;[B)V", &method_onAtBind}, + {"onATBiev", "(II[B)V", &method_onAtBiev}, + {"onAtBia", "(ZZZZ[B)V", &method_onAtBia}, }; - GET_JAVA_METHODS(env, "com/android/bluetooth/hfp/HeadsetNativeInterface", - javaMethods); + GET_JAVA_METHODS(env, "com/android/bluetooth/hfp/HeadsetNativeInterface", javaMethods); return 0; } diff --git a/android/app/jni/com_android_bluetooth_hfpclient.cpp b/android/app/jni/com_android_bluetooth_hfpclient.cpp index 02388603f0f..f42d8dd2104 100644 --- a/android/app/jni/com_android_bluetooth_hfpclient.cpp +++ b/android/app/jni/com_android_bluetooth_hfpclient.cpp @@ -56,117 +56,138 @@ static jmethodID method_onUnknownEvent; static jbyteArray marshall_bda(const RawAddress* bd_addr) { CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid()) return NULL; + if (!sCallbackEnv.valid()) { + return NULL; + } jbyteArray addr = sCallbackEnv->NewByteArray(sizeof(RawAddress)); if (!addr) { log::error("Fail to new jbyteArray bd addr"); return NULL; } - sCallbackEnv->SetByteArrayRegion(addr, 0, sizeof(RawAddress), - (jbyte*)bd_addr); + sCallbackEnv->SetByteArrayRegion(addr, 0, sizeof(RawAddress), (jbyte*)bd_addr); return addr; } -static void connection_state_cb(const RawAddress* bd_addr, - bthf_client_connection_state_t state, - unsigned int peer_feat, - unsigned int chld_feat) { +static void connection_state_cb(const RawAddress* bd_addr, bthf_client_connection_state_t state, + unsigned int peer_feat, unsigned int chld_feat) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == NULL) return; + if (!sCallbackEnv.valid() || mCallbacksObj == NULL) { + return; + } ScopedLocalRef addr(sCallbackEnv.get(), marshall_bda(bd_addr)); - if (!addr.get()) return; + if (!addr.get()) { + return; + } log::debug("state {} peer_feat {} chld_feat {}", state, peer_feat, chld_feat); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onConnectionStateChanged, - (jint)state, (jint)peer_feat, (jint)chld_feat, - addr.get()); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onConnectionStateChanged, (jint)state, + (jint)peer_feat, (jint)chld_feat, addr.get()); } -static void audio_state_cb(const RawAddress* bd_addr, - bthf_client_audio_state_t state) { +static void audio_state_cb(const RawAddress* bd_addr, bthf_client_audio_state_t state) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == NULL) return; + if (!sCallbackEnv.valid() || mCallbacksObj == NULL) { + return; + } ScopedLocalRef addr(sCallbackEnv.get(), marshall_bda(bd_addr)); - if (!addr.get()) return; + if (!addr.get()) { + return; + } - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onAudioStateChanged, - (jint)state, addr.get()); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onAudioStateChanged, (jint)state, addr.get()); } static void vr_cmd_cb(const RawAddress* bd_addr, bthf_client_vr_state_t state) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == NULL) return; + if (!sCallbackEnv.valid() || mCallbacksObj == NULL) { + return; + } ScopedLocalRef addr(sCallbackEnv.get(), marshall_bda(bd_addr)); - if (!addr.get()) return; + if (!addr.get()) { + return; + } - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onVrStateChanged, - (jint)state, addr.get()); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onVrStateChanged, (jint)state, addr.get()); } -static void network_state_cb(const RawAddress* bd_addr, - bthf_client_network_state_t state) { +static void network_state_cb(const RawAddress* bd_addr, bthf_client_network_state_t state) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == NULL) return; + if (!sCallbackEnv.valid() || mCallbacksObj == NULL) { + return; + } ScopedLocalRef addr(sCallbackEnv.get(), marshall_bda(bd_addr)); - if (!addr.get()) return; + if (!addr.get()) { + return; + } - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onNetworkState, - (jint)state, addr.get()); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onNetworkState, (jint)state, addr.get()); } -static void network_roaming_cb(const RawAddress* bd_addr, - bthf_client_service_type_t type) { +static void network_roaming_cb(const RawAddress* bd_addr, bthf_client_service_type_t type) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == NULL) return; + if (!sCallbackEnv.valid() || mCallbacksObj == NULL) { + return; + } ScopedLocalRef addr(sCallbackEnv.get(), marshall_bda(bd_addr)); - if (!addr.get()) return; + if (!addr.get()) { + return; + } - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onNetworkRoaming, - (jint)type, addr.get()); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onNetworkRoaming, (jint)type, addr.get()); } static void network_signal_cb(const RawAddress* bd_addr, int signal) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == NULL) return; + if (!sCallbackEnv.valid() || mCallbacksObj == NULL) { + return; + } ScopedLocalRef addr(sCallbackEnv.get(), marshall_bda(bd_addr)); - if (!addr.get()) return; + if (!addr.get()) { + return; + } - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onNetworkSignal, - (jint)signal, addr.get()); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onNetworkSignal, (jint)signal, addr.get()); } static void battery_level_cb(const RawAddress* bd_addr, int level) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == NULL) return; + if (!sCallbackEnv.valid() || mCallbacksObj == NULL) { + return; + } ScopedLocalRef addr(sCallbackEnv.get(), marshall_bda(bd_addr)); - if (!addr.get()) return; + if (!addr.get()) { + return; + } - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onBatteryLevel, - (jint)level, addr.get()); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onBatteryLevel, (jint)level, addr.get()); } static void current_operator_cb(const RawAddress* bd_addr, const char* name) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == NULL) return; + if (!sCallbackEnv.valid() || mCallbacksObj == NULL) { + return; + } ScopedLocalRef addr(sCallbackEnv.get(), marshall_bda(bd_addr)); - if (!addr.get()) return; + if (!addr.get()) { + return; + } const char null_str[] = ""; if (!sCallbackEnv.isValidUtf(name)) { @@ -174,72 +195,84 @@ static void current_operator_cb(const RawAddress* bd_addr, const char* name) { name = null_str; } - ScopedLocalRef js_name(sCallbackEnv.get(), - sCallbackEnv->NewStringUTF(name)); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onCurrentOperator, - js_name.get(), addr.get()); + ScopedLocalRef js_name(sCallbackEnv.get(), sCallbackEnv->NewStringUTF(name)); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onCurrentOperator, js_name.get(), addr.get()); } static void call_cb(const RawAddress* bd_addr, bthf_client_call_t call) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == NULL) return; + if (!sCallbackEnv.valid() || mCallbacksObj == NULL) { + return; + } ScopedLocalRef addr(sCallbackEnv.get(), marshall_bda(bd_addr)); - if (!addr.get()) return; + if (!addr.get()) { + return; + } - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onCall, (jint)call, - addr.get()); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onCall, (jint)call, addr.get()); } -static void callsetup_cb(const RawAddress* bd_addr, - bthf_client_callsetup_t callsetup) { +static void callsetup_cb(const RawAddress* bd_addr, bthf_client_callsetup_t callsetup) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == NULL) return; + if (!sCallbackEnv.valid() || mCallbacksObj == NULL) { + return; + } ScopedLocalRef addr(sCallbackEnv.get(), marshall_bda(bd_addr)); - if (!addr.get()) return; + if (!addr.get()) { + return; + } log::debug("callsetup_cb bdaddr {}", *bd_addr); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onCallSetup, - (jint)callsetup, addr.get()); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onCallSetup, (jint)callsetup, addr.get()); } -static void callheld_cb(const RawAddress* bd_addr, - bthf_client_callheld_t callheld) { +static void callheld_cb(const RawAddress* bd_addr, bthf_client_callheld_t callheld) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == NULL) return; + if (!sCallbackEnv.valid() || mCallbacksObj == NULL) { + return; + } ScopedLocalRef addr(sCallbackEnv.get(), marshall_bda(bd_addr)); - if (!addr.get()) return; + if (!addr.get()) { + return; + } - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onCallHeld, (jint)callheld, - addr.get()); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onCallHeld, (jint)callheld, addr.get()); } -static void resp_and_hold_cb(const RawAddress* bd_addr, - bthf_client_resp_and_hold_t resp_and_hold) { +static void resp_and_hold_cb(const RawAddress* bd_addr, bthf_client_resp_and_hold_t resp_and_hold) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == NULL) return; + if (!sCallbackEnv.valid() || mCallbacksObj == NULL) { + return; + } ScopedLocalRef addr(sCallbackEnv.get(), marshall_bda(bd_addr)); - if (!addr.get()) return; + if (!addr.get()) { + return; + } - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onRespAndHold, - (jint)resp_and_hold, addr.get()); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onRespAndHold, (jint)resp_and_hold, + addr.get()); } static void clip_cb(const RawAddress* bd_addr, const char* number) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == NULL) return; + if (!sCallbackEnv.valid() || mCallbacksObj == NULL) { + return; + } ScopedLocalRef addr(sCallbackEnv.get(), marshall_bda(bd_addr)); - if (!addr.get()) return; + if (!addr.get()) { + return; + } const char null_str[] = ""; if (!sCallbackEnv.isValidUtf(number)) { @@ -247,19 +280,21 @@ static void clip_cb(const RawAddress* bd_addr, const char* number) { number = null_str; } - ScopedLocalRef js_number(sCallbackEnv.get(), - sCallbackEnv->NewStringUTF(number)); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onClip, js_number.get(), - addr.get()); + ScopedLocalRef js_number(sCallbackEnv.get(), sCallbackEnv->NewStringUTF(number)); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onClip, js_number.get(), addr.get()); } static void call_waiting_cb(const RawAddress* bd_addr, const char* number) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == NULL) return; + if (!sCallbackEnv.valid() || mCallbacksObj == NULL) { + return; + } ScopedLocalRef addr(sCallbackEnv.get(), marshall_bda(bd_addr)); - if (!addr.get()) return; + if (!addr.get()) { + return; + } const char null_str[] = ""; if (!sCallbackEnv.isValidUtf(number)) { @@ -267,23 +302,23 @@ static void call_waiting_cb(const RawAddress* bd_addr, const char* number) { number = null_str; } - ScopedLocalRef js_number(sCallbackEnv.get(), - sCallbackEnv->NewStringUTF(number)); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onCallWaiting, - js_number.get(), addr.get()); + ScopedLocalRef js_number(sCallbackEnv.get(), sCallbackEnv->NewStringUTF(number)); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onCallWaiting, js_number.get(), addr.get()); } -static void current_calls_cb(const RawAddress* bd_addr, int index, - bthf_client_call_direction_t dir, - bthf_client_call_state_t state, - bthf_client_call_mpty_type_t mpty, +static void current_calls_cb(const RawAddress* bd_addr, int index, bthf_client_call_direction_t dir, + bthf_client_call_state_t state, bthf_client_call_mpty_type_t mpty, const char* number) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == NULL) return; + if (!sCallbackEnv.valid() || mCallbacksObj == NULL) { + return; + } ScopedLocalRef addr(sCallbackEnv.get(), marshall_bda(bd_addr)); - if (!addr.get()) return; + if (!addr.get()) { + return; + } const char null_str[] = ""; if (!sCallbackEnv.isValidUtf(number)) { @@ -291,44 +326,54 @@ static void current_calls_cb(const RawAddress* bd_addr, int index, number = null_str; } - ScopedLocalRef js_number(sCallbackEnv.get(), - sCallbackEnv->NewStringUTF(number)); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onCurrentCalls, index, dir, - state, mpty, js_number.get(), addr.get()); + ScopedLocalRef js_number(sCallbackEnv.get(), sCallbackEnv->NewStringUTF(number)); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onCurrentCalls, index, dir, state, mpty, + js_number.get(), addr.get()); } -static void volume_change_cb(const RawAddress* bd_addr, - bthf_client_volume_type_t type, int volume) { +static void volume_change_cb(const RawAddress* bd_addr, bthf_client_volume_type_t type, + int volume) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == NULL) return; + if (!sCallbackEnv.valid() || mCallbacksObj == NULL) { + return; + } ScopedLocalRef addr(sCallbackEnv.get(), marshall_bda(bd_addr)); - if (!addr.get()) return; - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onVolumeChange, (jint)type, - (jint)volume, addr.get()); + if (!addr.get()) { + return; + } + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onVolumeChange, (jint)type, (jint)volume, + addr.get()); } -static void cmd_complete_cb(const RawAddress* bd_addr, - bthf_client_cmd_complete_t type, int cme) { +static void cmd_complete_cb(const RawAddress* bd_addr, bthf_client_cmd_complete_t type, int cme) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == NULL) return; + if (!sCallbackEnv.valid() || mCallbacksObj == NULL) { + return; + } ScopedLocalRef addr(sCallbackEnv.get(), marshall_bda(bd_addr)); - if (!addr.get()) return; - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onCmdResult, (jint)type, - (jint)cme, addr.get()); + if (!addr.get()) { + return; + } + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onCmdResult, (jint)type, (jint)cme, + addr.get()); } static void subscriber_info_cb(const RawAddress* bd_addr, const char* name, bthf_client_subscriber_service_type_t type) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == NULL) return; + if (!sCallbackEnv.valid() || mCallbacksObj == NULL) { + return; + } ScopedLocalRef addr(sCallbackEnv.get(), marshall_bda(bd_addr)); - if (!addr.get()) return; + if (!addr.get()) { + return; + } const char null_str[] = ""; if (!sCallbackEnv.isValidUtf(name)) { @@ -336,32 +381,36 @@ static void subscriber_info_cb(const RawAddress* bd_addr, const char* name, name = null_str; } - ScopedLocalRef js_name(sCallbackEnv.get(), - sCallbackEnv->NewStringUTF(name)); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onSubscriberInfo, - js_name.get(), (jint)type, addr.get()); + ScopedLocalRef js_name(sCallbackEnv.get(), sCallbackEnv->NewStringUTF(name)); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onSubscriberInfo, js_name.get(), (jint)type, + addr.get()); } -static void in_band_ring_cb(const RawAddress* bd_addr, - bthf_client_in_band_ring_state_t in_band) { +static void in_band_ring_cb(const RawAddress* bd_addr, bthf_client_in_band_ring_state_t in_band) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == NULL) return; + if (!sCallbackEnv.valid() || mCallbacksObj == NULL) { + return; + } ScopedLocalRef addr(sCallbackEnv.get(), marshall_bda(bd_addr)); - if (!addr.get()) return; - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onInBandRing, - (jint)in_band, addr.get()); + if (!addr.get()) { + return; + } + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onInBandRing, (jint)in_band, addr.get()); } -static void last_voice_tag_number_cb(const RawAddress* bd_addr, - const char* number) { +static void last_voice_tag_number_cb(const RawAddress* bd_addr, const char* number) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == NULL) return; + if (!sCallbackEnv.valid() || mCallbacksObj == NULL) { + return; + } ScopedLocalRef addr(sCallbackEnv.get(), marshall_bda(bd_addr)); - if (!addr.get()) return; + if (!addr.get()) { + return; + } const char null_str[] = ""; if (!sCallbackEnv.isValidUtf(number)) { @@ -369,62 +418,65 @@ static void last_voice_tag_number_cb(const RawAddress* bd_addr, number = null_str; } - ScopedLocalRef js_number(sCallbackEnv.get(), - sCallbackEnv->NewStringUTF(number)); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onLastVoiceTagNumber, - js_number.get(), addr.get()); + ScopedLocalRef js_number(sCallbackEnv.get(), sCallbackEnv->NewStringUTF(number)); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onLastVoiceTagNumber, js_number.get(), + addr.get()); } static void ring_indication_cb(const RawAddress* bd_addr) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == NULL) return; + if (!sCallbackEnv.valid() || mCallbacksObj == NULL) { + return; + } ScopedLocalRef addr(sCallbackEnv.get(), marshall_bda(bd_addr)); - if (!addr.get()) return; - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onRingIndication, - addr.get()); + if (!addr.get()) { + return; + } + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onRingIndication, addr.get()); } -static void unknown_event_cb(const RawAddress* bd_addr, - const char* eventString) { +static void unknown_event_cb(const RawAddress* bd_addr, const char* eventString) { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == NULL) return; + if (!sCallbackEnv.valid() || mCallbacksObj == NULL) { + return; + } ScopedLocalRef addr(sCallbackEnv.get(), marshall_bda(bd_addr)); - if (!addr.get()) return; + if (!addr.get()) { + return; + } - ScopedLocalRef js_event(sCallbackEnv.get(), - sCallbackEnv->NewStringUTF(eventString)); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onUnknownEvent, - js_event.get(), addr.get()); + ScopedLocalRef js_event(sCallbackEnv.get(), sCallbackEnv->NewStringUTF(eventString)); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onUnknownEvent, js_event.get(), addr.get()); } static bthf_client_callbacks_t sBluetoothHfpClientCallbacks = { - sizeof(sBluetoothHfpClientCallbacks), - connection_state_cb, - audio_state_cb, - vr_cmd_cb, - network_state_cb, - network_roaming_cb, - network_signal_cb, - battery_level_cb, - current_operator_cb, - call_cb, - callsetup_cb, - callheld_cb, - resp_and_hold_cb, - clip_cb, - call_waiting_cb, - current_calls_cb, - volume_change_cb, - cmd_complete_cb, - subscriber_info_cb, - in_band_ring_cb, - last_voice_tag_number_cb, - ring_indication_cb, - unknown_event_cb, + sizeof(sBluetoothHfpClientCallbacks), + connection_state_cb, + audio_state_cb, + vr_cmd_cb, + network_state_cb, + network_roaming_cb, + network_signal_cb, + battery_level_cb, + current_operator_cb, + call_cb, + callsetup_cb, + callheld_cb, + resp_and_hold_cb, + clip_cb, + call_waiting_cb, + current_calls_cb, + volume_change_cb, + cmd_complete_cb, + subscriber_info_cb, + in_band_ring_cb, + last_voice_tag_number_cb, + ring_indication_cb, + unknown_event_cb, }; static void initializeNative(JNIEnv* env, jobject object) { @@ -451,18 +503,15 @@ static void initializeNative(JNIEnv* env, jobject object) { } sBluetoothHfpClientInterface = - (bthf_client_interface_t*)btInf->get_profile_interface( - BT_PROFILE_HANDSFREE_CLIENT_ID); + (bthf_client_interface_t*)btInf->get_profile_interface(BT_PROFILE_HANDSFREE_CLIENT_ID); if (sBluetoothHfpClientInterface == NULL) { log::error("Failed to get Bluetooth HFP Client Interface"); return; } - bt_status_t status = - sBluetoothHfpClientInterface->init(&sBluetoothHfpClientCallbacks); + bt_status_t status = sBluetoothHfpClientInterface->init(&sBluetoothHfpClientCallbacks); if (status != BT_STATUS_SUCCESS) { - log::error("Failed to initialize Bluetooth HFP Client, status: {}", - bt_status_text(status)); + log::error("Failed to initialize Bluetooth HFP Client, status: {}", bt_status_text(status)); sBluetoothHfpClientInterface = NULL; return; } @@ -493,10 +542,11 @@ static void cleanupNative(JNIEnv* env, jobject /* object */) { } } -static jboolean connectNative(JNIEnv* env, jobject /* object */, - jbyteArray address) { +static jboolean connectNative(JNIEnv* env, jobject /* object */, jbyteArray address) { std::shared_lock lock(interface_mutex); - if (!sBluetoothHfpClientInterface) return JNI_FALSE; + if (!sBluetoothHfpClientInterface) { + return JNI_FALSE; + } jbyte* addr = env->GetByteArrayElements(address, NULL); if (!addr) { @@ -504,8 +554,7 @@ static jboolean connectNative(JNIEnv* env, jobject /* object */, return JNI_FALSE; } - bt_status_t status = - sBluetoothHfpClientInterface->connect((const RawAddress*)addr); + bt_status_t status = sBluetoothHfpClientInterface->connect((const RawAddress*)addr); if (status != BT_STATUS_SUCCESS) { log::error("Failed AG connection, status: {}", bt_status_text(status)); } @@ -513,10 +562,11 @@ static jboolean connectNative(JNIEnv* env, jobject /* object */, return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } -static jboolean disconnectNative(JNIEnv* env, jobject /* object */, - jbyteArray address) { +static jboolean disconnectNative(JNIEnv* env, jobject /* object */, jbyteArray address) { std::shared_lock lock(interface_mutex); - if (!sBluetoothHfpClientInterface) return JNI_FALSE; + if (!sBluetoothHfpClientInterface) { + return JNI_FALSE; + } jbyte* addr = env->GetByteArrayElements(address, NULL); if (!addr) { @@ -524,8 +574,7 @@ static jboolean disconnectNative(JNIEnv* env, jobject /* object */, return JNI_FALSE; } - bt_status_t status = - sBluetoothHfpClientInterface->disconnect((const RawAddress*)addr); + bt_status_t status = sBluetoothHfpClientInterface->disconnect((const RawAddress*)addr); if (status != BT_STATUS_SUCCESS) { log::error("Failed AG disconnection, status: {}", bt_status_text(status)); } @@ -533,10 +582,11 @@ static jboolean disconnectNative(JNIEnv* env, jobject /* object */, return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } -static jboolean connectAudioNative(JNIEnv* env, jobject /* object */, - jbyteArray address) { +static jboolean connectAudioNative(JNIEnv* env, jobject /* object */, jbyteArray address) { std::shared_lock lock(interface_mutex); - if (!sBluetoothHfpClientInterface) return JNI_FALSE; + if (!sBluetoothHfpClientInterface) { + return JNI_FALSE; + } jbyte* addr = env->GetByteArrayElements(address, NULL); if (!addr) { @@ -544,20 +594,19 @@ static jboolean connectAudioNative(JNIEnv* env, jobject /* object */, return JNI_FALSE; } - bt_status_t status = - sBluetoothHfpClientInterface->connect_audio((const RawAddress*)addr); + bt_status_t status = sBluetoothHfpClientInterface->connect_audio((const RawAddress*)addr); if (status != BT_STATUS_SUCCESS) { - log::error("Failed AG audio connection, status: {}", - bt_status_text(status)); + log::error("Failed AG audio connection, status: {}", bt_status_text(status)); } env->ReleaseByteArrayElements(address, addr, 0); return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } -static jboolean disconnectAudioNative(JNIEnv* env, jobject /* object */, - jbyteArray address) { +static jboolean disconnectAudioNative(JNIEnv* env, jobject /* object */, jbyteArray address) { std::shared_lock lock(interface_mutex); - if (!sBluetoothHfpClientInterface) return JNI_FALSE; + if (!sBluetoothHfpClientInterface) { + return JNI_FALSE; + } jbyte* addr = env->GetByteArrayElements(address, NULL); if (!addr) { @@ -565,20 +614,19 @@ static jboolean disconnectAudioNative(JNIEnv* env, jobject /* object */, return JNI_FALSE; } - bt_status_t status = - sBluetoothHfpClientInterface->disconnect_audio((const RawAddress*)addr); + bt_status_t status = sBluetoothHfpClientInterface->disconnect_audio((const RawAddress*)addr); if (status != BT_STATUS_SUCCESS) { - log::error("Failed AG audio disconnection, status: {}", - bt_status_text(status)); + log::error("Failed AG audio disconnection, status: {}", bt_status_text(status)); } env->ReleaseByteArrayElements(address, addr, 0); return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } -static jboolean startVoiceRecognitionNative(JNIEnv* env, jobject /* object */, - jbyteArray address) { +static jboolean startVoiceRecognitionNative(JNIEnv* env, jobject /* object */, jbyteArray address) { std::shared_lock lock(interface_mutex); - if (!sBluetoothHfpClientInterface) return JNI_FALSE; + if (!sBluetoothHfpClientInterface) { + return JNI_FALSE; + } jbyte* addr = env->GetByteArrayElements(address, NULL); if (!addr) { @@ -586,20 +634,20 @@ static jboolean startVoiceRecognitionNative(JNIEnv* env, jobject /* object */, return JNI_FALSE; } - bt_status_t status = sBluetoothHfpClientInterface->start_voice_recognition( - (const RawAddress*)addr); + bt_status_t status = + sBluetoothHfpClientInterface->start_voice_recognition((const RawAddress*)addr); if (status != BT_STATUS_SUCCESS) { - log::error("Failed to start voice recognition, status: {}", - bt_status_text(status)); + log::error("Failed to start voice recognition, status: {}", bt_status_text(status)); } env->ReleaseByteArrayElements(address, addr, 0); return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } -static jboolean stopVoiceRecognitionNative(JNIEnv* env, jobject /* object */, - jbyteArray address) { +static jboolean stopVoiceRecognitionNative(JNIEnv* env, jobject /* object */, jbyteArray address) { std::shared_lock lock(interface_mutex); - if (!sBluetoothHfpClientInterface) return JNI_FALSE; + if (!sBluetoothHfpClientInterface) { + return JNI_FALSE; + } jbyte* addr = env->GetByteArrayElements(address, NULL); if (!addr) { @@ -607,21 +655,21 @@ static jboolean stopVoiceRecognitionNative(JNIEnv* env, jobject /* object */, return JNI_FALSE; } - bt_status_t status = sBluetoothHfpClientInterface->stop_voice_recognition( - (const RawAddress*)addr); + bt_status_t status = + sBluetoothHfpClientInterface->stop_voice_recognition((const RawAddress*)addr); if (status != BT_STATUS_SUCCESS) { - log::error("Failed to stop voice recognition, status: {}", - bt_status_text(status)); + log::error("Failed to stop voice recognition, status: {}", bt_status_text(status)); } env->ReleaseByteArrayElements(address, addr, 0); return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } -static jboolean setVolumeNative(JNIEnv* env, jobject /* object */, - jbyteArray address, jint volume_type, - jint volume) { +static jboolean setVolumeNative(JNIEnv* env, jobject /* object */, jbyteArray address, + jint volume_type, jint volume) { std::shared_lock lock(interface_mutex); - if (!sBluetoothHfpClientInterface) return JNI_FALSE; + if (!sBluetoothHfpClientInterface) { + return JNI_FALSE; + } jbyte* addr = env->GetByteArrayElements(address, NULL); if (!addr) { @@ -630,7 +678,7 @@ static jboolean setVolumeNative(JNIEnv* env, jobject /* object */, } bt_status_t status = sBluetoothHfpClientInterface->volume_control( - (const RawAddress*)addr, (bthf_client_volume_type_t)volume_type, volume); + (const RawAddress*)addr, (bthf_client_volume_type_t)volume_type, volume); if (status != BT_STATUS_SUCCESS) { log::error("FAILED to control volume, status: {}", bt_status_text(status)); } @@ -638,10 +686,12 @@ static jboolean setVolumeNative(JNIEnv* env, jobject /* object */, return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } -static jboolean dialNative(JNIEnv* env, jobject /* object */, - jbyteArray address, jstring number_str) { +static jboolean dialNative(JNIEnv* env, jobject /* object */, jbyteArray address, + jstring number_str) { std::shared_lock lock(interface_mutex); - if (!sBluetoothHfpClientInterface) return JNI_FALSE; + if (!sBluetoothHfpClientInterface) { + return JNI_FALSE; + } jbyte* addr = env->GetByteArrayElements(address, NULL); if (!addr) { @@ -653,9 +703,8 @@ static jboolean dialNative(JNIEnv* env, jobject /* object */, if (number_str != nullptr) { number = env->GetStringUTFChars(number_str, nullptr); } - bt_status_t status = - sBluetoothHfpClientInterface->dial((const RawAddress*)addr, - number == nullptr ? "" : number); + bt_status_t status = sBluetoothHfpClientInterface->dial((const RawAddress*)addr, + number == nullptr ? "" : number); if (status != BT_STATUS_SUCCESS) { log::error("Failed to dial, status: {}", bt_status_text(status)); @@ -667,10 +716,12 @@ static jboolean dialNative(JNIEnv* env, jobject /* object */, return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } -static jboolean dialMemoryNative(JNIEnv* env, jobject /* object */, - jbyteArray address, jint location) { +static jboolean dialMemoryNative(JNIEnv* env, jobject /* object */, jbyteArray address, + jint location) { std::shared_lock lock(interface_mutex); - if (!sBluetoothHfpClientInterface) return JNI_FALSE; + if (!sBluetoothHfpClientInterface) { + return JNI_FALSE; + } jbyte* addr = env->GetByteArrayElements(address, NULL); if (!addr) { @@ -678,22 +729,22 @@ static jboolean dialMemoryNative(JNIEnv* env, jobject /* object */, return JNI_FALSE; } - bt_status_t status = sBluetoothHfpClientInterface->dial_memory( - (const RawAddress*)addr, (int)location); + bt_status_t status = + sBluetoothHfpClientInterface->dial_memory((const RawAddress*)addr, (int)location); if (status != BT_STATUS_SUCCESS) { - log::error("Failed to dial from memory, status: {}", - bt_status_text(status)); + log::error("Failed to dial from memory, status: {}", bt_status_text(status)); } env->ReleaseByteArrayElements(address, addr, 0); return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } -static jboolean handleCallActionNative(JNIEnv* env, jobject /* object */, - jbyteArray address, jint action, - jint index) { +static jboolean handleCallActionNative(JNIEnv* env, jobject /* object */, jbyteArray address, + jint action, jint index) { std::shared_lock lock(interface_mutex); - if (!sBluetoothHfpClientInterface) return JNI_FALSE; + if (!sBluetoothHfpClientInterface) { + return JNI_FALSE; + } jbyte* addr = env->GetByteArrayElements(address, NULL); if (!addr) { @@ -702,20 +753,20 @@ static jboolean handleCallActionNative(JNIEnv* env, jobject /* object */, } bt_status_t status = sBluetoothHfpClientInterface->handle_call_action( - (const RawAddress*)addr, (bthf_client_call_action_t)action, (int)index); + (const RawAddress*)addr, (bthf_client_call_action_t)action, (int)index); if (status != BT_STATUS_SUCCESS) { - log::error("Failed to enter private mode, status: {}", - bt_status_text(status)); + log::error("Failed to enter private mode, status: {}", bt_status_text(status)); } env->ReleaseByteArrayElements(address, addr, 0); return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } -static jboolean queryCurrentCallsNative(JNIEnv* env, jobject /* object */, - jbyteArray address) { +static jboolean queryCurrentCallsNative(JNIEnv* env, jobject /* object */, jbyteArray address) { std::shared_lock lock(interface_mutex); - if (!sBluetoothHfpClientInterface) return JNI_FALSE; + if (!sBluetoothHfpClientInterface) { + return JNI_FALSE; + } jbyte* addr = env->GetByteArrayElements(address, NULL); if (!addr) { @@ -723,22 +774,21 @@ static jboolean queryCurrentCallsNative(JNIEnv* env, jobject /* object */, return JNI_FALSE; } - bt_status_t status = sBluetoothHfpClientInterface->query_current_calls( - (const RawAddress*)addr); + bt_status_t status = sBluetoothHfpClientInterface->query_current_calls((const RawAddress*)addr); if (status != BT_STATUS_SUCCESS) { - log::error("Failed to query current calls, status: {}", - bt_status_text(status)); + log::error("Failed to query current calls, status: {}", bt_status_text(status)); } env->ReleaseByteArrayElements(address, addr, 0); return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } -static jboolean queryCurrentOperatorNameNative(JNIEnv* env, - jobject /* object */, +static jboolean queryCurrentOperatorNameNative(JNIEnv* env, jobject /* object */, jbyteArray address) { std::shared_lock lock(interface_mutex); - if (!sBluetoothHfpClientInterface) return JNI_FALSE; + if (!sBluetoothHfpClientInterface) { + return JNI_FALSE; + } jbyte* addr = env->GetByteArrayElements(address, NULL); if (!addr) { @@ -747,11 +797,9 @@ static jboolean queryCurrentOperatorNameNative(JNIEnv* env, } bt_status_t status = - sBluetoothHfpClientInterface->query_current_operator_name( - (const RawAddress*)addr); + sBluetoothHfpClientInterface->query_current_operator_name((const RawAddress*)addr); if (status != BT_STATUS_SUCCESS) { - log::error("Failed to query current operator name, status: {}", - bt_status_text(status)); + log::error("Failed to query current operator name, status: {}", bt_status_text(status)); } env->ReleaseByteArrayElements(address, addr, 0); @@ -761,7 +809,9 @@ static jboolean queryCurrentOperatorNameNative(JNIEnv* env, static jboolean retrieveSubscriberInfoNative(JNIEnv* env, jobject /* object */, jbyteArray address) { std::shared_lock lock(interface_mutex); - if (!sBluetoothHfpClientInterface) return JNI_FALSE; + if (!sBluetoothHfpClientInterface) { + return JNI_FALSE; + } jbyte* addr = env->GetByteArrayElements(address, NULL); if (!addr) { @@ -769,21 +819,21 @@ static jboolean retrieveSubscriberInfoNative(JNIEnv* env, jobject /* object */, return JNI_FALSE; } - bt_status_t status = sBluetoothHfpClientInterface->retrieve_subscriber_info( - (const RawAddress*)addr); + bt_status_t status = + sBluetoothHfpClientInterface->retrieve_subscriber_info((const RawAddress*)addr); if (status != BT_STATUS_SUCCESS) { - log::error("Failed to retrieve subscriber info, status: {}", - bt_status_text(status)); + log::error("Failed to retrieve subscriber info, status: {}", bt_status_text(status)); } env->ReleaseByteArrayElements(address, addr, 0); return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } -static jboolean sendDtmfNative(JNIEnv* env, jobject /* object */, - jbyteArray address, jbyte code) { +static jboolean sendDtmfNative(JNIEnv* env, jobject /* object */, jbyteArray address, jbyte code) { std::shared_lock lock(interface_mutex); - if (!sBluetoothHfpClientInterface) return JNI_FALSE; + if (!sBluetoothHfpClientInterface) { + return JNI_FALSE; + } jbyte* addr = env->GetByteArrayElements(address, NULL); if (!addr) { @@ -791,8 +841,7 @@ static jboolean sendDtmfNative(JNIEnv* env, jobject /* object */, return JNI_FALSE; } - bt_status_t status = sBluetoothHfpClientInterface->send_dtmf( - (const RawAddress*)addr, (char)code); + bt_status_t status = sBluetoothHfpClientInterface->send_dtmf((const RawAddress*)addr, (char)code); if (status != BT_STATUS_SUCCESS) { log::error("Failed to send DTMF, status: {}", bt_status_text(status)); } @@ -801,11 +850,12 @@ static jboolean sendDtmfNative(JNIEnv* env, jobject /* object */, return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } -static jboolean requestLastVoiceTagNumberNative(JNIEnv* env, - jobject /* object */, +static jboolean requestLastVoiceTagNumberNative(JNIEnv* env, jobject /* object */, jbyteArray address) { std::shared_lock lock(interface_mutex); - if (!sBluetoothHfpClientInterface) return JNI_FALSE; + if (!sBluetoothHfpClientInterface) { + return JNI_FALSE; + } jbyte* addr = env->GetByteArrayElements(address, NULL); if (!addr) { @@ -814,23 +864,22 @@ static jboolean requestLastVoiceTagNumberNative(JNIEnv* env, } bt_status_t status = - sBluetoothHfpClientInterface->request_last_voice_tag_number( - (const RawAddress*)addr); + sBluetoothHfpClientInterface->request_last_voice_tag_number((const RawAddress*)addr); if (status != BT_STATUS_SUCCESS) { - log::error("Failed to request last Voice Tag number, status: {}", - bt_status_text(status)); + log::error("Failed to request last Voice Tag number, status: {}", bt_status_text(status)); } env->ReleaseByteArrayElements(address, addr, 0); return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } -static jboolean sendATCmdNative(JNIEnv* env, jobject /* object */, - jbyteArray address, jint cmd, jint val1, - jint val2, jstring arg_str) { +static jboolean sendATCmdNative(JNIEnv* env, jobject /* object */, jbyteArray address, jint cmd, + jint val1, jint val2, jstring arg_str) { std::shared_lock lock(interface_mutex); - if (!sBluetoothHfpClientInterface) return JNI_FALSE; + if (!sBluetoothHfpClientInterface) { + return JNI_FALSE; + } jbyte* addr = env->GetByteArrayElements(address, NULL); if (!addr) { @@ -842,8 +891,8 @@ static jboolean sendATCmdNative(JNIEnv* env, jobject /* object */, arg = env->GetStringUTFChars(arg_str, NULL); } - bt_status_t status = sBluetoothHfpClientInterface->send_at_cmd( - (const RawAddress*)addr, cmd, val1, val2, arg); + bt_status_t status = + sBluetoothHfpClientInterface->send_at_cmd((const RawAddress*)addr, cmd, val1, val2, arg); if (status != BT_STATUS_SUCCESS) { log::error("Failed to send cmd, status: {}", bt_status_text(status)); @@ -857,10 +906,12 @@ static jboolean sendATCmdNative(JNIEnv* env, jobject /* object */, return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } -static jboolean sendAndroidAtNative(JNIEnv* env, jobject /* object */, - jbyteArray address, jstring arg_str) { +static jboolean sendAndroidAtNative(JNIEnv* env, jobject /* object */, jbyteArray address, + jstring arg_str) { std::shared_lock lock(interface_mutex); - if (!sBluetoothHfpClientInterface) return JNI_FALSE; + if (!sBluetoothHfpClientInterface) { + return JNI_FALSE; + } jbyte* addr = env->GetByteArrayElements(address, NULL); if (!addr) { @@ -873,8 +924,7 @@ static jboolean sendAndroidAtNative(JNIEnv* env, jobject /* object */, arg = env->GetStringUTFChars(arg_str, NULL); } - bt_status_t status = sBluetoothHfpClientInterface->send_android_at( - (const RawAddress*)addr, arg); + bt_status_t status = sBluetoothHfpClientInterface->send_android_at((const RawAddress*)addr, arg); if (status != BT_STATUS_SUCCESS) { log::error("FAILED to control volume, status: {}", bt_status_text(status)); @@ -890,68 +940,57 @@ static jboolean sendAndroidAtNative(JNIEnv* env, jobject /* object */, int register_com_android_bluetooth_hfpclient(JNIEnv* env) { const JNINativeMethod methods[] = { - {"initializeNative", "()V", (void*)initializeNative}, - {"cleanupNative", "()V", (void*)cleanupNative}, - {"connectNative", "([B)Z", (void*)connectNative}, - {"disconnectNative", "([B)Z", (void*)disconnectNative}, - {"connectAudioNative", "([B)Z", (void*)connectAudioNative}, - {"disconnectAudioNative", "([B)Z", (void*)disconnectAudioNative}, - {"startVoiceRecognitionNative", "([B)Z", - (void*)startVoiceRecognitionNative}, - {"stopVoiceRecognitionNative", "([B)Z", - (void*)stopVoiceRecognitionNative}, - {"setVolumeNative", "([BII)Z", (void*)setVolumeNative}, - {"dialNative", "([BLjava/lang/String;)Z", (void*)dialNative}, - {"dialMemoryNative", "([BI)Z", (void*)dialMemoryNative}, - {"handleCallActionNative", "([BII)Z", (void*)handleCallActionNative}, - {"queryCurrentCallsNative", "([B)Z", (void*)queryCurrentCallsNative}, - {"queryCurrentOperatorNameNative", "([B)Z", - (void*)queryCurrentOperatorNameNative}, - {"retrieveSubscriberInfoNative", "([B)Z", - (void*)retrieveSubscriberInfoNative}, - {"sendDtmfNative", "([BB)Z", (void*)sendDtmfNative}, - {"requestLastVoiceTagNumberNative", "([B)Z", - (void*)requestLastVoiceTagNumberNative}, - {"sendATCmdNative", "([BIIILjava/lang/String;)Z", (void*)sendATCmdNative}, - {"sendAndroidAtNative", "([BLjava/lang/String;)Z", - (void*)sendAndroidAtNative}, + {"initializeNative", "()V", (void*)initializeNative}, + {"cleanupNative", "()V", (void*)cleanupNative}, + {"connectNative", "([B)Z", (void*)connectNative}, + {"disconnectNative", "([B)Z", (void*)disconnectNative}, + {"connectAudioNative", "([B)Z", (void*)connectAudioNative}, + {"disconnectAudioNative", "([B)Z", (void*)disconnectAudioNative}, + {"startVoiceRecognitionNative", "([B)Z", (void*)startVoiceRecognitionNative}, + {"stopVoiceRecognitionNative", "([B)Z", (void*)stopVoiceRecognitionNative}, + {"setVolumeNative", "([BII)Z", (void*)setVolumeNative}, + {"dialNative", "([BLjava/lang/String;)Z", (void*)dialNative}, + {"dialMemoryNative", "([BI)Z", (void*)dialMemoryNative}, + {"handleCallActionNative", "([BII)Z", (void*)handleCallActionNative}, + {"queryCurrentCallsNative", "([B)Z", (void*)queryCurrentCallsNative}, + {"queryCurrentOperatorNameNative", "([B)Z", (void*)queryCurrentOperatorNameNative}, + {"retrieveSubscriberInfoNative", "([B)Z", (void*)retrieveSubscriberInfoNative}, + {"sendDtmfNative", "([BB)Z", (void*)sendDtmfNative}, + {"requestLastVoiceTagNumberNative", "([B)Z", (void*)requestLastVoiceTagNumberNative}, + {"sendATCmdNative", "([BIIILjava/lang/String;)Z", (void*)sendATCmdNative}, + {"sendAndroidAtNative", "([BLjava/lang/String;)Z", (void*)sendAndroidAtNative}, }; - const int result = REGISTER_NATIVE_METHODS( - env, "com/android/bluetooth/hfpclient/NativeInterface", methods); + const int result = + REGISTER_NATIVE_METHODS(env, "com/android/bluetooth/hfpclient/NativeInterface", methods); if (result != 0) { return result; } const JNIJavaMethod javaMethods[] = { - {"onConnectionStateChanged", "(III[B)V", - &method_onConnectionStateChanged}, - {"onAudioStateChanged", "(I[B)V", &method_onAudioStateChanged}, - {"onVrStateChanged", "(I[B)V", &method_onVrStateChanged}, - {"onNetworkState", "(I[B)V", &method_onNetworkState}, - {"onNetworkRoaming", "(I[B)V", &method_onNetworkRoaming}, - {"onNetworkSignal", "(I[B)V", &method_onNetworkSignal}, - {"onBatteryLevel", "(I[B)V", &method_onBatteryLevel}, - {"onCurrentOperator", "(Ljava/lang/String;[B)V", - &method_onCurrentOperator}, - {"onCall", "(I[B)V", &method_onCall}, - {"onCallSetup", "(I[B)V", &method_onCallSetup}, - {"onCallHeld", "(I[B)V", &method_onCallHeld}, - {"onRespAndHold", "(I[B)V", &method_onRespAndHold}, - {"onClip", "(Ljava/lang/String;[B)V", &method_onClip}, - {"onCallWaiting", "(Ljava/lang/String;[B)V", &method_onCallWaiting}, - {"onCurrentCalls", "(IIIILjava/lang/String;[B)V", &method_onCurrentCalls}, - {"onVolumeChange", "(II[B)V", &method_onVolumeChange}, - {"onCmdResult", "(II[B)V", &method_onCmdResult}, - {"onSubscriberInfo", "(Ljava/lang/String;I[B)V", - &method_onSubscriberInfo}, - {"onInBandRing", "(I[B)V", &method_onInBandRing}, - {"onLastVoiceTagNumber", "(Ljava/lang/String;[B)V", - &method_onLastVoiceTagNumber}, - {"onRingIndication", "([B)V", &method_onRingIndication}, - {"onUnknownEvent", "(Ljava/lang/String;[B)V", &method_onUnknownEvent}, + {"onConnectionStateChanged", "(III[B)V", &method_onConnectionStateChanged}, + {"onAudioStateChanged", "(I[B)V", &method_onAudioStateChanged}, + {"onVrStateChanged", "(I[B)V", &method_onVrStateChanged}, + {"onNetworkState", "(I[B)V", &method_onNetworkState}, + {"onNetworkRoaming", "(I[B)V", &method_onNetworkRoaming}, + {"onNetworkSignal", "(I[B)V", &method_onNetworkSignal}, + {"onBatteryLevel", "(I[B)V", &method_onBatteryLevel}, + {"onCurrentOperator", "(Ljava/lang/String;[B)V", &method_onCurrentOperator}, + {"onCall", "(I[B)V", &method_onCall}, + {"onCallSetup", "(I[B)V", &method_onCallSetup}, + {"onCallHeld", "(I[B)V", &method_onCallHeld}, + {"onRespAndHold", "(I[B)V", &method_onRespAndHold}, + {"onClip", "(Ljava/lang/String;[B)V", &method_onClip}, + {"onCallWaiting", "(Ljava/lang/String;[B)V", &method_onCallWaiting}, + {"onCurrentCalls", "(IIIILjava/lang/String;[B)V", &method_onCurrentCalls}, + {"onVolumeChange", "(II[B)V", &method_onVolumeChange}, + {"onCmdResult", "(II[B)V", &method_onCmdResult}, + {"onSubscriberInfo", "(Ljava/lang/String;I[B)V", &method_onSubscriberInfo}, + {"onInBandRing", "(I[B)V", &method_onInBandRing}, + {"onLastVoiceTagNumber", "(Ljava/lang/String;[B)V", &method_onLastVoiceTagNumber}, + {"onRingIndication", "([B)V", &method_onRingIndication}, + {"onUnknownEvent", "(Ljava/lang/String;[B)V", &method_onUnknownEvent}, }; - GET_JAVA_METHODS(env, "com/android/bluetooth/hfpclient/NativeInterface", - javaMethods); + GET_JAVA_METHODS(env, "com/android/bluetooth/hfpclient/NativeInterface", javaMethods); return 0; } diff --git a/android/app/jni/com_android_bluetooth_hid_device.cpp b/android/app/jni/com_android_bluetooth_hid_device.cpp index fba1cff013b..6ff86e05307 100644 --- a/android/app/jni/com_android_bluetooth_hid_device.cpp +++ b/android/app/jni/com_android_bluetooth_hid_device.cpp @@ -36,20 +36,20 @@ static jobject mCallbacksObj = NULL; static jbyteArray marshall_bda(RawAddress* bd_addr) { CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid()) return NULL; + if (!sCallbackEnv.valid()) { + return NULL; + } jbyteArray addr = sCallbackEnv->NewByteArray(sizeof(RawAddress)); if (!addr) { log::error("Fail to new jbyteArray bd addr"); return NULL; } - sCallbackEnv->SetByteArrayRegion(addr, 0, sizeof(RawAddress), - (jbyte*)bd_addr); + sCallbackEnv->SetByteArrayRegion(addr, 0, sizeof(RawAddress), (jbyte*)bd_addr); return addr; } -static void application_state_callback(RawAddress* bd_addr, - bthd_application_state_t state) { +static void application_state_callback(RawAddress* bd_addr, bthd_application_state_t state) { jboolean registered = JNI_FALSE; CallbackEnv sCallbackEnv(__func__); @@ -68,12 +68,11 @@ static void application_state_callback(RawAddress* bd_addr, } } - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onApplicationStateChanged, - addr.get(), registered); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onApplicationStateChanged, addr.get(), + registered); } -static void connection_state_callback(RawAddress* bd_addr, - bthd_connection_state_t state) { +static void connection_state_callback(RawAddress* bd_addr, bthd_connection_state_t state) { CallbackEnv sCallbackEnv(__func__); ScopedLocalRef addr(sCallbackEnv.get(), marshall_bda(bd_addr)); @@ -82,32 +81,28 @@ static void connection_state_callback(RawAddress* bd_addr, return; } - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onConnectStateChanged, - addr.get(), (jint)state); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onConnectStateChanged, addr.get(), + (jint)state); } -static void get_report_callback(uint8_t type, uint8_t id, - uint16_t buffer_size) { +static void get_report_callback(uint8_t type, uint8_t id, uint16_t buffer_size) { CallbackEnv sCallbackEnv(__func__); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onGetReport, type, id, - buffer_size); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onGetReport, type, id, buffer_size); } -static void set_report_callback(uint8_t type, uint8_t id, uint16_t len, - uint8_t* p_data) { +static void set_report_callback(uint8_t type, uint8_t id, uint16_t len, uint8_t* p_data) { CallbackEnv sCallbackEnv(__func__); - ScopedLocalRef data(sCallbackEnv.get(), - sCallbackEnv->NewByteArray(len)); + ScopedLocalRef data(sCallbackEnv.get(), sCallbackEnv->NewByteArray(len)); if (!data.get()) { log::error("failed to allocate storage for report data"); return; } sCallbackEnv->SetByteArrayRegion(data.get(), 0, len, (jbyte*)p_data); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onSetReport, (jbyte)type, - (jbyte)id, data.get()); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onSetReport, (jbyte)type, (jbyte)id, + data.get()); } static void set_protocol_callback(uint8_t protocol) { @@ -116,20 +111,17 @@ static void set_protocol_callback(uint8_t protocol) { sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onSetProtocol, protocol); } -static void intr_data_callback(uint8_t report_id, uint16_t len, - uint8_t* p_data) { +static void intr_data_callback(uint8_t report_id, uint16_t len, uint8_t* p_data) { CallbackEnv sCallbackEnv(__func__); - ScopedLocalRef data(sCallbackEnv.get(), - sCallbackEnv->NewByteArray(len)); + ScopedLocalRef data(sCallbackEnv.get(), sCallbackEnv->NewByteArray(len)); if (!data.get()) { log::error("failed to allocate storage for report data"); return; } sCallbackEnv->SetByteArrayRegion(data.get(), 0, len, (jbyte*)p_data); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onInterruptData, - (jbyte)report_id, data.get()); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onInterruptData, (jbyte)report_id, data.get()); } static void vc_unplug_callback(void) { @@ -138,15 +130,15 @@ static void vc_unplug_callback(void) { } static bthd_callbacks_t sHiddCb = { - sizeof(sHiddCb), - - application_state_callback, - connection_state_callback, - get_report_callback, - set_report_callback, - set_protocol_callback, - intr_data_callback, - vc_unplug_callback, + sizeof(sHiddCb), + + application_state_callback, + connection_state_callback, + get_report_callback, + set_report_callback, + set_protocol_callback, + intr_data_callback, + vc_unplug_callback, }; static void initNative(JNIEnv* env, jobject object) { @@ -172,8 +164,7 @@ static void initNative(JNIEnv* env, jobject object) { mCallbacksObj = NULL; } - if ((sHiddIf = (bthd_interface_t*)btif->get_profile_interface( - BT_PROFILE_HIDDEV_ID)) == NULL) { + if ((sHiddIf = (bthd_interface_t*)btif->get_profile_interface(BT_PROFILE_HIDDEV_ID)) == NULL) { log::error("Cannot obtain interface"); return; } @@ -209,20 +200,25 @@ static void cleanupNative(JNIEnv* env, jobject /* object */) { static void fill_qos(JNIEnv* env, jintArray in, bthd_qos_param_t* out) { // set default values - out->service_type = 0x01; // best effort - out->token_rate = out->token_bucket_size = out->peak_bandwidth = - 0; // don't care - out->access_latency = out->delay_variation = 0xffffffff; // don't care + out->service_type = 0x01; // best effort + out->token_rate = out->token_bucket_size = out->peak_bandwidth = 0; // don't care + out->access_latency = out->delay_variation = 0xffffffff; // don't care - if (in == NULL) return; + if (in == NULL) { + return; + } jsize len = env->GetArrayLength(in); - if (len != 6) return; + if (len != 6) { + return; + } uint32_t* buf = (uint32_t*)calloc(len, sizeof(uint32_t)); - if (buf == NULL) return; + if (buf == NULL) { + return; + } env->GetIntArrayRegion(in, 0, len, (jint*)buf); @@ -237,9 +233,8 @@ static void fill_qos(JNIEnv* env, jintArray in, bthd_qos_param_t* out) { } static jboolean registerAppNative(JNIEnv* env, jobject /* thiz */, jstring name, - jstring description, jstring provider, - jbyte subclass, jbyteArray descriptors, - jintArray p_in_qos, jintArray p_out_qos) { + jstring description, jstring provider, jbyte subclass, + jbyteArray descriptors, jintArray p_in_qos, jintArray p_out_qos) { log::verbose("enter"); if (!sHiddIf) { @@ -313,8 +308,7 @@ static jboolean unregisterAppNative(JNIEnv* /* env */, jobject /* thiz */) { return result; } -static jboolean sendReportNative(JNIEnv* env, jobject /* thiz */, jint id, - jbyteArray data) { +static jboolean sendReportNative(JNIEnv* env, jobject /* thiz */, jint id, jbyteArray data) { jboolean result = JNI_FALSE; if (!sHiddIf) { @@ -331,8 +325,7 @@ static jboolean sendReportNative(JNIEnv* env, jobject /* thiz */, jint id, if (buf != NULL) { env->GetByteArrayRegion(data, 0, size, (jbyte*)buf); - bt_status_t ret = - sHiddIf->send_report(BTHD_REPORT_TYPE_INTRDATA, id, size, buf); + bt_status_t ret = sHiddIf->send_report(BTHD_REPORT_TYPE_INTRDATA, id, size, buf); if (ret == BT_STATUS_SUCCESS) { result = JNI_TRUE; @@ -344,8 +337,8 @@ static jboolean sendReportNative(JNIEnv* env, jobject /* thiz */, jint id, return result; } -static jboolean replyReportNative(JNIEnv* env, jobject /* thiz */, jbyte type, - jbyte id, jbyteArray data) { +static jboolean replyReportNative(JNIEnv* env, jobject /* thiz */, jbyte type, jbyte id, + jbyteArray data) { log::verbose("enter"); if (!sHiddIf) { @@ -364,8 +357,7 @@ static jboolean replyReportNative(JNIEnv* env, jobject /* thiz */, jbyte type, int report_type = (type & 0x03); env->GetByteArrayRegion(data, 0, size, (jbyte*)buf); - bt_status_t ret = - sHiddIf->send_report((bthd_report_type_t)report_type, id, size, buf); + bt_status_t ret = sHiddIf->send_report((bthd_report_type_t)report_type, id, size, buf); log::verbose("send_report() returned {}", bt_status_text(ret)); @@ -381,8 +373,7 @@ static jboolean replyReportNative(JNIEnv* env, jobject /* thiz */, jbyte type, return result; } -static jboolean reportErrorNative(JNIEnv* /* env */, jobject /* thiz */, - jbyte error) { +static jboolean reportErrorNative(JNIEnv* /* env */, jobject /* thiz */, jbyte error) { log::verbose("enter"); if (!sHiddIf) { @@ -428,8 +419,7 @@ static jboolean unplugNative(JNIEnv* /* env */, jobject /* thiz */) { return result; } -static jboolean connectNative(JNIEnv* env, jobject /* thiz */, - jbyteArray address) { +static jboolean connectNative(JNIEnv* env, jobject /* thiz */, jbyteArray address) { log::verbose("enter"); if (!sHiddIf) { @@ -483,37 +473,34 @@ static jboolean disconnectNative(JNIEnv* /* env */, jobject /* thiz */) { int register_com_android_bluetooth_hid_device(JNIEnv* env) { const JNINativeMethod methods[] = { - {"initNative", "()V", (void*)initNative}, - {"cleanupNative", "()V", (void*)cleanupNative}, - {"registerAppNative", - "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;B[B[I[I)Z", - (void*)registerAppNative}, - {"unregisterAppNative", "()Z", (void*)unregisterAppNative}, - {"sendReportNative", "(I[B)Z", (void*)sendReportNative}, - {"replyReportNative", "(BB[B)Z", (void*)replyReportNative}, - {"reportErrorNative", "(B)Z", (void*)reportErrorNative}, - {"unplugNative", "()Z", (void*)unplugNative}, - {"connectNative", "([B)Z", (void*)connectNative}, - {"disconnectNative", "()Z", (void*)disconnectNative}, + {"initNative", "()V", (void*)initNative}, + {"cleanupNative", "()V", (void*)cleanupNative}, + {"registerAppNative", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;B[B[I[I)Z", + (void*)registerAppNative}, + {"unregisterAppNative", "()Z", (void*)unregisterAppNative}, + {"sendReportNative", "(I[B)Z", (void*)sendReportNative}, + {"replyReportNative", "(BB[B)Z", (void*)replyReportNative}, + {"reportErrorNative", "(B)Z", (void*)reportErrorNative}, + {"unplugNative", "()Z", (void*)unplugNative}, + {"connectNative", "([B)Z", (void*)connectNative}, + {"disconnectNative", "()Z", (void*)disconnectNative}, }; const int result = REGISTER_NATIVE_METHODS( - env, "com/android/bluetooth/hid/HidDeviceNativeInterface", methods); + env, "com/android/bluetooth/hid/HidDeviceNativeInterface", methods); if (result != 0) { return result; } const JNIJavaMethod javaMethods[] = { - {"onApplicationStateChanged", "([BZ)V", - &method_onApplicationStateChanged}, - {"onConnectStateChanged", "([BI)V", &method_onConnectStateChanged}, - {"onGetReport", "(BBS)V", &method_onGetReport}, - {"onSetReport", "(BB[B)V", &method_onSetReport}, - {"onSetProtocol", "(B)V", &method_onSetProtocol}, - {"onInterruptData", "(B[B)V", &method_onInterruptData}, - {"onVirtualCableUnplug", "()V", &method_onVirtualCableUnplug}, + {"onApplicationStateChanged", "([BZ)V", &method_onApplicationStateChanged}, + {"onConnectStateChanged", "([BI)V", &method_onConnectStateChanged}, + {"onGetReport", "(BBS)V", &method_onGetReport}, + {"onSetReport", "(BB[B)V", &method_onSetReport}, + {"onSetProtocol", "(B)V", &method_onSetProtocol}, + {"onInterruptData", "(B[B)V", &method_onInterruptData}, + {"onVirtualCableUnplug", "()V", &method_onVirtualCableUnplug}, }; - GET_JAVA_METHODS(env, "com/android/bluetooth/hid/HidDeviceNativeInterface", - javaMethods); + GET_JAVA_METHODS(env, "com/android/bluetooth/hid/HidDeviceNativeInterface", javaMethods); return 0; } diff --git a/android/app/jni/com_android_bluetooth_hid_host.cpp b/android/app/jni/com_android_bluetooth_hid_host.cpp index 8eecdae5126..fcd28e5bbc7 100644 --- a/android/app/jni/com_android_bluetooth_hid_host.cpp +++ b/android/app/jni/com_android_bluetooth_hid_host.cpp @@ -16,12 +16,13 @@ #define LOG_TAG "BluetoothHidHostServiceJni" +#include + +#include + #include "com_android_bluetooth.h" #include "hardware/bt_hh.h" #include "utils/Log.h" - -#include -#include namespace android { static jmethodID method_onConnectStateChanged; @@ -37,25 +38,26 @@ static std::shared_timed_mutex mCallbacks_mutex; static jbyteArray marshall_bda(RawAddress* bd_addr) { CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid()) return NULL; + if (!sCallbackEnv.valid()) { + return NULL; + } jbyteArray addr = sCallbackEnv->NewByteArray(sizeof(RawAddress)); if (!addr) { log::error("Fail to new jbyteArray bd addr"); return NULL; } - sCallbackEnv->SetByteArrayRegion(addr, 0, sizeof(RawAddress), - (jbyte*)bd_addr); + sCallbackEnv->SetByteArrayRegion(addr, 0, sizeof(RawAddress), (jbyte*)bd_addr); return addr; } -static void connection_state_callback(RawAddress* bd_addr, - tBLE_ADDR_TYPE addr_type, - tBT_TRANSPORT transport, - bthh_connection_state_t state) { +static void connection_state_callback(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, + tBT_TRANSPORT transport, bthh_connection_state_t state) { std::shared_lock lock(mCallbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid()) return; + if (!sCallbackEnv.valid()) { + return; + } if (!mCallbacksObj) { log::error("mCallbacksObj is null"); return; @@ -66,19 +68,18 @@ static void connection_state_callback(RawAddress* bd_addr, return; } - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onConnectStateChanged, - addr.get(), (jint)addr_type, (jint)transport, - (jint)state); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onConnectStateChanged, addr.get(), + (jint)addr_type, (jint)transport, (jint)state); } -static void get_protocol_mode_callback(RawAddress* bd_addr, - tBLE_ADDR_TYPE addr_type, - tBT_TRANSPORT transport, - bthh_status_t hh_status, +static void get_protocol_mode_callback(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, + tBT_TRANSPORT transport, bthh_status_t hh_status, bthh_protocol_mode_t mode) { std::shared_lock lock(mCallbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid()) return; + if (!sCallbackEnv.valid()) { + return; + } if (!mCallbacksObj) { log::error("mCallbacksObj is null"); return; @@ -94,18 +95,18 @@ static void get_protocol_mode_callback(RawAddress* bd_addr, return; } - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onGetProtocolMode, - addr.get(), (jint)addr_type, (jint)transport, - (jint)mode); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onGetProtocolMode, addr.get(), (jint)addr_type, + (jint)transport, (jint)mode); } static void get_report_callback(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, - tBT_TRANSPORT transport, - bthh_status_t hh_status, uint8_t* rpt_data, + tBT_TRANSPORT transport, bthh_status_t hh_status, uint8_t* rpt_data, int rpt_size) { std::shared_lock lock(mCallbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid()) return; + if (!sCallbackEnv.valid()) { + return; + } if (!mCallbacksObj) { log::error("mCallbacksObj is null"); return; @@ -120,27 +121,25 @@ static void get_report_callback(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, log::error("Fail to new jbyteArray bd addr for get report callback"); return; } - ScopedLocalRef data(sCallbackEnv.get(), - sCallbackEnv->NewByteArray(rpt_size)); + ScopedLocalRef data(sCallbackEnv.get(), sCallbackEnv->NewByteArray(rpt_size)); if (!data.get()) { log::error("Fail to new jbyteArray data for get report callback"); return; } sCallbackEnv->SetByteArrayRegion(data.get(), 0, rpt_size, (jbyte*)rpt_data); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onGetReport, addr.get(), - (jint)addr_type, (jint)transport, data.get(), - (jint)rpt_size); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onGetReport, addr.get(), (jint)addr_type, + (jint)transport, data.get(), (jint)rpt_size); } -static void virtual_unplug_callback(RawAddress* bd_addr, - tBLE_ADDR_TYPE addr_type, - tBT_TRANSPORT transport, - bthh_status_t hh_status) { +static void virtual_unplug_callback(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, + tBT_TRANSPORT transport, bthh_status_t hh_status) { log::verbose("call to virtual_unplug_callback"); std::shared_lock lock(mCallbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid()) return; + if (!sCallbackEnv.valid()) { + return; + } if (!mCallbacksObj) { log::error("mCallbacksObj is null"); return; @@ -150,17 +149,17 @@ static void virtual_unplug_callback(RawAddress* bd_addr, log::error("Fail to new jbyteArray bd addr for HID channel state"); return; } - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onVirtualUnplug, - addr.get(), (jint)addr_type, (jint)transport, - (jint)hh_status); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onVirtualUnplug, addr.get(), (jint)addr_type, + (jint)transport, (jint)hh_status); } static void handshake_callback(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, - tBT_TRANSPORT transport, - bthh_status_t hh_status) { + tBT_TRANSPORT transport, bthh_status_t hh_status) { std::shared_lock lock(mCallbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid()) return; + if (!sCallbackEnv.valid()) { + return; + } if (!mCallbacksObj) { log::error("mCallbacksObj is null"); return; @@ -171,39 +170,32 @@ static void handshake_callback(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, log::error("Fail to new jbyteArray bd addr for handshake callback"); return; } - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onHandshake, addr.get(), - (jint)addr_type, (jint)transport, - (jint)hh_status); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onHandshake, addr.get(), (jint)addr_type, + (jint)transport, (jint)hh_status); } -static void get_idle_time_callback(RawAddress* bd_addr, - tBLE_ADDR_TYPE addr_type, - tBT_TRANSPORT transport, - bthh_status_t /* hh_status */, +static void get_idle_time_callback(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, + tBT_TRANSPORT transport, bthh_status_t /* hh_status */, int idle_time) { std::shared_lock lock(mCallbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid()) return; + if (!sCallbackEnv.valid()) { + return; + } ScopedLocalRef addr(sCallbackEnv.get(), marshall_bda(bd_addr)); if (!addr.get()) { log::error("Fail to new jbyteArray bd addr"); return; } - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onGetIdleTime, addr.get(), - (jint)addr_type, (jint)transport, - (jint)idle_time); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onGetIdleTime, addr.get(), (jint)addr_type, + (jint)transport, (jint)idle_time); } static bthh_callbacks_t sBluetoothHidCallbacks = { - sizeof(sBluetoothHidCallbacks), - connection_state_callback, - NULL, - get_protocol_mode_callback, - get_idle_time_callback, - get_report_callback, - virtual_unplug_callback, - handshake_callback}; + sizeof(sBluetoothHidCallbacks), connection_state_callback, NULL, + get_protocol_mode_callback, get_idle_time_callback, get_report_callback, + virtual_unplug_callback, handshake_callback}; // Define native functions static void initializeNative(JNIEnv* env, jobject object) { @@ -226,8 +218,7 @@ static void initializeNative(JNIEnv* env, jobject object) { mCallbacksObj = NULL; } - sBluetoothHidInterface = - (bthh_interface_t*)btInf->get_profile_interface(BT_PROFILE_HIDHOST_ID); + sBluetoothHidInterface = (bthh_interface_t*)btInf->get_profile_interface(BT_PROFILE_HIDHOST_ID); if (sBluetoothHidInterface == NULL) { log::error("Failed to get Bluetooth HID Interface"); return; @@ -235,8 +226,7 @@ static void initializeNative(JNIEnv* env, jobject object) { bt_status_t status = sBluetoothHidInterface->init(&sBluetoothHidCallbacks); if (status != BT_STATUS_SUCCESS) { - log::error("Failed to initialize Bluetooth HID, status: {}", - bt_status_text(status)); + log::error("Failed to initialize Bluetooth HID, status: {}", bt_status_text(status)); sBluetoothHidInterface = NULL; return; } @@ -266,10 +256,11 @@ static void cleanupNative(JNIEnv* env, jobject /* object */) { } } -static jboolean connectHidNative(JNIEnv* env, jobject /* object */, - jbyteArray address, jint address_type, - jint transport) { - if (!sBluetoothHidInterface) return JNI_FALSE; +static jboolean connectHidNative(JNIEnv* env, jobject /* object */, jbyteArray address, + jint address_type, jint transport) { + if (!sBluetoothHidInterface) { + return JNI_FALSE; + } jbyte* addr = env->GetByteArrayElements(address, NULL); if (!addr) { @@ -279,11 +270,9 @@ static jboolean connectHidNative(JNIEnv* env, jobject /* object */, jboolean ret = JNI_TRUE; bt_status_t status = sBluetoothHidInterface->connect( - (RawAddress*)addr, (tBLE_ADDR_TYPE)address_type, - (tBT_TRANSPORT)transport); + (RawAddress*)addr, (tBLE_ADDR_TYPE)address_type, (tBT_TRANSPORT)transport); if (status != BT_STATUS_SUCCESS && status != BT_STATUS_BUSY) { - log::error("Failed HID channel connection, status: {}", - bt_status_text(status)); + log::error("Failed HID channel connection, status: {}", bt_status_text(status)); ret = JNI_FALSE; } env->ReleaseByteArrayElements(address, addr, 0); @@ -291,13 +280,13 @@ static jboolean connectHidNative(JNIEnv* env, jobject /* object */, return ret; } -static jboolean disconnectHidNative(JNIEnv* env, jobject /* object */, - jbyteArray address, jint address_type, - jint transport, - jboolean reconnect_allowed) { +static jboolean disconnectHidNative(JNIEnv* env, jobject /* object */, jbyteArray address, + jint address_type, jint transport, jboolean reconnect_allowed) { jbyte* addr; jboolean ret = JNI_TRUE; - if (!sBluetoothHidInterface) return JNI_FALSE; + if (!sBluetoothHidInterface) { + return JNI_FALSE; + } addr = env->GetByteArrayElements(address, NULL); if (!addr) { @@ -305,12 +294,11 @@ static jboolean disconnectHidNative(JNIEnv* env, jobject /* object */, return JNI_FALSE; } - bt_status_t status = sBluetoothHidInterface->disconnect( - (RawAddress*)addr, (tBLE_ADDR_TYPE)address_type, (tBT_TRANSPORT)transport, - reconnect_allowed); + bt_status_t status = + sBluetoothHidInterface->disconnect((RawAddress*)addr, (tBLE_ADDR_TYPE)address_type, + (tBT_TRANSPORT)transport, reconnect_allowed); if (status != BT_STATUS_SUCCESS) { - log::error("Failed disconnect hid channel, status: {}", - bt_status_text(status)); + log::error("Failed disconnect hid channel, status: {}", bt_status_text(status)); ret = JNI_FALSE; } env->ReleaseByteArrayElements(address, addr, 0); @@ -318,10 +306,11 @@ static jboolean disconnectHidNative(JNIEnv* env, jobject /* object */, return ret; } -static jboolean getProtocolModeNative(JNIEnv* env, jobject /* object */, - jbyteArray address, jint address_type, - jint transport) { - if (!sBluetoothHidInterface) return JNI_FALSE; +static jboolean getProtocolModeNative(JNIEnv* env, jobject /* object */, jbyteArray address, + jint address_type, jint transport) { + if (!sBluetoothHidInterface) { + return JNI_FALSE; + } jbyte* addr = env->GetByteArrayElements(address, NULL); if (!addr) { @@ -333,8 +322,8 @@ static jboolean getProtocolModeNative(JNIEnv* env, jobject /* object */, // TODO: protocolMode is unused by the backend: see b/28908173 bthh_protocol_mode_t protocolMode = BTHH_UNSUPPORTED_MODE; bt_status_t status = sBluetoothHidInterface->get_protocol( - (RawAddress*)addr, (tBLE_ADDR_TYPE)address_type, (tBT_TRANSPORT)transport, - (bthh_protocol_mode_t)protocolMode); + (RawAddress*)addr, (tBLE_ADDR_TYPE)address_type, (tBT_TRANSPORT)transport, + (bthh_protocol_mode_t)protocolMode); if (status != BT_STATUS_SUCCESS) { log::error("Failed get protocol mode, status: {}", bt_status_text(status)); ret = JNI_FALSE; @@ -344,10 +333,11 @@ static jboolean getProtocolModeNative(JNIEnv* env, jobject /* object */, return ret; } -static jboolean virtualUnPlugNative(JNIEnv* env, jobject /* object */, - jbyteArray address, jint address_type, - jint transport) { - if (!sBluetoothHidInterface) return JNI_FALSE; +static jboolean virtualUnPlugNative(JNIEnv* env, jobject /* object */, jbyteArray address, + jint address_type, jint transport) { + if (!sBluetoothHidInterface) { + return JNI_FALSE; + } jbyte* addr = env->GetByteArrayElements(address, NULL); if (!addr) { @@ -357,8 +347,7 @@ static jboolean virtualUnPlugNative(JNIEnv* env, jobject /* object */, jboolean ret = JNI_TRUE; bt_status_t status = sBluetoothHidInterface->virtual_unplug( - (RawAddress*)addr, (tBLE_ADDR_TYPE)address_type, - (tBT_TRANSPORT)transport); + (RawAddress*)addr, (tBLE_ADDR_TYPE)address_type, (tBT_TRANSPORT)transport); if (status != BT_STATUS_SUCCESS) { log::error("Failed virual unplug, status: {}", bt_status_text(status)); ret = JNI_FALSE; @@ -367,10 +356,11 @@ static jboolean virtualUnPlugNative(JNIEnv* env, jobject /* object */, return ret; } -static jboolean setProtocolModeNative(JNIEnv* env, jobject /* object */, - jbyteArray address, jint address_type, - jint transport, jint protocolMode) { - if (!sBluetoothHidInterface) return JNI_FALSE; +static jboolean setProtocolModeNative(JNIEnv* env, jobject /* object */, jbyteArray address, + jint address_type, jint transport, jint protocolMode) { + if (!sBluetoothHidInterface) { + return JNI_FALSE; + } log::debug("protocolMode = {}", protocolMode); @@ -395,8 +385,7 @@ static jboolean setProtocolModeNative(JNIEnv* env, jobject /* object */, jboolean ret = JNI_TRUE; bt_status_t status = sBluetoothHidInterface->set_protocol( - (RawAddress*)addr, (tBLE_ADDR_TYPE)address_type, (tBT_TRANSPORT)transport, - mode); + (RawAddress*)addr, (tBLE_ADDR_TYPE)address_type, (tBT_TRANSPORT)transport, mode); if (status != BT_STATUS_SUCCESS) { log::error("Failed set protocol mode, status: {}", bt_status_text(status)); ret = JNI_FALSE; @@ -406,13 +395,13 @@ static jboolean setProtocolModeNative(JNIEnv* env, jobject /* object */, return ret; } -static jboolean getReportNative(JNIEnv* env, jobject /* object */, - jbyteArray address, jint address_type, - jint transport, jbyte reportType, - jbyte reportId, jint bufferSize) { - log::verbose("reportType = {}, reportId = {}, bufferSize = {}", reportType, - reportId, bufferSize); - if (!sBluetoothHidInterface) return JNI_FALSE; +static jboolean getReportNative(JNIEnv* env, jobject /* object */, jbyteArray address, + jint address_type, jint transport, jbyte reportType, jbyte reportId, + jint bufferSize) { + log::verbose("reportType = {}, reportId = {}, bufferSize = {}", reportType, reportId, bufferSize); + if (!sBluetoothHidInterface) { + return JNI_FALSE; + } jbyte* addr = env->GetByteArrayElements(address, NULL); if (!addr) { @@ -424,8 +413,8 @@ static jboolean getReportNative(JNIEnv* env, jobject /* object */, jint rId = reportId; bt_status_t status = sBluetoothHidInterface->get_report( - (RawAddress*)addr, (tBLE_ADDR_TYPE)address_type, (tBT_TRANSPORT)transport, - (bthh_report_type_t)rType, (uint8_t)rId, bufferSize); + (RawAddress*)addr, (tBLE_ADDR_TYPE)address_type, (tBT_TRANSPORT)transport, + (bthh_report_type_t)rType, (uint8_t)rId, bufferSize); jboolean ret = JNI_TRUE; if (status != BT_STATUS_SUCCESS) { log::error("Failed get report, status: {}", bt_status_text(status)); @@ -436,12 +425,13 @@ static jboolean getReportNative(JNIEnv* env, jobject /* object */, return ret; } -static jboolean setReportNative(JNIEnv* env, jobject /* object */, - jbyteArray address, jint address_type, - jint transport, jbyte reportType, +static jboolean setReportNative(JNIEnv* env, jobject /* object */, jbyteArray address, + jint address_type, jint transport, jbyte reportType, jstring report) { log::verbose("reportType = {}", reportType); - if (!sBluetoothHidInterface) return JNI_FALSE; + if (!sBluetoothHidInterface) { + return JNI_FALSE; + } jbyte* addr = env->GetByteArrayElements(address, NULL); if (!addr) { @@ -453,8 +443,8 @@ static jboolean setReportNative(JNIEnv* env, jobject /* object */, jboolean ret = JNI_TRUE; bt_status_t status = sBluetoothHidInterface->set_report( - (RawAddress*)addr, (tBLE_ADDR_TYPE)address_type, (tBT_TRANSPORT)transport, - (bthh_report_type_t)rType, (char*)c_report); + (RawAddress*)addr, (tBLE_ADDR_TYPE)address_type, (tBT_TRANSPORT)transport, + (bthh_report_type_t)rType, (char*)c_report); if (status != BT_STATUS_SUCCESS) { log::error("Failed set report, status: {}", bt_status_text(status)); ret = JNI_FALSE; @@ -465,12 +455,13 @@ static jboolean setReportNative(JNIEnv* env, jobject /* object */, return ret; } -static jboolean sendDataNative(JNIEnv* env, jobject /* object */, - jbyteArray address, jint address_type, - jint transport, jstring report) { +static jboolean sendDataNative(JNIEnv* env, jobject /* object */, jbyteArray address, + jint address_type, jint transport, jstring report) { log::verbose(""); jboolean ret = JNI_TRUE; - if (!sBluetoothHidInterface) return JNI_FALSE; + if (!sBluetoothHidInterface) { + return JNI_FALSE; + } jbyte* addr = env->GetByteArrayElements(address, NULL); if (!addr) { @@ -480,9 +471,9 @@ static jboolean sendDataNative(JNIEnv* env, jobject /* object */, const char* c_report = env->GetStringUTFChars(report, NULL); - bt_status_t status = sBluetoothHidInterface->send_data( - (RawAddress*)addr, (tBLE_ADDR_TYPE)address_type, (tBT_TRANSPORT)transport, - (char*)c_report); + bt_status_t status = + sBluetoothHidInterface->send_data((RawAddress*)addr, (tBLE_ADDR_TYPE)address_type, + (tBT_TRANSPORT)transport, (char*)c_report); if (status != BT_STATUS_SUCCESS) { log::error("Failed set data, status: {}", bt_status_text(status)); ret = JNI_FALSE; @@ -493,10 +484,11 @@ static jboolean sendDataNative(JNIEnv* env, jobject /* object */, return ret; } -static jboolean getIdleTimeNative(JNIEnv* env, jobject /* object */, - jbyteArray address, jint address_type, - jint transport) { - if (!sBluetoothHidInterface) return JNI_FALSE; +static jboolean getIdleTimeNative(JNIEnv* env, jobject /* object */, jbyteArray address, + jint address_type, jint transport) { + if (!sBluetoothHidInterface) { + return JNI_FALSE; + } jbyte* addr = env->GetByteArrayElements(address, NULL); if (!addr) { @@ -505,8 +497,7 @@ static jboolean getIdleTimeNative(JNIEnv* env, jobject /* object */, } bt_status_t status = sBluetoothHidInterface->get_idle_time( - (RawAddress*)addr, (tBLE_ADDR_TYPE)address_type, - (tBT_TRANSPORT)transport); + (RawAddress*)addr, (tBLE_ADDR_TYPE)address_type, (tBT_TRANSPORT)transport); if (status != BT_STATUS_SUCCESS) { log::error("Failed get idle time, status: {}", bt_status_text(status)); } @@ -515,10 +506,11 @@ static jboolean getIdleTimeNative(JNIEnv* env, jobject /* object */, return status == BT_STATUS_SUCCESS ? JNI_TRUE : JNI_FALSE; } -static jboolean setIdleTimeNative(JNIEnv* env, jobject /* object */, - jbyteArray address, jint address_type, - jint transport, jbyte idle_time) { - if (!sBluetoothHidInterface) return JNI_FALSE; +static jboolean setIdleTimeNative(JNIEnv* env, jobject /* object */, jbyteArray address, + jint address_type, jint transport, jbyte idle_time) { + if (!sBluetoothHidInterface) { + return JNI_FALSE; + } jbyte* addr = env->GetByteArrayElements(address, NULL); if (!addr) { @@ -527,8 +519,7 @@ static jboolean setIdleTimeNative(JNIEnv* env, jobject /* object */, } bt_status_t status = sBluetoothHidInterface->set_idle_time( - (RawAddress*)addr, (tBLE_ADDR_TYPE)address_type, (tBT_TRANSPORT)transport, - idle_time); + (RawAddress*)addr, (tBLE_ADDR_TYPE)address_type, (tBT_TRANSPORT)transport, idle_time); if (status != BT_STATUS_SUCCESS) { log::error("Failed set idle time, status: {}", bt_status_text(status)); } @@ -539,35 +530,34 @@ static jboolean setIdleTimeNative(JNIEnv* env, jobject /* object */, int register_com_android_bluetooth_hid_host(JNIEnv* env) { const JNINativeMethod methods[] = { - {"initializeNative", "()V", (void*)initializeNative}, - {"cleanupNative", "()V", (void*)cleanupNative}, - {"connectHidNative", "([BII)Z", (void*)connectHidNative}, - {"disconnectHidNative", "([BIIZ)Z", (void*)disconnectHidNative}, - {"getProtocolModeNative", "([BII)Z", (void*)getProtocolModeNative}, - {"virtualUnPlugNative", "([BII)Z", (void*)virtualUnPlugNative}, - {"setProtocolModeNative", "([BIIB)Z", (void*)setProtocolModeNative}, - {"getReportNative", "([BIIBBI)Z", (void*)getReportNative}, - {"setReportNative", "([BIIBLjava/lang/String;)Z", (void*)setReportNative}, - {"sendDataNative", "([BIILjava/lang/String;)Z", (void*)sendDataNative}, - {"getIdleTimeNative", "([BII)Z", (void*)getIdleTimeNative}, - {"setIdleTimeNative", "([BIIB)Z", (void*)setIdleTimeNative}, + {"initializeNative", "()V", (void*)initializeNative}, + {"cleanupNative", "()V", (void*)cleanupNative}, + {"connectHidNative", "([BII)Z", (void*)connectHidNative}, + {"disconnectHidNative", "([BIIZ)Z", (void*)disconnectHidNative}, + {"getProtocolModeNative", "([BII)Z", (void*)getProtocolModeNative}, + {"virtualUnPlugNative", "([BII)Z", (void*)virtualUnPlugNative}, + {"setProtocolModeNative", "([BIIB)Z", (void*)setProtocolModeNative}, + {"getReportNative", "([BIIBBI)Z", (void*)getReportNative}, + {"setReportNative", "([BIIBLjava/lang/String;)Z", (void*)setReportNative}, + {"sendDataNative", "([BIILjava/lang/String;)Z", (void*)sendDataNative}, + {"getIdleTimeNative", "([BII)Z", (void*)getIdleTimeNative}, + {"setIdleTimeNative", "([BIIB)Z", (void*)setIdleTimeNative}, }; - const int result = REGISTER_NATIVE_METHODS( - env, "com/android/bluetooth/hid/HidHostNativeInterface", methods); + const int result = + REGISTER_NATIVE_METHODS(env, "com/android/bluetooth/hid/HidHostNativeInterface", methods); if (result != 0) { return result; } const JNIJavaMethod javaMethods[] = { - {"onConnectStateChanged", "([BIII)V", &method_onConnectStateChanged}, - {"onGetProtocolMode", "([BIII)V", &method_onGetProtocolMode}, - {"onGetReport", "([BII[BI)V", &method_onGetReport}, - {"onHandshake", "([BIII)V", &method_onHandshake}, - {"onVirtualUnplug", "([BIII)V", &method_onVirtualUnplug}, - {"onGetIdleTime", "([BIII)V", &method_onGetIdleTime}, + {"onConnectStateChanged", "([BIII)V", &method_onConnectStateChanged}, + {"onGetProtocolMode", "([BIII)V", &method_onGetProtocolMode}, + {"onGetReport", "([BII[BI)V", &method_onGetReport}, + {"onHandshake", "([BIII)V", &method_onHandshake}, + {"onVirtualUnplug", "([BIII)V", &method_onVirtualUnplug}, + {"onGetIdleTime", "([BIII)V", &method_onGetIdleTime}, }; - GET_JAVA_METHODS(env, "com/android/bluetooth/hid/HidHostNativeInterface", - javaMethods); + GET_JAVA_METHODS(env, "com/android/bluetooth/hid/HidHostNativeInterface", javaMethods); return 0; } diff --git a/android/app/jni/com_android_bluetooth_le_audio.cpp b/android/app/jni/com_android_bluetooth_le_audio.cpp index 4c828d35ece..f1d1136b3ed 100644 --- a/android/app/jni/com_android_bluetooth_le_audio.cpp +++ b/android/app/jni/com_android_bluetooth_le_audio.cpp @@ -112,32 +112,28 @@ static std::shared_timed_mutex interface_mutex; static jobject mCallbacksObj = nullptr; static std::shared_timed_mutex callbacks_mutex; -jobject prepareCodecConfigObj(JNIEnv* env, - btle_audio_codec_config_t codecConfig) { +jobject prepareCodecConfigObj(JNIEnv* env, btle_audio_codec_config_t codecConfig) { log::info( - "ct: {}, codec_priority: {}, sample_rate: {}, bits_per_sample: {}, " - "channel_count: {}, frame_duration: {}, octets_per_frame: {}", - codecConfig.codec_type, codecConfig.codec_priority, - codecConfig.sample_rate, codecConfig.bits_per_sample, - codecConfig.channel_count, codecConfig.frame_duration, - codecConfig.octets_per_frame); + "ct: {}, codec_priority: {}, sample_rate: {}, bits_per_sample: {}, " + "channel_count: {}, frame_duration: {}, octets_per_frame: {}", + codecConfig.codec_type, codecConfig.codec_priority, codecConfig.sample_rate, + codecConfig.bits_per_sample, codecConfig.channel_count, codecConfig.frame_duration, + codecConfig.octets_per_frame); jobject codecConfigObj = env->NewObject( - android_bluetooth_BluetoothLeAudioCodecConfig.clazz, - android_bluetooth_BluetoothLeAudioCodecConfig.constructor, - (jint)codecConfig.codec_type, (jint)codecConfig.codec_priority, - (jint)codecConfig.sample_rate, (jint)codecConfig.bits_per_sample, - (jint)codecConfig.channel_count, (jint)codecConfig.frame_duration, - (jint)codecConfig.octets_per_frame, 0, 0); + android_bluetooth_BluetoothLeAudioCodecConfig.clazz, + android_bluetooth_BluetoothLeAudioCodecConfig.constructor, (jint)codecConfig.codec_type, + (jint)codecConfig.codec_priority, (jint)codecConfig.sample_rate, + (jint)codecConfig.bits_per_sample, (jint)codecConfig.channel_count, + (jint)codecConfig.frame_duration, (jint)codecConfig.octets_per_frame, 0, 0); return codecConfigObj; } -jobjectArray prepareArrayOfCodecConfigs( - JNIEnv* env, std::vector codecConfigs) { +jobjectArray prepareArrayOfCodecConfigs(JNIEnv* env, + std::vector codecConfigs) { jsize i = 0; jobjectArray CodecConfigArray = env->NewObjectArray( - (jsize)codecConfigs.size(), - android_bluetooth_BluetoothLeAudioCodecConfig.clazz, nullptr); + (jsize)codecConfigs.size(), android_bluetooth_BluetoothLeAudioCodecConfig.clazz, nullptr); for (auto const& cap : codecConfigs) { jobject Obj = prepareCodecConfigObj(env, cap); @@ -150,37 +146,38 @@ jobjectArray prepareArrayOfCodecConfigs( } class LeAudioClientCallbacksImpl : public LeAudioClientCallbacks { - public: +public: ~LeAudioClientCallbacksImpl() = default; void OnInitialized(void) override { log::info(""); std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) return; + if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) { + return; + } sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onInitialized); } - void OnConnectionState(ConnectionState state, - const RawAddress& bd_addr) override { - log::info("state:{}, addr: {}", int(state), - bd_addr.ToRedactedStringForLogging()); + void OnConnectionState(ConnectionState state, const RawAddress& bd_addr) override { + log::info("state:{}, addr: {}", int(state), bd_addr.ToRedactedStringForLogging()); std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) return; + if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) { + return; + } - ScopedLocalRef addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); + ScopedLocalRef addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); if (!addr.get()) { log::error("Failed to new jbyteArray bd addr for connection state"); return; } - sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), - (jbyte*)&bd_addr); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onConnectionStateChanged, - (jint)state, addr.get()); + sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), (jbyte*)&bd_addr); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onConnectionStateChanged, (jint)state, + addr.get()); } void OnGroupStatus(int group_id, GroupStatus group_status) override { @@ -188,10 +185,12 @@ class LeAudioClientCallbacksImpl : public LeAudioClientCallbacks { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) return; + if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) { + return; + } - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onGroupStatus, - (jint)group_id, (jint)group_status); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onGroupStatus, (jint)group_id, + (jint)group_status); } void OnGroupNodeStatus(const RawAddress& bd_addr, int group_id, @@ -200,34 +199,35 @@ class LeAudioClientCallbacksImpl : public LeAudioClientCallbacks { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) return; + if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) { + return; + } - ScopedLocalRef addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); + ScopedLocalRef addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); if (!addr.get()) { log::error("Failed to new jbyteArray bd addr for group status"); return; } - sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), - (jbyte*)&bd_addr); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onGroupNodeStatus, - addr.get(), (jint)group_id, (jint)node_status); + sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), (jbyte*)&bd_addr); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onGroupNodeStatus, addr.get(), + (jint)group_id, (jint)node_status); } - void OnAudioConf(uint8_t direction, int group_id, - uint32_t sink_audio_location, uint32_t source_audio_location, - uint16_t avail_cont) override { + void OnAudioConf(uint8_t direction, int group_id, uint32_t sink_audio_location, + uint32_t source_audio_location, uint16_t avail_cont) override { log::info(""); std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) return; + if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) { + return; + } - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onAudioConf, - (jint)direction, (jint)group_id, - (jint)sink_audio_location, - (jint)source_audio_location, (jint)avail_cont); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onAudioConf, (jint)direction, (jint)group_id, + (jint)sink_audio_location, (jint)source_audio_location, + (jint)avail_cont); } void OnSinkAudioLocationAvailable(const RawAddress& bd_addr, @@ -236,176 +236,173 @@ class LeAudioClientCallbacksImpl : public LeAudioClientCallbacks { std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) return; + if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) { + return; + } - ScopedLocalRef addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); + ScopedLocalRef addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); if (!addr.get()) { log::error("Failed to new jbyteArray bd addr for group status"); return; } - sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), - (jbyte*)&bd_addr); - sCallbackEnv->CallVoidMethod(mCallbacksObj, - method_onSinkAudioLocationAvailable, - addr.get(), (jint)sink_audio_location); + sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), (jbyte*)&bd_addr); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onSinkAudioLocationAvailable, addr.get(), + (jint)sink_audio_location); } void OnAudioLocalCodecCapabilities( - std::vector local_input_capa_codec_conf, - std::vector local_output_capa_codec_conf) - override { + std::vector local_input_capa_codec_conf, + std::vector local_output_capa_codec_conf) override { log::info(""); std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) return; + if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) { + return; + } - jobject localInputCapCodecConfigArray = prepareArrayOfCodecConfigs( - sCallbackEnv.get(), local_input_capa_codec_conf); + jobject localInputCapCodecConfigArray = + prepareArrayOfCodecConfigs(sCallbackEnv.get(), local_input_capa_codec_conf); - jobject localOutputCapCodecConfigArray = prepareArrayOfCodecConfigs( - sCallbackEnv.get(), local_output_capa_codec_conf); + jobject localOutputCapCodecConfigArray = + prepareArrayOfCodecConfigs(sCallbackEnv.get(), local_output_capa_codec_conf); - sCallbackEnv->CallVoidMethod( - mCallbacksObj, method_onAudioLocalCodecCapabilities, - localInputCapCodecConfigArray, localOutputCapCodecConfigArray); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onAudioLocalCodecCapabilities, + localInputCapCodecConfigArray, localOutputCapCodecConfigArray); } - void OnAudioGroupCurrentCodecConf( - int group_id, btle_audio_codec_config_t input_codec_conf, - btle_audio_codec_config_t output_codec_conf) override { + void OnAudioGroupCurrentCodecConf(int group_id, btle_audio_codec_config_t input_codec_conf, + btle_audio_codec_config_t output_codec_conf) override { log::info(""); std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) return; + if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) { + return; + } - jobject inputCodecConfigObj = - prepareCodecConfigObj(sCallbackEnv.get(), input_codec_conf); - jobject outputCodecConfigObj = - prepareCodecConfigObj(sCallbackEnv.get(), output_codec_conf); + jobject inputCodecConfigObj = prepareCodecConfigObj(sCallbackEnv.get(), input_codec_conf); + jobject outputCodecConfigObj = prepareCodecConfigObj(sCallbackEnv.get(), output_codec_conf); - sCallbackEnv->CallVoidMethod( - mCallbacksObj, method_onAudioGroupCurrentCodecConf, (jint)group_id, - inputCodecConfigObj, outputCodecConfigObj); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onAudioGroupCurrentCodecConf, (jint)group_id, + inputCodecConfigObj, outputCodecConfigObj); } void OnAudioGroupSelectableCodecConf( - int group_id, - std::vector input_selectable_codec_conf, - std::vector output_selectable_codec_conf) - override { + int group_id, std::vector input_selectable_codec_conf, + std::vector output_selectable_codec_conf) override { log::info(""); std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) return; + if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) { + return; + } - jobject inputSelectableCodecConfigArray = prepareArrayOfCodecConfigs( - sCallbackEnv.get(), input_selectable_codec_conf); - jobject outputSelectableCodecConfigArray = prepareArrayOfCodecConfigs( - sCallbackEnv.get(), output_selectable_codec_conf); + jobject inputSelectableCodecConfigArray = + prepareArrayOfCodecConfigs(sCallbackEnv.get(), input_selectable_codec_conf); + jobject outputSelectableCodecConfigArray = + prepareArrayOfCodecConfigs(sCallbackEnv.get(), output_selectable_codec_conf); - sCallbackEnv->CallVoidMethod( - mCallbacksObj, method_onAudioGroupSelectableCodecConf, (jint)group_id, - inputSelectableCodecConfigArray, outputSelectableCodecConfigArray); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onAudioGroupSelectableCodecConf, + (jint)group_id, inputSelectableCodecConfigArray, + outputSelectableCodecConfigArray); } void OnHealthBasedRecommendationAction( - const RawAddress& bd_addr, - bluetooth::le_audio::LeAudioHealthBasedAction action) override { + const RawAddress& bd_addr, + bluetooth::le_audio::LeAudioHealthBasedAction action) override { log::info(""); std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) return; + if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) { + return; + } - ScopedLocalRef addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); + ScopedLocalRef addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); if (!addr.get()) { log::error("Failed to new jbyteArray bd addr for group status"); return; } - sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), - (jbyte*)&bd_addr); - sCallbackEnv->CallVoidMethod(mCallbacksObj, - method_onHealthBasedRecommendationAction, + sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), (jbyte*)&bd_addr); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onHealthBasedRecommendationAction, addr.get(), (jint)action); } void OnHealthBasedGroupRecommendationAction( - int group_id, - bluetooth::le_audio::LeAudioHealthBasedAction action) override { + int group_id, bluetooth::le_audio::LeAudioHealthBasedAction action) override { log::info(""); std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) return; + if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) { + return; + } - sCallbackEnv->CallVoidMethod(mCallbacksObj, - method_onHealthBasedGroupRecommendationAction, + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onHealthBasedGroupRecommendationAction, (jint)group_id, (jint)action); } - void OnUnicastMonitorModeStatus(uint8_t direction, - UnicastMonitorModeStatus status) override { + void OnUnicastMonitorModeStatus(uint8_t direction, UnicastMonitorModeStatus status) override { log::info(""); std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) return; + if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) { + return; + } - sCallbackEnv->CallVoidMethod(mCallbacksObj, - method_onUnicastMonitorModeStatus, - (jint)direction, (jint)status); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onUnicastMonitorModeStatus, (jint)direction, + (jint)status); } - void OnGroupStreamStatus(int group_id, - GroupStreamStatus group_stream_status) override { + void OnGroupStreamStatus(int group_id, GroupStreamStatus group_stream_status) override { log::info(""); std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) return; + if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) { + return; + } - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onGroupStreamStatus, - (jint)group_id, (jint)group_stream_status); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onGroupStreamStatus, (jint)group_id, + (jint)group_stream_status); } }; static LeAudioClientCallbacksImpl sLeAudioClientCallbacks; -std::vector prepareCodecPreferences( - JNIEnv* env, jobject /* object */, jobjectArray codecConfigArray) { +std::vector prepareCodecPreferences(JNIEnv* env, jobject /* object */, + jobjectArray codecConfigArray) { std::vector codec_preferences; int numConfigs = env->GetArrayLength(codecConfigArray); for (int i = 0; i < numConfigs; i++) { jobject jcodecConfig = env->GetObjectArrayElement(codecConfigArray, i); - if (jcodecConfig == nullptr) continue; - if (!env->IsInstanceOf( - jcodecConfig, - android_bluetooth_BluetoothLeAudioCodecConfig.clazz)) { + if (jcodecConfig == nullptr) { + continue; + } + if (!env->IsInstanceOf(jcodecConfig, android_bluetooth_BluetoothLeAudioCodecConfig.clazz)) { log::error("Invalid BluetoothLeAudioCodecConfig instance"); continue; } - jint codecType = env->CallIntMethod( - jcodecConfig, - android_bluetooth_BluetoothLeAudioCodecConfig.getCodecType); + jint codecType = env->CallIntMethod(jcodecConfig, + android_bluetooth_BluetoothLeAudioCodecConfig.getCodecType); btle_audio_codec_config_t codec_config = { - .codec_type = static_cast(codecType)}; + .codec_type = static_cast(codecType)}; codec_preferences.push_back(codec_config); } return codec_preferences; } -static void initNative(JNIEnv* env, jobject object, - jobjectArray codecOffloadingArray) { +static void initNative(JNIEnv* env, jobject object, jobjectArray codecOffloadingArray) { std::unique_lock interface_lock(interface_mutex); std::unique_lock callbacks_lock(callbacks_mutex); @@ -426,28 +423,24 @@ static void initNative(JNIEnv* env, jobject object, return; } - android_bluetooth_BluetoothLeAudioCodecConfig.clazz = - (jclass)env->NewGlobalRef( + android_bluetooth_BluetoothLeAudioCodecConfig.clazz = (jclass)env->NewGlobalRef( env->FindClass("android/bluetooth/BluetoothLeAudioCodecConfig")); if (android_bluetooth_BluetoothLeAudioCodecConfig.clazz == nullptr) { - log::error( - "Failed to allocate Global Ref for BluetoothLeAudioCodecConfig class"); + log::error("Failed to allocate Global Ref for BluetoothLeAudioCodecConfig class"); return; } sLeAudioClientInterface = - (LeAudioClientInterface*)btInf->get_profile_interface( - BT_PROFILE_LE_AUDIO_ID); + (LeAudioClientInterface*)btInf->get_profile_interface(BT_PROFILE_LE_AUDIO_ID); if (sLeAudioClientInterface == nullptr) { log::error("Failed to get Bluetooth LeAudio Interface"); return; } std::vector codec_offloading = - prepareCodecPreferences(env, object, codecOffloadingArray); + prepareCodecPreferences(env, object, codecOffloadingArray); - sLeAudioClientInterface->Initialize(&sLeAudioClientCallbacks, - codec_offloading); + sLeAudioClientInterface->Initialize(&sLeAudioClientCallbacks, codec_offloading); } static void cleanupNative(JNIEnv* env, jobject /* object */) { @@ -474,11 +467,12 @@ static void cleanupNative(JNIEnv* env, jobject /* object */) { } } -static jboolean connectLeAudioNative(JNIEnv* env, jobject /* object */, - jbyteArray address) { +static jboolean connectLeAudioNative(JNIEnv* env, jobject /* object */, jbyteArray address) { log::info(""); std::shared_lock lock(interface_mutex); - if (!sLeAudioClientInterface) return JNI_FALSE; + if (!sLeAudioClientInterface) { + return JNI_FALSE; + } jbyte* addr = env->GetByteArrayElements(address, nullptr); if (!addr) { @@ -492,11 +486,12 @@ static jboolean connectLeAudioNative(JNIEnv* env, jobject /* object */, return JNI_TRUE; } -static jboolean disconnectLeAudioNative(JNIEnv* env, jobject /* object */, - jbyteArray address) { +static jboolean disconnectLeAudioNative(JNIEnv* env, jobject /* object */, jbyteArray address) { log::info(""); std::shared_lock lock(interface_mutex); - if (!sLeAudioClientInterface) return JNI_FALSE; + if (!sLeAudioClientInterface) { + return JNI_FALSE; + } jbyte* addr = env->GetByteArrayElements(address, nullptr); if (!addr) { @@ -510,8 +505,8 @@ static jboolean disconnectLeAudioNative(JNIEnv* env, jobject /* object */, return JNI_TRUE; } -static jboolean setEnableStateNative(JNIEnv* env, jobject /* object */, - jbyteArray address, jboolean enabled) { +static jboolean setEnableStateNative(JNIEnv* env, jobject /* object */, jbyteArray address, + jboolean enabled) { std::shared_lock lock(interface_mutex); jbyte* addr = env->GetByteArrayElements(address, nullptr); @@ -531,8 +526,8 @@ static jboolean setEnableStateNative(JNIEnv* env, jobject /* object */, return JNI_TRUE; } -static jboolean groupAddNodeNative(JNIEnv* env, jobject /* object */, - jint group_id, jbyteArray address) { +static jboolean groupAddNodeNative(JNIEnv* env, jobject /* object */, jint group_id, + jbyteArray address) { std::shared_lock lock(interface_mutex); jbyte* addr = env->GetByteArrayElements(address, nullptr); @@ -553,8 +548,8 @@ static jboolean groupAddNodeNative(JNIEnv* env, jobject /* object */, return JNI_TRUE; } -static jboolean groupRemoveNodeNative(JNIEnv* env, jobject /* object */, - jint group_id, jbyteArray address) { +static jboolean groupRemoveNodeNative(JNIEnv* env, jobject /* object */, jint group_id, + jbyteArray address) { std::shared_lock lock(interface_mutex); if (!sLeAudioClientInterface) { log::error("Failed to get the Bluetooth LeAudio Interface"); @@ -573,8 +568,7 @@ static jboolean groupRemoveNodeNative(JNIEnv* env, jobject /* object */, return JNI_TRUE; } -static void groupSetActiveNative(JNIEnv* /* env */, jobject /* object */, - jint group_id) { +static void groupSetActiveNative(JNIEnv* /* env */, jobject /* object */, jint group_id) { log::info(""); std::shared_lock lock(interface_mutex); @@ -586,110 +580,84 @@ static void groupSetActiveNative(JNIEnv* /* env */, jobject /* object */, sLeAudioClientInterface->GroupSetActive(group_id); } -static void setCodecConfigPreferenceNative(JNIEnv* env, jobject /* object */, - jint group_id, - jobject inputCodecConfig, - jobject outputCodecConfig) { +static void setCodecConfigPreferenceNative(JNIEnv* env, jobject /* object */, jint group_id, + jobject inputCodecConfig, jobject outputCodecConfig) { std::shared_lock lock(interface_mutex); - if (!env->IsInstanceOf(inputCodecConfig, - android_bluetooth_BluetoothLeAudioCodecConfig.clazz) || - !env->IsInstanceOf(outputCodecConfig, - android_bluetooth_BluetoothLeAudioCodecConfig.clazz)) { + if (!env->IsInstanceOf(inputCodecConfig, android_bluetooth_BluetoothLeAudioCodecConfig.clazz) || + !env->IsInstanceOf(outputCodecConfig, android_bluetooth_BluetoothLeAudioCodecConfig.clazz)) { log::error("Invalid BluetoothLeAudioCodecConfig instance"); return; } jint inputCodecType = env->CallIntMethod( - inputCodecConfig, - android_bluetooth_BluetoothLeAudioCodecConfig.getCodecType); + inputCodecConfig, android_bluetooth_BluetoothLeAudioCodecConfig.getCodecType); jint inputSampleRate = env->CallIntMethod( - inputCodecConfig, - android_bluetooth_BluetoothLeAudioCodecConfig.getSampleRate); + inputCodecConfig, android_bluetooth_BluetoothLeAudioCodecConfig.getSampleRate); jint inputBitsPerSample = env->CallIntMethod( - inputCodecConfig, - android_bluetooth_BluetoothLeAudioCodecConfig.getBitsPerSample); + inputCodecConfig, android_bluetooth_BluetoothLeAudioCodecConfig.getBitsPerSample); jint inputChannelCount = env->CallIntMethod( - inputCodecConfig, - android_bluetooth_BluetoothLeAudioCodecConfig.getChannelCount); + inputCodecConfig, android_bluetooth_BluetoothLeAudioCodecConfig.getChannelCount); jint inputFrameDuration = env->CallIntMethod( - inputCodecConfig, - android_bluetooth_BluetoothLeAudioCodecConfig.getFrameDuration); + inputCodecConfig, android_bluetooth_BluetoothLeAudioCodecConfig.getFrameDuration); jint inputOctetsPerFrame = env->CallIntMethod( - inputCodecConfig, - android_bluetooth_BluetoothLeAudioCodecConfig.getOctetsPerFrame); + inputCodecConfig, android_bluetooth_BluetoothLeAudioCodecConfig.getOctetsPerFrame); jint inputCodecPriority = env->CallIntMethod( - inputCodecConfig, - android_bluetooth_BluetoothLeAudioCodecConfig.getCodecPriority); + inputCodecConfig, android_bluetooth_BluetoothLeAudioCodecConfig.getCodecPriority); btle_audio_codec_config_t input_codec_config = { - .codec_type = static_cast(inputCodecType), - .sample_rate = - static_cast(inputSampleRate), - .bits_per_sample = - static_cast(inputBitsPerSample), - .channel_count = - static_cast(inputChannelCount), - .frame_duration = - static_cast(inputFrameDuration), - .octets_per_frame = static_cast(inputOctetsPerFrame), - .codec_priority = static_cast(inputCodecPriority), + .codec_type = static_cast(inputCodecType), + .sample_rate = static_cast(inputSampleRate), + .bits_per_sample = static_cast(inputBitsPerSample), + .channel_count = static_cast(inputChannelCount), + .frame_duration = static_cast(inputFrameDuration), + .octets_per_frame = static_cast(inputOctetsPerFrame), + .codec_priority = static_cast(inputCodecPriority), }; jint outputCodecType = env->CallIntMethod( - outputCodecConfig, - android_bluetooth_BluetoothLeAudioCodecConfig.getCodecType); + outputCodecConfig, android_bluetooth_BluetoothLeAudioCodecConfig.getCodecType); jint outputSampleRate = env->CallIntMethod( - outputCodecConfig, - android_bluetooth_BluetoothLeAudioCodecConfig.getSampleRate); + outputCodecConfig, android_bluetooth_BluetoothLeAudioCodecConfig.getSampleRate); jint outputBitsPerSample = env->CallIntMethod( - outputCodecConfig, - android_bluetooth_BluetoothLeAudioCodecConfig.getBitsPerSample); + outputCodecConfig, android_bluetooth_BluetoothLeAudioCodecConfig.getBitsPerSample); jint outputChannelCount = env->CallIntMethod( - outputCodecConfig, - android_bluetooth_BluetoothLeAudioCodecConfig.getChannelCount); + outputCodecConfig, android_bluetooth_BluetoothLeAudioCodecConfig.getChannelCount); jint outputFrameDuration = env->CallIntMethod( - outputCodecConfig, - android_bluetooth_BluetoothLeAudioCodecConfig.getFrameDuration); + outputCodecConfig, android_bluetooth_BluetoothLeAudioCodecConfig.getFrameDuration); jint outputOctetsPerFrame = env->CallIntMethod( - outputCodecConfig, - android_bluetooth_BluetoothLeAudioCodecConfig.getOctetsPerFrame); + outputCodecConfig, android_bluetooth_BluetoothLeAudioCodecConfig.getOctetsPerFrame); jint outputCodecPriority = env->CallIntMethod( - outputCodecConfig, - android_bluetooth_BluetoothLeAudioCodecConfig.getCodecPriority); + outputCodecConfig, android_bluetooth_BluetoothLeAudioCodecConfig.getCodecPriority); btle_audio_codec_config_t output_codec_config = { - .codec_type = static_cast(outputCodecType), - .sample_rate = - static_cast(outputSampleRate), - .bits_per_sample = - static_cast(outputBitsPerSample), - .channel_count = - static_cast(outputChannelCount), - .frame_duration = - static_cast(outputFrameDuration), - .octets_per_frame = static_cast(outputOctetsPerFrame), - .codec_priority = static_cast(outputCodecPriority), + .codec_type = static_cast(outputCodecType), + .sample_rate = static_cast(outputSampleRate), + .bits_per_sample = static_cast(outputBitsPerSample), + .channel_count = static_cast(outputChannelCount), + .frame_duration = static_cast(outputFrameDuration), + .octets_per_frame = static_cast(outputOctetsPerFrame), + .codec_priority = static_cast(outputCodecPriority), }; - sLeAudioClientInterface->SetCodecConfigPreference( - group_id, input_codec_config, output_codec_config); + sLeAudioClientInterface->SetCodecConfigPreference(group_id, input_codec_config, + output_codec_config); } -static void setCcidInformationNative(JNIEnv* /* env */, jobject /* object */, - jint ccid, jint contextType) { +static void setCcidInformationNative(JNIEnv* /* env */, jobject /* object */, jint ccid, + jint contextType) { std::shared_lock lock(interface_mutex); if (!sLeAudioClientInterface) { log::error("Failed to get the Bluetooth LeAudio Interface"); @@ -699,8 +667,7 @@ static void setCcidInformationNative(JNIEnv* /* env */, jobject /* object */, sLeAudioClientInterface->SetCcidInformation(ccid, contextType); } -static void setInCallNative(JNIEnv* /* env */, jobject /* object */, - jboolean inCall) { +static void setInCallNative(JNIEnv* /* env */, jobject /* object */, jboolean inCall) { std::shared_lock lock(interface_mutex); if (!sLeAudioClientInterface) { log::error("Failed to get the Bluetooth LeAudio Interface"); @@ -710,8 +677,8 @@ static void setInCallNative(JNIEnv* /* env */, jobject /* object */, sLeAudioClientInterface->SetInCall(inCall); } -static void setUnicastMonitorModeNative(JNIEnv* /* env */, jobject /* object */, - jint direction, jboolean enable) { +static void setUnicastMonitorModeNative(JNIEnv* /* env */, jobject /* object */, jint direction, + jboolean enable) { std::shared_lock lock(interface_mutex); if (!sLeAudioClientInterface) { log::error("Failed to get the Bluetooth LeAudio Interface"); @@ -721,31 +688,29 @@ static void setUnicastMonitorModeNative(JNIEnv* /* env */, jobject /* object */, sLeAudioClientInterface->SetUnicastMonitorMode(direction, enable); } -static void sendAudioProfilePreferencesNative( - JNIEnv* /* env */, jint groupId, jboolean isOutputPreferenceLeAudio, - jboolean isDuplexPreferenceLeAudio) { +static void sendAudioProfilePreferencesNative(JNIEnv* /* env */, jint groupId, + jboolean isOutputPreferenceLeAudio, + jboolean isDuplexPreferenceLeAudio) { std::shared_lock lock(interface_mutex); if (!sLeAudioClientInterface) { log::error("Failed to get the Bluetooth LeAudio Interface"); return; } - sLeAudioClientInterface->SendAudioProfilePreferences( - groupId, isOutputPreferenceLeAudio, isDuplexPreferenceLeAudio); + sLeAudioClientInterface->SendAudioProfilePreferences(groupId, isOutputPreferenceLeAudio, + isDuplexPreferenceLeAudio); } -static void setGroupAllowedContextMaskNative(JNIEnv* /* env */, - jobject /* object */, jint groupId, - jint sinkContextTypes, - jint sourceContextTypes) { +static void setGroupAllowedContextMaskNative(JNIEnv* /* env */, jobject /* object */, jint groupId, + jint sinkContextTypes, jint sourceContextTypes) { std::shared_lock lock(interface_mutex); if (!sLeAudioClientInterface) { log::error("Failed to get the Bluetooth LeAudio Interface"); return; } - log::info("group_id: {}, sink context types: {}, source context types: {}", - groupId, sinkContextTypes, sourceContextTypes); + log::info("group_id: {}, sink context types: {}, source context types: {}", groupId, + sinkContextTypes, sourceContextTypes); sLeAudioClientInterface->SetGroupAllowedContextMask(groupId, sinkContextTypes, sourceContextTypes); @@ -763,9 +728,8 @@ static std::shared_timed_mutex sBroadcasterInterfaceMutex; static jobject sBroadcasterCallbacksObj = nullptr; static std::shared_timed_mutex sBroadcasterCallbacksMutex; -#define VEC_UINT8_TO_UINT32(vec) \ - ((vec.data()[3] << 24) + (vec.data()[2] << 16) + (vec.data()[1] << 8) + \ - vec.data()[0]) +#define VEC_UINT8_TO_UINT32(vec) \ + ((vec.data()[3] << 24) + (vec.data()[2] << 16) + (vec.data()[1] << 8) + vec.data()[0]) #define VEC_UINT8_TO_UINT16(vec) (((vec).data()[1] << 8) + ((vec).data()[0])) @@ -777,8 +741,8 @@ size_t RawPacketSize(const std::map>& values) { return bytes; } -jbyteArray prepareRawLtvArray( - JNIEnv* env, const std::map>& metadata) { +jbyteArray prepareRawLtvArray(JNIEnv* env, + const std::map>& metadata) { auto raw_meta_size = RawPacketSize(metadata); jbyteArray raw_metadata = env->NewByteArray(raw_meta_size); @@ -794,8 +758,7 @@ jbyteArray prepareRawLtvArray( env->SetByteArrayRegion(raw_metadata, offset, 1, <v_sz); offset += 1; // Type - env->SetByteArrayRegion(raw_metadata, offset, 1, - (const jbyte*)&kv_pair.first); + env->SetByteArrayRegion(raw_metadata, offset, 1, (const jbyte*)&kv_pair.first); offset += 1; // Value env->SetByteArrayRegion(raw_metadata, offset, kv_pair.second.size(), @@ -806,102 +769,90 @@ jbyteArray prepareRawLtvArray( return raw_metadata; } -static jlong getAudioLocationOrDefault( - const std::map>& metadata, - jlong default_location) { - if (metadata.count( - bluetooth::le_audio::kLeAudioLtvTypeAudioChannelAllocation) == 0) +static jlong getAudioLocationOrDefault(const std::map>& metadata, + jlong default_location) { + if (metadata.count(bluetooth::le_audio::kLeAudioLtvTypeAudioChannelAllocation) == 0) { return default_location; + } - auto& vec = - metadata.at(bluetooth::le_audio::kLeAudioLtvTypeAudioChannelAllocation); + auto& vec = metadata.at(bluetooth::le_audio::kLeAudioLtvTypeAudioChannelAllocation); return VEC_UINT8_TO_UINT32(vec); } -static jint getSamplingFrequencyOrDefault( - const std::map>& metadata, - jint default_sampling_frequency) { - if (metadata.count(bluetooth::le_audio::kLeAudioLtvTypeSamplingFreq) == 0) +static jint getSamplingFrequencyOrDefault(const std::map>& metadata, + jint default_sampling_frequency) { + if (metadata.count(bluetooth::le_audio::kLeAudioLtvTypeSamplingFreq) == 0) { return default_sampling_frequency; + } auto& vec = metadata.at(bluetooth::le_audio::kLeAudioLtvTypeSamplingFreq); return (jint)(vec.data()[0]); } -static jint getFrameDurationOrDefault( - const std::map>& metadata, - jint default_frame_duration) { - if (metadata.count(bluetooth::le_audio::kLeAudioLtvTypeFrameDuration) == 0) +static jint getFrameDurationOrDefault(const std::map>& metadata, + jint default_frame_duration) { + if (metadata.count(bluetooth::le_audio::kLeAudioLtvTypeFrameDuration) == 0) { return default_frame_duration; + } auto& vec = metadata.at(bluetooth::le_audio::kLeAudioLtvTypeFrameDuration); return (jint)(vec.data()[0]); } -static jint getOctetsPerFrameOrDefault( - const std::map>& metadata, - jint default_octets_per_frame) { - if (metadata.count(bluetooth::le_audio::kLeAudioLtvTypeOctetsPerCodecFrame) == - 0) +static jint getOctetsPerFrameOrDefault(const std::map>& metadata, + jint default_octets_per_frame) { + if (metadata.count(bluetooth::le_audio::kLeAudioLtvTypeOctetsPerCodecFrame) == 0) { return default_octets_per_frame; + } - auto& vec = - metadata.at(bluetooth::le_audio::kLeAudioLtvTypeOctetsPerCodecFrame); + auto& vec = metadata.at(bluetooth::le_audio::kLeAudioLtvTypeOctetsPerCodecFrame); return VEC_UINT8_TO_UINT16(vec); } jobject prepareLeAudioCodecConfigMetadataObject( - JNIEnv* env, const std::map>& metadata) { + JNIEnv* env, const std::map>& metadata) { jlong audio_location = getAudioLocationOrDefault(metadata, -1); jint sampling_frequency = getSamplingFrequencyOrDefault(metadata, 0); jint frame_duration = getFrameDurationOrDefault(metadata, -1); jint octets_per_frame = getOctetsPerFrameOrDefault(metadata, 0); - ScopedLocalRef raw_metadata(env, - prepareRawLtvArray(env, metadata)); + ScopedLocalRef raw_metadata(env, prepareRawLtvArray(env, metadata)); if (!raw_metadata.get()) { log::error("Failed to create raw metadata jbyteArray"); return nullptr; } - jobject obj = env->NewObject( - android_bluetooth_BluetoothLeAudioCodecConfigMetadata.clazz, - android_bluetooth_BluetoothLeAudioCodecConfigMetadata.constructor, - audio_location, sampling_frequency, frame_duration, octets_per_frame, - raw_metadata.get()); + jobject obj = env->NewObject(android_bluetooth_BluetoothLeAudioCodecConfigMetadata.clazz, + android_bluetooth_BluetoothLeAudioCodecConfigMetadata.constructor, + audio_location, sampling_frequency, frame_duration, octets_per_frame, + raw_metadata.get()); return obj; } jobject prepareLeBroadcastChannelObject( - JNIEnv* env, - const bluetooth::le_audio::BasicAudioAnnouncementBisConfig& bis_config) { + JNIEnv* env, const bluetooth::le_audio::BasicAudioAnnouncementBisConfig& bis_config) { ScopedLocalRef meta_object( - env, prepareLeAudioCodecConfigMetadataObject( - env, bis_config.codec_specific_params)); + env, prepareLeAudioCodecConfigMetadataObject(env, bis_config.codec_specific_params)); if (!meta_object.get()) { log::error("Failed to create new metadata object for bis config"); return nullptr; } - jobject obj = - env->NewObject(android_bluetooth_BluetoothLeBroadcastChannel.clazz, - android_bluetooth_BluetoothLeBroadcastChannel.constructor, - false, bis_config.bis_index, meta_object.get()); + jobject obj = env->NewObject(android_bluetooth_BluetoothLeBroadcastChannel.clazz, + android_bluetooth_BluetoothLeBroadcastChannel.constructor, false, + bis_config.bis_index, meta_object.get()); return obj; } jobject prepareLeAudioContentMetadataObject( - JNIEnv* env, const std::map>& metadata) { + JNIEnv* env, const std::map>& metadata) { jstring program_info_str = nullptr; if (metadata.count(bluetooth::le_audio::kLeAudioMetadataTypeProgramInfo)) { // Convert the metadata vector to string with null terminator std::string p_str( - (const char*)metadata - .at(bluetooth::le_audio::kLeAudioMetadataTypeProgramInfo) - .data(), - metadata.at(bluetooth::le_audio::kLeAudioMetadataTypeProgramInfo) - .size()); + (const char*)metadata.at(bluetooth::le_audio::kLeAudioMetadataTypeProgramInfo).data(), + metadata.at(bluetooth::le_audio::kLeAudioMetadataTypeProgramInfo).size()); program_info_str = env->NewStringUTF(p_str.c_str()); if (!program_info_str) { @@ -914,10 +865,8 @@ jobject prepareLeAudioContentMetadataObject( if (metadata.count(bluetooth::le_audio::kLeAudioMetadataTypeLanguage)) { // Convert the metadata vector to string with null terminator std::string l_str( - (const char*)metadata - .at(bluetooth::le_audio::kLeAudioMetadataTypeLanguage) - .data(), - metadata.at(bluetooth::le_audio::kLeAudioMetadataTypeLanguage).size()); + (const char*)metadata.at(bluetooth::le_audio::kLeAudioMetadataTypeLanguage).data(), + metadata.at(bluetooth::le_audio::kLeAudioMetadataTypeLanguage).size()); language_str = env->NewStringUTF(l_str.c_str()); if (!language_str) { @@ -927,17 +876,15 @@ jobject prepareLeAudioContentMetadataObject( } // This can be nullptr - ScopedLocalRef raw_metadata(env, - prepareRawLtvArray(env, metadata)); + ScopedLocalRef raw_metadata(env, prepareRawLtvArray(env, metadata)); if (!raw_metadata.get()) { log::error("Failed to create raw_metadata jbyteArray"); return nullptr; } - jobject obj = env->NewObject( - android_bluetooth_BluetoothLeAudioContentMetadata.clazz, - android_bluetooth_BluetoothLeAudioContentMetadata.constructor, - program_info_str, language_str, raw_metadata.get()); + jobject obj = env->NewObject(android_bluetooth_BluetoothLeAudioContentMetadata.clazz, + android_bluetooth_BluetoothLeAudioContentMetadata.constructor, + program_info_str, language_str, raw_metadata.get()); if (program_info_str) { env->DeleteLocalRef(program_info_str); @@ -951,19 +898,16 @@ jobject prepareLeAudioContentMetadataObject( } jobject prepareLeBroadcastChannelListObject( - JNIEnv* env, - const std::vector& - bis_configs) { - jobject array = env->NewObject(java_util_ArrayList.clazz, - java_util_ArrayList.constructor); + JNIEnv* env, + const std::vector& bis_configs) { + jobject array = env->NewObject(java_util_ArrayList.clazz, java_util_ArrayList.constructor); if (!array) { log::error("Failed to create array for subgroups"); return nullptr; } for (const auto& el : bis_configs) { - ScopedLocalRef channel_obj( - env, prepareLeBroadcastChannelObject(env, el)); + ScopedLocalRef channel_obj(env, prepareLeBroadcastChannelObject(env, el)); if (!channel_obj.get()) { log::error("Failed to create new channel object"); return nullptr; @@ -975,58 +919,52 @@ jobject prepareLeBroadcastChannelListObject( } jobject prepareLeBroadcastSubgroupObject( - JNIEnv* env, - const bluetooth::le_audio::BasicAudioAnnouncementSubgroup& subgroup) { + JNIEnv* env, const bluetooth::le_audio::BasicAudioAnnouncementSubgroup& subgroup) { // Serialize codec ID - jlong jlong_codec_id = - subgroup.codec_config.codec_id | - ((jlong)subgroup.codec_config.vendor_company_id << 16) | - ((jlong)subgroup.codec_config.vendor_codec_id << 32); + jlong jlong_codec_id = subgroup.codec_config.codec_id | + ((jlong)subgroup.codec_config.vendor_company_id << 16) | + ((jlong)subgroup.codec_config.vendor_codec_id << 32); ScopedLocalRef codec_config_meta_obj( - env, prepareLeAudioCodecConfigMetadataObject( - env, subgroup.codec_config.codec_specific_params)); + env, prepareLeAudioCodecConfigMetadataObject( + env, subgroup.codec_config.codec_specific_params)); if (!codec_config_meta_obj.get()) { log::error("Failed to create new codec config metadata"); return nullptr; } ScopedLocalRef content_meta_obj( - env, prepareLeAudioContentMetadataObject(env, subgroup.metadata)); + env, prepareLeAudioContentMetadataObject(env, subgroup.metadata)); if (!content_meta_obj.get()) { log::error("Failed to create new codec config metadata"); return nullptr; } ScopedLocalRef channel_list_obj( - env, prepareLeBroadcastChannelListObject(env, subgroup.bis_configs)); + env, prepareLeBroadcastChannelListObject(env, subgroup.bis_configs)); if (!channel_list_obj.get()) { log::error("Failed to create new codec config metadata"); return nullptr; } // Create the subgroup - return env->NewObject( - android_bluetooth_BluetoothLeBroadcastSubgroup.clazz, - android_bluetooth_BluetoothLeBroadcastSubgroup.constructor, - jlong_codec_id, codec_config_meta_obj.get(), content_meta_obj.get(), - channel_list_obj.get()); + return env->NewObject(android_bluetooth_BluetoothLeBroadcastSubgroup.clazz, + android_bluetooth_BluetoothLeBroadcastSubgroup.constructor, jlong_codec_id, + codec_config_meta_obj.get(), content_meta_obj.get(), + channel_list_obj.get()); } jobject prepareLeBroadcastSubgroupListObject( - JNIEnv* env, - const std::vector& - subgroup_configs) { - jobject array = env->NewObject(java_util_ArrayList.clazz, - java_util_ArrayList.constructor); + JNIEnv* env, + const std::vector& subgroup_configs) { + jobject array = env->NewObject(java_util_ArrayList.clazz, java_util_ArrayList.constructor); if (!array) { log::error("Failed to create array for subgroups"); return nullptr; } for (const auto& el : subgroup_configs) { - ScopedLocalRef subgroup_obj( - env, prepareLeBroadcastSubgroupObject(env, el)); + ScopedLocalRef subgroup_obj(env, prepareLeBroadcastSubgroupObject(env, el)); if (!subgroup_obj.get()) { log::error("Failed to create new subgroup object"); return nullptr; @@ -1037,8 +975,7 @@ jobject prepareLeBroadcastSubgroupListObject( return array; } -jobject prepareBluetoothDeviceObject(JNIEnv* env, const RawAddress& addr, - int addr_type) { +jobject prepareBluetoothDeviceObject(JNIEnv* env, const RawAddress& addr, int addr_type) { // The address string has to be uppercase or the BluetoothDevice constructor // will treat it as invalid. auto addr_str = addr.ToString(); @@ -1052,25 +989,23 @@ jobject prepareBluetoothDeviceObject(JNIEnv* env, const RawAddress& addr, } return env->NewObject(android_bluetooth_BluetoothDevice.clazz, - android_bluetooth_BluetoothDevice.constructor, - addr_jstr.get(), (jint)addr_type); + android_bluetooth_BluetoothDevice.constructor, addr_jstr.get(), + (jint)addr_type); } jobject prepareBluetoothLeBroadcastMetadataObject( - JNIEnv* env, - const bluetooth::le_audio::BroadcastMetadata& broadcast_metadata) { + JNIEnv* env, const bluetooth::le_audio::BroadcastMetadata& broadcast_metadata) { ScopedLocalRef device_obj( - env, prepareBluetoothDeviceObject(env, broadcast_metadata.addr, - broadcast_metadata.addr_type)); + env, + prepareBluetoothDeviceObject(env, broadcast_metadata.addr, broadcast_metadata.addr_type)); if (!device_obj.get()) { log::error("Failed to create new BluetoothDevice"); return nullptr; } ScopedLocalRef subgroup_list_obj( - env, - prepareLeBroadcastSubgroupListObject( - env, broadcast_metadata.basic_audio_announcement.subgroup_configs)); + env, prepareLeBroadcastSubgroupListObject( + env, broadcast_metadata.basic_audio_announcement.subgroup_configs)); if (!subgroup_list_obj.get()) { log::error("Failed to create new Subgroup array"); return nullptr; @@ -1081,9 +1016,8 @@ jobject prepareBluetoothLeBroadcastMetadataObject( if (broadcast_metadata.broadcast_code) { auto& nativeCode = broadcast_metadata.broadcast_code.value(); nativeCodeSize = - std::find_if(nativeCode.cbegin(), nativeCode.cend(), - [](int x) { return x == 0x00; }) - - nativeCode.cbegin(); + std::find_if(nativeCode.cbegin(), nativeCode.cend(), [](int x) { return x == 0x00; }) - + nativeCode.cbegin(); } ScopedLocalRef code(env, env->NewByteArray(nativeCodeSize)); @@ -1093,15 +1027,13 @@ jobject prepareBluetoothLeBroadcastMetadataObject( } if (broadcast_metadata.broadcast_code) { - env->SetByteArrayRegion( - code.get(), 0, nativeCodeSize, - (const jbyte*)broadcast_metadata.broadcast_code->data()); - log::assert_that(!env->ExceptionCheck(), - "assert failed: !env->ExceptionCheck()"); + env->SetByteArrayRegion(code.get(), 0, nativeCodeSize, + (const jbyte*)broadcast_metadata.broadcast_code->data()); + log::assert_that(!env->ExceptionCheck(), "assert failed: !env->ExceptionCheck()"); } ScopedLocalRef broadcast_name( - env, env->NewStringUTF(broadcast_metadata.broadcast_name.c_str())); + env, env->NewStringUTF(broadcast_metadata.broadcast_name.c_str())); if (!broadcast_name.get()) { log::error("Failed to create new broadcast name String"); return nullptr; @@ -1113,36 +1045,33 @@ jobject prepareBluetoothLeBroadcastMetadataObject( // Set bit 0 for AUDIO_CONFIG_QUALITY_STANDARD audio_cfg_quality |= 0x1 << bluetooth::le_audio::QUALITY_STANDARD; } - if (broadcast_metadata.public_announcement.features & - bluetooth::le_audio::kLeAudioQualityHigh) { + if (broadcast_metadata.public_announcement.features & bluetooth::le_audio::kLeAudioQualityHigh) { // Set bit 1 for AUDIO_CONFIG_QUALITY_HIGH audio_cfg_quality |= 0x1 << bluetooth::le_audio::QUALITY_HIGH; } ScopedLocalRef public_meta_obj( - env, prepareLeAudioContentMetadataObject( - env, broadcast_metadata.public_announcement.metadata)); + env, prepareLeAudioContentMetadataObject( + env, broadcast_metadata.public_announcement.metadata)); if (!public_meta_obj.get()) { log::error("Failed to create new public metadata obj"); return nullptr; } return env->NewObject( - android_bluetooth_BluetoothLeBroadcastMetadata.clazz, - android_bluetooth_BluetoothLeBroadcastMetadata.constructor, - (jint)broadcast_metadata.addr_type, device_obj.get(), - (jint)broadcast_metadata.adv_sid, (jint)broadcast_metadata.broadcast_id, - (jint)broadcast_metadata.pa_interval, - broadcast_metadata.broadcast_code ? true : false, - broadcast_metadata.is_public, broadcast_name.get(), - broadcast_metadata.broadcast_code ? code.get() : nullptr, - (jint)broadcast_metadata.basic_audio_announcement.presentation_delay_us, - audio_cfg_quality, (jint)bluetooth::le_audio::kLeAudioSourceRssiUnknown, - public_meta_obj.get(), subgroup_list_obj.get()); + android_bluetooth_BluetoothLeBroadcastMetadata.clazz, + android_bluetooth_BluetoothLeBroadcastMetadata.constructor, + (jint)broadcast_metadata.addr_type, device_obj.get(), (jint)broadcast_metadata.adv_sid, + (jint)broadcast_metadata.broadcast_id, (jint)broadcast_metadata.pa_interval, + broadcast_metadata.broadcast_code ? true : false, broadcast_metadata.is_public, + broadcast_name.get(), broadcast_metadata.broadcast_code ? code.get() : nullptr, + (jint)broadcast_metadata.basic_audio_announcement.presentation_delay_us, + audio_cfg_quality, (jint)bluetooth::le_audio::kLeAudioSourceRssiUnknown, + public_meta_obj.get(), subgroup_list_obj.get()); } class LeAudioBroadcasterCallbacksImpl : public LeAudioBroadcasterCallbacks { - public: +public: ~LeAudioBroadcasterCallbacksImpl() = default; void OnBroadcastCreated(uint32_t broadcast_id, bool success) override { @@ -1151,10 +1080,11 @@ class LeAudioBroadcasterCallbacksImpl : public LeAudioBroadcasterCallbacks { std::shared_lock lock(sBroadcasterCallbacksMutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || sBroadcasterCallbacksObj == nullptr) return; - sCallbackEnv->CallVoidMethod(sBroadcasterCallbacksObj, - method_onBroadcastCreated, (jint)broadcast_id, - success ? JNI_TRUE : JNI_FALSE); + if (!sCallbackEnv.valid() || sBroadcasterCallbacksObj == nullptr) { + return; + } + sCallbackEnv->CallVoidMethod(sBroadcasterCallbacksObj, method_onBroadcastCreated, + (jint)broadcast_id, success ? JNI_TRUE : JNI_FALSE); } void OnBroadcastDestroyed(uint32_t broadcast_id) override { @@ -1163,41 +1093,43 @@ class LeAudioBroadcasterCallbacksImpl : public LeAudioBroadcasterCallbacks { std::shared_lock lock(sBroadcasterCallbacksMutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || sBroadcasterCallbacksObj == nullptr) return; - sCallbackEnv->CallVoidMethod(sBroadcasterCallbacksObj, - method_onBroadcastDestroyed, + if (!sCallbackEnv.valid() || sBroadcasterCallbacksObj == nullptr) { + return; + } + sCallbackEnv->CallVoidMethod(sBroadcasterCallbacksObj, method_onBroadcastDestroyed, (jint)broadcast_id); } - void OnBroadcastStateChanged(uint32_t broadcast_id, - BroadcastState state) override { + void OnBroadcastStateChanged(uint32_t broadcast_id, BroadcastState state) override { log::info(""); std::shared_lock lock(sBroadcasterCallbacksMutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || sBroadcasterCallbacksObj == nullptr) return; + if (!sCallbackEnv.valid() || sBroadcasterCallbacksObj == nullptr) { + return; + } sCallbackEnv->CallVoidMethod( - sBroadcasterCallbacksObj, method_onBroadcastStateChanged, - (jint)broadcast_id, - (jint) static_cast::type>(state)); + sBroadcasterCallbacksObj, method_onBroadcastStateChanged, (jint)broadcast_id, + (jint) static_cast::type>(state)); } - void OnBroadcastMetadataChanged(uint32_t broadcast_id, - const bluetooth::le_audio::BroadcastMetadata& - broadcast_metadata) override { + void OnBroadcastMetadataChanged( + uint32_t broadcast_id, + const bluetooth::le_audio::BroadcastMetadata& broadcast_metadata) override { log::info(""); std::shared_lock lock(sBroadcasterCallbacksMutex); CallbackEnv sCallbackEnv(__func__); ScopedLocalRef metadata_obj( - sCallbackEnv.get(), prepareBluetoothLeBroadcastMetadataObject( - sCallbackEnv.get(), broadcast_metadata)); + sCallbackEnv.get(), + prepareBluetoothLeBroadcastMetadataObject(sCallbackEnv.get(), broadcast_metadata)); - if (!sCallbackEnv.valid() || sBroadcasterCallbacksObj == nullptr) return; - sCallbackEnv->CallVoidMethod(sBroadcasterCallbacksObj, - method_onBroadcastMetadataChanged, + if (!sCallbackEnv.valid() || sBroadcasterCallbacksObj == nullptr) { + return; + } + sCallbackEnv->CallVoidMethod(sBroadcasterCallbacksObj, method_onBroadcastMetadataChanged, (jint)broadcast_id, metadata_obj.get()); } }; @@ -1205,10 +1137,8 @@ class LeAudioBroadcasterCallbacksImpl : public LeAudioBroadcasterCallbacks { static LeAudioBroadcasterCallbacksImpl sLeAudioBroadcasterCallbacks; static void BroadcasterInitNative(JNIEnv* env, jobject object) { - std::unique_lock interface_lock( - sBroadcasterInterfaceMutex); - std::unique_lock callbacks_lock( - sBroadcasterCallbacksMutex); + std::unique_lock interface_lock(sBroadcasterInterfaceMutex); + std::unique_lock callbacks_lock(sBroadcasterCallbacksMutex); const bt_interface_t* btInf = getBluetoothInterface(); if (btInf == nullptr) { @@ -1216,64 +1146,55 @@ static void BroadcasterInitNative(JNIEnv* env, jobject object) { return; } - android_bluetooth_BluetoothDevice.clazz = (jclass)env->NewGlobalRef( - env->FindClass("android/bluetooth/BluetoothDevice")); + android_bluetooth_BluetoothDevice.clazz = + (jclass)env->NewGlobalRef(env->FindClass("android/bluetooth/BluetoothDevice")); if (android_bluetooth_BluetoothDevice.clazz == nullptr) { log::error("Failed to allocate Global Ref for BluetoothDevice class"); return; } - java_util_ArrayList.clazz = - (jclass)env->NewGlobalRef(env->FindClass("java/util/ArrayList")); + java_util_ArrayList.clazz = (jclass)env->NewGlobalRef(env->FindClass("java/util/ArrayList")); if (java_util_ArrayList.clazz == nullptr) { log::error("Failed to allocate Global Ref for ArrayList class"); return; } - android_bluetooth_BluetoothLeAudioCodecConfigMetadata.clazz = - (jclass)env->NewGlobalRef(env->FindClass( - "android/bluetooth/BluetoothLeAudioCodecConfigMetadata")); + android_bluetooth_BluetoothLeAudioCodecConfigMetadata.clazz = (jclass)env->NewGlobalRef( + env->FindClass("android/bluetooth/BluetoothLeAudioCodecConfigMetadata")); if (android_bluetooth_BluetoothLeAudioCodecConfigMetadata.clazz == nullptr) { log::error( - "Failed to allocate Global Ref for BluetoothLeAudioCodecConfigMetadata " - "class"); + "Failed to allocate Global Ref for BluetoothLeAudioCodecConfigMetadata " + "class"); return; } - android_bluetooth_BluetoothLeAudioContentMetadata.clazz = - (jclass)env->NewGlobalRef( + android_bluetooth_BluetoothLeAudioContentMetadata.clazz = (jclass)env->NewGlobalRef( env->FindClass("android/bluetooth/BluetoothLeAudioContentMetadata")); if (android_bluetooth_BluetoothLeAudioContentMetadata.clazz == nullptr) { log::error( - "Failed to allocate Global Ref for BluetoothLeAudioContentMetadata " - "class"); + "Failed to allocate Global Ref for BluetoothLeAudioContentMetadata " + "class"); return; } - android_bluetooth_BluetoothLeBroadcastSubgroup.clazz = - (jclass)env->NewGlobalRef( + android_bluetooth_BluetoothLeBroadcastSubgroup.clazz = (jclass)env->NewGlobalRef( env->FindClass("android/bluetooth/BluetoothLeBroadcastSubgroup")); if (android_bluetooth_BluetoothLeBroadcastSubgroup.clazz == nullptr) { - log::error( - "Failed to allocate Global Ref for BluetoothLeBroadcastSubgroup class"); + log::error("Failed to allocate Global Ref for BluetoothLeBroadcastSubgroup class"); return; } - android_bluetooth_BluetoothLeBroadcastChannel.clazz = - (jclass)env->NewGlobalRef( + android_bluetooth_BluetoothLeBroadcastChannel.clazz = (jclass)env->NewGlobalRef( env->FindClass("android/bluetooth/BluetoothLeBroadcastChannel")); if (android_bluetooth_BluetoothLeBroadcastChannel.clazz == nullptr) { - log::error( - "Failed to allocate Global Ref for BluetoothLeBroadcastChannel class"); + log::error("Failed to allocate Global Ref for BluetoothLeBroadcastChannel class"); return; } - android_bluetooth_BluetoothLeBroadcastMetadata.clazz = - (jclass)env->NewGlobalRef( + android_bluetooth_BluetoothLeBroadcastMetadata.clazz = (jclass)env->NewGlobalRef( env->FindClass("android/bluetooth/BluetoothLeBroadcastMetadata")); if (android_bluetooth_BluetoothLeBroadcastMetadata.clazz == nullptr) { - log::error( - "Failed to allocate Global Ref for BluetoothLeBroadcastMetadata class"); + log::error("Failed to allocate Global Ref for BluetoothLeBroadcastMetadata class"); return; } @@ -1284,13 +1205,11 @@ static void BroadcasterInitNative(JNIEnv* env, jobject object) { } if ((sBroadcasterCallbacksObj = env->NewGlobalRef(object)) == nullptr) { - log::error( - "Failed to allocate Global Ref for LeAudio Broadcaster Callbacks"); + log::error("Failed to allocate Global Ref for LeAudio Broadcaster Callbacks"); return; } - sLeAudioBroadcasterInterface = - (LeAudioBroadcasterInterface*)btInf->get_profile_interface( + sLeAudioBroadcasterInterface = (LeAudioBroadcasterInterface*)btInf->get_profile_interface( BT_PROFILE_LE_AUDIO_BROADCASTER_ID); if (sLeAudioBroadcasterInterface == nullptr) { log::error("Failed to get Bluetooth LeAudio Broadcaster Interface"); @@ -1301,8 +1220,7 @@ static void BroadcasterInitNative(JNIEnv* env, jobject object) { } static void BroadcasterStopNative(JNIEnv* /* env */, jobject /* object */) { - std::unique_lock interface_lock( - sBroadcasterInterfaceMutex); + std::unique_lock interface_lock(sBroadcasterInterfaceMutex); const bt_interface_t* btInf = getBluetoothInterface(); if (btInf == nullptr) { @@ -1310,15 +1228,14 @@ static void BroadcasterStopNative(JNIEnv* /* env */, jobject /* object */) { return; } - if (sLeAudioBroadcasterInterface != nullptr) + if (sLeAudioBroadcasterInterface != nullptr) { sLeAudioBroadcasterInterface->Stop(); + } } static void BroadcasterCleanupNative(JNIEnv* env, jobject /* object */) { - std::unique_lock interface_lock( - sBroadcasterInterfaceMutex); - std::unique_lock callbacks_lock( - sBroadcasterCallbacksMutex); + std::unique_lock interface_lock(sBroadcasterInterfaceMutex); + std::unique_lock callbacks_lock(sBroadcasterCallbacksMutex); const bt_interface_t* btInf = getBluetoothInterface(); if (btInf == nullptr) { @@ -1332,8 +1249,7 @@ static void BroadcasterCleanupNative(JNIEnv* env, jobject /* object */) { env->DeleteGlobalRef(android_bluetooth_BluetoothDevice.clazz); android_bluetooth_BluetoothDevice.clazz = nullptr; - env->DeleteGlobalRef( - android_bluetooth_BluetoothLeAudioCodecConfigMetadata.clazz); + env->DeleteGlobalRef(android_bluetooth_BluetoothLeAudioCodecConfigMetadata.clazz); android_bluetooth_BluetoothLeAudioCodecConfigMetadata.clazz = nullptr; env->DeleteGlobalRef(android_bluetooth_BluetoothLeAudioContentMetadata.clazz); @@ -1359,8 +1275,7 @@ static void BroadcasterCleanupNative(JNIEnv* env, jobject /* object */) { } } -std::vector> convertToDataVectors(JNIEnv* env, - jobjectArray dataArray) { +std::vector> convertToDataVectors(JNIEnv* env, jobjectArray dataArray) { jsize arraySize = env->GetArrayLength(dataArray); std::vector> res(arraySize); @@ -1369,22 +1284,21 @@ std::vector> convertToDataVectors(JNIEnv* env, jsize dataSize = env->GetArrayLength(rowData); std::vector& rowVector = res[i]; rowVector.resize(dataSize); - env->GetByteArrayRegion(rowData, 0, dataSize, - reinterpret_cast(rowVector.data())); + env->GetByteArrayRegion(rowData, 0, dataSize, reinterpret_cast(rowVector.data())); env->DeleteLocalRef(rowData); } return res; } -static void CreateBroadcastNative(JNIEnv* env, jobject /* object */, - jboolean isPublic, jstring broadcastName, - jbyteArray broadcast_code, - jbyteArray publicMetadata, - jintArray qualityArray, +static void CreateBroadcastNative(JNIEnv* env, jobject /* object */, jboolean isPublic, + jstring broadcastName, jbyteArray broadcast_code, + jbyteArray publicMetadata, jintArray qualityArray, jobjectArray metadataArray) { log::info(""); std::shared_lock lock(sBroadcasterInterfaceMutex); - if (!sLeAudioBroadcasterInterface) return; + if (!sLeAudioBroadcasterInterface) { + return; + } std::array code_array{0}; if (broadcast_code) { @@ -1414,25 +1328,29 @@ static void CreateBroadcastNative(JNIEnv* env, jobject /* object */, } sLeAudioBroadcasterInterface->CreateBroadcast( - isPublic, broadcast_name ? broadcast_name : "", - broadcast_code ? std::optional>(code_array) - : std::nullopt, - public_meta ? std::vector( - public_meta, public_meta + env->GetArrayLength(publicMetadata)) - : std::vector(), - quality_array ? std::vector( - quality_array, quality_array + env->GetArrayLength(qualityArray)) - : std::vector(), - convertToDataVectors(env, metadataArray)); - - if (broadcast_name) env->ReleaseStringUTFChars(broadcastName, broadcast_name); - if (public_meta) env->ReleaseByteArrayElements(publicMetadata, public_meta, 0); - if (quality_array) env->ReleaseIntArrayElements(qualityArray, quality_array, 0); + isPublic, broadcast_name ? broadcast_name : "", + broadcast_code ? std::optional>(code_array) : std::nullopt, + public_meta ? std::vector(public_meta, + public_meta + env->GetArrayLength(publicMetadata)) + : std::vector(), + quality_array ? std::vector(quality_array, + quality_array + env->GetArrayLength(qualityArray)) + : std::vector(), + convertToDataVectors(env, metadataArray)); + + if (broadcast_name) { + env->ReleaseStringUTFChars(broadcastName, broadcast_name); + } + if (public_meta) { + env->ReleaseByteArrayElements(publicMetadata, public_meta, 0); + } + if (quality_array) { + env->ReleaseIntArrayElements(qualityArray, quality_array, 0); + } } -static void UpdateMetadataNative(JNIEnv* env, jobject /* object */, - jint broadcast_id, jstring broadcastName, - jbyteArray publicMetadata, +static void UpdateMetadataNative(JNIEnv* env, jobject /* object */, jint broadcast_id, + jstring broadcastName, jbyteArray publicMetadata, jobjectArray metadataArray) { const char* broadcast_name = nullptr; if (broadcastName) { @@ -1445,142 +1363,144 @@ static void UpdateMetadataNative(JNIEnv* env, jobject /* object */, } sLeAudioBroadcasterInterface->UpdateMetadata( - broadcast_id, broadcast_name ? broadcast_name : "", - public_meta - ? std::vector( - public_meta, public_meta + env->GetArrayLength(publicMetadata)) - : std::vector(), - convertToDataVectors(env, metadataArray)); - - if (broadcast_name) env->ReleaseStringUTFChars(broadcastName, broadcast_name); - if (public_meta) env->ReleaseByteArrayElements(publicMetadata, public_meta, 0); + broadcast_id, broadcast_name ? broadcast_name : "", + public_meta ? std::vector(public_meta, + public_meta + env->GetArrayLength(publicMetadata)) + : std::vector(), + convertToDataVectors(env, metadataArray)); + + if (broadcast_name) { + env->ReleaseStringUTFChars(broadcastName, broadcast_name); + } + if (public_meta) { + env->ReleaseByteArrayElements(publicMetadata, public_meta, 0); + } } -static void StartBroadcastNative(JNIEnv* /* env */, jobject /* object */, - jint broadcast_id) { +static void StartBroadcastNative(JNIEnv* /* env */, jobject /* object */, jint broadcast_id) { log::info(""); std::shared_lock lock(sBroadcasterInterfaceMutex); - if (!sLeAudioBroadcasterInterface) return; + if (!sLeAudioBroadcasterInterface) { + return; + } sLeAudioBroadcasterInterface->StartBroadcast(broadcast_id); } -static void StopBroadcastNative(JNIEnv* /* env */, jobject /* object */, - jint broadcast_id) { +static void StopBroadcastNative(JNIEnv* /* env */, jobject /* object */, jint broadcast_id) { log::info(""); std::shared_lock lock(sBroadcasterInterfaceMutex); - if (!sLeAudioBroadcasterInterface) return; + if (!sLeAudioBroadcasterInterface) { + return; + } sLeAudioBroadcasterInterface->StopBroadcast(broadcast_id); } -static void PauseBroadcastNative(JNIEnv* /* env */, jobject /* object */, - jint broadcast_id) { +static void PauseBroadcastNative(JNIEnv* /* env */, jobject /* object */, jint broadcast_id) { log::info(""); std::shared_lock lock(sBroadcasterInterfaceMutex); - if (!sLeAudioBroadcasterInterface) return; + if (!sLeAudioBroadcasterInterface) { + return; + } sLeAudioBroadcasterInterface->PauseBroadcast(broadcast_id); } -static void DestroyBroadcastNative(JNIEnv* /* env */, jobject /* object */, - jint broadcast_id) { +static void DestroyBroadcastNative(JNIEnv* /* env */, jobject /* object */, jint broadcast_id) { log::info(""); std::shared_lock lock(sBroadcasterInterfaceMutex); - if (!sLeAudioBroadcasterInterface) return; + if (!sLeAudioBroadcasterInterface) { + return; + } sLeAudioBroadcasterInterface->DestroyBroadcast(broadcast_id); } -static void getBroadcastMetadataNative(JNIEnv* /* env */, jobject /* object */, - jint broadcast_id) { +static void getBroadcastMetadataNative(JNIEnv* /* env */, jobject /* object */, jint broadcast_id) { log::info(""); std::shared_lock lock(sBroadcasterInterfaceMutex); - if (!sLeAudioBroadcasterInterface) return; + if (!sLeAudioBroadcasterInterface) { + return; + } sLeAudioBroadcasterInterface->GetBroadcastMetadata(broadcast_id); } static int register_com_android_bluetooth_le_audio_broadcaster(JNIEnv* env) { const JNINativeMethod methods[] = { - {"initNative", "()V", (void*)BroadcasterInitNative}, - {"stopNative", "()V", (void*)BroadcasterStopNative}, - {"cleanupNative", "()V", (void*)BroadcasterCleanupNative}, - {"createBroadcastNative", "(ZLjava/lang/String;[B[B[I[[B)V", - (void*)CreateBroadcastNative}, - {"updateMetadataNative", "(ILjava/lang/String;[B[[B)V", - (void*)UpdateMetadataNative}, - {"startBroadcastNative", "(I)V", (void*)StartBroadcastNative}, - {"stopBroadcastNative", "(I)V", (void*)StopBroadcastNative}, - {"pauseBroadcastNative", "(I)V", (void*)PauseBroadcastNative}, - {"destroyBroadcastNative", "(I)V", (void*)DestroyBroadcastNative}, - {"getBroadcastMetadataNative", "(I)V", (void*)getBroadcastMetadataNative}, + {"initNative", "()V", (void*)BroadcasterInitNative}, + {"stopNative", "()V", (void*)BroadcasterStopNative}, + {"cleanupNative", "()V", (void*)BroadcasterCleanupNative}, + {"createBroadcastNative", "(ZLjava/lang/String;[B[B[I[[B)V", + (void*)CreateBroadcastNative}, + {"updateMetadataNative", "(ILjava/lang/String;[B[[B)V", (void*)UpdateMetadataNative}, + {"startBroadcastNative", "(I)V", (void*)StartBroadcastNative}, + {"stopBroadcastNative", "(I)V", (void*)StopBroadcastNative}, + {"pauseBroadcastNative", "(I)V", (void*)PauseBroadcastNative}, + {"destroyBroadcastNative", "(I)V", (void*)DestroyBroadcastNative}, + {"getBroadcastMetadataNative", "(I)V", (void*)getBroadcastMetadataNative}, }; const int result = REGISTER_NATIVE_METHODS( - env, "com/android/bluetooth/le_audio/LeAudioBroadcasterNativeInterface", - methods); + env, "com/android/bluetooth/le_audio/LeAudioBroadcasterNativeInterface", methods); if (result != 0) { return result; } const JNIJavaMethod javaMethods[] = { - {"onBroadcastCreated", "(IZ)V", &method_onBroadcastCreated}, - {"onBroadcastDestroyed", "(I)V", &method_onBroadcastDestroyed}, - {"onBroadcastStateChanged", "(II)V", &method_onBroadcastStateChanged}, - {"onBroadcastMetadataChanged", - "(ILandroid/bluetooth/BluetoothLeBroadcastMetadata;)V", - &method_onBroadcastMetadataChanged}, + {"onBroadcastCreated", "(IZ)V", &method_onBroadcastCreated}, + {"onBroadcastDestroyed", "(I)V", &method_onBroadcastDestroyed}, + {"onBroadcastStateChanged", "(II)V", &method_onBroadcastStateChanged}, + {"onBroadcastMetadataChanged", "(ILandroid/bluetooth/BluetoothLeBroadcastMetadata;)V", + &method_onBroadcastMetadataChanged}, }; - GET_JAVA_METHODS( - env, "com/android/bluetooth/le_audio/LeAudioBroadcasterNativeInterface", - javaMethods); + GET_JAVA_METHODS(env, "com/android/bluetooth/le_audio/LeAudioBroadcasterNativeInterface", + javaMethods); const JNIJavaMethod javaArrayListMethods[] = { - {"", "()V", &java_util_ArrayList.constructor}, - {"add", "(Ljava/lang/Object;)Z", &java_util_ArrayList.add}, + {"", "()V", &java_util_ArrayList.constructor}, + {"add", "(Ljava/lang/Object;)Z", &java_util_ArrayList.add}, }; GET_JAVA_METHODS(env, "java/util/ArrayList", javaArrayListMethods); const JNIJavaMethod javaLeAudioCodecMethods[] = { - {"", "(JIII[B)V", - &android_bluetooth_BluetoothLeAudioCodecConfigMetadata.constructor}, + {"", "(JIII[B)V", + &android_bluetooth_BluetoothLeAudioCodecConfigMetadata.constructor}, }; GET_JAVA_METHODS(env, "android/bluetooth/BluetoothLeAudioCodecConfigMetadata", javaLeAudioCodecMethods); const JNIJavaMethod javaLeAudioContentMethods[] = { - {"", "(Ljava/lang/String;Ljava/lang/String;[B)V", - &android_bluetooth_BluetoothLeAudioContentMetadata.constructor}, + {"", "(Ljava/lang/String;Ljava/lang/String;[B)V", + &android_bluetooth_BluetoothLeAudioContentMetadata.constructor}, }; GET_JAVA_METHODS(env, "android/bluetooth/BluetoothLeAudioContentMetadata", javaLeAudioContentMethods); const JNIJavaMethod javaLeBroadcastChannelMethods[] = { - {"", "(ZILandroid/bluetooth/BluetoothLeAudioCodecConfigMetadata;)V", - &android_bluetooth_BluetoothLeBroadcastChannel.constructor}, + {"", "(ZILandroid/bluetooth/BluetoothLeAudioCodecConfigMetadata;)V", + &android_bluetooth_BluetoothLeBroadcastChannel.constructor}, }; GET_JAVA_METHODS(env, "android/bluetooth/BluetoothLeBroadcastChannel", javaLeBroadcastChannelMethods); const JNIJavaMethod javaLeBroadcastSubgroupMethods[] = { - {"", - "(JLandroid/bluetooth/BluetoothLeAudioCodecConfigMetadata;" - "Landroid/bluetooth/BluetoothLeAudioContentMetadata;" - "Ljava/util/List;)V", - &android_bluetooth_BluetoothLeBroadcastSubgroup.constructor}, + {"", + "(JLandroid/bluetooth/BluetoothLeAudioCodecConfigMetadata;" + "Landroid/bluetooth/BluetoothLeAudioContentMetadata;" + "Ljava/util/List;)V", + &android_bluetooth_BluetoothLeBroadcastSubgroup.constructor}, }; GET_JAVA_METHODS(env, "android/bluetooth/BluetoothLeBroadcastSubgroup", javaLeBroadcastSubgroupMethods); const JNIJavaMethod javaBluetoothDevieceMethods[] = { - {"", "(Ljava/lang/String;I)V", - &android_bluetooth_BluetoothDevice.constructor}, + {"", "(Ljava/lang/String;I)V", &android_bluetooth_BluetoothDevice.constructor}, }; - GET_JAVA_METHODS(env, "android/bluetooth/BluetoothDevice", - javaBluetoothDevieceMethods); + GET_JAVA_METHODS(env, "android/bluetooth/BluetoothDevice", javaBluetoothDevieceMethods); const JNIJavaMethod javaLeBroadcastMetadataMethods[] = { - {"", - "(ILandroid/bluetooth/BluetoothDevice;IIIZZLjava/lang/String;" - "[BIIILandroid/bluetooth/BluetoothLeAudioContentMetadata;" - "Ljava/util/List;)V", - &android_bluetooth_BluetoothLeBroadcastMetadata.constructor}, + {"", + "(ILandroid/bluetooth/BluetoothDevice;IIIZZLjava/lang/String;" + "[BIIILandroid/bluetooth/BluetoothLeAudioContentMetadata;" + "Ljava/util/List;)V", + &android_bluetooth_BluetoothLeBroadcastMetadata.constructor}, }; GET_JAVA_METHODS(env, "android/bluetooth/BluetoothLeBroadcastMetadata", javaLeBroadcastMetadataMethods); @@ -1590,86 +1510,75 @@ static int register_com_android_bluetooth_le_audio_broadcaster(JNIEnv* env) { int register_com_android_bluetooth_le_audio(JNIEnv* env) { const JNINativeMethod methods[] = { - {"initNative", "([Landroid/bluetooth/BluetoothLeAudioCodecConfig;)V", - (void*)initNative}, - {"cleanupNative", "()V", (void*)cleanupNative}, - {"connectLeAudioNative", "([B)Z", (void*)connectLeAudioNative}, - {"disconnectLeAudioNative", "([B)Z", (void*)disconnectLeAudioNative}, - {"setEnableStateNative", "([BZ)Z", (void*)setEnableStateNative}, - {"groupAddNodeNative", "(I[B)Z", (void*)groupAddNodeNative}, - {"groupRemoveNodeNative", "(I[B)Z", (void*)groupRemoveNodeNative}, - {"groupSetActiveNative", "(I)V", (void*)groupSetActiveNative}, - {"setCodecConfigPreferenceNative", - "(ILandroid/bluetooth/BluetoothLeAudioCodecConfig;" - "Landroid/bluetooth/BluetoothLeAudioCodecConfig;)V", - (void*)setCodecConfigPreferenceNative}, - {"setCcidInformationNative", "(II)V", (void*)setCcidInformationNative}, - {"setInCallNative", "(Z)V", (void*)setInCallNative}, - {"setUnicastMonitorModeNative", "(IZ)V", - (void*)setUnicastMonitorModeNative}, - {"sendAudioProfilePreferencesNative", "(IZZ)V", - (void*)sendAudioProfilePreferencesNative}, - {"setGroupAllowedContextMaskNative", "(III)V", - (void*)setGroupAllowedContextMaskNative}, + {"initNative", "([Landroid/bluetooth/BluetoothLeAudioCodecConfig;)V", (void*)initNative}, + {"cleanupNative", "()V", (void*)cleanupNative}, + {"connectLeAudioNative", "([B)Z", (void*)connectLeAudioNative}, + {"disconnectLeAudioNative", "([B)Z", (void*)disconnectLeAudioNative}, + {"setEnableStateNative", "([BZ)Z", (void*)setEnableStateNative}, + {"groupAddNodeNative", "(I[B)Z", (void*)groupAddNodeNative}, + {"groupRemoveNodeNative", "(I[B)Z", (void*)groupRemoveNodeNative}, + {"groupSetActiveNative", "(I)V", (void*)groupSetActiveNative}, + {"setCodecConfigPreferenceNative", + "(ILandroid/bluetooth/BluetoothLeAudioCodecConfig;" + "Landroid/bluetooth/BluetoothLeAudioCodecConfig;)V", + (void*)setCodecConfigPreferenceNative}, + {"setCcidInformationNative", "(II)V", (void*)setCcidInformationNative}, + {"setInCallNative", "(Z)V", (void*)setInCallNative}, + {"setUnicastMonitorModeNative", "(IZ)V", (void*)setUnicastMonitorModeNative}, + {"sendAudioProfilePreferencesNative", "(IZZ)V", (void*)sendAudioProfilePreferencesNative}, + {"setGroupAllowedContextMaskNative", "(III)V", (void*)setGroupAllowedContextMaskNative}, }; const int result = REGISTER_NATIVE_METHODS( - env, "com/android/bluetooth/le_audio/LeAudioNativeInterface", methods); + env, "com/android/bluetooth/le_audio/LeAudioNativeInterface", methods); if (result != 0) { return result; } const JNIJavaMethod javaMethods[] = { - {"onGroupStatus", "(II)V", &method_onGroupStatus}, - {"onGroupNodeStatus", "([BII)V", &method_onGroupNodeStatus}, - {"onAudioConf", "(IIIII)V", &method_onAudioConf}, - {"onSinkAudioLocationAvailable", "([BI)V", - &method_onSinkAudioLocationAvailable}, - {"onInitialized", "()V", &method_onInitialized}, - {"onConnectionStateChanged", "(I[B)V", &method_onConnectionStateChanged}, - {"onAudioLocalCodecCapabilities", - "([Landroid/bluetooth/BluetoothLeAudioCodecConfig;" - "[Landroid/bluetooth/BluetoothLeAudioCodecConfig;)V", - &method_onAudioLocalCodecCapabilities}, - {"onAudioGroupCurrentCodecConf", - "(ILandroid/bluetooth/BluetoothLeAudioCodecConfig;" - "Landroid/bluetooth/BluetoothLeAudioCodecConfig;)V", - &method_onAudioGroupCurrentCodecConf}, - {"onAudioGroupSelectableCodecConf", - "(I[Landroid/bluetooth/BluetoothLeAudioCodecConfig;" - "[Landroid/bluetooth/BluetoothLeAudioCodecConfig;)V", - &method_onAudioGroupSelectableCodecConf}, - {"onHealthBasedRecommendationAction", "([BI)V", - &method_onHealthBasedRecommendationAction}, - {"onHealthBasedGroupRecommendationAction", "(II)V", - &method_onHealthBasedGroupRecommendationAction}, - {"onUnicastMonitorModeStatus", "(II)V", - &method_onUnicastMonitorModeStatus}, - {"onGroupStreamStatus", "(II)V", &method_onGroupStreamStatus}, + {"onGroupStatus", "(II)V", &method_onGroupStatus}, + {"onGroupNodeStatus", "([BII)V", &method_onGroupNodeStatus}, + {"onAudioConf", "(IIIII)V", &method_onAudioConf}, + {"onSinkAudioLocationAvailable", "([BI)V", &method_onSinkAudioLocationAvailable}, + {"onInitialized", "()V", &method_onInitialized}, + {"onConnectionStateChanged", "(I[B)V", &method_onConnectionStateChanged}, + {"onAudioLocalCodecCapabilities", + "([Landroid/bluetooth/BluetoothLeAudioCodecConfig;" + "[Landroid/bluetooth/BluetoothLeAudioCodecConfig;)V", + &method_onAudioLocalCodecCapabilities}, + {"onAudioGroupCurrentCodecConf", + "(ILandroid/bluetooth/BluetoothLeAudioCodecConfig;" + "Landroid/bluetooth/BluetoothLeAudioCodecConfig;)V", + &method_onAudioGroupCurrentCodecConf}, + {"onAudioGroupSelectableCodecConf", + "(I[Landroid/bluetooth/BluetoothLeAudioCodecConfig;" + "[Landroid/bluetooth/BluetoothLeAudioCodecConfig;)V", + &method_onAudioGroupSelectableCodecConf}, + {"onHealthBasedRecommendationAction", "([BI)V", + &method_onHealthBasedRecommendationAction}, + {"onHealthBasedGroupRecommendationAction", "(II)V", + &method_onHealthBasedGroupRecommendationAction}, + {"onUnicastMonitorModeStatus", "(II)V", &method_onUnicastMonitorModeStatus}, + {"onGroupStreamStatus", "(II)V", &method_onGroupStreamStatus}, }; - GET_JAVA_METHODS(env, "com/android/bluetooth/le_audio/LeAudioNativeInterface", - javaMethods); + GET_JAVA_METHODS(env, "com/android/bluetooth/le_audio/LeAudioNativeInterface", javaMethods); const JNIJavaMethod javaLeAudioCodecMethods[] = { - {"", "(IIIIIIIII)V", - &android_bluetooth_BluetoothLeAudioCodecConfig.constructor}, - {"getCodecType", "()I", - &android_bluetooth_BluetoothLeAudioCodecConfig.getCodecType}, - {"getSampleRate", "()I", - &android_bluetooth_BluetoothLeAudioCodecConfig.getSampleRate}, - {"getBitsPerSample", "()I", - &android_bluetooth_BluetoothLeAudioCodecConfig.getBitsPerSample}, - {"getChannelCount", "()I", - &android_bluetooth_BluetoothLeAudioCodecConfig.getChannelCount}, - {"getFrameDuration", "()I", - &android_bluetooth_BluetoothLeAudioCodecConfig.getFrameDuration}, - {"getOctetsPerFrame", "()I", - &android_bluetooth_BluetoothLeAudioCodecConfig.getOctetsPerFrame}, - {"getCodecPriority", "()I", - &android_bluetooth_BluetoothLeAudioCodecConfig.getCodecPriority}, + {"", "(IIIIIIIII)V", &android_bluetooth_BluetoothLeAudioCodecConfig.constructor}, + {"getCodecType", "()I", &android_bluetooth_BluetoothLeAudioCodecConfig.getCodecType}, + {"getSampleRate", "()I", &android_bluetooth_BluetoothLeAudioCodecConfig.getSampleRate}, + {"getBitsPerSample", "()I", + &android_bluetooth_BluetoothLeAudioCodecConfig.getBitsPerSample}, + {"getChannelCount", "()I", + &android_bluetooth_BluetoothLeAudioCodecConfig.getChannelCount}, + {"getFrameDuration", "()I", + &android_bluetooth_BluetoothLeAudioCodecConfig.getFrameDuration}, + {"getOctetsPerFrame", "()I", + &android_bluetooth_BluetoothLeAudioCodecConfig.getOctetsPerFrame}, + {"getCodecPriority", "()I", + &android_bluetooth_BluetoothLeAudioCodecConfig.getCodecPriority}, }; - GET_JAVA_METHODS(env, "android/bluetooth/BluetoothLeAudioCodecConfig", - javaLeAudioCodecMethods); + GET_JAVA_METHODS(env, "android/bluetooth/BluetoothLeAudioCodecConfig", javaLeAudioCodecMethods); return register_com_android_bluetooth_le_audio_broadcaster(env); } diff --git a/android/app/jni/com_android_bluetooth_pan.cpp b/android/app/jni/com_android_bluetooth_pan.cpp index 28cb632948a..195b8fefc26 100644 --- a/android/app/jni/com_android_bluetooth_pan.cpp +++ b/android/app/jni/com_android_bluetooth_pan.cpp @@ -31,66 +31,66 @@ static jobject mCallbacksObj = NULL; static jbyteArray marshall_bda(const RawAddress* bd_addr) { CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid()) return NULL; + if (!sCallbackEnv.valid()) { + return NULL; + } jbyteArray addr = sCallbackEnv->NewByteArray(sizeof(RawAddress)); if (!addr) { log::error("Fail to new jbyteArray bd addr"); return NULL; } - sCallbackEnv->SetByteArrayRegion(addr, 0, sizeof(RawAddress), - (jbyte*)bd_addr); + sCallbackEnv->SetByteArrayRegion(addr, 0, sizeof(RawAddress), (jbyte*)bd_addr); return addr; } -static void control_state_callback(btpan_control_state_t state, int local_role, - bt_status_t error, const char* ifname) { +static void control_state_callback(btpan_control_state_t state, int local_role, bt_status_t error, + const char* ifname) { log::debug("state:{}, local_role:{}, ifname:{}", state, local_role, ifname); if (mCallbacksObj == NULL) { log::error("Callbacks Obj is NULL"); return; } CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid()) return; - ScopedLocalRef js_ifname(sCallbackEnv.get(), - sCallbackEnv->NewStringUTF(ifname)); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onControlStateChanged, - (jint)local_role, (jint)state, (jint)error, - js_ifname.get()); + if (!sCallbackEnv.valid()) { + return; + } + ScopedLocalRef js_ifname(sCallbackEnv.get(), sCallbackEnv->NewStringUTF(ifname)); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onControlStateChanged, (jint)local_role, + (jint)state, (jint)error, js_ifname.get()); } -static void connection_state_callback(btpan_connection_state_t state, - bt_status_t error, - const RawAddress* bd_addr, int local_role, - int remote_role) { - log::debug("state:{}, local_role:{}, remote_role:{}", state, local_role, - remote_role); +static void connection_state_callback(btpan_connection_state_t state, bt_status_t error, + const RawAddress* bd_addr, int local_role, int remote_role) { + log::debug("state:{}, local_role:{}, remote_role:{}", state, local_role, remote_role); if (mCallbacksObj == NULL) { log::error("Callbacks Obj is NULL"); return; } CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid()) return; + if (!sCallbackEnv.valid()) { + return; + } ScopedLocalRef addr(sCallbackEnv.get(), marshall_bda(bd_addr)); if (!addr.get()) { log::error("Fail to new jbyteArray bd addr for PAN channel state"); return; } - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onConnectStateChanged, - addr.get(), (jint)state, (jint)error, - (jint)local_role, (jint)remote_role); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onConnectStateChanged, addr.get(), (jint)state, + (jint)error, (jint)local_role, (jint)remote_role); } static btpan_callbacks_t sBluetoothPanCallbacks = { - sizeof(sBluetoothPanCallbacks), control_state_callback, - connection_state_callback}; + sizeof(sBluetoothPanCallbacks), control_state_callback, connection_state_callback}; // Define native functions static const bt_interface_t* btIf; static void initializeNative(JNIEnv* env, jobject object) { log::debug("Initialize pan"); - if (btIf) return; + if (btIf) { + return; + } btIf = getBluetoothInterface(); if (btIf == NULL) { @@ -120,12 +120,10 @@ static void initializeNative(JNIEnv* env, jobject object) { bt_status_t status = sPanIf->init(&sBluetoothPanCallbacks); if (status != BT_STATUS_SUCCESS) { - log::error("Failed to initialize Bluetooth PAN, status: {}", - bt_status_text(status)); + log::error("Failed to initialize Bluetooth PAN, status: {}", bt_status_text(status)); sPanIf = NULL; if (mCallbacksObj != NULL) { - log::warn( - "initialization failed: Cleaning up Bluetooth PAN callback object"); + log::warn("initialization failed: Cleaning up Bluetooth PAN callback object"); env->DeleteGlobalRef(mCallbacksObj); mCallbacksObj = NULL; } @@ -135,7 +133,9 @@ static void initializeNative(JNIEnv* env, jobject object) { static void cleanupNative(JNIEnv* env, jobject /* object */) { log::debug("Cleanup pan"); - if (!btIf) return; + if (!btIf) { + return; + } if (sPanIf != NULL) { log::warn("Cleaning up Bluetooth PAN Interface..."); @@ -151,11 +151,12 @@ static void cleanupNative(JNIEnv* env, jobject /* object */) { btIf = NULL; } -static jboolean connectPanNative(JNIEnv* env, jobject /* object */, - jbyteArray address, jint src_role, - jint dest_role) { +static jboolean connectPanNative(JNIEnv* env, jobject /* object */, jbyteArray address, + jint src_role, jint dest_role) { log::debug("Connect pan"); - if (!sPanIf) return JNI_FALSE; + if (!sPanIf) { + return JNI_FALSE; + } jbyte* addr = env->GetByteArrayElements(address, NULL); if (!addr) { @@ -166,8 +167,7 @@ static jboolean connectPanNative(JNIEnv* env, jobject /* object */, jboolean ret = JNI_TRUE; bt_status_t status = sPanIf->connect((RawAddress*)addr, src_role, dest_role); if (status != BT_STATUS_SUCCESS) { - log::error("Failed PAN channel connection, status: {}", - bt_status_text(status)); + log::error("Failed PAN channel connection, status: {}", bt_status_text(status)); ret = JNI_FALSE; } env->ReleaseByteArrayElements(address, addr, 0); @@ -175,10 +175,11 @@ static jboolean connectPanNative(JNIEnv* env, jobject /* object */, return ret; } -static jboolean disconnectPanNative(JNIEnv* env, jobject /* object */, - jbyteArray address) { +static jboolean disconnectPanNative(JNIEnv* env, jobject /* object */, jbyteArray address) { log::debug("Disconnects pan"); - if (!sPanIf) return JNI_FALSE; + if (!sPanIf) { + return JNI_FALSE; + } jbyte* addr = env->GetByteArrayElements(address, NULL); if (!addr) { @@ -189,8 +190,7 @@ static jboolean disconnectPanNative(JNIEnv* env, jobject /* object */, jboolean ret = JNI_TRUE; bt_status_t status = sPanIf->disconnect((RawAddress*)addr); if (status != BT_STATUS_SUCCESS) { - log::error("Failed disconnect pan channel, status: {}", - bt_status_text(status)); + log::error("Failed disconnect pan channel, status: {}", bt_status_text(status)); ret = JNI_FALSE; } env->ReleaseByteArrayElements(address, addr, 0); @@ -200,25 +200,23 @@ static jboolean disconnectPanNative(JNIEnv* env, jobject /* object */, int register_com_android_bluetooth_pan(JNIEnv* env) { const JNINativeMethod methods[] = { - {"initializeNative", "()V", (void*)initializeNative}, - {"cleanupNative", "()V", (void*)cleanupNative}, - {"connectPanNative", "([BII)Z", (void*)connectPanNative}, - {"disconnectPanNative", "([B)Z", (void*)disconnectPanNative}, + {"initializeNative", "()V", (void*)initializeNative}, + {"cleanupNative", "()V", (void*)cleanupNative}, + {"connectPanNative", "([BII)Z", (void*)connectPanNative}, + {"disconnectPanNative", "([B)Z", (void*)disconnectPanNative}, }; - const int result = REGISTER_NATIVE_METHODS( - env, "com/android/bluetooth/pan/PanNativeInterface", methods); + const int result = + REGISTER_NATIVE_METHODS(env, "com/android/bluetooth/pan/PanNativeInterface", methods); if (result != 0) { return result; } const JNIJavaMethod javaMethods[]{ - {"onConnectStateChanged", "([BIIII)V", &method_onConnectStateChanged}, - {"onControlStateChanged", "(IIILjava/lang/String;)V", - &method_onControlStateChanged}, + {"onConnectStateChanged", "([BIIII)V", &method_onConnectStateChanged}, + {"onControlStateChanged", "(IIILjava/lang/String;)V", &method_onControlStateChanged}, }; - GET_JAVA_METHODS(env, "com/android/bluetooth/pan/PanNativeInterface", - javaMethods); + GET_JAVA_METHODS(env, "com/android/bluetooth/pan/PanNativeInterface", javaMethods); return 0; } -} +} // namespace android diff --git a/android/app/jni/com_android_bluetooth_sdp.cpp b/android/app/jni/com_android_bluetooth_sdp.cpp index 8b173e55278..1d49fca11a1 100644 --- a/android/app/jni/com_android_bluetooth_sdp.cpp +++ b/android/app/jni/com_android_bluetooth_sdp.cpp @@ -41,12 +41,10 @@ static jmethodID method_sdpDipRecordFoundCallback; static const btsdp_interface_t* sBluetoothSdpInterface = NULL; -static void sdp_search_callback(bt_status_t status, const RawAddress& bd_addr, - const Uuid& uuid_in, int record_size, - bluetooth_sdp_record* record); +static void sdp_search_callback(bt_status_t status, const RawAddress& bd_addr, const Uuid& uuid_in, + int record_size, bluetooth_sdp_record* record); -btsdp_callbacks_t sBluetoothSdpCallbacks = {sizeof(sBluetoothSdpCallbacks), - sdp_search_callback}; +btsdp_callbacks_t sBluetoothSdpCallbacks = {sizeof(sBluetoothSdpCallbacks), sdp_search_callback}; static jobject sCallbacksObj = NULL; @@ -63,8 +61,8 @@ static void initializeNative(JNIEnv* env, jobject object) { sBluetoothSdpInterface = NULL; } - sBluetoothSdpInterface = (btsdp_interface_t*)btInf->get_profile_interface( - BT_PROFILE_SDP_CLIENT_ID); + sBluetoothSdpInterface = + (btsdp_interface_t*)btInf->get_profile_interface(BT_PROFILE_SDP_CLIENT_ID); if (sBluetoothSdpInterface == NULL) { log::error("Error getting SDP client interface"); } else { @@ -74,11 +72,13 @@ static void initializeNative(JNIEnv* env, jobject object) { sCallbacksObj = env->NewGlobalRef(object); } -static jboolean sdpSearchNative(JNIEnv* env, jobject /* obj */, - jbyteArray address, jbyteArray uuidObj) { +static jboolean sdpSearchNative(JNIEnv* env, jobject /* obj */, jbyteArray address, + jbyteArray uuidObj) { log::debug(""); - if (!sBluetoothSdpInterface) return JNI_FALSE; + if (!sBluetoothSdpInterface) { + return JNI_FALSE; + } jbyte* addr = env->GetByteArrayElements(address, NULL); if (addr == NULL) { @@ -100,27 +100,34 @@ static jboolean sdpSearchNative(JNIEnv* env, jobject /* obj */, log::error("SDP Search initialization failed: {}", ret); } - if (addr) env->ReleaseByteArrayElements(address, addr, 0); - if (raw_uuid) env->ReleaseByteArrayElements(uuidObj, raw_uuid, 0); + if (addr) { + env->ReleaseByteArrayElements(address, addr, 0); + } + if (raw_uuid) { + env->ReleaseByteArrayElements(uuidObj, raw_uuid, 0); + } return (ret == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE; } -static void sdp_search_callback(bt_status_t status, const RawAddress& bd_addr, - const Uuid& uuid_in, int count, - bluetooth_sdp_record* records) { +static void sdp_search_callback(bt_status_t status, const RawAddress& bd_addr, const Uuid& uuid_in, + int count, bluetooth_sdp_record* records) { CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid()) return; + if (!sCallbackEnv.valid()) { + return; + } - ScopedLocalRef addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); - if (!addr.get()) return; + ScopedLocalRef addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); + if (!addr.get()) { + return; + } - ScopedLocalRef uuid(sCallbackEnv.get(), - sCallbackEnv->NewByteArray(sizeof(Uuid))); - if (!uuid.get()) return; + ScopedLocalRef uuid(sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(Uuid))); + if (!uuid.get()) { + return; + } - sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), - (const jbyte*)&bd_addr); + sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), (const jbyte*)&bd_addr); sCallbackEnv->SetByteArrayRegion(uuid.get(), 0, sizeof(Uuid), (const jbyte*)uuid_in.To128BitBE().data()); @@ -133,96 +140,84 @@ static void sdp_search_callback(bt_status_t status, const RawAddress& bd_addr, ScopedLocalRef service_name(sCallbackEnv.get(), NULL); if (record->hdr.service_name_length > 0) { log::debug("ServiceName: {}", record->mas.hdr.service_name); - service_name.reset( - (jstring)sCallbackEnv->NewStringUTF(record->mas.hdr.service_name)); + service_name.reset((jstring)sCallbackEnv->NewStringUTF(record->mas.hdr.service_name)); } /* call the right callback according to the uuid*/ if (uuid_in == UUID_MAP_MAS) { sCallbackEnv->CallVoidMethod( - sCallbacksObj, method_sdpMasRecordFoundCallback, (jint)status, - addr.get(), uuid.get(), (jint)record->mas.mas_instance_id, - (jint)record->mas.hdr.l2cap_psm, - (jint)record->mas.hdr.rfcomm_channel_number, - (jint)record->mas.hdr.profile_version, - (jint)record->mas.supported_features, - (jint)record->mas.supported_message_types, service_name.get(), - more_results); + sCallbacksObj, method_sdpMasRecordFoundCallback, (jint)status, addr.get(), uuid.get(), + (jint)record->mas.mas_instance_id, (jint)record->mas.hdr.l2cap_psm, + (jint)record->mas.hdr.rfcomm_channel_number, (jint)record->mas.hdr.profile_version, + (jint)record->mas.supported_features, (jint)record->mas.supported_message_types, + service_name.get(), more_results); } else if (uuid_in == UUID_MAP_MNS) { sCallbackEnv->CallVoidMethod( - sCallbacksObj, method_sdpMnsRecordFoundCallback, (jint)status, - addr.get(), uuid.get(), (jint)record->mns.hdr.l2cap_psm, - (jint)record->mns.hdr.rfcomm_channel_number, - (jint)record->mns.hdr.profile_version, - (jint)record->mns.supported_features, service_name.get(), - more_results); + sCallbacksObj, method_sdpMnsRecordFoundCallback, (jint)status, addr.get(), uuid.get(), + (jint)record->mns.hdr.l2cap_psm, (jint)record->mns.hdr.rfcomm_channel_number, + (jint)record->mns.hdr.profile_version, (jint)record->mns.supported_features, + service_name.get(), more_results); } else if (uuid_in == UUID_PBAP_PSE) { sCallbackEnv->CallVoidMethod( - sCallbacksObj, method_sdpPseRecordFoundCallback, (jint)status, - addr.get(), uuid.get(), (jint)record->pse.hdr.l2cap_psm, - (jint)record->pse.hdr.rfcomm_channel_number, - (jint)record->pse.hdr.profile_version, - (jint)record->pse.supported_features, - (jint)record->pse.supported_repositories, service_name.get(), - more_results); + sCallbacksObj, method_sdpPseRecordFoundCallback, (jint)status, addr.get(), uuid.get(), + (jint)record->pse.hdr.l2cap_psm, (jint)record->pse.hdr.rfcomm_channel_number, + (jint)record->pse.hdr.profile_version, (jint)record->pse.supported_features, + (jint)record->pse.supported_repositories, service_name.get(), more_results); } else if (uuid_in == UUID_OBEX_OBJECT_PUSH) { jint formats_list_size = record->ops.supported_formats_list_len; - ScopedLocalRef formats_list( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(formats_list_size)); - if (!formats_list.get()) return; - sCallbackEnv->SetByteArrayRegion( - formats_list.get(), 0, formats_list_size, - (jbyte*)record->ops.supported_formats_list); - - sCallbackEnv->CallVoidMethod( - sCallbacksObj, method_sdpOppOpsRecordFoundCallback, (jint)status, - addr.get(), uuid.get(), (jint)record->ops.hdr.l2cap_psm, - (jint)record->ops.hdr.rfcomm_channel_number, - (jint)record->ops.hdr.profile_version, service_name.get(), - formats_list.get(), more_results); + ScopedLocalRef formats_list(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(formats_list_size)); + if (!formats_list.get()) { + return; + } + sCallbackEnv->SetByteArrayRegion(formats_list.get(), 0, formats_list_size, + (jbyte*)record->ops.supported_formats_list); + + sCallbackEnv->CallVoidMethod(sCallbacksObj, method_sdpOppOpsRecordFoundCallback, (jint)status, + addr.get(), uuid.get(), (jint)record->ops.hdr.l2cap_psm, + (jint)record->ops.hdr.rfcomm_channel_number, + (jint)record->ops.hdr.profile_version, service_name.get(), + formats_list.get(), more_results); } else if (uuid_in == UUID_SAP) { sCallbackEnv->CallVoidMethod( - sCallbacksObj, method_sdpSapsRecordFoundCallback, (jint)status, - addr.get(), uuid.get(), (jint)record->mas.hdr.rfcomm_channel_number, - (jint)record->mas.hdr.profile_version, service_name.get(), - more_results); + sCallbacksObj, method_sdpSapsRecordFoundCallback, (jint)status, addr.get(), + uuid.get(), (jint)record->mas.hdr.rfcomm_channel_number, + (jint)record->mas.hdr.profile_version, service_name.get(), more_results); } else if (uuid_in == UUID_DIP) { log::debug("Get UUID_DIP"); - sCallbackEnv->CallVoidMethod( - sCallbacksObj, method_sdpDipRecordFoundCallback, (jint)status, - addr.get(), uuid.get(), (jint)record->dip.spec_id, - (jint)record->dip.vendor, - (jint)record->dip.vendor_id_source, - (jint)record->dip.product, - (jint)record->dip.version, - record->dip.primary_record, - more_results); + sCallbackEnv->CallVoidMethod(sCallbacksObj, method_sdpDipRecordFoundCallback, (jint)status, + addr.get(), uuid.get(), (jint)record->dip.spec_id, + (jint)record->dip.vendor, (jint)record->dip.vendor_id_source, + (jint)record->dip.product, (jint)record->dip.version, + record->dip.primary_record, more_results); } else { // we don't have a wrapper for this uuid, send as raw data jint record_data_size = record->hdr.user1_ptr_len; - ScopedLocalRef record_data( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(record_data_size)); - if (!record_data.get()) return; + ScopedLocalRef record_data(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(record_data_size)); + if (!record_data.get()) { + return; + } sCallbackEnv->SetByteArrayRegion(record_data.get(), 0, record_data_size, (jbyte*)record->hdr.user1_ptr); - sCallbackEnv->CallVoidMethod(sCallbacksObj, method_sdpRecordFoundCallback, - (jint)status, addr.get(), uuid.get(), - record_data_size, record_data.get()); + sCallbackEnv->CallVoidMethod(sCallbacksObj, method_sdpRecordFoundCallback, (jint)status, + addr.get(), uuid.get(), record_data_size, record_data.get()); } } // End of for-loop } -static jint sdpCreateMapMasRecordNative(JNIEnv* env, jobject /* obj */, - jstring name_str, jint mas_id, jint scn, - jint l2cap_psm, jint version, +static jint sdpCreateMapMasRecordNative(JNIEnv* env, jobject /* obj */, jstring name_str, + jint mas_id, jint scn, jint l2cap_psm, jint version, jint msg_types, jint features) { log::debug(""); - if (!sBluetoothSdpInterface) return -1; + if (!sBluetoothSdpInterface) { + return -1; + } bluetooth_sdp_record record = {}; // Must be zero initialized record.mas.hdr.type = SDP_TYPE_MAP_MAS; @@ -252,16 +247,18 @@ static jint sdpCreateMapMasRecordNative(JNIEnv* env, jobject /* obj */, log::debug("SDP Create record success - handle: {}", handle); } - if (service_name) env->ReleaseStringUTFChars(name_str, service_name); + if (service_name) { + env->ReleaseStringUTFChars(name_str, service_name); + } return handle; } -static jint sdpCreateMapMnsRecordNative(JNIEnv* env, jobject /* obj */, - jstring name_str, jint scn, - jint l2cap_psm, jint version, - jint features) { +static jint sdpCreateMapMnsRecordNative(JNIEnv* env, jobject /* obj */, jstring name_str, jint scn, + jint l2cap_psm, jint version, jint features) { log::debug(""); - if (!sBluetoothSdpInterface) return -1; + if (!sBluetoothSdpInterface) { + return -1; + } bluetooth_sdp_record record = {}; // Must be zero initialized record.mns.hdr.type = SDP_TYPE_MAP_MNS; @@ -289,14 +286,18 @@ static jint sdpCreateMapMnsRecordNative(JNIEnv* env, jobject /* obj */, log::debug("SDP Create record success - handle: {}", handle); } - if (service_name) env->ReleaseStringUTFChars(name_str, service_name); + if (service_name) { + env->ReleaseStringUTFChars(name_str, service_name); + } return handle; } -static jint sdpCreatePbapPceRecordNative(JNIEnv* env, jobject /* obj */, - jstring name_str, jint version) { +static jint sdpCreatePbapPceRecordNative(JNIEnv* env, jobject /* obj */, jstring name_str, + jint version) { log::debug(""); - if (!sBluetoothSdpInterface) return -1; + if (!sBluetoothSdpInterface) { + return -1; + } bluetooth_sdp_record record = {}; // Must be zero initialized record.pce.hdr.type = SDP_TYPE_PBAP_PCE; @@ -320,17 +321,19 @@ static jint sdpCreatePbapPceRecordNative(JNIEnv* env, jobject /* obj */, log::debug("SDP Create record success - handle: {}", handle); } - if (service_name) env->ReleaseStringUTFChars(name_str, service_name); + if (service_name) { + env->ReleaseStringUTFChars(name_str, service_name); + } return handle; } -static jint sdpCreatePbapPseRecordNative(JNIEnv* env, jobject /* obj */, - jstring name_str, jint scn, - jint l2cap_psm, jint version, - jint supported_repositories, +static jint sdpCreatePbapPseRecordNative(JNIEnv* env, jobject /* obj */, jstring name_str, jint scn, + jint l2cap_psm, jint version, jint supported_repositories, jint features) { log::debug(""); - if (!sBluetoothSdpInterface) return -1; + if (!sBluetoothSdpInterface) { + return -1; + } bluetooth_sdp_record record = {}; // Must be zero initialized record.pse.hdr.type = SDP_TYPE_PBAP_PSE; @@ -359,16 +362,19 @@ static jint sdpCreatePbapPseRecordNative(JNIEnv* env, jobject /* obj */, log::debug("SDP Create record success - handle: {}", handle); } - if (service_name) env->ReleaseStringUTFChars(name_str, service_name); + if (service_name) { + env->ReleaseStringUTFChars(name_str, service_name); + } return handle; } -static jint sdpCreateOppOpsRecordNative(JNIEnv* env, jobject /* obj */, - jstring name_str, jint scn, +static jint sdpCreateOppOpsRecordNative(JNIEnv* env, jobject /* obj */, jstring name_str, jint scn, jint l2cap_psm, jint version, jbyteArray supported_formats_list) { log::debug(""); - if (!sBluetoothSdpInterface) return -1; + if (!sBluetoothSdpInterface) { + return -1; + } bluetooth_sdp_record record = {}; // Must be zero initialized record.ops.hdr.type = SDP_TYPE_OPP_SERVER; @@ -406,17 +412,21 @@ static jint sdpCreateOppOpsRecordNative(JNIEnv* env, jobject /* obj */, log::debug("SDP Create record success - handle: {}", handle); } - if (service_name) env->ReleaseStringUTFChars(name_str, service_name); - if (formats_list) + if (service_name) { + env->ReleaseStringUTFChars(name_str, service_name); + } + if (formats_list) { env->ReleaseByteArrayElements(supported_formats_list, formats_list, 0); + } return handle; } -static jint sdpCreateSapsRecordNative(JNIEnv* env, jobject /* obj */, - jstring name_str, jint scn, +static jint sdpCreateSapsRecordNative(JNIEnv* env, jobject /* obj */, jstring name_str, jint scn, jint version) { log::debug(""); - if (!sBluetoothSdpInterface) return -1; + if (!sBluetoothSdpInterface) { + return -1; + } bluetooth_sdp_record record = {}; // Must be zero initialized record.sap.hdr.type = SDP_TYPE_SAP_SERVER; @@ -441,14 +451,17 @@ static jint sdpCreateSapsRecordNative(JNIEnv* env, jobject /* obj */, log::debug("SDP Create record success - handle: {}", handle); } - if (service_name) env->ReleaseStringUTFChars(name_str, service_name); + if (service_name) { + env->ReleaseStringUTFChars(name_str, service_name); + } return handle; } -static jboolean sdpRemoveSdpRecordNative(JNIEnv* /* env */, jobject /* obj */, - jint record_id) { +static jboolean sdpRemoveSdpRecordNative(JNIEnv* /* env */, jobject /* obj */, jint record_id) { log::debug(""); - if (!sBluetoothSdpInterface) return false; + if (!sBluetoothSdpInterface) { + return false; + } int ret = sBluetoothSdpInterface->remove_sdp_record(record_id); if (ret != BT_STATUS_SUCCESS) { @@ -483,47 +496,45 @@ static void cleanupNative(JNIEnv* env, jobject /* object */) { int register_com_android_bluetooth_sdp(JNIEnv* env) { const JNINativeMethod methods[] = { - {"initializeNative", "()V", (void*)initializeNative}, - {"cleanupNative", "()V", (void*)cleanupNative}, - {"sdpSearchNative", "([B[B)Z", (void*)sdpSearchNative}, - {"sdpCreateMapMasRecordNative", "(Ljava/lang/String;IIIIII)I", - (void*)sdpCreateMapMasRecordNative}, - {"sdpCreateMapMnsRecordNative", "(Ljava/lang/String;IIII)I", - (void*)sdpCreateMapMnsRecordNative}, - {"sdpCreatePbapPceRecordNative", "(Ljava/lang/String;I)I", - (void*)sdpCreatePbapPceRecordNative}, - {"sdpCreatePbapPseRecordNative", "(Ljava/lang/String;IIIII)I", - (void*)sdpCreatePbapPseRecordNative}, - {"sdpCreateOppOpsRecordNative", "(Ljava/lang/String;III[B)I", - (void*)sdpCreateOppOpsRecordNative}, - {"sdpCreateSapsRecordNative", "(Ljava/lang/String;II)I", - (void*)sdpCreateSapsRecordNative}, - {"sdpRemoveSdpRecordNative", "(I)Z", (void*)sdpRemoveSdpRecordNative}, + {"initializeNative", "()V", (void*)initializeNative}, + {"cleanupNative", "()V", (void*)cleanupNative}, + {"sdpSearchNative", "([B[B)Z", (void*)sdpSearchNative}, + {"sdpCreateMapMasRecordNative", "(Ljava/lang/String;IIIIII)I", + (void*)sdpCreateMapMasRecordNative}, + {"sdpCreateMapMnsRecordNative", "(Ljava/lang/String;IIII)I", + (void*)sdpCreateMapMnsRecordNative}, + {"sdpCreatePbapPceRecordNative", "(Ljava/lang/String;I)I", + (void*)sdpCreatePbapPceRecordNative}, + {"sdpCreatePbapPseRecordNative", "(Ljava/lang/String;IIIII)I", + (void*)sdpCreatePbapPseRecordNative}, + {"sdpCreateOppOpsRecordNative", "(Ljava/lang/String;III[B)I", + (void*)sdpCreateOppOpsRecordNative}, + {"sdpCreateSapsRecordNative", "(Ljava/lang/String;II)I", + (void*)sdpCreateSapsRecordNative}, + {"sdpRemoveSdpRecordNative", "(I)Z", (void*)sdpRemoveSdpRecordNative}, }; const int result = REGISTER_NATIVE_METHODS( - env, "com/android/bluetooth/sdp/SdpManagerNativeInterface", methods); + env, "com/android/bluetooth/sdp/SdpManagerNativeInterface", methods); if (result != 0) { return result; } const JNIJavaMethod javaMethods[] = { - {"sdpRecordFoundCallback", "(I[B[BI[B)V", &method_sdpRecordFoundCallback}, - {"sdpMasRecordFoundCallback", "(I[B[BIIIIIILjava/lang/String;Z)V", - &method_sdpMasRecordFoundCallback}, - {"sdpMnsRecordFoundCallback", "(I[B[BIIIILjava/lang/String;Z)V", - &method_sdpMnsRecordFoundCallback}, - {"sdpPseRecordFoundCallback", "(I[B[BIIIIILjava/lang/String;Z)V", - &method_sdpPseRecordFoundCallback}, - {"sdpOppOpsRecordFoundCallback", "(I[B[BIIILjava/lang/String;[BZ)V", - &method_sdpOppOpsRecordFoundCallback}, - {"sdpSapsRecordFoundCallback", "(I[B[BIILjava/lang/String;Z)V", - &method_sdpSapsRecordFoundCallback}, - {"sdpDipRecordFoundCallback", "(I[B[BIIIIIZZ)V", - &method_sdpDipRecordFoundCallback}, + {"sdpRecordFoundCallback", "(I[B[BI[B)V", &method_sdpRecordFoundCallback}, + {"sdpMasRecordFoundCallback", "(I[B[BIIIIIILjava/lang/String;Z)V", + &method_sdpMasRecordFoundCallback}, + {"sdpMnsRecordFoundCallback", "(I[B[BIIIILjava/lang/String;Z)V", + &method_sdpMnsRecordFoundCallback}, + {"sdpPseRecordFoundCallback", "(I[B[BIIIIILjava/lang/String;Z)V", + &method_sdpPseRecordFoundCallback}, + {"sdpOppOpsRecordFoundCallback", "(I[B[BIIILjava/lang/String;[BZ)V", + &method_sdpOppOpsRecordFoundCallback}, + {"sdpSapsRecordFoundCallback", "(I[B[BIILjava/lang/String;Z)V", + &method_sdpSapsRecordFoundCallback}, + {"sdpDipRecordFoundCallback", "(I[B[BIIIIIZZ)V", &method_sdpDipRecordFoundCallback}, }; - GET_JAVA_METHODS(env, "com/android/bluetooth/sdp/SdpManagerNativeInterface", - javaMethods); + GET_JAVA_METHODS(env, "com/android/bluetooth/sdp/SdpManagerNativeInterface", javaMethods); return 0; } -} +} // namespace android diff --git a/android/app/jni/com_android_bluetooth_vc.cpp b/android/app/jni/com_android_bluetooth_vc.cpp index 27fec9fb466..f56b913afe8 100644 --- a/android/app/jni/com_android_bluetooth_vc.cpp +++ b/android/app/jni/com_android_bluetooth_vc.cpp @@ -44,157 +44,154 @@ static jobject mCallbacksObj = nullptr; static std::shared_timed_mutex callbacks_mutex; class VolumeControlCallbacksImpl : public VolumeControlCallbacks { - public: +public: ~VolumeControlCallbacksImpl() = default; - void OnConnectionState(ConnectionState state, - const RawAddress& bd_addr) override { - log::info("state:{}, addr: {}", int(state), - bd_addr.ToRedactedStringForLogging()); + void OnConnectionState(ConnectionState state, const RawAddress& bd_addr) override { + log::info("state:{}, addr: {}", int(state), bd_addr.ToRedactedStringForLogging()); std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) return; + if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) { + return; + } - ScopedLocalRef addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); + ScopedLocalRef addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); if (!addr.get()) { log::error("Failed to new jbyteArray bd addr for connection state"); return; } - sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), - (jbyte*)&bd_addr); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onConnectionStateChanged, - (jint)state, addr.get()); + sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), (jbyte*)&bd_addr); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onConnectionStateChanged, (jint)state, + addr.get()); } - void OnVolumeStateChanged(const RawAddress& bd_addr, uint8_t volume, - bool mute, bool isAutonomous) override { + void OnVolumeStateChanged(const RawAddress& bd_addr, uint8_t volume, bool mute, + bool isAutonomous) override { log::info(""); std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) return; + if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) { + return; + } - ScopedLocalRef addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); + ScopedLocalRef addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); if (!addr.get()) { log::error("Failed to new jbyteArray bd addr for connection state"); return; } - sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), - (jbyte*)&bd_addr); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onVolumeStateChanged, - (jint)volume, (jboolean)mute, addr.get(), (jboolean)isAutonomous); + sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), (jbyte*)&bd_addr); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onVolumeStateChanged, (jint)volume, + (jboolean)mute, addr.get(), (jboolean)isAutonomous); } - void OnGroupVolumeStateChanged(int group_id, uint8_t volume, - bool mute, bool isAutonomous) override { + void OnGroupVolumeStateChanged(int group_id, uint8_t volume, bool mute, + bool isAutonomous) override { log::info(""); std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) return; + if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) { + return; + } - sCallbackEnv->CallVoidMethod(mCallbacksObj, - method_onGroupVolumeStateChanged, (jint)volume, + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onGroupVolumeStateChanged, (jint)volume, (jboolean)mute, group_id, (jboolean)isAutonomous); } - void OnDeviceAvailable(const RawAddress& bd_addr, - uint8_t num_offsets) override { + void OnDeviceAvailable(const RawAddress& bd_addr, uint8_t num_offsets) override { log::info(""); std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) return; + if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) { + return; + } - ScopedLocalRef addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); + ScopedLocalRef addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); if (!addr.get()) { log::error("Failed to new jbyteArray bd addr for onDeviceAvailable"); return; } - sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), - (jbyte*)&bd_addr); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onDeviceAvailable, - (jint)num_offsets, addr.get()); + sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), (jbyte*)&bd_addr); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onDeviceAvailable, (jint)num_offsets, + addr.get()); } - void OnExtAudioOutVolumeOffsetChanged(const RawAddress& bd_addr, - uint8_t ext_output_id, + void OnExtAudioOutVolumeOffsetChanged(const RawAddress& bd_addr, uint8_t ext_output_id, int16_t offset) override { log::info(""); std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) return; + if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) { + return; + } - ScopedLocalRef addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); + ScopedLocalRef addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); if (!addr.get()) { log::error( - "Failed to new jbyteArray bd addr for " - "OnExtAudioOutVolumeOffsetChanged"); + "Failed to new jbyteArray bd addr for " + "OnExtAudioOutVolumeOffsetChanged"); return; } - sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), - (jbyte*)&bd_addr); - sCallbackEnv->CallVoidMethod(mCallbacksObj, - method_onExtAudioOutVolumeOffsetChanged, + sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), (jbyte*)&bd_addr); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onExtAudioOutVolumeOffsetChanged, (jint)ext_output_id, (jint)offset, addr.get()); } - void OnExtAudioOutLocationChanged(const RawAddress& bd_addr, - uint8_t ext_output_id, + void OnExtAudioOutLocationChanged(const RawAddress& bd_addr, uint8_t ext_output_id, uint32_t location) override { log::info(""); std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) return; + if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) { + return; + } - ScopedLocalRef addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); + ScopedLocalRef addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); if (!addr.get()) { - log::error( - "Failed to new jbyteArray bd addr for OnExtAudioOutLocationChanged"); + log::error("Failed to new jbyteArray bd addr for OnExtAudioOutLocationChanged"); return; } - sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), - (jbyte*)&bd_addr); - sCallbackEnv->CallVoidMethod( - mCallbacksObj, method_onExtAudioOutLocationChanged, (jint)ext_output_id, - (jint)location, addr.get()); + sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), (jbyte*)&bd_addr); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onExtAudioOutLocationChanged, + (jint)ext_output_id, (jint)location, addr.get()); } - void OnExtAudioOutDescriptionChanged(const RawAddress& bd_addr, - uint8_t ext_output_id, + void OnExtAudioOutDescriptionChanged(const RawAddress& bd_addr, uint8_t ext_output_id, std::string descr) override { log::info(""); std::shared_lock lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); - if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) return; + if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) { + return; + } - ScopedLocalRef addr( - sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress))); + ScopedLocalRef addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); if (!addr.get()) { log::error( - "Failed to new jbyteArray bd addr for " - "OnExtAudioOutDescriptionChanged"); + "Failed to new jbyteArray bd addr for " + "OnExtAudioOutDescriptionChanged"); return; } - sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), - (jbyte*)&bd_addr); + sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), (jbyte*)&bd_addr); jstring description = sCallbackEnv->NewStringUTF(descr.c_str()); - sCallbackEnv->CallVoidMethod(mCallbacksObj, - method_onExtAudioOutDescriptionChanged, + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onExtAudioOutDescriptionChanged, (jint)ext_output_id, description, addr.get()); } }; @@ -228,8 +225,7 @@ static void initNative(JNIEnv* env, jobject object) { return; } - sVolumeControlInterface = - (VolumeControlInterface*)btInf->get_profile_interface(BT_PROFILE_VC_ID); + sVolumeControlInterface = (VolumeControlInterface*)btInf->get_profile_interface(BT_PROFILE_VC_ID); if (sVolumeControlInterface == nullptr) { log::error("Failed to get Bluetooth Volume Control Interface"); return; @@ -259,8 +255,7 @@ static void cleanupNative(JNIEnv* env, jobject /* object */) { } } -static jboolean connectVolumeControlNative(JNIEnv* env, jobject /* object */, - jbyteArray address) { +static jboolean connectVolumeControlNative(JNIEnv* env, jobject /* object */, jbyteArray address) { log::info(""); std::shared_lock lock(interface_mutex); @@ -303,8 +298,7 @@ static jboolean disconnectVolumeControlNative(JNIEnv* env, jobject /* object */, return JNI_TRUE; } -static void setVolumeNative(JNIEnv* env, jobject /* object */, - jbyteArray address, jint volume) { +static void setVolumeNative(JNIEnv* env, jobject /* object */, jbyteArray address, jint volume) { if (!sVolumeControlInterface) { log::error("Failed to get the Bluetooth Volume Control Interface"); return; @@ -321,8 +315,8 @@ static void setVolumeNative(JNIEnv* env, jobject /* object */, env->ReleaseByteArrayElements(address, addr, 0); } -static void setGroupVolumeNative(JNIEnv* /* env */, jobject /* object */, - jint group_id, jint volume) { +static void setGroupVolumeNative(JNIEnv* /* env */, jobject /* object */, jint group_id, + jint volume) { if (!sVolumeControlInterface) { log::error("Failed to get the Bluetooth Volume Control Interface"); return; @@ -348,8 +342,7 @@ static void muteNative(JNIEnv* env, jobject /* object */, jbyteArray address) { env->ReleaseByteArrayElements(address, addr, 0); } -static void muteGroupNative(JNIEnv* /* env */, jobject /* object */, - jint group_id) { +static void muteGroupNative(JNIEnv* /* env */, jobject /* object */, jint group_id) { if (!sVolumeControlInterface) { log::error("Failed to get the Bluetooth Volume Control Interface"); return; @@ -357,8 +350,7 @@ static void muteGroupNative(JNIEnv* /* env */, jobject /* object */, sVolumeControlInterface->Mute(group_id); } -static void unmuteNative(JNIEnv* env, jobject /* object */, - jbyteArray address) { +static void unmuteNative(JNIEnv* env, jobject /* object */, jbyteArray address) { if (!sVolumeControlInterface) { log::error("Failed to get the Bluetooth Volume Control Interface"); return; @@ -375,8 +367,7 @@ static void unmuteNative(JNIEnv* env, jobject /* object */, env->ReleaseByteArrayElements(address, addr, 0); } -static void unmuteGroupNative(JNIEnv* /* env */, jobject /* object */, - jint group_id) { +static void unmuteGroupNative(JNIEnv* /* env */, jobject /* object */, jint group_id) { if (!sVolumeControlInterface) { log::error("Failed to get the Bluetooth Volume Control Interface"); return; @@ -385,13 +376,13 @@ static void unmuteGroupNative(JNIEnv* /* env */, jobject /* object */, } /* Native methods for exterbak audio outputs */ -static jboolean getExtAudioOutVolumeOffsetNative(JNIEnv* env, - jobject /* object */, - jbyteArray address, - jint ext_output_id) { +static jboolean getExtAudioOutVolumeOffsetNative(JNIEnv* env, jobject /* object */, + jbyteArray address, jint ext_output_id) { log::info(""); std::shared_lock lock(interface_mutex); - if (!sVolumeControlInterface) return JNI_FALSE; + if (!sVolumeControlInterface) { + return JNI_FALSE; + } jbyte* addr = env->GetByteArrayElements(address, nullptr); if (!addr) { @@ -405,14 +396,14 @@ static jboolean getExtAudioOutVolumeOffsetNative(JNIEnv* env, return JNI_TRUE; } -static jboolean setExtAudioOutVolumeOffsetNative(JNIEnv* env, - jobject /* object */, - jbyteArray address, - jint ext_output_id, +static jboolean setExtAudioOutVolumeOffsetNative(JNIEnv* env, jobject /* object */, + jbyteArray address, jint ext_output_id, jint offset) { log::info(""); std::shared_lock lock(interface_mutex); - if (!sVolumeControlInterface) return JNI_FALSE; + if (!sVolumeControlInterface) { + return JNI_FALSE; + } jbyte* addr = env->GetByteArrayElements(address, nullptr); if (!addr) { @@ -421,18 +412,18 @@ static jboolean setExtAudioOutVolumeOffsetNative(JNIEnv* env, } RawAddress* tmpraw = (RawAddress*)addr; - sVolumeControlInterface->SetExtAudioOutVolumeOffset(*tmpraw, ext_output_id, - offset); + sVolumeControlInterface->SetExtAudioOutVolumeOffset(*tmpraw, ext_output_id, offset); env->ReleaseByteArrayElements(address, addr, 0); return JNI_TRUE; } -static jboolean getExtAudioOutLocationNative(JNIEnv* env, jobject /* object */, - jbyteArray address, +static jboolean getExtAudioOutLocationNative(JNIEnv* env, jobject /* object */, jbyteArray address, jint ext_output_id) { log::info(""); std::shared_lock lock(interface_mutex); - if (!sVolumeControlInterface) return JNI_FALSE; + if (!sVolumeControlInterface) { + return JNI_FALSE; + } jbyte* addr = env->GetByteArrayElements(address, nullptr); if (!addr) { @@ -446,13 +437,13 @@ static jboolean getExtAudioOutLocationNative(JNIEnv* env, jobject /* object */, return JNI_TRUE; } -static jboolean setExtAudioOutLocationNative(JNIEnv* env, jobject /* object */, - jbyteArray address, - jint ext_output_id, - jint location) { +static jboolean setExtAudioOutLocationNative(JNIEnv* env, jobject /* object */, jbyteArray address, + jint ext_output_id, jint location) { log::info(""); std::shared_lock lock(interface_mutex); - if (!sVolumeControlInterface) return JNI_FALSE; + if (!sVolumeControlInterface) { + return JNI_FALSE; + } jbyte* addr = env->GetByteArrayElements(address, nullptr); if (!addr) { @@ -461,19 +452,18 @@ static jboolean setExtAudioOutLocationNative(JNIEnv* env, jobject /* object */, } RawAddress* tmpraw = (RawAddress*)addr; - sVolumeControlInterface->SetExtAudioOutLocation(*tmpraw, ext_output_id, - location); + sVolumeControlInterface->SetExtAudioOutLocation(*tmpraw, ext_output_id, location); env->ReleaseByteArrayElements(address, addr, 0); return JNI_TRUE; } -static jboolean getExtAudioOutDescriptionNative(JNIEnv* env, - jobject /* object */, - jbyteArray address, - jint ext_output_id) { +static jboolean getExtAudioOutDescriptionNative(JNIEnv* env, jobject /* object */, + jbyteArray address, jint ext_output_id) { log::info(""); std::shared_lock lock(interface_mutex); - if (!sVolumeControlInterface) return JNI_FALSE; + if (!sVolumeControlInterface) { + return JNI_FALSE; + } jbyte* addr = env->GetByteArrayElements(address, nullptr); if (!addr) { @@ -487,14 +477,14 @@ static jboolean getExtAudioOutDescriptionNative(JNIEnv* env, return JNI_TRUE; } -static jboolean setExtAudioOutDescriptionNative(JNIEnv* env, - jobject /* object */, - jbyteArray address, - jint ext_output_id, +static jboolean setExtAudioOutDescriptionNative(JNIEnv* env, jobject /* object */, + jbyteArray address, jint ext_output_id, jstring descr) { log::info(""); std::shared_lock lock(interface_mutex); - if (!sVolumeControlInterface) return JNI_FALSE; + if (!sVolumeControlInterface) { + return JNI_FALSE; + } jbyte* addr = env->GetByteArrayElements(address, nullptr); if (!addr) { @@ -510,60 +500,48 @@ static jboolean setExtAudioOutDescriptionNative(JNIEnv* env, } RawAddress* tmpraw = (RawAddress*)addr; - sVolumeControlInterface->SetExtAudioOutDescription(*tmpraw, ext_output_id, - description); + sVolumeControlInterface->SetExtAudioOutDescription(*tmpraw, ext_output_id, description); env->ReleaseByteArrayElements(address, addr, 0); return JNI_TRUE; } int register_com_android_bluetooth_vc(JNIEnv* env) { const JNINativeMethod methods[] = { - {"initNative", "()V", (void*)initNative}, - {"cleanupNative", "()V", (void*)cleanupNative}, - {"connectVolumeControlNative", "([B)Z", - (void*)connectVolumeControlNative}, - {"disconnectVolumeControlNative", "([B)Z", - (void*)disconnectVolumeControlNative}, - {"setVolumeNative", "([BI)V", (void*)setVolumeNative}, - {"setGroupVolumeNative", "(II)V", (void*)setGroupVolumeNative}, - {"muteNative", "([B)V", (void*)muteNative}, - {"muteGroupNative", "(I)V", (void*)muteGroupNative}, - {"unmuteNative", "([B)V", (void*)unmuteNative}, - {"unmuteGroupNative", "(I)V", (void*)unmuteGroupNative}, - {"getExtAudioOutVolumeOffsetNative", "([BI)Z", - (void*)getExtAudioOutVolumeOffsetNative}, - {"setExtAudioOutVolumeOffsetNative", "([BII)Z", - (void*)setExtAudioOutVolumeOffsetNative}, - {"getExtAudioOutLocationNative", "([BI)Z", - (void*)getExtAudioOutLocationNative}, - {"setExtAudioOutLocationNative", "([BII)Z", - (void*)setExtAudioOutLocationNative}, - {"getExtAudioOutDescriptionNative", "([BI)Z", - (void*)getExtAudioOutDescriptionNative}, - {"setExtAudioOutDescriptionNative", "([BILjava/lang/String;)Z", - (void*)setExtAudioOutDescriptionNative}, + {"initNative", "()V", (void*)initNative}, + {"cleanupNative", "()V", (void*)cleanupNative}, + {"connectVolumeControlNative", "([B)Z", (void*)connectVolumeControlNative}, + {"disconnectVolumeControlNative", "([B)Z", (void*)disconnectVolumeControlNative}, + {"setVolumeNative", "([BI)V", (void*)setVolumeNative}, + {"setGroupVolumeNative", "(II)V", (void*)setGroupVolumeNative}, + {"muteNative", "([B)V", (void*)muteNative}, + {"muteGroupNative", "(I)V", (void*)muteGroupNative}, + {"unmuteNative", "([B)V", (void*)unmuteNative}, + {"unmuteGroupNative", "(I)V", (void*)unmuteGroupNative}, + {"getExtAudioOutVolumeOffsetNative", "([BI)Z", (void*)getExtAudioOutVolumeOffsetNative}, + {"setExtAudioOutVolumeOffsetNative", "([BII)Z", (void*)setExtAudioOutVolumeOffsetNative}, + {"getExtAudioOutLocationNative", "([BI)Z", (void*)getExtAudioOutLocationNative}, + {"setExtAudioOutLocationNative", "([BII)Z", (void*)setExtAudioOutLocationNative}, + {"getExtAudioOutDescriptionNative", "([BI)Z", (void*)getExtAudioOutDescriptionNative}, + {"setExtAudioOutDescriptionNative", "([BILjava/lang/String;)Z", + (void*)setExtAudioOutDescriptionNative}, }; const int result = REGISTER_NATIVE_METHODS( - env, "com/android/bluetooth/vc/VolumeControlNativeInterface", methods); + env, "com/android/bluetooth/vc/VolumeControlNativeInterface", methods); if (result != 0) { return result; } const JNIJavaMethod javaMethods[] = { - {"onConnectionStateChanged", "(I[B)V", &method_onConnectionStateChanged}, - {"onVolumeStateChanged", "(IZ[BZ)V", &method_onVolumeStateChanged}, - {"onGroupVolumeStateChanged", "(IZIZ)V", - &method_onGroupVolumeStateChanged}, - {"onDeviceAvailable", "(I[B)V", &method_onDeviceAvailable}, - {"onExtAudioOutVolumeOffsetChanged", "(II[B)V", - &method_onExtAudioOutVolumeOffsetChanged}, - {"onExtAudioOutLocationChanged", "(II[B)V", - &method_onExtAudioOutLocationChanged}, - {"onExtAudioOutDescriptionChanged", "(ILjava/lang/String;[B)V", - &method_onExtAudioOutDescriptionChanged}, + {"onConnectionStateChanged", "(I[B)V", &method_onConnectionStateChanged}, + {"onVolumeStateChanged", "(IZ[BZ)V", &method_onVolumeStateChanged}, + {"onGroupVolumeStateChanged", "(IZIZ)V", &method_onGroupVolumeStateChanged}, + {"onDeviceAvailable", "(I[B)V", &method_onDeviceAvailable}, + {"onExtAudioOutVolumeOffsetChanged", "(II[B)V", &method_onExtAudioOutVolumeOffsetChanged}, + {"onExtAudioOutLocationChanged", "(II[B)V", &method_onExtAudioOutLocationChanged}, + {"onExtAudioOutDescriptionChanged", "(ILjava/lang/String;[B)V", + &method_onExtAudioOutDescriptionChanged}, }; - GET_JAVA_METHODS(env, "com/android/bluetooth/vc/VolumeControlNativeInterface", - javaMethods); + GET_JAVA_METHODS(env, "com/android/bluetooth/vc/VolumeControlNativeInterface", javaMethods); return 0; } diff --git a/android/app/jni/jni_logging.h b/android/app/jni/jni_logging.h index c2b9bd97d12..7caa2ab745d 100644 --- a/android/app/jni/jni_logging.h +++ b/android/app/jni/jni_logging.h @@ -22,8 +22,7 @@ * Logs an exception. If the exception is omitted or NULL, logs the current * exception from the JNI environment, if any. */ -#define LOG_EX(env, priority, tag, ...) \ - jniLogException(env, ANDROID_##priority, tag, ##__VA_ARGS__) +#define LOG_EX(env, priority, tag, ...) jniLogException(env, ANDROID_##priority, tag, ##__VA_ARGS__) #define LOGV_EX(env, ...) LOG_EX(env, LOG_VERBOSE, LOG_TAG, ##__VA_ARGS__) #define LOGD_EX(env, ...) LOG_EX(env, LOG_DEBUG, LOG_TAG, ##__VA_ARGS__) #define LOGI_EX(env, ...) LOG_EX(env, LOG_INFO, LOG_TAG, ##__VA_ARGS__) diff --git a/android/app/src/com/android/bluetooth/a2dp/A2dpCodecConfig.java b/android/app/src/com/android/bluetooth/a2dp/A2dpCodecConfig.java index bfab4d6e9f3..39efb93496f 100644 --- a/android/app/src/com/android/bluetooth/a2dp/A2dpCodecConfig.java +++ b/android/app/src/com/android/bluetooth/a2dp/A2dpCodecConfig.java @@ -64,7 +64,7 @@ class A2dpCodecConfig { AudioManager audioManager = mContext.getSystemService(AudioManager.class); if (audioManager == null) { - Log.w(TAG, "Can't obtain the codec offloading prefernece from null AudioManager"); + Log.w(TAG, "Can't obtain the codec offloading preference from null AudioManager"); return; } mCodecConfigOffloading = diff --git a/android/app/src/com/android/bluetooth/le_audio/LeAudioCodecConfig.java b/android/app/src/com/android/bluetooth/le_audio/LeAudioCodecConfig.java index b49a4992012..ae159225c45 100644 --- a/android/app/src/com/android/bluetooth/le_audio/LeAudioCodecConfig.java +++ b/android/app/src/com/android/bluetooth/le_audio/LeAudioCodecConfig.java @@ -37,7 +37,7 @@ class LeAudioCodecConfig { AudioManager audioManager = mContext.getSystemService(AudioManager.class); if (audioManager == null) { - Log.w(TAG, "Can't obtain the codec offloading prefernece from null AudioManager"); + Log.w(TAG, "Can't obtain the codec offloading preference from null AudioManager"); return; } diff --git a/android/app/src/com/android/bluetooth/map/BluetoothMapService.java b/android/app/src/com/android/bluetooth/map/BluetoothMapService.java index 97fb7c2baa8..04b00b97abf 100644 --- a/android/app/src/com/android/bluetooth/map/BluetoothMapService.java +++ b/android/app/src/com/android/bluetooth/map/BluetoothMapService.java @@ -259,7 +259,7 @@ public class BluetoothMapService extends ProfileService { 1); Log.w( TAG, - "IOException occured while starting an obexServerSession restarting" + "IOException occurred while starting an obexServerSession restarting" + " the listener", e); mMasInstances.valueAt(i).restartObexServerSession(); @@ -271,7 +271,7 @@ public class BluetoothMapService extends ProfileService { 2); Log.w( TAG, - "RemoteException occured while starting an obexServerSession restarting" + "RemoteException occurred while starting an obexServerSession restarting" + " the listener", e); mMasInstances.valueAt(i).restartObexServerSession(); diff --git a/android/app/src/com/android/bluetooth/sap/SapMessage.java b/android/app/src/com/android/bluetooth/sap/SapMessage.java index 9eb35e53c48..d06f4bc20ea 100644 --- a/android/app/src/com/android/bluetooth/sap/SapMessage.java +++ b/android/app/src/com/android/bluetooth/sap/SapMessage.java @@ -864,8 +864,8 @@ public class SapMessage { throw new IOException("Wrong msg header received: Type: " + msg.getType()); } } catch (InvalidProtocolBufferMicroException e) { - Log.w(TAG, "Error occured parsing a RIL message", e); - throw new IOException("Error occured parsing a RIL message"); + Log.w(TAG, "Error occurred parsing a RIL message", e); + throw new IOException("Error occurred parsing a RIL message"); } } diff --git a/flags/hfp.aconfig b/flags/hfp.aconfig index dabe666bfaa..5b493da3daf 100644 --- a/flags/hfp.aconfig +++ b/flags/hfp.aconfig @@ -49,7 +49,7 @@ flag { flag { name: "reset_after_collision" namespace: "bluetooth" - description: "Reset p_scb when collision occured and rfcomm is not opened yet" + description: "Reset p_scb when collision occurred and rfcomm is not opened yet" bug: "332324315" metadata { purpose: PURPOSE_BUGFIX diff --git a/floss/android-base/include/android-base/parseint.h b/floss/android-base/include/android-base/parseint.h index c4144fde842..e072f9828fa 100644 --- a/floss/android-base/include/android-base/parseint.h +++ b/floss/android-base/include/android-base/parseint.h @@ -34,8 +34,7 @@ namespace base { template bool ParseUint(const char* s, T* out, T max = std::numeric_limits::max(), bool allow_suffixes = false) { - static_assert(std::is_unsigned::value, - "ParseUint can only be used with unsigned types"); + static_assert(std::is_unsigned::value, "ParseUint can only be used with unsigned types"); while (isspace(*s)) { s++; } @@ -52,7 +51,9 @@ bool ParseUint(const char* s, T* out, T max = std::numeric_limits::max(), errno = 0; char* end; unsigned long long int result = strtoull(s, &end, base); - if (errno != 0) return false; + if (errno != 0) { + return false; + } if (end == s) { errno = EINVAL; return false; @@ -60,10 +61,8 @@ bool ParseUint(const char* s, T* out, T max = std::numeric_limits::max(), if (*end != '\0') { const char* suffixes = "bkmgtpe"; const char* suffix; - if ((!allow_suffixes || - (suffix = strchr(suffixes, tolower(*end))) == nullptr) || - __builtin_mul_overflow(result, 1ULL << (10 * (suffix - suffixes)), - &result)) { + if ((!allow_suffixes || (suffix = strchr(suffixes, tolower(*end))) == nullptr) || + __builtin_mul_overflow(result, 1ULL << (10 * (suffix - suffixes)), &result)) { errno = EINVAL; return false; } @@ -80,22 +79,19 @@ bool ParseUint(const char* s, T* out, T max = std::numeric_limits::max(), // TODO: string_view template -bool ParseUint(const std::string& s, T* out, - T max = std::numeric_limits::max(), +bool ParseUint(const std::string& s, T* out, T max = std::numeric_limits::max(), bool allow_suffixes = false) { return ParseUint(s.c_str(), out, max, allow_suffixes); } template -bool ParseByteCount(const char* s, T* out, - T max = std::numeric_limits::max()) { +bool ParseByteCount(const char* s, T* out, T max = std::numeric_limits::max()) { return ParseUint(s, out, max, true); } // TODO: string_view template -bool ParseByteCount(const std::string& s, T* out, - T max = std::numeric_limits::max()) { +bool ParseByteCount(const std::string& s, T* out, T max = std::numeric_limits::max()) { return ParseByteCount(s.c_str(), out, max); } @@ -106,8 +102,7 @@ bool ParseByteCount(const std::string& s, T* out, template bool ParseInt(const char* s, T* out, T min = std::numeric_limits::min(), T max = std::numeric_limits::max()) { - static_assert(std::is_signed::value, - "ParseInt can only be used with signed types"); + static_assert(std::is_signed::value, "ParseInt can only be used with signed types"); while (isspace(*s)) { s++; } @@ -135,8 +130,7 @@ bool ParseInt(const char* s, T* out, T min = std::numeric_limits::min(), // TODO: string_view template -bool ParseInt(const std::string& s, T* out, - T min = std::numeric_limits::min(), +bool ParseInt(const std::string& s, T* out, T min = std::numeric_limits::min(), T max = std::numeric_limits::max()) { return ParseInt(s.c_str(), out, min, max); } diff --git a/floss/android-base/include/android-base/properties.h b/floss/android-base/include/android-base/properties.h index 23a94fc5376..cd1c1d48bbf 100644 --- a/floss/android-base/include/android-base/properties.h +++ b/floss/android-base/include/android-base/properties.h @@ -23,8 +23,7 @@ namespace base { // Returns the current value of the system property `key`, // or `default_value` if the property is empty or doesn't exist. -std::string GetProperty(const std::string& key, - const std::string& default_value); +std::string GetProperty(const std::string& key, const std::string& default_value); // Sets the system property `key` to `value`. bool SetProperty(const std::string& key, const std::string& value); diff --git a/floss/android-base/properties.cc b/floss/android-base/properties.cc index dea892b6c42..45e293ba921 100644 --- a/floss/android-base/properties.cc +++ b/floss/android-base/properties.cc @@ -21,8 +21,7 @@ namespace android { namespace base { -std::string GetProperty(const std::string& key, - const std::string& default_value) { +std::string GetProperty(const std::string& key, const std::string& default_value) { return bluetooth::os::GetSystemProperty(key).value_or(default_value); } diff --git a/floss/libflags/get_flags.cc b/floss/libflags/get_flags.cc index 233662ac6de..661a2c92bed 100644 --- a/floss/libflags/get_flags.cc +++ b/floss/libflags/get_flags.cc @@ -20,11 +20,11 @@ namespace server_configurable_flags { -std::string GetServerConfigurableFlag( - const std::string& experiment_category_name, - const std::string& experiment_flag_name, const std::string& default_value) { - std::string prop_name = "persist.device_config." + experiment_category_name + - "." + experiment_flag_name; +std::string GetServerConfigurableFlag(const std::string& experiment_category_name, + const std::string& experiment_flag_name, + const std::string& default_value) { + std::string prop_name = + "persist.device_config." + experiment_category_name + "." + experiment_flag_name; return bluetooth::os::GetSystemProperty(prop_name).value_or(default_value); } } // namespace server_configurable_flags diff --git a/floss/libflags/include/server_configurable_flags/get_flags.h b/floss/libflags/include/server_configurable_flags/get_flags.h index 04f413e7495..1cc7ecbc75d 100644 --- a/floss/libflags/include/server_configurable_flags/get_flags.h +++ b/floss/libflags/include/server_configurable_flags/get_flags.h @@ -20,8 +20,8 @@ namespace server_configurable_flags { -std::string GetServerConfigurableFlag( - const std::string& experiment_category_name, - const std::string& experiment_flag_name, const std::string& default_value); +std::string GetServerConfigurableFlag(const std::string& experiment_category_name, + const std::string& experiment_flag_name, + const std::string& default_value); } // namespace server_configurable_flags diff --git a/system/audio/asrc/asrc_resampler.cc b/system/audio/asrc/asrc_resampler.cc index ed2c4cbcb48..fcb3a78027f 100644 --- a/system/audio/asrc/asrc_resampler.cc +++ b/system/audio/asrc/asrc_resampler.cc @@ -34,8 +34,7 @@ namespace bluetooth::audio::asrc { -class SourceAudioHalAsrc::ClockRecovery - : public bluetooth::hal::ReadClockHandler { +class SourceAudioHalAsrc::ClockRecovery : public bluetooth::hal::ReadClockHandler { std::mutex mutex_; bluetooth::common::RepeatingTimer read_clock_timer_; @@ -67,8 +66,8 @@ class SourceAudioHalAsrc::ClockRecovery int drift_us; } output_stats_; - __attribute__((no_sanitize("integer"))) void OnEvent( - uint32_t timestamp_us, uint32_t bt_clock) override { + __attribute__((no_sanitize("integer"))) void OnEvent(uint32_t timestamp_us, + uint32_t bt_clock) override { auto& state = state_; // Setup the start point of the streaming @@ -95,7 +94,9 @@ class SourceAudioHalAsrc::ClockRecovery int dt_current = int(timestamp_us - local_time); state.decim_dt[1] = std::min(state.decim_dt[1], dt_current); - if (local_time - state.decim_t0 < 1000 * 1000) return; + if (local_time - state.decim_t0 < 1000 * 1000) { + return; + } state.decim_t0 += 1000 * 1000; @@ -132,8 +133,7 @@ class SourceAudioHalAsrc::ClockRecovery const double b0 = 6.6077909823e-04, b1 = 1.3215581965e-03, b2 = b0; state.butter_drift = drift * b0 + state.butter_s[0]; - state.butter_s[0] = - state.butter_s[1] + drift * b1 - state.butter_drift * a1; + state.butter_s[0] = state.butter_s[1] + drift * b1 - state.butter_drift * a1; state.butter_s[1] = drift * b2 - state.butter_drift * a2; // The stream time is adjusted with the filtered drift, and the error is @@ -142,8 +142,7 @@ class SourceAudioHalAsrc::ClockRecovery // corrected by the decimated deviation. int err = state.stream_time - (state.local_time + state.decim_dt[0]); - state.stream_time += - (int(ldexpf(state.butter_drift, 8)) - err + (1 << 7)) >> 8; + state.stream_time += (int(ldexpf(state.butter_drift, 8)) - err + (1 << 7)) >> 8; // Update recovered timing information, and sample the output statistics. @@ -161,41 +160,41 @@ class SourceAudioHalAsrc::ClockRecovery } log::info( - "Deviation: {:6} us ({:3.0f} ppm) | Output Fs: {:5.2f} Hz drift: {:2} " - "us", - state.stream_time - state.local_time, state.butter_drift, - output_stats.sample_rate, output_stats.drift_us); + "Deviation: {:6} us ({:3.0f} ppm) | Output Fs: {:5.2f} Hz drift: {:2} " + "us", + state.stream_time - state.local_time, state.butter_drift, output_stats.sample_rate, + output_stats.drift_us); } - public: +public: ClockRecovery(bluetooth::common::MessageLoopThread* thread) : state_{.id = StateId::RESET}, reference_timing_{0, 0, 0} { if (com::android::bluetooth::flags::run_clock_recovery_in_worker_thread()) { read_clock_timer_.SchedulePeriodic( - thread->GetWeakPtr(), FROM_HERE, - base::BindRepeating( - [](void*) { - bluetooth::shim::GetHciLayer()->EnqueueCommand( - bluetooth::hci::ReadClockBuilder::Create( - 0, bluetooth::hci::WhichClock::LOCAL), - get_main_thread()->BindOnce( - [](bluetooth::hci::CommandCompleteView) {})); - }, - nullptr), - std::chrono::milliseconds(100)); + thread->GetWeakPtr(), FROM_HERE, + base::BindRepeating( + [](void*) { + bluetooth::shim::GetHciLayer()->EnqueueCommand( + bluetooth::hci::ReadClockBuilder::Create( + 0, bluetooth::hci::WhichClock::LOCAL), + get_main_thread()->BindOnce( + [](bluetooth::hci::CommandCompleteView) {})); + }, + nullptr), + std::chrono::milliseconds(100)); } else { read_clock_timer_.SchedulePeriodic( - get_main_thread()->GetWeakPtr(), FROM_HERE, - base::BindRepeating( - [](void*) { - bluetooth::shim::GetHciLayer()->EnqueueCommand( - bluetooth::hci::ReadClockBuilder::Create( - 0, bluetooth::hci::WhichClock::LOCAL), - get_main_thread()->BindOnce( - [](bluetooth::hci::CommandCompleteView) {})); - }, - nullptr), - std::chrono::milliseconds(100)); + get_main_thread()->GetWeakPtr(), FROM_HERE, + base::BindRepeating( + [](void*) { + bluetooth::shim::GetHciLayer()->EnqueueCommand( + bluetooth::hci::ReadClockBuilder::Create( + 0, bluetooth::hci::WhichClock::LOCAL), + get_main_thread()->BindOnce( + [](bluetooth::hci::CommandCompleteView) {})); + }, + nullptr), + std::chrono::milliseconds(100)); } hal::LinkClocker::Register(this); @@ -206,8 +205,7 @@ class SourceAudioHalAsrc::ClockRecovery read_clock_timer_.Cancel(); } - __attribute__((no_sanitize("integer"))) uint32_t Convert( - uint32_t stream_time) { + __attribute__((no_sanitize("integer"))) uint32_t Convert(uint32_t stream_time) { // Compute the difference between the stream time and the sampled time // of the clock recovery, and adjust according to the drift. // Then return the sampled local time, modified by this converted gap. @@ -246,17 +244,16 @@ class SourceAudioHalAsrc::Resampler { // Apply the transfer coefficients `h`, corrected by linear interpolation, // given fraction position `mu` weigthed by `d` values. - inline int32_t Filter(const int32_t* in, const int32_t* h, int16_t mu, - const int16_t* d); + inline int32_t Filter(const int32_t* in, const int32_t* h, int16_t mu, const int16_t* d); // Upsampling loop, the ratio is less than 1.0 in Q26 format, // more output samples are produced compared to input. template - __attribute__((no_sanitize("integer"))) void Upsample( - unsigned ratio, const T* in, int in_stride, size_t in_len, - size_t* in_count, T* out, int out_stride, size_t out_len, - size_t* out_count) { + __attribute__((no_sanitize("integer"))) void Upsample(unsigned ratio, const T* in, int in_stride, + size_t in_len, size_t* in_count, T* out, + int out_stride, size_t out_len, + size_t* out_count) { int nin = in_len, nout = out_len; while (nin > 0 && nout > 0) { @@ -289,10 +286,10 @@ class SourceAudioHalAsrc::Resampler { // less output samples are produced compared to input. template - __attribute__((no_sanitize("integer"))) void Downsample( - unsigned ratio, const T* in, int in_stride, size_t in_len, - size_t* in_count, T* out, int out_stride, size_t out_len, - size_t* out_count) { + __attribute__((no_sanitize("integer"))) void Downsample(unsigned ratio, const T* in, + int in_stride, size_t in_len, + size_t* in_count, T* out, int out_stride, + size_t out_len, size_t* out_count) { size_t nin = in_len, nout = out_len; while (nin > 0 && nout > 0) { @@ -321,7 +318,7 @@ class SourceAudioHalAsrc::Resampler { *out_count = out_len - nout; } - public: +public: Resampler(int bit_depth) : h_(asrc::resampler_tables.h), d_(asrc::resampler_tables.d), @@ -337,14 +334,11 @@ class SourceAudioHalAsrc::Resampler { // the input stream, in Q26 format. template - void Resample(unsigned ratio_q26, const T* in, int in_stride, size_t in_len, - size_t* in_count, T* out, int out_stride, size_t out_len, - size_t* out_count, unsigned* in_sub_q26) { - auto fn = ratio_q26 < (1u << 26) ? &Resampler::Upsample - : &Resampler::Downsample; + void Resample(unsigned ratio_q26, const T* in, int in_stride, size_t in_len, size_t* in_count, + T* out, int out_stride, size_t out_len, size_t* out_count, unsigned* in_sub_q26) { + auto fn = ratio_q26 < (1u << 26) ? &Resampler::Upsample : &Resampler::Downsample; - (this->*fn)(ratio_q26, in, in_stride, in_len, in_count, out, out_stride, - out_len, out_count); + (this->*fn)(ratio_q26, in, in_stride, in_len, in_count, out, out_stride, out_len, out_count); *in_sub_q26 = in_pos_ & ((1u << 26) - 1); } @@ -370,10 +364,8 @@ static inline int64x2_t vmlal_low_s32(int64x2_t r, int32x4_t a, int32x4_t b) { return vmlal_s32(r, vget_low_s32(a), vget_low_s32(b)); } -inline int32_t SourceAudioHalAsrc::Resampler::Filter(const int32_t* x, - const int32_t* h, - int16_t _mu, - const int16_t* d) { +inline int32_t SourceAudioHalAsrc::Resampler::Filter(const int32_t* x, const int32_t* h, + int16_t _mu, const int16_t* d) { int64x2_t sx; int16x8_t mu = vdupq_n_s16(_mu); @@ -414,13 +406,12 @@ inline int32_t SourceAudioHalAsrc::Resampler::Filter(const int32_t* x, #else -inline int32_t SourceAudioHalAsrc::Resampler::Filter(const int32_t* in, - const int32_t* h, - int16_t mu, - const int16_t* d) { +inline int32_t SourceAudioHalAsrc::Resampler::Filter(const int32_t* in, const int32_t* h, + int16_t mu, const int16_t* d) { int64_t s = 0; - for (int i = 0; i < 2 * KERNEL_A - 1; i++) + for (int i = 0; i < 2 * KERNEL_A - 1; i++) { s += int64_t(in[i]) * (h[i] + ((mu * d[i] + (1 << 6)) >> 7)); + } s = (s + (1 << 30)) >> 31; return std::clamp(s, int64_t(pcm_min_), int64_t(pcm_max_)); @@ -428,9 +419,9 @@ inline int32_t SourceAudioHalAsrc::Resampler::Filter(const int32_t* in, #endif -SourceAudioHalAsrc::SourceAudioHalAsrc( - bluetooth::common::MessageLoopThread* thread, int channels, int sample_rate, - int bit_depth, int interval_us, int num_burst_buffers, int burst_delay_ms) +SourceAudioHalAsrc::SourceAudioHalAsrc(bluetooth::common::MessageLoopThread* thread, int channels, + int sample_rate, int bit_depth, int interval_us, + int num_burst_buffers, int burst_delay_ms) : sample_rate_(sample_rate), bit_depth_(bit_depth), interval_us_(interval_us), @@ -442,21 +433,15 @@ SourceAudioHalAsrc::SourceAudioHalAsrc( // Check parameters - auto check_bounds = [](int v, int min, int max) { - return v >= min && v <= max; - }; + auto check_bounds = [](int v, int min, int max) { return v >= min && v <= max; }; - if (!check_bounds(channels, 1, 8) || - !check_bounds(sample_rate, 1 * 1000, 100 * 1000) || - !check_bounds(bit_depth, 8, 32) || - !check_bounds(interval_us, 1 * 1000, 100 * 1000) || - !check_bounds(num_burst_buffers, 0, 10) || - !check_bounds(burst_delay_ms, 0, 1000)) { + if (!check_bounds(channels, 1, 8) || !check_bounds(sample_rate, 1 * 1000, 100 * 1000) || + !check_bounds(bit_depth, 8, 32) || !check_bounds(interval_us, 1 * 1000, 100 * 1000) || + !check_bounds(num_burst_buffers, 0, 10) || !check_bounds(burst_delay_ms, 0, 1000)) { log::error( - "Bad parameters: channels: {} sample_rate: {} bit_depth: {} " - "interval_us: {} num_burst_buffers: {} burst_delay_ms: {}", - channels, sample_rate, bit_depth, interval_us, num_burst_buffers, - burst_delay_ms); + "Bad parameters: channels: {} sample_rate: {} bit_depth: {} " + "interval_us: {} num_burst_buffers: {} burst_delay_ms: {}", + channels, sample_rate, bit_depth, interval_us, num_burst_buffers, burst_delay_ms); return; } @@ -478,12 +463,12 @@ SourceAudioHalAsrc::SourceAudioHalAsrc( auto& buffers = buffers_; - int num_interval_samples = - channels * (interval_us_ * sample_rate_) / (1000 * 1000); - buffers_size_ = num_interval_samples * - (bit_depth_ <= 16 ? sizeof(int16_t) : sizeof(int32_t)); + int num_interval_samples = channels * (interval_us_ * sample_rate_) / (1000 * 1000); + buffers_size_ = num_interval_samples * (bit_depth_ <= 16 ? sizeof(int16_t) : sizeof(int32_t)); - for (auto& b : buffers.pool) b.resize(buffers_size_); + for (auto& b : buffers.pool) { + b.resize(buffers_size_); + } buffers.index = 0; buffers.offset = 0; @@ -493,7 +478,9 @@ SourceAudioHalAsrc::SourceAudioHalAsrc( std::fill(silence_buffer->begin(), silence_buffer->end(), 0); burst_buffers_.resize(num_burst_buffers); - for (auto& b : burst_buffers_) b = silence_buffer; + for (auto& b : burst_buffers_) { + b = silence_buffer; + } burst_delay_us_ = burst_delay_ms * 1000; } @@ -502,8 +489,8 @@ SourceAudioHalAsrc::~SourceAudioHalAsrc() {} template __attribute__((no_sanitize("integer"))) void SourceAudioHalAsrc::Resample( - double ratio, const std::vector& in, - std::vector*>* out, uint32_t* output_us) { + double ratio, const std::vector& in, std::vector*>* out, + uint32_t* output_us) { auto& resamplers = *resamplers_; auto& buffers = buffers_; auto channels = resamplers.size(); @@ -531,9 +518,10 @@ __attribute__((no_sanitize("integer"))) void SourceAudioHalAsrc::Resample( size_t in_count, out_count; - for (auto& r : resamplers) - r.Resample(ratio_q26, in_data++, channels, in_length, &in_count, - out_data++, channels, out_length, &out_count, &sub_q26); + for (auto& r : resamplers) { + r.Resample(ratio_q26, in_data++, channels, in_length, &in_count, out_data++, channels, + out_length, &out_count, &sub_q26); + } in_length -= in_count; buffers.offset += out_count * channels; @@ -543,9 +531,9 @@ __attribute__((no_sanitize("integer"))) void SourceAudioHalAsrc::Resample( // returned by the resampler, adds the sub-sample information. resampler_pos_.samples += out_count; - for (; resampler_pos_.samples >= sample_rate_; - resampler_pos_.samples -= sample_rate_) + for (; resampler_pos_.samples >= sample_rate_; resampler_pos_.samples -= sample_rate_) { resampler_pos_.seconds++; + } // An output buffer has been fulfilled, // select a new buffer in the pool, used as a ring. @@ -561,12 +549,11 @@ __attribute__((no_sanitize("integer"))) void SourceAudioHalAsrc::Resample( // The samples count within a seconds, and sub-sample position, are // converted, then add the number of seconds modulo 2^32. - int64_t output_samples_q26 = (int64_t(resampler_pos_.samples) << 26) - - ((int64_t(sub_q26) << 26) / ratio_q26); + int64_t output_samples_q26 = + (int64_t(resampler_pos_.samples) << 26) - ((int64_t(sub_q26) << 26) / ratio_q26); *output_us = resampler_pos_.seconds * (1000 * 1000) + - uint32_t((output_samples_q26 * 1000 * 1000) / - (int64_t(sample_rate_) << 26)); + uint32_t((output_samples_q26 * 1000 * 1000) / (int64_t(sample_rate_) << 26)); } __attribute__((no_sanitize("integer"))) std::vector*> @@ -574,16 +561,16 @@ SourceAudioHalAsrc::Run(const std::vector& in) { std::vector*> out; if (in.size() != buffers_size_) { - log::error("Inconsistent input buffer size: {} ({} expected)", in.size(), - buffers_size_); + log::error("Inconsistent input buffer size: {} ({} expected)", in.size(), buffers_size_); return out; } // The burst delay has expired, let's generate the burst. if (burst_buffers_.size() && stream_us_ >= burst_delay_us_) { - for (size_t i = 0; i < burst_buffers_.size(); i++) + for (size_t i = 0; i < burst_buffers_.size(); i++) { out.push_back(burst_buffers_[(out_counter_ + i) % burst_buffers_.size()]); + } burst_buffers_.clear(); } @@ -601,10 +588,11 @@ SourceAudioHalAsrc::Run(const std::vector& in) { uint32_t output_us; - if (bit_depth_ <= 16) + if (bit_depth_ <= 16) { Resample(ratio, in, &out, &output_us); - else + } else { Resample(ratio, in, &out, &output_us); + } drift_us_ += drift_z0_ * (int(output_us - local_us) - drift_us_); @@ -612,21 +600,21 @@ SourceAudioHalAsrc::Run(const std::vector& in) { // the associated delay has expired. if (burst_buffers_.size()) { - for (size_t i = 0; i < out.size(); i++) + for (size_t i = 0; i < out.size(); i++) { std::exchange*>( - out[i], burst_buffers_[(out_counter_ + i) % burst_buffers_.size()]); + out[i], burst_buffers_[(out_counter_ + i) % burst_buffers_.size()]); + } } // Return the output statistics to the clock recovery module out_counter_ += out.size(); - clock_recovery_->UpdateOutputStats(ratio * sample_rate_, - int(output_us - local_us)); + clock_recovery_->UpdateOutputStats(ratio * sample_rate_, int(output_us - local_us)); - if (0) - log::info("[{:6}.{:06}] Fs: {:.2f} Hz drift: {} us", - output_us / (1000 * 1000), output_us % (1000 * 1000), - ratio * sample_rate_, int(output_us - local_us)); + if (0) { + log::info("[{:6}.{:06}] Fs: {:.2f} Hz drift: {} us", output_us / (1000 * 1000), + output_us % (1000 * 1000), ratio * sample_rate_, int(output_us - local_us)); + } return out; } diff --git a/system/audio/asrc/asrc_resampler.h b/system/audio/asrc/asrc_resampler.h index 049bae26db4..9e42c147698 100644 --- a/system/audio/asrc/asrc_resampler.h +++ b/system/audio/asrc/asrc_resampler.h @@ -26,7 +26,7 @@ namespace bluetooth::audio::asrc { class SourceAudioHalAsrc { - public: +public: // The Asynchronous Sample Rate Conversion (ASRC) is set up from the PCM // stream characteristics and the length, expressed in us, of the buffers. // @@ -38,9 +38,9 @@ class SourceAudioHalAsrc { // `burst_delay_ms` helps to ensure that the synchronization with the // transmission intervals is done. - SourceAudioHalAsrc(bluetooth::common::MessageLoopThread* thread, int channels, - int sample_rate, int bit_depth, int interval_us, - int num_burst_buffers = 2, int burst_delay_ms = 500); + SourceAudioHalAsrc(bluetooth::common::MessageLoopThread* thread, int channels, int sample_rate, + int bit_depth, int interval_us, int num_burst_buffers = 2, + int burst_delay_ms = 500); ~SourceAudioHalAsrc(); @@ -54,7 +54,7 @@ class SourceAudioHalAsrc { std::vector*> Run(const std::vector& in); - private: +private: const int sample_rate_; const int bit_depth_; const int interval_us_; @@ -85,8 +85,8 @@ class SourceAudioHalAsrc { } resampler_pos_; template - void Resample(double, const std::vector&, - std::vector*>*, uint32_t*); + void Resample(double, const std::vector&, std::vector*>*, + uint32_t*); friend class SourceAudioHalAsrcTest; }; diff --git a/system/audio/asrc/asrc_resampler_test.cc b/system/audio/asrc/asrc_resampler_test.cc index a6a02163c83..f631a16ac67 100644 --- a/system/audio/asrc/asrc_resampler_test.cc +++ b/system/audio/asrc/asrc_resampler_test.cc @@ -20,9 +20,7 @@ #include bluetooth::common::MessageLoopThread message_loop_thread("main message loop"); -bluetooth::common::MessageLoopThread* get_main_thread() { - return &message_loop_thread; -} +bluetooth::common::MessageLoopThread* get_main_thread() { return &message_loop_thread; } namespace bluetooth::hal { void LinkClocker::Register(ReadClockHandler*) {} @@ -32,53 +30,50 @@ void LinkClocker::Unregister() {} namespace bluetooth::audio::asrc { class SourceAudioHalAsrcTest : public SourceAudioHalAsrc { - public: +public: SourceAudioHalAsrcTest(int channels, int bitdepth) - : SourceAudioHalAsrc(&message_loop_thread, channels, 48000, bitdepth, - 10000) {} + : SourceAudioHalAsrc(&message_loop_thread, channels, 48000, bitdepth, 10000) {} template - void Resample(double ratio, const T* in, size_t in_length, size_t* in_count, - T* out, size_t out_length, size_t* out_count) { + void Resample(double ratio, const T* in, size_t in_length, size_t* in_count, T* out, + size_t out_length, size_t* out_count) { auto resamplers = *resamplers_; auto channels = resamplers.size(); unsigned sub_q26; - for (auto& r : resamplers) - r.Resample(round(ldexp(ratio, 26)), in, channels, in_length / channels, - in_count, out, channels, out_length / channels, out_count, - &sub_q26); + for (auto& r : resamplers) { + r.Resample(round(ldexp(ratio, 26)), in, channels, in_length / channels, in_count, out, + channels, out_length / channels, out_count, &sub_q26); + } } }; -extern "C" void resample_i16(int channels, int bitdepth, double ratio, - const int16_t* in, size_t in_length, int16_t* out, - size_t out_length) { +extern "C" void resample_i16(int channels, int bitdepth, double ratio, const int16_t* in, + size_t in_length, int16_t* out, size_t out_length) { size_t in_count, out_count; SourceAudioHalAsrcTest(channels, bitdepth) - .Resample(ratio, in, in_length, &in_count, out, out_length, - &out_count); + .Resample(ratio, in, in_length, &in_count, out, out_length, &out_count); - if (out_count < out_length) - fprintf(stderr, "wrong output size: %zu:%zu %zu:%zu\n", in_length, in_count, - out_length, out_count); + if (out_count < out_length) { + fprintf(stderr, "wrong output size: %zu:%zu %zu:%zu\n", in_length, in_count, out_length, + out_count); + } return; } -extern "C" void resample_i32(int channels, int bitdepth, double ratio, - const int32_t* in, size_t in_length, int32_t* out, - size_t out_length) { +extern "C" void resample_i32(int channels, int bitdepth, double ratio, const int32_t* in, + size_t in_length, int32_t* out, size_t out_length) { size_t in_count, out_count; SourceAudioHalAsrcTest(channels, bitdepth) - .Resample(ratio, in, in_length, &in_count, out, out_length, - &out_count); + .Resample(ratio, in, in_length, &in_count, out, out_length, &out_count); - if (out_count < out_length) - fprintf(stderr, "wrong output size: %zu:%zu %zu:%zu\n", in_length, in_count, - out_length, out_count); + if (out_count < out_length) { + fprintf(stderr, "wrong output size: %zu:%zu %zu:%zu\n", in_length, in_count, out_length, + out_count); + } return; } diff --git a/system/audio/asrc/asrc_tables.cc b/system/audio/asrc/asrc_tables.cc index b8ecd01c3e8..d4227662bb9 100644 --- a/system/audio/asrc/asrc_tables.cc +++ b/system/audio/asrc/asrc_tables.cc @@ -22,9 +22,7 @@ namespace bluetooth::audio::asrc { // clang-format off const ResamplerTables resampler_tables = { - .h = { - { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2147483647, 0, 0, 0, 0, 0, 0, 0, 0, @@ -2073,11 +2071,9 @@ const ResamplerTables resampler_tables = { -105854, 179671, -292128, 460885, -717386, 1131440, -1911174, 4105509, 2147469981, -4088753, 1906742, -1129337, 716145, -460083, 291594, -179317, 105625, -58875, 30640, -14637, 6266, -2315, 688 }, - }, .d = { - { -1, 3, -9, 24, -57, 120, -230, 413, -700, 1139, -1797, 2797, -4411, 7448, -15972, -53, 16037, -7466, 4420, -2802, 1800, -1141, 702, -413, 231, -120, 57, -25, 9, -3, 1 }, @@ -3614,9 +3610,8 @@ const ResamplerTables resampler_tables = { { 0, -1, 3, -9, 25, -57, 120, -231, 413, -702, 1141, -1800, 2802, -4420, 7466, -16037, 53, 15972, -7448, 4411, -2797, 1797, -1139, 700, -413, 230, -120, 57, -24, 9, -3 }, - } }; -// clang-format off +// clang-format on -} // namespace bluetooth::audio::asrc +} // namespace bluetooth::audio::asrc diff --git a/system/audio/asrc/asrc_tables.h b/system/audio/asrc/asrc_tables.h index 1af63f2e41b..f588073c2cc 100644 --- a/system/audio/asrc/asrc_tables.h +++ b/system/audio/asrc/asrc_tables.h @@ -24,11 +24,8 @@ extern const struct ResamplerTables { static const int KERNEL_Q = 512; static const int KERNEL_A = 16; - const int32_t h alignas(2 * KERNEL_A * - sizeof(int32_t))[KERNEL_Q][2 * KERNEL_A]; - const int16_t d alignas(2 * KERNEL_A * - sizeof(int16_t))[KERNEL_Q][2 * KERNEL_A]; - + const int32_t h alignas(2 * KERNEL_A * sizeof(int32_t))[KERNEL_Q][2 * KERNEL_A]; + const int16_t d alignas(2 * KERNEL_A * sizeof(int16_t))[KERNEL_Q][2 * KERNEL_A]; } resampler_tables; } // namespace bluetooth::audio::asrc diff --git a/system/audio/asrc/asrc_tables.py b/system/audio/asrc/asrc_tables.py index 2bdc5797cdb..ca804af3cb7 100755 --- a/system/audio/asrc/asrc_tables.py +++ b/system/audio/asrc/asrc_tables.py @@ -79,22 +79,18 @@ d32 = np.clip(np.rint(d * 2**23), -(1 << 23), (1 << 23) - 1).astype(np.int16) print("""\ // clang-format off const ResamplerTables resampler_tables = { - - .h = { -""") + .h = {""") for q in range(len(h) - 1): layout = " {{" + " {:10d}," * 8 + "\n" + \ " " + " {:10d}," * 8 + "\n" + \ " " + " {:10d}," * 8 + "\n" + \ " " + " {:10d}," * 6 + " {:10d} }}," print(layout.format(*h32[q])) -print(""" - }, +print(""" }, """) print("""\ - .d = { -""") + .d = {""") for q in range(len(h) - 1): layout = " {{" + " {:6d}," * 10 + "\n" + \ " " + " {:6d}," * 10 + "\n" + \ @@ -103,11 +99,11 @@ for q in range(len(h) - 1): print(""" } }; -// clang-format off""") +// clang-format on""") # # File footer # print(""" -} // namespace bluetooth::audio::asrc""") +} // namespace bluetooth::audio::asrc""") diff --git a/system/audio_bluetooth_hw/audio_bluetooth_hw.cc b/system/audio_bluetooth_hw/audio_bluetooth_hw.cc index 4b66644c796..e752814d2a4 100644 --- a/system/audio_bluetooth_hw/audio_bluetooth_hw.cc +++ b/system/audio_bluetooth_hw/audio_bluetooth_hw.cc @@ -28,15 +28,14 @@ using ::android::bluetooth::audio::utils::GetAudioParamString; using ::android::bluetooth::audio::utils::ParseAudioParams; -static int adev_set_parameters(struct audio_hw_device* dev, - const char* kvpairs) { +static int adev_set_parameters(struct audio_hw_device* dev, const char* kvpairs) { LOG(VERBOSE) << __func__ << ": kevpairs=[" << kvpairs << "]"; - std::unordered_map params = - ParseAudioParams(kvpairs); - if (params.empty()) return 0; + std::unordered_map params = ParseAudioParams(kvpairs); + if (params.empty()) { + return 0; + } - LOG(VERBOSE) << __func__ << ": ParamsMap=[" << GetAudioParamString(params) - << "]"; + LOG(VERBOSE) << __func__ << ": ParamsMap=[" << GetAudioParamString(params) << "]"; if (params.find("A2dpSuspended") == params.end() && params.find("LeAudioSuspended") == params.end()) { return -ENOSYS; @@ -46,15 +45,13 @@ static int adev_set_parameters(struct audio_hw_device* dev, std::lock_guard guard(bluetooth_device->mutex_); for (auto sout : bluetooth_device->opened_stream_outs_) { if (sout->stream_out_.common.set_parameters != nullptr) { - sout->stream_out_.common.set_parameters(&sout->stream_out_.common, - kvpairs); + sout->stream_out_.common.set_parameters(&sout->stream_out_.common, kvpairs); } } return 0; } -static char* adev_get_parameters(const struct audio_hw_device* dev, - const char* keys) { +static char* adev_get_parameters(const struct audio_hw_device* dev, const char* keys) { LOG(VERBOSE) << __func__ << ": keys=[" << keys << "]"; return strdup(""); } @@ -71,18 +68,14 @@ static int adev_set_master_volume(struct audio_hw_device* dev, float volume) { return -ENOSYS; } -static int adev_get_master_volume(struct audio_hw_device* dev, float* volume) { - return -ENOSYS; -} +static int adev_get_master_volume(struct audio_hw_device* dev, float* volume) { return -ENOSYS; } static int adev_set_master_mute(struct audio_hw_device* dev, bool muted) { LOG(VERBOSE) << __func__ << ": mute=" << muted; return -ENOSYS; } -static int adev_get_master_mute(struct audio_hw_device* dev, bool* muted) { - return -ENOSYS; -} +static int adev_get_master_mute(struct audio_hw_device* dev, bool* muted) { return -ENOSYS; } static int adev_set_mode(struct audio_hw_device* dev, audio_mode_t mode) { LOG(VERBOSE) << __func__ << ": mode=" << mode; @@ -94,19 +87,14 @@ static int adev_set_mic_mute(struct audio_hw_device* dev, bool state) { return -ENOSYS; } -static int adev_get_mic_mute(const struct audio_hw_device* dev, bool* state) { - return -ENOSYS; -} +static int adev_get_mic_mute(const struct audio_hw_device* dev, bool* state) { return -ENOSYS; } -static int adev_create_audio_patch(struct audio_hw_device* device, - unsigned int num_sources, - const struct audio_port_config* sources, - unsigned int num_sinks, +static int adev_create_audio_patch(struct audio_hw_device* device, unsigned int num_sources, + const struct audio_port_config* sources, unsigned int num_sinks, const struct audio_port_config* sinks, audio_patch_handle_t* handle) { - if (device == nullptr || sources == nullptr || sinks == nullptr || - handle == nullptr || num_sources != 1 || num_sinks == 0 || - num_sinks > AUDIO_PATCH_PORTS_MAX) { + if (device == nullptr || sources == nullptr || sinks == nullptr || handle == nullptr || + num_sources != 1 || num_sinks == 0 || num_sinks > AUDIO_PATCH_PORTS_MAX) { return -EINVAL; } if (sources[0].type == AUDIO_PORT_TYPE_DEVICE) { @@ -143,16 +131,14 @@ static int adev_release_audio_patch(struct audio_hw_device* device, return 0; } -static int adev_get_audio_port_v7(struct audio_hw_device* device, - struct audio_port_v7* port) { +static int adev_get_audio_port_v7(struct audio_hw_device* device, struct audio_port_v7* port) { if (device == nullptr || port == nullptr) { return -EINVAL; } return -ENOSYS; } -static int adev_get_audio_port(struct audio_hw_device* device, - struct audio_port* port) { +static int adev_get_audio_port(struct audio_hw_device* device, struct audio_port* port) { if (device == nullptr || port == nullptr) { return -EINVAL; } @@ -167,14 +153,17 @@ static int adev_close(hw_device_t* device) { return 0; } -static int adev_open(const hw_module_t* module, const char* name, - hw_device_t** device) { +static int adev_open(const hw_module_t* module, const char* name, hw_device_t** device) { LOG(VERBOSE) << __func__ << ": name=[" << name << "]"; - if (strcmp(name, AUDIO_HARDWARE_INTERFACE) != 0) return -EINVAL; + if (strcmp(name, AUDIO_HARDWARE_INTERFACE) != 0) { + return -EINVAL; + } auto bluetooth_audio_device = new BluetoothAudioDevice{}; struct audio_hw_device* adev = &bluetooth_audio_device->audio_device_; - if (!adev) return -ENOMEM; + if (!adev) { + return -ENOMEM; + } adev->common.tag = HARDWARE_DEVICE_TAG; adev->common.version = AUDIO_DEVICE_API_VERSION_3_2; @@ -208,18 +197,18 @@ static int adev_open(const hw_module_t* module, const char* name, } static struct hw_module_methods_t hal_module_methods = { - .open = adev_open, + .open = adev_open, }; struct audio_module HAL_MODULE_INFO_SYM = { - .common = - { - .tag = HARDWARE_MODULE_TAG, - .module_api_version = AUDIO_MODULE_API_VERSION_0_1, - .hal_api_version = HARDWARE_HAL_API_VERSION, - .id = AUDIO_HARDWARE_MODULE_ID, - .name = "Bluetooth Audio HW HAL", - .author = "The Android Open Source Project", - .methods = &hal_module_methods, - }, + .common = + { + .tag = HARDWARE_MODULE_TAG, + .module_api_version = AUDIO_MODULE_API_VERSION_0_1, + .hal_api_version = HARDWARE_HAL_API_VERSION, + .id = AUDIO_HARDWARE_MODULE_ID, + .name = "Bluetooth Audio HW HAL", + .author = "The Android Open Source Project", + .methods = &hal_module_methods, + }, }; diff --git a/system/audio_bluetooth_hw/device_port_proxy.cc b/system/audio_bluetooth_hw/device_port_proxy.cc index cf88cfe8417..6c0ae4ea041 100644 --- a/system/audio_bluetooth_hw/device_port_proxy.cc +++ b/system/audio_bluetooth_hw/device_port_proxy.cc @@ -46,8 +46,8 @@ using ::aidl::android::media::audio::common::AudioSource; using ::aidl::android::media::audio::common::AudioUsage; using ::android::base::StringPrintf; -using ControlResultCallback = std::function; +using ControlResultCallback = + std::function; using SessionChangedCallback = std::function; namespace { @@ -84,8 +84,7 @@ audio_format_t BitsPerSampleToAudioFormat(uint8_t bits_per_sample, * LC3 encoder uses unpacked as input. This should be passed as parameter * from BT stack through AIDL, but it would require new interface version, * so sticking with this workaround for now. */ - if (session_type == - SessionType::A2DP_HARDWARE_OFFLOAD_ENCODING_DATAPATH || + if (session_type == SessionType::A2DP_HARDWARE_OFFLOAD_ENCODING_DATAPATH || session_type == SessionType::A2DP_SOFTWARE_ENCODING_DATAPATH) { return AUDIO_FORMAT_PCM_24_BIT_PACKED; } else { @@ -118,21 +117,26 @@ constexpr unsigned int kMaxWaitingTimeMs = 4500; } // namespace BluetoothAudioPortAidl::BluetoothAudioPortAidl() - : cookie_(::aidl::android::hardware::bluetooth::audio:: - kObserversCookieUndefined), + : cookie_(::aidl::android::hardware::bluetooth::audio::kObserversCookieUndefined), state_(BluetoothStreamState::DISABLED), session_type_(SessionType::UNKNOWN) {} BluetoothAudioPortAidlOut::~BluetoothAudioPortAidlOut() { - if (in_use()) TearDown(); + if (in_use()) { + TearDown(); + } } BluetoothAudioPortAidlIn::~BluetoothAudioPortAidlIn() { - if (in_use()) TearDown(); + if (in_use()) { + TearDown(); + } } bool BluetoothAudioPortAidl::SetUp(audio_devices_t devices) { - if (!init_session_type(devices)) return false; + if (!init_session_type(devices)) { + return false; + } state_ = BluetoothStreamState::STANDBY; @@ -163,17 +167,14 @@ bool BluetoothAudioPortAidl::SetUp(audio_devices_t devices) { }; // TODO: Add audio_config_changed_cb PortStatusCallbacks cbacks = { - .control_result_cb_ = control_result_cb, - .session_changed_cb_ = session_changed_cb, + .control_result_cb_ = control_result_cb, + .session_changed_cb_ = session_changed_cb, }; - cookie_ = BluetoothAudioSessionControl::RegisterControlResultCback( - session_type_, cbacks); + cookie_ = BluetoothAudioSessionControl::RegisterControlResultCback(session_type_, cbacks); LOG(INFO) << __func__ << ": session_type=" << toString(session_type_) << ", cookie=" << StringPrintf("%#hx", cookie_); - return ( - cookie_ != - ::aidl::android::hardware::bluetooth::audio::kObserversCookieUndefined); + return cookie_ != ::aidl::android::hardware::bluetooth::audio::kObserversCookieUndefined; } bool BluetoothAudioPortAidl::init_session_type(audio_devices_t device) { @@ -181,53 +182,43 @@ bool BluetoothAudioPortAidl::init_session_type(audio_devices_t device) { case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP: case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES: case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER: - LOG(VERBOSE) - << __func__ - << ": device=AUDIO_DEVICE_OUT_BLUETOOTH_A2DP (HEADPHONES/SPEAKER) (" - << StringPrintf("%#x", device) << ")"; + LOG(VERBOSE) << __func__ << ": device=AUDIO_DEVICE_OUT_BLUETOOTH_A2DP (HEADPHONES/SPEAKER) (" + << StringPrintf("%#x", device) << ")"; session_type_ = SessionType::A2DP_SOFTWARE_ENCODING_DATAPATH; break; case AUDIO_DEVICE_OUT_HEARING_AID: - LOG(VERBOSE) << __func__ - << ": device=AUDIO_DEVICE_OUT_HEARING_AID (MEDIA/VOICE) (" + LOG(VERBOSE) << __func__ << ": device=AUDIO_DEVICE_OUT_HEARING_AID (MEDIA/VOICE) (" << StringPrintf("%#x", device) << ")"; session_type_ = SessionType::HEARING_AID_SOFTWARE_ENCODING_DATAPATH; break; case AUDIO_DEVICE_OUT_BLE_HEADSET: - LOG(VERBOSE) << __func__ - << ": device=AUDIO_DEVICE_OUT_BLE_HEADSET (MEDIA/VOICE) (" + LOG(VERBOSE) << __func__ << ": device=AUDIO_DEVICE_OUT_BLE_HEADSET (MEDIA/VOICE) (" << StringPrintf("%#x", device) << ")"; session_type_ = SessionType::LE_AUDIO_SOFTWARE_ENCODING_DATAPATH; break; case AUDIO_DEVICE_OUT_BLE_SPEAKER: - LOG(VERBOSE) << __func__ - << ": device=AUDIO_DEVICE_OUT_BLE_SPEAKER (MEDIA) (" + LOG(VERBOSE) << __func__ << ": device=AUDIO_DEVICE_OUT_BLE_SPEAKER (MEDIA) (" << StringPrintf("%#x", device) << ")"; session_type_ = SessionType::LE_AUDIO_SOFTWARE_ENCODING_DATAPATH; break; case AUDIO_DEVICE_IN_BLE_HEADSET: - LOG(VERBOSE) << __func__ - << ": device=AUDIO_DEVICE_IN_BLE_HEADSET (VOICE) (" + LOG(VERBOSE) << __func__ << ": device=AUDIO_DEVICE_IN_BLE_HEADSET (VOICE) (" << StringPrintf("%#x", device) << ")"; session_type_ = SessionType::LE_AUDIO_SOFTWARE_DECODING_DATAPATH; break; case AUDIO_DEVICE_OUT_BLE_BROADCAST: - LOG(VERBOSE) << __func__ - << ": device=AUDIO_DEVICE_OUT_BLE_BROADCAST (MEDIA) (" + LOG(VERBOSE) << __func__ << ": device=AUDIO_DEVICE_OUT_BLE_BROADCAST (MEDIA) (" << StringPrintf("%#x", device) << ")"; - session_type_ = - SessionType::LE_AUDIO_BROADCAST_SOFTWARE_ENCODING_DATAPATH; + session_type_ = SessionType::LE_AUDIO_BROADCAST_SOFTWARE_ENCODING_DATAPATH; break; default: - LOG(ERROR) << __func__ - << ": unknown device=" << StringPrintf("%#x", device); + LOG(ERROR) << __func__ << ": unknown device=" << StringPrintf("%#x", device); return false; } if (!BluetoothAudioSessionControl::IsSessionReady(session_type_)) { LOG(ERROR) << __func__ << ": device=" << StringPrintf("%#x", device) - << ", session_type=" << toString(session_type_) - << " is not ready"; + << ", session_type=" << toString(session_type_) << " is not ready"; return false; } return true; @@ -236,21 +227,17 @@ bool BluetoothAudioPortAidl::init_session_type(audio_devices_t device) { void BluetoothAudioPortAidl::TearDown() { if (!in_use()) { LOG(ERROR) << __func__ << ": session_type=" << toString(session_type_) - << ", cookie=" << StringPrintf("%#hx", cookie_) - << " unknown monitor"; + << ", cookie=" << StringPrintf("%#hx", cookie_) << " unknown monitor"; return; } LOG(INFO) << __func__ << ": session_type=" << toString(session_type_) << ", cookie=" << StringPrintf("%#hx", cookie_); - BluetoothAudioSessionControl::UnregisterControlResultCback(session_type_, - cookie_); - cookie_ = - ::aidl::android::hardware::bluetooth::audio::kObserversCookieUndefined; + BluetoothAudioSessionControl::UnregisterControlResultCback(session_type_, cookie_); + cookie_ = ::aidl::android::hardware::bluetooth::audio::kObserversCookieUndefined; } -void BluetoothAudioPortAidl::ControlResultHandler( - const BluetoothAudioStatus& status) { +void BluetoothAudioPortAidl::ControlResultHandler(const BluetoothAudioStatus& status) { if (!in_use()) { LOG(ERROR) << __func__ << ": BluetoothAudioPortAidlis not in use"; return; @@ -258,8 +245,7 @@ void BluetoothAudioPortAidl::ControlResultHandler( std::unique_lock port_lock(cv_mutex_); BluetoothStreamState previous_state = state_; LOG(INFO) << "control_result_cb: session_type=" << toString(session_type_) - << ", cookie=" << StringPrintf("%#hx", cookie_) - << ", previous_state=" << previous_state + << ", cookie=" << StringPrintf("%#hx", cookie_) << ", previous_state=" << previous_state << ", status=" << toString(status); switch (previous_state) { @@ -328,31 +314,26 @@ void BluetoothAudioPortAidl::SessionChangedHandler() { } bool BluetoothAudioPortAidl::in_use() const { - return ( - cookie_ != - ::aidl::android::hardware::bluetooth::audio::kObserversCookieUndefined); + return cookie_ != ::aidl::android::hardware::bluetooth::audio::kObserversCookieUndefined; } -bool BluetoothAudioPortAidl::GetPreferredDataIntervalUs( - size_t* interval_us) const { +bool BluetoothAudioPortAidl::GetPreferredDataIntervalUs(size_t* interval_us) const { if (!in_use()) { return false; } const AudioConfiguration& hal_audio_cfg = - BluetoothAudioSessionControl::GetAudioConfig(session_type_); + BluetoothAudioSessionControl::GetAudioConfig(session_type_); if (hal_audio_cfg.getTag() != AudioConfiguration::pcmConfig) { return false; } - const PcmConfiguration& pcm_cfg = - hal_audio_cfg.get(); + const PcmConfiguration& pcm_cfg = hal_audio_cfg.get(); *interval_us = pcm_cfg.dataIntervalUs; return true; } -bool BluetoothAudioPortAidlOut::LoadAudioConfig( - audio_config_t* audio_cfg) const { +bool BluetoothAudioPortAidlOut::LoadAudioConfig(audio_config_t* audio_cfg) const { if (!in_use()) { LOG(ERROR) << __func__ << ": BluetoothAudioPortAidlOut is not in use"; audio_cfg->sample_rate = kBluetoothDefaultSampleRate; @@ -362,34 +343,29 @@ bool BluetoothAudioPortAidlOut::LoadAudioConfig( } const AudioConfiguration& hal_audio_cfg = - BluetoothAudioSessionControl::GetAudioConfig(session_type_); + BluetoothAudioSessionControl::GetAudioConfig(session_type_); if (hal_audio_cfg.getTag() != AudioConfiguration::pcmConfig) { audio_cfg->sample_rate = kBluetoothDefaultSampleRate; audio_cfg->channel_mask = kBluetoothDefaultOutputChannelModeMask; audio_cfg->format = kBluetoothDefaultAudioFormatBitsPerSample; return false; } - const PcmConfiguration& pcm_cfg = - hal_audio_cfg.get(); + const PcmConfiguration& pcm_cfg = hal_audio_cfg.get(); LOG(VERBOSE) << __func__ << ": session_type=" << toString(session_type_) - << ", cookie=" << StringPrintf("%#hx", cookie_) - << ", state=" << state_ << ", PcmConfig=[" << pcm_cfg.toString() - << "]"; + << ", cookie=" << StringPrintf("%#hx", cookie_) << ", state=" << state_ + << ", PcmConfig=[" << pcm_cfg.toString() << "]"; if (pcm_cfg.channelMode == ChannelMode::UNKNOWN) { return false; } audio_cfg->sample_rate = pcm_cfg.sampleRateHz; audio_cfg->channel_mask = - (is_stereo_to_mono_ - ? AUDIO_CHANNEL_OUT_STEREO - : OutputChannelModeToAudioFormat(pcm_cfg.channelMode)); - audio_cfg->format = - BitsPerSampleToAudioFormat(pcm_cfg.bitsPerSample, session_type_); + (is_stereo_to_mono_ ? AUDIO_CHANNEL_OUT_STEREO + : OutputChannelModeToAudioFormat(pcm_cfg.channelMode)); + audio_cfg->format = BitsPerSampleToAudioFormat(pcm_cfg.bitsPerSample, session_type_); return true; } -bool BluetoothAudioPortAidlIn::LoadAudioConfig( - audio_config_t* audio_cfg) const { +bool BluetoothAudioPortAidlIn::LoadAudioConfig(audio_config_t* audio_cfg) const { if (!in_use()) { LOG(ERROR) << __func__ << ": BluetoothAudioPortAidlIn is not in use"; audio_cfg->sample_rate = kBluetoothDefaultSampleRate; @@ -399,27 +375,24 @@ bool BluetoothAudioPortAidlIn::LoadAudioConfig( } const AudioConfiguration& hal_audio_cfg = - BluetoothAudioSessionControl::GetAudioConfig(session_type_); + BluetoothAudioSessionControl::GetAudioConfig(session_type_); if (hal_audio_cfg.getTag() != AudioConfiguration::pcmConfig) { audio_cfg->sample_rate = kBluetoothDefaultSampleRate; audio_cfg->channel_mask = kBluetoothDefaultInputChannelModeMask; audio_cfg->format = kBluetoothDefaultAudioFormatBitsPerSample; return false; } - const PcmConfiguration& pcm_cfg = - hal_audio_cfg.get(); + const PcmConfiguration& pcm_cfg = hal_audio_cfg.get(); LOG(VERBOSE) << __func__ << ": session_type=" << toString(session_type_) - << ", cookie=" << StringPrintf("%#hx", cookie_) - << ", state=" << state_ << ", PcmConfig=[" << pcm_cfg.toString() - << "]"; + << ", cookie=" << StringPrintf("%#hx", cookie_) << ", state=" << state_ + << ", PcmConfig=[" << pcm_cfg.toString() << "]"; if (pcm_cfg.channelMode == ChannelMode::UNKNOWN) { return false; } audio_cfg->sample_rate = pcm_cfg.sampleRateHz; audio_cfg->channel_mask = InputChannelModeToAudioFormat(pcm_cfg.channelMode); - audio_cfg->format = - BitsPerSampleToAudioFormat(pcm_cfg.bitsPerSample, session_type_); + audio_cfg->format = BitsPerSampleToAudioFormat(pcm_cfg.bitsPerSample, session_type_); return true; } @@ -429,26 +402,23 @@ bool BluetoothAudioPortAidl::CondwaitState(BluetoothStreamState state) { switch (state) { case BluetoothStreamState::STARTING: LOG(VERBOSE) << __func__ << ": session_type=" << toString(session_type_) - << ", cookie=" << StringPrintf("%#hx", cookie_) - << " waiting for STARTED"; + << ", cookie=" << StringPrintf("%#hx", cookie_) << " waiting for STARTED"; retval = internal_cv_.wait_for( - port_lock, std::chrono::milliseconds(kMaxWaitingTimeMs), - [this] { return this->state_ != BluetoothStreamState::STARTING; }); + port_lock, std::chrono::milliseconds(kMaxWaitingTimeMs), + [this] { return this->state_ != BluetoothStreamState::STARTING; }); retval = retval && state_ == BluetoothStreamState::STARTED; break; case BluetoothStreamState::SUSPENDING: LOG(VERBOSE) << __func__ << ": session_type=" << toString(session_type_) - << ", cookie=" << StringPrintf("%#hx", cookie_) - << " waiting for SUSPENDED"; + << ", cookie=" << StringPrintf("%#hx", cookie_) << " waiting for SUSPENDED"; retval = internal_cv_.wait_for( - port_lock, std::chrono::milliseconds(kMaxWaitingTimeMs), - [this] { return this->state_ != BluetoothStreamState::SUSPENDING; }); + port_lock, std::chrono::milliseconds(kMaxWaitingTimeMs), + [this] { return this->state_ != BluetoothStreamState::SUSPENDING; }); retval = retval && state_ == BluetoothStreamState::STANDBY; break; default: LOG(WARNING) << __func__ << ": session_type=" << toString(session_type_) - << ", cookie=" << StringPrintf("%#hx", cookie_) - << " waiting for KNOWN"; + << ", cookie=" << StringPrintf("%#hx", cookie_) << " waiting for KNOWN"; return false; } @@ -462,10 +432,8 @@ bool BluetoothAudioPortAidl::Start() { } LOG(INFO) << __func__ << ": session_type=" << toString(session_type_) - << ", cookie=" << StringPrintf("%#hx", cookie_) - << ", state=" << state_ - << ", mono=" << (is_stereo_to_mono_ ? "true" : "false") - << " request"; + << ", cookie=" << StringPrintf("%#hx", cookie_) << ", state=" << state_ + << ", mono=" << (is_stereo_to_mono_ ? "true" : "false") << " request"; bool retval = false; if (state_ == BluetoothStreamState::STANDBY) { state_ = BluetoothStreamState::STARTING; @@ -473,21 +441,19 @@ bool BluetoothAudioPortAidl::Start() { retval = CondwaitState(BluetoothStreamState::STARTING); } else { LOG(ERROR) << __func__ << ": session_type=" << toString(session_type_) - << ", cookie=" << StringPrintf("%#hx", cookie_) - << ", state=" << state_ << " Hal fails"; + << ", cookie=" << StringPrintf("%#hx", cookie_) << ", state=" << state_ + << " Hal fails"; } } if (retval) { LOG(INFO) << __func__ << ": session_type=" << toString(session_type_) - << ", cookie=" << StringPrintf("%#hx", cookie_) - << ", state=" << state_ - << ", mono=" << (is_stereo_to_mono_ ? "true" : "false") - << " done"; + << ", cookie=" << StringPrintf("%#hx", cookie_) << ", state=" << state_ + << ", mono=" << (is_stereo_to_mono_ ? "true" : "false") << " done"; } else { LOG(ERROR) << __func__ << ": session_type=" << toString(session_type_) - << ", cookie=" << StringPrintf("%#hx", cookie_) - << ", state=" << state_ << " failure"; + << ", cookie=" << StringPrintf("%#hx", cookie_) << ", state=" << state_ + << " failure"; } return retval; // false if any failure like timeout @@ -500,8 +466,7 @@ bool BluetoothAudioPortAidl::Suspend() { } LOG(INFO) << __func__ << ": session_type=" << toString(session_type_) - << ", cookie=" << StringPrintf("%#hx", cookie_) - << ", state=" << state_ << " request"; + << ", cookie=" << StringPrintf("%#hx", cookie_) << ", state=" << state_ << " request"; bool retval = false; if (state_ == BluetoothStreamState::STARTED) { state_ = BluetoothStreamState::SUSPENDING; @@ -509,19 +474,18 @@ bool BluetoothAudioPortAidl::Suspend() { retval = CondwaitState(BluetoothStreamState::SUSPENDING); } else { LOG(ERROR) << __func__ << ": session_type=" << toString(session_type_) - << ", cookie=" << StringPrintf("%#hx", cookie_) - << ", state=" << state_ << " Hal fails"; + << ", cookie=" << StringPrintf("%#hx", cookie_) << ", state=" << state_ + << " Hal fails"; } } if (retval) { LOG(INFO) << __func__ << ": session_type=" << toString(session_type_) - << ", cookie=" << StringPrintf("%#hx", cookie_) - << ", state=" << state_ << " done"; + << ", cookie=" << StringPrintf("%#hx", cookie_) << ", state=" << state_ << " done"; } else { LOG(ERROR) << __func__ << ": session_type=" << toString(session_type_) - << ", cookie=" << StringPrintf("%#hx", cookie_) - << ", state=" << state_ << " failure"; + << ", cookie=" << StringPrintf("%#hx", cookie_) << ", state=" << state_ + << " failure"; } return retval; // false if any failure like timeout @@ -533,125 +497,120 @@ void BluetoothAudioPortAidl::Stop() { return; } LOG(INFO) << __func__ << ": session_type=" << toString(session_type_) - << ", cookie=" << StringPrintf("%#hx", cookie_) - << ", state=" << state_ << " request"; + << ", cookie=" << StringPrintf("%#hx", cookie_) << ", state=" << state_ << " request"; state_ = BluetoothStreamState::DISABLED; BluetoothAudioSessionControl::StopStream(session_type_); LOG(INFO) << __func__ << ": session_type=" << toString(session_type_) - << ", cookie=" << StringPrintf("%#hx", cookie_) - << ", state=" << state_ << " done"; + << ", cookie=" << StringPrintf("%#hx", cookie_) << ", state=" << state_ << " done"; } -size_t BluetoothAudioPortAidlOut::WriteData(const void* buffer, - size_t bytes) const { - if (!in_use()) return 0; +size_t BluetoothAudioPortAidlOut::WriteData(const void* buffer, size_t bytes) const { + if (!in_use()) { + return 0; + } if (!is_stereo_to_mono_) { - return BluetoothAudioSessionControl::OutWritePcmData(session_type_, buffer, - bytes); + return BluetoothAudioSessionControl::OutWritePcmData(session_type_, buffer, bytes); } // WAR to mix the stereo into Mono (16 bits per sample) const size_t write_frames = bytes >> 2; - if (write_frames == 0) return 0; + if (write_frames == 0) { + return 0; + } auto src = static_cast(buffer); std::unique_ptr dst{new int16_t[write_frames]}; downmix_to_mono_i16_from_stereo_i16(dst.get(), src, write_frames); // a frame is 16 bits, and the size of a mono frame is equal to half a stereo. - return BluetoothAudioSessionControl::OutWritePcmData(session_type_, dst.get(), - write_frames * 2) * + return BluetoothAudioSessionControl::OutWritePcmData(session_type_, dst.get(), write_frames * 2) * 2; } size_t BluetoothAudioPortAidlIn::ReadData(void* buffer, size_t bytes) const { - if (!in_use()) return 0; - return BluetoothAudioSessionControl::InReadPcmData(session_type_, buffer, - bytes); + if (!in_use()) { + return 0; + } + return BluetoothAudioSessionControl::InReadPcmData(session_type_, buffer, bytes); } -bool BluetoothAudioPortAidl::GetPresentationPosition( - uint64_t* delay_ns, uint64_t* bytes, timespec* timestamp) const { +bool BluetoothAudioPortAidl::GetPresentationPosition(uint64_t* delay_ns, uint64_t* bytes, + timespec* timestamp) const { if (!in_use()) { LOG(ERROR) << __func__ << ": BluetoothAudioPortAidl is not in use"; return false; } PresentationPosition presentation_position; - bool retval = BluetoothAudioSessionControl::GetPresentationPosition( - session_type_, presentation_position); + bool retval = BluetoothAudioSessionControl::GetPresentationPosition(session_type_, + presentation_position); *delay_ns = presentation_position.remoteDeviceAudioDelayNanos; *bytes = presentation_position.transmittedOctets; - *timestamp = {.tv_sec = static_cast<__kernel_old_time_t>( - presentation_position.transmittedOctetsTimestamp.tvSec), - .tv_nsec = static_cast( - presentation_position.transmittedOctetsTimestamp.tvNSec)}; - LOG(VERBOSE) << __func__ << ": session_type=" - << StringPrintf("%#x", static_cast(session_type_)) - << ", cookie=" << StringPrintf("%#hx", cookie_) - << ", state=" << state_ << ", delay=" << *delay_ns - << "ns, data=" << *bytes + *timestamp = { + .tv_sec = static_cast<__kernel_old_time_t>( + presentation_position.transmittedOctetsTimestamp.tvSec), + .tv_nsec = static_cast(presentation_position.transmittedOctetsTimestamp.tvNSec)}; + LOG(VERBOSE) << __func__ + << ": session_type=" << StringPrintf("%#x", static_cast(session_type_)) + << ", cookie=" << StringPrintf("%#hx", cookie_) << ", state=" << state_ + << ", delay=" << *delay_ns << "ns, data=" << *bytes << " bytes, timestamp=" << timestamp->tv_sec << "." << StringPrintf("%09ld", timestamp->tv_nsec) << "s"; return retval; } -void BluetoothAudioPortAidl::UpdateSourceMetadata( - const source_metadata_v7* source_metadata) const { +void BluetoothAudioPortAidl::UpdateSourceMetadata(const source_metadata_v7* source_metadata) const { if (!in_use()) { LOG(ERROR) << __func__ << ": BluetoothAudioPortAidl is not in use"; return; } LOG(DEBUG) << __func__ << ": session_type=" << toString(session_type_) - << ", cookie=" << StringPrintf("%#hx", cookie_) - << ", state=" << state_ << ", " << source_metadata->track_count - << " track(s)"; + << ", cookie=" << StringPrintf("%#hx", cookie_) << ", state=" << state_ << ", " + << source_metadata->track_count << " track(s)"; ssize_t track_count = source_metadata->track_count; - if (track_count == 0) return; + if (track_count == 0) { + return; + } SourceMetadata hal_source_metadata; hal_source_metadata.tracks.resize(track_count); for (int i = 0; i < track_count; i++) { hal_source_metadata.tracks[i].usage = - static_cast(source_metadata->tracks[i].base.usage); - hal_source_metadata.tracks[i].contentType = static_cast( - source_metadata->tracks[i].base.content_type); + static_cast(source_metadata->tracks[i].base.usage); + hal_source_metadata.tracks[i].contentType = + static_cast(source_metadata->tracks[i].base.content_type); hal_source_metadata.tracks[i].tags = - std::move(CovertAudioTagFromV7(source_metadata->tracks[i].tags)); + std::move(CovertAudioTagFromV7(source_metadata->tracks[i].tags)); } - BluetoothAudioSessionControl::UpdateSourceMetadata(session_type_, - hal_source_metadata); + BluetoothAudioSessionControl::UpdateSourceMetadata(session_type_, hal_source_metadata); } -void BluetoothAudioPortAidl::UpdateSinkMetadata( - const sink_metadata_v7* sink_metadata) const { +void BluetoothAudioPortAidl::UpdateSinkMetadata(const sink_metadata_v7* sink_metadata) const { if (!in_use()) { LOG(ERROR) << __func__ << ": BluetoothAudioPortAidl is not in use"; return; } LOG(DEBUG) << __func__ << ": session_type=" << toString(session_type_) - << ", cookie=" << StringPrintf("%#hx", cookie_) - << ", state=" << state_ << ", " << sink_metadata->track_count - << " track(s)"; + << ", cookie=" << StringPrintf("%#hx", cookie_) << ", state=" << state_ << ", " + << sink_metadata->track_count << " track(s)"; ssize_t track_count = sink_metadata->track_count; - if (track_count == 0) return; + if (track_count == 0) { + return; + } SinkMetadata hal_sink_metadata; hal_sink_metadata.tracks.resize(track_count); for (int i = 0; i < track_count; i++) { hal_sink_metadata.tracks[i].source = - static_cast(sink_metadata->tracks[i].base.source); + static_cast(sink_metadata->tracks[i].base.source); hal_sink_metadata.tracks[i].gain = sink_metadata->tracks[i].base.gain; hal_sink_metadata.tracks[i].tags = - std::move(CovertAudioTagFromV7(sink_metadata->tracks[i].tags)); + std::move(CovertAudioTagFromV7(sink_metadata->tracks[i].tags)); } - BluetoothAudioSessionControl::UpdateSinkMetadata(session_type_, - hal_sink_metadata); + BluetoothAudioSessionControl::UpdateSinkMetadata(session_type_, hal_sink_metadata); } BluetoothStreamState BluetoothAudioPortAidl::GetState() const { return state_; } -void BluetoothAudioPortAidl::SetState(BluetoothStreamState state) { - state_ = state; -} +void BluetoothAudioPortAidl::SetState(BluetoothStreamState state) { state_ = state; } } // namespace aidl } // namespace audio diff --git a/system/audio_bluetooth_hw/device_port_proxy.h b/system/audio_bluetooth_hw/device_port_proxy.h index ff3deddffb7..1409d334844 100644 --- a/system/audio_bluetooth_hw/device_port_proxy.h +++ b/system/audio_bluetooth_hw/device_port_proxy.h @@ -39,8 +39,8 @@ namespace audio { * verbose logging, it is not locked, so the state may not be synchronized. ***/ class BluetoothAudioPort { - public: - BluetoothAudioPort(){}; +public: + BluetoothAudioPort() {} virtual ~BluetoothAudioPort() = default; /*** @@ -61,7 +61,7 @@ class BluetoothAudioPort { * channel mask and sample rate, it uses this function to fetch from the * Bluetooth stack ***/ - virtual bool LoadAudioConfig(audio_config_t*) const { return false; }; + virtual bool LoadAudioConfig(audio_config_t*) const { return false; } /*** * WAR to support Mono mode / 16 bits per sample @@ -79,7 +79,7 @@ class BluetoothAudioPort { /*** * Called by Audio framework / HAL to suspend the stream ***/ - virtual bool Suspend() { return false; }; + virtual bool Suspend() { return false; } /*** virtual bool Suspend() { return false; } @@ -91,16 +91,12 @@ class BluetoothAudioPort { * Called by the Audio framework / HAL to fetch information about audio frames * presented to an external sink, or frames presented fror an internal sink ***/ - virtual bool GetPresentationPosition(uint64_t*, uint64_t*, timespec*) const { - return false; - } + virtual bool GetPresentationPosition(uint64_t*, uint64_t*, timespec*) const { return false; } /*** * Return the current BluetoothStreamState ***/ - virtual BluetoothStreamState GetState() const { - return static_cast(0); - } + virtual BluetoothStreamState GetState() const { return static_cast(0); } /*** * Set the current BluetoothStreamState @@ -111,14 +107,10 @@ class BluetoothAudioPort { virtual bool IsLeAudio() const { return false; } - virtual bool GetPreferredDataIntervalUs(size_t* interval_us) const { - return false; - }; + virtual bool GetPreferredDataIntervalUs(size_t* interval_us) const { return false; } - virtual size_t WriteData(const void* buffer, size_t bytes) const { - return 0; - }; - virtual size_t ReadData(void* buffer, size_t bytes) const { return 0; }; + virtual size_t WriteData(const void* buffer, size_t bytes) const { return 0; } + virtual size_t ReadData(void* buffer, size_t bytes) const { return 0; } }; namespace aidl { @@ -127,7 +119,7 @@ using ::aidl::android::hardware::bluetooth::audio::BluetoothAudioStatus; using ::aidl::android::hardware::bluetooth::audio::SessionType; class BluetoothAudioPortAidl : public BluetoothAudioPort { - public: +public: BluetoothAudioPortAidl(); virtual ~BluetoothAudioPortAidl() = default; @@ -158,27 +150,21 @@ class BluetoothAudioPortAidl : public BluetoothAudioPort { bool IsA2dp() const override { return session_type_ == SessionType::A2DP_SOFTWARE_ENCODING_DATAPATH || - session_type_ == - SessionType::A2DP_HARDWARE_OFFLOAD_ENCODING_DATAPATH; + session_type_ == SessionType::A2DP_HARDWARE_OFFLOAD_ENCODING_DATAPATH; } bool IsLeAudio() const override { return session_type_ == SessionType::LE_AUDIO_SOFTWARE_ENCODING_DATAPATH || session_type_ == SessionType::LE_AUDIO_SOFTWARE_DECODING_DATAPATH || - session_type_ == - SessionType::LE_AUDIO_HARDWARE_OFFLOAD_ENCODING_DATAPATH || - session_type_ == - SessionType::LE_AUDIO_HARDWARE_OFFLOAD_DECODING_DATAPATH || - session_type_ == - SessionType::LE_AUDIO_BROADCAST_SOFTWARE_ENCODING_DATAPATH || - session_type_ == - SessionType:: - LE_AUDIO_BROADCAST_HARDWARE_OFFLOAD_ENCODING_DATAPATH; + session_type_ == SessionType::LE_AUDIO_HARDWARE_OFFLOAD_ENCODING_DATAPATH || + session_type_ == SessionType::LE_AUDIO_HARDWARE_OFFLOAD_DECODING_DATAPATH || + session_type_ == SessionType::LE_AUDIO_BROADCAST_SOFTWARE_ENCODING_DATAPATH || + session_type_ == SessionType::LE_AUDIO_BROADCAST_HARDWARE_OFFLOAD_ENCODING_DATAPATH; } bool GetPreferredDataIntervalUs(size_t* interval_us) const override; - protected: +protected: uint16_t cookie_; BluetoothStreamState state_; SessionType session_type_; @@ -186,7 +172,7 @@ class BluetoothAudioPortAidl : public BluetoothAudioPort { bool is_stereo_to_mono_ = false; virtual bool in_use() const; - private: +private: mutable std::mutex cv_mutex_; std::condition_variable internal_cv_; @@ -201,7 +187,7 @@ class BluetoothAudioPortAidl : public BluetoothAudioPort { }; class BluetoothAudioPortAidlOut : public BluetoothAudioPortAidl { - public: +public: ~BluetoothAudioPortAidlOut(); // The audio data path to the Bluetooth stack (Software encoding) @@ -210,7 +196,7 @@ class BluetoothAudioPortAidlOut : public BluetoothAudioPortAidl { }; class BluetoothAudioPortAidlIn : public BluetoothAudioPortAidl { - public: +public: ~BluetoothAudioPortAidlIn(); // The audio data path from the Bluetooth stack (Software decoded) diff --git a/system/audio_bluetooth_hw/device_port_proxy_hidl.cc b/system/audio_bluetooth_hw/device_port_proxy_hidl.cc index eeffdaecaf6..20bcb43bb98 100644 --- a/system/audio_bluetooth_hw/device_port_proxy_hidl.cc +++ b/system/audio_bluetooth_hw/device_port_proxy_hidl.cc @@ -40,10 +40,9 @@ using ::android::hardware::bluetooth::audio::V2_0::ChannelMode; using ::android::hardware::bluetooth::audio::V2_0::PcmParameters; using SampleRate = ::android::hardware::bluetooth::audio::V2_0::SampleRate; using SampleRate_2_1 = ::android::hardware::bluetooth::audio::V2_1::SampleRate; -using BluetoothAudioStatusHidl = - ::android::hardware::bluetooth::audio::V2_0::Status; -using ControlResultCallback = std::function; +using BluetoothAudioStatusHidl = ::android::hardware::bluetooth::audio::V2_0::Status; +using ControlResultCallback = std::function; using SessionChangedCallback = std::function; namespace { @@ -120,21 +119,26 @@ BluetoothAudioPortHidl::BluetoothAudioPortHidl() state_(BluetoothStreamState::DISABLED) {} BluetoothAudioPortHidlOut::~BluetoothAudioPortHidlOut() { - if (BluetoothAudioPortHidl::in_use()) BluetoothAudioPortHidl::TearDown(); + if (BluetoothAudioPortHidl::in_use()) { + BluetoothAudioPortHidl::TearDown(); + } } BluetoothAudioPortHidlIn::~BluetoothAudioPortHidlIn() { - if (BluetoothAudioPortHidl::in_use()) BluetoothAudioPortHidl::TearDown(); + if (BluetoothAudioPortHidl::in_use()) { + BluetoothAudioPortHidl::TearDown(); + } } bool BluetoothAudioPortHidl::SetUp(audio_devices_t devices) { - if (!init_session_type(devices)) return false; + if (!init_session_type(devices)) { + return false; + } state_ = BluetoothStreamState::STANDBY; - auto control_result_cb = [port = this]( - uint16_t cookie, bool start_resp, - const BluetoothAudioStatusHidl& status) { + auto control_result_cb = [port = this](uint16_t cookie, bool start_resp, + const BluetoothAudioStatusHidl& status) { if (!port->in_use()) { LOG(ERROR) << "control_result_cb: BluetoothAudioPort is not in use"; return; @@ -159,14 +163,13 @@ bool BluetoothAudioPortHidl::SetUp(audio_devices_t devices) { port->SessionChangedHandler(); }; ::android::bluetooth::audio::PortStatusCallbacks cbacks = { - .control_result_cb_ = control_result_cb, - .session_changed_cb_ = session_changed_cb}; - cookie_ = BluetoothAudioSessionControl_2_1::RegisterControlResultCback( - session_type_hidl_, cbacks); + .control_result_cb_ = control_result_cb, .session_changed_cb_ = session_changed_cb}; + cookie_ = + BluetoothAudioSessionControl_2_1::RegisterControlResultCback(session_type_hidl_, cbacks); LOG(INFO) << __func__ << ": session_type=" << toString(session_type_hidl_) << ", cookie=" << StringPrintf("%#hx", cookie_); - return (cookie_ != android::bluetooth::audio::kObserversCookieUndefined); + return cookie_ != android::bluetooth::audio::kObserversCookieUndefined; } bool BluetoothAudioPortHidl::init_session_type(audio_devices_t device) { @@ -174,47 +177,38 @@ bool BluetoothAudioPortHidl::init_session_type(audio_devices_t device) { case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP: case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES: case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER: - LOG(VERBOSE) - << __func__ - << ": device=AUDIO_DEVICE_OUT_BLUETOOTH_A2DP (HEADPHONES/SPEAKER) (" - << StringPrintf("%#x", device) << ")"; + LOG(VERBOSE) << __func__ << ": device=AUDIO_DEVICE_OUT_BLUETOOTH_A2DP (HEADPHONES/SPEAKER) (" + << StringPrintf("%#x", device) << ")"; session_type_hidl_ = SessionType_2_1::A2DP_SOFTWARE_ENCODING_DATAPATH; break; case AUDIO_DEVICE_OUT_HEARING_AID: - LOG(VERBOSE) << __func__ - << ": device=AUDIO_DEVICE_OUT_HEARING_AID (MEDIA/VOICE) (" + LOG(VERBOSE) << __func__ << ": device=AUDIO_DEVICE_OUT_HEARING_AID (MEDIA/VOICE) (" << StringPrintf("%#x", device) << ")"; - session_type_hidl_ = - SessionType_2_1::HEARING_AID_SOFTWARE_ENCODING_DATAPATH; + session_type_hidl_ = SessionType_2_1::HEARING_AID_SOFTWARE_ENCODING_DATAPATH; break; case AUDIO_DEVICE_OUT_BLE_HEADSET: - LOG(VERBOSE) << __func__ - << ": device=AUDIO_DEVICE_OUT_BLE_HEADSET (MEDIA/VOICE) (" + LOG(VERBOSE) << __func__ << ": device=AUDIO_DEVICE_OUT_BLE_HEADSET (MEDIA/VOICE) (" << StringPrintf("%#x", device) << ")"; session_type_hidl_ = SessionType_2_1::LE_AUDIO_SOFTWARE_ENCODING_DATAPATH; break; case AUDIO_DEVICE_OUT_BLE_SPEAKER: - LOG(VERBOSE) << __func__ - << ": device=AUDIO_DEVICE_OUT_BLE_SPEAKER (MEDIA) (" + LOG(VERBOSE) << __func__ << ": device=AUDIO_DEVICE_OUT_BLE_SPEAKER (MEDIA) (" << StringPrintf("%#x", device) << ")"; session_type_hidl_ = SessionType_2_1::LE_AUDIO_SOFTWARE_ENCODING_DATAPATH; break; case AUDIO_DEVICE_IN_BLE_HEADSET: - LOG(VERBOSE) << __func__ - << ": device=AUDIO_DEVICE_IN_BLE_HEADSET (VOICE) (" + LOG(VERBOSE) << __func__ << ": device=AUDIO_DEVICE_IN_BLE_HEADSET (VOICE) (" << StringPrintf("%#x", device) << ")"; session_type_hidl_ = SessionType_2_1::LE_AUDIO_SOFTWARE_DECODED_DATAPATH; break; default: - LOG(ERROR) << __func__ - << ": unknown device=" << StringPrintf("%#x", device); + LOG(ERROR) << __func__ << ": unknown device=" << StringPrintf("%#x", device); return false; } if (!BluetoothAudioSessionControl_2_1::IsSessionReady(session_type_hidl_)) { LOG(ERROR) << __func__ << ": device=" << StringPrintf("%#x", device) - << ", session_type=" << toString(session_type_hidl_) - << " is not ready"; + << ", session_type=" << toString(session_type_hidl_) << " is not ready"; return false; } return true; @@ -223,30 +217,25 @@ bool BluetoothAudioPortHidl::init_session_type(audio_devices_t device) { void BluetoothAudioPortHidl::TearDown() { if (!in_use()) { LOG(ERROR) << __func__ << ": session_type=" << toString(session_type_hidl_) - << ", cookie=" << StringPrintf("%#hx", cookie_) - << " unknown monitor"; + << ", cookie=" << StringPrintf("%#hx", cookie_) << " unknown monitor"; return; } LOG(INFO) << __func__ << ": session_type=" << toString(session_type_hidl_) << ", cookie=" << StringPrintf("%#hx", cookie_); - BluetoothAudioSessionControl_2_1::UnregisterControlResultCback( - session_type_hidl_, cookie_); + BluetoothAudioSessionControl_2_1::UnregisterControlResultCback(session_type_hidl_, cookie_); cookie_ = android::bluetooth::audio::kObserversCookieUndefined; } -void BluetoothAudioPortHidl::ControlResultHandler( - const BluetoothAudioStatusHidl& status) { +void BluetoothAudioPortHidl::ControlResultHandler(const BluetoothAudioStatusHidl& status) { if (!in_use()) { LOG(ERROR) << __func__ << ": BluetoothAudioPortis not in use"; return; } std::unique_lock port_lock(cv_mutex_); BluetoothStreamState previous_state = state_; - LOG(INFO) << "control_result_cb: session_type=" - << toString(session_type_hidl_) - << ", cookie=" << StringPrintf("%#hx", cookie_) - << ", previous_state=" << previous_state + LOG(INFO) << "control_result_cb: session_type=" << toString(session_type_hidl_) + << ", cookie=" << StringPrintf("%#hx", cookie_) << ", previous_state=" << previous_state << ", status=" << toString(status); switch (previous_state) { @@ -257,8 +246,7 @@ void BluetoothAudioPortHidl::ControlResultHandler( } else { // Set to standby since the stack may be busy switching between outputs LOG(WARNING) << "control_result_cb: status=" << toString(status) - << " failure for session_type=" - << toString(session_type_hidl_) + << " failure for session_type=" << toString(session_type_hidl_) << ", cookie=" << StringPrintf("%#hx", cookie_) << ", previous_state=" << previous_state; } @@ -269,8 +257,7 @@ void BluetoothAudioPortHidl::ControlResultHandler( } else { // Set to standby since the stack may be busy switching between outputs LOG(WARNING) << "control_result_cb: status=" << toString(status) - << " failure for session_type=" - << toString(session_type_hidl_) + << " failure for session_type=" << toString(session_type_hidl_) << ", cookie=" << StringPrintf("%#hx", cookie_) << ", previous_state=" << previous_state; state_ = BluetoothStreamState::STANDBY; @@ -283,8 +270,7 @@ void BluetoothAudioPortHidl::ControlResultHandler( // It will be failed if the headset is disconnecting, and set to disable // to wait for re-init again LOG(WARNING) << "control_result_cb: status=" << toString(status) - << " failure for session_type=" - << toString(session_type_hidl_) + << " failure for session_type=" << toString(session_type_hidl_) << ", cookie=" << StringPrintf("%#hx", cookie_) << ", previous_state=" << previous_state; state_ = BluetoothStreamState::DISABLED; @@ -308,8 +294,7 @@ void BluetoothAudioPortHidl::SessionChangedHandler() { } std::unique_lock port_lock(cv_mutex_); BluetoothStreamState previous_state = state_; - LOG(INFO) << "session_changed_cb: session_type=" - << toString(session_type_hidl_) + LOG(INFO) << "session_changed_cb: session_type=" << toString(session_type_hidl_) << ", cookie=" << StringPrintf("%#hx", cookie_) << ", previous_state=" << previous_state; state_ = BluetoothStreamState::DISABLED; @@ -318,26 +303,24 @@ void BluetoothAudioPortHidl::SessionChangedHandler() { } bool BluetoothAudioPortHidl::in_use() const { - return (cookie_ != android::bluetooth::audio::kObserversCookieUndefined); + return cookie_ != android::bluetooth::audio::kObserversCookieUndefined; } -bool BluetoothAudioPortHidl::GetPreferredDataIntervalUs( - size_t* interval_us) const { +bool BluetoothAudioPortHidl::GetPreferredDataIntervalUs(size_t* interval_us) const { if (!in_use()) { return false; } - const ::android::hardware::bluetooth::audio::V2_1::AudioConfiguration& - hal_audio_cfg = + const ::android::hardware::bluetooth::audio::V2_1::AudioConfiguration& hal_audio_cfg = BluetoothAudioSessionControl_2_1::GetAudioConfig(session_type_hidl_); if (hal_audio_cfg.getDiscriminator() != - ::android::hardware::bluetooth::audio::V2_1::AudioConfiguration:: - hidl_discriminator::pcmConfig) { + ::android::hardware::bluetooth::audio::V2_1::AudioConfiguration::hidl_discriminator:: + pcmConfig) { return false; } const ::android::hardware::bluetooth::audio::V2_1::PcmParameters& pcm_cfg = - hal_audio_cfg.pcmConfig(); + hal_audio_cfg.pcmConfig(); *interval_us = pcm_cfg.dataIntervalUs; return true; } @@ -347,30 +330,24 @@ bool BluetoothAudioPortHidl::CondwaitState(BluetoothStreamState state) { std::unique_lock port_lock(cv_mutex_); switch (state) { case BluetoothStreamState::STARTING: - LOG(VERBOSE) << __func__ - << ": session_type=" << toString(session_type_hidl_) - << ", cookie=" << StringPrintf("%#hx", cookie_) - << " waiting for STARTED"; + LOG(VERBOSE) << __func__ << ": session_type=" << toString(session_type_hidl_) + << ", cookie=" << StringPrintf("%#hx", cookie_) << " waiting for STARTED"; retval = internal_cv_.wait_for( - port_lock, std::chrono::milliseconds(kMaxWaitingTimeMs), - [this] { return this->state_ != BluetoothStreamState::STARTING; }); + port_lock, std::chrono::milliseconds(kMaxWaitingTimeMs), + [this] { return this->state_ != BluetoothStreamState::STARTING; }); retval = retval && state_ == BluetoothStreamState::STARTED; break; case BluetoothStreamState::SUSPENDING: - LOG(VERBOSE) << __func__ - << ": session_type=" << toString(session_type_hidl_) - << ", cookie=" << StringPrintf("%#hx", cookie_) - << " waiting for SUSPENDED"; + LOG(VERBOSE) << __func__ << ": session_type=" << toString(session_type_hidl_) + << ", cookie=" << StringPrintf("%#hx", cookie_) << " waiting for SUSPENDED"; retval = internal_cv_.wait_for( - port_lock, std::chrono::milliseconds(kMaxWaitingTimeMs), - [this] { return this->state_ != BluetoothStreamState::SUSPENDING; }); + port_lock, std::chrono::milliseconds(kMaxWaitingTimeMs), + [this] { return this->state_ != BluetoothStreamState::SUSPENDING; }); retval = retval && state_ == BluetoothStreamState::STANDBY; break; default: - LOG(WARNING) << __func__ - << ": session_type=" << toString(session_type_hidl_) - << ", cookie=" << StringPrintf("%#hx", cookie_) - << " waiting for KNOWN"; + LOG(WARNING) << __func__ << ": session_type=" << toString(session_type_hidl_) + << ", cookie=" << StringPrintf("%#hx", cookie_) << " waiting for KNOWN"; return false; } @@ -384,33 +361,28 @@ bool BluetoothAudioPortHidl::Start() { } LOG(INFO) << __func__ << ": session_type=" << toString(session_type_hidl_) - << ", cookie=" << StringPrintf("%#hx", cookie_) - << ", state=" << state_ - << ", mono=" << (is_stereo_to_mono_ ? "true" : "false") - << " request"; + << ", cookie=" << StringPrintf("%#hx", cookie_) << ", state=" << state_ + << ", mono=" << (is_stereo_to_mono_ ? "true" : "false") << " request"; bool retval = false; if (state_ == BluetoothStreamState::STANDBY) { state_ = BluetoothStreamState::STARTING; if (BluetoothAudioSessionControl_2_1::StartStream(session_type_hidl_)) { retval = CondwaitState(BluetoothStreamState::STARTING); } else { - LOG(ERROR) << __func__ - << ": session_type=" << toString(session_type_hidl_) - << ", cookie=" << StringPrintf("%#hx", cookie_) - << ", state=" << state_ << " Hal fails"; + LOG(ERROR) << __func__ << ": session_type=" << toString(session_type_hidl_) + << ", cookie=" << StringPrintf("%#hx", cookie_) << ", state=" << state_ + << " Hal fails"; } } if (retval) { LOG(INFO) << __func__ << ": session_type=" << toString(session_type_hidl_) - << ", cookie=" << StringPrintf("%#hx", cookie_) - << ", state=" << state_ - << ", mono=" << (is_stereo_to_mono_ ? "true" : "false") - << " done"; + << ", cookie=" << StringPrintf("%#hx", cookie_) << ", state=" << state_ + << ", mono=" << (is_stereo_to_mono_ ? "true" : "false") << " done"; } else { LOG(ERROR) << __func__ << ": session_type=" << toString(session_type_hidl_) - << ", cookie=" << StringPrintf("%#hx", cookie_) - << ", state=" << state_ << " failure"; + << ", cookie=" << StringPrintf("%#hx", cookie_) << ", state=" << state_ + << " failure"; } return retval; // false if any failure like timeout @@ -423,29 +395,26 @@ bool BluetoothAudioPortHidl::Suspend() { } LOG(INFO) << __func__ << ": session_type=" << toString(session_type_hidl_) - << ", cookie=" << StringPrintf("%#hx", cookie_) - << ", state=" << state_ << " request"; + << ", cookie=" << StringPrintf("%#hx", cookie_) << ", state=" << state_ << " request"; bool retval = false; if (state_ == BluetoothStreamState::STARTED) { state_ = BluetoothStreamState::SUSPENDING; if (BluetoothAudioSessionControl_2_1::SuspendStream(session_type_hidl_)) { retval = CondwaitState(BluetoothStreamState::SUSPENDING); } else { - LOG(ERROR) << __func__ - << ": session_type=" << toString(session_type_hidl_) - << ", cookie=" << StringPrintf("%#hx", cookie_) - << ", state=" << state_ << " Hal fails"; + LOG(ERROR) << __func__ << ": session_type=" << toString(session_type_hidl_) + << ", cookie=" << StringPrintf("%#hx", cookie_) << ", state=" << state_ + << " Hal fails"; } } if (retval) { LOG(INFO) << __func__ << ": session_type=" << toString(session_type_hidl_) - << ", cookie=" << StringPrintf("%#hx", cookie_) - << ", state=" << state_ << " done"; + << ", cookie=" << StringPrintf("%#hx", cookie_) << ", state=" << state_ << " done"; } else { LOG(ERROR) << __func__ << ": session_type=" << toString(session_type_hidl_) - << ", cookie=" << StringPrintf("%#hx", cookie_) - << ", state=" << state_ << " failure"; + << ", cookie=" << StringPrintf("%#hx", cookie_) << ", state=" << state_ + << " failure"; } return retval; // false if any failure like timeout @@ -457,83 +426,79 @@ void BluetoothAudioPortHidl::Stop() { return; } LOG(INFO) << __func__ << ": session_type=" << toString(session_type_hidl_) - << ", cookie=" << StringPrintf("%#hx", cookie_) - << ", state=" << state_ << " request"; + << ", cookie=" << StringPrintf("%#hx", cookie_) << ", state=" << state_ << " request"; state_ = BluetoothStreamState::DISABLED; BluetoothAudioSessionControl_2_1::StopStream(session_type_hidl_); LOG(INFO) << __func__ << ": session_type=" << toString(session_type_hidl_) - << ", cookie=" << StringPrintf("%#hx", cookie_) - << ", state=" << state_ << " done"; + << ", cookie=" << StringPrintf("%#hx", cookie_) << ", state=" << state_ << " done"; } -bool BluetoothAudioPortHidl::GetPresentationPosition( - uint64_t* delay_ns, uint64_t* bytes, timespec* timestamp) const { +bool BluetoothAudioPortHidl::GetPresentationPosition(uint64_t* delay_ns, uint64_t* bytes, + timespec* timestamp) const { if (!in_use()) { LOG(ERROR) << __func__ << ": BluetoothAudioPort is not in use"; return false; } bool retval = BluetoothAudioSessionControl_2_1::GetPresentationPosition( - session_type_hidl_, delay_ns, bytes, timestamp); + session_type_hidl_, delay_ns, bytes, timestamp); LOG(VERBOSE) << __func__ << ": session_type=" << StringPrintf("%#x", static_cast(session_type_hidl_)) - << ", cookie=" << StringPrintf("%#hx", cookie_) - << ", state=" << state_ << ", delay=" << *delay_ns - << "ns, data=" << *bytes + << ", cookie=" << StringPrintf("%#hx", cookie_) << ", state=" << state_ + << ", delay=" << *delay_ns << "ns, data=" << *bytes << " bytes, timestamp=" << timestamp->tv_sec << "." << StringPrintf("%09ld", timestamp->tv_nsec) << "s"; return retval; } -void BluetoothAudioPortHidl::UpdateTracksMetadata( - const source_metadata* source_metadata) const { +void BluetoothAudioPortHidl::UpdateTracksMetadata(const source_metadata* source_metadata) const { if (!in_use()) { LOG(ERROR) << __func__ << ": BluetoothAudioPort is not in use"; return; } LOG(DEBUG) << __func__ << ": session_type=" << toString(session_type_hidl_) - << ", cookie=" << StringPrintf("%#hx", cookie_) - << ", state=" << state_ << ", " << source_metadata->track_count - << " track(s)"; - if (source_metadata->track_count == 0) return; - BluetoothAudioSessionControl_2_1::UpdateTracksMetadata(session_type_hidl_, - source_metadata); + << ", cookie=" << StringPrintf("%#hx", cookie_) << ", state=" << state_ << ", " + << source_metadata->track_count << " track(s)"; + if (source_metadata->track_count == 0) { + return; + } + BluetoothAudioSessionControl_2_1::UpdateTracksMetadata(session_type_hidl_, source_metadata); } BluetoothStreamState BluetoothAudioPortHidl::GetState() const { return state_; } -void BluetoothAudioPortHidl::SetState(BluetoothStreamState state) { - state_ = state; -} +void BluetoothAudioPortHidl::SetState(BluetoothStreamState state) { state_ = state; } -size_t BluetoothAudioPortHidlOut::WriteData(const void* buffer, - size_t bytes) const { - if (!BluetoothAudioPortHidl::in_use()) return 0; +size_t BluetoothAudioPortHidlOut::WriteData(const void* buffer, size_t bytes) const { + if (!BluetoothAudioPortHidl::in_use()) { + return 0; + } if (!BluetoothAudioPortHidl::is_stereo_to_mono_) { - return BluetoothAudioSessionControl_2_1::OutWritePcmData(session_type_hidl_, - buffer, bytes); + return BluetoothAudioSessionControl_2_1::OutWritePcmData(session_type_hidl_, buffer, bytes); } // WAR to mix the stereo into Mono (16 bits per sample) const size_t write_frames = bytes >> 2; - if (write_frames == 0) return 0; + if (write_frames == 0) { + return 0; + } auto src = static_cast(buffer); std::unique_ptr dst{new int16_t[write_frames]}; downmix_to_mono_i16_from_stereo_i16(dst.get(), src, write_frames); // a frame is 16 bits, and the size of a mono frame is equal to half a stereo. - return BluetoothAudioSessionControl_2_1::OutWritePcmData( - session_type_hidl_, dst.get(), write_frames * 2) * + return BluetoothAudioSessionControl_2_1::OutWritePcmData(session_type_hidl_, dst.get(), + write_frames * 2) * 2; } size_t BluetoothAudioPortHidlIn::ReadData(void* buffer, size_t bytes) const { - if (!BluetoothAudioPortHidl::in_use()) return 0; - return BluetoothAudioSessionControl_2_1::InReadPcmData(session_type_hidl_, - buffer, bytes); + if (!BluetoothAudioPortHidl::in_use()) { + return 0; + } + return BluetoothAudioSessionControl_2_1::InReadPcmData(session_type_hidl_, buffer, bytes); } -bool BluetoothAudioPortHidlIn::LoadAudioConfig( - audio_config_t* audio_cfg) const { +bool BluetoothAudioPortHidlIn::LoadAudioConfig(audio_config_t* audio_cfg) const { if (!BluetoothAudioPortHidl::in_use()) { LOG(ERROR) << __func__ << ": BluetoothAudioPortIn is not in use"; audio_cfg->sample_rate = kBluetoothDefaultSampleRate; @@ -542,24 +507,22 @@ bool BluetoothAudioPortHidlIn::LoadAudioConfig( return false; } - const ::android::hardware::bluetooth::audio::V2_1::AudioConfiguration& - hal_audio_cfg = + const ::android::hardware::bluetooth::audio::V2_1::AudioConfiguration& hal_audio_cfg = BluetoothAudioSessionControl_2_1::GetAudioConfig(session_type_hidl_); if (hal_audio_cfg.getDiscriminator() != - ::android::hardware::bluetooth::audio::V2_1::AudioConfiguration:: - hidl_discriminator::pcmConfig) { + ::android::hardware::bluetooth::audio::V2_1::AudioConfiguration::hidl_discriminator:: + pcmConfig) { audio_cfg->sample_rate = kBluetoothDefaultSampleRate; audio_cfg->channel_mask = kBluetoothDefaultInputChannelModeMask; audio_cfg->format = kBluetoothDefaultAudioFormatBitsPerSample; return false; } const ::android::hardware::bluetooth::audio::V2_1::PcmParameters& pcm_cfg = - hal_audio_cfg.pcmConfig(); + hal_audio_cfg.pcmConfig(); LOG(VERBOSE) << __func__ << ": session_type=" << toString(session_type_hidl_) - << ", cookie=" - << StringPrintf("%#hx", BluetoothAudioPortHidl::cookie_) - << ", state=" << BluetoothAudioPortHidl::state_ - << ", PcmConfig=[" << toString(pcm_cfg) << "]"; + << ", cookie=" << StringPrintf("%#hx", BluetoothAudioPortHidl::cookie_) + << ", state=" << BluetoothAudioPortHidl::state_ << ", PcmConfig=[" + << toString(pcm_cfg) << "]"; if (pcm_cfg.sampleRate == SampleRate_2_1::RATE_UNKNOWN || pcm_cfg.channelMode == ChannelMode::UNKNOWN || pcm_cfg.bitsPerSample == BitsPerSample::BITS_UNKNOWN) { @@ -572,8 +535,7 @@ bool BluetoothAudioPortHidlIn::LoadAudioConfig( return true; } -bool BluetoothAudioPortHidlOut::LoadAudioConfig( - audio_config_t* audio_cfg) const { +bool BluetoothAudioPortHidlOut::LoadAudioConfig(audio_config_t* audio_cfg) const { if (!BluetoothAudioPortHidl::in_use()) { LOG(ERROR) << __func__ << ": BluetoothAudioPortOut is not in use"; audio_cfg->sample_rate = kBluetoothDefaultSampleRate; @@ -582,34 +544,31 @@ bool BluetoothAudioPortHidlOut::LoadAudioConfig( return false; } - const ::android::hardware::bluetooth::audio::V2_1::AudioConfiguration& - hal_audio_cfg = + const ::android::hardware::bluetooth::audio::V2_1::AudioConfiguration& hal_audio_cfg = BluetoothAudioSessionControl_2_1::GetAudioConfig(session_type_hidl_); if (hal_audio_cfg.getDiscriminator() != - ::android::hardware::bluetooth::audio::V2_1::AudioConfiguration:: - hidl_discriminator::pcmConfig) { + ::android::hardware::bluetooth::audio::V2_1::AudioConfiguration::hidl_discriminator:: + pcmConfig) { audio_cfg->sample_rate = kBluetoothDefaultSampleRate; audio_cfg->channel_mask = kBluetoothDefaultOutputChannelModeMask; audio_cfg->format = kBluetoothDefaultAudioFormatBitsPerSample; return false; } const ::android::hardware::bluetooth::audio::V2_1::PcmParameters& pcm_cfg = - hal_audio_cfg.pcmConfig(); + hal_audio_cfg.pcmConfig(); LOG(VERBOSE) << __func__ << ": session_type=" << toString(session_type_hidl_) - << ", cookie=" - << StringPrintf("%#hx", BluetoothAudioPortHidl::cookie_) - << ", state=" << BluetoothAudioPortHidl::state_ - << ", PcmConfig=[" << toString(pcm_cfg) << "]"; + << ", cookie=" << StringPrintf("%#hx", BluetoothAudioPortHidl::cookie_) + << ", state=" << BluetoothAudioPortHidl::state_ << ", PcmConfig=[" + << toString(pcm_cfg) << "]"; if (pcm_cfg.sampleRate == SampleRate_2_1::RATE_UNKNOWN || pcm_cfg.channelMode == ChannelMode::UNKNOWN || pcm_cfg.bitsPerSample == BitsPerSample::BITS_UNKNOWN) { return false; } audio_cfg->sample_rate = SampleRateToAudioFormat(pcm_cfg.sampleRate); - audio_cfg->channel_mask = - (BluetoothAudioPortHidl::is_stereo_to_mono_ - ? AUDIO_CHANNEL_OUT_STEREO - : OutputChannelModeToAudioFormat(pcm_cfg.channelMode)); + audio_cfg->channel_mask = (BluetoothAudioPortHidl::is_stereo_to_mono_ + ? AUDIO_CHANNEL_OUT_STEREO + : OutputChannelModeToAudioFormat(pcm_cfg.channelMode)); audio_cfg->format = BitsPerSampleToAudioFormat(pcm_cfg.bitsPerSample); return true; } diff --git a/system/audio_bluetooth_hw/device_port_proxy_hidl.h b/system/audio_bluetooth_hw/device_port_proxy_hidl.h index 5b32889ba47..640ff95fb1d 100644 --- a/system/audio_bluetooth_hw/device_port_proxy_hidl.h +++ b/system/audio_bluetooth_hw/device_port_proxy_hidl.h @@ -32,11 +32,10 @@ namespace bluetooth { namespace audio { namespace hidl { -using SessionType_2_1 = - ::android::hardware::bluetooth::audio::V2_1::SessionType; +using SessionType_2_1 = ::android::hardware::bluetooth::audio::V2_1::SessionType; class BluetoothAudioPortHidl : public BluetoothAudioPort { - public: +public: BluetoothAudioPortHidl(); virtual ~BluetoothAudioPortHidl() = default; @@ -62,26 +61,20 @@ class BluetoothAudioPortHidl : public BluetoothAudioPort { void SetState(BluetoothStreamState state) override; bool IsA2dp() const override { - return session_type_hidl_ == - SessionType_2_1::A2DP_SOFTWARE_ENCODING_DATAPATH || - session_type_hidl_ == - SessionType_2_1::A2DP_HARDWARE_OFFLOAD_DATAPATH; + return session_type_hidl_ == SessionType_2_1::A2DP_SOFTWARE_ENCODING_DATAPATH || + session_type_hidl_ == SessionType_2_1::A2DP_HARDWARE_OFFLOAD_DATAPATH; } bool IsLeAudio() const override { - return session_type_hidl_ == - SessionType_2_1::LE_AUDIO_SOFTWARE_ENCODING_DATAPATH || - session_type_hidl_ == - SessionType_2_1::LE_AUDIO_SOFTWARE_DECODED_DATAPATH || - session_type_hidl_ == - SessionType_2_1::LE_AUDIO_HARDWARE_OFFLOAD_ENCODING_DATAPATH || - session_type_hidl_ == - SessionType_2_1::LE_AUDIO_HARDWARE_OFFLOAD_DECODING_DATAPATH; + return session_type_hidl_ == SessionType_2_1::LE_AUDIO_SOFTWARE_ENCODING_DATAPATH || + session_type_hidl_ == SessionType_2_1::LE_AUDIO_SOFTWARE_DECODED_DATAPATH || + session_type_hidl_ == SessionType_2_1::LE_AUDIO_HARDWARE_OFFLOAD_ENCODING_DATAPATH || + session_type_hidl_ == SessionType_2_1::LE_AUDIO_HARDWARE_OFFLOAD_DECODING_DATAPATH; } bool GetPreferredDataIntervalUs(size_t* interval_us) const override; - protected: +protected: SessionType_2_1 session_type_hidl_; uint16_t cookie_; BluetoothStreamState state_; @@ -90,7 +83,7 @@ class BluetoothAudioPortHidl : public BluetoothAudioPort { bool in_use() const; - private: +private: mutable std::mutex cv_mutex_; std::condition_variable internal_cv_; @@ -98,14 +91,13 @@ class BluetoothAudioPortHidl : public BluetoothAudioPort { bool CondwaitState(BluetoothStreamState state); - void ControlResultHandler( - const ::android::hardware::bluetooth::audio::V2_0::Status& status); + void ControlResultHandler(const ::android::hardware::bluetooth::audio::V2_0::Status& status); void SessionChangedHandler(); }; class BluetoothAudioPortHidlOut : public BluetoothAudioPortHidl { - public: +public: ~BluetoothAudioPortHidlOut(); size_t WriteData(const void* buffer, size_t bytes) const override; @@ -113,7 +105,7 @@ class BluetoothAudioPortHidlOut : public BluetoothAudioPortHidl { }; class BluetoothAudioPortHidlIn : public BluetoothAudioPortHidl { - public: +public: ~BluetoothAudioPortHidlIn(); size_t ReadData(void* buffer, size_t bytes) const override; diff --git a/system/audio_bluetooth_hw/stream_apis.cc b/system/audio_bluetooth_hw/stream_apis.cc index bd26d7b6b0e..cabcdcd6071 100644 --- a/system/audio_bluetooth_hw/stream_apis.cc +++ b/system/audio_bluetooth_hw/stream_apis.cc @@ -48,8 +48,7 @@ std::ostream& operator<<(std::ostream& os, const audio_config& config) { << ", format=" << config.format << "]"; } -void out_calculate_feeding_delay_ms(const BluetoothStreamOut* out, - uint32_t* latency_ms, +void out_calculate_feeding_delay_ms(const BluetoothStreamOut* out, uint32_t* latency_ms, uint64_t* frames = nullptr, struct timespec* timestamp = nullptr) { if (latency_ms == nullptr && frames == nullptr && timestamp == nullptr) { @@ -68,14 +67,13 @@ void out_calculate_feeding_delay_ms(const BluetoothStreamOut* out, bool timestamp_fetched = false; std::unique_lock lock(out->mutex_); - if (out->bluetooth_output_->GetPresentationPosition( - &delay_report_ns, &absorbed_bytes, &absorbed_timestamp)) { + if (out->bluetooth_output_->GetPresentationPosition(&delay_report_ns, &absorbed_bytes, + &absorbed_timestamp)) { delay_report_ms = delay_report_ns / 1000000; // assume kMinimumDelayMs (50ms) < delay_report_ns < kMaximumDelayMs // (1000ms), or it is invalid / ignored and use old delay calculated // by ourselves. - if (delay_report_ms > kMinimumDelayMs && - delay_report_ms < kMaximumDelayMs) { + if (delay_report_ms > kMinimumDelayMs && delay_report_ms < kMaximumDelayMs) { timestamp_fetched = true; } else if (delay_report_ms >= kMaximumDelayMs) { LOG(INFO) << __func__ << ": state=" << out->bluetooth_output_->GetState() @@ -88,8 +86,7 @@ void out_calculate_feeding_delay_ms(const BluetoothStreamOut* out, // frames_count = buffer_size / frame_size // latency (sec.) = frames_count / samples_per_second (sample_rate) // Sync from audio_a2dp_hw to add extra delay kExtraAudioSyncMs(+200ms) - delay_report_ms = - out->frames_count_ * 1000 / out->sample_rate_ + kExtraAudioSyncMs; + delay_report_ms = out->frames_count_ * 1000 / out->sample_rate_ + kExtraAudioSyncMs; if (timestamp != nullptr) { clock_gettime(CLOCK_MONOTONIC, &absorbed_timestamp); } @@ -129,8 +126,7 @@ void out_calculate_feeding_delay_ms(const BluetoothStreamOut* out, } } -void in_calculate_starving_delay_ms(const BluetoothStreamIn* in, - int64_t* frames, int64_t* time) { +void in_calculate_starving_delay_ms(const BluetoothStreamIn* in, int64_t* frames, int64_t* time) { // delay_report is the audio delay from the remote headset receiving data to // the headset playing sound in units of nanoseconds uint64_t delay_report_ns = 0; @@ -141,16 +137,15 @@ void in_calculate_starving_delay_ms(const BluetoothStreamIn* in, struct timespec dispersed_timestamp = {}; std::unique_lock lock(in->mutex_); - in->bluetooth_input_->GetPresentationPosition( - &delay_report_ns, &dispersed_bytes, &dispersed_timestamp); + in->bluetooth_input_->GetPresentationPosition(&delay_report_ns, &dispersed_bytes, + &dispersed_timestamp); delay_report_ms = delay_report_ns / 1000000; const uint64_t latency_frames = delay_report_ms * in->sample_rate_ / 1000; *frames = dispersed_bytes / audio_stream_in_frame_size(&in->stream_in_); LOG(VERBOSE) << __func__ << ": state=" << in->bluetooth_input_->GetState() - << ", delay=" << delay_report_ms - << "ms, data=" << dispersed_bytes + << ", delay=" << delay_report_ms << "ms, data=" << dispersed_bytes << " bytes, timestamp=" << dispersed_timestamp.tv_sec << "." << StringPrintf("%09ld", dispersed_timestamp.tv_nsec) << "s"; @@ -171,9 +166,7 @@ void in_calculate_starving_delay_ms(const BluetoothStreamIn* in, *frames = 0; } - *time = (dispersed_timestamp.tv_sec * 1000000000LL + - dispersed_timestamp.tv_nsec) / - 1000; + *time = (dispersed_timestamp.tv_sec * 1000000000LL + dispersed_timestamp.tv_nsec) / 1000; } } // namespace @@ -215,20 +208,18 @@ static int out_set_sample_rate(struct audio_stream* stream, uint32_t rate) { auto* out = reinterpret_cast(stream); LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState() << ", sample_rate=" << out->sample_rate_; - return (rate == out->sample_rate_ ? 0 : -1); + return rate == out->sample_rate_ ? 0 : -1; } static size_t out_get_buffer_size(const struct audio_stream* stream) { const auto* out = reinterpret_cast(stream); - size_t buffer_size = - out->frames_count_ * audio_stream_out_frame_size(&out->stream_out_); + size_t buffer_size = out->frames_count_ * audio_stream_out_frame_size(&out->stream_out_); LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState() << ", buffer_size=" << buffer_size; return buffer_size; } -static audio_channel_mask_t out_get_channels( - const struct audio_stream* stream) { +static audio_channel_mask_t out_get_channels(const struct audio_stream* stream) { const auto* out = reinterpret_cast(stream); audio_config_t audio_cfg; if (out->bluetooth_output_->LoadAudioConfig(&audio_cfg)) { @@ -237,8 +228,7 @@ static audio_channel_mask_t out_get_channels( return audio_cfg.channel_mask; } else { LOG(WARNING) << __func__ << ": state=" << out->bluetooth_output_->GetState() - << ", channels=" << StringPrintf("%#x", out->channel_mask_) - << " failure"; + << ", channels=" << StringPrintf("%#x", out->channel_mask_) << " failure"; return out->channel_mask_; } } @@ -261,7 +251,7 @@ static int out_set_format(struct audio_stream* stream, audio_format_t format) { auto* out = reinterpret_cast(stream); LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState() << ", format=" << out->format_; - return (format == out->format_ ? 0 : -1); + return format == out->format_ ? 0 : -1; } static int out_standby(struct audio_stream* stream) { @@ -276,10 +266,8 @@ static int out_standby(struct audio_stream* stream) { if (out->bluetooth_output_->GetState() == BluetoothStreamState::STARTED) { out->frames_rendered_ = 0; retval = (out->bluetooth_output_->Suspend() ? 0 : -EIO); - } else if (out->bluetooth_output_->GetState() == - BluetoothStreamState::STARTING || - out->bluetooth_output_->GetState() == - BluetoothStreamState::SUSPENDING) { + } else if (out->bluetooth_output_->GetState() == BluetoothStreamState::STARTING || + out->bluetooth_output_->GetState() == BluetoothStreamState::SUSPENDING) { LOG(WARNING) << __func__ << ": state=" << out->bluetooth_output_->GetState() << " NOT ready to be standby"; retval = -EBUSY; @@ -299,21 +287,20 @@ static int out_dump(const struct audio_stream* stream, int fd) { return 0; } -static int out_set_parameters(struct audio_stream* stream, - const char* kvpairs) { +static int out_set_parameters(struct audio_stream* stream, const char* kvpairs) { auto* out = reinterpret_cast(stream); std::unique_lock lock(out->mutex_); int retval = 0; - LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState() - << ", kvpairs=[" << kvpairs << "]"; + LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState() << ", kvpairs=[" + << kvpairs << "]"; - std::unordered_map params = - ParseAudioParams(kvpairs); - if (params.empty()) return retval; + std::unordered_map params = ParseAudioParams(kvpairs); + if (params.empty()) { + return retval; + } - LOG(VERBOSE) << __func__ << ": ParamsMap=[" << GetAudioParamString(params) - << "]"; + LOG(VERBOSE) << __func__ << ": ParamsMap=[" << GetAudioParamString(params) << "]"; audio_config_t audio_cfg; if (params.find(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES) != params.end() || @@ -328,21 +315,18 @@ static int out_set_parameters(struct audio_stream* stream, << ", channels=" << StringPrintf("%#x", out->channel_mask_) << ", format=" << out->format_; } else { - LOG(WARNING) << __func__ - << ": state=" << out->bluetooth_output_->GetState() + LOG(WARNING) << __func__ << ": state=" << out->bluetooth_output_->GetState() << " failed to get audio config"; } } if (params.find(AUDIO_PARAMETER_STREAM_ROUTING) != params.end()) { auto routing_param = params.find("routing"); - LOG(INFO) << __func__ << ": state=" << out->bluetooth_output_->GetState() - << ", stream param '" << routing_param->first.c_str() << "=" - << routing_param->second.c_str() << "'"; + LOG(INFO) << __func__ << ": state=" << out->bluetooth_output_->GetState() << ", stream param '" + << routing_param->first.c_str() << "=" << routing_param->second.c_str() << "'"; } - if (params.find("A2dpSuspended") != params.end() && - out->bluetooth_output_->IsA2dp()) { + if (params.find("A2dpSuspended") != params.end() && out->bluetooth_output_->IsA2dp()) { if (params["A2dpSuspended"] == "true") { LOG(INFO) << __func__ << ": state=" << out->bluetooth_output_->GetState() << " stream param stopped"; @@ -350,40 +334,35 @@ static int out_set_parameters(struct audio_stream* stream, if (out->bluetooth_output_->GetState() == BluetoothStreamState::STARTED) { out->bluetooth_output_->Suspend(); out->bluetooth_output_->SetState(BluetoothStreamState::DISABLED); - } else if (out->bluetooth_output_->GetState() != - BluetoothStreamState::DISABLED) { + } else if (out->bluetooth_output_->GetState() != BluetoothStreamState::DISABLED) { out->bluetooth_output_->Stop(); } } else { LOG(INFO) << __func__ << ": state=" << out->bluetooth_output_->GetState() << " stream param standby"; - if (out->bluetooth_output_->GetState() == - BluetoothStreamState::DISABLED) { + if (out->bluetooth_output_->GetState() == BluetoothStreamState::DISABLED) { out->bluetooth_output_->SetState(BluetoothStreamState::STANDBY); } } } - if (params.find("LeAudioSuspended") != params.end() && - out->bluetooth_output_->IsLeAudio()) { - LOG(INFO) << __func__ << ": LeAudioSuspended found LEAudio=" - << out->bluetooth_output_->IsLeAudio(); + if (params.find("LeAudioSuspended") != params.end() && out->bluetooth_output_->IsLeAudio()) { + LOG(INFO) << __func__ + << ": LeAudioSuspended found LEAudio=" << out->bluetooth_output_->IsLeAudio(); if (params["LeAudioSuspended"] == "true") { - LOG(INFO) << __func__ << ": LeAudioSuspended true, state=" - << out->bluetooth_output_->GetState() + LOG(INFO) << __func__ + << ": LeAudioSuspended true, state=" << out->bluetooth_output_->GetState() << " stream param standby"; if (out->bluetooth_output_->GetState() == BluetoothStreamState::STARTED) { LOG(INFO) << __func__ << ": Stream is started, suspending LE Audio"; - } else if (out->bluetooth_output_->GetState() != - BluetoothStreamState::DISABLED) { + } else if (out->bluetooth_output_->GetState() != BluetoothStreamState::DISABLED) { LOG(INFO) << __func__ << ": Stream is disabled, suspending LE Audio"; } } else { - LOG(INFO) << __func__ << ": LeAudioSuspended false, state=" - << out->bluetooth_output_->GetState() + LOG(INFO) << __func__ + << ": LeAudioSuspended false, state=" << out->bluetooth_output_->GetState() << " stream param standby"; - if (out->bluetooth_output_->GetState() == - BluetoothStreamState::DISABLED) { + if (out->bluetooth_output_->GetState() == BluetoothStreamState::DISABLED) { LOG(INFO) << __func__ << ": Stream is disabled, unsuspending LE Audio"; } } @@ -393,8 +372,7 @@ static int out_set_parameters(struct audio_stream* stream, if (params[AUDIO_PARAMETER_KEY_CLOSING] == "true") { LOG(INFO) << __func__ << ": state=" << out->bluetooth_output_->GetState() << " stream param closing, disallow any writes?"; - if (out->bluetooth_output_->GetState() != - BluetoothStreamState::DISABLED) { + if (out->bluetooth_output_->GetState() != BluetoothStreamState::DISABLED) { out->frames_rendered_ = 0; out->frames_presented_ = 0; out->bluetooth_output_->Stop(); @@ -406,8 +384,7 @@ static int out_set_parameters(struct audio_stream* stream, if (params[AUDIO_PARAMETER_KEY_EXITING] == "1") { LOG(INFO) << __func__ << ": state=" << out->bluetooth_output_->GetState() << " stream param exiting"; - if (out->bluetooth_output_->GetState() != - BluetoothStreamState::DISABLED) { + if (out->bluetooth_output_->GetState() != BluetoothStreamState::DISABLED) { out->frames_rendered_ = 0; out->frames_presented_ = 0; out->bluetooth_output_->Stop(); @@ -415,21 +392,22 @@ static int out_set_parameters(struct audio_stream* stream, } } - LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState() - << ", kvpairs=[" << kvpairs << "], retval=" << retval; + LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState() << ", kvpairs=[" + << kvpairs << "], retval=" << retval; return retval; } -static char* out_get_parameters(const struct audio_stream* stream, - const char* keys) { +static char* out_get_parameters(const struct audio_stream* stream, const char* keys) { const auto* out = reinterpret_cast(stream); std::unique_lock lock(out->mutex_); - LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState() - << ", keys=[" << keys << "]"; + LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState() << ", keys=[" << keys + << "]"; std::unordered_map params = ParseAudioParams(keys); - if (params.empty()) return strdup(""); + if (params.empty()) { + return strdup(""); + } audio_config_t audio_cfg; if (out->bluetooth_output_->LoadAudioConfig(&audio_cfg)) { @@ -503,8 +481,8 @@ static char* out_get_parameters(const struct audio_stream* stream, result += ptr.first + "=" + ptr.second + ";"; } - LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState() - << ", result=[" << result << "]"; + LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState() << ", result=[" + << result << "]"; return strdup(result.c_str()); } @@ -517,16 +495,14 @@ static uint32_t out_get_latency_ms(const struct audio_stream_out* stream) { return latency_ms; } -static int out_set_volume(struct audio_stream_out* stream, float left, - float right) { +static int out_set_volume(struct audio_stream_out* stream, float left, float right) { auto* out = reinterpret_cast(stream); - LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState() - << ", Left=" << left << ", Right=" << right; + LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState() << ", Left=" << left + << ", Right=" << right; return -1; } -static ssize_t out_write(struct audio_stream_out* stream, const void* buffer, - size_t bytes) { +static ssize_t out_write(struct audio_stream_out* stream, const void* buffer, size_t bytes) { auto* out = reinterpret_cast(stream); std::unique_lock lock(out->mutex_); size_t totalWritten = 0; @@ -538,8 +514,7 @@ static ssize_t out_write(struct audio_stream_out* stream, const void* buffer, if (stream->resume(stream)) { LOG(ERROR) << __func__ << ": state=" << out->bluetooth_output_->GetState() << " failed to resume"; - if (out->bluetooth_output_->GetState() == - BluetoothStreamState::DISABLED) { + if (out->bluetooth_output_->GetState() == BluetoothStreamState::DISABLED) { // drop data for cases of A2dpSuspended=true / closing=true totalWritten = bytes; } @@ -561,14 +536,12 @@ static ssize_t out_write(struct audio_stream_out* stream, const void* buffer, out->last_write_time_us_ = (ts.tv_sec * 1000000000LL + ts.tv_nsec) / 1000; } else { const int64_t now = (ts.tv_sec * 1000000000LL + ts.tv_nsec) / 1000; - const int64_t elapsed_time_since_last_write = - now - out->last_write_time_us_; + const int64_t elapsed_time_since_last_write = now - out->last_write_time_us_; // frames_count = written_data / frame_size // play_time (ms) = frames_count / (sample_rate (Sec.) / 1000000) // sleep_time (ms) = play_time - elapsed_time - int64_t sleep_time = bytes * 1000000LL / - audio_stream_out_frame_size(stream) / - out_get_sample_rate(&stream->common) - + int64_t sleep_time = bytes * 1000000LL / audio_stream_out_frame_size(stream) / + out_get_sample_rate(&stream->common) - elapsed_time_since_last_write; if (sleep_time > 0) { LOG(VERBOSE) << __func__ << ": sleep " << (sleep_time / 1000) @@ -586,14 +559,14 @@ static ssize_t out_write(struct audio_stream_out* stream, const void* buffer, return totalWritten; } -static int out_get_render_position(const struct audio_stream_out* stream, - uint32_t* dsp_frames) { - if (dsp_frames == nullptr) return -EINVAL; +static int out_get_render_position(const struct audio_stream_out* stream, uint32_t* dsp_frames) { + if (dsp_frames == nullptr) { + return -EINVAL; + } const auto* out = reinterpret_cast(stream); // frames = (latency (ms) / 1000) * samples_per_second (sample_rate) - const uint64_t latency_frames = - (uint64_t)out_get_latency_ms(stream) * out->sample_rate_ / 1000; + const uint64_t latency_frames = (uint64_t)out_get_latency_ms(stream) * out->sample_rate_ / 1000; if (out->frames_rendered_ >= latency_frames) { *dsp_frames = (uint32_t)(out->frames_rendered_ - latency_frames); } else { @@ -605,24 +578,21 @@ static int out_get_render_position(const struct audio_stream_out* stream, return 0; } -static int out_add_audio_effect(const struct audio_stream* stream, - effect_handle_t effect) { +static int out_add_audio_effect(const struct audio_stream* stream, effect_handle_t effect) { const auto* out = reinterpret_cast(stream); LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState() << ", effect=" << effect; return 0; } -static int out_remove_audio_effect(const struct audio_stream* stream, - effect_handle_t effect) { +static int out_remove_audio_effect(const struct audio_stream* stream, effect_handle_t effect) { const auto* out = reinterpret_cast(stream); LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState() << ", effect=" << effect; return 0; } -static int out_get_next_write_timestamp(const struct audio_stream_out* stream, - int64_t* timestamp) { +static int out_get_next_write_timestamp(const struct audio_stream_out* stream, int64_t* timestamp) { const auto* out = reinterpret_cast(stream); *timestamp = 0; LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState() @@ -639,16 +609,13 @@ static int out_pause(struct audio_stream_out* stream) { if (out->bluetooth_output_->GetState() == BluetoothStreamState::STARTED) { out->frames_rendered_ = 0; retval = (out->bluetooth_output_->Suspend() ? 0 : -EIO); - } else if (out->bluetooth_output_->GetState() == - BluetoothStreamState::STARTING || - out->bluetooth_output_->GetState() == - BluetoothStreamState::SUSPENDING) { + } else if (out->bluetooth_output_->GetState() == BluetoothStreamState::STARTING || + out->bluetooth_output_->GetState() == BluetoothStreamState::SUSPENDING) { LOG(WARNING) << __func__ << ": state=" << out->bluetooth_output_->GetState() << " NOT ready to pause?!"; retval = -EBUSY; } else { - LOG(DEBUG) << __func__ << ": state=" << out->bluetooth_output_->GetState() - << " paused already"; + LOG(DEBUG) << __func__ << ": state=" << out->bluetooth_output_->GetState() << " paused already"; } LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState() << ", pausing (suspend) retval=" << retval; @@ -665,15 +632,12 @@ static int out_resume(struct audio_stream_out* stream) { << ", resuming (start)"; if (out->bluetooth_output_->GetState() == BluetoothStreamState::STANDBY) { retval = (out->bluetooth_output_->Start() ? 0 : -EIO); - } else if (out->bluetooth_output_->GetState() == - BluetoothStreamState::STARTING || - out->bluetooth_output_->GetState() == - BluetoothStreamState::SUSPENDING) { + } else if (out->bluetooth_output_->GetState() == BluetoothStreamState::STARTING || + out->bluetooth_output_->GetState() == BluetoothStreamState::SUSPENDING) { LOG(WARNING) << __func__ << ": state=" << out->bluetooth_output_->GetState() << " NOT ready to resume?!"; retval = -EBUSY; - } else if (out->bluetooth_output_->GetState() == - BluetoothStreamState::DISABLED) { + } else if (out->bluetooth_output_->GetState() == BluetoothStreamState::DISABLED) { LOG(WARNING) << __func__ << ": state=" << out->bluetooth_output_->GetState() << " NOT allow to resume?!"; retval = -EINVAL; @@ -687,8 +651,7 @@ static int out_resume(struct audio_stream_out* stream) { return retval; } -static int out_get_presentation_position(const struct audio_stream_out* stream, - uint64_t* frames, +static int out_get_presentation_position(const struct audio_stream_out* stream, uint64_t* frames, struct timespec* timestamp) { if (frames == nullptr || timestamp == nullptr) { return -EINVAL; @@ -697,55 +660,50 @@ static int out_get_presentation_position(const struct audio_stream_out* stream, const auto* out = reinterpret_cast(stream); out_calculate_feeding_delay_ms(out, nullptr, frames, timestamp); LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState() - << ", frames=" << *frames << ", timestamp=" << timestamp->tv_sec - << "." << StringPrintf("%09ld", timestamp->tv_nsec) << "s"; + << ", frames=" << *frames << ", timestamp=" << timestamp->tv_sec << "." + << StringPrintf("%09ld", timestamp->tv_nsec) << "s"; return 0; } -static void out_update_source_metadata_v7( - struct audio_stream_out* stream, - const struct source_metadata_v7* source_metadata_v7) { +static void out_update_source_metadata_v7(struct audio_stream_out* stream, + const struct source_metadata_v7* source_metadata_v7) { auto* out = reinterpret_cast(stream); std::unique_lock lock(out->mutex_); if (source_metadata_v7 == nullptr || source_metadata_v7->track_count == 0) { return; } - LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState() - << ", " << source_metadata_v7->track_count << " track(s)"; + LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState() << ", " + << source_metadata_v7->track_count << " track(s)"; if (!out->is_aidl) { struct source_metadata source_metadata; source_metadata.track_count = source_metadata_v7->track_count; struct playback_track_metadata playback_track; - playback_track_metadata_from_v7(&playback_track, - source_metadata_v7->tracks); + playback_track_metadata_from_v7(&playback_track, source_metadata_v7->tracks); source_metadata.tracks = &playback_track; static_cast<::android::bluetooth::audio::hidl::BluetoothAudioPortHidl*>( - out->bluetooth_output_.get()) - ->UpdateTracksMetadata(&source_metadata); + out->bluetooth_output_.get()) + ->UpdateTracksMetadata(&source_metadata); } else { static_cast<::android::bluetooth::audio::aidl::BluetoothAudioPortAidl*>( - out->bluetooth_output_.get()) - ->UpdateSourceMetadata(source_metadata_v7); + out->bluetooth_output_.get()) + ->UpdateSourceMetadata(source_metadata_v7); } } -int adev_open_output_stream(struct audio_hw_device* dev, - audio_io_handle_t handle, audio_devices_t devices, - audio_output_flags_t flags, - struct audio_config* config, - struct audio_stream_out** stream_out, +int adev_open_output_stream(struct audio_hw_device* dev, audio_io_handle_t handle, + audio_devices_t devices, audio_output_flags_t flags, + struct audio_config* config, struct audio_stream_out** stream_out, const char* address __unused) { *stream_out = nullptr; auto out = std::make_unique(); - if (::aidl::android::hardware::bluetooth::audio::BluetoothAudioSession:: - IsAidlAvailable()) { - out->bluetooth_output_ = std::make_unique< - ::android::bluetooth::audio::aidl::BluetoothAudioPortAidlOut>(); + if (::aidl::android::hardware::bluetooth::audio::BluetoothAudioSession::IsAidlAvailable()) { + out->bluetooth_output_ = + std::make_unique<::android::bluetooth::audio::aidl::BluetoothAudioPortAidlOut>(); out->is_aidl = true; } else { - out->bluetooth_output_ = std::make_unique< - ::android::bluetooth::audio::hidl::BluetoothAudioPortHidlOut>(); + out->bluetooth_output_ = + std::make_unique<::android::bluetooth::audio::hidl::BluetoothAudioPortHidlOut>(); out->is_aidl = false; } if (!out->bluetooth_output_->SetUp(devices)) { @@ -785,10 +743,8 @@ int adev_open_output_stream(struct audio_hw_device* dev, << " failed to get audio config"; } // WAR to support Mono / 16 bits per sample as the Bluetooth stack required - if (config->channel_mask == AUDIO_CHANNEL_OUT_MONO && - config->format == AUDIO_FORMAT_PCM_16_BIT) { - LOG(INFO) << __func__ - << ": force channels=" << StringPrintf("%#x", out->channel_mask_) + if (config->channel_mask == AUDIO_CHANNEL_OUT_MONO && config->format == AUDIO_FORMAT_PCM_16_BIT) { + LOG(INFO) << __func__ << ": force channels=" << StringPrintf("%#x", out->channel_mask_) << " to be AUDIO_CHANNEL_OUT_STEREO"; out->bluetooth_output_->ForcePcmStereoToMono(true); config->channel_mask = AUDIO_CHANNEL_OUT_STEREO; @@ -799,8 +755,7 @@ int adev_open_output_stream(struct audio_hw_device* dev, // frame is number of samples per channel size_t preferred_data_interval_us = kBluetoothDefaultOutputBufferMs * 1000; - if (out->bluetooth_output_->GetPreferredDataIntervalUs( - &preferred_data_interval_us) && + if (out->bluetooth_output_->GetPreferredDataIntervalUs(&preferred_data_interval_us) && preferred_data_interval_us != 0) { out->preferred_data_interval_us = preferred_data_interval_us; } else { @@ -810,17 +765,13 @@ int adev_open_output_stream(struct audio_hw_device* dev, // Ensure minimum buffer duration for spatialized output if ((flags == (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER) || flags == AUDIO_OUTPUT_FLAG_SPATIALIZER) && - out->preferred_data_interval_us < - kBluetoothSpatializerOutputBufferMs * 1000) { - out->preferred_data_interval_us = - kBluetoothSpatializerOutputBufferMs * 1000; - LOG(INFO) << __func__ - << ": adjusting to minimum buffer duration for spatializer: " + out->preferred_data_interval_us < kBluetoothSpatializerOutputBufferMs * 1000) { + out->preferred_data_interval_us = kBluetoothSpatializerOutputBufferMs * 1000; + LOG(INFO) << __func__ << ": adjusting to minimum buffer duration for spatializer: " << StringPrintf("%zu", out->preferred_data_interval_us); } - out->frames_count_ = - FrameCount(out->preferred_data_interval_us, out->sample_rate_); + out->frames_count_ = FrameCount(out->preferred_data_interval_us, out->sample_rate_); out->frames_rendered_ = 0; out->frames_presented_ = 0; @@ -837,17 +788,14 @@ int adev_open_output_stream(struct audio_hw_device* dev, << ", sample_rate=" << out_ptr->sample_rate_ << ", channels=" << StringPrintf("%#x", out_ptr->channel_mask_) << ", format=" << out_ptr->format_ - << ", preferred_data_interval_us=" - << out_ptr->preferred_data_interval_us + << ", preferred_data_interval_us=" << out_ptr->preferred_data_interval_us << ", frames=" << out_ptr->frames_count_; return 0; } -void adev_close_output_stream(struct audio_hw_device* dev, - struct audio_stream_out* stream) { +void adev_close_output_stream(struct audio_hw_device* dev, struct audio_stream_out* stream) { auto* out = reinterpret_cast(stream); - LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState() - << ", stopping"; + LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState() << ", stopping"; { auto* bluetooth_device = reinterpret_cast(dev); std::lock_guard guard(bluetooth_device->mutex_); @@ -859,8 +807,7 @@ void adev_close_output_stream(struct audio_hw_device* dev, out->bluetooth_output_->Stop(); } out->bluetooth_output_->TearDown(); - LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState() - << ", stopped"; + LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState() << ", stopped"; delete out; } @@ -882,13 +829,12 @@ static int in_set_sample_rate(struct audio_stream* stream, uint32_t rate) { LOG(VERBOSE) << __func__ << ": state=" << in->bluetooth_input_->GetState() << ", sample_rate=" << in->sample_rate_; - return (rate == in->sample_rate_ ? 0 : -ENOSYS); + return rate == in->sample_rate_ ? 0 : -ENOSYS; } static size_t in_get_buffer_size(const struct audio_stream* stream) { const auto* in = reinterpret_cast(stream); - size_t buffer_size = - in->frames_count_ * audio_stream_in_frame_size(&in->stream_in_); + size_t buffer_size = in->frames_count_ * audio_stream_in_frame_size(&in->stream_in_); LOG(VERBOSE) << __func__ << ": state=" << in->bluetooth_input_->GetState() << ", buffer_size=" << buffer_size; return buffer_size; @@ -903,8 +849,7 @@ static audio_channel_mask_t in_get_channels(const struct audio_stream* stream) { return audio_cfg.channel_mask; } else { LOG(WARNING) << __func__ << ": state=" << in->bluetooth_input_->GetState() - << ", channels=" << StringPrintf("%#x", in->channel_mask_) - << " failure"; + << ", channels=" << StringPrintf("%#x", in->channel_mask_) << " failure"; return in->channel_mask_; } } @@ -927,13 +872,11 @@ static int in_set_format(struct audio_stream* stream, audio_format_t format) { const auto* in = reinterpret_cast(stream); LOG(VERBOSE) << __func__ << ": state=" << in->bluetooth_input_->GetState() << ", format=" << in->format_; - return (format == in->format_ ? 0 : -ENOSYS); + return format == in->format_ ? 0 : -ENOSYS; } -static bool in_state_transition_timeout(BluetoothStreamIn* in, - std::unique_lock& lock, - const BluetoothStreamState& state, - uint16_t timeout_ms) { +static bool in_state_transition_timeout(BluetoothStreamIn* in, std::unique_lock& lock, + const BluetoothStreamState& state, uint16_t timeout_ms) { /* Don't loose suspend request, AF will not retry */ while (in->bluetooth_input_->GetState() == state) { lock.unlock(); @@ -942,8 +885,8 @@ static bool in_state_transition_timeout(BluetoothStreamIn* in, /* Don't block AF forever */ if (--timeout_ms <= 0) { - LOG(WARNING) << __func__ << ", can't suspend - stucked in: " - << static_cast(state) << " state"; + LOG(WARNING) << __func__ << ", can't suspend - stucked in: " << static_cast(state) + << " state"; return false; } } @@ -969,10 +912,8 @@ static int in_standby(struct audio_stream* stream) { if (in->bluetooth_input_->GetState() == BluetoothStreamState::STARTED) { retval = (in->bluetooth_input_->Suspend() ? 0 : -EIO); - } else if (in->bluetooth_input_->GetState() != - BluetoothStreamState::SUSPENDING) { - LOG(DEBUG) << __func__ << ": state=" << in->bluetooth_input_->GetState() - << " standby already"; + } else if (in->bluetooth_input_->GetState() != BluetoothStreamState::SUSPENDING) { + LOG(DEBUG) << __func__ << ": state=" << in->bluetooth_input_->GetState() << " standby already"; return retval; } @@ -1002,32 +943,31 @@ static int in_set_parameters(struct audio_stream* stream, const char* kvpairs) { std::unique_lock lock(in->mutex_); int retval = 0; - LOG(INFO) << __func__ - << ": NOT HANDLED! state=" << in->bluetooth_input_->GetState() + LOG(INFO) << __func__ << ": NOT HANDLED! state=" << in->bluetooth_input_->GetState() << ", kvpairs=[" << kvpairs << "]"; - std::unordered_map params = - ParseAudioParams(kvpairs); + std::unordered_map params = ParseAudioParams(kvpairs); - if (params.empty()) return retval; + if (params.empty()) { + return retval; + } - LOG(INFO) << __func__ << ": ParamsMap=[" << GetAudioParamString(params) - << "]"; + LOG(INFO) << __func__ << ": ParamsMap=[" << GetAudioParamString(params) << "]"; return retval; } -static char* in_get_parameters(const struct audio_stream* stream, - const char* keys) { +static char* in_get_parameters(const struct audio_stream* stream, const char* keys) { const auto* in = reinterpret_cast(stream); std::unique_lock lock(in->mutex_); - LOG(VERBOSE) << __func__ - << ": NOT HANDLED! state=" << in->bluetooth_input_->GetState() + LOG(VERBOSE) << __func__ << ": NOT HANDLED! state=" << in->bluetooth_input_->GetState() << ", keys=[" << keys << "]"; std::unordered_map params = ParseAudioParams(keys); - if (params.empty()) return strdup(""); + if (params.empty()) { + return strdup(""); + } audio_config_t audio_cfg; if (in->bluetooth_input_->LoadAudioConfig(&audio_cfg)) { @@ -1050,16 +990,14 @@ static char* in_get_parameters(const struct audio_stream* stream, return strdup(result.c_str()); } -static int in_add_audio_effect(const struct audio_stream* stream, - effect_handle_t effect) { +static int in_add_audio_effect(const struct audio_stream* stream, effect_handle_t effect) { const auto* in = reinterpret_cast(stream); LOG(VERBOSE) << __func__ << ": state=" << in->bluetooth_input_->GetState() << ", effect=" << effect; return 0; } -static int in_remove_audio_effect(const struct audio_stream* stream, - effect_handle_t effect) { +static int in_remove_audio_effect(const struct audio_stream* stream, effect_handle_t effect) { const auto* in = reinterpret_cast(stream); LOG(VERBOSE) << __func__ << ": state=" << in->bluetooth_input_->GetState() << ", effect=" << effect; @@ -1068,39 +1006,35 @@ static int in_remove_audio_effect(const struct audio_stream* stream, static int in_set_gain(struct audio_stream_in* stream, float gain) { const auto* in = reinterpret_cast(stream); - LOG(VERBOSE) << __func__ - << ": NOT HANDLED! state=" << in->bluetooth_input_->GetState(); + LOG(VERBOSE) << __func__ << ": NOT HANDLED! state=" << in->bluetooth_input_->GetState(); return 0; } -static ssize_t in_read(struct audio_stream_in* stream, void* buffer, - size_t bytes) { +static ssize_t in_read(struct audio_stream_in* stream, void* buffer, size_t bytes) { auto* in = reinterpret_cast(stream); std::unique_lock lock(in->mutex_); size_t totalRead = 0; /* Give some time to start up */ if (!in_state_transition_timeout(in, lock, BluetoothStreamState::STARTING, - kBluetoothDefaultInputStateTimeoutMs)) + kBluetoothDefaultInputStateTimeoutMs)) { return -EBUSY; + } if (in->bluetooth_input_->GetState() != BluetoothStreamState::STARTED) { LOG(INFO) << __func__ << ": state=" << in->bluetooth_input_->GetState() << " first time bytes=" << bytes; int retval = 0; - LOG(VERBOSE) << __func__ << ": state=" << in->bluetooth_input_->GetState() - << ", starting"; + LOG(VERBOSE) << __func__ << ": state=" << in->bluetooth_input_->GetState() << ", starting"; if (in->bluetooth_input_->GetState() == BluetoothStreamState::STANDBY) { retval = (in->bluetooth_input_->Start() ? 0 : -EIO); - } else if (in->bluetooth_input_->GetState() == - BluetoothStreamState::SUSPENDING) { + } else if (in->bluetooth_input_->GetState() == BluetoothStreamState::SUSPENDING) { LOG(WARNING) << __func__ << ": state=" << in->bluetooth_input_->GetState() << " NOT ready to start?!"; retval = -EBUSY; - } else if (in->bluetooth_input_->GetState() == - BluetoothStreamState::DISABLED) { + } else if (in->bluetooth_input_->GetState() == BluetoothStreamState::DISABLED) { LOG(WARNING) << __func__ << ": state=" << in->bluetooth_input_->GetState() << " NOT allow to start?!"; retval = -EINVAL; @@ -1134,14 +1068,13 @@ static ssize_t in_read(struct audio_stream_in* stream, void* buffer, static uint32_t in_get_input_frames_lost(struct audio_stream_in* stream) { const auto* in = reinterpret_cast(stream); - LOG(VERBOSE) << __func__ - << ": NOT HANDLED! state=" << in->bluetooth_input_->GetState(); + LOG(VERBOSE) << __func__ << ": NOT HANDLED! state=" << in->bluetooth_input_->GetState(); return 0; } -static int in_get_capture_position(const struct audio_stream_in* stream, - int64_t* frames, int64_t* time) { +static int in_get_capture_position(const struct audio_stream_in* stream, int64_t* frames, + int64_t* time) { if (stream == NULL || frames == NULL || time == NULL) { return -EINVAL; } @@ -1159,26 +1092,22 @@ static int in_get_capture_position(const struct audio_stream_in* stream, static int in_start(const struct audio_stream_in* stream) { const auto* in = reinterpret_cast(stream); - LOG(VERBOSE) << __func__ - << ": NOT HANDLED! state=" << in->bluetooth_input_->GetState(); + LOG(VERBOSE) << __func__ << ": NOT HANDLED! state=" << in->bluetooth_input_->GetState(); return 0; } static int in_stop(const struct audio_stream_in* stream) { const auto* in = reinterpret_cast(stream); - LOG(VERBOSE) << __func__ - << ": NOT HANDLED! state=" << in->bluetooth_input_->GetState(); + LOG(VERBOSE) << __func__ << ": NOT HANDLED! state=" << in->bluetooth_input_->GetState(); return 0; } -static int in_create_mmap_buffer(const struct audio_stream_in* stream, - int32_t min_size_frames, +static int in_create_mmap_buffer(const struct audio_stream_in* stream, int32_t min_size_frames, struct audio_mmap_buffer_info* info) { const auto* in = reinterpret_cast(stream); - LOG(VERBOSE) << __func__ - << ": NOT HANDLED! state=" << in->bluetooth_input_->GetState(); + LOG(VERBOSE) << __func__ << ": NOT HANDLED! state=" << in->bluetooth_input_->GetState(); return -ENOSYS; } @@ -1186,18 +1115,16 @@ static int in_create_mmap_buffer(const struct audio_stream_in* stream, static int in_get_mmap_position(const struct audio_stream_in* stream, struct audio_mmap_position* position) { const auto* in = reinterpret_cast(stream); - LOG(VERBOSE) << __func__ - << ": NOT HANDLED! state=" << in->bluetooth_input_->GetState(); + LOG(VERBOSE) << __func__ << ": NOT HANDLED! state=" << in->bluetooth_input_->GetState(); return -ENOSYS; } -static int in_get_active_microphones( - const struct audio_stream_in* stream, - struct audio_microphone_characteristic_t* mic_array, size_t* mic_count) { +static int in_get_active_microphones(const struct audio_stream_in* stream, + struct audio_microphone_characteristic_t* mic_array, + size_t* mic_count) { const auto* in = reinterpret_cast(stream); - LOG(VERBOSE) << __func__ - << ": NOT HANDLED! state=" << in->bluetooth_input_->GetState(); + LOG(VERBOSE) << __func__ << ": NOT HANDLED! state=" << in->bluetooth_input_->GetState(); return -ENOSYS; } @@ -1205,60 +1132,51 @@ static int in_get_active_microphones( static int in_set_microphone_direction(const struct audio_stream_in* stream, audio_microphone_direction_t direction) { const auto* in = reinterpret_cast(stream); - LOG(VERBOSE) << __func__ - << ": NOT HANDLED! state=" << in->bluetooth_input_->GetState(); + LOG(VERBOSE) << __func__ << ": NOT HANDLED! state=" << in->bluetooth_input_->GetState(); return -ENOSYS; } -static int in_set_microphone_field_dimension( - const struct audio_stream_in* stream, float zoom) { +static int in_set_microphone_field_dimension(const struct audio_stream_in* stream, float zoom) { const auto* in = reinterpret_cast(stream); - LOG(VERBOSE) << __func__ - << ": NOT HANDLED! state=" << in->bluetooth_input_->GetState(); + LOG(VERBOSE) << __func__ << ": NOT HANDLED! state=" << in->bluetooth_input_->GetState(); return -ENOSYS; } -static void in_update_sink_metadata_v7( - struct audio_stream_in* stream, - const struct sink_metadata_v7* sink_metadata) { +static void in_update_sink_metadata_v7(struct audio_stream_in* stream, + const struct sink_metadata_v7* sink_metadata) { LOG(INFO) << __func__; if (sink_metadata == nullptr || sink_metadata->track_count == 0) { return; } const auto* in = reinterpret_cast(stream); - LOG(INFO) << __func__ << ": state=" << in->bluetooth_input_->GetState() - << ", " << sink_metadata->track_count << " track(s)"; + LOG(INFO) << __func__ << ": state=" << in->bluetooth_input_->GetState() << ", " + << sink_metadata->track_count << " track(s)"; if (!in->is_aidl) { - LOG(WARNING) << __func__ - << " is only supported in AIDL but using HIDL now!"; + LOG(WARNING) << __func__ << " is only supported in AIDL but using HIDL now!"; return; } static_cast<::android::bluetooth::audio::aidl::BluetoothAudioPortAidl*>( - in->bluetooth_input_.get()) - ->UpdateSinkMetadata(sink_metadata); + in->bluetooth_input_.get()) + ->UpdateSinkMetadata(sink_metadata); } -int adev_open_input_stream(struct audio_hw_device* dev, - audio_io_handle_t handle, audio_devices_t devices, - struct audio_config* config, - struct audio_stream_in** stream_in, - audio_input_flags_t flags __unused, - const char* address __unused, - audio_source_t source __unused) { +int adev_open_input_stream(struct audio_hw_device* dev, audio_io_handle_t handle, + audio_devices_t devices, struct audio_config* config, + struct audio_stream_in** stream_in, audio_input_flags_t flags __unused, + const char* address __unused, audio_source_t source __unused) { *stream_in = nullptr; auto in = std::make_unique(); - if (::aidl::android::hardware::bluetooth::audio::BluetoothAudioSession:: - IsAidlAvailable()) { - in->bluetooth_input_ = std::make_unique< - ::android::bluetooth::audio::aidl::BluetoothAudioPortAidlIn>(); + if (::aidl::android::hardware::bluetooth::audio::BluetoothAudioSession::IsAidlAvailable()) { + in->bluetooth_input_ = + std::make_unique<::android::bluetooth::audio::aidl::BluetoothAudioPortAidlIn>(); in->is_aidl = true; } else { - in->bluetooth_input_ = std::make_unique< - ::android::bluetooth::audio::hidl::BluetoothAudioPortHidlIn>(); + in->bluetooth_input_ = + std::make_unique<::android::bluetooth::audio::hidl::BluetoothAudioPortHidlIn>(); in->is_aidl = false; } if (!in->bluetooth_input_->SetUp(devices)) { @@ -1291,8 +1209,7 @@ int adev_open_input_stream(struct audio_hw_device* dev, in->stream_in_.get_mmap_position = in_get_mmap_position; in->stream_in_.get_active_microphones = in_get_active_microphones; in->stream_in_.set_microphone_direction = in_set_microphone_direction; - in->stream_in_.set_microphone_field_dimension = - in_set_microphone_field_dimension; + in->stream_in_.set_microphone_field_dimension = in_set_microphone_field_dimension; in->stream_in_.update_sink_metadata_v7 = in_update_sink_metadata_v7; if (!in->bluetooth_input_->LoadAudioConfig(config)) { @@ -1307,16 +1224,14 @@ int adev_open_input_stream(struct audio_hw_device* dev, // frame is number of samples per channel size_t preferred_data_interval_us = kBluetoothDefaultInputBufferMs * 1000; - if (in->bluetooth_input_->GetPreferredDataIntervalUs( - &preferred_data_interval_us) && + if (in->bluetooth_input_->GetPreferredDataIntervalUs(&preferred_data_interval_us) && preferred_data_interval_us != 0) { in->preferred_data_interval_us = preferred_data_interval_us; } else { in->preferred_data_interval_us = kBluetoothDefaultInputBufferMs * 1000; } - in->frames_count_ = - FrameCount(in->preferred_data_interval_us, in->sample_rate_); + in->frames_count_ = FrameCount(in->preferred_data_interval_us, in->sample_rate_); in->frames_presented_ = 0; BluetoothStreamIn* in_ptr = in.release(); @@ -1324,15 +1239,14 @@ int adev_open_input_stream(struct audio_hw_device* dev, LOG(INFO) << __func__ << ": state=" << in_ptr->bluetooth_input_->GetState() << ", sample_rate=" << in_ptr->sample_rate_ << ", channels=" << StringPrintf("%#x", in_ptr->channel_mask_) - << ", format=" << in_ptr->format_ << ", preferred_data_interval_us=" - << in_ptr->preferred_data_interval_us + << ", format=" << in_ptr->format_ + << ", preferred_data_interval_us=" << in_ptr->preferred_data_interval_us << ", frames=" << in_ptr->frames_count_; return 0; } -void adev_close_input_stream(struct audio_hw_device* dev, - struct audio_stream_in* stream) { +void adev_close_input_stream(struct audio_hw_device* dev, struct audio_stream_in* stream) { auto* in = reinterpret_cast(stream); if (in->bluetooth_input_->GetState() != BluetoothStreamState::DISABLED) { @@ -1340,8 +1254,7 @@ void adev_close_input_stream(struct audio_hw_device* dev, } in->bluetooth_input_->TearDown(); - LOG(VERBOSE) << __func__ << ": state=" << in->bluetooth_input_->GetState() - << ", stopped"; + LOG(VERBOSE) << __func__ << ": state=" << in->bluetooth_input_->GetState() << ", stopped"; delete in; } diff --git a/system/audio_bluetooth_hw/stream_apis.h b/system/audio_bluetooth_hw/stream_apis.h index d1010273922..23c6ee153ab 100644 --- a/system/audio_bluetooth_hw/stream_apis.h +++ b/system/audio_bluetooth_hw/stream_apis.h @@ -25,8 +25,7 @@ #include "device_port_proxy_hidl.h" constexpr unsigned int kBluetoothDefaultSampleRate = 44100; -constexpr audio_format_t kBluetoothDefaultAudioFormatBitsPerSample = - AUDIO_FORMAT_PCM_16_BIT; +constexpr audio_format_t kBluetoothDefaultAudioFormatBitsPerSample = AUDIO_FORMAT_PCM_16_BIT; constexpr unsigned int kBluetoothDefaultInputBufferMs = 20; constexpr unsigned int kBluetoothDefaultInputStateTimeoutMs = 20; @@ -34,10 +33,8 @@ constexpr unsigned int kBluetoothDefaultInputStateTimeoutMs = 20; constexpr unsigned int kBluetoothDefaultOutputBufferMs = 10; constexpr unsigned int kBluetoothSpatializerOutputBufferMs = 10; -constexpr audio_channel_mask_t kBluetoothDefaultOutputChannelModeMask = - AUDIO_CHANNEL_OUT_STEREO; -constexpr audio_channel_mask_t kBluetoothDefaultInputChannelModeMask = - AUDIO_CHANNEL_IN_MONO; +constexpr audio_channel_mask_t kBluetoothDefaultOutputChannelModeMask = AUDIO_CHANNEL_OUT_STEREO; +constexpr audio_channel_mask_t kBluetoothDefaultInputChannelModeMask = AUDIO_CHANNEL_IN_MONO; enum class BluetoothStreamState : uint8_t { DISABLED = 0, // This stream is closing or set param "suspend=true" @@ -54,8 +51,7 @@ struct BluetoothStreamOut { // Must be the first member so it can be cast from audio_stream // or audio_stream_out pointer audio_stream_out stream_out_{}; - std::unique_ptr<::android::bluetooth::audio::BluetoothAudioPort> - bluetooth_output_; + std::unique_ptr<::android::bluetooth::audio::BluetoothAudioPort> bluetooth_output_; bool is_aidl; int64_t last_write_time_us_; // Audio PCM Configs @@ -79,8 +75,7 @@ struct BluetoothAudioDevice { audio_hw_device audio_device_{}; // protect against device->output and stream_out from being inconsistent std::mutex mutex_; - std::list opened_stream_outs_ = - std::list(0); + std::list opened_stream_outs_ = std::list(0); uint32_t next_unique_id = 1; }; @@ -88,8 +83,7 @@ struct BluetoothStreamIn { // Must be the first member so it can be cast from audio_stream // or audio_stream_in pointer audio_stream_in stream_in_; - std::unique_ptr<::android::bluetooth::audio::BluetoothAudioPort> - bluetooth_input_; + std::unique_ptr<::android::bluetooth::audio::BluetoothAudioPort> bluetooth_input_; bool is_aidl; int64_t last_read_time_us_; // Audio PCM Configs @@ -105,26 +99,19 @@ struct BluetoothStreamIn { mutable std::mutex mutex_; }; -int adev_open_output_stream(struct audio_hw_device* dev, - audio_io_handle_t handle, audio_devices_t devices, - audio_output_flags_t flags, - struct audio_config* config, - struct audio_stream_out** stream_out, +int adev_open_output_stream(struct audio_hw_device* dev, audio_io_handle_t handle, + audio_devices_t devices, audio_output_flags_t flags, + struct audio_config* config, struct audio_stream_out** stream_out, const char* address __unused); -void adev_close_output_stream(struct audio_hw_device* dev, - struct audio_stream_out* stream); +void adev_close_output_stream(struct audio_hw_device* dev, struct audio_stream_out* stream); size_t adev_get_input_buffer_size(const struct audio_hw_device* dev, const struct audio_config* config); -int adev_open_input_stream(struct audio_hw_device* dev, - audio_io_handle_t handle, audio_devices_t devices, - struct audio_config* config, - struct audio_stream_in** stream_in, - audio_input_flags_t flags __unused, - const char* address __unused, - audio_source_t source __unused); +int adev_open_input_stream(struct audio_hw_device* dev, audio_io_handle_t handle, + audio_devices_t devices, struct audio_config* config, + struct audio_stream_in** stream_in, audio_input_flags_t flags __unused, + const char* address __unused, audio_source_t source __unused); -void adev_close_input_stream(struct audio_hw_device* dev, - struct audio_stream_in* in); +void adev_close_input_stream(struct audio_hw_device* dev, struct audio_stream_in* in); diff --git a/system/audio_bluetooth_hw/utils.cc b/system/audio_bluetooth_hw/utils.cc index a74a83b76c2..f49ac1ec653 100644 --- a/system/audio_bluetooth_hw/utils.cc +++ b/system/audio_bluetooth_hw/utils.cc @@ -30,8 +30,7 @@ namespace bluetooth { namespace audio { namespace utils { -std::unordered_map ParseAudioParams( - const std::string& params) { +std::unordered_map ParseAudioParams(const std::string& params) { std::vector segments = android::base::Split(params, ";"); std::unordered_map params_map; for (const auto& segment : segments) { @@ -48,8 +47,7 @@ std::unordered_map ParseAudioParams( return params_map; } -std::string GetAudioParamString( - std::unordered_map& params_map) { +std::string GetAudioParamString(std::unordered_map& params_map) { std::ostringstream sout; for (const auto& ptr : params_map) { sout << "key: '" << ptr.first << "' value: '" << ptr.second << "'\n"; diff --git a/system/audio_bluetooth_hw/utils.h b/system/audio_bluetooth_hw/utils.h index bdd8a9bc3f8..184106fdb67 100644 --- a/system/audio_bluetooth_hw/utils.h +++ b/system/audio_bluetooth_hw/utils.h @@ -32,15 +32,13 @@ namespace utils { // "key0=value0;key1=value1;" -> map: [key0]="value0" [key1]="value1" // "key0=;key1=value1;" -> map: [key0]="" [key1]="value1" // "=value0;key1=value1;" -> map: [key1]="value1" -std::unordered_map ParseAudioParams( - const std::string& params); +std::unordered_map ParseAudioParams(const std::string& params); // Dumps the contents of the hash_map to the log for debugging purposes. // If |map| is not NULL, all entries of |map| will be dumped, otherwise // nothing will be dumped. Note that this function does not take the ownership // of the |map|. -std::string GetAudioParamString( - std::unordered_map& params_map); +std::string GetAudioParamString(std::unordered_map& params_map); size_t FrameCount(uint64_t microseconds, uint32_t sample_rate); } // namespace utils diff --git a/system/audio_bluetooth_hw/utils_unittest.cc b/system/audio_bluetooth_hw/utils_unittest.cc index 1bcd5ddc66e..95d11f95fe1 100644 --- a/system/audio_bluetooth_hw/utils_unittest.cc +++ b/system/audio_bluetooth_hw/utils_unittest.cc @@ -14,10 +14,11 @@ * limitations under the License. */ +#include "utils.h" + #include -#include -#include "utils.h" +#include namespace { @@ -25,7 +26,7 @@ using ::android::bluetooth::audio::utils::FrameCount; using ::android::bluetooth::audio::utils::ParseAudioParams; class UtilsTest : public testing::Test { - protected: +protected: void SetUp() override {} void TearDown() override { map_.clear(); } diff --git a/system/audio_hal_interface/a2dp_encoding.cc b/system/audio_hal_interface/a2dp_encoding.cc index 266944df2d1..c38745a243a 100644 --- a/system/audio_hal_interface/a2dp_encoding.cc +++ b/system/audio_hal_interface/a2dp_encoding.cc @@ -27,21 +27,18 @@ namespace audio { namespace a2dp { bool update_codec_offloading_capabilities( - const std::vector& framework_preference, - bool supports_a2dp_hw_offload_v2) { - if (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::HIDL) { - return hidl::a2dp::update_codec_offloading_capabilities( - framework_preference); + const std::vector& framework_preference, + bool supports_a2dp_hw_offload_v2) { + if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::HIDL) { + return hidl::a2dp::update_codec_offloading_capabilities(framework_preference); } - return aidl::a2dp::update_codec_offloading_capabilities( - framework_preference, supports_a2dp_hw_offload_v2); + return aidl::a2dp::update_codec_offloading_capabilities(framework_preference, + supports_a2dp_hw_offload_v2); } // Check if new bluetooth_audio is enabled bool is_hal_enabled() { - if (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::HIDL) { + if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::HIDL) { return hidl::a2dp::is_hal_2_0_enabled(); } return aidl::a2dp::is_hal_enabled(); @@ -49,8 +46,7 @@ bool is_hal_enabled() { // Check if new bluetooth_audio is running with offloading encoders bool is_hal_offloading() { - if (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::HIDL) { + if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::HIDL) { return hidl::a2dp::is_hal_2_0_offloading(); } return aidl::a2dp::is_hal_offloading(); @@ -58,8 +54,7 @@ bool is_hal_offloading() { // Initialize BluetoothAudio HAL: openProvider bool init(bluetooth::common::MessageLoopThread* message_loop) { - if (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::HIDL) { + if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::HIDL) { return hidl::a2dp::init(message_loop); } return aidl::a2dp::init(message_loop); @@ -67,8 +62,7 @@ bool init(bluetooth::common::MessageLoopThread* message_loop) { // Clean up BluetoothAudio HAL void cleanup() { - if (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::HIDL) { + if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::HIDL) { hidl::a2dp::cleanup(); return; } @@ -77,8 +71,7 @@ void cleanup() { // Set up the codec into BluetoothAudio HAL bool setup_codec() { - if (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::HIDL) { + if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::HIDL) { return hidl::a2dp::setup_codec(); } return aidl::a2dp::setup_codec(); @@ -87,8 +80,7 @@ bool setup_codec() { // Send command to the BluetoothAudio HAL: StartSession, EndSession, // StreamStarted, StreamSuspended void start_session() { - if (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::HIDL) { + if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::HIDL) { hidl::a2dp::start_session(); return; } @@ -96,20 +88,17 @@ void start_session() { } void end_session() { - if (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::AIDL) { + if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::AIDL) { return aidl::a2dp::end_session(); } - if (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::HIDL) { + if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::HIDL) { hidl::a2dp::end_session(); return; } } void ack_stream_started(BluetoothAudioStatus status) { - if (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::HIDL) { + if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::HIDL) { hidl::a2dp::ack_stream_started(status); return; } @@ -117,8 +106,7 @@ void ack_stream_started(BluetoothAudioStatus status) { } void ack_stream_suspended(BluetoothAudioStatus status) { - if (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::HIDL) { + if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::HIDL) { hidl::a2dp::ack_stream_suspended(status); return; } @@ -127,8 +115,7 @@ void ack_stream_suspended(BluetoothAudioStatus status) { // Read from the FMQ of BluetoothAudio HAL size_t read(uint8_t* p_buf, uint32_t len) { - if (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::HIDL) { + if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::HIDL) { return hidl::a2dp::read(p_buf, len); } return aidl::a2dp::read(p_buf, len); @@ -136,8 +123,7 @@ size_t read(uint8_t* p_buf, uint32_t len) { // Update A2DP delay report to BluetoothAudio HAL void set_remote_delay(uint16_t delay_report) { - if (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::HIDL) { + if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::HIDL) { hidl::a2dp::set_remote_delay(delay_report); return; } @@ -146,8 +132,7 @@ void set_remote_delay(uint16_t delay_report) { // Set low latency buffer mode allowed or disallowed void set_audio_low_latency_mode_allowed(bool allowed) { - if (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::AIDL) { + if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::AIDL) { aidl::a2dp::set_low_latency_mode_allowed(allowed); } } @@ -155,8 +140,7 @@ void set_audio_low_latency_mode_allowed(bool allowed) { // Check if OPUS codec is supported bool is_opus_supported() { // OPUS codec was added after HIDL HAL was frozen - if (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::AIDL) { + if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::AIDL) { return true; } return false; @@ -165,21 +149,17 @@ bool is_opus_supported() { namespace provider { // Lookup the codec info in the list of supported offloaded sink codecs. -std::optional sink_codec_index( - const uint8_t* p_codec_info) { - return (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::AIDL) - ? aidl::a2dp::provider::sink_codec_index(p_codec_info) - : std::nullopt; +std::optional sink_codec_index(const uint8_t* p_codec_info) { + return (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::AIDL) + ? aidl::a2dp::provider::sink_codec_index(p_codec_info) + : std::nullopt; } // Lookup the codec info in the list of supported offloaded source codecs. -std::optional source_codec_index( - const uint8_t* p_codec_info) { - return (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::AIDL) - ? aidl::a2dp::provider::source_codec_index(p_codec_info) - : std::nullopt; +std::optional source_codec_index(const uint8_t* p_codec_info) { + return (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::AIDL) + ? aidl::a2dp::provider::source_codec_index(p_codec_info) + : std::nullopt; } // Return the name of the codec which is assigned to the input index. @@ -188,45 +168,38 @@ std::optional source_codec_index( // BTAV_A2DP_CODEC_INDEX_SOURCE_EXT_MIN..BTAV_A2DP_CODEC_INDEX_SOURCE_EXT_MAX. // Returns nullopt if the codec_index is not assigned or codec extensibility // is not supported or enabled. -std::optional codec_index_str( - btav_a2dp_codec_index_t codec_index) { - return (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::AIDL) - ? aidl::a2dp::provider::codec_index_str(codec_index) - : std::nullopt; +std::optional codec_index_str(btav_a2dp_codec_index_t codec_index) { + return (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::AIDL) + ? aidl::a2dp::provider::codec_index_str(codec_index) + : std::nullopt; } // Return true if the codec is supported for the session type // A2DP_HARDWARE_ENCODING_DATAPATH or A2DP_HARDWARE_DECODING_DATAPATH. bool supports_codec(btav_a2dp_codec_index_t codec_index) { - return (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::AIDL) - ? aidl::a2dp::provider::supports_codec(codec_index) - : false; + return (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::AIDL) + ? aidl::a2dp::provider::supports_codec(codec_index) + : false; } // Return the A2DP capabilities for the selected codec. -bool codec_info(btav_a2dp_codec_index_t codec_index, uint64_t* codec_id, - uint8_t* codec_info, btav_a2dp_codec_config_t* codec_config) { - return (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::AIDL) - ? aidl::a2dp::provider::codec_info(codec_index, codec_id, - codec_info, codec_config) - : false; +bool codec_info(btav_a2dp_codec_index_t codec_index, uint64_t* codec_id, uint8_t* codec_info, + btav_a2dp_codec_config_t* codec_config) { + return (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::AIDL) + ? aidl::a2dp::provider::codec_info(codec_index, codec_id, codec_info, codec_config) + : false; } // Query the codec selection fromt the audio HAL. // The HAL is expected to pick the best audio configuration based on the // discovered remote SEPs. std::optional get_a2dp_configuration( - RawAddress peer_address, - std::vector const& remote_seps, - btav_a2dp_codec_config_t const& user_preferences) { - return (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::AIDL) - ? aidl::a2dp::provider::get_a2dp_configuration( - peer_address, remote_seps, user_preferences) - : std::nullopt; + RawAddress peer_address, std::vector const& remote_seps, + btav_a2dp_codec_config_t const& user_preferences) { + return (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::AIDL) + ? aidl::a2dp::provider::get_a2dp_configuration(peer_address, remote_seps, + user_preferences) + : std::nullopt; } // Query the codec parameters from the audio HAL. @@ -236,16 +209,14 @@ std::optional get_a2dp_configuration( // In case any of these checks fails, the corresponding A2DP // status is returned. If the configuration is valid and supported, // A2DP_OK is returned. -tA2DP_STATUS parse_a2dp_configuration( - btav_a2dp_codec_index_t codec_index, const uint8_t* codec_info, - btav_a2dp_codec_config_t* codec_parameters, - std::vector* vendor_specific_parameters) { - return (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::AIDL) - ? aidl::a2dp::provider::parse_a2dp_configuration( - codec_index, codec_info, codec_parameters, - vendor_specific_parameters) - : A2DP_FAIL; +tA2DP_STATUS parse_a2dp_configuration(btav_a2dp_codec_index_t codec_index, + const uint8_t* codec_info, + btav_a2dp_codec_config_t* codec_parameters, + std::vector* vendor_specific_parameters) { + return (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::AIDL) + ? aidl::a2dp::provider::parse_a2dp_configuration( + codec_index, codec_info, codec_parameters, vendor_specific_parameters) + : A2DP_FAIL; } } // namespace provider diff --git a/system/audio_hal_interface/a2dp_encoding.h b/system/audio_hal_interface/a2dp_encoding.h index 80066ddb6e3..e9fa447f5da 100644 --- a/system/audio_hal_interface/a2dp_encoding.h +++ b/system/audio_hal_interface/a2dp_encoding.h @@ -40,8 +40,8 @@ enum class BluetoothAudioStatus { }; bool update_codec_offloading_capabilities( - const std::vector& framework_preference, - bool supports_a2dp_hw_offload_v2); + const std::vector& framework_preference, + bool supports_a2dp_hw_offload_v2); // Check if new bluetooth_audio is enabled bool is_hal_enabled(); @@ -81,12 +81,10 @@ bool is_opus_supported(); namespace provider { // Lookup the codec info in the list of supported offloaded sink codecs. -std::optional sink_codec_index( - const uint8_t* p_codec_info); +std::optional sink_codec_index(const uint8_t* p_codec_info); // Lookup the codec info in the list of supported offloaded source codecs. -std::optional source_codec_index( - const uint8_t* p_codec_info); +std::optional source_codec_index(const uint8_t* p_codec_info); // Return the name of the codec which is assigned to the input index. // The codec index must be in the ranges @@ -103,8 +101,8 @@ bool supports_codec(btav_a2dp_codec_index_t codec_index); // Return the A2DP capabilities for the selected codec. // `codec_info` returns the OTA codec capabilities, `codec_config` // returns the supported capabilities in a generic format. -bool codec_info(btav_a2dp_codec_index_t codec_index, uint64_t* codec_id, - uint8_t* codec_info, btav_a2dp_codec_config_t* codec_config); +bool codec_info(btav_a2dp_codec_index_t codec_index, uint64_t* codec_id, uint8_t* codec_info, + btav_a2dp_codec_config_t* codec_config); struct a2dp_configuration { int remote_seid; @@ -121,7 +119,9 @@ struct a2dp_configuration { for (int i = 0; i < AVDT_CODEC_SIZE; i++) { os << "0x" << std::hex << std::setw(2) << std::setfill('0') << static_cast(codec_config[i]); - if (i != AVDT_CODEC_SIZE - 1) os << ","; + if (i != AVDT_CODEC_SIZE - 1) { + os << ","; + } } os << "}"; os << "}"; @@ -142,7 +142,9 @@ struct a2dp_remote_capabilities { for (int i = 0; i < AVDT_CODEC_SIZE; i++) { os << "0x" << std::hex << std::setw(2) << std::setfill('0') << static_cast(capabilities[i]); - if (i != AVDT_CODEC_SIZE - 1) os << ","; + if (i != AVDT_CODEC_SIZE - 1) { + os << ","; + } } } os << "}"; @@ -155,18 +157,17 @@ struct a2dp_remote_capabilities { // The HAL is expected to pick the best audio configuration based on the // discovered remote SEPs. std::optional get_a2dp_configuration( - RawAddress peer_address, - std::vector const& remote_seps, - btav_a2dp_codec_config_t const& user_preferences); + RawAddress peer_address, std::vector const& remote_seps, + btav_a2dp_codec_config_t const& user_preferences); // Query the codec parameters from the audio HAL. // The HAL is expected to parse the codec configuration // received from the peer and decide whether accept // the it or not. -tA2DP_STATUS parse_a2dp_configuration( - btav_a2dp_codec_index_t codec_index, const uint8_t* codec_info, - btav_a2dp_codec_config_t* codec_parameters, - std::vector* vendor_specific_parameters); +tA2DP_STATUS parse_a2dp_configuration(btav_a2dp_codec_index_t codec_index, + const uint8_t* codec_info, + btav_a2dp_codec_config_t* codec_parameters, + std::vector* vendor_specific_parameters); } // namespace provider } // namespace a2dp @@ -177,4 +178,4 @@ namespace fmt { template <> struct formatter<::bluetooth::audio::a2dp::BluetoothAudioStatus> : enum_formatter<::bluetooth::audio::a2dp::BluetoothAudioStatus> {}; -} // namespace fmt +} // namespace fmt diff --git a/system/audio_hal_interface/a2dp_encoding_host.cc b/system/audio_hal_interface/a2dp_encoding_host.cc index 66b36db51ea..3b93cf536d3 100644 --- a/system/audio_hal_interface/a2dp_encoding_host.cc +++ b/system/audio_hal_interface/a2dp_encoding_host.cc @@ -60,10 +60,8 @@ namespace { std::unique_ptr a2dp_uipc = nullptr; -static void btif_a2dp_data_cb([[maybe_unused]] tUIPC_CH_ID ch_id, - tUIPC_EVENT event) { - bluetooth::log::warn("BTIF MEDIA (A2DP-DATA) EVENT {}", - dump_uipc_event(event)); +static void btif_a2dp_data_cb([[maybe_unused]] tUIPC_CH_ID ch_id, tUIPC_EVENT event) { + bluetooth::log::warn("BTIF MEDIA (A2DP-DATA) EVENT {}", dump_uipc_event(event)); switch (event) { case UIPC_OPEN_EVT: @@ -71,8 +69,7 @@ static void btif_a2dp_data_cb([[maybe_unused]] tUIPC_CH_ID ch_id, * Read directly from media task from here on (keep callback for * connection events. */ - UIPC_Ioctl(*a2dp_uipc, UIPC_CH_ID_AV_AUDIO, - UIPC_REG_REMOVE_ACTIVE_READSET, NULL); + UIPC_Ioctl(*a2dp_uipc, UIPC_CH_ID_AV_AUDIO, UIPC_REG_REMOVE_ACTIVE_READSET, NULL); UIPC_Ioctl(*a2dp_uipc, UIPC_CH_ID_AV_AUDIO, UIPC_SET_READ_POLL_TMO, reinterpret_cast(A2DP_DATA_READ_POLL_MS)); @@ -97,8 +94,7 @@ static void btif_a2dp_data_cb([[maybe_unused]] tUIPC_CH_ID ch_id, // server should be in the same group that BT stack runs with to access // A2DP socket. static void a2dp_data_path_open() { - UIPC_Open(*a2dp_uipc, UIPC_CH_ID_AV_AUDIO, btif_a2dp_data_cb, - A2DP_HOST_DATA_PATH); + UIPC_Open(*a2dp_uipc, UIPC_CH_ID_AV_AUDIO, btif_a2dp_data_cb, A2DP_HOST_DATA_PATH); struct group* grp = getgrnam(A2DP_HOST_DATA_GROUP); chmod(A2DP_HOST_DATA_PATH, 0770); if (grp) { @@ -208,22 +204,20 @@ bool SuspendRequest() { // Invoked by audio server to check audio presentation position periodically. PresentationPosition GetPresentationPosition() { PresentationPosition presentation_position{ - .remote_delay_report_ns = remote_delay_report_ * 100000u, - .total_bytes_read = total_bytes_read_, - .data_position = data_position_, + .remote_delay_report_ns = remote_delay_report_ * 100000u, + .total_bytes_read = total_bytes_read_, + .data_position = data_position_, }; return presentation_position; } // delay reports from AVDTP is based on 1/10 ms (100us) -void set_remote_delay(uint16_t delay_report) { - remote_delay_report_ = delay_report; -} +void set_remote_delay(uint16_t delay_report) { remote_delay_report_ = delay_report; } // Inform audio server about offloading codec; not used for now bool update_codec_offloading_capabilities( - const std::vector& framework_preference, - bool supports_a2dp_hw_offload_v2) { + const std::vector& framework_preference, + bool supports_a2dp_hw_offload_v2) { return false; } @@ -272,8 +266,7 @@ void end_session() { a2dp_pending_cmd_ = A2DP_CTRL_CMD_NONE; } -void set_audio_low_latency_mode_allowed(bool allowed){ -} +void set_audio_low_latency_mode_allowed(bool allowed) {} void ack_stream_started(BluetoothAudioStatus /*ack*/) { a2dp_pending_cmd_ = A2DP_CTRL_CMD_NONE; @@ -305,14 +298,12 @@ bool is_opus_supported() { return true; } namespace provider { // Lookup the codec info in the list of supported offloaded sink codecs. -std::optional sink_codec_index( - const uint8_t* p_codec_info) { +std::optional sink_codec_index(const uint8_t* p_codec_info) { return std::nullopt; } // Lookup the codec info in the list of supported offloaded source codecs. -std::optional source_codec_index( - const uint8_t* p_codec_info) { +std::optional source_codec_index(const uint8_t* p_codec_info) { return std::nullopt; } @@ -322,8 +313,7 @@ std::optional source_codec_index( // BTAV_A2DP_CODEC_INDEX_SOURCE_EXT_MIN..BTAV_A2DP_CODEC_INDEX_SOURCE_EXT_MAX. // Returns nullopt if the codec_index is not assigned or codec extensibility // is not supported or enabled. -std::optional codec_index_str( - btav_a2dp_codec_index_t codec_index) { +std::optional codec_index_str(btav_a2dp_codec_index_t codec_index) { return std::nullopt; } @@ -332,8 +322,8 @@ std::optional codec_index_str( bool supports_codec(btav_a2dp_codec_index_t codec_index) { return false; } // Return the A2DP capabilities for the selected codec. -bool codec_info(btav_a2dp_codec_index_t codec_index, uint64_t* codec_id, - uint8_t* codec_info, btav_a2dp_codec_config_t* codec_config) { +bool codec_info(btav_a2dp_codec_index_t codec_index, uint64_t* codec_id, uint8_t* codec_info, + btav_a2dp_codec_config_t* codec_config) { return false; } @@ -341,9 +331,8 @@ bool codec_info(btav_a2dp_codec_index_t codec_index, uint64_t* codec_id, // The HAL is expected to pick the best audio configuration based on the // discovered remote SEPs. std::optional get_a2dp_configuration( - RawAddress peer_address, - std::vector const& remote_seps, - btav_a2dp_codec_config_t const& user_preferences) { + RawAddress peer_address, std::vector const& remote_seps, + btav_a2dp_codec_config_t const& user_preferences) { return std::nullopt; } @@ -354,10 +343,10 @@ std::optional get_a2dp_configuration( // In case any of these checks fails, the corresponding A2DP // status is returned. If the configuration is valid and supported, // A2DP_OK is returned. -tA2DP_STATUS parse_a2dp_configuration( - btav_a2dp_codec_index_t codec_index, const uint8_t* codec_info, - btav_a2dp_codec_config_t* codec_parameters, - std::vector* vendor_specific_parameters) { +tA2DP_STATUS parse_a2dp_configuration(btav_a2dp_codec_index_t codec_index, + const uint8_t* codec_info, + btav_a2dp_codec_config_t* codec_parameters, + std::vector* vendor_specific_parameters) { return A2DP_FAIL; } diff --git a/system/audio_hal_interface/a2dp_encoding_host.h b/system/audio_hal_interface/a2dp_encoding_host.h index 9f2615b55b1..835d50f022d 100644 --- a/system/audio_hal_interface/a2dp_encoding_host.h +++ b/system/audio_hal_interface/a2dp_encoding_host.h @@ -28,10 +28,8 @@ namespace a2dp { // Audio config from audio server; PCM format for now struct AudioConfig { btav_a2dp_codec_sample_rate_t sample_rate = BTAV_A2DP_CODEC_SAMPLE_RATE_48000; - btav_a2dp_codec_bits_per_sample_t bits_per_sample = - BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24; - btav_a2dp_codec_channel_mode_t channel_mode = - BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; + btav_a2dp_codec_bits_per_sample_t bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24; + btav_a2dp_codec_channel_mode_t channel_mode = BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; }; // Invoked by audio server to set audio config (PCM for now) diff --git a/system/audio_hal_interface/aidl/a2dp_encoding_aidl.cc b/system/audio_hal_interface/aidl/a2dp_encoding_aidl.cc index 2f2b0ec6eb2..79b287ac58e 100644 --- a/system/audio_hal_interface/aidl/a2dp_encoding_aidl.cc +++ b/system/audio_hal_interface/aidl/a2dp_encoding_aidl.cc @@ -37,8 +37,7 @@ struct formatter : enum_formatter {}; template <> struct formatter : enum_formatter {}; template <> -struct formatter : enum_formatter { -}; +struct formatter : enum_formatter {}; } // namespace fmt namespace bluetooth { @@ -175,19 +174,16 @@ void A2dpTransport::SetLatencyMode(LatencyMode latency_mode) { } bool A2dpTransport::GetPresentationPosition(uint64_t* remote_delay_report_ns, - uint64_t* total_bytes_read, - timespec* data_position) { + uint64_t* total_bytes_read, timespec* data_position) { *remote_delay_report_ns = remote_delay_report_ * 100000u; *total_bytes_read = total_bytes_read_; *data_position = data_position_; - log::verbose("delay={}/10ms, data={} byte(s), timestamp={}.{}s", - remote_delay_report_, total_bytes_read_, data_position_.tv_sec, - data_position_.tv_nsec); + log::verbose("delay={}/10ms, data={} byte(s), timestamp={}.{}s", remote_delay_report_, + total_bytes_read_, data_position_.tv_sec, data_position_.tv_nsec); return true; } -void A2dpTransport::SourceMetadataChanged( - const source_metadata_v7_t& source_metadata) { +void A2dpTransport::SourceMetadataChanged(const source_metadata_v7_t& source_metadata) { auto track_count = source_metadata.track_count; auto tracks = source_metadata.tracks; log::verbose("{} track(s) received", track_count); @@ -201,13 +197,9 @@ void A2dpTransport::SourceMetadataChanged( void A2dpTransport::SinkMetadataChanged(const sink_metadata_v7_t&) {} -tA2DP_CTRL_CMD A2dpTransport::GetPendingCmd() const { - return a2dp_pending_cmd_; -} +tA2DP_CTRL_CMD A2dpTransport::GetPendingCmd() const { return a2dp_pending_cmd_; } -void A2dpTransport::ResetPendingCmd() { - a2dp_pending_cmd_ = A2DP_CTRL_CMD_NONE; -} +void A2dpTransport::ResetPendingCmd() { a2dp_pending_cmd_ = A2DP_CTRL_CMD_NONE; } void A2dpTransport::ResetPresentationPosition() { remote_delay_report_ = 0; @@ -229,9 +221,7 @@ void A2dpTransport::LogBytesRead(size_t bytes_read) { ***/ // delay reports from AVDTP is based on 1/10 ms (100us) -void A2dpTransport::SetRemoteDelay(uint16_t delay_report) { - remote_delay_report_ = delay_report; -} +void A2dpTransport::SetRemoteDelay(uint16_t delay_report) { remote_delay_report_ = delay_report; } // Common interface to call-out into Bluetooth Audio HAL BluetoothAudioSinkClientInterface* software_hal_interface = nullptr; @@ -267,8 +257,7 @@ static BluetoothAudioCtrlAck a2dp_ack_to_bt_audio_ctrl_ack(BluetoothAudioStatus } /// Return the MTU for the active peer audio connection. -static uint16_t a2dp_get_peer_mtu(btav_a2dp_codec_index_t codec_index, - uint8_t const* codec_info) { +static uint16_t a2dp_get_peer_mtu(btav_a2dp_codec_index_t codec_index, uint8_t const* codec_info) { RawAddress peer_addr = btif_av_source_active_peer(); tA2DP_ENCODER_INIT_PEER_PARAMS peer_params; bta_av_co_get_peer_params(peer_addr, &peer_params); @@ -361,8 +350,8 @@ bool a2dp_get_selected_hal_codec_config(CodecConfiguration* codec_config) { codec_config->peerMtu = peer_param.peer_mtu; } if (current_codec.codec_type == BTAV_A2DP_CODEC_INDEX_SOURCE_SBC && - codec_config->config.get() - .maxBitpool <= A2DP_SBC_BITPOOL_MIDDLE_QUALITY) { + codec_config->config.get().maxBitpool <= + A2DP_SBC_BITPOOL_MIDDLE_QUALITY) { codec_config->peerMtu = MAX_2MBPS_AVDTP_MTU; } else if (codec_config->peerMtu > MAX_3MBPS_AVDTP_MTU) { codec_config->peerMtu = MAX_3MBPS_AVDTP_MTU; @@ -372,7 +361,9 @@ bool a2dp_get_selected_hal_codec_config(CodecConfiguration* codec_config) { } bool a2dp_get_selected_hal_pcm_config(PcmConfiguration* pcm_config) { - if (pcm_config == nullptr) return false; + if (pcm_config == nullptr) { + return false; + } A2dpCodecConfig* a2dp_codec_configs = bta_av_get_a2dp_current_codec(); if (a2dp_codec_configs == nullptr) { log::warn("failure to get A2DP codec config"); @@ -389,15 +380,14 @@ bool a2dp_get_selected_hal_pcm_config(PcmConfiguration* pcm_config) { pcm_config->dataIntervalUs = bta_av_co_get_encoder_preferred_interval_us(); } - return (pcm_config->sampleRateHz > 0 && pcm_config->bitsPerSample > 0 && - pcm_config->channelMode != ChannelMode::UNKNOWN); + return pcm_config->sampleRateHz > 0 && pcm_config->bitsPerSample > 0 && + pcm_config->channelMode != ChannelMode::UNKNOWN; } // Checking if new bluetooth_audio is supported bool is_hal_force_disabled() { if (!is_configured) { - btaudio_a2dp_disabled = - osi_property_get_bool(BLUETOOTH_AUDIO_HAL_PROP_DISABLED, false); + btaudio_a2dp_disabled = osi_property_get_bool(BLUETOOTH_AUDIO_HAL_PROP_DISABLED, false); is_configured = true; } return btaudio_a2dp_disabled; @@ -406,13 +396,12 @@ bool is_hal_force_disabled() { } // namespace bool update_codec_offloading_capabilities( - const std::vector& framework_preference, - bool supports_a2dp_hw_offload_v2) { + const std::vector& framework_preference, + bool supports_a2dp_hw_offload_v2) { /* Load the provider information if supported by the HAL. */ provider_info = ::bluetooth::audio::aidl::a2dp::ProviderInfo::GetProviderInfo( - supports_a2dp_hw_offload_v2); - return ::bluetooth::audio::aidl::codec::UpdateOffloadingCapabilities( - framework_preference); + supports_a2dp_hw_offload_v2); + return ::bluetooth::audio::aidl::codec::UpdateOffloadingCapabilities(framework_preference); } // Checking if new bluetooth_audio is enabled @@ -430,8 +419,7 @@ bool is_hal_offloading() { // Opens the HAL client interface of the specified session type and check // that is is valid. Returns nullptr if the client interface did not open // properly. -static BluetoothAudioSinkClientInterface* new_hal_interface( - SessionType session_type) { +static BluetoothAudioSinkClientInterface* new_hal_interface(SessionType session_type) { auto a2dp_transport = new A2dpTransport(session_type); auto hal_interface = new BluetoothAudioSinkClientInterface(a2dp_transport); if (hal_interface->IsValid()) { @@ -445,13 +433,11 @@ static BluetoothAudioSinkClientInterface* new_hal_interface( } /// Delete the selected HAL client interface. -static void delete_hal_interface( - BluetoothAudioSinkClientInterface* hal_interface) { +static void delete_hal_interface(BluetoothAudioSinkClientInterface* hal_interface) { if (hal_interface == nullptr) { return; } - auto a2dp_transport = - static_cast(hal_interface->GetTransportInstance()); + auto a2dp_transport = static_cast(hal_interface->GetTransportInstance()); delete a2dp_transport; delete hal_interface; } @@ -474,16 +460,14 @@ bool init(bluetooth::common::MessageLoopThread* /*message_loop*/) { return false; } - software_hal_interface = - new_hal_interface(SessionType::A2DP_SOFTWARE_ENCODING_DATAPATH); + software_hal_interface = new_hal_interface(SessionType::A2DP_SOFTWARE_ENCODING_DATAPATH); if (software_hal_interface == nullptr) { return false; } - if (btif_av_is_a2dp_offload_enabled() && - offloading_hal_interface == nullptr) { + if (btif_av_is_a2dp_offload_enabled() && offloading_hal_interface == nullptr) { offloading_hal_interface = - new_hal_interface(SessionType::A2DP_HARDWARE_OFFLOAD_ENCODING_DATAPATH); + new_hal_interface(SessionType::A2DP_HARDWARE_OFFLOAD_ENCODING_DATAPATH); if (offloading_hal_interface == nullptr) { delete_hal_interface(software_hal_interface); software_hal_interface = nullptr; @@ -492,13 +476,12 @@ bool init(bluetooth::common::MessageLoopThread* /*message_loop*/) { } active_hal_interface = - (offloading_hal_interface != nullptr ? offloading_hal_interface - : software_hal_interface); + (offloading_hal_interface != nullptr ? offloading_hal_interface : software_hal_interface); if (remote_delay != 0) { log::info("restore DELAY {} ms", static_cast(remote_delay / 10.0)); static_cast(active_hal_interface->GetTransportInstance()) - ->SetRemoteDelay(remote_delay); + ->SetRemoteDelay(remote_delay); remote_delay = 0; } return true; @@ -506,7 +489,9 @@ bool init(bluetooth::common::MessageLoopThread* /*message_loop*/) { // Clean up BluetoothAudio HAL void cleanup() { - if (!is_hal_enabled()) return; + if (!is_hal_enabled()) { + return; + } end_session(); auto a2dp_sink = active_hal_interface->GetTransportInstance(); @@ -550,10 +535,9 @@ bool setup_codec() { A2dpStreamConfiguration a2dp_stream_configuration; a2dp_config->copyOutOtaCodecConfig(codec_info); - a2dp_stream_configuration.peerMtu = - a2dp_get_peer_mtu(a2dp_config->codecIndex(), codec_info); + a2dp_stream_configuration.peerMtu = a2dp_get_peer_mtu(a2dp_config->codecIndex(), codec_info); a2dp_stream_configuration.codecId = - provider_info->GetCodec(a2dp_config->codecIndex()).value()->id; + provider_info->GetCodec(a2dp_config->codecIndex()).value()->id; size_t parameters_start = 0; size_t parameters_end = 0; @@ -569,9 +553,9 @@ bool setup_codec() { break; } - a2dp_stream_configuration.configuration.insert( - a2dp_stream_configuration.configuration.end(), - codec_info + parameters_start, codec_info + parameters_end); + a2dp_stream_configuration.configuration.insert(a2dp_stream_configuration.configuration.end(), + codec_info + parameters_start, + codec_info + parameters_end); if (!is_hal_offloading()) { log::warn("Switching BluetoothAudio HAL to Hardware"); @@ -579,8 +563,7 @@ bool setup_codec() { active_hal_interface = offloading_hal_interface; } - return active_hal_interface->UpdateAudioConfig( - AudioConfiguration(a2dp_stream_configuration)); + return active_hal_interface->UpdateAudioConfig(AudioConfiguration(a2dp_stream_configuration)); } // Fallback to legacy offloading path. @@ -592,7 +575,7 @@ bool setup_codec() { } bool should_codec_offloading = - bluetooth::audio::aidl::codec::IsCodecOffloadingEnabled(codec_config); + bluetooth::audio::aidl::codec::IsCodecOffloadingEnabled(codec_config); if (should_codec_offloading && !is_hal_offloading()) { log::warn("Switching BluetoothAudio HAL to Hardware"); end_session(); @@ -638,10 +621,9 @@ void end_session() { return; } active_hal_interface->EndSession(); + static_cast(active_hal_interface->GetTransportInstance())->ResetPendingCmd(); static_cast(active_hal_interface->GetTransportInstance()) - ->ResetPendingCmd(); - static_cast(active_hal_interface->GetTransportInstance()) - ->ResetPresentationPosition(); + ->ResetPresentationPosition(); } void ack_stream_started(BluetoothAudioStatus ack) { @@ -650,8 +632,7 @@ void ack_stream_started(BluetoothAudioStatus ack) { return; } log::info("result={}", ack); - auto a2dp_sink = - static_cast(active_hal_interface->GetTransportInstance()); + auto a2dp_sink = static_cast(active_hal_interface->GetTransportInstance()); auto pending_cmd = a2dp_sink->GetPendingCmd(); if (pending_cmd == A2DP_CTRL_CMD_START) { active_hal_interface->StreamStarted(a2dp_ack_to_bt_audio_ctrl_ack(ack)); @@ -670,8 +651,7 @@ void ack_stream_suspended(BluetoothAudioStatus ack) { return; } log::info("result={}", ack); - auto a2dp_sink = - static_cast(active_hal_interface->GetTransportInstance()); + auto a2dp_sink = static_cast(active_hal_interface->GetTransportInstance()); auto pending_cmd = a2dp_sink->GetPendingCmd(); if (pending_cmd == A2DP_CTRL_CMD_SUSPEND) { active_hal_interface->StreamSuspended(a2dp_ack_to_bt_audio_ctrl_ack(ack)); @@ -693,10 +673,8 @@ size_t read(uint8_t* p_buf, uint32_t len) { return 0; } if (is_hal_offloading()) { - log::error( - "session_type={} is not A2DP_SOFTWARE_ENCODING_DATAPATH", - toString( - active_hal_interface->GetTransportInstance()->GetSessionType())); + log::error("session_type={} is not A2DP_SOFTWARE_ENCODING_DATAPATH", + toString(active_hal_interface->GetTransportInstance()->GetSessionType())); return 0; } return active_hal_interface->ReadAudioData(p_buf, len); @@ -705,14 +683,13 @@ size_t read(uint8_t* p_buf, uint32_t len) { // Update A2DP delay report to BluetoothAudio HAL void set_remote_delay(uint16_t delay_report) { if (!is_hal_enabled()) { - log::info("not ready for DelayReport {} ms", - static_cast(delay_report / 10.0)); + log::info("not ready for DelayReport {} ms", static_cast(delay_report / 10.0)); remote_delay = delay_report; return; } log::verbose("DELAY {} ms", static_cast(delay_report / 10.0)); static_cast(active_hal_interface->GetTransportInstance()) - ->SetRemoteDelay(delay_report); + ->SetRemoteDelay(delay_report); } // Set low latency buffer mode allowed or disallowed @@ -732,19 +709,15 @@ void set_low_latency_mode_allowed(bool allowed) { /*** * Lookup the codec info in the list of supported offloaded sink codecs. ***/ -std::optional provider::sink_codec_index( - const uint8_t* p_codec_info) { - return provider_info ? provider_info->SinkCodecIndex(p_codec_info) - : std::nullopt; +std::optional provider::sink_codec_index(const uint8_t* p_codec_info) { + return provider_info ? provider_info->SinkCodecIndex(p_codec_info) : std::nullopt; } /*** * Lookup the codec info in the list of supported offloaded source codecs. ***/ -std::optional provider::source_codec_index( - const uint8_t* p_codec_info) { - return provider_info ? provider_info->SourceCodecIndex(p_codec_info) - : std::nullopt; +std::optional provider::source_codec_index(const uint8_t* p_codec_info) { + return provider_info ? provider_info->SourceCodecIndex(p_codec_info) : std::nullopt; } /*** @@ -755,10 +728,8 @@ std::optional provider::source_codec_index( * Returns nullopt if the codec_index is not assigned or codec extensibility * is not supported or enabled. ***/ -std::optional provider::codec_index_str( - btav_a2dp_codec_index_t codec_index) { - return provider_info ? provider_info->CodecIndexStr(codec_index) - : std::nullopt; +std::optional provider::codec_index_str(btav_a2dp_codec_index_t codec_index) { + return provider_info ? provider_info->CodecIndexStr(codec_index) : std::nullopt; } /*** @@ -772,16 +743,14 @@ bool provider::supports_codec(btav_a2dp_codec_index_t codec_index) { /*** * Return the A2DP capabilities for the selected codec. ***/ -bool provider::codec_info(btav_a2dp_codec_index_t codec_index, - uint64_t* codec_id, uint8_t* codec_info, - btav_a2dp_codec_config_t* codec_config) { - return provider_info ? provider_info->CodecCapabilities( - codec_index, codec_id, codec_info, codec_config) - : false; +bool provider::codec_info(btav_a2dp_codec_index_t codec_index, uint64_t* codec_id, + uint8_t* codec_info, btav_a2dp_codec_config_t* codec_config) { + return provider_info + ? provider_info->CodecCapabilities(codec_index, codec_id, codec_info, codec_config) + : false; } -static btav_a2dp_codec_channel_mode_t convert_channel_mode( - ChannelMode channel_mode) { +static btav_a2dp_codec_channel_mode_t convert_channel_mode(ChannelMode channel_mode) { switch (channel_mode) { case ChannelMode::MONO: return BTAV_A2DP_CODEC_CHANNEL_MODE_MONO; @@ -794,8 +763,7 @@ static btav_a2dp_codec_channel_mode_t convert_channel_mode( return BTAV_A2DP_CODEC_CHANNEL_MODE_NONE; } -static btav_a2dp_codec_sample_rate_t convert_sampling_frequency_hz( - int sampling_frequency_hz) { +static btav_a2dp_codec_sample_rate_t convert_sampling_frequency_hz(int sampling_frequency_hz) { switch (sampling_frequency_hz) { case 44100: return BTAV_A2DP_CODEC_SAMPLE_RATE_44100; @@ -842,11 +810,10 @@ static btav_a2dp_codec_bits_per_sample_t convert_bitdepth(int bitdepth) { ***/ std::optional<::bluetooth::audio::a2dp::provider::a2dp_configuration> provider::get_a2dp_configuration( - RawAddress peer_address, - std::vector< - ::bluetooth::audio::a2dp::provider::a2dp_remote_capabilities> const& - remote_seps, - btav_a2dp_codec_config_t const& user_preferences) { + RawAddress peer_address, + std::vector<::bluetooth::audio::a2dp::provider::a2dp_remote_capabilities> const& + remote_seps, + btav_a2dp_codec_config_t const& user_preferences) { if (provider_info == nullptr) { return std::nullopt; } @@ -864,22 +831,20 @@ provider::get_a2dp_configuration( switch (sep.capabilities[2]) { case A2DP_MEDIA_CT_SBC: case A2DP_MEDIA_CT_AAC: { - id = CodecId::make( - static_cast(sep.capabilities[2])); + id = CodecId::make(static_cast(sep.capabilities[2])); capabilities_start = 3; capabilities_end = 1 + sep.capabilities[0]; break; } case A2DP_MEDIA_CT_NON_A2DP: { - uint32_t vendor_id = - (static_cast(sep.capabilities[3]) << 0) | - (static_cast(sep.capabilities[4]) << 8) | - (static_cast(sep.capabilities[5]) << 16) | - (static_cast(sep.capabilities[6]) << 24); + uint32_t vendor_id = (static_cast(sep.capabilities[3]) << 0) | + (static_cast(sep.capabilities[4]) << 8) | + (static_cast(sep.capabilities[5]) << 16) | + (static_cast(sep.capabilities[6]) << 24); uint16_t codec_id = (static_cast(sep.capabilities[7]) << 0) | (static_cast(sep.capabilities[8]) << 8); id = CodecId::make( - CodecId::Vendor({.id = (int32_t)vendor_id, .codecId = codec_id})); + CodecId::Vendor({.id = (int32_t)vendor_id, .codecId = codec_id})); capabilities_start = 9; capabilities_end = 1 + sep.capabilities[0]; break; @@ -887,8 +852,7 @@ provider::get_a2dp_configuration( default: continue; } - A2dpRemoteCapabilities& capabilities = - a2dp_remote_capabilities.emplace_back(); + A2dpRemoteCapabilities& capabilities = a2dp_remote_capabilities.emplace_back(); capabilities.seid = sep.seid; capabilities.id = id; capabilities.capabilities.insert(capabilities.capabilities.end(), @@ -960,15 +924,14 @@ provider::get_a2dp_configuration( if (offloading_hal_interface == nullptr && (offloading_hal_interface = new_hal_interface( - SessionType::A2DP_HARDWARE_OFFLOAD_ENCODING_DATAPATH)) == nullptr) { + SessionType::A2DP_HARDWARE_OFFLOAD_ENCODING_DATAPATH)) == nullptr) { log::error("the offloading HAL interface cannot be opened"); return std::nullopt; } // Invoke the HAL GetAdpCapabilities method with the // remote capabilities. - auto result = offloading_hal_interface->GetA2dpConfiguration( - a2dp_remote_capabilities, hint); + auto result = offloading_hal_interface->GetA2dpConfiguration(a2dp_remote_capabilities, hint); // Convert the result configuration back to the stack's format. if (!result.has_value()) { @@ -980,18 +943,17 @@ provider::get_a2dp_configuration( ::bluetooth::audio::a2dp::provider::a2dp_configuration a2dp_configuration; a2dp_configuration.remote_seid = result->remoteSeid; - a2dp_configuration.vendor_specific_parameters = - result->parameters.vendorSpecificParameters; + a2dp_configuration.vendor_specific_parameters = result->parameters.vendorSpecificParameters; ProviderInfo::BuildCodecCapabilities(result->id, result->configuration, a2dp_configuration.codec_config); a2dp_configuration.codec_parameters.codec_type = - provider_info->SourceCodecIndex(result->id).value(); + provider_info->SourceCodecIndex(result->id).value(); a2dp_configuration.codec_parameters.channel_mode = - convert_channel_mode(result->parameters.channelMode); + convert_channel_mode(result->parameters.channelMode); a2dp_configuration.codec_parameters.sample_rate = - convert_sampling_frequency_hz(result->parameters.samplingFrequencyHz); + convert_sampling_frequency_hz(result->parameters.samplingFrequencyHz); a2dp_configuration.codec_parameters.bits_per_sample = - convert_bitdepth(result->parameters.bitdepth); + convert_bitdepth(result->parameters.bitdepth); return std::make_optional(a2dp_configuration); } @@ -1002,10 +964,10 @@ provider::get_a2dp_configuration( * received from the peer and decide whether accept * the it or not. ***/ -tA2DP_STATUS provider::parse_a2dp_configuration( - btav_a2dp_codec_index_t codec_index, const uint8_t* codec_info, - btav_a2dp_codec_config_t* codec_parameters, - std::vector* vendor_specific_parameters) { +tA2DP_STATUS provider::parse_a2dp_configuration(btav_a2dp_codec_index_t codec_index, + const uint8_t* codec_info, + btav_a2dp_codec_config_t* codec_parameters, + std::vector* vendor_specific_parameters) { std::vector configuration; CodecParameters codec_parameters_aidl; @@ -1020,11 +982,10 @@ tA2DP_STATUS provider::parse_a2dp_configuration( return A2DP_FAIL; } - std::copy(codec_info, codec_info + AVDT_CODEC_SIZE, - std::back_inserter(configuration)); + std::copy(codec_info, codec_info + AVDT_CODEC_SIZE, std::back_inserter(configuration)); auto a2dp_status = offloading_hal_interface->ParseA2dpConfiguration( - codec.value()->id, configuration, &codec_parameters_aidl); + codec.value()->id, configuration, &codec_parameters_aidl); if (!a2dp_status.has_value()) { log::error("provider failed to parse configuration"); @@ -1032,17 +993,14 @@ tA2DP_STATUS provider::parse_a2dp_configuration( } if (codec_parameters != nullptr) { - codec_parameters->channel_mode = - convert_channel_mode(codec_parameters_aidl.channelMode); - codec_parameters->sample_rate = convert_sampling_frequency_hz( - codec_parameters_aidl.samplingFrequencyHz); - codec_parameters->bits_per_sample = - convert_bitdepth(codec_parameters_aidl.bitdepth); + codec_parameters->channel_mode = convert_channel_mode(codec_parameters_aidl.channelMode); + codec_parameters->sample_rate = + convert_sampling_frequency_hz(codec_parameters_aidl.samplingFrequencyHz); + codec_parameters->bits_per_sample = convert_bitdepth(codec_parameters_aidl.bitdepth); } if (vendor_specific_parameters != nullptr) { - *vendor_specific_parameters = - codec_parameters_aidl.vendorSpecificParameters; + *vendor_specific_parameters = codec_parameters_aidl.vendorSpecificParameters; } return static_cast(a2dp_status.value()); diff --git a/system/audio_hal_interface/aidl/a2dp_encoding_aidl.h b/system/audio_hal_interface/aidl/a2dp_encoding_aidl.h index 25051078a6e..b48373c5411 100644 --- a/system/audio_hal_interface/aidl/a2dp_encoding_aidl.h +++ b/system/audio_hal_interface/aidl/a2dp_encoding_aidl.h @@ -36,8 +36,8 @@ namespace aidl { namespace a2dp { bool update_codec_offloading_capabilities( - const std::vector& framework_preference, - bool supports_a2dp_hw_offload_v2); + const std::vector& framework_preference, + bool supports_a2dp_hw_offload_v2); /*** * Check if new bluetooth_audio is enabled @@ -94,15 +94,13 @@ namespace provider { * Lookup the codec info in the list of supported offloaded sink codecs. * Should not be called before update_codec_offloading_capabilities. ***/ -std::optional sink_codec_index( - const uint8_t* p_codec_info); +std::optional sink_codec_index(const uint8_t* p_codec_info); /*** * Lookup the codec info in the list of supported offloaded source codecs. * Should not be called before update_codec_offloading_capabilities. ***/ -std::optional source_codec_index( - const uint8_t* p_codec_info); +std::optional source_codec_index(const uint8_t* p_codec_info); /*** * Return the name of the codec which is assigned to the input index. @@ -124,21 +122,19 @@ bool supports_codec(btav_a2dp_codec_index_t codec_index); /*** * Return the A2DP capabilities for the selected codec. ***/ -bool codec_info(btav_a2dp_codec_index_t codec_index, uint64_t* codec_id, - uint8_t* codec_info, btav_a2dp_codec_config_t* codec_config); +bool codec_info(btav_a2dp_codec_index_t codec_index, uint64_t* codec_id, uint8_t* codec_info, + btav_a2dp_codec_config_t* codec_config); /*** * Query the codec selection fromt the audio HAL. * The HAL is expected to pick the best audio configuration based on the * discovered remote SEPs. ***/ -std::optional<::bluetooth::audio::a2dp::provider::a2dp_configuration> -get_a2dp_configuration( - RawAddress peer_address, - std::vector< - ::bluetooth::audio::a2dp::provider::a2dp_remote_capabilities> const& - remote_seps, - btav_a2dp_codec_config_t const& user_preferences); +std::optional<::bluetooth::audio::a2dp::provider::a2dp_configuration> get_a2dp_configuration( + RawAddress peer_address, + std::vector<::bluetooth::audio::a2dp::provider::a2dp_remote_capabilities> const& + remote_seps, + btav_a2dp_codec_config_t const& user_preferences); /*** * Query the codec parameters from the audio HAL. @@ -146,10 +142,10 @@ get_a2dp_configuration( * received from the peer and decide whether accept * the it or not. ***/ -tA2DP_STATUS parse_a2dp_configuration( - btav_a2dp_codec_index_t codec_index, const uint8_t* codec_info, - btav_a2dp_codec_config_t* codec_parameters, - std::vector* vendor_specific_parameters); +tA2DP_STATUS parse_a2dp_configuration(btav_a2dp_codec_index_t codec_index, + const uint8_t* codec_info, + btav_a2dp_codec_config_t* codec_parameters, + std::vector* vendor_specific_parameters); } // namespace provider } // namespace a2dp diff --git a/system/audio_hal_interface/aidl/a2dp_provider_info.cc b/system/audio_hal_interface/aidl/a2dp_provider_info.cc index 38db9ad93cc..62dd675747f 100644 --- a/system/audio_hal_interface/aidl/a2dp_provider_info.cc +++ b/system/audio_hal_interface/aidl/a2dp_provider_info.cc @@ -40,8 +40,7 @@ namespace bluetooth::audio::aidl::a2dp { using ::aidl::android::hardware::bluetooth::audio::ChannelMode; using ::aidl::android::hardware::bluetooth::audio::CodecId; using ::aidl::android::hardware::bluetooth::audio::CodecInfo; -using ::aidl::android::hardware::bluetooth::audio:: - IBluetoothAudioProviderFactory; +using ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProviderFactory; using ::aidl::android::hardware::bluetooth::audio::SessionType; /*** @@ -50,32 +49,31 @@ using ::aidl::android::hardware::bluetooth::audio::SessionType; * getProviderInfo, or if the feature flag for codec * extensibility is disabled. ***/ -std::unique_ptr ProviderInfo::GetProviderInfo( - bool supports_a2dp_hw_offload_v2) { +std::unique_ptr ProviderInfo::GetProviderInfo(bool supports_a2dp_hw_offload_v2) { if (!com::android::bluetooth::flags::a2dp_offload_codec_extensibility()) { log::info( - "a2dp offload codec extensibility is disabled," - " not going to load the ProviderInfo"); + "a2dp offload codec extensibility is disabled," + " not going to load the ProviderInfo"); return nullptr; } if (!supports_a2dp_hw_offload_v2) { log::info( - "a2dp hw offload v2 is not supported by the controller," - " not going to load the ProviderInfo"); + "a2dp hw offload v2 is not supported by the controller," + " not going to load the ProviderInfo"); return nullptr; } auto source_provider_info = BluetoothAudioClientInterface::GetProviderInfo( - SessionType::A2DP_HARDWARE_OFFLOAD_ENCODING_DATAPATH, nullptr); + SessionType::A2DP_HARDWARE_OFFLOAD_ENCODING_DATAPATH, nullptr); auto sink_provider_info = BluetoothAudioClientInterface::GetProviderInfo( - SessionType::A2DP_HARDWARE_OFFLOAD_DECODING_DATAPATH, nullptr); + SessionType::A2DP_HARDWARE_OFFLOAD_DECODING_DATAPATH, nullptr); if (!source_provider_info.has_value() && !sink_provider_info.has_value()) { log::info( - "a2dp offload codec extensibility is enabled," - " but the provider info is empty"); + "a2dp offload codec extensibility is enabled," + " but the provider info is empty"); return nullptr; } @@ -91,19 +89,16 @@ std::unique_ptr ProviderInfo::GetProviderInfo( } log::info("successfully loaded provider info"); - return std::make_unique(std::move(source_codecs), - std::move(sink_codecs)); + return std::make_unique(std::move(source_codecs), std::move(sink_codecs)); } /*** * Returns the codec with the selected index if supported * by the provider. ***/ -std::optional ProviderInfo::GetCodec( - btav_a2dp_codec_index_t codec_index) const { +std::optional ProviderInfo::GetCodec(btav_a2dp_codec_index_t codec_index) const { auto it = assigned_codec_indexes.find(codec_index); - return it == assigned_codec_indexes.end() ? std::nullopt - : std::make_optional(it->second); + return it == assigned_codec_indexes.end() ? std::nullopt : std::make_optional(it->second); } /*** @@ -112,7 +107,7 @@ std::optional ProviderInfo::GetCodec( * ext_index. ***/ static std::optional assignSourceCodecIndex( - CodecInfo const& codec, btav_a2dp_codec_index_t* ext_index) { + CodecInfo const& codec, btav_a2dp_codec_index_t* ext_index) { switch (codec.id.getTag()) { case CodecId::core: default: @@ -132,12 +127,10 @@ static std::optional assignSourceCodecIndex( int codec_id = codec.id.get().codecId; /* match know vendor codecs */ - if (vendor_id == A2DP_APTX_VENDOR_ID && - codec_id == A2DP_APTX_CODEC_ID_BLUETOOTH) { + if (vendor_id == A2DP_APTX_VENDOR_ID && codec_id == A2DP_APTX_CODEC_ID_BLUETOOTH) { return BTAV_A2DP_CODEC_INDEX_SOURCE_APTX; } - if (vendor_id == A2DP_APTX_HD_VENDOR_ID && - codec_id == A2DP_APTX_HD_CODEC_ID_BLUETOOTH) { + if (vendor_id == A2DP_APTX_HD_VENDOR_ID && codec_id == A2DP_APTX_HD_CODEC_ID_BLUETOOTH) { return BTAV_A2DP_CODEC_INDEX_SOURCE_APTX_HD; } if (vendor_id == A2DP_LDAC_VENDOR_ID && codec_id == A2DP_LDAC_CODEC_ID) { @@ -149,9 +142,8 @@ static std::optional assignSourceCodecIndex( /* out of extension codec indexes */ if (*ext_index >= BTAV_A2DP_CODEC_INDEX_SOURCE_EXT_MAX) { - log::error( - "unable to assign a source codec index for vendorId={}, codecId={}", - vendor_id, codec_id); + log::error("unable to assign a source codec index for vendorId={}, codecId={}", vendor_id, + codec_id); } /* assign a new codec index for the @@ -167,7 +159,7 @@ static std::optional assignSourceCodecIndex( * ext_index. ***/ static std::optional assignSinkCodecIndex( - CodecInfo const& codec, btav_a2dp_codec_index_t* ext_index) { + CodecInfo const& codec, btav_a2dp_codec_index_t* ext_index) { switch (codec.id.getTag()) { case CodecId::core: default: @@ -196,9 +188,8 @@ static std::optional assignSinkCodecIndex( /* out of extension codec indexes */ if (*ext_index >= BTAV_A2DP_CODEC_INDEX_SINK_EXT_MAX) { - log::error( - "unable to assign a sink codec index for vendorId={}, codecId={}", - vendor_id, codec_id); + log::error("unable to assign a sink codec index for vendorId={}, codecId={}", vendor_id, + codec_id); } /* assign a new codec index for the @@ -208,12 +199,9 @@ static std::optional assignSinkCodecIndex( } } -ProviderInfo::ProviderInfo(std::vector source_codecs, - std::vector sink_codecs) - : source_codecs(std::move(source_codecs)), - sink_codecs(std::move(sink_codecs)) { - btav_a2dp_codec_index_t ext_source_index = - BTAV_A2DP_CODEC_INDEX_SOURCE_EXT_MIN; +ProviderInfo::ProviderInfo(std::vector source_codecs, std::vector sink_codecs) + : source_codecs(std::move(source_codecs)), sink_codecs(std::move(sink_codecs)) { + btav_a2dp_codec_index_t ext_source_index = BTAV_A2DP_CODEC_INDEX_SOURCE_EXT_MIN; for (size_t i = 0; i < this->source_codecs.size(); i++) { auto& codec = this->source_codecs[i]; log::info("supported source codec {}", codec.name); @@ -235,7 +223,7 @@ ProviderInfo::ProviderInfo(std::vector source_codecs, } std::optional ProviderInfo::SourceCodecIndex( - CodecId const& codec_id) const { + CodecId const& codec_id) const { for (auto const& [index, codec] : assigned_codec_indexes) { if (codec->id == codec_id && index >= BTAV_A2DP_CODEC_INDEX_SOURCE_MIN && index < BTAV_A2DP_CODEC_INDEX_SOURCE_EXT_MAX) { @@ -245,14 +233,13 @@ std::optional ProviderInfo::SourceCodecIndex( return std::nullopt; } -std::optional ProviderInfo::SourceCodecIndex( - uint32_t vendor_id, uint16_t codec_id) const { +std::optional ProviderInfo::SourceCodecIndex(uint32_t vendor_id, + uint16_t codec_id) const { for (auto const& [index, codec] : assigned_codec_indexes) { if (codec->id.getTag() == CodecId::vendor && codec->id.get().id == (int)vendor_id && codec->id.get().codecId == codec_id && - index >= BTAV_A2DP_CODEC_INDEX_SOURCE_MIN && - index < BTAV_A2DP_CODEC_INDEX_SOURCE_EXT_MAX) { + index >= BTAV_A2DP_CODEC_INDEX_SOURCE_MIN && index < BTAV_A2DP_CODEC_INDEX_SOURCE_EXT_MAX) { return index; } } @@ -260,7 +247,7 @@ std::optional ProviderInfo::SourceCodecIndex( } std::optional ProviderInfo::SourceCodecIndex( - uint8_t const* codec_info) const { + uint8_t const* codec_info) const { log::assert_that(codec_info != nullptr, "codec_info is unexpectedly null"); auto codec_type = A2DP_GetCodecType(codec_info); switch (codec_type) { @@ -281,8 +268,7 @@ std::optional ProviderInfo::SourceCodecIndex( } } -std::optional ProviderInfo::SinkCodecIndex( - CodecId const& codec_id) const { +std::optional ProviderInfo::SinkCodecIndex(CodecId const& codec_id) const { for (auto const& [index, codec] : assigned_codec_indexes) { if (codec->id == codec_id && index >= BTAV_A2DP_CODEC_INDEX_SINK_MIN && index < BTAV_A2DP_CODEC_INDEX_SINK_EXT_MAX) { @@ -292,14 +278,13 @@ std::optional ProviderInfo::SinkCodecIndex( return std::nullopt; } -std::optional ProviderInfo::SinkCodecIndex( - uint32_t vendor_id, uint16_t codec_id) const { +std::optional ProviderInfo::SinkCodecIndex(uint32_t vendor_id, + uint16_t codec_id) const { for (auto const& [index, codec] : assigned_codec_indexes) { if (codec->id.getTag() == CodecId::vendor && codec->id.get().id == (int)vendor_id && codec->id.get().codecId == codec_id && - index >= BTAV_A2DP_CODEC_INDEX_SINK_MIN && - index < BTAV_A2DP_CODEC_INDEX_SINK_EXT_MAX) { + index >= BTAV_A2DP_CODEC_INDEX_SINK_MIN && index < BTAV_A2DP_CODEC_INDEX_SINK_EXT_MAX) { return index; } } @@ -307,7 +292,7 @@ std::optional ProviderInfo::SinkCodecIndex( } std::optional ProviderInfo::SinkCodecIndex( - uint8_t const* codec_info) const { + uint8_t const* codec_info) const { log::assert_that(codec_info != nullptr, "codec_info is unexpectedly null"); auto codec_type = A2DP_GetCodecType(codec_info); switch (codec_type) { @@ -328,22 +313,19 @@ std::optional ProviderInfo::SinkCodecIndex( } } -std::optional ProviderInfo::CodecIndexStr( - btav_a2dp_codec_index_t codec_index) const { +std::optional ProviderInfo::CodecIndexStr(btav_a2dp_codec_index_t codec_index) const { auto it = assigned_codec_indexes.find(codec_index); - return it != assigned_codec_indexes.end() - ? std::make_optional(it->second->name.c_str()) - : std::nullopt; + return it != assigned_codec_indexes.end() ? std::make_optional(it->second->name.c_str()) + : std::nullopt; } bool ProviderInfo::SupportsCodec(btav_a2dp_codec_index_t codec_index) const { - return assigned_codec_indexes.find(codec_index) != - assigned_codec_indexes.end(); + return assigned_codec_indexes.find(codec_index) != assigned_codec_indexes.end(); } -bool ProviderInfo::BuildCodecCapabilities( - CodecId const& codec_id, std::vector const& capabilities, - uint8_t* codec_info) { +bool ProviderInfo::BuildCodecCapabilities(CodecId const& codec_id, + std::vector const& capabilities, + uint8_t* codec_info) { switch (codec_id.getTag()) { case CodecId::a2dp: { auto id = codec_id.get(); @@ -376,9 +358,9 @@ bool ProviderInfo::BuildCodecCapabilities( return false; } -bool ProviderInfo::CodecCapabilities( - btav_a2dp_codec_index_t codec_index, uint64_t* codec_id, - uint8_t* codec_info, btav_a2dp_codec_config_t* codec_config) const { +bool ProviderInfo::CodecCapabilities(btav_a2dp_codec_index_t codec_index, uint64_t* codec_id, + uint8_t* codec_info, + btav_a2dp_codec_config_t* codec_config) const { auto it = assigned_codec_indexes.find(codec_index); if (it == assigned_codec_indexes.end()) { return false; diff --git a/system/audio_hal_interface/aidl/a2dp_provider_info.h b/system/audio_hal_interface/aidl/a2dp_provider_info.h index 786c77e7d5f..beabc4b4edd 100644 --- a/system/audio_hal_interface/aidl/a2dp_provider_info.h +++ b/system/audio_hal_interface/aidl/a2dp_provider_info.h @@ -31,53 +31,45 @@ using ::aidl::android::hardware::bluetooth::audio::CodecInfo; * Record the provider info returned by the HAL implementer. ***/ class ProviderInfo { - public: +public: /*** * Reads the provider information from the HAL. * May return nullptr if the HAL does not implement * getProviderInfo, or if the feature flag for codec * extensibility is disabled. ***/ - static std::unique_ptr GetProviderInfo( - bool supports_a2dp_hw_offload_v2); + static std::unique_ptr GetProviderInfo(bool supports_a2dp_hw_offload_v2); - ProviderInfo(std::vector source_codecs, - std::vector sink_codecs); + ProviderInfo(std::vector source_codecs, std::vector sink_codecs); ~ProviderInfo() = default; /*** * Returns the codec with the selected index if supported * by the provider. ***/ - std::optional GetCodec( - btav_a2dp_codec_index_t codec_index) const; + std::optional GetCodec(btav_a2dp_codec_index_t codec_index) const; /*** * Find the source codec index by codec capabilities. ***/ - std::optional SourceCodecIndex( - CodecId const& codec_id) const; - std::optional SourceCodecIndex( - uint32_t vendor_id, uint16_t codec_id) const; - std::optional SourceCodecIndex( - uint8_t const* codec_info) const; + std::optional SourceCodecIndex(CodecId const& codec_id) const; + std::optional SourceCodecIndex(uint32_t vendor_id, + uint16_t codec_id) const; + std::optional SourceCodecIndex(uint8_t const* codec_info) const; /*** * Find the sink codec index by codec capabilities. ***/ - std::optional SinkCodecIndex( - CodecId const& codec_id) const; - std::optional SinkCodecIndex( - uint32_t vendor_id, uint16_t codec_id) const; - std::optional SinkCodecIndex( - uint8_t const* codec_info) const; + std::optional SinkCodecIndex(CodecId const& codec_id) const; + std::optional SinkCodecIndex(uint32_t vendor_id, + uint16_t codec_id) const; + std::optional SinkCodecIndex(uint8_t const* codec_info) const; /*** * Return the name of the codec with the assigned * input index. ***/ - std::optional CodecIndexStr( - btav_a2dp_codec_index_t codec_index) const; + std::optional CodecIndexStr(btav_a2dp_codec_index_t codec_index) const; /*** * Return true if the codec is supported by the @@ -91,23 +83,20 @@ class ProviderInfo { * Returns true if the capabilities were successfully converted. ***/ static bool BuildCodecCapabilities(CodecId const& codec_id, - std::vector const& capabilities, - uint8_t* codec_info); + std::vector const& capabilities, uint8_t* codec_info); /*** * Return the A2DP capabilities for the selected codec. * Returns true if the codec is supported, false otherwise. ***/ - bool CodecCapabilities(btav_a2dp_codec_index_t codec_index, - uint64_t* codec_id, uint8_t* codec_info, - btav_a2dp_codec_config_t* codec_config) const; + bool CodecCapabilities(btav_a2dp_codec_index_t codec_index, uint64_t* codec_id, + uint8_t* codec_info, btav_a2dp_codec_config_t* codec_config) const; const std::vector source_codecs; const std::vector sink_codecs; - private: - std::unordered_map - assigned_codec_indexes; +private: + std::unordered_map assigned_codec_indexes; }; } // namespace bluetooth::audio::aidl::a2dp diff --git a/system/audio_hal_interface/aidl/a2dp_provider_info_unittest.cc b/system/audio_hal_interface/aidl/a2dp_provider_info_unittest.cc index 56c46395960..f91637af982 100644 --- a/system/audio_hal_interface/aidl/a2dp_provider_info_unittest.cc +++ b/system/audio_hal_interface/aidl/a2dp_provider_info_unittest.cc @@ -61,19 +61,16 @@ uint32_t A2DP_VendorCodecGetVendorId(const uint8_t* p_codec_info) { const uint8_t* p = &p_codec_info[A2DP_VENDOR_CODEC_VENDOR_ID_START_IDX]; uint32_t vendor_id = (p[0] & 0x000000ff) | ((p[1] << 8) & 0x0000ff00) | - ((p[2] << 16) & 0x00ff0000) | - ((p[3] << 24) & 0xff000000); + ((p[2] << 16) & 0x00ff0000) | ((p[3] << 24) & 0xff000000); return vendor_id; } class MockBluetoothAudioClientInterface { - public: - MOCK_METHOD( - std::optional, - GetProviderInfo, - (SessionType session_type, - std::shared_ptr provider_factory)); +public: + MOCK_METHOD(std::optional, GetProviderInfo, + (SessionType session_type, + std::shared_ptr provider_factory)); }; static MockBluetoothAudioClientInterface* mock_bt_audio_client_itf = nullptr; @@ -84,10 +81,9 @@ namespace aidl { std::optional BluetoothAudioClientInterface::GetProviderInfo( - SessionType session_type, - std::shared_ptr provider_factory) { - return mock_bt_audio_client_itf->GetProviderInfo(session_type, - provider_factory); + SessionType session_type, + std::shared_ptr provider_factory) { + return mock_bt_audio_client_itf->GetProviderInfo(session_type, provider_factory); } } // namespace aidl @@ -96,36 +92,31 @@ BluetoothAudioClientInterface::GetProviderInfo( namespace { -std::vector test_sbc_codec_info = {0x06, 0x00, 0x00, 0x3f, - 0xff, 0x02, 0x25}; -std::vector test_aac_codec_info = {0x08, 0x00, 0x02, 0x80, 0x01, - 0x8c, 0x83, 0xe8, 0x00}; +std::vector test_sbc_codec_info = {0x06, 0x00, 0x00, 0x3f, 0xff, 0x02, 0x25}; +std::vector test_aac_codec_info = {0x08, 0x00, 0x02, 0x80, 0x01, 0x8c, 0x83, 0xe8, 0x00}; std::vector test_opus_codec_info = {0x09, 0x00, 0xff, 0xe0, 0x00, 0x00, 0x00, 0x01, 0x00, 0x3c}; std::vector test_foobar_codec_info = {0x09, 0x00, 0xff, 0x44, 0x33, 0x00, 0x00, 0x22, 0x11, 0x3c}; -CodecId::Vendor test_opus_codec_id = {.id = A2DP_OPUS_VENDOR_ID, - .codecId = A2DP_OPUS_CODEC_ID}; +CodecId::Vendor test_opus_codec_id = {.id = A2DP_OPUS_VENDOR_ID, .codecId = A2DP_OPUS_CODEC_ID}; CodecId::Vendor test_foobar_codec_id = {.id = 0x00003344, .codecId = 0x1122}; -CodecId::Vendor test_unknown_vendor_codec_id = {.id = 0x12345678, - .codecId = 0x1234}; +CodecId::Vendor test_unknown_vendor_codec_id = {.id = 0x12345678, .codecId = 0x1234}; IBluetoothAudioProviderFactory::ProviderInfo test_source_provider_info = { - .name = "TEST_PROVIDER_SOURCE_CODECS", + .name = "TEST_PROVIDER_SOURCE_CODECS", }; IBluetoothAudioProviderFactory::ProviderInfo test_sink_provider_info = { - .name = "TEST_PROVIDER_SINK_CODECS", + .name = "TEST_PROVIDER_SINK_CODECS", }; class ProviderInfoTest : public Test { - public: +public: std::unique_ptr provider_info; MockBluetoothAudioClientInterface client_itf_mock; - void CreateTestA2dpCodecInfo(CodecInfo& codecInfo, CodecId codecId, - std::string codecName, + void CreateTestA2dpCodecInfo(CodecInfo& codecInfo, CodecId codecId, std::string codecName, std::vector capabilities, std::vector channelMode, std::vector samplingFrequencyHz, @@ -142,28 +133,23 @@ class ProviderInfoTest : public Test { a2dpInfo.lossless = lossless; } - void GetProviderInfoForTesting(bool include_source_codecs, - bool include_sink_codecs) { + void GetProviderInfoForTesting(bool include_source_codecs, bool include_sink_codecs) { if (include_source_codecs) { EXPECT_CALL(client_itf_mock, - GetProviderInfo( - SessionType::A2DP_HARDWARE_OFFLOAD_ENCODING_DATAPATH, _)) - .WillOnce(Return(std::make_optional(test_source_provider_info))); + GetProviderInfo(SessionType::A2DP_HARDWARE_OFFLOAD_ENCODING_DATAPATH, _)) + .WillOnce(Return(std::make_optional(test_source_provider_info))); } else { EXPECT_CALL(client_itf_mock, - GetProviderInfo( - SessionType::A2DP_HARDWARE_OFFLOAD_ENCODING_DATAPATH, _)); + GetProviderInfo(SessionType::A2DP_HARDWARE_OFFLOAD_ENCODING_DATAPATH, _)); } if (include_sink_codecs) { EXPECT_CALL(client_itf_mock, - GetProviderInfo( - SessionType::A2DP_HARDWARE_OFFLOAD_DECODING_DATAPATH, _)) - .WillOnce(Return(std::make_optional(test_sink_provider_info))); + GetProviderInfo(SessionType::A2DP_HARDWARE_OFFLOAD_DECODING_DATAPATH, _)) + .WillOnce(Return(std::make_optional(test_sink_provider_info))); } else { EXPECT_CALL(client_itf_mock, - GetProviderInfo( - SessionType::A2DP_HARDWARE_OFFLOAD_DECODING_DATAPATH, _)); + GetProviderInfo(SessionType::A2DP_HARDWARE_OFFLOAD_DECODING_DATAPATH, _)); } provider_info = ProviderInfo::GetProviderInfo(true); @@ -174,54 +160,49 @@ class ProviderInfoTest : public Test { } } - protected: +protected: void SetUp() override { mock_bt_audio_client_itf = &client_itf_mock; auto& codec_info_sbc = test_source_provider_info.codecInfos.emplace_back(); - CreateTestA2dpCodecInfo( - codec_info_sbc, CodecId::A2dp::SBC, std::string("SBC"), - std::vector{0x3f, 0xff, 0x02, 0x25}, /* capabilities */ - std::vector{ChannelMode::MONO, ChannelMode::STEREO, - ChannelMode::DUALMONO}, /* channelMode */ - std::vector{44100, 48000}, /* samplingFrequencyHz */ - std::vector{16, 24, 32}, /* bitdepth */ - false /* lossless */ + CreateTestA2dpCodecInfo(codec_info_sbc, CodecId::A2dp::SBC, std::string("SBC"), + std::vector{0x3f, 0xff, 0x02, 0x25}, /* capabilities */ + std::vector{ChannelMode::MONO, ChannelMode::STEREO, + ChannelMode::DUALMONO}, /* channelMode */ + std::vector{44100, 48000}, /* samplingFrequencyHz */ + std::vector{16, 24, 32}, /* bitdepth */ + false /* lossless */ ); auto& codec_info_aac = test_source_provider_info.codecInfos.emplace_back(); CreateTestA2dpCodecInfo( - codec_info_aac, CodecId::A2dp::AAC, std::string("AAC"), - std::vector{0x80, 0x01, 0x8c, 0x83, 0xe8, - 0x00}, /* capabilities */ - std::vector{ChannelMode::MONO, ChannelMode::STEREO, - ChannelMode::DUALMONO}, /* channelMode */ - std::vector{44100, 48000}, /* samplingFrequencyHz */ - std::vector{16, 24, 32}, /* bitdepth */ - false /* lossless */ + codec_info_aac, CodecId::A2dp::AAC, std::string("AAC"), + std::vector{0x80, 0x01, 0x8c, 0x83, 0xe8, 0x00}, /* capabilities */ + std::vector{ChannelMode::MONO, ChannelMode::STEREO, + ChannelMode::DUALMONO}, /* channelMode */ + std::vector{44100, 48000}, /* samplingFrequencyHz */ + std::vector{16, 24, 32}, /* bitdepth */ + false /* lossless */ ); auto& codec_info_opus = test_source_provider_info.codecInfos.emplace_back(); - CreateTestA2dpCodecInfo( - codec_info_opus, test_opus_codec_id, std::string("Opus"), - std::vector{0x3c}, /* capabilities */ - std::vector{ChannelMode::MONO, ChannelMode::STEREO, - ChannelMode::DUALMONO}, /* channelMode */ - std::vector{44100, 48000}, /* samplingFrequencyHz */ - std::vector{16, 24, 32}, /* bitdepth */ - false /* lossless */ + CreateTestA2dpCodecInfo(codec_info_opus, test_opus_codec_id, std::string("Opus"), + std::vector{0x3c}, /* capabilities */ + std::vector{ChannelMode::MONO, ChannelMode::STEREO, + ChannelMode::DUALMONO}, /* channelMode */ + std::vector{44100, 48000}, /* samplingFrequencyHz */ + std::vector{16, 24, 32}, /* bitdepth */ + false /* lossless */ ); - auto& codec_info_foobar = - test_source_provider_info.codecInfos.emplace_back(); - CreateTestA2dpCodecInfo( - codec_info_foobar, test_foobar_codec_id, std::string("FooBar"), - std::vector{0x3c}, /* capabilities */ - std::vector{ChannelMode::MONO, ChannelMode::STEREO, - ChannelMode::DUALMONO}, /* channelMode */ - std::vector{44100, 48000}, /* samplingFrequencyHz */ - std::vector{16, 24, 32}, /* bitdepth */ - false /* lossless */ + auto& codec_info_foobar = test_source_provider_info.codecInfos.emplace_back(); + CreateTestA2dpCodecInfo(codec_info_foobar, test_foobar_codec_id, std::string("FooBar"), + std::vector{0x3c}, /* capabilities */ + std::vector{ChannelMode::MONO, ChannelMode::STEREO, + ChannelMode::DUALMONO}, /* channelMode */ + std::vector{44100, 48000}, /* samplingFrequencyHz */ + std::vector{16, 24, 32}, /* bitdepth */ + false /* lossless */ ); test_sink_provider_info.codecInfos = test_source_provider_info.codecInfos; @@ -235,40 +216,34 @@ class ProviderInfoTest : public Test { } // namespace TEST_F_WITH_FLAGS(ProviderInfoTest, TestGetProviderInfoFlagDisabled, - REQUIRES_FLAGS_DISABLED(ACONFIG_FLAG( - TEST_BT, a2dp_offload_codec_extensibility))) { - EXPECT_CALL( - client_itf_mock, - GetProviderInfo(SessionType::A2DP_HARDWARE_OFFLOAD_ENCODING_DATAPATH, _)) - .Times(0); - EXPECT_CALL( - client_itf_mock, - GetProviderInfo(SessionType::A2DP_HARDWARE_OFFLOAD_DECODING_DATAPATH, _)) - .Times(0); + REQUIRES_FLAGS_DISABLED(ACONFIG_FLAG(TEST_BT, + a2dp_offload_codec_extensibility))) { + EXPECT_CALL(client_itf_mock, + GetProviderInfo(SessionType::A2DP_HARDWARE_OFFLOAD_ENCODING_DATAPATH, _)) + .Times(0); + EXPECT_CALL(client_itf_mock, + GetProviderInfo(SessionType::A2DP_HARDWARE_OFFLOAD_DECODING_DATAPATH, _)) + .Times(0); provider_info = ProviderInfo::GetProviderInfo(true); ASSERT_EQ(provider_info, nullptr); } TEST_F_WITH_FLAGS(ProviderInfoTest, TestGetProviderInfoEmptyProviderInfo, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG( - TEST_BT, a2dp_offload_codec_extensibility))) { + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, a2dp_offload_codec_extensibility))) { GetProviderInfoForTesting(false, false); } TEST_F_WITH_FLAGS(ProviderInfoTest, TestGetProviderInfo, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG( - TEST_BT, a2dp_offload_codec_extensibility))) { + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, a2dp_offload_codec_extensibility))) { GetProviderInfoForTesting(true, false); } TEST_F_WITH_FLAGS(ProviderInfoTest, TestGetCodecSbc, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG( - TEST_BT, a2dp_offload_codec_extensibility))) { + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, a2dp_offload_codec_extensibility))) { GetProviderInfoForTesting(true, false); - auto received_codec_info_sbc = - provider_info->GetCodec(BTAV_A2DP_CODEC_INDEX_SOURCE_SBC); + auto received_codec_info_sbc = provider_info->GetCodec(BTAV_A2DP_CODEC_INDEX_SOURCE_SBC); ASSERT_TRUE(received_codec_info_sbc.has_value()); auto codec_info = received_codec_info_sbc.value(); log::error("{}", codec_info->toString()); @@ -277,12 +252,10 @@ TEST_F_WITH_FLAGS(ProviderInfoTest, TestGetCodecSbc, } TEST_F_WITH_FLAGS(ProviderInfoTest, TestGetCodecAac, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG( - TEST_BT, a2dp_offload_codec_extensibility))) { + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, a2dp_offload_codec_extensibility))) { GetProviderInfoForTesting(true, false); - auto received_codec_info_aac = - provider_info->GetCodec(BTAV_A2DP_CODEC_INDEX_SOURCE_AAC); + auto received_codec_info_aac = provider_info->GetCodec(BTAV_A2DP_CODEC_INDEX_SOURCE_AAC); ASSERT_TRUE(received_codec_info_aac.has_value()); auto codec_info = received_codec_info_aac.value(); log::error("{}", codec_info->toString()); @@ -291,12 +264,10 @@ TEST_F_WITH_FLAGS(ProviderInfoTest, TestGetCodecAac, } TEST_F_WITH_FLAGS(ProviderInfoTest, TestGetCodecOpus, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG( - TEST_BT, a2dp_offload_codec_extensibility))) { + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, a2dp_offload_codec_extensibility))) { GetProviderInfoForTesting(true, false); - auto received_codec_info_opus = - provider_info->GetCodec(BTAV_A2DP_CODEC_INDEX_SOURCE_OPUS); + auto received_codec_info_opus = provider_info->GetCodec(BTAV_A2DP_CODEC_INDEX_SOURCE_OPUS); ASSERT_TRUE(received_codec_info_opus.has_value()); auto codec_info = received_codec_info_opus.value(); log::error("{}", codec_info->toString()); @@ -305,12 +276,10 @@ TEST_F_WITH_FLAGS(ProviderInfoTest, TestGetCodecOpus, } TEST_F_WITH_FLAGS(ProviderInfoTest, TestGetCodecFoobar, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG( - TEST_BT, a2dp_offload_codec_extensibility))) { + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, a2dp_offload_codec_extensibility))) { GetProviderInfoForTesting(true, false); - auto received_codec_info_foobar = - provider_info->GetCodec(BTAV_A2DP_CODEC_INDEX_SOURCE_EXT_MIN); + auto received_codec_info_foobar = provider_info->GetCodec(BTAV_A2DP_CODEC_INDEX_SOURCE_EXT_MIN); ASSERT_TRUE(received_codec_info_foobar.has_value()); auto codec_info = received_codec_info_foobar.value(); log::error("{}", codec_info->toString()); @@ -319,18 +288,16 @@ TEST_F_WITH_FLAGS(ProviderInfoTest, TestGetCodecFoobar, } TEST_F_WITH_FLAGS(ProviderInfoTest, TestGetCodecNotSupported, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG( - TEST_BT, a2dp_offload_codec_extensibility))) { + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, a2dp_offload_codec_extensibility))) { GetProviderInfoForTesting(true, false); auto received_codec_info_not_supported_codec = - provider_info->GetCodec(BTAV_A2DP_CODEC_INDEX_SINK_LDAC); + provider_info->GetCodec(BTAV_A2DP_CODEC_INDEX_SINK_LDAC); ASSERT_FALSE(received_codec_info_not_supported_codec.has_value()); } TEST_F_WITH_FLAGS(ProviderInfoTest, TestSourceCodecIndexByCodecId, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG( - TEST_BT, a2dp_offload_codec_extensibility))) { + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, a2dp_offload_codec_extensibility))) { GetProviderInfoForTesting(true, false); std::optional a2dp_codec_index_opt; @@ -352,14 +319,12 @@ TEST_F_WITH_FLAGS(ProviderInfoTest, TestSourceCodecIndexByCodecId, ASSERT_TRUE(a2dp_codec_index_opt.has_value()); ASSERT_EQ(a2dp_codec_index_opt.value(), BTAV_A2DP_CODEC_INDEX_SOURCE_EXT_MIN); - a2dp_codec_index_opt = - provider_info->SourceCodecIndex(test_unknown_vendor_codec_id); + a2dp_codec_index_opt = provider_info->SourceCodecIndex(test_unknown_vendor_codec_id); ASSERT_FALSE(a2dp_codec_index_opt.has_value()); } TEST_F_WITH_FLAGS(ProviderInfoTest, TestSourceCodecIndexByVendorAndCodecId, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG( - TEST_BT, a2dp_offload_codec_extensibility))) { + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, a2dp_offload_codec_extensibility))) { GetProviderInfoForTesting(true, false); std::optional a2dp_codec_index_opt; @@ -373,47 +338,39 @@ TEST_F_WITH_FLAGS(ProviderInfoTest, TestSourceCodecIndexByVendorAndCodecId, ASSERT_TRUE(a2dp_codec_index_opt.has_value()); ASSERT_EQ(a2dp_codec_index_opt.value(), BTAV_A2DP_CODEC_INDEX_SOURCE_EXT_MIN); - a2dp_codec_index_opt = - provider_info->SourceCodecIndex(test_unknown_vendor_codec_id); + a2dp_codec_index_opt = provider_info->SourceCodecIndex(test_unknown_vendor_codec_id); ASSERT_FALSE(a2dp_codec_index_opt.has_value()); } TEST_F_WITH_FLAGS(ProviderInfoTest, TestSourceCodecIndexByCapabilities, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG( - TEST_BT, a2dp_offload_codec_extensibility))) { + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, a2dp_offload_codec_extensibility))) { GetProviderInfoForTesting(true, false); std::optional a2dp_codec_index_opt; - a2dp_codec_index_opt = - provider_info->SourceCodecIndex(test_sbc_codec_info.data()); + a2dp_codec_index_opt = provider_info->SourceCodecIndex(test_sbc_codec_info.data()); ASSERT_TRUE(a2dp_codec_index_opt.has_value()); ASSERT_EQ(a2dp_codec_index_opt.value(), BTAV_A2DP_CODEC_INDEX_SOURCE_SBC); - a2dp_codec_index_opt = - provider_info->SourceCodecIndex(test_aac_codec_info.data()); + a2dp_codec_index_opt = provider_info->SourceCodecIndex(test_aac_codec_info.data()); ASSERT_TRUE(a2dp_codec_index_opt.has_value()); ASSERT_EQ(a2dp_codec_index_opt.value(), BTAV_A2DP_CODEC_INDEX_SOURCE_AAC); - a2dp_codec_index_opt = - provider_info->SourceCodecIndex(test_opus_codec_info.data()); + a2dp_codec_index_opt = provider_info->SourceCodecIndex(test_opus_codec_info.data()); ASSERT_TRUE(a2dp_codec_index_opt.has_value()); ASSERT_EQ(a2dp_codec_index_opt.value(), BTAV_A2DP_CODEC_INDEX_SOURCE_OPUS); - a2dp_codec_index_opt = - provider_info->SourceCodecIndex(test_foobar_codec_info.data()); + a2dp_codec_index_opt = provider_info->SourceCodecIndex(test_foobar_codec_info.data()); ASSERT_TRUE(a2dp_codec_index_opt.has_value()); ASSERT_EQ(a2dp_codec_index_opt.value(), BTAV_A2DP_CODEC_INDEX_SOURCE_EXT_MIN); - a2dp_codec_index_opt = provider_info->SourceCodecIndex( - std::vector({0xde, 0xad, 0xbe, 0xef}).data()); + a2dp_codec_index_opt = + provider_info->SourceCodecIndex(std::vector({0xde, 0xad, 0xbe, 0xef}).data()); ASSERT_FALSE(a2dp_codec_index_opt.has_value()); } -TEST_F_WITH_FLAGS(ProviderInfoTest, - TestSourceCodecIndexByCodecIdAssertNoSources, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG( - TEST_BT, a2dp_offload_codec_extensibility))) { +TEST_F_WITH_FLAGS(ProviderInfoTest, TestSourceCodecIndexByCodecIdAssertNoSources, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, a2dp_offload_codec_extensibility))) { GetProviderInfoForTesting(false, true); std::optional a2dp_codec_index_opt; @@ -431,43 +388,39 @@ TEST_F_WITH_FLAGS(ProviderInfoTest, a2dp_codec_index_opt = provider_info->SourceCodecIndex(codecInfoArray[3].id); ASSERT_FALSE(a2dp_codec_index_opt.has_value()); - a2dp_codec_index_opt = - provider_info->SourceCodecIndex(test_unknown_vendor_codec_id); + a2dp_codec_index_opt = provider_info->SourceCodecIndex(test_unknown_vendor_codec_id); ASSERT_FALSE(a2dp_codec_index_opt.has_value()); } -TEST_F_WITH_FLAGS(ProviderInfoTest, - TestSourceCodecIndexByVendorAndCodecIdAssertNoSources, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG( - TEST_BT, a2dp_offload_codec_extensibility))) { +TEST_F_WITH_FLAGS(ProviderInfoTest, TestSourceCodecIndexByVendorAndCodecIdAssertNoSources, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, a2dp_offload_codec_extensibility))) { GetProviderInfoForTesting(false, true); std::optional a2dp_codec_index_opt; - a2dp_codec_index_opt = provider_info->SourceCodecIndex( - 0, static_cast(CodecId::A2dp::SBC)); + a2dp_codec_index_opt = + provider_info->SourceCodecIndex(0, static_cast(CodecId::A2dp::SBC)); ASSERT_FALSE(a2dp_codec_index_opt.has_value()); - a2dp_codec_index_opt = provider_info->SourceCodecIndex( - 0, static_cast(CodecId::A2dp::AAC)); + a2dp_codec_index_opt = + provider_info->SourceCodecIndex(0, static_cast(CodecId::A2dp::AAC)); ASSERT_FALSE(a2dp_codec_index_opt.has_value()); - a2dp_codec_index_opt = provider_info->SourceCodecIndex( - test_opus_codec_id.id, test_opus_codec_id.codecId); + a2dp_codec_index_opt = + provider_info->SourceCodecIndex(test_opus_codec_id.id, test_opus_codec_id.codecId); ASSERT_FALSE(a2dp_codec_index_opt.has_value()); - a2dp_codec_index_opt = provider_info->SourceCodecIndex( - test_foobar_codec_id.id, test_foobar_codec_id.codecId); + a2dp_codec_index_opt = + provider_info->SourceCodecIndex(test_foobar_codec_id.id, test_foobar_codec_id.codecId); ASSERT_FALSE(a2dp_codec_index_opt.has_value()); - a2dp_codec_index_opt = provider_info->SourceCodecIndex( - test_unknown_vendor_codec_id.id, test_unknown_vendor_codec_id.codecId); + a2dp_codec_index_opt = provider_info->SourceCodecIndex(test_unknown_vendor_codec_id.id, + test_unknown_vendor_codec_id.codecId); ASSERT_FALSE(a2dp_codec_index_opt.has_value()); } TEST_F_WITH_FLAGS(ProviderInfoTest, TestSinkCodecIndexByCodecId, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG( - TEST_BT, a2dp_offload_codec_extensibility))) { + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, a2dp_offload_codec_extensibility))) { GetProviderInfoForTesting(false, true); std::optional a2dp_codec_index_opt; @@ -489,75 +442,68 @@ TEST_F_WITH_FLAGS(ProviderInfoTest, TestSinkCodecIndexByCodecId, ASSERT_TRUE(a2dp_codec_index_opt.has_value()); ASSERT_EQ(a2dp_codec_index_opt.value(), BTAV_A2DP_CODEC_INDEX_SINK_EXT_MIN); - a2dp_codec_index_opt = - provider_info->SinkCodecIndex(test_unknown_vendor_codec_id); + a2dp_codec_index_opt = provider_info->SinkCodecIndex(test_unknown_vendor_codec_id); ASSERT_FALSE(a2dp_codec_index_opt.has_value()); } TEST_F_WITH_FLAGS(ProviderInfoTest, TestSinkCodecIndexByVendorAndCodecId, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG( - TEST_BT, a2dp_offload_codec_extensibility))) { + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, a2dp_offload_codec_extensibility))) { GetProviderInfoForTesting(false, true); std::optional a2dp_codec_index_opt; - a2dp_codec_index_opt = provider_info->SinkCodecIndex( - test_opus_codec_id.id, test_opus_codec_id.codecId); + a2dp_codec_index_opt = + provider_info->SinkCodecIndex(test_opus_codec_id.id, test_opus_codec_id.codecId); ASSERT_TRUE(a2dp_codec_index_opt.has_value()); ASSERT_EQ(a2dp_codec_index_opt.value(), BTAV_A2DP_CODEC_INDEX_SINK_OPUS); - a2dp_codec_index_opt = provider_info->SinkCodecIndex( - test_foobar_codec_id.id, test_foobar_codec_id.codecId); + a2dp_codec_index_opt = + provider_info->SinkCodecIndex(test_foobar_codec_id.id, test_foobar_codec_id.codecId); ASSERT_TRUE(a2dp_codec_index_opt.has_value()); ASSERT_EQ(a2dp_codec_index_opt.value(), BTAV_A2DP_CODEC_INDEX_SINK_EXT_MIN); - a2dp_codec_index_opt = provider_info->SinkCodecIndex( - test_unknown_vendor_codec_id.id, test_unknown_vendor_codec_id.codecId); + a2dp_codec_index_opt = provider_info->SinkCodecIndex(test_unknown_vendor_codec_id.id, + test_unknown_vendor_codec_id.codecId); ASSERT_FALSE(a2dp_codec_index_opt.has_value()); } -TEST_F_WITH_FLAGS(ProviderInfoTest, - TestSinkCodecIndexByVendorAndCodecIdAssertNoSinks, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG( - TEST_BT, a2dp_offload_codec_extensibility))) { +TEST_F_WITH_FLAGS(ProviderInfoTest, TestSinkCodecIndexByVendorAndCodecIdAssertNoSinks, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, a2dp_offload_codec_extensibility))) { GetProviderInfoForTesting(true, false); std::optional a2dp_codec_index_opt; auto codecInfoArray = test_sink_provider_info.codecInfos; - a2dp_codec_index_opt = provider_info->SinkCodecIndex( - 0, static_cast(CodecId::A2dp::SBC)); + a2dp_codec_index_opt = + provider_info->SinkCodecIndex(0, static_cast(CodecId::A2dp::SBC)); ASSERT_FALSE(a2dp_codec_index_opt.has_value()); - a2dp_codec_index_opt = provider_info->SinkCodecIndex( - 0, static_cast(CodecId::A2dp::AAC)); + a2dp_codec_index_opt = + provider_info->SinkCodecIndex(0, static_cast(CodecId::A2dp::AAC)); ASSERT_FALSE(a2dp_codec_index_opt.has_value()); - a2dp_codec_index_opt = provider_info->SinkCodecIndex( - test_opus_codec_id.id, test_opus_codec_id.codecId); + a2dp_codec_index_opt = + provider_info->SinkCodecIndex(test_opus_codec_id.id, test_opus_codec_id.codecId); ASSERT_FALSE(a2dp_codec_index_opt.has_value()); - a2dp_codec_index_opt = provider_info->SinkCodecIndex( - test_foobar_codec_id.id, test_foobar_codec_id.codecId); + a2dp_codec_index_opt = + provider_info->SinkCodecIndex(test_foobar_codec_id.id, test_foobar_codec_id.codecId); ASSERT_FALSE(a2dp_codec_index_opt.has_value()); - a2dp_codec_index_opt = provider_info->SinkCodecIndex( - test_unknown_vendor_codec_id.id, test_unknown_vendor_codec_id.codecId); + a2dp_codec_index_opt = provider_info->SinkCodecIndex(test_unknown_vendor_codec_id.id, + test_unknown_vendor_codec_id.codecId); ASSERT_FALSE(a2dp_codec_index_opt.has_value()); } TEST_F_WITH_FLAGS(ProviderInfoTest, TestCodecIndexStr, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG( - TEST_BT, a2dp_offload_codec_extensibility))) { + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, a2dp_offload_codec_extensibility))) { GetProviderInfoForTesting(true, false); auto codecInfoArray = test_source_provider_info.codecInfos; - ASSERT_EQ(provider_info->CodecIndexStr(BTAV_A2DP_CODEC_INDEX_SOURCE_SBC), - codecInfoArray[0].name); + ASSERT_EQ(provider_info->CodecIndexStr(BTAV_A2DP_CODEC_INDEX_SOURCE_SBC), codecInfoArray[0].name); - ASSERT_EQ(provider_info->CodecIndexStr(BTAV_A2DP_CODEC_INDEX_SOURCE_AAC), - codecInfoArray[1].name); + ASSERT_EQ(provider_info->CodecIndexStr(BTAV_A2DP_CODEC_INDEX_SOURCE_AAC), codecInfoArray[1].name); ASSERT_EQ(provider_info->CodecIndexStr(BTAV_A2DP_CODEC_INDEX_SOURCE_OPUS), codecInfoArray[2].name); @@ -567,8 +513,7 @@ TEST_F_WITH_FLAGS(ProviderInfoTest, TestCodecIndexStr, } TEST_F_WITH_FLAGS(ProviderInfoTest, TestSupportsCodec, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG( - TEST_BT, a2dp_offload_codec_extensibility))) { + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, a2dp_offload_codec_extensibility))) { GetProviderInfoForTesting(true, true); for (int i = static_cast(BTAV_A2DP_CODEC_INDEX_SOURCE_MIN); @@ -582,191 +527,162 @@ TEST_F_WITH_FLAGS(ProviderInfoTest, TestSupportsCodec, case BTAV_A2DP_CODEC_INDEX_SINK_AAC: case BTAV_A2DP_CODEC_INDEX_SINK_OPUS: case BTAV_A2DP_CODEC_INDEX_SINK_EXT_MIN: - ASSERT_TRUE(provider_info->SupportsCodec( - static_cast(i))); + ASSERT_TRUE(provider_info->SupportsCodec(static_cast(i))); break; default: - ASSERT_FALSE(provider_info->SupportsCodec( - static_cast(i))); + ASSERT_FALSE(provider_info->SupportsCodec(static_cast(i))); break; } } } TEST_F_WITH_FLAGS(ProviderInfoTest, TestBuildCodecCapabilitiesSbc, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG( - TEST_BT, a2dp_offload_codec_extensibility))) { + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, a2dp_offload_codec_extensibility))) { GetProviderInfoForTesting(true, false); std::vector sbc_caps = {0x3f, 0xff, 0x02, 0x25}; uint8_t result_sbc_codec_info[7]; - ASSERT_TRUE(ProviderInfo::BuildCodecCapabilities( - CodecId::A2dp(CodecId::A2dp::SBC), sbc_caps, result_sbc_codec_info)); + ASSERT_TRUE(ProviderInfo::BuildCodecCapabilities(CodecId::A2dp(CodecId::A2dp::SBC), sbc_caps, + result_sbc_codec_info)); ASSERT_EQ(std::memcmp(result_sbc_codec_info, test_sbc_codec_info.data(), test_sbc_codec_info.size()), 0); } TEST_F_WITH_FLAGS(ProviderInfoTest, TestBuildCodecCapabilitiesAac, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG( - TEST_BT, a2dp_offload_codec_extensibility))) { + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, a2dp_offload_codec_extensibility))) { GetProviderInfoForTesting(true, false); std::vector aac_caps = {0x80, 0x01, 0x8c, 0x83, 0xe8, 0x00}; uint8_t result_aac_codec_info[9]; - ASSERT_TRUE(ProviderInfo::BuildCodecCapabilities( - CodecId::A2dp(CodecId::A2dp::AAC), aac_caps, result_aac_codec_info)); + ASSERT_TRUE(ProviderInfo::BuildCodecCapabilities(CodecId::A2dp(CodecId::A2dp::AAC), aac_caps, + result_aac_codec_info)); ASSERT_EQ(std::memcmp(result_aac_codec_info, test_aac_codec_info.data(), test_aac_codec_info.size()), 0); } TEST_F_WITH_FLAGS(ProviderInfoTest, TestBuildCodecCapabilitiesOpus, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG( - TEST_BT, a2dp_offload_codec_extensibility))) { + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, a2dp_offload_codec_extensibility))) { std::vector opus_caps = {0x3c}; uint8_t result_opus_codec_info[10]; - ASSERT_TRUE(ProviderInfo::BuildCodecCapabilities( - test_opus_codec_id, opus_caps, result_opus_codec_info)); + ASSERT_TRUE(ProviderInfo::BuildCodecCapabilities(test_opus_codec_id, opus_caps, + result_opus_codec_info)); ASSERT_EQ(std::memcmp(result_opus_codec_info, test_opus_codec_info.data(), test_opus_codec_info.size()), 0); } TEST_F_WITH_FLAGS(ProviderInfoTest, TestBuildCodecCapabilitiesFoobar, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG( - TEST_BT, a2dp_offload_codec_extensibility))) { + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, a2dp_offload_codec_extensibility))) { std::vector foobar_caps = {0x3c}; uint8_t result_foobar_codec_info[10]; - ASSERT_TRUE(ProviderInfo::BuildCodecCapabilities( - test_foobar_codec_id, foobar_caps, result_foobar_codec_info)); + ASSERT_TRUE(ProviderInfo::BuildCodecCapabilities(test_foobar_codec_id, foobar_caps, + result_foobar_codec_info)); ASSERT_EQ(std::memcmp(result_foobar_codec_info, test_foobar_codec_info.data(), test_foobar_codec_info.size()), 0); } TEST_F_WITH_FLAGS(ProviderInfoTest, TestBuildCodecCapabilitiesNotSupported, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG( - TEST_BT, a2dp_offload_codec_extensibility))) { + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, a2dp_offload_codec_extensibility))) { std::vector foobar_caps = {0x3c}; uint8_t result_foobar_codec_info[10]; - ASSERT_FALSE(ProviderInfo::BuildCodecCapabilities( - CodecId::Core(CodecId::Core::CVSD), foobar_caps, - result_foobar_codec_info)); + ASSERT_FALSE(ProviderInfo::BuildCodecCapabilities(CodecId::Core(CodecId::Core::CVSD), foobar_caps, + result_foobar_codec_info)); } TEST_F_WITH_FLAGS(ProviderInfoTest, TestCodecCapabilitiesSbc, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG( - TEST_BT, a2dp_offload_codec_extensibility))) { + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, a2dp_offload_codec_extensibility))) { GetProviderInfoForTesting(true, false); uint8_t result_codec_info[20]; btav_a2dp_codec_config_t result_codec_config; uint64_t result_codec_id; - ASSERT_TRUE(provider_info->CodecCapabilities( - BTAV_A2DP_CODEC_INDEX_SOURCE_SBC, &result_codec_id, result_codec_info, - &result_codec_config)); + ASSERT_TRUE(provider_info->CodecCapabilities(BTAV_A2DP_CODEC_INDEX_SOURCE_SBC, &result_codec_id, + result_codec_info, &result_codec_config)); ASSERT_EQ(result_codec_id, A2DP_CODEC_ID_SBC); - ASSERT_EQ(std::memcmp(result_codec_info, test_sbc_codec_info.data(), - test_sbc_codec_info.size()), + ASSERT_EQ(std::memcmp(result_codec_info, test_sbc_codec_info.data(), test_sbc_codec_info.size()), 0); ASSERT_TRUE(result_codec_config.channel_mode == - (BTAV_A2DP_CODEC_CHANNEL_MODE_MONO | - BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO)); - ASSERT_TRUE( - result_codec_config.sample_rate == - (BTAV_A2DP_CODEC_SAMPLE_RATE_44100 | BTAV_A2DP_CODEC_SAMPLE_RATE_48000)); + (BTAV_A2DP_CODEC_CHANNEL_MODE_MONO | BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO)); + ASSERT_TRUE(result_codec_config.sample_rate == + (BTAV_A2DP_CODEC_SAMPLE_RATE_44100 | BTAV_A2DP_CODEC_SAMPLE_RATE_48000)); ASSERT_TRUE(result_codec_config.bits_per_sample == - (BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16 | - BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24 | + (BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16 | BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24 | BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32)); } TEST_F_WITH_FLAGS(ProviderInfoTest, TestCodecCapabilitiesAac, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG( - TEST_BT, a2dp_offload_codec_extensibility))) { + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, a2dp_offload_codec_extensibility))) { GetProviderInfoForTesting(true, false); uint8_t result_codec_info[20]; btav_a2dp_codec_config_t result_codec_config; uint64_t result_codec_id; - ASSERT_TRUE(provider_info->CodecCapabilities( - BTAV_A2DP_CODEC_INDEX_SOURCE_AAC, &result_codec_id, result_codec_info, - &result_codec_config)); + ASSERT_TRUE(provider_info->CodecCapabilities(BTAV_A2DP_CODEC_INDEX_SOURCE_AAC, &result_codec_id, + result_codec_info, &result_codec_config)); ASSERT_EQ(result_codec_id, A2DP_CODEC_ID_AAC); - ASSERT_EQ(std::memcmp(result_codec_info, test_aac_codec_info.data(), - test_aac_codec_info.size()), + ASSERT_EQ(std::memcmp(result_codec_info, test_aac_codec_info.data(), test_aac_codec_info.size()), 0); ASSERT_TRUE(result_codec_config.channel_mode == - (BTAV_A2DP_CODEC_CHANNEL_MODE_MONO | - BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO)); - ASSERT_TRUE( - result_codec_config.sample_rate == - (BTAV_A2DP_CODEC_SAMPLE_RATE_44100 | BTAV_A2DP_CODEC_SAMPLE_RATE_48000)); + (BTAV_A2DP_CODEC_CHANNEL_MODE_MONO | BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO)); + ASSERT_TRUE(result_codec_config.sample_rate == + (BTAV_A2DP_CODEC_SAMPLE_RATE_44100 | BTAV_A2DP_CODEC_SAMPLE_RATE_48000)); ASSERT_TRUE(result_codec_config.bits_per_sample == - (BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16 | - BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24 | + (BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16 | BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24 | BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32)); } TEST_F_WITH_FLAGS(ProviderInfoTest, TestCodecCapabilitiesOpus, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG( - TEST_BT, a2dp_offload_codec_extensibility))) { + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, a2dp_offload_codec_extensibility))) { GetProviderInfoForTesting(true, false); uint8_t result_codec_info[20]; btav_a2dp_codec_config_t result_codec_config; uint64_t result_codec_id; - ASSERT_TRUE(provider_info->CodecCapabilities( - BTAV_A2DP_CODEC_INDEX_SOURCE_OPUS, &result_codec_id, result_codec_info, - &result_codec_config)); + ASSERT_TRUE(provider_info->CodecCapabilities(BTAV_A2DP_CODEC_INDEX_SOURCE_OPUS, &result_codec_id, + result_codec_info, &result_codec_config)); ASSERT_EQ(result_codec_id, A2DP_CODEC_ID_OPUS); - ASSERT_EQ(std::memcmp(result_codec_info, test_opus_codec_info.data(), - test_opus_codec_info.size()), - 0); + ASSERT_EQ( + std::memcmp(result_codec_info, test_opus_codec_info.data(), test_opus_codec_info.size()), + 0); ASSERT_TRUE(result_codec_config.channel_mode == - (BTAV_A2DP_CODEC_CHANNEL_MODE_MONO | - BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO)); - ASSERT_TRUE( - result_codec_config.sample_rate == - (BTAV_A2DP_CODEC_SAMPLE_RATE_44100 | BTAV_A2DP_CODEC_SAMPLE_RATE_48000)); + (BTAV_A2DP_CODEC_CHANNEL_MODE_MONO | BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO)); + ASSERT_TRUE(result_codec_config.sample_rate == + (BTAV_A2DP_CODEC_SAMPLE_RATE_44100 | BTAV_A2DP_CODEC_SAMPLE_RATE_48000)); ASSERT_TRUE(result_codec_config.bits_per_sample == - (BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16 | - BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24 | + (BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16 | BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24 | BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32)); } TEST_F_WITH_FLAGS(ProviderInfoTest, TestCodecCapabilitiesFoobar, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG( - TEST_BT, a2dp_offload_codec_extensibility))) { + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, a2dp_offload_codec_extensibility))) { GetProviderInfoForTesting(true, false); uint8_t result_codec_info[20]; btav_a2dp_codec_config_t result_codec_config; uint64_t result_codec_id; - ASSERT_TRUE(provider_info->CodecCapabilities( - BTAV_A2DP_CODEC_INDEX_SOURCE_EXT_MIN, &result_codec_id, result_codec_info, - &result_codec_config)); + ASSERT_TRUE(provider_info->CodecCapabilities(BTAV_A2DP_CODEC_INDEX_SOURCE_EXT_MIN, + &result_codec_id, result_codec_info, + &result_codec_config)); ASSERT_EQ(result_codec_id, static_cast(0x11223344ff)); ASSERT_EQ(std::memcmp(result_codec_info, test_foobar_codec_info.data(), test_foobar_codec_info.size()), 0); ASSERT_TRUE(result_codec_config.channel_mode == - (BTAV_A2DP_CODEC_CHANNEL_MODE_MONO | - BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO)); - ASSERT_TRUE( - result_codec_config.sample_rate == - (BTAV_A2DP_CODEC_SAMPLE_RATE_44100 | BTAV_A2DP_CODEC_SAMPLE_RATE_48000)); + (BTAV_A2DP_CODEC_CHANNEL_MODE_MONO | BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO)); + ASSERT_TRUE(result_codec_config.sample_rate == + (BTAV_A2DP_CODEC_SAMPLE_RATE_44100 | BTAV_A2DP_CODEC_SAMPLE_RATE_48000)); ASSERT_TRUE(result_codec_config.bits_per_sample == - (BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16 | - BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24 | + (BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16 | BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24 | BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32)); } diff --git a/system/audio_hal_interface/aidl/a2dp_transport.h b/system/audio_hal_interface/aidl/a2dp_transport.h index f0cf26186f1..08f906dcfee 100644 --- a/system/audio_hal_interface/aidl/a2dp_transport.h +++ b/system/audio_hal_interface/aidl/a2dp_transport.h @@ -40,9 +40,8 @@ namespace { using ::bluetooth::audio::aidl::LatencyMode; // Provide call-in APIs for the Bluetooth Audio HAL -class A2dpTransport - : public ::bluetooth::audio::aidl::IBluetoothSinkTransportInstance { - public: +class A2dpTransport : public ::bluetooth::audio::aidl::IBluetoothSinkTransportInstance { +public: A2dpTransport(SessionType sessionType); BluetoothAudioCtrlAck StartRequest(bool is_low_latency) override; @@ -53,8 +52,7 @@ class A2dpTransport void SetLatencyMode(LatencyMode latency_mode) override; - bool GetPresentationPosition(uint64_t* remote_delay_report_ns, - uint64_t* total_bytes_read, + bool GetPresentationPosition(uint64_t* remote_delay_report_ns, uint64_t* total_bytes_read, timespec* data_position) override; void SourceMetadataChanged(const source_metadata_v7_t& source_metadata); @@ -72,7 +70,7 @@ class A2dpTransport // delay reports from AVDTP is based on 1/10 ms (100us) void SetRemoteDelay(uint16_t delay_report); - private: +private: static tA2DP_CTRL_CMD a2dp_pending_cmd_; static uint16_t remote_delay_report_; uint64_t total_bytes_read_; diff --git a/system/audio_hal_interface/aidl/audio_ctrl_ack.h b/system/audio_hal_interface/aidl/audio_ctrl_ack.h index 220a55cf66b..5cd051ca837 100644 --- a/system/audio_hal_interface/aidl/audio_ctrl_ack.h +++ b/system/audio_hal_interface/aidl/audio_ctrl_ack.h @@ -63,6 +63,5 @@ BluetoothAudioCtrlAckToHalStatus(const BluetoothAudioCtrlAck& ack) { namespace fmt { template <> -struct formatter - : ostream_formatter {}; +struct formatter : ostream_formatter {}; } // namespace fmt diff --git a/system/audio_hal_interface/aidl/bluetooth_audio_port_impl.cc b/system/audio_hal_interface/aidl/bluetooth_audio_port_impl.cc index b140b1f2ec9..b9055deb9f1 100644 --- a/system/audio_hal_interface/aidl/bluetooth_audio_port_impl.cc +++ b/system/audio_hal_interface/aidl/bluetooth_audio_port_impl.cc @@ -32,8 +32,8 @@ namespace aidl { using ::bluetooth::common::StopWatchLegacy; BluetoothAudioPortImpl::BluetoothAudioPortImpl( - IBluetoothTransportInstance* transport_instance, - const std::shared_ptr& provider) + IBluetoothTransportInstance* transport_instance, + const std::shared_ptr& provider) : transport_instance_(transport_instance), provider_(provider) {} BluetoothAudioPortImpl::~BluetoothAudioPortImpl() {} @@ -42,8 +42,7 @@ ndk::ScopedAStatus BluetoothAudioPortImpl::startStream(bool is_low_latency) { StopWatchLegacy stop_watch(__func__); BluetoothAudioCtrlAck ack = transport_instance_->StartRequest(is_low_latency); if (ack != BluetoothAudioCtrlAck::PENDING) { - auto aidl_retval = - provider_->streamStarted(BluetoothAudioCtrlAckToHalStatus(ack)); + auto aidl_retval = provider_->streamStarted(BluetoothAudioCtrlAckToHalStatus(ack)); if (!aidl_retval.isOk()) { log::error("BluetoothAudioHal failure: {}", aidl_retval.getDescription()); } @@ -55,8 +54,7 @@ ndk::ScopedAStatus BluetoothAudioPortImpl::suspendStream() { StopWatchLegacy stop_watch(__func__); BluetoothAudioCtrlAck ack = transport_instance_->SuspendRequest(); if (ack != BluetoothAudioCtrlAck::PENDING) { - auto aidl_retval = - provider_->streamSuspended(BluetoothAudioCtrlAckToHalStatus(ack)); + auto aidl_retval = provider_->streamSuspended(BluetoothAudioCtrlAckToHalStatus(ack)); if (!aidl_retval.isOk()) { log::error("BluetoothAudioHal failure: {}", aidl_retval.getDescription()); } @@ -71,13 +69,13 @@ ndk::ScopedAStatus BluetoothAudioPortImpl::stopStream() { } ndk::ScopedAStatus BluetoothAudioPortImpl::getPresentationPosition( - PresentationPosition* _aidl_return) { + PresentationPosition* _aidl_return) { StopWatchLegacy stop_watch(__func__); uint64_t remote_delay_report_ns; uint64_t total_bytes_read; timespec data_position; - bool retval = transport_instance_->GetPresentationPosition( - &remote_delay_report_ns, &total_bytes_read, &data_position); + bool retval = transport_instance_->GetPresentationPosition(&remote_delay_report_ns, + &total_bytes_read, &data_position); PresentationPosition::TimeSpec transmittedOctetsTimeStamp; if (retval) { @@ -87,18 +85,16 @@ ndk::ScopedAStatus BluetoothAudioPortImpl::getPresentationPosition( total_bytes_read = 0; transmittedOctetsTimeStamp = {}; } - log::verbose("result={}, delay={}, data={} byte(s), timestamp={}", retval, - remote_delay_report_ns, total_bytes_read, - transmittedOctetsTimeStamp.toString()); - _aidl_return->remoteDeviceAudioDelayNanos = - static_cast(remote_delay_report_ns); + log::verbose("result={}, delay={}, data={} byte(s), timestamp={}", retval, remote_delay_report_ns, + total_bytes_read, transmittedOctetsTimeStamp.toString()); + _aidl_return->remoteDeviceAudioDelayNanos = static_cast(remote_delay_report_ns); _aidl_return->transmittedOctets = static_cast(total_bytes_read); _aidl_return->transmittedOctetsTimestamp = transmittedOctetsTimeStamp; return ndk::ScopedAStatus::ok(); } ndk::ScopedAStatus BluetoothAudioPortImpl::updateSourceMetadata( - const SourceMetadata& source_metadata) { + const SourceMetadata& source_metadata) { StopWatchLegacy stop_watch(__func__); log::info("{} track(s)", source_metadata.tracks.size()); @@ -109,10 +105,9 @@ ndk::ScopedAStatus BluetoothAudioPortImpl::updateSourceMetadata( log::info("metadata tags size: {}", num_of_tags); playback_track_metadata_v7 desc_track = { - .base = {.usage = static_cast(track.usage), - .content_type = - static_cast(track.contentType), - .gain = track.gain}, + .base = {.usage = static_cast(track.usage), + .content_type = static_cast(track.contentType), + .gain = track.gain}, }; if (num_of_tags != 0) { @@ -122,8 +117,7 @@ ndk::ScopedAStatus BluetoothAudioPortImpl::updateSourceMetadata( for (size_t i = 0; i < num_of_tags - 1; i++) { int string_len = track.tags[i].length(); - if ((copied_size >= max_tags_size) || - (copied_size + string_len >= max_tags_size)) { + if ((copied_size >= max_tags_size) || (copied_size + string_len >= max_tags_size)) { log::error("Too many tags, copied size: {}", copied_size); break; } @@ -135,12 +129,10 @@ ndk::ScopedAStatus BluetoothAudioPortImpl::updateSourceMetadata( } int string_len = track.tags[num_of_tags - 1].length(); - if ((copied_size >= max_tags_size) || - (copied_size + string_len >= max_tags_size)) { + if ((copied_size >= max_tags_size) || (copied_size + string_len >= max_tags_size)) { log::error("Too many tags, copied size: {}", copied_size); } else { - track.tags[num_of_tags - 1].copy(desc_track.tags + copied_size, - string_len, 0); + track.tags[num_of_tags - 1].copy(desc_track.tags + copied_size, string_len, 0); } } else { memset(desc_track.tags, 0, sizeof(desc_track.tags)); @@ -149,14 +141,13 @@ ndk::ScopedAStatus BluetoothAudioPortImpl::updateSourceMetadata( tracks_vec.push_back(desc_track); } - const source_metadata_v7_t legacy_source_metadata = { - .track_count = tracks_vec.size(), .tracks = tracks_vec.data()}; + const source_metadata_v7_t legacy_source_metadata = {.track_count = tracks_vec.size(), + .tracks = tracks_vec.data()}; transport_instance_->SourceMetadataChanged(legacy_source_metadata); return ndk::ScopedAStatus::ok(); } -ndk::ScopedAStatus BluetoothAudioPortImpl::updateSinkMetadata( - const SinkMetadata& sink_metadata) { +ndk::ScopedAStatus BluetoothAudioPortImpl::updateSinkMetadata(const SinkMetadata& sink_metadata) { StopWatchLegacy stop_watch(__func__); log::info("{} track(s)", sink_metadata.tracks.size()); @@ -167,11 +158,11 @@ ndk::ScopedAStatus BluetoothAudioPortImpl::updateSinkMetadata( log::info("metadata tags size: {}", num_of_tags); record_track_metadata_v7 desc_track = { - .base = - { - .source = static_cast(track.source), - .gain = track.gain, - }, + .base = + { + .source = static_cast(track.source), + .gain = track.gain, + }, }; if (num_of_tags != 0) { @@ -181,8 +172,7 @@ ndk::ScopedAStatus BluetoothAudioPortImpl::updateSinkMetadata( for (size_t i = 0; i < num_of_tags - 1; i++) { int string_len = track.tags[i].length(); - if ((copied_size >= max_tags_size) || - (copied_size + string_len >= max_tags_size)) { + if ((copied_size >= max_tags_size) || (copied_size + string_len >= max_tags_size)) { log::error("Too many tags, copied size: {}", copied_size); break; } @@ -194,12 +184,10 @@ ndk::ScopedAStatus BluetoothAudioPortImpl::updateSinkMetadata( } int string_len = track.tags[num_of_tags - 1].length(); - if ((copied_size >= max_tags_size) || - (copied_size + string_len >= max_tags_size)) { + if ((copied_size >= max_tags_size) || (copied_size + string_len >= max_tags_size)) { log::error("Too many tags, copied size: {}", copied_size); } else { - track.tags[num_of_tags - 1].copy(desc_track.tags + copied_size, - string_len, 0); + track.tags[num_of_tags - 1].copy(desc_track.tags + copied_size, string_len, 0); } } else { memset(desc_track.tags, 0, sizeof(desc_track.tags)); @@ -208,24 +196,21 @@ ndk::ScopedAStatus BluetoothAudioPortImpl::updateSinkMetadata( tracks_vec.push_back(desc_track); } - const sink_metadata_v7_t legacy_sink_metadata = { - .track_count = tracks_vec.size(), .tracks = tracks_vec.data()}; + const sink_metadata_v7_t legacy_sink_metadata = {.track_count = tracks_vec.size(), + .tracks = tracks_vec.data()}; transport_instance_->SinkMetadataChanged(legacy_sink_metadata); return ndk::ScopedAStatus::ok(); } -ndk::ScopedAStatus BluetoothAudioPortImpl::setLatencyMode( - LatencyMode latency_mode) { +ndk::ScopedAStatus BluetoothAudioPortImpl::setLatencyMode(LatencyMode latency_mode) { bool is_low_latency = latency_mode == LatencyMode::LOW_LATENCY ? true : false; invoke_switch_buffer_size_cb(is_low_latency); transport_instance_->SetLatencyMode(latency_mode); return ndk::ScopedAStatus::ok(); } -PresentationPosition::TimeSpec BluetoothAudioPortImpl::timespec_convert_to_hal( - const timespec& ts) { - return {.tvSec = static_cast(ts.tv_sec), - .tvNSec = static_cast(ts.tv_nsec)}; +PresentationPosition::TimeSpec BluetoothAudioPortImpl::timespec_convert_to_hal(const timespec& ts) { + return {.tvSec = static_cast(ts.tv_sec), .tvNSec = static_cast(ts.tv_nsec)}; } // Overriding create binder and inherit RT from caller. diff --git a/system/audio_hal_interface/aidl/bluetooth_audio_port_impl.h b/system/audio_hal_interface/aidl/bluetooth_audio_port_impl.h index 95e0f89856d..fb116e9f19f 100644 --- a/system/audio_hal_interface/aidl/bluetooth_audio_port_impl.h +++ b/system/audio_hal_interface/aidl/bluetooth_audio_port_impl.h @@ -32,10 +32,9 @@ using ::aidl::android::hardware::bluetooth::audio::LatencyMode; using ::aidl::android::hardware::bluetooth::audio::PresentationPosition; class BluetoothAudioPortImpl : public BnBluetoothAudioPort { - public: - BluetoothAudioPortImpl( - IBluetoothTransportInstance* transport_instance, - const std::shared_ptr& provider); +public: + BluetoothAudioPortImpl(IBluetoothTransportInstance* transport_instance, + const std::shared_ptr& provider); ndk::ScopedAStatus startStream(bool is_low_latency) override; @@ -43,25 +42,22 @@ class BluetoothAudioPortImpl : public BnBluetoothAudioPort { ndk::ScopedAStatus stopStream() override; - ndk::ScopedAStatus getPresentationPosition( - PresentationPosition* _aidl_return) override; + ndk::ScopedAStatus getPresentationPosition(PresentationPosition* _aidl_return) override; - ndk::ScopedAStatus updateSourceMetadata( - const SourceMetadata& source_metadata) override; + ndk::ScopedAStatus updateSourceMetadata(const SourceMetadata& source_metadata) override; - ndk::ScopedAStatus updateSinkMetadata( - const SinkMetadata& sink_metadata) override; + ndk::ScopedAStatus updateSinkMetadata(const SinkMetadata& sink_metadata) override; ndk::ScopedAStatus setLatencyMode(LatencyMode latency_mode) override; - protected: +protected: virtual ~BluetoothAudioPortImpl(); IBluetoothTransportInstance* transport_instance_; const std::shared_ptr provider_; PresentationPosition::TimeSpec timespec_convert_to_hal(const timespec& ts); - private: +private: ndk::ScopedAStatus switchCodec(bool isLowLatency); ndk::SpAIBinder createBinder() override; diff --git a/system/audio_hal_interface/aidl/client_interface_aidl.cc b/system/audio_hal_interface/aidl/client_interface_aidl.cc index 32e96872d06..3db108d206e 100644 --- a/system/audio_hal_interface/aidl/client_interface_aidl.cc +++ b/system/audio_hal_interface/aidl/client_interface_aidl.cc @@ -50,49 +50,42 @@ std::ostream& operator<<(std::ostream& os, const BluetoothAudioCtrlAck& ack) { } } -BluetoothAudioClientInterface::BluetoothAudioClientInterface( - IBluetoothTransportInstance* instance) +BluetoothAudioClientInterface::BluetoothAudioClientInterface(IBluetoothTransportInstance* instance) : provider_(nullptr), provider_factory_(nullptr), session_started_(false), data_mq_(nullptr), transport_(instance), latency_modes_({LatencyMode::FREE}) { - death_recipient_ = ::ndk::ScopedAIBinder_DeathRecipient( - AIBinder_DeathRecipient_new(binderDiedCallbackAidl)); + death_recipient_ = + ::ndk::ScopedAIBinder_DeathRecipient(AIBinder_DeathRecipient_new(binderDiedCallbackAidl)); } -bool BluetoothAudioClientInterface::IsValid() const { - return provider_ != nullptr; -} +bool BluetoothAudioClientInterface::IsValid() const { return provider_ != nullptr; } bool BluetoothAudioClientInterface::is_aidl_available() { - return AServiceManager_isDeclared( - kDefaultAudioProviderFactoryInterface.c_str()); + return AServiceManager_isDeclared(kDefaultAudioProviderFactoryInterface.c_str()); } -std::vector -BluetoothAudioClientInterface::GetAudioCapabilities() const { +std::vector BluetoothAudioClientInterface::GetAudioCapabilities() const { return capabilities_; } -std::vector -BluetoothAudioClientInterface::GetAudioCapabilities(SessionType session_type) { +std::vector BluetoothAudioClientInterface::GetAudioCapabilities( + SessionType session_type) { std::vector capabilities(0); if (!is_aidl_available()) { return capabilities; } - auto provider_factory = IBluetoothAudioProviderFactory::fromBinder( - ::ndk::SpAIBinder(AServiceManager_waitForService( - kDefaultAudioProviderFactoryInterface.c_str()))); + auto provider_factory = IBluetoothAudioProviderFactory::fromBinder(::ndk::SpAIBinder( + AServiceManager_waitForService(kDefaultAudioProviderFactoryInterface.c_str()))); if (provider_factory == nullptr) { log::error("can't get capability from unknown factory"); return capabilities; } - auto aidl_retval = - provider_factory->getProviderCapabilities(session_type, &capabilities); + auto aidl_retval = provider_factory->getProviderCapabilities(session_type, &capabilities); if (!aidl_retval.isOk()) { log::fatal("BluetoothAudioHal::getProviderCapabilities failure: {}", aidl_retval.getDescription()); @@ -102,17 +95,15 @@ BluetoothAudioClientInterface::GetAudioCapabilities(SessionType session_type) { std::optional BluetoothAudioClientInterface::GetProviderInfo( - SessionType session_type, - std::shared_ptr provider_factory) { - if (!is_aidl_available() || - !com::android::bluetooth::flags::a2dp_offload_codec_extensibility()) { + SessionType session_type, + std::shared_ptr provider_factory) { + if (!is_aidl_available() || !com::android::bluetooth::flags::a2dp_offload_codec_extensibility()) { return std::nullopt; } if (provider_factory == nullptr) { - provider_factory = IBluetoothAudioProviderFactory::fromBinder( - ::ndk::SpAIBinder(AServiceManager_waitForService( - kDefaultAudioProviderFactoryInterface.c_str()))); + provider_factory = IBluetoothAudioProviderFactory::fromBinder(::ndk::SpAIBinder( + AServiceManager_waitForService(kDefaultAudioProviderFactoryInterface.c_str()))); } if (provider_factory == nullptr) { @@ -120,26 +111,21 @@ BluetoothAudioClientInterface::GetProviderInfo( return std::nullopt; } - std::optional provider_info = - {}; - auto aidl_retval = - provider_factory->getProviderInfo(session_type, &provider_info); + std::optional provider_info = {}; + auto aidl_retval = provider_factory->getProviderInfo(session_type, &provider_info); if (!aidl_retval.isOk()) { - log::error("BluetoothAudioHal::getProviderInfo failure: {}", - aidl_retval.getDescription()); + log::error("BluetoothAudioHal::getProviderInfo failure: {}", aidl_retval.getDescription()); return std::nullopt; } return provider_info; } -std::optional -BluetoothAudioClientInterface::GetA2dpConfiguration( - std::vector const& remote_capabilities, - A2dpConfigurationHint const& hint) const { - if (!is_aidl_available() || - !com::android::bluetooth::flags::a2dp_offload_codec_extensibility()) { +std::optional BluetoothAudioClientInterface::GetA2dpConfiguration( + std::vector const& remote_capabilities, + A2dpConfigurationHint const& hint) const { + if (!is_aidl_available() || !com::android::bluetooth::flags::a2dp_offload_codec_extensibility()) { return std::nullopt; } @@ -149,12 +135,10 @@ BluetoothAudioClientInterface::GetA2dpConfiguration( } std::optional configuration = std::nullopt; - auto aidl_retval = provider_->getA2dpConfiguration(remote_capabilities, hint, - &configuration); + auto aidl_retval = provider_->getA2dpConfiguration(remote_capabilities, hint, &configuration); if (!aidl_retval.isOk()) { - log::error("getA2dpConfiguration failure: {}", - aidl_retval.getDescription()); + log::error("getA2dpConfiguration failure: {}", aidl_retval.getDescription()); return std::nullopt; } @@ -162,8 +146,8 @@ BluetoothAudioClientInterface::GetA2dpConfiguration( } std::optional BluetoothAudioClientInterface::ParseA2dpConfiguration( - const CodecId& codec_id, const std::vector& configuration, - CodecParameters* codec_parameters) const { + const CodecId& codec_id, const std::vector& configuration, + CodecParameters* codec_parameters) const { A2dpStatus a2dp_status; if (provider_ == nullptr) { @@ -171,12 +155,11 @@ std::optional BluetoothAudioClientInterface::ParseA2dpConfiguration( return std::nullopt; } - auto aidl_retval = provider_->parseA2dpConfiguration( - codec_id, configuration, codec_parameters, &a2dp_status); + auto aidl_retval = provider_->parseA2dpConfiguration(codec_id, configuration, codec_parameters, + &a2dp_status); if (!aidl_retval.isOk()) { - log::error("parseA2dpConfiguration failure: {}", - aidl_retval.getDescription()); + log::error("parseA2dpConfiguration failure: {}", aidl_retval.getDescription()); return std::nullopt; } @@ -191,9 +174,8 @@ void BluetoothAudioClientInterface::FetchAudioProvider() { if (provider_ != nullptr) { log::warn("refetch"); } - auto provider_factory = IBluetoothAudioProviderFactory::fromBinder( - ::ndk::SpAIBinder(AServiceManager_waitForService( - kDefaultAudioProviderFactoryInterface.c_str()))); + auto provider_factory = IBluetoothAudioProviderFactory::fromBinder(::ndk::SpAIBinder( + AServiceManager_waitForService(kDefaultAudioProviderFactoryInterface.c_str()))); if (provider_factory == nullptr) { log::error("can't get capability from unknown factory"); @@ -201,8 +183,8 @@ void BluetoothAudioClientInterface::FetchAudioProvider() { } capabilities_.clear(); - auto aidl_retval = provider_factory->getProviderCapabilities( - transport_->GetSessionType(), &capabilities_); + auto aidl_retval = + provider_factory->getProviderCapabilities(transport_->GetSessionType(), &capabilities_); if (!aidl_retval.isOk()) { log::fatal("BluetoothAudioHal::getProviderCapabilities failure: {}", aidl_retval.getDescription()); @@ -216,49 +198,44 @@ void BluetoothAudioClientInterface::FetchAudioProvider() { log::info("BluetoothAudioHal SessionType={} has {} AudioCapabilities", toString(transport_->GetSessionType()), capabilities_.size()); - aidl_retval = - provider_factory->openProvider(transport_->GetSessionType(), &provider_); + aidl_retval = provider_factory->openProvider(transport_->GetSessionType(), &provider_); if (!aidl_retval.isOk()) { - log::fatal("BluetoothAudioHal::openProvider failure: {}", - aidl_retval.getDescription()); + log::fatal("BluetoothAudioHal::openProvider failure: {}", aidl_retval.getDescription()); } log::assert_that(provider_ != nullptr, "assert failed: provider_ != nullptr"); - binder_status_t binder_status = AIBinder_linkToDeath( - provider_factory->asBinder().get(), death_recipient_.get(), this); + binder_status_t binder_status = + AIBinder_linkToDeath(provider_factory->asBinder().get(), death_recipient_.get(), this); if (binder_status != STATUS_OK) { log::error("Failed to linkToDeath {}", static_cast(binder_status)); } provider_factory_ = std::move(provider_factory); log::info("IBluetoothAudioProvidersFactory::openProvider() returned {}{}", - fmt::ptr(provider_.get()), - (provider_->isRemote() ? " (remote)" : " (local)")); + fmt::ptr(provider_.get()), (provider_->isRemote() ? " (remote)" : " (local)")); } BluetoothAudioSinkClientInterface::BluetoothAudioSinkClientInterface( - IBluetoothSinkTransportInstance* sink) + IBluetoothSinkTransportInstance* sink) : BluetoothAudioClientInterface{sink}, sink_(sink) { FetchAudioProvider(); } BluetoothAudioSinkClientInterface::~BluetoothAudioSinkClientInterface() { if (provider_factory_ != nullptr) { - AIBinder_unlinkToDeath(provider_factory_->asBinder().get(), - death_recipient_.get(), nullptr); + AIBinder_unlinkToDeath(provider_factory_->asBinder().get(), death_recipient_.get(), nullptr); } } BluetoothAudioSourceClientInterface::BluetoothAudioSourceClientInterface( - IBluetoothSourceTransportInstance* source) + IBluetoothSourceTransportInstance* source) : BluetoothAudioClientInterface{source}, source_(source) { FetchAudioProvider(); } BluetoothAudioSourceClientInterface::~BluetoothAudioSourceClientInterface() { if (provider_factory_ != nullptr) { - AIBinder_unlinkToDeath(provider_factory_->asBinder().get(), - death_recipient_.get(), nullptr); + AIBinder_unlinkToDeath(provider_factory_->asBinder().get(), death_recipient_.get(), nullptr); } } @@ -272,57 +249,45 @@ void BluetoothAudioClientInterface::binderDiedCallbackAidl(void* ptr) { client->RenewAudioProviderAndSession(); } -bool BluetoothAudioClientInterface::UpdateAudioConfig( - const AudioConfiguration& audio_config) { +bool BluetoothAudioClientInterface::UpdateAudioConfig(const AudioConfiguration& audio_config) { bool is_software_session = - (transport_->GetSessionType() == - SessionType::A2DP_SOFTWARE_ENCODING_DATAPATH || - transport_->GetSessionType() == - SessionType::HEARING_AID_SOFTWARE_ENCODING_DATAPATH || - transport_->GetSessionType() == - SessionType::LE_AUDIO_SOFTWARE_ENCODING_DATAPATH || - transport_->GetSessionType() == - SessionType::LE_AUDIO_SOFTWARE_DECODING_DATAPATH || - transport_->GetSessionType() == - SessionType::LE_AUDIO_BROADCAST_SOFTWARE_ENCODING_DATAPATH || - (bta_ag_is_sco_managed_by_audio() && - (transport_->GetSessionType() == - SessionType::HFP_SOFTWARE_ENCODING_DATAPATH || - transport_->GetSessionType() == - SessionType::HFP_SOFTWARE_DECODING_DATAPATH))); + (transport_->GetSessionType() == SessionType::A2DP_SOFTWARE_ENCODING_DATAPATH || + transport_->GetSessionType() == SessionType::HEARING_AID_SOFTWARE_ENCODING_DATAPATH || + transport_->GetSessionType() == SessionType::LE_AUDIO_SOFTWARE_ENCODING_DATAPATH || + transport_->GetSessionType() == SessionType::LE_AUDIO_SOFTWARE_DECODING_DATAPATH || + transport_->GetSessionType() == + SessionType::LE_AUDIO_BROADCAST_SOFTWARE_ENCODING_DATAPATH || + (bta_ag_is_sco_managed_by_audio() && + (transport_->GetSessionType() == SessionType::HFP_SOFTWARE_ENCODING_DATAPATH || + transport_->GetSessionType() == SessionType::HFP_SOFTWARE_DECODING_DATAPATH))); bool is_a2dp_offload_session = - (transport_->GetSessionType() == - SessionType::A2DP_HARDWARE_OFFLOAD_ENCODING_DATAPATH); + (transport_->GetSessionType() == SessionType::A2DP_HARDWARE_OFFLOAD_ENCODING_DATAPATH); bool is_leaudio_unicast_offload_session = - (transport_->GetSessionType() == - SessionType::LE_AUDIO_HARDWARE_OFFLOAD_ENCODING_DATAPATH || - transport_->GetSessionType() == - SessionType::LE_AUDIO_HARDWARE_OFFLOAD_DECODING_DATAPATH); + (transport_->GetSessionType() == + SessionType::LE_AUDIO_HARDWARE_OFFLOAD_ENCODING_DATAPATH || + transport_->GetSessionType() == + SessionType::LE_AUDIO_HARDWARE_OFFLOAD_DECODING_DATAPATH); bool is_leaudio_broadcast_offload_session = - (transport_->GetSessionType() == - SessionType::LE_AUDIO_BROADCAST_HARDWARE_OFFLOAD_ENCODING_DATAPATH); + (transport_->GetSessionType() == + SessionType::LE_AUDIO_BROADCAST_HARDWARE_OFFLOAD_ENCODING_DATAPATH); auto audio_config_tag = audio_config.getTag(); bool is_software_audio_config = - (is_software_session && - audio_config_tag == AudioConfiguration::pcmConfig); + (is_software_session && audio_config_tag == AudioConfiguration::pcmConfig); bool is_a2dp_offload_audio_config = - (is_a2dp_offload_session && - (audio_config_tag == AudioConfiguration::a2dpConfig || - audio_config_tag == AudioConfiguration::a2dp)); + (is_a2dp_offload_session && (audio_config_tag == AudioConfiguration::a2dpConfig || + audio_config_tag == AudioConfiguration::a2dp)); bool is_leaudio_unicast_offload_audio_config = - (is_leaudio_unicast_offload_session && - audio_config_tag == AudioConfiguration::leAudioConfig); + (is_leaudio_unicast_offload_session && + audio_config_tag == AudioConfiguration::leAudioConfig); bool is_leaudio_broadcast_offload_audio_config = - (is_leaudio_broadcast_offload_session && - audio_config_tag == AudioConfiguration::leAudioBroadcastConfig); + (is_leaudio_broadcast_offload_session && + audio_config_tag == AudioConfiguration::leAudioBroadcastConfig); bool is_hfp_offload_audio_config = - (bta_ag_is_sco_managed_by_audio() && - transport_->GetSessionType() == - SessionType::HFP_HARDWARE_OFFLOAD_DATAPATH && - audio_config_tag == AudioConfiguration::hfpConfig); + (bta_ag_is_sco_managed_by_audio() && + transport_->GetSessionType() == SessionType::HFP_HARDWARE_OFFLOAD_DATAPATH && + audio_config_tag == AudioConfiguration::hfpConfig); if (!is_software_audio_config && !is_a2dp_offload_audio_config && - !is_leaudio_unicast_offload_audio_config && - !is_leaudio_broadcast_offload_audio_config && + !is_leaudio_unicast_offload_audio_config && !is_leaudio_broadcast_offload_audio_config && !is_hfp_offload_audio_config) { return false; } @@ -342,22 +307,19 @@ bool BluetoothAudioClientInterface::UpdateAudioConfig( if (!aidl_retval.isOk()) { if (audio_config.getTag() != transport_->GetAudioConfiguration().getTag()) { log::warn( - "BluetoothAudioHal audio config type: {} doesn't " - "match provider's audio config type: {}", - ::aidl::android::hardware::bluetooth::audio::toString( - audio_config.getTag()), - ::aidl::android::hardware::bluetooth::audio::toString( - transport_->GetAudioConfiguration().getTag())); + "BluetoothAudioHal audio config type: {} doesn't " + "match provider's audio config type: {}", + ::aidl::android::hardware::bluetooth::audio::toString(audio_config.getTag()), + ::aidl::android::hardware::bluetooth::audio::toString( + transport_->GetAudioConfiguration().getTag())); } else { - log::warn("BluetoothAudioHal is not ready: {} ", - aidl_retval.getDescription()); + log::warn("BluetoothAudioHal is not ready: {} ", aidl_retval.getDescription()); } } return true; } -bool BluetoothAudioClientInterface::SetAllowedLatencyModes( - std::vector latency_modes) { +bool BluetoothAudioClientInterface::SetAllowedLatencyModes(std::vector latency_modes) { if (provider_ == nullptr) { log::info("BluetoothAudioHal nullptr"); return false; @@ -375,9 +337,8 @@ bool BluetoothAudioClientInterface::SetAllowedLatencyModes( } for (auto latency_mode : latency_modes) { - log::info( - "Latency mode allowed: {}", - ::aidl::android::hardware::bluetooth::audio::toString(latency_mode)); + log::info("Latency mode allowed: {}", + ::aidl::android::hardware::bluetooth::audio::toString(latency_mode)); } /* Low latency mode is used if modes other than FREE are present */ @@ -386,9 +347,9 @@ bool BluetoothAudioClientInterface::SetAllowedLatencyModes( auto aidl_retval = provider_->setLowLatencyModeAllowed(allowed); if (!aidl_retval.isOk()) { log::warn( - "BluetoothAudioHal is not ready: {}. latency_modes_ is saved and it " - "will be sent to BluetoothAudioHal at StartSession.", - aidl_retval.getDescription()); + "BluetoothAudioHal is not ready: {}. latency_modes_ is saved and it " + "will be sent to BluetoothAudioHal at StartSession.", + aidl_retval.getDescription()); } return true; } @@ -406,17 +367,16 @@ int BluetoothAudioClientInterface::StartSession() { } std::shared_ptr stack_if = - ndk::SharedRefBase::make(transport_, provider_); + ndk::SharedRefBase::make(transport_, provider_); std::unique_ptr data_mq; DataMQDesc mq_desc; - auto aidl_retval = provider_->startSession( - stack_if, transport_->GetAudioConfiguration(), latency_modes_, &mq_desc); + auto aidl_retval = provider_->startSession(stack_if, transport_->GetAudioConfiguration(), + latency_modes_, &mq_desc); if (!aidl_retval.isOk()) { if (aidl_retval.getExceptionCode() == EX_ILLEGAL_ARGUMENT) { - log::error("BluetoothAudioHal Error: {}, audioConfig={}", - aidl_retval.getDescription(), + log::error("BluetoothAudioHal Error: {}, audioConfig={}", aidl_retval.getDescription(), transport_->GetAudioConfiguration().toString()); } else { log::fatal("BluetoothAudioHal failure: {}", aidl_retval.getDescription()); @@ -427,18 +387,15 @@ int BluetoothAudioClientInterface::StartSession() { if (data_mq && data_mq->isValid()) { data_mq_ = std::move(data_mq); - } else if (transport_->GetSessionType() == - SessionType::A2DP_HARDWARE_OFFLOAD_ENCODING_DATAPATH || + } else if (transport_->GetSessionType() == SessionType::A2DP_HARDWARE_OFFLOAD_ENCODING_DATAPATH || transport_->GetSessionType() == - SessionType::LE_AUDIO_HARDWARE_OFFLOAD_DECODING_DATAPATH || + SessionType::LE_AUDIO_HARDWARE_OFFLOAD_DECODING_DATAPATH || transport_->GetSessionType() == - SessionType::LE_AUDIO_HARDWARE_OFFLOAD_ENCODING_DATAPATH || + SessionType::LE_AUDIO_HARDWARE_OFFLOAD_ENCODING_DATAPATH || transport_->GetSessionType() == - SessionType:: - LE_AUDIO_BROADCAST_HARDWARE_OFFLOAD_ENCODING_DATAPATH || + SessionType::LE_AUDIO_BROADCAST_HARDWARE_OFFLOAD_ENCODING_DATAPATH || (bta_ag_is_sco_managed_by_audio() && - transport_->GetSessionType() == - SessionType::HFP_HARDWARE_OFFLOAD_DATAPATH)) { + transport_->GetSessionType() == SessionType::HFP_HARDWARE_OFFLOAD_DATAPATH)) { transport_->ResetPresentationPosition(); session_started_ = true; return 0; @@ -459,8 +416,7 @@ int BluetoothAudioClientInterface::StartSession() { } } -void BluetoothAudioClientInterface::StreamStarted( - const BluetoothAudioCtrlAck& ack) { +void BluetoothAudioClientInterface::StreamStarted(const BluetoothAudioCtrlAck& ack) { if (provider_ == nullptr) { log::error("BluetoothAudioHal nullptr"); return; @@ -478,8 +434,7 @@ void BluetoothAudioClientInterface::StreamStarted( } } -void BluetoothAudioClientInterface::StreamSuspended( - const BluetoothAudioCtrlAck& ack) { +void BluetoothAudioClientInterface::StreamSuspended(const BluetoothAudioCtrlAck& ack) { if (provider_ == nullptr) { log::error("BluetoothAudioHal nullptr"); return; @@ -521,15 +476,12 @@ int BluetoothAudioClientInterface::EndSession() { } void BluetoothAudioClientInterface::FlushAudioData() { - if (transport_->GetSessionType() == - SessionType::LE_AUDIO_HARDWARE_OFFLOAD_ENCODING_DATAPATH || + if (transport_->GetSessionType() == SessionType::LE_AUDIO_HARDWARE_OFFLOAD_ENCODING_DATAPATH || + transport_->GetSessionType() == SessionType::LE_AUDIO_HARDWARE_OFFLOAD_DECODING_DATAPATH || transport_->GetSessionType() == - SessionType::LE_AUDIO_HARDWARE_OFFLOAD_DECODING_DATAPATH || - transport_->GetSessionType() == - SessionType::LE_AUDIO_BROADCAST_HARDWARE_OFFLOAD_ENCODING_DATAPATH || + SessionType::LE_AUDIO_BROADCAST_HARDWARE_OFFLOAD_ENCODING_DATAPATH || (bta_ag_is_sco_managed_by_audio() && - transport_->GetSessionType() == - SessionType::HFP_HARDWARE_OFFLOAD_DATAPATH)) { + transport_->GetSessionType() == SessionType::HFP_HARDWARE_OFFLOAD_DATAPATH)) { return; } @@ -549,20 +501,23 @@ void BluetoothAudioClientInterface::FlushAudioData() { } } -size_t BluetoothAudioSinkClientInterface::ReadAudioData(uint8_t* p_buf, - uint32_t len) { +size_t BluetoothAudioSinkClientInterface::ReadAudioData(uint8_t* p_buf, uint32_t len) { if (!IsValid()) { log::error("BluetoothAudioHal is not valid"); return 0; } - if (p_buf == nullptr || len == 0) return 0; + if (p_buf == nullptr || len == 0) { + return 0; + } std::lock_guard guard(internal_mutex_); size_t total_read = 0; int timeout_ms = kDefaultDataReadTimeoutMs; do { - if (data_mq_ == nullptr || !data_mq_->isValid()) break; + if (data_mq_ == nullptr || !data_mq_->isValid()) { + break; + } size_t avail_to_read = data_mq_->availableToRead(); if (avail_to_read) { @@ -575,8 +530,7 @@ size_t BluetoothAudioSinkClientInterface::ReadAudioData(uint8_t* p_buf, } total_read += avail_to_read; } else if (timeout_ms >= kDefaultDataReadPollIntervalMs) { - std::this_thread::sleep_for( - std::chrono::milliseconds(kDefaultDataReadPollIntervalMs)); + std::this_thread::sleep_for(std::chrono::milliseconds(kDefaultDataReadPollIntervalMs)); timeout_ms -= kDefaultDataReadPollIntervalMs; continue; } else { @@ -586,8 +540,7 @@ size_t BluetoothAudioSinkClientInterface::ReadAudioData(uint8_t* p_buf, } } while (total_read < len); - if (timeout_ms < - (kDefaultDataReadTimeoutMs - kDefaultDataReadPollIntervalMs) && + if (timeout_ms < (kDefaultDataReadTimeoutMs - kDefaultDataReadPollIntervalMs) && timeout_ms >= kDefaultDataReadPollIntervalMs) { log::verbose("underflow {} -> {} read {} ms", len, total_read, kDefaultDataReadTimeoutMs - timeout_ms); @@ -612,35 +565,36 @@ void BluetoothAudioClientInterface::RenewAudioProviderAndSession() { } } -size_t BluetoothAudioSourceClientInterface::WriteAudioData(const uint8_t* p_buf, - uint32_t len) { +size_t BluetoothAudioSourceClientInterface::WriteAudioData(const uint8_t* p_buf, uint32_t len) { if (!IsValid()) { log::error("BluetoothAudioHal is not valid"); return 0; } - if (p_buf == nullptr || len == 0) return 0; + if (p_buf == nullptr || len == 0) { + return 0; + } std::lock_guard guard(internal_mutex_); size_t total_written = 0; int timeout_ms = kDefaultDataWriteTimeoutMs; do { - if (data_mq_ == nullptr || !data_mq_->isValid()) break; + if (data_mq_ == nullptr || !data_mq_->isValid()) { + break; + } size_t avail_to_write = data_mq_->availableToWrite(); if (avail_to_write) { if (avail_to_write > len - total_written) { avail_to_write = len - total_written; } - if (data_mq_->write((const MqDataType*)p_buf + total_written, - avail_to_write) == 0) { + if (data_mq_->write((const MqDataType*)p_buf + total_written, avail_to_write) == 0) { log::warn("len={} total_written={} failed", len, total_written); break; } total_written += avail_to_write; } else if (timeout_ms >= kDefaultDataWritePollIntervalMs) { - std::this_thread::sleep_for( - std::chrono::milliseconds(kDefaultDataWritePollIntervalMs)); + std::this_thread::sleep_for(std::chrono::milliseconds(kDefaultDataWritePollIntervalMs)); timeout_ms -= kDefaultDataWritePollIntervalMs; continue; } else { @@ -650,8 +604,7 @@ size_t BluetoothAudioSourceClientInterface::WriteAudioData(const uint8_t* p_buf, } } while (total_written < len); - if (timeout_ms < - (kDefaultDataWriteTimeoutMs - kDefaultDataWritePollIntervalMs) && + if (timeout_ms < (kDefaultDataWriteTimeoutMs - kDefaultDataWritePollIntervalMs) && timeout_ms >= kDefaultDataWritePollIntervalMs) { log::verbose("underflow {} -> {} read {} ms", len, total_written, kDefaultDataWriteTimeoutMs - timeout_ms); @@ -663,33 +616,29 @@ size_t BluetoothAudioSourceClientInterface::WriteAudioData(const uint8_t* p_buf, return total_written; } -void BluetoothAudioClientInterface::SetCodecPriority(CodecId codec_id, - int32_t priority) { +void BluetoothAudioClientInterface::SetCodecPriority(CodecId codec_id, int32_t priority) { log::assert_that(provider_ != nullptr, "assert failed: provider_ != nullptr"); auto aidl_retval = provider_->setCodecPriority(codec_id, priority); if (!aidl_retval.isOk()) { - log::fatal("BluetoothAudioHal::setCodecPriority failure: {}", - aidl_retval.getDescription()); + log::fatal("BluetoothAudioHal::setCodecPriority failure: {}", aidl_retval.getDescription()); } } std::vector BluetoothAudioClientInterface::GetLeAudioAseConfiguration( - std::optional>>& - remoteSinkAudioCapabilities, - std::optional>>& - remoteSourceAudioCapabilities, - std::vector& - requirements) { + std::optional< + std::vector>>& + remoteSinkAudioCapabilities, + std::optional< + std::vector>>& + remoteSourceAudioCapabilities, + std::vector& requirements) { log::assert_that(provider_ != nullptr, "assert failed: provider_ != nullptr"); - std::vector - configurations; - auto aidl_retval = provider_->getLeAudioAseConfiguration( - remoteSinkAudioCapabilities, remoteSourceAudioCapabilities, requirements, - &configurations); + std::vector configurations; + auto aidl_retval = provider_->getLeAudioAseConfiguration(remoteSinkAudioCapabilities, + remoteSourceAudioCapabilities, + requirements, &configurations); if (!aidl_retval.isOk()) { log::fatal("BluetoothAudioHal::getLeAudioAseConfiguration failure: {}", @@ -697,21 +646,19 @@ BluetoothAudioClientInterface::GetLeAudioAseConfiguration( } log::info( - "BluetoothAudioHal::getLeAudioAseConfiguration returned {} " - "configurations.", - configurations.size()); + "BluetoothAudioHal::getLeAudioAseConfiguration returned {} " + "configurations.", + configurations.size()); return configurations; } IBluetoothAudioProvider::LeAudioAseQosConfigurationPair BluetoothAudioClientInterface::getLeAudioAseQosConfiguration( - IBluetoothAudioProvider::LeAudioAseQosConfigurationRequirement& - qosRequirement) { + IBluetoothAudioProvider::LeAudioAseQosConfigurationRequirement& qosRequirement) { log::assert_that(provider_ != nullptr, "assert failed: provider_ != nullptr"); IBluetoothAudioProvider::LeAudioAseQosConfigurationPair qos_configuration; - auto aidl_retval = provider_->getLeAudioAseQosConfiguration( - qosRequirement, &qos_configuration); + auto aidl_retval = provider_->getLeAudioAseQosConfiguration(qosRequirement, &qos_configuration); if (!aidl_retval.isOk()) { log::fatal("BluetoothAudioHal::getLeAudioAseQosConfiguration failure: {}", @@ -721,12 +668,11 @@ BluetoothAudioClientInterface::getLeAudioAseQosConfiguration( } void BluetoothAudioClientInterface::onSinkAseMetadataChanged( - IBluetoothAudioProvider::AseState state, int32_t cigId, int32_t cisId, - std::optional>>& metadata) { + IBluetoothAudioProvider::AseState state, int32_t cigId, int32_t cisId, + std::optional>>& metadata) { log::assert_that(provider_ != nullptr, "assert failed: provider_ != nullptr"); - auto aidl_retval = - provider_->onSinkAseMetadataChanged(state, cigId, cisId, metadata); + auto aidl_retval = provider_->onSinkAseMetadataChanged(state, cigId, cisId, metadata); if (!aidl_retval.isOk()) { log::fatal("BluetoothAudioHal::onSinkAseMetadataChanged failure: {}", @@ -735,12 +681,11 @@ void BluetoothAudioClientInterface::onSinkAseMetadataChanged( } void BluetoothAudioClientInterface::onSourceAseMetadataChanged( - IBluetoothAudioProvider::AseState state, int32_t cigId, int32_t cisId, - std::optional>>& metadata) { + IBluetoothAudioProvider::AseState state, int32_t cigId, int32_t cisId, + std::optional>>& metadata) { log::assert_that(provider_ != nullptr, "assert failed: provider_ != nullptr"); - auto aidl_retval = - provider_->onSourceAseMetadataChanged(state, cigId, cisId, metadata); + auto aidl_retval = provider_->onSourceAseMetadataChanged(state, cigId, cisId, metadata); if (!aidl_retval.isOk()) { log::fatal("BluetoothAudioHal::onSinkAseMetadataChanged failure: {}", @@ -750,16 +695,15 @@ void BluetoothAudioClientInterface::onSourceAseMetadataChanged( IBluetoothAudioProvider::LeAudioBroadcastConfigurationSetting BluetoothAudioClientInterface::getLeAudioBroadcastConfiguration( - const std::optional>>& - remoteSinkAudioCapabilities, - const IBluetoothAudioProvider::LeAudioBroadcastConfigurationRequirement& - requirement) { + const std::optional< + std::vector>>& + remoteSinkAudioCapabilities, + const IBluetoothAudioProvider::LeAudioBroadcastConfigurationRequirement& requirement) { log::assert_that(provider_ != nullptr, "assert failed: provider_ != nullptr"); IBluetoothAudioProvider::LeAudioBroadcastConfigurationSetting setting; - auto aidl_retval = provider_->getLeAudioBroadcastConfiguration( - remoteSinkAudioCapabilities, requirement, &setting); + auto aidl_retval = provider_->getLeAudioBroadcastConfiguration(remoteSinkAudioCapabilities, + requirement, &setting); if (!aidl_retval.isOk()) { log::fatal("BluetoothAudioHal::onSinkAseMetadataChanged failure: {}", diff --git a/system/audio_hal_interface/aidl/client_interface_aidl.h b/system/audio_hal_interface/aidl/client_interface_aidl.h index 4b87cd75698..6ec50ccf4ec 100644 --- a/system/audio_hal_interface/aidl/client_interface_aidl.h +++ b/system/audio_hal_interface/aidl/client_interface_aidl.h @@ -30,8 +30,7 @@ #include "bta/le_audio/le_audio_types.h" #include "transport_instance.h" -#define BLUETOOTH_AUDIO_HAL_PROP_DISABLED \ - "persist.bluetooth.bluetooth_audio_hal.disabled" +#define BLUETOOTH_AUDIO_HAL_PROP_DISABLED "persist.bluetooth.bluetooth_audio_hal.disabled" namespace bluetooth { namespace audio { @@ -47,12 +46,10 @@ using ::aidl::android::hardware::bluetooth::audio::CodecId; using ::aidl::android::hardware::bluetooth::audio::CodecInfo; using ::aidl::android::hardware::bluetooth::audio::CodecParameters; using ::aidl::android::hardware::bluetooth::audio::CodecSpecificCapabilitiesLtv; -using ::aidl::android::hardware::bluetooth::audio:: - CodecSpecificConfigurationLtv; +using ::aidl::android::hardware::bluetooth::audio::CodecSpecificConfigurationLtv; using ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioPort; using ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider; -using ::aidl::android::hardware::bluetooth::audio:: - IBluetoothAudioProviderFactory; +using ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProviderFactory; using ::aidl::android::hardware::bluetooth::audio::LatencyMode; using ::aidl::android::hardware::bluetooth::audio::MetadataLtv; using ::aidl::android::hardware::bluetooth::audio::PcmConfiguration; @@ -72,7 +69,7 @@ using DataMQDesc = MQDescriptor; * IBluetoothTransportInstance ***/ class BluetoothAudioClientInterface { - public: +public: BluetoothAudioClientInterface(IBluetoothTransportInstance* instance); virtual ~BluetoothAudioClientInterface() = default; @@ -80,20 +77,18 @@ class BluetoothAudioClientInterface { std::vector GetAudioCapabilities() const; - static std::vector GetAudioCapabilities( - SessionType session_type); - static std::optional - GetProviderInfo(SessionType session_type, - std::shared_ptr - provider_factory = nullptr); + static std::vector GetAudioCapabilities(SessionType session_type); + static std::optional GetProviderInfo( + SessionType session_type, + std::shared_ptr provider_factory = nullptr); - std::optional ParseA2dpConfiguration( - const CodecId& codec_id, const std::vector& configuration, - CodecParameters* codec_parameters) const; + std::optional ParseA2dpConfiguration(const CodecId& codec_id, + const std::vector& configuration, + CodecParameters* codec_parameters) const; std::optional GetA2dpConfiguration( - std::vector const& remote_capabilities, - A2dpConfigurationHint const& hint) const; + std::vector const& remote_capabilities, + A2dpConfigurationHint const& hint) const; void StreamStarted(const BluetoothAudioCtrlAck& ack); @@ -116,43 +111,37 @@ class BluetoothAudioClientInterface { void SetCodecPriority(CodecId codec_id, int32_t priority); - std::vector - GetLeAudioAseConfiguration( - std::optional>>& - remoteSinkAudioCapabilities, - std::optional>>& - remoteSourceAudioCapabilities, - std::vector& - requirements); - - IBluetoothAudioProvider::LeAudioAseQosConfigurationPair - getLeAudioAseQosConfiguration( - IBluetoothAudioProvider::LeAudioAseQosConfigurationRequirement& - qosRequirement); - - void onSinkAseMetadataChanged( - IBluetoothAudioProvider::AseState state, int32_t cigId, int32_t cisId, - std::optional>>& metadata); - - void onSourceAseMetadataChanged( - IBluetoothAudioProvider::AseState state, int32_t cigId, int32_t cisId, - std::optional>>& metadata); - - IBluetoothAudioProvider::LeAudioBroadcastConfigurationSetting - getLeAudioBroadcastConfiguration( - const std::optional>>& - remoteSinkAudioCapabilities, - const IBluetoothAudioProvider::LeAudioBroadcastConfigurationRequirement& - requirement); + std::vector GetLeAudioAseConfiguration( + std::optional< + std::vector>>& + remoteSinkAudioCapabilities, + std::optional< + std::vector>>& + remoteSourceAudioCapabilities, + std::vector& requirements); + + IBluetoothAudioProvider::LeAudioAseQosConfigurationPair getLeAudioAseQosConfiguration( + IBluetoothAudioProvider::LeAudioAseQosConfigurationRequirement& qosRequirement); + + void onSinkAseMetadataChanged(IBluetoothAudioProvider::AseState state, int32_t cigId, + int32_t cisId, + std::optional>>& metadata); + + void onSourceAseMetadataChanged(IBluetoothAudioProvider::AseState state, int32_t cigId, + int32_t cisId, + std::optional>>& metadata); + + IBluetoothAudioProvider::LeAudioBroadcastConfigurationSetting getLeAudioBroadcastConfiguration( + const std::optional< + std::vector>>& + remoteSinkAudioCapabilities, + const IBluetoothAudioProvider::LeAudioBroadcastConfigurationRequirement& requirement); static constexpr PcmConfiguration kInvalidPcmConfiguration = {}; static bool is_aidl_available(); - protected: +protected: mutable std::mutex internal_mutex_; /*** * Helper function to connect to an IBluetoothAudioProvider @@ -175,9 +164,9 @@ class BluetoothAudioClientInterface { // static constexpr const char* kDefaultAudioProviderFactoryInterface = // "android.hardware.bluetooth.audio.IBluetoothAudioProviderFactory/default"; static inline const std::string kDefaultAudioProviderFactoryInterface = - std::string() + IBluetoothAudioProviderFactory::descriptor + "/default"; + std::string() + IBluetoothAudioProviderFactory::descriptor + "/default"; - private: +private: IBluetoothTransportInstance* transport_; std::vector capabilities_; std::vector latency_modes_; @@ -189,7 +178,7 @@ class BluetoothAudioClientInterface { * IBluetoothTransportInstance ***/ class BluetoothAudioSinkClientInterface : public BluetoothAudioClientInterface { - public: +public: /*** * Constructs an BluetoothAudioSinkClientInterface to communicate to * BluetoothAudio HAL. |sink| is the implementation for the transport. @@ -197,43 +186,37 @@ class BluetoothAudioSinkClientInterface : public BluetoothAudioClientInterface { BluetoothAudioSinkClientInterface(IBluetoothSinkTransportInstance* sink); virtual ~BluetoothAudioSinkClientInterface(); - IBluetoothSinkTransportInstance* GetTransportInstance() const { - return sink_; - } + IBluetoothSinkTransportInstance* GetTransportInstance() const { return sink_; } /*** * Read data from audio HAL through fmq ***/ size_t ReadAudioData(uint8_t* p_buf, uint32_t len); - private: +private: IBluetoothSinkTransportInstance* sink_; static constexpr int kDefaultDataReadTimeoutMs = 10; static constexpr int kDefaultDataReadPollIntervalMs = 1; }; -class BluetoothAudioSourceClientInterface - : public BluetoothAudioClientInterface { - public: +class BluetoothAudioSourceClientInterface : public BluetoothAudioClientInterface { +public: /*** * Constructs an BluetoothAudioSourceClientInterface to communicate to * BluetoothAudio HAL. |source| is the implementation for the transport. ***/ - BluetoothAudioSourceClientInterface( - IBluetoothSourceTransportInstance* source); + BluetoothAudioSourceClientInterface(IBluetoothSourceTransportInstance* source); virtual ~BluetoothAudioSourceClientInterface(); - IBluetoothSourceTransportInstance* GetTransportInstance() const { - return source_; - } + IBluetoothSourceTransportInstance* GetTransportInstance() const { return source_; } /*** * Write data to audio HAL through fmq ***/ size_t WriteAudioData(const uint8_t* p_buf, uint32_t len); - private: +private: IBluetoothSourceTransportInstance* source_; static constexpr int kDefaultDataWriteTimeoutMs = 10; diff --git a/system/audio_hal_interface/aidl/codec_status_aidl.cc b/system/audio_hal_interface/aidl/codec_status_aidl.cc index 506ab0df2f1..9f5fc95dab4 100644 --- a/system/audio_hal_interface/aidl/codec_status_aidl.cc +++ b/system/audio_hal_interface/aidl/codec_status_aidl.cc @@ -70,8 +70,7 @@ struct identity { }; template -bool ContainedInVector(const std::vector& vector, - const typename identity::type& target) { +bool ContainedInVector(const std::vector& vector, const typename identity::type& target) { return std::find(vector.begin(), vector.end(), target) != vector.end(); } @@ -81,19 +80,15 @@ bool sbc_offloading_capability_match(const SbcCapabilities& sbc_capability, !ContainedInVector(sbc_capability.allocMethod, sbc_config.allocMethod) || !ContainedInVector(sbc_capability.blockLength, sbc_config.blockLength) || !ContainedInVector(sbc_capability.numSubbands, sbc_config.numSubbands) || - !ContainedInVector(sbc_capability.bitsPerSample, - sbc_config.bitsPerSample) || - !ContainedInVector(sbc_capability.sampleRateHz, - sbc_config.sampleRateHz) || + !ContainedInVector(sbc_capability.bitsPerSample, sbc_config.bitsPerSample) || + !ContainedInVector(sbc_capability.sampleRateHz, sbc_config.sampleRateHz) || (sbc_config.minBitpool < sbc_capability.minBitpool || sbc_config.maxBitpool < sbc_config.minBitpool || sbc_capability.maxBitpool < sbc_config.maxBitpool)) { - log::warn("software codec={} capability={}", sbc_config.toString(), - sbc_capability.toString()); + log::warn("software codec={} capability={}", sbc_config.toString(), sbc_capability.toString()); return false; } - log::info("offload codec={} capability={}", sbc_config.toString(), - sbc_capability.toString()); + log::info("offload codec={} capability={}", sbc_config.toString(), sbc_capability.toString()); return true; } @@ -101,29 +96,21 @@ bool aac_offloading_capability_match(const AacCapabilities& aac_capability, const AacConfiguration& aac_config) { if (!ContainedInVector(aac_capability.channelMode, aac_config.channelMode) || !ContainedInVector(aac_capability.objectType, aac_config.objectType) || - !ContainedInVector(aac_capability.bitsPerSample, - aac_config.bitsPerSample) || - !ContainedInVector(aac_capability.sampleRateHz, - aac_config.sampleRateHz) || - (!aac_capability.variableBitRateSupported && - aac_config.variableBitRateEnabled)) { - log::warn("software codec={} capability={}", aac_config.toString(), - aac_capability.toString()); + !ContainedInVector(aac_capability.bitsPerSample, aac_config.bitsPerSample) || + !ContainedInVector(aac_capability.sampleRateHz, aac_config.sampleRateHz) || + (!aac_capability.variableBitRateSupported && aac_config.variableBitRateEnabled)) { + log::warn("software codec={} capability={}", aac_config.toString(), aac_capability.toString()); return false; } - log::info("offloading codec={} capability={}", aac_config.toString(), - aac_capability.toString()); + log::info("offloading codec={} capability={}", aac_config.toString(), aac_capability.toString()); return true; } bool aptx_offloading_capability_match(const AptxCapabilities& aptx_capability, const AptxConfiguration& aptx_config) { - if (!ContainedInVector(aptx_capability.channelMode, - aptx_config.channelMode) || - !ContainedInVector(aptx_capability.bitsPerSample, - aptx_config.bitsPerSample) || - !ContainedInVector(aptx_capability.sampleRateHz, - aptx_config.sampleRateHz)) { + if (!ContainedInVector(aptx_capability.channelMode, aptx_config.channelMode) || + !ContainedInVector(aptx_capability.bitsPerSample, aptx_config.bitsPerSample) || + !ContainedInVector(aptx_capability.sampleRateHz, aptx_config.sampleRateHz)) { log::warn("software codec={} capability={}", aptx_config.toString(), aptx_capability.toString()); return false; @@ -135,12 +122,9 @@ bool aptx_offloading_capability_match(const AptxCapabilities& aptx_capability, bool ldac_offloading_capability_match(const LdacCapabilities& ldac_capability, const LdacConfiguration& ldac_config) { - if (!ContainedInVector(ldac_capability.channelMode, - ldac_config.channelMode) || - !ContainedInVector(ldac_capability.bitsPerSample, - ldac_config.bitsPerSample) || - !ContainedInVector(ldac_capability.sampleRateHz, - ldac_config.sampleRateHz)) { + if (!ContainedInVector(ldac_capability.channelMode, ldac_config.channelMode) || + !ContainedInVector(ldac_capability.bitsPerSample, ldac_config.bitsPerSample) || + !ContainedInVector(ldac_capability.sampleRateHz, ldac_config.sampleRateHz)) { log::warn("software codec={} capability={}", ldac_config.toString(), ldac_capability.toString()); return false; @@ -150,15 +134,11 @@ bool ldac_offloading_capability_match(const LdacCapabilities& ldac_capability, return true; } -bool opus_offloading_capability_match( - const std::optional& opus_capability, - const std::optional& opus_config) { - if (!ContainedInVector(opus_capability->channelMode, - opus_config->channelMode) || - !ContainedInVector(opus_capability->frameDurationUs, - opus_config->frameDurationUs) || - !ContainedInVector(opus_capability->samplingFrequencyHz, - opus_config->samplingFrequencyHz)) { +bool opus_offloading_capability_match(const std::optional& opus_capability, + const std::optional& opus_config) { + if (!ContainedInVector(opus_capability->channelMode, opus_config->channelMode) || + !ContainedInVector(opus_capability->frameDurationUs, opus_config->frameDurationUs) || + !ContainedInVector(opus_capability->samplingFrequencyHz, opus_config->samplingFrequencyHz)) { log::warn("software codec={} capability={}", opus_config->toString(), opus_capability->toString()); return false; @@ -172,8 +152,7 @@ bool opus_offloading_capability_match( const CodecConfiguration kInvalidCodecConfiguration = {}; -int32_t A2dpCodecToHalSampleRate( - const btav_a2dp_codec_config_t& a2dp_codec_config) { +int32_t A2dpCodecToHalSampleRate(const btav_a2dp_codec_config_t& a2dp_codec_config) { switch (a2dp_codec_config.sample_rate) { case BTAV_A2DP_CODEC_SAMPLE_RATE_44100: return 44100; @@ -196,8 +175,7 @@ int32_t A2dpCodecToHalSampleRate( } } -int8_t A2dpCodecToHalBitsPerSample( - const btav_a2dp_codec_config_t& a2dp_codec_config) { +int8_t A2dpCodecToHalBitsPerSample(const btav_a2dp_codec_config_t& a2dp_codec_config) { switch (a2dp_codec_config.bits_per_sample) { case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16: return 16; @@ -210,8 +188,7 @@ int8_t A2dpCodecToHalBitsPerSample( } } -ChannelMode A2dpCodecToHalChannelMode( - const btav_a2dp_codec_config_t& a2dp_codec_config) { +ChannelMode A2dpCodecToHalChannelMode(const btav_a2dp_codec_config_t& a2dp_codec_config) { switch (a2dp_codec_config.channel_mode) { case BTAV_A2DP_CODEC_CHANNEL_MODE_MONO: return ChannelMode::MONO; @@ -222,8 +199,7 @@ ChannelMode A2dpCodecToHalChannelMode( } } -bool A2dpSbcToHalConfig(CodecConfiguration* codec_config, - A2dpCodecConfig* a2dp_config) { +bool A2dpSbcToHalConfig(CodecConfiguration* codec_config, A2dpCodecConfig* a2dp_config) { btav_a2dp_codec_config_t current_codec = a2dp_config->getCodecConfig(); if (current_codec.codec_type != BTAV_A2DP_CODEC_INDEX_SOURCE_SBC && current_codec.codec_type != BTAV_A2DP_CODEC_INDEX_SINK_SBC) { @@ -306,13 +282,11 @@ bool A2dpSbcToHalConfig(CodecConfiguration* codec_config, log::error("Unknown SBC bits_per_sample={}", current_codec.bits_per_sample); return false; } - codec_config->config.set( - sbc_config); + codec_config->config.set(sbc_config); return true; } -bool A2dpAacToHalConfig(CodecConfiguration* codec_config, - A2dpCodecConfig* a2dp_config) { +bool A2dpAacToHalConfig(CodecConfiguration* codec_config, A2dpCodecConfig* a2dp_config) { btav_a2dp_codec_config_t current_codec = a2dp_config->getCodecConfig(); if (current_codec.codec_type != BTAV_A2DP_CODEC_INDEX_SOURCE_AAC && current_codec.codec_type != BTAV_A2DP_CODEC_INDEX_SINK_AAC) { @@ -350,8 +324,7 @@ bool A2dpAacToHalConfig(CodecConfiguration* codec_config, log::error("Unknown AAC channel_mode={}", current_codec.channel_mode); return false; } - uint8_t vbr_enabled = - a2dp_offload.codec_info[1] & A2DP_AAC_VARIABLE_BIT_RATE_MASK; + uint8_t vbr_enabled = a2dp_offload.codec_info[1] & A2DP_AAC_VARIABLE_BIT_RATE_MASK; switch (vbr_enabled) { case A2DP_AAC_VARIABLE_BIT_RATE_ENABLED: aac_config.variableBitRateEnabled = true; @@ -368,13 +341,11 @@ bool A2dpAacToHalConfig(CodecConfiguration* codec_config, log::error("Unknown AAC bits_per_sample={}", current_codec.bits_per_sample); return false; } - codec_config->config.set( - aac_config); + codec_config->config.set(aac_config); return true; } -bool A2dpAptxToHalConfig(CodecConfiguration* codec_config, - A2dpCodecConfig* a2dp_config) { +bool A2dpAptxToHalConfig(CodecConfiguration* codec_config, A2dpCodecConfig* a2dp_config) { btav_a2dp_codec_config_t current_codec = a2dp_config->getCodecConfig(); if (current_codec.codec_type != BTAV_A2DP_CODEC_INDEX_SOURCE_APTX && current_codec.codec_type != BTAV_A2DP_CODEC_INDEX_SOURCE_APTX_HD) { @@ -400,17 +371,14 @@ bool A2dpAptxToHalConfig(CodecConfiguration* codec_config, } aptx_config.bitsPerSample = A2dpCodecToHalBitsPerSample(current_codec); if (aptx_config.bitsPerSample <= 0) { - log::error("Unknown aptX bits_per_sample={}", - current_codec.bits_per_sample); + log::error("Unknown aptX bits_per_sample={}", current_codec.bits_per_sample); return false; } - codec_config->config.set( - aptx_config); + codec_config->config.set(aptx_config); return true; } -bool A2dpLdacToHalConfig(CodecConfiguration* codec_config, - A2dpCodecConfig* a2dp_config) { +bool A2dpLdacToHalConfig(CodecConfiguration* codec_config, A2dpCodecConfig* a2dp_config) { btav_a2dp_codec_config_t current_codec = a2dp_config->getCodecConfig(); if (current_codec.codec_type != BTAV_A2DP_CODEC_INDEX_SOURCE_LDAC) { return false; @@ -458,17 +426,14 @@ bool A2dpLdacToHalConfig(CodecConfiguration* codec_config, } ldac_config.bitsPerSample = A2dpCodecToHalBitsPerSample(current_codec); if (ldac_config.bitsPerSample <= 0) { - log::error("Unknown LDAC bits_per_sample={}", - current_codec.bits_per_sample); + log::error("Unknown LDAC bits_per_sample={}", current_codec.bits_per_sample); return false; } - codec_config->config.set( - ldac_config); + codec_config->config.set(ldac_config); return true; } -bool A2dpOpusToHalConfig(CodecConfiguration* codec_config, - A2dpCodecConfig* a2dp_config) { +bool A2dpOpusToHalConfig(CodecConfiguration* codec_config, A2dpCodecConfig* a2dp_config) { btav_a2dp_codec_config_t current_codec = a2dp_config->getCodecConfig(); if (current_codec.codec_type != BTAV_A2DP_CODEC_INDEX_SOURCE_OPUS) { codec_config = {}; @@ -481,8 +446,7 @@ bool A2dpOpusToHalConfig(CodecConfiguration* codec_config, opus_config.pcmBitDepth = A2dpCodecToHalBitsPerSample(current_codec); if (opus_config.pcmBitDepth <= 0) { - log::error("Unknown Opus bits_per_sample={}", - current_codec.bits_per_sample); + log::error("Unknown Opus bits_per_sample={}", current_codec.bits_per_sample); return false; } opus_config.samplingFrequencyHz = A2dpCodecToHalSampleRate(current_codec); @@ -504,15 +468,13 @@ bool A2dpOpusToHalConfig(CodecConfiguration* codec_config, opus_config.octetsPerFrame = 320; } - codec_config->config.set( - opus_config); + codec_config->config.set(opus_config); return true; } bool UpdateOffloadingCapabilities( - const std::vector& framework_preference) { - audio_hal_capabilities = - BluetoothAudioSinkClientInterface::GetAudioCapabilities( + const std::vector& framework_preference) { + audio_hal_capabilities = BluetoothAudioSinkClientInterface::GetAudioCapabilities( SessionType::A2DP_HARDWARE_OFFLOAD_ENCODING_DATAPATH); std::unordered_set codec_type_set; for (auto preference : framework_preference) { @@ -533,8 +495,7 @@ bool UpdateOffloadingCapabilities( codec_type_set.insert(CodecType::LDAC); break; case BTAV_A2DP_CODEC_INDEX_SOURCE_LC3: - log::warn("Ignore source codec_type={}, not implemented", - preference.codec_type); + log::warn("Ignore source codec_type={}, not implemented", preference.codec_type); break; case BTAV_A2DP_CODEC_INDEX_SOURCE_OPUS: codec_type_set.insert(CodecType::OPUS); @@ -557,8 +518,7 @@ bool UpdateOffloadingCapabilities( } offloading_preference.clear(); for (auto capability : audio_hal_capabilities) { - auto codec_type = - capability.get().codecType; + auto codec_type = capability.get().codecType; if (codec_type_set.find(codec_type) != codec_type_set.end()) { log::info("enabled offloading capability={}", capability.toString()); offloading_preference.push_back(capability); @@ -573,69 +533,53 @@ bool UpdateOffloadingCapabilities( /*** * Check whether this codec is supported by the audio HAL and is allowed to - * use by prefernece of framework / Bluetooth SoC / runtime property. + * use by preference of framework / Bluetooth SoC / runtime property. ***/ bool IsCodecOffloadingEnabled(const CodecConfiguration& codec_config) { for (auto preference : offloading_preference) { - if (codec_config.codecType != - preference.get().codecType) { + if (codec_config.codecType != preference.get().codecType) { continue; } - auto codec_capability = - preference.get(); + auto codec_capability = preference.get(); switch (codec_capability.codecType) { case CodecType::SBC: { - auto sbc_capability = - codec_capability.capabilities - .get(); - auto sbc_config = - codec_config.config - .get(); + auto sbc_capability = codec_capability.capabilities + .get(); + auto sbc_config = codec_config.config.get(); return sbc_offloading_capability_match(sbc_capability, sbc_config); } case CodecType::AAC: { - auto aac_capability = - codec_capability.capabilities - .get(); - auto aac_config = - codec_config.config - .get(); + auto aac_capability = codec_capability.capabilities + .get(); + auto aac_config = codec_config.config.get(); return aac_offloading_capability_match(aac_capability, aac_config); } case CodecType::APTX: [[fallthrough]]; case CodecType::APTX_HD: { - auto aptx_capability = - codec_capability.capabilities - .get(); - auto aptx_config = - codec_config.config - .get(); + auto aptx_capability = codec_capability.capabilities + .get(); + auto aptx_config = codec_config.config.get(); return aptx_offloading_capability_match(aptx_capability, aptx_config); } case CodecType::LDAC: { - auto ldac_capability = - codec_capability.capabilities - .get(); - auto ldac_config = - codec_config.config - .get(); + auto ldac_capability = codec_capability.capabilities + .get(); + auto ldac_config = codec_config.config.get(); return ldac_offloading_capability_match(ldac_capability, ldac_config); } case CodecType::OPUS: { std::optional opus_capability = - codec_capability.capabilities - .get(); + codec_capability.capabilities + .get(); std::optional opus_config = - codec_config.config - .get(); + codec_config.config.get(); return opus_offloading_capability_match(opus_capability, opus_config); } case CodecType::UNKNOWN: [[fallthrough]]; default: - log::error("Unknown codecType={}", - toString(codec_capability.codecType)); + log::error("Unknown codecType={}", toString(codec_capability.codecType)); return false; } } diff --git a/system/audio_hal_interface/aidl/codec_status_aidl.h b/system/audio_hal_interface/aidl/codec_status_aidl.h index 3caac07aac1..b6eb8fb04f3 100644 --- a/system/audio_hal_interface/aidl/codec_status_aidl.h +++ b/system/audio_hal_interface/aidl/codec_status_aidl.h @@ -31,30 +31,22 @@ using ::aidl::android::hardware::bluetooth::audio::CodecConfiguration; extern const CodecConfiguration kInvalidCodecConfiguration; -int32_t A2dpCodecToHalSampleRate( - const btav_a2dp_codec_config_t& a2dp_codec_config); -int8_t A2dpCodecToHalBitsPerSample( - const btav_a2dp_codec_config_t& a2dp_codec_config); -ChannelMode A2dpCodecToHalChannelMode( - const btav_a2dp_codec_config_t& a2dp_codec_config); +int32_t A2dpCodecToHalSampleRate(const btav_a2dp_codec_config_t& a2dp_codec_config); +int8_t A2dpCodecToHalBitsPerSample(const btav_a2dp_codec_config_t& a2dp_codec_config); +ChannelMode A2dpCodecToHalChannelMode(const btav_a2dp_codec_config_t& a2dp_codec_config); -bool A2dpSbcToHalConfig(CodecConfiguration* codec_config, - A2dpCodecConfig* a2dp_config); -bool A2dpAacToHalConfig(CodecConfiguration* codec_config, - A2dpCodecConfig* a2dp_config); -bool A2dpAptxToHalConfig(CodecConfiguration* codec_config, - A2dpCodecConfig* a2dp_config); -bool A2dpLdacToHalConfig(CodecConfiguration* codec_config, - A2dpCodecConfig* a2dp_config); -bool A2dpOpusToHalConfig(CodecConfiguration* codec_config, - A2dpCodecConfig* a2dp_config); +bool A2dpSbcToHalConfig(CodecConfiguration* codec_config, A2dpCodecConfig* a2dp_config); +bool A2dpAacToHalConfig(CodecConfiguration* codec_config, A2dpCodecConfig* a2dp_config); +bool A2dpAptxToHalConfig(CodecConfiguration* codec_config, A2dpCodecConfig* a2dp_config); +bool A2dpLdacToHalConfig(CodecConfiguration* codec_config, A2dpCodecConfig* a2dp_config); +bool A2dpOpusToHalConfig(CodecConfiguration* codec_config, A2dpCodecConfig* a2dp_config); bool UpdateOffloadingCapabilities( - const std::vector& framework_preference); + const std::vector& framework_preference); /*** * Check whether this codec is supported by the audio HAL and is allowed to use - * by prefernece of framework / Bluetooth SoC / runtime property. + * by preference of framework / Bluetooth SoC / runtime property. ***/ bool IsCodecOffloadingEnabled(const CodecConfiguration& codec_config); diff --git a/system/audio_hal_interface/aidl/hearing_aid_software_encoding_aidl.cc b/system/audio_hal_interface/aidl/hearing_aid_software_encoding_aidl.cc index 82127d90542..5adfb81bf62 100644 --- a/system/audio_hal_interface/aidl/hearing_aid_software_encoding_aidl.cc +++ b/system/audio_hal_interface/aidl/hearing_aid_software_encoding_aidl.cc @@ -29,8 +29,7 @@ namespace fmt { template <> struct formatter : enum_formatter {}; template <> -struct formatter : enum_formatter { -}; +struct formatter : enum_formatter {}; } // namespace fmt namespace { @@ -46,17 +45,15 @@ using ::bluetooth::audio::aidl::hearing_aid::StreamCallbacks; using namespace bluetooth; // Transport implementation for Hearing Aids -class HearingAidTransport - : public bluetooth::audio::aidl::IBluetoothSinkTransportInstance { - public: +class HearingAidTransport : public bluetooth::audio::aidl::IBluetoothSinkTransportInstance { +public: HearingAidTransport(StreamCallbacks stream_cb) - : IBluetoothSinkTransportInstance( - SessionType::HEARING_AID_SOFTWARE_ENCODING_DATAPATH, - (AudioConfiguration){}), + : IBluetoothSinkTransportInstance(SessionType::HEARING_AID_SOFTWARE_ENCODING_DATAPATH, + (AudioConfiguration){}), stream_cb_(std::move(stream_cb)), remote_delay_report_ms_(0), total_bytes_read_(0), - data_position_({}){}; + data_position_({}) {} BluetoothAudioCtrlAck StartRequest(bool is_low_latency) override { log::info(""); @@ -88,12 +85,10 @@ class HearingAidTransport void SetLatencyMode(LatencyMode latency_mode) override {} - bool GetPresentationPosition(uint64_t* remote_delay_report_ns, - uint64_t* total_bytes_read, + bool GetPresentationPosition(uint64_t* remote_delay_report_ns, uint64_t* total_bytes_read, timespec* data_position) override { - log::verbose("data={} byte(s), timestamp={}.{}s, delay report={} msec.", - total_bytes_read_, data_position_.tv_sec, - data_position_.tv_nsec, remote_delay_report_ms_); + log::verbose("data={} byte(s), timestamp={}.{}s, delay report={} msec.", total_bytes_read_, + data_position_.tv_sec, data_position_.tv_nsec, remote_delay_report_ms_); if (remote_delay_report_ns != nullptr) { *remote_delay_report_ns = remote_delay_report_ms_ * 1000000u; } @@ -107,8 +102,7 @@ class HearingAidTransport return true; } - void SourceMetadataChanged( - const source_metadata_v7_t& source_metadata) override { + void SourceMetadataChanged(const source_metadata_v7_t& source_metadata) override { auto track_count = source_metadata.track_count; auto tracks = source_metadata.tracks; log::info("{} track(s) received", track_count); @@ -141,7 +135,7 @@ class HearingAidTransport remote_delay_report_ms_ = delay_report_ms; } - private: +private: StreamCallbacks stream_cb_; uint16_t remote_delay_report_ms_; uint64_t total_bytes_read_; @@ -149,7 +143,9 @@ class HearingAidTransport }; bool HearingAidGetSelectedHalPcmConfig(PcmConfiguration* hal_pcm_config) { - if (hal_pcm_config == nullptr) return false; + if (hal_pcm_config == nullptr) { + return false; + } // TODO: we only support one config for now! hal_pcm_config->sampleRateHz = 16000; hal_pcm_config->bitsPerSample = 16; @@ -160,8 +156,8 @@ bool HearingAidGetSelectedHalPcmConfig(PcmConfiguration* hal_pcm_config) { // Sink instance of Hearing Aids to provide call-in APIs for Bluetooth Audio Hal HearingAidTransport* hearing_aid_sink = nullptr; // Common interface to call-out into Bluetooth Audio Hal -bluetooth::audio::aidl::BluetoothAudioSinkClientInterface* - hearing_aid_hal_clientinterface = nullptr; +bluetooth::audio::aidl::BluetoothAudioSinkClientInterface* hearing_aid_hal_clientinterface = + nullptr; bool btaudio_hearing_aid_disabled = false; bool is_configured = false; @@ -171,8 +167,7 @@ uint16_t remote_delay_ms = 0; bool is_hal_force_disabled() { if (!is_configured) { - btaudio_hearing_aid_disabled = - osi_property_get_bool(BLUETOOTH_AUDIO_HAL_PROP_DISABLED, false); + btaudio_hearing_aid_disabled = osi_property_get_bool(BLUETOOTH_AUDIO_HAL_PROP_DISABLED, false); is_configured = true; } return btaudio_hearing_aid_disabled; @@ -187,8 +182,7 @@ namespace hearing_aid { bool is_hal_enabled() { return hearing_aid_hal_clientinterface != nullptr; } -bool init(StreamCallbacks stream_cb, - bluetooth::common::MessageLoopThread* /*message_loop*/) { +bool init(StreamCallbacks stream_cb, bluetooth::common::MessageLoopThread* /*message_loop*/) { log::info(""); if (is_hal_force_disabled()) { @@ -203,8 +197,7 @@ bool init(StreamCallbacks stream_cb, hearing_aid_sink = new HearingAidTransport(std::move(stream_cb)); hearing_aid_hal_clientinterface = - new bluetooth::audio::aidl::BluetoothAudioSinkClientInterface( - hearing_aid_sink); + new bluetooth::audio::aidl::BluetoothAudioSinkClientInterface(hearing_aid_sink); if (!hearing_aid_hal_clientinterface->IsValid()) { log::warn("BluetoothAudio HAL for Hearing Aid is invalid?!"); delete hearing_aid_hal_clientinterface; @@ -225,7 +218,9 @@ bool init(StreamCallbacks stream_cb, void cleanup() { log::info(""); - if (!is_hal_enabled()) return; + if (!is_hal_enabled()) { + return; + } end_session(); delete hearing_aid_hal_clientinterface; hearing_aid_hal_clientinterface = nullptr; @@ -236,7 +231,9 @@ void cleanup() { void start_session() { log::info(""); - if (!is_hal_enabled()) return; + if (!is_hal_enabled()) { + return; + } AudioConfiguration audio_config; PcmConfiguration pcm_config{}; if (!HearingAidGetSelectedHalPcmConfig(&pcm_config)) { @@ -253,12 +250,16 @@ void start_session() { void end_session() { log::info(""); - if (!is_hal_enabled()) return; + if (!is_hal_enabled()) { + return; + } hearing_aid_hal_clientinterface->EndSession(); } size_t read(uint8_t* p_buf, uint32_t len) { - if (!is_hal_enabled()) return 0; + if (!is_hal_enabled()) { + return 0; + } return hearing_aid_hal_clientinterface->ReadAudioData(p_buf, len); } diff --git a/system/audio_hal_interface/aidl/hearing_aid_software_encoding_aidl.h b/system/audio_hal_interface/aidl/hearing_aid_software_encoding_aidl.h index 977bd7ca14e..1e2c7080d22 100644 --- a/system/audio_hal_interface/aidl/hearing_aid_software_encoding_aidl.h +++ b/system/audio_hal_interface/aidl/hearing_aid_software_encoding_aidl.h @@ -31,8 +31,7 @@ using ::bluetooth::audio::hearing_aid::StreamCallbacks; bool is_hal_enabled(); // Initialize BluetoothAudio HAL: openProvider -bool init(StreamCallbacks stream_cb, - bluetooth::common::MessageLoopThread* message_loop); +bool init(StreamCallbacks stream_cb, bluetooth::common::MessageLoopThread* message_loop); // Clean up BluetoothAudio HAL void cleanup(); diff --git a/system/audio_hal_interface/aidl/hfp_client_interface_aidl.cc b/system/audio_hal_interface/aidl/hfp_client_interface_aidl.cc index 2781da69121..58c7f7002a5 100644 --- a/system/audio_hal_interface/aidl/hfp_client_interface_aidl.cc +++ b/system/audio_hal_interface/aidl/hfp_client_interface_aidl.cc @@ -37,12 +37,12 @@ namespace aidl { namespace hfp { std::map status_to_ack_map = { - {BT_STATUS_SUCCESS, BluetoothAudioCtrlAck::SUCCESS_FINISHED}, - {BT_STATUS_DONE, BluetoothAudioCtrlAck::SUCCESS_FINISHED}, - {BT_STATUS_FAIL, BluetoothAudioCtrlAck::FAILURE}, - {BT_STATUS_NOT_READY, BluetoothAudioCtrlAck::FAILURE_BUSY}, - {BT_STATUS_BUSY, BluetoothAudioCtrlAck::FAILURE_BUSY}, - {BT_STATUS_UNSUPPORTED, BluetoothAudioCtrlAck::FAILURE_UNSUPPORTED}, + {BT_STATUS_SUCCESS, BluetoothAudioCtrlAck::SUCCESS_FINISHED}, + {BT_STATUS_DONE, BluetoothAudioCtrlAck::SUCCESS_FINISHED}, + {BT_STATUS_FAIL, BluetoothAudioCtrlAck::FAILURE}, + {BT_STATUS_NOT_READY, BluetoothAudioCtrlAck::FAILURE_BUSY}, + {BT_STATUS_BUSY, BluetoothAudioCtrlAck::FAILURE_BUSY}, + {BT_STATUS_UNSUPPORTED, BluetoothAudioCtrlAck::FAILURE_UNSUPPORTED}, }; tBTA_AG_SCB* get_hfp_active_device_callback() { @@ -64,10 +64,9 @@ tBTA_AG_SCB* get_hfp_active_device_callback() { return cb; } -std::unordered_map -HfpTransport::GetHfpScoConfig(SessionType sessionType) { - auto providerInfo = - ::bluetooth::audio::aidl::ProviderInfo::GetProviderInfo(sessionType); +std::unordered_map HfpTransport::GetHfpScoConfig( + SessionType sessionType) { + auto providerInfo = ::bluetooth::audio::aidl::ProviderInfo::GetProviderInfo(sessionType); return providerInfo->GetHfpScoConfig(); } @@ -83,7 +82,9 @@ BluetoothAudioCtrlAck HfpTransport::StartRequest() { } auto cb = get_hfp_active_device_callback(); - if (cb == nullptr) return BluetoothAudioCtrlAck::FAILURE; + if (cb == nullptr) { + return BluetoothAudioCtrlAck::FAILURE; + } if (bta_ag_sco_is_open(cb)) { // Already started, ACK back immediately. @@ -94,8 +95,7 @@ BluetoothAudioCtrlAck HfpTransport::StartRequest() { hfp_pending_cmd_ = HFP_CTRL_CMD_START; // as ConnectAudio only queues the command into main thread, keep PENDING // status - auto status = - bluetooth::headset::GetInterface()->ConnectAudio(&cb->peer_addr, 0); + auto status = bluetooth::headset::GetInterface()->ConnectAudio(&cb->peer_addr, 0); log::info("ConnectAudio status = {} - {}", status, bt_status_text(status)); auto ctrl_ack = status_to_ack_map.find(status); if (ctrl_ack == status_to_ack_map.end()) { @@ -150,23 +150,20 @@ BluetoothAudioCtrlAck HfpTransport::SuspendRequest() { } auto status = instance->DisconnectAudio(&addr); log::info("DisconnectAudio status = {} - {}", status, bt_status_text(status)); - return status == BT_STATUS_SUCCESS ? - BluetoothAudioCtrlAck::SUCCESS_FINISHED : - BluetoothAudioCtrlAck::FAILURE; + return status == BT_STATUS_SUCCESS ? BluetoothAudioCtrlAck::SUCCESS_FINISHED + : BluetoothAudioCtrlAck::FAILURE; } void HfpTransport::SetLatencyMode(LatencyMode latency_mode) {} -void HfpTransport::SourceMetadataChanged( - const source_metadata_v7_t& source_metadata) {} +void HfpTransport::SourceMetadataChanged(const source_metadata_v7_t& source_metadata) {} void HfpTransport::SinkMetadataChanged(const sink_metadata_v7_t&) {} void HfpTransport::ResetPresentationPosition() {} bool HfpTransport::GetPresentationPosition(uint64_t* remote_delay_report_ns, - uint64_t* total_bytes_read, - timespec* data_position) { + uint64_t* total_bytes_read, timespec* data_position) { return false; } @@ -174,7 +171,7 @@ bool HfpTransport::GetPresentationPosition(uint64_t* remote_delay_report_ns, HfpDecodingTransport::HfpDecodingTransport(SessionType session_type) : IBluetoothSinkTransportInstance(session_type, (AudioConfiguration){}) { transport_ = new HfpTransport(); -}; +} HfpDecodingTransport::~HfpDecodingTransport() { delete transport_; } @@ -190,34 +187,28 @@ void HfpDecodingTransport::SetLatencyMode(LatencyMode latency_mode) { transport_->SetLatencyMode(latency_mode); } -bool HfpDecodingTransport::GetPresentationPosition( - uint64_t* remote_delay_report_ns, uint64_t* total_bytes_written, - timespec* data_position) { - return transport_->GetPresentationPosition( - remote_delay_report_ns, total_bytes_written, data_position); +bool HfpDecodingTransport::GetPresentationPosition(uint64_t* remote_delay_report_ns, + uint64_t* total_bytes_written, + timespec* data_position) { + return transport_->GetPresentationPosition(remote_delay_report_ns, total_bytes_written, + data_position); } -void HfpDecodingTransport::SourceMetadataChanged( - const source_metadata_v7_t& source_metadata) { +void HfpDecodingTransport::SourceMetadataChanged(const source_metadata_v7_t& source_metadata) { transport_->SourceMetadataChanged(source_metadata); } -void HfpDecodingTransport::SinkMetadataChanged( - const sink_metadata_v7_t& sink_metadata) { +void HfpDecodingTransport::SinkMetadataChanged(const sink_metadata_v7_t& sink_metadata) { transport_->SinkMetadataChanged(sink_metadata); } -void HfpDecodingTransport::ResetPresentationPosition() { - transport_->ResetPresentationPosition(); -} +void HfpDecodingTransport::ResetPresentationPosition() { transport_->ResetPresentationPosition(); } void HfpDecodingTransport::LogBytesRead(size_t bytes_written) { transport_->LogBytesProcessed(bytes_written); } -uint8_t HfpDecodingTransport::GetPendingCmd() const { - return transport_->GetPendingCmd(); -} +uint8_t HfpDecodingTransport::GetPendingCmd() const { return transport_->GetPendingCmd(); } void HfpDecodingTransport::ResetPendingCmd() { transport_->ResetPendingCmd(); } @@ -226,7 +217,7 @@ void HfpDecodingTransport::StopRequest() { transport_->StopRequest(); } HfpEncodingTransport::HfpEncodingTransport(SessionType session_type) : IBluetoothSourceTransportInstance(session_type, (AudioConfiguration){}) { transport_ = new HfpTransport(); -}; +} HfpEncodingTransport::~HfpEncodingTransport() { delete transport_; } @@ -244,34 +235,28 @@ void HfpEncodingTransport::SetLatencyMode(LatencyMode latency_mode) { transport_->SetLatencyMode(latency_mode); } -bool HfpEncodingTransport::GetPresentationPosition( - uint64_t* remote_delay_report_ns, uint64_t* total_bytes_written, - timespec* data_position) { - return transport_->GetPresentationPosition( - remote_delay_report_ns, total_bytes_written, data_position); +bool HfpEncodingTransport::GetPresentationPosition(uint64_t* remote_delay_report_ns, + uint64_t* total_bytes_written, + timespec* data_position) { + return transport_->GetPresentationPosition(remote_delay_report_ns, total_bytes_written, + data_position); } -void HfpEncodingTransport::SourceMetadataChanged( - const source_metadata_v7_t& source_metadata) { +void HfpEncodingTransport::SourceMetadataChanged(const source_metadata_v7_t& source_metadata) { transport_->SourceMetadataChanged(source_metadata); } -void HfpEncodingTransport::SinkMetadataChanged( - const sink_metadata_v7_t& sink_metadata) { +void HfpEncodingTransport::SinkMetadataChanged(const sink_metadata_v7_t& sink_metadata) { transport_->SinkMetadataChanged(sink_metadata); } -void HfpEncodingTransport::ResetPresentationPosition() { - transport_->ResetPresentationPosition(); -} +void HfpEncodingTransport::ResetPresentationPosition() { transport_->ResetPresentationPosition(); } void HfpEncodingTransport::LogBytesWritten(size_t bytes_written) { transport_->LogBytesProcessed(bytes_written); } -uint8_t HfpEncodingTransport::GetPendingCmd() const { - return transport_->GetPendingCmd(); -} +uint8_t HfpEncodingTransport::GetPendingCmd() const { return transport_->GetPendingCmd(); } void HfpEncodingTransport::ResetPendingCmd() { transport_->ResetPendingCmd(); } diff --git a/system/audio_hal_interface/aidl/hfp_client_interface_aidl.h b/system/audio_hal_interface/aidl/hfp_client_interface_aidl.h index 3b7f1f4f676..6aec16ef814 100644 --- a/system/audio_hal_interface/aidl/hfp_client_interface_aidl.h +++ b/system/audio_hal_interface/aidl/hfp_client_interface_aidl.h @@ -45,7 +45,7 @@ typedef enum { // Provide call-in APIs for the Bluetooth Audio HAL class HfpTransport { - public: +public: HfpTransport(); BluetoothAudioCtrlAck StartRequest(); @@ -56,8 +56,7 @@ class HfpTransport { void SetLatencyMode(LatencyMode latency_mode); - bool GetPresentationPosition(uint64_t* remote_delay_report_ns, - uint64_t* total_bytes_read, + bool GetPresentationPosition(uint64_t* remote_delay_report_ns, uint64_t* total_bytes_read, timespec* data_position); void SourceMetadataChanged(const source_metadata_v7_t& source_metadata); @@ -72,17 +71,16 @@ class HfpTransport { void LogBytesProcessed(size_t bytes_read); - static std::unordered_map - GetHfpScoConfig(SessionType sessionType); + static std::unordered_map GetHfpScoConfig( + SessionType sessionType); - private: +private: tHFP_CTRL_CMD hfp_pending_cmd_; }; // Sink transport implementation -class HfpDecodingTransport - : public ::bluetooth::audio::aidl::IBluetoothSinkTransportInstance { - public: +class HfpDecodingTransport : public ::bluetooth::audio::aidl::IBluetoothSinkTransportInstance { +public: HfpDecodingTransport(SessionType sessionType); ~HfpDecodingTransport(); @@ -95,8 +93,7 @@ class HfpDecodingTransport void SetLatencyMode(LatencyMode latency_mode); - bool GetPresentationPosition(uint64_t* remote_delay_report_ns, - uint64_t* total_bytes_read, + bool GetPresentationPosition(uint64_t* remote_delay_report_ns, uint64_t* total_bytes_read, timespec* data_position); void SourceMetadataChanged(const source_metadata_v7_t& source_metadata); @@ -112,20 +109,16 @@ class HfpDecodingTransport void ResetPendingCmd(); static inline HfpDecodingTransport* instance_ = nullptr; - static inline BluetoothAudioSinkClientInterface* software_hal_interface = - nullptr; - static inline BluetoothAudioSinkClientInterface* offloading_hal_interface = - nullptr; - static inline BluetoothAudioSinkClientInterface* active_hal_interface = - nullptr; - - private: + static inline BluetoothAudioSinkClientInterface* software_hal_interface = nullptr; + static inline BluetoothAudioSinkClientInterface* offloading_hal_interface = nullptr; + static inline BluetoothAudioSinkClientInterface* active_hal_interface = nullptr; + +private: HfpTransport* transport_; }; -class HfpEncodingTransport - : public ::bluetooth::audio::aidl::IBluetoothSourceTransportInstance { - public: +class HfpEncodingTransport : public ::bluetooth::audio::aidl::IBluetoothSourceTransportInstance { +public: HfpEncodingTransport(SessionType sessionType); ~HfpEncodingTransport(); @@ -138,8 +131,7 @@ class HfpEncodingTransport void SetLatencyMode(LatencyMode latency_mode); - bool GetPresentationPosition(uint64_t* remote_delay_report_ns, - uint64_t* total_bytes_read, + bool GetPresentationPosition(uint64_t* remote_delay_report_ns, uint64_t* total_bytes_read, timespec* data_position); void SourceMetadataChanged(const source_metadata_v7_t& source_metadata); @@ -155,14 +147,11 @@ class HfpEncodingTransport void ResetPendingCmd(); static inline HfpEncodingTransport* instance_ = nullptr; - static inline BluetoothAudioSourceClientInterface* software_hal_interface = - nullptr; - static inline BluetoothAudioSourceClientInterface* offloading_hal_interface = - nullptr; - static inline BluetoothAudioSourceClientInterface* active_hal_interface = - nullptr; - - private: + static inline BluetoothAudioSourceClientInterface* software_hal_interface = nullptr; + static inline BluetoothAudioSourceClientInterface* offloading_hal_interface = nullptr; + static inline BluetoothAudioSourceClientInterface* active_hal_interface = nullptr; + +private: HfpTransport* transport_; }; diff --git a/system/audio_hal_interface/aidl/le_audio_software_aidl.cc b/system/audio_hal_interface/aidl/le_audio_software_aidl.cc index c162d309e7e..4e7e9dad052 100644 --- a/system/audio_hal_interface/aidl/le_audio_software_aidl.cc +++ b/system/audio_hal_interface/aidl/le_audio_software_aidl.cc @@ -61,8 +61,7 @@ static ChannelMode le_audio_channel_mode2audio_hal(uint8_t channels_count) { return ChannelMode::UNKNOWN; } -LeAudioTransport::LeAudioTransport(void (*flush)(void), - StreamCallbacks stream_cb, +LeAudioTransport::LeAudioTransport(void (*flush)(void), StreamCallbacks stream_cb, PcmConfiguration pcm_config) : flush_(std::move(flush)), stream_cb_(std::move(stream_cb)), @@ -72,7 +71,7 @@ LeAudioTransport::LeAudioTransport(void (*flush)(void), pcm_config_(std::move(pcm_config)), start_request_state_(StartRequestState::IDLE), dsa_mode_(DsaMode::DISABLED), - cached_source_metadata_({}){}; + cached_source_metadata_({}) {} LeAudioTransport::~LeAudioTransport() { if (cached_source_metadata_.tracks != nullptr) { @@ -105,9 +104,8 @@ BluetoothAudioCtrlAck LeAudioTransport::StartRequest(bool /*is_low_latency*/) { } expected = StartRequestState::PENDING_BEFORE_RESUME; - if (std::atomic_compare_exchange_strong( - &start_request_state_, &expected, - StartRequestState::PENDING_AFTER_RESUME)) { + if (std::atomic_compare_exchange_strong(&start_request_state_, &expected, + StartRequestState::PENDING_AFTER_RESUME)) { log::info("Start pending."); return BluetoothAudioCtrlAck::PENDING; } @@ -115,13 +113,11 @@ BluetoothAudioCtrlAck LeAudioTransport::StartRequest(bool /*is_low_latency*/) { log::error("Start request failed."); auto expected = StartRequestState::PENDING_BEFORE_RESUME; - std::atomic_compare_exchange_strong(&start_request_state_, &expected, - StartRequestState::IDLE); + std::atomic_compare_exchange_strong(&start_request_state_, &expected, StartRequestState::IDLE); return BluetoothAudioCtrlAck::FAILURE; } -BluetoothAudioCtrlAck LeAudioTransport::StartRequestV2( - bool /*is_low_latency*/) { +BluetoothAudioCtrlAck LeAudioTransport::StartRequestV2(bool /*is_low_latency*/) { // Check if operation is pending already if (GetStartRequestState() == StartRequestState::PENDING_AFTER_RESUME) { log::info("Start request is already pending. Ignore the request"); @@ -147,8 +143,7 @@ BluetoothAudioCtrlAck LeAudioTransport::StartRequestV2( return BluetoothAudioCtrlAck::PENDING; default: SetStartRequestState(StartRequestState::IDLE); - log::error("Unexpected state {}", - static_cast(start_request_state_.load())); + log::error("Unexpected state {}", static_cast(start_request_state_.load())); return BluetoothAudioCtrlAck::FAILURE; } } @@ -179,9 +174,8 @@ void LeAudioTransport::StopRequest() { } void LeAudioTransport::SetLatencyMode(LatencyMode latency_mode) { - log::debug( - "Latency mode: {}", - ::aidl::android::hardware::bluetooth::audio::toString(latency_mode)); + log::debug("Latency mode: {}", + ::aidl::android::hardware::bluetooth::audio::toString(latency_mode)); DsaMode prev_dsa_mode = dsa_mode_; @@ -204,8 +198,7 @@ void LeAudioTransport::SetLatencyMode(LatencyMode latency_mode) { } if (com::android::bluetooth::flags::leaudio_dynamic_spatial_audio()) { - if (dsa_mode_ != prev_dsa_mode && - cached_source_metadata_.tracks != nullptr && + if (dsa_mode_ != prev_dsa_mode && cached_source_metadata_.tracks != nullptr && cached_source_metadata_.tracks != 0) { log::info(", latency mode changed, update source metadata"); stream_cb_.on_metadata_update_(cached_source_metadata_, dsa_mode_); @@ -216,21 +209,22 @@ void LeAudioTransport::SetLatencyMode(LatencyMode latency_mode) { bool LeAudioTransport::GetPresentationPosition(uint64_t* remote_delay_report_ns, uint64_t* total_bytes_processed, timespec* data_position) { - log::verbose("data={} byte(s), timestamp={}.{}s, delay report={} msec.", - total_bytes_processed_, data_position_.tv_sec, - data_position_.tv_nsec, remote_delay_report_ms_); + log::verbose("data={} byte(s), timestamp={}.{}s, delay report={} msec.", total_bytes_processed_, + data_position_.tv_sec, data_position_.tv_nsec, remote_delay_report_ms_); if (remote_delay_report_ns != nullptr) { *remote_delay_report_ns = remote_delay_report_ms_ * 1000000u; } - if (total_bytes_processed != nullptr) + if (total_bytes_processed != nullptr) { *total_bytes_processed = total_bytes_processed_; - if (data_position != nullptr) *data_position = data_position_; + } + if (data_position != nullptr) { + *data_position = data_position_; + } return true; } -void LeAudioTransport::SourceMetadataChanged( - const source_metadata_v7_t& source_metadata) { +void LeAudioTransport::SourceMetadataChanged(const source_metadata_v7_t& source_metadata) { auto track_count = source_metadata.track_count; if (track_count == 0) { @@ -257,8 +251,7 @@ void LeAudioTransport::SourceMetadataChanged( stream_cb_.on_metadata_update_(source_metadata, dsa_mode_); } -void LeAudioTransport::SinkMetadataChanged( - const sink_metadata_v7_t& sink_metadata) { +void LeAudioTransport::SinkMetadataChanged(const sink_metadata_v7_t& sink_metadata) { auto track_count = sink_metadata.track_count; if (track_count == 0) { @@ -266,8 +259,9 @@ void LeAudioTransport::SinkMetadataChanged( return; } - if (stream_cb_.on_sink_metadata_update_) + if (stream_cb_.on_sink_metadata_update_) { stream_cb_.on_sink_metadata_update_(sink_metadata); + } } void LeAudioTransport::ResetPresentationPosition() { @@ -289,12 +283,9 @@ void LeAudioTransport::SetRemoteDelay(uint16_t delay_report_ms) { remote_delay_report_ms_ = delay_report_ms; } -const PcmConfiguration& LeAudioTransport::LeAudioGetSelectedHalPcmConfig() { - return pcm_config_; -} +const PcmConfiguration& LeAudioTransport::LeAudioGetSelectedHalPcmConfig() { return pcm_config_; } -void LeAudioTransport::LeAudioSetSelectedHalPcmConfig(uint32_t sample_rate_hz, - uint8_t bit_rate, +void LeAudioTransport::LeAudioSetSelectedHalPcmConfig(uint32_t sample_rate_hz, uint8_t bit_rate, uint8_t channels_count, uint32_t data_interval) { pcm_config_.sampleRateHz = (sample_rate_hz); @@ -304,33 +295,30 @@ void LeAudioTransport::LeAudioSetSelectedHalPcmConfig(uint32_t sample_rate_hz, } void LeAudioTransport::LeAudioSetBroadcastConfig( - const ::bluetooth::le_audio::broadcast_offload_config& offload_config) { + const ::bluetooth::le_audio::broadcast_offload_config& offload_config) { broadcast_config_.streamMap.resize(0); for (auto& [handle, location] : offload_config.stream_map) { Lc3Configuration lc3_config{ - .pcmBitDepth = static_cast(offload_config.bits_per_sample), - .samplingFrequencyHz = - static_cast(offload_config.sampling_rate), - .frameDurationUs = static_cast(offload_config.frame_duration), - .octetsPerFrame = static_cast(offload_config.octets_per_frame), - .blocksPerSdu = static_cast(offload_config.blocks_per_sdu), + .pcmBitDepth = static_cast(offload_config.bits_per_sample), + .samplingFrequencyHz = static_cast(offload_config.sampling_rate), + .frameDurationUs = static_cast(offload_config.frame_duration), + .octetsPerFrame = static_cast(offload_config.octets_per_frame), + .blocksPerSdu = static_cast(offload_config.blocks_per_sdu), }; broadcast_config_.streamMap.push_back({ - .streamHandle = handle, - .audioChannelAllocation = static_cast(location), - .leAudioCodecConfig = std::move(lc3_config), + .streamHandle = handle, + .audioChannelAllocation = static_cast(location), + .leAudioCodecConfig = std::move(lc3_config), }); } } -const LeAudioBroadcastConfiguration& -LeAudioTransport::LeAudioGetBroadcastConfig() { +const LeAudioBroadcastConfiguration& LeAudioTransport::LeAudioGetBroadcastConfig() { return broadcast_config_; } bool LeAudioTransport::IsRequestCompletedAfterUpdate( - const std::function(StartRequestState)>& - lambda) { + const std::function(StartRequestState)>& lambda) { std::lock_guard guard(start_request_state_mutex_); auto result = lambda(start_request_state_); auto new_state = std::get<0>(result); @@ -339,15 +327,13 @@ bool LeAudioTransport::IsRequestCompletedAfterUpdate( } auto ret = std::get<1>(result); - log::verbose("new state: {}, return {}", (int)(start_request_state_.load()), - ret); + log::verbose("new state: {}, return {}", (int)(start_request_state_.load()), ret); return ret; } StartRequestState LeAudioTransport::GetStartRequestState(void) { - if (com::android::bluetooth::flags:: - leaudio_start_request_state_mutex_check()) { + if (com::android::bluetooth::flags::leaudio_start_request_state_mutex_check()) { std::lock_guard guard(start_request_state_mutex_); } return start_request_state_; @@ -360,36 +346,36 @@ void LeAudioTransport::SetStartRequestState(StartRequestState state) { } inline void flush_unicast_sink() { - if (LeAudioSinkTransport::interface_unicast_ == nullptr) return; + if (LeAudioSinkTransport::interface_unicast_ == nullptr) { + return; + } LeAudioSinkTransport::interface_unicast_->FlushAudioData(); } inline void flush_broadcast_sink() { - if (LeAudioSinkTransport::interface_broadcast_ == nullptr) return; + if (LeAudioSinkTransport::interface_broadcast_ == nullptr) { + return; + } LeAudioSinkTransport::interface_broadcast_->FlushAudioData(); } inline bool is_broadcaster_session(SessionType session_type) { - if (session_type == - SessionType::LE_AUDIO_BROADCAST_HARDWARE_OFFLOAD_ENCODING_DATAPATH || - session_type == - SessionType::LE_AUDIO_BROADCAST_SOFTWARE_ENCODING_DATAPATH) { + if (session_type == SessionType::LE_AUDIO_BROADCAST_HARDWARE_OFFLOAD_ENCODING_DATAPATH || + session_type == SessionType::LE_AUDIO_BROADCAST_SOFTWARE_ENCODING_DATAPATH) { return true; } return false; } -LeAudioSinkTransport::LeAudioSinkTransport(SessionType session_type, - StreamCallbacks stream_cb) +LeAudioSinkTransport::LeAudioSinkTransport(SessionType session_type, StreamCallbacks stream_cb) : IBluetoothSinkTransportInstance(session_type, (AudioConfiguration){}) { transport_ = new LeAudioTransport( - is_broadcaster_session(session_type) ? flush_broadcast_sink - : flush_unicast_sink, - std::move(stream_cb), {16000, ChannelMode::STEREO, 16, 0}); -}; + is_broadcaster_session(session_type) ? flush_broadcast_sink : flush_unicast_sink, + std::move(stream_cb), {16000, ChannelMode::STEREO, 16, 0}); +} LeAudioSinkTransport::~LeAudioSinkTransport() { delete transport_; } @@ -410,26 +396,22 @@ void LeAudioSinkTransport::SetLatencyMode(LatencyMode latency_mode) { transport_->SetLatencyMode(latency_mode); } -bool LeAudioSinkTransport::GetPresentationPosition( - uint64_t* remote_delay_report_ns, uint64_t* total_bytes_read, - timespec* data_position) { - return transport_->GetPresentationPosition(remote_delay_report_ns, - total_bytes_read, data_position); +bool LeAudioSinkTransport::GetPresentationPosition(uint64_t* remote_delay_report_ns, + uint64_t* total_bytes_read, + timespec* data_position) { + return transport_->GetPresentationPosition(remote_delay_report_ns, total_bytes_read, + data_position); } -void LeAudioSinkTransport::SourceMetadataChanged( - const source_metadata_v7_t& source_metadata) { +void LeAudioSinkTransport::SourceMetadataChanged(const source_metadata_v7_t& source_metadata) { transport_->SourceMetadataChanged(source_metadata); } -void LeAudioSinkTransport::SinkMetadataChanged( - const sink_metadata_v7_t& sink_metadata) { +void LeAudioSinkTransport::SinkMetadataChanged(const sink_metadata_v7_t& sink_metadata) { transport_->SinkMetadataChanged(sink_metadata); } -void LeAudioSinkTransport::ResetPresentationPosition() { - transport_->ResetPresentationPosition(); -} +void LeAudioSinkTransport::ResetPresentationPosition() { transport_->ResetPresentationPosition(); } void LeAudioSinkTransport::LogBytesRead(size_t bytes_read) { transport_->LogBytesProcessed(bytes_read); @@ -443,56 +425,52 @@ const PcmConfiguration& LeAudioSinkTransport::LeAudioGetSelectedHalPcmConfig() { return transport_->LeAudioGetSelectedHalPcmConfig(); } -void LeAudioSinkTransport::LeAudioSetSelectedHalPcmConfig( - uint32_t sample_rate_hz, uint8_t bit_rate, uint8_t channels_count, - uint32_t data_interval) { - transport_->LeAudioSetSelectedHalPcmConfig(sample_rate_hz, bit_rate, - channels_count, data_interval); +void LeAudioSinkTransport::LeAudioSetSelectedHalPcmConfig(uint32_t sample_rate_hz, uint8_t bit_rate, + uint8_t channels_count, + uint32_t data_interval) { + transport_->LeAudioSetSelectedHalPcmConfig(sample_rate_hz, bit_rate, channels_count, + data_interval); } void LeAudioSinkTransport::LeAudioSetBroadcastConfig( - const ::bluetooth::le_audio::broadcast_offload_config& offload_config) { + const ::bluetooth::le_audio::broadcast_offload_config& offload_config) { transport_->LeAudioSetBroadcastConfig(offload_config); } -const LeAudioBroadcastConfiguration& -LeAudioSinkTransport::LeAudioGetBroadcastConfig() { +const LeAudioBroadcastConfiguration& LeAudioSinkTransport::LeAudioGetBroadcastConfig() { return transport_->LeAudioGetBroadcastConfig(); } bool LeAudioSinkTransport::IsRequestCompletedAfterUpdate( - const std::function(StartRequestState)>& - lambda) { + const std::function(StartRequestState)>& lambda) { return transport_->IsRequestCompletedAfterUpdate(lambda); } StartRequestState LeAudioSinkTransport::GetStartRequestState(void) { return transport_->GetStartRequestState(); } -void LeAudioSinkTransport::ClearStartRequestState(void) { - transport_->ClearStartRequestState(); -} +void LeAudioSinkTransport::ClearStartRequestState(void) { transport_->ClearStartRequestState(); } void LeAudioSinkTransport::SetStartRequestState(StartRequestState state) { transport_->SetStartRequestState(state); } void flush_source() { - if (LeAudioSourceTransport::interface == nullptr) return; + if (LeAudioSourceTransport::interface == nullptr) { + return; + } LeAudioSourceTransport::interface->FlushAudioData(); } -LeAudioSourceTransport::LeAudioSourceTransport(SessionType session_type, - StreamCallbacks stream_cb) +LeAudioSourceTransport::LeAudioSourceTransport(SessionType session_type, StreamCallbacks stream_cb) : IBluetoothSourceTransportInstance(session_type, (AudioConfiguration){}) { transport_ = new LeAudioTransport(flush_source, std::move(stream_cb), {16000, ChannelMode::STEREO, 16, 0}); -}; +} LeAudioSourceTransport::~LeAudioSourceTransport() { delete transport_; } -BluetoothAudioCtrlAck LeAudioSourceTransport::StartRequest( - bool is_low_latency) { +BluetoothAudioCtrlAck LeAudioSourceTransport::StartRequest(bool is_low_latency) { if (com::android::bluetooth::flags::leaudio_start_stream_race_fix()) { return transport_->StartRequestV2(is_low_latency); } @@ -509,20 +487,18 @@ void LeAudioSourceTransport::SetLatencyMode(LatencyMode latency_mode) { transport_->SetLatencyMode(latency_mode); } -bool LeAudioSourceTransport::GetPresentationPosition( - uint64_t* remote_delay_report_ns, uint64_t* total_bytes_written, - timespec* data_position) { - return transport_->GetPresentationPosition( - remote_delay_report_ns, total_bytes_written, data_position); +bool LeAudioSourceTransport::GetPresentationPosition(uint64_t* remote_delay_report_ns, + uint64_t* total_bytes_written, + timespec* data_position) { + return transport_->GetPresentationPosition(remote_delay_report_ns, total_bytes_written, + data_position); } -void LeAudioSourceTransport::SourceMetadataChanged( - const source_metadata_v7_t& source_metadata) { +void LeAudioSourceTransport::SourceMetadataChanged(const source_metadata_v7_t& source_metadata) { transport_->SourceMetadataChanged(source_metadata); } -void LeAudioSourceTransport::SinkMetadataChanged( - const sink_metadata_v7_t& sink_metadata) { +void LeAudioSourceTransport::SinkMetadataChanged(const sink_metadata_v7_t& sink_metadata) { transport_->SinkMetadataChanged(sink_metadata); } @@ -538,85 +514,70 @@ void LeAudioSourceTransport::SetRemoteDelay(uint16_t delay_report_ms) { transport_->SetRemoteDelay(delay_report_ms); } -const PcmConfiguration& -LeAudioSourceTransport::LeAudioGetSelectedHalPcmConfig() { +const PcmConfiguration& LeAudioSourceTransport::LeAudioGetSelectedHalPcmConfig() { return transport_->LeAudioGetSelectedHalPcmConfig(); } -void LeAudioSourceTransport::LeAudioSetSelectedHalPcmConfig( - uint32_t sample_rate_hz, uint8_t bit_rate, uint8_t channels_count, - uint32_t data_interval) { - transport_->LeAudioSetSelectedHalPcmConfig(sample_rate_hz, bit_rate, - channels_count, data_interval); +void LeAudioSourceTransport::LeAudioSetSelectedHalPcmConfig(uint32_t sample_rate_hz, + uint8_t bit_rate, + uint8_t channels_count, + uint32_t data_interval) { + transport_->LeAudioSetSelectedHalPcmConfig(sample_rate_hz, bit_rate, channels_count, + data_interval); } bool LeAudioSourceTransport::IsRequestCompletedAfterUpdate( - const std::function(StartRequestState)>& - lambda) { + const std::function(StartRequestState)>& lambda) { return transport_->IsRequestCompletedAfterUpdate(lambda); } StartRequestState LeAudioSourceTransport::GetStartRequestState(void) { return transport_->GetStartRequestState(); } -void LeAudioSourceTransport::ClearStartRequestState(void) { - transport_->ClearStartRequestState(); -} +void LeAudioSourceTransport::ClearStartRequestState(void) { transport_->ClearStartRequestState(); } void LeAudioSourceTransport::SetStartRequestState(StartRequestState state) { transport_->SetStartRequestState(state); } std::unordered_map sampling_freq_map{ - {8000, ::bluetooth::le_audio::codec_spec_conf::kLeAudioSamplingFreq8000Hz}, - {16000, - ::bluetooth::le_audio::codec_spec_conf::kLeAudioSamplingFreq16000Hz}, - {24000, - ::bluetooth::le_audio::codec_spec_conf::kLeAudioSamplingFreq24000Hz}, - {32000, - ::bluetooth::le_audio::codec_spec_conf::kLeAudioSamplingFreq32000Hz}, - {44100, - ::bluetooth::le_audio::codec_spec_conf::kLeAudioSamplingFreq44100Hz}, - {48000, - ::bluetooth::le_audio::codec_spec_conf::kLeAudioSamplingFreq48000Hz}, - {88200, - ::bluetooth::le_audio::codec_spec_conf::kLeAudioSamplingFreq88200Hz}, - {96000, - ::bluetooth::le_audio::codec_spec_conf::kLeAudioSamplingFreq96000Hz}, - {176400, - ::bluetooth::le_audio::codec_spec_conf::kLeAudioSamplingFreq176400Hz}, - {192000, - ::bluetooth::le_audio::codec_spec_conf::kLeAudioSamplingFreq192000Hz}}; + {8000, ::bluetooth::le_audio::codec_spec_conf::kLeAudioSamplingFreq8000Hz}, + {16000, ::bluetooth::le_audio::codec_spec_conf::kLeAudioSamplingFreq16000Hz}, + {24000, ::bluetooth::le_audio::codec_spec_conf::kLeAudioSamplingFreq24000Hz}, + {32000, ::bluetooth::le_audio::codec_spec_conf::kLeAudioSamplingFreq32000Hz}, + {44100, ::bluetooth::le_audio::codec_spec_conf::kLeAudioSamplingFreq44100Hz}, + {48000, ::bluetooth::le_audio::codec_spec_conf::kLeAudioSamplingFreq48000Hz}, + {88200, ::bluetooth::le_audio::codec_spec_conf::kLeAudioSamplingFreq88200Hz}, + {96000, ::bluetooth::le_audio::codec_spec_conf::kLeAudioSamplingFreq96000Hz}, + {176400, ::bluetooth::le_audio::codec_spec_conf::kLeAudioSamplingFreq176400Hz}, + {192000, ::bluetooth::le_audio::codec_spec_conf::kLeAudioSamplingFreq192000Hz}}; std::unordered_map frame_duration_map{ - {7500, ::bluetooth::le_audio::codec_spec_conf::kLeAudioCodecFrameDur7500us}, - {10000, - ::bluetooth::le_audio::codec_spec_conf::kLeAudioCodecFrameDur10000us}}; + {7500, ::bluetooth::le_audio::codec_spec_conf::kLeAudioCodecFrameDur7500us}, + {10000, ::bluetooth::le_audio::codec_spec_conf::kLeAudioCodecFrameDur10000us}}; std::unordered_map octets_per_frame_map{ - {30, ::bluetooth::le_audio::codec_spec_conf::kLeAudioCodecFrameLen30}, - {40, ::bluetooth::le_audio::codec_spec_conf::kLeAudioCodecFrameLen40}, - {60, ::bluetooth::le_audio::codec_spec_conf::kLeAudioCodecFrameLen60}, - {80, ::bluetooth::le_audio::codec_spec_conf::kLeAudioCodecFrameLen80}, - {100, ::bluetooth::le_audio::codec_spec_conf::kLeAudioCodecFrameLen100}, - {120, ::bluetooth::le_audio::codec_spec_conf::kLeAudioCodecFrameLen120}}; + {30, ::bluetooth::le_audio::codec_spec_conf::kLeAudioCodecFrameLen30}, + {40, ::bluetooth::le_audio::codec_spec_conf::kLeAudioCodecFrameLen40}, + {60, ::bluetooth::le_audio::codec_spec_conf::kLeAudioCodecFrameLen60}, + {80, ::bluetooth::le_audio::codec_spec_conf::kLeAudioCodecFrameLen80}, + {100, ::bluetooth::le_audio::codec_spec_conf::kLeAudioCodecFrameLen100}, + {120, ::bluetooth::le_audio::codec_spec_conf::kLeAudioCodecFrameLen120}}; std::unordered_map audio_location_map{ - {AudioLocation::UNKNOWN, - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontCenter}, - {AudioLocation::FRONT_LEFT, - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft}, - {AudioLocation::FRONT_RIGHT, - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight}, - {static_cast( - static_cast(AudioLocation::FRONT_LEFT) | - static_cast(AudioLocation::FRONT_RIGHT)), - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft | - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight}}; - -bool hal_ucast_capability_to_stack_format( - const UnicastCapability& hal_capability, - CodecConfigSetting& stack_capability) { + {AudioLocation::UNKNOWN, + ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontCenter}, + {AudioLocation::FRONT_LEFT, + ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft}, + {AudioLocation::FRONT_RIGHT, + ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight}, + {static_cast(static_cast(AudioLocation::FRONT_LEFT) | + static_cast(AudioLocation::FRONT_RIGHT)), + ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft | + ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight}}; + +bool hal_ucast_capability_to_stack_format(const UnicastCapability& hal_capability, + CodecConfigSetting& stack_capability) { if (hal_capability.codecType != CodecType::LC3) { log::warn("Unsupported codecType: {}", toString(hal_capability.codecType)); return false; @@ -628,8 +589,8 @@ bool hal_ucast_capability_to_stack_format( } auto& hal_lc3_capability = - hal_capability.leAudioCodecCapabilities - .get(); + hal_capability.leAudioCodecCapabilities + .get(); auto supported_channel = hal_capability.supportedChannel; auto sample_rate_hz = hal_lc3_capability.samplingFrequencyHz[0]; auto frame_duration_us = hal_lc3_capability.frameDurationUs[0]; @@ -638,44 +599,38 @@ bool hal_ucast_capability_to_stack_format( if (sampling_freq_map.find(sample_rate_hz) == sampling_freq_map.end() || frame_duration_map.find(frame_duration_us) == frame_duration_map.end() || - octets_per_frame_map.find(octets_per_frame) == - octets_per_frame_map.end() || + octets_per_frame_map.find(octets_per_frame) == octets_per_frame_map.end() || audio_location_map.find(supported_channel) == audio_location_map.end()) { log::error( - "Failed to convert HAL format to stack format\nsample rate hz = " - "{}\nframe duration us = {}\noctets per frame= {}\nsupported channel = " - "{}\nchannel count per device = {}\ndevice count = {}", - sample_rate_hz, frame_duration_us, octets_per_frame, - toString(supported_channel), channel_count, hal_capability.deviceCount); + "Failed to convert HAL format to stack format\nsample rate hz = " + "{}\nframe duration us = {}\noctets per frame= {}\nsupported channel = " + "{}\nchannel count per device = {}\ndevice count = {}", + sample_rate_hz, frame_duration_us, octets_per_frame, toString(supported_channel), + channel_count, hal_capability.deviceCount); return false; } - stack_capability.id = - ::bluetooth::le_audio::set_configurations::LeAudioCodecIdLc3; + stack_capability.id = ::bluetooth::le_audio::set_configurations::LeAudioCodecIdLc3; stack_capability.channel_count_per_iso_stream = channel_count; + stack_capability.params.Add(::bluetooth::le_audio::codec_spec_conf::kLeAudioLtvTypeSamplingFreq, + sampling_freq_map[sample_rate_hz]); + stack_capability.params.Add(::bluetooth::le_audio::codec_spec_conf::kLeAudioLtvTypeFrameDuration, + frame_duration_map[frame_duration_us]); stack_capability.params.Add( - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLtvTypeSamplingFreq, - sampling_freq_map[sample_rate_hz]); + ::bluetooth::le_audio::codec_spec_conf::kLeAudioLtvTypeAudioChannelAllocation, + audio_location_map[supported_channel]); stack_capability.params.Add( - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLtvTypeFrameDuration, - frame_duration_map[frame_duration_us]); - stack_capability.params.Add(::bluetooth::le_audio::codec_spec_conf:: - kLeAudioLtvTypeAudioChannelAllocation, - audio_location_map[supported_channel]); - stack_capability.params.Add(::bluetooth::le_audio::codec_spec_conf:: - kLeAudioLtvTypeOctetsPerCodecFrame, - octets_per_frame_map[octets_per_frame]); + ::bluetooth::le_audio::codec_spec_conf::kLeAudioLtvTypeOctetsPerCodecFrame, + octets_per_frame_map[octets_per_frame]); return true; } -bool hal_bcast_capability_to_stack_format( - const BroadcastCapability& hal_bcast_capability, - CodecConfigSetting& stack_capability) { +bool hal_bcast_capability_to_stack_format(const BroadcastCapability& hal_bcast_capability, + CodecConfigSetting& stack_capability) { if (hal_bcast_capability.codecType != CodecType::LC3) { - log::warn("Unsupported codecType: {}", - toString(hal_bcast_capability.codecType)); + log::warn("Unsupported codecType: {}", toString(hal_bcast_capability.codecType)); return false; } if (hal_bcast_capability.leAudioCodecCapabilities.getTag() != @@ -685,8 +640,8 @@ bool hal_bcast_capability_to_stack_format( } auto& hal_lc3_capabilities = - hal_bcast_capability.leAudioCodecCapabilities.get< - BroadcastCapability::LeAudioCodecCapabilities::lc3Capabilities>(); + hal_bcast_capability.leAudioCodecCapabilities + .get(); if (hal_lc3_capabilities->size() != 1) { log::warn("The number of config is not supported yet."); @@ -700,35 +655,31 @@ bool hal_bcast_capability_to_stack_format( if (sampling_freq_map.find(sample_rate_hz) == sampling_freq_map.end() || frame_duration_map.find(frame_duration_us) == frame_duration_map.end() || - octets_per_frame_map.find(octets_per_frame) == - octets_per_frame_map.end() || + octets_per_frame_map.find(octets_per_frame) == octets_per_frame_map.end() || audio_location_map.find(supported_channel) == audio_location_map.end()) { log::warn( - "Failed to convert HAL format to stack format\nsample rate hz = " - "{}\nframe duration us = {}\noctets per frame= {}\nsupported channel = " - "{}\nchannel count per stream = {}", - sample_rate_hz, frame_duration_us, octets_per_frame, - toString(supported_channel), channel_count); + "Failed to convert HAL format to stack format\nsample rate hz = " + "{}\nframe duration us = {}\noctets per frame= {}\nsupported channel = " + "{}\nchannel count per stream = {}", + sample_rate_hz, frame_duration_us, octets_per_frame, toString(supported_channel), + channel_count); return false; } - stack_capability.id = - ::bluetooth::le_audio::set_configurations::LeAudioCodecIdLc3; + stack_capability.id = ::bluetooth::le_audio::set_configurations::LeAudioCodecIdLc3; stack_capability.channel_count_per_iso_stream = channel_count; + stack_capability.params.Add(::bluetooth::le_audio::codec_spec_conf::kLeAudioLtvTypeSamplingFreq, + sampling_freq_map[sample_rate_hz]); + stack_capability.params.Add(::bluetooth::le_audio::codec_spec_conf::kLeAudioLtvTypeFrameDuration, + frame_duration_map[frame_duration_us]); stack_capability.params.Add( - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLtvTypeSamplingFreq, - sampling_freq_map[sample_rate_hz]); + ::bluetooth::le_audio::codec_spec_conf::kLeAudioLtvTypeAudioChannelAllocation, + audio_location_map[supported_channel]); stack_capability.params.Add( - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLtvTypeFrameDuration, - frame_duration_map[frame_duration_us]); - stack_capability.params.Add(::bluetooth::le_audio::codec_spec_conf:: - kLeAudioLtvTypeAudioChannelAllocation, - audio_location_map[supported_channel]); - stack_capability.params.Add(::bluetooth::le_audio::codec_spec_conf:: - kLeAudioLtvTypeOctetsPerCodecFrame, - octets_per_frame_map[octets_per_frame]); + ::bluetooth::le_audio::codec_spec_conf::kLeAudioLtvTypeOctetsPerCodecFrame, + octets_per_frame_map[octets_per_frame]); return true; } @@ -737,27 +688,23 @@ bluetooth::audio::le_audio::OffloadCapabilities get_offload_capabilities() { std::vector offload_capabilities; std::vector broadcast_offload_capabilities; std::vector le_audio_hal_capabilities = - BluetoothAudioSinkClientInterface::GetAudioCapabilities( - SessionType::LE_AUDIO_HARDWARE_OFFLOAD_ENCODING_DATAPATH); + BluetoothAudioSinkClientInterface::GetAudioCapabilities( + SessionType::LE_AUDIO_HARDWARE_OFFLOAD_ENCODING_DATAPATH); std::string str_capability_log; for (auto hal_cap : le_audio_hal_capabilities) { CodecConfigSetting encode_cap, decode_cap, bcast_cap; UnicastCapability hal_encode_cap = - hal_cap.get() - .unicastEncodeCapability; + hal_cap.get().unicastEncodeCapability; UnicastCapability hal_decode_cap = - hal_cap.get() - .unicastDecodeCapability; + hal_cap.get().unicastDecodeCapability; BroadcastCapability hal_bcast_cap = - hal_cap.get() - .broadcastCapability; + hal_cap.get().broadcastCapability; AudioSetConfiguration audio_set_config = {.name = "offload capability"}; str_capability_log.clear(); if (hal_ucast_capability_to_stack_format(hal_encode_cap, encode_cap)) { - auto ase_cnt = - hal_encode_cap.deviceCount * hal_encode_cap.channelCountPerDevice; + auto ase_cnt = hal_encode_cap.deviceCount * hal_encode_cap.channelCountPerDevice; while (ase_cnt--) { audio_set_config.confs.sink.push_back(AseConfiguration(encode_cap)); } @@ -765,8 +712,7 @@ bluetooth::audio::le_audio::OffloadCapabilities get_offload_capabilities() { } if (hal_ucast_capability_to_stack_format(hal_decode_cap, decode_cap)) { - auto ase_cnt = - hal_decode_cap.deviceCount * hal_decode_cap.channelCountPerDevice; + auto ase_cnt = hal_decode_cap.deviceCount * hal_decode_cap.channelCountPerDevice; while (ase_cnt--) { audio_set_config.confs.source.push_back(AseConfiguration(decode_cap)); } @@ -774,8 +720,7 @@ bluetooth::audio::le_audio::OffloadCapabilities get_offload_capabilities() { } if (hal_bcast_capability_to_stack_format(hal_bcast_cap, bcast_cap)) { - AudioSetConfiguration audio_set_config = { - .name = "broadcast offload capability"}; + AudioSetConfiguration audio_set_config = {.name = "broadcast offload capability"}; // Note: The offloader config supports multiple channels per stream // (subgroup), corresponding to the number of BISes, where each BIS // has a single channel. @@ -785,12 +730,10 @@ bluetooth::audio::le_audio::OffloadCapabilities get_offload_capabilities() { audio_set_config.confs.sink.push_back(AseConfiguration(bcast_cap)); } broadcast_offload_capabilities.push_back(audio_set_config); - str_capability_log += - " Broadcast Capability: " + hal_bcast_cap.toString(); + str_capability_log += " Broadcast Capability: " + hal_bcast_cap.toString(); } - if (!audio_set_config.confs.sink.empty() || - !audio_set_config.confs.source.empty()) { + if (!audio_set_config.confs.sink.empty() || !audio_set_config.confs.source.empty()) { offload_capabilities.push_back(audio_set_config); log::info("Supported codec capability ={}", str_capability_log); @@ -803,23 +746,23 @@ bluetooth::audio::le_audio::OffloadCapabilities get_offload_capabilities() { } AudioConfiguration offload_config_to_hal_audio_config( - const ::bluetooth::le_audio::offload_config& offload_config) { + const ::bluetooth::le_audio::offload_config& offload_config) { Lc3Configuration lc3_config{ - .pcmBitDepth = static_cast(offload_config.bits_per_sample), - .samplingFrequencyHz = static_cast(offload_config.sampling_rate), - .frameDurationUs = static_cast(offload_config.frame_duration), - .octetsPerFrame = static_cast(offload_config.octets_per_frame), - .blocksPerSdu = static_cast(offload_config.blocks_per_sdu), + .pcmBitDepth = static_cast(offload_config.bits_per_sample), + .samplingFrequencyHz = static_cast(offload_config.sampling_rate), + .frameDurationUs = static_cast(offload_config.frame_duration), + .octetsPerFrame = static_cast(offload_config.octets_per_frame), + .blocksPerSdu = static_cast(offload_config.blocks_per_sdu), }; LeAudioConfiguration ucast_config = { - .peerDelayUs = static_cast(offload_config.peer_delay_ms * 1000), - .leAudioCodecConfig = LeAudioCodecConfiguration(lc3_config)}; + .peerDelayUs = static_cast(offload_config.peer_delay_ms * 1000), + .leAudioCodecConfig = LeAudioCodecConfiguration(lc3_config)}; for (auto& [handle, location, state] : offload_config.stream_map) { ucast_config.streamMap.push_back({ - .streamHandle = handle, - .audioChannelAllocation = static_cast(location), - .isStreamActive = state, + .streamHandle = handle, + .audioChannelAllocation = static_cast(location), + .isStreamActive = state, }); } diff --git a/system/audio_hal_interface/aidl/le_audio_software_aidl.h b/system/audio_hal_interface/aidl/le_audio_software_aidl.h index ce1fe223019..f6c19460804 100644 --- a/system/audio_hal_interface/aidl/le_audio_software_aidl.h +++ b/system/audio_hal_interface/aidl/le_audio_software_aidl.h @@ -27,8 +27,7 @@ namespace aidl { namespace le_audio { using ::aidl::android::hardware::bluetooth::audio::BroadcastCapability; -using ::aidl::android::hardware::bluetooth::audio:: - LeAudioBroadcastConfiguration; +using ::aidl::android::hardware::bluetooth::audio::LeAudioBroadcastConfiguration; using ::aidl::android::hardware::bluetooth::audio::LeAudioConfiguration; using ::aidl::android::hardware::bluetooth::audio::PcmConfiguration; using ::aidl::android::hardware::bluetooth::audio::SessionType; @@ -57,18 +56,16 @@ constexpr uint8_t kBitsPerSample32 = 32; using ::bluetooth::audio::le_audio::StreamCallbacks; void flush_source(); -bool hal_ucast_capability_to_stack_format( - const UnicastCapability& ucast_capability, - CodecConfigSetting& stack_capability); +bool hal_ucast_capability_to_stack_format(const UnicastCapability& ucast_capability, + CodecConfigSetting& stack_capability); AudioConfiguration offload_config_to_hal_audio_config( - const ::bluetooth::le_audio::offload_config& offload_config); + const ::bluetooth::le_audio::offload_config& offload_config); bluetooth::audio::le_audio::OffloadCapabilities get_offload_capabilities(); class LeAudioTransport { - public: - LeAudioTransport(void (*flush)(void), StreamCallbacks stream_cb, - PcmConfiguration pcm_config); +public: + LeAudioTransport(void (*flush)(void), StreamCallbacks stream_cb, PcmConfiguration pcm_config); ~LeAudioTransport(); BluetoothAudioCtrlAck StartRequest(bool is_low_latency); @@ -80,8 +77,7 @@ class LeAudioTransport { void SetLatencyMode(LatencyMode latency_mode); - bool GetPresentationPosition(uint64_t* remote_delay_report_ns, - uint64_t* total_bytes_processed, + bool GetPresentationPosition(uint64_t* remote_delay_report_ns, uint64_t* total_bytes_processed, timespec* data_position); void SourceMetadataChanged(const source_metadata_v7_t& source_metadata); @@ -97,22 +93,20 @@ class LeAudioTransport { const PcmConfiguration& LeAudioGetSelectedHalPcmConfig(); void LeAudioSetSelectedHalPcmConfig(uint32_t sample_rate_hz, uint8_t bit_rate, - uint8_t channels_count, - uint32_t data_interval); + uint8_t channels_count, uint32_t data_interval); void LeAudioSetBroadcastConfig( - const ::bluetooth::le_audio::broadcast_offload_config& offload_config); + const ::bluetooth::le_audio::broadcast_offload_config& offload_config); const LeAudioBroadcastConfiguration& LeAudioGetBroadcastConfig(); bool IsRequestCompletedAfterUpdate( - const std::function< - std::pair(StartRequestState)>& lambda); + const std::function(StartRequestState)>& lambda); StartRequestState GetStartRequestState(void); void ClearStartRequestState(void); void SetStartRequestState(StartRequestState state); - private: +private: void (*flush_)(void); StreamCallbacks stream_cb_; uint16_t remote_delay_report_ms_; @@ -127,9 +121,8 @@ class LeAudioTransport { }; // Sink transport implementation for Le Audio -class LeAudioSinkTransport - : public ::bluetooth::audio::aidl::IBluetoothSinkTransportInstance { - public: +class LeAudioSinkTransport : public ::bluetooth::audio::aidl::IBluetoothSinkTransportInstance { +public: LeAudioSinkTransport(SessionType session_type, StreamCallbacks stream_cb); ~LeAudioSinkTransport(); @@ -143,12 +136,10 @@ class LeAudioSinkTransport void SetLatencyMode(LatencyMode latency_mode) override; - bool GetPresentationPosition(uint64_t* remote_delay_report_ns, - uint64_t* total_bytes_read, + bool GetPresentationPosition(uint64_t* remote_delay_report_ns, uint64_t* total_bytes_read, timespec* data_position) override; - void SourceMetadataChanged( - const source_metadata_v7_t& source_metadata) override; + void SourceMetadataChanged(const source_metadata_v7_t& source_metadata) override; void SinkMetadataChanged(const sink_metadata_v7_t& sink_metadata) override; @@ -161,17 +152,15 @@ class LeAudioSinkTransport const PcmConfiguration& LeAudioGetSelectedHalPcmConfig(); void LeAudioSetSelectedHalPcmConfig(uint32_t sample_rate_hz, uint8_t bit_rate, - uint8_t channels_count, - uint32_t data_interval); + uint8_t channels_count, uint32_t data_interval); void LeAudioSetBroadcastConfig( - const ::bluetooth::le_audio::broadcast_offload_config& offload_config); + const ::bluetooth::le_audio::broadcast_offload_config& offload_config); const LeAudioBroadcastConfiguration& LeAudioGetBroadcastConfig(); bool IsRequestCompletedAfterUpdate( - const std::function< - std::pair(StartRequestState)>& lambda); + const std::function(StartRequestState)>& lambda); StartRequestState GetStartRequestState(void); void ClearStartRequestState(void); void SetStartRequestState(StartRequestState state); @@ -180,16 +169,14 @@ class LeAudioSinkTransport static inline LeAudioSinkTransport* instance_broadcast_ = nullptr; static inline BluetoothAudioSinkClientInterface* interface_unicast_ = nullptr; - static inline BluetoothAudioSinkClientInterface* interface_broadcast_ = - nullptr; + static inline BluetoothAudioSinkClientInterface* interface_broadcast_ = nullptr; - private: +private: LeAudioTransport* transport_; }; -class LeAudioSourceTransport - : public ::bluetooth::audio::aidl::IBluetoothSourceTransportInstance { - public: +class LeAudioSourceTransport : public ::bluetooth::audio::aidl::IBluetoothSourceTransportInstance { +public: LeAudioSourceTransport(SessionType session_type, StreamCallbacks stream_cb); ~LeAudioSourceTransport(); @@ -203,12 +190,10 @@ class LeAudioSourceTransport void SetLatencyMode(LatencyMode latency_mode) override; - bool GetPresentationPosition(uint64_t* remote_delay_report_ns, - uint64_t* total_bytes_written, + bool GetPresentationPosition(uint64_t* remote_delay_report_ns, uint64_t* total_bytes_written, timespec* data_position) override; - void SourceMetadataChanged( - const source_metadata_v7_t& source_metadata) override; + void SourceMetadataChanged(const source_metadata_v7_t& source_metadata) override; void SinkMetadataChanged(const sink_metadata_v7_t& sink_metadata) override; @@ -221,12 +206,10 @@ class LeAudioSourceTransport const PcmConfiguration& LeAudioGetSelectedHalPcmConfig(); void LeAudioSetSelectedHalPcmConfig(uint32_t sample_rate_hz, uint8_t bit_rate, - uint8_t channels_count, - uint32_t data_interval); + uint8_t channels_count, uint32_t data_interval); bool IsRequestCompletedAfterUpdate( - const std::function< - std::pair(StartRequestState)>& lambda); + const std::function(StartRequestState)>& lambda); StartRequestState GetStartRequestState(void); void ClearStartRequestState(void); @@ -235,7 +218,7 @@ class LeAudioSourceTransport static inline LeAudioSourceTransport* instance = nullptr; static inline BluetoothAudioSourceClientInterface* interface = nullptr; - private: +private: LeAudioTransport* transport_; }; diff --git a/system/audio_hal_interface/aidl/le_audio_utils.cc b/system/audio_hal_interface/aidl/le_audio_utils.cc index c77004a7cf3..9a581473afe 100644 --- a/system/audio_hal_interface/aidl/le_audio_utils.cc +++ b/system/audio_hal_interface/aidl/le_audio_utils.cc @@ -26,9 +26,8 @@ namespace bluetooth { namespace audio { namespace aidl { -::aidl::android::hardware::bluetooth::audio::CodecId -GetAidlCodecIdFromStackFormat( - const ::bluetooth::le_audio::types::LeAudioCodecId& codec_id) { +::aidl::android::hardware::bluetooth::audio::CodecId GetAidlCodecIdFromStackFormat( + const ::bluetooth::le_audio::types::LeAudioCodecId& codec_id) { ::aidl::android::hardware::bluetooth::audio::CodecId codec; if (codec_id.coding_format == 0x06) { @@ -49,27 +48,23 @@ GetAidlCodecIdFromStackFormat( } ::bluetooth::le_audio::types::LeAudioCodecId GetStackCodecIdFromAidlFormat( - const ::aidl::android::hardware::bluetooth::audio::CodecId& codec_id) { + const ::aidl::android::hardware::bluetooth::audio::CodecId& codec_id) { ::bluetooth::le_audio::types::LeAudioCodecId codec; switch (codec_id.getTag()) { case ::aidl::android::hardware::bluetooth::audio::CodecId::core: { codec.vendor_codec_id = 0x00; codec.vendor_company_id = 0x00; - if (codec_id == - ::aidl::android::hardware::bluetooth::audio::CodecId::Core::LC3) { + if (codec_id == ::aidl::android::hardware::bluetooth::audio::CodecId::Core::LC3) { codec.coding_format = 0x06; - } else if (codec_id == ::aidl::android::hardware::bluetooth::audio:: - CodecId::Core::CVSD) { + } else if (codec_id == ::aidl::android::hardware::bluetooth::audio::CodecId::Core::CVSD) { codec.coding_format = 0x02; - } else if (codec_id == ::aidl::android::hardware::bluetooth::audio:: - CodecId::Core::MSBC) { + } else if (codec_id == ::aidl::android::hardware::bluetooth::audio::CodecId::Core::MSBC) { codec.coding_format = 0x05; } } break; case ::aidl::android::hardware::bluetooth::audio::CodecId::vendor: { - auto vendor = codec_id.get< - ::aidl::android::hardware::bluetooth::audio::CodecId::vendor>(); + auto vendor = codec_id.get<::aidl::android::hardware::bluetooth::audio::CodecId::vendor>(); codec.coding_format = 0xFF; codec.vendor_company_id = vendor.id; codec.vendor_codec_id = vendor.codecId; @@ -83,117 +78,107 @@ GetAidlCodecIdFromStackFormat( return codec; } -std::vector< - ::aidl::android::hardware::bluetooth::audio::CodecSpecificCapabilitiesLtv> -GetAidlCodecCapabilitiesFromStack( - const ::bluetooth::le_audio::types::LeAudioLtvMap& in) { - std::vector< - ::aidl::android::hardware::bluetooth::audio::CodecSpecificCapabilitiesLtv> - ltvs; +std::vector<::aidl::android::hardware::bluetooth::audio::CodecSpecificCapabilitiesLtv> +GetAidlCodecCapabilitiesFromStack(const ::bluetooth::le_audio::types::LeAudioLtvMap& in) { + std::vector<::aidl::android::hardware::bluetooth::audio::CodecSpecificCapabilitiesLtv> ltvs; auto stack_caps = in.GetAsCoreCodecCapabilities(); if (stack_caps.supported_sampling_frequencies) { /* Note: The values match exactly */ ::aidl::android::hardware::bluetooth::audio::CodecSpecificCapabilitiesLtv:: - SupportedSamplingFrequencies freqs{ - .bitmask = *stack_caps.supported_sampling_frequencies}; - if (freqs.bitmask) ltvs.push_back(freqs); + SupportedSamplingFrequencies freqs{.bitmask = + *stack_caps.supported_sampling_frequencies}; + if (freqs.bitmask) { + ltvs.push_back(freqs); + } } if (stack_caps.supported_frame_durations) { /* Note: The values match exactly */ ::aidl::android::hardware::bluetooth::audio::CodecSpecificCapabilitiesLtv:: - SupportedFrameDurations durations{ - .bitmask = *stack_caps.supported_frame_durations}; - if (durations.bitmask) ltvs.push_back(durations); + SupportedFrameDurations durations{.bitmask = *stack_caps.supported_frame_durations}; + if (durations.bitmask) { + ltvs.push_back(durations); + } } if (stack_caps.supported_audio_channel_counts) { /* Note: The values match exactly */ ::aidl::android::hardware::bluetooth::audio::CodecSpecificCapabilitiesLtv:: - SupportedAudioChannelCounts counts{ - .bitmask = *stack_caps.supported_audio_channel_counts}; - if (counts.bitmask) ltvs.push_back(counts); + SupportedAudioChannelCounts counts{.bitmask = + *stack_caps.supported_audio_channel_counts}; + if (counts.bitmask) { + ltvs.push_back(counts); + } } if (stack_caps.supported_min_octets_per_codec_frame && stack_caps.supported_max_octets_per_codec_frame) { ::aidl::android::hardware::bluetooth::audio::CodecSpecificCapabilitiesLtv:: - SupportedOctetsPerCodecFrame octets_per_frame{ - .min = *stack_caps.supported_min_octets_per_codec_frame, - .max = *stack_caps.supported_max_octets_per_codec_frame, - }; + SupportedOctetsPerCodecFrame octets_per_frame{ + .min = *stack_caps.supported_min_octets_per_codec_frame, + .max = *stack_caps.supported_max_octets_per_codec_frame, + }; ltvs.push_back(octets_per_frame); } if (stack_caps.supported_max_codec_frames_per_sdu) { ::aidl::android::hardware::bluetooth::audio::CodecSpecificCapabilitiesLtv:: - SupportedMaxCodecFramesPerSDU codec_frames{ - .value = *stack_caps.supported_max_codec_frames_per_sdu}; + SupportedMaxCodecFramesPerSDU codec_frames{ + .value = *stack_caps.supported_max_codec_frames_per_sdu}; ltvs.push_back(codec_frames); } return ltvs; } -static std::vector< - ::aidl::android::hardware::bluetooth::audio::CodecSpecificConfigurationLtv> +static std::vector<::aidl::android::hardware::bluetooth::audio::CodecSpecificConfigurationLtv> GetAidlCodecSpecificConfigurationFromStack( - const ::bluetooth::le_audio::types::LeAudioLtvMap& stack_ltvs) { - std::vector<::aidl::android::hardware::bluetooth::audio:: - CodecSpecificConfigurationLtv> - aidl_ltvs; + const ::bluetooth::le_audio::types::LeAudioLtvMap& stack_ltvs) { + std::vector<::aidl::android::hardware::bluetooth::audio::CodecSpecificConfigurationLtv> aidl_ltvs; auto stack_config = stack_ltvs.GetAsCoreCodecConfig(); if (stack_config.sampling_frequency.has_value()) { // The frequency values match exactly aidl_ltvs.push_back( - static_cast<::aidl::android::hardware::bluetooth::audio:: - CodecSpecificConfigurationLtv::SamplingFrequency>( - stack_config.sampling_frequency.value())); + static_cast<::aidl::android::hardware::bluetooth::audio::CodecSpecificConfigurationLtv:: + SamplingFrequency>(stack_config.sampling_frequency.value())); } if (stack_config.frame_duration.has_value()) { // The frame duration values match exactly aidl_ltvs.push_back( - static_cast<::aidl::android::hardware::bluetooth::audio:: - CodecSpecificConfigurationLtv::FrameDuration>( - stack_config.frame_duration.value())); + static_cast<::aidl::android::hardware::bluetooth::audio::CodecSpecificConfigurationLtv:: + FrameDuration>(stack_config.frame_duration.value())); } if (stack_config.audio_channel_allocation.has_value()) { // The frequency values match exactly - auto aidl_location = - static_cast(stack_config.audio_channel_allocation.value()); - aidl_ltvs.push_back( - ::aidl::android::hardware::bluetooth::audio:: - CodecSpecificConfigurationLtv::AudioChannelAllocation{ - .bitmask = aidl_location}); + auto aidl_location = static_cast(stack_config.audio_channel_allocation.value()); + aidl_ltvs.push_back(::aidl::android::hardware::bluetooth::audio::CodecSpecificConfigurationLtv:: + AudioChannelAllocation{.bitmask = aidl_location}); } if (stack_config.octets_per_codec_frame.has_value()) { // The octetes per codec frame values match exactly aidl_ltvs.push_back( - ::aidl::android::hardware::bluetooth::audio:: - CodecSpecificConfigurationLtv::OctetsPerCodecFrame{ - .value = stack_config.octets_per_codec_frame.value()}); + ::aidl::android::hardware::bluetooth::audio::CodecSpecificConfigurationLtv:: + OctetsPerCodecFrame{.value = stack_config.octets_per_codec_frame.value()}); } if (stack_config.codec_frames_blocks_per_sdu.has_value()) { // The codec frame blocks per sdu values match exactly - aidl_ltvs.push_back( - ::aidl::android::hardware::bluetooth::audio:: - CodecSpecificConfigurationLtv::CodecFrameBlocksPerSDU{ - .value = stack_config.codec_frames_blocks_per_sdu.value()}); + aidl_ltvs.push_back(::aidl::android::hardware::bluetooth::audio::CodecSpecificConfigurationLtv:: + CodecFrameBlocksPerSDU{ + .value = stack_config.codec_frames_blocks_per_sdu.value()}); } return aidl_ltvs; } -std::optional>> +std::optional>> GetAidlMetadataFromStackFormat(const std::vector& vec) { - if (vec.empty()) return std::nullopt; - std::vector< - std::optional<::aidl::android::hardware::bluetooth::audio::MetadataLtv>> - out_ltvs; + if (vec.empty()) { + return std::nullopt; + } + std::vector> out_ltvs; auto ltvs = ::bluetooth::le_audio::types::LeAudioLtvMap(); if (ltvs.Parse(vec.data(), vec.size())) { @@ -201,33 +186,24 @@ GetAidlMetadataFromStackFormat(const std::vector& vec) { if (stackMetadata.preferred_audio_context) { out_ltvs.push_back( - ::aidl::android::hardware::bluetooth::audio::MetadataLtv:: - PreferredAudioContexts{ - .values = - ::aidl::android::hardware::bluetooth::audio::AudioContext{ - .bitmask = - stackMetadata.preferred_audio_context.value()}}); + ::aidl::android::hardware::bluetooth::audio::MetadataLtv::PreferredAudioContexts{ + .values = ::aidl::android::hardware::bluetooth::audio::AudioContext{ + .bitmask = stackMetadata.preferred_audio_context.value()}}); } if (stackMetadata.streaming_audio_context) { out_ltvs.push_back( - ::aidl::android::hardware::bluetooth::audio::MetadataLtv:: - StreamingAudioContexts{ - .values = - ::aidl::android::hardware::bluetooth::audio::AudioContext{ - .bitmask = - stackMetadata.streaming_audio_context.value()}}); + ::aidl::android::hardware::bluetooth::audio::MetadataLtv::StreamingAudioContexts{ + .values = ::aidl::android::hardware::bluetooth::audio::AudioContext{ + .bitmask = stackMetadata.streaming_audio_context.value()}}); } if (stackMetadata.vendor_specific) { if (stackMetadata.vendor_specific->size() >= 2) { - out_ltvs.push_back( - ::aidl::android::hardware::bluetooth::audio::MetadataLtv:: - VendorSpecific{/* Two octets for the company identifier */ - stackMetadata.vendor_specific->at(0) | - (stackMetadata.vendor_specific->at(1) << 8), - /* The rest is a payload */ - .opaqueValue = std::vector( - stackMetadata.vendor_specific->begin() + 2, - stackMetadata.vendor_specific->end())}); + out_ltvs.push_back(::aidl::android::hardware::bluetooth::audio::MetadataLtv::VendorSpecific{ + /* Two octets for the company identifier */ + stackMetadata.vendor_specific->at(0) | (stackMetadata.vendor_specific->at(1) << 8), + /* The rest is a payload */ + .opaqueValue = std::vector(stackMetadata.vendor_specific->begin() + 2, + stackMetadata.vendor_specific->end())}); } } /* Note: stackMetadata.program_info @@ -246,36 +222,33 @@ GetAidlMetadataFromStackFormat(const std::vector& vec) { } bluetooth::le_audio::types::LeAudioLtvMap GetStackMetadataFromAidlFormat( - const std::vector>& source) { + const std::vector>& + source) { bluetooth::le_audio::types::LeAudioLtvMap cfg; (void)source; for (auto const& entry : source) { - if (!entry.has_value()) continue; - - if (entry->getTag() == ::aidl::android::hardware::bluetooth::audio:: - MetadataLtv::preferredAudioContexts) { - auto aidl_contexts = - entry->get<::aidl::android::hardware::bluetooth::audio::MetadataLtv:: - preferredAudioContexts>(); - cfg.Add( - bluetooth::le_audio::types::kLeAudioMetadataTypePreferredAudioContext, - (uint16_t)aidl_contexts.values.bitmask); - - } else if (entry->getTag() == ::aidl::android::hardware::bluetooth::audio:: - MetadataLtv::streamingAudioContexts) { - auto aidl_contexts = - entry->get<::aidl::android::hardware::bluetooth::audio::MetadataLtv:: - streamingAudioContexts>(); - cfg.Add( - bluetooth::le_audio::types::kLeAudioMetadataTypeStreamingAudioContext, - (uint16_t)aidl_contexts.values.bitmask); - - } else if (entry->getTag() == ::aidl::android::hardware::bluetooth::audio:: - MetadataLtv::vendorSpecific) { - auto aidl_vendor_data = - entry->get<::aidl::android::hardware::bluetooth::audio::MetadataLtv:: - vendorSpecific>(); + if (!entry.has_value()) { + continue; + } + + if (entry->getTag() == + ::aidl::android::hardware::bluetooth::audio::MetadataLtv::preferredAudioContexts) { + auto aidl_contexts = entry->get< + ::aidl::android::hardware::bluetooth::audio::MetadataLtv::preferredAudioContexts>(); + cfg.Add(bluetooth::le_audio::types::kLeAudioMetadataTypePreferredAudioContext, + (uint16_t)aidl_contexts.values.bitmask); + + } else if (entry->getTag() == + ::aidl::android::hardware::bluetooth::audio::MetadataLtv::streamingAudioContexts) { + auto aidl_contexts = entry->get< + ::aidl::android::hardware::bluetooth::audio::MetadataLtv::streamingAudioContexts>(); + cfg.Add(bluetooth::le_audio::types::kLeAudioMetadataTypeStreamingAudioContext, + (uint16_t)aidl_contexts.values.bitmask); + + } else if (entry->getTag() == + ::aidl::android::hardware::bluetooth::audio::MetadataLtv::vendorSpecific) { + auto aidl_vendor_data = entry->get< + ::aidl::android::hardware::bluetooth::audio::MetadataLtv::vendorSpecific>(); cfg.Add(bluetooth::le_audio::types::kLeAudioMetadataTypeVendorSpecific, aidl_vendor_data.companyId, aidl_vendor_data.opaqueValue); } @@ -283,94 +256,84 @@ bluetooth::le_audio::types::LeAudioLtvMap GetStackMetadataFromAidlFormat( return cfg; } -std::optional>> +std::optional< + std::vector>> GetAidlLeAudioDeviceCapabilitiesFromStackFormat( - const std::optional< - std::vector<::bluetooth::le_audio::types::acs_ac_record>>& pacs) { - std::vector< - std::optional<::aidl::android::hardware::bluetooth::audio:: - IBluetoothAudioProvider::LeAudioDeviceCapabilities>> - caps; + const std::optional>& pacs) { + std::vector> + caps; if (pacs.has_value()) { for (auto const& rec : pacs.value()) { ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: - LeAudioDeviceCapabilities cap; + LeAudioDeviceCapabilities cap; cap.codecId = GetAidlCodecIdFromStackFormat(rec.codec_id); - cap.codecSpecificCapabilities = - GetAidlCodecCapabilitiesFromStack(rec.codec_spec_caps); + cap.codecSpecificCapabilities = GetAidlCodecCapabilitiesFromStack(rec.codec_spec_caps); cap.vendorCodecSpecificCapabilities = - (rec.codec_spec_caps_raw.empty() - ? std::nullopt - : std::optional>(rec.codec_spec_caps_raw)); + (rec.codec_spec_caps_raw.empty() + ? std::nullopt + : std::optional>(rec.codec_spec_caps_raw)); cap.metadata = GetAidlMetadataFromStackFormat(rec.metadata); caps.push_back(cap); } } - return (caps.empty() - ? std::nullopt - : std::optional>>( - caps)); + return caps.empty() ? std::nullopt + : std::optional>>(caps); } ::bluetooth::le_audio::types::LeAudioLtvMap GetStackLeAudioLtvMapFromAidlFormat( - const std::vector<::aidl::android::hardware::bluetooth::audio:: - CodecSpecificConfigurationLtv>& aidl_config_ltvs) { + const std::vector< + ::aidl::android::hardware::bluetooth::audio::CodecSpecificConfigurationLtv>& + aidl_config_ltvs) { ::bluetooth::le_audio::types::LeAudioLtvMap stack_ltv; for (auto const& ltv : aidl_config_ltvs) { switch (ltv.getTag()) { - case ::aidl::android::hardware::bluetooth::audio:: - CodecSpecificConfigurationLtv::Tag::codecFrameBlocksPerSDU: - stack_ltv.Add(::bluetooth::le_audio::codec_spec_conf:: - kLeAudioLtvTypeCodecFrameBlocksPerSdu, - (uint8_t)ltv - .get<::aidl::android::hardware::bluetooth::audio:: - CodecSpecificConfigurationLtv::Tag:: - codecFrameBlocksPerSDU>() - .value); + case ::aidl::android::hardware::bluetooth::audio::CodecSpecificConfigurationLtv::Tag:: + codecFrameBlocksPerSDU: + stack_ltv.Add( + ::bluetooth::le_audio::codec_spec_conf::kLeAudioLtvTypeCodecFrameBlocksPerSdu, + (uint8_t)ltv + .get<::aidl::android::hardware::bluetooth::audio:: + CodecSpecificConfigurationLtv::Tag::codecFrameBlocksPerSDU>() + .value); break; - case ::aidl::android::hardware::bluetooth::audio:: - CodecSpecificConfigurationLtv::Tag::samplingFrequency: + case ::aidl::android::hardware::bluetooth::audio::CodecSpecificConfigurationLtv::Tag:: + samplingFrequency: stack_ltv.Add( - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLtvTypeSamplingFreq, - (uint8_t)ltv.get< - ::aidl::android::hardware::bluetooth::audio:: - CodecSpecificConfigurationLtv::Tag::samplingFrequency>()); + ::bluetooth::le_audio::codec_spec_conf::kLeAudioLtvTypeSamplingFreq, + (uint8_t)ltv.get<::aidl::android::hardware::bluetooth::audio:: + CodecSpecificConfigurationLtv::Tag::samplingFrequency>()); break; - case ::aidl::android::hardware::bluetooth::audio:: - CodecSpecificConfigurationLtv::Tag::frameDuration: + case ::aidl::android::hardware::bluetooth::audio::CodecSpecificConfigurationLtv::Tag:: + frameDuration: stack_ltv.Add( - ::bluetooth::le_audio::codec_spec_conf:: - kLeAudioLtvTypeFrameDuration, - (uint8_t)ltv - .get<::aidl::android::hardware::bluetooth::audio:: - CodecSpecificConfigurationLtv::Tag::frameDuration>()); + ::bluetooth::le_audio::codec_spec_conf::kLeAudioLtvTypeFrameDuration, + (uint8_t)ltv.get<::aidl::android::hardware::bluetooth::audio:: + CodecSpecificConfigurationLtv::Tag::frameDuration>()); break; - case ::aidl::android::hardware::bluetooth::audio:: - CodecSpecificConfigurationLtv::Tag::audioChannelAllocation: - stack_ltv.Add(::bluetooth::le_audio::codec_spec_conf:: - kLeAudioLtvTypeAudioChannelAllocation, - (uint32_t)ltv - .get<::aidl::android::hardware::bluetooth::audio:: - CodecSpecificConfigurationLtv::Tag:: - audioChannelAllocation>() - .bitmask); + case ::aidl::android::hardware::bluetooth::audio::CodecSpecificConfigurationLtv::Tag:: + audioChannelAllocation: + stack_ltv.Add( + ::bluetooth::le_audio::codec_spec_conf::kLeAudioLtvTypeAudioChannelAllocation, + (uint32_t)ltv + .get<::aidl::android::hardware::bluetooth::audio:: + CodecSpecificConfigurationLtv::Tag::audioChannelAllocation>() + .bitmask); break; - case ::aidl::android::hardware::bluetooth::audio:: - CodecSpecificConfigurationLtv::Tag::octetsPerCodecFrame: - stack_ltv.Add(::bluetooth::le_audio::codec_spec_conf:: - kLeAudioLtvTypeOctetsPerCodecFrame, - (uint16_t)ltv - .get<::aidl::android::hardware::bluetooth::audio:: - CodecSpecificConfigurationLtv::Tag:: - octetsPerCodecFrame>() - .value); + case ::aidl::android::hardware::bluetooth::audio::CodecSpecificConfigurationLtv::Tag:: + octetsPerCodecFrame: + stack_ltv.Add( + ::bluetooth::le_audio::codec_spec_conf::kLeAudioLtvTypeOctetsPerCodecFrame, + (uint16_t)ltv + .get<::aidl::android::hardware::bluetooth::audio:: + CodecSpecificConfigurationLtv::Tag::octetsPerCodecFrame>() + .value); break; default: break; @@ -379,13 +342,11 @@ GetAidlLeAudioDeviceCapabilitiesFromStackFormat( return stack_ltv; } -::bluetooth::le_audio::broadcaster::BroadcastSubgroupBisCodecConfig -GetStackBisConfigFromAidlFormat( - const ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: - LeAudioSubgroupBisConfiguration& aidl_cfg, - ::bluetooth::le_audio::types::LeAudioCodecId& out_codec_id) { - out_codec_id = - GetStackCodecIdFromAidlFormat(aidl_cfg.bisConfiguration.codecId); +::bluetooth::le_audio::broadcaster::BroadcastSubgroupBisCodecConfig GetStackBisConfigFromAidlFormat( + const ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: + LeAudioSubgroupBisConfiguration& aidl_cfg, + ::bluetooth::le_audio::types::LeAudioCodecId& out_codec_id) { + out_codec_id = GetStackCodecIdFromAidlFormat(aidl_cfg.bisConfiguration.codecId); // Note: Using the hardcoded value for now - the BIS allocated channel uint8_t bis_channel_cnt = 1; @@ -393,36 +354,30 @@ GetStackBisConfigFromAidlFormat( // Note: No support for the metadata at the BIS level in the BT stack yet. return ::bluetooth::le_audio::broadcaster::BroadcastSubgroupBisCodecConfig( - aidl_cfg.numBis, bis_channel_cnt, - GetStackLeAudioLtvMapFromAidlFormat( - aidl_cfg.bisConfiguration.codecConfiguration), - aidl_cfg.bisConfiguration.vendorCodecConfiguration.empty() - ? std::nullopt - : std::optional>( - aidl_cfg.bisConfiguration.vendorCodecConfiguration)); + aidl_cfg.numBis, bis_channel_cnt, + GetStackLeAudioLtvMapFromAidlFormat(aidl_cfg.bisConfiguration.codecConfiguration), + aidl_cfg.bisConfiguration.vendorCodecConfiguration.empty() + ? std::nullopt + : std::optional>( + aidl_cfg.bisConfiguration.vendorCodecConfiguration)); } std::vector<::bluetooth::le_audio::broadcaster::BroadcastSubgroupCodecConfig> GetStackSubgroupsFromAidlFormat( - const std::vector< - ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: - LeAudioBroadcastSubgroupConfiguration>& aidl_subgroups) { - std::vector<::bluetooth::le_audio::broadcaster::BroadcastSubgroupCodecConfig> - vec; + const std::vector<::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: + LeAudioBroadcastSubgroupConfiguration>& aidl_subgroups) { + std::vector<::bluetooth::le_audio::broadcaster::BroadcastSubgroupCodecConfig> vec; for (const auto& subgroup : aidl_subgroups) { - std::vector< - ::bluetooth::le_audio::broadcaster::BroadcastSubgroupBisCodecConfig> - bis_codec_configs; + std::vector<::bluetooth::le_audio::broadcaster::BroadcastSubgroupBisCodecConfig> + bis_codec_configs; ::bluetooth::le_audio::types::LeAudioCodecId codec_id; for (auto const& bis_cfg : subgroup.bisConfigurations) { - bis_codec_configs.push_back( - GetStackBisConfigFromAidlFormat(bis_cfg, codec_id)); + bis_codec_configs.push_back(GetStackBisConfigFromAidlFormat(bis_cfg, codec_id)); } uint8_t bits_per_sample = 16; // Note: Irrelevant for the offloader - ::bluetooth::le_audio::broadcaster::BroadcastSubgroupCodecConfig - stack_subgroup(codec_id, bis_codec_configs, bits_per_sample, - subgroup.vendorCodecConfiguration); + ::bluetooth::le_audio::broadcaster::BroadcastSubgroupCodecConfig stack_subgroup( + codec_id, bis_codec_configs, bits_per_sample, subgroup.vendorCodecConfiguration); vec.push_back(stack_subgroup); } return vec; @@ -430,20 +385,18 @@ GetStackSubgroupsFromAidlFormat( std::optional<::bluetooth::le_audio::broadcaster::BroadcastConfiguration> GetStackBroadcastConfigurationFromAidlFormat( - const ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: - LeAudioBroadcastConfigurationSetting& setting) { + const ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: + LeAudioBroadcastConfigurationSetting& setting) { ::bluetooth::le_audio::broadcaster::BroadcastConfiguration cfg{ - .subgroups = - GetStackSubgroupsFromAidlFormat(setting.subgroupsConfigurations), - .qos = ::bluetooth::le_audio::broadcaster::BroadcastQosConfig( - setting.retransmitionNum, setting.maxTransportLatencyMs), - .data_path = - GetStackDataPathFromAidlFormat(*setting.dataPathConfiguration), - .sduIntervalUs = (uint32_t)setting.sduIntervalUs, - .maxSduOctets = (uint16_t)setting.maxSduOctets, - .phy = 0, // recomputed later on - .packing = (uint8_t)setting.packing, - .framing = (uint8_t)setting.framing, + .subgroups = GetStackSubgroupsFromAidlFormat(setting.subgroupsConfigurations), + .qos = ::bluetooth::le_audio::broadcaster::BroadcastQosConfig( + setting.retransmitionNum, setting.maxTransportLatencyMs), + .data_path = GetStackDataPathFromAidlFormat(*setting.dataPathConfiguration), + .sduIntervalUs = (uint32_t)setting.sduIntervalUs, + .maxSduOctets = (uint16_t)setting.maxSduOctets, + .phy = 0, // recomputed later on + .packing = (uint8_t)setting.packing, + .framing = (uint8_t)setting.framing, }; for (auto phy : setting.phy) { @@ -453,13 +406,11 @@ GetStackBroadcastConfigurationFromAidlFormat( return std::move(cfg); } -::bluetooth::le_audio::set_configurations::QosConfigSetting -GetStackQosConfigSettingFromAidl( - const std::optional< - ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: - LeAudioAseQosConfiguration>& aidl_qos, - ::aidl::android::hardware::bluetooth::audio::LeAudioAseConfiguration:: - TargetLatency target_latency) { +::bluetooth::le_audio::set_configurations::QosConfigSetting GetStackQosConfigSettingFromAidl( + const std::optional<::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: + LeAudioAseQosConfiguration>& aidl_qos, + ::aidl::android::hardware::bluetooth::audio::LeAudioAseConfiguration::TargetLatency + target_latency) { auto config = ::bluetooth::le_audio::set_configurations::QosConfigSetting(); if (aidl_qos.has_value()) { config.sduIntervalUs = aidl_qos->sduIntervalUs; @@ -472,30 +423,25 @@ GetStackQosConfigSettingFromAidl( return config; } -::bluetooth::le_audio::set_configurations::CodecConfigSetting -GetCodecConfigSettingFromAidl( - const std::optional< - ::aidl::android::hardware::bluetooth::audio::LeAudioAseConfiguration>& - ase_config) { - auto stack_config = - ::bluetooth::le_audio::set_configurations::CodecConfigSetting(); +::bluetooth::le_audio::set_configurations::CodecConfigSetting GetCodecConfigSettingFromAidl( + const std::optional<::aidl::android::hardware::bluetooth::audio::LeAudioAseConfiguration>& + ase_config) { + auto stack_config = ::bluetooth::le_audio::set_configurations::CodecConfigSetting(); if (ase_config.has_value()) { if (ase_config->codecId.has_value()) { - stack_config.id = - GetStackCodecIdFromAidlFormat(ase_config->codecId.value()); + stack_config.id = GetStackCodecIdFromAidlFormat(ase_config->codecId.value()); } if (ase_config->vendorCodecConfiguration.has_value()) { stack_config.vendor_params = ase_config->vendorCodecConfiguration.value(); } if (!ase_config->codecConfiguration.empty()) { - stack_config.params = - GetStackLeAudioLtvMapFromAidlFormat(ase_config->codecConfiguration); + stack_config.params = GetStackLeAudioLtvMapFromAidlFormat(ase_config->codecConfiguration); auto cfg = stack_config.params.GetAsCoreCodecConfig(); if (cfg.audio_channel_allocation.has_value()) { stack_config.channel_count_per_iso_stream = - std::bitset<32>(cfg.audio_channel_allocation.value()).count(); + std::bitset<32>(cfg.audio_channel_allocation.value()).count(); } } } @@ -503,21 +449,18 @@ GetCodecConfigSettingFromAidl( return stack_config; } -::bluetooth::le_audio::types::DataPathConfiguration -GetStackDataPathFromAidlFormat( - const ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: - LeAudioDataPathConfiguration& dp) { +::bluetooth::le_audio::types::DataPathConfiguration GetStackDataPathFromAidlFormat( + const ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: + LeAudioDataPathConfiguration& dp) { auto config = ::bluetooth::le_audio::types::DataPathConfiguration{ - .dataPathId = static_cast(dp.dataPathId), - .dataPathConfig = {}, - .isoDataPathConfig = { - .codecId = GetStackCodecIdFromAidlFormat( - dp.isoDataPathConfiguration.codecId), - .isTransparent = dp.isoDataPathConfiguration.isTransparent, - .controllerDelayUs = - (uint32_t)dp.isoDataPathConfiguration.controllerDelayUs, - .configuration = {}, - }}; + .dataPathId = static_cast(dp.dataPathId), + .dataPathConfig = {}, + .isoDataPathConfig = { + .codecId = GetStackCodecIdFromAidlFormat(dp.isoDataPathConfiguration.codecId), + .isTransparent = dp.isoDataPathConfiguration.isTransparent, + .controllerDelayUs = (uint32_t)dp.isoDataPathConfiguration.controllerDelayUs, + .configuration = {}, + }}; // Due to AIDL not having the Transparent codec type, it uses the boolean and // we should manually align the codecId. @@ -534,15 +477,13 @@ GetStackDataPathFromAidlFormat( // Due to AIDL not having the Transparent codec type, it uses the boolean and // we should manually align the codecId. if (config.isoDataPathConfig.isTransparent) { - config.isoDataPathConfig.codecId.coding_format = - bluetooth::hci::kIsoCodingFormatTransparent; + config.isoDataPathConfig.codecId.coding_format = bluetooth::hci::kIsoCodingFormatTransparent; config.isoDataPathConfig.codecId.vendor_codec_id = 0x00; config.isoDataPathConfig.codecId.vendor_company_id = 0x00; } if (dp.isoDataPathConfiguration.configuration) { - config.isoDataPathConfig.configuration = - *dp.isoDataPathConfiguration.configuration; + config.isoDataPathConfig.configuration = *dp.isoDataPathConfiguration.configuration; } return config; @@ -550,44 +491,40 @@ GetStackDataPathFromAidlFormat( // The number of source entries is the total count of ASEs within the group to // be configured -::bluetooth::le_audio::set_configurations::AseConfiguration -GetStackAseConfigurationFromAidl( - const ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: - LeAudioAseConfigurationSetting::AseDirectionConfiguration& source) { - auto stack_qos = GetStackQosConfigSettingFromAidl( - source.qosConfiguration, source.aseConfiguration.targetLatency); +::bluetooth::le_audio::set_configurations::AseConfiguration GetStackAseConfigurationFromAidl( + const ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: + LeAudioAseConfigurationSetting::AseDirectionConfiguration& source) { + auto stack_qos = GetStackQosConfigSettingFromAidl(source.qosConfiguration, + source.aseConfiguration.targetLatency); auto config = ::bluetooth::le_audio::set_configurations::AseConfiguration( - GetCodecConfigSettingFromAidl(source.aseConfiguration), stack_qos); + GetCodecConfigSettingFromAidl(source.aseConfiguration), stack_qos); if (source.dataPathConfiguration.has_value()) { - config.data_path_configuration = - GetStackDataPathFromAidlFormat(*source.dataPathConfiguration); + config.data_path_configuration = GetStackDataPathFromAidlFormat(*source.dataPathConfiguration); } return config; } -::bluetooth::le_audio::set_configurations::AudioSetConfiguration -GetStackConfigSettingFromAidl( - ::bluetooth::le_audio::types::LeAudioContextType ctx_type, - const ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: - LeAudioAseConfigurationSetting& aidl_ase_config) { +::bluetooth::le_audio::set_configurations::AudioSetConfiguration GetStackConfigSettingFromAidl( + ::bluetooth::le_audio::types::LeAudioContextType ctx_type, + const ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: + LeAudioAseConfigurationSetting& aidl_ase_config) { /* Verify the returned audio context and report if not matching */ if (aidl_ase_config.audioContext.bitmask != (uint16_t)ctx_type) { - log::error("Audio Context mismatch. Expected {}, but received: {}", - (int)ctx_type, aidl_ase_config.audioContext.bitmask); + log::error("Audio Context mismatch. Expected {}, but received: {}", (int)ctx_type, + aidl_ase_config.audioContext.bitmask); } ::bluetooth::le_audio::set_configurations::AudioSetConfiguration cig_config{ - .name = "AIDL codec provider configuration", - .packing = (uint8_t)aidl_ase_config.packing, - .confs = {.sink = {}, .source = {}}, + .name = "AIDL codec provider configuration", + .packing = (uint8_t)aidl_ase_config.packing, + .confs = {.sink = {}, .source = {}}, }; if (aidl_ase_config.sinkAseConfiguration) { for (auto const& entry : *aidl_ase_config.sinkAseConfiguration) { if (entry) { - cig_config.confs.sink.push_back( - GetStackAseConfigurationFromAidl(*entry)); + cig_config.confs.sink.push_back(GetStackAseConfigurationFromAidl(*entry)); } } } @@ -595,8 +532,7 @@ GetStackConfigSettingFromAidl( if (aidl_ase_config.sourceAseConfiguration) { for (auto const& entry : *aidl_ase_config.sourceAseConfiguration) { if (entry) { - cig_config.confs.source.push_back( - GetStackAseConfigurationFromAidl(*entry)); + cig_config.confs.source.push_back(GetStackAseConfigurationFromAidl(*entry)); } } } @@ -606,9 +542,9 @@ GetStackConfigSettingFromAidl( std::optional<::bluetooth::le_audio::set_configurations::AudioSetConfiguration> GetStackUnicastConfigurationFromAidlFormat( - ::bluetooth::le_audio::types::LeAudioContextType ctx_type, - const ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: - LeAudioAseConfigurationSetting& config) { + ::bluetooth::le_audio::types::LeAudioContextType ctx_type, + const ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: + LeAudioAseConfigurationSetting& config) { auto stack_config = GetStackConfigSettingFromAidl(ctx_type, config); if (stack_config.confs.sink.empty() && stack_config.confs.source.empty()) { @@ -619,28 +555,27 @@ GetStackUnicastConfigurationFromAidlFormat( } ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: - LeAudioBroadcastConfigurationRequirement - GetAidlLeAudioBroadcastConfigurationRequirementFromStackFormat( - const std::vector>& - subgroup_quality) { - auto aidl_requirements = ::aidl::android::hardware::bluetooth::audio:: - IBluetoothAudioProvider::LeAudioBroadcastConfigurationRequirement(); + LeAudioBroadcastConfigurationRequirement + GetAidlLeAudioBroadcastConfigurationRequirementFromStackFormat( + const std::vector>& subgroup_quality) { + auto aidl_requirements = ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: + LeAudioBroadcastConfigurationRequirement(); for (auto const& [context, quality] : subgroup_quality) { ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: - LeAudioBroadcastSubgroupConfigurationRequirement req; + LeAudioBroadcastSubgroupConfigurationRequirement req; req.audioContext.bitmask = static_cast(context); // Note: Currently there is no equivalent of this in the stack data format req.bisNumPerSubgroup = 2; if (quality == le_audio::QUALITY_STANDARD) { - req.quality = ::aidl::android::hardware::bluetooth::audio:: - IBluetoothAudioProvider::BroadcastQuality::STANDARD; + req.quality = ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: + BroadcastQuality::STANDARD; } else if (quality == le_audio::QUALITY_HIGH) { - req.quality = ::aidl::android::hardware::bluetooth::audio:: - IBluetoothAudioProvider::BroadcastQuality::HIGH; + req.quality = ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: + BroadcastQuality::HIGH; } aidl_requirements.subgroupConfigurationRequirements.push_back(req); @@ -650,70 +585,61 @@ GetStackUnicastConfigurationFromAidlFormat( } ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: - LeAudioConfigurationRequirement - GetAidlLeAudioUnicastConfigurationRequirementsFromStackFormat( - ::bluetooth::le_audio::types::LeAudioContextType context_type, - const std::optional>& - sink_reqs, - const std::optional>& - source_reqs) { - auto aidl_reqs = ::aidl::android::hardware::bluetooth::audio:: - IBluetoothAudioProvider::LeAudioConfigurationRequirement(); + LeAudioConfigurationRequirement + GetAidlLeAudioUnicastConfigurationRequirementsFromStackFormat( + ::bluetooth::le_audio::types::LeAudioContextType context_type, + const std::optional>& sink_reqs, + const std::optional>& source_reqs) { + auto aidl_reqs = ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: + LeAudioConfigurationRequirement(); if (sink_reqs) { - aidl_reqs.sinkAseRequirement = std::make_optional>>(); + aidl_reqs.sinkAseRequirement = std::make_optional>>(); for (auto const& stack_req : *sink_reqs) { - auto aidl_req = - ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: + auto aidl_req = ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: LeAudioConfigurationRequirement::AseDirectionRequirement(); - aidl_req.aseConfiguration.targetLatency = - static_cast<::aidl::android::hardware::bluetooth::audio:: - LeAudioAseConfiguration::TargetLatency>( + aidl_req.aseConfiguration.targetLatency = static_cast< + ::aidl::android::hardware::bluetooth::audio::LeAudioAseConfiguration::TargetLatency>( stack_req.target_latency); aidl_req.aseConfiguration.targetPhy = - static_cast<::aidl::android::hardware::bluetooth::audio::Phy>( - stack_req.target_Phy); + static_cast<::aidl::android::hardware::bluetooth::audio::Phy>(stack_req.target_Phy); // TODO(b/341936031): Add the codec enforcement mechanism in the stack // aidl_req.aseConfiguration.codecId = // GetAidlCodecIdFromStackFormat(stack_req.codecId); aidl_req.aseConfiguration.codecConfiguration = - GetAidlCodecSpecificConfigurationFromStack(stack_req.params); + GetAidlCodecSpecificConfigurationFromStack(stack_req.params); aidl_reqs.sinkAseRequirement->push_back(aidl_req); } } if (source_reqs) { - aidl_reqs - .sourceAseRequirement = std::make_optional>>(); + aidl_reqs.sourceAseRequirement = std::make_optional>>(); for (auto const& stack_req : *source_reqs) { - auto aidl_req = - ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: + auto aidl_req = ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: LeAudioConfigurationRequirement::AseDirectionRequirement(); - aidl_req.aseConfiguration.targetLatency = - static_cast<::aidl::android::hardware::bluetooth::audio:: - LeAudioAseConfiguration::TargetLatency>( + aidl_req.aseConfiguration.targetLatency = static_cast< + ::aidl::android::hardware::bluetooth::audio::LeAudioAseConfiguration::TargetLatency>( stack_req.target_latency); aidl_req.aseConfiguration.targetPhy = - static_cast<::aidl::android::hardware::bluetooth::audio::Phy>( - stack_req.target_Phy); + static_cast<::aidl::android::hardware::bluetooth::audio::Phy>(stack_req.target_Phy); // TODO(b/341936031): Add the codec enforcement mechanism in the stack // aidl_req.aseConfiguration.codecId = // GetAidlCodecIdFromStackFormat(stack_req.codecId); aidl_req.aseConfiguration.codecConfiguration = - GetAidlCodecSpecificConfigurationFromStack(stack_req.params); + GetAidlCodecSpecificConfigurationFromStack(stack_req.params); aidl_reqs.sourceAseRequirement->push_back(aidl_req); } diff --git a/system/audio_hal_interface/aidl/le_audio_utils.h b/system/audio_hal_interface/aidl/le_audio_utils.h index 22b2bfaffa7..df9d2e044e2 100644 --- a/system/audio_hal_interface/aidl/le_audio_utils.h +++ b/system/audio_hal_interface/aidl/le_audio_utils.h @@ -29,78 +29,70 @@ namespace bluetooth { namespace audio { namespace aidl { -::aidl::android::hardware::bluetooth::audio::CodecId -GetAidlCodecIdFromStackFormat( - const ::bluetooth::le_audio::types::LeAudioCodecId& codec_id); +::aidl::android::hardware::bluetooth::audio::CodecId GetAidlCodecIdFromStackFormat( + const ::bluetooth::le_audio::types::LeAudioCodecId& codec_id); ::bluetooth::le_audio::types::LeAudioCodecId GetStackCodecIdFromAidlFormat( - const ::aidl::android::hardware::bluetooth::audio::CodecId& codec_id); + const ::aidl::android::hardware::bluetooth::audio::CodecId& codec_id); -std::optional>> +std::optional>> GetAidlMetadataFromStackFormat(const std::vector& vec); bluetooth::le_audio::types::LeAudioLtvMap GetStackMetadataFromAidlFormat( - const std::vector>& source); + const std::vector>& + source); -std::optional>> +std::optional< + std::vector>> GetAidlLeAudioDeviceCapabilitiesFromStackFormat( - const std::optional< - std::vector<::bluetooth::le_audio::types::acs_ac_record>>& pacs); + const std::optional>& pacs); ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: - LeAudioBroadcastConfigurationRequirement - GetAidlLeAudioBroadcastConfigurationRequirementFromStackFormat( - const std::vector>& - subgroup_quality); + LeAudioBroadcastConfigurationRequirement + GetAidlLeAudioBroadcastConfigurationRequirementFromStackFormat( + const std::vector>& subgroup_quality); ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: - LeAudioConfigurationRequirement - GetAidlLeAudioUnicastConfigurationRequirementsFromStackFormat( - ::bluetooth::le_audio::types::LeAudioContextType context_type, - const std::optional>& - sink_reqs, - const std::optional>& - source_reqs); + LeAudioConfigurationRequirement + GetAidlLeAudioUnicastConfigurationRequirementsFromStackFormat( + ::bluetooth::le_audio::types::LeAudioContextType context_type, + const std::optional>& sink_reqs, + const std::optional>& source_reqs); ::bluetooth::le_audio::types::LeAudioLtvMap GetStackLeAudioLtvMapFromAidlFormat( - const std::vector<::aidl::android::hardware::bluetooth::audio:: - CodecSpecificConfigurationLtv>& aidl_config_ltvs); + const std::vector< + ::aidl::android::hardware::bluetooth::audio::CodecSpecificConfigurationLtv>& + aidl_config_ltvs); -::bluetooth::le_audio::broadcaster::BroadcastSubgroupBisCodecConfig -GetStackBisConfigFromAidlFormat( - const ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: - LeAudioSubgroupBisConfiguration& aidl_cfg, - ::bluetooth::le_audio::types::LeAudioCodecId& out_codec_id); +::bluetooth::le_audio::broadcaster::BroadcastSubgroupBisCodecConfig GetStackBisConfigFromAidlFormat( + const ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: + LeAudioSubgroupBisConfiguration& aidl_cfg, + ::bluetooth::le_audio::types::LeAudioCodecId& out_codec_id); std::vector<::bluetooth::le_audio::broadcaster::BroadcastSubgroupCodecConfig> GetStackSubgroupsFromAidlFormat( - const std::vector< - ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: - LeAudioBroadcastSubgroupConfiguration>& aidl_subgroups); + const std::vector<::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: + LeAudioBroadcastSubgroupConfiguration>& aidl_subgroups); -struct ::bluetooth::le_audio::types::DataPathConfiguration -GetStackDataPathFromAidlFormat( - const ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: - LeAudioDataPathConfiguration& dp); +struct ::bluetooth::le_audio::types::DataPathConfiguration GetStackDataPathFromAidlFormat( + const ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: + LeAudioDataPathConfiguration& dp); std::optional<::bluetooth::le_audio::broadcaster::BroadcastConfiguration> GetStackBroadcastConfigurationFromAidlFormat( - const ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: - LeAudioBroadcastConfigurationSetting& setting); + const ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: + LeAudioBroadcastConfigurationSetting& setting); std::optional<::bluetooth::le_audio::set_configurations::AudioSetConfiguration> GetStackUnicastConfigurationFromAidlFormat( - ::bluetooth::le_audio::types::LeAudioContextType ctx_type, - const ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: - LeAudioAseConfigurationSetting& config); + ::bluetooth::le_audio::types::LeAudioContextType ctx_type, + const ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: + LeAudioAseConfigurationSetting& config); } // namespace aidl } // namespace audio diff --git a/system/audio_hal_interface/aidl/le_audio_utils_unittest.cc b/system/audio_hal_interface/aidl/le_audio_utils_unittest.cc index 6de8059891f..8f3a1ac5f71 100644 --- a/system/audio_hal_interface/aidl/le_audio_utils_unittest.cc +++ b/system/audio_hal_interface/aidl/le_audio_utils_unittest.cc @@ -29,10 +29,9 @@ #include "btm_iso_api_types.h" namespace server_configurable_flags { -std::string GetServerConfigurableFlag( - const std::string& /* experiment_category_name */, - const std::string& /* experiment_flag_name */, - const std::string& /* default_value */) { +std::string GetServerConfigurableFlag(const std::string& /* experiment_category_name */, + const std::string& /* experiment_flag_name */, + const std::string& /* default_value */) { return ""; } } // namespace server_configurable_flags @@ -41,11 +40,9 @@ namespace bluetooth { namespace { using ::bluetooth::audio::aidl::GetAidlCodecIdFromStackFormat; -using ::bluetooth::audio::aidl:: - GetAidlLeAudioBroadcastConfigurationRequirementFromStackFormat; +using ::bluetooth::audio::aidl::GetAidlLeAudioBroadcastConfigurationRequirementFromStackFormat; using ::bluetooth::audio::aidl::GetAidlLeAudioDeviceCapabilitiesFromStackFormat; -using ::bluetooth::audio::aidl:: - GetAidlLeAudioUnicastConfigurationRequirementsFromStackFormat; +using ::bluetooth::audio::aidl::GetAidlLeAudioUnicastConfigurationRequirementsFromStackFormat; using ::bluetooth::audio::aidl::GetAidlMetadataFromStackFormat; using ::bluetooth::audio::aidl::GetStackBisConfigFromAidlFormat; using ::bluetooth::audio::aidl::GetStackBroadcastConfigurationFromAidlFormat; @@ -56,30 +53,24 @@ using ::bluetooth::audio::aidl::GetStackUnicastConfigurationFromAidlFormat; /* LC3 Core Codec: BT Stack and matching AIDL types */ static const ::bluetooth::le_audio::types::LeAudioCodecId kStackCodecLc3 = { - .coding_format = ::bluetooth::le_audio::types::kLeAudioCodingFormatLC3, - .vendor_company_id = - ::bluetooth::le_audio::types::kLeAudioVendorCompanyIdUndefined, - .vendor_codec_id = - ::bluetooth::le_audio::types::kLeAudioVendorCodecIdUndefined}; + .coding_format = ::bluetooth::le_audio::types::kLeAudioCodingFormatLC3, + .vendor_company_id = ::bluetooth::le_audio::types::kLeAudioVendorCompanyIdUndefined, + .vendor_codec_id = ::bluetooth::le_audio::types::kLeAudioVendorCodecIdUndefined}; aidl::android::hardware::bluetooth::audio::CodecId::Core kAidlCodecLc3 = - aidl::android::hardware::bluetooth::audio::CodecId::Core::LC3; + aidl::android::hardware::bluetooth::audio::CodecId::Core::LC3; /* Vendor Codec: BT Stack and matching AIDL types */ static const ::bluetooth::le_audio::types::LeAudioCodecId kStackCodecVendor1 = { - .coding_format = - ::bluetooth::le_audio::types::kLeAudioCodingFormatVendorSpecific, - .vendor_company_id = 0xC0DE, - .vendor_codec_id = 0xF00D}; -aidl::android::hardware::bluetooth::audio::CodecId::Vendor kAidlCodecVendor1{ - .id = 0xC0DE, .codecId = 0xF00D}; - -static const ::bluetooth::le_audio::types::LeAudioCodecId - kStackCodecTransparent = { + .coding_format = ::bluetooth::le_audio::types::kLeAudioCodingFormatVendorSpecific, + .vendor_company_id = 0xC0DE, + .vendor_codec_id = 0xF00D}; +aidl::android::hardware::bluetooth::audio::CodecId::Vendor kAidlCodecVendor1{.id = 0xC0DE, + .codecId = 0xF00D}; + +static const ::bluetooth::le_audio::types::LeAudioCodecId kStackCodecTransparent = { .coding_format = ::bluetooth::hci::kIsoCodingFormatTransparent, - .vendor_company_id = - ::bluetooth::le_audio::types::kLeAudioVendorCompanyIdUndefined, - .vendor_codec_id = - ::bluetooth::le_audio::types::kLeAudioVendorCodecIdUndefined}; + .vendor_company_id = ::bluetooth::le_audio::types::kLeAudioVendorCompanyIdUndefined, + .vendor_codec_id = ::bluetooth::le_audio::types::kLeAudioVendorCodecIdUndefined}; namespace test_utils { @@ -87,124 +78,101 @@ static auto PrepareStackMetadataLtv() { ::bluetooth::le_audio::types::LeAudioLtvMap metadata_ltvs; // Prepare the metadata LTVs metadata_ltvs - .Add(::bluetooth::le_audio::types:: - kLeAudioMetadataTypePreferredAudioContext, - (uint16_t)10) - .Add(::bluetooth::le_audio::types:: - kLeAudioMetadataTypeStreamingAudioContext, - (uint16_t)8) - .Add(::bluetooth::le_audio::types::kLeAudioMetadataTypeProgramInfo, - std::string{"ProgramInfo"}) - .Add(::bluetooth::le_audio::types::kLeAudioMetadataTypeLanguage, - std::string{"ice"}) - .Add(::bluetooth::le_audio::types::kLeAudioMetadataTypeCcidList, - std::vector{1, 2, 3}) - .Add(::bluetooth::le_audio::types::kLeAudioMetadataTypeparentalRating, - (uint8_t)0x01) - .Add(::bluetooth::le_audio::types::kLeAudioMetadataTypeProgramInfoUri, - std::string{"ProgramInfoUri"}) - .Add(::bluetooth::le_audio::types::kLeAudioMetadataTypeAudioActiveState, - false) - .Add(::bluetooth::le_audio::types:: - kLeAudioMetadataTypeBroadcastAudioImmediateRenderingFlag, - true) - .Add(::bluetooth::le_audio::types::kLeAudioMetadataTypeExtendedMetadata, - std::vector{1, 2, 3}) - .Add(::bluetooth::le_audio::types::kLeAudioMetadataTypeVendorSpecific, - std::vector{1, 2, 3}); + .Add(::bluetooth::le_audio::types::kLeAudioMetadataTypePreferredAudioContext, + (uint16_t)10) + .Add(::bluetooth::le_audio::types::kLeAudioMetadataTypeStreamingAudioContext, (uint16_t)8) + .Add(::bluetooth::le_audio::types::kLeAudioMetadataTypeProgramInfo, + std::string{"ProgramInfo"}) + .Add(::bluetooth::le_audio::types::kLeAudioMetadataTypeLanguage, std::string{"ice"}) + .Add(::bluetooth::le_audio::types::kLeAudioMetadataTypeCcidList, + std::vector{1, 2, 3}) + .Add(::bluetooth::le_audio::types::kLeAudioMetadataTypeparentalRating, (uint8_t)0x01) + .Add(::bluetooth::le_audio::types::kLeAudioMetadataTypeProgramInfoUri, + std::string{"ProgramInfoUri"}) + .Add(::bluetooth::le_audio::types::kLeAudioMetadataTypeAudioActiveState, false) + .Add(::bluetooth::le_audio::types:: + kLeAudioMetadataTypeBroadcastAudioImmediateRenderingFlag, + true) + .Add(::bluetooth::le_audio::types::kLeAudioMetadataTypeExtendedMetadata, + std::vector{1, 2, 3}) + .Add(::bluetooth::le_audio::types::kLeAudioMetadataTypeVendorSpecific, + std::vector{1, 2, 3}); return metadata_ltvs; } -static std::pair>, - bluetooth::le_audio::types::LeAudioLtvMap> +static std::pair< + std::vector>, + bluetooth::le_audio::types::LeAudioLtvMap> PrepareReferenceMetadata() { - std::vector< - std::optional<::aidl::android::hardware::bluetooth::audio::MetadataLtv>> - aidl_metadata; + std::vector> + aidl_metadata; bluetooth::le_audio::types::LeAudioLtvMap stack_metadata; aidl_metadata.push_back( - ::aidl::android::hardware::bluetooth::audio::MetadataLtv:: - PreferredAudioContexts{.values.bitmask = - ::aidl::android::hardware::bluetooth:: - audio::AudioContext::GAME | - ::aidl::android::hardware::bluetooth:: - audio::AudioContext::CONVERSATIONAL}); - stack_metadata.Add( - bluetooth::le_audio::types::kLeAudioMetadataTypePreferredAudioContext, - (uint16_t)((bluetooth::le_audio::types::LeAudioContextType::GAME | - bluetooth::le_audio::types::LeAudioContextType:: - CONVERSATIONAL) - .value())); + ::aidl::android::hardware::bluetooth::audio::MetadataLtv::PreferredAudioContexts{ + .values.bitmask = + ::aidl::android::hardware::bluetooth::audio::AudioContext::GAME | + ::aidl::android::hardware::bluetooth::audio::AudioContext:: + CONVERSATIONAL}); + stack_metadata.Add(bluetooth::le_audio::types::kLeAudioMetadataTypePreferredAudioContext, + (uint16_t)((bluetooth::le_audio::types::LeAudioContextType::GAME | + bluetooth::le_audio::types::LeAudioContextType::CONVERSATIONAL) + .value())); aidl_metadata.push_back( - ::aidl::android::hardware::bluetooth::audio::MetadataLtv:: - StreamingAudioContexts{.values.bitmask = ::aidl::android::hardware:: - bluetooth::audio::AudioContext::GAME}); - stack_metadata.Add( - bluetooth::le_audio::types::kLeAudioMetadataTypeStreamingAudioContext, - (uint16_t)(bluetooth::le_audio::types::LeAudioContextType::GAME)); + ::aidl::android::hardware::bluetooth::audio::MetadataLtv::StreamingAudioContexts{ + .values.bitmask = + ::aidl::android::hardware::bluetooth::audio::AudioContext::GAME}); + stack_metadata.Add(bluetooth::le_audio::types::kLeAudioMetadataTypeStreamingAudioContext, + (uint16_t)(bluetooth::le_audio::types::LeAudioContextType::GAME)); - aidl_metadata.push_back( - ::aidl::android::hardware::bluetooth::audio::MetadataLtv::VendorSpecific{ + aidl_metadata.push_back(::aidl::android::hardware::bluetooth::audio::MetadataLtv::VendorSpecific{ .companyId = 0x0201, .opaqueValue = {0x03}}); - stack_metadata.Add( - bluetooth::le_audio::types::kLeAudioMetadataTypeVendorSpecific, 0x0201, - {0x03}); + stack_metadata.Add(bluetooth::le_audio::types::kLeAudioMetadataTypeVendorSpecific, 0x0201, + {0x03}); return {aidl_metadata, stack_metadata}; } -static auto PrepareStackCapability(uint16_t capa_sampling_frequency, - uint8_t capa_frame_duration, - uint8_t audio_channel_counts, - uint16_t octets_per_frame_min, - uint16_t ocets_per_frame_max, - uint8_t codec_frames_per_sdu) { - uint32_t octets_per_frame_range = - octets_per_frame_min | (ocets_per_frame_max << 16); +static auto PrepareStackCapability(uint16_t capa_sampling_frequency, uint8_t capa_frame_duration, + uint8_t audio_channel_counts, uint16_t octets_per_frame_min, + uint16_t ocets_per_frame_max, uint8_t codec_frames_per_sdu) { + uint32_t octets_per_frame_range = octets_per_frame_min | (ocets_per_frame_max << 16); return ::bluetooth::le_audio::types::LeAudioLtvMap({ - {::bluetooth::le_audio::codec_spec_caps:: - kLeAudioLtvTypeSupportedSamplingFrequencies, - UINT16_TO_VEC_UINT8(capa_sampling_frequency)}, - {::bluetooth::le_audio::codec_spec_caps:: - kLeAudioLtvTypeSupportedFrameDurations, - UINT8_TO_VEC_UINT8(capa_frame_duration)}, - {::bluetooth::le_audio::codec_spec_caps:: - kLeAudioLtvTypeSupportedAudioChannelCounts, - UINT8_TO_VEC_UINT8(audio_channel_counts)}, - {::bluetooth::le_audio::codec_spec_caps:: - kLeAudioLtvTypeSupportedOctetsPerCodecFrame, - UINT32_TO_VEC_UINT8(octets_per_frame_range)}, - {::bluetooth::le_audio::codec_spec_caps:: - kLeAudioLtvTypeSupportedMaxCodecFramesPerSdu, - UINT8_TO_VEC_UINT8(codec_frames_per_sdu)}, + {::bluetooth::le_audio::codec_spec_caps::kLeAudioLtvTypeSupportedSamplingFrequencies, + UINT16_TO_VEC_UINT8(capa_sampling_frequency)}, + {::bluetooth::le_audio::codec_spec_caps::kLeAudioLtvTypeSupportedFrameDurations, + UINT8_TO_VEC_UINT8(capa_frame_duration)}, + {::bluetooth::le_audio::codec_spec_caps::kLeAudioLtvTypeSupportedAudioChannelCounts, + UINT8_TO_VEC_UINT8(audio_channel_counts)}, + {::bluetooth::le_audio::codec_spec_caps::kLeAudioLtvTypeSupportedOctetsPerCodecFrame, + UINT32_TO_VEC_UINT8(octets_per_frame_range)}, + {::bluetooth::le_audio::codec_spec_caps::kLeAudioLtvTypeSupportedMaxCodecFramesPerSdu, + UINT8_TO_VEC_UINT8(codec_frames_per_sdu)}, }); } -static auto PrepareStackPacRecord( - ::bluetooth::le_audio::types::LeAudioCodecId codec_id, - uint16_t capa_sampling_frequency, uint8_t capa_frame_duration, - uint8_t audio_channel_counts, uint16_t octets_per_frame_min, - uint16_t octets_per_frame_max, uint8_t codec_frames_per_sdu = 1) { - auto ltv_map = PrepareStackCapability( - capa_sampling_frequency, capa_frame_duration, audio_channel_counts, - octets_per_frame_min, octets_per_frame_max, codec_frames_per_sdu); +static auto PrepareStackPacRecord(::bluetooth::le_audio::types::LeAudioCodecId codec_id, + uint16_t capa_sampling_frequency, uint8_t capa_frame_duration, + uint8_t audio_channel_counts, uint16_t octets_per_frame_min, + uint16_t octets_per_frame_max, uint8_t codec_frames_per_sdu = 1) { + auto ltv_map = + PrepareStackCapability(capa_sampling_frequency, capa_frame_duration, audio_channel_counts, + octets_per_frame_min, octets_per_frame_max, codec_frames_per_sdu); return ::bluetooth::le_audio::types::acs_ac_record( - {.codec_id = codec_id, - .codec_spec_caps = ltv_map, - .codec_spec_caps_raw = ltv_map.RawPacket(), - .metadata = PrepareStackMetadataLtv().RawPacket()}); + {.codec_id = codec_id, + .codec_spec_caps = ltv_map, + .codec_spec_caps_raw = ltv_map.RawPacket(), + .metadata = PrepareStackMetadataLtv().RawPacket()}); } std::pair PrepareReferenceLeAudioDataPathConfigurationVendor() { - aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: - LeAudioDataPathConfiguration config; + aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider::LeAudioDataPathConfiguration + config; config.dataPathId = 0xC0DEC0DE; config.dataPathConfiguration.configuration = std::vector{0, 1, 2, 3}; @@ -216,174 +184,151 @@ PrepareReferenceLeAudioDataPathConfigurationVendor() { ::bluetooth::le_audio::types::DataPathConfiguration stack_config; stack_config.dataPathId = config.dataPathId; stack_config.dataPathConfig = *config.dataPathConfiguration.configuration; - stack_config.isoDataPathConfig.codecId = - config.isoDataPathConfiguration.isTransparent ? kStackCodecTransparent - : kStackCodecVendor1; - stack_config.isoDataPathConfig.isTransparent = - config.isoDataPathConfiguration.isTransparent; + stack_config.isoDataPathConfig.codecId = config.isoDataPathConfiguration.isTransparent + ? kStackCodecTransparent + : kStackCodecVendor1; + stack_config.isoDataPathConfig.isTransparent = config.isoDataPathConfiguration.isTransparent; stack_config.isoDataPathConfig.controllerDelayUs = - config.isoDataPathConfiguration.controllerDelayUs; - stack_config.isoDataPathConfig.configuration = - *config.isoDataPathConfiguration.configuration; + config.isoDataPathConfiguration.controllerDelayUs; + stack_config.isoDataPathConfig.configuration = *config.isoDataPathConfiguration.configuration; return {config, stack_config}; } std::pair PrepareReferenceLeAudioDataPathConfigurationLc3() { - auto config = ::aidl::android::hardware::bluetooth::audio:: - IBluetoothAudioProvider::LeAudioDataPathConfiguration{ - .dataPathId = 0x01, // kIsoDataPathPlatformDefault - // Empty vector - .dataPathConfiguration = {.configuration = {}}, - .isoDataPathConfiguration = - { - .codecId = kAidlCodecLc3, - // Transparent - the controller does not encode/decode - .isTransparent = true, - // Irrelevant for the transparent ISO data path - .controllerDelayUs = 0, - // Empty for LC3 codec - .configuration = std::nullopt, - }, - }; + auto config = ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: + LeAudioDataPathConfiguration{ + .dataPathId = 0x01, // kIsoDataPathPlatformDefault + // Empty vector + .dataPathConfiguration = {.configuration = {}}, + .isoDataPathConfiguration = + { + .codecId = kAidlCodecLc3, + // Transparent - the controller does not encode/decode + .isTransparent = true, + // Irrelevant for the transparent ISO data path + .controllerDelayUs = 0, + // Empty for LC3 codec + .configuration = std::nullopt, + }, + }; ::bluetooth::le_audio::types::DataPathConfiguration stack_config; stack_config.dataPathId = config.dataPathId; stack_config.dataPathConfig = *config.dataPathConfiguration.configuration; stack_config.isoDataPathConfig.codecId = - config.isoDataPathConfiguration.isTransparent ? kStackCodecTransparent - : kStackCodecLc3; - stack_config.isoDataPathConfig.isTransparent = - config.isoDataPathConfiguration.isTransparent; + config.isoDataPathConfiguration.isTransparent ? kStackCodecTransparent : kStackCodecLc3; + stack_config.isoDataPathConfig.isTransparent = config.isoDataPathConfiguration.isTransparent; stack_config.isoDataPathConfig.controllerDelayUs = - config.isoDataPathConfiguration.controllerDelayUs; - stack_config.isoDataPathConfig.configuration = - *config.isoDataPathConfiguration.configuration; + config.isoDataPathConfiguration.controllerDelayUs; + stack_config.isoDataPathConfig.configuration = *config.isoDataPathConfiguration.configuration; return {config, stack_config}; } std::pair<::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: - LeAudioAseQosConfiguration, + LeAudioAseQosConfiguration, bluetooth::le_audio::set_configurations::QosConfigSetting> PrepareReferenceQosConfiguration(bool is_low_latency) { - ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: - LeAudioAseQosConfiguration aidl_ase_config = ::aidl::android::hardware:: - bluetooth::audio::IBluetoothAudioProvider::LeAudioAseQosConfiguration{ - .sduIntervalUs = 10000, - .framing = ::aidl::android::hardware::bluetooth::audio:: - IBluetoothAudioProvider::Framing::UNFRAMED, - .phy = {::aidl::android::hardware::bluetooth::audio::Phy::TWO_M}, - .maxTransportLatencyMs = 10, // Preferred max transport latency - .maxSdu = 120, - .retransmissionNum = 2, - }; + ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider::LeAudioAseQosConfiguration + aidl_ase_config = ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: + LeAudioAseQosConfiguration{ + .sduIntervalUs = 10000, + .framing = ::aidl::android::hardware::bluetooth::audio:: + IBluetoothAudioProvider::Framing::UNFRAMED, + .phy = {::aidl::android::hardware::bluetooth::audio::Phy::TWO_M}, + .maxTransportLatencyMs = 10, // Preferred max transport latency + .maxSdu = 120, + .retransmissionNum = 2, + }; bluetooth::le_audio::set_configurations::QosConfigSetting stack_ase_config = { - .target_latency = is_low_latency - ? bluetooth::le_audio::types::kTargetLatencyLower - : bluetooth::le_audio::types:: - kTargetLatencyBalancedLatencyReliability, - .retransmission_number = 2, - .max_transport_latency = 10, - .sduIntervalUs = 10000, - .maxSdu = 120, + .target_latency = + is_low_latency + ? bluetooth::le_audio::types::kTargetLatencyLower + : bluetooth::le_audio::types::kTargetLatencyBalancedLatencyReliability, + .retransmission_number = 2, + .max_transport_latency = 10, + .sduIntervalUs = 10000, + .maxSdu = 120, }; return {aidl_ase_config, stack_ase_config}; } -std::pair, +std::pair, ::bluetooth::le_audio::types::LeAudioLtvMap> -PrepareReferenceCodecSpecificConfigurationLc3(bool is_low_latency, bool is_left, - bool is_right) { +PrepareReferenceCodecSpecificConfigurationLc3(bool is_low_latency, bool is_left, bool is_right) { ::bluetooth::le_audio::types::LeAudioLtvMap stack_params; - std::vector<::aidl::android::hardware::bluetooth::audio:: - CodecSpecificConfigurationLtv> - aidl_params; + std::vector<::aidl::android::hardware::bluetooth::audio::CodecSpecificConfigurationLtv> + aidl_params; aidl_params.push_back( - is_low_latency - ? ::aidl::android::hardware::bluetooth::audio:: - CodecSpecificConfigurationLtv::SamplingFrequency::HZ24000 - : ::aidl::android::hardware::bluetooth::audio:: - CodecSpecificConfigurationLtv::SamplingFrequency::HZ48000); + is_low_latency ? ::aidl::android::hardware::bluetooth::audio:: + CodecSpecificConfigurationLtv::SamplingFrequency::HZ24000 + : ::aidl::android::hardware::bluetooth::audio:: + CodecSpecificConfigurationLtv::SamplingFrequency::HZ48000); stack_params.Add( - le_audio::codec_spec_conf::kLeAudioLtvTypeSamplingFreq, - (uint8_t)(is_low_latency - ? le_audio::codec_spec_conf::kLeAudioSamplingFreq24000Hz - : le_audio::codec_spec_conf::kLeAudioSamplingFreq48000Hz)); + le_audio::codec_spec_conf::kLeAudioLtvTypeSamplingFreq, + (uint8_t)(is_low_latency ? le_audio::codec_spec_conf::kLeAudioSamplingFreq24000Hz + : le_audio::codec_spec_conf::kLeAudioSamplingFreq48000Hz)); aidl_params.push_back( - ::aidl::android::hardware::bluetooth::audio:: - CodecSpecificConfigurationLtv::AudioChannelAllocation{ - .bitmask = (is_left ? ::aidl::android::hardware::bluetooth:: - audio::CodecSpecificConfigurationLtv:: - AudioChannelAllocation::FRONT_LEFT - : 0) | - (is_right ? ::aidl::android::hardware::bluetooth:: - audio::CodecSpecificConfigurationLtv:: - AudioChannelAllocation::FRONT_RIGHT - : 0)}); + ::aidl::android::hardware::bluetooth::audio::CodecSpecificConfigurationLtv:: + AudioChannelAllocation{ + .bitmask = (is_left ? ::aidl::android::hardware::bluetooth::audio:: + CodecSpecificConfigurationLtv:: + AudioChannelAllocation::FRONT_LEFT + : 0) | + (is_right ? ::aidl::android::hardware::bluetooth::audio:: + CodecSpecificConfigurationLtv:: + AudioChannelAllocation::FRONT_RIGHT + : 0)}); stack_params.Add( - le_audio::codec_spec_conf::kLeAudioLtvTypeAudioChannelAllocation, - (uint32_t)((is_left ? le_audio::codec_spec_conf::kLeAudioLocationFrontLeft - : 0) | - (is_right - ? le_audio::codec_spec_conf::kLeAudioLocationFrontRight - : 0))); + le_audio::codec_spec_conf::kLeAudioLtvTypeAudioChannelAllocation, + (uint32_t)((is_left ? le_audio::codec_spec_conf::kLeAudioLocationFrontLeft : 0) | + (is_right ? le_audio::codec_spec_conf::kLeAudioLocationFrontRight : 0))); - aidl_params.push_back( - ::aidl::android::hardware::bluetooth::audio:: - CodecSpecificConfigurationLtv::FrameDuration::US7500); - stack_params.Add( - le_audio::codec_spec_conf::kLeAudioLtvTypeFrameDuration, - (uint8_t)le_audio::codec_spec_conf::kLeAudioCodecFrameDur7500us); + aidl_params.push_back(::aidl::android::hardware::bluetooth::audio::CodecSpecificConfigurationLtv:: + FrameDuration::US7500); + stack_params.Add(le_audio::codec_spec_conf::kLeAudioLtvTypeFrameDuration, + (uint8_t)le_audio::codec_spec_conf::kLeAudioCodecFrameDur7500us); - aidl_params.push_back( - ::aidl::android::hardware::bluetooth::audio:: - CodecSpecificConfigurationLtv::CodecFrameBlocksPerSDU{.value = 1}); - stack_params.Add( - le_audio::codec_spec_conf::kLeAudioLtvTypeCodecFrameBlocksPerSdu, - (uint8_t)1); + aidl_params.push_back(::aidl::android::hardware::bluetooth::audio::CodecSpecificConfigurationLtv:: + CodecFrameBlocksPerSDU{.value = 1}); + stack_params.Add(le_audio::codec_spec_conf::kLeAudioLtvTypeCodecFrameBlocksPerSdu, (uint8_t)1); // TODO: Verify these values with the standard 48kHz and 24kHz configs sets - aidl_params.push_back(::aidl::android::hardware::bluetooth::audio:: - CodecSpecificConfigurationLtv::OctetsPerCodecFrame{ - .value = is_low_latency ? 80 : 120}); - stack_params.Add( - le_audio::codec_spec_conf::kLeAudioLtvTypeOctetsPerCodecFrame, - (uint16_t)(is_low_latency ? 80 : 120)); + aidl_params.push_back(::aidl::android::hardware::bluetooth::audio::CodecSpecificConfigurationLtv:: + OctetsPerCodecFrame{.value = is_low_latency ? 80 : 120}); + stack_params.Add(le_audio::codec_spec_conf::kLeAudioLtvTypeOctetsPerCodecFrame, + (uint16_t)(is_low_latency ? 80 : 120)); return {aidl_params, stack_params}; } std::pair<::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: - LeAudioAseConfigurationSetting::AseDirectionConfiguration, + LeAudioAseConfigurationSetting::AseDirectionConfiguration, ::bluetooth::le_audio::set_configurations::AseConfiguration> -PrepareReferenceAseDirectionConfigLc3(bool is_left, bool is_right, - bool is_low_latency, bool has_qos = true, - bool has_datapath = true) { +PrepareReferenceAseDirectionConfigLc3(bool is_left, bool is_right, bool is_low_latency, + bool has_qos = true, bool has_datapath = true) { ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: - LeAudioAseConfigurationSetting::AseDirectionConfiguration aidl_ase_config; + LeAudioAseConfigurationSetting::AseDirectionConfiguration aidl_ase_config; ::bluetooth::le_audio::set_configurations::CodecConfigSetting stack_codec; - ::bluetooth::le_audio::set_configurations::AseConfiguration stack_ase_config( - stack_codec); + ::bluetooth::le_audio::set_configurations::AseConfiguration stack_ase_config(stack_codec); aidl_ase_config.aseConfiguration.targetLatency = - is_low_latency ? ::aidl::android::hardware::bluetooth::audio:: - LeAudioAseConfiguration::TargetLatency::LOWER - : ::aidl::android::hardware::bluetooth::audio:: - LeAudioAseConfiguration::TargetLatency:: - BALANCED_LATENCY_RELIABILITY; + is_low_latency ? ::aidl::android::hardware::bluetooth::audio::LeAudioAseConfiguration:: + TargetLatency::LOWER + : ::aidl::android::hardware::bluetooth::audio::LeAudioAseConfiguration:: + TargetLatency::BALANCED_LATENCY_RELIABILITY; /* Default Phy */ aidl_ase_config.aseConfiguration.targetPhy = - ::aidl::android::hardware::bluetooth::audio::Phy::TWO_M; + ::aidl::android::hardware::bluetooth::audio::Phy::TWO_M; // Note: Phy parameter is selected by the BT stack based on the remote support // Phy parameter from the AIDL is considered as a suggestion @@ -393,8 +338,7 @@ PrepareReferenceAseDirectionConfigLc3(bool is_left, bool is_right, /* Default Codec Parameters */ auto [aidl_params, stack_params] = - PrepareReferenceCodecSpecificConfigurationLc3(is_low_latency, is_left, - is_right); + PrepareReferenceCodecSpecificConfigurationLc3(is_low_latency, is_left, is_right); aidl_ase_config.aseConfiguration.codecConfiguration = aidl_params; stack_ase_config.codec.params = stack_params; @@ -408,13 +352,11 @@ PrepareReferenceAseDirectionConfigLc3(bool is_left, bool is_right, auto stack_codec_params = stack_params.GetAsCoreCodecConfig(); stack_ase_config.codec.channel_count_per_iso_stream = - std::bitset<32>(stack_codec_params.audio_channel_allocation.value_or(1)) - .count(); + std::bitset<32>(stack_codec_params.audio_channel_allocation.value_or(1)).count(); /* QoS configuration */ if (has_qos) { - auto [aidl_qos_config, stack_qos_config] = - PrepareReferenceQosConfiguration(is_low_latency); + auto [aidl_qos_config, stack_qos_config] = PrepareReferenceQosConfiguration(is_low_latency); aidl_ase_config.qosConfiguration = aidl_qos_config; stack_ase_config.qos = stack_qos_config; } @@ -422,7 +364,7 @@ PrepareReferenceAseDirectionConfigLc3(bool is_left, bool is_right, /* Data path configuration */ if (has_datapath) { auto [aidl_datapath_config, stack_datapath_config] = - PrepareReferenceLeAudioDataPathConfigurationLc3(); + PrepareReferenceLeAudioDataPathConfigurationLc3(); aidl_ase_config.dataPathConfiguration = aidl_datapath_config; stack_ase_config.data_path_configuration = stack_datapath_config; } @@ -431,37 +373,35 @@ PrepareReferenceAseDirectionConfigLc3(bool is_left, bool is_right, } std::pair<::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: - LeAudioAseConfigurationSetting, + LeAudioAseConfigurationSetting, ::bluetooth::le_audio::set_configurations::AudioSetConfiguration> -PrepareReferenceAseConfigurationSetting( - ::bluetooth::le_audio::types::LeAudioContextType ctx_type, - bool has_source = false) { +PrepareReferenceAseConfigurationSetting(::bluetooth::le_audio::types::LeAudioContextType ctx_type, + bool has_source = false) { // Prepare the AIDL format config ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: - LeAudioAseConfigurationSetting aidl_audio_set_config; - ::bluetooth::le_audio::set_configurations::AudioSetConfiguration - stack_audio_set_config; + LeAudioAseConfigurationSetting aidl_audio_set_config; + ::bluetooth::le_audio::set_configurations::AudioSetConfiguration stack_audio_set_config; aidl_audio_set_config.audioContext.bitmask = (uint16_t)ctx_type; // Packing // AIDL: - aidl_audio_set_config.packing = ::aidl::android::hardware::bluetooth::audio:: - IBluetoothAudioProvider::Packing::SEQUENTIAL; + aidl_audio_set_config.packing = + ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider::Packing::SEQUENTIAL; // STACK: stack_audio_set_config.packing = bluetooth::hci::kIsoCigPackingSequential; /* Stereo playback - Two sink ASES */ if (!aidl_audio_set_config.sinkAseConfiguration) { log::error("Has no sink container"); - aidl_audio_set_config.sinkAseConfiguration = std::vector>(); + aidl_audio_set_config.sinkAseConfiguration = std::vector< + std::optional<::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: + LeAudioAseConfigurationSetting::AseDirectionConfiguration>>(); } // Left ASE config auto [aidl_ase_config_left, stack_ase_config_left] = - PrepareReferenceAseDirectionConfigLc3(true, false, false); + PrepareReferenceAseDirectionConfigLc3(true, false, false); // AIDL: aidl_audio_set_config.sinkAseConfiguration->push_back(aidl_ase_config_left); // STACK: @@ -469,7 +409,7 @@ PrepareReferenceAseConfigurationSetting( // Right ASE config auto [aidl_ase_config_right, stack_ase_config_right] = - PrepareReferenceAseDirectionConfigLc3(false, true, false); + PrepareReferenceAseDirectionConfigLc3(false, true, false); // AIDL: aidl_audio_set_config.sinkAseConfiguration->push_back(aidl_ase_config_right); // STACK: @@ -478,29 +418,25 @@ PrepareReferenceAseConfigurationSetting( // Config Flags // AIDL: aidl_audio_set_config.flags->bitmask = - ::aidl::android::hardware::bluetooth::audio::ConfigurationFlags:: - SPATIAL_AUDIO | - ::aidl::android::hardware::bluetooth::audio::ConfigurationFlags:: - LOW_LATENCY | - ::aidl::android::hardware::bluetooth::audio::ConfigurationFlags:: - ALLOW_ASYMMETRIC_CONFIGURATIONS | - ::aidl::android::hardware::bluetooth::audio::ConfigurationFlags:: - MONO_MIC_CONFIGURATION; + ::aidl::android::hardware::bluetooth::audio::ConfigurationFlags::SPATIAL_AUDIO | + ::aidl::android::hardware::bluetooth::audio::ConfigurationFlags::LOW_LATENCY | + ::aidl::android::hardware::bluetooth::audio::ConfigurationFlags:: + ALLOW_ASYMMETRIC_CONFIGURATIONS | + ::aidl::android::hardware::bluetooth::audio::ConfigurationFlags::MONO_MIC_CONFIGURATION; /* Low latency, mono microphone - Single source ASE */ if (has_source) { if (!aidl_audio_set_config.sourceAseConfiguration) { log::error("Has no source container"); - aidl_audio_set_config.sourceAseConfiguration = std::vector>(); + aidl_audio_set_config.sourceAseConfiguration = std::vector< + std::optional<::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: + LeAudioAseConfigurationSetting::AseDirectionConfiguration>>(); } auto [aidl_ase_config_source, stack_ase_config_source] = - PrepareReferenceAseDirectionConfigLc3(true, true, true); + PrepareReferenceAseDirectionConfigLc3(true, true, true); // AIDL: - aidl_audio_set_config.sourceAseConfiguration->push_back( - aidl_ase_config_source); + aidl_audio_set_config.sourceAseConfiguration->push_back(aidl_ase_config_source); // STACK: stack_audio_set_config.confs.source.push_back(stack_ase_config_source); } @@ -509,15 +445,14 @@ PrepareReferenceAseConfigurationSetting( } std::pair<::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: - LeAudioSubgroupBisConfiguration, + LeAudioSubgroupBisConfiguration, ::bluetooth::le_audio::broadcaster::BroadcastSubgroupBisCodecConfig> PrepareReferenceBisConfiguration() { ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: - LeAudioSubgroupBisConfiguration aidl_cfg; + LeAudioSubgroupBisConfiguration aidl_cfg; auto [aidl_codec_spec, stack_codec_spec] = - test_utils::PrepareReferenceCodecSpecificConfigurationLc3(true, true, - true); + test_utils::PrepareReferenceCodecSpecificConfigurationLc3(true, true, true); auto [aidl_metadata, stack_metadata] = test_utils::PrepareReferenceMetadata(); @@ -529,98 +464,92 @@ PrepareReferenceBisConfiguration() { // TODO: Add metadata support at the BIS level ::bluetooth::le_audio::broadcaster::BroadcastSubgroupBisCodecConfig stack_cfg( - aidl_cfg.numBis, 1, stack_codec_spec, std::vector{0x02, 0x03}); + aidl_cfg.numBis, 1, stack_codec_spec, std::vector{0x02, 0x03}); return {aidl_cfg, stack_cfg}; } -std::pair< - std::vector< - ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: - LeAudioBroadcastSubgroupConfiguration>, - std::vector< - ::bluetooth::le_audio::broadcaster::BroadcastSubgroupCodecConfig>> +std::pair, + std::vector<::bluetooth::le_audio::broadcaster::BroadcastSubgroupCodecConfig>> PrepareReferenceBroadcastSubgroups() { - std::vector< - ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: - LeAudioBroadcastSubgroupConfiguration> - aidl_subgroups; - std::vector<::bluetooth::le_audio::broadcaster::BroadcastSubgroupCodecConfig> - stack_subgroups; + std::vector<::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: + LeAudioBroadcastSubgroupConfiguration> + aidl_subgroups; + std::vector<::bluetooth::le_audio::broadcaster::BroadcastSubgroupCodecConfig> stack_subgroups; auto [aidl_left_params, stack_left_params] = - PrepareReferenceCodecSpecificConfigurationLc3(false, true, false); + PrepareReferenceCodecSpecificConfigurationLc3(false, true, false); auto [aidl_right_params, stack_right_params] = - PrepareReferenceCodecSpecificConfigurationLc3(false, false, true); + PrepareReferenceCodecSpecificConfigurationLc3(false, false, true); ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: - LeAudioBroadcastSubgroupConfiguration aidl_subgroup{ - .bisConfigurations = - {::aidl::android::hardware::bluetooth::audio:: - IBluetoothAudioProvider::LeAudioSubgroupBisConfiguration{ - .numBis = 1, - .bisConfiguration = - { - .codecId = kAidlCodecLc3, - .codecConfiguration = aidl_left_params, - .vendorCodecConfiguration = - {}, // no vendor codec config - // The stack does not yet support - // metadata at BIS config level - .metadata = std::nullopt, - }, - }, - ::aidl::android::hardware::bluetooth::audio:: - IBluetoothAudioProvider::LeAudioSubgroupBisConfiguration{ - .numBis = 1, - .bisConfiguration = - { - .codecId = kAidlCodecLc3, - .codecConfiguration = aidl_right_params, - .vendorCodecConfiguration = - {}, // no vendor codec config - // The stack does not yet support - // metadata at BIS config level - .metadata = std::nullopt, - }, - }}, - .vendorCodecConfiguration = std::nullopt, - }; + LeAudioBroadcastSubgroupConfiguration aidl_subgroup{ + .bisConfigurations = + {::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: + LeAudioSubgroupBisConfiguration{ + .numBis = 1, + .bisConfiguration = + { + .codecId = kAidlCodecLc3, + .codecConfiguration = aidl_left_params, + .vendorCodecConfiguration = + {}, // no vendor codec config + // The stack does not yet + // support metadata at BIS + // config level + .metadata = std::nullopt, + }, + }, + ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: + LeAudioSubgroupBisConfiguration{ + .numBis = 1, + .bisConfiguration = + { + .codecId = kAidlCodecLc3, + .codecConfiguration = aidl_right_params, + .vendorCodecConfiguration = + {}, // no vendor codec config + // The stack does not yet + // support metadata at BIS + // config level + .metadata = std::nullopt, + }, + }}, + .vendorCodecConfiguration = std::nullopt, + }; aidl_subgroups.push_back(aidl_subgroup); - ::bluetooth::le_audio::broadcaster::BroadcastSubgroupCodecConfig - stack_subgroup(kStackCodecLc3, - {le_audio::broadcaster::BroadcastSubgroupBisCodecConfig( - 1, 1, stack_left_params, std::nullopt), - le_audio::broadcaster::BroadcastSubgroupBisCodecConfig( - 1, 1, stack_right_params, std::nullopt)}, - 16, std::nullopt); + ::bluetooth::le_audio::broadcaster::BroadcastSubgroupCodecConfig stack_subgroup( + kStackCodecLc3, + {le_audio::broadcaster::BroadcastSubgroupBisCodecConfig(1, 1, stack_left_params, + std::nullopt), + le_audio::broadcaster::BroadcastSubgroupBisCodecConfig(1, 1, stack_right_params, + std::nullopt)}, + 16, std::nullopt); stack_subgroups.push_back(stack_subgroup); return {aidl_subgroups, stack_subgroups}; } -::bluetooth::le_audio::broadcaster::BroadcastQosConfig -PrepareStackBroadcastQosConfig(uint8_t rtn = 2, - uint16_t max_transport_latency = 50) { - ::bluetooth::le_audio::broadcaster::BroadcastQosConfig qos( - rtn, max_transport_latency); +::bluetooth::le_audio::broadcaster::BroadcastQosConfig PrepareStackBroadcastQosConfig( + uint8_t rtn = 2, uint16_t max_transport_latency = 50) { + ::bluetooth::le_audio::broadcaster::BroadcastQosConfig qos(rtn, max_transport_latency); return qos; } std::pair<::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: - LeAudioBroadcastConfigurationSetting, + LeAudioBroadcastConfigurationSetting, ::bluetooth::le_audio::broadcaster::BroadcastConfiguration> PrepareReferenceBroadcastConfigurationLc3() { ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: - LeAudioBroadcastConfigurationSetting aidl_config; + LeAudioBroadcastConfigurationSetting aidl_config; auto [aidl_datapath_config, stack_datapath_config] = - PrepareReferenceLeAudioDataPathConfigurationLc3(); + PrepareReferenceLeAudioDataPathConfigurationLc3(); - auto [aidl_bis_subgroups, stack_bis_subgroups] = - test_utils::PrepareReferenceBroadcastSubgroups(); + auto [aidl_bis_subgroups, stack_bis_subgroups] = test_utils::PrepareReferenceBroadcastSubgroups(); aidl_config.dataPathConfiguration = aidl_datapath_config; aidl_config.sduIntervalUs = 10000; @@ -629,196 +558,171 @@ PrepareReferenceBroadcastConfigurationLc3() { aidl_config.maxTransportLatencyMs = 100; aidl_config.retransmitionNum = 4; aidl_config.phy = {::aidl::android::hardware::bluetooth::audio::Phy::TWO_M}; - aidl_config.packing = ::aidl::android::hardware::bluetooth::audio:: - IBluetoothAudioProvider::Packing::SEQUENTIAL; - aidl_config.framing = ::aidl::android::hardware::bluetooth::audio:: - IBluetoothAudioProvider::Framing::UNFRAMED; + aidl_config.packing = + ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider::Packing::SEQUENTIAL; + aidl_config.framing = + ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider::Framing::UNFRAMED; aidl_config.subgroupsConfigurations = aidl_bis_subgroups; ::bluetooth::le_audio::broadcaster::BroadcastConfiguration stack_config = { - .subgroups = stack_bis_subgroups, - .qos = PrepareStackBroadcastQosConfig(aidl_config.retransmitionNum, - aidl_config.maxTransportLatencyMs), - .data_path = stack_datapath_config, - .sduIntervalUs = 10000, - .maxSduOctets = 120, - .phy = hci::kIsoCigPhy2M, - .packing = bluetooth::hci::kIsoCigPackingSequential, - .framing = hci::kIsoCigFramingUnframed, + .subgroups = stack_bis_subgroups, + .qos = PrepareStackBroadcastQosConfig(aidl_config.retransmitionNum, + aidl_config.maxTransportLatencyMs), + .data_path = stack_datapath_config, + .sduIntervalUs = 10000, + .maxSduOctets = 120, + .phy = hci::kIsoCigPhy2M, + .packing = bluetooth::hci::kIsoCigPackingSequential, + .framing = hci::kIsoCigFramingUnframed, }; return {aidl_config, stack_config}; } std::pair<::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: - LeAudioBroadcastConfigurationRequirement, - const std::vector>> + LeAudioBroadcastConfigurationRequirement, + const std::vector>> PrepareReferenceBroadcastRequirements() { ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: - LeAudioBroadcastConfigurationRequirement aidl_requirements; - std::vector< - std::pair<::bluetooth::le_audio::types::LeAudioContextType, uint8_t>> - stack_requirements; - - std::pair<::bluetooth::le_audio::types::LeAudioContextType, uint8_t> - stack_req = std::make_pair(le_audio::types::LeAudioContextType::MEDIA, - le_audio::QUALITY_HIGH); + LeAudioBroadcastConfigurationRequirement aidl_requirements; + std::vector> + stack_requirements; + + std::pair<::bluetooth::le_audio::types::LeAudioContextType, uint8_t> stack_req = + std::make_pair(le_audio::types::LeAudioContextType::MEDIA, le_audio::QUALITY_HIGH); ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: - LeAudioBroadcastSubgroupConfigurationRequirement aidl_req = { - .audioContext.bitmask = - (int)le_audio::types::LeAudioContextType::MEDIA, - .quality = ::aidl::android::hardware::bluetooth::audio:: - IBluetoothAudioProvider::BroadcastQuality::HIGH, - // TODO: Currently there is no equivalent of this in the stack data - // format - .bisNumPerSubgroup = 2, - }; + LeAudioBroadcastSubgroupConfigurationRequirement aidl_req = { + .audioContext.bitmask = (int)le_audio::types::LeAudioContextType::MEDIA, + .quality = ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: + BroadcastQuality::HIGH, + // TODO: Currently there is no equivalent of this in the stack data + // format + .bisNumPerSubgroup = 2, + }; aidl_requirements.subgroupConfigurationRequirements.push_back(aidl_req); stack_requirements.push_back(stack_req); return {aidl_requirements, stack_requirements}; } -static std::pair< - ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: - LeAudioConfigurationRequirement::AseDirectionRequirement, - ::bluetooth::le_audio::CodecManager::UnicastConfigurationRequirements:: - DeviceDirectionRequirements> -PrepareReferenceDirectionRequirements(int32_t aidl_location, - uint32_t stack_location) { - ::bluetooth::le_audio::CodecManager::UnicastConfigurationRequirements:: - DeviceDirectionRequirements stack_req; +static std::pair<::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: + LeAudioConfigurationRequirement::AseDirectionRequirement, + ::bluetooth::le_audio::CodecManager::UnicastConfigurationRequirements:: + DeviceDirectionRequirements> +PrepareReferenceDirectionRequirements(int32_t aidl_location, uint32_t stack_location) { + ::bluetooth::le_audio::CodecManager::UnicastConfigurationRequirements::DeviceDirectionRequirements + stack_req; ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: - LeAudioConfigurationRequirement::AseDirectionRequirement aidl_req; + LeAudioConfigurationRequirement::AseDirectionRequirement aidl_req; // Target latency - stack_req.target_latency = - ::bluetooth::le_audio::types::kTargetLatencyBalancedLatencyReliability; - aidl_req.aseConfiguration.targetLatency = - aidl::android::hardware::bluetooth::audio::LeAudioAseConfiguration:: - TargetLatency::BALANCED_LATENCY_RELIABILITY; + stack_req.target_latency = ::bluetooth::le_audio::types::kTargetLatencyBalancedLatencyReliability; + aidl_req.aseConfiguration.targetLatency = aidl::android::hardware::bluetooth::audio:: + LeAudioAseConfiguration::TargetLatency::BALANCED_LATENCY_RELIABILITY; // PHY stack_req.target_Phy = ::bluetooth::le_audio::types::kTargetPhy2M; - aidl_req.aseConfiguration.targetPhy = - aidl::android::hardware::bluetooth::audio::Phy::TWO_M; + aidl_req.aseConfiguration.targetPhy = aidl::android::hardware::bluetooth::audio::Phy::TWO_M; // Sampling frequency - stack_req.params.Add(le_audio::codec_spec_conf::kLeAudioLtvTypeSamplingFreq, - (uint8_t)::bluetooth::le_audio::codec_spec_conf:: - kLeAudioSamplingFreq32000Hz); + stack_req.params.Add( + le_audio::codec_spec_conf::kLeAudioLtvTypeSamplingFreq, + (uint8_t)::bluetooth::le_audio::codec_spec_conf::kLeAudioSamplingFreq32000Hz); aidl_req.aseConfiguration.codecConfiguration.push_back( - ::aidl::android::hardware::bluetooth::audio:: - CodecSpecificConfigurationLtv::SamplingFrequency::HZ32000); + ::aidl::android::hardware::bluetooth::audio::CodecSpecificConfigurationLtv:: + SamplingFrequency::HZ32000); // Frame duration stack_req.params.Add( - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLtvTypeFrameDuration, - (uint8_t)::bluetooth::le_audio::codec_spec_conf:: - kLeAudioCodecFrameDur10000us); + ::bluetooth::le_audio::codec_spec_conf::kLeAudioLtvTypeFrameDuration, + (uint8_t)::bluetooth::le_audio::codec_spec_conf::kLeAudioCodecFrameDur10000us); aidl_req.aseConfiguration.codecConfiguration.push_back( - ::aidl::android::hardware::bluetooth::audio:: - CodecSpecificConfigurationLtv::FrameDuration::US10000); + ::aidl::android::hardware::bluetooth::audio::CodecSpecificConfigurationLtv:: + FrameDuration::US10000); // Codec frame Blocks per SDU - stack_req.params.Add(::bluetooth::le_audio::codec_spec_conf:: - kLeAudioLtvTypeCodecFrameBlocksPerSdu, - (uint8_t)1); + stack_req.params.Add( + ::bluetooth::le_audio::codec_spec_conf::kLeAudioLtvTypeCodecFrameBlocksPerSdu, + (uint8_t)1); aidl_req.aseConfiguration.codecConfiguration.push_back( - ::aidl::android::hardware::bluetooth::audio:: - CodecSpecificConfigurationLtv::CodecFrameBlocksPerSDU{.value = 1}); + ::aidl::android::hardware::bluetooth::audio::CodecSpecificConfigurationLtv:: + CodecFrameBlocksPerSDU{.value = 1}); // Audio channel allocation - stack_req.params.Add(::bluetooth::le_audio::codec_spec_conf:: - kLeAudioLtvTypeAudioChannelAllocation, - (uint32_t)stack_location); + stack_req.params.Add( + ::bluetooth::le_audio::codec_spec_conf::kLeAudioLtvTypeAudioChannelAllocation, + (uint32_t)stack_location); aidl_req.aseConfiguration.codecConfiguration.push_back( - ::aidl::android::hardware::bluetooth::audio:: - CodecSpecificConfigurationLtv::AudioChannelAllocation{ - .bitmask = aidl_location}); + ::aidl::android::hardware::bluetooth::audio::CodecSpecificConfigurationLtv:: + AudioChannelAllocation{.bitmask = aidl_location}); return {aidl_req, stack_req}; } } // namespace test_utils -TEST(BluetoothAudioClientInterfaceAidlTest, - testGetAidlCodecIdFromStackFormatLc3) { +TEST(BluetoothAudioClientInterfaceAidlTest, testGetAidlCodecIdFromStackFormatLc3) { /* Verify LC3 core codec */ auto aidl_codec = GetAidlCodecIdFromStackFormat(kStackCodecLc3); - ASSERT_EQ(aidl_codec.getTag(), - aidl::android::hardware::bluetooth::audio::CodecId::core); - ASSERT_EQ( - aidl_codec - .get(), - kAidlCodecLc3); + ASSERT_EQ(aidl_codec.getTag(), aidl::android::hardware::bluetooth::audio::CodecId::core); + ASSERT_EQ(aidl_codec.get(), + kAidlCodecLc3); } -TEST(BluetoothAudioClientInterfaceAidlTest, - testGetAidlCodecIdFromStackFormatVendor1) { +TEST(BluetoothAudioClientInterfaceAidlTest, testGetAidlCodecIdFromStackFormatVendor1) { /* Verify vendor codec */ auto aidl_codec = GetAidlCodecIdFromStackFormat(kStackCodecVendor1); - ASSERT_EQ(aidl_codec.getTag(), - aidl::android::hardware::bluetooth::audio::CodecId::vendor); - ASSERT_EQ( - aidl_codec - .get(), - kAidlCodecVendor1); + ASSERT_EQ(aidl_codec.getTag(), aidl::android::hardware::bluetooth::audio::CodecId::vendor); + ASSERT_EQ(aidl_codec.get(), + kAidlCodecVendor1); } -TEST(BluetoothAudioClientInterfaceAidlTest, - testGetStackCodecIdFromAidlFormatLc3) { +TEST(BluetoothAudioClientInterfaceAidlTest, testGetStackCodecIdFromAidlFormatLc3) { /* Verify LC3 core codec */ auto stack_codec = GetStackCodecIdFromAidlFormat(kAidlCodecLc3); ASSERT_EQ(stack_codec, kStackCodecLc3); } -TEST(BluetoothAudioClientInterfaceAidlTest, - testGetStackCodecIdFromAidlFormatVendor1) { +TEST(BluetoothAudioClientInterfaceAidlTest, testGetStackCodecIdFromAidlFormatVendor1) { /* Verify vendor codec */ auto stack_codec = GetStackCodecIdFromAidlFormat(kAidlCodecVendor1); ASSERT_EQ(stack_codec, kStackCodecVendor1); } static void verifyMetadata( - const std::optional< - ::aidl::android::hardware::bluetooth::audio::MetadataLtv>& aidl_meta, - const ::bluetooth::le_audio::types::LeAudioMetadata& stack_meta, - bool& matched_preferredAudioContexts, bool& matched_streamingAudioContexts, - bool& matched_vendorSpecific) { - if (aidl_meta->getTag() == ::aidl::android::hardware::bluetooth::audio:: - MetadataLtv::preferredAudioContexts) { + const std::optional<::aidl::android::hardware::bluetooth::audio::MetadataLtv>& aidl_meta, + const ::bluetooth::le_audio::types::LeAudioMetadata& stack_meta, + bool& matched_preferredAudioContexts, bool& matched_streamingAudioContexts, + bool& matched_vendorSpecific) { + if (aidl_meta->getTag() == + ::aidl::android::hardware::bluetooth::audio::MetadataLtv::preferredAudioContexts) { ASSERT_EQ(aidl_meta - ->get<::aidl::android::hardware::bluetooth::audio:: - MetadataLtv::preferredAudioContexts>() - .values.bitmask, + ->get<::aidl::android::hardware::bluetooth::audio::MetadataLtv:: + preferredAudioContexts>() + .values.bitmask, stack_meta.preferred_audio_context.value()); matched_preferredAudioContexts = true; } else if (aidl_meta->getTag() == - ::aidl::android::hardware::bluetooth::audio::MetadataLtv:: - streamingAudioContexts) { + ::aidl::android::hardware::bluetooth::audio::MetadataLtv::streamingAudioContexts) { ASSERT_EQ(aidl_meta - ->get<::aidl::android::hardware::bluetooth::audio:: - MetadataLtv::streamingAudioContexts>() - .values.bitmask, + ->get<::aidl::android::hardware::bluetooth::audio::MetadataLtv:: + streamingAudioContexts>() + .values.bitmask, stack_meta.streaming_audio_context.value()); matched_streamingAudioContexts = true; - } else if (aidl_meta->getTag() == ::aidl::android::hardware::bluetooth:: - audio::MetadataLtv::vendorSpecific) { - auto vendor_spec = aidl_meta->get<::aidl::android::hardware::bluetooth:: - audio::MetadataLtv::vendorSpecific>(); + } else if (aidl_meta->getTag() == + ::aidl::android::hardware::bluetooth::audio::MetadataLtv::vendorSpecific) { + auto vendor_spec = aidl_meta->get< + ::aidl::android::hardware::bluetooth::audio::MetadataLtv::vendorSpecific>(); /* Company ID is a 2 octet value */ ASSERT_EQ(vendor_spec.companyId, - stack_meta.vendor_specific->at(0) | - (stack_meta.vendor_specific->at(1) << 8)); + stack_meta.vendor_specific->at(0) | (stack_meta.vendor_specific->at(1) << 8)); auto expected_payload_size = stack_meta.vendor_specific->size() - 2; ASSERT_EQ(vendor_spec.opaqueValue.size(), expected_payload_size); - ASSERT_EQ(0, memcmp(vendor_spec.opaqueValue.data(), - stack_meta.vendor_specific->data() + 2, + ASSERT_EQ(0, memcmp(vendor_spec.opaqueValue.data(), stack_meta.vendor_specific->data() + 2, expected_payload_size)); matched_vendorSpecific = true; } else { @@ -826,12 +730,9 @@ static void verifyMetadata( } } -TEST(BluetoothAudioClientInterfaceAidlTest, - testGetAidlMetadataFromStackFormat) { - ::bluetooth::le_audio::types::LeAudioLtvMap metadata_ltvs = - test_utils::PrepareStackMetadataLtv(); - auto aidl_metadata = - GetAidlMetadataFromStackFormat(metadata_ltvs.RawPacket()); +TEST(BluetoothAudioClientInterfaceAidlTest, testGetAidlMetadataFromStackFormat) { + ::bluetooth::le_audio::types::LeAudioLtvMap metadata_ltvs = test_utils::PrepareStackMetadataLtv(); + auto aidl_metadata = GetAidlMetadataFromStackFormat(metadata_ltvs.RawPacket()); ASSERT_TRUE(aidl_metadata.has_value()); /* Only kLeAudioMetadataTypePreferredAudioContext, @@ -847,8 +748,7 @@ TEST(BluetoothAudioClientInterfaceAidlTest, for (const auto& meta : *aidl_metadata) { ASSERT_TRUE(meta.has_value()); - verifyMetadata(meta, metadata_ltvs.GetAsLeAudioMetadata(), - matched_preferredAudioContexts, + verifyMetadata(meta, metadata_ltvs.GetAsLeAudioMetadata(), matched_preferredAudioContexts, matched_streamingAudioContexts, matched_vendorSpecific); } @@ -857,18 +757,14 @@ TEST(BluetoothAudioClientInterfaceAidlTest, ASSERT_TRUE(matched_vendorSpecific); } -TEST(BluetoothAudioClientInterfaceAidlTest, - testGetAidlLeAudioDeviceCapabilitiesFromStackFormat) { +TEST(BluetoothAudioClientInterfaceAidlTest, testGetAidlLeAudioDeviceCapabilitiesFromStackFormat) { std::vector pac_records; // Add some records auto stack_record = test_utils::PrepareStackPacRecord( - kStackCodecLc3, - ::bluetooth::le_audio::codec_spec_caps::kLeAudioSamplingFreq16000Hz, - ::bluetooth::le_audio::codec_spec_caps::kLeAudioCodecFrameDurPrefer7500us, - ::bluetooth::le_audio::codec_spec_caps:: - kLeAudioCodecChannelCountTwoChannel, - 80, 120); + kStackCodecLc3, ::bluetooth::le_audio::codec_spec_caps::kLeAudioSamplingFreq16000Hz, + ::bluetooth::le_audio::codec_spec_caps::kLeAudioCodecFrameDurPrefer7500us, + ::bluetooth::le_audio::codec_spec_caps::kLeAudioCodecChannelCountTwoChannel, 80, 120); pac_records.push_back(stack_record); auto aidl_pacs = GetAidlLeAudioDeviceCapabilitiesFromStackFormat(pac_records); @@ -882,69 +778,55 @@ TEST(BluetoothAudioClientInterfaceAidlTest, for (auto const& aidl_pac : *aidl_pacs) { ASSERT_TRUE(aidl_pac.has_value()); - ASSERT_EQ(aidl::android::hardware::bluetooth::audio::CodecId::core, - aidl_pac->codecId.getTag()); - ASSERT_EQ( - kAidlCodecLc3, - aidl_pac->codecId - .get()); + ASSERT_EQ(aidl::android::hardware::bluetooth::audio::CodecId::core, aidl_pac->codecId.getTag()); + ASSERT_EQ(kAidlCodecLc3, + aidl_pac->codecId.get()); for (auto const& cap : aidl_pac->codecSpecificCapabilities) { - if (cap.getTag() == - ::aidl::android::hardware::bluetooth::audio:: - CodecSpecificCapabilitiesLtv::supportedSamplingFrequencies) { - ASSERT_EQ(::aidl::android::hardware::bluetooth::audio:: - CodecSpecificCapabilitiesLtv:: + if (cap.getTag() == ::aidl::android::hardware::bluetooth::audio:: + CodecSpecificCapabilitiesLtv::supportedSamplingFrequencies) { + ASSERT_EQ(::aidl::android::hardware::bluetooth::audio::CodecSpecificCapabilitiesLtv:: SupportedSamplingFrequencies::HZ16000, cap.get<::aidl::android::hardware::bluetooth::audio:: - CodecSpecificCapabilitiesLtv:: - supportedSamplingFrequencies>() - .bitmask); + CodecSpecificCapabilitiesLtv::supportedSamplingFrequencies>() + .bitmask); matched_supportedSamplingFrequencies = true; - } else if (cap.getTag() == - ::aidl::android::hardware::bluetooth::audio:: - CodecSpecificCapabilitiesLtv::supportedFrameDurations) { - ASSERT_EQ( - ::aidl::android::hardware::bluetooth::audio:: - CodecSpecificCapabilitiesLtv::SupportedFrameDurations:: - US7500PREFERRED, - cap.get<::aidl::android::hardware::bluetooth::audio:: - CodecSpecificCapabilitiesLtv::supportedFrameDurations>() - .bitmask); + } else if (cap.getTag() == ::aidl::android::hardware::bluetooth::audio:: + CodecSpecificCapabilitiesLtv::supportedFrameDurations) { + ASSERT_EQ(::aidl::android::hardware::bluetooth::audio::CodecSpecificCapabilitiesLtv:: + SupportedFrameDurations::US7500PREFERRED, + cap.get<::aidl::android::hardware::bluetooth::audio:: + CodecSpecificCapabilitiesLtv::supportedFrameDurations>() + .bitmask); matched_supportedFrameDurations = true; - } else if (cap.getTag() == ::aidl::android::hardware::bluetooth::audio:: - CodecSpecificCapabilitiesLtv:: - supportedAudioChannelCounts) { - ASSERT_EQ( - ::aidl::android::hardware::bluetooth::audio:: - CodecSpecificCapabilitiesLtv::SupportedAudioChannelCounts::TWO, - cap.get<::aidl::android::hardware::bluetooth::audio:: - CodecSpecificCapabilitiesLtv:: - supportedAudioChannelCounts>() - .bitmask); + } else if (cap.getTag() == + ::aidl::android::hardware::bluetooth::audio::CodecSpecificCapabilitiesLtv:: + supportedAudioChannelCounts) { + ASSERT_EQ(::aidl::android::hardware::bluetooth::audio::CodecSpecificCapabilitiesLtv:: + SupportedAudioChannelCounts::TWO, + cap.get<::aidl::android::hardware::bluetooth::audio:: + CodecSpecificCapabilitiesLtv::supportedAudioChannelCounts>() + .bitmask); matched_supportedAudioChannelCounts = true; - } else if (cap.getTag() == ::aidl::android::hardware::bluetooth::audio:: - CodecSpecificCapabilitiesLtv:: - supportedOctetsPerCodecFrame) { + } else if (cap.getTag() == + ::aidl::android::hardware::bluetooth::audio::CodecSpecificCapabilitiesLtv:: + supportedOctetsPerCodecFrame) { ASSERT_EQ(80, cap.get<::aidl::android::hardware::bluetooth::audio:: - CodecSpecificCapabilitiesLtv:: - supportedOctetsPerCodecFrame>() - .min); + CodecSpecificCapabilitiesLtv::supportedOctetsPerCodecFrame>() + .min); ASSERT_EQ(120, cap.get<::aidl::android::hardware::bluetooth::audio:: - CodecSpecificCapabilitiesLtv:: - supportedOctetsPerCodecFrame>() - .max); + CodecSpecificCapabilitiesLtv::supportedOctetsPerCodecFrame>() + .max); matched_supportedOctetsPerCodecFrame = true; - } else if (cap.getTag() == ::aidl::android::hardware::bluetooth::audio:: - CodecSpecificCapabilitiesLtv:: - supportedMaxCodecFramesPerSDU) { + } else if (cap.getTag() == + ::aidl::android::hardware::bluetooth::audio::CodecSpecificCapabilitiesLtv:: + supportedMaxCodecFramesPerSDU) { ASSERT_EQ(1, cap.get<::aidl::android::hardware::bluetooth::audio:: - CodecSpecificCapabilitiesLtv:: - supportedMaxCodecFramesPerSDU>() - .value); + CodecSpecificCapabilitiesLtv::supportedMaxCodecFramesPerSDU>() + .value); matched_supportedMaxCodecFramesPerSDU = true; } else { @@ -965,10 +847,8 @@ TEST(BluetoothAudioClientInterfaceAidlTest, bool matched_vendorSpecific = false; for (auto const& meta : *aidl_pac->metadata) { ::bluetooth::le_audio::types::LeAudioLtvMap stack_meta; - ASSERT_TRUE(stack_meta.Parse(stack_record.metadata.data(), - stack_record.metadata.size())); - verifyMetadata(meta, stack_meta.GetAsLeAudioMetadata(), - matched_preferredAudioContexts, + ASSERT_TRUE(stack_meta.Parse(stack_record.metadata.data(), stack_record.metadata.size())); + verifyMetadata(meta, stack_meta.GetAsLeAudioMetadata(), matched_preferredAudioContexts, matched_streamingAudioContexts, matched_vendorSpecific); } @@ -984,64 +864,50 @@ TEST(BluetoothAudioClientInterfaceAidlTest, ASSERT_TRUE(matched_supportedMaxCodecFramesPerSDU); } -TEST(BluetoothAudioClientInterfaceAidlTest, - testGetStackLeAudioLtvMapFromAidlFormat) { +TEST(BluetoothAudioClientInterfaceAidlTest, testGetStackLeAudioLtvMapFromAidlFormat) { auto [aidl_codec_spec, matching_stack_codec_spec] = - test_utils::PrepareReferenceCodecSpecificConfigurationLc3(true, true, - true); + test_utils::PrepareReferenceCodecSpecificConfigurationLc3(true, true, true); - auto stack_codec_config_ltv = - GetStackLeAudioLtvMapFromAidlFormat(aidl_codec_spec); + auto stack_codec_config_ltv = GetStackLeAudioLtvMapFromAidlFormat(aidl_codec_spec); ASSERT_EQ(matching_stack_codec_spec, stack_codec_config_ltv); } -TEST(BluetoothAudioClientInterfaceAidlTest, - testGetStackDataPathFromAidlFormat) { +TEST(BluetoothAudioClientInterfaceAidlTest, testGetStackDataPathFromAidlFormat) { auto [aidl_config, reference_stack_config] = - test_utils::PrepareReferenceLeAudioDataPathConfigurationVendor(); - auto stack_config = - bluetooth::audio::aidl::GetStackDataPathFromAidlFormat(aidl_config); + test_utils::PrepareReferenceLeAudioDataPathConfigurationVendor(); + auto stack_config = bluetooth::audio::aidl::GetStackDataPathFromAidlFormat(aidl_config); ASSERT_EQ(stack_config, reference_stack_config); } -TEST(BluetoothAudioClientInterfaceAidlTest, - testGetStackMetadataFromAidlFormat) { - auto [aidl_metadata, reference_stack_metadata] = - test_utils::PrepareReferenceMetadata(); - auto stack_metadata = - bluetooth::audio::aidl::GetStackMetadataFromAidlFormat(aidl_metadata); +TEST(BluetoothAudioClientInterfaceAidlTest, testGetStackMetadataFromAidlFormat) { + auto [aidl_metadata, reference_stack_metadata] = test_utils::PrepareReferenceMetadata(); + auto stack_metadata = bluetooth::audio::aidl::GetStackMetadataFromAidlFormat(aidl_metadata); ASSERT_EQ(stack_metadata, reference_stack_metadata); } -TEST(BluetoothAudioClientInterfaceAidlTest, - testGetStackUnicastConfigurationFromAidlFormat) { - auto [aidl_config, expected_stack_config] = - test_utils::PrepareReferenceAseConfigurationSetting( +TEST(BluetoothAudioClientInterfaceAidlTest, testGetStackUnicastConfigurationFromAidlFormat) { + auto [aidl_config, expected_stack_config] = test_utils::PrepareReferenceAseConfigurationSetting( ::bluetooth::le_audio::types::LeAudioContextType::GAME, true); auto stack_config = GetStackUnicastConfigurationFromAidlFormat( - ::bluetooth::le_audio::types::LeAudioContextType::GAME, aidl_config); + ::bluetooth::le_audio::types::LeAudioContextType::GAME, aidl_config); ASSERT_TRUE(stack_config.has_value()); ASSERT_EQ(stack_config->confs.sink.size(), 2ul); ASSERT_EQ(*stack_config, expected_stack_config); } -TEST(BluetoothAudioClientInterfaceAidlTest, - testGetStackBisConfigFromAidlFormat) { - auto [aidl_config, expected_stack_config] = - test_utils::PrepareReferenceBisConfiguration(); +TEST(BluetoothAudioClientInterfaceAidlTest, testGetStackBisConfigFromAidlFormat) { + auto [aidl_config, expected_stack_config] = test_utils::PrepareReferenceBisConfiguration(); ::bluetooth::le_audio::types::LeAudioCodecId out_stack_codec_id; - auto stack_config = - GetStackBisConfigFromAidlFormat(aidl_config, out_stack_codec_id); + auto stack_config = GetStackBisConfigFromAidlFormat(aidl_config, out_stack_codec_id); ASSERT_EQ(stack_config, expected_stack_config); ASSERT_EQ(out_stack_codec_id, kStackCodecLc3); } -TEST(BluetoothAudioClientInterfaceAidlTest, - testGetStackSubgroupsFromAidlFormat) { +TEST(BluetoothAudioClientInterfaceAidlTest, testGetStackSubgroupsFromAidlFormat) { auto [aidl_subgroups, expected_stack_subgroups] = - test_utils::PrepareReferenceBroadcastSubgroups(); + test_utils::PrepareReferenceBroadcastSubgroups(); auto stack_subgroups = GetStackSubgroupsFromAidlFormat(aidl_subgroups); ASSERT_FALSE(aidl_subgroups.empty()); @@ -1049,10 +915,9 @@ TEST(BluetoothAudioClientInterfaceAidlTest, ASSERT_EQ(stack_subgroups, expected_stack_subgroups); } -TEST(BluetoothAudioClientInterfaceAidlTest, - testGetStackBroadcastConfigurationFromAidlFormat) { +TEST(BluetoothAudioClientInterfaceAidlTest, testGetStackBroadcastConfigurationFromAidlFormat) { auto [aidl_config, expected_stack_config] = - test_utils::PrepareReferenceBroadcastConfigurationLc3(); + test_utils::PrepareReferenceBroadcastConfigurationLc3(); auto stack_config = GetStackBroadcastConfigurationFromAidlFormat(aidl_config); ASSERT_TRUE(stack_config.has_value()); ASSERT_EQ(stack_config.value(), expected_stack_config); @@ -1061,10 +926,9 @@ TEST(BluetoothAudioClientInterfaceAidlTest, TEST(BluetoothAudioClientInterfaceAidlTest, testGetAidlLeAudioBroadcastConfigurationRequirementFromStackFormat) { auto [reference_aidl_requirements, stack_requirements] = - test_utils::PrepareReferenceBroadcastRequirements(); + test_utils::PrepareReferenceBroadcastRequirements(); auto aidl_requirements = - GetAidlLeAudioBroadcastConfigurationRequirementFromStackFormat( - stack_requirements); + GetAidlLeAudioBroadcastConfigurationRequirementFromStackFormat(stack_requirements); ASSERT_EQ(aidl_requirements, reference_aidl_requirements); } @@ -1072,92 +936,79 @@ TEST(BluetoothAudioClientInterfaceAidlTest, testGetAidlLeAudioUnicastConfigurationRequirementsFromStackFormat) { auto stack_context = le_audio::types::LeAudioContextType::CONVERSATIONAL; auto aidl_context = ::aidl::android::hardware::bluetooth::audio::AudioContext{ - .bitmask = ::aidl::android::hardware::bluetooth::audio::AudioContext:: - CONVERSATIONAL, + .bitmask = ::aidl::android::hardware::bluetooth::audio::AudioContext::CONVERSATIONAL, }; ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: - LeAudioConfigurationRequirement reference_aidl_requirements; + LeAudioConfigurationRequirement reference_aidl_requirements; reference_aidl_requirements.audioContext = aidl_context; - auto [aidl_req_l, stack_req_l] = - test_utils::PrepareReferenceDirectionRequirements( - ::aidl::android::hardware::bluetooth::audio:: - CodecSpecificConfigurationLtv::AudioChannelAllocation::FRONT_LEFT, + auto [aidl_req_l, stack_req_l] = test_utils::PrepareReferenceDirectionRequirements( + ::aidl::android::hardware::bluetooth::audio::CodecSpecificConfigurationLtv:: + AudioChannelAllocation::FRONT_LEFT, le_audio::codec_spec_conf::kLeAudioLocationFrontLeft); - auto [aidl_req_r, stack_req_r] = - test_utils::PrepareReferenceDirectionRequirements( - ::aidl::android::hardware::bluetooth::audio:: - CodecSpecificConfigurationLtv::AudioChannelAllocation:: - FRONT_RIGHT, + auto [aidl_req_r, stack_req_r] = test_utils::PrepareReferenceDirectionRequirements( + ::aidl::android::hardware::bluetooth::audio::CodecSpecificConfigurationLtv:: + AudioChannelAllocation::FRONT_RIGHT, le_audio::codec_spec_conf::kLeAudioLocationFrontRight); // For this case lets make the sink and source requirements symmetric - std::vector<::bluetooth::le_audio::CodecManager:: - UnicastConfigurationRequirements::DeviceDirectionRequirements> - stack_sink_reqs = {stack_req_l, stack_req_r}; + std::vector<::bluetooth::le_audio::CodecManager::UnicastConfigurationRequirements:: + DeviceDirectionRequirements> + stack_sink_reqs = {stack_req_l, stack_req_r}; auto stack_source_reqs = stack_sink_reqs; - reference_aidl_requirements.sinkAseRequirement = std::vector>{ - aidl_req_l, aidl_req_r}; - reference_aidl_requirements.sourceAseRequirement = - reference_aidl_requirements.sinkAseRequirement; + reference_aidl_requirements.sinkAseRequirement = std::vector< + std::optional<::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: + LeAudioConfigurationRequirement::AseDirectionRequirement>>{ + aidl_req_l, aidl_req_r}; + reference_aidl_requirements.sourceAseRequirement = reference_aidl_requirements.sinkAseRequirement; - auto aidl_requirements = - GetAidlLeAudioUnicastConfigurationRequirementsFromStackFormat( + auto aidl_requirements = GetAidlLeAudioUnicastConfigurationRequirementsFromStackFormat( stack_context, stack_sink_reqs, stack_source_reqs); - ASSERT_EQ(aidl_requirements.audioContext, - reference_aidl_requirements.audioContext); + ASSERT_EQ(aidl_requirements.audioContext, reference_aidl_requirements.audioContext); ASSERT_EQ(aidl_requirements.flags, reference_aidl_requirements.flags); ASSERT_EQ(aidl_requirements.sinkAseRequirement.has_value(), reference_aidl_requirements.sinkAseRequirement.has_value()); if (reference_aidl_requirements.sinkAseRequirement.has_value()) { - for (auto const& reference_req : - reference_aidl_requirements.sinkAseRequirement.value()) { + for (auto const& reference_req : reference_aidl_requirements.sinkAseRequirement.value()) { auto iter = std::find_if( - aidl_requirements.sinkAseRequirement->begin(), - aidl_requirements.sinkAseRequirement->end(), - [reference_req](auto const& aidl_req) { - if (reference_req.has_value() != aidl_req.has_value()) { - return false; - } - if (reference_req->aseConfiguration.targetLatency != - aidl_req->aseConfiguration.targetLatency) { - return false; - } - if (reference_req->aseConfiguration.targetPhy != - aidl_req->aseConfiguration.targetPhy) { - return false; - } - if (reference_req->aseConfiguration.codecId != - aidl_req->aseConfiguration.codecId) { - return false; - } - if (reference_req->aseConfiguration.vendorCodecConfiguration != - aidl_req->aseConfiguration.vendorCodecConfiguration) { - return false; - } - if (reference_req->aseConfiguration.metadata != - aidl_req->aseConfiguration.metadata) { - return false; - } - for (auto const& ref_el : - reference_req->aseConfiguration.codecConfiguration) { - if (std::find( - aidl_req->aseConfiguration.codecConfiguration.begin(), - aidl_req->aseConfiguration.codecConfiguration.end(), - ref_el) == - aidl_req->aseConfiguration.codecConfiguration.end()) { - return false; - } - } - - return true; - }); + aidl_requirements.sinkAseRequirement->begin(), + aidl_requirements.sinkAseRequirement->end(), [reference_req](auto const& aidl_req) { + if (reference_req.has_value() != aidl_req.has_value()) { + return false; + } + if (reference_req->aseConfiguration.targetLatency != + aidl_req->aseConfiguration.targetLatency) { + return false; + } + if (reference_req->aseConfiguration.targetPhy != + aidl_req->aseConfiguration.targetPhy) { + return false; + } + if (reference_req->aseConfiguration.codecId != aidl_req->aseConfiguration.codecId) { + return false; + } + if (reference_req->aseConfiguration.vendorCodecConfiguration != + aidl_req->aseConfiguration.vendorCodecConfiguration) { + return false; + } + if (reference_req->aseConfiguration.metadata != + aidl_req->aseConfiguration.metadata) { + return false; + } + for (auto const& ref_el : reference_req->aseConfiguration.codecConfiguration) { + if (std::find(aidl_req->aseConfiguration.codecConfiguration.begin(), + aidl_req->aseConfiguration.codecConfiguration.end(), + ref_el) == aidl_req->aseConfiguration.codecConfiguration.end()) { + return false; + } + } + + return true; + }); ASSERT_NE(iter, aidl_requirements.sinkAseRequirement->end()); } } @@ -1165,48 +1016,42 @@ TEST(BluetoothAudioClientInterfaceAidlTest, ASSERT_EQ(aidl_requirements.sourceAseRequirement.has_value(), reference_aidl_requirements.sourceAseRequirement.has_value()); if (reference_aidl_requirements.sourceAseRequirement.has_value()) { - for (auto const& reference_req : - reference_aidl_requirements.sourceAseRequirement.value()) { + for (auto const& reference_req : reference_aidl_requirements.sourceAseRequirement.value()) { auto iter = std::find_if( - aidl_requirements.sourceAseRequirement->begin(), - aidl_requirements.sourceAseRequirement->end(), - [reference_req](auto const& aidl_req) { - if (reference_req.has_value() != aidl_req.has_value()) { - return false; - } - if (reference_req->aseConfiguration.targetLatency != - aidl_req->aseConfiguration.targetLatency) { - return false; - } - if (reference_req->aseConfiguration.targetPhy != - aidl_req->aseConfiguration.targetPhy) { - return false; - } - if (reference_req->aseConfiguration.codecId != - aidl_req->aseConfiguration.codecId) { - return false; - } - if (reference_req->aseConfiguration.vendorCodecConfiguration != - aidl_req->aseConfiguration.vendorCodecConfiguration) { - return false; - } - if (reference_req->aseConfiguration.metadata != - aidl_req->aseConfiguration.metadata) { - return false; - } - for (auto const& ref_el : - reference_req->aseConfiguration.codecConfiguration) { - if (std::find( - aidl_req->aseConfiguration.codecConfiguration.begin(), - aidl_req->aseConfiguration.codecConfiguration.end(), - ref_el) == - aidl_req->aseConfiguration.codecConfiguration.end()) { - return false; - } - } - - return true; - }); + aidl_requirements.sourceAseRequirement->begin(), + aidl_requirements.sourceAseRequirement->end(), [reference_req](auto const& aidl_req) { + if (reference_req.has_value() != aidl_req.has_value()) { + return false; + } + if (reference_req->aseConfiguration.targetLatency != + aidl_req->aseConfiguration.targetLatency) { + return false; + } + if (reference_req->aseConfiguration.targetPhy != + aidl_req->aseConfiguration.targetPhy) { + return false; + } + if (reference_req->aseConfiguration.codecId != aidl_req->aseConfiguration.codecId) { + return false; + } + if (reference_req->aseConfiguration.vendorCodecConfiguration != + aidl_req->aseConfiguration.vendorCodecConfiguration) { + return false; + } + if (reference_req->aseConfiguration.metadata != + aidl_req->aseConfiguration.metadata) { + return false; + } + for (auto const& ref_el : reference_req->aseConfiguration.codecConfiguration) { + if (std::find(aidl_req->aseConfiguration.codecConfiguration.begin(), + aidl_req->aseConfiguration.codecConfiguration.end(), + ref_el) == aidl_req->aseConfiguration.codecConfiguration.end()) { + return false; + } + } + + return true; + }); ASSERT_NE(iter, aidl_requirements.sourceAseRequirement->end()); } } diff --git a/system/audio_hal_interface/aidl/provider_info.cc b/system/audio_hal_interface/aidl/provider_info.cc index 1daacdbd01f..60f6869b8b3 100644 --- a/system/audio_hal_interface/aidl/provider_info.cc +++ b/system/audio_hal_interface/aidl/provider_info.cc @@ -33,17 +33,16 @@ using ::aidl::android::hardware::bluetooth::audio::SessionType; ::hfp::sco_config recordHfpCodecInfo(CodecInfo codecInfo) { auto hfp_transport = codecInfo.transport.get(); ::hfp::sco_config config{ - .inputDataPath = hfp_transport.inputDataPath, - .outputDataPath = hfp_transport.outputDataPath, - .useControllerCodec = hfp_transport.useControllerCodec, + .inputDataPath = hfp_transport.inputDataPath, + .outputDataPath = hfp_transport.outputDataPath, + .useControllerCodec = hfp_transport.useControllerCodec, }; return config; } -std::unique_ptr -bluetooth::audio::aidl::ProviderInfo::GetProviderInfo(SessionType sessionType) { - auto provider_info = - BluetoothAudioClientInterface::GetProviderInfo(sessionType); +std::unique_ptr bluetooth::audio::aidl::ProviderInfo::GetProviderInfo( + SessionType sessionType) { + auto provider_info = BluetoothAudioClientInterface::GetProviderInfo(sessionType); std::vector codecInfos; if (provider_info.has_value()) { @@ -53,29 +52,24 @@ bluetooth::audio::aidl::ProviderInfo::GetProviderInfo(SessionType sessionType) { return std::make_unique(sessionType, std::move(codecInfos)); } -ProviderInfo::ProviderInfo(SessionType sessionType, - std::vector codecs) +ProviderInfo::ProviderInfo(SessionType sessionType, std::vector codecs) : codecInfos(std::move(codecs)) { for (auto codecInfo : codecInfos) { if (codecInfo.id == CodecId::Core::CVSD) { - hfpScoConfigMap[tBTA_AG_UUID_CODEC::UUID_CODEC_CVSD] = - recordHfpCodecInfo(codecInfo); + hfpScoConfigMap[tBTA_AG_UUID_CODEC::UUID_CODEC_CVSD] = recordHfpCodecInfo(codecInfo); } else if (codecInfo.id == CodecId::Core::MSBC) { - hfpScoConfigMap[tBTA_AG_UUID_CODEC::UUID_CODEC_MSBC] = - recordHfpCodecInfo(codecInfo); + hfpScoConfigMap[tBTA_AG_UUID_CODEC::UUID_CODEC_MSBC] = recordHfpCodecInfo(codecInfo); } else if (codecInfo.id == CodecId::Core::LC3) { if (sessionType == SessionType::HFP_HARDWARE_OFFLOAD_DATAPATH || sessionType == SessionType::HFP_SOFTWARE_ENCODING_DATAPATH || sessionType == SessionType::HFP_SOFTWARE_DECODING_DATAPATH) { - hfpScoConfigMap[tBTA_AG_UUID_CODEC::UUID_CODEC_LC3] = - recordHfpCodecInfo(codecInfo); + hfpScoConfigMap[tBTA_AG_UUID_CODEC::UUID_CODEC_LC3] = recordHfpCodecInfo(codecInfo); } } } } -const std::unordered_map& -ProviderInfo::GetHfpScoConfig() { +const std::unordered_map& ProviderInfo::GetHfpScoConfig() { return hfpScoConfigMap; } } // namespace bluetooth::audio::aidl diff --git a/system/audio_hal_interface/aidl/provider_info.h b/system/audio_hal_interface/aidl/provider_info.h index b4453642154..c9546626f7f 100644 --- a/system/audio_hal_interface/aidl/provider_info.h +++ b/system/audio_hal_interface/aidl/provider_info.h @@ -29,20 +29,18 @@ using ::aidl::android::hardware::bluetooth::audio::CodecInfo; using ::aidl::android::hardware::bluetooth::audio::SessionType; class ProviderInfo { - public: +public: static std::unique_ptr GetProviderInfo(SessionType sessionType); ProviderInfo(SessionType sessionType, std::vector codecs); ~ProviderInfo() = default; - const std::unordered_map& - GetHfpScoConfig(); + const std::unordered_map& GetHfpScoConfig(); - private: +private: const std::vector codecInfos; - std::unordered_map - hfpScoConfigMap; + std::unordered_map + hfpScoConfigMap; }; } // namespace bluetooth::audio::aidl diff --git a/system/audio_hal_interface/aidl/transport_instance.h b/system/audio_hal_interface/aidl/transport_instance.h index 6b0adf09448..69cbe3e18d3 100644 --- a/system/audio_hal_interface/aidl/transport_instance.h +++ b/system/audio_hal_interface/aidl/transport_instance.h @@ -35,10 +35,9 @@ using ::aidl::android::hardware::bluetooth::audio::SessionType; * HAL. ***/ class IBluetoothTransportInstance { - public: - IBluetoothTransportInstance(SessionType sessionType, - AudioConfiguration audioConfig) - : session_type_(sessionType), audio_config_(std::move(audioConfig)){}; +public: + IBluetoothTransportInstance(SessionType sessionType, AudioConfiguration audioConfig) + : session_type_(sessionType), audio_config_(std::move(audioConfig)) {} virtual ~IBluetoothTransportInstance() = default; SessionType GetSessionType() const { return session_type_; } @@ -49,27 +48,26 @@ class IBluetoothTransportInstance { switch (audio_config.getTag()) { case AudioConfiguration::pcmConfig: audio_config_.set( - audio_config.get()); + audio_config.get()); break; case AudioConfiguration::a2dpConfig: audio_config_.set( - audio_config.get()); + audio_config.get()); break; case AudioConfiguration::hfpConfig: audio_config_.set( - audio_config.get()); + audio_config.get()); break; case AudioConfiguration::leAudioConfig: audio_config_.set( - audio_config.get()); + audio_config.get()); break; case AudioConfiguration::leAudioBroadcastConfig: audio_config_.set( - audio_config.get()); + audio_config.get()); break; case AudioConfiguration::a2dp: - audio_config_.set( - audio_config.get()); + audio_config_.set(audio_config.get()); break; } } @@ -83,11 +81,9 @@ class IBluetoothTransportInstance { virtual void SetLatencyMode(LatencyMode latency_mode) = 0; virtual bool GetPresentationPosition(uint64_t* remote_delay_report_ns, - uint64_t* total_bytes_readed, - timespec* data_position) = 0; + uint64_t* total_bytes_readed, timespec* data_position) = 0; - virtual void SourceMetadataChanged( - const source_metadata_v7_t& source_metadata) = 0; + virtual void SourceMetadataChanged(const source_metadata_v7_t& source_metadata) = 0; virtual void SinkMetadataChanged(const sink_metadata_v7_t& sink_metadata) = 0; /*** @@ -95,7 +91,7 @@ class IBluetoothTransportInstance { ***/ virtual void ResetPresentationPosition() = 0; - private: +private: const SessionType session_type_; AudioConfiguration audio_config_; }; @@ -106,9 +102,8 @@ class IBluetoothTransportInstance { * from Audio HAL. ***/ class IBluetoothSinkTransportInstance : public IBluetoothTransportInstance { - public: - IBluetoothSinkTransportInstance(SessionType sessionType, - AudioConfiguration audioConfig) +public: + IBluetoothSinkTransportInstance(SessionType sessionType, AudioConfiguration audioConfig) : IBluetoothTransportInstance{sessionType, audioConfig} {} virtual ~IBluetoothSinkTransportInstance() = default; @@ -119,9 +114,8 @@ class IBluetoothSinkTransportInstance : public IBluetoothTransportInstance { }; class IBluetoothSourceTransportInstance : public IBluetoothTransportInstance { - public: - IBluetoothSourceTransportInstance(SessionType sessionType, - AudioConfiguration audioConfig) +public: + IBluetoothSourceTransportInstance(SessionType sessionType, AudioConfiguration audioConfig) : IBluetoothTransportInstance{sessionType, audioConfig} {} virtual ~IBluetoothSourceTransportInstance() = default; diff --git a/system/audio_hal_interface/audio_linux.h b/system/audio_hal_interface/audio_linux.h index 7f98eee0265..7baa8aae103 100644 --- a/system/audio_hal_interface/audio_linux.h +++ b/system/audio_hal_interface/audio_linux.h @@ -120,65 +120,56 @@ typedef enum : uint32_t { AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT = 0x80000u, AUDIO_CHANNEL_OUT_HAPTIC_A = 0x20000000u, AUDIO_CHANNEL_OUT_HAPTIC_B = 0x10000000u, - AUDIO_CHANNEL_OUT_MONO = 0x1u, // OUT_FRONT_LEFT - AUDIO_CHANNEL_OUT_STEREO = 0x3u, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT - AUDIO_CHANNEL_OUT_2POINT1 = - 0xBu, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_LOW_FREQUENCY - AUDIO_CHANNEL_OUT_2POINT0POINT2 = - 0xC0003u, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_TOP_SIDE_LEFT | - // OUT_TOP_SIDE_RIGHT + AUDIO_CHANNEL_OUT_MONO = 0x1u, // OUT_FRONT_LEFT + AUDIO_CHANNEL_OUT_STEREO = 0x3u, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT + AUDIO_CHANNEL_OUT_2POINT1 = 0xBu, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_LOW_FREQUENCY + AUDIO_CHANNEL_OUT_2POINT0POINT2 = 0xC0003u, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | + // OUT_TOP_SIDE_LEFT | OUT_TOP_SIDE_RIGHT AUDIO_CHANNEL_OUT_2POINT1POINT2 = - 0xC000Bu, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_TOP_SIDE_LEFT | - // OUT_TOP_SIDE_RIGHT | OUT_LOW_FREQUENCY + 0xC000Bu, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_TOP_SIDE_LEFT | + // OUT_TOP_SIDE_RIGHT | OUT_LOW_FREQUENCY AUDIO_CHANNEL_OUT_3POINT0POINT2 = - 0xC0007u, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_FRONT_CENTER | - // OUT_TOP_SIDE_LEFT | OUT_TOP_SIDE_RIGHT + 0xC0007u, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_FRONT_CENTER + // | OUT_TOP_SIDE_LEFT | OUT_TOP_SIDE_RIGHT AUDIO_CHANNEL_OUT_3POINT1POINT2 = - 0xC000Fu, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_FRONT_CENTER | - // OUT_TOP_SIDE_LEFT | OUT_TOP_SIDE_RIGHT | OUT_LOW_FREQUENCY - AUDIO_CHANNEL_OUT_QUAD = 0x33u, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | - // OUT_BACK_LEFT | OUT_BACK_RIGHT - AUDIO_CHANNEL_OUT_QUAD_BACK = 0x33u, // OUT_QUAD - AUDIO_CHANNEL_OUT_QUAD_SIDE = 0x603u, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | - // OUT_SIDE_LEFT | OUT_SIDE_RIGHT - AUDIO_CHANNEL_OUT_SURROUND = 0x107u, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | - // OUT_FRONT_CENTER | OUT_BACK_CENTER - AUDIO_CHANNEL_OUT_PENTA = 0x37u, // OUT_QUAD | OUT_FRONT_CENTER - AUDIO_CHANNEL_OUT_5POINT1 = - 0x3Fu, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_FRONT_CENTER | - // OUT_LOW_FREQUENCY | OUT_BACK_LEFT | OUT_BACK_RIGHT - AUDIO_CHANNEL_OUT_5POINT1_BACK = 0x3Fu, // OUT_5POINT1 - AUDIO_CHANNEL_OUT_5POINT1_SIDE = - 0x60Fu, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_FRONT_CENTER | - // OUT_LOW_FREQUENCY | OUT_SIDE_LEFT | OUT_SIDE_RIGHT + 0xC000Fu, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_FRONT_CENTER | + // OUT_TOP_SIDE_LEFT | OUT_TOP_SIDE_RIGHT | OUT_LOW_FREQUENCY + AUDIO_CHANNEL_OUT_QUAD = 0x33u, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | + // OUT_BACK_LEFT | OUT_BACK_RIGHT + AUDIO_CHANNEL_OUT_QUAD_BACK = 0x33u, // OUT_QUAD + AUDIO_CHANNEL_OUT_QUAD_SIDE = 0x603u, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | + // OUT_SIDE_LEFT | OUT_SIDE_RIGHT + AUDIO_CHANNEL_OUT_SURROUND = 0x107u, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | + // OUT_FRONT_CENTER | OUT_BACK_CENTER + AUDIO_CHANNEL_OUT_PENTA = 0x37u, // OUT_QUAD | OUT_FRONT_CENTER + AUDIO_CHANNEL_OUT_5POINT1 = 0x3Fu, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_FRONT_CENTER | + // OUT_LOW_FREQUENCY | OUT_BACK_LEFT | OUT_BACK_RIGHT + AUDIO_CHANNEL_OUT_5POINT1_BACK = 0x3Fu, // OUT_5POINT1 + AUDIO_CHANNEL_OUT_5POINT1_SIDE = 0x60Fu, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_FRONT_CENTER | + // OUT_LOW_FREQUENCY | OUT_SIDE_LEFT | OUT_SIDE_RIGHT AUDIO_CHANNEL_OUT_5POINT1POINT2 = - 0xC003Fu, // OUT_5POINT1 | OUT_TOP_SIDE_LEFT | OUT_TOP_SIDE_RIGHT + 0xC003Fu, // OUT_5POINT1 | OUT_TOP_SIDE_LEFT | OUT_TOP_SIDE_RIGHT AUDIO_CHANNEL_OUT_5POINT1POINT4 = - 0x2D03Fu, // OUT_5POINT1 | OUT_TOP_FRONT_LEFT | OUT_TOP_FRONT_RIGHT | - // OUT_TOP_BACK_LEFT | OUT_TOP_BACK_RIGHT - AUDIO_CHANNEL_OUT_6POINT1 = - 0x13Fu, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_FRONT_CENTER | - // OUT_LOW_FREQUENCY | OUT_BACK_LEFT | OUT_BACK_RIGHT | - // OUT_BACK_CENTER - AUDIO_CHANNEL_OUT_7POINT1 = - 0x63Fu, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_FRONT_CENTER | - // OUT_LOW_FREQUENCY | OUT_BACK_LEFT | OUT_BACK_RIGHT | - // OUT_SIDE_LEFT | OUT_SIDE_RIGHT + 0x2D03Fu, // OUT_5POINT1 | OUT_TOP_FRONT_LEFT | OUT_TOP_FRONT_RIGHT | + // OUT_TOP_BACK_LEFT | OUT_TOP_BACK_RIGHT + AUDIO_CHANNEL_OUT_6POINT1 = 0x13Fu, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_FRONT_CENTER | + // OUT_LOW_FREQUENCY | OUT_BACK_LEFT | OUT_BACK_RIGHT | + // OUT_BACK_CENTER + AUDIO_CHANNEL_OUT_7POINT1 = 0x63Fu, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_FRONT_CENTER | + // OUT_LOW_FREQUENCY | OUT_BACK_LEFT | OUT_BACK_RIGHT | + // OUT_SIDE_LEFT | OUT_SIDE_RIGHT AUDIO_CHANNEL_OUT_7POINT1POINT2 = - 0xC063Fu, // OUT_7POINT1 | OUT_TOP_SIDE_LEFT | OUT_TOP_SIDE_RIGHT + 0xC063Fu, // OUT_7POINT1 | OUT_TOP_SIDE_LEFT | OUT_TOP_SIDE_RIGHT AUDIO_CHANNEL_OUT_7POINT1POINT4 = - 0x2D63Fu, // OUT_7POINT1 | OUT_TOP_FRONT_LEFT | OUT_TOP_FRONT_RIGHT | - // OUT_TOP_BACK_LEFT | OUT_TOP_BACK_RIGHT - AUDIO_CHANNEL_OUT_MONO_HAPTIC_A = - 0x20000001u, // OUT_FRONT_LEFT | OUT_HAPTIC_A + 0x2D63Fu, // OUT_7POINT1 | OUT_TOP_FRONT_LEFT | OUT_TOP_FRONT_RIGHT | + // OUT_TOP_BACK_LEFT | OUT_TOP_BACK_RIGHT + AUDIO_CHANNEL_OUT_MONO_HAPTIC_A = 0x20000001u, // OUT_FRONT_LEFT | OUT_HAPTIC_A AUDIO_CHANNEL_OUT_STEREO_HAPTIC_A = - 0x20000003u, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_HAPTIC_A + 0x20000003u, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_HAPTIC_A AUDIO_CHANNEL_OUT_HAPTIC_AB = 0x30000000u, // OUT_HAPTIC_A | OUT_HAPTIC_B - AUDIO_CHANNEL_OUT_MONO_HAPTIC_AB = - 0x30000001u, // OUT_FRONT_LEFT | OUT_HAPTIC_A | OUT_HAPTIC_B - AUDIO_CHANNEL_OUT_STEREO_HAPTIC_AB = - 0x30000003u, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_HAPTIC_A | - // OUT_HAPTIC_B + AUDIO_CHANNEL_OUT_MONO_HAPTIC_AB = 0x30000001u, // OUT_FRONT_LEFT | OUT_HAPTIC_A | OUT_HAPTIC_B + AUDIO_CHANNEL_OUT_STEREO_HAPTIC_AB = 0x30000003u, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | + // OUT_HAPTIC_A | OUT_HAPTIC_B AUDIO_CHANNEL_IN_LEFT = 0x4u, AUDIO_CHANNEL_IN_RIGHT = 0x8u, @@ -200,31 +191,26 @@ typedef enum : uint32_t { AUDIO_CHANNEL_IN_TOP_RIGHT = 0x400000u, AUDIO_CHANNEL_IN_VOICE_UPLINK = 0x4000u, AUDIO_CHANNEL_IN_VOICE_DNLINK = 0x8000u, - AUDIO_CHANNEL_IN_MONO = 0x10u, // IN_FRONT - AUDIO_CHANNEL_IN_STEREO = 0xCu, // IN_LEFT | IN_RIGHT - AUDIO_CHANNEL_IN_FRONT_BACK = 0x30u, // IN_FRONT | IN_BACK - AUDIO_CHANNEL_IN_6 = 0xFCu, // IN_LEFT | IN_RIGHT | IN_FRONT | IN_BACK | - // IN_LEFT_PROCESSED | IN_RIGHT_PROCESSED - AUDIO_CHANNEL_IN_2POINT0POINT2 = - 0x60000Cu, // IN_LEFT | IN_RIGHT | IN_TOP_LEFT | IN_TOP_RIGHT - AUDIO_CHANNEL_IN_2POINT1POINT2 = - 0x70000Cu, // IN_LEFT | IN_RIGHT | IN_TOP_LEFT | IN_TOP_RIGHT | - // IN_LOW_FREQUENCY + AUDIO_CHANNEL_IN_MONO = 0x10u, // IN_FRONT + AUDIO_CHANNEL_IN_STEREO = 0xCu, // IN_LEFT | IN_RIGHT + AUDIO_CHANNEL_IN_FRONT_BACK = 0x30u, // IN_FRONT | IN_BACK + AUDIO_CHANNEL_IN_6 = 0xFCu, // IN_LEFT | IN_RIGHT | IN_FRONT | IN_BACK | + // IN_LEFT_PROCESSED | IN_RIGHT_PROCESSED + AUDIO_CHANNEL_IN_2POINT0POINT2 = 0x60000Cu, // IN_LEFT | IN_RIGHT | IN_TOP_LEFT | IN_TOP_RIGHT + AUDIO_CHANNEL_IN_2POINT1POINT2 = 0x70000Cu, // IN_LEFT | IN_RIGHT | IN_TOP_LEFT | IN_TOP_RIGHT | + // IN_LOW_FREQUENCY AUDIO_CHANNEL_IN_3POINT0POINT2 = - 0x64000Cu, // IN_LEFT | IN_CENTER | IN_RIGHT | IN_TOP_LEFT | IN_TOP_RIGHT - AUDIO_CHANNEL_IN_3POINT1POINT2 = - 0x74000Cu, // IN_LEFT | IN_CENTER | IN_RIGHT | IN_TOP_LEFT | IN_TOP_RIGHT - // | IN_LOW_FREQUENCY - AUDIO_CHANNEL_IN_5POINT1 = - 0x17000Cu, // IN_LEFT | IN_CENTER | IN_RIGHT | IN_BACK_LEFT | - // IN_BACK_RIGHT | IN_LOW_FREQUENCY + 0x64000Cu, // IN_LEFT | IN_CENTER | IN_RIGHT | IN_TOP_LEFT | IN_TOP_RIGHT + AUDIO_CHANNEL_IN_3POINT1POINT2 = 0x74000Cu, // IN_LEFT | IN_CENTER | IN_RIGHT | IN_TOP_LEFT | + // IN_TOP_RIGHT | IN_LOW_FREQUENCY + AUDIO_CHANNEL_IN_5POINT1 = 0x17000Cu, // IN_LEFT | IN_CENTER | IN_RIGHT | IN_BACK_LEFT | + // IN_BACK_RIGHT | IN_LOW_FREQUENCY AUDIO_CHANNEL_IN_VOICE_UPLINK_MONO = 0x4010u, // IN_VOICE_UPLINK | IN_MONO AUDIO_CHANNEL_IN_VOICE_DNLINK_MONO = 0x8010u, // IN_VOICE_DNLINK | IN_MONO - AUDIO_CHANNEL_IN_VOICE_CALL_MONO = - 0xC010u, // IN_VOICE_UPLINK_MONO | IN_VOICE_DNLINK_MONO + AUDIO_CHANNEL_IN_VOICE_CALL_MONO = 0xC010u, // IN_VOICE_UPLINK_MONO | IN_VOICE_DNLINK_MONO AUDIO_CHANNEL_COUNT_MAX = 30u, - AUDIO_CHANNEL_INDEX_HDR = 0x80000000u, // REPRESENTATION_INDEX << COUNT_MAX + AUDIO_CHANNEL_INDEX_HDR = 0x80000000u, // REPRESENTATION_INDEX << COUNT_MAX AUDIO_CHANNEL_INDEX_MASK_1 = 0x80000001u, // INDEX_HDR | (1 << 1) - 1 AUDIO_CHANNEL_INDEX_MASK_2 = 0x80000003u, // INDEX_HDR | (1 << 2) - 1 AUDIO_CHANNEL_INDEX_MASK_3 = 0x80000007u, // INDEX_HDR | (1 << 3) - 1 diff --git a/system/audio_hal_interface/fuzzer/libbt_audio_hal_a2dp_encoding_fuzzer.cpp b/system/audio_hal_interface/fuzzer/libbt_audio_hal_a2dp_encoding_fuzzer.cpp index e0c4a392cbf..5529f7939b1 100644 --- a/system/audio_hal_interface/fuzzer/libbt_audio_hal_a2dp_encoding_fuzzer.cpp +++ b/system/audio_hal_interface/fuzzer/libbt_audio_hal_a2dp_encoding_fuzzer.cpp @@ -26,9 +26,7 @@ using ::bluetooth::audio::a2dp::BluetoothAudioStatus; using ::bluetooth::audio::a2dp::update_codec_offloading_capabilities; extern "C" { -struct android_namespace_t* android_get_exported_namespace(const char*) { - return nullptr; -} +struct android_namespace_t* android_get_exported_namespace(const char*) { return nullptr; } } constexpr BluetoothAudioStatus kBluetoothAudioStatus[] = { @@ -44,32 +42,29 @@ constexpr int32_t kRandomStringLength = 256; static void source_init_delayed(void) {} constexpr btav_a2dp_codec_index_t kCodecIndices[] = { - BTAV_A2DP_CODEC_INDEX_SOURCE_SBC, BTAV_A2DP_CODEC_INDEX_SOURCE_AAC, - BTAV_A2DP_CODEC_INDEX_SOURCE_APTX, BTAV_A2DP_CODEC_INDEX_SOURCE_APTX_HD, - BTAV_A2DP_CODEC_INDEX_SOURCE_LDAC, BTAV_A2DP_CODEC_INDEX_SINK_SBC, - BTAV_A2DP_CODEC_INDEX_SINK_AAC, BTAV_A2DP_CODEC_INDEX_SINK_LDAC}; + BTAV_A2DP_CODEC_INDEX_SOURCE_SBC, BTAV_A2DP_CODEC_INDEX_SOURCE_AAC, + BTAV_A2DP_CODEC_INDEX_SOURCE_APTX, BTAV_A2DP_CODEC_INDEX_SOURCE_APTX_HD, + BTAV_A2DP_CODEC_INDEX_SOURCE_LDAC, BTAV_A2DP_CODEC_INDEX_SINK_SBC, + BTAV_A2DP_CODEC_INDEX_SINK_AAC, BTAV_A2DP_CODEC_INDEX_SINK_LDAC}; -std::vector> -CodecOffloadingPreferenceGenerator() { +std::vector> CodecOffloadingPreferenceGenerator() { std::vector> offloadingPreferences = { - std::vector(0)}; + std::vector(0)}; btav_a2dp_codec_config_t btavCodecConfig = {}; for (btav_a2dp_codec_index_t i : kCodecIndices) { btavCodecConfig.codec_type = i; auto duplicated_preferences = offloadingPreferences; - for (auto iter = duplicated_preferences.begin(); - iter != duplicated_preferences.end(); ++iter) { + for (auto iter = duplicated_preferences.begin(); iter != duplicated_preferences.end(); ++iter) { iter->push_back(btavCodecConfig); } - offloadingPreferences.insert(offloadingPreferences.end(), - duplicated_preferences.begin(), + offloadingPreferences.insert(offloadingPreferences.end(), duplicated_preferences.begin(), duplicated_preferences.end()); } return offloadingPreferences; } class A2dpEncodingFuzzer { - public: +public: ~A2dpEncodingFuzzer() { delete (mCodec); mCodec = nullptr; diff --git a/system/audio_hal_interface/fuzzer/libbt_audio_hal_client_interface_fuzzer.cpp b/system/audio_hal_interface/fuzzer/libbt_audio_hal_client_interface_fuzzer.cpp index 365897991af..c309d44b348 100644 --- a/system/audio_hal_interface/fuzzer/libbt_audio_hal_client_interface_fuzzer.cpp +++ b/system/audio_hal_interface/fuzzer/libbt_audio_hal_client_interface_fuzzer.cpp @@ -65,20 +65,17 @@ using ::bluetooth::audio::hidl::codec::IsCodecOffloadingEnabled; using ::bluetooth::audio::hidl::codec::UpdateOffloadingCapabilities; extern "C" { -struct android_namespace_t* android_get_exported_namespace(const char*) { - return nullptr; -} +struct android_namespace_t* android_get_exported_namespace(const char*) { return nullptr; } } constexpr SessionType kSessionTypes[] = { - SessionType::UNKNOWN, - SessionType::A2DP_SOFTWARE_ENCODING_DATAPATH, - SessionType::A2DP_HARDWARE_OFFLOAD_DATAPATH, - SessionType::HEARING_AID_SOFTWARE_ENCODING_DATAPATH, + SessionType::UNKNOWN, + SessionType::A2DP_SOFTWARE_ENCODING_DATAPATH, + SessionType::A2DP_HARDWARE_OFFLOAD_DATAPATH, + SessionType::HEARING_AID_SOFTWARE_ENCODING_DATAPATH, }; -constexpr bluetooth::audio::hidl::BluetoothAudioCtrlAck - kBluetoothAudioCtrlAcks[] = { +constexpr bluetooth::audio::hidl::BluetoothAudioCtrlAck kBluetoothAudioCtrlAcks[] = { bluetooth::audio::hidl::BluetoothAudioCtrlAck::SUCCESS_FINISHED, bluetooth::audio::hidl::BluetoothAudioCtrlAck::PENDING, bluetooth::audio::hidl::BluetoothAudioCtrlAck::FAILURE_UNSUPPORTED, @@ -87,68 +84,64 @@ constexpr bluetooth::audio::hidl::BluetoothAudioCtrlAck bluetooth::audio::hidl::BluetoothAudioCtrlAck::FAILURE}; constexpr SessionType_2_1 kSessionTypes_2_1[] = { - SessionType_2_1::UNKNOWN, - SessionType_2_1::A2DP_SOFTWARE_ENCODING_DATAPATH, - SessionType_2_1::A2DP_HARDWARE_OFFLOAD_DATAPATH, - SessionType_2_1::HEARING_AID_SOFTWARE_ENCODING_DATAPATH, - SessionType_2_1::LE_AUDIO_SOFTWARE_ENCODING_DATAPATH, - SessionType_2_1::LE_AUDIO_SOFTWARE_DECODED_DATAPATH, - SessionType_2_1::LE_AUDIO_HARDWARE_OFFLOAD_ENCODING_DATAPATH, - SessionType_2_1::LE_AUDIO_HARDWARE_OFFLOAD_DECODING_DATAPATH, + SessionType_2_1::UNKNOWN, + SessionType_2_1::A2DP_SOFTWARE_ENCODING_DATAPATH, + SessionType_2_1::A2DP_HARDWARE_OFFLOAD_DATAPATH, + SessionType_2_1::HEARING_AID_SOFTWARE_ENCODING_DATAPATH, + SessionType_2_1::LE_AUDIO_SOFTWARE_ENCODING_DATAPATH, + SessionType_2_1::LE_AUDIO_SOFTWARE_DECODED_DATAPATH, + SessionType_2_1::LE_AUDIO_HARDWARE_OFFLOAD_ENCODING_DATAPATH, + SessionType_2_1::LE_AUDIO_HARDWARE_OFFLOAD_DECODING_DATAPATH, }; constexpr SampleRate kSampleRates[] = { - SampleRate::RATE_UNKNOWN, SampleRate::RATE_44100, SampleRate::RATE_48000, - SampleRate::RATE_88200, SampleRate::RATE_96000, SampleRate::RATE_176400, - SampleRate::RATE_192000, SampleRate::RATE_16000, SampleRate::RATE_24000}; + SampleRate::RATE_UNKNOWN, SampleRate::RATE_44100, SampleRate::RATE_48000, + SampleRate::RATE_88200, SampleRate::RATE_96000, SampleRate::RATE_176400, + SampleRate::RATE_192000, SampleRate::RATE_16000, SampleRate::RATE_24000}; constexpr btav_a2dp_codec_sample_rate_t kBtavSampleRates[] = { - BTAV_A2DP_CODEC_SAMPLE_RATE_NONE, BTAV_A2DP_CODEC_SAMPLE_RATE_44100, - BTAV_A2DP_CODEC_SAMPLE_RATE_48000, BTAV_A2DP_CODEC_SAMPLE_RATE_88200, - BTAV_A2DP_CODEC_SAMPLE_RATE_96000, BTAV_A2DP_CODEC_SAMPLE_RATE_176400, - BTAV_A2DP_CODEC_SAMPLE_RATE_192000, BTAV_A2DP_CODEC_SAMPLE_RATE_16000, - BTAV_A2DP_CODEC_SAMPLE_RATE_24000}; + BTAV_A2DP_CODEC_SAMPLE_RATE_NONE, BTAV_A2DP_CODEC_SAMPLE_RATE_44100, + BTAV_A2DP_CODEC_SAMPLE_RATE_48000, BTAV_A2DP_CODEC_SAMPLE_RATE_88200, + BTAV_A2DP_CODEC_SAMPLE_RATE_96000, BTAV_A2DP_CODEC_SAMPLE_RATE_176400, + BTAV_A2DP_CODEC_SAMPLE_RATE_192000, BTAV_A2DP_CODEC_SAMPLE_RATE_16000, + BTAV_A2DP_CODEC_SAMPLE_RATE_24000}; constexpr SampleRate_2_1 kSampleRates_2_1[] = { - SampleRate_2_1::RATE_UNKNOWN, SampleRate_2_1::RATE_8000, - SampleRate_2_1::RATE_16000, SampleRate_2_1::RATE_24000, - SampleRate_2_1::RATE_32000, SampleRate_2_1::RATE_44100, - SampleRate_2_1::RATE_48000}; + SampleRate_2_1::RATE_UNKNOWN, SampleRate_2_1::RATE_8000, SampleRate_2_1::RATE_16000, + SampleRate_2_1::RATE_24000, SampleRate_2_1::RATE_32000, SampleRate_2_1::RATE_44100, + SampleRate_2_1::RATE_48000}; -constexpr BitsPerSample kBitsPerSamples[] = { - BitsPerSample::BITS_UNKNOWN, BitsPerSample::BITS_16, BitsPerSample::BITS_24, - BitsPerSample::BITS_32}; +constexpr BitsPerSample kBitsPerSamples[] = {BitsPerSample::BITS_UNKNOWN, BitsPerSample::BITS_16, + BitsPerSample::BITS_24, BitsPerSample::BITS_32}; constexpr btav_a2dp_codec_bits_per_sample_t kBtavA2dpCodecBitsPerSample[] = { - BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE, BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16, - BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24, BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32}; + BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE, BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16, + BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24, BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32}; -constexpr ChannelMode kChannelModes[] = { - ChannelMode::UNKNOWN, ChannelMode::MONO, ChannelMode::STEREO}; +constexpr ChannelMode kChannelModes[] = {ChannelMode::UNKNOWN, ChannelMode::MONO, + ChannelMode::STEREO}; constexpr btav_a2dp_codec_channel_mode_t kBtavA2dpCodecChannelModes[] = { - BTAV_A2DP_CODEC_CHANNEL_MODE_NONE, BTAV_A2DP_CODEC_CHANNEL_MODE_MONO, - BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO}; + BTAV_A2DP_CODEC_CHANNEL_MODE_NONE, BTAV_A2DP_CODEC_CHANNEL_MODE_MONO, + BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO}; constexpr uint16_t kPeerMtus[] = {660, 663, 883, 1005, 1500}; constexpr btav_a2dp_codec_index_t kCodecIndices[] = { - BTAV_A2DP_CODEC_INDEX_SOURCE_SBC, BTAV_A2DP_CODEC_INDEX_SOURCE_AAC, - BTAV_A2DP_CODEC_INDEX_SOURCE_APTX, BTAV_A2DP_CODEC_INDEX_SOURCE_APTX_HD, - BTAV_A2DP_CODEC_INDEX_SOURCE_LDAC, BTAV_A2DP_CODEC_INDEX_SINK_SBC, - BTAV_A2DP_CODEC_INDEX_SINK_AAC, BTAV_A2DP_CODEC_INDEX_SINK_LDAC}; - -class TestSinkTransport - : public bluetooth::audio::hidl::IBluetoothSinkTransportInstance { - private: - public: + BTAV_A2DP_CODEC_INDEX_SOURCE_SBC, BTAV_A2DP_CODEC_INDEX_SOURCE_AAC, + BTAV_A2DP_CODEC_INDEX_SOURCE_APTX, BTAV_A2DP_CODEC_INDEX_SOURCE_APTX_HD, + BTAV_A2DP_CODEC_INDEX_SOURCE_LDAC, BTAV_A2DP_CODEC_INDEX_SINK_SBC, + BTAV_A2DP_CODEC_INDEX_SINK_AAC, BTAV_A2DP_CODEC_INDEX_SINK_LDAC}; + +class TestSinkTransport : public bluetooth::audio::hidl::IBluetoothSinkTransportInstance { +private: +public: TestSinkTransport(SessionType session_type) - : bluetooth::audio::hidl::IBluetoothSinkTransportInstance(session_type, - {}){}; + : bluetooth::audio::hidl::IBluetoothSinkTransportInstance(session_type, {}) {} TestSinkTransport(SessionType_2_1 session_type_2_1) - : bluetooth::audio::hidl::IBluetoothSinkTransportInstance( - session_type_2_1, (AudioConfiguration_2_1){}){}; + : bluetooth::audio::hidl::IBluetoothSinkTransportInstance(session_type_2_1, + (AudioConfiguration_2_1){}) {} bluetooth::audio::hidl::BluetoothAudioCtrlAck StartRequest() override { return bluetooth::audio::hidl::BluetoothAudioCtrlAck::SUCCESS_FINISHED; @@ -160,28 +153,24 @@ class TestSinkTransport void StopRequest() override {} - bool GetPresentationPosition(uint64_t*, uint64_t*, timespec*) override { - return true; - } + bool GetPresentationPosition(uint64_t*, uint64_t*, timespec*) override { return true; } void MetadataChanged(const source_metadata_t&) override {} - void ResetPresentationPosition() override{}; + void ResetPresentationPosition() override {} - void LogBytesRead(size_t) override{}; + void LogBytesRead(size_t) override {} }; -class TestSourceTransport - : public bluetooth::audio::hidl::IBluetoothSourceTransportInstance { - private: - public: +class TestSourceTransport : public bluetooth::audio::hidl::IBluetoothSourceTransportInstance { +private: +public: TestSourceTransport(SessionType session_type) - : bluetooth::audio::hidl::IBluetoothSourceTransportInstance(session_type, - {}){}; + : bluetooth::audio::hidl::IBluetoothSourceTransportInstance(session_type, {}) {} TestSourceTransport(SessionType_2_1 session_type_2_1) - : bluetooth::audio::hidl::IBluetoothSourceTransportInstance( - session_type_2_1, (AudioConfiguration_2_1){}){}; + : bluetooth::audio::hidl::IBluetoothSourceTransportInstance(session_type_2_1, + (AudioConfiguration_2_1){}) {} bluetooth::audio::hidl::BluetoothAudioCtrlAck StartRequest() override { return bluetooth::audio::hidl::BluetoothAudioCtrlAck::SUCCESS_FINISHED; @@ -193,19 +182,17 @@ class TestSourceTransport void StopRequest() override {} - bool GetPresentationPosition(uint64_t*, uint64_t*, timespec*) override { - return true; - } + bool GetPresentationPosition(uint64_t*, uint64_t*, timespec*) override { return true; } void MetadataChanged(const source_metadata_t&) override {} - void ResetPresentationPosition() override{}; + void ResetPresentationPosition() override {} - void LogBytesWritten(size_t) override{}; + void LogBytesWritten(size_t) override {} }; class ClientInterfaceFuzzer { - public: +public: ~ClientInterfaceFuzzer() { delete (mFdp); delete (mTestSinkTransport); @@ -215,7 +202,7 @@ class ClientInterfaceFuzzer { } void process(const uint8_t* data, size_t size); - private: +private: FuzzedDataProvider* mFdp = nullptr; TestSinkTransport* mTestSinkTransport = nullptr; TestSourceTransport* mTestSourceTransport = nullptr; @@ -223,23 +210,18 @@ class ClientInterfaceFuzzer { BluetoothAudioSourceClientInterface* mClientIfSource = nullptr; }; -static CodecConfiguration SbcCodecConfigurationsGenerator( - FuzzedDataProvider* mFdp) { - SbcNumSubbands numSubbands[] = {SbcNumSubbands::SUBBAND_4, - SbcNumSubbands::SUBBAND_8}; +static CodecConfiguration SbcCodecConfigurationsGenerator(FuzzedDataProvider* mFdp) { + SbcNumSubbands numSubbands[] = {SbcNumSubbands::SUBBAND_4, SbcNumSubbands::SUBBAND_8}; - SbcAllocMethod allocMethods[] = {SbcAllocMethod::ALLOC_MD_S, - SbcAllocMethod::ALLOC_MD_L}; + SbcAllocMethod allocMethods[] = {SbcAllocMethod::ALLOC_MD_S, SbcAllocMethod::ALLOC_MD_L}; SbcChannelMode channelModes[] = { - SbcChannelMode::UNKNOWN, SbcChannelMode::JOINT_STEREO, - SbcChannelMode::STEREO, SbcChannelMode::DUAL, - SbcChannelMode::MONO, + SbcChannelMode::UNKNOWN, SbcChannelMode::JOINT_STEREO, SbcChannelMode::STEREO, + SbcChannelMode::DUAL, SbcChannelMode::MONO, }; - SbcBlockLength blockLengths[] = { - SbcBlockLength::BLOCKS_4, SbcBlockLength::BLOCKS_8, - SbcBlockLength::BLOCKS_12, SbcBlockLength::BLOCKS_16}; + SbcBlockLength blockLengths[] = {SbcBlockLength::BLOCKS_4, SbcBlockLength::BLOCKS_8, + SbcBlockLength::BLOCKS_12, SbcBlockLength::BLOCKS_16}; SbcParameters sbc = {}; sbc.sampleRate = mFdp->PickValueInArray(kSampleRates); @@ -261,11 +243,9 @@ static CodecConfiguration SbcCodecConfigurationsGenerator( return codecConfig; } -static CodecConfiguration AacCodecConfigurationsGenerator( - FuzzedDataProvider* mFdp) { - AacObjectType objectTypes[] = { - AacObjectType::MPEG2_LC, AacObjectType::MPEG4_LC, - AacObjectType::MPEG4_LTP, AacObjectType::MPEG4_SCALABLE}; +static CodecConfiguration AacCodecConfigurationsGenerator(FuzzedDataProvider* mFdp) { + AacObjectType objectTypes[] = {AacObjectType::MPEG2_LC, AacObjectType::MPEG4_LC, + AacObjectType::MPEG4_LTP, AacObjectType::MPEG4_SCALABLE}; AacVariableBitRate variableBitrates[] = {AacVariableBitRate::DISABLED, AacVariableBitRate::ENABLED}; @@ -287,17 +267,16 @@ static CodecConfiguration AacCodecConfigurationsGenerator( return codecConfig; } -static CodecConfiguration LdacCodecConfigurationsGenerator( - FuzzedDataProvider* mFdp) { - LdacQualityIndex qualityIndexes[] = { - LdacQualityIndex::QUALITY_HIGH, LdacQualityIndex::QUALITY_MID, - LdacQualityIndex::QUALITY_LOW, LdacQualityIndex::QUALITY_ABR}; +static CodecConfiguration LdacCodecConfigurationsGenerator(FuzzedDataProvider* mFdp) { + LdacQualityIndex qualityIndexes[] = {LdacQualityIndex::QUALITY_HIGH, + LdacQualityIndex::QUALITY_MID, LdacQualityIndex::QUALITY_LOW, + LdacQualityIndex::QUALITY_ABR}; LdacChannelMode kChannelModes[] = { - LdacChannelMode::UNKNOWN, - LdacChannelMode::STEREO, - LdacChannelMode::DUAL, - LdacChannelMode::MONO, + LdacChannelMode::UNKNOWN, + LdacChannelMode::STEREO, + LdacChannelMode::DUAL, + LdacChannelMode::MONO, }; LdacParameters ldac = {}; @@ -316,8 +295,7 @@ static CodecConfiguration LdacCodecConfigurationsGenerator( return codecConfig; } -static CodecConfiguration AptxCodecConfigurationsGenerator( - FuzzedDataProvider* mFdp) { +static CodecConfiguration AptxCodecConfigurationsGenerator(FuzzedDataProvider* mFdp) { CodecType codecTypes[] = {CodecType::APTX, CodecType::APTX_HD}; AptxParameters aptx = {}; @@ -335,20 +313,17 @@ static CodecConfiguration AptxCodecConfigurationsGenerator( return codecConfig; } -std::vector> -CodecOffloadingPreferenceGenerator() { +std::vector> CodecOffloadingPreferenceGenerator() { std::vector> offloadingPreferences = { - std::vector(0)}; + std::vector(0)}; btav_a2dp_codec_config_t a2dpCodecConfig = {}; for (btav_a2dp_codec_index_t i : kCodecIndices) { a2dpCodecConfig.codec_type = i; auto duplicated_preferences = offloadingPreferences; - for (auto iter = duplicated_preferences.begin(); - iter != duplicated_preferences.end(); ++iter) { + for (auto iter = duplicated_preferences.begin(); iter != duplicated_preferences.end(); ++iter) { iter->push_back(a2dpCodecConfig); } - offloadingPreferences.insert(offloadingPreferences.end(), - duplicated_preferences.begin(), + offloadingPreferences.insert(offloadingPreferences.end(), duplicated_preferences.begin(), duplicated_preferences.end()); } return offloadingPreferences; @@ -361,10 +336,8 @@ void ClientInterfaceFuzzer::process(const uint8_t* data, size_t size) { btav_a2dp_codec_config_t a2dpCodecConfig = {}; a2dpCodecConfig.sample_rate = mFdp->PickValueInArray(kBtavSampleRates); - a2dpCodecConfig.bits_per_sample = - mFdp->PickValueInArray(kBtavA2dpCodecBitsPerSample); - a2dpCodecConfig.channel_mode = - mFdp->PickValueInArray(kBtavA2dpCodecChannelModes); + a2dpCodecConfig.bits_per_sample = mFdp->PickValueInArray(kBtavA2dpCodecBitsPerSample); + a2dpCodecConfig.channel_mode = mFdp->PickValueInArray(kBtavA2dpCodecChannelModes); A2dpCodecToHalSampleRate(a2dpCodecConfig); A2dpCodecToHalBitsPerSample(a2dpCodecConfig); @@ -384,13 +357,11 @@ void ClientInterfaceFuzzer::process(const uint8_t* data, size_t size) { mTestSourceTransport = new TestSourceTransport(sessionType); } - mClientIfSink = - new BluetoothAudioSinkClientInterface(mTestSinkTransport, nullptr); + mClientIfSink = new BluetoothAudioSinkClientInterface(mTestSinkTransport, nullptr); mClientIfSink->GetTransportInstance(); mClientIfSink->IsValid(); - mClientIfSource = - new BluetoothAudioSourceClientInterface(mTestSourceTransport, nullptr); + mClientIfSource = new BluetoothAudioSourceClientInterface(mTestSourceTransport, nullptr); mClientIfSource->IsValid(); CodecConfiguration codecConfig = {}; @@ -409,10 +380,8 @@ void ClientInterfaceFuzzer::process(const uint8_t* data, size_t size) { break; } - if ((!isSessionType_2_1) && - (sessionType == SessionType::A2DP_HARDWARE_OFFLOAD_DATAPATH)) { - for (auto codec_offloading_preference : - CodecOffloadingPreferenceGenerator()) { + if ((!isSessionType_2_1) && (sessionType == SessionType::A2DP_HARDWARE_OFFLOAD_DATAPATH)) { + for (auto codec_offloading_preference : CodecOffloadingPreferenceGenerator()) { UpdateOffloadingCapabilities(codec_offloading_preference); update_codec_offloading_capabilities(codec_offloading_preference, false); } @@ -451,15 +420,13 @@ void ClientInterfaceFuzzer::process(const uint8_t* data, size_t size) { if (((bluetooth::audio::HalVersionManager::GetHalVersion() == bluetooth::audio::BluetoothAudioHalVersion::VERSION_2_1) && - (mTestSinkTransport->GetSessionType_2_1() != - SessionType_2_1::UNKNOWN)) || + (mTestSinkTransport->GetSessionType_2_1() != SessionType_2_1::UNKNOWN)) || (mTestSinkTransport->GetSessionType() != SessionType::UNKNOWN)) { mClientIfSink->RenewAudioProviderAndSession(); } mClientIfSink->StreamStarted(mFdp->PickValueInArray(kBluetoothAudioCtrlAcks)); - mClientIfSink->StreamSuspended( - mFdp->PickValueInArray(kBluetoothAudioCtrlAcks)); + mClientIfSink->StreamSuspended(mFdp->PickValueInArray(kBluetoothAudioCtrlAcks)); mClientIfSink->EndSession(); } diff --git a/system/audio_hal_interface/fuzzer/libbt_audio_hal_hearing_aid_software_encoding_fuzzer.cpp b/system/audio_hal_interface/fuzzer/libbt_audio_hal_hearing_aid_software_encoding_fuzzer.cpp index c146c097586..7c136aa5ef4 100644 --- a/system/audio_hal_interface/fuzzer/libbt_audio_hal_hearing_aid_software_encoding_fuzzer.cpp +++ b/system/audio_hal_interface/fuzzer/libbt_audio_hal_hearing_aid_software_encoding_fuzzer.cpp @@ -30,9 +30,7 @@ constexpr int32_t kPropertyValueMax = 92; constexpr int32_t kMaxBytes = 1000; extern "C" { -struct android_namespace_t* android_get_exported_namespace(const char*) { - return nullptr; -} +struct android_namespace_t* android_get_exported_namespace(const char*) { return nullptr; } } static void source_init_delayed(void) {} @@ -42,8 +40,8 @@ bool hearingAidOnResumeReq(bool /*start_media_task*/) { return true; } bool hearingAidOnSuspendReq() { return true; } auto streamCb = bluetooth::audio::hearing_aid::StreamCallbacks{ - .on_resume_ = hearingAidOnResumeReq, - .on_suspend_ = hearingAidOnSuspendReq, + .on_resume_ = hearingAidOnResumeReq, + .on_suspend_ = hearingAidOnSuspendReq, }; extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { diff --git a/system/audio_hal_interface/fuzzer/libbt_audio_hal_le_audio_software_fuzzer.cpp b/system/audio_hal_interface/fuzzer/libbt_audio_hal_le_audio_software_fuzzer.cpp index 691979ae8eb..e382dbeb627 100644 --- a/system/audio_hal_interface/fuzzer/libbt_audio_hal_le_audio_software_fuzzer.cpp +++ b/system/audio_hal_interface/fuzzer/libbt_audio_hal_le_audio_software_fuzzer.cpp @@ -31,19 +31,14 @@ constexpr uint8_t kChannelCount[] = {1, 2}; constexpr uint32_t kSampleRates[] = {16000, 24000, 44100, 48000, 88200, 96000}; extern "C" { -struct android_namespace_t* android_get_exported_namespace(const char*) { - return nullptr; -} +struct android_namespace_t* android_get_exported_namespace(const char*) { return nullptr; } } bool onResume(bool) { return true; } bool onSuspend(void) { return true; } -bool onMetadataUpdate(const source_metadata_v7_t&, - bluetooth::le_audio::DsaMode) { - return true; -} +bool onMetadataUpdate(const source_metadata_v7_t&, bluetooth::le_audio::DsaMode) { return true; } bool onSinkMetadataUpdate(const sink_metadata_v7_t&) { return true; } @@ -60,18 +55,17 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { LeAudioClientInterface* interface = LeAudioClientInterface::Get(); - bluetooth::audio::le_audio::StreamCallbacks streamCb = { - onResume, onSuspend, onMetadataUpdate, onSinkMetadataUpdate}; + bluetooth::audio::le_audio::StreamCallbacks streamCb = {onResume, onSuspend, onMetadataUpdate, + onSinkMetadataUpdate}; if (!interface->IsSourceAcquired()) { - LeAudioClientInterface::Source* source = - interface->GetSource(streamCb, &messageLoopThread); + LeAudioClientInterface::Source* source = interface->GetSource(streamCb, &messageLoopThread); if (source != nullptr) { uint16_t delay = fdp.ConsumeIntegral(); source->SetRemoteDelay(delay); LeAudioClientInterface::PcmParameters params; - params.data_interval_us = fdp.ConsumeIntegralInRange( - 1000, std::numeric_limits::max()); + params.data_interval_us = + fdp.ConsumeIntegralInRange(1000, std::numeric_limits::max()); params.sample_rate = fdp.PickValueInArray(kSampleRates); params.bits_per_sample = fdp.PickValueInArray(kBitsPerSample); params.channels_count = fdp.PickValueInArray(kChannelCount); @@ -84,14 +78,13 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { } if (!interface->IsUnicastSinkAcquired()) { - LeAudioClientInterface::Sink* sink = - interface->GetSink(streamCb, &messageLoopThread, false); + LeAudioClientInterface::Sink* sink = interface->GetSink(streamCb, &messageLoopThread, false); if (sink != nullptr) { uint16_t delay = fdp.ConsumeIntegral(); sink->SetRemoteDelay(delay); LeAudioClientInterface::PcmParameters params; - params.data_interval_us = fdp.ConsumeIntegralInRange( - 1000, std::numeric_limits::max()); + params.data_interval_us = + fdp.ConsumeIntegralInRange(1000, std::numeric_limits::max()); params.sample_rate = fdp.PickValueInArray(kSampleRates); params.bits_per_sample = fdp.PickValueInArray(kBitsPerSample); params.channels_count = fdp.PickValueInArray(kChannelCount); diff --git a/system/audio_hal_interface/hal_version_manager.cc b/system/audio_hal_interface/hal_version_manager.cc index c4e01bc9079..19c48c58da2 100644 --- a/system/audio_hal_interface/hal_version_manager.cc +++ b/system/audio_hal_interface/hal_version_manager.cc @@ -29,11 +29,10 @@ namespace bluetooth { namespace audio { -using ::aidl::android::hardware::bluetooth::audio:: - IBluetoothAudioProviderFactory; +using ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProviderFactory; static const std::string kDefaultAudioProviderFactoryInterface = - std::string() + IBluetoothAudioProviderFactory::descriptor + "/default"; + std::string() + IBluetoothAudioProviderFactory::descriptor + "/default"; std::string toString(BluetoothAudioHalTransport transport) { switch (transport) { @@ -49,23 +48,23 @@ std::string toString(BluetoothAudioHalTransport transport) { } const BluetoothAudioHalVersion BluetoothAudioHalVersion::VERSION_UNAVAILABLE = - BluetoothAudioHalVersion(); + BluetoothAudioHalVersion(); const BluetoothAudioHalVersion BluetoothAudioHalVersion::VERSION_2_0 = - BluetoothAudioHalVersion(BluetoothAudioHalTransport::HIDL, 2, 0); + BluetoothAudioHalVersion(BluetoothAudioHalTransport::HIDL, 2, 0); const BluetoothAudioHalVersion BluetoothAudioHalVersion::VERSION_2_1 = - BluetoothAudioHalVersion(BluetoothAudioHalTransport::HIDL, 2, 1); + BluetoothAudioHalVersion(BluetoothAudioHalTransport::HIDL, 2, 1); const BluetoothAudioHalVersion BluetoothAudioHalVersion::VERSION_AIDL_V1 = - BluetoothAudioHalVersion(BluetoothAudioHalTransport::AIDL, 1, 0); + BluetoothAudioHalVersion(BluetoothAudioHalTransport::AIDL, 1, 0); const BluetoothAudioHalVersion BluetoothAudioHalVersion::VERSION_AIDL_V2 = - BluetoothAudioHalVersion(BluetoothAudioHalTransport::AIDL, 2, 0); + BluetoothAudioHalVersion(BluetoothAudioHalTransport::AIDL, 2, 0); const BluetoothAudioHalVersion BluetoothAudioHalVersion::VERSION_AIDL_V3 = - BluetoothAudioHalVersion(BluetoothAudioHalTransport::AIDL, 3, 0); + BluetoothAudioHalVersion(BluetoothAudioHalTransport::AIDL, 3, 0); const BluetoothAudioHalVersion BluetoothAudioHalVersion::VERSION_AIDL_V4 = - BluetoothAudioHalVersion(BluetoothAudioHalTransport::AIDL, 4, 0); + BluetoothAudioHalVersion(BluetoothAudioHalTransport::AIDL, 4, 0); // Ideally HalVersionManager can be a singleton class std::unique_ptr HalVersionManager::instance_ptr = - std::make_unique(); + std::make_unique(); /** * A singleton implementation to get the AIDL interface version. @@ -73,13 +72,11 @@ std::unique_ptr HalVersionManager::instance_ptr = BluetoothAudioHalVersion GetAidlInterfaceVersion() { static auto aidl_version = []() -> BluetoothAudioHalVersion { int version = 0; - auto provider_factory = IBluetoothAudioProviderFactory::fromBinder( - ::ndk::SpAIBinder(AServiceManager_waitForService( - kDefaultAudioProviderFactoryInterface.c_str()))); + auto provider_factory = IBluetoothAudioProviderFactory::fromBinder(::ndk::SpAIBinder( + AServiceManager_waitForService(kDefaultAudioProviderFactoryInterface.c_str()))); if (provider_factory == nullptr) { - log::error( - "getInterfaceVersion: Can't get aidl version from unknown factory"); + log::error("getInterfaceVersion: Can't get aidl version from unknown factory"); return BluetoothAudioHalVersion::VERSION_UNAVAILABLE; } @@ -90,8 +87,7 @@ BluetoothAudioHalVersion GetAidlInterfaceVersion() { return BluetoothAudioHalVersion::VERSION_UNAVAILABLE; } - return BluetoothAudioHalVersion(BluetoothAudioHalTransport::AIDL, version, - 0); + return BluetoothAudioHalVersion(BluetoothAudioHalTransport::AIDL, version, 0); }(); return aidl_version; @@ -106,17 +102,15 @@ BluetoothAudioHalVersion HalVersionManager::GetHalVersion() { return instance_ptr->hal_version_; } -android::sp -HalVersionManager::GetProvidersFactory_2_1() { +android::sp HalVersionManager::GetProvidersFactory_2_1() { std::lock_guard guard(instance_ptr->mutex_); if (instance_ptr->hal_version_ != BluetoothAudioHalVersion::VERSION_2_1) { return nullptr; } android::sp providers_factory = - IBluetoothAudioProvidersFactory_2_1::getService(); - log::assert_that( - providers_factory != nullptr, - "V2_1::IBluetoothAudioProvidersFactory::getService() failed"); + IBluetoothAudioProvidersFactory_2_1::getService(); + log::assert_that(providers_factory != nullptr, + "V2_1::IBluetoothAudioProvidersFactory::getService() failed"); log::info("V2_1::IBluetoothAudioProvidersFactory::getService() returned {}{}", fmt::ptr(providers_factory.get()), @@ -124,18 +118,16 @@ HalVersionManager::GetProvidersFactory_2_1() { return providers_factory; } -android::sp -HalVersionManager::GetProvidersFactory_2_0() { +android::sp HalVersionManager::GetProvidersFactory_2_0() { std::unique_lock guard(instance_ptr->mutex_); if (instance_ptr->hal_version_ == BluetoothAudioHalVersion::VERSION_2_1) { guard.unlock(); return instance_ptr->GetProvidersFactory_2_1(); } android::sp providers_factory = - IBluetoothAudioProvidersFactory_2_0::getService(); - log::assert_that( - providers_factory != nullptr, - "V2_0::IBluetoothAudioProvidersFactory::getService() failed"); + IBluetoothAudioProvidersFactory_2_0::getService(); + log::assert_that(providers_factory != nullptr, + "V2_0::IBluetoothAudioProvidersFactory::getService() failed"); log::info("V2_0::IBluetoothAudioProvidersFactory::getService() returned {}{}", fmt::ptr(providers_factory.get()), @@ -146,27 +138,23 @@ HalVersionManager::GetProvidersFactory_2_0() { HalVersionManager::HalVersionManager() { hal_transport_ = BluetoothAudioHalTransport::UNKNOWN; - if (AServiceManager_checkService( - kDefaultAudioProviderFactoryInterface.c_str()) != nullptr) { + if (AServiceManager_checkService(kDefaultAudioProviderFactoryInterface.c_str()) != nullptr) { hal_version_ = GetAidlInterfaceVersion(); hal_transport_ = BluetoothAudioHalTransport::AIDL; return; } auto service_manager = android::hardware::defaultServiceManager1_2(); - log::assert_that(service_manager != nullptr, - "assert failed: service_manager != nullptr"); + log::assert_that(service_manager != nullptr, "assert failed: service_manager != nullptr"); size_t instance_count = 0; auto listManifestByInterface_cb = - [&instance_count]( - const hidl_vec& instanceNames) { - instance_count = instanceNames.size(); - }; - auto hidl_retval = service_manager->listManifestByInterface( - kFullyQualifiedInterfaceName_2_1, listManifestByInterface_cb); + [&instance_count](const hidl_vec& instanceNames) { + instance_count = instanceNames.size(); + }; + auto hidl_retval = service_manager->listManifestByInterface(kFullyQualifiedInterfaceName_2_1, + listManifestByInterface_cb); if (!hidl_retval.isOk()) { - log::fatal("IServiceManager::listByInterface failure: {}", - hidl_retval.description()); + log::fatal("IServiceManager::listByInterface failure: {}", hidl_retval.description()); return; } @@ -176,11 +164,10 @@ HalVersionManager::HalVersionManager() { return; } - hidl_retval = service_manager->listManifestByInterface( - kFullyQualifiedInterfaceName_2_0, listManifestByInterface_cb); + hidl_retval = service_manager->listManifestByInterface(kFullyQualifiedInterfaceName_2_0, + listManifestByInterface_cb); if (!hidl_retval.isOk()) { - log::fatal("IServiceManager::listByInterface failure: {}", - hidl_retval.description()); + log::fatal("IServiceManager::listByInterface failure: {}", hidl_retval.description()); return; } diff --git a/system/audio_hal_interface/hal_version_manager.h b/system/audio_hal_interface/hal_version_manager.h index 8743219025b..d19785f0782 100644 --- a/system/audio_hal_interface/hal_version_manager.h +++ b/system/audio_hal_interface/hal_version_manager.h @@ -24,15 +24,15 @@ namespace audio { using ::android::hardware::hidl_vec; -using IBluetoothAudioProvidersFactory_2_0 = ::android::hardware::bluetooth:: - audio::V2_0::IBluetoothAudioProvidersFactory; -using IBluetoothAudioProvidersFactory_2_1 = ::android::hardware::bluetooth:: - audio::V2_1::IBluetoothAudioProvidersFactory; +using IBluetoothAudioProvidersFactory_2_0 = + ::android::hardware::bluetooth::audio::V2_0::IBluetoothAudioProvidersFactory; +using IBluetoothAudioProvidersFactory_2_1 = + ::android::hardware::bluetooth::audio::V2_1::IBluetoothAudioProvidersFactory; constexpr char kFullyQualifiedInterfaceName_2_0[] = - "android.hardware.bluetooth.audio@2.0::IBluetoothAudioProvidersFactory"; + "android.hardware.bluetooth.audio@2.0::IBluetoothAudioProvidersFactory"; constexpr char kFullyQualifiedInterfaceName_2_1[] = - "android.hardware.bluetooth.audio@2.1::IBluetoothAudioProvidersFactory"; + "android.hardware.bluetooth.audio@2.1::IBluetoothAudioProvidersFactory"; /** * The type of HAL transport, it's important to have @@ -52,10 +52,10 @@ std::string toString(BluetoothAudioHalTransport transport); * A hal version class with built-in comparison operators. */ class BluetoothAudioHalVersion { - public: - BluetoothAudioHalVersion(BluetoothAudioHalTransport transport = - BluetoothAudioHalTransport::UNKNOWN, - uint16_t major = 0, uint16_t minor = 0) +public: + BluetoothAudioHalVersion( + BluetoothAudioHalTransport transport = BluetoothAudioHalTransport::UNKNOWN, + uint16_t major = 0, uint16_t minor = 0) : mTransport(transport), mMajor(major), mMinor(minor) {} bool isHIDL() const { return mTransport == BluetoothAudioHalTransport::HIDL; } @@ -64,28 +64,22 @@ class BluetoothAudioHalVersion { BluetoothAudioHalTransport getTransport() const { return mTransport; } inline bool operator!=(const BluetoothAudioHalVersion& rhs) const { - return std::tie(mTransport, mMajor, mMinor) != - std::tie(rhs.mTransport, rhs.mMajor, rhs.mMinor); + return std::tie(mTransport, mMajor, mMinor) != std::tie(rhs.mTransport, rhs.mMajor, rhs.mMinor); } inline bool operator<(const BluetoothAudioHalVersion& rhs) const { - return std::tie(mTransport, mMajor, mMinor) < - std::tie(rhs.mTransport, rhs.mMajor, rhs.mMinor); + return std::tie(mTransport, mMajor, mMinor) < std::tie(rhs.mTransport, rhs.mMajor, rhs.mMinor); } inline bool operator<=(const BluetoothAudioHalVersion& rhs) const { - return std::tie(mTransport, mMajor, mMinor) <= - std::tie(rhs.mTransport, rhs.mMajor, rhs.mMinor); + return std::tie(mTransport, mMajor, mMinor) <= std::tie(rhs.mTransport, rhs.mMajor, rhs.mMinor); } inline bool operator==(const BluetoothAudioHalVersion& rhs) const { - return std::tie(mTransport, mMajor, mMinor) == - std::tie(rhs.mTransport, rhs.mMajor, rhs.mMinor); + return std::tie(mTransport, mMajor, mMinor) == std::tie(rhs.mTransport, rhs.mMajor, rhs.mMinor); } inline bool operator>(const BluetoothAudioHalVersion& rhs) const { - return std::tie(mTransport, mMajor, mMinor) > - std::tie(rhs.mTransport, rhs.mMajor, rhs.mMinor); + return std::tie(mTransport, mMajor, mMinor) > std::tie(rhs.mTransport, rhs.mMajor, rhs.mMinor); } inline bool operator>=(const BluetoothAudioHalVersion& rhs) const { - return std::tie(mTransport, mMajor, mMinor) >= - std::tie(rhs.mTransport, rhs.mMajor, rhs.mMinor); + return std::tie(mTransport, mMajor, mMinor) >= std::tie(rhs.mTransport, rhs.mMajor, rhs.mMinor); } inline std::string toString() const { @@ -107,27 +101,25 @@ class BluetoothAudioHalVersion { static const BluetoothAudioHalVersion VERSION_AIDL_V3; static const BluetoothAudioHalVersion VERSION_AIDL_V4; - private: +private: BluetoothAudioHalTransport mTransport = BluetoothAudioHalTransport::UNKNOWN; uint16_t mMajor = 0; uint16_t mMinor = 0; }; class HalVersionManager { - public: +public: static BluetoothAudioHalVersion GetHalVersion(); static BluetoothAudioHalTransport GetHalTransport(); - static android::sp - GetProvidersFactory_2_1(); + static android::sp GetProvidersFactory_2_1(); - static android::sp - GetProvidersFactory_2_0(); + static android::sp GetProvidersFactory_2_0(); HalVersionManager(); - private: +private: static std::unique_ptr instance_ptr; std::mutex mutex_; diff --git a/system/audio_hal_interface/hal_version_manager_host.cc b/system/audio_hal_interface/hal_version_manager_host.cc index 4cf8d80ba6e..1f5483e90bb 100644 --- a/system/audio_hal_interface/hal_version_manager_host.cc +++ b/system/audio_hal_interface/hal_version_manager_host.cc @@ -20,19 +20,19 @@ namespace bluetooth { namespace audio { const BluetoothAudioHalVersion BluetoothAudioHalVersion::VERSION_UNAVAILABLE = - BluetoothAudioHalVersion(); + BluetoothAudioHalVersion(); const BluetoothAudioHalVersion BluetoothAudioHalVersion::VERSION_2_0 = - BluetoothAudioHalVersion(BluetoothAudioHalTransport::HIDL, 2, 0); + BluetoothAudioHalVersion(BluetoothAudioHalTransport::HIDL, 2, 0); const BluetoothAudioHalVersion BluetoothAudioHalVersion::VERSION_2_1 = - BluetoothAudioHalVersion(BluetoothAudioHalTransport::HIDL, 2, 1); + BluetoothAudioHalVersion(BluetoothAudioHalTransport::HIDL, 2, 1); const BluetoothAudioHalVersion BluetoothAudioHalVersion::VERSION_AIDL_V1 = - BluetoothAudioHalVersion(BluetoothAudioHalTransport::AIDL, 1, 0); + BluetoothAudioHalVersion(BluetoothAudioHalTransport::AIDL, 1, 0); const BluetoothAudioHalVersion BluetoothAudioHalVersion::VERSION_AIDL_V2 = - BluetoothAudioHalVersion(BluetoothAudioHalTransport::AIDL, 2, 0); + BluetoothAudioHalVersion(BluetoothAudioHalTransport::AIDL, 2, 0); const BluetoothAudioHalVersion BluetoothAudioHalVersion::VERSION_AIDL_V3 = - BluetoothAudioHalVersion(BluetoothAudioHalTransport::AIDL, 3, 0); + BluetoothAudioHalVersion(BluetoothAudioHalTransport::AIDL, 3, 0); const BluetoothAudioHalVersion BluetoothAudioHalVersion::VERSION_AIDL_V4 = - BluetoothAudioHalVersion(BluetoothAudioHalTransport::AIDL, 4, 0); + BluetoothAudioHalVersion(BluetoothAudioHalTransport::AIDL, 4, 0); std::unique_ptr HalVersionManager::instance_ptr = nullptr; @@ -44,13 +44,11 @@ BluetoothAudioHalTransport HalVersionManager::GetHalTransport() { return BluetoothAudioHalTransport::UNKNOWN; } -android::sp -HalVersionManager::GetProvidersFactory_2_1() { +android::sp HalVersionManager::GetProvidersFactory_2_1() { return nullptr; } -android::sp -HalVersionManager::GetProvidersFactory_2_0() { +android::sp HalVersionManager::GetProvidersFactory_2_0() { return nullptr; } diff --git a/system/audio_hal_interface/hearing_aid_software_encoding.cc b/system/audio_hal_interface/hearing_aid_software_encoding.cc index ed1be1d5e3e..88cc3c783b3 100644 --- a/system/audio_hal_interface/hearing_aid_software_encoding.cc +++ b/system/audio_hal_interface/hearing_aid_software_encoding.cc @@ -26,18 +26,15 @@ namespace hearing_aid { // Check if new bluetooth_audio is enabled bool is_hal_enabled() { - if (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::HIDL) { + if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::HIDL) { return hidl::hearing_aid::is_hal_2_0_enabled(); } return aidl::hearing_aid::is_hal_enabled(); } // Initialize BluetoothAudio HAL: openProvider -bool init(StreamCallbacks stream_cb, - bluetooth::common::MessageLoopThread* message_loop) { - if (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::HIDL) { +bool init(StreamCallbacks stream_cb, bluetooth::common::MessageLoopThread* message_loop) { + if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::HIDL) { return hidl::hearing_aid::init(stream_cb, message_loop); } return aidl::hearing_aid::init(stream_cb, message_loop); @@ -45,8 +42,7 @@ bool init(StreamCallbacks stream_cb, // Clean up BluetoothAudio HAL void cleanup() { - if (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::HIDL) { + if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::HIDL) { hidl::hearing_aid::cleanup(); return; } @@ -55,8 +51,7 @@ void cleanup() { // Send command to the BluetoothAudio HAL: StartSession, EndSession void start_session() { - if (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::HIDL) { + if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::HIDL) { hidl::hearing_aid::start_session(); return; } @@ -64,8 +59,7 @@ void start_session() { } void end_session() { - if (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::HIDL) { + if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::HIDL) { hidl::hearing_aid::end_session(); return; } @@ -73,8 +67,7 @@ void end_session() { } void set_remote_delay(uint16_t delay_report_ms) { - if (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::HIDL) { + if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::HIDL) { hidl::hearing_aid::set_remote_delay(delay_report_ms); return; } @@ -83,8 +76,7 @@ void set_remote_delay(uint16_t delay_report_ms) { // Read from the FMQ of BluetoothAudio HAL size_t read(uint8_t* p_buf, uint32_t len) { - if (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::HIDL) { + if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::HIDL) { return hidl::hearing_aid::read(p_buf, len); } return aidl::hearing_aid::read(p_buf, len); diff --git a/system/audio_hal_interface/hearing_aid_software_encoding.h b/system/audio_hal_interface/hearing_aid_software_encoding.h index ec18c54de9a..8e3db304f2f 100644 --- a/system/audio_hal_interface/hearing_aid_software_encoding.h +++ b/system/audio_hal_interface/hearing_aid_software_encoding.h @@ -33,8 +33,7 @@ struct StreamCallbacks { bool is_hal_enabled(); // Initialize BluetoothAudio HAL: openProvider -bool init(StreamCallbacks stream_cb, - bluetooth::common::MessageLoopThread* message_loop); +bool init(StreamCallbacks stream_cb, bluetooth::common::MessageLoopThread* message_loop); // Clean up BluetoothAudio HAL void cleanup(); diff --git a/system/audio_hal_interface/hearing_aid_software_encoding_host.cc b/system/audio_hal_interface/hearing_aid_software_encoding_host.cc index 5a66ccd8a59..a085b650d7a 100644 --- a/system/audio_hal_interface/hearing_aid_software_encoding_host.cc +++ b/system/audio_hal_interface/hearing_aid_software_encoding_host.cc @@ -22,8 +22,7 @@ namespace hearing_aid { bool is_hal_enabled() { return false; } -bool init(StreamCallbacks stream_cb, - bluetooth::common::MessageLoopThread* message_loop) { +bool init(StreamCallbacks stream_cb, bluetooth::common::MessageLoopThread* message_loop) { return false; } diff --git a/system/audio_hal_interface/hfp_client_interface.cc b/system/audio_hal_interface/hfp_client_interface.cc index 00cd9e29a72..98e61ae68d7 100644 --- a/system/audio_hal_interface/hfp_client_interface.cc +++ b/system/audio_hal_interface/hfp_client_interface.cc @@ -29,8 +29,7 @@ using ::bluetooth::audio::aidl::hfp::HfpDecodingTransport; using ::bluetooth::audio::aidl::hfp::HfpEncodingTransport; -using AudioConfiguration = - ::aidl::android::hardware::bluetooth::audio::AudioConfiguration; +using AudioConfiguration = ::aidl::android::hardware::bluetooth::audio::AudioConfiguration; using ::aidl::android::hardware::bluetooth::audio::ChannelMode; using ::aidl::android::hardware::bluetooth::audio::CodecId; using ::aidl::android::hardware::bluetooth::audio::HfpConfiguration; @@ -49,30 +48,26 @@ aidl::BluetoothAudioSourceClientInterface* get_encode_client_interface() { return HfpEncodingTransport::active_hal_interface; } -HfpDecodingTransport* get_decode_transport_instance() { - return HfpDecodingTransport::instance_; -} +HfpDecodingTransport* get_decode_transport_instance() { return HfpDecodingTransport::instance_; } -HfpDecodingTransport* get_encode_transport_instance() { - return HfpDecodingTransport::instance_; -} +HfpDecodingTransport* get_encode_transport_instance() { return HfpDecodingTransport::instance_; } PcmConfiguration get_default_pcm_configuration() { PcmConfiguration pcm_config{ - .sampleRateHz = 8000, - .channelMode = ChannelMode::MONO, - .bitsPerSample = 16, - .dataIntervalUs = 7500, + .sampleRateHz = 8000, + .channelMode = ChannelMode::MONO, + .bitsPerSample = 16, + .dataIntervalUs = 7500, }; return pcm_config; } HfpConfiguration get_default_hfp_configuration() { HfpConfiguration hfp_config{ - .codecId = CodecId::Core::CVSD, - .connectionHandle = 6, - .nrec = false, - .controllerCodec = true, + .codecId = CodecId::Core::CVSD, + .connectionHandle = 6, + .nrec = false, + .controllerCodec = true, }; return hfp_config; } @@ -92,26 +87,21 @@ CodecId sco_codec_to_hal_codec(tBTA_AG_UUID_CODEC sco_codec) { } } -AudioConfiguration offload_config_to_hal_audio_config( - const ::hfp::offload_config& offload_config) { +AudioConfiguration offload_config_to_hal_audio_config(const ::hfp::offload_config& offload_config) { HfpConfiguration hfp_config{ - .codecId = sco_codec_to_hal_codec(offload_config.sco_codec), - .connectionHandle = offload_config.connection_handle, - .nrec = offload_config.is_nrec, - .controllerCodec = offload_config.is_controller_codec, + .codecId = sco_codec_to_hal_codec(offload_config.sco_codec), + .connectionHandle = offload_config.connection_handle, + .nrec = offload_config.is_nrec, + .controllerCodec = offload_config.is_controller_codec, }; return AudioConfiguration(hfp_config); } -bool is_hal_enabled() { - return !osi_property_get_bool(BLUETOOTH_AUDIO_HAL_PROP_DISABLED, false); -} +bool is_hal_enabled() { return !osi_property_get_bool(BLUETOOTH_AUDIO_HAL_PROP_DISABLED, false); } bool is_aidl_support_hfp() { - return HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::AIDL && - HalVersionManager::GetHalVersion() >= - BluetoothAudioHalVersion::VERSION_AIDL_V4; + return HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::AIDL && + HalVersionManager::GetHalVersion() >= BluetoothAudioHalVersion::VERSION_AIDL_V4; } // Parent client implementation @@ -150,8 +140,7 @@ void HfpClientInterface::Decode::StartSession() { } log::info("decode"); AudioConfiguration audio_config; - audio_config.set( - get_default_pcm_configuration()); + audio_config.set(get_default_pcm_configuration()); if (!get_decode_client_interface()->UpdateAudioConfig(audio_config)) { log::error("cannot update audio config to HAL"); return; @@ -173,7 +162,7 @@ void HfpClientInterface::Decode::StopSession() { } void HfpClientInterface::Decode::UpdateAudioConfigToHal( - const ::hfp::offload_config& offload_config) { + const ::hfp::offload_config& offload_config) { if (!is_aidl_support_hfp()) { log::warn("Unsupported HIDL or AIDL version"); return; @@ -198,7 +187,7 @@ void HfpClientInterface::Decode::ConfirmStreamingRequest() { switch (pending_cmd) { case aidl::hfp::HFP_CTRL_CMD_START: aidl::hfp::HfpDecodingTransport::software_hal_interface->StreamStarted( - aidl::BluetoothAudioCtrlAck::SUCCESS_FINISHED); + aidl::BluetoothAudioCtrlAck::SUCCESS_FINISHED); instance->ResetPendingCmd(); return; case aidl::hfp::HFP_CTRL_CMD_NONE: @@ -215,7 +204,7 @@ void HfpClientInterface::Decode::CancelStreamingRequest() { switch (pending_cmd) { case aidl::hfp::HFP_CTRL_CMD_START: aidl::hfp::HfpDecodingTransport::software_hal_interface->StreamStarted( - aidl::BluetoothAudioCtrlAck::FAILURE); + aidl::BluetoothAudioCtrlAck::FAILURE); instance->ResetPendingCmd(); return; case aidl::hfp::HFP_CTRL_CMD_NONE: @@ -224,7 +213,7 @@ void HfpClientInterface::Decode::CancelStreamingRequest() { case aidl::hfp::HFP_CTRL_CMD_SUSPEND: log::info("suspends"); aidl::hfp::HfpEncodingTransport::software_hal_interface->StreamSuspended( - aidl::BluetoothAudioCtrlAck::SUCCESS_FINISHED); + aidl::BluetoothAudioCtrlAck::SUCCESS_FINISHED); instance->ResetPendingCmd(); return; default: @@ -233,7 +222,7 @@ void HfpClientInterface::Decode::CancelStreamingRequest() { } HfpClientInterface::Decode* HfpClientInterface::GetDecode( - bluetooth::common::MessageLoopThread* /*message_loop*/) { + bluetooth::common::MessageLoopThread* /*message_loop*/) { if (!is_aidl_support_hfp()) { log::warn("Unsupported HIDL or AIDL version"); return nullptr; @@ -248,11 +237,10 @@ HfpClientInterface::Decode* HfpClientInterface::GetDecode( log::info("decode"); - HfpDecodingTransport::instance_ = new HfpDecodingTransport( - aidl::SessionType::HFP_SOFTWARE_DECODING_DATAPATH); + HfpDecodingTransport::instance_ = + new HfpDecodingTransport(aidl::SessionType::HFP_SOFTWARE_DECODING_DATAPATH); HfpDecodingTransport::software_hal_interface = - new aidl::BluetoothAudioSinkClientInterface( - HfpDecodingTransport::instance_); + new aidl::BluetoothAudioSinkClientInterface(HfpDecodingTransport::instance_); if (!HfpDecodingTransport::software_hal_interface->IsValid()) { log::warn("BluetoothAudio HAL for HFP is invalid"); delete HfpDecodingTransport::software_hal_interface; @@ -262,8 +250,7 @@ HfpClientInterface::Decode* HfpClientInterface::GetDecode( return nullptr; } - HfpDecodingTransport::active_hal_interface = - HfpDecodingTransport::software_hal_interface; + HfpDecodingTransport::active_hal_interface = HfpDecodingTransport::software_hal_interface; return decode_; } @@ -275,7 +262,9 @@ bool HfpClientInterface::ReleaseDecode(HfpClientInterface::Decode* decode) { } log::info("decode"); - if (get_decode_client_interface()) decode->Cleanup(); + if (get_decode_client_interface()) { + decode->Cleanup(); + } delete decode_; decode_ = nullptr; @@ -302,8 +291,7 @@ void HfpClientInterface::Encode::StartSession() { } log::info("encode"); AudioConfiguration audio_config; - audio_config.set( - get_default_pcm_configuration()); + audio_config.set(get_default_pcm_configuration()); if (!get_encode_client_interface()->UpdateAudioConfig(audio_config)) { log::error("cannot update audio config to HAL"); return; @@ -325,7 +313,7 @@ void HfpClientInterface::Encode::StopSession() { } void HfpClientInterface::Encode::UpdateAudioConfigToHal( - const ::hfp::offload_config& offload_config) { + const ::hfp::offload_config& offload_config) { if (!is_aidl_support_hfp()) { log::warn("Unsupported HIDL or AIDL version"); return; @@ -350,7 +338,7 @@ void HfpClientInterface::Encode::ConfirmStreamingRequest() { switch (pending_cmd) { case aidl::hfp::HFP_CTRL_CMD_START: aidl::hfp::HfpEncodingTransport::software_hal_interface->StreamStarted( - aidl::BluetoothAudioCtrlAck::SUCCESS_FINISHED); + aidl::BluetoothAudioCtrlAck::SUCCESS_FINISHED); instance->ResetPendingCmd(); return; case aidl::hfp::HFP_CTRL_CMD_NONE: @@ -367,7 +355,7 @@ void HfpClientInterface::Encode::CancelStreamingRequest() { switch (pending_cmd) { case aidl::hfp::HFP_CTRL_CMD_START: aidl::hfp::HfpEncodingTransport::software_hal_interface->StreamStarted( - aidl::BluetoothAudioCtrlAck::FAILURE); + aidl::BluetoothAudioCtrlAck::FAILURE); instance->ResetPendingCmd(); return; case aidl::hfp::HFP_CTRL_CMD_NONE: @@ -376,7 +364,7 @@ void HfpClientInterface::Encode::CancelStreamingRequest() { case aidl::hfp::HFP_CTRL_CMD_SUSPEND: log::info("suspends"); aidl::hfp::HfpEncodingTransport::software_hal_interface->StreamSuspended( - aidl::BluetoothAudioCtrlAck::SUCCESS_FINISHED); + aidl::BluetoothAudioCtrlAck::SUCCESS_FINISHED); instance->ResetPendingCmd(); return; default: @@ -385,7 +373,7 @@ void HfpClientInterface::Encode::CancelStreamingRequest() { } HfpClientInterface::Encode* HfpClientInterface::GetEncode( - bluetooth::common::MessageLoopThread* /*message_loop*/) { + bluetooth::common::MessageLoopThread* /*message_loop*/) { if (!is_aidl_support_hfp()) { log::warn("Unsupported HIDL or AIDL version"); return nullptr; @@ -400,11 +388,10 @@ HfpClientInterface::Encode* HfpClientInterface::GetEncode( log::info("encode"); - HfpEncodingTransport::instance_ = new HfpEncodingTransport( - aidl::SessionType::HFP_SOFTWARE_ENCODING_DATAPATH); + HfpEncodingTransport::instance_ = + new HfpEncodingTransport(aidl::SessionType::HFP_SOFTWARE_ENCODING_DATAPATH); HfpEncodingTransport::software_hal_interface = - new aidl::BluetoothAudioSourceClientInterface( - HfpEncodingTransport::instance_); + new aidl::BluetoothAudioSourceClientInterface(HfpEncodingTransport::instance_); if (!HfpEncodingTransport::software_hal_interface->IsValid()) { log::warn("BluetoothAudio HAL for HFP is invalid"); delete HfpEncodingTransport::software_hal_interface; @@ -414,8 +401,7 @@ HfpClientInterface::Encode* HfpClientInterface::GetEncode( return nullptr; } - HfpEncodingTransport::active_hal_interface = - HfpEncodingTransport::software_hal_interface; + HfpEncodingTransport::active_hal_interface = HfpEncodingTransport::software_hal_interface; return encode_; } @@ -426,7 +412,9 @@ bool HfpClientInterface::ReleaseEncode(HfpClientInterface::Encode* encode) { return false; } - if (get_encode_client_interface()) encode->Cleanup(); + if (get_encode_client_interface()) { + encode->Cleanup(); + } delete encode_; encode_ = nullptr; @@ -454,8 +442,7 @@ void HfpClientInterface::Offload::StartSession() { } log::info("offload"); AudioConfiguration audio_config; - audio_config.set( - get_default_hfp_configuration()); + audio_config.set(get_default_hfp_configuration()); if (!get_encode_client_interface()->UpdateAudioConfig(audio_config)) { log::error("cannot update audio config to HAL"); return; @@ -477,7 +464,7 @@ void HfpClientInterface::Offload::StopSession() { } void HfpClientInterface::Offload::UpdateAudioConfigToHal( - const ::hfp::offload_config& offload_config) { + const ::hfp::offload_config& offload_config) { if (!is_aidl_support_hfp()) { log::warn("Unsupported HIDL or AIDL version"); return; @@ -485,7 +472,7 @@ void HfpClientInterface::Offload::UpdateAudioConfigToHal( log::info("offload"); get_encode_client_interface()->UpdateAudioConfig( - offload_config_to_hal_audio_config(offload_config)); + offload_config_to_hal_audio_config(offload_config)); } void HfpClientInterface::Offload::ConfirmStreamingRequest() { @@ -494,7 +481,7 @@ void HfpClientInterface::Offload::ConfirmStreamingRequest() { switch (pending_cmd) { case aidl::hfp::HFP_CTRL_CMD_START: aidl::hfp::HfpEncodingTransport::offloading_hal_interface->StreamStarted( - aidl::BluetoothAudioCtrlAck::SUCCESS_FINISHED); + aidl::BluetoothAudioCtrlAck::SUCCESS_FINISHED); instance->ResetPendingCmd(); return; case aidl::hfp::HFP_CTRL_CMD_NONE: @@ -511,7 +498,7 @@ void HfpClientInterface::Offload::CancelStreamingRequest() { switch (pending_cmd) { case aidl::hfp::HFP_CTRL_CMD_START: aidl::hfp::HfpEncodingTransport::offloading_hal_interface->StreamStarted( - aidl::BluetoothAudioCtrlAck::FAILURE); + aidl::BluetoothAudioCtrlAck::FAILURE); instance->ResetPendingCmd(); return; case aidl::hfp::HFP_CTRL_CMD_NONE: @@ -519,8 +506,8 @@ void HfpClientInterface::Offload::CancelStreamingRequest() { return; case aidl::hfp::HFP_CTRL_CMD_SUSPEND: log::info("suspends"); - aidl::hfp::HfpEncodingTransport::offloading_hal_interface - ->StreamSuspended(aidl::BluetoothAudioCtrlAck::SUCCESS_FINISHED); + aidl::hfp::HfpEncodingTransport::offloading_hal_interface->StreamSuspended( + aidl::BluetoothAudioCtrlAck::SUCCESS_FINISHED); instance->ResetPendingCmd(); return; default: @@ -530,12 +517,11 @@ void HfpClientInterface::Offload::CancelStreamingRequest() { std::unordered_map HfpClientInterface::Offload::GetHfpScoConfig() { - return aidl::hfp::HfpTransport::GetHfpScoConfig( - aidl::SessionType::HFP_HARDWARE_OFFLOAD_DATAPATH); + return aidl::hfp::HfpTransport::GetHfpScoConfig(aidl::SessionType::HFP_HARDWARE_OFFLOAD_DATAPATH); } HfpClientInterface::Offload* HfpClientInterface::GetOffload( - bluetooth::common::MessageLoopThread* /*message_loop*/) { + bluetooth::common::MessageLoopThread* /*message_loop*/) { if (!is_aidl_support_hfp()) { log::warn("Unsupported HIDL or AIDL version"); return nullptr; @@ -552,18 +538,17 @@ HfpClientInterface::Offload* HfpClientInterface::GetOffload( // Prepare offload hal interface. if (bta_ag_get_sco_offload_enabled()) { - HfpEncodingTransport::instance_ = new HfpEncodingTransport( - aidl::SessionType::HFP_HARDWARE_OFFLOAD_DATAPATH); + HfpEncodingTransport::instance_ = + new HfpEncodingTransport(aidl::SessionType::HFP_HARDWARE_OFFLOAD_DATAPATH); HfpEncodingTransport::offloading_hal_interface = - new aidl::BluetoothAudioSourceClientInterface( - HfpEncodingTransport::instance_); + new aidl::BluetoothAudioSourceClientInterface(HfpEncodingTransport::instance_); if (!HfpEncodingTransport::offloading_hal_interface->IsValid()) { log::fatal("BluetoothAudio HAL for HFP offloading is invalid"); delete HfpEncodingTransport::offloading_hal_interface; HfpEncodingTransport::offloading_hal_interface = nullptr; delete HfpEncodingTransport::instance_; HfpEncodingTransport::instance_ = static_cast( - HfpEncodingTransport::software_hal_interface->GetTransportInstance()); + HfpEncodingTransport::software_hal_interface->GetTransportInstance()); delete HfpEncodingTransport::software_hal_interface; HfpEncodingTransport::software_hal_interface = nullptr; delete HfpEncodingTransport::instance_; @@ -571,8 +556,7 @@ HfpClientInterface::Offload* HfpClientInterface::GetOffload( } } - HfpEncodingTransport::active_hal_interface = - HfpEncodingTransport::offloading_hal_interface; + HfpEncodingTransport::active_hal_interface = HfpEncodingTransport::offloading_hal_interface; return offload_; } @@ -583,7 +567,9 @@ bool HfpClientInterface::ReleaseOffload(HfpClientInterface::Offload* offload) { return false; } - if (get_encode_client_interface()) offload->Cleanup(); + if (get_encode_client_interface()) { + offload->Cleanup(); + } delete offload_; offload_ = nullptr; diff --git a/system/audio_hal_interface/hfp_client_interface.h b/system/audio_hal_interface/hfp_client_interface.h index a050ce313ad..6030c4c2ac1 100644 --- a/system/audio_hal_interface/hfp_client_interface.h +++ b/system/audio_hal_interface/hfp_client_interface.h @@ -28,23 +28,22 @@ namespace hfp { * Only available if HFP is managed by AIDL sessions */ class HfpClientInterface { - private: +private: class IClientInterfaceEndpoint { - public: + public: virtual ~IClientInterfaceEndpoint() = default; virtual void Cleanup() = 0; virtual void StartSession() = 0; virtual void StopSession() = 0; - virtual void UpdateAudioConfigToHal( - const ::hfp::offload_config& config) = 0; + virtual void UpdateAudioConfigToHal(const ::hfp::offload_config& config) = 0; virtual void ConfirmStreamingRequest() = 0; virtual void CancelStreamingRequest() = 0; }; - public: +public: class Decode : public IClientInterfaceEndpoint { - public: - Decode(){}; + public: + Decode() {} virtual ~Decode() = default; void Cleanup() override; @@ -57,7 +56,7 @@ class HfpClientInterface { }; class Encode : public IClientInterfaceEndpoint { - public: + public: virtual ~Encode() = default; void Cleanup() override; @@ -70,7 +69,7 @@ class HfpClientInterface { }; class Offload : public IClientInterfaceEndpoint { - public: + public: virtual ~Offload() = default; void Cleanup() override; @@ -102,7 +101,7 @@ class HfpClientInterface { // Get interface, if previously not initialized - it'll initialize singleton. static HfpClientInterface* Get(); - private: +private: static HfpClientInterface* interface; Decode* decode_ = nullptr; Encode* encode_ = nullptr; diff --git a/system/audio_hal_interface/hfp_client_interface_host.cc b/system/audio_hal_interface/hfp_client_interface_host.cc index 44f6a849e2d..d4ef2576bff 100644 --- a/system/audio_hal_interface/hfp_client_interface_host.cc +++ b/system/audio_hal_interface/hfp_client_interface_host.cc @@ -21,31 +21,25 @@ namespace audio { namespace hfp { HfpClientInterface::Decode* HfpClientInterface::GetDecode( - bluetooth::common::MessageLoopThread* message_loop) { + bluetooth::common::MessageLoopThread* message_loop) { return nullptr; } -bool HfpClientInterface::ReleaseDecode(HfpClientInterface::Decode* decode) { - return false; -} +bool HfpClientInterface::ReleaseDecode(HfpClientInterface::Decode* decode) { return false; } HfpClientInterface::Encode* HfpClientInterface::GetEncode( - bluetooth::common::MessageLoopThread* message_loop) { + bluetooth::common::MessageLoopThread* message_loop) { return nullptr; } -bool HfpClientInterface::ReleaseEncode(HfpClientInterface::Encode* encode) { - return false; -} +bool HfpClientInterface::ReleaseEncode(HfpClientInterface::Encode* encode) { return false; } HfpClientInterface::Offload* HfpClientInterface::GetOffload( - bluetooth::common::MessageLoopThread* message_loop) { + bluetooth::common::MessageLoopThread* message_loop) { return nullptr; } -bool HfpClientInterface::ReleaseOffload(HfpClientInterface::Offload* offload) { - return false; -} +bool HfpClientInterface::ReleaseOffload(HfpClientInterface::Offload* offload) { return false; } HfpClientInterface* HfpClientInterface::Get() { return nullptr; } diff --git a/system/audio_hal_interface/hidl/a2dp_encoding_hidl.cc b/system/audio_hal_interface/hidl/a2dp_encoding_hidl.cc index 5acae15ca3a..c15c40bb743 100644 --- a/system/audio_hal_interface/hidl/a2dp_encoding_hidl.cc +++ b/system/audio_hal_interface/hidl/a2dp_encoding_hidl.cc @@ -49,8 +49,7 @@ struct formatter : enum_formatter {}; template <> struct formatter : enum_formatter {}; template <> -struct formatter : enum_formatter { -}; +struct formatter : enum_formatter {}; } // namespace fmt namespace bluetooth { @@ -82,9 +81,8 @@ using ::bluetooth::audio::hidl::codec::CodecConfiguration; using ::bluetooth::audio::a2dp::BluetoothAudioStatus; // Provide call-in APIs for the Bluetooth Audio HAL -class A2dpTransport - : public ::bluetooth::audio::hidl::IBluetoothSinkTransportInstance { - public: +class A2dpTransport : public ::bluetooth::audio::hidl::IBluetoothSinkTransportInstance { +public: A2dpTransport(SessionType sessionType) : IBluetoothSinkTransportInstance(sessionType, (AudioConfiguration){}), total_bytes_read_(0), @@ -167,15 +165,13 @@ class A2dpTransport btif_av_stream_stop(RawAddress::kEmpty); } - bool GetPresentationPosition(uint64_t* remote_delay_report_ns, - uint64_t* total_bytes_read, + bool GetPresentationPosition(uint64_t* remote_delay_report_ns, uint64_t* total_bytes_read, timespec* data_position) override { *remote_delay_report_ns = remote_delay_report_ * 100000u; *total_bytes_read = total_bytes_read_; *data_position = data_position_; - log::verbose("delay={}/10ms, data={} byte(s), timestamp={}.{}s", - remote_delay_report_, total_bytes_read_, data_position_.tv_sec, - data_position_.tv_nsec); + log::verbose("delay={}/10ms, data={} byte(s), timestamp={}.{}s", remote_delay_report_, + total_bytes_read_, data_position_.tv_sec, data_position_.tv_nsec); return true; } @@ -184,8 +180,8 @@ class A2dpTransport auto tracks = source_metadata.tracks; log::verbose("{} track(s) received", track_count); while (track_count) { - log::verbose("usage={}, content_type={}, gain={}", tracks->usage, - tracks->content_type, tracks->gain); + log::verbose("usage={}, content_type={}, gain={}", tracks->usage, tracks->content_type, + tracks->gain); --track_count; ++tracks; } @@ -209,11 +205,9 @@ class A2dpTransport } // delay reports from AVDTP is based on 1/10 ms (100us) - void SetRemoteDelay(uint16_t delay_report) { - remote_delay_report_ = delay_report; - } + void SetRemoteDelay(uint16_t delay_report) { remote_delay_report_ = delay_report; } - private: +private: static tA2DP_CTRL_CMD a2dp_pending_cmd_; static uint16_t remote_delay_report_; uint64_t total_bytes_read_; @@ -293,8 +287,7 @@ bool a2dp_get_selected_hal_codec_config(CodecConfiguration* codec_config) { [[fallthrough]]; default: log::error("Unknown codec_type={}", current_codec.codec_type); - *codec_config = - ::bluetooth::audio::hidl::codec::kInvalidCodecConfiguration; + *codec_config = ::bluetooth::audio::hidl::codec::kInvalidCodecConfiguration; return false; } codec_config->encodedAudioBitrate = a2dp_config->getTrackBitRate(); @@ -309,8 +302,7 @@ bool a2dp_get_selected_hal_codec_config(CodecConfiguration* codec_config) { codec_config->peerMtu = peer_param.peer_mtu; } if (current_codec.codec_type == BTAV_A2DP_CODEC_INDEX_SOURCE_SBC && - codec_config->config.sbcConfig().maxBitpool <= - A2DP_SBC_BITPOOL_MIDDLE_QUALITY) { + codec_config->config.sbcConfig().maxBitpool <= A2DP_SBC_BITPOOL_MIDDLE_QUALITY) { codec_config->peerMtu = MAX_2MBPS_AVDTP_MTU; } else if (codec_config->peerMtu > MAX_3MBPS_AVDTP_MTU) { codec_config->peerMtu = MAX_3MBPS_AVDTP_MTU; @@ -320,7 +312,9 @@ bool a2dp_get_selected_hal_codec_config(CodecConfiguration* codec_config) { } bool a2dp_get_selected_hal_pcm_config(PcmParameters* pcm_config) { - if (pcm_config == nullptr) return false; + if (pcm_config == nullptr) { + return false; + } A2dpCodecConfig* a2dp_codec_configs = bta_av_get_a2dp_current_codec(); if (a2dp_codec_configs == nullptr) { log::warn("failure to get A2DP codec config"); @@ -332,16 +326,15 @@ bool a2dp_get_selected_hal_pcm_config(PcmParameters* pcm_config) { pcm_config->sampleRate = A2dpCodecToHalSampleRate(current_codec); pcm_config->bitsPerSample = A2dpCodecToHalBitsPerSample(current_codec); pcm_config->channelMode = A2dpCodecToHalChannelMode(current_codec); - return (pcm_config->sampleRate != SampleRate::RATE_UNKNOWN && - pcm_config->bitsPerSample != BitsPerSample::BITS_UNKNOWN && - pcm_config->channelMode != ChannelMode::UNKNOWN); + return pcm_config->sampleRate != SampleRate::RATE_UNKNOWN && + pcm_config->bitsPerSample != BitsPerSample::BITS_UNKNOWN && + pcm_config->channelMode != ChannelMode::UNKNOWN; } // Checking if new bluetooth_audio is supported bool is_hal_2_0_force_disabled() { if (!is_configured) { - btaudio_a2dp_disabled = - osi_property_get_bool(BLUETOOTH_AUDIO_HAL_PROP_DISABLED, false); + btaudio_a2dp_disabled = osi_property_get_bool(BLUETOOTH_AUDIO_HAL_PROP_DISABLED, false); is_configured = true; } return btaudio_a2dp_disabled; @@ -349,9 +342,8 @@ bool is_hal_2_0_force_disabled() { } // namespace bool update_codec_offloading_capabilities( - const std::vector& framework_preference) { - return ::bluetooth::audio::hidl::codec::UpdateOffloadingCapabilities( - framework_preference); + const std::vector& framework_preference) { + return ::bluetooth::audio::hidl::codec::UpdateOffloadingCapabilities(framework_preference); } // Checking if new bluetooth_audio is enabled @@ -375,10 +367,8 @@ bool init(bluetooth::common::MessageLoopThread* message_loop) { return false; } - auto a2dp_sink = - new A2dpTransport(SessionType::A2DP_SOFTWARE_ENCODING_DATAPATH); - software_hal_interface = - new BluetoothAudioSinkClientInterface(a2dp_sink, message_loop); + auto a2dp_sink = new A2dpTransport(SessionType::A2DP_SOFTWARE_ENCODING_DATAPATH); + software_hal_interface = new BluetoothAudioSinkClientInterface(a2dp_sink, message_loop); if (!software_hal_interface->IsValid()) { log::warn("BluetoothAudio HAL for A2DP is invalid?!"); delete software_hal_interface; @@ -389,15 +379,13 @@ bool init(bluetooth::common::MessageLoopThread* message_loop) { if (btif_av_is_a2dp_offload_enabled()) { a2dp_sink = new A2dpTransport(SessionType::A2DP_HARDWARE_OFFLOAD_DATAPATH); - offloading_hal_interface = - new BluetoothAudioSinkClientInterface(a2dp_sink, message_loop); + offloading_hal_interface = new BluetoothAudioSinkClientInterface(a2dp_sink, message_loop); if (!offloading_hal_interface->IsValid()) { log::fatal("BluetoothAudio HAL for A2DP offloading is invalid?!"); delete offloading_hal_interface; offloading_hal_interface = nullptr; delete a2dp_sink; - a2dp_sink = static_cast( - software_hal_interface->GetTransportInstance()); + a2dp_sink = static_cast(software_hal_interface->GetTransportInstance()); delete software_hal_interface; software_hal_interface = nullptr; delete a2dp_sink; @@ -406,13 +394,12 @@ bool init(bluetooth::common::MessageLoopThread* message_loop) { } active_hal_interface = - (offloading_hal_interface != nullptr ? offloading_hal_interface - : software_hal_interface); + (offloading_hal_interface != nullptr ? offloading_hal_interface : software_hal_interface); if (remote_delay != 0) { log::info("restore DELAY {} ms", static_cast(remote_delay / 10.0)); static_cast(active_hal_interface->GetTransportInstance()) - ->SetRemoteDelay(remote_delay); + ->SetRemoteDelay(remote_delay); remote_delay = 0; } return true; @@ -420,7 +407,9 @@ bool init(bluetooth::common::MessageLoopThread* message_loop) { // Clean up BluetoothAudio HAL void cleanup() { - if (!is_hal_2_0_enabled()) return; + if (!is_hal_2_0_enabled()) { + return; + } end_session(); auto a2dp_sink = active_hal_interface->GetTransportInstance(); @@ -454,7 +443,7 @@ bool setup_codec() { return false; } bool should_codec_offloading = - bluetooth::audio::hidl::codec::IsCodecOffloadingEnabled(codec_config); + bluetooth::audio::hidl::codec::IsCodecOffloadingEnabled(codec_config); if (should_codec_offloading && !is_hal_2_0_offloading()) { log::warn("Switching BluetoothAudio HAL to Hardware"); end_session(); @@ -494,10 +483,9 @@ void end_session() { return; } active_hal_interface->EndSession(); + static_cast(active_hal_interface->GetTransportInstance())->ResetPendingCmd(); static_cast(active_hal_interface->GetTransportInstance()) - ->ResetPendingCmd(); - static_cast(active_hal_interface->GetTransportInstance()) - ->ResetPresentationPosition(); + ->ResetPresentationPosition(); } void ack_stream_started(BluetoothAudioStatus ack) { @@ -506,8 +494,7 @@ void ack_stream_started(BluetoothAudioStatus ack) { return; } log::info("result={}", ack); - auto a2dp_sink = - static_cast(active_hal_interface->GetTransportInstance()); + auto a2dp_sink = static_cast(active_hal_interface->GetTransportInstance()); auto pending_cmd = a2dp_sink->GetPendingCmd(); if (pending_cmd == A2DP_CTRL_CMD_START) { active_hal_interface->StreamStarted(a2dp_ack_to_bt_audio_ctrl_ack(ack)); @@ -526,8 +513,7 @@ void ack_stream_suspended(BluetoothAudioStatus ack) { return; } log::info("result={}", ack); - auto a2dp_sink = - static_cast(active_hal_interface->GetTransportInstance()); + auto a2dp_sink = static_cast(active_hal_interface->GetTransportInstance()); auto pending_cmd = a2dp_sink->GetPendingCmd(); if (pending_cmd == A2DP_CTRL_CMD_SUSPEND) { active_hal_interface->StreamSuspended(a2dp_ack_to_bt_audio_ctrl_ack(ack)); @@ -549,10 +535,8 @@ size_t read(uint8_t* p_buf, uint32_t len) { return 0; } if (is_hal_2_0_offloading()) { - log::error( - "session_type={} is not A2DP_SOFTWARE_ENCODING_DATAPATH", - toString( - active_hal_interface->GetTransportInstance()->GetSessionType())); + log::error("session_type={} is not A2DP_SOFTWARE_ENCODING_DATAPATH", + toString(active_hal_interface->GetTransportInstance()->GetSessionType())); return 0; } return active_hal_interface->ReadAudioData(p_buf, len); @@ -561,17 +545,16 @@ size_t read(uint8_t* p_buf, uint32_t len) { // Update A2DP delay report to BluetoothAudio HAL void set_remote_delay(uint16_t delay_report) { if (!is_hal_2_0_enabled()) { - log::info("not ready for DelayReport {} ms", - static_cast(delay_report / 10.0)); + log::info("not ready for DelayReport {} ms", static_cast(delay_report / 10.0)); remote_delay = delay_report; return; } log::verbose("DELAY {} ms", static_cast(delay_report / 10.0)); static_cast(active_hal_interface->GetTransportInstance()) - ->SetRemoteDelay(delay_report); + ->SetRemoteDelay(delay_report); } -} // namespace a2dp -} // namespace hidl -} // namespace audio -} // namespace bluetooth +} // namespace a2dp +} // namespace hidl +} // namespace audio +} // namespace bluetooth diff --git a/system/audio_hal_interface/hidl/a2dp_encoding_hidl.h b/system/audio_hal_interface/hidl/a2dp_encoding_hidl.h index c7933c864b6..758703e02ed 100644 --- a/system/audio_hal_interface/hidl/a2dp_encoding_hidl.h +++ b/system/audio_hal_interface/hidl/a2dp_encoding_hidl.h @@ -28,7 +28,7 @@ namespace hidl { namespace a2dp { bool update_codec_offloading_capabilities( - const std::vector& framework_preference); + const std::vector& framework_preference); // Check if new bluetooth_audio is enabled bool is_hal_2_0_enabled(); diff --git a/system/audio_hal_interface/hidl/client_interface_hidl.cc b/system/audio_hal_interface/hidl/client_interface_hidl.cc index a48d67fec87..c6987279986 100644 --- a/system/audio_hal_interface/hidl/client_interface_hidl.cc +++ b/system/audio_hal_interface/hidl/client_interface_hidl.cc @@ -39,8 +39,8 @@ using ::android::hardware::audio::common::V5_0::SourceMetadata; using ::android::hardware::bluetooth::audio::V2_0::IBluetoothAudioPort; using ::bluetooth::common::StopWatchLegacy; -using DataMQ = ::android::hardware::MessageQueue< - uint8_t, ::android::hardware::kSynchronizedReadWrite>; +using DataMQ = + ::android::hardware::MessageQueue; static constexpr int kDefaultDataReadTimeoutMs = 10; // 10 ms static constexpr int kDefaultDataWriteTimeoutMs = 10; // 10 ms @@ -67,7 +67,7 @@ std::ostream& operator<<(std::ostream& os, const BluetoothAudioCtrlAck& ack) { } class BluetoothAudioPortImpl : public IBluetoothAudioPort { - public: +public: BluetoothAudioPortImpl(IBluetoothTransportInstance* transport_instance, const android::sp& provider) : transport_instance_(transport_instance), provider_(provider) {} @@ -76,8 +76,7 @@ class BluetoothAudioPortImpl : public IBluetoothAudioPort { StopWatchLegacy stop_watch(__func__); BluetoothAudioCtrlAck ack = transport_instance_->StartRequest(); if (ack != BluetoothAudioCtrlAck::PENDING) { - auto hidl_retval = - provider_->streamStarted(BluetoothAudioCtrlAckToHalStatus(ack)); + auto hidl_retval = provider_->streamStarted(BluetoothAudioCtrlAckToHalStatus(ack)); if (!hidl_retval.isOk()) { log::error("BluetoothAudioHal failure: {}", hidl_retval.description()); } @@ -89,8 +88,7 @@ class BluetoothAudioPortImpl : public IBluetoothAudioPort { StopWatchLegacy stop_watch(__func__); BluetoothAudioCtrlAck ack = transport_instance_->SuspendRequest(); if (ack != BluetoothAudioCtrlAck::PENDING) { - auto hidl_retval = - provider_->streamSuspended(BluetoothAudioCtrlAckToHalStatus(ack)); + auto hidl_retval = provider_->streamSuspended(BluetoothAudioCtrlAckToHalStatus(ack)); if (!hidl_retval.isOk()) { log::error("BluetoothAudioHal failure: {}", hidl_retval.description()); } @@ -104,14 +102,13 @@ class BluetoothAudioPortImpl : public IBluetoothAudioPort { return Void(); } - Return getPresentationPosition( - getPresentationPosition_cb _hidl_cb) override { + Return getPresentationPosition(getPresentationPosition_cb _hidl_cb) override { StopWatchLegacy stop_watch(__func__); uint64_t remote_delay_report_ns; uint64_t total_bytes_read; timespec data_position; - bool retval = transport_instance_->GetPresentationPosition( - &remote_delay_report_ns, &total_bytes_read, &data_position); + bool retval = transport_instance_->GetPresentationPosition(&remote_delay_report_ns, + &total_bytes_read, &data_position); TimeSpec transmittedOctetsTimeStamp; if (retval) { @@ -122,12 +119,9 @@ class BluetoothAudioPortImpl : public IBluetoothAudioPort { transmittedOctetsTimeStamp = {}; } log::verbose("result={}, delay={}, data={} byte(s), timestamp={}", retval, - remote_delay_report_ns, total_bytes_read, - toString(transmittedOctetsTimeStamp)); - _hidl_cb((retval ? BluetoothAudioStatus::SUCCESS - : BluetoothAudioStatus::FAILURE), - remote_delay_report_ns, total_bytes_read, - transmittedOctetsTimeStamp); + remote_delay_report_ns, total_bytes_read, toString(transmittedOctetsTimeStamp)); + _hidl_cb((retval ? BluetoothAudioStatus::SUCCESS : BluetoothAudioStatus::FAILURE), + remote_delay_report_ns, total_bytes_read, transmittedOctetsTimeStamp); return Void(); } @@ -139,52 +133,45 @@ class BluetoothAudioPortImpl : public IBluetoothAudioPort { metadata_vec.reserve(sourceMetadata.tracks.size()); for (const auto& metadata : sourceMetadata.tracks) { metadata_vec.push_back({ - .usage = static_cast(metadata.usage), - .content_type = - static_cast(metadata.contentType), - .gain = metadata.gain, + .usage = static_cast(metadata.usage), + .content_type = static_cast(metadata.contentType), + .gain = metadata.gain, }); } - const source_metadata_t source_metadata = { - .track_count = metadata_vec.size(), .tracks = metadata_vec.data()}; + const source_metadata_t source_metadata = {.track_count = metadata_vec.size(), + .tracks = metadata_vec.data()}; transport_instance_->MetadataChanged(source_metadata); return Void(); } - private: +private: IBluetoothTransportInstance* transport_instance_; const android::sp provider_; TimeSpec timespec_convert_to_hal(const timespec& ts) { - return {.tvSec = static_cast(ts.tv_sec), - .tvNSec = static_cast(ts.tv_nsec)}; + return {.tvSec = static_cast(ts.tv_sec), .tvNSec = static_cast(ts.tv_nsec)}; } }; -class BluetoothAudioDeathRecipient - : public ::android::hardware::hidl_death_recipient { - public: - BluetoothAudioDeathRecipient( - BluetoothAudioClientInterface* clientif, - bluetooth::common::MessageLoopThread* message_loop) +class BluetoothAudioDeathRecipient : public ::android::hardware::hidl_death_recipient { +public: + BluetoothAudioDeathRecipient(BluetoothAudioClientInterface* clientif, + bluetooth::common::MessageLoopThread* message_loop) : bluetooth_audio_clientif_(clientif), message_loop_(message_loop) {} - void serviceDied( - uint64_t /*cookie*/, - const ::android::wp<::android::hidl::base::V1_0::IBase>& /*who*/) - override { + void serviceDied(uint64_t /*cookie*/, + const ::android::wp<::android::hidl::base::V1_0::IBase>& /*who*/) override { log::warn("restarting connection with new Audio Hal"); if (bluetooth_audio_clientif_ != nullptr && message_loop_ != nullptr) { // restart the session on the correct thread message_loop_->DoInThread( - FROM_HERE, - base::BindOnce( - &BluetoothAudioClientInterface::RenewAudioProviderAndSession, - base::Unretained(bluetooth_audio_clientif_))); + FROM_HERE, + base::BindOnce(&BluetoothAudioClientInterface::RenewAudioProviderAndSession, + base::Unretained(bluetooth_audio_clientif_))); } else { log::error("BluetoothAudioClientInterface corrupted"); } } - private: +private: BluetoothAudioClientInterface* bluetooth_audio_clientif_; bluetooth::common::MessageLoopThread* message_loop_; }; @@ -193,8 +180,8 @@ class BluetoothAudioDeathRecipient // BluetoothAudio HAL. |message_loop| is the thread where callbacks are // invoked. BluetoothAudioClientInterface::BluetoothAudioClientInterface( - android::sp death_recipient, - IBluetoothTransportInstance* instance) + android::sp death_recipient, + IBluetoothTransportInstance* instance) : provider_(nullptr), provider_2_1_(nullptr), session_started_(false), @@ -207,73 +194,65 @@ bool BluetoothAudioClientInterface::IsValid() const { return provider_ != nullptr || provider_2_1_ != nullptr; } -std::vector -BluetoothAudioClientInterface::GetAudioCapabilities() const { +std::vector BluetoothAudioClientInterface::GetAudioCapabilities() const { return capabilities_; } -std::vector -BluetoothAudioClientInterface::GetAudioCapabilities_2_1() const { +std::vector BluetoothAudioClientInterface::GetAudioCapabilities_2_1() const { return capabilities_2_1_; } -std::vector -BluetoothAudioClientInterface::GetAudioCapabilities(SessionType session_type) { +std::vector BluetoothAudioClientInterface::GetAudioCapabilities( + SessionType session_type) { std::vector capabilities(0); - if (HalVersionManager::GetHalVersion() == - BluetoothAudioHalVersion::VERSION_UNAVAILABLE) { + if (HalVersionManager::GetHalVersion() == BluetoothAudioHalVersion::VERSION_UNAVAILABLE) { log::error("can't get capability from unknown factory"); return capabilities; } android::sp providersFactory = - HalVersionManager::GetProvidersFactory_2_0(); + HalVersionManager::GetProvidersFactory_2_0(); log::assert_that(providersFactory != nullptr, "IBluetoothAudioProvidersFactory::getService() failed"); auto getProviderCapabilities_cb = - [&capabilities](const hidl_vec& audioCapabilities) { - for (auto capability : audioCapabilities) { - capabilities.push_back(capability); - } - }; - auto hidl_retval = providersFactory->getProviderCapabilities( - session_type, getProviderCapabilities_cb); + [&capabilities](const hidl_vec& audioCapabilities) { + for (auto capability : audioCapabilities) { + capabilities.push_back(capability); + } + }; + auto hidl_retval = + providersFactory->getProviderCapabilities(session_type, getProviderCapabilities_cb); if (!hidl_retval.isOk()) { - log::fatal("BluetoothAudioHal::getProviderCapabilities failure: {}", - hidl_retval.description()); + log::fatal("BluetoothAudioHal::getProviderCapabilities failure: {}", hidl_retval.description()); } return capabilities; } -std::vector -BluetoothAudioClientInterface::GetAudioCapabilities_2_1( - SessionType_2_1 session_type_2_1) { +std::vector BluetoothAudioClientInterface::GetAudioCapabilities_2_1( + SessionType_2_1 session_type_2_1) { std::vector capabilities_2_1(0); - if (HalVersionManager::GetHalVersion() != - BluetoothAudioHalVersion::VERSION_2_1) { + if (HalVersionManager::GetHalVersion() != BluetoothAudioHalVersion::VERSION_2_1) { log::error("can't get capability for HAL 2.1"); return capabilities_2_1; } android::sp providersFactory = - HalVersionManager::GetProvidersFactory_2_1(); + HalVersionManager::GetProvidersFactory_2_1(); log::assert_that(providersFactory != nullptr, "IBluetoothAudioProvidersFactory::getService() failed"); auto getProviderCapabilities_cb = - [&capabilities_2_1]( - const hidl_vec& audioCapabilities_2_1) { - for (auto capability_2_1 : audioCapabilities_2_1) { - capabilities_2_1.push_back(capability_2_1); - } - }; - auto hidl_retval = providersFactory->getProviderCapabilities_2_1( - session_type_2_1, getProviderCapabilities_cb); + [&capabilities_2_1](const hidl_vec& audioCapabilities_2_1) { + for (auto capability_2_1 : audioCapabilities_2_1) { + capabilities_2_1.push_back(capability_2_1); + } + }; + auto hidl_retval = providersFactory->getProviderCapabilities_2_1(session_type_2_1, + getProviderCapabilities_cb); if (!hidl_retval.isOk()) { - log::fatal("BluetoothAudioHal::getProviderCapabilities failure: {}", - hidl_retval.description()); + log::fatal("BluetoothAudioHal::getProviderCapabilities failure: {}", hidl_retval.description()); } return capabilities_2_1; } @@ -284,23 +263,21 @@ void BluetoothAudioClientInterface::FetchAudioProvider() { } android::sp providersFactory = - HalVersionManager::GetProvidersFactory_2_0(); + HalVersionManager::GetProvidersFactory_2_0(); log::assert_that(providersFactory != nullptr, "IBluetoothAudioProvidersFactory::getService() failed"); - auto getProviderCapabilities_cb = - [&capabilities = this->capabilities_]( - const hidl_vec& audioCapabilities) { - capabilities.clear(); - for (auto capability : audioCapabilities) { - capabilities.push_back(capability); - } - }; - auto hidl_retval = providersFactory->getProviderCapabilities( - transport_->GetSessionType(), getProviderCapabilities_cb); + auto getProviderCapabilities_cb = [&capabilities = this->capabilities_]( + const hidl_vec& audioCapabilities) { + capabilities.clear(); + for (auto capability : audioCapabilities) { + capabilities.push_back(capability); + } + }; + auto hidl_retval = providersFactory->getProviderCapabilities(transport_->GetSessionType(), + getProviderCapabilities_cb); if (!hidl_retval.isOk()) { - log::fatal("BluetoothAudioHal::getProviderCapabilities failure: {}", - hidl_retval.description()); + log::fatal("BluetoothAudioHal::getProviderCapabilities failure: {}", hidl_retval.description()); return; } if (capabilities_.empty()) { @@ -313,36 +290,31 @@ void BluetoothAudioClientInterface::FetchAudioProvider() { std::promise openProvider_promise; auto openProvider_future = openProvider_promise.get_future(); - auto openProvider_cb = - [&provider_ = this->provider_, &openProvider_promise]( - BluetoothAudioStatus status, - const android::sp& provider) { - log::info("openProvider_cb({})", toString(status)); - if (status == BluetoothAudioStatus::SUCCESS) { - provider_ = provider; - } - if (!provider_) { - log::error("Failed to open BluetoothAudio provider"); - } - openProvider_promise.set_value(); - }; - hidl_retval = providersFactory->openProvider(transport_->GetSessionType(), - openProvider_cb); + auto openProvider_cb = [&provider_ = this->provider_, &openProvider_promise]( + BluetoothAudioStatus status, + const android::sp& provider) { + log::info("openProvider_cb({})", toString(status)); + if (status == BluetoothAudioStatus::SUCCESS) { + provider_ = provider; + } + if (!provider_) { + log::error("Failed to open BluetoothAudio provider"); + } + openProvider_promise.set_value(); + }; + hidl_retval = providersFactory->openProvider(transport_->GetSessionType(), openProvider_cb); openProvider_future.get(); if (!hidl_retval.isOk()) { - log::fatal("BluetoothAudioHal::openProvider failure: {}", - hidl_retval.description()); + log::fatal("BluetoothAudioHal::openProvider failure: {}", hidl_retval.description()); } log::assert_that(provider_ != nullptr, "assert failed: provider_ != nullptr"); if (!provider_->linkToDeath(death_recipient_, 0).isOk()) { - log::fatal("BluetoothAudioDeathRecipient failure: {}", - hidl_retval.description()); + log::fatal("BluetoothAudioDeathRecipient failure: {}", hidl_retval.description()); } log::info("IBluetoothAudioProvidersFactory::openProvider() returned {}{}", - fmt::ptr(provider_.get()), - (provider_->isRemote() ? " (remote)" : " (local)")); + fmt::ptr(provider_.get()), (provider_->isRemote() ? " (remote)" : " (local)")); } void BluetoothAudioClientInterface::FetchAudioProvider_2_1() { @@ -351,23 +323,22 @@ void BluetoothAudioClientInterface::FetchAudioProvider_2_1() { } android::sp providersFactory = - HalVersionManager::GetProvidersFactory_2_1(); + HalVersionManager::GetProvidersFactory_2_1(); log::assert_that(providersFactory != nullptr, "IBluetoothAudioProvidersFactory_2_1::getService() failed"); auto getProviderCapabilities_cb = - [&capabilities_2_1 = this->capabilities_2_1_]( - const hidl_vec& audioCapabilities_2_1) { - capabilities_2_1.clear(); - for (auto capability_2_1 : audioCapabilities_2_1) { - capabilities_2_1.push_back(capability_2_1); - } - }; - auto hidl_retval = providersFactory->getProviderCapabilities_2_1( - transport_->GetSessionType_2_1(), getProviderCapabilities_cb); + [&capabilities_2_1 = this->capabilities_2_1_]( + const hidl_vec& audioCapabilities_2_1) { + capabilities_2_1.clear(); + for (auto capability_2_1 : audioCapabilities_2_1) { + capabilities_2_1.push_back(capability_2_1); + } + }; + auto hidl_retval = providersFactory->getProviderCapabilities_2_1(transport_->GetSessionType_2_1(), + getProviderCapabilities_cb); if (!hidl_retval.isOk()) { - log::fatal("BluetoothAudioHal::getProviderCapabilities failure: {}", - hidl_retval.description()); + log::fatal("BluetoothAudioHal::getProviderCapabilities failure: {}", hidl_retval.description()); return; } if (capabilities_2_1_.empty()) { @@ -376,58 +347,47 @@ void BluetoothAudioClientInterface::FetchAudioProvider_2_1() { return; } log::info("BluetoothAudioHal SessionType={} has {} AudioCapabilities", - toString(transport_->GetSessionType_2_1()), - capabilities_2_1_.size()); + toString(transport_->GetSessionType_2_1()), capabilities_2_1_.size()); std::promise openProvider_promise; auto openProvider_future = openProvider_promise.get_future(); - auto openProvider_cb = - [&provider_2_1_ = this->provider_2_1_, &openProvider_promise]( - BluetoothAudioStatus status, - const android::sp& provider_2_1) { - log::info("openProvider_cb({})", toString(status)); - if (status == BluetoothAudioStatus::SUCCESS) { - provider_2_1_ = provider_2_1; - } - if (!provider_2_1_) { - log::error("Failed to open BluetoothAudio provider_2_1"); - } - openProvider_promise.set_value(); - }; - hidl_retval = providersFactory->openProvider_2_1( - transport_->GetSessionType_2_1(), openProvider_cb); + auto openProvider_cb = [&provider_2_1_ = this->provider_2_1_, &openProvider_promise]( + BluetoothAudioStatus status, + const android::sp& provider_2_1) { + log::info("openProvider_cb({})", toString(status)); + if (status == BluetoothAudioStatus::SUCCESS) { + provider_2_1_ = provider_2_1; + } + if (!provider_2_1_) { + log::error("Failed to open BluetoothAudio provider_2_1"); + } + openProvider_promise.set_value(); + }; + hidl_retval = + providersFactory->openProvider_2_1(transport_->GetSessionType_2_1(), openProvider_cb); openProvider_future.get(); if (!hidl_retval.isOk()) { - log::fatal("BluetoothAudioHal::openProvider failure: {}", - hidl_retval.description()); + log::fatal("BluetoothAudioHal::openProvider failure: {}", hidl_retval.description()); } - log::assert_that(provider_2_1_ != nullptr, - "assert failed: provider_2_1_ != nullptr"); + log::assert_that(provider_2_1_ != nullptr, "assert failed: provider_2_1_ != nullptr"); if (!provider_2_1_->linkToDeath(death_recipient_, 0).isOk()) { - log::fatal("BluetoothAudioDeathRecipient failure: {}", - hidl_retval.description()); + log::fatal("BluetoothAudioDeathRecipient failure: {}", hidl_retval.description()); } log::info("IBluetoothAudioProvidersFactory::openProvider() returned {}{}", - fmt::ptr(provider_2_1_.get()), - (provider_2_1_->isRemote() ? " (remote)" : " (local)")); + fmt::ptr(provider_2_1_.get()), (provider_2_1_->isRemote() ? " (remote)" : " (local)")); } BluetoothAudioSinkClientInterface::BluetoothAudioSinkClientInterface( - IBluetoothSinkTransportInstance* sink, - bluetooth::common::MessageLoopThread* message_loop) - : BluetoothAudioClientInterface{new BluetoothAudioDeathRecipient( - this, message_loop), - sink}, + IBluetoothSinkTransportInstance* sink, bluetooth::common::MessageLoopThread* message_loop) + : BluetoothAudioClientInterface{new BluetoothAudioDeathRecipient(this, message_loop), sink}, sink_(sink) { - if (HalVersionManager::GetHalVersion() == - BluetoothAudioHalVersion::VERSION_UNAVAILABLE) { + if (HalVersionManager::GetHalVersion() == BluetoothAudioHalVersion::VERSION_UNAVAILABLE) { return; } - if ((HalVersionManager::GetHalVersion() == - BluetoothAudioHalVersion::VERSION_2_1) && + if ((HalVersionManager::GetHalVersion() == BluetoothAudioHalVersion::VERSION_2_1) && (sink_->GetSessionType_2_1() != SessionType_2_1::UNKNOWN)) { FetchAudioProvider_2_1(); return; @@ -439,33 +399,27 @@ BluetoothAudioSinkClientInterface::~BluetoothAudioSinkClientInterface() { if (provider_ != nullptr) { auto hidl_retval = provider_->unlinkToDeath(death_recipient_); if (!hidl_retval.isOk()) { - log::fatal("BluetoothAudioDeathRecipient failure: {}", - hidl_retval.description()); + log::fatal("BluetoothAudioDeathRecipient failure: {}", hidl_retval.description()); } } if (provider_2_1_ != nullptr) { auto hidl_retval = provider_2_1_->unlinkToDeath(death_recipient_); if (!hidl_retval.isOk()) { - log::fatal("BluetoothAudioDeathRecipient failure: {}", - hidl_retval.description()); + log::fatal("BluetoothAudioDeathRecipient failure: {}", hidl_retval.description()); } } } BluetoothAudioSourceClientInterface::BluetoothAudioSourceClientInterface( - IBluetoothSourceTransportInstance* source, - bluetooth::common::MessageLoopThread* message_loop) - : BluetoothAudioClientInterface{new BluetoothAudioDeathRecipient( - this, message_loop), - source}, + IBluetoothSourceTransportInstance* source, + bluetooth::common::MessageLoopThread* message_loop) + : BluetoothAudioClientInterface{new BluetoothAudioDeathRecipient(this, message_loop), source}, source_(source) { - if (HalVersionManager::GetHalVersion() == - BluetoothAudioHalVersion::VERSION_UNAVAILABLE) { + if (HalVersionManager::GetHalVersion() == BluetoothAudioHalVersion::VERSION_UNAVAILABLE) { return; } - if ((HalVersionManager::GetHalVersion() == - BluetoothAudioHalVersion::VERSION_2_1) && + if ((HalVersionManager::GetHalVersion() == BluetoothAudioHalVersion::VERSION_2_1) && (source_->GetSessionType_2_1() != SessionType_2_1::UNKNOWN)) { FetchAudioProvider_2_1(); return; @@ -477,37 +431,30 @@ BluetoothAudioSourceClientInterface::~BluetoothAudioSourceClientInterface() { if (provider_ != nullptr) { auto hidl_retval = provider_->unlinkToDeath(death_recipient_); if (!hidl_retval.isOk()) { - log::fatal("BluetoothAudioDeathRecipient failure: {}", - hidl_retval.description()); + log::fatal("BluetoothAudioDeathRecipient failure: {}", hidl_retval.description()); } } if (provider_2_1_ != nullptr) { auto hidl_retval = provider_2_1_->unlinkToDeath(death_recipient_); if (!hidl_retval.isOk()) { - log::fatal("BluetoothAudioDeathRecipient failure: {}", - hidl_retval.description()); + log::fatal("BluetoothAudioDeathRecipient failure: {}", hidl_retval.description()); } } } -bool BluetoothAudioClientInterface::UpdateAudioConfig( - const AudioConfiguration& audio_config) { +bool BluetoothAudioClientInterface::UpdateAudioConfig(const AudioConfiguration& audio_config) { bool is_software_session = - (transport_->GetSessionType() == - SessionType::A2DP_SOFTWARE_ENCODING_DATAPATH || - transport_->GetSessionType() == - SessionType::HEARING_AID_SOFTWARE_ENCODING_DATAPATH); - bool is_offload_session = (transport_->GetSessionType() == - SessionType::A2DP_HARDWARE_OFFLOAD_DATAPATH); + (transport_->GetSessionType() == SessionType::A2DP_SOFTWARE_ENCODING_DATAPATH || + transport_->GetSessionType() == SessionType::HEARING_AID_SOFTWARE_ENCODING_DATAPATH); + bool is_offload_session = + (transport_->GetSessionType() == SessionType::A2DP_HARDWARE_OFFLOAD_DATAPATH); auto audio_config_discriminator = audio_config.getDiscriminator(); bool is_software_audio_config = - (is_software_session && - audio_config_discriminator == - AudioConfiguration::hidl_discriminator::pcmConfig); + (is_software_session && + audio_config_discriminator == AudioConfiguration::hidl_discriminator::pcmConfig); bool is_offload_audio_config = - (is_offload_session && - audio_config_discriminator == - AudioConfiguration::hidl_discriminator::codecConfig); + (is_offload_session && + audio_config_discriminator == AudioConfiguration::hidl_discriminator::codecConfig); if (!is_software_audio_config && !is_offload_audio_config) { return false; } @@ -516,27 +463,23 @@ bool BluetoothAudioClientInterface::UpdateAudioConfig( } bool BluetoothAudioClientInterface::UpdateAudioConfig_2_1( - const AudioConfiguration_2_1& audio_config_2_1) { + const AudioConfiguration_2_1& audio_config_2_1) { bool is_software_session = - (transport_->GetSessionType_2_1() == - SessionType_2_1::A2DP_SOFTWARE_ENCODING_DATAPATH || - transport_->GetSessionType_2_1() == - SessionType_2_1::HEARING_AID_SOFTWARE_ENCODING_DATAPATH || - transport_->GetSessionType_2_1() == - SessionType_2_1::LE_AUDIO_SOFTWARE_ENCODING_DATAPATH || - transport_->GetSessionType_2_1() == - SessionType_2_1::LE_AUDIO_SOFTWARE_DECODED_DATAPATH); - bool is_offload_session = (transport_->GetSessionType_2_1() == - SessionType_2_1::A2DP_HARDWARE_OFFLOAD_DATAPATH); + (transport_->GetSessionType_2_1() == SessionType_2_1::A2DP_SOFTWARE_ENCODING_DATAPATH || + transport_->GetSessionType_2_1() == + SessionType_2_1::HEARING_AID_SOFTWARE_ENCODING_DATAPATH || + transport_->GetSessionType_2_1() == + SessionType_2_1::LE_AUDIO_SOFTWARE_ENCODING_DATAPATH || + transport_->GetSessionType_2_1() == SessionType_2_1::LE_AUDIO_SOFTWARE_DECODED_DATAPATH); + bool is_offload_session = + (transport_->GetSessionType_2_1() == SessionType_2_1::A2DP_HARDWARE_OFFLOAD_DATAPATH); auto audio_config_discriminator = audio_config_2_1.getDiscriminator(); bool is_software_audio_config = - (is_software_session && - audio_config_discriminator == - AudioConfiguration_2_1::hidl_discriminator::pcmConfig); + (is_software_session && + audio_config_discriminator == AudioConfiguration_2_1::hidl_discriminator::pcmConfig); bool is_offload_audio_config = - (is_offload_session && - audio_config_discriminator == - AudioConfiguration_2_1::hidl_discriminator::codecConfig); + (is_offload_session && + audio_config_discriminator == AudioConfiguration_2_1::hidl_discriminator::codecConfig); if (!is_software_audio_config && !is_offload_audio_config) { return false; } @@ -556,8 +499,7 @@ int BluetoothAudioClientInterface::StartSession() { return -EBUSY; } - android::sp stack_if = - new BluetoothAudioPortImpl(transport_, provider_); + android::sp stack_if = new BluetoothAudioPortImpl(transport_, provider_); std::unique_ptr tempDataMQ; BluetoothAudioStatus session_status; @@ -565,8 +507,7 @@ int BluetoothAudioClientInterface::StartSession() { std::promise hidl_startSession_promise; auto hidl_startSession_future = hidl_startSession_promise.get_future(); auto hidl_cb = [&session_status, &tempDataMQ, &hidl_startSession_promise]( - BluetoothAudioStatus status, - const DataMQ::Descriptor& dataMQ) { + BluetoothAudioStatus status, const DataMQ::Descriptor& dataMQ) { log::info("startSession_cb({})", toString(status)); session_status = status; if (status == BluetoothAudioStatus::SUCCESS && dataMQ.isHandleValid()) { @@ -574,8 +515,8 @@ int BluetoothAudioClientInterface::StartSession() { } hidl_startSession_promise.set_value(); }; - auto hidl_retval = provider_->startSession( - stack_if, transport_->GetAudioConfiguration(), hidl_cb); + auto hidl_retval = + provider_->startSession(stack_if, transport_->GetAudioConfiguration(), hidl_cb); hidl_startSession_future.get(); if (!hidl_retval.isOk()) { log::fatal("BluetoothAudioHal failure: {}", hidl_retval.description()); @@ -584,8 +525,7 @@ int BluetoothAudioClientInterface::StartSession() { if (tempDataMQ && tempDataMQ->isValid()) { mDataMQ = std::move(tempDataMQ); - } else if (transport_->GetSessionType() == - SessionType::A2DP_HARDWARE_OFFLOAD_DATAPATH && + } else if (transport_->GetSessionType() == SessionType::A2DP_HARDWARE_OFFLOAD_DATAPATH && session_status == BluetoothAudioStatus::SUCCESS) { transport_->ResetPresentationPosition(); session_started_ = true; @@ -617,8 +557,7 @@ int BluetoothAudioClientInterface::StartSession_2_1() { return -EBUSY; } - android::sp stack_if = - new BluetoothAudioPortImpl(transport_, provider_2_1_); + android::sp stack_if = new BluetoothAudioPortImpl(transport_, provider_2_1_); std::unique_ptr tempDataMQ; BluetoothAudioStatus session_status; @@ -626,8 +565,7 @@ int BluetoothAudioClientInterface::StartSession_2_1() { std::promise hidl_startSession_promise; auto hidl_startSession_future = hidl_startSession_promise.get_future(); auto hidl_cb = [&session_status, &tempDataMQ, &hidl_startSession_promise]( - BluetoothAudioStatus status, - const DataMQ::Descriptor& dataMQ) { + BluetoothAudioStatus status, const DataMQ::Descriptor& dataMQ) { log::info("startSession_cb({})", toString(status)); session_status = status; if (status == BluetoothAudioStatus::SUCCESS && dataMQ.isHandleValid()) { @@ -636,7 +574,7 @@ int BluetoothAudioClientInterface::StartSession_2_1() { hidl_startSession_promise.set_value(); }; auto hidl_retval = provider_2_1_->startSession_2_1( - stack_if, transport_->GetAudioConfiguration_2_1(), hidl_cb); + stack_if, transport_->GetAudioConfiguration_2_1(), hidl_cb); hidl_startSession_future.get(); if (!hidl_retval.isOk()) { log::fatal("BluetoothAudioHal failure: {}", hidl_retval.description()); @@ -645,8 +583,7 @@ int BluetoothAudioClientInterface::StartSession_2_1() { if (tempDataMQ && tempDataMQ->isValid()) { mDataMQ = std::move(tempDataMQ); - } else if (transport_->GetSessionType_2_1() == - SessionType_2_1::A2DP_HARDWARE_OFFLOAD_DATAPATH && + } else if (transport_->GetSessionType_2_1() == SessionType_2_1::A2DP_HARDWARE_OFFLOAD_DATAPATH && session_status == BluetoothAudioStatus::SUCCESS) { transport_->ResetPresentationPosition(); session_started_ = true; @@ -666,8 +603,7 @@ int BluetoothAudioClientInterface::StartSession_2_1() { return -EIO; } -void BluetoothAudioClientInterface::StreamStarted( - const BluetoothAudioCtrlAck& ack) { +void BluetoothAudioClientInterface::StreamStarted(const BluetoothAudioCtrlAck& ack) { if (ack == BluetoothAudioCtrlAck::PENDING) { log::info("{} ignored", ack); return; @@ -689,8 +625,7 @@ void BluetoothAudioClientInterface::StreamStarted( } } -void BluetoothAudioClientInterface::StreamSuspended( - const BluetoothAudioCtrlAck& ack) { +void BluetoothAudioClientInterface::StreamSuspended(const BluetoothAudioCtrlAck& ack) { if (ack == BluetoothAudioCtrlAck::PENDING) { log::info("{} ignored", ack); return; @@ -741,10 +676,11 @@ int BluetoothAudioClientInterface::EndSession() { void BluetoothAudioClientInterface::FlushAudioData() { if (transport_->GetSessionType_2_1() == - SessionType_2_1::LE_AUDIO_HARDWARE_OFFLOAD_ENCODING_DATAPATH || + SessionType_2_1::LE_AUDIO_HARDWARE_OFFLOAD_ENCODING_DATAPATH || transport_->GetSessionType_2_1() == - SessionType_2_1::LE_AUDIO_HARDWARE_OFFLOAD_DECODING_DATAPATH) + SessionType_2_1::LE_AUDIO_HARDWARE_OFFLOAD_DECODING_DATAPATH) { return; + } if (mDataMQ == nullptr || !mDataMQ->isValid()) { log::warn("mDataMQ invalid"); @@ -758,24 +694,28 @@ void BluetoothAudioClientInterface::FlushAudioData() { uint8_t p_buf[size]; - if (mDataMQ->read(p_buf, size) != size) + if (mDataMQ->read(p_buf, size) != size) { log::warn("failed to flush data queue!"); + } } -size_t BluetoothAudioSinkClientInterface::ReadAudioData(uint8_t* p_buf, - uint32_t len) { +size_t BluetoothAudioSinkClientInterface::ReadAudioData(uint8_t* p_buf, uint32_t len) { if (!IsValid()) { log::error("BluetoothAudioHal is not valid"); return 0; } - if (p_buf == nullptr || len == 0) return 0; + if (p_buf == nullptr || len == 0) { + return 0; + } std::lock_guard guard(internal_mutex_); size_t total_read = 0; int timeout_ms = kDefaultDataReadTimeoutMs; do { - if (mDataMQ == nullptr || !mDataMQ->isValid()) break; + if (mDataMQ == nullptr || !mDataMQ->isValid()) { + break; + } size_t avail_to_read = mDataMQ->availableToRead(); if (avail_to_read) { @@ -788,8 +728,7 @@ size_t BluetoothAudioSinkClientInterface::ReadAudioData(uint8_t* p_buf, } total_read += avail_to_read; } else if (timeout_ms >= kDefaultDataReadPollIntervalMs) { - std::this_thread::sleep_for( - std::chrono::milliseconds(kDefaultDataReadPollIntervalMs)); + std::this_thread::sleep_for(std::chrono::milliseconds(kDefaultDataReadPollIntervalMs)); timeout_ms -= kDefaultDataReadPollIntervalMs; continue; } else { @@ -799,8 +738,7 @@ size_t BluetoothAudioSinkClientInterface::ReadAudioData(uint8_t* p_buf, } } while (total_read < len); - if (timeout_ms < - (kDefaultDataReadTimeoutMs - kDefaultDataReadPollIntervalMs) && + if (timeout_ms < (kDefaultDataReadTimeoutMs - kDefaultDataReadPollIntervalMs) && timeout_ms >= kDefaultDataReadPollIntervalMs) { log::verbose("underflow {} -> {} read {} ms", len, total_read, kDefaultDataReadTimeoutMs - timeout_ms); @@ -830,27 +768,31 @@ void BluetoothAudioClientInterface::RenewAudioProviderAndSession() { log::info("Restart the session while audio HAL recovering"); session_started_ = false; - if (provider_2_1_ != nullptr) + if (provider_2_1_ != nullptr) { StartSession_2_1(); - else + } else { StartSession(); + } } } -size_t BluetoothAudioSourceClientInterface::WriteAudioData(const uint8_t* p_buf, - uint32_t len) { +size_t BluetoothAudioSourceClientInterface::WriteAudioData(const uint8_t* p_buf, uint32_t len) { if (!IsValid()) { log::error("BluetoothAudioHal is not valid"); return 0; } - if (p_buf == nullptr || len == 0) return 0; + if (p_buf == nullptr || len == 0) { + return 0; + } std::lock_guard guard(internal_mutex_); size_t total_written = 0; int timeout_ms = kDefaultDataWriteTimeoutMs; do { - if (mDataMQ == nullptr || !mDataMQ->isValid()) break; + if (mDataMQ == nullptr || !mDataMQ->isValid()) { + break; + } size_t avail_to_write = mDataMQ->availableToWrite(); if (avail_to_write) { @@ -863,8 +805,7 @@ size_t BluetoothAudioSourceClientInterface::WriteAudioData(const uint8_t* p_buf, } total_written += avail_to_write; } else if (timeout_ms >= kDefaultDataWritePollIntervalMs) { - std::this_thread::sleep_for( - std::chrono::milliseconds(kDefaultDataWritePollIntervalMs)); + std::this_thread::sleep_for(std::chrono::milliseconds(kDefaultDataWritePollIntervalMs)); timeout_ms -= kDefaultDataWritePollIntervalMs; continue; } else { @@ -874,8 +815,7 @@ size_t BluetoothAudioSourceClientInterface::WriteAudioData(const uint8_t* p_buf, } } while (total_written < len); - if (timeout_ms < - (kDefaultDataWriteTimeoutMs - kDefaultDataWritePollIntervalMs) && + if (timeout_ms < (kDefaultDataWriteTimeoutMs - kDefaultDataWritePollIntervalMs) && timeout_ms >= kDefaultDataWritePollIntervalMs) { log::verbose("underflow {} -> {} read {} ms", len, total_written, kDefaultDataWriteTimeoutMs - timeout_ms); diff --git a/system/audio_hal_interface/hidl/client_interface_hidl.h b/system/audio_hal_interface/hidl/client_interface_hidl.h index 54cea599360..2ffeed0b1fc 100644 --- a/system/audio_hal_interface/hidl/client_interface_hidl.h +++ b/system/audio_hal_interface/hidl/client_interface_hidl.h @@ -28,39 +28,30 @@ #include "common/message_loop_thread.h" -#define BLUETOOTH_AUDIO_HAL_PROP_DISABLED \ - "persist.bluetooth.bluetooth_audio_hal.disabled" +#define BLUETOOTH_AUDIO_HAL_PROP_DISABLED "persist.bluetooth.bluetooth_audio_hal.disabled" namespace bluetooth { namespace audio { namespace hidl { -using AudioCapabilities = - ::android::hardware::bluetooth::audio::V2_0::AudioCapabilities; -using AudioCapabilities_2_1 = - ::android::hardware::bluetooth::audio::V2_1::AudioCapabilities; -using AudioConfiguration = - ::android::hardware::bluetooth::audio::V2_0::AudioConfiguration; -using AudioConfiguration_2_1 = - ::android::hardware::bluetooth::audio::V2_1::AudioConfiguration; +using AudioCapabilities = ::android::hardware::bluetooth::audio::V2_0::AudioCapabilities; +using AudioCapabilities_2_1 = ::android::hardware::bluetooth::audio::V2_1::AudioCapabilities; +using AudioConfiguration = ::android::hardware::bluetooth::audio::V2_0::AudioConfiguration; +using AudioConfiguration_2_1 = ::android::hardware::bluetooth::audio::V2_1::AudioConfiguration; using ::android::hardware::bluetooth::audio::V2_0::BitsPerSample; using ::android::hardware::bluetooth::audio::V2_0::ChannelMode; using IBluetoothAudioProvider = - ::android::hardware::bluetooth::audio::V2_0::IBluetoothAudioProvider; + ::android::hardware::bluetooth::audio::V2_0::IBluetoothAudioProvider; using IBluetoothAudioProvider_2_1 = - ::android::hardware::bluetooth::audio::V2_1::IBluetoothAudioProvider; -using PcmParameters = - ::android::hardware::bluetooth::audio::V2_0::PcmParameters; -using PcmParameters_2_1 = - ::android::hardware::bluetooth::audio::V2_1::PcmParameters; + ::android::hardware::bluetooth::audio::V2_1::IBluetoothAudioProvider; +using PcmParameters = ::android::hardware::bluetooth::audio::V2_0::PcmParameters; +using PcmParameters_2_1 = ::android::hardware::bluetooth::audio::V2_1::PcmParameters; using SampleRate = ::android::hardware::bluetooth::audio::V2_0::SampleRate; using SampleRate_2_1 = ::android::hardware::bluetooth::audio::V2_1::SampleRate; using SessionType = ::android::hardware::bluetooth::audio::V2_0::SessionType; -using SessionType_2_1 = - ::android::hardware::bluetooth::audio::V2_1::SessionType; +using SessionType_2_1 = ::android::hardware::bluetooth::audio::V2_1::SessionType; using ::android::hardware::bluetooth::audio::V2_0::TimeSpec; -using BluetoothAudioStatus = - ::android::hardware::bluetooth::audio::V2_0::Status; +using BluetoothAudioStatus = ::android::hardware::bluetooth::audio::V2_0::Status; enum class BluetoothAudioCtrlAck : uint8_t { SUCCESS_FINISHED = 0, @@ -73,8 +64,7 @@ enum class BluetoothAudioCtrlAck : uint8_t { std::ostream& operator<<(std::ostream& os, const BluetoothAudioCtrlAck& ack); -inline BluetoothAudioStatus BluetoothAudioCtrlAckToHalStatus( - const BluetoothAudioCtrlAck& ack) { +inline BluetoothAudioStatus BluetoothAudioCtrlAckToHalStatus(const BluetoothAudioCtrlAck& ack) { switch (ack) { case BluetoothAudioCtrlAck::SUCCESS_FINISHED: return BluetoothAudioStatus::SUCCESS; @@ -95,34 +85,30 @@ inline BluetoothAudioStatus BluetoothAudioCtrlAckToHalStatus( // audio transport, such as A2DP or Hearing Aid, to handle callbacks from Audio // HAL. class IBluetoothTransportInstance { - public: - IBluetoothTransportInstance(SessionType sessionType, - AudioConfiguration audioConfig) +public: + IBluetoothTransportInstance(SessionType sessionType, AudioConfiguration audioConfig) : session_type_(sessionType), session_type_2_1_(SessionType_2_1::UNKNOWN), audio_config_(std::move(audioConfig)), - audio_config_2_1_({}){}; + audio_config_2_1_({}) {} IBluetoothTransportInstance(SessionType_2_1 sessionType_2_1, AudioConfiguration_2_1 audioConfig_2_1) : session_type_(SessionType::UNKNOWN), session_type_2_1_(sessionType_2_1), audio_config_({}), - audio_config_2_1_(std::move(audioConfig_2_1)){}; + audio_config_2_1_(std::move(audioConfig_2_1)) {} virtual ~IBluetoothTransportInstance() = default; SessionType GetSessionType() const { return session_type_; } SessionType_2_1 GetSessionType_2_1() const { return session_type_2_1_; } AudioConfiguration GetAudioConfiguration() const { return audio_config_; } - AudioConfiguration_2_1 GetAudioConfiguration_2_1() const { - return audio_config_2_1_; - } + AudioConfiguration_2_1 GetAudioConfiguration_2_1() const { return audio_config_2_1_; } void UpdateAudioConfiguration(const AudioConfiguration& audio_config) { audio_config_ = audio_config; } - void UpdateAudioConfiguration_2_1( - const AudioConfiguration_2_1& audio_config_2_1) { + void UpdateAudioConfiguration_2_1(const AudioConfiguration_2_1& audio_config_2_1) { audio_config_2_1_ = audio_config_2_1; } @@ -133,15 +119,14 @@ class IBluetoothTransportInstance { virtual void StopRequest() = 0; virtual bool GetPresentationPosition(uint64_t* remote_delay_report_ns, - uint64_t* total_bytes_readed, - timespec* data_position) = 0; + uint64_t* total_bytes_readed, timespec* data_position) = 0; virtual void MetadataChanged(const source_metadata_t& source_metadata) = 0; // Invoked when the transport is requested to reset presentation position virtual void ResetPresentationPosition() = 0; - private: +private: const SessionType session_type_; const SessionType_2_1 session_type_2_1_; AudioConfiguration audio_config_; @@ -152,9 +137,8 @@ class IBluetoothTransportInstance { // audio transport, such as A2DP, Hearing Aid or LeAudio, to handle callbacks // from Audio HAL. class IBluetoothSinkTransportInstance : public IBluetoothTransportInstance { - public: - IBluetoothSinkTransportInstance(SessionType sessionType, - AudioConfiguration audioConfig) +public: + IBluetoothSinkTransportInstance(SessionType sessionType, AudioConfiguration audioConfig) : IBluetoothTransportInstance{sessionType, audioConfig} {} IBluetoothSinkTransportInstance(SessionType_2_1 sessionType_2_1, AudioConfiguration_2_1 audioConfig_2_1) @@ -166,9 +150,8 @@ class IBluetoothSinkTransportInstance : public IBluetoothTransportInstance { }; class IBluetoothSourceTransportInstance : public IBluetoothTransportInstance { - public: - IBluetoothSourceTransportInstance(SessionType sessionType, - AudioConfiguration audioConfig) +public: + IBluetoothSourceTransportInstance(SessionType sessionType, AudioConfiguration audioConfig) : IBluetoothTransportInstance{sessionType, audioConfig} {} IBluetoothSourceTransportInstance(SessionType_2_1 sessionType_2_1, AudioConfiguration_2_1 audioConfig_2_1) @@ -186,20 +169,18 @@ class BluetoothAudioDeathRecipient; // IBluetoothAudioProvider and helps to route callbacks to // IBluetoothTransportInstance class BluetoothAudioClientInterface { - public: - BluetoothAudioClientInterface( - android::sp death_recipient, - IBluetoothTransportInstance* instance); +public: + BluetoothAudioClientInterface(android::sp death_recipient, + IBluetoothTransportInstance* instance); virtual ~BluetoothAudioClientInterface() = default; bool IsValid() const; std::vector GetAudioCapabilities() const; std::vector GetAudioCapabilities_2_1() const; - static std::vector GetAudioCapabilities( - SessionType session_type); + static std::vector GetAudioCapabilities(SessionType session_type); static std::vector GetAudioCapabilities_2_1( - SessionType_2_1 session_type_2_1); + SessionType_2_1 session_type_2_1); void StreamStarted(const BluetoothAudioCtrlAck& ack); @@ -219,11 +200,11 @@ class BluetoothAudioClientInterface { void FlushAudioData(); static constexpr PcmParameters kInvalidPcmConfiguration = { - .sampleRate = SampleRate::RATE_UNKNOWN, - .channelMode = ChannelMode::UNKNOWN, - .bitsPerSample = BitsPerSample::BITS_UNKNOWN}; + .sampleRate = SampleRate::RATE_UNKNOWN, + .channelMode = ChannelMode::UNKNOWN, + .bitsPerSample = BitsPerSample::BITS_UNKNOWN}; - protected: +protected: mutable std::mutex internal_mutex_; // Helper function to connect to an IBluetoothAudioProvider void FetchAudioProvider(); @@ -233,12 +214,12 @@ class BluetoothAudioClientInterface { android::sp provider_; android::sp provider_2_1_; bool session_started_; - std::unique_ptr<::android::hardware::MessageQueue< - uint8_t, ::android::hardware::kSynchronizedReadWrite>> - mDataMQ; + std::unique_ptr< + ::android::hardware::MessageQueue> + mDataMQ; android::sp death_recipient_; - private: +private: IBluetoothTransportInstance* transport_; std::vector capabilities_; std::vector capabilities_2_1_; @@ -248,45 +229,38 @@ class BluetoothAudioClientInterface { // IBluetoothAudioProvider and helps to route callbacks to // IBluetoothTransportInstance class BluetoothAudioSinkClientInterface : public BluetoothAudioClientInterface { - public: +public: // Constructs an BluetoothAudioSinkClientInterface to communicate to // BluetoothAudio HAL. |sink| is the implementation for the transport, and // |message_loop| is the thread where callbacks are invoked. - BluetoothAudioSinkClientInterface( - IBluetoothSinkTransportInstance* sink, - bluetooth::common::MessageLoopThread* message_loop); + BluetoothAudioSinkClientInterface(IBluetoothSinkTransportInstance* sink, + bluetooth::common::MessageLoopThread* message_loop); virtual ~BluetoothAudioSinkClientInterface(); - IBluetoothSinkTransportInstance* GetTransportInstance() const { - return sink_; - } + IBluetoothSinkTransportInstance* GetTransportInstance() const { return sink_; } // Read data from audio HAL through fmq size_t ReadAudioData(uint8_t* p_buf, uint32_t len); - private: +private: IBluetoothSinkTransportInstance* sink_; }; -class BluetoothAudioSourceClientInterface - : public BluetoothAudioClientInterface { - public: +class BluetoothAudioSourceClientInterface : public BluetoothAudioClientInterface { +public: // Constructs an BluetoothAudioSourceClientInterface to communicate to // BluetoothAudio HAL. |source| is the implementation for the transport, and // |message_loop| is the thread where callbacks are invoked. - BluetoothAudioSourceClientInterface( - IBluetoothSourceTransportInstance* source, - bluetooth::common::MessageLoopThread* message_loop); + BluetoothAudioSourceClientInterface(IBluetoothSourceTransportInstance* source, + bluetooth::common::MessageLoopThread* message_loop); virtual ~BluetoothAudioSourceClientInterface(); - IBluetoothSourceTransportInstance* GetTransportInstance() const { - return source_; - } + IBluetoothSourceTransportInstance* GetTransportInstance() const { return source_; } // Write data to audio HAL through fmq size_t WriteAudioData(const uint8_t* p_buf, uint32_t len); - private: +private: IBluetoothSourceTransportInstance* source_; }; diff --git a/system/audio_hal_interface/hidl/client_interface_hidl_unittest.cc b/system/audio_hal_interface/hidl/client_interface_hidl_unittest.cc index 59c7982563d..e29f543b590 100644 --- a/system/audio_hal_interface/hidl/client_interface_hidl_unittest.cc +++ b/system/audio_hal_interface/hidl/client_interface_hidl_unittest.cc @@ -70,79 +70,75 @@ struct SampleRatePair { btav_a2dp_codec_sample_rate_t btav_sample_rate_; }; constexpr SampleRatePair kSampleRatePairs[9] = { - {.hal_sample_rate_ = SampleRate::RATE_UNKNOWN, - .btav_sample_rate_ = BTAV_A2DP_CODEC_SAMPLE_RATE_NONE}, - {.hal_sample_rate_ = SampleRate::RATE_44100, - .btav_sample_rate_ = BTAV_A2DP_CODEC_SAMPLE_RATE_44100}, - {.hal_sample_rate_ = SampleRate::RATE_48000, - .btav_sample_rate_ = BTAV_A2DP_CODEC_SAMPLE_RATE_48000}, - {.hal_sample_rate_ = SampleRate::RATE_88200, - .btav_sample_rate_ = BTAV_A2DP_CODEC_SAMPLE_RATE_88200}, - {.hal_sample_rate_ = SampleRate::RATE_96000, - .btav_sample_rate_ = BTAV_A2DP_CODEC_SAMPLE_RATE_96000}, - {.hal_sample_rate_ = SampleRate::RATE_176400, - .btav_sample_rate_ = BTAV_A2DP_CODEC_SAMPLE_RATE_176400}, - {.hal_sample_rate_ = SampleRate::RATE_192000, - .btav_sample_rate_ = BTAV_A2DP_CODEC_SAMPLE_RATE_192000}, - {.hal_sample_rate_ = SampleRate::RATE_16000, - .btav_sample_rate_ = BTAV_A2DP_CODEC_SAMPLE_RATE_16000}, - {.hal_sample_rate_ = SampleRate::RATE_24000, - .btav_sample_rate_ = BTAV_A2DP_CODEC_SAMPLE_RATE_24000}}; + {.hal_sample_rate_ = SampleRate::RATE_UNKNOWN, + .btav_sample_rate_ = BTAV_A2DP_CODEC_SAMPLE_RATE_NONE}, + {.hal_sample_rate_ = SampleRate::RATE_44100, + .btav_sample_rate_ = BTAV_A2DP_CODEC_SAMPLE_RATE_44100}, + {.hal_sample_rate_ = SampleRate::RATE_48000, + .btav_sample_rate_ = BTAV_A2DP_CODEC_SAMPLE_RATE_48000}, + {.hal_sample_rate_ = SampleRate::RATE_88200, + .btav_sample_rate_ = BTAV_A2DP_CODEC_SAMPLE_RATE_88200}, + {.hal_sample_rate_ = SampleRate::RATE_96000, + .btav_sample_rate_ = BTAV_A2DP_CODEC_SAMPLE_RATE_96000}, + {.hal_sample_rate_ = SampleRate::RATE_176400, + .btav_sample_rate_ = BTAV_A2DP_CODEC_SAMPLE_RATE_176400}, + {.hal_sample_rate_ = SampleRate::RATE_192000, + .btav_sample_rate_ = BTAV_A2DP_CODEC_SAMPLE_RATE_192000}, + {.hal_sample_rate_ = SampleRate::RATE_16000, + .btav_sample_rate_ = BTAV_A2DP_CODEC_SAMPLE_RATE_16000}, + {.hal_sample_rate_ = SampleRate::RATE_24000, + .btav_sample_rate_ = BTAV_A2DP_CODEC_SAMPLE_RATE_24000}}; constexpr SampleRate_2_1 kSampleRates_2_1[] = { - SampleRate_2_1::RATE_UNKNOWN, SampleRate_2_1::RATE_8000, - SampleRate_2_1::RATE_16000, SampleRate_2_1::RATE_24000, - SampleRate_2_1::RATE_32000, SampleRate_2_1::RATE_44100, - SampleRate_2_1::RATE_48000}; + SampleRate_2_1::RATE_UNKNOWN, SampleRate_2_1::RATE_8000, SampleRate_2_1::RATE_16000, + SampleRate_2_1::RATE_24000, SampleRate_2_1::RATE_32000, SampleRate_2_1::RATE_44100, + SampleRate_2_1::RATE_48000}; -constexpr uint32_t kDataIntervalUs[] = {0 /* Invalid */, - 10000 /* Valid 10ms */}; +constexpr uint32_t kDataIntervalUs[] = {0 /* Invalid */, 10000 /* Valid 10ms */}; struct BitsPerSamplePair { BitsPerSample hal_bits_per_sample_; btav_a2dp_codec_bits_per_sample_t btav_bits_per_sample_; }; constexpr BitsPerSamplePair kBitsPerSamplePairs[4] = { - {.hal_bits_per_sample_ = BitsPerSample::BITS_UNKNOWN, - .btav_bits_per_sample_ = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE}, - {.hal_bits_per_sample_ = BitsPerSample::BITS_16, - .btav_bits_per_sample_ = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16}, - {.hal_bits_per_sample_ = BitsPerSample::BITS_24, - .btav_bits_per_sample_ = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24}, - {.hal_bits_per_sample_ = BitsPerSample::BITS_32, - .btav_bits_per_sample_ = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32}}; + {.hal_bits_per_sample_ = BitsPerSample::BITS_UNKNOWN, + .btav_bits_per_sample_ = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE}, + {.hal_bits_per_sample_ = BitsPerSample::BITS_16, + .btav_bits_per_sample_ = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16}, + {.hal_bits_per_sample_ = BitsPerSample::BITS_24, + .btav_bits_per_sample_ = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24}, + {.hal_bits_per_sample_ = BitsPerSample::BITS_32, + .btav_bits_per_sample_ = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32}}; struct ChannelModePair { ChannelMode hal_channel_mode_; btav_a2dp_codec_channel_mode_t btav_channel_mode_; }; constexpr ChannelModePair kChannelModePairs[3] = { - {.hal_channel_mode_ = ChannelMode::UNKNOWN, - .btav_channel_mode_ = BTAV_A2DP_CODEC_CHANNEL_MODE_NONE}, - {.hal_channel_mode_ = ChannelMode::MONO, - .btav_channel_mode_ = BTAV_A2DP_CODEC_CHANNEL_MODE_MONO}, - {.hal_channel_mode_ = ChannelMode::STEREO, - .btav_channel_mode_ = BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO}}; + {.hal_channel_mode_ = ChannelMode::UNKNOWN, + .btav_channel_mode_ = BTAV_A2DP_CODEC_CHANNEL_MODE_NONE}, + {.hal_channel_mode_ = ChannelMode::MONO, + .btav_channel_mode_ = BTAV_A2DP_CODEC_CHANNEL_MODE_MONO}, + {.hal_channel_mode_ = ChannelMode::STEREO, + .btav_channel_mode_ = BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO}}; constexpr btav_a2dp_codec_index_t codec_indexes[] = { - BTAV_A2DP_CODEC_INDEX_SOURCE_SBC, BTAV_A2DP_CODEC_INDEX_SOURCE_AAC, - BTAV_A2DP_CODEC_INDEX_SOURCE_APTX, BTAV_A2DP_CODEC_INDEX_SOURCE_APTX_HD, - BTAV_A2DP_CODEC_INDEX_SOURCE_LDAC, BTAV_A2DP_CODEC_INDEX_SINK_SBC, - BTAV_A2DP_CODEC_INDEX_SINK_AAC, BTAV_A2DP_CODEC_INDEX_SINK_LDAC}; + BTAV_A2DP_CODEC_INDEX_SOURCE_SBC, BTAV_A2DP_CODEC_INDEX_SOURCE_AAC, + BTAV_A2DP_CODEC_INDEX_SOURCE_APTX, BTAV_A2DP_CODEC_INDEX_SOURCE_APTX_HD, + BTAV_A2DP_CODEC_INDEX_SOURCE_LDAC, BTAV_A2DP_CODEC_INDEX_SINK_SBC, + BTAV_A2DP_CODEC_INDEX_SINK_AAC, BTAV_A2DP_CODEC_INDEX_SINK_LDAC}; constexpr uint16_t kPeerMtus[5] = {660, 663, 883, 1005, 1500}; -class TestSinkTransport - : public bluetooth::audio::hidl::IBluetoothSinkTransportInstance { - private: +class TestSinkTransport : public bluetooth::audio::hidl::IBluetoothSinkTransportInstance { +private: static constexpr uint64_t kRemoteDelayReportMs = 200; - public: +public: TestSinkTransport(SessionType session_type) - : bluetooth::audio::hidl::IBluetoothSinkTransportInstance(session_type, - {}){}; + : bluetooth::audio::hidl::IBluetoothSinkTransportInstance(session_type, {}) {} TestSinkTransport(SessionType_2_1 session_type_2_1) - : bluetooth::audio::hidl::IBluetoothSinkTransportInstance( - session_type_2_1, (AudioConfiguration_2_1){}){}; + : bluetooth::audio::hidl::IBluetoothSinkTransportInstance(session_type_2_1, + (AudioConfiguration_2_1){}) {} bluetooth::audio::hidl::BluetoothAudioCtrlAck StartRequest() override { return bluetooth::audio::hidl::BluetoothAudioCtrlAck::SUCCESS_FINISHED; } @@ -150,8 +146,7 @@ class TestSinkTransport return bluetooth::audio::hidl::BluetoothAudioCtrlAck::SUCCESS_FINISHED; } void StopRequest() override {} - bool GetPresentationPosition(uint64_t* remote_delay_report_ns, - uint64_t* total_bytes_readed, + bool GetPresentationPosition(uint64_t* remote_delay_report_ns, uint64_t* total_bytes_readed, timespec* data_position) override { if (remote_delay_report_ns) { *remote_delay_report_ns = kRemoteDelayReportMs * 1000000; @@ -164,24 +159,21 @@ class TestSinkTransport } return true; } - void MetadataChanged( - const source_metadata_t& source_metadata __unused) override {} - void ResetPresentationPosition() override{}; - void LogBytesRead(size_t bytes_readed __unused) override{}; + void MetadataChanged(const source_metadata_t& source_metadata __unused) override {} + void ResetPresentationPosition() override {} + void LogBytesRead(size_t bytes_readed __unused) override {} }; -class TestSourceTransport - : public bluetooth::audio::hidl::IBluetoothSourceTransportInstance { - private: +class TestSourceTransport : public bluetooth::audio::hidl::IBluetoothSourceTransportInstance { +private: static constexpr uint64_t kRemoteDelayReportMs = 200; - public: +public: TestSourceTransport(SessionType session_type) - : bluetooth::audio::hidl::IBluetoothSourceTransportInstance(session_type, - {}){}; + : bluetooth::audio::hidl::IBluetoothSourceTransportInstance(session_type, {}) {} TestSourceTransport(SessionType_2_1 session_type_2_1) - : bluetooth::audio::hidl::IBluetoothSourceTransportInstance( - session_type_2_1, (AudioConfiguration_2_1){}){}; + : bluetooth::audio::hidl::IBluetoothSourceTransportInstance(session_type_2_1, + (AudioConfiguration_2_1){}) {} bluetooth::audio::hidl::BluetoothAudioCtrlAck StartRequest() override { return bluetooth::audio::hidl::BluetoothAudioCtrlAck::SUCCESS_FINISHED; } @@ -189,8 +181,7 @@ class TestSourceTransport return bluetooth::audio::hidl::BluetoothAudioCtrlAck::SUCCESS_FINISHED; } void StopRequest() override {} - bool GetPresentationPosition(uint64_t* remote_delay_report_ns, - uint64_t* total_bytes_written, + bool GetPresentationPosition(uint64_t* remote_delay_report_ns, uint64_t* total_bytes_written, timespec* data_position) override { if (remote_delay_report_ns) { *remote_delay_report_ns = kRemoteDelayReportMs * 1000000; @@ -203,14 +194,13 @@ class TestSourceTransport } return true; } - void MetadataChanged( - const source_metadata_t& source_metadata __unused) override {} - void ResetPresentationPosition() override{}; - void LogBytesWritten(size_t bytes_written __unused) override{}; + void MetadataChanged(const source_metadata_t& source_metadata __unused) override {} + void ResetPresentationPosition() override {} + void LogBytesWritten(size_t bytes_written __unused) override {} }; class BluetoothAudioClientInterfaceTest : public Test { - protected: +protected: TestSinkTransport* test_sink_transport_ = nullptr; TestSourceTransport* test_source_transport_ = nullptr; BluetoothAudioSinkClientInterface* clientif_sink_ = nullptr; @@ -221,47 +211,49 @@ class BluetoothAudioClientInterfaceTest : public Test { void SetUp() override {} void TearDown() override { - if (clientif_sink_ != nullptr) delete clientif_sink_; + if (clientif_sink_ != nullptr) { + delete clientif_sink_; + } clientif_sink_ = nullptr; - if (test_sink_transport_ != nullptr) delete test_sink_transport_; + if (test_sink_transport_ != nullptr) { + delete test_sink_transport_; + } test_sink_transport_ = nullptr; - if (clientif_source_ != nullptr) delete clientif_source_; + if (clientif_source_ != nullptr) { + delete clientif_source_; + } clientif_source_ = nullptr; - if (test_source_transport_ != nullptr) delete test_source_transport_; + if (test_source_transport_ != nullptr) { + delete test_source_transport_; + } test_source_transport_ = nullptr; } bool IsSoftwarePcmParametersSupported(const PcmParameters& pcm_config) { - const std::vector& capabilities = - clientif_sink_->GetAudioCapabilities(); + const std::vector& capabilities = clientif_sink_->GetAudioCapabilities(); PcmParameters pcm_capabilities = capabilities[0].pcmCapabilities(); - bool is_pcm_config_valid = - (pcm_config.sampleRate != SampleRate::RATE_UNKNOWN && - pcm_config.bitsPerSample != BitsPerSample::BITS_UNKNOWN && - pcm_config.channelMode != ChannelMode::UNKNOWN); - bool is_pcm_config_supported = - (pcm_config.sampleRate & pcm_capabilities.sampleRate && - pcm_config.bitsPerSample & pcm_capabilities.bitsPerSample && - pcm_config.channelMode & pcm_capabilities.channelMode); - return (is_pcm_config_valid && is_pcm_config_supported); + bool is_pcm_config_valid = (pcm_config.sampleRate != SampleRate::RATE_UNKNOWN && + pcm_config.bitsPerSample != BitsPerSample::BITS_UNKNOWN && + pcm_config.channelMode != ChannelMode::UNKNOWN); + bool is_pcm_config_supported = (pcm_config.sampleRate & pcm_capabilities.sampleRate && + pcm_config.bitsPerSample & pcm_capabilities.bitsPerSample && + pcm_config.channelMode & pcm_capabilities.channelMode); + return is_pcm_config_valid && is_pcm_config_supported; } - bool IsSinkSoftwarePcmParameters_2_1_Supported( - const PcmParameters_2_1& pcm_config) { + bool IsSinkSoftwarePcmParameters_2_1_Supported(const PcmParameters_2_1& pcm_config) { return IsSoftwarePcmParameters_2_1_Supported(pcm_config, clientif_sink_); } - bool IsSourceSoftwarePcmParameters_2_1_Supported( - const PcmParameters_2_1& pcm_config) { + bool IsSourceSoftwarePcmParameters_2_1_Supported(const PcmParameters_2_1& pcm_config) { return IsSoftwarePcmParameters_2_1_Supported(pcm_config, clientif_source_); } bool IsCodecOffloadingSupported(const CodecConfiguration& codec_config) { CodecCapabilities codec_capability = {}; for (auto audio_capability : clientif_sink_->GetAudioCapabilities()) { - if (audio_capability.codecCapabilities().codecType == - codec_config.codecType) { + if (audio_capability.codecCapabilities().codecType == codec_config.codecType) { codec_capability = audio_capability.codecCapabilities(); } } @@ -273,55 +265,46 @@ class BluetoothAudioClientInterfaceTest : public Test { switch (codec_config.codecType) { case CodecType::SBC: { SbcParameters sbc_config = codec_config.config.sbcConfig(); - SbcParameters sbc_capability = - codec_capability.capabilities.sbcCapabilities(); - is_codec_config_supported = - (sbc_config.sampleRate & sbc_capability.sampleRate && - sbc_config.channelMode & sbc_capability.channelMode && - sbc_config.blockLength & sbc_capability.blockLength && - sbc_config.numSubbands & sbc_capability.numSubbands && - sbc_config.allocMethod & sbc_capability.allocMethod && - sbc_config.bitsPerSample & sbc_capability.bitsPerSample && - (sbc_capability.minBitpool <= sbc_config.minBitpool && - sbc_config.minBitpool <= sbc_config.maxBitpool && - sbc_config.maxBitpool <= sbc_capability.maxBitpool)); + SbcParameters sbc_capability = codec_capability.capabilities.sbcCapabilities(); + is_codec_config_supported = (sbc_config.sampleRate & sbc_capability.sampleRate && + sbc_config.channelMode & sbc_capability.channelMode && + sbc_config.blockLength & sbc_capability.blockLength && + sbc_config.numSubbands & sbc_capability.numSubbands && + sbc_config.allocMethod & sbc_capability.allocMethod && + sbc_config.bitsPerSample & sbc_capability.bitsPerSample && + (sbc_capability.minBitpool <= sbc_config.minBitpool && + sbc_config.minBitpool <= sbc_config.maxBitpool && + sbc_config.maxBitpool <= sbc_capability.maxBitpool)); return is_codec_config_supported; } case CodecType::AAC: { AacParameters aac_config = codec_config.config.aacConfig(); - AacParameters aac_capability = - codec_capability.capabilities.aacCapabilities(); + AacParameters aac_capability = codec_capability.capabilities.aacCapabilities(); is_codec_config_supported = - (aac_config.objectType & aac_capability.objectType && - aac_config.sampleRate & aac_capability.sampleRate && - aac_config.channelMode & aac_capability.channelMode && - (aac_config.variableBitRateEnabled == - AacVariableBitRate::DISABLED || - aac_capability.variableBitRateEnabled == - AacVariableBitRate::ENABLED) && - aac_config.bitsPerSample & aac_capability.bitsPerSample); + (aac_config.objectType & aac_capability.objectType && + aac_config.sampleRate & aac_capability.sampleRate && + aac_config.channelMode & aac_capability.channelMode && + (aac_config.variableBitRateEnabled == AacVariableBitRate::DISABLED || + aac_capability.variableBitRateEnabled == AacVariableBitRate::ENABLED) && + aac_config.bitsPerSample & aac_capability.bitsPerSample); return is_codec_config_supported; } case CodecType::LDAC: { LdacParameters ldac_config = codec_config.config.ldacConfig(); - LdacParameters ldac_capability = - codec_capability.capabilities.ldacCapabilities(); - is_codec_config_supported = - (ldac_config.sampleRate & ldac_capability.sampleRate && - ldac_config.channelMode & ldac_capability.channelMode && - ldac_config.bitsPerSample & ldac_capability.bitsPerSample); + LdacParameters ldac_capability = codec_capability.capabilities.ldacCapabilities(); + is_codec_config_supported = (ldac_config.sampleRate & ldac_capability.sampleRate && + ldac_config.channelMode & ldac_capability.channelMode && + ldac_config.bitsPerSample & ldac_capability.bitsPerSample); return is_codec_config_supported; } case CodecType::APTX: [[fallthrough]]; case CodecType::APTX_HD: { AptxParameters aptx_config = codec_config.config.aptxConfig(); - AptxParameters aptx_capability = - codec_capability.capabilities.aptxCapabilities(); - is_codec_config_supported = - (aptx_config.sampleRate & aptx_capability.sampleRate && - aptx_config.channelMode & aptx_capability.channelMode && - aptx_config.bitsPerSample & aptx_capability.bitsPerSample); + AptxParameters aptx_capability = codec_capability.capabilities.aptxCapabilities(); + is_codec_config_supported = (aptx_config.sampleRate & aptx_capability.sampleRate && + aptx_config.channelMode & aptx_capability.channelMode && + aptx_config.bitsPerSample & aptx_capability.bitsPerSample); return is_codec_config_supported; } case CodecType::UNKNOWN: @@ -329,23 +312,19 @@ class BluetoothAudioClientInterfaceTest : public Test { } } - private: - bool IsSoftwarePcmParameters_2_1_Supported( - const PcmParameters_2_1& pcm_config, - const BluetoothAudioClientInterface* clientif_) { - const std::vector& capabilities = - clientif_->GetAudioCapabilities_2_1(); +private: + bool IsSoftwarePcmParameters_2_1_Supported(const PcmParameters_2_1& pcm_config, + const BluetoothAudioClientInterface* clientif_) { + const std::vector& capabilities = clientif_->GetAudioCapabilities_2_1(); PcmParameters_2_1 pcm_capabilities = capabilities[0].pcmCapabilities(); bool is_pcm_config_valid = - (pcm_config.sampleRate != SampleRate_2_1::RATE_UNKNOWN && - pcm_config.bitsPerSample != BitsPerSample::BITS_UNKNOWN && - pcm_config.channelMode != ChannelMode::UNKNOWN && - pcm_config.dataIntervalUs != 0); - bool is_pcm_config_supported = - (pcm_config.sampleRate & pcm_capabilities.sampleRate && - pcm_config.bitsPerSample & pcm_capabilities.bitsPerSample && - pcm_config.channelMode & pcm_capabilities.channelMode); - return (is_pcm_config_valid && is_pcm_config_supported); + (pcm_config.sampleRate != SampleRate_2_1::RATE_UNKNOWN && + pcm_config.bitsPerSample != BitsPerSample::BITS_UNKNOWN && + pcm_config.channelMode != ChannelMode::UNKNOWN && pcm_config.dataIntervalUs != 0); + bool is_pcm_config_supported = (pcm_config.sampleRate & pcm_capabilities.sampleRate && + pcm_config.bitsPerSample & pcm_capabilities.bitsPerSample && + pcm_config.channelMode & pcm_capabilities.channelMode); + return is_pcm_config_valid && is_pcm_config_supported; } }; @@ -356,26 +335,22 @@ TEST_F(BluetoothAudioClientInterfaceTest, A2dpCodecToHalPcmConfig) { for (auto sample_rate_pair : kSampleRatePairs) { a2dp_codec_config.sample_rate = sample_rate_pair.btav_sample_rate_; for (auto bits_per_sample_pair : kBitsPerSamplePairs) { - a2dp_codec_config.bits_per_sample = - bits_per_sample_pair.btav_bits_per_sample_; + a2dp_codec_config.bits_per_sample = bits_per_sample_pair.btav_bits_per_sample_; for (auto channel_mode_pair : kChannelModePairs) { a2dp_codec_config.channel_mode = channel_mode_pair.btav_channel_mode_; - ASSERT_EQ(A2dpCodecToHalSampleRate(a2dp_codec_config), - sample_rate_pair.hal_sample_rate_); + ASSERT_EQ(A2dpCodecToHalSampleRate(a2dp_codec_config), sample_rate_pair.hal_sample_rate_); ASSERT_EQ(A2dpCodecToHalBitsPerSample(a2dp_codec_config), bits_per_sample_pair.hal_bits_per_sample_); ASSERT_EQ(A2dpCodecToHalChannelMode(a2dp_codec_config), channel_mode_pair.hal_channel_mode_); } // ChannelMode - } // BitsPerSampple - } // SampleRate + } // BitsPerSampple + } // SampleRate } TEST_F(BluetoothAudioClientInterfaceTest, StartAndEndA2dpSoftwareSession) { - test_sink_transport_ = - new TestSinkTransport(SessionType::A2DP_SOFTWARE_ENCODING_DATAPATH); - clientif_sink_ = - new BluetoothAudioSinkClientInterface(test_sink_transport_, nullptr); + test_sink_transport_ = new TestSinkTransport(SessionType::A2DP_SOFTWARE_ENCODING_DATAPATH); + clientif_sink_ = new BluetoothAudioSinkClientInterface(test_sink_transport_, nullptr); AudioConfiguration audio_config = {}; PcmParameters pcm_config = {}; for (auto sample_rate_pair : kSampleRatePairs) { @@ -393,8 +368,8 @@ TEST_F(BluetoothAudioClientInterfaceTest, StartAndEndA2dpSoftwareSession) { } ASSERT_EQ(clientif_sink_->EndSession(), kClientIfReturnSuccess); } // ChannelMode - } // BitsPerSampple - } // SampleRate + } // BitsPerSampple + } // SampleRate } struct CodecOffloadingPreference { @@ -403,16 +378,15 @@ struct CodecOffloadingPreference { }; std::vector CodecOffloadingPreferenceGenerator( - btav_a2dp_codec_index_t target_codec_index) { + btav_a2dp_codec_index_t target_codec_index) { std::vector codec_offloading_preferences = { - {.is_target_codec_included_ = false, - .preference_ = std::vector(0)}}; + {.is_target_codec_included_ = false, + .preference_ = std::vector(0)}}; btav_a2dp_codec_config_t a2dp_codec_config = {}; for (auto codec_index : codec_indexes) { a2dp_codec_config.codec_type = codec_index; auto duplicated_preferences = codec_offloading_preferences; - for (auto iter = duplicated_preferences.begin(); - iter != duplicated_preferences.end(); ++iter) { + for (auto iter = duplicated_preferences.begin(); iter != duplicated_preferences.end(); ++iter) { if (codec_index == target_codec_index) { iter->is_target_codec_included_ = true; } @@ -428,13 +402,10 @@ std::vector CodecOffloadingPreferenceGenerator( std::vector SbcCodecConfigurationsGenerator() { std::vector sbc_codec_configs; CodecConfiguration codec_config = {}; - SbcBlockLength block_lengths[4] = { - SbcBlockLength::BLOCKS_4, SbcBlockLength::BLOCKS_8, - SbcBlockLength::BLOCKS_12, SbcBlockLength::BLOCKS_16}; - SbcNumSubbands num_subbands[2] = {SbcNumSubbands::SUBBAND_4, - SbcNumSubbands::SUBBAND_8}; - SbcAllocMethod alloc_methods[2] = {SbcAllocMethod::ALLOC_MD_S, - SbcAllocMethod::ALLOC_MD_L}; + SbcBlockLength block_lengths[4] = {SbcBlockLength::BLOCKS_4, SbcBlockLength::BLOCKS_8, + SbcBlockLength::BLOCKS_12, SbcBlockLength::BLOCKS_16}; + SbcNumSubbands num_subbands[2] = {SbcNumSubbands::SUBBAND_4, SbcNumSubbands::SUBBAND_8}; + SbcAllocMethod alloc_methods[2] = {SbcAllocMethod::ALLOC_MD_S, SbcAllocMethod::ALLOC_MD_L}; for (auto sample_rate_pair : kSampleRatePairs) { for (auto bits_per_sample_pair : kBitsPerSamplePairs) { for (auto channel_mode_pair : kChannelModePairs) { @@ -448,34 +419,31 @@ std::vector SbcCodecConfigurationsGenerator() { // A2DP_SBC_DEFAULT_BITRATE codec_config.encodedAudioBitrate = 328000; SbcParameters sbc = { - .sampleRate = sample_rate_pair.hal_sample_rate_, - .channelMode = (channel_mode_pair.hal_channel_mode_ == - ChannelMode::MONO - ? SbcChannelMode::MONO - : SbcChannelMode::JOINT_STEREO), - .blockLength = block_length, - .numSubbands = num_subband, - .allocMethod = alloc_method, - .bitsPerSample = bits_per_sample_pair.hal_bits_per_sample_, - .minBitpool = 2, - .maxBitpool = 53}; + .sampleRate = sample_rate_pair.hal_sample_rate_, + .channelMode = (channel_mode_pair.hal_channel_mode_ == ChannelMode::MONO + ? SbcChannelMode::MONO + : SbcChannelMode::JOINT_STEREO), + .blockLength = block_length, + .numSubbands = num_subband, + .allocMethod = alloc_method, + .bitsPerSample = bits_per_sample_pair.hal_bits_per_sample_, + .minBitpool = 2, + .maxBitpool = 53}; codec_config.config.sbcConfig(sbc); sbc_codec_configs.push_back(codec_config); } // SbcAllocMethod - } // SbcNumSubbands - } // SbcBlockLength - } // peerMtu - } // ChannelMode - } // BitsPerSampple - } // SampleRate + } // SbcNumSubbands + } // SbcBlockLength + } // peerMtu + } // ChannelMode + } // BitsPerSampple + } // SampleRate return sbc_codec_configs; } TEST_F(BluetoothAudioClientInterfaceTest, A2dpSbcCodecOffloadingState) { - test_sink_transport_ = - new TestSinkTransport(SessionType::A2DP_HARDWARE_OFFLOAD_DATAPATH); - clientif_sink_ = - new BluetoothAudioSinkClientInterface(test_sink_transport_, nullptr); + test_sink_transport_ = new TestSinkTransport(SessionType::A2DP_HARDWARE_OFFLOAD_DATAPATH); + clientif_sink_ = new BluetoothAudioSinkClientInterface(test_sink_transport_, nullptr); auto sbc_codec_configs = SbcCodecConfigurationsGenerator(); for (auto codec_offloading_preference : CodecOffloadingPreferenceGenerator(BTAV_A2DP_CODEC_INDEX_SOURCE_SBC)) { @@ -492,10 +460,8 @@ TEST_F(BluetoothAudioClientInterfaceTest, A2dpSbcCodecOffloadingState) { } TEST_F(BluetoothAudioClientInterfaceTest, StartAndEndA2dpOffloadSbcSession) { - test_sink_transport_ = - new TestSinkTransport(SessionType::A2DP_HARDWARE_OFFLOAD_DATAPATH); - clientif_sink_ = - new BluetoothAudioSinkClientInterface(test_sink_transport_, nullptr); + test_sink_transport_ = new TestSinkTransport(SessionType::A2DP_HARDWARE_OFFLOAD_DATAPATH); + clientif_sink_ = new BluetoothAudioSinkClientInterface(test_sink_transport_, nullptr); AudioConfiguration audio_config = {}; for (CodecConfiguration codec_config : SbcCodecConfigurationsGenerator()) { audio_config.codecConfig(codec_config); @@ -512,9 +478,8 @@ TEST_F(BluetoothAudioClientInterfaceTest, StartAndEndA2dpOffloadSbcSession) { std::vector AacCodecConfigurationsGenerator() { std::vector aac_codec_configs; CodecConfiguration codec_config = {}; - AacObjectType object_types[4] = { - AacObjectType::MPEG2_LC, AacObjectType::MPEG4_LC, - AacObjectType::MPEG4_LTP, AacObjectType::MPEG4_SCALABLE}; + AacObjectType object_types[4] = {AacObjectType::MPEG2_LC, AacObjectType::MPEG4_LC, + AacObjectType::MPEG4_LTP, AacObjectType::MPEG4_SCALABLE}; AacVariableBitRate variable_bitrates[2] = {AacVariableBitRate::DISABLED, AacVariableBitRate::ENABLED}; for (auto sample_rate_pair : kSampleRatePairs) { @@ -528,28 +493,25 @@ std::vector AacCodecConfigurationsGenerator() { codec_config.isScmstEnabled = false; // A2DP_AAC_DEFAULT_BITRATE codec_config.encodedAudioBitrate = 320000; - AacParameters aac = { - .objectType = object_type, - .sampleRate = sample_rate_pair.hal_sample_rate_, - .channelMode = channel_mode_pair.hal_channel_mode_, - .variableBitRateEnabled = variable_bitrate, - .bitsPerSample = bits_per_sample_pair.hal_bits_per_sample_}; + AacParameters aac = {.objectType = object_type, + .sampleRate = sample_rate_pair.hal_sample_rate_, + .channelMode = channel_mode_pair.hal_channel_mode_, + .variableBitRateEnabled = variable_bitrate, + .bitsPerSample = bits_per_sample_pair.hal_bits_per_sample_}; codec_config.config.aacConfig(aac); aac_codec_configs.push_back(codec_config); } // AacVariableBitRate - } // AacObjectType - } // peerMtu - } // ChannelMode - } // BitsPerSampple - } // SampleRate + } // AacObjectType + } // peerMtu + } // ChannelMode + } // BitsPerSampple + } // SampleRate return aac_codec_configs; } TEST_F(BluetoothAudioClientInterfaceTest, A2dpAacCodecOffloadingState) { - test_sink_transport_ = - new TestSinkTransport(SessionType::A2DP_HARDWARE_OFFLOAD_DATAPATH); - clientif_sink_ = - new BluetoothAudioSinkClientInterface(test_sink_transport_, nullptr); + test_sink_transport_ = new TestSinkTransport(SessionType::A2DP_HARDWARE_OFFLOAD_DATAPATH); + clientif_sink_ = new BluetoothAudioSinkClientInterface(test_sink_transport_, nullptr); auto aac_codec_configs = AacCodecConfigurationsGenerator(); for (auto codec_offloading_preference : CodecOffloadingPreferenceGenerator(BTAV_A2DP_CODEC_INDEX_SOURCE_AAC)) { @@ -566,10 +528,8 @@ TEST_F(BluetoothAudioClientInterfaceTest, A2dpAacCodecOffloadingState) { } TEST_F(BluetoothAudioClientInterfaceTest, StartAndEndA2dpOffloadAacSession) { - test_sink_transport_ = - new TestSinkTransport(SessionType::A2DP_HARDWARE_OFFLOAD_DATAPATH); - clientif_sink_ = - new BluetoothAudioSinkClientInterface(test_sink_transport_, nullptr); + test_sink_transport_ = new TestSinkTransport(SessionType::A2DP_HARDWARE_OFFLOAD_DATAPATH); + clientif_sink_ = new BluetoothAudioSinkClientInterface(test_sink_transport_, nullptr); AudioConfiguration audio_config = {}; for (CodecConfiguration codec_config : AacCodecConfigurationsGenerator()) { audio_config.codecConfig(codec_config); @@ -587,8 +547,8 @@ std::vector LdacCodecConfigurationsGenerator() { std::vector ldac_codec_configs; CodecConfiguration codec_config = {}; LdacQualityIndex quality_indexes[4] = { - LdacQualityIndex::QUALITY_HIGH, LdacQualityIndex::QUALITY_MID, - LdacQualityIndex::QUALITY_LOW, LdacQualityIndex::QUALITY_ABR}; + LdacQualityIndex::QUALITY_HIGH, LdacQualityIndex::QUALITY_MID, + LdacQualityIndex::QUALITY_LOW, LdacQualityIndex::QUALITY_ABR}; for (auto sample_rate_pair : kSampleRatePairs) { for (auto bits_per_sample_pair : kBitsPerSamplePairs) { for (auto channel_mode_pair : kChannelModePairs) { @@ -599,28 +559,25 @@ std::vector LdacCodecConfigurationsGenerator() { codec_config.isScmstEnabled = false; codec_config.encodedAudioBitrate = 990000; LdacParameters ldac = { - .sampleRate = sample_rate_pair.hal_sample_rate_, - .channelMode = - (channel_mode_pair.hal_channel_mode_ == ChannelMode::MONO - ? LdacChannelMode::MONO - : LdacChannelMode::STEREO), - .qualityIndex = quality_index, - .bitsPerSample = bits_per_sample_pair.hal_bits_per_sample_}; + .sampleRate = sample_rate_pair.hal_sample_rate_, + .channelMode = (channel_mode_pair.hal_channel_mode_ == ChannelMode::MONO + ? LdacChannelMode::MONO + : LdacChannelMode::STEREO), + .qualityIndex = quality_index, + .bitsPerSample = bits_per_sample_pair.hal_bits_per_sample_}; codec_config.config.ldacConfig(ldac); ldac_codec_configs.push_back(codec_config); } // LdacQualityIndex - } // peerMtu - } // ChannelMode - } // BitsPerSampple - } // SampleRate + } // peerMtu + } // ChannelMode + } // BitsPerSampple + } // SampleRate return ldac_codec_configs; } TEST_F(BluetoothAudioClientInterfaceTest, A2dpLdacCodecOffloadingState) { - test_sink_transport_ = - new TestSinkTransport(SessionType::A2DP_HARDWARE_OFFLOAD_DATAPATH); - clientif_sink_ = - new BluetoothAudioSinkClientInterface(test_sink_transport_, nullptr); + test_sink_transport_ = new TestSinkTransport(SessionType::A2DP_HARDWARE_OFFLOAD_DATAPATH); + clientif_sink_ = new BluetoothAudioSinkClientInterface(test_sink_transport_, nullptr); auto ldac_codec_configs = LdacCodecConfigurationsGenerator(); for (auto codec_offloading_preference : CodecOffloadingPreferenceGenerator(BTAV_A2DP_CODEC_INDEX_SOURCE_LDAC)) { @@ -637,10 +594,8 @@ TEST_F(BluetoothAudioClientInterfaceTest, A2dpLdacCodecOffloadingState) { } TEST_F(BluetoothAudioClientInterfaceTest, StartAndEndA2dpOffloadLdacSession) { - test_sink_transport_ = - new TestSinkTransport(SessionType::A2DP_HARDWARE_OFFLOAD_DATAPATH); - clientif_sink_ = - new BluetoothAudioSinkClientInterface(test_sink_transport_, nullptr); + test_sink_transport_ = new TestSinkTransport(SessionType::A2DP_HARDWARE_OFFLOAD_DATAPATH); + clientif_sink_ = new BluetoothAudioSinkClientInterface(test_sink_transport_, nullptr); AudioConfiguration audio_config = {}; for (CodecConfiguration codec_config : LdacCodecConfigurationsGenerator()) { audio_config.codecConfig(codec_config); @@ -654,11 +609,11 @@ TEST_F(BluetoothAudioClientInterfaceTest, StartAndEndA2dpOffloadLdacSession) { } } -std::vector AptxCodecConfigurationsGenerator( - CodecType codec_type) { +std::vector AptxCodecConfigurationsGenerator(CodecType codec_type) { std::vector aptx_codec_configs; - if (codec_type != CodecType::APTX && codec_type != CodecType::APTX_HD) + if (codec_type != CodecType::APTX && codec_type != CodecType::APTX_HD) { return aptx_codec_configs; + } CodecConfiguration codec_config = {}; for (auto sample_rate_pair : kSampleRatePairs) { for (auto bits_per_sample_pair : kBitsPerSamplePairs) { @@ -667,26 +622,22 @@ std::vector AptxCodecConfigurationsGenerator( codec_config.codecType = codec_type; codec_config.peerMtu = peer_mtu; codec_config.isScmstEnabled = false; - codec_config.encodedAudioBitrate = - (codec_type == CodecType::APTX ? 352000 : 576000); - AptxParameters aptx = { - .sampleRate = sample_rate_pair.hal_sample_rate_, - .channelMode = channel_mode_pair.hal_channel_mode_, - .bitsPerSample = bits_per_sample_pair.hal_bits_per_sample_}; + codec_config.encodedAudioBitrate = (codec_type == CodecType::APTX ? 352000 : 576000); + AptxParameters aptx = {.sampleRate = sample_rate_pair.hal_sample_rate_, + .channelMode = channel_mode_pair.hal_channel_mode_, + .bitsPerSample = bits_per_sample_pair.hal_bits_per_sample_}; codec_config.config.aptxConfig(aptx); aptx_codec_configs.push_back(codec_config); } // peerMtu - } // ChannelMode - } // BitsPerSampple - } // SampleRate + } // ChannelMode + } // BitsPerSampple + } // SampleRate return aptx_codec_configs; } TEST_F(BluetoothAudioClientInterfaceTest, A2dpAptxCodecOffloadingState) { - test_sink_transport_ = - new TestSinkTransport(SessionType::A2DP_HARDWARE_OFFLOAD_DATAPATH); - clientif_sink_ = - new BluetoothAudioSinkClientInterface(test_sink_transport_, nullptr); + test_sink_transport_ = new TestSinkTransport(SessionType::A2DP_HARDWARE_OFFLOAD_DATAPATH); + clientif_sink_ = new BluetoothAudioSinkClientInterface(test_sink_transport_, nullptr); auto aptx_codec_configs = AptxCodecConfigurationsGenerator(CodecType::APTX); for (auto codec_offloading_preference : CodecOffloadingPreferenceGenerator(BTAV_A2DP_CODEC_INDEX_SOURCE_APTX)) { @@ -703,13 +654,10 @@ TEST_F(BluetoothAudioClientInterfaceTest, A2dpAptxCodecOffloadingState) { } TEST_F(BluetoothAudioClientInterfaceTest, StartAndEndA2dpOffloadAptxSession) { - test_sink_transport_ = - new TestSinkTransport(SessionType::A2DP_HARDWARE_OFFLOAD_DATAPATH); - clientif_sink_ = - new BluetoothAudioSinkClientInterface(test_sink_transport_, nullptr); + test_sink_transport_ = new TestSinkTransport(SessionType::A2DP_HARDWARE_OFFLOAD_DATAPATH); + clientif_sink_ = new BluetoothAudioSinkClientInterface(test_sink_transport_, nullptr); AudioConfiguration audio_config = {}; - for (CodecConfiguration codec_config : - AptxCodecConfigurationsGenerator(CodecType::APTX)) { + for (CodecConfiguration codec_config : AptxCodecConfigurationsGenerator(CodecType::APTX)) { audio_config.codecConfig(codec_config); clientif_sink_->UpdateAudioConfig(audio_config); if (IsCodecOffloadingSupported(codec_config)) { @@ -722,14 +670,11 @@ TEST_F(BluetoothAudioClientInterfaceTest, StartAndEndA2dpOffloadAptxSession) { } TEST_F(BluetoothAudioClientInterfaceTest, A2dpAptxHdCodecOffloadingState) { - test_sink_transport_ = - new TestSinkTransport(SessionType::A2DP_HARDWARE_OFFLOAD_DATAPATH); - clientif_sink_ = - new BluetoothAudioSinkClientInterface(test_sink_transport_, nullptr); - auto aptx_hd_codec_configs = - AptxCodecConfigurationsGenerator(CodecType::APTX_HD); - for (auto codec_offloading_preference : CodecOffloadingPreferenceGenerator( - BTAV_A2DP_CODEC_INDEX_SOURCE_APTX_HD)) { + test_sink_transport_ = new TestSinkTransport(SessionType::A2DP_HARDWARE_OFFLOAD_DATAPATH); + clientif_sink_ = new BluetoothAudioSinkClientInterface(test_sink_transport_, nullptr); + auto aptx_hd_codec_configs = AptxCodecConfigurationsGenerator(CodecType::APTX_HD); + for (auto codec_offloading_preference : + CodecOffloadingPreferenceGenerator(BTAV_A2DP_CODEC_INDEX_SOURCE_APTX_HD)) { UpdateOffloadingCapabilities(codec_offloading_preference.preference_); for (CodecConfiguration codec_config : aptx_hd_codec_configs) { if (IsCodecOffloadingSupported(codec_config) && @@ -743,13 +688,10 @@ TEST_F(BluetoothAudioClientInterfaceTest, A2dpAptxHdCodecOffloadingState) { } TEST_F(BluetoothAudioClientInterfaceTest, StartAndEndA2dpOffloadAptxHdSession) { - test_sink_transport_ = - new TestSinkTransport(SessionType::A2DP_HARDWARE_OFFLOAD_DATAPATH); - clientif_sink_ = - new BluetoothAudioSinkClientInterface(test_sink_transport_, nullptr); + test_sink_transport_ = new TestSinkTransport(SessionType::A2DP_HARDWARE_OFFLOAD_DATAPATH); + clientif_sink_ = new BluetoothAudioSinkClientInterface(test_sink_transport_, nullptr); AudioConfiguration audio_config = {}; - for (CodecConfiguration codec_config : - AptxCodecConfigurationsGenerator(CodecType::APTX_HD)) { + for (CodecConfiguration codec_config : AptxCodecConfigurationsGenerator(CodecType::APTX_HD)) { audio_config.codecConfig(codec_config); clientif_sink_->UpdateAudioConfig(audio_config); if (IsCodecOffloadingSupported(codec_config)) { @@ -761,12 +703,9 @@ TEST_F(BluetoothAudioClientInterfaceTest, StartAndEndA2dpOffloadAptxHdSession) { } } -TEST_F(BluetoothAudioClientInterfaceTest, - StartAndEndA2dpOffloadUnknownSession) { - test_sink_transport_ = - new TestSinkTransport(SessionType::A2DP_HARDWARE_OFFLOAD_DATAPATH); - clientif_sink_ = - new BluetoothAudioSinkClientInterface(test_sink_transport_, nullptr); +TEST_F(BluetoothAudioClientInterfaceTest, StartAndEndA2dpOffloadUnknownSession) { + test_sink_transport_ = new TestSinkTransport(SessionType::A2DP_HARDWARE_OFFLOAD_DATAPATH); + clientif_sink_ = new BluetoothAudioSinkClientInterface(test_sink_transport_, nullptr); AudioConfiguration audio_config = {}; CodecConfiguration codec_config = {}; codec_config.codecType = CodecType::UNKNOWN; @@ -784,12 +723,9 @@ TEST_F(BluetoothAudioClientInterfaceTest, ASSERT_EQ(clientif_sink_->EndSession(), kClientIfReturnSuccess); } -TEST_F(BluetoothAudioClientInterfaceTest, - StartAndEndHearingAidSoftwareSession) { - test_sink_transport_ = new TestSinkTransport( - SessionType::HEARING_AID_SOFTWARE_ENCODING_DATAPATH); - clientif_sink_ = - new BluetoothAudioSinkClientInterface(test_sink_transport_, nullptr); +TEST_F(BluetoothAudioClientInterfaceTest, StartAndEndHearingAidSoftwareSession) { + test_sink_transport_ = new TestSinkTransport(SessionType::HEARING_AID_SOFTWARE_ENCODING_DATAPATH); + clientif_sink_ = new BluetoothAudioSinkClientInterface(test_sink_transport_, nullptr); AudioConfiguration audio_config = {}; PcmParameters pcm_config = {}; for (auto sample_rate_pair : kSampleRatePairs) { @@ -807,16 +743,14 @@ TEST_F(BluetoothAudioClientInterfaceTest, } ASSERT_EQ(clientif_sink_->EndSession(), kClientIfReturnSuccess); } // ChannelMode - } // BitsPerSampple - } // SampleRate + } // BitsPerSampple + } // SampleRate } -TEST_F(BluetoothAudioClientInterfaceTest, - StartAndEndLeAudioEncodingSoftwareSession) { - test_sink_transport_ = new TestSinkTransport( - SessionType_2_1::LE_AUDIO_SOFTWARE_ENCODING_DATAPATH); - clientif_sink_ = - new BluetoothAudioSinkClientInterface(test_sink_transport_, nullptr); +TEST_F(BluetoothAudioClientInterfaceTest, StartAndEndLeAudioEncodingSoftwareSession) { + test_sink_transport_ = + new TestSinkTransport(SessionType_2_1::LE_AUDIO_SOFTWARE_ENCODING_DATAPATH); + clientif_sink_ = new BluetoothAudioSinkClientInterface(test_sink_transport_, nullptr); AudioConfiguration_2_1 audio_config = {}; PcmParameters_2_1 pcm_config = {}; for (auto sample_rate : kSampleRates_2_1) { @@ -830,25 +764,21 @@ TEST_F(BluetoothAudioClientInterfaceTest, audio_config.pcmConfig(pcm_config); clientif_sink_->UpdateAudioConfig_2_1(audio_config); if (IsSinkSoftwarePcmParameters_2_1_Supported(pcm_config)) { - ASSERT_EQ(clientif_sink_->StartSession_2_1(), - kClientIfReturnSuccess); + ASSERT_EQ(clientif_sink_->StartSession_2_1(), kClientIfReturnSuccess); } else { - ASSERT_NE(clientif_sink_->StartSession_2_1(), - kClientIfReturnSuccess); + ASSERT_NE(clientif_sink_->StartSession_2_1(), kClientIfReturnSuccess); } ASSERT_EQ(clientif_sink_->EndSession(), kClientIfReturnSuccess); } // dataIntervalUs - } // ChannelMode - } // BitsPerSampple - } // SampleRate + } // ChannelMode + } // BitsPerSampple + } // SampleRate } -TEST_F(BluetoothAudioClientInterfaceTest, - StartAndEndLeAudioDecodedSoftwareSession) { - test_source_transport_ = new TestSourceTransport( - SessionType_2_1::LE_AUDIO_SOFTWARE_DECODED_DATAPATH); - clientif_source_ = - new BluetoothAudioSourceClientInterface(test_source_transport_, nullptr); +TEST_F(BluetoothAudioClientInterfaceTest, StartAndEndLeAudioDecodedSoftwareSession) { + test_source_transport_ = + new TestSourceTransport(SessionType_2_1::LE_AUDIO_SOFTWARE_DECODED_DATAPATH); + clientif_source_ = new BluetoothAudioSourceClientInterface(test_source_transport_, nullptr); AudioConfiguration_2_1 audio_config = {}; PcmParameters_2_1 pcm_config = {}; for (auto sample_rate : kSampleRates_2_1) { @@ -862,15 +792,13 @@ TEST_F(BluetoothAudioClientInterfaceTest, audio_config.pcmConfig(pcm_config); clientif_source_->UpdateAudioConfig_2_1(audio_config); if (IsSourceSoftwarePcmParameters_2_1_Supported(pcm_config)) { - ASSERT_EQ(clientif_source_->StartSession_2_1(), - kClientIfReturnSuccess); + ASSERT_EQ(clientif_source_->StartSession_2_1(), kClientIfReturnSuccess); } else { - ASSERT_NE(clientif_source_->StartSession_2_1(), - kClientIfReturnSuccess); + ASSERT_NE(clientif_source_->StartSession_2_1(), kClientIfReturnSuccess); } ASSERT_EQ(clientif_source_->EndSession(), kClientIfReturnSuccess); } // dataIntervalUs - } // ChannelMode - } // BitsPerSampple - } // SampleRate + } // ChannelMode + } // BitsPerSampple + } // SampleRate } diff --git a/system/audio_hal_interface/hidl/codec_status_hidl.cc b/system/audio_hal_interface/hidl/codec_status_hidl.cc index ebc81dd5ad4..fe54dbdb1eb 100644 --- a/system/audio_hal_interface/hidl/codec_status_hidl.cc +++ b/system/audio_hal_interface/hidl/codec_status_hidl.cc @@ -60,74 +60,56 @@ std::vector offloading_preference(0); bool sbc_offloading_capability_match(const SbcParameters& sbc_capability, const SbcParameters& sbc_config) { - if ((static_cast(sbc_capability.sampleRate & - sbc_config.sampleRate) == + if ((static_cast(sbc_capability.sampleRate & sbc_config.sampleRate) == SampleRate::RATE_UNKNOWN) || - (static_cast(sbc_capability.channelMode & - sbc_config.channelMode) == + (static_cast(sbc_capability.channelMode & sbc_config.channelMode) == SbcChannelMode::UNKNOWN) || - (static_cast(sbc_capability.blockLength & - sbc_config.blockLength) == + (static_cast(sbc_capability.blockLength & sbc_config.blockLength) == static_cast(0)) || - (static_cast(sbc_capability.numSubbands & - sbc_config.numSubbands) == + (static_cast(sbc_capability.numSubbands & sbc_config.numSubbands) == static_cast(0)) || - (static_cast(sbc_capability.allocMethod & - sbc_config.allocMethod) == + (static_cast(sbc_capability.allocMethod & sbc_config.allocMethod) == static_cast(0)) || - (static_cast(sbc_capability.bitsPerSample & - sbc_config.bitsPerSample) == + (static_cast(sbc_capability.bitsPerSample & sbc_config.bitsPerSample) == BitsPerSample::BITS_UNKNOWN) || (sbc_config.minBitpool < sbc_capability.minBitpool || sbc_config.maxBitpool < sbc_config.minBitpool || sbc_capability.maxBitpool < sbc_config.maxBitpool)) { - log::warn("software codec={} capability={}", toString(sbc_config), - toString(sbc_capability)); + log::warn("software codec={} capability={}", toString(sbc_config), toString(sbc_capability)); return false; } - log::verbose("offloading codec={} capability={}", toString(sbc_config), - toString(sbc_capability)); + log::verbose("offloading codec={} capability={}", toString(sbc_config), toString(sbc_capability)); return true; } bool aac_offloading_capability_match(const AacParameters& aac_capability, const AacParameters& aac_config) { - if ((static_cast(aac_capability.objectType & - aac_config.objectType) == + if ((static_cast(aac_capability.objectType & aac_config.objectType) == static_cast(0)) || - (static_cast(aac_capability.sampleRate & - aac_config.sampleRate) == + (static_cast(aac_capability.sampleRate & aac_config.sampleRate) == SampleRate::RATE_UNKNOWN) || - (static_cast(aac_capability.channelMode & - aac_config.channelMode) == + (static_cast(aac_capability.channelMode & aac_config.channelMode) == ChannelMode::UNKNOWN) || (aac_capability.variableBitRateEnabled != AacVariableBitRate::ENABLED && aac_config.variableBitRateEnabled != AacVariableBitRate::DISABLED) || - (static_cast(aac_capability.bitsPerSample & - aac_config.bitsPerSample) == + (static_cast(aac_capability.bitsPerSample & aac_config.bitsPerSample) == BitsPerSample::BITS_UNKNOWN)) { - log::warn("software codec={} capability={}", toString(aac_config), - toString(aac_capability)); + log::warn("software codec={} capability={}", toString(aac_config), toString(aac_capability)); return false; } - log::verbose("offloading codec={} capability={}", toString(aac_config), - toString(aac_capability)); + log::verbose("offloading codec={} capability={}", toString(aac_config), toString(aac_capability)); return true; } bool aptx_offloading_capability_match(const AptxParameters& aptx_capability, const AptxParameters& aptx_config) { - if ((static_cast(aptx_capability.sampleRate & - aptx_config.sampleRate) == + if ((static_cast(aptx_capability.sampleRate & aptx_config.sampleRate) == SampleRate::RATE_UNKNOWN) || - (static_cast(aptx_capability.channelMode & - aptx_config.channelMode) == + (static_cast(aptx_capability.channelMode & aptx_config.channelMode) == ChannelMode::UNKNOWN) || - (static_cast(aptx_capability.bitsPerSample & - aptx_config.bitsPerSample) == + (static_cast(aptx_capability.bitsPerSample & aptx_config.bitsPerSample) == BitsPerSample::BITS_UNKNOWN)) { - log::warn("software codec={} capability={}", toString(aptx_config), - toString(aptx_capability)); + log::warn("software codec={} capability={}", toString(aptx_config), toString(aptx_capability)); return false; } log::verbose("offloading codec={} capability={}", toString(aptx_config), @@ -137,17 +119,13 @@ bool aptx_offloading_capability_match(const AptxParameters& aptx_capability, bool ldac_offloading_capability_match(const LdacParameters& ldac_capability, const LdacParameters& ldac_config) { - if ((static_cast(ldac_capability.sampleRate & - ldac_config.sampleRate) == + if ((static_cast(ldac_capability.sampleRate & ldac_config.sampleRate) == SampleRate::RATE_UNKNOWN) || - (static_cast(ldac_capability.channelMode & - ldac_config.channelMode) == + (static_cast(ldac_capability.channelMode & ldac_config.channelMode) == LdacChannelMode::UNKNOWN) || - (static_cast(ldac_capability.bitsPerSample & - ldac_config.bitsPerSample) == + (static_cast(ldac_capability.bitsPerSample & ldac_config.bitsPerSample) == BitsPerSample::BITS_UNKNOWN)) { - log::warn("software codec={} capability={}", toString(ldac_config), - toString(ldac_capability)); + log::warn("software codec={} capability={}", toString(ldac_config), toString(ldac_capability)); return false; } log::verbose("offloading codec={} capability={}", toString(ldac_config), @@ -161,15 +139,13 @@ namespace audio { namespace hidl { namespace codec { -const CodecConfiguration kInvalidCodecConfiguration = { - .codecType = CodecType::UNKNOWN, - .encodedAudioBitrate = 0x00000000, - .peerMtu = 0xffff, - .isScmstEnabled = false, - .config = {}}; +const CodecConfiguration kInvalidCodecConfiguration = {.codecType = CodecType::UNKNOWN, + .encodedAudioBitrate = 0x00000000, + .peerMtu = 0xffff, + .isScmstEnabled = false, + .config = {}}; -SampleRate A2dpCodecToHalSampleRate( - const btav_a2dp_codec_config_t& a2dp_codec_config) { +SampleRate A2dpCodecToHalSampleRate(const btav_a2dp_codec_config_t& a2dp_codec_config) { switch (a2dp_codec_config.sample_rate) { case BTAV_A2DP_CODEC_SAMPLE_RATE_44100: return SampleRate::RATE_44100; @@ -192,8 +168,7 @@ SampleRate A2dpCodecToHalSampleRate( } } -BitsPerSample A2dpCodecToHalBitsPerSample( - const btav_a2dp_codec_config_t& a2dp_codec_config) { +BitsPerSample A2dpCodecToHalBitsPerSample(const btav_a2dp_codec_config_t& a2dp_codec_config) { switch (a2dp_codec_config.bits_per_sample) { case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16: return BitsPerSample::BITS_16; @@ -206,8 +181,7 @@ BitsPerSample A2dpCodecToHalBitsPerSample( } } -ChannelMode A2dpCodecToHalChannelMode( - const btav_a2dp_codec_config_t& a2dp_codec_config) { +ChannelMode A2dpCodecToHalChannelMode(const btav_a2dp_codec_config_t& a2dp_codec_config) { switch (a2dp_codec_config.channel_mode) { case BTAV_A2DP_CODEC_CHANNEL_MODE_MONO: return ChannelMode::MONO; @@ -218,8 +192,7 @@ ChannelMode A2dpCodecToHalChannelMode( } } -bool A2dpSbcToHalConfig(CodecConfiguration* codec_config, - A2dpCodecConfig* a2dp_config) { +bool A2dpSbcToHalConfig(CodecConfiguration* codec_config, A2dpCodecConfig* a2dp_config) { btav_a2dp_codec_config_t current_codec = a2dp_config->getCodecConfig(); if (current_codec.codec_type != BTAV_A2DP_CODEC_INDEX_SOURCE_SBC && current_codec.codec_type != BTAV_A2DP_CODEC_INDEX_SINK_SBC) { @@ -308,8 +281,7 @@ bool A2dpSbcToHalConfig(CodecConfiguration* codec_config, return true; } -bool A2dpAacToHalConfig(CodecConfiguration* codec_config, - A2dpCodecConfig* a2dp_config) { +bool A2dpAacToHalConfig(CodecConfiguration* codec_config, A2dpCodecConfig* a2dp_config) { btav_a2dp_codec_config_t current_codec = a2dp_config->getCodecConfig(); if (current_codec.codec_type != BTAV_A2DP_CODEC_INDEX_SOURCE_AAC && current_codec.codec_type != BTAV_A2DP_CODEC_INDEX_SINK_AAC) { @@ -349,8 +321,7 @@ bool A2dpAacToHalConfig(CodecConfiguration* codec_config, log::error("Unknown AAC channel_mode={}", current_codec.channel_mode); return false; } - uint8_t vbr_enabled = - a2dp_offload.codec_info[1] & A2DP_AAC_VARIABLE_BIT_RATE_MASK; + uint8_t vbr_enabled = a2dp_offload.codec_info[1] & A2DP_AAC_VARIABLE_BIT_RATE_MASK; switch (vbr_enabled) { case A2DP_AAC_VARIABLE_BIT_RATE_ENABLED: aac_config.variableBitRateEnabled = AacVariableBitRate::ENABLED; @@ -371,8 +342,7 @@ bool A2dpAacToHalConfig(CodecConfiguration* codec_config, return true; } -bool A2dpAptxToHalConfig(CodecConfiguration* codec_config, - A2dpCodecConfig* a2dp_config) { +bool A2dpAptxToHalConfig(CodecConfiguration* codec_config, A2dpCodecConfig* a2dp_config) { btav_a2dp_codec_config_t current_codec = a2dp_config->getCodecConfig(); if (current_codec.codec_type != BTAV_A2DP_CODEC_INDEX_SOURCE_APTX && current_codec.codec_type != BTAV_A2DP_CODEC_INDEX_SOURCE_APTX_HD) { @@ -400,16 +370,14 @@ bool A2dpAptxToHalConfig(CodecConfiguration* codec_config, } aptx_config.bitsPerSample = A2dpCodecToHalBitsPerSample(current_codec); if (aptx_config.bitsPerSample == BitsPerSample::BITS_UNKNOWN) { - log::error("Unknown aptX bits_per_sample={}", - current_codec.bits_per_sample); + log::error("Unknown aptX bits_per_sample={}", current_codec.bits_per_sample); return false; } codec_config->config.aptxConfig(aptx_config); return true; } -bool A2dpLdacToHalConfig(CodecConfiguration* codec_config, - A2dpCodecConfig* a2dp_config) { +bool A2dpLdacToHalConfig(CodecConfiguration* codec_config, A2dpCodecConfig* a2dp_config) { btav_a2dp_codec_config_t current_codec = a2dp_config->getCodecConfig(); if (current_codec.codec_type != BTAV_A2DP_CODEC_INDEX_SOURCE_LDAC) { codec_config = {}; @@ -459,8 +427,7 @@ bool A2dpLdacToHalConfig(CodecConfiguration* codec_config, } ldac_config.bitsPerSample = A2dpCodecToHalBitsPerSample(current_codec); if (ldac_config.bitsPerSample == BitsPerSample::BITS_UNKNOWN) { - log::error("Unknown LDAC bits_per_sample={}", - current_codec.bits_per_sample); + log::error("Unknown LDAC bits_per_sample={}", current_codec.bits_per_sample); return false; } codec_config->config.ldacConfig(ldac_config); @@ -468,9 +435,8 @@ bool A2dpLdacToHalConfig(CodecConfiguration* codec_config, } bool UpdateOffloadingCapabilities( - const std::vector& framework_preference) { - audio_hal_capabilities = - BluetoothAudioSinkClientInterface::GetAudioCapabilities( + const std::vector& framework_preference) { + audio_hal_capabilities = BluetoothAudioSinkClientInterface::GetAudioCapabilities( SessionType::A2DP_HARDWARE_OFFLOAD_DATAPATH); uint32_t codec_type_masks = static_cast(CodecType::UNKNOWN); for (auto preference : framework_preference) { @@ -491,12 +457,10 @@ bool UpdateOffloadingCapabilities( codec_type_masks |= CodecType::LDAC; break; case BTAV_A2DP_CODEC_INDEX_SOURCE_LC3: - log::warn("Ignore source codec_type={}, not supported", - preference.codec_type); + log::warn("Ignore source codec_type={}, not supported", preference.codec_type); break; case BTAV_A2DP_CODEC_INDEX_SOURCE_OPUS: - log::warn("Ignore source codec_type={}, not supported on HIDL", - preference.codec_type); + log::warn("Ignore source codec_type={}, not supported on HIDL", preference.codec_type); break; case BTAV_A2DP_CODEC_INDEX_SINK_SBC: [[fallthrough]]; @@ -516,8 +480,8 @@ bool UpdateOffloadingCapabilities( } offloading_preference.clear(); for (auto capability : audio_hal_capabilities) { - if (static_cast(capability.codecCapabilities().codecType & - codec_type_masks) != CodecType::UNKNOWN) { + if (static_cast(capability.codecCapabilities().codecType & codec_type_masks) != + CodecType::UNKNOWN) { log::info("enabled offloading capability={}", toString(capability)); offloading_preference.push_back(capability); } else { @@ -529,11 +493,12 @@ bool UpdateOffloadingCapabilities( } // Check whether this codec is supported by the audio HAL and is allowed to use -// by prefernece of framework / Bluetooth SoC / runtime property. +// by preference of framework / Bluetooth SoC / runtime property. bool IsCodecOffloadingEnabled(const CodecConfiguration& codec_config) { for (auto preference : offloading_preference) { - if (codec_config.codecType != preference.codecCapabilities().codecType) + if (codec_config.codecType != preference.codecCapabilities().codecType) { continue; + } auto codec_capability = preference.codecCapabilities(); switch (codec_capability.codecType) { case CodecType::SBC: { @@ -561,8 +526,7 @@ bool IsCodecOffloadingEnabled(const CodecConfiguration& codec_config) { case CodecType::UNKNOWN: [[fallthrough]]; default: - log::error("Unknown codecType={}", - toString(codec_capability.codecType)); + log::error("Unknown codecType={}", toString(codec_capability.codecType)); return false; } } diff --git a/system/audio_hal_interface/hidl/codec_status_hidl.h b/system/audio_hal_interface/hidl/codec_status_hidl.h index 8ed431c80e6..fd597502073 100644 --- a/system/audio_hal_interface/hidl/codec_status_hidl.h +++ b/system/audio_hal_interface/hidl/codec_status_hidl.h @@ -34,26 +34,19 @@ using ::android::hardware::bluetooth::audio::V2_0::SampleRate; extern const CodecConfiguration kInvalidCodecConfiguration; -SampleRate A2dpCodecToHalSampleRate( - const btav_a2dp_codec_config_t& a2dp_codec_config); -BitsPerSample A2dpCodecToHalBitsPerSample( - const btav_a2dp_codec_config_t& a2dp_codec_config); -ChannelMode A2dpCodecToHalChannelMode( - const btav_a2dp_codec_config_t& a2dp_codec_config); - -bool A2dpSbcToHalConfig(CodecConfiguration* codec_config, - A2dpCodecConfig* a2dp_config); -bool A2dpAacToHalConfig(CodecConfiguration* codec_config, - A2dpCodecConfig* a2dp_config); -bool A2dpAptxToHalConfig(CodecConfiguration* codec_config, - A2dpCodecConfig* a2dp_config); -bool A2dpLdacToHalConfig(CodecConfiguration* codec_config, - A2dpCodecConfig* a2dp_config); +SampleRate A2dpCodecToHalSampleRate(const btav_a2dp_codec_config_t& a2dp_codec_config); +BitsPerSample A2dpCodecToHalBitsPerSample(const btav_a2dp_codec_config_t& a2dp_codec_config); +ChannelMode A2dpCodecToHalChannelMode(const btav_a2dp_codec_config_t& a2dp_codec_config); + +bool A2dpSbcToHalConfig(CodecConfiguration* codec_config, A2dpCodecConfig* a2dp_config); +bool A2dpAacToHalConfig(CodecConfiguration* codec_config, A2dpCodecConfig* a2dp_config); +bool A2dpAptxToHalConfig(CodecConfiguration* codec_config, A2dpCodecConfig* a2dp_config); +bool A2dpLdacToHalConfig(CodecConfiguration* codec_config, A2dpCodecConfig* a2dp_config); bool UpdateOffloadingCapabilities( - const std::vector& framework_preference); + const std::vector& framework_preference); // Check whether this codec is supported by the audio HAL and is allowed to use -// by prefernece of framework / Bluetooth SoC / runtime property. +// by preference of framework / Bluetooth SoC / runtime property. bool IsCodecOffloadingEnabled(const CodecConfiguration& codec_config); } // namespace codec diff --git a/system/audio_hal_interface/hidl/hearing_aid_software_encoding_hidl.cc b/system/audio_hal_interface/hidl/hearing_aid_software_encoding_hidl.cc index e0935748741..b90e9ff1e71 100644 --- a/system/audio_hal_interface/hidl/hearing_aid_software_encoding_hidl.cc +++ b/system/audio_hal_interface/hidl/hearing_aid_software_encoding_hidl.cc @@ -29,8 +29,7 @@ namespace fmt { template <> struct formatter : enum_formatter {}; template <> -struct formatter : enum_formatter { -}; +struct formatter : enum_formatter {}; } // namespace fmt namespace { @@ -49,17 +48,15 @@ using ::bluetooth::audio::hidl::hearing_aid::StreamCallbacks; using namespace bluetooth; // Transport implementation for Hearing Aids -class HearingAidTransport - : public bluetooth::audio::hidl::IBluetoothSinkTransportInstance { - public: +class HearingAidTransport : public bluetooth::audio::hidl::IBluetoothSinkTransportInstance { +public: HearingAidTransport(StreamCallbacks stream_cb) - : IBluetoothSinkTransportInstance( - SessionType::HEARING_AID_SOFTWARE_ENCODING_DATAPATH, - (AudioConfiguration){}), + : IBluetoothSinkTransportInstance(SessionType::HEARING_AID_SOFTWARE_ENCODING_DATAPATH, + (AudioConfiguration){}), stream_cb_(std::move(stream_cb)), remote_delay_report_ms_(0), total_bytes_read_(0), - data_position_({}){}; + data_position_({}) {} BluetoothAudioCtrlAck StartRequest() override { log::info(""); @@ -89,17 +86,19 @@ class HearingAidTransport } } - bool GetPresentationPosition(uint64_t* remote_delay_report_ns, - uint64_t* total_bytes_read, + bool GetPresentationPosition(uint64_t* remote_delay_report_ns, uint64_t* total_bytes_read, timespec* data_position) override { - log::verbose("data={} byte(s), timestamp={}.{}s, delay report={} msec.", - total_bytes_read_, data_position_.tv_sec, - data_position_.tv_nsec, remote_delay_report_ms_); + log::verbose("data={} byte(s), timestamp={}.{}s, delay report={} msec.", total_bytes_read_, + data_position_.tv_sec, data_position_.tv_nsec, remote_delay_report_ms_); if (remote_delay_report_ns != nullptr) { *remote_delay_report_ns = remote_delay_report_ms_ * 1000000u; } - if (total_bytes_read != nullptr) *total_bytes_read = total_bytes_read_; - if (data_position != nullptr) *data_position = data_position_; + if (total_bytes_read != nullptr) { + *total_bytes_read = total_bytes_read_; + } + if (data_position != nullptr) { + *data_position = data_position_; + } return true; } @@ -109,8 +108,8 @@ class HearingAidTransport auto tracks = source_metadata.tracks; log::info("{} track(s) received", track_count); while (track_count) { - log::verbose("usage={}, content_type={}, gain={}", tracks->usage, - tracks->content_type, tracks->gain); + log::verbose("usage={}, content_type={}, gain={}", tracks->usage, tracks->content_type, + tracks->gain); --track_count; ++tracks; } @@ -135,7 +134,7 @@ class HearingAidTransport remote_delay_report_ms_ = delay_report_ms; } - private: +private: StreamCallbacks stream_cb_; uint16_t remote_delay_report_ms_; uint64_t total_bytes_read_; @@ -143,7 +142,9 @@ class HearingAidTransport }; bool HearingAidGetSelectedHalPcmConfig(PcmParameters* hal_pcm_config) { - if (hal_pcm_config == nullptr) return false; + if (hal_pcm_config == nullptr) { + return false; + } // TODO: we only support one config for now! hal_pcm_config->sampleRate = SampleRate::RATE_16000; hal_pcm_config->bitsPerSample = BitsPerSample::BITS_16; @@ -154,8 +155,8 @@ bool HearingAidGetSelectedHalPcmConfig(PcmParameters* hal_pcm_config) { // Sink instance of Hearing Aids to provide call-in APIs for Bluetooth Audio Hal HearingAidTransport* hearing_aid_sink = nullptr; // Common interface to call-out into Bluetooth Audio Hal -bluetooth::audio::hidl::BluetoothAudioSinkClientInterface* - hearing_aid_hal_clientinterface = nullptr; +bluetooth::audio::hidl::BluetoothAudioSinkClientInterface* hearing_aid_hal_clientinterface = + nullptr; bool btaudio_hearing_aid_disabled = false; bool is_configured = false; @@ -165,8 +166,7 @@ uint16_t remote_delay_ms = 0; bool is_hal_2_0_force_disabled() { if (!is_configured) { - btaudio_hearing_aid_disabled = - osi_property_get_bool(BLUETOOTH_AUDIO_HAL_PROP_DISABLED, false); + btaudio_hearing_aid_disabled = osi_property_get_bool(BLUETOOTH_AUDIO_HAL_PROP_DISABLED, false); is_configured = true; } return btaudio_hearing_aid_disabled; @@ -181,8 +181,7 @@ namespace hearing_aid { bool is_hal_2_0_enabled() { return hearing_aid_hal_clientinterface != nullptr; } -bool init(StreamCallbacks stream_cb, - bluetooth::common::MessageLoopThread* message_loop) { +bool init(StreamCallbacks stream_cb, bluetooth::common::MessageLoopThread* message_loop) { log::info(""); if (is_hal_2_0_force_disabled()) { @@ -191,8 +190,7 @@ bool init(StreamCallbacks stream_cb, } hearing_aid_sink = new HearingAidTransport(std::move(stream_cb)); - hearing_aid_hal_clientinterface = - new bluetooth::audio::hidl::BluetoothAudioSinkClientInterface( + hearing_aid_hal_clientinterface = new bluetooth::audio::hidl::BluetoothAudioSinkClientInterface( hearing_aid_sink, message_loop); if (!hearing_aid_hal_clientinterface->IsValid()) { log::warn("BluetoothAudio HAL for Hearing Aid is invalid?!"); @@ -214,7 +212,9 @@ bool init(StreamCallbacks stream_cb, void cleanup() { log::info(""); - if (!is_hal_2_0_enabled()) return; + if (!is_hal_2_0_enabled()) { + return; + } end_session(); delete hearing_aid_hal_clientinterface; hearing_aid_hal_clientinterface = nullptr; @@ -225,7 +225,9 @@ void cleanup() { void start_session() { log::info(""); - if (!is_hal_2_0_enabled()) return; + if (!is_hal_2_0_enabled()) { + return; + } AudioConfiguration audio_config; PcmParameters pcm_config{}; if (!HearingAidGetSelectedHalPcmConfig(&pcm_config)) { @@ -242,12 +244,16 @@ void start_session() { void end_session() { log::info(""); - if (!is_hal_2_0_enabled()) return; + if (!is_hal_2_0_enabled()) { + return; + } hearing_aid_hal_clientinterface->EndSession(); } size_t read(uint8_t* p_buf, uint32_t len) { - if (!is_hal_2_0_enabled()) return 0; + if (!is_hal_2_0_enabled()) { + return 0; + } return hearing_aid_hal_clientinterface->ReadAudioData(p_buf, len); } diff --git a/system/audio_hal_interface/hidl/hearing_aid_software_encoding_hidl.h b/system/audio_hal_interface/hidl/hearing_aid_software_encoding_hidl.h index 2000bacafd0..f849715c930 100644 --- a/system/audio_hal_interface/hidl/hearing_aid_software_encoding_hidl.h +++ b/system/audio_hal_interface/hidl/hearing_aid_software_encoding_hidl.h @@ -32,8 +32,7 @@ using ::bluetooth::audio::hearing_aid::StreamCallbacks; bool is_hal_2_0_enabled(); // Initialize BluetoothAudio HAL: openProvider -bool init(StreamCallbacks stream_cb, - bluetooth::common::MessageLoopThread* message_loop); +bool init(StreamCallbacks stream_cb, bluetooth::common::MessageLoopThread* message_loop); // Clean up BluetoothAudio HAL void cleanup(); diff --git a/system/audio_hal_interface/hidl/le_audio_software_hidl.cc b/system/audio_hal_interface/hidl/le_audio_software_hidl.cc index ff212b3a0cc..a42c435dc18 100644 --- a/system/audio_hal_interface/hidl/le_audio_software_hidl.cc +++ b/system/audio_hal_interface/hidl/le_audio_software_hidl.cc @@ -69,8 +69,7 @@ static SampleRate_2_1 le_audio_sample_rate2audio_hal(uint32_t sample_rate_2_1) { return SampleRate_2_1::RATE_UNKNOWN; } -static BitsPerSample le_audio_bits_per_sample2audio_hal( - uint8_t bits_per_sample) { +static BitsPerSample le_audio_bits_per_sample2audio_hal(uint8_t bits_per_sample) { switch (bits_per_sample) { case 16: return BitsPerSample::BITS_16; @@ -92,16 +91,11 @@ static ChannelMode le_audio_channel_mode2audio_hal(uint8_t channels_count) { return ChannelMode::UNKNOWN; } -bool is_source_hal_enabled() { - return LeAudioSourceTransport::interface != nullptr; -} +bool is_source_hal_enabled() { return LeAudioSourceTransport::interface != nullptr; } -bool is_sink_hal_enabled() { - return LeAudioSinkTransport::interface != nullptr; -} +bool is_sink_hal_enabled() { return LeAudioSinkTransport::interface != nullptr; } -LeAudioTransport::LeAudioTransport(void (*flush)(void), - StreamCallbacks stream_cb, +LeAudioTransport::LeAudioTransport(void (*flush)(void), StreamCallbacks stream_cb, PcmParameters pcm_config) : flush_(std::move(flush)), stream_cb_(std::move(stream_cb)), @@ -109,7 +103,7 @@ LeAudioTransport::LeAudioTransport(void (*flush)(void), total_bytes_processed_(0), data_position_({}), pcm_config_(std::move(pcm_config)), - start_request_state_(StartRequestState::IDLE){}; + start_request_state_(StartRequestState::IDLE) {} BluetoothAudioCtrlAck LeAudioTransport::StartRequest() { SetStartRequestState(StartRequestState::PENDING_BEFORE_RESUME); @@ -185,21 +179,22 @@ void LeAudioTransport::StopRequest() { bool LeAudioTransport::GetPresentationPosition(uint64_t* remote_delay_report_ns, uint64_t* total_bytes_processed, timespec* data_position) { - log::verbose("data={} byte(s), timestamp={}.{}s, delay report={} msec.", - total_bytes_processed_, data_position_.tv_sec, - data_position_.tv_nsec, remote_delay_report_ms_); + log::verbose("data={} byte(s), timestamp={}.{}s, delay report={} msec.", total_bytes_processed_, + data_position_.tv_sec, data_position_.tv_nsec, remote_delay_report_ms_); if (remote_delay_report_ns != nullptr) { *remote_delay_report_ns = remote_delay_report_ms_ * 1000000u; } - if (total_bytes_processed != nullptr) + if (total_bytes_processed != nullptr) { *total_bytes_processed = total_bytes_processed_; - if (data_position != nullptr) *data_position = data_position_; + } + if (data_position != nullptr) { + *data_position = data_position_; + } return true; } -void LeAudioTransport::MetadataChanged( - const source_metadata_t& source_metadata) { +void LeAudioTransport::MetadataChanged(const source_metadata_t& source_metadata) { auto track_count = source_metadata.track_count; if (track_count == 0) { @@ -210,16 +205,16 @@ void LeAudioTransport::MetadataChanged( tracks_vec.reserve(track_count); for (size_t i = 0; i < track_count; i++) { tracks_vec.push_back({ - .base = - { - .usage = source_metadata.tracks[i].usage, - .content_type = source_metadata.tracks[i].content_type, - .gain = source_metadata.tracks[i].gain, - }, + .base = + { + .usage = source_metadata.tracks[i].usage, + .content_type = source_metadata.tracks[i].content_type, + .gain = source_metadata.tracks[i].gain, + }, }); } - const source_metadata_v7_t source_metadata_v7 = { - .track_count = tracks_vec.size(), .tracks = tracks_vec.data()}; + const source_metadata_v7_t source_metadata_v7 = {.track_count = tracks_vec.size(), + .tracks = tracks_vec.data()}; stream_cb_.on_metadata_update_(source_metadata_v7, DsaMode::DISABLED); } @@ -243,12 +238,9 @@ void LeAudioTransport::SetRemoteDelay(uint16_t delay_report_ms) { remote_delay_report_ms_ = delay_report_ms; } -const PcmParameters& LeAudioTransport::LeAudioGetSelectedHalPcmConfig() { - return pcm_config_; -} +const PcmParameters& LeAudioTransport::LeAudioGetSelectedHalPcmConfig() { return pcm_config_; } -void LeAudioTransport::LeAudioSetSelectedHalPcmConfig(uint32_t sample_rate_hz, - uint8_t bit_rate, +void LeAudioTransport::LeAudioSetSelectedHalPcmConfig(uint32_t sample_rate_hz, uint8_t bit_rate, uint8_t channels_count, uint32_t data_interval) { pcm_config_.sampleRate = le_audio_sample_rate2audio_hal(sample_rate_hz); @@ -258,8 +250,7 @@ void LeAudioTransport::LeAudioSetSelectedHalPcmConfig(uint32_t sample_rate_hz, } bool LeAudioTransport::IsRequestCompletedAfterUpdate( - const std::function(StartRequestState)>& - lambda) { + const std::function(StartRequestState)>& lambda) { std::lock_guard guard(start_request_state_mutex_); auto result = lambda(start_request_state_); auto new_state = std::get<0>(result); @@ -268,14 +259,11 @@ bool LeAudioTransport::IsRequestCompletedAfterUpdate( } auto ret = std::get<1>(result); - log::verbose("new state: {}, return: {}", - static_cast(start_request_state_.load()), ret); + log::verbose("new state: {}, return: {}", static_cast(start_request_state_.load()), ret); return ret; } -StartRequestState LeAudioTransport::GetStartRequestState(void) { - return start_request_state_; -} +StartRequestState LeAudioTransport::GetStartRequestState(void) { return start_request_state_; } void LeAudioTransport::ClearStartRequestState(void) { start_request_state_ = StartRequestState::IDLE; } @@ -284,19 +272,19 @@ void LeAudioTransport::SetStartRequestState(StartRequestState state) { } void flush_sink() { - if (!is_sink_hal_enabled()) return; + if (!is_sink_hal_enabled()) { + return; + } LeAudioSinkTransport::interface->FlushAudioData(); } -LeAudioSinkTransport::LeAudioSinkTransport(SessionType_2_1 session_type, - StreamCallbacks stream_cb) +LeAudioSinkTransport::LeAudioSinkTransport(SessionType_2_1 session_type, StreamCallbacks stream_cb) : IBluetoothSinkTransportInstance(session_type, {}) { - transport_ = - new LeAudioTransport(flush_sink, std::move(stream_cb), - {SampleRate_2_1::RATE_16000, ChannelMode::STEREO, - BitsPerSample::BITS_16, 0}); -}; + transport_ = new LeAudioTransport( + flush_sink, std::move(stream_cb), + {SampleRate_2_1::RATE_16000, ChannelMode::STEREO, BitsPerSample::BITS_16, 0}); +} LeAudioSinkTransport::~LeAudioSinkTransport() { delete transport_; } @@ -313,21 +301,18 @@ BluetoothAudioCtrlAck LeAudioSinkTransport::SuspendRequest() { void LeAudioSinkTransport::StopRequest() { transport_->StopRequest(); } -bool LeAudioSinkTransport::GetPresentationPosition( - uint64_t* remote_delay_report_ns, uint64_t* total_bytes_read, - timespec* data_position) { - return transport_->GetPresentationPosition(remote_delay_report_ns, - total_bytes_read, data_position); +bool LeAudioSinkTransport::GetPresentationPosition(uint64_t* remote_delay_report_ns, + uint64_t* total_bytes_read, + timespec* data_position) { + return transport_->GetPresentationPosition(remote_delay_report_ns, total_bytes_read, + data_position); } -void LeAudioSinkTransport::MetadataChanged( - const source_metadata_t& source_metadata) { +void LeAudioSinkTransport::MetadataChanged(const source_metadata_t& source_metadata) { transport_->MetadataChanged(source_metadata); } -void LeAudioSinkTransport::ResetPresentationPosition() { - transport_->ResetPresentationPosition(); -} +void LeAudioSinkTransport::ResetPresentationPosition() { transport_->ResetPresentationPosition(); } void LeAudioSinkTransport::LogBytesRead(size_t bytes_read) { transport_->LogBytesProcessed(bytes_read); @@ -341,31 +326,30 @@ const PcmParameters& LeAudioSinkTransport::LeAudioGetSelectedHalPcmConfig() { return transport_->LeAudioGetSelectedHalPcmConfig(); } -void LeAudioSinkTransport::LeAudioSetSelectedHalPcmConfig( - uint32_t sample_rate_hz, uint8_t bit_rate, uint8_t channels_count, - uint32_t data_interval) { - transport_->LeAudioSetSelectedHalPcmConfig(sample_rate_hz, bit_rate, - channels_count, data_interval); +void LeAudioSinkTransport::LeAudioSetSelectedHalPcmConfig(uint32_t sample_rate_hz, uint8_t bit_rate, + uint8_t channels_count, + uint32_t data_interval) { + transport_->LeAudioSetSelectedHalPcmConfig(sample_rate_hz, bit_rate, channels_count, + data_interval); } bool LeAudioSinkTransport::IsRequestCompletedAfterUpdate( - const std::function(StartRequestState)>& - lambda) { + const std::function(StartRequestState)>& lambda) { return transport_->IsRequestCompletedAfterUpdate(lambda); } StartRequestState LeAudioSinkTransport::GetStartRequestState(void) { return transport_->GetStartRequestState(); } -void LeAudioSinkTransport::ClearStartRequestState(void) { - transport_->ClearStartRequestState(); -} +void LeAudioSinkTransport::ClearStartRequestState(void) { transport_->ClearStartRequestState(); } void LeAudioSinkTransport::SetStartRequestState(StartRequestState state) { transport_->SetStartRequestState(state); } void flush_source() { - if (LeAudioSourceTransport::interface == nullptr) return; + if (LeAudioSourceTransport::interface == nullptr) { + return; + } LeAudioSourceTransport::interface->FlushAudioData(); } @@ -373,11 +357,10 @@ void flush_source() { LeAudioSourceTransport::LeAudioSourceTransport(SessionType_2_1 session_type, StreamCallbacks stream_cb) : IBluetoothSourceTransportInstance(session_type, {}) { - transport_ = - new LeAudioTransport(flush_source, std::move(stream_cb), - {SampleRate_2_1::RATE_16000, ChannelMode::MONO, - BitsPerSample::BITS_16, 0}); -}; + transport_ = new LeAudioTransport( + flush_source, std::move(stream_cb), + {SampleRate_2_1::RATE_16000, ChannelMode::MONO, BitsPerSample::BITS_16, 0}); +} LeAudioSourceTransport::~LeAudioSourceTransport() { delete transport_; } @@ -394,15 +377,14 @@ BluetoothAudioCtrlAck LeAudioSourceTransport::SuspendRequest() { void LeAudioSourceTransport::StopRequest() { transport_->StopRequest(); } -bool LeAudioSourceTransport::GetPresentationPosition( - uint64_t* remote_delay_report_ns, uint64_t* total_bytes_written, - timespec* data_position) { - return transport_->GetPresentationPosition( - remote_delay_report_ns, total_bytes_written, data_position); +bool LeAudioSourceTransport::GetPresentationPosition(uint64_t* remote_delay_report_ns, + uint64_t* total_bytes_written, + timespec* data_position) { + return transport_->GetPresentationPosition(remote_delay_report_ns, total_bytes_written, + data_position); } -void LeAudioSourceTransport::MetadataChanged( - const source_metadata_t& source_metadata) { +void LeAudioSourceTransport::MetadataChanged(const source_metadata_t& source_metadata) { transport_->MetadataChanged(source_metadata); } @@ -422,24 +404,22 @@ const PcmParameters& LeAudioSourceTransport::LeAudioGetSelectedHalPcmConfig() { return transport_->LeAudioGetSelectedHalPcmConfig(); } -void LeAudioSourceTransport::LeAudioSetSelectedHalPcmConfig( - uint32_t sample_rate_hz, uint8_t bit_rate, uint8_t channels_count, - uint32_t data_interval) { - transport_->LeAudioSetSelectedHalPcmConfig(sample_rate_hz, bit_rate, - channels_count, data_interval); +void LeAudioSourceTransport::LeAudioSetSelectedHalPcmConfig(uint32_t sample_rate_hz, + uint8_t bit_rate, + uint8_t channels_count, + uint32_t data_interval) { + transport_->LeAudioSetSelectedHalPcmConfig(sample_rate_hz, bit_rate, channels_count, + data_interval); } bool LeAudioSourceTransport::IsRequestCompletedAfterUpdate( - const std::function(StartRequestState)>& - lambda) { + const std::function(StartRequestState)>& lambda) { return transport_->IsRequestCompletedAfterUpdate(lambda); } StartRequestState LeAudioSourceTransport::GetStartRequestState(void) { return transport_->GetStartRequestState(); } -void LeAudioSourceTransport::ClearStartRequestState(void) { - transport_->ClearStartRequestState(); -} +void LeAudioSourceTransport::ClearStartRequestState(void) { transport_->ClearStartRequestState(); } void LeAudioSourceTransport::SetStartRequestState(StartRequestState state) { transport_->SetStartRequestState(state); } diff --git a/system/audio_hal_interface/hidl/le_audio_software_hidl.h b/system/audio_hal_interface/hidl/le_audio_software_hidl.h index 3ad92feb090..32c91b9a3a7 100644 --- a/system/audio_hal_interface/hidl/le_audio_software_hidl.h +++ b/system/audio_hal_interface/hidl/le_audio_software_hidl.h @@ -55,9 +55,8 @@ bool is_source_hal_enabled(); bool is_sink_hal_enabled(); class LeAudioTransport { - public: - LeAudioTransport(void (*flush)(void), StreamCallbacks stream_cb, - PcmParameters pcm_config); +public: + LeAudioTransport(void (*flush)(void), StreamCallbacks stream_cb, PcmParameters pcm_config); BluetoothAudioCtrlAck StartRequest(); BluetoothAudioCtrlAck StartRequestV2(); @@ -66,8 +65,7 @@ class LeAudioTransport { void StopRequest(); - bool GetPresentationPosition(uint64_t* remote_delay_report_ns, - uint64_t* total_bytes_processed, + bool GetPresentationPosition(uint64_t* remote_delay_report_ns, uint64_t* total_bytes_processed, timespec* data_position); void MetadataChanged(const source_metadata_t& source_metadata); @@ -81,18 +79,16 @@ class LeAudioTransport { const PcmParameters& LeAudioGetSelectedHalPcmConfig(); void LeAudioSetSelectedHalPcmConfig(uint32_t sample_rate_hz, uint8_t bit_rate, - uint8_t channels_count, - uint32_t data_interval); + uint8_t channels_count, uint32_t data_interval); bool IsRequestCompletedAfterUpdate( - const std::function< - std::pair(StartRequestState)>& lambda); + const std::function(StartRequestState)>& lambda); StartRequestState GetStartRequestState(void); void ClearStartRequestState(void); void SetStartRequestState(StartRequestState state); - private: +private: void (*flush_)(void); StreamCallbacks stream_cb_; uint16_t remote_delay_report_ms_; @@ -104,9 +100,8 @@ class LeAudioTransport { }; // Sink transport implementation for Le Audio -class LeAudioSinkTransport - : public ::bluetooth::audio::hidl::IBluetoothSinkTransportInstance { - public: +class LeAudioSinkTransport : public ::bluetooth::audio::hidl::IBluetoothSinkTransportInstance { +public: LeAudioSinkTransport(SessionType_2_1 session_type, StreamCallbacks stream_cb); ~LeAudioSinkTransport(); @@ -118,8 +113,7 @@ class LeAudioSinkTransport void StopRequest() override; - bool GetPresentationPosition(uint64_t* remote_delay_report_ns, - uint64_t* total_bytes_read, + bool GetPresentationPosition(uint64_t* remote_delay_report_ns, uint64_t* total_bytes_read, timespec* data_position) override; void MetadataChanged(const source_metadata_t& source_metadata) override; @@ -133,12 +127,10 @@ class LeAudioSinkTransport const PcmParameters& LeAudioGetSelectedHalPcmConfig(); void LeAudioSetSelectedHalPcmConfig(uint32_t sample_rate_hz, uint8_t bit_rate, - uint8_t channels_count, - uint32_t data_interval); + uint8_t channels_count, uint32_t data_interval); bool IsRequestCompletedAfterUpdate( - const std::function< - std::pair(StartRequestState)>& lambda); + const std::function(StartRequestState)>& lambda); StartRequestState GetStartRequestState(void); void ClearStartRequestState(void); @@ -147,15 +139,13 @@ class LeAudioSinkTransport static inline LeAudioSinkTransport* instance = nullptr; static inline BluetoothAudioSinkClientInterface* interface = nullptr; - private: +private: LeAudioTransport* transport_; }; -class LeAudioSourceTransport - : public ::bluetooth::audio::hidl::IBluetoothSourceTransportInstance { - public: - LeAudioSourceTransport(SessionType_2_1 session_type, - StreamCallbacks stream_cb); +class LeAudioSourceTransport : public ::bluetooth::audio::hidl::IBluetoothSourceTransportInstance { +public: + LeAudioSourceTransport(SessionType_2_1 session_type, StreamCallbacks stream_cb); ~LeAudioSourceTransport(); @@ -165,8 +155,7 @@ class LeAudioSourceTransport void StopRequest() override; - bool GetPresentationPosition(uint64_t* remote_delay_report_ns, - uint64_t* total_bytes_written, + bool GetPresentationPosition(uint64_t* remote_delay_report_ns, uint64_t* total_bytes_written, timespec* data_position) override; void MetadataChanged(const source_metadata_t& source_metadata) override; @@ -180,12 +169,10 @@ class LeAudioSourceTransport const PcmParameters& LeAudioGetSelectedHalPcmConfig(); void LeAudioSetSelectedHalPcmConfig(uint32_t sample_rate_hz, uint8_t bit_rate, - uint8_t channels_count, - uint32_t data_interval); + uint8_t channels_count, uint32_t data_interval); bool IsRequestCompletedAfterUpdate( - const std::function< - std::pair(StartRequestState)>& lambda); + const std::function(StartRequestState)>& lambda); StartRequestState GetStartRequestState(void); void ClearStartRequestState(void); void SetStartRequestState(StartRequestState state); @@ -193,7 +180,7 @@ class LeAudioSourceTransport static inline LeAudioSourceTransport* instance = nullptr; static inline BluetoothAudioSourceClientInterface* interface = nullptr; - private: +private: LeAudioTransport* transport_; }; diff --git a/system/audio_hal_interface/le_audio_software.cc b/system/audio_hal_interface/le_audio_software.cc index 54845499de0..6566e1d0431 100644 --- a/system/audio_hal_interface/le_audio_software.cc +++ b/system/audio_hal_interface/le_audio_software.cc @@ -48,10 +48,8 @@ namespace le_audio { namespace { using ::android::hardware::bluetooth::audio::V2_1::PcmParameters; -using AudioConfiguration_2_1 = - ::android::hardware::bluetooth::audio::V2_1::AudioConfiguration; -using AudioConfigurationAIDL = - ::aidl::android::hardware::bluetooth::audio::AudioConfiguration; +using AudioConfiguration_2_1 = ::android::hardware::bluetooth::audio::V2_1::AudioConfiguration; +using AudioConfigurationAIDL = ::aidl::android::hardware::bluetooth::audio::AudioConfiguration; using ::aidl::android::hardware::bluetooth::audio::AudioContext; using ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider; using ::aidl::android::hardware::bluetooth::audio::LatencyMode; @@ -63,40 +61,33 @@ using ::bluetooth::le_audio::types::CodecLocation; } // namespace OffloadCapabilities get_offload_capabilities() { - if (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::HIDL) { - return {std::vector(0), - std::vector(0)}; + if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::HIDL) { + return {std::vector(0), std::vector(0)}; } return aidl::le_audio::get_offload_capabilities(); } -aidl::BluetoothAudioSinkClientInterface* get_aidl_client_interface( - bool is_broadcaster) { - if (is_broadcaster) +aidl::BluetoothAudioSinkClientInterface* get_aidl_client_interface(bool is_broadcaster) { + if (is_broadcaster) { return aidl::le_audio::LeAudioSinkTransport::interface_broadcast_; + } return aidl::le_audio::LeAudioSinkTransport::interface_unicast_; } -aidl::le_audio::LeAudioSinkTransport* get_aidl_transport_instance( - bool is_broadcaster) { - if (is_broadcaster) +aidl::le_audio::LeAudioSinkTransport* get_aidl_transport_instance(bool is_broadcaster) { + if (is_broadcaster) { return aidl::le_audio::LeAudioSinkTransport::instance_broadcast_; + } return aidl::le_audio::LeAudioSinkTransport::instance_unicast_; } bool is_aidl_offload_encoding_session(bool is_broadcaster) { - return get_aidl_client_interface(is_broadcaster) - ->GetTransportInstance() - ->GetSessionType() == - aidl::SessionType::LE_AUDIO_HARDWARE_OFFLOAD_ENCODING_DATAPATH || - get_aidl_client_interface(is_broadcaster) - ->GetTransportInstance() - ->GetSessionType() == - aidl::SessionType:: - LE_AUDIO_BROADCAST_HARDWARE_OFFLOAD_ENCODING_DATAPATH; + return get_aidl_client_interface(is_broadcaster)->GetTransportInstance()->GetSessionType() == + aidl::SessionType::LE_AUDIO_HARDWARE_OFFLOAD_ENCODING_DATAPATH || + get_aidl_client_interface(is_broadcaster)->GetTransportInstance()->GetSessionType() == + aidl::SessionType::LE_AUDIO_BROADCAST_HARDWARE_OFFLOAD_ENCODING_DATAPATH; } LeAudioClientInterface* LeAudioClientInterface::interface = nullptr; @@ -106,20 +97,19 @@ LeAudioClientInterface* LeAudioClientInterface::Get() { return nullptr; } - if (LeAudioClientInterface::interface == nullptr) + if (LeAudioClientInterface::interface == nullptr) { LeAudioClientInterface::interface = new LeAudioClientInterface(); + } return LeAudioClientInterface::interface; } void LeAudioClientInterface::Sink::Cleanup() { log::info("HAL transport: 0x{:02x}, is broadcast: {}", - static_cast(HalVersionManager::GetHalTransport()), - is_broadcaster_); + static_cast(HalVersionManager::GetHalTransport()), is_broadcaster_); /* Cleanup transport interface and instance according to type and role */ - if (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::HIDL) { + if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::HIDL) { if (hidl::le_audio::LeAudioSinkTransport::interface) { delete hidl::le_audio::LeAudioSinkTransport::interface; hidl::le_audio::LeAudioSinkTransport::interface = nullptr; @@ -128,8 +118,7 @@ void LeAudioClientInterface::Sink::Cleanup() { delete hidl::le_audio::LeAudioSinkTransport::instance; hidl::le_audio::LeAudioSinkTransport::instance = nullptr; } - } else if (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::AIDL) { + } else if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::AIDL) { if (IsBroadcaster()) { if (aidl::le_audio::LeAudioSinkTransport::interface_broadcast_) { delete aidl::le_audio::LeAudioSinkTransport::interface_broadcast_; @@ -155,28 +144,22 @@ void LeAudioClientInterface::Sink::Cleanup() { } } -void LeAudioClientInterface::Sink::SetPcmParameters( - const PcmParameters& params) { - if (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::HIDL) { - return hidl::le_audio::LeAudioSinkTransport::instance - ->LeAudioSetSelectedHalPcmConfig( +void LeAudioClientInterface::Sink::SetPcmParameters(const PcmParameters& params) { + if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::HIDL) { + return hidl::le_audio::LeAudioSinkTransport::instance->LeAudioSetSelectedHalPcmConfig( params.sample_rate, params.bits_per_sample, params.channels_count, params.data_interval_us); } return get_aidl_transport_instance(is_broadcaster_) - ->LeAudioSetSelectedHalPcmConfig( - params.sample_rate, params.bits_per_sample, params.channels_count, - params.data_interval_us); + ->LeAudioSetSelectedHalPcmConfig(params.sample_rate, params.bits_per_sample, + params.channels_count, params.data_interval_us); } // Update Le Audio delay report to BluetoothAudio HAL void LeAudioClientInterface::Sink::SetRemoteDelay(uint16_t delay_report_ms) { log::info("delay_report_ms={} ms", delay_report_ms); - if (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::HIDL) { - hidl::le_audio::LeAudioSinkTransport::instance->SetRemoteDelay( - delay_report_ms); + if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::HIDL) { + hidl::le_audio::LeAudioSinkTransport::instance->SetRemoteDelay(delay_report_ms); return; } get_aidl_transport_instance(is_broadcaster_)->SetRemoteDelay(delay_report_ms); @@ -184,38 +167,31 @@ void LeAudioClientInterface::Sink::SetRemoteDelay(uint16_t delay_report_ms) { void LeAudioClientInterface::Sink::StartSession() { log::info(""); - if (HalVersionManager::GetHalVersion() == - BluetoothAudioHalVersion::VERSION_2_1) { + if (HalVersionManager::GetHalVersion() == BluetoothAudioHalVersion::VERSION_2_1) { AudioConfiguration_2_1 audio_config; - audio_config.pcmConfig(hidl::le_audio::LeAudioSinkTransport::instance - ->LeAudioGetSelectedHalPcmConfig()); - if (!hidl::le_audio::LeAudioSinkTransport::interface->UpdateAudioConfig_2_1( - audio_config)) { + audio_config.pcmConfig( + hidl::le_audio::LeAudioSinkTransport::instance->LeAudioGetSelectedHalPcmConfig()); + if (!hidl::le_audio::LeAudioSinkTransport::interface->UpdateAudioConfig_2_1(audio_config)) { log::error("cannot update audio config to HAL"); return; } hidl::le_audio::LeAudioSinkTransport::interface->StartSession_2_1(); return; - } else if (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::AIDL) { + } else if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::AIDL) { AudioConfigurationAIDL audio_config; if (is_aidl_offload_encoding_session(is_broadcaster_)) { if (is_broadcaster_) { audio_config.set( - get_aidl_transport_instance(is_broadcaster_) - ->LeAudioGetBroadcastConfig()); + get_aidl_transport_instance(is_broadcaster_)->LeAudioGetBroadcastConfig()); } else { aidl::le_audio::LeAudioConfiguration le_audio_config = {}; - audio_config.set( - le_audio_config); + audio_config.set(le_audio_config); } } else { audio_config.set( - get_aidl_transport_instance(is_broadcaster_) - ->LeAudioGetSelectedHalPcmConfig()); + get_aidl_transport_instance(is_broadcaster_)->LeAudioGetSelectedHalPcmConfig()); } - if (!get_aidl_client_interface(is_broadcaster_) - ->UpdateAudioConfig(audio_config)) { + if (!get_aidl_client_interface(is_broadcaster_)->UpdateAudioConfig(audio_config)) { log::error("cannot update audio config to HAL"); return; } @@ -224,8 +200,7 @@ void LeAudioClientInterface::Sink::StartSession() { } void LeAudioClientInterface::Sink::ConfirmStreamingRequest() { - if (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::HIDL) { + if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::HIDL) { auto hidl_instance = hidl::le_audio::LeAudioSinkTransport::instance; auto start_request_state = hidl_instance->GetStartRequestState(); @@ -241,7 +216,7 @@ void LeAudioClientInterface::Sink::ConfirmStreamingRequest() { log::info("Response after sending PENDING to audio HAL"); hidl_instance->ClearStartRequestState(); hidl::le_audio::LeAudioSinkTransport::interface->StreamStarted( - hidl::BluetoothAudioCtrlAck::SUCCESS_FINISHED); + hidl::BluetoothAudioCtrlAck::SUCCESS_FINISHED); return; case StartRequestState::CONFIRMED: case StartRequestState::CANCELED: @@ -264,7 +239,7 @@ void LeAudioClientInterface::Sink::ConfirmStreamingRequest() { log::info("Response after sending PENDING to audio HAL"); aidl_instance->ClearStartRequestState(); get_aidl_client_interface(is_broadcaster_) - ->StreamStarted(aidl::BluetoothAudioCtrlAck::SUCCESS_FINISHED); + ->StreamStarted(aidl::BluetoothAudioCtrlAck::SUCCESS_FINISHED); return; case StartRequestState::CONFIRMED: case StartRequestState::CANCELED: @@ -274,8 +249,8 @@ void LeAudioClientInterface::Sink::ConfirmStreamingRequest() { } void LeAudioClientInterface::Sink::ConfirmStreamingRequestV2() { - auto lambda = [&](StartRequestState currect_start_request_state) - -> std::pair { + auto lambda = + [&](StartRequestState currect_start_request_state) -> std::pair { switch (currect_start_request_state) { case StartRequestState::IDLE: log::warn(", no pending start stream request"); @@ -293,12 +268,11 @@ void LeAudioClientInterface::Sink::ConfirmStreamingRequestV2() { } }; - if (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::HIDL) { + if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::HIDL) { auto hidl_instance = hidl::le_audio::LeAudioSinkTransport::instance; if (hidl_instance->IsRequestCompletedAfterUpdate(lambda)) { hidl::le_audio::LeAudioSinkTransport::interface->StreamStarted( - hidl::BluetoothAudioCtrlAck::SUCCESS_FINISHED); + hidl::BluetoothAudioCtrlAck::SUCCESS_FINISHED); } return; @@ -307,13 +281,12 @@ void LeAudioClientInterface::Sink::ConfirmStreamingRequestV2() { auto aidl_instance = get_aidl_transport_instance(is_broadcaster_); if (aidl_instance->IsRequestCompletedAfterUpdate(lambda)) { get_aidl_client_interface(is_broadcaster_) - ->StreamStarted(aidl::BluetoothAudioCtrlAck::SUCCESS_FINISHED); + ->StreamStarted(aidl::BluetoothAudioCtrlAck::SUCCESS_FINISHED); } } void LeAudioClientInterface::Sink::CancelStreamingRequest() { - if (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::HIDL) { + if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::HIDL) { auto hidl_instance = hidl::le_audio::LeAudioSinkTransport::instance; auto start_request_state = hidl_instance->GetStartRequestState(); switch (start_request_state) { @@ -328,7 +301,7 @@ void LeAudioClientInterface::Sink::CancelStreamingRequest() { log::info("Response after sending PENDING to audio HAL"); hidl_instance->ClearStartRequestState(); hidl::le_audio::LeAudioSinkTransport::interface->StreamStarted( - hidl::BluetoothAudioCtrlAck::FAILURE); + hidl::BluetoothAudioCtrlAck::FAILURE); return; case StartRequestState::CONFIRMED: case StartRequestState::CANCELED: @@ -351,7 +324,7 @@ void LeAudioClientInterface::Sink::CancelStreamingRequest() { log::info("Response after sending PENDING to audio HAL"); aidl_instance->ClearStartRequestState(); get_aidl_client_interface(is_broadcaster_) - ->StreamStarted(aidl::BluetoothAudioCtrlAck::FAILURE); + ->StreamStarted(aidl::BluetoothAudioCtrlAck::FAILURE); return; case StartRequestState::CONFIRMED: case StartRequestState::CANCELED: @@ -361,8 +334,8 @@ void LeAudioClientInterface::Sink::CancelStreamingRequest() { } void LeAudioClientInterface::Sink::CancelStreamingRequestV2() { - auto lambda = [&](StartRequestState currect_start_request_state) - -> std::pair { + auto lambda = + [&](StartRequestState currect_start_request_state) -> std::pair { switch (currect_start_request_state) { case StartRequestState::IDLE: log::warn(", no pending start stream request"); @@ -380,27 +353,24 @@ void LeAudioClientInterface::Sink::CancelStreamingRequestV2() { } }; - if (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::HIDL) { + if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::HIDL) { auto hidl_instance = hidl::le_audio::LeAudioSinkTransport::instance; if (hidl_instance->IsRequestCompletedAfterUpdate(lambda)) { hidl::le_audio::LeAudioSinkTransport::interface->StreamStarted( - hidl::BluetoothAudioCtrlAck::FAILURE); + hidl::BluetoothAudioCtrlAck::FAILURE); } return; } auto aidl_instance = get_aidl_transport_instance(is_broadcaster_); if (aidl_instance->IsRequestCompletedAfterUpdate(lambda)) { - get_aidl_client_interface(is_broadcaster_) - ->StreamStarted(aidl::BluetoothAudioCtrlAck::FAILURE); + get_aidl_client_interface(is_broadcaster_)->StreamStarted(aidl::BluetoothAudioCtrlAck::FAILURE); } } void LeAudioClientInterface::Sink::StopSession() { log::info("sink"); - if (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::HIDL) { + if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::HIDL) { hidl::le_audio::LeAudioSinkTransport::instance->ClearStartRequestState(); hidl::le_audio::LeAudioSinkTransport::interface->EndSession(); return; @@ -410,9 +380,8 @@ void LeAudioClientInterface::Sink::StopSession() { } void LeAudioClientInterface::Sink::UpdateAudioConfigToHal( - const ::bluetooth::le_audio::offload_config& offload_config) { - if (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::HIDL) { + const ::bluetooth::le_audio::offload_config& offload_config) { + if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::HIDL) { return; } @@ -421,19 +390,15 @@ void LeAudioClientInterface::Sink::UpdateAudioConfigToHal( } get_aidl_client_interface(is_broadcaster_) - ->UpdateAudioConfig( - aidl::le_audio::offload_config_to_hal_audio_config(offload_config)); + ->UpdateAudioConfig(aidl::le_audio::offload_config_to_hal_audio_config(offload_config)); } std::optional<::bluetooth::le_audio::broadcaster::BroadcastConfiguration> LeAudioClientInterface::Sink::GetBroadcastConfig( - const std::vector< - std::pair<::bluetooth::le_audio::types::LeAudioContextType, uint8_t>>& - subgroup_quality, - const std::optional< - std::vector<::bluetooth::le_audio::types::acs_ac_record>>& pacs) const { - if (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::HIDL) { + const std::vector>& + subgroup_quality, + const std::optional>& pacs) const { + if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::HIDL) { return std::nullopt; } @@ -442,11 +407,10 @@ LeAudioClientInterface::Sink::GetBroadcastConfig( } auto aidl_pacs = GetAidlLeAudioDeviceCapabilitiesFromStackFormat(pacs); - auto reqs = GetAidlLeAudioBroadcastConfigurationRequirementFromStackFormat( - subgroup_quality); + auto reqs = GetAidlLeAudioBroadcastConfigurationRequirementFromStackFormat(subgroup_quality); auto aidl_broadcast_config = - aidl::le_audio::LeAudioSourceTransport:: - interface->getLeAudioBroadcastConfiguration(aidl_pacs, reqs); + aidl::le_audio::LeAudioSourceTransport::interface->getLeAudioBroadcastConfiguration( + aidl_pacs, reqs); return GetStackBroadcastConfigurationFromAidlFormat(aidl_broadcast_config); } @@ -455,25 +419,22 @@ LeAudioClientInterface::Sink::GetBroadcastConfig( // Note: We need a bulk API as well to get multiple configurations for caching std::optional<::bluetooth::le_audio::set_configurations::AudioSetConfiguration> LeAudioClientInterface::Sink::GetUnicastConfig( - const ::bluetooth::le_audio::CodecManager::UnicastConfigurationRequirements& - requirements) const { + const ::bluetooth::le_audio::CodecManager::UnicastConfigurationRequirements& requirements) + const { log::debug("Requirements: {}", requirements); - auto aidl_sink_pacs = - GetAidlLeAudioDeviceCapabilitiesFromStackFormat(requirements.sink_pacs); + auto aidl_sink_pacs = GetAidlLeAudioDeviceCapabilitiesFromStackFormat(requirements.sink_pacs); - auto aidl_source_pacs = - GetAidlLeAudioDeviceCapabilitiesFromStackFormat(requirements.source_pacs); + auto aidl_source_pacs = GetAidlLeAudioDeviceCapabilitiesFromStackFormat(requirements.source_pacs); std::vector reqs; reqs.push_back(GetAidlLeAudioUnicastConfigurationRequirementsFromStackFormat( - requirements.audio_context_type, requirements.sink_requirements, - requirements.source_requirements)); + requirements.audio_context_type, requirements.sink_requirements, + requirements.source_requirements)); log::debug("Making an AIDL call"); - auto aidl_configs = - get_aidl_client_interface(is_broadcaster_) - ->GetLeAudioAseConfiguration(aidl_sink_pacs, aidl_source_pacs, reqs); + auto aidl_configs = get_aidl_client_interface(is_broadcaster_) + ->GetLeAudioAseConfiguration(aidl_sink_pacs, aidl_source_pacs, reqs); log::debug("Received {} configs", aidl_configs.size()); @@ -486,17 +447,15 @@ LeAudioClientInterface::Sink::GetUnicastConfig( * Note: For a bulk request we need to implement GetUnicastConfigs() method */ if (aidl_configs.size() > 1) { - log::warn("Expected a single configuration, but received {}", - aidl_configs.size()); + log::warn("Expected a single configuration, but received {}", aidl_configs.size()); } - return GetStackUnicastConfigurationFromAidlFormat( - requirements.audio_context_type, aidl_configs.at(0)); + return GetStackUnicastConfigurationFromAidlFormat(requirements.audio_context_type, + aidl_configs.at(0)); } void LeAudioClientInterface::Sink::UpdateBroadcastAudioConfigToHal( - const ::bluetooth::le_audio::broadcast_offload_config& offload_config) { - if (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::HIDL) { + const ::bluetooth::le_audio::broadcast_offload_config& offload_config) { + if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::HIDL) { return; } @@ -504,39 +463,34 @@ void LeAudioClientInterface::Sink::UpdateBroadcastAudioConfigToHal( return; } - get_aidl_transport_instance(is_broadcaster_) - ->LeAudioSetBroadcastConfig(offload_config); + get_aidl_transport_instance(is_broadcaster_)->LeAudioSetBroadcastConfig(offload_config); } void LeAudioClientInterface::Sink::SuspendedForReconfiguration() { - if (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::HIDL) { + if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::HIDL) { hidl::le_audio::LeAudioSinkTransport::interface->StreamSuspended( - hidl::BluetoothAudioCtrlAck::SUCCESS_FINISHED); + hidl::BluetoothAudioCtrlAck::SUCCESS_FINISHED); return; } get_aidl_client_interface(is_broadcaster_) - ->StreamSuspended(aidl::BluetoothAudioCtrlAck::SUCCESS_RECONFIGURATION); + ->StreamSuspended(aidl::BluetoothAudioCtrlAck::SUCCESS_RECONFIGURATION); } void LeAudioClientInterface::Sink::ReconfigurationComplete() { // This is needed only for AIDL since SuspendedForReconfiguration() // already calls StreamSuspended(SUCCESS_FINISHED) for HIDL - if (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::AIDL) { + if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::AIDL) { // FIXME: For now we have to workaround the missing API and use // StreamSuspended() with SUCCESS_FINISHED ack code. get_aidl_client_interface(is_broadcaster_) - ->StreamSuspended(aidl::BluetoothAudioCtrlAck::SUCCESS_FINISHED); + ->StreamSuspended(aidl::BluetoothAudioCtrlAck::SUCCESS_FINISHED); } } size_t LeAudioClientInterface::Sink::Read(uint8_t* p_buf, uint32_t len) { - if (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::HIDL) { - return hidl::le_audio::LeAudioSinkTransport::interface->ReadAudioData(p_buf, - len); + if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::HIDL) { + return hidl::le_audio::LeAudioSinkTransport::interface->ReadAudioData(p_buf, len); } return get_aidl_client_interface(is_broadcaster_)->ReadAudioData(p_buf, len); } @@ -561,66 +515,53 @@ void LeAudioClientInterface::Source::Cleanup() { } } -void LeAudioClientInterface::Source::SetPcmParameters( - const PcmParameters& params) { - if (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::HIDL) { - hidl::le_audio::LeAudioSourceTransport::instance - ->LeAudioSetSelectedHalPcmConfig( +void LeAudioClientInterface::Source::SetPcmParameters(const PcmParameters& params) { + if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::HIDL) { + hidl::le_audio::LeAudioSourceTransport::instance->LeAudioSetSelectedHalPcmConfig( params.sample_rate, params.bits_per_sample, params.channels_count, params.data_interval_us); return; } - return aidl::le_audio::LeAudioSourceTransport::instance - ->LeAudioSetSelectedHalPcmConfig( + return aidl::le_audio::LeAudioSourceTransport::instance->LeAudioSetSelectedHalPcmConfig( params.sample_rate, params.bits_per_sample, params.channels_count, params.data_interval_us); } void LeAudioClientInterface::Source::SetRemoteDelay(uint16_t delay_report_ms) { log::info("delay_report_ms={} ms", delay_report_ms); - if (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::HIDL) { - hidl::le_audio::LeAudioSourceTransport::instance->SetRemoteDelay( - delay_report_ms); + if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::HIDL) { + hidl::le_audio::LeAudioSourceTransport::instance->SetRemoteDelay(delay_report_ms); return; } - return aidl::le_audio::LeAudioSourceTransport::instance->SetRemoteDelay( - delay_report_ms); + return aidl::le_audio::LeAudioSourceTransport::instance->SetRemoteDelay(delay_report_ms); } void LeAudioClientInterface::Source::StartSession() { log::info(""); - if (HalVersionManager::GetHalVersion() == - BluetoothAudioHalVersion::VERSION_2_1) { + if (HalVersionManager::GetHalVersion() == BluetoothAudioHalVersion::VERSION_2_1) { AudioConfiguration_2_1 audio_config; - audio_config.pcmConfig(hidl::le_audio::LeAudioSourceTransport::instance - ->LeAudioGetSelectedHalPcmConfig()); - if (!hidl::le_audio::LeAudioSourceTransport:: - interface->UpdateAudioConfig_2_1(audio_config)) { + audio_config.pcmConfig( + hidl::le_audio::LeAudioSourceTransport::instance->LeAudioGetSelectedHalPcmConfig()); + if (!hidl::le_audio::LeAudioSourceTransport::interface->UpdateAudioConfig_2_1(audio_config)) { log::error("cannot update audio config to HAL"); return; } hidl::le_audio::LeAudioSourceTransport::interface->StartSession_2_1(); return; - } else if (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::AIDL) { + } else if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::AIDL) { AudioConfigurationAIDL audio_config; - if (aidl::le_audio::LeAudioSourceTransport:: - interface->GetTransportInstance() + if (aidl::le_audio::LeAudioSourceTransport::interface->GetTransportInstance() ->GetSessionType() == aidl::SessionType::LE_AUDIO_HARDWARE_OFFLOAD_DECODING_DATAPATH) { aidl::le_audio::LeAudioConfiguration le_audio_config; audio_config.set( - aidl::le_audio::LeAudioConfiguration{}); + aidl::le_audio::LeAudioConfiguration{}); } else { audio_config.set( - aidl::le_audio::LeAudioSourceTransport::instance - ->LeAudioGetSelectedHalPcmConfig()); + aidl::le_audio::LeAudioSourceTransport::instance->LeAudioGetSelectedHalPcmConfig()); } - if (!aidl::le_audio::LeAudioSourceTransport::interface->UpdateAudioConfig( - audio_config)) { + if (!aidl::le_audio::LeAudioSourceTransport::interface->UpdateAudioConfig(audio_config)) { log::error("cannot update audio config to HAL"); return; } @@ -629,32 +570,29 @@ void LeAudioClientInterface::Source::StartSession() { } void LeAudioClientInterface::Source::SuspendedForReconfiguration() { - if (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::HIDL) { + if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::HIDL) { hidl::le_audio::LeAudioSourceTransport::interface->StreamSuspended( - hidl::BluetoothAudioCtrlAck::SUCCESS_FINISHED); + hidl::BluetoothAudioCtrlAck::SUCCESS_FINISHED); return; } aidl::le_audio::LeAudioSourceTransport::interface->StreamSuspended( - aidl::BluetoothAudioCtrlAck::SUCCESS_RECONFIGURATION); + aidl::BluetoothAudioCtrlAck::SUCCESS_RECONFIGURATION); } void LeAudioClientInterface::Source::ReconfigurationComplete() { // This is needed only for AIDL since SuspendedForReconfiguration() // already calls StreamSuspended(SUCCESS_FINISHED) for HIDL - if (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::AIDL) { + if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::AIDL) { // FIXME: For now we have to workaround the missing API and use // StreamSuspended() with SUCCESS_FINISHED ack code. aidl::le_audio::LeAudioSourceTransport::interface->StreamSuspended( - aidl::BluetoothAudioCtrlAck::SUCCESS_FINISHED); + aidl::BluetoothAudioCtrlAck::SUCCESS_FINISHED); } } void LeAudioClientInterface::Source::ConfirmStreamingRequest() { - if (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::HIDL) { + if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::HIDL) { auto hidl_instance = hidl::le_audio::LeAudioSourceTransport::instance; auto start_request_state = hidl_instance->GetStartRequestState(); @@ -670,7 +608,7 @@ void LeAudioClientInterface::Source::ConfirmStreamingRequest() { log::info("Response after sending PENDING to audio HAL"); hidl_instance->ClearStartRequestState(); hidl::le_audio::LeAudioSourceTransport::interface->StreamStarted( - hidl::BluetoothAudioCtrlAck::SUCCESS_FINISHED); + hidl::BluetoothAudioCtrlAck::SUCCESS_FINISHED); return; case StartRequestState::CONFIRMED: case StartRequestState::CANCELED: @@ -693,7 +631,7 @@ void LeAudioClientInterface::Source::ConfirmStreamingRequest() { log::info("Response after sending PENDING to audio HAL"); aidl_instance->ClearStartRequestState(); aidl::le_audio::LeAudioSourceTransport::interface->StreamStarted( - aidl::BluetoothAudioCtrlAck::SUCCESS_FINISHED); + aidl::BluetoothAudioCtrlAck::SUCCESS_FINISHED); return; case StartRequestState::CONFIRMED: case StartRequestState::CANCELED: @@ -703,8 +641,8 @@ void LeAudioClientInterface::Source::ConfirmStreamingRequest() { } void LeAudioClientInterface::Source::ConfirmStreamingRequestV2() { - auto lambda = [&](StartRequestState currect_start_request_state) - -> std::pair { + auto lambda = + [&](StartRequestState currect_start_request_state) -> std::pair { switch (currect_start_request_state) { case StartRequestState::IDLE: log::warn(", no pending start stream request"); @@ -722,13 +660,12 @@ void LeAudioClientInterface::Source::ConfirmStreamingRequestV2() { } }; - if (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::HIDL) { + if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::HIDL) { auto hidl_instance = hidl::le_audio::LeAudioSourceTransport::instance; if (hidl_instance->IsRequestCompletedAfterUpdate(lambda)) { hidl::le_audio::LeAudioSourceTransport::interface->StreamStarted( - hidl::BluetoothAudioCtrlAck::SUCCESS_FINISHED); + hidl::BluetoothAudioCtrlAck::SUCCESS_FINISHED); } return; } @@ -736,13 +673,12 @@ void LeAudioClientInterface::Source::ConfirmStreamingRequestV2() { auto aidl_instance = aidl::le_audio::LeAudioSourceTransport::instance; if (aidl_instance->IsRequestCompletedAfterUpdate(lambda)) { aidl::le_audio::LeAudioSourceTransport::interface->StreamStarted( - aidl::BluetoothAudioCtrlAck::SUCCESS_FINISHED); + aidl::BluetoothAudioCtrlAck::SUCCESS_FINISHED); } } void LeAudioClientInterface::Source::CancelStreamingRequest() { - if (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::HIDL) { + if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::HIDL) { auto hidl_instance = hidl::le_audio::LeAudioSourceTransport::instance; auto start_request_state = hidl_instance->GetStartRequestState(); switch (start_request_state) { @@ -757,7 +693,7 @@ void LeAudioClientInterface::Source::CancelStreamingRequest() { log::info("Response after sending PENDING to audio HAL"); hidl_instance->ClearStartRequestState(); hidl::le_audio::LeAudioSourceTransport::interface->StreamStarted( - hidl::BluetoothAudioCtrlAck::FAILURE); + hidl::BluetoothAudioCtrlAck::FAILURE); return; case StartRequestState::CONFIRMED: case StartRequestState::CANCELED: @@ -780,7 +716,7 @@ void LeAudioClientInterface::Source::CancelStreamingRequest() { log::info("Response after sending PENDING to audio HAL"); aidl_instance->ClearStartRequestState(); aidl::le_audio::LeAudioSourceTransport::interface->StreamStarted( - aidl::BluetoothAudioCtrlAck::FAILURE); + aidl::BluetoothAudioCtrlAck::FAILURE); return; case StartRequestState::CONFIRMED: case StartRequestState::CANCELED: @@ -790,8 +726,8 @@ void LeAudioClientInterface::Source::CancelStreamingRequest() { } void LeAudioClientInterface::Source::CancelStreamingRequestV2() { - auto lambda = [&](StartRequestState currect_start_request_state) - -> std::pair { + auto lambda = + [&](StartRequestState currect_start_request_state) -> std::pair { switch (currect_start_request_state) { case StartRequestState::IDLE: log::warn(", no pending start stream request"); @@ -809,12 +745,11 @@ void LeAudioClientInterface::Source::CancelStreamingRequestV2() { } }; - if (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::HIDL) { + if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::HIDL) { auto hidl_instance = hidl::le_audio::LeAudioSourceTransport::instance; if (hidl_instance->IsRequestCompletedAfterUpdate(lambda)) { hidl::le_audio::LeAudioSourceTransport::interface->StreamStarted( - hidl::BluetoothAudioCtrlAck::FAILURE); + hidl::BluetoothAudioCtrlAck::FAILURE); } return; } @@ -822,14 +757,13 @@ void LeAudioClientInterface::Source::CancelStreamingRequestV2() { auto aidl_instance = aidl::le_audio::LeAudioSourceTransport::instance; if (aidl_instance->IsRequestCompletedAfterUpdate(lambda)) { aidl::le_audio::LeAudioSourceTransport::interface->StreamStarted( - aidl::BluetoothAudioCtrlAck::FAILURE); + aidl::BluetoothAudioCtrlAck::FAILURE); } } void LeAudioClientInterface::Source::StopSession() { log::info("source"); - if (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::HIDL) { + if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::HIDL) { hidl::le_audio::LeAudioSourceTransport::instance->ClearStartRequestState(); hidl::le_audio::LeAudioSourceTransport::interface->EndSession(); return; @@ -839,38 +773,31 @@ void LeAudioClientInterface::Source::StopSession() { } void LeAudioClientInterface::Source::UpdateAudioConfigToHal( - const ::bluetooth::le_audio::offload_config& offload_config) { - if (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::HIDL) { + const ::bluetooth::le_audio::offload_config& offload_config) { + if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::HIDL) { return; } - if (aidl::le_audio::LeAudioSourceTransport::interface->GetTransportInstance() - ->GetSessionType() != + if (aidl::le_audio::LeAudioSourceTransport::interface->GetTransportInstance()->GetSessionType() != aidl::SessionType::LE_AUDIO_HARDWARE_OFFLOAD_DECODING_DATAPATH) { return; } aidl::le_audio::LeAudioSourceTransport::interface->UpdateAudioConfig( - aidl::le_audio::offload_config_to_hal_audio_config(offload_config)); + aidl::le_audio::offload_config_to_hal_audio_config(offload_config)); } -size_t LeAudioClientInterface::Source::Write(const uint8_t* p_buf, - uint32_t len) { - if (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::HIDL) { - return hidl::le_audio::LeAudioSourceTransport::interface->WriteAudioData( - p_buf, len); +size_t LeAudioClientInterface::Source::Write(const uint8_t* p_buf, uint32_t len) { + if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::HIDL) { + return hidl::le_audio::LeAudioSourceTransport::interface->WriteAudioData(p_buf, len); } - return aidl::le_audio::LeAudioSourceTransport::interface->WriteAudioData( - p_buf, len); + return aidl::le_audio::LeAudioSourceTransport::interface->WriteAudioData(p_buf, len); } LeAudioClientInterface::Sink* LeAudioClientInterface::GetSink( - StreamCallbacks stream_cb, - bluetooth::common::MessageLoopThread* message_loop, - bool is_broadcasting_session_type) { - if (is_broadcasting_session_type && HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::HIDL) { + StreamCallbacks stream_cb, bluetooth::common::MessageLoopThread* message_loop, + bool is_broadcasting_session_type) { + if (is_broadcasting_session_type && + HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::HIDL) { log::warn("No support for broadcasting Le Audio on HIDL"); return nullptr; } @@ -885,16 +812,12 @@ LeAudioClientInterface::Sink* LeAudioClientInterface::GetSink( log::info(""); - if (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::HIDL) { - hidl::SessionType_2_1 session_type = - hidl::SessionType_2_1::LE_AUDIO_SOFTWARE_ENCODING_DATAPATH; + if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::HIDL) { + hidl::SessionType_2_1 session_type = hidl::SessionType_2_1::LE_AUDIO_SOFTWARE_ENCODING_DATAPATH; hidl::le_audio::LeAudioSinkTransport::instance = - new hidl::le_audio::LeAudioSinkTransport(session_type, - std::move(stream_cb)); - hidl::le_audio::LeAudioSinkTransport::interface = - new hidl::BluetoothAudioSinkClientInterface( + new hidl::le_audio::LeAudioSinkTransport(session_type, std::move(stream_cb)); + hidl::le_audio::LeAudioSinkTransport::interface = new hidl::BluetoothAudioSinkClientInterface( hidl::le_audio::LeAudioSinkTransport::instance, message_loop); if (!hidl::le_audio::LeAudioSinkTransport::interface->IsValid()) { log::warn("BluetoothAudio HAL for Le Audio is invalid?!"); @@ -909,30 +832,24 @@ LeAudioClientInterface::Sink* LeAudioClientInterface::GetSink( } } else { aidl::SessionType session_type = - is_broadcasting_session_type - ? aidl::SessionType::LE_AUDIO_BROADCAST_SOFTWARE_ENCODING_DATAPATH - : aidl::SessionType::LE_AUDIO_SOFTWARE_ENCODING_DATAPATH; - if (CodecManager::GetInstance()->GetCodecLocation() != - CodecLocation::HOST) { + is_broadcasting_session_type + ? aidl::SessionType::LE_AUDIO_BROADCAST_SOFTWARE_ENCODING_DATAPATH + : aidl::SessionType::LE_AUDIO_SOFTWARE_ENCODING_DATAPATH; + if (CodecManager::GetInstance()->GetCodecLocation() != CodecLocation::HOST) { session_type = - is_broadcasting_session_type - ? aidl::SessionType:: - LE_AUDIO_BROADCAST_HARDWARE_OFFLOAD_ENCODING_DATAPATH - : aidl::SessionType::LE_AUDIO_HARDWARE_OFFLOAD_ENCODING_DATAPATH; + is_broadcasting_session_type + ? aidl::SessionType::LE_AUDIO_BROADCAST_HARDWARE_OFFLOAD_ENCODING_DATAPATH + : aidl::SessionType::LE_AUDIO_HARDWARE_OFFLOAD_ENCODING_DATAPATH; } - if (session_type == - aidl::SessionType::LE_AUDIO_HARDWARE_OFFLOAD_ENCODING_DATAPATH || - session_type == - aidl::SessionType::LE_AUDIO_SOFTWARE_ENCODING_DATAPATH) { + if (session_type == aidl::SessionType::LE_AUDIO_HARDWARE_OFFLOAD_ENCODING_DATAPATH || + session_type == aidl::SessionType::LE_AUDIO_SOFTWARE_ENCODING_DATAPATH) { aidl::le_audio::LeAudioSinkTransport::instance_unicast_ = - new aidl::le_audio::LeAudioSinkTransport(session_type, - std::move(stream_cb)); + new aidl::le_audio::LeAudioSinkTransport(session_type, std::move(stream_cb)); aidl::le_audio::LeAudioSinkTransport::interface_unicast_ = - new aidl::BluetoothAudioSinkClientInterface( - aidl::le_audio::LeAudioSinkTransport::instance_unicast_); - if (!aidl::le_audio::LeAudioSinkTransport::interface_unicast_ - ->IsValid()) { + new aidl::BluetoothAudioSinkClientInterface( + aidl::le_audio::LeAudioSinkTransport::instance_unicast_); + if (!aidl::le_audio::LeAudioSinkTransport::interface_unicast_->IsValid()) { log::warn("BluetoothAudio HAL for Le Audio is invalid?!"); delete aidl::le_audio::LeAudioSinkTransport::interface_unicast_; aidl::le_audio::LeAudioSinkTransport::interface_unicast_ = nullptr; @@ -945,13 +862,11 @@ LeAudioClientInterface::Sink* LeAudioClientInterface::GetSink( } } else { aidl::le_audio::LeAudioSinkTransport::instance_broadcast_ = - new aidl::le_audio::LeAudioSinkTransport(session_type, - std::move(stream_cb)); + new aidl::le_audio::LeAudioSinkTransport(session_type, std::move(stream_cb)); aidl::le_audio::LeAudioSinkTransport::interface_broadcast_ = - new aidl::BluetoothAudioSinkClientInterface( - aidl::le_audio::LeAudioSinkTransport::instance_broadcast_); - if (!aidl::le_audio::LeAudioSinkTransport::interface_broadcast_ - ->IsValid()) { + new aidl::BluetoothAudioSinkClientInterface( + aidl::le_audio::LeAudioSinkTransport::instance_broadcast_); + if (!aidl::le_audio::LeAudioSinkTransport::interface_broadcast_->IsValid()) { log::warn("BluetoothAudio HAL for Le Audio is invalid?!"); delete aidl::le_audio::LeAudioSinkTransport::interface_broadcast_; aidl::le_audio::LeAudioSinkTransport::interface_broadcast_ = nullptr; @@ -968,12 +883,8 @@ LeAudioClientInterface::Sink* LeAudioClientInterface::GetSink( return sink; } -bool LeAudioClientInterface::IsUnicastSinkAcquired() { - return unicast_sink_ != nullptr; -} -bool LeAudioClientInterface::IsBroadcastSinkAcquired() { - return broadcast_sink_ != nullptr; -} +bool LeAudioClientInterface::IsUnicastSinkAcquired() { return unicast_sink_ != nullptr; } +bool LeAudioClientInterface::IsBroadcastSinkAcquired() { return broadcast_sink_ != nullptr; } bool LeAudioClientInterface::ReleaseSink(LeAudioClientInterface::Sink* sink) { if (sink != unicast_sink_ && sink != broadcast_sink_) { @@ -986,8 +897,9 @@ bool LeAudioClientInterface::ReleaseSink(LeAudioClientInterface::Sink* sink) { (aidl::le_audio::LeAudioSinkTransport::interface_unicast_ && aidl::le_audio::LeAudioSinkTransport::instance_unicast_) || (aidl::le_audio::LeAudioSinkTransport::interface_broadcast_ && - aidl::le_audio::LeAudioSinkTransport::instance_broadcast_)) + aidl::le_audio::LeAudioSinkTransport::instance_broadcast_)) { sink->Cleanup(); + } if (sink == unicast_sink_) { delete (unicast_sink_); @@ -1001,8 +913,7 @@ bool LeAudioClientInterface::ReleaseSink(LeAudioClientInterface::Sink* sink) { } LeAudioClientInterface::Source* LeAudioClientInterface::GetSource( - StreamCallbacks stream_cb, - bluetooth::common::MessageLoopThread* message_loop) { + StreamCallbacks stream_cb, bluetooth::common::MessageLoopThread* message_loop) { if (source_ == nullptr) { source_ = new Source(); } else { @@ -1012,22 +923,17 @@ LeAudioClientInterface::Source* LeAudioClientInterface::GetSource( log::info(""); - if (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::HIDL) { - hidl::SessionType_2_1 session_type = - hidl::SessionType_2_1::LE_AUDIO_SOFTWARE_DECODED_DATAPATH; - if (CodecManager::GetInstance()->GetCodecLocation() != - CodecLocation::HOST) { - session_type = - hidl::SessionType_2_1::LE_AUDIO_HARDWARE_OFFLOAD_DECODING_DATAPATH; + if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::HIDL) { + hidl::SessionType_2_1 session_type = hidl::SessionType_2_1::LE_AUDIO_SOFTWARE_DECODED_DATAPATH; + if (CodecManager::GetInstance()->GetCodecLocation() != CodecLocation::HOST) { + session_type = hidl::SessionType_2_1::LE_AUDIO_HARDWARE_OFFLOAD_DECODING_DATAPATH; } hidl::le_audio::LeAudioSourceTransport::instance = - new hidl::le_audio::LeAudioSourceTransport(session_type, - std::move(stream_cb)); + new hidl::le_audio::LeAudioSourceTransport(session_type, std::move(stream_cb)); hidl::le_audio::LeAudioSourceTransport::interface = - new hidl::BluetoothAudioSourceClientInterface( - hidl::le_audio::LeAudioSourceTransport::instance, message_loop); + new hidl::BluetoothAudioSourceClientInterface( + hidl::le_audio::LeAudioSourceTransport::instance, message_loop); if (!hidl::le_audio::LeAudioSourceTransport::interface->IsValid()) { log::warn("BluetoothAudio HAL for Le Audio is invalid?!"); delete hidl::le_audio::LeAudioSourceTransport::interface; @@ -1040,20 +946,16 @@ LeAudioClientInterface::Source* LeAudioClientInterface::GetSource( return nullptr; } } else { - aidl::SessionType session_type = - aidl::SessionType::LE_AUDIO_SOFTWARE_DECODING_DATAPATH; - if (CodecManager::GetInstance()->GetCodecLocation() != - CodecLocation::HOST) { - session_type = - aidl::SessionType::LE_AUDIO_HARDWARE_OFFLOAD_DECODING_DATAPATH; + aidl::SessionType session_type = aidl::SessionType::LE_AUDIO_SOFTWARE_DECODING_DATAPATH; + if (CodecManager::GetInstance()->GetCodecLocation() != CodecLocation::HOST) { + session_type = aidl::SessionType::LE_AUDIO_HARDWARE_OFFLOAD_DECODING_DATAPATH; } aidl::le_audio::LeAudioSourceTransport::instance = - new aidl::le_audio::LeAudioSourceTransport(session_type, - std::move(stream_cb)); + new aidl::le_audio::LeAudioSourceTransport(session_type, std::move(stream_cb)); aidl::le_audio::LeAudioSourceTransport::interface = - new aidl::BluetoothAudioSourceClientInterface( - aidl::le_audio::LeAudioSourceTransport::instance); + new aidl::BluetoothAudioSourceClientInterface( + aidl::le_audio::LeAudioSourceTransport::instance); if (!aidl::le_audio::LeAudioSourceTransport::interface->IsValid()) { log::warn("BluetoothAudio HAL for Le Audio is invalid?!"); delete aidl::le_audio::LeAudioSourceTransport::interface; @@ -1072,8 +974,7 @@ LeAudioClientInterface::Source* LeAudioClientInterface::GetSource( bool LeAudioClientInterface::IsSourceAcquired() { return source_ != nullptr; } -bool LeAudioClientInterface::ReleaseSource( - LeAudioClientInterface::Source* source) { +bool LeAudioClientInterface::ReleaseSource(LeAudioClientInterface::Source* source) { if (source != source_) { log::warn("can't release not acquired source"); return false; @@ -1082,8 +983,9 @@ bool LeAudioClientInterface::ReleaseSource( if ((hidl::le_audio::LeAudioSourceTransport::interface && hidl::le_audio::LeAudioSourceTransport::instance) || (aidl::le_audio::LeAudioSourceTransport::interface && - aidl::le_audio::LeAudioSourceTransport::instance)) + aidl::le_audio::LeAudioSourceTransport::instance)) { source->Cleanup(); + } delete (source_); source_ = nullptr; @@ -1096,8 +998,7 @@ void LeAudioClientInterface::SetAllowedDsaModes(DsaModes dsa_modes) { return; } - if (HalVersionManager::GetHalTransport() == - BluetoothAudioHalTransport::AIDL) { + if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::AIDL) { if (aidl::le_audio::LeAudioSinkTransport::interface_unicast_ == nullptr || aidl::le_audio::LeAudioSinkTransport::instance_unicast_ == nullptr) { log::warn("LeAudioSourceTransport::interface is null"); @@ -1108,7 +1009,7 @@ void LeAudioClientInterface::SetAllowedDsaModes(DsaModes dsa_modes) { for (auto dsa_mode : dsa_modes) { switch (dsa_mode) { case DsaMode::DISABLED: - // Already added + // Already added break; case DsaMode::ACL: latency_modes.push_back(LatencyMode::LOW_LATENCY); @@ -1124,8 +1025,7 @@ void LeAudioClientInterface::SetAllowedDsaModes(DsaModes dsa_modes) { break; } } - aidl::le_audio::LeAudioSinkTransport::interface_unicast_ - ->SetAllowedLatencyModes(latency_modes); + aidl::le_audio::LeAudioSinkTransport::interface_unicast_->SetAllowedLatencyModes(latency_modes); } } diff --git a/system/audio_hal_interface/le_audio_software.h b/system/audio_hal_interface/le_audio_software.h index 30cc04229a8..e736a83b337 100644 --- a/system/audio_hal_interface/le_audio_software.h +++ b/system/audio_hal_interface/le_audio_software.h @@ -69,15 +69,15 @@ struct StreamCallbacks { struct OffloadCapabilities { std::vector - unicast_offload_capabilities; + unicast_offload_capabilities; std::vector - broadcast_offload_capabilities; + broadcast_offload_capabilities; }; OffloadCapabilities get_offload_capabilities(); class LeAudioClientInterface { - public: +public: struct PcmParameters { uint32_t data_interval_us; uint32_t sample_rate; @@ -85,9 +85,9 @@ class LeAudioClientInterface { uint8_t channels_count; }; - private: +private: class IClientInterfaceEndpoint { - public: + public: virtual ~IClientInterfaceEndpoint() = default; virtual void Cleanup() = 0; virtual void SetPcmParameters(const PcmParameters& params) = 0; @@ -98,16 +98,15 @@ class LeAudioClientInterface { virtual void CancelStreamingRequest() = 0; virtual void ConfirmStreamingRequestV2() = 0; virtual void CancelStreamingRequestV2() = 0; - virtual void UpdateAudioConfigToHal( - const ::bluetooth::le_audio::offload_config& config) = 0; + virtual void UpdateAudioConfigToHal(const ::bluetooth::le_audio::offload_config& config) = 0; virtual void SuspendedForReconfiguration() = 0; virtual void ReconfigurationComplete() = 0; }; - public: +public: class Sink : public IClientInterfaceEndpoint { - public: - Sink(bool is_broadcaster = false) : is_broadcaster_(is_broadcaster){}; + public: + Sink(bool is_broadcaster = false) : is_broadcaster_(is_broadcaster) {} virtual ~Sink() = default; void Cleanup() override; @@ -119,33 +118,28 @@ class LeAudioClientInterface { void CancelStreamingRequest() override; void ConfirmStreamingRequestV2() override; void CancelStreamingRequestV2() override; - void UpdateAudioConfigToHal( - const ::bluetooth::le_audio::offload_config& config) override; + void UpdateAudioConfigToHal(const ::bluetooth::le_audio::offload_config& config) override; void UpdateBroadcastAudioConfigToHal( - const ::bluetooth::le_audio::broadcast_offload_config& config); + const ::bluetooth::le_audio::broadcast_offload_config& config); void SuspendedForReconfiguration() override; void ReconfigurationComplete() override; // Read the stream of bytes sinked to us by the upper layers size_t Read(uint8_t* p_buf, uint32_t len); bool IsBroadcaster() { return is_broadcaster_; } - std::optional<::bluetooth::le_audio::broadcaster::BroadcastConfiguration> - GetBroadcastConfig( - const std::vector>& - subgroup_quality, - const std::optional< - std::vector<::bluetooth::le_audio::types::acs_ac_record>>& pacs) - const; - std::optional< - ::bluetooth::le_audio::set_configurations::AudioSetConfiguration> - GetUnicastConfig(const ::bluetooth::le_audio::CodecManager:: - UnicastConfigurationRequirements& requirements) const; - - private: + std::optional<::bluetooth::le_audio::broadcaster::BroadcastConfiguration> GetBroadcastConfig( + const std::vector>& + subgroup_quality, + const std::optional>& pacs) + const; + std::optional<::bluetooth::le_audio::set_configurations::AudioSetConfiguration> + GetUnicastConfig(const ::bluetooth::le_audio::CodecManager::UnicastConfigurationRequirements& + requirements) const; + + private: bool is_broadcaster_ = false; }; class Source : public IClientInterfaceEndpoint { - public: + public: virtual ~Source() = default; void Cleanup() override; @@ -157,8 +151,7 @@ class LeAudioClientInterface { void CancelStreamingRequest() override; void ConfirmStreamingRequestV2() override; void CancelStreamingRequestV2() override; - void UpdateAudioConfigToHal( - const ::bluetooth::le_audio::offload_config& config) override; + void UpdateAudioConfigToHal(const ::bluetooth::le_audio::offload_config& config) override; void SuspendedForReconfiguration() override; void ReconfigurationComplete() override; // Source the given stream of bytes to be sinked into the upper layers @@ -167,8 +160,7 @@ class LeAudioClientInterface { // Get LE Audio sink client interface if it's not previously acquired and not // yet released. - Sink* GetSink(StreamCallbacks stream_cb, - bluetooth::common::MessageLoopThread* message_loop, + Sink* GetSink(StreamCallbacks stream_cb, bluetooth::common::MessageLoopThread* message_loop, bool is_broadcasting_session_type); // This should be called before trying to get unicast sink interface bool IsUnicastSinkAcquired(); @@ -179,8 +171,7 @@ class LeAudioClientInterface { // Get LE Audio source client interface if it's not previously acquired and // not yet released. - Source* GetSource(StreamCallbacks stream_cb, - bluetooth::common::MessageLoopThread* message_loop); + Source* GetSource(StreamCallbacks stream_cb, bluetooth::common::MessageLoopThread* message_loop); // This should be called before trying to get source interface bool IsSourceAcquired(); // Release source interface if belongs to LE audio client interface @@ -193,7 +184,7 @@ class LeAudioClientInterface { // singleton. static LeAudioClientInterface* Get(); - private: +private: static LeAudioClientInterface* interface; Sink* unicast_sink_ = nullptr; Sink* broadcast_sink_ = nullptr; diff --git a/system/audio_hal_interface/le_audio_software_host.cc b/system/audio_hal_interface/le_audio_software_host.cc index 74f9b221632..f3ecc7cb782 100644 --- a/system/audio_hal_interface/le_audio_software_host.cc +++ b/system/audio_hal_interface/le_audio_software_host.cc @@ -47,8 +47,7 @@ void lea_data_cb(tUIPC_CH_ID, tUIPC_EVENT event) { * Read directly from media task from here on (keep callback for * connection events. */ - UIPC_Ioctl(*lea_uipc, UIPC_CH_ID_AV_AUDIO, UIPC_REG_REMOVE_ACTIVE_READSET, - NULL); + UIPC_Ioctl(*lea_uipc, UIPC_CH_ID_AV_AUDIO, UIPC_REG_REMOVE_ACTIVE_READSET, NULL); UIPC_Ioctl(*lea_uipc, UIPC_CH_ID_AV_AUDIO, UIPC_SET_READ_POLL_TMO, reinterpret_cast(LEA_DATA_READ_POLL_MS)); break; @@ -86,8 +85,7 @@ bool HostStartRequest() { return false; } - host::le_audio::LeAudioSinkTransport::stream_started = - btle_stream_started_status::IDLE; + host::le_audio::LeAudioSinkTransport::stream_started = btle_stream_started_status::IDLE; host::le_audio::LeAudioSinkTransport::instance->ResetPresentationPosition(); return host::le_audio::LeAudioSinkTransport::instance->StartRequest(); } @@ -107,14 +105,14 @@ btle_pcm_parameters GetHostPcmConfig() { return {}; } - auto pcm_params = host::le_audio::LeAudioSinkTransport::instance - ->LeAudioGetSelectedHalPcmConfig(); + auto pcm_params = + host::le_audio::LeAudioSinkTransport::instance->LeAudioGetSelectedHalPcmConfig(); btle_pcm_parameters pcm_config = { - .data_interval_us = pcm_params.data_interval_us, - .sample_rate = pcm_params.sample_rate, - .bits_per_sample = pcm_params.bits_per_sample, - .channels_count = pcm_params.channels_count, + .data_interval_us = pcm_params.data_interval_us, + .sample_rate = pcm_params.sample_rate, + .bits_per_sample = pcm_params.bits_per_sample, + .channels_count = pcm_params.channels_count, }; return pcm_config; @@ -127,8 +125,7 @@ bool PeerStartRequest() { return false; } - host::le_audio::LeAudioSourceTransport::stream_started = - btle_stream_started_status::IDLE; + host::le_audio::LeAudioSourceTransport::stream_started = btle_stream_started_status::IDLE; host::le_audio::LeAudioSourceTransport::instance->ResetPresentationPosition(); return host::le_audio::LeAudioSourceTransport::instance->StartRequest(); } @@ -148,14 +145,14 @@ btle_pcm_parameters GetPeerPcmConfig() { return {}; } - auto pcm_params = host::le_audio::LeAudioSourceTransport::instance - ->LeAudioGetSelectedHalPcmConfig(); + auto pcm_params = + host::le_audio::LeAudioSourceTransport::instance->LeAudioGetSelectedHalPcmConfig(); btle_pcm_parameters pcm_config = { - .data_interval_us = pcm_params.data_interval_us, - .sample_rate = pcm_params.sample_rate, - .bits_per_sample = pcm_params.bits_per_sample, - .channels_count = pcm_params.channels_count, + .data_interval_us = pcm_params.data_interval_us, + .sample_rate = pcm_params.sample_rate, + .bits_per_sample = pcm_params.bits_per_sample, + .channels_count = pcm_params.channels_count, }; return pcm_config; @@ -171,34 +168,27 @@ btle_stream_started_status GetPeerStreamStarted() { void SourceMetadataChanged(const source_metadata_v7_t& metadata) { if (host::le_audio::LeAudioSourceTransport::instance) { - host::le_audio::LeAudioSourceTransport::instance->SourceMetadataChanged( - metadata); + host::le_audio::LeAudioSourceTransport::instance->SourceMetadataChanged(metadata); } if (host::le_audio::LeAudioSinkTransport::instance) { - host::le_audio::LeAudioSinkTransport::instance->SourceMetadataChanged( - metadata); + host::le_audio::LeAudioSinkTransport::instance->SourceMetadataChanged(metadata); } } void SinkMetadataChanged(const sink_metadata_v7_t& metadata) { if (host::le_audio::LeAudioSourceTransport::instance) { - host::le_audio::LeAudioSourceTransport::instance->SinkMetadataChanged( - metadata); + host::le_audio::LeAudioSourceTransport::instance->SinkMetadataChanged(metadata); } if (host::le_audio::LeAudioSinkTransport::instance) { - host::le_audio::LeAudioSinkTransport::instance->SinkMetadataChanged( - metadata); + host::le_audio::LeAudioSinkTransport::instance->SinkMetadataChanged(metadata); } } OffloadCapabilities get_offload_capabilities() { - return { - std::vector< - bluetooth::le_audio::set_configurations::AudioSetConfiguration>(0), - std::vector< - bluetooth::le_audio::set_configurations::AudioSetConfiguration>(0)}; + return {std::vector(0), + std::vector(0)}; } int GetAidlInterfaceVersion() { return 0; } @@ -212,21 +202,19 @@ void LeAudioClientInterface::Sink::Cleanup() { host::le_audio::LeAudioSinkTransport::instance = nullptr; } -void LeAudioClientInterface::Sink::SetPcmParameters( - const PcmParameters& params) { +void LeAudioClientInterface::Sink::SetPcmParameters(const PcmParameters& params) { if (!host::le_audio::LeAudioSinkTransport::instance) { log::warn("instance is null"); return; } log::info( - "sample_rate={}, bits_per_sample={}, channels_count={}, " - "data_interval_us={}", - params.sample_rate, params.bits_per_sample, params.channels_count, - params.data_interval_us); + "sample_rate={}, bits_per_sample={}, channels_count={}, " + "data_interval_us={}", + params.sample_rate, params.bits_per_sample, params.channels_count, + params.data_interval_us); - host::le_audio::LeAudioSinkTransport::instance - ->LeAudioSetSelectedHalPcmConfig( + host::le_audio::LeAudioSinkTransport::instance->LeAudioSetSelectedHalPcmConfig( params.sample_rate, params.bits_per_sample, params.channels_count, params.data_interval_us); } @@ -239,8 +227,7 @@ void LeAudioClientInterface::Sink::SetRemoteDelay(uint16_t delay_report_ms) { log::info("delay_report_ms={} msec", delay_report_ms); - host::le_audio::LeAudioSinkTransport::instance->SetRemoteDelay( - delay_report_ms); + host::le_audio::LeAudioSinkTransport::instance->SetRemoteDelay(delay_report_ms); } void LeAudioClientInterface::Sink::StartSession() { log::info(""); } @@ -252,8 +239,7 @@ void LeAudioClientInterface::Sink::StopSession() { host::le_audio::LeAudioSinkTransport::instance->ClearStartRequestState(); } - host::le_audio::LeAudioSinkTransport::stream_started = - btle_stream_started_status::IDLE; + host::le_audio::LeAudioSinkTransport::stream_started = btle_stream_started_status::IDLE; } void LeAudioClientInterface::Sink::ConfirmStreamingRequest() { @@ -280,8 +266,7 @@ void LeAudioClientInterface::Sink::ConfirmStreamingRequest() { log::info("Response after sending PENDING to audio HAL"); instance->ClearStartRequestState(); lea_data_path_open(); - host::le_audio::LeAudioSinkTransport::stream_started = - btle_stream_started_status::STARTED; + host::le_audio::LeAudioSinkTransport::stream_started = btle_stream_started_status::STARTED; return; case StartRequestState::CONFIRMED: case StartRequestState::CANCELED: @@ -290,9 +275,7 @@ void LeAudioClientInterface::Sink::ConfirmStreamingRequest() { } } -void LeAudioClientInterface::Sink::ConfirmStreamingRequestV2() { - ConfirmStreamingRequest(); -} +void LeAudioClientInterface::Sink::ConfirmStreamingRequestV2() { ConfirmStreamingRequest(); } void LeAudioClientInterface::Sink::CancelStreamingRequest() { if (!host::le_audio::LeAudioSinkTransport::instance) { @@ -316,8 +299,7 @@ void LeAudioClientInterface::Sink::CancelStreamingRequest() { case StartRequestState::PENDING_AFTER_RESUME: log::info("Response after sending PENDING to audio HAL"); instance->ClearStartRequestState(); - host::le_audio::LeAudioSinkTransport::stream_started = - btle_stream_started_status::CANCELED; + host::le_audio::LeAudioSinkTransport::stream_started = btle_stream_started_status::CANCELED; return; case StartRequestState::CONFIRMED: case StartRequestState::CANCELED: @@ -326,15 +308,13 @@ void LeAudioClientInterface::Sink::CancelStreamingRequest() { } } -void LeAudioClientInterface::Sink::CancelStreamingRequestV2() { - CancelStreamingRequest(); -} +void LeAudioClientInterface::Sink::CancelStreamingRequestV2() { CancelStreamingRequest(); } void LeAudioClientInterface::Sink::UpdateAudioConfigToHal( - const ::le_audio::offload_config& offload_config) {} + const ::le_audio::offload_config& offload_config) {} void LeAudioClientInterface::Sink::UpdateBroadcastAudioConfigToHal( - ::le_audio::broadcast_offload_config const& config) {} + ::le_audio::broadcast_offload_config const& config) {} void LeAudioClientInterface::Sink::SuspendedForReconfiguration() { log::info(""); @@ -355,18 +335,16 @@ size_t LeAudioClientInterface::Sink::Read(uint8_t* p_buf, uint32_t len) { std::optional<::bluetooth::le_audio::set_configurations::AudioSetConfiguration> LeAudioClientInterface::Sink::GetUnicastConfig( - const ::bluetooth::le_audio::CodecManager::UnicastConfigurationRequirements& - requirements) const { + const ::bluetooth::le_audio::CodecManager::UnicastConfigurationRequirements& requirements) + const { return std::nullopt; } std::optional<::bluetooth::le_audio::broadcaster::BroadcastConfiguration> LeAudioClientInterface::Sink::GetBroadcastConfig( - const std::vector< - std::pair<::bluetooth::le_audio::types::LeAudioContextType, uint8_t>>& - subgroup_quality, - const std::optional< - std::vector<::bluetooth::le_audio::types::acs_ac_record>>& pacs) const { + const std::vector>& + subgroup_quality, + const std::optional>& pacs) const { return std::nullopt; } @@ -379,21 +357,19 @@ void LeAudioClientInterface::Source::Cleanup() { host::le_audio::LeAudioSourceTransport::instance = nullptr; } -void LeAudioClientInterface::Source::SetPcmParameters( - const PcmParameters& params) { +void LeAudioClientInterface::Source::SetPcmParameters(const PcmParameters& params) { if (!host::le_audio::LeAudioSourceTransport::instance) { log::warn("instance is null"); return; } log::info( - "sample_rate={}, bits_per_sample={}, channels_count={}, " - "data_interval_us={}", - params.sample_rate, params.bits_per_sample, params.channels_count, - params.data_interval_us); + "sample_rate={}, bits_per_sample={}, channels_count={}, " + "data_interval_us={}", + params.sample_rate, params.bits_per_sample, params.channels_count, + params.data_interval_us); - host::le_audio::LeAudioSourceTransport::instance - ->LeAudioSetSelectedHalPcmConfig( + host::le_audio::LeAudioSourceTransport::instance->LeAudioSetSelectedHalPcmConfig( params.sample_rate, params.bits_per_sample, params.channels_count, params.data_interval_us); } @@ -406,8 +382,7 @@ void LeAudioClientInterface::Source::SetRemoteDelay(uint16_t delay_report_ms) { log::info("delay_report_ms={} msec", delay_report_ms); - host::le_audio::LeAudioSourceTransport::instance->SetRemoteDelay( - delay_report_ms); + host::le_audio::LeAudioSourceTransport::instance->SetRemoteDelay(delay_report_ms); } void LeAudioClientInterface::Source::StartSession() { log::info(""); } @@ -419,8 +394,7 @@ void LeAudioClientInterface::Source::StopSession() { host::le_audio::LeAudioSourceTransport::instance->ClearStartRequestState(); } - host::le_audio::LeAudioSourceTransport::stream_started = - btle_stream_started_status::IDLE; + host::le_audio::LeAudioSourceTransport::stream_started = btle_stream_started_status::IDLE; } void LeAudioClientInterface::Source::ConfirmStreamingRequest() { @@ -447,8 +421,7 @@ void LeAudioClientInterface::Source::ConfirmStreamingRequest() { log::info("Response after sending PENDING to audio HAL"); instance->ClearStartRequestState(); lea_data_path_open(); - host::le_audio::LeAudioSourceTransport::stream_started = - btle_stream_started_status::STARTED; + host::le_audio::LeAudioSourceTransport::stream_started = btle_stream_started_status::STARTED; return; case StartRequestState::CONFIRMED: case StartRequestState::CANCELED: @@ -457,9 +430,7 @@ void LeAudioClientInterface::Source::ConfirmStreamingRequest() { } } -void LeAudioClientInterface::Source::ConfirmStreamingRequestV2() { - ConfirmStreamingRequest(); -} +void LeAudioClientInterface::Source::ConfirmStreamingRequestV2() { ConfirmStreamingRequest(); } void LeAudioClientInterface::Source::CancelStreamingRequest() { if (!host::le_audio::LeAudioSourceTransport::instance) { @@ -483,8 +454,7 @@ void LeAudioClientInterface::Source::CancelStreamingRequest() { case StartRequestState::PENDING_AFTER_RESUME: log::info("Response after sending PENDING to audio HAL"); instance->ClearStartRequestState(); - host::le_audio::LeAudioSourceTransport::stream_started = - btle_stream_started_status::CANCELED; + host::le_audio::LeAudioSourceTransport::stream_started = btle_stream_started_status::CANCELED; return; case StartRequestState::CANCELED: case StartRequestState::CONFIRMED: @@ -493,34 +463,27 @@ void LeAudioClientInterface::Source::CancelStreamingRequest() { } } -void LeAudioClientInterface::Source::CancelStreamingRequestV2() { - CancelStreamingRequest(); -} +void LeAudioClientInterface::Source::CancelStreamingRequestV2() { CancelStreamingRequest(); } void LeAudioClientInterface::Source::UpdateAudioConfigToHal( - const ::le_audio::offload_config& offload_config) {} + const ::le_audio::offload_config& offload_config) {} void LeAudioClientInterface::Source::SuspendedForReconfiguration() { log::info(""); // TODO } -void LeAudioClientInterface::Source::ReconfigurationComplete() { - log::info(""); -} +void LeAudioClientInterface::Source::ReconfigurationComplete() { log::info(""); } -size_t LeAudioClientInterface::Source::Write(const uint8_t* p_buf, - uint32_t len) { +size_t LeAudioClientInterface::Source::Write(const uint8_t* p_buf, uint32_t len) { bool ok = UIPC_Send(*lea_uipc, UIPC_CH_ID_AV_AUDIO, 0, p_buf, len); return ok ? len : 0; } LeAudioClientInterface::Sink* LeAudioClientInterface::GetSink( - StreamCallbacks stream_cb, - bluetooth::common::MessageLoopThread* message_loop, - bool is_broadcasting_session_type) { - if (is_broadcasting_session_type && - !LeAudioHalVerifier::SupportsLeAudioBroadcast()) { + StreamCallbacks stream_cb, bluetooth::common::MessageLoopThread* message_loop, + bool is_broadcasting_session_type) { + if (is_broadcasting_session_type && !LeAudioHalVerifier::SupportsLeAudioBroadcast()) { log::warn("No support for broadcasting Le Audio"); return nullptr; } @@ -535,18 +498,14 @@ LeAudioClientInterface::Sink* LeAudioClientInterface::GetSink( } host::le_audio::LeAudioSinkTransport::instance = - new host::le_audio::LeAudioSinkTransport(std::move(stream_cb)); + new host::le_audio::LeAudioSinkTransport(std::move(stream_cb)); return sink; } -bool LeAudioClientInterface::IsUnicastSinkAcquired() { - return unicast_sink_ != nullptr; -} +bool LeAudioClientInterface::IsUnicastSinkAcquired() { return unicast_sink_ != nullptr; } -bool LeAudioClientInterface::IsBroadcastSinkAcquired() { - return broadcast_sink_ != nullptr; -} +bool LeAudioClientInterface::IsBroadcastSinkAcquired() { return broadcast_sink_ != nullptr; } bool LeAudioClientInterface::ReleaseSink(LeAudioClientInterface::Sink* sink) { if (sink != unicast_sink_ && sink != broadcast_sink_) { @@ -568,8 +527,7 @@ bool LeAudioClientInterface::ReleaseSink(LeAudioClientInterface::Sink* sink) { } LeAudioClientInterface::Source* LeAudioClientInterface::GetSource( - StreamCallbacks stream_cb, - bluetooth::common::MessageLoopThread* message_loop) { + StreamCallbacks stream_cb, bluetooth::common::MessageLoopThread* message_loop) { if (source_ == nullptr) { source_ = new Source(); } else { @@ -580,15 +538,14 @@ LeAudioClientInterface::Source* LeAudioClientInterface::GetSource( log::info(""); host::le_audio::LeAudioSourceTransport::instance = - new host::le_audio::LeAudioSourceTransport(std::move(stream_cb)); + new host::le_audio::LeAudioSourceTransport(std::move(stream_cb)); return source_; } bool LeAudioClientInterface::IsSourceAcquired() { return source_ != nullptr; } -bool LeAudioClientInterface::ReleaseSource( - LeAudioClientInterface::Source* source) { +bool LeAudioClientInterface::ReleaseSource(LeAudioClientInterface::Source* source) { if (source != source_) { log::warn("Can't release not acquired source"); return false; @@ -596,7 +553,9 @@ bool LeAudioClientInterface::ReleaseSource( log::info(""); - if (host::le_audio::LeAudioSourceTransport::instance) source->Cleanup(); + if (host::le_audio::LeAudioSourceTransport::instance) { + source->Cleanup(); + } delete (source_); source_ = nullptr; diff --git a/system/audio_hal_interface/le_audio_software_host_transport.cc b/system/audio_hal_interface/le_audio_software_host_transport.cc index 67edc797047..e3eb36a06af 100644 --- a/system/audio_hal_interface/le_audio_software_host_transport.cc +++ b/system/audio_hal_interface/le_audio_software_host_transport.cc @@ -25,8 +25,7 @@ namespace audio { namespace host { namespace le_audio { -LeAudioTransport::LeAudioTransport(std::function flush, - StreamCallbacks stream_cb, +LeAudioTransport::LeAudioTransport(std::function flush, StreamCallbacks stream_cb, PcmParameters pcm_config) : flush_(std::move(flush)), stream_cb_(std::move(stream_cb)), @@ -34,7 +33,7 @@ LeAudioTransport::LeAudioTransport(std::function flush, total_bytes_processed_(0), data_position_({}), pcm_config_(std::move(pcm_config)), - start_request_state_(StartRequestState::IDLE){}; + start_request_state_(StartRequestState::IDLE) {} bool LeAudioTransport::StartRequest() { SetStartRequestState(StartRequestState::PENDING_BEFORE_RESUME); @@ -81,21 +80,22 @@ void LeAudioTransport::StopRequest() { bool LeAudioTransport::GetPresentationPosition(uint64_t* remote_delay_report_ns, uint64_t* total_bytes_processed, timespec* data_position) { - log::verbose("data={} byte(s), timestamp={}.{}s, delay report={} msec.", - total_bytes_processed_, data_position_.tv_sec, - data_position_.tv_nsec, remote_delay_report_ms_); + log::verbose("data={} byte(s), timestamp={}.{}s, delay report={} msec.", total_bytes_processed_, + data_position_.tv_sec, data_position_.tv_nsec, remote_delay_report_ms_); if (remote_delay_report_ns != nullptr) { *remote_delay_report_ns = remote_delay_report_ms_ * 1000000u; } - if (total_bytes_processed != nullptr) + if (total_bytes_processed != nullptr) { *total_bytes_processed = total_bytes_processed_; - if (data_position != nullptr) *data_position = data_position_; + } + if (data_position != nullptr) { + *data_position = data_position_; + } return true; } -void LeAudioTransport::SourceMetadataChanged( - const source_metadata_v7_t& source_metadata) { +void LeAudioTransport::SourceMetadataChanged(const source_metadata_v7_t& source_metadata) { auto track_count = source_metadata.track_count; if (track_count == 0) { @@ -103,12 +103,10 @@ void LeAudioTransport::SourceMetadataChanged( return; } - stream_cb_.on_metadata_update_(source_metadata, - ::bluetooth::le_audio::DsaMode::DISABLED); + stream_cb_.on_metadata_update_(source_metadata, ::bluetooth::le_audio::DsaMode::DISABLED); } -void LeAudioTransport::SinkMetadataChanged( - const sink_metadata_v7_t& sink_metadata) { +void LeAudioTransport::SinkMetadataChanged(const sink_metadata_v7_t& sink_metadata) { auto track_count = sink_metadata.track_count; if (track_count == 0) { @@ -138,12 +136,9 @@ void LeAudioTransport::SetRemoteDelay(uint16_t delay_report_ms) { remote_delay_report_ms_ = delay_report_ms; } -const PcmParameters& LeAudioTransport::LeAudioGetSelectedHalPcmConfig() { - return pcm_config_; -} +const PcmParameters& LeAudioTransport::LeAudioGetSelectedHalPcmConfig() { return pcm_config_; } -void LeAudioTransport::LeAudioSetSelectedHalPcmConfig(uint32_t sample_rate_hz, - uint8_t bit_rate, +void LeAudioTransport::LeAudioSetSelectedHalPcmConfig(uint32_t sample_rate_hz, uint8_t bit_rate, uint8_t channels_count, uint32_t data_interval) { pcm_config_.sample_rate = sample_rate_hz; @@ -152,9 +147,7 @@ void LeAudioTransport::LeAudioSetSelectedHalPcmConfig(uint32_t sample_rate_hz, pcm_config_.data_interval_us = data_interval; } -StartRequestState LeAudioTransport::GetStartRequestState(void) { - return start_request_state_; -} +StartRequestState LeAudioTransport::GetStartRequestState(void) { return start_request_state_; } void LeAudioTransport::ClearStartRequestState(void) { log::verbose(""); @@ -168,19 +161,19 @@ void LeAudioTransport::SetStartRequestState(StartRequestState state) { static PcmParameters get_source_default_pcm_parameters() { return PcmParameters{ - .data_interval_us = 0, - .sample_rate = 16000, - .bits_per_sample = 16, - .channels_count = 1, + .data_interval_us = 0, + .sample_rate = 16000, + .bits_per_sample = 16, + .channels_count = 1, }; } static PcmParameters get_sink_default_pcm_parameters() { return PcmParameters{ - .data_interval_us = 0, - .sample_rate = 16000, - .bits_per_sample = 16, - .channels_count = 2, + .data_interval_us = 0, + .sample_rate = 16000, + .bits_per_sample = 16, + .channels_count = 2, }; } @@ -189,40 +182,34 @@ LeAudioSinkTransport::LeAudioSinkTransport(StreamCallbacks stream_cb) { // TODO(b/331315361): investigate the effect of flushing the buffer }; - transport_ = new LeAudioTransport(flush_sink, std::move(stream_cb), - get_sink_default_pcm_parameters()); -}; + transport_ = + new LeAudioTransport(flush_sink, std::move(stream_cb), get_sink_default_pcm_parameters()); +} LeAudioSinkTransport::~LeAudioSinkTransport() { delete transport_; } bool LeAudioSinkTransport::StartRequest() { return transport_->StartRequest(); } -bool LeAudioSinkTransport::SuspendRequest() { - return transport_->SuspendRequest(); -} +bool LeAudioSinkTransport::SuspendRequest() { return transport_->SuspendRequest(); } void LeAudioSinkTransport::StopRequest() { transport_->StopRequest(); } -bool LeAudioSinkTransport::GetPresentationPosition( - uint64_t* remote_delay_report_ns, uint64_t* total_bytes_read, - timespec* data_position) { - return transport_->GetPresentationPosition(remote_delay_report_ns, - total_bytes_read, data_position); +bool LeAudioSinkTransport::GetPresentationPosition(uint64_t* remote_delay_report_ns, + uint64_t* total_bytes_read, + timespec* data_position) { + return transport_->GetPresentationPosition(remote_delay_report_ns, total_bytes_read, + data_position); } -void LeAudioSinkTransport::SourceMetadataChanged( - const source_metadata_v7_t& source_metadata) { +void LeAudioSinkTransport::SourceMetadataChanged(const source_metadata_v7_t& source_metadata) { transport_->SourceMetadataChanged(source_metadata); } -void LeAudioSinkTransport::SinkMetadataChanged( - const sink_metadata_v7_t& sink_metadata) { +void LeAudioSinkTransport::SinkMetadataChanged(const sink_metadata_v7_t& sink_metadata) { transport_->SinkMetadataChanged(sink_metadata); } -void LeAudioSinkTransport::ResetPresentationPosition() { - transport_->ResetPresentationPosition(); -} +void LeAudioSinkTransport::ResetPresentationPosition() { transport_->ResetPresentationPosition(); } void LeAudioSinkTransport::LogBytesRead(size_t bytes_read) { transport_->LogBytesProcessed(bytes_read); @@ -236,11 +223,11 @@ const PcmParameters& LeAudioSinkTransport::LeAudioGetSelectedHalPcmConfig() { return transport_->LeAudioGetSelectedHalPcmConfig(); } -void LeAudioSinkTransport::LeAudioSetSelectedHalPcmConfig( - uint32_t sample_rate_hz, uint8_t bit_rate, uint8_t channels_count, - uint32_t data_interval) { - transport_->LeAudioSetSelectedHalPcmConfig(sample_rate_hz, bit_rate, - channels_count, data_interval); +void LeAudioSinkTransport::LeAudioSetSelectedHalPcmConfig(uint32_t sample_rate_hz, uint8_t bit_rate, + uint8_t channels_count, + uint32_t data_interval) { + transport_->LeAudioSetSelectedHalPcmConfig(sample_rate_hz, bit_rate, channels_count, + data_interval); } StartRequestState LeAudioSinkTransport::GetStartRequestState(void) { @@ -263,32 +250,26 @@ LeAudioSourceTransport::LeAudioSourceTransport(StreamCallbacks stream_cb) { transport_ = new LeAudioTransport(flush_source, std::move(stream_cb), get_source_default_pcm_parameters()); -}; +} LeAudioSourceTransport::~LeAudioSourceTransport() { delete transport_; } -bool LeAudioSourceTransport::StartRequest() { - return transport_->StartRequest(); -} +bool LeAudioSourceTransport::StartRequest() { return transport_->StartRequest(); } -bool LeAudioSourceTransport::SuspendRequest() { - return transport_->SuspendRequest(); -} +bool LeAudioSourceTransport::SuspendRequest() { return transport_->SuspendRequest(); } void LeAudioSourceTransport::StopRequest() { transport_->StopRequest(); } -bool LeAudioSourceTransport::GetPresentationPosition( - uint64_t* remote_delay_report_ns, uint64_t* total_bytes_written, - timespec* data_position) { - return transport_->GetPresentationPosition( - remote_delay_report_ns, total_bytes_written, data_position); +bool LeAudioSourceTransport::GetPresentationPosition(uint64_t* remote_delay_report_ns, + uint64_t* total_bytes_written, + timespec* data_position) { + return transport_->GetPresentationPosition(remote_delay_report_ns, total_bytes_written, + data_position); } -void LeAudioSourceTransport::SourceMetadataChanged( - const source_metadata_v7_t& source_metadata) {} +void LeAudioSourceTransport::SourceMetadataChanged(const source_metadata_v7_t& source_metadata) {} -void LeAudioSourceTransport::SinkMetadataChanged( - const sink_metadata_v7_t& sink_metadata) { +void LeAudioSourceTransport::SinkMetadataChanged(const sink_metadata_v7_t& sink_metadata) { transport_->SinkMetadataChanged(sink_metadata); } @@ -308,11 +289,12 @@ const PcmParameters& LeAudioSourceTransport::LeAudioGetSelectedHalPcmConfig() { return transport_->LeAudioGetSelectedHalPcmConfig(); } -void LeAudioSourceTransport::LeAudioSetSelectedHalPcmConfig( - uint32_t sample_rate_hz, uint8_t bit_rate, uint8_t channels_count, - uint32_t data_interval) { - transport_->LeAudioSetSelectedHalPcmConfig(sample_rate_hz, bit_rate, - channels_count, data_interval); +void LeAudioSourceTransport::LeAudioSetSelectedHalPcmConfig(uint32_t sample_rate_hz, + uint8_t bit_rate, + uint8_t channels_count, + uint32_t data_interval) { + transport_->LeAudioSetSelectedHalPcmConfig(sample_rate_hz, bit_rate, channels_count, + data_interval); } StartRequestState LeAudioSourceTransport::GetStartRequestState(void) { diff --git a/system/audio_hal_interface/le_audio_software_host_transport.h b/system/audio_hal_interface/le_audio_software_host_transport.h index c0140ba8964..cb1e1a2bcf7 100644 --- a/system/audio_hal_interface/le_audio_software_host_transport.h +++ b/system/audio_hal_interface/le_audio_software_host_transport.h @@ -38,7 +38,7 @@ using ::bluetooth::audio::le_audio::StreamCallbacks; typedef LeAudioClientInterface::PcmParameters PcmParameters; class LeAudioTransport { - public: +public: LeAudioTransport(std::function flush, StreamCallbacks stream_cb, PcmParameters pcm_config); @@ -48,8 +48,7 @@ class LeAudioTransport { void StopRequest(); - bool GetPresentationPosition(uint64_t* remote_delay_report_ns, - uint64_t* total_bytes_processed, + bool GetPresentationPosition(uint64_t* remote_delay_report_ns, uint64_t* total_bytes_processed, timespec* data_position); void SourceMetadataChanged(const source_metadata_v7_t& source_metadata); @@ -65,14 +64,13 @@ class LeAudioTransport { const PcmParameters& LeAudioGetSelectedHalPcmConfig(); void LeAudioSetSelectedHalPcmConfig(uint32_t sample_rate_hz, uint8_t bit_rate, - uint8_t channels_count, - uint32_t data_interval); + uint8_t channels_count, uint32_t data_interval); StartRequestState GetStartRequestState(void); void ClearStartRequestState(void); void SetStartRequestState(StartRequestState state); - private: +private: std::function flush_; StreamCallbacks stream_cb_; uint16_t remote_delay_report_ms_; @@ -84,7 +82,7 @@ class LeAudioTransport { // Sink transport implementation for Le Audio class LeAudioSinkTransport { - public: +public: LeAudioSinkTransport(StreamCallbacks stream_cb); ~LeAudioSinkTransport(); @@ -95,8 +93,7 @@ class LeAudioSinkTransport { void StopRequest(); - bool GetPresentationPosition(uint64_t* remote_delay_report_ns, - uint64_t* total_bytes_read, + bool GetPresentationPosition(uint64_t* remote_delay_report_ns, uint64_t* total_bytes_read, timespec* data_position); void SourceMetadataChanged(const source_metadata_v7_t& source_metadata); @@ -112,23 +109,21 @@ class LeAudioSinkTransport { const PcmParameters& LeAudioGetSelectedHalPcmConfig(); void LeAudioSetSelectedHalPcmConfig(uint32_t sample_rate_hz, uint8_t bit_rate, - uint8_t channels_count, - uint32_t data_interval); + uint8_t channels_count, uint32_t data_interval); StartRequestState GetStartRequestState(void); void ClearStartRequestState(void); void SetStartRequestState(StartRequestState state); static inline LeAudioSinkTransport* instance = nullptr; - static inline btle_stream_started_status stream_started = - btle_stream_started_status::IDLE; + static inline btle_stream_started_status stream_started = btle_stream_started_status::IDLE; - private: +private: LeAudioTransport* transport_; }; class LeAudioSourceTransport { - public: +public: LeAudioSourceTransport(StreamCallbacks stream_cb); ~LeAudioSourceTransport(); @@ -139,8 +134,7 @@ class LeAudioSourceTransport { void StopRequest(); - bool GetPresentationPosition(uint64_t* remote_delay_report_ns, - uint64_t* total_bytes_written, + bool GetPresentationPosition(uint64_t* remote_delay_report_ns, uint64_t* total_bytes_written, timespec* data_position); void SourceMetadataChanged(const source_metadata_v7_t& source_metadata); @@ -156,18 +150,16 @@ class LeAudioSourceTransport { const PcmParameters& LeAudioGetSelectedHalPcmConfig(); void LeAudioSetSelectedHalPcmConfig(uint32_t sample_rate_hz, uint8_t bit_rate, - uint8_t channels_count, - uint32_t data_interval); + uint8_t channels_count, uint32_t data_interval); StartRequestState GetStartRequestState(void); void ClearStartRequestState(void); void SetStartRequestState(StartRequestState state); static inline LeAudioSourceTransport* instance = nullptr; - static inline btle_stream_started_status stream_started = - btle_stream_started_status::IDLE; + static inline btle_stream_started_status stream_started = btle_stream_started_status::IDLE; - private: +private: LeAudioTransport* transport_; }; diff --git a/system/audio_hal_interface/le_audio_software_unittest.cc b/system/audio_hal_interface/le_audio_software_unittest.cc index e03dde1fc3b..7c1d8138717 100644 --- a/system/audio_hal_interface/le_audio_software_unittest.cc +++ b/system/audio_hal_interface/le_audio_software_unittest.cc @@ -37,57 +37,45 @@ using bluetooth::audio::le_audio::LeAudioClientInterface; using bluetooth::audio::le_audio::StreamCallbacks; extern "C" { -struct android_namespace_t* android_get_exported_namespace(const char*) { - return nullptr; -} -void* android_load_sphal_library(const char* /*name*/, int /*flag*/) { - return nullptr; -} +struct android_namespace_t* android_get_exported_namespace(const char*) { return nullptr; } +void* android_load_sphal_library(const char* /*name*/, int /*flag*/) { return nullptr; } } // MOCKS namespace { class MockHalVersionManager { - public: +public: MockHalVersionManager() = default; MOCK_METHOD((bluetooth::audio::BluetoothAudioHalVersion), GetHalVersion, ()); - MOCK_METHOD((bluetooth::audio::BluetoothAudioHalTransport), GetHalTransport, - ()); - MOCK_METHOD( - (android::sp), - GetProvidersFactory_2_1, ()); - MOCK_METHOD( - (android::sp), - GetProvidersFactory_2_0, ()); + MOCK_METHOD((bluetooth::audio::BluetoothAudioHalTransport), GetHalTransport, ()); + MOCK_METHOD((android::sp), + GetProvidersFactory_2_1, ()); + MOCK_METHOD((android::sp), + GetProvidersFactory_2_0, ()); - static void SetInstance(MockHalVersionManager* ptr) { - MockHalVersionManager::instance_ptr = ptr; - } + static void SetInstance(MockHalVersionManager* ptr) { MockHalVersionManager::instance_ptr = ptr; } static MockHalVersionManager* GetInstance() { return instance_ptr; } - private: +private: static MockHalVersionManager* instance_ptr; }; MockHalVersionManager* MockHalVersionManager::instance_ptr = nullptr; class MockBluetoothAudioClientInterfaceBidirEndpoint { - public: - MOCK_METHOD((size_t), WriteAudioData, - (const uint8_t* /*p_buf*/, uint32_t /*len*/), ()); - MOCK_METHOD((size_t), ReadAudioData, (uint8_t* /*p_buf*/, uint32_t /*len*/), - ()); +public: + MOCK_METHOD((size_t), WriteAudioData, (const uint8_t* /*p_buf*/, uint32_t /*len*/), ()); + MOCK_METHOD((size_t), ReadAudioData, (uint8_t* /*p_buf*/, uint32_t /*len*/), ()); }; class MockBluetoothAudioClientInterfaceHidl { - public: +public: MockBluetoothAudioClientInterfaceBidirEndpoint endpoint; MOCK_METHOD((bool), IsValid, (), (const)); MOCK_METHOD((void), FlushAudioData, ()); MOCK_METHOD((bool), UpdateAudioConfig_2_1, - (const bluetooth::audio::hidl:: - AudioConfiguration_2_1& /*audio_config_2_1*/)); + (const bluetooth::audio::hidl::AudioConfiguration_2_1& /*audio_config_2_1*/)); MOCK_METHOD((int), StartSession_2_1, ()); MOCK_METHOD((void), StreamStarted, (const bluetooth::audio::hidl::BluetoothAudioCtrlAck& /*ack*/)); @@ -95,82 +83,68 @@ class MockBluetoothAudioClientInterfaceHidl { MOCK_METHOD((void), StreamSuspended, (const bluetooth::audio::hidl::BluetoothAudioCtrlAck& /*ack*/)); - static void SetInstance(MockBluetoothAudioClientInterfaceHidl* ptr) { - instance_ptr = ptr; - } + static void SetInstance(MockBluetoothAudioClientInterfaceHidl* ptr) { instance_ptr = ptr; } - static MockBluetoothAudioClientInterfaceHidl* GetInstance() { - return instance_ptr; - } + static MockBluetoothAudioClientInterfaceHidl* GetInstance() { return instance_ptr; } - private: +private: static MockBluetoothAudioClientInterfaceHidl* instance_ptr; }; -MockBluetoothAudioClientInterfaceHidl* - MockBluetoothAudioClientInterfaceHidl::instance_ptr = nullptr; +MockBluetoothAudioClientInterfaceHidl* MockBluetoothAudioClientInterfaceHidl::instance_ptr = + nullptr; class MockBluetoothAudioClientInterfaceAidl { - public: +public: MockBluetoothAudioClientInterfaceBidirEndpoint endpoint; MOCK_METHOD((bool), IsValid, (), (const)); - MOCK_METHOD( - (bool), SetAllowedLatencyModes, - (std::vector /*latency_modes*/)); + MOCK_METHOD((bool), SetAllowedLatencyModes, + (std::vector /*latency_modes*/)); MOCK_METHOD((void), FlushAudioData, ()); - MOCK_METHOD( - (bool), UpdateAudioConfig, - (const bluetooth::audio::aidl::AudioConfiguration& /*audio_config*/)); + MOCK_METHOD((bool), UpdateAudioConfig, + (const bluetooth::audio::aidl::AudioConfiguration& /*audio_config*/)); MOCK_METHOD((int), StartSession, ()); MOCK_METHOD((void), StreamStarted, (const bluetooth::audio::aidl::BluetoothAudioCtrlAck& /*ack*/)); MOCK_METHOD((int), EndSession, ()); MOCK_METHOD((void), StreamSuspended, (const bluetooth::audio::aidl::BluetoothAudioCtrlAck& /*ack*/)); - MOCK_METHOD((std::vector), - GetAudioCapabilities, + MOCK_METHOD((std::vector), GetAudioCapabilities, (bluetooth::audio::aidl::SessionType /*session_type*/)); MOCK_METHOD( - (std::vector< - ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: - LeAudioAseConfigurationSetting>), - GetLeAudioAseConfiguration, - ((std::optional>>&), - (std::optional>>&), - (std::vector< - ::aidl::android::hardware::bluetooth::audio:: - IBluetoothAudioProvider::LeAudioConfigurationRequirement>&))); + (std::vector<::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: + LeAudioAseConfigurationSetting>), + GetLeAudioAseConfiguration, + ((std::optional>>&), + (std::optional>>&), + (std::vector<::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: + LeAudioConfigurationRequirement>&))); MOCK_METHOD( - (::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: - LeAudioBroadcastConfigurationSetting), - getLeAudioBroadcastConfiguration, - ((const std::optional>>&), - (const ::aidl::android::hardware::bluetooth::audio:: - IBluetoothAudioProvider:: - LeAudioBroadcastConfigurationRequirement&))); - - static void SetInstance(MockBluetoothAudioClientInterfaceAidl* ptr) { - instance_ptr = ptr; - } + (::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: + LeAudioBroadcastConfigurationSetting), + getLeAudioBroadcastConfiguration, + ((const std::optional>>&), + (const ::aidl::android::hardware::bluetooth::audio::IBluetoothAudioProvider:: + LeAudioBroadcastConfigurationRequirement&))); - static MockBluetoothAudioClientInterfaceAidl* GetInstance() { - return instance_ptr; - } + static void SetInstance(MockBluetoothAudioClientInterfaceAidl* ptr) { instance_ptr = ptr; } - private: + static MockBluetoothAudioClientInterfaceAidl* GetInstance() { return instance_ptr; } + +private: static MockBluetoothAudioClientInterfaceAidl* instance_ptr; }; -MockBluetoothAudioClientInterfaceAidl* - MockBluetoothAudioClientInterfaceAidl::instance_ptr = nullptr; +MockBluetoothAudioClientInterfaceAidl* MockBluetoothAudioClientInterfaceAidl::instance_ptr = + nullptr; class MockStreamCallbacks { - public: +public: MOCK_METHOD((bool), OnResume, (bool)); MOCK_METHOD((bool), OnSuspend, ()); MOCK_METHOD((bool), OnSourceMetadataUpdate, @@ -181,9 +155,9 @@ class MockStreamCallbacks { namespace bluetooth::audio { const BluetoothAudioHalVersion BluetoothAudioHalVersion::VERSION_UNAVAILABLE = - BluetoothAudioHalVersion(); + BluetoothAudioHalVersion(); const BluetoothAudioHalVersion BluetoothAudioHalVersion::VERSION_2_1 = - BluetoothAudioHalVersion(BluetoothAudioHalTransport::HIDL, 2, 1); + BluetoothAudioHalVersion(BluetoothAudioHalTransport::HIDL, 2, 1); BluetoothAudioHalTransport HalVersionManager::GetHalTransport() { auto instance = MockHalVersionManager::GetInstance(); @@ -202,28 +176,25 @@ BluetoothAudioHalVersion HalVersionManager::GetHalVersion() { } namespace hidl { -class BluetoothAudioDeathRecipient - : public ::android::hardware::hidl_death_recipient { - public: - BluetoothAudioDeathRecipient( - BluetoothAudioClientInterface* clientif, - bluetooth::common::MessageLoopThread* message_loop) +class BluetoothAudioDeathRecipient : public ::android::hardware::hidl_death_recipient { +public: + BluetoothAudioDeathRecipient(BluetoothAudioClientInterface* clientif, + bluetooth::common::MessageLoopThread* message_loop) : bluetooth_audio_clientif_(clientif), message_loop_(message_loop) {} - MOCK_METHOD( - (void), serviceDied, - (uint64_t /*cookie*/, - const ::android::wp<::android::hidl::base::V1_0::IBase>& /*who*/), - (override)); + MOCK_METHOD((void), serviceDied, + (uint64_t /*cookie*/, + const ::android::wp<::android::hidl::base::V1_0::IBase>& /*who*/), + (override)); - private: +private: BluetoothAudioClientInterface* bluetooth_audio_clientif_; bluetooth::common::MessageLoopThread* message_loop_; }; BluetoothAudioClientInterface::BluetoothAudioClientInterface( - android::sp death_recipient, - IBluetoothTransportInstance* instance) + android::sp death_recipient, + IBluetoothTransportInstance* instance) : provider_(nullptr), provider_2_1_(nullptr), session_started_(false), @@ -233,16 +204,12 @@ BluetoothAudioClientInterface::BluetoothAudioClientInterface( } BluetoothAudioSinkClientInterface::BluetoothAudioSinkClientInterface( - IBluetoothSinkTransportInstance* sink, - bluetooth::common::MessageLoopThread* message_loop) - : BluetoothAudioClientInterface{new BluetoothAudioDeathRecipient( - this, message_loop), - sink}, + IBluetoothSinkTransportInstance* sink, bluetooth::common::MessageLoopThread* message_loop) + : BluetoothAudioClientInterface{new BluetoothAudioDeathRecipient(this, message_loop), sink}, sink_(sink) {} BluetoothAudioSinkClientInterface::~BluetoothAudioSinkClientInterface() {} -size_t BluetoothAudioSinkClientInterface::ReadAudioData(uint8_t* p_buf, - uint32_t len) { +size_t BluetoothAudioSinkClientInterface::ReadAudioData(uint8_t* p_buf, uint32_t len) { auto instance = MockBluetoothAudioClientInterfaceHidl::GetInstance(); if (instance) { return instance->endpoint.ReadAudioData(p_buf, len); @@ -251,11 +218,9 @@ size_t BluetoothAudioSinkClientInterface::ReadAudioData(uint8_t* p_buf, } BluetoothAudioSourceClientInterface::BluetoothAudioSourceClientInterface( - IBluetoothSourceTransportInstance* source, - bluetooth::common::MessageLoopThread* message_loop) - : BluetoothAudioClientInterface{new BluetoothAudioDeathRecipient( - this, message_loop), - source}, + IBluetoothSourceTransportInstance* source, + bluetooth::common::MessageLoopThread* message_loop) + : BluetoothAudioClientInterface{new BluetoothAudioDeathRecipient(this, message_loop), source}, source_(source) {} BluetoothAudioSourceClientInterface::~BluetoothAudioSourceClientInterface() {} @@ -267,8 +232,7 @@ bool BluetoothAudioClientInterface::IsValid() const { return false; } -size_t BluetoothAudioSourceClientInterface::WriteAudioData(const uint8_t* p_buf, - uint32_t len) { +size_t BluetoothAudioSourceClientInterface::WriteAudioData(const uint8_t* p_buf, uint32_t len) { auto instance = MockBluetoothAudioClientInterfaceHidl::GetInstance(); if (instance) { return instance->endpoint.WriteAudioData(p_buf, len); @@ -283,8 +247,7 @@ void BluetoothAudioClientInterface::FlushAudioData() { } } -bool BluetoothAudioClientInterface::UpdateAudioConfig_2_1( - const AudioConfiguration_2_1& cfg) { +bool BluetoothAudioClientInterface::UpdateAudioConfig_2_1(const AudioConfiguration_2_1& cfg) { auto instance = MockBluetoothAudioClientInterfaceHidl::GetInstance(); if (instance) { return instance->UpdateAudioConfig_2_1(cfg); @@ -300,8 +263,7 @@ int BluetoothAudioClientInterface::StartSession_2_1() { return -EINVAL; } -void BluetoothAudioClientInterface::StreamStarted( - const BluetoothAudioCtrlAck& ack) { +void BluetoothAudioClientInterface::StreamStarted(const BluetoothAudioCtrlAck& ack) { auto instance = MockBluetoothAudioClientInterfaceHidl::GetInstance(); if (instance) { instance->StreamStarted(ack); @@ -316,8 +278,7 @@ int BluetoothAudioClientInterface::EndSession() { return -EINVAL; } -void BluetoothAudioClientInterface::StreamSuspended( - const BluetoothAudioCtrlAck& ack) { +void BluetoothAudioClientInterface::StreamSuspended(const BluetoothAudioCtrlAck& ack) { auto instance = MockBluetoothAudioClientInterfaceHidl::GetInstance(); if (instance) { instance->StreamSuspended(ack); @@ -353,8 +314,7 @@ std::ostream& operator<<(std::ostream& os, const BluetoothAudioCtrlAck& ack) { } // namespace hidl namespace aidl { -BluetoothAudioClientInterface::BluetoothAudioClientInterface( - IBluetoothTransportInstance* instance) +BluetoothAudioClientInterface::BluetoothAudioClientInterface(IBluetoothTransportInstance* instance) : provider_(nullptr), provider_factory_(nullptr), session_started_(false), @@ -363,12 +323,11 @@ BluetoothAudioClientInterface::BluetoothAudioClientInterface( latency_modes_({LatencyMode::FREE}) {} BluetoothAudioSinkClientInterface::BluetoothAudioSinkClientInterface( - IBluetoothSinkTransportInstance* sink) + IBluetoothSinkTransportInstance* sink) : BluetoothAudioClientInterface{sink}, sink_(sink) {} BluetoothAudioSinkClientInterface::~BluetoothAudioSinkClientInterface() {} -size_t BluetoothAudioSinkClientInterface::ReadAudioData(uint8_t* p_buf, - uint32_t len) { +size_t BluetoothAudioSinkClientInterface::ReadAudioData(uint8_t* p_buf, uint32_t len) { auto instance = MockBluetoothAudioClientInterfaceAidl::GetInstance(); if (instance) { return instance->endpoint.ReadAudioData(p_buf, len); @@ -377,12 +336,11 @@ size_t BluetoothAudioSinkClientInterface::ReadAudioData(uint8_t* p_buf, } BluetoothAudioSourceClientInterface::BluetoothAudioSourceClientInterface( - IBluetoothSourceTransportInstance* source) + IBluetoothSourceTransportInstance* source) : BluetoothAudioClientInterface{source}, source_(source) {} BluetoothAudioSourceClientInterface::~BluetoothAudioSourceClientInterface() {} -size_t BluetoothAudioSourceClientInterface::WriteAudioData(const uint8_t* p_buf, - uint32_t len) { +size_t BluetoothAudioSourceClientInterface::WriteAudioData(const uint8_t* p_buf, uint32_t len) { auto instance = MockBluetoothAudioClientInterfaceAidl::GetInstance(); if (instance) { return instance->endpoint.WriteAudioData(p_buf, len); @@ -398,8 +356,7 @@ bool BluetoothAudioClientInterface::IsValid() const { return false; } -bool BluetoothAudioClientInterface::SetAllowedLatencyModes( - std::vector latency_modes) { +bool BluetoothAudioClientInterface::SetAllowedLatencyModes(std::vector latency_modes) { auto instance = MockBluetoothAudioClientInterfaceAidl::GetInstance(); if (instance) { return instance->SetAllowedLatencyModes(latency_modes); @@ -414,8 +371,7 @@ void BluetoothAudioClientInterface::FlushAudioData() { } } -bool BluetoothAudioClientInterface::UpdateAudioConfig( - const AudioConfiguration& audio_config) { +bool BluetoothAudioClientInterface::UpdateAudioConfig(const AudioConfiguration& audio_config) { auto instance = MockBluetoothAudioClientInterfaceAidl::GetInstance(); if (instance) { return instance->UpdateAudioConfig(audio_config); @@ -431,8 +387,7 @@ int BluetoothAudioClientInterface::StartSession() { return -EINVAL; } -void BluetoothAudioClientInterface::StreamStarted( - const BluetoothAudioCtrlAck& ack) { +void BluetoothAudioClientInterface::StreamStarted(const BluetoothAudioCtrlAck& ack) { auto instance = MockBluetoothAudioClientInterfaceAidl::GetInstance(); if (instance) { instance->StreamStarted(ack); @@ -447,16 +402,15 @@ int BluetoothAudioClientInterface::EndSession() { return -EINVAL; } -void BluetoothAudioClientInterface::StreamSuspended( - const BluetoothAudioCtrlAck& ack) { +void BluetoothAudioClientInterface::StreamSuspended(const BluetoothAudioCtrlAck& ack) { auto instance = MockBluetoothAudioClientInterfaceAidl::GetInstance(); if (instance) { return instance->StreamSuspended(ack); } } -std::vector -BluetoothAudioClientInterface::GetAudioCapabilities(SessionType session_type) { +std::vector BluetoothAudioClientInterface::GetAudioCapabilities( + SessionType session_type) { auto instance = MockBluetoothAudioClientInterfaceAidl::GetInstance(); if (instance) { return instance->GetAudioCapabilities(session_type); @@ -466,19 +420,17 @@ BluetoothAudioClientInterface::GetAudioCapabilities(SessionType session_type) { std::vector BluetoothAudioClientInterface::GetLeAudioAseConfiguration( - std::optional>>& - remoteSinkAudioCapabilities, - std::optional>>& - remoteSourceAudioCapabilities, - std::vector& - requirements) { + std::optional< + std::vector>>& + remoteSinkAudioCapabilities, + std::optional< + std::vector>>& + remoteSourceAudioCapabilities, + std::vector& requirements) { auto instance = MockBluetoothAudioClientInterfaceAidl::GetInstance(); if (instance) { return instance->GetLeAudioAseConfiguration(remoteSinkAudioCapabilities, - remoteSourceAudioCapabilities, - requirements); + remoteSourceAudioCapabilities, requirements); } return std::vector(); @@ -486,15 +438,13 @@ BluetoothAudioClientInterface::GetLeAudioAseConfiguration( IBluetoothAudioProvider::LeAudioBroadcastConfigurationSetting BluetoothAudioClientInterface::getLeAudioBroadcastConfiguration( - const std::optional>>& - remoteSinkAudioCapabilities, - const IBluetoothAudioProvider::LeAudioBroadcastConfigurationRequirement& - requirement) { + const std::optional< + std::vector>>& + remoteSinkAudioCapabilities, + const IBluetoothAudioProvider::LeAudioBroadcastConfigurationRequirement& requirement) { auto instance = MockBluetoothAudioClientInterfaceAidl::GetInstance(); if (instance) { - return instance->getLeAudioBroadcastConfiguration( - remoteSinkAudioCapabilities, requirement); + return instance->getLeAudioBroadcastConfiguration(remoteSinkAudioCapabilities, requirement); } return IBluetoothAudioProvider::LeAudioBroadcastConfigurationSetting(); @@ -533,16 +483,13 @@ std::ostream& operator<<(std::ostream& os, const BluetoothAudioCtrlAck& ack) { } // namespace bluetooth::audio namespace bluetooth::le_audio::broadcaster { -std::ostream& operator<<(std::ostream& os, const BroadcastConfiguration&) { - return os; -} +std::ostream& operator<<(std::ostream& os, const BroadcastConfiguration&) { return os; } } // namespace bluetooth::le_audio::broadcaster namespace server_configurable_flags { -std::string GetServerConfigurableFlag( - const std::string& /* experiment_category_name */, - const std::string& /* experiment_flag_name */, - const std::string& /* default_value */) { +std::string GetServerConfigurableFlag(const std::string& /* experiment_category_name */, + const std::string& /* experiment_flag_name */, + const std::string& /* default_value */) { return ""; } } // namespace server_configurable_flags @@ -563,7 +510,9 @@ static void init_message_loop_thread() { } message_loop_ = message_loop_thread.message_loop(); - if (message_loop_ == nullptr) FAIL() << "unable to get message loop."; + if (message_loop_ == nullptr) { + FAIL() << "unable to get message loop."; + } } static void cleanup_message_loop_thread() { @@ -572,37 +521,35 @@ static void cleanup_message_loop_thread() { } class LeAudioSoftwareUnicastTest : public Test { - protected: +protected: virtual void SetUp() override { init_message_loop_thread(); MockHalVersionManager::SetInstance(&hal_version_manager_); unicast_sink_stream_cb_.reset(new StreamCallbacks{ - std::bind(&MockStreamCallbacks::OnResume, &sink_stream_callbacks_, - std::placeholders::_1), - std::bind(&MockStreamCallbacks::OnSuspend, &sink_stream_callbacks_), - std::bind(&MockStreamCallbacks::OnSourceMetadataUpdate, - &sink_stream_callbacks_, std::placeholders::_1, - std::placeholders::_2), - std::bind(&MockStreamCallbacks::OnSinkMetadataUpdate, - &sink_stream_callbacks_, std::placeholders::_1), + std::bind(&MockStreamCallbacks::OnResume, &sink_stream_callbacks_, + std::placeholders::_1), + std::bind(&MockStreamCallbacks::OnSuspend, &sink_stream_callbacks_), + std::bind(&MockStreamCallbacks::OnSourceMetadataUpdate, &sink_stream_callbacks_, + std::placeholders::_1, std::placeholders::_2), + std::bind(&MockStreamCallbacks::OnSinkMetadataUpdate, &sink_stream_callbacks_, + std::placeholders::_1), }); unicast_source_stream_cb_.reset(new StreamCallbacks{ - std::bind(&MockStreamCallbacks::OnResume, &source_stream_callbacks_, - std::placeholders::_1), - std::bind(&MockStreamCallbacks::OnSuspend, &source_stream_callbacks_), - std::bind(&MockStreamCallbacks::OnSourceMetadataUpdate, - &source_stream_callbacks_, std::placeholders::_1, - std::placeholders::_2), - std::bind(&MockStreamCallbacks::OnSinkMetadataUpdate, - &source_stream_callbacks_, std::placeholders::_1), + std::bind(&MockStreamCallbacks::OnResume, &source_stream_callbacks_, + std::placeholders::_1), + std::bind(&MockStreamCallbacks::OnSuspend, &source_stream_callbacks_), + std::bind(&MockStreamCallbacks::OnSourceMetadataUpdate, &source_stream_callbacks_, + std::placeholders::_1, std::placeholders::_2), + std::bind(&MockStreamCallbacks::OnSinkMetadataUpdate, &source_stream_callbacks_, + std::placeholders::_1), }); - sink_ = LeAudioClientInterface::Get()->GetSink( - *unicast_sink_stream_cb_, &message_loop_thread, is_broadcast_); - source_ = LeAudioClientInterface::Get()->GetSource( - *unicast_source_stream_cb_, &message_loop_thread); + sink_ = LeAudioClientInterface::Get()->GetSink(*unicast_sink_stream_cb_, &message_loop_thread, + is_broadcast_); + source_ = LeAudioClientInterface::Get()->GetSource(*unicast_source_stream_cb_, + &message_loop_thread); if (is_broadcast_) { ASSERT_TRUE(LeAudioClientInterface::Get()->IsBroadcastSinkAcquired()); @@ -651,14 +598,12 @@ class LeAudioSoftwareUnicastTest : public Test { }; class LeAudioSoftwareUnicastTestAidl : public LeAudioSoftwareUnicastTest { - protected: +protected: virtual void SetUp() override { ON_CALL(hal_version_manager_, GetHalTransport) - .WillByDefault( - Return(bluetooth::audio::BluetoothAudioHalTransport::AIDL)); + .WillByDefault(Return(bluetooth::audio::BluetoothAudioHalTransport::AIDL)); - MockBluetoothAudioClientInterfaceAidl::SetInstance( - &audio_client_interface_); + MockBluetoothAudioClientInterfaceAidl::SetInstance(&audio_client_interface_); ON_CALL(audio_client_interface_, IsValid).WillByDefault(Return(true)); LeAudioSoftwareUnicastTest::SetUp(); @@ -673,14 +618,12 @@ TEST_F(LeAudioSoftwareUnicastTestAidl, AcquireAndRelease) { } class LeAudioSoftwareUnicastTestHidl : public LeAudioSoftwareUnicastTest { - protected: +protected: virtual void SetUp() override { ON_CALL(hal_version_manager_, GetHalTransport) - .WillByDefault( - Return(bluetooth::audio::BluetoothAudioHalTransport::HIDL)); + .WillByDefault(Return(bluetooth::audio::BluetoothAudioHalTransport::HIDL)); - MockBluetoothAudioClientInterfaceHidl::SetInstance( - &audio_client_interface_); + MockBluetoothAudioClientInterfaceHidl::SetInstance(&audio_client_interface_); ON_CALL(audio_client_interface_, IsValid).WillByDefault(Return(true)); LeAudioSoftwareUnicastTest::SetUp(); diff --git a/system/audio_hearing_aid_hw/include/audio_hearing_aid_hw.h b/system/audio_hearing_aid_hw/include/audio_hearing_aid_hw.h index d4e8193e562..7283079b334 100644 --- a/system/audio_hearing_aid_hw/include/audio_hearing_aid_hw.h +++ b/system/audio_hearing_aid_hw/include/audio_hearing_aid_hw.h @@ -27,9 +27,8 @@ #ifndef AUDIO_HEARING_AID_HW_H #define AUDIO_HEARING_AID_HW_H -#include - #include +#include /***************************************************************************** * Constants & Macros @@ -140,8 +139,8 @@ typedef uint8_t tHA_CHANNEL_COUNT; // Returns the computed buffer size. If any of the input parameters is // invalid, the return value is the default |AUDIO_STREAM_OUTPUT_BUFFER_SZ|. size_t audio_ha_hw_stream_compute_buffer_size( - btav_a2dp_codec_sample_rate_t codec_sample_rate, - btav_a2dp_codec_bits_per_sample_t codec_bits_per_sample, - btav_a2dp_codec_channel_mode_t codec_channel_mode); + btav_a2dp_codec_sample_rate_t codec_sample_rate, + btav_a2dp_codec_bits_per_sample_t codec_bits_per_sample, + btav_a2dp_codec_channel_mode_t codec_channel_mode); #endif /* AUDIO_HEARING_AID_HW_H */ diff --git a/system/audio_hearing_aid_hw/src/audio_hearing_aid_hw.cc b/system/audio_hearing_aid_hw/src/audio_hearing_aid_hw.cc index 9ee73b28c2e..ac63105662f 100644 --- a/system/audio_hearing_aid_hw/src/audio_hearing_aid_hw.cc +++ b/system/audio_hearing_aid_hw/src/audio_hearing_aid_hw.cc @@ -56,19 +56,14 @@ #define WRITE_POLL_MS 20 #define FNLOG() ALOGV("%s:%d %s: ", __FILE__, __LINE__, __func__) -#define DEBUG(fmt, args...) \ - ALOGD("%s:%d %s: " fmt, __FILE__, __LINE__, __func__, ##args) -#define INFO(fmt, args...) \ - ALOGI("%s:%d %s: " fmt, __FILE__, __LINE__, __func__, ##args) -#define WARN(fmt, args...) \ - ALOGW("%s:%d %s: " fmt, __FILE__, __LINE__, __func__, ##args) -#define ERROR(fmt, args...) \ - ALOGE("%s:%d %s: " fmt, __FILE__, __LINE__, __func__, ##args) +#define DEBUG(fmt, args...) ALOGD("%s:%d %s: " fmt, __FILE__, __LINE__, __func__, ##args) +#define INFO(fmt, args...) ALOGI("%s:%d %s: " fmt, __FILE__, __LINE__, __func__, ##args) +#define WARN(fmt, args...) ALOGW("%s:%d %s: " fmt, __FILE__, __LINE__, __func__, ##args) +#define ERROR(fmt, args...) ALOGE("%s:%d %s: " fmt, __FILE__, __LINE__, __func__, ##args) -#define ASSERTC(cond, msg, val) \ - if (!(cond)) { \ - ERROR("### ASSERT : %s line %d %s (%d) ###", __FILE__, __LINE__, msg, \ - val); \ +#define ASSERTC(cond, msg, val) \ + if (!(cond)) { \ + ERROR("### ASSERT : %s line %d %s (%d) ###", __FILE__, __LINE__, msg, val); \ } #define CASE_RETURN_STR(const) \ @@ -166,7 +161,7 @@ struct ha_stream_in { * Static functions *****************************************************************************/ static void hash_map_utils_dump_string_keys_string_values( - std::unordered_map& map) { + std::unordered_map& map) { for (const auto& ptr : map) { INFO("key: '%s' value: '%s'\n", ptr.first.c_str(), ptr.second.c_str()); } @@ -189,8 +184,7 @@ static void ha_open_ctrl_path(struct ha_stream_common* common); /* logs timestamp with microsec precision pprev is optional in case a dedicated diff is required */ -static void ts_log(UNUSED_ATTR const char* tag, UNUSED_ATTR int val, - struct timespec* pprev_opt) { +static void ts_log(UNUSED_ATTR const char* tag, UNUSED_ATTR int val, struct timespec* pprev_opt) { struct timespec now; static struct timespec prev = {0, 0}; unsigned long long now_us; @@ -201,13 +195,11 @@ static void ts_log(UNUSED_ATTR const char* tag, UNUSED_ATTR int val, now_us = now.tv_sec * USEC_PER_SEC + now.tv_nsec / 1000; if (pprev_opt) { - diff_us = (now.tv_sec - prev.tv_sec) * USEC_PER_SEC + - (now.tv_nsec - prev.tv_nsec) / 1000; + diff_us = (now.tv_sec - prev.tv_sec) * USEC_PER_SEC + (now.tv_nsec - prev.tv_nsec) / 1000; *pprev_opt = now; DEBUG("[%s] ts %08lld, *diff %08lld, val %d", tag, now_us, diff_us, val); } else { - diff_us = (now.tv_sec - prev.tv_sec) * USEC_PER_SEC + - (now.tv_nsec - prev.tv_nsec) / 1000; + diff_us = (now.tv_sec - prev.tv_sec) * USEC_PER_SEC + (now.tv_nsec - prev.tv_nsec) / 1000; prev = now; DEBUG("[%s] ts %08lld, diff %08lld, val %d", tag, now_us, diff_us, val); } @@ -239,9 +231,7 @@ static int calc_audiotime_usec(struct ha_config cfg, int bytes) { break; } - return ( - int)(((int64_t)bytes * (USEC_PER_SEC / (chan_count * bytes_per_sample))) / - cfg.rate); + return (int)(((int64_t)bytes * (USEC_PER_SEC / (chan_count * bytes_per_sample))) / cfg.rate); } /***************************************************************************** @@ -259,21 +249,23 @@ static int skt_connect(const char* path, size_t buffer_sz) { skt_fd = socket(AF_LOCAL, SOCK_STREAM, 0); - if (osi_socket_local_client_connect( - skt_fd, path, ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM) < 0) { + if (osi_socket_local_client_connect(skt_fd, path, ANDROID_SOCKET_NAMESPACE_ABSTRACT, + SOCK_STREAM) < 0) { ERROR("failed to connect (%s)", strerror(errno)); close(skt_fd); return -1; } len = buffer_sz; - ret = - setsockopt(skt_fd, SOL_SOCKET, SO_SNDBUF, (char*)&len, (int)sizeof(len)); - if (ret < 0) ERROR("setsockopt failed (%s)", strerror(errno)); + ret = setsockopt(skt_fd, SOL_SOCKET, SO_SNDBUF, (char*)&len, (int)sizeof(len)); + if (ret < 0) { + ERROR("setsockopt failed (%s)", strerror(errno)); + } - ret = - setsockopt(skt_fd, SOL_SOCKET, SO_RCVBUF, (char*)&len, (int)sizeof(len)); - if (ret < 0) ERROR("setsockopt failed (%s)", strerror(errno)); + ret = setsockopt(skt_fd, SOL_SOCKET, SO_RCVBUF, (char*)&len, (int)sizeof(len)); + if (ret < 0) { + ERROR("setsockopt failed (%s)", strerror(errno)); + } /* Socket send/receive timeout value */ struct timeval tv; @@ -281,13 +273,17 @@ static int skt_connect(const char* path, size_t buffer_sz) { tv.tv_usec = (SOCK_SEND_TIMEOUT_MS % 1000) * 1000; ret = setsockopt(skt_fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)); - if (ret < 0) ERROR("setsockopt failed (%s)", strerror(errno)); + if (ret < 0) { + ERROR("setsockopt failed (%s)", strerror(errno)); + } tv.tv_sec = SOCK_RECV_TIMEOUT_MS / 1000; tv.tv_usec = (SOCK_RECV_TIMEOUT_MS % 1000) * 1000; ret = setsockopt(skt_fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); - if (ret < 0) ERROR("setsockopt failed (%s)", strerror(errno)); + if (ret < 0) { + ERROR("setsockopt failed (%s)", strerror(errno)); + } INFO("connected to stack fd = %d", skt_fd); @@ -302,7 +298,9 @@ static int skt_read(int fd, void* p, size_t len) { ts_log("skt_read recv", len, NULL); OSI_NO_INTR(read = recv(fd, p, len, MSG_NOSIGNAL)); - if (read == -1) ERROR("read failed with errno=%d\n", errno); + if (read == -1) { + ERROR("read failed with errno=%d\n", errno); + } return (int)read; } @@ -316,7 +314,9 @@ static int skt_write(int fd, const void* p, size_t len) { if (WRITE_POLL_MS == 0) { // do not poll, use blocking send OSI_NO_INTR(sent = send(fd, p, len, MSG_NOSIGNAL)); - if (sent == -1) ERROR("write failed with error(%s)", strerror(errno)); + if (sent == -1) { + ERROR("write failed with error(%s)", strerror(errno)); + } return (int)sent; } @@ -361,8 +361,7 @@ static int skt_disconnect(int fd) { * ****************************************************************************/ -static int ha_ctrl_receive(struct ha_stream_common* common, void* buffer, - size_t length) { +static int ha_ctrl_receive(struct ha_stream_common* common, void* buffer, size_t length) { ssize_t ret; int i; @@ -395,13 +394,14 @@ static int ha_ctrl_receive(struct ha_stream_common* common, void* buffer, // Sends control info for stream |common|. The data to send is stored in // |buffer| and has size |length|. // On success, returns the number of octets sent, otherwise -1. -static int ha_ctrl_send(struct ha_stream_common* common, const void* buffer, - size_t length) { +static int ha_ctrl_send(struct ha_stream_common* common, const void* buffer, size_t length) { ssize_t sent; size_t remaining = length; int i; - if (length == 0) return 0; // Nothing to do + if (length == 0) { + return 0; // Nothing to do + } for (i = 0;; i++) { OSI_NO_INTR(sent = send(common->ctrl_fd, buffer, remaining, MSG_NOSIGNAL)); @@ -434,8 +434,7 @@ static int ha_ctrl_send(struct ha_stream_common* common, const void* buffer, return length; } -static int ha_command(struct ha_stream_common* common, - tHEARING_AID_CTRL_CMD cmd) { +static int ha_command(struct ha_stream_common* common, tHEARING_AID_CTRL_CMD cmd) { char ack; DEBUG("HEARING_AID COMMAND %s", audio_ha_hw_dump_ctrl_event(cmd)); @@ -465,13 +464,13 @@ static int ha_command(struct ha_stream_common* common, return -1; } - DEBUG("HEARING_AID COMMAND %s DONE STATUS %d", - audio_ha_hw_dump_ctrl_event(cmd), ack); + DEBUG("HEARING_AID COMMAND %s DONE STATUS %d", audio_ha_hw_dump_ctrl_event(cmd), ack); - if (ack == HEARING_AID_CTRL_ACK_INCALL_FAILURE) return ack; + if (ack == HEARING_AID_CTRL_ACK_INCALL_FAILURE) { + return ack; + } if (ack != HEARING_AID_CTRL_ACK_SUCCESS) { - ERROR("HEARING_AID COMMAND %s error %d", audio_ha_hw_dump_ctrl_event(cmd), - ack); + ERROR("HEARING_AID COMMAND %s error %d", audio_ha_hw_dump_ctrl_event(cmd), ack); return -1; } @@ -495,8 +494,9 @@ static int ha_read_input_audio_config(struct ha_stream_common* common) { return -1; } - if (ha_ctrl_receive(common, &sample_rate, sizeof(tHA_SAMPLE_RATE)) < 0) + if (ha_ctrl_receive(common, &sample_rate, sizeof(tHA_SAMPLE_RATE)) < 0) { return -1; + } if (ha_ctrl_receive(common, &channel_count, sizeof(tHA_CHANNEL_COUNT)) < 0) { return -1; } @@ -533,9 +533,10 @@ static int ha_read_input_audio_config(struct ha_stream_common* common) { return 0; } -static int ha_read_output_audio_config( - struct ha_stream_common* common, btav_a2dp_codec_config_t* codec_config, - btav_a2dp_codec_config_t* codec_capability, bool update_stream_config) { +static int ha_read_output_audio_config(struct ha_stream_common* common, + btav_a2dp_codec_config_t* codec_config, + btav_a2dp_codec_config_t* codec_capability, + bool update_stream_config) { struct ha_config stream_config; if (ha_command(common, HEARING_AID_CTRL_GET_OUTPUT_AUDIO_CONFIG) < 0) { @@ -544,16 +545,16 @@ static int ha_read_output_audio_config( } // Receive the current codec config - if (ha_ctrl_receive(common, &codec_config->sample_rate, - sizeof(btav_a2dp_codec_sample_rate_t)) < 0) { + if (ha_ctrl_receive(common, &codec_config->sample_rate, sizeof(btav_a2dp_codec_sample_rate_t)) < + 0) { return -1; } if (ha_ctrl_receive(common, &codec_config->bits_per_sample, sizeof(btav_a2dp_codec_bits_per_sample_t)) < 0) { return -1; } - if (ha_ctrl_receive(common, &codec_config->channel_mode, - sizeof(btav_a2dp_codec_channel_mode_t)) < 0) { + if (ha_ctrl_receive(common, &codec_config->channel_mode, sizeof(btav_a2dp_codec_channel_mode_t)) < + 0) { return -1; } @@ -646,25 +647,21 @@ static int ha_read_output_audio_config( common->cfg.is_stereo_to_mono = stream_config.is_stereo_to_mono; common->cfg.format = stream_config.format; common->buffer_sz = audio_ha_hw_stream_compute_buffer_size( - codec_config->sample_rate, codec_config->bits_per_sample, - codec_config->channel_mode); + codec_config->sample_rate, codec_config->bits_per_sample, codec_config->channel_mode); if (common->cfg.is_stereo_to_mono) { // We need to fetch twice as much data from the Audio framework common->buffer_sz *= 2; } } - INFO( - "got output codec config (update_stream_config=%s): " - "sample_rate=0x%x bits_per_sample=0x%x channel_mode=0x%x", - update_stream_config ? "true" : "false", codec_config->sample_rate, - codec_config->bits_per_sample, codec_config->channel_mode); + INFO("got output codec config (update_stream_config=%s): " + "sample_rate=0x%x bits_per_sample=0x%x channel_mode=0x%x", + update_stream_config ? "true" : "false", codec_config->sample_rate, + codec_config->bits_per_sample, codec_config->channel_mode); - INFO( - "got output codec capability: sample_rate=0x%x bits_per_sample=0x%x " - "channel_mode=0x%x", - codec_capability->sample_rate, codec_capability->bits_per_sample, - codec_capability->channel_mode); + INFO("got output codec capability: sample_rate=0x%x bits_per_sample=0x%x channel_mode=0x%x", + codec_capability->sample_rate, codec_capability->bits_per_sample, + codec_capability->channel_mode); return 0; } @@ -746,23 +743,20 @@ static int ha_write_output_audio_config(struct ha_stream_common* common) { } // Send the current codec config that has been selected by us - if (ha_ctrl_send(common, &codec_config.sample_rate, - sizeof(btav_a2dp_codec_sample_rate_t)) < 0) + if (ha_ctrl_send(common, &codec_config.sample_rate, sizeof(btav_a2dp_codec_sample_rate_t)) < 0) { return -1; + } if (ha_ctrl_send(common, &codec_config.bits_per_sample, sizeof(btav_a2dp_codec_bits_per_sample_t)) < 0) { return -1; } - if (ha_ctrl_send(common, &codec_config.channel_mode, - sizeof(btav_a2dp_codec_channel_mode_t)) < 0) { + if (ha_ctrl_send(common, &codec_config.channel_mode, sizeof(btav_a2dp_codec_channel_mode_t)) < + 0) { return -1; } - INFO( - "sent output codec config: sample_rate=0x%x bits_per_sample=0x%x " - "channel_mode=0x%x", - codec_config.sample_rate, codec_config.bits_per_sample, - codec_config.channel_mode); + INFO("sent output codec config: sample_rate=0x%x bits_per_sample=0x%x channel_mode=0x%x", + codec_config.sample_rate, codec_config.bits_per_sample, codec_config.channel_mode); return 0; } @@ -770,16 +764,19 @@ static int ha_write_output_audio_config(struct ha_stream_common* common) { static void ha_open_ctrl_path(struct ha_stream_common* common) { int i; - if (common->ctrl_fd != AUDIO_SKT_DISCONNECTED) return; // already connected + if (common->ctrl_fd != AUDIO_SKT_DISCONNECTED) { + return; // already connected + } /* retry logic to catch any timing variations on control channel */ for (i = 0; i < CTRL_CHAN_RETRY_COUNT; i++) { /* connect control channel if not already connected */ - if ((common->ctrl_fd = skt_connect( - HEARING_AID_CTRL_PATH, AUDIO_STREAM_CONTROL_OUTPUT_BUFFER_SZ)) >= - 0) { + if ((common->ctrl_fd = + skt_connect(HEARING_AID_CTRL_PATH, AUDIO_STREAM_CONTROL_OUTPUT_BUFFER_SZ)) >= 0) { /* success, now check if stack is ready */ - if (check_ha_ready(common) == 0) break; + if (check_ha_ready(common) == 0) { + break; + } ERROR("error : ha not ready, wait 250 ms and retry"); usleep(250000); @@ -873,18 +870,22 @@ static int stop_audio_datapath(struct ha_stream_common* common) { return 0; } -static int suspend_audio_datapath(struct ha_stream_common* common, - bool standby) { +static int suspend_audio_datapath(struct ha_stream_common* common, bool standby) { INFO("state %d", common->state); - if (common->state == AUDIO_HA_STATE_STOPPING) return -1; + if (common->state == AUDIO_HA_STATE_STOPPING) { + return -1; + } - if (ha_command(common, HEARING_AID_CTRL_CMD_SUSPEND) < 0) return -1; + if (ha_command(common, HEARING_AID_CTRL_CMD_SUSPEND) < 0) { + return -1; + } - if (standby) + if (standby) { common->state = AUDIO_HA_STATE_STANDBY; - else + } else { common->state = AUDIO_HA_STATE_SUSPENDED; + } /* disconnect audio path */ skt_disconnect(common->audio_fd); @@ -900,8 +901,7 @@ static int suspend_audio_datapath(struct ha_stream_common* common, * ****************************************************************************/ -static ssize_t out_write(struct audio_stream_out* stream, const void* buffer, - size_t bytes) { +static ssize_t out_write(struct audio_stream_out* stream, const void* buffer, size_t bytes) { struct ha_stream_out* out = (struct ha_stream_out*)stream; int sent = -1; size_t write_bytes = bytes; @@ -935,8 +935,7 @@ static ssize_t out_write(struct audio_stream_out* stream, const void* buffer, *dst = (int16_t)(((int32_t)src[0] + (int32_t)src[1]) >> 1); } write_bytes /= 2; - DEBUG("stereo-to-mono mixing: write %zu bytes (fd %d)", write_bytes, - out->common.audio_fd); + DEBUG("stereo-to-mono mixing: write %zu bytes (fd %d)", write_bytes, out->common.audio_fd); } lock.unlock(); @@ -991,19 +990,17 @@ static int out_set_sample_rate(struct audio_stream* stream, uint32_t rate) { static size_t out_get_buffer_size(const struct audio_stream* stream) { struct ha_stream_out* out = (struct ha_stream_out*)stream; // period_size is the AudioFlinger mixer buffer size. - const size_t period_size = - out->common.buffer_sz / AUDIO_STREAM_OUTPUT_BUFFER_PERIODS; + const size_t period_size = out->common.buffer_sz / AUDIO_STREAM_OUTPUT_BUFFER_PERIODS; - DEBUG("socket buffer size: %zu period size: %zu", out->common.buffer_sz, - period_size); + DEBUG("socket buffer size: %zu period size: %zu", out->common.buffer_sz, period_size); return period_size; } size_t audio_ha_hw_stream_compute_buffer_size( - btav_a2dp_codec_sample_rate_t codec_sample_rate, - btav_a2dp_codec_bits_per_sample_t codec_bits_per_sample, - btav_a2dp_codec_channel_mode_t codec_channel_mode) { + btav_a2dp_codec_sample_rate_t codec_sample_rate, + btav_a2dp_codec_bits_per_sample_t codec_bits_per_sample, + btav_a2dp_codec_channel_mode_t codec_channel_mode) { size_t buffer_sz = AUDIO_STREAM_OUTPUT_BUFFER_SZ; // Default value const uint64_t time_period_ms = 20; // Conservative 20ms uint32_t sample_rate; @@ -1089,12 +1086,11 @@ size_t audio_ha_hw_stream_compute_buffer_size( // // Furthermore, the AudioFlinger expects the buffer size to be a multiple // of 16 frames. - const size_t divisor = (AUDIO_STREAM_OUTPUT_BUFFER_PERIODS * 16 * - number_of_channels * bits_per_sample) / - 8; + const size_t divisor = + (AUDIO_STREAM_OUTPUT_BUFFER_PERIODS * 16 * number_of_channels * bits_per_sample) / 8; - buffer_sz = (time_period_ms * AUDIO_STREAM_OUTPUT_BUFFER_PERIODS * - sample_rate * number_of_channels * (bits_per_sample / 8)) / + buffer_sz = (time_period_ms * AUDIO_STREAM_OUTPUT_BUFFER_PERIODS * sample_rate * + number_of_channels * (bits_per_sample / 8)) / 1000; // Adjust the buffer size so it can be divided by the divisor @@ -1106,8 +1102,7 @@ size_t audio_ha_hw_stream_compute_buffer_size( return buffer_sz; } -static audio_channel_mask_t out_get_channels( - const struct audio_stream* stream) { +static audio_channel_mask_t out_get_channels(const struct audio_stream* stream) { struct ha_stream_out* out = (struct ha_stream_out*)stream; DEBUG("channels 0x%" PRIx32, out->common.cfg.channel_mask); @@ -1135,30 +1130,31 @@ static int out_standby(struct audio_stream* stream) { std::lock_guard lock(*out->common.mutex); // Do nothing in SUSPENDED state. - if (out->common.state != AUDIO_HA_STATE_SUSPENDED) + if (out->common.state != AUDIO_HA_STATE_SUSPENDED) { retVal = suspend_audio_datapath(&out->common, true); + } out->frames_rendered = 0; // rendered is reset, presented is not return retVal; } -static int out_dump(UNUSED_ATTR const struct audio_stream* stream, - UNUSED_ATTR int fd) { +static int out_dump(UNUSED_ATTR const struct audio_stream* stream, UNUSED_ATTR int fd) { FNLOG(); return 0; } -static int out_set_parameters(struct audio_stream* stream, - const char* kvpairs) { +static int out_set_parameters(struct audio_stream* stream, const char* kvpairs) { struct ha_stream_out* out = (struct ha_stream_out*)stream; INFO("state %d kvpairs %s", out->common.state, kvpairs); std::unordered_map params = - hash_map_utils_new_from_string_params(kvpairs); + hash_map_utils_new_from_string_params(kvpairs); int status = 0; - if (params.empty()) return status; + if (params.empty()) { + return status; + } std::lock_guard lock(*out->common.mutex); @@ -1171,22 +1167,23 @@ static int out_set_parameters(struct audio_stream* stream, } if (params["HearingAidSuspended"].compare("true") == 0) { - if (out->common.state == AUDIO_HA_STATE_STARTED) + if (out->common.state == AUDIO_HA_STATE_STARTED) { status = suspend_audio_datapath(&out->common, false); + } } else { /* Do not start the streaming automatically. If the phone was streaming * prior to being suspended, the next out_write shall trigger the * AVDTP start procedure */ - if (out->common.state == AUDIO_HA_STATE_SUSPENDED) + if (out->common.state == AUDIO_HA_STATE_SUSPENDED) { out->common.state = AUDIO_HA_STATE_STANDBY; + } /* Irrespective of the state, return 0 */ } return status; } -static char* out_get_parameters(const struct audio_stream* stream, - const char* keys) { +static char* out_get_parameters(const struct audio_stream* stream, const char* keys) { FNLOG(); btav_a2dp_codec_config_t codec_config; @@ -1194,16 +1191,16 @@ static char* out_get_parameters(const struct audio_stream* stream, struct ha_stream_out* out = (struct ha_stream_out*)stream; - std::unordered_map params = - hash_map_utils_new_from_string_params(keys); + std::unordered_map params = hash_map_utils_new_from_string_params(keys); std::unordered_map return_params; - if (params.empty()) return strdup(""); + if (params.empty()) { + return strdup(""); + } std::lock_guard lock(*out->common.mutex); - if (ha_read_output_audio_config(&out->common, &codec_config, - &codec_capability, + if (ha_read_output_audio_config(&out->common, &codec_config, &codec_capability, false /* update_stream_config */) < 0) { ERROR("ha_read_output_audio_config failed"); goto done; @@ -1213,20 +1210,25 @@ static char* out_get_parameters(const struct audio_stream* stream, if (params.find(AUDIO_PARAMETER_STREAM_SUP_FORMATS) != params.end()) { std::string param; if (codec_capability.bits_per_sample & BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16) { - if (!param.empty()) param += "|"; + if (!param.empty()) { + param += "|"; + } param += "AUDIO_FORMAT_PCM_16_BIT"; } if (codec_capability.bits_per_sample & BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24) { - if (!param.empty()) param += "|"; + if (!param.empty()) { + param += "|"; + } param += "AUDIO_FORMAT_PCM_24_BIT_PACKED"; } if (codec_capability.bits_per_sample & BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32) { - if (!param.empty()) param += "|"; + if (!param.empty()) { + param += "|"; + } param += "AUDIO_FORMAT_PCM_32_BIT"; } if (param.empty()) { - ERROR("Invalid codec capability bits_per_sample=0x%x", - codec_capability.bits_per_sample); + ERROR("Invalid codec capability bits_per_sample=0x%x", codec_capability.bits_per_sample); goto done; } else { return_params[AUDIO_PARAMETER_STREAM_SUP_FORMATS] = param; @@ -1237,40 +1239,55 @@ static char* out_get_parameters(const struct audio_stream* stream, if (params.find(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES) != params.end()) { std::string param; if (codec_capability.sample_rate & BTAV_A2DP_CODEC_SAMPLE_RATE_44100) { - if (!param.empty()) param += "|"; + if (!param.empty()) { + param += "|"; + } param += "44100"; } if (codec_capability.sample_rate & BTAV_A2DP_CODEC_SAMPLE_RATE_48000) { - if (!param.empty()) param += "|"; + if (!param.empty()) { + param += "|"; + } param += "48000"; } if (codec_capability.sample_rate & BTAV_A2DP_CODEC_SAMPLE_RATE_88200) { - if (!param.empty()) param += "|"; + if (!param.empty()) { + param += "|"; + } param += "88200"; } if (codec_capability.sample_rate & BTAV_A2DP_CODEC_SAMPLE_RATE_96000) { - if (!param.empty()) param += "|"; + if (!param.empty()) { + param += "|"; + } param += "96000"; } if (codec_capability.sample_rate & BTAV_A2DP_CODEC_SAMPLE_RATE_176400) { - if (!param.empty()) param += "|"; + if (!param.empty()) { + param += "|"; + } param += "176400"; } if (codec_capability.sample_rate & BTAV_A2DP_CODEC_SAMPLE_RATE_192000) { - if (!param.empty()) param += "|"; + if (!param.empty()) { + param += "|"; + } param += "192000"; } if (codec_capability.sample_rate & BTAV_A2DP_CODEC_SAMPLE_RATE_16000) { - if (!param.empty()) param += "|"; + if (!param.empty()) { + param += "|"; + } param += "16000"; } if (codec_capability.sample_rate & BTAV_A2DP_CODEC_SAMPLE_RATE_24000) { - if (!param.empty()) param += "|"; + if (!param.empty()) { + param += "|"; + } param += "24000"; } if (param.empty()) { - ERROR("Invalid codec capability sample_rate=0x%x", - codec_capability.sample_rate); + ERROR("Invalid codec capability sample_rate=0x%x", codec_capability.sample_rate); goto done; } else { return_params[AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES] = param; @@ -1281,16 +1298,19 @@ static char* out_get_parameters(const struct audio_stream* stream, if (params.find(AUDIO_PARAMETER_STREAM_SUP_CHANNELS) != params.end()) { std::string param; if (codec_capability.channel_mode & BTAV_A2DP_CODEC_CHANNEL_MODE_MONO) { - if (!param.empty()) param += "|"; + if (!param.empty()) { + param += "|"; + } param += "AUDIO_CHANNEL_OUT_MONO"; } if (codec_capability.channel_mode & BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO) { - if (!param.empty()) param += "|"; + if (!param.empty()) { + param += "|"; + } param += "AUDIO_CHANNEL_OUT_STEREO"; } if (param.empty()) { - ERROR("Invalid codec capability channel_mode=0x%x", - codec_capability.channel_mode); + ERROR("Invalid codec capability channel_mode=0x%x", codec_capability.channel_mode); goto done; } else { return_params[AUDIO_PARAMETER_STREAM_SUP_CHANNELS] = param; @@ -1315,16 +1335,15 @@ static uint32_t out_get_latency(const struct audio_stream_out* stream) { FNLOG(); - latency_us = - ((out->common.buffer_sz * 1000) / - audio_stream_out_frame_size(&out->stream) / out->common.cfg.rate) * - 1000; + latency_us = ((out->common.buffer_sz * 1000) / audio_stream_out_frame_size(&out->stream) / + out->common.cfg.rate) * + 1000; return (latency_us / 1000) + 200; } -static int out_set_volume(UNUSED_ATTR struct audio_stream_out* stream, - UNUSED_ATTR float left, UNUSED_ATTR float right) { +static int out_set_volume(UNUSED_ATTR struct audio_stream_out* stream, UNUSED_ATTR float left, + UNUSED_ATTR float right) { FNLOG(); /* volume controlled in audioflinger mixer (digital) */ @@ -1332,18 +1351,18 @@ static int out_set_volume(UNUSED_ATTR struct audio_stream_out* stream, return -ENOSYS; } -static int out_get_presentation_position(const struct audio_stream_out* stream, - uint64_t* frames, +static int out_get_presentation_position(const struct audio_stream_out* stream, uint64_t* frames, struct timespec* timestamp) { struct ha_stream_out* out = (struct ha_stream_out*)stream; FNLOG(); - if (stream == NULL || frames == NULL || timestamp == NULL) return -EINVAL; + if (stream == NULL || frames == NULL || timestamp == NULL) { + return -EINVAL; + } int ret = -EWOULDBLOCK; std::lock_guard lock(*out->common.mutex); - uint64_t latency_frames = - (uint64_t)out_get_latency(stream) * out->common.cfg.rate / 1000; + uint64_t latency_frames = (uint64_t)out_get_latency(stream) * out->common.cfg.rate / 1000; if (out->frames_presented >= latency_frames) { *frames = out->frames_presented - latency_frames; clock_gettime(CLOCK_MONOTONIC, @@ -1353,16 +1372,16 @@ static int out_get_presentation_position(const struct audio_stream_out* stream, return ret; } -static int out_get_render_position(const struct audio_stream_out* stream, - uint32_t* dsp_frames) { +static int out_get_render_position(const struct audio_stream_out* stream, uint32_t* dsp_frames) { struct ha_stream_out* out = (struct ha_stream_out*)stream; FNLOG(); - if (stream == NULL || dsp_frames == NULL) return -EINVAL; + if (stream == NULL || dsp_frames == NULL) { + return -EINVAL; + } std::lock_guard lock(*out->common.mutex); - uint64_t latency_frames = - (uint64_t)out_get_latency(stream) * out->common.cfg.rate / 1000; + uint64_t latency_frames = (uint64_t)out_get_latency(stream) * out->common.cfg.rate / 1000; if (out->frames_rendered >= latency_frames) { *dsp_frames = (uint32_t)(out->frames_rendered - latency_frames); } else { @@ -1377,9 +1396,8 @@ static int out_add_audio_effect(UNUSED_ATTR const struct audio_stream* stream, return 0; } -static int out_remove_audio_effect( - UNUSED_ATTR const struct audio_stream* stream, - UNUSED_ATTR effect_handle_t effect) { +static int out_remove_audio_effect(UNUSED_ATTR const struct audio_stream* stream, + UNUSED_ATTR effect_handle_t effect) { FNLOG(); return 0; } @@ -1400,14 +1418,14 @@ static int in_set_sample_rate(struct audio_stream* stream, uint32_t rate) { FNLOG(); - if (in->common.cfg.rate > 0 && in->common.cfg.rate == rate) + if (in->common.cfg.rate > 0 && in->common.cfg.rate == rate) { return 0; - else + } else { return -1; + } } -static size_t in_get_buffer_size( - UNUSED_ATTR const struct audio_stream* stream) { +static size_t in_get_buffer_size(UNUSED_ATTR const struct audio_stream* stream) { FNLOG(); return 320; } @@ -1419,8 +1437,7 @@ static audio_channel_mask_t in_get_channels(const struct audio_stream* stream) { return (audio_channel_mask_t)in->common.cfg.channel_mask; } -static audio_format_t in_get_format( - UNUSED_ATTR const struct audio_stream* stream) { +static audio_format_t in_get_format(UNUSED_ATTR const struct audio_stream* stream) { FNLOG(); return AUDIO_FORMAT_PCM_16_BIT; } @@ -1428,10 +1445,11 @@ static audio_format_t in_get_format( static int in_set_format(UNUSED_ATTR struct audio_stream* stream, UNUSED_ATTR audio_format_t format) { FNLOG(); - if (format == AUDIO_FORMAT_PCM_16_BIT) + if (format == AUDIO_FORMAT_PCM_16_BIT) { return 0; - else + } else { return -1; + } } static int in_standby(UNUSED_ATTR struct audio_stream* stream) { @@ -1439,8 +1457,7 @@ static int in_standby(UNUSED_ATTR struct audio_stream* stream) { return 0; } -static int in_dump(UNUSED_ATTR const struct audio_stream* stream, - UNUSED_ATTR int fd) { +static int in_dump(UNUSED_ATTR const struct audio_stream* stream, UNUSED_ATTR int fd) { FNLOG(); return 0; } @@ -1457,14 +1474,12 @@ static char* in_get_parameters(UNUSED_ATTR const struct audio_stream* stream, return strdup(""); } -static int in_set_gain(UNUSED_ATTR struct audio_stream_in* stream, - UNUSED_ATTR float gain) { +static int in_set_gain(UNUSED_ATTR struct audio_stream_in* stream, UNUSED_ATTR float gain) { FNLOG(); return 0; } -static ssize_t in_read(struct audio_stream_in* stream, void* buffer, - size_t bytes) { +static ssize_t in_read(struct audio_stream_in* stream, void* buffer, size_t bytes) { struct ha_stream_in* in = (struct ha_stream_in*)stream; int read; int us_delay; @@ -1472,8 +1487,7 @@ static ssize_t in_read(struct audio_stream_in* stream, void* buffer, DEBUG("read %zu bytes, state: %d", bytes, in->common.state); std::unique_lock lock(*in->common.mutex); - if (in->common.state == AUDIO_HA_STATE_SUSPENDED || - in->common.state == AUDIO_HA_STATE_STOPPING) { + if (in->common.state == AUDIO_HA_STATE_SUSPENDED || in->common.state == AUDIO_HA_STATE_STOPPING) { DEBUG("stream suspended"); goto error; } @@ -1521,8 +1535,7 @@ error: return bytes; } -static uint32_t in_get_input_frames_lost( - UNUSED_ATTR struct audio_stream_in* stream) { +static uint32_t in_get_input_frames_lost(UNUSED_ATTR struct audio_stream_in* stream) { FNLOG(); return 0; } @@ -1558,7 +1571,9 @@ static int adev_open_output_stream(struct audio_hw_device* dev, std::lock_guard lock(*ha_dev->mutex); out = (struct ha_stream_out*)calloc(1, sizeof(struct ha_stream_out)); - if (!out) return -ENOMEM; + if (!out) { + return -ENOMEM; + } out->stream.common.get_sample_rate = out_get_sample_rate; out->stream.common.set_sample_rate = out_set_sample_rate; @@ -1584,8 +1599,7 @@ static int adev_open_output_stream(struct audio_hw_device* dev, // Make sure we always have the feeding parameters configured btav_a2dp_codec_config_t codec_config; btav_a2dp_codec_config_t codec_capability; - if (ha_read_output_audio_config(&out->common, &codec_config, - &codec_capability, + if (ha_read_output_audio_config(&out->common, &codec_config, &codec_capability, true /* update_stream_config */) < 0) { ERROR("ha_read_output_audio_config failed"); ret = -1; @@ -1597,10 +1611,15 @@ static int adev_open_output_stream(struct audio_hw_device* dev, if (config != nullptr) { // Try to use the config parameters and send it to the remote side // TODO: Shall we use out_set_format() and similar? - if (config->format != 0) out->common.cfg.format = config->format; - if (config->sample_rate != 0) out->common.cfg.rate = config->sample_rate; - if (config->channel_mask != 0) + if (config->format != 0) { + out->common.cfg.format = config->format; + } + if (config->sample_rate != 0) { + out->common.cfg.rate = config->sample_rate; + } + if (config->channel_mask != 0) { out->common.cfg.channel_mask = config->channel_mask; + } if ((out->common.cfg.format != 0) || (out->common.cfg.rate != 0) || (out->common.cfg.channel_mask != 0)) { if (ha_write_output_audio_config(&out->common) < 0) { @@ -1609,8 +1628,7 @@ static int adev_open_output_stream(struct audio_hw_device* dev, goto err_open; } // Read again and make sure we use the same parameters as the remote side - if (ha_read_output_audio_config(&out->common, &codec_config, - &codec_capability, + if (ha_read_output_audio_config(&out->common, &codec_config, &codec_capability, true /* update_stream_config */) < 0) { ERROR("ha_read_output_audio_config failed"); ret = -1; @@ -1618,16 +1636,11 @@ static int adev_open_output_stream(struct audio_hw_device* dev, } } config->format = out_get_format((const struct audio_stream*)&out->stream); - config->sample_rate = - out_get_sample_rate((const struct audio_stream*)&out->stream); - config->channel_mask = - out_get_channels((const struct audio_stream*)&out->stream); + config->sample_rate = out_get_sample_rate((const struct audio_stream*)&out->stream); + config->channel_mask = out_get_channels((const struct audio_stream*)&out->stream); - INFO( - "Output stream config: format=0x%x sample_rate=%d channel_mask=0x%x " - "buffer_sz=%zu", - config->format, config->sample_rate, config->channel_mask, - out->common.buffer_sz); + INFO("Output stream config: format=0x%x sample_rate=%d channel_mask=0x%x buffer_sz=%zu", + config->format, config->sample_rate, config->channel_mask, out->common.buffer_sz); } *stream_out = &out->stream; ha_dev->output = out; @@ -1647,8 +1660,7 @@ err_open: return ret; } -static void adev_close_output_stream(struct audio_hw_device* dev, - struct audio_stream_out* stream) { +static void adev_close_output_stream(struct audio_hw_device* dev, struct audio_stream_out* stream) { struct ha_audio_device* ha_dev = (struct ha_audio_device*)dev; struct ha_stream_out* out = (struct ha_stream_out*)stream; @@ -1658,8 +1670,7 @@ static void adev_close_output_stream(struct audio_hw_device* dev, std::lock_guard lock(*out->common.mutex); const ha_state_t state = out->common.state; INFO("closing output (state %d)", (int)state); - if ((state == AUDIO_HA_STATE_STARTED) || - (state == AUDIO_HA_STATE_STOPPING)) { + if ((state == AUDIO_HA_STATE_STARTED) || (state == AUDIO_HA_STATE_STOPPING)) { stop_audio_datapath(&out->common); } @@ -1674,8 +1685,7 @@ static void adev_close_output_stream(struct audio_hw_device* dev, DEBUG("done"); } -static int adev_set_parameters(struct audio_hw_device* dev, - const char* kvpairs) { +static int adev_set_parameters(struct audio_hw_device* dev, const char* kvpairs) { struct ha_audio_device* ha_dev = (struct ha_audio_device*)dev; int retval = 0; @@ -1683,22 +1693,21 @@ static int adev_set_parameters(struct audio_hw_device* dev, std::lock_guard lock(*ha_dev->mutex); struct ha_stream_out* out = ha_dev->output; - if (out == NULL) return retval; + if (out == NULL) { + return retval; + } INFO("state %d", out->common.state); - retval = - out->stream.common.set_parameters((struct audio_stream*)out, kvpairs); + retval = out->stream.common.set_parameters((struct audio_stream*)out, kvpairs); return retval; } -static char* adev_get_parameters(UNUSED_ATTR const struct audio_hw_device* dev, - const char* keys) { +static char* adev_get_parameters(UNUSED_ATTR const struct audio_hw_device* dev, const char* keys) { FNLOG(); - std::unordered_map params = - hash_map_utils_new_from_string_params(keys); + std::unordered_map params = hash_map_utils_new_from_string_params(keys); hash_map_utils_dump_string_keys_string_values(params); return strdup(""); @@ -1724,15 +1733,13 @@ static int adev_set_master_volume(UNUSED_ATTR struct audio_hw_device* dev, return -ENOSYS; } -static int adev_set_mode(UNUSED_ATTR struct audio_hw_device* dev, - UNUSED_ATTR audio_mode_t mode) { +static int adev_set_mode(UNUSED_ATTR struct audio_hw_device* dev, UNUSED_ATTR audio_mode_t mode) { FNLOG(); return 0; } -static int adev_set_mic_mute(UNUSED_ATTR struct audio_hw_device* dev, - UNUSED_ATTR bool state) { +static int adev_set_mic_mute(UNUSED_ATTR struct audio_hw_device* dev, UNUSED_ATTR bool state) { FNLOG(); return -ENOSYS; @@ -1745,16 +1752,14 @@ static int adev_get_mic_mute(UNUSED_ATTR const struct audio_hw_device* dev, return -ENOSYS; } -static size_t adev_get_input_buffer_size( - UNUSED_ATTR const struct audio_hw_device* dev, - UNUSED_ATTR const struct audio_config* config) { +static size_t adev_get_input_buffer_size(UNUSED_ATTR const struct audio_hw_device* dev, + UNUSED_ATTR const struct audio_config* config) { FNLOG(); return 320; } -static int adev_open_input_stream(struct audio_hw_device* dev, - UNUSED_ATTR audio_io_handle_t handle, +static int adev_open_input_stream(struct audio_hw_device* dev, UNUSED_ATTR audio_io_handle_t handle, UNUSED_ATTR audio_devices_t devices, UNUSED_ATTR struct audio_config* config, struct audio_stream_in** stream_in, @@ -1771,7 +1776,9 @@ static int adev_open_input_stream(struct audio_hw_device* dev, std::lock_guard lock(*ha_dev->mutex); in = (struct ha_stream_in*)calloc(1, sizeof(struct ha_stream_in)); - if (!in) return -ENOMEM; + if (!in) { + return -ENOMEM; + } in->stream.common.get_sample_rate = in_get_sample_rate; in->stream.common.set_sample_rate = in_set_sample_rate; @@ -1814,8 +1821,7 @@ err_open: return ret; } -static void adev_close_input_stream(struct audio_hw_device* dev, - struct audio_stream_in* stream) { +static void adev_close_input_stream(struct audio_hw_device* dev, struct audio_stream_in* stream) { struct ha_audio_device* ha_dev = (struct ha_audio_device*)dev; struct ha_stream_in* in = (struct ha_stream_in*)stream; @@ -1825,8 +1831,9 @@ static void adev_close_input_stream(struct audio_hw_device* dev, const ha_state_t state = in->common.state; INFO("closing input (state %d)", (int)state); - if ((state == AUDIO_HA_STATE_STARTED) || (state == AUDIO_HA_STATE_STOPPING)) + if ((state == AUDIO_HA_STATE_STARTED) || (state == AUDIO_HA_STATE_STOPPING)) { stop_audio_datapath(&in->common); + } skt_disconnect(in->common.ctrl_fd); in->common.ctrl_fd = AUDIO_SKT_DISCONNECTED; @@ -1838,8 +1845,7 @@ static void adev_close_input_stream(struct audio_hw_device* dev, DEBUG("done"); } -static int adev_dump(UNUSED_ATTR const audio_hw_device_t* device, - UNUSED_ATTR int fd) { +static int adev_dump(UNUSED_ATTR const audio_hw_device_t* device, UNUSED_ATTR int fd) { FNLOG(); return 0; @@ -1855,8 +1861,7 @@ static int adev_close(hw_device_t* device) { return 0; } -static int adev_open(const hw_module_t* module, const char* name, - hw_device_t** device) { +static int adev_open(const hw_module_t* module, const char* name, hw_device_t** device) { struct ha_audio_device* adev; INFO(" adev_open in ha_hw module"); @@ -1869,7 +1874,9 @@ static int adev_open(const hw_module_t* module, const char* name, adev = (struct ha_audio_device*)calloc(1, sizeof(struct ha_audio_device)); - if (!adev) return -ENOMEM; + if (!adev) { + return -ENOMEM; + } adev->mutex = new std::recursive_mutex; @@ -1901,19 +1908,18 @@ static int adev_open(const hw_module_t* module, const char* name, } static struct hw_module_methods_t hal_module_methods = { - .open = adev_open, + .open = adev_open, }; -__attribute__(( - visibility("default"))) struct audio_module HAL_MODULE_INFO_SYM = { - .common = - { - .tag = HARDWARE_MODULE_TAG, - .version_major = 1, - .version_minor = 0, - .id = AUDIO_HARDWARE_MODULE_ID, - .name = "Hearing Aid Audio HW HAL", - .author = "The Android Open Source Project", - .methods = &hal_module_methods, - }, +__attribute__((visibility("default"))) struct audio_module HAL_MODULE_INFO_SYM = { + .common = + { + .tag = HARDWARE_MODULE_TAG, + .version_major = 1, + .version_minor = 0, + .id = AUDIO_HARDWARE_MODULE_ID, + .name = "Hearing Aid Audio HW HAL", + .author = "The Android Open Source Project", + .methods = &hal_module_methods, + }, }; diff --git a/system/audio_hearing_aid_hw/test/audio_hearing_aid_hw_test.cc b/system/audio_hearing_aid_hw/test/audio_hearing_aid_hw_test.cc index c5d0e2b4e5a..69bcfbc6419 100644 --- a/system/audio_hearing_aid_hw/test/audio_hearing_aid_hw_test.cc +++ b/system/audio_hearing_aid_hw/test/audio_hearing_aid_hw_test.cc @@ -16,13 +16,12 @@ * ******************************************************************************/ -#include - #include "audio_hearing_aid_hw/include/audio_hearing_aid_hw.h" +#include + namespace { -static uint32_t codec_sample_rate2value( - btav_a2dp_codec_sample_rate_t codec_sample_rate) { +static uint32_t codec_sample_rate2value(btav_a2dp_codec_sample_rate_t codec_sample_rate) { switch (codec_sample_rate) { case BTAV_A2DP_CODEC_SAMPLE_RATE_44100: return 44100; @@ -47,7 +46,7 @@ static uint32_t codec_sample_rate2value( } static uint32_t codec_bits_per_sample2value( - btav_a2dp_codec_bits_per_sample_t codec_bits_per_sample) { + btav_a2dp_codec_bits_per_sample_t codec_bits_per_sample) { switch (codec_bits_per_sample) { case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16: return 16; @@ -61,8 +60,7 @@ static uint32_t codec_bits_per_sample2value( return 0; } -static uint32_t codec_channel_mode2value( - btav_a2dp_codec_channel_mode_t codec_channel_mode) { +static uint32_t codec_channel_mode2value(btav_a2dp_codec_channel_mode_t codec_channel_mode) { switch (codec_channel_mode) { case BTAV_A2DP_CODEC_CHANNEL_MODE_MONO: return 1; @@ -77,63 +75,59 @@ static uint32_t codec_channel_mode2value( } // namespace class AudioA2dpHwTest : public ::testing::Test { - protected: +protected: AudioA2dpHwTest() {} - private: +private: }; TEST_F(AudioA2dpHwTest, test_compute_buffer_size) { const btav_a2dp_codec_sample_rate_t codec_sample_rate_array[] = { - BTAV_A2DP_CODEC_SAMPLE_RATE_NONE, BTAV_A2DP_CODEC_SAMPLE_RATE_44100, - BTAV_A2DP_CODEC_SAMPLE_RATE_48000, BTAV_A2DP_CODEC_SAMPLE_RATE_88200, - BTAV_A2DP_CODEC_SAMPLE_RATE_96000, BTAV_A2DP_CODEC_SAMPLE_RATE_176400, - BTAV_A2DP_CODEC_SAMPLE_RATE_192000}; + BTAV_A2DP_CODEC_SAMPLE_RATE_NONE, BTAV_A2DP_CODEC_SAMPLE_RATE_44100, + BTAV_A2DP_CODEC_SAMPLE_RATE_48000, BTAV_A2DP_CODEC_SAMPLE_RATE_88200, + BTAV_A2DP_CODEC_SAMPLE_RATE_96000, BTAV_A2DP_CODEC_SAMPLE_RATE_176400, + BTAV_A2DP_CODEC_SAMPLE_RATE_192000}; const btav_a2dp_codec_bits_per_sample_t codec_bits_per_sample_array[] = { - BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE, BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16, - BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24, BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32}; + BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE, BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16, + BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24, BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32}; const btav_a2dp_codec_channel_mode_t codec_channel_mode_array[] = { - BTAV_A2DP_CODEC_CHANNEL_MODE_NONE, BTAV_A2DP_CODEC_CHANNEL_MODE_MONO, - BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO}; + BTAV_A2DP_CODEC_CHANNEL_MODE_NONE, BTAV_A2DP_CODEC_CHANNEL_MODE_MONO, + BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO}; for (const auto codec_sample_rate : codec_sample_rate_array) { for (const auto codec_bits_per_sample : codec_bits_per_sample_array) { for (const auto codec_channel_mode : codec_channel_mode_array) { size_t buffer_size = audio_ha_hw_stream_compute_buffer_size( - codec_sample_rate, codec_bits_per_sample, codec_channel_mode); + codec_sample_rate, codec_bits_per_sample, codec_channel_mode); // Check for invalid input if ((codec_sample_rate == BTAV_A2DP_CODEC_SAMPLE_RATE_NONE) || (codec_bits_per_sample == BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE) || (codec_channel_mode == BTAV_A2DP_CODEC_CHANNEL_MODE_NONE)) { - EXPECT_EQ(buffer_size, - static_cast(AUDIO_STREAM_OUTPUT_BUFFER_SZ)); + EXPECT_EQ(buffer_size, static_cast(AUDIO_STREAM_OUTPUT_BUFFER_SZ)); continue; } uint32_t sample_rate = codec_sample_rate2value(codec_sample_rate); EXPECT_TRUE(sample_rate != 0); - uint32_t bits_per_sample = - codec_bits_per_sample2value(codec_bits_per_sample); + uint32_t bits_per_sample = codec_bits_per_sample2value(codec_bits_per_sample); EXPECT_TRUE(bits_per_sample != 0); - uint32_t number_of_channels = - codec_channel_mode2value(codec_channel_mode); + uint32_t number_of_channels = codec_channel_mode2value(codec_channel_mode); EXPECT_TRUE(number_of_channels != 0); const uint64_t time_period_ms = 20; // TODO: Must be a parameter - size_t expected_buffer_size = - (time_period_ms * AUDIO_STREAM_OUTPUT_BUFFER_PERIODS * sample_rate * - number_of_channels * (bits_per_sample / 8)) / - 1000; + size_t expected_buffer_size = (time_period_ms * AUDIO_STREAM_OUTPUT_BUFFER_PERIODS * + sample_rate * number_of_channels * (bits_per_sample / 8)) / + 1000; // Compute the divisor and adjust the buffer size - const size_t divisor = (AUDIO_STREAM_OUTPUT_BUFFER_PERIODS * 16 * - number_of_channels * bits_per_sample) / - 8; + const size_t divisor = + (AUDIO_STREAM_OUTPUT_BUFFER_PERIODS * 16 * number_of_channels * bits_per_sample) / + 8; const size_t remainder = expected_buffer_size % divisor; if (remainder != 0) { expected_buffer_size += divisor - remainder; diff --git a/system/bta/ag/bta_ag_act.cc b/system/bta/ag/bta_ag_act.cc index d6f2675c07b..56db4af02cd 100644 --- a/system/bta/ag/bta_ag_act.cc +++ b/system/bta/ag/bta_ag_act.cc @@ -61,24 +61,22 @@ using namespace bluetooth::legacy::stack::sdp; /* maximum AT command length */ #define BTA_AG_CMD_MAX 512 -const uint16_t bta_ag_uuid[BTA_AG_NUM_IDX] = { - UUID_SERVCLASS_HEADSET_AUDIO_GATEWAY, UUID_SERVCLASS_AG_HANDSFREE}; +const uint16_t bta_ag_uuid[BTA_AG_NUM_IDX] = {UUID_SERVCLASS_HEADSET_AUDIO_GATEWAY, + UUID_SERVCLASS_AG_HANDSFREE}; const uint8_t bta_ag_sec_id[BTA_AG_NUM_IDX] = {BTM_SEC_SERVICE_HEADSET_AG, BTM_SEC_SERVICE_AG_HANDSFREE}; -const tBTA_SERVICE_ID bta_ag_svc_id[BTA_AG_NUM_IDX] = {BTA_HSP_SERVICE_ID, - BTA_HFP_SERVICE_ID}; +const tBTA_SERVICE_ID bta_ag_svc_id[BTA_AG_NUM_IDX] = {BTA_HSP_SERVICE_ID, BTA_HFP_SERVICE_ID}; -const tBTA_SERVICE_MASK bta_ag_svc_mask[BTA_AG_NUM_IDX] = { - BTA_HSP_SERVICE_MASK, BTA_HFP_SERVICE_MASK}; +const tBTA_SERVICE_MASK bta_ag_svc_mask[BTA_AG_NUM_IDX] = {BTA_HSP_SERVICE_MASK, + BTA_HFP_SERVICE_MASK}; -typedef void (*tBTA_AG_ATCMD_CBACK)(tBTA_AG_SCB* p_scb, uint16_t cmd, - uint8_t arg_type, char* p_arg, char* p_end, - int16_t int_arg); +typedef void (*tBTA_AG_ATCMD_CBACK)(tBTA_AG_SCB* p_scb, uint16_t cmd, uint8_t arg_type, char* p_arg, + char* p_end, int16_t int_arg); -const tBTA_AG_ATCMD_CBACK bta_ag_at_cback_tbl[BTA_AG_NUM_IDX] = { - bta_ag_at_hsp_cback, bta_ag_at_hfp_cback}; +const tBTA_AG_ATCMD_CBACK bta_ag_at_cback_tbl[BTA_AG_NUM_IDX] = {bta_ag_at_hsp_cback, + bta_ag_at_hfp_cback}; /******************************************************************************* * @@ -229,8 +227,7 @@ void bta_ag_disc_int_res(tBTA_AG_SCB* p_scb, const tBTA_AG_DATA& data) { log::verbose("bta_ag_disc_int_res: Status: {}", data.disc_result.status); /* if found service */ - if (data.disc_result.status == SDP_SUCCESS || - data.disc_result.status == SDP_DB_FULL) { + if (data.disc_result.status == SDP_SUCCESS || data.disc_result.status == SDP_DB_FULL) { /* get attributes */ if (bta_ag_sdp_find_attr(p_scb, p_scb->open_services)) { /* set connected service */ @@ -239,9 +236,8 @@ void bta_ag_disc_int_res(tBTA_AG_SCB* p_scb, const tBTA_AG_DATA& data) { /* send ourselves sdp ok event */ event = BTA_AG_DISC_OK_EVT; - DEVICE_IOT_CONFIG_ADDR_SET_HEX_IF_GREATER( - p_scb->peer_addr, IOT_CONF_KEY_HFP_VERSION, p_scb->peer_version, - IOT_CONF_BYTE_NUM_2); + DEVICE_IOT_CONFIG_ADDR_SET_HEX_IF_GREATER(p_scb->peer_addr, IOT_CONF_KEY_HFP_VERSION, + p_scb->peer_version, IOT_CONF_BYTE_NUM_2); } } @@ -250,8 +246,7 @@ void bta_ag_disc_int_res(tBTA_AG_SCB* p_scb, const tBTA_AG_DATA& data) { /* if service not found check if we should search for other service */ if ((event == BTA_AG_DISC_FAIL_EVT) && - (data.disc_result.status == SDP_SUCCESS || - data.disc_result.status == SDP_DB_FULL || + (data.disc_result.status == SDP_SUCCESS || data.disc_result.status == SDP_DB_FULL || data.disc_result.status == SDP_NO_RECS_MATCH)) { if ((p_scb->open_services & BTA_HFP_SERVICE_MASK) && (p_scb->open_services & BTA_HSP_SERVICE_MASK)) { @@ -285,13 +280,11 @@ void bta_ag_disc_int_res(tBTA_AG_SCB* p_scb, const tBTA_AG_DATA& data) { ******************************************************************************/ void bta_ag_disc_acp_res(tBTA_AG_SCB* p_scb, const tBTA_AG_DATA& data) { /* if found service */ - if (data.disc_result.status == SDP_SUCCESS || - data.disc_result.status == SDP_DB_FULL) { + if (data.disc_result.status == SDP_SUCCESS || data.disc_result.status == SDP_DB_FULL) { /* get attributes */ bta_ag_sdp_find_attr(p_scb, bta_ag_svc_mask[p_scb->conn_service]); - DEVICE_IOT_CONFIG_ADDR_SET_HEX_IF_GREATER( - p_scb->peer_addr, IOT_CONF_KEY_HFP_VERSION, p_scb->peer_version, - IOT_CONF_BYTE_NUM_2); + DEVICE_IOT_CONFIG_ADDR_SET_HEX_IF_GREATER(p_scb->peer_addr, IOT_CONF_KEY_HFP_VERSION, + p_scb->peer_version, IOT_CONF_BYTE_NUM_2); } /* free discovery db */ @@ -442,8 +435,9 @@ void bta_ag_rfc_close(tBTA_AG_SCB* p_scb, const tBTA_AG_DATA& /* data */) { /* start only unopened server */ services = p_scb->reg_services; for (i = 0; i < BTA_AG_NUM_IDX && services != 0; i++) { - if (p_scb->serv_handle[i]) + if (p_scb->serv_handle[i]) { services &= ~((tBTA_SERVICE_MASK)1 << (BTA_HSP_SERVICE_ID + i)); + } } bta_ag_start_servers(p_scb, services); @@ -454,20 +448,20 @@ void bta_ag_rfc_close(tBTA_AG_SCB* p_scb, const tBTA_AG_DATA& /* data */) { /* Check if all the SLCs are down */ for (i = 0; i < BTA_AG_MAX_NUM_CLIENTS; i++) { - if (bta_ag_cb.scb[i].in_use && bta_ag_cb.scb[i].svc_conn) + if (bta_ag_cb.scb[i].in_use && bta_ag_cb.scb[i].svc_conn) { num_active_conn++; + } } if (!num_active_conn) { bta_sys_sco_unuse(BTA_ID_AG, p_scb->app_id, p_scb->peer_addr); } - } - /* else close port and deallocate scb */ - else { + /* else close port and deallocate scb */ + } else { if (RFCOMM_RemoveServer(p_scb->conn_handle) != PORT_SUCCESS) { - log::warn("Unable to remove RFCOMM server peer:{} handle:{}", - p_scb->peer_addr, p_scb->conn_handle); + log::warn("Unable to remove RFCOMM server peer:{} handle:{}", p_scb->peer_addr, + p_scb->conn_handle); }; bta_ag_scb_dealloc(p_scb); } @@ -489,20 +483,17 @@ void bta_ag_rfc_open(tBTA_AG_SCB* p_scb, const tBTA_AG_DATA& data) { p_scb->ccwa_enabled = false; p_scb->cmer_enabled = false; p_scb->cmee_enabled = false; - p_scb->inband_enabled = - ((p_scb->features & BTA_AG_FEAT_INBAND) == BTA_AG_FEAT_INBAND); + p_scb->inband_enabled = ((p_scb->features & BTA_AG_FEAT_INBAND) == BTA_AG_FEAT_INBAND); if (p_scb->conn_service == BTA_AG_HFP) { size_t version_value_size = sizeof(p_scb->peer_version); - if (!btif_config_get_bin( - p_scb->peer_addr.ToString(), BTIF_STORAGE_KEY_HFP_VERSION, - (uint8_t*)&p_scb->peer_version, &version_value_size)) { + if (!btif_config_get_bin(p_scb->peer_addr.ToString(), BTIF_STORAGE_KEY_HFP_VERSION, + (uint8_t*)&p_scb->peer_version, &version_value_size)) { log::warn("Failed read cached peer HFP version for {}", p_scb->peer_addr); p_scb->peer_version = HFP_HSP_VERSION_UNKNOWN; } size_t sdp_features_size = sizeof(p_scb->peer_sdp_features); - if (btif_config_get_bin( - p_scb->peer_addr.ToString(), BTIF_STORAGE_KEY_HFP_SDP_FEATURES, - (uint8_t*)&p_scb->peer_sdp_features, &sdp_features_size)) { + if (btif_config_get_bin(p_scb->peer_addr.ToString(), BTIF_STORAGE_KEY_HFP_SDP_FEATURES, + (uint8_t*)&p_scb->peer_sdp_features, &sdp_features_size)) { bool sdp_wbs_support = p_scb->peer_sdp_features & BTA_AG_FEAT_WBS_SUPPORT; if (!p_scb->received_at_bac && sdp_wbs_support) { p_scb->codec_updated = true; @@ -516,8 +507,7 @@ void bta_ag_rfc_open(tBTA_AG_SCB* p_scb, const tBTA_AG_DATA& data) { p_scb->sco_codec = BTM_SCO_CODEC_LC3; } } else { - log::warn("Failed read cached peer HFP SDP features for {}", - p_scb->peer_addr); + log::warn("Failed read cached peer HFP SDP features for {}", p_scb->peer_addr); } } @@ -535,8 +525,8 @@ void bta_ag_rfc_open(tBTA_AG_SCB* p_scb, const tBTA_AG_DATA& data) { if (p_scb->conn_service == BTA_AG_HFP) { /* if hfp start timer for service level conn */ - bta_sys_start_timer(p_scb->ring_timer, p_bta_ag_cfg->conn_tout, - BTA_AG_SVC_TIMEOUT_EVT, bta_ag_scb_to_idx(p_scb)); + bta_sys_start_timer(p_scb->ring_timer, p_bta_ag_cfg->conn_tout, BTA_AG_SVC_TIMEOUT_EVT, + bta_ag_scb_to_idx(p_scb)); } else { /* else service level conn is open */ bta_ag_svc_conn_open(p_scb, data); @@ -554,8 +544,7 @@ void bta_ag_rfc_open(tBTA_AG_SCB* p_scb, const tBTA_AG_DATA& data) { * ******************************************************************************/ void bta_ag_rfc_acp_open(tBTA_AG_SCB* p_scb, const tBTA_AG_DATA& data) { - log::verbose("serv_handle0 = {} serv_handle = {}", p_scb->serv_handle[0], - p_scb->serv_handle[1]); + log::verbose("serv_handle0 = {} serv_handle = {}", p_scb->serv_handle[0], p_scb->serv_handle[1]); /* set role */ p_scb->role = BTA_AG_ACP; @@ -581,18 +570,16 @@ void bta_ag_rfc_acp_open(tBTA_AG_SCB* p_scb, const tBTA_AG_DATA& data) { } } if (dev_addr == ag_scb.peer_addr && p_scb != &ag_scb) { - log::info( - "close outgoing connection before accepting {} with conn_handle={}", - ag_scb.peer_addr, ag_scb.conn_handle); + log::info("close outgoing connection before accepting {} with conn_handle={}", + ag_scb.peer_addr, ag_scb.conn_handle); // If client port is opened, close it, state machine will handle rfcomm // closed in opening state as failure and pass to upper layer if (ag_scb.conn_handle > 0) { status = RFCOMM_RemoveConnection(ag_scb.conn_handle); if (status != PORT_SUCCESS) { - log::warn( - "RFCOMM_RemoveConnection failed for {}, handle {}, error {}", - dev_addr, ag_scb.conn_handle, status); + log::warn("RFCOMM_RemoveConnection failed for {}, handle {}, error {}", dev_addr, + ag_scb.conn_handle, status); } } else if (com::android::bluetooth::flags::reset_after_collision()) { // As no existing outgoing rfcomm connection, then manual reset current @@ -600,17 +587,16 @@ void bta_ag_rfc_acp_open(tBTA_AG_SCB* p_scb, const tBTA_AG_DATA& data) { bta_ag_rfc_fail(&ag_scb, tBTA_AG_DATA::kEmpty); } } - log::info("dev_addr={}, peer_addr={}, in_use={}, index={}", dev_addr, - ag_scb.peer_addr, ag_scb.in_use, bta_ag_scb_to_idx(p_scb)); + log::info("dev_addr={}, peer_addr={}, in_use={}, index={}", dev_addr, ag_scb.peer_addr, + ag_scb.in_use, bta_ag_scb_to_idx(p_scb)); } p_scb->peer_addr = dev_addr; /* determine connected service from port handle */ for (uint8_t i = 0; i < BTA_AG_NUM_IDX; i++) { - log::verbose( - "bta_ag_rfc_acp_open: i = {} serv_handle = {} port_handle = {}", i, - p_scb->serv_handle[i], data.rfc.port_handle); + log::verbose("bta_ag_rfc_acp_open: i = {} serv_handle = {} port_handle = {}", i, + p_scb->serv_handle[i], data.rfc.port_handle); if (p_scb->serv_handle[i] == data.rfc.port_handle) { p_scb->conn_service = i; @@ -619,21 +605,18 @@ void bta_ag_rfc_acp_open(tBTA_AG_SCB* p_scb, const tBTA_AG_DATA& data) { } } - log::verbose("bta_ag_rfc_acp_open: conn_service = {} conn_handle = {}", - p_scb->conn_service, p_scb->conn_handle); + log::verbose("bta_ag_rfc_acp_open: conn_service = {} conn_handle = {}", p_scb->conn_service, + p_scb->conn_handle); /* close any unopened server */ - bta_ag_close_servers( - p_scb, (p_scb->reg_services & ~bta_ag_svc_mask[p_scb->conn_service])); + bta_ag_close_servers(p_scb, (p_scb->reg_services & ~bta_ag_svc_mask[p_scb->conn_service])); size_t version_value_size = sizeof(hfp_version); - bool get_version = btif_config_get_bin( - p_scb->peer_addr.ToString(), BTIF_STORAGE_KEY_HFP_VERSION, - (uint8_t*)&hfp_version, &version_value_size); + bool get_version = btif_config_get_bin(p_scb->peer_addr.ToString(), BTIF_STORAGE_KEY_HFP_VERSION, + (uint8_t*)&hfp_version, &version_value_size); if (p_scb->conn_service == BTA_AG_HFP && get_version) { - DEVICE_IOT_CONFIG_ADDR_SET_HEX_IF_GREATER(p_scb->peer_addr, - IOT_CONF_KEY_HFP_VERSION, + DEVICE_IOT_CONFIG_ADDR_SET_HEX_IF_GREATER(p_scb->peer_addr, IOT_CONF_KEY_HFP_VERSION, hfp_version, IOT_CONF_BYTE_NUM_2); } /* do service discovery to get features */ @@ -662,8 +645,7 @@ void bta_ag_rfc_data(tBTA_AG_SCB* p_scb, const tBTA_AG_DATA& /* data */) { /* do the following */ for (;;) { /* read data from rfcomm; if bad status, we're done */ - if (PORT_ReadData(p_scb->conn_handle, buf, BTA_AG_RFC_READ_MAX, &len) != - PORT_SUCCESS) { + if (PORT_ReadData(p_scb->conn_handle, buf, BTA_AG_RFC_READ_MAX, &len) != PORT_SUCCESS) { log::error("failed to read data {}", p_scb->peer_addr); break; } @@ -677,8 +659,7 @@ void bta_ag_rfc_data(tBTA_AG_SCB* p_scb, const tBTA_AG_DATA& /* data */) { /* run AT command interpreter on data */ bta_sys_busy(BTA_ID_AG, p_scb->app_id, p_scb->peer_addr); bta_ag_at_parse(&p_scb->at_cb, buf, len); - if ((p_scb->sco_idx != BTM_INVALID_SCO_INDEX) && - bta_ag_sco_is_open(p_scb)) { + if ((p_scb->sco_idx != BTM_INVALID_SCO_INDEX) && bta_ag_sco_is_open(p_scb)) { log::verbose("change link policy for SCO"); bta_sys_sco_open(BTA_ID_AG, p_scb->app_id, p_scb->peer_addr); } else { @@ -783,14 +764,12 @@ void bta_ag_post_sco_close(tBTA_AG_SCB* p_scb, const tBTA_AG_DATA& data) { case BTA_AG_POST_SCO_CALL_END_INCALL: bta_ag_send_call_inds(p_scb, BTA_AG_END_CALL_RES); - /* Sending callsetup IND and Ring were defered to after SCO close. */ + /* Sending callsetup IND and Ring were deferred to after SCO close. */ bta_ag_send_call_inds(p_scb, BTA_AG_IN_CALL_RES); - if (bta_ag_inband_enabled(p_scb) && - !(p_scb->features & BTA_AG_FEAT_NOSCO)) { + if (bta_ag_inband_enabled(p_scb) && !(p_scb->features & BTA_AG_FEAT_NOSCO)) { p_scb->post_sco = BTA_AG_POST_SCO_RING; - if (!bta_ag_is_sco_open_allowed(p_scb, - "BTA_AG_POST_SCO_CALL_END_INCALL")) { + if (!bta_ag_is_sco_open_allowed(p_scb, "BTA_AG_POST_SCO_CALL_END_INCALL")) { break; } if (bta_ag_is_sco_managed_by_audio()) { @@ -862,17 +841,15 @@ void bta_ag_svc_conn_open(tBTA_AG_SCB* p_scb, const tBTA_AG_DATA& /* data */) { void bta_ag_setcodec(tBTA_AG_SCB* p_scb, const tBTA_AG_DATA& data) { tBTA_AG_PEER_CODEC codec_type = data.api_setcodec.codec; tBTA_AG_VAL val = {}; - const bool aptx_voice = is_hfp_aptx_voice_enabled() && - (codec_type == BTA_AG_SCO_APTX_SWB_SETTINGS_Q0); + const bool aptx_voice = + is_hfp_aptx_voice_enabled() && (codec_type == BTA_AG_SCO_APTX_SWB_SETTINGS_Q0); log::verbose("aptx_voice={}, codec_type={:#x}", aptx_voice, codec_type); val.hdr.handle = bta_ag_scb_to_idx(p_scb); /* Check if the requested codec type is valid */ - if ((codec_type != BTM_SCO_CODEC_NONE) && - (codec_type != BTM_SCO_CODEC_CVSD) && - (codec_type != BTM_SCO_CODEC_MSBC) && (codec_type != BTM_SCO_CODEC_LC3) && - !aptx_voice) { + if ((codec_type != BTM_SCO_CODEC_NONE) && (codec_type != BTM_SCO_CODEC_CVSD) && + (codec_type != BTM_SCO_CODEC_MSBC) && (codec_type != BTM_SCO_CODEC_LC3) && !aptx_voice) { val.num = codec_type; val.hdr.status = BTA_AG_FAIL_RESOURCES; log::error("bta_ag_setcodec error: unsupported codec type {}", codec_type); @@ -906,14 +883,11 @@ static void bta_ag_collision_timer_cback(void* data) { bta_ag_resume_open(static_cast(data)); } -void bta_ag_handle_collision(tBTA_AG_SCB* p_scb, - const tBTA_AG_DATA& /* data */) { +void bta_ag_handle_collision(tBTA_AG_SCB* p_scb, const tBTA_AG_DATA& /* data */) { /* Cancel SDP if it had been started. */ if (p_scb->p_disc_db) { - if (!get_legacy_stack_sdp_api()->service.SDP_CancelServiceSearch( - p_scb->p_disc_db)) { - log::warn("Unable to cancel SDP service discovery search peer:{}", - p_scb->peer_addr); + if (!get_legacy_stack_sdp_api()->service.SDP_CancelServiceSearch(p_scb->p_disc_db)) { + log::warn("Unable to cancel SDP service discovery search peer:{}", p_scb->peer_addr); } bta_ag_free_db(p_scb, tBTA_AG_DATA::kEmpty); } diff --git a/system/bta/ag/bta_ag_api.cc b/system/bta/ag/bta_ag_api.cc index 7db4adf9a72..9d3dcd16dad 100644 --- a/system/bta/ag/bta_ag_api.cc +++ b/system/bta/ag/bta_ag_api.cc @@ -83,9 +83,7 @@ tBTA_STATUS BTA_AgEnable(tBTA_AG_CBACK* p_cback) { * Returns void * ******************************************************************************/ -void BTA_AgDisable() { - do_in_main_thread(FROM_HERE, base::BindOnce(&bta_ag_api_disable)); -} +void BTA_AgDisable() { do_in_main_thread(FROM_HERE, base::BindOnce(&bta_ag_api_disable)); } /******************************************************************************* * @@ -98,10 +96,9 @@ void BTA_AgDisable() { * ******************************************************************************/ void BTA_AgRegister(tBTA_SERVICE_MASK services, tBTA_AG_FEAT features, - const std::vector& service_names, - uint8_t app_id) { - do_in_main_thread(FROM_HERE, base::BindOnce(&bta_ag_api_register, services, - features, service_names, app_id)); + const std::vector& service_names, uint8_t app_id) { + do_in_main_thread(FROM_HERE, base::BindOnce(&bta_ag_api_register, services, features, + service_names, app_id)); } /******************************************************************************* @@ -115,9 +112,8 @@ void BTA_AgRegister(tBTA_SERVICE_MASK services, tBTA_AG_FEAT features, * ******************************************************************************/ void BTA_AgDeregister(uint16_t handle) { - do_in_main_thread(FROM_HERE, base::BindOnce(&bta_ag_sm_execute_by_handle, - handle, BTA_AG_API_DEREGISTER_EVT, - tBTA_AG_DATA::kEmpty)); + do_in_main_thread(FROM_HERE, base::BindOnce(&bta_ag_sm_execute_by_handle, handle, + BTA_AG_API_DEREGISTER_EVT, tBTA_AG_DATA::kEmpty)); } /******************************************************************************* @@ -136,9 +132,8 @@ void BTA_AgDeregister(uint16_t handle) { void BTA_AgOpen(uint16_t handle, const RawAddress& bd_addr) { tBTA_AG_DATA data = {}; data.api_open.bd_addr = bd_addr; - do_in_main_thread(FROM_HERE, - base::BindOnce(&bta_ag_sm_execute_by_handle, handle, - BTA_AG_API_OPEN_EVT, data)); + do_in_main_thread(FROM_HERE, base::BindOnce(&bta_ag_sm_execute_by_handle, handle, + BTA_AG_API_OPEN_EVT, data)); } /******************************************************************************* @@ -153,9 +148,8 @@ void BTA_AgOpen(uint16_t handle, const RawAddress& bd_addr) { * ******************************************************************************/ void BTA_AgClose(uint16_t handle) { - do_in_main_thread(FROM_HERE, - base::BindOnce(&bta_ag_sm_execute_by_handle, handle, - BTA_AG_API_CLOSE_EVT, tBTA_AG_DATA::kEmpty)); + do_in_main_thread(FROM_HERE, base::BindOnce(&bta_ag_sm_execute_by_handle, handle, + BTA_AG_API_CLOSE_EVT, tBTA_AG_DATA::kEmpty)); } /******************************************************************************* @@ -175,9 +169,8 @@ void BTA_AgClose(uint16_t handle) { void BTA_AgAudioOpen(uint16_t handle, tBTA_AG_PEER_CODEC disabled_codecs) { tBTA_AG_DATA data = {}; data.api_audio_open.disabled_codecs = disabled_codecs; - do_in_main_thread(FROM_HERE, - base::BindOnce(&bta_ag_sm_execute_by_handle, handle, - BTA_AG_API_AUDIO_OPEN_EVT, data)); + do_in_main_thread(FROM_HERE, base::BindOnce(&bta_ag_sm_execute_by_handle, handle, + BTA_AG_API_AUDIO_OPEN_EVT, data)); } /******************************************************************************* @@ -192,10 +185,8 @@ void BTA_AgAudioOpen(uint16_t handle, tBTA_AG_PEER_CODEC disabled_codecs) { * ******************************************************************************/ void BTA_AgAudioClose(uint16_t handle) { - do_in_main_thread( - FROM_HERE, - base::BindOnce(&bta_ag_sm_execute_by_handle, handle, - BTA_AG_API_AUDIO_CLOSE_EVT, tBTA_AG_DATA::kEmpty)); + do_in_main_thread(FROM_HERE, base::BindOnce(&bta_ag_sm_execute_by_handle, handle, + BTA_AG_API_AUDIO_CLOSE_EVT, tBTA_AG_DATA::kEmpty)); } /******************************************************************************* @@ -210,10 +201,8 @@ void BTA_AgAudioClose(uint16_t handle) { * Returns void * ******************************************************************************/ -void BTA_AgResult(uint16_t handle, tBTA_AG_RES result, - const tBTA_AG_RES_DATA& data) { - do_in_main_thread(FROM_HERE, - base::BindOnce(&bta_ag_api_result, handle, result, data)); +void BTA_AgResult(uint16_t handle, tBTA_AG_RES result, const tBTA_AG_RES_DATA& data) { + do_in_main_thread(FROM_HERE, base::BindOnce(&bta_ag_api_result, handle, result, data)); } /******************************************************************************* @@ -231,14 +220,12 @@ void BTA_AgResult(uint16_t handle, tBTA_AG_RES result, void BTA_AgSetCodec(uint16_t handle, tBTA_AG_PEER_CODEC codec) { tBTA_AG_DATA data = {}; data.api_setcodec.codec = codec; - do_in_main_thread(FROM_HERE, - base::BindOnce(&bta_ag_sm_execute_by_handle, handle, - BTA_AG_API_SETCODEC_EVT, data)); + do_in_main_thread(FROM_HERE, base::BindOnce(&bta_ag_sm_execute_by_handle, handle, + BTA_AG_API_SETCODEC_EVT, data)); } void BTA_AgSetScoOffloadEnabled(bool value) { - do_in_main_thread(FROM_HERE, - base::BindOnce(&bta_ag_set_sco_offload_enabled, value)); + do_in_main_thread(FROM_HERE, base::BindOnce(&bta_ag_set_sco_offload_enabled, value)); } void BTA_AgSetScoAllowed(bool value) { @@ -249,7 +236,6 @@ void BTA_AgSetActiveDevice(const RawAddress& active_device_addr) { if (active_device_addr.IsEmpty()) { do_in_main_thread(FROM_HERE, base::BindOnce(&bta_clear_active_device)); } else { - do_in_main_thread(FROM_HERE, base::BindOnce(&bta_ag_api_set_active_device, - active_device_addr)); + do_in_main_thread(FROM_HERE, base::BindOnce(&bta_ag_api_set_active_device, active_device_addr)); } } diff --git a/system/bta/ag/bta_ag_at.cc b/system/bta/ag/bta_ag_at.cc index d5ad62da165..e5fee21d8b7 100644 --- a/system/bta/ag/bta_ag_at.cc +++ b/system/bta/ag/bta_ag_at.cc @@ -138,14 +138,15 @@ void bta_ag_process_at(tBTA_AG_AT_CB* p_cb, char* p_end) { /* if arguments match command capabilities */ if ((arg_type & p_cb->p_at_tbl[idx].arg_type) != 0) { /* if it's a set integer check max, min range */ - if (arg_type == BTA_AG_AT_SET && - p_cb->p_at_tbl[idx].fmt == BTA_AG_AT_INT) { + if (arg_type == BTA_AG_AT_SET && p_cb->p_at_tbl[idx].fmt == BTA_AG_AT_INT) { if (com::android::bluetooth::flags::bta_ag_cmd_brsf_allow_uint32()) { if (p_cb->p_at_tbl[idx].command_id == BTA_AG_LOCAL_EVT_BRSF) { // Per HFP v1.9 BRSF could be 32-bit integer and we should ignore // all reserved bits rather than responding ERROR. long long int_arg_ll = std::atoll(p_arg); - if (int_arg_ll >= (1ll << 32) || int_arg_ll < 0) int_arg_ll = -1; + if (int_arg_ll >= (1ll << 32) || int_arg_ll < 0) { + int_arg_ll = -1; + } // Ignore reserved bits. 0xfff because there are 12 defined bits. if (int_arg_ll > 0 && (int_arg_ll & (~0xfffll))) { @@ -166,19 +167,17 @@ void bta_ag_process_at(tBTA_AG_AT_CB* p_cb, char* p_end) { log::warn("arg out of range"); (*p_cb->p_err_cback)((tBTA_AG_SCB*)p_cb->p_user, false, nullptr); } else { - (*p_cb->p_cmd_cback)((tBTA_AG_SCB*)p_cb->p_user, - p_cb->p_at_tbl[idx].command_id, arg_type, p_arg, - p_end, int_arg); + (*p_cb->p_cmd_cback)((tBTA_AG_SCB*)p_cb->p_user, p_cb->p_at_tbl[idx].command_id, arg_type, + p_arg, p_end, int_arg); } } else { - (*p_cb->p_cmd_cback)((tBTA_AG_SCB*)p_cb->p_user, - p_cb->p_at_tbl[idx].command_id, arg_type, p_arg, - p_end, int_arg); + (*p_cb->p_cmd_cback)((tBTA_AG_SCB*)p_cb->p_user, p_cb->p_at_tbl[idx].command_id, arg_type, + p_arg, p_end, int_arg); } } else { /* else error */ - log::warn("Incoming arg type 0x{:x} does not match cmd arg type 0x{:x}", - arg_type, p_cb->p_at_tbl[idx].arg_type); + log::warn("Incoming arg type 0x{:x} does not match cmd arg type 0x{:x}", arg_type, + p_cb->p_at_tbl[idx].arg_type); (*p_cb->p_err_cback)((tBTA_AG_SCB*)p_cb->p_user, false, nullptr); } } else { @@ -218,11 +217,9 @@ void bta_ag_at_parse(tBTA_AG_AT_CB* p_cb, char* p_buf, uint16_t len) { } p_cb->p_cmd_buf[p_cb->cmd_pos] = p_buf[i++]; - if (p_cb->p_cmd_buf[p_cb->cmd_pos] == '\r' || - p_cb->p_cmd_buf[p_cb->cmd_pos] == '\n') { + if (p_cb->p_cmd_buf[p_cb->cmd_pos] == '\r' || p_cb->p_cmd_buf[p_cb->cmd_pos] == '\n') { p_cb->p_cmd_buf[p_cb->cmd_pos] = 0; - if ((p_cb->cmd_pos > 2) && - (p_cb->p_cmd_buf[0] == 'A' || p_cb->p_cmd_buf[0] == 'a') && + if ((p_cb->cmd_pos > 2) && (p_cb->p_cmd_buf[0] == 'A' || p_cb->p_cmd_buf[0] == 'a') && (p_cb->p_cmd_buf[1] == 'T' || p_cb->p_cmd_buf[1] == 't')) { p_save = p_cb->p_cmd_buf; char* p_end = p_cb->p_cmd_buf + p_cb->cmd_pos; @@ -233,8 +230,7 @@ void bta_ag_at_parse(tBTA_AG_AT_CB* p_cb, char* p_buf, uint16_t len) { p_cb->cmd_pos = 0; - } else if (p_cb->p_cmd_buf[p_cb->cmd_pos] == 0x1A || - p_cb->p_cmd_buf[p_cb->cmd_pos] == 0x1B) { + } else if (p_cb->p_cmd_buf[p_cb->cmd_pos] == 0x1A || p_cb->p_cmd_buf[p_cb->cmd_pos] == 0x1B) { p_cb->p_cmd_buf[++p_cb->cmd_pos] = 0; (*p_cb->p_err_cback)((tBTA_AG_SCB*)p_cb->p_user, true, p_cb->p_cmd_buf); p_cb->cmd_pos = 0; @@ -243,6 +239,8 @@ void bta_ag_at_parse(tBTA_AG_AT_CB* p_cb, char* p_buf, uint16_t len) { } } - if (i < len) p_cb->cmd_pos = 0; + if (i < len) { + p_cb->cmd_pos = 0; + } } } diff --git a/system/bta/ag/bta_ag_at.h b/system/bta/ag/bta_ag_at.h index 0d61a06c19a..1d955764157 100644 --- a/system/bta/ag/bta_ag_at.h +++ b/system/bta/ag/bta_ag_at.h @@ -25,6 +25,7 @@ #define BTA_AG_AT_H #include + #include #include @@ -59,13 +60,11 @@ typedef struct { /* callback function executed when command is parsed */ struct tBTA_AG_SCB; -typedef void(tBTA_AG_AT_CMD_CBACK)(tBTA_AG_SCB* p_user, uint16_t command_id, - uint8_t arg_type, char* p_arg, char* p_end, - int16_t int_arg); +typedef void(tBTA_AG_AT_CMD_CBACK)(tBTA_AG_SCB* p_user, uint16_t command_id, uint8_t arg_type, + char* p_arg, char* p_end, int16_t int_arg); /* callback function executed to send "ERROR" result code */ -typedef void(tBTA_AG_AT_ERR_CBACK)(tBTA_AG_SCB* p_user, bool unknown, - const char* p_arg); +typedef void(tBTA_AG_AT_ERR_CBACK)(tBTA_AG_SCB* p_user, bool unknown, const char* p_arg); /* AT command parsing control block */ typedef struct { diff --git a/system/bta/ag/bta_ag_cfg.cc b/system/bta/ag/bta_ag_cfg.cc index 446a07be5c9..6d803327a50 100644 --- a/system/bta/ag/bta_ag_cfg.cc +++ b/system/bta/ag/bta_ag_cfg.cc @@ -42,29 +42,25 @@ #endif /* S1 packet type setting from HFP 1.5 spec */ -#define BTA_AG_SCO_PKT_TYPES /* BTM_SCO_LINK_ALL_PKT_MASK */ \ - (BTM_SCO_LINK_ONLY_MASK | ESCO_PKT_TYPES_MASK_EV3 | \ - ESCO_PKT_TYPES_MASK_NO_3_EV3 | ESCO_PKT_TYPES_MASK_NO_2_EV5 | \ - ESCO_PKT_TYPES_MASK_NO_3_EV5) +#define BTA_AG_SCO_PKT_TYPES /* BTM_SCO_LINK_ALL_PKT_MASK */ \ + (BTM_SCO_LINK_ONLY_MASK | ESCO_PKT_TYPES_MASK_EV3 | ESCO_PKT_TYPES_MASK_NO_3_EV3 | \ + ESCO_PKT_TYPES_MASK_NO_2_EV5 | ESCO_PKT_TYPES_MASK_NO_3_EV5) #ifndef BTA_AG_BIND_INFO #define BTA_AG_BIND_INFO "(1)" #endif const tBTA_AG_HF_IND bta_ag_local_hf_ind_cfg[] = { - /* The first row contains the number of indicators. Need to be updated - accordingly */ - {BTA_AG_NUM_LOCAL_HF_IND, false, false, 0, 0}, + /* The first row contains the number of indicators. Need to be updated + accordingly */ + {BTA_AG_NUM_LOCAL_HF_IND, false, false, 0, 0}, - {1, true, true, 0, - 1}, /* Enhanced Driver Status, supported, enabled, range 0 ~ 1 */ - {2, true, true, 0, - 100} /* Battery Level Status, supported, enabled, range 0 ~ 100 */ + {1, true, true, 0, 1}, /* Enhanced Driver Status, supported, enabled, range 0 ~ 1 */ + {2, true, true, 0, 100} /* Battery Level Status, supported, enabled, range 0 ~ 100 */ }; -const tBTA_AG_CFG bta_ag_cfg = {BTA_AG_CIND_INFO, BTA_AG_BIND_INFO, - BTA_AG_NUM_LOCAL_HF_IND, BTA_AG_CONN_TIMEOUT, - BTA_AG_SCO_PKT_TYPES, BTA_AG_CHLD_VAL_ECC, +const tBTA_AG_CFG bta_ag_cfg = {BTA_AG_CIND_INFO, BTA_AG_BIND_INFO, BTA_AG_NUM_LOCAL_HF_IND, + BTA_AG_CONN_TIMEOUT, BTA_AG_SCO_PKT_TYPES, BTA_AG_CHLD_VAL_ECC, BTA_AG_CHLD_VAL}; const tBTA_AG_CFG* p_bta_ag_cfg = &bta_ag_cfg; diff --git a/system/bta/ag/bta_ag_cmd.cc b/system/bta/ag/bta_ag_cmd.cc index 27b7452c465..f13bc39361d 100644 --- a/system/bta/ag/bta_ag_cmd.cc +++ b/system/bta/ag/bta_ag_cmd.cc @@ -62,57 +62,49 @@ using namespace bluetooth; /* AT command interpreter table for HSP */ static const tBTA_AG_AT_CMD bta_ag_hsp_cmd[] = { - {"+CKPD", BTA_AG_AT_CKPD_EVT, BTA_AG_AT_SET, BTA_AG_AT_INT, 200, 200}, - {"+VGS", BTA_AG_SPK_EVT, BTA_AG_AT_SET, BTA_AG_AT_INT, 0, 15}, - {"+VGM", BTA_AG_MIC_EVT, BTA_AG_AT_SET, BTA_AG_AT_INT, 0, 15}, - /* End-of-table marker used to stop lookup iteration */ - {"", 0, 0, 0, 0, 0}}; + {"+CKPD", BTA_AG_AT_CKPD_EVT, BTA_AG_AT_SET, BTA_AG_AT_INT, 200, 200}, + {"+VGS", BTA_AG_SPK_EVT, BTA_AG_AT_SET, BTA_AG_AT_INT, 0, 15}, + {"+VGM", BTA_AG_MIC_EVT, BTA_AG_AT_SET, BTA_AG_AT_INT, 0, 15}, + /* End-of-table marker used to stop lookup iteration */ + {"", 0, 0, 0, 0, 0}}; /* AT command interpreter table for HFP */ static const tBTA_AG_AT_CMD bta_ag_hfp_cmd[] = { - {"A", BTA_AG_AT_A_EVT, BTA_AG_AT_NONE, BTA_AG_AT_STR, 0, 0}, - {"D", BTA_AG_AT_D_EVT, BTA_AG_AT_NONE | BTA_AG_AT_FREE, BTA_AG_AT_STR, 0, - 0}, - {"+VGS", BTA_AG_SPK_EVT, BTA_AG_AT_SET, BTA_AG_AT_INT, 0, 15}, - {"+VGM", BTA_AG_MIC_EVT, BTA_AG_AT_SET, BTA_AG_AT_INT, 0, 15}, - {"+CCWA", BTA_AG_LOCAL_EVT_CCWA, BTA_AG_AT_SET, BTA_AG_AT_INT, 0, 1}, - /* Consider CHLD as str to take care of indexes for ECC */ - {"+CHLD", BTA_AG_AT_CHLD_EVT, BTA_AG_AT_SET | BTA_AG_AT_TEST, BTA_AG_AT_STR, - 0, 4}, - {"+CHUP", BTA_AG_AT_CHUP_EVT, BTA_AG_AT_NONE, BTA_AG_AT_STR, 0, 0}, - {"+CIND", BTA_AG_AT_CIND_EVT, BTA_AG_AT_READ | BTA_AG_AT_TEST, - BTA_AG_AT_STR, 0, 0}, - {"+CLIP", BTA_AG_LOCAL_EVT_CLIP, BTA_AG_AT_SET, BTA_AG_AT_INT, 0, 1}, - {"+CMER", BTA_AG_LOCAL_EVT_CMER, BTA_AG_AT_SET, BTA_AG_AT_STR, 0, 0}, - {"+VTS", BTA_AG_AT_VTS_EVT, BTA_AG_AT_SET, BTA_AG_AT_STR, 0, 0}, - {"+BINP", BTA_AG_AT_BINP_EVT, BTA_AG_AT_SET, BTA_AG_AT_INT, 1, 1}, - {"+BLDN", BTA_AG_AT_BLDN_EVT, BTA_AG_AT_NONE, BTA_AG_AT_STR, 0, 0}, - {"+BVRA", BTA_AG_AT_BVRA_EVT, BTA_AG_AT_SET, BTA_AG_AT_INT, 0, 1}, - {"+BRSF", BTA_AG_LOCAL_EVT_BRSF, BTA_AG_AT_SET, BTA_AG_AT_INT, 0, - BTA_AG_CMD_MAX_VAL}, - {"+NREC", BTA_AG_AT_NREC_EVT, BTA_AG_AT_SET, BTA_AG_AT_INT, 0, 0}, - {"+CNUM", BTA_AG_AT_CNUM_EVT, BTA_AG_AT_NONE, BTA_AG_AT_STR, 0, 0}, - {"+BTRH", BTA_AG_AT_BTRH_EVT, BTA_AG_AT_READ | BTA_AG_AT_SET, BTA_AG_AT_INT, - 0, 2}, - {"+CLCC", BTA_AG_AT_CLCC_EVT, BTA_AG_AT_NONE, BTA_AG_AT_STR, 0, 0}, - {"+COPS", BTA_AG_AT_COPS_EVT, BTA_AG_AT_READ | BTA_AG_AT_SET, BTA_AG_AT_STR, - 0, 0}, - {"+CMEE", BTA_AG_LOCAL_EVT_CMEE, BTA_AG_AT_SET, BTA_AG_AT_INT, 0, 1}, - {"+BIA", BTA_AG_AT_BIA_EVT, BTA_AG_AT_SET, BTA_AG_AT_STR, 0, 20}, - {"+CBC", BTA_AG_AT_CBC_EVT, BTA_AG_AT_SET, BTA_AG_AT_INT, 0, 100}, - {"+BCC", BTA_AG_LOCAL_EVT_BCC, BTA_AG_AT_NONE, BTA_AG_AT_STR, 0, 0}, - {"+BCS", BTA_AG_AT_BCS_EVT, BTA_AG_AT_SET, BTA_AG_AT_INT, 0, - BTA_AG_CMD_MAX_VAL}, - {"+BIND", BTA_AG_AT_BIND_EVT, - BTA_AG_AT_SET | BTA_AG_AT_READ | BTA_AG_AT_TEST, BTA_AG_AT_STR, 0, 0}, - {"+BIEV", BTA_AG_AT_BIEV_EVT, BTA_AG_AT_SET, BTA_AG_AT_STR, 0, 0}, - {"+BAC", BTA_AG_AT_BAC_EVT, BTA_AG_AT_SET, BTA_AG_AT_STR, 0, 0}, - {"+%QAC", BTA_AG_AT_QAC_EVT, BTA_AG_AT_SET, BTA_AG_AT_STR, 0, 0}, - {"+%QCS", BTA_AG_AT_QCS_EVT, BTA_AG_AT_SET, BTA_AG_AT_INT, 0, - BTA_AG_CMD_MAX_VAL}, - - /* End-of-table marker used to stop lookup iteration */ - {"", 0, 0, 0, 0, 0}}; + {"A", BTA_AG_AT_A_EVT, BTA_AG_AT_NONE, BTA_AG_AT_STR, 0, 0}, + {"D", BTA_AG_AT_D_EVT, BTA_AG_AT_NONE | BTA_AG_AT_FREE, BTA_AG_AT_STR, 0, 0}, + {"+VGS", BTA_AG_SPK_EVT, BTA_AG_AT_SET, BTA_AG_AT_INT, 0, 15}, + {"+VGM", BTA_AG_MIC_EVT, BTA_AG_AT_SET, BTA_AG_AT_INT, 0, 15}, + {"+CCWA", BTA_AG_LOCAL_EVT_CCWA, BTA_AG_AT_SET, BTA_AG_AT_INT, 0, 1}, + /* Consider CHLD as str to take care of indexes for ECC */ + {"+CHLD", BTA_AG_AT_CHLD_EVT, BTA_AG_AT_SET | BTA_AG_AT_TEST, BTA_AG_AT_STR, 0, 4}, + {"+CHUP", BTA_AG_AT_CHUP_EVT, BTA_AG_AT_NONE, BTA_AG_AT_STR, 0, 0}, + {"+CIND", BTA_AG_AT_CIND_EVT, BTA_AG_AT_READ | BTA_AG_AT_TEST, BTA_AG_AT_STR, 0, 0}, + {"+CLIP", BTA_AG_LOCAL_EVT_CLIP, BTA_AG_AT_SET, BTA_AG_AT_INT, 0, 1}, + {"+CMER", BTA_AG_LOCAL_EVT_CMER, BTA_AG_AT_SET, BTA_AG_AT_STR, 0, 0}, + {"+VTS", BTA_AG_AT_VTS_EVT, BTA_AG_AT_SET, BTA_AG_AT_STR, 0, 0}, + {"+BINP", BTA_AG_AT_BINP_EVT, BTA_AG_AT_SET, BTA_AG_AT_INT, 1, 1}, + {"+BLDN", BTA_AG_AT_BLDN_EVT, BTA_AG_AT_NONE, BTA_AG_AT_STR, 0, 0}, + {"+BVRA", BTA_AG_AT_BVRA_EVT, BTA_AG_AT_SET, BTA_AG_AT_INT, 0, 1}, + {"+BRSF", BTA_AG_LOCAL_EVT_BRSF, BTA_AG_AT_SET, BTA_AG_AT_INT, 0, BTA_AG_CMD_MAX_VAL}, + {"+NREC", BTA_AG_AT_NREC_EVT, BTA_AG_AT_SET, BTA_AG_AT_INT, 0, 0}, + {"+CNUM", BTA_AG_AT_CNUM_EVT, BTA_AG_AT_NONE, BTA_AG_AT_STR, 0, 0}, + {"+BTRH", BTA_AG_AT_BTRH_EVT, BTA_AG_AT_READ | BTA_AG_AT_SET, BTA_AG_AT_INT, 0, 2}, + {"+CLCC", BTA_AG_AT_CLCC_EVT, BTA_AG_AT_NONE, BTA_AG_AT_STR, 0, 0}, + {"+COPS", BTA_AG_AT_COPS_EVT, BTA_AG_AT_READ | BTA_AG_AT_SET, BTA_AG_AT_STR, 0, 0}, + {"+CMEE", BTA_AG_LOCAL_EVT_CMEE, BTA_AG_AT_SET, BTA_AG_AT_INT, 0, 1}, + {"+BIA", BTA_AG_AT_BIA_EVT, BTA_AG_AT_SET, BTA_AG_AT_STR, 0, 20}, + {"+CBC", BTA_AG_AT_CBC_EVT, BTA_AG_AT_SET, BTA_AG_AT_INT, 0, 100}, + {"+BCC", BTA_AG_LOCAL_EVT_BCC, BTA_AG_AT_NONE, BTA_AG_AT_STR, 0, 0}, + {"+BCS", BTA_AG_AT_BCS_EVT, BTA_AG_AT_SET, BTA_AG_AT_INT, 0, BTA_AG_CMD_MAX_VAL}, + {"+BIND", BTA_AG_AT_BIND_EVT, BTA_AG_AT_SET | BTA_AG_AT_READ | BTA_AG_AT_TEST, + BTA_AG_AT_STR, 0, 0}, + {"+BIEV", BTA_AG_AT_BIEV_EVT, BTA_AG_AT_SET, BTA_AG_AT_STR, 0, 0}, + {"+BAC", BTA_AG_AT_BAC_EVT, BTA_AG_AT_SET, BTA_AG_AT_STR, 0, 0}, + {"+%QAC", BTA_AG_AT_QAC_EVT, BTA_AG_AT_SET, BTA_AG_AT_STR, 0, 0}, + {"+%QCS", BTA_AG_AT_QCS_EVT, BTA_AG_AT_SET, BTA_AG_AT_INT, 0, BTA_AG_CMD_MAX_VAL}, + + /* End-of-table marker used to stop lookup iteration */ + {"", 0, 0, 0, 0, 0}}; /* AT result code table element */ typedef struct { @@ -142,42 +134,42 @@ enum { /* AT result code constant table */ static const tBTA_AG_RESULT bta_ag_result_tbl[] = { - {"OK", BTA_AG_LOCAL_RES_OK, BTA_AG_RES_FMT_NONE}, - {"ERROR", BTA_AG_LOCAL_RES_ERROR, BTA_AG_RES_FMT_NONE}, - {"RING", BTA_AG_LOCAL_RES_RING, BTA_AG_RES_FMT_NONE}, - {"+VGS: ", BTA_AG_SPK_RES, BTA_AG_RES_FMT_INT}, - {"+VGM: ", BTA_AG_MIC_RES, BTA_AG_RES_FMT_INT}, - {"+CCWA: ", BTA_AG_CALL_WAIT_RES, BTA_AG_RES_FMT_STR}, - {"+CHLD: ", BTA_AG_IN_CALL_HELD_RES, BTA_AG_RES_FMT_STR}, - {"+CIND: ", BTA_AG_CIND_RES, BTA_AG_RES_FMT_STR}, - {"+CLIP: ", BTA_AG_LOCAL_RES_CLIP, BTA_AG_RES_FMT_STR}, - {"+CIEV: ", BTA_AG_IND_RES, BTA_AG_RES_FMT_STR}, - {"+BINP: ", BTA_AG_BINP_RES, BTA_AG_RES_FMT_STR}, - {"+BVRA: ", BTA_AG_BVRA_RES, BTA_AG_RES_FMT_INT}, - {"+BRSF: ", BTA_AG_LOCAL_RES_BRSF, BTA_AG_RES_FMT_INT}, - {"+BSIR: ", BTA_AG_INBAND_RING_RES, BTA_AG_RES_FMT_INT}, - {"+CNUM: ", BTA_AG_CNUM_RES, BTA_AG_RES_FMT_STR}, - {"+BTRH: ", BTA_AG_BTRH_RES, BTA_AG_RES_FMT_INT}, - {"+CLCC: ", BTA_AG_CLCC_RES, BTA_AG_RES_FMT_STR}, - {"+COPS: ", BTA_AG_COPS_RES, BTA_AG_RES_FMT_STR}, - {"+CME ERROR: ", BTA_AG_LOCAL_RES_CMEE, BTA_AG_RES_FMT_INT}, - {"+BCS: ", BTA_AG_LOCAL_RES_BCS, BTA_AG_RES_FMT_INT}, - {"+BIND: ", BTA_AG_BIND_RES, BTA_AG_RES_FMT_STR}, - {"+%QAC: ", BTA_AG_LOCAL_RES_QAC, BTA_AG_RES_FMT_STR}, - {"+%QCS: ", BTA_AG_LOCAL_RES_QCS, BTA_AG_RES_FMT_INT}, - - {"", BTA_AG_UNAT_RES, BTA_AG_RES_FMT_STR}}; + {"OK", BTA_AG_LOCAL_RES_OK, BTA_AG_RES_FMT_NONE}, + {"ERROR", BTA_AG_LOCAL_RES_ERROR, BTA_AG_RES_FMT_NONE}, + {"RING", BTA_AG_LOCAL_RES_RING, BTA_AG_RES_FMT_NONE}, + {"+VGS: ", BTA_AG_SPK_RES, BTA_AG_RES_FMT_INT}, + {"+VGM: ", BTA_AG_MIC_RES, BTA_AG_RES_FMT_INT}, + {"+CCWA: ", BTA_AG_CALL_WAIT_RES, BTA_AG_RES_FMT_STR}, + {"+CHLD: ", BTA_AG_IN_CALL_HELD_RES, BTA_AG_RES_FMT_STR}, + {"+CIND: ", BTA_AG_CIND_RES, BTA_AG_RES_FMT_STR}, + {"+CLIP: ", BTA_AG_LOCAL_RES_CLIP, BTA_AG_RES_FMT_STR}, + {"+CIEV: ", BTA_AG_IND_RES, BTA_AG_RES_FMT_STR}, + {"+BINP: ", BTA_AG_BINP_RES, BTA_AG_RES_FMT_STR}, + {"+BVRA: ", BTA_AG_BVRA_RES, BTA_AG_RES_FMT_INT}, + {"+BRSF: ", BTA_AG_LOCAL_RES_BRSF, BTA_AG_RES_FMT_INT}, + {"+BSIR: ", BTA_AG_INBAND_RING_RES, BTA_AG_RES_FMT_INT}, + {"+CNUM: ", BTA_AG_CNUM_RES, BTA_AG_RES_FMT_STR}, + {"+BTRH: ", BTA_AG_BTRH_RES, BTA_AG_RES_FMT_INT}, + {"+CLCC: ", BTA_AG_CLCC_RES, BTA_AG_RES_FMT_STR}, + {"+COPS: ", BTA_AG_COPS_RES, BTA_AG_RES_FMT_STR}, + {"+CME ERROR: ", BTA_AG_LOCAL_RES_CMEE, BTA_AG_RES_FMT_INT}, + {"+BCS: ", BTA_AG_LOCAL_RES_BCS, BTA_AG_RES_FMT_INT}, + {"+BIND: ", BTA_AG_BIND_RES, BTA_AG_RES_FMT_STR}, + {"+%QAC: ", BTA_AG_LOCAL_RES_QAC, BTA_AG_RES_FMT_STR}, + {"+%QCS: ", BTA_AG_LOCAL_RES_QCS, BTA_AG_RES_FMT_INT}, + + {"", BTA_AG_UNAT_RES, BTA_AG_RES_FMT_STR}}; static const tBTA_AG_RESULT* bta_ag_result_by_code(size_t code) { - for (size_t i = 0; - i != sizeof(bta_ag_result_tbl) / sizeof(bta_ag_result_tbl[0]); ++i) { - if (code == bta_ag_result_tbl[i].result_id) return &bta_ag_result_tbl[i]; + for (size_t i = 0; i != sizeof(bta_ag_result_tbl) / sizeof(bta_ag_result_tbl[0]); ++i) { + if (code == bta_ag_result_tbl[i].result_id) { + return &bta_ag_result_tbl[i]; + } } return nullptr; } -const tBTA_AG_AT_CMD* bta_ag_at_tbl[BTA_AG_NUM_IDX] = {bta_ag_hsp_cmd, - bta_ag_hfp_cmd}; +const tBTA_AG_AT_CMD* bta_ag_at_tbl[BTA_AG_NUM_IDX] = {bta_ag_hsp_cmd, bta_ag_hfp_cmd}; typedef struct { size_t result_code; @@ -186,18 +178,17 @@ typedef struct { /* callsetup indicator value lookup table */ static const tBTA_AG_INDICATOR_MAP callsetup_indicator_map[] = { - {BTA_AG_IN_CALL_RES, BTA_AG_CALLSETUP_INCOMING}, - {BTA_AG_CALL_WAIT_RES, BTA_AG_CALLSETUP_INCOMING}, - {BTA_AG_OUT_CALL_ORIG_RES, BTA_AG_CALLSETUP_OUTGOING}, - {BTA_AG_OUT_CALL_ALERT_RES, BTA_AG_CALLSETUP_ALERTING}}; + {BTA_AG_IN_CALL_RES, BTA_AG_CALLSETUP_INCOMING}, + {BTA_AG_CALL_WAIT_RES, BTA_AG_CALLSETUP_INCOMING}, + {BTA_AG_OUT_CALL_ORIG_RES, BTA_AG_CALLSETUP_OUTGOING}, + {BTA_AG_OUT_CALL_ALERT_RES, BTA_AG_CALLSETUP_ALERTING}}; static size_t bta_ag_indicator_by_result_code(size_t code) { - for (size_t i = 0; - i != - sizeof(callsetup_indicator_map) / sizeof(callsetup_indicator_map[0]); + for (size_t i = 0; i != sizeof(callsetup_indicator_map) / sizeof(callsetup_indicator_map[0]); ++i) { - if (code == callsetup_indicator_map[i].result_code) + if (code == callsetup_indicator_map[i].result_code) { return callsetup_indicator_map[i].indicator; + } } return BTA_AG_CALLSETUP_NONE; } @@ -212,8 +203,8 @@ static size_t bta_ag_indicator_by_result_code(size_t code) { * Returns void * ******************************************************************************/ -static void bta_ag_send_result(tBTA_AG_SCB* p_scb, size_t code, - const char* p_arg, int16_t int_arg) { +static void bta_ag_send_result(tBTA_AG_SCB* p_scb, size_t code, const char* p_arg, + int16_t int_arg) { const tBTA_AG_RESULT* result = bta_ag_result_by_code(code); if (result == nullptr) { log::error("Unable to lookup result for code {}", code); @@ -258,11 +249,9 @@ static void bta_ag_send_result(tBTA_AG_SCB* p_scb, size_t code, /* send to RFCOMM */ uint16_t len = 0; - if (PORT_WriteData(p_scb->conn_handle, buf, (uint16_t)(p - buf), &len) != - PORT_SUCCESS) { - log::warn( - "Unable to write RFCOMM data peer:{} handle:{} len_exp:{} len_act:{}", - p_scb->peer_addr, p_scb->conn_handle, (uint16_t)(p - buf), len); + if (PORT_WriteData(p_scb->conn_handle, buf, (uint16_t)(p - buf), &len) != PORT_SUCCESS) { + log::warn("Unable to write RFCOMM data peer:{} handle:{} len_exp:{} len_act:{}", + p_scb->peer_addr, p_scb->conn_handle, (uint16_t)(p - buf), len); } } @@ -293,10 +282,11 @@ static void bta_ag_send_ok(tBTA_AG_SCB* p_scb) { ******************************************************************************/ static void bta_ag_send_error(tBTA_AG_SCB* p_scb, int16_t errcode) { /* If HFP and extended audio gateway error codes are enabled */ - if (p_scb->conn_service == BTA_AG_HFP && p_scb->cmee_enabled) + if (p_scb->conn_service == BTA_AG_HFP && p_scb->cmee_enabled) { bta_ag_send_result(p_scb, BTA_AG_LOCAL_RES_CMEE, nullptr, errcode); - else + } else { bta_ag_send_result(p_scb, BTA_AG_LOCAL_RES_ERROR, nullptr, 0); + } } /******************************************************************************* @@ -309,56 +299,69 @@ static void bta_ag_send_error(tBTA_AG_SCB* p_scb, int16_t errcode) { * Returns void * ******************************************************************************/ -static void bta_ag_send_ind(tBTA_AG_SCB* p_scb, uint16_t id, uint16_t value, - bool on_demand) { +static void bta_ag_send_ind(tBTA_AG_SCB* p_scb, uint16_t id, uint16_t value, bool on_demand) { char str[12]; char* p = str; /* If the indicator is masked out, just return */ /* Mandatory indicators can not be masked out. */ if ((p_scb->bia_masked_out & ((uint32_t)1 << id)) && - ((id != BTA_AG_IND_CALL) && (id != BTA_AG_IND_CALLSETUP) && - (id != BTA_AG_IND_CALLHELD))) + ((id != BTA_AG_IND_CALL) && (id != BTA_AG_IND_CALLSETUP) && (id != BTA_AG_IND_CALLHELD))) { return; + } /* Ensure we do not send duplicate indicators if not requested by app */ /* If it was requested by app, transmit CIEV even if it is duplicate. */ if (id == BTA_AG_IND_CALL) { - if ((value == p_scb->call_ind) && (!on_demand)) return; + if ((value == p_scb->call_ind) && (!on_demand)) { + return; + } p_scb->call_ind = (uint8_t)value; } if ((id == BTA_AG_IND_CALLSETUP) && (!on_demand)) { - if (value == p_scb->callsetup_ind) return; + if (value == p_scb->callsetup_ind) { + return; + } p_scb->callsetup_ind = (uint8_t)value; } if ((id == BTA_AG_IND_SERVICE) && (!on_demand)) { - if (value == p_scb->service_ind) return; + if (value == p_scb->service_ind) { + return; + } p_scb->service_ind = (uint8_t)value; } if ((id == BTA_AG_IND_SIGNAL) && (!on_demand)) { - if (value == p_scb->signal_ind) return; + if (value == p_scb->signal_ind) { + return; + } p_scb->signal_ind = (uint8_t)value; } if ((id == BTA_AG_IND_ROAM) && (!on_demand)) { - if (value == p_scb->roam_ind) return; + if (value == p_scb->roam_ind) { + return; + } p_scb->roam_ind = (uint8_t)value; } if ((id == BTA_AG_IND_BATTCHG) && (!on_demand)) { - if (value == p_scb->battchg_ind) return; + if (value == p_scb->battchg_ind) { + return; + } p_scb->battchg_ind = (uint8_t)value; } if ((id == BTA_AG_IND_CALLHELD) && (!on_demand)) { /* call swap could result in sending callheld=1 multiple times */ - if ((value != 1) && (value == p_scb->callheld_ind)) return; + if ((value != 1) && (value == p_scb->callheld_ind)) { + return; + } p_scb->callheld_ind = (uint8_t)value; } @@ -441,7 +444,7 @@ static uint8_t bta_ag_parse_chld(tBTA_AG_SCB* /* p_scb */, char* p_s) { } } - return (retval); + return retval; } /******************************************************************************* @@ -453,8 +456,7 @@ static uint8_t bta_ag_parse_chld(tBTA_AG_SCB* /* p_scb */, char* p_s) { * Returns Returns bitmap of supported codecs. * ******************************************************************************/ -static tBTA_AG_PEER_CODEC bta_ag_parse_bac(tBTA_AG_SCB* p_scb, char* p_s, - char* p_end) { +static tBTA_AG_PEER_CODEC bta_ag_parse_bac(tBTA_AG_SCB* p_scb, char* p_s, char* p_end) { tBTA_AG_PEER_CODEC retval = BTM_SCO_CODEC_NONE; tBTA_AG_UUID_CODEC uuid_codec; char* p; @@ -485,18 +487,18 @@ static tBTA_AG_PEER_CODEC bta_ag_parse_bac(tBTA_AG_SCB* p_scb, char* p_s, retval |= BTM_SCO_CODEC_LC3; break; default: - log::error("Unknown Codec UUID({}) received", - bta_ag_uuid_codec_text(uuid_codec)); + log::error("Unknown Codec UUID({}) received", bta_ag_uuid_codec_text(uuid_codec)); break; } - if (cont) + if (cont) { p_s = p + 1; - else + } else { break; + } } - return (retval); + return retval; } /******************************************************************************* @@ -519,11 +521,12 @@ static void bta_ag_process_unat_res(char* unat_result) { uint8_t str_leng = strlen(unat_result); /* If no extra CR and LF, just return */ - if (str_leng < 4) return; + if (str_leng < 4) { + return; + } /* Remove the carriage return and left feed */ - while (unat_result[0] == '\r' && unat_result[1] == '\n' && - unat_result[str_leng - 2] == '\r' && + while (unat_result[0] == '\r' && unat_result[1] == '\n' && unat_result[str_leng - 2] == '\r' && unat_result[str_leng - 1] == '\n') { pairs_of_nl_cr = 1; for (int i = 0; i < (str_leng - 4 * pairs_of_nl_cr); i++) { @@ -535,7 +538,9 @@ static void bta_ag_process_unat_res(char* unat_result) { strlcpy(unat_result, trim_data, str_leng + 1); j = 0; - if (str_leng < 4) return; + if (str_leng < 4) { + return; + } } } @@ -572,8 +577,7 @@ void bta_ag_send_call_inds(tBTA_AG_SCB* p_scb, tBTA_AG_RES result) { if (result == BTA_AG_END_CALL_RES) { call = BTA_AG_CALL_INACTIVE; - } else if (result == BTA_AG_IN_CALL_CONN_RES || - result == BTA_AG_OUT_CALL_CONN_RES || + } else if (result == BTA_AG_IN_CALL_CONN_RES || result == BTA_AG_OUT_CALL_CONN_RES || result == BTA_AG_IN_CALL_HELD_RES) { call = BTA_AG_CALL_ACTIVE; } else { @@ -595,11 +599,9 @@ void bta_ag_send_call_inds(tBTA_AG_SCB* p_scb, tBTA_AG_RES result) { * Returns void * ******************************************************************************/ -void bta_ag_at_hsp_cback(tBTA_AG_SCB* p_scb, uint16_t command_id, - uint8_t arg_type, char* p_arg, char* p_end, - int16_t int_arg) { - log::verbose("AT cmd:{} arg_type:{} arg:{} arg:{}", command_id, arg_type, - int_arg, p_arg); +void bta_ag_at_hsp_cback(tBTA_AG_SCB* p_scb, uint16_t command_id, uint8_t arg_type, char* p_arg, + char* p_end, int16_t int_arg) { + log::verbose("AT cmd:{} arg_type:{} arg:{} arg:{}", command_id, arg_type, int_arg, p_arg); bta_ag_send_ok(p_scb); @@ -650,7 +652,9 @@ static void remove_spaces(char* str) { ******************************************************************************/ static int bta_ag_find_empty_hf_ind(tBTA_AG_SCB* p_scb) { for (int index = 0; index < BTA_AG_MAX_NUM_PEER_HF_IND; index++) { - if (p_scb->peer_hf_indicators[index].ind_id == 0) return index; + if (p_scb->peer_hf_indicators[index].ind_id == 0) { + return index; + } } return -1; @@ -668,10 +672,11 @@ static int bta_ag_find_empty_hf_ind(tBTA_AG_SCB* p_scb) { * was not found. * ******************************************************************************/ -static int bta_ag_find_hf_ind_by_id(tBTA_AG_HF_IND* p_hf_ind, int size, - uint32_t ind_id) { +static int bta_ag_find_hf_ind_by_id(tBTA_AG_HF_IND* p_hf_ind, int size, uint32_t ind_id) { for (int index = 0; index < size; index++) { - if (p_hf_ind[index].ind_id == ind_id) return index; + if (p_hf_ind[index].ind_id == ind_id) { + return index; + } } return -1; @@ -688,7 +693,9 @@ static int bta_ag_find_hf_ind_by_id(tBTA_AG_HF_IND* p_hf_ind, int size, ******************************************************************************/ static bool bta_ag_parse_bind_set(tBTA_AG_SCB* p_scb, tBTA_AG_VAL val) { char* p_token = strtok(val.str, ","); - if (p_token == nullptr) return false; + if (p_token == nullptr) { + return false; + } while (p_token != nullptr) { uint16_t rcv_ind_id = atoi(p_token); @@ -727,9 +734,10 @@ static void bta_ag_bind_response(tBTA_AG_SCB* p_scb, uint8_t arg_type) { for (uint32_t i = 0; i < bta_ag_local_hf_ind_cfg[0].ind_id; i++) { if (bta_ag_local_hf_ind_cfg[i + 1].is_supported) { /* Add ',' from second indicator */ - if (index > 1) buffer[index++] = ','; - snprintf(&buffer[index++], 2, "%d", - bta_ag_local_hf_ind_cfg[i + 1].ind_id); + if (index > 1) { + buffer[index++] = ','; + } + snprintf(&buffer[index++], 2, "%d", bta_ag_local_hf_ind_cfg[i + 1].ind_id); } } @@ -747,16 +755,13 @@ static void bta_ag_bind_response(tBTA_AG_SCB* p_scb, uint8_t arg_type) { break; } - p_scb->local_hf_indicators[i].ind_id = - bta_ag_local_hf_ind_cfg[i + 1].ind_id; - p_scb->local_hf_indicators[i].is_supported = - bta_ag_local_hf_ind_cfg[i + 1].is_supported; - p_scb->local_hf_indicators[i].is_enable = - bta_ag_local_hf_ind_cfg[i + 1].is_enable; + p_scb->local_hf_indicators[i].ind_id = bta_ag_local_hf_ind_cfg[i + 1].ind_id; + p_scb->local_hf_indicators[i].is_supported = bta_ag_local_hf_ind_cfg[i + 1].is_supported; + p_scb->local_hf_indicators[i].is_enable = bta_ag_local_hf_ind_cfg[i + 1].is_enable; - int peer_index = bta_ag_find_hf_ind_by_id( - p_scb->peer_hf_indicators, BTA_AG_MAX_NUM_PEER_HF_IND, - p_scb->local_hf_indicators[i].ind_id); + int peer_index = + bta_ag_find_hf_ind_by_id(p_scb->peer_hf_indicators, BTA_AG_MAX_NUM_PEER_HF_IND, + p_scb->local_hf_indicators[i].ind_id); /* Check whether local and peer sides support this indicator */ if (p_scb->local_hf_indicators[i].is_supported && peer_index != -1) { @@ -797,11 +802,15 @@ static void bta_ag_bind_response(tBTA_AG_SCB* p_scb, uint8_t arg_type) { ******************************************************************************/ static bool bta_ag_parse_biev_response(tBTA_AG_SCB* p_scb, tBTA_AG_VAL* val) { char* p_token = strtok(val->str, ","); - if (p_token == nullptr) return false; + if (p_token == nullptr) { + return false; + } uint16_t rcv_ind_id = atoi(p_token); p_token = strtok(nullptr, ","); - if (p_token == nullptr) return false; + if (p_token == nullptr) { + return false; + } uint16_t rcv_ind_val = atoi(p_token); log::verbose("BIEV indicator id {}, value {}", rcv_ind_id, rcv_ind_val); @@ -813,10 +822,9 @@ static bool bta_ag_parse_biev_response(tBTA_AG_SCB* p_scb, tBTA_AG_VAL* val) { } /* Check this indicator is support or not and enabled or not */ - int local_index = bta_ag_find_hf_ind_by_id( - p_scb->local_hf_indicators, BTA_AG_MAX_NUM_LOCAL_HF_IND, rcv_ind_id); - if (local_index == -1 || - !p_scb->local_hf_indicators[local_index].is_supported || + int local_index = bta_ag_find_hf_ind_by_id(p_scb->local_hf_indicators, + BTA_AG_MAX_NUM_LOCAL_HF_IND, rcv_ind_id); + if (local_index == -1 || !p_scb->local_hf_indicators[local_index].is_supported || !p_scb->local_hf_indicators[local_index].is_enable) { log::warn("indicator id {} not supported or disabled", rcv_ind_id); return false; @@ -860,8 +868,8 @@ static void bta_ag_bind_timer_cback(void* data) { * Returns void * ******************************************************************************/ -void bta_ag_at_hfp_cback(tBTA_AG_SCB* p_scb, uint16_t cmd, uint8_t arg_type, - char* p_arg, char* p_end, int16_t int_arg) { +void bta_ag_at_hfp_cback(tBTA_AG_SCB* p_scb, uint16_t cmd, uint8_t arg_type, char* p_arg, + char* p_end, int16_t int_arg) { tBTA_AG_VAL val = {}; tBTA_AG_SCB* ag_scb; uint32_t i, ind_id; @@ -872,8 +880,7 @@ void bta_ag_at_hfp_cback(tBTA_AG_SCB* p_scb, uint16_t cmd, uint8_t arg_type, return; } - log::verbose("AT command {}, arg_type {}, int_arg {}, arg {}", cmd, arg_type, - int_arg, p_arg); + log::verbose("AT command {}, arg_type {}, int_arg {}, arg {}", cmd, arg_type, int_arg, p_arg); val.hdr.handle = bta_ag_scb_to_idx(p_scb); val.hdr.app_id = p_scb->app_id; @@ -965,14 +972,12 @@ void bta_ag_at_hfp_cback(tBTA_AG_SCB* p_scb, uint16_t cmd, uint8_t arg_type, /* send CHLD string */ /* Form string based on supported 1.5 feature */ - if ((p_scb->peer_version >= HFP_VERSION_1_5) && - (p_scb->features & BTA_AG_FEAT_ECC) && - (p_scb->peer_features & BTA_AG_PEER_FEAT_ECC)) - bta_ag_send_result(p_scb, BTA_AG_IN_CALL_HELD_RES, - p_bta_ag_cfg->chld_val_ecc, 0); - else - bta_ag_send_result(p_scb, BTA_AG_IN_CALL_HELD_RES, - p_bta_ag_cfg->chld_val, 0); + if ((p_scb->peer_version >= HFP_VERSION_1_5) && (p_scb->features & BTA_AG_FEAT_ECC) && + (p_scb->peer_features & BTA_AG_PEER_FEAT_ECC)) { + bta_ag_send_result(p_scb, BTA_AG_IN_CALL_HELD_RES, p_bta_ag_cfg->chld_val_ecc, 0); + } else { + bta_ag_send_result(p_scb, BTA_AG_IN_CALL_HELD_RES, p_bta_ag_cfg->chld_val, 0); + } /* send OK */ bta_ag_send_ok(p_scb); @@ -980,16 +985,14 @@ void bta_ag_at_hfp_cback(tBTA_AG_SCB* p_scb, uint16_t cmd, uint8_t arg_type, /* if service level conn. not already open and our features and ** peer features do not have HF Indicators, service level conn. now open */ - if (!p_scb->svc_conn && - !((p_scb->masked_features & BTA_AG_FEAT_HF_IND) && - (p_scb->peer_features & BTA_AG_PEER_FEAT_HF_IND))) { + if (!p_scb->svc_conn && !((p_scb->masked_features & BTA_AG_FEAT_HF_IND) && + (p_scb->peer_features & BTA_AG_PEER_FEAT_HF_IND))) { bta_ag_svc_conn_open(p_scb, tBTA_AG_DATA::kEmpty); } else { if (p_scb->peer_version >= HFP_VERSION_1_7 && - interop_match_addr(INTEROP_SLC_SKIP_BIND_COMMAND, - &p_scb->peer_addr)) { - alarm_set_on_mloop(p_scb->bind_timer, BTA_AG_BIND_TIMEOUT_MS, - bta_ag_bind_timer_cback, p_scb); + interop_match_addr(INTEROP_SLC_SKIP_BIND_COMMAND, &p_scb->peer_addr)) { + alarm_set_on_mloop(p_scb->bind_timer, BTA_AG_BIND_TIMEOUT_MS, bta_ag_bind_timer_cback, + p_scb); } } } else { @@ -1000,9 +1003,8 @@ void bta_ag_at_hfp_cback(tBTA_AG_SCB* p_scb, uint16_t cmd, uint8_t arg_type, bta_ag_send_error(p_scb, BTA_AG_ERR_OP_NOT_SUPPORTED); break; } - if (val.idx && - !((p_scb->features & BTA_AG_FEAT_ECC) && - (p_scb->peer_features & BTA_AG_PEER_FEAT_ECC))) { + if (val.idx && !((p_scb->features & BTA_AG_FEAT_ECC) && + (p_scb->peer_features & BTA_AG_PEER_FEAT_ECC))) { /* we do not support ECC, but HF is sending us a CHLD with call * index*/ event = BTA_AG_ENABLE_EVT; @@ -1010,16 +1012,16 @@ void bta_ag_at_hfp_cback(tBTA_AG_SCB* p_scb, uint16_t cmd, uint8_t arg_type, } else { /* If it is swap between calls, set call held indicator to 3(out of - *valid 0-2) - ** Application will set it back to 1 - ** callheld indicator will be sent across to the peer. */ + *valid 0-2) + ** Application will set it back to 1 + ** callheld indicator will be sent across to the peer. */ if (val.str[0] == '2') { - for (i = 0, ag_scb = &bta_ag_cb.scb[0]; i < BTA_AG_MAX_NUM_CLIENTS; - i++, ag_scb++) { + for (i = 0, ag_scb = &bta_ag_cb.scb[0]; i < BTA_AG_MAX_NUM_CLIENTS; i++, ag_scb++) { if (ag_scb->in_use) { if ((ag_scb->call_ind == BTA_AG_CALL_ACTIVE) && - (ag_scb->callsetup_ind == BTA_AG_CALLSETUP_NONE)) + (ag_scb->callsetup_ind == BTA_AG_CALLSETUP_NONE)) { ag_scb->callheld_ind = BTA_AG_CALLHELD_NOACTIVE + 1; + } } } } @@ -1131,12 +1133,10 @@ void bta_ag_at_hfp_cback(tBTA_AG_SCB* p_scb, uint16_t cmd, uint8_t arg_type, p_scb->masked_features &= HFP_1_6_FEAT_MASK; } - log::verbose("BRSF HF: 0x{:x}, phone: 0x{:x}", p_scb->peer_features, - p_scb->masked_features); + log::verbose("BRSF HF: 0x{:x}, phone: 0x{:x}", p_scb->peer_features, p_scb->masked_features); /* send BRSF, send OK */ - bta_ag_send_result(p_scb, BTA_AG_LOCAL_RES_BRSF, nullptr, - (int16_t)p_scb->masked_features); + bta_ag_send_result(p_scb, BTA_AG_LOCAL_RES_BRSF, nullptr, (int16_t)p_scb->masked_features); bta_ag_send_ok(p_scb); break; } @@ -1157,8 +1157,7 @@ void bta_ag_at_hfp_cback(tBTA_AG_SCB* p_scb, uint16_t cmd, uint8_t arg_type, if (p_scb->features & BTA_AG_FEAT_BTRH) { /* If set command; send response and notify app */ if (arg_type == BTA_AG_AT_SET) { - for (i = 0, ag_scb = &bta_ag_cb.scb[0]; i < BTA_AG_MAX_NUM_CLIENTS; - i++, ag_scb++) { + for (i = 0, ag_scb = &bta_ag_cb.scb[0]; i < BTA_AG_MAX_NUM_CLIENTS; i++, ag_scb++) { if (ag_scb->in_use) { bta_ag_send_result(ag_scb, BTA_AG_BTRH_RES, nullptr, int_arg); } @@ -1202,8 +1201,7 @@ void bta_ag_at_hfp_cback(tBTA_AG_SCB* p_scb, uint16_t cmd, uint8_t arg_type, bia_masked_out = p_scb->bia_masked_out; /* Parse the indicator mask */ - for (i = 0, ind_id = 1; (val.str[i] != 0) && (ind_id <= 20); - i++, ind_id++) { + for (i = 0, ind_id = 1; (val.str[i] != 0) && (ind_id <= 20); i++, ind_id++) { if (val.str[i] == ',') { continue; } @@ -1253,8 +1251,7 @@ void bta_ag_at_hfp_cback(tBTA_AG_SCB* p_scb, uint16_t cmd, uint8_t arg_type, bool wbs_supported = hfp_hal_interface::get_wbs_supported(); bool swb_supported = hfp_hal_interface::get_swb_supported(); - const bool aptx_voice = - is_hfp_aptx_voice_enabled() && p_scb->is_aptx_swb_codec; + const bool aptx_voice = is_hfp_aptx_voice_enabled() && p_scb->is_aptx_swb_codec; log::verbose("BTA_AG_AT_BAC_EVT aptx_voice={}", aptx_voice); if (swb_supported && (p_scb->peer_codecs & BTM_SCO_CODEC_LC3) && @@ -1280,8 +1277,7 @@ void bta_ag_at_hfp_cback(tBTA_AG_SCB* p_scb, uint16_t cmd, uint8_t arg_type, application. */ val.num = p_scb->peer_codecs; /* Received BAC while in codec negotiation. */ - if ((bta_ag_cb.sco.state == BTA_AG_SCO_CODEC_ST) && - (bta_ag_cb.sco.p_curr_scb == p_scb)) { + if ((bta_ag_cb.sco.state == BTA_AG_SCO_CODEC_ST) && (bta_ag_cb.sco.p_curr_scb == p_scb)) { bta_ag_codec_negotiate(p_scb); } } else { @@ -1311,10 +1307,11 @@ void bta_ag_at_hfp_cback(tBTA_AG_SCB* p_scb, uint16_t cmd, uint8_t arg_type, break; } - if (p_scb->codec_fallback) + if (p_scb->codec_fallback) { codec_sent = BTM_SCO_CODEC_CVSD; - else + } else { codec_sent = p_scb->sco_codec; + } bta_ag_sco_codec_nego(p_scb, codec_type == codec_sent); @@ -1324,9 +1321,8 @@ void bta_ag_at_hfp_cback(tBTA_AG_SCB* p_scb, uint16_t cmd, uint8_t arg_type, } case BTA_AG_LOCAL_EVT_BCC: { if (!bta_ag_sco_is_active_device(p_scb->peer_addr)) { - log::warn( - "NOT opening SCO for EVT {} as {} is not the active HFP device", - "BTA_AG_LOCAL_EVT_BCC", p_scb->peer_addr.ToStringForLogging()); + log::warn("NOT opening SCO for EVT {} as {} is not the active HFP device", + "BTA_AG_LOCAL_EVT_BCC", p_scb->peer_addr.ToStringForLogging()); bta_ag_send_error(p_scb, BTA_AG_ERR_OP_NOT_ALLOWED); break; } @@ -1413,8 +1409,7 @@ void bta_ag_at_err_cback(tBTA_AG_SCB* p_scb, bool unknown, const char* p_arg) { * Returns void * ******************************************************************************/ -static void bta_ag_hsp_result(tBTA_AG_SCB* p_scb, - const tBTA_AG_API_RESULT& result) { +static void bta_ag_hsp_result(tBTA_AG_SCB* p_scb, const tBTA_AG_API_RESULT& result) { log::verbose("bta_ag_hsp_result : res = {}", result.result); switch (result.result) { @@ -1440,8 +1435,7 @@ static void bta_ag_hsp_result(tBTA_AG_SCB* p_scb, p_scb->post_sco = BTA_AG_POST_SCO_RING; } - if (!bta_ag_is_sco_open_allowed(p_scb, - bta_ag_result_text(result.result))) { + if (!bta_ag_is_sco_open_allowed(p_scb, bta_ag_result_text(result.result))) { break; } if (bta_ag_is_sco_managed_by_audio()) { @@ -1461,10 +1455,8 @@ static void bta_ag_hsp_result(tBTA_AG_SCB* p_scb, if (!(p_scb->features & BTA_AG_FEAT_NOSCO)) { /* if audio connected to this scb AND sco is not opened, open sco */ - if (result.data.audio_handle == bta_ag_scb_to_idx(p_scb) && - !bta_ag_sco_is_open(p_scb)) { - if (!bta_ag_is_sco_open_allowed(p_scb, - bta_ag_result_text(result.result))) { + if (result.data.audio_handle == bta_ag_scb_to_idx(p_scb) && !bta_ag_sco_is_open(p_scb)) { + if (!bta_ag_is_sco_open_allowed(p_scb, bta_ag_result_text(result.result))) { break; } if (bta_ag_is_sco_managed_by_audio()) { @@ -1472,8 +1464,7 @@ static void bta_ag_hsp_result(tBTA_AG_SCB* p_scb, break; } bta_ag_sco_open(p_scb, tBTA_AG_DATA::kEmpty); - } else if (result.data.audio_handle == BTA_AG_HANDLE_NONE && - bta_ag_sco_is_open(p_scb)) { + } else if (result.data.audio_handle == BTA_AG_HANDLE_NONE && bta_ag_sco_is_open(p_scb)) { /* else if no audio at call close sco */ bta_ag_sco_close(p_scb, tBTA_AG_DATA::kEmpty); } @@ -1504,7 +1495,9 @@ static void bta_ag_hsp_result(tBTA_AG_SCB* p_scb, bta_ag_send_result(p_scb, result.result, result.data.str, 0); } - if (result.data.ok_flag == BTA_AG_OK_DONE) bta_ag_send_ok(p_scb); + if (result.data.ok_flag == BTA_AG_OK_DONE) { + bta_ag_send_ok(p_scb); + } } else { bta_ag_send_error(p_scb, BTA_AG_ERR_INV_CHAR_IN_TSTR); } @@ -1526,8 +1519,7 @@ static void bta_ag_hsp_result(tBTA_AG_SCB* p_scb, * Returns void * ******************************************************************************/ -static void bta_ag_hfp_result(tBTA_AG_SCB* p_scb, - const tBTA_AG_API_RESULT& result) { +static void bta_ag_hfp_result(tBTA_AG_SCB* p_scb, const tBTA_AG_API_RESULT& result) { log::debug("HFP connection result:{}", result.ToString()); switch (result.result) { @@ -1561,8 +1553,7 @@ static void bta_ag_hfp_result(tBTA_AG_SCB* p_scb, /* else open sco, send ring after sco opened */ p_scb->post_sco = BTA_AG_POST_SCO_RING; - if (!bta_ag_is_sco_open_allowed(p_scb, - bta_ag_result_text(result.result))) { + if (!bta_ag_is_sco_open_allowed(p_scb, bta_ag_result_text(result.result))) { break; } if (bta_ag_is_sco_managed_by_audio()) { @@ -1583,10 +1574,8 @@ static void bta_ag_hfp_result(tBTA_AG_SCB* p_scb, bta_ag_send_call_inds(p_scb, result.result); if (!(p_scb->features & BTA_AG_FEAT_NOSCO)) { - if (result.data.audio_handle == bta_ag_scb_to_idx(p_scb) && - !bta_ag_sco_is_open(p_scb)) { - if (!bta_ag_is_sco_open_allowed(p_scb, - bta_ag_result_text(result.result))) { + if (result.data.audio_handle == bta_ag_scb_to_idx(p_scb) && !bta_ag_sco_is_open(p_scb)) { + if (!bta_ag_is_sco_open_allowed(p_scb, bta_ag_result_text(result.result))) { break; } if (bta_ag_is_sco_managed_by_audio()) { @@ -1594,8 +1583,7 @@ static void bta_ag_hfp_result(tBTA_AG_SCB* p_scb, break; } bta_ag_sco_open(p_scb, tBTA_AG_DATA::kEmpty); - } else if ((result.data.audio_handle == BTA_AG_HANDLE_NONE) && - bta_ag_sco_is_open(p_scb)) { + } else if ((result.data.audio_handle == BTA_AG_HANDLE_NONE) && bta_ag_sco_is_open(p_scb)) { bta_ag_sco_close(p_scb, tBTA_AG_DATA::kEmpty); } } @@ -1612,8 +1600,7 @@ static void bta_ag_hfp_result(tBTA_AG_SCB* p_scb, bta_ag_send_call_inds(p_scb, result.result); if (result.data.audio_handle == bta_ag_scb_to_idx(p_scb) && !(p_scb->features & BTA_AG_FEAT_NOSCO)) { - if (!bta_ag_is_sco_open_allowed(p_scb, - bta_ag_result_text(result.result))) { + if (!bta_ag_is_sco_open_allowed(p_scb, bta_ag_result_text(result.result))) { break; } if (bta_ag_is_sco_managed_by_audio()) { @@ -1629,8 +1616,7 @@ static void bta_ag_hfp_result(tBTA_AG_SCB* p_scb, bta_ag_send_call_inds(p_scb, result.result); if (result.data.audio_handle == bta_ag_scb_to_idx(p_scb) && !(p_scb->features & BTA_AG_FEAT_NOSCO)) { - if (!bta_ag_is_sco_open_allowed(p_scb, - bta_ag_result_text(result.result))) { + if (!bta_ag_is_sco_open_allowed(p_scb, bta_ag_result_text(result.result))) { break; } if (bta_ag_is_sco_managed_by_audio()) { @@ -1646,8 +1632,7 @@ static void bta_ag_hfp_result(tBTA_AG_SCB* p_scb, log::verbose("Headset Connected in three way call"); if (!(p_scb->features & BTA_AG_FEAT_NOSCO)) { if (result.data.audio_handle == bta_ag_scb_to_idx(p_scb)) { - if (!bta_ag_is_sco_open_allowed(p_scb, - bta_ag_result_text(result.result))) { + if (!bta_ag_is_sco_open_allowed(p_scb, bta_ag_result_text(result.result))) { break; } if (bta_ag_is_sco_managed_by_audio()) { @@ -1668,8 +1653,7 @@ static void bta_ag_hfp_result(tBTA_AG_SCB* p_scb, /* open or close sco */ if (!(p_scb->features & BTA_AG_FEAT_NOSCO)) { if (result.data.audio_handle == bta_ag_scb_to_idx(p_scb)) { - if (!bta_ag_is_sco_open_allowed(p_scb, - bta_ag_result_text(result.result))) { + if (!bta_ag_is_sco_open_allowed(p_scb, bta_ag_result_text(result.result))) { break; } if (bta_ag_is_sco_managed_by_audio()) { @@ -1723,8 +1707,7 @@ static void bta_ag_hfp_result(tBTA_AG_SCB* p_scb, p_scb->roam_ind = result.data.str[8] - '0'; p_scb->battchg_ind = result.data.str[10] - '0'; p_scb->callheld_ind = result.data.str[12] - '0'; - log::verbose("cind call:{} callsetup:{}", p_scb->call_ind, - p_scb->callsetup_ind); + log::verbose("cind call:{} callsetup:{}", p_scb->call_ind, p_scb->callsetup_ind); bta_ag_send_result(p_scb, result.result, result.data.str, 0); bta_ag_send_ok(p_scb); @@ -1739,7 +1722,9 @@ static void bta_ag_hfp_result(tBTA_AG_SCB* p_scb, bta_ag_send_result(p_scb, result.result, result.data.str, 0); } - if (result.data.ok_flag == BTA_AG_OK_DONE) bta_ag_send_ok(p_scb); + if (result.data.ok_flag == BTA_AG_OK_DONE) { + bta_ag_send_ok(p_scb); + } } else { bta_ag_send_error(p_scb, result.data.errcode); } @@ -1751,8 +1736,7 @@ static void bta_ag_hfp_result(tBTA_AG_SCB* p_scb, tBTA_AG_API_RESULT result_copy(result); bta_ag_process_unat_res(result_copy.data.str); log::verbose("BTA_AG_RES :{}", result_copy.data.str); - bta_ag_send_result(p_scb, result_copy.result, result_copy.data.str, - 0); + bta_ag_send_result(p_scb, result_copy.result, result_copy.data.str, 0); } if (result.data.ok_flag == BTA_AG_OK_DONE) { bta_ag_send_ok(p_scb); @@ -1801,8 +1785,7 @@ static void bta_ag_hfp_result(tBTA_AG_SCB* p_scb, case BTA_AG_BIND_RES: { /* Find whether ind_id is supported by local device or not */ int local_index = bta_ag_find_hf_ind_by_id(p_scb->local_hf_indicators, - BTA_AG_MAX_NUM_LOCAL_HF_IND, - result.data.ind.id); + BTA_AG_MAX_NUM_LOCAL_HF_IND, result.data.ind.id); if (local_index == -1) { log::warn("Invalid HF Indicator ID {}", result.data.ind.id); return; @@ -1810,21 +1793,18 @@ static void bta_ag_hfp_result(tBTA_AG_SCB* p_scb, /* Find whether ind_id is supported by peer device or not */ int peer_index = bta_ag_find_hf_ind_by_id(p_scb->peer_hf_indicators, - BTA_AG_MAX_NUM_PEER_HF_IND, - result.data.ind.id); + BTA_AG_MAX_NUM_PEER_HF_IND, result.data.ind.id); if (peer_index == -1) { log::warn("Invalid HF Indicator ID {}", result.data.ind.id); return; } else { /* If the current state is different from the one upper layer request change current state and send out the result */ - if (p_scb->local_hf_indicators[local_index].is_enable != - result.data.ind.on_demand) { + if (p_scb->local_hf_indicators[local_index].is_enable != result.data.ind.on_demand) { char buffer[BTA_AG_AT_MAX_LEN] = {0}; char* p = buffer; - p_scb->local_hf_indicators[local_index].is_enable = - result.data.ind.on_demand; + p_scb->local_hf_indicators[local_index].is_enable = result.data.ind.on_demand; p += utl_itoa(result.data.ind.id, p); *p++ = ','; p += utl_itoa(p_scb->local_hf_indicators[local_index].is_enable, p); @@ -1889,8 +1869,7 @@ void bta_ag_send_bcs(tBTA_AG_SCB* p_scb) { codec_uuid = tBTA_AG_UUID_CODEC::UUID_CODEC_LC3; break; default: - log::error("bta_ag_send_bcs: unknown codec {}, use CVSD", - p_scb->sco_codec); + log::error("bta_ag_send_bcs: unknown codec {}, use CVSD", p_scb->sco_codec); codec_uuid = tBTA_AG_UUID_CODEC::UUID_CODEC_CVSD; break; } @@ -1898,8 +1877,7 @@ void bta_ag_send_bcs(tBTA_AG_SCB* p_scb) { /* send +BCS */ log::verbose("send +BCS codec is {}", bta_ag_uuid_codec_text(codec_uuid)); - bta_ag_send_result(p_scb, BTA_AG_LOCAL_RES_BCS, nullptr, - static_cast(codec_uuid)); + bta_ag_send_result(p_scb, BTA_AG_LOCAL_RES_BCS, nullptr, static_cast(codec_uuid)); } /******************************************************************************* @@ -1915,8 +1893,7 @@ bool bta_ag_is_sco_open_allowed(tBTA_AG_SCB* p_scb, const std::string event) { #ifdef __ANDROID__ /* Do not open SCO if 1. the dual mode audio system property is enabled, 2. LEA is active, and 3. LEA is preferred for DUPLEX */ - if (bluetooth::os::GetSystemPropertyBool( - bluetooth::os::kIsDualModeAudioEnabledProperty, false)) { + if (bluetooth::os::GetSystemPropertyBool(bluetooth::os::kIsDualModeAudioEnabledProperty, false)) { if (LeAudioClient::Get()->isDuplexPreferenceLeAudio(p_scb->peer_addr)) { log::info("NOT opening SCO for EVT {} on dual mode device {}", event, p_scb->peer_addr.ToStringForLogging()); @@ -1941,23 +1918,21 @@ bool bta_ag_is_sco_open_allowed(tBTA_AG_SCB* p_scb, const std::string event) { * ******************************************************************************/ void bta_ag_send_ring(tBTA_AG_SCB* p_scb, const tBTA_AG_DATA& /* data */) { - if ((p_scb->conn_service == BTA_AG_HFP) && - p_scb->callsetup_ind != BTA_AG_CALLSETUP_INCOMING) { - log::warn("don't send RING, conn_service={}, callsetup_ind={}", - p_scb->conn_service, p_scb->callsetup_ind); + if ((p_scb->conn_service == BTA_AG_HFP) && p_scb->callsetup_ind != BTA_AG_CALLSETUP_INCOMING) { + log::warn("don't send RING, conn_service={}, callsetup_ind={}", p_scb->conn_service, + p_scb->callsetup_ind); return; } /* send RING */ bta_ag_send_result(p_scb, BTA_AG_LOCAL_RES_RING, nullptr, 0); /* if HFP and clip enabled and clip data send CLIP */ - if (p_scb->conn_service == BTA_AG_HFP && p_scb->clip_enabled && - p_scb->clip[0] != 0) { + if (p_scb->conn_service == BTA_AG_HFP && p_scb->clip_enabled && p_scb->clip[0] != 0) { bta_ag_send_result(p_scb, BTA_AG_LOCAL_RES_CLIP, p_scb->clip, 0); } - bta_sys_start_timer(p_scb->ring_timer, BTA_AG_RING_TIMEOUT_MS, - BTA_AG_RING_TIMEOUT_EVT, bta_ag_scb_to_idx(p_scb)); + bta_sys_start_timer(p_scb->ring_timer, BTA_AG_RING_TIMEOUT_MS, BTA_AG_RING_TIMEOUT_EVT, + bta_ag_scb_to_idx(p_scb)); } /******************************************************************************* @@ -1982,8 +1957,7 @@ void bta_ag_send_qcs(tBTA_AG_SCB* p_scb, tBTA_AG_DATA* p_data) { } log::verbose("send +QCS codec is {}", bta_ag_uuid_codec_text(codec_uuid)); - bta_ag_send_result(p_scb, BTA_AG_LOCAL_RES_QCS, NULL, - static_cast(codec_uuid)); + bta_ag_send_result(p_scb, BTA_AG_LOCAL_RES_QCS, NULL, static_cast(codec_uuid)); } /******************************************************************************* @@ -1996,8 +1970,7 @@ void bta_ag_send_qcs(tBTA_AG_SCB* p_scb, tBTA_AG_DATA* p_data) { * ******************************************************************************/ void bta_ag_send_qac(tBTA_AG_SCB* p_scb, tBTA_AG_DATA* p_data) { - if (!get_swb_codec_status(bluetooth::headset::BTHF_SWB_CODEC_VENDOR_APTX, - &p_scb->peer_addr)) { + if (!get_swb_codec_status(bluetooth::headset::BTHF_SWB_CODEC_VENDOR_APTX, &p_scb->peer_addr)) { log::verbose("send +QAC codecs unsupported"); bta_ag_send_result(p_scb, BTA_AG_LOCAL_RES_QAC, SWB_CODECS_UNSUPPORTED, 0); return; diff --git a/system/bta/ag/bta_ag_int.h b/system/bta/ag/bta_ag_int.h index 908d76dd4bd..65bb14c7773 100644 --- a/system/bta/ag/bta_ag_int.h +++ b/system/bta/ag/bta_ag_int.h @@ -63,9 +63,8 @@ #define BTA_AG_ACP 0 /* accepted connection */ #define BTA_AG_INT 1 /* initiating connection */ -#define BTA_AG_SDP_FEAT_SPEC \ - (BTA_AG_FEAT_3WAY | BTA_AG_FEAT_ECNR | BTA_AG_FEAT_VREC | \ - BTA_AG_FEAT_INBAND | BTA_AG_FEAT_VTAG) +#define BTA_AG_SDP_FEAT_SPEC \ + (BTA_AG_FEAT_3WAY | BTA_AG_FEAT_ECNR | BTA_AG_FEAT_VREC | BTA_AG_FEAT_INBAND | BTA_AG_FEAT_VTAG) /* Timeout for alarm in 2018 toyota camry carkit workaround */ #define BTA_AG_BIND_TIMEOUT_MS 500 @@ -109,12 +108,12 @@ enum { /* Actions to perform after a SCO event */ enum { - BTA_AG_POST_SCO_NONE, /* no action */ - BTA_AG_POST_SCO_CLOSE_RFC, /* close RFCOMM channel after SCO closes */ - BTA_AG_POST_SCO_RING, /* send RING result code after SCO opens */ - BTA_AG_POST_SCO_CALL_CONN, /* send call indicators after SCO opens/closes */ - BTA_AG_POST_SCO_CALL_ORIG, /* send call indicators after SCO closes */ - BTA_AG_POST_SCO_CALL_END, /* send call indicators after SCO closes */ + BTA_AG_POST_SCO_NONE, /* no action */ + BTA_AG_POST_SCO_CLOSE_RFC, /* close RFCOMM channel after SCO closes */ + BTA_AG_POST_SCO_RING, /* send RING result code after SCO opens */ + BTA_AG_POST_SCO_CALL_CONN, /* send call indicators after SCO opens/closes */ + BTA_AG_POST_SCO_CALL_ORIG, /* send call indicators after SCO closes */ + BTA_AG_POST_SCO_CALL_END, /* send call indicators after SCO closes */ BTA_AG_POST_SCO_CALL_END_INCALL /* send call indicators for end call & incoming call after SCO closes */ }; @@ -198,7 +197,7 @@ union tBTA_AG_DATA { * @return true if both unions are equal in memory */ bool operator==(const tBTA_AG_DATA& rhs) const { - return (std::memcmp(this, &rhs, sizeof(tBTA_AG_DATA)) == 0); + return std::memcmp(this, &rhs, sizeof(tBTA_AG_DATA)) == 0; } /** @@ -240,12 +239,7 @@ typedef enum { } tBTA_AG_SCO_APTX_SWB_SETTINGS; /* state machine states */ -typedef enum { - BTA_AG_INIT_ST, - BTA_AG_OPENING_ST, - BTA_AG_OPEN_ST, - BTA_AG_CLOSING_ST -} tBTA_AG_STATE; +typedef enum { BTA_AG_INIT_ST, BTA_AG_OPENING_ST, BTA_AG_OPEN_ST, BTA_AG_CLOSING_ST } tBTA_AG_STATE; /* type for each service control block */ struct tBTA_AG_SCB { @@ -266,81 +260,75 @@ struct tBTA_AG_SCB { uint16_t sco_idx; /* SCO handle */ bool in_use; /* scb in use */ bool dealloc; /* true if service shutting down */ - bool clip_enabled; /* set to true if HF enables CLIP reporting */ - bool ccwa_enabled; /* set to true if HF enables CCWA reporting */ - bool cmer_enabled; /* set to true if HF enables CMER reporting */ - bool cmee_enabled; /* set to true if HF enables CME ERROR reporting */ - bool inband_enabled; /* set to true if inband ring enabled */ - bool nrec_enabled; /* noise reduction & echo canceling */ - bool svc_conn; /* set to true when service level connection up */ - tBTA_AG_STATE state; /* state machine state */ - uint8_t conn_service; /* connected service */ - uint8_t peer_scn; /* peer scn */ - uint8_t app_id; /* application id */ - uint8_t role; /* initiator/acceptor role */ - uint8_t post_sco; /* action to perform after sco event */ - uint8_t call_ind; /* CIEV call indicator value */ - uint8_t callsetup_ind; /* CIEV callsetup indicator value */ - uint8_t service_ind; /* CIEV service indicator value */ - uint8_t signal_ind; /* CIEV signal indicator value */ - uint8_t roam_ind; /* CIEV roam indicator value */ - uint8_t battchg_ind; /* CIEV battery charge indicator value */ - uint8_t callheld_ind; /* CIEV call held indicator value */ - uint32_t bia_masked_out; /* indicators HF does not want us to send */ - alarm_t* bind_timer; /* Timer for toyota camry 2018 carkit workaround */ + bool clip_enabled; /* set to true if HF enables CLIP reporting */ + bool ccwa_enabled; /* set to true if HF enables CCWA reporting */ + bool cmer_enabled; /* set to true if HF enables CMER reporting */ + bool cmee_enabled; /* set to true if HF enables CME ERROR reporting */ + bool inband_enabled; /* set to true if inband ring enabled */ + bool nrec_enabled; /* noise reduction & echo canceling */ + bool svc_conn; /* set to true when service level connection up */ + tBTA_AG_STATE state; /* state machine state */ + uint8_t conn_service; /* connected service */ + uint8_t peer_scn; /* peer scn */ + uint8_t app_id; /* application id */ + uint8_t role; /* initiator/acceptor role */ + uint8_t post_sco; /* action to perform after sco event */ + uint8_t call_ind; /* CIEV call indicator value */ + uint8_t callsetup_ind; /* CIEV callsetup indicator value */ + uint8_t service_ind; /* CIEV service indicator value */ + uint8_t signal_ind; /* CIEV signal indicator value */ + uint8_t roam_ind; /* CIEV roam indicator value */ + uint8_t battchg_ind; /* CIEV battery charge indicator value */ + uint8_t callheld_ind; /* CIEV call held indicator value */ + uint32_t bia_masked_out; /* indicators HF does not want us to send */ + alarm_t* bind_timer; /* Timer for toyota camry 2018 carkit workaround */ alarm_t* collision_timer; alarm_t* ring_timer; alarm_t* codec_negotiation_timer; - bool received_at_bac; /* indicate AT+BAC is received at least once */ - tBTA_AG_PEER_CODEC - disabled_codecs; /* set by app to block certain codecs from being used */ - tBTA_AG_PEER_CODEC peer_codecs; /* codecs for eSCO supported by the peer */ - tBTA_AG_PEER_CODEC sco_codec; /* codecs to be used for eSCO connection */ - tBTA_AG_UUID_CODEC - inuse_codec; /* codec being used for the current SCO connection */ - bool codec_updated; /* set to true whenever the app updates codec type */ - bool codec_fallback; /* If sco nego fails for mSBC, fallback to CVSD */ - bool trying_cvsd_safe_settings; /* set to true whenever we are trying CVSD - safe settings */ - uint8_t retransmission_effort_retries; /* Retry eSCO - with retransmission_effort value*/ - tBTA_AG_SCO_MSBC_SETTINGS codec_msbc_settings; /* settings to be used for the - impending eSCO on WB */ - tBTA_AG_SCO_LC3_SETTINGS codec_lc3_settings; /* settings to be used for the - impending eSCO on SWB */ - tBTA_AG_SCO_CVSD_SETTINGS codec_cvsd_settings; /* settings to be used for the - impending eSCO on CVSD */ - tBTA_AG_SCO_APTX_SWB_SETTINGS - codec_aptx_settings; /* settings to be used for the - aptX Voice SWB eSCO */ - bool is_aptx_swb_codec; /* Flag to determine aptX Voice SWB codec */ - - tBTA_AG_HF_IND - peer_hf_indicators[BTA_AG_MAX_NUM_PEER_HF_IND]; /* Peer supported - HF indicators */ - tBTA_AG_HF_IND - local_hf_indicators[BTA_AG_MAX_NUM_LOCAL_HF_IND]; /* Local supported - HF indicators */ + bool received_at_bac; /* indicate AT+BAC is received at least once */ + tBTA_AG_PEER_CODEC disabled_codecs; /* set by app to block certain codecs from being used */ + tBTA_AG_PEER_CODEC peer_codecs; /* codecs for eSCO supported by the peer */ + tBTA_AG_PEER_CODEC sco_codec; /* codecs to be used for eSCO connection */ + tBTA_AG_UUID_CODEC inuse_codec; /* codec being used for the current SCO connection */ + bool codec_updated; /* set to true whenever the app updates codec type */ + bool codec_fallback; /* If sco nego fails for mSBC, fallback to CVSD */ + bool trying_cvsd_safe_settings; /* set to true whenever we are trying CVSD + safe settings */ + uint8_t retransmission_effort_retries; /* Retry eSCO + with retransmission_effort value*/ + tBTA_AG_SCO_MSBC_SETTINGS codec_msbc_settings; /* settings to be used for the + impending eSCO on WB */ + tBTA_AG_SCO_LC3_SETTINGS codec_lc3_settings; /* settings to be used for the + impending eSCO on SWB */ + tBTA_AG_SCO_CVSD_SETTINGS codec_cvsd_settings; /* settings to be used for the + impending eSCO on CVSD */ + tBTA_AG_SCO_APTX_SWB_SETTINGS codec_aptx_settings; /* settings to be used for the + aptX Voice SWB eSCO */ + bool is_aptx_swb_codec; /* Flag to determine aptX Voice SWB codec */ + + tBTA_AG_HF_IND peer_hf_indicators[BTA_AG_MAX_NUM_PEER_HF_IND]; /* Peer supported + HF indicators */ + tBTA_AG_HF_IND local_hf_indicators[BTA_AG_MAX_NUM_LOCAL_HF_IND]; /* Local supported + HF indicators */ std::string ToString() const { return base::StringPrintf( - "codec_updated=%d, codec_fallback=%d, nrec=%d" - "sco_codec=%d, peer_codec=%d, msbc_settings=%d, lc3_settings=%d, " - "device=%s", - codec_updated, codec_fallback, nrec_enabled, sco_codec, peer_codecs, - codec_msbc_settings, codec_lc3_settings, - ADDRESS_TO_LOGGABLE_CSTR(peer_addr)); + "codec_updated=%d, codec_fallback=%d, nrec=%d" + "sco_codec=%d, peer_codec=%d, msbc_settings=%d, lc3_settings=%d, " + "device=%s", + codec_updated, codec_fallback, nrec_enabled, sco_codec, peer_codecs, + codec_msbc_settings, codec_lc3_settings, ADDRESS_TO_LOGGABLE_CSTR(peer_addr)); } }; /* type for sco data */ typedef struct { tBTM_ESCO_CONN_REQ_EVT_DATA conn_data; /* SCO data for pending conn request */ - tBTA_AG_SCB* p_curr_scb; /* SCB associated with SCO connection */ - tBTA_AG_SCB* p_xfer_scb; /* SCB associated with SCO transfer */ - uint16_t cur_idx; /* SCO handle */ - tBTA_AG_SCO state; /* SCO state variable */ - bool is_local; /* SCO connection initiated locally or remotely */ + tBTA_AG_SCB* p_curr_scb; /* SCB associated with SCO connection */ + tBTA_AG_SCB* p_xfer_scb; /* SCB associated with SCO transfer */ + uint16_t cur_idx; /* SCO handle */ + tBTA_AG_SCO state; /* SCO state variable */ + bool is_local; /* SCO connection initiated locally or remotely */ } tBTA_AG_SCO_CB; /* type for AG control block */ @@ -377,10 +365,8 @@ void bta_ag_api_enable(tBTA_AG_CBACK* p_cback); void bta_ag_api_disable(); void bta_ag_api_set_active_device(const RawAddress& new_active_device); void bta_ag_api_register(tBTA_SERVICE_MASK services, tBTA_AG_FEAT features, - const std::vector& service_names, - uint8_t app_id); -void bta_ag_api_result(uint16_t handle, tBTA_AG_RES result, - const tBTA_AG_RES_DATA& result_data); + const std::vector& service_names, uint8_t app_id); +void bta_ag_api_result(uint16_t handle, tBTA_AG_RES result, const tBTA_AG_RES_DATA& result_data); /* main functions */ void bta_ag_scb_dealloc(tBTA_AG_SCB* p_scb); @@ -390,18 +376,16 @@ uint8_t bta_ag_service_to_idx(tBTA_SERVICE_MASK services); uint16_t bta_ag_idx_by_bdaddr(const RawAddress* peer_addr); bool bta_ag_other_scb_open(tBTA_AG_SCB* p_curr_scb); bool bta_ag_scb_open(tBTA_AG_SCB* p_curr_scb); -void bta_ag_sm_execute(tBTA_AG_SCB* p_scb, uint16_t event, - const tBTA_AG_DATA& data); -void bta_ag_sm_execute_by_handle(uint16_t handle, uint16_t event, - const tBTA_AG_DATA& data); -void bta_ag_collision_cback(tBTA_SYS_CONN_STATUS status, tBTA_SYS_ID id, - uint8_t app_id, const RawAddress& peer_addr); +void bta_ag_sm_execute(tBTA_AG_SCB* p_scb, uint16_t event, const tBTA_AG_DATA& data); +void bta_ag_sm_execute_by_handle(uint16_t handle, uint16_t event, const tBTA_AG_DATA& data); +void bta_ag_collision_cback(tBTA_SYS_CONN_STATUS status, tBTA_SYS_ID id, uint8_t app_id, + const RawAddress& peer_addr); void bta_ag_resume_open(tBTA_AG_SCB* p_scb); const std::string bta_ag_state_str(tBTA_AG_STATE state); /* SDP functions */ -bool bta_ag_add_record(uint16_t service_uuid, const char* p_service_name, - uint8_t scn, tBTA_AG_FEAT features, uint32_t sdp_handle); +bool bta_ag_add_record(uint16_t service_uuid, const char* p_service_name, uint8_t scn, + tBTA_AG_FEAT features, uint32_t sdp_handle); void bta_ag_create_records(tBTA_AG_SCB* p_scb, const tBTA_AG_DATA& data); void bta_ag_del_records(tBTA_AG_SCB* p_scb); bool bta_ag_sdp_find_attr(tBTA_AG_SCB* p_scb, tBTA_SERVICE_MASK service); @@ -424,10 +408,10 @@ void bta_ag_sco_conn_rsp(tBTA_AG_SCB* p_scb, tBTM_ESCO_CONN_REQ_EVT_DATA* data); void bta_ag_create_sco(tBTA_AG_SCB* p_scb, bool is_orig); /* AT command functions */ -void bta_ag_at_hsp_cback(tBTA_AG_SCB* p_scb, uint16_t cmd, uint8_t arg_type, - char* p_arg, char* p_end, int16_t int_arg); -void bta_ag_at_hfp_cback(tBTA_AG_SCB* p_scb, uint16_t cmd, uint8_t arg_type, - char* p_arg, char* p_end, int16_t int_arg); +void bta_ag_at_hsp_cback(tBTA_AG_SCB* p_scb, uint16_t cmd, uint8_t arg_type, char* p_arg, + char* p_end, int16_t int_arg); +void bta_ag_at_hfp_cback(tBTA_AG_SCB* p_scb, uint16_t cmd, uint8_t arg_type, char* p_arg, + char* p_end, int16_t int_arg); void bta_ag_at_err_cback(tBTA_AG_SCB* p_scb, bool unknown, const char* p_arg); bool bta_ag_inband_enabled(tBTA_AG_SCB* p_scb); void bta_ag_send_call_inds(tBTA_AG_SCB* p_scb, tBTA_AG_RES result); @@ -490,8 +474,7 @@ void bta_ag_stream_suspended(); namespace fmt { template <> -struct formatter - : enum_formatter {}; +struct formatter : enum_formatter {}; template <> struct formatter : enum_formatter {}; } // namespace fmt diff --git a/system/bta/ag/bta_ag_main.cc b/system/bta/ag/bta_ag_main.cc index f121af0a89d..e8eb51cd688 100644 --- a/system/bta/ag/bta_ag_main.cc +++ b/system/bta/ag/bta_ag_main.cc @@ -157,8 +157,7 @@ static tBTA_AG_SCB* bta_ag_scb_alloc(void) { /* set up timers */ p_scb->ring_timer = alarm_new("bta_ag.scb_ring_timer"); p_scb->collision_timer = alarm_new("bta_ag.scb_collision_timer"); - p_scb->codec_negotiation_timer = - alarm_new("bta_ag.scb_codec_negotiation_timer"); + p_scb->codec_negotiation_timer = alarm_new("bta_ag.scb_codec_negotiation_timer"); /* reset to CVSD S4 settings as the preferred */ p_scb->codec_cvsd_settings = BTA_AG_SCO_CVSD_SETTINGS_S4; /* set eSCO mSBC setting to T2 as the preferred */ @@ -295,7 +294,7 @@ uint16_t bta_ag_idx_by_bdaddr(const RawAddress* peer_addr) { if (peer_addr != nullptr) { for (uint16_t i = 0; i < BTA_AG_MAX_NUM_CLIENTS; i++, p_scb++) { if (p_scb->in_use && *peer_addr == p_scb->peer_addr) { - return (i + 1); + return i + 1; } } } @@ -318,8 +317,7 @@ uint16_t bta_ag_idx_by_bdaddr(const RawAddress* peer_addr) { bool bta_ag_other_scb_open(tBTA_AG_SCB* p_curr_scb) { tBTA_AG_SCB* p_scb = &bta_ag_cb.scb[0]; for (int i = 0; i < BTA_AG_MAX_NUM_CLIENTS; i++, p_scb++) { - if (p_scb->in_use && p_scb != p_curr_scb && - p_scb->state == BTA_AG_OPEN_ST) { + if (p_scb->in_use && p_scb != p_curr_scb && p_scb->state == BTA_AG_OPEN_ST) { return true; } } @@ -339,8 +337,7 @@ bool bta_ag_other_scb_open(tBTA_AG_SCB* p_curr_scb) { * ******************************************************************************/ bool bta_ag_scb_open(tBTA_AG_SCB* p_curr_scb) { - return p_curr_scb && p_curr_scb->in_use && - p_curr_scb->state == BTA_AG_OPEN_ST; + return p_curr_scb && p_curr_scb->in_use && p_curr_scb->state == BTA_AG_OPEN_ST; } /******************************************************************************* @@ -353,22 +350,20 @@ bool bta_ag_scb_open(tBTA_AG_SCB* p_curr_scb) { * Returns void * ******************************************************************************/ -void bta_ag_collision_cback(tBTA_SYS_CONN_STATUS /* status */, tBTA_SYS_ID id, - uint8_t /* app_id */, const RawAddress& peer_addr) { +void bta_ag_collision_cback(tBTA_SYS_CONN_STATUS /* status */, tBTA_SYS_ID id, uint8_t /* app_id */, + const RawAddress& peer_addr) { /* Check if we have opening scb for the peer device. */ uint16_t handle = bta_ag_idx_by_bdaddr(&peer_addr); tBTA_AG_SCB* p_scb = bta_ag_scb_by_idx(handle); if (p_scb && (p_scb->state == BTA_AG_OPENING_ST)) { if (id == BTA_ID_SYS) { - log::warn("AG found collision (ACL) for handle {} device {}", - unsigned(handle), peer_addr); + log::warn("AG found collision (ACL) for handle {} device {}", unsigned(handle), peer_addr); } else if (id == BTA_ID_AG) { - log::warn("AG found collision (RFCOMM) for handle {} device {}", - unsigned(handle), peer_addr); + log::warn("AG found collision (RFCOMM) for handle {} device {}", unsigned(handle), peer_addr); } else { - log::warn("AG found collision (UNKNOWN) for handle {} device {}", - unsigned(handle), peer_addr); + log::warn("AG found collision (UNKNOWN) for handle {} device {}", unsigned(handle), + peer_addr); } bta_ag_sm_execute(p_scb, BTA_AG_COLLISION_EVT, tBTA_AG_DATA::kEmpty); } @@ -386,8 +381,7 @@ void bta_ag_collision_cback(tBTA_SYS_CONN_STATUS /* status */, tBTA_SYS_ID id, ******************************************************************************/ void bta_ag_resume_open(tBTA_AG_SCB* p_scb) { if (p_scb->state == BTA_AG_INIT_ST) { - log::info("Resume connection to {}, handle{}", p_scb->peer_addr, - bta_ag_scb_to_idx(p_scb)); + log::info("Resume connection to {}, handle{}", p_scb->peer_addr, bta_ag_scb_to_idx(p_scb)); tBTA_AG_DATA open_data = {.api_open = {.bd_addr = p_scb->peer_addr}}; bta_ag_sm_execute(p_scb, BTA_AG_API_OPEN_EVT, open_data); } else { @@ -483,11 +477,9 @@ void bta_ag_api_disable() { * ******************************************************************************/ void bta_ag_api_register(tBTA_SERVICE_MASK services, tBTA_AG_FEAT features, - const std::vector& service_names, - uint8_t app_id) { + const std::vector& service_names, uint8_t app_id) { tBTA_AG_SCB* p_scb = bta_ag_scb_alloc(); - log::debug("bta_ag_api_register: p_scb allocation {}", - p_scb == nullptr ? "failed" : "success"); + log::debug("bta_ag_api_register: p_scb allocation {}", p_scb == nullptr ? "failed" : "success"); if (p_scb) { tBTA_AG_DATA data = {}; data.api_register.features = features; @@ -495,8 +487,7 @@ void bta_ag_api_register(tBTA_SERVICE_MASK services, tBTA_AG_FEAT features, data.api_register.app_id = app_id; for (int i = 0; i < BTA_AG_NUM_IDX; i++) { if (!service_names[i].empty()) { - strlcpy(data.api_register.p_name[i], service_names[i].c_str(), - BTA_SERVICE_NAME_LEN); + strlcpy(data.api_register.p_name[i], service_names[i].c_str(), BTA_SERVICE_NAME_LEN); } else { data.api_register.p_name[i][0] = 0; } @@ -519,8 +510,7 @@ void bta_ag_api_register(tBTA_SERVICE_MASK services, tBTA_AG_FEAT features, * Returns void * ******************************************************************************/ -void bta_ag_api_result(uint16_t handle, tBTA_AG_RES result, - const tBTA_AG_RES_DATA& result_data) { +void bta_ag_api_result(uint16_t handle, tBTA_AG_RES result, const tBTA_AG_RES_DATA& result_data) { tBTA_AG_DATA event_data = {}; event_data.api_result.result = result; event_data.api_result.data = result_data; @@ -528,24 +518,17 @@ void bta_ag_api_result(uint16_t handle, tBTA_AG_RES result, if (handle != BTA_AG_HANDLE_ALL) { p_scb = bta_ag_scb_by_idx(handle); if (p_scb) { - log::debug("Audio gateway event for one client handle:{} scb:{}", handle, - p_scb->ToString()); - bta_ag_sm_execute(p_scb, static_cast(BTA_AG_API_RESULT_EVT), - event_data); + log::debug("Audio gateway event for one client handle:{} scb:{}", handle, p_scb->ToString()); + bta_ag_sm_execute(p_scb, static_cast(BTA_AG_API_RESULT_EVT), event_data); } else { - log::warn( - "Received audio gateway event for unknown AG control block handle:{}", - handle); + log::warn("Received audio gateway event for unknown AG control block handle:{}", handle); } } else { int i; - for (i = 0, p_scb = &bta_ag_cb.scb[0]; i < BTA_AG_MAX_NUM_CLIENTS; - i++, p_scb++) { + for (i = 0, p_scb = &bta_ag_cb.scb[0]; i < BTA_AG_MAX_NUM_CLIENTS; i++, p_scb++) { if (p_scb->in_use && p_scb->svc_conn) { - log::debug("Audio gateway event for all clients scb:{}", - p_scb->ToString()); - bta_ag_sm_execute(p_scb, static_cast(BTA_AG_API_RESULT_EVT), - event_data); + log::debug("Audio gateway event for all clients scb:{}", p_scb->ToString()); + bta_ag_sm_execute(p_scb, static_cast(BTA_AG_API_RESULT_EVT), event_data); } } } @@ -582,8 +565,7 @@ static void bta_ag_better_state_machine(tBTA_AG_SCB* p_scb, uint16_t event, bta_ag_free_db(p_scb, data); break; default: - log::error("unknown event {} at state {}", event, - bta_ag_state_str(p_scb->state)); + log::error("unknown event {} at state {}", event, bta_ag_state_str(p_scb->state)); break; } break; @@ -632,8 +614,7 @@ static void bta_ag_better_state_machine(tBTA_AG_SCB* p_scb, uint16_t event, bta_ag_handle_collision(p_scb, data); break; default: - log::error("unknown event {} at state {}", event, - bta_ag_state_str(p_scb->state)); + log::error("unknown event {} at state {}", event, bta_ag_state_str(p_scb->state)); break; } break; @@ -690,8 +671,7 @@ static void bta_ag_better_state_machine(tBTA_AG_SCB* p_scb, uint16_t event, bta_ag_start_close(p_scb, data); break; default: - log::error("unknown event {} at state {}", event, - bta_ag_state_str(p_scb->state)); + log::error("unknown event {} at state {}", event, bta_ag_state_str(p_scb->state)); break; } break; @@ -723,8 +703,7 @@ static void bta_ag_better_state_machine(tBTA_AG_SCB* p_scb, uint16_t event, bta_ag_free_db(p_scb, data); break; default: - log::error("unknown event {} at state {}", event, - bta_ag_state_str(p_scb->state)); + log::error("unknown event {} at state {}", event, bta_ag_state_str(p_scb->state)); break; } break; @@ -741,40 +720,36 @@ static void bta_ag_better_state_machine(tBTA_AG_SCB* p_scb, uint16_t event, * Returns void * ******************************************************************************/ -void bta_ag_sm_execute(tBTA_AG_SCB* p_scb, uint16_t event, - const tBTA_AG_DATA& data) { +void bta_ag_sm_execute(tBTA_AG_SCB* p_scb, uint16_t event, const tBTA_AG_DATA& data) { uint16_t previous_event = event; tBTA_AG_STATE previous_state = p_scb->state; log::debug( - "Execute AG event handle:0x{:04x} bd_addr:{} state:{}[0x{:02x}] " - "event:{}[0x{:04x}] result:{}[0x{:02x}]", - bta_ag_scb_to_idx(p_scb), p_scb->peer_addr, - bta_ag_state_str(p_scb->state), static_cast(p_scb->state), - bta_ag_evt_str(event), event, bta_ag_res_str(data.api_result.result), - data.api_result.result); + "Execute AG event handle:0x{:04x} bd_addr:{} state:{}[0x{:02x}] " + "event:{}[0x{:04x}] result:{}[0x{:02x}]", + bta_ag_scb_to_idx(p_scb), p_scb->peer_addr, bta_ag_state_str(p_scb->state), + static_cast(p_scb->state), bta_ag_evt_str(event), event, + bta_ag_res_str(data.api_result.result), data.api_result.result); bta_ag_better_state_machine(p_scb, event, data); if (p_scb->state != previous_state) { log::debug( - "State changed handle:0x{:04x} bd_addr:{} " - "state_change:{}[0x{:02x}]->{}[0x{:02x}] event:{}[0x{:04x}] " - "result:{}[0x{:02x}]", - bta_ag_scb_to_idx(p_scb), p_scb->peer_addr, - bta_ag_state_str(previous_state), static_cast(previous_state), - bta_ag_state_str(p_scb->state), static_cast(p_scb->state), - bta_ag_evt_str(previous_event), previous_event, - bta_ag_res_str(data.api_result.result), data.api_result.result); + "State changed handle:0x{:04x} bd_addr:{} " + "state_change:{}[0x{:02x}]->{}[0x{:02x}] event:{}[0x{:04x}] " + "result:{}[0x{:02x}]", + bta_ag_scb_to_idx(p_scb), p_scb->peer_addr, bta_ag_state_str(previous_state), + static_cast(previous_state), bta_ag_state_str(p_scb->state), + static_cast(p_scb->state), bta_ag_evt_str(previous_event), previous_event, + bta_ag_res_str(data.api_result.result), data.api_result.result); } } -void bta_ag_sm_execute_by_handle(uint16_t handle, uint16_t event, - const tBTA_AG_DATA& data) { +void bta_ag_sm_execute_by_handle(uint16_t handle, uint16_t event, const tBTA_AG_DATA& data) { tBTA_AG_SCB* p_scb = bta_ag_scb_by_idx(handle); if (p_scb) { - log::debug("AG state machine event:{}[0x{:04x}] handle:0x{:04x}", - bta_ag_evt_str(event), event, handle); + log::debug("AG state machine event:{}[0x{:04x}] handle:0x{:04x}", bta_ag_evt_str(event), event, + handle); bta_ag_sm_execute(p_scb, event, data); } } @@ -790,12 +765,10 @@ bool bta_ag_hdl_event(const BT_HDR_RIGID* p_msg) { switch (p_msg->event) { case BTA_AG_RING_TIMEOUT_EVT: case BTA_AG_SVC_TIMEOUT_EVT: - bta_ag_sm_execute_by_handle(p_msg->layer_specific, p_msg->event, - tBTA_AG_DATA::kEmpty); + bta_ag_sm_execute_by_handle(p_msg->layer_specific, p_msg->event, tBTA_AG_DATA::kEmpty); break; default: - log::fatal("bad event {} layer_specific={}", p_msg->event, - p_msg->layer_specific); + log::fatal("bad event {} layer_specific={}", p_msg->event, p_msg->layer_specific); break; } return true; diff --git a/system/bta/ag/bta_ag_rfc.cc b/system/bta/ag/bta_ag_rfc.cc index d201c0761c2..653af93d84e 100644 --- a/system/bta/ag/bta_ag_rfc.cc +++ b/system/bta/ag/bta_ag_rfc.cc @@ -54,14 +54,14 @@ void bta_ag_mgmt_cback_6(const tPORT_RESULT code, uint16_t port_handle); /* rfcomm callback function tables */ typedef tPORT_CALLBACK* tBTA_AG_PORT_CBACK; -const tBTA_AG_PORT_CBACK bta_ag_port_cback_tbl[] = { - bta_ag_port_cback_1, bta_ag_port_cback_2, bta_ag_port_cback_3, - bta_ag_port_cback_4, bta_ag_port_cback_5, bta_ag_port_cback_6}; +const tBTA_AG_PORT_CBACK bta_ag_port_cback_tbl[] = {bta_ag_port_cback_1, bta_ag_port_cback_2, + bta_ag_port_cback_3, bta_ag_port_cback_4, + bta_ag_port_cback_5, bta_ag_port_cback_6}; typedef tPORT_MGMT_CALLBACK* tBTA_AG_PORT_MGMT_CBACK; -const tBTA_AG_PORT_MGMT_CBACK bta_ag_mgmt_cback_tbl[] = { - bta_ag_mgmt_cback_1, bta_ag_mgmt_cback_2, bta_ag_mgmt_cback_3, - bta_ag_mgmt_cback_4, bta_ag_mgmt_cback_5, bta_ag_mgmt_cback_6}; +const tBTA_AG_PORT_MGMT_CBACK bta_ag_mgmt_cback_tbl[] = {bta_ag_mgmt_cback_1, bta_ag_mgmt_cback_2, + bta_ag_mgmt_cback_3, bta_ag_mgmt_cback_4, + bta_ag_mgmt_cback_5, bta_ag_mgmt_cback_6}; /******************************************************************************* * @@ -73,25 +73,21 @@ const tBTA_AG_PORT_MGMT_CBACK bta_ag_mgmt_cback_tbl[] = { * Returns void * ******************************************************************************/ -static void bta_ag_port_cback(uint32_t /* code */, uint16_t port_handle, - uint16_t handle) { +static void bta_ag_port_cback(uint32_t /* code */, uint16_t port_handle, uint16_t handle) { tBTA_AG_SCB* p_scb = bta_ag_scb_by_idx(handle); if (p_scb != nullptr) { /* ignore port events for port handles other than connected handle */ if (port_handle != p_scb->conn_handle) { - log::error( - "ag_port_cback ignoring handle:{} conn_handle = {} other handle = {}", - port_handle, p_scb->conn_handle, handle); + log::error("ag_port_cback ignoring handle:{} conn_handle = {} other handle = {}", port_handle, + p_scb->conn_handle, handle); return; } if (!bta_ag_scb_open(p_scb)) { - log::error( - "rfcomm data on an unopened control block {} peer_addr {} state {}", - handle, p_scb->peer_addr, bta_ag_state_str(p_scb->state)); + log::error("rfcomm data on an unopened control block {} peer_addr {} state {}", handle, + p_scb->peer_addr, bta_ag_state_str(p_scb->state)); } - do_in_main_thread( - FROM_HERE, base::BindOnce(&bta_ag_sm_execute_by_handle, handle, - BTA_AG_RFC_DATA_EVT, tBTA_AG_DATA::kEmpty)); + do_in_main_thread(FROM_HERE, base::BindOnce(&bta_ag_sm_execute_by_handle, handle, + BTA_AG_RFC_DATA_EVT, tBTA_AG_DATA::kEmpty)); } } @@ -105,20 +101,18 @@ static void bta_ag_port_cback(uint32_t /* code */, uint16_t port_handle, * Returns void * ******************************************************************************/ -static void bta_ag_mgmt_cback(const tPORT_RESULT code, uint16_t port_handle, - uint16_t handle) { +static void bta_ag_mgmt_cback(const tPORT_RESULT code, uint16_t port_handle, uint16_t handle) { tBTA_AG_SCB* p_scb = bta_ag_scb_by_idx(handle); - log::verbose("code={}, port_handle={}, scb_handle={}, p_scb=0x{}", code, - port_handle, handle, fmt::ptr(p_scb)); + log::verbose("code={}, port_handle={}, scb_handle={}, p_scb=0x{}", code, port_handle, handle, + fmt::ptr(p_scb)); if (p_scb == nullptr) { - log::warn("cannot find scb, code={}, port_handle={}, handle={}", code, - port_handle, handle); + log::warn("cannot find scb, code={}, port_handle={}, handle={}", code, port_handle, handle); return; } /* ignore close event for port handles other than connected handle */ if ((code != PORT_SUCCESS) && (port_handle != p_scb->conn_handle)) { - log::warn("ignore open failure for unmatched port_handle {}, scb_handle={}", - port_handle, handle); + log::warn("ignore open failure for unmatched port_handle {}, scb_handle={}", port_handle, + handle); return; } uint16_t event; @@ -139,10 +133,8 @@ static void bta_ag_mgmt_cback(const tPORT_RESULT code, uint16_t port_handle, } } if (!found_handle) { - log::error( - "port opened successfully, but port_handle {} is unknown, " - "scb_handle={}", - port_handle, handle); + log::error("port opened successfully, but port_handle {} is unknown, scb_handle={}", + port_handle, handle); return; } event = BTA_AG_RFC_OPEN_EVT; @@ -155,8 +147,7 @@ static void bta_ag_mgmt_cback(const tPORT_RESULT code, uint16_t port_handle, tBTA_AG_DATA data = {}; data.rfc.port_handle = port_handle; - do_in_main_thread(FROM_HERE, base::BindOnce(&bta_ag_sm_execute_by_handle, - handle, event, data)); + do_in_main_thread(FROM_HERE, base::BindOnce(&bta_ag_sm_execute_by_handle, handle, event, data)); } /******************************************************************************* @@ -220,19 +211,16 @@ void bta_ag_port_cback_6(uint32_t code, uint16_t port_handle) { ******************************************************************************/ void bta_ag_setup_port(tBTA_AG_SCB* p_scb, uint16_t handle) { int port_callback_index = bta_ag_scb_to_idx(p_scb) - 1; - log::assert_that(port_callback_index >= 0, - "invalid callback index, handle={}, bd_addr={}", handle, + log::assert_that(port_callback_index >= 0, "invalid callback index, handle={}, bd_addr={}", + handle, ADDRESS_TO_LOGGABLE_STR(p_scb->peer_addr)); + log::assert_that(port_callback_index < static_cast(sizeof(bta_ag_port_cback_tbl) / + sizeof(bta_ag_port_cback_tbl[0])), + "callback index out of bound, handle={}, bd_addr={}", handle, ADDRESS_TO_LOGGABLE_STR(p_scb->peer_addr)); - log::assert_that( - port_callback_index < static_cast(sizeof(bta_ag_port_cback_tbl) / - sizeof(bta_ag_port_cback_tbl[0])), - "callback index out of bound, handle={}, bd_addr={}", handle, - ADDRESS_TO_LOGGABLE_STR(p_scb->peer_addr)); - if (PORT_SetEventMaskAndCallback( - handle, BTA_AG_PORT_EV_MASK, - bta_ag_port_cback_tbl[port_callback_index]) != PORT_SUCCESS) { - log::warn("Unable to set RFCOMM event and callback mask peer:{} handle:{}", - p_scb->peer_addr, handle); + if (PORT_SetEventMaskAndCallback(handle, BTA_AG_PORT_EV_MASK, + bta_ag_port_cback_tbl[port_callback_index]) != PORT_SUCCESS) { + log::warn("Unable to set RFCOMM event and callback mask peer:{} handle:{}", p_scb->peer_addr, + handle); } } @@ -253,30 +241,28 @@ void bta_ag_start_servers(tBTA_AG_SCB* p_scb, tBTA_SERVICE_MASK services) { if (services & 1) { int management_callback_index = bta_ag_scb_to_idx(p_scb) - 1; log::assert_that(management_callback_index >= 0, - "invalid callback index, services=0x{:x}, bd_addr={}", - services, ADDRESS_TO_LOGGABLE_STR(p_scb->peer_addr)); + "invalid callback index, services=0x{:x}, bd_addr={}", services, + ADDRESS_TO_LOGGABLE_STR(p_scb->peer_addr)); log::assert_that( - management_callback_index < - static_cast(sizeof(bta_ag_mgmt_cback_tbl) / - sizeof(bta_ag_mgmt_cback_tbl[0])), - "callback index out of bound, services=0x{:x}, bd_addr={}", services, - ADDRESS_TO_LOGGABLE_STR(p_scb->peer_addr)); + management_callback_index < static_cast(sizeof(bta_ag_mgmt_cback_tbl) / + sizeof(bta_ag_mgmt_cback_tbl[0])), + "callback index out of bound, services=0x{:x}, bd_addr={}", services, + ADDRESS_TO_LOGGABLE_STR(p_scb->peer_addr)); int status = RFCOMM_CreateConnectionWithSecurity( - bta_ag_uuid[i], bta_ag_cb.profile[i].scn, true, BTA_AG_MTU, - RawAddress::kAny, &(p_scb->serv_handle[i]), - bta_ag_mgmt_cback_tbl[management_callback_index], - BTA_SEC_AUTHENTICATE | BTA_SEC_ENCRYPT); + bta_ag_uuid[i], bta_ag_cb.profile[i].scn, true, BTA_AG_MTU, RawAddress::kAny, + &(p_scb->serv_handle[i]), bta_ag_mgmt_cback_tbl[management_callback_index], + BTA_SEC_AUTHENTICATE | BTA_SEC_ENCRYPT); if (status == PORT_SUCCESS) { bta_ag_setup_port(p_scb, p_scb->serv_handle[i]); } else { /* TODO: CR#137125 to handle to error properly */ log::error( - "RFCOMM_CreateConnectionWithSecurity ERROR {}, p_scb={}, " - "services=0x{:x}, mgmt_cback_index={}", - status, fmt::ptr(p_scb), services, management_callback_index); + "RFCOMM_CreateConnectionWithSecurity ERROR {}, p_scb={}, " + "services=0x{:x}, mgmt_cback_index={}", + status, fmt::ptr(p_scb), services, management_callback_index); } - log::verbose("p_scb=0x{}, services=0x{:04x}, mgmt_cback_index={}", - fmt::ptr(p_scb), services, management_callback_index); + log::verbose("p_scb=0x{}, services=0x{:04x}, mgmt_cback_index={}", fmt::ptr(p_scb), services, + management_callback_index); } } } @@ -319,7 +305,9 @@ bool bta_ag_is_server_closed(tBTA_AG_SCB* p_scb) { bool is_closed = true; for (xx = 0; xx < BTA_AG_NUM_IDX; xx++) { - if (p_scb->serv_handle[xx] != 0) is_closed = false; + if (p_scb->serv_handle[xx] != 0) { + is_closed = false; + } } return is_closed; @@ -338,19 +326,16 @@ bool bta_ag_is_server_closed(tBTA_AG_SCB* p_scb) { void bta_ag_rfc_do_open(tBTA_AG_SCB* p_scb, const tBTA_AG_DATA& data) { int management_callback_index = bta_ag_scb_to_idx(p_scb) - 1; int status = RFCOMM_CreateConnectionWithSecurity( - bta_ag_uuid[p_scb->conn_service], p_scb->peer_scn, false, BTA_AG_MTU, - p_scb->peer_addr, &(p_scb->conn_handle), - bta_ag_mgmt_cback_tbl[management_callback_index], - BTA_SEC_AUTHENTICATE | BTA_SEC_ENCRYPT); - log::verbose("p_scb=0x{}, conn_handle={}, mgmt_cback_index={}, status={}", - fmt::ptr(p_scb), p_scb->conn_handle, management_callback_index, - status); + bta_ag_uuid[p_scb->conn_service], p_scb->peer_scn, false, BTA_AG_MTU, p_scb->peer_addr, + &(p_scb->conn_handle), bta_ag_mgmt_cback_tbl[management_callback_index], + BTA_SEC_AUTHENTICATE | BTA_SEC_ENCRYPT); + log::verbose("p_scb=0x{}, conn_handle={}, mgmt_cback_index={}, status={}", fmt::ptr(p_scb), + p_scb->conn_handle, management_callback_index, status); if (status == PORT_SUCCESS) { bta_ag_setup_port(p_scb, p_scb->conn_handle); } else { /* RFCOMM create connection failed; send ourselves RFCOMM close event */ - log::error("RFCOMM_CreateConnection ERROR {} for {}", status, - p_scb->peer_addr); + log::error("RFCOMM_CreateConnection ERROR {} for {}", status, p_scb->peer_addr); bta_ag_sm_execute(p_scb, BTA_AG_RFC_CLOSE_EVT, data); } } @@ -369,17 +354,15 @@ void bta_ag_rfc_do_close(tBTA_AG_SCB* p_scb, const tBTA_AG_DATA& /* data */) { log::info("p_scb->conn_handle: 0x{:04x}", p_scb->conn_handle); if (p_scb->conn_handle) { if (RFCOMM_RemoveConnection(p_scb->conn_handle) != PORT_SUCCESS) { - log::warn("Unable to remove RFCOMM connection handle:0x{:04x}", - p_scb->conn_handle); + log::warn("Unable to remove RFCOMM connection handle:0x{:04x}", p_scb->conn_handle); } } else { /* Close API was called while AG is in Opening state. */ /* Need to trigger the state machine to send callback to the app */ /* and move back to INIT state. */ - do_in_main_thread( - FROM_HERE, - base::BindOnce(&bta_ag_sm_execute_by_handle, bta_ag_scb_to_idx(p_scb), - BTA_AG_RFC_CLOSE_EVT, tBTA_AG_DATA::kEmpty)); + do_in_main_thread(FROM_HERE, + base::BindOnce(&bta_ag_sm_execute_by_handle, bta_ag_scb_to_idx(p_scb), + BTA_AG_RFC_CLOSE_EVT, tBTA_AG_DATA::kEmpty)); /* Cancel SDP if it had been started. */ /* diff --git a/system/bta/ag/bta_ag_sco.cc b/system/bta/ag/bta_ag_sco.cc index 07bd94c4422..a17a71ce4a5 100644 --- a/system/bta/ag/bta_ag_sco.cc +++ b/system/bta/ag/bta_ag_sco.cc @@ -57,25 +57,24 @@ using namespace bluetooth; #define BTA_AG_CODEC_NEGOTIATION_TIMEOUT_MS (3 * 1000) /* 3 seconds */ #endif -#define BTM_VOICE_SETTING_CVSD \ - ((uint16_t)(HCI_INP_CODING_LINEAR | HCI_INP_DATA_FMT_2S_COMPLEMENT | \ - HCI_INP_SAMPLE_SIZE_16BIT | HCI_AIR_CODING_FORMAT_CVSD)) +#define BTM_VOICE_SETTING_CVSD \ + ((uint16_t)(HCI_INP_CODING_LINEAR | HCI_INP_DATA_FMT_2S_COMPLEMENT | HCI_INP_SAMPLE_SIZE_16BIT | \ + HCI_AIR_CODING_FORMAT_CVSD)) -#define BTM_VOICE_SETTING_TRANS \ - ((uint16_t)(HCI_INP_CODING_LINEAR | HCI_INP_DATA_FMT_2S_COMPLEMENT | \ - HCI_INP_SAMPLE_SIZE_16BIT | HCI_AIR_CODING_FORMAT_TRANSPNT)) +#define BTM_VOICE_SETTING_TRANS \ + ((uint16_t)(HCI_INP_CODING_LINEAR | HCI_INP_DATA_FMT_2S_COMPLEMENT | HCI_INP_SAMPLE_SIZE_16BIT | \ + HCI_AIR_CODING_FORMAT_TRANSPNT)) static bool sco_allowed = true; static RawAddress active_device_addr = {}; static std::unique_ptr hfp_client_interface; static std::unique_ptr hfp_offload_interface; static std::unordered_map sco_config_map; -static std::unordered_map - codec_coding_format_map{ +static std::unordered_map codec_coding_format_map{ {tBTA_AG_UUID_CODEC::UUID_CODEC_LC3, ESCO_CODING_FORMAT_LC3}, {tBTA_AG_UUID_CODEC::UUID_CODEC_MSBC, ESCO_CODING_FORMAT_MSBC}, {tBTA_AG_UUID_CODEC::UUID_CODEC_CVSD, ESCO_CODING_FORMAT_CVSD}, - }; +}; /* sco events */ enum { @@ -165,13 +164,14 @@ static void bta_ag_sco_conn_cback(uint16_t sco_idx) { /* Check if SLC is up */ handle = bta_ag_idx_by_bdaddr(BTM_ReadScoBdAddr(sco_idx)); p_scb = bta_ag_scb_by_idx(handle); - if (p_scb && !p_scb->svc_conn) handle = 0; + if (p_scb && !p_scb->svc_conn) { + handle = 0; + } } if (handle != 0) { - do_in_main_thread( - FROM_HERE, base::BindOnce(&bta_ag_sm_execute_by_handle, handle, - BTA_AG_SCO_OPEN_EVT, tBTA_AG_DATA::kEmpty)); + do_in_main_thread(FROM_HERE, base::BindOnce(&bta_ag_sm_execute_by_handle, handle, + BTA_AG_SCO_OPEN_EVT, tBTA_AG_DATA::kEmpty)); } else { /* no match found; disconnect sco, init sco variables */ bta_ag_cb.sco.p_curr_scb = nullptr; @@ -197,107 +197,85 @@ static void bta_ag_sco_disc_cback(uint16_t sco_idx) { log::debug("sco_idx: 0x{:x} sco.state:{}", sco_idx, sco_state_text(static_cast(bta_ag_cb.sco.state))); - log::debug("scb[0] in_use:{} sco_idx: 0x{:x} ag state:{}", - bta_ag_cb.scb[0].in_use, bta_ag_cb.scb[0].sco_idx, - bta_ag_state_str(bta_ag_cb.scb[0].state)); - log::debug("scb[1] in_use:{} sco_idx:0x{:x} ag state:{}", - bta_ag_cb.scb[1].in_use, bta_ag_cb.scb[1].sco_idx, - bta_ag_state_str(bta_ag_cb.scb[1].state)); + log::debug("scb[0] in_use:{} sco_idx: 0x{:x} ag state:{}", bta_ag_cb.scb[0].in_use, + bta_ag_cb.scb[0].sco_idx, bta_ag_state_str(bta_ag_cb.scb[0].state)); + log::debug("scb[1] in_use:{} sco_idx:0x{:x} ag state:{}", bta_ag_cb.scb[1].in_use, + bta_ag_cb.scb[1].sco_idx, bta_ag_state_str(bta_ag_cb.scb[1].state)); /* match callback to scb */ if (bta_ag_cb.sco.p_curr_scb != nullptr && bta_ag_cb.sco.p_curr_scb->in_use) { /* We only care about callbacks for the active SCO */ if (bta_ag_cb.sco.p_curr_scb->sco_idx != sco_idx) { - if (bta_ag_cb.sco.p_curr_scb->sco_idx != 0xFFFF) return; + if (bta_ag_cb.sco.p_curr_scb->sco_idx != 0xFFFF) { + return; + } } handle = bta_ag_scb_to_idx(bta_ag_cb.sco.p_curr_scb); } if (handle != 0) { - const bool aptx_voice = - is_hfp_aptx_voice_enabled() && - (bta_ag_cb.sco.p_curr_scb->is_aptx_swb_codec == true) && - (bta_ag_cb.sco.p_curr_scb->inuse_codec == - tBTA_AG_UUID_CODEC::BTA_AG_SCO_APTX_SWB_SETTINGS_Q0); + const bool aptx_voice = is_hfp_aptx_voice_enabled() && + (bta_ag_cb.sco.p_curr_scb->is_aptx_swb_codec == true) && + (bta_ag_cb.sco.p_curr_scb->inuse_codec == + tBTA_AG_UUID_CODEC::BTA_AG_SCO_APTX_SWB_SETTINGS_Q0); log::verbose("aptx_voice={}, inuse_codec={}", aptx_voice, bta_ag_uuid_codec_text(bta_ag_cb.sco.p_curr_scb->inuse_codec)); /* Restore settings */ - if (bta_ag_cb.sco.p_curr_scb->inuse_codec == - tBTA_AG_UUID_CODEC::UUID_CODEC_MSBC || - bta_ag_cb.sco.p_curr_scb->inuse_codec == - tBTA_AG_UUID_CODEC::UUID_CODEC_LC3 || - aptx_voice || + if (bta_ag_cb.sco.p_curr_scb->inuse_codec == tBTA_AG_UUID_CODEC::UUID_CODEC_MSBC || + bta_ag_cb.sco.p_curr_scb->inuse_codec == tBTA_AG_UUID_CODEC::UUID_CODEC_LC3 || aptx_voice || (com::android::bluetooth::flags::fix_hfp_qual_1_9() && - bta_ag_cb.sco.p_curr_scb->inuse_codec == - tBTA_AG_UUID_CODEC::UUID_CODEC_CVSD && - bta_ag_cb.sco.p_curr_scb->codec_cvsd_settings != - BTA_AG_SCO_CVSD_SETTINGS_S1)) { + bta_ag_cb.sco.p_curr_scb->inuse_codec == tBTA_AG_UUID_CODEC::UUID_CODEC_CVSD && + bta_ag_cb.sco.p_curr_scb->codec_cvsd_settings != BTA_AG_SCO_CVSD_SETTINGS_S1)) { /* Bypass vendor specific and voice settings if enhanced eSCO supported */ if (!(bluetooth::shim::GetController()->IsSupported( - bluetooth::hci::OpCode::ENHANCED_SETUP_SYNCHRONOUS_CONNECTION))) { - get_btm_client_interface().sco.BTM_WriteVoiceSettings( - BTM_VOICE_SETTING_CVSD); + bluetooth::hci::OpCode::ENHANCED_SETUP_SYNCHRONOUS_CONNECTION))) { + get_btm_client_interface().sco.BTM_WriteVoiceSettings(BTM_VOICE_SETTING_CVSD); } /* If SCO open was initiated by AG and failed for mSBC T2, try mSBC T1 * 'Safe setting' first. If T1 also fails, try CVSD * same operations for LC3 settings */ if (bta_ag_sco_is_opening(bta_ag_cb.sco.p_curr_scb) && - (!com::android::bluetooth::flags::fix_hfp_qual_1_9() || - bta_ag_cb.sco.is_local)) { + (!com::android::bluetooth::flags::fix_hfp_qual_1_9() || bta_ag_cb.sco.is_local)) { /* Don't bother to edit |p_curr_scb->state| because it is in * |BTA_AG_OPEN_ST|, which has the same value as |BTA_AG_SCO_CODEC_ST| */ if (!com::android::bluetooth::flags::fix_hfp_qual_1_9()) { bta_ag_cb.sco.p_curr_scb->state = (tBTA_AG_STATE)BTA_AG_SCO_CODEC_ST; } - if (bta_ag_cb.sco.p_curr_scb->inuse_codec == - tBTA_AG_UUID_CODEC::UUID_CODEC_LC3) { - if (bta_ag_cb.sco.p_curr_scb->codec_lc3_settings == - BTA_AG_SCO_LC3_SETTINGS_T2) { - log::warn( - "eSCO/SCO failed to open, falling back to LC3 T1 settings"); - bta_ag_cb.sco.p_curr_scb->codec_lc3_settings = - BTA_AG_SCO_LC3_SETTINGS_T1; + if (bta_ag_cb.sco.p_curr_scb->inuse_codec == tBTA_AG_UUID_CODEC::UUID_CODEC_LC3) { + if (bta_ag_cb.sco.p_curr_scb->codec_lc3_settings == BTA_AG_SCO_LC3_SETTINGS_T2) { + log::warn("eSCO/SCO failed to open, falling back to LC3 T1 settings"); + bta_ag_cb.sco.p_curr_scb->codec_lc3_settings = BTA_AG_SCO_LC3_SETTINGS_T1; } else { log::warn("eSCO/SCO failed to open, falling back to CVSD settings"); - bta_ag_cb.sco.p_curr_scb->inuse_codec = - tBTA_AG_UUID_CODEC::UUID_CODEC_CVSD; + bta_ag_cb.sco.p_curr_scb->inuse_codec = tBTA_AG_UUID_CODEC::UUID_CODEC_CVSD; bta_ag_cb.sco.p_curr_scb->codec_fallback = true; } - } else if (bta_ag_cb.sco.p_curr_scb->inuse_codec == - tBTA_AG_UUID_CODEC::UUID_CODEC_MSBC || + } else if (bta_ag_cb.sco.p_curr_scb->inuse_codec == tBTA_AG_UUID_CODEC::UUID_CODEC_MSBC || aptx_voice) { - if (bta_ag_cb.sco.p_curr_scb->codec_msbc_settings == - BTA_AG_SCO_MSBC_SETTINGS_T2) { - log::warn( - "eSCO/SCO failed to open, falling back to mSBC T1 settings"); - bta_ag_cb.sco.p_curr_scb->codec_msbc_settings = - BTA_AG_SCO_MSBC_SETTINGS_T1; + if (bta_ag_cb.sco.p_curr_scb->codec_msbc_settings == BTA_AG_SCO_MSBC_SETTINGS_T2) { + log::warn("eSCO/SCO failed to open, falling back to mSBC T1 settings"); + bta_ag_cb.sco.p_curr_scb->codec_msbc_settings = BTA_AG_SCO_MSBC_SETTINGS_T1; } else { log::warn("eSCO/SCO failed to open, falling back to CVSD"); - bta_ag_cb.sco.p_curr_scb->inuse_codec = - tBTA_AG_UUID_CODEC::UUID_CODEC_CVSD; + bta_ag_cb.sco.p_curr_scb->inuse_codec = tBTA_AG_UUID_CODEC::UUID_CODEC_CVSD; bta_ag_cb.sco.p_curr_scb->codec_fallback = true; } } else { // Entering this block implies // - |fix_hfp_qual_1_9| is enabled, AND // - we just failed CVSD S2+. - log::warn( - "eSCO/SCO failed to open, falling back to CVSD S1 settings"); - bta_ag_cb.sco.p_curr_scb->codec_cvsd_settings = - BTA_AG_SCO_CVSD_SETTINGS_S1; + log::warn("eSCO/SCO failed to open, falling back to CVSD S1 settings"); + bta_ag_cb.sco.p_curr_scb->codec_cvsd_settings = BTA_AG_SCO_CVSD_SETTINGS_S1; bta_ag_cb.sco.p_curr_scb->trying_cvsd_safe_settings = true; } } } else if (bta_ag_sco_is_opening(bta_ag_cb.sco.p_curr_scb) && - (!com::android::bluetooth::flags::fix_hfp_qual_1_9() || - bta_ag_cb.sco.is_local)) { - if (com::android::bluetooth::flags:: - retry_esco_with_zero_retransmission_effort() && + (!com::android::bluetooth::flags::fix_hfp_qual_1_9() || bta_ag_cb.sco.is_local)) { + if (com::android::bluetooth::flags::retry_esco_with_zero_retransmission_effort() && bta_ag_cb.sco.p_curr_scb->retransmission_effort_retries == 0) { bta_ag_cb.sco.p_curr_scb->retransmission_effort_retries++; if (!com::android::bluetooth::flags::fix_hfp_qual_1_9()) { @@ -314,9 +292,8 @@ static void bta_ag_sco_disc_cback(uint16_t sco_idx) { bta_ag_cb.sco.p_curr_scb->inuse_codec = tBTA_AG_UUID_CODEC::UUID_CODEC_NONE; - do_in_main_thread( - FROM_HERE, base::BindOnce(&bta_ag_sm_execute_by_handle, handle, - BTA_AG_SCO_CLOSE_EVT, tBTA_AG_DATA::kEmpty)); + do_in_main_thread(FROM_HERE, base::BindOnce(&bta_ag_sm_execute_by_handle, handle, + BTA_AG_SCO_CLOSE_EVT, tBTA_AG_DATA::kEmpty)); } else { /* no match found */ log::verbose("no scb for ag_sco_disc_cback"); @@ -345,8 +322,7 @@ static bool bta_ag_remove_sco(tBTA_AG_SCB* p_scb, bool only_active) { if (p_scb->sco_idx != BTM_INVALID_SCO_INDEX) { if (!only_active || p_scb->sco_idx == bta_ag_cb.sco.cur_idx) { tBTM_STATUS status = BTM_RemoveSco(p_scb->sco_idx); - log::debug("Removed SCO index:0x{:04x} status:{}", p_scb->sco_idx, - btm_status_text(status)); + log::debug("Removed SCO index:0x{:04x} status:{}", p_scb->sco_idx, btm_status_text(status)); if (status == BTM_CMD_STARTED) { /* SCO is connected; set current control block */ bta_ag_cb.sco.p_curr_scb = p_scb; @@ -370,15 +346,13 @@ static bool bta_ag_remove_sco(tBTA_AG_SCB* p_scb, bool only_active) { * Returns void * ******************************************************************************/ -static void bta_ag_esco_connreq_cback(tBTM_ESCO_EVT event, - tBTM_ESCO_EVT_DATA* p_data) { +static void bta_ag_esco_connreq_cback(tBTM_ESCO_EVT event, tBTM_ESCO_EVT_DATA* p_data) { /* Only process connection requests */ if (event == BTM_ESCO_CONN_REQ_EVT) { uint16_t sco_inx = p_data->conn_evt.sco_inx; const RawAddress* remote_bda = BTM_ReadScoBdAddr(sco_inx); tBTA_AG_SCB* p_scb = bta_ag_scb_by_idx(bta_ag_idx_by_bdaddr(remote_bda)); - if (remote_bda && bta_ag_sco_is_active_device(*remote_bda) && p_scb && - p_scb->svc_conn) { + if (remote_bda && bta_ag_sco_is_active_device(*remote_bda) && p_scb && p_scb->svc_conn) { p_scb->sco_idx = sco_inx; /* If no other SCO active, allow this one */ @@ -397,9 +371,7 @@ static void bta_ag_esco_connreq_cback(tBTM_ESCO_EVT event, bta_ag_cb.sco.state = BTA_AG_SCO_OPEN_XFER_ST; if (!bta_ag_remove_sco(bta_ag_cb.sco.p_curr_scb, true)) { - log::error( - "Nothing to remove,so accept Conn Request(sco_inx 0x{:04x})", - sco_inx); + log::error("Nothing to remove,so accept Conn Request(sco_inx 0x{:04x})", sco_inx); bta_ag_cb.sco.p_xfer_scb = nullptr; bta_ag_cb.sco.state = BTA_AG_SCO_LISTEN_ST; @@ -407,11 +379,9 @@ static void bta_ag_esco_connreq_cback(tBTM_ESCO_EVT event, } } } else { - log::warn( - "reject incoming SCO connection, remote_bda={}, active_bda={}, " - "current_bda={}", - remote_bda ? *remote_bda : RawAddress::kEmpty, active_device_addr, - p_scb ? p_scb->peer_addr : RawAddress::kEmpty); + log::warn("reject incoming SCO connection, remote_bda={}, active_bda={}, current_bda={}", + remote_bda ? *remote_bda : RawAddress::kEmpty, active_device_addr, + p_scb ? p_scb->peer_addr : RawAddress::kEmpty); BTM_EScoConnRsp(p_data->conn_evt.sco_inx, HCI_ERR_HOST_REJECT_RESOURCES, (enh_esco_params_t*)nullptr); } @@ -452,20 +422,17 @@ void bta_ag_create_sco(tBTA_AG_SCB* p_scb, bool is_orig) { tBTA_AG_UUID_CODEC esco_codec = tBTA_AG_UUID_CODEC::UUID_CODEC_CVSD; if (!bta_ag_sco_is_active_device(p_scb->peer_addr)) { - log::warn("device {} is not active, active_device={}", p_scb->peer_addr, - active_device_addr); - if (bta_ag_cb.sco.p_curr_scb != nullptr && - bta_ag_cb.sco.p_curr_scb->in_use && p_scb == bta_ag_cb.sco.p_curr_scb) { - do_in_main_thread(FROM_HERE, base::BindOnce(&bta_ag_sm_execute, p_scb, - BTA_AG_SCO_CLOSE_EVT, + log::warn("device {} is not active, active_device={}", p_scb->peer_addr, active_device_addr); + if (bta_ag_cb.sco.p_curr_scb != nullptr && bta_ag_cb.sco.p_curr_scb->in_use && + p_scb == bta_ag_cb.sco.p_curr_scb) { + do_in_main_thread(FROM_HERE, base::BindOnce(&bta_ag_sm_execute, p_scb, BTA_AG_SCO_CLOSE_EVT, tBTA_AG_DATA::kEmpty)); } return; } /* Make sure this SCO handle is not already in use */ if (p_scb->sco_idx != BTM_INVALID_SCO_INDEX) { - log::error("device {}, index 0x{:04x} already in use!", p_scb->peer_addr, - p_scb->sco_idx); + log::error("device {}, index 0x{:04x} already in use!", p_scb->peer_addr, p_scb->sco_idx); return; } @@ -475,8 +442,7 @@ void bta_ag_create_sco(tBTA_AG_SCB* p_scb, bool is_orig) { } if (is_hfp_aptx_voice_enabled()) { - if ((p_scb->sco_codec == BTA_AG_SCO_APTX_SWB_SETTINGS_Q0) && - !p_scb->codec_fallback) { + if ((p_scb->sco_codec == BTA_AG_SCO_APTX_SWB_SETTINGS_Q0) && !p_scb->codec_fallback) { esco_codec = tBTA_AG_UUID_CODEC ::BTA_AG_SCO_APTX_SWB_SETTINGS_Q0; } } @@ -551,8 +517,7 @@ void bta_ag_create_sco(tBTA_AG_SCB* p_scb, bool is_orig) { updateCodecParametersFromProviderInfo(esco_codec, params); - if (com::android::bluetooth::flags:: - retry_esco_with_zero_retransmission_effort() && + if (com::android::bluetooth::flags::retry_esco_with_zero_retransmission_effort() && p_scb->retransmission_effort_retries == 1) { log::info("change retransmission_effort to 0, retry"); p_scb->retransmission_effort_retries++; @@ -567,8 +532,7 @@ void bta_ag_create_sco(tBTA_AG_SCB* p_scb, bool is_orig) { if (is_orig) { bta_ag_cb.sco.is_local = true; /* Set eSCO Mode */ - if (get_btm_client_interface().sco.BTM_SetEScoMode(¶ms) != - BTM_SUCCESS) { + if (get_btm_client_interface().sco.BTM_SetEScoMode(¶ms) != BTM_SUCCESS) { log::warn("Unable to set ESCO mode"); } bta_ag_cb.sco.p_curr_scb = p_scb; @@ -582,7 +546,7 @@ void bta_ag_create_sco(tBTA_AG_SCB* p_scb, bool is_orig) { /* Bypass voice settings if enhanced SCO setup command is supported */ if (!(bluetooth::shim::GetController()->IsSupported( - bluetooth::hci::OpCode::ENHANCED_SETUP_SYNCHRONOUS_CONNECTION))) { + bluetooth::hci::OpCode::ENHANCED_SETUP_SYNCHRONOUS_CONNECTION))) { if (esco_codec == tBTA_AG_UUID_CODEC::UUID_CODEC_MSBC || esco_codec == tBTA_AG_UUID_CODEC::UUID_CODEC_LC3) { get_btm_client_interface().sco.BTM_WriteVoiceSettings(BTM_VOICE_SETTING_TRANS); @@ -591,9 +555,8 @@ void bta_ag_create_sco(tBTA_AG_SCB* p_scb, bool is_orig) { } } - if (BTM_CreateSco(&p_scb->peer_addr, true, params.packet_types, - &p_scb->sco_idx, bta_ag_sco_conn_cback, - bta_ag_sco_disc_cback) == BTM_CMD_STARTED) { + if (BTM_CreateSco(&p_scb->peer_addr, true, params.packet_types, &p_scb->sco_idx, + bta_ag_sco_conn_cback, bta_ag_sco_disc_cback) == BTM_CMD_STARTED) { /* Initiating the connection, set the current sco handle */ bta_ag_cb.sco.cur_idx = p_scb->sco_idx; /* Configure input/output data. */ @@ -601,22 +564,21 @@ void bta_ag_create_sco(tBTA_AG_SCB* p_scb, bool is_orig) { log::verbose("initiated SCO connection"); } - log::debug("Initiating AG SCO inx 0x{:04x}, pkt types 0x{:04x}", - p_scb->sco_idx, params.packet_types); + log::debug("Initiating AG SCO inx 0x{:04x}, pkt types 0x{:04x}", p_scb->sco_idx, + params.packet_types); } else { /* Not initiating, go to listen mode */ - tBTM_STATUS btm_status = BTM_CreateSco( - &p_scb->peer_addr, false, params.packet_types, &p_scb->sco_idx, - bta_ag_sco_conn_cback, bta_ag_sco_disc_cback); + tBTM_STATUS btm_status = + BTM_CreateSco(&p_scb->peer_addr, false, params.packet_types, &p_scb->sco_idx, + bta_ag_sco_conn_cback, bta_ag_sco_disc_cback); if (btm_status == BTM_CMD_STARTED) { if (get_btm_client_interface().sco.BTM_RegForEScoEvts( - p_scb->sco_idx, bta_ag_esco_connreq_cback) != BTM_SUCCESS) { + p_scb->sco_idx, bta_ag_esco_connreq_cback) != BTM_SUCCESS) { log::warn("Unable to register for ESCO events"); } } - log::debug("Listening AG SCO inx 0x{:04x} status:{} pkt types 0x{:04x}", - p_scb->sco_idx, btm_status_text(btm_status), - params.packet_types); + log::debug("Listening AG SCO inx 0x{:04x} status:{} pkt types 0x{:04x}", p_scb->sco_idx, + btm_status_text(btm_status), params.packet_types); } log::debug("AFTER {}", p_scb->ToString()); } @@ -701,33 +663,29 @@ void bta_ag_codec_negotiate(tBTA_AG_SCB* p_scb) { log::info("Assume CVSD by default due to mask mismatch"); p_scb->sco_codec = BTM_SCO_CODEC_CVSD; } - const bool aptx_voice = - is_hfp_aptx_voice_enabled() && - (get_swb_codec_status(bluetooth::headset::BTHF_SWB_CODEC_VENDOR_APTX, - &p_scb->peer_addr) || - p_scb->is_aptx_swb_codec); - log::verbose( - "aptx_voice={}, is_aptx_swb_codec={}, Q0 codec supported={}", aptx_voice, - p_scb->is_aptx_swb_codec, - (p_scb->peer_codecs & BTA_AG_SCO_APTX_SWB_SETTINGS_Q0_MASK) != 0); - - if (((p_scb->codec_updated || p_scb->codec_fallback) && - (p_scb->features & BTA_AG_FEAT_CODEC) && + const bool aptx_voice = is_hfp_aptx_voice_enabled() && + (get_swb_codec_status(bluetooth::headset::BTHF_SWB_CODEC_VENDOR_APTX, + &p_scb->peer_addr) || + p_scb->is_aptx_swb_codec); + log::verbose("aptx_voice={}, is_aptx_swb_codec={}, Q0 codec supported={}", aptx_voice, + p_scb->is_aptx_swb_codec, + (p_scb->peer_codecs & BTA_AG_SCO_APTX_SWB_SETTINGS_Q0_MASK) != 0); + + if (((p_scb->codec_updated || p_scb->codec_fallback) && (p_scb->features & BTA_AG_FEAT_CODEC) && (p_scb->peer_features & BTA_AG_PEER_FEAT_CODEC)) || (aptx_voice)) { log::info("Starting codec negotiation"); /* Change the power mode to Active until SCO open is completed. */ bta_sys_busy(BTA_ID_AG, p_scb->app_id, p_scb->peer_addr); - if (get_swb_codec_status(bluetooth::headset::BTHF_SWB_CODEC_VENDOR_APTX, - &p_scb->peer_addr) && + if (get_swb_codec_status(bluetooth::headset::BTHF_SWB_CODEC_VENDOR_APTX, &p_scb->peer_addr) && (p_scb->peer_codecs & BTA_AG_SCO_APTX_SWB_SETTINGS_Q0_MASK)) { if (p_scb->is_aptx_swb_codec == false) { p_scb->sco_codec = BTA_AG_SCO_APTX_SWB_SETTINGS_Q0; p_scb->is_aptx_swb_codec = true; } - log::verbose("Sending +QCS, sco_codec={}, is_aptx_swb_codec={}", - p_scb->sco_codec, p_scb->is_aptx_swb_codec); + log::verbose("Sending +QCS, sco_codec={}, is_aptx_swb_codec={}", p_scb->sco_codec, + p_scb->is_aptx_swb_codec); /* Send +QCS to the peer */ bta_ag_send_qcs(p_scb, NULL); } else { @@ -735,15 +693,14 @@ void bta_ag_codec_negotiate(tBTA_AG_SCB* p_scb) { p_scb->sco_codec = BTM_SCO_CODEC_MSBC; p_scb->is_aptx_swb_codec = false; } - log::verbose("Sending +BCS, sco_codec={}, is_aptx_swb_codec={}", - p_scb->sco_codec, p_scb->is_aptx_swb_codec); + log::verbose("Sending +BCS, sco_codec={}, is_aptx_swb_codec={}", p_scb->sco_codec, + p_scb->is_aptx_swb_codec); /* Send +BCS to the peer */ bta_ag_send_bcs(p_scb); } /* Start timer to handle timeout */ - alarm_set_on_mloop(p_scb->codec_negotiation_timer, - BTA_AG_CODEC_NEGOTIATION_TIMEOUT_MS, + alarm_set_on_mloop(p_scb->codec_negotiation_timer, BTA_AG_CODEC_NEGOTIATION_TIMEOUT_MS, bta_ag_codec_negotiation_timer_cback, p_scb); } else { /* use same codec type as previous SCO connection, skip codec negotiation */ @@ -755,10 +712,8 @@ void bta_ag_codec_negotiate(tBTA_AG_SCB* p_scb) { static void bta_ag_sco_event(tBTA_AG_SCB* p_scb, uint8_t event) { tBTA_AG_SCO_CB* p_sco = &bta_ag_cb.sco; uint8_t previous_state = p_sco->state; - log::info("device:{} index:0x{:04x} state:{}[{}] event:{}[{}]", - p_scb->peer_addr, p_scb->sco_idx, - bta_ag_sco_state_str(p_sco->state), p_sco->state, - bta_ag_sco_evt_str(event), event); + log::info("device:{} index:0x{:04x} state:{}[{}] event:{}[{}]", p_scb->peer_addr, p_scb->sco_idx, + bta_ag_sco_state_str(p_sco->state), p_sco->state, bta_ag_sco_evt_str(event), event); switch (p_sco->state) { case BTA_AG_SCO_SHUTDOWN_ST: @@ -770,8 +725,8 @@ static void bta_ag_sco_event(tBTA_AG_SCB* p_scb, uint8_t event) { break; default: - log::warn("BTA_AG_SCO_SHUTDOWN_ST: Ignoring event {}[{}]", - bta_ag_sco_evt_str(event), event); + log::warn("BTA_AG_SCO_SHUTDOWN_ST: Ignoring event {}[{}]", bta_ag_sco_evt_str(event), + event); break; } break; @@ -796,7 +751,9 @@ static void bta_ag_sco_event(tBTA_AG_SCB* p_scb, uint8_t event) { /* remove listening connection */ bta_ag_remove_sco(p_scb, false); - if (p_scb == p_sco->p_curr_scb) p_sco->p_curr_scb = nullptr; + if (p_scb == p_sco->p_curr_scb) { + p_sco->p_curr_scb = nullptr; + } /* If last SCO instance then finish shutting down */ if (!bta_ag_other_scb_open(p_scb)) { @@ -807,8 +764,8 @@ static void bta_ag_sco_event(tBTA_AG_SCB* p_scb, uint8_t event) { case BTA_AG_SCO_CLOSE_E: /* remove listening connection */ /* Ignore the event. Keep listening SCO for the active SLC */ - log::warn("BTA_AG_SCO_LISTEN_ST: Ignoring event {}[{}]", - bta_ag_sco_evt_str(event), event); + log::warn("BTA_AG_SCO_LISTEN_ST: Ignoring event {}[{}]", bta_ag_sco_evt_str(event), + event); break; case BTA_AG_SCO_CONN_CLOSE_E: @@ -818,8 +775,8 @@ static void bta_ag_sco_event(tBTA_AG_SCB* p_scb, uint8_t event) { break; default: - log::warn("BTA_AG_SCO_LISTEN_ST: Ignoring event {}[{}]", - bta_ag_sco_evt_str(event), event); + log::warn("BTA_AG_SCO_LISTEN_ST: Ignoring event {}[{}]", bta_ag_sco_evt_str(event), + event); break; } break; @@ -847,7 +804,9 @@ static void bta_ag_sco_event(tBTA_AG_SCB* p_scb, uint8_t event) { /* remove listening connection */ bta_ag_remove_sco(p_scb, false); - if (p_scb == p_sco->p_curr_scb) p_sco->p_curr_scb = nullptr; + if (p_scb == p_sco->p_curr_scb) { + p_sco->p_curr_scb = nullptr; + } /* If last SCO instance then finish shutting down */ if (!bta_ag_other_scb_open(p_scb)) { @@ -856,12 +815,13 @@ static void bta_ag_sco_event(tBTA_AG_SCB* p_scb, uint8_t event) { break; case BTA_AG_SCO_CLOSE_E: - if (bluetooth::common::init_flags:: - sco_codec_timeout_clear_is_enabled()) { + if (bluetooth::common::init_flags::sco_codec_timeout_clear_is_enabled()) { /* remove listening connection */ bta_ag_remove_sco(p_scb, false); - if (p_scb == p_sco->p_curr_scb) p_sco->p_curr_scb = nullptr; + if (p_scb == p_sco->p_curr_scb) { + p_sco->p_curr_scb = nullptr; + } bta_ag_create_sco(p_scb, false); } @@ -876,8 +836,7 @@ static void bta_ag_sco_event(tBTA_AG_SCB* p_scb, uint8_t event) { break; default: - log::warn("BTA_AG_SCO_CODEC_ST: Ignoring event {}[{}]", - bta_ag_sco_evt_str(event), event); + log::warn("BTA_AG_SCO_CODEC_ST: Ignoring event {}[{}]", bta_ag_sco_evt_str(event), event); break; } break; @@ -913,8 +872,9 @@ static void bta_ag_sco_event(tBTA_AG_SCB* p_scb, uint8_t event) { if (p_scb != p_sco->p_curr_scb) { /* remove listening connection */ bta_ag_remove_sco(p_scb, false); - } else + } else { p_sco->state = BTA_AG_SCO_SHUTTING_ST; + } break; @@ -929,8 +889,8 @@ static void bta_ag_sco_event(tBTA_AG_SCB* p_scb, uint8_t event) { break; default: - log::warn("BTA_AG_SCO_OPENING_ST: Ignoring event {}[{}]", - bta_ag_sco_evt_str(event), event); + log::warn("BTA_AG_SCO_OPENING_ST: Ignoring event {}[{}]", bta_ag_sco_evt_str(event), + event); break; } break; @@ -953,8 +913,9 @@ static void bta_ag_sco_event(tBTA_AG_SCB* p_scb, uint8_t event) { if (p_scb != p_sco->p_curr_scb) { /* remove listening connection */ bta_ag_remove_sco(p_scb, false); - } else + } else { p_sco->state = BTA_AG_SCO_SHUTTING_ST; + } break; @@ -972,8 +933,8 @@ static void bta_ag_sco_event(tBTA_AG_SCB* p_scb, uint8_t event) { break; default: - log::warn("BTA_AG_SCO_OPEN_CL_ST: Ignoring event {}[{}]", - bta_ag_sco_evt_str(event), event); + log::warn("BTA_AG_SCO_OPEN_CL_ST: Ignoring event {}[{}]", bta_ag_sco_evt_str(event), + event); break; } break; @@ -1008,8 +969,8 @@ static void bta_ag_sco_event(tBTA_AG_SCB* p_scb, uint8_t event) { break; default: - log::warn("BTA_AG_SCO_OPEN_XFER_ST: Ignoring event {}[{}]", - bta_ag_sco_evt_str(event), event); + log::warn("BTA_AG_SCO_OPEN_XFER_ST: Ignoring event {}[{}]", bta_ag_sco_evt_str(event), + event); break; } break; @@ -1058,8 +1019,7 @@ static void bta_ag_sco_event(tBTA_AG_SCB* p_scb, uint8_t event) { break; default: - log::warn("BTA_AG_SCO_OPEN_ST: Ignoring event {}[{}]", - bta_ag_sco_evt_str(event), event); + log::warn("BTA_AG_SCO_OPEN_ST: Ignoring event {}[{}]", bta_ag_sco_evt_str(event), event); break; } break; @@ -1089,8 +1049,9 @@ static void bta_ag_sco_event(tBTA_AG_SCB* p_scb, uint8_t event) { if (p_scb != p_sco->p_curr_scb) { /* remove listening connection */ bta_ag_remove_sco(p_scb, false); - } else + } else { p_sco->state = BTA_AG_SCO_SHUTTING_ST; + } break; @@ -1102,8 +1063,8 @@ static void bta_ag_sco_event(tBTA_AG_SCB* p_scb, uint8_t event) { break; default: - log::warn("BTA_AG_SCO_CLOSING_ST: Ignoring event {}[{}]", - bta_ag_sco_evt_str(event), event); + log::warn("BTA_AG_SCO_CLOSING_ST: Ignoring event {}[{}]", bta_ag_sco_evt_str(event), + event); break; } break; @@ -1132,8 +1093,8 @@ static void bta_ag_sco_event(tBTA_AG_SCB* p_scb, uint8_t event) { break; default: - log::warn("BTA_AG_SCO_CLOSE_OP_ST: Ignoring event {}[{}]", - bta_ag_sco_evt_str(event), event); + log::warn("BTA_AG_SCO_CLOSE_OP_ST: Ignoring event {}[{}]", bta_ag_sco_evt_str(event), + event); break; } break; @@ -1177,8 +1138,8 @@ static void bta_ag_sco_event(tBTA_AG_SCB* p_scb, uint8_t event) { } default: - log::warn("BTA_AG_SCO_CLOSE_XFER_ST: Ignoring event {}[{}]", - bta_ag_sco_evt_str(event), event); + log::warn("BTA_AG_SCO_CLOSE_XFER_ST: Ignoring event {}[{}]", bta_ag_sco_evt_str(event), + event); break; } break; @@ -1235,8 +1196,8 @@ static void bta_ag_sco_event(tBTA_AG_SCB* p_scb, uint8_t event) { break; default: - log::warn("BTA_AG_SCO_SHUTTING_ST: Ignoring event {}[{}]", - bta_ag_sco_evt_str(event), event); + log::warn("BTA_AG_SCO_SHUTTING_ST: Ignoring event {}[{}]", bta_ag_sco_evt_str(event), + event); break; } break; @@ -1246,11 +1207,10 @@ static void bta_ag_sco_event(tBTA_AG_SCB* p_scb, uint8_t event) { } if (p_sco->state != previous_state) { log::warn( - "SCO_state_change: [{}(0x{:02x})]->[{}(0x{:02x})] after event " - "[{}(0x{:02x})]", - bta_ag_sco_state_str(previous_state), previous_state, - bta_ag_sco_state_str(p_sco->state), p_sco->state, - bta_ag_sco_evt_str(event), event); + "SCO_state_change: [{}(0x{:02x})]->[{}(0x{:02x})] after event " + "[{}(0x{:02x})]", + bta_ag_sco_state_str(previous_state), previous_state, + bta_ag_sco_state_str(p_sco->state), p_sco->state, bta_ag_sco_evt_str(event), event); } } @@ -1265,8 +1225,7 @@ static void bta_ag_sco_event(tBTA_AG_SCB* p_scb, uint8_t event) { * ******************************************************************************/ bool bta_ag_sco_is_open(tBTA_AG_SCB* p_scb) { - return ((bta_ag_cb.sco.state == BTA_AG_SCO_OPEN_ST) && - (bta_ag_cb.sco.p_curr_scb == p_scb)); + return (bta_ag_cb.sco.state == BTA_AG_SCO_OPEN_ST) && (bta_ag_cb.sco.p_curr_scb == p_scb); } /******************************************************************************* @@ -1281,8 +1240,7 @@ bool bta_ag_sco_is_open(tBTA_AG_SCB* p_scb) { * ******************************************************************************/ bool bta_ag_sco_is_opening(tBTA_AG_SCB* p_scb) { - return ((bta_ag_cb.sco.state == BTA_AG_SCO_OPENING_ST) && - (bta_ag_cb.sco.p_curr_scb == p_scb)); + return (bta_ag_cb.sco.state == BTA_AG_SCO_OPENING_ST) && (bta_ag_cb.sco.p_curr_scb == p_scb); } /******************************************************************************* @@ -1317,14 +1275,12 @@ void bta_ag_sco_open(tBTA_AG_SCB* p_scb, const tBTA_AG_DATA& data) { } p_scb->disabled_codecs = data.api_audio_open.disabled_codecs; - log::info("disabled_codecs = {}, sco_codec = {}", p_scb->disabled_codecs, - p_scb->sco_codec); + log::info("disabled_codecs = {}, sco_codec = {}", p_scb->disabled_codecs, p_scb->sco_codec); if (p_scb->disabled_codecs & p_scb->sco_codec) { tBTA_AG_PEER_CODEC updated_codec = BTM_SCO_CODEC_NONE; - if (hfp_hal_interface::get_swb_supported() && - (p_scb->peer_codecs & BTM_SCO_CODEC_LC3) && + if (hfp_hal_interface::get_swb_supported() && (p_scb->peer_codecs & BTM_SCO_CODEC_LC3) && !(p_scb->disabled_codecs & BTM_SCO_CODEC_LC3)) { updated_codec = BTM_SCO_CODEC_LC3; } else if ((p_scb->peer_codecs & BTM_SCO_CODEC_MSBC) && @@ -1340,8 +1296,7 @@ void bta_ag_sco_open(tBTA_AG_SCB* p_scb, const tBTA_AG_DATA& data) { /* if another scb using sco, this is a transfer */ if (bta_ag_cb.sco.p_curr_scb && bta_ag_cb.sco.p_curr_scb != p_scb) { - log::info("transfer {} -> {}", bta_ag_cb.sco.p_curr_scb->peer_addr, - p_scb->peer_addr); + log::info("transfer {} -> {}", bta_ag_cb.sco.p_curr_scb->peer_addr, p_scb->peer_addr); bta_ag_sco_event(p_scb, BTA_AG_SCO_XFER_E); } else { /* else it is an open */ @@ -1364,8 +1319,7 @@ void bta_ag_sco_close(tBTA_AG_SCB* p_scb, const tBTA_AG_DATA& /* data */) { /* if scb is in use */ /* sco_idx is not allocated in SCO_CODEC_ST, still need to move to listen * state. */ - if ((p_scb->sco_idx != BTM_INVALID_SCO_INDEX) || - (bta_ag_cb.sco.state == BTA_AG_SCO_CODEC_ST)) { + if ((p_scb->sco_idx != BTM_INVALID_SCO_INDEX) || (bta_ag_cb.sco.state == BTA_AG_SCO_CODEC_ST)) { log::verbose("bta_ag_sco_close: sco_inx = {}", p_scb->sco_idx); bta_ag_sco_event(p_scb, BTA_AG_SCO_CLOSE_E); } @@ -1384,14 +1338,12 @@ void bta_ag_sco_close(tBTA_AG_SCB* p_scb, const tBTA_AG_DATA& /* data */) { void bta_ag_sco_codec_nego(tBTA_AG_SCB* p_scb, bool result) { if (result) { /* Subsequent SCO connection will skip codec negotiation */ - log::info("Succeeded for index 0x{:04x}, device {}", p_scb->sco_idx, - p_scb->peer_addr); + log::info("Succeeded for index 0x{:04x}, device {}", p_scb->sco_idx, p_scb->peer_addr); p_scb->codec_updated = false; bta_ag_sco_event(p_scb, BTA_AG_SCO_CN_DONE_E); } else { /* codec negotiation failed */ - log::info("Failed for index 0x{:04x}, device {}", p_scb->sco_idx, - p_scb->peer_addr); + log::info("Failed for index 0x{:04x}, device {}", p_scb->sco_idx, p_scb->peer_addr); bta_ag_sco_event(p_scb, BTA_AG_SCO_CLOSE_E); } } @@ -1433,15 +1385,14 @@ void bta_ag_sco_conn_open(tBTA_AG_SCB* p_scb, const tBTA_AG_DATA& /* data */) { log::error("sco_config_map does not have inuse_codec={}", bta_ag_uuid_codec_text(p_scb->inuse_codec)); } else { - is_controller_codec = - sco_config_map[p_scb->inuse_codec].useControllerCodec; + is_controller_codec = sco_config_map[p_scb->inuse_codec].useControllerCodec; } hfp::offload_config config{ - .sco_codec = p_scb->inuse_codec, - .connection_handle = p_scb->conn_handle, - .is_controller_codec = is_controller_codec, - .is_nrec = p_scb->nrec_enabled, + .sco_codec = p_scb->inuse_codec, + .connection_handle = p_scb->conn_handle, + .is_controller_codec = is_controller_codec, + .is_nrec = p_scb->nrec_enabled, }; hfp_offload_interface->UpdateAudioConfigToHal(config); } @@ -1473,11 +1424,10 @@ void bta_ag_sco_conn_close(tBTA_AG_SCB* p_scb, const tBTA_AG_DATA& /* data */) { /* clear current scb */ bta_ag_cb.sco.p_curr_scb = nullptr; p_scb->sco_idx = BTM_INVALID_SCO_INDEX; - const bool aptx_voice = is_hfp_aptx_voice_enabled() && - p_scb->codec_fallback && + const bool aptx_voice = is_hfp_aptx_voice_enabled() && p_scb->codec_fallback && (p_scb->sco_codec == BTA_AG_SCO_APTX_SWB_SETTINGS_Q0); - log::verbose("aptx_voice={}, codec_fallback={:#x}, sco_codec={:#x}", - aptx_voice, p_scb->codec_fallback, p_scb->sco_codec); + log::verbose("aptx_voice={}, codec_fallback={:#x}, sco_codec={:#x}", aptx_voice, + p_scb->codec_fallback, p_scb->sco_codec); /* codec_fallback is set when AG is initiator and connection failed for mSBC. * OR if codec is msbc and T2 settings failed, then retry Safe T1 settings @@ -1488,8 +1438,7 @@ void bta_ag_sco_conn_close(tBTA_AG_SCB* p_scb, const tBTA_AG_DATA& /* data */) { p_scb->codec_msbc_settings == BTA_AG_SCO_MSBC_SETTINGS_T1) || (p_scb->sco_codec == BTM_SCO_CODEC_LC3 && p_scb->codec_lc3_settings == BTA_AG_SCO_LC3_SETTINGS_T1) || - (com::android::bluetooth::flags:: - retry_esco_with_zero_retransmission_effort() && + (com::android::bluetooth::flags::retry_esco_with_zero_retransmission_effort() && p_scb->retransmission_effort_retries == 1) || aptx_voice || (com::android::bluetooth::flags::fix_hfp_qual_1_9() && @@ -1532,15 +1481,13 @@ void bta_ag_sco_conn_close(tBTA_AG_SCB* p_scb, const tBTA_AG_DATA& /* data */) { * Returns void * ******************************************************************************/ -void bta_ag_sco_conn_rsp(tBTA_AG_SCB* p_scb, - tBTM_ESCO_CONN_REQ_EVT_DATA* p_data) { +void bta_ag_sco_conn_rsp(tBTA_AG_SCB* p_scb, tBTM_ESCO_CONN_REQ_EVT_DATA* p_data) { bta_ag_cb.sco.is_local = false; - log::verbose( - "eSCO {}, state {}", - bluetooth::shim::GetController()->IsSupported( - bluetooth::hci::OpCode::ENHANCED_SETUP_SYNCHRONOUS_CONNECTION), - bta_ag_cb.sco.state); + log::verbose("eSCO {}, state {}", + bluetooth::shim::GetController()->IsSupported( + bluetooth::hci::OpCode::ENHANCED_SETUP_SYNCHRONOUS_CONNECTION), + bta_ag_cb.sco.state); if (bta_ag_cb.sco.state == BTA_AG_SCO_LISTEN_ST || bta_ag_cb.sco.state == BTA_AG_SCO_CLOSE_XFER_ST || @@ -1574,8 +1521,9 @@ void bta_ag_sco_conn_rsp(tBTA_AG_SCB* p_scb, // HFP v1.8 5.7.3 CVSD coding tSCO_CONN* p_sco = NULL; - if (p_scb->sco_idx < BTM_MAX_SCO_LINKS) + if (p_scb->sco_idx < BTM_MAX_SCO_LINKS) { p_sco = &btm_cb.sco_cb.sco_db[p_scb->sco_idx]; + } if (p_sco && (p_sco->esco.data.link_type == BTM_LINK_TYPE_SCO || !btm_peer_supports_esco_ev3(p_sco->esco.data.bd_addr))) { params = esco_parameters_for_codec(SCO_CODEC_CVSD_D1, offload); @@ -1585,13 +1533,9 @@ void bta_ag_sco_conn_rsp(tBTA_AG_SCB* p_scb, log::verbose("listening for SCO connection"); } -bool bta_ag_get_sco_offload_enabled() { - return hfp_hal_interface::get_offload_enabled(); -} +bool bta_ag_get_sco_offload_enabled() { return hfp_hal_interface::get_offload_enabled(); } -void bta_ag_set_sco_offload_enabled(bool value) { - hfp_hal_interface::enable_offload(value); -} +void bta_ag_set_sco_offload_enabled(bool value) { hfp_hal_interface::enable_offload(value); } void bta_ag_set_sco_allowed(bool value) { sco_allowed = value; @@ -1616,8 +1560,7 @@ void bta_ag_stream_suspended() { const RawAddress& bta_ag_get_active_device() { return active_device_addr; } void bta_clear_active_device() { - log::debug("Set bta active device to null, current active device:{}", - active_device_addr); + log::debug("Set bta active device to null, current active device:{}", active_device_addr); if (bta_ag_is_sco_managed_by_audio()) { if (hfp_offload_interface && !active_device_addr.IsEmpty()) { hfp_offload_interface->StopSession(); @@ -1627,8 +1570,7 @@ void bta_clear_active_device() { } void bta_ag_api_set_active_device(const RawAddress& new_active_device) { - log::info("active_device_addr{}, new_active_device:{}", active_device_addr, - new_active_device); + log::info("active_device_addr{}, new_active_device:{}", active_device_addr, new_active_device); if (new_active_device.IsEmpty()) { log::error("empty device"); return; @@ -1644,7 +1586,7 @@ void bta_ag_api_set_active_device(const RawAddress& new_active_device) { if (hfp_client_interface && !hfp_offload_interface) { hfp_offload_interface = std::unique_ptr( - hfp_client_interface->GetOffload(get_main_thread())); + hfp_client_interface->GetOffload(get_main_thread())); if (!hfp_offload_interface) { log::warn("could not get offload interface"); } diff --git a/system/bta/ag/bta_ag_sdp.cc b/system/bta/ag/bta_ag_sdp.cc index 38795cd99cd..25c3dd729cc 100644 --- a/system/bta/ag/bta_ag_sdp.cc +++ b/system/bta/ag/bta_ag_sdp.cc @@ -70,9 +70,9 @@ void bta_ag_sdp_cback_6(const RawAddress& bd_addr, tSDP_RESULT); /* SDP callback function table */ typedef tSDP_DISC_CMPL_CB* tBTA_AG_SDP_CBACK; -const tBTA_AG_SDP_CBACK bta_ag_sdp_cback_tbl[] = { - bta_ag_sdp_cback_1, bta_ag_sdp_cback_2, bta_ag_sdp_cback_3, - bta_ag_sdp_cback_4, bta_ag_sdp_cback_5, bta_ag_sdp_cback_6}; +const tBTA_AG_SDP_CBACK bta_ag_sdp_cback_tbl[] = {bta_ag_sdp_cback_1, bta_ag_sdp_cback_2, + bta_ag_sdp_cback_3, bta_ag_sdp_cback_4, + bta_ag_sdp_cback_5, bta_ag_sdp_cback_6}; /******************************************************************************* * @@ -96,8 +96,8 @@ static void bta_ag_sdp_cback(uint16_t status, uint8_t idx) { event = BTA_AG_DISC_INT_RES_EVT; } tBTA_AG_DATA disc_result = {.disc_result = {.status = status}}; - do_in_main_thread(FROM_HERE, base::BindOnce(&bta_ag_sm_execute_by_handle, - idx, event, disc_result)); + do_in_main_thread(FROM_HERE, + base::BindOnce(&bta_ag_sm_execute_by_handle, idx, event, disc_result)); } } @@ -145,9 +145,8 @@ void bta_ag_sdp_cback_6(const RawAddress& /* bd_addr */, tSDP_STATUS status) { * false if function execution failed. * *****************************************************************************/ -bool bta_ag_add_record(uint16_t service_uuid, const char* p_service_name, - uint8_t scn, tBTA_AG_FEAT features, - uint32_t sdp_handle) { +bool bta_ag_add_record(uint16_t service_uuid, const char* p_service_name, uint8_t scn, + tBTA_AG_FEAT features, uint32_t sdp_handle) { tSDP_PROTOCOL_ELEM proto_elem_list[BTA_AG_NUM_PROTO_ELEMS]; uint16_t svc_class_id_list[BTA_AG_NUM_SVC_ELEMS]; uint16_t browse_list[] = {UUID_SERVCLASS_PUBLIC_BROWSE_GROUP}; @@ -172,13 +171,13 @@ bool bta_ag_add_record(uint16_t service_uuid, const char* p_service_name, proto_elem_list[1].num_params = 1; proto_elem_list[1].params[0] = scn; result &= get_legacy_stack_sdp_api()->handle.SDP_AddProtocolList( - sdp_handle, BTA_AG_NUM_PROTO_ELEMS, proto_elem_list); + sdp_handle, BTA_AG_NUM_PROTO_ELEMS, proto_elem_list); /* add service class id list */ svc_class_id_list[0] = service_uuid; svc_class_id_list[1] = UUID_SERVCLASS_GENERIC_AUDIO; result &= get_legacy_stack_sdp_api()->handle.SDP_AddServiceClassIdList( - sdp_handle, BTA_AG_NUM_SVC_ELEMS, svc_class_id_list); + sdp_handle, BTA_AG_NUM_SVC_ELEMS, svc_class_id_list); /* add profile descriptor list */ if (service_uuid == UUID_SERVCLASS_AG_HANDSFREE) { @@ -192,29 +191,32 @@ bool bta_ag_add_record(uint16_t service_uuid, const char* p_service_name, profile_uuid = UUID_SERVCLASS_HEADSET; version = HSP_VERSION_1_2; } - result &= get_legacy_stack_sdp_api()->handle.SDP_AddProfileDescriptorList( - sdp_handle, profile_uuid, version); + result &= get_legacy_stack_sdp_api()->handle.SDP_AddProfileDescriptorList(sdp_handle, + profile_uuid, version); /* add service name */ if (p_service_name != nullptr && p_service_name[0] != 0) { result &= get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - sdp_handle, ATTR_ID_SERVICE_NAME, TEXT_STR_DESC_TYPE, - (uint32_t)(strlen(p_service_name) + 1), (uint8_t*)p_service_name); + sdp_handle, ATTR_ID_SERVICE_NAME, TEXT_STR_DESC_TYPE, + (uint32_t)(strlen(p_service_name) + 1), (uint8_t*)p_service_name); } /* add features and network */ if (service_uuid == UUID_SERVCLASS_AG_HANDSFREE) { network = (features & BTA_AG_FEAT_REJECT) ? 1 : 0; result &= get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - sdp_handle, ATTR_ID_DATA_STORES_OR_NETWORK, UINT_DESC_TYPE, 1, - &network); + sdp_handle, ATTR_ID_DATA_STORES_OR_NETWORK, UINT_DESC_TYPE, 1, &network); - if (features & BTA_AG_FEAT_CODEC) codec_supported = true; + if (features & BTA_AG_FEAT_CODEC) { + codec_supported = true; + } features &= BTA_AG_SDP_FEAT_SPEC; /* Codec bit position is different in SDP and in BRSF */ - if (codec_supported) features |= BTA_AG_FEAT_WBS_SUPPORT; + if (codec_supported) { + features |= BTA_AG_FEAT_WBS_SUPPORT; + } // check property for SWB support if (hfp_hal_interface::get_swb_supported()) { features |= BTA_AG_FEAT_SWB_SUPPORT; @@ -222,12 +224,12 @@ bool bta_ag_add_record(uint16_t service_uuid, const char* p_service_name, UINT16_TO_BE_FIELD(buf, features); result &= get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - sdp_handle, ATTR_ID_SUPPORTED_FEATURES, UINT_DESC_TYPE, 2, buf); + sdp_handle, ATTR_ID_SUPPORTED_FEATURES, UINT_DESC_TYPE, 2, buf); } /* add browse group list */ result &= get_legacy_stack_sdp_api()->handle.SDP_AddUuidSequence( - sdp_handle, ATTR_ID_BROWSE_GROUP_LIST, 1, browse_list); + sdp_handle, ATTR_ID_BROWSE_GROUP_LIST, 1, browse_list); return result; } @@ -252,12 +254,10 @@ void bta_ag_create_records(tBTA_AG_SCB* p_scb, const tBTA_AG_DATA& data) { if (services & 1) { /* add sdp record if not already registered */ if (bta_ag_cb.profile[i].sdp_handle == 0) { - bta_ag_cb.profile[i].sdp_handle = - get_legacy_stack_sdp_api()->handle.SDP_CreateRecord(); + bta_ag_cb.profile[i].sdp_handle = get_legacy_stack_sdp_api()->handle.SDP_CreateRecord(); bta_ag_cb.profile[i].scn = BTA_AllocateSCN(); - bta_ag_add_record(bta_ag_uuid[i], data.api_register.p_name[i], - bta_ag_cb.profile[i].scn, data.api_register.features, - bta_ag_cb.profile[i].sdp_handle); + bta_ag_add_record(bta_ag_uuid[i], data.api_register.p_name[i], bta_ag_cb.profile[i].scn, + data.api_register.features, bta_ag_cb.profile[i].sdp_handle); bta_sys_add_uuid(bta_ag_uuid[i]); } } @@ -293,17 +293,14 @@ void bta_ag_del_records(tBTA_AG_SCB* p_scb) { others >>= BTA_HSP_SERVICE_ID; services = p_scb->reg_services >> BTA_HSP_SERVICE_ID; - for (i = 0; i < BTA_AG_NUM_IDX && services != 0; - i++, services >>= 1, others >>= 1) { + for (i = 0; i < BTA_AG_NUM_IDX && services != 0; i++, services >>= 1, others >>= 1) { /* if service registered for this scb and not registered for any other scb */ if (((services & 1) == 1) && ((others & 1) == 0)) { log::verbose("bta_ag_del_records {}", i); if (bta_ag_cb.profile[i].sdp_handle != 0) { - if (!get_legacy_stack_sdp_api()->handle.SDP_DeleteRecord( - bta_ag_cb.profile[i].sdp_handle)) { - log::warn("Unable to delete record sdp_handle:{}", - bta_ag_cb.profile[i].sdp_handle); + if (!get_legacy_stack_sdp_api()->handle.SDP_DeleteRecord(bta_ag_cb.profile[i].sdp_handle)) { + log::warn("Unable to delete record sdp_handle:{}", bta_ag_cb.profile[i].sdp_handle); } bta_ag_cb.profile[i].sdp_handle = 0; } @@ -348,26 +345,25 @@ bool bta_ag_sdp_find_attr(tBTA_AG_SCB* p_scb, tBTA_SERVICE_MASK service) { /* loop through all records we found */ while (true) { /* get next record; if none found, we're done */ - p_rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb(p_scb->p_disc_db, - uuid, p_rec); + p_rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb(p_scb->p_disc_db, uuid, p_rec); if (p_rec == nullptr) { if (uuid == UUID_SERVCLASS_HEADSET_HS) { /* Search again in case the peer device uses the old HSP UUID */ uuid = UUID_SERVCLASS_HEADSET; p_scb->peer_version = HSP_VERSION_1_0; - p_rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb( - p_scb->p_disc_db, uuid, p_rec); + p_rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb(p_scb->p_disc_db, uuid, p_rec); if (p_rec == nullptr) { break; } - } else + } else { break; + } } /* get scn from proto desc list if initiator */ if (p_scb->role == BTA_AG_INT) { if (get_legacy_stack_sdp_api()->record.SDP_FindProtocolListElemInRec( - p_rec, UUID_PROTOCOL_RFCOMM, &pe)) { + p_rec, UUID_PROTOCOL_RFCOMM, &pe)) { p_scb->peer_scn = (uint8_t)pe.params[0]; } else { continue; @@ -376,10 +372,9 @@ bool bta_ag_sdp_find_attr(tBTA_AG_SCB* p_scb, tBTA_SERVICE_MASK service) { /* get profile version (if failure, version parameter is not updated) */ uint16_t peer_version = HFP_HSP_VERSION_UNKNOWN; - if (!get_legacy_stack_sdp_api()->record.SDP_FindProfileVersionInRec( - p_rec, uuid, &peer_version)) { - log::warn("Get peer_version failed, using default 0x{:04x}", - p_scb->peer_version); + if (!get_legacy_stack_sdp_api()->record.SDP_FindProfileVersionInRec(p_rec, uuid, + &peer_version)) { + log::warn("Get peer_version failed, using default 0x{:04x}", p_scb->peer_version); peer_version = p_scb->peer_version; } @@ -387,19 +382,16 @@ bool bta_ag_sdp_find_attr(tBTA_AG_SCB* p_scb, tBTA_SERVICE_MASK service) { /* Update cached peer version if the new one is different */ if (peer_version != p_scb->peer_version) { p_scb->peer_version = peer_version; - if (btif_config_set_bin( - p_scb->peer_addr.ToString(), BTIF_STORAGE_KEY_HFP_VERSION, - (const uint8_t*)&peer_version, sizeof(peer_version))) { + if (btif_config_set_bin(p_scb->peer_addr.ToString(), BTIF_STORAGE_KEY_HFP_VERSION, + (const uint8_t*)&peer_version, sizeof(peer_version))) { } else { - log::warn("Failed to store peer HFP version for {}", - p_scb->peer_addr); + log::warn("Failed to store peer HFP version for {}", p_scb->peer_addr); } } /* get features if HFP */ p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - p_rec, ATTR_ID_SUPPORTED_FEATURES); - if (p_attr != nullptr && - SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == UINT_DESC_TYPE && + p_rec, ATTR_ID_SUPPORTED_FEATURES); + if (p_attr != nullptr && SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == UINT_DESC_TYPE && SDP_DISC_ATTR_LEN(p_attr->attr_len_type) >= 2) { /* Found attribute. Get value. */ /* There might be race condition between SDP and BRSF. */ @@ -417,13 +409,10 @@ bool bta_ag_sdp_find_attr(tBTA_AG_SCB* p_scb, tBTA_SERVICE_MASK service) { } if (sdp_features != p_scb->peer_sdp_features) { p_scb->peer_sdp_features = sdp_features; - if (btif_config_set_bin(p_scb->peer_addr.ToString(), - BTIF_STORAGE_KEY_HFP_SDP_FEATURES, - (const uint8_t*)&sdp_features, - sizeof(sdp_features))) { + if (btif_config_set_bin(p_scb->peer_addr.ToString(), BTIF_STORAGE_KEY_HFP_SDP_FEATURES, + (const uint8_t*)&sdp_features, sizeof(sdp_features))) { } else { - log::warn("Failed to store peer HFP SDP Features for {}", - p_scb->peer_addr); + log::warn("Failed to store peer HFP SDP Features for {}", p_scb->peer_addr); } } if (p_scb->peer_features == 0) { @@ -432,11 +421,9 @@ bool bta_ag_sdp_find_attr(tBTA_AG_SCB* p_scb, tBTA_SERVICE_MASK service) { /* Remote supports 1.7, store it in HFP 1.7 BL file */ if (bluetooth::common::init_flags::hfp_dynamic_version_is_enabled()) { if (p_scb->peer_version >= HFP_VERSION_1_9) { - interop_database_add_addr(INTEROP_HFP_1_9_ALLOWLIST, - &p_scb->peer_addr, 3); + interop_database_add_addr(INTEROP_HFP_1_9_ALLOWLIST, &p_scb->peer_addr, 3); } else if (p_scb->peer_version >= HFP_VERSION_1_7) { - interop_database_add_addr(INTEROP_HFP_1_7_ALLOWLIST, - &p_scb->peer_addr, 3); + interop_database_add_addr(INTEROP_HFP_1_7_ALLOWLIST, &p_scb->peer_addr, 3); } } } @@ -445,15 +432,15 @@ bool bta_ag_sdp_find_attr(tBTA_AG_SCB* p_scb, tBTA_SERVICE_MASK service) { p_scb->peer_version = peer_version; /* get features if HSP */ p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - p_rec, ATTR_ID_REMOTE_AUDIO_VOLUME_CONTROL); - if (p_attr != nullptr && - SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == BOOLEAN_DESC_TYPE && - SDP_DISC_ATTR_LEN(p_attr->attr_len_type) >= 1) { + p_rec, ATTR_ID_REMOTE_AUDIO_VOLUME_CONTROL); + if (p_attr != nullptr && SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == BOOLEAN_DESC_TYPE && + SDP_DISC_ATTR_LEN(p_attr->attr_len_type) >= 1) { /* Remote volume control of HSP */ - if (p_attr->attr_value.v.u8) + if (p_attr->attr_value.v.u8) { p_scb->peer_features |= BTA_AG_PEER_FEAT_VOL; - else + } else { p_scb->peer_features &= ~BTA_AG_PEER_FEAT_VOL; + } } } @@ -538,18 +525,16 @@ void bta_ag_do_disc(tBTA_AG_SCB* p_scb, tBTA_SERVICE_MASK service) { p_scb->p_disc_db = (tSDP_DISCOVERY_DB*)osi_malloc(BTA_AG_DISC_BUF_SIZE); /* set up service discovery database; attr happens to be attr_list len */ if (get_legacy_stack_sdp_api()->service.SDP_InitDiscoveryDb( - p_scb->p_disc_db, BTA_AG_DISC_BUF_SIZE, num_uuid, uuid_list, num_attr, - attr_list)) { + p_scb->p_disc_db, BTA_AG_DISC_BUF_SIZE, num_uuid, uuid_list, num_attr, attr_list)) { if (get_legacy_stack_sdp_api()->service.SDP_ServiceSearchAttributeRequest( - p_scb->peer_addr, p_scb->p_disc_db, - bta_ag_sdp_cback_tbl[bta_ag_scb_to_idx(p_scb) - 1])) { + p_scb->peer_addr, p_scb->p_disc_db, + bta_ag_sdp_cback_tbl[bta_ag_scb_to_idx(p_scb) - 1])) { return; } else { log::error("failed to start SDP discovery for {}", p_scb->peer_addr); } } else { - log::error("failed to init SDP discovery database for {}", - p_scb->peer_addr); + log::error("failed to init SDP discovery database for {}", p_scb->peer_addr); } // Failure actions bta_ag_free_db(p_scb, tBTA_AG_DATA::kEmpty); diff --git a/system/bta/ag/bta_ag_swb_aptx.cc b/system/bta/ag/bta_ag_swb_aptx.cc index 5943f6ec470..97b23a18097 100644 --- a/system/bta/ag/bta_ag_swb_aptx.cc +++ b/system/bta/ag/bta_ag_swb_aptx.cc @@ -40,9 +40,8 @@ static bool get_lc3_swb_codec_status(RawAddress* bd_addr) { uint16_t p_scb_idx = bta_ag_idx_by_bdaddr(bd_addr); tBTA_AG_SCB* p_scb = bta_ag_scb_by_idx(p_scb_idx); if (p_scb != NULL) { - return (hfp_hal_interface::get_swb_supported() && - (p_scb->peer_codecs & BTM_SCO_CODEC_LC3) && - !(p_scb->disabled_codecs & BTM_SCO_CODEC_LC3)); + return hfp_hal_interface::get_swb_supported() && (p_scb->peer_codecs & BTM_SCO_CODEC_LC3) && + !(p_scb->disabled_codecs & BTM_SCO_CODEC_LC3); } return false; } @@ -54,8 +53,7 @@ static bool get_aptx_swb_codec_status() { return false; } -bool get_swb_codec_status(bluetooth::headset::bthf_swb_codec_t swb_codec, - RawAddress* bd_addr) { +bool get_swb_codec_status(bluetooth::headset::bthf_swb_codec_t swb_codec, RawAddress* bd_addr) { bool status = false; switch (swb_codec) { case bluetooth::headset::BTHF_SWB_CODEC_LC3: @@ -74,8 +72,7 @@ bool get_swb_codec_status(bluetooth::headset::bthf_swb_codec_t swb_codec, } bt_status_t enable_aptx_swb_codec(bool enable, RawAddress* bd_addr) { - if (is_hfp_aptx_voice_enabled() && - (get_lc3_swb_codec_status(bd_addr) == false)) { + if (is_hfp_aptx_voice_enabled() && (get_lc3_swb_codec_status(bd_addr) == false)) { log::verbose("enable={}", enable); aptx_swb_codec_status = enable; return BT_STATUS_SUCCESS; @@ -83,8 +80,8 @@ bt_status_t enable_aptx_swb_codec(bool enable, RawAddress* bd_addr) { return BT_STATUS_FAIL; } -void bta_ag_swb_handle_vs_at_events(tBTA_AG_SCB* p_scb, uint16_t cmd, - int16_t int_arg, tBTA_AG_VAL* val) { +void bta_ag_swb_handle_vs_at_events(tBTA_AG_SCB* p_scb, uint16_t cmd, int16_t int_arg, + tBTA_AG_VAL* val) { switch (cmd) { case BTA_AG_AT_QAC_EVT: if (!get_swb_codec_status(bluetooth::headset::BTHF_SWB_CODEC_VENDOR_APTX, @@ -100,8 +97,7 @@ void bta_ag_swb_handle_vs_at_events(tBTA_AG_SCB* p_scb, uint16_t cmd, p_scb->sco_codec = BTM_SCO_CODEC_MSBC; } bta_ag_send_qac(p_scb, NULL); - log::verbose("Received AT+QAC, updating sco codec to SWB: {}", - p_scb->sco_codec); + log::verbose("Received AT+QAC, updating sco codec to SWB: {}", p_scb->sco_codec); val->num = p_scb->peer_codecs; break; case BTA_AG_AT_QCS_EVT: { @@ -148,15 +144,14 @@ void bta_ag_swb_handle_vs_at_events(tBTA_AG_SCB* p_scb, uint16_t cmd, tBTA_AG_PEER_CODEC bta_ag_parse_qac(char* p_s) { tBTA_AG_PEER_CODEC retval = BTM_SCO_CODEC_NONE; - tBTA_AG_SCO_APTX_SWB_SETTINGS codec_mode = - BTA_AG_SCO_APTX_SWB_SETTINGS_UNKNOWN; + tBTA_AG_SCO_APTX_SWB_SETTINGS codec_mode = BTA_AG_SCO_APTX_SWB_SETTINGS_UNKNOWN; - auto codec_modes = - bluetooth::common::StringSplit(std::string(p_s), ",", SWB_CODECS_NUMBER); + auto codec_modes = bluetooth::common::StringSplit(std::string(p_s), ",", SWB_CODECS_NUMBER); for (auto& codec_mode_str : codec_modes) { - if (!std::isdigit(*codec_mode_str.c_str())) continue; - codec_mode = static_cast( - std::atoi(codec_mode_str.c_str())); + if (!std::isdigit(*codec_mode_str.c_str())) { + continue; + } + codec_mode = static_cast(std::atoi(codec_mode_str.c_str())); switch (codec_mode) { case BTA_AG_SCO_APTX_SWB_SETTINGS_Q0: retval |= BTA_AG_SCO_APTX_SWB_SETTINGS_Q0_MASK; @@ -175,5 +170,5 @@ tBTA_AG_PEER_CODEC bta_ag_parse_qac(char* p_s) { break; } } - return (retval); + return retval; } diff --git a/system/bta/ar/bta_ar.cc b/system/bta/ar/bta_ar.cc index 5a8f5307407..d252f07c2fa 100644 --- a/system/bta/ar/bta_ar.cc +++ b/system/bta/ar/bta_ar.cc @@ -66,11 +66,10 @@ static void bta_ar_avrc_add_cat(uint16_t categories) { p = temp; UINT16_TO_BE_STREAM(p, categories); if (!get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - bta_ar_cb.sdp_tg_handle, ATTR_ID_SUPPORTED_FEATURES, UINT_DESC_TYPE, - sizeof(temp), (uint8_t*)temp)) { - log::warn( - "Unable to add SDP attribute for supported categories handle:{}", - bta_ar_cb.sdp_tg_handle); + bta_ar_cb.sdp_tg_handle, ATTR_ID_SUPPORTED_FEATURES, UINT_DESC_TYPE, sizeof(temp), + (uint8_t*)temp)) { + log::warn("Unable to add SDP attribute for supported categories handle:{}", + bta_ar_cb.sdp_tg_handle); } } } @@ -98,12 +97,12 @@ void bta_ar_init(void) { * Returns void * ******************************************************************************/ -static void bta_ar_avdt_cback(uint8_t handle, const RawAddress& bd_addr, - uint8_t event, tAVDT_CTRL* p_data, - uint8_t scb_index) { +static void bta_ar_avdt_cback(uint8_t handle, const RawAddress& bd_addr, uint8_t event, + tAVDT_CTRL* p_data, uint8_t scb_index) { /* route the AVDT registration callback to av or avk */ - if (bta_ar_cb.p_av_conn_cback) + if (bta_ar_cb.p_av_conn_cback) { (*bta_ar_cb.p_av_conn_cback)(handle, bd_addr, event, p_data, scb_index); + } } /******************************************************************************* @@ -120,8 +119,7 @@ void bta_ar_reg_avdt(AvdtpRcb* p_reg, tAVDT_CTRL_CBACK* p_cback) { if (bta_ar_cb.avdt_registered == 0) { AVDT_Register(p_reg, bta_ar_avdt_cback); } else { - log::warn("doesn't register again (registered:{})", - bta_ar_cb.avdt_registered); + log::warn("doesn't register again (registered:{})", bta_ar_cb.avdt_registered); } bta_ar_cb.avdt_registered |= BTA_AR_AV_MASK; } @@ -139,7 +137,9 @@ void bta_ar_dereg_avdt() { bta_ar_cb.p_av_conn_cback = NULL; bta_ar_cb.avdt_registered &= ~BTA_AR_AV_MASK; - if (bta_ar_cb.avdt_registered == 0) AVDT_Deregister(); + if (bta_ar_cb.avdt_registered == 0) { + AVDT_Deregister(); + } } /******************************************************************************* @@ -154,9 +154,7 @@ void bta_ar_dereg_avdt() { * Returns void * ******************************************************************************/ -void bta_ar_avdt_conn(tBTA_SYS_ID sys_id, const RawAddress& bd_addr, - uint8_t scb_index) { -} +void bta_ar_avdt_conn(tBTA_SYS_ID sys_id, const RawAddress& bd_addr, uint8_t scb_index) {} /******************************************************************************* * @@ -186,7 +184,9 @@ void bta_ar_reg_avct() { void bta_ar_dereg_avct() { bta_ar_cb.avct_registered &= ~BTA_AR_AV_MASK; - if (bta_ar_cb.avct_registered == 0) AVCT_Deregister(); + if (bta_ar_cb.avct_registered == 0) { + AVCT_Deregister(); + } } /****************************************************************************** @@ -198,22 +198,21 @@ void bta_ar_dereg_avct() { * Returns void * *****************************************************************************/ -void bta_ar_reg_avrc(uint16_t service_uuid, const char* service_name, - const char* provider_name, uint16_t categories, - bool browse_supported, uint16_t profile_version) { +void bta_ar_reg_avrc(uint16_t service_uuid, const char* service_name, const char* provider_name, + uint16_t categories, bool browse_supported, uint16_t profile_version) { uint8_t mask = BTA_AR_AV_MASK; uint8_t temp[8], *p; - if (!categories) return; + if (!categories) { + return; + } if (service_uuid == UUID_SERVCLASS_AV_REM_CTRL_TARGET) { if (bta_ar_cb.sdp_tg_handle == 0) { bta_ar_cb.tg_registered = mask; - bta_ar_cb.sdp_tg_handle = - get_legacy_stack_sdp_api()->handle.SDP_CreateRecord(); - AVRC_AddRecord(service_uuid, service_name, provider_name, categories, - bta_ar_cb.sdp_tg_handle, browse_supported, - profile_version, 0); + bta_ar_cb.sdp_tg_handle = get_legacy_stack_sdp_api()->handle.SDP_CreateRecord(); + AVRC_AddRecord(service_uuid, service_name, provider_name, categories, bta_ar_cb.sdp_tg_handle, + browse_supported, profile_version, 0); bta_sys_add_uuid(service_uuid); } /* only one TG is allowed (first-come, first-served). @@ -223,11 +222,9 @@ void bta_ar_reg_avrc(uint16_t service_uuid, const char* service_name, bta_ar_cb.ct_categories[mask - 1] = categories; categories = bta_ar_cb.ct_categories[0] | bta_ar_cb.ct_categories[1]; if (bta_ar_cb.sdp_ct_handle == 0) { - bta_ar_cb.sdp_ct_handle = - get_legacy_stack_sdp_api()->handle.SDP_CreateRecord(); - AVRC_AddRecord(service_uuid, service_name, provider_name, categories, - bta_ar_cb.sdp_ct_handle, browse_supported, - profile_version, 0); + bta_ar_cb.sdp_ct_handle = get_legacy_stack_sdp_api()->handle.SDP_CreateRecord(); + AVRC_AddRecord(service_uuid, service_name, provider_name, categories, bta_ar_cb.sdp_ct_handle, + browse_supported, profile_version, 0); bta_sys_add_uuid(service_uuid); } else { /* multiple CTs are allowed. @@ -235,10 +232,9 @@ void bta_ar_reg_avrc(uint16_t service_uuid, const char* service_name, p = temp; UINT16_TO_BE_STREAM(p, categories); if (!get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - bta_ar_cb.sdp_ct_handle, ATTR_ID_SUPPORTED_FEATURES, - UINT_DESC_TYPE, (uint32_t)2, (uint8_t*)temp)) { - log::warn("Unable to add supported features handle:{}", - bta_ar_cb.sdp_ct_handle); + bta_ar_cb.sdp_ct_handle, ATTR_ID_SUPPORTED_FEATURES, UINT_DESC_TYPE, (uint32_t)2, + (uint8_t*)temp)) { + log::warn("Unable to add supported features handle:{}", bta_ar_cb.sdp_ct_handle); } } } @@ -262,10 +258,8 @@ void bta_ar_dereg_avrc(uint16_t service_uuid) { if (service_uuid == UUID_SERVCLASS_AV_REM_CTRL_TARGET) { if (bta_ar_cb.sdp_tg_handle && mask == bta_ar_cb.tg_registered) { bta_ar_cb.tg_registered = 0; - if (!get_legacy_stack_sdp_api()->handle.SDP_DeleteRecord( - bta_ar_cb.sdp_tg_handle)) { - log::warn("Unable to delete SDP record handle:{}", - bta_ar_cb.sdp_tg_handle); + if (!get_legacy_stack_sdp_api()->handle.SDP_DeleteRecord(bta_ar_cb.sdp_tg_handle)) { + log::warn("Unable to delete SDP record handle:{}", bta_ar_cb.sdp_tg_handle); } bta_ar_cb.sdp_tg_handle = 0; bta_sys_remove_uuid(service_uuid); @@ -275,23 +269,20 @@ void bta_ar_dereg_avrc(uint16_t service_uuid) { bta_ar_cb.ct_categories[mask - 1] = 0; categories = bta_ar_cb.ct_categories[0] | bta_ar_cb.ct_categories[1]; if (!categories) { - /* no CT is still registered - cleaup */ - if (get_legacy_stack_sdp_api()->handle.SDP_DeleteRecord( - bta_ar_cb.sdp_ct_handle)) { - log::warn("Unable to delete SDP record handle:{}", - bta_ar_cb.sdp_ct_handle); + /* no CT is still registered - cleanup */ + if (get_legacy_stack_sdp_api()->handle.SDP_DeleteRecord(bta_ar_cb.sdp_ct_handle)) { + log::warn("Unable to delete SDP record handle:{}", bta_ar_cb.sdp_ct_handle); } bta_ar_cb.sdp_ct_handle = 0; bta_sys_remove_uuid(service_uuid); } else { - /* change supported categories to the remaning one */ + /* change supported categories to the remaining one */ p = temp; UINT16_TO_BE_STREAM(p, categories); if (!get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - bta_ar_cb.sdp_ct_handle, ATTR_ID_SUPPORTED_FEATURES, - UINT_DESC_TYPE, (uint32_t)2, (uint8_t*)temp)) { - log::warn("Unable to add SDP supported features handle:{}", - bta_ar_cb.sdp_ct_handle); + bta_ar_cb.sdp_ct_handle, ATTR_ID_SUPPORTED_FEATURES, UINT_DESC_TYPE, + (uint32_t)2, (uint8_t*)temp)) { + log::warn("Unable to add SDP supported features handle:{}", bta_ar_cb.sdp_ct_handle); } } } @@ -309,25 +300,25 @@ void bta_ar_dereg_avrc(uint16_t service_uuid) { * Returns void * *****************************************************************************/ -void bta_ar_reg_avrc_for_src_sink_coexist( - uint16_t service_uuid, const char* service_name, const char* provider_name, - uint16_t categories, tBTA_SYS_ID sys_id, bool browse_supported, - uint16_t profile_version) { +void bta_ar_reg_avrc_for_src_sink_coexist(uint16_t service_uuid, const char* service_name, + const char* provider_name, uint16_t categories, + tBTA_SYS_ID sys_id, bool browse_supported, + uint16_t profile_version) { uint8_t mask = bta_ar_id(sys_id); uint8_t temp[8], *p; uint16_t class_list[2]; uint16_t count = 1; - if (!mask || !categories) return; + if (!mask || !categories) { + return; + } if (service_uuid == UUID_SERVCLASS_AV_REM_CTRL_TARGET) { bta_ar_cb.tg_categories[mask - 1] = categories; categories = bta_ar_cb.tg_categories[0] | bta_ar_cb.tg_categories[1]; if (bta_ar_cb.sdp_tg_handle == 0) { bta_ar_cb.tg_registered = mask; - bta_ar_cb.sdp_tg_handle = - get_legacy_stack_sdp_api()->handle.SDP_CreateRecord(); - AVRC_AddRecord(service_uuid, service_name, provider_name, categories, - bta_ar_cb.sdp_tg_handle, browse_supported, profile_version, - 0); + bta_ar_cb.sdp_tg_handle = get_legacy_stack_sdp_api()->handle.SDP_CreateRecord(); + AVRC_AddRecord(service_uuid, service_name, provider_name, categories, bta_ar_cb.sdp_tg_handle, + browse_supported, profile_version, 0); bta_sys_add_uuid(service_uuid); } /* Change supported categories on the second one */ @@ -339,19 +330,16 @@ void bta_ar_reg_avrc_for_src_sink_coexist( bta_ar_cb.ct_categories[mask - 1] = categories; categories = bta_ar_cb.ct_categories[0] | bta_ar_cb.ct_categories[1]; if (bta_ar_cb.sdp_ct_handle == 0) { - bta_ar_cb.sdp_ct_handle = - get_legacy_stack_sdp_api()->handle.SDP_CreateRecord(); - AVRC_AddRecord(service_uuid, service_name, provider_name, categories, - bta_ar_cb.sdp_ct_handle, browse_supported, profile_version, - 0); + bta_ar_cb.sdp_ct_handle = get_legacy_stack_sdp_api()->handle.SDP_CreateRecord(); + AVRC_AddRecord(service_uuid, service_name, provider_name, categories, bta_ar_cb.sdp_ct_handle, + browse_supported, profile_version, 0); bta_sys_add_uuid(service_uuid); bta_ar_cb.ct_ver = categories; } else { /* If first reg 1,3 version, reg 1.6 must update class id */ if (bta_ar_cb.ct_ver < profile_version) { log::verbose("ver=0x{:x}", profile_version); - if (bta_ar_cb.ct_ver <= AVRC_REV_1_3 && - profile_version > AVRC_REV_1_3) { + if (bta_ar_cb.ct_ver <= AVRC_REV_1_3 && profile_version > AVRC_REV_1_3) { bta_ar_cb.ct_ver = profile_version; /* add service class id list */ class_list[0] = service_uuid; @@ -359,16 +347,15 @@ void bta_ar_reg_avrc_for_src_sink_coexist( class_list[1] = UUID_SERVCLASS_AV_REM_CTRL_CONTROL; count = 2; } - if (!get_legacy_stack_sdp_api()->handle.SDP_AddServiceClassIdList( - bta_ar_cb.sdp_ct_handle, count, class_list)) { - log::warn("Unable to add SDP service class id list handle:{}", - bta_ar_cb.sdp_ct_handle); + if (!get_legacy_stack_sdp_api()->handle.SDP_AddServiceClassIdList(bta_ar_cb.sdp_ct_handle, + count, class_list)) { + log::warn("Unable to add SDP service class id list handle:{}", bta_ar_cb.sdp_ct_handle); } } else { bta_ar_cb.ct_ver = profile_version; } if (!get_legacy_stack_sdp_api()->handle.SDP_AddProfileDescriptorList( - bta_ar_cb.sdp_ct_handle, service_uuid, profile_version)) { + bta_ar_cb.sdp_ct_handle, service_uuid, profile_version)) { log::warn("Unable to add SDP profile descriptor version handle:{}", bta_ar_cb.sdp_ct_handle); } @@ -378,8 +365,8 @@ void bta_ar_reg_avrc_for_src_sink_coexist( p = temp; UINT16_TO_BE_STREAM(p, categories); if (!get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - bta_ar_cb.sdp_ct_handle, ATTR_ID_SUPPORTED_FEATURES, - UINT_DESC_TYPE, (uint32_t)2, (uint8_t*)temp)) { + bta_ar_cb.sdp_ct_handle, ATTR_ID_SUPPORTED_FEATURES, UINT_DESC_TYPE, (uint32_t)2, + (uint8_t*)temp)) { log::warn("Unable to add SDP attribute supported features handle:{}", bta_ar_cb.sdp_ct_handle); } diff --git a/system/bta/ar/bta_ar_int.h b/system/bta/ar/bta_ar_int.h index 596495da56b..bc7e50d850c 100644 --- a/system/bta/ar/bta_ar_int.h +++ b/system/bta/ar/bta_ar_int.h @@ -35,7 +35,7 @@ /* data associated with BTA_AR */ typedef struct { - tAVDT_CTRL_CBACK* p_av_conn_cback; /* av connection callback function */ + tAVDT_CTRL_CBACK* p_av_conn_cback; /* av connection callback function */ uint8_t avdt_registered; uint8_t avct_registered; uint32_t sdp_tg_handle; diff --git a/system/bta/av/bta_av_aact.cc b/system/bta/av/bta_av_aact.cc index f3f1397e635..5dd91f8eca7 100644 --- a/system/bta/av/bta_av_aact.cc +++ b/system/bta/av/bta_av_aact.cc @@ -91,8 +91,7 @@ constexpr char kBtmLogTag[] = "A2DP"; /* ACL quota we are letting FW use for A2DP Offload Tx. */ #define BTA_AV_A2DP_OFFLOAD_XMIT_QUOTA 4 -static void bta_av_offload_codec_builder(tBTA_AV_SCB* p_scb, - tBT_A2DP_OFFLOAD* p_a2dp_offload); +static void bta_av_offload_codec_builder(tBTA_AV_SCB* p_scb, tBT_A2DP_OFFLOAD* p_a2dp_offload); /* state machine states */ enum { @@ -105,68 +104,61 @@ enum { }; /* the call out functions for audio stream */ -const tBTA_AV_CO_FUNCTS bta_av_a2dp_cos = {bta_av_co_audio_init, - bta_av_co_audio_disc_res, - bta_av_co_audio_getconfig, - bta_av_co_audio_setconfig, - bta_av_co_audio_open, - bta_av_co_audio_close, - bta_av_co_audio_start, - bta_av_co_audio_stop, - bta_av_co_audio_source_data_path, - bta_av_co_audio_delay, - bta_av_co_audio_update_mtu, - bta_av_co_get_scmst_info}; +const tBTA_AV_CO_FUNCTS bta_av_a2dp_cos = { + bta_av_co_audio_init, bta_av_co_audio_disc_res, bta_av_co_audio_getconfig, + bta_av_co_audio_setconfig, bta_av_co_audio_open, bta_av_co_audio_close, + bta_av_co_audio_start, bta_av_co_audio_stop, bta_av_co_audio_source_data_path, + bta_av_co_audio_delay, bta_av_co_audio_update_mtu, bta_av_co_get_scmst_info}; /* these tables translate AVDT events to SSM events */ static const uint16_t bta_av_stream_evt_ok[] = { - BTA_AV_STR_DISC_OK_EVT, /* AVDT_DISCOVER_CFM_EVT */ - BTA_AV_STR_GETCAP_OK_EVT, /* AVDT_GETCAP_CFM_EVT */ - BTA_AV_STR_OPEN_OK_EVT, /* AVDT_OPEN_CFM_EVT */ - BTA_AV_STR_OPEN_OK_EVT, /* AVDT_OPEN_IND_EVT */ - BTA_AV_STR_CONFIG_IND_EVT, /* AVDT_CONFIG_IND_EVT */ - BTA_AV_STR_START_OK_EVT, /* AVDT_START_CFM_EVT */ - BTA_AV_STR_START_OK_EVT, /* AVDT_START_IND_EVT */ - BTA_AV_STR_SUSPEND_CFM_EVT, /* AVDT_SUSPEND_CFM_EVT */ - BTA_AV_STR_SUSPEND_CFM_EVT, /* AVDT_SUSPEND_IND_EVT */ - BTA_AV_STR_CLOSE_EVT, /* AVDT_CLOSE_CFM_EVT */ - BTA_AV_STR_CLOSE_EVT, /* AVDT_CLOSE_IND_EVT */ - BTA_AV_STR_RECONFIG_CFM_EVT, /* AVDT_RECONFIG_CFM_EVT */ - 0, /* AVDT_RECONFIG_IND_EVT */ - BTA_AV_STR_SECURITY_CFM_EVT, /* AVDT_SECURITY_CFM_EVT */ - BTA_AV_STR_SECURITY_IND_EVT, /* AVDT_SECURITY_IND_EVT */ - BTA_AV_STR_WRITE_CFM_EVT, /* AVDT_WRITE_CFM_EVT */ - BTA_AV_AVDT_CONNECT_EVT, /* AVDT_CONNECT_IND_EVT */ - BTA_AV_AVDT_DISCONNECT_EVT, /* AVDT_DISCONNECT_IND_EVT */ - BTA_AV_AVDT_RPT_CONN_EVT, /* AVDT_REPORT_CONN_EVT */ - BTA_AV_AVDT_RPT_CONN_EVT, /* AVDT_REPORT_DISCONN_EVT */ - BTA_AV_AVDT_DELAY_RPT_EVT, /* AVDT_DELAY_REPORT_EVT */ - BTA_AV_AVDT_DELAY_RPT_CFM_EVT, /* AVDT_DELAY_REPORT_CFM_EVT */ + BTA_AV_STR_DISC_OK_EVT, /* AVDT_DISCOVER_CFM_EVT */ + BTA_AV_STR_GETCAP_OK_EVT, /* AVDT_GETCAP_CFM_EVT */ + BTA_AV_STR_OPEN_OK_EVT, /* AVDT_OPEN_CFM_EVT */ + BTA_AV_STR_OPEN_OK_EVT, /* AVDT_OPEN_IND_EVT */ + BTA_AV_STR_CONFIG_IND_EVT, /* AVDT_CONFIG_IND_EVT */ + BTA_AV_STR_START_OK_EVT, /* AVDT_START_CFM_EVT */ + BTA_AV_STR_START_OK_EVT, /* AVDT_START_IND_EVT */ + BTA_AV_STR_SUSPEND_CFM_EVT, /* AVDT_SUSPEND_CFM_EVT */ + BTA_AV_STR_SUSPEND_CFM_EVT, /* AVDT_SUSPEND_IND_EVT */ + BTA_AV_STR_CLOSE_EVT, /* AVDT_CLOSE_CFM_EVT */ + BTA_AV_STR_CLOSE_EVT, /* AVDT_CLOSE_IND_EVT */ + BTA_AV_STR_RECONFIG_CFM_EVT, /* AVDT_RECONFIG_CFM_EVT */ + 0, /* AVDT_RECONFIG_IND_EVT */ + BTA_AV_STR_SECURITY_CFM_EVT, /* AVDT_SECURITY_CFM_EVT */ + BTA_AV_STR_SECURITY_IND_EVT, /* AVDT_SECURITY_IND_EVT */ + BTA_AV_STR_WRITE_CFM_EVT, /* AVDT_WRITE_CFM_EVT */ + BTA_AV_AVDT_CONNECT_EVT, /* AVDT_CONNECT_IND_EVT */ + BTA_AV_AVDT_DISCONNECT_EVT, /* AVDT_DISCONNECT_IND_EVT */ + BTA_AV_AVDT_RPT_CONN_EVT, /* AVDT_REPORT_CONN_EVT */ + BTA_AV_AVDT_RPT_CONN_EVT, /* AVDT_REPORT_DISCONN_EVT */ + BTA_AV_AVDT_DELAY_RPT_EVT, /* AVDT_DELAY_REPORT_EVT */ + BTA_AV_AVDT_DELAY_RPT_CFM_EVT, /* AVDT_DELAY_REPORT_CFM_EVT */ }; static const uint16_t bta_av_stream_evt_fail[] = { - BTA_AV_STR_DISC_FAIL_EVT, /* AVDT_DISCOVER_CFM_EVT */ - BTA_AV_STR_GETCAP_FAIL_EVT, /* AVDT_GETCAP_CFM_EVT */ - BTA_AV_STR_OPEN_FAIL_EVT, /* AVDT_OPEN_CFM_EVT */ - BTA_AV_STR_OPEN_OK_EVT, /* AVDT_OPEN_IND_EVT */ - BTA_AV_STR_CONFIG_IND_EVT, /* AVDT_CONFIG_IND_EVT */ - BTA_AV_STR_START_FAIL_EVT, /* AVDT_START_CFM_EVT */ - BTA_AV_STR_START_OK_EVT, /* AVDT_START_IND_EVT */ - BTA_AV_STR_SUSPEND_CFM_EVT, /* AVDT_SUSPEND_CFM_EVT */ - BTA_AV_STR_SUSPEND_CFM_EVT, /* AVDT_SUSPEND_IND_EVT */ - BTA_AV_STR_CLOSE_EVT, /* AVDT_CLOSE_CFM_EVT */ - BTA_AV_STR_CLOSE_EVT, /* AVDT_CLOSE_IND_EVT */ - BTA_AV_STR_RECONFIG_CFM_EVT, /* AVDT_RECONFIG_CFM_EVT */ - 0, /* AVDT_RECONFIG_IND_EVT */ - BTA_AV_STR_SECURITY_CFM_EVT, /* AVDT_SECURITY_CFM_EVT */ - BTA_AV_STR_SECURITY_IND_EVT, /* AVDT_SECURITY_IND_EVT */ - BTA_AV_STR_WRITE_CFM_EVT, /* AVDT_WRITE_CFM_EVT */ - BTA_AV_AVDT_CONNECT_EVT, /* AVDT_CONNECT_IND_EVT */ - BTA_AV_AVDT_DISCONNECT_EVT, /* AVDT_DISCONNECT_IND_EVT */ - BTA_AV_AVDT_RPT_CONN_EVT, /* AVDT_REPORT_CONN_EVT */ - BTA_AV_AVDT_RPT_CONN_EVT, /* AVDT_REPORT_DISCONN_EVT */ - BTA_AV_AVDT_DELAY_RPT_EVT, /* AVDT_DELAY_REPORT_EVT */ - BTA_AV_AVDT_DELAY_RPT_CFM_EVT, /* AVDT_DELAY_REPORT_CFM_EVT */ + BTA_AV_STR_DISC_FAIL_EVT, /* AVDT_DISCOVER_CFM_EVT */ + BTA_AV_STR_GETCAP_FAIL_EVT, /* AVDT_GETCAP_CFM_EVT */ + BTA_AV_STR_OPEN_FAIL_EVT, /* AVDT_OPEN_CFM_EVT */ + BTA_AV_STR_OPEN_OK_EVT, /* AVDT_OPEN_IND_EVT */ + BTA_AV_STR_CONFIG_IND_EVT, /* AVDT_CONFIG_IND_EVT */ + BTA_AV_STR_START_FAIL_EVT, /* AVDT_START_CFM_EVT */ + BTA_AV_STR_START_OK_EVT, /* AVDT_START_IND_EVT */ + BTA_AV_STR_SUSPEND_CFM_EVT, /* AVDT_SUSPEND_CFM_EVT */ + BTA_AV_STR_SUSPEND_CFM_EVT, /* AVDT_SUSPEND_IND_EVT */ + BTA_AV_STR_CLOSE_EVT, /* AVDT_CLOSE_CFM_EVT */ + BTA_AV_STR_CLOSE_EVT, /* AVDT_CLOSE_IND_EVT */ + BTA_AV_STR_RECONFIG_CFM_EVT, /* AVDT_RECONFIG_CFM_EVT */ + 0, /* AVDT_RECONFIG_IND_EVT */ + BTA_AV_STR_SECURITY_CFM_EVT, /* AVDT_SECURITY_CFM_EVT */ + BTA_AV_STR_SECURITY_IND_EVT, /* AVDT_SECURITY_IND_EVT */ + BTA_AV_STR_WRITE_CFM_EVT, /* AVDT_WRITE_CFM_EVT */ + BTA_AV_AVDT_CONNECT_EVT, /* AVDT_CONNECT_IND_EVT */ + BTA_AV_AVDT_DISCONNECT_EVT, /* AVDT_DISCONNECT_IND_EVT */ + BTA_AV_AVDT_RPT_CONN_EVT, /* AVDT_REPORT_CONN_EVT */ + BTA_AV_AVDT_RPT_CONN_EVT, /* AVDT_REPORT_DISCONN_EVT */ + BTA_AV_AVDT_DELAY_RPT_EVT, /* AVDT_DELAY_REPORT_EVT */ + BTA_AV_AVDT_DELAY_RPT_CFM_EVT, /* AVDT_DELAY_REPORT_CFM_EVT */ }; /*********************************************** @@ -181,9 +173,8 @@ static const uint16_t bta_av_stream_evt_fail[] = { static uint8_t bta_av_get_scb_handle(tBTA_AV_SCB* p_scb, uint8_t local_sep) { for (int i = 0; i < BTAV_A2DP_CODEC_INDEX_MAX; i++) { if ((p_scb->seps[i].tsep == local_sep) && - A2DP_CodecTypeEquals(p_scb->seps[i].codec_info, - p_scb->cfg.codec_info)) { - return (p_scb->seps[i].av_handle); + A2DP_CodecTypeEquals(p_scb->seps[i].codec_info, p_scb->cfg.codec_info)) { + return p_scb->seps[i].av_handle; } } log::verbose("local sep_type {} not found", local_sep); @@ -199,10 +190,11 @@ static uint8_t bta_av_get_scb_handle(tBTA_AV_SCB* p_scb, uint8_t local_sep) { * * Returns void **********************************************/ -static uint8_t bta_av_get_scb_sep_type(tBTA_AV_SCB* p_scb, - uint8_t tavdt_handle) { +static uint8_t bta_av_get_scb_sep_type(tBTA_AV_SCB* p_scb, uint8_t tavdt_handle) { for (int i = 0; i < BTAV_A2DP_CODEC_INDEX_MAX; i++) { - if (p_scb->seps[i].av_handle == tavdt_handle) return (p_scb->seps[i].tsep); + if (p_scb->seps[i].av_handle == tavdt_handle) { + return p_scb->seps[i].tsep; + } } log::verbose("avdt_handle {} not found", tavdt_handle); return AVDT_TSEP_INVALID; @@ -219,11 +211,10 @@ static uint8_t bta_av_get_scb_sep_type(tBTA_AV_SCB* p_scb, * ******************************************************************************/ static void bta_av_save_addr(tBTA_AV_SCB* p_scb, const RawAddress& bd_addr) { - log::verbose("peer={} recfg_sup:{}, suspend_sup:{}", bd_addr, - p_scb->recfg_sup, p_scb->suspend_sup); + log::verbose("peer={} recfg_sup:{}, suspend_sup:{}", bd_addr, p_scb->recfg_sup, + p_scb->suspend_sup); if (p_scb->PeerAddress() != bd_addr) { - log::info("reset flags old_addr={} new_addr={}", p_scb->PeerAddress(), - bd_addr); + log::info("reset flags old_addr={} new_addr={}", p_scb->PeerAddress(), bd_addr); /* a new addr, reset the supported flags */ p_scb->recfg_sup = true; p_scb->suspend_sup = true; @@ -245,17 +236,17 @@ static void bta_av_save_addr(tBTA_AV_SCB* p_scb, const RawAddress& bd_addr) { * ******************************************************************************/ static void notify_start_failed(tBTA_AV_SCB* p_scb) { - log::error("peer {} role:0x{:x} bta_channel:{} bta_handle:0x{:x}", - p_scb->PeerAddress(), p_scb->role, p_scb->chnl, p_scb->hndl); + log::error("peer {} role:0x{:x} bta_channel:{} bta_handle:0x{:x}", p_scb->PeerAddress(), + p_scb->role, p_scb->chnl, p_scb->hndl); tBTA_AV bta_av_data = { - .start = - { - .chnl = p_scb->chnl, - .hndl = p_scb->hndl, - .status = BTA_AV_FAIL, - .initiator = true, - .suspending = false, - }, + .start = + { + .chnl = p_scb->chnl, + .hndl = p_scb->hndl, + .status = BTA_AV_FAIL, + .initiator = true, + .suspending = false, + }, }; /* if start failed, clear role */ @@ -282,8 +273,8 @@ void bta_av_st_rc_timer(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* /* p_data */) { /* (bta_av_cb.features & BTA_AV_FEAT_RCCT) && */ (p_scb->use_rc || (p_scb->role & BTA_AV_ROLE_AD_ACP))) { if ((p_scb->wait & BTA_AV_WAIT_ROLE_SW_BITS) == 0) { - bta_sys_start_timer(p_scb->avrc_ct_timer, BTA_AV_RC_DISC_TIME_VAL, - BTA_AV_AVRC_TIMER_EVT, p_scb->hndl); + bta_sys_start_timer(p_scb->avrc_ct_timer, BTA_AV_RC_DISC_TIME_VAL, BTA_AV_AVRC_TIMER_EVT, + p_scb->hndl); } else { p_scb->wait |= BTA_AV_WAIT_CHECK_RC; } @@ -306,23 +297,23 @@ static bool bta_av_next_getcap(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { uint16_t uuid_int = p_scb->uuid_int; uint8_t sep_requested = 0; - if (uuid_int == UUID_SERVCLASS_AUDIO_SOURCE) + if (uuid_int == UUID_SERVCLASS_AUDIO_SOURCE) { sep_requested = AVDT_TSEP_SNK; - else if (uuid_int == UUID_SERVCLASS_AUDIO_SINK) + } else if (uuid_int == UUID_SERVCLASS_AUDIO_SINK) { sep_requested = AVDT_TSEP_SRC; + } for (i = p_scb->sep_info_idx; i < p_scb->num_seps; i++) { /* steam not in use, is a sink, and is the right media type (audio/video) */ - if ((!p_scb->sep_info[i].in_use) && - (p_scb->sep_info[i].tsep == sep_requested) && + if ((!p_scb->sep_info[i].in_use) && (p_scb->sep_info[i].tsep == sep_requested) && (p_scb->sep_info[i].media_type == p_scb->media_type)) { p_scb->sep_info_idx = i; /* we got a stream; get its capabilities */ bool get_all_cap = (p_scb->AvdtpVersion() >= AVDT_VERSION_1_3) && (A2DP_GetAvdtpVersion() >= AVDT_VERSION_1_3); - AVDT_GetCapReq(p_scb->PeerAddress(), p_scb->hdi, p_scb->sep_info[i].seid, - &p_scb->peer_cap, &bta_av_proc_stream_evt, get_all_cap); + AVDT_GetCapReq(p_scb->PeerAddress(), p_scb->hdi, p_scb->sep_info[i].seid, &p_scb->peer_cap, + &bta_av_proc_stream_evt, get_all_cap); sent_cmd = true; break; } @@ -330,8 +321,7 @@ static bool bta_av_next_getcap(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { /* if no streams available then stream open fails */ if (!sent_cmd) { - log::error("BTA_AV_STR_GETCAP_FAIL_EVT: peer_addr={}", - p_scb->PeerAddress()); + log::error("BTA_AV_STR_GETCAP_FAIL_EVT: peer_addr={}", p_scb->PeerAddress()); bta_av_ssm_execute(p_scb, BTA_AV_STR_GETCAP_FAIL_EVT, p_data); } @@ -347,41 +337,34 @@ static bool bta_av_next_getcap(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { * Returns void * ******************************************************************************/ -void bta_av_proc_stream_evt(uint8_t handle, const RawAddress& bd_addr, - uint8_t event, tAVDT_CTRL* p_data, - uint8_t scb_index) { - log::assert_that(scb_index < BTA_AV_NUM_STRS, - "assert failed: scb_index < BTA_AV_NUM_STRS"); +void bta_av_proc_stream_evt(uint8_t handle, const RawAddress& bd_addr, uint8_t event, + tAVDT_CTRL* p_data, uint8_t scb_index) { + log::assert_that(scb_index < BTA_AV_NUM_STRS, "assert failed: scb_index < BTA_AV_NUM_STRS"); tBTA_AV_SCB* p_scb = bta_av_cb.p_scb[scb_index]; uint16_t sec_len = 0; - log::verbose( - "peer_address: {} avdt_handle: {} event=0x{:x} scb_index={} p_scb={}", - bd_addr, handle, event, scb_index, fmt::ptr(p_scb)); + log::verbose("peer_address: {} avdt_handle: {} event=0x{:x} scb_index={} p_scb={}", bd_addr, + handle, event, scb_index, fmt::ptr(p_scb)); if (p_data) { if (event == AVDT_SECURITY_IND_EVT) { - sec_len = (p_data->security_ind.len < BTA_AV_SECURITY_MAX_LEN) - ? p_data->security_ind.len - : BTA_AV_SECURITY_MAX_LEN; + sec_len = (p_data->security_ind.len < BTA_AV_SECURITY_MAX_LEN) ? p_data->security_ind.len + : BTA_AV_SECURITY_MAX_LEN; } else if (event == AVDT_SECURITY_CFM_EVT && p_data->hdr.err_code == 0) { - sec_len = (p_data->security_cfm.len < BTA_AV_SECURITY_MAX_LEN) - ? p_data->security_cfm.len - : BTA_AV_SECURITY_MAX_LEN; + sec_len = (p_data->security_cfm.len < BTA_AV_SECURITY_MAX_LEN) ? p_data->security_cfm.len + : BTA_AV_SECURITY_MAX_LEN; } } if (p_scb) { - tBTA_AV_STR_MSG* p_msg = - (tBTA_AV_STR_MSG*)osi_malloc(sizeof(tBTA_AV_STR_MSG) + sec_len); + tBTA_AV_STR_MSG* p_msg = (tBTA_AV_STR_MSG*)osi_malloc(sizeof(tBTA_AV_STR_MSG) + sec_len); /* copy event data, bd addr, and handle to event message buffer */ p_msg->hdr.offset = 0; p_msg->bd_addr = bd_addr; p_msg->scb_index = scb_index; - log::verbose("stream event bd_addr: {} scb_index: {}", p_msg->bd_addr, - scb_index); + log::verbose("stream event bd_addr: {} scb_index: {}", p_msg->bd_addr, scb_index); if (p_data != NULL) { memcpy(&p_msg->msg, p_data, sizeof(tAVDT_CTRL)); @@ -393,15 +376,13 @@ void bta_av_proc_stream_evt(uint8_t handle, const RawAddress& bd_addr, case AVDT_SECURITY_IND_EVT: p_msg->msg.security_ind.p_data = (uint8_t*)(p_msg + 1); - memcpy(p_msg->msg.security_ind.p_data, p_data->security_ind.p_data, - sec_len); + memcpy(p_msg->msg.security_ind.p_data, p_data->security_ind.p_data, sec_len); break; case AVDT_SECURITY_CFM_EVT: p_msg->msg.security_cfm.p_data = (uint8_t*)(p_msg + 1); if (p_data->hdr.err_code == 0) { - memcpy(p_msg->msg.security_cfm.p_data, p_data->security_cfm.p_data, - sec_len); + memcpy(p_msg->msg.security_cfm.p_data, p_data->security_cfm.p_data, sec_len); } break; @@ -429,7 +410,9 @@ void bta_av_proc_stream_evt(uint8_t handle, const RawAddress& bd_addr, } p_msg->initiator = false; - if (event == AVDT_SUSPEND_CFM_EVT) p_msg->initiator = true; + if (event == AVDT_SUSPEND_CFM_EVT) { + p_msg->initiator = true; + } log::verbose("bta_handle:0x{:x} avdt_handle:{}", p_scb->hndl, handle); p_msg->hdr.layer_specific = p_scb->hndl; @@ -454,20 +437,18 @@ void bta_av_proc_stream_evt(uint8_t handle, const RawAddress& bd_addr, * Returns void * ******************************************************************************/ -void bta_av_sink_data_cback(uint8_t handle, BT_HDR* p_pkt, uint32_t time_stamp, - uint8_t m_pt) { +void bta_av_sink_data_cback(uint8_t handle, BT_HDR* p_pkt, uint32_t time_stamp, uint8_t m_pt) { int index = 0; tBTA_AV_SCB* p_scb; log::verbose( - "avdt_handle: {} pkt_len=0x{:x} offset = 0x{:x} number of frames 0x{:x} " - "sequence number 0x{:x}", - handle, p_pkt->len, p_pkt->offset, - *((uint8_t*)(p_pkt + 1) + p_pkt->offset), p_pkt->layer_specific); + "avdt_handle: {} pkt_len=0x{:x} offset = 0x{:x} number of frames 0x{:x} " + "sequence number 0x{:x}", + handle, p_pkt->len, p_pkt->offset, *((uint8_t*)(p_pkt + 1) + p_pkt->offset), + p_pkt->layer_specific); /* Get SCB and correct sep type */ for (index = 0; index < BTA_AV_NUM_STRS; index++) { p_scb = bta_av_cb.p_scb[index]; - if ((p_scb->avdt_handle == handle) && - (p_scb->seps[p_scb->sep_idx].tsep == AVDT_TSEP_SNK)) { + if ((p_scb->avdt_handle == handle) && (p_scb->seps[p_scb->sep_idx].tsep == AVDT_TSEP_SNK)) { break; } } @@ -478,7 +459,7 @@ void bta_av_sink_data_cback(uint8_t handle, BT_HDR* p_pkt, uint32_t time_stamp, } p_pkt->event = BTA_AV_SINK_MEDIA_DATA_EVT; p_scb->seps[p_scb->sep_idx].p_app_sink_data_cback( - p_scb->PeerAddress(), BTA_AV_SINK_MEDIA_DATA_EVT, (tBTA_AV_MEDIA*)p_pkt); + p_scb->PeerAddress(), BTA_AV_SINK_MEDIA_DATA_EVT, (tBTA_AV_MEDIA*)p_pkt); /* Free the buffer: a copy of the packet has been delivered */ osi_free(p_pkt); } @@ -508,8 +489,7 @@ static void bta_av_a2dp_sdp_cback(bool found, tA2DP_Service* p_service, return; } if (bta_av_cb.handle != p_scb->hndl) { - log::warn("SDP bta_handle expected=0x{:x} processing=0x{:x}", - bta_av_cb.handle, p_scb->hndl); + log::warn("SDP bta_handle expected=0x{:x} processing=0x{:x}", bta_av_cb.handle, p_scb->hndl); } if (!found) { @@ -517,8 +497,7 @@ static void bta_av_a2dp_sdp_cback(bool found, tA2DP_Service* p_service, } log::verbose("peer {} found={}", p_scb->PeerAddress(), found); - tBTA_AV_SDP_RES* p_msg = - (tBTA_AV_SDP_RES*)osi_malloc(sizeof(tBTA_AV_SDP_RES)); + tBTA_AV_SDP_RES* p_msg = (tBTA_AV_SDP_RES*)osi_malloc(sizeof(tBTA_AV_SDP_RES)); if (found) { p_msg->hdr.event = BTA_AV_SDP_DISC_OK_EVT; } else { @@ -528,18 +507,15 @@ static void bta_av_a2dp_sdp_cback(bool found, tA2DP_Service* p_service, if (found) { if (p_service != NULL) { p_scb->SetAvdtpVersion(p_service->avdt_version); - DEVICE_IOT_CONFIG_ADDR_SET_HEX_IF_GREATER( - p_scb->PeerAddress(), IOT_CONF_KEY_A2DP_VERSION, - p_service->avdt_version, IOT_CONF_BYTE_NUM_2); + DEVICE_IOT_CONFIG_ADDR_SET_HEX_IF_GREATER(p_scb->PeerAddress(), IOT_CONF_KEY_A2DP_VERSION, + p_service->avdt_version, IOT_CONF_BYTE_NUM_2); if (p_service->avdt_version != 0) { - if (btif_config_set_bin(p_scb->PeerAddress().ToString(), - BTIF_STORAGE_KEY_AVDTP_VERSION, + if (btif_config_set_bin(p_scb->PeerAddress().ToString(), BTIF_STORAGE_KEY_AVDTP_VERSION, (const uint8_t*)&p_service->avdt_version, sizeof(p_service->avdt_version))) { } else { - log::warn("Failed to store peer AVDTP version for {}", - p_scb->PeerAddress()); + log::warn("Failed to store peer AVDTP version for {}", p_scb->PeerAddress()); } } } @@ -566,8 +542,7 @@ static void bta_av_adjust_seps_idx(tBTA_AV_SCB* p_scb, uint8_t avdt_handle) { log::verbose("avdt_handle: {} codec: {}", p_scb->seps[i].av_handle, A2DP_CodecName(p_scb->seps[i].codec_info)); if (p_scb->seps[i].av_handle && (p_scb->seps[i].av_handle == avdt_handle) && - A2DP_CodecTypeEquals(p_scb->seps[i].codec_info, - p_scb->cfg.codec_info)) { + A2DP_CodecTypeEquals(p_scb->seps[i].codec_info, p_scb->cfg.codec_info)) { p_scb->sep_idx = i; p_scb->avdt_handle = p_scb->seps[i].av_handle; break; @@ -590,16 +565,15 @@ void bta_av_switch_role(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* /* p_data */) { tBTA_AV_API_OPEN* p_buf = &p_scb->q_info.open; log::verbose("peer {} wait:0x{:x}", p_scb->PeerAddress(), p_scb->wait); - if (p_scb->wait & BTA_AV_WAIT_ROLE_SW_RES_START) + if (p_scb->wait & BTA_AV_WAIT_ROLE_SW_RES_START) { p_scb->wait |= BTA_AV_WAIT_ROLE_SW_RETRY; + } /* clear the masks set when the timer is started */ - p_scb->wait &= - ~(BTA_AV_WAIT_ROLE_SW_RES_OPEN | BTA_AV_WAIT_ROLE_SW_RES_START); + p_scb->wait &= ~(BTA_AV_WAIT_ROLE_SW_RES_OPEN | BTA_AV_WAIT_ROLE_SW_RES_START); if (p_scb->q_tag == BTA_AV_Q_TAG_OPEN) { - if (bta_av_switch_if_needed(p_scb) || - !bta_av_link_role_ok(p_scb, A2DP_SET_MULTL_BIT)) { + if (bta_av_switch_if_needed(p_scb) || !bta_av_link_role_ok(p_scb, A2DP_SET_MULTL_BIT)) { p_scb->wait |= BTA_AV_WAIT_ROLE_SW_RES_OPEN; } else { /* this should not happen in theory. Just in case... @@ -608,8 +582,7 @@ void bta_av_switch_role(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* /* p_data */) { } } else { /* report failure on OPEN */ - log::error("peer {} role switch failed (wait=0x{:x})", p_scb->PeerAddress(), - p_scb->wait); + log::error("peer {} role switch failed (wait=0x{:x})", p_scb->PeerAddress(), p_scb->wait); switch_res = BTA_AV_RS_FAIL; } @@ -637,9 +610,11 @@ void bta_av_switch_role(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* /* p_data */) { void bta_av_role_res(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { bool initiator = false; - log::verbose("peer {} q_tag:{}, wait:0x{:x}, role:0x{:x}", - p_scb->PeerAddress(), p_scb->q_tag, p_scb->wait, p_scb->role); - if (p_scb->role & BTA_AV_ROLE_START_INT) initiator = true; + log::verbose("peer {} q_tag:{}, wait:0x{:x}, role:0x{:x}", p_scb->PeerAddress(), p_scb->q_tag, + p_scb->wait, p_scb->role); + if (p_scb->role & BTA_AV_ROLE_START_INT) { + initiator = true; + } if (p_scb->q_tag == BTA_AV_Q_TAG_START) { if (p_scb->wait & BTA_AV_WAIT_ROLE_SW_STARTED) { @@ -649,21 +624,22 @@ void bta_av_role_res(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { bta_sys_idle(BTA_ID_AV, bta_av_cb.audio_open_cnt, p_scb->PeerAddress()); /* start failed because of role switch. */ tBTA_AV bta_av_data = { - .start = - { - .chnl = p_scb->chnl, - .hndl = p_scb->hndl, - .status = BTA_AV_FAIL_ROLE, - .initiator = initiator, - .suspending = false, - }, + .start = + { + .chnl = p_scb->chnl, + .hndl = p_scb->hndl, + .status = BTA_AV_FAIL_ROLE, + .initiator = initiator, + .suspending = false, + }, }; (*bta_av_cb.p_cback)(BTA_AV_START_EVT, &bta_av_data); } else { bta_av_start_ok(p_scb, p_data); } - } else if (p_scb->wait & BTA_AV_WAIT_ROLE_SW_RES_START) + } else if (p_scb->wait & BTA_AV_WAIT_ROLE_SW_RES_START) { p_scb->wait |= BTA_AV_WAIT_ROLE_SW_FAILED; + } } else if (p_scb->q_tag == BTA_AV_Q_TAG_OPEN) { if (p_scb->wait & BTA_AV_WAIT_ROLE_SW_RES_OPEN) { p_scb->role &= ~BTA_AV_ROLE_START_INT; @@ -672,16 +648,16 @@ void bta_av_role_res(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { if (p_data->role_res.hci_status != HCI_SUCCESS) { /* Open failed because of role switch. */ tBTA_AV bta_av_data = { - .open = - { - .chnl = p_scb->chnl, - .hndl = p_scb->hndl, - .bd_addr = p_scb->PeerAddress(), - .status = BTA_AV_FAIL_ROLE, - .starting = false, - .edr = 0, - .sep = AVDT_TSEP_INVALID, - }, + .open = + { + .chnl = p_scb->chnl, + .hndl = p_scb->hndl, + .bd_addr = p_scb->PeerAddress(), + .status = BTA_AV_FAIL_ROLE, + .starting = false, + .edr = 0, + .sep = AVDT_TSEP_INVALID, + }, }; if (p_scb->seps[p_scb->sep_idx].tsep == AVDT_TSEP_SRC) { bta_av_data.open.sep = AVDT_TSEP_SNK; @@ -695,14 +671,12 @@ void bta_av_role_res(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { bta_av_do_disc_a2dp(p_scb, (tBTA_AV_DATA*)&(p_scb->q_info.open)); } } else { - log::warn( - "peer {} unexpected role switch event: q_tag = {} wait = 0x{:x}", - p_scb->PeerAddress(), p_scb->q_tag, p_scb->wait); + log::warn("peer {} unexpected role switch event: q_tag = {} wait = 0x{:x}", + p_scb->PeerAddress(), p_scb->q_tag, p_scb->wait); } } - log::verbose("peer {} wait:0x{:x}, role:0x{:x}", p_scb->PeerAddress(), - p_scb->wait, p_scb->role); + log::verbose("peer {} wait:0x{:x}, role:0x{:x}", p_scb->PeerAddress(), p_scb->wait, p_scb->role); } /******************************************************************************* @@ -716,10 +690,9 @@ void bta_av_role_res(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { * ******************************************************************************/ void bta_av_delay_co(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { - log::verbose("peer {} bta_handle:0x{:x} delay:{}", p_scb->PeerAddress(), - p_scb->hndl, p_data->str_msg.msg.delay_rpt_cmd.delay); - p_scb->p_cos->delay(p_scb->hndl, p_scb->PeerAddress(), - p_data->str_msg.msg.delay_rpt_cmd.delay); + log::verbose("peer {} bta_handle:0x{:x} delay:{}", p_scb->PeerAddress(), p_scb->hndl, + p_data->str_msg.msg.delay_rpt_cmd.delay); + p_scb->p_cos->delay(p_scb->hndl, p_scb->PeerAddress(), p_data->str_msg.msg.delay_rpt_cmd.delay); } /******************************************************************************* @@ -734,24 +707,20 @@ void bta_av_delay_co(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { void bta_av_do_disc_a2dp(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { bool ok_continue = false; tA2DP_SDP_DB_PARAMS db_params; - uint16_t attr_list[] = {ATTR_ID_SERVICE_CLASS_ID_LIST, - ATTR_ID_PROTOCOL_DESC_LIST, + uint16_t attr_list[] = {ATTR_ID_SERVICE_CLASS_ID_LIST, ATTR_ID_PROTOCOL_DESC_LIST, ATTR_ID_BT_PROFILE_DESC_LIST}; uint16_t sdp_uuid = 0; /* UUID for which SDP has to be done */ - log::verbose("peer_addr: {} use_rc: {} switch_res:{}, oc:{}", - p_data->api_open.bd_addr, p_data->api_open.use_rc, - p_data->api_open.switch_res, bta_av_cb.audio_open_cnt); + log::verbose("peer_addr: {} use_rc: {} switch_res:{}, oc:{}", p_data->api_open.bd_addr, + p_data->api_open.use_rc, p_data->api_open.switch_res, bta_av_cb.audio_open_cnt); memcpy(&(p_scb->open_api), &(p_data->api_open), sizeof(tBTA_AV_API_OPEN)); switch (p_data->api_open.switch_res) { case BTA_AV_RS_NONE: - if (bta_av_switch_if_needed(p_scb) || - !bta_av_link_role_ok(p_scb, A2DP_SET_MULTL_BIT)) { + if (bta_av_switch_if_needed(p_scb) || !bta_av_link_role_ok(p_scb, A2DP_SET_MULTL_BIT)) { /* waiting for role switch result. save the api to control block */ - memcpy(&p_scb->q_info.open, &p_data->api_open, - sizeof(tBTA_AV_API_OPEN)); + memcpy(&p_scb->q_info.open, &p_data->api_open, sizeof(tBTA_AV_API_OPEN)); p_scb->wait |= BTA_AV_WAIT_ROLE_SW_RES_OPEN; p_scb->q_tag = BTA_AV_Q_TAG_OPEN; } else { @@ -762,8 +731,7 @@ void bta_av_do_disc_a2dp(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { case BTA_AV_RS_FAIL: /* report a new failure event */ p_scb->open_status = BTA_AV_FAIL_ROLE; - log::error("BTA_AV_SDP_DISC_FAIL_EVT: peer_addr={}", - p_scb->PeerAddress()); + log::error("BTA_AV_SDP_DISC_FAIL_EVT: peer_addr={}", p_scb->PeerAddress()); bta_av_ssm_execute(p_scb, BTA_AV_SDP_DISC_FAIL_EVT, NULL); break; @@ -782,17 +750,18 @@ void bta_av_do_disc_a2dp(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { break; } - log::verbose("ok_continue: {} wait:0x{:x}, q_tag: {}", ok_continue, - p_scb->wait, p_scb->q_tag); - if (!ok_continue) return; + log::verbose("ok_continue: {} wait:0x{:x}, q_tag: {}", ok_continue, p_scb->wait, p_scb->q_tag); + if (!ok_continue) { + return; + } /* clear the role switch bits */ p_scb->wait &= ~BTA_AV_WAIT_ROLE_SW_BITS; if (p_scb->wait & BTA_AV_WAIT_CHECK_RC) { p_scb->wait &= ~BTA_AV_WAIT_CHECK_RC; - bta_sys_start_timer(p_scb->avrc_ct_timer, BTA_AV_RC_DISC_TIME_VAL, - BTA_AV_AVRC_TIMER_EVT, p_scb->hndl); + bta_sys_start_timer(p_scb->avrc_ct_timer, BTA_AV_RC_DISC_TIME_VAL, BTA_AV_AVRC_TIMER_EVT, + p_scb->hndl); } /* store peer addr other parameters */ @@ -802,13 +771,10 @@ void bta_av_do_disc_a2dp(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { bta_sys_app_open(BTA_ID_AV, p_scb->app_id, p_scb->PeerAddress()); p_scb->uuid_int = p_data->api_open.uuid; - if (p_scb->AvdtpVersion() != 0 - && interop_match_addr_or_name( - INTEROP_A2DP_SKIP_SDP_DURING_RECONNECTION, - &p_scb->PeerAddress(), - &btif_storage_get_remote_device_property)) { - log::info("Skip SDP with valid AVDTP version 0x{:04x}", - p_scb->AvdtpVersion()); + if (p_scb->AvdtpVersion() != 0 && + interop_match_addr_or_name(INTEROP_A2DP_SKIP_SDP_DURING_RECONNECTION, &p_scb->PeerAddress(), + &btif_storage_get_remote_device_property)) { + log::info("Skip SDP with valid AVDTP version 0x{:04x}", p_scb->AvdtpVersion()); bta_av_a2dp_sdp_cback(true, nullptr, p_scb->PeerAddress()); return; } @@ -818,22 +784,19 @@ void bta_av_do_disc_a2dp(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { db_params.num_attr = 3; db_params.p_attrs = attr_list; p_scb->sdp_discovery_started = true; - if (p_scb->uuid_int == UUID_SERVCLASS_AUDIO_SINK) + if (p_scb->uuid_int == UUID_SERVCLASS_AUDIO_SINK) { sdp_uuid = UUID_SERVCLASS_AUDIO_SOURCE; - else if (p_scb->uuid_int == UUID_SERVCLASS_AUDIO_SOURCE) + } else if (p_scb->uuid_int == UUID_SERVCLASS_AUDIO_SOURCE) { sdp_uuid = UUID_SERVCLASS_AUDIO_SINK; + } - log::verbose( - "Initiate SDP discovery for peer {} : uuid_int=0x{:x} sdp_uuid=0x{:x}", - p_scb->PeerAddress(), p_scb->uuid_int, sdp_uuid); - tA2DP_STATUS find_service_status = - A2DP_FindService(sdp_uuid, p_scb->PeerAddress(), &db_params, - base::Bind(bta_av_a2dp_sdp_cback)); + log::verbose("Initiate SDP discovery for peer {} : uuid_int=0x{:x} sdp_uuid=0x{:x}", + p_scb->PeerAddress(), p_scb->uuid_int, sdp_uuid); + tA2DP_STATUS find_service_status = A2DP_FindService(sdp_uuid, p_scb->PeerAddress(), &db_params, + base::Bind(bta_av_a2dp_sdp_cback)); if (find_service_status != A2DP_SUCCESS) { - log::error( - "A2DP_FindService() failed for peer {} uuid_int=0x{:x} sdp_uuid=0x{:x} " - ": status={}", - p_scb->PeerAddress(), p_scb->uuid_int, sdp_uuid, find_service_status); + log::error("A2DP_FindService() failed for peer {} uuid_int=0x{:x} sdp_uuid=0x{:x} : status={}", + p_scb->PeerAddress(), p_scb->uuid_int, sdp_uuid, find_service_status); bta_av_a2dp_sdp_cback(false, nullptr, p_scb->PeerAddress()); } else { /* only one A2DP find service is active at a time */ @@ -892,7 +855,9 @@ void bta_av_cleanup(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* /* p_data */) { if (p_scb->deregistering) { /* remove stream */ for (int i = 0; i < BTAV_A2DP_CODEC_INDEX_MAX; i++) { - if (p_scb->seps[i].av_handle) AVDT_RemoveStream(p_scb->seps[i].av_handle); + if (p_scb->seps[i].av_handle) { + AVDT_RemoveStream(p_scb->seps[i].av_handle); + } p_scb->seps[i].av_handle = 0; } @@ -932,15 +897,14 @@ void bta_av_config_ind(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { tAVDT_SEP_INFO* p_info; const AvdtpSepConfig* p_evt_cfg = &p_data->str_msg.cfg; uint8_t psc_mask = (p_evt_cfg->psc_mask | p_scb->cfg.psc_mask); - uint8_t - local_sep; /* sep type of local handle on which connection was received */ + uint8_t local_sep; /* sep type of local handle on which connection was received */ tBTA_AV_STR_MSG* p_msg = (tBTA_AV_STR_MSG*)p_data; local_sep = bta_av_get_scb_sep_type(p_scb, p_msg->handle); p_scb->avdt_label = p_data->str_msg.msg.hdr.label; - log::verbose("peer {} bta_handle:0x{:x} local_sep:{}", p_scb->PeerAddress(), - p_scb->hndl, local_sep); + log::verbose("peer {} bta_handle:0x{:x} local_sep:{}", p_scb->PeerAddress(), p_scb->hndl, + local_sep); log::verbose("codec: {}", A2DP_CodecInfoString(p_evt_cfg->codec_info)); memcpy(p_scb->cfg.codec_info, p_evt_cfg->codec_info, AVDT_CODEC_SIZE); @@ -957,8 +921,7 @@ void bta_av_config_ind(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { (psc_mask != (p_scb->cfg.psc_mask & ~AVDT_PSC_DELAY_RPT)))) { setconfig.hndl = p_scb->hndl; /* we may not need this */ setconfig.err_code = AVDT_ERR_UNSUP_CFG; - bta_av_ssm_execute(p_scb, BTA_AV_CI_SETCONFIG_FAIL_EVT, - (tBTA_AV_DATA*)&setconfig); + bta_av_ssm_execute(p_scb, BTA_AV_CI_SETCONFIG_FAIL_EVT, (tBTA_AV_DATA*)&setconfig); } else { p_info = &p_scb->sep_info[0]; p_info->in_use = 0; @@ -968,39 +931,36 @@ void bta_av_config_ind(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { /* Sep type of Peer will be oppsite role to our local sep */ if (local_sep == AVDT_TSEP_SRC) { p_info->tsep = AVDT_TSEP_SNK; - DEVICE_IOT_CONFIG_ADDR_SET_INT(p_scb->PeerAddress(), - IOT_CONF_KEY_A2DP_ROLE, + DEVICE_IOT_CONFIG_ADDR_SET_INT(p_scb->PeerAddress(), IOT_CONF_KEY_A2DP_ROLE, IOT_CONF_VAL_A2DP_ROLE_SINK); } else if (local_sep == AVDT_TSEP_SNK) { p_info->tsep = AVDT_TSEP_SRC; - DEVICE_IOT_CONFIG_ADDR_SET_INT(p_scb->PeerAddress(), - IOT_CONF_KEY_A2DP_ROLE, + DEVICE_IOT_CONFIG_ADDR_SET_INT(p_scb->PeerAddress(), IOT_CONF_KEY_A2DP_ROLE, IOT_CONF_VAL_A2DP_ROLE_SOURCE); } p_scb->role |= BTA_AV_ROLE_AD_ACP; p_scb->cur_psc_mask = p_evt_cfg->psc_mask; - if (bta_av_cb.features & BTA_AV_FEAT_RCTG) + if (bta_av_cb.features & BTA_AV_FEAT_RCTG) { p_scb->use_rc = true; - else + } else { p_scb->use_rc = false; + } p_scb->num_seps = 1; p_scb->sep_info_idx = 0; - log::verbose("SEID: {} use_rc: {} cur_psc_mask:0x{:x}", p_info->seid, - p_scb->use_rc, p_scb->cur_psc_mask); + log::verbose("SEID: {} use_rc: {} cur_psc_mask:0x{:x}", p_info->seid, p_scb->use_rc, + p_scb->cur_psc_mask); /* in case of A2DP SINK this is the first time peer data is being sent to * co functions */ if (local_sep == AVDT_TSEP_SNK) { - p_scb->p_cos->setcfg(p_scb->hndl, p_scb->PeerAddress(), - p_evt_cfg->codec_info, p_info->seid, - p_evt_cfg->num_protect, p_evt_cfg->protect_info, - AVDT_TSEP_SNK, p_msg->handle); + p_scb->p_cos->setcfg(p_scb->hndl, p_scb->PeerAddress(), p_evt_cfg->codec_info, p_info->seid, + p_evt_cfg->num_protect, p_evt_cfg->protect_info, AVDT_TSEP_SNK, + p_msg->handle); } else { - p_scb->p_cos->setcfg(p_scb->hndl, p_scb->PeerAddress(), - p_evt_cfg->codec_info, p_info->seid, - p_evt_cfg->num_protect, p_evt_cfg->protect_info, - AVDT_TSEP_SRC, p_msg->handle); + p_scb->p_cos->setcfg(p_scb->hndl, p_scb->PeerAddress(), p_evt_cfg->codec_info, p_info->seid, + p_evt_cfg->num_protect, p_evt_cfg->protect_info, AVDT_TSEP_SRC, + p_msg->handle); } } } @@ -1017,8 +977,7 @@ void bta_av_config_ind(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { void bta_av_disconnect_req(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* /* p_data */) { tBTA_AV_RCB* p_rcb; - log::verbose("conn_lcb: 0x{:x} peer_addr: {}", bta_av_cb.conn_lcb, - p_scb->PeerAddress()); + log::verbose("conn_lcb: 0x{:x} peer_addr: {}", bta_av_cb.conn_lcb, p_scb->PeerAddress()); alarm_cancel(p_scb->link_signalling_timer); alarm_cancel(p_scb->accept_signalling_timer); @@ -1033,8 +992,8 @@ void bta_av_disconnect_req(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* /* p_data */) { } AVDT_DisconnectReq(p_scb->PeerAddress(), &bta_av_proc_stream_evt); } else { - log::warn("conn_lcb=0x{:x} bta_handle=0x{:x} (hdi={}) no link", - bta_av_cb.conn_lcb, p_scb->hndl, p_scb->hdi); + log::warn("conn_lcb=0x{:x} bta_handle=0x{:x} (hdi={}) no link", bta_av_cb.conn_lcb, p_scb->hndl, + p_scb->hdi); bta_av_ssm_execute(p_scb, BTA_AV_AVDT_DISCONNECT_EVT, NULL); } } @@ -1066,13 +1025,10 @@ void bta_av_security_req(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { ******************************************************************************/ void bta_av_security_rsp(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { if (bta_av_cb.features & BTA_AV_FEAT_PROTECT) { - AVDT_SecurityRsp(p_scb->avdt_handle, p_scb->avdt_label, - p_data->api_protect_rsp.error_code, - p_data->api_protect_rsp.p_data, - p_data->api_protect_rsp.len); + AVDT_SecurityRsp(p_scb->avdt_handle, p_scb->avdt_label, p_data->api_protect_rsp.error_code, + p_data->api_protect_rsp.p_data, p_data->api_protect_rsp.len); } else { - AVDT_SecurityRsp(p_scb->avdt_handle, p_scb->avdt_label, AVDT_ERR_NSC, NULL, - 0); + AVDT_SecurityRsp(p_scb->avdt_handle, p_scb->avdt_label, AVDT_ERR_NSC, NULL, 0); } } @@ -1095,53 +1051,55 @@ void bta_av_setconfig_rsp(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { /* we like this codec_type. find the sep_idx */ local_sep = bta_av_get_scb_sep_type(p_scb, avdt_handle); bta_av_adjust_seps_idx(p_scb, avdt_handle); - log::info( - "peer {} bta_handle=0x{:x} avdt_handle={} sep_idx={} cur_psc_mask:0x{:x}", - p_scb->PeerAddress(), p_scb->hndl, p_scb->avdt_handle, p_scb->sep_idx, - p_scb->cur_psc_mask); + log::info("peer {} bta_handle=0x{:x} avdt_handle={} sep_idx={} cur_psc_mask:0x{:x}", + p_scb->PeerAddress(), p_scb->hndl, p_scb->avdt_handle, p_scb->sep_idx, + p_scb->cur_psc_mask); - if ((AVDT_TSEP_SNK == local_sep) && - (p_data->ci_setconfig.err_code == AVDT_SUCCESS) && + if ((AVDT_TSEP_SNK == local_sep) && (p_data->ci_setconfig.err_code == AVDT_SUCCESS) && (p_scb->seps[p_scb->sep_idx].p_app_sink_data_cback != NULL)) { tBTA_AV_MEDIA av_sink_codec_info; av_sink_codec_info.avk_config.bd_addr = p_scb->PeerAddress(); av_sink_codec_info.avk_config.codec_info = p_scb->cfg.codec_info; p_scb->seps[p_scb->sep_idx].p_app_sink_data_cback( - p_scb->PeerAddress(), BTA_AV_SINK_MEDIA_CFG_EVT, &av_sink_codec_info); + p_scb->PeerAddress(), BTA_AV_SINK_MEDIA_CFG_EVT, &av_sink_codec_info); } - AVDT_ConfigRsp(p_scb->avdt_handle, p_scb->avdt_label, - p_data->ci_setconfig.err_code, p_data->ci_setconfig.category); + AVDT_ConfigRsp(p_scb->avdt_handle, p_scb->avdt_label, p_data->ci_setconfig.err_code, + p_data->ci_setconfig.category); alarm_cancel(p_scb->link_signalling_timer); if (p_data->ci_setconfig.err_code == AVDT_SUCCESS) { p_scb->wait = BTA_AV_WAIT_ACP_CAPS_ON; - if (p_data->ci_setconfig.recfg_needed) + if (p_data->ci_setconfig.recfg_needed) { p_scb->role |= BTA_AV_ROLE_SUSPEND_OPT; - log::verbose("recfg_needed:{} role:0x{:x} num:{}", - p_data->ci_setconfig.recfg_needed, p_scb->role, num); + } + log::verbose("recfg_needed:{} role:0x{:x} num:{}", p_data->ci_setconfig.recfg_needed, + p_scb->role, num); /* callout module tells BTA the number of "good" SEPs and their SEIDs. * getcap on these SEID */ p_scb->num_seps = num; - if (p_scb->cur_psc_mask & AVDT_PSC_DELAY_RPT) + if (p_scb->cur_psc_mask & AVDT_PSC_DELAY_RPT) { p_scb->SetAvdtpVersion(AVDT_VERSION_1_3); + } - if (A2DP_GetCodecType(p_scb->cfg.codec_info) == A2DP_MEDIA_CT_SBC || - num > 1) { + if (A2DP_GetCodecType(p_scb->cfg.codec_info) == A2DP_MEDIA_CT_SBC || num > 1) { /* if SBC is used by the SNK as INT, discover req is not sent in * bta_av_config_ind. * call disc_res now */ /* this is called in A2DP SRC path only, In case of SINK we don't need it */ - if (local_sep == AVDT_TSEP_SRC) + if (local_sep == AVDT_TSEP_SRC) { p_scb->p_cos->disc_res(p_scb->hndl, p_scb->PeerAddress(), num, num, 0, UUID_SERVCLASS_AUDIO_SOURCE); + } } else { /* we do not know the peer device and it is using non-SBC codec * we need to know all the SEPs on SNK */ - if (p_scb->uuid_int == 0) p_scb->uuid_int = p_scb->open_api.uuid; + if (p_scb->uuid_int == 0) { + p_scb->uuid_int = p_scb->open_api.uuid; + } bta_av_discover_req(p_scb, NULL); return; } @@ -1204,26 +1162,21 @@ void bta_av_str_opened(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { // Don't use AVDTP SUSPEND for restrict listed devices btif_storage_get_stored_remote_name(p_scb->PeerAddress(), remote_name); if (interop_match_name(INTEROP_DISABLE_AVDTP_SUSPEND, remote_name) || - interop_match_addr(INTEROP_DISABLE_AVDTP_SUSPEND, - &p_scb->PeerAddress())) { - log::info("disable AVDTP SUSPEND: interop matched name {} address {}", - remote_name, p_scb->PeerAddress()); + interop_match_addr(INTEROP_DISABLE_AVDTP_SUSPEND, &p_scb->PeerAddress())) { + log::info("disable AVDTP SUSPEND: interop matched name {} address {}", remote_name, + p_scb->PeerAddress()); p_scb->suspend_sup = false; } - p_scb->stream_mtu = - p_data->str_msg.msg.open_ind.peer_mtu - AVDT_MEDIA_HDR_SIZE; - log::verbose("l2c_cid: 0x{:x} stream_mtu: {}", p_scb->l2c_cid, - p_scb->stream_mtu); + p_scb->stream_mtu = p_data->str_msg.msg.open_ind.peer_mtu - AVDT_MEDIA_HDR_SIZE; + log::verbose("l2c_cid: 0x{:x} stream_mtu: {}", p_scb->l2c_cid, p_scb->stream_mtu); /* Set the media channel as high priority */ if (!L2CA_SetTxPriority(p_scb->l2c_cid, L2CAP_CHNL_PRIORITY_HIGH)) { - log::warn("Unable to set L2CAP flush peer:{} cid:{}", p_scb->PeerAddress(), - p_scb->l2c_cid); + log::warn("Unable to set L2CAP flush peer:{} cid:{}", p_scb->PeerAddress(), p_scb->l2c_cid); } if (!L2CA_SetChnlFlushability(p_scb->l2c_cid, true)) { - log::warn("Unable to set L2CAP flush peer:{} cid:{}", p_scb->PeerAddress(), - p_scb->l2c_cid); + log::warn("Unable to set L2CAP flush peer:{} cid:{}", p_scb->PeerAddress(), p_scb->l2c_cid); } bta_sys_conn_open(BTA_ID_AV, p_scb->app_id, p_scb->PeerAddress()); @@ -1235,7 +1188,7 @@ void bta_av_str_opened(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { { /* TODO check if other audio channel is open. * If yes, check if reconfig is needed - * Rigt now we do not do this kind of checking. + * Right now we do not do this kind of checking. * BTA-AV is INT for 2nd audio connection. * The application needs to make sure the current codec_info is proper. * If one audio connection is open and another SNK attempts to connect to @@ -1244,24 +1197,24 @@ void bta_av_str_opened(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { */ /* check if other audio channel is started. If yes, start */ tBTA_AV_OPEN open = { - .chnl = p_scb->chnl, - .hndl = p_scb->hndl, - .bd_addr = p_scb->PeerAddress(), - .status = BTA_AV_SUCCESS, - .starting = false, - .edr = 0, - .sep = AVDT_TSEP_INVALID, + .chnl = p_scb->chnl, + .hndl = p_scb->hndl, + .bd_addr = p_scb->PeerAddress(), + .status = BTA_AV_SUCCESS, + .starting = false, + .edr = 0, + .sep = AVDT_TSEP_INVALID, }; L2CA_SetMediaStreamChannel(p_scb->l2c_cid, true); - p = get_btm_client_interface().peer.BTM_ReadRemoteFeatures( - p_scb->PeerAddress()); + p = get_btm_client_interface().peer.BTM_ReadRemoteFeatures(p_scb->PeerAddress()); if (p != NULL) { - if (HCI_EDR_ACL_2MPS_SUPPORTED(p)) open.edr |= BTA_AV_EDR_2MBPS; + if (HCI_EDR_ACL_2MPS_SUPPORTED(p)) { + open.edr |= BTA_AV_EDR_2MBPS; + } if (HCI_EDR_ACL_3MPS_SUPPORTED(p)) { - if (!interop_match_addr(INTEROP_2MBPS_LINK_ONLY, - &p_scb->PeerAddress())) { + if (!interop_match_addr(INTEROP_2MBPS_LINK_ONLY, &p_scb->PeerAddress())) { open.edr |= BTA_AV_EDR_3MBPS; } } @@ -1306,20 +1259,19 @@ void bta_av_security_ind(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { if (bta_av_cb.features & BTA_AV_FEAT_PROTECT) { tBTA_AV bta_av_data = { - .protect_req = - { - .chnl = p_scb->chnl, - .hndl = p_scb->hndl, - .p_data = p_data->str_msg.msg.security_ind.p_data, - .len = p_data->str_msg.msg.security_ind.len, - }, + .protect_req = + { + .chnl = p_scb->chnl, + .hndl = p_scb->hndl, + .p_data = p_data->str_msg.msg.security_ind.p_data, + .len = p_data->str_msg.msg.security_ind.len, + }, }; (*bta_av_cb.p_cback)(BTA_AV_PROTECT_REQ_EVT, &bta_av_data); } /* app doesn't support security indication; respond with failure */ else { - AVDT_SecurityRsp(p_scb->avdt_handle, p_scb->avdt_label, AVDT_ERR_NSC, NULL, - 0); + AVDT_SecurityRsp(p_scb->avdt_handle, p_scb->avdt_label, AVDT_ERR_NSC, NULL, 0); } } @@ -1335,14 +1287,14 @@ void bta_av_security_ind(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { void bta_av_security_cfm(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { if (bta_av_cb.features & BTA_AV_FEAT_PROTECT) { tBTA_AV bta_av_data = { - .protect_rsp = - { - .chnl = p_scb->chnl, - .hndl = p_scb->hndl, - .p_data = p_data->str_msg.msg.security_cfm.p_data, - .len = p_data->str_msg.msg.security_cfm.len, - .err_code = p_data->str_msg.msg.hdr.err_code, - }, + .protect_rsp = + { + .chnl = p_scb->chnl, + .hndl = p_scb->hndl, + .p_data = p_data->str_msg.msg.security_cfm.p_data, + .len = p_data->str_msg.msg.security_cfm.len, + .err_code = p_data->str_msg.msg.hdr.err_code, + }, }; (*bta_av_cb.p_cback)(BTA_AV_PROTECT_RSP_EVT, &bta_av_data); } @@ -1371,12 +1323,10 @@ void bta_av_do_close(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* /* p_data */) { p_scb->use_rtp_header_marker_bit = false; /* drop the buffers queued in L2CAP */ - const uint16_t buffers_left = - L2CA_FlushChannel(p_scb->l2c_cid, L2CAP_FLUSH_CHANS_ALL); + const uint16_t buffers_left = L2CA_FlushChannel(p_scb->l2c_cid, L2CAP_FLUSH_CHANS_ALL); if (buffers_left) { - log::warn( - "Unable to flush L2CAP ALL channel peer:{} cid:{} buffers_left:{}", - p_scb->PeerAddress(), p_scb->l2c_cid, buffers_left); + log::warn("Unable to flush L2CAP ALL channel peer:{} cid:{} buffers_left:{}", + p_scb->PeerAddress(), p_scb->l2c_cid, buffers_left); } AVDT_CloseReq(p_scb->avdt_handle); @@ -1385,8 +1335,8 @@ void bta_av_do_close(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* /* p_data */) { * when this timer expires, AVDT_DisconnectReq will be called to disconnect * the link */ - bta_sys_start_timer(p_scb->avrc_ct_timer, BTA_AV_CLOSE_REQ_TIME_VAL, - BTA_AV_API_CLOSE_EVT, p_scb->hndl); + bta_sys_start_timer(p_scb->avrc_ct_timer, BTA_AV_CLOSE_REQ_TIME_VAL, BTA_AV_API_CLOSE_EVT, + p_scb->hndl); } /******************************************************************************* @@ -1399,8 +1349,7 @@ void bta_av_do_close(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* /* p_data */) { * ******************************************************************************/ void bta_av_connect_req(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* /* p_data */) { - log::verbose("peer {} coll_mask=0x{:02x}", p_scb->PeerAddress(), - p_scb->coll_mask); + log::verbose("peer {} coll_mask=0x{:02x}", p_scb->PeerAddress(), p_scb->coll_mask); p_scb->sdp_discovery_started = false; if (p_scb->coll_mask & BTA_AV_COLL_INC_TMR) { /* SNK initiated L2C connection while SRC was doing SDP. */ @@ -1424,8 +1373,7 @@ void bta_av_connect_req(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* /* p_data */) { * ******************************************************************************/ void bta_av_sdp_failed(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { - log::error("peer_addr={} open_status={}", p_scb->PeerAddress(), - p_scb->open_status); + log::error("peer_addr={} open_status={}", p_scb->PeerAddress(), p_scb->open_status); if (p_scb->open_status == BTA_AV_SUCCESS) { p_scb->open_status = BTA_AV_FAIL_SDP; @@ -1451,8 +1399,8 @@ void bta_av_disc_results(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { /* our uuid in case we initiate connection */ uint16_t uuid_int = p_scb->uuid_int; - log::verbose("peer {} bta_handle: 0x{:x} initiator UUID 0x{:x}", - p_scb->PeerAddress(), p_scb->hndl, uuid_int); + log::verbose("peer {} bta_handle: 0x{:x} initiator UUID 0x{:x}", p_scb->PeerAddress(), + p_scb->hndl, uuid_int); /* store number of stream endpoints returned */ p_scb->num_seps = p_data->str_msg.msg.discover_cfm.num_seps; @@ -1460,47 +1408,48 @@ void bta_av_disc_results(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { if (btif_av_src_sink_coexist_enabled()) { for (i = 0; i < p_scb->num_seps; i++) { /* steam not in use, is a sink, and is audio */ - if ((!p_scb->sep_info[i].in_use) && - (p_scb->sep_info[i].media_type == p_scb->media_type)) { - if (p_scb->sep_info[i].tsep == AVDT_TSEP_SNK) num_snks++; + if ((!p_scb->sep_info[i].in_use) && (p_scb->sep_info[i].media_type == p_scb->media_type)) { + if (p_scb->sep_info[i].tsep == AVDT_TSEP_SNK) { + num_snks++; + } - if (p_scb->sep_info[i].tsep == AVDT_TSEP_SRC) num_srcs++; + if (p_scb->sep_info[i].tsep == AVDT_TSEP_SRC) { + num_srcs++; + } } } - log::verbose("both_enable={}, uuid_int=0x{:x}, incoming={}", - btif_av_both_enable(), uuid_int, p_scb->open_api.incoming); + log::verbose("both_enable={}, uuid_int=0x{:x}, incoming={}", btif_av_both_enable(), uuid_int, + p_scb->open_api.incoming); if (btif_av_both_enable() && p_scb->open_api.incoming) { - if (uuid_int == UUID_SERVCLASS_AUDIO_SOURCE && num_snks == 0 && - num_srcs > 0) { + if (uuid_int == UUID_SERVCLASS_AUDIO_SOURCE && num_snks == 0 && num_srcs > 0) { p_scb->uuid_int = UUID_SERVCLASS_AUDIO_SINK; - log::verbose("change UUID to 0x{:x}, num_snks={}, num_srcs={}", - p_scb->uuid_int, num_snks, num_srcs); - } else if (uuid_int == UUID_SERVCLASS_AUDIO_SINK && num_srcs == 0 && - num_snks > 0) { + log::verbose("change UUID to 0x{:x}, num_snks={}, num_srcs={}", p_scb->uuid_int, num_snks, + num_srcs); + } else if (uuid_int == UUID_SERVCLASS_AUDIO_SINK && num_srcs == 0 && num_snks > 0) { p_scb->uuid_int = UUID_SERVCLASS_AUDIO_SOURCE; - log::verbose("change UUID to 0x{:x}, num_snks={}, num_srcs={}", - p_scb->uuid_int, num_snks, num_srcs); + log::verbose("change UUID to 0x{:x}, num_snks={}, num_srcs={}", p_scb->uuid_int, num_snks, + num_srcs); } uuid_int = p_scb->uuid_int; } } else { for (i = 0; i < p_scb->num_seps; i++) { /* steam not in use, is a sink, and is audio */ - if ((!p_scb->sep_info[i].in_use) && - (p_scb->sep_info[i].media_type == p_scb->media_type)) { + if ((!p_scb->sep_info[i].in_use) && (p_scb->sep_info[i].media_type == p_scb->media_type)) { if ((p_scb->sep_info[i].tsep == AVDT_TSEP_SNK) && - (uuid_int == UUID_SERVCLASS_AUDIO_SOURCE)) + (uuid_int == UUID_SERVCLASS_AUDIO_SOURCE)) { num_snks++; + } - if ((p_scb->sep_info[i].tsep == AVDT_TSEP_SRC) && - (uuid_int == UUID_SERVCLASS_AUDIO_SINK)) + if ((p_scb->sep_info[i].tsep == AVDT_TSEP_SRC) && (uuid_int == UUID_SERVCLASS_AUDIO_SINK)) { num_srcs++; + } } } } - p_scb->p_cos->disc_res(p_scb->hndl, p_scb->PeerAddress(), p_scb->num_seps, - num_snks, num_srcs, uuid_int); + p_scb->p_cos->disc_res(p_scb->hndl, p_scb->PeerAddress(), p_scb->num_seps, num_snks, num_srcs, + uuid_int); p_scb->num_disc_snks = num_snks; p_scb->num_disc_srcs = num_srcs; @@ -1546,8 +1495,8 @@ void bta_av_disc_res_as_acp(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { num_snks++; } } - p_scb->p_cos->disc_res(p_scb->hndl, p_scb->PeerAddress(), p_scb->num_seps, - num_snks, 0, UUID_SERVCLASS_AUDIO_SOURCE); + p_scb->p_cos->disc_res(p_scb->hndl, p_scb->PeerAddress(), p_scb->num_seps, num_snks, 0, + UUID_SERVCLASS_AUDIO_SOURCE); p_scb->num_disc_snks = num_snks; p_scb->num_disc_srcs = 0; @@ -1581,17 +1530,15 @@ void bta_av_save_caps(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { uint8_t old_wait = p_scb->wait; bool getcap_done = false; - log::verbose( - "peer {} bta_handle:0x{:x} num_seps:{} sep_info_idx:{} wait:0x{:x}", - p_scb->PeerAddress(), p_scb->hndl, p_scb->num_seps, p_scb->sep_info_idx, - p_scb->wait); + log::verbose("peer {} bta_handle:0x{:x} num_seps:{} sep_info_idx:{} wait:0x{:x}", + p_scb->PeerAddress(), p_scb->hndl, p_scb->num_seps, p_scb->sep_info_idx, + p_scb->wait); log::verbose("codec: {}", A2DP_CodecInfoString(p_scb->peer_cap.codec_info)); cfg = p_scb->peer_cap; /* let application know the capability of the SNK */ - if (p_scb->p_cos->getcfg(p_scb->hndl, p_scb->PeerAddress(), cfg.codec_info, - &p_scb->sep_info_idx, p_info->seid, &cfg.num_protect, - cfg.protect_info) != A2DP_SUCCESS) { + if (p_scb->p_cos->getcfg(p_scb->hndl, p_scb->PeerAddress(), cfg.codec_info, &p_scb->sep_info_idx, + p_info->seid, &cfg.num_protect, cfg.protect_info) != A2DP_SUCCESS) { p_scb->sep_info_idx++; log::verbose("result: next sep_info_idx:{}", p_scb->sep_info_idx); } else { @@ -1606,14 +1553,16 @@ void bta_av_save_caps(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { /* matching media type(video not audio). */ /* In this case, we are done with getcap without sending another */ /* request to AVDT. */ - if (!bta_av_next_getcap(p_scb, p_data)) getcap_done = true; + if (!bta_av_next_getcap(p_scb, p_data)) { + getcap_done = true; + } } else { getcap_done = true; } if (getcap_done) { - log::verbose("getcap_done: num_seps:{} sep_info_idx:{} wait:0x{:x}", - p_scb->num_seps, p_scb->sep_info_idx, p_scb->wait); + log::verbose("getcap_done: num_seps:{} sep_info_idx:{} wait:0x{:x}", p_scb->num_seps, + p_scb->sep_info_idx, p_scb->wait); p_scb->wait &= ~(BTA_AV_WAIT_ACP_CAPS_ON | BTA_AV_WAIT_ACP_CAPS_STARTED); if (old_wait & BTA_AV_WAIT_ACP_CAPS_STARTED) { bta_av_start_ok(p_scb, NULL); @@ -1630,9 +1579,7 @@ void bta_av_save_caps(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { * Returns void * ******************************************************************************/ -void bta_av_set_use_rc(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* /* p_data */) { - p_scb->use_rc = true; -} +void bta_av_set_use_rc(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* /* p_data */) { p_scb->use_rc = true; } /******************************************************************************* * @@ -1671,8 +1618,9 @@ void bta_av_open_failed(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { for (idx = 0; (idx < BTA_AV_NUM_STRS) && (!is_av_opened); idx++) { p_opened_scb = bta_av_cb.p_scb[idx]; if (p_opened_scb && (p_opened_scb->state == BTA_AV_OPEN_SST) && - (p_opened_scb->PeerAddress() == p_scb->PeerAddress())) + (p_opened_scb->PeerAddress() == p_scb->PeerAddress())) { is_av_opened = true; + } } /* if there is already an active AV connnection with the same bd_addr, @@ -1680,13 +1628,13 @@ void bta_av_open_failed(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { BTA_AV_FAIL_GET_CAP status */ if (is_av_opened) { tBTA_AV bta_av_data = {.open = { - .chnl = p_scb->chnl, - .hndl = p_scb->hndl, - .bd_addr = p_scb->PeerAddress(), - .status = BTA_AV_FAIL_GET_CAP, - .starting = bta_av_chk_start(p_scb), - .edr = 0, - .sep = AVDT_TSEP_INVALID, + .chnl = p_scb->chnl, + .hndl = p_scb->hndl, + .bd_addr = p_scb->PeerAddress(), + .status = BTA_AV_FAIL_GET_CAP, + .starting = bta_av_chk_start(p_scb), + .edr = 0, + .sep = AVDT_TSEP_INVALID, }}; /* set the state back to initial state */ bta_av_set_scb_sst_init(p_scb); @@ -1698,11 +1646,10 @@ void bta_av_open_failed(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { } log::error( - "there is already an active connection: peer_addr={} chnl={} " - "hndl=0x{:x} status={} starting={} edr={}", - bta_av_data.open.bd_addr, bta_av_data.open.chnl, bta_av_data.open.hndl, - bta_av_data.open.status, bta_av_data.open.starting, - bta_av_data.open.edr); + "there is already an active connection: peer_addr={} chnl={} " + "hndl=0x{:x} status={} starting={} edr={}", + bta_av_data.open.bd_addr, bta_av_data.open.chnl, bta_av_data.open.hndl, + bta_av_data.open.status, bta_av_data.open.starting, bta_av_data.open.edr); (*bta_av_cb.p_cback)(BTA_AV_OPEN_EVT, &bta_av_data); } else { @@ -1731,18 +1678,15 @@ void bta_av_getcap_results(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { memcpy(cfg.codec_info, p_scb->peer_cap.codec_info, AVDT_CODEC_SIZE); memcpy(cfg.protect_info, p_scb->peer_cap.protect_info, AVDT_PROTECT_SIZE); - log::verbose("peer {} bta_handle:0x{:x} num_codec:{} psc_mask=0x{:x}", - p_scb->PeerAddress(), p_scb->hndl, p_scb->peer_cap.num_codec, - p_scb->cfg.psc_mask); + log::verbose("peer {} bta_handle:0x{:x} num_codec:{} psc_mask=0x{:x}", p_scb->PeerAddress(), + p_scb->hndl, p_scb->peer_cap.num_codec, p_scb->cfg.psc_mask); log::verbose("media type 0x{:x}, 0x{:x}", media_type, p_scb->media_type); log::verbose("codec: {}", A2DP_CodecInfoString(p_scb->cfg.codec_info)); /* if codec present and we get a codec configuration */ if ((p_scb->peer_cap.num_codec != 0) && (media_type == p_scb->media_type) && - (p_scb->p_cos->getcfg(p_scb->hndl, p_scb->PeerAddress(), cfg.codec_info, - &p_scb->sep_info_idx, p_info->seid, - &cfg.num_protect, - cfg.protect_info) == A2DP_SUCCESS)) { + (p_scb->p_cos->getcfg(p_scb->hndl, p_scb->PeerAddress(), cfg.codec_info, &p_scb->sep_info_idx, + p_info->seid, &cfg.num_protect, cfg.protect_info) == A2DP_SUCCESS)) { /* UUID for which connection was initiatied */ uint16_t uuid_int = p_scb->uuid_int; @@ -1753,36 +1697,33 @@ void bta_av_getcap_results(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { log::verbose("codec: {}", A2DP_CodecInfoString(p_scb->cfg.codec_info)); log::verbose("initiator UUID = 0x{:x}", uuid_int); - if (uuid_int == UUID_SERVCLASS_AUDIO_SOURCE) - bta_av_adjust_seps_idx(p_scb, - bta_av_get_scb_handle(p_scb, AVDT_TSEP_SRC)); - else if (uuid_int == UUID_SERVCLASS_AUDIO_SINK) - bta_av_adjust_seps_idx(p_scb, - bta_av_get_scb_handle(p_scb, AVDT_TSEP_SNK)); - log::info("sep_idx={} avdt_handle={} bta_handle=0x{:x}", p_scb->sep_idx, - p_scb->avdt_handle, p_scb->hndl); + if (uuid_int == UUID_SERVCLASS_AUDIO_SOURCE) { + bta_av_adjust_seps_idx(p_scb, bta_av_get_scb_handle(p_scb, AVDT_TSEP_SRC)); + } else if (uuid_int == UUID_SERVCLASS_AUDIO_SINK) { + bta_av_adjust_seps_idx(p_scb, bta_av_get_scb_handle(p_scb, AVDT_TSEP_SNK)); + } + log::info("sep_idx={} avdt_handle={} bta_handle=0x{:x}", p_scb->sep_idx, p_scb->avdt_handle, + p_scb->hndl); /* use only the services peer supports */ cfg.psc_mask &= p_scb->peer_cap.psc_mask; p_scb->cur_psc_mask = cfg.psc_mask; - log::verbose( - "peer {} bta_handle:0x{:x} sep_idx:{} sep_info_idx:{} " - "cur_psc_mask:0x{:x}", - p_scb->PeerAddress(), p_scb->hndl, p_scb->sep_idx, p_scb->sep_info_idx, - p_scb->cur_psc_mask); + log::verbose("peer {} bta_handle:0x{:x} sep_idx:{} sep_info_idx:{} cur_psc_mask:0x{:x}", + p_scb->PeerAddress(), p_scb->hndl, p_scb->sep_idx, p_scb->sep_info_idx, + p_scb->cur_psc_mask); if ((uuid_int == UUID_SERVCLASS_AUDIO_SINK) && (p_scb->seps[p_scb->sep_idx].p_app_sink_data_cback != NULL)) { log::verbose("configure decoder for Sink connection"); tBTA_AV_MEDIA av_sink_codec_info = { - .avk_config = - { - .codec_info = p_scb->cfg.codec_info, - .bd_addr = p_scb->PeerAddress(), - }, + .avk_config = + { + .codec_info = p_scb->cfg.codec_info, + .bd_addr = p_scb->PeerAddress(), + }, }; p_scb->seps[p_scb->sep_idx].p_app_sink_data_cback( - p_scb->PeerAddress(), BTA_AV_SINK_MEDIA_CFG_EVT, &av_sink_codec_info); + p_scb->PeerAddress(), BTA_AV_SINK_MEDIA_CFG_EVT, &av_sink_codec_info); } if (uuid_int == UUID_SERVCLASS_AUDIO_SOURCE) { @@ -1790,8 +1731,8 @@ void bta_av_getcap_results(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { } /* open the stream */ - AVDT_OpenReq(p_scb->seps[p_scb->sep_idx].av_handle, p_scb->PeerAddress(), - p_scb->hdi, p_scb->sep_info[p_scb->sep_info_idx].seid, &cfg); + AVDT_OpenReq(p_scb->seps[p_scb->sep_idx].av_handle, p_scb->PeerAddress(), p_scb->hdi, + p_scb->sep_info[p_scb->sep_info_idx].seid, &cfg); } else { /* try the next stream, if any */ p_scb->sep_info_idx++; @@ -1839,8 +1780,8 @@ void bta_av_setconfig_rej(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { void bta_av_discover_req(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* /* p_data */) { /* send avdtp discover request */ - AVDT_DiscoverReq(p_scb->PeerAddress(), p_scb->hdi, p_scb->sep_info, - BTA_AV_NUM_SEPS, &bta_av_proc_stream_evt); + AVDT_DiscoverReq(p_scb->PeerAddress(), p_scb->hdi, p_scb->sep_info, BTA_AV_NUM_SEPS, + &bta_av_proc_stream_evt); } /******************************************************************************* @@ -1853,8 +1794,7 @@ void bta_av_discover_req(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* /* p_data */) { * ******************************************************************************/ void bta_av_conn_failed(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { - log::error("peer_addr={} open_status={}", p_scb->PeerAddress(), - p_scb->open_status); + log::error("peer_addr={} open_status={}", p_scb->PeerAddress(), p_scb->open_status); p_scb->open_status = BTA_AV_FAIL_STREAM; bta_av_str_closed(p_scb, p_data); @@ -1870,11 +1810,8 @@ void bta_av_conn_failed(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { * ******************************************************************************/ void bta_av_do_start(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { - log::info( - "A2dp stream start peer:{} sco_occupied:{} av_role:0x{:x} started:{} " - "wait:0x{:x}", - p_scb->PeerAddress(), bta_av_cb.sco_occupied, p_scb->role, p_scb->started, - p_scb->wait); + log::info("A2dp stream start peer:{} sco_occupied:{} av_role:0x{:x} started:{} wait:0x{:x}", + p_scb->PeerAddress(), bta_av_cb.sco_occupied, p_scb->role, p_scb->started, p_scb->wait); if (bta_av_cb.sco_occupied) { log::warn("A2dp stream start failed"); bta_av_start_failed(p_scb, p_data); @@ -1885,10 +1822,10 @@ void bta_av_do_start(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { p_scb->role |= BTA_AV_ROLE_START_INT; if (p_scb->wait != 0) { log::warn( - "peer {} start stream request ignored: already waiting: " - "sco_occupied:{} role:0x{:x} started:{} wait:0x{:x}", - p_scb->PeerAddress(), bta_av_cb.sco_occupied, p_scb->role, - p_scb->started, p_scb->wait); + "peer {} start stream request ignored: already waiting: " + "sco_occupied:{} role:0x{:x} started:{} wait:0x{:x}", + p_scb->PeerAddress(), bta_av_cb.sco_occupied, p_scb->role, p_scb->started, + p_scb->wait); return; } if (p_scb->role & BTA_AV_ROLE_SUSPEND) { @@ -1904,10 +1841,9 @@ void bta_av_do_start(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { if ((p_scb->role & BTA_AV_ROLE_START_INT) != 0) { log::warn( - "peer {} start stream request ignored: already initiated: " - "sco_occupied:{} role:0x{:x} started:{} wait:0x{:x}", - p_scb->PeerAddress(), bta_av_cb.sco_occupied, p_scb->role, - p_scb->started, p_scb->wait); + "peer {} start stream request ignored: already initiated: " + "sco_occupied:{} role:0x{:x} started:{} wait:0x{:x}", + p_scb->PeerAddress(), bta_av_cb.sco_occupied, p_scb->role, p_scb->started, p_scb->wait); return; } @@ -1927,17 +1863,13 @@ void bta_av_do_start(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { uint16_t result = AVDT_StartReq(&p_scb->avdt_handle, 1); if (result != AVDT_SUCCESS) { - log::error("AVDT_StartReq failed for peer {} result:{}", - p_scb->PeerAddress(), result); + log::error("AVDT_StartReq failed for peer {} result:{}", p_scb->PeerAddress(), result); bta_av_start_failed(p_scb, p_data); } else if (p_data) { bta_av_set_use_latency_mode(p_scb, p_data->do_start.use_latency_mode); } - log::info( - "peer {} start requested: sco_occupied:{} role:0x{:x} started:{} " - "wait:0x{:x}", - p_scb->PeerAddress(), bta_av_cb.sco_occupied, p_scb->role, p_scb->started, - p_scb->wait); + log::info("peer {} start requested: sco_occupied:{} role:0x{:x} started:{} wait:0x{:x}", + p_scb->PeerAddress(), bta_av_cb.sco_occupied, p_scb->role, p_scb->started, p_scb->wait); } /******************************************************************************* @@ -1954,9 +1886,8 @@ void bta_av_str_stopped(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { bool sus_evt = true; BT_HDR* p_buf; - log::info("peer {} bta_handle:0x{:x} audio_open_cnt:{}, p_data {} start:{}", - p_scb->PeerAddress(), p_scb->hndl, bta_av_cb.audio_open_cnt, - fmt::ptr(p_data), start); + log::info("peer {} bta_handle:0x{:x} audio_open_cnt:{}, p_data {} start:{}", p_scb->PeerAddress(), + p_scb->hndl, bta_av_cb.audio_open_cnt, fmt::ptr(p_data), start); bta_sys_idle(BTA_ID_AV, bta_av_cb.audio_open_cnt, p_scb->PeerAddress()); BTM_unblock_role_switch_and_sniff_mode_for(p_scb->PeerAddress()); @@ -1987,14 +1918,11 @@ void bta_av_str_stopped(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { /* drop the audio buffers queued in L2CAP */ if (p_data && p_data->api_stop.flush) { - const uint16_t buffers_left = - L2CA_FlushChannel(p_scb->l2c_cid, L2CAP_FLUSH_CHANS_ALL); + const uint16_t buffers_left = L2CA_FlushChannel(p_scb->l2c_cid, L2CAP_FLUSH_CHANS_ALL); if (buffers_left) { - log::warn( - "Unable to flush all L2CAP ALL channel peer:{} cid:{} " - "buffers_left:{}", - p_scb->PeerAddress(), p_scb->l2c_cid, buffers_left); + log::warn("Unable to flush all L2CAP ALL channel peer:{} cid:{} buffers_left:{}", + p_scb->PeerAddress(), p_scb->l2c_cid, buffers_left); } } } @@ -2004,8 +1932,7 @@ void bta_av_str_stopped(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { suspend_rsp.hndl = p_scb->hndl; if (p_data && p_data->api_stop.suspend) { - log::verbose("peer {} suspending: {}, sup:{}", p_scb->PeerAddress(), start, - p_scb->suspend_sup); + log::verbose("peer {} suspending: {}, sup:{}", p_scb->PeerAddress(), start, p_scb->suspend_sup); if ((start) && (p_scb->suspend_sup)) { sus_evt = false; p_scb->l2c_bufs = 0; @@ -2029,8 +1956,7 @@ void bta_av_str_stopped(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { // Send STOP_EVT event only if not in reconfiguring state. // However, we should send STOP_EVT if we are reconfiguring when taking // the Close->Configure->Open->Start path. - if (p_scb->state != BTA_AV_RCFG_SST || - (p_data && p_data->api_stop.reconfig_stop)) { + if (p_scb->state != BTA_AV_RCFG_SST || (p_data && p_data->api_stop.reconfig_stop)) { tBTA_AV bta_av_data; bta_av_data.suspend = suspend_rsp; (*bta_av_cb.p_cback)(BTA_AV_STOP_EVT, &bta_av_data); @@ -2054,8 +1980,8 @@ void bta_av_reconfig(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { tBTA_AV_API_STOP stop = {}; tBTA_AV_API_RCFG* p_rcfg = &p_data->api_reconfig; - log::verbose("r:{}, s:{} idx: {} (o:{})", p_scb->recfg_sup, - p_scb->suspend_sup, p_scb->rcfg_idx, p_scb->sep_info_idx); + log::verbose("r:{}, s:{} idx: {} (o:{})", p_scb->recfg_sup, p_scb->suspend_sup, p_scb->rcfg_idx, + p_scb->sep_info_idx); p_scb->num_recfg = 0; /* store the new configuration in control block */ @@ -2063,18 +1989,15 @@ void bta_av_reconfig(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { alarm_cancel(p_scb->avrc_ct_timer); - log::debug( - "p_scb->sep_info_idx={} p_scb->rcfg_idx={} p_rcfg->sep_info_idx={}", - p_scb->sep_info_idx, p_scb->rcfg_idx, p_rcfg->sep_info_idx); - log::debug("Peer capable codec: {}", - A2DP_CodecInfoString(p_scb->peer_cap.codec_info)); + log::debug("p_scb->sep_info_idx={} p_scb->rcfg_idx={} p_rcfg->sep_info_idx={}", + p_scb->sep_info_idx, p_scb->rcfg_idx, p_rcfg->sep_info_idx); + log::debug("Peer capable codec: {}", A2DP_CodecInfoString(p_scb->peer_cap.codec_info)); log::debug("Current codec: {}", A2DP_CodecInfoString(p_scb->cfg.codec_info)); log::debug("Reconfig codec: {}", A2DP_CodecInfoString(p_rcfg->codec_info)); - BTM_LogHistory( - kBtmLogTag, p_scb->PeerAddress(), "Codec reconfig", - base::StringPrintf("%s => %s", A2DP_CodecName(p_scb->cfg.codec_info), - A2DP_CodecName(p_rcfg->codec_info))); + BTM_LogHistory(kBtmLogTag, p_scb->PeerAddress(), "Codec reconfig", + base::StringPrintf("%s => %s", A2DP_CodecName(p_scb->cfg.codec_info), + A2DP_CodecName(p_rcfg->codec_info))); p_cfg->num_protect = p_rcfg->num_protect; memcpy(p_cfg->codec_info, p_rcfg->codec_info, AVDT_CODEC_SIZE); @@ -2086,8 +2009,8 @@ void bta_av_reconfig(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { // can Suspend->Reconfigure->Start. // Otherwise, we have to Close->Configure->Open->Start or // Close->Configure->Open for streams that are / are not started. - if ((p_scb->rcfg_idx == p_scb->sep_info_idx) && p_rcfg->suspend && - p_scb->recfg_sup && p_scb->suspend_sup) { + if ((p_scb->rcfg_idx == p_scb->sep_info_idx) && p_rcfg->suspend && p_scb->recfg_sup && + p_scb->suspend_sup) { if (p_scb->started) { // Suspend->Reconfigure->Start stop.flush = false; @@ -2103,8 +2026,8 @@ void bta_av_reconfig(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { } } else { // Close the stream first, and then Configure it - log::verbose("Close/Open started: {} state: {} num_protect: {}", - p_scb->started, p_scb->state, p_cfg->num_protect); + log::verbose("Close/Open started: {} state: {} num_protect: {}", p_scb->started, p_scb->state, + p_cfg->num_protect); if (p_scb->started) { // Close->Configure->Open->Start if ((p_scb->rcfg_idx != p_scb->sep_info_idx) && p_scb->recfg_sup) { @@ -2123,13 +2046,10 @@ void bta_av_reconfig(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { bta_av_str_stopped(p_scb, NULL); } // Drop the buffers queued in L2CAP - const uint16_t buffers_left = - L2CA_FlushChannel(p_scb->l2c_cid, L2CAP_FLUSH_CHANS_ALL); + const uint16_t buffers_left = L2CA_FlushChannel(p_scb->l2c_cid, L2CAP_FLUSH_CHANS_ALL); if (buffers_left) { - log::warn( - "Unable to flush all L2CAP ALL channel peer:{} cid:{} " - "buffers_left:{}", - p_scb->PeerAddress(), p_scb->l2c_cid, buffers_left); + log::warn("Unable to flush all L2CAP ALL channel peer:{} cid:{} buffers_left:{}", + p_scb->PeerAddress(), p_scb->l2c_cid, buffers_left); } AVDT_CloseReq(p_scb->avdt_handle); } @@ -2151,17 +2071,20 @@ void bta_av_data_path(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* /* p_data */) { uint8_t m_pt = 0x60; tAVDT_DATA_OPT_MASK opt; - if (!p_scb->started) return; + if (!p_scb->started) { + return; + } - if (p_scb->cong) return; + if (p_scb->cong) { + return; + } if (p_scb->use_rtp_header_marker_bit) { m_pt |= AVDT_MARKER_SET; } // Always get the current number of bufs que'd up - p_scb->l2c_bufs = - (uint8_t)L2CA_FlushChannel(p_scb->l2c_cid, L2CAP_FLUSH_CHANS_GET); + p_scb->l2c_bufs = (uint8_t)L2CA_FlushChannel(p_scb->l2c_cid, L2CAP_FLUSH_CHANS_GET); if (!list_is_empty(p_scb->a2dp_list)) { p_buf = (BT_HDR*)list_front(p_scb->a2dp_list); @@ -2201,8 +2124,8 @@ void bta_av_data_path(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* /* p_data */) { // size_t extra_fragments_n = 0; if (p_buf->len > 0) { - extra_fragments_n = (p_buf->len / p_scb->stream_mtu) + - ((p_buf->len % p_scb->stream_mtu) ? 1 : 0) - 1; + extra_fragments_n = + (p_buf->len / p_scb->stream_mtu) + ((p_buf->len % p_scb->stream_mtu) ? 1 : 0) - 1; } std::vector extra_fragments; extra_fragments.reserve(extra_fragments_n); @@ -2212,14 +2135,15 @@ void bta_av_data_path(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* /* p_data */) { while (extra_fragments_n-- > 0) { data_begin += p_scb->stream_mtu; size_t fragment_len = data_end - data_begin; - if (fragment_len > p_scb->stream_mtu) fragment_len = p_scb->stream_mtu; + if (fragment_len > p_scb->stream_mtu) { + fragment_len = p_scb->stream_mtu; + } BT_HDR* p_buf2 = (BT_HDR*)osi_malloc(BT_DEFAULT_BUFFER_SIZE); p_buf2->offset = p_buf->offset; p_buf2->len = 0; p_buf2->layer_specific = 0; - uint8_t* packet2 = - (uint8_t*)(p_buf2 + 1) + p_buf2->offset + p_buf2->len; + uint8_t* packet2 = (uint8_t*)(p_buf2 + 1) + p_buf2->offset + p_buf2->len; memcpy(packet2, data_begin, fragment_len); p_buf2->len += fragment_len; extra_fragments.push_back(p_buf2); @@ -2278,18 +2202,15 @@ void bta_av_start_ok(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { tHCI_ROLE cur_role; uint8_t local_tsep = p_scb->seps[p_scb->sep_idx].tsep; - log::info("peer {} bta_handle:0x{:x} wait:0x{:x} role:0x{:x} local_tsep:{}", - p_scb->PeerAddress(), p_scb->hndl, p_scb->wait, p_scb->role, - local_tsep); + log::info("peer {} bta_handle:0x{:x} wait:0x{:x} role:0x{:x} local_tsep:{}", p_scb->PeerAddress(), + p_scb->hndl, p_scb->wait, p_scb->role, local_tsep); p_scb->started = true; if (local_tsep == AVDT_TSEP_SRC) { // The RTP Header marker bit for the A2DP Source encoder - A2dpCodecConfig* codec_config = - bta_av_get_a2dp_peer_current_codec(p_scb->PeerAddress()); - log::assert_that(codec_config != nullptr, - "assert failed: codec_config != nullptr"); + A2dpCodecConfig* codec_config = bta_av_get_a2dp_peer_current_codec(p_scb->PeerAddress()); + log::assert_that(codec_config != nullptr, "assert failed: codec_config != nullptr"); p_scb->use_rtp_header_marker_bit = codec_config->useRtpHeaderMarkerBit(); } @@ -2297,7 +2218,9 @@ void bta_av_start_ok(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { p_scb->sco_suspend = false; } - if (new_role & BTA_AV_ROLE_START_INT) initiator = true; + if (new_role & BTA_AV_ROLE_START_INT) { + initiator = true; + } /* for A2DP SINK we do not send get_caps */ if ((p_scb->avdt_handle == p_scb->seps[p_scb->sep_idx].av_handle) && @@ -2307,40 +2230,37 @@ void bta_av_start_ok(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { } if (p_scb->wait & BTA_AV_WAIT_ROLE_SW_FAILED) { /* role switch has failed */ - log::error( - "peer {} role switch failed: bta_handle:0x{:x} wait:0x{:x}, " - "role:0x{:x}", - p_scb->PeerAddress(), p_scb->hndl, p_scb->wait, p_scb->role); + log::error("peer {} role switch failed: bta_handle:0x{:x} wait:0x{:x}, role:0x{:x}", + p_scb->PeerAddress(), p_scb->hndl, p_scb->wait, p_scb->role); p_scb->wait &= ~BTA_AV_WAIT_ROLE_SW_FAILED; p_data = (tBTA_AV_DATA*)&hdr; hdr.offset = BTA_AV_RS_FAIL; } - log::verbose("peer {} wait:0x{:x} use_rtp_header_marker_bit:{}", - p_scb->PeerAddress(), p_scb->wait, - p_scb->use_rtp_header_marker_bit); + log::verbose("peer {} wait:0x{:x} use_rtp_header_marker_bit:{}", p_scb->PeerAddress(), + p_scb->wait, p_scb->use_rtp_header_marker_bit); if (p_data && (p_data->hdr.offset != BTA_AV_RS_NONE)) { p_scb->wait &= ~BTA_AV_WAIT_ROLE_SW_BITS; if (p_data->hdr.offset == BTA_AV_RS_FAIL) { bta_sys_idle(BTA_ID_AV, bta_av_cb.audio_open_cnt, p_scb->PeerAddress()); tBTA_AV bta_av_data = { - .start = - { - .chnl = p_scb->chnl, - .hndl = p_scb->hndl, - .status = BTA_AV_FAIL_ROLE, - .initiator = initiator, - .suspending = false, - }, + .start = + { + .chnl = p_scb->chnl, + .hndl = p_scb->hndl, + .status = BTA_AV_FAIL_ROLE, + .initiator = initiator, + .suspending = false, + }, }; (*bta_av_cb.p_cback)(BTA_AV_START_EVT, &bta_av_data); return; } } - if (!bta_av_link_role_ok(p_scb, A2DP_SET_ONE_BIT)) + if (!bta_av_link_role_ok(p_scb, A2DP_SET_ONE_BIT)) { p_scb->q_tag = BTA_AV_Q_TAG_START; - else { + } else { /* The wait flag may be set here while we are already central on the link */ /* this could happen if a role switch complete event occurred during * reconfig */ @@ -2350,15 +2270,14 @@ void bta_av_start_ok(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { p_scb->wait &= ~BTA_AV_WAIT_ROLE_SW_BITS; } - if (p_scb->wait & - (BTA_AV_WAIT_ROLE_SW_RES_OPEN | BTA_AV_WAIT_ROLE_SW_RES_START)) { + if (p_scb->wait & (BTA_AV_WAIT_ROLE_SW_RES_OPEN | BTA_AV_WAIT_ROLE_SW_RES_START)) { p_scb->wait |= BTA_AV_WAIT_ROLE_SW_STARTED; p_scb->q_tag = BTA_AV_Q_TAG_START; } if (p_scb->wait) { - log::error("peer {} wait:0x{:x} q_tag:{} not started", p_scb->PeerAddress(), - p_scb->wait, p_scb->q_tag); + log::error("peer {} wait:0x{:x} q_tag:{} not started", p_scb->PeerAddress(), p_scb->wait, + p_scb->q_tag); /* Clear first bit of p_scb->wait and not to return from this point else * HAL layer gets blocked. And if there is delay in Get Capability response * as @@ -2389,8 +2308,7 @@ void bta_av_start_ok(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { if (new_role & BTA_AV_ROLE_START_INT) { new_role &= ~BTA_AV_ROLE_START_INT; - } else if ((new_role & BTA_AV_ROLE_AD_ACP) && - (new_role & BTA_AV_ROLE_SUSPEND_OPT)) { + } else if ((new_role & BTA_AV_ROLE_AD_ACP) && (new_role & BTA_AV_ROLE_SUSPEND_OPT)) { suspend = true; } @@ -2420,22 +2338,22 @@ void bta_av_start_ok(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { p_scb->role &= ~BTA_AV_ROLE_SUSPEND_OPT; p_scb->no_rtp_header = false; - p_scb->p_cos->start(p_scb->hndl, p_scb->PeerAddress(), - p_scb->cfg.codec_info, &p_scb->no_rtp_header); + p_scb->p_cos->start(p_scb->hndl, p_scb->PeerAddress(), p_scb->cfg.codec_info, + &p_scb->no_rtp_header); p_scb->co_started = true; - log::verbose("peer {} suspending: {}, role:0x{:x}, init {}", - p_scb->PeerAddress(), suspend, p_scb->role, initiator); + log::verbose("peer {} suspending: {}, role:0x{:x}, init {}", p_scb->PeerAddress(), suspend, + p_scb->role, initiator); tBTA_AV bta_av_data = { - .start = - { - .chnl = p_scb->chnl, - .hndl = p_scb->hndl, - .status = BTA_AV_SUCCESS, - .initiator = initiator, - .suspending = suspend, - }, + .start = + { + .chnl = p_scb->chnl, + .hndl = p_scb->hndl, + .status = BTA_AV_SUCCESS, + .initiator = initiator, + .suspending = suspend, + }, }; (*bta_av_cb.p_cback)(BTA_AV_START_EVT, &bta_av_data); @@ -2446,10 +2364,10 @@ void bta_av_start_ok(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { p_scb->p_cos->stop(p_scb->hndl, p_scb->PeerAddress()); p_scb->co_started = false; tBTA_AV_API_STOP stop = { - .hdr = {}, - .suspend = true, - .flush = false, - .reconfig_stop = false, + .hdr = {}, + .suspend = true, + .flush = false, + .reconfig_stop = false, }; bta_av_ssm_execute(p_scb, BTA_AV_AP_STOP_EVT, (tBTA_AV_DATA*)&stop); } @@ -2466,10 +2384,9 @@ void bta_av_start_ok(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { * ******************************************************************************/ void bta_av_start_failed(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* /* p_data */) { - log::error( - "peer {} bta_handle:0x{:x} audio_open_cnt:{} started:{} co_started:{}", - p_scb->PeerAddress(), p_scb->hndl, bta_av_cb.audio_open_cnt, - p_scb->started, p_scb->co_started); + log::error("peer {} bta_handle:0x{:x} audio_open_cnt:{} started:{} co_started:{}", + p_scb->PeerAddress(), p_scb->hndl, bta_av_cb.audio_open_cnt, p_scb->started, + p_scb->co_started); if (!p_scb->started && !p_scb->co_started) { bta_sys_idle(BTA_ID_AV, bta_av_cb.audio_open_cnt, p_scb->PeerAddress()); @@ -2493,9 +2410,8 @@ void bta_av_str_closed(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { tBTA_AV data = {}; tBTA_AV_EVT event = {}; - log::warn("peer {} bta_handle:0x{:x} open_status:{} chnl:{} co_started:{}", - p_scb->PeerAddress(), p_scb->hndl, p_scb->open_status, p_scb->chnl, - p_scb->co_started); + log::warn("peer {} bta_handle:0x{:x} open_status:{} chnl:{} co_started:{}", p_scb->PeerAddress(), + p_scb->hndl, p_scb->open_status, p_scb->chnl, p_scb->co_started); BTM_unblock_role_switch_and_sniff_mode_for(p_scb->PeerAddress()); if (bta_av_cb.audio_open_cnt <= 1) { @@ -2511,10 +2427,11 @@ void bta_av_str_closed(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { data.open.chnl = p_scb->chnl; data.open.hndl = p_scb->hndl; - if (p_scb->seps[p_scb->sep_idx].tsep == AVDT_TSEP_SRC) + if (p_scb->seps[p_scb->sep_idx].tsep == AVDT_TSEP_SRC) { data.open.sep = AVDT_TSEP_SNK; - else if (p_scb->seps[p_scb->sep_idx].tsep == AVDT_TSEP_SNK) + } else if (p_scb->seps[p_scb->sep_idx].tsep == AVDT_TSEP_SNK) { data.open.sep = AVDT_TSEP_SRC; + } event = BTA_AV_OPEN_EVT; p_scb->open_status = BTA_AV_SUCCESS; @@ -2570,9 +2487,8 @@ void bta_av_suspend_cfm(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { tBTA_AV_SUSPEND suspend_rsp = {}; uint8_t err_code = p_data->str_msg.msg.hdr.err_code; - log::verbose("peer {} bta_handle:0x{:x} audio_open_cnt:{} err_code:{}", - p_scb->PeerAddress(), p_scb->hndl, bta_av_cb.audio_open_cnt, - err_code); + log::verbose("peer {} bta_handle:0x{:x} audio_open_cnt:{} err_code:{}", p_scb->PeerAddress(), + p_scb->hndl, bta_av_cb.audio_open_cnt, err_code); if (!p_scb->started) { /* handle the condition where there is a collision of SUSPEND req from @@ -2643,17 +2559,14 @@ void bta_av_suspend_cfm(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { ******************************************************************************/ void bta_av_rcfg_str_ok(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { p_scb->l2c_cid = AVDT_GetL2CapChannel(p_scb->avdt_handle); - log::verbose("peer {} bta_handle:0x{:x} l2c_cid:{}", p_scb->PeerAddress(), - p_scb->hndl, p_scb->l2c_cid); + log::verbose("peer {} bta_handle:0x{:x} l2c_cid:{}", p_scb->PeerAddress(), p_scb->hndl, + p_scb->l2c_cid); if (p_data != NULL) { // p_data could be NULL if the reconfig was triggered by the local device - p_scb->stream_mtu = - p_data->str_msg.msg.open_ind.peer_mtu - AVDT_MEDIA_HDR_SIZE; - log::verbose("l2c_cid: 0x{:x} stream_mtu: {}", p_scb->l2c_cid, - p_scb->stream_mtu); - p_scb->p_cos->update_mtu(p_scb->hndl, p_scb->PeerAddress(), - p_scb->stream_mtu); + p_scb->stream_mtu = p_data->str_msg.msg.open_ind.peer_mtu - AVDT_MEDIA_HDR_SIZE; + log::verbose("l2c_cid: 0x{:x} stream_mtu: {}", p_scb->l2c_cid, p_scb->stream_mtu); + p_scb->p_cos->update_mtu(p_scb->hndl, p_scb->PeerAddress(), p_scb->stream_mtu); } /* rc listen */ @@ -2667,12 +2580,12 @@ void bta_av_rcfg_str_ok(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { { /* reconfigure success */ tBTA_AV bta_av_data = { - .reconfig = - { - .chnl = p_scb->chnl, - .hndl = p_scb->hndl, - .status = BTA_AV_SUCCESS, - }, + .reconfig = + { + .chnl = p_scb->chnl, + .hndl = p_scb->hndl, + .status = BTA_AV_SUCCESS, + }, }; (*bta_av_cb.p_cback)(BTA_AV_RECONFIG_EVT, &bta_av_data); } @@ -2688,19 +2601,19 @@ void bta_av_rcfg_str_ok(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { * ******************************************************************************/ void bta_av_rcfg_failed(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { - log::error("num_recfg={} conn_lcb=0x{:x} peer_addr={}", p_scb->num_recfg, - bta_av_cb.conn_lcb, p_scb->PeerAddress()); + log::error("num_recfg={} conn_lcb=0x{:x} peer_addr={}", p_scb->num_recfg, bta_av_cb.conn_lcb, + p_scb->PeerAddress()); if (p_scb->num_recfg > BTA_AV_RECONFIG_RETRY) { bta_av_cco_close(p_scb, p_data); /* report failure */ tBTA_AV bta_av_data = { - .reconfig = - { - .chnl = p_scb->chnl, - .hndl = p_scb->hndl, - .status = BTA_AV_FAIL_STREAM, - }, + .reconfig = + { + .chnl = p_scb->chnl, + .hndl = p_scb->hndl, + .status = BTA_AV_FAIL_STREAM, + }, }; (*bta_av_cb.p_cback)(BTA_AV_RECONFIG_EVT, &bta_av_data); /* go to closing state */ @@ -2713,8 +2626,8 @@ void bta_av_rcfg_failed(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { if ((bta_av_cb.conn_lcb & (1 << p_scb->hdi)) != 0) { AVDT_DisconnectReq(p_scb->PeerAddress(), &bta_av_proc_stream_evt); } else { - log::warn("conn_lcb=0x{:x} bta_handle=0x{:x} (hdi={}) no link", - bta_av_cb.conn_lcb, p_scb->hndl, p_scb->hdi); + log::warn("conn_lcb=0x{:x} bta_handle=0x{:x} (hdi={}) no link", bta_av_cb.conn_lcb, + p_scb->hndl, p_scb->hdi); bta_av_connect_req(p_scb, NULL); } } @@ -2753,19 +2666,19 @@ void bta_av_rcfg_connect(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* /* p_data */) { * ******************************************************************************/ void bta_av_rcfg_discntd(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { - log::error("num_recfg={} conn_lcb=0x{:x} peer_addr={}", p_scb->num_recfg, - bta_av_cb.conn_lcb, p_scb->PeerAddress()); + log::error("num_recfg={} conn_lcb=0x{:x} peer_addr={}", p_scb->num_recfg, bta_av_cb.conn_lcb, + p_scb->PeerAddress()); p_scb->num_recfg++; if (p_scb->num_recfg > BTA_AV_RECONFIG_RETRY) { /* report failure */ tBTA_AV bta_av_data = { - .reconfig = - { - .chnl = p_scb->chnl, - .hndl = p_scb->hndl, - .status = BTA_AV_FAIL_STREAM, - }, + .reconfig = + { + .chnl = p_scb->chnl, + .hndl = p_scb->hndl, + .status = BTA_AV_FAIL_STREAM, + }, }; (*bta_av_cb.p_cback)(BTA_AV_RECONFIG_EVT, &bta_av_data); /* report close event & go to init state */ @@ -2796,24 +2709,22 @@ void bta_av_suspend_cont(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { if (AVDT_ERR_CONNECT == err_code) { /* report failure */ tBTA_AV bta_av_data = { - .reconfig = - { - .chnl = p_scb->chnl, - .hndl = p_scb->hndl, - .status = BTA_AV_FAIL, - }, + .reconfig = + { + .chnl = p_scb->chnl, + .hndl = p_scb->hndl, + .status = BTA_AV_FAIL, + }, }; (*bta_av_cb.p_cback)(BTA_AV_RECONFIG_EVT, &bta_av_data); - log::error("BTA_AV_STR_DISC_FAIL_EVT: peer_addr={}", - p_scb->PeerAddress()); + log::error("BTA_AV_STR_DISC_FAIL_EVT: peer_addr={}", p_scb->PeerAddress()); bta_av_ssm_execute(p_scb, BTA_AV_STR_DISC_FAIL_EVT, NULL); } else { /* drop the buffers queued in L2CAP */ - const uint16_t buffers_left = - L2CA_FlushChannel(p_scb->l2c_cid, L2CAP_FLUSH_CHANS_ALL); + const uint16_t buffers_left = L2CA_FlushChannel(p_scb->l2c_cid, L2CAP_FLUSH_CHANS_ALL); if (buffers_left) { - log::error("suspend rejected, closing peer:{} cid:{} buffers_left:{}", - p_scb->PeerAddress(), p_scb->l2c_cid, buffers_left); + log::error("suspend rejected, closing peer:{} cid:{} buffers_left:{}", p_scb->PeerAddress(), + p_scb->l2c_cid, buffers_left); } AVDT_CloseReq(p_scb->avdt_handle); } @@ -2846,14 +2757,12 @@ void bta_av_rcfg_cfm(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { bool disable_avdtp_reconfigure = false; { char remote_name[BD_NAME_LEN] = ""; - if (btif_storage_get_stored_remote_name(p_scb->PeerAddress(), - remote_name)) { + if (btif_storage_get_stored_remote_name(p_scb->PeerAddress(), remote_name)) { if (interop_match_name(INTEROP_DISABLE_AVDTP_RECONFIGURE, remote_name) || interop_match_addr(INTEROP_DISABLE_AVDTP_RECONFIGURE, (const RawAddress*)&p_scb->PeerAddress())) { - log::info( - "disable AVDTP RECONFIGURE: interop matched name {} address {}", - remote_name, p_scb->PeerAddress()); + log::info("disable AVDTP RECONFIGURE: interop matched name {} address {}", remote_name, + p_scb->PeerAddress()); disable_avdtp_reconfigure = true; } } @@ -2867,22 +2776,18 @@ void bta_av_rcfg_cfm(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { } /* started flag is false when reconfigure command is sent */ /* drop the buffers queued in L2CAP */ - const uint16_t buffers_left = - L2CA_FlushChannel(p_scb->l2c_cid, L2CAP_FLUSH_CHANS_ALL); + const uint16_t buffers_left = L2CA_FlushChannel(p_scb->l2c_cid, L2CAP_FLUSH_CHANS_ALL); if (buffers_left) { - log::error( - "reconfig rejected, closing queued peer:{} cid:{} buffers_left:{}", - p_scb->PeerAddress(), p_scb->l2c_cid, buffers_left); + log::error("reconfig rejected, closing queued peer:{} cid:{} buffers_left:{}", + p_scb->PeerAddress(), p_scb->l2c_cid, buffers_left); } AVDT_CloseReq(p_scb->avdt_handle); } else { /* update the codec info after rcfg cfm */ - log::verbose( - "updating from codec {} to codec {}", - A2DP_CodecName(p_scb->cfg.codec_info), - A2DP_CodecName(p_data->str_msg.msg.reconfig_cfm.p_cfg->codec_info)); - memcpy(p_scb->cfg.codec_info, - p_data->str_msg.msg.reconfig_cfm.p_cfg->codec_info, AVDT_CODEC_SIZE); + log::verbose("updating from codec {} to codec {}", A2DP_CodecName(p_scb->cfg.codec_info), + A2DP_CodecName(p_data->str_msg.msg.reconfig_cfm.p_cfg->codec_info)); + memcpy(p_scb->cfg.codec_info, p_data->str_msg.msg.reconfig_cfm.p_cfg->codec_info, + AVDT_CODEC_SIZE); /* take the SSM back to OPEN state */ bta_av_ssm_execute(p_scb, BTA_AV_STR_OPEN_OK_EVT, NULL); } @@ -2899,16 +2804,16 @@ void bta_av_rcfg_cfm(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { * ******************************************************************************/ void bta_av_rcfg_open(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* /* p_data */) { - log::verbose("peer {} bta_handle:0x{:x} num_disc_snks:{}", - p_scb->PeerAddress(), p_scb->hndl, p_scb->num_disc_snks); + log::verbose("peer {} bta_handle:0x{:x} num_disc_snks:{}", p_scb->PeerAddress(), p_scb->hndl, + p_scb->num_disc_snks); if (p_scb->num_disc_snks == 0) { /* Need to update call-out module so that it will be ready for discover */ p_scb->p_cos->stop(p_scb->hndl, p_scb->PeerAddress()); /* send avdtp discover request */ - AVDT_DiscoverReq(p_scb->PeerAddress(), p_scb->hdi, p_scb->sep_info, - BTA_AV_NUM_SEPS, &bta_av_proc_stream_evt); + AVDT_DiscoverReq(p_scb->PeerAddress(), p_scb->hdi, p_scb->sep_info, BTA_AV_NUM_SEPS, + &bta_av_proc_stream_evt); } else { log::verbose("calling AVDT_OpenReq()"); log::verbose("codec: {}", A2DP_CodecInfoString(p_scb->cfg.codec_info)); @@ -2916,8 +2821,8 @@ void bta_av_rcfg_open(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* /* p_data */) { /* we may choose to use a different SEP at reconfig. * adjust the sep_idx now */ bta_av_adjust_seps_idx(p_scb, bta_av_get_scb_handle(p_scb, AVDT_TSEP_SRC)); - log::info("sep_idx={} avdt_handle={} bta_handle=0x{:x}", p_scb->sep_idx, - p_scb->avdt_handle, p_scb->hndl); + log::info("sep_idx={} avdt_handle={} bta_handle=0x{:x}", p_scb->sep_idx, p_scb->avdt_handle, + p_scb->hndl); /* open the stream with the new config */ p_scb->sep_info_idx = p_scb->rcfg_idx; @@ -2936,8 +2841,7 @@ void bta_av_rcfg_open(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* /* p_data */) { * ******************************************************************************/ void bta_av_security_rej(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* /* p_data */) { - AVDT_SecurityRsp(p_scb->avdt_handle, p_scb->avdt_label, AVDT_ERR_BAD_STATE, - NULL, 0); + AVDT_SecurityRsp(p_scb->avdt_handle, p_scb->avdt_label, AVDT_ERR_BAD_STATE, NULL, 0); } /******************************************************************************* @@ -2950,24 +2854,22 @@ void bta_av_security_rej(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* /* p_data */) { * ******************************************************************************/ void bta_av_open_rc(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { - log::verbose("use_rc: {}, wait: 0x{:x} role: 0x{:x}", p_scb->use_rc, - p_scb->wait, p_scb->role); - if ((p_scb->wait & BTA_AV_WAIT_ROLE_SW_BITS) && - (p_scb->q_tag == BTA_AV_Q_TAG_START)) { + log::verbose("use_rc: {}, wait: 0x{:x} role: 0x{:x}", p_scb->use_rc, p_scb->wait, p_scb->role); + if ((p_scb->wait & BTA_AV_WAIT_ROLE_SW_BITS) && (p_scb->q_tag == BTA_AV_Q_TAG_START)) { /* waiting for role switch for some reason & the timer expires */ if (!bta_av_link_role_ok(p_scb, A2DP_SET_ONE_BIT)) { log::error("failed to start streaming for role management reasons!!"); alarm_cancel(p_scb->avrc_ct_timer); tBTA_AV bta_av_data = { - .start = - { - .chnl = p_scb->chnl, - .hndl = p_scb->hndl, - .status = BTA_AV_FAIL_ROLE, - .initiator = true, - .suspending = false, - }, + .start = + { + .chnl = p_scb->chnl, + .hndl = p_scb->hndl, + .status = BTA_AV_FAIL_ROLE, + .initiator = true, + .suspending = false, + }, }; p_scb->wait &= ~BTA_AV_WAIT_ROLE_SW_BITS; bta_av_cb.rs_idx = 0; @@ -2987,8 +2889,8 @@ void bta_av_open_rc(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { if (p_scb->rc_handle == BTA_AV_RC_HANDLE_NONE) { /* AVRC channel is not connected. delay a little bit */ if ((p_scb->wait & BTA_AV_WAIT_ROLE_SW_BITS) == 0) { - bta_sys_start_timer(p_scb->avrc_ct_timer, BTA_AV_RC_DISC_TIME_VAL, - BTA_AV_AVRC_TIMER_EVT, p_scb->hndl); + bta_sys_start_timer(p_scb->avrc_ct_timer, BTA_AV_RC_DISC_TIME_VAL, BTA_AV_AVRC_TIMER_EVT, + p_scb->hndl); } else { p_scb->wait |= BTA_AV_WAIT_CHECK_RC; } @@ -2997,12 +2899,10 @@ void bta_av_open_rc(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { /* use main SM for AVRC SDP activities */ if (btif_av_both_enable()) { /* if peer is sink, it should run new avrcp */ - if ((p_scb->seps[p_scb->sep_idx].tsep == AVDT_TSEP_SRC) && - is_new_avrcp_enabled()) { + if ((p_scb->seps[p_scb->sep_idx].tsep == AVDT_TSEP_SRC) && is_new_avrcp_enabled()) { log::warn("local src Using the new AVRCP Profile"); if (bluetooth::avrcp::AvrcpService::Get() != nullptr) { - bluetooth::avrcp::AvrcpService::Get()->ConnectDevice( - p_scb->PeerAddress()); + bluetooth::avrcp::AvrcpService::Get()->ConnectDevice(p_scb->PeerAddress()); return; } } @@ -3014,8 +2914,7 @@ void bta_av_open_rc(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { } if (btif_av_is_source_enabled() && is_new_avrcp_enabled()) { log::warn("Using the new AVRCP Profile"); - bluetooth::avrcp::AvrcpService::Get()->ConnectDevice( - p_scb->PeerAddress()); + bluetooth::avrcp::AvrcpService::Get()->ConnectDevice(p_scb->PeerAddress()); } else { bta_av_rc_disc((uint8_t)(p_scb->hdi + 1)); } @@ -3042,8 +2941,7 @@ void bta_av_open_rc(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { void bta_av_open_at_inc(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { memcpy(&(p_scb->open_api), &(p_data->api_open), sizeof(tBTA_AV_API_OPEN)); - log::verbose("peer {} coll_mask=0x{:02x}", p_scb->PeerAddress(), - p_scb->coll_mask); + log::verbose("peer {} coll_mask=0x{:02x}", p_scb->PeerAddress(), p_scb->coll_mask); if (p_scb->coll_mask & BTA_AV_COLL_INC_TMR) { p_scb->coll_mask |= BTA_AV_COLL_API_CALLED; @@ -3056,8 +2954,7 @@ void bta_av_open_at_inc(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { p_scb->coll_mask = 0; bta_av_set_scb_sst_init(p_scb); - tBTA_AV_API_OPEN* p_buf = - (tBTA_AV_API_OPEN*)osi_malloc(sizeof(tBTA_AV_API_OPEN)); + tBTA_AV_API_OPEN* p_buf = (tBTA_AV_API_OPEN*)osi_malloc(sizeof(tBTA_AV_API_OPEN)); memcpy(p_buf, &(p_scb->open_api), sizeof(tBTA_AV_API_OPEN)); bta_sys_sendmsg(p_buf); } @@ -3067,8 +2964,7 @@ void offload_vendor_callback(tBTM_VSC_CMPL* param) { tBTA_AV value{0}; uint8_t sub_opcode = 0; if (param->param_len) { - log::verbose("param_len = {} status = {}", param->param_len, - param->p_param_buf[0]); + log::verbose("param_len = {} status = {}", param->param_len, param->p_param_buf[0]); value.status = static_cast(param->p_param_buf[0]); } if (value.status == 0) { @@ -3086,8 +2982,7 @@ void offload_vendor_callback(tBTM_VSC_CMPL* param) { bta_av_cb.offload_started_hndl = bta_av_cb.offload_start_pending_hndl; bta_av_cb.offload_start_pending_hndl = BTA_AV_INVALID_HANDLE; } else { - log::info( - "No pending start command due to AVDTP suspend immediately"); + log::info("No pending start command due to AVDTP suspend immediately"); } (*bta_av_cb.p_cback)(BTA_AV_OFFLOAD_START_RSP_EVT, &value); break; @@ -3096,16 +2991,14 @@ void offload_vendor_callback(tBTM_VSC_CMPL* param) { } } else { log::verbose("Offload failed for subopcode= {}", sub_opcode); - if (param->opcode != VS_HCI_A2DP_OFFLOAD_STOP && - param->opcode != VS_HCI_A2DP_OFFLOAD_STOP_V2) { + if (param->opcode != VS_HCI_A2DP_OFFLOAD_STOP && param->opcode != VS_HCI_A2DP_OFFLOAD_STOP_V2) { bta_av_cb.offload_start_pending_hndl = BTA_AV_INVALID_HANDLE; (*bta_av_cb.p_cback)(BTA_AV_OFFLOAD_START_RSP_EVT, &value); } } } -void bta_av_vendor_offload_start(tBTA_AV_SCB* p_scb, - tBT_A2DP_OFFLOAD* offload_start) { +void bta_av_vendor_offload_start(tBTA_AV_SCB* p_scb, tBT_A2DP_OFFLOAD* offload_start) { uint8_t param[sizeof(tBT_A2DP_OFFLOAD)]; log::verbose(""); @@ -3123,30 +3016,25 @@ void bta_av_vendor_offload_start(tBTA_AV_SCB* p_scb, UINT16_TO_STREAM(p_param, offload_start->acl_hdl); UINT16_TO_STREAM(p_param, offload_start->l2c_rcid); UINT16_TO_STREAM(p_param, offload_start->mtu); - ARRAY_TO_STREAM(p_param, offload_start->codec_info, - (int8_t)sizeof(offload_start->codec_info)); + ARRAY_TO_STREAM(p_param, offload_start->codec_info, (int8_t)sizeof(offload_start->codec_info)); bta_av_cb.offload_start_pending_hndl = p_scb->hndl; bta_av_cb.offload_start_v2 = false; log::info( - "codec: {:#x}, sample rate: {:#x}, bit depth: {:#x}, channel: {:#x}, " - "bitrate: {:#x}, ACL: {:#x}, L2CAP: {:#x}, MTU: {:#x}", - offload_start->codec_type, offload_start->sample_rate, - offload_start->bits_per_sample, offload_start->ch_mode, - offload_start->encoded_audio_bitrate, offload_start->acl_hdl, - offload_start->l2c_rcid, offload_start->mtu); - get_btm_client_interface().vendor.BTM_VendorSpecificCommand( - HCI_CONTROLLER_A2DP, p_param - param, param, offload_vendor_callback); -} - -void bta_av_vendor_offload_start_v2(tBTA_AV_SCB* p_scb, - A2dpCodecConfigExt* offload_codec) { + "codec: {:#x}, sample rate: {:#x}, bit depth: {:#x}, channel: {:#x}, " + "bitrate: {:#x}, ACL: {:#x}, L2CAP: {:#x}, MTU: {:#x}", + offload_start->codec_type, offload_start->sample_rate, offload_start->bits_per_sample, + offload_start->ch_mode, offload_start->encoded_audio_bitrate, offload_start->acl_hdl, + offload_start->l2c_rcid, offload_start->mtu); + get_btm_client_interface().vendor.BTM_VendorSpecificCommand(HCI_CONTROLLER_A2DP, p_param - param, + param, offload_vendor_callback); +} + +void bta_av_vendor_offload_start_v2(tBTA_AV_SCB* p_scb, A2dpCodecConfigExt* offload_codec) { log::verbose(""); - uint16_t connection_handle = - get_btm_client_interface().peer.BTM_GetHCIConnHandle(p_scb->PeerAddress(), - BT_TRANSPORT_BR_EDR); - btav_a2dp_scmst_info_t scmst_info = - p_scb->p_cos->get_scmst_info(p_scb->PeerAddress()); + uint16_t connection_handle = get_btm_client_interface().peer.BTM_GetHCIConnHandle( + p_scb->PeerAddress(), BT_TRANSPORT_BR_EDR); + btav_a2dp_scmst_info_t scmst_info = p_scb->p_cos->get_scmst_info(p_scb->PeerAddress()); uint16_t mtu = p_scb->stream_mtu; uint16_t l2cap_channel_handle = 0; @@ -3176,10 +3064,8 @@ void bta_av_vendor_offload_start_v2(tBTA_AV_SCB* p_scb, UINT8_TO_STREAM(p_param, scmst_info.cp_header); // Vendor_Specific_Parameters_Len: 1 byte // Vendor_Specific_Parameters: N bytes - auto const& vendor_specific_parameters = - offload_codec->getVendorCodecParameters(); - UINT8_TO_STREAM(p_param, - static_cast(vendor_specific_parameters.size())); + auto const& vendor_specific_parameters = offload_codec->getVendorCodecParameters(); + UINT8_TO_STREAM(p_param, static_cast(vendor_specific_parameters.size())); ARRAY_TO_STREAM(p_param, vendor_specific_parameters.data(), static_cast(vendor_specific_parameters.size())); @@ -3187,8 +3073,8 @@ void bta_av_vendor_offload_start_v2(tBTA_AV_SCB* p_scb, bta_av_cb.offload_start_pending_hndl = p_scb->hndl; bta_av_cb.offload_start_v2 = true; - get_btm_client_interface().vendor.BTM_VendorSpecificCommand( - HCI_CONTROLLER_A2DP, p_param - param, param, offload_vendor_callback); + get_btm_client_interface().vendor.BTM_VendorSpecificCommand(HCI_CONTROLLER_A2DP, p_param - param, + param, offload_vendor_callback); } void bta_av_vendor_offload_stop() { @@ -3198,18 +3084,15 @@ void bta_av_vendor_offload_stop() { log::verbose(""); if (bta_av_cb.offload_start_v2) { - tBTA_AV_SCB* p_scb = - bta_av_hndl_to_scb(bta_av_cb.offload_start_pending_hndl); + tBTA_AV_SCB* p_scb = bta_av_hndl_to_scb(bta_av_cb.offload_start_pending_hndl); if (p_scb == nullptr) { return; } - uint16_t connection_handle = - get_btm_client_interface().peer.BTM_GetHCIConnHandle( + uint16_t connection_handle = get_btm_client_interface().peer.BTM_GetHCIConnHandle( p_scb->PeerAddress(), BT_TRANSPORT_BR_EDR); uint16_t l2cap_channel_handle = 0; - if (L2CA_GetRemoteChannelId(p_scb->l2c_cid, &l2cap_channel_handle) == - false) { + if (L2CA_GetRemoteChannelId(p_scb->l2c_cid, &l2cap_channel_handle) == false) { log::error("Failed to fetch l2c rcid"); } @@ -3225,8 +3108,8 @@ void bta_av_vendor_offload_stop() { *p_param++ = VS_HCI_A2DP_OFFLOAD_STOP; } - get_btm_client_interface().vendor.BTM_VendorSpecificCommand( - HCI_CONTROLLER_A2DP, p_param - param, param, offload_vendor_callback); + get_btm_client_interface().vendor.BTM_VendorSpecificCommand(HCI_CONTROLLER_A2DP, p_param - param, + param, offload_vendor_callback); } /******************************************************************************* @@ -3243,26 +3126,21 @@ void bta_av_offload_req(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { tBTA_AV_STATUS status = BTA_AV_FAIL_RESOURCES; tBT_A2DP_OFFLOAD offload_start; - log::verbose("stream {}, audio channels open {}", - p_scb->started ? "STARTED" : "STOPPED", + log::verbose("stream {}, audio channels open {}", p_scb->started ? "STARTED" : "STOPPED", bta_av_cb.audio_open_cnt); A2dpCodecConfig* codec_config = bta_av_get_a2dp_current_codec(); - log::assert_that(codec_config != nullptr, - "assert failed: codec_config != nullptr"); + log::assert_that(codec_config != nullptr, "assert failed: codec_config != nullptr"); /* Check if stream has already been started. */ /* Support offload if only one audio source stream is open. */ if (p_scb->started != true) { status = BTA_AV_FAIL_STREAM; - } else if (bta_av_cb.offload_start_pending_hndl || - bta_av_cb.offload_started_hndl) { + } else if (bta_av_cb.offload_start_pending_hndl || bta_av_cb.offload_started_hndl) { log::warn("offload already started, ignore request"); return; - } else if (::bluetooth::audio::a2dp::provider::supports_codec( - codec_config->codecIndex())) { - bta_av_vendor_offload_start_v2( - p_scb, static_cast(codec_config)); + } else if (::bluetooth::audio::a2dp::provider::supports_codec(codec_config->codecIndex())) { + bta_av_vendor_offload_start_v2(p_scb, static_cast(codec_config)); } else { bta_av_offload_codec_builder(p_scb, &offload_start); bta_av_vendor_offload_start(p_scb, &offload_start); @@ -3335,19 +3213,16 @@ void bta_av_offload_rsp(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data) { (*bta_av_cb.p_cback)(BTA_AV_OFFLOAD_START_RSP_EVT, &bta_av_data); } -static void bta_av_offload_codec_builder(tBTA_AV_SCB* p_scb, - tBT_A2DP_OFFLOAD* p_a2dp_offload) { +static void bta_av_offload_codec_builder(tBTA_AV_SCB* p_scb, tBT_A2DP_OFFLOAD* p_a2dp_offload) { A2dpCodecConfig* CodecConfig = bta_av_get_a2dp_current_codec(); - btav_a2dp_codec_index_t codec_index = - A2DP_SourceCodecIndex(p_scb->cfg.codec_info); + btav_a2dp_codec_index_t codec_index = A2DP_SourceCodecIndex(p_scb->cfg.codec_info); uint32_t codec_type = 0; uint16_t mtu = p_scb->stream_mtu; log::verbose("codec_index = {}", codec_index); switch (codec_index) { case BTAV_A2DP_CODEC_INDEX_SOURCE_SBC: codec_type = BTA_AV_CODEC_TYPE_SBC; - if (A2DP_GetMaxBitpoolSbc(p_scb->cfg.codec_info) <= - A2DP_SBC_BITPOOL_MIDDLE_QUALITY) { + if (A2DP_GetMaxBitpoolSbc(p_scb->cfg.codec_info) <= A2DP_SBC_BITPOOL_MIDDLE_QUALITY) { log::warn("Restricting streaming MTU size for MQ Bitpool"); mtu = MAX_2MBPS_AVDTP_MTU; } @@ -3371,20 +3246,19 @@ static void bta_av_offload_codec_builder(tBTA_AV_SCB* p_scb, log::error("Unknown Codec type"); return; } - if (mtu > MAX_3MBPS_AVDTP_MTU) mtu = MAX_3MBPS_AVDTP_MTU; + if (mtu > MAX_3MBPS_AVDTP_MTU) { + mtu = MAX_3MBPS_AVDTP_MTU; + } p_a2dp_offload->codec_type = codec_type; p_a2dp_offload->max_latency = 0; p_a2dp_offload->mtu = mtu; - p_a2dp_offload->acl_hdl = - get_btm_client_interface().peer.BTM_GetHCIConnHandle(p_scb->PeerAddress(), - BT_TRANSPORT_BR_EDR); - btav_a2dp_scmst_info_t scmst_info = - p_scb->p_cos->get_scmst_info(p_scb->PeerAddress()); + p_a2dp_offload->acl_hdl = get_btm_client_interface().peer.BTM_GetHCIConnHandle( + p_scb->PeerAddress(), BT_TRANSPORT_BR_EDR); + btav_a2dp_scmst_info_t scmst_info = p_scb->p_cos->get_scmst_info(p_scb->PeerAddress()); p_a2dp_offload->scms_t_enable[0] = scmst_info.enable_status; p_a2dp_offload->scms_t_enable[1] = scmst_info.cp_header; - log::verbose( - "SCMS-T_enable status: {}, SCMS-T header (if it's enabled): 0x{:02x}", - scmst_info.enable_status, scmst_info.cp_header); + log::verbose("SCMS-T_enable status: {}, SCMS-T header (if it's enabled): 0x{:02x}", + scmst_info.enable_status, scmst_info.cp_header); switch (A2DP_GetTrackSampleRate(p_scb->cfg.codec_info)) { case 44100: @@ -3400,8 +3274,7 @@ static void bta_av_offload_codec_builder(tBTA_AV_SCB* p_scb, p_a2dp_offload->sample_rate = BTAV_A2DP_CODEC_SAMPLE_RATE_96000; break; } - if (L2CA_GetRemoteChannelId(p_scb->l2c_cid, &p_a2dp_offload->l2c_rcid) == - false) { + if (L2CA_GetRemoteChannelId(p_scb->l2c_cid, &p_a2dp_offload->l2c_rcid) == false) { log::error("Failed to fetch l2c rcid"); return; } @@ -3423,8 +3296,7 @@ static void bta_av_offload_codec_builder(tBTA_AV_SCB* p_scb, } } void bta_av_api_set_peer_sep(tBTA_AV_DATA* p_data) { - log::verbose("bd_addr={}, sep:{}", p_data->peer_sep.addr, - p_data->peer_sep.sep); + log::verbose("bd_addr={}, sep:{}", p_data->peer_sep.addr, p_data->peer_sep.sep); const tBTA_AV_SCB* p_scb = bta_av_addr_to_scb(p_data->peer_sep.addr); if (!p_scb) { log::warn("scb not found"); diff --git a/system/bta/av/bta_av_act.cc b/system/bta/av/bta_av_act.cc index 76ef4c6bd8d..0f2c7fa1e09 100644 --- a/system/bta/av/bta_av_act.cc +++ b/system/bta/av/bta_av_act.cc @@ -91,8 +91,7 @@ tBTA_AV_RCB* bta_av_get_rcb_by_shdl(uint8_t shdl) { int i; for (i = 0; i < BTA_AV_NUM_RCB; i++) { - if (bta_av_cb.rcb[i].shdl == shdl && - bta_av_cb.rcb[i].handle != BTA_AV_RC_HANDLE_NONE) { + if (bta_av_cb.rcb[i].shdl == shdl && bta_av_cb.rcb[i].handle != BTA_AV_RC_HANDLE_NONE) { p_rcb = &bta_av_cb.rcb[i]; break; } @@ -122,10 +121,10 @@ void bta_av_del_rc(tBTA_AV_RCB* p_rcb) { p_scb = bta_av_cb.p_scb[p_rcb->shdl - 1]; } if (p_scb) { - log::verbose("shdl:{}, srch:{} rc_handle:{}", p_rcb->shdl, - p_scb->rc_handle, p_rcb->handle); - if (p_scb->rc_handle == p_rcb->handle) + log::verbose("shdl:{}, srch:{} rc_handle:{}", p_rcb->shdl, p_scb->rc_handle, p_rcb->handle); + if (p_scb->rc_handle == p_rcb->handle) { p_scb->rc_handle = BTA_AV_RC_HANDLE_NONE; + } /* just in case the RC timer is active if (bta_av_cb.features & BTA_AV_FEAT_RCCT && p_scb->chnl == BTA_AV_CHNL_AUDIO) */ @@ -133,9 +132,8 @@ void bta_av_del_rc(tBTA_AV_RCB* p_rcb) { } } - log::verbose("handle: {} status=0x{:x}, rc_acp_handle:{}, idx:{}", - p_rcb->handle, p_rcb->status, bta_av_cb.rc_acp_handle, - bta_av_cb.rc_acp_idx); + log::verbose("handle: {} status=0x{:x}, rc_acp_handle:{}, idx:{}", p_rcb->handle, p_rcb->status, + bta_av_cb.rc_acp_handle, bta_av_cb.rc_acp_idx); rc_handle = p_rcb->handle; if (!(p_rcb->status & BTA_AV_RC_CONN_MASK) || ((p_rcb->status & BTA_AV_RC_ROLE_MASK) == BTA_AV_RC_ROLE_INT)) { @@ -146,11 +144,11 @@ void bta_av_del_rc(tBTA_AV_RCB* p_rcb) { } /* else ACP && connected. do not clear the handle yet */ AVRC_Close(rc_handle); - if (rc_handle == bta_av_cb.rc_acp_handle) + if (rc_handle == bta_av_cb.rc_acp_handle) { bta_av_cb.rc_acp_handle = BTA_AV_RC_HANDLE_NONE; - log::verbose( - "end del_rc handle: {} status=0x{:x}, rc_acp_handle:{}, lidx:{}", - p_rcb->handle, p_rcb->status, bta_av_cb.rc_acp_handle, p_rcb->lidx); + } + log::verbose("end del_rc handle: {} status=0x{:x}, rc_acp_handle:{}, lidx:{}", p_rcb->handle, + p_rcb->status, bta_av_cb.rc_acp_handle, p_rcb->lidx); } } @@ -167,8 +165,9 @@ static void bta_av_close_all_rc(tBTA_AV_CB* p_cb) { int i; for (i = 0; i < BTA_AV_NUM_RCB; i++) { - if ((p_cb->disabling) || (bta_av_cb.rcb[i].shdl != 0)) + if ((p_cb->disabling) || (bta_av_cb.rcb[i].shdl != 0)) { bta_av_del_rc(&bta_av_cb.rcb[i]); + } } } @@ -216,19 +215,16 @@ static void bta_av_avrc_sdp_cback(uint16_t /* status */) { * Returns void * ******************************************************************************/ -static void bta_av_rc_ctrl_cback(uint8_t handle, uint8_t event, - uint16_t /* result */, +static void bta_av_rc_ctrl_cback(uint8_t handle, uint8_t event, uint16_t /* result */, const RawAddress* peer_addr) { uint16_t msg_event = 0; - if (btif_av_both_enable() && peer_addr != NULL && - btif_av_peer_is_connected_sink(*peer_addr)) { + if (btif_av_both_enable() && peer_addr != NULL && btif_av_peer_is_connected_sink(*peer_addr)) { log::warn("not cback legacy cback, and close the handle"); if (event == AVRC_CLOSE_IND_EVT || event == AVRC_OPEN_IND_EVT) { log::verbose("resend close event"); - tBTA_AV_RC_CONN_CHG* p_msg = - (tBTA_AV_RC_CONN_CHG*)osi_malloc(sizeof(tBTA_AV_RC_CONN_CHG)); + tBTA_AV_RC_CONN_CHG* p_msg = (tBTA_AV_RC_CONN_CHG*)osi_malloc(sizeof(tBTA_AV_RC_CONN_CHG)); p_msg->hdr.event = BTA_AV_AVRC_CLOSE_EVT; p_msg->handle = handle; p_msg->peer_addr = *peer_addr; @@ -252,8 +248,7 @@ static void bta_av_rc_ctrl_cback(uint8_t handle, uint8_t event, } if (msg_event) { - tBTA_AV_RC_CONN_CHG* p_msg = - (tBTA_AV_RC_CONN_CHG*)osi_malloc(sizeof(tBTA_AV_RC_CONN_CHG)); + tBTA_AV_RC_CONN_CHG* p_msg = (tBTA_AV_RC_CONN_CHG*)osi_malloc(sizeof(tBTA_AV_RC_CONN_CHG)); p_msg->hdr.event = msg_event; p_msg->handle = handle; p_msg->peer_addr = (peer_addr) ? (*peer_addr) : RawAddress::kEmpty; @@ -270,8 +265,7 @@ static void bta_av_rc_ctrl_cback(uint8_t handle, uint8_t event, * Returns void * ******************************************************************************/ -static void bta_av_rc_msg_cback(uint8_t handle, uint8_t label, uint8_t opcode, - tAVRC_MSG* p_msg) { +static void bta_av_rc_msg_cback(uint8_t handle, uint8_t label, uint8_t opcode, tAVRC_MSG* p_msg) { uint8_t* p_data_src = NULL; uint16_t data_len = 0; @@ -292,8 +286,7 @@ static void bta_av_rc_msg_cback(uint8_t handle, uint8_t label, uint8_t opcode, } /* Create a copy of the message */ - tBTA_AV_RC_MSG* p_buf = - (tBTA_AV_RC_MSG*)osi_malloc(sizeof(tBTA_AV_RC_MSG) + data_len); + tBTA_AV_RC_MSG* p_buf = (tBTA_AV_RC_MSG*)osi_malloc(sizeof(tBTA_AV_RC_MSG) + data_len); p_buf->hdr.event = BTA_AV_AVRC_MSG_EVT; p_buf->handle = handle; @@ -308,10 +301,11 @@ static void bta_av_rc_msg_cback(uint8_t handle, uint8_t label, uint8_t opcode, /* Update bta message buffer to point to payload data */ /* (Note AVRC_OP_BROWSING uses zero-copy: p_buf->msg.browse.p_browse_data * already points to original avrc buffer) */ - if (opcode == AVRC_OP_VENDOR) + if (opcode == AVRC_OP_VENDOR) { p_buf->msg.vendor.p_vendor_data = p_data_dst; - else if (opcode == AVRC_OP_PASS_THRU) + } else if (opcode == AVRC_OP_PASS_THRU) { p_buf->msg.pass.p_pass_data = p_data_dst; + } } if (opcode == AVRC_OP_BROWSE) { @@ -331,8 +325,7 @@ static void bta_av_rc_msg_cback(uint8_t handle, uint8_t label, uint8_t opcode, * Returns the created rc handle * ******************************************************************************/ -uint8_t bta_av_rc_create(tBTA_AV_CB* p_cb, uint8_t role, uint8_t shdl, - uint8_t lidx) { +uint8_t bta_av_rc_create(tBTA_AV_CB* p_cb, uint8_t role, uint8_t shdl, uint8_t lidx) { if ((!btif_av_src_sink_coexist_enabled() || (btif_av_src_sink_coexist_enabled() && !btif_av_is_sink_enabled() && btif_av_is_source_enabled())) && @@ -351,15 +344,13 @@ uint8_t bta_av_rc_create(tBTA_AV_CB* p_cb, uint8_t role, uint8_t shdl, if (role == AVCT_INT) { // Can't grab a stream control block that doesn't have a valid handle if (!shdl) { - log::error("Can't grab stream control block for shdl = {} -> index = {}", - shdl, shdl - 1); + log::error("Can't grab stream control block for shdl = {} -> index = {}", shdl, shdl - 1); return BTA_AV_RC_HANDLE_NONE; } tBTA_AV_SCB* p_scb = p_cb->p_scb[shdl - 1]; bda = p_scb->PeerAddress(); status = BTA_AV_RC_ROLE_INT; - DEVICE_IOT_CONFIG_ADDR_INT_ADD_ONE(p_scb->PeerAddress(), - IOT_CONF_KEY_AVRCP_CONN_COUNT); + DEVICE_IOT_CONFIG_ADDR_INT_ADD_ONE(p_scb->PeerAddress(), IOT_CONF_KEY_AVRCP_CONN_COUNT); } else { p_rcb = bta_av_get_rcb_by_shdl(shdl); @@ -376,8 +367,8 @@ uint8_t bta_av_rc_create(tBTA_AV_CB* p_cb, uint8_t role, uint8_t shdl, ccb.conn = role; /* note: BTA_AV_FEAT_RCTG = AVRC_CT_TARGET, BTA_AV_FEAT_RCCT = AVRC_CT_CONTROL */ - ccb.control = p_cb->features & (BTA_AV_FEAT_RCTG | BTA_AV_FEAT_RCCT | - BTA_AV_FEAT_METADATA | AVRC_CT_PASSIVE); + ccb.control = p_cb->features & + (BTA_AV_FEAT_RCTG | BTA_AV_FEAT_RCCT | BTA_AV_FEAT_METADATA | AVRC_CT_PASSIVE); if (AVRC_Open(&rc_handle, &ccb, bda) != AVRC_SUCCESS) { DEVICE_IOT_CONFIG_ADDR_INT_ADD_ONE(bda, IOT_CONF_KEY_AVRCP_CONN_FAIL_COUNT); @@ -403,12 +394,10 @@ uint8_t bta_av_rc_create(tBTA_AV_CB* p_cb, uint8_t role, uint8_t shdl, /* this LIDX is reserved for the AVRCP ACP connection */ p_cb->rc_acp_handle = p_rcb->handle; p_cb->rc_acp_idx = (i + 1); - log::verbose("rc_acp_handle:{} idx:{}", p_cb->rc_acp_handle, - p_cb->rc_acp_idx); + log::verbose("rc_acp_handle:{} idx:{}", p_cb->rc_acp_handle, p_cb->rc_acp_idx); } - log::verbose( - "create {}, role: {}, shdl:{}, rc_handle:{}, lidx:{}, status:0x{:x}", i, - role, shdl, p_rcb->handle, lidx, p_rcb->status); + log::verbose("create {}, role: {}, shdl:{}, rc_handle:{}, lidx:{}, status:0x{:x}", i, role, shdl, + p_rcb->handle, lidx, p_rcb->status); return rc_handle; } @@ -422,8 +411,7 @@ uint8_t bta_av_rc_create(tBTA_AV_CB* p_cb, uint8_t role, uint8_t shdl, * Returns AVRC_RSP_ACCEPT or AVRC_RSP_NOT_IMPL * ******************************************************************************/ -static tBTA_AV_CODE bta_av_group_navi_supported(uint8_t len, uint8_t* p_data, - bool is_inquiry) { +static tBTA_AV_CODE bta_av_group_navi_supported(uint8_t len, uint8_t* p_data, bool is_inquiry) { tBTA_AV_CODE ret = AVRC_RSP_NOT_IMPL; uint8_t* p_ptr = p_data; uint16_t u16; @@ -435,12 +423,15 @@ static tBTA_AV_CODE bta_av_group_navi_supported(uint8_t len, uint8_t* p_data, if (u32 == AVRC_CO_METADATA) { if (is_inquiry) { - if (u16 <= AVRC_PDU_PREV_GROUP) ret = AVRC_RSP_IMPL_STBL; + if (u16 <= AVRC_PDU_PREV_GROUP) { + ret = AVRC_RSP_IMPL_STBL; + } } else { - if (u16 <= AVRC_PDU_PREV_GROUP) + if (u16 <= AVRC_PDU_PREV_GROUP) { ret = AVRC_RSP_ACCEPT; - else + } else { ret = AVRC_RSP_REJ; + } } } } @@ -468,8 +459,7 @@ static tBTA_AV_CODE bta_av_op_supported(tBTA_AV_RC rc_id, bool is_inquiry) { } else { if (p_bta_av_rc_id[rc_id >> 4] & (1 << (rc_id & 0x0F))) { ret_code = AVRC_RSP_ACCEPT; - } else if ((p_bta_av_cfg->rc_pass_rsp == AVRC_RSP_INTERIM) && - p_bta_av_rc_id_ac) { + } else if ((p_bta_av_cfg->rc_pass_rsp == AVRC_RSP_INTERIM) && p_bta_av_rc_id_ac) { if (p_bta_av_rc_id_ac[rc_id >> 4] & (1 << (rc_id & 0x0F))) { ret_code = AVRC_RSP_INTERIM; } @@ -548,8 +538,7 @@ void bta_av_rc_opened(tBTA_AV_CB* p_cb, tBTA_AV_DATA* p_data) { return; } - log::verbose("local features {} peer features {}", p_cb->features, - p_cb->rcb[i].peer_features); + log::verbose("local features {} peer features {}", p_cb->features, p_cb->rcb[i].peer_features); /* listen to browsing channel when the connection is open, * if peer initiated AVRCP connection and local device supports browsing @@ -567,8 +556,7 @@ void bta_av_rc_opened(tBTA_AV_CB* p_cb, tBTA_AV_DATA* p_data) { p_cb->rcb[i].lidx = tmp; p_cb->rc_acp_handle = p_rcb->handle; p_cb->rc_acp_idx = (p_rcb - p_cb->rcb) + 1; - log::verbose("switching RCB rc_acp_handle:{} idx:{}", p_cb->rc_acp_handle, - p_cb->rc_acp_idx); + log::verbose("switching RCB rc_acp_handle:{} idx:{}", p_cb->rc_acp_handle, p_cb->rc_acp_idx); } } @@ -586,8 +574,8 @@ void bta_av_rc_opened(tBTA_AV_CB* p_cb, tBTA_AV_DATA* p_data) { p_lcb->lidx = BTA_AV_NUM_LINKS + 1; p_cb->rcb[i].lidx = p_lcb->lidx; p_lcb->conn_msk = 1; - log::error("bd_addr: {} rcb[{}].lidx={}, lcb.conn_msk=x{:x}", p_lcb->addr, - i, p_cb->rcb[i].lidx, p_lcb->conn_msk); + log::error("bd_addr: {} rcb[{}].lidx={}, lcb.conn_msk=x{:x}", p_lcb->addr, i, p_cb->rcb[i].lidx, + p_lcb->conn_msk); disc = p_data->rc_conn_chg.handle | BTA_AV_CHNL_MSK; } @@ -606,10 +594,10 @@ void bta_av_rc_opened(tBTA_AV_CB* p_cb, tBTA_AV_DATA* p_data) { } rc_open.status = BTA_AV_SUCCESS; log::verbose( - "local features:0x{:x} peer_features:0x{:x}, peer_ct_feature:0x{:x}, " - "peer_tg_feature:0x{:x}", - p_cb->features, rc_open.peer_features, rc_open.peer_ct_features, - rc_open.peer_tg_features); + "local features:0x{:x} peer_features:0x{:x}, peer_ct_feature:0x{:x}, " + "peer_tg_feature:0x{:x}", + p_cb->features, rc_open.peer_features, rc_open.peer_ct_features, + rc_open.peer_tg_features); if (rc_open.peer_features == 0 && rc_open.peer_ct_features == 0 && rc_open.peer_tg_features == 0) { /* we have not done SDP on peer RC capabilities. @@ -640,16 +628,17 @@ void bta_av_rc_opened(tBTA_AV_CB* p_cb, tBTA_AV_DATA* p_data) { return; } rc_open.status = BTA_AV_SUCCESS; - log::verbose("local features:x{:x} peer_features:x{:x}", p_cb->features, - rc_open.peer_features); + log::verbose("local features:x{:x} peer_features:x{:x}", p_cb->features, rc_open.peer_features); log::verbose("cover art psm:x{:x}", rc_open.cover_art_psm); if (rc_open.peer_features == 0) { /* we have not done SDP on peer RC capabilities. * peer must have initiated the RC connection */ - if (p_cb->features & BTA_AV_FEAT_RCCT) + if (p_cb->features & BTA_AV_FEAT_RCCT) { rc_open.peer_features |= BTA_AV_FEAT_RCTG; - if (p_cb->features & BTA_AV_FEAT_RCTG) + } + if (p_cb->features & BTA_AV_FEAT_RCTG) { rc_open.peer_features |= BTA_AV_FEAT_RCCT; + } bta_av_rc_disc(disc); } @@ -661,8 +650,7 @@ void bta_av_rc_opened(tBTA_AV_CB* p_cb, tBTA_AV_DATA* p_data) { * browsing channel, open the browsing channel now * TODO (sanketa): Some TG would not broadcast browse feature hence check * inter-op. */ - if ((p_cb->features & BTA_AV_FEAT_BROWSE) && - (rc_open.peer_features & BTA_AV_FEAT_BROWSE) && + if ((p_cb->features & BTA_AV_FEAT_BROWSE) && (rc_open.peer_features & BTA_AV_FEAT_BROWSE) && ((p_cb->rcb[i].status & BTA_AV_RC_ROLE_MASK) == BTA_AV_RC_ROLE_INT)) { log::verbose("opening AVRC Browse channel"); AVRC_OpenBrowse(p_data->rc_conn_chg.handle, AVCT_INT); @@ -684,8 +672,7 @@ void bta_av_rc_remote_cmd(tBTA_AV_CB* p_cb, tBTA_AV_DATA* p_data) { if (p_data->hdr.layer_specific < BTA_AV_NUM_RCB) { p_rcb = &p_cb->rcb[p_data->hdr.layer_specific]; if (p_rcb->status & BTA_AV_RC_CONN_MASK) { - AVRC_PassCmd(p_rcb->handle, p_data->api_remote_cmd.label, - &p_data->api_remote_cmd.msg); + AVRC_PassCmd(p_rcb->handle, p_data->api_remote_cmd.label, &p_data->api_remote_cmd.msg); } } } @@ -706,8 +693,7 @@ void bta_av_rc_vendor_cmd(tBTA_AV_CB* p_cb, tBTA_AV_DATA* p_data) { (BTA_AV_FEAT_RCCT | BTA_AV_FEAT_VENDOR)) { if (p_data->hdr.layer_specific < BTA_AV_NUM_RCB) { p_rcb = &p_cb->rcb[p_data->hdr.layer_specific]; - AVRC_VendorCmd(p_rcb->handle, p_data->api_vendor.label, - &p_data->api_vendor.msg); + AVRC_VendorCmd(p_rcb->handle, p_data->api_vendor.label, &p_data->api_vendor.msg); } } } @@ -727,8 +713,7 @@ void bta_av_rc_vendor_rsp(tBTA_AV_CB* p_cb, tBTA_AV_DATA* p_data) { (BTA_AV_FEAT_RCTG | BTA_AV_FEAT_VENDOR)) { if (p_data->hdr.layer_specific < BTA_AV_NUM_RCB) { p_rcb = &p_cb->rcb[p_data->hdr.layer_specific]; - AVRC_VendorRsp(p_rcb->handle, p_data->api_vendor.label, - &p_data->api_vendor.msg); + AVRC_VendorRsp(p_rcb->handle, p_data->api_vendor.label, &p_data->api_vendor.msg); } } } @@ -746,21 +731,21 @@ void bta_av_rc_meta_rsp(tBTA_AV_CB* p_cb, tBTA_AV_DATA* p_data) { tBTA_AV_RCB* p_rcb; bool do_free = true; - if ((p_cb->features & BTA_AV_FEAT_METADATA) && - (p_data->hdr.layer_specific < BTA_AV_NUM_RCB)) { + if ((p_cb->features & BTA_AV_FEAT_METADATA) && (p_data->hdr.layer_specific < BTA_AV_NUM_RCB)) { if ((p_data->api_meta_rsp.is_rsp && (p_cb->features & BTA_AV_FEAT_RCTG)) || (!p_data->api_meta_rsp.is_rsp && (p_cb->features & BTA_AV_FEAT_RCCT))) { p_rcb = &p_cb->rcb[p_data->hdr.layer_specific]; if (p_rcb->handle != BTA_AV_RC_HANDLE_NONE) { - AVRC_MsgReq(p_rcb->handle, p_data->api_meta_rsp.label, - p_data->api_meta_rsp.rsp_code, p_data->api_meta_rsp.p_pkt, - false); + AVRC_MsgReq(p_rcb->handle, p_data->api_meta_rsp.label, p_data->api_meta_rsp.rsp_code, + p_data->api_meta_rsp.p_pkt, false); do_free = false; } } } - if (do_free) osi_free_and_reset((void**)&p_data->api_meta_rsp.p_pkt); + if (do_free) { + osi_free_and_reset((void**)&p_data->api_meta_rsp.p_pkt); + } } /******************************************************************************* @@ -841,13 +826,13 @@ static tAVRC_STS bta_av_chk_notif_evt_id(tAVRC_MSG_VENDOR* p_vendor) { void bta_av_proc_rsp(tAVRC_RESPONSE* p_rc_rsp) { uint16_t rc_ver = 0x105; const tBTA_AV_CFG* p_src_cfg = NULL; - if (rc_ver != 0x103) + if (rc_ver != 0x103) { p_src_cfg = &bta_av_cfg; - else + } else { p_src_cfg = &bta_av_cfg_compatibility; + } p_rc_rsp->get_caps.count = p_src_cfg->num_evt_ids; - memcpy(p_rc_rsp->get_caps.param.event_id, p_src_cfg->p_meta_evt_ids, - p_src_cfg->num_evt_ids); + memcpy(p_rc_rsp->get_caps.param.event_id, p_src_cfg->p_meta_evt_ids, p_src_cfg->num_evt_ids); log::verbose("ver: 0x{:x}", rc_ver); /* if it's not 1.3, then there should be a absolute volume */ if (rc_ver != 0x103) { @@ -855,11 +840,9 @@ void bta_av_proc_rsp(tAVRC_RESPONSE* p_rc_rsp) { p_rc_rsp->get_caps.count += get_bta_avk_cfg()->num_evt_ids; if (evt_cnt < AVRC_CAP_MAX_NUM_EVT_ID) { uint32_t i = 0; - for (i = 0; i < get_bta_avk_cfg()->num_evt_ids && - i + evt_cnt < AVRC_CAP_MAX_NUM_EVT_ID; + for (i = 0; i < get_bta_avk_cfg()->num_evt_ids && i + evt_cnt < AVRC_CAP_MAX_NUM_EVT_ID; i++) { - p_rc_rsp->get_caps.param.event_id[evt_cnt + i] = - get_bta_avk_cfg()->p_meta_evt_ids[i]; + p_rc_rsp->get_caps.param.event_id[evt_cnt + i] = get_bta_avk_cfg()->p_meta_evt_ids[i]; } } } @@ -874,8 +857,8 @@ void bta_av_proc_rsp(tAVRC_RESPONSE* p_rc_rsp) { * Returns true to respond immediately * ******************************************************************************/ -tBTA_AV_EVT bta_av_proc_meta_cmd(tAVRC_RESPONSE* p_rc_rsp, - tBTA_AV_RC_MSG* p_msg, uint8_t* p_ctype) { +tBTA_AV_EVT bta_av_proc_meta_cmd(tAVRC_RESPONSE* p_rc_rsp, tBTA_AV_RC_MSG* p_msg, + uint8_t* p_ctype) { tBTA_AV_EVT evt = BTA_AV_META_MSG_EVT; uint8_t u8, pdu, *p; uint16_t u16; @@ -933,8 +916,7 @@ tBTA_AV_EVT bta_av_proc_meta_cmd(tAVRC_RESPONSE* p_rc_rsp, if (u8 == AVRC_CAP_COMPANY_ID) { *p_ctype = AVRC_RSP_IMPL_STBL; p_rc_rsp->get_caps.count = p_bta_av_cfg->num_co_ids; - memcpy(p_rc_rsp->get_caps.param.company_id, - p_bta_av_cfg->p_meta_co_ids, + memcpy(p_rc_rsp->get_caps.param.company_id, p_bta_av_cfg->p_meta_co_ids, (p_bta_av_cfg->num_co_ids << 2)); } else if (u8 == AVRC_CAP_EVENTS_SUPPORTED) { *p_ctype = AVRC_RSP_IMPL_STBL; @@ -943,8 +925,8 @@ tBTA_AV_EVT bta_av_proc_meta_cmd(tAVRC_RESPONSE* p_rc_rsp, break; } p_rc_rsp->get_caps.count = p_bta_av_cfg->num_evt_ids; - memcpy(p_rc_rsp->get_caps.param.event_id, - p_bta_av_cfg->p_meta_evt_ids, p_bta_av_cfg->num_evt_ids); + memcpy(p_rc_rsp->get_caps.param.event_id, p_bta_av_cfg->p_meta_evt_ids, + p_bta_av_cfg->num_evt_ids); } else { log::verbose("Invalid capability ID: 0x{:x}", u8); /* reject - unknown capability ID */ @@ -956,7 +938,9 @@ tBTA_AV_EVT bta_av_proc_meta_cmd(tAVRC_RESPONSE* p_rc_rsp, case AVRC_PDU_REGISTER_NOTIFICATION: /* make sure the event_id is implemented */ p_rc_rsp->rsp.status = bta_av_chk_notif_evt_id(p_vendor); - if (p_rc_rsp->rsp.status != BTA_AV_STS_NO_RSP) evt = 0; + if (p_rc_rsp->rsp.status != BTA_AV_STS_NO_RSP) { + evt = 0; + } break; } } @@ -990,8 +974,7 @@ void bta_av_rc_msg(tBTA_AV_CB* p_cb, tBTA_AV_DATA* p_data) { return; } - log::verbose("opcode={:x}, ctype={:x}", p_data->rc_msg.opcode, - p_data->rc_msg.msg.hdr.ctype); + log::verbose("opcode={:x}, ctype={:x}", p_data->rc_msg.opcode, p_data->rc_msg.msg.hdr.ctype); if (p_data->rc_msg.opcode == AVRC_OP_PASS_THRU) { /* if this is a pass thru command */ @@ -1000,29 +983,29 @@ void bta_av_rc_msg(tBTA_AV_CB* p_cb, tBTA_AV_DATA* p_data) { (p_data->rc_msg.msg.hdr.ctype == AVRC_CMD_GEN_INQ)) { /* check if operation is supported */ char avrcp_ct_support[PROPERTY_VALUE_MAX]; - osi_property_get("bluetooth.pts.avrcp_ct.support", avrcp_ct_support, - "false"); + osi_property_get("bluetooth.pts.avrcp_ct.support", avrcp_ct_support, "false"); if (p_data->rc_msg.msg.pass.op_id == AVRC_ID_VENDOR) { p_data->rc_msg.msg.hdr.ctype = AVRC_RSP_NOT_IMPL; - if (p_cb->features & BTA_AV_FEAT_METADATA) - p_data->rc_msg.msg.hdr.ctype = bta_av_group_navi_supported( - p_data->rc_msg.msg.pass.pass_len, - p_data->rc_msg.msg.pass.p_pass_data, is_inquiry); + if (p_cb->features & BTA_AV_FEAT_METADATA) { + p_data->rc_msg.msg.hdr.ctype = + bta_av_group_navi_supported(p_data->rc_msg.msg.pass.pass_len, + p_data->rc_msg.msg.pass.p_pass_data, is_inquiry); + } } else if (((p_data->rc_msg.msg.pass.op_id == AVRC_ID_VOL_UP) || (p_data->rc_msg.msg.pass.op_id == AVRC_ID_VOL_DOWN)) && !strcmp(avrcp_ct_support, "true")) { p_data->rc_msg.msg.hdr.ctype = AVRC_RSP_ACCEPT; } else { p_data->rc_msg.msg.hdr.ctype = - bta_av_op_supported(p_data->rc_msg.msg.pass.op_id, is_inquiry); + bta_av_op_supported(p_data->rc_msg.msg.pass.op_id, is_inquiry); } log::verbose("ctype {}", p_data->rc_msg.msg.hdr.ctype); /* send response */ - if (p_data->rc_msg.msg.hdr.ctype != AVRC_RSP_INTERIM) - AVRC_PassRsp(p_data->rc_msg.handle, p_data->rc_msg.label, - &p_data->rc_msg.msg.pass); + if (p_data->rc_msg.msg.hdr.ctype != AVRC_RSP_INTERIM) { + AVRC_PassRsp(p_data->rc_msg.handle, p_data->rc_msg.label, &p_data->rc_msg.msg.pass); + } /* set up for callback if supported */ if (p_data->rc_msg.msg.hdr.ctype == AVRC_RSP_ACCEPT || @@ -1051,10 +1034,8 @@ void bta_av_rc_msg(tBTA_AV_CB* p_cb, tBTA_AV_DATA* p_data) { /* If this response is for vendor unique command */ if ((p_data->rc_msg.msg.pass.op_id == AVRC_ID_VENDOR) && (p_data->rc_msg.msg.pass.pass_len > 0)) { - av.remote_rsp.p_data = - (uint8_t*)osi_malloc(p_data->rc_msg.msg.pass.pass_len); - log::verbose("Vendor Unique data len = {}", - p_data->rc_msg.msg.pass.pass_len); + av.remote_rsp.p_data = (uint8_t*)osi_malloc(p_data->rc_msg.msg.pass.pass_len); + log::verbose("Vendor Unique data len = {}", p_data->rc_msg.msg.pass.pass_len); memcpy(av.remote_rsp.p_data, p_data->rc_msg.msg.pass.p_pass_data, p_data->rc_msg.msg.pass.pass_len); } @@ -1062,8 +1043,7 @@ void bta_av_rc_msg(tBTA_AV_CB* p_cb, tBTA_AV_DATA* p_data) { /* must be a bad ctype -> reject*/ else { p_data->rc_msg.msg.hdr.ctype = AVRC_RSP_REJ; - AVRC_PassRsp(p_data->rc_msg.handle, p_data->rc_msg.label, - &p_data->rc_msg.msg.pass); + AVRC_PassRsp(p_data->rc_msg.handle, p_data->rc_msg.label, &p_data->rc_msg.msg.pass); } } /* else if this is a vendor specific command or response */ @@ -1076,10 +1056,8 @@ void bta_av_rc_msg(tBTA_AV_CB* p_cb, tBTA_AV_DATA* p_data) { av.vendor_cmd.len = p_vendor->vendor_len; /* if configured to support vendor specific and it's a command */ - if ((p_cb->features & BTA_AV_FEAT_VENDOR) && - p_data->rc_msg.msg.hdr.ctype <= AVRC_CMD_GEN_INQ) { - if ((p_cb->features & BTA_AV_FEAT_METADATA) && - (p_vendor->company_id == AVRC_CO_METADATA)) { + if ((p_cb->features & BTA_AV_FEAT_VENDOR) && p_data->rc_msg.msg.hdr.ctype <= AVRC_CMD_GEN_INQ) { + if ((p_cb->features & BTA_AV_FEAT_METADATA) && (p_vendor->company_id == AVRC_CO_METADATA)) { av.meta_msg.p_msg = &p_data->rc_msg.msg; rc_rsp.rsp.status = BTA_AV_STS_NO_RSP; evt = bta_av_proc_meta_cmd(&rc_rsp, &p_data->rc_msg, &ctype); @@ -1089,8 +1067,7 @@ void bta_av_rc_msg(tBTA_AV_CB* p_cb, tBTA_AV_DATA* p_data) { } else if ((p_cb->features & BTA_AV_FEAT_VENDOR) && p_data->rc_msg.msg.hdr.ctype >= AVRC_RSP_NOT_IMPL) { /* else if configured to support vendor specific and it's a response */ - if ((p_cb->features & BTA_AV_FEAT_METADATA) && - (p_vendor->company_id == AVRC_CO_METADATA)) { + if ((p_cb->features & BTA_AV_FEAT_METADATA) && (p_vendor->company_id == AVRC_CO_METADATA)) { av.meta_msg.p_msg = &p_data->rc_msg.msg; evt = BTA_AV_META_MSG_EVT; } else { @@ -1106,8 +1083,7 @@ void bta_av_rc_msg(tBTA_AV_CB* p_cb, tBTA_AV_DATA* p_data) { } else { p_data->rc_msg.msg.hdr.ctype = AVRC_RSP_NOT_IMPL; } - AVRC_VendorRsp(p_data->rc_msg.handle, p_data->rc_msg.label, - &p_data->rc_msg.msg.vendor); + AVRC_VendorRsp(p_data->rc_msg.handle, p_data->rc_msg.label, &p_data->rc_msg.msg.vendor); } } else if (p_data->rc_msg.opcode == AVRC_OP_BROWSE) { /* set up for callback */ @@ -1126,9 +1102,9 @@ void bta_av_rc_msg(tBTA_AV_CB* p_cb, tBTA_AV_DATA* p_data) { rc_rsp.rsp.opcode = p_data->rc_msg.opcode; AVRC_BldResponse(0, &rc_rsp, &p_pkt); } - if (p_pkt) - AVRC_MsgReq(p_data->rc_msg.handle, p_data->rc_msg.label, ctype, p_pkt, - false); + if (p_pkt) { + AVRC_MsgReq(p_data->rc_msg.handle, p_data->rc_msg.label, ctype, p_pkt, false); + } } /* call callback */ @@ -1136,8 +1112,7 @@ void bta_av_rc_msg(tBTA_AV_CB* p_cb, tBTA_AV_DATA* p_data) { av.remote_cmd.rc_handle = p_data->rc_msg.handle; (*p_cb->p_cback)(evt, &av); /* If browsing message, then free the browse message buffer */ - if (p_data->rc_msg.opcode == AVRC_OP_BROWSE && - p_data->rc_msg.msg.browse.p_browse_pkt != NULL) { + if (p_data->rc_msg.opcode == AVRC_OP_BROWSE && p_data->rc_msg.msg.browse.p_browse_pkt != NULL) { bta_av_rc_free_browse_msg(p_cb, p_data); } } @@ -1209,20 +1184,17 @@ static uint8_t bta_av_get_shdl(tBTA_AV_SCB* p_scb) { void bta_av_stream_chg(tBTA_AV_SCB* p_scb, bool started) { uint8_t started_msk = BTA_AV_HNDL_TO_MSK(p_scb->hdi); - log::verbose("peer {} started:{} started_msk:0x{:x}", p_scb->PeerAddress(), - started, started_msk); + log::verbose("peer {} started:{} started_msk:0x{:x}", p_scb->PeerAddress(), started, started_msk); if (started) { /* Let L2CAP know this channel is processed with high priority */ if (!L2CA_SetAclPriority(p_scb->PeerAddress(), L2CAP_PRIORITY_HIGH)) { - log::warn("Unable to set L2CAP acl high priority peer:{}", - p_scb->PeerAddress()); + log::warn("Unable to set L2CAP acl high priority peer:{}", p_scb->PeerAddress()); } } else { /* Let L2CAP know this channel is processed with low priority */ if (!L2CA_SetAclPriority(p_scb->PeerAddress(), L2CAP_PRIORITY_NORMAL)) { - log::warn("Unable to set L2CAP acl normal priority peer:{}", - p_scb->PeerAddress()); + log::warn("Unable to set L2CAP acl normal priority peer:{}", p_scb->PeerAddress()); } } } @@ -1266,9 +1238,9 @@ void bta_av_conn_chg(tBTA_AV_DATA* p_data) { for (i = 0; i < BTA_AV_NUM_RCB; i++) { if (bta_av_cb.rcb[i].lidx == p_lcb->lidx) { bta_av_cb.rcb[i].shdl = index + 1; - log::verbose("conn_chg up[{}]: {}, status=0x{:x}, shdl:{}, lidx:{}", - i, bta_av_cb.rcb[i].handle, bta_av_cb.rcb[i].status, - bta_av_cb.rcb[i].shdl, bta_av_cb.rcb[i].lidx); + log::verbose("conn_chg up[{}]: {}, status=0x{:x}, shdl:{}, lidx:{}", i, + bta_av_cb.rcb[i].handle, bta_av_cb.rcb[i].status, bta_av_cb.rcb[i].shdl, + bta_av_cb.rcb[i].lidx); break; } } @@ -1281,42 +1253,36 @@ void bta_av_conn_chg(tBTA_AV_DATA* p_data) { bta_av_cb.audio_open_cnt++; } - log::verbose("rc_acp_handle:{} rc_acp_idx:{}", p_cb->rc_acp_handle, - p_cb->rc_acp_idx); + log::verbose("rc_acp_handle:{} rc_acp_idx:{}", p_cb->rc_acp_handle, p_cb->rc_acp_idx); /* check if the AVRCP ACP channel is already connected */ - if (p_lcb && p_cb->rc_acp_handle != BTA_AV_RC_HANDLE_NONE && - p_cb->rc_acp_idx) { + if (p_lcb && p_cb->rc_acp_handle != BTA_AV_RC_HANDLE_NONE && p_cb->rc_acp_idx) { p_lcb_rc = &p_cb->lcb[BTA_AV_NUM_LINKS]; - log::verbose( - "rc_acp is connected && conn_chg on same addr " - "p_lcb_rc->conn_msk:x{:x}", - p_lcb_rc->conn_msk); + log::verbose("rc_acp is connected && conn_chg on same addr p_lcb_rc->conn_msk:x{:x}", + p_lcb_rc->conn_msk); /* check if the RC is connected to the scb addr */ log::info("p_lcb_rc->addr: {} conn_chg.peer_addr: {}", p_lcb_rc->addr, p_data->conn_chg.peer_addr); - if (p_lcb_rc->conn_msk && - p_lcb_rc->addr == p_data->conn_chg.peer_addr) { + if (p_lcb_rc->conn_msk && p_lcb_rc->addr == p_data->conn_chg.peer_addr) { /* AVRCP is already connected. - * need to update the association betwen SCB and RCB */ + * need to update the association between SCB and RCB */ p_lcb_rc->conn_msk = 0; /* indicate RC ONLY is not connected */ p_lcb_rc->lidx = 0; p_scb->rc_handle = p_cb->rc_acp_handle; p_rcb = &p_cb->rcb[p_cb->rc_acp_idx - 1]; p_rcb->shdl = bta_av_get_shdl(p_scb); - log::verbose("update rc_acp shdl:{}/{} srch:{}", index + 1, - p_rcb->shdl, p_scb->rc_handle); + log::verbose("update rc_acp shdl:{}/{} srch:{}", index + 1, p_rcb->shdl, + p_scb->rc_handle); p_rcb2 = bta_av_get_rcb_by_shdl(p_rcb->shdl); if (p_rcb2) { /* found the RCB that was created to associated with this SCB */ p_cb->rc_acp_handle = p_rcb2->handle; p_cb->rc_acp_idx = (p_rcb2 - p_cb->rcb) + 1; - log::verbose("new rc_acp_handle:{}, idx:{}", p_cb->rc_acp_handle, - p_cb->rc_acp_idx); + log::verbose("new rc_acp_handle:{}, idx:{}", p_cb->rc_acp_handle, p_cb->rc_acp_idx); p_rcb2->lidx = (BTA_AV_NUM_LINKS + 1); - log::verbose("rc2 handle:{} lidx:{}/{}", p_rcb2->handle, - p_rcb2->lidx, p_cb->lcb[p_rcb2->lidx - 1].lidx); + log::verbose("rc2 handle:{} lidx:{}/{}", p_rcb2->handle, p_rcb2->lidx, + p_cb->lcb[p_rcb2->lidx - 1].lidx); } p_rcb->lidx = p_lcb->lidx; log::verbose("rc handle:{} lidx:{}/{}", p_rcb->handle, p_rcb->lidx, @@ -1352,8 +1318,8 @@ void bta_av_conn_chg(tBTA_AV_DATA* p_data) { log::verbose("shdl:{}", index + 1); for (i = 0; i < BTA_AV_NUM_RCB; i++) { log::verbose("conn_chg dn[{}]: {}, status=0x{:x}, shdl:{}, lidx:{}", i, - bta_av_cb.rcb[i].handle, bta_av_cb.rcb[i].status, - bta_av_cb.rcb[i].shdl, bta_av_cb.rcb[i].lidx); + bta_av_cb.rcb[i].handle, bta_av_cb.rcb[i].status, bta_av_cb.rcb[i].shdl, + bta_av_cb.rcb[i].lidx); if (bta_av_cb.rcb[i].shdl == index + 1) { bta_av_del_rc(&bta_av_cb.rcb[i]); /* since the connection is already down and info was removed, clean @@ -1370,15 +1336,14 @@ void bta_av_conn_chg(tBTA_AV_DATA* p_data) { } /* if the AVRCP is no longer listening, create the listening channel */ - if (bta_av_cb.rc_acp_handle == BTA_AV_RC_HANDLE_NONE && - bta_av_cb.features & BTA_AV_FEAT_RCTG) + if (bta_av_cb.rc_acp_handle == BTA_AV_RC_HANDLE_NONE && bta_av_cb.features & BTA_AV_FEAT_RCTG) { bta_av_rc_create(&bta_av_cb, AVCT_ACP, 0, BTA_AV_NUM_LINKS + 1); + } } - log::verbose( - "audio:{:x} up:{} conn_msk:0x{:x} chk_restore:{} audio_open_cnt:{}", - p_cb->conn_audio, p_data->conn_chg.is_up, conn_msk, chk_restore, - p_cb->audio_open_cnt); + log::verbose("audio:{:x} up:{} conn_msk:0x{:x} chk_restore:{} audio_open_cnt:{}", + p_cb->conn_audio, p_data->conn_chg.is_up, conn_msk, chk_restore, + p_cb->audio_open_cnt); if (chk_restore) { if (p_cb->audio_open_cnt == 1) { @@ -1454,8 +1419,7 @@ void bta_av_disable(tBTA_AV_CB* p_cb, tBTA_AV_DATA* /* p_data */) { * ******************************************************************************/ void bta_av_api_disconnect(tBTA_AV_DATA* p_data) { - tBTA_AV_SCB* p_scb = - bta_av_hndl_to_scb(p_data->api_discnt.hdr.layer_specific); + tBTA_AV_SCB* p_scb = bta_av_hndl_to_scb(p_data->api_discnt.hdr.layer_specific); AVDT_DisconnectReq(p_scb->PeerAddress(), bta_av_conn_cback); alarm_cancel(p_scb->link_signalling_timer); } @@ -1471,8 +1435,8 @@ void bta_av_api_disconnect(tBTA_AV_DATA* p_data) { ******************************************************************************/ void bta_av_set_use_latency_mode(tBTA_AV_SCB* p_scb, bool use_latency_mode) { if (!L2CA_UseLatencyMode(p_scb->PeerAddress(), use_latency_mode)) { - log::warn("Unable to set L2CAP latenty mode peer:{} use_latency_mode:{}", - p_scb->PeerAddress(), use_latency_mode); + log::warn("Unable to set L2CAP latenty mode peer:{} use_latency_mode:{}", p_scb->PeerAddress(), + use_latency_mode); } } @@ -1486,15 +1450,13 @@ void bta_av_set_use_latency_mode(tBTA_AV_SCB* p_scb, bool use_latency_mode) { * ******************************************************************************/ void bta_av_api_set_latency(tBTA_AV_DATA* p_data) { - tBTA_AV_SCB* p_scb = - bta_av_hndl_to_scb(p_data->api_set_latency.hdr.layer_specific); + tBTA_AV_SCB* p_scb = bta_av_hndl_to_scb(p_data->api_set_latency.hdr.layer_specific); - tL2CAP_LATENCY latency = p_data->api_set_latency.is_low_latency - ? L2CAP_LATENCY_LOW - : L2CAP_LATENCY_NORMAL; + tL2CAP_LATENCY latency = + p_data->api_set_latency.is_low_latency ? L2CAP_LATENCY_LOW : L2CAP_LATENCY_NORMAL; if (!L2CA_SetAclLatency(p_scb->PeerAddress(), latency)) { - log::warn("Unable to set L2CAP latenty mode peer:{} use_latency_mode:{}", - p_scb->PeerAddress(), latency); + log::warn("Unable to set L2CAP latenty mode peer:{} use_latency_mode:{}", p_scb->PeerAddress(), + latency); } } @@ -1510,10 +1472,8 @@ void bta_av_api_set_latency(tBTA_AV_DATA* p_data) { * @return the index for the free LCB entry to use or BTA_AV_NUM_LINKS * if no entry is found */ -static uint8_t bta_av_find_lcb_index_by_scb_and_address( - const RawAddress& peer_address) { - log::verbose("peer_address: {} conn_lcb: 0x{:x}", peer_address, - bta_av_cb.conn_lcb); +static uint8_t bta_av_find_lcb_index_by_scb_and_address(const RawAddress& peer_address) { + log::verbose("peer_address: {} conn_lcb: 0x{:x}", peer_address, bta_av_cb.conn_lcb); // Find the index if there is already SCB entry for the peer address for (uint8_t index = 0; index < BTA_AV_NUM_LINKS; index++) { @@ -1582,13 +1542,11 @@ void bta_av_sig_chg(tBTA_AV_DATA* p_data) { if (xx >= BTA_AV_NUM_LINKS) { /* We do not have scb for this avdt connection. */ /* Silently close the connection. */ - log::error("av scb not available for avdt connection for {}", - p_data->str_msg.bd_addr); + log::error("av scb not available for avdt connection for {}", p_data->str_msg.bd_addr); AVDT_DisconnectReq(p_data->str_msg.bd_addr, NULL); return; } - log::info("AVDT_CONNECT_IND_EVT: peer {} selected lcb_index {}", - p_data->str_msg.bd_addr, xx); + log::info("AVDT_CONNECT_IND_EVT: peer {} selected lcb_index {}", p_data->str_msg.bd_addr, xx); tBTA_AV_SCB* p_scb = p_cb->p_scb[xx]; mask = 1 << xx; @@ -1631,17 +1589,14 @@ void bta_av_sig_chg(tBTA_AV_DATA* p_data) { if (!p_scb->accept_signalling_timer) { p_scb->accept_signalling_timer = alarm_new("accept_signalling_timer"); } - alarm_set_on_mloop( - p_scb->accept_signalling_timer, BTA_AV_ACCEPT_SIGNALLING_TIMEOUT_MS, - bta_av_accept_signalling_timer_cback, UINT_TO_PTR(xx)); + alarm_set_on_mloop(p_scb->accept_signalling_timer, BTA_AV_ACCEPT_SIGNALLING_TIMEOUT_MS, + bta_av_accept_signalling_timer_cback, UINT_TO_PTR(xx)); } } - } - else if (event == BTA_AR_AVDT_CONN_EVT) { + } else if (event == BTA_AR_AVDT_CONN_EVT) { uint8_t scb_index = p_data->str_msg.scb_index; alarm_cancel(p_cb->p_scb[scb_index]->link_signalling_timer); - } - else { + } else { /* disconnected. */ log::verbose("bta_av_cb.conn_lcb=0x{:x}", bta_av_cb.conn_lcb); @@ -1650,24 +1605,20 @@ void bta_av_sig_chg(tBTA_AV_DATA* p_data) { log::verbose("conn_msk: 0x{:x}", p_lcb->conn_msk); /* clean up ssm */ for (xx = 0; xx < BTA_AV_NUM_STRS; xx++) { - if (p_cb->p_scb[xx] && - p_cb->p_scb[xx]->PeerAddress() == p_data->str_msg.bd_addr) { + if (p_cb->p_scb[xx] && p_cb->p_scb[xx]->PeerAddress() == p_data->str_msg.bd_addr) { if ((p_cb->p_scb[xx]->state == 1) && alarm_is_scheduled(p_cb->p_scb[xx]->accept_signalling_timer) && interop_match_addr(INTEROP_IGNORE_DISC_BEFORE_SIGNALLING_TIMEOUT, - &(p_data->str_msg.bd_addr))) { + &(p_data->str_msg.bd_addr))) { continue; } log::verbose("Closing timer for AVDTP service"); - bta_sys_conn_close(BTA_ID_AV, p_cb->p_scb[xx]->app_id, - p_cb->p_scb[xx]->PeerAddress()); + bta_sys_conn_close(BTA_ID_AV, p_cb->p_scb[xx]->app_id, p_cb->p_scb[xx]->PeerAddress()); } mask = 1 << (xx + 1); - if (((mask & p_lcb->conn_msk) || bta_av_cb.conn_lcb) && - p_cb->p_scb[xx] && + if (((mask & p_lcb->conn_msk) || bta_av_cb.conn_lcb) && p_cb->p_scb[xx] && p_cb->p_scb[xx]->PeerAddress() == p_data->str_msg.bd_addr) { - log::warn("Sending AVDT_DISCONNECT_EVT peer_addr={}", - p_cb->p_scb[xx]->PeerAddress()); + log::warn("Sending AVDT_DISCONNECT_EVT peer_addr={}", p_cb->p_scb[xx]->PeerAddress()); bta_av_ssm_execute(p_cb->p_scb[xx], BTA_AV_AVDT_DISCONNECT_EVT, NULL); } } @@ -1701,14 +1652,13 @@ void bta_av_signalling_timer(tBTA_AV_DATA* p_data) { for (xx = 0; xx < BTA_AV_NUM_LINKS; xx++) { p_lcb = &p_cb->lcb[xx]; mask = 1 << xx; - log::verbose("index={} conn_lcb=0x{:x} peer={} conn_mask=0x{:x} lidx={}", - xx, p_cb->conn_lcb, p_lcb->addr, p_lcb->conn_msk, p_lcb->lidx); + log::verbose("index={} conn_lcb=0x{:x} peer={} conn_mask=0x{:x} lidx={}", xx, p_cb->conn_lcb, + p_lcb->addr, p_lcb->conn_msk, p_lcb->lidx); if (mask & p_cb->conn_lcb) { /* this entry is used. check if it is connected */ if (!p_lcb->conn_msk) { log::verbose("hndl 0x{:x}", p_scb->hndl); - bta_sys_start_timer(p_scb->link_signalling_timer, - BTA_AV_SIGNALLING_TIMEOUT_MS, + bta_sys_start_timer(p_scb->link_signalling_timer, BTA_AV_SIGNALLING_TIMEOUT_MS, BTA_AV_SIGNALLING_TIMER_EVT, hndl); tBTA_AV bta_av_data = { .pend = @@ -1748,16 +1698,13 @@ static void bta_av_accept_signalling_timer_cback(void* data) { p_scb->coll_mask &= ~BTA_AV_COLL_INC_TMR; if (bta_av_is_scb_opening(p_scb)) { - log::verbose("stream state opening: SDP started = {}", - p_scb->sdp_discovery_started); + log::verbose("stream state opening: SDP started = {}", p_scb->sdp_discovery_started); if (p_scb->sdp_discovery_started) { /* We are still doing SDP. Run the timer again. */ p_scb->coll_mask |= BTA_AV_COLL_INC_TMR; - alarm_set_on_mloop(p_scb->accept_signalling_timer, - BTA_AV_ACCEPT_SIGNALLING_TIMEOUT_MS, - bta_av_accept_signalling_timer_cback, - UINT_TO_PTR(inx)); + alarm_set_on_mloop(p_scb->accept_signalling_timer, BTA_AV_ACCEPT_SIGNALLING_TIMEOUT_MS, + bta_av_accept_signalling_timer_cback, UINT_TO_PTR(inx)); } else { /* SNK did not start signalling, resume signalling process. */ bta_av_discover_req(p_scb, NULL); @@ -1771,8 +1718,7 @@ static void bta_av_accept_signalling_timer_cback(void* data) { p_scb->coll_mask &= ~BTA_AV_COLL_API_CALLED; /* BTA_AV_API_OPEN_EVT */ - tBTA_AV_API_OPEN* p_buf = - (tBTA_AV_API_OPEN*)osi_malloc(sizeof(tBTA_AV_API_OPEN)); + tBTA_AV_API_OPEN* p_buf = (tBTA_AV_API_OPEN*)osi_malloc(sizeof(tBTA_AV_API_OPEN)); memcpy(p_buf, &(p_scb->open_api), sizeof(tBTA_AV_API_OPEN)); bta_sys_sendmsg(p_buf); } @@ -1787,38 +1733,38 @@ static void bta_av_store_peer_rc_version() { uint16_t peer_rc_version = 0; /*Assuming Default peer version as 1.3*/ if ((p_rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb( - p_cb->p_disc_db, UUID_SERVCLASS_AV_REMOTE_CONTROL, NULL)) != NULL) { + p_cb->p_disc_db, UUID_SERVCLASS_AV_REMOTE_CONTROL, NULL)) != NULL) { if ((get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - p_rec, ATTR_ID_BT_PROFILE_DESC_LIST)) != NULL) { + p_rec, ATTR_ID_BT_PROFILE_DESC_LIST)) != NULL) { /* get profile version (if failure, version parameter is not updated) */ if (!get_legacy_stack_sdp_api()->record.SDP_FindProfileVersionInRec( - p_rec, UUID_SERVCLASS_AV_REMOTE_CONTROL, &peer_rc_version)) { - log::warn("Unable to find AVRC profile version in record peer:{}", - p_rec->remote_bd_addr); + p_rec, UUID_SERVCLASS_AV_REMOTE_CONTROL, &peer_rc_version)) { + log::warn("Unable to find AVRC profile version in record peer:{}", p_rec->remote_bd_addr); } } - if (peer_rc_version != 0) - DEVICE_IOT_CONFIG_ADDR_SET_HEX_IF_GREATER( - p_rec->remote_bd_addr, IOT_CONF_KEY_AVRCP_CTRL_VERSION, - peer_rc_version, IOT_CONF_BYTE_NUM_2); + if (peer_rc_version != 0) { + DEVICE_IOT_CONFIG_ADDR_SET_HEX_IF_GREATER(p_rec->remote_bd_addr, + IOT_CONF_KEY_AVRCP_CTRL_VERSION, peer_rc_version, + IOT_CONF_BYTE_NUM_2); + } } peer_rc_version = 0; if ((p_rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb( - p_cb->p_disc_db, UUID_SERVCLASS_AV_REM_CTRL_TARGET, NULL)) != NULL) { + p_cb->p_disc_db, UUID_SERVCLASS_AV_REM_CTRL_TARGET, NULL)) != NULL) { if ((get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - p_rec, ATTR_ID_BT_PROFILE_DESC_LIST)) != NULL) { + p_rec, ATTR_ID_BT_PROFILE_DESC_LIST)) != NULL) { /* get profile version (if failure, version parameter is not updated) */ if (!get_legacy_stack_sdp_api()->record.SDP_FindProfileVersionInRec( - p_rec, UUID_SERVCLASS_AV_REMOTE_CONTROL, &peer_rc_version)) { - log::warn("Unable to find SDP profile version in record peer:{}", - p_rec->remote_bd_addr); + p_rec, UUID_SERVCLASS_AV_REMOTE_CONTROL, &peer_rc_version)) { + log::warn("Unable to find SDP profile version in record peer:{}", p_rec->remote_bd_addr); } } - if (peer_rc_version != 0) - DEVICE_IOT_CONFIG_ADDR_SET_HEX_IF_GREATER( - p_rec->remote_bd_addr, IOT_CONF_KEY_AVRCP_TG_VERSION, peer_rc_version, - IOT_CONF_BYTE_NUM_2); + if (peer_rc_version != 0) { + DEVICE_IOT_CONFIG_ADDR_SET_HEX_IF_GREATER(p_rec->remote_bd_addr, + IOT_CONF_KEY_AVRCP_TG_VERSION, peer_rc_version, + IOT_CONF_BYTE_NUM_2); + } } } @@ -1844,50 +1790,51 @@ tBTA_AV_FEAT bta_av_check_peer_features(uint16_t service_uuid) { /* loop through all records we found */ while (true) { /* get next record; if none found, we're done */ - p_rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb( - p_cb->p_disc_db, service_uuid, p_rec); + p_rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb(p_cb->p_disc_db, service_uuid, + p_rec); if (p_rec == NULL) { break; } if ((get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - p_rec, ATTR_ID_SERVICE_CLASS_ID_LIST)) != NULL) { + p_rec, ATTR_ID_SERVICE_CLASS_ID_LIST)) != NULL) { /* find peer features */ if (get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb( - p_cb->p_disc_db, UUID_SERVCLASS_AV_REMOTE_CONTROL, NULL)) { + p_cb->p_disc_db, UUID_SERVCLASS_AV_REMOTE_CONTROL, NULL)) { peer_features |= BTA_AV_FEAT_RCCT; } if (get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb( - p_cb->p_disc_db, UUID_SERVCLASS_AV_REM_CTRL_TARGET, NULL)) { + p_cb->p_disc_db, UUID_SERVCLASS_AV_REM_CTRL_TARGET, NULL)) { peer_features |= BTA_AV_FEAT_RCTG; } } if ((get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - p_rec, ATTR_ID_BT_PROFILE_DESC_LIST)) != NULL) { + p_rec, ATTR_ID_BT_PROFILE_DESC_LIST)) != NULL) { /* get profile version (if failure, version parameter is not updated) */ if (!get_legacy_stack_sdp_api()->record.SDP_FindProfileVersionInRec( - p_rec, UUID_SERVCLASS_AV_REMOTE_CONTROL, &peer_rc_version)) { - log::warn("Unable to find AVRC profile version in record peer:{}", - p_rec->remote_bd_addr); + p_rec, UUID_SERVCLASS_AV_REMOTE_CONTROL, &peer_rc_version)) { + log::warn("Unable to find AVRC profile version in record peer:{}", p_rec->remote_bd_addr); } log::verbose("peer_rc_version 0x{:x}", peer_rc_version); - if (peer_rc_version >= AVRC_REV_1_3) + if (peer_rc_version >= AVRC_REV_1_3) { peer_features |= (BTA_AV_FEAT_VENDOR | BTA_AV_FEAT_METADATA); + } if (peer_rc_version >= AVRC_REV_1_4) { /* get supported categories */ p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - p_rec, ATTR_ID_SUPPORTED_FEATURES); - if (p_attr != NULL && - SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == UINT_DESC_TYPE && + p_rec, ATTR_ID_SUPPORTED_FEATURES); + if (p_attr != NULL && SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == UINT_DESC_TYPE && SDP_DISC_ATTR_LEN(p_attr->attr_len_type) >= 2) { categories = p_attr->attr_value.v.u16; - if (categories & AVRC_SUPF_CT_CAT2) + if (categories & AVRC_SUPF_CT_CAT2) { peer_features |= (BTA_AV_FEAT_ADV_CTRL); - if (categories & AVRC_SUPF_CT_BROWSE) + } + if (categories & AVRC_SUPF_CT_BROWSE) { peer_features |= (BTA_AV_FEAT_BROWSE); + } } } } @@ -1913,42 +1860,40 @@ tBTA_AV_FEAT bta_avk_check_peer_features(uint16_t service_uuid) { log::verbose("service_uuid:x{:x}", service_uuid); /* loop through all records we found */ - tSDP_DISC_REC* p_rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb( - p_cb->p_disc_db, service_uuid, NULL); + tSDP_DISC_REC* p_rec = + get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb(p_cb->p_disc_db, service_uuid, NULL); while (p_rec) { log::verbose("found Service record for x{:x}", service_uuid); if ((get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - p_rec, ATTR_ID_SERVICE_CLASS_ID_LIST)) != NULL) { + p_rec, ATTR_ID_SERVICE_CLASS_ID_LIST)) != NULL) { /* find peer features */ if (get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb( - p_cb->p_disc_db, UUID_SERVCLASS_AV_REMOTE_CONTROL, NULL)) { + p_cb->p_disc_db, UUID_SERVCLASS_AV_REMOTE_CONTROL, NULL)) { peer_features |= BTA_AV_FEAT_RCCT; } if (get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb( - p_cb->p_disc_db, UUID_SERVCLASS_AV_REM_CTRL_TARGET, NULL)) { + p_cb->p_disc_db, UUID_SERVCLASS_AV_REM_CTRL_TARGET, NULL)) { peer_features |= BTA_AV_FEAT_RCTG; } } if ((get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - p_rec, ATTR_ID_BT_PROFILE_DESC_LIST)) != NULL) { + p_rec, ATTR_ID_BT_PROFILE_DESC_LIST)) != NULL) { /* get profile version (if failure, version parameter is not updated) */ uint16_t peer_rc_version = 0; bool val = get_legacy_stack_sdp_api()->record.SDP_FindProfileVersionInRec( - p_rec, UUID_SERVCLASS_AV_REMOTE_CONTROL, &peer_rc_version); - log::verbose("peer_rc_version for TG 0x{:x}, profile_found {}", - peer_rc_version, val); + p_rec, UUID_SERVCLASS_AV_REMOTE_CONTROL, &peer_rc_version); + log::verbose("peer_rc_version for TG 0x{:x}, profile_found {}", peer_rc_version, val); - if (peer_rc_version >= AVRC_REV_1_3) + if (peer_rc_version >= AVRC_REV_1_3) { peer_features |= (BTA_AV_FEAT_VENDOR | BTA_AV_FEAT_METADATA); + } /* Get supported features */ - tSDP_DISC_ATTR* p_attr = - get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( + tSDP_DISC_ATTR* p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( p_rec, ATTR_ID_SUPPORTED_FEATURES); - if (p_attr != NULL && - SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == UINT_DESC_TYPE && + if (p_attr != NULL && SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == UINT_DESC_TYPE && SDP_DISC_ATTR_LEN(p_attr->attr_len_type) >= 2) { uint16_t categories = p_attr->attr_value.v.u16; /* @@ -1958,25 +1903,29 @@ tBTA_AV_FEAT bta_avk_check_peer_features(uint16_t service_uuid) { * 1.3 as minimum version */ if (peer_rc_version >= AVRC_REV_1_3) { - if (categories & AVRC_SUPF_TG_CAT2) + if (categories & AVRC_SUPF_TG_CAT2) { peer_features |= (BTA_AV_FEAT_ADV_CTRL); - if (categories & AVRC_SUPF_TG_APP_SETTINGS) + } + if (categories & AVRC_SUPF_TG_APP_SETTINGS) { peer_features |= (BTA_AV_FEAT_APP_SETTING); - if (categories & AVRC_SUPF_TG_BROWSE) + } + if (categories & AVRC_SUPF_TG_BROWSE) { peer_features |= (BTA_AV_FEAT_BROWSE); + } } /* AVRCP Cover Artwork over BIP */ if (peer_rc_version >= AVRC_REV_1_6) { if (service_uuid == UUID_SERVCLASS_AV_REM_CTRL_TARGET && - categories & AVRC_SUPF_TG_PLAYER_COVER_ART) + categories & AVRC_SUPF_TG_PLAYER_COVER_ART) { peer_features |= (BTA_AV_FEAT_COVER_ARTWORK); + } } } } /* get next record; if none found, we're done */ - p_rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb( - p_cb->p_disc_db, service_uuid, p_rec); + p_rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb(p_cb->p_disc_db, service_uuid, + p_rec); } log::verbose("peer_features:x{:x}", peer_features); return peer_features; @@ -1998,10 +1947,9 @@ uint16_t bta_avk_get_cover_art_psm() { /* Cover Art L2CAP PSM is only available on a target device */ tBTA_AV_CB* p_cb = &bta_av_cb; tSDP_DISC_REC* p_rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb( - p_cb->p_disc_db, UUID_SERVCLASS_AV_REM_CTRL_TARGET, NULL); + p_cb->p_disc_db, UUID_SERVCLASS_AV_REM_CTRL_TARGET, NULL); while (p_rec) { - tSDP_DISC_ATTR* p_attr = - (get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( + tSDP_DISC_ATTR* p_attr = (get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( p_rec, ATTR_ID_ADDITION_PROTO_DESC_LISTS)); /* * If we have the Additional Protocol Description Lists attribute then we @@ -2014,27 +1962,22 @@ uint16_t bta_avk_get_cover_art_psm() { * list parameter, if the parameter is L2CAP then find the PSM associated * with it, then make sure we see OBEX in that same protocol" */ - if (p_attr != NULL && SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) - == DATA_ELE_SEQ_DESC_TYPE) { + if (p_attr != NULL && SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == DATA_ELE_SEQ_DESC_TYPE) { // Point to first in List of protocols (i.e [(L2CAP -> AVCTP), // (L2CAP -> OBEX)]) tSDP_DISC_ATTR* p_protocol_list = p_attr->attr_value.v.p_sub_attr; while (p_protocol_list != NULL) { - if (SDP_DISC_ATTR_TYPE(p_protocol_list->attr_len_type) - == DATA_ELE_SEQ_DESC_TYPE) { + if (SDP_DISC_ATTR_TYPE(p_protocol_list->attr_len_type) == DATA_ELE_SEQ_DESC_TYPE) { // Point to fist in list of protocol elements (i.e. [L2CAP, AVCTP]) - tSDP_DISC_ATTR* p_protocol = - p_protocol_list->attr_value.v.p_sub_attr; + tSDP_DISC_ATTR* p_protocol = p_protocol_list->attr_value.v.p_sub_attr; bool protocol_has_obex = false; bool protocol_has_l2cap = false; uint16_t psm = 0x0000; while (p_protocol) { - if (SDP_DISC_ATTR_TYPE(p_protocol->attr_len_type) - == DATA_ELE_SEQ_DESC_TYPE) { + if (SDP_DISC_ATTR_TYPE(p_protocol->attr_len_type) == DATA_ELE_SEQ_DESC_TYPE) { // Point to first item protocol parameters list (i.e [UUID=L2CAP, // PSM=0x1234]) - tSDP_DISC_ATTR* p_protocol_param = - p_protocol->attr_value.v.p_sub_attr; + tSDP_DISC_ATTR* p_protocol_param = p_protocol->attr_value.v.p_sub_attr; /* * Currently there's only ever one UUID and one parameter. L2cap * has a single PSM, AVCTP has a version and OBEX has nothing. @@ -2043,16 +1986,13 @@ uint16_t bta_avk_get_cover_art_psm() { uint16_t protocol_uuid = 0; uint16_t protocol_param = 0; while (p_protocol_param) { - uint16_t param_type = - SDP_DISC_ATTR_TYPE(p_protocol_param->attr_len_type); - uint16_t param_len = - SDP_DISC_ATTR_LEN(p_protocol_param->attr_len_type); + uint16_t param_type = SDP_DISC_ATTR_TYPE(p_protocol_param->attr_len_type); + uint16_t param_len = SDP_DISC_ATTR_LEN(p_protocol_param->attr_len_type); if (param_type == UUID_DESC_TYPE) { protocol_uuid = p_protocol_param->attr_value.v.u16; } else if (param_type == UINT_DESC_TYPE) { - protocol_param = (param_len == 2) - ? p_protocol_param->attr_value.v.u16 - : p_protocol_param->attr_value.v.u8; + protocol_param = (param_len == 2) ? p_protocol_param->attr_value.v.u16 + : p_protocol_param->attr_value.v.u8; } /* else dont care */ p_protocol_param = p_protocol_param->p_next_attr; // next } @@ -2077,7 +2017,7 @@ uint16_t bta_avk_get_cover_art_psm() { } /* get next record; if none found, we're done */ p_rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb( - p_cb->p_disc_db, UUID_SERVCLASS_AV_REM_CTRL_TARGET, p_rec); + p_cb->p_disc_db, UUID_SERVCLASS_AV_REM_CTRL_TARGET, p_rec); } /* L2CAP PSM range is 0x1000-0xFFFF so 0x0000 is safe default invalid */ log::verbose("could not find a BIP psm"); @@ -2119,43 +2059,39 @@ void bta_av_rc_disc_done_all(tBTA_AV_DATA* /* p_data */) { log::verbose("rc_handle {}", rc_handle); if (p_cb->sdp_a2dp_snk_handle) { /* This is Sink + CT + TG(Abs Vol) */ - peer_tg_features = - bta_avk_check_peer_features(UUID_SERVCLASS_AV_REM_CTRL_TARGET); + peer_tg_features = bta_avk_check_peer_features(UUID_SERVCLASS_AV_REM_CTRL_TARGET); log::verbose("populating rem ctrl target features {}", peer_tg_features); - if (BTA_AV_FEAT_ADV_CTRL & - bta_avk_check_peer_features(UUID_SERVCLASS_AV_REMOTE_CONTROL)) + if (BTA_AV_FEAT_ADV_CTRL & bta_avk_check_peer_features(UUID_SERVCLASS_AV_REMOTE_CONTROL)) { peer_tg_features |= (BTA_AV_FEAT_ADV_CTRL | BTA_AV_FEAT_RCCT); + } - if (peer_tg_features & BTA_AV_FEAT_COVER_ARTWORK) + if (peer_tg_features & BTA_AV_FEAT_COVER_ARTWORK) { cover_art_psm = bta_avk_get_cover_art_psm(); + } log::verbose("populating rem ctrl target bip psm 0x{:x}", cover_art_psm); } else if (p_cb->sdp_a2dp_handle) { /* check peer version and whether support CT and TG role */ - peer_ct_features = - bta_av_check_peer_features(UUID_SERVCLASS_AV_REMOTE_CONTROL); + peer_ct_features = bta_av_check_peer_features(UUID_SERVCLASS_AV_REMOTE_CONTROL); if ((p_cb->features & BTA_AV_FEAT_ADV_CTRL) && ((peer_ct_features & BTA_AV_FEAT_ADV_CTRL) == 0)) { /* if we support advance control and peer does not, check their support on * TG role * some implementation uses 1.3 on CT ans 1.4 on TG */ - peer_ct_features |= - bta_av_check_peer_features(UUID_SERVCLASS_AV_REM_CTRL_TARGET); + peer_ct_features |= bta_av_check_peer_features(UUID_SERVCLASS_AV_REM_CTRL_TARGET); } /* Change our features if the remote AVRCP version is 1.3 or less */ tSDP_DISC_REC* p_rec = nullptr; p_rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb( - p_cb->p_disc_db, UUID_SERVCLASS_AV_REMOTE_CONTROL, p_rec); - if (p_rec != NULL && - get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - p_rec, ATTR_ID_BT_PROFILE_DESC_LIST) != NULL) { + p_cb->p_disc_db, UUID_SERVCLASS_AV_REMOTE_CONTROL, p_rec); + if (p_rec != NULL && get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( + p_rec, ATTR_ID_BT_PROFILE_DESC_LIST) != NULL) { /* get profile version (if failure, version parameter is not updated) */ uint16_t peer_rc_version = 0xFFFF; // Don't change the AVRCP version if (!get_legacy_stack_sdp_api()->record.SDP_FindProfileVersionInRec( - p_rec, UUID_SERVCLASS_AV_REMOTE_CONTROL, &peer_rc_version)) { - log::warn("Unable to find SDP in record peer:{}", - p_rec->remote_bd_addr); + p_rec, UUID_SERVCLASS_AV_REMOTE_CONTROL, &peer_rc_version)) { + log::warn("Unable to find SDP in record peer:{}", p_rec->remote_bd_addr); } if (peer_rc_version <= AVRC_REV_1_3) { log::verbose("Using AVRCP 1.3 Capabilities with remote device"); @@ -2169,24 +2105,22 @@ void bta_av_rc_disc_done_all(tBTA_AV_DATA* /* p_data */) { p_cb->rc_feature.peer_ct_features = peer_ct_features; p_cb->rc_feature.peer_tg_features = peer_tg_features; p_cb->rc_feature.rc_handle = rc_handle; - if (p_scb) p_cb->rc_feature.peer_addr = p_scb->PeerAddress(); + if (p_scb) { + p_cb->rc_feature.peer_addr = p_scb->PeerAddress(); + } - log::verbose( - "peer_tg_features 0x{:x}, peer_ct_features 0x{:x}, features 0x{:x}", - peer_tg_features, peer_ct_features, p_cb->features); + log::verbose("peer_tg_features 0x{:x}, peer_ct_features 0x{:x}, features 0x{:x}", + peer_tg_features, peer_ct_features, p_cb->features); /* if we have no rc connection */ if (rc_handle == BTA_AV_RC_HANDLE_NONE) { if (p_scb) { /* if peer remote control service matches ours and USE_RC is true */ - if ((((p_cb->features & BTA_AV_FEAT_RCCT) && - (peer_tg_features & BTA_AV_FEAT_RCTG)) || - ((p_cb->features & BTA_AV_FEAT_RCTG) && - (peer_ct_features & BTA_AV_FEAT_RCCT)))) { + if (((p_cb->features & BTA_AV_FEAT_RCCT) && (peer_tg_features & BTA_AV_FEAT_RCTG)) || + ((p_cb->features & BTA_AV_FEAT_RCTG) && (peer_ct_features & BTA_AV_FEAT_RCCT))) { p_lcb = bta_av_find_lcb(p_scb->PeerAddress(), BTA_AV_LCB_FIND); if (p_lcb) { - rc_handle = bta_av_rc_create(p_cb, AVCT_INT, - (uint8_t)(p_scb->hdi + 1), p_lcb->lidx); + rc_handle = bta_av_rc_create(p_cb, AVCT_INT, (uint8_t)(p_scb->hdi + 1), p_lcb->lidx); if (rc_handle != BTA_AV_RC_HANDLE_NONE) { p_cb->rcb[rc_handle].peer_ct_features = peer_ct_features; p_cb->rcb[rc_handle].peer_tg_features = peer_tg_features; @@ -2198,11 +2132,11 @@ void bta_av_rc_disc_done_all(tBTA_AV_DATA* /* p_data */) { log::error("no link resources available"); p_scb->use_rc = false; tBTA_AV bta_av_data = { - .rc_open = - { - .peer_addr = p_scb->PeerAddress(), - .status = BTA_AV_FAIL_RESOURCES, - }, + .rc_open = + { + .peer_addr = p_scb->PeerAddress(), + .status = BTA_AV_FAIL_RESOURCES, + }, }; (*p_cb->p_cback)(BTA_AV_RC_OPEN_EVT, &bta_av_data); } @@ -2213,13 +2147,13 @@ void bta_av_rc_disc_done_all(tBTA_AV_DATA* /* p_data */) { /* can not find AVRC on peer device. report failure */ p_scb->use_rc = false; tBTA_AV bta_av_data = { - .rc_open = - { - .peer_ct_features = peer_ct_features, - .peer_tg_features = peer_tg_features, - .peer_addr = p_scb->PeerAddress(), - .status = BTA_AV_FAIL_SDP, - }, + .rc_open = + { + .peer_ct_features = peer_ct_features, + .peer_tg_features = peer_tg_features, + .peer_addr = p_scb->PeerAddress(), + .status = BTA_AV_FAIL_SDP, + }, }; (*p_cb->p_cback)(BTA_AV_RC_OPEN_EVT, &bta_av_data); } @@ -2236,19 +2170,20 @@ void bta_av_rc_disc_done_all(tBTA_AV_DATA* /* p_data */) { * we still need to send RC feature event. So we need to get BD * from Message. Note that lidx is 1 based not 0 based */ - if (p_cb->rcb[rc_handle].lidx > 0) + if (p_cb->rcb[rc_handle].lidx > 0) { peer_addr = p_cb->lcb[p_cb->rcb[rc_handle].lidx - 1].addr; - else + } else { peer_addr = p_cb->lcb[p_cb->rcb[rc_handle].lidx].addr; + } } else { peer_addr = p_scb->PeerAddress(); } tBTA_AV bta_av_feat = {.rc_feat = { - .rc_handle = rc_handle, - .peer_ct_features = peer_ct_features, - .peer_tg_features = peer_tg_features, - .peer_addr = peer_addr, + .rc_handle = rc_handle, + .peer_ct_features = peer_ct_features, + .peer_tg_features = peer_tg_features, + .peer_addr = peer_addr, }}; (*p_cb->p_cback)(BTA_AV_RC_FEAT_EVT, &bta_av_feat); @@ -2256,12 +2191,12 @@ void bta_av_rc_disc_done_all(tBTA_AV_DATA* /* p_data */) { log::verbose("Send PSM data. rc_psm = {:#x}", cover_art_psm); p_cb->rcb[rc_handle].cover_art_psm = cover_art_psm; tBTA_AV bta_av_psm = { - .rc_cover_art_psm = - { - .rc_handle = rc_handle, - .cover_art_psm = cover_art_psm, - .peer_addr = peer_addr, - }, + .rc_cover_art_psm = + { + .rc_handle = rc_handle, + .cover_art_psm = cover_art_psm, + .peer_addr = peer_addr, + }, }; (*p_cb->p_cback)(BTA_AV_RC_PSM_EVT, &bta_av_psm); } @@ -2314,43 +2249,38 @@ void bta_av_rc_disc_done(tBTA_AV_DATA* p_data) { log::verbose("rc_handle {}", rc_handle); if (p_cb->sdp_a2dp_snk_handle) { /* This is Sink + CT + TG(Abs Vol) */ - peer_features = - bta_avk_check_peer_features(UUID_SERVCLASS_AV_REM_CTRL_TARGET); + peer_features = bta_avk_check_peer_features(UUID_SERVCLASS_AV_REM_CTRL_TARGET); log::verbose("populating rem ctrl target features {}", peer_features); - if (BTA_AV_FEAT_ADV_CTRL & - bta_avk_check_peer_features(UUID_SERVCLASS_AV_REMOTE_CONTROL)) + if (BTA_AV_FEAT_ADV_CTRL & bta_avk_check_peer_features(UUID_SERVCLASS_AV_REMOTE_CONTROL)) { peer_features |= (BTA_AV_FEAT_ADV_CTRL | BTA_AV_FEAT_RCCT); + } - if (peer_features & BTA_AV_FEAT_COVER_ARTWORK) + if (peer_features & BTA_AV_FEAT_COVER_ARTWORK) { cover_art_psm = bta_avk_get_cover_art_psm(); + } log::verbose("populating rem ctrl target bip psm 0x{:x}", cover_art_psm); } else if (p_cb->sdp_a2dp_handle) { /* check peer version and whether support CT and TG role */ - peer_features = - bta_av_check_peer_features(UUID_SERVCLASS_AV_REMOTE_CONTROL); - if ((p_cb->features & BTA_AV_FEAT_ADV_CTRL) && - ((peer_features & BTA_AV_FEAT_ADV_CTRL) == 0)) { + peer_features = bta_av_check_peer_features(UUID_SERVCLASS_AV_REMOTE_CONTROL); + if ((p_cb->features & BTA_AV_FEAT_ADV_CTRL) && ((peer_features & BTA_AV_FEAT_ADV_CTRL) == 0)) { /* if we support advance control and peer does not, check their support on * TG role * some implementation uses 1.3 on CT ans 1.4 on TG */ - peer_features |= - bta_av_check_peer_features(UUID_SERVCLASS_AV_REM_CTRL_TARGET); + peer_features |= bta_av_check_peer_features(UUID_SERVCLASS_AV_REM_CTRL_TARGET); } /* Change our features if the remote AVRCP version is 1.3 or less */ tSDP_DISC_REC* p_rec = nullptr; p_rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb( - p_cb->p_disc_db, UUID_SERVCLASS_AV_REMOTE_CONTROL, p_rec); - if (p_rec != NULL && - get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - p_rec, ATTR_ID_BT_PROFILE_DESC_LIST) != NULL) { + p_cb->p_disc_db, UUID_SERVCLASS_AV_REMOTE_CONTROL, p_rec); + if (p_rec != NULL && get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( + p_rec, ATTR_ID_BT_PROFILE_DESC_LIST) != NULL) { /* get profile version (if failure, version parameter is not updated) */ uint16_t peer_rc_version = 0xFFFF; // Don't change the AVRCP version if (!get_legacy_stack_sdp_api()->record.SDP_FindProfileVersionInRec( - p_rec, UUID_SERVCLASS_AV_REMOTE_CONTROL, &peer_rc_version)) { - log::warn("Unable to find AVRCP version peer:{}", - p_rec->remote_bd_addr); + p_rec, UUID_SERVCLASS_AV_REMOTE_CONTROL, &peer_rc_version)) { + log::warn("Unable to find AVRCP version peer:{}", p_rec->remote_bd_addr); } if (peer_rc_version <= AVRC_REV_1_3) { log::verbose("Using AVRCP 1.3 Capabilities with remote device"); @@ -2364,21 +2294,17 @@ void bta_av_rc_disc_done(tBTA_AV_DATA* p_data) { p_cb->disc = 0; osi_free_and_reset((void**)&p_cb->p_disc_db); - log::verbose("peer_features 0x{:x}, features 0x{:x}", peer_features, - p_cb->features); + log::verbose("peer_features 0x{:x}, features 0x{:x}", peer_features, p_cb->features); /* if we have no rc connection */ if (rc_handle == BTA_AV_RC_HANDLE_NONE) { if (p_scb) { /* if peer remote control service matches ours and USE_RC is true */ - if ((((p_cb->features & BTA_AV_FEAT_RCCT) && - (peer_features & BTA_AV_FEAT_RCTG)) || - ((p_cb->features & BTA_AV_FEAT_RCTG) && - (peer_features & BTA_AV_FEAT_RCCT)))) { + if (((p_cb->features & BTA_AV_FEAT_RCCT) && (peer_features & BTA_AV_FEAT_RCTG)) || + ((p_cb->features & BTA_AV_FEAT_RCTG) && (peer_features & BTA_AV_FEAT_RCCT))) { p_lcb = bta_av_find_lcb(p_scb->PeerAddress(), BTA_AV_LCB_FIND); if (p_lcb) { - rc_handle = bta_av_rc_create(p_cb, AVCT_INT, - (uint8_t)(p_scb->hdi + 1), p_lcb->lidx); + rc_handle = bta_av_rc_create(p_cb, AVCT_INT, (uint8_t)(p_scb->hdi + 1), p_lcb->lidx); if (rc_handle < BTA_AV_NUM_RCB) { p_cb->rcb[rc_handle].peer_features = peer_features; p_cb->rcb[rc_handle].cover_art_psm = cover_art_psm; @@ -2405,20 +2331,21 @@ void bta_av_rc_disc_done(tBTA_AV_DATA* p_data) { /* can not find AVRC on peer device. report failure */ p_scb->use_rc = false; tBTA_AV bta_av_data = { - .rc_open = { - .rc_handle = BTA_AV_RC_HANDLE_NONE, - .cover_art_psm = 0, - .peer_features = 0, - .peer_addr = p_scb->PeerAddress(), - .status = BTA_AV_FAIL_SDP, - }, + .rc_open = + { + .rc_handle = BTA_AV_RC_HANDLE_NONE, + .cover_art_psm = 0, + .peer_features = 0, + .peer_addr = p_scb->PeerAddress(), + .status = BTA_AV_FAIL_SDP, + }, }; (*p_cb->p_cback)(BTA_AV_RC_OPEN_EVT, &bta_av_data); } - if (peer_features != 0) - DEVICE_IOT_CONFIG_ADDR_SET_HEX(p_scb->PeerAddress(), - IOT_CONF_KEY_AVRCP_FEATURES, + if (peer_features != 0) { + DEVICE_IOT_CONFIG_ADDR_SET_HEX(p_scb->PeerAddress(), IOT_CONF_KEY_AVRCP_FEATURES, peer_features, IOT_CONF_BYTE_NUM_2); + } } } else { tBTA_AV_RC_FEAT rc_feat; @@ -2440,10 +2367,10 @@ void bta_av_rc_disc_done(tBTA_AV_DATA* p_data) { bta_av_feat.rc_feat = rc_feat; (*p_cb->p_cback)(BTA_AV_RC_FEAT_EVT, &bta_av_feat); - if (peer_features != 0) - DEVICE_IOT_CONFIG_ADDR_SET_HEX(rc_feat.peer_addr, - IOT_CONF_KEY_AVRCP_FEATURES, peer_features, + if (peer_features != 0) { + DEVICE_IOT_CONFIG_ADDR_SET_HEX(rc_feat.peer_addr, IOT_CONF_KEY_AVRCP_FEATURES, peer_features, IOT_CONF_BYTE_NUM_2); + } // Send PSM data log::verbose("Send PSM data"); @@ -2490,15 +2417,14 @@ void bta_av_rc_closed(tBTA_AV_DATA* p_data) { log::verbose("rc_handle:{}, address:{}", p_msg->handle, p_msg->peer_addr); for (i = 0; i < BTA_AV_NUM_RCB; i++) { p_rcb = &p_cb->rcb[i]; - log::verbose("rcb[{}] rc_handle:{}, status=0x{:x}, shdl:{}, lidx:{}", i, - p_rcb->handle, p_rcb->status, p_rcb->shdl, p_rcb->lidx); + log::verbose("rcb[{}] rc_handle:{}, status=0x{:x}, shdl:{}, lidx:{}", i, p_rcb->handle, + p_rcb->status, p_rcb->shdl, p_rcb->lidx); if (p_rcb->handle == p_msg->handle) { if (btif_av_src_sink_coexist_enabled() && p_rcb->shdl && (p_rcb->shdl - 1) < BTA_AV_NUM_STRS) { p_scb = bta_av_cb.p_scb[p_rcb->shdl - 1]; if (p_scb && !(p_scb->PeerAddress() == p_msg->peer_addr)) { - log::verbose("handle{} {} error p_scb or addr", i, - p_scb->PeerAddress()); + log::verbose("handle{} {} error p_scb or addr", i, p_scb->PeerAddress()); conn = true; continue; } @@ -2517,8 +2443,9 @@ void bta_av_rc_closed(tBTA_AV_DATA* p_data) { } if (p_scb) { rc_close.peer_addr = p_scb->PeerAddress(); - if (p_scb->rc_handle == p_rcb->handle) + if (p_scb->rc_handle == p_rcb->handle) { p_scb->rc_handle = BTA_AV_RC_HANDLE_NONE; + } log::verbose("shdl:{}, srch:{}", p_rcb->shdl, p_scb->rc_handle); } p_rcb->shdl = 0; @@ -2540,8 +2467,7 @@ void bta_av_rc_closed(tBTA_AV_DATA* p_data) { /* AVCT CCB is still there. dealloc */ bta_av_del_rc(p_rcb); } - } else if ((p_rcb->handle != BTA_AV_RC_HANDLE_NONE) && - (p_rcb->status & BTA_AV_RC_CONN_MASK)) { + } else if ((p_rcb->handle != BTA_AV_RC_HANDLE_NONE) && (p_rcb->status & BTA_AV_RC_CONN_MASK)) { /* at least one channel is still connected */ conn = true; } @@ -2559,9 +2485,9 @@ void bta_av_rc_closed(tBTA_AV_DATA* p_data) { tBTA_AV bta_av_data; bta_av_data.rc_close = rc_close; (*p_cb->p_cback)(BTA_AV_RC_CLOSE_EVT, &bta_av_data); - if (bta_av_cb.rc_acp_handle == BTA_AV_RC_HANDLE_NONE - && bta_av_cb.features & BTA_AV_FEAT_RCTG) - bta_av_rc_create(&bta_av_cb, AVCT_ACP, 0, BTA_AV_NUM_LINKS + 1); + if (bta_av_cb.rc_acp_handle == BTA_AV_RC_HANDLE_NONE && bta_av_cb.features & BTA_AV_FEAT_RCTG) { + bta_av_rc_create(&bta_av_cb, AVCT_ACP, 0, BTA_AV_NUM_LINKS + 1); + } } /******************************************************************************* @@ -2629,17 +2555,17 @@ void bta_av_rc_browse_closed(tBTA_AV_DATA* p_data) { void bta_av_rc_disc(uint8_t disc) { tBTA_AV_CB* p_cb = &bta_av_cb; tAVRC_SDP_DB_PARAMS db_params; - uint16_t attr_list[] = {ATTR_ID_SERVICE_CLASS_ID_LIST, - ATTR_ID_BT_PROFILE_DESC_LIST, - ATTR_ID_SUPPORTED_FEATURES, - ATTR_ID_ADDITION_PROTO_DESC_LISTS}; + uint16_t attr_list[] = {ATTR_ID_SERVICE_CLASS_ID_LIST, ATTR_ID_BT_PROFILE_DESC_LIST, + ATTR_ID_SUPPORTED_FEATURES, ATTR_ID_ADDITION_PROTO_DESC_LISTS}; uint8_t hdi; tBTA_AV_SCB* p_scb; RawAddress peer_addr = RawAddress::kEmpty; uint8_t rc_handle; log::verbose("disc: 0x{:x}, bta_av_cb.disc: 0x{:x}", disc, bta_av_cb.disc); - if ((bta_av_cb.disc != 0) || (disc == 0)) return; + if ((bta_av_cb.disc != 0) || (disc == 0)) { + return; + } if ((disc & BTA_AV_CHNL_MSK) == BTA_AV_CHNL_MSK) { /* this is the rc handle/index to tBTA_AV_RCB */ @@ -2659,8 +2585,9 @@ void bta_av_rc_disc(uint8_t disc) { if (!peer_addr.IsEmpty()) { /* allocate discovery database */ - if (p_cb->p_disc_db == NULL) + if (p_cb->p_disc_db == NULL) { p_cb->p_disc_db = (tSDP_DISCOVERY_DB*)osi_malloc(BTA_AV_DISC_BUF_SIZE); + } /* set up parameters */ db_params.db_len = BTA_AV_DISC_BUF_SIZE; @@ -2669,8 +2596,7 @@ void bta_av_rc_disc(uint8_t disc) { db_params.p_attrs = attr_list; /* searching for UUID_SERVCLASS_AV_REMOTE_CONTROL gets both TG and CT */ - if (AVRC_FindService(UUID_SERVCLASS_AV_REMOTE_CONTROL, peer_addr, - &db_params, + if (AVRC_FindService(UUID_SERVCLASS_AV_REMOTE_CONTROL, peer_addr, &db_params, base::Bind(bta_av_avrc_sdp_cback)) == AVRC_SUCCESS) { p_cb->disc = disc; log::verbose("disc 0x{:x}", p_cb->disc); @@ -2691,9 +2617,9 @@ void bta_av_dereg_comp(tBTA_AV_DATA* p_data) { tBTA_AV_CB* p_cb = &bta_av_cb; tBTA_AV_SCB* p_scb; tBTA_UTL_COD cod = { - .minor = BTM_COD_MINOR_UNCLASSIFIED, - .major = BTM_COD_MAJOR_UNCLASSIFIED, - .service = 0, + .minor = BTM_COD_MINOR_UNCLASSIFIED, + .major = BTM_COD_MAJOR_UNCLASSIFIED, + .service = 0, }; uint8_t mask; @@ -2726,8 +2652,7 @@ void bta_av_dereg_comp(tBTA_AV_DATA* p_data) { /* Only remove the SDP record if we're the ones that created it */ if (is_new_avrcp_enabled()) { log::verbose( - "newavrcp is the owner of the AVRCP Target SDP record. Don't dereg " - "the SDP record"); + "newavrcp is the owner of the AVRCP Target SDP record. Don't dereg the SDP record"); } else { log::verbose("newavrcp is not enabled. Remove SDP record"); bta_ar_dereg_avrc(UUID_SERVCLASS_AV_REMOTE_CONTROL); diff --git a/system/bta/av/bta_av_api.cc b/system/bta/av/bta_av_api.cc index d8fb9989897..2c349e43343 100644 --- a/system/bta/av/bta_av_api.cc +++ b/system/bta/av/bta_av_api.cc @@ -61,8 +61,7 @@ static const tBTA_SYS_REG bta_av_reg = {bta_av_hdl_event, BTA_AvDisable}; * ******************************************************************************/ void BTA_AvEnable(tBTA_AV_FEAT features, tBTA_AV_CBACK* p_cback) { - tBTA_AV_API_ENABLE* p_buf = - (tBTA_AV_API_ENABLE*)osi_malloc(sizeof(tBTA_AV_API_ENABLE)); + tBTA_AV_API_ENABLE* p_buf = (tBTA_AV_API_ENABLE*)osi_malloc(sizeof(tBTA_AV_API_ENABLE)); /* register with BTA system manager */ bta_sys_register(BTA_ID_AV, &bta_av_reg); @@ -105,18 +104,17 @@ void BTA_AvDisable(void) { * Returns void * ******************************************************************************/ -void BTA_AvRegister(tBTA_AV_CHNL chnl, const char* p_service_name, - uint8_t app_id, tBTA_AV_SINK_DATA_CBACK* p_sink_data_cback, - uint16_t service_uuid) { - tBTA_AV_API_REG* p_buf = - (tBTA_AV_API_REG*)osi_malloc(sizeof(tBTA_AV_API_REG)); +void BTA_AvRegister(tBTA_AV_CHNL chnl, const char* p_service_name, uint8_t app_id, + tBTA_AV_SINK_DATA_CBACK* p_sink_data_cback, uint16_t service_uuid) { + tBTA_AV_API_REG* p_buf = (tBTA_AV_API_REG*)osi_malloc(sizeof(tBTA_AV_API_REG)); p_buf->hdr.layer_specific = chnl; p_buf->hdr.event = BTA_AV_API_REGISTER_EVT; - if (p_service_name) + if (p_service_name) { strlcpy(p_buf->p_service_name, p_service_name, BTA_SERVICE_NAME_LEN); - else + } else { p_buf->p_service_name[0] = 0; + } p_buf->app_id = app_id; p_buf->p_app_sink_data_cback = p_sink_data_cback; p_buf->service_uuid = service_uuid; @@ -153,13 +151,10 @@ void BTA_AvDeregister(tBTA_AV_HNDL hndl) { * Returns void * ******************************************************************************/ -void BTA_AvOpen(const RawAddress& bd_addr, tBTA_AV_HNDL handle, bool use_rc, - uint16_t uuid) { - log::info("peer {} bta_handle:0x{:x} use_rc={} uuid=0x{:x}", bd_addr, handle, - use_rc, uuid); +void BTA_AvOpen(const RawAddress& bd_addr, tBTA_AV_HNDL handle, bool use_rc, uint16_t uuid) { + log::info("peer {} bta_handle:0x{:x} use_rc={} uuid=0x{:x}", bd_addr, handle, use_rc, uuid); - tBTA_AV_API_OPEN* p_buf = - (tBTA_AV_API_OPEN*)osi_malloc(sizeof(tBTA_AV_API_OPEN)); + tBTA_AV_API_OPEN* p_buf = (tBTA_AV_API_OPEN*)osi_malloc(sizeof(tBTA_AV_API_OPEN)); p_buf->hdr.event = BTA_AV_API_OPEN_EVT; p_buf->hdr.layer_specific = handle; @@ -214,8 +209,7 @@ void BTA_AvClose(tBTA_AV_HNDL handle) { void BTA_AvDisconnect(tBTA_AV_HNDL handle) { log::info("bta_handle=0x{:x}", handle); - tBTA_AV_API_DISCNT* p_buf = - (tBTA_AV_API_DISCNT*)osi_malloc(sizeof(tBTA_AV_API_DISCNT)); + tBTA_AV_API_DISCNT* p_buf = (tBTA_AV_API_DISCNT*)osi_malloc(sizeof(tBTA_AV_API_DISCNT)); p_buf->hdr.event = BTA_AV_API_DISCONNECT_EVT; p_buf->hdr.layer_specific = handle; @@ -233,13 +227,10 @@ void BTA_AvDisconnect(tBTA_AV_HNDL handle) { * ******************************************************************************/ void BTA_AvStart(tBTA_AV_HNDL handle, bool use_latency_mode) { - log::info( - "Starting audio/video stream data transfer bta_handle:{}, " - "use_latency_mode:{}", - handle, use_latency_mode); + log::info("Starting audio/video stream data transfer bta_handle:{}, use_latency_mode:{}", handle, + use_latency_mode); - tBTA_AV_DO_START* p_buf = - (tBTA_AV_DO_START*)osi_malloc(sizeof(tBTA_AV_DO_START)); + tBTA_AV_DO_START* p_buf = (tBTA_AV_DO_START*)osi_malloc(sizeof(tBTA_AV_DO_START)); p_buf->hdr.event = BTA_AV_API_START_EVT; p_buf->hdr.layer_specific = handle; p_buf->use_latency_mode = use_latency_mode; @@ -281,8 +272,7 @@ void BTA_AvOffloadStart(tBTA_AV_HNDL hndl) { void BTA_AvStop(tBTA_AV_HNDL handle, bool suspend) { log::info("bta_handle=0x{:x} suspend={}", handle, suspend); - tBTA_AV_API_STOP* p_buf = - (tBTA_AV_API_STOP*)osi_malloc(sizeof(tBTA_AV_API_STOP)); + tBTA_AV_API_STOP* p_buf = (tBTA_AV_API_STOP*)osi_malloc(sizeof(tBTA_AV_API_STOP)); p_buf->hdr.event = BTA_AV_API_STOP_EVT; p_buf->hdr.layer_specific = handle; @@ -306,14 +296,11 @@ void BTA_AvStop(tBTA_AV_HNDL handle, bool suspend) { * Returns void * ******************************************************************************/ -void BTA_AvReconfig(tBTA_AV_HNDL hndl, bool suspend, uint8_t sep_info_idx, - uint8_t* p_codec_info, uint8_t num_protect, - const uint8_t* p_protect_info) { - log::info("bta_handle=0x{:x} suspend={} sep_info_idx={}", hndl, suspend, - sep_info_idx); +void BTA_AvReconfig(tBTA_AV_HNDL hndl, bool suspend, uint8_t sep_info_idx, uint8_t* p_codec_info, + uint8_t num_protect, const uint8_t* p_protect_info) { + log::info("bta_handle=0x{:x} suspend={} sep_info_idx={}", hndl, suspend, sep_info_idx); - tBTA_AV_API_RCFG* p_buf = - (tBTA_AV_API_RCFG*)osi_malloc(sizeof(tBTA_AV_API_RCFG) + num_protect); + tBTA_AV_API_RCFG* p_buf = (tBTA_AV_API_RCFG*)osi_malloc(sizeof(tBTA_AV_API_RCFG) + num_protect); p_buf->hdr.layer_specific = hndl; p_buf->hdr.event = BTA_AV_API_RECONFIG_EVT; @@ -338,8 +325,8 @@ void BTA_AvReconfig(tBTA_AV_HNDL hndl, bool suspend, uint8_t sep_info_idx, * ******************************************************************************/ void BTA_AvProtectReq(tBTA_AV_HNDL hndl, uint8_t* p_data, uint16_t len) { - tBTA_AV_API_PROTECT_REQ* p_buf = (tBTA_AV_API_PROTECT_REQ*)osi_malloc( - sizeof(tBTA_AV_API_PROTECT_REQ) + len); + tBTA_AV_API_PROTECT_REQ* p_buf = + (tBTA_AV_API_PROTECT_REQ*)osi_malloc(sizeof(tBTA_AV_API_PROTECT_REQ) + len); p_buf->hdr.layer_specific = hndl; p_buf->hdr.event = BTA_AV_API_PROTECT_REQ_EVT; @@ -366,10 +353,9 @@ void BTA_AvProtectReq(tBTA_AV_HNDL hndl, uint8_t* p_data, uint16_t len) { * Returns void * ******************************************************************************/ -void BTA_AvProtectRsp(tBTA_AV_HNDL hndl, uint8_t error_code, uint8_t* p_data, - uint16_t len) { - tBTA_AV_API_PROTECT_RSP* p_buf = (tBTA_AV_API_PROTECT_RSP*)osi_malloc( - sizeof(tBTA_AV_API_PROTECT_RSP) + len); +void BTA_AvProtectRsp(tBTA_AV_HNDL hndl, uint8_t error_code, uint8_t* p_data, uint16_t len) { + tBTA_AV_API_PROTECT_RSP* p_buf = + (tBTA_AV_API_PROTECT_RSP*)osi_malloc(sizeof(tBTA_AV_API_PROTECT_RSP) + len); p_buf->hdr.layer_specific = hndl; p_buf->hdr.event = BTA_AV_API_PROTECT_RSP_EVT; @@ -395,10 +381,9 @@ void BTA_AvProtectRsp(tBTA_AV_HNDL hndl, uint8_t error_code, uint8_t* p_data, * Returns void * ******************************************************************************/ -void BTA_AvRemoteCmd(uint8_t rc_handle, uint8_t label, tBTA_AV_RC rc_id, - tBTA_AV_STATE key_state) { +void BTA_AvRemoteCmd(uint8_t rc_handle, uint8_t label, tBTA_AV_RC rc_id, tBTA_AV_STATE key_state) { tBTA_AV_API_REMOTE_CMD* p_buf = - (tBTA_AV_API_REMOTE_CMD*)osi_malloc(sizeof(tBTA_AV_API_REMOTE_CMD)); + (tBTA_AV_API_REMOTE_CMD*)osi_malloc(sizeof(tBTA_AV_API_REMOTE_CMD)); p_buf->hdr.event = BTA_AV_API_REMOTE_CMD_EVT; p_buf->hdr.layer_specific = rc_handle; @@ -422,11 +407,10 @@ void BTA_AvRemoteCmd(uint8_t rc_handle, uint8_t label, tBTA_AV_RC rc_id, * Returns void * ******************************************************************************/ -void BTA_AvRemoteVendorUniqueCmd(uint8_t rc_handle, uint8_t label, - tBTA_AV_STATE key_state, uint8_t* p_msg, - uint8_t buf_len) { - tBTA_AV_API_REMOTE_CMD* p_buf = (tBTA_AV_API_REMOTE_CMD*)osi_malloc( - sizeof(tBTA_AV_API_REMOTE_CMD) + buf_len); +void BTA_AvRemoteVendorUniqueCmd(uint8_t rc_handle, uint8_t label, tBTA_AV_STATE key_state, + uint8_t* p_msg, uint8_t buf_len) { + tBTA_AV_API_REMOTE_CMD* p_buf = + (tBTA_AV_API_REMOTE_CMD*)osi_malloc(sizeof(tBTA_AV_API_REMOTE_CMD) + buf_len); p_buf->label = label; p_buf->hdr.event = BTA_AV_API_REMOTE_CMD_EVT; @@ -454,10 +438,9 @@ void BTA_AvRemoteVendorUniqueCmd(uint8_t rc_handle, uint8_t label, * Returns void * ******************************************************************************/ -void BTA_AvVendorCmd(uint8_t rc_handle, uint8_t label, tBTA_AV_CODE cmd_code, - uint8_t* p_data, uint16_t len) { - tBTA_AV_API_VENDOR* p_buf = - (tBTA_AV_API_VENDOR*)osi_malloc(sizeof(tBTA_AV_API_VENDOR) + len); +void BTA_AvVendorCmd(uint8_t rc_handle, uint8_t label, tBTA_AV_CODE cmd_code, uint8_t* p_data, + uint16_t len) { + tBTA_AV_API_VENDOR* p_buf = (tBTA_AV_API_VENDOR*)osi_malloc(sizeof(tBTA_AV_API_VENDOR) + len); p_buf->hdr.event = BTA_AV_API_VENDOR_CMD_EVT; p_buf->hdr.layer_specific = rc_handle; @@ -489,20 +472,20 @@ void BTA_AvVendorCmd(uint8_t rc_handle, uint8_t label, tBTA_AV_CODE cmd_code, * Returns void * ******************************************************************************/ -void BTA_AvVendorRsp(uint8_t rc_handle, uint8_t label, tBTA_AV_CODE rsp_code, - uint8_t* p_data, uint16_t len, uint32_t company_id) { - tBTA_AV_API_VENDOR* p_buf = - (tBTA_AV_API_VENDOR*)osi_malloc(sizeof(tBTA_AV_API_VENDOR) + len); +void BTA_AvVendorRsp(uint8_t rc_handle, uint8_t label, tBTA_AV_CODE rsp_code, uint8_t* p_data, + uint16_t len, uint32_t company_id) { + tBTA_AV_API_VENDOR* p_buf = (tBTA_AV_API_VENDOR*)osi_malloc(sizeof(tBTA_AV_API_VENDOR) + len); p_buf->hdr.event = BTA_AV_API_VENDOR_RSP_EVT; p_buf->hdr.layer_specific = rc_handle; p_buf->msg.hdr.ctype = rsp_code; p_buf->msg.hdr.subunit_type = AVRC_SUB_PANEL; p_buf->msg.hdr.subunit_id = 0; - if (company_id) + if (company_id) { p_buf->msg.company_id = company_id; - else + } else { p_buf->msg.company_id = p_bta_av_cfg->company_id; + } p_buf->label = label; p_buf->msg.vendor_len = len; if (p_data == NULL) { @@ -526,8 +509,7 @@ void BTA_AvVendorRsp(uint8_t rc_handle, uint8_t label, tBTA_AV_CODE rsp_code, * ******************************************************************************/ void BTA_AvOpenRc(tBTA_AV_HNDL handle) { - tBTA_AV_API_OPEN_RC* p_buf = - (tBTA_AV_API_OPEN_RC*)osi_malloc(sizeof(tBTA_AV_API_OPEN_RC)); + tBTA_AV_API_OPEN_RC* p_buf = (tBTA_AV_API_OPEN_RC*)osi_malloc(sizeof(tBTA_AV_API_OPEN_RC)); p_buf->hdr.event = BTA_AV_API_RC_OPEN_EVT; p_buf->hdr.layer_specific = handle; @@ -545,8 +527,7 @@ void BTA_AvOpenRc(tBTA_AV_HNDL handle) { * ******************************************************************************/ void BTA_AvCloseRc(uint8_t rc_handle) { - tBTA_AV_API_CLOSE_RC* p_buf = - (tBTA_AV_API_CLOSE_RC*)osi_malloc(sizeof(tBTA_AV_API_CLOSE_RC)); + tBTA_AV_API_CLOSE_RC* p_buf = (tBTA_AV_API_CLOSE_RC*)osi_malloc(sizeof(tBTA_AV_API_CLOSE_RC)); p_buf->hdr.event = BTA_AV_API_RC_CLOSE_EVT; p_buf->hdr.layer_specific = rc_handle; @@ -567,10 +548,8 @@ void BTA_AvCloseRc(uint8_t rc_handle) { * Returns void * ******************************************************************************/ -void BTA_AvMetaRsp(uint8_t rc_handle, uint8_t label, tBTA_AV_CODE rsp_code, - BT_HDR* p_pkt) { - tBTA_AV_API_META_RSP* p_buf = - (tBTA_AV_API_META_RSP*)osi_malloc(sizeof(tBTA_AV_API_META_RSP)); +void BTA_AvMetaRsp(uint8_t rc_handle, uint8_t label, tBTA_AV_CODE rsp_code, BT_HDR* p_pkt) { + tBTA_AV_API_META_RSP* p_buf = (tBTA_AV_API_META_RSP*)osi_malloc(sizeof(tBTA_AV_API_META_RSP)); p_buf->hdr.event = BTA_AV_API_META_RSP_EVT; p_buf->hdr.layer_specific = rc_handle; @@ -587,22 +566,20 @@ void BTA_AvMetaRsp(uint8_t rc_handle, uint8_t label, tBTA_AV_CODE rsp_code, * Function BTA_AvMetaCmd * * Description Send a Metadata/Advanced Control command. The message -*contained + *contained * in p_pkt can be composed with AVRC utility functions. * This function can only be used if AV is enabled with feature * BTA_AV_FEAT_METADATA. * This message is sent only when the peer supports the TG -*role. -*8 The only command makes sense right now is the absolute -*volume command. + *role. + *8 The only command makes sense right now is the absolute + *volume command. * * Returns void * ******************************************************************************/ -void BTA_AvMetaCmd(uint8_t rc_handle, uint8_t label, tBTA_AV_CMD cmd_code, - BT_HDR* p_pkt) { - tBTA_AV_API_META_RSP* p_buf = - (tBTA_AV_API_META_RSP*)osi_malloc(sizeof(tBTA_AV_API_META_RSP)); +void BTA_AvMetaCmd(uint8_t rc_handle, uint8_t label, tBTA_AV_CMD cmd_code, BT_HDR* p_pkt) { + tBTA_AV_API_META_RSP* p_buf = (tBTA_AV_API_META_RSP*)osi_malloc(sizeof(tBTA_AV_API_META_RSP)); p_buf->hdr.event = BTA_AV_API_META_RSP_EVT; p_buf->hdr.layer_specific = rc_handle; @@ -624,12 +601,11 @@ void BTA_AvMetaCmd(uint8_t rc_handle, uint8_t label, tBTA_AV_CMD cmd_code, * ******************************************************************************/ void BTA_AvSetLatency(tBTA_AV_HNDL handle, bool is_low_latency) { - log::info( - "Set audio/video stream low latency bta_handle:{}, is_low_latency:{}", - handle, is_low_latency); + log::info("Set audio/video stream low latency bta_handle:{}, is_low_latency:{}", handle, + is_low_latency); tBTA_AV_API_SET_LATENCY* p_buf = - (tBTA_AV_API_SET_LATENCY*)osi_malloc(sizeof(tBTA_AV_API_SET_LATENCY)); + (tBTA_AV_API_SET_LATENCY*)osi_malloc(sizeof(tBTA_AV_API_SET_LATENCY)); p_buf->hdr.event = BTA_AV_API_SET_LATENCY_EVT; p_buf->hdr.layer_specific = handle; p_buf->is_low_latency = is_low_latency; @@ -649,8 +625,7 @@ void BTA_AvSetLatency(tBTA_AV_HNDL handle, bool is_low_latency) { * ******************************************************************************/ void BTA_AvSetPeerSep(const RawAddress& bdaddr, uint8_t sep) { - tBTA_AV_API_PEER_SEP* p_buf = - (tBTA_AV_API_PEER_SEP*)osi_malloc(sizeof(tBTA_AV_API_PEER_SEP)); + tBTA_AV_API_PEER_SEP* p_buf = (tBTA_AV_API_PEER_SEP*)osi_malloc(sizeof(tBTA_AV_API_PEER_SEP)); p_buf->hdr.event = BTA_AV_API_PEER_SEP_EVT; p_buf->addr = bdaddr; diff --git a/system/bta/av/bta_av_cfg.cc b/system/bta/av/bta_av_cfg.cc index 319e6294b40..76aee2d45e1 100644 --- a/system/bta/av/bta_av_cfg.cc +++ b/system/bta/av/bta_av_cfg.cc @@ -45,13 +45,13 @@ const uint32_t bta_av_meta_caps_co_ids[] = {AVRC_CO_METADATA, AVRC_CO_BROADCOM}; /* AVRCP supported categories */ #define BTA_AV_RC_SUPF_CT (AVRC_SUPF_CT_CAT2) -#define BTA_AVK_RC_SUPF_CT \ - (AVRC_SUPF_CT_CAT1 | AVRC_SUPF_CT_BROWSE | \ - AVRC_SUPF_CT_COVER_ART_GET_IMAGE_PROP | AVRC_SUPF_CT_COVER_ART_GET_IMAGE) +#define BTA_AVK_RC_SUPF_CT \ + (AVRC_SUPF_CT_CAT1 | AVRC_SUPF_CT_BROWSE | AVRC_SUPF_CT_COVER_ART_GET_IMAGE_PROP | \ + AVRC_SUPF_CT_COVER_ART_GET_IMAGE) #define BTA_AVK_RC_SUPF_TG (AVRC_SUPF_TG_CAT2) -/* AVRCP Controller and Targer default name */ +/* AVRCP Controller and Target default name */ #ifndef BTA_AV_RC_CT_NAME #define BTA_AV_RC_CT_NAME "AVRC Controller" #endif @@ -65,7 +65,7 @@ const uint32_t bta_av_meta_caps_co_ids[] = {AVRC_CO_METADATA, AVRC_CO_BROADCOM}; * 2. Remove Group navigation support in SupportedFeatures * 3. GetCapabilities supported event_ids list * 4. GetCapabilities supported event_ids count -*/ + */ /* Note: Android doesnt support AVRC_SUPF_TG_GROUP_NAVI */ /* Note: if AVRC_SUPF_TG_GROUP_NAVI is set, bta_av_cfg.avrc_group should be true @@ -81,13 +81,12 @@ const uint32_t bta_av_meta_caps_co_ids[] = {AVRC_CO_METADATA, AVRC_CO_BROADCOM}; * also needs to be changed. */ const uint8_t bta_av_meta_caps_evt_ids[] = { - AVRC_EVT_PLAY_STATUS_CHANGE, AVRC_EVT_TRACK_CHANGE, - AVRC_EVT_PLAY_POS_CHANGED, AVRC_EVT_AVAL_PLAYERS_CHANGE, - AVRC_EVT_ADDR_PLAYER_CHANGE, AVRC_EVT_UIDS_CHANGE, - AVRC_EVT_NOW_PLAYING_CHANGE, - /* TODO: Add support for these events - AVRC_EVT_APP_SETTING_CHANGE, - */ + AVRC_EVT_PLAY_STATUS_CHANGE, AVRC_EVT_TRACK_CHANGE, AVRC_EVT_PLAY_POS_CHANGED, + AVRC_EVT_AVAL_PLAYERS_CHANGE, AVRC_EVT_ADDR_PLAYER_CHANGE, AVRC_EVT_UIDS_CHANGE, + AVRC_EVT_NOW_PLAYING_CHANGE, + /* TODO: Add support for these events + AVRC_EVT_APP_SETTING_CHANGE, + */ }; #ifndef BTA_AV_NUM_RC_EVT_IDS @@ -98,7 +97,7 @@ const uint8_t bta_av_meta_caps_evt_ids[] = { const uint8_t* get_bta_avk_meta_caps_evt_ids() { if (avrcp_absolute_volume_is_enabled()) { static const uint8_t bta_avk_meta_caps_evt_ids[] = { - AVRC_EVT_VOLUME_CHANGE, + AVRC_EVT_VOLUME_CHANGE, }; return bta_avk_meta_caps_evt_ids; } else { @@ -108,34 +107,31 @@ const uint8_t* get_bta_avk_meta_caps_evt_ids() { // These are the only events used with AVRCP1.3 const uint8_t bta_av_meta_caps_evt_ids_avrcp13[] = { - AVRC_EVT_PLAY_STATUS_CHANGE, AVRC_EVT_TRACK_CHANGE, - AVRC_EVT_PLAY_POS_CHANGED, + AVRC_EVT_PLAY_STATUS_CHANGE, + AVRC_EVT_TRACK_CHANGE, + AVRC_EVT_PLAY_POS_CHANGED, }; #ifndef BTA_AV_NUM_RC_EVT_IDS_AVRCP13 -#define BTA_AV_NUM_RC_EVT_IDS_AVRCP13 \ - (sizeof(bta_av_meta_caps_evt_ids_avrcp13) / \ - sizeof(bta_av_meta_caps_evt_ids_avrcp13[0])) +#define BTA_AV_NUM_RC_EVT_IDS_AVRCP13 \ + (sizeof(bta_av_meta_caps_evt_ids_avrcp13) / sizeof(bta_av_meta_caps_evt_ids_avrcp13[0])) #endif /* BTA_AV_NUM_RC_EVT_IDS_AVRCP13 */ /* This configuration to be used when we are Src + TG + CT( only for abs vol) */ extern const tBTA_AV_CFG bta_av_cfg = { - AVRC_CO_METADATA, /* AVRCP Company ID */ - - BTA_AV_RC_SUPF_CT, /* AVRCP controller categories */ - BTA_AV_RC_SUPF_TG, /* AVRCP target categories */ - 6, /* AVDTP audio channel max data queue size */ - false, /* true, to accept AVRC 1.3 group nevigation command */ - 2, /* company id count in p_meta_co_ids */ - BTA_AV_NUM_RC_EVT_IDS, /* event id count in p_meta_evt_ids */ - BTA_AV_RC_PASS_RSP_CODE, /* the default response code for pass - through commands */ - bta_av_meta_caps_co_ids, /* the metadata Get Capabilities response - for company id */ - bta_av_meta_caps_evt_ids, /* the the metadata Get Capabilities - response for event id */ - BTA_AV_RC_CT_NAME, /* Default AVRCP controller name */ - BTA_AV_RC_TG_NAME /* Default AVRCP target name */ + AVRC_CO_METADATA, /* AVRCP Company ID */ + + BTA_AV_RC_SUPF_CT, /* AVRCP controller categories */ + BTA_AV_RC_SUPF_TG, /* AVRCP target categories */ + 6, /* AVDTP audio channel max data queue size */ + false, /* true, to accept AVRC 1.3 group nevigation command */ + 2, /* company id count in p_meta_co_ids */ + BTA_AV_NUM_RC_EVT_IDS, /* event id count in p_meta_evt_ids */ + BTA_AV_RC_PASS_RSP_CODE, /* the default response code for pass through commands */ + bta_av_meta_caps_co_ids, /* the metadata Get Capabilities response for company id */ + bta_av_meta_caps_evt_ids, /* the metadata Get Capabilities response for event id */ + BTA_AV_RC_CT_NAME, /* Default AVRCP controller name */ + BTA_AV_RC_TG_NAME /* Default AVRCP target name */ }; /* This configuration to be used when we are Sink + CT + TG( only for abs vol) @@ -143,66 +139,63 @@ extern const tBTA_AV_CFG bta_av_cfg = { const tBTA_AV_CFG* get_bta_avk_cfg() { static const tBTA_AV_CFG bta_avk_cfg = { - AVRC_CO_METADATA, /* AVRCP Company ID */ - BTA_AVK_RC_SUPF_CT, /* AVRCP controller categories */ - BTA_AVK_RC_SUPF_TG, /* AVRCP target categories */ - 6, /* AVDTP audio channel max data queue size */ - false, /* true, to accept AVRC 1.3 group nevigation command */ - 2, /* company id count in p_meta_co_ids */ - (uint8_t)(avrcp_absolute_volume_is_enabled() - ? 1 - : 0), /* event id count in p_meta_evt_ids */ - BTA_AV_RC_PASS_RSP_CODE, /* the default response code for pass - through commands */ - bta_av_meta_caps_co_ids, /* the metadata Get Capabilities response - for company id */ - get_bta_avk_meta_caps_evt_ids(), /* the metadata Get Capabilities response - for event id */ - {0}, /* Default AVRCP controller name */ - {0}, /* Default AVRCP target name */ + AVRC_CO_METADATA, /* AVRCP Company ID */ + BTA_AVK_RC_SUPF_CT, /* AVRCP controller categories */ + BTA_AVK_RC_SUPF_TG, /* AVRCP target categories */ + 6, /* AVDTP audio channel max data queue size */ + false, /* true, to accept AVRC 1.3 group nevigation command */ + 2, /* company id count in p_meta_co_ids */ + (uint8_t)(avrcp_absolute_volume_is_enabled() ? 1 + : 0), /* event id count in p_meta_evt_ids */ + BTA_AV_RC_PASS_RSP_CODE, /* the default response code for pass + through commands */ + bta_av_meta_caps_co_ids, /* the metadata Get Capabilities response + for company id */ + get_bta_avk_meta_caps_evt_ids(), /* the metadata Get Capabilities response + for event id */ + {0}, /* Default AVRCP controller name */ + {0}, /* Default AVRCP target name */ }; return &bta_avk_cfg; } /* This configuration to be used when we are using AVRCP1.3 */ extern const tBTA_AV_CFG bta_av_cfg_compatibility = { - AVRC_CO_METADATA, /* AVRCP Company ID */ - - BTA_AV_RC_SUPF_CT, /* AVRCP controller categories */ - AVRC_SUPF_TG_CAT1, /* Only support CAT1 for AVRCP1.3 */ - 6, /* AVDTP audio channel max data queue size */ - false, /* true, to accept AVRC 1.3 group nevigation command */ - 2, /* company id count in p_meta_co_ids */ - BTA_AV_NUM_RC_EVT_IDS_AVRCP13, /* event id count for AVRCP1.3 */ - BTA_AV_RC_PASS_RSP_CODE, /* the default response code for pass - through commands */ - bta_av_meta_caps_co_ids, /* the metadata Get Capabilities response - for company id */ - bta_av_meta_caps_evt_ids_avrcp13, /* the the metadata Get Capabilities - response for event id, compatible - with AVRCP1.3 */ - BTA_AV_RC_CT_NAME, /* Default AVRCP controller name */ - BTA_AV_RC_TG_NAME /* Default AVRCP target name */ + AVRC_CO_METADATA, /* AVRCP Company ID */ + + BTA_AV_RC_SUPF_CT, /* AVRCP controller categories */ + AVRC_SUPF_TG_CAT1, /* Only support CAT1 for AVRCP1.3 */ + 6, /* AVDTP audio channel max data queue size */ + false, /* true, to accept AVRC 1.3 group nevigation command */ + 2, /* company id count in p_meta_co_ids */ + BTA_AV_NUM_RC_EVT_IDS_AVRCP13, /* event id count for AVRCP1.3 */ + BTA_AV_RC_PASS_RSP_CODE, /* the default response code for pass through commands */ + bta_av_meta_caps_co_ids, /* the metadata Get Capabilities response + for company id */ + bta_av_meta_caps_evt_ids_avrcp13, /* the metadata Get Capabilities + response for event id, compatible with AVRCP1.3 */ + BTA_AV_RC_CT_NAME, /* Default AVRCP controller name */ + BTA_AV_RC_TG_NAME /* Default AVRCP target name */ }; const tBTA_AV_CFG* p_bta_av_cfg = NULL; const uint16_t bta_av_rc_id[] = { - 0x0000, /* bit mask: 0=SELECT, 1=UP, 2=DOWN, 3=LEFT, - 4=RIGHT, 5=RIGHT_UP, 6=RIGHT_DOWN, 7=LEFT_UP, - 8=LEFT_DOWN, 9=ROOT_MENU, 10=SETUP_MENU, 11=CONT_MENU, - 12=FAV_MENU, 13=EXIT */ + 0x0000, /* bit mask: 0=SELECT, 1=UP, 2=DOWN, 3=LEFT, + 4=RIGHT, 5=RIGHT_UP, 6=RIGHT_DOWN, 7=LEFT_UP, + 8=LEFT_DOWN, 9=ROOT_MENU, 10=SETUP_MENU, 11=CONT_MENU, + 12=FAV_MENU, 13=EXIT */ - 0, /* not used */ + 0, /* not used */ - 0x0000, /* bit mask: 0=0, 1=1, 2=2, 3=3, - 4=4, 5=5, 6=6, 7=7, - 8=8, 9=9, 10=DOT, 11=ENTER, - 12=CLEAR */ + 0x0000, /* bit mask: 0=0, 1=1, 2=2, 3=3, + 4=4, 5=5, 6=6, 7=7, + 8=8, 9=9, 10=DOT, 11=ENTER, + 12=CLEAR */ - 0x0000, /* bit mask: 0=CHAN_UP, 1=CHAN_DOWN, 2=PREV_CHAN, 3=SOUND_SEL, - 4=INPUT_SEL, 5=DISP_INFO, 6=HELP, 7=PAGE_UP, - 8=PAGE_DOWN */ + 0x0000, /* bit mask: 0=CHAN_UP, 1=CHAN_DOWN, 2=PREV_CHAN, 3=SOUND_SEL, + 4=INPUT_SEL, 5=DISP_INFO, 6=HELP, 7=PAGE_UP, + 8=PAGE_DOWN */ /* btui_app provides an example of how to leave the decision of rejecting a command or not @@ -214,59 +207,59 @@ const uint16_t bta_av_rc_id[] = { 6=PAUSE, 7=RECORD, 8=REWIND, 9=FAST_FOR, 10=EJECT, 11=FORWARD, 12=BACKWARD */ #if (BTA_AV_RC_PASS_RSP_CODE == AVRC_RSP_INTERIM) - 0x0070, /* PLAY | STOP | PAUSE */ -#else /* BTA_AV_RC_PASS_RSP_CODE != AVRC_RSP_INTERIM */ - 0x1b7E, /* PLAY | STOP | PAUSE | FF | RW | VOL_UP | VOL_DOWN | MUTE | FW | - BACK */ -#endif /* BTA_AV_RC_PASS_RSP_CODE */ + 0x0070, /* PLAY | STOP | PAUSE */ +#else /* BTA_AV_RC_PASS_RSP_CODE != AVRC_RSP_INTERIM */ + 0x1b7E, /* PLAY | STOP | PAUSE | FF | RW | VOL_UP | VOL_DOWN | MUTE | FW | + BACK */ +#endif /* BTA_AV_RC_PASS_RSP_CODE */ - 0x0000, /* bit mask: 0=ANGLE, 1=SUBPICT */ + 0x0000, /* bit mask: 0=ANGLE, 1=SUBPICT */ - 0, /* not used */ + 0, /* not used */ - 0x0000 /* bit mask: 0=not used, 1=F1, 2=F2, 3=F3, - 4=F4, 5=F5 */ + 0x0000 /* bit mask: 0=not used, 1=F1, 2=F2, 3=F3, + 4=F4, 5=F5 */ }; #if (BTA_AV_RC_PASS_RSP_CODE == AVRC_RSP_INTERIM) const uint16_t bta_av_rc_id_ac[] = { - 0x0000, /* bit mask: 0=SELECT, 1=UP, 2=DOWN, 3=LEFT, - 4=RIGHT, 5=RIGHT_UP, 6=RIGHT_DOWN, - 7=LEFT_UP, - 8=LEFT_DOWN, 9=ROOT_MENU, 10=SETUP_MENU, - 11=CONT_MENU, - 12=FAV_MENU, 13=EXIT */ - - 0, /* not used */ - - 0x0000, /* bit mask: 0=0, 1=1, 2=2, 3=3, - 4=4, 5=5, 6=6, 7=7, - 8=8, 9=9, 10=DOT, 11=ENTER, - 12=CLEAR */ - - 0x0000, /* bit mask: 0=CHAN_UP, 1=CHAN_DOWN, 2=PREV_CHAN, - 3=SOUND_SEL, - 4=INPUT_SEL, 5=DISP_INFO, 6=HELP, - 7=PAGE_UP, - 8=PAGE_DOWN */ - - /* btui_app provides an example of how to leave the decision of - * rejecting a command or not - * based on which media player is currently addressed (this is - * only applicable for AVRCP 1.4 or later) - * If the decision is per player for a particular rc_id, the - * related bit is set */ - 0x1800, /* bit mask: 0=POWER, 1=VOL_UP, 2=VOL_DOWN, 3=MUTE, - 4=PLAY, 5=STOP, 6=PAUSE, 7=RECORD, - 8=REWIND, 9=FAST_FOR, 10=EJECT, 11=FORWARD, - 12=BACKWARD */ - - 0x0000, /* bit mask: 0=ANGLE, 1=SUBPICT */ - - 0, /* not used */ - - 0x0000 /* bit mask: 0=not used, 1=F1, 2=F2, 3=F3, - 4=F4, 5=F5 */ + 0x0000, /* bit mask: 0=SELECT, 1=UP, 2=DOWN, 3=LEFT, + 4=RIGHT, 5=RIGHT_UP, 6=RIGHT_DOWN, + 7=LEFT_UP, + 8=LEFT_DOWN, 9=ROOT_MENU, 10=SETUP_MENU, + 11=CONT_MENU, + 12=FAV_MENU, 13=EXIT */ + + 0, /* not used */ + + 0x0000, /* bit mask: 0=0, 1=1, 2=2, 3=3, + 4=4, 5=5, 6=6, 7=7, + 8=8, 9=9, 10=DOT, 11=ENTER, + 12=CLEAR */ + + 0x0000, /* bit mask: 0=CHAN_UP, 1=CHAN_DOWN, 2=PREV_CHAN, + 3=SOUND_SEL, + 4=INPUT_SEL, 5=DISP_INFO, 6=HELP, + 7=PAGE_UP, + 8=PAGE_DOWN */ + + /* btui_app provides an example of how to leave the decision of + * rejecting a command or not + * based on which media player is currently addressed (this is + * only applicable for AVRCP 1.4 or later) + * If the decision is per player for a particular rc_id, the + * related bit is set */ + 0x1800, /* bit mask: 0=POWER, 1=VOL_UP, 2=VOL_DOWN, 3=MUTE, + 4=PLAY, 5=STOP, 6=PAUSE, 7=RECORD, + 8=REWIND, 9=FAST_FOR, 10=EJECT, 11=FORWARD, + 12=BACKWARD */ + + 0x0000, /* bit mask: 0=ANGLE, 1=SUBPICT */ + + 0, /* not used */ + + 0x0000 /* bit mask: 0=not used, 1=F1, 2=F2, 3=F3, + 4=F4, 5=F5 */ }; uint16_t* p_bta_av_rc_id_ac = (uint16_t*)bta_av_rc_id_ac; #else diff --git a/system/bta/av/bta_av_ci.cc b/system/bta/av/bta_av_ci.cc index 3220d2b0a25..5f2fe827044 100644 --- a/system/bta/av/bta_av_ci.cc +++ b/system/bta/av/bta_av_ci.cc @@ -67,20 +67,18 @@ void bta_av_ci_src_data_ready(tBTA_AV_CHNL chnl) { * Returns void * ******************************************************************************/ -void bta_av_ci_setconfig(tBTA_AV_HNDL bta_av_handle, uint8_t err_code, - uint8_t category, uint8_t num_seid, uint8_t* p_seid, - bool recfg_needed, uint8_t avdt_handle) { +void bta_av_ci_setconfig(tBTA_AV_HNDL bta_av_handle, uint8_t err_code, uint8_t category, + uint8_t num_seid, uint8_t* p_seid, bool recfg_needed, + uint8_t avdt_handle) { log::info( - "bta_av_handle=0x{:x} err_code={} category={} num_seid={} " - "recfg_needed={} avdt_handle={}", - bta_av_handle, err_code, category, num_seid, recfg_needed, avdt_handle); + "bta_av_handle=0x{:x} err_code={} category={} num_seid={} recfg_needed={} avdt_handle={}", + bta_av_handle, err_code, category, num_seid, recfg_needed, avdt_handle); - tBTA_AV_CI_SETCONFIG* p_buf = - (tBTA_AV_CI_SETCONFIG*)osi_malloc(sizeof(tBTA_AV_CI_SETCONFIG)); + tBTA_AV_CI_SETCONFIG* p_buf = (tBTA_AV_CI_SETCONFIG*)osi_malloc(sizeof(tBTA_AV_CI_SETCONFIG)); p_buf->hdr.layer_specific = bta_av_handle; - p_buf->hdr.event = (err_code == A2DP_SUCCESS) ? BTA_AV_CI_SETCONFIG_OK_EVT - : BTA_AV_CI_SETCONFIG_FAIL_EVT; + p_buf->hdr.event = + (err_code == A2DP_SUCCESS) ? BTA_AV_CI_SETCONFIG_OK_EVT : BTA_AV_CI_SETCONFIG_FAIL_EVT; p_buf->err_code = err_code; p_buf->category = category; p_buf->recfg_needed = recfg_needed; diff --git a/system/bta/av/bta_av_int.h b/system/bta/av/bta_av_int.h index 6256be76a46..b9fd3c60134 100644 --- a/system/bta/av/bta_av_int.h +++ b/system/bta/av/bta_av_int.h @@ -170,44 +170,31 @@ enum { ****************************************************************************/ /* function types for call-out functions */ -typedef bool (*tBTA_AV_CO_INIT)(btav_a2dp_codec_index_t codec_index, - AvdtpSepConfig* p_cfg); -typedef void (*tBTA_AV_CO_DISC_RES)(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_addr, - uint8_t num_seps, uint8_t num_snk, - uint8_t num_src, uint16_t uuid_local); -typedef tA2DP_STATUS (*tBTA_AV_CO_GETCFG)(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_addr, - uint8_t* p_codec_info, - uint8_t* p_sep_info_idx, uint8_t seid, - uint8_t* p_num_protect, +typedef bool (*tBTA_AV_CO_INIT)(btav_a2dp_codec_index_t codec_index, AvdtpSepConfig* p_cfg); +typedef void (*tBTA_AV_CO_DISC_RES)(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_addr, + uint8_t num_seps, uint8_t num_snk, uint8_t num_src, + uint16_t uuid_local); +typedef tA2DP_STATUS (*tBTA_AV_CO_GETCFG)(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_addr, + uint8_t* p_codec_info, uint8_t* p_sep_info_idx, + uint8_t seid, uint8_t* p_num_protect, uint8_t* p_protect_info); -typedef void (*tBTA_AV_CO_SETCFG)(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_addr, - const uint8_t* p_codec_info, uint8_t seid, - uint8_t num_protect, - const uint8_t* p_protect_info, - uint8_t t_local_sep, uint8_t avdt_handle); -typedef void (*tBTA_AV_CO_OPEN)(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_addr, uint16_t mtu); -typedef void (*tBTA_AV_CO_CLOSE)(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_addr); -typedef void (*tBTA_AV_CO_START)(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_addr, - const uint8_t* p_codec_info, - bool* p_no_rtp_header); -typedef void (*tBTA_AV_CO_STOP)(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_addr); -typedef BT_HDR* (*tBTA_AV_CO_DATAPATH)(const uint8_t* p_codec_info, - uint32_t* p_timestamp); -typedef void (*tBTA_AV_CO_DELAY)(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_addr, uint16_t delay); -typedef void (*tBTA_AV_CO_UPDATE_MTU)(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_addr, +typedef void (*tBTA_AV_CO_SETCFG)(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_addr, + const uint8_t* p_codec_info, uint8_t seid, uint8_t num_protect, + const uint8_t* p_protect_info, uint8_t t_local_sep, + uint8_t avdt_handle); +typedef void (*tBTA_AV_CO_OPEN)(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_addr, + uint16_t mtu); +typedef void (*tBTA_AV_CO_CLOSE)(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_addr); +typedef void (*tBTA_AV_CO_START)(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_addr, + const uint8_t* p_codec_info, bool* p_no_rtp_header); +typedef void (*tBTA_AV_CO_STOP)(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_addr); +typedef BT_HDR* (*tBTA_AV_CO_DATAPATH)(const uint8_t* p_codec_info, uint32_t* p_timestamp); +typedef void (*tBTA_AV_CO_DELAY)(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_addr, + uint16_t delay); +typedef void (*tBTA_AV_CO_UPDATE_MTU)(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_addr, uint16_t mtu); -typedef btav_a2dp_scmst_info_t (*tBTA_AV_CO_GET_SCMST_INFO)( - const RawAddress& peer_addr); +typedef btav_a2dp_scmst_info_t (*tBTA_AV_CO_GET_SCMST_INFO)(const RawAddress& peer_addr); /* the call-out functions for one stream */ typedef struct { @@ -248,8 +235,7 @@ typedef enum : uint8_t { BTA_AV_RS_DONE /* the role switch is done - continue */ } tBTA_AV_RS_RES; -inline std::string bta_av_role_switch_result_text( - const tBTA_AV_RS_RES& result) { +inline std::string bta_av_role_switch_result_text(const tBTA_AV_RS_RES& result) { switch (result) { CASE_RETURN_TEXT(BTA_AV_RS_NONE); CASE_RETURN_TEXT(BTA_AV_RS_OK); @@ -369,7 +355,7 @@ typedef struct { typedef struct { BT_HDR_RIGID hdr; AvdtpSepConfig cfg; /* configuration/capabilities parameters */ - tAVDT_CTRL msg; /* AVDTP callback message parameters */ + tAVDT_CTRL msg; /* AVDTP callback message parameters */ RawAddress bd_addr; /* bd address */ uint8_t scb_index; uint8_t handle; @@ -420,11 +406,10 @@ typedef struct { /* type for SEP control block */ typedef struct { - uint8_t av_handle; /* AVDTP handle */ - uint8_t tsep; /* SEP type of local SEP */ - uint8_t codec_info[AVDT_CODEC_SIZE]; /* Codec info */ - tBTA_AV_SINK_DATA_CBACK* - p_app_sink_data_cback; /* Sink application callback for media packets */ + uint8_t av_handle; /* AVDTP handle */ + uint8_t tsep; /* SEP type of local SEP */ + uint8_t codec_info[AVDT_CODEC_SIZE]; /* Codec info */ + tBTA_AV_SINK_DATA_CBACK* p_app_sink_data_cback; /* Sink application callback for media packets */ } tBTA_AV_SEP; enum : uint8_t { @@ -483,89 +468,81 @@ typedef union { #define BTA_AV_Q_TAG_START 0x02 /* before start sending media packets */ #define BTA_AV_Q_TAG_STREAM 0x03 /* during streaming */ -#define BTA_AV_WAIT_ACP_CAPS_ON 0x01 /* retriving the peer capabilities */ -#define BTA_AV_WAIT_ACP_CAPS_STARTED \ - 0x02 /* started while retriving peer capabilities */ +#define BTA_AV_WAIT_ACP_CAPS_ON 0x01 /* retrieving the peer capabilities */ +#define BTA_AV_WAIT_ACP_CAPS_STARTED 0x02 /* started while retrieving peer capabilities */ #define BTA_AV_WAIT_ROLE_SW_RES_OPEN \ 0x04 /* waiting for role switch result after API_OPEN, before STR_OPENED */ -#define BTA_AV_WAIT_ROLE_SW_RES_START \ - 0x08 /* waiting for role switch result before streaming */ -#define BTA_AV_WAIT_ROLE_SW_STARTED \ - 0x10 /* started while waiting for role switch result */ -#define BTA_AV_WAIT_ROLE_SW_RETRY 0x20 /* set when retry on timeout */ -#define BTA_AV_WAIT_CHECK_RC \ - 0x40 /* set when the timer is used by role switch */ -#define BTA_AV_WAIT_ROLE_SW_FAILED 0x80 /* role switch failed */ - -#define BTA_AV_WAIT_ROLE_SW_BITS \ - (BTA_AV_WAIT_ROLE_SW_RES_OPEN | BTA_AV_WAIT_ROLE_SW_RES_START | \ - BTA_AV_WAIT_ROLE_SW_STARTED | BTA_AV_WAIT_ROLE_SW_RETRY) +#define BTA_AV_WAIT_ROLE_SW_RES_START 0x08 /* waiting for role switch result before streaming */ +#define BTA_AV_WAIT_ROLE_SW_STARTED 0x10 /* started while waiting for role switch result */ +#define BTA_AV_WAIT_ROLE_SW_RETRY 0x20 /* set when retry on timeout */ +#define BTA_AV_WAIT_CHECK_RC 0x40 /* set when the timer is used by role switch */ +#define BTA_AV_WAIT_ROLE_SW_FAILED 0x80 /* role switch failed */ + +#define BTA_AV_WAIT_ROLE_SW_BITS \ + (BTA_AV_WAIT_ROLE_SW_RES_OPEN | BTA_AV_WAIT_ROLE_SW_RES_START | BTA_AV_WAIT_ROLE_SW_STARTED | \ + BTA_AV_WAIT_ROLE_SW_RETRY) /* Bitmap for collision, coll_mask */ -#define BTA_AV_COLL_INC_TMR \ - 0x01 /* Timer is running for incoming L2C connection */ -#define BTA_AV_COLL_API_CALLED \ - 0x02 /* API open was called while incoming timer is running */ +#define BTA_AV_COLL_INC_TMR 0x01 /* Timer is running for incoming L2C connection */ +#define BTA_AV_COLL_API_CALLED 0x02 /* API open was called while incoming timer is running */ /* type for AV stream control block */ // TODO: This should be renamed and changed to a proper class struct tBTA_AV_SCB final { - public: +public: const tBTA_AV_CO_FUNCTS* p_cos; /* the associated callout functions */ - bool sdp_discovery_started; /* variable to determine whether SDP is started */ + bool sdp_discovery_started; /* variable to determine whether SDP is started */ tBTA_AV_SEP seps[BTAV_A2DP_CODEC_INDEX_MAX]; AvdtpSepConfig peer_cap; /* buffer used for get capabilities */ - list_t* a2dp_list; /* used for audio channels only */ + list_t* a2dp_list; /* used for audio channels only */ tBTA_AV_Q_INFO q_info; tAVDT_SEP_INFO sep_info[BTA_AV_NUM_SEPS]; /* stream discovery results */ AvdtpSepConfig cfg; /* local SEP configuration */ alarm_t* avrc_ct_timer; /* delay timer for AVRC CT */ alarm_t* link_signalling_timer; - alarm_t* - accept_signalling_timer; /* timer to monitor signalling when accepting */ - uint16_t l2c_cid; /* L2CAP channel ID */ - uint16_t stream_mtu; /* MTU of stream */ - uint8_t media_type; /* Media type: AVDT_MEDIA_TYPE_* */ - bool cong; /* true if AVDTP congested */ - tBTA_AV_STATUS open_status; /* open failure status */ - tBTA_AV_CHNL chnl; /* the channel: audio/video */ - tBTA_AV_HNDL hndl; /* the handle: ((hdi + 1)|chnl) */ - uint16_t cur_psc_mask; /* Protocol service capabilities mask for current - connection */ - uint8_t avdt_handle; /* AVDTP handle */ - uint8_t hdi; /* the index to SCB[] */ - uint8_t num_seps; /* number of seps returned by stream discovery */ - uint8_t num_disc_snks; /* number of discovered snks */ - uint8_t num_disc_srcs; /* number of discovered srcs */ - uint8_t sep_info_idx; /* current index into sep_info */ - uint8_t sep_idx; /* current index into local seps[] */ - uint8_t rcfg_idx; /* reconfig requested index into sep_info */ - uint8_t state; /* state machine state */ - uint8_t avdt_label; /* AVDTP label */ - uint8_t app_id; /* application id */ - uint8_t num_recfg; /* number of reconfigure sent */ + alarm_t* accept_signalling_timer; /* timer to monitor signalling when accepting */ + uint16_t l2c_cid; /* L2CAP channel ID */ + uint16_t stream_mtu; /* MTU of stream */ + uint8_t media_type; /* Media type: AVDT_MEDIA_TYPE_* */ + bool cong; /* true if AVDTP congested */ + tBTA_AV_STATUS open_status; /* open failure status */ + tBTA_AV_CHNL chnl; /* the channel: audio/video */ + tBTA_AV_HNDL hndl; /* the handle: ((hdi + 1)|chnl) */ + uint16_t cur_psc_mask; /* Protocol service capabilities mask for current + connection */ + uint8_t avdt_handle; /* AVDTP handle */ + uint8_t hdi; /* the index to SCB[] */ + uint8_t num_seps; /* number of seps returned by stream discovery */ + uint8_t num_disc_snks; /* number of discovered snks */ + uint8_t num_disc_srcs; /* number of discovered srcs */ + uint8_t sep_info_idx; /* current index into sep_info */ + uint8_t sep_idx; /* current index into local seps[] */ + uint8_t rcfg_idx; /* reconfig requested index into sep_info */ + uint8_t state; /* state machine state */ + uint8_t avdt_label; /* AVDTP label */ + uint8_t app_id; /* application id */ + uint8_t num_recfg; /* number of reconfigure sent */ uint8_t role; - uint8_t l2c_bufs; /* the number of buffers queued to L2CAP */ - uint8_t rc_handle; /* connected AVRCP handle */ - bool use_rc; /* true if AVRCP is allowed */ - bool started; /* true if stream started */ + uint8_t l2c_bufs; /* the number of buffers queued to L2CAP */ + uint8_t rc_handle; /* connected AVRCP handle */ + bool use_rc; /* true if AVRCP is allowed */ + bool started; /* true if stream started */ bool use_rtp_header_marker_bit; /* true if the encoded data packets have RTP * headers, and the Marker bit in the header * is set according to RFC 6416 */ - uint8_t - co_started; /* non-zero, if stream started from call-out perspective */ - bool recfg_sup; /* true if the first attempt to reconfigure the stream was - successfull, else False if command fails */ - bool suspend_sup; /* true if Suspend stream is supported, else false if - suspend command fails */ - bool deregistering; /* true if deregistering */ - bool sco_suspend; /* true if SUSPEND is issued automatically for SCO */ - uint8_t coll_mask; /* Mask to check incoming and outgoing collision */ - tBTA_AV_API_OPEN open_api; /* Saved OPEN api message */ - uint8_t wait; /* set 0x1, when getting Caps as ACP, set 0x2, when started */ - uint8_t q_tag; /* identify the associated q_info union member */ - bool no_rtp_header; /* true if add no RTP header */ - uint16_t uuid_int; /*intended UUID of Initiator to connect to */ + uint8_t co_started; /* non-zero, if stream started from call-out perspective */ + bool recfg_sup; /* true if the first attempt to reconfigure the stream was + successful, else False if command fails */ + bool suspend_sup; /* true if Suspend stream is supported, else false if + suspend command fails */ + bool deregistering; /* true if deregistering */ + bool sco_suspend; /* true if SUSPEND is issued automatically for SCO */ + uint8_t coll_mask; /* Mask to check incoming and outgoing collision */ + tBTA_AV_API_OPEN open_api; /* Saved OPEN api message */ + uint8_t wait; /* set 0x1, when getting Caps as ACP, set 0x2, when started */ + uint8_t q_tag; /* identify the associated q_info union member */ + bool no_rtp_header; /* true if add no RTP header */ + uint16_t uuid_int; /*intended UUID of Initiator to connect to */ /** * Called to setup the state when connected to a peer. @@ -604,7 +581,7 @@ struct tBTA_AV_SCB final { */ bool IsAssigned() const { return !peer_address_.IsEmpty(); } - private: +private: RawAddress peer_address_; // Peer address uint16_t avdtp_version_; // The AVDTP version of the peer device }; @@ -648,15 +625,14 @@ typedef struct { tBTA_AV_CBACK* p_cback; /* application callback function */ tBTA_AV_RCB rcb[BTA_AV_NUM_RCB]; /* RCB control block */ tBTA_AV_LCB lcb[BTA_AV_NUM_LINKS + 1]; /* link control block */ - uint32_t sdp_a2dp_handle; /* SDP record handle for audio src */ - uint32_t sdp_a2dp_snk_handle; /* SDP record handle for audio snk */ - tBTA_AV_FEAT features; /* features mask */ - tBTA_SEC sec_mask; /* security mask */ - tBTA_AV_HNDL handle; /* the handle for SDP activity */ - bool disabling; /* true if api disabled called */ - uint8_t enabling_attempts; // counter to wait for previous disabling - uint8_t - disc; /* (hdi+1) or (rc_handle|BTA_AV_CHNL_MSK) if p_disc_db is in use */ + uint32_t sdp_a2dp_handle; /* SDP record handle for audio src */ + uint32_t sdp_a2dp_snk_handle; /* SDP record handle for audio snk */ + tBTA_AV_FEAT features; /* features mask */ + tBTA_SEC sec_mask; /* security mask */ + tBTA_AV_HNDL handle; /* the handle for SDP activity */ + bool disabling; /* true if api disabled called */ + uint8_t enabling_attempts; // counter to wait for previous disabling + uint8_t disc; /* (hdi+1) or (rc_handle|BTA_AV_CHNL_MSK) if p_disc_db is in use */ uint8_t state; /* state machine state */ uint8_t conn_audio; /* handle mask of connected audio channels */ uint8_t conn_lcb; /* index mask of used LCBs */ @@ -664,8 +640,8 @@ typedef struct { uint8_t reg_audio; /* handle mask of registered audio channels */ uint8_t rc_acp_handle; uint8_t rc_acp_idx; /* (index + 1) to RCB */ - uint8_t rs_idx; /* (index + 1) to SCB for the one waiting for RS on open */ - bool sco_occupied; /* true if SCO is being used or call is in progress */ + uint8_t rs_idx; /* (index + 1) to SCB for the one waiting for RS on open */ + bool sco_occupied; /* true if SCO is being used or call is in progress */ uint16_t offload_start_pending_hndl; uint16_t offload_started_hndl; /* Set to true if the new offload start vendor command @@ -682,18 +658,18 @@ constexpr uint8_t kEnablingAttemptsCountMaximum = 5; // A2DP offload VSC parameters class tBT_A2DP_OFFLOAD { - public: - uint32_t codec_type; /* codec types ex: SBC/AAC/LDAC/APTx */ - uint16_t max_latency; /* maximum latency */ +public: + uint32_t codec_type; /* codec types ex: SBC/AAC/LDAC/APTx */ + uint16_t max_latency; /* maximum latency */ std::array scms_t_enable; /* SCMS-T enable */ - uint32_t sample_rate; /* Sample rates ex: 44.1/48/88.2/96 Khz */ - uint8_t bits_per_sample; /* bits per sample ex: 16/24/32 */ - uint8_t ch_mode; /* None:0 Left:1 Right:2 */ - uint32_t encoded_audio_bitrate; /* encoder audio bitrates */ - uint16_t acl_hdl; /* connection handle */ - uint16_t l2c_rcid; /* l2cap channel id */ - uint16_t mtu; /* MTU size */ - uint8_t codec_info[32]; /* Codec specific information */ + uint32_t sample_rate; /* Sample rates ex: 44.1/48/88.2/96 Khz */ + uint8_t bits_per_sample; /* bits per sample ex: 16/24/32 */ + uint8_t ch_mode; /* None:0 Left:1 Right:2 */ + uint32_t encoded_audio_bitrate; /* encoder audio bitrates */ + uint16_t acl_hdl; /* connection handle */ + uint16_t l2c_rcid; /* l2cap channel id */ + uint16_t mtu; /* MTU size */ + uint8_t codec_info[32]; /* Codec specific information */ }; /* Vendor OFFLOAD VSC */ @@ -722,8 +698,7 @@ extern uint16_t* p_bta_av_rc_id; extern uint16_t* p_bta_av_rc_id_ac; extern const tBTA_AV_CO_FUNCTS bta_av_a2dp_cos; -void bta_av_sink_data_cback(uint8_t handle, BT_HDR* p_pkt, uint32_t time_stamp, - uint8_t m_pt); +void bta_av_sink_data_cback(uint8_t handle, BT_HDR* p_pkt, uint32_t time_stamp, uint8_t m_pt); /***************************************************************************** * Function prototypes @@ -733,10 +708,9 @@ tBTA_AV_SCB* bta_av_hndl_to_scb(uint16_t handle); tBTA_AV_SCB* bta_av_addr_to_scb(const RawAddress& bd_addr); bool bta_av_chk_start(tBTA_AV_SCB* p_scb); void bta_av_restore_switch(void); -void bta_av_conn_cback(uint8_t handle, const RawAddress& bd_addr, uint8_t event, - tAVDT_CTRL* p_data, uint8_t scb_index); -uint8_t bta_av_rc_create(tBTA_AV_CB* p_cb, uint8_t role, uint8_t shdl, - uint8_t lidx); +void bta_av_conn_cback(uint8_t handle, const RawAddress& bd_addr, uint8_t event, tAVDT_CTRL* p_data, + uint8_t scb_index); +uint8_t bta_av_rc_create(tBTA_AV_CB* p_cb, uint8_t role, uint8_t shdl, uint8_t lidx); void bta_av_stream_chg(tBTA_AV_SCB* p_scb, bool started); bool bta_av_is_scb_opening(tBTA_AV_SCB* p_scb); bool bta_av_is_scb_incoming(tBTA_AV_SCB* p_scb); @@ -749,8 +723,7 @@ void bta_av_free_scb(tBTA_AV_SCB* p_scb); void bta_av_api_deregister(tBTA_AV_DATA* p_data); void bta_av_dup_audio_buf(tBTA_AV_SCB* p_scb, BT_HDR* p_buf); void bta_av_sm_execute(tBTA_AV_CB* p_cb, uint16_t event, tBTA_AV_DATA* p_data); -void bta_av_ssm_execute(tBTA_AV_SCB* p_scb, uint16_t event, - tBTA_AV_DATA* p_data); +void bta_av_ssm_execute(tBTA_AV_SCB* p_scb, uint16_t event, tBTA_AV_DATA* p_data); bool bta_av_hdl_event(const BT_HDR_RIGID* p_msg); const char* bta_av_evt_code(uint16_t evt_code); bool bta_av_switch_if_needed(tBTA_AV_SCB* p_scb); @@ -785,9 +758,8 @@ void bta_av_rc_free_browse_msg(tBTA_AV_CB* p_cb, tBTA_AV_DATA* p_data); tBTA_AV_RCB* bta_av_get_rcb_by_shdl(uint8_t shdl); void bta_av_del_rc(tBTA_AV_RCB* p_rcb); -void bta_av_proc_stream_evt(uint8_t handle, const RawAddress& bd_addr, - uint8_t event, tAVDT_CTRL* p_data, - uint8_t scb_index); +void bta_av_proc_stream_evt(uint8_t handle, const RawAddress& bd_addr, uint8_t event, + tAVDT_CTRL* p_data, uint8_t scb_index); /* ssm action functions */ void bta_av_do_disc_a2dp(tBTA_AV_SCB* p_scb, tBTA_AV_DATA* p_data); diff --git a/system/bta/av/bta_av_main.cc b/system/bta/av/bta_av_main.cc index 1c08195c943..04da5783aa5 100644 --- a/system/bta/av/bta_av_main.cc +++ b/system/bta/av/bta_av_main.cc @@ -108,12 +108,10 @@ static void bta_av_ci_data(tBTA_AV_DATA* p_data); static void bta_av_rpc_conn(tBTA_AV_DATA* p_data); static void bta_av_api_to_ssm(tBTA_AV_DATA* p_data); -static void bta_av_sco_chg_cback(tBTA_SYS_CONN_STATUS status, - uint8_t num_sco_links, uint8_t app_id, +static void bta_av_sco_chg_cback(tBTA_SYS_CONN_STATUS status, uint8_t num_sco_links, uint8_t app_id, const RawAddress& peer_addr); static void bta_av_sys_rs_cback(tBTA_SYS_CONN_STATUS status, tHCI_ROLE new_role, - tHCI_STATUS hci_status, - const RawAddress& peer_addr); + tHCI_STATUS hci_status, const RawAddress& peer_addr); /***************************************************************************** * Global data @@ -154,29 +152,23 @@ static void bta_av_api_enable(tBTA_AV_DATA* p_data) { } if (bta_av_cb.disabling) { - log::warn("previous (reg_audio={:#x}) is still disabling (attempts={})", - bta_av_cb.reg_audio, bta_av_cb.enabling_attempts); + log::warn("previous (reg_audio={:#x}) is still disabling (attempts={})", bta_av_cb.reg_audio, + bta_av_cb.enabling_attempts); if (++bta_av_cb.enabling_attempts <= kEnablingAttemptsCountMaximum) { - tBTA_AV_API_ENABLE* p_buf = - (tBTA_AV_API_ENABLE*)osi_malloc(sizeof(tBTA_AV_API_ENABLE)); + tBTA_AV_API_ENABLE* p_buf = (tBTA_AV_API_ENABLE*)osi_malloc(sizeof(tBTA_AV_API_ENABLE)); memcpy(p_buf, &p_data->api_enable, sizeof(tBTA_AV_API_ENABLE)); - bta_sys_sendmsg_delayed( - p_buf, std::chrono::milliseconds(kEnablingAttemptsIntervalMs)); + bta_sys_sendmsg_delayed(p_buf, std::chrono::milliseconds(kEnablingAttemptsIntervalMs)); return; } if (bta_av_cb.sdp_a2dp_handle) { - if (!get_legacy_stack_sdp_api()->handle.SDP_DeleteRecord( - bta_av_cb.sdp_a2dp_handle)) { - log::warn("Unable to delete SDP record handle:{}", - bta_av_cb.sdp_a2dp_handle); + if (!get_legacy_stack_sdp_api()->handle.SDP_DeleteRecord(bta_av_cb.sdp_a2dp_handle)) { + log::warn("Unable to delete SDP record handle:{}", bta_av_cb.sdp_a2dp_handle); } bta_sys_remove_uuid(UUID_SERVCLASS_AUDIO_SOURCE); } if (bta_av_cb.sdp_a2dp_snk_handle) { - if (!get_legacy_stack_sdp_api()->handle.SDP_DeleteRecord( - bta_av_cb.sdp_a2dp_snk_handle)) { - log::warn("Unable to delete SDP record handle:{}", - bta_av_cb.sdp_a2dp_snk_handle); + if (!get_legacy_stack_sdp_api()->handle.SDP_DeleteRecord(bta_av_cb.sdp_a2dp_snk_handle)) { + log::warn("Unable to delete SDP record handle:{}", bta_av_cb.sdp_a2dp_snk_handle); } bta_sys_remove_uuid(UUID_SERVCLASS_AUDIO_SINK); } @@ -192,8 +184,9 @@ static void bta_av_api_enable(tBTA_AV_DATA* p_data) { /* initialize control block */ memset(&bta_av_cb, 0, sizeof(tBTA_AV_CB)); - for (int i = 0; i < BTA_AV_NUM_RCB; i++) + for (int i = 0; i < BTA_AV_NUM_RCB; i++) { bta_av_cb.rcb[i].handle = BTA_AV_RC_HANDLE_NONE; + } bta_av_cb.rc_acp_handle = BTA_AV_RC_HANDLE_NONE; @@ -255,7 +248,7 @@ int BTA_AvObtainPeerChannelIndex(const RawAddress& peer_address) { } if (p_scb->PeerAddress().IsEmpty()) { const RawAddress& btif_addr = btif_av_find_by_handle(p_scb->hndl); - if (!btif_addr.IsEmpty() && btif_addr != peer_address) { + if (!btif_addr.IsEmpty() && btif_addr != peer_address) { log::verbose("btif_addr = {}, index={}!", btif_addr.ToString(), index); continue; } @@ -304,7 +297,9 @@ static tBTA_AV_SCB* bta_av_alloc_scb(tBTA_AV_CHNL chnl) { } for (int xx = 0; xx < BTA_AV_NUM_STRS; xx++) { - if (bta_av_cb.p_scb[xx] != nullptr) continue; + if (bta_av_cb.p_scb[xx] != nullptr) { + continue; + } // Found an empty spot // TODO: After tBTA_AV_SCB is changed to a proper class, the entry // here should be allocated by C++ 'new' statement. @@ -329,8 +324,7 @@ static tBTA_AV_SCB* bta_av_find_scb(tBTA_AV_CHNL chnl, uint8_t app_id) { } for (int xx = 0; xx < BTA_AV_NUM_STRS; xx++) { - if ((bta_av_cb.p_scb[xx] != nullptr) && - (bta_av_cb.p_scb[xx]->chnl == chnl) && + if ((bta_av_cb.p_scb[xx] != nullptr) && (bta_av_cb.p_scb[xx]->chnl == chnl) && (bta_av_cb.p_scb[xx]->app_id == app_id)) { log::verbose("found at: {}", xx); return bta_av_cb.p_scb[xx]; @@ -341,10 +335,11 @@ static tBTA_AV_SCB* bta_av_find_scb(tBTA_AV_CHNL chnl, uint8_t app_id) { } void bta_av_free_scb(tBTA_AV_SCB* p_scb) { - if (p_scb == nullptr) return; + if (p_scb == nullptr) { + return; + } uint8_t scb_index = p_scb->hdi; - log::assert_that(scb_index < BTA_AV_NUM_STRS, - "assert failed: scb_index < BTA_AV_NUM_STRS"); + log::assert_that(scb_index < BTA_AV_NUM_STRS, "assert failed: scb_index < BTA_AV_NUM_STRS"); log::assert_that(p_scb == bta_av_cb.p_scb[scb_index], "assert failed: p_scb == bta_av_cb.p_scb[scb_index]"); @@ -368,8 +363,7 @@ void tBTA_AV_SCB::OnConnected(const RawAddress& peer_address) { // Read and restore the AVDTP version from local storage uint16_t avdtp_version = 0; size_t version_value_size = sizeof(avdtp_version); - if (!btif_config_get_bin(peer_address_.ToString(), - BTIF_STORAGE_KEY_AVDTP_VERSION, + if (!btif_config_get_bin(peer_address_.ToString(), BTIF_STORAGE_KEY_AVDTP_VERSION, (uint8_t*)&avdtp_version, &version_value_size)) { log::warn("Failed to read cached peer AVDTP version for {}", peer_address_); } else { @@ -384,20 +378,18 @@ void tBTA_AV_SCB::OnDisconnected() { void tBTA_AV_SCB::SetAvdtpVersion(uint16_t avdtp_version) { avdtp_version_ = avdtp_version; - log::info("AVDTP version for {} set to 0x{:x}", peer_address_, - avdtp_version_); + log::info("AVDTP version for {} set to 0x{:x}", peer_address_, avdtp_version_); } /******************************************************************************* ******************************************************************************/ -void bta_av_conn_cback(uint8_t /* handle */, const RawAddress& bd_addr, - uint8_t event, tAVDT_CTRL* p_data, uint8_t scb_index) { +void bta_av_conn_cback(uint8_t /* handle */, const RawAddress& bd_addr, uint8_t event, + tAVDT_CTRL* p_data, uint8_t scb_index) { uint16_t evt = 0; tBTA_AV_SCB* p_scb = NULL; if (event == BTA_AR_AVDT_CONN_EVT || event == AVDT_CONNECT_IND_EVT || - event == AVDT_DISCONNECT_IND_EVT) - { + event == AVDT_DISCONNECT_IND_EVT) { evt = BTA_AV_SIG_CHG_EVT; if (event == AVDT_DISCONNECT_IND_EVT) { p_scb = bta_av_addr_to_scb(bd_addr); @@ -405,8 +397,7 @@ void bta_av_conn_cback(uint8_t /* handle */, const RawAddress& bd_addr, log::verbose("CONN_IND is ACP:{}", p_data->hdr.err_param); } - tBTA_AV_STR_MSG* p_msg = - (tBTA_AV_STR_MSG*)osi_malloc(sizeof(tBTA_AV_STR_MSG)); + tBTA_AV_STR_MSG* p_msg = (tBTA_AV_STR_MSG*)osi_malloc(sizeof(tBTA_AV_STR_MSG)); p_msg->hdr.event = evt; p_msg->hdr.layer_specific = event; p_msg->hdr.offset = p_data->hdr.err_param; @@ -429,8 +420,7 @@ void bta_av_conn_cback(uint8_t /* handle */, const RawAddress& bd_addr, * Returns void * ******************************************************************************/ -static void bta_av_a2dp_report_cback(uint8_t /* handle */, - AVDT_REPORT_TYPE /* type */, +static void bta_av_a2dp_report_cback(uint8_t /* handle */, AVDT_REPORT_TYPE /* type */, tAVDT_REPORT_DATA* /* p_data */) { /* Do not need to handle report data for now. * This empty function is here for conformance reasons. */ @@ -457,23 +447,18 @@ static void bta_av_api_register(tBTA_AV_DATA* p_data) { uint8_t local_role = 0; if (bta_av_cb.disabling || (bta_av_cb.features == 0)) { - log::warn( - "AV instance (features={:#x}, reg_audio={:#x}) is not ready for app_id " - "{}", - bta_av_cb.features, bta_av_cb.reg_audio, p_data->api_reg.app_id); - tBTA_AV_API_REG* p_buf = - (tBTA_AV_API_REG*)osi_malloc(sizeof(tBTA_AV_API_REG)); + log::warn("AV instance (features={:#x}, reg_audio={:#x}) is not ready for app_id {}", + bta_av_cb.features, bta_av_cb.reg_audio, p_data->api_reg.app_id); + tBTA_AV_API_REG* p_buf = (tBTA_AV_API_REG*)osi_malloc(sizeof(tBTA_AV_API_REG)); memcpy(p_buf, &p_data->api_reg, sizeof(tBTA_AV_API_REG)); - bta_sys_sendmsg_delayed( - p_buf, std::chrono::milliseconds(kEnablingAttemptsIntervalMs)); + bta_sys_sendmsg_delayed(p_buf, std::chrono::milliseconds(kEnablingAttemptsIntervalMs)); return; } avdtp_stream_config.Reset(); if (btif_av_src_sink_coexist_enabled()) { - local_role = (p_data->api_reg.service_uuid == UUID_SERVCLASS_AUDIO_SINK) - ? AVDT_TSEP_SNK - : AVDT_TSEP_SRC; + local_role = (p_data->api_reg.service_uuid == UUID_SERVCLASS_AUDIO_SINK) ? AVDT_TSEP_SNK + : AVDT_TSEP_SRC; } reg_data.status = BTA_AV_FAIL_RESOURCES; @@ -481,8 +466,7 @@ static void bta_av_api_register(tBTA_AV_DATA* p_data) { reg_data.chnl = (tBTA_AV_CHNL)p_data->hdr.layer_specific; char avrcp_version[PROPERTY_VALUE_MAX] = {0}; - osi_property_get(AVRCP_VERSION_PROPERTY, avrcp_version, - AVRCP_DEFAULT_VERSION); + osi_property_get(AVRCP_VERSION_PROPERTY, avrcp_version, AVRCP_DEFAULT_VERSION); log::info("AVRCP version used for sdp: \"{}\"", avrcp_version); uint16_t profile_initialized = p_data->api_reg.service_uuid; @@ -522,8 +506,7 @@ static void bta_av_api_register(tBTA_AV_DATA* p_data) { /* initialize the stream control block */ reg_data.status = BTA_AV_SUCCESS; - if ((btif_av_src_sink_coexist_enabled() && - !(bta_av_cb.reg_role & (1 << local_role))) || + if ((btif_av_src_sink_coexist_enabled() && !(bta_av_cb.reg_role & (1 << local_role))) || (!btif_av_src_sink_coexist_enabled() && bta_av_cb.reg_audio == 0)) { /* the first channel registered. register to AVDTP */ reg.ctrl_mtu = 672; @@ -545,44 +528,40 @@ static void bta_av_api_register(tBTA_AV_DATA* p_data) { */ if (is_new_avrcp_enabled()) { log::verbose( - "newavrcp is the owner of the AVRCP Target SDP record. Don't " - "create the SDP record"); + "newavrcp is the owner of the AVRCP Target SDP record. Don't " + "create the SDP record"); } else { log::verbose("newavrcp is not enabled. Create SDP record"); uint16_t profile_version = AVRC_REV_1_0; - if (!strncmp(AVRCP_1_6_STRING, avrcp_version, - sizeof(AVRCP_1_6_STRING))) { + if (!strncmp(AVRCP_1_6_STRING, avrcp_version, sizeof(AVRCP_1_6_STRING))) { profile_version = AVRC_REV_1_6; - } else if (!strncmp(AVRCP_1_5_STRING, avrcp_version, - sizeof(AVRCP_1_5_STRING))) { + } else if (!strncmp(AVRCP_1_5_STRING, avrcp_version, sizeof(AVRCP_1_5_STRING))) { profile_version = AVRC_REV_1_5; - } else if (!strncmp(AVRCP_1_3_STRING, avrcp_version, - sizeof(AVRCP_1_3_STRING))) { + } else if (!strncmp(AVRCP_1_3_STRING, avrcp_version, sizeof(AVRCP_1_3_STRING))) { profile_version = AVRC_REV_1_3; } else { profile_version = AVRC_REV_1_4; } if (btif_av_src_sink_coexist_enabled()) { bta_ar_reg_avrc_for_src_sink_coexist( - UUID_SERVCLASS_AV_REM_CTRL_TARGET, "AV Remote Control Target", - NULL, p_bta_av_cfg->avrc_tg_cat, - static_cast(BTA_ID_AV + local_role), - (bta_av_cb.features & BTA_AV_FEAT_BROWSE), profile_version); + UUID_SERVCLASS_AV_REM_CTRL_TARGET, "AV Remote Control Target", NULL, + p_bta_av_cfg->avrc_tg_cat, static_cast(BTA_ID_AV + local_role), + (bta_av_cb.features & BTA_AV_FEAT_BROWSE), profile_version); } else { - bta_ar_reg_avrc( - UUID_SERVCLASS_AV_REM_CTRL_TARGET, "AV Remote Control Target", - NULL, p_bta_av_cfg->avrc_tg_cat, - (bta_av_cb.features & BTA_AV_FEAT_BROWSE), profile_version); + bta_ar_reg_avrc(UUID_SERVCLASS_AV_REM_CTRL_TARGET, "AV Remote Control Target", NULL, + p_bta_av_cfg->avrc_tg_cat, (bta_av_cb.features & BTA_AV_FEAT_BROWSE), + profile_version); } } } /* Set the Capturing service class bit */ - if (profile_initialized == UUID_SERVCLASS_AUDIO_SOURCE) + if (profile_initialized == UUID_SERVCLASS_AUDIO_SOURCE) { cod.service = BTM_COD_SERVICE_CAPTURING; - else if (profile_initialized == UUID_SERVCLASS_AUDIO_SINK) + } else if (profile_initialized == UUID_SERVCLASS_AUDIO_SINK) { cod.service = BTM_COD_SERVICE_RENDERING; + } utl_set_device_class(&cod, BTA_UTL_SET_COD_SERVICE_CLASS); } /* if 1st channel */ @@ -619,8 +598,9 @@ static void bta_av_api_register(tBTA_AV_DATA* p_data) { avdtp_stream_config.cfg.psc_mask |= AVDT_PSC_REPORT; avdtp_stream_config.p_report_cback = bta_av_a2dp_report_cback; } - if (bta_av_cb.features & BTA_AV_FEAT_DELAY_RPT) + if (bta_av_cb.features & BTA_AV_FEAT_DELAY_RPT) { avdtp_stream_config.cfg.psc_mask |= AVDT_PSC_DELAY_RPT; + } if (profile_initialized == UUID_SERVCLASS_AUDIO_SOURCE) { avdtp_stream_config.tsep = AVDT_TSEP_SRC; @@ -646,8 +626,7 @@ static void bta_av_api_register(tBTA_AV_DATA* p_data) { /* keep the configuration in the stream control block */ p_scb->cfg = avdtp_stream_config.cfg; for (int i = codec_index_min; i < codec_index_max; i++) { - btav_a2dp_codec_index_t codec_index = - static_cast(i); + btav_a2dp_codec_index_t codec_index = static_cast(i); if (!bta_av_co_is_supported_codec(codec_index)) { log::warn("Skipping the codec index for codec index {}", i); continue; @@ -657,18 +636,16 @@ static void bta_av_api_register(tBTA_AV_DATA* p_data) { } if (AVDT_CreateStream(p_scb->app_id, &p_scb->seps[codec_index].av_handle, avdtp_stream_config) != AVDT_SUCCESS) { - log::warn( - "bta_handle=0x{:x} (app_id {}) failed to alloc an SEP index:{}", - p_scb->hndl, p_scb->app_id, codec_index); + log::warn("bta_handle=0x{:x} (app_id {}) failed to alloc an SEP index:{}", p_scb->hndl, + p_scb->app_id, codec_index); continue; } /* Save a copy of the codec */ - memcpy(p_scb->seps[codec_index].codec_info, - avdtp_stream_config.cfg.codec_info, AVDT_CODEC_SIZE); + memcpy(p_scb->seps[codec_index].codec_info, avdtp_stream_config.cfg.codec_info, + AVDT_CODEC_SIZE); p_scb->seps[codec_index].tsep = avdtp_stream_config.tsep; if (avdtp_stream_config.tsep == AVDT_TSEP_SNK) { - p_scb->seps[codec_index].p_app_sink_data_cback = - p_data->api_reg.p_app_sink_data_cback; + p_scb->seps[codec_index].p_app_sink_data_cback = p_data->api_reg.p_app_sink_data_cback; } else { /* In case of A2DP SOURCE we don't need a callback to * handle media packets. @@ -676,28 +653,26 @@ static void bta_av_api_register(tBTA_AV_DATA* p_data) { p_scb->seps[codec_index].p_app_sink_data_cback = NULL; } } - if ((btif_av_src_sink_coexist_enabled() && - !(bta_av_cb.reg_role & (1 << local_role))) || + if ((btif_av_src_sink_coexist_enabled() && !(bta_av_cb.reg_role & (1 << local_role))) || (!btif_av_src_sink_coexist_enabled() && !bta_av_cb.reg_audio)) { bta_av_cb.sdp_a2dp_handle = 0; bta_av_cb.sdp_a2dp_snk_handle = 0; if (profile_initialized == UUID_SERVCLASS_AUDIO_SOURCE) { /* create the SDP records on the 1st audio channel */ - bta_av_cb.sdp_a2dp_handle = - get_legacy_stack_sdp_api()->handle.SDP_CreateRecord(); - A2DP_AddRecord(UUID_SERVCLASS_AUDIO_SOURCE, p_service_name, NULL, - A2DP_SUPF_PLAYER, bta_av_cb.sdp_a2dp_handle); + bta_av_cb.sdp_a2dp_handle = get_legacy_stack_sdp_api()->handle.SDP_CreateRecord(); + A2DP_AddRecord(UUID_SERVCLASS_AUDIO_SOURCE, p_service_name, NULL, A2DP_SUPF_PLAYER, + bta_av_cb.sdp_a2dp_handle); bta_sys_add_uuid(UUID_SERVCLASS_AUDIO_SOURCE); } else if (profile_initialized == UUID_SERVCLASS_AUDIO_SINK) { - bta_av_cb.sdp_a2dp_snk_handle = - get_legacy_stack_sdp_api()->handle.SDP_CreateRecord(); - A2DP_AddRecord(UUID_SERVCLASS_AUDIO_SINK, p_service_name, NULL, - A2DP_SUPF_PLAYER, bta_av_cb.sdp_a2dp_snk_handle); + bta_av_cb.sdp_a2dp_snk_handle = get_legacy_stack_sdp_api()->handle.SDP_CreateRecord(); + A2DP_AddRecord(UUID_SERVCLASS_AUDIO_SINK, p_service_name, NULL, A2DP_SUPF_PLAYER, + bta_av_cb.sdp_a2dp_snk_handle); bta_sys_add_uuid(UUID_SERVCLASS_AUDIO_SINK); } /* start listening when A2DP is registered */ - if (bta_av_cb.features & BTA_AV_FEAT_RCTG) + if (bta_av_cb.features & BTA_AV_FEAT_RCTG) { bta_av_rc_create(&bta_av_cb, AVCT_ACP, 0, BTA_AV_NUM_LINKS + 1); + } /* if the AV and AVK are both supported, it cannot support the CT role */ @@ -716,27 +691,22 @@ static void bta_av_api_register(tBTA_AV_DATA* p_data) { if (btif_av_src_sink_coexist_enabled()) { if (profile_initialized == UUID_SERVCLASS_AUDIO_SOURCE) { bta_ar_reg_avrc_for_src_sink_coexist( - UUID_SERVCLASS_AV_REMOTE_CONTROL, NULL, NULL, - p_bta_av_cfg->avrc_ct_cat, BTA_ID_AV, - (bta_av_cb.features & BTA_AV_FEAT_BROWSE), AVRC_REV_1_5); - } else if (profile_initialized == UUID_SERVCLASS_AUDIO_SINK) - bta_ar_reg_avrc_for_src_sink_coexist( - UUID_SERVCLASS_AV_REMOTE_CONTROL, NULL, NULL, - p_bta_av_cfg->avrc_ct_cat, BTA_ID_AVK, - (bta_av_cb.features & BTA_AV_FEAT_BROWSE), - AVRC_GetControlProfileVersion()); + UUID_SERVCLASS_AV_REMOTE_CONTROL, NULL, NULL, p_bta_av_cfg->avrc_ct_cat, + BTA_ID_AV, (bta_av_cb.features & BTA_AV_FEAT_BROWSE), AVRC_REV_1_5); + } else if (profile_initialized == UUID_SERVCLASS_AUDIO_SINK) { + bta_ar_reg_avrc_for_src_sink_coexist(UUID_SERVCLASS_AV_REMOTE_CONTROL, NULL, NULL, + p_bta_av_cfg->avrc_ct_cat, BTA_ID_AVK, + (bta_av_cb.features & BTA_AV_FEAT_BROWSE), + AVRC_GetControlProfileVersion()); + } } else { - if (profile_initialized == UUID_SERVCLASS_AUDIO_SOURCE && - !is_new_avrcp_enabled()) { - bta_ar_reg_avrc(UUID_SERVCLASS_AV_REMOTE_CONTROL, NULL, NULL, - p_bta_av_cfg->avrc_ct_cat, - (bta_av_cb.features & BTA_AV_FEAT_BROWSE), - AVRC_REV_1_3); - } else if (profile_initialized == UUID_SERVCLASS_AUDIO_SINK) - bta_ar_reg_avrc(UUID_SERVCLASS_AV_REMOTE_CONTROL, NULL, NULL, - p_bta_av_cfg->avrc_ct_cat, - (bta_av_cb.features & BTA_AV_FEAT_BROWSE), - AVRC_REV_1_6); + if (profile_initialized == UUID_SERVCLASS_AUDIO_SOURCE && !is_new_avrcp_enabled()) { + bta_ar_reg_avrc(UUID_SERVCLASS_AV_REMOTE_CONTROL, NULL, NULL, p_bta_av_cfg->avrc_ct_cat, + (bta_av_cb.features & BTA_AV_FEAT_BROWSE), AVRC_REV_1_3); + } else if (profile_initialized == UUID_SERVCLASS_AUDIO_SINK) { + bta_ar_reg_avrc(UUID_SERVCLASS_AV_REMOTE_CONTROL, NULL, NULL, p_bta_av_cfg->avrc_ct_cat, + (bta_av_cb.features & BTA_AV_FEAT_BROWSE), AVRC_REV_1_6); + } } } } @@ -746,9 +716,8 @@ static void bta_av_api_register(tBTA_AV_DATA* p_data) { if (btif_av_src_sink_coexist_enabled()) { bta_av_cb.reg_role |= (1 << local_role); - reg_data.peer_sep = (profile_initialized == UUID_SERVCLASS_AUDIO_SOURCE) - ? AVDT_TSEP_SNK - : AVDT_TSEP_SRC; + reg_data.peer_sep = + (profile_initialized == UUID_SERVCLASS_AUDIO_SOURCE) ? AVDT_TSEP_SNK : AVDT_TSEP_SRC; /* there are too much check depend on it's only source */ if ((profile_initialized == UUID_SERVCLASS_AUDIO_SINK) && @@ -837,8 +806,7 @@ static void bta_av_rpc_conn(tBTA_AV_DATA* /* p_data */) {} * ******************************************************************************/ static void bta_av_api_to_ssm(tBTA_AV_DATA* p_data) { - uint16_t event = - p_data->hdr.event - BTA_AV_FIRST_A2S_API_EVT + BTA_AV_FIRST_A2S_SSM_EVT; + uint16_t event = p_data->hdr.event - BTA_AV_FIRST_A2S_API_EVT + BTA_AV_FIRST_A2S_SSM_EVT; tBTA_AV_HNDL handle = p_data->hdr.layer_specific; tBTA_AV_SCB* p_scb = bta_av_hndl_to_scb(handle); @@ -861,7 +829,7 @@ bool bta_av_chk_start(tBTA_AV_SCB* p_scb) { bool start = false; if ((p_scb->chnl == BTA_AV_CHNL_AUDIO) && (bta_av_cb.audio_open_cnt >= 2) && - (((p_scb->role & BTA_AV_ROLE_AD_ACP) == 0) || // Outgoing connection or + (((p_scb->role & BTA_AV_ROLE_AD_ACP) == 0) || // Outgoing connection or (bta_av_cb.features & BTA_AV_FEAT_ACP_START))) { // Auto-starting option // More than one audio channel is connected. // If this is the 2nd stream as ACP, give INT a chance to issue the START @@ -878,11 +846,9 @@ bool bta_av_chk_start(tBTA_AV_SCB* p_scb) { } } - log::info( - "peer {} channel:{} bta_av_cb.audio_open_cnt:{} role:0x{:x} " - "features:0x{:x} start:{}", - p_scb->PeerAddress(), p_scb->chnl, bta_av_cb.audio_open_cnt, p_scb->role, - bta_av_cb.features, start); + log::info("peer {} channel:{} bta_av_cb.audio_open_cnt:{} role:0x{:x} features:0x{:x} start:{}", + p_scb->PeerAddress(), p_scb->chnl, bta_av_cb.audio_open_cnt, p_scb->role, + bta_av_cb.features, start); return start; } @@ -922,16 +888,15 @@ void bta_av_restore_switch(void) { * Returns (BTA_SYS_ROLE_CHANGE, new_role, hci_status, p_bda) * ******************************************************************************/ -static void bta_av_sys_rs_cback(tBTA_SYS_CONN_STATUS /* status */, - tHCI_ROLE new_role, tHCI_STATUS hci_status, - const RawAddress& peer_addr) { +static void bta_av_sys_rs_cback(tBTA_SYS_CONN_STATUS /* status */, tHCI_ROLE new_role, + tHCI_STATUS hci_status, const RawAddress& peer_addr) { int i; tBTA_AV_SCB* p_scb = NULL; tHCI_ROLE cur_role; uint8_t peer_idx = 0; - log::verbose("peer {} new_role:{} hci_status:0x{:x} bta_av_cb.rs_idx:{}", - peer_addr, new_role, hci_status, bta_av_cb.rs_idx); + log::verbose("peer {} new_role:{} hci_status:0x{:x} bta_av_cb.rs_idx:{}", peer_addr, new_role, + hci_status, bta_av_cb.rs_idx); for (i = 0; i < BTA_AV_NUM_STRS; i++) { /* loop through all the SCBs to find matching peer addresses and report the @@ -939,11 +904,9 @@ static void bta_av_sys_rs_cback(tBTA_SYS_CONN_STATUS /* status */, /* note that more than one SCB (a2dp & vdp) maybe waiting for this event */ p_scb = bta_av_cb.p_scb[i]; if (p_scb && p_scb->PeerAddress() == peer_addr) { - tBTA_AV_ROLE_RES* p_buf = - (tBTA_AV_ROLE_RES*)osi_malloc(sizeof(tBTA_AV_ROLE_RES)); - log::verbose( - "peer {} found: new_role:{}, hci_status:0x{:x} bta_handle:0x{:x}", - peer_addr, new_role, hci_status, p_scb->hndl); + tBTA_AV_ROLE_RES* p_buf = (tBTA_AV_ROLE_RES*)osi_malloc(sizeof(tBTA_AV_ROLE_RES)); + log::verbose("peer {} found: new_role:{}, hci_status:0x{:x} bta_handle:0x{:x}", peer_addr, + new_role, hci_status, p_scb->hndl); p_buf->hdr.event = BTA_AV_ROLE_CHANGE_EVT; p_buf->hdr.layer_specific = p_scb->hndl; p_buf->new_role = new_role; @@ -955,8 +918,7 @@ static void bta_av_sys_rs_cback(tBTA_SYS_CONN_STATUS /* status */, } /* restore role switch policy, if role switch failed */ - if ((HCI_SUCCESS != hci_status) && - (BTM_GetRole(peer_addr, &cur_role) == BTM_SUCCESS) && + if ((HCI_SUCCESS != hci_status) && (BTM_GetRole(peer_addr, &cur_role) == BTM_SUCCESS) && (cur_role == HCI_ROLE_PERIPHERAL)) { BTM_unblock_role_switch_for(peer_addr); } @@ -969,17 +931,14 @@ static void bta_av_sys_rs_cback(tBTA_SYS_CONN_STATUS /* status */, p_scb = bta_av_cb.p_scb[bta_av_cb.rs_idx - 1]; } if (p_scb && p_scb->q_tag == BTA_AV_Q_TAG_OPEN) { - log::verbose("peer {} rs_idx:{}, bta_handle:0x{:x} q_tag:{}", - p_scb->PeerAddress(), bta_av_cb.rs_idx, p_scb->hndl, - p_scb->q_tag); + log::verbose("peer {} rs_idx:{}, bta_handle:0x{:x} q_tag:{}", p_scb->PeerAddress(), + bta_av_cb.rs_idx, p_scb->hndl, p_scb->q_tag); if (HCI_SUCCESS == hci_status || HCI_ERR_NO_CONNECTION == hci_status) { p_scb->q_info.open.switch_res = BTA_AV_RS_OK; } else { - log::error( - "peer {} (p_scb peer {}) role switch failed: new_role:{} " - "hci_status:0x{:x}", - peer_addr, p_scb->PeerAddress(), new_role, hci_status); + log::error("peer {} (p_scb peer {}) role switch failed: new_role:{} hci_status:0x{:x}", + peer_addr, p_scb->PeerAddress(), new_role, hci_status); p_scb->q_info.open.switch_res = BTA_AV_RS_FAIL; } @@ -1002,19 +961,16 @@ static void bta_av_sys_rs_cback(tBTA_SYS_CONN_STATUS /* status */, * Returns void * ******************************************************************************/ -static void bta_av_sco_chg_cback(tBTA_SYS_CONN_STATUS status, - uint8_t num_sco_links, uint8_t /* app_id */, - const RawAddress& peer_addr) { +static void bta_av_sco_chg_cback(tBTA_SYS_CONN_STATUS status, uint8_t num_sco_links, + uint8_t /* app_id */, const RawAddress& peer_addr) { tBTA_AV_SCB* p_scb; int i; tBTA_AV_API_STOP stop; - log::info("status={}, num_links={}", bta_sys_conn_status_text(status), - num_sco_links); + log::info("status={}, num_links={}", bta_sys_conn_status_text(status), num_sco_links); if (num_sco_links) { bta_av_cb.sco_occupied = true; - log::debug("SCO occupied peer:{} status:{}", peer_addr, - bta_sys_conn_status_text(status)); + log::debug("SCO occupied peer:{} status:{}", peer_addr, bta_sys_conn_status_text(status)); if (bta_av_cb.features & BTA_AV_FEAT_NO_SCO_SSPD) { return; @@ -1036,8 +992,7 @@ static void bta_av_sco_chg_cback(tBTA_SYS_CONN_STATUS status, } } else { bta_av_cb.sco_occupied = false; - log::debug("SCO unoccupied peer:{} status:{}", peer_addr, - bta_sys_conn_status_text(status)); + log::debug("SCO unoccupied peer:{} status:{}", peer_addr, bta_sys_conn_status_text(status)); if (bta_av_cb.features & BTA_AV_FEAT_NO_SCO_SSPD) { return; @@ -1127,10 +1082,10 @@ bool bta_av_link_role_ok(tBTA_AV_SCB* p_scb, uint8_t bits) { if (role != HCI_ROLE_CENTRAL && (A2DP_BitsSet(bta_av_cb.conn_audio) > bits)) { log::info( - "Switch link role to central peer:{} bta_handle:0x{:x} current_role:{} " - "conn_audio:0x{:x} bits:{} features:0x{:x}", - p_scb->PeerAddress(), p_scb->hndl, RoleText(role), bta_av_cb.conn_audio, - bits, bta_av_cb.features); + "Switch link role to central peer:{} bta_handle:0x{:x} current_role:{} " + "conn_audio:0x{:x} bits:{} features:0x{:x}", + p_scb->PeerAddress(), p_scb->hndl, RoleText(role), bta_av_cb.conn_audio, bits, + bta_av_cb.features); const tBTM_STATUS status = BTM_SwitchRoleToCentral(p_scb->PeerAddress()); switch (status) { case BTM_CMD_STARTED: @@ -1140,14 +1095,13 @@ bool bta_av_link_role_ok(tBTA_AV_SCB* p_scb, uint8_t bits) { // Role switch can never happen, but indicate to caller // a result such that a timer will not start to repeatedly // try something not possible. - log::error("Link can never role switch to central device:{}", - p_scb->PeerAddress()); + log::error("Link can never role switch to central device:{}", p_scb->PeerAddress()); break; default: /* can not switch role on SCB - start the timer on SCB */ p_scb->wait |= BTA_AV_WAIT_ROLE_SW_RES_START; - log::error("Unable to switch role to central device:{} error:{}", - p_scb->PeerAddress(), btm_status_text(status)); + log::error("Unable to switch role to central device:{} error:{}", p_scb->PeerAddress(), + btm_status_text(status)); return false; } } @@ -1166,17 +1120,23 @@ bool bta_av_link_role_ok(tBTA_AV_SCB* p_scb, uint8_t bits) { ******************************************************************************/ void bta_av_dup_audio_buf(tBTA_AV_SCB* p_scb, BT_HDR* p_buf) { /* Test whether there is more than one audio channel connected */ - if ((p_buf == NULL) || (bta_av_cb.audio_open_cnt < 2)) return; + if ((p_buf == NULL) || (bta_av_cb.audio_open_cnt < 2)) { + return; + } uint16_t copy_size = BT_HDR_SIZE + p_buf->len + p_buf->offset; for (int i = 0; i < BTA_AV_NUM_STRS; i++) { tBTA_AV_SCB* p_scbi = bta_av_cb.p_scb[i]; - if (i == p_scb->hdi) continue; /* Ignore the original channel */ - if ((p_scbi == NULL) || !p_scbi->co_started) + if (i == p_scb->hdi) { + continue; /* Ignore the original channel */ + } + if ((p_scbi == NULL) || !p_scbi->co_started) { continue; /* Ignore if SCB is not used or started */ - if (!(bta_av_cb.conn_audio & BTA_AV_HNDL_TO_MSK(i))) + } + if (!(bta_av_cb.conn_audio & BTA_AV_HNDL_TO_MSK(i))) { continue; /* Audio is not connected */ + } /* Enqueue the data */ BT_HDR* p_new = (BT_HDR*)osi_malloc(copy_size); @@ -1193,8 +1153,7 @@ void bta_av_dup_audio_buf(tBTA_AV_SCB* p_scb, BT_HDR* p_buf) { } } -static void bta_av_non_state_machine_event(uint16_t event, - tBTA_AV_DATA* p_data) { +static void bta_av_non_state_machine_event(uint16_t event, tBTA_AV_DATA* p_data) { switch (event) { case BTA_AV_API_ENABLE_EVT: bta_av_api_enable(p_data); @@ -1253,8 +1212,7 @@ static void bta_av_non_state_machine_event(uint16_t event, } } -static void bta_av_better_state_machine(tBTA_AV_CB* p_cb, uint16_t event, - tBTA_AV_DATA* p_data) { +static void bta_av_better_state_machine(tBTA_AV_CB* p_cb, uint16_t event, tBTA_AV_DATA* p_data) { switch (p_cb->state) { case BTA_AV_INIT_ST: switch (event) { @@ -1309,8 +1267,7 @@ static void bta_av_better_state_machine(tBTA_AV_CB* p_cb, uint16_t event, } void bta_av_sm_execute(tBTA_AV_CB* p_cb, uint16_t event, tBTA_AV_DATA* p_data) { - log::verbose("AV event=0x{:x}({}) state={}({})", event, - bta_av_evt_code(event), p_cb->state, + log::verbose("AV event=0x{:x}({}) state={}({})", event, bta_av_evt_code(event), p_cb->state, bta_av_st_code(p_cb->state)); bta_av_better_state_machine(p_cb, event, p_data); } @@ -1330,13 +1287,10 @@ bool bta_av_hdl_event(const BT_HDR_RIGID* p_msg) { return true; /* to free p_msg */ } if (p_msg->event >= BTA_AV_FIRST_NSM_EVT) { - log::verbose("AV nsm event=0x{:x}({})", p_msg->event, - bta_av_evt_code(p_msg->event)); + log::verbose("AV nsm event=0x{:x}({})", p_msg->event, bta_av_evt_code(p_msg->event)); bta_av_non_state_machine_event(p_msg->event, (tBTA_AV_DATA*)p_msg); - } else if (p_msg->event >= BTA_AV_FIRST_SM_EVT && - p_msg->event <= BTA_AV_LAST_SM_EVT) { - log::verbose("AV sm event=0x{:x}({})", p_msg->event, - bta_av_evt_code(p_msg->event)); + } else if (p_msg->event >= BTA_AV_FIRST_SM_EVT && p_msg->event <= BTA_AV_LAST_SM_EVT) { + log::verbose("AV sm event=0x{:x}({})", p_msg->event, bta_av_evt_code(p_msg->event)); /* state machine events */ bta_av_sm_execute(&bta_av_cb, p_msg->event, (tBTA_AV_DATA*)p_msg); } else { @@ -1518,24 +1472,20 @@ void bta_debug_av_dump(int fd) { dprintf(fd, " Features: 0x%x\n", bta_av_cb.features); dprintf(fd, " SDP handle: %d\n", bta_av_cb.handle); dprintf(fd, " Disabling: %s\n", bta_av_cb.disabling ? "true" : "false"); - dprintf(fd, " SCO occupied: %s\n", - bta_av_cb.sco_occupied ? "true" : "false"); + dprintf(fd, " SCO occupied: %s\n", bta_av_cb.sco_occupied ? "true" : "false"); dprintf(fd, " Connected audio channels: %d\n", bta_av_cb.audio_open_cnt); dprintf(fd, " Connected audio channels mask: 0x%x\n", bta_av_cb.conn_audio); dprintf(fd, " Registered audio channels mask: 0x%x\n", bta_av_cb.reg_audio); dprintf(fd, " Connected LCBs mask: 0x%x\n", bta_av_cb.conn_lcb); - dprintf(fd, " Offload start pending handle: %d\n", - bta_av_cb.offload_start_pending_hndl); + dprintf(fd, " Offload start pending handle: %d\n", bta_av_cb.offload_start_pending_hndl); dprintf(fd, " Offload started handle: %d\n", bta_av_cb.offload_started_hndl); - for (size_t i = 0; i < sizeof(bta_av_cb.lcb) / sizeof(bta_av_cb.lcb[0]); - i++) { + for (size_t i = 0; i < sizeof(bta_av_cb.lcb) / sizeof(bta_av_cb.lcb[0]); i++) { const tBTA_AV_LCB& lcb = bta_av_cb.lcb[i]; if (lcb.addr.IsEmpty()) { continue; } - dprintf(fd, "\n Link control block: %zu peer: %s\n", i, - ADDRESS_TO_LOGGABLE_CSTR(lcb.addr)); + dprintf(fd, "\n Link control block: %zu peer: %s\n", i, ADDRESS_TO_LOGGABLE_CSTR(lcb.addr)); dprintf(fd, " Connected stream handle mask: 0x%x\n", lcb.conn_msk); dprintf(fd, " Index(+1) to LCB: %d\n", lcb.lidx); } @@ -1547,10 +1497,8 @@ void bta_debug_av_dump(int fd) { if (p_scb->PeerAddress().IsEmpty()) { continue; } - dprintf(fd, "\n BTA ID: %zu peer: %s\n", i, - ADDRESS_TO_LOGGABLE_CSTR(p_scb->PeerAddress())); - dprintf(fd, " SDP discovery started: %s\n", - p_scb->sdp_discovery_started ? "true" : "false"); + dprintf(fd, "\n BTA ID: %zu peer: %s\n", i, ADDRESS_TO_LOGGABLE_CSTR(p_scb->PeerAddress())); + dprintf(fd, " SDP discovery started: %s\n", p_scb->sdp_discovery_started ? "true" : "false"); for (size_t j = 0; j < BTAV_A2DP_CODEC_INDEX_MAX; j++) { const tBTA_AV_SEP& sep = p_scb->seps[j]; if (sep.av_handle == 0) { @@ -1562,25 +1510,18 @@ void bta_debug_av_dump(int fd) { dprintf(fd, " Codec: %s\n", A2DP_CodecName(sep.codec_info)); } dprintf(fd, " BTA info tag: %d\n", p_scb->q_tag); - dprintf(fd, " API Open peer: %s\n", - ADDRESS_TO_LOGGABLE_CSTR(p_scb->q_info.open.bd_addr)); - dprintf(fd, " Use AVRCP: %s\n", - p_scb->q_info.open.use_rc ? "true" : "false"); + dprintf(fd, " API Open peer: %s\n", ADDRESS_TO_LOGGABLE_CSTR(p_scb->q_info.open.bd_addr)); + dprintf(fd, " Use AVRCP: %s\n", p_scb->q_info.open.use_rc ? "true" : "false"); dprintf(fd, " Switch result: %d\n", p_scb->q_info.open.switch_res); dprintf(fd, " Initiator UUID: 0x%x\n", p_scb->q_info.open.uuid); - dprintf(fd, " Saved API Open peer: %s\n", - ADDRESS_TO_LOGGABLE_CSTR(p_scb->open_api.bd_addr)); - dprintf(fd, " Use AVRCP: %s\n", - p_scb->open_api.use_rc ? "true" : "false"); + dprintf(fd, " Saved API Open peer: %s\n", ADDRESS_TO_LOGGABLE_CSTR(p_scb->open_api.bd_addr)); + dprintf(fd, " Use AVRCP: %s\n", p_scb->open_api.use_rc ? "true" : "false"); dprintf(fd, " Switch result: %d\n", p_scb->open_api.switch_res); dprintf(fd, " Initiator UUID: 0x%x\n", p_scb->open_api.uuid); dprintf(fd, " Link signalling timer: %s\n", - alarm_is_scheduled(p_scb->link_signalling_timer) ? "Scheduled" - : "Not scheduled"); + alarm_is_scheduled(p_scb->link_signalling_timer) ? "Scheduled" : "Not scheduled"); dprintf(fd, " Accept signalling timer: %s\n", - alarm_is_scheduled(p_scb->accept_signalling_timer) - ? "Scheduled" - : "Not scheduled"); + alarm_is_scheduled(p_scb->accept_signalling_timer) ? "Scheduled" : "Not scheduled"); // TODO: Print p_scb->sep_info[], cfg, avrc_ct_timer, current_codec ? dprintf(fd, " L2CAP Channel ID: %d\n", p_scb->l2c_cid); dprintf(fd, " Stream MTU: %d\n", p_scb->stream_mtu); @@ -1590,12 +1531,10 @@ void bta_debug_av_dump(int fd) { dprintf(fd, " Open status: %d\n", p_scb->open_status); dprintf(fd, " Channel: %d\n", p_scb->chnl); dprintf(fd, " BTA handle: 0x%x\n", p_scb->hndl); - dprintf(fd, " Protocol service capabilities mask: 0x%x\n", - p_scb->cur_psc_mask); + dprintf(fd, " Protocol service capabilities mask: 0x%x\n", p_scb->cur_psc_mask); dprintf(fd, " AVDTP handle: %d\n", p_scb->avdt_handle); dprintf(fd, " Stream control block index: %d\n", p_scb->hdi); - dprintf(fd, " State machine state: %s(%d)\n", - bta_av_sst_code(p_scb->state), p_scb->state); + dprintf(fd, " State machine state: %s(%d)\n", bta_av_sst_code(p_scb->state), p_scb->state); dprintf(fd, " AVDTP label: 0x%x\n", p_scb->avdt_label); dprintf(fd, " Application ID: %d\n", p_scb->app_id); dprintf(fd, " Role: 0x%x\n", p_scb->role); @@ -1603,20 +1542,13 @@ void bta_debug_av_dump(int fd) { dprintf(fd, " AVRCP allowed: %s\n", p_scb->use_rc ? "true" : "false"); dprintf(fd, " Stream started: %s\n", p_scb->started ? "true" : "false"); dprintf(fd, " Stream call-out started: %d\n", p_scb->co_started); - dprintf(fd, " AVDTP Reconfig supported: %s\n", - p_scb->recfg_sup ? "true" : "false"); - dprintf(fd, " AVDTP Suspend supported: %s\n", - p_scb->suspend_sup ? "true" : "false"); - dprintf(fd, " Deregistering: %s\n", - p_scb->deregistering ? "true" : "false"); - dprintf(fd, " SCO automatic Suspend: %s\n", - p_scb->sco_suspend ? "true" : "false"); - dprintf(fd, " Incoming/outgoing connection collusion mask: 0x%x\n", - p_scb->coll_mask); + dprintf(fd, " AVDTP Reconfig supported: %s\n", p_scb->recfg_sup ? "true" : "false"); + dprintf(fd, " AVDTP Suspend supported: %s\n", p_scb->suspend_sup ? "true" : "false"); + dprintf(fd, " Deregistering: %s\n", p_scb->deregistering ? "true" : "false"); + dprintf(fd, " SCO automatic Suspend: %s\n", p_scb->sco_suspend ? "true" : "false"); + dprintf(fd, " Incoming/outgoing connection collusion mask: 0x%x\n", p_scb->coll_mask); dprintf(fd, " Wait mask: 0x%x\n", p_scb->wait); - dprintf(fd, " Don't use RTP header: %s\n", - p_scb->no_rtp_header ? "true" : "false"); - dprintf(fd, " Intended UUID of Initiator to connect to: 0x%x\n", - p_scb->uuid_int); + dprintf(fd, " Don't use RTP header: %s\n", p_scb->no_rtp_header ? "true" : "false"); + dprintf(fd, " Intended UUID of Initiator to connect to: 0x%x\n", p_scb->uuid_int); } } diff --git a/system/bta/av/bta_av_ssm.cc b/system/bta/av/bta_av_ssm.cc index 7f9d8bb499c..56c03a00cc5 100644 --- a/system/bta/av/bta_av_ssm.cc +++ b/system/bta/av/bta_av_ssm.cc @@ -46,8 +46,7 @@ enum { BTA_AV_CLOSING_SST }; -static void bta_av_better_stream_state_machine(tBTA_AV_SCB* p_scb, - uint16_t event, +static void bta_av_better_stream_state_machine(tBTA_AV_SCB* p_scb, uint16_t event, tBTA_AV_DATA* p_data) { uint8_t previous_state = p_scb->state; tBTA_AV_ACT event_handler1 = nullptr; @@ -422,16 +421,14 @@ static void bta_av_better_stream_state_machine(tBTA_AV_SCB* p_scb, } if (previous_state != p_scb->state) { - log::info( - "peer {} p_scb={:#x}({}) AV event=0x{:x}({}) state={}({}) -> {}({})", - p_scb->PeerAddress(), p_scb->hndl, fmt::ptr(p_scb), event, - bta_av_evt_code(event), previous_state, bta_av_sst_code(previous_state), - p_scb->state, bta_av_sst_code(p_scb->state)); + log::info("peer {} p_scb={:#x}({}) AV event=0x{:x}({}) state={}({}) -> {}({})", + p_scb->PeerAddress(), p_scb->hndl, fmt::ptr(p_scb), event, bta_av_evt_code(event), + previous_state, bta_av_sst_code(previous_state), p_scb->state, + bta_av_sst_code(p_scb->state)); } else { - log::verbose("peer {} p_scb={:#x}({}) AV event=0x{:x}({}) state={}({})", - p_scb->PeerAddress(), p_scb->hndl, fmt::ptr(p_scb), event, - bta_av_evt_code(event), p_scb->state, + log::verbose("peer {} p_scb={:#x}({}) AV event=0x{:x}({}) state={}({})", p_scb->PeerAddress(), + p_scb->hndl, fmt::ptr(p_scb), event, bta_av_evt_code(event), p_scb->state, bta_av_sst_code(p_scb->state)); } @@ -453,8 +450,7 @@ static void bta_av_better_stream_state_machine(tBTA_AV_SCB* p_scb, * Returns void * ******************************************************************************/ -void bta_av_ssm_execute(tBTA_AV_SCB* p_scb, uint16_t event, - tBTA_AV_DATA* p_data) { +void bta_av_ssm_execute(tBTA_AV_SCB* p_scb, uint16_t event, tBTA_AV_DATA* p_data) { if (p_scb == NULL) { /* this stream is not registered */ log::verbose("AV channel not registered"); @@ -478,7 +474,9 @@ bool bta_av_is_scb_opening(tBTA_AV_SCB* p_scb) { bool is_opening = false; if (p_scb) { - if (p_scb->state == BTA_AV_OPENING_SST) is_opening = true; + if (p_scb->state == BTA_AV_OPENING_SST) { + is_opening = true; + } } return is_opening; @@ -498,7 +496,9 @@ bool bta_av_is_scb_incoming(tBTA_AV_SCB* p_scb) { bool is_incoming = false; if (p_scb) { - if (p_scb->state == BTA_AV_INCOMING_SST) is_incoming = true; + if (p_scb->state == BTA_AV_INCOMING_SST) { + is_incoming = true; + } } return is_incoming; @@ -521,11 +521,9 @@ void bta_av_set_scb_sst_init(tBTA_AV_SCB* p_scb) { uint8_t next_state = BTA_AV_INIT_SST; - log::verbose( - "peer {} AV (hndl=0x{:x}) state={}({}) next state={}({}) p_scb={}", - p_scb->PeerAddress(), p_scb->hndl, p_scb->state, - bta_av_sst_code(p_scb->state), next_state, bta_av_sst_code(next_state), - fmt::ptr(p_scb)); + log::verbose("peer {} AV (hndl=0x{:x}) state={}({}) next state={}({}) p_scb={}", + p_scb->PeerAddress(), p_scb->hndl, p_scb->state, bta_av_sst_code(p_scb->state), + next_state, bta_av_sst_code(next_state), fmt::ptr(p_scb)); p_scb->state = next_state; } diff --git a/system/bta/csis/csis_client.cc b/system/bta/csis/csis_client.cc index 60c9463d541..1b197c6dae9 100644 --- a/system/bta/csis/csis_client.cc +++ b/system/bta/csis/csis_client.cc @@ -110,41 +110,40 @@ DeviceGroupsCallbacks* device_group_callbacks; class CsisClientImpl : public CsisClient { static constexpr uint8_t CSIS_STORAGE_CURRENT_LAYOUT_MAGIC = 0x10; static constexpr size_t CSIS_STORAGE_HEADER_SZ = - sizeof(CSIS_STORAGE_CURRENT_LAYOUT_MAGIC) + - sizeof(uint8_t); /* num_of_sets */ - static constexpr size_t CSIS_STORAGE_ENTRY_SZ = - sizeof(uint8_t) /* set_id */ + sizeof(uint8_t) /* desired_size */ + - sizeof(uint8_t) /* rank */ + Octet16().size(); - - public: - CsisClientImpl(bluetooth::csis::CsisClientCallbacks* callbacks, - Closure initCb) + sizeof(CSIS_STORAGE_CURRENT_LAYOUT_MAGIC) + sizeof(uint8_t); /* num_of_sets */ + static constexpr size_t CSIS_STORAGE_ENTRY_SZ = sizeof(uint8_t) /* set_id */ + + sizeof(uint8_t) /* desired_size */ + + sizeof(uint8_t) /* rank */ + Octet16().size(); + +public: + CsisClientImpl(bluetooth::csis::CsisClientCallbacks* callbacks, Closure initCb) : gatt_if_(0), callbacks_(callbacks) { BTA_GATTC_AppRegister( - [](tBTA_GATTC_EVT event, tBTA_GATTC* p_data) { - if (instance && p_data) instance->GattcCallback(event, p_data); - }, - base::Bind( - [](Closure initCb, uint8_t client_id, uint8_t status) { - if (status != GATT_SUCCESS) { - log::error( - "Can't start Coordinated Set Service client profile - no " - "gatt clients left!"); - return; + [](tBTA_GATTC_EVT event, tBTA_GATTC* p_data) { + if (instance && p_data) { + instance->GattcCallback(event, p_data); } - instance->gatt_if_ = client_id; - initCb.Run(); - - DeviceGroups::Initialize(device_group_callbacks); - instance->dev_groups_ = DeviceGroups::Get(); }, - initCb), - true); + base::Bind( + [](Closure initCb, uint8_t client_id, uint8_t status) { + if (status != GATT_SUCCESS) { + log::error( + "Can't start Coordinated Set Service client profile - no " + "gatt clients left!"); + return; + } + instance->gatt_if_ = client_id; + initCb.Run(); + + DeviceGroups::Initialize(device_group_callbacks); + instance->dev_groups_ = DeviceGroups::Get(); + }, + initCb), + true); BTA_DmSirkSecCbRegister([](tBTA_DM_SEC_EVT event, tBTA_DM_SEC* p_data) { if (event != BTA_DM_SIRK_VERIFICATION_REQ_EVT) { - log::error("Invalid event received by CSIP: {}", - static_cast(event)); + log::error("Invalid event received by CSIP: {}", static_cast(event)); return; } @@ -157,9 +156,10 @@ class CsisClientImpl : public CsisClient { ~CsisClientImpl() override = default; - std::shared_ptr AssignCsisGroup( - const RawAddress& address, int group_id, - bool create_group_if_non_existing, const bluetooth::Uuid& uuid) { + std::shared_ptr AssignCsisGroup(const RawAddress& address, + int group_id, + bool create_group_if_non_existing, + const bluetooth::Uuid& uuid) { log::debug("Device: {}, group_id: {}", address, group_id); auto csis_group = FindCsisGroup(group_id); if (!csis_group) { @@ -182,15 +182,15 @@ class CsisClientImpl : public CsisClient { device = FindDeviceByAddress(address); } - if (!csis_group->IsDeviceInTheGroup(device)) csis_group->AddDevice(device); + if (!csis_group->IsDeviceInTheGroup(device)) { + csis_group->AddDevice(device); + } return csis_group; } - void OnGroupAddedCb(const RawAddress& address, const bluetooth::Uuid& uuid, - int group_id) { - log::debug("address: {}, uuid: {}, group_id: {}", address, uuid.ToString(), - group_id); + void OnGroupAddedCb(const RawAddress& address, const bluetooth::Uuid& uuid, int group_id) { + log::debug("address: {}, uuid: {}, group_id: {}", address, uuid.ToString(), group_id); AssignCsisGroup(address, group_id, true, uuid); } @@ -201,21 +201,23 @@ class CsisClientImpl : public CsisClient { AssignCsisGroup(address, group_id, false, Uuid::kEmpty); } - void OnGroupRemovedCb(const bluetooth::Uuid& uuid, int group_id) { - RemoveCsisGroup(group_id); - } + void OnGroupRemovedCb(const bluetooth::Uuid& uuid, int group_id) { RemoveCsisGroup(group_id); } void OnGroupMemberRemovedCb(const RawAddress& address, int group_id) { log::debug("{}, group_id: {}", address, group_id); auto device = FindDeviceByAddress(address); - if (device) RemoveCsisDevice(device, group_id); + if (device) { + RemoveCsisDevice(device, group_id); + } } - void OnGroupAddFromStorageCb(const RawAddress& address, - const bluetooth::Uuid& uuid, int group_id) { + void OnGroupAddFromStorageCb(const RawAddress& address, const bluetooth::Uuid& uuid, + int group_id) { auto device = FindDeviceByAddress(address); - if (device == nullptr) return; + if (device == nullptr) { + return; + } auto csis_group = FindCsisGroup(group_id); if (csis_group == nullptr) { @@ -224,8 +226,7 @@ class CsisClientImpl : public CsisClient { } if (!csis_group->IsDeviceInTheGroup(device)) { - log::error("the csis group (id: {} ) does contain the device: {}", - group_id, address); + log::error("the csis group (id: {} ) does contain the device: {}", group_id, address); return; } @@ -300,20 +301,22 @@ class CsisClientImpl : public CsisClient { int GetGroupId(const RawAddress& addr, Uuid uuid) override { auto device = FindDeviceByAddress(addr); - if (device == nullptr) return bluetooth::groups::kGroupUnknown; + if (device == nullptr) { + return bluetooth::groups::kGroupUnknown; + } int group_id = dev_groups_->GetGroupId(addr, uuid); auto csis_group = FindCsisGroup(group_id); - if (csis_group == nullptr) return bluetooth::groups::kGroupUnknown; + if (csis_group == nullptr) { + return bluetooth::groups::kGroupUnknown; + } return csis_group->GetGroupId(); } void HandleCsisLockProcedureError( - std::shared_ptr& csis_group, - std::shared_ptr& csis_device, - CsisGroupLockStatus status = - CsisGroupLockStatus::FAILED_LOCKED_BY_OTHER) { + std::shared_ptr& csis_group, std::shared_ptr& csis_device, + CsisGroupLockStatus status = CsisGroupLockStatus::FAILED_LOCKED_BY_OTHER) { /* Clear information about ongoing lock procedure */ CsisLockCb cb = csis_group->GetLockCb(); csis_group->SetTargetLockState(CsisLockState::CSIS_STATE_UNSET); @@ -324,10 +327,8 @@ class CsisClientImpl : public CsisClient { while (prev_dev) { if (prev_dev->IsConnected()) { auto prev_csis_instance = prev_dev->GetCsisInstanceByGroupId(group_id); - log::assert_that(prev_csis_instance != nullptr, - "prev_csis_instance does not exist!"); - SetLock(prev_dev, prev_csis_instance, - CsisLockState::CSIS_STATE_UNLOCKED); + log::assert_that(prev_csis_instance != nullptr, "prev_csis_instance does not exist!"); + SetLock(prev_dev, prev_csis_instance, CsisLockState::CSIS_STATE_UNLOCKED); } prev_dev = csis_group->GetPrevDevice(prev_dev); } @@ -335,8 +336,7 @@ class CsisClientImpl : public CsisClient { NotifyGroupStatus(group_id, false, status, std::move(cb)); } - void OnGattCsisWriteLockRsp(uint16_t conn_id, tGATT_STATUS status, - uint16_t handle, void* data) { + void OnGattCsisWriteLockRsp(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, void* data) { auto device = FindDeviceByConnId(conn_id); if (device == nullptr) { log::error("Device not there for conn_id: 0x{:04x}", conn_id); @@ -352,12 +352,13 @@ class CsisClientImpl : public CsisClient { CsisLockState target_lock_state = csis_group->GetTargetLockState(); - log::debug("Device {}, target lock: {}, status: 0x{:02x}", device->addr, - (int)target_lock_state, (int)status); - if (target_lock_state == CsisLockState::CSIS_STATE_UNSET) return; + log::debug("Device {}, target lock: {}, status: 0x{:02x}", device->addr, (int)target_lock_state, + (int)status); + if (target_lock_state == CsisLockState::CSIS_STATE_UNSET) { + return; + } - if (status != GATT_SUCCESS && - status != bluetooth::csis::kCsisErrorCodeLockAlreadyGranted) { + if (status != GATT_SUCCESS && status != bluetooth::csis::kCsisErrorCodeLockAlreadyGranted) { if (target_lock_state == CsisLockState::CSIS_STATE_UNLOCKED) { /* When unlocking just drop the counter on error and that is it */ csis_group->UpdateLockTransitionCnt(-1); @@ -389,10 +390,9 @@ class CsisClientImpl : public CsisClient { if (csis_group->UpdateLockTransitionCnt(-1) == 0) { csis_group->SetCurrentLockState(csis_group->GetTargetLockState()); - CsisLockCompleted( - csis_group, - csis_group->GetCurrentLockState() == CsisLockState::CSIS_STATE_LOCKED, - CsisGroupLockStatus::SUCCESS); + CsisLockCompleted(csis_group, + csis_group->GetCurrentLockState() == CsisLockState::CSIS_STATE_LOCKED, + CsisGroupLockStatus::SUCCESS); return; } @@ -401,16 +401,16 @@ class CsisClientImpl : public CsisClient { do { next_dev = csis_group->GetNextDevice(device); - if (!next_dev) break; + if (!next_dev) { + break; + } } while (!next_dev->IsConnected()); if (next_dev) { auto next_csis_inst = next_dev->GetCsisInstanceByGroupId(group_id); - log::assert_that(csis_instance != nullptr, - "csis_instance does not exist!"); + log::assert_that(csis_instance != nullptr, "csis_instance does not exist!"); #if CSIP_UPPER_TESTER_FORCE_TO_SEND_LOCK == FALSE - if (next_csis_inst->GetLockState() == - CsisLockState::CSIS_STATE_LOCKED) { + if (next_csis_inst->GetLockState() == CsisLockState::CSIS_STATE_LOCKED) { /* Somebody else managed to lock it. * Unlock previous devices */ @@ -423,38 +423,39 @@ class CsisClientImpl : public CsisClient { } } - void SetLock(std::shared_ptr& device, - std::shared_ptr& csis_instance, + void SetLock(std::shared_ptr& device, std::shared_ptr& csis_instance, CsisLockState lock) { - std::vector value = { - (std::underlying_type::type)lock}; + std::vector value = {(std::underlying_type::type)lock}; - log::info("{}, rank: {}, conn_id: 0x{:04x}, handle: 0x{:04x}", - device->addr, csis_instance->GetRank(), device->conn_id, + log::info("{}, rank: {}, conn_id: 0x{:04x}, handle: 0x{:04x}", device->addr, + csis_instance->GetRank(), device->conn_id, csis_instance->svc_data.lock_handle.val_hdl); BtaGattQueue::WriteCharacteristic( - device->conn_id, csis_instance->svc_data.lock_handle.val_hdl, value, - GATT_WRITE, - [](uint16_t conn_id, tGATT_STATUS status, uint16_t handle, uint16_t len, - const uint8_t* value, void* data) { - if (instance) - instance->OnGattCsisWriteLockRsp(conn_id, status, handle, data); - }, - UINT_TO_PTR(csis_instance->GetGroupId())); - } - - void NotifyGroupStatus(int group_id, bool lock, CsisGroupLockStatus status, - CsisLockCb cb) { + device->conn_id, csis_instance->svc_data.lock_handle.val_hdl, value, GATT_WRITE, + [](uint16_t conn_id, tGATT_STATUS status, uint16_t handle, uint16_t len, + const uint8_t* value, void* data) { + if (instance) { + instance->OnGattCsisWriteLockRsp(conn_id, status, handle, data); + } + }, + UINT_TO_PTR(csis_instance->GetGroupId())); + } + + void NotifyGroupStatus(int group_id, bool lock, CsisGroupLockStatus status, CsisLockCb cb) { callbacks_->OnGroupLockChanged(group_id, lock, status); - if (cb) std::move(cb).Run(group_id, lock, status); + if (cb) { + std::move(cb).Run(group_id, lock, status); + } } std::vector GetDeviceList(int group_id) override { std::vector result; auto csis_group = FindCsisGroup(group_id); - if (!csis_group || csis_group->IsEmpty()) return result; + if (!csis_group || csis_group->IsEmpty()) { + return result; + } auto csis_device = csis_group->GetFirstDevice(); while (csis_device) { @@ -479,44 +480,37 @@ class CsisClientImpl : public CsisClient { auto csis_group = FindCsisGroup(group_id); if (csis_group == nullptr) { log::error("Group not found: {}", group_id); - NotifyGroupStatus(group_id, false, - CsisGroupLockStatus::FAILED_INVALID_GROUP, - std::move(cb)); + NotifyGroupStatus(group_id, false, CsisGroupLockStatus::FAILED_INVALID_GROUP, std::move(cb)); return; } if (csis_group->IsEmpty()) { - NotifyGroupStatus(group_id, false, - CsisGroupLockStatus::FAILED_GROUP_EMPTY, std::move(cb)); + NotifyGroupStatus(group_id, false, CsisGroupLockStatus::FAILED_GROUP_EMPTY, std::move(cb)); return; } if (csis_group->GetTargetLockState() != CsisLockState::CSIS_STATE_UNSET) { /* CSIS operation ongoing */ - log::debug( - "Lock operation ongoing: group id: {}, target state {}", group_id, - (csis_group->GetTargetLockState() == CsisLockState::CSIS_STATE_LOCKED - ? "lock" - : "unlock")); + log::debug("Lock operation ongoing: group id: {}, target state {}", group_id, + (csis_group->GetTargetLockState() == CsisLockState::CSIS_STATE_LOCKED ? "lock" + : "unlock")); return; } - CsisLockState new_lock_state = lock ? CsisLockState::CSIS_STATE_LOCKED - : CsisLockState::CSIS_STATE_UNLOCKED; + CsisLockState new_lock_state = + lock ? CsisLockState::CSIS_STATE_LOCKED : CsisLockState::CSIS_STATE_UNLOCKED; if (csis_group->GetCurrentLockState() == new_lock_state) { log::debug("Nothing to do as requested lock is there"); - NotifyGroupStatus(group_id, lock, CsisGroupLockStatus::SUCCESS, - std::move(cb)); + NotifyGroupStatus(group_id, lock, CsisGroupLockStatus::SUCCESS, std::move(cb)); return; } #if CSIP_UPPER_TESTER_FORCE_TO_SEND_LOCK == FALSE if (lock && !csis_group->IsAvailableForCsisLockOperation()) { log::debug("Group {} locked by other", group_id); - NotifyGroupStatus(group_id, false, - CsisGroupLockStatus::FAILED_LOCKED_BY_OTHER, + NotifyGroupStatus(group_id, false, CsisGroupLockStatus::FAILED_LOCKED_BY_OTHER, std::move(cb)); return; } @@ -535,8 +529,7 @@ class CsisClientImpl : public CsisClient { } auto csis_instance = csis_device->GetCsisInstanceByGroupId(group_id); - log::assert_that(csis_instance != nullptr, - "csis_instance does not exist!"); + log::assert_that(csis_instance != nullptr, "csis_instance does not exist!"); SetLock(csis_device, csis_instance, new_lock_state); } else { /* For unlocking, we don't have to monitor status of unlocking device, @@ -545,11 +538,9 @@ class CsisClientImpl : public CsisClient { */ auto csis_device = csis_group->GetLastDevice(); auto csis_instance = csis_device->GetCsisInstanceByGroupId(group_id); - log::assert_that(csis_instance != nullptr, - "csis_instance does not exist!"); + log::assert_that(csis_instance != nullptr, "csis_instance does not exist!"); while (csis_device) { - if ((csis_device->IsConnected()) && - ((csis_instance->GetLockState() != new_lock_state))) { + if ((csis_device->IsConnected()) && (csis_instance->GetLockState() != new_lock_state)) { csis_group->UpdateLockTransitionCnt(1); SetLock(csis_device, csis_instance, new_lock_state); } @@ -583,8 +574,9 @@ class CsisClientImpl : public CsisClient { log::debug(": device= {}", device->addr); auto num_sets = device->GetNumberOfCsisInstances(); - if ((num_sets == 0) || (num_sets > std::numeric_limits::max())) + if ((num_sets == 0) || (num_sets > std::numeric_limits::max())) { return false; + } out.resize(CSIS_STORAGE_HEADER_SZ + (num_sets * CSIS_STORAGE_ENTRY_SZ)); auto* ptr = out.data(); @@ -594,22 +586,21 @@ class CsisClientImpl : public CsisClient { UINT8_TO_STREAM(ptr, num_sets); /* set entries */ - device->ForEachCsisInstance( - [&](const std::shared_ptr& csis_inst) { - auto gid = csis_inst->GetGroupId(); - auto csis_group = FindCsisGroup(gid); - if (csis_group == nullptr) { - log::error("SerializeSets: No matching group found!"); - return; - } + device->ForEachCsisInstance([&](const std::shared_ptr& csis_inst) { + auto gid = csis_inst->GetGroupId(); + auto csis_group = FindCsisGroup(gid); + if (csis_group == nullptr) { + log::error("SerializeSets: No matching group found!"); + return; + } - UINT8_TO_STREAM(ptr, gid); - UINT8_TO_STREAM(ptr, csis_group->GetDesiredSize()); - UINT8_TO_STREAM(ptr, csis_inst->GetRank()); - Octet16 sirk = csis_group->GetSirk(); - memcpy(ptr, sirk.data(), sirk.size()); - ptr += sirk.size(); - }); + UINT8_TO_STREAM(ptr, gid); + UINT8_TO_STREAM(ptr, csis_group->GetDesiredSize()); + UINT8_TO_STREAM(ptr, csis_inst->GetRank()); + Octet16 sirk = csis_group->GetSirk(); + memcpy(ptr, sirk.data(), sirk.size()); + ptr += sirk.size(); + }); return true; } @@ -618,8 +609,9 @@ class CsisClientImpl : public CsisClient { const std::vector& in) { std::map group_rank_map; - if (in.size() < CSIS_STORAGE_HEADER_SZ + CSIS_STORAGE_ENTRY_SZ) + if (in.size() < CSIS_STORAGE_HEADER_SZ + CSIS_STORAGE_ENTRY_SZ) { return group_rank_map; + } auto* ptr = in.data(); uint8_t magic; @@ -629,8 +621,7 @@ class CsisClientImpl : public CsisClient { uint8_t num_sets; STREAM_TO_UINT8(num_sets, ptr); - if (in.size() < - CSIS_STORAGE_HEADER_SZ + (num_sets * CSIS_STORAGE_ENTRY_SZ)) { + if (in.size() < CSIS_STORAGE_HEADER_SZ + (num_sets * CSIS_STORAGE_ENTRY_SZ)) { log::error("Invalid persistent storage data"); return group_rank_map; } @@ -675,8 +666,7 @@ class CsisClientImpl : public CsisClient { void AddFromStorage(const RawAddress& addr, const std::vector& in) { auto group_rank_map = DeserializeSets(addr, in); - log::debug("{}, number of groups {}", addr, - static_cast(csis_groups_.size())); + log::debug("{}, number of groups {}", addr, static_cast(csis_groups_.size())); auto device = FindDeviceByAddress(addr); if (device == nullptr) { @@ -685,7 +675,9 @@ class CsisClientImpl : public CsisClient { } for (const auto& csis_group : csis_groups_) { - if (!csis_group->IsDeviceInTheGroup(device)) continue; + if (!csis_group->IsDeviceInTheGroup(device)) { + continue; + } if (csis_group->GetUuid() != Uuid::kEmpty) { auto group_id = csis_group->GetGroupId(); @@ -694,8 +686,7 @@ class CsisClientImpl : public CsisClient { rank = group_rank_map.at(group_id); } - callbacks_->OnDeviceAvailable(device->addr, group_id, - csis_group->GetDesiredSize(), rank, + callbacks_->OnDeviceAvailable(device->addr, group_id, csis_group->GetDesiredSize(), rank, csis_group->GetUuid()); } } @@ -709,7 +700,9 @@ class CsisClientImpl : public CsisClient { BTA_GATTC_AppDeregister(gatt_if_); for (auto& device : devices_) { - if (device->IsConnected()) BTA_GATTC_Close(device->conn_id); + if (device->IsConnected()) { + BTA_GATTC_Close(device->conn_id); + } DoDisconnectCleanUp(device); } @@ -729,41 +722,34 @@ class CsisClientImpl : public CsisClient { stream << " == id: " << g->GetGroupId() << " ==\n" << " uuid: " << g->GetUuid() << "\n" << " desired size: " << g->GetDesiredSize() << "\n" - << " discoverable state: " - << static_cast(g->GetDiscoveryState()) << "\n" - << " current lock state: " - << static_cast(g->GetCurrentLockState()) << "\n" - << " target lock state: " - << static_cast(g->GetTargetLockState()) << "\n" + << " discoverable state: " << static_cast(g->GetDiscoveryState()) << "\n" + << " current lock state: " << static_cast(g->GetCurrentLockState()) << "\n" + << " target lock state: " << static_cast(g->GetTargetLockState()) << "\n" << " devices: \n"; for (auto& device : devices_) { if (!g->IsDeviceInTheGroup(device)) { if (device->GetExpectedGroupIdMember() == g->GetGroupId()) { - stream << " == candidate addr: " - << ADDRESS_TO_LOGGABLE_STR(device->addr) << "\n"; + stream << " == candidate addr: " << ADDRESS_TO_LOGGABLE_STR(device->addr) + << "\n"; } continue; } - stream << " == addr: " << ADDRESS_TO_LOGGABLE_STR(device->addr) - << " ==\n" - << " csis instance: data:" - << "\n"; + stream << " == addr: " << ADDRESS_TO_LOGGABLE_STR(device->addr) << " ==\n" + << " csis instance: data:" << "\n"; auto instance = device->GetCsisInstanceByGroupId(g->GetGroupId()); if (!instance) { stream << " No csis instance available\n"; } else { - stream << " service handle: " - << loghex(instance->svc_data.start_handle) + stream << " service handle: " << loghex(instance->svc_data.start_handle) << " rank: " << +instance->GetRank() << "\n"; } if (!device->IsConnected()) { stream << " Not connected\n"; } else { - stream << " Connected conn_id = " - << std::to_string(device->conn_id) << "\n"; + stream << " Connected conn_id = " << std::to_string(device->conn_id) << "\n"; } } } @@ -771,26 +757,27 @@ class CsisClientImpl : public CsisClient { dprintf(fd, "%s", stream.str().c_str()); } - private: +private: std::shared_ptr FindDeviceByConnId(uint16_t conn_id) { - auto it = find_if(devices_.begin(), devices_.end(), - CsisDevice::MatchConnId(conn_id)); - if (it != devices_.end()) return (*it); + auto it = find_if(devices_.begin(), devices_.end(), CsisDevice::MatchConnId(conn_id)); + if (it != devices_.end()) { + return *it; + } return nullptr; } void RemoveCsisDevice(std::shared_ptr& device) { - auto it = find_if(devices_.begin(), devices_.end(), - CsisDevice::MatchAddress(device->addr)); + auto it = find_if(devices_.begin(), devices_.end(), CsisDevice::MatchAddress(device->addr)); devices_.erase(it); } void RemoveCsisDevice(std::shared_ptr& device, int group_id) { log::info(""); - auto it = find_if(devices_.begin(), devices_.end(), - CsisDevice::MatchAddress(device->addr)); - if (it == devices_.end()) return; + auto it = find_if(devices_.begin(), devices_.end(), CsisDevice::MatchAddress(device->addr)); + if (it == devices_.end()) { + return; + } if (group_id != bluetooth::groups::kGroupUnknown) { auto csis_group = FindCsisGroup(group_id); @@ -807,18 +794,17 @@ class CsisClientImpl : public CsisClient { RemoveCsisGroup(group_id); /* Remove cached candidate devices for group */ - devices_.erase( - std::remove_if(devices_.begin(), devices_.end(), - [group_id](auto& dev) { - if (dev->GetNumberOfCsisInstances() == 0 && - dev->GetExpectedGroupIdMember() == group_id && - dev->GetPairingSirkReadFlag() == false) { - return true; - } - - return false; - }), - devices_.end()); + devices_.erase(std::remove_if(devices_.begin(), devices_.end(), + [group_id](auto& dev) { + if (dev->GetNumberOfCsisInstances() == 0 && + dev->GetExpectedGroupIdMember() == group_id && + dev->GetPairingSirkReadFlag() == false) { + return true; + } + + return false; + }), + devices_.end()); } device->RemoveCsisInstance(group_id); @@ -829,22 +815,23 @@ class CsisClientImpl : public CsisClient { } } - std::shared_ptr FindDeviceByAddress( - const RawAddress& addr) const { - auto it = find_if(devices_.cbegin(), devices_.cend(), - CsisDevice::MatchAddress(addr)); - if (it != devices_.end()) return (*it); + std::shared_ptr FindDeviceByAddress(const RawAddress& addr) const { + auto it = find_if(devices_.cbegin(), devices_.cend(), CsisDevice::MatchAddress(addr)); + if (it != devices_.end()) { + return *it; + } return nullptr; } std::shared_ptr FindCsisGroup(int group_id) const { - auto it = - find_if(csis_groups_.cbegin(), csis_groups_.cend(), - [group_id](auto& g) { return (group_id == g->GetGroupId()); }); + auto it = find_if(csis_groups_.cbegin(), csis_groups_.cend(), + [group_id](auto& g) { return group_id == g->GetGroupId(); }); - if (it == csis_groups_.end()) return nullptr; - return (*it); + if (it == csis_groups_.end()) { + return nullptr; + } + return *it; } void RemoveCsisGroup(int group_id) { @@ -867,8 +854,7 @@ class CsisClientImpl : public CsisClient { } } - void NotifyCsisDeviceValidAndStoreIfNeeded( - std::shared_ptr& device) { + void NotifyCsisDeviceValidAndStoreIfNeeded(std::shared_ptr& device) { /* Notify that we are ready to go. Notice that multiple callback calls * for a single device address can be called if device is in more than one * CSIS group. @@ -876,7 +862,9 @@ class CsisClientImpl : public CsisClient { bool notify_connected = false; int group_id_to_discover = bluetooth::groups::kGroupUnknown; for (const auto& csis_group : csis_groups_) { - if (!csis_group->IsDeviceInTheGroup(device)) continue; + if (!csis_group->IsDeviceInTheGroup(device)) { + continue; + } int group_id = csis_group->GetGroupId(); auto csis_instance = device->GetCsisInstanceByGroupId(group_id); @@ -893,9 +881,8 @@ class CsisClientImpl : public CsisClient { continue; } - callbacks_->OnDeviceAvailable( - device->addr, group_id, csis_group->GetDesiredSize(), - csis_instance->GetRank(), csis_instance->GetUuid()); + callbacks_->OnDeviceAvailable(device->addr, group_id, csis_group->GetDesiredSize(), + csis_instance->GetRank(), csis_instance->GetUuid()); notify_connected = true; if (group_id_to_discover == bluetooth::groups::kGroupUnknown) { @@ -912,25 +899,21 @@ class CsisClientImpl : public CsisClient { * b/281120322 */ auto g = FindCsisGroup(group_id_to_discover); - log::debug("Group size {} target size {}", g->GetDesiredSize(), - g->GetCurrentSize()); + log::debug("Group size {} target size {}", g->GetDesiredSize(), g->GetCurrentSize()); auto dev_waiting_for_bonding_cnt = - GetNumOfKnownExpectedDevicesWaitingForBonding(g->GetGroupId()); - log::debug("Group size: {}, desired size: {}, waiting for bonding: {}", - g->GetCurrentSize(), g->GetDesiredSize(), - dev_waiting_for_bonding_cnt); + GetNumOfKnownExpectedDevicesWaitingForBonding(g->GetGroupId()); + log::debug("Group size: {}, desired size: {}, waiting for bonding: {}", g->GetCurrentSize(), + g->GetDesiredSize(), dev_waiting_for_bonding_cnt); - if (g->GetDesiredSize() > - g->GetCurrentSize() + dev_waiting_for_bonding_cnt) { + if (g->GetDesiredSize() > g->GetCurrentSize() + dev_waiting_for_bonding_cnt) { CsisActiveDiscovery(g); } } } } - void OnGattWriteCcc(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, - void* user_data) { + void OnGattWriteCcc(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, void* user_data) { auto device = FindDeviceByConnId(conn_id); if (device == nullptr) { log::info("unknown conn_id= 0x{:04x}", conn_id); @@ -945,20 +928,16 @@ class CsisClientImpl : public CsisClient { } if (status == GATT_SUCCESS) { - log::info("Successfully registered on ccc: 0x{:04x}, device: {}", handle, - device->addr); + log::info("Successfully registered on ccc: 0x{:04x}, device: {}", handle, device->addr); return; } - log::error( - "Failed to register for indications: 0x{:04x}, device: {}, status: " - "0x{:02x}", - handle, device->addr, status); + log::error("Failed to register for indications: 0x{:04x}, device: {}, status: 0x{:02x}", handle, + device->addr, status); auto val_handle = device->FindValueHandleByCccHandle(handle); if (!val_handle) { - log::error("Unknown ccc handle: 0x{:04x}, device: {}", handle, - device->addr); + log::error("Unknown ccc handle: 0x{:04x}, device: {}", handle, device->addr); return; } @@ -967,8 +946,7 @@ class CsisClientImpl : public CsisClient { } } - void OnCsisNotification(uint16_t conn_id, uint16_t handle, uint16_t len, - const uint8_t* value) { + void OnCsisNotification(uint16_t conn_id, uint16_t handle, uint16_t len, const uint8_t* value) { auto device = FindDeviceByConnId(conn_id); if (device == nullptr) { log::warn("Skipping unknown device, conn_id= 0x{:04x}", conn_id); @@ -977,8 +955,7 @@ class CsisClientImpl : public CsisClient { auto csis_instance = device->GetCsisInstanceByOwningHandle(handle); if (csis_instance == nullptr) { - log::error("unknown notification handle: 0x{:04x} for conn_id: 0x{:04x}", - handle, conn_id); + log::error("unknown notification handle: 0x{:04x} for conn_id: 0x{:04x}", handle, conn_id); return; } @@ -989,8 +966,7 @@ class CsisClientImpl : public CsisClient { } else if (handle == csis_instance->svc_data.size_handle.val_hdl) { OnCsisSizeValueUpdate(conn_id, GATT_SUCCESS, handle, len, value); } else { - log::warn("unknown notification handle 0x{:04x} for conn_id= 0x{:04x}", - handle, conn_id); + log::warn("unknown notification handle 0x{:04x} for conn_id= 0x{:04x}", handle, conn_id); } } @@ -1009,17 +985,15 @@ class CsisClientImpl : public CsisClient { void CsisLockCompleted(std::shared_ptr& csis_group, bool lock, CsisGroupLockStatus status) { - log::debug("group id: {}, target state {}", csis_group->GetGroupId(), - lock ? "lock" : "unlock"); + log::debug("group id: {}, target state {}", csis_group->GetGroupId(), lock ? "lock" : "unlock"); - NotifyGroupStatus(csis_group->GetGroupId(), lock, status, - std::move(csis_group->GetLockCb())); + NotifyGroupStatus(csis_group->GetGroupId(), lock, status, std::move(csis_group->GetLockCb())); csis_group->SetTargetLockState(CsisLockState::CSIS_STATE_UNSET); } void OnCsisLockNotifications(std::shared_ptr& device, - std::shared_ptr& csis_instance, - uint16_t len, const uint8_t* value) { + std::shared_ptr& csis_instance, uint16_t len, + const uint8_t* value) { if (len != 1) { log::error("invalid notification len: {}", len); return; @@ -1027,18 +1001,19 @@ class CsisClientImpl : public CsisClient { CsisLockState new_lock = (CsisLockState)(value[0]); - log::debug("New lock state: {}, device rank: {}", - static_cast(new_lock), csis_instance->GetRank()); + log::debug("New lock state: {}, device rank: {}", static_cast(new_lock), + csis_instance->GetRank()); csis_instance->SetLockState(new_lock); auto csis_group = FindCsisGroup(csis_instance->GetGroupId()); - if (!csis_group) return; + if (!csis_group) { + return; + } CsisLockCb cb = csis_group->GetLockCb(); if (csis_group->GetTargetLockState() == CsisLockState::CSIS_STATE_UNSET) { - if (csis_group->GetCurrentLockState() == - CsisLockState::CSIS_STATE_LOCKED && + if (csis_group->GetCurrentLockState() == CsisLockState::CSIS_STATE_LOCKED && new_lock == CsisLockState::CSIS_STATE_UNLOCKED) { /* We are here when members fires theirs lock timeout. * Not sure what to do with our current lock state. For now we will @@ -1046,8 +1021,8 @@ class CsisClientImpl : public CsisClient { * we count that others will do the same */ csis_group->SetCurrentLockState(CsisLockState::CSIS_STATE_UNLOCKED); - NotifyGroupStatus(csis_group->GetGroupId(), false, - CsisGroupLockStatus::SUCCESS, std::move(cb)); + NotifyGroupStatus(csis_group->GetGroupId(), false, CsisGroupLockStatus::SUCCESS, + std::move(cb)); } return; } @@ -1064,16 +1039,13 @@ class CsisClientImpl : public CsisClient { /* Device changed back the lock state from what we expected, skip * locking and notify user about that */ - CsisLockCompleted(csis_group, false, - CsisGroupLockStatus::FAILED_OTHER_REASON); + CsisLockCompleted(csis_group, false, CsisGroupLockStatus::FAILED_OTHER_REASON); } } } - void OnCsisSizeValueUpdate(uint16_t conn_id, tGATT_STATUS status, - uint16_t handle, uint16_t len, - const uint8_t* value, - bool notify_valid_services = false) { + void OnCsisSizeValueUpdate(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, uint16_t len, + const uint8_t* value, bool notify_valid_services = false) { auto device = FindDeviceByConnId(conn_id); if (device == nullptr) { @@ -1095,8 +1067,7 @@ class CsisClientImpl : public CsisClient { } if (len != 1) { - log::error("Invalid size value length={} at handle= 0x{:04x}", len, - handle); + log::error("Invalid size value length={} at handle= 0x{:04x}", len, handle); BTA_GATTC_Close(device->conn_id); return; } @@ -1116,12 +1087,13 @@ class CsisClientImpl : public CsisClient { auto new_size = value[0]; csis_group->SetDesiredSize(new_size); - if (notify_valid_services) NotifyCsisDeviceValidAndStoreIfNeeded(device); + if (notify_valid_services) { + NotifyCsisDeviceValidAndStoreIfNeeded(device); + } } - void OnCsisLockReadRsp(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, - uint16_t len, const uint8_t* value, - bool notify_valid_services = false) { + void OnCsisLockReadRsp(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, uint16_t len, + const uint8_t* value, bool notify_valid_services = false) { auto device = FindDeviceByConnId(conn_id); if (device == nullptr) { log::warn("Skipping unknown device, conn_id=0x{:04x}", conn_id); @@ -1142,8 +1114,7 @@ class CsisClientImpl : public CsisClient { } if (len != 1) { - log::error("Invalid lock value length={}, at handle=0x{:04x}", len, - handle); + log::error("Invalid lock value length={}, at handle=0x{:04x}", len, handle); BTA_GATTC_Close(device->conn_id); return; } @@ -1156,20 +1127,20 @@ class CsisClientImpl : public CsisClient { } csis_instance->SetLockState((CsisLockState)(value[0])); - if (notify_valid_services) NotifyCsisDeviceValidAndStoreIfNeeded(device); + if (notify_valid_services) { + NotifyCsisDeviceValidAndStoreIfNeeded(device); + } } - void OnCsisRankReadRsp(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, - uint16_t len, const uint8_t* value, - bool notify_valid_services) { + void OnCsisRankReadRsp(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, uint16_t len, + const uint8_t* value, bool notify_valid_services) { auto device = FindDeviceByConnId(conn_id); if (device == nullptr) { log::warn("Skipping unknown device, conn_id= 0x{:04x}", conn_id); return; } - log::debug("{}, status: 0x{:02x}, rank: {}", device->addr, status, - value[0]); + log::debug("{}, status: 0x{:02x}, rank: {}", device->addr, status, value[0]); if (status != GATT_SUCCESS) { if (status == GATT_DATABASE_OUT_OF_SYNC) { log::info("Database out of sync for {}", device->addr); @@ -1182,8 +1153,7 @@ class CsisClientImpl : public CsisClient { } if (len != 1) { - log::error("Invalid rank value length= {}, at handle= 0x{:04x}", len, - handle); + log::error("Invalid rank value length= {}, at handle= 0x{:04x}", len, handle); BTA_GATTC_Close(device->conn_id); return; } @@ -1195,7 +1165,7 @@ class CsisClientImpl : public CsisClient { return; } - csis_instance->SetRank((value[0])); + csis_instance->SetRank(value[0]); auto csis_group = FindCsisGroup(csis_instance->GetGroupId()); if (!csis_group) { log::error("Unknown group id yet"); @@ -1204,7 +1174,9 @@ class CsisClientImpl : public CsisClient { csis_group->SortByCsisRank(); - if (notify_valid_services) NotifyCsisDeviceValidAndStoreIfNeeded(device); + if (notify_valid_services) { + NotifyCsisDeviceValidAndStoreIfNeeded(device); + } } void OnCsisObserveCompleted(void) { @@ -1226,8 +1198,7 @@ class CsisClientImpl : public CsisClient { discovering_group_ = bluetooth::groups::kGroupUnknown; if (csis_group->IsGroupComplete()) { - csis_group->SetDiscoveryState( - CsisDiscoveryState::CSIS_DISCOVERY_COMPLETED); + csis_group->SetDiscoveryState(CsisDiscoveryState::CSIS_DISCOVERY_COMPLETED); } else { csis_group->SetDiscoveryState(CsisDiscoveryState::CSIS_DISCOVERY_IDLE); } @@ -1237,8 +1208,7 @@ class CsisClientImpl : public CsisClient { * Sirk shall be in LE order * encrypted_sirk: LE order */ - bool sdf(const RawAddress& address, const Octet16& encrypted_sirk, - Octet16& sirk) { + bool sdf(const RawAddress& address, const Octet16& encrypted_sirk, Octet16& sirk) { auto pltk = BTM_BleGetPeerLTK(address); if (!pltk.has_value()) { log::error("No security for {}", address); @@ -1258,8 +1228,7 @@ class CsisClientImpl : public CsisClient { std::string msg1 = "SIRKenc"; std::reverse(msg1.begin(), msg1.end()); - Octet16 s1 = crypto_toolbox::aes_cmac(zero_key, (uint8_t*)(msg1.c_str()), - msg1.size()); + Octet16 s1 = crypto_toolbox::aes_cmac(zero_key, (uint8_t*)(msg1.c_str()), msg1.size()); #ifdef CSIS_DEBUG log::info("s1 (le) {}", base::HexEncode(s1.data(), 16)); @@ -1276,13 +1245,14 @@ class CsisClientImpl : public CsisClient { std::string msg2 = "csis"; std::reverse(msg2.begin(), msg2.end()); - Octet16 k1 = - crypto_toolbox::aes_cmac(T, (uint8_t*)(msg2.c_str()), msg2.size()); + Octet16 k1 = crypto_toolbox::aes_cmac(T, (uint8_t*)(msg2.c_str()), msg2.size()); #ifdef CSIS_DEBUG log::info("K1 (le) {}", base::HexEncode(k1.data(), 16)); #endif - for (int i = 0; i < 16; i++) sirk[i] = encrypted_sirk[i] ^ k1[i]; + for (int i = 0; i < 16; i++) { + sirk[i] = encrypted_sirk[i] ^ k1[i]; + } #ifdef CSIS_DEBUG log::info("SIRK (le){}", base::HexEncode(sirk.data(), 16)); @@ -1291,17 +1261,15 @@ class CsisClientImpl : public CsisClient { return true; } - std::vector GetAllRsiFromAdvertising( - const tBTA_DM_INQ_RES* result) { + std::vector GetAllRsiFromAdvertising(const tBTA_DM_INQ_RES* result) { const uint8_t* p_service_data = result->p_eir; std::vector devices; uint8_t service_data_len = 0; while ((p_service_data = AdvertiseDataParser::GetFieldByType( - p_service_data + service_data_len, - result->eir_len - (p_service_data - result->p_eir) - - service_data_len, - BTM_BLE_AD_TYPE_RSI, &service_data_len))) { + p_service_data + service_data_len, + result->eir_len - (p_service_data - result->p_eir) - service_data_len, + BTM_BLE_AD_TYPE_RSI, &service_data_len))) { RawAddress bda; const uint8_t* p_bda = p_service_data; if (service_data_len < RawAddress::kLength) { @@ -1316,15 +1284,13 @@ class CsisClientImpl : public CsisClient { } int GetNumOfKnownExpectedDevicesWaitingForBonding(int group_id) { - return std::count_if( - devices_.begin(), devices_.end(), [group_id](const auto& device) { - return device->GetExpectedGroupIdMember() == group_id && - !device->GetCsisInstanceByGroupId(group_id); - }); + return std::count_if(devices_.begin(), devices_.end(), [group_id](const auto& device) { + return device->GetExpectedGroupIdMember() == group_id && + !device->GetCsisInstanceByGroupId(group_id); + }); } - void CacheAndAdvertiseExpectedMember(const RawAddress& address, - int group_id) { + void CacheAndAdvertiseExpectedMember(const RawAddress& address, int group_id) { auto device = FindDeviceByAddress(address); if (device == nullptr) { device = std::make_shared(address, false); @@ -1336,8 +1302,7 @@ class CsisClientImpl : public CsisClient { * truly is member of group. */ device.get()->SetExpectedGroupIdMember(group_id); - callbacks_->OnSetMemberAvailable(address, - device.get()->GetExpectedGroupIdMember()); + callbacks_->OnSetMemberAvailable(address, device.get()->GetExpectedGroupIdMember()); } void OnActiveScanResult(const tBTA_DM_INQ_RES* result) { @@ -1351,14 +1316,15 @@ class CsisClientImpl : public CsisClient { * be a case for dual mode devices where */ if (BTM_BleIsLinkKeyKnown(result->bd_addr)) { - log::verbose("Device {} already bonded. Identity address: {}", - result->bd_addr, + log::verbose("Device {} already bonded. Identity address: {}", result->bd_addr, *BTM_BleGetIdentityAddress(result->bd_addr)); return; } auto all_rsi = GetAllRsiFromAdvertising(result); - if (all_rsi.empty()) return; + if (all_rsi.empty()) { + return; + } /* Notify only the actively searched group */ auto csis_group = FindCsisGroup(discovering_group_); @@ -1374,15 +1340,13 @@ class CsisClientImpl : public CsisClient { return; } - auto discovered_group_rsi = std::find_if( - all_rsi.cbegin(), all_rsi.cend(), [&csis_group](const auto& rsi) { - return csis_group->IsRsiMatching(rsi); - }); + auto discovered_group_rsi = + std::find_if(all_rsi.cbegin(), all_rsi.cend(), + [&csis_group](const auto& rsi) { return csis_group->IsRsiMatching(rsi); }); if (discovered_group_rsi != all_rsi.cend()) { log::debug("Found set member {}", result->bd_addr); - CacheAndAdvertiseExpectedMember(result->bd_addr, - csis_group->GetGroupId()); + CacheAndAdvertiseExpectedMember(result->bd_addr, csis_group->GetGroupId()); /* Switch back to the opportunistic observer mode. * When second device will pair, csis will restart active scan @@ -1393,11 +1357,9 @@ class CsisClientImpl : public CsisClient { } static void csis_ad_type_filter_set(bool enable) { - bool is_ad_type_filter_supported = - bluetooth::shim::is_ad_type_filter_supported(); + bool is_ad_type_filter_supported = bluetooth::shim::is_ad_type_filter_supported(); - log::info("enable: {}, is_ad_type_filter_supported: {}", enable, - is_ad_type_filter_supported); + log::info("enable: {}, is_ad_type_filter_supported: {}", enable, is_ad_type_filter_supported); if (is_ad_type_filter_supported) { bluetooth::shim::set_ad_type_rsi_filter(enable); @@ -1410,32 +1372,30 @@ class CsisClientImpl : public CsisClient { log::info("Group_id {}: enable: {}", discovering_group_, enable); csis_ad_type_filter_set(enable); - BTA_DmBleCsisObserve(enable, - [](tBTA_DM_SEARCH_EVT event, tBTA_DM_SEARCH* p_data) { - /* If there's no instance we are most likely shutting - * down the whole stack and we can ignore this event. - */ - if (instance == nullptr) return; - - if (event == BTA_DM_OBSERVE_CMPL_EVT) { - power_telemetry::GetInstance().LogBleScan( - static_cast( - p_data->observe_cmpl.num_resps)); - log::info("BLE observe complete. Num Resp: {}", - p_data->observe_cmpl.num_resps); - csis_ad_type_filter_set(false); - instance->OnCsisObserveCompleted(); - instance->CsisObserverSetBackground(true); - return; - } - - if (event != BTA_DM_INQ_RES_EVT) { - log::warn("Unknown event: 0x{:02x}", event); - return; - } - - instance->OnActiveScanResult(&p_data->inq_res); - }); + BTA_DmBleCsisObserve(enable, [](tBTA_DM_SEARCH_EVT event, tBTA_DM_SEARCH* p_data) { + /* If there's no instance we are most likely shutting + * down the whole stack and we can ignore this event. + */ + if (instance == nullptr) { + return; + } + + if (event == BTA_DM_OBSERVE_CMPL_EVT) { + power_telemetry::GetInstance().LogBleScan(static_cast(p_data->observe_cmpl.num_resps)); + log::info("BLE observe complete. Num Resp: {}", p_data->observe_cmpl.num_resps); + csis_ad_type_filter_set(false); + instance->OnCsisObserveCompleted(); + instance->CsisObserverSetBackground(true); + return; + } + + if (event != BTA_DM_INQ_RES_EVT) { + log::warn("Unknown event: 0x{:02x}", event); + return; + } + + instance->OnActiveScanResult(&p_data->inq_res); + }); BTA_DmBleScan(enable, bluetooth::csis::kDefaultScanDurationS, true); /* Need to call it by ourselfs */ @@ -1447,12 +1407,12 @@ class CsisClientImpl : public CsisClient { void CheckForGroupInInqDb(const std::shared_ptr& csis_group) { // Check if last inquiry already found devices with RSI matching this group - for (tBTM_INQ_INFO* inq_ent = - get_btm_client_interface().db.BTM_InqDbFirst(); - inq_ent != nullptr; - inq_ent = get_btm_client_interface().db.BTM_InqDbNext(inq_ent)) { + for (tBTM_INQ_INFO* inq_ent = get_btm_client_interface().db.BTM_InqDbFirst(); + inq_ent != nullptr; inq_ent = get_btm_client_interface().db.BTM_InqDbNext(inq_ent)) { RawAddress rsi = inq_ent->results.ble_ad_rsi; - if (!csis_group->IsRsiMatching(rsi)) continue; + if (!csis_group->IsRsiMatching(rsi)) { + continue; + } RawAddress address = inq_ent->results.remote_bd_addr; auto device = FindDeviceByAddress(address); @@ -1474,10 +1434,8 @@ class CsisClientImpl : public CsisClient { CheckForGroupInInqDb(csis_group); } - if ((csis_group->GetDiscoveryState() != - CsisDiscoveryState::CSIS_DISCOVERY_IDLE)) { - log::error("Incorrect ase group: {}, state 0x{:02x}", - csis_group->GetGroupId(), + if (csis_group->GetDiscoveryState() != CsisDiscoveryState::CSIS_DISCOVERY_IDLE) { + log::error("Incorrect ase group: {}, state 0x{:02x}", csis_group->GetGroupId(), static_cast(csis_group->GetDiscoveryState())); return; } @@ -1489,7 +1447,9 @@ class CsisClientImpl : public CsisClient { } void OnScanBackgroundResult(const tBTA_DM_INQ_RES* result) { - if (csis_groups_.empty()) return; + if (csis_groups_.empty()) { + return; + } auto csis_device = FindDeviceByAddress(result->bd_addr); if (csis_device) { @@ -1501,25 +1461,23 @@ class CsisClientImpl : public CsisClient { * be a case for dual mode devices where */ if (BTM_BleIsLinkKeyKnown(result->bd_addr)) { - log::verbose("Device {} already bonded. Identity address: {}", - result->bd_addr, + log::verbose("Device {} already bonded. Identity address: {}", result->bd_addr, *BTM_BleGetIdentityAddress(result->bd_addr)); return; } auto all_rsi = GetAllRsiFromAdvertising(result); - if (all_rsi.empty()) return; + if (all_rsi.empty()) { + return; + } /* Notify all the groups this device belongs to. */ for (auto& group : csis_groups_) { for (auto& rsi : all_rsi) { if (group->IsRsiMatching(rsi)) { - log::info("Device {} match to group id {}", result->bd_addr, - group->GetGroupId()); - if (group->GetDesiredSize() > 0 && - (group->GetCurrentSize() == group->GetDesiredSize())) { - log::warn( - "Group is already completed. Some other device use same SIRK"); + log::info("Device {} match to group id {}", result->bd_addr, group->GetGroupId()); + if (group->GetDesiredSize() > 0 && (group->GetCurrentSize() == group->GetDesiredSize())) { + log::warn("Group is already completed. Some other device use same SIRK"); break; } @@ -1534,35 +1492,31 @@ class CsisClientImpl : public CsisClient { void CsisObserverSetBackground(bool enable) { log::debug("CSIS Discovery background: {}", enable); - BTA_DmBleCsisObserve(enable, - [](tBTA_DM_SEARCH_EVT event, tBTA_DM_SEARCH* p_data) { - /* If there's no instance we are most likely shutting - * down the whole stack and we can ignore this event. - */ - if (instance == nullptr) return; - - if (event == BTA_DM_OBSERVE_CMPL_EVT) { - power_telemetry::GetInstance().LogBleScan( - static_cast( - p_data->observe_cmpl.num_resps)); - log::verbose("BLE observe complete. Num Resp: {}", - p_data->observe_cmpl.num_resps); - return; - } - - if (event != BTA_DM_INQ_RES_EVT) { - log::warn("Unknown event: 0x{:02x}", event); - return; - } - - instance->OnScanBackgroundResult(&p_data->inq_res); - }); - } - - void OnCsisSirkValueUpdate(uint16_t conn_id, tGATT_STATUS status, - uint16_t handle, uint16_t len, - const uint8_t* value, - bool notify_valid_services = true) { + BTA_DmBleCsisObserve(enable, [](tBTA_DM_SEARCH_EVT event, tBTA_DM_SEARCH* p_data) { + /* If there's no instance we are most likely shutting + * down the whole stack and we can ignore this event. + */ + if (instance == nullptr) { + return; + } + + if (event == BTA_DM_OBSERVE_CMPL_EVT) { + power_telemetry::GetInstance().LogBleScan(static_cast(p_data->observe_cmpl.num_resps)); + log::verbose("BLE observe complete. Num Resp: {}", p_data->observe_cmpl.num_resps); + return; + } + + if (event != BTA_DM_INQ_RES_EVT) { + log::warn("Unknown event: 0x{:02x}", event); + return; + } + + instance->OnScanBackgroundResult(&p_data->inq_res); + }); + } + + void OnCsisSirkValueUpdate(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, uint16_t len, + const uint8_t* value, bool notify_valid_services = true) { auto device = FindDeviceByConnId(conn_id); if (device == nullptr) { log::warn("Skipping unknown device, conn_id=0x{:04x}", conn_id); @@ -1587,8 +1541,7 @@ class CsisClientImpl : public CsisClient { } if (len != bluetooth::csis::kCsisSirkCharLen) { - log::error("Invalid sirk value length= {} at handle= 0x{:04x}", len, - handle); + log::error("Invalid sirk value length= {} at handle= 0x{:04x}", len, handle); BTA_GATTC_Close(device->conn_id); return; } @@ -1606,8 +1559,7 @@ class CsisClientImpl : public CsisClient { /* Verify if sirk is not all zeros */ Octet16 zero{}; if (memcmp(zero.data(), value + 1, 16) == 0) { - log::error("Received invalid zero SIRK conn_id: 0x{:02x}. Disconnecting", - device->conn_id); + log::error("Received invalid zero SIRK conn_id: 0x{:02x}. Disconnecting", device->conn_id); BTA_GATTC_Close(device->conn_id); return; } @@ -1629,8 +1581,7 @@ class CsisClientImpl : public CsisClient { if (group_id != bluetooth::groups::kGroupUnknown) { /* Group already exist. */ csis_group = FindCsisGroup(group_id); - log::assert_that(csis_group != nullptr, "group does not exist? {}", - group_id); + log::assert_that(csis_group != nullptr, "group does not exist? {}", group_id); } else { /* Now having SIRK we can decide if the device belongs to some group we * know or this is a new group @@ -1644,14 +1595,11 @@ class CsisClientImpl : public CsisClient { if (group_id == bluetooth::groups::kGroupUnknown) { /* Here it means, we have new group. Let's us create it */ - group_id = - dev_groups_->AddDevice(device->addr, csis_instance->GetUuid()); - log::assert_that( - group_id != bluetooth::groups::kGroupUnknown, - "assert failed: group_id != bluetooth::groups::kGroupUnknown"); + group_id = dev_groups_->AddDevice(device->addr, csis_instance->GetUuid()); + log::assert_that(group_id != bluetooth::groups::kGroupUnknown, + "assert failed: group_id != bluetooth::groups::kGroupUnknown"); } else { - dev_groups_->AddDevice(device->addr, csis_instance->GetUuid(), - group_id); + dev_groups_->AddDevice(device->addr, csis_instance->GetUuid(), group_id); } csis_group = FindCsisGroup(group_id); @@ -1664,15 +1612,16 @@ class CsisClientImpl : public CsisClient { device->is_gatt_service_valid = true; btif_storage_update_csis_info(device->addr); - if (notify_valid_services) NotifyCsisDeviceValidAndStoreIfNeeded(device); + if (notify_valid_services) { + NotifyCsisDeviceValidAndStoreIfNeeded(device); + } #ifdef CSIS_DEBUG - log::info("SIRK {}, address: {}", base::HexEncode(received_sirk.data(), 16), - device->addr); + log::info("SIRK {}, address: {}", base::HexEncode(received_sirk.data(), 16), device->addr); #endif - log::verbose("Expected group size {}, actual group Size: {}", - csis_group->GetDesiredSize(), csis_group->GetCurrentSize()); + log::verbose("Expected group size {}, actual group Size: {}", csis_group->GetDesiredSize(), + csis_group->GetCurrentSize()); if (csis_group->GetDesiredSize() == csis_group->GetCurrentSize()) { auto iter = devices_.cbegin(); @@ -1695,15 +1644,14 @@ class CsisClientImpl : public CsisClient { } void DeregisterNotifications(std::shared_ptr device) { - device->ForEachCsisInstance( - [&](const std::shared_ptr& csis_inst) { - DisableGattNotification(device->conn_id, device->addr, - csis_inst->svc_data.lock_handle.val_hdl); - DisableGattNotification(device->conn_id, device->addr, - csis_inst->svc_data.sirk_handle.val_hdl); - DisableGattNotification(device->conn_id, device->addr, - csis_inst->svc_data.size_handle.val_hdl); - }); + device->ForEachCsisInstance([&](const std::shared_ptr& csis_inst) { + DisableGattNotification(device->conn_id, device->addr, + csis_inst->svc_data.lock_handle.val_hdl); + DisableGattNotification(device->conn_id, device->addr, + csis_inst->svc_data.sirk_handle.val_hdl); + DisableGattNotification(device->conn_id, device->addr, + csis_inst->svc_data.size_handle.val_hdl); + }); } void DoDisconnectCleanUp(std::shared_ptr device) { @@ -1717,20 +1665,19 @@ class CsisClientImpl : public CsisClient { } } - bool OnCsisServiceFound(std::shared_ptr device, - const gatt::Service* service, - const bluetooth::Uuid& context_uuid, - bool is_last_instance) { - log::debug("service handle: 0x{:04x}, end handle: 0x{:04x}, uuid: {}", - service->handle, service->end_handle, context_uuid.ToString()); + bool OnCsisServiceFound(std::shared_ptr device, const gatt::Service* service, + const bluetooth::Uuid& context_uuid, bool is_last_instance) { + log::debug("service handle: 0x{:04x}, end handle: 0x{:04x}, uuid: {}", service->handle, + service->end_handle, context_uuid.ToString()); - auto csis_inst = std::make_shared( - (uint16_t)service->handle, (uint16_t)service->end_handle, context_uuid); + auto csis_inst = std::make_shared((uint16_t)service->handle, + (uint16_t)service->end_handle, context_uuid); /* Let's check if we know group of this device */ int group_id = dev_groups_->GetGroupId(device->addr, context_uuid); - if (group_id != bluetooth::groups::kGroupUnknown) + if (group_id != bluetooth::groups::kGroupUnknown) { csis_inst->SetGroupId(group_id); + } device->SetCsisInstance(csis_inst->svc_data.start_handle, csis_inst); @@ -1738,8 +1685,7 @@ class CsisClientImpl : public CsisClient { for (const gatt::Characteristic& charac : service->characteristics) { if (charac.uuid == kCsisLockUuid) { /* Find the mandatory CCC descriptor */ - uint16_t ccc_handle = - FindCccHandle(device->conn_id, charac.value_handle); + uint16_t ccc_handle = FindCccHandle(device->conn_id, charac.value_handle); if (ccc_handle == GAP_INVALID_HANDLE) { log::error("no HAS Active Preset CCC descriptor found!"); device->RemoveCsisInstance(group_id); @@ -1748,51 +1694,42 @@ class CsisClientImpl : public CsisClient { csis_inst->svc_data.lock_handle.val_hdl = charac.value_handle; csis_inst->svc_data.lock_handle.ccc_hdl = ccc_handle; - SubscribeForNotifications(device->conn_id, device->addr, - charac.value_handle, ccc_handle); + SubscribeForNotifications(device->conn_id, device->addr, charac.value_handle, ccc_handle); - log::debug( - "Lock UUID found handle: 0x{:04x}, ccc handle: 0x{:04x}, device: " - "{}", - csis_inst->svc_data.lock_handle.val_hdl, - csis_inst->svc_data.lock_handle.ccc_hdl, device->addr); + log::debug("Lock UUID found handle: 0x{:04x}, ccc handle: 0x{:04x}, device: {}", + csis_inst->svc_data.lock_handle.val_hdl, csis_inst->svc_data.lock_handle.ccc_hdl, + device->addr); } else if (charac.uuid == kCsisRankUuid) { csis_inst->svc_data.rank_handle = charac.value_handle; - log::debug("Rank UUID found handle: 0x{:04x}, device: {}", - csis_inst->svc_data.rank_handle, device->addr); + log::debug("Rank UUID found handle: 0x{:04x}, device: {}", csis_inst->svc_data.rank_handle, + device->addr); } else if (charac.uuid == kCsisSirkUuid) { /* Find the optional CCC descriptor */ - uint16_t ccc_handle = - FindCccHandle(device->conn_id, charac.value_handle); + uint16_t ccc_handle = FindCccHandle(device->conn_id, charac.value_handle); csis_inst->svc_data.sirk_handle.ccc_hdl = ccc_handle; csis_inst->svc_data.sirk_handle.val_hdl = charac.value_handle; - if (ccc_handle != GAP_INVALID_HANDLE) - SubscribeForNotifications(device->conn_id, device->addr, - charac.value_handle, ccc_handle); + if (ccc_handle != GAP_INVALID_HANDLE) { + SubscribeForNotifications(device->conn_id, device->addr, charac.value_handle, ccc_handle); + } - log::debug( - "SIRK UUID found handle: 0x{:04x}, ccc handle: 0x{:04x}, device: " - "{}", - csis_inst->svc_data.sirk_handle.val_hdl, - csis_inst->svc_data.sirk_handle.ccc_hdl, device->addr); + log::debug("SIRK UUID found handle: 0x{:04x}, ccc handle: 0x{:04x}, device: {}", + csis_inst->svc_data.sirk_handle.val_hdl, csis_inst->svc_data.sirk_handle.ccc_hdl, + device->addr); } else if (charac.uuid == kCsisSizeUuid) { /* Find the optional CCC descriptor */ - uint16_t ccc_handle = - FindCccHandle(device->conn_id, charac.value_handle); + uint16_t ccc_handle = FindCccHandle(device->conn_id, charac.value_handle); csis_inst->svc_data.size_handle.ccc_hdl = ccc_handle; csis_inst->svc_data.size_handle.val_hdl = charac.value_handle; - if (ccc_handle != GAP_INVALID_HANDLE) - SubscribeForNotifications(device->conn_id, device->addr, - charac.value_handle, ccc_handle); + if (ccc_handle != GAP_INVALID_HANDLE) { + SubscribeForNotifications(device->conn_id, device->addr, charac.value_handle, ccc_handle); + } - log::debug( - "Size UUID found handle: 0x{:04x}, ccc handle: 0x{:04x}, device: " - "{}", - csis_inst->svc_data.size_handle.val_hdl, - csis_inst->svc_data.size_handle.ccc_hdl, device->addr); + log::debug("Size UUID found handle: 0x{:04x}, ccc handle: 0x{:04x}, device: {}", + csis_inst->svc_data.size_handle.val_hdl, csis_inst->svc_data.size_handle.ccc_hdl, + device->addr); } } @@ -1815,11 +1752,9 @@ class CsisClientImpl : public CsisClient { if (is_last_instance) { if (csis_inst->svc_data.rank_handle != GAP_INVALID_HANDLE) { notify_after_rank_read = true; - } else if (csis_inst->svc_data.size_handle.val_hdl != - GAP_INVALID_HANDLE) { + } else if (csis_inst->svc_data.size_handle.val_hdl != GAP_INVALID_HANDLE) { notify_after_size_read = true; - } else if (csis_inst->svc_data.lock_handle.val_hdl != - GAP_INVALID_HANDLE) { + } else if (csis_inst->svc_data.lock_handle.val_hdl != GAP_INVALID_HANDLE) { notify_after_lock_read = true; } else { notify_after_sirk_read = true; @@ -1828,52 +1763,54 @@ class CsisClientImpl : public CsisClient { /* Read SIRK */ BtaGattQueue::ReadCharacteristic( - device->conn_id, csis_inst->svc_data.sirk_handle.val_hdl, - [](uint16_t conn_id, tGATT_STATUS status, uint16_t handle, uint16_t len, - uint8_t* value, void* user_data) { - if (instance) - instance->OnCsisSirkValueUpdate(conn_id, status, handle, len, value, - (bool)user_data); - }, - (void*)notify_after_sirk_read); + device->conn_id, csis_inst->svc_data.sirk_handle.val_hdl, + [](uint16_t conn_id, tGATT_STATUS status, uint16_t handle, uint16_t len, uint8_t* value, + void* user_data) { + if (instance) { + instance->OnCsisSirkValueUpdate(conn_id, status, handle, len, value, + (bool)user_data); + } + }, + (void*)notify_after_sirk_read); /* Read Lock */ if (csis_inst->svc_data.lock_handle.val_hdl != GAP_INVALID_HANDLE) { BtaGattQueue::ReadCharacteristic( - device->conn_id, csis_inst->svc_data.lock_handle.val_hdl, - [](uint16_t conn_id, tGATT_STATUS status, uint16_t handle, - uint16_t len, uint8_t* value, void* user_data) { - if (instance) - instance->OnCsisLockReadRsp(conn_id, status, handle, len, value, - (bool)user_data); - }, - (void*)notify_after_lock_read); + device->conn_id, csis_inst->svc_data.lock_handle.val_hdl, + [](uint16_t conn_id, tGATT_STATUS status, uint16_t handle, uint16_t len, + uint8_t* value, void* user_data) { + if (instance) { + instance->OnCsisLockReadRsp(conn_id, status, handle, len, value, (bool)user_data); + } + }, + (void*)notify_after_lock_read); } /* Read Size */ if (csis_inst->svc_data.size_handle.val_hdl != GAP_INVALID_HANDLE) { BtaGattQueue::ReadCharacteristic( - device->conn_id, csis_inst->svc_data.size_handle.val_hdl, - [](uint16_t conn_id, tGATT_STATUS status, uint16_t handle, - uint16_t len, uint8_t* value, void* user_data) { - if (instance) - instance->OnCsisSizeValueUpdate(conn_id, status, handle, len, - value, (bool)user_data); - }, - (void*)notify_after_size_read); + device->conn_id, csis_inst->svc_data.size_handle.val_hdl, + [](uint16_t conn_id, tGATT_STATUS status, uint16_t handle, uint16_t len, + uint8_t* value, void* user_data) { + if (instance) { + instance->OnCsisSizeValueUpdate(conn_id, status, handle, len, value, + (bool)user_data); + } + }, + (void*)notify_after_size_read); } /* Read Rank */ if (csis_inst->svc_data.rank_handle != GAP_INVALID_HANDLE) { BtaGattQueue::ReadCharacteristic( - device->conn_id, csis_inst->svc_data.rank_handle, - [](uint16_t conn_id, tGATT_STATUS status, uint16_t handle, - uint16_t len, uint8_t* value, void* user_data) { - if (instance) - instance->OnCsisRankReadRsp(conn_id, status, handle, len, value, - (bool)user_data); - }, - (void*)notify_after_rank_read); + device->conn_id, csis_inst->svc_data.rank_handle, + [](uint16_t conn_id, tGATT_STATUS status, uint16_t handle, uint16_t len, + uint8_t* value, void* user_data) { + if (instance) { + instance->OnCsisRankReadRsp(conn_id, status, handle, len, value, (bool)user_data); + } + }, + (void*)notify_after_rank_read); } return true; @@ -1886,7 +1823,9 @@ class CsisClientImpl : public CsisClient { /* This is in case Csis CleanUp is already done * while GATT is still up and could send events */ - if (!instance) return; + if (!instance) { + return; + } switch (event) { case BTA_GATTC_DEREG_EVT: @@ -1932,13 +1871,12 @@ class CsisClientImpl : public CsisClient { } void OnGattConnected(const tBTA_GATTC_OPEN& evt) { - log::info("{}, conn_id=0x{:04x}, transport={}, status={}(0x{:02x})", - evt.remote_bda, evt.conn_id, bt_transport_text(evt.transport), - gatt_status_text(evt.status), evt.status); + log::info("{}, conn_id=0x{:04x}, transport={}, status={}(0x{:02x})", evt.remote_bda, + evt.conn_id, bt_transport_text(evt.transport), gatt_status_text(evt.status), + evt.status); if (evt.transport != BT_TRANSPORT_LE) { - log::warn("Only LE connection is allowed (transport {})", - bt_transport_text(evt.transport)); + log::warn("Only LE connection is allowed (transport {})", bt_transport_text(evt.transport)); BTA_GATTC_Close(evt.conn_id); return; } @@ -1952,9 +1890,9 @@ class CsisClientImpl : public CsisClient { if (evt.status != GATT_SUCCESS) { log::error("Failed to connect to server device {}", evt.remote_bda); - if (device->connecting_actively) - callbacks_->OnConnectionState(evt.remote_bda, - ConnectionState::DISCONNECTED); + if (device->connecting_actively) { + callbacks_->OnConnectionState(evt.remote_bda, ConnectionState::DISCONNECTED); + } DoDisconnectCleanUp(device); StartOpportunisticConnect(evt.remote_bda); return; @@ -1977,11 +1915,10 @@ class CsisClientImpl : public CsisClient { return; } - int result = BTM_SetEncryption(device->addr, BT_TRANSPORT_LE, nullptr, - nullptr, BTM_BLE_SEC_ENCRYPT); + int result = + BTM_SetEncryption(device->addr, BT_TRANSPORT_LE, nullptr, nullptr, BTM_BLE_SEC_ENCRYPT); - log::info("Encryption required for {}. Request result: 0x{:02x}", - device->addr, result); + log::info("Encryption required for {}. Request result: 0x{:02x}", device->addr, result); if (result == BTM_ERR_KEY_MISSING) { log::error("Link key unknown for {}, disconnect profile", device->addr); @@ -1992,31 +1929,27 @@ class CsisClientImpl : public CsisClient { void OnGattDisconnected(const tBTA_GATTC_CLOSE& evt) { auto device = FindDeviceByAddress(evt.remote_bda); if (device == nullptr) { - log::warn("Skipping unknown device disconnect, conn_id= 0x{:04x}", - evt.conn_id); + log::warn("Skipping unknown device disconnect, conn_id= 0x{:04x}", evt.conn_id); return; } log::debug("device={}", device->addr); - callbacks_->OnConnectionState(evt.remote_bda, - ConnectionState::DISCONNECTED); + callbacks_->OnConnectionState(evt.remote_bda, ConnectionState::DISCONNECTED); // Unlock others only if device was locked by us but has disconnected // unexpectedly. - if ((evt.reason == GATT_CONN_TIMEOUT) || - (evt.reason == GATT_CONN_TERMINATE_PEER_USER)) { - device->ForEachCsisInstance( - [&](const std::shared_ptr& csis_inst) { - auto csis_group = FindCsisGroup(csis_inst->GetGroupId()); - if (csis_group == nullptr) return; - if ((csis_group->GetCurrentLockState() == - CsisLockState::CSIS_STATE_LOCKED)) { - HandleCsisLockProcedureError( - csis_group, device, - CsisGroupLockStatus::LOCKED_GROUP_MEMBER_LOST); - } - }); + if ((evt.reason == GATT_CONN_TIMEOUT) || (evt.reason == GATT_CONN_TERMINATE_PEER_USER)) { + device->ForEachCsisInstance([&](const std::shared_ptr& csis_inst) { + auto csis_group = FindCsisGroup(csis_inst->GetGroupId()); + if (csis_group == nullptr) { + return; + } + if (csis_group->GetCurrentLockState() == CsisLockState::CSIS_STATE_LOCKED) { + HandleCsisLockProcedureError(csis_group, device, + CsisGroupLockStatus::LOCKED_GROUP_MEMBER_LOST); + } + }); } DoDisconnectCleanUp(device); @@ -2048,8 +1981,7 @@ class CsisClientImpl : public CsisClient { log::verbose(""); - const std::list* all_services = - BTA_GATTC_GetServices(device->conn_id); + const std::list* all_services = BTA_GATTC_GetServices(device->conn_id); std::vector all_csis_start_handles; @@ -2069,18 +2001,20 @@ class CsisClientImpl : public CsisClient { } for (auto& svrc : *all_services) { - if (svrc.uuid == kCsisServiceUuid) continue; + if (svrc.uuid == kCsisServiceUuid) { + continue; + } /* Try to find context for CSIS instances */ for (auto& included_srvc : svrc.included_services) { if (included_srvc.uuid == kCsisServiceUuid) { - auto csis_svrc = BTA_GATTC_GetOwningService( - device->conn_id, included_srvc.start_handle); - auto iter = std::find(all_csis_start_handles.begin(), - all_csis_start_handles.end(), + auto csis_svrc = + BTA_GATTC_GetOwningService(device->conn_id, included_srvc.start_handle); + auto iter = std::find(all_csis_start_handles.begin(), all_csis_start_handles.end(), included_srvc.start_handle); - if (iter != all_csis_start_handles.end()) + if (iter != all_csis_start_handles.end()) { all_csis_start_handles.erase(iter); + } instance->OnCsisServiceFound(device, csis_svrc, svrc.uuid, all_csis_start_handles.empty()); } @@ -2095,10 +2029,9 @@ class CsisClientImpl : public CsisClient { if (all_csis_start_handles.size()) { log::debug("there is {} primary services without a context", static_cast(all_csis_start_handles.size())); - auto csis_svrc = BTA_GATTC_GetOwningService(device->conn_id, - all_csis_start_handles[0]); - instance->OnCsisServiceFound( - device, csis_svrc, bluetooth::groups::kGenericContextUuid, true); + auto csis_svrc = BTA_GATTC_GetOwningService(device->conn_id, all_csis_start_handles[0]); + instance->OnCsisServiceFound(device, csis_svrc, bluetooth::groups::kGenericContextUuid, + true); all_csis_start_handles.clear(); } } else { @@ -2114,8 +2047,7 @@ class CsisClientImpl : public CsisClient { void OnGattNotification(const tBTA_GATTC_NOTIFY& evt) { /* Reject invalid lengths and indications as they are not supported */ if (!evt.is_notify || evt.len > GATT_MAX_ATTR_LEN) { - log::error(": rejected BTA_GATTC_NOTIF_EVT. is_notify = {}, len= {}", - evt.is_notify, evt.len); + log::error(": rejected BTA_GATTC_NOTIF_EVT. is_notify = {}, len= {}", evt.is_notify, evt.len); } OnCsisNotification(evt.conn_id, evt.handle, evt.len, evt.value); @@ -2143,8 +2075,7 @@ class CsisClientImpl : public CsisClient { } } - void ClearDeviceInformationAndStartSearch( - std::shared_ptr device) { + void ClearDeviceInformationAndStartSearch(std::shared_ptr device) { log::info("{}", device->addr); if (device->is_gatt_service_valid == false) { log::debug("Device database already invalidated."); @@ -2178,69 +2109,69 @@ class CsisClientImpl : public CsisClient { log::debug("address={}", address); - if (!device->is_gatt_service_valid) + if (!device->is_gatt_service_valid) { BTA_GATTC_ServiceSearchRequest(device->conn_id, kCsisServiceUuid); + } } static uint16_t FindCccHandle(uint16_t conn_id, uint16_t char_handle) { - const gatt::Characteristic* p_char = - BTA_GATTC_GetCharacteristic(conn_id, char_handle); + const gatt::Characteristic* p_char = BTA_GATTC_GetCharacteristic(conn_id, char_handle); if (!p_char) { log::warn("No such characteristic: 0x{:04x}", char_handle); return GAP_INVALID_HANDLE; } for (const gatt::Descriptor& desc : p_char->descriptors) { - if (desc.uuid == Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)) + if (desc.uuid == Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)) { return desc.handle; + } } return GAP_INVALID_HANDLE; } - void SubscribeForNotifications(uint16_t conn_id, const RawAddress& address, - uint16_t value_handle, uint16_t ccc_handle) { + void SubscribeForNotifications(uint16_t conn_id, const RawAddress& address, uint16_t value_handle, + uint16_t ccc_handle) { if (value_handle != GAP_INVALID_HANDLE) { tGATT_STATUS register_status = - BTA_GATTC_RegisterForNotifications(gatt_if_, address, value_handle); - log::debug( - "BTA_GATTC_RegisterForNotifications, status=0x{:02x}, value=0x{:x}, " - "ccc=0x{:04x}", - register_status, value_handle, ccc_handle); + BTA_GATTC_RegisterForNotifications(gatt_if_, address, value_handle); + log::debug("BTA_GATTC_RegisterForNotifications, status=0x{:02x}, value=0x{:x}, ccc=0x{:04x}", + register_status, value_handle, ccc_handle); - if (register_status != GATT_SUCCESS) return; + if (register_status != GATT_SUCCESS) { + return; + } } std::vector value(2); uint8_t* value_ptr = value.data(); UINT16_TO_STREAM(value_ptr, GATT_CHAR_CLIENT_CONFIG_NOTIFICATION); BtaGattQueue::WriteDescriptor( - conn_id, ccc_handle, std::move(value), GATT_WRITE, - [](uint16_t conn_id, tGATT_STATUS status, uint16_t handle, uint16_t len, - const uint8_t* value, void* user_data) { - if (instance) - instance->OnGattWriteCcc(conn_id, status, handle, user_data); - }, - nullptr); + conn_id, ccc_handle, std::move(value), GATT_WRITE, + [](uint16_t conn_id, tGATT_STATUS status, uint16_t handle, uint16_t len, + const uint8_t* value, void* user_data) { + if (instance) { + instance->OnGattWriteCcc(conn_id, status, handle, user_data); + } + }, + nullptr); } - void DisableGattNotification(uint16_t conn_id, const RawAddress& address, - uint16_t value_handle) { + void DisableGattNotification(uint16_t conn_id, const RawAddress& address, uint16_t value_handle) { if (value_handle != GAP_INVALID_HANDLE) { tGATT_STATUS register_status = - BTA_GATTC_DeregisterForNotifications(gatt_if_, address, value_handle); - log::debug( - "DisableGattNotification, status=0x{:02x}, value_handle=0x{:04x}", - register_status, value_handle); + BTA_GATTC_DeregisterForNotifications(gatt_if_, address, value_handle); + log::debug("DisableGattNotification, status=0x{:02x}, value_handle=0x{:04x}", register_status, + value_handle); - if (register_status != GATT_SUCCESS) return; + if (register_status != GATT_SUCCESS) { + return; + } } } - void SirkValueReadCompleteDuringPairing(tGATT_STATUS status, - const RawAddress& address, - uint8_t sirk_type, - Octet16& received_sirk) { + void SirkValueReadCompleteDuringPairing(tGATT_STATUS status, const RawAddress& address, + uint8_t sirk_type, Octet16& received_sirk) { log::info("{}, status: 0x{:02x}", address, status); auto device = FindDeviceByAddress(address); @@ -2258,8 +2189,7 @@ class CsisClientImpl : public CsisClient { */ auto csis_group = FindCsisGroup(group_id_to_join); if (!csis_group) { - log::error("Group {} removed during paring a set member", - group_id_to_join); + log::error("Group {} removed during paring a set member", group_id_to_join); RemoveDevice(address); BTA_DmSirkConfirmDeviceReply(address, false); return; @@ -2292,8 +2222,7 @@ class CsisClientImpl : public CsisClient { * that its SIRK is different. Device connection was triggered by RSI * match for group. */ - log::error("Joining device {}, does not match any existig group", - address); + log::error("Joining device {}, does not match any existig group", address); BTA_DmSirkConfirmDeviceReply(address, false); return; } @@ -2322,17 +2251,16 @@ class CsisClientImpl : public CsisClient { auto group_id_to_join = device->GetExpectedGroupIdMember(); if (group_id_to_join == bluetooth::groups::kGroupUnknown) { log::warn( - "Device {} (conn_id=0x{:04x}) is already known to CSIS (# of " - "instances={}) but it is not scheduled to join any group.", - address, device->conn_id, device->GetNumberOfCsisInstances()); + "Device {} (conn_id=0x{:04x}) is already known to CSIS (# of " + "instances={}) but it is not scheduled to join any group.", + address, device->conn_id, device->GetNumberOfCsisInstances()); BTA_DmSirkConfirmDeviceReply(address, true); return; } - if (!gatt_cl_read_sirk_req( - address, - base::BindOnce(&CsisClientImpl::SirkValueReadCompleteDuringPairing, - weak_factory_.GetWeakPtr()))) { + if (!gatt_cl_read_sirk_req(address, + base::BindOnce(&CsisClientImpl::SirkValueReadCompleteDuringPairing, + weak_factory_.GetWeakPtr()))) { log::error("Could not read SIKR of {}", address); BTA_DmSirkConfirmDeviceReply(address, false); return; @@ -2351,28 +2279,36 @@ class CsisClientImpl : public CsisClient { }; class DeviceGroupsCallbacksImpl : public DeviceGroupsCallbacks { - public: - void OnGroupAdded(const RawAddress& address, const bluetooth::Uuid& uuid, - int group_id) override { - if (instance) instance->OnGroupAddedCb(address, uuid, group_id); +public: + void OnGroupAdded(const RawAddress& address, const bluetooth::Uuid& uuid, int group_id) override { + if (instance) { + instance->OnGroupAddedCb(address, uuid, group_id); + } } void OnGroupMemberAdded(const RawAddress& address, int group_id) override { - if (instance) instance->OnGroupMemberAddedCb(address, group_id); + if (instance) { + instance->OnGroupMemberAddedCb(address, group_id); + } } void OnGroupRemoved(const bluetooth::Uuid& uuid, int group_id) override { - if (instance) instance->OnGroupRemovedCb(uuid, group_id); + if (instance) { + instance->OnGroupRemovedCb(uuid, group_id); + } } void OnGroupMemberRemoved(const RawAddress& address, int group_id) override { - if (instance) instance->OnGroupMemberRemovedCb(address, group_id); + if (instance) { + instance->OnGroupMemberRemovedCb(address, group_id); + } } - void OnGroupAddFromStorage(const RawAddress& address, - const bluetooth::Uuid& uuid, + void OnGroupAddFromStorage(const RawAddress& address, const bluetooth::Uuid& uuid, int group_id) override { - if (instance) instance->OnGroupAddFromStorageCb(address, uuid, group_id); + if (instance) { + instance->OnGroupAddFromStorageCb(address, uuid, group_id); + } } }; @@ -2381,8 +2317,7 @@ DeviceGroupsCallbacksImpl deviceGroupsCallbacksImpl; } // namespace -void CsisClient::Initialize(bluetooth::csis::CsisClientCallbacks* callbacks, - Closure initCb) { +void CsisClient::Initialize(bluetooth::csis::CsisClientCallbacks* callbacks, Closure initCb) { std::scoped_lock lock(instance_mutex); if (instance) { log::info("Already initialized!"); @@ -2400,8 +2335,7 @@ CsisClient* CsisClient::Get(void) { return instance; } -void CsisClient::AddFromStorage(const RawAddress& addr, - const std::vector& in) { +void CsisClient::AddFromStorage(const RawAddress& addr, const std::vector& in) { if (!instance) { log::error("Not initialized yet!"); return; @@ -2410,8 +2344,7 @@ void CsisClient::AddFromStorage(const RawAddress& addr, instance->AddFromStorage(addr, in); } -bool CsisClient::GetForStorage(const RawAddress& addr, - std::vector& out) { +bool CsisClient::GetForStorage(const RawAddress& addr, std::vector& out) { if (!instance) { log::error("Not initialized yet!"); return false; @@ -2435,6 +2368,8 @@ void CsisClient::CleanUp() { void CsisClient::DebugDump(int fd) { std::scoped_lock lock(instance_mutex); dprintf(fd, "Coordinated Set Service Client:\n"); - if (instance) instance->Dump(fd); + if (instance) { + instance->Dump(fd); + } dprintf(fd, "\n"); } diff --git a/system/bta/csis/csis_client_test.cc b/system/bta/csis/csis_client_test.cc index e2858a47885..f4065c15fe6 100644 --- a/system/bta/csis/csis_client_test.cc +++ b/system/bta/csis/csis_client_test.cc @@ -36,11 +36,10 @@ #include "stack/include/bt_uuid16.h" #include "test/common/mock_functions.h" -bool gatt_cl_read_sirk_req( - const RawAddress& peer_bda, - base::OnceCallback - cb) { +bool gatt_cl_read_sirk_req(const RawAddress& peer_bda, + base::OnceCallback + cb) { return true; } @@ -73,118 +72,92 @@ using testing::SetArgPointee; using testing::WithArg; // Disables most likely false-positives from base::SplitString() -extern "C" const char* __asan_default_options() { - return "detect_container_overflow=0"; -} +extern "C" const char* __asan_default_options() { return "detect_container_overflow=0"; } RawAddress GetTestAddress(int index) { EXPECT_LT(index, UINT8_MAX); - RawAddress result = { - {0xC0, 0xDE, 0xC0, 0xDE, 0x00, static_cast(index)}}; + RawAddress result = {{0xC0, 0xDE, 0xC0, 0xDE, 0x00, static_cast(index)}}; return result; } /* Csis lock callback */ class MockCsisLockCallback { - public: +public: MockCsisLockCallback() = default; MockCsisLockCallback(const MockCsisLockCallback&) = delete; MockCsisLockCallback& operator=(const MockCsisLockCallback&) = delete; ~MockCsisLockCallback() = default; - MOCK_METHOD((void), CsisGroupLockCb, - (int group_id, bool locked, CsisGroupLockStatus status)); + MOCK_METHOD((void), CsisGroupLockCb, (int group_id, bool locked, CsisGroupLockStatus status)); }; static MockCsisLockCallback* csis_lock_callback_mock; -void SetMockCsisLockCallback(MockCsisLockCallback* mock) { - csis_lock_callback_mock = mock; -} +void SetMockCsisLockCallback(MockCsisLockCallback* mock) { csis_lock_callback_mock = mock; } /* Csis callbacks to JNI */ class MockCsisCallbacks : public CsisClientCallbacks { - public: +public: MockCsisCallbacks() = default; MockCsisCallbacks(const MockCsisCallbacks&) = delete; MockCsisCallbacks& operator=(const MockCsisCallbacks&) = delete; ~MockCsisCallbacks() override = default; - MOCK_METHOD((void), OnConnectionState, - (const RawAddress& address, ConnectionState state), (override)); + MOCK_METHOD((void), OnConnectionState, (const RawAddress& address, ConnectionState state), + (override)); MOCK_METHOD((void), OnDeviceAvailable, - (const RawAddress& address, int group_id, int group_size, - int rank, const bluetooth::Uuid& uuid), + (const RawAddress& address, int group_id, int group_size, int rank, + const bluetooth::Uuid& uuid), (override)); - MOCK_METHOD((void), OnSetMemberAvailable, - (const RawAddress& address, int group_id), (override)); + MOCK_METHOD((void), OnSetMemberAvailable, (const RawAddress& address, int group_id), (override)); MOCK_METHOD((void), OnGroupLockChanged, - (int group_id, bool locked, - bluetooth::csis::CsisGroupLockStatus status), - (override)); + (int group_id, bool locked, bluetooth::csis::CsisGroupLockStatus status), (override)); MOCK_METHOD((void), OnGattCsisWriteLockRsp, - (uint16_t conn_id, tGATT_STATUS status, uint16_t handle, - void* data)); + (uint16_t conn_id, tGATT_STATUS status, uint16_t handle, void* data)); }; class CsisClientTest : public ::testing::Test { - private: - void set_sample_cap_included_database(uint16_t conn_id, bool csis, - bool csis_broken, uint8_t rank, +private: + void set_sample_cap_included_database(uint16_t conn_id, bool csis, bool csis_broken, uint8_t rank, uint8_t sirk_msb = 1) { gatt::DatabaseBuilder builder; builder.AddService(0x0001, 0x0003, Uuid::From16Bit(0x1800), true); - builder.AddCharacteristic(0x0002, 0x0003, Uuid::From16Bit(0x2a00), - GATT_CHAR_PROP_BIT_READ); + builder.AddCharacteristic(0x0002, 0x0003, Uuid::From16Bit(0x2a00), GATT_CHAR_PROP_BIT_READ); if (csis) { - builder.AddService(0x0005, 0x0009, - bluetooth::Uuid::From16Bit(UUID_COMMON_AUDIO_SERVICE), + builder.AddService(0x0005, 0x0009, bluetooth::Uuid::From16Bit(UUID_COMMON_AUDIO_SERVICE), true); builder.AddIncludedService(0x0006, kCsisServiceUuid, 0x0010, 0x0030); builder.AddService(0x0010, 0x0030, kCsisServiceUuid, true); - builder.AddCharacteristic( - 0x0020, 0x0021, kCsisSirkUuid, - GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY); + builder.AddCharacteristic(0x0020, 0x0021, kCsisSirkUuid, + GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY); - builder.AddDescriptor(0x0022, - Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); + builder.AddDescriptor(0x0022, Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); + builder.AddCharacteristic(0x0023, 0x0024, kCsisSizeUuid, + GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY); + builder.AddDescriptor(0x0025, Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); builder.AddCharacteristic( - 0x0023, 0x0024, kCsisSizeUuid, - GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY); - builder.AddDescriptor(0x0025, - Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); - builder.AddCharacteristic(0x0026, 0x0027, kCsisLockUuid, - GATT_CHAR_PROP_BIT_READ | - GATT_CHAR_PROP_BIT_NOTIFY | - GATT_CHAR_PROP_BIT_WRITE); - builder.AddDescriptor(0x0028, - Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); - builder.AddCharacteristic(0x0029, 0x0030, kCsisRankUuid, - GATT_CHAR_PROP_BIT_READ); + 0x0026, 0x0027, kCsisLockUuid, + GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY | GATT_CHAR_PROP_BIT_WRITE); + builder.AddDescriptor(0x0028, Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); + builder.AddCharacteristic(0x0029, 0x0030, kCsisRankUuid, GATT_CHAR_PROP_BIT_READ); } if (csis_broken) { - builder.AddCharacteristic( - 0x0020, 0x0021, kCsisSirkUuid, - GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY); + builder.AddCharacteristic(0x0020, 0x0021, kCsisSirkUuid, + GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY); - builder.AddDescriptor(0x0022, - Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); + builder.AddDescriptor(0x0022, Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); } - builder.AddService(0x0090, 0x0093, - Uuid::From16Bit(UUID_SERVCLASS_GATT_SERVER), true); - builder.AddCharacteristic(0x0091, 0x0092, - Uuid::From16Bit(GATT_UUID_GATT_SRV_CHGD), + builder.AddService(0x0090, 0x0093, Uuid::From16Bit(UUID_SERVCLASS_GATT_SERVER), true); + builder.AddCharacteristic(0x0091, 0x0092, Uuid::From16Bit(GATT_UUID_GATT_SRV_CHGD), GATT_CHAR_PROP_BIT_NOTIFY); - builder.AddDescriptor(0x0093, - Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); + builder.AddDescriptor(0x0093, Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); services_map[conn_id] = builder.Build().Services(); ON_CALL(gatt_queue, ReadCharacteristic(conn_id, _, _, _)) - .WillByDefault( - Invoke([rank, sirk_msb](uint16_t conn_id, uint16_t handle, - GATT_READ_OP_CB cb, void* cb_data) -> void { + .WillByDefault(Invoke([rank, sirk_msb](uint16_t conn_id, uint16_t handle, + GATT_READ_OP_CB cb, void* cb_data) -> void { std::vector value; switch (handle) { @@ -211,60 +184,45 @@ class CsisClientTest : public ::testing::Test { return; } - cb(conn_id, GATT_SUCCESS, handle, value.size(), value.data(), - cb_data); + cb(conn_id, GATT_SUCCESS, handle, value.size(), value.data(), cb_data); })); } - void set_sample_database(uint16_t conn_id, bool csis, bool csis_broken, - uint8_t rank, uint8_t sirk_msb = 1) { + void set_sample_database(uint16_t conn_id, bool csis, bool csis_broken, uint8_t rank, + uint8_t sirk_msb = 1) { gatt::DatabaseBuilder builder; builder.AddService(0x0001, 0x0003, Uuid::From16Bit(0x1800), true); - builder.AddCharacteristic(0x0002, 0x0003, Uuid::From16Bit(0x2a00), - GATT_CHAR_PROP_BIT_READ); + builder.AddCharacteristic(0x0002, 0x0003, Uuid::From16Bit(0x2a00), GATT_CHAR_PROP_BIT_READ); if (csis) { builder.AddService(0x0010, 0x0030, kCsisServiceUuid, true); - builder.AddCharacteristic( - 0x0020, 0x0021, kCsisSirkUuid, - GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY); + builder.AddCharacteristic(0x0020, 0x0021, kCsisSirkUuid, + GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY); - builder.AddDescriptor(0x0022, - Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); + builder.AddDescriptor(0x0022, Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); + builder.AddCharacteristic(0x0023, 0x0024, kCsisSizeUuid, + GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY); + builder.AddDescriptor(0x0025, Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); builder.AddCharacteristic( - 0x0023, 0x0024, kCsisSizeUuid, - GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY); - builder.AddDescriptor(0x0025, - Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); - builder.AddCharacteristic(0x0026, 0x0027, kCsisLockUuid, - GATT_CHAR_PROP_BIT_READ | - GATT_CHAR_PROP_BIT_NOTIFY | - GATT_CHAR_PROP_BIT_WRITE); - builder.AddDescriptor(0x0028, - Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); - builder.AddCharacteristic(0x0029, 0x0030, kCsisRankUuid, - GATT_CHAR_PROP_BIT_READ); + 0x0026, 0x0027, kCsisLockUuid, + GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY | GATT_CHAR_PROP_BIT_WRITE); + builder.AddDescriptor(0x0028, Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); + builder.AddCharacteristic(0x0029, 0x0030, kCsisRankUuid, GATT_CHAR_PROP_BIT_READ); } if (csis_broken) { - builder.AddCharacteristic( - 0x0020, 0x0021, kCsisSirkUuid, - GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY); + builder.AddCharacteristic(0x0020, 0x0021, kCsisSirkUuid, + GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY); - builder.AddDescriptor(0x0022, - Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); + builder.AddDescriptor(0x0022, Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); } - builder.AddService(0x0090, 0x0093, - Uuid::From16Bit(UUID_SERVCLASS_GATT_SERVER), true); - builder.AddCharacteristic(0x0091, 0x0092, - Uuid::From16Bit(GATT_UUID_GATT_SRV_CHGD), + builder.AddService(0x0090, 0x0093, Uuid::From16Bit(UUID_SERVCLASS_GATT_SERVER), true); + builder.AddCharacteristic(0x0091, 0x0092, Uuid::From16Bit(GATT_UUID_GATT_SRV_CHGD), GATT_CHAR_PROP_BIT_NOTIFY); - builder.AddDescriptor(0x0093, - Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); + builder.AddDescriptor(0x0093, Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); services_map[conn_id] = builder.Build().Services(); ON_CALL(gatt_queue, ReadCharacteristic(conn_id, _, _, _)) - .WillByDefault( - Invoke([rank, sirk_msb](uint16_t conn_id, uint16_t handle, - GATT_READ_OP_CB cb, void* cb_data) -> void { + .WillByDefault(Invoke([rank, sirk_msb](uint16_t conn_id, uint16_t handle, + GATT_READ_OP_CB cb, void* cb_data) -> void { std::vector value; switch (handle) { @@ -287,144 +245,119 @@ class CsisClientTest : public ::testing::Test { value.assign(1, rank); break; default: - ASSERT_TRUE(false); + FAIL(); return; } - cb(conn_id, GATT_SUCCESS, handle, value.size(), value.data(), - cb_data); + cb(conn_id, GATT_SUCCESS, handle, value.size(), value.data(), cb_data); })); } - void set_sample_database_double_csis(uint16_t conn_id, uint8_t rank_1, - uint8_t rank_2, bool broken, - uint8_t sirk1_infill = 1, + void set_sample_database_double_csis(uint16_t conn_id, uint8_t rank_1, uint8_t rank_2, + bool broken, uint8_t sirk1_infill = 1, uint8_t sirk2_infill = 2) { gatt::DatabaseBuilder builder; builder.AddService(0x0001, 0x0003, Uuid::From16Bit(0x1800), true); - builder.AddCharacteristic(0x0002, 0x0003, Uuid::From16Bit(0x2a00), - GATT_CHAR_PROP_BIT_READ); - builder.AddService(0x0010, 0x0026, bluetooth::Uuid::From16Bit(0x1850), - true); + builder.AddCharacteristic(0x0002, 0x0003, Uuid::From16Bit(0x2a00), GATT_CHAR_PROP_BIT_READ); + builder.AddService(0x0010, 0x0026, bluetooth::Uuid::From16Bit(0x1850), true); builder.AddIncludedService(0x0011, kCsisServiceUuid, 0x0031, 0x0041); - builder.AddCharacteristic( - 0x0031, 0x0032, kCsisSirkUuid, - GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY); + builder.AddCharacteristic(0x0031, 0x0032, kCsisSirkUuid, + GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY); - builder.AddDescriptor(0x0033, - Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); + builder.AddDescriptor(0x0033, Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); + builder.AddCharacteristic(0x0034, 0x0035, kCsisSizeUuid, + GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY); + builder.AddDescriptor(0x0036, Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); builder.AddCharacteristic( - 0x0034, 0x0035, kCsisSizeUuid, - GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY); - builder.AddDescriptor(0x0036, - Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); - builder.AddCharacteristic(0x0037, 0x0038, kCsisLockUuid, - GATT_CHAR_PROP_BIT_READ | - GATT_CHAR_PROP_BIT_NOTIFY | - GATT_CHAR_PROP_BIT_WRITE); - builder.AddDescriptor(0x0039, - Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); - builder.AddCharacteristic(0x0040, 0x0041, kCsisRankUuid, - GATT_CHAR_PROP_BIT_READ); + 0x0037, 0x0038, kCsisLockUuid, + GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY | GATT_CHAR_PROP_BIT_WRITE); + builder.AddDescriptor(0x0039, Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); + builder.AddCharacteristic(0x0040, 0x0041, kCsisRankUuid, GATT_CHAR_PROP_BIT_READ); if (broken) { - builder.AddCharacteristic( - 0x0020, 0x0021, kCsisSirkUuid, - GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY); + builder.AddCharacteristic(0x0020, 0x0021, kCsisSirkUuid, + GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY); - builder.AddDescriptor(0x0022, - Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); + builder.AddDescriptor(0x0022, Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); } - builder.AddService(0x0042, 0x0044, bluetooth::Uuid::From16Bit(0x1860), - true); + builder.AddService(0x0042, 0x0044, bluetooth::Uuid::From16Bit(0x1860), true); builder.AddIncludedService(0x0043, kCsisServiceUuid, 0x0045, 0x0055); - builder.AddCharacteristic( - 0x0045, 0x0046, kCsisSirkUuid, - GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY); + builder.AddCharacteristic(0x0045, 0x0046, kCsisSirkUuid, + GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY); - builder.AddDescriptor(0x0047, - Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); + builder.AddDescriptor(0x0047, Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); + builder.AddCharacteristic(0x0048, 0x0049, kCsisSizeUuid, + GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY); + builder.AddDescriptor(0x0050, Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); builder.AddCharacteristic( - 0x0048, 0x0049, kCsisSizeUuid, - GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY); - builder.AddDescriptor(0x0050, - Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); - builder.AddCharacteristic(0x0051, 0x0052, kCsisLockUuid, - GATT_CHAR_PROP_BIT_READ | - GATT_CHAR_PROP_BIT_NOTIFY | - GATT_CHAR_PROP_BIT_WRITE); - builder.AddDescriptor(0x0053, - Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); - builder.AddCharacteristic(0x0054, 0x0055, kCsisRankUuid, - GATT_CHAR_PROP_BIT_READ); - - builder.AddService(0x0090, 0x0093, - Uuid::From16Bit(UUID_SERVCLASS_GATT_SERVER), true); - builder.AddCharacteristic(0x0091, 0x0092, - Uuid::From16Bit(GATT_UUID_GATT_SRV_CHGD), + 0x0051, 0x0052, kCsisLockUuid, + GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY | GATT_CHAR_PROP_BIT_WRITE); + builder.AddDescriptor(0x0053, Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); + builder.AddCharacteristic(0x0054, 0x0055, kCsisRankUuid, GATT_CHAR_PROP_BIT_READ); + + builder.AddService(0x0090, 0x0093, Uuid::From16Bit(UUID_SERVCLASS_GATT_SERVER), true); + builder.AddCharacteristic(0x0091, 0x0092, Uuid::From16Bit(GATT_UUID_GATT_SRV_CHGD), GATT_CHAR_PROP_BIT_NOTIFY); - builder.AddDescriptor(0x0093, - Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); + builder.AddDescriptor(0x0093, Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); services_map[conn_id] = builder.Build().Services(); ON_CALL(gatt_queue, ReadCharacteristic(conn_id, _, _, _)) - .WillByDefault(Invoke([sirk1_infill, sirk2_infill, rank_1, rank_2]( - uint16_t conn_id, uint16_t handle, - GATT_READ_OP_CB cb, void* cb_data) -> void { - std::vector value; - - switch (handle) { - case 0x0003: - /* device name */ - value.resize(20); - break; - case 0x0032: - value.resize(17); - value.assign(17, sirk1_infill); - value[0] = 1; // Plain text SIRK - break; - case 0x0035: - value.resize(1); - value.assign(1, 2); - break; - case 0x0038: - value.resize(1); - break; - case 0x0041: - value.resize(1); - value.assign(1, rank_1); - break; - case 0x0046: - value.resize(17); - value.assign(17, sirk2_infill); - value[0] = 1; // Plain text SIRK - break; - case 0x0049: - value.resize(1); - value.assign(1, 2); - break; - case 0x0052: - value.resize(1); - break; - case 0x0055: - value.resize(1); - value.assign(1, rank_2); - break; - default: - log::error("Unknown handle? {}", handle); - ASSERT_TRUE(false); - return; - } + .WillByDefault(Invoke([sirk1_infill, sirk2_infill, rank_1, rank_2]( + uint16_t conn_id, uint16_t handle, GATT_READ_OP_CB cb, + void* cb_data) -> void { + std::vector value; + + switch (handle) { + case 0x0003: + /* device name */ + value.resize(20); + break; + case 0x0032: + value.resize(17); + value.assign(17, sirk1_infill); + value[0] = 1; // Plain text SIRK + break; + case 0x0035: + value.resize(1); + value.assign(1, 2); + break; + case 0x0038: + value.resize(1); + break; + case 0x0041: + value.resize(1); + value.assign(1, rank_1); + break; + case 0x0046: + value.resize(17); + value.assign(17, sirk2_infill); + value[0] = 1; // Plain text SIRK + break; + case 0x0049: + value.resize(1); + value.assign(1, 2); + break; + case 0x0052: + value.resize(1); + break; + case 0x0055: + value.resize(1); + value.assign(1, rank_2); + break; + default: + log::error("Unknown handle? {}", handle); + FAIL(); + return; + } - cb(conn_id, GATT_SUCCESS, handle, value.size(), value.data(), - cb_data); - })); + cb(conn_id, GATT_SUCCESS, handle, value.size(), value.data(), cb_data); + })); } - protected: +protected: void SetUp(void) override { reset_mock_function_count_map(); bluetooth::manager::SetMockBtmInterface(&btm_interface); @@ -434,32 +367,28 @@ class CsisClientTest : public ::testing::Test { SetMockCsisLockCallback(&csis_lock_cb); callbacks.reset(new MockCsisCallbacks()); - ON_CALL(btm_interface, IsLinkKeyKnown(_, _)) - .WillByDefault(DoAll(Return(true))); + ON_CALL(btm_interface, IsLinkKeyKnown(_, _)).WillByDefault(DoAll(Return(true))); - ON_CALL(btm_interface, BTM_IsEncrypted(_, _)) - .WillByDefault(DoAll(Return(true))); + ON_CALL(btm_interface, BTM_IsEncrypted(_, _)).WillByDefault(DoAll(Return(true))); ON_CALL(gatt_interface, GetCharacteristic(_, _)) - .WillByDefault( - Invoke([&](uint16_t conn_id, - uint16_t handle) -> const gatt::Characteristic* { - std::list& services = services_map[conn_id]; - for (auto const& service : services) { - for (auto const& characteristic : service.characteristics) { - if (characteristic.value_handle == handle) { - return &characteristic; - } - } - } - - return nullptr; - })); + .WillByDefault( + Invoke([&](uint16_t conn_id, uint16_t handle) -> const gatt::Characteristic* { + std::list& services = services_map[conn_id]; + for (auto const& service : services) { + for (auto const& characteristic : service.characteristics) { + if (characteristic.value_handle == handle) { + return &characteristic; + } + } + } + + return nullptr; + })); // default action for GetOwningService function call ON_CALL(gatt_interface, GetOwningService(_, _)) - .WillByDefault(Invoke( - [&](uint16_t conn_id, uint16_t handle) -> const gatt::Service* { + .WillByDefault(Invoke([&](uint16_t conn_id, uint16_t handle) -> const gatt::Service* { std::list& services = services_map[conn_id]; for (auto const& service : services) { if (service.handle <= handle && service.end_handle >= handle) { @@ -472,28 +401,26 @@ class CsisClientTest : public ::testing::Test { // default action for GetServices function call ON_CALL(gatt_interface, GetServices(_)) - .WillByDefault(WithArg<0>( - Invoke([&](uint16_t conn_id) -> std::list* { + .WillByDefault(WithArg<0>(Invoke([&](uint16_t conn_id) -> std::list* { return &services_map[conn_id]; }))); // default action for RegisterForNotifications function call ON_CALL(gatt_interface, RegisterForNotifications(gatt_if, _, _)) - .WillByDefault(Return(GATT_SUCCESS)); + .WillByDefault(Return(GATT_SUCCESS)); // default action for DeregisterForNotifications function call ON_CALL(gatt_interface, DeregisterForNotifications(gatt_if, _, _)) - .WillByDefault(Return(GATT_SUCCESS)); + .WillByDefault(Return(GATT_SUCCESS)); // default action for WriteDescriptor function call ON_CALL(gatt_queue, WriteDescriptor(_, _, _, _, _, _)) - .WillByDefault( - Invoke([](uint16_t conn_id, uint16_t handle, - std::vector value, tGATT_WRITE_TYPE write_type, - GATT_WRITE_OP_CB cb, void* cb_data) -> void { - if (cb) - cb(conn_id, GATT_SUCCESS, handle, value.size(), value.data(), - cb_data); + .WillByDefault(Invoke([](uint16_t conn_id, uint16_t handle, std::vector value, + tGATT_WRITE_TYPE write_type, GATT_WRITE_OP_CB cb, + void* cb_data) -> void { + if (cb) { + cb(conn_id, GATT_SUCCESS, handle, value.size(), value.data(), cb_data); + } })); } @@ -508,10 +435,8 @@ class CsisClientTest : public ::testing::Test { void TestAppRegister(void) { BtaAppRegisterCallback app_register_callback; EXPECT_CALL(gatt_interface, AppRegister(_, _, _)) - .WillOnce(DoAll(SaveArg<0>(&gatt_callback), - SaveArg<1>(&app_register_callback))); - CsisClient::Initialize(callbacks.get(), - Bind(&btif_storage_load_bonded_csis_devices)); + .WillOnce(DoAll(SaveArg<0>(&gatt_callback), SaveArg<1>(&app_register_callback))); + CsisClient::Initialize(callbacks.get(), Bind(&btif_storage_load_bonded_csis_devices)); ASSERT_TRUE(gatt_callback); ASSERT_TRUE(app_register_callback); app_register_callback.Run(gatt_if, GATT_SUCCESS); @@ -528,11 +453,9 @@ class CsisClientTest : public ::testing::Test { void TestConnect(const RawAddress& address, bool encrypted = true) { // by default indicate link as encrypted ON_CALL(btm_interface, GetSecurityFlagsByTransport(address, NotNull(), _)) - .WillByDefault( - DoAll(SetArgPointee<1>(BTM_SEC_FLAG_ENCRYPTED), Return(encrypted))); + .WillByDefault(DoAll(SetArgPointee<1>(BTM_SEC_FLAG_ENCRYPTED), Return(encrypted))); - EXPECT_CALL(gatt_interface, - Open(gatt_if, address, BTM_BLE_DIRECT_CONNECTION, _)); + EXPECT_CALL(gatt_interface, Open(gatt_if, address, BTM_BLE_DIRECT_CONNECTION, _)); CsisClient::Get()->Connect(address); Mock::VerifyAndClearExpectations(&gatt_interface); Mock::VerifyAndClearExpectations(&btm_interface); @@ -541,8 +464,7 @@ class CsisClientTest : public ::testing::Test { void TestDisconnect(const RawAddress& address, uint16_t conn_id) { if (conn_id != GATT_INVALID_CONN_ID) { EXPECT_CALL(gatt_interface, Close(conn_id)); - EXPECT_CALL(*callbacks, OnConnectionState(test_address, - ConnectionState::DISCONNECTED)); + EXPECT_CALL(*callbacks, OnConnectionState(test_address, ConnectionState::DISCONNECTED)); } else { EXPECT_CALL(gatt_interface, CancelOpen(_, address, _)); } @@ -552,20 +474,15 @@ class CsisClientTest : public ::testing::Test { void TestAddFromStorage(const RawAddress& address, uint16_t conn_id, std::vector& storage_group_buf, std::vector& storage_buf) { - EXPECT_CALL(*callbacks, - OnConnectionState(address, ConnectionState::CONNECTED)) - .Times(1); - EXPECT_CALL(*callbacks, OnDeviceAvailable(address, _, _, _, _)) - .Times(AtLeast(1)); - - EXPECT_CALL(gatt_interface, - Open(gatt_if, address, BTM_BLE_DIRECT_CONNECTION, true)) - .WillOnce(Invoke([this, conn_id](tGATT_IF client_if, - const RawAddress& remote_bda, - bool is_direct, bool opportunistic) { - InjectConnectedEvent(remote_bda, conn_id); - GetSearchCompleteEvent(conn_id); - })); + EXPECT_CALL(*callbacks, OnConnectionState(address, ConnectionState::CONNECTED)).Times(1); + EXPECT_CALL(*callbacks, OnDeviceAvailable(address, _, _, _, _)).Times(AtLeast(1)); + + EXPECT_CALL(gatt_interface, Open(gatt_if, address, BTM_BLE_DIRECT_CONNECTION, true)) + .WillOnce(Invoke([this, conn_id](tGATT_IF client_if, const RawAddress& remote_bda, + bool is_direct, bool opportunistic) { + InjectConnectedEvent(remote_bda, conn_id); + GetSearchCompleteEvent(conn_id); + })); DeviceGroups::AddFromStorage(address, storage_group_buf); CsisClient::AddFromStorage(address, storage_buf); @@ -573,8 +490,8 @@ class CsisClientTest : public ::testing::Test { void InjectEncryptionEvent(const RawAddress& test_address, uint16_t conn_id) { tBTA_GATTC_ENC_CMPL_CB event_data = { - .client_if = static_cast(conn_id), - .remote_bda = test_address, + .client_if = static_cast(conn_id), + .remote_bda = test_address, }; gatt_callback(BTA_GATTC_ENC_CMPL_CB_EVT, (tBTA_GATTC*)&event_data); @@ -594,15 +511,14 @@ class CsisClientTest : public ::testing::Test { gatt_callback(BTA_GATTC_OPEN_EVT, (tBTA_GATTC*)&event_data); } - void InjectDisconnectedEvent( - const RawAddress& address, uint16_t conn_id, - tGATT_DISCONN_REASON reason = GATT_CONN_TERMINATE_PEER_USER) { + void InjectDisconnectedEvent(const RawAddress& address, uint16_t conn_id, + tGATT_DISCONN_REASON reason = GATT_CONN_TERMINATE_PEER_USER) { tBTA_GATTC_CLOSE event_data = { - .conn_id = conn_id, - .status = GATT_SUCCESS, - .client_if = gatt_if, - .remote_bda = address, - .reason = reason, + .conn_id = conn_id, + .status = GATT_SUCCESS, + .client_if = gatt_if, + .remote_bda = address, + .reason = reason, }; gatt_callback(BTA_GATTC_CLOSE_EVT, (tBTA_GATTC*)&event_data); @@ -610,8 +526,8 @@ class CsisClientTest : public ::testing::Test { void GetSearchCompleteEvent(uint16_t conn_id) { tBTA_GATTC_SEARCH_CMPL event_data = { - .conn_id = conn_id, - .status = GATT_SUCCESS, + .conn_id = conn_id, + .status = GATT_SUCCESS, }; gatt_callback(BTA_GATTC_SEARCH_CMPL_EVT, (tBTA_GATTC*)&event_data); @@ -624,30 +540,25 @@ class CsisClientTest : public ::testing::Test { TestConnect(address); InjectConnectedEvent(address, conn_id); - EXPECT_CALL(gatt_queue, ReadCharacteristic(conn_id, _, _, _)) - .WillRepeatedly(DoDefault()); + EXPECT_CALL(gatt_queue, ReadCharacteristic(conn_id, _, _, _)).WillRepeatedly(DoDefault()); for (auto const& handle : handles) { - EXPECT_CALL(gatt_queue, ReadCharacteristic(conn_id, handle, _, _)) - .WillOnce(DoDefault()); + EXPECT_CALL(gatt_queue, ReadCharacteristic(conn_id, handle, _, _)).WillOnce(DoDefault()); } GetSearchCompleteEvent(conn_id); TestAppUnregister(); } - void TestGattWriteCCC(uint16_t ccc_handle, GattStatus status, - int deregister_times) { + void TestGattWriteCCC(uint16_t ccc_handle, GattStatus status, int deregister_times) { SetSampleDatabaseCsis(1, 1); TestAppRegister(); TestConnect(test_address); InjectConnectedEvent(test_address, 1); - auto WriteDescriptorCbGenerator = [](tGATT_STATUS status, - uint16_t ccc_handle) { - return [status, ccc_handle](uint16_t conn_id, uint16_t handle, - std::vector value, - tGATT_WRITE_TYPE write_type, - GATT_WRITE_OP_CB cb, void* cb_data) -> void { + auto WriteDescriptorCbGenerator = [](tGATT_STATUS status, uint16_t ccc_handle) { + return [status, ccc_handle](uint16_t conn_id, uint16_t handle, std::vector value, + tGATT_WRITE_TYPE write_type, GATT_WRITE_OP_CB cb, + void* cb_data) -> void { if (cb) { if (ccc_handle) { handle = ccc_handle; @@ -659,13 +570,12 @@ class CsisClientTest : public ::testing::Test { // sirk, size, lock EXPECT_CALL(gatt_queue, WriteDescriptor(_, _, _, _, _, _)) - .Times(3) - .WillOnce(Invoke(WriteDescriptorCbGenerator(GATT_SUCCESS, 0))) - .WillOnce(Invoke(WriteDescriptorCbGenerator(GATT_SUCCESS, 0))) - .WillOnce(Invoke(WriteDescriptorCbGenerator(status, ccc_handle))); + .Times(3) + .WillOnce(Invoke(WriteDescriptorCbGenerator(GATT_SUCCESS, 0))) + .WillOnce(Invoke(WriteDescriptorCbGenerator(GATT_SUCCESS, 0))) + .WillOnce(Invoke(WriteDescriptorCbGenerator(status, ccc_handle))); - EXPECT_CALL(gatt_interface, DeregisterForNotifications(_, _, _)) - .Times(deregister_times); + EXPECT_CALL(gatt_interface, DeregisterForNotifications(_, _, _)).Times(deregister_times); GetSearchCompleteEvent(1); Mock::VerifyAndClearExpectations(&gatt_interface); @@ -673,22 +583,20 @@ class CsisClientTest : public ::testing::Test { void GetDisconnectedEvent(const RawAddress& address, uint16_t conn_id) { tBTA_GATTC_CLOSE event_data = { - .conn_id = conn_id, - .status = GATT_SUCCESS, - .client_if = gatt_if, - .remote_bda = address, - .reason = GATT_CONN_TERMINATE_PEER_USER, + .conn_id = conn_id, + .status = GATT_SUCCESS, + .client_if = gatt_if, + .remote_bda = address, + .reason = GATT_CONN_TERMINATE_PEER_USER, }; gatt_callback(BTA_GATTC_CLOSE_EVT, (tBTA_GATTC*)&event_data); } - void SetSampleCapIncludedDatabaseCsis(uint16_t conn_id, uint8_t rank, - uint8_t sirk_msb = 1) { + void SetSampleCapIncludedDatabaseCsis(uint16_t conn_id, uint8_t rank, uint8_t sirk_msb = 1) { set_sample_cap_included_database(conn_id, true, false, rank, sirk_msb); } - void SetSampleDatabaseCsis(uint16_t conn_id, uint8_t rank, - uint8_t sirk_msb = 1) { + void SetSampleDatabaseCsis(uint16_t conn_id, uint8_t rank, uint8_t sirk_msb = 1) { set_sample_database(conn_id, true, false, rank, sirk_msb); } void SetSampleDatabaseNoCsis(uint16_t conn_id, uint8_t rank) { @@ -697,12 +605,10 @@ class CsisClientTest : public ::testing::Test { void SetSampleDatabaseCsisBroken(uint16_t conn_id, uint rank) { set_sample_database(conn_id, false, true, rank); } - void SetSampleDatabaseDoubleCsis(uint16_t conn_id, uint8_t rank_1, - uint8_t rank_2) { + void SetSampleDatabaseDoubleCsis(uint16_t conn_id, uint8_t rank_1, uint8_t rank_2) { set_sample_database_double_csis(conn_id, rank_1, rank_2, false); } - void SetSampleDatabaseDoubleCsisBroken(uint16_t conn_id, uint8_t rank_1, - uint8_t rank_2) { + void SetSampleDatabaseDoubleCsisBroken(uint16_t conn_id, uint8_t rank_1, uint8_t rank_2) { set_sample_database_double_csis(conn_id, rank_1, rank_2, true); } @@ -721,9 +627,7 @@ class CsisClientTest : public ::testing::Test { const RawAddress test_address2 = GetTestAddress(1); }; -TEST_F(CsisClientTest, test_get_uninitialized) { - ASSERT_DEATH(CsisClient::Get(), ""); -} +TEST_F(CsisClientTest, test_get_uninitialized) { ASSERT_DEATH(CsisClient::Get(), ""); } TEST_F(CsisClientTest, test_initialize) { CsisClient::Initialize(callbacks.get(), base::DoNothing()); @@ -805,8 +709,7 @@ TEST_F(CsisClientTest, test_disconnected) { TestAppRegister(); TestConnect(test_address); InjectConnectedEvent(test_address, 1); - EXPECT_CALL(*callbacks, - OnConnectionState(test_address, ConnectionState::DISCONNECTED)); + EXPECT_CALL(*callbacks, OnConnectionState(test_address, ConnectionState::DISCONNECTED)); InjectDisconnectedEvent(test_address, 1); TestAppUnregister(); @@ -818,8 +721,7 @@ TEST_F(CsisClientTest, test_connect_after_remove) { InjectConnectedEvent(test_address, 1); CsisClient::Get()->RemoveDevice(test_address); - EXPECT_CALL(*callbacks, - OnConnectionState(test_address, ConnectionState::DISCONNECTED)); + EXPECT_CALL(*callbacks, OnConnectionState(test_address, ConnectionState::DISCONNECTED)); ON_CALL(btm_interface, IsLinkKeyKnown(_, _)).WillByDefault(Return(false)); CsisClient::Get()->Connect(test_address); Mock::VerifyAndClearExpectations(callbacks.get()); @@ -831,8 +733,7 @@ TEST_F(CsisClientTest, test_discovery_csis_found) { SetSampleDatabaseCsis(1, 1); TestAppRegister(); TestConnect(test_address); - EXPECT_CALL(*callbacks, - OnConnectionState(test_address, ConnectionState::CONNECTED)); + EXPECT_CALL(*callbacks, OnConnectionState(test_address, ConnectionState::CONNECTED)); EXPECT_CALL(*callbacks, OnDeviceAvailable(test_address, _, _, _, _)); InjectConnectedEvent(test_address, 1); GetSearchCompleteEvent(1); @@ -881,7 +782,7 @@ TEST_F(CsisClientTest, test_ccc_reg_fail_out_of_sync) { } class CsisClientCallbackTest : public CsisClientTest { - protected: +protected: const RawAddress test_address = GetTestAddress(0); uint16_t conn_id = 22; @@ -901,11 +802,11 @@ class CsisClientCallbackTest : public CsisClientTest { void GetNotificationEvent(uint16_t handle, std::vector& value) { tBTA_GATTC_NOTIFY event_data = { - .conn_id = conn_id, - .bda = test_address, - .handle = handle, - .len = (uint8_t)value.size(), - .is_notify = true, + .conn_id = conn_id, + .bda = test_address, + .handle = handle, + .len = (uint8_t)value.size(), + .is_notify = true, }; std::copy(value.begin(), value.end(), event_data.value); @@ -915,19 +816,16 @@ class CsisClientCallbackTest : public CsisClientTest { TEST_F(CsisClientCallbackTest, test_on_group_lock_changed_group_not_found) { bool callback_called = false; - EXPECT_CALL( - *callbacks, - OnGroupLockChanged(2, false, CsisGroupLockStatus::FAILED_INVALID_GROUP)); + EXPECT_CALL(*callbacks, OnGroupLockChanged(2, false, CsisGroupLockStatus::FAILED_INVALID_GROUP)); CsisClient::Get()->LockGroup( - 2, true, - base::BindOnce( - [](bool* callback_called, int group_id, bool locked, - CsisGroupLockStatus status) { - if ((group_id == 2) && - (status == CsisGroupLockStatus::FAILED_INVALID_GROUP)) - *callback_called = true; - }, - &callback_called)); + 2, true, + base::BindOnce( + [](bool* callback_called, int group_id, bool locked, CsisGroupLockStatus status) { + if ((group_id == 2) && (status == CsisGroupLockStatus::FAILED_INVALID_GROUP)) { + *callback_called = true; + } + }, + &callback_called)); ASSERT_TRUE(callback_called); } @@ -935,8 +833,7 @@ TEST_F(CsisClientTest, test_get_group_id) { SetSampleDatabaseCsis(1, 1); TestAppRegister(); TestConnect(test_address); - EXPECT_CALL(*callbacks, - OnConnectionState(test_address, ConnectionState::CONNECTED)); + EXPECT_CALL(*callbacks, OnConnectionState(test_address, ConnectionState::CONNECTED)); EXPECT_CALL(*callbacks, OnDeviceAvailable(test_address, _, _, _, _)); InjectConnectedEvent(test_address, 1); GetSearchCompleteEvent(1); @@ -949,26 +846,20 @@ TEST_F(CsisClientTest, test_search_complete_before_encryption) { SetSampleDatabaseCsis(1, 1); TestAppRegister(); TestConnect(test_address, false); - EXPECT_CALL(*callbacks, - OnConnectionState(test_address, ConnectionState::CONNECTED)) - .Times(0); + EXPECT_CALL(*callbacks, OnConnectionState(test_address, ConnectionState::CONNECTED)).Times(0); EXPECT_CALL(*callbacks, OnDeviceAvailable(test_address, _, _, _, _)).Times(0); - ON_CALL(btm_interface, BTM_IsEncrypted(test_address, _)) - .WillByDefault(DoAll(Return(false))); + ON_CALL(btm_interface, BTM_IsEncrypted(test_address, _)).WillByDefault(DoAll(Return(false))); InjectConnectedEvent(test_address, 1); GetSearchCompleteEvent(1); Mock::VerifyAndClearExpectations(callbacks.get()); /* Incject encryption and expect device connection */ - EXPECT_CALL(*callbacks, - OnConnectionState(test_address, ConnectionState::CONNECTED)) - .Times(1); + EXPECT_CALL(*callbacks, OnConnectionState(test_address, ConnectionState::CONNECTED)).Times(1); EXPECT_CALL(*callbacks, OnDeviceAvailable(test_address, _, _, _, _)).Times(1); - ON_CALL(btm_interface, BTM_IsEncrypted(test_address, _)) - .WillByDefault(DoAll(Return(true))); + ON_CALL(btm_interface, BTM_IsEncrypted(test_address, _)).WillByDefault(DoAll(Return(true))); EXPECT_CALL(gatt_interface, ServiceSearchRequest(_, _)).Times(1); InjectEncryptionEvent(test_address, 1); @@ -984,14 +875,11 @@ TEST_F(CsisClientTest, test_disconnect_when_link_key_is_gone) { SetSampleDatabaseCsis(1, 1); TestAppRegister(); TestConnect(test_address, false); - EXPECT_CALL(*callbacks, - OnConnectionState(test_address, ConnectionState::CONNECTED)) - .Times(0); + EXPECT_CALL(*callbacks, OnConnectionState(test_address, ConnectionState::CONNECTED)).Times(0); - ON_CALL(btm_interface, BTM_IsEncrypted(test_address, _)) - .WillByDefault(DoAll(Return(false))); + ON_CALL(btm_interface, BTM_IsEncrypted(test_address, _)).WillByDefault(DoAll(Return(false))); ON_CALL(btm_interface, SetEncryption(test_address, _, _, _, _)) - .WillByDefault(Return(BTM_ERR_KEY_MISSING)); + .WillByDefault(Return(BTM_ERR_KEY_MISSING)); EXPECT_CALL(gatt_interface, Close(1)); @@ -1078,8 +966,7 @@ TEST_F(CsisClientTest, test_set_various_lock_states) { TEST_F(CsisClientTest, test_set_discovery_state_completed) { auto g_1 = std::make_shared(666, bluetooth::Uuid::kEmpty); g_1->SetDiscoveryState(CsisDiscoveryState::CSIS_DISCOVERY_COMPLETED); - ASSERT_EQ(g_1->GetDiscoveryState(), - CsisDiscoveryState::CSIS_DISCOVERY_COMPLETED); + ASSERT_EQ(g_1->GetDiscoveryState(), CsisDiscoveryState::CSIS_DISCOVERY_COMPLETED); } TEST_F(CsisClientTest, test_set_discovery_state_idle) { @@ -1091,20 +978,17 @@ TEST_F(CsisClientTest, test_set_discovery_state_idle) { TEST_F(CsisClientTest, test_set_discovery_state_ongoing) { auto g_1 = std::make_shared(666, bluetooth::Uuid::kEmpty); g_1->SetDiscoveryState(CsisDiscoveryState::CSIS_DISCOVERY_ONGOING); - ASSERT_EQ(g_1->GetDiscoveryState(), - CsisDiscoveryState::CSIS_DISCOVERY_ONGOING); + ASSERT_EQ(g_1->GetDiscoveryState(), CsisDiscoveryState::CSIS_DISCOVERY_ONGOING); } TEST_F(CsisClientTest, test_set_various_discovery_states) { auto g_1 = std::make_shared(666, bluetooth::Uuid::kEmpty); g_1->SetDiscoveryState(CsisDiscoveryState::CSIS_DISCOVERY_COMPLETED); - ASSERT_EQ(g_1->GetDiscoveryState(), - CsisDiscoveryState::CSIS_DISCOVERY_COMPLETED); + ASSERT_EQ(g_1->GetDiscoveryState(), CsisDiscoveryState::CSIS_DISCOVERY_COMPLETED); g_1->SetDiscoveryState(CsisDiscoveryState::CSIS_DISCOVERY_IDLE); ASSERT_EQ(g_1->GetDiscoveryState(), CsisDiscoveryState::CSIS_DISCOVERY_IDLE); g_1->SetDiscoveryState(CsisDiscoveryState::CSIS_DISCOVERY_ONGOING); - ASSERT_EQ(g_1->GetDiscoveryState(), - CsisDiscoveryState::CSIS_DISCOVERY_ONGOING); + ASSERT_EQ(g_1->GetDiscoveryState(), CsisDiscoveryState::CSIS_DISCOVERY_ONGOING); } TEST_F(CsisClientTest, test_get_first_last_device) { @@ -1129,8 +1013,7 @@ TEST_F(CsisClientTest, test_get_set_sirk) { ASSERT_EQ(g_1->GetSirk(), sirk); } -TEST_F(CsisClientTest, - test_not_open_duplicate_active_scan_while_bonding_set_member) { +TEST_F(CsisClientTest, test_not_open_duplicate_active_scan_while_bonding_set_member) { uint16_t conn_id = 0x0001; EXPECT_CALL(dm_interface, BTA_DmBleCsisObserve(true, _)).Times(1); SetSampleDatabaseCsis(conn_id, 1, 1); @@ -1143,8 +1026,7 @@ TEST_F(CsisClientTest, InjectConnectedEvent(test_address, 1); auto ReadCharacteristicCbGenerator = []() { - return [](uint16_t conn_id, uint16_t handle, GATT_READ_OP_CB cb, - void* cb_data) -> void { + return [](uint16_t conn_id, uint16_t handle, GATT_READ_OP_CB cb, void* cb_data) -> void { std::vector value; switch (handle) { case 0x0003: @@ -1182,17 +1064,17 @@ TEST_F(CsisClientTest, // We should read 4 times for sirk, rank, size, and lock characteristics EXPECT_CALL(gatt_queue, ReadCharacteristic(conn_id, _, _, _)) - .Times(4) - .WillOnce(Invoke(ReadCharacteristicCbGenerator())) - .WillOnce(Invoke(ReadCharacteristicCbGenerator())) - .WillOnce(Invoke(ReadCharacteristicCbGenerator())) - .WillOnce(Invoke(ReadCharacteristicCbGenerator())); + .Times(4) + .WillOnce(Invoke(ReadCharacteristicCbGenerator())) + .WillOnce(Invoke(ReadCharacteristicCbGenerator())) + .WillOnce(Invoke(ReadCharacteristicCbGenerator())) + .WillOnce(Invoke(ReadCharacteristicCbGenerator())); // Here is actual active scan request for the first device tBTA_DM_SEARCH_CBACK* p_results_cb = nullptr; EXPECT_CALL(dm_interface, BTA_DmBleCsisObserve(true, _)) - .Times(1) - .WillOnce(DoAll(SaveArg<1>(&p_results_cb))); + .Times(1) + .WillOnce(DoAll(SaveArg<1>(&p_results_cb))); GetSearchCompleteEvent(conn_id); @@ -1234,7 +1116,7 @@ TEST_F(CsisClientTest, test_csis_member_not_found) { tBTA_DM_SEARCH_CBACK* p_results_cb = nullptr; /* Here is actual Active Scan request */ EXPECT_CALL(dm_interface, BTA_DmBleCsisObserve(true, _)) - .WillOnce(DoAll(SaveArg<1>(&p_results_cb))); + .WillOnce(DoAll(SaveArg<1>(&p_results_cb))); TestConnect(test_address); InjectConnectedEvent(test_address, 1); @@ -1258,7 +1140,7 @@ TEST_F(CsisClientTest, test_csis_member_not_found) { } class CsisMultiClientTest : public CsisClientTest { - protected: +protected: const RawAddress test_address_1 = GetTestAddress(1); const RawAddress test_address_2 = GetTestAddress(2); @@ -1270,7 +1152,7 @@ class CsisMultiClientTest : public CsisClientTest { }; class CsisMultiClientTestBroken : public CsisClientTest { - protected: +protected: const RawAddress test_address_1 = GetTestAddress(1); const RawAddress test_address_2 = GetTestAddress(2); @@ -1299,8 +1181,7 @@ TEST_F(CsisMultiClientTest, test_connect_multiple_instances) { TEST_F(CsisMultiClientTest, test_disconnect_multiple_instances) { TestConnect(test_address); InjectConnectedEvent(test_address, 1); - EXPECT_CALL(*callbacks, - OnConnectionState(test_address, ConnectionState::DISCONNECTED)); + EXPECT_CALL(*callbacks, OnConnectionState(test_address, ConnectionState::DISCONNECTED)); InjectDisconnectedEvent(test_address, 1); TestAppUnregister(); @@ -1312,34 +1193,27 @@ TEST_F(CsisMultiClientTest, test_lock_multiple_instances) { InjectConnectedEvent(test_address, 1); GetSearchCompleteEvent(1); - EXPECT_CALL(*callbacks, - OnGroupLockChanged(1, true, CsisGroupLockStatus::SUCCESS)); - EXPECT_CALL(*csis_lock_callback_mock, - CsisGroupLockCb(1, true, CsisGroupLockStatus::SUCCESS)); + EXPECT_CALL(*callbacks, OnGroupLockChanged(1, true, CsisGroupLockStatus::SUCCESS)); + EXPECT_CALL(*csis_lock_callback_mock, CsisGroupLockCb(1, true, CsisGroupLockStatus::SUCCESS)); ON_CALL(gatt_queue, WriteCharacteristic(_, _, _, _, _, _)) - .WillByDefault( - Invoke([](uint16_t conn_id, uint16_t handle, - std::vector value, tGATT_WRITE_TYPE write_type, - GATT_WRITE_OP_CB cb, void* cb_data) -> void { - if (cb) - cb(conn_id, GATT_SUCCESS, handle, value.size(), value.data(), - cb_data); + .WillByDefault(Invoke([](uint16_t conn_id, uint16_t handle, std::vector value, + tGATT_WRITE_TYPE write_type, GATT_WRITE_OP_CB cb, + void* cb_data) -> void { + if (cb) { + cb(conn_id, GATT_SUCCESS, handle, value.size(), value.data(), cb_data); + } })); CsisClient::Get()->LockGroup( - 1, true, - base::BindOnce([](int group_id, bool locked, CsisGroupLockStatus status) { - csis_lock_callback_mock->CsisGroupLockCb(group_id, locked, status); - })); + 1, true, base::BindOnce([](int group_id, bool locked, CsisGroupLockStatus status) { + csis_lock_callback_mock->CsisGroupLockCb(group_id, locked, status); + })); - EXPECT_CALL(*callbacks, - OnGroupLockChanged(2, true, CsisGroupLockStatus::SUCCESS)); - EXPECT_CALL(*csis_lock_callback_mock, - CsisGroupLockCb(2, true, CsisGroupLockStatus::SUCCESS)); + EXPECT_CALL(*callbacks, OnGroupLockChanged(2, true, CsisGroupLockStatus::SUCCESS)); + EXPECT_CALL(*csis_lock_callback_mock, CsisGroupLockCb(2, true, CsisGroupLockStatus::SUCCESS)); CsisClient::Get()->LockGroup( - 2, true, - base::BindOnce([](int group_id, bool locked, CsisGroupLockStatus status) { - csis_lock_callback_mock->CsisGroupLockCb(group_id, locked, status); - })); + 2, true, base::BindOnce([](int group_id, bool locked, CsisGroupLockStatus status) { + csis_lock_callback_mock->CsisGroupLockCb(group_id, locked, status); + })); } TEST_F(CsisMultiClientTest, test_unlock_multiple_instances) { @@ -1348,29 +1222,24 @@ TEST_F(CsisMultiClientTest, test_unlock_multiple_instances) { GetSearchCompleteEvent(1); ON_CALL(gatt_queue, WriteCharacteristic(_, _, _, _, _, _)) - .WillByDefault( - Invoke([](uint16_t conn_id, uint16_t handle, - std::vector value, tGATT_WRITE_TYPE write_type, - GATT_WRITE_OP_CB cb, void* cb_data) -> void { - if (cb) - cb(conn_id, GATT_SUCCESS, handle, value.size(), value.data(), - cb_data); + .WillByDefault(Invoke([](uint16_t conn_id, uint16_t handle, std::vector value, + tGATT_WRITE_TYPE write_type, GATT_WRITE_OP_CB cb, + void* cb_data) -> void { + if (cb) { + cb(conn_id, GATT_SUCCESS, handle, value.size(), value.data(), cb_data); + } })); CsisClient::Get()->LockGroup( - 1, true, - base::BindOnce([](int group_id, bool locked, CsisGroupLockStatus status) { - csis_lock_callback_mock->CsisGroupLockCb(group_id, locked, status); - })); + 1, true, base::BindOnce([](int group_id, bool locked, CsisGroupLockStatus status) { + csis_lock_callback_mock->CsisGroupLockCb(group_id, locked, status); + })); - EXPECT_CALL(*callbacks, - OnGroupLockChanged(1, false, CsisGroupLockStatus::SUCCESS)); - EXPECT_CALL(*csis_lock_callback_mock, - CsisGroupLockCb(1, false, CsisGroupLockStatus::SUCCESS)); + EXPECT_CALL(*callbacks, OnGroupLockChanged(1, false, CsisGroupLockStatus::SUCCESS)); + EXPECT_CALL(*csis_lock_callback_mock, CsisGroupLockCb(1, false, CsisGroupLockStatus::SUCCESS)); CsisClient::Get()->LockGroup( - 1, false, - base::BindOnce([](int group_id, bool locked, CsisGroupLockStatus status) { - csis_lock_callback_mock->CsisGroupLockCb(group_id, locked, status); - })); + 1, false, base::BindOnce([](int group_id, bool locked, CsisGroupLockStatus status) { + csis_lock_callback_mock->CsisGroupLockCb(group_id, locked, status); + })); } TEST_F(CsisMultiClientTest, test_disconnect_locked_multiple_instances) { @@ -1382,36 +1251,29 @@ TEST_F(CsisMultiClientTest, test_disconnect_locked_multiple_instances) { InjectConnectedEvent(test_address2, 2); GetSearchCompleteEvent(2); - EXPECT_CALL(*callbacks, - OnGroupLockChanged(1, true, CsisGroupLockStatus::SUCCESS)); - EXPECT_CALL(*csis_lock_callback_mock, - CsisGroupLockCb(1, true, CsisGroupLockStatus::SUCCESS)); + EXPECT_CALL(*callbacks, OnGroupLockChanged(1, true, CsisGroupLockStatus::SUCCESS)); + EXPECT_CALL(*csis_lock_callback_mock, CsisGroupLockCb(1, true, CsisGroupLockStatus::SUCCESS)); ON_CALL(gatt_queue, WriteCharacteristic(_, _, _, _, _, _)) - .WillByDefault( - Invoke([](uint16_t conn_id, uint16_t handle, - std::vector value, tGATT_WRITE_TYPE write_type, - GATT_WRITE_OP_CB cb, void* cb_data) -> void { - if (cb) - cb(conn_id, GATT_SUCCESS, handle, value.size(), value.data(), - cb_data); + .WillByDefault(Invoke([](uint16_t conn_id, uint16_t handle, std::vector value, + tGATT_WRITE_TYPE write_type, GATT_WRITE_OP_CB cb, + void* cb_data) -> void { + if (cb) { + cb(conn_id, GATT_SUCCESS, handle, value.size(), value.data(), cb_data); + } })); CsisClient::Get()->LockGroup( - 1, true, - base::BindOnce([](int group_id, bool locked, CsisGroupLockStatus status) { - csis_lock_callback_mock->CsisGroupLockCb(group_id, locked, status); - })); + 1, true, base::BindOnce([](int group_id, bool locked, CsisGroupLockStatus status) { + csis_lock_callback_mock->CsisGroupLockCb(group_id, locked, status); + })); EXPECT_CALL(*callbacks, - OnGroupLockChanged( - 1, false, CsisGroupLockStatus::LOCKED_GROUP_MEMBER_LOST)); + OnGroupLockChanged(1, false, CsisGroupLockStatus::LOCKED_GROUP_MEMBER_LOST)); InjectDisconnectedEvent(test_address, 2, GATT_CONN_TIMEOUT); } TEST_F(CsisMultiClientTest, test_discover_multiple_instances) { TestConnect(test_address); - EXPECT_CALL(*callbacks, - OnConnectionState(test_address, ConnectionState::CONNECTED)) - .Times(1); + EXPECT_CALL(*callbacks, OnConnectionState(test_address, ConnectionState::CONNECTED)).Times(1); EXPECT_CALL(*callbacks, OnDeviceAvailable(test_address, _, _, _, _)).Times(2); InjectConnectedEvent(test_address, 1); GetSearchCompleteEvent(1); @@ -1453,22 +1315,19 @@ TEST_F(CsisClientTest, test_storage_content) { InjectConnectedEvent(GetTestAddress(1), 1); GetSearchCompleteEvent(1); ASSERT_EQ(1, CsisClient::Get()->GetGroupId( - GetTestAddress(1), - bluetooth::Uuid::From16Bit(UUID_COMMON_AUDIO_SERVICE))); + GetTestAddress(1), bluetooth::Uuid::From16Bit(UUID_COMMON_AUDIO_SERVICE))); TestConnect(GetTestAddress(2)); InjectConnectedEvent(GetTestAddress(2), 2); GetSearchCompleteEvent(2); ASSERT_EQ(1, CsisClient::Get()->GetGroupId( - GetTestAddress(2), - bluetooth::Uuid::From16Bit(UUID_COMMON_AUDIO_SERVICE))); + GetTestAddress(2), bluetooth::Uuid::From16Bit(UUID_COMMON_AUDIO_SERVICE))); TestConnect(GetTestAddress(3)); InjectConnectedEvent(GetTestAddress(3), 3); GetSearchCompleteEvent(3); ASSERT_EQ(2, CsisClient::Get()->GetGroupId( - GetTestAddress(3), - bluetooth::Uuid::From16Bit(UUID_COMMON_AUDIO_SERVICE))); + GetTestAddress(3), bluetooth::Uuid::From16Bit(UUID_COMMON_AUDIO_SERVICE))); std::vector dev1_storage; std::vector dev2_storage; @@ -1504,27 +1363,23 @@ TEST_F(CsisClientTest, test_storage_content) { // Restore dev1 from the byte buffer TestAddFromStorage(GetTestAddress(1), 1, dev1_group_storage, dev1_storage); ASSERT_EQ(1, CsisClient::Get()->GetGroupId( - GetTestAddress(1), - bluetooth::Uuid::From16Bit(UUID_COMMON_AUDIO_SERVICE))); + GetTestAddress(1), bluetooth::Uuid::From16Bit(UUID_COMMON_AUDIO_SERVICE))); // Restore dev2 from the byte buffer TestAddFromStorage(GetTestAddress(2), 2, dev2_group_storage, dev2_storage); ASSERT_EQ(1, CsisClient::Get()->GetGroupId( - GetTestAddress(2), - bluetooth::Uuid::From16Bit(UUID_COMMON_AUDIO_SERVICE))); + GetTestAddress(2), bluetooth::Uuid::From16Bit(UUID_COMMON_AUDIO_SERVICE))); // Restore dev3 from the byte buffer TestAddFromStorage(GetTestAddress(3), 3, dev3_group_storage, dev3_storage); ASSERT_EQ(2, CsisClient::Get()->GetGroupId( - GetTestAddress(3), - bluetooth::Uuid::From16Bit(UUID_COMMON_AUDIO_SERVICE))); + GetTestAddress(3), bluetooth::Uuid::From16Bit(UUID_COMMON_AUDIO_SERVICE))); // Restore not inerrogated dev4 - empty buffer but valid sirk for group 2 std::vector no_set_info; TestAddFromStorage(GetTestAddress(4), 4, no_set_info, no_set_info); ASSERT_EQ(3, CsisClient::Get()->GetGroupId( - GetTestAddress(4), - bluetooth::Uuid::From16Bit(UUID_COMMON_AUDIO_SERVICE))); + GetTestAddress(4), bluetooth::Uuid::From16Bit(UUID_COMMON_AUDIO_SERVICE))); TestAppUnregister(); } @@ -1538,30 +1393,30 @@ TEST_F(CsisClientTest, test_database_out_of_sync) { TestConnect(test_address); InjectConnectedEvent(test_address, conn_id); GetSearchCompleteEvent(conn_id); - ASSERT_EQ(1, CsisClient::Get()->GetGroupId( - test_address, bluetooth::Uuid::From16Bit(0x0000))); + ASSERT_EQ(1, CsisClient::Get()->GetGroupId(test_address, bluetooth::Uuid::From16Bit(0x0000))); // Simulated database changed on the remote side. ON_CALL(gatt_queue, WriteCharacteristic(_, _, _, _, _, _)) - .WillByDefault( - Invoke([this](uint16_t conn_id, uint16_t handle, - std::vector value, tGATT_WRITE_TYPE write_type, - GATT_WRITE_OP_CB cb, void* cb_data) { - auto* svc = gatt::FindService(services_map[conn_id], handle); - if (svc == nullptr) return; - - tGATT_STATUS status = GATT_DATABASE_OUT_OF_SYNC; - if (cb) - cb(conn_id, status, handle, value.size(), value.data(), cb_data); - })); + .WillByDefault( + Invoke([this](uint16_t conn_id, uint16_t handle, std::vector value, + tGATT_WRITE_TYPE write_type, GATT_WRITE_OP_CB cb, void* cb_data) { + auto* svc = gatt::FindService(services_map[conn_id], handle); + if (svc == nullptr) { + return; + } + + tGATT_STATUS status = GATT_DATABASE_OUT_OF_SYNC; + if (cb) { + cb(conn_id, status, handle, value.size(), value.data(), cb_data); + } + })); ON_CALL(gatt_interface, ServiceSearchRequest(_, _)).WillByDefault(Return()); EXPECT_CALL(gatt_interface, ServiceSearchRequest(_, _)); CsisClient::Get()->LockGroup( - 1, true, - base::BindOnce([](int group_id, bool locked, CsisGroupLockStatus status) { - csis_lock_callback_mock->CsisGroupLockCb(group_id, locked, status); - })); + 1, true, base::BindOnce([](int group_id, bool locked, CsisGroupLockStatus status) { + csis_lock_callback_mock->CsisGroupLockCb(group_id, locked, status); + })); TestAppUnregister(); } diff --git a/system/bta/csis/csis_types.h b/system/bta/csis/csis_types.h index 0fb3a56c58f..3a53c9ec869 100644 --- a/system/bta/csis/csis_types.h +++ b/system/bta/csis/csis_types.h @@ -43,8 +43,7 @@ using bluetooth::csis::CsisLockCb; // CSIP additions /* Generic UUID is used when CSIS is not included in any context */ -static const bluetooth::Uuid kCsisServiceUuid = - bluetooth::Uuid::From16Bit(0x1846); +static const bluetooth::Uuid kCsisServiceUuid = bluetooth::Uuid::From16Bit(0x1846); static const bluetooth::Uuid kCsisSirkUuid = bluetooth::Uuid::From16Bit(0x2B84); static const bluetooth::Uuid kCsisSizeUuid = bluetooth::Uuid::From16Bit(0x2B85); static const bluetooth::Uuid kCsisLockUuid = bluetooth::Uuid::From16Bit(0x2B86); @@ -62,8 +61,7 @@ static constexpr uint8_t kCsisSirkCharLen = 17; struct hdl_pair { hdl_pair() {} - hdl_pair(uint16_t val_hdl, uint16_t ccc_hdl) - : val_hdl(val_hdl), ccc_hdl(ccc_hdl) {} + hdl_pair(uint16_t val_hdl, uint16_t ccc_hdl) : val_hdl(val_hdl), ccc_hdl(ccc_hdl) {} uint16_t val_hdl; uint16_t ccc_hdl; @@ -88,7 +86,7 @@ enum class CsisDiscoveryState : uint8_t { }; class GattServiceDevice { - public: +public: RawAddress addr; /* * We are making active attempt to connect to this device, 'direct connect'. @@ -99,32 +97,31 @@ class GattServiceDevice { uint16_t service_handle = GAP_INVALID_HANDLE; bool is_gatt_service_valid = false; - GattServiceDevice(const RawAddress& addr, bool first_connection) - : addr(addr) {} + GattServiceDevice(const RawAddress& addr, bool first_connection) : addr(addr) {} GattServiceDevice() : GattServiceDevice(RawAddress::kEmpty, false) {} - bool IsConnected() const { return (conn_id != GATT_INVALID_CONN_ID); } + bool IsConnected() const { return conn_id != GATT_INVALID_CONN_ID; } class MatchAddress { - private: + private: RawAddress addr; - public: + public: MatchAddress(const RawAddress& addr) : addr(addr) {} bool operator()(const std::shared_ptr& other) const { - return (addr == other->addr); + return addr == other->addr; } }; class MatchConnId { - private: + private: uint16_t conn_id; - public: + public: MatchConnId(uint16_t conn_id) : conn_id(conn_id) {} bool operator()(const std::shared_ptr& other) const { - return (conn_id == other->conn_id); + return conn_id == other->conn_id; } }; }; @@ -139,7 +136,7 @@ class GattServiceDevice { * service. */ class CsisInstance { - public: +public: bluetooth::Uuid coordinated_service = bluetooth::groups::kGenericContextUuid; struct SvcData { @@ -150,16 +147,15 @@ class CsisInstance { uint16_t rank_handle; struct hdl_pair size_handle; } svc_data = { - GAP_INVALID_HANDLE, - GAP_INVALID_HANDLE, - {GAP_INVALID_HANDLE, GAP_INVALID_HANDLE}, - {GAP_INVALID_HANDLE, GAP_INVALID_HANDLE}, - GAP_INVALID_HANDLE, - {GAP_INVALID_HANDLE, GAP_INVALID_HANDLE}, + GAP_INVALID_HANDLE, + GAP_INVALID_HANDLE, + {GAP_INVALID_HANDLE, GAP_INVALID_HANDLE}, + {GAP_INVALID_HANDLE, GAP_INVALID_HANDLE}, + GAP_INVALID_HANDLE, + {GAP_INVALID_HANDLE, GAP_INVALID_HANDLE}, }; - CsisInstance(uint16_t start_handle, uint16_t end_handle, - const bluetooth::Uuid& uuid) + CsisInstance(uint16_t start_handle, uint16_t end_handle, const bluetooth::Uuid& uuid) : coordinated_service(uuid), group_id_(bluetooth::groups::kGroupUnknown), rank_(kUnknownRank), @@ -169,36 +165,32 @@ class CsisInstance { } void SetLockState(CsisLockState state) { - log::debug("current lock state: {}, new lock state: {}", - static_cast(lock_state_), static_cast(state)); + log::debug("current lock state: {}, new lock state: {}", static_cast(lock_state_), + static_cast(state)); lock_state_ = state; } CsisLockState GetLockState(void) const { return lock_state_; } uint8_t GetRank(void) const { return rank_; } void SetRank(uint8_t rank) { - log::debug("current rank: {}, new rank: {}", static_cast(rank_), - static_cast(rank)); + log::debug("current rank: {}, new rank: {}", static_cast(rank_), static_cast(rank)); rank_ = rank; } void SetGroupId(int group_id) { - log::info("set group id: {}, instance handle: 0x{:04x}", group_id, - svc_data.start_handle); + log::info("set group id: {}, instance handle: 0x{:04x}", group_id, svc_data.start_handle); group_id_ = group_id; } int GetGroupId(void) const { return group_id_; } bool HasSameUuid(const CsisInstance& csis_instance) const { - return (csis_instance.coordinated_service == coordinated_service); + return csis_instance.coordinated_service == coordinated_service; } const bluetooth::Uuid& GetUuid(void) const { return coordinated_service; } - bool IsForUuid(const bluetooth::Uuid& uuid) const { - return coordinated_service == uuid; - } + bool IsForUuid(const bluetooth::Uuid& uuid) const { return coordinated_service == uuid; } - private: +private: int group_id_; uint8_t rank_; CsisLockState lock_state_; @@ -213,7 +205,7 @@ class CsisInstance { * CsisDevice contains vector of the instances. */ class CsisDevice : public GattServiceDevice { - public: +public: using GattServiceDevice::GattServiceDevice; void ClearSvcData() { @@ -243,8 +235,7 @@ class CsisDevice : public GattServiceDevice { std::shared_ptr GetCsisInstanceByOwningHandle(uint16_t handle) { uint16_t hdl = 0; for (const auto& [h, inst] : csis_instances_) { - if (handle >= inst->svc_data.start_handle && - handle <= inst->svc_data.end_handle) { + if (handle >= inst->svc_data.start_handle && handle <= inst->svc_data.end_handle) { hdl = h; log::verbose("found 0x{:04x}", hdl); break; @@ -264,11 +255,9 @@ class CsisDevice : public GattServiceDevice { return (hdl > 0) ? csis_instances_.at(hdl) : nullptr; } - void SetCsisInstance(uint16_t handle, - std::shared_ptr csis_instance) { + void SetCsisInstance(uint16_t handle, std::shared_ptr csis_instance) { if (csis_instances_.count(handle)) { - log::debug("instance is already here: {}", - csis_instance->GetUuid().ToString()); + log::debug("instance is already here: {}", csis_instance->GetUuid().ToString()); return; } @@ -287,8 +276,7 @@ class CsisDevice : public GattServiceDevice { int GetNumberOfCsisInstances(void) { return csis_instances_.size(); } - void ForEachCsisInstance( - std::function&)> cb) { + void ForEachCsisInstance(std::function&)> cb) { for (auto const& kv_pair : csis_instances_) { cb(kv_pair.second); } @@ -300,15 +288,15 @@ class CsisDevice : public GattServiceDevice { } void SetPairingSirkReadFlag(bool flag) { - log::info("Pairing flag for Group ID: {}, member: {} is set to {}", - expected_group_id_member_, addr, flag); + log::info("Pairing flag for Group ID: {}, member: {} is set to {}", expected_group_id_member_, + addr, flag); pairing_sirk_read_flag_ = flag; } inline int GetExpectedGroupIdMember() { return expected_group_id_member_; } inline bool GetPairingSirkReadFlag() { return pairing_sirk_read_flag_; } - private: +private: /* Instances per start handle */ std::map> csis_instances_; int expected_group_id_member_ = bluetooth::groups::kGroupUnknown; @@ -321,7 +309,7 @@ class CsisDevice : public GattServiceDevice { * resolve PRSI in order to find out if device belongs to given group */ class CsisGroup { - public: +public: CsisGroup(int group_id, const bluetooth::Uuid& uuid) : group_id_(group_id), size_(kDefaultCsisSetSize), @@ -331,25 +319,28 @@ class CsisGroup { target_lock_state_(CsisLockState::CSIS_STATE_UNSET), lock_transition_cnt_(0) { devices_.clear(); - BTIF_STORAGE_FILL_PROPERTY(&model_name, BT_PROPERTY_REMOTE_MODEL_NUM, - sizeof(model_name_val), &model_name_val); + BTIF_STORAGE_FILL_PROPERTY(&model_name, BT_PROPERTY_REMOTE_MODEL_NUM, sizeof(model_name_val), + &model_name_val); } bt_property_t model_name; bt_bdname_t model_name_val = {0}; void AddDevice(std::shared_ptr csis_device) { - auto it = find_if(devices_.begin(), devices_.end(), - CsisDevice::MatchAddress(csis_device->addr)); - if (it != devices_.end()) return; + auto it = + find_if(devices_.begin(), devices_.end(), CsisDevice::MatchAddress(csis_device->addr)); + if (it != devices_.end()) { + return; + } devices_.push_back(std::move(csis_device)); } void RemoveDevice(const RawAddress& bd_addr) { - auto it = find_if(devices_.begin(), devices_.end(), - CsisDevice::MatchAddress(bd_addr)); - if (it != devices_.end()) devices_.erase(it); + auto it = find_if(devices_.begin(), devices_.end(), CsisDevice::MatchAddress(bd_addr)); + if (it != devices_.end()) { + devices_.erase(it); + } } int GetCurrentSize(void) const { return devices_.size(); } @@ -362,16 +353,12 @@ class CsisGroup { bool IsEmpty(void) const { return devices_.empty(); } bool IsDeviceInTheGroup(std::shared_ptr& csis_device) { - auto it = find_if(devices_.begin(), devices_.end(), - CsisDevice::MatchAddress(csis_device->addr)); - return (it != devices_.end()); - } - bool IsRsiMatching(const RawAddress& rsi) const { - return is_rsi_match_sirk(rsi, GetSirk()); - } - bool IsSirkBelongsToGroup(Octet16 sirk) const { - return (sirk_available_ && sirk_ == sirk); + auto it = + find_if(devices_.begin(), devices_.end(), CsisDevice::MatchAddress(csis_device->addr)); + return it != devices_.end(); } + bool IsRsiMatching(const RawAddress& rsi) const { return is_rsi_match_sirk(rsi, GetSirk()); } + bool IsSirkBelongsToGroup(Octet16 sirk) const { return sirk_available_ && sirk_ == sirk; } Octet16 GetSirk(void) const { return sirk_; } void SetSirk(Octet16& sirk) { if (sirk_available_) { @@ -386,20 +373,16 @@ class CsisGroup { [](auto& d) { return d->IsConnected(); }); } - CsisDiscoveryState GetDiscoveryState(void) const { - return member_discovery_state_; - } + CsisDiscoveryState GetDiscoveryState(void) const { return member_discovery_state_; } void SetDiscoveryState(CsisDiscoveryState state) { log::debug("current discovery state: {}, new discovery state: {}", - static_cast(member_discovery_state_), - static_cast(state)); + static_cast(member_discovery_state_), static_cast(state)); member_discovery_state_ = state; } void SetCurrentLockState(CsisLockState state) { lock_state_ = state; } - void SetTargetLockState(CsisLockState state, - CsisLockCb cb = base::DoNothing()) { + void SetTargetLockState(CsisLockState state, CsisLockCb cb = base::DoNothing()) { target_lock_state_ = state; cb_ = std::move(cb); switch (state) { @@ -421,22 +404,20 @@ class CsisGroup { bool IsAvailableForCsisLockOperation(void) { int id = group_id_; int number_of_connected = 0; - auto iter = std::find_if( - devices_.begin(), devices_.end(), [id, &number_of_connected](auto& d) { - if (!d->IsConnected()) { - log::debug("Device {} is not connected in group {}", d->addr, id); - return false; - } - auto inst = d->GetCsisInstanceByGroupId(id); - if (!inst) { - log::debug("Instance not available for group {}", id); - return false; - } - number_of_connected++; - log::debug("Device {}, lock state: {}", d->addr, - (int)inst->GetLockState()); - return inst->GetLockState() == CsisLockState::CSIS_STATE_LOCKED; - }); + auto iter = std::find_if(devices_.begin(), devices_.end(), [id, &number_of_connected](auto& d) { + if (!d->IsConnected()) { + log::debug("Device {} is not connected in group {}", d->addr, id); + return false; + } + auto inst = d->GetCsisInstanceByGroupId(id); + if (!inst) { + log::debug("Instance not available for group {}", id); + return false; + } + number_of_connected++; + log::debug("Device {}, lock state: {}", d->addr, (int)inst->GetLockState()); + return inst->GetLockState() == CsisLockState::CSIS_STATE_LOCKED; + }); log::debug("Locked set: {}, number of connected {}", iter != devices_.end(), number_of_connected); @@ -446,7 +427,7 @@ class CsisGroup { return false; } - return (number_of_connected > 0); + return number_of_connected > 0; } void SortByCsisRank(void) { @@ -456,45 +437,49 @@ class CsisGroup { auto inst2 = dev2->GetCsisInstanceByGroupId(id); if (!inst1 || !inst2) { /* One of the device is not connected */ - log::debug("Device {} is not connected.", - inst1 == nullptr ? ADDRESS_TO_LOGGABLE_CSTR(dev1->addr) - : ADDRESS_TO_LOGGABLE_CSTR(dev2->addr)); + log::debug("Device {} is not connected.", inst1 == nullptr + ? ADDRESS_TO_LOGGABLE_CSTR(dev1->addr) + : ADDRESS_TO_LOGGABLE_CSTR(dev2->addr)); return dev1->IsConnected(); } - return (inst1->GetRank() < inst2->GetRank()); + return inst1->GetRank() < inst2->GetRank(); }); } - std::shared_ptr GetFirstDevice(void) { - return (devices_.front()); - } - std::shared_ptr GetLastDevice(void) { return (devices_.back()); } - std::shared_ptr GetNextDevice( - std::shared_ptr& device) { - auto iter = std::find_if(devices_.begin(), devices_.end(), - CsisDevice::MatchAddress(device->addr)); + std::shared_ptr GetFirstDevice(void) { return devices_.front(); } + std::shared_ptr GetLastDevice(void) { return devices_.back(); } + std::shared_ptr GetNextDevice(std::shared_ptr& device) { + auto iter = + std::find_if(devices_.begin(), devices_.end(), CsisDevice::MatchAddress(device->addr)); /* If reference device not found */ - if (iter == devices_.end()) return nullptr; + if (iter == devices_.end()) { + return nullptr; + } iter++; /* If reference device is last in group */ - if (iter == devices_.end()) return nullptr; + if (iter == devices_.end()) { + return nullptr; + } - return (*iter); + return *iter; } - std::shared_ptr GetPrevDevice( - std::shared_ptr& device) { + std::shared_ptr GetPrevDevice(std::shared_ptr& device) { auto iter = std::find_if(devices_.rbegin(), devices_.rend(), CsisDevice::MatchAddress(device->addr)); /* If reference device not found */ - if (iter == devices_.rend()) return nullptr; + if (iter == devices_.rend()) { + return nullptr; + } iter++; - if (iter == devices_.rend()) return nullptr; - return (*iter); + if (iter == devices_.rend()) { + return nullptr; + } + return *iter; } int GetLockTransitionCnt(void) const { return lock_transition_cnt_; } @@ -539,7 +524,7 @@ class CsisGroup { return false; } - private: +private: int group_id_; Octet16 sirk_ = {0}; bool sirk_available_ = false; diff --git a/system/bta/dm/bta_dm_act.cc b/system/bta/dm/bta_dm_act.cc index 91ba4857879..6d5a0ba3d3e 100644 --- a/system/bta/dm/bta_dm_act.cc +++ b/system/bta/dm/bta_dm_act.cc @@ -76,25 +76,23 @@ void btm_ble_scanner_init(void); static void bta_dm_local_name_cback(void* p_name); static void bta_dm_check_av(); -void BTA_dm_update_policy(tBTA_SYS_CONN_STATUS status, uint8_t id, - uint8_t app_id, const RawAddress& peer_addr); +void BTA_dm_update_policy(tBTA_SYS_CONN_STATUS status, uint8_t id, uint8_t app_id, + const RawAddress& peer_addr); /* Extended Inquiry Response */ static void bta_dm_set_eir(char* local_name); static void bta_dm_disable_conn_down_timer_cback(void* data); -static void bta_dm_rm_cback(tBTA_SYS_CONN_STATUS status, tBTA_SYS_ID id, - uint8_t app_id, const RawAddress& peer_addr); +static void bta_dm_rm_cback(tBTA_SYS_CONN_STATUS status, tBTA_SYS_ID id, uint8_t app_id, + const RawAddress& peer_addr); static void bta_dm_adjust_roles(bool delay_role_switch); tBTM_CONTRL_STATE bta_dm_pm_obtain_controller_state(void); static void bta_dm_ctrl_features_rd_cmpl_cback(tHCI_STATUS result); -static const char kPropertySniffOffloadEnabled[] = - "bluetooth.sniff_offload.enabled"; +static const char kPropertySniffOffloadEnabled[] = "bluetooth.sniff_offload.enabled"; #ifndef BTA_DM_BLE_ADV_CHNL_MAP -#define BTA_DM_BLE_ADV_CHNL_MAP \ - (BTM_BLE_ADV_CHNL_37 | BTM_BLE_ADV_CHNL_38 | BTM_BLE_ADV_CHNL_39) +#define BTA_DM_BLE_ADV_CHNL_MAP (BTM_BLE_ADV_CHNL_37 | BTM_BLE_ADV_CHNL_38 | BTM_BLE_ADV_CHNL_39) #endif /* Disable timer interval (in milliseconds) */ @@ -126,34 +124,27 @@ namespace { struct WaitForAllAclConnectionsToDrain { uint64_t time_to_wait_in_ms; - unsigned long TimeToWaitInMs() const { - return static_cast(time_to_wait_in_ms); - } - void* AlarmCallbackData() const { - return const_cast(static_cast(this)); - } + unsigned long TimeToWaitInMs() const { return static_cast(time_to_wait_in_ms); } + void* AlarmCallbackData() const { return const_cast(static_cast(this)); } - static const WaitForAllAclConnectionsToDrain* FromAlarmCallbackData( - void* data); + static const WaitForAllAclConnectionsToDrain* FromAlarmCallbackData(void* data); static bool IsFirstPass(const WaitForAllAclConnectionsToDrain*); } first_pass = - { - .time_to_wait_in_ms = static_cast(BTA_DM_DISABLE_TIMER_MS), + { + .time_to_wait_in_ms = static_cast(BTA_DM_DISABLE_TIMER_MS), }, second_pass = { - .time_to_wait_in_ms = - static_cast(BTA_DM_DISABLE_TIMER_RETRIAL_MS), + .time_to_wait_in_ms = static_cast(BTA_DM_DISABLE_TIMER_RETRIAL_MS), }; -bool WaitForAllAclConnectionsToDrain::IsFirstPass( - const WaitForAllAclConnectionsToDrain* pass) { +bool WaitForAllAclConnectionsToDrain::IsFirstPass(const WaitForAllAclConnectionsToDrain* pass) { return pass == &first_pass; } -const WaitForAllAclConnectionsToDrain* -WaitForAllAclConnectionsToDrain::FromAlarmCallbackData(void* data) { +const WaitForAllAclConnectionsToDrain* WaitForAllAclConnectionsToDrain::FromAlarmCallbackData( + void* data) { return const_cast( - static_cast(data)); + static_cast(data)); } } // namespace @@ -162,10 +153,10 @@ static void bta_dm_delay_role_switch_cback(void* data); static void bta_dm_wait_for_acl_to_drain_cback(void* data); /** Initialises the BT device manager */ -void bta_dm_enable(tBTA_DM_SEC_CBACK* p_sec_cback, - tBTA_DM_ACL_CBACK *p_acl_cback) { - - if (p_acl_cback != NULL) bta_dm_acl_cb.p_acl_cback = p_acl_cback; +void bta_dm_enable(tBTA_DM_SEC_CBACK* p_sec_cback, tBTA_DM_ACL_CBACK* p_acl_cback) { + if (p_acl_cback != NULL) { + bta_dm_acl_cb.p_acl_cback = p_acl_cback; + } bta_dm_sec_enable(p_sec_cback); } @@ -234,18 +225,16 @@ void BTA_dm_on_hw_on() { /* make sure the control block is properly initialized */ bta_dm_init_cb(); - bta_dm_disc_start( - osi_property_get_bool("bluetooth.gatt.delay_close.enabled", true)); + bta_dm_disc_start(osi_property_get_bool("bluetooth.gatt.delay_close.enabled", true)); memset(&bta_dm_conn_srvcs, 0, sizeof(bta_dm_conn_srvcs)); memset(&bta_dm_di_cb, 0, sizeof(tBTA_DM_DI_CB)); DEV_CLASS dev_class = btif_dm_get_local_class_of_device(); - log::info("Read default class of device [0x{:x}, 0x{:x}, 0x{:x}]", - dev_class[0], dev_class[1], dev_class[2]); + log::info("Read default class of device [0x{:x}, 0x{:x}, 0x{:x}]", dev_class[0], dev_class[1], + dev_class[2]); - if (get_btm_client_interface().local.BTM_SetDeviceClass(dev_class) != - BTM_SUCCESS) { + if (get_btm_client_interface().local.BTM_SetDeviceClass(dev_class) != BTM_SUCCESS) { log::warn("Unable to set local device class:{}", dev_class_text(dev_class)); } @@ -254,28 +243,28 @@ void BTA_dm_on_hw_on() { btif_dm_get_ble_local_keys(&key_mask, &er, &id_key); if (key_mask & BTA_BLE_LOCAL_KEY_TYPE_ER) { - get_btm_client_interface().security.BTM_BleLoadLocalKeys( - BTA_BLE_LOCAL_KEY_TYPE_ER, (tBTM_BLE_LOCAL_KEYS*)&er); + get_btm_client_interface().security.BTM_BleLoadLocalKeys(BTA_BLE_LOCAL_KEY_TYPE_ER, + (tBTM_BLE_LOCAL_KEYS*)&er); } if (key_mask & BTA_BLE_LOCAL_KEY_TYPE_ID) { - get_btm_client_interface().security.BTM_BleLoadLocalKeys( - BTA_BLE_LOCAL_KEY_TYPE_ID, (tBTM_BLE_LOCAL_KEYS*)&id_key); + get_btm_client_interface().security.BTM_BleLoadLocalKeys(BTA_BLE_LOCAL_KEY_TYPE_ID, + (tBTM_BLE_LOCAL_KEYS*)&id_key); } btm_dm_sec_init(); btm_sec_on_hw_on(); get_btm_client_interface().link_policy.BTM_WritePageTimeout( - osi_property_get_int32(PROPERTY_PAGE_TIMEOUT, - p_bta_dm_cfg->page_timeout)); + osi_property_get_int32(PROPERTY_PAGE_TIMEOUT, p_bta_dm_cfg->page_timeout)); if (ble_vnd_is_included()) { get_btm_client_interface().ble.BTM_BleReadControllerFeatures( - bta_dm_ctrl_features_rd_cmpl_cback); + bta_dm_ctrl_features_rd_cmpl_cback); } else { /* Set controller features even if vendor support is not included */ - if (bta_dm_acl_cb.p_acl_cback) + if (bta_dm_acl_cb.p_acl_cback) { bta_dm_acl_cb.p_acl_cback(BTA_DM_LE_FEATURES_READ, NULL); + } } btm_ble_scanner_init(); @@ -291,7 +280,7 @@ void BTA_dm_on_hw_on() { the DM_ENABLE_EVT to be sent only after all the init steps are complete */ if (get_btm_client_interface().local.BTM_ReadLocalDeviceNameFromController( - bta_dm_local_name_cback) != BTM_CMD_STARTED) { + bta_dm_local_name_cback) != BTM_CMD_STARTED) { log::warn("Unable to read local device name from controller"); } @@ -313,14 +302,12 @@ void bta_dm_disable() { /* Set l2cap idle timeout to 0 (so BTE immediately disconnects ACL link after * last channel is closed) */ if (!L2CA_SetIdleTimeoutByBdAddr(RawAddress::kAny, 0, BT_TRANSPORT_BR_EDR)) { - log::warn( - "Unable to set L2CAP idle timeout peer:{} transport:{} timeout:{}", - RawAddress::kAny, BT_TRANSPORT_BR_EDR, 0); + log::warn("Unable to set L2CAP idle timeout peer:{} transport:{} timeout:{}", RawAddress::kAny, + BT_TRANSPORT_BR_EDR, 0); } if (!L2CA_SetIdleTimeoutByBdAddr(RawAddress::kAny, 0, BT_TRANSPORT_LE)) { - log::warn( - "Unable to set L2CAP idle timeout peer:{} transport:{} timeout:{}", - RawAddress::kAny, BT_TRANSPORT_LE, 0); + log::warn("Unable to set L2CAP idle timeout peer:{} transport:{} timeout:{}", RawAddress::kAny, + BT_TRANSPORT_LE, 0); } /* disable all active subsystems */ @@ -365,8 +352,7 @@ void bta_dm_disable() { log::debug("Set timer to wait for all ACL connections to close:{} ms", first_pass.TimeToWaitInMs()); alarm_set_on_mloop(bta_dm_cb.disable_timer, first_pass.time_to_wait_in_ms, - bta_dm_wait_for_acl_to_drain_cback, - first_pass.AlarmCallbackData()); + bta_dm_wait_for_acl_to_drain_cback, first_pass.AlarmCallbackData()); } } @@ -393,19 +379,16 @@ static bool force_disconnect_all_acl_connections() { static void bta_dm_wait_for_acl_to_drain_cback(void* data) { log::assert_that(data != nullptr, "assert failed: data != nullptr"); const WaitForAllAclConnectionsToDrain* pass = - WaitForAllAclConnectionsToDrain::FromAlarmCallbackData(data); + WaitForAllAclConnectionsToDrain::FromAlarmCallbackData(data); if (BTM_GetNumAclLinks() && force_disconnect_all_acl_connections() && WaitForAllAclConnectionsToDrain::IsFirstPass(pass)) { /* DISABLE_EVT still need to be sent out to avoid java layer disable timeout */ - log::debug( - "Set timer for second pass to wait for all ACL connections to close:{} " - "ms", - second_pass.TimeToWaitInMs()); + log::debug("Set timer for second pass to wait for all ACL connections to close:{} ms", + second_pass.TimeToWaitInMs()); alarm_set_on_mloop(bta_dm_cb.disable_timer, second_pass.time_to_wait_in_ms, - bta_dm_wait_for_acl_to_drain_cback, - second_pass.AlarmCallbackData()); + bta_dm_wait_for_acl_to_drain_cback, second_pass.AlarmCallbackData()); } else { // No ACL links to close were up or is second pass at ACL closure log::info("Ensuring all ACL connections have been properly flushed"); @@ -420,8 +403,8 @@ static void bta_dm_wait_for_acl_to_drain_cback(void* data) { /** Sets local device name */ void bta_dm_set_dev_name(const std::vector& name) { - if (get_btm_client_interface().local.BTM_SetLocalDeviceName( - (const char*)name.data()) != BTM_CMD_STARTED) { + if (get_btm_client_interface().local.BTM_SetLocalDeviceName((const char*)name.data()) != + BTM_CMD_STARTED) { log::warn("Unable to set local device name"); } bta_dm_set_eir((char*)name.data()); @@ -458,12 +441,10 @@ bool BTA_DmSetVisibility(bt_scan_mode_t mode) { } if (BTM_SetDiscoverability(disc_mode_param) != BTM_SUCCESS) { - log::warn("Unable to set classic BR/EDR discoverability 0x{:04x}", - disc_mode_param); + log::warn("Unable to set classic BR/EDR discoverability 0x{:04x}", disc_mode_param); } if (BTM_SetConnectability(conn_mode_param) != BTM_SUCCESS) { - log::warn("Unable to set classic BR/EDR connectability 0x{:04x}", - conn_mode_param); + log::warn("Unable to set classic BR/EDR connectability 0x{:04x}", conn_mode_param); } return true; } @@ -494,10 +475,8 @@ void bta_dm_process_remove_device(const RawAddress& bd_addr) { void bta_dm_remove_device(const RawAddress& bd_addr) { /* If ACL exists for the device in the remove_bond message*/ bool is_bd_addr_connected = - get_btm_client_interface().peer.BTM_IsAclConnectionUp(bd_addr, - BT_TRANSPORT_LE) || - get_btm_client_interface().peer.BTM_IsAclConnectionUp( - bd_addr, BT_TRANSPORT_BR_EDR); + get_btm_client_interface().peer.BTM_IsAclConnectionUp(bd_addr, BT_TRANSPORT_LE) || + get_btm_client_interface().peer.BTM_IsAclConnectionUp(bd_addr, BT_TRANSPORT_BR_EDR); tBT_TRANSPORT other_transport = BT_TRANSPORT_AUTO; if (is_bd_addr_connected) { @@ -512,8 +491,7 @@ void bta_dm_remove_device(const RawAddress& bd_addr) { /* Make sure device is not in acceptlist before we disconnect */ if (!GATT_CancelConnect(0, bd_addr, false)) { - log::warn("Unable to cancel GATT connect peer:{} is_direct:{}", - bd_addr, false); + log::warn("Unable to cancel GATT connect peer:{} is_direct:{}", bd_addr, false); } btm_remove_acl(bd_addr, peer_device.transport); @@ -521,10 +499,11 @@ void bta_dm_remove_device(const RawAddress& bd_addr) { /* save the other transport to check if device is connected on * other_transport */ - if (peer_device.transport == BT_TRANSPORT_LE) + if (peer_device.transport == BT_TRANSPORT_LE) { other_transport = BT_TRANSPORT_BR_EDR; - else + } else { other_transport = BT_TRANSPORT_LE; + } break; } @@ -537,39 +516,35 @@ void bta_dm_remove_device(const RawAddress& bd_addr) { // If it is DUMO device and device is paired as different address, unpair that // device bool other_address_connected = - (other_transport) - ? get_btm_client_interface().peer.BTM_ReadConnectedTransportAddress( - &other_address, other_transport) - : (get_btm_client_interface().peer.BTM_ReadConnectedTransportAddress( - &other_address, BT_TRANSPORT_BR_EDR) || - get_btm_client_interface().peer.BTM_ReadConnectedTransportAddress( - &other_address2, BT_TRANSPORT_LE)); - if (other_address == bd_addr) other_address = other_address2; + (other_transport) ? get_btm_client_interface().peer.BTM_ReadConnectedTransportAddress( + &other_address, other_transport) + : (get_btm_client_interface().peer.BTM_ReadConnectedTransportAddress( + &other_address, BT_TRANSPORT_BR_EDR) || + get_btm_client_interface().peer.BTM_ReadConnectedTransportAddress( + &other_address2, BT_TRANSPORT_LE)); + if (other_address == bd_addr) { + other_address = other_address2; + } if (other_address_connected) { // Get real transport if (other_transport == BT_TRANSPORT_AUTO) { - bool connected_with_br_edr = - get_btm_client_interface().peer.BTM_IsAclConnectionUp( + bool connected_with_br_edr = get_btm_client_interface().peer.BTM_IsAclConnectionUp( other_address, BT_TRANSPORT_BR_EDR); - other_transport = - connected_with_br_edr ? BT_TRANSPORT_BR_EDR : BT_TRANSPORT_LE; + other_transport = connected_with_br_edr ? BT_TRANSPORT_BR_EDR : BT_TRANSPORT_LE; } - log::info("other_address {} with transport {} connected", other_address, - other_transport); + log::info("other_address {} with transport {} connected", other_address, other_transport); /* Take the link down first, and mark the device for removal when * disconnected */ for (int i = 0; i < bta_dm_cb.device_list.count; i++) { auto& peer_device = bta_dm_cb.device_list.peer_device[i]; - if (peer_device.peer_bdaddr == other_address && - peer_device.transport == other_transport) { + if (peer_device.peer_bdaddr == other_address && peer_device.transport == other_transport) { peer_device.conn_state = tBTA_DM_CONN_STATE::BTA_DM_UNPAIRING; log::info("Remove ACL of address {}", other_address); /* Make sure device is not in acceptlist before we disconnect */ if (!GATT_CancelConnect(0, bd_addr, false)) { - log::warn("Unable to cancel GATT connect peer:{} is_direct:{}", - bd_addr, false); + log::warn("Unable to cancel GATT connect peer:{} is_direct:{}", bd_addr, false); } btm_remove_acl(other_address, peer_device.transport); @@ -605,18 +580,14 @@ static void handle_role_change(const RawAddress& bd_addr, tHCI_ROLE new_role, tHCI_STATUS hci_status) { tBTA_DM_PEER_DEVICE* p_dev = bta_dm_find_peer_device(bd_addr); if (!p_dev) { - log::warn( - "Unable to find device for role change peer:{} new_role:{} " - "hci_status:{}", - bd_addr, RoleText(new_role), hci_error_code_text(hci_status)); + log::warn("Unable to find device for role change peer:{} new_role:{} hci_status:{}", bd_addr, + RoleText(new_role), hci_error_code_text(hci_status)); return; } - log::info( - "Role change callback peer:{} info:{} new_role:{} dev count:{} " - "hci_status:{}", - bd_addr, p_dev->info_text(), RoleText(new_role), - bta_dm_cb.device_list.count, hci_error_code_text(hci_status)); + log::info("Role change callback peer:{} info:{} new_role:{} dev count:{} hci_status:{}", bd_addr, + p_dev->info_text(), RoleText(new_role), bta_dm_cb.device_list.count, + hci_error_code_text(hci_status)); if (p_dev->is_av_active()) { bool need_policy_change = false; @@ -628,8 +599,7 @@ static void handle_role_change(const RawAddress& bd_addr, tHCI_ROLE new_role, * to peripheral * switch it back to central and remove the switch policy */ const tBTM_STATUS status = - get_btm_client_interface().link_policy.BTM_SwitchRoleToCentral( - bd_addr); + get_btm_client_interface().link_policy.BTM_SwitchRoleToCentral(bd_addr); switch (status) { case BTM_SUCCESS: log::debug("Role policy already set to central peer:{}", bd_addr); @@ -649,8 +619,7 @@ static void handle_role_change(const RawAddress& bd_addr, tHCI_ROLE new_role, } if (need_policy_change) { - get_btm_client_interface().link_policy.BTM_block_role_switch_for( - p_dev->peer_bdaddr); + get_btm_client_interface().link_policy.BTM_block_role_switch_for(p_dev->peer_bdaddr); } } else { /* there's AV no activity on this link and role switch happened @@ -663,8 +632,7 @@ static void handle_role_change(const RawAddress& bd_addr, tHCI_ROLE new_role, void BTA_dm_report_role_change(const RawAddress bd_addr, tHCI_ROLE new_role, tHCI_STATUS hci_status) { - do_in_main_thread(FROM_HERE, base::BindOnce(handle_role_change, bd_addr, - new_role, hci_status)); + do_in_main_thread(FROM_HERE, base::BindOnce(handle_role_change, bd_addr, new_role, hci_status)); } void handle_remote_features_complete(const RawAddress& bd_addr) { @@ -684,8 +652,7 @@ void handle_remote_features_complete(const RawAddress& bd_addr) { } void BTA_dm_notify_remote_features_complete(const RawAddress bd_addr) { - do_in_main_thread(FROM_HERE, - base::BindOnce(handle_remote_features_complete, bd_addr)); + do_in_main_thread(FROM_HERE, base::BindOnce(handle_remote_features_complete, bd_addr)); } static tBTA_DM_PEER_DEVICE* allocate_device_for(const RawAddress& bd_addr, @@ -698,8 +665,7 @@ static tBTA_DM_PEER_DEVICE* allocate_device_for(const RawAddress& bd_addr, } if (bta_dm_cb.device_list.count < BTA_DM_NUM_PEER_DEVICE) { - auto device = - &bta_dm_cb.device_list.peer_device[bta_dm_cb.device_list.count]; + auto device = &bta_dm_cb.device_list.peer_device[bta_dm_cb.device_list.count]; device->peer_bdaddr = bd_addr; bta_dm_cb.device_list.count++; if (transport == BT_TRANSPORT_LE) { @@ -710,15 +676,14 @@ static tBTA_DM_PEER_DEVICE* allocate_device_for(const RawAddress& bd_addr, return nullptr; } -static void bta_dm_acl_up(const RawAddress& bd_addr, tBT_TRANSPORT transport, - uint16_t acl_handle) { +static void bta_dm_acl_up(const RawAddress& bd_addr, tBT_TRANSPORT transport, uint16_t acl_handle) { auto device = allocate_device_for(bd_addr, transport); if (device == nullptr) { log::warn("Unable to allocate device resources for new connection"); return; } - log::info("Acl connected peer:{} transport:{} handle:{}", bd_addr, - bt_transport_text(transport), acl_handle); + log::info("Acl connected peer:{} transport:{} handle:{}", bd_addr, bt_transport_text(transport), + acl_handle); device->conn_state = tBTA_DM_CONN_STATE::BTA_DM_CONNECTED; device->pref_role = BTA_ANY_ROLE; device->reset_device_info(); @@ -747,14 +712,12 @@ static void bta_dm_acl_up(const RawAddress& bd_addr, tBT_TRANSPORT transport, bta_dm_adjust_roles(true); } -void BTA_dm_acl_up(const RawAddress bd_addr, tBT_TRANSPORT transport, - uint16_t acl_handle) { - do_in_main_thread( - FROM_HERE, base::BindOnce(bta_dm_acl_up, bd_addr, transport, acl_handle)); +void BTA_dm_acl_up(const RawAddress bd_addr, tBT_TRANSPORT transport, uint16_t acl_handle) { + do_in_main_thread(FROM_HERE, base::BindOnce(bta_dm_acl_up, bd_addr, transport, acl_handle)); } -static void bta_dm_acl_up_failed(const RawAddress bd_addr, - tBT_TRANSPORT transport, tHCI_STATUS status) { +static void bta_dm_acl_up_failed(const RawAddress bd_addr, tBT_TRANSPORT transport, + tHCI_STATUS status) { if (bta_dm_acl_cb.p_acl_cback) { tBTA_DM_ACL conn = {}; conn.link_up_failed.bd_addr = bd_addr; @@ -764,25 +727,23 @@ static void bta_dm_acl_up_failed(const RawAddress bd_addr, } } -void BTA_dm_acl_up_failed(const RawAddress bd_addr, tBT_TRANSPORT transport, - tHCI_STATUS status) { - do_in_main_thread(FROM_HERE, base::BindOnce(bta_dm_acl_up_failed, bd_addr, - transport, status)); +void BTA_dm_acl_up_failed(const RawAddress bd_addr, tBT_TRANSPORT transport, tHCI_STATUS status) { + do_in_main_thread(FROM_HERE, base::BindOnce(bta_dm_acl_up_failed, bd_addr, transport, status)); } -static void bta_dm_acl_down(const RawAddress& bd_addr, - tBT_TRANSPORT transport) { +static void bta_dm_acl_down(const RawAddress& bd_addr, tBT_TRANSPORT transport) { bool issue_unpair_cb = false; bool remove_device = false; for (uint8_t i = 0; i < bta_dm_cb.device_list.count; i++) { auto device = &bta_dm_cb.device_list.peer_device[i]; - if (device->peer_bdaddr != bd_addr || device->transport != transport) + if (device->peer_bdaddr != bd_addr || device->transport != transport) { continue; + } if (device->conn_state == tBTA_DM_CONN_STATE::BTA_DM_UNPAIRING) { - issue_unpair_cb = get_btm_client_interface().security.BTM_SecDeleteDevice( - device->peer_bdaddr); + issue_unpair_cb = + get_btm_client_interface().security.BTM_SecDeleteDevice(device->peer_bdaddr); /* remove all cached GATT information */ get_gatt_interface().BTA_GATTC_Refresh(bd_addr); @@ -796,8 +757,7 @@ static void bta_dm_acl_down(const RawAddress& bd_addr, // otherwise we memcpy garbage data into the record. // Then clear out the last item in the list since we are shrinking. for (; i < bta_dm_cb.device_list.count - 1; i++) { - memcpy(&bta_dm_cb.device_list.peer_device[i], - &bta_dm_cb.device_list.peer_device[i + 1], + memcpy(&bta_dm_cb.device_list.peer_device[i], &bta_dm_cb.device_list.peer_device[i + 1], sizeof(bta_dm_cb.device_list.peer_device[i])); } if (bta_dm_cb.device_list.count > 0) { @@ -807,7 +767,9 @@ static void bta_dm_acl_down(const RawAddress& bd_addr, } break; } - if (bta_dm_cb.device_list.count) bta_dm_cb.device_list.count--; + if (bta_dm_cb.device_list.count) { + bta_dm_cb.device_list.count--; + } if ((transport == BT_TRANSPORT_LE) && (bta_dm_cb.device_list.le_count)) { bta_dm_cb.device_list.le_count--; } @@ -820,8 +782,7 @@ static void bta_dm_acl_down(const RawAddress& bd_addr, * Start a timer to make sure that the profiles * get the disconnect event. */ - alarm_set_on_mloop(bta_dm_cb.disable_timer, - BTA_DM_DISABLE_CONN_DOWN_TIMER_MS, + alarm_set_on_mloop(bta_dm_cb.disable_timer, BTA_DM_DISABLE_CONN_DOWN_TIMER_MS, bta_dm_disable_conn_down_timer_cback, NULL); } } @@ -851,8 +812,7 @@ static void bta_dm_acl_down(const RawAddress& bd_addr, } void BTA_dm_acl_down(const RawAddress bd_addr, tBT_TRANSPORT transport) { - do_in_main_thread(FROM_HERE, - base::BindOnce(bta_dm_acl_down, bd_addr, transport)); + do_in_main_thread(FROM_HERE, base::BindOnce(bta_dm_acl_down, bd_addr, transport)); } /******************************************************************************* @@ -871,31 +831,24 @@ static void bta_dm_check_av() { log::info("av_count:{}", bta_dm_cb.cur_av_count); for (i = 0; i < bta_dm_cb.device_list.count; i++) { p_dev = &bta_dm_cb.device_list.peer_device[i]; - log::warn("[{}]: state:{}, info:{}", i, p_dev->conn_state, - p_dev->info_text()); - if ((p_dev->conn_state == tBTA_DM_CONN_STATE::BTA_DM_CONNECTED) && - p_dev->is_av_active()) { + log::warn("[{}]: state:{}, info:{}", i, p_dev->conn_state, p_dev->info_text()); + if ((p_dev->conn_state == tBTA_DM_CONN_STATE::BTA_DM_CONNECTED) && p_dev->is_av_active()) { /* make central and take away the role switch policy */ const tBTM_STATUS status = - get_btm_client_interface().link_policy.BTM_SwitchRoleToCentral( - p_dev->peer_bdaddr); + get_btm_client_interface().link_policy.BTM_SwitchRoleToCentral(p_dev->peer_bdaddr); switch (status) { case BTM_SUCCESS: - log::debug("Role policy already set to central peer:{}", - p_dev->peer_bdaddr); + log::debug("Role policy already set to central peer:{}", p_dev->peer_bdaddr); break; case BTM_CMD_STARTED: - log::debug("Role policy started to central peer:{}", - p_dev->peer_bdaddr); + log::debug("Role policy started to central peer:{}", p_dev->peer_bdaddr); break; default: - log::warn("Unable to set role policy to central peer:{}", - p_dev->peer_bdaddr); + log::warn("Unable to set role policy to central peer:{}", p_dev->peer_bdaddr); break; } /* else either already central or can not switch for some reasons */ - get_btm_client_interface().link_policy.BTM_block_role_switch_for( - p_dev->peer_bdaddr); + get_btm_client_interface().link_policy.BTM_block_role_switch_for(p_dev->peer_bdaddr); break; } } @@ -931,15 +884,14 @@ static void bta_dm_disable_conn_down_timer_cback(void* /* data */) { * Returns void * ******************************************************************************/ -static void bta_dm_rm_cback(tBTA_SYS_CONN_STATUS status, tBTA_SYS_ID id, - uint8_t app_id, const RawAddress& peer_addr) { +static void bta_dm_rm_cback(tBTA_SYS_CONN_STATUS status, tBTA_SYS_ID id, uint8_t app_id, + const RawAddress& peer_addr) { uint8_t j; tBTA_PREF_ROLES role; tBTA_DM_PEER_DEVICE* p_dev; - log::debug("BTA Role management callback count:{} status:{} peer:{}", - bta_dm_cb.cur_av_count, bta_sys_conn_status_text(status), - peer_addr); + log::debug("BTA Role management callback count:{} status:{} peer:{}", bta_dm_cb.cur_av_count, + bta_sys_conn_status_text(status), peer_addr); p_dev = bta_dm_find_peer_device(peer_addr); if (status == BTA_SYS_CONN_OPEN) { @@ -950,19 +902,21 @@ static void bta_dm_rm_cback(tBTA_SYS_CONN_STATUS status, tBTA_SYS_ID id, * switch command. * But this should not be done if we are in the middle of unpairing. */ - if (p_dev->conn_state != tBTA_DM_CONN_STATE::BTA_DM_UNPAIRING) + if (p_dev->conn_state != tBTA_DM_CONN_STATE::BTA_DM_UNPAIRING) { p_dev->conn_state = tBTA_DM_CONN_STATE::BTA_DM_CONNECTED; + } for (j = 1; j <= p_bta_dm_rm_cfg[0].app_id; j++) { if (((p_bta_dm_rm_cfg[j].app_id == app_id) || (p_bta_dm_rm_cfg[j].app_id == BTA_ALL_APP_ID)) && (p_bta_dm_rm_cfg[j].id == id)) { - log::assert_that( - p_bta_dm_rm_cfg[j].cfg <= BTA_PERIPHERAL_ROLE_ONLY, - "Passing illegal preferred role:0x{:02x} [0x{:02x}<=>0x{:02x}]", - p_bta_dm_rm_cfg[j].cfg, BTA_ANY_ROLE, BTA_PERIPHERAL_ROLE_ONLY); + log::assert_that(p_bta_dm_rm_cfg[j].cfg <= BTA_PERIPHERAL_ROLE_ONLY, + "Passing illegal preferred role:0x{:02x} [0x{:02x}<=>0x{:02x}]", + p_bta_dm_rm_cfg[j].cfg, BTA_ANY_ROLE, BTA_PERIPHERAL_ROLE_ONLY); role = static_cast(p_bta_dm_rm_cfg[j].cfg); - if (role > p_dev->pref_role) p_dev->pref_role = role; + if (role > p_dev->pref_role) { + p_dev->pref_role = role; + } break; } } @@ -971,22 +925,31 @@ static void bta_dm_rm_cback(tBTA_SYS_CONN_STATUS status, tBTA_SYS_ID id, if (BTA_ID_AV == id) { if (status == BTA_SYS_CONN_BUSY) { - if (p_dev) p_dev->set_av_active(); + if (p_dev) { + p_dev->set_av_active(); + } /* AV calls bta_sys_conn_open with the A2DP stream count as app_id */ - if (BTA_ID_AV == id) bta_dm_cb.cur_av_count = bta_dm_get_av_count(); + if (BTA_ID_AV == id) { + bta_dm_cb.cur_av_count = bta_dm_get_av_count(); + } } else if (status == BTA_SYS_CONN_IDLE) { - if (p_dev) p_dev->reset_av_active(); + if (p_dev) { + p_dev->reset_av_active(); + } /* get cur_av_count from connected services */ - if (BTA_ID_AV == id) bta_dm_cb.cur_av_count = bta_dm_get_av_count(); + if (BTA_ID_AV == id) { + bta_dm_cb.cur_av_count = bta_dm_get_av_count(); + } } } /* Don't adjust roles for each busy/idle state transition to avoid excessive switch requests when individual profile busy/idle status changes */ - if ((status != BTA_SYS_CONN_BUSY) && (status != BTA_SYS_CONN_IDLE)) + if ((status != BTA_SYS_CONN_BUSY) && (status != BTA_SYS_CONN_IDLE)) { bta_dm_adjust_roles(false); + } } /******************************************************************************* @@ -1018,12 +981,9 @@ static void bta_dm_adjust_roles(bool delay_role_switch) { uint8_t link_count = bta_dm_cb.device_list.count; if (link_count) { for (i = 0; i < bta_dm_cb.device_list.count; i++) { - if (bta_dm_cb.device_list.peer_device[i].conn_state == - tBTA_DM_CONN_STATE::BTA_DM_CONNECTED && - bta_dm_cb.device_list.peer_device[i].transport == - BT_TRANSPORT_BR_EDR) { - if ((bta_dm_cb.device_list.peer_device[i].pref_role == - BTA_CENTRAL_ROLE_ONLY) || + if (bta_dm_cb.device_list.peer_device[i].conn_state == tBTA_DM_CONN_STATE::BTA_DM_CONNECTED && + bta_dm_cb.device_list.peer_device[i].transport == BT_TRANSPORT_BR_EDR) { + if ((bta_dm_cb.device_list.peer_device[i].pref_role == BTA_CENTRAL_ROLE_ONLY) || (link_count > 1)) { /* Initiating immediate role switch with certain remote devices has caused issues due to role switch colliding with link encryption @@ -1034,12 +994,11 @@ static void bta_dm_adjust_roles(bool delay_role_switch) { devices are delayed to avoid the collision with link encryption setup */ - if (bta_dm_cb.device_list.peer_device[i].pref_role != - BTA_PERIPHERAL_ROLE_ONLY && + if (bta_dm_cb.device_list.peer_device[i].pref_role != BTA_PERIPHERAL_ROLE_ONLY && !delay_role_switch) { const tBTM_STATUS status = - get_btm_client_interface().link_policy.BTM_SwitchRoleToCentral( - bta_dm_cb.device_list.peer_device[i].peer_bdaddr); + get_btm_client_interface().link_policy.BTM_SwitchRoleToCentral( + bta_dm_cb.device_list.peer_device[i].peer_bdaddr); switch (status) { case BTM_SUCCESS: log::debug("Role policy already set to central peer:{}", @@ -1055,8 +1014,7 @@ static void bta_dm_adjust_roles(bool delay_role_switch) { break; } } else { - alarm_set_on_mloop(bta_dm_cb.switch_delay_timer, - BTA_DM_SWITCH_DELAY_TIMER_MS, + alarm_set_on_mloop(bta_dm_cb.switch_delay_timer, BTA_DM_SWITCH_DELAY_TIMER_MS, bta_dm_delay_role_switch_cback, NULL); } } @@ -1082,10 +1040,12 @@ static size_t find_utf8_char_boundary(const char* utf8str, size_t offset) { while (--offset) { uint8_t ch = (uint8_t)utf8str[offset]; - if ((ch & 0x80) == 0x00) // ASCII + if ((ch & 0x80) == 0x00) { // ASCII return offset + 1; - if ((ch & 0xC0) == 0xC0) // Multi-byte sequence start + } + if ((ch & 0xC0) == 0xC0) { // Multi-byte sequence start return offset; + } } return 0; @@ -1115,7 +1075,9 @@ static void bta_dm_set_eir(char* local_name) { uint8_t local_name_len; /* wait until complete to disable */ - if (alarm_is_scheduled(bta_dm_cb.disable_timer)) return; + if (alarm_is_scheduled(bta_dm_cb.disable_timer)) { + return; + } /* if local name is not provided, get it from controller */ if (local_name == NULL) { @@ -1133,10 +1095,11 @@ static void bta_dm_set_eir(char* local_name) { log::info("Generating extended inquiry response packet EIR"); - if (local_name) + if (local_name) { local_name_len = strlen(local_name); - else + } else { local_name_len = 0; + } data_type = HCI_EIR_COMPLETE_LOCAL_NAME_TYPE; /* if local name is longer than minimum length of shortened name */ @@ -1144,14 +1107,14 @@ static void bta_dm_set_eir(char* local_name) { if (local_name_len > p_bta_dm_eir_cfg->bta_dm_eir_min_name_len) { /* get number of UUID 16-bit list */ max_num_uuid = (free_eir_length - 2) / Uuid::kNumBytes16; - data_type = get_btm_client_interface().eir.BTM_GetEirSupportedServices( - bta_dm_cb.eir_uuid, &p, max_num_uuid, &num_uuid); + data_type = get_btm_client_interface().eir.BTM_GetEirSupportedServices(bta_dm_cb.eir_uuid, &p, + max_num_uuid, &num_uuid); p = (uint8_t*)p_buf + BTM_HCI_EIR_OFFSET; /* reset p */ /* if UUID doesn't fit remaing space, shorten local name */ if (local_name_len > (free_eir_length - 4 - num_uuid * Uuid::kNumBytes16)) { - local_name_len = find_utf8_char_boundary( - local_name, p_bta_dm_eir_cfg->bta_dm_eir_min_name_len); + local_name_len = + find_utf8_char_boundary(local_name, p_bta_dm_eir_cfg->bta_dm_eir_min_name_len); log::warn("local name is shortened ({})", local_name_len); data_type = HCI_EIR_SHORTENED_LOCAL_NAME_TYPE; } else { @@ -1175,16 +1138,15 @@ static void bta_dm_set_eir(char* local_name) { num_uuid = 0; max_num_uuid = (free_eir_length - 2) / Uuid::kNumBytes16; - data_type = get_btm_client_interface().eir.BTM_GetEirSupportedServices( - bta_dm_cb.eir_uuid, &p, max_num_uuid, &num_uuid); + data_type = get_btm_client_interface().eir.BTM_GetEirSupportedServices(bta_dm_cb.eir_uuid, &p, + max_num_uuid, &num_uuid); if (data_type == HCI_EIR_MORE_16BITS_UUID_TYPE) { log::warn("BTA EIR: UUID 16-bit list is truncated"); } #if (BTA_EIR_SERVER_NUM_CUSTOM_UUID > 0) else { - for (custom_uuid_idx = 0; - custom_uuid_idx < BTA_EIR_SERVER_NUM_CUSTOM_UUID; + for (custom_uuid_idx = 0; custom_uuid_idx < BTA_EIR_SERVER_NUM_CUSTOM_UUID; custom_uuid_idx++) { const Uuid& curr = bta_dm_cb.bta_custom_uuid[custom_uuid_idx].custom_uuid; if (curr.GetShortestRepresentationSize() == Uuid::kNumBytes16) { @@ -1216,8 +1178,7 @@ static void bta_dm_set_eir(char* local_name) { max_num_uuid = (free_eir_length - 2) / Uuid::kNumBytes32; - for (custom_uuid_idx = 0; custom_uuid_idx < BTA_EIR_SERVER_NUM_CUSTOM_UUID; - custom_uuid_idx++) { + for (custom_uuid_idx = 0; custom_uuid_idx < BTA_EIR_SERVER_NUM_CUSTOM_UUID; custom_uuid_idx++) { const Uuid& curr = bta_dm_cb.bta_custom_uuid[custom_uuid_idx].custom_uuid; if (curr.GetShortestRepresentationSize() == Uuid::kNumBytes32) { if (num_uuid < max_num_uuid) { @@ -1245,8 +1206,7 @@ static void bta_dm_set_eir(char* local_name) { max_num_uuid = (free_eir_length - 2) / Uuid::kNumBytes128; - for (custom_uuid_idx = 0; custom_uuid_idx < BTA_EIR_SERVER_NUM_CUSTOM_UUID; - custom_uuid_idx++) { + for (custom_uuid_idx = 0; custom_uuid_idx < BTA_EIR_SERVER_NUM_CUSTOM_UUID; custom_uuid_idx++) { const Uuid& curr = bta_dm_cb.bta_custom_uuid[custom_uuid_idx].custom_uuid; if (curr.GetShortestRepresentationSize() == Uuid::kNumBytes128) { if (num_uuid < max_num_uuid) { @@ -1267,13 +1227,11 @@ static void bta_dm_set_eir(char* local_name) { #endif /* BTA_EIR_SERVER_NUM_CUSTOM_UUID > 0 */ /* if Flags are provided in configuration */ - if ((p_bta_dm_eir_cfg->bta_dm_eir_flag_len > 0) && - (p_bta_dm_eir_cfg->bta_dm_eir_flags) && + if ((p_bta_dm_eir_cfg->bta_dm_eir_flag_len > 0) && (p_bta_dm_eir_cfg->bta_dm_eir_flags) && (free_eir_length >= p_bta_dm_eir_cfg->bta_dm_eir_flag_len + 2)) { UINT8_TO_STREAM(p, p_bta_dm_eir_cfg->bta_dm_eir_flag_len + 1); UINT8_TO_STREAM(p, HCI_EIR_FLAGS_TYPE); - memcpy(p, p_bta_dm_eir_cfg->bta_dm_eir_flags, - p_bta_dm_eir_cfg->bta_dm_eir_flag_len); + memcpy(p, p_bta_dm_eir_cfg->bta_dm_eir_flags, p_bta_dm_eir_cfg->bta_dm_eir_flag_len); p += p_bta_dm_eir_cfg->bta_dm_eir_flag_len; free_eir_length -= p_bta_dm_eir_cfg->bta_dm_eir_flag_len + 2; } @@ -1303,8 +1261,9 @@ static void bta_dm_set_eir(char* local_name) { free_eir_length -= 3; } - if (free_eir_length) + if (free_eir_length) { UINT8_TO_STREAM(p, 0); /* terminator of significant part */ + } if (get_btm_client_interface().eir.BTM_WriteEIR(p_buf) != BTM_SUCCESS) { log::warn("Unable to write EIR data"); @@ -1327,8 +1286,8 @@ static uint8_t bta_dm_get_cust_uuid_index(uint32_t handle) { #if (BTA_EIR_SERVER_NUM_CUSTOM_UUID > 0) uint8_t c_uu_idx = 0; - while(c_uu_idx < BTA_EIR_SERVER_NUM_CUSTOM_UUID && - bta_dm_cb.bta_custom_uuid[c_uu_idx].handle != handle) { + while (c_uu_idx < BTA_EIR_SERVER_NUM_CUSTOM_UUID && + bta_dm_cb.bta_custom_uuid[c_uu_idx].handle != handle) { c_uu_idx++; } @@ -1398,20 +1357,18 @@ void bta_dm_eir_update_cust_uuid(const tBTA_CUSTOM_UUID& curr, bool adding) { ******************************************************************************/ void bta_dm_eir_update_uuid(uint16_t uuid16, bool adding) { /* if this UUID is not advertised in EIR */ - if (!BTM_HasEirService(p_bta_dm_eir_cfg->uuid_mask, uuid16)) return; + if (!BTM_HasEirService(p_bta_dm_eir_cfg->uuid_mask, uuid16)) { + return; + } if (adding) { - log::info("EIR Adding UUID=0x{:04X} into extended inquiry response", - uuid16); + log::info("EIR Adding UUID=0x{:04X} into extended inquiry response", uuid16); - get_btm_client_interface().eir.BTM_AddEirService(bta_dm_cb.eir_uuid, - uuid16); + get_btm_client_interface().eir.BTM_AddEirService(bta_dm_cb.eir_uuid, uuid16); } else { - log::info("EIR Removing UUID=0x{:04X} from extended inquiry response", - uuid16); + log::info("EIR Removing UUID=0x{:04X} from extended inquiry response", uuid16); - get_btm_client_interface().eir.BTM_RemoveEirService(bta_dm_cb.eir_uuid, - uuid16); + get_btm_client_interface().eir.BTM_RemoveEirService(bta_dm_cb.eir_uuid, uuid16); } bta_dm_set_eir(NULL); @@ -1421,9 +1378,9 @@ tBTA_DM_PEER_DEVICE* find_connected_device(const RawAddress& bd_addr, tBT_TRANSPORT /* transport */) { for (uint8_t i = 0; i < bta_dm_cb.device_list.count; i++) { if (bta_dm_cb.device_list.peer_device[i].peer_bdaddr == bd_addr && - bta_dm_cb.device_list.peer_device[i].conn_state == - tBTA_DM_CONN_STATE::BTA_DM_CONNECTED) + bta_dm_cb.device_list.peer_device[i].conn_state == tBTA_DM_CONN_STATE::BTA_DM_CONNECTED) { return &bta_dm_cb.device_list.peer_device[i]; + } } return nullptr; } @@ -1435,8 +1392,7 @@ bool bta_dm_check_if_only_hd_connected(const RawAddress& peer_addr) { // Check if profiles other than hid are connected if ((bta_dm_conn_srvcs.conn_srvc[j].id != BTA_ID_HD) && bta_dm_conn_srvcs.conn_srvc[j].peer_bdaddr == peer_addr) { - log::verbose("Another profile (id={}) is connected", - bta_dm_conn_srvcs.conn_srvc[j].id); + log::verbose("Another profile (id={}) is connected", bta_dm_conn_srvcs.conn_srvc[j].id); return false; } } @@ -1445,36 +1401,31 @@ bool bta_dm_check_if_only_hd_connected(const RawAddress& peer_addr) { } /** This function set the preferred connection parameters */ -void bta_dm_ble_set_conn_params(const RawAddress& bd_addr, - uint16_t conn_int_min, uint16_t conn_int_max, - uint16_t peripheral_latency, +void bta_dm_ble_set_conn_params(const RawAddress& bd_addr, uint16_t conn_int_min, + uint16_t conn_int_max, uint16_t peripheral_latency, uint16_t supervision_tout) { - L2CA_AdjustConnectionIntervals(&conn_int_min, &conn_int_max, - BTM_BLE_CONN_INT_MIN); + L2CA_AdjustConnectionIntervals(&conn_int_min, &conn_int_max, BTM_BLE_CONN_INT_MIN); - get_btm_client_interface().ble.BTM_BleSetPrefConnParams( - bd_addr, conn_int_min, conn_int_max, peripheral_latency, - supervision_tout); + get_btm_client_interface().ble.BTM_BleSetPrefConnParams(bd_addr, conn_int_min, conn_int_max, + peripheral_latency, supervision_tout); } /** This function update LE connection parameters */ -void bta_dm_ble_update_conn_params(const RawAddress& bd_addr, uint16_t min_int, - uint16_t max_int, uint16_t latency, - uint16_t timeout, uint16_t min_ce_len, +void bta_dm_ble_update_conn_params(const RawAddress& bd_addr, uint16_t min_int, uint16_t max_int, + uint16_t latency, uint16_t timeout, uint16_t min_ce_len, uint16_t max_ce_len) { L2CA_AdjustConnectionIntervals(&min_int, &max_int, BTM_BLE_CONN_INT_MIN); - if (!L2CA_UpdateBleConnParams(bd_addr, min_int, max_int, latency, timeout, - min_ce_len, max_ce_len)) { + if (!L2CA_UpdateBleConnParams(bd_addr, min_int, max_int, latency, timeout, min_ce_len, + max_ce_len)) { log::error("Update connection parameters failed!"); } } /** This function set the maximum transmission packet size */ void bta_dm_ble_set_data_length(const RawAddress& bd_addr) { - uint16_t max_len = bluetooth::shim::GetController() - ->GetLeMaximumDataLength() - .supported_max_tx_octets_; + uint16_t max_len = + bluetooth::shim::GetController()->GetLeMaximumDataLength().supported_max_tx_octets_; if (BTM_SetBleDataLength(bd_addr, max_len) != BTM_SUCCESS) { log::info("Unable to set ble data length:{}", max_len); @@ -1487,8 +1438,7 @@ static tBTM_CONTRL_STATE bta_dm_obtain_system_context() { uint32_t sniff_acl_num = BTM_PM_ReadSniffLinkCount(); uint32_t le_acl_num = BTM_PM_ReadBleLinkCount(); uint32_t active_acl_num = total_acl_num - sniff_acl_num - le_acl_num; - uint32_t le_adv_num = - bluetooth::shim::BTM_BleGetNumberOfAdvertisingInstancesInUse(); + uint32_t le_adv_num = bluetooth::shim::BTM_BleGetNumberOfAdvertisingInstancesInUse(); uint32_t le_scan_duty_cycle = BTM_PM_ReadBleScanDutyCycle(); bool is_inquiry_active = BTM_PM_DeviceInScanState(); bool is_le_audio_active = LeAudioClient::IsLeAudioClientInStreaming(); @@ -1497,8 +1447,7 @@ static tBTM_CONTRL_STATE bta_dm_obtain_system_context() { for (int i = 0; i < bta_dm_cb.device_list.count; i++) { tBTA_DM_PEER_DEVICE* p_dev = &bta_dm_cb.device_list.peer_device[i]; - if (p_dev->conn_state == tBTA_DM_CONN_STATE::BTA_DM_CONNECTED && - p_dev->is_av_active()) { + if (p_dev->conn_state == tBTA_DM_CONN_STATE::BTA_DM_CONNECTED && p_dev->is_av_active()) { is_av_active = true; break; } @@ -1534,11 +1483,10 @@ static tBTM_CONTRL_STATE bta_dm_obtain_system_context() { ctrl_state |= BTM_CONTRL_LE_AUDIO; } log::debug( - "active_acl_num {} sniff_acl_num {} le_acl_num {} le_adv_num {} " - "le_scan_duty {} inquiry {} sco {} a2dp {} le_audio {} ctrl_state 0x{:x}", - active_acl_num, sniff_acl_num, le_acl_num, le_adv_num, le_scan_duty_cycle, - is_inquiry_active, is_sco_active, is_av_active, is_le_audio_active, - ctrl_state); + "active_acl_num {} sniff_acl_num {} le_acl_num {} le_adv_num {} " + "le_scan_duty {} inquiry {} sco {} a2dp {} le_audio {} ctrl_state 0x{:x}", + active_acl_num, sniff_acl_num, le_acl_num, le_adv_num, le_scan_duty_cycle, + is_inquiry_active, is_sco_active, is_av_active, is_le_audio_active, ctrl_state); return ctrl_state; } @@ -1552,33 +1500,31 @@ static tBTM_CONTRL_STATE bta_dm_obtain_system_context() { * Returns None * ******************************************************************************/ -static void bta_ble_energy_info_cmpl(tBTM_BLE_TX_TIME_MS tx_time, - tBTM_BLE_RX_TIME_MS rx_time, +static void bta_ble_energy_info_cmpl(tBTM_BLE_TX_TIME_MS tx_time, tBTM_BLE_RX_TIME_MS rx_time, tBTM_BLE_IDLE_TIME_MS idle_time, - tBTM_BLE_ENERGY_USED energy_used, - tHCI_STATUS status) { + tBTM_BLE_ENERGY_USED energy_used, tHCI_STATUS status) { tBTA_STATUS st = (status == HCI_SUCCESS) ? BTA_SUCCESS : BTA_FAILURE; tBTM_CONTRL_STATE ctrl_state = BTM_CONTRL_UNKNOWN; if (BTA_SUCCESS == st) { ctrl_state = com::android::bluetooth::flags::bt_system_context_report() - ? bta_dm_obtain_system_context() - : bta_dm_pm_obtain_controller_state(); + ? bta_dm_obtain_system_context() + : bta_dm_pm_obtain_controller_state(); } - if (bta_dm_cb.p_energy_info_cback) - bta_dm_cb.p_energy_info_cback(tx_time, rx_time, idle_time, energy_used, - ctrl_state, st); + if (bta_dm_cb.p_energy_info_cback) { + bta_dm_cb.p_energy_info_cback(tx_time, rx_time, idle_time, energy_used, ctrl_state, st); + } } /** This function obtains the energy info */ -void bta_dm_ble_get_energy_info( - tBTA_BLE_ENERGY_INFO_CBACK* p_energy_info_cback) { +void bta_dm_ble_get_energy_info(tBTA_BLE_ENERGY_INFO_CBACK* p_energy_info_cback) { bta_dm_cb.p_energy_info_cback = p_energy_info_cback; - tBTM_STATUS btm_status = get_btm_client_interface().ble.BTM_BleGetEnergyInfo( - bta_ble_energy_info_cmpl); - if (btm_status != BTM_CMD_STARTED) + tBTM_STATUS btm_status = + get_btm_client_interface().ble.BTM_BleGetEnergyInfo(bta_ble_energy_info_cmpl); + if (btm_status != BTM_CMD_STARTED) { bta_ble_energy_info_cmpl(0, 0, 0, 0, HCI_ERR_UNSPECIFIED); + } } /******************************************************************************* @@ -1668,9 +1614,8 @@ void bta_dm_set_event_filter_connection_setup_all_devices() { * Parameters std::vector of Classic Address and LE (Address, Address Type) * *******************************************************************************/ -void bta_dm_allow_wake_by_hid( - std::vector classic_hid_devices, - std::vector> le_hid_devices) { +void bta_dm_allow_wake_by_hid(std::vector classic_hid_devices, + std::vector> le_hid_devices) { // If there are any entries in the classic hid list, we should also make // the adapter connectable for classic. if (classic_hid_devices.size() > 0) { @@ -1679,8 +1624,7 @@ void bta_dm_allow_wake_by_hid( } } - bluetooth::shim::BTM_AllowWakeByHid(std::move(classic_hid_devices), - std::move(le_hid_devices)); + bluetooth::shim::BTM_AllowWakeByHid(std::move(classic_hid_devices), std::move(le_hid_devices)); } /******************************************************************************* @@ -1692,8 +1636,7 @@ void bta_dm_allow_wake_by_hid( * Parameters * *******************************************************************************/ -void bta_dm_restore_filter_accept_list( - std::vector> le_devices) { +void bta_dm_restore_filter_accept_list(std::vector> le_devices) { // Autoplumbed bluetooth::shim::BTM_RestoreFilterAcceptList(le_devices); } @@ -1755,8 +1698,9 @@ void bta_dm_ble_reset_id(void) { static void bta_dm_ctrl_features_rd_cmpl_cback(tHCI_STATUS result) { log::verbose("status = {}", result); if (result == HCI_SUCCESS) { - if (bta_dm_acl_cb.p_acl_cback) + if (bta_dm_acl_cb.p_acl_cback) { bta_dm_acl_cb.p_acl_cback(BTA_DM_LE_FEATURES_READ, NULL); + } } else { log::error("Ctrl BLE feature read failed: status :{}", result); } @@ -1772,25 +1716,22 @@ static void bta_dm_ctrl_features_rd_cmpl_cback(tHCI_STATUS result) { * ******************************************************************************/ void bta_dm_ble_subrate_request(const RawAddress& bd_addr, uint16_t subrate_min, - uint16_t subrate_max, uint16_t max_latency, - uint16_t cont_num, uint16_t timeout) { - // Logging done in l2c_ble.cc - if (!L2CA_SubrateRequest(bd_addr, subrate_min, subrate_max, max_latency, - cont_num, timeout)) { - log::warn("Unable to set L2CAP ble subrating peer:{}", bd_addr); - } + uint16_t subrate_max, uint16_t max_latency, uint16_t cont_num, + uint16_t timeout) { + // Logging done in l2c_ble.cc + if (!L2CA_SubrateRequest(bd_addr, subrate_min, subrate_max, max_latency, cont_num, timeout)) { + log::warn("Unable to set L2CAP ble subrating peer:{}", bd_addr); + } } namespace bluetooth { namespace legacy { namespace testing { -tBTA_DM_PEER_DEVICE* allocate_device_for(const RawAddress& bd_addr, - tBT_TRANSPORT transport) { +tBTA_DM_PEER_DEVICE* allocate_device_for(const RawAddress& bd_addr, tBT_TRANSPORT transport) { return ::allocate_device_for(bd_addr, transport); } -void bta_dm_acl_up(const RawAddress& bd_addr, tBT_TRANSPORT transport, - uint16_t acl_handle) { +void bta_dm_acl_up(const RawAddress& bd_addr, tBT_TRANSPORT transport, uint16_t acl_handle) { ::bta_dm_acl_up(bd_addr, transport, acl_handle); } void bta_dm_acl_down(const RawAddress& bd_addr, tBT_TRANSPORT transport) { diff --git a/system/bta/dm/bta_dm_api.cc b/system/bta/dm/bta_dm_api.cc index 0475074099f..42995f792a1 100644 --- a/system/bta/dm/bta_dm_api.cc +++ b/system/bta/dm/bta_dm_api.cc @@ -59,8 +59,7 @@ void BTA_dm_init() { /** Enables bluetooth device under test mode */ void BTA_EnableTestMode(void) { - do_in_main_thread(FROM_HERE, - base::BindOnce(base::IgnoreResult(BTM_EnableTestMode))); + do_in_main_thread(FROM_HERE, base::BindOnce(base::IgnoreResult(BTM_EnableTestMode))); } /** This function sets the Bluetooth name of local device */ @@ -82,9 +81,7 @@ void BTA_DmSetDeviceName(const char* p_name) { * Returns void * ******************************************************************************/ -void BTA_DmSearch(tBTA_DM_SEARCH_CBACK* p_cback) { - bta_dm_disc_start_device_discovery(p_cback); -} +void BTA_DmSearch(tBTA_DM_SEARCH_CBACK* p_cback) { bta_dm_disc_start_device_discovery(p_cback); } /******************************************************************************* * @@ -108,8 +105,7 @@ void BTA_DmSearchCancel(void) { bta_dm_disc_stop_device_discovery(); } * Returns void * ******************************************************************************/ -void BTA_DmDiscover(const RawAddress& bd_addr, - service_discovery_callbacks cbacks, +void BTA_DmDiscover(const RawAddress& bd_addr, service_discovery_callbacks cbacks, tBT_TRANSPORT transport) { bta_dm_disc_start_service_discovery(cbacks, bd_addr, transport); } @@ -125,7 +121,7 @@ void BTA_DmDiscover(const RawAddress& bd_addr, ******************************************************************************/ bool BTA_DmGetConnectionState(const RawAddress& bd_addr) { tBTA_DM_PEER_DEVICE* p_dev = bta_dm_find_peer_device(bd_addr); - return (p_dev && p_dev->conn_state == tBTA_DM_CONN_STATE::BTA_DM_CONNECTED); + return p_dev && p_dev->conn_state == tBTA_DM_CONN_STATE::BTA_DM_CONNECTED; } /******************************************************************************* @@ -140,13 +136,12 @@ bool BTA_DmGetConnectionState(const RawAddress& bd_addr) { * Returns BTA_SUCCESS if record set sucessfully, otherwise error code. * ******************************************************************************/ -tBTA_STATUS BTA_DmSetLocalDiRecord(tSDP_DI_RECORD* p_device_info, - uint32_t* p_handle) { +tBTA_STATUS BTA_DmSetLocalDiRecord(tSDP_DI_RECORD* p_device_info, uint32_t* p_handle) { tBTA_STATUS status = BTA_FAILURE; if (bta_dm_di_cb.di_num < BTA_DI_NUM_MAX) { - if (get_legacy_stack_sdp_api()->device_id.SDP_SetLocalDiRecord( - (tSDP_DI_RECORD*)p_device_info, p_handle) == SDP_SUCCESS) { + if (get_legacy_stack_sdp_api()->device_id.SDP_SetLocalDiRecord((tSDP_DI_RECORD*)p_device_info, + p_handle) == SDP_SUCCESS) { if (!p_device_info->primary_record) { bta_dm_di_cb.di_handle[bta_dm_di_cb.di_num] = *p_handle; bta_dm_di_cb.di_num++; @@ -179,14 +174,11 @@ tBTA_STATUS BTA_DmSetLocalDiRecord(tSDP_DI_RECORD* p_device_info, * Returns void * ******************************************************************************/ -void BTA_DmSetBlePrefConnParams(const RawAddress& bd_addr, - uint16_t min_conn_int, uint16_t max_conn_int, - uint16_t peripheral_latency, +void BTA_DmSetBlePrefConnParams(const RawAddress& bd_addr, uint16_t min_conn_int, + uint16_t max_conn_int, uint16_t peripheral_latency, uint16_t supervision_tout) { - do_in_main_thread( - FROM_HERE, - base::BindOnce(bta_dm_ble_set_conn_params, bd_addr, min_conn_int, - max_conn_int, peripheral_latency, supervision_tout)); + do_in_main_thread(FROM_HERE, base::BindOnce(bta_dm_ble_set_conn_params, bd_addr, min_conn_int, + max_conn_int, peripheral_latency, supervision_tout)); } /******************************************************************************* @@ -207,14 +199,11 @@ void BTA_DmSetBlePrefConnParams(const RawAddress& bd_addr, * Returns void * ******************************************************************************/ -void BTA_DmBleUpdateConnectionParams(const RawAddress& bd_addr, - uint16_t min_int, uint16_t max_int, - uint16_t latency, uint16_t timeout, - uint16_t min_ce_len, uint16_t max_ce_len) { - do_in_main_thread( - FROM_HERE, - base::BindOnce(bta_dm_ble_update_conn_params, bd_addr, min_int, max_int, - latency, timeout, min_ce_len, max_ce_len)); +void BTA_DmBleUpdateConnectionParams(const RawAddress& bd_addr, uint16_t min_int, uint16_t max_int, + uint16_t latency, uint16_t timeout, uint16_t min_ce_len, + uint16_t max_ce_len) { + do_in_main_thread(FROM_HERE, base::BindOnce(bta_dm_ble_update_conn_params, bd_addr, min_int, + max_int, latency, timeout, min_ce_len, max_ce_len)); } /******************************************************************************* @@ -232,8 +221,7 @@ void BTA_DmBleConfigLocalPrivacy(bool privacy_enable) { if (com::android::bluetooth::flags::synchronous_bta_sec()) { bta_dm_ble_config_local_privacy(privacy_enable); } else { - do_in_main_thread(FROM_HERE, base::BindOnce(bta_dm_ble_config_local_privacy, - privacy_enable)); + do_in_main_thread(FROM_HERE, base::BindOnce(bta_dm_ble_config_local_privacy, privacy_enable)); } } @@ -249,14 +237,12 @@ void BTA_DmBleConfigLocalPrivacy(bool privacy_enable) { * ******************************************************************************/ void BTA_DmBleGetEnergyInfo(tBTA_BLE_ENERGY_INFO_CBACK* p_cmpl_cback) { - do_in_main_thread(FROM_HERE, - base::BindOnce(bta_dm_ble_get_energy_info, p_cmpl_cback)); + do_in_main_thread(FROM_HERE, base::BindOnce(bta_dm_ble_get_energy_info, p_cmpl_cback)); } /** This function is to set maximum LE data packet size */ void BTA_DmBleRequestMaxTxDataLength(const RawAddress& remote_device) { - do_in_main_thread(FROM_HERE, - base::BindOnce(bta_dm_ble_set_data_length, remote_device)); + do_in_main_thread(FROM_HERE, base::BindOnce(bta_dm_ble_set_data_length, remote_device)); } /******************************************************************************* @@ -276,8 +262,8 @@ void BTA_DmBleRequestMaxTxDataLength(const RawAddress& remote_device) { ******************************************************************************/ void BTA_DmBleScan(bool start, uint8_t duration_sec, bool low_latency_scan) { log::verbose("start = {}", start); - do_in_main_thread(FROM_HERE, base::BindOnce(bta_dm_ble_scan, start, - duration_sec, low_latency_scan)); + do_in_main_thread(FROM_HERE, + base::BindOnce(bta_dm_ble_scan, start, duration_sec, low_latency_scan)); } /******************************************************************************* @@ -295,8 +281,7 @@ void BTA_DmBleScan(bool start, uint8_t duration_sec, bool low_latency_scan) { ******************************************************************************/ void BTA_DmBleCsisObserve(bool observe, tBTA_DM_SEARCH_CBACK* p_results_cb) { log::verbose("enable = {}", observe); - do_in_main_thread(FROM_HERE, base::BindOnce(bta_dm_ble_csis_observe, observe, - p_results_cb)); + do_in_main_thread(FROM_HERE, base::BindOnce(bta_dm_ble_csis_observe, observe, p_results_cb)); } /******************************************************************************* @@ -371,39 +356,32 @@ void BTA_DmDisconnectAllAcls() { void BTA_DmSetEventFilterConnectionSetupAllDevices() { log::verbose("BTA_DmSetEventFilterConnectionSetupAllDevices"); - do_in_main_thread( - FROM_HERE, - base::BindOnce(bta_dm_set_event_filter_connection_setup_all_devices)); + do_in_main_thread(FROM_HERE, + base::BindOnce(bta_dm_set_event_filter_connection_setup_all_devices)); } -void BTA_DmAllowWakeByHid( - std::vector classic_hid_devices, - std::vector> le_hid_devices) { +void BTA_DmAllowWakeByHid(std::vector classic_hid_devices, + std::vector> le_hid_devices) { log::verbose("BTA_DmAllowWakeByHid"); - do_in_main_thread(FROM_HERE, base::BindOnce(bta_dm_allow_wake_by_hid, - std::move(classic_hid_devices), - std::move(le_hid_devices))); + do_in_main_thread(FROM_HERE, + base::BindOnce(bta_dm_allow_wake_by_hid, std::move(classic_hid_devices), + std::move(le_hid_devices))); } -void BTA_DmRestoreFilterAcceptList( - std::vector> le_devices) { +void BTA_DmRestoreFilterAcceptList(std::vector> le_devices) { log::verbose("BTA_DmRestoreFilterAcceptList"); - do_in_main_thread(FROM_HERE, base::BindOnce(bta_dm_restore_filter_accept_list, - std::move(le_devices))); + do_in_main_thread(FROM_HERE, + base::BindOnce(bta_dm_restore_filter_accept_list, std::move(le_devices))); } void BTA_DmSetDefaultEventMaskExcept(uint64_t mask, uint64_t le_mask) { log::verbose("BTA_DmSetDefaultEventMaskExcept"); - do_in_main_thread( - FROM_HERE, - base::BindOnce(bta_dm_set_default_event_mask_except, mask, le_mask)); + do_in_main_thread(FROM_HERE, base::BindOnce(bta_dm_set_default_event_mask_except, mask, le_mask)); } void BTA_DmSetEventFilterInquiryResultAllDevices() { log::verbose("BTA_DmSetEventFilterInquiryResultAllDevices"); - do_in_main_thread( - FROM_HERE, - base::BindOnce(bta_dm_set_event_filter_inquiry_result_all_devices)); + do_in_main_thread(FROM_HERE, base::BindOnce(bta_dm_set_event_filter_inquiry_result_all_devices)); } /******************************************************************************* @@ -436,20 +414,19 @@ void BTA_DmBleResetId(void) { * Returns void * ******************************************************************************/ -void BTA_DmBleSubrateRequest(const RawAddress& bd_addr, uint16_t subrate_min, - uint16_t subrate_max, uint16_t max_latency, - uint16_t cont_num, uint16_t timeout) { +void BTA_DmBleSubrateRequest(const RawAddress& bd_addr, uint16_t subrate_min, uint16_t subrate_max, + uint16_t max_latency, uint16_t cont_num, uint16_t timeout) { log::verbose(""); - do_in_main_thread(FROM_HERE, base::BindOnce(bta_dm_ble_subrate_request, - bd_addr, subrate_min, subrate_max, - max_latency, cont_num, timeout)); + do_in_main_thread(FROM_HERE, base::BindOnce(bta_dm_ble_subrate_request, bd_addr, subrate_min, + subrate_max, max_latency, cont_num, timeout)); } bool BTA_DmCheckLeAudioCapable(const RawAddress& address) { - for (tBTM_INQ_INFO* inq_ent = get_btm_client_interface().db.BTM_InqDbFirst(); - inq_ent != nullptr; + for (tBTM_INQ_INFO* inq_ent = get_btm_client_interface().db.BTM_InqDbFirst(); inq_ent != nullptr; inq_ent = get_btm_client_interface().db.BTM_InqDbNext(inq_ent)) { - if (inq_ent->results.remote_bd_addr != address) continue; + if (inq_ent->results.remote_bd_addr != address) { + continue; + } if (inq_ent->results.ble_ad_is_le_audio_capable) { log::info("Device is LE Audio capable based on AD content"); diff --git a/system/bta/dm/bta_dm_cfg.cc b/system/bta/dm/bta_dm_cfg.cc index 37c83cd327b..aa9dc6bea3a 100644 --- a/system/bta/dm/bta_dm_cfg.cc +++ b/system/bta/dm/bta_dm_cfg.cc @@ -44,10 +44,10 @@ #endif const tBTA_DM_CFG bta_dm_cfg = { - /* page timeout in 625uS */ - BTA_DM_PAGE_TIMEOUT, - /* true to avoid scatternet when av is streaming (be the central) */ - BTA_DM_AVOID_SCATTER_A2DP}; + /* page timeout in 625uS */ + BTA_DM_PAGE_TIMEOUT, + /* true to avoid scatternet when av is streaming (be the central) */ + BTA_DM_AVOID_SCATTER_A2DP}; #ifndef BTA_DM_SCATTERNET /* By default, allow partial scatternet */ @@ -74,429 +74,319 @@ const tBTA_DM_CFG bta_dm_cfg = { /* First element is always for SYS: app_id = # of entries table, cfg is device scatternet support */ -const tBTA_DM_RM bta_dm_rm_cfg[] = { - {BTA_ID_SYS, BTA_DM_NUM_RM_ENTRY, BTA_DM_SCATTERNET}, - {BTA_ID_PAN, BTUI_PAN_ID_NAP, BTA_ANY_ROLE}, - {BTA_ID_PAN, BTUI_PAN_ID_GN, BTA_ANY_ROLE}, - {BTA_ID_PAN, BTA_APP_ID_PAN_MULTI, BTA_CENTRAL_ROLE_ONLY}, - {BTA_ID_PAN, BTUI_PAN_ID_PANU, BTA_PANU_ROLE}, - {BTA_ID_HH, BTA_ALL_APP_ID, BTA_HH_ROLE}, - {BTA_ID_AV, BTA_ALL_APP_ID, BTA_CENTRAL_ROLE_PREF}}; +const tBTA_DM_RM bta_dm_rm_cfg[] = {{BTA_ID_SYS, BTA_DM_NUM_RM_ENTRY, BTA_DM_SCATTERNET}, + {BTA_ID_PAN, BTUI_PAN_ID_NAP, BTA_ANY_ROLE}, + {BTA_ID_PAN, BTUI_PAN_ID_GN, BTA_ANY_ROLE}, + {BTA_ID_PAN, BTA_APP_ID_PAN_MULTI, BTA_CENTRAL_ROLE_ONLY}, + {BTA_ID_PAN, BTUI_PAN_ID_PANU, BTA_PANU_ROLE}, + {BTA_ID_HH, BTA_ALL_APP_ID, BTA_HH_ROLE}, + {BTA_ID_AV, BTA_ALL_APP_ID, BTA_CENTRAL_ROLE_PREF}}; const tBTA_DM_CFG* p_bta_dm_cfg = &bta_dm_cfg; const tBTA_DM_RM* p_bta_dm_rm_cfg = &bta_dm_rm_cfg[0]; -#define BTA_DM_NUM_PM_ENTRY \ - 25 /* number of entries in bta_dm_pm_cfg except the first */ -#define BTA_DM_NUM_PM_SPEC 16 /* number of entries in bta_dm_pm_spec */ - -tBTA_DM_PM_TYPE_QUALIFIER tBTA_DM_PM_CFG - bta_dm_pm_cfg[BTA_DM_NUM_PM_ENTRY + 1] = { - {BTA_ID_SYS, BTA_DM_NUM_PM_ENTRY, - 0}, /* reserved: specifies length of this table. */ - {BTA_ID_AG, BTA_ALL_APP_ID, - 0}, /* ag uses first spec table for app id 0 */ - {BTA_ID_CT, 1, 1}, /* ct (BTA_ID_CT,APP ID=1) spec table */ - {BTA_ID_CG, BTA_ALL_APP_ID, 1}, /* cg resue ct spec table */ - {BTA_ID_DG, BTA_ALL_APP_ID, 2}, /* dg spec table */ - {BTA_ID_AV, BTA_ALL_APP_ID, 4}, /* av spec table */ - {BTA_ID_FTC, BTA_ALL_APP_ID, 7}, /* ftc spec table */ - {BTA_ID_FTS, BTA_ALL_APP_ID, 8}, /* fts spec table */ - {BTA_ID_HD, BTA_ALL_APP_ID, 3}, /* hd spec table */ - {BTA_ID_HH, BTA_HH_APP_ID_JOY, 5}, /* app BTA_HH_APP_ID_JOY, - similar to hh spec table */ - {BTA_ID_HH, BTA_HH_APP_ID_GPAD, 5}, /* app BTA_HH_APP_ID_GPAD, - similar to hh spec table */ - {BTA_ID_HH, BTA_ALL_APP_ID, 6}, /* hh spec table */ - {BTA_ID_PBC, BTA_ALL_APP_ID, 2}, /* reuse dg spec table */ - {BTA_ID_PBS, BTA_ALL_APP_ID, 8}, /* reuse fts spec table */ - {BTA_ID_OPC, BTA_ALL_APP_ID, 7}, /* reuse ftc spec table */ - {BTA_ID_OPS, BTA_ALL_APP_ID, 8}, /* reuse fts spec table */ - {BTA_ID_MSE, BTA_ALL_APP_ID, 8}, /* reuse fts spec table */ - {BTA_ID_JV, BTA_JV_PM_ID_1, - 7}, /* app BTA_JV_PM_ID_1, reuse ftc spec table */ - {BTA_ID_JV, BTA_ALL_APP_ID, 8}, /* reuse fts spec table */ - {BTA_ID_HL, BTA_ALL_APP_ID, 9}, /* reuse fts spec table */ - {BTA_ID_PAN, BTUI_PAN_ID_PANU, 10}, /* PANU spec table */ - {BTA_ID_PAN, BTUI_PAN_ID_NAP, 11}, /* NAP spec table */ - {BTA_ID_HS, BTA_ALL_APP_ID, 12}, /* HS spec table */ - {BTA_ID_GATTC, BTA_ALL_APP_ID, 14}, /* gattc spec table */ - {BTA_ID_GATTS, BTA_ALL_APP_ID, 15} /* gatts spec table */ +#define BTA_DM_NUM_PM_ENTRY 25 /* number of entries in bta_dm_pm_cfg except the first */ +#define BTA_DM_NUM_PM_SPEC 16 /* number of entries in bta_dm_pm_spec */ + +tBTA_DM_PM_TYPE_QUALIFIER tBTA_DM_PM_CFG bta_dm_pm_cfg[BTA_DM_NUM_PM_ENTRY + 1] = { + {BTA_ID_SYS, BTA_DM_NUM_PM_ENTRY, 0}, /* reserved: specifies length of this table. */ + {BTA_ID_AG, BTA_ALL_APP_ID, 0}, /* ag uses first spec table for app id 0 */ + {BTA_ID_CT, 1, 1}, /* ct (BTA_ID_CT,APP ID=1) spec table */ + {BTA_ID_CG, BTA_ALL_APP_ID, 1}, /* cg reuse ct spec table */ + {BTA_ID_DG, BTA_ALL_APP_ID, 2}, /* dg spec table */ + {BTA_ID_AV, BTA_ALL_APP_ID, 4}, /* av spec table */ + {BTA_ID_FTC, BTA_ALL_APP_ID, 7}, /* ftc spec table */ + {BTA_ID_FTS, BTA_ALL_APP_ID, 8}, /* fts spec table */ + {BTA_ID_HD, BTA_ALL_APP_ID, 3}, /* hd spec table */ + {BTA_ID_HH, BTA_HH_APP_ID_JOY, 5}, /* app BTA_HH_APP_ID_JOY, + similar to hh spec table */ + {BTA_ID_HH, BTA_HH_APP_ID_GPAD, 5}, /* app BTA_HH_APP_ID_GPAD, + similar to hh spec table */ + {BTA_ID_HH, BTA_ALL_APP_ID, 6}, /* hh spec table */ + {BTA_ID_PBC, BTA_ALL_APP_ID, 2}, /* reuse dg spec table */ + {BTA_ID_PBS, BTA_ALL_APP_ID, 8}, /* reuse fts spec table */ + {BTA_ID_OPC, BTA_ALL_APP_ID, 7}, /* reuse ftc spec table */ + {BTA_ID_OPS, BTA_ALL_APP_ID, 8}, /* reuse fts spec table */ + {BTA_ID_MSE, BTA_ALL_APP_ID, 8}, /* reuse fts spec table */ + {BTA_ID_JV, BTA_JV_PM_ID_1, 7}, /* app BTA_JV_PM_ID_1, reuse ftc spec table */ + {BTA_ID_JV, BTA_ALL_APP_ID, 8}, /* reuse fts spec table */ + {BTA_ID_HL, BTA_ALL_APP_ID, 9}, /* reuse fts spec table */ + {BTA_ID_PAN, BTUI_PAN_ID_PANU, 10}, /* PANU spec table */ + {BTA_ID_PAN, BTUI_PAN_ID_NAP, 11}, /* NAP spec table */ + {BTA_ID_HS, BTA_ALL_APP_ID, 12}, /* HS spec table */ + {BTA_ID_GATTC, BTA_ALL_APP_ID, 14}, /* gattc spec table */ + {BTA_ID_GATTS, BTA_ALL_APP_ID, 15} /* gatts spec table */ }; tBTA_DM_PM_TYPE_QUALIFIER tBTA_DM_PM_SPEC* get_bta_dm_pm_spec() { - static uint16_t hs_sniff_delay = uint16_t( - osi_property_get_int32("bluetooth.bta_hs_sniff_delay_ms.config", 7000)); + static uint16_t hs_sniff_delay = + uint16_t(osi_property_get_int32("bluetooth.bta_hs_sniff_delay_ms.config", 7000)); static uint16_t fts_ops_idle_to_sniff_delay_ms = - uint16_t(osi_property_get_int32( - "bluetooth.bta_fts_ops_idle_to_sniff_delay_ms.config", - BTA_FTS_OPS_IDLE_TO_SNIFF_DELAY_MS)); - static uint16_t ftc_idle_to_sniff_delay_ms = uint16_t( - osi_property_get_int32("bluetooth.bta_ftc_idle_to_sniff_delay_ms.config", - BTA_FTC_IDLE_TO_SNIFF_DELAY_MS)); - - static tBTA_DM_PM_TYPE_QUALIFIER tBTA_DM_PM_SPEC - bta_dm_pm_spec[BTA_DM_NUM_PM_SPEC] = { + uint16_t(osi_property_get_int32("bluetooth.bta_fts_ops_idle_to_sniff_delay_ms.config", + BTA_FTS_OPS_IDLE_TO_SNIFF_DELAY_MS)); + static uint16_t ftc_idle_to_sniff_delay_ms = uint16_t(osi_property_get_int32( + "bluetooth.bta_ftc_idle_to_sniff_delay_ms.config", BTA_FTC_IDLE_TO_SNIFF_DELAY_MS)); + + static tBTA_DM_PM_TYPE_QUALIFIER tBTA_DM_PM_SPEC bta_dm_pm_spec[BTA_DM_NUM_PM_SPEC] = { /* AG : 0 */ {(BTA_DM_PM_SNIFF | BTA_DM_PM_PARK), /* allow park & sniff */ (BTA_DM_PM_SSR2), /* the SSR entry */ { - {{BTA_DM_PM_SNIFF_A2DP_IDX, 7000}, - {BTA_DM_PM_NO_ACTION, 0}}, /* conn open sniff */ - {{BTA_DM_PM_NO_PREF, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* conn close */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* app open */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* app close */ - {{BTA_DM_PM_SNIFF_SCO_OPEN_IDX, 7000}, - {BTA_DM_PM_NO_ACTION, 0}}, /* sco open, active */ - {{BTA_DM_PM_SNIFF_A2DP_IDX, 7000}, - {BTA_DM_PM_NO_ACTION, 0}}, /* sco close sniff */ - {{BTA_DM_PM_SNIFF_A2DP_IDX, 7000}, - {BTA_DM_PM_NO_ACTION, 0}}, /* idle */ - {{BTA_DM_PM_ACTIVE, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* busy */ - {{BTA_DM_PM_RETRY, 7000}, - {BTA_DM_PM_NO_ACTION, 0}} /* mode change retry */ + {{BTA_DM_PM_SNIFF_A2DP_IDX, 7000}, + {BTA_DM_PM_NO_ACTION, 0}}, /* conn open sniff */ + {{BTA_DM_PM_NO_PREF, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* conn close */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* app open */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* app close */ + {{BTA_DM_PM_SNIFF_SCO_OPEN_IDX, 7000}, + {BTA_DM_PM_NO_ACTION, 0}}, /* sco open, active */ + {{BTA_DM_PM_SNIFF_A2DP_IDX, 7000}, + {BTA_DM_PM_NO_ACTION, 0}}, /* sco close sniff */ + {{BTA_DM_PM_SNIFF_A2DP_IDX, 7000}, {BTA_DM_PM_NO_ACTION, 0}}, /* idle */ + {{BTA_DM_PM_ACTIVE, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* busy */ + {{BTA_DM_PM_RETRY, 7000}, {BTA_DM_PM_NO_ACTION, 0}} /* mode change retry */ }}, /* CT, CG : 1 */ {(BTA_DM_PM_SNIFF | BTA_DM_PM_PARK), /* allow park & sniff */ (BTA_DM_PM_SSR2), /* the SSR entry */ { - {{BTA_DM_PM_PARK, 5000}, - {BTA_DM_PM_NO_ACTION, 0}}, /* conn open park */ - {{BTA_DM_PM_NO_PREF, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* conn close */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* app open */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* app close */ - {{BTA_DM_PM_SNIFF_A2DP_IDX, 5000}, - {BTA_DM_PM_NO_ACTION, 0}}, /* sco open sniff */ - {{BTA_DM_PM_PARK, 5000}, - {BTA_DM_PM_NO_ACTION, 0}}, /* sco close park */ - {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* idle */ - {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* busy */ - {{BTA_DM_PM_RETRY, 5000}, - {BTA_DM_PM_NO_ACTION, 0}} /* mode change retry */ + {{BTA_DM_PM_PARK, 5000}, {BTA_DM_PM_NO_ACTION, 0}}, /* conn open park */ + {{BTA_DM_PM_NO_PREF, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* conn close */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* app open */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* app close */ + {{BTA_DM_PM_SNIFF_A2DP_IDX, 5000}, + {BTA_DM_PM_NO_ACTION, 0}}, /* sco open sniff */ + {{BTA_DM_PM_PARK, 5000}, {BTA_DM_PM_NO_ACTION, 0}}, /* sco close park */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* idle */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* busy */ + {{BTA_DM_PM_RETRY, 5000}, {BTA_DM_PM_NO_ACTION, 0}} /* mode change retry */ }}, /* DG, PBC : 2 */ {(BTA_DM_PM_ACTIVE), /* no power saving mode allowed */ (BTA_DM_PM_SSR2), /* the SSR entry */ { - {{BTA_DM_PM_SNIFF, 5000}, - {BTA_DM_PM_NO_ACTION, 0}}, /* conn open active */ - {{BTA_DM_PM_NO_PREF, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* conn close */ - {{BTA_DM_PM_ACTIVE, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* app open */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* app close */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* sco open */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* sco close */ - {{BTA_DM_PM_SNIFF, 1000}, {BTA_DM_PM_NO_ACTION, 0}}, /* idle */ - {{BTA_DM_PM_ACTIVE, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* busy */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}} /* mode change retry */ + {{BTA_DM_PM_SNIFF, 5000}, {BTA_DM_PM_NO_ACTION, 0}}, /* conn open active */ + {{BTA_DM_PM_NO_PREF, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* conn close */ + {{BTA_DM_PM_ACTIVE, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* app open */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* app close */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* sco open */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* sco close */ + {{BTA_DM_PM_SNIFF, 1000}, {BTA_DM_PM_NO_ACTION, 0}}, /* idle */ + {{BTA_DM_PM_ACTIVE, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* busy */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}} /* mode change retry */ }}, /* HD : 3 */ {(BTA_DM_PM_SNIFF | BTA_DM_PM_PARK), /* allow park & sniff */ (BTA_DM_PM_SSR3), /* the SSR entry */ { - {{BTA_DM_PM_SNIFF_HD_ACTIVE_IDX, 5000}, - {BTA_DM_PM_NO_ACTION, 0}}, /* conn open sniff */ - {{BTA_DM_PM_NO_PREF, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* conn close */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* app open */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* app close */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* sco open */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* sco close */ - {{BTA_DM_PM_SNIFF_HD_IDLE_IDX, 5000}, - {BTA_DM_PM_NO_ACTION, 0}}, /* idle */ - {{BTA_DM_PM_SNIFF_HD_ACTIVE_IDX, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* busy */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}} /* mode change retry */ + {{BTA_DM_PM_SNIFF_HD_ACTIVE_IDX, 5000}, + {BTA_DM_PM_NO_ACTION, 0}}, /* conn open sniff */ + {{BTA_DM_PM_NO_PREF, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* conn close */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* app open */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* app close */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* sco open */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* sco close */ + {{BTA_DM_PM_SNIFF_HD_IDLE_IDX, 5000}, {BTA_DM_PM_NO_ACTION, 0}}, /* idle */ + {{BTA_DM_PM_SNIFF_HD_ACTIVE_IDX, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* busy */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}} /* mode change retry */ }}, /* AV : 4 */ {(BTA_DM_PM_SNIFF), /* allow sniff */ (BTA_DM_PM_SSR2), /* the SSR entry */ { - {{BTA_DM_PM_SNIFF_A2DP_IDX, 7000}, - {BTA_DM_PM_NO_ACTION, 0}}, /* conn open sniff */ - {{BTA_DM_PM_NO_PREF, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* conn close */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* app open */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* app close */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* sco open */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* sco close */ - {{BTA_DM_PM_SNIFF_A2DP_IDX, 7000}, - {BTA_DM_PM_NO_ACTION, 0}}, /* idle */ - {{BTA_DM_PM_ACTIVE, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* busy */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}} /* mode change retry */ + {{BTA_DM_PM_SNIFF_A2DP_IDX, 7000}, + {BTA_DM_PM_NO_ACTION, 0}}, /* conn open sniff */ + {{BTA_DM_PM_NO_PREF, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* conn close */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* app open */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* app close */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* sco open */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* sco close */ + {{BTA_DM_PM_SNIFF_A2DP_IDX, 7000}, {BTA_DM_PM_NO_ACTION, 0}}, /* idle */ + {{BTA_DM_PM_ACTIVE, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* busy */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}} /* mode change retry */ }}, /* HH for joysticks and gamepad : 5 */ {(BTA_DM_PM_SNIFF | BTA_DM_PM_PARK), /* allow park & sniff */ (BTA_DM_PM_SSR1), /* the SSR entry */ { - {{BTA_DM_PM_SNIFF6, BTA_DM_PM_HH_OPEN_DELAY}, - {BTA_DM_PM_NO_ACTION, 0}}, /* conn open sniff */ - {{BTA_DM_PM_NO_PREF, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* conn close */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* app open */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* app close */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* sco open */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* sco close, used for HH suspend */ - {{BTA_DM_PM_SNIFF6, BTA_DM_PM_HH_IDLE_DELAY}, - {BTA_DM_PM_NO_ACTION, 0}}, /* idle */ - {{BTA_DM_PM_SNIFF6, BTA_DM_PM_HH_ACTIVE_DELAY}, - {BTA_DM_PM_NO_ACTION, 0}}, /* busy */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}} /* mode change retry */ + {{BTA_DM_PM_SNIFF6, BTA_DM_PM_HH_OPEN_DELAY}, + {BTA_DM_PM_NO_ACTION, 0}}, /* conn open sniff */ + {{BTA_DM_PM_NO_PREF, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* conn close */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* app open */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* app close */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* sco open */ + {{BTA_DM_PM_NO_ACTION, 0}, + {BTA_DM_PM_NO_ACTION, 0}}, /* sco close, used for HH suspend */ + {{BTA_DM_PM_SNIFF6, BTA_DM_PM_HH_IDLE_DELAY}, + {BTA_DM_PM_NO_ACTION, 0}}, /* idle */ + {{BTA_DM_PM_SNIFF6, BTA_DM_PM_HH_ACTIVE_DELAY}, + {BTA_DM_PM_NO_ACTION, 0}}, /* busy */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}} /* mode change retry */ }}, /* HH : 6 */ {(BTA_DM_PM_SNIFF | BTA_DM_PM_PARK), /* allow park & sniff */ (BTA_DM_PM_SSR1), /* the SSR entry */ { - {{BTA_DM_PM_SNIFF_HH_OPEN_IDX, BTA_DM_PM_HH_OPEN_DELAY}, - {BTA_DM_PM_NO_ACTION, 0}}, /* conn open sniff */ - {{BTA_DM_PM_NO_PREF, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* conn close */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* app open */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* app close */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* sco open */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* sco close, used for HH suspend */ - {{BTA_DM_PM_SNIFF_HH_IDLE_IDX, BTA_DM_PM_HH_IDLE_DELAY}, - {BTA_DM_PM_NO_ACTION, 0}}, /* idle */ - {{BTA_DM_PM_SNIFF_HH_ACTIVE_IDX, BTA_DM_PM_HH_ACTIVE_DELAY}, - {BTA_DM_PM_NO_ACTION, 0}}, /* busy */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}} /* mode change retry */ + {{BTA_DM_PM_SNIFF_HH_OPEN_IDX, BTA_DM_PM_HH_OPEN_DELAY}, + {BTA_DM_PM_NO_ACTION, 0}}, /* conn open sniff */ + {{BTA_DM_PM_NO_PREF, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* conn close */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* app open */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* app close */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* sco open */ + {{BTA_DM_PM_NO_ACTION, 0}, + {BTA_DM_PM_NO_ACTION, 0}}, /* sco close, used for HH suspend */ + {{BTA_DM_PM_SNIFF_HH_IDLE_IDX, BTA_DM_PM_HH_IDLE_DELAY}, + {BTA_DM_PM_NO_ACTION, 0}}, /* idle */ + {{BTA_DM_PM_SNIFF_HH_ACTIVE_IDX, BTA_DM_PM_HH_ACTIVE_DELAY}, + {BTA_DM_PM_NO_ACTION, 0}}, /* busy */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}} /* mode change retry */ }}, /* FTC, OPC, JV : 7 */ {(BTA_DM_PM_SNIFF), /* allow sniff */ (BTA_DM_PM_SSR2), /* the SSR entry */ { - {{BTA_DM_PM_ACTIVE, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* conn open active */ - {{BTA_DM_PM_NO_PREF, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* conn close */ - {{BTA_DM_PM_ACTIVE, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* app open */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* app close */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* sco open */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* sco close */ - {{BTA_DM_PM_SNIFF_A2DP_IDX, ftc_idle_to_sniff_delay_ms}, - {BTA_DM_PM_NO_ACTION, 0}}, /* idle */ - {{BTA_DM_PM_ACTIVE, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* busy */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}} /* mode change retry */ + {{BTA_DM_PM_ACTIVE, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* conn open active */ + {{BTA_DM_PM_NO_PREF, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* conn close */ + {{BTA_DM_PM_ACTIVE, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* app open */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* app close */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* sco open */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* sco close */ + {{BTA_DM_PM_SNIFF_A2DP_IDX, ftc_idle_to_sniff_delay_ms}, + {BTA_DM_PM_NO_ACTION, 0}}, /* idle */ + {{BTA_DM_PM_ACTIVE, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* busy */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}} /* mode change retry */ }}, /* FTS, PBS, OPS, MSE, BTA_JV_PM_ID_1 : 8 */ {(BTA_DM_PM_SNIFF), /* allow sniff */ (BTA_DM_PM_SSR2), /* the SSR entry */ { - {{BTA_DM_PM_ACTIVE, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* conn open active */ - {{BTA_DM_PM_NO_PREF, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* conn close */ - {{BTA_DM_PM_ACTIVE, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* app open */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* app close */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* sco open */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* sco close */ - {{BTA_DM_PM_SNIFF_A2DP_IDX, fts_ops_idle_to_sniff_delay_ms}, - {BTA_DM_PM_NO_ACTION, 0}}, /* idle */ - {{BTA_DM_PM_ACTIVE, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* busy */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}} /* mode change retry */ + {{BTA_DM_PM_ACTIVE, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* conn open active */ + {{BTA_DM_PM_NO_PREF, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* conn close */ + {{BTA_DM_PM_ACTIVE, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* app open */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* app close */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* sco open */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* sco close */ + {{BTA_DM_PM_SNIFF_A2DP_IDX, fts_ops_idle_to_sniff_delay_ms}, + {BTA_DM_PM_NO_ACTION, 0}}, /* idle */ + {{BTA_DM_PM_ACTIVE, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* busy */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}} /* mode change retry */ }}, /* HL : 9 */ {(BTA_DM_PM_SNIFF), /* allow sniff */ (BTA_DM_PM_SSR2), /* the SSR entry */ { - {{BTA_DM_PM_SNIFF_A2DP_IDX, 5000}, - {BTA_DM_PM_NO_ACTION, 0}}, /* conn open sniff */ - {{BTA_DM_PM_NO_PREF, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* conn close */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* app open */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* app close */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* sco open, active */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* sco close sniff */ - {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* idle */ - {{BTA_DM_PM_ACTIVE, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* busy */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}} /* mode change retry */ + {{BTA_DM_PM_SNIFF_A2DP_IDX, 5000}, + {BTA_DM_PM_NO_ACTION, 0}}, /* conn open sniff */ + {{BTA_DM_PM_NO_PREF, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* conn close */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* app open */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* app close */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* sco open, active */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* sco close sniff */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* idle */ + {{BTA_DM_PM_ACTIVE, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* busy */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}} /* mode change retry */ }}, /* PANU : 10 */ {(BTA_DM_PM_SNIFF), /* allow sniff */ (BTA_DM_PM_SSR2), /* the SSR entry */ { - {{BTA_DM_PM_ACTIVE, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* conn open active */ - {{BTA_DM_PM_NO_PREF, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* conn close */ - {{BTA_DM_PM_ACTIVE, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* app open */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* app close */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* sco open */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* sco close */ - {{BTA_DM_PM_SNIFF_A2DP_IDX, 5000}, - {BTA_DM_PM_NO_ACTION, 0}}, /* idle */ - {{BTA_DM_PM_ACTIVE, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* busy */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}} /* mode change retry */ + {{BTA_DM_PM_ACTIVE, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* conn open active */ + {{BTA_DM_PM_NO_PREF, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* conn close */ + {{BTA_DM_PM_ACTIVE, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* app open */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* app close */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* sco open */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* sco close */ + {{BTA_DM_PM_SNIFF_A2DP_IDX, 5000}, {BTA_DM_PM_NO_ACTION, 0}}, /* idle */ + {{BTA_DM_PM_ACTIVE, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* busy */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}} /* mode change retry */ }}, /* NAP : 11 */ {(BTA_DM_PM_SNIFF), /* allow sniff */ (BTA_DM_PM_SSR2), /* the SSR entry */ { - {{BTA_DM_PM_ACTIVE, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* conn open active */ - {{BTA_DM_PM_NO_PREF, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* conn close */ - {{BTA_DM_PM_ACTIVE, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* app open */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* app close */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* sco open */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* sco close */ - {{BTA_DM_PM_SNIFF_A2DP_IDX, 5000}, - {BTA_DM_PM_NO_ACTION, 0}}, /* idle */ - {{BTA_DM_PM_ACTIVE, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* busy */ - - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}} /* mode change retry */ + {{BTA_DM_PM_ACTIVE, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* conn open active */ + {{BTA_DM_PM_NO_PREF, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* conn close */ + {{BTA_DM_PM_ACTIVE, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* app open */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* app close */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* sco open */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* sco close */ + {{BTA_DM_PM_SNIFF_A2DP_IDX, 5000}, {BTA_DM_PM_NO_ACTION, 0}}, /* idle */ + {{BTA_DM_PM_ACTIVE, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* busy */ + + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}} /* mode change retry */ }}, /* HS : 12 */ {(BTA_DM_PM_SNIFF | BTA_DM_PM_PARK), /* allow park & sniff */ (BTA_DM_PM_SSR2), /* the SSR entry */ { - {{BTA_DM_PM_SNIFF, hs_sniff_delay}, - {BTA_DM_PM_NO_ACTION, 0}}, /* conn open sniff */ - {{BTA_DM_PM_NO_PREF, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* conn close */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* app open */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* app close */ - {{BTA_DM_PM_SNIFF3, 7000}, - {BTA_DM_PM_NO_ACTION, 0}}, /* sco open, active */ - {{BTA_DM_PM_SNIFF, 7000}, - {BTA_DM_PM_NO_ACTION, 0}}, /* sco close sniff */ - {{BTA_DM_PM_SNIFF, hs_sniff_delay}, - {BTA_DM_PM_NO_ACTION, 0}}, /* idle */ - {{BTA_DM_PM_ACTIVE, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* busy */ - {{BTA_DM_PM_RETRY, 7000}, - {BTA_DM_PM_NO_ACTION, 0}} /* mode change retry */ + {{BTA_DM_PM_SNIFF, hs_sniff_delay}, + {BTA_DM_PM_NO_ACTION, 0}}, /* conn open sniff */ + {{BTA_DM_PM_NO_PREF, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* conn close */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* app open */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* app close */ + {{BTA_DM_PM_SNIFF3, 7000}, {BTA_DM_PM_NO_ACTION, 0}}, /* sco open, active */ + {{BTA_DM_PM_SNIFF, 7000}, {BTA_DM_PM_NO_ACTION, 0}}, /* sco close sniff */ + {{BTA_DM_PM_SNIFF, hs_sniff_delay}, {BTA_DM_PM_NO_ACTION, 0}}, /* idle */ + {{BTA_DM_PM_ACTIVE, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* busy */ + {{BTA_DM_PM_RETRY, 7000}, {BTA_DM_PM_NO_ACTION, 0}} /* mode change retry */ }}, /* AVK : 13 */ {(BTA_DM_PM_SNIFF), /* allow sniff */ (BTA_DM_PM_SSR2), /* the SSR entry */ { - {{BTA_DM_PM_SNIFF, 3000}, - {BTA_DM_PM_NO_ACTION, 0}}, /* conn open sniff */ - {{BTA_DM_PM_NO_PREF, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* conn close */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* app open */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* app close */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* sco open */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* sco close */ - {{BTA_DM_PM_SNIFF4, 3000}, {BTA_DM_PM_NO_ACTION, 0}}, /* idle */ - {{BTA_DM_PM_ACTIVE, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* busy */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}} /* mode change retry */ + {{BTA_DM_PM_SNIFF, 3000}, {BTA_DM_PM_NO_ACTION, 0}}, /* conn open sniff */ + {{BTA_DM_PM_NO_PREF, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* conn close */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* app open */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* app close */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* sco open */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* sco close */ + {{BTA_DM_PM_SNIFF4, 3000}, {BTA_DM_PM_NO_ACTION, 0}}, /* idle */ + {{BTA_DM_PM_ACTIVE, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* busy */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}} /* mode change retry */ }}, /* GATTC : 14 */ {(BTA_DM_PM_SNIFF | BTA_DM_PM_PARK), /* allow park & sniff */ (BTA_DM_PM_SSR2), /* the SSR entry */ { - {{BTA_DM_PM_SNIFF_A2DP_IDX, 10000}, - {BTA_DM_PM_NO_ACTION, 0}}, /* conn open active */ - {{BTA_DM_PM_NO_PREF, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* conn close */ - {{BTA_DM_PM_ACTIVE, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* app open */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* app close */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* sco open */ - {{BTA_DM_PM_NO_ACTION, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* sco close */ - {{BTA_DM_PM_SNIFF_A2DP_IDX, 10000}, - {BTA_DM_PM_NO_ACTION, 0}}, /* idle */ - {{BTA_DM_PM_ACTIVE, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* busy */ - {{BTA_DM_PM_RETRY, 5000}, - {BTA_DM_PM_NO_ACTION, 0}} /* mode change retry */ + {{BTA_DM_PM_SNIFF_A2DP_IDX, 10000}, + {BTA_DM_PM_NO_ACTION, 0}}, /* conn open active */ + {{BTA_DM_PM_NO_PREF, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* conn close */ + {{BTA_DM_PM_ACTIVE, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* app open */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* app close */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* sco open */ + {{BTA_DM_PM_NO_ACTION, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* sco close */ + {{BTA_DM_PM_SNIFF_A2DP_IDX, 10000}, {BTA_DM_PM_NO_ACTION, 0}}, /* idle */ + {{BTA_DM_PM_ACTIVE, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* busy */ + {{BTA_DM_PM_RETRY, 5000}, {BTA_DM_PM_NO_ACTION, 0}} /* mode change retry */ }}, /* GATTS : 15 */ {(BTA_DM_PM_SNIFF | BTA_DM_PM_PARK), /* allow park & sniff */ (BTA_DM_PM_SSR2), /* the SSR entry */ { - {{BTA_DM_PM_NO_PREF, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* conn open active */ - {{BTA_DM_PM_NO_PREF, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* conn close */ - {{BTA_DM_PM_NO_PREF, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* app open */ - {{BTA_DM_PM_NO_PREF, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* app close */ - {{BTA_DM_PM_NO_PREF, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* sco open */ - {{BTA_DM_PM_NO_PREF, 0}, - {BTA_DM_PM_NO_ACTION, 0}}, /* sco close */ - {{BTA_DM_PM_NO_PREF, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* idle */ - {{BTA_DM_PM_NO_PREF, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* busy */ - {{BTA_DM_PM_RETRY, 5000}, - {BTA_DM_PM_NO_ACTION, 0}} /* mode change retry */ + {{BTA_DM_PM_NO_PREF, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* conn open active */ + {{BTA_DM_PM_NO_PREF, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* conn close */ + {{BTA_DM_PM_NO_PREF, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* app open */ + {{BTA_DM_PM_NO_PREF, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* app close */ + {{BTA_DM_PM_NO_PREF, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* sco open */ + {{BTA_DM_PM_NO_PREF, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* sco close */ + {{BTA_DM_PM_NO_PREF, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* idle */ + {{BTA_DM_PM_NO_PREF, 0}, {BTA_DM_PM_NO_ACTION, 0}}, /* busy */ + {{BTA_DM_PM_RETRY, 5000}, {BTA_DM_PM_NO_ACTION, 0}} /* mode change retry */ }} #ifdef BTE_SIM_APP /* For Insight builds only */ @@ -510,8 +400,8 @@ tBTA_DM_PM_TYPE_QUALIFIER tBTA_DM_PM_SPEC* get_bta_dm_pm_spec() { , {BTA_DM_PM_NO_PREF}, /* pm_spec USER_DEFINED_0 */ {BTA_DM_PM_NO_PREF} /* pm_spec USER_DEFINED_1 */ -#endif /* BTE_SIM_APP */ - }; +#endif /* BTE_SIM_APP */ + }; return bta_dm_pm_spec; } @@ -536,58 +426,53 @@ tBTA_DM_PM_TYPE_QUALIFIER tBTA_DM_PM_SPEC* get_bta_dm_pm_spec() { * be selected. */ tBTA_DM_PM_TYPE_QUALIFIER tBTM_PM_PWR_MD bta_dm_pm_md[] = { - /* - * More sniff parameter entries can be added for - * BTA_DM_PM_SNIFF3 - BTA_DM_PM_SNIFF7, if needed. When entries are added or - * removed, BTA_DM_PM_PARK_IDX needs to be updated to reflect the actual - * index - * BTA_DM_PM_PARK_IDX is defined in bta_api.h and can be override by the - * bdroid_buildcfg.h settings. - * The SNIFF table entries must be in the order from highest latency - * (biggest - * interval) to lowest latency. If there's a conflict among the connected - * services, the setting with lowest latency wins. - */ - /* sniff modes: max interval, min interval, attempt, timeout */ - {BTA_DM_PM_SNIFF_MAX, BTA_DM_PM_SNIFF_MIN, BTA_DM_PM_SNIFF_ATTEMPT, - BTA_DM_PM_SNIFF_TIMEOUT, BTM_PM_MD_SNIFF}, /* for BTA_DM_PM_SNIFF - A2DP */ - {BTA_DM_PM_SNIFF1_MAX, BTA_DM_PM_SNIFF1_MIN, BTA_DM_PM_SNIFF1_ATTEMPT, - BTA_DM_PM_SNIFF1_TIMEOUT, BTM_PM_MD_SNIFF}, /* for BTA_DM_PM_SNIFF1 */ - {BTA_DM_PM_SNIFF2_MAX, BTA_DM_PM_SNIFF2_MIN, BTA_DM_PM_SNIFF2_ATTEMPT, - BTA_DM_PM_SNIFF2_TIMEOUT, - BTM_PM_MD_SNIFF}, /* for BTA_DM_PM_SNIFF2- HD idle */ - {BTA_DM_PM_SNIFF3_MAX, BTA_DM_PM_SNIFF3_MIN, BTA_DM_PM_SNIFF3_ATTEMPT, - BTA_DM_PM_SNIFF3_TIMEOUT, - BTM_PM_MD_SNIFF}, /* for BTA_DM_PM_SNIFF3- SCO open */ - {BTA_DM_PM_SNIFF4_MAX, BTA_DM_PM_SNIFF4_MIN, BTA_DM_PM_SNIFF4_ATTEMPT, - BTA_DM_PM_SNIFF4_TIMEOUT, - BTM_PM_MD_SNIFF}, /* for BTA_DM_PM_SNIFF4- HD active */ - {BTA_DM_PM_SNIFF5_MAX, BTA_DM_PM_SNIFF5_MIN, BTA_DM_PM_SNIFF5_ATTEMPT, - BTA_DM_PM_SNIFF5_TIMEOUT, - BTM_PM_MD_SNIFF}, /* for BTA_DM_PM_SNIFF5- HD active */ - {BTA_DM_PM_SNIFF6_MAX, BTA_DM_PM_SNIFF6_MIN, BTA_DM_PM_SNIFF6_ATTEMPT, - BTA_DM_PM_SNIFF6_TIMEOUT, - BTM_PM_MD_SNIFF}, /* for BTA_DM_PM_SNIFF6- HD active */ - {BTA_DM_PM_PARK_MAX, BTA_DM_PM_PARK_MIN, BTA_DM_PM_PARK_ATTEMPT, - BTA_DM_PM_PARK_TIMEOUT, BTM_PM_MD_PARK} + /* + * More sniff parameter entries can be added for + * BTA_DM_PM_SNIFF3 - BTA_DM_PM_SNIFF7, if needed. When entries are added or + * removed, BTA_DM_PM_PARK_IDX needs to be updated to reflect the actual + * index + * BTA_DM_PM_PARK_IDX is defined in bta_api.h and can be override by the + * bdroid_buildcfg.h settings. + * The SNIFF table entries must be in the order from highest latency + * (biggest + * interval) to lowest latency. If there's a conflict among the connected + * services, the setting with lowest latency wins. + */ + /* sniff modes: max interval, min interval, attempt, timeout */ + {BTA_DM_PM_SNIFF_MAX, BTA_DM_PM_SNIFF_MIN, BTA_DM_PM_SNIFF_ATTEMPT, BTA_DM_PM_SNIFF_TIMEOUT, + BTM_PM_MD_SNIFF}, /* for BTA_DM_PM_SNIFF - A2DP */ + {BTA_DM_PM_SNIFF1_MAX, BTA_DM_PM_SNIFF1_MIN, BTA_DM_PM_SNIFF1_ATTEMPT, + BTA_DM_PM_SNIFF1_TIMEOUT, BTM_PM_MD_SNIFF}, /* for BTA_DM_PM_SNIFF1 */ + {BTA_DM_PM_SNIFF2_MAX, BTA_DM_PM_SNIFF2_MIN, BTA_DM_PM_SNIFF2_ATTEMPT, + BTA_DM_PM_SNIFF2_TIMEOUT, BTM_PM_MD_SNIFF}, /* for BTA_DM_PM_SNIFF2- HD idle */ + {BTA_DM_PM_SNIFF3_MAX, BTA_DM_PM_SNIFF3_MIN, BTA_DM_PM_SNIFF3_ATTEMPT, + BTA_DM_PM_SNIFF3_TIMEOUT, BTM_PM_MD_SNIFF}, /* for BTA_DM_PM_SNIFF3- SCO open */ + {BTA_DM_PM_SNIFF4_MAX, BTA_DM_PM_SNIFF4_MIN, BTA_DM_PM_SNIFF4_ATTEMPT, + BTA_DM_PM_SNIFF4_TIMEOUT, BTM_PM_MD_SNIFF}, /* for BTA_DM_PM_SNIFF4- HD active */ + {BTA_DM_PM_SNIFF5_MAX, BTA_DM_PM_SNIFF5_MIN, BTA_DM_PM_SNIFF5_ATTEMPT, + BTA_DM_PM_SNIFF5_TIMEOUT, BTM_PM_MD_SNIFF}, /* for BTA_DM_PM_SNIFF5- HD active */ + {BTA_DM_PM_SNIFF6_MAX, BTA_DM_PM_SNIFF6_MIN, BTA_DM_PM_SNIFF6_ATTEMPT, + BTA_DM_PM_SNIFF6_TIMEOUT, BTM_PM_MD_SNIFF}, /* for BTA_DM_PM_SNIFF6- HD active */ + {BTA_DM_PM_PARK_MAX, BTA_DM_PM_PARK_MIN, BTA_DM_PM_PARK_ATTEMPT, BTA_DM_PM_PARK_TIMEOUT, + BTM_PM_MD_PARK} #ifdef BTE_SIM_APP /* For Insight builds only */ - /* Entries at the end of the bta_dm_pm_md table are user-defined (runtime - configurable), - for power consumption experiments. - Insight finds the first user-defined entry by looking for the first - 'max=0'. - The number of user_defined specs is defined by BTA_SWRAP_UD_PM_DM_COUNT - */ - , - {0}, /* CONN_OPEN/SCO_CLOSE power mode settings for pm_spec USER_DEFINED_0 - */ - {0}, /* SCO_OPEN power mode settings for pm_spec USER_DEFINED_0 */ - - {0}, /* CONN_OPEN/SCO_CLOSE power mode settings for pm_spec USER_DEFINED_1 - */ - {0} /* SCO_OPEN power mode settings for pm_spec USER_DEFINED_1 */ -#endif /* BTE_SIM_APP */ + /* Entries at the end of the bta_dm_pm_md table are user-defined (runtime + configurable), + for power consumption experiments. + Insight finds the first user-defined entry by looking for the first + 'max=0'. + The number of user_defined specs is defined by BTA_SWRAP_UD_PM_DM_COUNT + */ + , + {0}, /* CONN_OPEN/SCO_CLOSE power mode settings for pm_spec USER_DEFINED_0 + */ + {0}, /* SCO_OPEN power mode settings for pm_spec USER_DEFINED_0 */ + + {0}, /* CONN_OPEN/SCO_CLOSE power mode settings for pm_spec USER_DEFINED_1 + */ + {0} /* SCO_OPEN power mode settings for pm_spec USER_DEFINED_1 */ +#endif /* BTE_SIM_APP */ }; /* 0=max_lat -> no SSR */ @@ -595,16 +480,16 @@ tBTA_DM_PM_TYPE_QUALIFIER tBTM_PM_PWR_MD bta_dm_pm_md[] = { * the entries in this table must be from highest latency (biggest interval) to * lowest latency */ tBTA_DM_SSR_SPEC bta_dm_ssr_spec[] = { - /*max_lat, min_rmt_to, min_loc_to*/ - {0, 0, 0, "no_ssr"}, /* BTA_DM_PM_SSR0 - do not use SSR */ - /* BTA_DM_PM_SSR1 - HH, can NOT share entry with any other profile, seting - default max latency and min remote timeout as 0, and always read - individual device preference from HH module */ - {0, 0, 2, "hid_host"}, - {1200, 2, 2, "sniff_capable"}, /* BTA_DM_PM_SSR2 - others (as long as sniff - is allowed)*/ - {360, 160, 1600, "hid_device"}, /* BTA_DM_PM_SSR3 - HD */ - {1200, 65534, 65534, "a2dp"} /* BTA_DM_PM_SSR4 - A2DP streaming */ + /*max_lat, min_rmt_to, min_loc_to*/ + {0, 0, 0, "no_ssr"}, /* BTA_DM_PM_SSR0 - do not use SSR */ + /* BTA_DM_PM_SSR1 - HH, can NOT share entry with any other profile, setting + default max latency and min remote timeout as 0, and always read + individual device preference from HH module */ + {0, 0, 2, "hid_host"}, + {1200, 2, 2, "sniff_capable"}, /* BTA_DM_PM_SSR2 - others (as long as sniff + is allowed)*/ + {360, 160, 1600, "hid_device"}, /* BTA_DM_PM_SSR3 - HD */ + {1200, 65534, 65534, "a2dp"} /* BTA_DM_PM_SSR4 - A2DP streaming */ }; tBTA_DM_SSR_SPEC* p_bta_dm_ssr_spec = &bta_dm_ssr_spec[0]; @@ -625,23 +510,23 @@ const tBTM_PM_PWR_MD* p_bta_dm_pm_md = &bta_dm_pm_md[0]; /* Extended Inquiry Response */ const tBTA_DM_EIR_CONF bta_dm_eir_cfg = { - 50, /* minimum length of local name when it is shortened */ - /* if length of local name is longer than this and EIR has not enough */ - /* room for all UUID list then local name is shortened to this length */ - { - /* mask of UUID list in EIR */ - 0xFFFFFFFF, /* LSB is the first UUID of the first 32 UUIDs in - BTM_EIR_UUID_LKUP_TBL */ - 0xFFFFFFFF /* LSB is the first UUID of the next 32 UUIDs in - BTM_EIR_UUID_LKUP_TBL */ - /* BTM_EIR_UUID_LKUP_TBL can be overrided */ - }, - NULL, /* Inquiry TX power */ - 0, /* length of flags in bytes */ - NULL, /* flags for EIR */ - 0, /* length of manufacturer specific in bytes */ - NULL, /* manufacturer specific */ - 0, /* length of additional data in bytes */ - NULL /* additional data */ + 50, /* minimum length of local name when it is shortened */ + /* if length of local name is longer than this and EIR has not enough */ + /* room for all UUID list then local name is shortened to this length */ + { + /* mask of UUID list in EIR */ + 0xFFFFFFFF, /* LSB is the first UUID of the first 32 UUIDs in + BTM_EIR_UUID_LKUP_TBL */ + 0xFFFFFFFF /* LSB is the first UUID of the next 32 UUIDs in + BTM_EIR_UUID_LKUP_TBL */ + /* BTM_EIR_UUID_LKUP_TBL can be overrided */ + }, + NULL, /* Inquiry TX power */ + 0, /* length of flags in bytes */ + NULL, /* flags for EIR */ + 0, /* length of manufacturer specific in bytes */ + NULL, /* manufacturer specific */ + 0, /* length of additional data in bytes */ + NULL /* additional data */ }; const tBTA_DM_EIR_CONF* p_bta_dm_eir_cfg = &bta_dm_eir_cfg; diff --git a/system/bta/dm/bta_dm_ci.cc b/system/bta/dm/bta_dm_ci.cc index b1f9be483bd..7932d8374dd 100644 --- a/system/bta/dm/bta_dm_ci.cc +++ b/system/bta/dm/bta_dm_ci.cc @@ -40,17 +40,13 @@ * Returns void * ******************************************************************************/ -void bta_dm_ci_rmt_oob(bool accept, const RawAddress& bd_addr, const Octet16& c, - const Octet16& r) { - std::unique_ptr msg = - std::make_unique(); +void bta_dm_ci_rmt_oob(bool accept, const RawAddress& bd_addr, const Octet16& c, const Octet16& r) { + std::unique_ptr msg = std::make_unique(); msg->bd_addr = bd_addr; msg->accept = accept; msg->c = c; msg->r = r; - do_in_main_thread(FROM_HERE, - base::Bind(bta_dm_ci_rmt_oob_act, base::Passed(&msg))); + do_in_main_thread(FROM_HERE, base::Bind(bta_dm_ci_rmt_oob_act, base::Passed(&msg))); } - diff --git a/system/bta/dm/bta_dm_device_search.cc b/system/bta/dm/bta_dm_device_search.cc index 6a1a402a869..491adc42a10 100644 --- a/system/bta/dm/bta_dm_device_search.cc +++ b/system/bta/dm/bta_dm_device_search.cc @@ -56,16 +56,14 @@ constexpr char kBtmLogTag[] = "DEV_SEARCH"; tBTA_DM_SEARCH_CB bta_dm_search_cb; } // namespace -static void bta_dm_inq_results_cb(tBTM_INQ_RESULTS* p_inq, const uint8_t* p_eir, - uint16_t eir_len); +static void bta_dm_inq_results_cb(tBTM_INQ_RESULTS* p_inq, const uint8_t* p_eir, uint16_t eir_len); static void bta_dm_inq_cmpl(); static void bta_dm_inq_cmpl_cb(void* p_result); static void bta_dm_search_cmpl(); static void bta_dm_discover_next_device(void); static void bta_dm_remname_cback(const tBTM_REMOTE_DEV_NAME* p); -static bool bta_dm_read_remote_device_name(const RawAddress& bd_addr, - tBT_TRANSPORT transport); +static bool bta_dm_read_remote_device_name(const RawAddress& bd_addr, tBT_TRANSPORT transport); static void bta_dm_discover_name(const RawAddress& remote_bd_addr); static void bta_dm_execute_queued_search_request(); static void bta_dm_search_cancel_notify(); @@ -73,8 +71,8 @@ static void bta_dm_disable_search(); static void bta_dm_search_sm_execute(tBTA_DM_DEV_SEARCH_EVT event, std::unique_ptr msg); -static void bta_dm_observe_results_cb(tBTM_INQ_RESULTS* p_inq, - const uint8_t* p_eir, uint16_t eir_len); +static void bta_dm_observe_results_cb(tBTM_INQ_RESULTS* p_inq, const uint8_t* p_eir, + uint16_t eir_len); static void bta_dm_observe_cmpl_cb(void* p_result); static void bta_dm_search_set_state(tBTA_DM_DEVICE_SEARCH_STATE state) { @@ -84,18 +82,15 @@ static tBTA_DM_DEVICE_SEARCH_STATE bta_dm_search_get_state() { return bta_dm_search_cb.search_state; } -static void post_search_evt(tBTA_DM_DEV_SEARCH_EVT event, - std::unique_ptr msg) { - if (do_in_main_thread(FROM_HERE, base::BindOnce(&bta_dm_search_sm_execute, - event, std::move(msg))) != - BT_STATUS_SUCCESS) { +static void post_search_evt(tBTA_DM_DEV_SEARCH_EVT event, std::unique_ptr msg) { + if (do_in_main_thread(FROM_HERE, base::BindOnce(&bta_dm_search_sm_execute, event, + std::move(msg))) != BT_STATUS_SUCCESS) { log::error("post_search_evt failed"); } } void bta_dm_disc_disable_search() { - if (!com::android::bluetooth::flags:: - separate_service_and_device_discovery()) { + if (!com::android::bluetooth::flags::separate_service_and_device_discovery()) { log::info("no-op when flag is disabled"); return; } @@ -119,8 +114,7 @@ static void bta_dm_search_start(tBTA_DM_API_SEARCH& search) { /* save search params */ bta_dm_search_cb.p_device_search_cback = search.p_cback; - const tBTM_STATUS btm_status = - BTM_StartInquiry(bta_dm_inq_results_cb, bta_dm_inq_cmpl_cb); + const tBTM_STATUS btm_status = BTM_StartInquiry(bta_dm_inq_results_cb, bta_dm_inq_cmpl_cb); switch (btm_status) { case BTM_CMD_STARTED: // Completion callback will be executed when controller inquiry @@ -154,13 +148,12 @@ static void bta_dm_search_cancel() { /* If no Service Search going on then issue cancel remote name in case it is active */ else if (!bta_dm_search_cb.name_discover_done) { - if (get_btm_client_interface().peer.BTM_CancelRemoteDeviceName() != - BTM_CMD_STARTED) { + if (get_btm_client_interface().peer.BTM_CancelRemoteDeviceName() != BTM_CMD_STARTED) { log::warn("Unable to cancel RNR"); } /* bta_dm_search_cmpl is called when receiving the remote name cancel evt */ if (!com::android::bluetooth::flags:: - bta_dm_defer_device_discovery_state_change_until_rnr_complete()) { + bta_dm_defer_device_discovery_state_change_until_rnr_complete()) { bta_dm_search_cmpl(); } } else { @@ -192,8 +185,7 @@ static void bta_dm_inq_cmpl_cb(void* /* p_result */) { * Returns void * ******************************************************************************/ -static void bta_dm_inq_results_cb(tBTM_INQ_RESULTS* p_inq, const uint8_t* p_eir, - uint16_t eir_len) { +static void bta_dm_inq_results_cb(tBTM_INQ_RESULTS* p_inq, const uint8_t* p_eir, uint16_t eir_len) { tBTA_DM_SEARCH result; tBTM_INQ_INFO* p_inq_info; uint16_t service_class; @@ -205,8 +197,7 @@ static void bta_dm_inq_results_cb(tBTM_INQ_RESULTS* p_inq, const uint8_t* p_eir, result.inq_res.dev_class = p_inq->dev_class; BTM_COD_SERVICE_CLASS(service_class, p_inq->dev_class); - result.inq_res.is_limited = - (service_class & BTM_COD_SERVICE_LMTD_DISCOVER) ? true : false; + result.inq_res.is_limited = (service_class & BTM_COD_SERVICE_LMTD_DISCOVER) ? true : false; result.inq_res.rssi = p_inq->rssi; result.inq_res.ble_addr_type = p_inq->ble_addr_type; @@ -222,22 +213,23 @@ static void bta_dm_inq_results_cb(tBTM_INQ_RESULTS* p_inq, const uint8_t* p_eir, result.inq_res.ble_evt_type = p_inq->ble_evt_type; - p_inq_info = - get_btm_client_interface().db.BTM_InqDbRead(p_inq->remote_bd_addr); + p_inq_info = get_btm_client_interface().db.BTM_InqDbRead(p_inq->remote_bd_addr); if (p_inq_info != NULL) { /* initialize remt_name_not_required to false so that we get the name by * default */ result.inq_res.remt_name_not_required = false; } - if (bta_dm_search_cb.p_device_search_cback) + if (bta_dm_search_cb.p_device_search_cback) { bta_dm_search_cb.p_device_search_cback(BTA_DM_INQ_RES_EVT, &result); + } if (p_inq_info) { /* application indicates if it knows the remote name, inside the callback copy that to the inquiry data base*/ - if (result.inq_res.remt_name_not_required) + if (result.inq_res.remt_name_not_required) { p_inq_info->appl_knows_rem_name = true; + } } } @@ -251,30 +243,25 @@ static void bta_dm_inq_results_cb(tBTM_INQ_RESULTS* p_inq, const uint8_t* p_eir, * ******************************************************************************/ static void bta_dm_remname_cback(const tBTM_REMOTE_DEV_NAME* p_remote_name) { - log::assert_that(p_remote_name != nullptr, - "assert failed: p_remote_name != nullptr"); + log::assert_that(p_remote_name != nullptr, "assert failed: p_remote_name != nullptr"); log::info( - "Remote name request complete peer:{} btm_status:{} hci_status:{} " - "name[0]:{:c} length:{}", - p_remote_name->bd_addr, btm_status_text(p_remote_name->status), - hci_error_code_text(p_remote_name->hci_status), - p_remote_name->remote_bd_name[0], - strnlen((const char*)p_remote_name->remote_bd_name, BD_NAME_LEN)); + "Remote name request complete peer:{} btm_status:{} hci_status:{} " + "name[0]:{:c} length:{}", + p_remote_name->bd_addr, btm_status_text(p_remote_name->status), + hci_error_code_text(p_remote_name->hci_status), p_remote_name->remote_bd_name[0], + strnlen((const char*)p_remote_name->remote_bd_name, BD_NAME_LEN)); if (bta_dm_search_cb.peer_bdaddr != p_remote_name->bd_addr) { // if we got a different response, maybe ignore it // we will have made a request directly from BTM_ReadRemoteDeviceName so we // expect a dedicated response for us if (p_remote_name->hci_status == HCI_ERR_CONNECTION_EXISTS) { - log::info( - "Assume command failed due to disconnection hci_status:{} peer:{}", - hci_error_code_text(p_remote_name->hci_status), - p_remote_name->bd_addr); + log::info("Assume command failed due to disconnection hci_status:{} peer:{}", + hci_error_code_text(p_remote_name->hci_status), p_remote_name->bd_addr); } else { - log::info( - "Ignored remote name response for the wrong address exp:{} act:{}", - bta_dm_search_cb.peer_bdaddr, p_remote_name->bd_addr); + log::info("Ignored remote name response for the wrong address exp:{} act:{}", + bta_dm_search_cb.peer_bdaddr, p_remote_name->bd_addr); return; } } @@ -301,8 +288,7 @@ static void bta_dm_remname_cback(const tBTM_REMOTE_DEV_NAME* p_remote_name) { * Returns true if started to get remote name * ******************************************************************************/ -static bool bta_dm_read_remote_device_name(const RawAddress& bd_addr, - tBT_TRANSPORT transport) { +static bool bta_dm_read_remote_device_name(const RawAddress& bd_addr, tBT_TRANSPORT transport) { tBTM_STATUS btm_status; log::verbose(""); @@ -311,20 +297,20 @@ static bool bta_dm_read_remote_device_name(const RawAddress& bd_addr, bta_dm_search_cb.peer_name[0] = 0; btm_status = get_btm_client_interface().peer.BTM_ReadRemoteDeviceName( - bta_dm_search_cb.peer_bdaddr, bta_dm_remname_cback, transport); + bta_dm_search_cb.peer_bdaddr, bta_dm_remname_cback, transport); if (btm_status == BTM_CMD_STARTED) { log::verbose("BTM_ReadRemoteDeviceName is started"); - return (true); + return true; } else if (btm_status == BTM_BUSY) { log::verbose("BTM_ReadRemoteDeviceName is busy"); - return (true); + return true; } else { log::warn("BTM_ReadRemoteDeviceName returns 0x{:02X}", btm_status); - return (false); + return false; } } @@ -350,31 +336,27 @@ static void bta_dm_inq_cmpl() { log::verbose("bta_dm_inq_cmpl"); - bta_dm_search_cb.p_btm_inq_info = - get_btm_client_interface().db.BTM_InqDbFirst(); + bta_dm_search_cb.p_btm_inq_info = get_btm_client_interface().db.BTM_InqDbFirst(); if (bta_dm_search_cb.p_btm_inq_info != NULL) { /* start name discovery from the first device on inquiry result */ bta_dm_search_cb.name_discover_done = false; bta_dm_search_cb.peer_name[0] = 0; - bta_dm_discover_name( - bta_dm_search_cb.p_btm_inq_info->results.remote_bd_addr); + bta_dm_discover_name(bta_dm_search_cb.p_btm_inq_info->results.remote_bd_addr); } else { bta_dm_search_cmpl(); } } -static void bta_dm_remote_name_cmpl( - const tBTA_DM_REMOTE_NAME& remote_name_msg) { +static void bta_dm_remote_name_cmpl(const tBTA_DM_REMOTE_NAME& remote_name_msg) { BTM_LogHistory(kBtmLogTag, remote_name_msg.bd_addr, "Remote name completed", - base::StringPrintf( - "status:%s state:%s name:\"%s\"", - hci_status_code_text(remote_name_msg.hci_status).c_str(), - bta_dm_state_text(bta_dm_search_get_state()).c_str(), - PRIVATE_NAME(remote_name_msg.bd_name))); + base::StringPrintf("status:%s state:%s name:\"%s\"", + hci_status_code_text(remote_name_msg.hci_status).c_str(), + bta_dm_state_text(bta_dm_search_get_state()).c_str(), + PRIVATE_NAME(remote_name_msg.bd_name))); tBTM_INQ_INFO* p_btm_inq_info = - get_btm_client_interface().db.BTM_InqDbRead(remote_name_msg.bd_addr); + get_btm_client_interface().db.BTM_InqDbRead(remote_name_msg.bd_addr); if (!bd_name_is_empty(remote_name_msg.bd_name) && p_btm_inq_info) { p_btm_inq_info->appl_knows_rem_name = true; } @@ -382,7 +364,7 @@ static void bta_dm_remote_name_cmpl( // Callback with this property if (bta_dm_search_cb.p_device_search_cback != nullptr) { tBTA_DM_SEARCH search_data = { - .name_res = {.bd_addr = remote_name_msg.bd_addr, .bd_name = {}}, + .name_res = {.bd_addr = remote_name_msg.bd_addr, .bd_name = {}}, }; if (remote_name_msg.hci_status == HCI_SUCCESS) { bd_name_copy(search_data.name_res.bd_name, remote_name_msg.bd_name); @@ -415,11 +397,12 @@ static void bta_dm_search_cmpl() { } static void bta_dm_execute_queued_search_request() { - if (!bta_dm_search_cb.p_pending_search) return; + if (!bta_dm_search_cb.p_pending_search) { + return; + } log::info("Start pending search"); - post_search_evt(BTA_DM_API_SEARCH_EVT, - std::move(bta_dm_search_cb.p_pending_search)); + post_search_evt(BTA_DM_API_SEARCH_EVT, std::move(bta_dm_search_cb.p_pending_search)); bta_dm_search_cb.p_pending_search.reset(); } @@ -432,9 +415,7 @@ static void bta_dm_execute_queued_search_request() { * Returns void * ******************************************************************************/ -static void bta_dm_search_clear_queue() { - bta_dm_search_cb.p_pending_search.reset(); -} +static void bta_dm_search_clear_queue() { bta_dm_search_cb.p_pending_search.reset(); } /******************************************************************************* * @@ -453,8 +434,7 @@ static void bta_dm_search_cancel_notify() { case BTA_DM_SEARCH_ACTIVE: case BTA_DM_SEARCH_CANCELLING: if (!bta_dm_search_cb.name_discover_done) { - if (get_btm_client_interface().peer.BTM_CancelRemoteDeviceName() != - BTM_CMD_STARTED) { + if (get_btm_client_interface().peer.BTM_CancelRemoteDeviceName() != BTM_CMD_STARTED) { log::warn("Unable to cancel RNR"); } } @@ -478,34 +458,31 @@ static void bta_dm_discover_next_device(void) { log::verbose("bta_dm_discover_next_device"); /* searching next device on inquiry result */ - bta_dm_search_cb.p_btm_inq_info = get_btm_client_interface().db.BTM_InqDbNext( - bta_dm_search_cb.p_btm_inq_info); + bta_dm_search_cb.p_btm_inq_info = + get_btm_client_interface().db.BTM_InqDbNext(bta_dm_search_cb.p_btm_inq_info); if (bta_dm_search_cb.p_btm_inq_info != NULL) { bta_dm_search_cb.name_discover_done = false; bta_dm_search_cb.peer_name[0] = 0; - bta_dm_discover_name( - bta_dm_search_cb.p_btm_inq_info->results.remote_bd_addr); + bta_dm_discover_name(bta_dm_search_cb.p_btm_inq_info->results.remote_bd_addr); } else { post_search_evt(BTA_DM_SEARCH_CMPL_EVT, nullptr); } } /*TODO: this function is duplicated, make it common ?*/ -static tBT_TRANSPORT bta_dm_determine_discovery_transport( - const RawAddress& remote_bd_addr) { +static tBT_TRANSPORT bta_dm_determine_discovery_transport(const RawAddress& remote_bd_addr) { tBT_DEVICE_TYPE dev_type; tBLE_ADDR_TYPE addr_type; - get_btm_client_interface().peer.BTM_ReadDevInfo(remote_bd_addr, &dev_type, - &addr_type); + get_btm_client_interface().peer.BTM_ReadDevInfo(remote_bd_addr, &dev_type, &addr_type); if (dev_type == BT_DEVICE_TYPE_BLE || addr_type == BLE_ADDR_RANDOM) { return BT_TRANSPORT_LE; } else if (dev_type == BT_DEVICE_TYPE_DUMO) { - if (get_btm_client_interface().peer.BTM_IsAclConnectionUp( - remote_bd_addr, BT_TRANSPORT_BR_EDR)) { + if (get_btm_client_interface().peer.BTM_IsAclConnectionUp(remote_bd_addr, + BT_TRANSPORT_BR_EDR)) { return BT_TRANSPORT_BR_EDR; - } else if (get_btm_client_interface().peer.BTM_IsAclConnectionUp( - remote_bd_addr, BT_TRANSPORT_LE)) { + } else if (get_btm_client_interface().peer.BTM_IsAclConnectionUp(remote_bd_addr, + BT_TRANSPORT_LE)) { return BT_TRANSPORT_LE; } } @@ -513,39 +490,31 @@ static tBT_TRANSPORT bta_dm_determine_discovery_transport( } static void bta_dm_discover_name(const RawAddress& remote_bd_addr) { - const tBT_TRANSPORT transport = - bta_dm_determine_discovery_transport(remote_bd_addr); + const tBT_TRANSPORT transport = bta_dm_determine_discovery_transport(remote_bd_addr); log::verbose("BDA: {}", remote_bd_addr); bta_dm_search_cb.peer_bdaddr = remote_bd_addr; - log::verbose( - "name_discover_done = {} p_btm_inq_info 0x{} state = {}, transport={}", - bta_dm_search_cb.name_discover_done, - fmt::ptr(bta_dm_search_cb.p_btm_inq_info), bta_dm_search_get_state(), - transport); + log::verbose("name_discover_done = {} p_btm_inq_info 0x{} state = {}, transport={}", + bta_dm_search_cb.name_discover_done, fmt::ptr(bta_dm_search_cb.p_btm_inq_info), + bta_dm_search_get_state(), transport); if (bta_dm_search_cb.p_btm_inq_info) { - log::verbose("appl_knows_rem_name {}", - bta_dm_search_cb.p_btm_inq_info->appl_knows_rem_name); + log::verbose("appl_knows_rem_name {}", bta_dm_search_cb.p_btm_inq_info->appl_knows_rem_name); } if (((bta_dm_search_cb.p_btm_inq_info) && - (bta_dm_search_cb.p_btm_inq_info->results.device_type == - BT_DEVICE_TYPE_BLE) && + (bta_dm_search_cb.p_btm_inq_info->results.device_type == BT_DEVICE_TYPE_BLE) && (bta_dm_search_get_state() == BTA_DM_SEARCH_ACTIVE)) || (transport == BT_TRANSPORT_LE && - interop_match_addr(INTEROP_DISABLE_NAME_REQUEST, - &bta_dm_search_cb.peer_bdaddr))) { + interop_match_addr(INTEROP_DISABLE_NAME_REQUEST, &bta_dm_search_cb.peer_bdaddr))) { /* Do not perform RNR for LE devices at inquiry complete*/ bta_dm_search_cb.name_discover_done = true; } // If we already have the name we can skip getting the name if (BTM_IsRemoteNameKnown(remote_bd_addr, transport) && bluetooth::common::init_flags::sdp_skip_rnr_if_known_is_enabled()) { - log::debug( - "Security record already known skipping read remote name peer:{}", - remote_bd_addr); + log::debug("Security record already known skipping read remote name peer:{}", remote_bd_addr); bta_dm_search_cb.name_discover_done = true; } @@ -554,12 +523,9 @@ static void bta_dm_discover_name(const RawAddress& remote_bd_addr) { ((bta_dm_search_cb.p_btm_inq_info == NULL) || (bta_dm_search_cb.p_btm_inq_info && (!bta_dm_search_cb.p_btm_inq_info->appl_knows_rem_name)))) { - if (bta_dm_read_remote_device_name(bta_dm_search_cb.peer_bdaddr, - transport)) { - BTM_LogHistory(kBtmLogTag, bta_dm_search_cb.peer_bdaddr, - "Read remote name", - base::StringPrintf("Transport:%s", - bt_transport_text(transport).c_str())); + if (bta_dm_read_remote_device_name(bta_dm_search_cb.peer_bdaddr, transport)) { + BTM_LogHistory(kBtmLogTag, bta_dm_search_cb.peer_bdaddr, "Read remote name", + base::StringPrintf("Transport:%s", bt_transport_text(transport).c_str())); return; } else { log::error("Unable to start read remote device name"); @@ -594,8 +560,7 @@ static void bta_dm_discover_name(const RawAddress& remote_bd_addr) { * ******************************************************************************/ bool bta_dm_is_search_request_queued() { - if (!com::android::bluetooth::flags:: - separate_service_and_device_discovery()) { + if (!com::android::bluetooth::flags::separate_service_and_device_discovery()) { return bta_dm_disc_legacy::bta_dm_is_search_request_queued(); } return bta_dm_search_cb.p_pending_search != NULL; @@ -628,8 +593,8 @@ static void bta_dm_queue_search(tBTA_DM_API_SEARCH& search) { * Returns void * ******************************************************************************/ -static void bta_dm_observe_results_cb(tBTM_INQ_RESULTS* p_inq, - const uint8_t* p_eir, uint16_t eir_len) { +static void bta_dm_observe_results_cb(tBTM_INQ_RESULTS* p_inq, const uint8_t* p_eir, + uint16_t eir_len) { tBTA_DM_SEARCH result; tBTM_INQ_INFO* p_inq_info; log::verbose("bta_dm_observe_results_cb"); @@ -652,8 +617,7 @@ static void bta_dm_observe_results_cb(tBTM_INQ_RESULTS* p_inq, result.inq_res.p_eir = const_cast(p_eir); result.inq_res.eir_len = eir_len; - p_inq_info = - get_btm_client_interface().db.BTM_InqDbRead(p_inq->remote_bd_addr); + p_inq_info = get_btm_client_interface().db.BTM_InqDbRead(p_inq->remote_bd_addr); if (p_inq_info != NULL) { /* initialize remt_name_not_required to false so that we get the name by * default */ @@ -663,8 +627,9 @@ static void bta_dm_observe_results_cb(tBTM_INQ_RESULTS* p_inq, if (p_inq_info) { /* application indicates if it knows the remote name, inside the callback copy that to the inquiry data base*/ - if (result.inq_res.remt_name_not_required) + if (result.inq_res.remt_name_not_required) { p_inq_info->appl_knows_rem_name = true; + } } } @@ -678,8 +643,7 @@ static void bta_dm_observe_results_cb(tBTM_INQ_RESULTS* p_inq, * Returns void * ******************************************************************************/ -static void bta_dm_opportunistic_observe_results_cb(tBTM_INQ_RESULTS* p_inq, - const uint8_t* p_eir, +static void bta_dm_opportunistic_observe_results_cb(tBTM_INQ_RESULTS* p_inq, const uint8_t* p_eir, uint16_t eir_len) { tBTA_DM_SEARCH result; tBTM_INQ_INFO* p_inq_info; @@ -701,22 +665,23 @@ static void bta_dm_opportunistic_observe_results_cb(tBTM_INQ_RESULTS* p_inq, result.inq_res.p_eir = const_cast(p_eir); result.inq_res.eir_len = eir_len; - p_inq_info = - get_btm_client_interface().db.BTM_InqDbRead(p_inq->remote_bd_addr); + p_inq_info = get_btm_client_interface().db.BTM_InqDbRead(p_inq->remote_bd_addr); if (p_inq_info != NULL) { /* initialize remt_name_not_required to false so that we get the name by * default */ result.inq_res.remt_name_not_required = false; } - if (bta_dm_search_cb.p_csis_scan_cback) + if (bta_dm_search_cb.p_csis_scan_cback) { bta_dm_search_cb.p_csis_scan_cback(BTA_DM_INQ_RES_EVT, &result); + } if (p_inq_info) { /* application indicates if it knows the remote name, inside the callback copy that to the inquiry data base*/ - if (result.inq_res.remt_name_not_required) + if (result.inq_res.remt_name_not_required) { p_inq_info->appl_knows_rem_name = true; + } } } @@ -740,11 +705,9 @@ static void bta_dm_observe_cmpl_cb(void* p_result) { } } -static void bta_dm_start_scan(uint8_t duration_sec, - bool low_latency_scan = false) { +static void bta_dm_start_scan(uint8_t duration_sec, bool low_latency_scan = false) { tBTM_STATUS status = get_btm_client_interface().ble.BTM_BleObserve( - true, duration_sec, bta_dm_observe_results_cb, bta_dm_observe_cmpl_cb, - low_latency_scan); + true, duration_sec, bta_dm_observe_results_cb, bta_dm_observe_cmpl_cb, low_latency_scan); if (status != BTM_CMD_STARTED) { log::warn("BTM_BleObserve failed. status {}", status); @@ -755,11 +718,10 @@ static void bta_dm_start_scan(uint8_t duration_sec, } } -void bta_dm_ble_scan(bool start, uint8_t duration_sec, - bool low_latency_scan = false) { +void bta_dm_ble_scan(bool start, uint8_t duration_sec, bool low_latency_scan = false) { if (!start) { - if (get_btm_client_interface().ble.BTM_BleObserve( - false, 0, NULL, NULL, false) != BTM_CMD_STARTED) { + if (get_btm_client_interface().ble.BTM_BleObserve(false, 0, NULL, NULL, false) != + BTM_CMD_STARTED) { log::warn("Unable to start ble observe"); } return; @@ -784,9 +746,7 @@ namespace bluetooth { namespace legacy { namespace testing { -void bta_dm_remname_cback(const tBTM_REMOTE_DEV_NAME* p) { - ::bta_dm_remname_cback(p); -} +void bta_dm_remname_cback(const tBTM_REMOTE_DEV_NAME* p) { ::bta_dm_remname_cback(p); } void bta_dm_remote_name_cmpl(const tBTA_DM_REMOTE_NAME& remote_name_msg) { ::bta_dm_remote_name_cmpl(remote_name_msg); @@ -806,9 +766,8 @@ std::string EpochMillisToString(long long time_ms) { struct tm tm; localtime_r(&time_sec, &tm); std::string s = bluetooth::common::StringFormatTime(kTimeFormatString, tm); - return base::StringPrintf( - "%s.%03u", s.c_str(), - static_cast(time_ms % MillisPerSecond)); + return base::StringPrintf("%s.%03u", s.c_str(), + static_cast(time_ms % MillisPerSecond)); } } // namespace @@ -817,14 +776,13 @@ struct tSEARCH_STATE_HISTORY { const tBTA_DM_DEVICE_SEARCH_STATE state; const tBTA_DM_DEV_SEARCH_EVT event; std::string ToString() const { - return base::StringPrintf("state:%25s event:%s", - bta_dm_state_text(state).c_str(), + return base::StringPrintf("state:%25s event:%s", bta_dm_state_text(state).c_str(), bta_dm_event_text(event).c_str()); } }; -bluetooth::common::TimestampedCircularBuffer - search_state_history_(kSearchStateHistorySize); +bluetooth::common::TimestampedCircularBuffer search_state_history_( + kSearchStateHistorySize); /******************************************************************************* * @@ -838,12 +796,11 @@ bluetooth::common::TimestampedCircularBuffer ******************************************************************************/ static void bta_dm_search_sm_execute(tBTA_DM_DEV_SEARCH_EVT event, std::unique_ptr msg) { - log::info("state:{}, event:{}[0x{:x}]", - bta_dm_state_text(bta_dm_search_get_state()), + log::info("state:{}, event:{}[0x{:x}]", bta_dm_state_text(bta_dm_search_get_state()), bta_dm_event_text(event), event); search_state_history_.Push({ - .state = bta_dm_search_get_state(), - .event = event, + .state = bta_dm_search_get_state(), + .event = event, }); switch (bta_dm_search_get_state()) { @@ -851,8 +808,8 @@ static void bta_dm_search_sm_execute(tBTA_DM_DEV_SEARCH_EVT event, switch (event) { case BTA_DM_API_SEARCH_EVT: bta_dm_search_set_state(BTA_DM_SEARCH_ACTIVE); - log::assert_that(std::holds_alternative(*msg), - "bad message type: {}", msg->index()); + log::assert_that(std::holds_alternative(*msg), "bad message type: {}", + msg->index()); bta_dm_search_start(std::get(*msg)); break; @@ -861,9 +818,8 @@ static void bta_dm_search_sm_execute(tBTA_DM_DEV_SEARCH_EVT event, bta_dm_search_cancel_notify(); break; default: - log::info("Received unexpected event {}[0x{:x}] in state {}", - bta_dm_event_text(event), event, - bta_dm_state_text(bta_dm_search_get_state())); + log::info("Received unexpected event {}[0x{:x}] in state {}", bta_dm_event_text(event), + event, bta_dm_state_text(bta_dm_search_get_state())); } break; case BTA_DM_SEARCH_ACTIVE: @@ -883,16 +839,15 @@ static void bta_dm_search_sm_execute(tBTA_DM_DEV_SEARCH_EVT event, bta_dm_search_cancel(); break; default: - log::info("Received unexpected event {}[0x{:x}] in state {}", - bta_dm_event_text(event), event, - bta_dm_state_text(bta_dm_search_get_state())); + log::info("Received unexpected event {}[0x{:x}] in state {}", bta_dm_event_text(event), + event, bta_dm_state_text(bta_dm_search_get_state())); } break; case BTA_DM_SEARCH_CANCELLING: switch (event) { case BTA_DM_API_SEARCH_EVT: - log::assert_that(std::holds_alternative(*msg), - "bad message type: {}", msg->index()); + log::assert_that(std::holds_alternative(*msg), "bad message type: {}", + msg->index()); bta_dm_queue_search(std::get(*msg)); break; @@ -907,9 +862,8 @@ static void bta_dm_search_sm_execute(tBTA_DM_DEV_SEARCH_EVT event, bta_dm_execute_queued_search_request(); break; default: - log::info("Received unexpected event {}[0x{:x}] in state {}", - bta_dm_event_text(event), event, - bta_dm_state_text(bta_dm_search_get_state())); + log::info("Received unexpected event {}[0x{:x}] in state {}", bta_dm_event_text(event), + event, bta_dm_state_text(bta_dm_search_get_state())); } break; } @@ -923,27 +877,24 @@ static void bta_dm_disable_search(void) { case BTA_DM_SEARCH_CANCELLING: default: log::debug( - "Search state machine is not idle so issuing search cancel current " - "state:{}", - bta_dm_state_text(bta_dm_search_get_state())); + "Search state machine is not idle so issuing search cancel current " + "state:{}", + bta_dm_state_text(bta_dm_search_get_state())); bta_dm_search_cancel(); } } void bta_dm_disc_start_device_discovery(tBTA_DM_SEARCH_CBACK* p_cback) { - if (!com::android::bluetooth::flags:: - separate_service_and_device_discovery()) { + if (!com::android::bluetooth::flags::separate_service_and_device_discovery()) { bta_dm_disc_legacy::bta_dm_disc_start_device_discovery(p_cback); return; } - bta_dm_search_sm_execute(BTA_DM_API_SEARCH_EVT, - std::make_unique( - tBTA_DM_API_SEARCH{.p_cback = p_cback})); + bta_dm_search_sm_execute(BTA_DM_API_SEARCH_EVT, std::make_unique( + tBTA_DM_API_SEARCH{.p_cback = p_cback})); } void bta_dm_disc_stop_device_discovery() { - if (!com::android::bluetooth::flags:: - separate_service_and_device_discovery()) { + if (!com::android::bluetooth::flags::separate_service_and_device_discovery()) { bta_dm_disc_legacy::bta_dm_disc_stop_device_discovery(); return; } @@ -961,8 +912,7 @@ static void bta_dm_search_reset() { } void bta_dm_search_stop() { - if (!com::android::bluetooth::flags:: - separate_service_and_device_discovery()) { + if (!com::android::bluetooth::flags::separate_service_and_device_discovery()) { log::info("no-op when flag is disabled"); return; } @@ -970,8 +920,7 @@ void bta_dm_search_stop() { } void bta_dm_disc_discover_next_device() { - if (!com::android::bluetooth::flags:: - separate_service_and_device_discovery()) { + if (!com::android::bluetooth::flags::separate_service_and_device_discovery()) { bta_dm_disc_legacy::bta_dm_disc_discover_next_device(); return; } @@ -980,8 +929,7 @@ void bta_dm_disc_discover_next_device() { #define DUMPSYS_TAG "shim::legacy::bta::dm" void DumpsysBtaDmSearch(int fd) { - if (!com::android::bluetooth::flags:: - separate_service_and_device_discovery()) { + if (!com::android::bluetooth::flags::separate_service_and_device_discovery()) { log::info("no-op when flag is disabled"); return; } @@ -1011,28 +959,21 @@ tBTA_DM_SEARCH_CB bta_dm_disc_get_search_cb() { return search_cb; } tBTA_DM_SEARCH_CB& bta_dm_disc_search_cb() { return ::bta_dm_search_cb; } -bool bta_dm_read_remote_device_name(const RawAddress& bd_addr, - tBT_TRANSPORT transport) { +bool bta_dm_read_remote_device_name(const RawAddress& bd_addr, tBT_TRANSPORT transport) { return ::bta_dm_read_remote_device_name(bd_addr, transport); } void bta_dm_inq_cmpl() { ::bta_dm_inq_cmpl(); } void bta_dm_inq_cmpl_cb(void* p_result) { ::bta_dm_inq_cmpl_cb(p_result); } -void bta_dm_observe_cmpl_cb(void* p_result) { - ::bta_dm_observe_cmpl_cb(p_result); -} -void bta_dm_observe_results_cb(tBTM_INQ_RESULTS* p_inq, const uint8_t* p_eir, - uint16_t eir_len) { +void bta_dm_observe_cmpl_cb(void* p_result) { ::bta_dm_observe_cmpl_cb(p_result); } +void bta_dm_observe_results_cb(tBTM_INQ_RESULTS* p_inq, const uint8_t* p_eir, uint16_t eir_len) { ::bta_dm_observe_results_cb(p_inq, p_eir, eir_len); } -void bta_dm_opportunistic_observe_results_cb(tBTM_INQ_RESULTS* p_inq, - const uint8_t* p_eir, +void bta_dm_opportunistic_observe_results_cb(tBTM_INQ_RESULTS* p_inq, const uint8_t* p_eir, uint16_t eir_len) { ::bta_dm_opportunistic_observe_results_cb(p_inq, p_eir, eir_len); } -void bta_dm_queue_search(tBTA_DM_API_SEARCH& search) { - ::bta_dm_queue_search(search); -} +void bta_dm_queue_search(tBTA_DM_API_SEARCH& search) { ::bta_dm_queue_search(search); } void bta_dm_start_scan(uint8_t duration_sec, bool low_latency_scan = false) { ::bta_dm_start_scan(duration_sec, low_latency_scan); diff --git a/system/bta/dm/bta_dm_device_search_int.h b/system/bta/dm/bta_dm_device_search_int.h index 73bb03e8102..68df101863f 100644 --- a/system/bta/dm/bta_dm_device_search_int.h +++ b/system/bta/dm/bta_dm_device_search_int.h @@ -57,8 +57,7 @@ typedef struct { tHCI_STATUS hci_status; } tBTA_DM_REMOTE_NAME; -using tBTA_DM_SEARCH_MSG = - std::variant; +using tBTA_DM_SEARCH_MSG = std::variant; /* DM search state */ typedef enum { @@ -93,9 +92,7 @@ typedef struct { namespace fmt { template <> -struct formatter - : enum_formatter {}; +struct formatter : enum_formatter {}; template <> -struct formatter - : enum_formatter {}; +struct formatter : enum_formatter {}; } // namespace fmt diff --git a/system/bta/dm/bta_dm_disc.cc b/system/bta/dm/bta_dm_disc.cc index 37840398b9a..16166e52651 100644 --- a/system/bta/dm/bta_dm_disc.cc +++ b/system/bta/dm/bta_dm_disc.cc @@ -45,7 +45,7 @@ #include "stack/include/bt_uuid16.h" #include "stack/include/btm_client_interface.h" #include "stack/include/btm_log_history.h" -#include "stack/include/gap_api.h" // GAP_BleReadPeerPrefConnParams +#include "stack/include/gap_api.h" // GAP_BleReadPeerPrefConnParams #include "stack/include/hidh_api.h" #include "stack/include/main_thread.h" #include "stack/include/sdp_status.h" @@ -66,16 +66,16 @@ constexpr char kBtmLogTag[] = "SDP"; tBTA_DM_SERVICE_DISCOVERY_CB bta_dm_discovery_cb; base::RepeatingCallback default_sdp_performer = - base::Bind(bta_dm_sdp_find_services); + base::Bind(bta_dm_sdp_find_services); base::RepeatingCallback default_gatt_performer = - base::Bind(btm_dm_start_gatt_discovery); -base::RepeatingCallback sdp_performer = - default_sdp_performer; -base::RepeatingCallback gatt_performer = - default_gatt_performer; + base::Bind(btm_dm_start_gatt_discovery); +base::RepeatingCallback sdp_performer = default_sdp_performer; +base::RepeatingCallback gatt_performer = default_gatt_performer; static bool is_same_device(const RawAddress& a, const RawAddress& b) { - if (a == b) return true; + if (a == b) { + return true; + } auto devA = btm_find_dev(a); if (devA != nullptr && devA == btm_find_dev(b)) { @@ -86,13 +86,10 @@ static bool is_same_device(const RawAddress& a, const RawAddress& b) { } } // namespace -static void bta_dm_disc_sm_execute(tBTA_DM_DISC_EVT event, - std::unique_ptr msg); -static void post_disc_evt(tBTA_DM_DISC_EVT event, - std::unique_ptr msg) { - if (do_in_main_thread(FROM_HERE, base::BindOnce(&bta_dm_disc_sm_execute, - event, std::move(msg))) != - BT_STATUS_SUCCESS) { +static void bta_dm_disc_sm_execute(tBTA_DM_DISC_EVT event, std::unique_ptr msg); +static void post_disc_evt(tBTA_DM_DISC_EVT event, std::unique_ptr msg) { + if (do_in_main_thread(FROM_HERE, base::BindOnce(&bta_dm_disc_sm_execute, event, + std::move(msg))) != BT_STATUS_SUCCESS) { log::error("post_disc_evt failed"); } } @@ -107,51 +104,45 @@ static void bta_dm_close_gatt_conn(); namespace { struct gatt_interface_t { - void (*BTA_GATTC_CancelOpen)(tGATT_IF client_if, const RawAddress& remote_bda, - bool is_direct); + void (*BTA_GATTC_CancelOpen)(tGATT_IF client_if, const RawAddress& remote_bda, bool is_direct); void (*BTA_GATTC_Refresh)(const RawAddress& remote_bda); - void (*BTA_GATTC_GetGattDb)(uint16_t conn_id, uint16_t start_handle, - uint16_t end_handle, btgatt_db_element_t** db, - int* count); - void (*BTA_GATTC_AppRegister)(tBTA_GATTC_CBACK* p_client_cb, - BtaAppRegisterCallback cb, bool eatt_support); + void (*BTA_GATTC_GetGattDb)(uint16_t conn_id, uint16_t start_handle, uint16_t end_handle, + btgatt_db_element_t** db, int* count); + void (*BTA_GATTC_AppRegister)(tBTA_GATTC_CBACK* p_client_cb, BtaAppRegisterCallback cb, + bool eatt_support); void (*BTA_GATTC_Close)(uint16_t conn_id); - void (*BTA_GATTC_ServiceSearchRequest)(uint16_t conn_id, - const bluetooth::Uuid* p_srvc_uuid); + void (*BTA_GATTC_ServiceSearchRequest)(uint16_t conn_id, const bluetooth::Uuid* p_srvc_uuid); void (*BTA_GATTC_Open)(tGATT_IF client_if, const RawAddress& remote_bda, - tBTM_BLE_CONN_TYPE connection_type, - bool opportunistic); + tBTM_BLE_CONN_TYPE connection_type, bool opportunistic); } default_gatt_interface = { - .BTA_GATTC_CancelOpen = - [](tGATT_IF client_if, const RawAddress& remote_bda, bool is_direct) { - BTA_GATTC_CancelOpen(client_if, remote_bda, is_direct); - }, - .BTA_GATTC_Refresh = - [](const RawAddress& remote_bda) { BTA_GATTC_Refresh(remote_bda); }, - .BTA_GATTC_GetGattDb = - [](uint16_t conn_id, uint16_t start_handle, uint16_t end_handle, - btgatt_db_element_t** db, int* count) { - BTA_GATTC_GetGattDb(conn_id, start_handle, end_handle, db, count); - }, - .BTA_GATTC_AppRegister = - [](tBTA_GATTC_CBACK* p_client_cb, BtaAppRegisterCallback cb, - bool eatt_support) { - BTA_GATTC_AppRegister(p_client_cb, cb, eatt_support); - }, - .BTA_GATTC_Close = [](uint16_t conn_id) { BTA_GATTC_Close(conn_id); }, - .BTA_GATTC_ServiceSearchRequest = - [](uint16_t conn_id, const bluetooth::Uuid* p_srvc_uuid) { - if (p_srvc_uuid) { - BTA_GATTC_ServiceSearchRequest(conn_id, *p_srvc_uuid); - } else { - BTA_GATTC_ServiceSearchAllRequest(conn_id); - } - }, - .BTA_GATTC_Open = - [](tGATT_IF client_if, const RawAddress& remote_bda, - tBTM_BLE_CONN_TYPE connection_type, bool opportunistic) { - BTA_GATTC_Open(client_if, remote_bda, connection_type, opportunistic); - }, + .BTA_GATTC_CancelOpen = + [](tGATT_IF client_if, const RawAddress& remote_bda, bool is_direct) { + BTA_GATTC_CancelOpen(client_if, remote_bda, is_direct); + }, + .BTA_GATTC_Refresh = [](const RawAddress& remote_bda) { BTA_GATTC_Refresh(remote_bda); }, + .BTA_GATTC_GetGattDb = + [](uint16_t conn_id, uint16_t start_handle, uint16_t end_handle, + btgatt_db_element_t** db, int* count) { + BTA_GATTC_GetGattDb(conn_id, start_handle, end_handle, db, count); + }, + .BTA_GATTC_AppRegister = + [](tBTA_GATTC_CBACK* p_client_cb, BtaAppRegisterCallback cb, bool eatt_support) { + BTA_GATTC_AppRegister(p_client_cb, cb, eatt_support); + }, + .BTA_GATTC_Close = [](uint16_t conn_id) { BTA_GATTC_Close(conn_id); }, + .BTA_GATTC_ServiceSearchRequest = + [](uint16_t conn_id, const bluetooth::Uuid* p_srvc_uuid) { + if (p_srvc_uuid) { + BTA_GATTC_ServiceSearchRequest(conn_id, *p_srvc_uuid); + } else { + BTA_GATTC_ServiceSearchAllRequest(conn_id); + } + }, + .BTA_GATTC_Open = + [](tGATT_IF client_if, const RawAddress& remote_bda, + tBTM_BLE_CONN_TYPE connection_type, bool opportunistic) { + BTA_GATTC_Open(client_if, remote_bda, connection_type, opportunistic); + }, }; gatt_interface_t* gatt_interface = &default_gatt_interface; @@ -169,8 +160,7 @@ void bta_dm_disc_disable_search_and_disc() { } void bta_dm_disc_disable_disc() { - if (!com::android::bluetooth::flags:: - separate_service_and_device_discovery()) { + if (!com::android::bluetooth::flags::separate_service_and_device_discovery()) { log::info("no-op when flag is disabled"); return; } @@ -178,8 +168,7 @@ void bta_dm_disc_disable_disc() { } void bta_dm_disc_gatt_cancel_open(const RawAddress& bd_addr) { - if (!com::android::bluetooth::flags:: - separate_service_and_device_discovery()) { + if (!com::android::bluetooth::flags::separate_service_and_device_discovery()) { bta_dm_disc_legacy::bta_dm_disc_gatt_cancel_open(bd_addr); return; } @@ -187,8 +176,7 @@ void bta_dm_disc_gatt_cancel_open(const RawAddress& bd_addr) { } void bta_dm_disc_gatt_refresh(const RawAddress& bd_addr) { - if (!com::android::bluetooth::flags:: - separate_service_and_device_discovery()) { + if (!com::android::bluetooth::flags::separate_service_and_device_discovery()) { bta_dm_disc_legacy::bta_dm_disc_gatt_refresh(bd_addr); return; } @@ -196,24 +184,19 @@ void bta_dm_disc_gatt_refresh(const RawAddress& bd_addr) { } void bta_dm_disc_remove_device(const RawAddress& bd_addr) { - if (!com::android::bluetooth::flags:: - separate_service_and_device_discovery()) { + if (!com::android::bluetooth::flags::separate_service_and_device_discovery()) { bta_dm_disc_legacy::bta_dm_disc_remove_device(bd_addr); return; } if (bta_dm_discovery_cb.service_discovery_state == BTA_DM_DISCOVER_ACTIVE && bta_dm_discovery_cb.peer_bdaddr == bd_addr) { - log::info( - "Device removed while service discovery was pending, conclude the " - "service disvovery"); - bta_dm_gatt_disc_complete((uint16_t)GATT_INVALID_CONN_ID, - (tGATT_STATUS)GATT_ERROR); + log::info("Device removed while service discovery was pending, conclude the service disvovery"); + bta_dm_gatt_disc_complete((uint16_t)GATT_INVALID_CONN_ID, (tGATT_STATUS)GATT_ERROR); } } void bta_dm_disc_gattc_register() { - if (!com::android::bluetooth::flags:: - separate_service_and_device_discovery()) { + if (!com::android::bluetooth::flags::separate_service_and_device_discovery()) { bta_dm_disc_legacy::bta_dm_disc_gattc_register(); return; } @@ -246,58 +229,49 @@ static void bta_dm_disable_disc(void) { break; case BTA_DM_DISCOVER_ACTIVE: default: - log::debug( - "Discovery state machine is not idle so issuing discovery cancel " - "current " - "state:{}", - bta_dm_state_text(bta_dm_discovery_get_state())); + log::debug("Discovery state machine is not idle so issuing discovery cancel current state:{}", + bta_dm_state_text(bta_dm_discovery_get_state())); bta_dm_discovery_cancel(); } } -void bta_dm_sdp_finished(RawAddress bda, tBTA_STATUS result, - std::vector uuids, +void bta_dm_sdp_finished(RawAddress bda, tBTA_STATUS result, std::vector uuids, std::vector gatt_uuids) { - bta_dm_disc_sm_execute(BTA_DM_DISCOVERY_RESULT_EVT, - std::make_unique(tBTA_DM_SVC_RES{ - .bd_addr = bda, - .uuids = uuids, - .gatt_uuids = gatt_uuids, - .result = result, - })); + bta_dm_disc_sm_execute(BTA_DM_DISCOVERY_RESULT_EVT, std::make_unique(tBTA_DM_SVC_RES{ + .bd_addr = bda, + .uuids = uuids, + .gatt_uuids = gatt_uuids, + .result = result, + })); } /* Callback from sdp with discovery status */ -void bta_dm_sdp_callback(const RawAddress& /* bd_addr */, - tSDP_STATUS sdp_status) { +void bta_dm_sdp_callback(const RawAddress& /* bd_addr */, tSDP_STATUS sdp_status) { log::info("{}", bta_dm_state_text(bta_dm_discovery_get_state())); if (bta_dm_discovery_get_state() == BTA_DM_DISCOVER_IDLE) { return; } - do_in_main_thread(FROM_HERE, - base::BindOnce(&bta_dm_sdp_result, sdp_status, - bta_dm_discovery_cb.sdp_state.get())); + do_in_main_thread(FROM_HERE, base::BindOnce(&bta_dm_sdp_result, sdp_status, + bta_dm_discovery_cb.sdp_state.get())); } /** Callback of peer's DIS reply. This is only called for floss */ #if TARGET_FLOSS -void bta_dm_sdp_received_di(const RawAddress& bd_addr, - tSDP_DI_GET_RECORD& di_record) { +void bta_dm_sdp_received_di(const RawAddress& bd_addr, tSDP_DI_GET_RECORD& di_record) { bta_dm_discovery_cb.service_search_cbacks.on_did_received( - bd_addr, di_record.rec.vendor_id_source, di_record.rec.vendor, - di_record.rec.product, di_record.rec.version); + bd_addr, di_record.rec.vendor_id_source, di_record.rec.vendor, di_record.rec.product, + di_record.rec.version); } -static void bta_dm_read_dis_cmpl(const RawAddress& addr, - tDIS_VALUE* p_dis_value) { +static void bta_dm_read_dis_cmpl(const RawAddress& addr, tDIS_VALUE* p_dis_value) { if (!p_dis_value) { log::warn("read DIS failed"); } else { bta_dm_discovery_cb.service_search_cbacks.on_did_received( - addr, p_dis_value->pnp_id.vendor_id_src, p_dis_value->pnp_id.vendor_id, - p_dis_value->pnp_id.product_id, p_dis_value->pnp_id.product_version); + addr, p_dis_value->pnp_id.vendor_id_src, p_dis_value->pnp_id.vendor_id, + p_dis_value->pnp_id.product_id, p_dis_value->pnp_id.product_version); } if (!bta_dm_discovery_cb.transports) { @@ -327,18 +301,18 @@ static void bta_dm_disc_result(tBTA_DM_SVC_RES& disc_result) { if (!r.gatt_uuids.empty()) { log::info("Sending GATT services discovered using SDP"); // send GATT result back to app, if any - bta_dm_discovery_cb.service_search_cbacks.on_gatt_results( - r.bd_addr, BD_NAME{}, r.gatt_uuids, /* transport_le */ false); + bta_dm_discovery_cb.service_search_cbacks.on_gatt_results(r.bd_addr, BD_NAME{}, r.gatt_uuids, + /* transport_le */ false); } - bta_dm_discovery_cb.service_search_cbacks.on_service_discovery_results( - r.bd_addr, r.uuids, r.result); + bta_dm_discovery_cb.service_search_cbacks.on_service_discovery_results(r.bd_addr, r.uuids, + r.result); } else { bta_dm_discovery_cb.transports &= ~BT_TRANSPORT_LE; GAP_BleReadPeerPrefConnParams(bta_dm_discovery_cb.peer_bdaddr); - bta_dm_discovery_cb.service_search_cbacks.on_gatt_results( - bta_dm_discovery_cb.peer_bdaddr, BD_NAME{}, disc_result.gatt_uuids, - /* transport_le */ true); + bta_dm_discovery_cb.service_search_cbacks.on_gatt_results(bta_dm_discovery_cb.peer_bdaddr, + BD_NAME{}, disc_result.gatt_uuids, + /* transport_le */ true); } if (!bta_dm_discovery_cb.transports) { @@ -347,8 +321,7 @@ static void bta_dm_disc_result(tBTA_DM_SVC_RES& disc_result) { #if TARGET_FLOSS if (bta_dm_discovery_cb.conn_id != GATT_INVALID_CONN_ID && - DIS_ReadDISInfo(bta_dm_discovery_cb.peer_bdaddr, bta_dm_read_dis_cmpl, - DIS_ATTR_PNP_ID_BIT)) { + DIS_ReadDISInfo(bta_dm_discovery_cb.peer_bdaddr, bta_dm_read_dis_cmpl, DIS_ATTR_PNP_ID_BIT)) { return; } #endif @@ -368,8 +341,8 @@ static void bta_dm_disc_result(tBTA_DM_SVC_RES& disc_result) { * ******************************************************************************/ static void bta_dm_queue_disc(tBTA_DM_API_DISCOVER& discovery) { - log::info("bta_dm_discovery: queuing service discovery to {} [{}]", - discovery.bd_addr, bt_transport_text(discovery.transport)); + log::info("bta_dm_discovery: queuing service discovery to {} [{}]", discovery.bd_addr, + bt_transport_text(discovery.transport)); bta_dm_discovery_cb.pending_discovery_queue.push(discovery); } @@ -380,14 +353,12 @@ static void bta_dm_execute_queued_discovery_request() { return; } - tBTA_DM_API_DISCOVER pending_discovery = - bta_dm_discovery_cb.pending_discovery_queue.front(); + tBTA_DM_API_DISCOVER pending_discovery = bta_dm_discovery_cb.pending_discovery_queue.front(); bta_dm_discovery_cb.pending_discovery_queue.pop(); log::info("Start pending discovery {} [{}]", pending_discovery.bd_addr, pending_discovery.transport); - post_disc_evt( - BTA_DM_API_DISCOVER_EVT, - std::make_unique(tBTA_DM_API_DISCOVER{pending_discovery})); + post_disc_evt(BTA_DM_API_DISCOVER_EVT, + std::make_unique(tBTA_DM_API_DISCOVER{pending_discovery})); } /******************************************************************************* @@ -399,21 +370,19 @@ static void bta_dm_execute_queued_discovery_request() { * Returns void * ******************************************************************************/ -static tBT_TRANSPORT bta_dm_determine_discovery_transport( - const RawAddress& remote_bd_addr) { +static tBT_TRANSPORT bta_dm_determine_discovery_transport(const RawAddress& remote_bd_addr) { tBT_DEVICE_TYPE dev_type; tBLE_ADDR_TYPE addr_type; - get_btm_client_interface().peer.BTM_ReadDevInfo(remote_bd_addr, &dev_type, - &addr_type); + get_btm_client_interface().peer.BTM_ReadDevInfo(remote_bd_addr, &dev_type, &addr_type); if (dev_type == BT_DEVICE_TYPE_BLE || addr_type == BLE_ADDR_RANDOM) { return BT_TRANSPORT_LE; } else if (dev_type == BT_DEVICE_TYPE_DUMO) { - if (get_btm_client_interface().peer.BTM_IsAclConnectionUp( - remote_bd_addr, BT_TRANSPORT_BR_EDR)) { + if (get_btm_client_interface().peer.BTM_IsAclConnectionUp(remote_bd_addr, + BT_TRANSPORT_BR_EDR)) { return BT_TRANSPORT_BR_EDR; - } else if (get_btm_client_interface().peer.BTM_IsAclConnectionUp( - remote_bd_addr, BT_TRANSPORT_LE)) { + } else if (get_btm_client_interface().peer.BTM_IsAclConnectionUp(remote_bd_addr, + BT_TRANSPORT_LE)) { return BT_TRANSPORT_LE; } } @@ -426,8 +395,8 @@ static void bta_dm_discover_services(tBTA_DM_API_DISCOVER& discover) { RawAddress bd_addr = discover.bd_addr; tBT_TRANSPORT transport = (discover.transport == BT_TRANSPORT_AUTO) - ? bta_dm_determine_discovery_transport(bd_addr) - : discover.transport; + ? bta_dm_determine_discovery_transport(bd_addr) + : discover.transport; log::info("starting service discovery to: {}, transport: {}", bd_addr, bt_transport_text(transport)); @@ -444,14 +413,13 @@ static void bta_dm_discover_services(tBTA_DM_API_DISCOVER& discover) { /* service discovery is done for this device */ bta_dm_disc_sm_execute(BTA_DM_DISCOVERY_RESULT_EVT, - std::make_unique(tBTA_DM_SVC_RES{ - .bd_addr = bd_addr, .result = BTA_SUCCESS})); + std::make_unique( + tBTA_DM_SVC_RES{.bd_addr = bd_addr, .result = BTA_SUCCESS})); return; } - BTM_LogHistory( - kBtmLogTag, bd_addr, "Discovery started ", - base::StringPrintf("Transport:%s", bt_transport_text(transport).c_str())); + BTM_LogHistory(kBtmLogTag, bd_addr, "Discovery started ", + base::StringPrintf("Transport:%s", bt_transport_text(transport).c_str())); if (transport == BT_TRANSPORT_LE) { if (bta_dm_discovery_cb.transports & BT_TRANSPORT_LE) { @@ -473,19 +441,18 @@ static void bta_dm_discover_services(tBTA_DM_API_DISCOVER& discover) { log::info("starting SDP discovery on {}", bd_addr); bta_dm_discovery_cb.transports |= BT_TRANSPORT_BR_EDR; - bta_dm_discovery_cb.sdp_state = - std::make_unique(tBTA_DM_SDP_STATE{ + bta_dm_discovery_cb.sdp_state = std::make_unique(tBTA_DM_SDP_STATE{ .bd_addr = bd_addr, .services_to_search = BTA_ALL_SERVICE_MASK, .services_found = 0, .service_index = 0, - }); + }); sdp_performer.Run(bta_dm_discovery_cb.sdp_state.get()); } } void bta_dm_disc_override_sdp_performer_for_testing( - base::RepeatingCallback test_sdp_performer) { + base::RepeatingCallback test_sdp_performer) { if (test_sdp_performer.is_null()) { sdp_performer = default_sdp_performer; } else { @@ -493,7 +460,7 @@ void bta_dm_disc_override_sdp_performer_for_testing( } } void bta_dm_disc_override_gatt_performer_for_testing( - base::RepeatingCallback test_gatt_performer) { + base::RepeatingCallback test_gatt_performer) { if (test_gatt_performer.is_null()) { gatt_performer = default_gatt_performer; } else { @@ -521,22 +488,20 @@ static void bta_dm_gattc_register(void) { return; } get_gatt_interface().BTA_GATTC_AppRegister( - bta_dm_gattc_callback, base::Bind([](uint8_t client_id, uint8_t status) { - tGATT_STATUS gatt_status = static_cast(status); - if (static_cast(status) == GATT_SUCCESS) { - log::info( - "Registered device discovery search gatt client tGATT_IF:{}", - client_id); - bta_dm_discovery_cb.client_if = client_id; - } else { - log::warn( - "Failed to register device discovery search gatt client " - "gatt_status:{} previous tGATT_IF:{}", - bta_dm_discovery_cb.client_if, status); - bta_dm_discovery_cb.client_if = BTA_GATTS_INVALID_IF; - } - }), - false); + bta_dm_gattc_callback, base::Bind([](uint8_t client_id, uint8_t status) { + tGATT_STATUS gatt_status = static_cast(status); + if (static_cast(status) == GATT_SUCCESS) { + log::info("Registered device discovery search gatt client tGATT_IF:{}", client_id); + bta_dm_discovery_cb.client_if = client_id; + } else { + log::warn( + "Failed to register device discovery search gatt client " + "gatt_status:{} previous tGATT_IF:{}", + bta_dm_discovery_cb.client_if, status); + bta_dm_discovery_cb.client_if = BTA_GATTS_INVALID_IF; + } + }), + false); } static void gatt_close_timer_cb(void*) { @@ -545,13 +510,12 @@ static void gatt_close_timer_cb(void*) { void bta_dm_gatt_finished(RawAddress bda, tBTA_STATUS result, std::vector gatt_uuids) { - bta_dm_disc_sm_execute(BTA_DM_DISCOVERY_RESULT_EVT, - std::make_unique(tBTA_DM_SVC_RES{ - .bd_addr = bda, - .is_gatt_over_ble = true, - .gatt_uuids = gatt_uuids, - .result = result, - })); + bta_dm_disc_sm_execute(BTA_DM_DISCOVERY_RESULT_EVT, std::make_unique(tBTA_DM_SVC_RES{ + .bd_addr = bda, + .is_gatt_over_ble = true, + .gatt_uuids = gatt_uuids, + .result = result, + })); } /******************************************************************************* @@ -567,11 +531,10 @@ static void bta_dm_gatt_disc_complete(uint16_t conn_id, tGATT_STATUS status) { bool sdp_pending = bta_dm_discovery_cb.transports & BT_TRANSPORT_BR_EDR; bool le_pending = bta_dm_discovery_cb.transports & BT_TRANSPORT_LE; - log::verbose("conn_id = {}, status = {}, sdp_pending = {}, le_pending = {}", - conn_id, status, sdp_pending, le_pending); + log::verbose("conn_id = {}, status = {}, sdp_pending = {}, le_pending = {}", conn_id, status, + sdp_pending, le_pending); - if (com::android::bluetooth::flags::bta_dm_discover_both() && sdp_pending && - !le_pending) { + if (com::android::bluetooth::flags::bta_dm_discover_both() && sdp_pending && !le_pending) { /* LE Service discovery finished, and services were reported, but SDP is not * finished yet. gatt_close_timer closed the connection, and we received * this callback because of disconnnection */ @@ -583,8 +546,7 @@ static void bta_dm_gatt_disc_complete(uint16_t conn_id, tGATT_STATUS status) { if (conn_id != GATT_INVALID_CONN_ID && status == GATT_SUCCESS) { btgatt_db_element_t* db = NULL; int count = 0; - get_gatt_interface().BTA_GATTC_GetGattDb(conn_id, 0x0000, 0xFFFF, &db, - &count); + get_gatt_interface().BTA_GATTC_GetGattDb(conn_id, 0x0000, 0xFFFF, &db, &count); if (count != 0) { for (int i = 0; i < count; i++) { // we process service entries only @@ -594,8 +556,7 @@ static void bta_dm_gatt_disc_complete(uint16_t conn_id, tGATT_STATUS status) { } osi_free(db); } - log::info("GATT services discovered using LE Transport, count: {}", - gatt_services.size()); + log::info("GATT services discovered using LE Transport, count: {}", gatt_services.size()); } /* no more services to be discovered */ @@ -609,8 +570,8 @@ static void bta_dm_gatt_disc_complete(uint16_t conn_id, tGATT_STATUS status) { // set to false. If property is true / unset there will be a delay if (bta_dm_discovery_cb.gatt_close_timer != nullptr) { /* start a GATT channel close delay timer */ - alarm_set_on_mloop(bta_dm_discovery_cb.gatt_close_timer, - BTA_DM_GATT_CLOSE_DELAY_TOUT, gatt_close_timer_cb, 0); + alarm_set_on_mloop(bta_dm_discovery_cb.gatt_close_timer, BTA_DM_GATT_CLOSE_DELAY_TOUT, + gatt_close_timer_cb, 0); } else { bta_dm_disc_sm_execute(BTA_DM_DISC_CLOSE_TOUT_EVT, nullptr); } @@ -634,8 +595,9 @@ static void bta_dm_gatt_disc_complete(uint16_t conn_id, tGATT_STATUS status) { * ******************************************************************************/ static void bta_dm_close_gatt_conn() { - if (bta_dm_discovery_cb.conn_id != GATT_INVALID_CONN_ID) + if (bta_dm_discovery_cb.conn_id != GATT_INVALID_CONN_ID) { BTA_GATTC_Close(bta_dm_discovery_cb.conn_id); + } bta_dm_discovery_cb.pending_close_bda = RawAddress::kEmpty; bta_dm_discovery_cb.conn_id = GATT_INVALID_CONN_ID; @@ -658,28 +620,22 @@ static void btm_dm_start_gatt_discovery(const RawAddress& bd_addr) { bta_dm_discovery_cb.conn_id != GATT_INVALID_CONN_ID) { bta_dm_discovery_cb.pending_close_bda = RawAddress::kEmpty; alarm_cancel(bta_dm_discovery_cb.gatt_close_timer); - get_gatt_interface().BTA_GATTC_ServiceSearchRequest( - bta_dm_discovery_cb.conn_id, nullptr); + get_gatt_interface().BTA_GATTC_ServiceSearchRequest(bta_dm_discovery_cb.conn_id, nullptr); } else { - if (get_btm_client_interface().peer.BTM_IsAclConnectionUp( - bd_addr, BT_TRANSPORT_LE)) { + if (get_btm_client_interface().peer.BTM_IsAclConnectionUp(bd_addr, BT_TRANSPORT_LE)) { log::debug( - "Use existing gatt client connection for discovery peer:{} " - "transport:{} opportunistic:{:c}", - bd_addr, bt_transport_text(BT_TRANSPORT_LE), - (kUseOpportunistic) ? 'T' : 'F'); - get_gatt_interface().BTA_GATTC_Open(bta_dm_discovery_cb.client_if, - bd_addr, BTM_BLE_DIRECT_CONNECTION, - kUseOpportunistic); + "Use existing gatt client connection for discovery peer:{} " + "transport:{} opportunistic:{:c}", + bd_addr, bt_transport_text(BT_TRANSPORT_LE), (kUseOpportunistic) ? 'T' : 'F'); + get_gatt_interface().BTA_GATTC_Open(bta_dm_discovery_cb.client_if, bd_addr, + BTM_BLE_DIRECT_CONNECTION, kUseOpportunistic); } else { log::debug( - "Opening new gatt client connection for discovery peer:{} " - "transport:{} opportunistic:{:c}", - bd_addr, bt_transport_text(BT_TRANSPORT_LE), - (!kUseOpportunistic) ? 'T' : 'F'); - get_gatt_interface().BTA_GATTC_Open(bta_dm_discovery_cb.client_if, - bd_addr, BTM_BLE_DIRECT_CONNECTION, - !kUseOpportunistic); + "Opening new gatt client connection for discovery peer:{} " + "transport:{} opportunistic:{:c}", + bd_addr, bt_transport_text(BT_TRANSPORT_LE), (!kUseOpportunistic) ? 'T' : 'F'); + get_gatt_interface().BTA_GATTC_Open(bta_dm_discovery_cb.client_if, bd_addr, + BTM_BLE_DIRECT_CONNECTION, !kUseOpportunistic); } } } @@ -694,19 +650,16 @@ static void btm_dm_start_gatt_discovery(const RawAddress& bd_addr) { * ******************************************************************************/ static void bta_dm_proc_open_evt(tBTA_GATTC_OPEN* p_data) { - log::verbose( - "DM Search state= {} bta_dm_discovery_cb.peer_dbaddr:{} connected_bda={}", - bta_dm_discovery_get_state(), bta_dm_discovery_cb.peer_bdaddr, - p_data->remote_bda); + log::verbose("DM Search state= {} bta_dm_discovery_cb.peer_dbaddr:{} connected_bda={}", + bta_dm_discovery_get_state(), bta_dm_discovery_cb.peer_bdaddr, p_data->remote_bda); - log::debug("BTA_GATTC_OPEN_EVT conn_id = {} client_if={} status = {}", - p_data->conn_id, p_data->client_if, p_data->status); + log::debug("BTA_GATTC_OPEN_EVT conn_id = {} client_if={} status = {}", p_data->conn_id, + p_data->client_if, p_data->status); bta_dm_discovery_cb.conn_id = p_data->conn_id; if (p_data->status == GATT_SUCCESS) { - get_gatt_interface().BTA_GATTC_ServiceSearchRequest(p_data->conn_id, - nullptr); + get_gatt_interface().BTA_GATTC_ServiceSearchRequest(p_data->conn_id, nullptr); } else { bta_dm_gatt_disc_complete(GATT_INVALID_CONN_ID, p_data->status); } @@ -731,8 +684,7 @@ static void bta_dm_gattc_callback(tBTA_GATTC_EVT event, tBTA_GATTC* p_data) { case BTA_GATTC_SEARCH_CMPL_EVT: if (bta_dm_discovery_get_state() == BTA_DM_DISCOVER_ACTIVE) { - bta_dm_gatt_disc_complete(p_data->search_cmpl.conn_id, - p_data->search_cmpl.status); + bta_dm_gatt_disc_complete(p_data->search_cmpl.conn_id, p_data->search_cmpl.status); } break; @@ -746,8 +698,7 @@ static void bta_dm_gattc_callback(tBTA_GATTC_EVT event, tBTA_GATTC* p_data) { if (bta_dm_discovery_get_state() == BTA_DM_DISCOVER_ACTIVE) { /* in case of disconnect before search is completed */ if (p_data->close.remote_bda == bta_dm_discovery_cb.peer_bdaddr) { - bta_dm_gatt_disc_complete((uint16_t)GATT_INVALID_CONN_ID, - (tGATT_STATUS)GATT_ERROR); + bta_dm_gatt_disc_complete((uint16_t)GATT_INVALID_CONN_ID, (tGATT_STATUS)GATT_ERROR); } } break; @@ -794,9 +745,8 @@ std::string EpochMillisToString(long long time_ms) { struct tm tm; localtime_r(&time_sec, &tm); std::string s = bluetooth::common::StringFormatTime(kTimeFormatString, tm); - return base::StringPrintf( - "%s.%03u", s.c_str(), - static_cast(time_ms % MillisPerSecond)); + return base::StringPrintf("%s.%03u", s.c_str(), + static_cast(time_ms % MillisPerSecond)); } } // namespace @@ -805,23 +755,20 @@ struct tDISCOVERY_STATE_HISTORY { const tBTA_DM_SERVICE_DISCOVERY_STATE state; const tBTA_DM_DISC_EVT event; std::string ToString() const { - return base::StringPrintf("state:%25s event:%s", - bta_dm_state_text(state).c_str(), + return base::StringPrintf("state:%25s event:%s", bta_dm_state_text(state).c_str(), bta_dm_event_text(event).c_str()); } }; -bluetooth::common::TimestampedCircularBuffer - discovery_state_history_(50 /*history size*/); +bluetooth::common::TimestampedCircularBuffer discovery_state_history_( + 50 /*history size*/); -static void bta_dm_disc_sm_execute(tBTA_DM_DISC_EVT event, - std::unique_ptr msg) { - log::info("state:{}, event:{}[0x{:x}]", - bta_dm_state_text(bta_dm_discovery_get_state()), +static void bta_dm_disc_sm_execute(tBTA_DM_DISC_EVT event, std::unique_ptr msg) { + log::info("state:{}, event:{}[0x{:x}]", bta_dm_state_text(bta_dm_discovery_get_state()), bta_dm_event_text(event), event); discovery_state_history_.Push({ - .state = bta_dm_discovery_get_state(), - .event = event, + .state = bta_dm_discovery_get_state(), + .event = event, }); switch (bta_dm_discovery_get_state()) { @@ -838,17 +785,16 @@ static void bta_dm_disc_sm_execute(tBTA_DM_DISC_EVT event, bta_dm_close_gatt_conn(); break; default: - log::info("Received unexpected event {}[0x{:x}] in state {}", - bta_dm_event_text(event), event, - bta_dm_state_text(bta_dm_discovery_get_state())); + log::info("Received unexpected event {}[0x{:x}] in state {}", bta_dm_event_text(event), + event, bta_dm_state_text(bta_dm_discovery_get_state())); } break; case BTA_DM_DISCOVER_ACTIVE: switch (event) { case BTA_DM_DISCOVERY_RESULT_EVT: - log::assert_that(std::holds_alternative(*msg), - "bad message type: {}", msg->index()); + log::assert_that(std::holds_alternative(*msg), "bad message type: {}", + msg->index()); bta_dm_disc_result(std::get(*msg)); break; @@ -868,16 +814,14 @@ static void bta_dm_disc_sm_execute(tBTA_DM_DISC_EVT event, bta_dm_close_gatt_conn(); break; default: - log::info("Received unexpected event {}[0x{:x}] in state {}", - bta_dm_event_text(event), event, - bta_dm_state_text(bta_dm_discovery_get_state())); + log::info("Received unexpected event {}[0x{:x}] in state {}", bta_dm_event_text(event), + event, bta_dm_state_text(bta_dm_discovery_get_state())); } break; } } -static void bta_dm_disc_init_discovery_cb( - tBTA_DM_SERVICE_DISCOVERY_CB& bta_dm_discovery_cb) { +static void bta_dm_disc_init_discovery_cb(tBTA_DM_SERVICE_DISCOVERY_CB& bta_dm_discovery_cb) { bta_dm_discovery_cb = {}; bta_dm_discovery_cb.service_discovery_state = BTA_DM_DISCOVER_IDLE; bta_dm_discovery_cb.conn_id = GATT_INVALID_CONN_ID; @@ -889,28 +833,25 @@ static void bta_dm_disc_reset() { } void bta_dm_disc_start(bool delay_close_gatt) { - if (!com::android::bluetooth::flags:: - separate_service_and_device_discovery()) { + if (!com::android::bluetooth::flags::separate_service_and_device_discovery()) { bta_dm_disc_legacy::bta_dm_disc_start(delay_close_gatt); return; } bta_dm_disc_reset(); bta_dm_discovery_cb.gatt_close_timer = - delay_close_gatt ? alarm_new("bta_dm_search.gatt_close_timer") : nullptr; + delay_close_gatt ? alarm_new("bta_dm_search.gatt_close_timer") : nullptr; bta_dm_discovery_cb.pending_discovery_queue = {}; } void bta_dm_disc_acl_down(const RawAddress& bd_addr, tBT_TRANSPORT transport) { - if (!com::android::bluetooth::flags:: - separate_service_and_device_discovery()) { + if (!com::android::bluetooth::flags::separate_service_and_device_discovery()) { bta_dm_disc_legacy::bta_dm_disc_acl_down(bd_addr, transport); return; } } void bta_dm_disc_stop() { - if (!com::android::bluetooth::flags:: - separate_service_and_device_discovery()) { + if (!com::android::bluetooth::flags::separate_service_and_device_discovery()) { bta_dm_disc_legacy::bta_dm_disc_stop(); return; } @@ -918,24 +859,19 @@ void bta_dm_disc_stop() { } void bta_dm_disc_start_service_discovery(service_discovery_callbacks cbacks, - const RawAddress& bd_addr, - tBT_TRANSPORT transport) { - if (!com::android::bluetooth::flags:: - separate_service_and_device_discovery()) { - bta_dm_disc_legacy::bta_dm_disc_start_service_discovery(cbacks, bd_addr, - transport); + const RawAddress& bd_addr, tBT_TRANSPORT transport) { + if (!com::android::bluetooth::flags::separate_service_and_device_discovery()) { + bta_dm_disc_legacy::bta_dm_disc_start_service_discovery(cbacks, bd_addr, transport); return; } - bta_dm_disc_sm_execute( - BTA_DM_API_DISCOVER_EVT, - std::make_unique(tBTA_DM_API_DISCOVER{ - .bd_addr = bd_addr, .cbacks = cbacks, .transport = transport})); + bta_dm_disc_sm_execute(BTA_DM_API_DISCOVER_EVT, + std::make_unique(tBTA_DM_API_DISCOVER{ + .bd_addr = bd_addr, .cbacks = cbacks, .transport = transport})); } #define DUMPSYS_TAG "shim::legacy::bta::dm" void DumpsysBtaDmDisc(int fd) { - if (!com::android::bluetooth::flags:: - separate_service_and_device_discovery()) { + if (!com::android::bluetooth::flags::separate_service_and_device_discovery()) { bta_dm_disc_legacy::DumpsysBtaDmDisc(fd); return; } @@ -954,9 +890,7 @@ namespace bluetooth { namespace legacy { namespace testing { -tBTA_DM_SERVICE_DISCOVERY_CB& bta_dm_discovery_cb() { - return ::bta_dm_discovery_cb; -} +tBTA_DM_SERVICE_DISCOVERY_CB& bta_dm_discovery_cb() { return ::bta_dm_discovery_cb; } } // namespace testing } // namespace legacy diff --git a/system/bta/dm/bta_dm_disc.h b/system/bta/dm/bta_dm_disc.h index 6219846a68d..94fcd78f52c 100644 --- a/system/bta/dm/bta_dm_disc.h +++ b/system/bta/dm/bta_dm_disc.h @@ -31,8 +31,7 @@ void bta_dm_disc_stop_device_discovery(); // Bta service discovery start and stop entry points void bta_dm_disc_start_service_discovery(service_discovery_callbacks cbacks, - const RawAddress& bd_addr, - tBT_TRANSPORT transport); + const RawAddress& bd_addr, tBT_TRANSPORT transport); // Bta subsystem entrypoint and lifecycle // Remove when separate_service_and_device_discovery rolls out diff --git a/system/bta/dm/bta_dm_disc_int.h b/system/bta/dm/bta_dm_disc_int.h index 27977dd863f..3b948da5e21 100644 --- a/system/bta/dm/bta_dm_disc_int.h +++ b/system/bta/dm/bta_dm_disc_int.h @@ -67,13 +67,9 @@ typedef struct { using tBTA_DM_MSG = std::variant; -typedef enum { - BTA_DM_DISCOVER_IDLE, - BTA_DM_DISCOVER_ACTIVE -} tBTA_DM_SERVICE_DISCOVERY_STATE; +typedef enum { BTA_DM_DISCOVER_IDLE, BTA_DM_DISCOVER_ACTIVE } tBTA_DM_SERVICE_DISCOVERY_STATE; -inline std::string bta_dm_state_text( - const tBTA_DM_SERVICE_DISCOVERY_STATE& state) { +inline std::string bta_dm_state_text(const tBTA_DM_SERVICE_DISCOVERY_STATE& state) { switch (state) { CASE_RETURN_TEXT(BTA_DM_DISCOVER_IDLE); CASE_RETURN_TEXT(BTA_DM_DISCOVER_ACTIVE); @@ -119,9 +115,9 @@ extern const uint32_t bta_service_id_to_btm_srv_id_lkup_tbl[]; extern const uint16_t bta_service_id_to_uuid_lkup_tbl[]; void bta_dm_disc_override_sdp_performer_for_testing( - base::RepeatingCallback sdp_performer); + base::RepeatingCallback sdp_performer); void bta_dm_disc_override_gatt_performer_for_testing( - base::RepeatingCallback test_gatt_performer); + base::RepeatingCallback test_gatt_performer); void bta_dm_sdp_find_services(tBTA_DM_SDP_STATE* sdp_state); void bta_dm_sdp_result(tSDP_STATUS sdp_result, tBTA_DM_SDP_STATE* sdp_state); void bta_dm_sdp_finished(RawAddress bda, tBTA_STATUS result, @@ -132,8 +128,7 @@ void bta_dm_gatt_finished(RawAddress bda, tBTA_STATUS result, void bta_dm_sdp_callback(const RawAddress& bd_addr, tSDP_STATUS sdp_status); #ifdef TARGET_FLOSS -void bta_dm_sdp_received_di(const RawAddress& bd_addr, - tSDP_DI_GET_RECORD& di_record); +void bta_dm_sdp_received_di(const RawAddress& bd_addr, tSDP_DI_GET_RECORD& di_record); #endif namespace fmt { diff --git a/system/bta/dm/bta_dm_disc_int_legacy.h b/system/bta/dm/bta_dm_disc_int_legacy.h index e791a8e87c6..b8c3ad2567a 100644 --- a/system/bta/dm/bta_dm_disc_int_legacy.h +++ b/system/bta/dm/bta_dm_disc_int_legacy.h @@ -116,10 +116,9 @@ typedef struct { tHCI_STATUS hci_status; } tBTA_DM_SVC_RES; -using tBTA_DM_MSG = - std::variant; +using tBTA_DM_MSG = std::variant; /* DM search state */ typedef enum { diff --git a/system/bta/dm/bta_dm_disc_legacy.cc b/system/bta/dm/bta_dm_disc_legacy.cc index 8281a301da3..e8a92d24be8 100644 --- a/system/bta/dm/bta_dm_disc_legacy.cc +++ b/system/bta/dm/bta_dm_disc_legacy.cc @@ -51,7 +51,7 @@ #include "stack/include/btm_client_interface.h" #include "stack/include/btm_inq.h" #include "stack/include/btm_log_history.h" -#include "stack/include/gap_api.h" // GAP_BleReadPeerPrefConnParams +#include "stack/include/gap_api.h" // GAP_BleReadPeerPrefConnParams #include "stack/include/hidh_api.h" #include "stack/include/main_thread.h" #include "stack/include/sdp_status.h" @@ -80,31 +80,26 @@ constexpr char kBtmLogTag[] = "SDP"; tBTA_DM_SEARCH_CB bta_dm_search_cb; } // namespace -static void bta_dm_search_sm_execute(tBTA_DM_EVT event, - std::unique_ptr msg); +static void bta_dm_search_sm_execute(tBTA_DM_EVT event, std::unique_ptr msg); static void post_disc_evt(tBTA_DM_EVT event, std::unique_ptr msg) { - if (do_in_main_thread(FROM_HERE, base::BindOnce(&bta_dm_search_sm_execute, - event, std::move(msg))) != - BT_STATUS_SUCCESS) { + if (do_in_main_thread(FROM_HERE, base::BindOnce(&bta_dm_search_sm_execute, event, + std::move(msg))) != BT_STATUS_SUCCESS) { log::error("post_disc_evt failed"); } } static void bta_dm_gatt_disc_complete(uint16_t conn_id, tGATT_STATUS status); -static void bta_dm_inq_results_cb(tBTM_INQ_RESULTS* p_inq, const uint8_t* p_eir, - uint16_t eir_len); +static void bta_dm_inq_results_cb(tBTM_INQ_RESULTS* p_inq, const uint8_t* p_eir, uint16_t eir_len); static void bta_dm_inq_cmpl(); static void bta_dm_inq_cmpl_cb(void* p_result); -static void bta_dm_service_search_remname_cback(const RawAddress& bd_addr, - DEV_CLASS dc, BD_NAME bd_name); +static void bta_dm_service_search_remname_cback(const RawAddress& bd_addr, DEV_CLASS dc, + BD_NAME bd_name); static void bta_dm_remname_cback(const tBTM_REMOTE_DEV_NAME* p); static void bta_dm_find_services(const RawAddress& bd_addr); static void bta_dm_discover_next_device(void); -static void bta_dm_sdp_callback(const RawAddress& bd_addr, - tSDP_STATUS sdp_status); +static void bta_dm_sdp_callback(const RawAddress& bd_addr, tSDP_STATUS sdp_status); -static bool bta_dm_read_remote_device_name(const RawAddress& bd_addr, - tBT_TRANSPORT transport); +static bool bta_dm_read_remote_device_name(const RawAddress& bd_addr, tBT_TRANSPORT transport); static void bta_dm_discover_name(const RawAddress& remote_bd_addr); static void bta_dm_discover_services(const RawAddress& remote_bd_addr); @@ -124,77 +119,71 @@ TimestampedStringCircularBuffer disc_gatt_history_{50}; namespace { struct gatt_interface_t { - void (*BTA_GATTC_CancelOpen)(tGATT_IF client_if, const RawAddress& remote_bda, - bool is_direct); + void (*BTA_GATTC_CancelOpen)(tGATT_IF client_if, const RawAddress& remote_bda, bool is_direct); void (*BTA_GATTC_Refresh)(const RawAddress& remote_bda); - void (*BTA_GATTC_GetGattDb)(uint16_t conn_id, uint16_t start_handle, - uint16_t end_handle, btgatt_db_element_t** db, - int* count); - void (*BTA_GATTC_AppRegister)(tBTA_GATTC_CBACK* p_client_cb, - BtaAppRegisterCallback cb, bool eatt_support); + void (*BTA_GATTC_GetGattDb)(uint16_t conn_id, uint16_t start_handle, uint16_t end_handle, + btgatt_db_element_t** db, int* count); + void (*BTA_GATTC_AppRegister)(tBTA_GATTC_CBACK* p_client_cb, BtaAppRegisterCallback cb, + bool eatt_support); void (*BTA_GATTC_Close)(uint16_t conn_id); - void (*BTA_GATTC_ServiceSearchRequest)(uint16_t conn_id, - const bluetooth::Uuid* p_srvc_uuid); + void (*BTA_GATTC_ServiceSearchRequest)(uint16_t conn_id, const bluetooth::Uuid* p_srvc_uuid); void (*BTA_GATTC_Open)(tGATT_IF client_if, const RawAddress& remote_bda, - tBTM_BLE_CONN_TYPE connection_type, - bool opportunistic); + tBTM_BLE_CONN_TYPE connection_type, bool opportunistic); } default_gatt_interface = { - .BTA_GATTC_CancelOpen = - [](tGATT_IF client_if, const RawAddress& remote_bda, bool is_direct) { - disc_gatt_history_.Push(base::StringPrintf( - "%-32s bd_addr:%s client_if:%hu is_direct:%c", "GATTC_CancelOpen", - ADDRESS_TO_LOGGABLE_CSTR(remote_bda), client_if, - (is_direct) ? 'T' : 'F')); - BTA_GATTC_CancelOpen(client_if, remote_bda, is_direct); - }, - .BTA_GATTC_Refresh = - [](const RawAddress& remote_bda) { - disc_gatt_history_.Push( - base::StringPrintf("%-32s bd_addr:%s", "GATTC_Refresh", - ADDRESS_TO_LOGGABLE_CSTR(remote_bda))); - BTA_GATTC_Refresh(remote_bda); - }, - .BTA_GATTC_GetGattDb = - [](uint16_t conn_id, uint16_t start_handle, uint16_t end_handle, - btgatt_db_element_t** db, int* count) { - disc_gatt_history_.Push(base::StringPrintf( - "%-32s conn_id:%hu start_handle:%hu end:handle:%hu", - "GATTC_GetGattDb", conn_id, start_handle, end_handle)); - BTA_GATTC_GetGattDb(conn_id, start_handle, end_handle, db, count); - }, - .BTA_GATTC_AppRegister = - [](tBTA_GATTC_CBACK* p_client_cb, BtaAppRegisterCallback cb, - bool eatt_support) { - disc_gatt_history_.Push( - base::StringPrintf("%-32s eatt_support:%c", "GATTC_AppRegister", - (eatt_support) ? 'T' : 'F')); - BTA_GATTC_AppRegister(p_client_cb, cb, eatt_support); - }, - .BTA_GATTC_Close = - [](uint16_t conn_id) { - disc_gatt_history_.Push( - base::StringPrintf("%-32s conn_id:%hu", "GATTC_Close", conn_id)); - BTA_GATTC_Close(conn_id); - }, - .BTA_GATTC_ServiceSearchRequest = - [](uint16_t conn_id, const bluetooth::Uuid* p_srvc_uuid) { - disc_gatt_history_.Push(base::StringPrintf( - "%-32s conn_id:%hu", "GATTC_ServiceSearchRequest", conn_id)); - if (p_srvc_uuid) { - BTA_GATTC_ServiceSearchRequest(conn_id, *p_srvc_uuid); - } else { - BTA_GATTC_ServiceSearchAllRequest(conn_id); - } - }, - .BTA_GATTC_Open = - [](tGATT_IF client_if, const RawAddress& remote_bda, - tBTM_BLE_CONN_TYPE connection_type, bool opportunistic) { - disc_gatt_history_.Push(base::StringPrintf( - "%-32s bd_addr:%s client_if:%hu type:0x%x opportunistic:%c", - "GATTC_Open", ADDRESS_TO_LOGGABLE_CSTR(remote_bda), client_if, - connection_type, (opportunistic) ? 'T' : 'F')); - BTA_GATTC_Open(client_if, remote_bda, connection_type, opportunistic); - }, + .BTA_GATTC_CancelOpen = + [](tGATT_IF client_if, const RawAddress& remote_bda, bool is_direct) { + disc_gatt_history_.Push(base::StringPrintf( + "%-32s bd_addr:%s client_if:%hu is_direct:%c", "GATTC_CancelOpen", + ADDRESS_TO_LOGGABLE_CSTR(remote_bda), client_if, + (is_direct) ? 'T' : 'F')); + BTA_GATTC_CancelOpen(client_if, remote_bda, is_direct); + }, + .BTA_GATTC_Refresh = + [](const RawAddress& remote_bda) { + disc_gatt_history_.Push(base::StringPrintf("%-32s bd_addr:%s", "GATTC_Refresh", + ADDRESS_TO_LOGGABLE_CSTR(remote_bda))); + BTA_GATTC_Refresh(remote_bda); + }, + .BTA_GATTC_GetGattDb = + [](uint16_t conn_id, uint16_t start_handle, uint16_t end_handle, + btgatt_db_element_t** db, int* count) { + disc_gatt_history_.Push( + base::StringPrintf("%-32s conn_id:%hu start_handle:%hu end:handle:%hu", + "GATTC_GetGattDb", conn_id, start_handle, end_handle)); + BTA_GATTC_GetGattDb(conn_id, start_handle, end_handle, db, count); + }, + .BTA_GATTC_AppRegister = + [](tBTA_GATTC_CBACK* p_client_cb, BtaAppRegisterCallback cb, bool eatt_support) { + disc_gatt_history_.Push(base::StringPrintf("%-32s eatt_support:%c", + "GATTC_AppRegister", + (eatt_support) ? 'T' : 'F')); + BTA_GATTC_AppRegister(p_client_cb, cb, eatt_support); + }, + .BTA_GATTC_Close = + [](uint16_t conn_id) { + disc_gatt_history_.Push( + base::StringPrintf("%-32s conn_id:%hu", "GATTC_Close", conn_id)); + BTA_GATTC_Close(conn_id); + }, + .BTA_GATTC_ServiceSearchRequest = + [](uint16_t conn_id, const bluetooth::Uuid* p_srvc_uuid) { + disc_gatt_history_.Push(base::StringPrintf( + "%-32s conn_id:%hu", "GATTC_ServiceSearchRequest", conn_id)); + if (p_srvc_uuid) { + BTA_GATTC_ServiceSearchRequest(conn_id, *p_srvc_uuid); + } else { + BTA_GATTC_ServiceSearchAllRequest(conn_id); + } + }, + .BTA_GATTC_Open = + [](tGATT_IF client_if, const RawAddress& remote_bda, + tBTM_BLE_CONN_TYPE connection_type, bool opportunistic) { + disc_gatt_history_.Push(base::StringPrintf( + "%-32s bd_addr:%s client_if:%hu type:0x%x opportunistic:%c", "GATTC_Open", + ADDRESS_TO_LOGGABLE_CSTR(remote_bda), client_if, connection_type, + (opportunistic) ? 'T' : 'F')); + BTA_GATTC_Open(client_if, remote_bda, connection_type, opportunistic); + }, }; gatt_interface_t* gatt_interface = &default_gatt_interface; @@ -214,13 +203,9 @@ void bta_dm_disc_gatt_refresh(const RawAddress& bd_addr) { } void bta_dm_disc_remove_device(const RawAddress& bd_addr) { - if (bta_dm_search_cb.state == BTA_DM_DISCOVER_ACTIVE && - bta_dm_search_cb.peer_bdaddr == bd_addr) { - log::info( - "Device removed while service discovery was pending, conclude the " - "service disvovery"); - bta_dm_gatt_disc_complete((uint16_t)GATT_INVALID_CONN_ID, - (tGATT_STATUS)GATT_ERROR); + if (bta_dm_search_cb.state == BTA_DM_DISCOVER_ACTIVE && bta_dm_search_cb.peer_bdaddr == bd_addr) { + log::info("Device removed while service discovery was pending, conclude the service disvovery"); + bta_dm_gatt_disc_complete((uint16_t)GATT_INVALID_CONN_ID, (tGATT_STATUS)GATT_ERROR); } } @@ -228,52 +213,48 @@ void bta_dm_disc_discover_next_device() { bta_dm_discover_next_device(); } void bta_dm_disc_gattc_register() { bta_dm_gattc_register(); } -static void bta_dm_observe_results_cb(tBTM_INQ_RESULTS* p_inq, - const uint8_t* p_eir, uint16_t eir_len); +static void bta_dm_observe_results_cb(tBTM_INQ_RESULTS* p_inq, const uint8_t* p_eir, + uint16_t eir_len); static void bta_dm_observe_cmpl_cb(void* p_result); const uint16_t bta_service_id_to_uuid_lkup_tbl[BTA_MAX_SERVICE_ID] = { - UUID_SERVCLASS_PNP_INFORMATION, /* Reserved */ - UUID_SERVCLASS_SERIAL_PORT, /* BTA_SPP_SERVICE_ID */ - UUID_SERVCLASS_DIALUP_NETWORKING, /* BTA_DUN_SERVICE_ID */ - UUID_SERVCLASS_AUDIO_SOURCE, /* BTA_A2DP_SOURCE_SERVICE_ID */ - UUID_SERVCLASS_LAN_ACCESS_USING_PPP, /* BTA_LAP_SERVICE_ID */ - UUID_SERVCLASS_HEADSET, /* BTA_HSP_HS_SERVICE_ID */ - UUID_SERVCLASS_HF_HANDSFREE, /* BTA_HFP_HS_SERVICE_ID */ - UUID_SERVCLASS_OBEX_OBJECT_PUSH, /* BTA_OPP_SERVICE_ID */ - UUID_SERVCLASS_OBEX_FILE_TRANSFER, /* BTA_FTP_SERVICE_ID */ - UUID_SERVCLASS_CORDLESS_TELEPHONY, /* BTA_CTP_SERVICE_ID */ - UUID_SERVCLASS_INTERCOM, /* BTA_ICP_SERVICE_ID */ - UUID_SERVCLASS_IRMC_SYNC, /* BTA_SYNC_SERVICE_ID */ - UUID_SERVCLASS_DIRECT_PRINTING, /* BTA_BPP_SERVICE_ID */ - UUID_SERVCLASS_IMAGING_RESPONDER, /* BTA_BIP_SERVICE_ID */ - UUID_SERVCLASS_PANU, /* BTA_PANU_SERVICE_ID */ - UUID_SERVCLASS_NAP, /* BTA_NAP_SERVICE_ID */ - UUID_SERVCLASS_GN, /* BTA_GN_SERVICE_ID */ - UUID_SERVCLASS_SAP, /* BTA_SAP_SERVICE_ID */ - UUID_SERVCLASS_AUDIO_SINK, /* BTA_A2DP_SERVICE_ID */ - UUID_SERVCLASS_AV_REMOTE_CONTROL, /* BTA_AVRCP_SERVICE_ID */ - UUID_SERVCLASS_HUMAN_INTERFACE, /* BTA_HID_SERVICE_ID */ - UUID_SERVCLASS_VIDEO_SINK, /* BTA_VDP_SERVICE_ID */ - UUID_SERVCLASS_PBAP_PSE, /* BTA_PBAP_SERVICE_ID */ - UUID_SERVCLASS_HEADSET_AUDIO_GATEWAY, /* BTA_HSP_SERVICE_ID */ - UUID_SERVCLASS_AG_HANDSFREE, /* BTA_HFP_SERVICE_ID */ - UUID_SERVCLASS_MESSAGE_ACCESS, /* BTA_MAP_SERVICE_ID */ - UUID_SERVCLASS_MESSAGE_NOTIFICATION, /* BTA_MN_SERVICE_ID */ - UUID_SERVCLASS_HDP_PROFILE, /* BTA_HDP_SERVICE_ID */ - UUID_SERVCLASS_PBAP_PCE, /* BTA_PCE_SERVICE_ID */ - UUID_PROTOCOL_ATT /* BTA_GATT_SERVICE_ID */ + UUID_SERVCLASS_PNP_INFORMATION, /* Reserved */ + UUID_SERVCLASS_SERIAL_PORT, /* BTA_SPP_SERVICE_ID */ + UUID_SERVCLASS_DIALUP_NETWORKING, /* BTA_DUN_SERVICE_ID */ + UUID_SERVCLASS_AUDIO_SOURCE, /* BTA_A2DP_SOURCE_SERVICE_ID */ + UUID_SERVCLASS_LAN_ACCESS_USING_PPP, /* BTA_LAP_SERVICE_ID */ + UUID_SERVCLASS_HEADSET, /* BTA_HSP_HS_SERVICE_ID */ + UUID_SERVCLASS_HF_HANDSFREE, /* BTA_HFP_HS_SERVICE_ID */ + UUID_SERVCLASS_OBEX_OBJECT_PUSH, /* BTA_OPP_SERVICE_ID */ + UUID_SERVCLASS_OBEX_FILE_TRANSFER, /* BTA_FTP_SERVICE_ID */ + UUID_SERVCLASS_CORDLESS_TELEPHONY, /* BTA_CTP_SERVICE_ID */ + UUID_SERVCLASS_INTERCOM, /* BTA_ICP_SERVICE_ID */ + UUID_SERVCLASS_IRMC_SYNC, /* BTA_SYNC_SERVICE_ID */ + UUID_SERVCLASS_DIRECT_PRINTING, /* BTA_BPP_SERVICE_ID */ + UUID_SERVCLASS_IMAGING_RESPONDER, /* BTA_BIP_SERVICE_ID */ + UUID_SERVCLASS_PANU, /* BTA_PANU_SERVICE_ID */ + UUID_SERVCLASS_NAP, /* BTA_NAP_SERVICE_ID */ + UUID_SERVCLASS_GN, /* BTA_GN_SERVICE_ID */ + UUID_SERVCLASS_SAP, /* BTA_SAP_SERVICE_ID */ + UUID_SERVCLASS_AUDIO_SINK, /* BTA_A2DP_SERVICE_ID */ + UUID_SERVCLASS_AV_REMOTE_CONTROL, /* BTA_AVRCP_SERVICE_ID */ + UUID_SERVCLASS_HUMAN_INTERFACE, /* BTA_HID_SERVICE_ID */ + UUID_SERVCLASS_VIDEO_SINK, /* BTA_VDP_SERVICE_ID */ + UUID_SERVCLASS_PBAP_PSE, /* BTA_PBAP_SERVICE_ID */ + UUID_SERVCLASS_HEADSET_AUDIO_GATEWAY, /* BTA_HSP_SERVICE_ID */ + UUID_SERVCLASS_AG_HANDSFREE, /* BTA_HFP_SERVICE_ID */ + UUID_SERVCLASS_MESSAGE_ACCESS, /* BTA_MAP_SERVICE_ID */ + UUID_SERVCLASS_MESSAGE_NOTIFICATION, /* BTA_MN_SERVICE_ID */ + UUID_SERVCLASS_HDP_PROFILE, /* BTA_HDP_SERVICE_ID */ + UUID_SERVCLASS_PBAP_PCE, /* BTA_PCE_SERVICE_ID */ + UUID_PROTOCOL_ATT /* BTA_GATT_SERVICE_ID */ }; #define MAX_DISC_RAW_DATA_BUF (4096) static uint8_t g_disc_raw_data_buf[MAX_DISC_RAW_DATA_BUF]; -static void bta_dm_search_set_state(tBTA_DM_STATE state) { - bta_dm_search_cb.state = state; -} -static tBTA_DM_STATE bta_dm_search_get_state() { - return bta_dm_search_cb.state; -} +static void bta_dm_search_set_state(tBTA_DM_STATE state) { bta_dm_search_cb.state = state; } +static tBTA_DM_STATE bta_dm_search_get_state() { return bta_dm_search_cb.state; } /******************************************************************************* * @@ -295,8 +276,7 @@ static void bta_dm_search_start(tBTA_DM_API_SEARCH& search) { /* save search params */ bta_dm_search_cb.p_device_search_cback = search.p_cback; - const tBTM_STATUS btm_status = - BTM_StartInquiry(bta_dm_inq_results_cb, bta_dm_inq_cmpl_cb); + const tBTM_STATUS btm_status = BTM_StartInquiry(bta_dm_inq_results_cb, bta_dm_inq_cmpl_cb); switch (btm_status) { case BTM_CMD_STARTED: // Completion callback will be executed when controller inquiry @@ -330,13 +310,12 @@ static void bta_dm_search_cancel() { /* If no Service Search going on then issue cancel remote name in case it is active */ else if (!bta_dm_search_cb.name_discover_done) { - if (get_btm_client_interface().peer.BTM_CancelRemoteDeviceName() != - BTM_CMD_STARTED) { + if (get_btm_client_interface().peer.BTM_CancelRemoteDeviceName() != BTM_CMD_STARTED) { log::warn("Unable to cancel RNR"); } /* bta_dm_search_cmpl is called when receiving the remote name cancel evt */ if (!com::android::bluetooth::flags:: - bta_dm_defer_device_discovery_state_change_until_rnr_complete()) { + bta_dm_defer_device_discovery_state_change_until_rnr_complete()) { bta_dm_search_cmpl(); } } else { @@ -362,15 +341,13 @@ static void bta_dm_discover(tBTA_DM_API_DISCOVER& discover) { bta_dm_search_cb.service_index = 0; bta_dm_search_cb.services_found = 0; bta_dm_search_cb.peer_name[0] = 0; - bta_dm_search_cb.p_btm_inq_info = - get_btm_client_interface().db.BTM_InqDbRead(discover.bd_addr); + bta_dm_search_cb.p_btm_inq_info = get_btm_client_interface().db.BTM_InqDbRead(discover.bd_addr); bta_dm_search_cb.transport = discover.transport; bta_dm_search_cb.name_discover_done = false; - log::info( - "bta_dm_discovery: starting service discovery to {} , transport: {}", - discover.bd_addr, bt_transport_text(discover.transport)); + log::info("bta_dm_discovery: starting service discovery to {} , transport: {}", discover.bd_addr, + bt_transport_text(discover.transport)); bta_dm_discover_services(discover.bd_addr); } @@ -392,10 +369,8 @@ static void bta_dm_disable_search_and_disc(void) { case BTA_DM_SEARCH_CANCELLING: case BTA_DM_DISCOVER_ACTIVE: default: - log::debug( - "Search state machine is not idle so issuing search cancel current " - "state:{}", - bta_dm_state_text(bta_dm_search_get_state())); + log::debug("Search state machine is not idle so issuing search cancel current state:{}", + bta_dm_state_text(bta_dm_search_get_state())); bta_dm_search_cancel(); } } @@ -409,8 +384,7 @@ static void bta_dm_disable_search_and_disc(void) { * Returns true if started to get remote name * ******************************************************************************/ -static bool bta_dm_read_remote_device_name(const RawAddress& bd_addr, - tBT_TRANSPORT transport) { +static bool bta_dm_read_remote_device_name(const RawAddress& bd_addr, tBT_TRANSPORT transport) { tBTM_STATUS btm_status; log::verbose(""); @@ -419,12 +393,12 @@ static bool bta_dm_read_remote_device_name(const RawAddress& bd_addr, bta_dm_search_cb.peer_name[0] = 0; btm_status = get_btm_client_interface().peer.BTM_ReadRemoteDeviceName( - bta_dm_search_cb.peer_bdaddr, bta_dm_remname_cback, transport); + bta_dm_search_cb.peer_bdaddr, bta_dm_remname_cback, transport); if (btm_status == BTM_CMD_STARTED) { log::verbose("BTM_ReadRemoteDeviceName is started"); - return (true); + return true; } else if (btm_status == BTM_BUSY) { log::verbose("BTM_ReadRemoteDeviceName is busy"); @@ -433,13 +407,13 @@ static bool bta_dm_read_remote_device_name(const RawAddress& bd_addr, /* adding callback to get notified that current reading remote name done */ get_btm_client_interface().security.BTM_SecAddRmtNameNotifyCallback( - &bta_dm_service_search_remname_cback); + &bta_dm_service_search_remname_cback); - return (true); + return true; } else { log::warn("BTM_ReadRemoteDeviceName returns 0x{:02X}", btm_status); - return (false); + return false; } } @@ -465,31 +439,27 @@ static void bta_dm_inq_cmpl() { log::verbose("bta_dm_inq_cmpl"); - bta_dm_search_cb.p_btm_inq_info = - get_btm_client_interface().db.BTM_InqDbFirst(); + bta_dm_search_cb.p_btm_inq_info = get_btm_client_interface().db.BTM_InqDbFirst(); if (bta_dm_search_cb.p_btm_inq_info != NULL) { /* start name discovery from the first device on inquiry result */ bta_dm_search_cb.name_discover_done = false; bta_dm_search_cb.peer_name[0] = 0; - bta_dm_discover_name( - bta_dm_search_cb.p_btm_inq_info->results.remote_bd_addr); + bta_dm_discover_name(bta_dm_search_cb.p_btm_inq_info->results.remote_bd_addr); } else { bta_dm_search_cmpl(); } } -static void bta_dm_remote_name_cmpl( - const tBTA_DM_REMOTE_NAME& remote_name_msg) { +static void bta_dm_remote_name_cmpl(const tBTA_DM_REMOTE_NAME& remote_name_msg) { BTM_LogHistory(kBtmLogTag, remote_name_msg.bd_addr, "Remote name completed", - base::StringPrintf( - "status:%s state:%s name:\"%s\"", - hci_status_code_text(remote_name_msg.hci_status).c_str(), - bta_dm_state_text(bta_dm_search_get_state()).c_str(), - PRIVATE_NAME(remote_name_msg.bd_name))); + base::StringPrintf("status:%s state:%s name:\"%s\"", + hci_status_code_text(remote_name_msg.hci_status).c_str(), + bta_dm_state_text(bta_dm_search_get_state()).c_str(), + PRIVATE_NAME(remote_name_msg.bd_name))); tBTM_INQ_INFO* p_btm_inq_info = - get_btm_client_interface().db.BTM_InqDbRead(remote_name_msg.bd_addr); + get_btm_client_interface().db.BTM_InqDbRead(remote_name_msg.bd_addr); if (!bd_name_is_empty(remote_name_msg.bd_name) && p_btm_inq_info) { p_btm_inq_info->appl_knows_rem_name = true; } @@ -501,17 +471,15 @@ static void bta_dm_remote_name_cmpl( // It's enough to send callback to just one of them. if (bta_dm_search_cb.p_device_search_cback != nullptr) { tBTA_DM_SEARCH search_data = { - .name_res = {.bd_addr = remote_name_msg.bd_addr, .bd_name = {}}, + .name_res = {.bd_addr = remote_name_msg.bd_addr, .bd_name = {}}, }; if (remote_name_msg.hci_status == HCI_SUCCESS) { bd_name_copy(search_data.name_res.bd_name, remote_name_msg.bd_name); } - bta_dm_search_cb.p_device_search_cback(BTA_DM_NAME_READ_EVT, - &search_data); + bta_dm_search_cb.p_device_search_cback(BTA_DM_NAME_READ_EVT, &search_data); } else if (bta_dm_search_cb.service_search_cbacks.on_name_read != nullptr) { bta_dm_search_cb.service_search_cbacks.on_name_read( - remote_name_msg.bd_addr, remote_name_msg.hci_status, - remote_name_msg.bd_name); + remote_name_msg.bd_addr, remote_name_msg.hci_status, remote_name_msg.bd_name); } } else { log::warn("Received remote name complete without callback"); @@ -535,8 +503,7 @@ static void bta_dm_remote_name_cmpl( } static void store_avrcp_profile_feature(tSDP_DISC_REC* sdp_rec) { - tSDP_DISC_ATTR* p_attr = - get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( + tSDP_DISC_ATTR* p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( sdp_rec, ATTR_ID_SUPPORTED_FEATURES); if (p_attr == NULL) { return; @@ -548,8 +515,7 @@ static void store_avrcp_profile_feature(tSDP_DISC_REC* sdp_rec) { } if (btif_config_set_bin(sdp_rec->remote_bd_addr.ToString().c_str(), - BTIF_STORAGE_KEY_AV_REM_CTRL_FEATURES, - (const uint8_t*)&avrcp_features, + BTIF_STORAGE_KEY_AV_REM_CTRL_FEATURES, (const uint8_t*)&avrcp_features, sizeof(avrcp_features))) { log::info("Saving avrcp_features: 0x{:x}", avrcp_features); } else { @@ -567,38 +533,37 @@ static void bta_dm_store_audio_profiles_version() { }; std::array audio_profiles = {{ - { - .servclass_uuid = UUID_SERVCLASS_AV_REMOTE_CONTROL, - .btprofile_uuid = UUID_SERVCLASS_AV_REMOTE_CONTROL, - .profile_key = BTIF_STORAGE_KEY_AVRCP_CONTROLLER_VERSION, - .store_audio_profile_feature = store_avrcp_profile_feature, - }, + { + .servclass_uuid = UUID_SERVCLASS_AV_REMOTE_CONTROL, + .btprofile_uuid = UUID_SERVCLASS_AV_REMOTE_CONTROL, + .profile_key = BTIF_STORAGE_KEY_AVRCP_CONTROLLER_VERSION, + .store_audio_profile_feature = store_avrcp_profile_feature, + }, }}; for (const auto& audio_profile : audio_profiles) { tSDP_DISC_REC* sdp_rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb( - bta_dm_search_cb.p_sdp_db, audio_profile.servclass_uuid, NULL); - if (sdp_rec == NULL) continue; + bta_dm_search_cb.p_sdp_db, audio_profile.servclass_uuid, NULL); + if (sdp_rec == NULL) { + continue; + } if (get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - sdp_rec, ATTR_ID_BT_PROFILE_DESC_LIST) == NULL) + sdp_rec, ATTR_ID_BT_PROFILE_DESC_LIST) == NULL) { continue; + } uint16_t profile_version = 0; /* get profile version (if failure, version parameter is not updated) */ if (!get_legacy_stack_sdp_api()->record.SDP_FindProfileVersionInRec( - sdp_rec, audio_profile.btprofile_uuid, &profile_version)) { - log::warn("Unable to find SDP profile version in record peer:{}", - sdp_rec->remote_bd_addr); + sdp_rec, audio_profile.btprofile_uuid, &profile_version)) { + log::warn("Unable to find SDP profile version in record peer:{}", sdp_rec->remote_bd_addr); } if (profile_version != 0) { - if (btif_config_set_bin(sdp_rec->remote_bd_addr.ToString().c_str(), - audio_profile.profile_key, - (const uint8_t*)&profile_version, - sizeof(profile_version))) { + if (btif_config_set_bin(sdp_rec->remote_bd_addr.ToString().c_str(), audio_profile.profile_key, + (const uint8_t*)&profile_version, sizeof(profile_version))) { } else { - log::info("Failed to store peer profile version for {}", - sdp_rec->remote_bd_addr); + log::info("Failed to store peer profile version for {}", sdp_rec->remote_bd_addr); } } audio_profile.store_audio_profile_feature(sdp_rec); @@ -624,24 +589,21 @@ static void bta_dm_sdp_result(tBTA_DM_SDP_RESULT& sdp_event) { const tSDP_RESULT sdp_result = sdp_event.sdp_result; - if ((sdp_event.sdp_result == SDP_SUCCESS) || - (sdp_event.sdp_result == SDP_NO_RECS_MATCH) || + if ((sdp_event.sdp_result == SDP_SUCCESS) || (sdp_event.sdp_result == SDP_NO_RECS_MATCH) || (sdp_event.sdp_result == SDP_DB_FULL)) { log::verbose("sdp_result::0x{:x}", sdp_event.sdp_result); do { p_sdp_rec = NULL; if (bta_dm_search_cb.service_index == (BTA_USER_SERVICE_ID + 1)) { - if (p_sdp_rec && - get_legacy_stack_sdp_api()->record.SDP_FindProtocolListElemInRec( - p_sdp_rec, UUID_PROTOCOL_RFCOMM, &pe)) { + if (p_sdp_rec && get_legacy_stack_sdp_api()->record.SDP_FindProtocolListElemInRec( + p_sdp_rec, UUID_PROTOCOL_RFCOMM, &pe)) { bta_dm_search_cb.peer_scn = (uint8_t)pe.params[0]; scn_found = true; } } else { - service = - bta_service_id_to_uuid_lkup_tbl[bta_dm_search_cb.service_index - 1]; - p_sdp_rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb( - bta_dm_search_cb.p_sdp_db, service, p_sdp_rec); + service = bta_service_id_to_uuid_lkup_tbl[bta_dm_search_cb.service_index - 1]; + p_sdp_rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb(bta_dm_search_cb.p_sdp_db, + service, p_sdp_rec); } /* finished with BR/EDR services, now we check the result for GATT based * service UUID */ @@ -652,12 +614,12 @@ static void bta_dm_sdp_result(tBTA_DM_SDP_RESULT& sdp_event) { do { /* find a service record, report it */ - p_sdp_rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb( - bta_dm_search_cb.p_sdp_db, 0, p_sdp_rec); + p_sdp_rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb(bta_dm_search_cb.p_sdp_db, + 0, p_sdp_rec); if (p_sdp_rec) { Uuid service_uuid; - if (get_legacy_stack_sdp_api()->record.SDP_FindServiceUUIDInRec( - p_sdp_rec, &service_uuid)) { + if (get_legacy_stack_sdp_api()->record.SDP_FindServiceUUIDInRec(p_sdp_rec, + &service_uuid)) { gatt_uuids.push_back(service_uuid); } } @@ -670,19 +632,16 @@ static void bta_dm_sdp_result(tBTA_DM_SDP_RESULT& sdp_event) { BD_NAME bd_name; bd_name_from_char_pointer(bd_name, bta_dm_get_remname()); - bta_dm_search_cb.service_search_cbacks.on_gatt_results( - bta_dm_search_cb.peer_bdaddr, bd_name, gatt_uuids, - /* transport_le */ false); + bta_dm_search_cb.service_search_cbacks.on_gatt_results(bta_dm_search_cb.peer_bdaddr, + bd_name, gatt_uuids, + /* transport_le */ false); } } else { - if ((p_sdp_rec != NULL)) { + if (p_sdp_rec != NULL) { if (service != UUID_SERVCLASS_PNP_INFORMATION) { - bta_dm_search_cb.services_found |= - (tBTA_SERVICE_MASK)(BTA_SERVICE_ID_TO_SERVICE_MASK( + bta_dm_search_cb.services_found |= (tBTA_SERVICE_MASK)(BTA_SERVICE_ID_TO_SERVICE_MASK( bta_dm_search_cb.service_index - 1)); - uint16_t tmp_svc = - bta_service_id_to_uuid_lkup_tbl[bta_dm_search_cb.service_index - - 1]; + uint16_t tmp_svc = bta_service_id_to_uuid_lkup_tbl[bta_dm_search_cb.service_index - 1]; /* Add to the list of UUIDs */ uuid_list.push_back(Uuid::From16Bit(tmp_svc)); } @@ -691,8 +650,9 @@ static void bta_dm_sdp_result(tBTA_DM_SDP_RESULT& sdp_event) { if (bta_dm_search_cb.services_to_search == 0) { bta_dm_search_cb.service_index++; - } else /* regular one service per search or PNP search */ + } else { /* regular one service per search or PNP search */ break; + } } while (bta_dm_search_cb.service_index <= BTA_MAX_SERVICE_ID); @@ -703,19 +663,18 @@ static void bta_dm_sdp_result(tBTA_DM_SDP_RESULT& sdp_event) { do { /* find a service record, report it */ p_sdp_rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb_128bit( - bta_dm_search_cb.p_sdp_db, p_sdp_rec); + bta_dm_search_cb.p_sdp_db, p_sdp_rec); if (p_sdp_rec) { // SDP_FindServiceUUIDInRec_128bit is used only once, refactor? Uuid temp_uuid; - if (get_legacy_stack_sdp_api()->record.SDP_FindServiceUUIDInRec_128bit( - p_sdp_rec, &temp_uuid)) { + if (get_legacy_stack_sdp_api()->record.SDP_FindServiceUUIDInRec_128bit(p_sdp_rec, + &temp_uuid)) { uuid_list.push_back(temp_uuid); } } } while (p_sdp_rec); - if (bluetooth::common::init_flags:: - dynamic_avrcp_version_enhancement_is_enabled() && + if (bluetooth::common::init_flags::dynamic_avrcp_version_enhancement_is_enabled() && bta_dm_search_cb.services_to_search == 0) { bta_dm_store_audio_profiles_version(); } @@ -723,10 +682,10 @@ static void bta_dm_sdp_result(tBTA_DM_SDP_RESULT& sdp_event) { #if TARGET_FLOSS tSDP_DI_GET_RECORD di_record; if (get_legacy_stack_sdp_api()->device_id.SDP_GetDiRecord( - 1, &di_record, bta_dm_search_cb.p_sdp_db) == SDP_SUCCESS) { + 1, &di_record, bta_dm_search_cb.p_sdp_db) == SDP_SUCCESS) { bta_dm_search_cb.service_search_cbacks.on_did_received( - bta_dm_search_cb.peer_bdaddr, di_record.rec.vendor_id_source, - di_record.rec.vendor, di_record.rec.product, di_record.rec.version); + bta_dm_search_cb.peer_bdaddr, di_record.rec.vendor_id_source, di_record.rec.vendor, + di_record.rec.product, di_record.rec.version); } #endif @@ -740,14 +699,13 @@ static void bta_dm_sdp_result(tBTA_DM_SDP_RESULT& sdp_event) { /* start next bd_addr if necessary */ get_btm_client_interface().security.BTM_SecDeleteRmtNameNotifyCallback( - &bta_dm_service_search_remname_cback); + &bta_dm_service_search_remname_cback); BTM_LogHistory( - kBtmLogTag, bta_dm_search_cb.peer_bdaddr, "Discovery completed", - base::StringPrintf("Result:%s services_found:0x%x service_index:0x%d", - sdp_result_text(sdp_result).c_str(), - bta_dm_search_cb.services_found, - bta_dm_search_cb.service_index)); + kBtmLogTag, bta_dm_search_cb.peer_bdaddr, "Discovery completed", + base::StringPrintf("Result:%s services_found:0x%x service_index:0x%d", + sdp_result_text(sdp_result).c_str(), + bta_dm_search_cb.services_found, bta_dm_search_cb.service_index)); auto msg = std::make_unique(tBTA_DM_SVC_RES{}); auto& disc_result = std::get(*msg); @@ -755,15 +713,14 @@ static void bta_dm_sdp_result(tBTA_DM_SDP_RESULT& sdp_event) { disc_result.result = BTA_SUCCESS; disc_result.uuids = std::move(uuid_list); // Copy the raw_data to the discovery result structure - if (bta_dm_search_cb.p_sdp_db != NULL && - bta_dm_search_cb.p_sdp_db->raw_used != 0 && + if (bta_dm_search_cb.p_sdp_db != NULL && bta_dm_search_cb.p_sdp_db->raw_used != 0 && bta_dm_search_cb.p_sdp_db->raw_data != NULL) { log::verbose("raw_data used = 0x{:x} raw_data_ptr = 0x{}", bta_dm_search_cb.p_sdp_db->raw_used, fmt::ptr(bta_dm_search_cb.p_sdp_db->raw_data)); bta_dm_search_cb.p_sdp_db->raw_data = - NULL; // no need to free this - it is a global assigned. + NULL; // no need to free this - it is a global assigned. bta_dm_search_cb.p_sdp_db->raw_used = 0; bta_dm_search_cb.p_sdp_db->raw_size = 0; } else { @@ -775,31 +732,30 @@ static void bta_dm_sdp_result(tBTA_DM_SDP_RESULT& sdp_event) { // Piggy back the SCN over result field if (scn_found) { - disc_result.result = - static_cast((3 + bta_dm_search_cb.peer_scn)); + disc_result.result = static_cast(3 + bta_dm_search_cb.peer_scn); disc_result.services |= BTA_USER_SERVICE_MASK; - log::verbose("Piggy back the SCN over result field SCN={}", - bta_dm_search_cb.peer_scn); + log::verbose("Piggy back the SCN over result field SCN={}", bta_dm_search_cb.peer_scn); } disc_result.bd_addr = bta_dm_search_cb.peer_bdaddr; bta_dm_search_sm_execute(BTA_DM_DISCOVERY_RESULT_EVT, std::move(msg)); } } else { - BTM_LogHistory( - kBtmLogTag, bta_dm_search_cb.peer_bdaddr, "Discovery failed", - base::StringPrintf("Result:%s", sdp_result_text(sdp_result).c_str())); + BTM_LogHistory(kBtmLogTag, bta_dm_search_cb.peer_bdaddr, "Discovery failed", + base::StringPrintf("Result:%s", sdp_result_text(sdp_result).c_str())); log::error("SDP connection failed {}", sdp_status_text(sdp_result)); - if (sdp_event.sdp_result == SDP_CONN_FAILED) + if (sdp_event.sdp_result == SDP_CONN_FAILED) { bta_dm_search_cb.wait_disc = false; + } /* not able to connect go to next device */ - if (bta_dm_search_cb.p_sdp_db) + if (bta_dm_search_cb.p_sdp_db) { osi_free_and_reset((void**)&bta_dm_search_cb.p_sdp_db); + } get_btm_client_interface().security.BTM_SecDeleteRmtNameNotifyCallback( - &bta_dm_service_search_remname_cback); + &bta_dm_service_search_remname_cback); auto msg = std::make_unique(tBTA_DM_SVC_RES{}); auto& disc_result = std::get(*msg); @@ -814,14 +770,13 @@ static void bta_dm_sdp_result(tBTA_DM_SDP_RESULT& sdp_event) { /** Callback of peer's DIS reply. This is only called for floss */ #if TARGET_FLOSS -static void bta_dm_read_dis_cmpl(const RawAddress& addr, - tDIS_VALUE* p_dis_value) { +static void bta_dm_read_dis_cmpl(const RawAddress& addr, tDIS_VALUE* p_dis_value) { if (!p_dis_value) { log::warn("read DIS failed"); } else { bta_dm_search_cb.service_search_cbacks.on_did_received( - addr, p_dis_value->pnp_id.vendor_id_src, p_dis_value->pnp_id.vendor_id, - p_dis_value->pnp_id.product_id, p_dis_value->pnp_id.product_version); + addr, p_dis_value->pnp_id.vendor_id_src, p_dis_value->pnp_id.vendor_id, + p_dis_value->pnp_id.product_id, p_dis_value->pnp_id.product_version); } bta_dm_execute_queued_request(); @@ -849,17 +804,14 @@ static void bta_dm_search_cmpl() { /* no BLE connection, i.e. Classic service discovery end */ if (conn_id == GATT_INVALID_CONN_ID) { if (bta_dm_search_cb.gatt_disc_active) { - log::warn( - "GATT active but no BLE connection, likely disconnected midway " - "through"); + log::warn("GATT active but no BLE connection, likely disconnected midway through"); } else { log::info("No BLE connection, processing classic results"); } } else { btgatt_db_element_t* db = NULL; int count = 0; - get_gatt_interface().BTA_GATTC_GetGattDb(conn_id, 0x0000, 0xFFFF, &db, - &count); + get_gatt_interface().BTA_GATTC_GetGattDb(conn_id, 0x0000, 0xFFFF, &db, &count); if (count != 0) { for (int i = 0; i < count; i++) { // we process service entries only @@ -868,9 +820,7 @@ static void bta_dm_search_cmpl() { } } osi_free(db); - log::info( - "GATT services discovered using LE Transport, will always send to " - "upper layer"); + log::info("GATT services discovered using LE Transport, will always send to upper layer"); send_gatt_results = true; } else { log::warn("Empty GATT database - no BLE services discovered"); @@ -884,9 +834,9 @@ static void bta_dm_search_cmpl() { BD_NAME bd_name; bd_name_from_char_pointer(bd_name, bta_dm_get_remname()); - bta_dm_search_cb.service_search_cbacks.on_gatt_results( - bta_dm_search_cb.peer_bdaddr, bd_name, gatt_services, - /* transport_le */ true); + bta_dm_search_cb.service_search_cbacks.on_gatt_results(bta_dm_search_cb.peer_bdaddr, bd_name, + gatt_services, + /* transport_le */ true); } else { log::warn("on_gatt_results is nullptr!"); } @@ -899,8 +849,7 @@ static void bta_dm_search_cmpl() { #if TARGET_FLOSS if (conn_id != GATT_INVALID_CONN_ID && - DIS_ReadDISInfo(bta_dm_search_cb.peer_bdaddr, bta_dm_read_dis_cmpl, - DIS_ATTR_PNP_ID_BIT)) { + DIS_ReadDISInfo(bta_dm_search_cb.peer_bdaddr, bta_dm_read_dis_cmpl, DIS_ATTR_PNP_ID_BIT)) { return; } #endif @@ -928,16 +877,15 @@ static void bta_dm_disc_result(tBTA_DM_SVC_RES& disc_result) { /* if any BR/EDR service discovery has been done, report the event */ if (!is_gatt_over_ble) { auto& r = disc_result; - bta_dm_search_cb.service_search_cbacks.on_service_discovery_results( - r.bd_addr, r.uuids, r.result); + bta_dm_search_cb.service_search_cbacks.on_service_discovery_results(r.bd_addr, r.uuids, + r.result); } /* Services were discovered while device search is in progress. * Don't execute bta_dm_search_cmpl, as it would also finish the device * search. It will be executed later when device search is finished. */ if (bta_dm_search_get_state() != BTA_DM_SEARCH_ACTIVE) { - get_gatt_interface().BTA_GATTC_CancelOpen(0, bta_dm_search_cb.peer_bdaddr, - true); + get_gatt_interface().BTA_GATTC_CancelOpen(0, bta_dm_search_cb.peer_bdaddr, true); bta_dm_search_cmpl(); } @@ -952,9 +900,7 @@ static void bta_dm_disc_result(tBTA_DM_SVC_RES& disc_result) { * Returns void * ******************************************************************************/ -static void bta_dm_free_sdp_db() { - osi_free_and_reset((void**)&bta_dm_search_cb.p_sdp_db); -} +static void bta_dm_free_sdp_db() { osi_free_and_reset((void**)&bta_dm_search_cb.p_sdp_db); } /******************************************************************************* * @@ -983,8 +929,7 @@ static void bta_dm_queue_search(tBTA_DM_API_SEARCH& search) { * ******************************************************************************/ static void bta_dm_queue_disc(tBTA_DM_API_DISCOVER& discovery) { - log::info("bta_dm_discovery: queuing service discovery to {}", - discovery.bd_addr); + log::info("bta_dm_discovery: queuing service discovery to {}", discovery.bd_addr); bta_dm_search_cb.pending_discovery_queue.push(discovery); } @@ -999,17 +944,14 @@ static void bta_dm_queue_disc(tBTA_DM_API_DISCOVER& discovery) { ******************************************************************************/ static void bta_dm_execute_queued_request() { if (!bta_dm_search_cb.pending_discovery_queue.empty()) { - tBTA_DM_API_DISCOVER pending_discovery = - bta_dm_search_cb.pending_discovery_queue.front(); + tBTA_DM_API_DISCOVER pending_discovery = bta_dm_search_cb.pending_discovery_queue.front(); bta_dm_search_cb.pending_discovery_queue.pop(); log::info("Start pending discovery"); - post_disc_evt( - BTA_DM_API_DISCOVER_EVT, - std::make_unique(tBTA_DM_API_DISCOVER{pending_discovery})); + post_disc_evt(BTA_DM_API_DISCOVER_EVT, + std::make_unique(tBTA_DM_API_DISCOVER{pending_discovery})); } else if (bta_dm_search_cb.p_pending_search) { log::info("Start pending search"); - post_disc_evt(BTA_DM_API_SEARCH_EVT, - std::move(bta_dm_search_cb.p_pending_search)); + post_disc_evt(BTA_DM_API_SEARCH_EVT, std::move(bta_dm_search_cb.p_pending_search)); bta_dm_search_cb.p_pending_search.reset(); } } @@ -1023,9 +965,7 @@ static void bta_dm_execute_queued_request() { * Returns bool * ******************************************************************************/ -bool bta_dm_is_search_request_queued() { - return bta_dm_search_cb.p_pending_search != NULL; -} +bool bta_dm_is_search_request_queued() { return bta_dm_search_cb.p_pending_search != NULL; } /******************************************************************************* * @@ -1055,8 +995,7 @@ static void bta_dm_search_cancel_notify() { case BTA_DM_SEARCH_ACTIVE: case BTA_DM_SEARCH_CANCELLING: if (!bta_dm_search_cb.name_discover_done) { - if (get_btm_client_interface().peer.BTM_CancelRemoteDeviceName() != - BTM_CMD_STARTED) { + if (get_btm_client_interface().peer.BTM_CancelRemoteDeviceName() != BTM_CMD_STARTED) { log::warn("Unable to cancel RNR"); } } @@ -1081,14 +1020,11 @@ static void bta_dm_find_services(const RawAddress& bd_addr) { while (bta_dm_search_cb.service_index < BTA_MAX_SERVICE_ID) { Uuid uuid = Uuid::kEmpty; if (bta_dm_search_cb.services_to_search & - (tBTA_SERVICE_MASK)(BTA_SERVICE_ID_TO_SERVICE_MASK( - bta_dm_search_cb.service_index))) { - bta_dm_search_cb.p_sdp_db = - (tSDP_DISCOVERY_DB*)osi_malloc(BTA_DM_SDP_DB_SIZE); + (tBTA_SERVICE_MASK)(BTA_SERVICE_ID_TO_SERVICE_MASK(bta_dm_search_cb.service_index))) { + bta_dm_search_cb.p_sdp_db = (tSDP_DISCOVERY_DB*)osi_malloc(BTA_DM_SDP_DB_SIZE); /* try to search all services by search based on L2CAP UUID */ - log::info("services_to_search={:08x}", - bta_dm_search_cb.services_to_search); + log::info("services_to_search={:08x}", bta_dm_search_cb.services_to_search); if (bta_dm_search_cb.services_to_search & BTA_RES_SERVICE_MASK) { uuid = Uuid::From16Bit(bta_service_id_to_uuid_lkup_tbl[0]); bta_dm_search_cb.services_to_search &= ~BTA_RES_SERVICE_MASK; @@ -1099,10 +1035,8 @@ static void bta_dm_find_services(const RawAddress& bd_addr) { log::info("search UUID = {}", uuid.ToString()); if (!get_legacy_stack_sdp_api()->service.SDP_InitDiscoveryDb( - bta_dm_search_cb.p_sdp_db, BTA_DM_SDP_DB_SIZE, 1, &uuid, 0, - NULL)) { - log::warn("Unable to initialize SDP service discovery db peer:{}", - bd_addr); + bta_dm_search_cb.p_sdp_db, BTA_DM_SDP_DB_SIZE, 1, &uuid, 0, NULL)) { + log::warn("Unable to initialize SDP service discovery db peer:{}", bd_addr); } memset(g_disc_raw_data_buf, 0, sizeof(g_disc_raw_data_buf)); @@ -1110,12 +1044,9 @@ static void bta_dm_find_services(const RawAddress& bd_addr) { bta_dm_search_cb.p_sdp_db->raw_size = MAX_DISC_RAW_DATA_BUF; - if (!get_legacy_stack_sdp_api() - ->service.SDP_ServiceSearchAttributeRequest( - bd_addr, bta_dm_search_cb.p_sdp_db, &bta_dm_sdp_callback)) { - log::warn( - "Unable to start SDP service search attribute request peer:{}", - bd_addr); + if (!get_legacy_stack_sdp_api()->service.SDP_ServiceSearchAttributeRequest( + bd_addr, bta_dm_search_cb.p_sdp_db, &bta_dm_sdp_callback)) { + log::warn("Unable to start SDP service search attribute request peer:{}", bd_addr); /* * If discovery is not successful with this device, then * proceed with the next one. @@ -1162,13 +1093,12 @@ static void bta_dm_discover_next_device(void) { log::verbose("bta_dm_discover_next_device"); /* searching next device on inquiry result */ - bta_dm_search_cb.p_btm_inq_info = get_btm_client_interface().db.BTM_InqDbNext( - bta_dm_search_cb.p_btm_inq_info); + bta_dm_search_cb.p_btm_inq_info = + get_btm_client_interface().db.BTM_InqDbNext(bta_dm_search_cb.p_btm_inq_info); if (bta_dm_search_cb.p_btm_inq_info != NULL) { bta_dm_search_cb.name_discover_done = false; bta_dm_search_cb.peer_name[0] = 0; - bta_dm_discover_name( - bta_dm_search_cb.p_btm_inq_info->results.remote_bd_addr); + bta_dm_discover_name(bta_dm_search_cb.p_btm_inq_info->results.remote_bd_addr); } else { post_disc_evt(BTA_DM_SEARCH_CMPL_EVT, nullptr); } @@ -1183,23 +1113,21 @@ static void bta_dm_discover_next_device(void) { * Returns void * ******************************************************************************/ -static tBT_TRANSPORT bta_dm_determine_discovery_transport( - const RawAddress& remote_bd_addr) { +static tBT_TRANSPORT bta_dm_determine_discovery_transport(const RawAddress& remote_bd_addr) { tBT_TRANSPORT transport = BT_TRANSPORT_BR_EDR; if (bta_dm_search_cb.transport == BT_TRANSPORT_AUTO) { tBT_DEVICE_TYPE dev_type; tBLE_ADDR_TYPE addr_type; - get_btm_client_interface().peer.BTM_ReadDevInfo(remote_bd_addr, &dev_type, - &addr_type); + get_btm_client_interface().peer.BTM_ReadDevInfo(remote_bd_addr, &dev_type, &addr_type); if (dev_type == BT_DEVICE_TYPE_BLE || addr_type == BLE_ADDR_RANDOM) { transport = BT_TRANSPORT_LE; } else if (dev_type == BT_DEVICE_TYPE_DUMO) { - if (get_btm_client_interface().peer.BTM_IsAclConnectionUp( - remote_bd_addr, BT_TRANSPORT_BR_EDR)) { + if (get_btm_client_interface().peer.BTM_IsAclConnectionUp(remote_bd_addr, + BT_TRANSPORT_BR_EDR)) { transport = BT_TRANSPORT_BR_EDR; - } else if (get_btm_client_interface().peer.BTM_IsAclConnectionUp( - remote_bd_addr, BT_TRANSPORT_LE)) { + } else if (get_btm_client_interface().peer.BTM_IsAclConnectionUp(remote_bd_addr, + BT_TRANSPORT_LE)) { transport = BT_TRANSPORT_LE; } } @@ -1210,39 +1138,31 @@ static tBT_TRANSPORT bta_dm_determine_discovery_transport( } static void bta_dm_discover_name(const RawAddress& remote_bd_addr) { - const tBT_TRANSPORT transport = - bta_dm_determine_discovery_transport(remote_bd_addr); + const tBT_TRANSPORT transport = bta_dm_determine_discovery_transport(remote_bd_addr); log::verbose("BDA: {}", remote_bd_addr); bta_dm_search_cb.peer_bdaddr = remote_bd_addr; - log::verbose( - "name_discover_done = {} p_btm_inq_info 0x{} state = {}, transport={}", - bta_dm_search_cb.name_discover_done, - fmt::ptr(bta_dm_search_cb.p_btm_inq_info), bta_dm_search_get_state(), - transport); + log::verbose("name_discover_done = {} p_btm_inq_info 0x{} state = {}, transport={}", + bta_dm_search_cb.name_discover_done, fmt::ptr(bta_dm_search_cb.p_btm_inq_info), + bta_dm_search_get_state(), transport); if (bta_dm_search_cb.p_btm_inq_info) { - log::verbose("appl_knows_rem_name {}", - bta_dm_search_cb.p_btm_inq_info->appl_knows_rem_name); + log::verbose("appl_knows_rem_name {}", bta_dm_search_cb.p_btm_inq_info->appl_knows_rem_name); } if (((bta_dm_search_cb.p_btm_inq_info) && - (bta_dm_search_cb.p_btm_inq_info->results.device_type == - BT_DEVICE_TYPE_BLE) && + (bta_dm_search_cb.p_btm_inq_info->results.device_type == BT_DEVICE_TYPE_BLE) && (bta_dm_search_get_state() == BTA_DM_SEARCH_ACTIVE)) || (transport == BT_TRANSPORT_LE && - interop_match_addr(INTEROP_DISABLE_NAME_REQUEST, - &bta_dm_search_cb.peer_bdaddr))) { + interop_match_addr(INTEROP_DISABLE_NAME_REQUEST, &bta_dm_search_cb.peer_bdaddr))) { /* Do not perform RNR for LE devices at inquiry complete*/ bta_dm_search_cb.name_discover_done = true; } // If we already have the name we can skip getting the name if (BTM_IsRemoteNameKnown(remote_bd_addr, transport) && bluetooth::common::init_flags::sdp_skip_rnr_if_known_is_enabled()) { - log::debug( - "Security record already known skipping read remote name peer:{}", - remote_bd_addr); + log::debug("Security record already known skipping read remote name peer:{}", remote_bd_addr); bta_dm_search_cb.name_discover_done = true; } @@ -1251,16 +1171,13 @@ static void bta_dm_discover_name(const RawAddress& remote_bd_addr) { ((bta_dm_search_cb.p_btm_inq_info == NULL) || (bta_dm_search_cb.p_btm_inq_info && (!bta_dm_search_cb.p_btm_inq_info->appl_knows_rem_name)))) { - if (bta_dm_read_remote_device_name(bta_dm_search_cb.peer_bdaddr, - transport)) { + if (bta_dm_read_remote_device_name(bta_dm_search_cb.peer_bdaddr, transport)) { if (bta_dm_search_get_state() != BTA_DM_DISCOVER_ACTIVE) { log::debug("Reset transport state for next discovery"); bta_dm_search_cb.transport = BT_TRANSPORT_AUTO; } - BTM_LogHistory(kBtmLogTag, bta_dm_search_cb.peer_bdaddr, - "Read remote name", - base::StringPrintf("Transport:%s", - bt_transport_text(transport).c_str())); + BTM_LogHistory(kBtmLogTag, bta_dm_search_cb.peer_bdaddr, "Read remote name", + base::StringPrintf("Transport:%s", bt_transport_text(transport).c_str())); return; } else { log::error("Unable to start read remote device name"); @@ -1289,8 +1206,7 @@ static void bta_dm_discover_name(const RawAddress& remote_bd_addr) { } static void bta_dm_discover_services(const RawAddress& remote_bd_addr) { - const tBT_TRANSPORT transport = - bta_dm_determine_discovery_transport(remote_bd_addr); + const tBT_TRANSPORT transport = bta_dm_determine_discovery_transport(remote_bd_addr); log::verbose("BDA: {}, transport={}, state = {}", remote_bd_addr, transport, bta_dm_search_get_state()); @@ -1301,8 +1217,9 @@ static void bta_dm_discover_services(const RawAddress& remote_bd_addr) { bta_dm_search_cb.transport = BT_TRANSPORT_AUTO; bool sdp_disable = HID_HostSDPDisable(remote_bd_addr); - if (sdp_disable) + if (sdp_disable) { log::debug("peer:{} with HIDSDPDisable attribute.", remote_bd_addr); + } /* if application wants to discover service and HIDSDPDisable attribute is false. @@ -1311,8 +1228,7 @@ static void bta_dm_discover_services(const RawAddress& remote_bd_addr) { connections to the Control or Interrupt channels */ if (!sdp_disable) { BTM_LogHistory(kBtmLogTag, remote_bd_addr, "Discovery started ", - base::StringPrintf("Transport:%s", - bt_transport_text(transport).c_str())); + base::StringPrintf("Transport:%s", bt_transport_text(transport).c_str())); /* initialize variables */ bta_dm_search_cb.service_index = 0; @@ -1325,11 +1241,12 @@ static void bta_dm_discover_services(const RawAddress& remote_bd_addr) { if connection exists, we don't have to wait for ACL link to go down to start search on next device */ if (transport == BT_TRANSPORT_BR_EDR) { - if (get_btm_client_interface().peer.BTM_IsAclConnectionUp( - bta_dm_search_cb.peer_bdaddr, BT_TRANSPORT_BR_EDR)) + if (get_btm_client_interface().peer.BTM_IsAclConnectionUp(bta_dm_search_cb.peer_bdaddr, + BT_TRANSPORT_BR_EDR)) { bta_dm_search_cb.wait_disc = false; - else + } else { bta_dm_search_cb.wait_disc = true; + } } if (transport == BT_TRANSPORT_LE) { @@ -1343,8 +1260,7 @@ static void bta_dm_discover_services(const RawAddress& remote_bd_addr) { return; } } else { - log::info("bta_dm_discovery: starting SDP discovery on {}", - bta_dm_search_cb.peer_bdaddr); + log::info("bta_dm_discovery: starting SDP discovery on {}", bta_dm_search_cb.peer_bdaddr); bta_dm_search_cb.sdp_results = false; bta_dm_find_services(bta_dm_search_cb.peer_bdaddr); return; @@ -1373,11 +1289,9 @@ static void bta_dm_discover_services(const RawAddress& remote_bd_addr) { * Returns void * ******************************************************************************/ -static void bta_dm_sdp_callback(const RawAddress& /* bd_addr */, - tSDP_STATUS sdp_status) { +static void bta_dm_sdp_callback(const RawAddress& /* bd_addr */, tSDP_STATUS sdp_status) { post_disc_evt(BTA_DM_SDP_RESULT_EVT, - std::make_unique( - tBTA_DM_SDP_RESULT{.sdp_result = sdp_status})); + std::make_unique(tBTA_DM_SDP_RESULT{.sdp_result = sdp_status})); } /******************************************************************************* @@ -1389,8 +1303,7 @@ static void bta_dm_sdp_callback(const RawAddress& /* bd_addr */, * Returns void * ******************************************************************************/ -static void bta_dm_inq_results_cb(tBTM_INQ_RESULTS* p_inq, const uint8_t* p_eir, - uint16_t eir_len) { +static void bta_dm_inq_results_cb(tBTM_INQ_RESULTS* p_inq, const uint8_t* p_eir, uint16_t eir_len) { tBTA_DM_SEARCH result; tBTM_INQ_INFO* p_inq_info; uint16_t service_class; @@ -1402,8 +1315,7 @@ static void bta_dm_inq_results_cb(tBTM_INQ_RESULTS* p_inq, const uint8_t* p_eir, result.inq_res.dev_class = p_inq->dev_class; BTM_COD_SERVICE_CLASS(service_class, p_inq->dev_class); - result.inq_res.is_limited = - (service_class & BTM_COD_SERVICE_LMTD_DISCOVER) ? true : false; + result.inq_res.is_limited = (service_class & BTM_COD_SERVICE_LMTD_DISCOVER) ? true : false; result.inq_res.rssi = p_inq->rssi; result.inq_res.ble_addr_type = p_inq->ble_addr_type; @@ -1419,22 +1331,23 @@ static void bta_dm_inq_results_cb(tBTM_INQ_RESULTS* p_inq, const uint8_t* p_eir, result.inq_res.ble_evt_type = p_inq->ble_evt_type; - p_inq_info = - get_btm_client_interface().db.BTM_InqDbRead(p_inq->remote_bd_addr); + p_inq_info = get_btm_client_interface().db.BTM_InqDbRead(p_inq->remote_bd_addr); if (p_inq_info != NULL) { /* initialize remt_name_not_required to false so that we get the name by * default */ result.inq_res.remt_name_not_required = false; } - if (bta_dm_search_cb.p_device_search_cback) + if (bta_dm_search_cb.p_device_search_cback) { bta_dm_search_cb.p_device_search_cback(BTA_DM_INQ_RES_EVT, &result); + } if (p_inq_info) { /* application indicates if it knows the remote name, inside the callback copy that to the inquiry data base*/ - if (result.inq_res.remt_name_not_required) + if (result.inq_res.remt_name_not_required) { p_inq_info->appl_knows_rem_name = true; + } } } @@ -1462,8 +1375,7 @@ static void bta_dm_inq_cmpl_cb(void* /* p_result */) { * Returns void * ******************************************************************************/ -static void bta_dm_service_search_remname_cback(const RawAddress& bd_addr, - DEV_CLASS /* dc */, +static void bta_dm_service_search_remname_cback(const RawAddress& bd_addr, DEV_CLASS /* dc */, BD_NAME bd_name) { tBTM_REMOTE_DEV_NAME rem_name = {}; tBTM_STATUS btm_status; @@ -1480,8 +1392,7 @@ static void bta_dm_service_search_remname_cback(const RawAddress& bd_addr, } else { /* get name of device */ btm_status = get_btm_client_interface().peer.BTM_ReadRemoteDeviceName( - bta_dm_search_cb.peer_bdaddr, bta_dm_remname_cback, - BT_TRANSPORT_BR_EDR); + bta_dm_search_cb.peer_bdaddr, bta_dm_remname_cback, BT_TRANSPORT_BR_EDR); if (btm_status == BTM_BUSY) { /* wait for next chance(notification of remote name discovery done) */ log::verbose("BTM_ReadRemoteDeviceName is busy"); @@ -1510,35 +1421,29 @@ static void bta_dm_service_search_remname_cback(const RawAddress& bd_addr, * ******************************************************************************/ static void bta_dm_remname_cback(const tBTM_REMOTE_DEV_NAME* p_remote_name) { - log::assert_that(p_remote_name != nullptr, - "assert failed: p_remote_name != nullptr"); + log::assert_that(p_remote_name != nullptr, "assert failed: p_remote_name != nullptr"); log::info( - "Remote name request complete peer:{} btm_status:{} hci_status:{} " - "name[0]:{:c} length:{}", - p_remote_name->bd_addr, btm_status_text(p_remote_name->status), - hci_error_code_text(p_remote_name->hci_status), - p_remote_name->remote_bd_name[0], - strnlen((const char*)p_remote_name->remote_bd_name, BD_NAME_LEN)); + "Remote name request complete peer:{} btm_status:{} hci_status:{} name[0]:{:c} length:{}", + p_remote_name->bd_addr, btm_status_text(p_remote_name->status), + hci_error_code_text(p_remote_name->hci_status), p_remote_name->remote_bd_name[0], + strnlen((const char*)p_remote_name->remote_bd_name, BD_NAME_LEN)); if (bta_dm_search_cb.peer_bdaddr == p_remote_name->bd_addr) { get_btm_client_interface().security.BTM_SecDeleteRmtNameNotifyCallback( - &bta_dm_service_search_remname_cback); + &bta_dm_service_search_remname_cback); } else { // if we got a different response, maybe ignore it // we will have made a request directly from BTM_ReadRemoteDeviceName so we // expect a dedicated response for us if (p_remote_name->hci_status == HCI_ERR_CONNECTION_EXISTS) { get_btm_client_interface().security.BTM_SecDeleteRmtNameNotifyCallback( - &bta_dm_service_search_remname_cback); - log::info( - "Assume command failed due to disconnection hci_status:{} peer:{}", - hci_error_code_text(p_remote_name->hci_status), - p_remote_name->bd_addr); + &bta_dm_service_search_remname_cback); + log::info("Assume command failed due to disconnection hci_status:{} peer:{}", + hci_error_code_text(p_remote_name->hci_status), p_remote_name->bd_addr); } else { - log::info( - "Ignored remote name response for the wrong address exp:{} act:{}", - bta_dm_search_cb.peer_bdaddr, p_remote_name->bd_addr); + log::info("Ignored remote name response for the wrong address exp:{} act:{}", + bta_dm_search_cb.peer_bdaddr, p_remote_name->bd_addr); return; } } @@ -1574,9 +1479,11 @@ const char* bta_dm_get_remname(void) { /* If the name isn't already stored, try retrieving from BTM */ if (*p_name == '\0') { - const char* p_temp = get_btm_client_interface().security.BTM_SecReadDevName( - bta_dm_search_cb.peer_bdaddr); - if (p_temp != NULL) p_name = (const char*)p_temp; + const char* p_temp = + get_btm_client_interface().security.BTM_SecReadDevName(bta_dm_search_cb.peer_bdaddr); + if (p_temp != NULL) { + p_name = (const char*)p_temp; + } } return p_name; @@ -1592,8 +1499,8 @@ const char* bta_dm_get_remname(void) { * Returns void * ******************************************************************************/ -static void bta_dm_observe_results_cb(tBTM_INQ_RESULTS* p_inq, - const uint8_t* p_eir, uint16_t eir_len) { +static void bta_dm_observe_results_cb(tBTM_INQ_RESULTS* p_inq, const uint8_t* p_eir, + uint16_t eir_len) { tBTA_DM_SEARCH result; tBTM_INQ_INFO* p_inq_info; log::verbose("bta_dm_observe_results_cb"); @@ -1616,8 +1523,7 @@ static void bta_dm_observe_results_cb(tBTM_INQ_RESULTS* p_inq, result.inq_res.p_eir = const_cast(p_eir); result.inq_res.eir_len = eir_len; - p_inq_info = - get_btm_client_interface().db.BTM_InqDbRead(p_inq->remote_bd_addr); + p_inq_info = get_btm_client_interface().db.BTM_InqDbRead(p_inq->remote_bd_addr); if (p_inq_info != NULL) { /* initialize remt_name_not_required to false so that we get the name by * default */ @@ -1627,8 +1533,9 @@ static void bta_dm_observe_results_cb(tBTM_INQ_RESULTS* p_inq, if (p_inq_info) { /* application indicates if it knows the remote name, inside the callback copy that to the inquiry data base*/ - if (result.inq_res.remt_name_not_required) + if (result.inq_res.remt_name_not_required) { p_inq_info->appl_knows_rem_name = true; + } } } @@ -1642,8 +1549,7 @@ static void bta_dm_observe_results_cb(tBTM_INQ_RESULTS* p_inq, * Returns void * ******************************************************************************/ -static void bta_dm_opportunistic_observe_results_cb(tBTM_INQ_RESULTS* p_inq, - const uint8_t* p_eir, +static void bta_dm_opportunistic_observe_results_cb(tBTM_INQ_RESULTS* p_inq, const uint8_t* p_eir, uint16_t eir_len) { tBTA_DM_SEARCH result; tBTM_INQ_INFO* p_inq_info; @@ -1665,22 +1571,23 @@ static void bta_dm_opportunistic_observe_results_cb(tBTM_INQ_RESULTS* p_inq, result.inq_res.p_eir = const_cast(p_eir); result.inq_res.eir_len = eir_len; - p_inq_info = - get_btm_client_interface().db.BTM_InqDbRead(p_inq->remote_bd_addr); + p_inq_info = get_btm_client_interface().db.BTM_InqDbRead(p_inq->remote_bd_addr); if (p_inq_info != NULL) { /* initialize remt_name_not_required to false so that we get the name by * default */ result.inq_res.remt_name_not_required = false; } - if (bta_dm_search_cb.p_csis_scan_cback) + if (bta_dm_search_cb.p_csis_scan_cback) { bta_dm_search_cb.p_csis_scan_cback(BTA_DM_INQ_RES_EVT, &result); + } if (p_inq_info) { /* application indicates if it knows the remote name, inside the callback copy that to the inquiry data base*/ - if (result.inq_res.remt_name_not_required) + if (result.inq_res.remt_name_not_required) { p_inq_info->appl_knows_rem_name = true; + } } } @@ -1704,11 +1611,9 @@ static void bta_dm_observe_cmpl_cb(void* p_result) { } } -static void bta_dm_start_scan(uint8_t duration_sec, - bool low_latency_scan = false) { +static void bta_dm_start_scan(uint8_t duration_sec, bool low_latency_scan = false) { tBTM_STATUS status = get_btm_client_interface().ble.BTM_BleObserve( - true, duration_sec, bta_dm_observe_results_cb, bta_dm_observe_cmpl_cb, - low_latency_scan); + true, duration_sec, bta_dm_observe_results_cb, bta_dm_observe_cmpl_cb, low_latency_scan); if (status != BTM_CMD_STARTED) { log::warn("BTM_BleObserve failed. status {}", status); @@ -1719,11 +1624,10 @@ static void bta_dm_start_scan(uint8_t duration_sec, } } -void bta_dm_ble_scan(bool start, uint8_t duration_sec, - bool low_latency_scan = false) { +void bta_dm_ble_scan(bool start, uint8_t duration_sec, bool low_latency_scan = false) { if (!start) { - if (get_btm_client_interface().ble.BTM_BleObserve( - false, 0, NULL, NULL, false) != BTM_CMD_STARTED) { + if (get_btm_client_interface().ble.BTM_BleObserve(false, 0, NULL, NULL, false) != + BTM_CMD_STARTED) { log::warn("Unable to stop ble observe"); } return; @@ -1764,25 +1668,23 @@ static void bta_dm_gattc_register(void) { return; } get_gatt_interface().BTA_GATTC_AppRegister( - bta_dm_gattc_callback, base::Bind([](uint8_t client_id, uint8_t status) { - tGATT_STATUS gatt_status = static_cast(status); - disc_gatt_history_.Push(base::StringPrintf( - "%-32s client_id:%hu status:%s", "GATTC_RegisteredCallback", - client_id, gatt_status_text(gatt_status).c_str())); - if (static_cast(status) == GATT_SUCCESS) { - log::info( - "Registered device discovery search gatt client tGATT_IF:{}", - client_id); - bta_dm_search_cb.client_if = client_id; - } else { - log::warn( - "Failed to register device discovery search gatt client " - "gatt_status:{} previous tGATT_IF:{}", - bta_dm_search_cb.client_if, status); - bta_dm_search_cb.client_if = BTA_GATTS_INVALID_IF; - } - }), - false); + bta_dm_gattc_callback, base::Bind([](uint8_t client_id, uint8_t status) { + tGATT_STATUS gatt_status = static_cast(status); + disc_gatt_history_.Push(base::StringPrintf("%-32s client_id:%hu status:%s", + "GATTC_RegisteredCallback", client_id, + gatt_status_text(gatt_status).c_str())); + if (static_cast(status) == GATT_SUCCESS) { + log::info("Registered device discovery search gatt client tGATT_IF:{}", client_id); + bta_dm_search_cb.client_if = client_id; + } else { + log::warn( + "Failed to register device discovery search gatt client " + "gatt_status:{} previous tGATT_IF:{}", + bta_dm_search_cb.client_if, status); + bta_dm_search_cb.client_if = BTA_GATTS_INVALID_IF; + } + }), + false); } static void gatt_close_timer_cb(void*) { @@ -1819,8 +1721,8 @@ static void bta_dm_gatt_disc_complete(uint16_t conn_id, tGATT_STATUS status) { // set to false. If property is true / unset there will be a delay if (bta_dm_search_cb.gatt_close_timer != nullptr) { /* start a GATT channel close delay timer */ - alarm_set_on_mloop(bta_dm_search_cb.gatt_close_timer, - BTA_DM_GATT_CLOSE_DELAY_TOUT, gatt_close_timer_cb, 0); + alarm_set_on_mloop(bta_dm_search_cb.gatt_close_timer, BTA_DM_GATT_CLOSE_DELAY_TOUT, + gatt_close_timer_cb, 0); } else { bta_dm_search_sm_execute(BTA_DM_DISC_CLOSE_TOUT_EVT, nullptr); } @@ -1845,8 +1747,9 @@ static void bta_dm_gatt_disc_complete(uint16_t conn_id, tGATT_STATUS status) { * ******************************************************************************/ static void bta_dm_close_gatt_conn() { - if (bta_dm_search_cb.conn_id != GATT_INVALID_CONN_ID) + if (bta_dm_search_cb.conn_id != GATT_INVALID_CONN_ID) { BTA_GATTC_Close(bta_dm_search_cb.conn_id); + } bta_dm_search_cb.pending_close_bda = RawAddress::kEmpty; bta_dm_search_cb.conn_id = GATT_INVALID_CONN_ID; @@ -1871,28 +1774,22 @@ static void btm_dm_start_gatt_discovery(const RawAddress& bd_addr) { bta_dm_search_cb.conn_id != GATT_INVALID_CONN_ID) { bta_dm_search_cb.pending_close_bda = RawAddress::kEmpty; alarm_cancel(bta_dm_search_cb.gatt_close_timer); - get_gatt_interface().BTA_GATTC_ServiceSearchRequest( - bta_dm_search_cb.conn_id, nullptr); + get_gatt_interface().BTA_GATTC_ServiceSearchRequest(bta_dm_search_cb.conn_id, nullptr); } else { - if (get_btm_client_interface().peer.BTM_IsAclConnectionUp( - bd_addr, BT_TRANSPORT_LE)) { + if (get_btm_client_interface().peer.BTM_IsAclConnectionUp(bd_addr, BT_TRANSPORT_LE)) { log::debug( - "Use existing gatt client connection for discovery peer:{} " - "transport:{} opportunistic:{:c}", - bd_addr, bt_transport_text(BT_TRANSPORT_LE), - (kUseOpportunistic) ? 'T' : 'F'); + "Use existing gatt client connection for discovery peer:{} " + "transport:{} opportunistic:{:c}", + bd_addr, bt_transport_text(BT_TRANSPORT_LE), (kUseOpportunistic) ? 'T' : 'F'); get_gatt_interface().BTA_GATTC_Open(bta_dm_search_cb.client_if, bd_addr, - BTM_BLE_DIRECT_CONNECTION, - kUseOpportunistic); + BTM_BLE_DIRECT_CONNECTION, kUseOpportunistic); } else { log::debug( - "Opening new gatt client connection for discovery peer:{} " - "transport:{} opportunistic:{:c}", - bd_addr, bt_transport_text(BT_TRANSPORT_LE), - (!kUseOpportunistic) ? 'T' : 'F'); + "Opening new gatt client connection for discovery peer:{} " + "transport:{} opportunistic:{:c}", + bd_addr, bt_transport_text(BT_TRANSPORT_LE), (!kUseOpportunistic) ? 'T' : 'F'); get_gatt_interface().BTA_GATTC_Open(bta_dm_search_cb.client_if, bd_addr, - BTM_BLE_DIRECT_CONNECTION, - !kUseOpportunistic); + BTM_BLE_DIRECT_CONNECTION, !kUseOpportunistic); } } } @@ -1908,23 +1805,20 @@ static void btm_dm_start_gatt_discovery(const RawAddress& bd_addr) { ******************************************************************************/ static void bta_dm_proc_open_evt(tBTA_GATTC_OPEN* p_data) { log::verbose("DM Search state= {} search_cb.peer_dbaddr:{} connected_bda={}", - bta_dm_search_get_state(), bta_dm_search_cb.peer_bdaddr, - p_data->remote_bda); + bta_dm_search_get_state(), bta_dm_search_cb.peer_bdaddr, p_data->remote_bda); - log::debug("BTA_GATTC_OPEN_EVT conn_id = {} client_if={} status = {}", - p_data->conn_id, p_data->client_if, p_data->status); + log::debug("BTA_GATTC_OPEN_EVT conn_id = {} client_if={} status = {}", p_data->conn_id, + p_data->client_if, p_data->status); disc_gatt_history_.Push(base::StringPrintf( - "%-32s bd_addr:%s conn_id:%hu client_if:%hu event:%s", - "GATTC_EventCallback", ADDRESS_TO_LOGGABLE_CSTR(p_data->remote_bda), - p_data->conn_id, p_data->client_if, - gatt_client_event_text(BTA_GATTC_OPEN_EVT).c_str())); + "%-32s bd_addr:%s conn_id:%hu client_if:%hu event:%s", "GATTC_EventCallback", + ADDRESS_TO_LOGGABLE_CSTR(p_data->remote_bda), p_data->conn_id, p_data->client_if, + gatt_client_event_text(BTA_GATTC_OPEN_EVT).c_str())); bta_dm_search_cb.conn_id = p_data->conn_id; if (p_data->status == GATT_SUCCESS) { - get_gatt_interface().BTA_GATTC_ServiceSearchRequest(p_data->conn_id, - nullptr); + get_gatt_interface().BTA_GATTC_ServiceSearchRequest(p_data->conn_id, nullptr); } else { bta_dm_gatt_disc_complete(GATT_INVALID_CONN_ID, p_data->status); } @@ -1954,14 +1848,12 @@ static void bta_dm_gattc_callback(tBTA_GATTC_EVT event, tBTA_GATTC* p_data) { case BTA_DM_SEARCH_ACTIVE: case BTA_DM_SEARCH_CANCELLING: case BTA_DM_DISCOVER_ACTIVE: - bta_dm_gatt_disc_complete(p_data->search_cmpl.conn_id, - p_data->search_cmpl.status); + bta_dm_gatt_disc_complete(p_data->search_cmpl.conn_id, p_data->search_cmpl.status); break; } disc_gatt_history_.Push(base::StringPrintf( - "%-32s conn_id:%hu status:%s", "GATTC_EventCallback", - p_data->search_cmpl.conn_id, - gatt_status_text(p_data->search_cmpl.status).c_str())); + "%-32s conn_id:%hu status:%s", "GATTC_EventCallback", p_data->search_cmpl.conn_id, + gatt_status_text(p_data->search_cmpl.status).c_str())); break; case BTA_GATTC_CLOSE_EVT: @@ -1980,8 +1872,7 @@ static void bta_dm_gattc_callback(tBTA_GATTC_EVT event, tBTA_GATTC* p_data) { case BTA_DM_DISCOVER_ACTIVE: /* in case of disconnect before search is completed */ if (p_data->close.remote_bda == bta_dm_search_cb.peer_bdaddr) { - bta_dm_gatt_disc_complete((uint16_t)GATT_INVALID_CONN_ID, - (tGATT_STATUS)GATT_ERROR); + bta_dm_gatt_disc_complete((uint16_t)GATT_INVALID_CONN_ID, (tGATT_STATUS)GATT_ERROR); } } break; @@ -1999,9 +1890,8 @@ static void bta_dm_gattc_callback(tBTA_GATTC_EVT event, tBTA_GATTC* p_data) { case BTA_GATTC_SRVC_CHG_EVT: case BTA_GATTC_SRVC_DISC_DONE_EVT: case BTA_GATTC_SUBRATE_CHG_EVT: - disc_gatt_history_.Push( - base::StringPrintf("%-32s event:%s", "GATTC_EventCallback", - gatt_client_event_text(event).c_str())); + disc_gatt_history_.Push(base::StringPrintf("%-32s event:%s", "GATTC_EventCallback", + gatt_client_event_text(event).c_str())); break; } } @@ -2040,9 +1930,8 @@ std::string EpochMillisToString(long long time_ms) { struct tm tm; localtime_r(&time_sec, &tm); std::string s = ::bluetooth::common::StringFormatTime(kTimeFormatString, tm); - return base::StringPrintf( - "%s.%03u", s.c_str(), - static_cast(time_ms % MillisPerSecond)); + return base::StringPrintf("%s.%03u", s.c_str(), + static_cast(time_ms % MillisPerSecond)); } } // namespace @@ -2051,14 +1940,13 @@ struct tSEARCH_STATE_HISTORY { const tBTA_DM_STATE state; const tBTA_DM_EVT event; std::string ToString() const { - return base::StringPrintf("state:%25s event:%s", - bta_dm_state_text(state).c_str(), + return base::StringPrintf("state:%25s event:%s", bta_dm_state_text(state).c_str(), bta_dm_event_text(event).c_str()); } }; -::bluetooth::common::TimestampedCircularBuffer - search_state_history_(kSearchStateHistorySize); +::bluetooth::common::TimestampedCircularBuffer search_state_history_( + kSearchStateHistorySize); /******************************************************************************* * @@ -2070,14 +1958,12 @@ struct tSEARCH_STATE_HISTORY { * Returns void * ******************************************************************************/ -static void bta_dm_search_sm_execute(tBTA_DM_EVT event, - std::unique_ptr msg) { - log::info("state:{}, event:{}[0x{:x}]", - bta_dm_state_text(bta_dm_search_get_state()), +static void bta_dm_search_sm_execute(tBTA_DM_EVT event, std::unique_ptr msg) { + log::info("state:{}, event:{}[0x{:x}]", bta_dm_state_text(bta_dm_search_get_state()), bta_dm_event_text(event), event); search_state_history_.Push({ - .state = bta_dm_search_get_state(), - .event = event, + .state = bta_dm_search_get_state(), + .event = event, }); switch (bta_dm_search_get_state()) { @@ -2085,8 +1971,8 @@ static void bta_dm_search_sm_execute(tBTA_DM_EVT event, switch (event) { case BTA_DM_API_SEARCH_EVT: bta_dm_search_set_state(BTA_DM_SEARCH_ACTIVE); - log::assert_that(std::holds_alternative(*msg), - "bad message type: {}", msg->index()); + log::assert_that(std::holds_alternative(*msg), "bad message type: {}", + msg->index()); bta_dm_search_start(std::get(*msg)); break; @@ -2108,9 +1994,8 @@ static void bta_dm_search_sm_execute(tBTA_DM_EVT event, bta_dm_close_gatt_conn(); break; default: - log::info("Received unexpected event {}[0x{:x}] in state {}", - bta_dm_event_text(event), event, - bta_dm_state_text(bta_dm_search_get_state())); + log::info("Received unexpected event {}[0x{:x}] in state {}", bta_dm_event_text(event), + event, bta_dm_state_text(bta_dm_search_get_state())); } break; case BTA_DM_SEARCH_ACTIVE: @@ -2125,8 +2010,8 @@ static void bta_dm_search_sm_execute(tBTA_DM_EVT event, bta_dm_search_cmpl(); break; case BTA_DM_DISCOVERY_RESULT_EVT: - log::assert_that(std::holds_alternative(*msg), - "bad message type: {}", msg->index()); + log::assert_that(std::holds_alternative(*msg), "bad message type: {}", + msg->index()); bta_dm_disc_result(std::get(*msg)); break; @@ -2145,16 +2030,15 @@ static void bta_dm_search_sm_execute(tBTA_DM_EVT event, bta_dm_search_cancel(); break; default: - log::info("Received unexpected event {}[0x{:x}] in state {}", - bta_dm_event_text(event), event, - bta_dm_state_text(bta_dm_search_get_state())); + log::info("Received unexpected event {}[0x{:x}] in state {}", bta_dm_event_text(event), + event, bta_dm_state_text(bta_dm_search_get_state())); } break; case BTA_DM_SEARCH_CANCELLING: switch (event) { case BTA_DM_API_SEARCH_EVT: - log::assert_that(std::holds_alternative(*msg), - "bad message type: {}", msg->index()); + log::assert_that(std::holds_alternative(*msg), "bad message type: {}", + msg->index()); bta_dm_queue_search(std::get(*msg)); break; @@ -2181,9 +2065,8 @@ static void bta_dm_search_sm_execute(tBTA_DM_EVT event, bta_dm_close_gatt_conn(); break; default: - log::info("Received unexpected event {}[0x{:x}] in state {}", - bta_dm_event_text(event), event, - bta_dm_state_text(bta_dm_search_get_state())); + log::info("Received unexpected event {}[0x{:x}] in state {}", bta_dm_event_text(event), + event, bta_dm_state_text(bta_dm_search_get_state())); } break; case BTA_DM_DISCOVER_ACTIVE: @@ -2195,8 +2078,8 @@ static void bta_dm_search_sm_execute(tBTA_DM_EVT event, bta_dm_remote_name_cmpl(std::get(*msg)); break; case BTA_DM_SDP_RESULT_EVT: - log::assert_that(std::holds_alternative(*msg), - "bad message type: {}", msg->index()); + log::assert_that(std::holds_alternative(*msg), "bad message type: {}", + msg->index()); bta_dm_sdp_result(std::get(*msg)); break; @@ -2204,14 +2087,14 @@ static void bta_dm_search_sm_execute(tBTA_DM_EVT event, bta_dm_search_cmpl(); break; case BTA_DM_DISCOVERY_RESULT_EVT: - log::assert_that(std::holds_alternative(*msg), - "bad message type: {}", msg->index()); + log::assert_that(std::holds_alternative(*msg), "bad message type: {}", + msg->index()); bta_dm_disc_result(std::get(*msg)); break; case BTA_DM_API_SEARCH_EVT: - log::assert_that(std::holds_alternative(*msg), - "bad message type: {}", msg->index()); + log::assert_that(std::holds_alternative(*msg), "bad message type: {}", + msg->index()); bta_dm_queue_search(std::get(*msg)); break; @@ -2230,9 +2113,8 @@ static void bta_dm_search_sm_execute(tBTA_DM_EVT event, bta_dm_close_gatt_conn(); break; default: - log::info("Received unexpected event {}[0x{:x}] in state {}", - bta_dm_event_text(event), event, - bta_dm_state_text(bta_dm_search_get_state())); + log::info("Received unexpected event {}[0x{:x}] in state {}", bta_dm_event_text(event), + event, bta_dm_state_text(bta_dm_search_get_state())); } break; } @@ -2257,15 +2139,14 @@ void bta_dm_disc_start(bool delay_close_gatt) { bta_dm_disc_reset(); bta_dm_search_cb.search_timer = alarm_new("bta_dm_search.search_timer"); bta_dm_search_cb.gatt_close_timer = - delay_close_gatt ? alarm_new("bta_dm_search.gatt_close_timer") : nullptr; + delay_close_gatt ? alarm_new("bta_dm_search.gatt_close_timer") : nullptr; bta_dm_search_cb.pending_discovery_queue = {}; } void bta_dm_disc_acl_down(const RawAddress& bd_addr, tBT_TRANSPORT transport) { switch (transport) { case BT_TRANSPORT_BR_EDR: - if (bta_dm_search_cb.wait_disc && - bta_dm_search_cb.peer_bdaddr == bd_addr) { + if (bta_dm_search_cb.wait_disc && bta_dm_search_cb.peer_bdaddr == bd_addr) { bta_dm_search_cb.wait_disc = false; if (bta_dm_search_cb.sdp_results) { @@ -2285,9 +2166,8 @@ void bta_dm_disc_acl_down(const RawAddress& bd_addr, tBT_TRANSPORT transport) { void bta_dm_disc_stop() { bta_dm_disc_reset(); } void bta_dm_disc_start_device_discovery(tBTA_DM_SEARCH_CBACK* p_cback) { - bta_dm_search_sm_execute( - BTA_DM_API_SEARCH_EVT, - std::make_unique(tBTA_DM_API_SEARCH{.p_cback = p_cback})); + bta_dm_search_sm_execute(BTA_DM_API_SEARCH_EVT, + std::make_unique(tBTA_DM_API_SEARCH{.p_cback = p_cback})); } void bta_dm_disc_stop_device_discovery() { @@ -2295,12 +2175,10 @@ void bta_dm_disc_stop_device_discovery() { } void bta_dm_disc_start_service_discovery(service_discovery_callbacks cbacks, - const RawAddress& bd_addr, - tBT_TRANSPORT transport) { - bta_dm_search_sm_execute( - BTA_DM_API_DISCOVER_EVT, - std::make_unique(tBTA_DM_API_DISCOVER{ - .bd_addr = bd_addr, .cbacks = cbacks, .transport = transport})); + const RawAddress& bd_addr, tBT_TRANSPORT transport) { + bta_dm_search_sm_execute(BTA_DM_API_DISCOVER_EVT, + std::make_unique(tBTA_DM_API_DISCOVER{ + .bd_addr = bd_addr, .cbacks = cbacks, .transport = transport})); } #define DUMPSYS_TAG "shim::legacy::bta::dm" @@ -2328,49 +2206,34 @@ tBTA_DM_SEARCH_CB bta_dm_disc_get_search_cb() { ::bta_dm_disc_legacy::bta_dm_disc_init_search_cb(search_cb); return search_cb; } -tBTA_DM_SEARCH_CB& bta_dm_disc_search_cb() { - return ::bta_dm_disc_legacy::bta_dm_search_cb; -} -bool bta_dm_read_remote_device_name(const RawAddress& bd_addr, - tBT_TRANSPORT transport) { - return ::bta_dm_disc_legacy::bta_dm_read_remote_device_name(bd_addr, - transport); -} -void bta_dm_discover_next_device() { - ::bta_dm_disc_legacy::bta_dm_discover_next_device(); +tBTA_DM_SEARCH_CB& bta_dm_disc_search_cb() { return ::bta_dm_disc_legacy::bta_dm_search_cb; } +bool bta_dm_read_remote_device_name(const RawAddress& bd_addr, tBT_TRANSPORT transport) { + return ::bta_dm_disc_legacy::bta_dm_read_remote_device_name(bd_addr, transport); } +void bta_dm_discover_next_device() { ::bta_dm_disc_legacy::bta_dm_discover_next_device(); } -void bta_dm_execute_queued_request() { - ::bta_dm_disc_legacy::bta_dm_execute_queued_request(); -} +void bta_dm_execute_queued_request() { ::bta_dm_disc_legacy::bta_dm_execute_queued_request(); } void bta_dm_find_services(const RawAddress& bd_addr) { ::bta_dm_disc_legacy::bta_dm_find_services(bd_addr); } void bta_dm_inq_cmpl() { ::bta_dm_disc_legacy::bta_dm_inq_cmpl(); } -void bta_dm_inq_cmpl_cb(void* p_result) { - ::bta_dm_disc_legacy::bta_dm_inq_cmpl_cb(p_result); -} +void bta_dm_inq_cmpl_cb(void* p_result) { ::bta_dm_disc_legacy::bta_dm_inq_cmpl_cb(p_result); } void bta_dm_observe_cmpl_cb(void* p_result) { ::bta_dm_disc_legacy::bta_dm_observe_cmpl_cb(p_result); } -void bta_dm_observe_results_cb(tBTM_INQ_RESULTS* p_inq, const uint8_t* p_eir, - uint16_t eir_len) { +void bta_dm_observe_results_cb(tBTM_INQ_RESULTS* p_inq, const uint8_t* p_eir, uint16_t eir_len) { ::bta_dm_disc_legacy::bta_dm_observe_results_cb(p_inq, p_eir, eir_len); } -void bta_dm_opportunistic_observe_results_cb(tBTM_INQ_RESULTS* p_inq, - const uint8_t* p_eir, +void bta_dm_opportunistic_observe_results_cb(tBTM_INQ_RESULTS* p_inq, const uint8_t* p_eir, uint16_t eir_len) { - ::bta_dm_disc_legacy::bta_dm_opportunistic_observe_results_cb(p_inq, p_eir, - eir_len); + ::bta_dm_disc_legacy::bta_dm_opportunistic_observe_results_cb(p_inq, p_eir, eir_len); } void bta_dm_queue_search(tBTA_DM_API_SEARCH& search) { ::bta_dm_disc_legacy::bta_dm_queue_search(search); } -void bta_dm_service_search_remname_cback(const RawAddress& bd_addr, - DEV_CLASS dc, BD_NAME bd_name) { - ::bta_dm_disc_legacy::bta_dm_service_search_remname_cback(bd_addr, dc, - bd_name); +void bta_dm_service_search_remname_cback(const RawAddress& bd_addr, DEV_CLASS dc, BD_NAME bd_name) { + ::bta_dm_disc_legacy::bta_dm_service_search_remname_cback(bd_addr, dc, bd_name); } void bta_dm_start_scan(uint8_t duration_sec, bool low_latency_scan = false) { diff --git a/system/bta/dm/bta_dm_disc_legacy.h b/system/bta/dm/bta_dm_disc_legacy.h index c6ae6eb57d0..33c4a1f58c6 100644 --- a/system/bta/dm/bta_dm_disc_legacy.h +++ b/system/bta/dm/bta_dm_disc_legacy.h @@ -35,8 +35,7 @@ void bta_dm_disc_stop_device_discovery(); // Bta service discovery start and stop entry points void bta_dm_disc_start_service_discovery(service_discovery_callbacks cbacks, - const RawAddress& bd_addr, - tBT_TRANSPORT transport); + const RawAddress& bd_addr, tBT_TRANSPORT transport); // Bta subsystem entrypoint and lifecycle void bta_dm_disc_disable_search_and_disc(); diff --git a/system/bta/dm/bta_dm_disc_sdp.cc b/system/bta/dm/bta_dm_disc_sdp.cc index 53e8d96b9cd..82fa8fa028e 100644 --- a/system/bta/dm/bta_dm_disc_sdp.cc +++ b/system/bta/dm/bta_dm_disc_sdp.cc @@ -50,36 +50,36 @@ using namespace bluetooth::legacy::stack::sdp; using namespace bluetooth; const uint16_t bta_service_id_to_uuid_lkup_tbl[BTA_MAX_SERVICE_ID] = { - UUID_SERVCLASS_PNP_INFORMATION, /* Reserved */ - UUID_SERVCLASS_SERIAL_PORT, /* BTA_SPP_SERVICE_ID */ - UUID_SERVCLASS_DIALUP_NETWORKING, /* BTA_DUN_SERVICE_ID */ - UUID_SERVCLASS_AUDIO_SOURCE, /* BTA_A2DP_SOURCE_SERVICE_ID */ - UUID_SERVCLASS_LAN_ACCESS_USING_PPP, /* BTA_LAP_SERVICE_ID */ - UUID_SERVCLASS_HEADSET, /* BTA_HSP_HS_SERVICE_ID */ - UUID_SERVCLASS_HF_HANDSFREE, /* BTA_HFP_HS_SERVICE_ID */ - UUID_SERVCLASS_OBEX_OBJECT_PUSH, /* BTA_OPP_SERVICE_ID */ - UUID_SERVCLASS_OBEX_FILE_TRANSFER, /* BTA_FTP_SERVICE_ID */ - UUID_SERVCLASS_CORDLESS_TELEPHONY, /* BTA_CTP_SERVICE_ID */ - UUID_SERVCLASS_INTERCOM, /* BTA_ICP_SERVICE_ID */ - UUID_SERVCLASS_IRMC_SYNC, /* BTA_SYNC_SERVICE_ID */ - UUID_SERVCLASS_DIRECT_PRINTING, /* BTA_BPP_SERVICE_ID */ - UUID_SERVCLASS_IMAGING_RESPONDER, /* BTA_BIP_SERVICE_ID */ - UUID_SERVCLASS_PANU, /* BTA_PANU_SERVICE_ID */ - UUID_SERVCLASS_NAP, /* BTA_NAP_SERVICE_ID */ - UUID_SERVCLASS_GN, /* BTA_GN_SERVICE_ID */ - UUID_SERVCLASS_SAP, /* BTA_SAP_SERVICE_ID */ - UUID_SERVCLASS_AUDIO_SINK, /* BTA_A2DP_SERVICE_ID */ - UUID_SERVCLASS_AV_REMOTE_CONTROL, /* BTA_AVRCP_SERVICE_ID */ - UUID_SERVCLASS_HUMAN_INTERFACE, /* BTA_HID_SERVICE_ID */ - UUID_SERVCLASS_VIDEO_SINK, /* BTA_VDP_SERVICE_ID */ - UUID_SERVCLASS_PBAP_PSE, /* BTA_PBAP_SERVICE_ID */ - UUID_SERVCLASS_HEADSET_AUDIO_GATEWAY, /* BTA_HSP_SERVICE_ID */ - UUID_SERVCLASS_AG_HANDSFREE, /* BTA_HFP_SERVICE_ID */ - UUID_SERVCLASS_MESSAGE_ACCESS, /* BTA_MAP_SERVICE_ID */ - UUID_SERVCLASS_MESSAGE_NOTIFICATION, /* BTA_MN_SERVICE_ID */ - UUID_SERVCLASS_HDP_PROFILE, /* BTA_HDP_SERVICE_ID */ - UUID_SERVCLASS_PBAP_PCE, /* BTA_PCE_SERVICE_ID */ - UUID_PROTOCOL_ATT /* BTA_GATT_SERVICE_ID */ + UUID_SERVCLASS_PNP_INFORMATION, /* Reserved */ + UUID_SERVCLASS_SERIAL_PORT, /* BTA_SPP_SERVICE_ID */ + UUID_SERVCLASS_DIALUP_NETWORKING, /* BTA_DUN_SERVICE_ID */ + UUID_SERVCLASS_AUDIO_SOURCE, /* BTA_A2DP_SOURCE_SERVICE_ID */ + UUID_SERVCLASS_LAN_ACCESS_USING_PPP, /* BTA_LAP_SERVICE_ID */ + UUID_SERVCLASS_HEADSET, /* BTA_HSP_HS_SERVICE_ID */ + UUID_SERVCLASS_HF_HANDSFREE, /* BTA_HFP_HS_SERVICE_ID */ + UUID_SERVCLASS_OBEX_OBJECT_PUSH, /* BTA_OPP_SERVICE_ID */ + UUID_SERVCLASS_OBEX_FILE_TRANSFER, /* BTA_FTP_SERVICE_ID */ + UUID_SERVCLASS_CORDLESS_TELEPHONY, /* BTA_CTP_SERVICE_ID */ + UUID_SERVCLASS_INTERCOM, /* BTA_ICP_SERVICE_ID */ + UUID_SERVCLASS_IRMC_SYNC, /* BTA_SYNC_SERVICE_ID */ + UUID_SERVCLASS_DIRECT_PRINTING, /* BTA_BPP_SERVICE_ID */ + UUID_SERVCLASS_IMAGING_RESPONDER, /* BTA_BIP_SERVICE_ID */ + UUID_SERVCLASS_PANU, /* BTA_PANU_SERVICE_ID */ + UUID_SERVCLASS_NAP, /* BTA_NAP_SERVICE_ID */ + UUID_SERVCLASS_GN, /* BTA_GN_SERVICE_ID */ + UUID_SERVCLASS_SAP, /* BTA_SAP_SERVICE_ID */ + UUID_SERVCLASS_AUDIO_SINK, /* BTA_A2DP_SERVICE_ID */ + UUID_SERVCLASS_AV_REMOTE_CONTROL, /* BTA_AVRCP_SERVICE_ID */ + UUID_SERVCLASS_HUMAN_INTERFACE, /* BTA_HID_SERVICE_ID */ + UUID_SERVCLASS_VIDEO_SINK, /* BTA_VDP_SERVICE_ID */ + UUID_SERVCLASS_PBAP_PSE, /* BTA_PBAP_SERVICE_ID */ + UUID_SERVCLASS_HEADSET_AUDIO_GATEWAY, /* BTA_HSP_SERVICE_ID */ + UUID_SERVCLASS_AG_HANDSFREE, /* BTA_HFP_SERVICE_ID */ + UUID_SERVCLASS_MESSAGE_ACCESS, /* BTA_MAP_SERVICE_ID */ + UUID_SERVCLASS_MESSAGE_NOTIFICATION, /* BTA_MN_SERVICE_ID */ + UUID_SERVCLASS_HDP_PROFILE, /* BTA_HDP_SERVICE_ID */ + UUID_SERVCLASS_PBAP_PCE, /* BTA_PCE_SERVICE_ID */ + UUID_PROTOCOL_ATT /* BTA_GATT_SERVICE_ID */ }; namespace { @@ -87,8 +87,7 @@ constexpr char kBtmLogTag[] = "SDP"; } static void store_avrcp_profile_feature(tSDP_DISC_REC* sdp_rec) { - tSDP_DISC_ATTR* p_attr = - get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( + tSDP_DISC_ATTR* p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( sdp_rec, ATTR_ID_SUPPORTED_FEATURES); if (p_attr == NULL) { return; @@ -100,8 +99,7 @@ static void store_avrcp_profile_feature(tSDP_DISC_REC* sdp_rec) { } if (btif_config_set_bin(sdp_rec->remote_bd_addr.ToString().c_str(), - BTIF_STORAGE_KEY_AV_REM_CTRL_FEATURES, - (const uint8_t*)&avrcp_features, + BTIF_STORAGE_KEY_AV_REM_CTRL_FEATURES, (const uint8_t*)&avrcp_features, sizeof(avrcp_features))) { log::info("Saving avrcp_features: 0x{:x}", avrcp_features); } else { @@ -119,38 +117,37 @@ static void bta_dm_store_audio_profiles_version(tSDP_DISCOVERY_DB* p_sdp_db) { }; std::array audio_profiles = {{ - { - .servclass_uuid = UUID_SERVCLASS_AV_REMOTE_CONTROL, - .btprofile_uuid = UUID_SERVCLASS_AV_REMOTE_CONTROL, - .profile_key = BTIF_STORAGE_KEY_AVRCP_CONTROLLER_VERSION, - .store_audio_profile_feature = store_avrcp_profile_feature, - }, + { + .servclass_uuid = UUID_SERVCLASS_AV_REMOTE_CONTROL, + .btprofile_uuid = UUID_SERVCLASS_AV_REMOTE_CONTROL, + .profile_key = BTIF_STORAGE_KEY_AVRCP_CONTROLLER_VERSION, + .store_audio_profile_feature = store_avrcp_profile_feature, + }, }}; for (const auto& audio_profile : audio_profiles) { tSDP_DISC_REC* sdp_rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb( - p_sdp_db, audio_profile.servclass_uuid, NULL); - if (sdp_rec == NULL) continue; + p_sdp_db, audio_profile.servclass_uuid, NULL); + if (sdp_rec == NULL) { + continue; + } if (get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - sdp_rec, ATTR_ID_BT_PROFILE_DESC_LIST) == NULL) + sdp_rec, ATTR_ID_BT_PROFILE_DESC_LIST) == NULL) { continue; + } uint16_t profile_version = 0; /* get profile version (if failure, version parameter is not updated) */ if (!get_legacy_stack_sdp_api()->record.SDP_FindProfileVersionInRec( - sdp_rec, audio_profile.btprofile_uuid, &profile_version)) { - log::warn("Unable to find SDP profile version in record peer:{}", - sdp_rec->remote_bd_addr); + sdp_rec, audio_profile.btprofile_uuid, &profile_version)) { + log::warn("Unable to find SDP profile version in record peer:{}", sdp_rec->remote_bd_addr); } if (profile_version != 0) { - if (btif_config_set_bin(sdp_rec->remote_bd_addr.ToString().c_str(), - audio_profile.profile_key, - (const uint8_t*)&profile_version, - sizeof(profile_version))) { + if (btif_config_set_bin(sdp_rec->remote_bd_addr.ToString().c_str(), audio_profile.profile_key, + (const uint8_t*)&profile_version, sizeof(profile_version))) { } else { - log::info("Failed to store peer profile version for {}", - sdp_rec->remote_bd_addr); + log::info("Failed to store peer profile version for {}", sdp_rec->remote_bd_addr); } } audio_profile.store_audio_profile_feature(sdp_rec); @@ -174,16 +171,15 @@ void bta_dm_sdp_result(tSDP_STATUS sdp_result, tBTA_DM_SDP_STATE* sdp_state) { do { p_sdp_rec = NULL; if (sdp_state->service_index == (BTA_USER_SERVICE_ID + 1)) { - if (p_sdp_rec && - get_legacy_stack_sdp_api()->record.SDP_FindProtocolListElemInRec( - p_sdp_rec, UUID_PROTOCOL_RFCOMM, &pe)) { + if (p_sdp_rec && get_legacy_stack_sdp_api()->record.SDP_FindProtocolListElemInRec( + p_sdp_rec, UUID_PROTOCOL_RFCOMM, &pe)) { sdp_state->peer_scn = (uint8_t)pe.params[0]; scn_found = true; } } else { service = bta_service_id_to_uuid_lkup_tbl[sdp_state->service_index - 1]; - p_sdp_rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb( - p_sdp_db, service, p_sdp_rec); + p_sdp_rec = + get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb(p_sdp_db, service, p_sdp_rec); } /* finished with BR/EDR services, now we check the result for GATT based * service UUID */ @@ -191,12 +187,11 @@ void bta_dm_sdp_result(tSDP_STATUS sdp_result, tBTA_DM_SDP_STATE* sdp_state) { /* all GATT based services */ do { /* find a service record, report it */ - p_sdp_rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb( - p_sdp_db, 0, p_sdp_rec); + p_sdp_rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb(p_sdp_db, 0, p_sdp_rec); if (p_sdp_rec) { Uuid service_uuid; - if (get_legacy_stack_sdp_api()->record.SDP_FindServiceUUIDInRec( - p_sdp_rec, &service_uuid)) { + if (get_legacy_stack_sdp_api()->record.SDP_FindServiceUUIDInRec(p_sdp_rec, + &service_uuid)) { gatt_uuids.push_back(service_uuid); } } @@ -208,10 +203,8 @@ void bta_dm_sdp_result(tSDP_STATUS sdp_result, tBTA_DM_SDP_STATE* sdp_state) { } else { if (p_sdp_rec != NULL && service != UUID_SERVCLASS_PNP_INFORMATION) { sdp_state->services_found |= - (tBTA_SERVICE_MASK)(BTA_SERVICE_ID_TO_SERVICE_MASK( - sdp_state->service_index - 1)); - uint16_t tmp_svc = - bta_service_id_to_uuid_lkup_tbl[sdp_state->service_index - 1]; + (tBTA_SERVICE_MASK)(BTA_SERVICE_ID_TO_SERVICE_MASK(sdp_state->service_index - 1)); + uint16_t tmp_svc = bta_service_id_to_uuid_lkup_tbl[sdp_state->service_index - 1]; /* Add to the list of UUIDs */ uuid_list.push_back(Uuid::From16Bit(tmp_svc)); } @@ -219,8 +212,9 @@ void bta_dm_sdp_result(tSDP_STATUS sdp_result, tBTA_DM_SDP_STATE* sdp_state) { if (sdp_state->services_to_search == 0) { sdp_state->service_index++; - } else /* regular one service per search or PNP search */ + } else { /* regular one service per search or PNP search */ break; + } } while (sdp_state->service_index <= BTA_MAX_SERVICE_ID); @@ -230,28 +224,26 @@ void bta_dm_sdp_result(tSDP_STATUS sdp_result, tBTA_DM_SDP_STATE* sdp_state) { p_sdp_rec = NULL; do { /* find a service record, report it */ - p_sdp_rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb_128bit( - p_sdp_db, p_sdp_rec); + p_sdp_rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb_128bit(p_sdp_db, p_sdp_rec); if (p_sdp_rec) { // SDP_FindServiceUUIDInRec_128bit is used only once, refactor? Uuid temp_uuid; - if (get_legacy_stack_sdp_api()->record.SDP_FindServiceUUIDInRec_128bit( - p_sdp_rec, &temp_uuid)) { + if (get_legacy_stack_sdp_api()->record.SDP_FindServiceUUIDInRec_128bit(p_sdp_rec, + &temp_uuid)) { uuid_list.push_back(temp_uuid); } } } while (p_sdp_rec); - if (bluetooth::common::init_flags:: - dynamic_avrcp_version_enhancement_is_enabled() && + if (bluetooth::common::init_flags::dynamic_avrcp_version_enhancement_is_enabled() && sdp_state->services_to_search == 0) { bta_dm_store_audio_profiles_version(p_sdp_db); } #if TARGET_FLOSS tSDP_DI_GET_RECORD di_record; - if (get_legacy_stack_sdp_api()->device_id.SDP_GetDiRecord( - 1, &di_record, p_sdp_db) == SDP_SUCCESS) { + if (get_legacy_stack_sdp_api()->device_id.SDP_GetDiRecord(1, &di_record, p_sdp_db) == + SDP_SUCCESS) { bta_dm_sdp_received_di(sdp_state->bd_addr, di_record); } #endif @@ -265,19 +257,16 @@ void bta_dm_sdp_result(tSDP_STATUS sdp_result, tBTA_DM_SDP_STATE* sdp_state) { /* callbacks */ /* start next bd_addr if necessary */ BTM_LogHistory(kBtmLogTag, sdp_state->bd_addr, "Discovery completed", - base::StringPrintf( - "Result:%s services_found:0x%x service_index:0x%d", - sdp_result_text(sdp_result).c_str(), - sdp_state->services_found, sdp_state->service_index)); + base::StringPrintf("Result:%s services_found:0x%x service_index:0x%d", + sdp_result_text(sdp_result).c_str(), + sdp_state->services_found, sdp_state->service_index)); // Copy the raw_data to the discovery result structure - if (p_sdp_db != NULL && p_sdp_db->raw_used != 0 && - p_sdp_db->raw_data != NULL) { - log::verbose("raw_data used = 0x{:x} raw_data_ptr = 0x{}", - p_sdp_db->raw_used, fmt::ptr(p_sdp_db->raw_data)); + if (p_sdp_db != NULL && p_sdp_db->raw_used != 0 && p_sdp_db->raw_data != NULL) { + log::verbose("raw_data used = 0x{:x} raw_data_ptr = 0x{}", p_sdp_db->raw_used, + fmt::ptr(p_sdp_db->raw_data)); - p_sdp_db->raw_data = - NULL; // no need to free this - it is a global assigned. + p_sdp_db->raw_data = NULL; // no need to free this - it is a global assigned. p_sdp_db->raw_used = 0; p_sdp_db->raw_size = 0; } else { @@ -287,17 +276,15 @@ void bta_dm_sdp_result(tSDP_STATUS sdp_result, tBTA_DM_SDP_STATE* sdp_state) { tBTA_STATUS result = BTA_SUCCESS; // Piggy back the SCN over result field if (scn_found) { - result = static_cast((3 + sdp_state->peer_scn)); + result = static_cast(3 + sdp_state->peer_scn); - log::verbose("Piggy back the SCN over result field SCN={}", - sdp_state->peer_scn); + log::verbose("Piggy back the SCN over result field SCN={}", sdp_state->peer_scn); } bta_dm_sdp_finished(sdp_state->bd_addr, result, uuid_list, gatt_uuids); } else { - BTM_LogHistory( - kBtmLogTag, sdp_state->bd_addr, "Discovery failed", - base::StringPrintf("Result:%s", sdp_result_text(sdp_result).c_str())); + BTM_LogHistory(kBtmLogTag, sdp_state->bd_addr, "Discovery failed", + base::StringPrintf("Result:%s", sdp_result_text(sdp_result).c_str())); log::error("SDP connection failed {}", sdp_status_text(sdp_result)); /* not able to connect go to next device */ @@ -317,8 +304,7 @@ void bta_dm_sdp_result(tSDP_STATUS sdp_result, tBTA_DM_SDP_STATE* sdp_state) { void bta_dm_sdp_find_services(tBTA_DM_SDP_STATE* sdp_state) { while (sdp_state->service_index < BTA_MAX_SERVICE_ID) { if (sdp_state->services_to_search & - (tBTA_SERVICE_MASK)(BTA_SERVICE_ID_TO_SERVICE_MASK( - sdp_state->service_index))) { + (tBTA_SERVICE_MASK)(BTA_SERVICE_ID_TO_SERVICE_MASK(sdp_state->service_index))) { break; } sdp_state->service_index++; @@ -345,10 +331,9 @@ void bta_dm_sdp_find_services(tBTA_DM_SDP_STATE* sdp_state) { tSDP_DISCOVERY_DB* p_sdp_db = (tSDP_DISCOVERY_DB*)sdp_state->sdp_db_buffer; log::info("search UUID = {}", uuid.ToString()); - if (!get_legacy_stack_sdp_api()->service.SDP_InitDiscoveryDb( - p_sdp_db, BTA_DM_SDP_DB_SIZE, 1, &uuid, 0, NULL)) { - log::warn("Unable to initialize SDP service discovery db peer:{}", - sdp_state->bd_addr); + if (!get_legacy_stack_sdp_api()->service.SDP_InitDiscoveryDb(p_sdp_db, BTA_DM_SDP_DB_SIZE, 1, + &uuid, 0, NULL)) { + log::warn("Unable to initialize SDP service discovery db peer:{}", sdp_state->bd_addr); } sdp_state->g_disc_raw_data_buf = {}; @@ -357,13 +342,12 @@ void bta_dm_sdp_find_services(tBTA_DM_SDP_STATE* sdp_state) { p_sdp_db->raw_size = MAX_DISC_RAW_DATA_BUF; if (!get_legacy_stack_sdp_api()->service.SDP_ServiceSearchAttributeRequest( - sdp_state->bd_addr, p_sdp_db, &bta_dm_sdp_callback)) { + sdp_state->bd_addr, p_sdp_db, &bta_dm_sdp_callback)) { /* * If discovery is not successful with this device, then * proceed with the next one. */ - log::warn("Unable to start SDP service search attribute request peer:{}", - sdp_state->bd_addr); + log::warn("Unable to start SDP service search attribute request peer:{}", sdp_state->bd_addr); sdp_state->service_index = BTA_MAX_SERVICE_ID; bta_dm_sdp_finished(sdp_state->bd_addr, BTA_SUCCESS); @@ -373,8 +357,7 @@ void bta_dm_sdp_find_services(tBTA_DM_SDP_STATE* sdp_state) { if (uuid == Uuid::From16Bit(UUID_PROTOCOL_L2CAP)) { if (!is_sdp_pbap_pce_disabled(sdp_state->bd_addr)) { log::debug("SDP search for PBAP Client"); - BTA_SdpSearch(sdp_state->bd_addr, - Uuid::From16Bit(UUID_SERVCLASS_PBAP_PCE)); + BTA_SdpSearch(sdp_state->bd_addr, Uuid::From16Bit(UUID_SERVCLASS_PBAP_PCE)); } } sdp_state->service_index++; @@ -388,9 +371,7 @@ void bta_dm_sdp_find_services(tBTA_DM_SDP_STATE* sdp_state) { ::bta_dm_sdp_find_services(sdp_state); } -void store_avrcp_profile_feature(tSDP_DISC_REC* sdp_rec) { - ::store_avrcp_profile_feature(sdp_rec); -} +void store_avrcp_profile_feature(tSDP_DISC_REC* sdp_rec) { ::store_avrcp_profile_feature(sdp_rec); } } // namespace testing } // namespace legacy diff --git a/system/bta/dm/bta_dm_gatt_client.cc b/system/bta/dm/bta_dm_gatt_client.cc index 5fa028ceb90..1de70b5fa14 100644 --- a/system/bta/dm/bta_dm_gatt_client.cc +++ b/system/bta/dm/bta_dm_gatt_client.cc @@ -39,86 +39,80 @@ std::string EpochMillisToString(long long time_ms) { struct tm tm; localtime_r(&time_sec, &tm); std::string s = bluetooth::common::StringFormatTime(kTimeFormatString, tm); - return base::StringPrintf( - "%s.%03u", s.c_str(), - static_cast(time_ms % MillisPerSecond)); + return base::StringPrintf("%s.%03u", s.c_str(), + static_cast(time_ms % MillisPerSecond)); } } // namespace gatt_interface_t default_gatt_interface = { - .BTA_GATTC_CancelOpen = - [](tGATT_IF client_if, const RawAddress& remote_bda, bool is_direct) { - gatt_history_.Push(base::StringPrintf( - "%-32s bd_addr:%s client_if:%hu is_direct:%c", "GATTC_CancelOpen", - ADDRESS_TO_LOGGABLE_CSTR(remote_bda), client_if, - (is_direct) ? 'T' : 'F')); - BTA_GATTC_CancelOpen(client_if, remote_bda, is_direct); - }, - .BTA_GATTC_Refresh = - [](const RawAddress& remote_bda) { - gatt_history_.Push( - base::StringPrintf("%-32s bd_addr:%s", "GATTC_Refresh", - ADDRESS_TO_LOGGABLE_CSTR(remote_bda))); - BTA_GATTC_Refresh(remote_bda); - }, - .BTA_GATTC_GetGattDb = - [](uint16_t conn_id, uint16_t start_handle, uint16_t end_handle, - btgatt_db_element_t** db, int* count) { - gatt_history_.Push(base::StringPrintf( - "%-32s conn_id:%hu start_handle:%hu end:handle:%hu", - "GATTC_GetGattDb", conn_id, start_handle, end_handle)); - BTA_GATTC_GetGattDb(conn_id, start_handle, end_handle, db, count); - }, - .BTA_GATTC_AppRegister = - [](tBTA_GATTC_CBACK* p_client_cb, BtaAppRegisterCallback cb, - bool eatt_support) { - gatt_history_.Push(base::StringPrintf("%-32s eatt_support:%c", - "GATTC_AppRegister", - (eatt_support) ? 'T' : 'F')); - BTA_GATTC_AppRegister(p_client_cb, cb, eatt_support); - }, - .BTA_GATTC_Close = - [](uint16_t conn_id) { - gatt_history_.Push( - base::StringPrintf("%-32s conn_id:%hu", "GATTC_Close", conn_id)); - BTA_GATTC_Close(conn_id); - }, - .BTA_GATTC_ServiceSearchRequest = - [](uint16_t conn_id, const bluetooth::Uuid* p_srvc_uuid) { - gatt_history_.Push(base::StringPrintf( - "%-32s conn_id:%hu", "GATTC_ServiceSearchRequest", conn_id)); - if (p_srvc_uuid) { - BTA_GATTC_ServiceSearchRequest(conn_id, *p_srvc_uuid); - } else { - BTA_GATTC_ServiceSearchAllRequest(conn_id); - } - }, - .BTA_GATTC_Open = - [](tGATT_IF client_if, const RawAddress& remote_bda, - tBTM_BLE_CONN_TYPE connection_type, bool opportunistic) { - gatt_history_.Push(base::StringPrintf( - "%-32s bd_addr:%s client_if:%hu type:0x%x opportunistic:%c", - "GATTC_Open", ADDRESS_TO_LOGGABLE_CSTR(remote_bda), client_if, - connection_type, (opportunistic) ? 'T' : 'F')); - BTA_GATTC_Open(client_if, remote_bda, connection_type, opportunistic); - }, + .BTA_GATTC_CancelOpen = + [](tGATT_IF client_if, const RawAddress& remote_bda, bool is_direct) { + gatt_history_.Push(base::StringPrintf( + "%-32s bd_addr:%s client_if:%hu is_direct:%c", "GATTC_CancelOpen", + ADDRESS_TO_LOGGABLE_CSTR(remote_bda), client_if, + (is_direct) ? 'T' : 'F')); + BTA_GATTC_CancelOpen(client_if, remote_bda, is_direct); + }, + .BTA_GATTC_Refresh = + [](const RawAddress& remote_bda) { + gatt_history_.Push(base::StringPrintf("%-32s bd_addr:%s", "GATTC_Refresh", + ADDRESS_TO_LOGGABLE_CSTR(remote_bda))); + BTA_GATTC_Refresh(remote_bda); + }, + .BTA_GATTC_GetGattDb = + [](uint16_t conn_id, uint16_t start_handle, uint16_t end_handle, + btgatt_db_element_t** db, int* count) { + gatt_history_.Push( + base::StringPrintf("%-32s conn_id:%hu start_handle:%hu end:handle:%hu", + "GATTC_GetGattDb", conn_id, start_handle, end_handle)); + BTA_GATTC_GetGattDb(conn_id, start_handle, end_handle, db, count); + }, + .BTA_GATTC_AppRegister = + [](tBTA_GATTC_CBACK* p_client_cb, BtaAppRegisterCallback cb, bool eatt_support) { + gatt_history_.Push(base::StringPrintf("%-32s eatt_support:%c", + "GATTC_AppRegister", + (eatt_support) ? 'T' : 'F')); + BTA_GATTC_AppRegister(p_client_cb, cb, eatt_support); + }, + .BTA_GATTC_Close = + [](uint16_t conn_id) { + gatt_history_.Push( + base::StringPrintf("%-32s conn_id:%hu", "GATTC_Close", conn_id)); + BTA_GATTC_Close(conn_id); + }, + .BTA_GATTC_ServiceSearchRequest = + [](uint16_t conn_id, const bluetooth::Uuid* p_srvc_uuid) { + gatt_history_.Push(base::StringPrintf("%-32s conn_id:%hu", + "GATTC_ServiceSearchRequest", conn_id)); + if (p_srvc_uuid) { + BTA_GATTC_ServiceSearchRequest(conn_id, *p_srvc_uuid); + } else { + BTA_GATTC_ServiceSearchAllRequest(conn_id); + } + }, + .BTA_GATTC_Open = + [](tGATT_IF client_if, const RawAddress& remote_bda, + tBTM_BLE_CONN_TYPE connection_type, bool opportunistic) { + gatt_history_.Push(base::StringPrintf( + "%-32s bd_addr:%s client_if:%hu type:0x%x opportunistic:%c", "GATTC_Open", + ADDRESS_TO_LOGGABLE_CSTR(remote_bda), client_if, connection_type, + (opportunistic) ? 'T' : 'F')); + BTA_GATTC_Open(client_if, remote_bda, connection_type, opportunistic); + }, }; gatt_interface_t* gatt_interface = &default_gatt_interface; gatt_interface_t& get_gatt_interface() { return *gatt_interface; } -void gatt_history_callback(const std::string& entry) { - gatt_history_.Push(entry); -} +void gatt_history_callback(const std::string& entry) { gatt_history_.Push(entry); } #define DUMPSYS_TAG "shim::legacy::bta::dm" void DumpsysBtaDmGattClient(int fd) { auto gatt_history = gatt_history_.Pull(); LOG_DUMPSYS(fd, " last %zu gatt history entries", gatt_history.size()); for (const auto& it : gatt_history) { - LOG_DUMPSYS(fd, " %s %s", EpochMillisToString(it.timestamp).c_str(), - it.entry.c_str()); + LOG_DUMPSYS(fd, " %s %s", EpochMillisToString(it.timestamp).c_str(), it.entry.c_str()); } } #undef DUMPSYS_TAG @@ -131,8 +125,7 @@ namespace bluetooth { namespace legacy { namespace testing { -std::vector> -PullCopyOfGattHistory() { +std::vector> PullCopyOfGattHistory() { return gatt_history_.Pull(); } diff --git a/system/bta/dm/bta_dm_gatt_client.h b/system/bta/dm/bta_dm_gatt_client.h index 4113b7d828b..6cb764a3e0e 100644 --- a/system/bta/dm/bta_dm_gatt_client.h +++ b/system/bta/dm/bta_dm_gatt_client.h @@ -28,20 +28,16 @@ // Interface as a GATT client for bta clients // struct gatt_interface_t { - void (*BTA_GATTC_CancelOpen)(tGATT_IF client_if, const RawAddress& remote_bda, - bool is_direct); + void (*BTA_GATTC_CancelOpen)(tGATT_IF client_if, const RawAddress& remote_bda, bool is_direct); void (*BTA_GATTC_Refresh)(const RawAddress& remote_bda); - void (*BTA_GATTC_GetGattDb)(uint16_t conn_id, uint16_t start_handle, - uint16_t end_handle, btgatt_db_element_t** db, - int* count); - void (*BTA_GATTC_AppRegister)(tBTA_GATTC_CBACK* p_client_cb, - BtaAppRegisterCallback cb, bool eatt_support); + void (*BTA_GATTC_GetGattDb)(uint16_t conn_id, uint16_t start_handle, uint16_t end_handle, + btgatt_db_element_t** db, int* count); + void (*BTA_GATTC_AppRegister)(tBTA_GATTC_CBACK* p_client_cb, BtaAppRegisterCallback cb, + bool eatt_support); void (*BTA_GATTC_Close)(uint16_t conn_id); - void (*BTA_GATTC_ServiceSearchRequest)(uint16_t conn_id, - const bluetooth::Uuid* p_srvc_uuid); + void (*BTA_GATTC_ServiceSearchRequest)(uint16_t conn_id, const bluetooth::Uuid* p_srvc_uuid); void (*BTA_GATTC_Open)(tGATT_IF client_if, const RawAddress& remote_bda, - tBTM_BLE_CONN_TYPE connection_type, - bool opportunistic); + tBTM_BLE_CONN_TYPE connection_type, bool opportunistic); }; // diff --git a/system/bta/dm/bta_dm_int.h b/system/bta/dm/bta_dm_int.h index ce2ab3c1313..86ff2aa860a 100644 --- a/system/bta/dm/bta_dm_int.h +++ b/system/bta/dm/bta_dm_int.h @@ -67,22 +67,24 @@ typedef enum : uint8_t { enter sniff mode */ BTA_DM_DI_ACP_SNIFF = 0x04, /* set this bit if peer init sniff */ BTA_DM_DI_UNUSED = 0x08, - BTA_DM_DI_USE_SSR = 0x10, /* set this bit if ssr is supported for this link */ + BTA_DM_DI_USE_SSR = 0x10, /* set this bit if ssr is supported for this link */ BTA_DM_DI_AV_ACTIVE = 0x20, /* set this bit if AV is active for this link */ } tBTA_DM_DEV_INFO_BITMASK; typedef uint8_t tBTA_DM_DEV_INFO; inline std::string device_info_text(tBTA_DM_DEV_INFO info) { const char* const device_info_text[] = { - ":set_sniff", ":int_sniff", ":acp_sniff", - ":unused", ":use_ssr", ":av_active", + ":set_sniff", ":int_sniff", ":acp_sniff", ":unused", ":use_ssr", ":av_active", }; std::string s = base::StringPrintf("0x%02x", info); - if (info == BTA_DM_DI_NONE) return s + std::string(":none"); - for (size_t i = 0; i < sizeof(device_info_text) / sizeof(device_info_text[0]); - i++) { - if (info & (1u << i)) s += std::string(device_info_text[i]); + if (info == BTA_DM_DI_NONE) { + return s + std::string(":none"); + } + for (size_t i = 0; i < sizeof(device_info_text) / sizeof(device_info_text[0]); i++) { + if (info & (1u << i)) { + s += std::string(device_info_text[i]); + } } return s; } @@ -99,11 +101,11 @@ struct tBTA_DM_PEER_DEVICE { tBTA_PREF_ROLES pref_role; bool in_use; - private: +private: // Dynamic pieces of operational device information tBTA_DM_DEV_INFO info{BTA_DM_DI_NONE}; - public: +public: std::string info_text() const { return device_info_text(info); } void reset_device_info() { info = BTA_DM_DI_NONE; } @@ -156,11 +158,10 @@ typedef struct { bool new_request; std::string ToString() const { - return base::StringPrintf( - "peer:%s sys_name:%s app_id:%hhu state:%s new_request:%s", - ADDRESS_TO_LOGGABLE_CSTR(peer_bdaddr), BtaIdSysText(id).c_str(), app_id, - bta_sys_conn_status_text(state).c_str(), - new_request ? "true" : "false"); + return base::StringPrintf("peer:%s sys_name:%s app_id:%hhu state:%s new_request:%s", + ADDRESS_TO_LOGGABLE_CSTR(peer_bdaddr), BtaIdSysText(id).c_str(), + app_id, bta_sys_conn_status_text(state).c_str(), + new_request ? "true" : "false"); } } tBTA_DM_SRVCS; @@ -210,7 +211,7 @@ typedef struct { alarm_t* disable_timer; uint8_t pm_id; tBTA_PM_TIMER pm_timer[BTA_DM_NUM_PM_TIMER]; - uint8_t cur_av_count; /* current AV connecions */ + uint8_t cur_av_count; /* current AV connections */ /* store UUID list for EIR */ uint32_t eir_uuid[BTM_EIR_SERVICE_ARRAY_SIZE]; @@ -229,8 +230,8 @@ typedef struct { typedef struct { uint16_t page_timeout; /* timeout for page in slots */ - bool avoid_scatter; /* true to avoid scatternet when av is streaming (be the - central) */ + bool avoid_scatter; /* true to avoid scatternet when av is streaming (be the + central) */ } tBTA_DM_CFG; @@ -261,7 +262,7 @@ typedef struct { typedef struct { uint8_t allow_mask; /* mask of sniff/hold/park modes to allow */ - uint8_t ssr; /* set SSR on conn open/unpark */ + uint8_t ssr; /* set SSR on conn open/unpark */ tBTA_DM_PM_ACTN actn_tbl[BTA_DM_PM_NUM_EVTS][2]; } tBTA_DM_PM_SPEC; @@ -311,10 +312,9 @@ void bta_dm_enable(tBTA_DM_SEC_CBACK*, tBTA_DM_ACL_CBACK*); void bta_dm_disable(); void bta_dm_set_dev_name(const std::vector&); -void bta_dm_ble_set_conn_params(const RawAddress&, uint16_t, uint16_t, uint16_t, - uint16_t); -void bta_dm_ble_update_conn_params(const RawAddress&, uint16_t, uint16_t, - uint16_t, uint16_t, uint16_t, uint16_t); +void bta_dm_ble_set_conn_params(const RawAddress&, uint16_t, uint16_t, uint16_t, uint16_t); +void bta_dm_ble_update_conn_params(const RawAddress&, uint16_t, uint16_t, uint16_t, uint16_t, + uint16_t, uint16_t); void bta_dm_ble_set_data_length(const RawAddress& bd_addr); @@ -332,22 +332,20 @@ void bta_dm_clear_filter_accept_list(void); void bta_dm_disconnect_all_acls(void); void bta_dm_le_rand(bluetooth::hci::LeRandCallback cb); void bta_dm_set_event_filter_connection_setup_all_devices(); -void bta_dm_allow_wake_by_hid( - std::vector classic_hid_devices, - std::vector> le_hid_devices); -void bta_dm_restore_filter_accept_list( - std::vector> le_devices); +void bta_dm_allow_wake_by_hid(std::vector classic_hid_devices, + std::vector> le_hid_devices); +void bta_dm_restore_filter_accept_list(std::vector> le_devices); void bta_dm_set_default_event_mask_except(uint64_t mask, uint64_t le_mask); void bta_dm_set_event_filter_inquiry_result_all_devices(); void bta_dm_ble_reset_id(void); void bta_dm_eir_update_uuid(uint16_t uuid16, bool adding); -void bta_dm_eir_update_cust_uuid(const tBTA_CUSTOM_UUID &curr, bool adding); +void bta_dm_eir_update_cust_uuid(const tBTA_CUSTOM_UUID& curr, bool adding); void bta_dm_ble_subrate_request(const RawAddress& bd_addr, uint16_t subrate_min, - uint16_t subrate_max, uint16_t max_latency, - uint16_t cont_num, uint16_t timeout); + uint16_t subrate_max, uint16_t max_latency, uint16_t cont_num, + uint16_t timeout); namespace fmt { template <> diff --git a/system/bta/dm/bta_dm_pm.cc b/system/bta/dm/bta_dm_pm.cc index c0030491c04..72cc580a160 100644 --- a/system/bta/dm/bta_dm_pm.cc +++ b/system/bta/dm/bta_dm_pm.cc @@ -48,26 +48,21 @@ using namespace bluetooth; -static void bta_dm_pm_cback(tBTA_SYS_CONN_STATUS status, const tBTA_SYS_ID id, - uint8_t app_id, const RawAddress& peer_addr); -static void bta_dm_pm_set_mode(const RawAddress& peer_addr, - tBTA_DM_PM_ACTION pm_mode, +static void bta_dm_pm_cback(tBTA_SYS_CONN_STATUS status, const tBTA_SYS_ID id, uint8_t app_id, + const RawAddress& peer_addr); +static void bta_dm_pm_set_mode(const RawAddress& peer_addr, tBTA_DM_PM_ACTION pm_mode, tBTA_DM_PM_REQ pm_req); static void bta_dm_pm_timer_cback(void* data); -static void bta_dm_pm_btm_cback(const RawAddress& bd_addr, - tBTM_PM_STATUS status, uint16_t value, +static void bta_dm_pm_btm_cback(const RawAddress& bd_addr, tBTM_PM_STATUS status, uint16_t value, tHCI_STATUS hci_status); static bool bta_dm_pm_park(const RawAddress& peer_addr); static void bta_dm_pm_sniff(tBTA_DM_PEER_DEVICE* p_peer_dev, uint8_t index); -static void bta_dm_sniff_cback(uint8_t id, uint8_t app_id, - const RawAddress& peer_addr); +static void bta_dm_sniff_cback(uint8_t id, uint8_t app_id, const RawAddress& peer_addr); static int bta_dm_get_sco_index(); -static void bta_dm_pm_stop_timer_by_index(tBTA_PM_TIMER* p_timer, - uint8_t timer_idx); +static void bta_dm_pm_stop_timer_by_index(tBTA_PM_TIMER* p_timer, uint8_t timer_idx); static tBTM_PM_PWR_MD get_sniff_entry(uint8_t index); -static void bta_dm_pm_timer(const RawAddress& bd_addr, - tBTA_DM_PM_ACTION pm_request); +static void bta_dm_pm_timer(const RawAddress& bd_addr, tBTA_DM_PM_ACTION pm_request); #include "../hh/bta_hh_int.h" /* BTA_DM_PM_SSR1 will be dedicated for HH SSR setting entry, no other profile @@ -80,14 +75,10 @@ static std::recursive_mutex pm_timer_schedule_mutex; static std::recursive_mutex pm_timer_state_mutex; /* Sysprop paths for sniff parameters */ -static const char kPropertySniffMaxIntervals[] = - "bluetooth.core.classic.sniff_max_intervals"; -static const char kPropertySniffMinIntervals[] = - "bluetooth.core.classic.sniff_min_intervals"; -static const char kPropertySniffAttempts[] = - "bluetooth.core.classic.sniff_attempts"; -static const char kPropertySniffTimeouts[] = - "bluetooth.core.classic.sniff_timeouts"; +static const char kPropertySniffMaxIntervals[] = "bluetooth.core.classic.sniff_max_intervals"; +static const char kPropertySniffMinIntervals[] = "bluetooth.core.classic.sniff_min_intervals"; +static const char kPropertySniffAttempts[] = "bluetooth.core.classic.sniff_attempts"; +static const char kPropertySniffTimeouts[] = "bluetooth.core.classic.sniff_timeouts"; /******************************************************************************* * @@ -107,17 +98,17 @@ void bta_dm_init_pm(void) { bta_sys_pm_register(bta_dm_pm_cback); bta_sys_sniff_register(bta_dm_sniff_cback); - if (get_btm_client_interface().lifecycle.BTM_PmRegister( - (BTM_PM_REG_SET), &bta_dm_cb.pm_id, bta_dm_pm_btm_cback) != - BTM_SUCCESS) { + if (get_btm_client_interface().lifecycle.BTM_PmRegister((BTM_PM_REG_SET), &bta_dm_cb.pm_id, + bta_dm_pm_btm_cback) != BTM_SUCCESS) { log::warn("Unable to initialize BTM power manager"); }; } /* Need to initialize all PM timer service IDs */ for (int i = 0; i < BTA_DM_NUM_PM_TIMER; i++) { - for (int j = 0; j < BTA_DM_PM_MODE_TIMER_MAX; j++) + for (int j = 0; j < BTA_DM_PM_MODE_TIMER_MAX; j++) { bta_dm_cb.pm_timer[i].srvc_id[j] = BTA_ID_MAX; + } } } @@ -132,8 +123,8 @@ void bta_dm_init_pm(void) { * ******************************************************************************/ void bta_dm_disable_pm(void) { - if (get_btm_client_interface().lifecycle.BTM_PmRegister( - BTM_PM_DEREG, &bta_dm_cb.pm_id, bta_dm_pm_btm_cback) != BTM_SUCCESS) { + if (get_btm_client_interface().lifecycle.BTM_PmRegister(BTM_PM_DEREG, &bta_dm_cb.pm_id, + bta_dm_pm_btm_cback) != BTM_SUCCESS) { log::warn("Unable to terminate BTM power manager"); } @@ -165,7 +156,9 @@ void bta_dm_disable_pm(void) { uint8_t bta_dm_get_av_count(void) { uint8_t count = 0; for (int i = 0; i < bta_dm_conn_srvcs.count; i++) { - if (bta_dm_conn_srvcs.conn_srvc[i].id == BTA_ID_AV) ++count; + if (bta_dm_conn_srvcs.conn_srvc[i].id == BTA_ID_AV) { + ++count; + } } return count; } @@ -184,8 +177,7 @@ static void bta_dm_pm_stop_timer(const RawAddress& peer_addr) { log::verbose(""); for (int i = 0; i < BTA_DM_NUM_PM_TIMER; i++) { - if (bta_dm_cb.pm_timer[i].in_use && - bta_dm_cb.pm_timer[i].peer_bdaddr == peer_addr) { + if (bta_dm_cb.pm_timer[i].in_use && bta_dm_cb.pm_timer[i].peer_bdaddr == peer_addr) { for (int j = 0; j < BTA_DM_PM_MODE_TIMER_MAX; j++) { bta_dm_pm_stop_timer_by_index(&bta_dm_cb.pm_timer[i], j); /* @@ -216,12 +208,13 @@ static void bta_dm_pm_stop_timer(const RawAddress& peer_addr) { * ******************************************************************************/ static uint8_t bta_pm_action_to_timer_idx(uint8_t pm_action) { - if (pm_action == BTA_DM_PM_SUSPEND) + if (pm_action == BTA_DM_PM_SUSPEND) { return BTA_DM_PM_SUSPEND_TIMER_IDX; - else if (pm_action == BTA_DM_PM_PARK) + } else if (pm_action == BTA_DM_PM_PARK) { return BTA_DM_PM_PARK_TIMER_IDX; - else if ((pm_action & BTA_DM_PM_SNIFF) == BTA_DM_PM_SNIFF) + } else if ((pm_action & BTA_DM_PM_SNIFF) == BTA_DM_PM_SNIFF) { return BTA_DM_PM_SNIFF_TIMER_IDX; + } /* Active, no preference, no action and retry */ return BTA_DM_PM_MODE_TIMER_MAX; @@ -237,14 +230,14 @@ static uint8_t bta_pm_action_to_timer_idx(uint8_t pm_action) { * Returns void * ******************************************************************************/ -static void bta_dm_pm_stop_timer_by_mode(const RawAddress& peer_addr, - uint8_t power_mode) { +static void bta_dm_pm_stop_timer_by_mode(const RawAddress& peer_addr, uint8_t power_mode) { const uint8_t timer_idx = bta_pm_action_to_timer_idx(power_mode); - if (timer_idx == BTA_DM_PM_MODE_TIMER_MAX) return; + if (timer_idx == BTA_DM_PM_MODE_TIMER_MAX) { + return; + } for (int i = 0; i < BTA_DM_NUM_PM_TIMER; i++) { - if (bta_dm_cb.pm_timer[i].in_use && - bta_dm_cb.pm_timer[i].peer_bdaddr == peer_addr) { + if (bta_dm_cb.pm_timer[i].in_use && bta_dm_cb.pm_timer[i].peer_bdaddr == peer_addr) { if (bta_dm_cb.pm_timer[i].srvc_id[timer_idx] != BTA_ID_MAX) { bta_dm_pm_stop_timer_by_index(&bta_dm_cb.pm_timer[i], timer_idx); /* @@ -270,11 +263,9 @@ static void bta_dm_pm_stop_timer_by_mode(const RawAddress& peer_addr, * Returns index of the power mode delay timer * ******************************************************************************/ -static void bta_dm_pm_stop_timer_by_srvc_id(const RawAddress& peer_addr, - uint8_t srvc_id) { +static void bta_dm_pm_stop_timer_by_srvc_id(const RawAddress& peer_addr, uint8_t srvc_id) { for (int i = 0; i < BTA_DM_NUM_PM_TIMER; i++) { - if (bta_dm_cb.pm_timer[i].in_use && - bta_dm_cb.pm_timer[i].peer_bdaddr == peer_addr) { + if (bta_dm_cb.pm_timer[i].in_use && bta_dm_cb.pm_timer[i].peer_bdaddr == peer_addr) { for (int j = 0; j < BTA_DM_PM_MODE_TIMER_MAX; j++) { if (bta_dm_cb.pm_timer[i].srvc_id[j] == srvc_id) { bta_dm_pm_stop_timer_by_index(&bta_dm_cb.pm_timer[i], j); @@ -296,23 +287,25 @@ static void bta_dm_pm_stop_timer_by_srvc_id(const RawAddress& peer_addr, * Returns void * ******************************************************************************/ -static void bta_dm_pm_start_timer(tBTA_PM_TIMER* p_timer, uint8_t timer_idx, - uint64_t timeout_ms, uint8_t srvc_id, - uint8_t pm_action) { +static void bta_dm_pm_start_timer(tBTA_PM_TIMER* p_timer, uint8_t timer_idx, uint64_t timeout_ms, + uint8_t srvc_id, uint8_t pm_action) { std::unique_lock schedule_lock(pm_timer_schedule_mutex); std::unique_lock state_lock(pm_timer_state_mutex); p_timer->in_use = true; - if (p_timer->srvc_id[timer_idx] == BTA_ID_MAX) p_timer->active++; + if (p_timer->srvc_id[timer_idx] == BTA_ID_MAX) { + p_timer->active++; + } - if (p_timer->pm_action[timer_idx] < pm_action) + if (p_timer->pm_action[timer_idx] < pm_action) { p_timer->pm_action[timer_idx] = pm_action; + } p_timer->srvc_id[timer_idx] = srvc_id; state_lock.unlock(); - alarm_set_on_mloop(p_timer->timer[timer_idx], timeout_ms, - bta_dm_pm_timer_cback, p_timer->timer[timer_idx]); + alarm_set_on_mloop(p_timer->timer[timer_idx], timeout_ms, bta_dm_pm_timer_cback, + p_timer->timer[timer_idx]); } /******************************************************************************* @@ -325,9 +318,10 @@ static void bta_dm_pm_start_timer(tBTA_PM_TIMER* p_timer, uint8_t timer_idx, * Returns void * ******************************************************************************/ -static void bta_dm_pm_stop_timer_by_index(tBTA_PM_TIMER* p_timer, - uint8_t timer_idx) { - if ((p_timer == NULL) || (timer_idx >= BTA_DM_PM_MODE_TIMER_MAX)) return; +static void bta_dm_pm_stop_timer_by_index(tBTA_PM_TIMER* p_timer, uint8_t timer_idx) { + if ((p_timer == NULL) || (timer_idx >= BTA_DM_PM_MODE_TIMER_MAX)) { + return; + } std::unique_lock schedule_lock(pm_timer_schedule_mutex); std::unique_lock state_lock(pm_timer_state_mutex); @@ -335,8 +329,7 @@ static void bta_dm_pm_stop_timer_by_index(tBTA_PM_TIMER* p_timer, return; } /* The timer was not scheduled */ - log::assert_that(p_timer->in_use, - "Timer was not scheduled p_timer->srvc_id[timer_idx]:{}", + log::assert_that(p_timer->in_use, "Timer was not scheduled p_timer->srvc_id[timer_idx]:{}", p_timer->srvc_id[timer_idx]); log::assert_that(p_timer->active > 0, "No tasks on timer are active"); @@ -344,7 +337,9 @@ static void bta_dm_pm_stop_timer_by_index(tBTA_PM_TIMER* p_timer, /* NOTE: pm_action[timer_idx] intentionally not reset */ p_timer->active--; - if (p_timer->active == 0) p_timer->in_use = false; + if (p_timer->active == 0) { + p_timer->in_use = false; + } state_lock.unlock(); alarm_cancel(p_timer->timer[timer_idx]); @@ -360,8 +355,7 @@ static void bta_dm_pm_stop_timer_by_index(tBTA_PM_TIMER* p_timer, * Returns void * ******************************************************************************/ -static void bta_dm_sniff_cback(uint8_t id, uint8_t app_id, - const RawAddress& peer_addr) { +static void bta_dm_sniff_cback(uint8_t id, uint8_t app_id, const RawAddress& peer_addr) { int i = 0, j = 0; uint64_t timeout_ms = 0; @@ -375,9 +369,9 @@ static void bta_dm_sniff_cback(uint8_t id, uint8_t app_id, p_bta_dm_pm_cfg[0].app_id is the number of entries */ for (j = 1; j <= p_bta_dm_pm_cfg[0].app_id; j++) { if ((p_bta_dm_pm_cfg[j].id == id) && - ((p_bta_dm_pm_cfg[j].app_id == BTA_ALL_APP_ID) || - (p_bta_dm_pm_cfg[j].app_id == app_id))) + ((p_bta_dm_pm_cfg[j].app_id == BTA_ALL_APP_ID) || (p_bta_dm_pm_cfg[j].app_id == app_id))) { break; + } } // Handle overflow access if (j > p_bta_dm_pm_cfg[0].app_id) { @@ -401,14 +395,12 @@ static void bta_dm_sniff_cback(uint8_t id, uint8_t app_id, /* Refresh the sniff timer */ for (i = 0; i < BTA_DM_NUM_PM_TIMER; i++) { - if (bta_dm_cb.pm_timer[i].in_use && - bta_dm_cb.pm_timer[i].peer_bdaddr == peer_addr) { + if (bta_dm_cb.pm_timer[i].in_use && bta_dm_cb.pm_timer[i].peer_bdaddr == peer_addr) { int timer_idx = bta_pm_action_to_timer_idx(BTA_DM_PM_SNIFF); if (timer_idx != BTA_DM_PM_MODE_TIMER_MAX) { /* Cancel and restart the timer */ bta_dm_pm_stop_timer_by_index(&bta_dm_cb.pm_timer[i], timer_idx); - bta_dm_pm_start_timer(&bta_dm_cb.pm_timer[i], timer_idx, timeout_ms, id, - BTA_DM_PM_SNIFF); + bta_dm_pm_start_timer(&bta_dm_cb.pm_timer[i], timer_idx, timeout_ms, id, BTA_DM_PM_SNIFF); } } } @@ -424,34 +416,32 @@ static void bta_dm_sniff_cback(uint8_t id, uint8_t app_id, * Returns void * ******************************************************************************/ -static void bta_dm_pm_cback(tBTA_SYS_CONN_STATUS status, const tBTA_SYS_ID id, - uint8_t app_id, const RawAddress& peer_addr) { +static void bta_dm_pm_cback(tBTA_SYS_CONN_STATUS status, const tBTA_SYS_ID id, uint8_t app_id, + const RawAddress& peer_addr) { uint8_t i, j; tBTA_DM_PEER_DEVICE* p_dev; tBTA_DM_PM_REQ pm_req = BTA_DM_PM_NEW_REQ; log::verbose("Power management callback status:{}[{}] id:{}[{}], app:{}", - bta_sys_conn_status_text(status), status, BtaIdSysText(id), id, - app_id); + bta_sys_conn_status_text(status), status, BtaIdSysText(id), id, app_id); /* find if there is an power mode entry for the service */ for (i = 1; i <= p_bta_dm_pm_cfg[0].app_id; i++) { if ((p_bta_dm_pm_cfg[i].id == id) && - ((p_bta_dm_pm_cfg[i].app_id == BTA_ALL_APP_ID) || - (p_bta_dm_pm_cfg[i].app_id == app_id))) + ((p_bta_dm_pm_cfg[i].app_id == BTA_ALL_APP_ID) || (p_bta_dm_pm_cfg[i].app_id == app_id))) { break; + } } /* if no entries are there for the app_id and subsystem in * get_bta_dm_pm_spec()*/ if (i > p_bta_dm_pm_cfg[0].app_id) { - log::debug( - "Ignoring power management callback as no service entries exist"); + log::debug("Ignoring power management callback as no service entries exist"); return; } - log::verbose("Stopped all timers for service to device:{} id:{}[{}]", - peer_addr, BtaIdSysText(id), id); + log::verbose("Stopped all timers for service to device:{} id:{}[{}]", peer_addr, BtaIdSysText(id), + id); bta_dm_pm_stop_timer_by_srvc_id(peer_addr, static_cast(id)); p_dev = bta_dm_find_peer_device(peer_addr); @@ -475,11 +465,11 @@ static void bta_dm_pm_cback(tBTA_SYS_CONN_STATUS status, const tBTA_SYS_ID id, } /* if no action for the event */ - if (get_bta_dm_pm_spec()[p_bta_dm_pm_cfg[i].spec_idx] - .actn_tbl[status][0] - .power_mode == BTA_DM_PM_NO_ACTION) { - if (BTA_DM_PM_SSR0 == index) /* and do not need to set SSR, return. */ + if (get_bta_dm_pm_spec()[p_bta_dm_pm_cfg[i].spec_idx].actn_tbl[status][0].power_mode == + BTA_DM_PM_NO_ACTION) { + if (BTA_DM_PM_SSR0 == index) { /* and do not need to set SSR, return. */ return; + } } for (j = 0; j < bta_dm_conn_srvcs.count; j++) { @@ -494,15 +484,13 @@ static void bta_dm_pm_cback(tBTA_SYS_CONN_STATUS status, const tBTA_SYS_ID id, /* if subsystem has no more preference on the power mode remove the cb */ - if (get_bta_dm_pm_spec()[p_bta_dm_pm_cfg[i].spec_idx] - .actn_tbl[status][0] - .power_mode == BTA_DM_PM_NO_PREF) { + if (get_bta_dm_pm_spec()[p_bta_dm_pm_cfg[i].spec_idx].actn_tbl[status][0].power_mode == + BTA_DM_PM_NO_PREF) { if (j != bta_dm_conn_srvcs.count) { bta_dm_conn_srvcs.count--; for (; j < bta_dm_conn_srvcs.count; j++) { - memcpy(&bta_dm_conn_srvcs.conn_srvc[j], - &bta_dm_conn_srvcs.conn_srvc[j + 1], + memcpy(&bta_dm_conn_srvcs.conn_srvc[j], &bta_dm_conn_srvcs.conn_srvc[j + 1], sizeof(bta_dm_conn_srvcs.conn_srvc[j])); } } else { @@ -522,8 +510,7 @@ static void bta_dm_pm_cback(tBTA_SYS_CONN_STATUS status, const tBTA_SYS_ID id, bta_dm_conn_srvcs.conn_srvc[j].new_request = true; bta_dm_conn_srvcs.conn_srvc[j].peer_bdaddr = peer_addr; - log::info("New connection service:{}[{}] app_id:{}", BtaIdSysText(id), id, - app_id); + log::info("New connection service:{}[{}] app_id:{}", BtaIdSysText(id), id, app_id); bta_dm_conn_srvcs.count++; bta_dm_conn_srvcs.conn_srvc[j].state = status; @@ -537,9 +524,9 @@ static void bta_dm_pm_cback(tBTA_SYS_CONN_STATUS status, const tBTA_SYS_ID id, if (bta_dm_conn_srvcs.count > 0) { pm_req = BTA_DM_PM_RESTART; log::verbose( - "bta_dm_pm_stop_timer for current service, restart other service " - "timers: count = {}", - bta_dm_conn_srvcs.count); + "bta_dm_pm_stop_timer for current service, restart other service " + "timers: count = {}", + bta_dm_conn_srvcs.count); } if (p_dev) { @@ -557,14 +544,13 @@ static void bta_dm_pm_cback(tBTA_SYS_CONN_STATUS status, const tBTA_SYS_ID id, } else { uint8_t* p = NULL; if (bluetooth::shim::GetController()->SupportsSniffSubrating() && - ((NULL != (p = get_btm_client_interface().peer.BTM_ReadRemoteFeatures( - peer_addr))) && + ((NULL != (p = get_btm_client_interface().peer.BTM_ReadRemoteFeatures(peer_addr))) && HCI_SNIFF_SUB_RATE_SUPPORTED(p)) && (index == BTA_DM_PM_SSR0)) { if (status == BTA_SYS_SCO_OPEN) { log::verbose("SCO inactive, reset SSR to zero"); - if (get_btm_client_interface().link_policy.BTM_SetSsrParams( - peer_addr, 0, 0, 0) != BTM_SUCCESS) { + if (get_btm_client_interface().link_policy.BTM_SetSsrParams(peer_addr, 0, 0, 0) != + BTM_SUCCESS) { log::warn("Unable to set link into sniff mode peer:{}", peer_addr); } } else if (status == BTA_SYS_SCO_CLOSE) { @@ -588,8 +574,7 @@ static void bta_dm_pm_cback(tBTA_SYS_CONN_STATUS status, const tBTA_SYS_ID id, * ******************************************************************************/ -static void bta_dm_pm_set_mode(const RawAddress& peer_addr, - tBTA_DM_PM_ACTION pm_request, +static void bta_dm_pm_set_mode(const RawAddress& peer_addr, tBTA_DM_PM_ACTION pm_request, tBTA_DM_PM_REQ pm_req) { tBTA_DM_PM_ACTION pm_action = BTA_DM_PM_NO_ACTION; uint64_t timeout_ms = 0; @@ -629,8 +614,9 @@ static void bta_dm_pm_set_mode(const RawAddress& peer_addr, for (j = 1; j <= p_bta_dm_pm_cfg[0].app_id; j++) { if ((p_bta_dm_pm_cfg[j].id == p_srvcs->id) && ((p_bta_dm_pm_cfg[j].app_id == BTA_ALL_APP_ID) || - (p_bta_dm_pm_cfg[j].app_id == p_srvcs->app_id))) + (p_bta_dm_pm_cfg[j].app_id == p_srvcs->app_id))) { break; + } } p_pm_cfg = &p_bta_dm_pm_cfg[j]; @@ -639,11 +625,9 @@ static void bta_dm_pm_set_mode(const RawAddress& peer_addr, p_act1 = &p_pm_spec->actn_tbl[p_srvcs->state][1]; allowed_modes |= p_pm_spec->allow_mask; - log::verbose( - "Service:{}[{}] state:{}[{}] allowed_modes:0x{:02x} service_index:{}", - BtaIdSysText(p_srvcs->id), p_srvcs->id, - bta_sys_conn_status_text(p_srvcs->state), p_srvcs->state, - allowed_modes, j); + log::verbose("Service:{}[{}] state:{}[{}] allowed_modes:0x{:02x} service_index:{}", + BtaIdSysText(p_srvcs->id), p_srvcs->id, bta_sys_conn_status_text(p_srvcs->state), + p_srvcs->state, allowed_modes, j); /* PM actions are in the order of strictness */ @@ -677,8 +661,7 @@ static void bta_dm_pm_set_mode(const RawAddress& peer_addr, if (!(allowed_modes & pm_action)) { /* select the other mode if its allowed and preferred, otherwise 0 which * is BTA_DM_PM_NO_ACTION */ - pm_action = - (allowed_modes & (BTA_DM_PM_PARK | BTA_DM_PM_SNIFF) & pref_modes); + pm_action = (allowed_modes & (BTA_DM_PM_PARK | BTA_DM_PM_SNIFF) & pref_modes); /* no timeout needed if no action is required */ if (pm_action == BTA_DM_PM_NO_ACTION) { @@ -689,12 +672,10 @@ static void bta_dm_pm_set_mode(const RawAddress& peer_addr, /* if need to start a timer */ if ((pm_req != BTA_DM_PM_EXECUTE) && (timeout_ms > 0)) { for (i = 0; i < BTA_DM_NUM_PM_TIMER; i++) { - if (bta_dm_cb.pm_timer[i].in_use && - bta_dm_cb.pm_timer[i].peer_bdaddr == peer_addr) { + if (bta_dm_cb.pm_timer[i].in_use && bta_dm_cb.pm_timer[i].peer_bdaddr == peer_addr) { timer_idx = bta_pm_action_to_timer_idx(pm_action); if (timer_idx != BTA_DM_PM_MODE_TIMER_MAX) { - remaining_ms = - alarm_get_remaining_ms(bta_dm_cb.pm_timer[i].timer[timer_idx]); + remaining_ms = alarm_get_remaining_ms(bta_dm_cb.pm_timer[i].timer[timer_idx]); if (remaining_ms < timeout_ms) { /* Cancel and restart the timer */ /* @@ -705,14 +686,16 @@ static void bta_dm_pm_set_mode(const RawAddress& peer_addr, * in the future. */ bta_dm_pm_stop_timer_by_index(&bta_dm_cb.pm_timer[i], timer_idx); - bta_dm_pm_start_timer(&bta_dm_cb.pm_timer[i], timer_idx, timeout_ms, - p_srvcs->id, pm_action); + bta_dm_pm_start_timer(&bta_dm_cb.pm_timer[i], timer_idx, timeout_ms, p_srvcs->id, + pm_action); } timer_started = true; } break; } else if (!bta_dm_cb.pm_timer[i].in_use) { - if (available_timer == BTA_DM_PM_MODE_TIMER_MAX) available_timer = i; + if (available_timer == BTA_DM_PM_MODE_TIMER_MAX) { + available_timer = i; + } } } /* new power mode for a new active connection */ @@ -721,8 +704,8 @@ static void bta_dm_pm_set_mode(const RawAddress& peer_addr, bta_dm_cb.pm_timer[available_timer].peer_bdaddr = peer_addr; timer_idx = bta_pm_action_to_timer_idx(pm_action); if (timer_idx != BTA_DM_PM_MODE_TIMER_MAX) { - bta_dm_pm_start_timer(&bta_dm_cb.pm_timer[available_timer], timer_idx, - timeout_ms, p_srvcs->id, pm_action); + bta_dm_pm_start_timer(&bta_dm_cb.pm_timer[available_timer], timer_idx, timeout_ms, + p_srvcs->id, pm_action); timer_started = true; } } else { @@ -744,13 +727,11 @@ static void bta_dm_pm_set_mode(const RawAddress& peer_addr, } else if (pm_action & BTA_DM_PM_SNIFF) { /* dont initiate SNIFF, if link_policy has it disabled */ if (BTM_is_sniff_allowed_for(peer_addr)) { - log::verbose("Link policy allows sniff mode so setting mode peer:{}", - peer_addr); + log::verbose("Link policy allows sniff mode so setting mode peer:{}", peer_addr); p_peer_device->pm_mode_attempted = BTA_DM_PM_SNIFF; bta_dm_pm_sniff(p_peer_device, (uint8_t)(pm_action & 0x0F)); } else { - log::debug("Link policy disallows sniff mode, ignore request peer:{}", - peer_addr); + log::debug("Link policy disallows sniff mode, ignore request peer:{}", peer_addr); } } else if (pm_action == BTA_DM_PM_ACTIVE) { log::verbose("Setting link to active mode peer:{}", peer_addr); @@ -776,8 +757,7 @@ static bool bta_dm_pm_park(const RawAddress& peer_addr) { } if (mode != BTM_PM_MD_PARK) { - tBTM_STATUS status = - get_btm_client_interface().link_policy.BTM_SetPowerMode( + tBTM_STATUS status = get_btm_client_interface().link_policy.BTM_SetPowerMode( bta_dm_cb.pm_id, peer_addr, &p_bta_dm_pm_md[BTA_DM_PM_PARK_IDX]); if (status == BTM_CMD_STORED || status == BTM_CMD_STARTED) { return true; @@ -807,31 +787,26 @@ static tBTM_PM_PWR_MD get_sniff_entry(uint8_t index) { } std::vector invalid_list(BTA_DM_PM_PARK_IDX, 0); - std::vector max = - osi_property_get_uintlist(kPropertySniffMaxIntervals, invalid_list); - std::vector min = - osi_property_get_uintlist(kPropertySniffMinIntervals, invalid_list); - std::vector attempt = - osi_property_get_uintlist(kPropertySniffAttempts, invalid_list); - std::vector timeout = - osi_property_get_uintlist(kPropertySniffTimeouts, invalid_list); + std::vector max = osi_property_get_uintlist(kPropertySniffMaxIntervals, invalid_list); + std::vector min = osi_property_get_uintlist(kPropertySniffMinIntervals, invalid_list); + std::vector attempt = osi_property_get_uintlist(kPropertySniffAttempts, invalid_list); + std::vector timeout = osi_property_get_uintlist(kPropertySniffTimeouts, invalid_list); // If any of the sysprops are malformed or don't exist, use default table // value - bool use_defaults = - (max.size() < BTA_DM_PM_PARK_IDX || max == invalid_list || - min.size() < BTA_DM_PM_PARK_IDX || min == invalid_list || - attempt.size() < BTA_DM_PM_PARK_IDX || attempt == invalid_list || - timeout.size() < BTA_DM_PM_PARK_IDX || timeout == invalid_list); + bool use_defaults = (max.size() < BTA_DM_PM_PARK_IDX || max == invalid_list || + min.size() < BTA_DM_PM_PARK_IDX || min == invalid_list || + attempt.size() < BTA_DM_PM_PARK_IDX || attempt == invalid_list || + timeout.size() < BTA_DM_PM_PARK_IDX || timeout == invalid_list); for (auto i = 0; i < BTA_DM_PM_PARK_IDX; i++) { if (use_defaults) { pwr_mds_cache.push_back(p_bta_dm_pm_md[i]); } else { - pwr_mds_cache.push_back(tBTM_PM_PWR_MD{ - static_cast(max[i]), static_cast(min[i]), - static_cast(attempt[i]), static_cast(timeout[i]), - BTM_PM_MD_SNIFF}); + pwr_mds_cache.push_back(tBTM_PM_PWR_MD{static_cast(max[i]), + static_cast(min[i]), + static_cast(attempt[i]), + static_cast(timeout[i]), BTM_PM_MD_SNIFF}); } } @@ -859,17 +834,15 @@ static void bta_dm_pm_sniff(tBTA_DM_PEER_DEVICE* p_peer_dev, uint8_t index) { log::warn("Unable to read power mode for peer:{}", p_peer_dev->peer_bdaddr); } tBTM_PM_STATUS mode_status = static_cast(mode); - log::debug("Current power mode:{}[0x{:x}] peer_info:{}", - power_mode_status_text(mode_status), mode_status, - p_peer_dev->info_text()); + log::debug("Current power mode:{}[0x{:x}] peer_info:{}", power_mode_status_text(mode_status), + mode_status, p_peer_dev->info_text()); - uint8_t* p_rem_feat = get_btm_client_interface().peer.BTM_ReadRemoteFeatures( - p_peer_dev->peer_bdaddr); + uint8_t* p_rem_feat = + get_btm_client_interface().peer.BTM_ReadRemoteFeatures(p_peer_dev->peer_bdaddr); if (mode != BTM_PM_MD_SNIFF || - (bluetooth::shim::GetController()->SupportsSniffSubrating() && - p_rem_feat && HCI_SNIFF_SUB_RATE_SUPPORTED(p_rem_feat) && - !(p_peer_dev->is_ssr_active()))) { + (bluetooth::shim::GetController()->SupportsSniffSubrating() && p_rem_feat && + HCI_SNIFF_SUB_RATE_SUPPORTED(p_rem_feat) && !(p_peer_dev->is_ssr_active()))) { /* Dont initiate Sniff if controller has alreay accepted * remote sniff params. This avoid sniff loop issue with * some agrresive headsets who use sniff latencies more than @@ -888,7 +861,7 @@ static void bta_dm_pm_sniff(tBTA_DM_PEER_DEVICE* p_peer_dev, uint8_t index) { pwr_md.mode |= BTM_PM_MD_FORCE; } status = get_btm_client_interface().link_policy.BTM_SetPowerMode( - bta_dm_cb.pm_id, p_peer_dev->peer_bdaddr, &pwr_md); + bta_dm_cb.pm_id, p_peer_dev->peer_bdaddr, &pwr_md); if (status == BTM_CMD_STORED || status == BTM_CMD_STARTED) { p_peer_dev->reset_sniff_flags(); p_peer_dev->set_sniff_command_sent(); @@ -896,8 +869,8 @@ static void bta_dm_pm_sniff(tBTA_DM_PEER_DEVICE* p_peer_dev, uint8_t index) { log::verbose("bta_dm_pm_sniff BTM_SetPowerMode() returns BTM_SUCCESS"); p_peer_dev->reset_sniff_flags(); } else { - log::error("Unable to set power mode peer:{} status:{}", - p_peer_dev->peer_bdaddr, btm_status_text(status)); + log::error("Unable to set power mode peer:{} status:{}", p_peer_dev->peer_bdaddr, + btm_status_text(status)); p_peer_dev->reset_sniff_flags(); } } @@ -914,8 +887,7 @@ static void bta_dm_pm_ssr(const RawAddress& peer_addr, const int ssr) { int ssr_index = ssr; tBTA_DM_SSR_SPEC* p_spec = &p_bta_dm_ssr_spec[ssr]; - log::debug("Request to put link to device:{} into power_mode:{}", peer_addr, - p_spec->name); + log::debug("Request to put link to device:{} into power_mode:{}", peer_addr, p_spec->name); /* go through the connected services */ for (int i = 0; i < bta_dm_conn_srvcs.count; i++) { const tBTA_DM_SRVCS& service = bta_dm_conn_srvcs.conn_srvc[i]; @@ -928,8 +900,8 @@ static void bta_dm_pm_ssr(const RawAddress& peer_addr, const int ssr) { /* find the associated p_bta_dm_pm_cfg */ const tBTA_DM_PM_CFG& config = p_bta_dm_pm_cfg[j]; current_ssr_index = get_bta_dm_pm_spec()[config.spec_idx].ssr; - if ((config.id == service.id) && ((config.app_id == BTA_ALL_APP_ID) || - (config.app_id == service.app_id))) { + if ((config.id == service.id) && + ((config.app_id == BTA_ALL_APP_ID) || (config.app_id == service.app_id))) { log::info("Found connected service:{} app_id:{} peer:{} spec_name:{}", BtaIdSysText(service.id), service.app_id, peer_addr, p_bta_dm_ssr_spec[current_ssr_index].name); @@ -946,18 +918,16 @@ static void bta_dm_pm_ssr(const RawAddress& peer_addr, const int ssr) { link_spec.addrt.type = BLE_ADDR_PUBLIC; link_spec.transport = BT_TRANSPORT_BR_EDR; if (GetInterfaceToProfiles()->profileSpecific_HACK->bta_hh_read_ssr_param( - link_spec, &p_spec_cur->max_lat, &p_spec_cur->min_rmt_to) == - BTA_HH_ERR) { + link_spec, &p_spec_cur->max_lat, &p_spec_cur->min_rmt_to) == BTA_HH_ERR) { continue; } } if (p_spec_cur->max_lat < p_spec->max_lat || (ssr_index == BTA_DM_PM_SSR0 && current_ssr_index != BTA_DM_PM_SSR0)) { log::debug( - "Changing sniff subrating specification for {} from {}[{}] ==> " - "{}[{}]", - peer_addr, p_spec->name, ssr_index, p_spec_cur->name, - current_ssr_index); + "Changing sniff subrating specification for {} from {}[{}] ==> " + "{}[{}]", + peer_addr, p_spec->name, ssr_index, p_spec_cur->name, current_ssr_index); ssr_index = current_ssr_index; p_spec = &p_bta_dm_ssr_spec[ssr_index]; } @@ -974,16 +944,15 @@ static void bta_dm_pm_ssr(const RawAddress& peer_addr, const int ssr) { } log::debug( - "Setting sniff subrating for device:{} spec_name:{} " - "max_latency(s):{:.2f} min_local_timeout(s):{:.2f} " - "min_remote_timeout(s):{:.2f}", - peer_addr, p_spec->name, ticks_to_seconds(p_spec->max_lat), - ticks_to_seconds(p_spec->min_loc_to), - ticks_to_seconds(p_spec->min_rmt_to)); + "Setting sniff subrating for device:{} spec_name:{} " + "max_latency(s):{:.2f} min_local_timeout(s):{:.2f} " + "min_remote_timeout(s):{:.2f}", + peer_addr, p_spec->name, ticks_to_seconds(p_spec->max_lat), + ticks_to_seconds(p_spec->min_loc_to), ticks_to_seconds(p_spec->min_rmt_to)); /* set the SSR parameters. */ if (get_btm_client_interface().link_policy.BTM_SetSsrParams( - peer_addr, p_spec->max_lat, p_spec->min_rmt_to, - p_spec->min_loc_to) != BTM_SUCCESS) { + peer_addr, p_spec->max_lat, p_spec->min_rmt_to, p_spec->min_loc_to) != + BTM_SUCCESS) { log::warn("Unable to set link into sniff mode peer:{}", peer_addr); } } @@ -1000,16 +969,15 @@ static void bta_dm_pm_ssr(const RawAddress& peer_addr, const int ssr) { ******************************************************************************/ void bta_dm_pm_active(const RawAddress& peer_addr) { tBTM_PM_PWR_MD pm{ - .mode = BTM_PM_MD_ACTIVE, + .mode = BTM_PM_MD_ACTIVE, }; /* switch to active mode */ - tBTM_STATUS status = get_btm_client_interface().link_policy.BTM_SetPowerMode( - bta_dm_cb.pm_id, peer_addr, &pm); + tBTM_STATUS status = + get_btm_client_interface().link_policy.BTM_SetPowerMode(bta_dm_cb.pm_id, peer_addr, &pm); switch (status) { case BTM_CMD_STORED: - log::debug("Active power mode stored for execution later for remote:{}", - peer_addr); + log::debug("Active power mode stored for execution later for remote:{}", peer_addr); break; case BTM_CMD_STARTED: log::debug("Active power mode started for remote:{}", peer_addr); @@ -1018,22 +986,20 @@ void bta_dm_pm_active(const RawAddress& peer_addr) { log::debug("Active power mode already set for device:{}", peer_addr); break; default: - log::warn("Unable to set active power mode for device:{} status:{}", - peer_addr, btm_status_text(status)); + log::warn("Unable to set active power mode for device:{} status:{}", peer_addr, + btm_status_text(status)); break; } } -static void bta_dm_pm_btm_status(const RawAddress& bd_addr, - tBTM_PM_STATUS status, uint16_t interval, - tHCI_STATUS hci_status); +static void bta_dm_pm_btm_status(const RawAddress& bd_addr, tBTM_PM_STATUS status, + uint16_t interval, tHCI_STATUS hci_status); /** BTM power manager callback */ -static void bta_dm_pm_btm_cback(const RawAddress& bd_addr, - tBTM_PM_STATUS status, uint16_t value, +static void bta_dm_pm_btm_cback(const RawAddress& bd_addr, tBTM_PM_STATUS status, uint16_t value, tHCI_STATUS hci_status) { - do_in_main_thread(FROM_HERE, base::BindOnce(bta_dm_pm_btm_status, bd_addr, - status, value, hci_status)); + do_in_main_thread(FROM_HERE, + base::BindOnce(bta_dm_pm_btm_status, bd_addr, status, value, hci_status)); } /******************************************************************************* @@ -1062,31 +1028,32 @@ static void bta_dm_pm_timer_cback(void* data) { break; } } - if (bta_dm_cb.pm_timer[i].active == 0) + if (bta_dm_cb.pm_timer[i].active == 0) { bta_dm_cb.pm_timer[i].in_use = false; - if (j < BTA_DM_PM_MODE_TIMER_MAX) break; + } + if (j < BTA_DM_PM_MODE_TIMER_MAX) { + break; + } } } state_lock.unlock(); /* no more timers */ - if (i == BTA_DM_NUM_PM_TIMER) return; + if (i == BTA_DM_NUM_PM_TIMER) { + return; + } - do_in_main_thread( - FROM_HERE, - base::BindOnce(bta_dm_pm_timer, bta_dm_cb.pm_timer[i].peer_bdaddr, - bta_dm_cb.pm_timer[i].pm_action[j])); + do_in_main_thread(FROM_HERE, base::BindOnce(bta_dm_pm_timer, bta_dm_cb.pm_timer[i].peer_bdaddr, + bta_dm_cb.pm_timer[i].pm_action[j])); } /** Process pm status event from btm */ -static void bta_dm_pm_btm_status(const RawAddress& bd_addr, - tBTM_PM_STATUS status, uint16_t interval, - tHCI_STATUS hci_status) { +static void bta_dm_pm_btm_status(const RawAddress& bd_addr, tBTM_PM_STATUS status, + uint16_t interval, tHCI_STATUS hci_status) { log::verbose( - "Power mode notification event status:{} peer:{} interval:{} " - "hci_status:{}", - power_mode_status_text(status), bd_addr, interval, - hci_error_code_text(hci_status)); + "Power mode notification event status:{} peer:{} interval:{} " + "hci_status:{}", + power_mode_status_text(status), bd_addr, interval, hci_error_code_text(hci_status)); tBTA_DM_PEER_DEVICE* p_dev = bta_dm_find_peer_device(bd_addr); if (p_dev == nullptr) { @@ -1104,8 +1071,7 @@ static void bta_dm_pm_btm_status(const RawAddress& bd_addr, p_dev->reset_sniff_flags(); if (p_dev->pm_mode_attempted & (BTA_DM_PM_PARK | BTA_DM_PM_SNIFF)) { - p_dev->pm_mode_failed |= - ((BTA_DM_PM_PARK | BTA_DM_PM_SNIFF) & p_dev->pm_mode_attempted); + p_dev->pm_mode_failed |= ((BTA_DM_PM_PARK | BTA_DM_PM_SNIFF) & p_dev->pm_mode_attempted); bta_dm_pm_stop_timer_by_mode(bd_addr, p_dev->pm_mode_attempted); bta_dm_pm_set_mode(bd_addr, BTA_DM_PM_NO_ACTION, BTA_DM_PM_RESTART); } @@ -1127,7 +1093,9 @@ static void bta_dm_pm_btm_status(const RawAddress& bd_addr, /* save the previous low power mode - for SSR. * SSR parameters are sent to controller on "conn open". * the numbers stay good until park/hold/detach */ - if (p_dev->is_ssr_active()) p_dev->prev_low = status; + if (p_dev->is_ssr_active()) { + p_dev->prev_low = status; + } break; case BTM_PM_STS_SSR: @@ -1154,10 +1122,11 @@ static void bta_dm_pm_btm_status(const RawAddress& bd_addr, } else { bool is_sniff_command_sent = p_dev->is_sniff_command_sent(); p_dev->reset_sniff_flags(); - if (is_sniff_command_sent) + if (is_sniff_command_sent) { p_dev->set_local_init_sniff(); - else + } else { p_dev->set_remote_init_sniff(); + } } break; @@ -1174,8 +1143,7 @@ static void bta_dm_pm_btm_status(const RawAddress& bd_addr, } /** Process pm timer event from btm */ -static void bta_dm_pm_timer(const RawAddress& bd_addr, - tBTA_DM_PM_ACTION pm_request) { +static void bta_dm_pm_timer(const RawAddress& bd_addr, tBTA_DM_PM_ACTION pm_request) { log::verbose(""); bta_dm_pm_set_mode(bd_addr, pm_request, BTA_DM_PM_EXECUTE); } diff --git a/system/bta/dm/bta_dm_sec.cc b/system/bta/dm/bta_dm_sec.cc index d15ab4afb92..ec3bc4b16c2 100644 --- a/system/bta/dm/bta_dm_sec.cc +++ b/system/bta/dm/bta_dm_sec.cc @@ -42,33 +42,29 @@ using namespace bluetooth; static tBTM_STATUS bta_dm_sp_cback(tBTM_SP_EVT event, tBTM_SP_EVT_DATA* p_data); static uint8_t bta_dm_ble_smp_cback(tBTM_LE_EVT event, const RawAddress& bda, tBTM_LE_EVT_DATA* p_data); -static uint8_t bta_dm_new_link_key_cback(const RawAddress& bd_addr, - DEV_CLASS dev_class, BD_NAME bd_name, - const LinkKey& key, uint8_t key_type, +static uint8_t bta_dm_new_link_key_cback(const RawAddress& bd_addr, DEV_CLASS dev_class, + BD_NAME bd_name, const LinkKey& key, uint8_t key_type, bool is_ctkd); static uint8_t bta_dm_pin_cback(const RawAddress& bd_addr, DEV_CLASS dev_class, const BD_NAME bd_name, bool min_16_digit); static uint8_t bta_dm_sirk_verifiction_cback(const RawAddress& bd_addr); -static void bta_dm_authentication_complete_cback(const RawAddress& bd_addr, - DEV_CLASS dev_class, - BD_NAME bd_name, - tHCI_REASON result); -static void bta_dm_ble_id_key_cback(uint8_t key_type, - tBTM_BLE_LOCAL_KEYS* p_key); +static void bta_dm_authentication_complete_cback(const RawAddress& bd_addr, DEV_CLASS dev_class, + BD_NAME bd_name, tHCI_REASON result); +static void bta_dm_ble_id_key_cback(uint8_t key_type, tBTM_BLE_LOCAL_KEYS* p_key); static void bta_dm_bond_cancel_complete_cback(tBTM_STATUS result); static void bta_dm_remove_sec_dev_entry(const RawAddress& remote_bd_addr); static void bta_dm_reset_sec_dev_pending(const RawAddress& remote_bd_addr); /* bta security callback */ const tBTM_APPL_INFO bta_security = { - .p_pin_callback = &bta_dm_pin_cback, - .p_link_key_callback = &bta_dm_new_link_key_cback, - .p_auth_complete_callback = &bta_dm_authentication_complete_cback, - .p_bond_cancel_cmpl_callback = &bta_dm_bond_cancel_complete_cback, - .p_sp_callback = &bta_dm_sp_cback, - .p_le_callback = &bta_dm_ble_smp_cback, - .p_le_key_callback = &bta_dm_ble_id_key_cback, - .p_sirk_verification_callback = &bta_dm_sirk_verifiction_cback}; + .p_pin_callback = &bta_dm_pin_cback, + .p_link_key_callback = &bta_dm_new_link_key_cback, + .p_auth_complete_callback = &bta_dm_authentication_complete_cback, + .p_bond_cancel_cmpl_callback = &bta_dm_bond_cancel_complete_cback, + .p_sp_callback = &bta_dm_sp_cback, + .p_le_callback = &bta_dm_ble_smp_cback, + .p_le_key_callback = &bta_dm_ble_id_key_cback, + .p_sirk_verification_callback = &bta_dm_sirk_verifiction_cback}; void btm_sec_on_hw_on() { tBTA_DM_SEC_CBACK* temp_sec_cback = bta_dm_sec_cb.p_sec_cback; @@ -82,33 +78,33 @@ void bta_dm_ble_sirk_sec_cb_register(tBTA_DM_SEC_CBACK* p_cback) { bta_dm_sec_cb.p_sec_sirk_cback = p_cback; } -void bta_dm_ble_sirk_confirm_device_reply(const RawAddress& bd_addr, - bool accept) { +void bta_dm_ble_sirk_confirm_device_reply(const RawAddress& bd_addr, bool accept) { log::debug("addr:{}", bd_addr); get_btm_client_interface().security.BTM_BleSirkConfirmDeviceReply( - bd_addr, accept ? BTM_SUCCESS : BTM_NOT_AUTHORIZED); + bd_addr, accept ? BTM_SUCCESS : BTM_NOT_AUTHORIZED); } -void bta_dm_consolidate(const RawAddress& identity_addr, - const RawAddress& rpa) { +void bta_dm_consolidate(const RawAddress& identity_addr, const RawAddress& rpa) { for (auto i = 0; i < bta_dm_cb.device_list.count; i++) { - if (bta_dm_cb.device_list.peer_device[i].peer_bdaddr != rpa) continue; + if (bta_dm_cb.device_list.peer_device[i].peer_bdaddr != rpa) { + continue; + } log::info("consolidating bda_dm_cb record {} -> {}", rpa, identity_addr); bta_dm_cb.device_list.peer_device[i].peer_bdaddr = identity_addr; } } -void btm_dm_sec_init() { - get_btm_client_interface().security.BTM_SecRegister(&bta_security); -} +void btm_dm_sec_init() { get_btm_client_interface().security.BTM_SecRegister(&bta_security); } /** Initialises the BT device security manager */ void bta_dm_sec_enable(tBTA_DM_SEC_CBACK* p_sec_cback) { /* make sure security callback is saved - if no callback, do not erase the previous one, it could be an error recovery mechanism */ - if (p_sec_cback != NULL) bta_dm_sec_cb.p_sec_cback = p_sec_cback; + if (p_sec_cback != NULL) { + bta_dm_sec_cb.p_sec_cback = p_sec_cback; + } } void bta_dm_remote_key_missing(const RawAddress bd_addr) { @@ -120,23 +116,21 @@ void bta_dm_remote_key_missing(const RawAddress bd_addr) { } /** Bonds with peer device */ -void bta_dm_bond(const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type, - tBT_TRANSPORT transport, tBT_DEVICE_TYPE device_type) { - log::debug("Bonding with peer device:{} type:{} transport:{} type:{}", - bd_addr, AddressTypeText(addr_type), bt_transport_text(transport), - DeviceTypeText(device_type)); +void bta_dm_bond(const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type, tBT_TRANSPORT transport, + tBT_DEVICE_TYPE device_type) { + log::debug("Bonding with peer device:{} type:{} transport:{} type:{}", bd_addr, + AddressTypeText(addr_type), bt_transport_text(transport), DeviceTypeText(device_type)); tBTA_DM_SEC sec_event; - tBTM_STATUS status = get_btm_client_interface().security.BTM_SecBond( - bd_addr, addr_type, transport, device_type); + tBTM_STATUS status = get_btm_client_interface().security.BTM_SecBond(bd_addr, addr_type, + transport, device_type); if (bta_dm_sec_cb.p_sec_cback && (status != BTM_CMD_STARTED)) { memset(&sec_event, 0, sizeof(tBTA_DM_SEC)); sec_event.auth_cmpl.bd_addr = bd_addr; - bd_name_from_char_pointer( - sec_event.auth_cmpl.bd_name, - get_btm_client_interface().security.BTM_SecReadDevName(bd_addr)); + bd_name_from_char_pointer(sec_event.auth_cmpl.bd_name, + get_btm_client_interface().security.BTM_SecReadDevName(bd_addr)); /* taken care of by memset [above] sec_event.auth_cmpl.key_present = false; @@ -162,8 +156,7 @@ void bta_dm_bond_cancel(const RawAddress& bd_addr) { status = get_btm_client_interface().security.BTM_SecBondCancel(bd_addr); - if (bta_dm_sec_cb.p_sec_cback && - (status != BTM_CMD_STARTED && status != BTM_SUCCESS)) { + if (bta_dm_sec_cb.p_sec_cback && (status != BTM_CMD_STARTED && status != BTM_SUCCESS)) { sec_event.bond_cancel_cmpl.result = BTA_FAILURE; bta_dm_sec_cb.p_sec_cback(BTA_DM_BOND_CANCEL_CMPL_EVT, &sec_event); @@ -173,25 +166,23 @@ void bta_dm_bond_cancel(const RawAddress& bd_addr) { /** Send the pin_reply to a request from BTM */ void bta_dm_pin_reply(std::unique_ptr msg) { if (msg->accept) { - get_btm_client_interface().security.BTM_PINCodeReply( - msg->bd_addr, BTM_SUCCESS, msg->pin_len, msg->p_pin); + get_btm_client_interface().security.BTM_PINCodeReply(msg->bd_addr, BTM_SUCCESS, msg->pin_len, + msg->p_pin); } else { - get_btm_client_interface().security.BTM_PINCodeReply( - msg->bd_addr, BTM_NOT_AUTHORIZED, 0, NULL); + get_btm_client_interface().security.BTM_PINCodeReply(msg->bd_addr, BTM_NOT_AUTHORIZED, 0, NULL); } } /** Send the user confirm request reply in response to a request from BTM */ void bta_dm_confirm(const RawAddress& bd_addr, bool accept) { get_btm_client_interface().security.BTM_SecConfirmReqReply( - accept ? BTM_SUCCESS : BTM_NOT_AUTHORIZED, BT_TRANSPORT_BR_EDR, bd_addr); + accept ? BTM_SUCCESS : BTM_NOT_AUTHORIZED, BT_TRANSPORT_BR_EDR, bd_addr); } /** respond to the OOB data request for the remote device from BTM */ void bta_dm_ci_rmt_oob_act(std::unique_ptr msg) { get_btm_client_interface().security.BTM_RemoteOobDataReply( - msg->accept ? BTM_SUCCESS : BTM_NOT_AUTHORIZED, msg->bd_addr, msg->c, - msg->r); + msg->accept ? BTM_SUCCESS : BTM_NOT_AUTHORIZED, msg->bd_addr, msg->c, msg->r); } /******************************************************************************* @@ -216,11 +207,11 @@ static void bta_dm_pinname_cback(const tBTM_REMOTE_DEV_NAME* p_data) { if (p_result && p_result->status == BTM_SUCCESS) { bd_name_copy(sec_event.cfm_req.bd_name, p_result->remote_bd_name); - } else /* No name found */ + } else { /* No name found */ sec_event.cfm_req.bd_name[0] = 0; + } - sec_event.key_notif.passkey = - bta_dm_sec_cb.num_val; /* get PIN code numeric number */ + sec_event.key_notif.passkey = bta_dm_sec_cb.num_val; /* get PIN code numeric number */ /* 1 additional event data fields for this event */ sec_event.cfm_req.just_works = bta_dm_sec_cb.just_works; @@ -237,15 +228,17 @@ static void bta_dm_pinname_cback(const tBTM_REMOTE_DEV_NAME* p_data) { if (p_result && p_result->status == BTM_SUCCESS) { bd_name_copy(sec_event.pin_req.bd_name, p_result->remote_bd_name); - } else /* No name found */ + } else { /* No name found */ sec_event.pin_req.bd_name[0] = 0; + } event = bta_dm_sec_cb.pin_evt; - sec_event.key_notif.passkey = - bta_dm_sec_cb.num_val; /* get PIN code numeric number */ + sec_event.key_notif.passkey = bta_dm_sec_cb.num_val; /* get PIN code numeric number */ } - if (bta_dm_sec_cb.p_sec_cback) bta_dm_sec_cb.p_sec_cback(event, &sec_event); + if (bta_dm_sec_cb.p_sec_cback) { + bta_dm_sec_cb.p_sec_cback(event, &sec_event); + } } /******************************************************************************* @@ -259,7 +252,9 @@ static void bta_dm_pinname_cback(const tBTM_REMOTE_DEV_NAME* p_data) { ******************************************************************************/ static uint8_t bta_dm_pin_cback(const RawAddress& bd_addr, DEV_CLASS dev_class, const BD_NAME bd_name, bool min_16_digit) { - if (!bta_dm_sec_cb.p_sec_cback) return BTM_NOT_AUTHORIZED; + if (!bta_dm_sec_cb.p_sec_cback) { + return BTM_NOT_AUTHORIZED; + } /* If the device name is not known, save bdaddr and devclass and initiate a * name request */ @@ -268,18 +263,18 @@ static uint8_t bta_dm_pin_cback(const RawAddress& bd_addr, DEV_CLASS dev_class, bta_dm_sec_cb.pin_bd_addr = bd_addr; bta_dm_sec_cb.pin_dev_class = dev_class; if ((get_btm_client_interface().peer.BTM_ReadRemoteDeviceName( - bd_addr, bta_dm_pinname_cback, BT_TRANSPORT_BR_EDR)) == - BTM_CMD_STARTED) + bd_addr, bta_dm_pinname_cback, BT_TRANSPORT_BR_EDR)) == BTM_CMD_STARTED) { return BTM_CMD_STARTED; + } log::warn("Failed to start Remote Name Request, addr:{}", bd_addr); } tBTA_DM_SEC sec_event = {.pin_req = { - .bd_addr = bd_addr, - .dev_class = dev_class, - .bd_name = "", - .min_16_digit = min_16_digit, + .bd_addr = bd_addr, + .dev_class = dev_class, + .bd_name = "", + .min_16_digit = min_16_digit, }}; bd_name_copy(sec_event.pin_req.bd_name, bd_name); @@ -296,10 +291,9 @@ static uint8_t bta_dm_pin_cback(const RawAddress& bd_addr, DEV_CLASS dev_class, * Returns void * ******************************************************************************/ -static uint8_t bta_dm_new_link_key_cback(const RawAddress& bd_addr, - DEV_CLASS /* dev_class */, - BD_NAME bd_name, const LinkKey& key, - uint8_t key_type, bool is_ctkd) { +static uint8_t bta_dm_new_link_key_cback(const RawAddress& bd_addr, DEV_CLASS /* dev_class */, + BD_NAME bd_name, const LinkKey& key, uint8_t key_type, + bool is_ctkd) { tBTA_DM_SEC sec_event; tBTA_DM_AUTH_CMPL* p_auth_cmpl; tBTA_DM_SEC_EVT event = BTA_DM_AUTH_CMPL_EVT; @@ -320,16 +314,19 @@ static uint8_t bta_dm_new_link_key_cback(const RawAddress& bd_addr, sec_event.auth_cmpl.fail_reason = HCI_SUCCESS; // Report the BR link key based on the BR/EDR address and type - get_btm_client_interface().peer.BTM_ReadDevInfo( - bd_addr, &sec_event.auth_cmpl.dev_type, &sec_event.auth_cmpl.addr_type); - if (bta_dm_sec_cb.p_sec_cback) bta_dm_sec_cb.p_sec_cback(event, &sec_event); + get_btm_client_interface().peer.BTM_ReadDevInfo(bd_addr, &sec_event.auth_cmpl.dev_type, + &sec_event.auth_cmpl.addr_type); + if (bta_dm_sec_cb.p_sec_cback) { + bta_dm_sec_cb.p_sec_cback(event, &sec_event); + } // Setting remove_dev_pending flag to false, where it will avoid deleting // the // security device record when the ACL connection link goes down in case of // reconnection. - if (bta_dm_cb.device_list.count) + if (bta_dm_cb.device_list.count) { bta_dm_reset_sec_dev_pending(p_auth_cmpl->bd_addr); + } return BTM_CMD_STARTED; } @@ -344,24 +341,22 @@ static uint8_t bta_dm_new_link_key_cback(const RawAddress& bd_addr, * ******************************************************************************/ static void bta_dm_authentication_complete_cback(const RawAddress& bd_addr, - DEV_CLASS /* dev_class */, - BD_NAME bd_name, + DEV_CLASS /* dev_class */, BD_NAME bd_name, tHCI_REASON reason) { if (reason != HCI_SUCCESS) { if (bta_dm_sec_cb.p_sec_cback) { // Build out the security event data structure tBTA_DM_SEC sec_event = { - .auth_cmpl = - { - .bd_addr = bd_addr, - }, + .auth_cmpl = + { + .bd_addr = bd_addr, + }, }; bd_name_copy(sec_event.auth_cmpl.bd_name, bd_name); // Report the BR link key based on the BR/EDR address and type - get_btm_client_interface().peer.BTM_ReadDevInfo( - bd_addr, &sec_event.auth_cmpl.dev_type, - &sec_event.auth_cmpl.addr_type); + get_btm_client_interface().peer.BTM_ReadDevInfo(bd_addr, &sec_event.auth_cmpl.dev_type, + &sec_event.auth_cmpl.addr_type); sec_event.auth_cmpl.fail_reason = reason; bta_dm_sec_cb.p_sec_cback(BTA_DM_AUTH_CMPL_EVT, &sec_event); @@ -391,14 +386,15 @@ static void bta_dm_authentication_complete_cback(const RawAddress& bd_addr, * Returns void * ******************************************************************************/ -static tBTM_STATUS bta_dm_sp_cback(tBTM_SP_EVT event, - tBTM_SP_EVT_DATA* p_data) { +static tBTM_STATUS bta_dm_sp_cback(tBTM_SP_EVT event, tBTM_SP_EVT_DATA* p_data) { tBTM_STATUS status = BTM_CMD_STARTED; tBTA_DM_SEC sec_event = {}; tBTA_DM_SEC_EVT pin_evt = BTA_DM_SP_KEY_NOTIF_EVT; log::verbose("event:{}", sp_evt_to_text(event)); - if (!bta_dm_sec_cb.p_sec_cback) return BTM_NOT_AUTHORIZED; + if (!bta_dm_sec_cb.p_sec_cback) { + return BTM_NOT_AUTHORIZED; + } bool sp_rmt_result = false; /* TODO_SP */ @@ -407,18 +403,16 @@ static tBTM_STATUS bta_dm_sp_cback(tBTM_SP_EVT event, /* translate auth_req */ btif_dm_set_oob_for_io_req(&p_data->io_req.oob_data); btif_dm_proc_io_req(&p_data->io_req.auth_req, p_data->io_req.is_orig); - log::verbose("io mitm: {} oob_data:{}", p_data->io_req.auth_req, - p_data->io_req.oob_data); + log::verbose("io mitm: {} oob_data:{}", p_data->io_req.auth_req, p_data->io_req.oob_data); break; case BTM_SP_IO_RSP_EVT: - btif_dm_proc_io_rsp(p_data->io_rsp.bd_addr, p_data->io_rsp.io_cap, - p_data->io_rsp.oob_data, p_data->io_rsp.auth_req); + btif_dm_proc_io_rsp(p_data->io_rsp.bd_addr, p_data->io_rsp.io_cap, p_data->io_rsp.oob_data, + p_data->io_rsp.auth_req); break; case BTM_SP_CFM_REQ_EVT: pin_evt = BTA_DM_SP_CFM_REQ_EVT; - bta_dm_sec_cb.just_works = sec_event.cfm_req.just_works = - p_data->cfm_req.just_works; + bta_dm_sec_cb.just_works = sec_event.cfm_req.just_works = p_data->cfm_req.just_works; sec_event.cfm_req.loc_auth_req = p_data->cfm_req.loc_auth_req; sec_event.cfm_req.rmt_auth_req = p_data->cfm_req.rmt_auth_req; sec_event.cfm_req.loc_io_caps = p_data->cfm_req.loc_io_caps; @@ -431,8 +425,7 @@ static tBTM_STATUS bta_dm_sp_cback(tBTM_SP_EVT event, case BTM_SP_KEY_NOTIF_EVT: // TODO PleaseFix: This assignment only works with event // BTM_SP_KEY_NOTIF_EVT - bta_dm_sec_cb.num_val = sec_event.key_notif.passkey = - p_data->key_notif.passkey; + bta_dm_sec_cb.num_val = sec_event.key_notif.passkey = p_data->key_notif.passkey; if (BTM_SP_CFM_REQ_EVT == event) { /* Due to the switch case falling through below to @@ -457,10 +450,8 @@ static tBTM_STATUS bta_dm_sp_cback(tBTM_SP_EVT event, log::info("CoD: bta_dm_sec_cb.pin_dev_class = {}", dev_class_text(bta_dm_sec_cb.pin_dev_class)); { - const tBTM_STATUS btm_status = - get_btm_client_interface().peer.BTM_ReadRemoteDeviceName( - p_data->cfm_req.bd_addr, bta_dm_pinname_cback, - BT_TRANSPORT_BR_EDR); + const tBTM_STATUS btm_status = get_btm_client_interface().peer.BTM_ReadRemoteDeviceName( + p_data->cfm_req.bd_addr, bta_dm_pinname_cback, BT_TRANSPORT_BR_EDR); switch (btm_status) { case BTM_CMD_STARTED: return btm_status; @@ -481,11 +472,11 @@ static tBTM_STATUS bta_dm_sp_cback(tBTM_SP_EVT event, bta_dm_sec_cb.pin_bd_addr = p_data->key_notif.bd_addr; bta_dm_sec_cb.pin_dev_class = p_data->key_notif.dev_class; if ((get_btm_client_interface().peer.BTM_ReadRemoteDeviceName( - p_data->key_notif.bd_addr, bta_dm_pinname_cback, - BT_TRANSPORT_BR_EDR)) == BTM_CMD_STARTED) + p_data->key_notif.bd_addr, bta_dm_pinname_cback, BT_TRANSPORT_BR_EDR)) == + BTM_CMD_STARTED) { return BTM_CMD_STARTED; - log::warn("Failed to start Remote Name Request, addr:{}", - p_data->key_notif.bd_addr); + } + log::warn("Failed to start Remote Name Request, addr:{}", p_data->key_notif.bd_addr); } else { sec_event.key_notif.bd_addr = p_data->key_notif.bd_addr; sec_event.key_notif.dev_class = p_data->key_notif.dev_class; @@ -500,8 +491,7 @@ static tBTM_STATUS bta_dm_sp_cback(tBTM_SP_EVT event, case BTM_SP_LOC_OOB_EVT: // BR/EDR OOB pairing is not supported with Secure Connections - btif_dm_proc_loc_oob(BT_TRANSPORT_BR_EDR, - (bool)(p_data->loc_oob.status == BTM_SUCCESS), + btif_dm_proc_loc_oob(BT_TRANSPORT_BR_EDR, (bool)(p_data->loc_oob.status == BTM_SUCCESS), p_data->loc_oob.c_192, p_data->loc_oob.r_192); break; @@ -561,14 +551,10 @@ static void bta_dm_reset_sec_dev_pending(const RawAddress& remote_bd_addr) { * ******************************************************************************/ static void bta_dm_remove_sec_dev_entry(const RawAddress& remote_bd_addr) { - if (get_btm_client_interface().peer.BTM_IsAclConnectionUp(remote_bd_addr, - BT_TRANSPORT_LE) || - get_btm_client_interface().peer.BTM_IsAclConnectionUp( - remote_bd_addr, BT_TRANSPORT_BR_EDR)) { - log::debug("ACL is not down. Schedule for Dev Removal when ACL closes:{}", - remote_bd_addr); - get_btm_client_interface().security.BTM_SecClearSecurityFlags( - remote_bd_addr); + if (get_btm_client_interface().peer.BTM_IsAclConnectionUp(remote_bd_addr, BT_TRANSPORT_LE) || + get_btm_client_interface().peer.BTM_IsAclConnectionUp(remote_bd_addr, BT_TRANSPORT_BR_EDR)) { + log::debug("ACL is not down. Schedule for Dev Removal when ACL closes:{}", remote_bd_addr); + get_btm_client_interface().security.BTM_SecClearSecurityFlags(remote_bd_addr); for (int i = 0; i < bta_dm_cb.device_list.count; i++) { auto& dev = bta_dm_cb.device_list.peer_device[i]; if (dev.peer_bdaddr == remote_bd_addr) { @@ -597,30 +583,33 @@ static void bta_dm_remove_sec_dev_entry(const RawAddress& remote_bd_addr) { static void bta_dm_bond_cancel_complete_cback(tBTM_STATUS result) { tBTA_DM_SEC sec_event; - if (result == BTM_SUCCESS) + if (result == BTM_SUCCESS) { sec_event.bond_cancel_cmpl.result = BTA_SUCCESS; - else + } else { sec_event.bond_cancel_cmpl.result = BTA_FAILURE; + } if (bta_dm_sec_cb.p_sec_cback) { bta_dm_sec_cb.p_sec_cback(BTA_DM_BOND_CANCEL_CMPL_EVT, &sec_event); } } -static void ble_io_req(const RawAddress& bd_addr, tBTM_IO_CAP* p_io_cap, - tBTM_OOB_DATA* p_oob_data, tBTM_LE_AUTH_REQ* p_auth_req, - uint8_t* p_max_key_size, tBTM_LE_KEY_TYPE* p_init_key, - tBTM_LE_KEY_TYPE* p_resp_key) { +static void ble_io_req(const RawAddress& bd_addr, tBTM_IO_CAP* p_io_cap, tBTM_OOB_DATA* p_oob_data, + tBTM_LE_AUTH_REQ* p_auth_req, uint8_t* p_max_key_size, + tBTM_LE_KEY_TYPE* p_init_key, tBTM_LE_KEY_TYPE* p_resp_key) { /* Retrieve the properties from file system if possible */ tBTE_APPL_CFG nv_config; - if (btif_dm_get_smp_config(&nv_config)) bte_appl_cfg = nv_config; + if (btif_dm_get_smp_config(&nv_config)) { + bte_appl_cfg = nv_config; + } /* *p_auth_req by default is false for devices with NoInputNoOutput; true for * other devices. */ - if (bte_appl_cfg.ble_auth_req) - *p_auth_req = bte_appl_cfg.ble_auth_req | - (bte_appl_cfg.ble_auth_req & 0x04) | ((*p_auth_req) & 0x04); + if (bte_appl_cfg.ble_auth_req) { + *p_auth_req = + bte_appl_cfg.ble_auth_req | (bte_appl_cfg.ble_auth_req & 0x04) | ((*p_auth_req) & 0x04); + } /* if OOB is not supported, this call-out function does not need to do * anything @@ -633,17 +622,21 @@ static void ble_io_req(const RawAddress& bd_addr, tBTM_IO_CAP* p_io_cap, btif_dm_set_oob_for_le_io_req(bd_addr, p_oob_data, p_auth_req); - if (bte_appl_cfg.ble_io_cap <= 4) + if (bte_appl_cfg.ble_io_cap <= 4) { *p_io_cap = static_cast(bte_appl_cfg.ble_io_cap); + } - if (bte_appl_cfg.ble_init_key <= BTM_BLE_INITIATOR_KEY_SIZE) + if (bte_appl_cfg.ble_init_key <= BTM_BLE_INITIATOR_KEY_SIZE) { *p_init_key = bte_appl_cfg.ble_init_key; + } - if (bte_appl_cfg.ble_resp_key <= BTM_BLE_RESPONDER_KEY_SIZE) + if (bte_appl_cfg.ble_resp_key <= BTM_BLE_RESPONDER_KEY_SIZE) { *p_resp_key = bte_appl_cfg.ble_resp_key; + } - if (bte_appl_cfg.ble_max_key_size > 7 && bte_appl_cfg.ble_max_key_size <= 16) + if (bte_appl_cfg.ble_max_key_size > 7 && bte_appl_cfg.ble_max_key_size <= 16) { *p_max_key_size = bte_appl_cfg.ble_max_key_size; + } } /******************************************************************************* @@ -663,39 +656,37 @@ static uint8_t bta_dm_ble_smp_cback(tBTM_LE_EVT event, const RawAddress& bda, log::debug("addr:{},event:{}", bda, ble_evt_to_text(event)); - if (!bta_dm_sec_cb.p_sec_cback) return BTM_NOT_AUTHORIZED; + if (!bta_dm_sec_cb.p_sec_cback) { + return BTM_NOT_AUTHORIZED; + } memset(&sec_event, 0, sizeof(tBTA_DM_SEC)); switch (event) { case BTM_LE_IO_REQ_EVT: - ble_io_req(bda, &p_data->io_req.io_cap, &p_data->io_req.oob_data, - &p_data->io_req.auth_req, &p_data->io_req.max_key_size, - &p_data->io_req.init_keys, &p_data->io_req.resp_keys); - log::info("io mitm:{} oob_data:{}", p_data->io_req.auth_req, - p_data->io_req.oob_data); + ble_io_req(bda, &p_data->io_req.io_cap, &p_data->io_req.oob_data, &p_data->io_req.auth_req, + &p_data->io_req.max_key_size, &p_data->io_req.init_keys, + &p_data->io_req.resp_keys); + log::info("io mitm:{} oob_data:{}", p_data->io_req.auth_req, p_data->io_req.oob_data); break; case BTM_LE_CONSENT_REQ_EVT: sec_event.ble_req.bd_addr = bda; - bd_name_from_char_pointer( - sec_event.ble_req.bd_name, - get_btm_client_interface().security.BTM_SecReadDevName(bda)); + bd_name_from_char_pointer(sec_event.ble_req.bd_name, + get_btm_client_interface().security.BTM_SecReadDevName(bda)); bta_dm_sec_cb.p_sec_cback(BTA_DM_BLE_CONSENT_REQ_EVT, &sec_event); break; case BTM_LE_SEC_REQUEST_EVT: sec_event.ble_req.bd_addr = bda; - bd_name_from_char_pointer( - sec_event.ble_req.bd_name, - get_btm_client_interface().security.BTM_SecReadDevName(bda)); + bd_name_from_char_pointer(sec_event.ble_req.bd_name, + get_btm_client_interface().security.BTM_SecReadDevName(bda)); bta_dm_sec_cb.p_sec_cback(BTA_DM_BLE_SEC_REQ_EVT, &sec_event); break; case BTM_LE_KEY_NOTIF_EVT: sec_event.key_notif.bd_addr = bda; - bd_name_from_char_pointer( - sec_event.key_notif.bd_name, - get_btm_client_interface().security.BTM_SecReadDevName(bda)); + bd_name_from_char_pointer(sec_event.key_notif.bd_name, + get_btm_client_interface().security.BTM_SecReadDevName(bda)); sec_event.key_notif.passkey = p_data->key_notif; bta_dm_sec_cb.p_sec_cback(BTA_DM_BLE_PASSKEY_NOTIF_EVT, &sec_event); break; @@ -739,27 +730,22 @@ static uint8_t bta_dm_ble_smp_cback(tBTM_LE_EVT event, const RawAddress& bda, case BTM_LE_COMPLT_EVT: sec_event.auth_cmpl.bd_addr = bda; - get_btm_client_interface().peer.BTM_ReadDevInfo( - bda, &sec_event.auth_cmpl.dev_type, &sec_event.auth_cmpl.addr_type); - bd_name_from_char_pointer( - sec_event.auth_cmpl.bd_name, - get_btm_client_interface().security.BTM_SecReadDevName(bda)); + get_btm_client_interface().peer.BTM_ReadDevInfo(bda, &sec_event.auth_cmpl.dev_type, + &sec_event.auth_cmpl.addr_type); + bd_name_from_char_pointer(sec_event.auth_cmpl.bd_name, + get_btm_client_interface().security.BTM_SecReadDevName(bda)); if (p_data->complt.reason != SMP_SUCCESS) { // TODO This is not a proper use of this type - sec_event.auth_cmpl.fail_reason = - static_cast(BTA_DM_AUTH_CONVERT_SMP_CODE( - (static_cast(p_data->complt.reason)))); + sec_event.auth_cmpl.fail_reason = static_cast( + BTA_DM_AUTH_CONVERT_SMP_CODE(static_cast(p_data->complt.reason))); - if (btm_sec_is_a_bonded_dev(bda) && - p_data->complt.reason == SMP_CONN_TOUT && + if (btm_sec_is_a_bonded_dev(bda) && p_data->complt.reason == SMP_CONN_TOUT && !p_data->complt.smp_over_br) { // Bonded device failed to encrypt - to test this remove battery from // HID device right after connection, but before encryption is // established - log::warn( - "bonded device disconnected when encrypting - no reason to " - "unbond"); + log::warn("bonded device disconnected when encrypting - no reason to unbond"); } else { /* delete this device entry from Sec Dev DB */ bta_dm_remove_sec_dev_entry(bda); @@ -767,8 +753,9 @@ static uint8_t bta_dm_ble_smp_cback(tBTM_LE_EVT event, const RawAddress& bda, } else { sec_event.auth_cmpl.success = true; - if (!p_data->complt.smp_over_br) + if (!p_data->complt.smp_over_br) { GATT_ConfigServiceChangeCCC(bda, true, BT_TRANSPORT_LE); + } } if (bta_dm_sec_cb.p_sec_cback) { @@ -799,8 +786,8 @@ static uint8_t bta_dm_ble_smp_cback(tBTM_LE_EVT event, const RawAddress& bda, * Returns None * ******************************************************************************/ -void bta_dm_encrypt_cback(RawAddress bd_addr, tBT_TRANSPORT transport, - void* /* p_ref_data */, tBTM_STATUS result) { +void bta_dm_encrypt_cback(RawAddress bd_addr, tBT_TRANSPORT transport, void* /* p_ref_data */, + tBTM_STATUS result) { tBTA_DM_ENCRYPT_CBACK* p_callback = nullptr; tBTA_DM_PEER_DEVICE* device = find_connected_device(bd_addr, transport); if (device != nullptr) { @@ -809,9 +796,8 @@ void bta_dm_encrypt_cback(RawAddress bd_addr, tBT_TRANSPORT transport, } log::debug("Encrypted:{:c}, peer:{} transport:{} status:{} callback:{:c}", - result == BTM_SUCCESS ? 'T' : 'F', bd_addr, - bt_transport_text(transport), btm_status_text(result), - (p_callback) ? 'T' : 'F'); + result == BTM_SUCCESS ? 'T' : 'F', bd_addr, bt_transport_text(transport), + btm_status_text(result), (p_callback) ? 'T' : 'F'); tBTA_STATUS bta_status = BTA_SUCCESS; switch (result) { @@ -838,8 +824,7 @@ void bta_dm_encrypt_cback(RawAddress bd_addr, tBT_TRANSPORT transport, /**This function to encrypt the link */ void bta_dm_set_encryption(const RawAddress& bd_addr, tBT_TRANSPORT transport, - tBTA_DM_ENCRYPT_CBACK* p_callback, - tBTM_BLE_SEC_ACT sec_act) { + tBTA_DM_ENCRYPT_CBACK* p_callback, tBTM_BLE_SEC_ACT sec_act) { if (p_callback == nullptr) { log::error("callback is not provided,addr:{}", bd_addr); return; @@ -847,29 +832,25 @@ void bta_dm_set_encryption(const RawAddress& bd_addr, tBT_TRANSPORT transport, tBTA_DM_PEER_DEVICE* device = find_connected_device(bd_addr, transport); if (device == nullptr) { - log::error("Unable to find active ACL connection device:{} transport:{}", - bd_addr, bt_transport_text(transport)); + log::error("Unable to find active ACL connection device:{} transport:{}", bd_addr, + bt_transport_text(transport)); return; } if (device->p_encrypt_cback) { - log::error( - "Unable to start encryption as already in progress peer:{} " - "transport:{}", - bd_addr, bt_transport_text(transport)); + log::error("Unable to start encryption as already in progress peer:{} transport:{}", bd_addr, + bt_transport_text(transport)); (*p_callback)(bd_addr, transport, BTA_BUSY); return; } if (get_btm_client_interface().security.BTM_SetEncryption( - bd_addr, transport, bta_dm_encrypt_cback, NULL, sec_act) == - BTM_CMD_STARTED) { + bd_addr, transport, bta_dm_encrypt_cback, NULL, sec_act) == BTM_CMD_STARTED) { device->p_encrypt_cback = p_callback; - log::debug("Started encryption peer:{} transport:{}", bd_addr, - bt_transport_text(transport)); + log::debug("Started encryption peer:{} transport:{}", bd_addr, bt_transport_text(transport)); } else { - log::error("Unable to start encryption process peer:{} transport:{}", - bd_addr, bt_transport_text(transport)); + log::error("Unable to start encryption process peer:{} transport:{}", bd_addr, + bt_transport_text(transport)); } } @@ -883,20 +864,18 @@ void bta_dm_set_encryption(const RawAddress& bd_addr, tBT_TRANSPORT transport, * Returns void * ******************************************************************************/ -static void bta_dm_ble_id_key_cback(uint8_t key_type, - tBTM_BLE_LOCAL_KEYS* p_key) { +static void bta_dm_ble_id_key_cback(uint8_t key_type, tBTM_BLE_LOCAL_KEYS* p_key) { switch (key_type) { case BTM_BLE_KEY_TYPE_ID: case BTM_BLE_KEY_TYPE_ER: if (bta_dm_sec_cb.p_sec_cback) { tBTA_DM_SEC dm_key = { - .ble_id_keys = {}, + .ble_id_keys = {}, }; memcpy(&dm_key.ble_id_keys, p_key, sizeof(tBTM_BLE_LOCAL_KEYS)); - tBTA_DM_SEC_EVT evt = (key_type == BTM_BLE_KEY_TYPE_ID) - ? BTA_DM_BLE_LOCAL_IR_EVT - : BTA_DM_BLE_LOCAL_ER_EVT; + tBTA_DM_SEC_EVT evt = (key_type == BTM_BLE_KEY_TYPE_ID) ? BTA_DM_BLE_LOCAL_IR_EVT + : BTA_DM_BLE_LOCAL_ER_EVT; bta_dm_sec_cb.p_sec_cback(evt, &dm_key); } break; @@ -919,7 +898,7 @@ static void bta_dm_ble_id_key_cback(uint8_t key_type, ******************************************************************************/ static uint8_t bta_dm_sirk_verifiction_cback(const RawAddress& bd_addr) { tBTA_DM_SEC sec_event = {.ble_req = { - .bd_addr = bd_addr, + .bd_addr = bd_addr, }}; if (bta_dm_sec_cb.p_sec_sirk_cback) { @@ -948,8 +927,8 @@ static uint8_t bta_dm_sirk_verifiction_cback(const RawAddress& bd_addr) { ******************************************************************************/ void bta_dm_add_blekey(const RawAddress& bd_addr, tBTA_LE_KEY_VALUE blekey, tBTM_LE_KEY_TYPE key_type) { - get_btm_client_interface().security.BTM_SecAddBleKey( - bd_addr, (tBTM_LE_KEY_VALUE*)&blekey, key_type); + get_btm_client_interface().security.BTM_SecAddBleKey(bd_addr, (tBTM_LE_KEY_VALUE*)&blekey, + key_type); } /******************************************************************************* @@ -966,8 +945,7 @@ void bta_dm_add_blekey(const RawAddress& bd_addr, tBTA_LE_KEY_VALUE blekey, ******************************************************************************/ void bta_dm_add_ble_device(const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type, tBT_DEVICE_TYPE dev_type) { - get_btm_client_interface().security.BTM_SecAddBleDevice(bd_addr, dev_type, - addr_type); + get_btm_client_interface().security.BTM_SecAddBleDevice(bd_addr, dev_type, addr_type); } /******************************************************************************* @@ -982,23 +960,20 @@ void bta_dm_add_ble_device(const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type, * Parameters: * ******************************************************************************/ -void bta_dm_ble_passkey_reply(const RawAddress& bd_addr, bool accept, - uint32_t passkey) { +void bta_dm_ble_passkey_reply(const RawAddress& bd_addr, bool accept, uint32_t passkey) { get_btm_client_interface().security.BTM_BlePasskeyReply( - bd_addr, accept ? BTM_SUCCESS : BTM_NOT_AUTHORIZED, passkey); + bd_addr, accept ? BTM_SUCCESS : BTM_NOT_AUTHORIZED, passkey); } /** This is response to SM numeric comparison request submitted to application. */ void bta_dm_ble_confirm_reply(const RawAddress& bd_addr, bool accept) { get_btm_client_interface().security.BTM_SecConfirmReqReply( - accept ? BTM_SUCCESS : BTM_NOT_AUTHORIZED, BT_TRANSPORT_LE, bd_addr); + accept ? BTM_SUCCESS : BTM_NOT_AUTHORIZED, BT_TRANSPORT_LE, bd_addr); } /** This function set the local device LE privacy settings. */ -void bta_dm_ble_config_local_privacy(bool privacy_enable) { - BTM_BleConfigPrivacy(privacy_enable); -} +void bta_dm_ble_config_local_privacy(bool privacy_enable) { BTM_BleConfigPrivacy(privacy_enable); } namespace bluetooth { namespace legacy { diff --git a/system/bta/dm/bta_dm_sec_api.cc b/system/bta/dm/bta_dm_sec_api.cc index 572fa1f63d9..a5e59f54c18 100644 --- a/system/bta/dm/bta_dm_sec_api.cc +++ b/system/bta/dm/bta_dm_sec_api.cc @@ -37,13 +37,13 @@ using namespace bluetooth; /** This function initiates a bonding procedure with a peer device */ -void BTA_DmBond(const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type, - tBT_TRANSPORT transport, tBT_DEVICE_TYPE device_type) { +void BTA_DmBond(const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type, tBT_TRANSPORT transport, + tBT_DEVICE_TYPE device_type) { if (com::android::bluetooth::flags::synchronous_bta_sec()) { bta_dm_bond(bd_addr, addr_type, transport, device_type); } else { - do_in_main_thread(FROM_HERE, base::BindOnce(bta_dm_bond, bd_addr, addr_type, - transport, device_type)); + do_in_main_thread(FROM_HERE, + base::BindOnce(bta_dm_bond, bd_addr, addr_type, transport, device_type)); } } @@ -68,10 +68,8 @@ void BTA_DmBondCancel(const RawAddress& bd_addr) { * Returns void * ******************************************************************************/ -void BTA_DmPinReply(const RawAddress& bd_addr, bool accept, uint8_t pin_len, - uint8_t* p_pin) { - std::unique_ptr msg = - std::make_unique(); +void BTA_DmPinReply(const RawAddress& bd_addr, bool accept, uint8_t pin_len, uint8_t* p_pin) { + std::unique_ptr msg = std::make_unique(); msg->bd_addr = bd_addr; msg->accept = accept; @@ -83,8 +81,7 @@ void BTA_DmPinReply(const RawAddress& bd_addr, bool accept, uint8_t pin_len, if (com::android::bluetooth::flags::synchronous_bta_sec()) { bta_dm_pin_reply(std::move(msg)); } else { - do_in_main_thread(FROM_HERE, - base::Bind(bta_dm_pin_reply, base::Passed(&msg))); + do_in_main_thread(FROM_HERE, base::Bind(bta_dm_pin_reply, base::Passed(&msg))); } } @@ -123,8 +120,7 @@ void BTA_DmConfirm(const RawAddress& bd_addr, bool accept) { if (com::android::bluetooth::flags::synchronous_bta_sec()) { bta_dm_confirm(bd_addr, accept); } else { - do_in_main_thread(FROM_HERE, - base::BindOnce(bta_dm_confirm, bd_addr, accept)); + do_in_main_thread(FROM_HERE, base::BindOnce(bta_dm_confirm, bd_addr, accept)); } } @@ -138,11 +134,10 @@ void BTA_DmConfirm(const RawAddress& bd_addr, bool accept) { * Returns void * ******************************************************************************/ -void BTA_DmAddDevice(RawAddress bd_addr, DEV_CLASS dev_class, LinkKey link_key, - uint8_t key_type, uint8_t pin_length) { - auto closure = - base::Bind(get_btm_client_interface().security.BTM_SecAddDevice, bd_addr, - dev_class, link_key, key_type, pin_length); +void BTA_DmAddDevice(RawAddress bd_addr, DEV_CLASS dev_class, LinkKey link_key, uint8_t key_type, + uint8_t pin_length) { + auto closure = base::Bind(get_btm_client_interface().security.BTM_SecAddDevice, bd_addr, + dev_class, link_key, key_type, pin_length); if (com::android::bluetooth::flags::synchronous_bta_sec()) { closure.Run(); @@ -183,8 +178,7 @@ void BTA_DmAddBleKey(const RawAddress& bd_addr, tBTA_LE_KEY_VALUE* p_le_key, if (com::android::bluetooth::flags::synchronous_bta_sec()) { bta_dm_add_blekey(bd_addr, *p_le_key, key_type); } else { - do_in_main_thread(FROM_HERE, base::BindOnce(bta_dm_add_blekey, bd_addr, - *p_le_key, key_type)); + do_in_main_thread(FROM_HERE, base::BindOnce(bta_dm_add_blekey, bd_addr, *p_le_key, key_type)); } } @@ -208,8 +202,8 @@ void BTA_DmAddBleDevice(const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type, if (com::android::bluetooth::flags::synchronous_bta_sec()) { bta_dm_add_ble_device(bd_addr, addr_type, dev_type); } else { - do_in_main_thread(FROM_HERE, base::BindOnce(bta_dm_add_ble_device, bd_addr, - addr_type, dev_type)); + do_in_main_thread(FROM_HERE, + base::BindOnce(bta_dm_add_ble_device, bd_addr, addr_type, dev_type)); } } @@ -227,14 +221,12 @@ void BTA_DmAddBleDevice(const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type, * Returns void * ******************************************************************************/ -void BTA_DmBlePasskeyReply(const RawAddress& bd_addr, bool accept, - uint32_t passkey) { +void BTA_DmBlePasskeyReply(const RawAddress& bd_addr, bool accept, uint32_t passkey) { if (com::android::bluetooth::flags::synchronous_bta_sec()) { bta_dm_ble_passkey_reply(bd_addr, accept, accept ? passkey : 0); } else { - do_in_main_thread(FROM_HERE, - base::BindOnce(bta_dm_ble_passkey_reply, bd_addr, accept, - accept ? passkey : 0)); + do_in_main_thread(FROM_HERE, base::BindOnce(bta_dm_ble_passkey_reply, bd_addr, accept, + accept ? passkey : 0)); } } @@ -255,8 +247,7 @@ void BTA_DmBleConfirmReply(const RawAddress& bd_addr, bool accept) { if (com::android::bluetooth::flags::synchronous_bta_sec()) { bta_dm_ble_confirm_reply(bd_addr, accept); } else { - do_in_main_thread( - FROM_HERE, base::BindOnce(bta_dm_ble_confirm_reply, bd_addr, accept)); + do_in_main_thread(FROM_HERE, base::BindOnce(bta_dm_ble_confirm_reply, bd_addr, accept)); } } @@ -272,13 +263,11 @@ void BTA_DmBleConfirmReply(const RawAddress& bd_addr, bool accept) { * Returns void * ******************************************************************************/ -void BTA_DmBleSecurityGrant(const RawAddress& bd_addr, - tBTA_DM_BLE_SEC_GRANT res) { +void BTA_DmBleSecurityGrant(const RawAddress& bd_addr, tBTA_DM_BLE_SEC_GRANT res) { if (com::android::bluetooth::flags::synchronous_bta_sec()) { BTM_SecurityGrant(bd_addr, res); } else { - do_in_main_thread(FROM_HERE, - base::BindOnce(BTM_SecurityGrant, bd_addr, res)); + do_in_main_thread(FROM_HERE, base::BindOnce(BTM_SecurityGrant, bd_addr, res)); } } @@ -305,15 +294,13 @@ void BTA_DmBleSecurityGrant(const RawAddress& bd_addr, * ******************************************************************************/ void BTA_DmSetEncryption(const RawAddress& bd_addr, tBT_TRANSPORT transport, - tBTA_DM_ENCRYPT_CBACK* p_callback, - tBTM_BLE_SEC_ACT sec_act) { + tBTA_DM_ENCRYPT_CBACK* p_callback, tBTM_BLE_SEC_ACT sec_act) { log::verbose(""); if (com::android::bluetooth::flags::synchronous_bta_sec()) { bta_dm_set_encryption(bd_addr, transport, p_callback, sec_act); } else { - do_in_main_thread(FROM_HERE, - base::BindOnce(bta_dm_set_encryption, bd_addr, transport, - p_callback, sec_act)); + do_in_main_thread(FROM_HERE, base::BindOnce(bta_dm_set_encryption, bd_addr, transport, + p_callback, sec_act)); } } @@ -334,8 +321,7 @@ void BTA_DmSirkSecCbRegister(tBTA_DM_SEC_CBACK* p_cback) { if (com::android::bluetooth::flags::synchronous_bta_sec()) { bta_dm_ble_sirk_sec_cb_register(p_cback); } else { - do_in_main_thread(FROM_HERE, - base::BindOnce(bta_dm_ble_sirk_sec_cb_register, p_cback)); + do_in_main_thread(FROM_HERE, base::BindOnce(bta_dm_ble_sirk_sec_cb_register, p_cback)); } } @@ -357,9 +343,7 @@ void BTA_DmSirkConfirmDeviceReply(const RawAddress& bd_addr, bool accept) { if (com::android::bluetooth::flags::synchronous_bta_sec()) { bta_dm_ble_sirk_confirm_device_reply(bd_addr, accept); } else { - do_in_main_thread( - FROM_HERE, - base::BindOnce(bta_dm_ble_sirk_confirm_device_reply, bd_addr, accept)); + do_in_main_thread(FROM_HERE, + base::BindOnce(bta_dm_ble_sirk_confirm_device_reply, bd_addr, accept)); } } - diff --git a/system/bta/dm/bta_dm_sec_int.h b/system/bta/dm/bta_dm_sec_int.h index 5ce80b6331b..540205dd99d 100644 --- a/system/bta/dm/bta_dm_sec_int.h +++ b/system/bta/dm/bta_dm_sec_int.h @@ -48,7 +48,7 @@ typedef struct { typedef struct { tBTA_DM_SEC_CBACK* p_sec_cback; tBTA_DM_SEC_CBACK* p_sec_sirk_cback; -/* Storage for pin code request parameters */ + /* Storage for pin code request parameters */ RawAddress pin_bd_addr; DEV_CLASS pin_dev_class; tBTA_DM_SEC_EVT pin_evt; @@ -72,13 +72,11 @@ void bta_dm_add_blekey(const RawAddress& bd_addr, tBTA_LE_KEY_VALUE blekey, tBTM_LE_KEY_TYPE key_type); void bta_dm_ble_config_local_privacy(bool privacy_enable); void bta_dm_ble_confirm_reply(const RawAddress& bd_addr, bool accept); -void bta_dm_ble_passkey_reply(const RawAddress& bd_addr, bool accept, - uint32_t passkey); -void bta_dm_ble_sirk_confirm_device_reply(const RawAddress& bd_addr, - bool accept); +void bta_dm_ble_passkey_reply(const RawAddress& bd_addr, bool accept, uint32_t passkey); +void bta_dm_ble_sirk_confirm_device_reply(const RawAddress& bd_addr, bool accept); void bta_dm_ble_sirk_sec_cb_register(tBTA_DM_SEC_CBACK* p_cback); -void bta_dm_bond(const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type, - tBT_TRANSPORT transport, tBT_DEVICE_TYPE device_type); +void bta_dm_bond(const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type, tBT_TRANSPORT transport, + tBT_DEVICE_TYPE device_type); void bta_dm_bond_cancel(const RawAddress& bd_addr); void bta_dm_remove_device(const RawAddress& bd_addr); void bta_dm_ci_rmt_oob_act(std::unique_ptr msg); @@ -89,6 +87,5 @@ void bta_dm_encrypt_cback(const RawAddress* bd_addr, tBT_TRANSPORT transport, void* /* p_ref_data */, tBTM_STATUS result); void bta_dm_pin_reply(std::unique_ptr msg); void bta_dm_set_encryption(const RawAddress& bd_addr, tBT_TRANSPORT transport, - tBTA_DM_ENCRYPT_CBACK* p_callback, - tBTM_BLE_SEC_ACT sec_act); + tBTA_DM_ENCRYPT_CBACK* p_callback, tBTM_BLE_SEC_ACT sec_act); void btm_dm_sec_init(); diff --git a/system/bta/gatt/bta_gattc_act.cc b/system/bta/gatt/bta_gattc_act.cc index 1cdeacae34f..65a6275f622 100644 --- a/system/bta/gatt/bta_gattc_act.cc +++ b/system/bta/gatt/bta_gattc_act.cc @@ -55,62 +55,56 @@ using namespace bluetooth; /***************************************************************************** * Constants ****************************************************************************/ -static void bta_gattc_conn_cback(tGATT_IF gattc_if, const RawAddress& bda, - uint16_t conn_id, bool connected, - tGATT_DISCONN_REASON reason, +static void bta_gattc_conn_cback(tGATT_IF gattc_if, const RawAddress& bda, uint16_t conn_id, + bool connected, tGATT_DISCONN_REASON reason, tBT_TRANSPORT transport); -static void bta_gattc_cmpl_cback(uint16_t conn_id, tGATTC_OPTYPE op, - tGATT_STATUS status, +static void bta_gattc_cmpl_cback(uint16_t conn_id, tGATTC_OPTYPE op, tGATT_STATUS status, tGATT_CL_COMPLETE* p_data); static void bta_gattc_deregister_cmpl(tBTA_GATTC_RCB* p_clreg); static void bta_gattc_enc_cmpl_cback(tGATT_IF gattc_if, const RawAddress& bda); static void bta_gattc_cong_cback(uint16_t conn_id, bool congested); -static void bta_gattc_phy_update_cback(tGATT_IF gatt_if, uint16_t conn_id, - uint8_t tx_phy, uint8_t rx_phy, - tGATT_STATUS status); -static void bta_gattc_conn_update_cback(tGATT_IF gatt_if, uint16_t conn_id, - uint16_t interval, uint16_t latency, - uint16_t timeout, tGATT_STATUS status); -static void bta_gattc_subrate_chg_cback(tGATT_IF gatt_if, uint16_t conn_id, - uint16_t subrate_factor, - uint16_t latency, uint16_t cont_num, - uint16_t timeout, tGATT_STATUS status); -static void bta_gattc_init_bk_conn(const tBTA_GATTC_API_OPEN* p_data, - tBTA_GATTC_RCB* p_clreg); +static void bta_gattc_phy_update_cback(tGATT_IF gatt_if, uint16_t conn_id, uint8_t tx_phy, + uint8_t rx_phy, tGATT_STATUS status); +static void bta_gattc_conn_update_cback(tGATT_IF gatt_if, uint16_t conn_id, uint16_t interval, + uint16_t latency, uint16_t timeout, tGATT_STATUS status); +static void bta_gattc_subrate_chg_cback(tGATT_IF gatt_if, uint16_t conn_id, uint16_t subrate_factor, + uint16_t latency, uint16_t cont_num, uint16_t timeout, + tGATT_STATUS status); +static void bta_gattc_init_bk_conn(const tBTA_GATTC_API_OPEN* p_data, tBTA_GATTC_RCB* p_clreg); static tGATT_CBACK bta_gattc_cl_cback = { - .p_conn_cb = bta_gattc_conn_cback, - .p_cmpl_cb = bta_gattc_cmpl_cback, - .p_disc_res_cb = bta_gattc_disc_res_cback, - .p_disc_cmpl_cb = bta_gattc_disc_cmpl_cback, - .p_req_cb = nullptr, - .p_enc_cmpl_cb = bta_gattc_enc_cmpl_cback, - .p_congestion_cb = bta_gattc_cong_cback, - .p_phy_update_cb = bta_gattc_phy_update_cback, - .p_conn_update_cb = bta_gattc_conn_update_cback, - .p_subrate_chg_cb = bta_gattc_subrate_chg_cback, + .p_conn_cb = bta_gattc_conn_cback, + .p_cmpl_cb = bta_gattc_cmpl_cback, + .p_disc_res_cb = bta_gattc_disc_res_cback, + .p_disc_cmpl_cb = bta_gattc_disc_cmpl_cback, + .p_req_cb = nullptr, + .p_enc_cmpl_cb = bta_gattc_enc_cmpl_cback, + .p_congestion_cb = bta_gattc_cong_cback, + .p_phy_update_cb = bta_gattc_phy_update_cback, + .p_conn_update_cb = bta_gattc_conn_update_cback, + .p_subrate_chg_cb = bta_gattc_subrate_chg_cback, }; /* opcode(tGATTC_OPTYPE) order has to be comply with internal event order */ static uint16_t bta_gattc_opcode_to_int_evt[] = { - /* Skip: GATTC_OPTYPE_NONE */ - /* Skip: GATTC_OPTYPE_DISCOVERY */ - BTA_GATTC_API_READ_EVT, /* GATTC_OPTYPE_READ */ - BTA_GATTC_API_WRITE_EVT, /* GATTC_OPTYPE_WRITE */ - BTA_GATTC_API_EXEC_EVT, /* GATTC_OPTYPE_EXE_WRITE */ - BTA_GATTC_API_CFG_MTU_EVT /* GATTC_OPTYPE_CONFIG */ + /* Skip: GATTC_OPTYPE_NONE */ + /* Skip: GATTC_OPTYPE_DISCOVERY */ + BTA_GATTC_API_READ_EVT, /* GATTC_OPTYPE_READ */ + BTA_GATTC_API_WRITE_EVT, /* GATTC_OPTYPE_WRITE */ + BTA_GATTC_API_EXEC_EVT, /* GATTC_OPTYPE_EXE_WRITE */ + BTA_GATTC_API_CFG_MTU_EVT /* GATTC_OPTYPE_CONFIG */ }; static const char* bta_gattc_op_code_name[] = { - "Unknown", /* GATTC_OPTYPE_NONE */ - "Discovery", /* GATTC_OPTYPE_DISCOVERY */ - "Read", /* GATTC_OPTYPE_READ */ - "Write", /* GATTC_OPTYPE_WRITE */ - "Exec", /* GATTC_OPTYPE_EXE_WRITE */ - "Config", /* GATTC_OPTYPE_CONFIG */ - "Notification", /* GATTC_OPTYPE_NOTIFICATION */ - "Indication" /* GATTC_OPTYPE_INDICATION */ + "Unknown", /* GATTC_OPTYPE_NONE */ + "Discovery", /* GATTC_OPTYPE_DISCOVERY */ + "Read", /* GATTC_OPTYPE_READ */ + "Write", /* GATTC_OPTYPE_WRITE */ + "Exec", /* GATTC_OPTYPE_EXE_WRITE */ + "Config", /* GATTC_OPTYPE_CONFIG */ + "Notification", /* GATTC_OPTYPE_NOTIFICATION */ + "Indication" /* GATTC_OPTYPE_INDICATION */ }; /***************************************************************************** @@ -145,7 +139,9 @@ void bta_gattc_disable() { } for (i = 0; i < BTA_GATTC_CL_MAX; i++) { - if (!bta_gattc_cb.cl_rcb[i].in_use) continue; + if (!bta_gattc_cb.cl_rcb[i].in_use) { + continue; + } bta_gattc_cb.state = BTA_GATTC_STATE_DISABLING; bta_gattc_deregister(&bta_gattc_cb.cl_rcb[i]); @@ -170,8 +166,8 @@ static void bta_gattc_start_if(uint8_t client_if) { } /** Register a GATT client application with BTA */ -void bta_gattc_register(const Uuid& app_uuid, tBTA_GATTC_CBACK* p_cback, - BtaAppRegisterCallback cb, bool eatt_support) { +void bta_gattc_register(const Uuid& app_uuid, tBTA_GATTC_CBACK* p_cback, BtaAppRegisterCallback cb, + bool eatt_support) { tGATT_STATUS status = GATT_NO_RESOURCES; uint8_t client_if = 0; log::debug("state: {}, uuid={}", bta_gattc_cb.state, app_uuid.ToString()); @@ -184,12 +180,10 @@ void bta_gattc_register(const Uuid& app_uuid, tBTA_GATTC_CBACK* p_cback, /* todo need to check duplicate uuid */ for (uint8_t i = 0; i < BTA_GATTC_CL_MAX; i++) { if (!bta_gattc_cb.cl_rcb[i].in_use) { - bta_gattc_cb.cl_rcb[i].client_if = GATT_Register( - app_uuid, "GattClient", &bta_gattc_cl_cback, eatt_support); + bta_gattc_cb.cl_rcb[i].client_if = + GATT_Register(app_uuid, "GattClient", &bta_gattc_cl_cback, eatt_support); if (bta_gattc_cb.cl_rcb[i].client_if == 0) { - log::error( - "Register with GATT stack failed with index {}, trying next index", - i); + log::error("Register with GATT stack failed with index {}, trying next index", i); status = GATT_ERROR; } else { bta_gattc_cb.cl_rcb[i].in_use = true; @@ -199,13 +193,10 @@ void bta_gattc_register(const Uuid& app_uuid, tBTA_GATTC_CBACK* p_cback, /* BTA use the same client interface as BTE GATT statck */ client_if = bta_gattc_cb.cl_rcb[i].client_if; - log::debug( - "Registered GATT client interface {} with uuid={}, starting it on " - "main thread", - client_if, app_uuid.ToString()); + log::debug("Registered GATT client interface {} with uuid={}, starting it on main thread", + client_if, app_uuid.ToString()); - do_in_main_thread(FROM_HERE, - base::BindOnce(&bta_gattc_start_if, client_if)); + do_in_main_thread(FROM_HERE, base::BindOnce(&bta_gattc_start_if, client_if)); status = GATT_SUCCESS; break; @@ -216,8 +207,7 @@ void bta_gattc_register(const Uuid& app_uuid, tBTA_GATTC_CBACK* p_cback, if (!cb.is_null()) { cb.Run(client_if, status); } else { - log::warn("No GATT callback available, client_if={}, status={}", client_if, - status); + log::warn("No GATT callback available, client_if={}, status={}", client_if, status); } } @@ -225,23 +215,20 @@ void bta_gattc_register(const Uuid& app_uuid, tBTA_GATTC_CBACK* p_cback, void bta_gattc_deregister(tBTA_GATTC_RCB* p_clreg) { uint8_t accept_list_size = 0; if (bluetooth::shim::GetController()->SupportsBle()) { - accept_list_size = - bluetooth::shim::GetController()->GetLeFilterAcceptListSize(); + accept_list_size = bluetooth::shim::GetController()->GetLeFilterAcceptListSize(); } /* remove bg connection associated with this rcb */ for (uint8_t i = 0; i < accept_list_size; i++) { - if (!bta_gattc_cb.bg_track[i].in_use) continue; + if (!bta_gattc_cb.bg_track[i].in_use) { + continue; + } if (bta_gattc_cb.bg_track[i].cif_mask & ((tBTA_GATTC_CIF_MASK)1 << (p_clreg->client_if - 1))) { - bta_gattc_mark_bg_conn(p_clreg->client_if, - bta_gattc_cb.bg_track[i].remote_bda, false); - if (!GATT_CancelConnect(p_clreg->client_if, - bta_gattc_cb.bg_track[i].remote_bda, false)) { - log::warn( - "Unable to cancel GATT connection client_if:{} peer:{} " - "is_direct:{}", - p_clreg->client_if, bta_gattc_cb.bg_track[i].remote_bda, false); + bta_gattc_mark_bg_conn(p_clreg->client_if, bta_gattc_cb.bg_track[i].remote_bda, false); + if (!GATT_CancelConnect(p_clreg->client_if, bta_gattc_cb.bg_track[i].remote_bda, false)) { + log::warn("Unable to cancel GATT connection client_if:{} peer:{} is_direct:{}", + p_clreg->client_if, bta_gattc_cb.bg_track[i].remote_bda, false); } } } @@ -253,8 +240,9 @@ void bta_gattc_deregister(tBTA_GATTC_RCB* p_clreg) { /* close all CLCB related to this app */ for (size_t i = 0; i < BTA_GATTC_CLCB_MAX; i++) { - if (!bta_gattc_cb.clcb[i].in_use || (bta_gattc_cb.clcb[i].p_rcb != p_clreg)) + if (!bta_gattc_cb.clcb[i].in_use || (bta_gattc_cb.clcb[i].p_rcb != p_clreg)) { continue; + } p_clreg->dereg_pending = true; @@ -281,16 +269,14 @@ void bta_gattc_process_api_open(const tBTA_GATTC_DATA* p_msg) { } tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_alloc_clcb( - p_msg->api_conn.client_if, p_msg->api_conn.remote_bda, - p_msg->api_conn.transport); + p_msg->api_conn.client_if, p_msg->api_conn.remote_bda, p_msg->api_conn.transport); if (p_clcb != nullptr) { bta_gattc_sm_execute(p_clcb, event, p_msg); } else { log::error("No resources to open a new connection."); - bta_gattc_send_open_cback(p_clreg, GATT_NO_RESOURCES, - p_msg->api_conn.remote_bda, GATT_INVALID_CONN_ID, - p_msg->api_conn.transport, 0); + bta_gattc_send_open_cback(p_clreg, GATT_NO_RESOURCES, p_msg->api_conn.remote_bda, + GATT_INVALID_CONN_ID, p_msg->api_conn.transport, 0); } } @@ -308,8 +294,7 @@ void bta_gattc_process_api_open_cancel(const tBTA_GATTC_DATA* p_msg) { log::debug("Cancel GATT client direct connection"); tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_clcb_by_cif( - p_msg->api_cancel_conn.client_if, p_msg->api_cancel_conn.remote_bda, - BT_TRANSPORT_LE); + p_msg->api_cancel_conn.client_if, p_msg->api_cancel_conn.remote_bda, BT_TRANSPORT_LE); if (p_clcb != NULL) { bta_gattc_sm_execute(p_clcb, event, p_msg); return; @@ -317,8 +302,7 @@ void bta_gattc_process_api_open_cancel(const tBTA_GATTC_DATA* p_msg) { log::error("No such connection need to be cancelled"); - tBTA_GATTC_RCB* p_clreg = - bta_gattc_cl_get_regcb(p_msg->api_cancel_conn.client_if); + tBTA_GATTC_RCB* p_clreg = bta_gattc_cl_get_regcb(p_msg->api_cancel_conn.client_if); if (p_clreg && p_clreg->p_cback) { tBTA_GATTC cb_data; @@ -328,11 +312,12 @@ void bta_gattc_process_api_open_cancel(const tBTA_GATTC_DATA* p_msg) { } /** process encryption complete message */ -static void bta_gattc_process_enc_cmpl(tGATT_IF client_if, - const RawAddress& bda) { +static void bta_gattc_process_enc_cmpl(tGATT_IF client_if, const RawAddress& bda) { tBTA_GATTC_RCB* p_clreg = bta_gattc_cl_get_regcb(client_if); - if (!p_clreg || !p_clreg->p_cback) return; + if (!p_clreg || !p_clreg->p_cback) { + return; + } tBTA_GATTC cb_data; memset(&cb_data, 0, sizeof(tBTA_GATTC)); @@ -343,41 +328,37 @@ static void bta_gattc_process_enc_cmpl(tGATT_IF client_if, (*p_clreg->p_cback)(BTA_GATTC_ENC_CMPL_CB_EVT, &cb_data); } -void bta_gattc_cancel_open_error(tBTA_GATTC_CLCB* p_clcb, - const tBTA_GATTC_DATA* /* p_data */) { +void bta_gattc_cancel_open_error(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* /* p_data */) { tBTA_GATTC cb_data; cb_data.status = GATT_ERROR; - if (p_clcb && p_clcb->p_rcb && p_clcb->p_rcb->p_cback) + if (p_clcb && p_clcb->p_rcb && p_clcb->p_rcb->p_cback) { (*p_clcb->p_rcb->p_cback)(BTA_GATTC_CANCEL_OPEN_EVT, &cb_data); + } } -void bta_gattc_open_error(tBTA_GATTC_CLCB* p_clcb, - const tBTA_GATTC_DATA* /* p_data */) { +void bta_gattc_open_error(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* /* p_data */) { log::error("Connection already opened. wrong state"); - bta_gattc_send_open_cback(p_clcb->p_rcb, GATT_SUCCESS, p_clcb->bda, - p_clcb->bta_conn_id, p_clcb->transport, 0); + bta_gattc_send_open_cback(p_clcb->p_rcb, GATT_SUCCESS, p_clcb->bda, p_clcb->bta_conn_id, + p_clcb->transport, 0); } -void bta_gattc_open_fail(tBTA_GATTC_CLCB* p_clcb, - const tBTA_GATTC_DATA* p_data) { +void bta_gattc_open_fail(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data) { if (com::android::bluetooth::flags::enumerate_gatt_errors() && p_data->int_conn.reason == GATT_CONN_TIMEOUT) { log::warn( - "Connection timed out after 30 seconds. conn_id=0x{:x}. Return " - "GATT_CONNECTION_TIMEOUT({})", - p_clcb->bta_conn_id, GATT_CONNECTION_TIMEOUT); - bta_gattc_send_open_cback(p_clcb->p_rcb, GATT_CONNECTION_TIMEOUT, - p_clcb->bda, p_clcb->bta_conn_id, - p_clcb->transport, 0); - } else { - log::warn( - "Cannot establish Connection. conn_id=0x{:x}. Return GATT_ERROR({})", - p_clcb->bta_conn_id, GATT_ERROR); - bta_gattc_send_open_cback(p_clcb->p_rcb, GATT_ERROR, p_clcb->bda, + "Connection timed out after 30 seconds. conn_id=0x{:x}. Return " + "GATT_CONNECTION_TIMEOUT({})", + p_clcb->bta_conn_id, GATT_CONNECTION_TIMEOUT); + bta_gattc_send_open_cback(p_clcb->p_rcb, GATT_CONNECTION_TIMEOUT, p_clcb->bda, p_clcb->bta_conn_id, p_clcb->transport, 0); + } else { + log::warn("Cannot establish Connection. conn_id=0x{:x}. Return GATT_ERROR({})", + p_clcb->bta_conn_id, GATT_ERROR); + bta_gattc_send_open_cback(p_clcb->p_rcb, GATT_ERROR, p_clcb->bda, p_clcb->bta_conn_id, + p_clcb->transport, 0); } /* open failure, remove clcb */ @@ -390,9 +371,8 @@ void bta_gattc_open(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data) { /* open/hold a connection */ if (!GATT_Connect(p_clcb->p_rcb->client_if, p_data->api_conn.remote_bda, - p_data->api_conn.remote_addr_type, - BTM_BLE_DIRECT_CONNECTION, p_data->api_conn.transport, - p_data->api_conn.opportunistic, + p_data->api_conn.remote_addr_type, BTM_BLE_DIRECT_CONNECTION, + p_data->api_conn.transport, p_data->api_conn.opportunistic, p_data->api_conn.initiating_phys)) { log::error("Connection open failure"); bta_gattc_sm_execute(p_clcb, BTA_GATTC_INT_OPEN_FAIL_EVT, p_data); @@ -402,17 +382,15 @@ void bta_gattc_open(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data) { tBTA_GATTC_RCB* p_clreg = p_clcb->p_rcb; /* Re-enable notification registration for closed connection */ for (int i = 0; i < BTA_GATTC_NOTIF_REG_MAX; i++) { - if (p_clreg->notif_reg[i].in_use && - p_clreg->notif_reg[i].remote_bda == p_clcb->bda && + if (p_clreg->notif_reg[i].in_use && p_clreg->notif_reg[i].remote_bda == p_clcb->bda && p_clreg->notif_reg[i].app_disconnected) { p_clreg->notif_reg[i].app_disconnected = false; } } /* a connected remote device */ - if (GATT_GetConnIdIfConnected( - p_clcb->p_rcb->client_if, p_data->api_conn.remote_bda, - &p_clcb->bta_conn_id, p_data->api_conn.transport)) { + if (GATT_GetConnIdIfConnected(p_clcb->p_rcb->client_if, p_data->api_conn.remote_bda, + &p_clcb->bta_conn_id, p_data->api_conn.transport)) { gattc_data.int_conn.hdr.layer_specific = p_clcb->bta_conn_id; bta_gattc_sm_execute(p_clcb, BTA_GATTC_INT_CONN_EVT, &gattc_data); @@ -421,46 +399,43 @@ void bta_gattc_open(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data) { } /** Process API Open for a background connection */ -static void bta_gattc_init_bk_conn(const tBTA_GATTC_API_OPEN* p_data, - tBTA_GATTC_RCB* p_clreg) { +static void bta_gattc_init_bk_conn(const tBTA_GATTC_API_OPEN* p_data, tBTA_GATTC_RCB* p_clreg) { if (!bta_gattc_mark_bg_conn(p_data->client_if, p_data->remote_bda, true)) { log::warn("Unable to find space for accept list connection mask"); - bta_gattc_send_open_cback(p_clreg, GATT_NO_RESOURCES, p_data->remote_bda, - GATT_INVALID_CONN_ID, BT_TRANSPORT_LE, 0); + bta_gattc_send_open_cback(p_clreg, GATT_NO_RESOURCES, p_data->remote_bda, GATT_INVALID_CONN_ID, + BT_TRANSPORT_LE, 0); return; } /* always call open to hold a connection */ - if (!GATT_Connect(p_data->client_if, p_data->remote_bda, - p_data->connection_type, p_data->transport, false)) { + if (!GATT_Connect(p_data->client_if, p_data->remote_bda, p_data->connection_type, + p_data->transport, false)) { log::error("Unable to connect to remote bd_addr={}", p_data->remote_bda); - bta_gattc_send_open_cback(p_clreg, GATT_ILLEGAL_PARAMETER, - p_data->remote_bda, GATT_INVALID_CONN_ID, - BT_TRANSPORT_LE, 0); + bta_gattc_send_open_cback(p_clreg, GATT_ILLEGAL_PARAMETER, p_data->remote_bda, + GATT_INVALID_CONN_ID, BT_TRANSPORT_LE, 0); return; } uint16_t conn_id; - if (!GATT_GetConnIdIfConnected(p_data->client_if, p_data->remote_bda, - &conn_id, p_data->transport)) { + if (!GATT_GetConnIdIfConnected(p_data->client_if, p_data->remote_bda, &conn_id, + p_data->transport)) { log::info("Not a connected remote device yet"); return; } - tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_alloc_clcb( - p_data->client_if, p_data->remote_bda, BT_TRANSPORT_LE); + tBTA_GATTC_CLCB* p_clcb = + bta_gattc_find_alloc_clcb(p_data->client_if, p_data->remote_bda, BT_TRANSPORT_LE); if (!p_clcb) { - log::warn("Unable to find connection link for device:{}", - p_data->remote_bda); + log::warn("Unable to find connection link for device:{}", p_data->remote_bda); return; } p_clcb->bta_conn_id = conn_id; tBTA_GATTC_DATA gattc_data = { - .hdr = - { - .layer_specific = conn_id, - }, + .hdr = + { + .layer_specific = conn_id, + }, }; /* open connection */ @@ -490,8 +465,7 @@ void bta_gattc_cancel_bk_conn(const tBTA_GATTC_API_CANCEL_OPEN* p_data) { } } -void bta_gattc_cancel_open_ok(tBTA_GATTC_CLCB* p_clcb, - const tBTA_GATTC_DATA* /* p_data */) { +void bta_gattc_cancel_open_ok(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* /* p_data */) { tBTA_GATTC cb_data; if (p_clcb->p_rcb->p_cback) { @@ -502,12 +476,10 @@ void bta_gattc_cancel_open_ok(tBTA_GATTC_CLCB* p_clcb, bta_gattc_clcb_dealloc(p_clcb); } -void bta_gattc_cancel_open(tBTA_GATTC_CLCB* p_clcb, - const tBTA_GATTC_DATA* p_data) { +void bta_gattc_cancel_open(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data) { tBTA_GATTC cb_data; - if (GATT_CancelConnect(p_clcb->p_rcb->client_if, - p_data->api_cancel_conn.remote_bda, true)) { + if (GATT_CancelConnect(p_clcb->p_rcb->client_if, p_data->api_cancel_conn.remote_bda, true)) { bta_gattc_sm_execute(p_clcb, BTA_GATTC_INT_CANCEL_OPEN_OK_EVT, p_data); } else { if (p_clcb->p_rcb->p_cback) { @@ -526,30 +498,29 @@ void bta_gattc_conn(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data) { log::verbose("conn_id=0x{:x}", p_data->hdr.layer_specific); p_clcb->bta_conn_id = p_data->int_conn.hdr.layer_specific; - if (!GATT_GetConnectionInfor(p_data->hdr.layer_specific, &gatt_if, - p_clcb->bda, &p_clcb->transport)) { - log::warn("Unable to get GATT connection information peer:{}", - p_clcb->bda); + if (!GATT_GetConnectionInfor(p_data->hdr.layer_specific, &gatt_if, p_clcb->bda, + &p_clcb->transport)) { + log::warn("Unable to get GATT connection information peer:{}", p_clcb->bda); } } p_clcb->p_srcb->connected = true; - if (p_clcb->p_srcb->mtu == 0) p_clcb->p_srcb->mtu = GATT_DEF_BLE_MTU_SIZE; + if (p_clcb->p_srcb->mtu == 0) { + p_clcb->p_srcb->mtu = GATT_DEF_BLE_MTU_SIZE; + } tBTA_GATTC_RCB* p_clreg = p_clcb->p_rcb; /* Re-enable notification registration for closed connection */ for (int i = 0; i < BTA_GATTC_NOTIF_REG_MAX; i++) { - if (p_clreg->notif_reg[i].in_use && - p_clreg->notif_reg[i].remote_bda == p_clcb->bda && + if (p_clreg->notif_reg[i].in_use && p_clreg->notif_reg[i].remote_bda == p_clcb->bda && p_clreg->notif_reg[i].app_disconnected) { p_clreg->notif_reg[i].app_disconnected = false; } } /* start database cache if needed */ - if (p_clcb->p_srcb->gatt_database.IsEmpty() || - p_clcb->p_srcb->state != BTA_GATTC_SERV_IDLE) { + if (p_clcb->p_srcb->gatt_database.IsEmpty() || p_clcb->p_srcb->state != BTA_GATTC_SERV_IDLE) { if (p_clcb->p_srcb->state == BTA_GATTC_SERV_IDLE) { p_clcb->p_srcb->state = BTA_GATTC_SERV_LOAD; // Consider the case that if GATT Server is changed, but no service @@ -560,17 +531,17 @@ void bta_gattc_conn(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data) { // Only load the database if we are bonded, since the device cache is // meaningless otherwise (as we need to do rediscovery regardless) gatt::Database db = btm_sec_is_a_bonded_dev(p_clcb->bda) - ? bta_gattc_cache_load(p_clcb->p_srcb->server_bda) - : gatt::Database(); + ? bta_gattc_cache_load(p_clcb->p_srcb->server_bda) + : gatt::Database(); auto robust_caching_support = GetRobustCachingSupport(p_clcb, db); log::info("Connected to {}, robust caching support is {}", - p_clcb->bda.ToRedactedStringForLogging(), - robust_caching_support); + p_clcb->bda.ToRedactedStringForLogging(), robust_caching_support); - if (!db.IsEmpty()) p_clcb->p_srcb->gatt_database = db; + if (!db.IsEmpty()) { + p_clcb->p_srcb->gatt_database = db; + } - if (db.IsEmpty() || - robust_caching_support != RobustCachingSupport::UNSUPPORTED) { + if (db.IsEmpty() || robust_caching_support != RobustCachingSupport::UNSUPPORTED) { // If the peer device is expected to support robust caching, or if we // don't know its services yet, then we should do discovery (which may // short-circuit through a hash match, but might also do the full @@ -586,8 +557,9 @@ void bta_gattc_conn(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data) { p_clcb->p_srcb->state = BTA_GATTC_SERV_IDLE; bta_gattc_reset_discover_st(p_clcb->p_srcb, GATT_SUCCESS); } - } else /* cache is building */ + } else { /* cache is building */ p_clcb->state = BTA_GATTC_DISCOVER_ST; + } } else { @@ -605,18 +577,17 @@ void bta_gattc_conn(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data) { if (p_clcb->p_rcb) { /* there is no RM for GATT */ - if (p_clcb->transport == BT_TRANSPORT_BR_EDR) + if (p_clcb->transport == BT_TRANSPORT_BR_EDR) { bta_sys_conn_open(BTA_ID_GATTC, BTA_ALL_APP_ID, p_clcb->bda); + } - bta_gattc_send_open_cback(p_clcb->p_rcb, GATT_SUCCESS, p_clcb->bda, - p_clcb->bta_conn_id, p_clcb->transport, - p_clcb->p_srcb->mtu); + bta_gattc_send_open_cback(p_clcb->p_rcb, GATT_SUCCESS, p_clcb->bda, p_clcb->bta_conn_id, + p_clcb->transport, p_clcb->p_srcb->mtu); } } /** close a connection */ -void bta_gattc_close_fail(tBTA_GATTC_CLCB* p_clcb, - const tBTA_GATTC_DATA* p_data) { +void bta_gattc_close_fail(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data) { tBTA_GATTC cb_data; if (p_clcb->p_rcb->p_cback) { @@ -627,8 +598,7 @@ void bta_gattc_close_fail(tBTA_GATTC_CLCB* p_clcb, cb_data.close.reason = BTA_GATT_CONN_NONE; cb_data.close.status = GATT_ERROR; - log::warn("conn_id=0x{:x}. Returns GATT_ERROR({}).", cb_data.close.conn_id, - GATT_ERROR); + log::warn("conn_id=0x{:x}. Returns GATT_ERROR({}).", cb_data.close.conn_id, GATT_ERROR); (*p_clcb->p_rcb->p_cback)(BTA_GATTC_CLOSE_EVT, &cb_data); } @@ -639,14 +609,14 @@ void bta_gattc_close(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data) { tBTA_GATTC_CBACK* p_cback = p_clcb->p_rcb->p_cback; tBTA_GATTC_RCB* p_clreg = p_clcb->p_rcb; tBTA_GATTC cb_data = { - .close = - { - .conn_id = p_clcb->bta_conn_id, - .status = GATT_SUCCESS, - .client_if = p_clcb->p_rcb->client_if, - .remote_bda = p_clcb->bda, - .reason = GATT_CONN_OK, - }, + .close = + { + .conn_id = p_clcb->bta_conn_id, + .status = GATT_SUCCESS, + .client_if = p_clcb->p_rcb->client_if, + .remote_bda = p_clcb->bda, + .reason = GATT_CONN_OK, + }, }; if (p_clcb->transport == BT_TRANSPORT_BR_EDR) { @@ -655,8 +625,7 @@ void bta_gattc_close(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data) { /* Disable notification registration for closed connection */ for (int i = 0; i < BTA_GATTC_NOTIF_REG_MAX; i++) { - if (p_clreg->notif_reg[i].in_use && - p_clreg->notif_reg[i].remote_bda == p_clcb->bda) { + if (p_clreg->notif_reg[i].in_use && p_clreg->notif_reg[i].remote_bda == p_clcb->bda) { p_clreg->notif_reg[i].app_disconnected = true; } } @@ -678,20 +647,22 @@ void bta_gattc_close(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data) { if (p_data->hdr.event == BTA_GATTC_API_CLOSE_EVT) { cb_data.close.status = GATT_Disconnect(p_data->hdr.layer_specific); cb_data.close.reason = GATT_CONN_TERMINATE_LOCAL_HOST; - log::debug("Local close event client_if:{} conn_id:{} reason:{}", - cb_data.close.client_if, cb_data.close.conn_id, + log::debug("Local close event client_if:{} conn_id:{} reason:{}", cb_data.close.client_if, + cb_data.close.conn_id, gatt_disconnection_reason_text( - static_cast(cb_data.close.reason))); + static_cast(cb_data.close.reason))); } else if (p_data->hdr.event == BTA_GATTC_INT_DISCONN_EVT) { cb_data.close.status = static_cast(p_data->int_conn.reason); cb_data.close.reason = p_data->int_conn.reason; log::debug("Peer close disconnect event client_if:{} conn_id:{} reason:{}", cb_data.close.client_if, cb_data.close.conn_id, gatt_disconnection_reason_text( - static_cast(cb_data.close.reason))); + static_cast(cb_data.close.reason))); } - if (p_cback) (*p_cback)(BTA_GATTC_CLOSE_EVT, &cb_data); + if (p_cback) { + (*p_cback)(BTA_GATTC_CLOSE_EVT, &cb_data); + } if (p_clreg->num_clcb == 0 && p_clreg->dereg_pending) { bta_gattc_deregister_cmpl(p_clreg); @@ -703,23 +674,19 @@ void bta_gattc_reset_discover_st(tBTA_GATTC_SERV* p_srcb, tGATT_STATUS status) { for (size_t i = 0; i < BTA_GATTC_CLCB_MAX; i++) { if (bta_gattc_cb.clcb[i].p_srcb == p_srcb) { bta_gattc_cb.clcb[i].status = status; - bta_gattc_sm_execute(&bta_gattc_cb.clcb[i], BTA_GATTC_DISCOVER_CMPL_EVT, - NULL); + bta_gattc_sm_execute(&bta_gattc_cb.clcb[i], BTA_GATTC_DISCOVER_CMPL_EVT, NULL); } } } /** close a GATTC connection while in discovery state */ -void bta_gattc_disc_close(tBTA_GATTC_CLCB* p_clcb, - const tBTA_GATTC_DATA* p_data) { +void bta_gattc_disc_close(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data) { log::verbose("Discovery cancel conn_id=0x{:x}", p_clcb->bta_conn_id); if (p_clcb->disc_active || (com::android::bluetooth::flags::gatt_rediscover_on_canceled() && - (p_clcb->request_during_discovery == - BTA_GATTC_DISCOVER_REQ_READ_DB_HASH || - p_clcb->request_during_discovery == - BTA_GATTC_DISCOVER_REQ_READ_DB_HASH_FOR_SVC_CHG))) { + (p_clcb->request_during_discovery == BTA_GATTC_DISCOVER_REQ_READ_DB_HASH || + p_clcb->request_during_discovery == BTA_GATTC_DISCOVER_REQ_READ_DB_HASH_FOR_SVC_CHG))) { bta_gattc_reset_discover_st(p_clcb->p_srcb, GATT_ERROR); } else { p_clcb->state = BTA_GATTC_CONN_ST; @@ -729,8 +696,7 @@ void bta_gattc_disc_close(tBTA_GATTC_CLCB* p_clcb, // while in the BTA_GATTC_DISCOVER_ST state. Once the state changes, the // connection itself still needs to be closed to resolve the original event. if (p_clcb->state == BTA_GATTC_CONN_ST) { - log::verbose( - "State is back to BTA_GATTC_CONN_ST. Trigger connection close"); + log::verbose("State is back to BTA_GATTC_CONN_ST. Trigger connection close"); bta_gattc_close(p_clcb, p_data); } } @@ -741,8 +707,7 @@ static void bta_gattc_set_discover_st(tBTA_GATTC_SERV* p_srcb) { if (bta_gattc_cb.clcb[i].p_srcb == p_srcb) { bta_gattc_cb.clcb[i].status = GATT_SUCCESS; bta_gattc_cb.clcb[i].state = BTA_GATTC_DISCOVER_ST; - bta_gattc_cb.clcb[i].request_during_discovery = - BTA_GATTC_DISCOVER_REQ_NONE; + bta_gattc_cb.clcb[i].request_during_discovery = BTA_GATTC_DISCOVER_REQ_NONE; } } } @@ -750,8 +715,7 @@ static void bta_gattc_set_discover_st(tBTA_GATTC_SERV* p_srcb) { /** process service change in discovery state, mark up the auto update flag and * set status to be discovery cancel for current discovery. */ -void bta_gattc_restart_discover(tBTA_GATTC_CLCB* p_clcb, - const tBTA_GATTC_DATA* /* p_data */) { +void bta_gattc_restart_discover(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* /* p_data */) { p_clcb->status = GATT_CANCEL; p_clcb->auto_update = BTA_GATTC_DISC_WAITING; } @@ -759,32 +723,28 @@ void bta_gattc_restart_discover(tBTA_GATTC_CLCB* p_clcb, /** Configure MTU size on the GATT connection */ void bta_gattc_cfg_mtu(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data) { uint16_t current_mtu = 0; - auto result = GATTC_TryMtuRequest(p_clcb->bda, p_clcb->transport, - p_clcb->bta_conn_id, ¤t_mtu); + auto result = + GATTC_TryMtuRequest(p_clcb->bda, p_clcb->transport, p_clcb->bta_conn_id, ¤t_mtu); switch (result) { case MTU_EXCHANGE_DEVICE_DISCONNECTED: log::info("Device {} disconnected", p_clcb->bda); - bta_gattc_cmpl_sendmsg(p_clcb->bta_conn_id, GATTC_OPTYPE_CONFIG, - GATT_NO_RESOURCES, NULL); + bta_gattc_cmpl_sendmsg(p_clcb->bta_conn_id, GATTC_OPTYPE_CONFIG, GATT_NO_RESOURCES, NULL); bta_gattc_continue(p_clcb); return; case MTU_EXCHANGE_NOT_ALLOWED: log::info("Not allowed for BR/EDR devices {}", p_clcb->bda); - bta_gattc_cmpl_sendmsg(p_clcb->bta_conn_id, GATTC_OPTYPE_CONFIG, - GATT_ERR_UNLIKELY, NULL); + bta_gattc_cmpl_sendmsg(p_clcb->bta_conn_id, GATTC_OPTYPE_CONFIG, GATT_ERR_UNLIKELY, NULL); bta_gattc_continue(p_clcb); return; case MTU_EXCHANGE_ALREADY_DONE: /* Check if MTU is not already set, if so, just report it back to the user * and continue with other requests. */ - GATTC_UpdateUserAttMtuIfNeeded(p_clcb->bda, p_clcb->transport, - p_data->api_mtu.mtu); + GATTC_UpdateUserAttMtuIfNeeded(p_clcb->bda, p_clcb->transport, p_data->api_mtu.mtu); bta_gattc_send_mtu_response(p_clcb, p_data, current_mtu); return; case MTU_EXCHANGE_IN_PROGRESS: - log::info("Enqueue MTU Request - waiting for response on p_clcb {}", - fmt::ptr(p_clcb)); + log::info("Enqueue MTU Request - waiting for response on p_clcb {}", fmt::ptr(p_clcb)); /* MTU request is in progress and this one will not be sent to remote * device. Just push back on the queue and response will be sent up to * the upper layer when MTU Exchange will be completed. @@ -797,48 +757,50 @@ void bta_gattc_cfg_mtu(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data) { break; } - if (bta_gattc_enqueue(p_clcb, p_data) == ENQUEUED_FOR_LATER) return; + if (bta_gattc_enqueue(p_clcb, p_data) == ENQUEUED_FOR_LATER) { + return; + } - tGATT_STATUS status = - GATTC_ConfigureMTU(p_clcb->bta_conn_id, p_data->api_mtu.mtu); + tGATT_STATUS status = GATTC_ConfigureMTU(p_clcb->bta_conn_id, p_data->api_mtu.mtu); /* if failed, return callback here */ if (status != GATT_SUCCESS && status != GATT_CMD_STARTED) { /* Dequeue the data, if it was enqueued */ - if (p_clcb->p_q_cmd == p_data) p_clcb->p_q_cmd = NULL; + if (p_clcb->p_q_cmd == p_data) { + p_clcb->p_q_cmd = NULL; + } - bta_gattc_cmpl_sendmsg(p_clcb->bta_conn_id, GATTC_OPTYPE_CONFIG, status, - NULL); + bta_gattc_cmpl_sendmsg(p_clcb->bta_conn_id, GATTC_OPTYPE_CONFIG, status, NULL); bta_gattc_continue(p_clcb); } } void bta_gattc_start_discover_internal(tBTA_GATTC_CLCB* p_clcb) { - if (p_clcb->transport == BT_TRANSPORT_LE) + if (p_clcb->transport == BT_TRANSPORT_LE) { L2CA_LockBleConnParamsForServiceDiscovery(p_clcb->p_srcb->server_bda, true); + } bta_gattc_init_cache(p_clcb->p_srcb); - p_clcb->status = bta_gattc_discover_pri_service( - p_clcb->bta_conn_id, p_clcb->p_srcb, GATT_DISC_SRVC_ALL); + p_clcb->status = + bta_gattc_discover_pri_service(p_clcb->bta_conn_id, p_clcb->p_srcb, GATT_DISC_SRVC_ALL); if (p_clcb->status != GATT_SUCCESS) { log::error("discovery on server failed"); bta_gattc_reset_discover_st(p_clcb->p_srcb, p_clcb->status); - } else + } else { p_clcb->disc_active = true; + } } -static void bta_gattc_continue_with_version_and_cache_known( - tBTA_GATTC_CLCB* p_clcb, RobustCachingSupport cache_support, - bool is_svc_chg); +static void bta_gattc_continue_with_version_and_cache_known(tBTA_GATTC_CLCB* p_clcb, + RobustCachingSupport cache_support, + bool is_svc_chg); /** Start a discovery on server */ -void bta_gattc_start_discover(tBTA_GATTC_CLCB* p_clcb, - const tBTA_GATTC_DATA* /* p_data */) { +void bta_gattc_start_discover(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* /* p_data */) { log::verbose("conn_id:0x{:x} p_clcb->p_srcb->state:{}", p_clcb->bta_conn_id, p_clcb->p_srcb->state); - if (((p_clcb->p_q_cmd == NULL || - p_clcb->auto_update == BTA_GATTC_REQ_WAITING) && + if (((p_clcb->p_q_cmd == NULL || p_clcb->auto_update == BTA_GATTC_REQ_WAITING) && p_clcb->p_srcb->state == BTA_GATTC_SERV_IDLE) || p_clcb->p_srcb->state == BTA_GATTC_SERV_DISC) /* no pending operation, start discovery right away */ @@ -864,31 +826,28 @@ void bta_gattc_start_discover(tBTA_GATTC_CLCB* p_clcb, p_clcb->p_srcb->state = BTA_GATTC_SERV_DISC_ACT; p_clcb->p_srcb->disc_blocked_waiting_on_version = false; - auto cache_support = - GetRobustCachingSupport(p_clcb, p_clcb->p_srcb->gatt_database); + auto cache_support = GetRobustCachingSupport(p_clcb, p_clcb->p_srcb->gatt_database); if (cache_support == RobustCachingSupport::W4_REMOTE_VERSION) { - log::info( - "Pausing service discovery till remote version is read conn_id:{}", - p_clcb->bta_conn_id); + log::info("Pausing service discovery till remote version is read conn_id:{}", + p_clcb->bta_conn_id); p_clcb->p_srcb->disc_blocked_waiting_on_version = true; p_clcb->p_srcb->blocked_conn_id = p_clcb->bta_conn_id; return; } - bta_gattc_continue_with_version_and_cache_known(p_clcb, cache_support, - is_svc_chg); + bta_gattc_continue_with_version_and_cache_known(p_clcb, cache_support, is_svc_chg); } /* pending operation, wait until it finishes */ else { p_clcb->auto_update = BTA_GATTC_DISC_WAITING; - if (p_clcb->p_srcb->state == BTA_GATTC_SERV_IDLE) + if (p_clcb->p_srcb->state == BTA_GATTC_SERV_IDLE) { p_clcb->state = BTA_GATTC_CONN_ST; /* set clcb state */ + } } } -void bta_gattc_continue_discovery_if_needed(const RawAddress& bd_addr, - uint16_t /* acl_handle */) { +void bta_gattc_continue_discovery_if_needed(const RawAddress& bd_addr, uint16_t /* acl_handle */) { tBTA_GATTC_SERV* p_srcb = bta_gattc_find_srvr_cache(bd_addr); if (!p_srcb || !p_srcb->disc_blocked_waiting_on_version) { return; @@ -899,8 +858,7 @@ void bta_gattc_continue_discovery_if_needed(const RawAddress& bd_addr, p_srcb->disc_blocked_waiting_on_version = false; p_srcb->blocked_conn_id = 0; - log::info("Received remote version, continue service discovery for {}", - bd_addr); + log::info("Received remote version, continue service discovery for {}", bd_addr); tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_clcb_by_conn_id(conn_id); @@ -911,15 +869,13 @@ void bta_gattc_continue_discovery_if_needed(const RawAddress& bd_addr, bool is_svc_chg = p_clcb->p_srcb->srvc_hdl_chg; - auto cache_support = - GetRobustCachingSupport(p_clcb, p_clcb->p_srcb->gatt_database); - bta_gattc_continue_with_version_and_cache_known(p_clcb, cache_support, - is_svc_chg); + auto cache_support = GetRobustCachingSupport(p_clcb, p_clcb->p_srcb->gatt_database); + bta_gattc_continue_with_version_and_cache_known(p_clcb, cache_support, is_svc_chg); } -void bta_gattc_continue_with_version_and_cache_known( - tBTA_GATTC_CLCB* p_clcb, RobustCachingSupport cache_support, - bool is_svc_chg) { +void bta_gattc_continue_with_version_and_cache_known(tBTA_GATTC_CLCB* p_clcb, + RobustCachingSupport cache_support, + bool is_svc_chg) { if (cache_support == RobustCachingSupport::UNSUPPORTED || (com::android::bluetooth::flags::skip_unknown_robust_caching() && cache_support == RobustCachingSupport::UNKNOWN)) { @@ -930,10 +886,8 @@ void bta_gattc_continue_with_version_and_cache_known( } /* read db hash if db hash characteristic exists */ - if (p_clcb->p_srcb->srvc_hdl_db_hash && - bta_gattc_read_db_hash(p_clcb, is_svc_chg)) { - log::info("pending service discovery, read db hash first conn_id:0x{:x}", - p_clcb->bta_conn_id); + if (p_clcb->p_srcb->srvc_hdl_db_hash && bta_gattc_read_db_hash(p_clcb, is_svc_chg)) { + log::info("pending service discovery, read db hash first conn_id:0x{:x}", p_clcb->bta_conn_id); p_clcb->p_srcb->srvc_hdl_db_hash = false; return; } @@ -941,15 +895,13 @@ void bta_gattc_continue_with_version_and_cache_known( } /** discovery on server is finished */ -void bta_gattc_disc_cmpl(tBTA_GATTC_CLCB* p_clcb, - const tBTA_GATTC_DATA* /* p_data */) { +void bta_gattc_disc_cmpl(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* /* p_data */) { const tBTA_GATTC_DATA* p_q_cmd = p_clcb->p_q_cmd; log::verbose("conn_id=0x{:x}", p_clcb->bta_conn_id); if (p_clcb->transport == BT_TRANSPORT_LE) { - L2CA_LockBleConnParamsForServiceDiscovery(p_clcb->p_srcb->server_bda, - false); + L2CA_LockBleConnParamsForServiceDiscovery(p_clcb->p_srcb->server_bda, false); } p_clcb->p_srcb->state = BTA_GATTC_SERV_IDLE; p_clcb->disc_active = false; @@ -1000,7 +952,9 @@ void bta_gattc_disc_cmpl(tBTA_GATTC_CLCB* p_clcb, /** Read an attribute */ void bta_gattc_read(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data) { - if (bta_gattc_enqueue(p_clcb, p_data) == ENQUEUED_FOR_LATER) return; + if (bta_gattc_enqueue(p_clcb, p_data) == ENQUEUED_FOR_LATER) { + return; + } tGATT_STATUS status; if (p_data->api_read.handle != 0) { @@ -1023,18 +977,20 @@ void bta_gattc_read(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data) { /* read fail */ if (status != GATT_SUCCESS) { /* Dequeue the data, if it was enqueued */ - if (p_clcb->p_q_cmd == p_data) p_clcb->p_q_cmd = NULL; + if (p_clcb->p_q_cmd == p_data) { + p_clcb->p_q_cmd = NULL; + } - bta_gattc_cmpl_sendmsg(p_clcb->bta_conn_id, GATTC_OPTYPE_READ, status, - NULL); + bta_gattc_cmpl_sendmsg(p_clcb->bta_conn_id, GATTC_OPTYPE_READ, status, NULL); bta_gattc_continue(p_clcb); } } /** read multiple */ -void bta_gattc_read_multi(tBTA_GATTC_CLCB* p_clcb, - const tBTA_GATTC_DATA* p_data) { - if (bta_gattc_enqueue(p_clcb, p_data) == ENQUEUED_FOR_LATER) return; +void bta_gattc_read_multi(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data) { + if (bta_gattc_enqueue(p_clcb, p_data) == ENQUEUED_FOR_LATER) { + return; + } if (p_data->api_read_multi.handles.num_attr > GATT_MAX_READ_MULTI_HANDLES) { log::error("api_read_multi.num_attr > GATT_MAX_READ_MULTI_HANDLES"); @@ -1044,32 +1000,32 @@ void bta_gattc_read_multi(tBTA_GATTC_CLCB* p_clcb, tGATT_READ_PARAM read_param; memset(&read_param, 0, sizeof(tGATT_READ_PARAM)); - read_param.read_multiple.num_handles = - p_data->api_read_multi.handles.num_attr; + read_param.read_multiple.num_handles = p_data->api_read_multi.handles.num_attr; read_param.read_multiple.auth_req = p_data->api_read_multi.auth_req; read_param.read_multiple.variable_len = p_data->api_read_multi.variable_len; - memcpy(&read_param.read_multiple.handles, - p_data->api_read_multi.handles.handles, + memcpy(&read_param.read_multiple.handles, p_data->api_read_multi.handles.handles, sizeof(uint16_t) * p_data->api_read_multi.handles.num_attr); - tGATT_READ_TYPE read_type = (read_param.read_multiple.variable_len) - ? GATT_READ_MULTIPLE_VAR_LEN - : GATT_READ_MULTIPLE; + tGATT_READ_TYPE read_type = + (read_param.read_multiple.variable_len) ? GATT_READ_MULTIPLE_VAR_LEN : GATT_READ_MULTIPLE; tGATT_STATUS status = GATTC_Read(p_clcb->bta_conn_id, read_type, &read_param); /* read fail */ if (status != GATT_SUCCESS) { /* Dequeue the data, if it was enqueued */ - if (p_clcb->p_q_cmd == p_data) p_clcb->p_q_cmd = NULL; + if (p_clcb->p_q_cmd == p_data) { + p_clcb->p_q_cmd = NULL; + } - bta_gattc_cmpl_sendmsg(p_clcb->bta_conn_id, GATTC_OPTYPE_READ, status, - NULL); + bta_gattc_cmpl_sendmsg(p_clcb->bta_conn_id, GATTC_OPTYPE_READ, status, NULL); bta_gattc_continue(p_clcb); } } /** Write an attribute */ void bta_gattc_write(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data) { - if (bta_gattc_enqueue(p_clcb, p_data) == ENQUEUED_FOR_LATER) return; + if (bta_gattc_enqueue(p_clcb, p_data) == ENQUEUED_FOR_LATER) { + return; + } tGATT_STATUS status = GATT_SUCCESS; tGATT_VALUE attr; @@ -1084,36 +1040,39 @@ void bta_gattc_write(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data) { if (attr.len > GATT_MAX_ATTR_LEN) { status = GATT_INVALID_ATTR_LEN; } else { - if (p_data->api_write.p_value) + if (p_data->api_write.p_value) { memcpy(attr.value, p_data->api_write.p_value, p_data->api_write.len); + } - status = - GATTC_Write(p_clcb->bta_conn_id, p_data->api_write.write_type, &attr); + status = GATTC_Write(p_clcb->bta_conn_id, p_data->api_write.write_type, &attr); } /* write fail */ if (status != GATT_SUCCESS) { /* Dequeue the data, if it was enqueued */ - if (p_clcb->p_q_cmd == p_data) p_clcb->p_q_cmd = NULL; + if (p_clcb->p_q_cmd == p_data) { + p_clcb->p_q_cmd = NULL; + } - bta_gattc_cmpl_sendmsg(p_clcb->bta_conn_id, GATTC_OPTYPE_WRITE, status, - NULL); + bta_gattc_cmpl_sendmsg(p_clcb->bta_conn_id, GATTC_OPTYPE_WRITE, status, NULL); bta_gattc_continue(p_clcb); } } /** send execute write */ void bta_gattc_execute(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data) { - if (bta_gattc_enqueue(p_clcb, p_data) == ENQUEUED_FOR_LATER) return; + if (bta_gattc_enqueue(p_clcb, p_data) == ENQUEUED_FOR_LATER) { + return; + } - tGATT_STATUS status = - GATTC_ExecuteWrite(p_clcb->bta_conn_id, p_data->api_exec.is_execute); + tGATT_STATUS status = GATTC_ExecuteWrite(p_clcb->bta_conn_id, p_data->api_exec.is_execute); if (status != GATT_SUCCESS) { /* Dequeue the data, if it was enqueued */ - if (p_clcb->p_q_cmd == p_data) p_clcb->p_q_cmd = NULL; + if (p_clcb->p_q_cmd == p_data) { + p_clcb->p_q_cmd = NULL; + } - bta_gattc_cmpl_sendmsg(p_clcb->bta_conn_id, GATTC_OPTYPE_EXE_WRITE, status, - NULL); + bta_gattc_cmpl_sendmsg(p_clcb->bta_conn_id, GATTC_OPTYPE_EXE_WRITE, status, NULL); bta_gattc_continue(p_clcb); } } @@ -1122,8 +1081,7 @@ void bta_gattc_execute(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data) { void bta_gattc_confirm(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data) { uint16_t cid = p_data->api_confirm.cid; - if (GATTC_SendHandleValueConfirm(p_data->api_confirm.hdr.layer_specific, - cid) != GATT_SUCCESS) { + if (GATTC_SendHandleValueConfirm(p_data->api_confirm.hdr.layer_specific, cid) != GATT_SUCCESS) { log::error("to cid=0x{:x} failed", cid); } else { /* if over BR_EDR, inform PM for mode change */ @@ -1135,8 +1093,7 @@ void bta_gattc_confirm(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data) { } /** read complete */ -static void bta_gattc_read_cmpl(tBTA_GATTC_CLCB* p_clcb, - const tBTA_GATTC_OP_CMPL* p_data) { +static void bta_gattc_read_cmpl(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_OP_CMPL* p_data) { void* my_cb_data; if (!p_clcb->p_q_cmd->api_read.is_multi_read) { @@ -1147,14 +1104,15 @@ static void bta_gattc_read_cmpl(tBTA_GATTC_CLCB* p_clcb, * use handle returned from remote */ uint16_t handle = p_clcb->p_q_cmd->api_read.handle; - if (handle == 0) handle = p_data->p_cmpl->att_value.handle; + if (handle == 0) { + handle = p_data->p_cmpl->att_value.handle; + } osi_free_and_reset((void**)&p_clcb->p_q_cmd); if (cb) { - cb(p_clcb->bta_conn_id, p_data->status, handle, - p_data->p_cmpl->att_value.len, p_data->p_cmpl->att_value.value, - my_cb_data); + cb(p_clcb->bta_conn_id, p_data->status, handle, p_data->p_cmpl->att_value.len, + p_data->p_cmpl->att_value.value, my_cb_data); } } else { GATT_READ_MULTI_OP_CB cb = p_clcb->p_q_cmd->api_read_multi.read_cb; @@ -1164,37 +1122,31 @@ static void bta_gattc_read_cmpl(tBTA_GATTC_CLCB* p_clcb, osi_free_and_reset((void**)&p_clcb->p_q_cmd); if (cb) { - cb(p_clcb->bta_conn_id, p_data->status, handles, - p_data->p_cmpl->att_value.len, p_data->p_cmpl->att_value.value, - my_cb_data); + cb(p_clcb->bta_conn_id, p_data->status, handles, p_data->p_cmpl->att_value.len, + p_data->p_cmpl->att_value.value, my_cb_data); } } } /** write complete */ -static void bta_gattc_write_cmpl(tBTA_GATTC_CLCB* p_clcb, - const tBTA_GATTC_OP_CMPL* p_data) { +static void bta_gattc_write_cmpl(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_OP_CMPL* p_data) { GATT_WRITE_OP_CB cb = p_clcb->p_q_cmd->api_write.write_cb; void* my_cb_data = p_clcb->p_q_cmd->api_write.write_cb_data; if (cb) { - if (p_data->status == 0 && - p_clcb->p_q_cmd->api_write.write_type == BTA_GATTC_WRITE_PREPARE) { + if (p_data->status == 0 && p_clcb->p_q_cmd->api_write.write_type == BTA_GATTC_WRITE_PREPARE) { log::debug("Handling prepare write success response: handle 0x{:04x}", p_data->p_cmpl->att_value.handle); /* If this is successful Prepare write, lets provide to the callback the * data provided by server */ cb(p_clcb->bta_conn_id, p_data->status, p_data->p_cmpl->att_value.handle, - p_data->p_cmpl->att_value.len, p_data->p_cmpl->att_value.value, - my_cb_data); + p_data->p_cmpl->att_value.len, p_data->p_cmpl->att_value.value, my_cb_data); } else { log::debug("Handling write response type: {}: handle 0x{:04x}", - p_clcb->p_q_cmd->api_write.write_type, - p_data->p_cmpl->att_value.handle); + p_clcb->p_q_cmd->api_write.write_type, p_data->p_cmpl->att_value.handle); /* Otherwise, provide data which were intended to write. */ cb(p_clcb->bta_conn_id, p_data->status, p_data->p_cmpl->att_value.handle, - p_clcb->p_q_cmd->api_write.len, p_clcb->p_q_cmd->api_write.p_value, - my_cb_data); + p_clcb->p_q_cmd->api_write.len, p_clcb->p_q_cmd->api_write.p_value, my_cb_data); } } @@ -1202,8 +1154,7 @@ static void bta_gattc_write_cmpl(tBTA_GATTC_CLCB* p_clcb, } /** execute write complete */ -static void bta_gattc_exec_cmpl(tBTA_GATTC_CLCB* p_clcb, - const tBTA_GATTC_OP_CMPL* p_data) { +static void bta_gattc_exec_cmpl(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_OP_CMPL* p_data) { tBTA_GATTC cb_data; osi_free_and_reset((void**)&p_clcb->p_q_cmd); @@ -1217,16 +1168,16 @@ static void bta_gattc_exec_cmpl(tBTA_GATTC_CLCB* p_clcb, } /** configure MTU operation complete */ -static void bta_gattc_cfg_mtu_cmpl(tBTA_GATTC_CLCB* p_clcb, - const tBTA_GATTC_OP_CMPL* p_data) { +static void bta_gattc_cfg_mtu_cmpl(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_OP_CMPL* p_data) { GATT_CONFIGURE_MTU_OP_CB cb = p_clcb->p_q_cmd->api_mtu.mtu_cb; void* my_cb_data = p_clcb->p_q_cmd->api_mtu.mtu_cb_data; tBTA_GATTC cb_data; osi_free_and_reset((void**)&p_clcb->p_q_cmd); - if (p_data->p_cmpl && p_data->status == GATT_SUCCESS) + if (p_data->p_cmpl && p_data->status == GATT_SUCCESS) { p_clcb->p_srcb->mtu = p_data->p_cmpl->mtu; + } /* configure MTU complete, callback */ p_clcb->status = p_data->status; @@ -1265,14 +1216,13 @@ void bta_gattc_op_cmpl(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data) { return; } - if (p_clcb->p_q_cmd->hdr.event != - bta_gattc_opcode_to_int_evt[op - GATTC_OPTYPE_READ] && - (p_clcb->p_q_cmd->hdr.event != BTA_GATTC_API_READ_MULTI_EVT || - op != GATTC_OPTYPE_READ)) { - uint8_t mapped_op = - p_clcb->p_q_cmd->hdr.event - BTA_GATTC_API_READ_EVT + GATTC_OPTYPE_READ; + if (p_clcb->p_q_cmd->hdr.event != bta_gattc_opcode_to_int_evt[op - GATTC_OPTYPE_READ] && + (p_clcb->p_q_cmd->hdr.event != BTA_GATTC_API_READ_MULTI_EVT || op != GATTC_OPTYPE_READ)) { + uint8_t mapped_op = p_clcb->p_q_cmd->hdr.event - BTA_GATTC_API_READ_EVT + GATTC_OPTYPE_READ; - if (mapped_op > GATTC_OPTYPE_INDICATION) mapped_op = 0; + if (mapped_op > GATTC_OPTYPE_INDICATION) { + mapped_op = 0; + } log::error("expect op:({} :0x{:04x}), receive unexpected operation ({}).", bta_gattc_op_code_name[mapped_op], p_clcb->p_q_cmd->hdr.event, @@ -1283,10 +1233,9 @@ void bta_gattc_op_cmpl(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data) { /* Except for MTU configuration, discard responses if service change * indication is received before operation completed */ - if (p_clcb->auto_update == BTA_GATTC_DISC_WAITING && - p_clcb->p_srcb->srvc_hdl_chg && op != GATTC_OPTYPE_CONFIG) { - log::verbose( - "Discard all responses when service change indication is received."); + if (p_clcb->auto_update == BTA_GATTC_DISC_WAITING && p_clcb->p_srcb->srvc_hdl_chg && + op != GATTC_OPTYPE_CONFIG) { + log::verbose("Discard all responses when service change indication is received."); // TODO Fix constness const_cast(p_data)->op_cmpl.status = GATT_ERROR; } @@ -1305,8 +1254,7 @@ void bta_gattc_op_cmpl(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data) { * lets trigger them now. */ - auto outstanding_conn_ids = - GATTC_GetAndRemoveListOfConnIdsWaitingForMtuRequest(p_clcb->bda); + auto outstanding_conn_ids = GATTC_GetAndRemoveListOfConnIdsWaitingForMtuRequest(p_clcb->bda); for (auto conn_id : outstanding_conn_ids) { tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_clcb_by_conn_id(conn_id); log::debug("Continue MTU request clcb {}", fmt::ptr(p_clcb)); @@ -1365,8 +1313,7 @@ void bta_gattc_q_cmd(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data) { } /** report API call failure back to apps */ -void bta_gattc_fail(tBTA_GATTC_CLCB* p_clcb, - const tBTA_GATTC_DATA* /* p_data */) { +void bta_gattc_fail(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* /* p_data */) { if (p_clcb->status == GATT_SUCCESS) { log::error("operation not supported at current state {}", p_clcb->state); } @@ -1386,36 +1333,31 @@ static void bta_gattc_deregister_cmpl(tBTA_GATTC_RCB* p_clreg) { cb_data.reg_oper.client_if = client_if; cb_data.reg_oper.status = GATT_SUCCESS; - if (p_cback) /* callback with de-register event */ + if (p_cback) { /* callback with de-register event */ (*p_cback)(BTA_GATTC_DEREG_EVT, &cb_data); + } - if (bta_gattc_num_reg_app() == 0 && - bta_gattc_cb.state == BTA_GATTC_STATE_DISABLING) { + if (bta_gattc_num_reg_app() == 0 && bta_gattc_cb.state == BTA_GATTC_STATE_DISABLING) { bta_gattc_cb.state = BTA_GATTC_STATE_DISABLED; } } /** callback functions to GATT client stack */ -static void bta_gattc_conn_cback(tGATT_IF gattc_if, const RawAddress& bdaddr, - uint16_t conn_id, bool connected, - tGATT_DISCONN_REASON reason, +static void bta_gattc_conn_cback(tGATT_IF gattc_if, const RawAddress& bdaddr, uint16_t conn_id, + bool connected, tGATT_DISCONN_REASON reason, tBT_TRANSPORT transport) { if (connected) { - log::info("Connected client_if:{} addr:{}, transport:{} reason:{}", - gattc_if, bdaddr, bt_transport_text(transport), - gatt_disconnection_reason_text(reason)); + log::info("Connected client_if:{} addr:{}, transport:{} reason:{}", gattc_if, bdaddr, + bt_transport_text(transport), gatt_disconnection_reason_text(reason)); btif_debug_conn_state(bdaddr, BTIF_DEBUG_CONNECTED, GATT_CONN_OK); } else { - log::info("Disconnected att_id:{} addr:{}, transport:{} reason:{}", - gattc_if, bdaddr, bt_transport_text(transport), - gatt_disconnection_reason_text(reason)); + log::info("Disconnected att_id:{} addr:{}, transport:{} reason:{}", gattc_if, bdaddr, + bt_transport_text(transport), gatt_disconnection_reason_text(reason)); btif_debug_conn_state(bdaddr, BTIF_DEBUG_DISCONNECTED, GATT_CONN_OK); } - tBTA_GATTC_DATA* p_buf = - (tBTA_GATTC_DATA*)osi_calloc(sizeof(tBTA_GATTC_DATA)); - p_buf->int_conn.hdr.event = - connected ? BTA_GATTC_INT_CONN_EVT : BTA_GATTC_INT_DISCONN_EVT; + tBTA_GATTC_DATA* p_buf = (tBTA_GATTC_DATA*)osi_calloc(sizeof(tBTA_GATTC_DATA)); + p_buf->int_conn.hdr.event = connected ? BTA_GATTC_INT_CONN_EVT : BTA_GATTC_INT_DISCONN_EVT; p_buf->int_conn.hdr.layer_specific = conn_id; p_buf->int_conn.client_if = gattc_if; p_buf->int_conn.role = L2CA_GetBleConnRole(bdaddr); @@ -1428,15 +1370,15 @@ static void bta_gattc_conn_cback(tGATT_IF gattc_if, const RawAddress& bdaddr, /** encryption complete callback function to GATT client stack */ static void bta_gattc_enc_cmpl_cback(tGATT_IF gattc_if, const RawAddress& bda) { - tBTA_GATTC_CLCB* p_clcb = - bta_gattc_find_clcb_by_cif(gattc_if, bda, BT_TRANSPORT_LE); + tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_clcb_by_cif(gattc_if, bda, BT_TRANSPORT_LE); - if (p_clcb == NULL) return; + if (p_clcb == NULL) { + return; + } log::verbose("cif:{}", gattc_if); - do_in_main_thread(FROM_HERE, - base::BindOnce(&bta_gattc_process_enc_cmpl, gattc_if, bda)); + do_in_main_thread(FROM_HERE, base::BindOnce(&bta_gattc_process_enc_cmpl, gattc_if, bda)); } /** process refresh API to delete cache and start a new discovery if currently @@ -1469,12 +1411,9 @@ void bta_gattc_process_api_refresh(const RawAddress& remote_bda) { } /** process service change indication */ -static bool bta_gattc_process_srvc_chg_ind(uint16_t conn_id, - tBTA_GATTC_RCB* p_clrcb, - tBTA_GATTC_SERV* p_srcb, - tBTA_GATTC_CLCB* p_clcb, - tBTA_GATTC_NOTIFY* p_notify, - tGATT_VALUE* att_value) { +static bool bta_gattc_process_srvc_chg_ind(uint16_t conn_id, tBTA_GATTC_RCB* p_clrcb, + tBTA_GATTC_SERV* p_srcb, tBTA_GATTC_CLCB* p_clcb, + tBTA_GATTC_NOTIFY* p_notify, tGATT_VALUE* att_value) { Uuid gattp_uuid = Uuid::From16Bit(UUID_SERVCLASS_GATT_SERVER); Uuid srvc_chg_uuid = Uuid::From16Bit(GATT_UUID_GATT_SRV_CHGD); @@ -1485,11 +1424,11 @@ static bool bta_gattc_process_srvc_chg_ind(uint16_t conn_id, } } - const gatt::Characteristic* p_char = - bta_gattc_get_characteristic_srcb(p_srcb, p_notify->handle); - if (!p_char) return false; - const gatt::Service* p_svc = - bta_gattc_get_service_for_handle_srcb(p_srcb, p_char->value_handle); + const gatt::Characteristic* p_char = bta_gattc_get_characteristic_srcb(p_srcb, p_notify->handle); + if (!p_char) { + return false; + } + const gatt::Service* p_svc = bta_gattc_get_service_for_handle_srcb(p_srcb, p_char->value_handle); if (!p_svc || p_svc->uuid != gattp_uuid || p_char->uuid != srvc_chg_uuid) { return false; } @@ -1503,8 +1442,7 @@ static bool bta_gattc_process_srvc_chg_ind(uint16_t conn_id, uint16_t s_handle = ((uint16_t)(*(p)) + (((uint16_t)(*(p + 1))) << 8)); uint16_t e_handle = ((uint16_t)(*(p + 2)) + (((uint16_t)(*(p + 3))) << 8)); - log::error("service changed s_handle=0x{:x}, e_handle=0x{:x}", s_handle, - e_handle); + log::error("service changed s_handle=0x{:x}, e_handle=0x{:x}", s_handle, e_handle); /* mark service handle change pending */ p_srcb->srvc_hdl_chg = true; @@ -1516,8 +1454,7 @@ static bool bta_gattc_process_srvc_chg_ind(uint16_t conn_id, /* search for first available clcb and start discovery */ if (p_clcb == NULL || (p_clcb && p_clcb->p_q_cmd != NULL)) { for (size_t i = 0; i < BTA_GATTC_CLCB_MAX; i++) { - if (bta_gattc_cb.clcb[i].in_use && - bta_gattc_cb.clcb[i].p_srcb == p_srcb && + if (bta_gattc_cb.clcb[i].in_use && bta_gattc_cb.clcb[i].p_srcb == p_srcb && bta_gattc_cb.clcb[i].p_q_cmd == NULL) { p_clcb = &bta_gattc_cb.clcb[i]; break; @@ -1526,10 +1463,8 @@ static bool bta_gattc_process_srvc_chg_ind(uint16_t conn_id, } /* send confirmation here if this is an indication, it should always be */ if (GATTC_SendHandleValueConfirm(conn_id, p_notify->cid) != GATT_SUCCESS) { - log::warn( - "Unable to send GATT client handle value confirmation conn_id:{} " - "cid:{}", - conn_id, p_notify->cid); + log::warn("Unable to send GATT client handle value confirmation conn_id:{} cid:{}", conn_id, + p_notify->cid); } /* if connection available, refresh cache by doing discovery now */ @@ -1555,8 +1490,8 @@ static bool bta_gattc_process_srvc_chg_ind(uint16_t conn_id, static void bta_gattc_proc_other_indication(tBTA_GATTC_CLCB* p_clcb, uint8_t op, tGATT_CL_COMPLETE* p_data, tBTA_GATTC_NOTIFY* p_notify) { - log::verbose("check p_data->att_value.handle={} p_data->handle={}", - p_data->att_value.handle, p_data->handle); + log::verbose("check p_data->att_value.handle={} p_data->handle={}", p_data->att_value.handle, + p_data->handle); log::verbose("is_notify {}", p_notify->is_notify); p_notify->is_notify = (op == GATTC_OPTYPE_INDICATION) ? false : true; @@ -1585,10 +1520,8 @@ static void bta_gattc_process_indicate(uint16_t conn_id, tGATTC_OPTYPE op, log::error("indication/notif for unknown app"); if (op == GATTC_OPTYPE_INDICATION) { if (GATTC_SendHandleValueConfirm(conn_id, p_data->cid) != GATT_SUCCESS) { - log::warn( - "Unable to send GATT client handle value confirmation conn_id:{} " - "cid:{}", - conn_id, p_data->cid); + log::warn("Unable to send GATT client handle value confirmation conn_id:{} cid:{}", conn_id, + p_data->cid); } } return; @@ -1599,10 +1532,8 @@ static void bta_gattc_process_indicate(uint16_t conn_id, tGATTC_OPTYPE op, log::error("indication/notif for unregistered app"); if (op == GATTC_OPTYPE_INDICATION) { if (GATTC_SendHandleValueConfirm(conn_id, p_data->cid) != GATT_SUCCESS) { - log::warn( - "Unable to send GATT client handle value confirmation conn_id:{} " - "cid:{}", - conn_id, p_data->cid); + log::warn("Unable to send GATT client handle value confirmation conn_id:{} cid:{}", conn_id, + p_data->cid); } } return; @@ -1613,10 +1544,8 @@ static void bta_gattc_process_indicate(uint16_t conn_id, tGATTC_OPTYPE op, log::error("indication/notif for unknown device, ignore"); if (op == GATTC_OPTYPE_INDICATION) { if (GATTC_SendHandleValueConfirm(conn_id, p_data->cid) != GATT_SUCCESS) { - log::warn( - "Unable to send GATT client handle value confirmation conn_id:{} " - "cid:{}", - conn_id, p_data->cid); + log::warn("Unable to send GATT client handle value confirmation conn_id:{} cid:{}", conn_id, + p_data->cid); } } return; @@ -1629,8 +1558,9 @@ static void bta_gattc_process_indicate(uint16_t conn_id, tGATTC_OPTYPE op, /* if service change indication/notification, don't forward to application */ if (bta_gattc_process_srvc_chg_ind(conn_id, p_clrcb, p_srcb, p_clcb, ¬ify, - &p_data->att_value)) + &p_data->att_value)) { return; + } /* if app registered for the notification */ if (bta_gattc_check_notif_registry(p_clrcb, p_srcb, ¬ify)) { @@ -1649,24 +1579,22 @@ static void bta_gattc_process_indicate(uint16_t conn_id, tGATTC_OPTYPE op, bta_gattc_sm_execute(p_clcb, BTA_GATTC_INT_CONN_EVT, NULL); } - if (p_clcb != NULL) + if (p_clcb != NULL) { bta_gattc_proc_other_indication(p_clcb, op, p_data, ¬ify); + } } /* no one intersted and need ack? */ else if (op == GATTC_OPTYPE_INDICATION) { log::verbose("no one interested, ack now"); if (GATTC_SendHandleValueConfirm(conn_id, p_data->cid) != GATT_SUCCESS) { - log::warn( - "Unable to send GATT client handle value confirmation conn_id:{} " - "cid:{}", - conn_id, p_data->cid); + log::warn("Unable to send GATT client handle value confirmation conn_id:{} cid:{}", conn_id, + p_data->cid); } } } /** client operation complete callback register with BTE GATT */ -static void bta_gattc_cmpl_cback(uint16_t conn_id, tGATTC_OPTYPE op, - tGATT_STATUS status, +static void bta_gattc_cmpl_cback(uint16_t conn_id, tGATTC_OPTYPE op, tGATT_STATUS status, tGATT_CL_COMPLETE* p_data) { log::verbose("conn_id:{} op:{} status:{}", conn_id, op, status); @@ -1692,8 +1620,8 @@ static void bta_gattc_cmpl_cback(uint16_t conn_id, tGATTC_OPTYPE op, } /** client operation complete send message */ -void bta_gattc_cmpl_sendmsg(uint16_t conn_id, tGATTC_OPTYPE op, - tGATT_STATUS status, tGATT_CL_COMPLETE* p_data) { +void bta_gattc_cmpl_sendmsg(uint16_t conn_id, tGATTC_OPTYPE op, tGATT_STATUS status, + tGATT_CL_COMPLETE* p_data) { const size_t len = sizeof(tBTA_GATTC_OP_CMPL) + sizeof(tGATT_CL_COMPLETE); tBTA_GATTC_OP_CMPL* p_buf = (tBTA_GATTC_OP_CMPL*)osi_calloc(len); @@ -1713,7 +1641,9 @@ void bta_gattc_cmpl_sendmsg(uint16_t conn_id, tGATTC_OPTYPE op, /** congestion callback for BTA GATT client */ static void bta_gattc_cong_cback(uint16_t conn_id, bool congested) { tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_clcb_by_conn_id(conn_id); - if (!p_clcb || !p_clcb->p_rcb->p_cback) return; + if (!p_clcb || !p_clcb->p_rcb->p_cback) { + return; + } tBTA_GATTC cb_data; cb_data.congest.conn_id = conn_id; @@ -1722,9 +1652,8 @@ static void bta_gattc_cong_cback(uint16_t conn_id, bool congested) { (*p_clcb->p_rcb->p_cback)(BTA_GATTC_CONGEST_EVT, &cb_data); } -static void bta_gattc_phy_update_cback(tGATT_IF gatt_if, uint16_t conn_id, - uint8_t tx_phy, uint8_t rx_phy, - tGATT_STATUS status) { +static void bta_gattc_phy_update_cback(tGATT_IF gatt_if, uint16_t conn_id, uint8_t tx_phy, + uint8_t rx_phy, tGATT_STATUS status) { tBTA_GATTC_RCB* p_clreg = bta_gattc_cl_get_regcb(gatt_if); if (!p_clreg || !p_clreg->p_cback) { @@ -1741,9 +1670,8 @@ static void bta_gattc_phy_update_cback(tGATT_IF gatt_if, uint16_t conn_id, (*p_clreg->p_cback)(BTA_GATTC_PHY_UPDATE_EVT, &cb_data); } -static void bta_gattc_conn_update_cback(tGATT_IF gatt_if, uint16_t conn_id, - uint16_t interval, uint16_t latency, - uint16_t timeout, tGATT_STATUS status) { +static void bta_gattc_conn_update_cback(tGATT_IF gatt_if, uint16_t conn_id, uint16_t interval, + uint16_t latency, uint16_t timeout, tGATT_STATUS status) { tBTA_GATTC_RCB* p_clreg = bta_gattc_cl_get_regcb(gatt_if); if (!p_clreg || !p_clreg->p_cback) { @@ -1760,10 +1688,9 @@ static void bta_gattc_conn_update_cback(tGATT_IF gatt_if, uint16_t conn_id, (*p_clreg->p_cback)(BTA_GATTC_CONN_UPDATE_EVT, &cb_data); } -static void bta_gattc_subrate_chg_cback(tGATT_IF gatt_if, uint16_t conn_id, - uint16_t subrate_factor, - uint16_t latency, uint16_t cont_num, - uint16_t timeout, tGATT_STATUS status) { +static void bta_gattc_subrate_chg_cback(tGATT_IF gatt_if, uint16_t conn_id, uint16_t subrate_factor, + uint16_t latency, uint16_t cont_num, uint16_t timeout, + tGATT_STATUS status) { tBTA_GATTC_RCB* p_clreg = bta_gattc_cl_get_regcb(gatt_if); if (!p_clreg || !p_clreg->p_cback) { diff --git a/system/bta/gatt/bta_gattc_api.cc b/system/bta/gatt/bta_gattc_api.cc index 66b1e0f91f0..7dc3140a97e 100644 --- a/system/bta/gatt/bta_gattc_api.cc +++ b/system/bta/gatt/bta_gattc_api.cc @@ -49,8 +49,7 @@ using namespace bluetooth; * Constants ****************************************************************************/ -static const tBTA_SYS_REG bta_gattc_reg = {bta_gattc_hdl_event, - BTA_GATTC_Disable}; +static const tBTA_SYS_REG bta_gattc_reg = {bta_gattc_hdl_event, BTA_GATTC_Disable}; /******************************************************************************* * @@ -78,20 +77,18 @@ void BTA_GATTC_Disable(void) { * module. |client_cb| pointer to the application callback function. * |cb| one time callback when registration is finished */ -void BTA_GATTC_AppRegister(tBTA_GATTC_CBACK* p_client_cb, - BtaAppRegisterCallback cb, bool eatt_support) { +void BTA_GATTC_AppRegister(tBTA_GATTC_CBACK* p_client_cb, BtaAppRegisterCallback cb, + bool eatt_support) { log::debug("eatt_support={}", eatt_support); if (!bta_sys_is_register(BTA_ID_GATTC)) { log::debug("BTA_ID_GATTC not registered in BTA, registering it"); bta_sys_register(BTA_ID_GATTC, &bta_gattc_reg); } - Uuid uuid = - Uuid::From128BitBE(bluetooth::os::GenerateRandom()); + Uuid uuid = Uuid::From128BitBE(bluetooth::os::GenerateRandom()); - do_in_main_thread(FROM_HERE, - base::BindOnce(&bta_gattc_register, uuid, p_client_cb, - std::move(cb), eatt_support)); + do_in_main_thread(FROM_HERE, base::BindOnce(&bta_gattc_register, uuid, p_client_cb, std::move(cb), + eatt_support)); } static void app_deregister_impl(tGATT_IF client_if) { @@ -140,39 +137,37 @@ void BTA_GATTC_Open(tGATT_IF client_if, const RawAddress& remote_bda, tBTM_BLE_CONN_TYPE connection_type, bool opportunistic) { constexpr uint8_t kPhyLe1M = 0x01; // From the old controller shim. uint8_t phy = kPhyLe1M; - BTA_GATTC_Open(client_if, remote_bda, connection_type, BT_TRANSPORT_LE, - opportunistic, phy); + BTA_GATTC_Open(client_if, remote_bda, connection_type, BT_TRANSPORT_LE, opportunistic, phy); } -void BTA_GATTC_Open(tGATT_IF client_if, const RawAddress& remote_bda, - tBLE_ADDR_TYPE addr_type, - tBTM_BLE_CONN_TYPE connection_type, tBT_TRANSPORT transport, - bool opportunistic, uint8_t initiating_phys) { +void BTA_GATTC_Open(tGATT_IF client_if, const RawAddress& remote_bda, tBLE_ADDR_TYPE addr_type, + tBTM_BLE_CONN_TYPE connection_type, tBT_TRANSPORT transport, bool opportunistic, + uint8_t initiating_phys) { tBTA_GATTC_DATA data = { - .api_conn = - { - .hdr = + .api_conn = { - .event = BTA_GATTC_API_OPEN_EVT, + .hdr = + { + .event = BTA_GATTC_API_OPEN_EVT, + }, + .remote_bda = remote_bda, + .client_if = client_if, + .connection_type = connection_type, + .transport = transport, + .initiating_phys = initiating_phys, + .opportunistic = opportunistic, + .remote_addr_type = addr_type, }, - .remote_bda = remote_bda, - .client_if = client_if, - .connection_type = connection_type, - .transport = transport, - .initiating_phys = initiating_phys, - .opportunistic = opportunistic, - .remote_addr_type = addr_type, - }, }; post_on_bt_main([data]() { bta_gattc_process_api_open(&data); }); } void BTA_GATTC_Open(tGATT_IF client_if, const RawAddress& remote_bda, - tBTM_BLE_CONN_TYPE connection_type, tBT_TRANSPORT transport, - bool opportunistic, uint8_t initiating_phys) { - BTA_GATTC_Open(client_if, remote_bda, BLE_ADDR_PUBLIC, connection_type, - BT_TRANSPORT_LE, opportunistic, initiating_phys); + tBTM_BLE_CONN_TYPE connection_type, tBT_TRANSPORT transport, bool opportunistic, + uint8_t initiating_phys) { + BTA_GATTC_Open(client_if, remote_bda, BLE_ADDR_PUBLIC, connection_type, BT_TRANSPORT_LE, + opportunistic, initiating_phys); } /******************************************************************************* @@ -190,10 +185,9 @@ void BTA_GATTC_Open(tGATT_IF client_if, const RawAddress& remote_bda, * Returns void * ******************************************************************************/ -void BTA_GATTC_CancelOpen(tGATT_IF client_if, const RawAddress& remote_bda, - bool is_direct) { - tBTA_GATTC_API_CANCEL_OPEN* p_buf = (tBTA_GATTC_API_CANCEL_OPEN*)osi_malloc( - sizeof(tBTA_GATTC_API_CANCEL_OPEN)); +void BTA_GATTC_CancelOpen(tGATT_IF client_if, const RawAddress& remote_bda, bool is_direct) { + tBTA_GATTC_API_CANCEL_OPEN* p_buf = + (tBTA_GATTC_API_CANCEL_OPEN*)osi_malloc(sizeof(tBTA_GATTC_API_CANCEL_OPEN)); p_buf->hdr.event = BTA_GATTC_API_CANCEL_OPEN_EVT; p_buf->client_if = client_if; @@ -241,10 +235,10 @@ void BTA_GATTC_ConfigureMTU(uint16_t conn_id, uint16_t mtu) { BTA_GATTC_ConfigureMTU(conn_id, mtu, NULL, NULL); } -void BTA_GATTC_ConfigureMTU(uint16_t conn_id, uint16_t mtu, - GATT_CONFIGURE_MTU_OP_CB callback, void* cb_data) { +void BTA_GATTC_ConfigureMTU(uint16_t conn_id, uint16_t mtu, GATT_CONFIGURE_MTU_OP_CB callback, + void* cb_data) { tBTA_GATTC_API_CFG_MTU* p_buf = - (tBTA_GATTC_API_CFG_MTU*)osi_malloc(sizeof(tBTA_GATTC_API_CFG_MTU)); + (tBTA_GATTC_API_CFG_MTU*)osi_malloc(sizeof(tBTA_GATTC_API_CFG_MTU)); p_buf->hdr.event = BTA_GATTC_API_CFG_MTU_EVT; p_buf->hdr.layer_specific = conn_id; @@ -280,12 +274,11 @@ void BTA_GATTC_ServiceSearchRequest(uint16_t conn_id, Uuid p_srvc_uuid) { void BTA_GATTC_DiscoverServiceByUuid(uint16_t conn_id, const Uuid& srvc_uuid) { do_in_main_thread( - FROM_HERE, - base::BindOnce( - base::IgnoreResult( - &GATTC_Discover), - conn_id, GATT_DISC_SRVC_BY_UUID, 0x0001, 0xFFFF, srvc_uuid)); + FROM_HERE, + base::BindOnce( + base::IgnoreResult(&GATTC_Discover), + conn_id, GATT_DISC_SRVC_BY_UUID, 0x0001, 0xFFFF, srvc_uuid)); } /******************************************************************************* @@ -317,8 +310,7 @@ const std::list* BTA_GATTC_GetServices(uint16_t conn_id) { * Returns returns pointer to gatt::Characteristic or NULL. * ******************************************************************************/ -const gatt::Characteristic* BTA_GATTC_GetCharacteristic(uint16_t conn_id, - uint16_t handle) { +const gatt::Characteristic* BTA_GATTC_GetCharacteristic(uint16_t conn_id, uint16_t handle) { return bta_gattc_get_characteristic(conn_id, handle); } @@ -335,22 +327,19 @@ const gatt::Characteristic* BTA_GATTC_GetCharacteristic(uint16_t conn_id, * Returns returns pointer to gatt::Descriptor or NULL. * ******************************************************************************/ -const gatt::Descriptor* BTA_GATTC_GetDescriptor(uint16_t conn_id, - uint16_t handle) { +const gatt::Descriptor* BTA_GATTC_GetDescriptor(uint16_t conn_id, uint16_t handle) { return bta_gattc_get_descriptor(conn_id, handle); } /* Return characteristic that owns descriptor with handle equal to |handle|, or * NULL */ -const gatt::Characteristic* BTA_GATTC_GetOwningCharacteristic(uint16_t conn_id, - uint16_t handle) { +const gatt::Characteristic* BTA_GATTC_GetOwningCharacteristic(uint16_t conn_id, uint16_t handle) { return bta_gattc_get_owning_characteristic(conn_id, handle); } /* Return service that owns descriptor or characteristic with handle equal to * |handle|, or NULL */ -const gatt::Service* BTA_GATTC_GetOwningService(uint16_t conn_id, - uint16_t handle) { +const gatt::Service* BTA_GATTC_GetOwningService(uint16_t conn_id, uint16_t handle) { return bta_gattc_get_service_for_handle(conn_id, handle); } @@ -366,9 +355,8 @@ const gatt::Service* BTA_GATTC_GetOwningService(uint16_t conn_id, * count: number of elements in database. * ******************************************************************************/ -void BTA_GATTC_GetGattDb(uint16_t conn_id, uint16_t start_handle, - uint16_t end_handle, btgatt_db_element_t** db, - int* count) { +void BTA_GATTC_GetGattDb(uint16_t conn_id, uint16_t start_handle, uint16_t end_handle, + btgatt_db_element_t** db, int* count) { bta_gattc_get_gatt_db(conn_id, start_handle, end_handle, db, count); } @@ -384,11 +372,9 @@ void BTA_GATTC_GetGattDb(uint16_t conn_id, uint16_t start_handle, * Returns None * ******************************************************************************/ -void BTA_GATTC_ReadCharacteristic(uint16_t conn_id, uint16_t handle, - tGATT_AUTH_REQ auth_req, +void BTA_GATTC_ReadCharacteristic(uint16_t conn_id, uint16_t handle, tGATT_AUTH_REQ auth_req, GATT_READ_OP_CB callback, void* cb_data) { - tBTA_GATTC_API_READ* p_buf = - (tBTA_GATTC_API_READ*)osi_calloc(sizeof(tBTA_GATTC_API_READ)); + tBTA_GATTC_API_READ* p_buf = (tBTA_GATTC_API_READ*)osi_calloc(sizeof(tBTA_GATTC_API_READ)); p_buf->hdr.event = BTA_GATTC_API_READ_EVT; p_buf->hdr.layer_specific = conn_id; @@ -405,12 +391,10 @@ void BTA_GATTC_ReadCharacteristic(uint16_t conn_id, uint16_t handle, * This function is called to read a value of characteristic with uuid equal to * |uuid| */ -void BTA_GATTC_ReadUsingCharUuid(uint16_t conn_id, const Uuid& uuid, - uint16_t s_handle, uint16_t e_handle, - tGATT_AUTH_REQ auth_req, +void BTA_GATTC_ReadUsingCharUuid(uint16_t conn_id, const Uuid& uuid, uint16_t s_handle, + uint16_t e_handle, tGATT_AUTH_REQ auth_req, GATT_READ_OP_CB callback, void* cb_data) { - tBTA_GATTC_API_READ* p_buf = - (tBTA_GATTC_API_READ*)osi_calloc(sizeof(tBTA_GATTC_API_READ)); + tBTA_GATTC_API_READ* p_buf = (tBTA_GATTC_API_READ*)osi_calloc(sizeof(tBTA_GATTC_API_READ)); p_buf->hdr.event = BTA_GATTC_API_READ_EVT; p_buf->hdr.layer_specific = conn_id; @@ -438,11 +422,9 @@ void BTA_GATTC_ReadUsingCharUuid(uint16_t conn_id, const Uuid& uuid, * Returns None * ******************************************************************************/ -void BTA_GATTC_ReadCharDescr(uint16_t conn_id, uint16_t handle, - tGATT_AUTH_REQ auth_req, GATT_READ_OP_CB callback, - void* cb_data) { - tBTA_GATTC_API_READ* p_buf = - (tBTA_GATTC_API_READ*)osi_calloc(sizeof(tBTA_GATTC_API_READ)); +void BTA_GATTC_ReadCharDescr(uint16_t conn_id, uint16_t handle, tGATT_AUTH_REQ auth_req, + GATT_READ_OP_CB callback, void* cb_data) { + tBTA_GATTC_API_READ* p_buf = (tBTA_GATTC_API_READ*)osi_calloc(sizeof(tBTA_GATTC_API_READ)); p_buf->hdr.event = BTA_GATTC_API_READ_EVT; p_buf->hdr.layer_specific = conn_id; @@ -471,11 +453,11 @@ void BTA_GATTC_ReadCharDescr(uint16_t conn_id, uint16_t handle, * Returns None * ******************************************************************************/ -void BTA_GATTC_ReadMultiple(uint16_t conn_id, tBTA_GATTC_MULTI& handles, - bool variable_len, tGATT_AUTH_REQ auth_req, - GATT_READ_MULTI_OP_CB callback, void* cb_data) { +void BTA_GATTC_ReadMultiple(uint16_t conn_id, tBTA_GATTC_MULTI& handles, bool variable_len, + tGATT_AUTH_REQ auth_req, GATT_READ_MULTI_OP_CB callback, + void* cb_data) { tBTA_GATTC_API_READ_MULTI* p_buf = - (tBTA_GATTC_API_READ_MULTI*)osi_calloc(sizeof(tBTA_GATTC_API_READ_MULTI)); + (tBTA_GATTC_API_READ_MULTI*)osi_calloc(sizeof(tBTA_GATTC_API_READ_MULTI)); p_buf->hdr.event = BTA_GATTC_API_READ_MULTI_EVT; p_buf->hdr.layer_specific = conn_id; @@ -502,13 +484,11 @@ void BTA_GATTC_ReadMultiple(uint16_t conn_id, tBTA_GATTC_MULTI& handles, * Returns None * ******************************************************************************/ -void BTA_GATTC_WriteCharValue(uint16_t conn_id, uint16_t handle, - tGATT_WRITE_TYPE write_type, - std::vector value, - tGATT_AUTH_REQ auth_req, +void BTA_GATTC_WriteCharValue(uint16_t conn_id, uint16_t handle, tGATT_WRITE_TYPE write_type, + std::vector value, tGATT_AUTH_REQ auth_req, GATT_WRITE_OP_CB callback, void* cb_data) { - tBTA_GATTC_API_WRITE* p_buf = (tBTA_GATTC_API_WRITE*)osi_calloc( - sizeof(tBTA_GATTC_API_WRITE) + value.size()); + tBTA_GATTC_API_WRITE* p_buf = + (tBTA_GATTC_API_WRITE*)osi_calloc(sizeof(tBTA_GATTC_API_WRITE) + value.size()); p_buf->hdr.event = BTA_GATTC_API_WRITE_EVT; p_buf->hdr.layer_specific = conn_id; @@ -540,12 +520,10 @@ void BTA_GATTC_WriteCharValue(uint16_t conn_id, uint16_t handle, * Returns None * ******************************************************************************/ -void BTA_GATTC_WriteCharDescr(uint16_t conn_id, uint16_t handle, - std::vector value, - tGATT_AUTH_REQ auth_req, - GATT_WRITE_OP_CB callback, void* cb_data) { - tBTA_GATTC_API_WRITE* p_buf = (tBTA_GATTC_API_WRITE*)osi_calloc( - sizeof(tBTA_GATTC_API_WRITE) + value.size()); +void BTA_GATTC_WriteCharDescr(uint16_t conn_id, uint16_t handle, std::vector value, + tGATT_AUTH_REQ auth_req, GATT_WRITE_OP_CB callback, void* cb_data) { + tBTA_GATTC_API_WRITE* p_buf = + (tBTA_GATTC_API_WRITE*)osi_calloc(sizeof(tBTA_GATTC_API_WRITE) + value.size()); p_buf->hdr.event = BTA_GATTC_API_WRITE_EVT; p_buf->hdr.layer_specific = conn_id; @@ -582,8 +560,8 @@ void BTA_GATTC_WriteCharDescr(uint16_t conn_id, uint16_t handle, void BTA_GATTC_PrepareWrite(uint16_t conn_id, uint16_t handle, uint16_t offset, std::vector value, tGATT_AUTH_REQ auth_req, GATT_WRITE_OP_CB callback, void* cb_data) { - tBTA_GATTC_API_WRITE* p_buf = (tBTA_GATTC_API_WRITE*)osi_calloc( - sizeof(tBTA_GATTC_API_WRITE) + value.size()); + tBTA_GATTC_API_WRITE* p_buf = + (tBTA_GATTC_API_WRITE*)osi_calloc(sizeof(tBTA_GATTC_API_WRITE) + value.size()); p_buf->hdr.event = BTA_GATTC_API_WRITE_EVT; p_buf->hdr.layer_specific = conn_id; @@ -618,8 +596,7 @@ void BTA_GATTC_PrepareWrite(uint16_t conn_id, uint16_t handle, uint16_t offset, * ******************************************************************************/ void BTA_GATTC_ExecuteWrite(uint16_t conn_id, bool is_execute) { - tBTA_GATTC_API_EXEC* p_buf = - (tBTA_GATTC_API_EXEC*)osi_calloc(sizeof(tBTA_GATTC_API_EXEC)); + tBTA_GATTC_API_EXEC* p_buf = (tBTA_GATTC_API_EXEC*)osi_calloc(sizeof(tBTA_GATTC_API_EXEC)); p_buf->hdr.event = BTA_GATTC_API_EXEC_EVT; p_buf->hdr.layer_specific = conn_id; @@ -642,7 +619,7 @@ void BTA_GATTC_ExecuteWrite(uint16_t conn_id, bool is_execute) { ******************************************************************************/ void BTA_GATTC_SendIndConfirm(uint16_t conn_id, uint16_t cid) { tBTA_GATTC_API_CONFIRM* p_buf = - (tBTA_GATTC_API_CONFIRM*)osi_calloc(sizeof(tBTA_GATTC_API_CONFIRM)); + (tBTA_GATTC_API_CONFIRM*)osi_calloc(sizeof(tBTA_GATTC_API_CONFIRM)); log::verbose("conn_id={} cid=0x{:x}", conn_id, cid); @@ -667,8 +644,7 @@ void BTA_GATTC_SendIndConfirm(uint16_t conn_id, uint16_t cid) { * Returns OK if registration succeed, otherwise failed. * ******************************************************************************/ -tGATT_STATUS BTA_GATTC_RegisterForNotifications(tGATT_IF client_if, - const RawAddress& bda, +tGATT_STATUS BTA_GATTC_RegisterForNotifications(tGATT_IF client_if, const RawAddress& bda, uint16_t handle) { tBTA_GATTC_RCB* p_clreg; tGATT_STATUS status = GATT_ILLEGAL_PARAMETER; @@ -682,8 +658,7 @@ tGATT_STATUS BTA_GATTC_RegisterForNotifications(tGATT_IF client_if, p_clreg = bta_gattc_cl_get_regcb(client_if); if (p_clreg != NULL) { for (i = 0; i < BTA_GATTC_NOTIF_REG_MAX; i++) { - if (p_clreg->notif_reg[i].in_use && - p_clreg->notif_reg[i].remote_bda == bda && + if (p_clreg->notif_reg[i].in_use && p_clreg->notif_reg[i].remote_bda == bda && p_clreg->notif_reg[i].handle == handle) { log::warn("notification already registered"); status = GATT_SUCCESS; @@ -693,8 +668,7 @@ tGATT_STATUS BTA_GATTC_RegisterForNotifications(tGATT_IF client_if, if (status != GATT_SUCCESS) { for (i = 0; i < BTA_GATTC_NOTIF_REG_MAX; i++) { if (!p_clreg->notif_reg[i].in_use) { - memset((void*)&p_clreg->notif_reg[i], 0, - sizeof(tBTA_GATTC_NOTIF_REG)); + memset((void*)&p_clreg->notif_reg[i], 0, sizeof(tBTA_GATTC_NOTIF_REG)); p_clreg->notif_reg[i].in_use = true; p_clreg->notif_reg[i].remote_bda = bda; @@ -730,8 +704,7 @@ tGATT_STATUS BTA_GATTC_RegisterForNotifications(tGATT_IF client_if, * Returns OK if deregistration succeed, otherwise failed. * ******************************************************************************/ -tGATT_STATUS BTA_GATTC_DeregisterForNotifications(tGATT_IF client_if, - const RawAddress& bda, +tGATT_STATUS BTA_GATTC_DeregisterForNotifications(tGATT_IF client_if, const RawAddress& bda, uint16_t handle) { if (!handle) { log::error("deregistration failed, handle is 0"); @@ -745,8 +718,7 @@ tGATT_STATUS BTA_GATTC_DeregisterForNotifications(tGATT_IF client_if, } for (int i = 0; i < BTA_GATTC_NOTIF_REG_MAX; i++) { - if (p_clreg->notif_reg[i].in_use && - p_clreg->notif_reg[i].remote_bda == bda && + if (p_clreg->notif_reg[i].in_use && p_clreg->notif_reg[i].remote_bda == bda && p_clreg->notif_reg[i].handle == handle) { log::verbose("deregistered bd_addr={}", bda); memset(&p_clreg->notif_reg[i], 0, sizeof(tBTA_GATTC_NOTIF_REG)); @@ -770,6 +742,5 @@ tGATT_STATUS BTA_GATTC_DeregisterForNotifications(tGATT_IF client_if, * ******************************************************************************/ void BTA_GATTC_Refresh(const RawAddress& remote_bda) { - do_in_main_thread(FROM_HERE, - base::Bind(&bta_gattc_process_api_refresh, remote_bda)); + do_in_main_thread(FROM_HERE, base::Bind(&bta_gattc_process_api_refresh, remote_bda)); } diff --git a/system/bta/gatt/bta_gattc_cache.cc b/system/bta/gatt/bta_gattc_cache.cc index 9a86ed0538e..286f2156dcf 100644 --- a/system/bta/gatt/bta_gattc_cache.cc +++ b/system/bta/gatt/bta_gattc_cache.cc @@ -60,17 +60,12 @@ using gatt::Descriptor; using gatt::IncludedService; using gatt::Service; -static tGATT_STATUS bta_gattc_sdp_service_disc(uint16_t conn_id, - tBTA_GATTC_SERV* p_server_cb); -const Descriptor* bta_gattc_get_descriptor_srcb(tBTA_GATTC_SERV* p_srcb, - uint16_t handle); -const Characteristic* bta_gattc_get_characteristic_srcb(tBTA_GATTC_SERV* p_srcb, - uint16_t handle); -static void bta_gattc_explore_srvc_finished(uint16_t conn_id, - tBTA_GATTC_SERV* p_srvc_cb); - -static void bta_gattc_read_db_hash_cmpl(tBTA_GATTC_CLCB* p_clcb, - const tBTA_GATTC_OP_CMPL* p_data, +static tGATT_STATUS bta_gattc_sdp_service_disc(uint16_t conn_id, tBTA_GATTC_SERV* p_server_cb); +const Descriptor* bta_gattc_get_descriptor_srcb(tBTA_GATTC_SERV* p_srcb, uint16_t handle); +const Characteristic* bta_gattc_get_characteristic_srcb(tBTA_GATTC_SERV* p_srcb, uint16_t handle); +static void bta_gattc_explore_srvc_finished(uint16_t conn_id, tBTA_GATTC_SERV* p_srvc_cb); + +static void bta_gattc_read_db_hash_cmpl(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_OP_CMPL* p_data, bool is_svc_chg); static void bta_gattc_read_ext_prop_desc_cmpl(tBTA_GATTC_CLCB* p_clcb, @@ -120,11 +115,12 @@ void bta_gattc_init_cache(tBTA_GATTC_SERV* p_srvc_cb) { p_srvc_cb->pending_discovery.Clear(); } -const Service* bta_gattc_find_matching_service( - const std::list& services, uint16_t handle) { +const Service* bta_gattc_find_matching_service(const std::list& services, + uint16_t handle) { for (const Service& service : services) { - if (handle >= service.handle && handle <= service.end_handle) + if (handle >= service.handle && handle <= service.end_handle) { return &service; + } } return nullptr; @@ -133,8 +129,7 @@ const Service* bta_gattc_find_matching_service( /// Whether the peer device uses robust caching RobustCachingSupport GetRobustCachingSupport(const tBTA_GATTC_CLCB* p_clcb, const gatt::Database& db) { - log::debug("GetRobustCachingSupport {}", - p_clcb->bda.ToRedactedStringForLogging()); + log::debug("GetRobustCachingSupport {}", p_clcb->bda.ToRedactedStringForLogging()); // An empty database means that discovery hasn't taken place yet, so // we can't infer anything from that @@ -162,8 +157,7 @@ RobustCachingSupport GetRobustCachingSupport(const tBTA_GATTC_CLCB* p_clcb, } if (p_clcb->transport == BT_TRANSPORT_LE && - !get_btm_client_interface().ble.BTM_IsRemoteVersionReceived( - p_clcb->bda)) { + !get_btm_client_interface().ble.BTM_IsRemoteVersionReceived(p_clcb->bda)) { log::info("version info is not ready yet"); return RobustCachingSupport::W4_REMOTE_VERSION; } @@ -174,28 +168,27 @@ RobustCachingSupport GetRobustCachingSupport(const tBTA_GATTC_CLCB* p_clcb, // embedded device having LMP version lower than 5.1 (0x0a), it does not // support GATT Caching. uint8_t lmp_version = 0; - if (!get_btm_client_interface().peer.BTM_ReadRemoteVersion( - p_clcb->bda, &lmp_version, nullptr, nullptr)) { + if (!get_btm_client_interface().peer.BTM_ReadRemoteVersion(p_clcb->bda, &lmp_version, nullptr, + nullptr)) { log::warn("Could not read remote version for {}", p_clcb->bda); } if (lmp_version < 0x0a) { log::warn( - "Device LMP version 0x{:02x} < Bluetooth 5.1. Ignore database cache " - "read.", - lmp_version); + "Device LMP version 0x{:02x} < Bluetooth 5.1. Ignore database cache " + "read.", + lmp_version); return RobustCachingSupport::UNSUPPORTED; } // Some LMP 5.2 devices also don't support robust caching. This workaround // conditionally disables the feature based on a combination of LMP // version and OUI prefix. - if (lmp_version < 0x0c && - interop_match_addr(INTEROP_DISABLE_ROBUST_CACHING, &p_clcb->bda)) { + if (lmp_version < 0x0c && interop_match_addr(INTEROP_DISABLE_ROBUST_CACHING, &p_clcb->bda)) { log::warn( - "Device LMP version 0x{:02x} <= Bluetooth 5.2 and MAC addr on interop " - "list, skipping robust caching", - lmp_version); + "Device LMP version 0x{:02x} <= Bluetooth 5.2 and MAC addr on interop " + "list, skipping robust caching", + lmp_version); return RobustCachingSupport::UNSUPPORTED; } @@ -206,10 +199,13 @@ RobustCachingSupport GetRobustCachingSupport(const tBTA_GATTC_CLCB* p_clcb, } /** Start primary service discovery */ -[[nodiscard]] tGATT_STATUS bta_gattc_discover_pri_service( - uint16_t conn_id, tBTA_GATTC_SERV* p_server_cb, tGATT_DISC_TYPE disc_type) { +[[nodiscard]] tGATT_STATUS bta_gattc_discover_pri_service(uint16_t conn_id, + tBTA_GATTC_SERV* p_server_cb, + tGATT_DISC_TYPE disc_type) { tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_clcb_by_conn_id(conn_id); - if (!p_clcb) return GATT_ERROR; + if (!p_clcb) { + return GATT_ERROR; + } if (p_clcb->transport == BT_TRANSPORT_LE) { return GATTC_Discover(conn_id, disc_type, 0x0001, 0xFFFF); @@ -221,8 +217,7 @@ RobustCachingSupport GetRobustCachingSupport(const tBTA_GATTC_CLCB* p_clcb, /** start exploring next service, or finish discovery if no more services left */ -static void bta_gattc_explore_next_service(uint16_t conn_id, - tBTA_GATTC_SERV* p_srvc_cb) { +static void bta_gattc_explore_next_service(uint16_t conn_id, tBTA_GATTC_SERV* p_srvc_cb) { tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_clcb_by_conn_id(conn_id); if (!p_clcb) { log::error("unknown conn_id=0x{:x}", conn_id); @@ -230,13 +225,12 @@ static void bta_gattc_explore_next_service(uint16_t conn_id, } if (p_srvc_cb->pending_discovery.StartNextServiceExploration()) { - const auto& service = - p_srvc_cb->pending_discovery.CurrentlyExploredService(); + const auto& service = p_srvc_cb->pending_discovery.CurrentlyExploredService(); log::verbose("Start service discovery"); /* start discovering included services */ - if (GATTC_Discover(conn_id, GATT_DISC_INC_SRVC, service.first, - service.second) != GATT_SUCCESS) { + if (GATTC_Discover(conn_id, GATT_DISC_INC_SRVC, service.first, service.second) != + GATT_SUCCESS) { log::warn("Unable to discover GATT client conn_id:{}", conn_id); } return; @@ -245,18 +239,15 @@ static void bta_gattc_explore_next_service(uint16_t conn_id, // As part of service discovery, read the values of "Characteristic Extended // Properties" descriptor - const auto& descriptors = - p_srvc_cb->pending_discovery.DescriptorHandlesToRead(); + const auto& descriptors = p_srvc_cb->pending_discovery.DescriptorHandlesToRead(); if (!descriptors.empty()) { // set request field to READ_EXT_PROP_DESC - p_clcb->request_during_discovery = - BTA_GATTC_DISCOVER_REQ_READ_EXT_PROP_DESC; + p_clcb->request_during_discovery = BTA_GATTC_DISCOVER_REQ_READ_EXT_PROP_DESC; if (p_srvc_cb->read_multiple_not_supported || descriptors.size() == 1) { - tGATT_READ_PARAM read_param{.by_handle = {.auth_req = GATT_AUTH_REQ_NONE, - .handle = descriptors.front()}}; - if (GATTC_Read(conn_id, GATT_READ_BY_HANDLE, &read_param) != - GATT_SUCCESS) { + tGATT_READ_PARAM read_param{ + .by_handle = {.auth_req = GATT_AUTH_REQ_NONE, .handle = descriptors.front()}}; + if (GATTC_Read(conn_id, GATT_READ_BY_HANDLE, &read_param) != GATT_SUCCESS) { log::warn("Unable to read GATT client conn_id:{}", conn_id); } // asynchronous continuation in bta_gattc_op_cmpl_during_discovery @@ -267,16 +258,14 @@ static void bta_gattc_explore_next_service(uint16_t conn_id, // GATT_MAX_READ_MULTI_HANDLES /* each descriptor contains just 2 bytes, so response size is same as * request size */ - size_t num_handles = - std::min(descriptors.size(), (size_t)GATT_MAX_READ_MULTI_HANDLES); + size_t num_handles = std::min(descriptors.size(), (size_t)GATT_MAX_READ_MULTI_HANDLES); tGATT_READ_PARAM read_param; memset(&read_param, 0, sizeof(tGATT_READ_PARAM)); read_param.read_multiple.num_handles = num_handles; read_param.read_multiple.auth_req = GATT_AUTH_REQ_NONE; - memcpy(&read_param.read_multiple.handles, descriptors.data(), - sizeof(uint16_t) * num_handles); + memcpy(&read_param.read_multiple.handles, descriptors.data(), sizeof(uint16_t) * num_handles); if (GATTC_Read(conn_id, GATT_READ_MULTIPLE, &read_param) != GATT_SUCCESS) { log::warn("Unable to read GATT client conn_id:{}", conn_id); } @@ -288,8 +277,7 @@ static void bta_gattc_explore_next_service(uint16_t conn_id, bta_gattc_explore_srvc_finished(conn_id, p_srvc_cb); } -static void bta_gattc_explore_srvc_finished(uint16_t conn_id, - tBTA_GATTC_SERV* p_srvc_cb) { +static void bta_gattc_explore_srvc_finished(uint16_t conn_id, tBTA_GATTC_SERV* p_srvc_cb) { tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_clcb_by_conn_id(conn_id); if (!p_clcb) { log::error("unknown conn_id=0x{:x}", conn_id); @@ -319,26 +307,22 @@ static void bta_gattc_explore_srvc_finished(uint16_t conn_id, } // After success, reset the count. - log::debug("service discovery succeed, reset count to zero, conn_id=0x{:04x}", - conn_id); + log::debug("service discovery succeed, reset count to zero, conn_id=0x{:04x}", conn_id); p_srvc_cb->srvc_disc_count = 0; bta_gattc_reset_discover_st(p_clcb->p_srcb, GATT_SUCCESS); } /** Start discovery for characteristic descriptor */ -void bta_gattc_start_disc_char_dscp(uint16_t conn_id, - tBTA_GATTC_SERV* p_srvc_cb) { +void bta_gattc_start_disc_char_dscp(uint16_t conn_id, tBTA_GATTC_SERV* p_srvc_cb) { log::verbose("starting discover characteristics descriptor"); - std::pair range = - p_srvc_cb->pending_discovery.NextDescriptorRangeToExplore(); + std::pair range = p_srvc_cb->pending_discovery.NextDescriptorRangeToExplore(); if (range == DatabaseBuilder::EXPLORE_END) { goto descriptor_discovery_done; } - if (GATTC_Discover(conn_id, GATT_DISC_CHAR_DSCPT, range.first, - range.second) != GATT_SUCCESS) { + if (GATTC_Discover(conn_id, GATT_DISC_CHAR_DSCPT, range.first, range.second) != GATT_SUCCESS) { goto descriptor_discovery_done; } return; @@ -350,8 +334,7 @@ descriptor_discovery_done: } /* Process the discovery result from sdp */ -void bta_gattc_sdp_callback(tBTA_GATTC_CB_DATA* cb_data, - const RawAddress& /* bd_addr */, +void bta_gattc_sdp_callback(tBTA_GATTC_CB_DATA* cb_data, const RawAddress& /* bd_addr */, tSDP_STATUS sdp_status) { tBTA_GATTC_SERV* p_srvc_cb = bta_gattc_find_scb_by_cid(cb_data->sdp_conn_id); @@ -372,43 +355,40 @@ void bta_gattc_sdp_callback(tBTA_GATTC_CB_DATA* cb_data, bool no_pending_disc = !p_srvc_cb->pending_discovery.InProgress(); - tSDP_DISC_REC* p_sdp_rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb( - cb_data->p_sdp_db, 0, nullptr); + tSDP_DISC_REC* p_sdp_rec = + get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb(cb_data->p_sdp_db, 0, nullptr); while (p_sdp_rec != nullptr) { /* find a service record, report it */ Uuid service_uuid; - if (!get_legacy_stack_sdp_api()->record.SDP_FindServiceUUIDInRec( - p_sdp_rec, &service_uuid)) + if (!get_legacy_stack_sdp_api()->record.SDP_FindServiceUUIDInRec(p_sdp_rec, &service_uuid)) { continue; + } tSDP_PROTOCOL_ELEM pe; - if (!get_legacy_stack_sdp_api()->record.SDP_FindProtocolListElemInRec( - p_sdp_rec, UUID_PROTOCOL_ATT, &pe)) + if (!get_legacy_stack_sdp_api()->record.SDP_FindProtocolListElemInRec(p_sdp_rec, + UUID_PROTOCOL_ATT, &pe)) { continue; + } uint16_t start_handle = (uint16_t)pe.params[0]; uint16_t end_handle = (uint16_t)pe.params[1]; #if (BTA_GATT_DEBUG == TRUE) - log::verbose("Found ATT service uuid={}, s_handle=0x{:x}, e_handle=0x{:x}", - service_uuid, start_handle, end_handle); + log::verbose("Found ATT service uuid={}, s_handle=0x{:x}, e_handle=0x{:x}", service_uuid, + start_handle, end_handle); #endif - if (!GATT_HANDLE_IS_VALID(start_handle) || - !GATT_HANDLE_IS_VALID(end_handle)) { - log::error("invalid start_handle=0x{:x}, end_handle=0x{:x}", start_handle, - end_handle); - p_sdp_rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb( - cb_data->p_sdp_db, 0, p_sdp_rec); + if (!GATT_HANDLE_IS_VALID(start_handle) || !GATT_HANDLE_IS_VALID(end_handle)) { + log::error("invalid start_handle=0x{:x}, end_handle=0x{:x}", start_handle, end_handle); + p_sdp_rec = + get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb(cb_data->p_sdp_db, 0, p_sdp_rec); continue; } /* discover services result, add services into a service list */ - p_srvc_cb->pending_discovery.AddService(start_handle, end_handle, - service_uuid, true); + p_srvc_cb->pending_discovery.AddService(start_handle, end_handle, service_uuid, true); - p_sdp_rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb( - cb_data->p_sdp_db, 0, p_sdp_rec); + p_sdp_rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb(cb_data->p_sdp_db, 0, p_sdp_rec); } // If discovery is already pending, no need to call @@ -423,8 +403,7 @@ void bta_gattc_sdp_callback(tBTA_GATTC_CB_DATA* cb_data, } /* Start DSP Service Discovery */ -static tGATT_STATUS bta_gattc_sdp_service_disc(uint16_t conn_id, - tBTA_GATTC_SERV* p_server_cb) { +static tGATT_STATUS bta_gattc_sdp_service_disc(uint16_t conn_id, tBTA_GATTC_SERV* p_server_cb) { uint16_t num_attrs = 2; uint16_t attr_list[2]; @@ -432,8 +411,8 @@ static tGATT_STATUS bta_gattc_sdp_service_disc(uint16_t conn_id, * On success, cb_data will be freed inside bta_gattc_sdp_callback, * otherwise it will be freed within this function. */ - tBTA_GATTC_CB_DATA* cb_data = (tBTA_GATTC_CB_DATA*)osi_malloc( - sizeof(tBTA_GATTC_CB_DATA) + BTA_GATT_SDP_DB_SIZE); + tBTA_GATTC_CB_DATA* cb_data = + (tBTA_GATTC_CB_DATA*)osi_malloc(sizeof(tBTA_GATTC_CB_DATA) + BTA_GATT_SDP_DB_SIZE); cb_data->p_sdp_db = (tSDP_DISCOVERY_DB*)(cb_data + 1); attr_list[0] = ATTR_ID_SERVICE_CLASS_ID_LIST; @@ -441,15 +420,13 @@ static tGATT_STATUS bta_gattc_sdp_service_disc(uint16_t conn_id, Uuid uuid = Uuid::From16Bit(UUID_PROTOCOL_ATT); if (!get_legacy_stack_sdp_api()->service.SDP_InitDiscoveryDb( - cb_data->p_sdp_db, BTA_GATT_SDP_DB_SIZE, 1, &uuid, num_attrs, - attr_list)) { - log::warn("Unable to initialize SDP service discovery db peer:{}", - p_server_cb->server_bda); + cb_data->p_sdp_db, BTA_GATT_SDP_DB_SIZE, 1, &uuid, num_attrs, attr_list)) { + log::warn("Unable to initialize SDP service discovery db peer:{}", p_server_cb->server_bda); }; if (!get_legacy_stack_sdp_api()->service.SDP_ServiceSearchAttributeRequest2( - p_server_cb->server_bda, cb_data->p_sdp_db, - base::BindRepeating(bta_gattc_sdp_callback, cb_data))) { + p_server_cb->server_bda, cb_data->p_sdp_db, + base::BindRepeating(bta_gattc_sdp_callback, cb_data))) { log::warn("Unable to start SDP service search attribute request peer:{}", p_server_cb->server_bda); osi_free(cb_data); @@ -461,8 +438,7 @@ static tGATT_STATUS bta_gattc_sdp_service_disc(uint16_t conn_id, } /** operation completed */ -void bta_gattc_op_cmpl_during_discovery(tBTA_GATTC_CLCB* p_clcb, - const tBTA_GATTC_DATA* p_data) { +void bta_gattc_op_cmpl_during_discovery(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data) { // Currently, there are two cases needed to be handled. // 1. Read ext prop descriptor value after service discovery // 2. Read db hash before starting service discovery @@ -472,8 +448,8 @@ void bta_gattc_op_cmpl_during_discovery(tBTA_GATTC_CLCB* p_clcb, break; case BTA_GATTC_DISCOVER_REQ_READ_DB_HASH: case BTA_GATTC_DISCOVER_REQ_READ_DB_HASH_FOR_SVC_CHG: { - bool is_svc_chg = (p_clcb->request_during_discovery == - BTA_GATTC_DISCOVER_REQ_READ_DB_HASH_FOR_SVC_CHG); + bool is_svc_chg = + (p_clcb->request_during_discovery == BTA_GATTC_DISCOVER_REQ_READ_DB_HASH_FOR_SVC_CHG); bta_gattc_read_db_hash_cmpl(p_clcb, &p_data->op_cmpl, is_svc_chg); break; } @@ -484,33 +460,31 @@ void bta_gattc_op_cmpl_during_discovery(tBTA_GATTC_CLCB* p_clcb, } /** callback function to GATT client stack */ -void bta_gattc_disc_res_cback(uint16_t conn_id, tGATT_DISC_TYPE disc_type, - tGATT_DISC_RES* p_data) { +void bta_gattc_disc_res_cback(uint16_t conn_id, tGATT_DISC_TYPE disc_type, tGATT_DISC_RES* p_data) { tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_clcb_by_conn_id(conn_id); tBTA_GATTC_SERV* p_srvc_cb = bta_gattc_find_scb_by_cid(conn_id); - if (!p_srvc_cb || !p_clcb || p_clcb->state != BTA_GATTC_DISCOVER_ST) return; + if (!p_srvc_cb || !p_clcb || p_clcb->state != BTA_GATTC_DISCOVER_ST) { + return; + } switch (disc_type) { case GATT_DISC_SRVC_ALL: case GATT_DISC_SRVC_BY_UUID: - p_srvc_cb->pending_discovery.AddService( - p_data->handle, p_data->value.group_value.e_handle, - p_data->value.group_value.service_type, true); + p_srvc_cb->pending_discovery.AddService(p_data->handle, p_data->value.group_value.e_handle, + p_data->value.group_value.service_type, true); break; case GATT_DISC_INC_SRVC: p_srvc_cb->pending_discovery.AddIncludedService( - p_data->handle, p_data->value.incl_service.service_type, - p_data->value.incl_service.s_handle, - p_data->value.incl_service.e_handle); + p_data->handle, p_data->value.incl_service.service_type, + p_data->value.incl_service.s_handle, p_data->value.incl_service.e_handle); break; case GATT_DISC_CHAR: p_srvc_cb->pending_discovery.AddCharacteristic( - p_data->handle, p_data->value.dclr_value.val_handle, - p_data->value.dclr_value.char_uuid, - p_data->value.dclr_value.char_prop); + p_data->handle, p_data->value.dclr_value.val_handle, + p_data->value.dclr_value.char_uuid, p_data->value.dclr_value.char_prop); break; case GATT_DISC_CHAR_DSCPT: @@ -524,23 +498,22 @@ void bta_gattc_disc_res_cback(uint16_t conn_id, tGATT_DISC_TYPE disc_type, } } -void bta_gattc_disc_cmpl_cback(uint16_t conn_id, tGATT_DISC_TYPE disc_type, - tGATT_STATUS status) { +void bta_gattc_disc_cmpl_cback(uint16_t conn_id, tGATT_DISC_TYPE disc_type, tGATT_STATUS status) { tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_clcb_by_conn_id(conn_id); tBTA_GATTC_SERV* p_srvc_cb = bta_gattc_find_scb_by_cid(conn_id); if (p_clcb && (status != GATT_SUCCESS || p_clcb->status != GATT_SUCCESS)) { - if (status == GATT_SUCCESS) p_clcb->status = status; + if (status == GATT_SUCCESS) { + p_clcb->status = status; + } // if db out of sync is received, try to start service discovery if possible if (status == GATT_DATABASE_OUT_OF_SYNC) { - if (p_srvc_cb && - p_srvc_cb->srvc_disc_count < BTA_GATTC_DISCOVER_RETRY_COUNT) { + if (p_srvc_cb && p_srvc_cb->srvc_disc_count < BTA_GATTC_DISCOVER_RETRY_COUNT) { p_srvc_cb->srvc_disc_count++; p_clcb->auto_update = BTA_GATTC_DISC_WAITING; } else { - log::error("retry limit exceeds for db out of sync, conn_id={}", - conn_id); + log::error("retry limit exceeds for db out of sync, conn_id={}", conn_id); } } @@ -548,7 +521,9 @@ void bta_gattc_disc_cmpl_cback(uint16_t conn_id, tGATT_DISC_TYPE disc_type, return; } - if (!p_srvc_cb) return; + if (!p_srvc_cb) { + return; + } switch (disc_type) { case GATT_DISC_SRVC_ALL: @@ -564,8 +539,7 @@ void bta_gattc_disc_cmpl_cback(uint16_t conn_id, tGATT_DISC_TYPE disc_type, case GATT_DISC_INC_SRVC: { auto& service = p_srvc_cb->pending_discovery.CurrentlyExploredService(); /* start discovering characteristic */ - if (GATTC_Discover(conn_id, GATT_DISC_CHAR, service.first, - service.second) != GATT_SUCCESS) { + if (GATTC_Discover(conn_id, GATT_DISC_CHAR, service.first, service.second) != GATT_SUCCESS) { log::warn("Unable to discover GATT client conn_id:{}", conn_id); } break; @@ -594,12 +568,16 @@ void bta_gattc_disc_cmpl_cback(uint16_t conn_id, tGATT_DISC_TYPE disc_type, /** search local cache for matching service record */ void bta_gattc_search_service(tBTA_GATTC_CLCB* p_clcb, Uuid* p_uuid) { for (const Service& service : p_clcb->p_srcb->gatt_database.Services()) { - if (p_uuid && *p_uuid != service.uuid) continue; + if (p_uuid && *p_uuid != service.uuid) { + continue; + } #if (BTA_GATT_DEBUG == TRUE) log::verbose("found service {} handle:{}", service.uuid, service.handle); #endif - if (!p_clcb->p_rcb->p_cback) continue; + if (!p_clcb->p_rcb->p_cback) { + continue; + } tBTA_GATTC cb_data; memset(&cb_data, 0, sizeof(tBTA_GATTC)); @@ -612,7 +590,9 @@ void bta_gattc_search_service(tBTA_GATTC_CLCB* p_clcb, Uuid* p_uuid) { } const std::list* bta_gattc_get_services_srcb(tBTA_GATTC_SERV* p_srcb) { - if (!p_srcb || p_srcb->gatt_database.IsEmpty()) return NULL; + if (!p_srcb || p_srcb->gatt_database.IsEmpty()) { + return NULL; + } return &p_srcb->gatt_database.Services(); } @@ -620,56 +600,61 @@ const std::list* bta_gattc_get_services_srcb(tBTA_GATTC_SERV* p_srcb) { const std::list* bta_gattc_get_services(uint16_t conn_id) { tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_clcb_by_conn_id(conn_id); - if (p_clcb == NULL) return NULL; + if (p_clcb == NULL) { + return NULL; + } tBTA_GATTC_SERV* p_srcb = p_clcb->p_srcb; return bta_gattc_get_services_srcb(p_srcb); } -const Service* bta_gattc_get_service_for_handle_srcb(tBTA_GATTC_SERV* p_srcb, - uint16_t handle) { +const Service* bta_gattc_get_service_for_handle_srcb(tBTA_GATTC_SERV* p_srcb, uint16_t handle) { const std::list* services = bta_gattc_get_services_srcb(p_srcb); - if (services == NULL) return NULL; + if (services == NULL) { + return NULL; + } return bta_gattc_find_matching_service(*services, handle); } -const Service* bta_gattc_get_service_for_handle(uint16_t conn_id, - uint16_t handle) { +const Service* bta_gattc_get_service_for_handle(uint16_t conn_id, uint16_t handle) { const std::list* services = bta_gattc_get_services(conn_id); - if (services == NULL) return NULL; + if (services == NULL) { + return NULL; + } return bta_gattc_find_matching_service(*services, handle); } -const Characteristic* bta_gattc_get_characteristic_srcb(tBTA_GATTC_SERV* p_srcb, - uint16_t handle) { - const Service* service = - bta_gattc_get_service_for_handle_srcb(p_srcb, handle); +const Characteristic* bta_gattc_get_characteristic_srcb(tBTA_GATTC_SERV* p_srcb, uint16_t handle) { + const Service* service = bta_gattc_get_service_for_handle_srcb(p_srcb, handle); - if (!service) return NULL; + if (!service) { + return NULL; + } for (const Characteristic& charac : service->characteristics) { - if (handle == charac.value_handle) return &charac; + if (handle == charac.value_handle) { + return &charac; + } } return NULL; } -const Characteristic* bta_gattc_get_characteristic(uint16_t conn_id, - uint16_t handle) { +const Characteristic* bta_gattc_get_characteristic(uint16_t conn_id, uint16_t handle) { tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_clcb_by_conn_id(conn_id); - if (p_clcb == NULL) return NULL; + if (p_clcb == NULL) { + return NULL; + } tBTA_GATTC_SERV* p_srcb = p_clcb->p_srcb; return bta_gattc_get_characteristic_srcb(p_srcb, handle); } -const Descriptor* bta_gattc_get_descriptor_srcb(tBTA_GATTC_SERV* p_srcb, - uint16_t handle) { - const Service* service = - bta_gattc_get_service_for_handle_srcb(p_srcb, handle); +const Descriptor* bta_gattc_get_descriptor_srcb(tBTA_GATTC_SERV* p_srcb, uint16_t handle) { + const Service* service = bta_gattc_get_service_for_handle_srcb(p_srcb, handle); if (!service) { return NULL; @@ -677,7 +662,9 @@ const Descriptor* bta_gattc_get_descriptor_srcb(tBTA_GATTC_SERV* p_srcb, for (const Characteristic& charac : service->characteristics) { for (const Descriptor& desc : charac.descriptors) { - if (handle == desc.handle) return &desc; + if (handle == desc.handle) { + return &desc; + } } } @@ -687,32 +674,38 @@ const Descriptor* bta_gattc_get_descriptor_srcb(tBTA_GATTC_SERV* p_srcb, const Descriptor* bta_gattc_get_descriptor(uint16_t conn_id, uint16_t handle) { tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_clcb_by_conn_id(conn_id); - if (p_clcb == NULL) return NULL; + if (p_clcb == NULL) { + return NULL; + } tBTA_GATTC_SERV* p_srcb = p_clcb->p_srcb; return bta_gattc_get_descriptor_srcb(p_srcb, handle); } -const Characteristic* bta_gattc_get_owning_characteristic_srcb( - tBTA_GATTC_SERV* p_srcb, uint16_t handle) { - const Service* service = - bta_gattc_get_service_for_handle_srcb(p_srcb, handle); +const Characteristic* bta_gattc_get_owning_characteristic_srcb(tBTA_GATTC_SERV* p_srcb, + uint16_t handle) { + const Service* service = bta_gattc_get_service_for_handle_srcb(p_srcb, handle); - if (!service) return NULL; + if (!service) { + return NULL; + } for (const Characteristic& charac : service->characteristics) { for (const Descriptor& desc : charac.descriptors) { - if (handle == desc.handle) return &charac; + if (handle == desc.handle) { + return &charac; + } } } return NULL; } -const Characteristic* bta_gattc_get_owning_characteristic(uint16_t conn_id, - uint16_t handle) { +const Characteristic* bta_gattc_get_owning_characteristic(uint16_t conn_id, uint16_t handle) { tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_clcb_by_conn_id(conn_id); - if (!p_clcb) return NULL; + if (!p_clcb) { + return NULL; + } return bta_gattc_get_owning_characteristic_srcb(p_clcb->p_srcb, handle); } @@ -726,14 +719,14 @@ bool bta_gattc_read_db_hash(tBTA_GATTC_CLCB* p_clcb, bool is_svc_chg) { read_param.char_type.e_handle = 0xFFFF; read_param.char_type.uuid = Uuid::From16Bit(GATT_UUID_DATABASE_HASH); read_param.char_type.auth_req = GATT_AUTH_REQ_NONE; - tGATT_STATUS status = - GATTC_Read(p_clcb->bta_conn_id, GATT_READ_BY_TYPE, &read_param); + tGATT_STATUS status = GATTC_Read(p_clcb->bta_conn_id, GATT_READ_BY_TYPE, &read_param); - if (status != GATT_SUCCESS) return false; + if (status != GATT_SUCCESS) { + return false; + } if (is_svc_chg) { - p_clcb->request_during_discovery = - BTA_GATTC_DISCOVER_REQ_READ_DB_HASH_FOR_SVC_CHG; + p_clcb->request_during_discovery = BTA_GATTC_DISCOVER_REQ_READ_DB_HASH_FOR_SVC_CHG; } else { p_clcb->request_during_discovery = BTA_GATTC_DISCOVER_REQ_READ_DB_HASH; } @@ -742,8 +735,7 @@ bool bta_gattc_read_db_hash(tBTA_GATTC_CLCB* p_clcb, bool is_svc_chg) { } /* handle response of reading database hash */ -static void bta_gattc_read_db_hash_cmpl(tBTA_GATTC_CLCB* p_clcb, - const tBTA_GATTC_OP_CMPL* p_data, +static void bta_gattc_read_db_hash_cmpl(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_OP_CMPL* p_data, bool is_svc_chg) { uint8_t op = (uint8_t)p_data->op_code; if (op != GATTC_OPTYPE_READ) { @@ -767,10 +759,8 @@ static void bta_gattc_read_db_hash_cmpl(tBTA_GATTC_CLCB* p_clcb, Octet16 local_hash = p_clcb->p_srcb->gatt_database.Hash(); matched = (local_hash == remote_hash); - log::debug("lhash={}", - base::HexEncode(local_hash.data(), local_hash.size())); - log::debug("rhash={}", - base::HexEncode(remote_hash.data(), remote_hash.size())); + log::debug("lhash={}", base::HexEncode(local_hash.data(), local_hash.size())); + log::debug("rhash={}", base::HexEncode(remote_hash.data(), remote_hash.size())); if (!matched) { gatt::Database db = bta_gattc_hash_load(remote_hash); @@ -796,8 +786,7 @@ static void bta_gattc_read_db_hash_cmpl(tBTA_GATTC_CLCB* p_clcb, } log::debug("load cache directly, result={}", found); } else { - log::debug("skip read cache, is_svc_chg={}, is_a_bonded_dev={}", - is_svc_chg, is_a_bonded_dev); + log::debug("skip read cache, is_svc_chg={}, is_a_bonded_dev={}", is_svc_chg, is_a_bonded_dev); } } @@ -823,8 +812,8 @@ static void bta_gattc_read_db_hash_cmpl(tBTA_GATTC_CLCB* p_clcb, } /* handle response of reading extended properties descriptor */ -static void bta_gattc_read_ext_prop_desc_cmpl( - tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_OP_CMPL* p_data) { +static void bta_gattc_read_ext_prop_desc_cmpl(tBTA_GATTC_CLCB* p_clcb, + const tBTA_GATTC_OP_CMPL* p_data) { uint8_t op = (uint8_t)p_data->op_code; if (op != GATTC_OPTYPE_READ) { log::verbose("op = {}", p_data->hdr.layer_specific); @@ -840,8 +829,7 @@ static void bta_gattc_read_ext_prop_desc_cmpl( tBTA_GATTC_SERV* p_srvc_cb = p_clcb->p_srcb; const uint8_t status = p_data->status; - if (status == GATT_REQ_NOT_SUPPORTED && - !p_srvc_cb->read_multiple_not_supported) { + if (status == GATT_REQ_NOT_SUPPORTED && !p_srvc_cb->read_multiple_not_supported) { // can't do "read multiple request", fall back to "read request" p_srvc_cb->read_multiple_not_supported = true; bta_gattc_explore_next_service(p_clcb->bta_conn_id, p_srvc_cb); @@ -872,8 +860,7 @@ static void bta_gattc_read_ext_prop_desc_cmpl( value_of_descriptors.push_back(extended_properties); } - bool ret = - p_srvc_cb->pending_discovery.SetValueOfDescriptors(value_of_descriptors); + bool ret = p_srvc_cb->pending_discovery.SetValueOfDescriptors(value_of_descriptors); if (!ret) { log::warn("Problem setting Extended Properties descriptors values"); bta_gattc_reset_discover_st(p_clcb->p_srcb, GATT_ERROR); @@ -893,11 +880,9 @@ static void bta_gattc_read_ext_prop_desc_cmpl( * Returns None. * ******************************************************************************/ -void bta_gattc_fill_gatt_db_el(btgatt_db_element_t* p_attr, - bt_gatt_db_attribute_type_t type, - uint16_t att_handle, uint16_t s_handle, - uint16_t e_handle, uint16_t id, const Uuid& uuid, - uint8_t prop) { +void bta_gattc_fill_gatt_db_el(btgatt_db_element_t* p_attr, bt_gatt_db_attribute_type_t type, + uint16_t att_handle, uint16_t s_handle, uint16_t e_handle, + uint16_t id, const Uuid& uuid, uint8_t prop) { p_attr->type = type; p_attr->attribute_handle = att_handle; p_attr->start_handle = s_handle; @@ -914,17 +899,22 @@ void bta_gattc_fill_gatt_db_el(btgatt_db_element_t* p_attr, /******************************************************************************* * Returns number of elements inside db from start_handle to end_handle ******************************************************************************/ -static size_t bta_gattc_get_db_size(const std::list& services, - uint16_t start_handle, +static size_t bta_gattc_get_db_size(const std::list& services, uint16_t start_handle, uint16_t end_handle) { - if (services.empty()) return 0; + if (services.empty()) { + return 0; + } size_t db_size = 0; for (const Service& service : services) { - if (service.handle < start_handle) continue; + if (service.handle < start_handle) { + continue; + } - if (service.end_handle > end_handle) break; + if (service.end_handle > end_handle) { + break; + } db_size++; @@ -955,12 +945,9 @@ static size_t bta_gattc_get_db_size(const std::list& services, * Returns None. * ******************************************************************************/ -static void bta_gattc_get_gatt_db_impl(tBTA_GATTC_SERV* p_srvc_cb, - uint16_t start_handle, - uint16_t end_handle, - btgatt_db_element_t** db, int* count) { - log::verbose("start_handle 0x{:04x}, end_handle 0x{:04x}", start_handle, - end_handle); +static void bta_gattc_get_gatt_db_impl(tBTA_GATTC_SERV* p_srvc_cb, uint16_t start_handle, + uint16_t end_handle, btgatt_db_element_t** db, int* count) { + log::verbose("start_handle 0x{:04x}, end_handle 0x{:04x}", start_handle, end_handle); if (p_srvc_cb->gatt_database.IsEmpty()) { *count = 0; @@ -968,50 +955,49 @@ static void bta_gattc_get_gatt_db_impl(tBTA_GATTC_SERV* p_srvc_cb, return; } - size_t db_size = bta_gattc_get_db_size(p_srvc_cb->gatt_database.Services(), - start_handle, end_handle); + size_t db_size = + bta_gattc_get_db_size(p_srvc_cb->gatt_database.Services(), start_handle, end_handle); void* buffer = osi_malloc(db_size * sizeof(btgatt_db_element_t)); btgatt_db_element_t* curr_db_attr = (btgatt_db_element_t*)buffer; for (const Service& service : p_srvc_cb->gatt_database.Services()) { - if (service.handle < start_handle) continue; + if (service.handle < start_handle) { + continue; + } - if (service.end_handle > end_handle) break; + if (service.end_handle > end_handle) { + break; + } - bta_gattc_fill_gatt_db_el(curr_db_attr, - service.is_primary ? BTGATT_DB_PRIMARY_SERVICE - : BTGATT_DB_SECONDARY_SERVICE, - 0 /* att_handle */, service.handle, - service.end_handle, service.handle, service.uuid, - 0 /* prop */); + bta_gattc_fill_gatt_db_el( + curr_db_attr, + service.is_primary ? BTGATT_DB_PRIMARY_SERVICE : BTGATT_DB_SECONDARY_SERVICE, + 0 /* att_handle */, service.handle, service.end_handle, service.handle, service.uuid, + 0 /* prop */); curr_db_attr++; for (const Characteristic& charac : service.characteristics) { - bta_gattc_fill_gatt_db_el(curr_db_attr, BTGATT_DB_CHARACTERISTIC, - charac.value_handle, 0 /* s_handle */, - 0 /* e_handle */, charac.value_handle, + bta_gattc_fill_gatt_db_el(curr_db_attr, BTGATT_DB_CHARACTERISTIC, charac.value_handle, + 0 /* s_handle */, 0 /* e_handle */, charac.value_handle, charac.uuid, charac.properties); btgatt_db_element_t* characteristic = curr_db_attr; curr_db_attr++; for (const Descriptor& desc : charac.descriptors) { - bta_gattc_fill_gatt_db_el( - curr_db_attr, BTGATT_DB_DESCRIPTOR, desc.handle, 0 /* s_handle */, - 0 /* e_handle */, desc.handle, desc.uuid, 0 /* property */); + bta_gattc_fill_gatt_db_el(curr_db_attr, BTGATT_DB_DESCRIPTOR, desc.handle, 0 /* s_handle */, + 0 /* e_handle */, desc.handle, desc.uuid, 0 /* property */); if (desc.uuid == Uuid::From16Bit(GATT_UUID_CHAR_EXT_PROP)) { - characteristic->extended_properties = - desc.characteristic_extended_properties; + characteristic->extended_properties = desc.characteristic_extended_properties; } curr_db_attr++; } } for (const IncludedService& p_isvc : service.included_services) { - bta_gattc_fill_gatt_db_el(curr_db_attr, BTGATT_DB_INCLUDED_SERVICE, - p_isvc.handle, p_isvc.start_handle, - 0 /* e_handle */, p_isvc.handle, p_isvc.uuid, + bta_gattc_fill_gatt_db_el(curr_db_attr, BTGATT_DB_INCLUDED_SERVICE, p_isvc.handle, + p_isvc.start_handle, 0 /* e_handle */, p_isvc.handle, p_isvc.uuid, 0 /* property */); curr_db_attr++; } @@ -1035,9 +1021,8 @@ static void bta_gattc_get_gatt_db_impl(tBTA_GATTC_SERV* p_srvc_cb, * Returns None. * ******************************************************************************/ -void bta_gattc_get_gatt_db(uint16_t conn_id, uint16_t start_handle, - uint16_t end_handle, btgatt_db_element_t** db, - int* count) { +void bta_gattc_get_gatt_db(uint16_t conn_id, uint16_t start_handle, uint16_t end_handle, + btgatt_db_element_t** db, int* count) { tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_clcb_by_conn_id(conn_id); log::info(""); @@ -1057,6 +1042,5 @@ void bta_gattc_get_gatt_db(uint16_t conn_id, uint16_t start_handle, return; } - bta_gattc_get_gatt_db_impl(p_clcb->p_srcb, start_handle, end_handle, db, - count); + bta_gattc_get_gatt_db_impl(p_clcb->p_srcb, start_handle, end_handle, db, count); } diff --git a/system/bta/gatt/bta_gattc_db_storage.cc b/system/bta/gatt/bta_gattc_db_storage.cc index f074dbd507d..6a741e85442 100644 --- a/system/bta/gatt/bta_gattc_db_storage.cc +++ b/system/bta/gatt/bta_gattc_db_storage.cc @@ -63,9 +63,8 @@ static void bta_gattc_hash_remove_least_recently_used_if_possible(); static void bta_gattc_generate_cache_file_name(char* buffer, size_t buffer_len, const RawAddress& bda) { - snprintf(buffer, buffer_len, "%s%02x%02x%02x%02x%02x%02x", GATT_CACHE_PREFIX, - bda.address[0], bda.address[1], bda.address[2], bda.address[3], - bda.address[4], bda.address[5]); + snprintf(buffer, buffer_len, "%s%02x%02x%02x%02x%02x%02x", GATT_CACHE_PREFIX, bda.address[0], + bda.address[1], bda.address[2], bda.address[3], bda.address[4], bda.address[5]); } static void bta_gattc_generate_hash_file_name(char* buffer, size_t buffer_len, @@ -91,8 +90,7 @@ static gatt::Database EMPTY_DB; static gatt::Database bta_gattc_load_db(const char* fname) { FILE* fd = fopen(fname, "rb"); if (!fd) { - log::error("can't open GATT cache file {} for reading, error: {}", fname, - strerror(errno)); + log::error("can't open GATT cache file {} for reading, error: {}", fname, strerror(errno)); return EMPTY_DB; } @@ -218,8 +216,7 @@ void StoredAttribute::SerializeStoredAttribute(const StoredAttribute& attr, } } // padding - for (size_t i = bytes.size() - original_size; - i < StoredAttribute::kSizeOnDisk; i++) { + for (size_t i = bytes.size() - original_size; i < StoredAttribute::kSizeOnDisk; i++) { bytes.push_back(0); } } @@ -236,8 +233,7 @@ void StoredAttribute::SerializeStoredAttribute(const StoredAttribute& attr, * Returns true on success, false otherwise * ******************************************************************************/ -static bool bta_gattc_store_db(const char* fname, - const std::vector& attr) { +static bool bta_gattc_store_db(const char* fname, const std::vector& attr) { FILE* fd = fopen(fname, "wb"); if (!fd) { log::error("can't open GATT cache file for writing: {}", fname); @@ -264,8 +260,7 @@ static bool bta_gattc_store_db(const char* fname, StoredAttribute::SerializeStoredAttribute(attribute, db_bytes); } - if (fwrite(db_bytes.data(), sizeof(uint8_t), db_bytes.size(), fd) != - db_bytes.size()) { + if (fwrite(db_bytes.data(), sizeof(uint8_t), db_bytes.size(), fd) != db_bytes.size()) { log::error("can't write GATT cache attributes: {}", fname); fclose(fd); return false; @@ -289,8 +284,7 @@ static bool bta_gattc_store_db(const char* fname, * Returns * ******************************************************************************/ -void bta_gattc_cache_write(const RawAddress& server_bda, - const gatt::Database& database) { +void bta_gattc_cache_write(const RawAddress& server_bda, const gatt::Database& database) { char addr_file[255] = {0}; char hash_file[255] = {0}; Octet16 hash = database.Hash(); @@ -380,8 +374,7 @@ void bta_gattc_cache_reset(const RawAddress& server_bda) { * ******************************************************************************/ static void bta_gattc_hash_remove_least_recently_used_if_possible() { - std::unique_ptr dirp(opendir(GATT_HASH_PATH), - &closedir); + std::unique_ptr dirp(opendir(GATT_HASH_PATH), &closedir); if (dirp == nullptr) { log::error("open dir error, dir={}", GATT_HASH_PATH); return; diff --git a/system/bta/gatt/bta_gattc_int.h b/system/bta/gatt/bta_gattc_int.h index 214852e6f46..bf5e4cb56d1 100644 --- a/system/bta/gatt/bta_gattc_int.h +++ b/system/bta/gatt/bta_gattc_int.h @@ -247,10 +247,10 @@ typedef struct { * Properties */ bool read_multiple_not_supported; - uint8_t srvc_hdl_chg; /* service handle change indication pending */ + uint8_t srvc_hdl_chg; /* service handle change indication pending */ bool srvc_hdl_db_hash; /* read db hash pending */ uint8_t srvc_disc_count; /* current discovery retry count */ - uint16_t attr_index; /* cahce NV saving/loading attribute index */ + uint16_t attr_index; /* cache NV saving/loading attribute index */ uint16_t mtu; @@ -273,7 +273,7 @@ typedef struct { tBTA_GATTC_CBACK* p_cback; bool in_use; tGATT_IF client_if; /* client interface with BTE stack for this application */ - uint8_t num_clcb; /* number of associated CLCB */ + uint8_t num_clcb; /* number of associated CLCB */ bool dereg_pending; bluetooth::Uuid app_uuid; tBTA_GATTC_NOTIF_REG notif_reg[BTA_GATTC_NOTIF_REG_MAX]; @@ -284,9 +284,9 @@ typedef struct { typedef struct { uint16_t bta_conn_id; /* client channel ID, unique for clcb */ RawAddress bda; - tBT_TRANSPORT transport; /* channel transport */ - tBTA_GATTC_RCB* p_rcb; /* pointer to the registration CB */ - tBTA_GATTC_SERV* p_srcb; /* server cache CB */ + tBT_TRANSPORT transport; /* channel transport */ + tBTA_GATTC_RCB* p_rcb; /* pointer to the registration CB */ + tBTA_GATTC_SERV* p_srcb; /* server cache CB */ const tBTA_GATTC_DATA* p_q_cmd; /* command in queue waiting for execution */ std::deque p_q_cmd_queue; @@ -359,45 +359,34 @@ extern tBTA_GATTC_CB bta_gattc_cb; * Function prototypes ****************************************************************************/ bool bta_gattc_hdl_event(const BT_HDR_RIGID* p_msg); -bool bta_gattc_sm_execute(tBTA_GATTC_CLCB* p_clcb, uint16_t event, - const tBTA_GATTC_DATA* p_data); +bool bta_gattc_sm_execute(tBTA_GATTC_CLCB* p_clcb, uint16_t event, const tBTA_GATTC_DATA* p_data); /* function processed outside SM */ void bta_gattc_disable(); -void bta_gattc_register(const bluetooth::Uuid& app_uuid, - tBTA_GATTC_CBACK* p_data, BtaAppRegisterCallback cb, - bool eatt_support); +void bta_gattc_register(const bluetooth::Uuid& app_uuid, tBTA_GATTC_CBACK* p_data, + BtaAppRegisterCallback cb, bool eatt_support); void bta_gattc_process_api_open(const tBTA_GATTC_DATA* p_msg); void bta_gattc_process_api_open_cancel(const tBTA_GATTC_DATA* p_msg); void bta_gattc_deregister(tBTA_GATTC_RCB* p_clreg); /* function within state machine */ void bta_gattc_open(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data); -void bta_gattc_open_fail(tBTA_GATTC_CLCB* p_clcb, - const tBTA_GATTC_DATA* p_data); -void bta_gattc_open_error(tBTA_GATTC_CLCB* p_clcb, - const tBTA_GATTC_DATA* p_data); - -void bta_gattc_cancel_open(tBTA_GATTC_CLCB* p_clcb, - const tBTA_GATTC_DATA* p_data); -void bta_gattc_cancel_open_ok(tBTA_GATTC_CLCB* p_clcb, - const tBTA_GATTC_DATA* p_data); -void bta_gattc_cancel_open_error(tBTA_GATTC_CLCB* p_clcb, - const tBTA_GATTC_DATA* p_data); +void bta_gattc_open_fail(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data); +void bta_gattc_open_error(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data); + +void bta_gattc_cancel_open(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data); +void bta_gattc_cancel_open_ok(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data); +void bta_gattc_cancel_open_error(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data); void bta_gattc_conn(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data); void bta_gattc_close(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data); -void bta_gattc_close_fail(tBTA_GATTC_CLCB* p_clcb, - const tBTA_GATTC_DATA* p_data); -void bta_gattc_disc_close(tBTA_GATTC_CLCB* p_clcb, - const tBTA_GATTC_DATA* p_data); +void bta_gattc_close_fail(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data); +void bta_gattc_disc_close(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data); -void bta_gattc_start_discover(tBTA_GATTC_CLCB* p_clcb, - const tBTA_GATTC_DATA* p_data); +void bta_gattc_start_discover(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data); void bta_gattc_start_discover_internal(tBTA_GATTC_CLCB* p_clcb); -void bta_gattc_disc_cmpl(tBTA_GATTC_CLCB* p_clcb, - const tBTA_GATTC_DATA* p_data); +void bta_gattc_disc_cmpl(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data); void bta_gattc_read(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data); void bta_gattc_write(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data); void bta_gattc_op_cmpl(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data); @@ -406,14 +395,11 @@ void bta_gattc_search(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data); void bta_gattc_fail(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data); void bta_gattc_confirm(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data); void bta_gattc_execute(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data); -void bta_gattc_read_multi(tBTA_GATTC_CLCB* p_clcb, - const tBTA_GATTC_DATA* p_data); +void bta_gattc_read_multi(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data); void bta_gattc_ci_open(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data); void bta_gattc_ci_close(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data); -void bta_gattc_op_cmpl_during_discovery(tBTA_GATTC_CLCB* p_clcb, - const tBTA_GATTC_DATA* p_data); -void bta_gattc_restart_discover(tBTA_GATTC_CLCB* p_clcb, - const tBTA_GATTC_DATA* p_msg); +void bta_gattc_op_cmpl_during_discovery(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data); +void bta_gattc_restart_discover(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_msg); void bta_gattc_cancel_bk_conn(const tBTA_GATTC_API_CANCEL_OPEN* p_data); void bta_gattc_send_open_cback(tBTA_GATTC_RCB* p_clreg, tGATT_STATUS status, const RawAddress& remote_bda, uint16_t conn_id, @@ -424,17 +410,14 @@ void bta_gattc_listen(tBTA_GATTC_DATA* p_msg); void bta_gattc_broadcast(tBTA_GATTC_DATA* p_msg); /* utility functions */ -tBTA_GATTC_CLCB* bta_gattc_find_clcb_by_cif(uint8_t client_if, - const RawAddress& remote_bda, +tBTA_GATTC_CLCB* bta_gattc_find_clcb_by_cif(uint8_t client_if, const RawAddress& remote_bda, tBT_TRANSPORT transport); tBTA_GATTC_CLCB* bta_gattc_find_clcb_by_conn_id(uint16_t conn_id); -tBTA_GATTC_CLCB* bta_gattc_clcb_alloc(tGATT_IF client_if, - const RawAddress& remote_bda, +tBTA_GATTC_CLCB* bta_gattc_clcb_alloc(tGATT_IF client_if, const RawAddress& remote_bda, tBT_TRANSPORT transport); void bta_gattc_clcb_dealloc(tBTA_GATTC_CLCB* p_clcb); void bta_gattc_server_disconnected(tBTA_GATTC_SERV* p_srcb); -tBTA_GATTC_CLCB* bta_gattc_find_alloc_clcb(tGATT_IF client_if, - const RawAddress& remote_bda, +tBTA_GATTC_CLCB* bta_gattc_find_alloc_clcb(tGATT_IF client_if, const RawAddress& remote_bda, tBT_TRANSPORT transport); tBTA_GATTC_RCB* bta_gattc_cl_get_regcb(uint8_t client_if); tBTA_GATTC_SERV* bta_gattc_find_srcb(const RawAddress& bda); @@ -448,63 +431,43 @@ enum BtaEnqueuedResult_t { ENQUEUED_FOR_LATER, }; -BtaEnqueuedResult_t bta_gattc_enqueue(tBTA_GATTC_CLCB* p_clcb, - const tBTA_GATTC_DATA* p_data); -bool bta_gattc_is_data_queued(tBTA_GATTC_CLCB* p_clcb, - const tBTA_GATTC_DATA* p_data); +BtaEnqueuedResult_t bta_gattc_enqueue(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data); +bool bta_gattc_is_data_queued(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data); void bta_gattc_continue(tBTA_GATTC_CLCB* p_clcb); -void bta_gattc_send_mtu_response(tBTA_GATTC_CLCB* p_clcb, - const tBTA_GATTC_DATA* p_data, +void bta_gattc_send_mtu_response(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data, uint16_t current_mtu); -void bta_gattc_cmpl_sendmsg(uint16_t conn_id, tGATTC_OPTYPE op, - tGATT_STATUS status, tGATT_CL_COMPLETE* p_data); +void bta_gattc_cmpl_sendmsg(uint16_t conn_id, tGATTC_OPTYPE op, tGATT_STATUS status, + tGATT_CL_COMPLETE* p_data); -bool bta_gattc_check_notif_registry(tBTA_GATTC_RCB* p_clreg, - tBTA_GATTC_SERV* p_srcb, +bool bta_gattc_check_notif_registry(tBTA_GATTC_RCB* p_clreg, tBTA_GATTC_SERV* p_srcb, tBTA_GATTC_NOTIFY* p_notify); -bool bta_gattc_mark_bg_conn(tGATT_IF client_if, const RawAddress& remote_bda, - bool add); -bool bta_gattc_check_bg_conn(tGATT_IF client_if, const RawAddress& remote_bda, - uint8_t role); +bool bta_gattc_mark_bg_conn(tGATT_IF client_if, const RawAddress& remote_bda, bool add); +bool bta_gattc_check_bg_conn(tGATT_IF client_if, const RawAddress& remote_bda, uint8_t role); uint8_t bta_gattc_num_reg_app(void); -void bta_gattc_clear_notif_registration(tBTA_GATTC_SERV* p_srcb, - uint16_t conn_id, uint16_t start_handle, - uint16_t end_handle); +void bta_gattc_clear_notif_registration(tBTA_GATTC_SERV* p_srcb, uint16_t conn_id, + uint16_t start_handle, uint16_t end_handle); tBTA_GATTC_SERV* bta_gattc_find_srvr_cache(const RawAddress& bda); /* discovery functions */ -void bta_gattc_disc_res_cback(uint16_t conn_id, tGATT_DISC_TYPE disc_type, - tGATT_DISC_RES* p_data); -void bta_gattc_disc_cmpl_cback(uint16_t conn_id, tGATT_DISC_TYPE disc_type, - tGATT_STATUS status); -tGATT_STATUS bta_gattc_discover_pri_service(uint16_t conn_id, - tBTA_GATTC_SERV* p_server_cb, +void bta_gattc_disc_res_cback(uint16_t conn_id, tGATT_DISC_TYPE disc_type, tGATT_DISC_RES* p_data); +void bta_gattc_disc_cmpl_cback(uint16_t conn_id, tGATT_DISC_TYPE disc_type, tGATT_STATUS status); +tGATT_STATUS bta_gattc_discover_pri_service(uint16_t conn_id, tBTA_GATTC_SERV* p_server_cb, tGATT_DISC_TYPE disc_type); void bta_gattc_search_service(tBTA_GATTC_CLCB* p_clcb, bluetooth::Uuid* p_uuid); const std::list* bta_gattc_get_services(uint16_t conn_id); -const gatt::Service* bta_gattc_get_service_for_handle(uint16_t conn_id, - uint16_t handle); -const gatt::Characteristic* bta_gattc_get_characteristic_srcb( - tBTA_GATTC_SERV* p_srcb, uint16_t handle); -const gatt::Service* bta_gattc_get_service_for_handle_srcb( - tBTA_GATTC_SERV* p_srcb, uint16_t handle); -const gatt::Characteristic* bta_gattc_get_characteristic(uint16_t conn_id, - uint16_t handle); -const gatt::Descriptor* bta_gattc_get_descriptor(uint16_t conn_id, - uint16_t handle); -const gatt::Characteristic* bta_gattc_get_owning_characteristic( - uint16_t conn_id, uint16_t handle); -void bta_gattc_get_gatt_db(uint16_t conn_id, uint16_t start_handle, - uint16_t end_handle, btgatt_db_element_t** db, - int* count); +const gatt::Service* bta_gattc_get_service_for_handle(uint16_t conn_id, uint16_t handle); +const gatt::Characteristic* bta_gattc_get_characteristic_srcb(tBTA_GATTC_SERV* p_srcb, + uint16_t handle); +const gatt::Service* bta_gattc_get_service_for_handle_srcb(tBTA_GATTC_SERV* p_srcb, + uint16_t handle); +const gatt::Characteristic* bta_gattc_get_characteristic(uint16_t conn_id, uint16_t handle); +const gatt::Descriptor* bta_gattc_get_descriptor(uint16_t conn_id, uint16_t handle); +const gatt::Characteristic* bta_gattc_get_owning_characteristic(uint16_t conn_id, uint16_t handle); +void bta_gattc_get_gatt_db(uint16_t conn_id, uint16_t start_handle, uint16_t end_handle, + btgatt_db_element_t** db, int* count); void bta_gattc_init_cache(tBTA_GATTC_SERV* p_srvc_cb); -enum class RobustCachingSupport { - UNSUPPORTED, - SUPPORTED, - UNKNOWN, - W4_REMOTE_VERSION -}; +enum class RobustCachingSupport { UNSUPPORTED, SUPPORTED, UNKNOWN, W4_REMOTE_VERSION }; RobustCachingSupport GetRobustCachingSupport(const tBTA_GATTC_CLCB* p_clcb, const gatt::Database& db); @@ -522,8 +485,7 @@ bool bta_gattc_read_db_hash(tBTA_GATTC_CLCB* p_clcb, bool is_svc_chg); gatt::Database bta_gattc_hash_load(const Octet16& hash); bool bta_gattc_hash_write(const Octet16& hash, const gatt::Database& database); gatt::Database bta_gattc_cache_load(const RawAddress& server_bda); -void bta_gattc_cache_write(const RawAddress& server_bda, - const gatt::Database& database); +void bta_gattc_cache_write(const RawAddress& server_bda, const gatt::Database& database); void bta_gattc_cache_link(const RawAddress& server_bda, const Octet16& hash); void bta_gattc_cache_reset(const RawAddress& server_bda); @@ -565,13 +527,11 @@ namespace fmt { template <> struct formatter : enum_formatter {}; template <> -struct formatter - : enum_formatter {}; +struct formatter : enum_formatter {}; template <> struct formatter : enum_formatter {}; template <> -struct formatter : enum_formatter { -}; +struct formatter : enum_formatter {}; } // namespace fmt #endif /* BTA_GATTC_INT_H */ diff --git a/system/bta/gatt/bta_gattc_main.cc b/system/bta/gatt/bta_gattc_main.cc index a7a58457ad1..0bf55b1cfb3 100644 --- a/system/bta/gatt/bta_gattc_main.cc +++ b/system/bta/gatt/bta_gattc_main.cc @@ -68,35 +68,34 @@ enum { BTA_GATTC_IGNORE }; /* type for action functions */ -typedef void (*tBTA_GATTC_ACTION)(tBTA_GATTC_CLCB* p_clcb, - const tBTA_GATTC_DATA* p_data); +typedef void (*tBTA_GATTC_ACTION)(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data); /* action function list */ const tBTA_GATTC_ACTION bta_gattc_action[] = { - bta_gattc_open, /* BTA_GATTC_OPEN */ - bta_gattc_open_fail, /* BTA_GATTC_OPEN_FAIL */ - bta_gattc_open_error, /* BTA_GATTC_OPEN_ERROR */ - bta_gattc_cancel_open, /* BTA_GATTC_CANCEL_OPEN */ - bta_gattc_cancel_open_ok, /* BTA_GATTC_CANCEL_OPEN_OK */ - bta_gattc_cancel_open_error, /* BTA_GATTC_CANCEL_OPEN_ERROR */ - bta_gattc_conn, /* BTA_GATTC_CONN */ - bta_gattc_start_discover, /* BTA_GATTC_START_DISCOVER */ - bta_gattc_disc_cmpl, /* BTA_GATTC_DISC_CMPL */ - bta_gattc_q_cmd, /* BTA_GATTC_Q_CMD */ - bta_gattc_close, /* BTA_GATTC_CLOSE */ - bta_gattc_close_fail, /* BTA_GATTC_CLOSE_FAIL */ - bta_gattc_read, /* BTA_GATTC_READ */ - bta_gattc_write, /* BTA_GATTC_WRITE */ - bta_gattc_op_cmpl, /* BTA_GATTC_OP_CMPL */ - bta_gattc_search, /* BTA_GATTC_SEARCH */ - bta_gattc_fail, /* BTA_GATTC_FAIL */ - bta_gattc_confirm, /* BTA_GATTC_CONFIRM */ - bta_gattc_execute, /* BTA_GATTC_EXEC */ - bta_gattc_read_multi, /* BTA_GATTC_READ_MULTI */ - bta_gattc_op_cmpl_during_discovery, /* BTA_GATTC_OP_CMPL_DURING_DISCOVERY */ - bta_gattc_disc_close, /* BTA_GATTC_DISC_CLOSE */ - bta_gattc_restart_discover, /* BTA_GATTC_RESTART_DISCOVER */ - bta_gattc_cfg_mtu /* BTA_GATTC_CFG_MTU */ + bta_gattc_open, /* BTA_GATTC_OPEN */ + bta_gattc_open_fail, /* BTA_GATTC_OPEN_FAIL */ + bta_gattc_open_error, /* BTA_GATTC_OPEN_ERROR */ + bta_gattc_cancel_open, /* BTA_GATTC_CANCEL_OPEN */ + bta_gattc_cancel_open_ok, /* BTA_GATTC_CANCEL_OPEN_OK */ + bta_gattc_cancel_open_error, /* BTA_GATTC_CANCEL_OPEN_ERROR */ + bta_gattc_conn, /* BTA_GATTC_CONN */ + bta_gattc_start_discover, /* BTA_GATTC_START_DISCOVER */ + bta_gattc_disc_cmpl, /* BTA_GATTC_DISC_CMPL */ + bta_gattc_q_cmd, /* BTA_GATTC_Q_CMD */ + bta_gattc_close, /* BTA_GATTC_CLOSE */ + bta_gattc_close_fail, /* BTA_GATTC_CLOSE_FAIL */ + bta_gattc_read, /* BTA_GATTC_READ */ + bta_gattc_write, /* BTA_GATTC_WRITE */ + bta_gattc_op_cmpl, /* BTA_GATTC_OP_CMPL */ + bta_gattc_search, /* BTA_GATTC_SEARCH */ + bta_gattc_fail, /* BTA_GATTC_FAIL */ + bta_gattc_confirm, /* BTA_GATTC_CONFIRM */ + bta_gattc_execute, /* BTA_GATTC_EXEC */ + bta_gattc_read_multi, /* BTA_GATTC_READ_MULTI */ + bta_gattc_op_cmpl_during_discovery, /* BTA_GATTC_OP_CMPL_DURING_DISCOVERY */ + bta_gattc_disc_close, /* BTA_GATTC_DISC_CLOSE */ + bta_gattc_restart_discover, /* BTA_GATTC_RESTART_DISCOVER */ + bta_gattc_cfg_mtu /* BTA_GATTC_CFG_MTU */ }; /* state table information */ @@ -106,162 +105,111 @@ const tBTA_GATTC_ACTION bta_gattc_action[] = { /* state table for idle state */ static const uint8_t bta_gattc_st_idle[][BTA_GATTC_NUM_COLS] = { - /* Event Action 1 Next state */ - /* BTA_GATTC_API_OPEN_EVT */ {BTA_GATTC_OPEN, - BTA_GATTC_W4_CONN_ST}, - /* BTA_GATTC_INT_OPEN_FAIL_EVT */ {BTA_GATTC_IGNORE, - BTA_GATTC_IDLE_ST}, - /* BTA_GATTC_API_CANCEL_OPEN_EVT */ {BTA_GATTC_IGNORE, - BTA_GATTC_IDLE_ST}, - /* BTA_GATTC_INT_CANCEL_OPEN_OK_EVT */ {BTA_GATTC_IGNORE, - BTA_GATTC_IDLE_ST}, - - /* BTA_GATTC_API_READ_EVT */ {BTA_GATTC_FAIL, BTA_GATTC_IDLE_ST}, - /* BTA_GATTC_API_WRITE_EVT */ {BTA_GATTC_FAIL, BTA_GATTC_IDLE_ST}, - /* BTA_GATTC_API_EXEC_EVT */ {BTA_GATTC_FAIL, BTA_GATTC_IDLE_ST}, - /* BTA_GATTC_API_CFG_MTU_EVT */ {BTA_GATTC_IGNORE, - BTA_GATTC_IDLE_ST}, - - /* BTA_GATTC_API_CLOSE_EVT */ {BTA_GATTC_CLOSE_FAIL, - BTA_GATTC_IDLE_ST}, - - /* BTA_GATTC_API_SEARCH_EVT */ {BTA_GATTC_FAIL, BTA_GATTC_IDLE_ST}, - /* BTA_GATTC_API_CONFIRM_EVT */ {BTA_GATTC_FAIL, BTA_GATTC_IDLE_ST}, - /* BTA_GATTC_API_READ_MULTI_EVT */ {BTA_GATTC_FAIL, BTA_GATTC_IDLE_ST}, - - /* BTA_GATTC_INT_CONN_EVT */ {BTA_GATTC_CONN, BTA_GATTC_CONN_ST}, - /* BTA_GATTC_INT_DISCOVER_EVT */ {BTA_GATTC_IGNORE, - BTA_GATTC_IDLE_ST}, - /* BTA_GATTC_DISCOVER_CMPL_EVT */ {BTA_GATTC_IGNORE, - BTA_GATTC_IDLE_ST}, - /* BTA_GATTC_OP_CMPL_EVT */ {BTA_GATTC_IGNORE, - BTA_GATTC_IDLE_ST}, - /* BTA_GATTC_INT_DISCONN_EVT */ {BTA_GATTC_IGNORE, BTA_GATTC_IDLE_ST}, + /* Event Action 1 Next state */ + /* BTA_GATTC_API_OPEN_EVT */ {BTA_GATTC_OPEN, BTA_GATTC_W4_CONN_ST}, + /* BTA_GATTC_INT_OPEN_FAIL_EVT */ {BTA_GATTC_IGNORE, BTA_GATTC_IDLE_ST}, + /* BTA_GATTC_API_CANCEL_OPEN_EVT */ {BTA_GATTC_IGNORE, BTA_GATTC_IDLE_ST}, + /* BTA_GATTC_INT_CANCEL_OPEN_OK_EVT */ {BTA_GATTC_IGNORE, BTA_GATTC_IDLE_ST}, + + /* BTA_GATTC_API_READ_EVT */ {BTA_GATTC_FAIL, BTA_GATTC_IDLE_ST}, + /* BTA_GATTC_API_WRITE_EVT */ {BTA_GATTC_FAIL, BTA_GATTC_IDLE_ST}, + /* BTA_GATTC_API_EXEC_EVT */ {BTA_GATTC_FAIL, BTA_GATTC_IDLE_ST}, + /* BTA_GATTC_API_CFG_MTU_EVT */ {BTA_GATTC_IGNORE, BTA_GATTC_IDLE_ST}, + + /* BTA_GATTC_API_CLOSE_EVT */ {BTA_GATTC_CLOSE_FAIL, BTA_GATTC_IDLE_ST}, + + /* BTA_GATTC_API_SEARCH_EVT */ {BTA_GATTC_FAIL, BTA_GATTC_IDLE_ST}, + /* BTA_GATTC_API_CONFIRM_EVT */ {BTA_GATTC_FAIL, BTA_GATTC_IDLE_ST}, + /* BTA_GATTC_API_READ_MULTI_EVT */ {BTA_GATTC_FAIL, BTA_GATTC_IDLE_ST}, + + /* BTA_GATTC_INT_CONN_EVT */ {BTA_GATTC_CONN, BTA_GATTC_CONN_ST}, + /* BTA_GATTC_INT_DISCOVER_EVT */ {BTA_GATTC_IGNORE, BTA_GATTC_IDLE_ST}, + /* BTA_GATTC_DISCOVER_CMPL_EVT */ {BTA_GATTC_IGNORE, BTA_GATTC_IDLE_ST}, + /* BTA_GATTC_OP_CMPL_EVT */ {BTA_GATTC_IGNORE, BTA_GATTC_IDLE_ST}, + /* BTA_GATTC_INT_DISCONN_EVT */ {BTA_GATTC_IGNORE, BTA_GATTC_IDLE_ST}, }; /* state table for wait for open state */ static const uint8_t bta_gattc_st_w4_conn[][BTA_GATTC_NUM_COLS] = { - /* Event Action 1 Next state */ - /* BTA_GATTC_API_OPEN_EVT */ {BTA_GATTC_OPEN, - BTA_GATTC_W4_CONN_ST}, - /* BTA_GATTC_INT_OPEN_FAIL_EVT */ {BTA_GATTC_OPEN_FAIL, - BTA_GATTC_IDLE_ST}, - /* BTA_GATTC_API_CANCEL_OPEN_EVT */ {BTA_GATTC_CANCEL_OPEN, - BTA_GATTC_W4_CONN_ST}, - /* BTA_GATTC_INT_CANCEL_OPEN_OK_EVT */ {BTA_GATTC_CANCEL_OPEN_OK, - BTA_GATTC_IDLE_ST}, - - /* BTA_GATTC_API_READ_EVT */ {BTA_GATTC_FAIL, - BTA_GATTC_W4_CONN_ST}, - /* BTA_GATTC_API_WRITE_EVT */ {BTA_GATTC_FAIL, - BTA_GATTC_W4_CONN_ST}, - /* BTA_GATTC_API_EXEC_EVT */ {BTA_GATTC_FAIL, - BTA_GATTC_W4_CONN_ST}, - /* BTA_GATTC_API_CFG_MTU_EVT */ {BTA_GATTC_IGNORE, - BTA_GATTC_W4_CONN_ST}, - - /* BTA_GATTC_API_CLOSE_EVT */ {BTA_GATTC_CANCEL_OPEN, - BTA_GATTC_W4_CONN_ST}, - - /* BTA_GATTC_API_SEARCH_EVT */ {BTA_GATTC_FAIL, - BTA_GATTC_W4_CONN_ST}, - /* BTA_GATTC_API_CONFIRM_EVT */ {BTA_GATTC_FAIL, - BTA_GATTC_W4_CONN_ST}, - /* BTA_GATTC_API_READ_MULTI_EVT */ {BTA_GATTC_FAIL, - BTA_GATTC_W4_CONN_ST}, - - /* BTA_GATTC_INT_CONN_EVT */ {BTA_GATTC_CONN, BTA_GATTC_CONN_ST}, - /* BTA_GATTC_INT_DISCOVER_EVT */ {BTA_GATTC_IGNORE, - BTA_GATTC_W4_CONN_ST}, - /* BTA_GATTC_DISCOVER_CMPL_EVT */ {BTA_GATTC_IGNORE, - BTA_GATTC_W4_CONN_ST}, - /* BTA_GATTC_OP_CMPL_EVT */ {BTA_GATTC_IGNORE, - BTA_GATTC_W4_CONN_ST}, - /* BTA_GATTC_INT_DISCONN_EVT */ {BTA_GATTC_OPEN_FAIL, - BTA_GATTC_IDLE_ST}, + /* Event Action 1 Next state */ + /* BTA_GATTC_API_OPEN_EVT */ {BTA_GATTC_OPEN, BTA_GATTC_W4_CONN_ST}, + /* BTA_GATTC_INT_OPEN_FAIL_EVT */ {BTA_GATTC_OPEN_FAIL, BTA_GATTC_IDLE_ST}, + /* BTA_GATTC_API_CANCEL_OPEN_EVT */ {BTA_GATTC_CANCEL_OPEN, BTA_GATTC_W4_CONN_ST}, + /* BTA_GATTC_INT_CANCEL_OPEN_OK_EVT */ {BTA_GATTC_CANCEL_OPEN_OK, BTA_GATTC_IDLE_ST}, + + /* BTA_GATTC_API_READ_EVT */ {BTA_GATTC_FAIL, BTA_GATTC_W4_CONN_ST}, + /* BTA_GATTC_API_WRITE_EVT */ {BTA_GATTC_FAIL, BTA_GATTC_W4_CONN_ST}, + /* BTA_GATTC_API_EXEC_EVT */ {BTA_GATTC_FAIL, BTA_GATTC_W4_CONN_ST}, + /* BTA_GATTC_API_CFG_MTU_EVT */ {BTA_GATTC_IGNORE, BTA_GATTC_W4_CONN_ST}, + + /* BTA_GATTC_API_CLOSE_EVT */ {BTA_GATTC_CANCEL_OPEN, BTA_GATTC_W4_CONN_ST}, + + /* BTA_GATTC_API_SEARCH_EVT */ {BTA_GATTC_FAIL, BTA_GATTC_W4_CONN_ST}, + /* BTA_GATTC_API_CONFIRM_EVT */ {BTA_GATTC_FAIL, BTA_GATTC_W4_CONN_ST}, + /* BTA_GATTC_API_READ_MULTI_EVT */ {BTA_GATTC_FAIL, BTA_GATTC_W4_CONN_ST}, + + /* BTA_GATTC_INT_CONN_EVT */ {BTA_GATTC_CONN, BTA_GATTC_CONN_ST}, + /* BTA_GATTC_INT_DISCOVER_EVT */ {BTA_GATTC_IGNORE, BTA_GATTC_W4_CONN_ST}, + /* BTA_GATTC_DISCOVER_CMPL_EVT */ {BTA_GATTC_IGNORE, BTA_GATTC_W4_CONN_ST}, + /* BTA_GATTC_OP_CMPL_EVT */ {BTA_GATTC_IGNORE, BTA_GATTC_W4_CONN_ST}, + /* BTA_GATTC_INT_DISCONN_EVT */ {BTA_GATTC_OPEN_FAIL, BTA_GATTC_IDLE_ST}, }; /* state table for open state */ static const uint8_t bta_gattc_st_connected[][BTA_GATTC_NUM_COLS] = { - /* Event Action 1 Next state */ - /* BTA_GATTC_API_OPEN_EVT */ {BTA_GATTC_OPEN, BTA_GATTC_CONN_ST}, - /* BTA_GATTC_INT_OPEN_FAIL_EVT */ {BTA_GATTC_IGNORE, - BTA_GATTC_CONN_ST}, - /* BTA_GATTC_API_CANCEL_OPEN_EVT */ {BTA_GATTC_CANCEL_OPEN_ERROR, - BTA_GATTC_CONN_ST}, - /* BTA_GATTC_INT_CANCEL_OPEN_OK_EVT */ {BTA_GATTC_IGNORE, - BTA_GATTC_CONN_ST}, - - /* BTA_GATTC_API_READ_EVT */ {BTA_GATTC_READ, BTA_GATTC_CONN_ST}, - /* BTA_GATTC_API_WRITE_EVT */ {BTA_GATTC_WRITE, BTA_GATTC_CONN_ST}, - /* BTA_GATTC_API_EXEC_EVT */ {BTA_GATTC_EXEC, BTA_GATTC_CONN_ST}, - /* BTA_GATTC_API_CFG_MTU_EVT */ {BTA_GATTC_CFG_MTU, - BTA_GATTC_CONN_ST}, - - /* BTA_GATTC_API_CLOSE_EVT */ {BTA_GATTC_CLOSE, BTA_GATTC_IDLE_ST}, - - /* BTA_GATTC_API_SEARCH_EVT */ {BTA_GATTC_SEARCH, - BTA_GATTC_CONN_ST}, - /* BTA_GATTC_API_CONFIRM_EVT */ {BTA_GATTC_CONFIRM, - BTA_GATTC_CONN_ST}, - /* BTA_GATTC_API_READ_MULTI_EVT */ {BTA_GATTC_READ_MULTI, - BTA_GATTC_CONN_ST}, - - /* BTA_GATTC_INT_CONN_EVT */ {BTA_GATTC_IGNORE, - BTA_GATTC_CONN_ST}, - /* BTA_GATTC_INT_DISCOVER_EVT */ {BTA_GATTC_START_DISCOVER, - BTA_GATTC_DISCOVER_ST}, - /* BTA_GATTC_DISCOVER_CMPL_EVT */ {BTA_GATTC_IGNORE, - BTA_GATTC_CONN_ST}, - /* BTA_GATTC_OP_CMPL_EVT */ {BTA_GATTC_OP_CMPL, - BTA_GATTC_CONN_ST}, - - /* BTA_GATTC_INT_DISCONN_EVT */ {BTA_GATTC_CLOSE, BTA_GATTC_IDLE_ST}, + /* Event Action 1 Next state */ + /* BTA_GATTC_API_OPEN_EVT */ {BTA_GATTC_OPEN, BTA_GATTC_CONN_ST}, + /* BTA_GATTC_INT_OPEN_FAIL_EVT */ {BTA_GATTC_IGNORE, BTA_GATTC_CONN_ST}, + /* BTA_GATTC_API_CANCEL_OPEN_EVT */ {BTA_GATTC_CANCEL_OPEN_ERROR, BTA_GATTC_CONN_ST}, + /* BTA_GATTC_INT_CANCEL_OPEN_OK_EVT */ {BTA_GATTC_IGNORE, BTA_GATTC_CONN_ST}, + + /* BTA_GATTC_API_READ_EVT */ {BTA_GATTC_READ, BTA_GATTC_CONN_ST}, + /* BTA_GATTC_API_WRITE_EVT */ {BTA_GATTC_WRITE, BTA_GATTC_CONN_ST}, + /* BTA_GATTC_API_EXEC_EVT */ {BTA_GATTC_EXEC, BTA_GATTC_CONN_ST}, + /* BTA_GATTC_API_CFG_MTU_EVT */ {BTA_GATTC_CFG_MTU, BTA_GATTC_CONN_ST}, + + /* BTA_GATTC_API_CLOSE_EVT */ {BTA_GATTC_CLOSE, BTA_GATTC_IDLE_ST}, + + /* BTA_GATTC_API_SEARCH_EVT */ {BTA_GATTC_SEARCH, BTA_GATTC_CONN_ST}, + /* BTA_GATTC_API_CONFIRM_EVT */ {BTA_GATTC_CONFIRM, BTA_GATTC_CONN_ST}, + /* BTA_GATTC_API_READ_MULTI_EVT */ {BTA_GATTC_READ_MULTI, BTA_GATTC_CONN_ST}, + + /* BTA_GATTC_INT_CONN_EVT */ {BTA_GATTC_IGNORE, BTA_GATTC_CONN_ST}, + /* BTA_GATTC_INT_DISCOVER_EVT */ {BTA_GATTC_START_DISCOVER, BTA_GATTC_DISCOVER_ST}, + /* BTA_GATTC_DISCOVER_CMPL_EVT */ {BTA_GATTC_IGNORE, BTA_GATTC_CONN_ST}, + /* BTA_GATTC_OP_CMPL_EVT */ {BTA_GATTC_OP_CMPL, BTA_GATTC_CONN_ST}, + + /* BTA_GATTC_INT_DISCONN_EVT */ {BTA_GATTC_CLOSE, BTA_GATTC_IDLE_ST}, }; /* state table for discover state */ static const uint8_t bta_gattc_st_discover[][BTA_GATTC_NUM_COLS] = { - /* Event Action 1 Next state */ - /* BTA_GATTC_API_OPEN_EVT */ {BTA_GATTC_OPEN, - BTA_GATTC_DISCOVER_ST}, - /* BTA_GATTC_INT_OPEN_FAIL_EVT */ {BTA_GATTC_IGNORE, - BTA_GATTC_DISCOVER_ST}, - /* BTA_GATTC_API_CANCEL_OPEN_EVT */ {BTA_GATTC_CANCEL_OPEN_ERROR, - BTA_GATTC_DISCOVER_ST}, - /* BTA_GATTC_INT_CANCEL_OPEN_OK_EVT */ {BTA_GATTC_FAIL, - BTA_GATTC_DISCOVER_ST}, - - /* BTA_GATTC_API_READ_EVT */ {BTA_GATTC_Q_CMD, - BTA_GATTC_DISCOVER_ST}, - /* BTA_GATTC_API_WRITE_EVT */ {BTA_GATTC_Q_CMD, - BTA_GATTC_DISCOVER_ST}, - /* BTA_GATTC_API_EXEC_EVT */ {BTA_GATTC_Q_CMD, - BTA_GATTC_DISCOVER_ST}, - /* BTA_GATTC_API_CFG_MTU_EVT */ {BTA_GATTC_Q_CMD, - BTA_GATTC_DISCOVER_ST}, - - /* BTA_GATTC_API_CLOSE_EVT */ {BTA_GATTC_DISC_CLOSE, - BTA_GATTC_DISCOVER_ST}, - - /* BTA_GATTC_API_SEARCH_EVT */ {BTA_GATTC_Q_CMD, - BTA_GATTC_DISCOVER_ST}, - /* BTA_GATTC_API_CONFIRM_EVT */ {BTA_GATTC_CONFIRM, - BTA_GATTC_DISCOVER_ST}, - /* BTA_GATTC_API_READ_MULTI_EVT */ {BTA_GATTC_Q_CMD, - BTA_GATTC_DISCOVER_ST}, - - /* BTA_GATTC_INT_CONN_EVT */ {BTA_GATTC_CONN, - BTA_GATTC_DISCOVER_ST}, - /* BTA_GATTC_INT_DISCOVER_EVT */ {BTA_GATTC_RESTART_DISCOVER, - BTA_GATTC_DISCOVER_ST}, - /* BTA_GATTC_DISCOVER_CMPL_EVT */ {BTA_GATTC_DISC_CMPL, - BTA_GATTC_CONN_ST}, - /* BTA_GATTC_OP_CMPL_EVT */ {BTA_GATTC_OP_CMPL_DURING_DISCOVERY, - BTA_GATTC_DISCOVER_ST}, - /* BTA_GATTC_INT_DISCONN_EVT */ {BTA_GATTC_CLOSE, BTA_GATTC_IDLE_ST}, + /* Event Action 1 Next state */ + /* BTA_GATTC_API_OPEN_EVT */ {BTA_GATTC_OPEN, BTA_GATTC_DISCOVER_ST}, + /* BTA_GATTC_INT_OPEN_FAIL_EVT */ {BTA_GATTC_IGNORE, BTA_GATTC_DISCOVER_ST}, + /* BTA_GATTC_API_CANCEL_OPEN_EVT */ {BTA_GATTC_CANCEL_OPEN_ERROR, BTA_GATTC_DISCOVER_ST}, + /* BTA_GATTC_INT_CANCEL_OPEN_OK_EVT */ {BTA_GATTC_FAIL, BTA_GATTC_DISCOVER_ST}, + + /* BTA_GATTC_API_READ_EVT */ {BTA_GATTC_Q_CMD, BTA_GATTC_DISCOVER_ST}, + /* BTA_GATTC_API_WRITE_EVT */ {BTA_GATTC_Q_CMD, BTA_GATTC_DISCOVER_ST}, + /* BTA_GATTC_API_EXEC_EVT */ {BTA_GATTC_Q_CMD, BTA_GATTC_DISCOVER_ST}, + /* BTA_GATTC_API_CFG_MTU_EVT */ {BTA_GATTC_Q_CMD, BTA_GATTC_DISCOVER_ST}, + + /* BTA_GATTC_API_CLOSE_EVT */ {BTA_GATTC_DISC_CLOSE, BTA_GATTC_DISCOVER_ST}, + + /* BTA_GATTC_API_SEARCH_EVT */ {BTA_GATTC_Q_CMD, BTA_GATTC_DISCOVER_ST}, + /* BTA_GATTC_API_CONFIRM_EVT */ {BTA_GATTC_CONFIRM, BTA_GATTC_DISCOVER_ST}, + /* BTA_GATTC_API_READ_MULTI_EVT */ {BTA_GATTC_Q_CMD, BTA_GATTC_DISCOVER_ST}, + + /* BTA_GATTC_INT_CONN_EVT */ {BTA_GATTC_CONN, BTA_GATTC_DISCOVER_ST}, + /* BTA_GATTC_INT_DISCOVER_EVT */ {BTA_GATTC_RESTART_DISCOVER, BTA_GATTC_DISCOVER_ST}, + /* BTA_GATTC_DISCOVER_CMPL_EVT */ {BTA_GATTC_DISC_CMPL, BTA_GATTC_CONN_ST}, + /* BTA_GATTC_OP_CMPL_EVT */ + {BTA_GATTC_OP_CMPL_DURING_DISCOVERY, BTA_GATTC_DISCOVER_ST}, + /* BTA_GATTC_INT_DISCONN_EVT */ {BTA_GATTC_CLOSE, BTA_GATTC_IDLE_ST}, }; @@ -270,10 +218,10 @@ typedef const uint8_t (*tBTA_GATTC_ST_TBL)[BTA_GATTC_NUM_COLS]; /* state table */ const tBTA_GATTC_ST_TBL bta_gattc_st_tbl[] = { - bta_gattc_st_idle, /* BTA_GATTC_IDLE_ST */ - bta_gattc_st_w4_conn, /* BTA_GATTC_W4_CONN_ST */ - bta_gattc_st_connected, /* BTA_GATTC_CONN_ST */ - bta_gattc_st_discover /* BTA_GATTC_DISCOVER_ST */ + bta_gattc_st_idle, /* BTA_GATTC_IDLE_ST */ + bta_gattc_st_w4_conn, /* BTA_GATTC_W4_CONN_ST */ + bta_gattc_st_connected, /* BTA_GATTC_CONN_ST */ + bta_gattc_st_discover /* BTA_GATTC_DISCOVER_ST */ }; /***************************************************************************** @@ -299,8 +247,7 @@ static const char* gattc_state_code(tBTA_GATTC_STATE state_code); * immediately released, else false * ******************************************************************************/ -bool bta_gattc_sm_execute(tBTA_GATTC_CLCB* p_clcb, uint16_t event, - const tBTA_GATTC_DATA* p_data) { +bool bta_gattc_sm_execute(tBTA_GATTC_CLCB* p_clcb, uint16_t event, const tBTA_GATTC_DATA* p_data) { tBTA_GATTC_ST_TBL state_table; uint8_t action; int i; @@ -308,8 +255,8 @@ bool bta_gattc_sm_execute(tBTA_GATTC_CLCB* p_clcb, uint16_t event, tBTA_GATTC_STATE in_state = p_clcb->state; uint16_t in_event = event; #if (BTA_GATT_DEBUG == TRUE) - log::verbose("State 0x{:02x} [{}], Event 0x{:x}[{}]", in_state, - gattc_state_code(in_state), in_event, gattc_evt_code(in_event)); + log::verbose("State 0x{:02x} [{}], Event 0x{:x}[{}]", in_state, gattc_state_code(in_state), + in_event, gattc_evt_code(in_event)); #else log::verbose("State 0x{:02x}, Event 0x{:x}", in_state, in_event); #endif @@ -340,13 +287,12 @@ bool bta_gattc_sm_execute(tBTA_GATTC_CLCB* p_clcb, uint16_t event, #if (BTA_GATT_DEBUG == TRUE) if (in_state != p_clcb->state) { - log::verbose("GATTC State Change: [{}] -> [{}] after Event [{}]", - gattc_state_code(in_state), gattc_state_code(p_clcb->state), - gattc_evt_code(in_event)); + log::verbose("GATTC State Change: [{}] -> [{}] after Event [{}]", gattc_state_code(in_state), + gattc_state_code(p_clcb->state), gattc_evt_code(in_event)); } #else - log::verbose("GATTC State Change: 0x{:02x} -> 0x{:02x} after Event 0x{:x}", - in_state, p_clcb->state, in_event); + log::verbose("GATTC State Change: 0x{:02x} -> 0x{:02x} after Event 0x{:x}", in_state, + p_clcb->state, in_event); #endif return rt; } @@ -368,7 +314,6 @@ bool bta_gattc_hdl_event(const BT_HDR_RIGID* p_msg) { log::verbose("Event:{}", gattc_evt_code(p_msg->event)); #endif switch (p_msg->event) { - case BTA_GATTC_API_OPEN_EVT: bta_gattc_process_api_open((tBTA_GATTC_DATA*)p_msg); break; @@ -378,16 +323,16 @@ bool bta_gattc_hdl_event(const BT_HDR_RIGID* p_msg) { break; default: - if (p_msg->event == BTA_GATTC_INT_CONN_EVT) + if (p_msg->event == BTA_GATTC_INT_CONN_EVT) { p_clcb = bta_gattc_find_int_conn_clcb((tBTA_GATTC_DATA*)p_msg); - else if (p_msg->event == BTA_GATTC_INT_DISCONN_EVT) + } else if (p_msg->event == BTA_GATTC_INT_DISCONN_EVT) { p_clcb = bta_gattc_find_int_disconn_clcb((tBTA_GATTC_DATA*)p_msg); - else + } else { p_clcb = bta_gattc_find_clcb_by_conn_id(p_msg->layer_specific); + } if (p_clcb != nullptr) { - rt = bta_gattc_sm_execute(p_clcb, p_msg->event, - (const tBTA_GATTC_DATA*)p_msg); + rt = bta_gattc_sm_execute(p_clcb, p_msg->event, (const tBTA_GATTC_DATA*)p_msg); } else { log::error("Ignore unknown conn ID: {}", p_msg->layer_specific); } diff --git a/system/bta/gatt/bta_gattc_queue.cc b/system/bta/gatt/bta_gattc_queue.cc index 9929dabf6a3..32c0bcb8e63 100644 --- a/system/bta/gatt/bta_gattc_queue.cc +++ b/system/bta/gatt/bta_gattc_queue.cc @@ -42,17 +42,15 @@ struct gatt_read_op_data { void* cb_data; }; -std::unordered_map> - BtaGattQueue::gatt_op_queue; +std::unordered_map> BtaGattQueue::gatt_op_queue; std::unordered_set BtaGattQueue::gatt_op_queue_executing; void BtaGattQueue::mark_as_not_executing(uint16_t conn_id) { gatt_op_queue_executing.erase(conn_id); } -void BtaGattQueue::gatt_read_op_finished(uint16_t conn_id, tGATT_STATUS status, - uint16_t handle, uint16_t len, - uint8_t* value, void* data) { +void BtaGattQueue::gatt_read_op_finished(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, + uint16_t len, uint8_t* value, void* data) { gatt_read_op_data* tmp = (gatt_read_op_data*)data; GATT_READ_OP_CB tmp_cb = tmp->cb; void* tmp_cb_data = tmp->cb_data; @@ -73,9 +71,8 @@ struct gatt_write_op_data { void* cb_data; }; -void BtaGattQueue::gatt_write_op_finished(uint16_t conn_id, tGATT_STATUS status, - uint16_t handle, uint16_t len, - const uint8_t* value, void* data) { +void BtaGattQueue::gatt_write_op_finished(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, + uint16_t len, const uint8_t* value, void* data) { gatt_write_op_data* tmp = (gatt_write_op_data*)data; GATT_WRITE_OP_CB tmp_cb = tmp->cb; void* tmp_cb_data = tmp->cb_data; @@ -96,8 +93,7 @@ struct gatt_configure_mtu_op_data { void* cb_data; }; -void BtaGattQueue::gatt_configure_mtu_op_finished(uint16_t conn_id, - tGATT_STATUS status, +void BtaGattQueue::gatt_configure_mtu_op_finished(uint16_t conn_id, tGATT_STATUS status, void* data) { gatt_configure_mtu_op_data* tmp = (gatt_configure_mtu_op_data*)data; GATT_CONFIGURE_MTU_OP_CB tmp_cb = tmp->cb; @@ -119,11 +115,9 @@ struct gatt_read_multi_op_data { void* cb_data; }; -void BtaGattQueue::gatt_read_multi_op_finished(uint16_t conn_id, - tGATT_STATUS status, - tBTA_GATTC_MULTI& handles, - uint16_t len, uint8_t* value, - void* data) { +void BtaGattQueue::gatt_read_multi_op_finished(uint16_t conn_id, tGATT_STATUS status, + tBTA_GATTC_MULTI& handles, uint16_t len, + uint8_t* value, void* data) { gatt_read_multi_op_data* tmp = (gatt_read_multi_op_data*)data; GATT_READ_MULTI_OP_CB tmp_cb = tmp->cb; void* tmp_cb_data = tmp->cb_data; @@ -164,53 +158,45 @@ void BtaGattQueue::gatt_execute_next_op(uint16_t conn_id) { gatt_operation& op = gatt_ops.front(); if (op.type == GATT_READ_CHAR) { - gatt_read_op_data* data = - (gatt_read_op_data*)osi_malloc(sizeof(gatt_read_op_data)); + gatt_read_op_data* data = (gatt_read_op_data*)osi_malloc(sizeof(gatt_read_op_data)); data->cb = op.read_cb; data->cb_data = op.read_cb_data; - BTA_GATTC_ReadCharacteristic(conn_id, op.handle, GATT_AUTH_REQ_NONE, - gatt_read_op_finished, data); + BTA_GATTC_ReadCharacteristic(conn_id, op.handle, GATT_AUTH_REQ_NONE, gatt_read_op_finished, + data); } else if (op.type == GATT_READ_DESC) { - gatt_read_op_data* data = - (gatt_read_op_data*)osi_malloc(sizeof(gatt_read_op_data)); + gatt_read_op_data* data = (gatt_read_op_data*)osi_malloc(sizeof(gatt_read_op_data)); data->cb = op.read_cb; data->cb_data = op.read_cb_data; - BTA_GATTC_ReadCharDescr(conn_id, op.handle, GATT_AUTH_REQ_NONE, - gatt_read_op_finished, data); + BTA_GATTC_ReadCharDescr(conn_id, op.handle, GATT_AUTH_REQ_NONE, gatt_read_op_finished, data); } else if (op.type == GATT_WRITE_CHAR) { - gatt_write_op_data* data = - (gatt_write_op_data*)osi_malloc(sizeof(gatt_write_op_data)); + gatt_write_op_data* data = (gatt_write_op_data*)osi_malloc(sizeof(gatt_write_op_data)); data->cb = op.write_cb; data->cb_data = op.write_cb_data; - BTA_GATTC_WriteCharValue(conn_id, op.handle, op.write_type, - std::move(op.value), GATT_AUTH_REQ_NONE, - gatt_write_op_finished, data); + BTA_GATTC_WriteCharValue(conn_id, op.handle, op.write_type, std::move(op.value), + GATT_AUTH_REQ_NONE, gatt_write_op_finished, data); } else if (op.type == GATT_WRITE_DESC) { - gatt_write_op_data* data = - (gatt_write_op_data*)osi_malloc(sizeof(gatt_write_op_data)); + gatt_write_op_data* data = (gatt_write_op_data*)osi_malloc(sizeof(gatt_write_op_data)); data->cb = op.write_cb; data->cb_data = op.write_cb_data; - BTA_GATTC_WriteCharDescr(conn_id, op.handle, std::move(op.value), - GATT_AUTH_REQ_NONE, gatt_write_op_finished, data); + BTA_GATTC_WriteCharDescr(conn_id, op.handle, std::move(op.value), GATT_AUTH_REQ_NONE, + gatt_write_op_finished, data); } else if (op.type == GATT_CONFIG_MTU) { gatt_configure_mtu_op_data* data = - (gatt_configure_mtu_op_data*)osi_malloc(sizeof(gatt_configure_mtu_op_data)); + (gatt_configure_mtu_op_data*)osi_malloc(sizeof(gatt_configure_mtu_op_data)); data->cb = op.mtu_cb; data->cb_data = op.mtu_cb_data; - BTA_GATTC_ConfigureMTU(conn_id, static_cast(op.value[0] | - (op.value[1] << 8)), + BTA_GATTC_ConfigureMTU(conn_id, static_cast(op.value[0] | (op.value[1] << 8)), gatt_configure_mtu_op_finished, data); } else if (op.type == GATT_READ_MULTI) { gatt_read_multi_op_data* data = - (gatt_read_multi_op_data*)osi_malloc(sizeof(gatt_read_multi_op_data)); + (gatt_read_multi_op_data*)osi_malloc(sizeof(gatt_read_multi_op_data)); data->cb = op.read_multi_cb; data->cb_data = op.read_cb_data; - BTA_GATTC_ReadMultiple(conn_id, op.handles, op.variable_len, - GATT_AUTH_REQ_NONE, gatt_read_multi_op_finished, - data); + BTA_GATTC_ReadMultiple(conn_id, op.handles, op.variable_len, GATT_AUTH_REQ_NONE, + gatt_read_multi_op_finished, data); } gatt_ops.pop_front(); @@ -221,27 +207,22 @@ void BtaGattQueue::Clean(uint16_t conn_id) { gatt_op_queue_executing.erase(conn_id); } -void BtaGattQueue::ReadCharacteristic(uint16_t conn_id, uint16_t handle, - GATT_READ_OP_CB cb, void* cb_data) { - gatt_op_queue[conn_id].push_back({.type = GATT_READ_CHAR, - .handle = handle, - .read_cb = cb, - .read_cb_data = cb_data}); +void BtaGattQueue::ReadCharacteristic(uint16_t conn_id, uint16_t handle, GATT_READ_OP_CB cb, + void* cb_data) { + gatt_op_queue[conn_id].push_back( + {.type = GATT_READ_CHAR, .handle = handle, .read_cb = cb, .read_cb_data = cb_data}); gatt_execute_next_op(conn_id); } -void BtaGattQueue::ReadDescriptor(uint16_t conn_id, uint16_t handle, - GATT_READ_OP_CB cb, void* cb_data) { - gatt_op_queue[conn_id].push_back({.type = GATT_READ_DESC, - .handle = handle, - .read_cb = cb, - .read_cb_data = cb_data}); +void BtaGattQueue::ReadDescriptor(uint16_t conn_id, uint16_t handle, GATT_READ_OP_CB cb, + void* cb_data) { + gatt_op_queue[conn_id].push_back( + {.type = GATT_READ_DESC, .handle = handle, .read_cb = cb, .read_cb_data = cb_data}); gatt_execute_next_op(conn_id); } void BtaGattQueue::WriteCharacteristic(uint16_t conn_id, uint16_t handle, - std::vector value, - tGATT_WRITE_TYPE write_type, + std::vector value, tGATT_WRITE_TYPE write_type, GATT_WRITE_OP_CB cb, void* cb_data) { gatt_op_queue[conn_id].push_back({.type = GATT_WRITE_CHAR, .handle = handle, @@ -252,10 +233,9 @@ void BtaGattQueue::WriteCharacteristic(uint16_t conn_id, uint16_t handle, gatt_execute_next_op(conn_id); } -void BtaGattQueue::WriteDescriptor(uint16_t conn_id, uint16_t handle, - std::vector value, - tGATT_WRITE_TYPE write_type, - GATT_WRITE_OP_CB cb, void* cb_data) { +void BtaGattQueue::WriteDescriptor(uint16_t conn_id, uint16_t handle, std::vector value, + tGATT_WRITE_TYPE write_type, GATT_WRITE_OP_CB cb, + void* cb_data) { gatt_op_queue[conn_id].push_back({.type = GATT_WRITE_DESC, .handle = handle, .write_cb = cb, @@ -267,17 +247,13 @@ void BtaGattQueue::WriteDescriptor(uint16_t conn_id, uint16_t handle, void BtaGattQueue::ConfigureMtu(uint16_t conn_id, uint16_t mtu) { log::info("mtu: {}", static_cast(mtu)); - std::vector value = {static_cast(mtu & 0xff), - static_cast(mtu >> 8)}; - gatt_op_queue[conn_id].push_back({.type = GATT_CONFIG_MTU, - .value = std::move(value)}); + std::vector value = {static_cast(mtu & 0xff), static_cast(mtu >> 8)}; + gatt_op_queue[conn_id].push_back({.type = GATT_CONFIG_MTU, .value = std::move(value)}); gatt_execute_next_op(conn_id); } -void BtaGattQueue::ReadMultiCharacteristic(uint16_t conn_id, - tBTA_GATTC_MULTI& handles, - bool variable_len, - GATT_READ_MULTI_OP_CB cb, +void BtaGattQueue::ReadMultiCharacteristic(uint16_t conn_id, tBTA_GATTC_MULTI& handles, + bool variable_len, GATT_READ_MULTI_OP_CB cb, void* cb_data) { gatt_op_queue[conn_id].push_back({.type = GATT_READ_MULTI, .handles = handles, diff --git a/system/bta/gatt/bta_gattc_utils.cc b/system/bta/gatt/bta_gattc_utils.cc index f7a3f38eb8e..67b66fb73bc 100644 --- a/system/bta/gatt/bta_gattc_utils.cc +++ b/system/bta/gatt/bta_gattc_utils.cc @@ -63,7 +63,9 @@ tBTA_GATTC_RCB* bta_gattc_cl_get_regcb(uint8_t client_if) { tBTA_GATTC_RCB* p_clrcb = &bta_gattc_cb.cl_rcb[0]; for (i = 0; i < BTA_GATTC_CL_MAX; i++, p_clrcb++) { - if (p_clrcb->in_use && p_clrcb->client_if == client_if) return p_clrcb; + if (p_clrcb->in_use && p_clrcb->client_if == client_if) { + return p_clrcb; + } } return NULL; } @@ -80,7 +82,9 @@ uint8_t bta_gattc_num_reg_app(void) { uint8_t i = 0, j = 0; for (i = 0; i < BTA_GATTC_CL_MAX; i++) { - if (bta_gattc_cb.cl_rcb[i].in_use) j++; + if (bta_gattc_cb.cl_rcb[i].in_use) { + j++; + } } return j; } @@ -93,15 +97,15 @@ uint8_t bta_gattc_num_reg_app(void) { * Returns pointer to the clcb * ******************************************************************************/ -tBTA_GATTC_CLCB* bta_gattc_find_clcb_by_cif(uint8_t client_if, - const RawAddress& remote_bda, +tBTA_GATTC_CLCB* bta_gattc_find_clcb_by_cif(uint8_t client_if, const RawAddress& remote_bda, tBT_TRANSPORT transport) { tBTA_GATTC_CLCB* p_clcb = &bta_gattc_cb.clcb[0]; for (size_t i = 0; i < BTA_GATTC_CLCB_MAX; i++, p_clcb++) { - if (p_clcb->in_use && p_clcb->p_rcb->client_if == client_if && - p_clcb->transport == transport && p_clcb->bda == remote_bda) + if (p_clcb->in_use && p_clcb->p_rcb->client_if == client_if && p_clcb->transport == transport && + p_clcb->bda == remote_bda) { return p_clcb; + } } return NULL; } @@ -118,7 +122,9 @@ tBTA_GATTC_CLCB* bta_gattc_find_clcb_by_conn_id(uint16_t conn_id) { tBTA_GATTC_CLCB* p_clcb = &bta_gattc_cb.clcb[0]; for (size_t i = 0; i < BTA_GATTC_CLCB_MAX; i++, p_clcb++) { - if (p_clcb->in_use && p_clcb->bta_conn_id == conn_id) return p_clcb; + if (p_clcb->in_use && p_clcb->bta_conn_id == conn_id) { + return p_clcb; + } } return NULL; } @@ -132,8 +138,7 @@ tBTA_GATTC_CLCB* bta_gattc_find_clcb_by_conn_id(uint16_t conn_id) { * Returns pointer to the clcb * ******************************************************************************/ -tBTA_GATTC_CLCB* bta_gattc_clcb_alloc(tGATT_IF client_if, - const RawAddress& remote_bda, +tBTA_GATTC_CLCB* bta_gattc_clcb_alloc(tGATT_IF client_if, const RawAddress& remote_bda, tBT_TRANSPORT transport) { tBTA_GATTC_CLCB* p_clcb = NULL; @@ -152,8 +157,9 @@ tBTA_GATTC_CLCB* bta_gattc_clcb_alloc(tGATT_IF client_if, p_clcb->p_rcb = bta_gattc_cl_get_regcb(client_if); p_clcb->p_srcb = bta_gattc_find_srcb(remote_bda); - if (p_clcb->p_srcb == NULL) + if (p_clcb->p_srcb == NULL) { p_clcb->p_srcb = bta_gattc_srcb_alloc(remote_bda); + } if (p_clcb->p_rcb != NULL && p_clcb->p_srcb != NULL) { p_clcb->p_srcb->num_clcb++; @@ -177,8 +183,7 @@ tBTA_GATTC_CLCB* bta_gattc_clcb_alloc(tGATT_IF client_if, * Returns pointer to the clcb * ******************************************************************************/ -tBTA_GATTC_CLCB* bta_gattc_find_alloc_clcb(tGATT_IF client_if, - const RawAddress& remote_bda, +tBTA_GATTC_CLCB* bta_gattc_find_alloc_clcb(tGATT_IF client_if, const RawAddress& remote_bda, tBT_TRANSPORT transport) { tBTA_GATTC_CLCB* p_clcb; @@ -225,9 +230,13 @@ void bta_gattc_clcb_dealloc(tBTA_GATTC_CLCB* p_clcb) { } tBTA_GATTC_SERV* p_srcb = p_clcb->p_srcb; - if (p_srcb->num_clcb) p_srcb->num_clcb--; + if (p_srcb->num_clcb) { + p_srcb->num_clcb--; + } - if (p_clcb->p_rcb->num_clcb) p_clcb->p_rcb->num_clcb--; + if (p_clcb->p_rcb->num_clcb) { + p_clcb->p_rcb->num_clcb--; + } /* if the srcb is no longer needed, reset the state */ if (p_srcb->num_clcb == 0) { @@ -278,7 +287,9 @@ tBTA_GATTC_SERV* bta_gattc_find_srcb(const RawAddress& bda) { uint8_t i; for (i = 0; i < ble_acceptlist_size(); i++, p_srcb++) { - if (p_srcb->in_use && p_srcb->server_bda == bda) return p_srcb; + if (p_srcb->in_use && p_srcb->server_bda == bda) { + return p_srcb; + } } return NULL; } @@ -297,7 +308,9 @@ tBTA_GATTC_SERV* bta_gattc_find_srvr_cache(const RawAddress& bda) { uint8_t i; for (i = 0; i < ble_acceptlist_size(); i++, p_srcb++) { - if (p_srcb->server_bda == bda) return p_srcb; + if (p_srcb->server_bda == bda) { + return p_srcb; + } } return NULL; } @@ -313,10 +326,11 @@ tBTA_GATTC_SERV* bta_gattc_find_srvr_cache(const RawAddress& bda) { tBTA_GATTC_SERV* bta_gattc_find_scb_by_cid(uint16_t conn_id) { tBTA_GATTC_CLCB* p_clcb = bta_gattc_find_clcb_by_conn_id(conn_id); - if (p_clcb) + if (p_clcb) { return p_clcb->p_srcb; - else + } else { return NULL; + } } /******************************************************************************* * @@ -342,10 +356,11 @@ tBTA_GATTC_SERV* bta_gattc_srcb_alloc(const RawAddress& bda) { } /* if not found, try to recycle one known device */ - if (!found && !p_recycle) + if (!found && !p_recycle) { p_tcb = NULL; - else if (!found && p_recycle) + } else if (!found && p_recycle) { p_tcb = p_recycle; + } if (p_tcb != NULL) { // clear reallocating @@ -359,8 +374,7 @@ tBTA_GATTC_SERV* bta_gattc_srcb_alloc(const RawAddress& bda) { return p_tcb; } -void bta_gattc_send_mtu_response(tBTA_GATTC_CLCB* p_clcb, - const tBTA_GATTC_DATA* p_data, +void bta_gattc_send_mtu_response(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data, uint16_t current_mtu) { GATT_CONFIGURE_MTU_OP_CB cb = p_data->api_mtu.mtu_cb; if (cb) { @@ -382,8 +396,7 @@ void bta_gattc_send_mtu_response(tBTA_GATTC_CLCB* p_clcb, void bta_gattc_continue(tBTA_GATTC_CLCB* p_clcb) { if (p_clcb->p_q_cmd != NULL) { - log::info("Already scheduled another request for conn_id = 0x{:04x}", - p_clcb->bta_conn_id); + log::info("Already scheduled another request for conn_id = 0x{:04x}", p_clcb->bta_conn_id); return; } @@ -397,17 +410,15 @@ void bta_gattc_continue(tBTA_GATTC_CLCB* p_clcb) { /* The p_q_cmd is the MTU Request event. */ uint16_t current_mtu = 0; - auto result = GATTC_TryMtuRequest(p_clcb->bda, p_clcb->transport, - p_clcb->bta_conn_id, ¤t_mtu); + auto result = + GATTC_TryMtuRequest(p_clcb->bda, p_clcb->transport, p_clcb->bta_conn_id, ¤t_mtu); switch (result) { case MTU_EXCHANGE_DEVICE_DISCONNECTED: - bta_gattc_cmpl_sendmsg(p_clcb->bta_conn_id, GATTC_OPTYPE_CONFIG, - GATT_NO_RESOURCES, NULL); + bta_gattc_cmpl_sendmsg(p_clcb->bta_conn_id, GATTC_OPTYPE_CONFIG, GATT_NO_RESOURCES, NULL); /* Handled, free command below and continue with a p_q_cmd_queue */ break; case MTU_EXCHANGE_NOT_ALLOWED: - bta_gattc_cmpl_sendmsg(p_clcb->bta_conn_id, GATTC_OPTYPE_CONFIG, - GATT_ERR_UNLIKELY, NULL); + bta_gattc_cmpl_sendmsg(p_clcb->bta_conn_id, GATTC_OPTYPE_CONFIG, GATT_ERR_UNLIKELY, NULL); /* Handled, free command below and continue with a p_q_cmd_queue */ break; case MTU_EXCHANGE_ALREADY_DONE: @@ -432,14 +443,12 @@ void bta_gattc_continue(tBTA_GATTC_CLCB* p_clcb) { } } -bool bta_gattc_is_data_queued(tBTA_GATTC_CLCB* p_clcb, - const tBTA_GATTC_DATA* p_data) { +bool bta_gattc_is_data_queued(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data) { if (p_clcb->p_q_cmd == p_data) { return true; } - auto it = std::find(p_clcb->p_q_cmd_queue.begin(), - p_clcb->p_q_cmd_queue.end(), p_data); + auto it = std::find(p_clcb->p_q_cmd_queue.begin(), p_clcb->p_q_cmd_queue.end(), p_data); return it != p_clcb->p_q_cmd_queue.end(); } /******************************************************************************* @@ -451,17 +460,14 @@ bool bta_gattc_is_data_queued(tBTA_GATTC_CLCB* p_clcb, * Returns BtaEnqueuedResult_t * ******************************************************************************/ -BtaEnqueuedResult_t bta_gattc_enqueue(tBTA_GATTC_CLCB* p_clcb, - const tBTA_GATTC_DATA* p_data) { +BtaEnqueuedResult_t bta_gattc_enqueue(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data) { if (p_clcb->p_q_cmd == NULL) { p_clcb->p_q_cmd = p_data; return ENQUEUED_READY_TO_SEND; } - log::info( - "Already has a pending command to executer. Queuing for later {} conn " - "id=0x{:04x}", - p_clcb->bda, p_clcb->bta_conn_id); + log::info("Already has a pending command to executer. Queuing for later {} conn id=0x{:04x}", + p_clcb->bda, p_clcb->bta_conn_id); p_clcb->p_q_cmd_queue.push_back(p_data); return ENQUEUED_FOR_LATER; @@ -476,14 +482,12 @@ BtaEnqueuedResult_t bta_gattc_enqueue(tBTA_GATTC_CLCB* p_clcb, * Returns * ******************************************************************************/ -bool bta_gattc_check_notif_registry(tBTA_GATTC_RCB* p_clreg, - tBTA_GATTC_SERV* p_srcb, +bool bta_gattc_check_notif_registry(tBTA_GATTC_RCB* p_clreg, tBTA_GATTC_SERV* p_srcb, tBTA_GATTC_NOTIFY* p_notify) { uint8_t i; for (i = 0; i < BTA_GATTC_NOTIF_REG_MAX; i++) { - if (p_clreg->notif_reg[i].in_use && - p_clreg->notif_reg[i].remote_bda == p_srcb->server_bda && + if (p_clreg->notif_reg[i].in_use && p_clreg->notif_reg[i].remote_bda == p_srcb->server_bda && p_clreg->notif_reg[i].handle == p_notify->handle && !p_clreg->notif_reg[i].app_disconnected) { log::verbose("Notification registered!"); @@ -505,9 +509,8 @@ bool bta_gattc_check_notif_registry(tBTA_GATTC_RCB* p_clreg, * Returns None. * ******************************************************************************/ -void bta_gattc_clear_notif_registration(tBTA_GATTC_SERV* p_srcb, - uint16_t conn_id, uint16_t start_handle, - uint16_t end_handle) { +void bta_gattc_clear_notif_registration(tBTA_GATTC_SERV* p_srcb, uint16_t conn_id, + uint16_t start_handle, uint16_t end_handle) { RawAddress remote_bda; tGATT_IF gatt_if; tBTA_GATTC_RCB* p_clrcb; @@ -519,14 +522,14 @@ void bta_gattc_clear_notif_registration(tBTA_GATTC_SERV* p_srcb, p_clrcb = bta_gattc_cl_get_regcb(gatt_if); if (p_clrcb != NULL) { for (i = 0; i < BTA_GATTC_NOTIF_REG_MAX; i++) { - if (p_clrcb->notif_reg[i].in_use && - p_clrcb->notif_reg[i].remote_bda == remote_bda) { + if (p_clrcb->notif_reg[i].in_use && p_clrcb->notif_reg[i].remote_bda == remote_bda) { /* It's enough to get service or characteristic handle, as * clear boundaries are always around service. */ handle = p_clrcb->notif_reg[i].handle; - if (handle >= start_handle && handle <= end_handle) + if (handle >= start_handle && handle <= end_handle) { memset(&p_clrcb->notif_reg[i], 0, sizeof(tBTA_GATTC_NOTIF_REG)); + } } } } @@ -546,24 +549,24 @@ void bta_gattc_clear_notif_registration(tBTA_GATTC_SERV* p_srcb, * Returns true if success; false otherwise. * ******************************************************************************/ -bool bta_gattc_mark_bg_conn(tGATT_IF client_if, - const RawAddress& remote_bda_ptr, bool add) { +bool bta_gattc_mark_bg_conn(tGATT_IF client_if, const RawAddress& remote_bda_ptr, bool add) { tBTA_GATTC_BG_TCK* p_bg_tck = &bta_gattc_cb.bg_track[0]; uint8_t i = 0; tBTA_GATTC_CIF_MASK* p_cif_mask; for (i = 0; i < ble_acceptlist_size(); i++, p_bg_tck++) { - if (p_bg_tck->in_use && ((p_bg_tck->remote_bda == remote_bda_ptr) || - (p_bg_tck->remote_bda.IsEmpty()))) { + if (p_bg_tck->in_use && + ((p_bg_tck->remote_bda == remote_bda_ptr) || (p_bg_tck->remote_bda.IsEmpty()))) { p_cif_mask = &p_bg_tck->cif_mask; - if (add) /* mask on the cif bit */ + if (add) { /* mask on the cif bit */ *p_cif_mask |= (1 << (client_if - 1)); - else { - if (client_if != 0) + } else { + if (client_if != 0) { *p_cif_mask &= (~(1 << (client_if - 1))); - else + } else { *p_cif_mask = 0; + } } /* no BG connection for this device, make it available */ if (p_bg_tck->cif_mask == 0) { @@ -573,13 +576,11 @@ bool bta_gattc_mark_bg_conn(tGATT_IF client_if, } } if (!add) { - log::error("unable to find the bg connection mask for bd_addr={}", - remote_bda_ptr); + log::error("unable to find the bg connection mask for bd_addr={}", remote_bda_ptr); return false; } else /* adding a new device mask */ { - for (i = 0, p_bg_tck = &bta_gattc_cb.bg_track[0]; i < ble_acceptlist_size(); - i++, p_bg_tck++) { + for (i = 0, p_bg_tck = &bta_gattc_cb.bg_track[0]; i < ble_acceptlist_size(); i++, p_bg_tck++) { if (!p_bg_tck->in_use) { p_bg_tck->in_use = true; p_bg_tck->remote_bda = remote_bda_ptr; @@ -604,18 +605,18 @@ bool bta_gattc_mark_bg_conn(tGATT_IF client_if, * Returns true if success; false otherwise. * ******************************************************************************/ -bool bta_gattc_check_bg_conn(tGATT_IF client_if, const RawAddress& remote_bda, - uint8_t role) { +bool bta_gattc_check_bg_conn(tGATT_IF client_if, const RawAddress& remote_bda, uint8_t role) { tBTA_GATTC_BG_TCK* p_bg_tck = &bta_gattc_cb.bg_track[0]; uint8_t i = 0; bool is_bg_conn = false; for (i = 0; i < ble_acceptlist_size() && !is_bg_conn; i++, p_bg_tck++) { - if (p_bg_tck->in_use && (p_bg_tck->remote_bda == remote_bda || - p_bg_tck->remote_bda.IsEmpty())) { + if (p_bg_tck->in_use && + (p_bg_tck->remote_bda == remote_bda || p_bg_tck->remote_bda.IsEmpty())) { if (((p_bg_tck->cif_mask & ((tBTA_GATTC_CIF_MASK)1 << (client_if - 1))) != 0) && - role == HCI_ROLE_CENTRAL) + role == HCI_ROLE_CENTRAL) { is_bg_conn = true; + } } } return is_bg_conn; @@ -748,22 +749,20 @@ bool bta_gattc_conn_dealloc(const RawAddress& remote_bda) { tBTA_GATTC_CLCB* bta_gattc_find_int_conn_clcb(tBTA_GATTC_DATA* p_msg) { tBTA_GATTC_CLCB* p_clcb = NULL; - if (p_msg->int_conn.role == HCI_ROLE_PERIPHERAL) + if (p_msg->int_conn.role == HCI_ROLE_PERIPHERAL) { bta_gattc_conn_find_alloc(p_msg->int_conn.remote_bda); + } /* try to locate a logic channel */ - p_clcb = bta_gattc_find_clcb_by_cif(p_msg->int_conn.client_if, - p_msg->int_conn.remote_bda, + p_clcb = bta_gattc_find_clcb_by_cif(p_msg->int_conn.client_if, p_msg->int_conn.remote_bda, p_msg->int_conn.transport); if (p_clcb == NULL) { /* for a background connection or listening connection */ if (/*p_msg->int_conn.role == HCI_ROLE_PERIPHERAL || */ - bta_gattc_check_bg_conn(p_msg->int_conn.client_if, - p_msg->int_conn.remote_bda, + bta_gattc_check_bg_conn(p_msg->int_conn.client_if, p_msg->int_conn.remote_bda, p_msg->int_conn.role)) { /* allocate a new channel */ - p_clcb = bta_gattc_clcb_alloc(p_msg->int_conn.client_if, - p_msg->int_conn.remote_bda, + p_clcb = bta_gattc_clcb_alloc(p_msg->int_conn.client_if, p_msg->int_conn.remote_bda, p_msg->int_conn.transport); } } @@ -787,13 +786,11 @@ tBTA_GATTC_CLCB* bta_gattc_find_int_disconn_clcb(tBTA_GATTC_DATA* p_msg) { p_clcb = bta_gattc_find_clcb_by_conn_id(p_msg->int_conn.hdr.layer_specific); if (p_clcb == NULL) { /* connection attempt failed, send connection callback event */ - p_clcb = bta_gattc_find_clcb_by_cif(p_msg->int_conn.client_if, - p_msg->int_conn.remote_bda, + p_clcb = bta_gattc_find_clcb_by_cif(p_msg->int_conn.client_if, p_msg->int_conn.remote_bda, p_msg->int_conn.transport); } if (p_clcb == NULL) { - log::verbose("disconnection ID:{} not used by BTA", - p_msg->int_conn.hdr.layer_specific); + log::verbose("disconnection ID:{} not used by BTA", p_msg->int_conn.hdr.layer_specific); } return p_clcb; } @@ -802,22 +799,19 @@ void bta_gatt_client_dump(int fd) { std::stringstream stream; int entry_count = 0; - stream << " ->conn_track (GATT_MAX_PHY_CHANNEL=" << GATT_MAX_PHY_CHANNEL - << ")\n"; + stream << " ->conn_track (GATT_MAX_PHY_CHANNEL=" << GATT_MAX_PHY_CHANNEL << ")\n"; for (int i = 0; i < GATT_MAX_PHY_CHANNEL; i++) { tBTA_GATTC_CONN* p_conn_track = &bta_gattc_cb.conn_track[i]; if (p_conn_track->in_use) { entry_count++; - stream << " address: " - << ADDRESS_TO_LOGGABLE_STR(p_conn_track->remote_bda); + stream << " address: " << ADDRESS_TO_LOGGABLE_STR(p_conn_track->remote_bda); stream << "\n"; } } stream << " -- used: " << entry_count << "\n"; entry_count = 0; - stream << " ->bg_track (BTA_GATTC_KNOWN_SR_MAX=" << BTA_GATTC_KNOWN_SR_MAX - << ")\n"; + stream << " ->bg_track (BTA_GATTC_KNOWN_SR_MAX=" << BTA_GATTC_KNOWN_SR_MAX << ")\n"; for (int i = 0; i < BTA_GATTC_KNOWN_SR_MAX; i++) { tBTA_GATTC_BG_TCK* p_bg_track = &bta_gattc_cb.bg_track[i]; if (!p_bg_track->in_use) { @@ -838,8 +832,7 @@ void bta_gatt_client_dump(int fd) { continue; } entry_count++; - stream << " client_if: " << +p_cl_rcb->client_if - << " app uuids: " << p_cl_rcb->app_uuid + stream << " client_if: " << +p_cl_rcb->client_if << " app uuids: " << p_cl_rcb->app_uuid << " clcb_num: " << +p_cl_rcb->num_clcb; stream << "\n"; } @@ -862,20 +855,17 @@ void bta_gatt_client_dump(int fd) { stream << " -- used: " << entry_count << "\n"; entry_count = 0; - stream << " ->known_server (BTA_GATTC_KNOWN_SR_MAX=" << BTA_GATTC_KNOWN_SR_MAX - << ")\n"; + stream << " ->known_server (BTA_GATTC_KNOWN_SR_MAX=" << BTA_GATTC_KNOWN_SR_MAX << ")\n"; for (int i = 0; i < BTA_GATTC_CL_MAX; i++) { tBTA_GATTC_SERV* p_known_server = &bta_gattc_cb.known_server[i]; if (!p_known_server->in_use) { continue; } entry_count++; - stream << " server_address: " - << ADDRESS_TO_LOGGABLE_STR(p_known_server->server_bda) + stream << " server_address: " << ADDRESS_TO_LOGGABLE_STR(p_known_server->server_bda) << " mtu: " << p_known_server->mtu << " blocked_conn_id: " << loghex(p_known_server->blocked_conn_id) - << " pending_discovery: " - << p_known_server->pending_discovery.ToString() + << " pending_discovery: " << p_known_server->pending_discovery.ToString() << " num_clcb: " << +p_known_server->num_clcb << " state: " << bta_server_state_text(p_known_server->state) << " connected: " << p_known_server->connected @@ -891,7 +881,6 @@ void bta_gatt_client_dump(int fd) { stream << " -- used: " << entry_count << "\n"; entry_count = 0; - dprintf(fd, "BTA_GATTC_CB state %s \n%s\n", - bta_gattc_state_text(bta_gattc_cb.state).c_str(), + dprintf(fd, "BTA_GATTC_CB state %s \n%s\n", bta_gattc_state_text(bta_gattc_cb.state).c_str(), stream.str().c_str()); } diff --git a/system/bta/gatt/bta_gatts_act.cc b/system/bta/gatt/bta_gatts_act.cc index c7ea8a5b46e..f9759dbbdfd 100644 --- a/system/bta/gatt/bta_gatts_act.cc +++ b/system/bta/gatt/bta_gatts_act.cc @@ -40,46 +40,38 @@ using namespace bluetooth; -static void bta_gatts_nv_save_cback(bool is_saved, - tGATTS_HNDL_RANGE* p_hndl_range); -static bool bta_gatts_nv_srv_chg_cback(tGATTS_SRV_CHG_CMD cmd, - tGATTS_SRV_CHG_REQ* p_req, +static void bta_gatts_nv_save_cback(bool is_saved, tGATTS_HNDL_RANGE* p_hndl_range); +static bool bta_gatts_nv_srv_chg_cback(tGATTS_SRV_CHG_CMD cmd, tGATTS_SRV_CHG_REQ* p_req, tGATTS_SRV_CHG_RSP* p_rsp); -static void bta_gatts_conn_cback(tGATT_IF gatt_if, const RawAddress& bda, - uint16_t conn_id, bool connected, - tGATT_DISCONN_REASON reason, +static void bta_gatts_conn_cback(tGATT_IF gatt_if, const RawAddress& bda, uint16_t conn_id, + bool connected, tGATT_DISCONN_REASON reason, tBT_TRANSPORT transport); static void bta_gatts_send_request_cback(uint16_t conn_id, uint32_t trans_id, - tGATTS_REQ_TYPE req_type, - tGATTS_DATA* p_data); + tGATTS_REQ_TYPE req_type, tGATTS_DATA* p_data); static void bta_gatts_cong_cback(uint16_t conn_id, bool congested); -static void bta_gatts_phy_update_cback(tGATT_IF gatt_if, uint16_t conn_id, - uint8_t tx_phy, uint8_t rx_phy, - tGATT_STATUS status); -static void bta_gatts_conn_update_cback(tGATT_IF gatt_if, uint16_t conn_id, - uint16_t interval, uint16_t latency, - uint16_t timeout, tGATT_STATUS status); -static void bta_gatts_subrate_chg_cback(tGATT_IF gatt_if, uint16_t conn_id, - uint16_t subrate_factor, - uint16_t latency, uint16_t cont_num, - uint16_t timeout, tGATT_STATUS status); +static void bta_gatts_phy_update_cback(tGATT_IF gatt_if, uint16_t conn_id, uint8_t tx_phy, + uint8_t rx_phy, tGATT_STATUS status); +static void bta_gatts_conn_update_cback(tGATT_IF gatt_if, uint16_t conn_id, uint16_t interval, + uint16_t latency, uint16_t timeout, tGATT_STATUS status); +static void bta_gatts_subrate_chg_cback(tGATT_IF gatt_if, uint16_t conn_id, uint16_t subrate_factor, + uint16_t latency, uint16_t cont_num, uint16_t timeout, + tGATT_STATUS status); static tGATT_CBACK bta_gatts_cback = { - .p_conn_cb = bta_gatts_conn_cback, - .p_cmpl_cb = nullptr, - .p_disc_res_cb = nullptr, - .p_disc_cmpl_cb = nullptr, - .p_req_cb = bta_gatts_send_request_cback, - .p_enc_cmpl_cb = nullptr, - .p_congestion_cb = bta_gatts_cong_cback, - .p_phy_update_cb = bta_gatts_phy_update_cback, - .p_conn_update_cb = bta_gatts_conn_update_cback, - .p_subrate_chg_cb = bta_gatts_subrate_chg_cback, + .p_conn_cb = bta_gatts_conn_cback, + .p_cmpl_cb = nullptr, + .p_disc_res_cb = nullptr, + .p_disc_cmpl_cb = nullptr, + .p_req_cb = bta_gatts_send_request_cback, + .p_enc_cmpl_cb = nullptr, + .p_congestion_cb = bta_gatts_cong_cback, + .p_phy_update_cb = bta_gatts_phy_update_cback, + .p_conn_update_cb = bta_gatts_conn_update_cback, + .p_subrate_chg_cb = bta_gatts_subrate_chg_cback, }; -tGATT_APPL_INFO bta_gatts_nv_cback = {bta_gatts_nv_save_cback, - bta_gatts_nv_srv_chg_cback}; +tGATT_APPL_INFO bta_gatts_nv_cback = {bta_gatts_nv_save_cback, bta_gatts_nv_srv_chg_cback}; /******************************************************************************* * @@ -92,8 +84,7 @@ tGATT_APPL_INFO bta_gatts_nv_cback = {bta_gatts_nv_save_cback, * Returns none. * ******************************************************************************/ -static void bta_gatts_nv_save_cback(bool is_add, - tGATTS_HNDL_RANGE* p_hndl_range) {} +static void bta_gatts_nv_save_cback(bool is_add, tGATTS_HNDL_RANGE* p_hndl_range) {} /******************************************************************************* * @@ -106,8 +97,7 @@ static void bta_gatts_nv_save_cback(bool is_add, * Returns none. * ******************************************************************************/ -static bool bta_gatts_nv_srv_chg_cback(tGATTS_SRV_CHG_CMD cmd, - tGATTS_SRV_CHG_REQ* p_req, +static bool bta_gatts_nv_srv_chg_cback(tGATTS_SRV_CHG_CMD cmd, tGATTS_SRV_CHG_REQ* p_req, tGATTS_SRV_CHG_RSP* p_rsp) { return false; } @@ -205,14 +195,13 @@ void bta_gatts_register(tBTA_GATTS_CB* p_cb, tBTA_GATTS_DATA* p_msg) { p_cb->rcb[first_unuse].in_use = true; p_cb->rcb[first_unuse].p_cback = p_msg->api_reg.p_cback; p_cb->rcb[first_unuse].app_uuid = p_msg->api_reg.app_uuid; - cb_data.reg_oper.server_if = p_cb->rcb[first_unuse].gatt_if = - GATT_Register(p_msg->api_reg.app_uuid, "GattServer", &bta_gatts_cback, - p_msg->api_reg.eatt_support); + cb_data.reg_oper.server_if = p_cb->rcb[first_unuse].gatt_if = GATT_Register( + p_msg->api_reg.app_uuid, "GattServer", &bta_gatts_cback, p_msg->api_reg.eatt_support); if (!p_cb->rcb[first_unuse].gatt_if) { status = GATT_NO_RESOURCES; } else { - tBTA_GATTS_INT_START_IF* p_buf = (tBTA_GATTS_INT_START_IF*)osi_malloc( - sizeof(tBTA_GATTS_INT_START_IF)); + tBTA_GATTS_INT_START_IF* p_buf = + (tBTA_GATTS_INT_START_IF*)osi_malloc(sizeof(tBTA_GATTS_INT_START_IF)); p_buf->hdr.event = BTA_GATTS_INT_START_IF_EVT; p_buf->server_if = p_cb->rcb[first_unuse].gatt_if; @@ -223,8 +212,9 @@ void bta_gatts_register(tBTA_GATTS_CB* p_cb, tBTA_GATTS_DATA* p_msg) { } } cb_data.reg_oper.status = status; - if (p_msg->api_reg.p_cback) + if (p_msg->api_reg.p_cback) { (*p_msg->api_reg.p_cback)(BTA_GATTS_REG_EVT, &cb_data); + } } /******************************************************************************* @@ -240,8 +230,7 @@ void bta_gatts_start_if(tBTA_GATTS_CB* /* p_cb */, tBTA_GATTS_DATA* p_msg) { if (bta_gatts_find_app_rcb_by_app_if(p_msg->int_start_if.server_if)) { GATT_StartIf(p_msg->int_start_if.server_if); } else { - log::error("Unable to start app.: Unknown interface={}", - p_msg->int_start_if.server_if); + log::error("Unable to start app.: Unknown interface={}", p_msg->int_start_if.server_if); } } /******************************************************************************* @@ -263,8 +252,7 @@ void bta_gatts_deregister(tBTA_GATTS_CB* p_cb, tBTA_GATTS_DATA* p_msg) { cb_data.reg_oper.status = status; for (i = 0; i < BTA_GATTS_MAX_APP_NUM; i++) { - if (p_cb->rcb[i].in_use && - p_cb->rcb[i].gatt_if == p_msg->api_dereg.server_if) { + if (p_cb->rcb[i].in_use && p_cb->rcb[i].gatt_if == p_msg->api_dereg.server_if) { p_cback = p_cb->rcb[i].p_cback; status = GATT_SUCCESS; @@ -294,23 +282,23 @@ void bta_gatts_deregister(tBTA_GATTS_CB* p_cb, tBTA_GATTS_DATA* p_msg) { * Returns none. * ******************************************************************************/ -void bta_gatts_delete_service(tBTA_GATTS_SRVC_CB* p_srvc_cb, - tBTA_GATTS_DATA* p_msg) { +void bta_gatts_delete_service(tBTA_GATTS_SRVC_CB* p_srvc_cb, tBTA_GATTS_DATA* p_msg) { tBTA_GATTS_RCB* p_rcb = &bta_gatts_cb.rcb[p_srvc_cb->rcb_idx]; tBTA_GATTS cb_data; cb_data.srvc_oper.server_if = p_rcb->gatt_if; cb_data.srvc_oper.service_id = p_srvc_cb->service_id; - if (GATTS_DeleteService(p_rcb->gatt_if, &p_srvc_cb->service_uuid, - p_srvc_cb->service_id)) { + if (GATTS_DeleteService(p_rcb->gatt_if, &p_srvc_cb->service_uuid, p_srvc_cb->service_id)) { cb_data.srvc_oper.status = GATT_SUCCESS; memset(p_srvc_cb, 0, sizeof(tBTA_GATTS_SRVC_CB)); } else { cb_data.srvc_oper.status = GATT_ERROR; } - if (p_rcb->p_cback) (*p_rcb->p_cback)(BTA_GATTS_DELETE_EVT, &cb_data); + if (p_rcb->p_cback) { + (*p_rcb->p_cback)(BTA_GATTS_DELETE_EVT, &cb_data); + } } /******************************************************************************* @@ -322,8 +310,7 @@ void bta_gatts_delete_service(tBTA_GATTS_SRVC_CB* p_srvc_cb, * Returns none. * ******************************************************************************/ -void bta_gatts_stop_service(tBTA_GATTS_SRVC_CB* p_srvc_cb, - tBTA_GATTS_DATA* /* p_msg */) { +void bta_gatts_stop_service(tBTA_GATTS_SRVC_CB* p_srvc_cb, tBTA_GATTS_DATA* /* p_msg */) { tBTA_GATTS_RCB* p_rcb = &bta_gatts_cb.rcb[p_srvc_cb->rcb_idx]; tBTA_GATTS cb_data; @@ -333,7 +320,9 @@ void bta_gatts_stop_service(tBTA_GATTS_SRVC_CB* p_srvc_cb, cb_data.srvc_oper.status = GATT_SUCCESS; log::error("service_id={}", p_srvc_cb->service_id); - if (p_rcb->p_cback) (*p_rcb->p_cback)(BTA_GATTS_STOP_EVT, &cb_data); + if (p_rcb->p_cback) { + (*p_rcb->p_cback)(BTA_GATTS_STOP_EVT, &cb_data); + } } /******************************************************************************* * @@ -346,8 +335,7 @@ void bta_gatts_stop_service(tBTA_GATTS_SRVC_CB* p_srvc_cb, ******************************************************************************/ void bta_gatts_send_rsp(tBTA_GATTS_CB* /* p_cb */, tBTA_GATTS_DATA* p_msg) { if (GATTS_SendRsp(p_msg->api_rsp.hdr.layer_specific, p_msg->api_rsp.trans_id, - p_msg->api_rsp.status, - (tGATTS_RSP*)p_msg->api_rsp.p_rsp) != GATT_SUCCESS) { + p_msg->api_rsp.status, (tGATTS_RSP*)p_msg->api_rsp.p_rsp) != GATT_SUCCESS) { log::error("Sending response failed"); } } @@ -369,23 +357,22 @@ void bta_gatts_indicate_handle(tBTA_GATTS_CB* p_cb, tBTA_GATTS_DATA* p_msg) { tBT_TRANSPORT transport; tBTA_GATTS cb_data; - p_srvc_cb = - bta_gatts_find_srvc_cb_by_attr_id(p_cb, p_msg->api_indicate.attr_id); + p_srvc_cb = bta_gatts_find_srvc_cb_by_attr_id(p_cb, p_msg->api_indicate.attr_id); if (p_srvc_cb) { - if (GATT_GetConnectionInfor(p_msg->api_indicate.hdr.layer_specific, - &gatt_if, remote_bda, &transport)) { + if (GATT_GetConnectionInfor(p_msg->api_indicate.hdr.layer_specific, &gatt_if, remote_bda, + &transport)) { p_rcb = bta_gatts_find_app_rcb_by_app_if(gatt_if); - if (p_msg->api_indicate.need_confirm) - - status = GATTS_HandleValueIndication( - p_msg->api_indicate.hdr.layer_specific, p_msg->api_indicate.attr_id, - p_msg->api_indicate.len, p_msg->api_indicate.value); - else - status = GATTS_HandleValueNotification( - p_msg->api_indicate.hdr.layer_specific, p_msg->api_indicate.attr_id, - p_msg->api_indicate.len, p_msg->api_indicate.value); + if (p_msg->api_indicate.need_confirm) { + status = GATTS_HandleValueIndication(p_msg->api_indicate.hdr.layer_specific, + p_msg->api_indicate.attr_id, p_msg->api_indicate.len, + p_msg->api_indicate.value); + } else { + status = GATTS_HandleValueNotification(p_msg->api_indicate.hdr.layer_specific, + p_msg->api_indicate.attr_id, p_msg->api_indicate.len, + p_msg->api_indicate.value); + } /* if over BR_EDR, inform PM for mode change */ if (transport == BT_TRANSPORT_BR_EDR) { @@ -397,16 +384,15 @@ void bta_gatts_indicate_handle(tBTA_GATTS_CB* p_cb, tBTA_GATTS_DATA* p_msg) { p_msg->api_indicate.hdr.layer_specific); } - if ((status != GATT_SUCCESS || !p_msg->api_indicate.need_confirm) && - p_rcb && p_cb->rcb[p_srvc_cb->rcb_idx].p_cback) { + if ((status != GATT_SUCCESS || !p_msg->api_indicate.need_confirm) && p_rcb && + p_cb->rcb[p_srvc_cb->rcb_idx].p_cback) { cb_data.req_data.status = status; cb_data.req_data.conn_id = p_msg->api_indicate.hdr.layer_specific; (*p_rcb->p_cback)(BTA_GATTS_CONF_EVT, &cb_data); } } else { - log::error("Not an registered servce attribute ID: 0x{:x}", - p_msg->api_indicate.attr_id); + log::error("Not an registered servce attribute ID: 0x{:x}", p_msg->api_indicate.attr_id); } } @@ -428,22 +414,19 @@ void bta_gatts_open(tBTA_GATTS_CB* /* p_cb */, tBTA_GATTS_DATA* p_msg) { if (p_rcb != NULL) { /* should always get the connection ID */ bool success = false; - if (com::android::bluetooth::flags:: - ble_gatt_server_use_address_type_in_connection()) { + if (com::android::bluetooth::flags::ble_gatt_server_use_address_type_in_connection()) { success = GATT_Connect(p_rcb->gatt_if, p_msg->api_open.remote_bda, - p_msg->api_open.remote_addr_type, - p_msg->api_open.connection_type, + p_msg->api_open.remote_addr_type, p_msg->api_open.connection_type, p_msg->api_open.transport, false); } else { success = GATT_Connect(p_rcb->gatt_if, p_msg->api_open.remote_bda, - p_msg->api_open.connection_type, - p_msg->api_open.transport, false); + p_msg->api_open.connection_type, p_msg->api_open.transport, false); } if (success) { status = GATT_SUCCESS; - if (GATT_GetConnIdIfConnected(p_rcb->gatt_if, p_msg->api_open.remote_bda, - &conn_id, p_msg->api_open.transport)) { + if (GATT_GetConnIdIfConnected(p_rcb->gatt_if, p_msg->api_open.remote_bda, &conn_id, + p_msg->api_open.transport)) { status = GATT_ALREADY_OPEN; } } @@ -504,10 +487,9 @@ void bta_gatts_close(tBTA_GATTS_CB* /* p_cb */, tBTA_GATTS_DATA* p_msg) { RawAddress remote_bda; tBT_TRANSPORT transport; - if (GATT_GetConnectionInfor(p_msg->hdr.layer_specific, &gatt_if, remote_bda, - &transport)) { - log::debug("Disconnecting gatt_if={}, remote_bda={}, transport={}", gatt_if, - remote_bda, transport); + if (GATT_GetConnectionInfor(p_msg->hdr.layer_specific, &gatt_if, remote_bda, &transport)) { + log::debug("Disconnecting gatt_if={}, remote_bda={}, transport={}", gatt_if, remote_bda, + transport); status = GATT_Disconnect(p_msg->hdr.layer_specific); if (status != GATT_SUCCESS) { log::error("fail conn_id={}", p_msg->hdr.layer_specific); @@ -540,8 +522,7 @@ void bta_gatts_close(tBTA_GATTS_CB* /* p_cb */, tBTA_GATTS_DATA* p_msg) { * ******************************************************************************/ static void bta_gatts_send_request_cback(uint16_t conn_id, uint32_t trans_id, - tGATTS_REQ_TYPE req_type, - tGATTS_DATA* p_data) { + tGATTS_REQ_TYPE req_type, tGATTS_DATA* p_data) { tBTA_GATTS cb_data; tBTA_GATTS_RCB* p_rcb; tGATT_IF gatt_if; @@ -549,12 +530,10 @@ static void bta_gatts_send_request_cback(uint16_t conn_id, uint32_t trans_id, memset(&cb_data, 0, sizeof(tBTA_GATTS)); - if (GATT_GetConnectionInfor(conn_id, &gatt_if, cb_data.req_data.remote_bda, - &transport)) { + if (GATT_GetConnectionInfor(conn_id, &gatt_if, cb_data.req_data.remote_bda, &transport)) { p_rcb = bta_gatts_find_app_rcb_by_app_if(gatt_if); - log::verbose("conn_id=0x{:x}, trans_id={}, req_type={}", conn_id, trans_id, - req_type); + log::verbose("conn_id=0x{:x}, trans_id={}, req_type={}", conn_id, trans_id, req_type); if (p_rcb && p_rcb->p_cback) { /* if over BR_EDR, inform PM for mode change */ @@ -585,31 +564,31 @@ static void bta_gatts_send_request_cback(uint16_t conn_id, uint32_t trans_id, * Returns none. * ******************************************************************************/ -static void bta_gatts_conn_cback(tGATT_IF gatt_if, const RawAddress& bdaddr, - uint16_t conn_id, bool connected, - tGATT_DISCONN_REASON, - tBT_TRANSPORT transport) { +static void bta_gatts_conn_cback(tGATT_IF gatt_if, const RawAddress& bdaddr, uint16_t conn_id, + bool connected, tGATT_DISCONN_REASON, tBT_TRANSPORT transport) { tBTA_GATTS cb_data; uint8_t evt = connected ? BTA_GATTS_CONNECT_EVT : BTA_GATTS_DISCONNECT_EVT; tBTA_GATTS_RCB* p_reg; - log::verbose("bda={} gatt_if= {}, conn_id=0x{:x} connected={}", bdaddr, - gatt_if, conn_id, connected); + log::verbose("bda={} gatt_if= {}, conn_id=0x{:x} connected={}", bdaddr, gatt_if, conn_id, + connected); - if (connected) + if (connected) { btif_debug_conn_state(bdaddr, BTIF_DEBUG_CONNECTED, GATT_CONN_OK); - else + } else { btif_debug_conn_state(bdaddr, BTIF_DEBUG_DISCONNECTED, GATT_CONN_OK); + } p_reg = bta_gatts_find_app_rcb_by_app_if(gatt_if); if (p_reg && p_reg->p_cback) { /* there is no RM for GATT */ if (transport == BT_TRANSPORT_BR_EDR) { - if (connected) + if (connected) { bta_sys_conn_open(BTA_ID_GATTS, BTA_ALL_APP_ID, bdaddr); - else + } else { bta_sys_conn_close(BTA_ID_GATTS, BTA_ALL_APP_ID, bdaddr); + } } cb_data.conn.conn_id = conn_id; @@ -622,9 +601,8 @@ static void bta_gatts_conn_cback(tGATT_IF gatt_if, const RawAddress& bdaddr, } } -static void bta_gatts_phy_update_cback(tGATT_IF gatt_if, uint16_t conn_id, - uint8_t tx_phy, uint8_t rx_phy, - tGATT_STATUS status) { +static void bta_gatts_phy_update_cback(tGATT_IF gatt_if, uint16_t conn_id, uint8_t tx_phy, + uint8_t rx_phy, tGATT_STATUS status) { tBTA_GATTS_RCB* p_reg = bta_gatts_find_app_rcb_by_app_if(gatt_if); if (!p_reg || !p_reg->p_cback) { log::error("server_if={} not found", gatt_if); @@ -640,9 +618,8 @@ static void bta_gatts_phy_update_cback(tGATT_IF gatt_if, uint16_t conn_id, (*p_reg->p_cback)(BTA_GATTS_PHY_UPDATE_EVT, &cb_data); } -static void bta_gatts_conn_update_cback(tGATT_IF gatt_if, uint16_t conn_id, - uint16_t interval, uint16_t latency, - uint16_t timeout, tGATT_STATUS status) { +static void bta_gatts_conn_update_cback(tGATT_IF gatt_if, uint16_t conn_id, uint16_t interval, + uint16_t latency, uint16_t timeout, tGATT_STATUS status) { tBTA_GATTS_RCB* p_reg = bta_gatts_find_app_rcb_by_app_if(gatt_if); if (!p_reg || !p_reg->p_cback) { log::error("server_if={} not found", gatt_if); @@ -659,10 +636,9 @@ static void bta_gatts_conn_update_cback(tGATT_IF gatt_if, uint16_t conn_id, (*p_reg->p_cback)(BTA_GATTS_CONN_UPDATE_EVT, &cb_data); } -static void bta_gatts_subrate_chg_cback(tGATT_IF gatt_if, uint16_t conn_id, - uint16_t subrate_factor, - uint16_t latency, uint16_t cont_num, - uint16_t timeout, tGATT_STATUS status) { +static void bta_gatts_subrate_chg_cback(tGATT_IF gatt_if, uint16_t conn_id, uint16_t subrate_factor, + uint16_t latency, uint16_t cont_num, uint16_t timeout, + tGATT_STATUS status) { tBTA_GATTS_RCB* p_reg = bta_gatts_find_app_rcb_by_app_if(gatt_if); if (!p_reg || !p_reg->p_cback) { log::error("server_if={} not found", gatt_if); @@ -695,8 +671,7 @@ static void bta_gatts_cong_cback(uint16_t conn_id, bool congested) { tBT_TRANSPORT transport; tBTA_GATTS cb_data; - if (GATT_GetConnectionInfor(conn_id, &gatt_if, cb_data.req_data.remote_bda, - &transport)) { + if (GATT_GetConnectionInfor(conn_id, &gatt_if, cb_data.req_data.remote_bda, &transport)) { p_rcb = bta_gatts_find_app_rcb_by_app_if(gatt_if); if (p_rcb && p_rcb->p_cback) { diff --git a/system/bta/gatt/bta_gatts_api.cc b/system/bta/gatt/bta_gatts_api.cc index fbcb67aea47..7204ef36f27 100644 --- a/system/bta/gatt/bta_gatts_api.cc +++ b/system/bta/gatt/bta_gatts_api.cc @@ -45,8 +45,7 @@ using namespace bluetooth; * Constants ****************************************************************************/ -static const tBTA_SYS_REG bta_gatts_reg = {bta_gatts_hdl_event, - BTA_GATTS_Disable}; +static const tBTA_SYS_REG bta_gatts_reg = {bta_gatts_hdl_event, BTA_GATTS_Disable}; /******************************************************************************* * @@ -78,20 +77,20 @@ void BTA_GATTS_Disable(void) { * Description This function is called to register application callbacks * with BTA GATTS module. * - * Parameters p_app_uuid - applicaiton UUID + * Parameters p_app_uuid - application UUID * p_cback - pointer to the application callback function. * * Returns None * ******************************************************************************/ -void BTA_GATTS_AppRegister(const bluetooth::Uuid& app_uuid, - tBTA_GATTS_CBACK* p_cback, bool eatt_support) { - tBTA_GATTS_API_REG* p_buf = - (tBTA_GATTS_API_REG*)osi_malloc(sizeof(tBTA_GATTS_API_REG)); +void BTA_GATTS_AppRegister(const bluetooth::Uuid& app_uuid, tBTA_GATTS_CBACK* p_cback, + bool eatt_support) { + tBTA_GATTS_API_REG* p_buf = (tBTA_GATTS_API_REG*)osi_malloc(sizeof(tBTA_GATTS_API_REG)); /* register with BTA system manager */ - if (!bta_sys_is_register(BTA_ID_GATTS)) + if (!bta_sys_is_register(BTA_ID_GATTS)) { bta_sys_register(BTA_ID_GATTS, &bta_gatts_reg); + } p_buf->hdr.event = BTA_GATTS_API_REG_EVT; p_buf->app_uuid = app_uuid; @@ -113,8 +112,7 @@ void BTA_GATTS_AppRegister(const bluetooth::Uuid& app_uuid, * ******************************************************************************/ void BTA_GATTS_AppDeregister(tGATT_IF server_if) { - tBTA_GATTS_API_DEREG* p_buf = - (tBTA_GATTS_API_DEREG*)osi_malloc(sizeof(tBTA_GATTS_API_DEREG)); + tBTA_GATTS_API_DEREG* p_buf = (tBTA_GATTS_API_DEREG*)osi_malloc(sizeof(tBTA_GATTS_API_DEREG)); p_buf->hdr.event = BTA_GATTS_API_DEREG_EVT; p_buf->server_if = server_if; @@ -122,11 +120,9 @@ void BTA_GATTS_AppDeregister(tGATT_IF server_if) { bta_sys_sendmsg(p_buf); } -void bta_gatts_add_service_impl(tGATT_IF server_if, - std::vector service, +void bta_gatts_add_service_impl(tGATT_IF server_if, std::vector service, BTA_GATTS_AddServiceCb cb) { - uint8_t rcb_idx = - bta_gatts_find_app_rcb_idx_by_app_if(&bta_gatts_cb, server_if); + uint8_t rcb_idx = bta_gatts_find_app_rcb_idx_by_app_if(&bta_gatts_cb, server_if); log::info("rcb_idx={}", rcb_idx); @@ -141,8 +137,7 @@ void bta_gatts_add_service_impl(tGATT_IF server_if, return; } - tGATT_STATUS status = - GATTS_AddService(server_if, service.data(), service.size()); + tGATT_STATUS status = GATTS_AddService(server_if, service.data(), service.size()); if (status != GATT_SERVICE_STARTED) { memset(&bta_gatts_cb.srvc_cb[srvc_idx], 0, sizeof(tBTA_GATTS_SRVC_CB)); log::error("service creation failed."); @@ -175,12 +170,10 @@ void bta_gatts_add_service_impl(tGATT_IF server_if, * service cannot be added. * ******************************************************************************/ -void BTA_GATTS_AddService(tGATT_IF server_if, - std::vector service, +void BTA_GATTS_AddService(tGATT_IF server_if, std::vector service, BTA_GATTS_AddServiceCb cb) { - do_in_main_thread(FROM_HERE, - base::BindOnce(&bta_gatts_add_service_impl, server_if, - std::move(service), std::move(cb))); + do_in_main_thread(FROM_HERE, base::BindOnce(&bta_gatts_add_service_impl, server_if, + std::move(service), std::move(cb))); } /******************************************************************************* @@ -241,17 +234,15 @@ void BTA_GATTS_StopService(uint16_t service_id) { * Returns None * ******************************************************************************/ -void BTA_GATTS_HandleValueIndication(uint16_t conn_id, uint16_t attr_id, - std::vector value, +void BTA_GATTS_HandleValueIndication(uint16_t conn_id, uint16_t attr_id, std::vector value, bool need_confirm) { - if (value.size() > sizeof(tBTA_GATTS_API_INDICATION::value)) { log::error("data to indicate is too long"); return; } tBTA_GATTS_API_INDICATION* p_buf = - (tBTA_GATTS_API_INDICATION*)osi_calloc(sizeof(tBTA_GATTS_API_INDICATION)); + (tBTA_GATTS_API_INDICATION*)osi_calloc(sizeof(tBTA_GATTS_API_INDICATION)); p_buf->hdr.event = BTA_GATTS_API_INDICATION_EVT; p_buf->hdr.layer_specific = conn_id; @@ -312,11 +303,9 @@ void BTA_GATTS_SendRsp(uint16_t conn_id, uint32_t trans_id, tGATT_STATUS status, * Returns void * ******************************************************************************/ -void BTA_GATTS_Open(tGATT_IF server_if, const RawAddress& remote_bda, - tBLE_ADDR_TYPE addr_type, bool is_direct, - tBT_TRANSPORT transport) { - tBTA_GATTS_API_OPEN* p_buf = - (tBTA_GATTS_API_OPEN*)osi_malloc(sizeof(tBTA_GATTS_API_OPEN)); +void BTA_GATTS_Open(tGATT_IF server_if, const RawAddress& remote_bda, tBLE_ADDR_TYPE addr_type, + bool is_direct, tBT_TRANSPORT transport) { + tBTA_GATTS_API_OPEN* p_buf = (tBTA_GATTS_API_OPEN*)osi_malloc(sizeof(tBTA_GATTS_API_OPEN)); p_buf->hdr.event = BTA_GATTS_API_OPEN_EVT; p_buf->server_if = server_if; @@ -346,10 +335,9 @@ void BTA_GATTS_Open(tGATT_IF server_if, const RawAddress& remote_bda, * Returns void * ******************************************************************************/ -void BTA_GATTS_CancelOpen(tGATT_IF server_if, const RawAddress& remote_bda, - bool is_direct) { - tBTA_GATTS_API_CANCEL_OPEN* p_buf = (tBTA_GATTS_API_CANCEL_OPEN*)osi_malloc( - sizeof(tBTA_GATTS_API_CANCEL_OPEN)); +void BTA_GATTS_CancelOpen(tGATT_IF server_if, const RawAddress& remote_bda, bool is_direct) { + tBTA_GATTS_API_CANCEL_OPEN* p_buf = + (tBTA_GATTS_API_CANCEL_OPEN*)osi_malloc(sizeof(tBTA_GATTS_API_CANCEL_OPEN)); p_buf->hdr.event = BTA_GATTS_API_CANCEL_OPEN_EVT; p_buf->server_if = server_if; diff --git a/system/bta/gatt/bta_gatts_int.h b/system/bta/gatt/bta_gatts_int.h index 578f9c62367..91161ac8a95 100644 --- a/system/bta/gatt/bta_gatts_int.h +++ b/system/bta/gatt/bta_gatts_int.h @@ -146,7 +146,7 @@ typedef struct { /* service registration control block */ typedef struct { bluetooth::Uuid service_uuid; /* service UUID */ - uint16_t service_id; /* service start handle */ + uint16_t service_id; /* service start handle */ uint8_t rcb_idx; uint8_t idx; /* self index of serviec CB */ bool in_use; @@ -176,10 +176,8 @@ void bta_gatts_api_enable(tBTA_GATTS_CB* p_cb, tBTA_GATTS_DATA* p_data); void bta_gatts_register(tBTA_GATTS_CB* p_cb, tBTA_GATTS_DATA* p_msg); void bta_gatts_start_if(tBTA_GATTS_CB* p_cb, tBTA_GATTS_DATA* p_msg); void bta_gatts_deregister(tBTA_GATTS_CB* p_cb, tBTA_GATTS_DATA* p_msg); -void bta_gatts_delete_service(tBTA_GATTS_SRVC_CB* p_srvc_cb, - tBTA_GATTS_DATA* p_msg); -void bta_gatts_stop_service(tBTA_GATTS_SRVC_CB* p_srvc_cb, - tBTA_GATTS_DATA* p_msg); +void bta_gatts_delete_service(tBTA_GATTS_SRVC_CB* p_srvc_cb, tBTA_GATTS_DATA* p_msg); +void bta_gatts_stop_service(tBTA_GATTS_SRVC_CB* p_srvc_cb, tBTA_GATTS_DATA* p_msg); void bta_gatts_send_rsp(tBTA_GATTS_CB* p_cb, tBTA_GATTS_DATA* p_msg); void bta_gatts_indicate_handle(tBTA_GATTS_CB* p_cb, tBTA_GATTS_DATA* p_msg); @@ -189,12 +187,9 @@ void bta_gatts_cancel_open(tBTA_GATTS_CB* p_cb, tBTA_GATTS_DATA* p_msg); void bta_gatts_close(tBTA_GATTS_CB* p_cb, tBTA_GATTS_DATA* p_msg); tBTA_GATTS_RCB* bta_gatts_find_app_rcb_by_app_if(tGATT_IF server_if); -uint8_t bta_gatts_find_app_rcb_idx_by_app_if(tBTA_GATTS_CB* p_cb, - tGATT_IF server_if); +uint8_t bta_gatts_find_app_rcb_idx_by_app_if(tBTA_GATTS_CB* p_cb, tGATT_IF server_if); uint8_t bta_gatts_alloc_srvc_cb(tBTA_GATTS_CB* p_cb, uint8_t rcb_idx); -tBTA_GATTS_SRVC_CB* bta_gatts_find_srvc_cb_by_srvc_id(tBTA_GATTS_CB* p_cb, - uint16_t service_id); -tBTA_GATTS_SRVC_CB* bta_gatts_find_srvc_cb_by_attr_id(tBTA_GATTS_CB* p_cb, - uint16_t attr_id); +tBTA_GATTS_SRVC_CB* bta_gatts_find_srvc_cb_by_srvc_id(tBTA_GATTS_CB* p_cb, uint16_t service_id); +tBTA_GATTS_SRVC_CB* bta_gatts_find_srvc_cb_by_attr_id(tBTA_GATTS_CB* p_cb, uint16_t attr_id); #endif /* BTA_GATTS_INT_H */ diff --git a/system/bta/gatt/bta_gatts_main.cc b/system/bta/gatt/bta_gatts_main.cc index 853c63ad2f2..da0ff3ca100 100644 --- a/system/bta/gatt/bta_gatts_main.cc +++ b/system/bta/gatt/bta_gatts_main.cc @@ -85,24 +85,26 @@ bool bta_gatts_hdl_event(const BT_HDR_RIGID* p_msg) { case BTA_GATTS_API_DEL_SRVC_EVT: { tBTA_GATTS_SRVC_CB* p_srvc_cb = bta_gatts_find_srvc_cb_by_srvc_id( - p_cb, ((tBTA_GATTS_DATA*)p_msg)->api_add_service.hdr.layer_specific); + p_cb, ((tBTA_GATTS_DATA*)p_msg)->api_add_service.hdr.layer_specific); - if (p_srvc_cb != NULL) + if (p_srvc_cb != NULL) { bta_gatts_delete_service(p_srvc_cb, (tBTA_GATTS_DATA*)p_msg); - else + } else { log::error("can't delete service - no srvc_cb found"); + } break; } case BTA_GATTS_API_STOP_SRVC_EVT: { tBTA_GATTS_SRVC_CB* p_srvc_cb = bta_gatts_find_srvc_cb_by_srvc_id( - p_cb, ((tBTA_GATTS_DATA*)p_msg)->api_add_service.hdr.layer_specific); + p_cb, ((tBTA_GATTS_DATA*)p_msg)->api_add_service.hdr.layer_specific); - if (p_srvc_cb != NULL) + if (p_srvc_cb != NULL) { bta_gatts_stop_service(p_srvc_cb, (tBTA_GATTS_DATA*)p_msg); - else + } else { log::error("can't stop service - no srvc_cb found"); + } break; } @@ -115,5 +117,5 @@ bool bta_gatts_hdl_event(const BT_HDR_RIGID* p_msg) { break; } - return (true); + return true; } diff --git a/system/bta/gatt/bta_gatts_queue.cc b/system/bta/gatt/bta_gatts_queue.cc index 525e7eb14d7..32ab5d8b327 100644 --- a/system/bta/gatt/bta_gatts_queue.cc +++ b/system/bta/gatt/bta_gatts_queue.cc @@ -31,8 +31,7 @@ using namespace bluetooth; constexpr uint8_t GATT_NOTIFY = 1; -std::unordered_map> - BtaGattServerQueue::gatts_op_queue; +std::unordered_map> BtaGattServerQueue::gatts_op_queue; std::unordered_set BtaGattServerQueue::gatts_op_queue_executing; std::unordered_map BtaGattServerQueue::congestion_queue; @@ -52,8 +51,7 @@ void BtaGattServerQueue::gatts_execute_next_op(uint16_t conn_id) { if (ptr != congestion_queue.end()) { bool is_congested = ptr->second; - log::verbose("congestion queue exist, conn_id: {}, is_congested: {}", - conn_id, is_congested); + log::verbose("congestion queue exist, conn_id: {}, is_congested: {}", conn_id, is_congested); if (is_congested) { log::verbose("lower layer is congested"); return; @@ -81,8 +79,7 @@ void BtaGattServerQueue::gatts_execute_next_op(uint16_t conn_id) { log::verbose("op.type={}, attr_id={}", op.type, op.attr_id); if (op.type == GATT_NOTIFY) { - BTA_GATTS_HandleValueIndication(conn_id, op.attr_id, op.value, - op.need_confirm); + BTA_GATTS_HandleValueIndication(conn_id, op.attr_id, op.value, op.need_confirm); gatts_op_queue_executing.insert(conn_id); } } @@ -95,13 +92,9 @@ void BtaGattServerQueue::Clean(uint16_t conn_id) { } void BtaGattServerQueue::SendNotification(uint16_t conn_id, uint16_t handle, - std::vector value, - bool need_confirm) { - gatts_op_queue[conn_id].emplace_back( - gatts_operation{.type = GATT_NOTIFY, - .attr_id = handle, - .value = value, - .need_confirm = need_confirm}); + std::vector value, bool need_confirm) { + gatts_op_queue[conn_id].emplace_back(gatts_operation{ + .type = GATT_NOTIFY, .attr_id = handle, .value = value, .need_confirm = need_confirm}); gatts_execute_next_op(conn_id); } diff --git a/system/bta/gatt/bta_gatts_utils.cc b/system/bta/gatt/bta_gatts_utils.cc index 783d42ba527..d8d22c5aea1 100644 --- a/system/bta/gatt/bta_gatts_utils.cc +++ b/system/bta/gatt/bta_gatts_utils.cc @@ -66,9 +66,10 @@ tBTA_GATTS_RCB* bta_gatts_find_app_rcb_by_app_if(tGATT_IF server_if) { uint8_t i; tBTA_GATTS_RCB* p_reg; - for (i = 0, p_reg = bta_gatts_cb.rcb; i < BTA_GATTS_MAX_APP_NUM; - i++, p_reg++) { - if (p_reg->in_use && p_reg->gatt_if == server_if) return p_reg; + for (i = 0, p_reg = bta_gatts_cb.rcb; i < BTA_GATTS_MAX_APP_NUM; i++, p_reg++) { + if (p_reg->in_use && p_reg->gatt_if == server_if) { + return p_reg; + } } return NULL; } @@ -84,12 +85,13 @@ tBTA_GATTS_RCB* bta_gatts_find_app_rcb_by_app_if(tGATT_IF server_if) { * ******************************************************************************/ -uint8_t bta_gatts_find_app_rcb_idx_by_app_if(tBTA_GATTS_CB* p_cb, - tGATT_IF server_if) { +uint8_t bta_gatts_find_app_rcb_idx_by_app_if(tBTA_GATTS_CB* p_cb, tGATT_IF server_if) { uint8_t i; for (i = 0; i < BTA_GATTS_MAX_APP_NUM; i++) { - if (p_cb->rcb[i].in_use && p_cb->rcb[i].gatt_if == server_if) return i; + if (p_cb->rcb[i].in_use && p_cb->rcb[i].gatt_if == server_if) { + return i; + } } return BTA_GATTS_INVALID_APP; } @@ -102,8 +104,7 @@ uint8_t bta_gatts_find_app_rcb_idx_by_app_if(tBTA_GATTS_CB* p_cb, * Returns pointer to the rcb. * ******************************************************************************/ -tBTA_GATTS_SRVC_CB* bta_gatts_find_srvc_cb_by_srvc_id(tBTA_GATTS_CB* p_cb, - uint16_t service_id) { +tBTA_GATTS_SRVC_CB* bta_gatts_find_srvc_cb_by_srvc_id(tBTA_GATTS_CB* p_cb, uint16_t service_id) { uint8_t i; log::verbose("service_id={}", service_id); for (i = 0; i < BTA_GATTS_MAX_SRVC_NUM; i++) { @@ -123,23 +124,19 @@ tBTA_GATTS_SRVC_CB* bta_gatts_find_srvc_cb_by_srvc_id(tBTA_GATTS_CB* p_cb, * Returns pointer to the rcb. * ******************************************************************************/ -tBTA_GATTS_SRVC_CB* bta_gatts_find_srvc_cb_by_attr_id(tBTA_GATTS_CB* p_cb, - uint16_t attr_id) { +tBTA_GATTS_SRVC_CB* bta_gatts_find_srvc_cb_by_attr_id(tBTA_GATTS_CB* p_cb, uint16_t attr_id) { uint8_t i; for (i = 0; i < (BTA_GATTS_MAX_SRVC_NUM); i++) { if (/* middle service */ (i < (BTA_GATTS_MAX_SRVC_NUM - 1) && p_cb->srvc_cb[i].in_use && - p_cb->srvc_cb[i + 1].in_use && - attr_id >= p_cb->srvc_cb[i].service_id && + p_cb->srvc_cb[i + 1].in_use && attr_id >= p_cb->srvc_cb[i].service_id && attr_id < p_cb->srvc_cb[i + 1].service_id) || /* last active service */ (i < (BTA_GATTS_MAX_SRVC_NUM - 1) && p_cb->srvc_cb[i].in_use && - !p_cb->srvc_cb[i + 1].in_use && - attr_id >= p_cb->srvc_cb[i].service_id) || + !p_cb->srvc_cb[i + 1].in_use && attr_id >= p_cb->srvc_cb[i].service_id) || /* last service incb */ - (i == (BTA_GATTS_MAX_SRVC_NUM - 1) && - attr_id >= p_cb->srvc_cb[i].service_id)) { + (i == (BTA_GATTS_MAX_SRVC_NUM - 1) && attr_id >= p_cb->srvc_cb[i].service_id)) { return &p_cb->srvc_cb[i]; } } diff --git a/system/bta/gatt/database.cc b/system/bta/gatt/database.cc index a7548d23e09..4f38651edbe 100644 --- a/system/bta/gatt/database.cc +++ b/system/bta/gatt/database.cc @@ -40,8 +40,7 @@ const Uuid PRIMARY_SERVICE = Uuid::From16Bit(GATT_UUID_PRI_SERVICE); const Uuid SECONDARY_SERVICE = Uuid::From16Bit(GATT_UUID_SEC_SERVICE); const Uuid INCLUDE = Uuid::From16Bit(GATT_UUID_INCLUDE_SERVICE); const Uuid CHARACTERISTIC = Uuid::From16Bit(GATT_UUID_CHAR_DECLARE); -const Uuid CHARACTERISTIC_EXTENDED_PROPERTIES = - Uuid::From16Bit(GATT_UUID_CHAR_EXT_PROP); +const Uuid CHARACTERISTIC_EXTENDED_PROPERTIES = Uuid::From16Bit(GATT_UUID_CHAR_EXT_PROP); bool HandleInRange(const Service& svc, uint16_t handle) { return handle >= svc.handle && handle <= svc.end_handle; @@ -55,8 +54,9 @@ static size_t UuidSize(const Uuid& uuid) { Service* FindService(std::list& services, uint16_t handle) { for (Service& service : services) { - if (handle >= service.handle && handle <= service.end_handle) + if (handle >= service.handle && handle <= service.end_handle) { return &service; + } } return nullptr; @@ -67,25 +67,21 @@ std::string Database::ToString() const { for (const Service& service : services) { tmp << "Service: handle=" << loghex(service.handle) - << ", end_handle=" << loghex(service.end_handle) - << ", uuid=" << service.uuid << "\n"; + << ", end_handle=" << loghex(service.end_handle) << ", uuid=" << service.uuid << "\n"; for (const auto& is : service.included_services) { tmp << "\t Included service: handle=" << loghex(is.handle) << ", start_handle=" << loghex(is.start_handle) - << ", end_handle=" << loghex(is.end_handle) << ", uuid=" << is.uuid - << "\n"; + << ", end_handle=" << loghex(is.end_handle) << ", uuid=" << is.uuid << "\n"; } for (const Characteristic& c : service.characteristics) { - tmp << "\t Characteristic: declaration_handle=" - << loghex(c.declaration_handle) + tmp << "\t Characteristic: declaration_handle=" << loghex(c.declaration_handle) << ", value_handle=" << loghex(c.value_handle) << ", uuid=" << c.uuid << ", prop=" << loghex(c.properties) << "\n"; for (const Descriptor& d : c.descriptors) { - tmp << "\t\t Descriptor: handle=" << loghex(d.handle) - << ", uuid=" << d.uuid << "\n"; + tmp << "\t\t Descriptor: handle=" << loghex(d.handle) << ", uuid=" << d.uuid << "\n"; } } } @@ -95,14 +91,15 @@ std::string Database::ToString() const { std::vector Database::Serialize() const { std::vector nv_attr; - if (services.empty()) return std::vector(); + if (services.empty()) { + return std::vector(); + } for (const Service& service : services) { // TODO: add constructor to NV_ATTR, use emplace_back nv_attr.push_back({service.handle, service.is_primary ? PRIMARY_SERVICE : SECONDARY_SERVICE, - {.service = {.uuid = service.uuid, - .end_handle = service.end_handle}}}); + {.service = {.uuid = service.uuid, .end_handle = service.end_handle}}}); } for (const Service& service : services) { @@ -115,19 +112,18 @@ std::vector Database::Serialize() const { } for (const Characteristic& charac : service.characteristics) { - nv_attr.push_back( - {charac.declaration_handle, - CHARACTERISTIC, - {.characteristic = {.properties = charac.properties, - .value_handle = charac.value_handle, - .uuid = charac.uuid}}}); + nv_attr.push_back({charac.declaration_handle, + CHARACTERISTIC, + {.characteristic = {.properties = charac.properties, + .value_handle = charac.value_handle, + .uuid = charac.uuid}}}); for (const Descriptor& desc : charac.descriptors) { if (desc.uuid == CHARACTERISTIC_EXTENDED_PROPERTIES) { nv_attr.push_back({desc.handle, desc.uuid, {.characteristic_extended_properties = - desc.characteristic_extended_properties}}); + desc.characteristic_extended_properties}}); } else { nv_attr.push_back({desc.handle, desc.uuid, {}}); } @@ -138,22 +134,23 @@ std::vector Database::Serialize() const { return nv_attr; } -Database Database::Deserialize(const std::vector& nv_attr, - bool* success) { +Database Database::Deserialize(const std::vector& nv_attr, bool* success) { // clear reallocating Database result; auto it = nv_attr.cbegin(); for (; it != nv_attr.cend(); ++it) { const auto& attr = *it; - if (attr.type != PRIMARY_SERVICE && attr.type != SECONDARY_SERVICE) break; + if (attr.type != PRIMARY_SERVICE && attr.type != SECONDARY_SERVICE) { + break; + } result.services.emplace_back(Service{ - .handle = attr.handle, - .uuid = attr.value.service.uuid, - .is_primary = (attr.type == PRIMARY_SERVICE), - .end_handle = attr.value.service.end_handle, - .included_services = {}, - .characteristics = {}, + .handle = attr.handle, + .uuid = attr.value.service.uuid, + .is_primary = (attr.type == PRIMARY_SERVICE), + .end_handle = attr.value.service.end_handle, + .included_services = {}, + .characteristics = {}, }); } @@ -170,50 +167,47 @@ Database Database::Deserialize(const std::vector& nv_attr, if (current_service_it == result.services.end() || !HandleInRange(*current_service_it, attr.handle)) { - log::error("Can't find service for attribute with handle: 0x{:x}", - attr.handle); + log::error("Can't find service for attribute with handle: 0x{:x}", attr.handle); *success = false; return result; } if (attr.type == INCLUDE) { - Service* included_service = - FindService(result.services, attr.value.included_service.handle); + Service* included_service = FindService(result.services, attr.value.included_service.handle); if (!included_service) { log::error("Non-existing included service!"); *success = false; return result; } current_service_it->included_services.push_back(IncludedService{ - .handle = attr.handle, - .uuid = attr.value.included_service.uuid, - .start_handle = attr.value.included_service.handle, - .end_handle = attr.value.included_service.end_handle, + .handle = attr.handle, + .uuid = attr.value.included_service.uuid, + .start_handle = attr.value.included_service.handle, + .end_handle = attr.value.included_service.end_handle, }); } else if (attr.type == CHARACTERISTIC) { current_service_it->characteristics.emplace_back(Characteristic{ - .declaration_handle = attr.handle, - .uuid = attr.value.characteristic.uuid, - .value_handle = attr.value.characteristic.value_handle, - .properties = attr.value.characteristic.properties, - .descriptors = {}, + .declaration_handle = attr.handle, + .uuid = attr.value.characteristic.uuid, + .value_handle = attr.value.characteristic.value_handle, + .properties = attr.value.characteristic.properties, + .descriptors = {}, }); } else { if (attr.type == CHARACTERISTIC_EXTENDED_PROPERTIES) { current_service_it->characteristics.back().descriptors.emplace_back( - Descriptor{.handle = attr.handle, - .uuid = attr.type, - .characteristic_extended_properties = - attr.value.characteristic_extended_properties}); + Descriptor{.handle = attr.handle, + .uuid = attr.type, + .characteristic_extended_properties = + attr.value.characteristic_extended_properties}); } else { - current_service_it->characteristics.back().descriptors.emplace_back( - Descriptor{ + current_service_it->characteristics.back().descriptors.emplace_back(Descriptor{ .handle = attr.handle, .uuid = attr.type, .characteristic_extended_properties = {}, - }); + }); } } } @@ -239,10 +233,8 @@ Octet16 Database::Hash() const { continue; } uint16_t value = d.uuid.As16Bit(); - if (value == GATT_UUID_CHAR_DESCRIPTION || - value == GATT_UUID_CHAR_CLIENT_CONFIG || - value == GATT_UUID_CHAR_SRVR_CONFIG || - value == GATT_UUID_CHAR_PRESENT_FORMAT || + if (value == GATT_UUID_CHAR_DESCRIPTION || value == GATT_UUID_CHAR_CLIENT_CONFIG || + value == GATT_UUID_CHAR_SRVR_CONFIG || value == GATT_UUID_CHAR_PRESENT_FORMAT || value == GATT_UUID_CHAR_AGG_FORMAT) { len += 2 + UuidSize(d.uuid); } else if (value == GATT_UUID_CHAR_EXT_PROP) { @@ -294,12 +286,12 @@ Octet16 Database::Hash() const { } for (const Descriptor& d : c.descriptors) { - if (UuidSize(d.uuid) != Uuid::kNumBytes16) continue; + if (UuidSize(d.uuid) != Uuid::kNumBytes16) { + continue; + } uint16_t value = d.uuid.As16Bit(); - if (value == GATT_UUID_CHAR_DESCRIPTION || - value == GATT_UUID_CHAR_CLIENT_CONFIG || - value == GATT_UUID_CHAR_SRVR_CONFIG || - value == GATT_UUID_CHAR_PRESENT_FORMAT || + if (value == GATT_UUID_CHAR_DESCRIPTION || value == GATT_UUID_CHAR_CLIENT_CONFIG || + value == GATT_UUID_CHAR_SRVR_CONFIG || value == GATT_UUID_CHAR_PRESENT_FORMAT || value == GATT_UUID_CHAR_AGG_FORMAT) { UINT16_TO_STREAM(p, d.handle); UINT16_TO_STREAM(p, d.uuid.As16Bit()); @@ -313,7 +305,6 @@ Octet16 Database::Hash() const { } std::reverse(serialized.begin(), serialized.end()); - return crypto_toolbox::aes_cmac(Octet16{0}, serialized.data(), - serialized.size()); + return crypto_toolbox::aes_cmac(Octet16{0}, serialized.data(), serialized.size()); } } // namespace gatt diff --git a/system/bta/gatt/database.h b/system/bta/gatt/database.h index 3a87ebc792e..1f0bbb8e148 100644 --- a/system/bta/gatt/database.h +++ b/system/bta/gatt/database.h @@ -61,8 +61,7 @@ struct StoredAttribute { * «Characteristic Extended Properties» */ uint16_t characteristic_extended_properties; } value; - static void SerializeStoredAttribute(const StoredAttribute& attr, - std::vector& bytes); + static void SerializeStoredAttribute(const StoredAttribute& attr, std::vector& bytes); }; struct IncludedService; @@ -103,7 +102,7 @@ struct Descriptor { class DatabaseBuilder; class Database { - public: +public: /* Return true if there are no services in this database. */ bool IsEmpty() const { return services.empty(); } @@ -118,15 +117,14 @@ class Database { std::vector Serialize() const; - static Database Deserialize(const std::vector& nv_attr, - bool* success); + static Database Deserialize(const std::vector& nv_attr, bool* success); /* Return 128 bit unique identifier of this GATT database */ Octet16 Hash() const; friend class DatabaseBuilder; - private: +private: std::list services; }; diff --git a/system/bta/gatt/database_builder.cc b/system/bta/gatt/database_builder.cc index 624a24682aa..878e2f6982b 100644 --- a/system/bta/gatt/database_builder.cc +++ b/system/bta/gatt/database_builder.cc @@ -38,39 +38,36 @@ using namespace bluetooth; namespace gatt { -void DatabaseBuilder::AddService(uint16_t handle, uint16_t end_handle, - const Uuid& uuid, bool is_primary) { +void DatabaseBuilder::AddService(uint16_t handle, uint16_t end_handle, const Uuid& uuid, + bool is_primary) { // general case optimization - we add services in order - if (database.services.empty() || - database.services.back().end_handle < handle) { + if (database.services.empty() || database.services.back().end_handle < handle) { database.services.emplace_back(Service{ - .handle = handle, - .uuid = uuid, - .is_primary = is_primary, - .end_handle = end_handle, + .handle = handle, + .uuid = uuid, + .is_primary = is_primary, + .end_handle = end_handle, }); } else { auto& vec = database.services; // Find first service whose start handle is bigger than new service handle - auto it = std::lower_bound( - vec.begin(), vec.end(), handle, - [](Service s, uint16_t handle) { return s.end_handle < handle; }); + auto it = std::lower_bound(vec.begin(), vec.end(), handle, + [](Service s, uint16_t handle) { return s.end_handle < handle; }); // Insert new service just before it vec.emplace(it, Service{ - .handle = handle, - .uuid = uuid, - .is_primary = is_primary, - .end_handle = end_handle, + .handle = handle, + .uuid = uuid, + .is_primary = is_primary, + .end_handle = end_handle, }); } services_to_discover.insert({handle, end_handle}); } -void DatabaseBuilder::AddIncludedService(uint16_t handle, const Uuid& uuid, - uint16_t start_handle, +void DatabaseBuilder::AddIncludedService(uint16_t handle, const Uuid& uuid, uint16_t start_handle, uint16_t end_handle) { Service* service = FindService(database.services, handle); if (!service) { @@ -85,32 +82,31 @@ void DatabaseBuilder::AddIncludedService(uint16_t handle, const Uuid& uuid, } service->included_services.push_back(IncludedService{ - .handle = handle, - .uuid = uuid, - .start_handle = start_handle, - .end_handle = end_handle, + .handle = handle, + .uuid = uuid, + .start_handle = start_handle, + .end_handle = end_handle, }); } -void DatabaseBuilder::AddCharacteristic(uint16_t handle, uint16_t value_handle, - const Uuid& uuid, uint8_t properties) { +void DatabaseBuilder::AddCharacteristic(uint16_t handle, uint16_t value_handle, const Uuid& uuid, + uint8_t properties) { Service* service = FindService(database.services, handle); if (!service) { log::error("Illegal action to add to non-existing service!"); return; } - if (service->end_handle < value_handle) - log::warn( - "Remote device violates spec: value_handle=0x{:x} is after service " - "end_handle=0x{:x}", - value_handle, service->end_handle); + if (service->end_handle < value_handle) { + log::warn("Remote device violates spec: value_handle=0x{:x} is after service end_handle=0x{:x}", + value_handle, service->end_handle); + } service->characteristics.emplace_back(Characteristic{ - .declaration_handle = handle, - .uuid = uuid, - .value_handle = value_handle, - .properties = properties, + .declaration_handle = handle, + .uuid = uuid, + .value_handle = value_handle, + .properties = properties, }); return; } @@ -128,14 +124,14 @@ void DatabaseBuilder::AddDescriptor(uint16_t handle, const Uuid& uuid) { } Characteristic* char_node = &service->characteristics.front(); - for (auto it = service->characteristics.begin(); - it != service->characteristics.end(); it++) { - if (it->declaration_handle > handle) break; + for (auto it = service->characteristics.begin(); it != service->characteristics.end(); it++) { + if (it->declaration_handle > handle) { + break; + } char_node = &(*it); } - char_node->descriptors.emplace_back( - gatt::Descriptor{.handle = handle, .uuid = uuid}); + char_node->descriptors.emplace_back(gatt::Descriptor{.handle = handle, .uuid = uuid}); // We must read value for Characteristic Extended Properties if (uuid == Uuid::From16Bit(GATT_UUID_CHAR_EXT_PROP)) { @@ -150,7 +146,9 @@ bool DatabaseBuilder::StartNextServiceExploration() { services_to_discover.erase(handle_range); // Empty service declaration, nothing to explore, skip to next. - if (pending_service.first == pending_service.second) continue; + if (pending_service.first == pending_service.second) { + continue; + } pending_characteristic = HANDLE_MIN; return true; @@ -158,8 +156,7 @@ bool DatabaseBuilder::StartNextServiceExploration() { return false; } -const std::pair& -DatabaseBuilder::CurrentlyExploredService() { +const std::pair& DatabaseBuilder::CurrentlyExploredService() { return pending_service; } @@ -169,8 +166,7 @@ std::pair DatabaseBuilder::NextDescriptorRangeToExplore() { return {HANDLE_MAX, HANDLE_MAX}; } - for (auto it = service->characteristics.cbegin(); - it != service->characteristics.cend(); it++) { + for (auto it = service->characteristics.cbegin(); it != service->characteristics.cend(); it++) { if (it->declaration_handle > pending_characteristic) { auto next = std::next(it); @@ -179,13 +175,16 @@ std::pair DatabaseBuilder::NextDescriptorRangeToExplore() { * Part G 3.3.2 and 3.3.3 */ uint16_t start = it->declaration_handle + 2; uint16_t end; - if (next != service->characteristics.end()) + if (next != service->characteristics.end()) { end = next->declaration_handle - 1; - else + } else { end = service->end_handle; + } // No place for descriptor - skip to next characteristic - if (start > end) continue; + if (start > end) { + continue; + } pending_characteristic = start; return {start, end}; @@ -196,27 +195,30 @@ std::pair DatabaseBuilder::NextDescriptorRangeToExplore() { return {HANDLE_MAX, HANDLE_MAX}; } -Descriptor* FindDescriptorByHandle(std::list& services, - uint16_t handle) { +Descriptor* FindDescriptorByHandle(std::list& services, uint16_t handle) { Service* service = FindService(services, handle); - if (!service) return nullptr; + if (!service) { + return nullptr; + } Characteristic* char_node = &service->characteristics.front(); - for (auto it = service->characteristics.begin(); - it != service->characteristics.end(); it++) { - if (it->declaration_handle > handle) break; + for (auto it = service->characteristics.begin(); it != service->characteristics.end(); it++) { + if (it->declaration_handle > handle) { + break; + } char_node = &(*it); } for (auto& descriptor : char_node->descriptors) { - if (descriptor.handle == handle) return &descriptor; + if (descriptor.handle == handle) { + return &descriptor; + } } return nullptr; } -bool DatabaseBuilder::SetValueOfDescriptors( - const std::vector& values) { +bool DatabaseBuilder::SetValueOfDescriptors(const std::vector& values) { if (values.size() > descriptor_handles_to_read.size()) { log::error("values.size() <= descriptors.size() expected"); descriptor_handles_to_read.clear(); @@ -224,8 +226,7 @@ bool DatabaseBuilder::SetValueOfDescriptors( } for (size_t i = 0; i < values.size(); i++) { - Descriptor* d = FindDescriptorByHandle(database.services, - descriptor_handles_to_read[i]); + Descriptor* d = FindDescriptorByHandle(database.services, descriptor_handles_to_read[i]); if (!d) { log::error("non-existing descriptor!"); descriptor_handles_to_read.clear(); @@ -235,9 +236,8 @@ bool DatabaseBuilder::SetValueOfDescriptors( d->characteristic_extended_properties = values[i]; } - descriptor_handles_to_read.erase( - descriptor_handles_to_read.begin(), - descriptor_handles_to_read.begin() + values.size()); + descriptor_handles_to_read.erase(descriptor_handles_to_read.begin(), + descriptor_handles_to_read.begin() + values.size()); return true; } diff --git a/system/bta/gatt/database_builder.h b/system/bta/gatt/database_builder.h index 5149fa0e68e..44226c7e1b2 100644 --- a/system/bta/gatt/database_builder.h +++ b/system/bta/gatt/database_builder.h @@ -28,16 +28,15 @@ namespace gatt { class DatabaseBuilder { - public: - constexpr static std::pair EXPLORE_END = - std::make_pair(0xFFFF, 0xFFFF); - - void AddService(uint16_t handle, uint16_t end_handle, - const bluetooth::Uuid& uuid, bool is_primary); - void AddIncludedService(uint16_t handle, const bluetooth::Uuid& uuid, - uint16_t start_handle, uint16_t end_handle); - void AddCharacteristic(uint16_t handle, uint16_t value_handle, - const bluetooth::Uuid& uuid, uint8_t properties); +public: + constexpr static std::pair EXPLORE_END = std::make_pair(0xFFFF, 0xFFFF); + + void AddService(uint16_t handle, uint16_t end_handle, const bluetooth::Uuid& uuid, + bool is_primary); + void AddIncludedService(uint16_t handle, const bluetooth::Uuid& uuid, uint16_t start_handle, + uint16_t end_handle); + void AddCharacteristic(uint16_t handle, uint16_t value_handle, const bluetooth::Uuid& uuid, + uint8_t properties); void AddDescriptor(uint16_t handle, const bluetooth::Uuid& uuid); /* Returns true if next service exploration started, false if there are no @@ -55,9 +54,7 @@ class DatabaseBuilder { /* Return vector of "Characteristic Extended Properties" descriptors that must * be read as part of service discovery process */ - std::vector DescriptorHandlesToRead() { - return descriptor_handles_to_read; - } + std::vector DescriptorHandlesToRead() { return descriptor_handles_to_read; } /* Assign value to descriptors from |DescriptorHandlesToRead()|. Values must * be in same order. Returns |true| if all goes well, |false| if there is @@ -81,7 +78,7 @@ class DatabaseBuilder { /* Return text representation of internal state for debugging purposes */ std::string ToString() const; - private: +private: Database database; /* Start and end handle of service that is currently being discovered on the * remote device */ diff --git a/system/bta/groups/groups.cc b/system/bta/groups/groups.cc index 716ea019fbf..a574c7d2227 100644 --- a/system/bta/groups/groups.cc +++ b/system/bta/groups/groups.cc @@ -41,14 +41,11 @@ std::mutex instance_mutex; static constexpr int kMaxGroupId = 0xEF; class DeviceGroup { - public: - DeviceGroup(int group_id, Uuid uuid) - : group_id_(group_id), group_uuid_(uuid) {} +public: + DeviceGroup(int group_id, Uuid uuid) : group_id_(group_id), group_uuid_(uuid) {} void Add(const RawAddress& addr) { devices_.insert(addr); } void Remove(const RawAddress& addr) { devices_.erase(addr); } - bool Contains(const RawAddress& addr) const { - return (devices_.count(addr) != 0); - } + bool Contains(const RawAddress& addr) const { return devices_.count(addr) != 0; } void ForEachDevice(std::function cb) const { for (auto const& addr : devices_) { @@ -60,9 +57,8 @@ class DeviceGroup { int GetGroupId(void) const { return group_id_; } const Uuid& GetUuid(void) const { return group_uuid_; } - private: - friend std::ostream& operator<<(std::ostream& out, - const bluetooth::groups::DeviceGroup& value); +private: + friend std::ostream& operator<<(std::ostream& out, const bluetooth::groups::DeviceGroup& value); int group_id_; Uuid group_uuid_; std::unordered_set devices_; @@ -71,12 +67,11 @@ class DeviceGroup { class DeviceGroupsImpl : public DeviceGroups { static constexpr uint8_t GROUP_STORAGE_CURRENT_LAYOUT_MAGIC = 0x10; static constexpr size_t GROUP_STORAGE_HEADER_SZ = - sizeof(GROUP_STORAGE_CURRENT_LAYOUT_MAGIC) + - sizeof(uint8_t); /* num_of_groups */ + sizeof(GROUP_STORAGE_CURRENT_LAYOUT_MAGIC) + sizeof(uint8_t); /* num_of_groups */ static constexpr size_t GROUP_STORAGE_ENTRY_SZ = - sizeof(uint8_t) /* group_id */ + Uuid::kNumBytes128; + sizeof(uint8_t) /* group_id */ + Uuid::kNumBytes128; - public: +public: DeviceGroupsImpl(DeviceGroupsCallbacks* callbacks) { AddCallbacks(callbacks); btif_storage_load_bonded_groups(); @@ -84,7 +79,9 @@ class DeviceGroupsImpl : public DeviceGroups { int GetGroupId(const RawAddress& addr, Uuid uuid) const override { for (const auto& [id, g] : groups_) { - if ((g.Contains(addr)) && (uuid == g.GetUuid())) return id; + if ((g.Contains(addr)) && (uuid == g.GetUuid())) { + return id; + } } return kGroupUnknown; } @@ -108,7 +105,9 @@ class DeviceGroupsImpl : public DeviceGroups { if (group_id == kGroupUnknown) { auto gid = GetGroupId(addr, uuid); - if (gid != kGroupUnknown) return gid; + if (gid != kGroupUnknown) { + return gid; + } group = create_group(uuid); } else { group = get_or_create_group_with_id(group_id, uuid); @@ -171,14 +170,13 @@ class DeviceGroupsImpl : public DeviceGroups { } } - bool SerializeGroups(const RawAddress& addr, - std::vector& out) const { - auto num_groups = std::count_if( - groups_.begin(), groups_.end(), [&addr](auto& id_group_pair) { - return id_group_pair.second.Contains(addr); - }); - if ((num_groups == 0) || (num_groups > std::numeric_limits::max())) + bool SerializeGroups(const RawAddress& addr, std::vector& out) const { + auto num_groups = std::count_if(groups_.begin(), groups_.end(), [&addr](auto& id_group_pair) { + return id_group_pair.second.Contains(addr); + }); + if ((num_groups == 0) || (num_groups > std::numeric_limits::max())) { return false; + } out.resize(GROUP_STORAGE_HEADER_SZ + (num_groups * GROUP_STORAGE_ENTRY_SZ)); auto* ptr = out.data(); @@ -201,9 +199,10 @@ class DeviceGroupsImpl : public DeviceGroups { return true; } - void DeserializeGroups(const RawAddress& addr, - const std::vector& in) { - if (in.size() < GROUP_STORAGE_HEADER_SZ + GROUP_STORAGE_ENTRY_SZ) return; + void DeserializeGroups(const RawAddress& addr, const std::vector& in) { + if (in.size() < GROUP_STORAGE_HEADER_SZ + GROUP_STORAGE_ENTRY_SZ) { + return; + } auto* ptr = in.data(); @@ -214,8 +213,7 @@ class DeviceGroupsImpl : public DeviceGroups { uint8_t num_groups; STREAM_TO_UINT8(num_groups, ptr); - if (in.size() < - GROUP_STORAGE_HEADER_SZ + (num_groups * GROUP_STORAGE_ENTRY_SZ)) { + if (in.size() < GROUP_STORAGE_HEADER_SZ + (num_groups * GROUP_STORAGE_ENTRY_SZ)) { log::error("Invalid persistent storage data"); return; } @@ -228,9 +226,10 @@ class DeviceGroupsImpl : public DeviceGroups { Uuid::UUID128Bit uuid128; STREAM_TO_ARRAY(uuid128.data(), ptr, (int)Uuid::kNumBytes128); - auto* group = - get_or_create_group_with_id(id, Uuid::From128BitLE(uuid128)); - if (group) add_to_group(addr, group); + auto* group = get_or_create_group_with_id(id, Uuid::From128BitLE(uuid128)); + if (group) { + add_to_group(addr, group); + } for (auto c : callbacks_) { c->OnGroupAddFromStorage(addr, Uuid::From128BitLE(uuid128), id); @@ -246,9 +245,7 @@ class DeviceGroupsImpl : public DeviceGroups { for (const auto& [id, g] : groups_) { auto group_uuid = g.GetUuid(); auto group_id = g.GetGroupId(); - g.ForEachDevice([&](auto& dev) { - callbacks->OnGroupAdded(dev, group_uuid, group_id); - }); + g.ForEachDevice([&](auto& dev) { callbacks->OnGroupAdded(dev, group_uuid, group_id); }); } } @@ -256,7 +253,9 @@ class DeviceGroupsImpl : public DeviceGroups { auto it = find_if(callbacks_.begin(), callbacks_.end(), [callbacks](auto c) { return c == callbacks; }); - if (it != callbacks_.end()) callbacks_.erase(it); + if (it != callbacks_.end()) { + callbacks_.erase(it); + } if (callbacks_.size() != 0) { return false; @@ -278,7 +277,7 @@ class DeviceGroupsImpl : public DeviceGroups { dprintf(fd, "%s", stream.str().c_str()); } - private: +private: DeviceGroup* find_device_group(int group_id) { return groups_.count(group_id) ? &groups_.at(group_id) : nullptr; } @@ -287,9 +286,8 @@ class DeviceGroupsImpl : public DeviceGroups { auto group = find_device_group(group_id); if (group) { if (group->GetUuid() != uuid) { - log::error( - "group {} exists but for different uuid: {}, user request uuid: {}", - group_id, group->GetUuid(), uuid); + log::error("group {} exists but for different uuid: {}, user request uuid: {}", group_id, + group->GetUuid(), uuid); return nullptr; } @@ -340,8 +338,7 @@ void DeviceGroups::Initialize(DeviceGroupsCallbacks* callbacks) { instance->AddCallbacks(callbacks); } -void DeviceGroups::AddFromStorage(const RawAddress& addr, - const std::vector& in) { +void DeviceGroups::AddFromStorage(const RawAddress& addr, const std::vector& in) { if (!instance) { log::error("Not initialized yet"); return; @@ -350,8 +347,7 @@ void DeviceGroups::AddFromStorage(const RawAddress& addr, instance->DeserializeGroups(addr, in); } -bool DeviceGroups::GetForStorage(const RawAddress& addr, - std::vector& out) { +bool DeviceGroups::GetForStorage(const RawAddress& addr, std::vector& out) { if (!instance) { log::error("Not initialized yet"); return false; @@ -362,7 +358,9 @@ bool DeviceGroups::GetForStorage(const RawAddress& addr, void DeviceGroups::CleanUp(DeviceGroupsCallbacks* callbacks) { std::scoped_lock lock(instance_mutex); - if (!instance) return; + if (!instance) { + return; + } if (instance->Clear(callbacks)) { delete (instance); @@ -370,8 +368,7 @@ void DeviceGroups::CleanUp(DeviceGroupsCallbacks* callbacks) { } } -std::ostream& operator<<(std::ostream& out, - bluetooth::groups::DeviceGroup const& group) { +std::ostream& operator<<(std::ostream& out, bluetooth::groups::DeviceGroup const& group) { out << " == Group id: " << group.group_id_ << " == \n" << " Uuid: " << group.group_uuid_ << std::endl; out << " Devices:\n"; @@ -384,10 +381,11 @@ std::ostream& operator<<(std::ostream& out, void DeviceGroups::DebugDump(int fd) { std::scoped_lock lock(instance_mutex); dprintf(fd, "Device Groups Manager:\n"); - if (instance) + if (instance) { instance->Dump(fd); - else + } else { dprintf(fd, " Not initialized \n"); + } } DeviceGroups* DeviceGroups::Get() { return instance; } diff --git a/system/bta/groups/groups_test.cc b/system/bta/groups/groups_test.cc index 91f2eeccd46..ea11e169b16 100644 --- a/system/bta/groups/groups_test.cc +++ b/system/bta/groups/groups_test.cc @@ -43,13 +43,12 @@ DeviceGroupsCallbacks* dev_callbacks; RawAddress GetTestAddress(int index) { EXPECT_LT(index, UINT8_MAX); - RawAddress result = { - {0xC0, 0xDE, 0xC0, 0xDE, 0x00, static_cast(index)}}; + RawAddress result = {{0xC0, 0xDE, 0xC0, 0xDE, 0x00, static_cast(index)}}; return result; } class MockGroupsCallbacks : public DeviceGroupsCallbacks { - public: +public: MockGroupsCallbacks() = default; MockGroupsCallbacks(const MockGroupsCallbacks&) = delete; MockGroupsCallbacks& operator=(const MockGroupsCallbacks&) = delete; @@ -57,24 +56,17 @@ class MockGroupsCallbacks : public DeviceGroupsCallbacks { ~MockGroupsCallbacks() override = default; MOCK_METHOD((void), OnGroupAdded, - (const RawAddress& address, const bluetooth::Uuid& uuid, - int group_id), - (override)); - MOCK_METHOD((void), OnGroupMemberAdded, - (const RawAddress& address, int group_id), (override)); - - MOCK_METHOD((void), OnGroupRemoved, - (const bluetooth::Uuid& uuid, int group_id), (override)); - MOCK_METHOD((void), OnGroupMemberRemoved, - (const RawAddress& address, int group_id), (override)); + (const RawAddress& address, const bluetooth::Uuid& uuid, int group_id), (override)); + MOCK_METHOD((void), OnGroupMemberAdded, (const RawAddress& address, int group_id), (override)); + + MOCK_METHOD((void), OnGroupRemoved, (const bluetooth::Uuid& uuid, int group_id), (override)); + MOCK_METHOD((void), OnGroupMemberRemoved, (const RawAddress& address, int group_id), (override)); MOCK_METHOD((void), OnGroupAddFromStorage, - (const RawAddress& address, const bluetooth::Uuid& uuid, - int group_id), - (override)); + (const RawAddress& address, const bluetooth::Uuid& uuid, int group_id), (override)); }; class GroupsTest : public ::testing::Test { - protected: +protected: void SetUp() override { reset_mock_function_count_map(); callbacks.reset(new MockGroupsCallbacks()); @@ -132,10 +124,8 @@ TEST_F(GroupsTest, test_groups_remove_device) { DeviceGroups::Initialize(callbacks.get()); DeviceGroups::Get()->AddDevice(GetTestAddress(2), Uuid::kEmpty, 7); DeviceGroups::Get()->RemoveDevice(GetTestAddress(2)); - ASSERT_EQ(kGroupUnknown, - DeviceGroups::Get()->GetGroupId(GetTestAddress(2), Uuid::kEmpty)); - ASSERT_EQ(kGroupUnknown, - DeviceGroups::Get()->GetGroupId(GetTestAddress(3), Uuid::kEmpty)); + ASSERT_EQ(kGroupUnknown, DeviceGroups::Get()->GetGroupId(GetTestAddress(2), Uuid::kEmpty)); + ASSERT_EQ(kGroupUnknown, DeviceGroups::Get()->GetGroupId(GetTestAddress(3), Uuid::kEmpty)); DeviceGroups::CleanUp(callbacks.get()); } @@ -170,10 +160,8 @@ TEST_F(GroupsTest, test_add_multiple_groups) { } TEST_F(GroupsTest, test_remove_multiple_groups) { - Uuid uuid1 = - Uuid::From128BitBE(bluetooth::os::GenerateRandom()); - Uuid uuid2 = - Uuid::From128BitBE(bluetooth::os::GenerateRandom()); + Uuid uuid1 = Uuid::From128BitBE(bluetooth::os::GenerateRandom()); + Uuid uuid2 = Uuid::From128BitBE(bluetooth::os::GenerateRandom()); ASSERT_NE(uuid1, uuid2); EXPECT_CALL(*callbacks, OnGroupAdded(_, _, _)).Times(2); @@ -192,10 +180,8 @@ TEST_F(GroupsTest, test_remove_multiple_groups) { } TEST_F(GroupsTest, test_remove_device_fo_devices) { - Uuid uuid1 = - Uuid::From128BitBE(bluetooth::os::GenerateRandom()); - Uuid uuid2 = - Uuid::From128BitBE(bluetooth::os::GenerateRandom()); + Uuid uuid1 = Uuid::From128BitBE(bluetooth::os::GenerateRandom()); + Uuid uuid2 = Uuid::From128BitBE(bluetooth::os::GenerateRandom()); EXPECT_CALL(*callbacks, OnGroupAdded(_, _, _)).Times(2); DeviceGroups::Initialize(callbacks.get()); DeviceGroups::Get()->AddDevice(GetTestAddress(1), uuid1, 8); @@ -218,10 +204,8 @@ TEST_F(GroupsTest, test_add_devices_different_group_id) { DeviceGroups::Initialize(callbacks.get()); DeviceGroups::Get()->AddDevice(GetTestAddress(2), Uuid::kEmpty, 10); DeviceGroups::Get()->AddDevice(GetTestAddress(3), Uuid::kEmpty, 11); - auto group_id_1 = - DeviceGroups::Get()->GetGroupId(GetTestAddress(2), Uuid::kEmpty); - auto group_id_2 = - DeviceGroups::Get()->GetGroupId(GetTestAddress(3), Uuid::kEmpty); + auto group_id_1 = DeviceGroups::Get()->GetGroupId(GetTestAddress(2), Uuid::kEmpty); + auto group_id_2 = DeviceGroups::Get()->GetGroupId(GetTestAddress(3), Uuid::kEmpty); ASSERT_TRUE(group_id_1 != group_id_2); DeviceGroups::CleanUp(callbacks.get()); } @@ -232,9 +216,9 @@ TEST_F(GroupsTest, test_group_id_assign) { DeviceGroups::Initialize(callbacks.get()); EXPECT_CALL(*callbacks, OnGroupAdded(GetTestAddress(1), _, _)) - .WillOnce(SaveArg<2>(&captured_gid1)); + .WillOnce(SaveArg<2>(&captured_gid1)); EXPECT_CALL(*callbacks, OnGroupAdded(GetTestAddress(2), _, _)) - .WillOnce(SaveArg<2>(&captured_gid2)); + .WillOnce(SaveArg<2>(&captured_gid2)); int gid1 = DeviceGroups::Get()->AddDevice(GetTestAddress(1), Uuid::kEmpty, bluetooth::groups::kGroupUnknown); @@ -275,10 +259,8 @@ TEST_F(GroupsTest, test_storage_calls) { TEST_F(GroupsTest, test_storage_content) { int gid1 = bluetooth::groups::kGroupUnknown; int gid2 = bluetooth::groups::kGroupUnknown; - Uuid uuid1 = - Uuid::From128BitBE(bluetooth::os::GenerateRandom()); - Uuid uuid2 = - Uuid::From128BitBE(bluetooth::os::GenerateRandom()); + Uuid uuid1 = Uuid::From128BitBE(bluetooth::os::GenerateRandom()); + Uuid uuid2 = Uuid::From128BitBE(bluetooth::os::GenerateRandom()); ASSERT_NE(uuid1, uuid2); DeviceGroups::Initialize(callbacks.get()); diff --git a/system/bta/has/has_client.cc b/system/bta/has/has_client.cc index ebd60c84f8c..857ef69235e 100644 --- a/system/bta/has/has_client.cc +++ b/system/bta/has/has_client.cc @@ -70,20 +70,16 @@ using bluetooth::le_audio::has::PresetCtpOpcode; using namespace bluetooth; void btif_storage_add_leaudio_has_device(const RawAddress& address, - std::vector presets_bin, - uint8_t features, + std::vector presets_bin, uint8_t features, uint8_t active_preset); bool btif_storage_get_leaudio_has_presets(const RawAddress& address, std::vector& presets_bin, uint8_t& active_preset); void btif_storage_set_leaudio_has_presets(const RawAddress& address, std::vector presets_bin); -bool btif_storage_get_leaudio_has_features(const RawAddress& address, - uint8_t& features); -void btif_storage_set_leaudio_has_features(const RawAddress& address, - uint8_t features); -void btif_storage_set_leaudio_has_active_preset(const RawAddress& address, - uint8_t active_preset); +bool btif_storage_get_leaudio_has_features(const RawAddress& address, uint8_t& features); +void btif_storage_set_leaudio_has_features(const RawAddress& address, uint8_t features); +void btif_storage_set_leaudio_has_active_preset(const RawAddress& address, uint8_t active_preset); void btif_storage_remove_leaudio_has(const RawAddress& address); bool gatt_profile_get_eatt_support(const RawAddress& remote_bda); @@ -122,27 +118,28 @@ std::mutex instance_mutex; * synchronised preset change operations on the Binaural Hearing Aid devices. */ class HasClientImpl : public HasClient { - public: - HasClientImpl(bluetooth::has::HasClientCallbacks* callbacks, - base::Closure initCb) +public: + HasClientImpl(bluetooth::has::HasClientCallbacks* callbacks, base::Closure initCb) : gatt_if_(0), callbacks_(callbacks) { BTA_GATTC_AppRegister( - [](tBTA_GATTC_EVT event, tBTA_GATTC* p_data) { - if (instance && p_data) instance->GattcCallback(event, p_data); - }, - base::Bind( - [](base::Closure initCb, uint8_t client_id, uint8_t status) { - if (status != GATT_SUCCESS) { - log::error( - "Can't start Hearing Aid Service client profile - no gatt " - "clients left!"); - return; + [](tBTA_GATTC_EVT event, tBTA_GATTC* p_data) { + if (instance && p_data) { + instance->GattcCallback(event, p_data); } - instance->gatt_if_ = client_id; - initCb.Run(); }, - initCb), - true); + base::Bind( + [](base::Closure initCb, uint8_t client_id, uint8_t status) { + if (status != GATT_SUCCESS) { + log::error( + "Can't start Hearing Aid Service client profile - no gatt " + "clients left!"); + return; + } + instance->gatt_if_ = client_id; + initCb.Run(); + }, + initCb), + true); } ~HasClientImpl() override = default; @@ -160,8 +157,8 @@ class HasClientImpl : public HasClient { auto csis_api = CsisClient::Get(); if (csis_api != nullptr) { // Connect entire CAS set of devices - auto group_id = csis_api->GetGroupId( - address, bluetooth::Uuid::From16Bit(UUID_COMMON_AUDIO_SERVICE)); + auto group_id = + csis_api->GetGroupId(address, bluetooth::Uuid::From16Bit(UUID_COMMON_AUDIO_SERVICE)); addresses = csis_api->GetDeviceList(group_id); } @@ -171,32 +168,31 @@ class HasClientImpl : public HasClient { } for (auto const& addr : addresses) { - auto device = std::find_if(devices_.begin(), devices_.end(), - HasDevice::MatchAddress(addr)); + auto device = std::find_if(devices_.begin(), devices_.end(), HasDevice::MatchAddress(addr)); if (device == devices_.end()) { devices_.emplace_back(addr, true); BTA_GATTC_Open(gatt_if_, addr, BTM_BLE_DIRECT_CONNECTION, false); } else { device->is_connecting_actively = true; - if (!device->IsConnected()) + if (!device->IsConnected()) { BTA_GATTC_Open(gatt_if_, addr, BTM_BLE_DIRECT_CONNECTION, false); + } } } } - void AddFromStorage(const RawAddress& address, uint8_t features, - uint16_t is_acceptlisted) { - log::debug("{}, features=0x{:x}, isAcceptlisted={}", address, features, - is_acceptlisted); + void AddFromStorage(const RawAddress& address, uint8_t features, uint16_t is_acceptlisted) { + log::debug("{}, features=0x{:x}, isAcceptlisted={}", address, features, is_acceptlisted); /* Notify upper layer about the device */ callbacks_->OnDeviceAvailable(address, features); if (is_acceptlisted) { - auto device = std::find_if(devices_.begin(), devices_.end(), - HasDevice::MatchAddress(address)); - if (device == devices_.end()) + auto device = + std::find_if(devices_.begin(), devices_.end(), HasDevice::MatchAddress(address)); + if (device == devices_.end()) { devices_.push_back(HasDevice(address, features)); + } /* Connect in background */ BTA_GATTC_Open(gatt_if_, address, BTM_BLE_BKG_CONNECT_ALLOW_LIST, false); @@ -210,8 +206,8 @@ class HasClientImpl : public HasClient { auto csis_api = CsisClient::Get(); if (csis_api != nullptr) { // Disconnect entire CAS set of devices - auto group_id = csis_api->GetGroupId( - address, bluetooth::Uuid::From16Bit(UUID_COMMON_AUDIO_SERVICE)); + auto group_id = + csis_api->GetGroupId(address, bluetooth::Uuid::From16Bit(UUID_COMMON_AUDIO_SERVICE)); addresses = csis_api->GetDeviceList(group_id); } @@ -221,8 +217,7 @@ class HasClientImpl : public HasClient { } for (auto const& addr : addresses) { - auto device = std::find_if(devices_.begin(), devices_.end(), - HasDevice::MatchAddress(addr)); + auto device = std::find_if(devices_.begin(), devices_.end(), HasDevice::MatchAddress(addr)); if (device == devices_.end()) { log::warn("Device not connected to profile{}", addr); return; @@ -252,18 +247,17 @@ class HasClientImpl : public HasClient { tGATT_STATUS status) { /* Find journal entry by the context and update */ auto journal_entry = std::find_if( - device.has_journal_.begin(), device.has_journal_.end(), - [&context](auto const& record) { - if (record.is_operation) { - return HasGattOpContext(record.op_context_handle) == context; - } - return false; - }); + device.has_journal_.begin(), device.has_journal_.end(), [&context](auto const& record) { + if (record.is_operation) { + return HasGattOpContext(record.op_context_handle) == context; + } + return false; + }); if (journal_entry == device.has_journal_.end()) { log::warn( - "Journaling error or journal length limit was set to low. Unable to " - "log the operation outcome."); + "Journaling error or journal length limit was set to low. Unable to " + "log the operation outcome."); return; } @@ -276,9 +270,8 @@ class HasClientImpl : public HasClient { } std::optional ExtractPendingCtpOp(uint16_t op_id) { - auto op_it = - std::find_if(pending_operations_.begin(), pending_operations_.end(), - [op_id](auto const& el) { return op_id == el.op_id; }); + auto op_it = std::find_if(pending_operations_.begin(), pending_operations_.end(), + [op_id](auto const& el) { return op_id == el.op_id; }); if (op_it != pending_operations_.end()) { auto op = *op_it; @@ -291,8 +284,7 @@ class HasClientImpl : public HasClient { void EnqueueCtpOp(HasCtpOp op) { pending_operations_.push_back(op); } - void OnHasActivePresetCycleStatus(uint16_t conn_id, tGATT_STATUS status, - void* user_data) { + void OnHasActivePresetCycleStatus(uint16_t conn_id, tGATT_STATUS status, void* user_data) { log::debug("status: {}", status); auto device = GetDevice(conn_id); @@ -307,7 +299,9 @@ class HasClientImpl : public HasClient { UpdateJournalOpEntryStatus(*device, context, status); auto op_opt = ExtractPendingCtpOp(context.ctp_op_id); - if (status == GATT_SUCCESS) return; + if (status == GATT_SUCCESS) { + return; + } /* This could be one of the coordinated group preset change request */ pending_group_operation_timeouts_.erase(context.ctp_op_id); @@ -318,8 +312,7 @@ class HasClientImpl : public HasClient { return; } auto op = op_opt.value(); - callbacks_->OnActivePresetSelectError(op.addr_or_group, - GattStatus2SvcErrorCode(status)); + callbacks_->OnActivePresetSelectError(op.addr_or_group, GattStatus2SvcErrorCode(status)); if (status == GATT_DATABASE_OUT_OF_SYNC) { log::info("Database out of sync for {}", device->addr); @@ -327,8 +320,7 @@ class HasClientImpl : public HasClient { } } - void OnHasPresetNameSetStatus(uint16_t conn_id, tGATT_STATUS status, - void* user_data) { + void OnHasPresetNameSetStatus(uint16_t conn_id, tGATT_STATUS status, void* user_data) { auto device = GetDevice(conn_id); if (!device) { log::warn("Device not connected to profile, conn_id={}", conn_id); @@ -342,7 +334,9 @@ class HasClientImpl : public HasClient { UpdateJournalOpEntryStatus(*device, context, status); auto op_opt = ExtractPendingCtpOp(context.ctp_op_id); - if (status == GATT_SUCCESS) return; + if (status == GATT_SUCCESS) { + return; + } /* This could be one of the coordinated group preset change request */ pending_group_operation_timeouts_.erase(context.ctp_op_id); @@ -353,16 +347,14 @@ class HasClientImpl : public HasClient { return; } auto op = op_opt.value(); - callbacks_->OnSetPresetNameError(device->addr, op.index, - GattStatus2SvcErrorCode(status)); + callbacks_->OnSetPresetNameError(device->addr, op.index, GattStatus2SvcErrorCode(status)); if (status == GATT_DATABASE_OUT_OF_SYNC) { log::info("Database out of sync for {}", device->addr); ClearDeviceInformationAndStartSearch(device); } } - void OnHasPresetNameGetStatus(uint16_t conn_id, tGATT_STATUS status, - void* user_data) { + void OnHasPresetNameGetStatus(uint16_t conn_id, tGATT_STATUS status, void* user_data) { auto device = GetDevice(conn_id); if (!device) { log::warn("Device not connected to profile, conn_id={}", conn_id); @@ -376,7 +368,9 @@ class HasClientImpl : public HasClient { UpdateJournalOpEntryStatus(*device, context, status); auto op_opt = ExtractPendingCtpOp(context.ctp_op_id); - if (status == GATT_SUCCESS) return; + if (status == GATT_SUCCESS) { + return; + } /* Error handling */ if (!op_opt.has_value()) { @@ -384,21 +378,18 @@ class HasClientImpl : public HasClient { return; } auto op = op_opt.value(); - callbacks_->OnPresetInfoError(device->addr, op.index, - GattStatus2SvcErrorCode(status)); + callbacks_->OnPresetInfoError(device->addr, op.index, GattStatus2SvcErrorCode(status)); if (status == GATT_DATABASE_OUT_OF_SYNC) { log::info("Database out of sync for {}", device->addr); ClearDeviceInformationAndStartSearch(device); } else { - log::error("Devices {}: Control point not usable. Disconnecting!", - device->addr); + log::error("Devices {}: Control point not usable. Disconnecting!", device->addr); BTA_GATTC_Close(device->conn_id); } } - void OnHasPresetIndexOperation(uint16_t conn_id, tGATT_STATUS status, - void* user_data) { + void OnHasPresetIndexOperation(uint16_t conn_id, tGATT_STATUS status, void* user_data) { log::debug(""); auto device = GetDevice(conn_id); @@ -414,7 +405,9 @@ class HasClientImpl : public HasClient { UpdateJournalOpEntryStatus(*device, context, status); auto op_opt = ExtractPendingCtpOp(context.ctp_op_id); - if (status == GATT_SUCCESS) return; + if (status == GATT_SUCCESS) { + return; + } /* This could be one of the coordinated group preset change request */ pending_group_operation_timeouts_.erase(context.ctp_op_id); @@ -427,20 +420,17 @@ class HasClientImpl : public HasClient { auto op = op_opt.value(); if (op.opcode == PresetCtpOpcode::READ_PRESETS) { - callbacks_->OnPresetInfoError(device->addr, op.index, - GattStatus2SvcErrorCode(status)); + callbacks_->OnPresetInfoError(device->addr, op.index, GattStatus2SvcErrorCode(status)); } else { - callbacks_->OnActivePresetSelectError(op.addr_or_group, - GattStatus2SvcErrorCode(status)); + callbacks_->OnActivePresetSelectError(op.addr_or_group, GattStatus2SvcErrorCode(status)); } if (status == GATT_DATABASE_OUT_OF_SYNC) { log::info("Database out of sync for {}", device->addr); ClearDeviceInformationAndStartSearch(device); } else { - log::error("Devices {}: Control point not usable. Disconnecting!", - device->addr); + log::error("Devices {}: Control point not usable. Disconnecting!", device->addr); BTA_GATTC_Close(device->conn_id); } } @@ -455,9 +445,9 @@ class HasClientImpl : public HasClient { return; } - auto device = std::find_if( - devices_.begin(), devices_.end(), - HasDevice::MatchAddress(std::get(operation.addr_or_group))); + auto device = + std::find_if(devices_.begin(), devices_.end(), + HasDevice::MatchAddress(std::get(operation.addr_or_group))); if (device == devices_.end()) { log::warn("Device not connected to profile addr: {}", std::get(operation.addr_or_group)); @@ -479,31 +469,35 @@ class HasClientImpl : public HasClient { /* Write to control point */ EnqueueCtpOp(operation); BtaGattQueue::WriteCharacteristic( - device->conn_id, device->cp_handle, operation.ToCharacteristicValue(), - GATT_WRITE, - [](uint16_t conn_id, tGATT_STATUS status, uint16_t handle, uint16_t len, - const uint8_t* value, void* user_data) { - if (instance) - instance->OnHasPresetNameGetStatus(conn_id, status, user_data); - }, - context); - } - - ErrorCode CpPresetIndexOperationWriteReq(HasDevice& device, - HasCtpOp& operation) { + device->conn_id, device->cp_handle, operation.ToCharacteristicValue(), GATT_WRITE, + [](uint16_t conn_id, tGATT_STATUS status, uint16_t handle, uint16_t len, + const uint8_t* value, void* user_data) { + if (instance) { + instance->OnHasPresetNameGetStatus(conn_id, status, user_data); + } + }, + context); + } + + ErrorCode CpPresetIndexOperationWriteReq(HasDevice& device, HasCtpOp& operation) { log::debug("Operation: {}", operation); - if (!device.IsConnected()) return ErrorCode::OPERATION_NOT_POSSIBLE; + if (!device.IsConnected()) { + return ErrorCode::OPERATION_NOT_POSSIBLE; + } - if (!device.SupportsPresets()) return ErrorCode::OPERATION_NOT_SUPPORTED; + if (!device.SupportsPresets()) { + return ErrorCode::OPERATION_NOT_SUPPORTED; + } - if (!device.SupportsOperation(operation.opcode)) - return operation.IsGroupRequest() - ? ErrorCode::GROUP_OPERATION_NOT_SUPPORTED - : ErrorCode::OPERATION_NOT_SUPPORTED; + if (!device.SupportsOperation(operation.opcode)) { + return operation.IsGroupRequest() ? ErrorCode::GROUP_OPERATION_NOT_SUPPORTED + : ErrorCode::OPERATION_NOT_SUPPORTED; + } - if (!device.IsValidPreset(operation.index)) + if (!device.IsValidPreset(operation.index)) { return ErrorCode::INVALID_PRESET_INDEX; + } auto context = HasGattOpContext(operation); @@ -513,22 +507,21 @@ class HasClientImpl : public HasClient { /* Write to control point */ EnqueueCtpOp(operation); BtaGattQueue::WriteCharacteristic( - device.conn_id, device.cp_handle, operation.ToCharacteristicValue(), - GATT_WRITE, - [](uint16_t conn_id, tGATT_STATUS status, uint16_t handle, uint16_t len, - const uint8_t* value, void* user_data) { - if (instance) - instance->OnHasPresetIndexOperation(conn_id, status, user_data); - }, - context); + device.conn_id, device.cp_handle, operation.ToCharacteristicValue(), GATT_WRITE, + [](uint16_t conn_id, tGATT_STATUS status, uint16_t handle, uint16_t len, + const uint8_t* value, void* user_data) { + if (instance) { + instance->OnHasPresetIndexOperation(conn_id, status, user_data); + } + }, + context); return ErrorCode::NO_ERROR; } bool AreAllDevicesAvailable(const std::vector& addresses) { for (auto& addr : addresses) { - auto device = std::find_if(devices_.begin(), devices_.end(), - HasDevice::MatchAddress(addr)); + auto device = std::find_if(devices_.begin(), devices_.end(), HasDevice::MatchAddress(addr)); if (device == devices_.end() || !device->IsConnected()) { return false; } @@ -537,9 +530,8 @@ class HasClientImpl : public HasClient { } ErrorCode CpPresetOperationCaller( - HasCtpOp operation, - std::function - write_cb) { + HasCtpOp operation, + std::function write_cb) { log::debug("Operation: {}", operation); auto status = ErrorCode::NO_ERROR; @@ -563,8 +555,8 @@ class HasClientImpl : public HasClient { } else { /* Make this a coordinated operation */ - pending_group_operation_timeouts_.emplace( - operation.op_id, HasCtpGroupOpCoordinator(addresses, operation)); + pending_group_operation_timeouts_.emplace(operation.op_id, + HasCtpGroupOpCoordinator(addresses, operation)); if (operation.IsSyncedOperation()) { status = ErrorCode::GROUP_OPERATION_NOT_SUPPORTED; @@ -572,8 +564,8 @@ class HasClientImpl : public HasClient { /* Clear the error if we find device to forward the operation */ bool was_sent = false; for (auto& addr : addresses) { - auto device = std::find_if(devices_.begin(), devices_.end(), - HasDevice::MatchAddress(addr)); + auto device = + std::find_if(devices_.begin(), devices_.end(), HasDevice::MatchAddress(addr)); if (device != devices_.end()) { status = write_cb(*device, operation); if (status == ErrorCode::NO_ERROR) { @@ -582,17 +574,21 @@ class HasClientImpl : public HasClient { } } } - if (!was_sent) status = ErrorCode::OPERATION_NOT_POSSIBLE; + if (!was_sent) { + status = ErrorCode::OPERATION_NOT_POSSIBLE; + } } else { status = ErrorCode::GROUP_OPERATION_NOT_SUPPORTED; for (auto& addr : addresses) { - auto device = std::find_if(devices_.begin(), devices_.end(), - HasDevice::MatchAddress(addr)); + auto device = + std::find_if(devices_.begin(), devices_.end(), HasDevice::MatchAddress(addr)); if (device != devices_.end()) { status = write_cb(*device, operation); - if (status != ErrorCode::NO_ERROR) break; + if (status != ErrorCode::NO_ERROR) { + break; + } } } } @@ -605,11 +601,13 @@ class HasClientImpl : public HasClient { } } else { - auto device = std::find_if(devices_.begin(), devices_.end(), - HasDevice::MatchAddress(std::get( - operation.addr_or_group))); + auto device = + std::find_if(devices_.begin(), devices_.end(), + HasDevice::MatchAddress(std::get(operation.addr_or_group))); status = ErrorCode::OPERATION_NOT_POSSIBLE; - if (device != devices_.end()) status = write_cb(*device, operation); + if (device != devices_.end()) { + status = write_cb(*device, operation); + } } return status; @@ -619,27 +617,25 @@ class HasClientImpl : public HasClient { log::info("Operation: {}", operation); auto status = CpPresetOperationCaller( - operation, [](HasDevice& device, HasCtpOp operation) -> ErrorCode { - if (instance) - return instance->CpPresetIndexOperationWriteReq(device, operation); - return ErrorCode::OPERATION_NOT_POSSIBLE; - }); + operation, [](HasDevice& device, HasCtpOp operation) -> ErrorCode { + if (instance) { + return instance->CpPresetIndexOperationWriteReq(device, operation); + } + return ErrorCode::OPERATION_NOT_POSSIBLE; + }); if (status != ErrorCode::NO_ERROR) { switch (operation.opcode) { case PresetCtpOpcode::READ_PRESETS: - log::assert_that( - std::holds_alternative(operation.addr_or_group), - "Unsupported group operation!"); + log::assert_that(std::holds_alternative(operation.addr_or_group), + "Unsupported group operation!"); - callbacks_->OnPresetInfoError( - std::get(operation.addr_or_group), operation.index, - status); + callbacks_->OnPresetInfoError(std::get(operation.addr_or_group), + operation.index, status); break; case PresetCtpOpcode::SET_ACTIVE_PRESET: case PresetCtpOpcode::SET_ACTIVE_PRESET_SYNC: - callbacks_->OnActivePresetSelectError(operation.addr_or_group, - status); + callbacks_->OnActivePresetSelectError(operation.addr_or_group, status); break; default: break; @@ -647,18 +643,21 @@ class HasClientImpl : public HasClient { } } - ErrorCode CpPresetsCycleOperationWriteReq(HasDevice& device, - HasCtpOp& operation) { + ErrorCode CpPresetsCycleOperationWriteReq(HasDevice& device, HasCtpOp& operation) { log::debug("addr: {} operation: {}", device.addr, operation); - if (!device.IsConnected()) return ErrorCode::OPERATION_NOT_POSSIBLE; + if (!device.IsConnected()) { + return ErrorCode::OPERATION_NOT_POSSIBLE; + } - if (!device.SupportsPresets()) return ErrorCode::OPERATION_NOT_SUPPORTED; + if (!device.SupportsPresets()) { + return ErrorCode::OPERATION_NOT_SUPPORTED; + } - if (!device.SupportsOperation(operation.opcode)) - return operation.IsGroupRequest() - ? ErrorCode::GROUP_OPERATION_NOT_SUPPORTED - : ErrorCode::OPERATION_NOT_SUPPORTED; + if (!device.SupportsOperation(operation.opcode)) { + return operation.IsGroupRequest() ? ErrorCode::GROUP_OPERATION_NOT_SUPPORTED + : ErrorCode::OPERATION_NOT_SUPPORTED; + } auto context = HasGattOpContext(operation); @@ -668,14 +667,14 @@ class HasClientImpl : public HasClient { /* Write to control point */ EnqueueCtpOp(operation); BtaGattQueue::WriteCharacteristic( - device.conn_id, device.cp_handle, operation.ToCharacteristicValue(), - GATT_WRITE, - [](uint16_t conn_id, tGATT_STATUS status, uint16_t handle, uint16_t len, - const uint8_t* value, void* user_data) { - if (instance) - instance->OnHasActivePresetCycleStatus(conn_id, status, user_data); - }, - context); + device.conn_id, device.cp_handle, operation.ToCharacteristicValue(), GATT_WRITE, + [](uint16_t conn_id, tGATT_STATUS status, uint16_t handle, uint16_t len, + const uint8_t* value, void* user_data) { + if (instance) { + instance->OnHasActivePresetCycleStatus(conn_id, status, user_data); + } + }, + context); return ErrorCode::NO_ERROR; } @@ -683,35 +682,42 @@ class HasClientImpl : public HasClient { log::debug("Operation: {}", operation); auto status = CpPresetOperationCaller( - operation, [](HasDevice& device, HasCtpOp operation) -> ErrorCode { - if (instance) - return instance->CpPresetsCycleOperationWriteReq(device, operation); - return ErrorCode::OPERATION_NOT_POSSIBLE; - }); + operation, [](HasDevice& device, HasCtpOp operation) -> ErrorCode { + if (instance) { + return instance->CpPresetsCycleOperationWriteReq(device, operation); + } + return ErrorCode::OPERATION_NOT_POSSIBLE; + }); - if (status != ErrorCode::NO_ERROR) + if (status != ErrorCode::NO_ERROR) { callbacks_->OnActivePresetSelectError(operation.addr_or_group, status); + } } - ErrorCode CpWritePresetNameOperationWriteReq(HasDevice& device, - HasCtpOp operation) { + ErrorCode CpWritePresetNameOperationWriteReq(HasDevice& device, HasCtpOp operation) { log::debug("addr: {} operation: {}", device.addr, operation); - if (!device.IsConnected()) return ErrorCode::OPERATION_NOT_POSSIBLE; + if (!device.IsConnected()) { + return ErrorCode::OPERATION_NOT_POSSIBLE; + } - if (!device.SupportsPresets()) return ErrorCode::OPERATION_NOT_SUPPORTED; + if (!device.SupportsPresets()) { + return ErrorCode::OPERATION_NOT_SUPPORTED; + } - if (!device.IsValidPreset(operation.index, true)) - return device.IsValidPreset(operation.index) - ? ErrorCode::SET_NAME_NOT_ALLOWED - : ErrorCode::INVALID_PRESET_INDEX; + if (!device.IsValidPreset(operation.index, true)) { + return device.IsValidPreset(operation.index) ? ErrorCode::SET_NAME_NOT_ALLOWED + : ErrorCode::INVALID_PRESET_INDEX; + } - if (!device.SupportsOperation(operation.opcode)) + if (!device.SupportsOperation(operation.opcode)) { return ErrorCode::OPERATION_NOT_SUPPORTED; + } if (operation.name.value_or("").length() > - bluetooth::le_audio::has::HasPreset::kPresetNameLengthLimit) + bluetooth::le_audio::has::HasPreset::kPresetNameLengthLimit) { return ErrorCode::INVALID_PRESET_NAME_LENGTH; + } auto context = HasGattOpContext(operation, operation.index); @@ -721,14 +727,14 @@ class HasClientImpl : public HasClient { /* Write to control point */ EnqueueCtpOp(operation); BtaGattQueue::WriteCharacteristic( - device.conn_id, device.cp_handle, operation.ToCharacteristicValue(), - GATT_WRITE, - [](uint16_t conn_id, tGATT_STATUS status, uint16_t handle, uint16_t len, - const uint8_t* value, void* user_data) { - if (instance) - instance->OnHasPresetNameSetStatus(conn_id, status, user_data); - }, - context); + device.conn_id, device.cp_handle, operation.ToCharacteristicValue(), GATT_WRITE, + [](uint16_t conn_id, tGATT_STATUS status, uint16_t handle, uint16_t len, + const uint8_t* value, void* user_data) { + if (instance) { + instance->OnHasPresetNameSetStatus(conn_id, status, user_data); + } + }, + context); return ErrorCode::NO_ERROR; } @@ -745,8 +751,8 @@ class HasClientImpl : public HasClient { addresses = csis_api->GetDeviceList(operation.GetGroupId()); /* Make this a coordinated operation */ - pending_group_operation_timeouts_.emplace( - operation.op_id, HasCtpGroupOpCoordinator(addresses, operation)); + pending_group_operation_timeouts_.emplace(operation.op_id, + HasCtpGroupOpCoordinator(addresses, operation)); } } else { @@ -761,8 +767,7 @@ class HasClientImpl : public HasClient { } for (auto& addr : addresses) { - auto device = std::find_if(devices_.begin(), devices_.end(), - HasDevice::MatchAddress(addr)); + auto device = std::find_if(devices_.begin(), devices_.end(), HasDevice::MatchAddress(addr)); if (device != devices_.end()) { status = CpWritePresetNameOperationWriteReq(*device, operation); if (status != ErrorCode::NO_ERROR) { @@ -773,11 +778,11 @@ class HasClientImpl : public HasClient { } if (status != ErrorCode::NO_ERROR) { - if (operation.IsGroupRequest()) + if (operation.IsGroupRequest()) { pending_group_operation_timeouts_.erase(operation.op_id); + } - callbacks_->OnSetPresetNameError(operation.addr_or_group, operation.index, - status); + callbacks_->OnSetPresetNameError(operation.addr_or_group, operation.index, status); } } @@ -787,19 +792,26 @@ class HasClientImpl : public HasClient { * You never know if the user will make another call for the other devices * in this set even though the may support locally synced operations. */ - if (std::holds_alternative(addr_or_group_id)) return false; + if (std::holds_alternative(addr_or_group_id)) { + return false; + } auto csis_api = CsisClient::Get(); - if (csis_api == nullptr) return false; + if (csis_api == nullptr) { + return false; + } auto addresses = csis_api->GetDeviceList(std::get(addr_or_group_id)); - if (addresses.empty()) return false; + if (addresses.empty()) { + return false; + } for (auto& addr : addresses) { - auto device = std::find_if(devices_.begin(), devices_.end(), - HasDevice::MatchAddress(addr)); + auto device = std::find_if(devices_.begin(), devices_.end(), HasDevice::MatchAddress(addr)); if (device != devices_.end()) { - if (device->SupportsOperation(opcode)) return true; + if (device->SupportsOperation(opcode)) { + return true; + } } } @@ -810,41 +822,35 @@ class HasClientImpl : public HasClient { uint8_t preset_index) override { log::debug(""); - auto opcode = shouldRequestSyncedOp(addr_or_group_id, - PresetCtpOpcode::SET_ACTIVE_PRESET_SYNC) - ? PresetCtpOpcode::SET_ACTIVE_PRESET_SYNC - : PresetCtpOpcode::SET_ACTIVE_PRESET; + auto opcode = shouldRequestSyncedOp(addr_or_group_id, PresetCtpOpcode::SET_ACTIVE_PRESET_SYNC) + ? PresetCtpOpcode::SET_ACTIVE_PRESET_SYNC + : PresetCtpOpcode::SET_ACTIVE_PRESET; CpPresetIndexOperation(HasCtpOp(addr_or_group_id, opcode, preset_index)); } - void NextActivePreset( - std::variant addr_or_group_id) override { + void NextActivePreset(std::variant addr_or_group_id) override { log::debug(""); - auto opcode = shouldRequestSyncedOp(addr_or_group_id, - PresetCtpOpcode::SET_NEXT_PRESET_SYNC) - ? PresetCtpOpcode::SET_NEXT_PRESET_SYNC - : PresetCtpOpcode::SET_NEXT_PRESET; + auto opcode = shouldRequestSyncedOp(addr_or_group_id, PresetCtpOpcode::SET_NEXT_PRESET_SYNC) + ? PresetCtpOpcode::SET_NEXT_PRESET_SYNC + : PresetCtpOpcode::SET_NEXT_PRESET; CpPresetsCycleOperation(HasCtpOp(addr_or_group_id, opcode)); } - void PreviousActivePreset( - std::variant addr_or_group_id) override { + void PreviousActivePreset(std::variant addr_or_group_id) override { log::debug(""); - auto opcode = shouldRequestSyncedOp(addr_or_group_id, - PresetCtpOpcode::SET_PREV_PRESET_SYNC) - ? PresetCtpOpcode::SET_PREV_PRESET_SYNC - : PresetCtpOpcode::SET_PREV_PRESET; + auto opcode = shouldRequestSyncedOp(addr_or_group_id, PresetCtpOpcode::SET_PREV_PRESET_SYNC) + ? PresetCtpOpcode::SET_PREV_PRESET_SYNC + : PresetCtpOpcode::SET_PREV_PRESET; CpPresetsCycleOperation(HasCtpOp(addr_or_group_id, opcode)); } void GetPresetInfo(const RawAddress& address, uint8_t preset_index) override { - auto device = std::find_if(devices_.begin(), devices_.end(), - HasDevice::MatchAddress(address)); + auto device = std::find_if(devices_.begin(), devices_.end(), HasDevice::MatchAddress(address)); if (device == devices_.end()) { log::warn("Device not connected to profile{}", address); return; @@ -856,42 +862,38 @@ class HasClientImpl : public HasClient { * details are always up to date. However we have to be able to do the * READ_PRESET_BY_INDEX, to pass the test specification requirements. */ - if (osi_property_get_bool("persist.bluetooth.has.always_use_preset_cache", - true)) { + if (osi_property_get_bool("persist.bluetooth.has.always_use_preset_cache", true)) { auto* preset = device->GetPreset(preset_index); if (preset == nullptr) { log::error("Invalid preset request{}", address); - callbacks_->OnPresetInfoError(address, preset_index, - ErrorCode::INVALID_PRESET_INDEX); + callbacks_->OnPresetInfoError(address, preset_index, ErrorCode::INVALID_PRESET_INDEX); return; } - callbacks_->OnPresetInfo(address, - PresetInfoReason::PRESET_INFO_REQUEST_RESPONSE, + callbacks_->OnPresetInfo(address, PresetInfoReason::PRESET_INFO_REQUEST_RESPONSE, {{.preset_index = preset_index, .writable = preset->IsWritable(), .available = preset->IsAvailable(), .preset_name = preset->GetName()}}); } else { - CpPresetIndexOperation( - HasCtpOp(address, PresetCtpOpcode::READ_PRESETS, preset_index)); + CpPresetIndexOperation(HasCtpOp(address, PresetCtpOpcode::READ_PRESETS, preset_index)); } } - void SetPresetName(std::variant addr_or_group_id, - uint8_t preset_index, std::string name) override { + void SetPresetName(std::variant addr_or_group_id, uint8_t preset_index, + std::string name) override { log::debug("preset_idx: {}, name: {}", preset_index, name); - CpWritePresetNameOperation(HasCtpOp(addr_or_group_id, - PresetCtpOpcode::WRITE_PRESET_NAME, + CpWritePresetNameOperation(HasCtpOp(addr_or_group_id, PresetCtpOpcode::WRITE_PRESET_NAME, preset_index, 1 /* Don't care */, name)); } void CleanUp() { BTA_GATTC_AppDeregister(gatt_if_); for (auto& device : devices_) { - if (device.conn_id != GATT_INVALID_CONN_ID) + if (device.conn_id != GATT_INVALID_CONN_ID) { BTA_GATTC_Close(device.conn_id); + } DoDisconnectCleanUp(device); } @@ -918,15 +920,15 @@ class HasClientImpl : public HasClient { void OnGroupOpCoordinatorTimeout(void* p) { log::error( - "Coordinated operation timeout: not all the devices notified their " - "state change on time."); + "Coordinated operation timeout: not all the devices notified their " + "state change on time."); /* Clear pending group operations */ pending_group_operation_timeouts_.clear(); HasCtpGroupOpCoordinator::Cleanup(); } - private: +private: void WriteAllNeededCcc(const HasDevice& device) { if (device.conn_id == GATT_INVALID_CONN_ID) { log::error("Device {} is not connected", device.addr); @@ -936,25 +938,21 @@ class HasClientImpl : public HasClient { /* Write CCC values even remote should have it */ log::info("Subscribing for notification/indications"); if (device.SupportsFeaturesNotification()) { - SubscribeForNotifications(device.conn_id, device.addr, - device.features_handle, + SubscribeForNotifications(device.conn_id, device.addr, device.features_handle, device.features_ccc_handle); } if (device.SupportsPresets()) { - SubscribeForNotifications(device.conn_id, device.addr, device.cp_handle, - device.cp_ccc_handle, device.cp_ccc_val); - SubscribeForNotifications(device.conn_id, device.addr, - device.active_preset_handle, + SubscribeForNotifications(device.conn_id, device.addr, device.cp_handle, device.cp_ccc_handle, + device.cp_ccc_val); + SubscribeForNotifications(device.conn_id, device.addr, device.active_preset_handle, device.active_preset_ccc_handle); } - if (osi_property_get_bool("persist.bluetooth.has.always_use_preset_cache", - true) == false) { - CpReadAllPresetsOperation( - HasCtpOp(device.addr, PresetCtpOpcode::READ_PRESETS, - bluetooth::le_audio::has::kStartPresetIndex, - bluetooth::le_audio::has::kMaxNumOfPresets)); + if (osi_property_get_bool("persist.bluetooth.has.always_use_preset_cache", true) == false) { + CpReadAllPresetsOperation(HasCtpOp(device.addr, PresetCtpOpcode::READ_PRESETS, + bluetooth::le_audio::has::kStartPresetIndex, + bluetooth::le_audio::has::kMaxNumOfPresets)); } } @@ -966,8 +964,7 @@ class HasClientImpl : public HasClient { NotifyHasDeviceValid(device); callbacks_->OnPresetInfo(device.addr, PresetInfoReason::ALL_PRESET_INFO, device.GetAllPresetInfo()); - callbacks_->OnActivePresetSelected(device.addr, - device.currently_active_preset); + callbacks_->OnActivePresetSelected(device.addr, device.currently_active_preset); WriteAllNeededCcc(device); } else { BTA_GATTC_ServiceSearchRequest(device.conn_id, kUuidHearingAccessService); @@ -988,7 +985,9 @@ class HasClientImpl : public HasClient { } void MarkDeviceValidIfInInitialDiscovery(HasDevice& device) { - if (device.isGattServiceValid()) return; + if (device.isGattServiceValid()) { + return; + } --device.gatt_svc_validation_steps; @@ -997,16 +996,14 @@ class HasClientImpl : public HasClient { std::vector presets_bin; if (device.SerializePresets(presets_bin)) { - btif_storage_add_leaudio_has_device(device.addr, presets_bin, - device.GetFeatures(), + btif_storage_add_leaudio_has_device(device.addr, presets_bin, device.GetFeatures(), device.currently_active_preset); } NotifyHasDeviceValid(device); } } - void OnGattWriteCcc(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, - void* user_data) { + void OnGattWriteCcc(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, void* user_data) { log::debug("handle=0x{:x}", handle); auto device = GetDevice(conn_id); @@ -1023,27 +1020,24 @@ class HasClientImpl : public HasClient { } HasGattOpContext context(user_data); - bool enabling_ntf = context.context_flags & - HasGattOpContext::kContextFlagsEnableNotification; + bool enabling_ntf = context.context_flags & HasGattOpContext::kContextFlagsEnableNotification; if (handle == device->features_ccc_handle) { - if (status == GATT_SUCCESS) + if (status == GATT_SUCCESS) { device->features_notifications_enabled = enabling_ntf; + } - } else if ((handle == device->active_preset_ccc_handle) || - (handle == device->cp_ccc_handle)) { + } else if ((handle == device->active_preset_ccc_handle) || (handle == device->cp_ccc_handle)) { /* Both of these CCC are mandatory */ if (enabling_ntf && (status != GATT_SUCCESS)) { - log::error("Failed to register for notifications on handle=0x{:x}", - handle); + log::error("Failed to register for notifications on handle=0x{:x}", handle); BTA_GATTC_Close(conn_id); return; } } } - void OnHasNotification(uint16_t conn_id, uint16_t handle, uint16_t len, - const uint8_t* value) { + void OnHasNotification(uint16_t conn_id, uint16_t handle, uint16_t len, const uint8_t* value) { auto device = GetDevice(conn_id); if (!device) { log::warn("Skipping unknown device, conn_id=0x{:x}", conn_id); @@ -1062,26 +1056,25 @@ class HasClientImpl : public HasClient { } /* Gets the device from variant, possibly searching by conn_id */ - HasDevice* GetDevice( - std::variant conn_id_device_variant) { + HasDevice* GetDevice(std::variant conn_id_device_variant) { HasDevice* device = nullptr; if (std::holds_alternative(conn_id_device_variant)) { device = std::get(conn_id_device_variant); } else { - auto it = std::find_if( - devices_.begin(), devices_.end(), - HasDevice::MatchConnId(std::get(conn_id_device_variant))); - if (it != devices_.end()) device = &(*it); + auto it = std::find_if(devices_.begin(), devices_.end(), + HasDevice::MatchConnId(std::get(conn_id_device_variant))); + if (it != devices_.end()) { + device = &(*it); + } } return device; } - void OnHasFeaturesValue( - std::variant conn_id_device_variant, - tGATT_STATUS status, uint16_t handle, uint16_t len, const uint8_t* value, - void* user_data = nullptr) { + void OnHasFeaturesValue(std::variant conn_id_device_variant, + tGATT_STATUS status, uint16_t handle, uint16_t len, const uint8_t* value, + void* user_data = nullptr) { log::debug(""); auto device = GetDevice(conn_id_device_variant); @@ -1102,8 +1095,7 @@ class HasClientImpl : public HasClient { } if (len != 1) { - log::error("Invalid features value length={} at handle=0x{:x}", len, - handle); + log::error("Invalid features value length={} at handle=0x{:x}", len, handle); BTA_GATTC_Close(device->conn_id); return; } @@ -1123,8 +1115,9 @@ class HasClientImpl : public HasClient { /* When service is not yet validated, report the available device with * features. */ - if (!device->isGattServiceValid()) + if (!device->isGattServiceValid()) { callbacks_->OnDeviceAvailable(device->addr, device->GetFeatures()); + } /* Notify features */ callbacks_->OnFeaturesUpdate(device->addr, device->GetFeatures()); @@ -1165,7 +1158,9 @@ class HasClientImpl : public HasClient { while (device.ctp_notifications_.size() != 0) { auto ntf = device.ctp_notifications_.front(); /* Process only read response events */ - if (ntf.opcode != PresetCtpOpcode::READ_PRESET_RESPONSE) break; + if (ntf.opcode != PresetCtpOpcode::READ_PRESET_RESPONSE) { + break; + } /* Update preset values */ if (ntf.preset.has_value()) { @@ -1178,10 +1173,10 @@ class HasClientImpl : public HasClient { */ if (device.isGattServiceValid()) { auto info = device.GetPresetInfo(ntf.preset.value().GetIndex()); - if (info.has_value()) - callbacks_->OnPresetInfo( - device.addr, PresetInfoReason::PRESET_INFO_REQUEST_RESPONSE, - {{info.value()}}); + if (info.has_value()) { + callbacks_->OnPresetInfo(device.addr, PresetInfoReason::PRESET_INFO_REQUEST_RESPONSE, + {{info.value()}}); + } } /* Journal update */ @@ -1202,9 +1197,9 @@ class HasClientImpl : public HasClient { /* If this was the last validation step then send the currently active * preset as well. */ - if (device.isGattServiceValid()) - callbacks_->OnActivePresetSelected(device.addr, - device.currently_active_preset); + if (device.isGattServiceValid()) { + callbacks_->OnActivePresetSelected(device.addr, device.currently_active_preset); + } } } @@ -1219,17 +1214,22 @@ class HasClientImpl : public HasClient { auto nt = device.ctp_notifications_.front(); /* Break if not a generic update anymore */ - if (nt.opcode != PresetCtpOpcode::PRESET_CHANGED) break; - if (nt.change_id != PresetCtpChangeId::PRESET_GENERIC_UPDATE) break; + if (nt.opcode != PresetCtpOpcode::PRESET_CHANGED) { + break; + } + if (nt.change_id != PresetCtpChangeId::PRESET_GENERIC_UPDATE) { + break; + } if (nt.preset.has_value()) { /* Erase in-between indices */ auto it = device.has_presets.begin(); while (it != device.has_presets.end()) { - if ((it->GetIndex() > nt.prev_index) && - (it->GetIndex() < nt.preset->GetIndex())) { + if ((it->GetIndex() > nt.prev_index) && (it->GetIndex() < nt.preset->GetIndex())) { auto info = device.GetPresetInfo(it->GetIndex()); - if (info.has_value()) deleted_infos.push_back(info.value()); + if (info.has_value()) { + deleted_infos.push_back(info.value()); + } it = device.has_presets.erase(it); @@ -1243,8 +1243,7 @@ class HasClientImpl : public HasClient { if (*info != *nt.preset) { device.has_presets.erase(nt.preset->GetIndex()); device.has_presets.insert(*nt.preset); - updated_infos.push_back( - *device.GetPresetInfo(nt.preset->GetIndex())); + updated_infos.push_back(*device.GetPresetInfo(nt.preset->GetIndex())); } } else { device.has_presets.insert(*nt.preset); @@ -1270,29 +1269,28 @@ class HasClientImpl : public HasClient { auto& group_op_coordinator = it->second; /* Here we interested only in valid preset name changes */ - if (!((group_op_coordinator.operation.opcode == - PresetCtpOpcode::WRITE_PRESET_NAME) && - group_op_coordinator.operation.name.has_value())) + if (!((group_op_coordinator.operation.opcode == PresetCtpOpcode::WRITE_PRESET_NAME) && + group_op_coordinator.operation.name.has_value())) { continue; + } /* Match preset update results with the triggering operation */ auto renamed_preset_info = std::find_if( - updated_infos.begin(), updated_infos.end(), - [&group_op_coordinator](const auto& info) { - return (group_op_coordinator.operation.name.value() == - info.preset_name); - }); - if (renamed_preset_info == updated_infos.end()) continue; + updated_infos.begin(), updated_infos.end(), + [&group_op_coordinator](const auto& info) { + return group_op_coordinator.operation.name.value() == info.preset_name; + }); + if (renamed_preset_info == updated_infos.end()) { + continue; + } if (group_op_coordinator.SetCompleted(device.addr)) { - group_op_coordinator.preset_info_verification_list.push_back( - *renamed_preset_info); + group_op_coordinator.preset_info_verification_list.push_back(*renamed_preset_info); /* Call the proper group operation completion callback */ if (group_op_coordinator.IsFullyCompleted()) { - callbacks_->OnPresetInfo( - group_op_coordinator.operation.GetGroupId(), - PresetInfoReason::PRESET_INFO_UPDATE, {*renamed_preset_info}); + callbacks_->OnPresetInfo(group_op_coordinator.operation.GetGroupId(), + PresetInfoReason::PRESET_INFO_UPDATE, {*renamed_preset_info}); pending_group_operation_timeouts_.erase(it->first); } @@ -1311,13 +1309,11 @@ class HasClientImpl : public HasClient { } if (!updated_infos.empty()) { - callbacks_->OnPresetInfo( - device.addr, PresetInfoReason::PRESET_INFO_UPDATE, updated_infos); + callbacks_->OnPresetInfo(device.addr, PresetInfoReason::PRESET_INFO_UPDATE, updated_infos); } if (!deleted_infos.empty()) { - callbacks_->OnPresetInfo(device.addr, PresetInfoReason::PRESET_DELETED, - deleted_infos); + callbacks_->OnPresetInfo(device.addr, PresetInfoReason::PRESET_DELETED, deleted_infos); } } } @@ -1331,15 +1327,18 @@ class HasClientImpl : public HasClient { auto nt = device.ctp_notifications_.front(); /* Process only preset change notifications */ - if (nt.opcode != PresetCtpOpcode::PRESET_CHANGED) break; + if (nt.opcode != PresetCtpOpcode::PRESET_CHANGED) { + break; + } auto preset = device.has_presets.extract(nt.index).value(); auto new_props = preset.GetProperties(); /* Process only the preset availability changes and then notify */ if ((nt.change_id != PresetCtpChangeId::PRESET_AVAILABLE) && - (nt.change_id != PresetCtpChangeId::PRESET_UNAVAILABLE)) + (nt.change_id != PresetCtpChangeId::PRESET_UNAVAILABLE)) { break; + } /* Availability change */ if (nt.change_id == PresetCtpChangeId::PRESET_AVAILABLE) { @@ -1347,11 +1346,12 @@ class HasClientImpl : public HasClient { } else { new_props &= !HasPreset::kPropertyAvailable; } - device.has_presets.insert( - HasPreset(preset.GetIndex(), new_props, preset.GetName())); + device.has_presets.insert(HasPreset(preset.GetIndex(), new_props, preset.GetName())); auto info = device.GetPresetInfo(nt.index); - if (info.has_value()) infos.push_back(info.value()); + if (info.has_value()) { + infos.push_back(info.value()); + } /* Journal update */ device.has_journal_.Append(HasJournalRecord(nt)); @@ -1366,8 +1366,7 @@ class HasClientImpl : public HasClient { } } - callbacks_->OnPresetInfo( - device.addr, PresetInfoReason::PRESET_AVAILABILITY_CHANGED, infos); + callbacks_->OnPresetInfo(device.addr, PresetInfoReason::PRESET_AVAILABILITY_CHANGED, infos); } void OnHasPresetDeleted(HasDevice& device) { @@ -1380,13 +1379,19 @@ class HasClientImpl : public HasClient { auto nt = device.ctp_notifications_.front(); /* Process only preset change notifications */ - if (nt.opcode != PresetCtpOpcode::PRESET_CHANGED) break; + if (nt.opcode != PresetCtpOpcode::PRESET_CHANGED) { + break; + } /* Process only the deletions and then notify */ - if (nt.change_id != PresetCtpChangeId::PRESET_DELETED) break; + if (nt.change_id != PresetCtpChangeId::PRESET_DELETED) { + break; + } auto info = device.GetPresetInfo(nt.index); - if (info.has_value()) infos.push_back(info.value()); + if (info.has_value()) { + infos.push_back(info.value()); + } if (device.has_presets.count(nt.index)) { is_deleted = true; @@ -1406,9 +1411,9 @@ class HasClientImpl : public HasClient { } } - if (is_deleted) - callbacks_->OnPresetInfo(device.addr, PresetInfoReason::PRESET_DELETED, - infos); + if (is_deleted) { + callbacks_->OnPresetInfo(device.addr, PresetInfoReason::PRESET_DELETED, infos); + } } void ProcessCtpNotificationQueue(HasDevice& device) { @@ -1446,8 +1451,7 @@ class HasClientImpl : public HasClient { } } - void OnHasCtpValueNotification(HasDevice* device, uint16_t len, - const uint8_t* value) { + void OnHasCtpValueNotification(HasDevice* device, uint16_t len, const uint8_t* value) { auto ntf_opt = HasCtpNtf::FromCharacteristicValue(len, value); if (!ntf_opt.has_value()) { log::error("Unhandled notification for device: {}", *device); @@ -1459,13 +1463,14 @@ class HasClientImpl : public HasClient { log::debug("{}", ntf); device->ctp_notifications_.push_back(ntf); - if (ntf.is_last) ProcessCtpNotificationQueue(*device); + if (ntf.is_last) { + ProcessCtpNotificationQueue(*device); + } } - void OnHasActivePresetValue( - std::variant conn_id_device_variant, - tGATT_STATUS status, uint16_t handle, uint16_t len, const uint8_t* value, - void* user_data = nullptr) { + void OnHasActivePresetValue(std::variant conn_id_device_variant, + tGATT_STATUS status, uint16_t handle, uint16_t len, + const uint8_t* value, void* user_data = nullptr) { log::debug(""); auto device = GetDevice(conn_id_device_variant); @@ -1485,8 +1490,7 @@ class HasClientImpl : public HasClient { } if (len != 1) { - log::error("Invalid preset value length={} at handle=0x{:x}", len, - handle); + log::error("Invalid preset value length={} at handle=0x{:x}", len, handle); BTA_GATTC_Close(device->conn_id); return; } @@ -1496,13 +1500,11 @@ class HasClientImpl : public HasClient { STREAM_TO_UINT8(device->currently_active_preset, pp); if (device->isGattServiceValid()) { - btif_storage_set_leaudio_has_active_preset( - device->addr, device->currently_active_preset); + btif_storage_set_leaudio_has_active_preset(device->addr, device->currently_active_preset); } /* Journal update */ - device->has_journal_.Append( - HasJournalRecord(device->currently_active_preset, false)); + device->has_journal_.Append(HasJournalRecord(device->currently_active_preset, false)); /* If svc not marked valid, this might be the last validation step. */ MarkDeviceValidIfInInitialDiscovery(*device); @@ -1536,17 +1538,17 @@ class HasClientImpl : public HasClient { break; } if (group_op_coordinator.IsFullyCompleted()) { - callbacks_->OnActivePresetSelected( - group_op_coordinator.operation.GetGroupId(), - device->currently_active_preset); + callbacks_->OnActivePresetSelected(group_op_coordinator.operation.GetGroupId(), + device->currently_active_preset); pending_group_operation_timeouts_.erase(it->first); } - if (matches) break; + if (matches) { + break; + } } } else { - callbacks_->OnActivePresetSelected(device->addr, - device->currently_active_preset); + callbacks_->OnActivePresetSelected(device->addr, device->currently_active_preset); } } } @@ -1554,47 +1556,44 @@ class HasClientImpl : public HasClient { void DeregisterNotifications(HasDevice& device) { /* Deregister from optional features notifications */ if (device.features_ccc_handle != GAP_INVALID_HANDLE) { - BTA_GATTC_DeregisterForNotifications(gatt_if_, device.addr, - device.features_handle); + BTA_GATTC_DeregisterForNotifications(gatt_if_, device.addr, device.features_handle); } /* Deregister from active presets notifications if presets exist */ if (device.active_preset_ccc_handle != GAP_INVALID_HANDLE) { - BTA_GATTC_DeregisterForNotifications(gatt_if_, device.addr, - device.active_preset_handle); + BTA_GATTC_DeregisterForNotifications(gatt_if_, device.addr, device.active_preset_handle); } /* Deregister from control point notifications */ if (device.cp_ccc_handle != GAP_INVALID_HANDLE) { - BTA_GATTC_DeregisterForNotifications(gatt_if_, device.addr, - device.cp_handle); + BTA_GATTC_DeregisterForNotifications(gatt_if_, device.addr, device.cp_handle); } } /* Cleans up after the device disconnection */ - void DoDisconnectCleanUp(HasDevice& device, - bool invalidate_gatt_service = true) { + void DoDisconnectCleanUp(HasDevice& device, bool invalidate_gatt_service = true) { log::debug(": device={}", device.addr); DeregisterNotifications(device); if (device.conn_id != GATT_INVALID_CONN_ID) { BtaGattQueue::Clean(device.conn_id); - if (invalidate_gatt_service) device.gatt_svc_validation_steps = 0xFE; + if (invalidate_gatt_service) { + device.gatt_svc_validation_steps = 0xFE; + } } /* Clear pending operations */ auto addr = device.addr; pending_operations_.erase( - std::remove_if( - pending_operations_.begin(), pending_operations_.end(), - [&addr](auto& el) { - if (std::holds_alternative(el.addr_or_group)) { - return std::get(el.addr_or_group) == addr; - } - return false; - }), - pending_operations_.end()); + std::remove_if(pending_operations_.begin(), pending_operations_.end(), + [&addr](auto& el) { + if (std::holds_alternative(el.addr_or_group)) { + return std::get(el.addr_or_group) == addr; + } + return false; + }), + pending_operations_.end()); device.ConnectionCleanUp(); } @@ -1606,8 +1605,7 @@ class HasClientImpl : public HasClient { for (const gatt::Characteristic& charac : service.characteristics) { if (charac.uuid == kUuidActivePresetIndex) { /* Find the mandatory CCC descriptor */ - uint16_t ccc_handle = - FindCccHandle(device->conn_id, charac.value_handle); + uint16_t ccc_handle = FindCccHandle(device->conn_id, charac.value_handle); if (ccc_handle == GAP_INVALID_HANDLE) { log::error("no HAS Active Preset CCC descriptor found!"); return false; @@ -1617,22 +1615,22 @@ class HasClientImpl : public HasClient { } else if (charac.uuid == kUuidHearingAidPresetControlPoint) { /* Find the mandatory CCC descriptor */ - uint16_t ccc_handle = - FindCccHandle(device->conn_id, charac.value_handle); + uint16_t ccc_handle = FindCccHandle(device->conn_id, charac.value_handle); if (ccc_handle == GAP_INVALID_HANDLE) { log::error("no HAS Control Point CCC descriptor found!"); return false; } uint8_t ccc_val = 0; - if (charac.properties & GATT_CHAR_PROP_BIT_NOTIFY) + if (charac.properties & GATT_CHAR_PROP_BIT_NOTIFY) { ccc_val |= GATT_CHAR_CLIENT_CONFIG_NOTIFICATION; + } - if (charac.properties & GATT_CHAR_PROP_BIT_INDICATE) + if (charac.properties & GATT_CHAR_PROP_BIT_INDICATE) { ccc_val |= GATT_CHAR_CLIENT_CONFIG_INDICTION; + } if (ccc_val == 0) { - log::error("Invalid properties for the control point 0x{:02x}", - charac.properties); + log::error("Invalid properties for the control point 0x{:02x}", charac.properties); return false; } @@ -1641,8 +1639,7 @@ class HasClientImpl : public HasClient { device->cp_ccc_val = ccc_val; } else if (charac.uuid == kUuidHearingAidFeatures) { /* Find the optional CCC descriptor */ - uint16_t ccc_handle = - FindCccHandle(device->conn_id, charac.value_handle); + uint16_t ccc_handle = FindCccHandle(device->conn_id, charac.value_handle); device->features_ccc_handle = ccc_handle; device->features_handle = charac.value_handle; } @@ -1656,13 +1653,13 @@ class HasClientImpl : public HasClient { std::vector presets_bin; uint8_t active_preset; - if (!btif_storage_get_leaudio_has_presets(device->addr, presets_bin, - active_preset)) + if (!btif_storage_get_leaudio_has_presets(device->addr, presets_bin, active_preset)) { return false; + } - if (!HasDevice::DeserializePresets(presets_bin.data(), presets_bin.size(), - *device)) + if (!HasDevice::DeserializePresets(presets_bin.data(), presets_bin.size(), *device)) { return false; + } log::verbose("Loading HAS service details from storage."); @@ -1670,8 +1667,9 @@ class HasClientImpl : public HasClient { /* Update features and refresh opcode support map */ uint8_t val; - if (btif_storage_get_leaudio_has_features(device->addr, val)) + if (btif_storage_get_leaudio_has_features(device->addr, val)) { device->UpdateFeatures(val); + } /* With all the details loaded we can already mark it as valid */ device->gatt_svc_validation_steps = 0; @@ -1680,9 +1678,10 @@ class HasClientImpl : public HasClient { NotifyHasDeviceValid(*device); callbacks_->OnPresetInfo(device->addr, PresetInfoReason::ALL_PRESET_INFO, device->GetAllPresetInfo()); - callbacks_->OnActivePresetSelected(device->addr, - device->currently_active_preset); - if (device->conn_id == GATT_INVALID_CONN_ID) return true; + callbacks_->OnActivePresetSelected(device->addr, device->currently_active_preset); + if (device->conn_id == GATT_INVALID_CONN_ID) { + return true; + } /* Be mistrustful here: write CCC values even remote should have it */ log::info("Subscribing for notification/indications"); @@ -1691,8 +1690,7 @@ class HasClientImpl : public HasClient { return true; } - bool StartInitialHasDetailsReadAndValidation(const gatt::Service& service, - HasDevice* device) { + bool StartInitialHasDetailsReadAndValidation(const gatt::Service& service, HasDevice* device) { // Validate service structure if (device->features_handle == GAP_INVALID_HANDLE) { /* Missing key characteristic */ @@ -1701,8 +1699,12 @@ class HasClientImpl : public HasClient { } if (device->cp_handle != GAP_INVALID_HANDLE) { - if (device->active_preset_handle == GAP_INVALID_HANDLE) return false; - if (device->active_preset_ccc_handle == GAP_INVALID_HANDLE) return false; + if (device->active_preset_handle == GAP_INVALID_HANDLE) { + return false; + } + if (device->active_preset_ccc_handle == GAP_INVALID_HANDLE) { + return false; + } } /* Number of reads or notifications required to validate the service */ @@ -1710,19 +1712,18 @@ class HasClientImpl : public HasClient { /* Read the initial features */ BtaGattQueue::ReadCharacteristic( - device->conn_id, device->features_handle, - [](uint16_t conn_id, tGATT_STATUS status, uint16_t handle, uint16_t len, - uint8_t* value, void* user_data) { - if (instance) - instance->OnHasFeaturesValue(conn_id, status, handle, len, value, - user_data); - }, - nullptr); + device->conn_id, device->features_handle, + [](uint16_t conn_id, tGATT_STATUS status, uint16_t handle, uint16_t len, uint8_t* value, + void* user_data) { + if (instance) { + instance->OnHasFeaturesValue(conn_id, status, handle, len, value, user_data); + } + }, + nullptr); /* Register for features notifications */ if (device->SupportsFeaturesNotification()) { - SubscribeForNotifications(device->conn_id, device->addr, - device->features_handle, + SubscribeForNotifications(device->conn_id, device->addr, device->features_handle, device->features_ccc_handle); } else { log::warn("server does not support features notification"); @@ -1733,34 +1734,29 @@ class HasClientImpl : public HasClient { */ if (device->SupportsPresets()) { /* Subscribe for active preset notifications */ - SubscribeForNotifications(device->conn_id, device->addr, - device->active_preset_handle, + SubscribeForNotifications(device->conn_id, device->addr, device->active_preset_handle, device->active_preset_ccc_handle); - SubscribeForNotifications(device->conn_id, device->addr, - device->cp_handle, device->cp_ccc_handle, - device->cp_ccc_val); + SubscribeForNotifications(device->conn_id, device->addr, device->cp_handle, + device->cp_ccc_handle, device->cp_ccc_val); /* Get all the presets */ - CpReadAllPresetsOperation( - HasCtpOp(device->addr, PresetCtpOpcode::READ_PRESETS, - bluetooth::le_audio::has::kStartPresetIndex, - bluetooth::le_audio::has::kMaxNumOfPresets)); + CpReadAllPresetsOperation(HasCtpOp(device->addr, PresetCtpOpcode::READ_PRESETS, + bluetooth::le_audio::has::kStartPresetIndex, + bluetooth::le_audio::has::kMaxNumOfPresets)); /* Read the current active preset index */ BtaGattQueue::ReadCharacteristic( - device->conn_id, device->active_preset_handle, - [](uint16_t conn_id, tGATT_STATUS status, uint16_t handle, - uint16_t len, uint8_t* value, void* user_data) { - if (instance) - instance->OnHasActivePresetValue(conn_id, status, handle, len, - value, user_data); - }, - nullptr); + device->conn_id, device->active_preset_handle, + [](uint16_t conn_id, tGATT_STATUS status, uint16_t handle, uint16_t len, + uint8_t* value, void* user_data) { + if (instance) { + instance->OnHasActivePresetValue(conn_id, status, handle, len, value, user_data); + } + }, + nullptr); } else { - log::warn( - "server can only report HAS features, other functionality is " - "disabled"); + log::warn("server can only report HAS features, other functionality is disabled"); } return true; @@ -1772,10 +1768,14 @@ class HasClientImpl : public HasClient { auto* device = static_cast(context); /* Initially validate and store GATT service discovery data */ - if (!CacheAttributeHandles(service, device)) return false; + if (!CacheAttributeHandles(service, device)) { + return false; + } /* If deatails are loaded from storage we are done here */ - if (LoadHasDetailsFromStorage(device)) return true; + if (LoadHasDetailsFromStorage(device)) { + return true; + } /* No storred details - read all the details and validate */ return StartInitialHasDetailsReadAndValidation(service, device); @@ -1807,7 +1807,7 @@ class HasClientImpl : public HasClient { case BTA_GATTC_ENC_CMPL_CB_EVT: OnLeEncryptionComplete(p_data->enc_cmpl.remote_bda, - BTM_IsEncrypted(p_data->enc_cmpl.remote_bda, BT_TRANSPORT_LE)); + BTM_IsEncrypted(p_data->enc_cmpl.remote_bda, BT_TRANSPORT_LE)); break; case BTA_GATTC_SRVC_CHG_EVT: @@ -1824,19 +1824,18 @@ class HasClientImpl : public HasClient { } void OnGattConnected(const tBTA_GATTC_OPEN& evt) { - log::info("{}, conn_id=0x{:04x}, transport={}, status={}(0x{:02x})", - evt.remote_bda, evt.conn_id, bt_transport_text(evt.transport), - gatt_status_text(evt.status), evt.status); + log::info("{}, conn_id=0x{:04x}, transport={}, status={}(0x{:02x})", evt.remote_bda, + evt.conn_id, bt_transport_text(evt.transport), gatt_status_text(evt.status), + evt.status); if (evt.transport != BT_TRANSPORT_LE) { - log::warn("Only LE connection is allowed (transport {})", - bt_transport_text(evt.transport)); + log::warn("Only LE connection is allowed (transport {})", bt_transport_text(evt.transport)); BTA_GATTC_Close(evt.conn_id); return; } - auto device = std::find_if(devices_.begin(), devices_.end(), - HasDevice::MatchAddress(evt.remote_bda)); + auto device = + std::find_if(devices_.begin(), devices_.end(), HasDevice::MatchAddress(evt.remote_bda)); if (device == devices_.end()) { log::warn("Skipping unknown device, address={}", evt.remote_bda); BTA_GATTC_Close(evt.conn_id); @@ -1851,8 +1850,7 @@ class HasClientImpl : public HasClient { log::warn("Failed to connect to server device"); devices_.erase(device); - callbacks_->OnConnectionState(ConnectionState::DISCONNECTED, - evt.remote_bda); + callbacks_->OnConnectionState(ConnectionState::DISCONNECTED, evt.remote_bda); return; } @@ -1872,11 +1870,10 @@ class HasClientImpl : public HasClient { return; } - int result = BTM_SetEncryption(device->addr, BT_TRANSPORT_LE, nullptr, - nullptr, BTM_BLE_SEC_ENCRYPT); + int result = + BTM_SetEncryption(device->addr, BT_TRANSPORT_LE, nullptr, nullptr, BTM_BLE_SEC_ENCRYPT); - log::info("Encryption required for {}. Request result: 0x{:02x}", - device->addr, result); + log::info("Encryption required for {}. Request result: 0x{:02x}", device->addr, result); if (result == BTM_ERR_KEY_MISSING) { log::error("Link key unknown for {}, disconnect profile", device->addr); @@ -1885,29 +1882,27 @@ class HasClientImpl : public HasClient { } void OnGattDisconnected(const tBTA_GATTC_CLOSE& evt) { - auto device = std::find_if(devices_.begin(), devices_.end(), - HasDevice::MatchAddress(evt.remote_bda)); + auto device = + std::find_if(devices_.begin(), devices_.end(), HasDevice::MatchAddress(evt.remote_bda)); if (device == devices_.end()) { - log::warn("Skipping unknown device disconnect, conn_id=0x{:x}", - evt.conn_id); + log::warn("Skipping unknown device disconnect, conn_id=0x{:x}", evt.conn_id); return; } - log::debug("device={}: reason=0x{:x}", device->addr, - static_cast(evt.reason)); + log::debug("device={}: reason=0x{:x}", device->addr, static_cast(evt.reason)); /* Don't notify disconnect state for background connection that failed */ - if (device->is_connecting_actively || device->isGattServiceValid()) - callbacks_->OnConnectionState(ConnectionState::DISCONNECTED, - evt.remote_bda); + if (device->is_connecting_actively || device->isGattServiceValid()) { + callbacks_->OnConnectionState(ConnectionState::DISCONNECTED, evt.remote_bda); + } - auto peer_disconnected = (evt.reason == GATT_CONN_TIMEOUT) || - (evt.reason == GATT_CONN_TERMINATE_PEER_USER); + auto peer_disconnected = + (evt.reason == GATT_CONN_TIMEOUT) || (evt.reason == GATT_CONN_TERMINATE_PEER_USER); DoDisconnectCleanUp(*device, peer_disconnected ? false : true); /* Connect in background - is this ok? */ - if (peer_disconnected) - BTA_GATTC_Open(gatt_if_, device->addr, BTM_BLE_BKG_CONNECT_ALLOW_LIST, - false); + if (peer_disconnected) { + BTA_GATTC_Open(gatt_if_, device->addr, BTM_BLE_BKG_CONNECT_ALLOW_LIST, false); + } } void OnGattServiceSearchComplete(const tBTA_GATTC_SEARCH_CMPL& evt) { @@ -1935,14 +1930,11 @@ class HasClientImpl : public HasClient { return; } - const std::list* all_services = - BTA_GATTC_GetServices(device->conn_id); + const std::list* all_services = BTA_GATTC_GetServices(device->conn_id); - auto service = - std::find_if(all_services->begin(), all_services->end(), - [](const gatt::Service& svc) { - return svc.uuid == kUuidHearingAccessService; - }); + auto service = std::find_if( + all_services->begin(), all_services->end(), + [](const gatt::Service& svc) { return svc.uuid == kUuidHearingAccessService; }); if (service == all_services->end()) { log::error("No service found"); BTA_GATTC_Close(device->conn_id); @@ -1961,10 +1953,12 @@ class HasClientImpl : public HasClient { void OnGattNotification(const tBTA_GATTC_NOTIFY& evt) { /* Reject invalid lengths */ if (evt.len > GATT_MAX_ATTR_LEN) { - log::error("rejected BTA_GATTC_NOTIF_EVT. is_notify = {}, len={}", - evt.is_notify, static_cast(evt.len)); + log::error("rejected BTA_GATTC_NOTIF_EVT. is_notify = {}, len={}", evt.is_notify, + static_cast(evt.len)); + } + if (!evt.is_notify) { + BTA_GATTC_SendIndConfirm(evt.conn_id, evt.cid); } - if (!evt.is_notify) BTA_GATTC_SendIndConfirm(evt.conn_id, evt.cid); OnHasNotification(evt.conn_id, evt.handle, evt.len, evt.value); } @@ -1972,8 +1966,7 @@ class HasClientImpl : public HasClient { void OnLeEncryptionComplete(const RawAddress& address, bool success) { log::debug("{}", address); - auto device = std::find_if(devices_.begin(), devices_.end(), - HasDevice::MatchAddress(address)); + auto device = std::find_if(devices_.begin(), devices_.end(), HasDevice::MatchAddress(address)); if (device == devices_.end()) { log::warn("Skipping unknown device{}", address); return; @@ -1989,8 +1982,7 @@ class HasClientImpl : public HasClient { if (device->isGattServiceValid()) { instance->OnEncrypted(*device); } else { - BTA_GATTC_ServiceSearchRequest(device->conn_id, - kUuidHearingAccessService); + BTA_GATTC_ServiceSearchRequest(device->conn_id, kUuidHearingAccessService); } } @@ -2016,8 +2008,7 @@ class HasClientImpl : public HasClient { } void OnGattServiceChangeEvent(const RawAddress& address) { - auto device = std::find_if(devices_.begin(), devices_.end(), - HasDevice::MatchAddress(address)); + auto device = std::find_if(devices_.begin(), devices_.end(), HasDevice::MatchAddress(address)); if (device == devices_.end()) { log::warn("Skipping unknown device: {}", address); return; @@ -2027,8 +2018,7 @@ class HasClientImpl : public HasClient { } void OnGattServiceDiscoveryDoneEvent(const RawAddress& address) { - auto device = std::find_if(devices_.begin(), devices_.end(), - HasDevice::MatchAddress(address)); + auto device = std::find_if(devices_.begin(), devices_.end(), HasDevice::MatchAddress(address)); if (device == devices_.end()) { log::warn("Skipping unknown device: {}", address); return; @@ -2036,53 +2026,53 @@ class HasClientImpl : public HasClient { log::debug("address={}", address); - if (!device->isGattServiceValid()) - BTA_GATTC_ServiceSearchRequest(device->conn_id, - kUuidHearingAccessService); + if (!device->isGattServiceValid()) { + BTA_GATTC_ServiceSearchRequest(device->conn_id, kUuidHearingAccessService); + } } static uint16_t FindCccHandle(uint16_t conn_id, uint16_t char_handle) { - const gatt::Characteristic* p_char = - BTA_GATTC_GetCharacteristic(conn_id, char_handle); + const gatt::Characteristic* p_char = BTA_GATTC_GetCharacteristic(conn_id, char_handle); if (!p_char) { log::warn("No such characteristic: {}", char_handle); return GAP_INVALID_HANDLE; } for (const gatt::Descriptor& desc : p_char->descriptors) { - if (desc.uuid == Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)) + if (desc.uuid == Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)) { return desc.handle; + } } return GAP_INVALID_HANDLE; } - void SubscribeForNotifications( - uint16_t conn_id, const RawAddress& address, uint16_t value_handle, - uint16_t ccc_handle, - uint16_t ccc_val = GATT_CHAR_CLIENT_CONFIG_NOTIFICATION) { + void SubscribeForNotifications(uint16_t conn_id, const RawAddress& address, uint16_t value_handle, + uint16_t ccc_handle, + uint16_t ccc_val = GATT_CHAR_CLIENT_CONFIG_NOTIFICATION) { if (value_handle != GAP_INVALID_HANDLE) { tGATT_STATUS register_status = - BTA_GATTC_RegisterForNotifications(gatt_if_, address, value_handle); - log::debug( - "BTA_GATTC_RegisterForNotifications, status=0x{:x} value=0x{:x} " - "ccc=0x{:x}", - register_status, value_handle, ccc_handle); + BTA_GATTC_RegisterForNotifications(gatt_if_, address, value_handle); + log::debug("BTA_GATTC_RegisterForNotifications, status=0x{:x} value=0x{:x} ccc=0x{:x}", + register_status, value_handle, ccc_handle); - if (register_status != GATT_SUCCESS) return; + if (register_status != GATT_SUCCESS) { + return; + } } std::vector value(2); uint8_t* value_ptr = value.data(); UINT16_TO_STREAM(value_ptr, ccc_val); BtaGattQueue::WriteDescriptor( - conn_id, ccc_handle, std::move(value), GATT_WRITE, - [](uint16_t conn_id, tGATT_STATUS status, uint16_t value_handle, - uint16_t len, const uint8_t* value, void* data) { - if (instance) - instance->OnGattWriteCcc(conn_id, status, value_handle, data); - }, - HasGattOpContext(HasGattOpContext::kContextFlagsEnableNotification)); + conn_id, ccc_handle, std::move(value), GATT_WRITE, + [](uint16_t conn_id, tGATT_STATUS status, uint16_t value_handle, uint16_t len, + const uint8_t* value, void* data) { + if (instance) { + instance->OnGattWriteCcc(conn_id, status, value_handle, data); + } + }, + HasGattOpContext(HasGattOpContext::kContextFlagsEnableNotification)); } uint8_t gatt_if_; @@ -2090,8 +2080,7 @@ class HasClientImpl : public HasClient { std::list devices_; std::list pending_operations_; - typedef std::map - has_operation_timeouts_t; + typedef std::map has_operation_timeouts_t; has_operation_timeouts_t pending_group_operation_timeouts_; }; @@ -2101,8 +2090,7 @@ alarm_t* HasCtpGroupOpCoordinator::operation_timeout_timer = nullptr; size_t HasCtpGroupOpCoordinator::ref_cnt = 0u; alarm_callback_t HasCtpGroupOpCoordinator::cb = [](void*) {}; -void HasClient::Initialize(bluetooth::has::HasClientCallbacks* callbacks, - base::Closure initCb) { +void HasClient::Initialize(bluetooth::has::HasClientCallbacks* callbacks, base::Closure initCb) { std::scoped_lock lock(instance_mutex); if (instance) { log::error("Already initialized!"); @@ -2110,7 +2098,9 @@ void HasClient::Initialize(bluetooth::has::HasClientCallbacks* callbacks, } HasCtpGroupOpCoordinator::Initialize([](void* p) { - if (instance) instance->OnGroupOpCoordinatorTimeout(p); + if (instance) { + instance->OnGroupOpCoordinatorTimeout(p); + } }); instance = new HasClientImpl(callbacks, initCb); } @@ -2120,16 +2110,15 @@ bool HasClient::IsHasClientRunning() { return instance; } HasClient* HasClient::Get(void) { log::assert_that(instance != nullptr, "assert failed: instance != nullptr"); return instance; -}; +} -void HasClient::AddFromStorage(const RawAddress& addr, uint8_t features, - uint16_t is_acceptlisted) { +void HasClient::AddFromStorage(const RawAddress& addr, uint8_t features, uint16_t is_acceptlisted) { if (!instance) { log::error("Not initialized yet"); } instance->AddFromStorage(addr, features, is_acceptlisted); -}; +} void HasClient::CleanUp() { std::scoped_lock lock(instance_mutex); @@ -2142,13 +2131,14 @@ void HasClient::CleanUp() { } HasCtpGroupOpCoordinator::Cleanup(); -}; +} void HasClient::DebugDump(int fd) { std::scoped_lock lock(instance_mutex); dprintf(fd, "Hearing Access Service Client:\n"); - if (instance) + if (instance) { instance->Dump(fd); - else + } else { dprintf(fd, " no instance\n\n"); + } } diff --git a/system/bta/has/has_client_test.cc b/system/bta/has/has_client_test.cc index 8724823544a..24a1c9081d8 100644 --- a/system/bta/has/has_client_test.cc +++ b/system/bta/has/has_client_test.cc @@ -82,8 +82,7 @@ using ::testing::WithArg; RawAddress GetTestAddress(int index) { EXPECT_LT(index, UINT8_MAX); - RawAddress result = { - {0xC0, 0xDE, 0xC0, 0xDE, 0x00, static_cast(index)}}; + RawAddress result = {{0xC0, 0xDE, 0xC0, 0xDE, 0x00, static_cast(index)}}; return result; } @@ -92,48 +91,40 @@ static uint16_t GetTestConnId(const RawAddress& address) { } class MockHasCallbacks : public HasClientCallbacks { - public: +public: MockHasCallbacks() = default; MockHasCallbacks(const MockHasCallbacks&) = delete; MockHasCallbacks& operator=(const MockHasCallbacks&) = delete; ~MockHasCallbacks() override = default; - MOCK_METHOD((void), OnConnectionState, - (ConnectionState state, const RawAddress& address), (override)); - MOCK_METHOD((void), OnDeviceAvailable, - (const RawAddress& address, uint8_t features), (override)); - MOCK_METHOD((void), OnFeaturesUpdate, - (const RawAddress& address, uint8_t features), (override)); - MOCK_METHOD((void), OnActivePresetSelected, - ((std::variant addr_or_group_id), - uint8_t preset_index), + MOCK_METHOD((void), OnConnectionState, (ConnectionState state, const RawAddress& address), (override)); + MOCK_METHOD((void), OnDeviceAvailable, (const RawAddress& address, uint8_t features), (override)); + MOCK_METHOD((void), OnFeaturesUpdate, (const RawAddress& address, uint8_t features), (override)); + MOCK_METHOD((void), OnActivePresetSelected, + ((std::variant addr_or_group_id), uint8_t preset_index), (override)); MOCK_METHOD((void), OnActivePresetSelectError, - ((std::variant addr_or_group_id), - ErrorCode result), - (override)); + ((std::variant addr_or_group_id), ErrorCode result), (override)); MOCK_METHOD((void), OnPresetInfo, - ((std::variant addr_or_group_id), - PresetInfoReason change_id, + ((std::variant addr_or_group_id), PresetInfoReason change_id, std::vector preset_change_records), (override)); MOCK_METHOD((void), OnPresetInfoError, - ((std::variant addr_or_group_id), - uint8_t preset_index, ErrorCode error_code), + ((std::variant addr_or_group_id), uint8_t preset_index, + ErrorCode error_code), (override)); MOCK_METHOD((void), OnSetPresetNameError, - ((std::variant addr_or_group_id), - uint8_t preset_index, ErrorCode error_code), + ((std::variant addr_or_group_id), uint8_t preset_index, + ErrorCode error_code), (override)); }; class HasClientTestBase : public ::testing::Test { - protected: +protected: std::map current_peer_active_preset_idx_; std::map current_peer_features_val_; - std::map> - current_peer_presets_; + std::map> current_peer_presets_; struct HasDbBuilder { bool has; @@ -166,491 +157,463 @@ class HasClientTestBase : public ::testing::Test { gatt::DatabaseBuilder bob; /* Generic Access Service */ - bob.AddService(kGapSvcStartHdl, kGapSvcEndHdl, Uuid::From16Bit(0x1800), - true); + bob.AddService(kGapSvcStartHdl, kGapSvcEndHdl, Uuid::From16Bit(0x1800), true); /* Device Name Char. */ - bob.AddCharacteristic(kGapDeviceNameValHdl - 1, kGapDeviceNameValHdl, - Uuid::From16Bit(0x2a00), GATT_CHAR_PROP_BIT_READ); + bob.AddCharacteristic(kGapDeviceNameValHdl - 1, kGapDeviceNameValHdl, Uuid::From16Bit(0x2a00), + GATT_CHAR_PROP_BIT_READ); /* 0x0004-0x000f left empty on purpose */ if (has) { bob.AddService(kSvcStartHdl, kSvcEndHdl, - ::bluetooth::le_audio::has::kUuidHearingAccessService, - true); + ::bluetooth::le_audio::has::kUuidHearingAccessService, true); if (features) { bob.AddCharacteristic( - kFeaturesValHdl - 1, kFeaturesValHdl, - ::bluetooth::le_audio::has::kUuidHearingAidFeatures, - GATT_CHAR_PROP_BIT_READ | - (features_ntf ? GATT_CHAR_PROP_BIT_NOTIFY : 0)); + kFeaturesValHdl - 1, kFeaturesValHdl, + ::bluetooth::le_audio::has::kUuidHearingAidFeatures, + GATT_CHAR_PROP_BIT_READ | (features_ntf ? GATT_CHAR_PROP_BIT_NOTIFY : 0)); if (features_ntf) { - bob.AddDescriptor(kFeaturesValHdl + 1, - Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); + bob.AddDescriptor(kFeaturesValHdl + 1, Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); } } if (preset_cp) { - bob.AddCharacteristic( - kPresetsCtpValHdl - 1, kPresetsCtpValHdl, - ::bluetooth::le_audio::has::kUuidHearingAidPresetControlPoint, - GATT_CHAR_PROP_BIT_WRITE | - (preset_cp_ntf ? GATT_CHAR_PROP_BIT_NOTIFY : 0) | - (preset_cp_ind ? GATT_CHAR_PROP_BIT_INDICATE : 0)); + bob.AddCharacteristic(kPresetsCtpValHdl - 1, kPresetsCtpValHdl, + ::bluetooth::le_audio::has::kUuidHearingAidPresetControlPoint, + GATT_CHAR_PROP_BIT_WRITE | + (preset_cp_ntf ? GATT_CHAR_PROP_BIT_NOTIFY : 0) | + (preset_cp_ind ? GATT_CHAR_PROP_BIT_INDICATE : 0)); if (preset_cp_ntf || preset_cp_ind) { - bob.AddDescriptor(kPresetsCtpValHdl + 1, - Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); + bob.AddDescriptor(kPresetsCtpValHdl + 1, Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); } } if (active_preset_idx) { - bob.AddCharacteristic( - kActivePresetIndexValHdl - 1, kActivePresetIndexValHdl, - ::bluetooth::le_audio::has::kUuidActivePresetIndex, - GATT_CHAR_PROP_BIT_READ | - (active_preset_idx_ntf ? GATT_CHAR_PROP_BIT_NOTIFY : 0)); + bob.AddCharacteristic(kActivePresetIndexValHdl - 1, kActivePresetIndexValHdl, + ::bluetooth::le_audio::has::kUuidActivePresetIndex, + GATT_CHAR_PROP_BIT_READ | + (active_preset_idx_ntf ? GATT_CHAR_PROP_BIT_NOTIFY : 0)); - if (active_preset_idx_ntf) + if (active_preset_idx_ntf) { bob.AddDescriptor(kActivePresetIndexValHdl + 1, Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); + } } } /* GATTS */ /* 0x001F-0x0090 left empty on purpose */ - bob.AddService(kGattSvcStartHdl, kGattSvcEndHdl, - Uuid::From16Bit(UUID_SERVCLASS_GATT_SERVER), true); + bob.AddService(kGattSvcStartHdl, kGattSvcEndHdl, Uuid::From16Bit(UUID_SERVCLASS_GATT_SERVER), + true); bob.AddCharacteristic(kGattSvcChangedValHdl - 1, kGattSvcChangedValHdl, - Uuid::From16Bit(GATT_UUID_GATT_SRV_CHGD), - GATT_CHAR_PROP_BIT_NOTIFY); - bob.AddDescriptor(kGattSvcChangedValHdl + 1, - Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); + Uuid::From16Bit(GATT_UUID_GATT_SRV_CHGD), GATT_CHAR_PROP_BIT_NOTIFY); + bob.AddDescriptor(kGattSvcChangedValHdl + 1, Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); return bob.Build(); - }; + } }; - const gatt::Characteristic* FindCharacteristicByValueHandle( - const gatt::Service* svc, uint16_t handle) { - if (svc == nullptr) return nullptr; + const gatt::Characteristic* FindCharacteristicByValueHandle(const gatt::Service* svc, + uint16_t handle) { + if (svc == nullptr) { + return nullptr; + } - auto it = - std::find_if(svc->characteristics.cbegin(), svc->characteristics.cend(), - [handle](const auto& characteristic) { - return characteristic.value_handle == handle; - }); + auto it = std::find_if( + svc->characteristics.cbegin(), svc->characteristics.cend(), + [handle](const auto& characteristic) { return characteristic.value_handle == handle; }); return (it != svc->characteristics.cend()) ? &(*it) : nullptr; } void set_sample_database( - const RawAddress& address, HasDbBuilder& builder, - uint8_t features_val = 0x0, - std::optional> presets_op = - std::nullopt) { + const RawAddress& address, HasDbBuilder& builder, uint8_t features_val = 0x0, + std::optional> presets_op = std::nullopt) { uint16_t conn_id = GetTestConnId(address); /* For some test cases these defaults are enough */ - if (!presets_op) + if (!presets_op) { presets_op = {{ - HasPreset(6, HasPreset::kPropertyAvailable, "Universal"), - HasPreset( - 55, HasPreset::kPropertyAvailable | HasPreset::kPropertyWritable, - "YourPreset55"), + HasPreset(6, HasPreset::kPropertyAvailable, "Universal"), + HasPreset(55, HasPreset::kPropertyAvailable | HasPreset::kPropertyWritable, + "YourPreset55"), }}; + } auto& presets = presets_op.value(); auto const active_preset = presets.begin(); services_map[conn_id] = builder.Build().Services(); current_peer_features_val_.insert_or_assign(conn_id, features_val); - current_peer_active_preset_idx_.insert_or_assign(conn_id, - active_preset->GetIndex()); + current_peer_active_preset_idx_.insert_or_assign(conn_id, active_preset->GetIndex()); current_peer_presets_.insert_or_assign(conn_id, std::move(presets)); ON_CALL(gatt_queue, ReadCharacteristic(conn_id, _, _, _)) - .WillByDefault(Invoke([this](uint16_t conn_id, uint16_t handle, - GATT_READ_OP_CB cb, void* cb_data) { - auto* svc = gatt::FindService(services_map[conn_id], handle); - if (svc == nullptr) return; - - std::vector value; - tGATT_STATUS status = GATT_SUCCESS; - - switch (handle) { - case HasDbBuilder::kGapDeviceNameValHdl: - value.resize(20); - break; - case HasDbBuilder::kFeaturesValHdl: - value.resize(1); - value[0] = current_peer_features_val_.at(conn_id); - break; - case HasDbBuilder::kActivePresetIndexValHdl: - value.resize(1); - value[0] = current_peer_active_preset_idx_.at(conn_id); - break; - case HasDbBuilder::kPresetsCtpValHdl: - /* passthrough */ - default: - status = GATT_READ_NOT_PERMIT; - break; - } - - if (cb) - cb(conn_id, status, handle, value.size(), value.data(), cb_data); - })); + .WillByDefault(Invoke( + [this](uint16_t conn_id, uint16_t handle, GATT_READ_OP_CB cb, void* cb_data) { + auto* svc = gatt::FindService(services_map[conn_id], handle); + if (svc == nullptr) { + return; + } + + std::vector value; + tGATT_STATUS status = GATT_SUCCESS; + + switch (handle) { + case HasDbBuilder::kGapDeviceNameValHdl: + value.resize(20); + break; + case HasDbBuilder::kFeaturesValHdl: + value.resize(1); + value[0] = current_peer_features_val_.at(conn_id); + break; + case HasDbBuilder::kActivePresetIndexValHdl: + value.resize(1); + value[0] = current_peer_active_preset_idx_.at(conn_id); + break; + case HasDbBuilder::kPresetsCtpValHdl: + /* passthrough */ + default: + status = GATT_READ_NOT_PERMIT; + break; + } + + if (cb) { + cb(conn_id, status, handle, value.size(), value.data(), cb_data); + } + })); /* Default action for the Control Point operation writes */ ON_CALL(gatt_queue, - WriteCharacteristic(conn_id, HasDbBuilder::kPresetsCtpValHdl, _, - GATT_WRITE, _, _)) - .WillByDefault(Invoke([this, address](uint16_t conn_id, uint16_t handle, - std::vector value, - tGATT_WRITE_TYPE write_type, - GATT_WRITE_OP_CB cb, - void* cb_data) { - auto pp = value.data(); - auto len = value.size(); - uint8_t op, index, num_of_indices; - - const bool indicate = false; - - if (len < 1) { - if (cb) - cb(conn_id, GATT_INVALID_ATTR_LEN, handle, value.size(), - value.data(), cb_data); - return; - } + WriteCharacteristic(conn_id, HasDbBuilder::kPresetsCtpValHdl, _, GATT_WRITE, _, _)) + .WillByDefault(Invoke([this, address](uint16_t conn_id, uint16_t handle, + std::vector value, + tGATT_WRITE_TYPE write_type, GATT_WRITE_OP_CB cb, + void* cb_data) { + auto pp = value.data(); + auto len = value.size(); + uint8_t op, index, num_of_indices; - STREAM_TO_UINT8(op, pp) - --len; - if (op > static_cast>( - ::bluetooth::le_audio::has::PresetCtpOpcode::OP_MAX_)) { - /* Invalid Opcode */ - if (cb) - cb(conn_id, (tGATT_STATUS)0x80, handle, value.size(), - value.data(), cb_data); - return; - } + const bool indicate = false; - switch ( - static_cast<::bluetooth::le_audio::has::PresetCtpOpcode>(op)) { - case ::bluetooth::le_audio::has::PresetCtpOpcode::READ_PRESETS: - if (len < 2) { - if (cb) - cb(conn_id, GATT_INVALID_ATTR_LEN, handle, value.size(), - value.data(), cb_data); - - } else { - STREAM_TO_UINT8(index, pp); - STREAM_TO_UINT8(num_of_indices, pp); - len -= 2; - ASSERT_EQ(0u, len); - - InjectNotifyReadPresetsResponse(conn_id, address, handle, value, - indicate, index, num_of_indices, - cb, cb_data); - } - break; - - case ::bluetooth::le_audio::has::PresetCtpOpcode:: - SET_ACTIVE_PRESET: { if (len < 1) { - if (cb) - cb(conn_id, GATT_INVALID_ATTR_LEN, handle, value.size(), - value.data(), cb_data); - break; - } - STREAM_TO_UINT8(index, pp); - --len; - ASSERT_EQ(0u, len); - - auto presets = current_peer_presets_.at(conn_id); - if (presets.count(index)) { - current_peer_active_preset_idx_.insert_or_assign(conn_id, - index); - if (cb) - cb(conn_id, GATT_SUCCESS, handle, value.size(), value.data(), - cb_data); - InjectActivePresetNotification(conn_id, address, handle, value, - index, cb, cb_data); - } else { - /* Preset Operation Not Possible */ - if (cb) - cb(conn_id, (tGATT_STATUS)0x83, handle, value.size(), - value.data(), cb_data); - } - } break; - - case ::bluetooth::le_audio::has::PresetCtpOpcode:: - SET_ACTIVE_PRESET_SYNC: { - auto features = current_peer_features_val_.at(conn_id); - if ((features & ::bluetooth::has:: - kFeatureBitPresetSynchronizationSupported) == - 0) { - /* Synchronization Not Supported */ - if (cb) - cb(conn_id, (tGATT_STATUS)0x82, handle, value.size(), - value.data(), cb_data); - break; + if (cb) { + cb(conn_id, GATT_INVALID_ATTR_LEN, handle, value.size(), value.data(), cb_data); + } + return; } - if (len < 1) { - if (cb) - cb(conn_id, GATT_INVALID_ATTR_LEN, handle, value.size(), - value.data(), cb_data); - break; - } - STREAM_TO_UINT8(index, pp); + STREAM_TO_UINT8(op, pp) --len; - ASSERT_EQ(0u, len); - - auto csis_api = CsisClient::Get(); - int group_id = bluetooth::groups::kGroupUnknown; - if (csis_api != nullptr) { - group_id = csis_api->GetGroupId( - address, ::bluetooth::le_audio::uuid::kCapServiceUuid); - } - - if (group_id != bluetooth::groups::kGroupUnknown) { - if (cb) - cb(conn_id, GATT_SUCCESS, handle, value.size(), value.data(), - cb_data); - /* Send notification from all grouped devices */ - auto addresses = csis_api->GetDeviceList(group_id); - for (auto& addr : addresses) { - auto conn = GetTestConnId(addr); - InjectActivePresetNotification(conn, addr, handle, value, - index, cb, cb_data); + if (op > + static_cast>( + ::bluetooth::le_audio::has::PresetCtpOpcode::OP_MAX_)) { + /* Invalid Opcode */ + if (cb) { + cb(conn_id, (tGATT_STATUS)0x80, handle, value.size(), value.data(), cb_data); } - } else { - /* Preset Operation Not Possible */ - if (cb) - cb(conn_id, (tGATT_STATUS)0x83, handle, value.size(), - value.data(), cb_data); - } - } break; - - case ::bluetooth::le_audio::has::PresetCtpOpcode::SET_NEXT_PRESET: { - ASSERT_EQ(0u, len); - ASSERT_NE(0u, current_peer_active_preset_idx_.count(conn_id)); - ASSERT_NE(0u, current_peer_presets_.count(conn_id)); - - auto current_preset = current_peer_active_preset_idx_.at(conn_id); - auto presets = current_peer_presets_.at(conn_id); - auto current = presets.find(current_preset); - if (current != presets.end()) { - ++current; - if (current == presets.end()) current = presets.begin(); - - current_peer_active_preset_idx_.insert_or_assign( - conn_id, current->GetIndex()); - InjectActivePresetNotification(conn_id, address, handle, value, - current->GetIndex(), cb, - cb_data); - - } else { - /* Preset Operation Not Possible */ - if (cb) - cb(conn_id, (tGATT_STATUS)0x83, handle, value.size(), - value.data(), cb_data); + return; } - } break; - - case ::bluetooth::le_audio::has::PresetCtpOpcode::SET_PREV_PRESET: { - ASSERT_EQ(0u, len); - ASSERT_NE(0u, current_peer_active_preset_idx_.count(conn_id)); - ASSERT_NE(0u, current_peer_presets_.count(conn_id)); - - auto current_preset = current_peer_active_preset_idx_.at(conn_id); - auto presets = current_peer_presets_.at(conn_id); - auto rit = presets.rbegin(); - while (rit != presets.rend()) { - if (rit->GetIndex() == current_preset) { - rit++; - /* Wrap around */ - if (rit == presets.rend()) { - rit = presets.rbegin(); + + switch (static_cast<::bluetooth::le_audio::has::PresetCtpOpcode>(op)) { + case ::bluetooth::le_audio::has::PresetCtpOpcode::READ_PRESETS: + if (len < 2) { + if (cb) { + cb(conn_id, GATT_INVALID_ATTR_LEN, handle, value.size(), value.data(), + cb_data); + } + + } else { + STREAM_TO_UINT8(index, pp); + STREAM_TO_UINT8(num_of_indices, pp); + len -= 2; + ASSERT_EQ(0u, len); + + InjectNotifyReadPresetsResponse(conn_id, address, handle, value, indicate, + index, num_of_indices, cb, cb_data); } break; - } - rit++; - } - if (rit != presets.rend()) { - if (cb) - cb(conn_id, GATT_SUCCESS, handle, value.size(), value.data(), - cb_data); - current_peer_active_preset_idx_.insert_or_assign( - conn_id, rit->GetIndex()); - InjectActivePresetNotification(conn_id, address, handle, value, - rit->GetIndex(), cb, cb_data); - } else { - /* Preset Operation Not Possible */ - if (cb) - cb(conn_id, (tGATT_STATUS)0x83, handle, value.size(), - value.data(), cb_data); - } - } break; - - case ::bluetooth::le_audio::has::PresetCtpOpcode:: - SET_NEXT_PRESET_SYNC: { - ASSERT_EQ(0u, len); - auto features = current_peer_features_val_.at(conn_id); - if ((features & ::bluetooth::has:: - kFeatureBitPresetSynchronizationSupported) == - 0) { - /* Synchronization Not Supported */ - if (cb) - cb(conn_id, (tGATT_STATUS)0x82, handle, value.size(), - value.data(), cb_data); - break; - } + case ::bluetooth::le_audio::has::PresetCtpOpcode::SET_ACTIVE_PRESET: { + if (len < 1) { + if (cb) { + cb(conn_id, GATT_INVALID_ATTR_LEN, handle, value.size(), value.data(), + cb_data); + } + break; + } + STREAM_TO_UINT8(index, pp); + --len; + ASSERT_EQ(0u, len); + + auto presets = current_peer_presets_.at(conn_id); + if (presets.count(index)) { + current_peer_active_preset_idx_.insert_or_assign(conn_id, index); + if (cb) { + cb(conn_id, GATT_SUCCESS, handle, value.size(), value.data(), cb_data); + } + InjectActivePresetNotification(conn_id, address, handle, value, index, cb, + cb_data); + } else { + /* Preset Operation Not Possible */ + if (cb) { + cb(conn_id, (tGATT_STATUS)0x83, handle, value.size(), value.data(), cb_data); + } + } + } break; + + case ::bluetooth::le_audio::has::PresetCtpOpcode::SET_ACTIVE_PRESET_SYNC: { + auto features = current_peer_features_val_.at(conn_id); + if ((features & ::bluetooth::has::kFeatureBitPresetSynchronizationSupported) == + 0) { + /* Synchronization Not Supported */ + if (cb) { + cb(conn_id, (tGATT_STATUS)0x82, handle, value.size(), value.data(), cb_data); + } + break; + } - auto current_preset = current_peer_active_preset_idx_.at(conn_id); - auto presets = current_peer_presets_.at(conn_id); - auto rit = presets.begin(); - while (rit != presets.end()) { - if (rit->GetIndex() == current_preset) { - rit++; - /* Wrap around */ - if (rit == presets.end()) { - rit = presets.begin(); + if (len < 1) { + if (cb) { + cb(conn_id, GATT_INVALID_ATTR_LEN, handle, value.size(), value.data(), + cb_data); + } + break; + } + STREAM_TO_UINT8(index, pp); + --len; + ASSERT_EQ(0u, len); + + auto csis_api = CsisClient::Get(); + int group_id = bluetooth::groups::kGroupUnknown; + if (csis_api != nullptr) { + group_id = csis_api->GetGroupId(address, + ::bluetooth::le_audio::uuid::kCapServiceUuid); } - break; - } - rit++; - } - if (rit != presets.end()) { - auto synced_group = mock_csis_client_module_.GetGroupId( - GetTestAddress(conn_id), - ::bluetooth::le_audio::uuid::kCapServiceUuid); - auto addresses = - mock_csis_client_module_.GetDeviceList(synced_group); - - // Emulate locally synced op. - notify from all of the devices - for (auto addr : addresses) { - auto cid = GetTestConnId(addr); - if ((cid == conn_id) && (cb != nullptr)) - cb(cid, GATT_SUCCESS, handle, value.size(), value.data(), - cb_data); - - current_peer_active_preset_idx_.insert_or_assign( - conn_id, rit->GetIndex()); - InjectActivePresetNotification(cid, addr, handle, value, - rit->GetIndex(), cb, cb_data); - } - } else { - /* Preset Operation Not Possible */ - if (cb) - cb(conn_id, (tGATT_STATUS)0x83, handle, value.size(), - value.data(), cb_data); - } - } break; - - case ::bluetooth::le_audio::has::PresetCtpOpcode:: - SET_PREV_PRESET_SYNC: { - ASSERT_EQ(0u, len); - auto features = current_peer_features_val_.at(conn_id); - if ((features & ::bluetooth::has:: - kFeatureBitPresetSynchronizationSupported) == - 0) { - /* Synchronization Not Supported */ - if (cb) - cb(conn_id, (tGATT_STATUS)0x82, handle, value.size(), - value.data(), cb_data); - break; - } + if (group_id != bluetooth::groups::kGroupUnknown) { + if (cb) { + cb(conn_id, GATT_SUCCESS, handle, value.size(), value.data(), cb_data); + } + /* Send notification from all grouped devices */ + auto addresses = csis_api->GetDeviceList(group_id); + for (auto& addr : addresses) { + auto conn = GetTestConnId(addr); + InjectActivePresetNotification(conn, addr, handle, value, index, cb, cb_data); + } + } else { + /* Preset Operation Not Possible */ + if (cb) { + cb(conn_id, (tGATT_STATUS)0x83, handle, value.size(), value.data(), cb_data); + } + } + } break; + + case ::bluetooth::le_audio::has::PresetCtpOpcode::SET_NEXT_PRESET: { + ASSERT_EQ(0u, len); + ASSERT_NE(0u, current_peer_active_preset_idx_.count(conn_id)); + ASSERT_NE(0u, current_peer_presets_.count(conn_id)); + + auto current_preset = current_peer_active_preset_idx_.at(conn_id); + auto presets = current_peer_presets_.at(conn_id); + auto current = presets.find(current_preset); + if (current != presets.end()) { + ++current; + if (current == presets.end()) { + current = presets.begin(); + } + + current_peer_active_preset_idx_.insert_or_assign(conn_id, current->GetIndex()); + InjectActivePresetNotification(conn_id, address, handle, value, + current->GetIndex(), cb, cb_data); + + } else { + /* Preset Operation Not Possible */ + if (cb) { + cb(conn_id, (tGATT_STATUS)0x83, handle, value.size(), value.data(), cb_data); + } + } + } break; + + case ::bluetooth::le_audio::has::PresetCtpOpcode::SET_PREV_PRESET: { + ASSERT_EQ(0u, len); + ASSERT_NE(0u, current_peer_active_preset_idx_.count(conn_id)); + ASSERT_NE(0u, current_peer_presets_.count(conn_id)); + + auto current_preset = current_peer_active_preset_idx_.at(conn_id); + auto presets = current_peer_presets_.at(conn_id); + auto rit = presets.rbegin(); + while (rit != presets.rend()) { + if (rit->GetIndex() == current_preset) { + rit++; + /* Wrap around */ + if (rit == presets.rend()) { + rit = presets.rbegin(); + } + break; + } + rit++; + } - auto current_preset = current_peer_active_preset_idx_.at(conn_id); - auto presets = current_peer_presets_.at(conn_id); - auto rit = presets.rbegin(); - while (rit != presets.rend()) { - if (rit->GetIndex() == current_preset) { - rit++; - /* Wrap around */ - if (rit == presets.rend()) { - rit = presets.rbegin(); + if (rit != presets.rend()) { + if (cb) { + cb(conn_id, GATT_SUCCESS, handle, value.size(), value.data(), cb_data); + } + current_peer_active_preset_idx_.insert_or_assign(conn_id, rit->GetIndex()); + InjectActivePresetNotification(conn_id, address, handle, value, rit->GetIndex(), + cb, cb_data); + } else { + /* Preset Operation Not Possible */ + if (cb) { + cb(conn_id, (tGATT_STATUS)0x83, handle, value.size(), value.data(), cb_data); + } + } + } break; + + case ::bluetooth::le_audio::has::PresetCtpOpcode::SET_NEXT_PRESET_SYNC: { + ASSERT_EQ(0u, len); + auto features = current_peer_features_val_.at(conn_id); + if ((features & ::bluetooth::has::kFeatureBitPresetSynchronizationSupported) == + 0) { + /* Synchronization Not Supported */ + if (cb) { + cb(conn_id, (tGATT_STATUS)0x82, handle, value.size(), value.data(), cb_data); + } + break; } - break; - } - rit++; - } - if (rit != presets.rend()) { - auto synced_group = mock_csis_client_module_.GetGroupId( - GetTestAddress(conn_id), - ::bluetooth::le_audio::uuid::kCapServiceUuid); - auto addresses = - mock_csis_client_module_.GetDeviceList(synced_group); - - // Emulate locally synced op. - notify from all of the devices - for (auto addr : addresses) { - auto cid = GetTestConnId(addr); - if ((cid == conn_id) && (cb != nullptr)) - cb(cid, GATT_SUCCESS, handle, value.size(), value.data(), - cb_data); - - current_peer_active_preset_idx_.insert_or_assign( - conn_id, rit->GetIndex()); - InjectActivePresetNotification(cid, addr, handle, value, - rit->GetIndex(), cb, cb_data); - } - } else { - /* Preset Operation Not Possible */ - if (cb) - cb(conn_id, (tGATT_STATUS)0x83, handle, value.size(), - value.data(), cb_data); - } - } break; + auto current_preset = current_peer_active_preset_idx_.at(conn_id); + auto presets = current_peer_presets_.at(conn_id); + auto rit = presets.begin(); + while (rit != presets.end()) { + if (rit->GetIndex() == current_preset) { + rit++; + /* Wrap around */ + if (rit == presets.end()) { + rit = presets.begin(); + } + break; + } + rit++; + } - case ::bluetooth::le_audio::has::PresetCtpOpcode:: - WRITE_PRESET_NAME: { - STREAM_TO_UINT8(index, pp); - --len; - auto name = std::string(pp, pp + len); - len = 0; - - ASSERT_NE(0u, current_peer_presets_.count(conn_id)); - auto presets = current_peer_presets_.at(conn_id); - auto rit = presets.rbegin(); - auto current = rit; - while (rit != presets.rend()) { - if (rit->GetIndex() == index) { - current = rit; - rit++; + if (rit != presets.end()) { + auto synced_group = mock_csis_client_module_.GetGroupId( + GetTestAddress(conn_id), ::bluetooth::le_audio::uuid::kCapServiceUuid); + auto addresses = mock_csis_client_module_.GetDeviceList(synced_group); + + // Emulate locally synced op. - notify from all of the devices + for (auto addr : addresses) { + auto cid = GetTestConnId(addr); + if ((cid == conn_id) && (cb != nullptr)) { + cb(cid, GATT_SUCCESS, handle, value.size(), value.data(), cb_data); + } + + current_peer_active_preset_idx_.insert_or_assign(conn_id, rit->GetIndex()); + InjectActivePresetNotification(cid, addr, handle, value, rit->GetIndex(), cb, + cb_data); + } + } else { + /* Preset Operation Not Possible */ + if (cb) { + cb(conn_id, (tGATT_STATUS)0x83, handle, value.size(), value.data(), cb_data); + } + } + } break; + + case ::bluetooth::le_audio::has::PresetCtpOpcode::SET_PREV_PRESET_SYNC: { + ASSERT_EQ(0u, len); + auto features = current_peer_features_val_.at(conn_id); + if ((features & ::bluetooth::has::kFeatureBitPresetSynchronizationSupported) == + 0) { + /* Synchronization Not Supported */ + if (cb) { + cb(conn_id, (tGATT_STATUS)0x82, handle, value.size(), value.data(), cb_data); + } + break; + } + + auto current_preset = current_peer_active_preset_idx_.at(conn_id); + auto presets = current_peer_presets_.at(conn_id); + auto rit = presets.rbegin(); + while (rit != presets.rend()) { + if (rit->GetIndex() == current_preset) { + rit++; + /* Wrap around */ + if (rit == presets.rend()) { + rit = presets.rbegin(); + } + break; + } + rit++; + } + + if (rit != presets.rend()) { + auto synced_group = mock_csis_client_module_.GetGroupId( + GetTestAddress(conn_id), ::bluetooth::le_audio::uuid::kCapServiceUuid); + auto addresses = mock_csis_client_module_.GetDeviceList(synced_group); + + // Emulate locally synced op. - notify from all of the devices + for (auto addr : addresses) { + auto cid = GetTestConnId(addr); + if ((cid == conn_id) && (cb != nullptr)) { + cb(cid, GATT_SUCCESS, handle, value.size(), value.data(), cb_data); + } + + current_peer_active_preset_idx_.insert_or_assign(conn_id, rit->GetIndex()); + InjectActivePresetNotification(cid, addr, handle, value, rit->GetIndex(), cb, + cb_data); + } + } else { + /* Preset Operation Not Possible */ + if (cb) { + cb(conn_id, (tGATT_STATUS)0x83, handle, value.size(), value.data(), cb_data); + } + } + } break; + + case ::bluetooth::le_audio::has::PresetCtpOpcode::WRITE_PRESET_NAME: { + STREAM_TO_UINT8(index, pp); + --len; + auto name = std::string(pp, pp + len); + len = 0; + + ASSERT_NE(0u, current_peer_presets_.count(conn_id)); + auto presets = current_peer_presets_.at(conn_id); + auto rit = presets.rbegin(); + auto current = rit; + while (rit != presets.rend()) { + if (rit->GetIndex() == index) { + current = rit; + rit++; + break; + } + rit++; + } + + auto prev_index = (rit == presets.rend()) ? 0 : rit->GetIndex(); + + ASSERT_NE(current, presets.rend()); + if (cb) { + cb(conn_id, GATT_SUCCESS, handle, value.size(), value.data(), cb_data); + } + + auto new_preset = HasPreset(current->GetIndex(), current->GetProperties(), name); + presets.erase(current->GetIndex()); + presets.insert(new_preset); + + InjectPresetChanged( + conn_id, address, indicate, new_preset, prev_index, + ::bluetooth::le_audio::has::PresetCtpChangeId::PRESET_GENERIC_UPDATE, + true); + } break; + + default: + if (cb) { + cb(conn_id, GATT_INVALID_HANDLE, handle, value.size(), value.data(), cb_data); + } break; - } - rit++; } - - auto prev_index = (rit == presets.rend()) ? 0 : rit->GetIndex(); - - ASSERT_NE(current, presets.rend()); - if (cb) - cb(conn_id, GATT_SUCCESS, handle, value.size(), value.data(), - cb_data); - - auto new_preset = HasPreset(current->GetIndex(), - current->GetProperties(), name); - presets.erase(current->GetIndex()); - presets.insert(new_preset); - - InjectPresetChanged(conn_id, address, indicate, new_preset, - prev_index, - ::bluetooth::le_audio::has:: - PresetCtpChangeId::PRESET_GENERIC_UPDATE, - true); - } break; - - default: - if (cb) - cb(conn_id, GATT_INVALID_HANDLE, handle, value.size(), - value.data(), cb_data); - break; - } - })); + })); } void SetUp(void) override { @@ -663,45 +626,39 @@ class HasClientTestBase : public ::testing::Test { encryption_result = true; - ON_CALL(btm_interface, IsLinkKeyKnown(_, _)) - .WillByDefault(DoAll(Return(true))); + ON_CALL(btm_interface, IsLinkKeyKnown(_, _)).WillByDefault(DoAll(Return(true))); ON_CALL(btm_interface, SetEncryption(_, _, _, _, _)) - .WillByDefault( - Invoke([this](const RawAddress& bd_addr, tBT_TRANSPORT transport, - tBTM_SEC_CALLBACK* p_callback, void* p_ref_data, - tBTM_BLE_SEC_ACT sec_act) -> tBTM_STATUS { + .WillByDefault(Invoke([this](const RawAddress& bd_addr, tBT_TRANSPORT transport, + tBTM_SEC_CALLBACK* p_callback, void* p_ref_data, + tBTM_BLE_SEC_ACT sec_act) -> tBTM_STATUS { InjectEncryptionEvent(bd_addr); return BTM_SUCCESS; })); MockCsisClient::SetMockInstanceForTesting(&mock_csis_client_module_); - ON_CALL(mock_csis_client_module_, Get()) - .WillByDefault(Return(&mock_csis_client_module_)); - ON_CALL(mock_csis_client_module_, IsCsisClientRunning()) - .WillByDefault(Return(true)); + ON_CALL(mock_csis_client_module_, Get()).WillByDefault(Return(&mock_csis_client_module_)); + ON_CALL(mock_csis_client_module_, IsCsisClientRunning()).WillByDefault(Return(true)); /* default action for GetCharacteristic function call */ ON_CALL(gatt_interface, GetCharacteristic(_, _)) - .WillByDefault( - Invoke([&](uint16_t conn_id, - uint16_t handle) -> const gatt::Characteristic* { - std::list& services = services_map[conn_id]; - for (auto const& service : services) { - for (auto const& characteristic : service.characteristics) { - if (characteristic.value_handle == handle) { - return &characteristic; - } - } - } - - return nullptr; - })); + .WillByDefault( + Invoke([&](uint16_t conn_id, uint16_t handle) -> const gatt::Characteristic* { + std::list& services = services_map[conn_id]; + for (auto const& service : services) { + for (auto const& characteristic : service.characteristics) { + if (characteristic.value_handle == handle) { + return &characteristic; + } + } + } + + return nullptr; + })); /* default action for GetOwningService function call */ ON_CALL(gatt_interface, GetOwningService(_, _)) - .WillByDefault(Invoke( - [&](uint16_t conn_id, uint16_t handle) -> const gatt::Service* { + .WillByDefault(Invoke([&](uint16_t conn_id, uint16_t handle) -> const gatt::Service* { std::list& services = services_map[conn_id]; for (auto const& service : services) { if (service.handle <= handle && service.end_handle >= handle) { @@ -713,47 +670,45 @@ class HasClientTestBase : public ::testing::Test { })); ON_CALL(gatt_interface, ServiceSearchRequest(_, _)) - .WillByDefault(WithArg<0>(Invoke( - [&](uint16_t conn_id) { InjectSearchCompleteEvent(conn_id); }))); + .WillByDefault(WithArg<0>( + Invoke([&](uint16_t conn_id) { InjectSearchCompleteEvent(conn_id); }))); /* default action for GetServices function call */ ON_CALL(gatt_interface, GetServices(_)) - .WillByDefault(WithArg<0>( - Invoke([&](uint16_t conn_id) -> std::list* { + .WillByDefault(WithArg<0>(Invoke([&](uint16_t conn_id) -> std::list* { return &services_map[conn_id]; }))); /* default action for RegisterForNotifications function call */ ON_CALL(gatt_interface, RegisterForNotifications(gatt_if, _, _)) - .WillByDefault(Return(GATT_SUCCESS)); + .WillByDefault(Return(GATT_SUCCESS)); /* default action for DeregisterForNotifications function call */ ON_CALL(gatt_interface, DeregisterForNotifications(gatt_if, _, _)) - .WillByDefault(Return(GATT_SUCCESS)); + .WillByDefault(Return(GATT_SUCCESS)); /* default action for WriteDescriptor function call */ ON_CALL(gatt_queue, WriteDescriptor(_, _, _, _, _, _)) - .WillByDefault( - Invoke([](uint16_t conn_id, uint16_t handle, - std::vector value, tGATT_WRITE_TYPE write_type, - GATT_WRITE_OP_CB cb, void* cb_data) -> void { - if (cb) - cb(conn_id, GATT_SUCCESS, handle, value.size(), value.data(), - cb_data); + .WillByDefault(Invoke([](uint16_t conn_id, uint16_t handle, std::vector value, + tGATT_WRITE_TYPE write_type, GATT_WRITE_OP_CB cb, + void* cb_data) -> void { + if (cb) { + cb(conn_id, GATT_SUCCESS, handle, value.size(), value.data(), cb_data); + } })); /* by default connect only direct connection requests */ ON_CALL(gatt_interface, Open(_, _, _, _)) - .WillByDefault( - Invoke([&](tGATT_IF client_if, const RawAddress& remote_bda, - tBTM_BLE_CONN_TYPE connection_type, bool opportunistic) { - if (connection_type == BTM_BLE_DIRECT_CONNECTION) + .WillByDefault(Invoke([&](tGATT_IF client_if, const RawAddress& remote_bda, + tBTM_BLE_CONN_TYPE connection_type, bool opportunistic) { + if (connection_type == BTM_BLE_DIRECT_CONNECTION) { InjectConnectedEvent(remote_bda, GetTestConnId(remote_bda)); + } })); - ON_CALL(gatt_interface, Close(_)) - .WillByDefault(Invoke( - [&](uint16_t conn_id) { InjectDisconnectedEvent(conn_id); })); + ON_CALL(gatt_interface, Close(_)).WillByDefault(Invoke([&](uint16_t conn_id) { + InjectDisconnectedEvent(conn_id); + })); } void TearDown(void) override { @@ -771,8 +726,7 @@ class HasClientTestBase : public ::testing::Test { void TestAppRegister(void) { BtaAppRegisterCallback app_register_callback; EXPECT_CALL(gatt_interface, AppRegister(_, _, _)) - .WillOnce(DoAll(SaveArg<0>(&gatt_callback), - SaveArg<1>(&app_register_callback))); + .WillOnce(DoAll(SaveArg<0>(&gatt_callback), SaveArg<1>(&app_register_callback))); HasClient::Initialize(callbacks.get(), base::DoNothing()); ASSERT_TRUE(gatt_callback); ASSERT_TRUE(app_register_callback); @@ -790,10 +744,9 @@ class HasClientTestBase : public ::testing::Test { void TestConnect(const RawAddress& address) { ON_CALL(btm_interface, BTM_IsEncrypted(address, _)) - .WillByDefault(DoAll(Return(encryption_result))); + .WillByDefault(DoAll(Return(encryption_result))); - EXPECT_CALL(gatt_interface, - Open(gatt_if, address, BTM_BLE_DIRECT_CONNECTION, _)); + EXPECT_CALL(gatt_interface, Open(gatt_if, address, BTM_BLE_DIRECT_CONNECTION, _)); HasClient::Get()->Connect(address); Mock::VerifyAndClearExpectations(&*callbacks); @@ -813,11 +766,9 @@ class HasClientTestBase : public ::testing::Test { HasClient::Get()->Disconnect(address); } - void TestAddFromStorage(const RawAddress& address, uint8_t features, - bool auto_connect) { + void TestAddFromStorage(const RawAddress& address, uint8_t features, bool auto_connect) { if (auto_connect) { - EXPECT_CALL(gatt_interface, - Open(gatt_if, address, BTM_BLE_BKG_CONNECT_ALLOW_LIST, _)); + EXPECT_CALL(gatt_interface, Open(gatt_if, address, BTM_BLE_BKG_CONNECT_ALLOW_LIST, _)); HasClient::Get()->AddFromStorage(address, features, auto_connect); /* Inject connected event for autoconnect/background connection */ @@ -833,30 +784,31 @@ class HasClientTestBase : public ::testing::Test { void InjectConnectedEvent(const RawAddress& address, uint16_t conn_id, tGATT_STATUS status = GATT_SUCCESS) { tBTA_GATTC_OPEN event_data = { - .status = status, - .conn_id = conn_id, - .client_if = gatt_if, - .remote_bda = address, - .transport = GATT_TRANSPORT_LE, - .mtu = 240, + .status = status, + .conn_id = conn_id, + .client_if = gatt_if, + .remote_bda = address, + .transport = GATT_TRANSPORT_LE, + .mtu = 240, }; connected_devices[conn_id] = address; gatt_callback(BTA_GATTC_OPEN_EVT, (tBTA_GATTC*)&event_data); } - void InjectDisconnectedEvent( - uint16_t conn_id, - tGATT_DISCONN_REASON reason = GATT_CONN_TERMINATE_LOCAL_HOST, - bool allow_fake_conn = false) { - if (!allow_fake_conn) ASSERT_NE(connected_devices.count(conn_id), 0u); + void InjectDisconnectedEvent(uint16_t conn_id, + tGATT_DISCONN_REASON reason = GATT_CONN_TERMINATE_LOCAL_HOST, + bool allow_fake_conn = false) { + if (!allow_fake_conn) { + ASSERT_NE(connected_devices.count(conn_id), 0u); + } tBTA_GATTC_CLOSE event_data = { - .conn_id = conn_id, - .status = GATT_SUCCESS, - .client_if = gatt_if, - .remote_bda = connected_devices[conn_id], - .reason = reason, + .conn_id = conn_id, + .status = GATT_SUCCESS, + .client_if = gatt_if, + .remote_bda = connected_devices[conn_id], + .reason = reason, }; connected_devices.erase(conn_id); @@ -865,22 +817,21 @@ class HasClientTestBase : public ::testing::Test { void InjectSearchCompleteEvent(uint16_t conn_id) { tBTA_GATTC_SEARCH_CMPL event_data = { - .conn_id = conn_id, - .status = GATT_SUCCESS, + .conn_id = conn_id, + .status = GATT_SUCCESS, }; gatt_callback(BTA_GATTC_SEARCH_CMPL_EVT, (tBTA_GATTC*)&event_data); } - void InjectNotificationEvent(const RawAddress& test_address, uint16_t conn_id, - uint16_t handle, std::vector value, - bool indicate = false) { + void InjectNotificationEvent(const RawAddress& test_address, uint16_t conn_id, uint16_t handle, + std::vector value, bool indicate = false) { tBTA_GATTC_NOTIFY event_data = { - .conn_id = conn_id, - .bda = test_address, - .handle = handle, - .len = (uint8_t)value.size(), - .is_notify = !indicate, + .conn_id = conn_id, + .bda = test_address, + .handle = handle, + .len = (uint8_t)value.size(), + .is_notify = !indicate, }; ASSERT_TRUE(value.size() < GATT_MAX_ATTR_LEN); @@ -890,8 +841,8 @@ class HasClientTestBase : public ::testing::Test { void InjectEncryptionEvent(const RawAddress& test_address) { tBTA_GATTC_ENC_CMPL_CB event_data = { - .client_if = static_cast(GetTestConnId(test_address)), - .remote_bda = test_address, + .client_if = static_cast(GetTestConnId(test_address)), + .remote_bda = test_address, }; gatt_callback(BTA_GATTC_ENC_CMPL_CB_EVT, (tBTA_GATTC*)&event_data); @@ -901,36 +852,32 @@ class HasClientTestBase : public ::testing::Test { encryption_result = success; ON_CALL(btm_interface, BTM_IsEncrypted(address, _)) - .WillByDefault(DoAll(Return(encryption_result))); + .WillByDefault(DoAll(Return(encryption_result))); - ON_CALL(btm_interface, IsLinkKeyKnown(address, _)) - .WillByDefault(DoAll(Return(true))); + ON_CALL(btm_interface, IsLinkKeyKnown(address, _)).WillByDefault(DoAll(Return(true))); } - void InjectNotifyReadPresetResponse(uint16_t conn_id, - RawAddress const& address, - uint16_t handle, const HasPreset& preset, - bool indicate, bool is_last) { + void InjectNotifyReadPresetResponse(uint16_t conn_id, RawAddress const& address, uint16_t handle, + const HasPreset& preset, bool indicate, bool is_last) { std::vector value; - value.push_back(static_cast>( - ::bluetooth::le_audio::has::PresetCtpOpcode::READ_PRESET_RESPONSE)); + value.push_back( + static_cast>( + ::bluetooth::le_audio::has::PresetCtpOpcode::READ_PRESET_RESPONSE)); value.push_back(is_last ? 0x01 : 0x00); preset.ToCharacteristicValue(value); InjectNotificationEvent(address, conn_id, handle, value, indicate); } - void InjectPresetChanged( - uint16_t conn_id, RawAddress const& address, bool indicate, - const HasPreset& preset, uint8_t prev_index, - ::bluetooth::le_audio::has::PresetCtpChangeId change_id, bool is_last) { + void InjectPresetChanged(uint16_t conn_id, RawAddress const& address, bool indicate, + const HasPreset& preset, uint8_t prev_index, + ::bluetooth::le_audio::has::PresetCtpChangeId change_id, bool is_last) { std::vector value; - value.push_back(static_cast>( - ::bluetooth::le_audio::has::PresetCtpOpcode::PRESET_CHANGED)); + value.push_back( + static_cast>( + ::bluetooth::le_audio::has::PresetCtpOpcode::PRESET_CHANGED)); value.push_back(static_cast(change_id)); value.push_back(is_last ? 0x01 : 0x00); @@ -947,84 +894,78 @@ class HasClientTestBase : public ::testing::Test { break; } - InjectNotificationEvent(address, conn_id, HasDbBuilder::kPresetsCtpValHdl, - value, indicate); + InjectNotificationEvent(address, conn_id, HasDbBuilder::kPresetsCtpValHdl, value, indicate); } - void InjectNotifyReadPresetsResponse( - uint16_t conn_id, RawAddress const& address, uint16_t handle, - std::vector value, bool indicate, int index, int num_of_indices, - GATT_WRITE_OP_CB cb, void* cb_data) { + void InjectNotifyReadPresetsResponse(uint16_t conn_id, RawAddress const& address, uint16_t handle, + std::vector value, bool indicate, int index, + int num_of_indices, GATT_WRITE_OP_CB cb, void* cb_data) { auto presets = current_peer_presets_.at(conn_id); log::assert_that(!presets.empty(), "Mocking error!"); /* Index is a start index, not necessary is a valid index for the * peer device */ auto preset = presets.find(index); - while (preset == presets.end() && - index++ <= ::bluetooth::le_audio::has::kMaxNumOfPresets) { + while (preset == presets.end() && index++ <= ::bluetooth::le_audio::has::kMaxNumOfPresets) { preset = presets.find(index); } if (preset == presets.end()) { /* operation not possible */ - if (cb) - cb(conn_id, (tGATT_STATUS)0x83, handle, value.size(), value.data(), - cb_data); + if (cb) { + cb(conn_id, (tGATT_STATUS)0x83, handle, value.size(), value.data(), cb_data); + } return; } - if (cb) + if (cb) { cb(conn_id, GATT_SUCCESS, handle, value.size(), value.data(), cb_data); + } /* Notify presets */ int num_of_notif = 1; while (1) { - bool last = - preset == std::prev(presets.end()) || num_of_notif == num_of_indices; - InjectNotifyReadPresetResponse(conn_id, address, handle, *preset, - indicate, (last)); - if (last) return; + bool last = preset == std::prev(presets.end()) || num_of_notif == num_of_indices; + InjectNotifyReadPresetResponse(conn_id, address, handle, *preset, indicate, (last)); + if (last) { + return; + } num_of_notif++; preset++; } } - void InjectActivePresetNotification(uint16_t conn_id, - RawAddress const& address, - uint16_t handle, - std::vector wr_value, - uint8_t index, GATT_WRITE_OP_CB cb, - void* cb_data) { + void InjectActivePresetNotification(uint16_t conn_id, RawAddress const& address, uint16_t handle, + std::vector wr_value, uint8_t index, + GATT_WRITE_OP_CB cb, void* cb_data) { auto presets = current_peer_presets_.at(conn_id); log::assert_that(!presets.empty(), "Mocking error!"); auto preset = presets.find(index); if (preset == presets.end()) { /* preset operation not possible */ - if (cb) - cb(conn_id, (tGATT_STATUS)0x83, handle, wr_value.size(), - wr_value.data(), cb_data); + if (cb) { + cb(conn_id, (tGATT_STATUS)0x83, handle, wr_value.size(), wr_value.data(), cb_data); + } return; } std::vector value; value.push_back(index); - InjectNotificationEvent( - address, conn_id, HasDbBuilder::kActivePresetIndexValHdl, value, false); + InjectNotificationEvent(address, conn_id, HasDbBuilder::kActivePresetIndexValHdl, value, false); } void SetSampleDatabaseHasNoFeatures(const RawAddress& address) { HasDbBuilder builder = { - .has = true, - .features = false, - .features_ntf = false, - .preset_cp = true, - .preset_cp_ntf = false, - .preset_cp_ind = true, - .active_preset_idx = true, - .active_preset_idx_ntf = true, + .has = true, + .features = false, + .features_ntf = false, + .preset_cp = true, + .preset_cp_ntf = false, + .preset_cp_ind = true, + .active_preset_idx = true, + .active_preset_idx_ntf = true, }; set_sample_database(address, builder); } @@ -1032,44 +973,42 @@ class HasClientTestBase : public ::testing::Test { void SetSampleDatabaseHasNoPresetChange(const RawAddress& address, uint8_t features_value = 0x00) { HasDbBuilder builder = { - .has = true, - .features = true, - .features_ntf = false, - .preset_cp = false, - .preset_cp_ntf = false, - .preset_cp_ind = false, - .active_preset_idx = false, - .active_preset_idx_ntf = false, + .has = true, + .features = true, + .features_ntf = false, + .preset_cp = false, + .preset_cp_ntf = false, + .preset_cp_ind = false, + .active_preset_idx = false, + .active_preset_idx_ntf = false, }; set_sample_database(address, builder, features_value); } - void SetSampleDatabaseHasNoOptionalNtf(const RawAddress& address, - uint8_t features = 0x00) { + void SetSampleDatabaseHasNoOptionalNtf(const RawAddress& address, uint8_t features = 0x00) { HasDbBuilder builder = { - .has = true, - .features = true, - .features_ntf = false, - .preset_cp = true, - .preset_cp_ntf = false, - .preset_cp_ind = true, - .active_preset_idx = true, - .active_preset_idx_ntf = true, + .has = true, + .features = true, + .features_ntf = false, + .preset_cp = true, + .preset_cp_ntf = false, + .preset_cp_ind = true, + .active_preset_idx = true, + .active_preset_idx_ntf = true, }; set_sample_database(address, builder, features); } - void SetSampleDatabaseNoHas(const RawAddress& address, - uint8_t features = 0x00) { + void SetSampleDatabaseNoHas(const RawAddress& address, uint8_t features = 0x00) { HasDbBuilder builder = { - .has = false, - .features = false, - .features_ntf = false, - .preset_cp = false, - .preset_cp_ntf = false, - .preset_cp_ind = false, - .active_preset_idx = true, - .active_preset_idx_ntf = true, + .has = false, + .features = false, + .features_ntf = false, + .preset_cp = false, + .preset_cp_ntf = false, + .preset_cp_ind = false, + .active_preset_idx = true, + .active_preset_idx_ntf = true, }; set_sample_database(address, builder, features); } @@ -1077,14 +1016,14 @@ class HasClientTestBase : public ::testing::Test { void SetSampleDatabaseHasBrokenNoActivePreset(const RawAddress& address, uint8_t features = 0x00) { HasDbBuilder builder = { - .has = true, - .features = true, - .features_ntf = false, - .preset_cp = true, - .preset_cp_ntf = true, - .preset_cp_ind = true, - .active_preset_idx = false, - .active_preset_idx_ntf = false, + .has = true, + .features = true, + .features_ntf = false, + .preset_cp = true, + .preset_cp_ntf = true, + .preset_cp_ind = true, + .active_preset_idx = false, + .active_preset_idx_ntf = false, }; set_sample_database(address, builder, features); } @@ -1092,62 +1031,59 @@ class HasClientTestBase : public ::testing::Test { void SetSampleDatabaseHasBrokenNoActivePresetNtf(const RawAddress& address, uint8_t features = 0x00) { HasDbBuilder builder = { - .has = true, - .features = true, - .features_ntf = false, - .preset_cp = true, - .preset_cp_ntf = true, - .preset_cp_ind = true, - .active_preset_idx = true, - .active_preset_idx_ntf = false, + .has = true, + .features = true, + .features_ntf = false, + .preset_cp = true, + .preset_cp_ntf = true, + .preset_cp_ind = true, + .active_preset_idx = true, + .active_preset_idx_ntf = false, }; set_sample_database(address, builder, features); } - void SetSampleDatabaseHasOnlyFeaturesNtf(const RawAddress& address, - uint8_t features = 0x00) { + void SetSampleDatabaseHasOnlyFeaturesNtf(const RawAddress& address, uint8_t features = 0x00) { HasDbBuilder builder = { - .has = true, - .features = true, - .features_ntf = true, - .preset_cp = false, - .preset_cp_ntf = false, - .preset_cp_ind = false, - .active_preset_idx = false, - .active_preset_idx_ntf = false, + .has = true, + .features = true, + .features_ntf = true, + .preset_cp = false, + .preset_cp_ntf = false, + .preset_cp_ind = false, + .active_preset_idx = false, + .active_preset_idx_ntf = false, }; set_sample_database(address, builder, features); } - void SetSampleDatabaseHasOnlyFeaturesNoNtf(const RawAddress& address, - uint8_t features = 0x00) { + void SetSampleDatabaseHasOnlyFeaturesNoNtf(const RawAddress& address, uint8_t features = 0x00) { HasDbBuilder builder = { - .has = true, - .features = true, - .features_ntf = false, - .preset_cp = false, - .preset_cp_ntf = false, - .preset_cp_ind = false, - .active_preset_idx = false, - .active_preset_idx_ntf = false, + .has = true, + .features = true, + .features_ntf = false, + .preset_cp = false, + .preset_cp_ntf = false, + .preset_cp_ind = false, + .active_preset_idx = false, + .active_preset_idx_ntf = false, }; set_sample_database(address, builder, features); } void SetSampleDatabaseHasPresetsNtf( - const RawAddress& address, - uint8_t features = bluetooth::has::kFeatureBitHearingAidTypeMonaural, - std::optional> presets = - std::nullopt) { + const RawAddress& address, + uint8_t features = bluetooth::has::kFeatureBitHearingAidTypeMonaural, + std::optional> presets = std::nullopt) { HasDbBuilder builder = { - .has = true, - .features = true, - .features_ntf = true, - .preset_cp = true, - .preset_cp_ntf = true, - .preset_cp_ind = true, - .active_preset_idx = true, - .active_preset_idx_ntf = true, + .has = true, + .features = true, + .features_ntf = true, + .preset_cp = true, + .preset_cp_ntf = true, + .preset_cp_ind = true, + .active_preset_idx = true, + .active_preset_idx_ntf = true, }; set_sample_database(address, builder, features, presets); @@ -1156,14 +1092,14 @@ class HasClientTestBase : public ::testing::Test { void SetSampleDatabaseHasNoPresetsFlagsOnly(const RawAddress& address) { uint8_t features = bluetooth::has::kFeatureBitHearingAidTypeMonaural; HasDbBuilder builder = { - .has = true, - .features = true, - .features_ntf = true, - .preset_cp = false, - .preset_cp_ntf = false, - .preset_cp_ind = false, - .active_preset_idx = false, - .active_preset_idx_ntf = false, + .has = true, + .features = true, + .features_ntf = true, + .preset_cp = false, + .preset_cp_ntf = false, + .preset_cp_ind = false, + .active_preset_idx = false, + .active_preset_idx_ntf = false, }; set_sample_database(address, builder, features, std::nullopt); @@ -1193,9 +1129,7 @@ class HasClientTest : public HasClientTestBase { } }; -TEST_F(HasClientTestBase, test_get_uninitialized) { - ASSERT_DEATH(HasClient::Get(), ""); -} +TEST_F(HasClientTestBase, test_get_uninitialized) { ASSERT_DEATH(HasClient::Get(), ""); } TEST_F(HasClientTestBase, test_initialize) { HasClient::Initialize(callbacks.get(), base::DoNothing()); @@ -1238,19 +1172,16 @@ TEST_F(HasClientTest, test_connect_after_remove) { const RawAddress test_address = GetTestAddress(1); /* Override the default action to prevent us sendind the connected event */ - EXPECT_CALL(gatt_interface, - Open(gatt_if, test_address, BTM_BLE_DIRECT_CONNECTION, _)) - .WillOnce(Return()); + EXPECT_CALL(gatt_interface, Open(gatt_if, test_address, BTM_BLE_DIRECT_CONNECTION, _)) + .WillOnce(Return()); HasClient::Get()->Connect(test_address); TestDisconnect(test_address, GATT_INVALID_CONN_ID); Mock::VerifyAndClearExpectations(&gatt_interface); - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::DISCONNECTED, test_address)); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::DISCONNECTED, test_address)); // Device has no Link Key - ON_CALL(btm_interface, IsLinkKeyKnown(test_address, _)) - .WillByDefault(DoAll(Return(true))); + ON_CALL(btm_interface, IsLinkKeyKnown(test_address, _)).WillByDefault(DoAll(Return(true))); HasClient::Get()->Connect(test_address); Mock::VerifyAndClearExpectations(&callbacks); } @@ -1259,9 +1190,8 @@ TEST_F(HasClientTest, test_disconnect_non_connected) { const RawAddress test_address = GetTestAddress(1); /* Override the default action to prevent us sendind the connected event */ - EXPECT_CALL(gatt_interface, - Open(gatt_if, test_address, BTM_BLE_DIRECT_CONNECTION, _)) - .WillOnce(Return()); + EXPECT_CALL(gatt_interface, Open(gatt_if, test_address, BTM_BLE_DIRECT_CONNECTION, _)) + .WillOnce(Return()); HasClient::Get()->Connect(test_address); TestDisconnect(test_address, GATT_INVALID_CONN_ID); } @@ -1269,76 +1199,56 @@ TEST_F(HasClientTest, test_disconnect_non_connected) { TEST_F(HasClientTest, test_has_connected) { const RawAddress test_address = GetTestAddress(1); /* Minimal possible HA device (only feature flags) */ - SetSampleDatabaseHasNoPresetChange( - test_address, bluetooth::has::kFeatureBitHearingAidTypeBinaural); + SetSampleDatabaseHasNoPresetChange(test_address, + bluetooth::has::kFeatureBitHearingAidTypeBinaural); - EXPECT_CALL( - *callbacks, - OnDeviceAvailable(test_address, - bluetooth::has::kFeatureBitHearingAidTypeBinaural)); EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::CONNECTED, test_address)); + OnDeviceAvailable(test_address, bluetooth::has::kFeatureBitHearingAidTypeBinaural)); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::CONNECTED, test_address)); TestConnect(test_address); } TEST_F(HasClientTest, test_disconnect_connected) { const RawAddress test_address = GetTestAddress(1); /* Minimal possible HA device (only feature flags) */ - SetSampleDatabaseHasNoPresetChange( - test_address, bluetooth::has::kFeatureBitHearingAidTypeBinaural); + SetSampleDatabaseHasNoPresetChange(test_address, + bluetooth::has::kFeatureBitHearingAidTypeBinaural); - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::CONNECTED, test_address)) - .Times(1); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::CONNECTED, test_address)).Times(1); TestConnect(test_address); - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::DISCONNECTED, test_address)) - .Times(1); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::DISCONNECTED, test_address)).Times(1); TestDisconnect(test_address, 1); } TEST_F(HasClientTest, test_disconnected_while_autoconnect) { const RawAddress test_address = GetTestAddress(1); - TestAddFromStorage(test_address, - bluetooth::has::kFeatureBitHearingAidTypeBinaural, true); + TestAddFromStorage(test_address, bluetooth::has::kFeatureBitHearingAidTypeBinaural, true); /* autoconnect - don't indicate disconnection */ - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::DISCONNECTED, test_address)) - .Times(0); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::DISCONNECTED, test_address)).Times(0); /* Verify that the device still can connect in te background */ InjectDisconnectedEvent(1, GATT_CONN_TERMINATE_PEER_USER, true); } TEST_F(HasClientTest, test_encryption_failed) { const RawAddress test_address = GetTestAddress(1); - SetSampleDatabaseHasNoPresetChange( - test_address, bluetooth::has::kFeatureBitHearingAidTypeBinaural); - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::DISCONNECTED, test_address)) - .Times(1); - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::CONNECTED, test_address)) - .Times(0); + SetSampleDatabaseHasNoPresetChange(test_address, + bluetooth::has::kFeatureBitHearingAidTypeBinaural); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::DISCONNECTED, test_address)).Times(1); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::CONNECTED, test_address)).Times(0); SetEncryptionResult(test_address, false); TestConnect(test_address); } TEST_F(HasClientTest, test_service_discovery_complete_before_encryption) { const RawAddress test_address = GetTestAddress(1); - SetSampleDatabaseHasPresetsNtf( - test_address, bluetooth::has::kFeatureBitHearingAidTypeBinaural); + SetSampleDatabaseHasPresetsNtf(test_address, bluetooth::has::kFeatureBitHearingAidTypeBinaural); - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::DISCONNECTED, test_address)) - .Times(0); - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::CONNECTED, test_address)) - .Times(0); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::DISCONNECTED, test_address)).Times(0); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::CONNECTED, test_address)).Times(0); SetEncryptionResult(test_address, false); - ON_CALL(btm_interface, SetEncryption(_, _, _, _, _)) - .WillByDefault(Return(BTM_SUCCESS)); + ON_CALL(btm_interface, SetEncryption(_, _, _, _, _)).WillByDefault(Return(BTM_SUCCESS)); TestConnect(test_address); auto test_conn_id = GetTestConnId(test_address); @@ -1346,9 +1256,7 @@ TEST_F(HasClientTest, test_service_discovery_complete_before_encryption) { Mock::VerifyAndClearExpectations(callbacks.get()); - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::CONNECTED, test_address)) - .Times(1); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::CONNECTED, test_address)).Times(1); SetEncryptionResult(test_address, true); InjectEncryptionEvent(test_address); @@ -1357,20 +1265,14 @@ TEST_F(HasClientTest, test_service_discovery_complete_before_encryption) { TEST_F(HasClientTest, test_disconnect_when_link_key_is_gone) { const RawAddress test_address = GetTestAddress(1); - SetSampleDatabaseHasPresetsNtf( - test_address, bluetooth::has::kFeatureBitHearingAidTypeBinaural); + SetSampleDatabaseHasPresetsNtf(test_address, bluetooth::has::kFeatureBitHearingAidTypeBinaural); - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::DISCONNECTED, test_address)) - .Times(0); - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::CONNECTED, test_address)) - .Times(0); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::DISCONNECTED, test_address)).Times(0); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::CONNECTED, test_address)).Times(0); - ON_CALL(btm_interface, BTM_IsEncrypted(test_address, _)) - .WillByDefault(DoAll(Return(false))); + ON_CALL(btm_interface, BTM_IsEncrypted(test_address, _)).WillByDefault(DoAll(Return(false))); ON_CALL(btm_interface, SetEncryption(test_address, _, _, _, _)) - .WillByDefault(Return(BTM_ERR_KEY_MISSING)); + .WillByDefault(Return(BTM_ERR_KEY_MISSING)); auto test_conn_id = GetTestConnId(test_address); EXPECT_CALL(gatt_interface, Close(test_conn_id)).Times(1); @@ -1381,20 +1283,14 @@ TEST_F(HasClientTest, test_disconnect_when_link_key_is_gone) { TEST_F(HasClientTest, test_reconnect_after_encryption_failed) { const RawAddress test_address = GetTestAddress(1); - SetSampleDatabaseHasNoPresetChange( - test_address, bluetooth::has::kFeatureBitHearingAidTypeBinaural); - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::DISCONNECTED, test_address)) - .Times(1); - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::CONNECTED, test_address)) - .Times(0); + SetSampleDatabaseHasNoPresetChange(test_address, + bluetooth::has::kFeatureBitHearingAidTypeBinaural); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::DISCONNECTED, test_address)).Times(1); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::CONNECTED, test_address)).Times(0); SetEncryptionResult(test_address, false); TestConnect(test_address); - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::CONNECTED, test_address)) - .Times(1); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::CONNECTED, test_address)).Times(1); SetEncryptionResult(test_address, true); InjectConnectedEvent(test_address, GetTestConnId(test_address)); } @@ -1402,23 +1298,20 @@ TEST_F(HasClientTest, test_reconnect_after_encryption_failed) { TEST_F(HasClientTest, test_reconnect_after_encryption_failed_from_storage) { const RawAddress test_address = GetTestAddress(1); - SetSampleDatabaseHasNoPresetChange( - test_address, bluetooth::has::kFeatureBitHearingAidTypeBinaural); + SetSampleDatabaseHasNoPresetChange(test_address, + bluetooth::has::kFeatureBitHearingAidTypeBinaural); SetEncryptionResult(test_address, false); TestAddFromStorage(test_address, 0, true); /* autoconnect - don't indicate disconnection */ - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::DISCONNECTED, test_address)) - .Times(0); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::DISCONNECTED, test_address)).Times(0); Mock::VerifyAndClearExpectations(&btm_interface); /* Fake no persistent storage data */ - ON_CALL(btif_storage_interface_, GetLeaudioHasPresets(_, _, _)) - .WillByDefault([]() { return false; }); + ON_CALL(btif_storage_interface_, GetLeaudioHasPresets(_, _, _)).WillByDefault([]() { + return false; + }); - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::CONNECTED, test_address)) - .Times(1); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::CONNECTED, test_address)).Times(1); SetEncryptionResult(test_address, true); InjectConnectedEvent(test_address, GetTestConnId(test_address)); } @@ -1429,66 +1322,64 @@ TEST_F(HasClientTest, test_load_from_storage_and_connect) { SetEncryptionResult(test_address, true); std::set has_presets = {{ - HasPreset(5, HasPreset::kPropertyAvailable | HasPreset::kPropertyWritable, - "YourWritablePreset5"), - HasPreset(55, HasPreset::kPropertyAvailable, "YourPreset55"), + HasPreset(5, HasPreset::kPropertyAvailable | HasPreset::kPropertyWritable, + "YourWritablePreset5"), + HasPreset(55, HasPreset::kPropertyAvailable, "YourPreset55"), }}; /* Load persistent storage data */ ON_CALL(btif_storage_interface_, GetLeaudioHasPresets(test_address, _, _)) - .WillByDefault([&has_presets](const RawAddress& address, - std::vector& presets_bin, - uint8_t& active_preset) { - /* Generate presets binary to be used instead the attribute values */ - HasDevice device(address, 0); - device.has_presets = has_presets; - active_preset = 55; + .WillByDefault([&has_presets](const RawAddress& address, + std::vector& presets_bin, uint8_t& active_preset) { + /* Generate presets binary to be used instead the attribute values */ + HasDevice device(address, 0); + device.has_presets = has_presets; + active_preset = 55; - if (device.SerializePresets(presets_bin)) return true; + if (device.SerializePresets(presets_bin)) { + return true; + } - return false; - }); + return false; + }); EXPECT_CALL(gatt_interface, RegisterForNotifications(gatt_if, _, _)) - .Times(1 // preset control point - + 1 // active preset - + 1); // features + .Times(1 // preset control point + + 1 // active preset + + 1); // features EXPECT_CALL(*callbacks, - OnDeviceAvailable(test_address, - (kFeatureBitWritablePresets | - kFeatureBitPresetSynchronizationSupported | - kFeatureBitHearingAidTypeBanded))); + OnDeviceAvailable(test_address, (kFeatureBitWritablePresets | + kFeatureBitPresetSynchronizationSupported | + kFeatureBitHearingAidTypeBanded))); std::vector loaded_preset_details; - EXPECT_CALL(*callbacks, - OnPresetInfo(std::variant(test_address), - PresetInfoReason::ALL_PRESET_INFO, _)) - .WillOnce(SaveArg<2>(&loaded_preset_details)); + EXPECT_CALL(*callbacks, OnPresetInfo(std::variant(test_address), + PresetInfoReason::ALL_PRESET_INFO, _)) + .WillOnce(SaveArg<2>(&loaded_preset_details)); - EXPECT_CALL(*callbacks, OnActivePresetSelected( - std::variant(test_address), 55)); + EXPECT_CALL(*callbacks, OnActivePresetSelected(std::variant(test_address), 55)); - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::CONNECTED, test_address)); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::CONNECTED, test_address)); /* Expect no read or write operations when loading from storage */ EXPECT_CALL(gatt_queue, ReadCharacteristic(1, _, _, _)).Times(0); EXPECT_CALL(gatt_queue, WriteDescriptor(1, _, _, _, _, _)).Times(3); TestAddFromStorage(test_address, - kFeatureBitWritablePresets | - kFeatureBitPresetSynchronizationSupported | - kFeatureBitHearingAidTypeBanded, + kFeatureBitWritablePresets | kFeatureBitPresetSynchronizationSupported | + kFeatureBitHearingAidTypeBanded, true); for (auto const& info : loaded_preset_details) { auto preset = has_presets.find(info.preset_index); ASSERT_NE(preset, has_presets.end()); - if (preset->GetProperties() & HasPreset::kPropertyAvailable) + if (preset->GetProperties() & HasPreset::kPropertyAvailable) { ASSERT_TRUE(info.available); - if (preset->GetProperties() & HasPreset::kPropertyWritable) + } + if (preset->GetProperties() & HasPreset::kPropertyWritable) { ASSERT_TRUE(info.writable); + } ASSERT_EQ(preset->GetName(), info.preset_name); } } @@ -1499,49 +1390,46 @@ TEST_F(HasClientTest, test_load_from_storage) { SetEncryptionResult(test_address, true); std::set has_presets = {{ - HasPreset(5, HasPreset::kPropertyAvailable | HasPreset::kPropertyWritable, - "YourWritablePreset5"), - HasPreset(55, HasPreset::kPropertyAvailable, "YourPreset55"), + HasPreset(5, HasPreset::kPropertyAvailable | HasPreset::kPropertyWritable, + "YourWritablePreset5"), + HasPreset(55, HasPreset::kPropertyAvailable, "YourPreset55"), }}; /* Load persistent storage data */ ON_CALL(btif_storage_interface_, GetLeaudioHasPresets(test_address, _, _)) - .WillByDefault([&has_presets](const RawAddress& address, - std::vector& presets_bin, - uint8_t& active_preset) { - /* Generate presets binary to be used instead the attribute values */ - HasDevice device(address, 0); - device.has_presets = has_presets; - active_preset = 55; + .WillByDefault([&has_presets](const RawAddress& address, + std::vector& presets_bin, uint8_t& active_preset) { + /* Generate presets binary to be used instead the attribute values */ + HasDevice device(address, 0); + device.has_presets = has_presets; + active_preset = 55; - if (device.SerializePresets(presets_bin)) return true; + if (device.SerializePresets(presets_bin)) { + return true; + } - return false; - }); + return false; + }); - EXPECT_CALL(gatt_interface, RegisterForNotifications(gatt_if, _, _)) - .Times(0); // features + EXPECT_CALL(gatt_interface, RegisterForNotifications(gatt_if, _, _)).Times(0); // features EXPECT_CALL(*callbacks, - OnDeviceAvailable(test_address, - (kFeatureBitWritablePresets | - kFeatureBitPresetSynchronizationSupported | - kFeatureBitHearingAidTypeBanded))); + OnDeviceAvailable(test_address, (kFeatureBitWritablePresets | + kFeatureBitPresetSynchronizationSupported | + kFeatureBitHearingAidTypeBanded))); std::vector loaded_preset_details; - EXPECT_CALL(*callbacks, - OnPresetInfo(std::variant(test_address), - PresetInfoReason::ALL_PRESET_INFO, _)) - .Times(0); + EXPECT_CALL(*callbacks, OnPresetInfo(std::variant(test_address), + PresetInfoReason::ALL_PRESET_INFO, _)) + .Times(0); /* Expect no read or write operations when loading from storage */ EXPECT_CALL(gatt_queue, ReadCharacteristic(1, _, _, _)).Times(0); EXPECT_CALL(gatt_queue, WriteDescriptor(1, _, _, _, _, _)).Times(0); TestAddFromStorage(test_address, - kFeatureBitWritablePresets | - kFeatureBitPresetSynchronizationSupported | - kFeatureBitHearingAidTypeBanded, + kFeatureBitWritablePresets | kFeatureBitPresetSynchronizationSupported | + kFeatureBitHearingAidTypeBanded, false); } @@ -1549,44 +1437,41 @@ TEST_F(HasClientTest, test_write_to_storage) { const RawAddress test_address = GetTestAddress(1); std::set has_presets = {{ - HasPreset(1, HasPreset::kPropertyAvailable, "Universal"), - HasPreset(2, HasPreset::kPropertyAvailable | HasPreset::kPropertyWritable, - "Preset2"), + HasPreset(1, HasPreset::kPropertyAvailable, "Universal"), + HasPreset(2, HasPreset::kPropertyAvailable | HasPreset::kPropertyWritable, "Preset2"), }}; - SetSampleDatabaseHasPresetsNtf( - test_address, - bluetooth::has::kFeatureBitHearingAidTypeBanded | - bluetooth::has::kFeatureBitWritablePresets | - bluetooth::has::kFeatureBitDynamicPresets, - has_presets); + SetSampleDatabaseHasPresetsNtf(test_address, + bluetooth::has::kFeatureBitHearingAidTypeBanded | + bluetooth::has::kFeatureBitWritablePresets | + bluetooth::has::kFeatureBitDynamicPresets, + has_presets); std::vector serialized; - EXPECT_CALL( - btif_storage_interface_, - AddLeaudioHasDevice(test_address, _, - bluetooth::has::kFeatureBitHearingAidTypeBanded | - bluetooth::has::kFeatureBitWritablePresets | - bluetooth::has::kFeatureBitDynamicPresets, - 1)) - .WillOnce(SaveArg<1>(&serialized)); + EXPECT_CALL(btif_storage_interface_, + AddLeaudioHasDevice(test_address, _, + bluetooth::has::kFeatureBitHearingAidTypeBanded | + bluetooth::has::kFeatureBitWritablePresets | + bluetooth::has::kFeatureBitDynamicPresets, + 1)) + .WillOnce(SaveArg<1>(&serialized)); TestConnect(test_address); /* Deserialize the written binary to verify the content */ - HasDevice clone(test_address, - bluetooth::has::kFeatureBitHearingAidTypeBanded | - bluetooth::has::kFeatureBitWritablePresets | - bluetooth::has::kFeatureBitDynamicPresets); - ASSERT_TRUE(HasDevice::DeserializePresets(serialized.data(), - serialized.size(), clone)); + HasDevice clone(test_address, bluetooth::has::kFeatureBitHearingAidTypeBanded | + bluetooth::has::kFeatureBitWritablePresets | + bluetooth::has::kFeatureBitDynamicPresets); + ASSERT_TRUE(HasDevice::DeserializePresets(serialized.data(), serialized.size(), clone)); auto storage_info = clone.GetAllPresetInfo(); ASSERT_EQ(storage_info.size(), has_presets.size()); for (auto const& info : storage_info) { auto preset = has_presets.find(info.preset_index); ASSERT_NE(preset, has_presets.end()); - if (preset->GetProperties() & HasPreset::kPropertyAvailable) + if (preset->GetProperties() & HasPreset::kPropertyAvailable) { ASSERT_TRUE(info.available); - if (preset->GetProperties() & HasPreset::kPropertyWritable) + } + if (preset->GetProperties() & HasPreset::kPropertyWritable) { ASSERT_TRUE(info.writable); + } ASSERT_EQ(preset->GetName(), info.preset_name); } } @@ -1602,23 +1487,19 @@ TEST_F(HasClientTest, test_discovery_basic_has_no_opt_ntf) { uint8_t active_preset_index; uint8_t has_features; - EXPECT_CALL(*callbacks, OnDeviceAvailable(test_address, _)) - .WillOnce(SaveArg<1>(&has_features)); - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::CONNECTED, test_address)); + EXPECT_CALL(*callbacks, OnDeviceAvailable(test_address, _)).WillOnce(SaveArg<1>(&has_features)); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::CONNECTED, test_address)); EXPECT_CALL(*callbacks, OnPresetInfo(_, PresetInfoReason::ALL_PRESET_INFO, _)) - .WillOnce(DoAll(SaveArg<0>(&addr_or_group), SaveArg<2>(&preset_details))); + .WillOnce(DoAll(SaveArg<0>(&addr_or_group), SaveArg<2>(&preset_details))); EXPECT_CALL(*callbacks, OnActivePresetSelected(_, _)) - .WillOnce( - DoAll(SaveArg<0>(&addr_or_group), SaveArg<1>(&active_preset_index))); + .WillOnce(DoAll(SaveArg<0>(&addr_or_group), SaveArg<1>(&active_preset_index))); TestConnect(test_address); /* Verify sample database content */ ASSERT_TRUE(std::holds_alternative(addr_or_group)); ASSERT_EQ(std::get(addr_or_group), test_address); ASSERT_EQ(has_features, 0x00); - ASSERT_EQ(active_preset_index, - current_peer_presets_.at(test_conn_id).begin()->GetIndex()); + ASSERT_EQ(active_preset_index, current_peer_presets_.at(test_conn_id).begin()->GetIndex()); /* Verify presets */ uint16_t conn_id = GetTestConnId(test_address); @@ -1626,11 +1507,10 @@ TEST_F(HasClientTest, test_discovery_basic_has_no_opt_ntf) { ASSERT_EQ(current_peer_presets_.at(conn_id).size(), preset_details.size()); for (auto const& preset : current_peer_presets_.at(conn_id)) { - auto it = - std::find_if(preset_details.cbegin(), preset_details.cend(), - [&preset](auto const& preset_info) { - return preset_info.preset_index == preset.GetIndex(); - }); + auto it = std::find_if(preset_details.cbegin(), preset_details.cend(), + [&preset](auto const& preset_info) { + return preset_info.preset_index == preset.GetIndex(); + }); ASSERT_NE(it, preset_details.cend()); ASSERT_EQ(preset.GetName(), it->preset_name); ASSERT_EQ(preset.IsAvailable(), it->available); @@ -1638,12 +1518,10 @@ TEST_F(HasClientTest, test_discovery_basic_has_no_opt_ntf) { } /* Verify active preset is there */ - ASSERT_EQ(preset_details.size(), - current_peer_presets_.at(test_conn_id).size()); + ASSERT_EQ(preset_details.size(), current_peer_presets_.at(test_conn_id).size()); ASSERT_TRUE(std::find_if(preset_details.begin(), preset_details.end(), [active_preset_index](auto const& preset_info) { - return preset_info.preset_index == - active_preset_index; + return preset_info.preset_index == active_preset_index; }) != preset_details.end()); } @@ -1651,13 +1529,10 @@ TEST_F(HasClientTest, test_discovery_has_not_found) { const RawAddress test_address = GetTestAddress(1); SetSampleDatabaseNoHas(test_address); - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::CONNECTED, test_address)) - .Times(0); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::CONNECTED, test_address)).Times(0); EXPECT_CALL(*callbacks, OnDeviceAvailable(test_address, _)).Times(0); EXPECT_CALL(*callbacks, OnFeaturesUpdate(test_address, _)).Times(0); - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::DISCONNECTED, test_address)); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::DISCONNECTED, test_address)); TestConnect(test_address); } @@ -1666,13 +1541,10 @@ TEST_F(HasClientTest, test_discovery_has_broken_no_active_preset) { const RawAddress test_address = GetTestAddress(1); SetSampleDatabaseHasBrokenNoActivePreset(test_address); - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::CONNECTED, test_address)) - .Times(0); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::CONNECTED, test_address)).Times(0); EXPECT_CALL(*callbacks, OnDeviceAvailable(test_address, _)).Times(0); EXPECT_CALL(*callbacks, OnFeaturesUpdate(test_address, _)).Times(0); - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::DISCONNECTED, test_address)); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::DISCONNECTED, test_address)); TestConnect(test_address); } @@ -1681,13 +1553,10 @@ TEST_F(HasClientTest, test_discovery_has_broken_no_active_preset_ntf) { const RawAddress test_address = GetTestAddress(1); SetSampleDatabaseHasBrokenNoActivePresetNtf(test_address); - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::CONNECTED, test_address)) - .Times(0); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::CONNECTED, test_address)).Times(0); EXPECT_CALL(*callbacks, OnDeviceAvailable(test_address, _)).Times(0); EXPECT_CALL(*callbacks, OnFeaturesUpdate(test_address, _)).Times(0); - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::DISCONNECTED, test_address)); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::DISCONNECTED, test_address)); TestConnect(test_address); } @@ -1697,28 +1566,21 @@ TEST_F(HasClientTest, test_discovery_has_features_ntf) { auto test_conn_id = GetTestConnId(test_address); uint8_t has_features; - SetSampleDatabaseHasOnlyFeaturesNtf( - test_address, bluetooth::has::kFeatureBitHearingAidTypeBanded); + SetSampleDatabaseHasOnlyFeaturesNtf(test_address, + bluetooth::has::kFeatureBitHearingAidTypeBanded); - EXPECT_CALL(*callbacks, OnDeviceAvailable(test_address, _)) - .WillOnce(SaveArg<1>(&has_features)); - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::CONNECTED, test_address)) - .Times(1); + EXPECT_CALL(*callbacks, OnDeviceAvailable(test_address, _)).WillOnce(SaveArg<1>(&has_features)); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::CONNECTED, test_address)).Times(1); /* Verify subscription to features */ - EXPECT_CALL(gatt_interface, RegisterForNotifications(gatt_if, _, _)) - .Times(AnyNumber()); + EXPECT_CALL(gatt_interface, RegisterForNotifications(gatt_if, _, _)).Times(AnyNumber()); EXPECT_CALL(gatt_interface, - RegisterForNotifications(gatt_if, test_address, - HasDbBuilder::kFeaturesValHdl)); + RegisterForNotifications(gatt_if, test_address, HasDbBuilder::kFeaturesValHdl)); /* Verify features CCC was written */ - EXPECT_CALL(gatt_queue, WriteDescriptor(test_conn_id, _, _, _, _, _)) - .Times(AnyNumber()); - EXPECT_CALL(gatt_queue, - WriteDescriptor(test_conn_id, HasDbBuilder::kFeaturesValHdl + 1, - std::vector{0x01, 0x00}, _, _, _)); + EXPECT_CALL(gatt_queue, WriteDescriptor(test_conn_id, _, _, _, _, _)).Times(AnyNumber()); + EXPECT_CALL(gatt_queue, WriteDescriptor(test_conn_id, HasDbBuilder::kFeaturesValHdl + 1, + std::vector{0x01, 0x00}, _, _, _)); TestConnect(test_address); /* Verify features */ @@ -1727,10 +1589,8 @@ TEST_F(HasClientTest, test_discovery_has_features_ntf) { uint8_t new_features; /* Verify peer features change notification */ - EXPECT_CALL(*callbacks, OnFeaturesUpdate(test_address, _)) - .WillOnce(SaveArg<1>(&new_features)); - InjectNotificationEvent(test_address, test_conn_id, - HasDbBuilder::kFeaturesValHdl, + EXPECT_CALL(*callbacks, OnFeaturesUpdate(test_address, _)).WillOnce(SaveArg<1>(&new_features)); + InjectNotificationEvent(test_address, test_conn_id, HasDbBuilder::kFeaturesValHdl, std::vector({0x00})); ASSERT_NE(has_features, new_features); } @@ -1740,30 +1600,23 @@ TEST_F(HasClientTest, test_discovery_has_features_no_ntf) { auto test_conn_id = GetTestConnId(test_address); uint8_t has_features; - SetSampleDatabaseHasOnlyFeaturesNoNtf( - test_address, bluetooth::has::kFeatureBitHearingAidTypeBanded); + SetSampleDatabaseHasOnlyFeaturesNoNtf(test_address, + bluetooth::has::kFeatureBitHearingAidTypeBanded); - EXPECT_CALL(*callbacks, OnDeviceAvailable(test_address, _)) - .WillOnce(SaveArg<1>(&has_features)); - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::CONNECTED, test_address)) - .Times(1); + EXPECT_CALL(*callbacks, OnDeviceAvailable(test_address, _)).WillOnce(SaveArg<1>(&has_features)); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::CONNECTED, test_address)).Times(1); /* Verify no subscription to features */ - EXPECT_CALL(gatt_interface, RegisterForNotifications(gatt_if, _, _)) - .Times(AnyNumber()); + EXPECT_CALL(gatt_interface, RegisterForNotifications(gatt_if, _, _)).Times(AnyNumber()); EXPECT_CALL(gatt_interface, - RegisterForNotifications(gatt_if, test_address, - HasDbBuilder::kFeaturesValHdl)) - .Times(0); + RegisterForNotifications(gatt_if, test_address, HasDbBuilder::kFeaturesValHdl)) + .Times(0); /* Verify no features CCC was written */ - EXPECT_CALL(gatt_queue, WriteDescriptor(test_conn_id, _, _, _, _, _)) - .Times(AnyNumber()); + EXPECT_CALL(gatt_queue, WriteDescriptor(test_conn_id, _, _, _, _, _)).Times(AnyNumber()); EXPECT_CALL(gatt_queue, - WriteDescriptor(test_conn_id, HasDbBuilder::kFeaturesValHdl + 1, - _, _, _, _)) - .Times(0); + WriteDescriptor(test_conn_id, HasDbBuilder::kFeaturesValHdl + 1, _, _, _, _)) + .Times(0); TestConnect(test_address); /* Verify features */ @@ -1772,36 +1625,29 @@ TEST_F(HasClientTest, test_discovery_has_features_no_ntf) { TEST_F(HasClientTest, test_discovery_has_multiple_presets_ntf) { const RawAddress test_address = GetTestAddress(1); - SetSampleDatabaseHasPresetsNtf( - test_address, bluetooth::has::kFeatureBitHearingAidTypeBanded); + SetSampleDatabaseHasPresetsNtf(test_address, bluetooth::has::kFeatureBitHearingAidTypeBanded); std::variant addr_or_group = test_address; std::vector preset_details; uint8_t active_preset_index; uint8_t has_features; - EXPECT_CALL(*callbacks, OnDeviceAvailable(test_address, _)) - .WillOnce(SaveArg<1>(&has_features)); - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::CONNECTED, test_address)); + EXPECT_CALL(*callbacks, OnDeviceAvailable(test_address, _)).WillOnce(SaveArg<1>(&has_features)); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::CONNECTED, test_address)); EXPECT_CALL(*callbacks, OnPresetInfo(_, PresetInfoReason::ALL_PRESET_INFO, _)) - .WillOnce(DoAll(SaveArg<0>(&addr_or_group), SaveArg<2>(&preset_details))); + .WillOnce(DoAll(SaveArg<0>(&addr_or_group), SaveArg<2>(&preset_details))); EXPECT_CALL(*callbacks, OnActivePresetSelected(_, _)) - .WillOnce( - DoAll(SaveArg<0>(&addr_or_group), SaveArg<1>(&active_preset_index))); + .WillOnce(DoAll(SaveArg<0>(&addr_or_group), SaveArg<1>(&active_preset_index))); /* Verify subscription to control point */ - EXPECT_CALL(gatt_interface, RegisterForNotifications(gatt_if, _, _)) - .Times(AnyNumber()); + EXPECT_CALL(gatt_interface, RegisterForNotifications(gatt_if, _, _)).Times(AnyNumber()); EXPECT_CALL(gatt_interface, - RegisterForNotifications(gatt_if, test_address, - HasDbBuilder::kPresetsCtpValHdl)); + RegisterForNotifications(gatt_if, test_address, HasDbBuilder::kPresetsCtpValHdl)); /* Verify features CCC was written */ EXPECT_CALL(gatt_queue, WriteDescriptor(1, _, _, _, _, _)).Times(AnyNumber()); - EXPECT_CALL(gatt_queue, - WriteDescriptor(1, HasDbBuilder::kPresetsCtpValHdl + 1, - std::vector{0x03, 0x00}, _, _, _)); + EXPECT_CALL(gatt_queue, WriteDescriptor(1, HasDbBuilder::kPresetsCtpValHdl + 1, + std::vector{0x03, 0x00}, _, _, _)); TestConnect(test_address); /* Verify features */ @@ -1816,20 +1662,15 @@ TEST_F(HasClientTest, test_active_preset_change) { uint8_t active_preset_index; EXPECT_CALL(*callbacks, OnDeviceAvailable(test_address, _)); - EXPECT_CALL(*callbacks, - OnPresetInfo(_, PresetInfoReason::ALL_PRESET_INFO, _)); - EXPECT_CALL(*callbacks, OnActivePresetSelected(_, _)) - .WillOnce(SaveArg<1>(&active_preset_index)); - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::CONNECTED, test_address)); + EXPECT_CALL(*callbacks, OnPresetInfo(_, PresetInfoReason::ALL_PRESET_INFO, _)); + EXPECT_CALL(*callbacks, OnActivePresetSelected(_, _)).WillOnce(SaveArg<1>(&active_preset_index)); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::CONNECTED, test_address)); TestConnect(test_address); uint8_t new_active_preset; - EXPECT_CALL(*callbacks, OnActivePresetSelected( - std::variant(test_address), _)) - .WillOnce(SaveArg<1>(&new_active_preset)); - InjectNotificationEvent(test_address, test_conn_id, - HasDbBuilder::kActivePresetIndexValHdl, + EXPECT_CALL(*callbacks, OnActivePresetSelected(std::variant(test_address), _)) + .WillOnce(SaveArg<1>(&new_active_preset)); + InjectNotificationEvent(test_address, test_conn_id, HasDbBuilder::kActivePresetIndexValHdl, std::vector({0x00})); ASSERT_NE(active_preset_index, new_active_preset); @@ -1842,25 +1683,21 @@ TEST_F(HasClientTest, test_duplicate_presets) { /* Handle duplicates gracefully */ SetSampleDatabaseHasPresetsNtf( - test_address, kFeatureBitWritablePresets, - {{HasPreset(5, - HasPreset::kPropertyAvailable | HasPreset::kPropertyWritable, - "YourWritablePreset5"), - HasPreset(5, - HasPreset::kPropertyAvailable | HasPreset::kPropertyWritable, - "YourWritablePreset5")}}); + test_address, kFeatureBitWritablePresets, + {{HasPreset(5, HasPreset::kPropertyAvailable | HasPreset::kPropertyWritable, + "YourWritablePreset5"), + HasPreset(5, HasPreset::kPropertyAvailable | HasPreset::kPropertyWritable, + "YourWritablePreset5")}}); - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::CONNECTED, test_address)); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::CONNECTED, test_address)); EXPECT_CALL(*callbacks, OnPresetInfo(_, PresetInfoReason::ALL_PRESET_INFO, _)) - .WillOnce(SaveArg<2>(&preset_details)); + .WillOnce(SaveArg<2>(&preset_details)); TestConnect(test_address); /* Verify presets - expect 1, no duplicates */ ASSERT_EQ(preset_details.size(), 1u); - auto preset = std::find_if( - preset_details.begin(), preset_details.end(), - [](auto const& preset_info) { return preset_info.preset_index == 5; }); + auto preset = std::find_if(preset_details.begin(), preset_details.end(), + [](auto const& preset_info) { return preset_info.preset_index == 5; }); ASSERT_TRUE(preset != preset_details.end()); ASSERT_EQ("YourWritablePreset5", preset->preset_name); ASSERT_TRUE(preset->available); @@ -1872,14 +1709,12 @@ TEST_F(HasClientTest, test_preset_set_name_invalid_index) { SetSampleDatabaseHasPresetsNtf(test_address); TestConnect(test_address); - EXPECT_CALL(*callbacks, - OnSetPresetNameError(std::variant(test_address), - 0x40, ErrorCode::INVALID_PRESET_INDEX)) - .Times(1); + EXPECT_CALL(*callbacks, OnSetPresetNameError(std::variant(test_address), 0x40, + ErrorCode::INVALID_PRESET_INDEX)) + .Times(1); EXPECT_CALL(gatt_queue, - WriteCharacteristic(1, HasDbBuilder::kPresetsCtpValHdl, _, - GATT_WRITE, _, _)) - .Times(0); + WriteCharacteristic(1, HasDbBuilder::kPresetsCtpValHdl, _, GATT_WRITE, _, _)) + .Times(0); HasClient::Get()->SetPresetName(test_address, 0x40, "new preset name"); } @@ -1889,26 +1724,22 @@ TEST_F(HasClientTest, test_preset_set_name_non_writable) { uint16_t test_conn_id = GetTestConnId(test_address); SetSampleDatabaseHasPresetsNtf( - test_address, kFeatureBitWritablePresets, - {{ - HasPreset(5, HasPreset::kPropertyAvailable, "YourPreset5"), - HasPreset( - 55, HasPreset::kPropertyAvailable | HasPreset::kPropertyWritable, - "YourWritablePreset55"), - }}); + test_address, kFeatureBitWritablePresets, + {{ + HasPreset(5, HasPreset::kPropertyAvailable, "YourPreset5"), + HasPreset(55, HasPreset::kPropertyAvailable | HasPreset::kPropertyWritable, + "YourWritablePreset55"), + }}); TestConnect(test_address); - EXPECT_CALL(*callbacks, - OnSetPresetNameError(_, _, ErrorCode::SET_NAME_NOT_ALLOWED)) - .Times(1); + EXPECT_CALL(*callbacks, OnSetPresetNameError(_, _, ErrorCode::SET_NAME_NOT_ALLOWED)).Times(1); EXPECT_CALL(gatt_queue, - WriteCharacteristic(1, HasDbBuilder::kPresetsCtpValHdl, _, - GATT_WRITE, _, _)) - .Times(0); + WriteCharacteristic(1, HasDbBuilder::kPresetsCtpValHdl, _, GATT_WRITE, _, _)) + .Times(0); - HasClient::Get()->SetPresetName( - test_address, current_peer_presets_.at(test_conn_id).begin()->GetIndex(), - "new preset name"); + HasClient::Get()->SetPresetName(test_address, + current_peer_presets_.at(test_conn_id).begin()->GetIndex(), + "new preset name"); } TEST_F(HasClientTest, test_preset_set_name_to_long) { @@ -1916,22 +1747,18 @@ TEST_F(HasClientTest, test_preset_set_name_to_long) { uint16_t test_conn_id = GetTestConnId(test_address); SetSampleDatabaseHasPresetsNtf( - test_address, kFeatureBitWritablePresets, - {{HasPreset(5, - HasPreset::kPropertyAvailable | HasPreset::kPropertyWritable, - "YourWritablePreset")}}); + test_address, kFeatureBitWritablePresets, + {{HasPreset(5, HasPreset::kPropertyAvailable | HasPreset::kPropertyWritable, + "YourWritablePreset")}}); TestConnect(test_address); - EXPECT_CALL(*callbacks, - OnSetPresetNameError(_, _, ErrorCode::INVALID_PRESET_NAME_LENGTH)) - .Times(1); - EXPECT_CALL(gatt_queue, - WriteCharacteristic(test_conn_id, HasDbBuilder::kPresetsCtpValHdl, - _, GATT_WRITE, _, _)) - .Times(0); + EXPECT_CALL(*callbacks, OnSetPresetNameError(_, _, ErrorCode::INVALID_PRESET_NAME_LENGTH)) + .Times(1); + EXPECT_CALL(gatt_queue, WriteCharacteristic(test_conn_id, HasDbBuilder::kPresetsCtpValHdl, _, + GATT_WRITE, _, _)) + .Times(0); - HasClient::Get()->SetPresetName(test_address, 5, - "this name is more than 40 characters long"); + HasClient::Get()->SetPresetName(test_address, 5, "this name is more than 40 characters long"); } TEST_F(HasClientTest, test_preset_set_name) { @@ -1939,24 +1766,21 @@ TEST_F(HasClientTest, test_preset_set_name) { uint16_t test_conn_id = GetTestConnId(test_address); SetSampleDatabaseHasPresetsNtf( - test_address, kFeatureBitWritablePresets, - {{HasPreset(5, - HasPreset::kPropertyAvailable | HasPreset::kPropertyWritable, - "YourWritablePreset5")}}); + test_address, kFeatureBitWritablePresets, + {{HasPreset(5, HasPreset::kPropertyAvailable | HasPreset::kPropertyWritable, + "YourWritablePreset5")}}); TestConnect(test_address); std::vector value; EXPECT_CALL(*callbacks, OnSetPresetNameError(_, _, _)).Times(0); - EXPECT_CALL(gatt_queue, - WriteCharacteristic(test_conn_id, HasDbBuilder::kPresetsCtpValHdl, - _, GATT_WRITE, _, _)); + EXPECT_CALL(gatt_queue, WriteCharacteristic(test_conn_id, HasDbBuilder::kPresetsCtpValHdl, _, + GATT_WRITE, _, _)); std::vector updated_preset_details; - EXPECT_CALL(*callbacks, - OnPresetInfo(std::variant(test_address), - PresetInfoReason::PRESET_INFO_UPDATE, _)) - .WillOnce(SaveArg<2>(&updated_preset_details)); + EXPECT_CALL(*callbacks, OnPresetInfo(std::variant(test_address), + PresetInfoReason::PRESET_INFO_UPDATE, _)) + .WillOnce(SaveArg<2>(&updated_preset_details)); HasClient::Get()->SetPresetName(test_address, 5, "new preset name"); ASSERT_EQ(1u, updated_preset_details.size()); @@ -1966,14 +1790,12 @@ TEST_F(HasClientTest, test_preset_set_name) { TEST_F(HasClientTest, test_preset_group_set_name) { /* None of these devices support preset syncing */ const RawAddress test_address1 = GetTestAddress(1); - SetSampleDatabaseHasPresetsNtf( - test_address1, bluetooth::has::kFeatureBitHearingAidTypeBinaural | - bluetooth::has::kFeatureBitWritablePresets); + SetSampleDatabaseHasPresetsNtf(test_address1, bluetooth::has::kFeatureBitHearingAidTypeBinaural | + bluetooth::has::kFeatureBitWritablePresets); const RawAddress test_address2 = GetTestAddress(2); - SetSampleDatabaseHasPresetsNtf( - test_address2, bluetooth::has::kFeatureBitHearingAidTypeBinaural | - bluetooth::has::kFeatureBitWritablePresets); + SetSampleDatabaseHasPresetsNtf(test_address2, bluetooth::has::kFeatureBitHearingAidTypeBinaural | + bluetooth::has::kFeatureBitWritablePresets); TestConnect(test_address1); TestConnect(test_address2); @@ -1981,41 +1803,33 @@ TEST_F(HasClientTest, test_preset_group_set_name) { /* Mock the csis group with two devices */ uint8_t not_synced_group = 13; ON_CALL(mock_csis_client_module_, GetDeviceList(not_synced_group)) - .WillByDefault( - Return(std::vector({{test_address1, test_address2}}))); - ON_CALL( - mock_csis_client_module_, - GetGroupId(test_address1, ::bluetooth::le_audio::uuid::kCapServiceUuid)) - .WillByDefault(Return(not_synced_group)); - ON_CALL( - mock_csis_client_module_, - GetGroupId(test_address2, ::bluetooth::le_audio::uuid::kCapServiceUuid)) - .WillByDefault(Return(not_synced_group)); + .WillByDefault(Return(std::vector({{test_address1, test_address2}}))); + ON_CALL(mock_csis_client_module_, + GetGroupId(test_address1, ::bluetooth::le_audio::uuid::kCapServiceUuid)) + .WillByDefault(Return(not_synced_group)); + ON_CALL(mock_csis_client_module_, + GetGroupId(test_address2, ::bluetooth::le_audio::uuid::kCapServiceUuid)) + .WillByDefault(Return(not_synced_group)); std::vector preset_details; - EXPECT_CALL(*callbacks, OnActivePresetSelected( - std::variant(test_address1), 55)) - .Times(0); - EXPECT_CALL(*callbacks, OnActivePresetSelected( - std::variant(test_address2), 55)) - .Times(0); + EXPECT_CALL(*callbacks, OnActivePresetSelected(std::variant(test_address1), 55)) + .Times(0); + EXPECT_CALL(*callbacks, OnActivePresetSelected(std::variant(test_address2), 55)) + .Times(0); /* This should be a group callback */ - EXPECT_CALL(*callbacks, - OnPresetInfo(std::variant(not_synced_group), - PresetInfoReason::PRESET_INFO_UPDATE, _)) - .Times(1) - .WillOnce(SaveArg<2>(&preset_details)); + EXPECT_CALL(*callbacks, OnPresetInfo(std::variant(not_synced_group), + PresetInfoReason::PRESET_INFO_UPDATE, _)) + .Times(1) + .WillOnce(SaveArg<2>(&preset_details)); /* No locally synced opcodes support so expect both devices getting writes */ EXPECT_CALL(gatt_queue, WriteCharacteristic(GetTestConnId(test_address1), - HasDbBuilder::kPresetsCtpValHdl, - _, GATT_WRITE, _, _)) - .Times(1); + HasDbBuilder::kPresetsCtpValHdl, _, GATT_WRITE, _, _)) + .Times(1); EXPECT_CALL(gatt_queue, WriteCharacteristic(GetTestConnId(test_address2), - HasDbBuilder::kPresetsCtpValHdl, - _, GATT_WRITE, _, _)) - .Times(1); + HasDbBuilder::kPresetsCtpValHdl, _, GATT_WRITE, _, _)) + .Times(1); HasClient::Get()->SetPresetName(not_synced_group, 55, "new preset name"); ASSERT_EQ(preset_details.size(), 1u); @@ -2026,33 +1840,30 @@ TEST_F(HasClientTest, test_preset_group_set_name) { TEST_F(HasClientTest, test_multiple_presets_get_name) { const RawAddress test_address = GetTestAddress(1); SetSampleDatabaseHasPresetsNtf( - test_address, kFeatureBitWritablePresets, - {{ - HasPreset( - 5, HasPreset::kPropertyAvailable | HasPreset::kPropertyWritable, - "YourWritablePreset5"), - HasPreset(55, HasPreset::kPropertyAvailable, "YourPreset55"), - HasPreset(99, 0, "YourPreset99"), - }}); + test_address, kFeatureBitWritablePresets, + {{ + HasPreset(5, HasPreset::kPropertyAvailable | HasPreset::kPropertyWritable, + "YourWritablePreset5"), + HasPreset(55, HasPreset::kPropertyAvailable, "YourPreset55"), + HasPreset(99, 0, "YourPreset99"), + }}); std::vector preset_details; EXPECT_CALL(*callbacks, OnDeviceAvailable(test_address, _)); - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::CONNECTED, test_address)); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::CONNECTED, test_address)); EXPECT_CALL(*callbacks, OnPresetInfo(_, PresetInfoReason::ALL_PRESET_INFO, _)) - .WillOnce(SaveArg<2>(&preset_details)); + .WillOnce(SaveArg<2>(&preset_details)); TestConnect(test_address); /* Get each preset info individually */ for (auto const& preset : preset_details) { std::vector new_preset_details; - EXPECT_CALL(*callbacks, - OnPresetInfo(std::variant(test_address), - PresetInfoReason::PRESET_INFO_REQUEST_RESPONSE, _)) - .Times(1) - .WillOnce(SaveArg<2>(&new_preset_details)); + EXPECT_CALL(*callbacks, OnPresetInfo(std::variant(test_address), + PresetInfoReason::PRESET_INFO_REQUEST_RESPONSE, _)) + .Times(1) + .WillOnce(SaveArg<2>(&new_preset_details)); HasClient::Get()->GetPresetInfo(test_address, preset.preset_index); Mock::VerifyAndClearExpectations(&*callbacks); @@ -2069,14 +1880,12 @@ TEST_F(HasClientTest, test_presets_get_name_invalid_index) { SetSampleDatabaseHasPresetsNtf(test_address); TestConnect(test_address); - EXPECT_CALL(*callbacks, - OnPresetInfoError(std::variant(test_address), - 128, ErrorCode::INVALID_PRESET_INDEX)); + EXPECT_CALL(*callbacks, OnPresetInfoError(std::variant(test_address), 128, + ErrorCode::INVALID_PRESET_INDEX)); HasClient::Get()->GetPresetInfo(test_address, 128); - EXPECT_CALL(*callbacks, - OnPresetInfoError(std::variant(test_address), 0, - ErrorCode::INVALID_PRESET_INDEX)); + EXPECT_CALL(*callbacks, OnPresetInfoError(std::variant(test_address), 0, + ErrorCode::INVALID_PRESET_INDEX)); HasClient::Get()->GetPresetInfo(test_address, 0); } @@ -2085,40 +1894,34 @@ TEST_F(HasClientTest, test_presets_changed_generic_update_no_add_or_delete) { uint16_t test_conn_id = GetTestConnId(test_address); std::set presets = {{ - HasPreset(1, HasPreset::kPropertyAvailable, "Universal"), - HasPreset(2, HasPreset::kPropertyAvailable | HasPreset::kPropertyWritable, - "Preset2"), - HasPreset(4, HasPreset::kPropertyAvailable, "Preset4"), - HasPreset(7, HasPreset::kPropertyAvailable, "Preset7"), + HasPreset(1, HasPreset::kPropertyAvailable, "Universal"), + HasPreset(2, HasPreset::kPropertyAvailable | HasPreset::kPropertyWritable, "Preset2"), + HasPreset(4, HasPreset::kPropertyAvailable, "Preset4"), + HasPreset(7, HasPreset::kPropertyAvailable, "Preset7"), }}; - SetSampleDatabaseHasPresetsNtf( - test_address, - bluetooth::has::kFeatureBitHearingAidTypeBanded | - bluetooth::has::kFeatureBitDynamicPresets | - bluetooth::has::kFeatureBitWritablePresets, - presets); + SetSampleDatabaseHasPresetsNtf(test_address, + bluetooth::has::kFeatureBitHearingAidTypeBanded | + bluetooth::has::kFeatureBitDynamicPresets | + bluetooth::has::kFeatureBitWritablePresets, + presets); - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::CONNECTED, test_address)); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::CONNECTED, test_address)); TestConnect(test_address); std::vector preset_details; - EXPECT_CALL(*callbacks, - OnPresetInfo(std::variant(test_address), - PresetInfoReason::PRESET_INFO_UPDATE, _)) - .Times(1) - .WillOnce(SaveArg<2>(&preset_details)); + EXPECT_CALL(*callbacks, OnPresetInfo(std::variant(test_address), + PresetInfoReason::PRESET_INFO_UPDATE, _)) + .Times(1) + .WillOnce(SaveArg<2>(&preset_details)); /* Inject generic update on the first preset */ auto preset_index = 2; auto new_test_preset = HasPreset(preset_index, 0, "props new name"); - ASSERT_NE(*current_peer_presets_.at(test_conn_id).find(preset_index), - new_test_preset); + ASSERT_NE(*current_peer_presets_.at(test_conn_id).find(preset_index), new_test_preset); - InjectPresetChanged( - test_conn_id, test_address, false, new_test_preset, 1 /* prev_index */, - ::bluetooth::le_audio::has::PresetCtpChangeId::PRESET_GENERIC_UPDATE, - true /* is_last */); + InjectPresetChanged(test_conn_id, test_address, false, new_test_preset, 1 /* prev_index */, + ::bluetooth::le_audio::has::PresetCtpChangeId::PRESET_GENERIC_UPDATE, + true /* is_last */); /* Verify received preset info update on the 2nd preset */ ASSERT_EQ(1u, preset_details.size()); @@ -2133,84 +1936,69 @@ TEST_F(HasClientTest, test_presets_changed_generic_update_add_and_delete) { uint16_t test_conn_id = GetTestConnId(test_address); std::set presets = {{ - HasPreset(1, HasPreset::kPropertyAvailable, "Universal"), - HasPreset(2, HasPreset::kPropertyAvailable | HasPreset::kPropertyWritable, - "Preset2"), - HasPreset(4, HasPreset::kPropertyAvailable, "Preset4"), - HasPreset(5, HasPreset::kPropertyAvailable, "Preset5"), - HasPreset(32, HasPreset::kPropertyAvailable, "Preset32"), + HasPreset(1, HasPreset::kPropertyAvailable, "Universal"), + HasPreset(2, HasPreset::kPropertyAvailable | HasPreset::kPropertyWritable, "Preset2"), + HasPreset(4, HasPreset::kPropertyAvailable, "Preset4"), + HasPreset(5, HasPreset::kPropertyAvailable, "Preset5"), + HasPreset(32, HasPreset::kPropertyAvailable, "Preset32"), }}; - SetSampleDatabaseHasPresetsNtf( - test_address, - bluetooth::has::kFeatureBitHearingAidTypeBanded | - bluetooth::has::kFeatureBitWritablePresets, - presets); + SetSampleDatabaseHasPresetsNtf(test_address, + bluetooth::has::kFeatureBitHearingAidTypeBanded | + bluetooth::has::kFeatureBitWritablePresets, + presets); std::vector preset_details; - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::CONNECTED, test_address)); - EXPECT_CALL(*callbacks, - OnPresetInfo(std::variant(test_address), - PresetInfoReason::ALL_PRESET_INFO, _)) - .Times(1) - .WillOnce(SaveArg<2>(&preset_details)); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::CONNECTED, test_address)); + EXPECT_CALL(*callbacks, OnPresetInfo(std::variant(test_address), + PresetInfoReason::ALL_PRESET_INFO, _)) + .Times(1) + .WillOnce(SaveArg<2>(&preset_details)); TestConnect(test_address); /* Expect more OnPresetInfo call */ std::vector updated_preset_details; - EXPECT_CALL(*callbacks, - OnPresetInfo(std::variant(test_address), - PresetInfoReason::PRESET_INFO_UPDATE, _)) - .Times(1) - .WillOnce(SaveArg<2>(&updated_preset_details)); + EXPECT_CALL(*callbacks, OnPresetInfo(std::variant(test_address), + PresetInfoReason::PRESET_INFO_UPDATE, _)) + .Times(1) + .WillOnce(SaveArg<2>(&updated_preset_details)); /* Expect more OnPresetInfo call */ std::vector deleted_preset_details; - EXPECT_CALL(*callbacks, - OnPresetInfo(std::variant(test_address), - PresetInfoReason::PRESET_DELETED, _)) - .Times(1) - .WillOnce(SaveArg<2>(&deleted_preset_details)); + EXPECT_CALL(*callbacks, OnPresetInfo(std::variant(test_address), + PresetInfoReason::PRESET_DELETED, _)) + .Times(1) + .WillOnce(SaveArg<2>(&deleted_preset_details)); /* Inject generic updates */ /* First event replaces all the existing presets from 1 to 8 with preset 8 */ - auto new_test_preset1 = - HasPreset(8, HasPreset::kPropertyAvailable, "props new name9"); - InjectPresetChanged( - test_conn_id, test_address, false, new_test_preset1, 1 /* prev_index */, - ::bluetooth::le_audio::has::PresetCtpChangeId::PRESET_GENERIC_UPDATE, - false /* is_last */); + auto new_test_preset1 = HasPreset(8, HasPreset::kPropertyAvailable, "props new name9"); + InjectPresetChanged(test_conn_id, test_address, false, new_test_preset1, 1 /* prev_index */, + ::bluetooth::le_audio::has::PresetCtpChangeId::PRESET_GENERIC_UPDATE, + false /* is_last */); /* Second event adds preset 9 to the already existing presets 1 and 8 */ - auto new_test_preset2 = - HasPreset(9, HasPreset::kPropertyAvailable | HasPreset::kPropertyWritable, - "props new name11"); - InjectPresetChanged( - test_conn_id, test_address, false, new_test_preset2, 8 /* prev_index */, - ::bluetooth::le_audio::has::PresetCtpChangeId::PRESET_GENERIC_UPDATE, - false /* is_last */); + auto new_test_preset2 = HasPreset(9, HasPreset::kPropertyAvailable | HasPreset::kPropertyWritable, + "props new name11"); + InjectPresetChanged(test_conn_id, test_address, false, new_test_preset2, 8 /* prev_index */, + ::bluetooth::le_audio::has::PresetCtpChangeId::PRESET_GENERIC_UPDATE, + false /* is_last */); /* Third event deletes preset 1 with the generic update */ - InjectPresetChanged( - test_conn_id, test_address, false, new_test_preset1, 0 /* prev_index */, - ::bluetooth::le_audio::has::PresetCtpChangeId::PRESET_GENERIC_UPDATE, - true /* is_last */); + InjectPresetChanged(test_conn_id, test_address, false, new_test_preset1, 0 /* prev_index */, + ::bluetooth::le_audio::has::PresetCtpChangeId::PRESET_GENERIC_UPDATE, + true /* is_last */); /* Verify received preset info - expect presets 1, 32 unchanged, 8, 9 * updated, and 1, 2, 4, 5 deleted. */ ASSERT_EQ(2u, updated_preset_details.size()); - ASSERT_EQ(new_test_preset1.GetIndex(), - updated_preset_details[0].preset_index); - ASSERT_EQ(new_test_preset1.IsAvailable(), - updated_preset_details[0].available); + ASSERT_EQ(new_test_preset1.GetIndex(), updated_preset_details[0].preset_index); + ASSERT_EQ(new_test_preset1.IsAvailable(), updated_preset_details[0].available); ASSERT_EQ(new_test_preset1.IsWritable(), updated_preset_details[0].writable); ASSERT_EQ(new_test_preset1.GetName(), updated_preset_details[0].preset_name); - ASSERT_EQ(new_test_preset2.GetIndex(), - updated_preset_details[1].preset_index); - ASSERT_EQ(new_test_preset2.IsAvailable(), - updated_preset_details[1].available); + ASSERT_EQ(new_test_preset2.GetIndex(), updated_preset_details[1].preset_index); + ASSERT_EQ(new_test_preset2.IsAvailable(), updated_preset_details[1].available); ASSERT_EQ(new_test_preset2.IsWritable(), updated_preset_details[1].writable); ASSERT_EQ(new_test_preset2.GetName(), updated_preset_details[1].preset_name); @@ -2226,51 +2014,42 @@ TEST_F(HasClientTest, test_presets_changed_deleted) { uint16_t test_conn_id = GetTestConnId(test_address); std::set presets = {{ - HasPreset(1, HasPreset::kPropertyAvailable, "Universal"), - HasPreset(2, HasPreset::kPropertyAvailable | HasPreset::kPropertyWritable, - "Preset2"), + HasPreset(1, HasPreset::kPropertyAvailable, "Universal"), + HasPreset(2, HasPreset::kPropertyAvailable | HasPreset::kPropertyWritable, "Preset2"), }}; - SetSampleDatabaseHasPresetsNtf( - test_address, - bluetooth::has::kFeatureBitHearingAidTypeBanded | - bluetooth::has::kFeatureBitWritablePresets | - bluetooth::has::kFeatureBitDynamicPresets, - presets); + SetSampleDatabaseHasPresetsNtf(test_address, + bluetooth::has::kFeatureBitHearingAidTypeBanded | + bluetooth::has::kFeatureBitWritablePresets | + bluetooth::has::kFeatureBitDynamicPresets, + presets); std::vector preset_details; - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::CONNECTED, test_address)); - EXPECT_CALL(*callbacks, - OnPresetInfo(std::variant(test_address), - PresetInfoReason::ALL_PRESET_INFO, _)) - .Times(1) - .WillOnce(SaveArg<2>(&preset_details)); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::CONNECTED, test_address)); + EXPECT_CALL(*callbacks, OnPresetInfo(std::variant(test_address), + PresetInfoReason::ALL_PRESET_INFO, _)) + .Times(1) + .WillOnce(SaveArg<2>(&preset_details)); TestConnect(test_address); /* Expect second OnPresetInfo call */ std::vector deleted_preset_details; - EXPECT_CALL(*callbacks, - OnPresetInfo(std::variant(test_address), - PresetInfoReason::PRESET_DELETED, _)) - .Times(1) - .WillOnce(SaveArg<2>(&deleted_preset_details)); + EXPECT_CALL(*callbacks, OnPresetInfo(std::variant(test_address), + PresetInfoReason::PRESET_DELETED, _)) + .Times(1) + .WillOnce(SaveArg<2>(&deleted_preset_details)); /* Inject preset deletion of index 2 */ auto deleted_index = preset_details[1].preset_index; InjectPresetChanged( - test_conn_id, test_address, false, *presets.find(deleted_index), - 0 /* prev_index */, - ::bluetooth::le_audio::has::PresetCtpChangeId::PRESET_DELETED, - true /* is_last */); + test_conn_id, test_address, false, *presets.find(deleted_index), 0 /* prev_index */, + ::bluetooth::le_audio::has::PresetCtpChangeId::PRESET_DELETED, true /* is_last */); ASSERT_EQ(2u, preset_details.size()); ASSERT_EQ(1u, deleted_preset_details.size()); - ASSERT_EQ(preset_details[1].preset_index, - deleted_preset_details[0].preset_index); + ASSERT_EQ(preset_details[1].preset_index, deleted_preset_details[0].preset_index); ASSERT_EQ(preset_details[1].writable, deleted_preset_details[0].writable); ASSERT_EQ(preset_details[1].available, deleted_preset_details[0].available); - ASSERT_EQ(preset_details[1].preset_name, - deleted_preset_details[0].preset_name); + ASSERT_EQ(preset_details[1].preset_name, deleted_preset_details[0].preset_name); } TEST_F(HasClientTest, test_presets_changed_available) { @@ -2278,50 +2057,41 @@ TEST_F(HasClientTest, test_presets_changed_available) { uint16_t test_conn_id = GetTestConnId(test_address); std::set presets = {{ - HasPreset(1, 0, "Universal"), - HasPreset(2, HasPreset::kPropertyAvailable | HasPreset::kPropertyWritable, - "Preset2"), + HasPreset(1, 0, "Universal"), + HasPreset(2, HasPreset::kPropertyAvailable | HasPreset::kPropertyWritable, "Preset2"), }}; - SetSampleDatabaseHasPresetsNtf( - test_address, - bluetooth::has::kFeatureBitHearingAidTypeBanded | - bluetooth::has::kFeatureBitWritablePresets | - bluetooth::has::kFeatureBitDynamicPresets, - presets); + SetSampleDatabaseHasPresetsNtf(test_address, + bluetooth::has::kFeatureBitHearingAidTypeBanded | + bluetooth::has::kFeatureBitWritablePresets | + bluetooth::has::kFeatureBitDynamicPresets, + presets); std::vector preset_details; - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::CONNECTED, test_address)); - EXPECT_CALL(*callbacks, - OnPresetInfo(std::variant(test_address), - PresetInfoReason::ALL_PRESET_INFO, _)) - .Times(1) - .WillOnce(SaveArg<2>(&preset_details)); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::CONNECTED, test_address)); + EXPECT_CALL(*callbacks, OnPresetInfo(std::variant(test_address), + PresetInfoReason::ALL_PRESET_INFO, _)) + .Times(1) + .WillOnce(SaveArg<2>(&preset_details)); TestConnect(test_address); /* Expect second OnPresetInfo call */ std::vector changed_preset_details; - EXPECT_CALL(*callbacks, - OnPresetInfo(std::variant(test_address), - PresetInfoReason::PRESET_AVAILABILITY_CHANGED, _)) - .Times(1) - .WillOnce(SaveArg<2>(&changed_preset_details)); + EXPECT_CALL(*callbacks, OnPresetInfo(std::variant(test_address), + PresetInfoReason::PRESET_AVAILABILITY_CHANGED, _)) + .Times(1) + .WillOnce(SaveArg<2>(&changed_preset_details)); /* Inject preset deletion of index 2 */ auto changed_index = preset_details[0].preset_index; InjectPresetChanged( - test_conn_id, test_address, false, *presets.find(changed_index), - 0 /* prev_index */, - ::bluetooth::le_audio::has::PresetCtpChangeId::PRESET_AVAILABLE, - true /* is_last */); + test_conn_id, test_address, false, *presets.find(changed_index), 0 /* prev_index */, + ::bluetooth::le_audio::has::PresetCtpChangeId::PRESET_AVAILABLE, true /* is_last */); ASSERT_EQ(2u, preset_details.size()); ASSERT_EQ(1u, changed_preset_details.size()); - ASSERT_EQ(preset_details[0].preset_index, - changed_preset_details[0].preset_index); + ASSERT_EQ(preset_details[0].preset_index, changed_preset_details[0].preset_index); ASSERT_EQ(preset_details[0].writable, changed_preset_details[0].writable); - ASSERT_EQ(preset_details[0].preset_name, - changed_preset_details[0].preset_name); + ASSERT_EQ(preset_details[0].preset_name, changed_preset_details[0].preset_name); /* This field should have changed */ ASSERT_NE(preset_details[0].available, changed_preset_details[0].available); ASSERT_TRUE(changed_preset_details[0].available); @@ -2332,50 +2102,41 @@ TEST_F(HasClientTest, test_presets_changed_unavailable) { uint16_t test_conn_id = GetTestConnId(test_address); std::set presets = {{ - HasPreset(1, HasPreset::kPropertyAvailable, "Universal"), - HasPreset(2, HasPreset::kPropertyAvailable | HasPreset::kPropertyWritable, - "Preset2"), + HasPreset(1, HasPreset::kPropertyAvailable, "Universal"), + HasPreset(2, HasPreset::kPropertyAvailable | HasPreset::kPropertyWritable, "Preset2"), }}; - SetSampleDatabaseHasPresetsNtf( - test_address, - bluetooth::has::kFeatureBitHearingAidTypeBanded | - bluetooth::has::kFeatureBitWritablePresets | - bluetooth::has::kFeatureBitDynamicPresets, - presets); + SetSampleDatabaseHasPresetsNtf(test_address, + bluetooth::has::kFeatureBitHearingAidTypeBanded | + bluetooth::has::kFeatureBitWritablePresets | + bluetooth::has::kFeatureBitDynamicPresets, + presets); std::vector preset_details; - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::CONNECTED, test_address)); - EXPECT_CALL(*callbacks, - OnPresetInfo(std::variant(test_address), - PresetInfoReason::ALL_PRESET_INFO, _)) - .Times(1) - .WillOnce(SaveArg<2>(&preset_details)); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::CONNECTED, test_address)); + EXPECT_CALL(*callbacks, OnPresetInfo(std::variant(test_address), + PresetInfoReason::ALL_PRESET_INFO, _)) + .Times(1) + .WillOnce(SaveArg<2>(&preset_details)); TestConnect(test_address); /* Expect second OnPresetInfo call */ std::vector changed_preset_details; - EXPECT_CALL(*callbacks, - OnPresetInfo(std::variant(test_address), - PresetInfoReason::PRESET_AVAILABILITY_CHANGED, _)) - .Times(1) - .WillOnce(SaveArg<2>(&changed_preset_details)); + EXPECT_CALL(*callbacks, OnPresetInfo(std::variant(test_address), + PresetInfoReason::PRESET_AVAILABILITY_CHANGED, _)) + .Times(1) + .WillOnce(SaveArg<2>(&changed_preset_details)); /* Inject preset deletion of index 2 */ auto changed_index = preset_details[0].preset_index; InjectPresetChanged( - test_conn_id, test_address, false, *presets.find(changed_index), - 0 /* prev_index */, - ::bluetooth::le_audio::has::PresetCtpChangeId::PRESET_UNAVAILABLE, - true /* is_last */); + test_conn_id, test_address, false, *presets.find(changed_index), 0 /* prev_index */, + ::bluetooth::le_audio::has::PresetCtpChangeId::PRESET_UNAVAILABLE, true /* is_last */); ASSERT_EQ(2u, preset_details.size()); ASSERT_EQ(1u, changed_preset_details.size()); - ASSERT_EQ(preset_details[0].preset_index, - changed_preset_details[0].preset_index); + ASSERT_EQ(preset_details[0].preset_index, changed_preset_details[0].preset_index); ASSERT_EQ(preset_details[0].writable, changed_preset_details[0].writable); - ASSERT_EQ(preset_details[0].preset_name, - changed_preset_details[0].preset_name); + ASSERT_EQ(preset_details[0].preset_name, changed_preset_details[0].preset_name); /* This field should have changed */ ASSERT_NE(preset_details[0].available, changed_preset_details[0].available); ASSERT_FALSE(changed_preset_details[0].available); @@ -2388,15 +2149,12 @@ TEST_F(HasClientTest, test_select_preset_valid) { uint8_t active_preset_index = 0; std::vector preset_details; - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::CONNECTED, test_address)); - EXPECT_CALL(*callbacks, - OnPresetInfo(std::variant(test_address), - PresetInfoReason::ALL_PRESET_INFO, _)) - .Times(1) - .WillOnce(SaveArg<2>(&preset_details)); - EXPECT_CALL(*callbacks, OnActivePresetSelected(_, _)) - .WillOnce(SaveArg<1>(&active_preset_index)); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::CONNECTED, test_address)); + EXPECT_CALL(*callbacks, OnPresetInfo(std::variant(test_address), + PresetInfoReason::ALL_PRESET_INFO, _)) + .Times(1) + .WillOnce(SaveArg<2>(&preset_details)); + EXPECT_CALL(*callbacks, OnActivePresetSelected(_, _)).WillOnce(SaveArg<1>(&active_preset_index)); TestConnect(test_address); ASSERT_TRUE(preset_details.size() > 1); @@ -2404,10 +2162,9 @@ TEST_F(HasClientTest, test_select_preset_valid) { uint8_t new_active_preset_index = 0; EXPECT_CALL(*callbacks, OnActivePresetSelected(_, _)) - .WillOnce(SaveArg<1>(&new_active_preset_index)); + .WillOnce(SaveArg<1>(&new_active_preset_index)); - HasClient::Get()->SelectActivePreset(test_address, - preset_details.back().preset_index); + HasClient::Get()->SelectActivePreset(test_address, preset_details.back().preset_index); Mock::VerifyAndClearExpectations(&*callbacks); ASSERT_NE(active_preset_index, new_active_preset_index); @@ -2427,12 +2184,11 @@ TEST_F(HasClientTest, test_select_group_preset_invalid_group) { /* Mock the csis group with no devices */ uint8_t unlucky_group = 13; ON_CALL(mock_csis_client_module_, GetDeviceList(unlucky_group)) - .WillByDefault(Return(std::vector())); + .WillByDefault(Return(std::vector())); - EXPECT_CALL(*callbacks, OnActivePresetSelectError( - std::variant(unlucky_group), - ErrorCode::OPERATION_NOT_POSSIBLE)) - .Times(1); + EXPECT_CALL(*callbacks, OnActivePresetSelectError(std::variant(unlucky_group), + ErrorCode::OPERATION_NOT_POSSIBLE)) + .Times(1); HasClient::Get()->SelectActivePreset(unlucky_group, 6); } @@ -2440,12 +2196,10 @@ TEST_F(HasClientTest, test_select_group_preset_invalid_group) { TEST_F(HasClientTest, test_select_group_preset_valid_no_preset_sync_supported) { /* None of these devices support preset syncing */ const RawAddress test_address1 = GetTestAddress(1); - SetSampleDatabaseHasPresetsNtf( - test_address1, bluetooth::has::kFeatureBitHearingAidTypeBinaural); + SetSampleDatabaseHasPresetsNtf(test_address1, bluetooth::has::kFeatureBitHearingAidTypeBinaural); const RawAddress test_address2 = GetTestAddress(2); - SetSampleDatabaseHasPresetsNtf( - test_address2, bluetooth::has::kFeatureBitHearingAidTypeBinaural); + SetSampleDatabaseHasPresetsNtf(test_address2, bluetooth::has::kFeatureBitHearingAidTypeBinaural); TestConnect(test_address1); TestConnect(test_address2); @@ -2453,38 +2207,30 @@ TEST_F(HasClientTest, test_select_group_preset_valid_no_preset_sync_supported) { /* Mock the csis group with two devices */ uint8_t not_synced_group = 13; ON_CALL(mock_csis_client_module_, GetDeviceList(not_synced_group)) - .WillByDefault( - Return(std::vector({{test_address1, test_address2}}))); - ON_CALL( - mock_csis_client_module_, - GetGroupId(test_address1, ::bluetooth::le_audio::uuid::kCapServiceUuid)) - .WillByDefault(Return(not_synced_group)); - ON_CALL( - mock_csis_client_module_, - GetGroupId(test_address2, ::bluetooth::le_audio::uuid::kCapServiceUuid)) - .WillByDefault(Return(not_synced_group)); + .WillByDefault(Return(std::vector({{test_address1, test_address2}}))); + ON_CALL(mock_csis_client_module_, + GetGroupId(test_address1, ::bluetooth::le_audio::uuid::kCapServiceUuid)) + .WillByDefault(Return(not_synced_group)); + ON_CALL(mock_csis_client_module_, + GetGroupId(test_address2, ::bluetooth::le_audio::uuid::kCapServiceUuid)) + .WillByDefault(Return(not_synced_group)); uint8_t group_active_preset_index = 0; - EXPECT_CALL(*callbacks, OnActivePresetSelected( - std::variant(test_address1), 55)) - .Times(0); - EXPECT_CALL(*callbacks, OnActivePresetSelected( - std::variant(test_address2), 55)) - .Times(0); + EXPECT_CALL(*callbacks, OnActivePresetSelected(std::variant(test_address1), 55)) + .Times(0); + EXPECT_CALL(*callbacks, OnActivePresetSelected(std::variant(test_address2), 55)) + .Times(0); EXPECT_CALL(*callbacks, - OnActivePresetSelected( - std::variant(not_synced_group), _)) - .WillOnce(SaveArg<1>(&group_active_preset_index)); + OnActivePresetSelected(std::variant(not_synced_group), _)) + .WillOnce(SaveArg<1>(&group_active_preset_index)); /* No locally synced opcodes support so expect both devices getting writes */ EXPECT_CALL(gatt_queue, WriteCharacteristic(GetTestConnId(test_address1), - HasDbBuilder::kPresetsCtpValHdl, - _, GATT_WRITE, _, _)) - .Times(1); + HasDbBuilder::kPresetsCtpValHdl, _, GATT_WRITE, _, _)) + .Times(1); EXPECT_CALL(gatt_queue, WriteCharacteristic(GetTestConnId(test_address2), - HasDbBuilder::kPresetsCtpValHdl, - _, GATT_WRITE, _, _)) - .Times(1); + HasDbBuilder::kPresetsCtpValHdl, _, GATT_WRITE, _, _)) + .Times(1); HasClient::Get()->SelectActivePreset(not_synced_group, 55); ASSERT_EQ(group_active_preset_index, 55); @@ -2494,68 +2240,55 @@ TEST_F(HasClientTest, test_select_group_preset_valid_preset_sync_supported) { /* Only one of these devices support preset syncing */ const RawAddress test_address1 = GetTestAddress(1); uint16_t test_conn_id1 = GetTestConnId(test_address1); - SetSampleDatabaseHasPresetsNtf( - test_address1, bluetooth::has::kFeatureBitHearingAidTypeBinaural); + SetSampleDatabaseHasPresetsNtf(test_address1, bluetooth::has::kFeatureBitHearingAidTypeBinaural); const RawAddress test_address2 = GetTestAddress(2); uint16_t test_conn_id2 = GetTestConnId(test_address2); - SetSampleDatabaseHasPresetsNtf( - test_address2, - bluetooth::has::kFeatureBitHearingAidTypeBinaural | - bluetooth::has::kFeatureBitPresetSynchronizationSupported); + SetSampleDatabaseHasPresetsNtf(test_address2, + bluetooth::has::kFeatureBitHearingAidTypeBinaural | + bluetooth::has::kFeatureBitPresetSynchronizationSupported); uint8_t active_preset_index1 = 0; uint8_t active_preset_index2 = 0; - EXPECT_CALL(*callbacks, OnActivePresetSelected( - std::variant(test_address1), _)) - .WillOnce(SaveArg<1>(&active_preset_index1)); + EXPECT_CALL(*callbacks, OnActivePresetSelected(std::variant(test_address1), _)) + .WillOnce(SaveArg<1>(&active_preset_index1)); TestConnect(test_address1); - EXPECT_CALL(*callbacks, OnActivePresetSelected( - std::variant(test_address2), _)) - .WillOnce(SaveArg<1>(&active_preset_index2)); + EXPECT_CALL(*callbacks, OnActivePresetSelected(std::variant(test_address2), _)) + .WillOnce(SaveArg<1>(&active_preset_index2)); TestConnect(test_address2); /* Mock the csis group with two devices */ uint8_t synced_group = 13; ON_CALL(mock_csis_client_module_, GetDeviceList(synced_group)) - .WillByDefault( - Return(std::vector({{test_address1, test_address2}}))); - ON_CALL( - mock_csis_client_module_, - GetGroupId(test_address1, ::bluetooth::le_audio::uuid::kCapServiceUuid)) - .WillByDefault(Return(synced_group)); - ON_CALL( - mock_csis_client_module_, - GetGroupId(test_address2, ::bluetooth::le_audio::uuid::kCapServiceUuid)) - .WillByDefault(Return(synced_group)); - - EXPECT_CALL(*callbacks, OnActivePresetSelectError( - _, ErrorCode::GROUP_OPERATION_NOT_SUPPORTED)) - .Times(0); + .WillByDefault(Return(std::vector({{test_address1, test_address2}}))); + ON_CALL(mock_csis_client_module_, + GetGroupId(test_address1, ::bluetooth::le_audio::uuid::kCapServiceUuid)) + .WillByDefault(Return(synced_group)); + ON_CALL(mock_csis_client_module_, + GetGroupId(test_address2, ::bluetooth::le_audio::uuid::kCapServiceUuid)) + .WillByDefault(Return(synced_group)); + + EXPECT_CALL(*callbacks, OnActivePresetSelectError(_, ErrorCode::GROUP_OPERATION_NOT_SUPPORTED)) + .Times(0); /* Expect callback from the group but not from the devices */ uint8_t group_active_preset_index = 0; - EXPECT_CALL(*callbacks, OnActivePresetSelected( - std::variant(test_address1), _)) - .Times(0); - EXPECT_CALL(*callbacks, OnActivePresetSelected( - std::variant(test_address2), _)) - .Times(0); - EXPECT_CALL(*callbacks, OnActivePresetSelected( - std::variant(synced_group), _)) - .WillOnce(SaveArg<1>(&group_active_preset_index)); + EXPECT_CALL(*callbacks, OnActivePresetSelected(std::variant(test_address1), _)) + .Times(0); + EXPECT_CALL(*callbacks, OnActivePresetSelected(std::variant(test_address2), _)) + .Times(0); + EXPECT_CALL(*callbacks, OnActivePresetSelected(std::variant(synced_group), _)) + .WillOnce(SaveArg<1>(&group_active_preset_index)); /* Expect Ctp write on on this device which forwards operation to the other */ - EXPECT_CALL(gatt_queue, WriteCharacteristic(test_conn_id1, - HasDbBuilder::kPresetsCtpValHdl, - _, GATT_WRITE, _, _)) - .Times(0); - EXPECT_CALL(gatt_queue, WriteCharacteristic(test_conn_id2, - HasDbBuilder::kPresetsCtpValHdl, - _, GATT_WRITE, _, _)) - .Times(1); + EXPECT_CALL(gatt_queue, WriteCharacteristic(test_conn_id1, HasDbBuilder::kPresetsCtpValHdl, _, + GATT_WRITE, _, _)) + .Times(0); + EXPECT_CALL(gatt_queue, WriteCharacteristic(test_conn_id2, HasDbBuilder::kPresetsCtpValHdl, _, + GATT_WRITE, _, _)) + .Times(1); HasClient::Get()->SelectActivePreset(synced_group, 55); ASSERT_EQ(group_active_preset_index, 55); @@ -2566,29 +2299,24 @@ TEST_F(HasClientTest, test_select_preset_invalid) { uint16_t test_conn_id = GetTestConnId(test_address); std::set presets = {{ - HasPreset(1, HasPreset::kPropertyAvailable, "Universal"), - HasPreset(2, HasPreset::kPropertyAvailable | HasPreset::kPropertyWritable, - "Preset2"), + HasPreset(1, HasPreset::kPropertyAvailable, "Universal"), + HasPreset(2, HasPreset::kPropertyAvailable | HasPreset::kPropertyWritable, "Preset2"), }}; - SetSampleDatabaseHasPresetsNtf( - test_address, - bluetooth::has::kFeatureBitHearingAidTypeBanded | - bluetooth::has::kFeatureBitWritablePresets | - bluetooth::has::kFeatureBitDynamicPresets, - presets); + SetSampleDatabaseHasPresetsNtf(test_address, + bluetooth::has::kFeatureBitHearingAidTypeBanded | + bluetooth::has::kFeatureBitWritablePresets | + bluetooth::has::kFeatureBitDynamicPresets, + presets); uint8_t active_preset_index = 0; std::vector preset_details; - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::CONNECTED, test_address)); - EXPECT_CALL(*callbacks, - OnPresetInfo(std::variant(test_address), - PresetInfoReason::ALL_PRESET_INFO, _)) - .Times(1) - .WillOnce(SaveArg<2>(&preset_details)); - EXPECT_CALL(*callbacks, OnActivePresetSelected(_, _)) - .WillOnce(SaveArg<1>(&active_preset_index)); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::CONNECTED, test_address)); + EXPECT_CALL(*callbacks, OnPresetInfo(std::variant(test_address), + PresetInfoReason::ALL_PRESET_INFO, _)) + .Times(1) + .WillOnce(SaveArg<2>(&preset_details)); + EXPECT_CALL(*callbacks, OnActivePresetSelected(_, _)).WillOnce(SaveArg<1>(&active_preset_index)); TestConnect(test_address); ASSERT_TRUE(preset_details.size() > 1); @@ -2597,66 +2325,55 @@ TEST_F(HasClientTest, test_select_preset_invalid) { /* Inject preset deletion of index 2 */ auto deleted_index = preset_details[1].preset_index; InjectPresetChanged( - test_conn_id, test_address, false, *presets.find(deleted_index), - 0 /* prev_index */, - ::bluetooth::le_audio::has::PresetCtpChangeId::PRESET_DELETED, - true /* is_last */); + test_conn_id, test_address, false, *presets.find(deleted_index), 0 /* prev_index */, + ::bluetooth::le_audio::has::PresetCtpChangeId::PRESET_DELETED, true /* is_last */); - EXPECT_CALL(*callbacks, OnActivePresetSelectError( - std::variant(test_address), - ErrorCode::INVALID_PRESET_INDEX)) - .Times(1); + EXPECT_CALL(*callbacks, OnActivePresetSelectError(std::variant(test_address), + ErrorCode::INVALID_PRESET_INDEX)) + .Times(1); /* Check if preset was actually deleted - try setting it as an active one */ - HasClient::Get()->SelectActivePreset(test_address, - preset_details[1].preset_index); + HasClient::Get()->SelectActivePreset(test_address, preset_details[1].preset_index); } TEST_F(HasClientTest, test_select_preset_next) { const RawAddress test_address = GetTestAddress(1); std::set presets = {{ - HasPreset(1, HasPreset::kPropertyAvailable, "Universal"), - HasPreset(2, HasPreset::kPropertyAvailable | HasPreset::kPropertyWritable, - "Preset2"), + HasPreset(1, HasPreset::kPropertyAvailable, "Universal"), + HasPreset(2, HasPreset::kPropertyAvailable | HasPreset::kPropertyWritable, "Preset2"), }}; - SetSampleDatabaseHasPresetsNtf( - test_address, - bluetooth::has::kFeatureBitHearingAidTypeBanded | - bluetooth::has::kFeatureBitWritablePresets | - bluetooth::has::kFeatureBitDynamicPresets, - presets); + SetSampleDatabaseHasPresetsNtf(test_address, + bluetooth::has::kFeatureBitHearingAidTypeBanded | + bluetooth::has::kFeatureBitWritablePresets | + bluetooth::has::kFeatureBitDynamicPresets, + presets); uint8_t active_preset_index = 0; std::vector preset_details; - EXPECT_CALL(*callbacks, - OnPresetInfo(std::variant(test_address), - PresetInfoReason::ALL_PRESET_INFO, _)) - .Times(1) - .WillOnce(SaveArg<2>(&preset_details)); - EXPECT_CALL(*callbacks, OnActivePresetSelected(_, _)) - .WillOnce(SaveArg<1>(&active_preset_index)); + EXPECT_CALL(*callbacks, OnPresetInfo(std::variant(test_address), + PresetInfoReason::ALL_PRESET_INFO, _)) + .Times(1) + .WillOnce(SaveArg<2>(&preset_details)); + EXPECT_CALL(*callbacks, OnActivePresetSelected(_, _)).WillOnce(SaveArg<1>(&active_preset_index)); TestConnect(test_address); ASSERT_TRUE(preset_details.size() > 1); ASSERT_EQ(1, active_preset_index); /* Verify active preset change */ - EXPECT_CALL(*callbacks, OnActivePresetSelected( - std::variant(test_address), 2)); + EXPECT_CALL(*callbacks, OnActivePresetSelected(std::variant(test_address), 2)); HasClient::Get()->NextActivePreset(test_address); } TEST_F(HasClientTest, test_select_group_preset_next_no_preset_sync_supported) { /* None of these devices support preset syncing */ const RawAddress test_address1 = GetTestAddress(1); - SetSampleDatabaseHasPresetsNtf( - test_address1, bluetooth::has::kFeatureBitHearingAidTypeBinaural); + SetSampleDatabaseHasPresetsNtf(test_address1, bluetooth::has::kFeatureBitHearingAidTypeBinaural); const RawAddress test_address2 = GetTestAddress(2); - SetSampleDatabaseHasPresetsNtf( - test_address2, bluetooth::has::kFeatureBitHearingAidTypeBinaural); + SetSampleDatabaseHasPresetsNtf(test_address2, bluetooth::has::kFeatureBitHearingAidTypeBinaural); TestConnect(test_address1); TestConnect(test_address2); @@ -2664,38 +2381,30 @@ TEST_F(HasClientTest, test_select_group_preset_next_no_preset_sync_supported) { /* Mock the csis group with two devices */ uint8_t not_synced_group = 13; ON_CALL(mock_csis_client_module_, GetDeviceList(not_synced_group)) - .WillByDefault( - Return(std::vector({{test_address1, test_address2}}))); - ON_CALL( - mock_csis_client_module_, - GetGroupId(test_address1, ::bluetooth::le_audio::uuid::kCapServiceUuid)) - .WillByDefault(Return(not_synced_group)); - ON_CALL( - mock_csis_client_module_, - GetGroupId(test_address2, ::bluetooth::le_audio::uuid::kCapServiceUuid)) - .WillByDefault(Return(not_synced_group)); + .WillByDefault(Return(std::vector({{test_address1, test_address2}}))); + ON_CALL(mock_csis_client_module_, + GetGroupId(test_address1, ::bluetooth::le_audio::uuid::kCapServiceUuid)) + .WillByDefault(Return(not_synced_group)); + ON_CALL(mock_csis_client_module_, + GetGroupId(test_address2, ::bluetooth::le_audio::uuid::kCapServiceUuid)) + .WillByDefault(Return(not_synced_group)); uint8_t group_active_preset_index = 0; - EXPECT_CALL(*callbacks, OnActivePresetSelected( - std::variant(test_address1), 55)) - .Times(0); - EXPECT_CALL(*callbacks, OnActivePresetSelected( - std::variant(test_address2), 55)) - .Times(0); + EXPECT_CALL(*callbacks, OnActivePresetSelected(std::variant(test_address1), 55)) + .Times(0); + EXPECT_CALL(*callbacks, OnActivePresetSelected(std::variant(test_address2), 55)) + .Times(0); EXPECT_CALL(*callbacks, - OnActivePresetSelected( - std::variant(not_synced_group), _)) - .WillOnce(SaveArg<1>(&group_active_preset_index)); + OnActivePresetSelected(std::variant(not_synced_group), _)) + .WillOnce(SaveArg<1>(&group_active_preset_index)); /* No locally synced opcodes support so expect both devices getting writes */ EXPECT_CALL(gatt_queue, WriteCharacteristic(GetTestConnId(test_address1), - HasDbBuilder::kPresetsCtpValHdl, - _, GATT_WRITE, _, _)) - .Times(1); + HasDbBuilder::kPresetsCtpValHdl, _, GATT_WRITE, _, _)) + .Times(1); EXPECT_CALL(gatt_queue, WriteCharacteristic(GetTestConnId(test_address2), - HasDbBuilder::kPresetsCtpValHdl, - _, GATT_WRITE, _, _)) - .Times(1); + HasDbBuilder::kPresetsCtpValHdl, _, GATT_WRITE, _, _)) + .Times(1); HasClient::Get()->NextActivePreset(not_synced_group); ASSERT_EQ(group_active_preset_index, 55); @@ -2705,68 +2414,55 @@ TEST_F(HasClientTest, test_select_group_preset_next_preset_sync_supported) { /* Only one of these devices support preset syncing */ const RawAddress test_address1 = GetTestAddress(1); uint16_t test_conn_id1 = GetTestConnId(test_address1); - SetSampleDatabaseHasPresetsNtf( - test_address1, bluetooth::has::kFeatureBitHearingAidTypeBinaural); + SetSampleDatabaseHasPresetsNtf(test_address1, bluetooth::has::kFeatureBitHearingAidTypeBinaural); const RawAddress test_address2 = GetTestAddress(2); uint16_t test_conn_id2 = GetTestConnId(test_address2); - SetSampleDatabaseHasPresetsNtf( - test_address2, - bluetooth::has::kFeatureBitHearingAidTypeBinaural | - bluetooth::has::kFeatureBitPresetSynchronizationSupported); + SetSampleDatabaseHasPresetsNtf(test_address2, + bluetooth::has::kFeatureBitHearingAidTypeBinaural | + bluetooth::has::kFeatureBitPresetSynchronizationSupported); uint8_t active_preset_index1 = 0; uint8_t active_preset_index2 = 0; - EXPECT_CALL(*callbacks, OnActivePresetSelected( - std::variant(test_address1), _)) - .WillOnce(SaveArg<1>(&active_preset_index1)); + EXPECT_CALL(*callbacks, OnActivePresetSelected(std::variant(test_address1), _)) + .WillOnce(SaveArg<1>(&active_preset_index1)); TestConnect(test_address1); - EXPECT_CALL(*callbacks, OnActivePresetSelected( - std::variant(test_address2), _)) - .WillOnce(SaveArg<1>(&active_preset_index2)); + EXPECT_CALL(*callbacks, OnActivePresetSelected(std::variant(test_address2), _)) + .WillOnce(SaveArg<1>(&active_preset_index2)); TestConnect(test_address2); /* Mock the csis group with two devices */ uint8_t synced_group = 13; ON_CALL(mock_csis_client_module_, GetDeviceList(synced_group)) - .WillByDefault( - Return(std::vector({{test_address1, test_address2}}))); - ON_CALL( - mock_csis_client_module_, - GetGroupId(test_address1, ::bluetooth::le_audio::uuid::kCapServiceUuid)) - .WillByDefault(Return(synced_group)); - ON_CALL( - mock_csis_client_module_, - GetGroupId(test_address2, ::bluetooth::le_audio::uuid::kCapServiceUuid)) - .WillByDefault(Return(synced_group)); - - EXPECT_CALL(*callbacks, OnActivePresetSelectError( - _, ErrorCode::GROUP_OPERATION_NOT_SUPPORTED)) - .Times(0); + .WillByDefault(Return(std::vector({{test_address1, test_address2}}))); + ON_CALL(mock_csis_client_module_, + GetGroupId(test_address1, ::bluetooth::le_audio::uuid::kCapServiceUuid)) + .WillByDefault(Return(synced_group)); + ON_CALL(mock_csis_client_module_, + GetGroupId(test_address2, ::bluetooth::le_audio::uuid::kCapServiceUuid)) + .WillByDefault(Return(synced_group)); + + EXPECT_CALL(*callbacks, OnActivePresetSelectError(_, ErrorCode::GROUP_OPERATION_NOT_SUPPORTED)) + .Times(0); /* Expect callback from the group but not from the devices */ uint8_t group_active_preset_index = 0; - EXPECT_CALL(*callbacks, OnActivePresetSelected( - std::variant(test_address1), _)) - .Times(0); - EXPECT_CALL(*callbacks, OnActivePresetSelected( - std::variant(test_address2), _)) - .Times(0); - EXPECT_CALL(*callbacks, OnActivePresetSelected( - std::variant(synced_group), _)) - .WillOnce(SaveArg<1>(&group_active_preset_index)); + EXPECT_CALL(*callbacks, OnActivePresetSelected(std::variant(test_address1), _)) + .Times(0); + EXPECT_CALL(*callbacks, OnActivePresetSelected(std::variant(test_address2), _)) + .Times(0); + EXPECT_CALL(*callbacks, OnActivePresetSelected(std::variant(synced_group), _)) + .WillOnce(SaveArg<1>(&group_active_preset_index)); /* Expect Ctp write on on this device which forwards operation to the other */ - EXPECT_CALL(gatt_queue, WriteCharacteristic(test_conn_id1, - HasDbBuilder::kPresetsCtpValHdl, - _, GATT_WRITE, _, _)) - .Times(0); - EXPECT_CALL(gatt_queue, WriteCharacteristic(test_conn_id2, - HasDbBuilder::kPresetsCtpValHdl, - _, GATT_WRITE, _, _)) - .Times(1); + EXPECT_CALL(gatt_queue, WriteCharacteristic(test_conn_id1, HasDbBuilder::kPresetsCtpValHdl, _, + GATT_WRITE, _, _)) + .Times(0); + EXPECT_CALL(gatt_queue, WriteCharacteristic(test_conn_id2, HasDbBuilder::kPresetsCtpValHdl, _, + GATT_WRITE, _, _)) + .Times(1); HasClient::Get()->NextActivePreset(synced_group); ASSERT_EQ(group_active_preset_index, 55); @@ -2776,27 +2472,23 @@ TEST_F(HasClientTest, test_select_preset_prev) { const RawAddress test_address = GetTestAddress(1); std::set presets = {{ - HasPreset(1, HasPreset::kPropertyAvailable, "Universal"), - HasPreset(2, HasPreset::kPropertyAvailable | HasPreset::kPropertyWritable, - "Preset2"), + HasPreset(1, HasPreset::kPropertyAvailable, "Universal"), + HasPreset(2, HasPreset::kPropertyAvailable | HasPreset::kPropertyWritable, "Preset2"), }}; - SetSampleDatabaseHasPresetsNtf( - test_address, - bluetooth::has::kFeatureBitHearingAidTypeBanded | - bluetooth::has::kFeatureBitWritablePresets | - bluetooth::has::kFeatureBitDynamicPresets, - presets); + SetSampleDatabaseHasPresetsNtf(test_address, + bluetooth::has::kFeatureBitHearingAidTypeBanded | + bluetooth::has::kFeatureBitWritablePresets | + bluetooth::has::kFeatureBitDynamicPresets, + presets); uint8_t active_preset_index = 0; std::vector preset_details; - EXPECT_CALL(*callbacks, - OnPresetInfo(std::variant(test_address), - PresetInfoReason::ALL_PRESET_INFO, _)) - .Times(1) - .WillOnce(SaveArg<2>(&preset_details)); - ON_CALL(*callbacks, OnActivePresetSelected(_, _)) - .WillByDefault(SaveArg<1>(&active_preset_index)); + EXPECT_CALL(*callbacks, OnPresetInfo(std::variant(test_address), + PresetInfoReason::ALL_PRESET_INFO, _)) + .Times(1) + .WillOnce(SaveArg<2>(&preset_details)); + ON_CALL(*callbacks, OnActivePresetSelected(_, _)).WillByDefault(SaveArg<1>(&active_preset_index)); TestConnect(test_address); HasClient::Get()->SelectActivePreset(test_address, 2); @@ -2804,20 +2496,17 @@ TEST_F(HasClientTest, test_select_preset_prev) { ASSERT_EQ(2, active_preset_index); /* Verify active preset change */ - EXPECT_CALL(*callbacks, OnActivePresetSelected( - std::variant(test_address), 1)); + EXPECT_CALL(*callbacks, OnActivePresetSelected(std::variant(test_address), 1)); HasClient::Get()->PreviousActivePreset(test_address); } TEST_F(HasClientTest, test_select_group_preset_prev_no_preset_sync_supported) { /* None of these devices support preset syncing */ const RawAddress test_address1 = GetTestAddress(1); - SetSampleDatabaseHasPresetsNtf( - test_address1, bluetooth::has::kFeatureBitHearingAidTypeBinaural); + SetSampleDatabaseHasPresetsNtf(test_address1, bluetooth::has::kFeatureBitHearingAidTypeBinaural); const RawAddress test_address2 = GetTestAddress(2); - SetSampleDatabaseHasPresetsNtf( - test_address2, bluetooth::has::kFeatureBitHearingAidTypeBinaural); + SetSampleDatabaseHasPresetsNtf(test_address2, bluetooth::has::kFeatureBitHearingAidTypeBinaural); TestConnect(test_address1); TestConnect(test_address2); @@ -2825,38 +2514,30 @@ TEST_F(HasClientTest, test_select_group_preset_prev_no_preset_sync_supported) { /* Mock the csis group with two devices */ uint8_t not_synced_group = 13; ON_CALL(mock_csis_client_module_, GetDeviceList(not_synced_group)) - .WillByDefault( - Return(std::vector({{test_address1, test_address2}}))); - ON_CALL( - mock_csis_client_module_, - GetGroupId(test_address1, ::bluetooth::le_audio::uuid::kCapServiceUuid)) - .WillByDefault(Return(not_synced_group)); - ON_CALL( - mock_csis_client_module_, - GetGroupId(test_address2, ::bluetooth::le_audio::uuid::kCapServiceUuid)) - .WillByDefault(Return(not_synced_group)); + .WillByDefault(Return(std::vector({{test_address1, test_address2}}))); + ON_CALL(mock_csis_client_module_, + GetGroupId(test_address1, ::bluetooth::le_audio::uuid::kCapServiceUuid)) + .WillByDefault(Return(not_synced_group)); + ON_CALL(mock_csis_client_module_, + GetGroupId(test_address2, ::bluetooth::le_audio::uuid::kCapServiceUuid)) + .WillByDefault(Return(not_synced_group)); uint8_t group_active_preset_index = 0; - EXPECT_CALL(*callbacks, OnActivePresetSelected( - std::variant(test_address1), 55)) - .Times(0); - EXPECT_CALL(*callbacks, OnActivePresetSelected( - std::variant(test_address2), 55)) - .Times(0); + EXPECT_CALL(*callbacks, OnActivePresetSelected(std::variant(test_address1), 55)) + .Times(0); + EXPECT_CALL(*callbacks, OnActivePresetSelected(std::variant(test_address2), 55)) + .Times(0); EXPECT_CALL(*callbacks, - OnActivePresetSelected( - std::variant(not_synced_group), _)) - .WillOnce(SaveArg<1>(&group_active_preset_index)); + OnActivePresetSelected(std::variant(not_synced_group), _)) + .WillOnce(SaveArg<1>(&group_active_preset_index)); /* No locally synced opcodes support so expect both devices getting writes */ EXPECT_CALL(gatt_queue, WriteCharacteristic(GetTestConnId(test_address1), - HasDbBuilder::kPresetsCtpValHdl, - _, GATT_WRITE, _, _)) - .Times(1); + HasDbBuilder::kPresetsCtpValHdl, _, GATT_WRITE, _, _)) + .Times(1); EXPECT_CALL(gatt_queue, WriteCharacteristic(GetTestConnId(test_address2), - HasDbBuilder::kPresetsCtpValHdl, - _, GATT_WRITE, _, _)) - .Times(1); + HasDbBuilder::kPresetsCtpValHdl, _, GATT_WRITE, _, _)) + .Times(1); HasClient::Get()->PreviousActivePreset(not_synced_group); ASSERT_EQ(group_active_preset_index, 55); @@ -2866,68 +2547,55 @@ TEST_F(HasClientTest, test_select_group_preset_prev_preset_sync_supported) { /* Only one of these devices support preset syncing */ const RawAddress test_address1 = GetTestAddress(1); uint16_t test_conn_id1 = GetTestConnId(test_address1); - SetSampleDatabaseHasPresetsNtf( - test_address1, bluetooth::has::kFeatureBitHearingAidTypeBinaural); + SetSampleDatabaseHasPresetsNtf(test_address1, bluetooth::has::kFeatureBitHearingAidTypeBinaural); const RawAddress test_address2 = GetTestAddress(2); uint16_t test_conn_id2 = GetTestConnId(test_address2); - SetSampleDatabaseHasPresetsNtf( - test_address2, - bluetooth::has::kFeatureBitHearingAidTypeBinaural | - bluetooth::has::kFeatureBitPresetSynchronizationSupported); + SetSampleDatabaseHasPresetsNtf(test_address2, + bluetooth::has::kFeatureBitHearingAidTypeBinaural | + bluetooth::has::kFeatureBitPresetSynchronizationSupported); uint8_t active_preset_index1 = 0; uint8_t active_preset_index2 = 0; - EXPECT_CALL(*callbacks, OnActivePresetSelected( - std::variant(test_address1), _)) - .WillOnce(SaveArg<1>(&active_preset_index1)); + EXPECT_CALL(*callbacks, OnActivePresetSelected(std::variant(test_address1), _)) + .WillOnce(SaveArg<1>(&active_preset_index1)); TestConnect(test_address1); - EXPECT_CALL(*callbacks, OnActivePresetSelected( - std::variant(test_address2), _)) - .WillOnce(SaveArg<1>(&active_preset_index2)); + EXPECT_CALL(*callbacks, OnActivePresetSelected(std::variant(test_address2), _)) + .WillOnce(SaveArg<1>(&active_preset_index2)); TestConnect(test_address2); /* Mock the csis group with two devices */ uint8_t synced_group = 13; ON_CALL(mock_csis_client_module_, GetDeviceList(synced_group)) - .WillByDefault( - Return(std::vector({{test_address1, test_address2}}))); - ON_CALL( - mock_csis_client_module_, - GetGroupId(test_address1, ::bluetooth::le_audio::uuid::kCapServiceUuid)) - .WillByDefault(Return(synced_group)); - ON_CALL( - mock_csis_client_module_, - GetGroupId(test_address2, ::bluetooth::le_audio::uuid::kCapServiceUuid)) - .WillByDefault(Return(synced_group)); - - EXPECT_CALL(*callbacks, OnActivePresetSelectError( - _, ErrorCode::GROUP_OPERATION_NOT_SUPPORTED)) - .Times(0); + .WillByDefault(Return(std::vector({{test_address1, test_address2}}))); + ON_CALL(mock_csis_client_module_, + GetGroupId(test_address1, ::bluetooth::le_audio::uuid::kCapServiceUuid)) + .WillByDefault(Return(synced_group)); + ON_CALL(mock_csis_client_module_, + GetGroupId(test_address2, ::bluetooth::le_audio::uuid::kCapServiceUuid)) + .WillByDefault(Return(synced_group)); + + EXPECT_CALL(*callbacks, OnActivePresetSelectError(_, ErrorCode::GROUP_OPERATION_NOT_SUPPORTED)) + .Times(0); /* Expect callback from the group but not from the devices */ uint8_t group_active_preset_index = 0; - EXPECT_CALL(*callbacks, OnActivePresetSelected( - std::variant(test_address1), _)) - .Times(0); - EXPECT_CALL(*callbacks, OnActivePresetSelected( - std::variant(test_address2), _)) - .Times(0); - EXPECT_CALL(*callbacks, OnActivePresetSelected( - std::variant(synced_group), _)) - .WillOnce(SaveArg<1>(&group_active_preset_index)); + EXPECT_CALL(*callbacks, OnActivePresetSelected(std::variant(test_address1), _)) + .Times(0); + EXPECT_CALL(*callbacks, OnActivePresetSelected(std::variant(test_address2), _)) + .Times(0); + EXPECT_CALL(*callbacks, OnActivePresetSelected(std::variant(synced_group), _)) + .WillOnce(SaveArg<1>(&group_active_preset_index)); /* Expect Ctp write on on this device which forwards operation to the other */ - EXPECT_CALL(gatt_queue, WriteCharacteristic(test_conn_id1, - HasDbBuilder::kPresetsCtpValHdl, - _, GATT_WRITE, _, _)) - .Times(0); - EXPECT_CALL(gatt_queue, WriteCharacteristic(test_conn_id2, - HasDbBuilder::kPresetsCtpValHdl, - _, GATT_WRITE, _, _)) - .Times(1); + EXPECT_CALL(gatt_queue, WriteCharacteristic(test_conn_id1, HasDbBuilder::kPresetsCtpValHdl, _, + GATT_WRITE, _, _)) + .Times(0); + EXPECT_CALL(gatt_queue, WriteCharacteristic(test_conn_id2, HasDbBuilder::kPresetsCtpValHdl, _, + GATT_WRITE, _, _)) + .Times(1); HasClient::Get()->PreviousActivePreset(synced_group); ASSERT_EQ(group_active_preset_index, 55); @@ -2938,15 +2606,12 @@ TEST_F(HasClientTest, test_select_has_no_presets) { SetSampleDatabaseHasNoPresetsFlagsOnly(test_address); EXPECT_CALL(*callbacks, OnDeviceAvailable(test_address, _)).Times(1); - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::CONNECTED, test_address)) - .Times(1); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::CONNECTED, test_address)).Times(1); TestConnect(test_address); /* Test this not so useful service */ - EXPECT_CALL(*callbacks, - OnActivePresetSelectError(_, ErrorCode::OPERATION_NOT_SUPPORTED)) - .Times(3); + EXPECT_CALL(*callbacks, OnActivePresetSelectError(_, ErrorCode::OPERATION_NOT_SUPPORTED)) + .Times(3); HasClient::Get()->SelectActivePreset(test_address, 0x01); HasClient::Get()->NextActivePreset(test_address); @@ -2956,8 +2621,7 @@ TEST_F(HasClientTest, test_select_has_no_presets) { static int GetSocketBufferSize(int sockfd) { int socket_buffer_size; socklen_t optlen = sizeof(socket_buffer_size); - getsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, (void*)&socket_buffer_size, - &optlen); + getsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, (void*)&socket_buffer_size, &optlen); return socket_buffer_size; } @@ -3000,35 +2664,30 @@ bool SimpleJsonValidator(int fd, int* dumpsys_byte_cnt) { ss << buf; } log::error("{}", ss.str()); - return (left_bracket == right_bracket) && - (left_sq_bracket == right_sq_bracket); + return (left_bracket == right_bracket) && (left_sq_bracket == right_sq_bracket); } TEST_F(HasClientTest, test_dumpsys) { const RawAddress test_address = GetTestAddress(1); std::set presets = {{ - HasPreset(1, HasPreset::kPropertyAvailable, "Universal"), - HasPreset(2, HasPreset::kPropertyAvailable | HasPreset::kPropertyWritable, - "Preset2"), + HasPreset(1, HasPreset::kPropertyAvailable, "Universal"), + HasPreset(2, HasPreset::kPropertyAvailable | HasPreset::kPropertyWritable, "Preset2"), }}; - SetSampleDatabaseHasPresetsNtf( - test_address, - bluetooth::has::kFeatureBitHearingAidTypeBanded | - bluetooth::has::kFeatureBitWritablePresets | - bluetooth::has::kFeatureBitDynamicPresets, - presets); + SetSampleDatabaseHasPresetsNtf(test_address, + bluetooth::has::kFeatureBitHearingAidTypeBanded | + bluetooth::has::kFeatureBitWritablePresets | + bluetooth::has::kFeatureBitDynamicPresets, + presets); uint8_t active_preset_index = 0; std::vector preset_details; - EXPECT_CALL(*callbacks, - OnPresetInfo(std::variant(test_address), - PresetInfoReason::ALL_PRESET_INFO, _)) - .Times(1) - .WillOnce(SaveArg<2>(&preset_details)); - ON_CALL(*callbacks, OnActivePresetSelected(_, _)) - .WillByDefault(SaveArg<1>(&active_preset_index)); + EXPECT_CALL(*callbacks, OnPresetInfo(std::variant(test_address), + PresetInfoReason::ALL_PRESET_INFO, _)) + .Times(1) + .WillOnce(SaveArg<2>(&preset_details)); + ON_CALL(*callbacks, OnActivePresetSelected(_, _)).WillByDefault(SaveArg<1>(&active_preset_index)); TestConnect(test_address); int sv[2]; @@ -3046,38 +2705,36 @@ TEST_F(HasClientTest, test_connect_database_out_of_sync) { const RawAddress test_address = GetTestAddress(1); std::set has_presets = {{ - HasPreset(1, HasPreset::kPropertyAvailable, "Universal"), - HasPreset(2, HasPreset::kPropertyAvailable | HasPreset::kPropertyWritable, - "Preset2"), + HasPreset(1, HasPreset::kPropertyAvailable, "Universal"), + HasPreset(2, HasPreset::kPropertyAvailable | HasPreset::kPropertyWritable, "Preset2"), }}; - SetSampleDatabaseHasPresetsNtf( - test_address, - bluetooth::has::kFeatureBitHearingAidTypeBanded | - bluetooth::has::kFeatureBitWritablePresets | - bluetooth::has::kFeatureBitDynamicPresets, - has_presets); - - EXPECT_CALL(*callbacks, OnDeviceAvailable( - test_address, - bluetooth::has::kFeatureBitHearingAidTypeBanded | - bluetooth::has::kFeatureBitWritablePresets | - bluetooth::has::kFeatureBitDynamicPresets)); + SetSampleDatabaseHasPresetsNtf(test_address, + bluetooth::has::kFeatureBitHearingAidTypeBanded | + bluetooth::has::kFeatureBitWritablePresets | + bluetooth::has::kFeatureBitDynamicPresets, + has_presets); + EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::CONNECTED, test_address)); + OnDeviceAvailable(test_address, bluetooth::has::kFeatureBitHearingAidTypeBanded | + bluetooth::has::kFeatureBitWritablePresets | + bluetooth::has::kFeatureBitDynamicPresets)); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::CONNECTED, test_address)); TestConnect(test_address); ON_CALL(gatt_queue, WriteCharacteristic(_, _, _, _, _, _)) - .WillByDefault( - Invoke([this](uint16_t conn_id, uint16_t handle, - std::vector value, tGATT_WRITE_TYPE write_type, - GATT_WRITE_OP_CB cb, void* cb_data) { - auto* svc = gatt::FindService(services_map[conn_id], handle); - if (svc == nullptr) return; - - tGATT_STATUS status = GATT_DATABASE_OUT_OF_SYNC; - if (cb) - cb(conn_id, status, handle, value.size(), value.data(), cb_data); - })); + .WillByDefault( + Invoke([this](uint16_t conn_id, uint16_t handle, std::vector value, + tGATT_WRITE_TYPE write_type, GATT_WRITE_OP_CB cb, void* cb_data) { + auto* svc = gatt::FindService(services_map[conn_id], handle); + if (svc == nullptr) { + return; + } + + tGATT_STATUS status = GATT_DATABASE_OUT_OF_SYNC; + if (cb) { + cb(conn_id, status, handle, value.size(), value.data(), cb_data); + } + })); ON_CALL(gatt_interface, ServiceSearchRequest(_, _)).WillByDefault(Return()); EXPECT_CALL(gatt_interface, ServiceSearchRequest(_, _)); @@ -3085,24 +2742,23 @@ TEST_F(HasClientTest, test_connect_database_out_of_sync) { } class HasTypesTest : public ::testing::Test { - protected: +protected: void SetUp(void) override { reset_mock_function_count_map(); } void TearDown(void) override {} }; // namespace TEST_F(HasTypesTest, test_has_preset_serialize) { - HasPreset preset(0x01, - HasPreset::kPropertyAvailable | HasPreset::kPropertyWritable, + HasPreset preset(0x01, HasPreset::kPropertyAvailable | HasPreset::kPropertyWritable, "My Writable Preset01"); auto sp_sz = preset.SerializedSize(); std::vector serialized(sp_sz); - ASSERT_EQ(1 + // preset index - 1 + // properties - 1 + // name length - preset.GetName().length(), + ASSERT_EQ(1 + // preset index + 1 + // properties + 1 + // name length + preset.GetName().length(), sp_sz); /* Serialize should move the received buffer pointer by the size of data @@ -3122,33 +2778,28 @@ TEST_F(HasTypesTest, test_has_preset_serialize) { } TEST_F(HasTypesTest, test_has_preset_serialize_output_buffer_to_small) { - HasPreset preset(0x01, - HasPreset::kPropertyAvailable | HasPreset::kPropertyWritable, + HasPreset preset(0x01, HasPreset::kPropertyAvailable | HasPreset::kPropertyWritable, "My Writable Preset01"); /* On failure, the offset should still point on .data() */ std::vector serialized(preset.SerializedSize() - 1); - ASSERT_EQ(preset.Serialize(serialized.data(), serialized.size()), - serialized.data()); + ASSERT_EQ(preset.Serialize(serialized.data(), serialized.size()), serialized.data()); ASSERT_EQ(preset.Serialize(serialized.data(), 0), serialized.data()); ASSERT_EQ(preset.Serialize(serialized.data(), 1), serialized.data()); ASSERT_EQ(preset.Serialize(serialized.data(), 10), serialized.data()); } TEST_F(HasTypesTest, test_has_preset_serialize_name_to_long) { - HasPreset preset(0x01, - HasPreset::kPropertyAvailable | HasPreset::kPropertyWritable, + HasPreset preset(0x01, HasPreset::kPropertyAvailable | HasPreset::kPropertyWritable, "This name is more than 40 characters long"); /* On failure, the offset should still point on .data() */ std::vector serialized(preset.SerializedSize()); - EXPECT_EQ(preset.Serialize(serialized.data(), serialized.size()), - serialized.data()); + EXPECT_EQ(preset.Serialize(serialized.data(), serialized.size()), serialized.data()); } TEST_F(HasTypesTest, test_has_preset_deserialize_input_buffer_to_small) { - HasPreset preset(0x01, - HasPreset::kPropertyAvailable | HasPreset::kPropertyWritable, + HasPreset preset(0x01, HasPreset::kPropertyAvailable | HasPreset::kPropertyWritable, "My Writable Preset01"); std::vector serialized(preset.SerializedSize()); @@ -3160,20 +2811,15 @@ TEST_F(HasTypesTest, test_has_preset_deserialize_input_buffer_to_small) { /* Deserialize */ HasPreset clone; - ASSERT_EQ(HasPreset::Deserialize(serialized.data(), 0, clone), - serialized.data()); - ASSERT_EQ(HasPreset::Deserialize(serialized.data(), 1, clone), - serialized.data()); - ASSERT_EQ(HasPreset::Deserialize(serialized.data(), 11, clone), + ASSERT_EQ(HasPreset::Deserialize(serialized.data(), 0, clone), serialized.data()); + ASSERT_EQ(HasPreset::Deserialize(serialized.data(), 1, clone), serialized.data()); + ASSERT_EQ(HasPreset::Deserialize(serialized.data(), 11, clone), serialized.data()); + ASSERT_EQ(HasPreset::Deserialize(serialized.data(), serialized.size() - 1, clone), serialized.data()); - ASSERT_EQ( - HasPreset::Deserialize(serialized.data(), serialized.size() - 1, clone), - serialized.data()); } TEST_F(HasTypesTest, test_has_presets_serialize) { - HasPreset preset(0x01, - HasPreset::kPropertyAvailable | HasPreset::kPropertyWritable, + HasPreset preset(0x01, HasPreset::kPropertyAvailable | HasPreset::kPropertyWritable, "My Writable Preset01"); HasPreset preset2(0x02, 0, "Nonwritable Unavailable Preset"); @@ -3192,8 +2838,7 @@ TEST_F(HasTypesTest, test_has_presets_serialize) { /* Deserialize */ HasDevice clone(GetTestAddress(1)); - ASSERT_TRUE(HasDevice::DeserializePresets(serialized.data(), - serialized.size(), clone)); + ASSERT_TRUE(HasDevice::DeserializePresets(serialized.data(), serialized.size(), clone)); /* Verify */ ASSERT_EQ(clone.has_presets.size(), has_device.has_presets.size()); @@ -3204,15 +2849,13 @@ TEST_F(HasTypesTest, test_has_presets_serialize) { has_device.has_presets.find(0x01)->GetIndex()); ASSERT_EQ(clone.has_presets.find(0x01)->GetProperties(), has_device.has_presets.find(0x01)->GetProperties()); - ASSERT_EQ(clone.has_presets.find(0x01)->GetName(), - has_device.has_presets.find(0x01)->GetName()); + ASSERT_EQ(clone.has_presets.find(0x01)->GetName(), has_device.has_presets.find(0x01)->GetName()); ASSERT_EQ(clone.has_presets.find(0x02)->GetIndex(), has_device.has_presets.find(0x02)->GetIndex()); ASSERT_EQ(clone.has_presets.find(0x02)->GetProperties(), has_device.has_presets.find(0x02)->GetProperties()); - ASSERT_EQ(clone.has_presets.find(0x02)->GetName(), - has_device.has_presets.find(0x02)->GetName()); + ASSERT_EQ(clone.has_presets.find(0x02)->GetName(), has_device.has_presets.find(0x02)->GetName()); } TEST_F(HasTypesTest, test_group_op_coordinator_init) { @@ -3224,9 +2867,8 @@ TEST_F(HasTypesTest, test_group_op_coordinator_init) { auto address2 = GetTestAddress(2); HasCtpGroupOpCoordinator wrapper( - {address1, address2}, - HasCtpOp(0x01, ::bluetooth::le_audio::has::PresetCtpOpcode::READ_PRESETS, - 6)); + {address1, address2}, + HasCtpOp(0x01, ::bluetooth::le_audio::has::PresetCtpOpcode::READ_PRESETS, 6)); ASSERT_EQ(2u, wrapper.ref_cnt); HasCtpGroupOpCoordinator::Cleanup(); @@ -3245,17 +2887,13 @@ TEST_F(HasTypesTest, test_group_op_coordinator_copy) { auto address2 = GetTestAddress(2); HasCtpGroupOpCoordinator wrapper( - {address1, address2}, - HasCtpOp(0x01, ::bluetooth::le_audio::has::PresetCtpOpcode::READ_PRESETS, - 6)); + {address1, address2}, + HasCtpOp(0x01, ::bluetooth::le_audio::has::PresetCtpOpcode::READ_PRESETS, 6)); HasCtpGroupOpCoordinator wrapper2( - {address1}, - HasCtpOp(0x01, ::bluetooth::le_audio::has::PresetCtpOpcode::READ_PRESETS, - 6)); + {address1}, HasCtpOp(0x01, ::bluetooth::le_audio::has::PresetCtpOpcode::READ_PRESETS, 6)); ASSERT_EQ(3u, wrapper.ref_cnt); HasCtpGroupOpCoordinator wrapper3 = wrapper2; - auto* wrapper4 = - new HasCtpGroupOpCoordinator(HasCtpGroupOpCoordinator(wrapper2)); + auto* wrapper4 = new HasCtpGroupOpCoordinator(HasCtpGroupOpCoordinator(wrapper2)); ASSERT_EQ(5u, wrapper.ref_cnt); delete wrapper4; @@ -3279,13 +2917,10 @@ TEST_F(HasTypesTest, test_group_op_coordinator_completion) { auto address3 = GetTestAddress(3); HasCtpGroupOpCoordinator wrapper( - {address1, address3}, - HasCtpOp(0x01, ::bluetooth::le_audio::has::PresetCtpOpcode::READ_PRESETS, - 6)); + {address1, address3}, + HasCtpOp(0x01, ::bluetooth::le_audio::has::PresetCtpOpcode::READ_PRESETS, 6)); HasCtpGroupOpCoordinator wrapper2( - {address2}, - HasCtpOp(0x01, ::bluetooth::le_audio::has::PresetCtpOpcode::READ_PRESETS, - 6)); + {address2}, HasCtpOp(0x01, ::bluetooth::le_audio::has::PresetCtpOpcode::READ_PRESETS, 6)); ASSERT_EQ(3u, wrapper.ref_cnt); ASSERT_FALSE(wrapper.IsFullyCompleted()); diff --git a/system/bta/has/has_ctp.cc b/system/bta/has/has_ctp.cc index 7d7e0242804..080298fc9e5 100644 --- a/system/bta/has/has_ctp.cc +++ b/system/bta/has/has_ctp.cc @@ -27,8 +27,7 @@ using namespace bluetooth; namespace bluetooth::le_audio { namespace has { -static bool ParsePresetGenericUpdate(uint16_t& len, const uint8_t* value, - HasCtpNtf& ntf) { +static bool ParsePresetGenericUpdate(uint16_t& len, const uint8_t* value, HasCtpNtf& ntf) { if (len < sizeof(ntf.prev_index) + HasPreset::kCharValueMinSize) { log::error("Invalid preset value length={} for generic update.", len); return false; @@ -41,8 +40,7 @@ static bool ParsePresetGenericUpdate(uint16_t& len, const uint8_t* value, return true; } -static bool ParsePresetIndex(uint16_t& len, const uint8_t* value, - HasCtpNtf& ntf) { +static bool ParsePresetIndex(uint16_t& len, const uint8_t* value, HasCtpNtf& ntf) { if (len < sizeof(ntf.index)) { log::error("Invalid preset value length={} for generic update.", len); return false; @@ -53,8 +51,7 @@ static bool ParsePresetIndex(uint16_t& len, const uint8_t* value, return true; } -static bool ParsePresetReadResponse(uint16_t& len, const uint8_t* value, - HasCtpNtf& ntf) { +static bool ParsePresetReadResponse(uint16_t& len, const uint8_t* value, HasCtpNtf& ntf) { if (len < sizeof(ntf.is_last) + HasPreset::kCharValueMinSize) { log::error("Invalid preset value length={}", len); return false; @@ -67,8 +64,7 @@ static bool ParsePresetReadResponse(uint16_t& len, const uint8_t* value, return true; } -static bool ParsePresetChanged(uint16_t len, const uint8_t* value, - HasCtpNtf& ntf) { +static bool ParsePresetChanged(uint16_t len, const uint8_t* value, HasCtpNtf& ntf) { if (len < sizeof(ntf.is_last) + sizeof(ntf.change_id)) { log::error("Invalid preset value length={}", len); return false; @@ -77,8 +73,8 @@ static bool ParsePresetChanged(uint16_t len, const uint8_t* value, uint8_t change_id; STREAM_TO_UINT8(change_id, value); len -= 1; - if (change_id > static_cast>( - PresetCtpChangeId::CHANGE_ID_MAX_)) { + if (change_id > + static_cast>(PresetCtpChangeId::CHANGE_ID_MAX_)) { log::error("Invalid preset chenge_id={}", change_id); return false; } @@ -102,8 +98,7 @@ static bool ParsePresetChanged(uint16_t len, const uint8_t* value, return true; } -std::optional HasCtpNtf::FromCharacteristicValue( - uint16_t len, const uint8_t* value) { +std::optional HasCtpNtf::FromCharacteristicValue(uint16_t len, const uint8_t* value) { if (len < 3) { log::error("Invalid Cp notification."); return std::nullopt; @@ -114,9 +109,9 @@ std::optional HasCtpNtf::FromCharacteristicValue( --len; if ((op != static_cast>( - PresetCtpOpcode::READ_PRESET_RESPONSE)) && - (op != static_cast>( - PresetCtpOpcode::PRESET_CHANGED))) { + PresetCtpOpcode::READ_PRESET_RESPONSE)) && + (op != + static_cast>(PresetCtpOpcode::PRESET_CHANGED))) { log::error("Received invalid opcode in control point notification: {}", op); return std::nullopt; } @@ -124,11 +119,14 @@ std::optional HasCtpNtf::FromCharacteristicValue( HasCtpNtf ntf; ntf.opcode = PresetCtpOpcode(op); if (ntf.opcode == bluetooth::le_audio::has::PresetCtpOpcode::PRESET_CHANGED) { - if (!ParsePresetChanged(len, value, ntf)) return std::nullopt; + if (!ParsePresetChanged(len, value, ntf)) { + return std::nullopt; + } - } else if (ntf.opcode == - bluetooth::le_audio::has::PresetCtpOpcode::READ_PRESET_RESPONSE) { - if (!ParsePresetReadResponse(len, value, ntf)) return std::nullopt; + } else if (ntf.opcode == bluetooth::le_audio::has::PresetCtpOpcode::READ_PRESET_RESPONSE) { + if (!ParsePresetReadResponse(len, value, ntf)) { + return std::nullopt; + } } return ntf; @@ -144,8 +142,7 @@ std::vector HasCtpOp::ToCharacteristicValue() const { case PresetCtpOpcode::READ_PRESETS: value.resize(3); pp = value.data(); - UINT8_TO_STREAM( - pp, static_cast>(opcode)); + UINT8_TO_STREAM(pp, static_cast>(opcode)); UINT8_TO_STREAM(pp, index); UINT8_TO_STREAM(pp, num_of_indices); break; @@ -153,8 +150,7 @@ std::vector HasCtpOp::ToCharacteristicValue() const { case PresetCtpOpcode::SET_ACTIVE_PRESET_SYNC: value.resize(2); pp = value.data(); - UINT8_TO_STREAM( - pp, static_cast>(opcode)); + UINT8_TO_STREAM(pp, static_cast>(opcode)); UINT8_TO_STREAM(pp, index); break; @@ -164,8 +160,7 @@ std::vector HasCtpOp::ToCharacteristicValue() const { case PresetCtpOpcode::SET_PREV_PRESET_SYNC: value.resize(1); pp = value.data(); - UINT8_TO_STREAM( - pp, static_cast>(opcode)); + UINT8_TO_STREAM(pp, static_cast>(opcode)); break; case PresetCtpOpcode::WRITE_PRESET_NAME: { @@ -173,8 +168,7 @@ std::vector HasCtpOp::ToCharacteristicValue() const { value.resize(2 + name_str.length()); pp = value.data(); - UINT8_TO_STREAM( - pp, static_cast>(opcode)); + UINT8_TO_STREAM(pp, static_cast>(opcode)); UINT8_TO_STREAM(pp, index); memcpy(pp, name_str.c_str(), name_str.length()); } break; @@ -232,14 +226,13 @@ std::ostream& operator<<(std::ostream& out, const HasCtpOp& op) { if (std::holds_alternative(op.addr_or_group)) { out << "\"group_id\": " << std::get(op.addr_or_group); } else if (std::holds_alternative(op.addr_or_group)) { - out << "\"address\": \"" - << ADDRESS_TO_LOGGABLE_STR(std::get(op.addr_or_group)) << "\""; + out << "\"address\": \"" << ADDRESS_TO_LOGGABLE_STR(std::get(op.addr_or_group)) + << "\""; } else { out << "\"bad value\""; } out << ", \"id\": " << op.op_id << ", \"opcode\": \"" << op.opcode << "\"" - << ", \"index\": " << +op.index << ", \"name\": \"" - << op.name.value_or("") << "\"" + << ", \"index\": " << +op.index << ", \"name\": \"" << op.name.value_or("") << "\"" << "}"; return out; } diff --git a/system/bta/has/has_ctp.h b/system/bta/has/has_ctp.h index 9dff63c674c..5e5a55b6697 100644 --- a/system/bta/has/has_ctp.h +++ b/system/bta/has/has_ctp.h @@ -63,22 +63,21 @@ enum class PresetCtpOpcode : uint8_t { std::ostream& operator<<(std::ostream& out, const PresetCtpOpcode value); static constexpr uint16_t PresetCtpOpcode2Bitmask(PresetCtpOpcode op) { - return ((uint16_t)0b1 << static_cast>( - op)); + return (uint16_t)0b1 << static_cast>(op); } /* Mandatory opcodes if control point characteristic exists */ static constexpr uint16_t kControlPointMandatoryOpcodesBitmask = - PresetCtpOpcode2Bitmask(PresetCtpOpcode::READ_PRESETS) | - PresetCtpOpcode2Bitmask(PresetCtpOpcode::SET_ACTIVE_PRESET) | - PresetCtpOpcode2Bitmask(PresetCtpOpcode::SET_NEXT_PRESET) | - PresetCtpOpcode2Bitmask(PresetCtpOpcode::SET_PREV_PRESET); + PresetCtpOpcode2Bitmask(PresetCtpOpcode::READ_PRESETS) | + PresetCtpOpcode2Bitmask(PresetCtpOpcode::SET_ACTIVE_PRESET) | + PresetCtpOpcode2Bitmask(PresetCtpOpcode::SET_NEXT_PRESET) | + PresetCtpOpcode2Bitmask(PresetCtpOpcode::SET_PREV_PRESET); /* Optional coordinated operation opcodes */ static constexpr uint16_t kControlPointSynchronizedOpcodesBitmask = - PresetCtpOpcode2Bitmask(PresetCtpOpcode::SET_ACTIVE_PRESET_SYNC) | - PresetCtpOpcode2Bitmask(PresetCtpOpcode::SET_NEXT_PRESET_SYNC) | - PresetCtpOpcode2Bitmask(PresetCtpOpcode::SET_PREV_PRESET_SYNC); + PresetCtpOpcode2Bitmask(PresetCtpOpcode::SET_ACTIVE_PRESET_SYNC) | + PresetCtpOpcode2Bitmask(PresetCtpOpcode::SET_NEXT_PRESET_SYNC) | + PresetCtpOpcode2Bitmask(PresetCtpOpcode::SET_PREV_PRESET_SYNC); /* Represents HAS Control Point value notification */ struct HasCtpNtf { @@ -91,8 +90,7 @@ struct HasCtpNtf { }; std::optional preset; - static std::optional FromCharacteristicValue(uint16_t len, - const uint8_t* value); + static std::optional FromCharacteristicValue(uint16_t len, const uint8_t* value); }; std::ostream& operator<<(std::ostream& out, const HasCtpNtf& value); @@ -106,8 +104,7 @@ struct HasCtpOp { uint16_t op_id; HasCtpOp(std::variant addr_or_group_id, PresetCtpOpcode op, - uint8_t index = bluetooth::has::kHasPresetIndexInvalid, - uint8_t num_of_indices = 1, + uint8_t index = bluetooth::has::kHasPresetIndexInvalid, uint8_t num_of_indices = 1, std::optional name = std::nullopt) : addr_or_group(addr_or_group_id), opcode(op), @@ -116,26 +113,23 @@ struct HasCtpOp { name(name) { /* Skip 0 on roll-over */ last_op_id_ += 1; - if (last_op_id_ == 0) last_op_id_ = 1; + if (last_op_id_ == 0) { + last_op_id_ = 1; + } op_id = last_op_id_; } std::vector ToCharacteristicValue(void) const; - bool IsGroupRequest() const { - return std::holds_alternative(addr_or_group); - } + bool IsGroupRequest() const { return std::holds_alternative(addr_or_group); } int GetGroupId() const { - return std::holds_alternative(addr_or_group) - ? std::get(addr_or_group) - : -1; + return std::holds_alternative(addr_or_group) ? std::get(addr_or_group) : -1; } RawAddress GetDeviceAddr() const { - return std::holds_alternative(addr_or_group) - ? std::get(addr_or_group) - : RawAddress::kEmpty; + return std::holds_alternative(addr_or_group) ? std::get(addr_or_group) + : RawAddress::kEmpty; } bool IsSyncedOperation() const { @@ -144,7 +138,7 @@ struct HasCtpOp { (opcode == PresetCtpOpcode::SET_PREV_PRESET_SYNC); } - private: +private: /* It's fine for this to roll-over eventually */ static uint16_t last_op_id_; }; @@ -206,15 +200,12 @@ struct HasCtpGroupOpCoordinator { ref_cnt += other.devices.size(); } - HasCtpGroupOpCoordinator(const std::vector& targets, - HasCtpOp operation) + HasCtpGroupOpCoordinator(const std::vector& targets, HasCtpOp operation) : operation(operation) { log::assert_that(targets.size() != 0, "Empty device list error."); if (targets.size() != 1) { - log::assert_that(operation.IsGroupRequest(), - "Must be a group operation!"); - log::assert_that(operation.GetGroupId() != -1, - "Must set valid group_id!"); + log::assert_that(operation.IsGroupRequest(), "Must be a group operation!"); + log::assert_that(operation.GetGroupId() != -1, "Must set valid group_id!"); } devices = std::list(targets.cbegin(), targets.cend()); @@ -224,12 +215,12 @@ struct HasCtpGroupOpCoordinator { operation_timeout_timer = alarm_new("GroupOpTimer"); } - if (alarm_is_scheduled(operation_timeout_timer)) + if (alarm_is_scheduled(operation_timeout_timer)) { alarm_cancel(operation_timeout_timer); + } log::assert_that(cb != nullptr, "Timeout timer callback not set!"); - alarm_set_on_mloop(operation_timeout_timer, kOperationTimeoutMs, cb, - nullptr); + alarm_set_on_mloop(operation_timeout_timer, kOperationTimeoutMs, cb, nullptr); } ~HasCtpGroupOpCoordinator() { diff --git a/system/bta/has/has_journal.cc b/system/bta/has/has_journal.cc index bca7ea8ec4f..8940348fcbd 100644 --- a/system/bta/has/has_journal.cc +++ b/system/bta/has/has_journal.cc @@ -29,8 +29,7 @@ std::ostream& operator<<(std::ostream& os, const HasJournalRecord& r) { char temptime[20]; struct tm* tstamp = localtime(&r.timestamp.tv_sec); strftime(temptime, sizeof(temptime), "%H:%M:%S", tstamp); - snprintf(eventtime, sizeof(eventtime), "%s.%03ld", temptime, - r.timestamp.tv_nsec / 1000000); + snprintf(eventtime, sizeof(eventtime), "%s.%03ld", temptime, r.timestamp.tv_nsec / 1000000); os << "\"time\": \"" << eventtime << "\", "; if (r.is_operation) { @@ -41,12 +40,11 @@ std::ostream& operator<<(std::ostream& os, const HasJournalRecord& r) { os << std::get(r.event) << ", "; } else if (r.is_active_preset_change) { - os << "\"Active preset changed\": {\"active_preset_idx\": " - << +std::get(r.event) << "}"; + os << "\"Active preset changed\": {\"active_preset_idx\": " << +std::get(r.event) + << "}"; } else { - os << "\"Features changed\": {\"features\": \"" - << loghex(std::get(r.event)) << "\"}"; + os << "\"Features changed\": {\"features\": \"" << loghex(std::get(r.event)) << "\"}"; } os << "}"; diff --git a/system/bta/has/has_journal.h b/system/bta/has/has_journal.h index e84213d0597..2ddee7edac6 100644 --- a/system/bta/has/has_journal.h +++ b/system/bta/has/has_journal.h @@ -33,8 +33,7 @@ static constexpr uint8_t kHasJournalNumRecords = 20; struct HasJournalRecord { /* Indicates which value the `event` contains (due to ambiguous uint8_t) */ - bool is_operation : 1, is_notification : 1, is_features_change : 1, - is_active_preset_change : 1; + bool is_operation : 1, is_notification : 1, is_features_change : 1, is_active_preset_change : 1; std::variant event; struct timespec timestamp; @@ -44,8 +43,7 @@ struct HasJournalRecord { /* Status of the operation to be set once it gets completed */ uint8_t op_status; - HasJournalRecord(const HasCtpOp& op, void* context) - : event(op), op_context_handle(context) { + HasJournalRecord(const HasCtpOp& op, void* context) : event(op), op_context_handle(context) { clock_gettime(CLOCK_REALTIME, ×tamp); is_operation = true; is_notification = false; @@ -78,7 +76,7 @@ std::ostream& operator<<(std::ostream& os, const HasJournalRecord& r); template class CacheList { - public: +public: valT& Append(valT data) { items_.push_front(std::move(data)); @@ -98,13 +96,15 @@ class CacheList { const_iterator end(void) const { return items_.end(); } void Erase(iterator it) { - if (it != items_.end()) items_.erase(it); + if (it != items_.end()) { + items_.erase(it); + } } void Clear(void) { items_.clear(); } bool isEmpty(void) { return items_.empty(); } - private: +private: typename std::list items_; }; diff --git a/system/bta/has/has_preset.cc b/system/bta/has/has_preset.cc index b00117dcdce..610437e0404 100644 --- a/system/bta/has/has_preset.cc +++ b/system/bta/has/has_preset.cc @@ -26,10 +26,8 @@ using namespace bluetooth; namespace bluetooth::le_audio { namespace has { -std::optional HasPreset::FromCharacteristicValue( - uint16_t& len, const uint8_t* value) { - if ((len < kCharValueMinSize) || - (len > kCharValueMinSize + kPresetNameLengthLimit)) { +std::optional HasPreset::FromCharacteristicValue(uint16_t& len, const uint8_t* value) { + if ((len < kCharValueMinSize) || (len > kCharValueMinSize + kPresetNameLengthLimit)) { log::error("Preset record to long: {}", len); return std::nullopt; } @@ -76,8 +74,7 @@ uint8_t* HasPreset::Serialize(uint8_t* p_out, size_t buffer_size) const { return p_out; } -const uint8_t* HasPreset::Deserialize(const uint8_t* p_in, size_t len, - HasPreset& preset) { +const uint8_t* HasPreset::Deserialize(const uint8_t* p_in, size_t len, HasPreset& preset) { const uint8_t nonamed_size = HasPreset(0, 0).SerializedSize(); auto* p_curr = p_in; @@ -94,15 +91,16 @@ const uint8_t* HasPreset::Deserialize(const uint8_t* p_in, size_t len, } auto name_len = serialized_data_len - 2; - if ((name_len > kPresetNameLengthLimit) || - ((size_t)nonamed_size + name_len > len)) { + if ((name_len > kPresetNameLengthLimit) || ((size_t)nonamed_size + name_len > len)) { log::error("Invalid preset name length. Cannot be deserialized!"); return p_in; } STREAM_TO_UINT8(preset.index_, p_curr); STREAM_TO_UINT8(preset.properties_, p_curr); - if (name_len) preset.name_ = std::string((const char*)p_curr, name_len); + if (name_len) { + preset.name_ = std::string((const char*)p_curr, name_len); + } return p_curr + name_len; } diff --git a/system/bta/has/has_preset.h b/system/bta/has/has_preset.h index 57991beaa59..48c61852413 100644 --- a/system/bta/has/has_preset.h +++ b/system/bta/has/has_preset.h @@ -31,12 +31,12 @@ namespace has { * GATT characteristics and descriptor informations. */ class HasPreset { - private: +private: mutable std::string name_; mutable uint8_t properties_; uint8_t index_; - public: +public: static constexpr size_t kCharValueMinSize = 1 /*index*/ + 1 /*properties*/; static constexpr uint8_t kPropertyWritable = 0x01; @@ -44,15 +44,11 @@ class HasPreset { static constexpr uint8_t kPresetNameLengthLimit = 40; - HasPreset(uint8_t index, uint8_t props = 0, - std::optional name = std::nullopt) + HasPreset(uint8_t index, uint8_t props = 0, std::optional name = std::nullopt) : properties_(props), index_(index) { name_ = name.value_or(""); } - HasPreset() - : name_(""), - properties_(0), - index_(bluetooth::has::kHasPresetIndexInvalid) {} + HasPreset() : name_(""), properties_(0), index_(bluetooth::has::kHasPresetIndexInvalid) {} auto& GetName() const { return name_; } decltype(index_) GetIndex() const { return index_; } @@ -61,8 +57,7 @@ class HasPreset { bool IsAvailable() const { return properties_ & kPropertyAvailable; } HasPreset& operator=(const HasPreset& other) { - log::assert_that(index_ == other.GetIndex(), - "Assigning immutable preset index!"); + log::assert_that(index_ == other.GetIndex(), "Assigning immutable preset index!"); if ((this != &other) && (*this != other)) { index_ = other.GetIndex(); @@ -72,43 +67,33 @@ class HasPreset { } bool operator==(const HasPreset& b) const { - return (index_ == b.index_) && (properties_ == b.properties_) && - (name_ == b.name_); + return (index_ == b.index_) && (properties_ == b.properties_) && (name_ == b.name_); } bool operator!=(const HasPreset& b) const { - return (index_ != b.index_) || (properties_ != b.properties_) || - (name_ != b.name_); + return (index_ != b.index_) || (properties_ != b.properties_) || (name_ != b.name_); } bool operator<(const HasPreset& b) const { return index_ < b.index_; } friend std::ostream& operator<<(std::ostream& os, const HasPreset& b); struct ComparatorDesc { using is_transparent = void; - bool operator()(HasPreset const& a, int index) const { - return a.index_ < index; - } - bool operator()(int index, HasPreset const& a) const { - return index < a.index_; - } - bool operator()(HasPreset const& a, HasPreset const& b) const { - return a.index_ < b.index_; - } + bool operator()(HasPreset const& a, int index) const { return a.index_ < index; } + bool operator()(int index, HasPreset const& a) const { return index < a.index_; } + bool operator()(HasPreset const& a, HasPreset const& b) const { return a.index_ < b.index_; } }; - static std::optional FromCharacteristicValue(uint16_t& len, - const uint8_t* value); + static std::optional FromCharacteristicValue(uint16_t& len, const uint8_t* value); void ToCharacteristicValue(std::vector& value) const; /* Calculates buffer space that the preset will use when serialized */ uint8_t SerializedSize() const { - return (sizeof(index_) + sizeof(properties_) + 1 /* name length */ - + name_.length()); + return sizeof(index_) + sizeof(properties_) + 1 /* name length */ + + name_.length(); } /* Serializes into binary blob for the persistent storage */ uint8_t* Serialize(uint8_t* p_out, size_t buffer_size) const; /* Deserializes binary blob read from the persistent storage */ - static const uint8_t* Deserialize(const uint8_t* p_in, size_t len, - HasPreset& preset); + static const uint8_t* Deserialize(const uint8_t* p_in, size_t len, HasPreset& preset); }; } // namespace has diff --git a/system/bta/has/has_types.cc b/system/bta/has/has_types.cc index 174c77fd135..a77d3610c9e 100644 --- a/system/bta/has/has_types.cc +++ b/system/bta/has/has_types.cc @@ -21,8 +21,7 @@ namespace bluetooth::le_audio { namespace has { std::ostream& operator<<(std::ostream& os, const HasDevice& b) { - os << "HAP device: {" - << "addr: " << b.addr << ", conn id: " << b.conn_id << "}"; + os << "HAP device: {" << "addr: " << b.addr << ", conn id: " << b.conn_id << "}"; return os; } diff --git a/system/bta/has/has_types.h b/system/bta/has/has_types.h index c5b100b66db..cb15f543e89 100644 --- a/system/bta/has/has_types.h +++ b/system/bta/has/has_types.h @@ -38,7 +38,7 @@ namespace has { /* Helper class to pass some minimal context through the GATT operation API. */ union HasGattOpContext { - public: +public: void* ptr = nullptr; struct { /* Ctp. Operation ID or 0 if not a control point operation context */ @@ -59,9 +59,7 @@ union HasGattOpContext { /* Differ from nullptr in at least 1 bit when everything else is 0 */ context_flags = flags | kIsNotNull; } - HasGattOpContext(uint8_t flags) : ctp_op_id(0) { - context_flags = flags | kIsNotNull; - } + HasGattOpContext(uint8_t flags) : ctp_op_id(0) { context_flags = flags | kIsNotNull; } HasGattOpContext(void* pp) { ptr = pp; /* Differ from nullptr in at least 1 bit when everything else is 0 */ @@ -74,21 +72,17 @@ union HasGattOpContext { static_assert(sizeof(HasGattOpContext) <= sizeof(void*)); /* Service UUIDs */ -static const bluetooth::Uuid kUuidHearingAccessService = - bluetooth::Uuid::From16Bit(0x1854); -static const bluetooth::Uuid kUuidHearingAidFeatures = - bluetooth::Uuid::From16Bit(0x2BDA); -static const bluetooth::Uuid kUuidHearingAidPresetControlPoint = - bluetooth::Uuid::From16Bit(0x2BDB); -static const bluetooth::Uuid kUuidActivePresetIndex = - bluetooth::Uuid::From16Bit(0x2BDC); +static const bluetooth::Uuid kUuidHearingAccessService = bluetooth::Uuid::From16Bit(0x1854); +static const bluetooth::Uuid kUuidHearingAidFeatures = bluetooth::Uuid::From16Bit(0x2BDA); +static const bluetooth::Uuid kUuidHearingAidPresetControlPoint = bluetooth::Uuid::From16Bit(0x2BDB); +static const bluetooth::Uuid kUuidActivePresetIndex = bluetooth::Uuid::From16Bit(0x2BDC); static const uint8_t kStartPresetIndex = 1; static const uint8_t kMaxNumOfPresets = 255; /* Base device class for the GATT-based service clients */ class GattServiceDevice { - public: +public: RawAddress addr; uint16_t conn_id = GATT_INVALID_CONN_ID; uint16_t service_handle = GAP_INVALID_HANDLE; @@ -105,25 +99,21 @@ class GattServiceDevice { bool IsConnected() const { return conn_id != GATT_INVALID_CONN_ID; } class MatchAddress { - private: + private: RawAddress addr; - public: + public: MatchAddress(RawAddress addr) : addr(addr) {} - bool operator()(const GattServiceDevice& other) const { - return (addr == other.addr); - } + bool operator()(const GattServiceDevice& other) const { return addr == other.addr; } }; class MatchConnId { - private: + private: uint16_t conn_id; - public: + public: MatchConnId(uint16_t conn_id) : conn_id(conn_id) {} - bool operator()(const GattServiceDevice& other) const { - return (conn_id == other.conn_id); - } + bool operator()(const GattServiceDevice& other) const { return conn_id == other.conn_id; } }; void Dump(std::ostream& os) const { @@ -132,8 +122,7 @@ class GattServiceDevice { os << ", \"is_gatt_service_valid\": " << (gatt_svc_validation_steps == 0 ? "\"True\"" : "\"False\"") << "(" << +gatt_svc_validation_steps << ")"; - os << ", \"is_connecting_actively\": " - << (is_connecting_actively ? "\"True\"" : "\"False\""); + os << ", \"is_connecting_actively\": " << (is_connecting_actively ? "\"True\"" : "\"False\""); } }; @@ -152,8 +141,7 @@ class HasDevice : public GattServiceDevice { /* Some opcodes are mandatory but the characteristics aren't - these are * conditional then. */ - if ((cp_handle != GAP_INVALID_HANDLE) && - (active_preset_handle != GAP_INVALID_HANDLE)) { + if ((cp_handle != GAP_INVALID_HANDLE) && (active_preset_handle != GAP_INVALID_HANDLE)) { supported_opcodes_bitmask |= kControlPointMandatoryOpcodesBitmask; } @@ -163,12 +151,11 @@ class HasDevice : public GattServiceDevice { } if (features & bluetooth::has::kFeatureBitWritablePresets) { - supported_opcodes_bitmask |= - PresetCtpOpcode2Bitmask(PresetCtpOpcode::WRITE_PRESET_NAME); + supported_opcodes_bitmask |= PresetCtpOpcode2Bitmask(PresetCtpOpcode::WRITE_PRESET_NAME); } } - public: +public: /* Char handle and current ccc value */ uint16_t active_preset_handle = GAP_INVALID_HANDLE; uint16_t active_preset_ccc_handle = GAP_INVALID_HANDLE; @@ -187,8 +174,7 @@ class HasDevice : public GattServiceDevice { std::list ctp_notifications_; HasJournal has_journal_; - HasDevice(const RawAddress& addr, uint8_t features) - : GattServiceDevice(addr) { + HasDevice(const RawAddress& addr, uint8_t features) : GattServiceDevice(addr) { UpdateFeatures(features); } @@ -229,8 +215,7 @@ class HasDevice : public GattServiceDevice { } inline bool SupportsPresets() const { - return (active_preset_handle != GAP_INVALID_HANDLE) && - (cp_handle != GAP_INVALID_HANDLE); + return (active_preset_handle != GAP_INVALID_HANDLE) && (cp_handle != GAP_INVALID_HANDLE); } inline bool SupportsActivePresetNotification() const { @@ -241,9 +226,7 @@ class HasDevice : public GattServiceDevice { return features_ccc_handle != GAP_INVALID_HANDLE; } - inline bool HasFeaturesNotificationEnabled() const { - return features_notifications_enabled; - } + inline bool HasFeaturesNotificationEnabled() const { return features_notifications_enabled; } inline bool SupportsOperation(PresetCtpOpcode op) { auto mask = PresetCtpOpcode2Bitmask(op); @@ -252,17 +235,17 @@ class HasDevice : public GattServiceDevice { bool IsValidPreset(uint8_t preset_index, bool writable_only = false) const { if (has_presets.count(preset_index)) { - return writable_only ? has_presets.find(preset_index)->IsWritable() - : true; + return writable_only ? has_presets.find(preset_index)->IsWritable() : true; } return false; } - const HasPreset* GetPreset(uint8_t preset_index, - bool writable_only = false) const { + const HasPreset* GetPreset(uint8_t preset_index, bool writable_only = false) const { if (has_presets.count(preset_index)) { decltype(has_presets)::iterator preset = has_presets.find(preset_index); - if (writable_only) return preset->IsWritable() ? &*preset : nullptr; + if (writable_only) { + return preset->IsWritable() ? &*preset : nullptr; + } return &*preset; } return nullptr; @@ -329,12 +312,10 @@ class HasDevice : public GattServiceDevice { /* Deserializes all the presets from a binary blob read from the persistent * storage. */ - static bool DeserializePresets(const uint8_t* p_in, size_t len, - HasDevice& device) { + static bool DeserializePresets(const uint8_t* p_in, size_t len, HasDevice& device) { HasPreset preset; if (len < 2 + preset.SerializedSize()) { - bluetooth::log::error( - "Deserialization error. Invalid input buffer size length."); + bluetooth::log::error("Deserialization error. Invalid input buffer size length."); return false; } auto* p_end = p_in + len; @@ -375,15 +356,13 @@ class HasDevice : public GattServiceDevice { os << ", \"ctp_notifications size\": " << ctp_notifications_.size(); os << ",\n"; - os << " " - << "\"presets\": ["; + os << " " << "\"presets\": ["; for (auto const& preset : has_presets) { os << "\n " << preset << ","; } os << "\n ],\n"; - os << " " - << "\"Ctp. notifications process queue\": {"; + os << " " << "\"Ctp. notifications process queue\": {"; if (ctp_notifications_.size() != 0) { size_t ntf_pos = 0; for (auto const& ntf : ctp_notifications_) { @@ -400,8 +379,7 @@ class HasDevice : public GattServiceDevice { } os << "\n },\n"; - os << " " - << "\"event history\": {"; + os << " " << "\"event history\": {"; size_t pos = 0; for (auto const& record : has_journal_) { os << "\n "; @@ -417,7 +395,7 @@ class HasDevice : public GattServiceDevice { os << "\n }"; } - private: +private: static constexpr int kHasDeviceBinaryBlobHdr = 0x55; }; diff --git a/system/bta/hd/bta_hd_act.cc b/system/bta/hd/bta_hd_act.cc index 518c350b215..566d845a9b3 100644 --- a/system/bta/hd/bta_hd_act.cc +++ b/system/bta/hd/bta_hd_act.cc @@ -44,11 +44,9 @@ using namespace bluetooth::legacy::stack::sdp; using namespace bluetooth; -static void bta_hd_cback(const RawAddress& bd_addr, uint8_t event, - uint32_t data, BT_HDR* pdata); +static void bta_hd_cback(const RawAddress& bd_addr, uint8_t event, uint32_t data, BT_HDR* pdata); -static bool check_descriptor(uint8_t* data, uint16_t length, - bool* has_report_id) { +static bool check_descriptor(uint8_t* data, uint16_t length, bool* has_report_id) { uint8_t* ptr = data; *has_report_id = FALSE; @@ -74,7 +72,7 @@ static bool check_descriptor(uint8_t* data, uint16_t length, } } - return (ptr == data + length); + return ptr == data + length; } /******************************************************************************* @@ -128,12 +126,13 @@ void bta_hd_api_disable(void) { log::verbose(""); /* service is not enabled */ - if (bta_hd_cb.p_cback == NULL) return; + if (bta_hd_cb.p_cback == NULL) { + return; + } /* Remove service record */ if (bta_hd_cb.sdp_handle != 0) { - if (!get_legacy_stack_sdp_api()->handle.SDP_DeleteRecord( - bta_hd_cb.sdp_handle)) { + if (!get_legacy_stack_sdp_api()->handle.SDP_DeleteRecord(bta_hd_cb.sdp_handle)) { log::warn("Unable to delete SDP record handle:{}", bta_hd_cb.sdp_handle); }; bta_sys_remove_uuid(UUID_SERVCLASS_HUMAN_INTERFACE); @@ -176,15 +175,12 @@ void bta_hd_register_act(tBTA_HD_DATA* p_data) { * itself is well-formed. Also check if descriptor has Report Id item so we * know if report will have prefix or not. */ if (p_app_data->d_len > BTA_HD_APP_DESCRIPTOR_LEN || - !check_descriptor(p_app_data->d_data, p_app_data->d_len, - &use_report_id)) { + !check_descriptor(p_app_data->d_data, p_app_data->d_len, &use_report_id)) { log::error("Descriptor is too long or malformed"); ret.reg_status.status = BTA_HD_ERROR; (*bta_hd_cb.p_cback)(BTA_HD_REGISTER_APP_EVT, &ret); bluetooth::shim::CountCounterMetrics( - android::bluetooth::CodePathCounterKeyEnum:: - HIDD_REGISTER_DESCRIPTOR_MALFORMED, - 1); + android::bluetooth::CodePathCounterKeyEnum::HIDD_REGISTER_DESCRIPTOR_MALFORMED, 1); return; } @@ -192,28 +188,25 @@ void bta_hd_register_act(tBTA_HD_DATA* p_data) { /* Remove old record if for some reason it's already registered */ if (bta_hd_cb.sdp_handle != 0) { - if (!get_legacy_stack_sdp_api()->handle.SDP_DeleteRecord( - bta_hd_cb.sdp_handle)) { + if (!get_legacy_stack_sdp_api()->handle.SDP_DeleteRecord(bta_hd_cb.sdp_handle)) { log::warn("Unable to delete SDP record handle:{}", bta_hd_cb.sdp_handle); } } bta_hd_cb.use_report_id = use_report_id; bta_hd_cb.sdp_handle = get_legacy_stack_sdp_api()->handle.SDP_CreateRecord(); - HID_DevAddRecord(bta_hd_cb.sdp_handle, p_app_data->name, - p_app_data->description, p_app_data->provider, - p_app_data->subclass, p_app_data->d_len, p_app_data->d_data); + HID_DevAddRecord(bta_hd_cb.sdp_handle, p_app_data->name, p_app_data->description, + p_app_data->provider, p_app_data->subclass, p_app_data->d_len, + p_app_data->d_data); bta_sys_add_uuid(UUID_SERVCLASS_HUMAN_INTERFACE); - HID_DevSetIncomingQos( - p_app_data->in_qos.service_type, p_app_data->in_qos.token_rate, - p_app_data->in_qos.token_bucket_size, p_app_data->in_qos.peak_bandwidth, - p_app_data->in_qos.access_latency, p_app_data->in_qos.delay_variation); + HID_DevSetIncomingQos(p_app_data->in_qos.service_type, p_app_data->in_qos.token_rate, + p_app_data->in_qos.token_bucket_size, p_app_data->in_qos.peak_bandwidth, + p_app_data->in_qos.access_latency, p_app_data->in_qos.delay_variation); - HID_DevSetOutgoingQos( - p_app_data->out_qos.service_type, p_app_data->out_qos.token_rate, - p_app_data->out_qos.token_bucket_size, p_app_data->out_qos.peak_bandwidth, - p_app_data->out_qos.access_latency, p_app_data->out_qos.delay_variation); + HID_DevSetOutgoingQos(p_app_data->out_qos.service_type, p_app_data->out_qos.token_rate, + p_app_data->out_qos.token_bucket_size, p_app_data->out_qos.peak_bandwidth, + p_app_data->out_qos.access_latency, p_app_data->out_qos.delay_variation); // application is registered so we can accept incoming connections HID_DevSetIncomingPolicy(TRUE); @@ -243,8 +236,7 @@ void bta_hd_unregister_act() { HID_DevSetIncomingPolicy(FALSE); if (bta_hd_cb.sdp_handle != 0) { - if (!get_legacy_stack_sdp_api()->handle.SDP_DeleteRecord( - bta_hd_cb.sdp_handle)) { + if (!get_legacy_stack_sdp_api()->handle.SDP_DeleteRecord(bta_hd_cb.sdp_handle)) { log::warn("Unable to delete SDP record handle:{}", bta_hd_cb.sdp_handle); } } @@ -393,11 +385,9 @@ void bta_hd_send_report_act(tBTA_HD_DATA* p_data) { log::verbose(""); channel = p_report->use_intr ? HID_CHANNEL_INTR : HID_CHANNEL_CTRL; - report_id = - (bta_hd_cb.use_report_id || bta_hd_cb.boot_mode) ? p_report->id : 0x00; + report_id = (bta_hd_cb.use_report_id || bta_hd_cb.boot_mode) ? p_report->id : 0x00; - HID_DevSendReport(channel, p_report->type, report_id, p_report->len, - p_report->data); + HID_DevSendReport(channel, p_report->type, report_id, p_report->len, p_report->data); /* trigger PM */ bta_sys_busy(BTA_ID_HD, 1, bta_hd_cb.bd_addr); @@ -728,8 +718,7 @@ void bta_hd_exit_suspend_act(tBTA_HD_DATA* p_data) { * Returns void * ******************************************************************************/ -static void bta_hd_cback(const RawAddress& bd_addr, uint8_t event, - uint32_t data, BT_HDR* pdata) { +static void bta_hd_cback(const RawAddress& bd_addr, uint8_t event, uint32_t data, BT_HDR* pdata) { tBTA_HD_CBACK_DATA* p_buf = NULL; uint16_t sm_event = BTA_HD_INVALID_EVT; @@ -774,8 +763,8 @@ static void bta_hd_cback(const RawAddress& bd_addr, uint8_t event, } if (sm_event != BTA_HD_INVALID_EVT && - (p_buf = (tBTA_HD_CBACK_DATA*)osi_malloc(sizeof(tBTA_HD_CBACK_DATA) + - sizeof(BT_HDR))) != NULL) { + (p_buf = (tBTA_HD_CBACK_DATA*)osi_malloc(sizeof(tBTA_HD_CBACK_DATA) + sizeof(BT_HDR))) != + NULL) { p_buf->hdr.event = sm_event; p_buf->addr = bd_addr; p_buf->data = data; diff --git a/system/bta/hd/bta_hd_api.cc b/system/bta/hd/bta_hd_api.cc index 2cf1b886b16..09c353b7df6 100644 --- a/system/bta/hd/bta_hd_api.cc +++ b/system/bta/hd/bta_hd_api.cc @@ -60,8 +60,7 @@ void BTA_HdEnable(tBTA_HD_CBACK* p_cback) { bta_sys_register(BTA_ID_HD, &bta_hd_reg); - tBTA_HD_API_ENABLE* p_buf = - (tBTA_HD_API_ENABLE*)osi_malloc((uint16_t)sizeof(tBTA_HD_API_ENABLE)); + tBTA_HD_API_ENABLE* p_buf = (tBTA_HD_API_ENABLE*)osi_malloc((uint16_t)sizeof(tBTA_HD_API_ENABLE)); memset(p_buf, 0, sizeof(tBTA_HD_API_ENABLE)); @@ -93,7 +92,7 @@ void BTA_HdDisable(void) { * Function BTA_HdRegisterApp * * Description This function is called when application should be -*registered + *registered * * Returns void * @@ -102,8 +101,7 @@ void BTA_HdRegisterApp(tBTA_HD_APP_INFO* p_app_info, tBTA_HD_QOS_INFO* p_in_qos, tBTA_HD_QOS_INFO* p_out_qos) { log::verbose(""); - tBTA_HD_REGISTER_APP* p_buf = - (tBTA_HD_REGISTER_APP*)osi_malloc(sizeof(tBTA_HD_REGISTER_APP)); + tBTA_HD_REGISTER_APP* p_buf = (tBTA_HD_REGISTER_APP*)osi_malloc(sizeof(tBTA_HD_REGISTER_APP)); p_buf->hdr.event = BTA_HD_API_REGISTER_APP_EVT; if (p_app_info->p_name) { @@ -113,8 +111,7 @@ void BTA_HdRegisterApp(tBTA_HD_APP_INFO* p_app_info, tBTA_HD_QOS_INFO* p_in_qos, } if (p_app_info->p_description) { - strlcpy(p_buf->description, p_app_info->p_description, - BTA_HD_APP_DESCRIPTION_LEN); + strlcpy(p_buf->description, p_app_info->p_description, BTA_HD_APP_DESCRIPTION_LEN); } else { p_buf->description[0] = '\0'; } @@ -131,8 +128,7 @@ void BTA_HdRegisterApp(tBTA_HD_APP_INFO* p_app_info, tBTA_HD_QOS_INFO* p_in_qos, p_app_info->descriptor.dl_len = BTA_HD_APP_DESCRIPTOR_LEN; } p_buf->d_len = p_app_info->descriptor.dl_len; - memcpy(p_buf->d_data, p_app_info->descriptor.dsc_list, - p_app_info->descriptor.dl_len); + memcpy(p_buf->d_data, p_app_info->descriptor.dsc_list, p_app_info->descriptor.dl_len); // copy qos data as-is memcpy(&p_buf->in_qos, p_in_qos, sizeof(tBTA_HD_QOS_INFO)); @@ -146,7 +142,7 @@ void BTA_HdRegisterApp(tBTA_HD_APP_INFO* p_app_info, tBTA_HD_QOS_INFO* p_in_qos, * Function BTA_HdUnregisterApp * * Description This function is called when application should be -*unregistered + *unregistered * * Returns void * @@ -174,14 +170,13 @@ void BTA_HdSendReport(tBTA_HD_REPORT* p_report) { if (p_report->len > BTA_HD_REPORT_LEN) { log::warn( - "report len ({}) > MTU len ({}), can't send report. Increase value of " - "HID_DEV_MTU_SIZE to send larger reports", - p_report->len, BTA_HD_REPORT_LEN); + "report len ({}) > MTU len ({}), can't send report. Increase value of " + "HID_DEV_MTU_SIZE to send larger reports", + p_report->len, BTA_HD_REPORT_LEN); return; } - tBTA_HD_SEND_REPORT* p_buf = - (tBTA_HD_SEND_REPORT*)osi_malloc(sizeof(tBTA_HD_SEND_REPORT)); + tBTA_HD_SEND_REPORT* p_buf = (tBTA_HD_SEND_REPORT*)osi_malloc(sizeof(tBTA_HD_SEND_REPORT)); p_buf->hdr.event = BTA_HD_API_SEND_REPORT_EVT; p_buf->use_intr = p_report->use_intr; @@ -216,7 +211,7 @@ void BTA_HdVirtualCableUnplug(void) { * Function BTA_HdConnect * * Description This function is called when connection to host shall be -*made + *made * * Returns void * @@ -224,8 +219,7 @@ void BTA_HdVirtualCableUnplug(void) { void BTA_HdConnect(const RawAddress& addr) { log::verbose(""); - tBTA_HD_DEVICE_CTRL* p_buf = - (tBTA_HD_DEVICE_CTRL*)osi_malloc(sizeof(tBTA_HD_DEVICE_CTRL)); + tBTA_HD_DEVICE_CTRL* p_buf = (tBTA_HD_DEVICE_CTRL*)osi_malloc(sizeof(tBTA_HD_DEVICE_CTRL)); p_buf->hdr.event = BTA_HD_API_CONNECT_EVT; p_buf->addr = addr; @@ -261,8 +255,7 @@ void BTA_HdDisconnect(void) { ******************************************************************************/ void BTA_HdAddDevice(const RawAddress& addr) { log::verbose(""); - tBTA_HD_DEVICE_CTRL* p_buf = - (tBTA_HD_DEVICE_CTRL*)osi_malloc(sizeof(tBTA_HD_DEVICE_CTRL)); + tBTA_HD_DEVICE_CTRL* p_buf = (tBTA_HD_DEVICE_CTRL*)osi_malloc(sizeof(tBTA_HD_DEVICE_CTRL)); p_buf->hdr.event = BTA_HD_API_ADD_DEVICE_EVT; p_buf->addr = addr; @@ -281,8 +274,7 @@ void BTA_HdAddDevice(const RawAddress& addr) { ******************************************************************************/ void BTA_HdRemoveDevice(const RawAddress& addr) { log::verbose(""); - tBTA_HD_DEVICE_CTRL* p_buf = - (tBTA_HD_DEVICE_CTRL*)osi_malloc(sizeof(tBTA_HD_DEVICE_CTRL)); + tBTA_HD_DEVICE_CTRL* p_buf = (tBTA_HD_DEVICE_CTRL*)osi_malloc(sizeof(tBTA_HD_DEVICE_CTRL)); p_buf->hdr.event = BTA_HD_API_REMOVE_DEVICE_EVT; p_buf->addr = addr; @@ -301,8 +293,7 @@ void BTA_HdRemoveDevice(const RawAddress& addr) { ******************************************************************************/ void BTA_HdReportError(uint8_t error) { log::verbose(""); - tBTA_HD_REPORT_ERR* p_buf = - (tBTA_HD_REPORT_ERR*)osi_malloc(sizeof(tBTA_HD_REPORT_ERR)); + tBTA_HD_REPORT_ERR* p_buf = (tBTA_HD_REPORT_ERR*)osi_malloc(sizeof(tBTA_HD_REPORT_ERR)); p_buf->hdr.event = BTA_HD_API_REPORT_ERROR_EVT; p_buf->error = error; diff --git a/system/bta/hd/bta_hd_main.cc b/system/bta/hd/bta_hd_main.cc index 12e17d3018a..b916a425813 100644 --- a/system/bta/hd/bta_hd_main.cc +++ b/system/bta/hd/bta_hd_main.cc @@ -45,7 +45,7 @@ enum { BTA_HD_IDLE_ST, /* not connected, waiting for connection */ BTA_HD_CONN_ST, /* host connected */ BTA_HD_TRANSIENT_TO_INIT_ST, /* transient state: going back from CONN to INIT - */ + */ }; typedef uint8_t tBTA_HD_STATE; @@ -194,8 +194,7 @@ bool bta_hd_hdl_event(const BT_HDR_RIGID* p_msg) { // unregister (and disconnect) bta_hd_cb.disable_w4_close = TRUE; - bta_hd_better_state_machine(BTA_HD_API_UNREGISTER_APP_EVT, - (tBTA_HD_DATA*)p_msg); + bta_hd_better_state_machine(BTA_HD_API_UNREGISTER_APP_EVT, (tBTA_HD_DATA*)p_msg); } else { bta_hd_api_disable(); } @@ -204,7 +203,7 @@ bool bta_hd_hdl_event(const BT_HDR_RIGID* p_msg) { default: bta_hd_better_state_machine(p_msg->event, (tBTA_HD_DATA*)p_msg); } - return (TRUE); + return TRUE; } #endif /* BTA_HD_INCLUDED */ diff --git a/system/bta/hearing_aid/hearing_aid.cc b/system/bta/hearing_aid/hearing_aid.cc index 4035fd4cbf0..9da64c48475 100644 --- a/system/bta/hearing_aid/hearing_aid.cc +++ b/system/bta/hearing_aid/hearing_aid.cc @@ -71,9 +71,9 @@ constexpr uint16_t CONNECTION_INTERVAL_10MS_PARAM = 0x0008; constexpr uint16_t CONNECTION_INTERVAL_20MS_PARAM = 0x0010; void btif_storage_add_hearing_aid(const HearingDevice& dev_info); -bool btif_storage_get_hearing_aid_prop( - const RawAddress& address, uint8_t* capabilities, uint64_t* hi_sync_id, - uint16_t* render_delay, uint16_t* preparation_delay, uint16_t* codecs); +bool btif_storage_get_hearing_aid_prop(const RawAddress& address, uint8_t* capabilities, + uint64_t* hi_sync_id, uint16_t* render_delay, + uint16_t* preparation_delay, uint16_t* codecs); constexpr uint8_t CODEC_G722_16KHZ = 0x01; constexpr uint8_t CODEC_G722_24KHZ = 0x02; @@ -138,9 +138,11 @@ std::mutex instance_mutex; HearingAidAudioReceiver* audioReceiver; class HearingDevices { - public: +public: void Add(HearingDevice device) { - if (FindByAddress(device.address) != nullptr) return; + if (FindByAddress(device.address) != nullptr) { + return; + } devices.push_back(device); } @@ -158,38 +160,33 @@ class HearingDevices { } HearingDevice* FindByAddress(const RawAddress& address) { - auto iter = std::find_if(devices.begin(), devices.end(), - [&address](const HearingDevice& device) { - return device.address == address; - }); + auto iter = std::find_if( + devices.begin(), devices.end(), + [&address](const HearingDevice& device) { return device.address == address; }); return (iter == devices.end()) ? nullptr : &(*iter); } HearingDevice* FindOtherConnectedDeviceFromSet(const HearingDevice& device) { - auto iter = std::find_if( - devices.begin(), devices.end(), [&device](const HearingDevice& other) { - return &device != &other && device.hi_sync_id == other.hi_sync_id && - other.conn_id != 0; - }); + auto iter = std::find_if(devices.begin(), devices.end(), [&device](const HearingDevice& other) { + return &device != &other && device.hi_sync_id == other.hi_sync_id && other.conn_id != 0; + }); return (iter == devices.end()) ? nullptr : &(*iter); } HearingDevice* FindByConnId(uint16_t conn_id) { - auto iter = std::find_if(devices.begin(), devices.end(), - [&conn_id](const HearingDevice& device) { - return device.conn_id == conn_id; - }); + auto iter = std::find_if( + devices.begin(), devices.end(), + [&conn_id](const HearingDevice& device) { return device.conn_id == conn_id; }); return (iter == devices.end()) ? nullptr : &(*iter); } HearingDevice* FindByGapHandle(uint16_t gap_handle) { - auto iter = std::find_if(devices.begin(), devices.end(), - [&gap_handle](const HearingDevice& device) { - return device.gap_handle == gap_handle; - }); + auto iter = std::find_if( + devices.begin(), devices.end(), + [&gap_handle](const HearingDevice& device) { return device.gap_handle == gap_handle; }); return (iter == devices.end()) ? nullptr : &(*iter); } @@ -218,17 +215,16 @@ class HearingDevices { } } - size_t size() { return (devices.size()); } + size_t size() { return devices.size(); } std::vector devices; }; -static void write_rpt_ctl_cfg_cb(uint16_t conn_id, tGATT_STATUS status, - uint16_t handle, uint16_t len, - const uint8_t* value, void* data) { +static void write_rpt_ctl_cfg_cb(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, + uint16_t len, const uint8_t* value, void* data) { if (status != GATT_SUCCESS) { - log::error("handle= {}, conn_id={}, status= 0x{:x}, length={}", handle, - conn_id, static_cast(status), len); + log::error("handle= {}, conn_id={}, status= 0x{:x}, length={}", handle, conn_id, + static_cast(status), len); } } @@ -254,7 +250,7 @@ inline void encoder_state_release() { } class HearingAidImpl : public HearingAid { - private: +private: // Keep track of whether the Audio Service has resumed audio playback bool audio_running; bool is_iso_running = false; @@ -262,14 +258,12 @@ class HearingAidImpl : public HearingAid { // parameter updates int16_t overwrite_min_ce_len = -1; int16_t overwrite_max_ce_len = -1; - const std::string PERSIST_MIN_CE_LEN_NAME = - "persist.bluetooth.hearing_aid_min_ce_len"; - const std::string PERSIST_MAX_CE_LEN_NAME = - "persist.bluetooth.hearing_aid_max_ce_len"; + const std::string PERSIST_MIN_CE_LEN_NAME = "persist.bluetooth.hearing_aid_min_ce_len"; + const std::string PERSIST_MAX_CE_LEN_NAME = "persist.bluetooth.hearing_aid_max_ce_len"; // Record whether the connection parameter needs to update to a better one bool needs_parameter_update = false; std::chrono::time_point last_drop_time_point = - std::chrono::steady_clock::now(); + std::chrono::steady_clock::now(); // at most 1 packet DROP per kDropFrequencyThreshold seconds static constexpr int64_t kDropFrequencyThreshold = 60; @@ -279,11 +273,10 @@ class HearingAidImpl : public HearingAid { // connected. std::unique_ptr asrc; - public: +public: ~HearingAidImpl() override = default; - HearingAidImpl(bluetooth::hearing_aid::HearingAidCallbacks* callbacks, - Closure initCb) + HearingAidImpl(bluetooth::hearing_aid::HearingAidCallbacks* callbacks, Closure initCb) : audio_running(false), overwrite_min_ce_len(-1), overwrite_max_ce_len(-1), @@ -293,48 +286,41 @@ class HearingAidImpl : public HearingAid { callbacks(callbacks), codec_in_use(0) { default_data_interval_ms = (uint16_t)osi_property_get_int32( - "persist.bluetooth.hearingaid.interval", (int32_t)HA_INTERVAL_20_MS); + "persist.bluetooth.hearingaid.interval", (int32_t)HA_INTERVAL_20_MS); if ((default_data_interval_ms != HA_INTERVAL_10_MS) && (default_data_interval_ms != HA_INTERVAL_20_MS)) { - log::error("invalid interval={}ms. Overwrriting back to default", - default_data_interval_ms); + log::error("invalid interval={}ms. Overwrriting back to default", default_data_interval_ms); default_data_interval_ms = HA_INTERVAL_20_MS; } - overwrite_min_ce_len = - (int16_t)osi_property_get_int32(PERSIST_MIN_CE_LEN_NAME.c_str(), -1); - overwrite_max_ce_len = - (int16_t)osi_property_get_int32(PERSIST_MAX_CE_LEN_NAME.c_str(), -1); + overwrite_min_ce_len = (int16_t)osi_property_get_int32(PERSIST_MIN_CE_LEN_NAME.c_str(), -1); + overwrite_max_ce_len = (int16_t)osi_property_get_int32(PERSIST_MAX_CE_LEN_NAME.c_str(), -1); - log::info( - "default_data_interval_ms={} overwrite_min_ce_len={}" - " overwrite_max_ce_len={}", - default_data_interval_ms, overwrite_min_ce_len, overwrite_max_ce_len); + log::info("default_data_interval_ms={} overwrite_min_ce_len={} overwrite_max_ce_len={}", + default_data_interval_ms, overwrite_min_ce_len, overwrite_max_ce_len); BTA_GATTC_AppRegister( - hearingaid_gattc_callback, - base::Bind( - [](Closure initCb, uint8_t client_id, uint8_t status) { - if (status != GATT_SUCCESS) { - log::error( - "Can't start Hearing Aid profile - no gatt clients left!"); - return; - } - instance->gatt_if = client_id; - initCb.Run(); - }, - initCb), - false); + hearingaid_gattc_callback, + base::Bind( + [](Closure initCb, uint8_t client_id, uint8_t status) { + if (status != GATT_SUCCESS) { + log::error("Can't start Hearing Aid profile - no gatt clients left!"); + return; + } + instance->gatt_if = client_id; + initCb.Run(); + }, + initCb), + false); IsoManager::GetInstance()->Start(); - IsoManager::GetInstance()->RegisterOnIsoTrafficActiveCallback( - [](bool is_active) { - if (!instance) { - return; - } - instance->IsoTrafficEventCb(is_active); - }); + IsoManager::GetInstance()->RegisterOnIsoTrafficActiveCallback([](bool is_active) { + if (!instance) { + return; + } + instance->IsoTrafficEventCb(is_active); + }); } void IsoTrafficEventCb(bool is_active) { @@ -352,8 +338,7 @@ class HearingAidImpl : public HearingAid { for (auto& device : hearingDevices.devices) { if (device.conn_id != 0) { device.connection_update_status = STARTED; - device.requested_connection_interval = - UpdateBleConnParams(device.address); + device.requested_connection_interval = UpdateBleConnParams(device.address); } } } @@ -371,13 +356,13 @@ class HearingAidImpl : public HearingAid { if (asrc == nullptr) { log::info("Configuring Asha resampler"); asrc = std::make_unique( - /*thread*/ get_main_thread(), - /*channels*/ 2, - /*sample_rate*/ codec_in_use == CODEC_G722_24KHZ ? 24000 : 16000, - /*bit_depth*/ 16, - /*interval_us*/ default_data_interval_ms * 1000, - /*num_burst_buffers*/ 0, - /*burst_delay*/ 0); + /*thread*/ get_main_thread(), + /*channels*/ 2, + /*sample_rate*/ codec_in_use == CODEC_G722_24KHZ ? 24000 : 16000, + /*bit_depth*/ 16, + /*interval_us*/ default_data_interval_ms * 1000, + /*num_burst_buffers*/ 0, + /*burst_delay*/ 0); } } @@ -417,37 +402,32 @@ class HearingAidImpl : public HearingAid { break; default: - log::error("invalid default_data_interval_ms={}", - default_data_interval_ms); + log::error("invalid default_data_interval_ms={}", default_data_interval_ms); min_ce_len = MIN_CE_LEN_10MS_CI; connection_interval = CONNECTION_INTERVAL_10MS_PARAM; } if (overwrite_min_ce_len != -1) { - log::warn("min_ce_len={} for device {} is overwritten to {}", min_ce_len, - address, overwrite_min_ce_len); + log::warn("min_ce_len={} for device {} is overwritten to {}", min_ce_len, address, + overwrite_min_ce_len); min_ce_len = overwrite_min_ce_len; } if (overwrite_max_ce_len != -1) { - log::warn("max_ce_len={} for device {} is overwritten to {}", max_ce_len, - address, overwrite_max_ce_len); + log::warn("max_ce_len={} for device {} is overwritten to {}", max_ce_len, address, + overwrite_max_ce_len); max_ce_len = overwrite_max_ce_len; } - log::info( - "L2CA_UpdateBleConnParams for device {} min_ce_len:{} max_ce_len:{}", - address, min_ce_len, max_ce_len); - if (!L2CA_UpdateBleConnParams(address, connection_interval, - connection_interval, 0x000A, 0x0064 /*1s*/, - min_ce_len, max_ce_len)) { - log::warn("Unable to update L2CAP ble connection parameters peer:{}", - address); + log::info("L2CA_UpdateBleConnParams for device {} min_ce_len:{} max_ce_len:{}", address, + min_ce_len, max_ce_len); + if (!L2CA_UpdateBleConnParams(address, connection_interval, connection_interval, 0x000A, + 0x0064 /*1s*/, min_ce_len, max_ce_len)) { + log::warn("Unable to update L2CAP ble connection parameters peer:{}", address); } return connection_interval; } - bool IsBelowDropFrequency( - std::chrono::time_point tp) { + bool IsBelowDropFrequency(std::chrono::time_point tp) { auto duration = tp - last_drop_time_point; bool droppable = std::chrono::duration_cast(duration).count() >= kDropFrequencyThreshold; @@ -468,8 +448,8 @@ class HearingAidImpl : public HearingAid { } void AddFromStorage(const HearingDevice& dev_info, bool is_acceptlisted) { - log::info("bd_addr={} hi_sync_id=0x{:x} is_acceptlisted={}", - dev_info.address, dev_info.hi_sync_id, is_acceptlisted); + log::info("bd_addr={} hi_sync_id=0x{:x} is_acceptlisted={}", dev_info.address, + dev_info.hi_sync_id, is_acceptlisted); if (is_acceptlisted) { hearingDevices.Add(dev_info); @@ -478,25 +458,21 @@ class HearingAidImpl : public HearingAid { // BTM_BleSetConnScanParams(2048, 1024); /* add device into BG connection to accept remote initiated connection */ - BTA_GATTC_Open(gatt_if, dev_info.address, BTM_BLE_BKG_CONNECT_ALLOW_LIST, - false); + BTA_GATTC_Open(gatt_if, dev_info.address, BTM_BLE_BKG_CONNECT_ALLOW_LIST, false); } - callbacks->OnDeviceAvailable(dev_info.capabilities, dev_info.hi_sync_id, - dev_info.address); + callbacks->OnDeviceAvailable(dev_info.capabilities, dev_info.hi_sync_id, dev_info.address); } - int GetDeviceCount() { return (hearingDevices.size()); } + int GetDeviceCount() { return hearingDevices.size(); } - void OnGattConnected(tGATT_STATUS status, uint16_t conn_id, - tGATT_IF client_if, RawAddress address, - tBT_TRANSPORT transport, uint16_t mtu) { + void OnGattConnected(tGATT_STATUS status, uint16_t conn_id, tGATT_IF client_if, + RawAddress address, tBT_TRANSPORT transport, uint16_t mtu) { HearingDevice* hearingDevice = hearingDevices.FindByAddress(address); if (!hearingDevice) { /* When Hearing Aid is quickly disabled and enabled in settings, this case * might happen */ - log::warn("Closing connection to non hearing-aid device: bd_addr={}", - address); + log::warn("Closing connection to non hearing-aid device: bd_addr={}", address); BTA_GATTC_Close(conn_id); return; } @@ -527,19 +503,15 @@ class HearingAidImpl : public HearingAid { uint64_t hi_sync_id = hearingDevice->hi_sync_id; // If there a background connection to the other device of a pair, promote - // it to a direct connection to scan more agressively for it + // it to a direct connection to scan more aggressively for it if (hi_sync_id != 0) { for (auto& device : hearingDevices.devices) { - if (device.hi_sync_id == hi_sync_id && device.conn_id == 0 && - !device.connecting_actively) { - log::info( - "Promoting device from the set from background to direct " - "connection, bda={}", - device.address); + if (device.hi_sync_id == hi_sync_id && device.conn_id == 0 && !device.connecting_actively) { + log::info("Promoting device from the set from background to direct connection, bda={}", + device.address); device.connecting_actively = true; device.switch_to_background_connection_after_failure = true; - BTA_GATTC_Open(gatt_if, device.address, BTM_BLE_DIRECT_CONNECTION, - false); + BTA_GATTC_Open(gatt_if, device.address, BTM_BLE_DIRECT_CONNECTION, false); } } } @@ -590,34 +562,31 @@ class HearingAidImpl : public HearingAid { if (p_data) { if (p_data->conn_update.status == 0) { bool same_conn_interval = - (hearingDevice->requested_connection_interval == - p_data->conn_update.interval); + (hearingDevice->requested_connection_interval == p_data->conn_update.interval); switch (hearingDevice->connection_update_status) { case COMPLETED: if (!same_conn_interval) { log::warn( - "Unexpected change. Redo. connection interval={}, " - "expected={}, conn_id={}, connection_update_status={}", - p_data->conn_update.interval, - hearingDevice->requested_connection_interval, conn_id, - hearingDevice->connection_update_status); + "Unexpected change. Redo. connection interval={}, " + "expected={}, conn_id={}, connection_update_status={}", + p_data->conn_update.interval, hearingDevice->requested_connection_interval, + conn_id, hearingDevice->connection_update_status); // Redo this connection interval change. hearingDevice->connection_update_status = AWAITING; } break; case STARTED: if (same_conn_interval) { - log::info("Connection update completed: conn_id={} bd_addr={}", - conn_id, hearingDevice->address); + log::info("Connection update completed: conn_id={} bd_addr={}", conn_id, + hearingDevice->address); hearingDevice->connection_update_status = COMPLETED; } else { log::warn( - "Ignored. Different connection interval={}, expected={}, " - "conn_id={}, connection_update_status={}", - p_data->conn_update.interval, - hearingDevice->requested_connection_interval, conn_id, - hearingDevice->connection_update_status); + "Ignored. Different connection interval={}, expected={}, " + "conn_id={}, connection_update_status={}", + p_data->conn_update.interval, hearingDevice->requested_connection_interval, + conn_id, hearingDevice->connection_update_status); // Wait for the right Connection Update Completion. return; } @@ -629,17 +598,14 @@ class HearingAidImpl : public HearingAid { // Inform this side and other side device (if any) of Connection // Updates. - std::vector conn_update( - {CONTROL_POINT_OP_STATE_CHANGE, STATE_CHANGE_CONN_UPDATE, - (uint8_t)p_data->conn_update.interval}); + std::vector conn_update({CONTROL_POINT_OP_STATE_CHANGE, STATE_CHANGE_CONN_UPDATE, + (uint8_t)p_data->conn_update.interval}); send_state_change_to_other_side(hearingDevice, conn_update); send_state_change(hearingDevice, conn_update); } else { - log::info( - "error status=0x{:x}, conn_id={} bd_addr={}, " - "connection_update_status={}", - static_cast(p_data->conn_update.status), conn_id, - hearingDevice->address, hearingDevice->connection_update_status); + log::info("error status=0x{:x}, conn_id={} bd_addr={}, connection_update_status={}", + static_cast(p_data->conn_update.status), conn_id, hearingDevice->address, + hearingDevice->connection_update_status); if (hearingDevice->connection_update_status == STARTED) { // Redo this connection interval change. log::error("Redo Connection Interval change"); @@ -650,8 +616,7 @@ class HearingAidImpl : public HearingAid { hearingDevice->connection_update_status = NONE; } - if (!hearingDevice->accepting_audio && - hearingDevice->connection_update_status == COMPLETED && + if (!hearingDevice->accepting_audio && hearingDevice->connection_update_status == COMPLETED && hearingDevice->gap_opened) { OnDeviceReady(hearingDevice->address); } @@ -659,8 +624,7 @@ class HearingAidImpl : public HearingAid { for (auto& device : hearingDevices.devices) { if (device.conn_id && (device.connection_update_status == AWAITING)) { device.connection_update_status = STARTED; - device.requested_connection_interval = - UpdateBleConnParams(device.address); + device.requested_connection_interval = UpdateBleConnParams(device.address); return; } } @@ -677,8 +641,7 @@ class HearingAidImpl : public HearingAid { log::debug("bd_addr={} rssi={}", address, (int)rssi_value); if (hearingDevice->read_rssi_count <= 0) { - log::error("bd_addr={}, invalid read_rssi_count={}", address, - hearingDevice->read_rssi_count); + log::error("bd_addr={}, invalid read_rssi_count={}", address, hearingDevice->read_rssi_count); return; } @@ -712,23 +675,20 @@ class HearingAidImpl : public HearingAid { log::info("encryption successful: bd_addr={}", address); - if (hearingDevice->audio_control_point_handle && - hearingDevice->audio_status_handle && - hearingDevice->audio_status_ccc_handle && - hearingDevice->volume_handle && hearingDevice->read_psm_handle) { + if (hearingDevice->audio_control_point_handle && hearingDevice->audio_status_handle && + hearingDevice->audio_status_ccc_handle && hearingDevice->volume_handle && + hearingDevice->read_psm_handle) { // Use cached data, jump to read PSM ReadPSM(hearingDevice); } else { - log::info("starting service search request for ASHA: bd_addr={}", - address); + log::info("starting service search request for ASHA: bd_addr={}", address); hearingDevice->first_connection = true; BTA_GATTC_ServiceSearchRequest(hearingDevice->conn_id, HEARING_AID_UUID); } } - // Just take care phy update successful case to avoid loop excuting. - void OnPhyUpdateEvent(uint16_t conn_id, uint8_t tx_phys, uint8_t rx_phys, - tGATT_STATUS status) { + // Just take care phy update successful case to avoid loop executing. + void OnPhyUpdateEvent(uint16_t conn_id, uint8_t tx_phys, uint8_t rx_phys, tGATT_STATUS status) { HearingDevice* hearingDevice = hearingDevices.FindByConnId(conn_id); if (!hearingDevice) { log::error("unknown device: conn_id=0x{:x}", conn_id); @@ -736,30 +696,28 @@ class HearingAidImpl : public HearingAid { } if (status != GATT_SUCCESS) { - log::warn("phy update failed: bd_addr={} status={}", - hearingDevice->address, status); + log::warn("phy update failed: bd_addr={} status={}", hearingDevice->address, status); return; } if (tx_phys == PHY_LE_2M && rx_phys == PHY_LE_2M) { - log::info("phy update to 2M successful: bd_addr={}", - hearingDevice->address); + log::info("phy update to 2M successful: bd_addr={}", hearingDevice->address); hearingDevice->phy_update_retry_remain = kPhyUpdateRetryLimit; return; } if (hearingDevice->phy_update_retry_remain > 0) { log::info( - "phy update successful with unexpected phys, retrying:" - " bd_addr={} tx_phy=0x{:x} rx_phy=0x{:x}", - hearingDevice->address, tx_phys, rx_phys); + "phy update successful with unexpected phys, retrying:" + " bd_addr={} tx_phy=0x{:x} rx_phy=0x{:x}", + hearingDevice->address, tx_phys, rx_phys); BTM_BleSetPhy(hearingDevice->address, PHY_LE_2M, PHY_LE_2M, 0); hearingDevice->phy_update_retry_remain--; } else { log::warn( - "phy update successful with unexpected phys, exceeded retry count:" - " bd_addr={} tx_phy=0x{:x} rx_phy=0x{:x}", - hearingDevice->address, tx_phys, rx_phys); + "phy update successful with unexpected phys, exceeded retry count:" + " bd_addr={} tx_phy=0x{:x} rx_phy=0x{:x}", + hearingDevice->address, tx_phys, rx_phys); } } @@ -792,12 +750,10 @@ class HearingAidImpl : public HearingAid { log::info("bd_addr={}", address); if (hearingDevice->service_changed_rcvd || - !(hearingDevice->audio_control_point_handle && - hearingDevice->audio_status_handle && - hearingDevice->audio_status_ccc_handle && - hearingDevice->volume_handle && hearingDevice->read_psm_handle)) { - log::info("starting service search request for ASHA: bd_addr={}", - address); + !(hearingDevice->audio_control_point_handle && hearingDevice->audio_status_handle && + hearingDevice->audio_status_ccc_handle && hearingDevice->volume_handle && + hearingDevice->read_psm_handle)) { + log::info("starting service search request for ASHA: bd_addr={}", address); BTA_GATTC_ServiceSearchRequest(hearingDevice->conn_id, HEARING_AID_UUID); } } @@ -811,33 +767,28 @@ class HearingAidImpl : public HearingAid { // Known device, nothing to do. if (!hearingDevice->first_connection) { - log::info("service discovery result ignored: bd_addr={}", - hearingDevice->address); + log::info("service discovery result ignored: bd_addr={}", hearingDevice->address); return; } if (status != GATT_SUCCESS) { /* close connection and report service discovery complete with error */ - log::error("service discovery failed: bd_addr={} status={}", - hearingDevice->address, status); + log::error("service discovery failed: bd_addr={} status={}", hearingDevice->address, status); if (hearingDevice->first_connection) { - callbacks->OnConnectionState(ConnectionState::DISCONNECTED, - hearingDevice->address); + callbacks->OnConnectionState(ConnectionState::DISCONNECTED, hearingDevice->address); } return; } - log::info("service discovery successful: bd_addr={}", - hearingDevice->address); + log::info("service discovery successful: bd_addr={}", hearingDevice->address); const std::list* services = BTA_GATTC_GetServices(conn_id); const gatt::Service* service = nullptr; for (const gatt::Service& tmp : *services) { if (tmp.uuid == Uuid::From16Bit(UUID_SERVCLASS_GATT_SERVER)) { - log::info("Found UUID_SERVCLASS_GATT_SERVER, handle=0x{:x}", - tmp.handle); + log::info("Found UUID_SERVCLASS_GATT_SERVER, handle=0x{:x}", tmp.handle); const gatt::Service* service_changed_service = &tmp; find_server_changed_ccc_handle(conn_id, service_changed_service); } else if (tmp.uuid == HEARING_AID_UUID) { @@ -848,22 +799,19 @@ class HearingAidImpl : public HearingAid { if (!service) { log::error("No Hearing Aid service found"); - callbacks->OnConnectionState(ConnectionState::DISCONNECTED, - hearingDevice->address); + callbacks->OnConnectionState(ConnectionState::DISCONNECTED, hearingDevice->address); return; } for (const gatt::Characteristic& charac : service->characteristics) { if (charac.uuid == READ_ONLY_PROPERTIES_UUID) { if (!btif_storage_get_hearing_aid_prop( - hearingDevice->address, &hearingDevice->capabilities, - &hearingDevice->hi_sync_id, &hearingDevice->render_delay, - &hearingDevice->preparation_delay, &hearingDevice->codecs)) { - log::debug("Reading read only properties 0x{:x}", - charac.value_handle); - BtaGattQueue::ReadCharacteristic( - conn_id, charac.value_handle, - HearingAidImpl::OnReadOnlyPropertiesReadStatic, nullptr); + hearingDevice->address, &hearingDevice->capabilities, + &hearingDevice->hi_sync_id, &hearingDevice->render_delay, + &hearingDevice->preparation_delay, &hearingDevice->codecs)) { + log::debug("Reading read only properties 0x{:x}", charac.value_handle); + BtaGattQueue::ReadCharacteristic(conn_id, charac.value_handle, + HearingAidImpl::OnReadOnlyPropertiesReadStatic, nullptr); } } else if (charac.uuid == AUDIO_CONTROL_POINT_UUID) { hearingDevice->audio_control_point_handle = charac.value_handle; @@ -871,8 +819,7 @@ class HearingAidImpl : public HearingAid { } else if (charac.uuid == AUDIO_STATUS_UUID) { hearingDevice->audio_status_handle = charac.value_handle; - hearingDevice->audio_status_ccc_handle = - find_ccc_handle(conn_id, charac.value_handle); + hearingDevice->audio_status_ccc_handle = find_ccc_handle(conn_id, charac.value_handle); if (!hearingDevice->audio_status_ccc_handle) { log::error("cannot find Audio Status CCC descriptor"); continue; @@ -898,16 +845,13 @@ class HearingAidImpl : public HearingAid { void ReadPSM(HearingDevice* hearingDevice) { if (hearingDevice->read_psm_handle) { - log::info("bd_addr={} handle=0x{:x}", hearingDevice->address, - hearingDevice->read_psm_handle); - BtaGattQueue::ReadCharacteristic( - hearingDevice->conn_id, hearingDevice->read_psm_handle, - HearingAidImpl::OnPsmReadStatic, nullptr); + log::info("bd_addr={} handle=0x{:x}", hearingDevice->address, hearingDevice->read_psm_handle); + BtaGattQueue::ReadCharacteristic(hearingDevice->conn_id, hearingDevice->read_psm_handle, + HearingAidImpl::OnPsmReadStatic, nullptr); } } - void OnNotificationEvent(uint16_t conn_id, uint16_t handle, uint16_t len, - uint8_t* value) { + void OnNotificationEvent(uint16_t conn_id, uint16_t handle, uint16_t len, uint8_t* value) { HearingDevice* device = hearingDevices.FindByConnId(conn_id); if (!device) { log::error("unknown device: conn_id=0x{:x}", conn_id); @@ -915,33 +859,28 @@ class HearingAidImpl : public HearingAid { } if (device->audio_status_handle != handle) { - log::warn( - "unexpected handle: bd_addr={} audio_status_handle=0x{:x}" - " handle=0x{:x}", - device->address, device->audio_status_handle, handle); + log::warn("unexpected handle: bd_addr={} audio_status_handle=0x{:x} handle=0x{:x}", + device->address, device->audio_status_handle, handle); return; } if (len < 1) { - log::warn("invalid data length (expected 1+ bytes): bd_addr={} len={}", - device->address, len); + log::warn("invalid data length (expected 1+ bytes): bd_addr={} len={}", device->address, len); return; } if (value[0] != 0) { - log::warn("received error status: bd_addr={} status=0x{:x}", - device->address, value[0]); + log::warn("received error status: bd_addr={} status=0x{:x}", device->address, value[0]); return; } - log::info("received success notification: bd_addr={} command_acked={}", - device->address, device->command_acked); + log::info("received success notification: bd_addr={} command_acked={}", device->address, + device->command_acked); device->command_acked = true; } - void OnReadOnlyPropertiesRead(uint16_t conn_id, tGATT_STATUS status, - uint16_t handle, uint16_t len, uint8_t* value, - void* data) { + void OnReadOnlyPropertiesRead(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, + uint16_t len, uint8_t* value, void* data) { HearingDevice* hearingDevice = hearingDevices.FindByConnId(conn_id); if (!hearingDevice) { log::error("unknown device: conn_id=0x{:x}", conn_id); @@ -954,8 +893,7 @@ class HearingAidImpl : public HearingAid { STREAM_TO_UINT8(version, p); if (version != 0x01) { - log::warn("unsupported version: bd_addr={} version=0x{:x}", - hearingDevice->address, version); + log::warn("unsupported version: bd_addr={} version=0x{:x}", hearingDevice->address, version); return; } @@ -984,31 +922,27 @@ class HearingAidImpl : public HearingAid { bool csis_capable = capabilities & CAPABILITY_CSIS; if (capabilities & CAPABILITY_RESERVED) { - log::warn( - "reserved capabilities bits are set: bd_addr={} capabilities=0x{:x}", - hearingDevice->address, capabilities); + log::warn("reserved capabilities bits are set: bd_addr={} capabilities=0x{:x}", + hearingDevice->address, capabilities); } bool g722_16khz_supported = codecs & (1 << CODEC_G722_16KHZ); bool g722_24khz_supported = codecs & (1 << CODEC_G722_24KHZ); if (!g722_16khz_supported) { - log::warn("mandatory codec G722@16kHz not supported: bd_addr={}", - hearingDevice->address); + log::warn("mandatory codec G722@16kHz not supported: bd_addr={}", hearingDevice->address); } log::info( - "device capabilities: bd_addr={} side={} binaural={}" - " CSIS_supported={} hi_sync_id=0x{:x} render_delay={}" - " preparation_delay={} G722@16kHz_supported={} G722@24kHz_supported={}", - hearingDevice->address, side ? "right" : "left", binaural, csis_capable, - hearingDevice->hi_sync_id, hearingDevice->render_delay, - hearingDevice->preparation_delay, g722_16khz_supported, - g722_24khz_supported); + "device capabilities: bd_addr={} side={} binaural={}" + " CSIS_supported={} hi_sync_id=0x{:x} render_delay={}" + " preparation_delay={} G722@16kHz_supported={} G722@24kHz_supported={}", + hearingDevice->address, side ? "right" : "left", binaural, csis_capable, + hearingDevice->hi_sync_id, hearingDevice->render_delay, + hearingDevice->preparation_delay, g722_16khz_supported, g722_24khz_supported); } - uint16_t CalcCompressedAudioPacketSize(uint16_t codec_type, - int connection_interval) { + uint16_t CalcCompressedAudioPacketSize(uint16_t codec_type, int connection_interval) { int sample_rate; const int sample_bit_rate = 16; /* 16 bits per sample */ @@ -1022,20 +956,22 @@ class HearingAidImpl : public HearingAid { // compressed_data_packet_size is the size in bytes of the compressed audio // data buffer that is generated for each connection interval. uint32_t compressed_data_packet_size = - (sample_rate * connection_interval * (sample_bit_rate / 8) / - compression_ratio) / - 1000; - return ((uint16_t)compressed_data_packet_size); + (sample_rate * connection_interval * (sample_bit_rate / 8) / compression_ratio) / 1000; + return (uint16_t)compressed_data_packet_size; } void ChooseCodec(const HearingDevice& hearingDevice) { - if (codec_in_use) return; + if (codec_in_use) { + return; + } // use the best codec available for this pair of devices. uint16_t codecs = hearingDevice.codecs; if (hearingDevice.hi_sync_id != 0) { for (const auto& device : hearingDevices.devices) { - if (device.hi_sync_id != hearingDevice.hi_sync_id) continue; + if (device.hi_sync_id != hearingDevice.hi_sync_id) { + continue; + } codecs &= device.codecs; } @@ -1050,13 +986,13 @@ class HearingAidImpl : public HearingAid { } } - void OnAudioStatus(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, - uint16_t len, uint8_t* value, void* data) { + void OnAudioStatus(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, uint16_t len, + uint8_t* value, void* data) { log::info("{}", base::HexEncode(value, len)); } - void OnPsmRead(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, - uint16_t len, uint8_t* value, void* data) { + void OnPsmRead(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, uint16_t len, + uint8_t* value, void* data) { HearingDevice* hearingDevice = hearingDevices.FindByConnId(conn_id); if (!hearingDevice) { log::error("unknown device: conn_id=0x{:x}", conn_id); @@ -1064,14 +1000,12 @@ class HearingAidImpl : public HearingAid { } if (status != GATT_SUCCESS) { - log::error("error reading PSM: bd_addr={} status={}", - hearingDevice->address, status); + log::error("error reading PSM: bd_addr={} status={}", hearingDevice->address, status); return; } if (len < 2) { - log::error("invalid PSM length: bd_addr={} len={}", - hearingDevice->address, len); + log::error("invalid PSM length: bd_addr={} len={}", hearingDevice->address, len); return; } @@ -1093,54 +1027,50 @@ class HearingAidImpl : public HearingAid { SendEnableServiceChangedInd(hearingDevice); - uint8_t service_id = hearingDevice->isLeft() - ? BTM_SEC_SERVICE_HEARING_AID_LEFT - : BTM_SEC_SERVICE_HEARING_AID_RIGHT; + uint8_t service_id = hearingDevice->isLeft() ? BTM_SEC_SERVICE_HEARING_AID_LEFT + : BTM_SEC_SERVICE_HEARING_AID_RIGHT; uint16_t gap_handle = GAP_ConnOpen( - "", service_id, false, &hearingDevice->address, psm, 514 /* MPS */, - &cfg_info, nullptr, - /// b/309483354: - /// Encryption needs to be explicitly requested at channel - /// establishment even though validation is performed in this module - /// because of re-connection logic present in the L2CAP module. - /// The L2CAP will automatically reconnect the LE-ACL link on - /// disconnection when there is a pending channel request, - /// which invalidates all encryption checks performed here. - com::android::bluetooth::flags::asha_encrypted_l2c_coc() - ? BTM_SEC_IN_ENCRYPT | BTM_SEC_OUT_ENCRYPT - : BTM_SEC_NONE, - HearingAidImpl::GapCallbackStatic, BT_TRANSPORT_LE); + "", service_id, false, &hearingDevice->address, psm, 514 /* MPS */, &cfg_info, nullptr, + /// b/309483354: + /// Encryption needs to be explicitly requested at channel + /// establishment even though validation is performed in this module + /// because of re-connection logic present in the L2CAP module. + /// The L2CAP will automatically reconnect the LE-ACL link on + /// disconnection when there is a pending channel request, + /// which invalidates all encryption checks performed here. + com::android::bluetooth::flags::asha_encrypted_l2c_coc() + ? BTM_SEC_IN_ENCRYPT | BTM_SEC_OUT_ENCRYPT + : BTM_SEC_NONE, + HearingAidImpl::GapCallbackStatic, BT_TRANSPORT_LE); if (gap_handle == GAP_INVALID_HANDLE) { log::error("failed to open socket: bd_addr={}", hearingDevice->address); } else { hearingDevice->gap_handle = gap_handle; - log::info("sent GAP connect request: bd_addr={}, gap_handle={}", - hearingDevice->address, gap_handle); + log::info("sent GAP connect request: bd_addr={}, gap_handle={}", hearingDevice->address, + gap_handle); } } - static void OnReadOnlyPropertiesReadStatic(uint16_t conn_id, - tGATT_STATUS status, - uint16_t handle, uint16_t len, - uint8_t* value, void* data) { - if (instance) - instance->OnReadOnlyPropertiesRead(conn_id, status, handle, len, value, - data); + static void OnReadOnlyPropertiesReadStatic(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, + uint16_t len, uint8_t* value, void* data) { + if (instance) { + instance->OnReadOnlyPropertiesRead(conn_id, status, handle, len, value, data); + } } - static void OnAudioStatusStatic(uint16_t conn_id, tGATT_STATUS status, - uint16_t handle, uint16_t len, uint8_t* value, - void* data) { - if (instance) + static void OnAudioStatusStatic(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, + uint16_t len, uint8_t* value, void* data) { + if (instance) { instance->OnAudioStatus(conn_id, status, handle, len, value, data); + } } - static void OnPsmReadStatic(uint16_t conn_id, tGATT_STATUS status, - uint16_t handle, uint16_t len, uint8_t* value, - void* data) { - if (instance) + static void OnPsmReadStatic(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, uint16_t len, + uint8_t* value, void* data) { + if (instance) { instance->OnPsmRead(conn_id, status, handle, len, value, data); + } } /* CoC Socket, BLE connection parameter are ready */ @@ -1161,13 +1091,11 @@ class HearingAidImpl : public HearingAid { /* Register and enable the Audio Status Notification */ tGATT_STATUS register_status = BTA_GATTC_RegisterForNotifications( - gatt_if, address, hearingDevice->audio_status_handle); + gatt_if, address, hearingDevice->audio_status_handle); if (register_status != GATT_SUCCESS) { - log::error( - "failed to register for notifications:" - " bd_addr={} status={} handle=0x{:x}", - address, register_status, hearingDevice->audio_status_handle); + log::error("failed to register for notifications: bd_addr={} status={} handle=0x{:x}", + address, register_status, hearingDevice->audio_status_handle); return; } @@ -1175,9 +1103,8 @@ class HearingAidImpl : public HearingAid { uint8_t* ptr = value.data(); UINT16_TO_STREAM(ptr, GATT_CHAR_CLIENT_CONFIG_NOTIFICATION); - BtaGattQueue::WriteDescriptor( - hearingDevice->conn_id, hearingDevice->audio_status_ccc_handle, - std::move(value), GATT_WRITE, write_rpt_ctl_cfg_cb, nullptr); + BtaGattQueue::WriteDescriptor(hearingDevice->conn_id, hearingDevice->audio_status_ccc_handle, + std::move(value), GATT_WRITE, write_rpt_ctl_cfg_cb, nullptr); ChooseCodec(*hearingDevice); SendStart(hearingDevice); @@ -1185,7 +1112,7 @@ class HearingAidImpl : public HearingAid { if (audio_running) { // Inform the other side (if any) of this connection std::vector inform_conn_state( - {CONTROL_POINT_OP_STATE_CHANGE, STATE_CHANGE_OTHER_SIDE_CONNECTED}); + {CONTROL_POINT_OP_STATE_CHANGE, STATE_CHANGE_OTHER_SIDE_CONNECTED}); send_state_change_to_other_side(hearingDevice, inform_conn_state); } @@ -1193,8 +1120,7 @@ class HearingAidImpl : public HearingAid { hearingDevice->accepting_audio = true; StartSendingAudio(*hearingDevice); - callbacks->OnDeviceAvailable(hearingDevice->capabilities, - hearingDevice->hi_sync_id, address); + callbacks->OnDeviceAvailable(hearingDevice->capabilities, hearingDevice->hi_sync_id, address); callbacks->OnConnectionState(ConnectionState::CONNECTED, address); } @@ -1216,9 +1142,8 @@ class HearingAidImpl : public HearingAid { uint16_t delay_report_ms = 0; if (hearingDevice.render_delay != 0) { - delay_report_ms = - hearingDevice.render_delay + - (ADD_RENDER_DELAY_INTERVALS * default_data_interval_ms); + delay_report_ms = hearingDevice.render_delay + + (ADD_RENDER_DELAY_INTERVALS * default_data_interval_ms); } HearingAidAudioSource::Start(codec, audioReceiver, delay_report_ms); @@ -1242,18 +1167,18 @@ class HearingAidImpl : public HearingAid { std::vector stop({CONTROL_POINT_OP_STOP}); for (auto& device : hearingDevices.devices) { - if (!device.accepting_audio) continue; + if (!device.accepting_audio) { + continue; + } if (!device.playback_started) { - log::warn("Playback not started, skip send Stop cmd, bd_addr={}", - device.address); + log::warn("Playback not started, skip send Stop cmd, bd_addr={}", device.address); } else { log::info("send Stop cmd, bd_addr={}", device.address); device.playback_started = false; device.command_acked = false; - BtaGattQueue::WriteCharacteristic(device.conn_id, - device.audio_control_point_handle, - stop, GATT_WRITE, nullptr, nullptr); + BtaGattQueue::WriteCharacteristic(device.conn_id, device.audio_control_point_handle, stop, + GATT_WRITE, nullptr, nullptr); } } } @@ -1268,7 +1193,9 @@ class HearingAidImpl : public HearingAid { } for (auto& device : hearingDevices.devices) { - if (!device.accepting_audio) continue; + if (!device.accepting_audio) { + continue; + } audio_running = true; SendStart(&device); } @@ -1296,12 +1223,12 @@ class HearingAidImpl : public HearingAid { continue; } if (audio_running && (device.conn_id != 0)) { - return (OTHER_SIDE_IS_STREAMING); + return OTHER_SIDE_IS_STREAMING; } else { - return (OTHER_SIDE_NOT_STREAMING); + return OTHER_SIDE_NOT_STREAMING; } } - return (OTHER_SIDE_NOT_STREAMING); + return OTHER_SIDE_NOT_STREAMING; } void SendEnableServiceChangedInd(HearingDevice* device) { @@ -1311,49 +1238,44 @@ class HearingAidImpl : public HearingAid { uint8_t* ptr = value.data(); UINT16_TO_STREAM(ptr, GATT_CHAR_CLIENT_CONFIG_INDICTION); - BtaGattQueue::WriteDescriptor( - device->conn_id, device->service_changed_ccc_handle, std::move(value), - GATT_WRITE, nullptr, nullptr); + BtaGattQueue::WriteDescriptor(device->conn_id, device->service_changed_ccc_handle, + std::move(value), GATT_WRITE, nullptr, nullptr); } void SendStart(HearingDevice* device) { - std::vector start({CONTROL_POINT_OP_START, codec_in_use, - AUDIOTYPE_UNKNOWN, (uint8_t)current_volume, - OTHER_SIDE_NOT_STREAMING}); + std::vector start({CONTROL_POINT_OP_START, codec_in_use, AUDIOTYPE_UNKNOWN, + (uint8_t)current_volume, OTHER_SIDE_NOT_STREAMING}); if (!audio_running) { if (!device->playback_started) { - log::info("Skip Send Start since audio is not running, bd_addr={}", - device->address); + log::info("Skip Send Start since audio is not running, bd_addr={}", device->address); } else { - log::error("Audio not running but Playback has started, bd_addr={}", - device->address); + log::error("Audio not running but Playback has started, bd_addr={}", device->address); } return; } - if (current_volume == VOLUME_UNKNOWN) start[3] = (uint8_t)VOLUME_MIN; + if (current_volume == VOLUME_UNKNOWN) { + start[3] = (uint8_t)VOLUME_MIN; + } if (device->playback_started) { - log::error("Playback already started, skip send Start cmd, bd_addr={}", - device->address); + log::error("Playback already started, skip send Start cmd, bd_addr={}", device->address); } else { start[4] = GetOtherSideStreamStatus(device); log::info( - "send Start cmd, volume=0x{:x}, audio type=0x{:x}, bd_addr={}, other " - "side streaming=0x{:x}", - start[3], start[2], device->address, start[4]); + "send Start cmd, volume=0x{:x}, audio type=0x{:x}, bd_addr={}, other " + "side streaming=0x{:x}", + start[3], start[2], device->address, start[4]); device->command_acked = false; - BtaGattQueue::WriteCharacteristic( - device->conn_id, device->audio_control_point_handle, start, - GATT_WRITE, HearingAidImpl::StartAudioCtrlCallbackStatic, nullptr); + BtaGattQueue::WriteCharacteristic(device->conn_id, device->audio_control_point_handle, start, + GATT_WRITE, HearingAidImpl::StartAudioCtrlCallbackStatic, + nullptr); } } - static void StartAudioCtrlCallbackStatic(uint16_t conn_id, - tGATT_STATUS status, uint16_t handle, - uint16_t len, const uint8_t* value, - void* data) { + static void StartAudioCtrlCallbackStatic(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, + uint16_t len, const uint8_t* value, void* data) { if (status != GATT_SUCCESS) { log::error("handle={}, conn_id={}, status=0x{:x}", handle, conn_id, static_cast(status)); @@ -1394,14 +1316,14 @@ class HearingAidImpl : public HearingAid { uint16_t diff_credit = 0; uint16_t target_current_credit = L2CA_GetPeerLECocCredit( - target_side->address, GAP_ConnGetL2CAPCid(target_side->gap_handle)); + target_side->address, GAP_ConnGetL2CAPCid(target_side->gap_handle)); if (target_current_credit == L2CAP_LE_CREDIT_MAX) { log::error("Get target side credit value fail."); return true; } uint16_t other_current_credit = L2CA_GetPeerLECocCredit( - other_side->address, GAP_ConnGetL2CAPCid(other_side->gap_handle)); + other_side->address, GAP_ConnGetL2CAPCid(other_side->gap_handle)); if (other_current_credit == L2CAP_LE_CREDIT_MAX) { log::error("Get other side credit value fail."); return true; @@ -1412,9 +1334,8 @@ class HearingAidImpl : public HearingAid { } else { diff_credit = other_current_credit - target_current_credit; } - log::debug("Target({}) Credit: {}, Other({}) Credit: {}, Init Credit: {}", - target_side->address, target_current_credit, other_side->address, - other_current_credit, init_credit); + log::debug("Target({}) Credit: {}, Other({}) Credit: {}, Init Credit: {}", target_side->address, + target_current_credit, other_side->address, other_current_credit, init_credit); return diff_credit < (init_credit / 2 - 1); } @@ -1431,24 +1352,27 @@ class HearingAidImpl : public HearingAid { void OnAudioDataReady(const std::vector& data) { /* For now we assume data comes in as 16bit per sample 16kHz PCM stereo */ bool need_drop = false; - int num_samples = - data.size() / (2 /*bytes_per_sample*/ * 2 /*number of channels*/); + int num_samples = data.size() / (2 /*bytes_per_sample*/ * 2 /*number of channels*/); // The G.722 codec accept only even number of samples for encoding - if (num_samples % 2 != 0) + if (num_samples % 2 != 0) { log::fatal("num_samples is not even: {}", num_samples); + } - // TODO: we should cache left/right and current state, instad of recomputing + // TODO: we should cache left/right and current state, instead of recomputing // it for each packet, 100 times a second. HearingDevice* left = nullptr; HearingDevice* right = nullptr; for (auto& device : hearingDevices.devices) { - if (!device.accepting_audio) continue; + if (!device.accepting_audio) { + continue; + } - if (device.isLeft()) + if (device.isLeft()) { left = &device; - else + } else { right = &device; + } } if (left == nullptr && right == nullptr) { @@ -1515,9 +1439,8 @@ class HearingAidImpl : public HearingAid { // TODO: instead of a magic number, we need to figure out the correct // buffer size encoded_data_left.resize(4000); - int encoded_size = - g722_encode(encoder_state_left, encoded_data_left.data(), - (const int16_t*)chan_left.data(), chan_left.size()); + int encoded_size = g722_encode(encoder_state_left, encoded_data_left.data(), + (const int16_t*)chan_left.data(), chan_left.size()); encoded_data_left.resize(encoded_size); uint16_t cid = GAP_ConnGetL2CAPCid(left->gap_handle); @@ -1526,21 +1449,17 @@ class HearingAidImpl : public HearingAid { // Compare the two sides LE CoC credit value to confirm need to drop or // skip audio packet. if (NeedToDropPacket(left, right) && IsBelowDropFrequency(time_point)) { - log::info("{} triggers dropping, {} packets in channel", - left->address, packets_in_chans); + log::info("{} triggers dropping, {} packets in channel", left->address, packets_in_chans); need_drop = true; left->audio_stats.trigger_drop_count++; } else { log::info("{} skipping {} packets", left->address, packets_in_chans); left->audio_stats.packet_flush_count += packets_in_chans; left->audio_stats.frame_flush_count++; - const uint16_t buffers_left = - L2CA_FlushChannel(cid, L2CAP_FLUSH_CHANS_ALL); + const uint16_t buffers_left = L2CA_FlushChannel(cid, L2CAP_FLUSH_CHANS_ALL); if (buffers_left) { - log::warn( - "Unable to flush L2CAP ALL (left HA) channel peer:{} cid:{} " - "buffers_left:{}", - left->address, cid, buffers_left); + log::warn("Unable to flush L2CAP ALL (left HA) channel peer:{} cid:{} buffers_left:{}", + left->address, cid, buffers_left); } } hearingDevices.StartRssiLog(); @@ -1553,9 +1472,8 @@ class HearingAidImpl : public HearingAid { // TODO: instead of a magic number, we need to figure out the correct // buffer size encoded_data_right.resize(4000); - int encoded_size = - g722_encode(encoder_state_right, encoded_data_right.data(), - (const int16_t*)chan_right.data(), chan_right.size()); + int encoded_size = g722_encode(encoder_state_right, encoded_data_right.data(), + (const int16_t*)chan_right.data(), chan_right.size()); encoded_data_right.resize(encoded_size); uint16_t cid = GAP_ConnGetL2CAPCid(right->gap_handle); @@ -1564,21 +1482,18 @@ class HearingAidImpl : public HearingAid { // Compare the two sides LE CoC credit value to confirm need to drop or // skip audio packet. if (NeedToDropPacket(right, left) && IsBelowDropFrequency(time_point)) { - log::info("{} triggers dropping, {} packets in channel", - right->address, packets_in_chans); + log::info("{} triggers dropping, {} packets in channel", right->address, + packets_in_chans); need_drop = true; right->audio_stats.trigger_drop_count++; } else { log::info("{} skipping {} packets", right->address, packets_in_chans); right->audio_stats.packet_flush_count += packets_in_chans; right->audio_stats.frame_flush_count++; - const uint16_t buffers_left = - L2CA_FlushChannel(cid, L2CAP_FLUSH_CHANS_ALL); + const uint16_t buffers_left = L2CA_FlushChannel(cid, L2CAP_FLUSH_CHANS_ALL); if (buffers_left) { - log::warn( - "Unable to flush L2CAP ALL (right HA) channel peer:{} cid:{} " - "buffers_left:{}", - right->address, cid, buffers_left); + log::warn("Unable to flush L2CAP ALL (right HA) channel peer:{} cid:{} buffers_left:{}", + right->address, cid, buffers_left); } } hearingDevices.StartRssiLog(); @@ -1586,11 +1501,9 @@ class HearingAidImpl : public HearingAid { check_and_do_rssi_read(right); } - size_t encoded_data_size = - std::max(encoded_data_left.size(), encoded_data_right.size()); + size_t encoded_data_size = std::max(encoded_data_left.size(), encoded_data_right.size()); - uint16_t packet_size = - CalcCompressedAudioPacketSize(codec_in_use, default_data_interval_ms); + uint16_t packet_size = CalcCompressedAudioPacketSize(codec_in_use, default_data_interval_ms); if (need_drop) { last_drop_time_point = time_point; @@ -1614,16 +1527,18 @@ class HearingAidImpl : public HearingAid { } seq_counter++; } - if (left) left->audio_stats.frame_send_count++; - if (right) right->audio_stats.frame_send_count++; + if (left) { + left->audio_stats.frame_send_count++; + } + if (right) { + right->audio_stats.frame_send_count++; + } } - void SendAudio(uint8_t* encoded_data, uint16_t packet_size, - HearingDevice* hearingAid) { + void SendAudio(uint8_t* encoded_data, uint16_t packet_size, HearingDevice* hearingAid) { if (!hearingAid->playback_started || !hearingAid->command_acked) { - log::warn("Playback stalled: bd_addr={} cmd send={} cmd acked={}", - hearingAid->address, hearingAid->playback_started, - hearingAid->command_acked); + log::warn("Playback stalled: bd_addr={} cmd send={} cmd acked={}", hearingAid->address, + hearingAid->playback_started, hearingAid->command_acked); return; } @@ -1645,8 +1560,7 @@ class HearingAidImpl : public HearingAid { void GapCallback(uint16_t gap_handle, uint16_t event, tGAP_CB_DATA* data) { HearingDevice* hearingDevice = hearingDevices.FindByGapHandle(gap_handle); if (!hearingDevice) { - log::error("unknown device: gap_handle={} event=0x{:x}", gap_handle, - event); + log::error("unknown device: gap_handle={} event=0x{:x}", gap_handle, event); return; } @@ -1655,11 +1569,10 @@ class HearingAidImpl : public HearingAid { RawAddress address = *GAP_ConnGetRemoteAddr(gap_handle); uint16_t tx_mtu = GAP_ConnGetRemMtuSize(gap_handle); - init_credit = - L2CA_GetPeerLECocCredit(address, GAP_ConnGetL2CAPCid(gap_handle)); + init_credit = L2CA_GetPeerLECocCredit(address, GAP_ConnGetL2CAPCid(gap_handle)); - log::info("GAP_EVT_CONN_OPENED: bd_addr={} tx_mtu={} init_credit={}", - address, tx_mtu, init_credit); + log::info("GAP_EVT_CONN_OPENED: bd_addr={} tx_mtu={} init_credit={}", address, tx_mtu, + init_credit); HearingDevice* hearingDevice = hearingDevices.FindByAddress(address); if (!hearingDevice) { @@ -1674,8 +1587,8 @@ class HearingAidImpl : public HearingAid { } case GAP_EVT_CONN_CLOSED: - log::info("GAP_EVT_CONN_CLOSED: bd_addr={} accepting_audio={}", - hearingDevice->address, hearingDevice->accepting_audio); + log::info("GAP_EVT_CONN_CLOSED: bd_addr={} accepting_audio={}", hearingDevice->address, + hearingDevice->accepting_audio); if (!hearingDevice->accepting_audio) { /* Disconnect connection when data channel is not available */ @@ -1692,8 +1605,7 @@ class HearingAidImpl : public HearingAid { break; case GAP_EVT_CONN_DATA_AVAIL: { - log::verbose("GAP_EVT_CONN_DATA_AVAIL: bd_addr={}", - hearingDevice->address); + log::verbose("GAP_EVT_CONN_DATA_AVAIL: bd_addr={}", hearingDevice->address); // only data we receive back from hearing aids are some stats, not // really important, but useful now for debugging. @@ -1702,7 +1614,7 @@ class HearingAidImpl : public HearingAid { std::vector buffer(bytes_to_read); uint16_t bytes_read = 0; - // TODO:GAP_ConnReadData should accpet uint32_t for length! + // TODO:GAP_ConnReadData should accept uint32_t for length! GAP_ConnReadData(gap_handle, buffer.data(), buffer.size(), &bytes_read); if (bytes_read < 4) { @@ -1717,8 +1629,7 @@ class HearingAidImpl : public HearingAid { uint16_t event_counter, frame_index; STREAM_TO_UINT16(event_counter, p); STREAM_TO_UINT16(frame_index, p); - log::verbose("event_counter={} frame_index: {}", event_counter, - frame_index); + log::verbose("event_counter={} frame_index: {}", event_counter, frame_index); } break; } @@ -1739,27 +1650,25 @@ class HearingAidImpl : public HearingAid { break; case GAP_EVT_CONN_UNCONGESTED: - log::info("GAP_EVT_CONN_UNCONGESTED: bd_addr={}", - hearingDevice->address); + log::info("GAP_EVT_CONN_UNCONGESTED: bd_addr={}", hearingDevice->address); break; } } - static void GapCallbackStatic(uint16_t gap_handle, uint16_t event, - tGAP_CB_DATA* data) { - if (instance) instance->GapCallback(gap_handle, event, data); + static void GapCallbackStatic(uint16_t gap_handle, uint16_t event, tGAP_CB_DATA* data) { + if (instance) { + instance->GapCallback(gap_handle, event, data); + } } void DumpRssi(int fd, const HearingDevice& device) { const struct AudioStats* stats = &device.audio_stats; if (stats->rssi_history.size() <= 0) { - dprintf(fd, " No RSSI history for %s:\n", - ADDRESS_TO_LOGGABLE_CSTR(device.address)); + dprintf(fd, " No RSSI history for %s:\n", ADDRESS_TO_LOGGABLE_CSTR(device.address)); return; } - dprintf(fd, " RSSI history for %s:\n", - ADDRESS_TO_LOGGABLE_CSTR(device.address)); + dprintf(fd, " RSSI history for %s:\n", ADDRESS_TO_LOGGABLE_CSTR(device.address)); dprintf(fd, " Time of RSSI 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9\n"); for (auto& rssi_logs : stats->rssi_history) { @@ -1771,11 +1680,12 @@ class HearingAidImpl : public HearingAid { char temptime[20]; struct tm* tstamp = localtime(&rssi_logs.timestamp.tv_sec); if (!strftime(temptime, sizeof(temptime), "%H:%M:%S", tstamp)) { - log::error("strftime fails. tm_sec={}, tm_min={}, tm_hour={}", - tstamp->tm_sec, tstamp->tm_min, tstamp->tm_hour); + log::error("strftime fails. tm_sec={}, tm_min={}, tm_hour={}", tstamp->tm_sec, + tstamp->tm_min, tstamp->tm_hour); strlcpy(temptime, "UNKNOWN TIME", sizeof(temptime)); } - snprintf(eventtime, sizeof(eventtime), "%s.%03ld", temptime, rssi_logs.timestamp.tv_nsec / 1000000); + snprintf(eventtime, sizeof(eventtime), "%s.%03ld", temptime, + rssi_logs.timestamp.tv_nsec / 1000000); dprintf(fd, " %s: ", eventtime); @@ -1791,22 +1701,19 @@ class HearingAidImpl : public HearingAid { for (const auto& device : hearingDevices.devices) { bool side = device.capabilities & CAPABILITY_SIDE; bool standalone = device.capabilities & CAPABILITY_BINAURAL; - stream << " " << device.address.ToString() << " " - << (device.accepting_audio ? "" : "not ") << "connected" - << "\n " << (standalone ? "binaural" : "monaural") << " " - << (side ? "right" : "left") << " " << loghex(device.hi_sync_id) + stream << " " << device.address.ToString() << " " << (device.accepting_audio ? "" : "not ") + << "connected" << "\n " << (standalone ? "binaural" : "monaural") << " " + << (side ? "right" : "left") << " " << loghex(device.hi_sync_id) << std::endl; + stream << " Trigger dropped counts : " + << device.audio_stats.trigger_drop_count + << "\n Packet dropped counts : " + << device.audio_stats.packet_drop_count + << "\n Packet counts (send/flush) : " + << device.audio_stats.packet_send_count << " / " + << device.audio_stats.packet_flush_count + << "\n Frame counts (sent/flush) : " + << device.audio_stats.frame_send_count << " / " << device.audio_stats.frame_flush_count << std::endl; - stream - << " Trigger dropped counts : " - << device.audio_stats.trigger_drop_count - << "\n Packet dropped counts : " - << device.audio_stats.packet_drop_count - << "\n Packet counts (send/flush) : " - << device.audio_stats.packet_send_count << " / " - << device.audio_stats.packet_flush_count - << "\n Frame counts (sent/flush) : " - << device.audio_stats.frame_send_count << " / " - << device.audio_stats.frame_flush_count << std::endl; DumpRssi(fd, device); } @@ -1823,9 +1730,8 @@ class HearingAidImpl : public HearingAid { bool connected = hearingDevice->accepting_audio; bool connecting_by_user = hearingDevice->connecting_actively; - log::info("bd_addr={} playback_started={} accepting_audio={}", - hearingDevice->address, hearingDevice->playback_started, - hearingDevice->accepting_audio); + log::info("bd_addr={} playback_started={} accepting_audio={}", hearingDevice->address, + hearingDevice->playback_started, hearingDevice->accepting_audio); if (hearingDevice->connecting_actively) { // cancel pending direct connect @@ -1837,7 +1743,7 @@ class HearingAidImpl : public HearingAid { // Inform the other side (if any) of this disconnection std::vector inform_disconn_state( - {CONTROL_POINT_OP_STATE_CHANGE, STATE_CHANGE_OTHER_SIDE_DISCONNECTED}); + {CONTROL_POINT_OP_STATE_CHANGE, STATE_CHANGE_OTHER_SIDE_DISCONNECTED}); send_state_change_to_other_side(hearingDevice, inform_disconn_state); DoDisconnectCleanUp(hearingDevice); @@ -1856,19 +1762,19 @@ class HearingAidImpl : public HearingAid { /* Do remove device when the address is useless. */ hearingDevices.Remove(address); for (const auto& device : hearingDevices.devices) { - if (device.accepting_audio) return; + if (device.accepting_audio) { + return; + } } log::info("No more (0/{}) devices ready", GetDeviceCount()); DoDisconnectAudioStop(); } - void OnGattDisconnected(uint16_t conn_id, tGATT_IF client_if, - RawAddress remote_bda) { + void OnGattDisconnected(uint16_t conn_id, tGATT_IF client_if, RawAddress remote_bda) { HearingDevice* hearingDevice = hearingDevices.FindByConnId(conn_id); if (!hearingDevice) { - log::error("unknown device: conn_id=0x{:x} bd_addr={}", conn_id, - remote_bda); + log::error("unknown device: conn_id=0x{:x} bd_addr={}", conn_id, remote_bda); return; } @@ -1876,32 +1782,30 @@ class HearingAidImpl : public HearingAid { // Inform the other side (if any) of this disconnection std::vector inform_disconn_state( - {CONTROL_POINT_OP_STATE_CHANGE, STATE_CHANGE_OTHER_SIDE_DISCONNECTED}); + {CONTROL_POINT_OP_STATE_CHANGE, STATE_CHANGE_OTHER_SIDE_DISCONNECTED}); send_state_change_to_other_side(hearingDevice, inform_disconn_state); DoDisconnectCleanUp(hearingDevice); HearingDevice* other_connected_device_from_set = - hearingDevices.FindOtherConnectedDeviceFromSet(*hearingDevice); + hearingDevices.FindOtherConnectedDeviceFromSet(*hearingDevice); if (other_connected_device_from_set != nullptr) { log::info( - "Another device from the set is still connected, issuing a direct " - "connection, other_device_bda={}", - other_connected_device_from_set->address); + "Another device from the set is still connected, issuing a direct " + "connection, other_device_bda={}", + other_connected_device_from_set->address); } // If another device from the pair is still connected, do a direct // connection to scan more aggressively and connect as fast as possible - hearingDevice->connecting_actively = - other_connected_device_from_set != nullptr; + hearingDevice->connecting_actively = other_connected_device_from_set != nullptr; - auto connection_type = hearingDevice->connecting_actively - ? BTM_BLE_DIRECT_CONNECTION - : BTM_BLE_BKG_CONNECT_ALLOW_LIST; + auto connection_type = hearingDevice->connecting_actively ? BTM_BLE_DIRECT_CONNECTION + : BTM_BLE_BKG_CONNECT_ALLOW_LIST; hearingDevice->switch_to_background_connection_after_failure = - connection_type == BTM_BLE_DIRECT_CONNECTION; + connection_type == BTM_BLE_DIRECT_CONNECTION; // This is needed just for the first connection. After stack is restarted, // code that loads device will add them to acceptlist. @@ -1910,7 +1814,9 @@ class HearingAidImpl : public HearingAid { callbacks->OnConnectionState(ConnectionState::DISCONNECTED, remote_bda); for (const auto& device : hearingDevices.devices) { - if (device.accepting_audio) return; + if (device.accepting_audio) { + return; + } } log::info("No more (0/{}) devices ready", GetDeviceCount()); @@ -1920,8 +1826,7 @@ class HearingAidImpl : public HearingAid { void DoDisconnectCleanUp(HearingDevice* hearingDevice) { if (hearingDevice->connection_update_status != COMPLETED) { log::info("connection update not completed: status={}, bd_addr={}", - hearingDevice->connection_update_status, - hearingDevice->address); + hearingDevice->connection_update_status, hearingDevice->address); if (hearingDevice->connection_update_status == STARTED) { OnConnectionUpdateComplete(hearingDevice->conn_id, NULL); @@ -1960,12 +1865,13 @@ class HearingAidImpl : public HearingAid { log::debug("{}", volume); current_volume = volume; for (HearingDevice& device : hearingDevices.devices) { - if (!device.accepting_audio) continue; + if (!device.accepting_audio) { + continue; + } std::vector volume_value({static_cast(volume)}); - BtaGattQueue::WriteCharacteristic(device.conn_id, device.volume_handle, - volume_value, GATT_WRITE_NO_RSP, - nullptr, nullptr); + BtaGattQueue::WriteCharacteristic(device.conn_id, device.volume_handle, volume_value, + GATT_WRITE_NO_RSP, nullptr, nullptr); } } @@ -1980,7 +1886,7 @@ class HearingAidImpl : public HearingAid { encoder_state_release(); } - private: +private: uint8_t gatt_if; uint8_t seq_counter; /* current volume gain for the hearing aids*/ @@ -1996,8 +1902,7 @@ class HearingAidImpl : public HearingAid { HearingDevices hearingDevices; - void find_server_changed_ccc_handle(uint16_t conn_id, - const gatt::Service* service) { + void find_server_changed_ccc_handle(uint16_t conn_id, const gatt::Service* service) { HearingDevice* hearingDevice = hearingDevices.FindByConnId(conn_id); if (!hearingDevice) { log::error("unknown device: conn_id=0x{:x}", conn_id); @@ -2006,16 +1911,13 @@ class HearingAidImpl : public HearingAid { for (const gatt::Characteristic& charac : service->characteristics) { if (charac.uuid == Uuid::From16Bit(GATT_UUID_GATT_SRV_CHGD)) { - hearingDevice->service_changed_ccc_handle = - find_ccc_handle(conn_id, charac.value_handle); + hearingDevice->service_changed_ccc_handle = find_ccc_handle(conn_id, charac.value_handle); if (!hearingDevice->service_changed_ccc_handle) { - log::error( - "failed to find service changed CCC descriptor: bd_addr={}", - hearingDevice->address); + log::error("failed to find service changed CCC descriptor: bd_addr={}", + hearingDevice->address); continue; } - log::info("bd_addr={} service_changed_ccc=0x{:x}", - hearingDevice->address, + log::info("bd_addr={} service_changed_ccc=0x{:x}", hearingDevice->address, hearingDevice->service_changed_ccc_handle); break; } @@ -2025,8 +1927,7 @@ class HearingAidImpl : public HearingAid { // Find the handle for the client characteristics configuration of a given // characteristics uint16_t find_ccc_handle(uint16_t conn_id, uint16_t char_handle) { - const gatt::Characteristic* p_char = - BTA_GATTC_GetCharacteristic(conn_id, char_handle); + const gatt::Characteristic* p_char = BTA_GATTC_GetCharacteristic(conn_id, char_handle); if (!p_char) { log::warn("No such characteristic: {}", char_handle); @@ -2034,8 +1935,9 @@ class HearingAidImpl : public HearingAid { } for (const gatt::Descriptor& desc : p_char->descriptors) { - if (desc.uuid == Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)) + if (desc.uuid == Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)) { return desc.handle; + } } return 0; @@ -2044,16 +1946,13 @@ class HearingAidImpl : public HearingAid { void send_state_change(HearingDevice* device, std::vector payload) { if (device->conn_id != 0) { if (device->service_changed_rcvd) { - log::info( - "service discover is in progress, skip send State Change cmd."); + log::info("service discover is in progress, skip send State Change cmd."); return; } // Send the data packet - log::info("Send State Change: bd_addr={} status=0x{:x}", device->address, - payload[1]); - BtaGattQueue::WriteCharacteristic( - device->conn_id, device->audio_control_point_handle, payload, - GATT_WRITE_NO_RSP, nullptr, nullptr); + log::info("Send State Change: bd_addr={} status=0x{:x}", device->address, payload[1]); + BtaGattQueue::WriteCharacteristic(device->conn_id, device->audio_control_point_handle, + payload, GATT_WRITE_NO_RSP, nullptr, nullptr); } } @@ -2083,16 +1982,19 @@ class HearingAidImpl : public HearingAid { static void read_rssi_callback(void* p_void) { tBTM_RSSI_RESULT* p_result = (tBTM_RSSI_RESULT*)p_void; - if (!p_result) return; + if (!p_result) { + return; + } if ((instance) && (p_result->status == BTM_SUCCESS)) { instance->OnReadRssiComplete(p_result->rem_bda, p_result->rssi); } } -static void hearingaid_gattc_callback(tBTA_GATTC_EVT event, - tBTA_GATTC* p_data) { - if (p_data == nullptr) return; +static void hearingaid_gattc_callback(tBTA_GATTC_EVT event, tBTA_GATTC* p_data) { + if (p_data == nullptr) { + return; + } switch (event) { case BTA_GATTC_DEREG_EVT: @@ -2100,60 +2002,74 @@ static void hearingaid_gattc_callback(tBTA_GATTC_EVT event, break; case BTA_GATTC_OPEN_EVT: { - if (!instance) return; + if (!instance) { + return; + } tBTA_GATTC_OPEN& o = p_data->open; - instance->OnGattConnected(o.status, o.conn_id, o.client_if, o.remote_bda, - o.transport, o.mtu); + instance->OnGattConnected(o.status, o.conn_id, o.client_if, o.remote_bda, o.transport, o.mtu); break; } case BTA_GATTC_CLOSE_EVT: { - if (!instance) return; + if (!instance) { + return; + } tBTA_GATTC_CLOSE& c = p_data->close; instance->OnGattDisconnected(c.conn_id, c.client_if, c.remote_bda); } break; case BTA_GATTC_SEARCH_CMPL_EVT: - if (!instance) return; - instance->OnServiceSearchComplete(p_data->search_cmpl.conn_id, - p_data->search_cmpl.status); + if (!instance) { + return; + } + instance->OnServiceSearchComplete(p_data->search_cmpl.conn_id, p_data->search_cmpl.status); break; case BTA_GATTC_NOTIF_EVT: - if (!instance) return; + if (!instance) { + return; + } if (!p_data->notify.is_notify || p_data->notify.len > GATT_MAX_ATTR_LEN) { - log::error("rejected BTA_GATTC_NOTIF_EVT. is_notify={}, len={}", - p_data->notify.is_notify, p_data->notify.len); + log::error("rejected BTA_GATTC_NOTIF_EVT. is_notify={}, len={}", p_data->notify.is_notify, + p_data->notify.len); break; } - instance->OnNotificationEvent(p_data->notify.conn_id, - p_data->notify.handle, p_data->notify.len, - p_data->notify.value); + instance->OnNotificationEvent(p_data->notify.conn_id, p_data->notify.handle, + p_data->notify.len, p_data->notify.value); break; case BTA_GATTC_ENC_CMPL_CB_EVT: - if (!instance) return; - instance->OnEncryptionComplete( - p_data->enc_cmpl.remote_bda, - BTM_IsEncrypted(p_data->enc_cmpl.remote_bda, BT_TRANSPORT_LE)); + if (!instance) { + return; + } + instance->OnEncryptionComplete(p_data->enc_cmpl.remote_bda, + BTM_IsEncrypted(p_data->enc_cmpl.remote_bda, BT_TRANSPORT_LE)); break; case BTA_GATTC_CONN_UPDATE_EVT: - if (!instance) return; + if (!instance) { + return; + } instance->OnConnectionUpdateComplete(p_data->conn_update.conn_id, p_data); break; case BTA_GATTC_SRVC_CHG_EVT: - if (!instance) return; + if (!instance) { + return; + } instance->OnServiceChangeEvent(p_data->remote_bda); break; case BTA_GATTC_SRVC_DISC_DONE_EVT: - if (!instance) return; + if (!instance) { + return; + } instance->OnServiceDiscDoneEvent(p_data->service_changed.remote_bda); break; case BTA_GATTC_PHY_UPDATE_EVT: { - if (!instance) return; + if (!instance) { + return; + } tBTA_GATTC_PHY_UPDATE& p = p_data->phy_update; instance->OnPhyUpdateEvent(p.conn_id, p.tx_phy, p.rx_phy, p.status); break; @@ -2164,24 +2080,28 @@ static void hearingaid_gattc_callback(tBTA_GATTC_EVT event, } } -static void encryption_callback(RawAddress address, tBT_TRANSPORT, void*, - tBTM_STATUS status) { +static void encryption_callback(RawAddress address, tBT_TRANSPORT, void*, tBTM_STATUS status) { if (instance) { - instance->OnEncryptionComplete(address, - status == BTM_SUCCESS ? true : false); + instance->OnEncryptionComplete(address, status == BTM_SUCCESS ? true : false); } } class HearingAidAudioReceiverImpl : public HearingAidAudioReceiver { - public: +public: void OnAudioDataReady(const std::vector& data) override { - if (instance) instance->OnAudioDataReadyResample(data); + if (instance) { + instance->OnAudioDataReadyResample(data); + } } void OnAudioSuspend(const std::function& stop_audio_ticks) override { - if (instance) instance->OnAudioSuspend(stop_audio_ticks); + if (instance) { + instance->OnAudioSuspend(stop_audio_ticks); + } } void OnAudioResume(const std::function& start_audio_ticks) override { - if (instance) instance->OnAudioResume(start_audio_ticks); + if (instance) { + instance->OnAudioResume(start_audio_ticks); + } } }; @@ -2189,8 +2109,8 @@ HearingAidAudioReceiverImpl audioReceiverImpl; } // namespace -void HearingAid::Initialize( - bluetooth::hearing_aid::HearingAidCallbacks* callbacks, Closure initCb) { +void HearingAid::Initialize(bluetooth::hearing_aid::HearingAidCallbacks* callbacks, + Closure initCb) { std::scoped_lock lock(instance_mutex); if (instance) { log::error("Already initialized!"); @@ -2236,14 +2156,13 @@ void HearingAid::SetVolume(int8_t volume) { instance->SetVolume(volume); } -void HearingAid::AddFromStorage(const HearingDevice& dev_info, - bool is_acceptlisted) { +void HearingAid::AddFromStorage(const HearingDevice& dev_info, bool is_acceptlisted) { if (!instance) { log::error("Not initialized yet"); } instance->AddFromStorage(dev_info, is_acceptlisted); -}; +} int HearingAid::GetDeviceCount() { if (!instance) { @@ -2251,7 +2170,7 @@ int HearingAid::GetDeviceCount() { return 0; } - return (instance->GetDeviceCount()); + return instance->GetDeviceCount(); } void HearingAid::CleanUp() { @@ -2267,12 +2186,14 @@ void HearingAid::CleanUp() { ptr->CleanUp(); delete ptr; -}; +} void HearingAid::DebugDump(int fd) { std::scoped_lock lock(instance_mutex); dprintf(fd, "Hearing Aid Manager:\n"); - if (instance) instance->Dump(fd); + if (instance) { + instance->Dump(fd); + } HearingAidAudioSource::DebugDump(fd); dprintf(fd, "\n"); } diff --git a/system/bta/hearing_aid/hearing_aid_audio_source.cc b/system/bta/hearing_aid/hearing_aid_audio_source.cc index 6c5656cbaed..7f6535c681d 100644 --- a/system/bta/hearing_aid/hearing_aid_audio_source.cc +++ b/system/bta/hearing_aid/hearing_aid_audio_source.cc @@ -41,11 +41,9 @@ namespace fmt { template <> struct formatter : enum_formatter {}; template <> -struct formatter - : enum_formatter {}; +struct formatter : enum_formatter {}; template <> -struct formatter - : enum_formatter {}; +struct formatter : enum_formatter {}; } // namespace fmt namespace { @@ -99,8 +97,7 @@ bool hearing_aid_on_resume_req(bool start_media_task); bool hearing_aid_on_suspend_req(); void send_audio_data() { - uint32_t bytes_per_tick = - (num_channels * sample_rate * data_interval_ms * (bit_rate / 8)) / 1000; + uint32_t bytes_per_tick = (num_channels * sample_rate * data_interval_ms * (bit_rate / 8)) / 1000; uint8_t p_buf[bytes_per_tick]; @@ -108,16 +105,14 @@ void send_audio_data() { if (bluetooth::audio::hearing_aid::is_hal_enabled()) { bytes_read = bluetooth::audio::hearing_aid::read(p_buf, bytes_per_tick); } else { - bytes_read = UIPC_Read(*uipc_hearing_aid, UIPC_CH_ID_AV_AUDIO, p_buf, - bytes_per_tick); + bytes_read = UIPC_Read(*uipc_hearing_aid, UIPC_CH_ID_AV_AUDIO, p_buf, bytes_per_tick); } log::debug("bytes_read: {}", bytes_read); if (bytes_read < bytes_per_tick) { stats.media_read_total_underflow_bytes += bytes_per_tick - bytes_read; stats.media_read_total_underflow_count++; - stats.media_read_last_underflow_us = - bluetooth::common::time_get_os_boottime_us(); + stats.media_read_last_underflow_us = bluetooth::common::time_get_os_boottime_us(); } std::vector data(p_buf, p_buf + bytes_read); @@ -134,8 +129,7 @@ void hearing_aid_send_ack(tHEARING_AID_CTRL_ACK status) { } void start_audio_ticks() { - if (data_interval_ms != HA_INTERVAL_10_MS && - data_interval_ms != HA_INTERVAL_20_MS) { + if (data_interval_ms != HA_INTERVAL_10_MS && data_interval_ms != HA_INTERVAL_20_MS) { log::fatal("Unsupported data interval: {}", data_interval_ms); } @@ -161,8 +155,7 @@ void hearing_aid_data_cb(tUIPC_CH_ID, tUIPC_EVENT event) { * Read directly from media task from here on (keep callback for * connection events. */ - UIPC_Ioctl(*uipc_hearing_aid, UIPC_CH_ID_AV_AUDIO, - UIPC_REG_REMOVE_ACTIVE_READSET, NULL); + UIPC_Ioctl(*uipc_hearing_aid, UIPC_CH_ID_AV_AUDIO, UIPC_REG_REMOVE_ACTIVE_READSET, NULL); UIPC_Ioctl(*uipc_hearing_aid, UIPC_CH_ID_AV_AUDIO, UIPC_SET_READ_POLL_TMO, reinterpret_cast(0)); @@ -217,9 +210,7 @@ void hearing_aid_recv_ctrl_data() { case HEARING_AID_CTRL_CMD_STOP: if (!hearing_aid_on_suspend_req()) { - log::info( - "HEARING_AID_CTRL_CMD_STOP: hearing_aid_on_suspend_req() errs, but " - "ignored."); + log::info("HEARING_AID_CTRL_CMD_STOP: hearing_aid_on_suspend_req() errs, but ignored."); } hearing_aid_send_ack(HEARING_AID_CTRL_ACK_SUCCESS); break; @@ -266,14 +257,12 @@ void hearing_aid_recv_ctrl_data() { UIPC_Send(*uipc_hearing_aid, UIPC_CH_ID_AV_CTRL, 0, reinterpret_cast(&codec_capability.sample_rate), sizeof(btav_a2dp_codec_sample_rate_t)); - UIPC_Send( - *uipc_hearing_aid, UIPC_CH_ID_AV_CTRL, 0, - reinterpret_cast(&codec_capability.bits_per_sample), - sizeof(btav_a2dp_codec_bits_per_sample_t)); - UIPC_Send( - *uipc_hearing_aid, UIPC_CH_ID_AV_CTRL, 0, - reinterpret_cast(&codec_capability.channel_mode), - sizeof(btav_a2dp_codec_channel_mode_t)); + UIPC_Send(*uipc_hearing_aid, UIPC_CH_ID_AV_CTRL, 0, + reinterpret_cast(&codec_capability.bits_per_sample), + sizeof(btav_a2dp_codec_bits_per_sample_t)); + UIPC_Send(*uipc_hearing_aid, UIPC_CH_ID_AV_CTRL, 0, + reinterpret_cast(&codec_capability.channel_mode), + sizeof(btav_a2dp_codec_channel_mode_t)); break; } @@ -310,10 +299,9 @@ void hearing_aid_recv_ctrl_data() { break; } log::info( - "HEARING_AID_CTRL_SET_OUTPUT_AUDIO_CONFIG: sample_rate={}, " - "bits_per_sample={},channel_mode={}", - codec_config.sample_rate, codec_config.bits_per_sample, - codec_config.channel_mode); + "HEARING_AID_CTRL_SET_OUTPUT_AUDIO_CONFIG: sample_rate={}, " + "bits_per_sample={},channel_mode={}", + codec_config.sample_rate, codec_config.bits_per_sample, codec_config.channel_mode); break; } @@ -353,17 +341,13 @@ bool hearing_aid_on_resume_req(bool start_media_task) { bt_status_t status; if (start_media_task) { status = do_in_main_thread( - FROM_HERE, base::BindOnce(&HearingAidAudioReceiver::OnAudioResume, - base::Unretained(localAudioReceiver), - start_audio_ticks)); + FROM_HERE, base::BindOnce(&HearingAidAudioReceiver::OnAudioResume, + base::Unretained(localAudioReceiver), start_audio_ticks)); } else { - auto start_dummy_ticks = []() { - log::info("start_audio_ticks: waiting for data path opened"); - }; + auto start_dummy_ticks = []() { log::info("start_audio_ticks: waiting for data path opened"); }; status = do_in_main_thread( - FROM_HERE, base::BindOnce(&HearingAidAudioReceiver::OnAudioResume, - base::Unretained(localAudioReceiver), - start_dummy_ticks)); + FROM_HERE, base::BindOnce(&HearingAidAudioReceiver::OnAudioResume, + base::Unretained(localAudioReceiver), start_dummy_ticks)); } if (status != BT_STATUS_SUCCESS) { log::error("HEARING_AID_CTRL_CMD_START: do_in_main_thread err={}", status); @@ -378,12 +362,10 @@ bool hearing_aid_on_suspend_req() { return false; } bt_status_t status = do_in_main_thread( - FROM_HERE, - base::BindOnce(&HearingAidAudioReceiver::OnAudioSuspend, - base::Unretained(localAudioReceiver), stop_audio_ticks)); + FROM_HERE, base::BindOnce(&HearingAidAudioReceiver::OnAudioSuspend, + base::Unretained(localAudioReceiver), stop_audio_ticks)); if (status != BT_STATUS_SUCCESS) { - log::error("HEARING_AID_CTRL_CMD_SUSPEND: do_in_main_thread err={}", - status); + log::error("HEARING_AID_CTRL_CMD_SUSPEND: do_in_main_thread err={}", status); return false; } return true; @@ -421,8 +403,8 @@ void HearingAidAudioSource::Stop() { void HearingAidAudioSource::Initialize() { auto stream_cb = bluetooth::audio::hearing_aid::StreamCallbacks{ - .on_resume_ = hearing_aid_on_resume_req, - .on_suspend_ = hearing_aid_on_suspend_req, + .on_resume_ = hearing_aid_on_resume_req, + .on_suspend_ = hearing_aid_on_suspend_req, }; if (!bluetooth::audio::hearing_aid::init(stream_cb, get_main_thread())) { log::warn("Using legacy HAL"); @@ -450,10 +432,8 @@ void HearingAidAudioSource::DebugDump(int fd) { << stats.media_read_total_underflow_bytes << "\n Last update time ago in ms (underflow) : " << (stats.media_read_last_underflow_us > 0 - ? (unsigned long long)(now_us - - stats.media_read_last_underflow_us) / - 1000 - : 0) + ? (unsigned long long)(now_us - stats.media_read_last_underflow_us) / 1000 + : 0) << std::endl; dprintf(fd, "%s", stream.str().c_str()); } diff --git a/system/bta/hf_client/bta_hf_client_act.cc b/system/bta/hf_client/bta_hf_client_act.cc index 93952e4fad8..3a9585519a3 100644 --- a/system/bta/hf_client/bta_hf_client_act.cc +++ b/system/bta/hf_client/bta_hf_client_act.cc @@ -53,8 +53,7 @@ using namespace bluetooth; * ******************************************************************************/ void bta_hf_client_start_close(tBTA_HF_CLIENT_DATA* p_data) { - tBTA_HF_CLIENT_CB* client_cb = - bta_hf_client_find_cb_by_handle(p_data->hdr.layer_specific); + tBTA_HF_CLIENT_CB* client_cb = bta_hf_client_find_cb_by_handle(p_data->hdr.layer_specific); if (client_cb == NULL) { log::error("wrong handle to control block {}", p_data->hdr.layer_specific); return; @@ -62,11 +61,9 @@ void bta_hf_client_start_close(tBTA_HF_CLIENT_DATA* p_data) { /* Take the link out of sniff and set L2C idle time to 0 */ bta_dm_pm_active(client_cb->peer_addr); - if (!L2CA_SetIdleTimeoutByBdAddr(client_cb->peer_addr, 0, - BT_TRANSPORT_BR_EDR)) { - log::warn( - "Unable to set L2CAP idle timeout peer:{} transport:{} timeout:{}", - client_cb->peer_addr, bt_transport_text(BT_TRANSPORT_BR_EDR), 0); + if (!L2CA_SetIdleTimeoutByBdAddr(client_cb->peer_addr, 0, BT_TRANSPORT_BR_EDR)) { + log::warn("Unable to set L2CAP idle timeout peer:{} transport:{} timeout:{}", + client_cb->peer_addr, bt_transport_text(BT_TRANSPORT_BR_EDR), 0); } /* if SCO is open close SCO and wait on RFCOMM close */ @@ -91,8 +88,7 @@ void bta_hf_client_start_close(tBTA_HF_CLIENT_DATA* p_data) { * ******************************************************************************/ void bta_hf_client_start_open(tBTA_HF_CLIENT_DATA* p_data) { - tBTA_HF_CLIENT_CB* client_cb = - bta_hf_client_find_cb_by_handle(p_data->hdr.layer_specific); + tBTA_HF_CLIENT_CB* client_cb = bta_hf_client_find_cb_by_handle(p_data->hdr.layer_specific); if (client_cb == NULL) { log::error("wrong handle to control block {}", p_data->hdr.layer_specific); return; @@ -109,8 +105,7 @@ void bta_hf_client_start_open(tBTA_HF_CLIENT_DATA* p_data) { /* Let the incoming connection goes through. */ /* Issue collision for now. */ /* We will decide what to do when we find incoming connection later.*/ - bta_hf_client_collision_cback(BTA_SYS_CONN_OPEN, BTA_ID_HS, 0, - client_cb->peer_addr); + bta_hf_client_collision_cback(BTA_SYS_CONN_OPEN, BTA_ID_HS, 0, client_cb->peer_addr); return; } @@ -133,8 +128,7 @@ void bta_hf_client_start_open(tBTA_HF_CLIENT_DATA* p_data) { ******************************************************************************/ void bta_hf_client_rfc_open(tBTA_HF_CLIENT_DATA* p_data) { log::verbose(""); - tBTA_HF_CLIENT_CB* client_cb = - bta_hf_client_find_cb_by_handle(p_data->hdr.layer_specific); + tBTA_HF_CLIENT_CB* client_cb = bta_hf_client_find_cb_by_handle(p_data->hdr.layer_specific); if (client_cb == NULL) { log::error("cb not found for handle {}", p_data->hdr.layer_specific); return; @@ -158,8 +152,7 @@ void bta_hf_client_rfc_open(tBTA_HF_CLIENT_DATA* p_data) { ******************************************************************************/ void bta_hf_client_rfc_acp_open(tBTA_HF_CLIENT_DATA* p_data) { log::verbose(""); - tBTA_HF_CLIENT_CB* client_cb = - bta_hf_client_find_cb_by_handle(p_data->hdr.layer_specific); + tBTA_HF_CLIENT_CB* client_cb = bta_hf_client_find_cb_by_handle(p_data->hdr.layer_specific); if (client_cb == NULL) { log::error("cb not found for handle {}", p_data->hdr.layer_specific); return; @@ -211,8 +204,7 @@ void bta_hf_client_rfc_acp_open(tBTA_HF_CLIENT_DATA* p_data) { * ******************************************************************************/ void bta_hf_client_rfc_fail(tBTA_HF_CLIENT_DATA* p_data) { - tBTA_HF_CLIENT_CB* client_cb = - bta_hf_client_find_cb_by_handle(p_data->hdr.layer_specific); + tBTA_HF_CLIENT_CB* client_cb = bta_hf_client_find_cb_by_handle(p_data->hdr.layer_specific); if (client_cb == NULL) { log::error("cb not found for handle {}", p_data->hdr.layer_specific); return; @@ -240,8 +232,7 @@ void bta_hf_client_rfc_fail(tBTA_HF_CLIENT_DATA* p_data) { * ******************************************************************************/ void bta_hf_client_disc_fail(tBTA_HF_CLIENT_DATA* p_data) { - tBTA_HF_CLIENT_CB* client_cb = - bta_hf_client_find_cb_by_handle(p_data->hdr.layer_specific); + tBTA_HF_CLIENT_CB* client_cb = bta_hf_client_find_cb_by_handle(p_data->hdr.layer_specific); if (client_cb == NULL) { log::error("cb not found for handle {}", p_data->hdr.layer_specific); return; @@ -259,8 +250,7 @@ void bta_hf_client_disc_fail(tBTA_HF_CLIENT_DATA* p_data) { * ******************************************************************************/ void bta_hf_client_open_fail(tBTA_HF_CLIENT_DATA* p_data) { - tBTA_HF_CLIENT_CB* client_cb = - bta_hf_client_find_cb_by_handle(p_data->hdr.layer_specific); + tBTA_HF_CLIENT_CB* client_cb = bta_hf_client_find_cb_by_handle(p_data->hdr.layer_specific); if (client_cb == NULL) { log::error("cb not found for handle {}", p_data->hdr.layer_specific); return; @@ -278,8 +268,7 @@ void bta_hf_client_open_fail(tBTA_HF_CLIENT_DATA* p_data) { * ******************************************************************************/ void bta_hf_client_rfc_close(tBTA_HF_CLIENT_DATA* p_data) { - tBTA_HF_CLIENT_CB* client_cb = - bta_hf_client_find_cb_by_handle(p_data->hdr.layer_specific); + tBTA_HF_CLIENT_CB* client_cb = bta_hf_client_find_cb_by_handle(p_data->hdr.layer_specific); if (client_cb == NULL) { log::error("cb not found for handle {}", p_data->hdr.layer_specific); return; @@ -324,16 +313,14 @@ void bta_hf_client_disc_int_res(tBTA_HF_CLIENT_DATA* p_data) { uint16_t event = BTA_HF_CLIENT_DISC_FAIL_EVT; log::verbose("Status: {}", p_data->disc_result.status); - tBTA_HF_CLIENT_CB* client_cb = - bta_hf_client_find_cb_by_handle(p_data->hdr.layer_specific); + tBTA_HF_CLIENT_CB* client_cb = bta_hf_client_find_cb_by_handle(p_data->hdr.layer_specific); if (client_cb == NULL) { log::error("cb not found for handle {}", p_data->hdr.layer_specific); return; } /* if found service */ - if (p_data->disc_result.status == SDP_SUCCESS || - p_data->disc_result.status == SDP_DB_FULL) { + if (p_data->disc_result.status == SDP_SUCCESS || p_data->disc_result.status == SDP_DB_FULL) { /* get attributes */ if (bta_hf_client_sdp_find_attr(client_cb)) { event = BTA_HF_CLIENT_DISC_OK_EVT; @@ -358,16 +345,14 @@ void bta_hf_client_disc_int_res(tBTA_HF_CLIENT_DATA* p_data) { * ******************************************************************************/ void bta_hf_client_disc_acp_res(tBTA_HF_CLIENT_DATA* p_data) { - tBTA_HF_CLIENT_CB* client_cb = - bta_hf_client_find_cb_by_handle(p_data->hdr.layer_specific); + tBTA_HF_CLIENT_CB* client_cb = bta_hf_client_find_cb_by_handle(p_data->hdr.layer_specific); if (client_cb == NULL) { log::error("cb not found for handle {}", p_data->hdr.layer_specific); return; } /* if found service */ - if (p_data->disc_result.status == SDP_SUCCESS || - p_data->disc_result.status == SDP_DB_FULL) { + if (p_data->disc_result.status == SDP_SUCCESS || p_data->disc_result.status == SDP_DB_FULL) { /* get attributes */ bta_hf_client_sdp_find_attr(client_cb); } @@ -387,8 +372,7 @@ void bta_hf_client_disc_acp_res(tBTA_HF_CLIENT_DATA* p_data) { * ******************************************************************************/ void bta_hf_client_rfc_data(tBTA_HF_CLIENT_DATA* p_data) { - tBTA_HF_CLIENT_CB* client_cb = - bta_hf_client_find_cb_by_handle(p_data->hdr.layer_specific); + tBTA_HF_CLIENT_CB* client_cb = bta_hf_client_find_cb_by_handle(p_data->hdr.layer_specific); if (client_cb == NULL) { log::error("cb not found for handle {}", p_data->hdr.layer_specific); return; @@ -398,8 +382,8 @@ void bta_hf_client_rfc_data(tBTA_HF_CLIENT_DATA* p_data) { char buf[BTA_HF_CLIENT_RFC_READ_MAX]; memset(buf, 0, sizeof(buf)); /* read data from rfcomm; if bad status, we're done */ - while (PORT_ReadData(client_cb->conn_handle, buf, BTA_HF_CLIENT_RFC_READ_MAX, - &len) == PORT_SUCCESS) { + while (PORT_ReadData(client_cb->conn_handle, buf, BTA_HF_CLIENT_RFC_READ_MAX, &len) == + PORT_SUCCESS) { /* if no data, we're done */ if (len == 0) { break; @@ -426,8 +410,7 @@ void bta_hf_client_rfc_data(tBTA_HF_CLIENT_DATA* p_data) { ******************************************************************************/ void bta_hf_client_svc_conn_open(tBTA_HF_CLIENT_DATA* p_data) { log::verbose(""); - tBTA_HF_CLIENT_CB* client_cb = - bta_hf_client_find_cb_by_handle(p_data->hdr.layer_specific); + tBTA_HF_CLIENT_CB* client_cb = bta_hf_client_find_cb_by_handle(p_data->hdr.layer_specific); if (client_cb == NULL) { log::error("cb not found for handle {}", p_data->hdr.layer_specific); return; diff --git a/system/bta/hf_client/bta_hf_client_api.cc b/system/bta/hf_client/bta_hf_client_api.cc index d4730473a7f..93da47501c7 100644 --- a/system/bta/hf_client/bta_hf_client_api.cc +++ b/system/bta/hf_client/bta_hf_client_api.cc @@ -60,8 +60,7 @@ using namespace bluetooth; * Returns BTA_SUCCESS if OK, BTA_FAILURE otherwise. * ******************************************************************************/ -tBTA_STATUS BTA_HfClientEnable(tBTA_HF_CLIENT_CBACK* p_cback, - tBTA_HF_CLIENT_FEAT features, +tBTA_STATUS BTA_HfClientEnable(tBTA_HF_CLIENT_CBACK* p_cback, tBTA_HF_CLIENT_FEAT features, const char* p_service_name) { return bta_hf_client_api_enable(p_cback, features, p_service_name); } @@ -90,7 +89,7 @@ void BTA_HfClientDisable(void) { bta_hf_client_api_disable(); } bt_status_t BTA_HfClientOpen(const RawAddress& bd_addr, uint16_t* p_handle) { log::verbose(""); tBTA_HF_CLIENT_API_OPEN* p_buf = - (tBTA_HF_CLIENT_API_OPEN*)osi_malloc(sizeof(tBTA_HF_CLIENT_API_OPEN)); + (tBTA_HF_CLIENT_API_OPEN*)osi_malloc(sizeof(tBTA_HF_CLIENT_API_OPEN)); if (!bta_hf_client_allocate_handle(bd_addr, p_handle)) { log::error("could not allocate handle"); @@ -175,10 +174,10 @@ void BTA_HfClientAudioClose(uint16_t handle) { * Returns void * ******************************************************************************/ -void BTA_HfClientSendAT(uint16_t handle, tBTA_HF_CLIENT_AT_CMD_TYPE at, - uint32_t val1, uint32_t val2, const char* str) { +void BTA_HfClientSendAT(uint16_t handle, tBTA_HF_CLIENT_AT_CMD_TYPE at, uint32_t val1, + uint32_t val2, const char* str) { tBTA_HF_CLIENT_DATA_VAL* p_buf = - (tBTA_HF_CLIENT_DATA_VAL*)osi_malloc(sizeof(tBTA_HF_CLIENT_DATA_VAL)); + (tBTA_HF_CLIENT_DATA_VAL*)osi_malloc(sizeof(tBTA_HF_CLIENT_DATA_VAL)); p_buf->hdr.event = BTA_HF_CLIENT_SEND_AT_CMD_EVT; p_buf->uint8_val = at; @@ -220,10 +219,10 @@ void BTA_HfClientDumpStatistics(int fd) { bta_hf_client_dump_statistics(fd); } * ******************************************************************************/ int get_default_hf_client_features() { -#define DEFAULT_BTIF_HF_CLIENT_FEATURES \ - (BTA_HF_CLIENT_FEAT_ECNR | BTA_HF_CLIENT_FEAT_3WAY | \ - BTA_HF_CLIENT_FEAT_CLI | BTA_HF_CLIENT_FEAT_VREC | BTA_HF_CLIENT_FEAT_VOL | \ - BTA_HF_CLIENT_FEAT_ECS | BTA_HF_CLIENT_FEAT_ECC | BTA_HF_CLIENT_FEAT_CODEC) +#define DEFAULT_BTIF_HF_CLIENT_FEATURES \ + (BTA_HF_CLIENT_FEAT_ECNR | BTA_HF_CLIENT_FEAT_3WAY | BTA_HF_CLIENT_FEAT_CLI | \ + BTA_HF_CLIENT_FEAT_VREC | BTA_HF_CLIENT_FEAT_VOL | BTA_HF_CLIENT_FEAT_ECS | \ + BTA_HF_CLIENT_FEAT_ECC | BTA_HF_CLIENT_FEAT_CODEC) return android::sysprop::bluetooth::Hfp::hf_client_features().value_or( DEFAULT_BTIF_HF_CLIENT_FEATURES); diff --git a/system/bta/hf_client/bta_hf_client_at.cc b/system/bta/hf_client/bta_hf_client_at.cc index 58daf4a605b..3494a89c37a 100644 --- a/system/bta/hf_client/bta_hf_client_at.cc +++ b/system/bta/hf_client/bta_hf_client_at.cc @@ -45,7 +45,7 @@ using namespace bluetooth; static constexpr char kPropertyEnhancedDrivingIndicatorEnabled[] = - "bluetooth.headset_client.indicator.enhanced_driver_safety.enabled"; + "bluetooth.headset_client.indicator.enhanced_driver_safety.enabled"; /****************************************************************************** * SUPPORTED EVENT MESSAGES @@ -83,23 +83,18 @@ typedef struct { /* CIND: storage room for indicators value range and their statuses */ static const tBTA_HF_CLIENT_INDICATOR - bta_hf_client_indicators[BTA_HF_CLIENT_AT_SUPPORTED_INDICATOR_COUNT] = { - /* name | min | max | name length - - used by parser */ - {BTA_HF_CLIENT_INDICATOR_BATTERYCHG, 0, 5, - sizeof(BTA_HF_CLIENT_INDICATOR_BATTERYCHG)}, - {BTA_HF_CLIENT_INDICATOR_SIGNAL, 0, 5, - sizeof(BTA_HF_CLIENT_INDICATOR_SIGNAL)}, - {BTA_HF_CLIENT_INDICATOR_SERVICE, 0, 1, - sizeof(BTA_HF_CLIENT_INDICATOR_SERVICE)}, - {BTA_HF_CLIENT_INDICATOR_CALL, 0, 1, - sizeof(BTA_HF_CLIENT_INDICATOR_CALL)}, - {BTA_HF_CLIENT_INDICATOR_ROAM, 0, 1, - sizeof(BTA_HF_CLIENT_INDICATOR_ROAM)}, - {BTA_HF_CLIENT_INDICATOR_CALLSETUP, 0, 3, - sizeof(BTA_HF_CLIENT_INDICATOR_CALLSETUP)}, - {BTA_HF_CLIENT_INDICATOR_CALLHELD, 0, 2, - sizeof(BTA_HF_CLIENT_INDICATOR_CALLHELD)}}; + bta_hf_client_indicators[BTA_HF_CLIENT_AT_SUPPORTED_INDICATOR_COUNT] = { + /* name | min | max | name length - + used by parser */ + {BTA_HF_CLIENT_INDICATOR_BATTERYCHG, 0, 5, + sizeof(BTA_HF_CLIENT_INDICATOR_BATTERYCHG)}, + {BTA_HF_CLIENT_INDICATOR_SIGNAL, 0, 5, sizeof(BTA_HF_CLIENT_INDICATOR_SIGNAL)}, + {BTA_HF_CLIENT_INDICATOR_SERVICE, 0, 1, sizeof(BTA_HF_CLIENT_INDICATOR_SERVICE)}, + {BTA_HF_CLIENT_INDICATOR_CALL, 0, 1, sizeof(BTA_HF_CLIENT_INDICATOR_CALL)}, + {BTA_HF_CLIENT_INDICATOR_ROAM, 0, 1, sizeof(BTA_HF_CLIENT_INDICATOR_ROAM)}, + {BTA_HF_CLIENT_INDICATOR_CALLSETUP, 0, 3, + sizeof(BTA_HF_CLIENT_INDICATOR_CALLSETUP)}, + {BTA_HF_CLIENT_INDICATOR_CALLHELD, 0, 2, sizeof(BTA_HF_CLIENT_INDICATOR_CALLHELD)}}; /* +VGM/+VGS - gain min/max values */ #define BTA_HF_CLIENT_VGS_MIN 0 @@ -126,11 +121,10 @@ static void bta_hf_client_clear_queued_at(tBTA_HF_CLIENT_CB* client_cb) { client_cb->at_cb.queued_cmd = NULL; } -static void bta_hf_client_queue_at(tBTA_HF_CLIENT_CB* client_cb, - tBTA_HF_CLIENT_AT_CMD cmd, const char* buf, - uint16_t buf_len) { +static void bta_hf_client_queue_at(tBTA_HF_CLIENT_CB* client_cb, tBTA_HF_CLIENT_AT_CMD cmd, + const char* buf, uint16_t buf_len) { tBTA_HF_CLIENT_AT_QCMD* new_cmd = - (tBTA_HF_CLIENT_AT_QCMD*)osi_malloc(sizeof(tBTA_HF_CLIENT_AT_QCMD)); + (tBTA_HF_CLIENT_AT_QCMD*)osi_malloc(sizeof(tBTA_HF_CLIENT_AT_QCMD)); log::verbose("cmd:{}", (int)cmd); @@ -142,7 +136,9 @@ static void bta_hf_client_queue_at(tBTA_HF_CLIENT_CB* client_cb, if (client_cb->at_cb.queued_cmd != NULL) { tBTA_HF_CLIENT_AT_QCMD* qcmd = client_cb->at_cb.queued_cmd; - while (qcmd->next != NULL) qcmd = qcmd->next; + while (qcmd->next != NULL) { + qcmd = qcmd->next; + } qcmd->next = new_cmd; } else { @@ -173,12 +169,10 @@ static void bta_hf_client_stop_at_resp_timer(tBTA_HF_CLIENT_CB* client_cb) { alarm_cancel(client_cb->at_cb.resp_timer); } -static void bta_hf_client_send_at(tBTA_HF_CLIENT_CB* client_cb, - tBTA_HF_CLIENT_AT_CMD cmd, const char* buf, - uint16_t buf_len) { +static void bta_hf_client_send_at(tBTA_HF_CLIENT_CB* client_cb, tBTA_HF_CLIENT_AT_CMD cmd, + const char* buf, uint16_t buf_len) { log::verbose("{}", cmd); - if ((client_cb->at_cb.current_cmd == BTA_HF_CLIENT_AT_NONE || - !client_cb->svc_conn) && + if ((client_cb->at_cb.current_cmd == BTA_HF_CLIENT_AT_NONE || !client_cb->svc_conn) && !alarm_is_scheduled(client_cb->at_cb.hold_timer)) { uint16_t len; @@ -188,18 +182,16 @@ static void bta_hf_client_send_at(tBTA_HF_CLIENT_CB* client_cb, client_cb->at_cb.current_cmd = cmd; /* Generate fake responses for these because they won't reliably work */ - if (!service_availability && - (cmd == BTA_HF_CLIENT_AT_CNUM || cmd == BTA_HF_CLIENT_AT_COPS)) { + if (!service_availability && (cmd == BTA_HF_CLIENT_AT_CNUM || cmd == BTA_HF_CLIENT_AT_COPS)) { log::warn("No service, skipping {} command", cmd); bta_hf_client_handle_ok(client_cb); return; } log::verbose("writing port data to {}", client_cb->conn_handle); - if (PORT_WriteData(client_cb->conn_handle, buf, buf_len, &len) != - PORT_SUCCESS) { - log::warn("Unable to write RFCOMM data peer:{} handle:{} len:{}", - client_cb->peer_addr, client_cb->conn_handle, buf_len); + if (PORT_WriteData(client_cb->conn_handle, buf, buf_len, &len) != PORT_SUCCESS) { + log::warn("Unable to write RFCOMM data peer:{} handle:{} len:{}", client_cb->peer_addr, + client_cb->conn_handle, buf_len); }; bta_hf_client_start_at_resp_timer(client_cb); @@ -293,10 +285,8 @@ static void bta_hf_client_handle_ok(tBTA_HF_CLIENT_CB* client_cb) { } static void bta_hf_client_handle_error(tBTA_HF_CLIENT_CB* client_cb, - tBTA_HF_CLIENT_AT_RESULT_TYPE type, - uint16_t cme) { - log::verbose("type:{} cme:{} current_cmd:{}", type, cme, - client_cb->at_cb.current_cmd); + tBTA_HF_CLIENT_AT_RESULT_TYPE type, uint16_t cme) { + log::verbose("type:{} cme:{} current_cmd:{}", type, cme, client_cb->at_cb.current_cmd); bta_hf_client_stop_at_resp_timer(client_cb); @@ -335,32 +325,29 @@ static void bta_hf_client_handle_error(tBTA_HF_CLIENT_CB* client_cb, static void bta_hf_client_handle_ring(tBTA_HF_CLIENT_CB* client_cb) { log::verbose(""); - const bool exit_sniff_while_ring = osi_property_get_bool( - "bluetooth.headset_client.exit_sniff_while_ring", false); + const bool exit_sniff_while_ring = + osi_property_get_bool("bluetooth.headset_client.exit_sniff_while_ring", false); // Invoke mode change to active mode if feature flag is enabled and current // status is sniff if (exit_sniff_while_ring) { tBTM_PM_MODE mode; - if (BTM_ReadPowerMode(client_cb->peer_addr, &mode) && - mode == BTM_PM_STS_SNIFF) { + if (BTM_ReadPowerMode(client_cb->peer_addr, &mode) && mode == BTM_PM_STS_SNIFF) { bta_sys_busy(BTA_ID_HS, 1, client_cb->peer_addr); } } bta_hf_client_evt_val(client_cb, BTA_HF_CLIENT_RING_INDICATION, 0); } -static void bta_hf_client_handle_brsf(tBTA_HF_CLIENT_CB* client_cb, - uint32_t value) { +static void bta_hf_client_handle_brsf(tBTA_HF_CLIENT_CB* client_cb, uint32_t value) { log::verbose("0x{:x}", value); client_cb->peer_features = value; } /* handles a single indicator descriptor - registers it for value changing * events */ -static void bta_hf_client_handle_cind_list_item(tBTA_HF_CLIENT_CB* client_cb, - char* name, uint32_t min, - uint32_t max, uint32_t index) { +static void bta_hf_client_handle_cind_list_item(tBTA_HF_CLIENT_CB* client_cb, char* name, + uint32_t min, uint32_t max, uint32_t index) { uint8_t i = 0; log::verbose("{} .{} <{}:{}>", index, name, min, max); @@ -378,9 +365,9 @@ static void bta_hf_client_handle_cind_list_item(tBTA_HF_CLIENT_CB* client_cb, * for string end */ /* It will distinguish 'callheld' which could be matched by strncmp as * 'call'. */ - if (strncmp(name, bta_hf_client_indicators[i].name, - bta_hf_client_indicators[i].namelen) != 0) + if (strncmp(name, bta_hf_client_indicators[i].name, bta_hf_client_indicators[i].namelen) != 0) { continue; + } /* index - enumerates value position in the incoming sequence */ /* if name matches one of the known indicators, add its incoming position */ @@ -392,8 +379,8 @@ static void bta_hf_client_handle_cind_list_item(tBTA_HF_CLIENT_CB* client_cb, } } -static void bta_hf_client_handle_cind_value(tBTA_HF_CLIENT_CB* client_cb, - uint32_t index, uint32_t value) { +static void bta_hf_client_handle_cind_value(tBTA_HF_CLIENT_CB* client_cb, uint32_t index, + uint32_t value) { log::verbose("index: {} value: {}", index, value); if (index >= BTA_HF_CLIENT_AT_INDICATOR_COUNT) { @@ -415,8 +402,7 @@ static void bta_hf_client_handle_cind_value(tBTA_HF_CLIENT_CB* client_cb, index = client_cb->at_cb.indicator_lookup[index]; /* Ignore out of range values */ - if (value > bta_hf_client_indicators[index].max || - value < bta_hf_client_indicators[index].min) { + if (value > bta_hf_client_indicators[index].max || value < bta_hf_client_indicators[index].min) { return; } @@ -424,22 +410,21 @@ static void bta_hf_client_handle_cind_value(tBTA_HF_CLIENT_CB* client_cb, bta_hf_client_ind(client_cb, index, value); } -static void bta_hf_client_handle_chld(tBTA_HF_CLIENT_CB* client_cb, - uint32_t mask) { +static void bta_hf_client_handle_chld(tBTA_HF_CLIENT_CB* client_cb, uint32_t mask) { log::verbose("0x{:x}", mask); client_cb->chld_features |= mask; } -static void bta_hf_client_handle_bind_read_supported_ind( - tBTA_HF_CLIENT_CB* client_cb, int indicator_id) { +static void bta_hf_client_handle_bind_read_supported_ind(tBTA_HF_CLIENT_CB* client_cb, + int indicator_id) { log::verbose("{}", indicator_id); client_cb->peer_hf_indicators.insert(indicator_id); } -static void bta_hf_client_handle_bind_read_enabled_ind( - tBTA_HF_CLIENT_CB* client_cb, int indicator_id, bool enable) { +static void bta_hf_client_handle_bind_read_enabled_ind(tBTA_HF_CLIENT_CB* client_cb, + int indicator_id, bool enable) { log::verbose("{}", indicator_id); if (enable) { @@ -449,8 +434,8 @@ static void bta_hf_client_handle_bind_read_enabled_ind( } } -static void bta_hf_client_handle_ciev(tBTA_HF_CLIENT_CB* client_cb, - uint32_t index, uint32_t value) { +static void bta_hf_client_handle_ciev(tBTA_HF_CLIENT_CB* client_cb, uint32_t index, + uint32_t value) { int8_t realind = -1; log::verbose("index: {} value: {}", index, value); @@ -487,14 +472,12 @@ static void bta_hf_client_handle_ciev(tBTA_HF_CLIENT_CB* client_cb, } } -static void bta_hf_client_handle_bcs(tBTA_HF_CLIENT_CB* client_cb, - uint32_t codec) { +static void bta_hf_client_handle_bcs(tBTA_HF_CLIENT_CB* client_cb, uint32_t codec) { tBTA_AG_UUID_CODEC uuid_codec = static_cast(codec); log::verbose("codec: {} sco listen state: {}", codec, client_cb->sco_state); if (uuid_codec == tBTA_AG_UUID_CODEC::UUID_CODEC_CVSD || uuid_codec == tBTA_AG_UUID_CODEC::UUID_CODEC_MSBC || - (bta_hf_client_cb_arr.is_support_lc3 && - uuid_codec == tBTA_AG_UUID_CODEC::UUID_CODEC_LC3)) { + (bta_hf_client_cb_arr.is_support_lc3 && uuid_codec == tBTA_AG_UUID_CODEC::UUID_CODEC_LC3)) { switch (uuid_codec) { case tBTA_AG_UUID_CODEC::UUID_CODEC_CVSD: client_cb->negotiated_codec = BTM_SCO_CODEC_CVSD; @@ -516,20 +499,17 @@ static void bta_hf_client_handle_bcs(tBTA_HF_CLIENT_CB* client_cb, } } -static void bta_hf_client_handle_bsir(tBTA_HF_CLIENT_CB* client_cb, - uint32_t provided) { +static void bta_hf_client_handle_bsir(tBTA_HF_CLIENT_CB* client_cb, uint32_t provided) { log::verbose("{}", provided); bta_hf_client_evt_val(client_cb, BTA_HF_CLIENT_BSIR_EVT, provided); } -static void bta_hf_client_handle_cmeerror(tBTA_HF_CLIENT_CB* client_cb, - uint32_t code) { +static void bta_hf_client_handle_cmeerror(tBTA_HF_CLIENT_CB* client_cb, uint32_t code) { bta_hf_client_handle_error(client_cb, BTA_HF_CLIENT_AT_RESULT_CME, code); } -static void bta_hf_client_handle_vgm(tBTA_HF_CLIENT_CB* client_cb, - uint32_t value) { +static void bta_hf_client_handle_vgm(tBTA_HF_CLIENT_CB* client_cb, uint32_t value) { log::verbose("{}", value); if (value <= BTA_HF_CLIENT_VGM_MAX) { @@ -537,8 +517,7 @@ static void bta_hf_client_handle_vgm(tBTA_HF_CLIENT_CB* client_cb, } } -static void bta_hf_client_handle_vgs(tBTA_HF_CLIENT_CB* client_cb, - uint32_t value) { +static void bta_hf_client_handle_vgs(tBTA_HF_CLIENT_CB* client_cb, uint32_t value) { log::verbose("{}", value); if (value <= BTA_HF_CLIENT_VGS_MAX) { @@ -546,8 +525,7 @@ static void bta_hf_client_handle_vgs(tBTA_HF_CLIENT_CB* client_cb, } } -static void bta_hf_client_handle_bvra(tBTA_HF_CLIENT_CB* client_cb, - uint32_t value) { +static void bta_hf_client_handle_bvra(tBTA_HF_CLIENT_CB* client_cb, uint32_t value) { log::verbose("{}", value); if (value > 1) { @@ -557,44 +535,37 @@ static void bta_hf_client_handle_bvra(tBTA_HF_CLIENT_CB* client_cb, bta_hf_client_evt_val(client_cb, BTA_HF_CLIENT_VOICE_REC_EVT, value); } -static void bta_hf_client_handle_clip(tBTA_HF_CLIENT_CB* client_cb, - char* numstr, uint32_t type) { +static void bta_hf_client_handle_clip(tBTA_HF_CLIENT_CB* client_cb, char* numstr, uint32_t type) { std::string cell_number(numstr); log::verbose("{} {}", type, PRIVATE_CELL(cell_number)); bta_hf_client_clip(client_cb, numstr); } -static void bta_hf_client_handle_ccwa(tBTA_HF_CLIENT_CB* client_cb, - char* numstr, uint32_t type) { +static void bta_hf_client_handle_ccwa(tBTA_HF_CLIENT_CB* client_cb, char* numstr, uint32_t type) { std::string cell_number(numstr); log::verbose("{} {}", type, PRIVATE_CELL(cell_number)); bta_hf_client_ccwa(client_cb, numstr); } -static void bta_hf_client_handle_cops(tBTA_HF_CLIENT_CB* client_cb, char* opstr, - uint32_t mode) { +static void bta_hf_client_handle_cops(tBTA_HF_CLIENT_CB* client_cb, char* opstr, uint32_t mode) { log::verbose("{} {}", mode, opstr); bta_hf_client_operator_name(client_cb, opstr); } -static void bta_hf_client_handle_binp(tBTA_HF_CLIENT_CB* client_cb, - char* numstr) { +static void bta_hf_client_handle_binp(tBTA_HF_CLIENT_CB* client_cb, char* numstr) { std::string cell_number(numstr); log::verbose("{}", PRIVATE_CELL(cell_number)); bta_hf_client_binp(client_cb, numstr); } -static void bta_hf_client_handle_clcc(tBTA_HF_CLIENT_CB* client_cb, - uint16_t idx, uint16_t dir, - uint16_t status, uint16_t mode, - uint16_t mpty, char* numstr, +static void bta_hf_client_handle_clcc(tBTA_HF_CLIENT_CB* client_cb, uint16_t idx, uint16_t dir, + uint16_t status, uint16_t mode, uint16_t mpty, char* numstr, uint16_t type) { - log::verbose("idx: {} dir: {} status: {} mode: {} mpty: {}", idx, dir, status, - mode, mpty); + log::verbose("idx: {} dir: {} status: {} mode: {} mpty: {}", idx, dir, status, mode, mpty); if (numstr) { std::string cell_number(numstr); @@ -604,19 +575,16 @@ static void bta_hf_client_handle_clcc(tBTA_HF_CLIENT_CB* client_cb, bta_hf_client_clcc(client_cb, idx, dir, status, mpty, numstr); } -static void bta_hf_client_handle_cnum(tBTA_HF_CLIENT_CB* client_cb, - char* numstr, uint16_t type, +static void bta_hf_client_handle_cnum(tBTA_HF_CLIENT_CB* client_cb, char* numstr, uint16_t type, uint16_t service) { std::string cell_number(numstr); - log::verbose("number: {} type: {} service: {}", PRIVATE_CELL(cell_number), - type, service); + log::verbose("number: {} type: {} service: {}", PRIVATE_CELL(cell_number), type, service); /* TODO: should number be modified according to type? */ bta_hf_client_cnum(client_cb, numstr, service); } -static void bta_hf_client_handle_btrh(tBTA_HF_CLIENT_CB* client_cb, - uint16_t code) { +static void bta_hf_client_handle_btrh(tBTA_HF_CLIENT_CB* client_cb, uint16_t code) { log::verbose("{}", code); bta_hf_client_evt_val(client_cb, BTA_HF_CLIENT_BTRH_EVT, code); @@ -631,8 +599,7 @@ static void bta_hf_client_handle_btrh(tBTA_HF_CLIENT_CB* client_cb, * Returns void * ******************************************************************************/ -void bta_hf_client_ind(tBTA_HF_CLIENT_CB* client_cb, - tBTA_HF_CLIENT_IND_TYPE type, uint16_t value) { +void bta_hf_client_ind(tBTA_HF_CLIENT_CB* client_cb, tBTA_HF_CLIENT_IND_TYPE type, uint16_t value) { tBTA_HF_CLIENT evt; memset(&evt, 0, sizeof(evt)); @@ -655,8 +622,7 @@ void bta_hf_client_ind(tBTA_HF_CLIENT_CB* client_cb, * Returns void * ******************************************************************************/ -void bta_hf_client_evt_val(tBTA_HF_CLIENT_CB* client_cb, - tBTA_HF_CLIENT_EVT type, uint16_t value) { +void bta_hf_client_evt_val(tBTA_HF_CLIENT_CB* client_cb, tBTA_HF_CLIENT_EVT type, uint16_t value) { tBTA_HF_CLIENT evt; memset(&evt, 0, sizeof(evt)); @@ -743,8 +709,8 @@ void bta_hf_client_ccwa(tBTA_HF_CLIENT_CB* client_cb, char* number) { * Returns void * ******************************************************************************/ -void bta_hf_client_at_result(tBTA_HF_CLIENT_CB* client_cb, - tBTA_HF_CLIENT_AT_RESULT_TYPE type, uint16_t cme) { +void bta_hf_client_at_result(tBTA_HF_CLIENT_CB* client_cb, tBTA_HF_CLIENT_AT_RESULT_TYPE type, + uint16_t cme) { tBTA_HF_CLIENT evt; memset(&evt, 0, sizeof(evt)); @@ -766,9 +732,8 @@ void bta_hf_client_at_result(tBTA_HF_CLIENT_CB* client_cb, * Returns void * ******************************************************************************/ -void bta_hf_client_clcc(tBTA_HF_CLIENT_CB* client_cb, uint32_t idx, - bool incoming, uint8_t status, bool mpty, - char* number) { +void bta_hf_client_clcc(tBTA_HF_CLIENT_CB* client_cb, uint32_t idx, bool incoming, uint8_t status, + bool mpty, char* number) { tBTA_HF_CLIENT evt; memset(&evt, 0, sizeof(evt)); @@ -798,8 +763,7 @@ void bta_hf_client_clcc(tBTA_HF_CLIENT_CB* client_cb, uint32_t idx, * Returns void * ******************************************************************************/ -void bta_hf_client_cnum(tBTA_HF_CLIENT_CB* client_cb, char* number, - uint16_t service) { +void bta_hf_client_cnum(tBTA_HF_CLIENT_CB* client_cb, char* number, uint16_t service) { tBTA_HF_CLIENT evt = {}; evt.cnum.service = service; @@ -810,12 +774,10 @@ void bta_hf_client_cnum(tBTA_HF_CLIENT_CB* client_cb, char* number, bta_hf_client_app_callback(BTA_HF_CLIENT_CNUM_EVT, &evt); } -void bta_hf_client_unknown_response(tBTA_HF_CLIENT_CB* client_cb, - const char* evt_buffer) { +void bta_hf_client_unknown_response(tBTA_HF_CLIENT_CB* client_cb, const char* evt_buffer) { tBTA_HF_CLIENT evt = {}; - strlcpy(evt.unknown.event_string, evt_buffer, - BTA_HF_CLIENT_UNKNOWN_EVENT_LEN + 1); + strlcpy(evt.unknown.event_string, evt_buffer, BTA_HF_CLIENT_UNKNOWN_EVENT_LEN + 1); evt.unknown.event_string[BTA_HF_CLIENT_UNKNOWN_EVENT_LEN] = '\0'; evt.unknown.bd_addr = client_cb->peer_addr; @@ -851,11 +813,13 @@ void bta_hf_client_binp(tBTA_HF_CLIENT_CB* client_cb, char* number) { ******************************************************************************/ /* Check if prefix match and skip spaces if any */ -#define AT_CHECK_EVENT(buf, event) \ - do { \ - if (strncmp("\r\n" event, buf, sizeof("\r\n" event) - 1) != 0) return buf; \ - (buf) += sizeof("\r\n" event) - 1; \ - while (*(buf) == ' ') (buf)++; \ +#define AT_CHECK_EVENT(buf, event) \ + do { \ + if (strncmp("\r\n" event, buf, sizeof("\r\n" event) - 1) != 0) \ + return buf; \ + (buf) += sizeof("\r\n" event) - 1; \ + while (*(buf) == ' ') \ + (buf)++; \ } while (0) /* check for and forward buffer if match */ @@ -869,13 +833,13 @@ void bta_hf_client_binp(tBTA_HF_CLIENT_CB* client_cb, char* number) { } while (0) /* skip rest of AT string up to */ -#define AT_SKIP_REST(buf) \ - do { \ - while (*(buf) != '\r' && *(buf) != '\0') (buf)++; \ +#define AT_SKIP_REST(buf) \ + do { \ + while (*(buf) != '\r' && *(buf) != '\0') \ + (buf)++; \ } while (0) -static char* bta_hf_client_parse_ok(tBTA_HF_CLIENT_CB* client_cb, - char* buffer) { +static char* bta_hf_client_parse_ok(tBTA_HF_CLIENT_CB* client_cb, char* buffer) { AT_CHECK_EVENT(buffer, "OK"); AT_CHECK_RN(buffer); @@ -884,8 +848,7 @@ static char* bta_hf_client_parse_ok(tBTA_HF_CLIENT_CB* client_cb, return buffer; } -static char* bta_hf_client_parse_error(tBTA_HF_CLIENT_CB* client_cb, - char* buffer) { +static char* bta_hf_client_parse_error(tBTA_HF_CLIENT_CB* client_cb, char* buffer) { AT_CHECK_EVENT(buffer, "ERROR"); AT_CHECK_RN(buffer); @@ -894,8 +857,7 @@ static char* bta_hf_client_parse_error(tBTA_HF_CLIENT_CB* client_cb, return buffer; } -static char* bta_hf_client_parse_ring(tBTA_HF_CLIENT_CB* client_cb, - char* buffer) { +static char* bta_hf_client_parse_ring(tBTA_HF_CLIENT_CB* client_cb, char* buffer) { AT_CHECK_EVENT(buffer, "RING"); AT_CHECK_RN(buffer); @@ -905,9 +867,8 @@ static char* bta_hf_client_parse_ring(tBTA_HF_CLIENT_CB* client_cb, } /* generic uint32 parser */ -static char* bta_hf_client_parse_uint32( - tBTA_HF_CLIENT_CB* client_cb, char* buffer, - void (*handler_callback)(tBTA_HF_CLIENT_CB*, uint32_t)) { +static char* bta_hf_client_parse_uint32(tBTA_HF_CLIENT_CB* client_cb, char* buffer, + void (*handler_callback)(tBTA_HF_CLIENT_CB*, uint32_t)) { uint32_t value; int res; int offset; @@ -925,16 +886,13 @@ static char* bta_hf_client_parse_uint32( return buffer; } -static char* bta_hf_client_parse_brsf(tBTA_HF_CLIENT_CB* client_cb, - char* buffer) { +static char* bta_hf_client_parse_brsf(tBTA_HF_CLIENT_CB* client_cb, char* buffer) { AT_CHECK_EVENT(buffer, "+BRSF:"); - return bta_hf_client_parse_uint32(client_cb, buffer, - bta_hf_client_handle_brsf); + return bta_hf_client_parse_uint32(client_cb, buffer, bta_hf_client_handle_brsf); } -static char* bta_hf_client_parse_cind_values(tBTA_HF_CLIENT_CB* client_cb, - char* buffer) { +static char* bta_hf_client_parse_cind_values(tBTA_HF_CLIENT_CB* client_cb, char* buffer) { /* value and its position */ uint16_t index = 0; uint32_t value = 0; @@ -965,16 +923,14 @@ static char* bta_hf_client_parse_cind_values(tBTA_HF_CLIENT_CB* client_cb, return NULL; } -static char* bta_hf_client_parse_cind_list(tBTA_HF_CLIENT_CB* client_cb, - char* buffer) { +static char* bta_hf_client_parse_cind_list(tBTA_HF_CLIENT_CB* client_cb, char* buffer) { int offset = 0; char name[129]; uint32_t min, max; uint32_t index = 0; int res; - while ((res = sscanf(buffer, "(\"%128[^\"]\",(%u%*[-,]%u))%n", name, &min, - &max, &offset)) > 2) { + while ((res = sscanf(buffer, "(\"%128[^\"]\",(%u%*[-,]%u))%n", name, &min, &max, &offset)) > 2) { bta_hf_client_handle_cind_list_item(client_cb, name, min, max, index); if (offset == 0) { log::error("Format Error {}", buffer); @@ -999,17 +955,17 @@ static char* bta_hf_client_parse_cind_list(tBTA_HF_CLIENT_CB* client_cb, return NULL; } -static char* bta_hf_client_parse_cind(tBTA_HF_CLIENT_CB* client_cb, - char* buffer) { +static char* bta_hf_client_parse_cind(tBTA_HF_CLIENT_CB* client_cb, char* buffer) { AT_CHECK_EVENT(buffer, "+CIND:"); - if (*buffer == '(') return bta_hf_client_parse_cind_list(client_cb, buffer); + if (*buffer == '(') { + return bta_hf_client_parse_cind_list(client_cb, buffer); + } return bta_hf_client_parse_cind_values(client_cb, buffer); } -static char* bta_hf_client_parse_chld(tBTA_HF_CLIENT_CB* client_cb, - char* buffer) { +static char* bta_hf_client_parse_chld(tBTA_HF_CLIENT_CB* client_cb, char* buffer) { AT_CHECK_EVENT(buffer, "+CHLD:"); if (*buffer != '(') { @@ -1062,8 +1018,7 @@ static char* bta_hf_client_parse_chld(tBTA_HF_CLIENT_CB* client_cb, return buffer; } -static char* bta_hf_client_parse_bind(tBTA_HF_CLIENT_CB* client_cb, - char* buffer) { +static char* bta_hf_client_parse_bind(tBTA_HF_CLIENT_CB* client_cb, char* buffer) { AT_CHECK_EVENT(buffer, "+BIND:"); uint8_t mode = BTA_HF_CLIENT_BIND_PARSE_READ_ENABLED_IND; @@ -1082,15 +1037,13 @@ static char* bta_hf_client_parse_bind(tBTA_HF_CLIENT_CB* client_cb, case '2': if (mode == BTA_HF_CLIENT_BIND_PARSE_READ_SUPPOETED_IND) { // +BIND: (id0, id1, ...) - bta_hf_client_handle_bind_read_supported_ind(client_cb, - (*buffer - '0')); + bta_hf_client_handle_bind_read_supported_ind(client_cb, (*buffer - '0')); } else if (idx == -1) { // +BIND: [id]... idx = *buffer - '0'; } else { // +BIND: ...[status] - bta_hf_client_handle_bind_read_enabled_ind(client_cb, idx, - *buffer - '0'); + bta_hf_client_handle_bind_read_enabled_ind(client_cb, idx, *buffer - '0'); } break; default: @@ -1104,8 +1057,7 @@ static char* bta_hf_client_parse_bind(tBTA_HF_CLIENT_CB* client_cb, return buffer; } -static char* bta_hf_client_parse_ciev(tBTA_HF_CLIENT_CB* client_cb, - char* buffer) { +static char* bta_hf_client_parse_ciev(tBTA_HF_CLIENT_CB* client_cb, char* buffer) { uint32_t index, value; int res; int offset = 0; @@ -1130,72 +1082,55 @@ static char* bta_hf_client_parse_ciev(tBTA_HF_CLIENT_CB* client_cb, return buffer; } -static char* bta_hf_client_parse_bcs(tBTA_HF_CLIENT_CB* client_cb, - char* buffer) { +static char* bta_hf_client_parse_bcs(tBTA_HF_CLIENT_CB* client_cb, char* buffer) { AT_CHECK_EVENT(buffer, "+BCS:"); - return bta_hf_client_parse_uint32(client_cb, buffer, - bta_hf_client_handle_bcs); + return bta_hf_client_parse_uint32(client_cb, buffer, bta_hf_client_handle_bcs); } -static char* bta_hf_client_parse_bsir(tBTA_HF_CLIENT_CB* client_cb, - char* buffer) { +static char* bta_hf_client_parse_bsir(tBTA_HF_CLIENT_CB* client_cb, char* buffer) { AT_CHECK_EVENT(buffer, "+BSIR:"); - return bta_hf_client_parse_uint32(client_cb, buffer, - bta_hf_client_handle_bsir); + return bta_hf_client_parse_uint32(client_cb, buffer, bta_hf_client_handle_bsir); } -static char* bta_hf_client_parse_cmeerror(tBTA_HF_CLIENT_CB* client_cb, - char* buffer) { +static char* bta_hf_client_parse_cmeerror(tBTA_HF_CLIENT_CB* client_cb, char* buffer) { AT_CHECK_EVENT(buffer, "+CME ERROR:"); - return bta_hf_client_parse_uint32(client_cb, buffer, - bta_hf_client_handle_cmeerror); + return bta_hf_client_parse_uint32(client_cb, buffer, bta_hf_client_handle_cmeerror); } -static char* bta_hf_client_parse_vgm(tBTA_HF_CLIENT_CB* client_cb, - char* buffer) { +static char* bta_hf_client_parse_vgm(tBTA_HF_CLIENT_CB* client_cb, char* buffer) { AT_CHECK_EVENT(buffer, "+VGM:"); - return bta_hf_client_parse_uint32(client_cb, buffer, - bta_hf_client_handle_vgm); + return bta_hf_client_parse_uint32(client_cb, buffer, bta_hf_client_handle_vgm); } -static char* bta_hf_client_parse_vgme(tBTA_HF_CLIENT_CB* client_cb, - char* buffer) { +static char* bta_hf_client_parse_vgme(tBTA_HF_CLIENT_CB* client_cb, char* buffer) { AT_CHECK_EVENT(buffer, "+VGM="); - return bta_hf_client_parse_uint32(client_cb, buffer, - bta_hf_client_handle_vgm); + return bta_hf_client_parse_uint32(client_cb, buffer, bta_hf_client_handle_vgm); } -static char* bta_hf_client_parse_vgs(tBTA_HF_CLIENT_CB* client_cb, - char* buffer) { +static char* bta_hf_client_parse_vgs(tBTA_HF_CLIENT_CB* client_cb, char* buffer) { AT_CHECK_EVENT(buffer, "+VGS:"); - return bta_hf_client_parse_uint32(client_cb, buffer, - bta_hf_client_handle_vgs); + return bta_hf_client_parse_uint32(client_cb, buffer, bta_hf_client_handle_vgs); } -static char* bta_hf_client_parse_vgse(tBTA_HF_CLIENT_CB* client_cb, - char* buffer) { +static char* bta_hf_client_parse_vgse(tBTA_HF_CLIENT_CB* client_cb, char* buffer) { AT_CHECK_EVENT(buffer, "+VGS="); - return bta_hf_client_parse_uint32(client_cb, buffer, - bta_hf_client_handle_vgs); + return bta_hf_client_parse_uint32(client_cb, buffer, bta_hf_client_handle_vgs); } -static char* bta_hf_client_parse_bvra(tBTA_HF_CLIENT_CB* client_cb, - char* buffer) { +static char* bta_hf_client_parse_bvra(tBTA_HF_CLIENT_CB* client_cb, char* buffer) { AT_CHECK_EVENT(buffer, "+BVRA:"); - return bta_hf_client_parse_uint32(client_cb, buffer, - bta_hf_client_handle_bvra); + return bta_hf_client_parse_uint32(client_cb, buffer, bta_hf_client_handle_bvra); } -static char* bta_hf_client_parse_clip(tBTA_HF_CLIENT_CB* client_cb, - char* buffer) { +static char* bta_hf_client_parse_clip(tBTA_HF_CLIENT_CB* client_cb, char* buffer) { /* spec forces 32 chars, plus \0 here */ char number[33]; uint32_t type = 0; @@ -1226,8 +1161,7 @@ static char* bta_hf_client_parse_clip(tBTA_HF_CLIENT_CB* client_cb, } /* in HFP context there is no difference between ccwa and clip */ -static char* bta_hf_client_parse_ccwa(tBTA_HF_CLIENT_CB* client_cb, - char* buffer) { +static char* bta_hf_client_parse_ccwa(tBTA_HF_CLIENT_CB* client_cb, char* buffer) { /* ac to spec 32 chars max, plus \0 here */ char number[33]; uint32_t type = 0; @@ -1257,8 +1191,7 @@ static char* bta_hf_client_parse_ccwa(tBTA_HF_CLIENT_CB* client_cb, return buffer; } -static char* bta_hf_client_parse_cops(tBTA_HF_CLIENT_CB* client_cb, - char* buffer) { +static char* bta_hf_client_parse_cops(tBTA_HF_CLIENT_CB* client_cb, char* buffer) { uint8_t mode; /* spec forces 16 chars max, plus \0 here */ char opstr[17]; @@ -1295,8 +1228,7 @@ static char* bta_hf_client_parse_cops(tBTA_HF_CLIENT_CB* client_cb, return buffer; } -static char* bta_hf_client_parse_binp(tBTA_HF_CLIENT_CB* client_cb, - char* buffer) { +static char* bta_hf_client_parse_binp(tBTA_HF_CLIENT_CB* client_cb, char* buffer) { /* HFP only supports phone number as BINP data */ /* phone number is 32 chars plus one for \0*/ char numstr[33]; @@ -1334,8 +1266,7 @@ static char* bta_hf_client_parse_binp(tBTA_HF_CLIENT_CB* client_cb, return buffer; } -static char* bta_hf_client_parse_clcc(tBTA_HF_CLIENT_CB* client_cb, - char* buffer) { +static char* bta_hf_client_parse_clcc(tBTA_HF_CLIENT_CB* client_cb, char* buffer) { uint16_t idx, dir, status, mode, mpty; char numstr[33]; /* spec forces 32 chars, plus one for \0*/ uint16_t type = 0; @@ -1344,8 +1275,7 @@ static char* bta_hf_client_parse_clcc(tBTA_HF_CLIENT_CB* client_cb, AT_CHECK_EVENT(buffer, "+CLCC:"); - res = sscanf(buffer, "%hu,%hu,%hu,%hu,%hu%n", &idx, &dir, &status, &mode, - &mpty, &offset); + res = sscanf(buffer, "%hu,%hu,%hu,%hu,%hu%n", &idx, &dir, &status, &mode, &mpty, &offset); if (res < 5) { return NULL; } @@ -1362,11 +1292,15 @@ static char* bta_hf_client_parse_clcc(tBTA_HF_CLIENT_CB* client_cb, /* check optional part */ if (*buffer == ',') { int res2 = sscanf(buffer, ",\"%32[^\"]\",%hu%n", numstr, &type, &offset); - if (res2 < 0) return NULL; + if (res2 < 0) { + return NULL; + } if (res2 == 0) { res2 = sscanf(buffer, ",\"\",%hu%n", &type, &offset); - if (res2 < 0) return NULL; + if (res2 < 0) { + return NULL; + } /* numstr is not matched in second attempt, correct this */ res2++; @@ -1391,8 +1325,7 @@ static char* bta_hf_client_parse_clcc(tBTA_HF_CLIENT_CB* client_cb, if (res > 6) { /* we also have last two optional parameters */ - bta_hf_client_handle_clcc(client_cb, idx, dir, status, mode, mpty, numstr, - type); + bta_hf_client_handle_clcc(client_cb, idx, dir, status, mode, mpty, numstr, type); } else { /* we didn't get the last two parameters */ bta_hf_client_handle_clcc(client_cb, idx, dir, status, mode, mpty, NULL, 0); @@ -1406,19 +1339,16 @@ static char* bta_hf_client_parse_clcc(tBTA_HF_CLIENT_CB* client_cb, return buffer; } -static char* bta_hf_client_parse_cnum(tBTA_HF_CLIENT_CB* client_cb, - char* buffer) { +static char* bta_hf_client_parse_cnum(tBTA_HF_CLIENT_CB* client_cb, char* buffer) { char numstr[33]; /* spec forces 32 chars, plus one for \0*/ uint16_t type; - uint16_t service = - 0; /* 0 in case this optional parameter is not being sent */ + uint16_t service = 0; /* 0 in case this optional parameter is not being sent */ int res; int offset = 0; AT_CHECK_EVENT(buffer, "+CNUM:"); - res = sscanf(buffer, ",\"%32[^\"]\",%hu,,%hu%n", numstr, &type, &service, - &offset); + res = sscanf(buffer, ",\"%32[^\"]\",%hu,,%hu%n", numstr, &type, &service, &offset); if (res < 0) { return NULL; } @@ -1468,8 +1398,7 @@ static char* bta_hf_client_parse_cnum(tBTA_HF_CLIENT_CB* client_cb, return buffer; } -static char* bta_hf_client_parse_btrh(tBTA_HF_CLIENT_CB* client_cb, - char* buffer) { +static char* bta_hf_client_parse_btrh(tBTA_HF_CLIENT_CB* client_cb, char* buffer) { uint16_t code = 0; int res; int offset; @@ -1489,8 +1418,7 @@ static char* bta_hf_client_parse_btrh(tBTA_HF_CLIENT_CB* client_cb, return buffer; } -static char* bta_hf_client_parse_busy(tBTA_HF_CLIENT_CB* client_cb, - char* buffer) { +static char* bta_hf_client_parse_busy(tBTA_HF_CLIENT_CB* client_cb, char* buffer) { AT_CHECK_EVENT(buffer, "BUSY"); AT_CHECK_RN(buffer); @@ -1499,8 +1427,7 @@ static char* bta_hf_client_parse_busy(tBTA_HF_CLIENT_CB* client_cb, return buffer; } -static char* bta_hf_client_parse_delayed(tBTA_HF_CLIENT_CB* client_cb, - char* buffer) { +static char* bta_hf_client_parse_delayed(tBTA_HF_CLIENT_CB* client_cb, char* buffer) { AT_CHECK_EVENT(buffer, "DELAYED"); AT_CHECK_RN(buffer); @@ -1509,8 +1436,7 @@ static char* bta_hf_client_parse_delayed(tBTA_HF_CLIENT_CB* client_cb, return buffer; } -static char* bta_hf_client_parse_no_carrier(tBTA_HF_CLIENT_CB* client_cb, - char* buffer) { +static char* bta_hf_client_parse_no_carrier(tBTA_HF_CLIENT_CB* client_cb, char* buffer) { AT_CHECK_EVENT(buffer, "NO CARRIER"); AT_CHECK_RN(buffer); @@ -1519,8 +1445,7 @@ static char* bta_hf_client_parse_no_carrier(tBTA_HF_CLIENT_CB* client_cb, return buffer; } -static char* bta_hf_client_parse_no_answer(tBTA_HF_CLIENT_CB* client_cb, - char* buffer) { +static char* bta_hf_client_parse_no_answer(tBTA_HF_CLIENT_CB* client_cb, char* buffer) { AT_CHECK_EVENT(buffer, "NO ANSWER"); AT_CHECK_RN(buffer); @@ -1529,19 +1454,16 @@ static char* bta_hf_client_parse_no_answer(tBTA_HF_CLIENT_CB* client_cb, return buffer; } -static char* bta_hf_client_parse_rejectlisted(tBTA_HF_CLIENT_CB* client_cb, - char* buffer) { +static char* bta_hf_client_parse_rejectlisted(tBTA_HF_CLIENT_CB* client_cb, char* buffer) { AT_CHECK_EVENT(buffer, "REJECTLISTED"); AT_CHECK_RN(buffer); - bta_hf_client_handle_error(client_cb, BTA_HF_CLIENT_AT_RESULT_REJECTLISTED, - 0); + bta_hf_client_handle_error(client_cb, BTA_HF_CLIENT_AT_RESULT_REJECTLISTED, 0); return buffer; } -static char* bta_hf_client_skip_unknown(tBTA_HF_CLIENT_CB* client_cb, - char* buffer) { +static char* bta_hf_client_skip_unknown(tBTA_HF_CLIENT_CB* client_cb, char* buffer) { char* start; char* tmp; @@ -1565,8 +1487,7 @@ static char* bta_hf_client_skip_unknown(tBTA_HF_CLIENT_CB* client_cb, return buffer; } -static char* bta_hf_client_process_unknown(tBTA_HF_CLIENT_CB* client_cb, - char* buffer) { +static char* bta_hf_client_process_unknown(tBTA_HF_CLIENT_CB* client_cb, char* buffer) { char* start = strstr(buffer, "\r\n"); if (start == NULL) { return NULL; @@ -1586,8 +1507,7 @@ static char* bta_hf_client_process_unknown(tBTA_HF_CLIENT_CB* client_cb, bta_hf_client_unknown_response(client_cb, tmp_buf); AT_CHECK_RN(end); } else { - log::error("exceed event buffer size. ({}, {})", evt_size, - BTA_HF_CLIENT_UNKNOWN_EVENT_LEN); + log::error("exceed event buffer size. ({}, {})", evt_size, BTA_HF_CLIENT_UNKNOWN_EVENT_LEN); } log::verbose("{}", buffer); @@ -1607,25 +1527,25 @@ static char* bta_hf_client_process_unknown(tBTA_HF_CLIENT_CB* client_cb, typedef char* (*tBTA_HF_CLIENT_PARSER_CALLBACK)(tBTA_HF_CLIENT_CB*, char*); static const tBTA_HF_CLIENT_PARSER_CALLBACK bta_hf_client_parser_cb[] = { - bta_hf_client_parse_ok, bta_hf_client_parse_error, - bta_hf_client_parse_ring, bta_hf_client_parse_brsf, - bta_hf_client_parse_cind, bta_hf_client_parse_ciev, - bta_hf_client_parse_chld, bta_hf_client_parse_bcs, - bta_hf_client_parse_bsir, bta_hf_client_parse_cmeerror, - bta_hf_client_parse_vgm, bta_hf_client_parse_vgme, - bta_hf_client_parse_vgs, bta_hf_client_parse_vgse, - bta_hf_client_parse_bvra, bta_hf_client_parse_clip, - bta_hf_client_parse_ccwa, bta_hf_client_parse_cops, - bta_hf_client_parse_binp, bta_hf_client_parse_clcc, - bta_hf_client_parse_cnum, bta_hf_client_parse_btrh, - bta_hf_client_parse_bind, bta_hf_client_parse_busy, - bta_hf_client_parse_delayed, bta_hf_client_parse_no_carrier, - bta_hf_client_parse_no_answer, bta_hf_client_parse_rejectlisted, - bta_hf_client_process_unknown}; + bta_hf_client_parse_ok, bta_hf_client_parse_error, + bta_hf_client_parse_ring, bta_hf_client_parse_brsf, + bta_hf_client_parse_cind, bta_hf_client_parse_ciev, + bta_hf_client_parse_chld, bta_hf_client_parse_bcs, + bta_hf_client_parse_bsir, bta_hf_client_parse_cmeerror, + bta_hf_client_parse_vgm, bta_hf_client_parse_vgme, + bta_hf_client_parse_vgs, bta_hf_client_parse_vgse, + bta_hf_client_parse_bvra, bta_hf_client_parse_clip, + bta_hf_client_parse_ccwa, bta_hf_client_parse_cops, + bta_hf_client_parse_binp, bta_hf_client_parse_clcc, + bta_hf_client_parse_cnum, bta_hf_client_parse_btrh, + bta_hf_client_parse_bind, bta_hf_client_parse_busy, + bta_hf_client_parse_delayed, bta_hf_client_parse_no_carrier, + bta_hf_client_parse_no_answer, bta_hf_client_parse_rejectlisted, + bta_hf_client_process_unknown}; /* calculate supported event list length */ static const uint16_t bta_hf_client_parser_cb_count = - sizeof(bta_hf_client_parser_cb) / sizeof(bta_hf_client_parser_cb[0]); + sizeof(bta_hf_client_parser_cb) / sizeof(bta_hf_client_parser_cb[0]); #ifdef BTA_HF_CLIENT_AT_DUMP static void bta_hf_client_dump_at(tBTA_HF_CLIENT_CB* client_cb) { @@ -1704,8 +1624,7 @@ static bool bta_hf_client_check_at_complete(tBTA_HF_CLIENT_CB* client_cb) { tBTA_HF_CLIENT_AT_CB* at_cb = &client_cb->at_cb; if (at_cb->offset >= BTA_HF_CLIENT_AT_EVENT_MIN_LEN) { - if (at_cb->buf[at_cb->offset - 2] == '\r' && - at_cb->buf[at_cb->offset - 1] == '\n') { + if (at_cb->buf[at_cb->offset - 2] == '\r' && at_cb->buf[at_cb->offset - 1] == '\n') { ret = true; } } @@ -1726,15 +1645,13 @@ static void bta_hf_client_at_clear_buf(tBTA_HF_CLIENT_CB* client_cb) { * * ******************************************************************************/ -void bta_hf_client_at_parse(tBTA_HF_CLIENT_CB* client_cb, char* buf, - unsigned int len) { +void bta_hf_client_at_parse(tBTA_HF_CLIENT_CB* client_cb, char* buf, unsigned int len) { log::verbose("offset: {} len: {}", client_cb->at_cb.offset, len); if (len + client_cb->at_cb.offset > BTA_HF_CLIENT_AT_PARSER_MAX_LEN) { char tmp_buff[BTA_HF_CLIENT_AT_PARSER_MAX_LEN]; unsigned int tmp = client_cb->at_cb.offset; - unsigned int space_left = - BTA_HF_CLIENT_AT_PARSER_MAX_LEN - client_cb->at_cb.offset; + unsigned int space_left = BTA_HF_CLIENT_AT_PARSER_MAX_LEN - client_cb->at_cb.offset; log::verbose("overrun, trying to recover"); @@ -1790,8 +1707,7 @@ void bta_hf_client_at_parse(tBTA_HF_CLIENT_CB* client_cb, char* buf, } } -void bta_hf_client_send_at_brsf(tBTA_HF_CLIENT_CB* client_cb, - tBTA_HF_CLIENT_FEAT features) { +void bta_hf_client_send_at_brsf(tBTA_HF_CLIENT_CB* client_cb, tBTA_HF_CLIENT_FEAT features) { char buf[BTA_HF_CLIENT_AT_MAX_LEN]; int at_len; @@ -1857,25 +1773,26 @@ void bta_hf_client_send_at_cmer(tBTA_HF_CLIENT_CB* client_cb, bool activate) { log::verbose(""); - if (activate) + if (activate) { buf = "AT+CMER=3,0,0,1\r"; - else + } else { buf = "AT+CMER=3,0,0,0\r"; + } bta_hf_client_send_at(client_cb, BTA_HF_CLIENT_AT_CMER, buf, strlen(buf)); } -void bta_hf_client_send_at_chld(tBTA_HF_CLIENT_CB* client_cb, char cmd, - uint32_t idx) { +void bta_hf_client_send_at_chld(tBTA_HF_CLIENT_CB* client_cb, char cmd, uint32_t idx) { char buf[BTA_HF_CLIENT_AT_MAX_LEN]; int at_len; log::verbose(""); - if (idx > 0) + if (idx > 0) { at_len = snprintf(buf, sizeof(buf), "AT+CHLD=%c%u\r", cmd, idx); - else + } else { at_len = snprintf(buf, sizeof(buf), "AT+CHLD=%c\r", cmd); + } if (at_len < 0) { log::error("AT command Framing error"); @@ -1893,8 +1810,7 @@ void bta_hf_client_send_at_bind(tBTA_HF_CLIENT_CB* client_cb, int step) { switch (step) { case 0: // List HF supported indicators - if (osi_property_get_bool(kPropertyEnhancedDrivingIndicatorEnabled, - false)) { + if (osi_property_get_bool(kPropertyEnhancedDrivingIndicatorEnabled, false)) { buf = "AT+BIND=1,2\r"; } else { buf = "AT+BIND=2\r"; @@ -1942,10 +1858,11 @@ void bta_hf_client_send_at_clip(tBTA_HF_CLIENT_CB* client_cb, bool activate) { log::verbose(""); - if (activate) + if (activate) { buf = "AT+CLIP=1\r"; - else + } else { buf = "AT+CLIP=0\r"; + } bta_hf_client_send_at(client_cb, BTA_HF_CLIENT_AT_CLIP, buf, strlen(buf)); } @@ -1955,10 +1872,11 @@ void bta_hf_client_send_at_ccwa(tBTA_HF_CLIENT_CB* client_cb, bool activate) { log::verbose(""); - if (activate) + if (activate) { buf = "AT+CCWA=1\r"; - else + } else { buf = "AT+CCWA=0\r"; + } bta_hf_client_send_at(client_cb, BTA_HF_CLIENT_AT_CCWA, buf, strlen(buf)); } @@ -1968,10 +1886,11 @@ void bta_hf_client_send_at_cmee(tBTA_HF_CLIENT_CB* client_cb, bool activate) { log::verbose(""); - if (activate) + if (activate) { buf = "AT+CMEE=1\r"; - else + } else { buf = "AT+CMEE=0\r"; + } bta_hf_client_send_at(client_cb, BTA_HF_CLIENT_AT_CMEE, buf, strlen(buf)); } @@ -1981,10 +1900,11 @@ void bta_hf_client_send_at_cops(tBTA_HF_CLIENT_CB* client_cb, bool query) { log::verbose(""); - if (query) + if (query) { buf = "AT+COPS?\r"; - else + } else { buf = "AT+COPS=3,0\r"; + } bta_hf_client_send_at(client_cb, BTA_HF_CLIENT_AT_COPS, buf, strlen(buf)); } @@ -2004,10 +1924,11 @@ void bta_hf_client_send_at_bvra(tBTA_HF_CLIENT_CB* client_cb, bool enable) { log::verbose(""); - if (enable) + if (enable) { buf = "AT+BVRA=1\r"; - else + } else { buf = "AT+BVRA=0\r"; + } bta_hf_client_send_at(client_cb, BTA_HF_CLIENT_AT_BVRA, buf, strlen(buf)); } @@ -2042,8 +1963,7 @@ void bta_hf_client_send_at_vgm(tBTA_HF_CLIENT_CB* client_cb, uint32_t volume) { bta_hf_client_send_at(client_cb, BTA_HF_CLIENT_AT_VGM, buf, at_len); } -void bta_hf_client_send_at_atd(tBTA_HF_CLIENT_CB* client_cb, char* number, - uint32_t memory) { +void bta_hf_client_send_at_atd(tBTA_HF_CLIENT_CB* client_cb, char* number, uint32_t memory) { char buf[BTA_HF_CLIENT_AT_MAX_LEN]; int at_len; @@ -2099,8 +2019,7 @@ void bta_hf_client_send_at_chup(tBTA_HF_CLIENT_CB* client_cb) { bta_hf_client_send_at(client_cb, BTA_HF_CLIENT_AT_CHUP, buf, strlen(buf)); } -void bta_hf_client_send_at_btrh(tBTA_HF_CLIENT_CB* client_cb, bool query, - uint32_t val) { +void bta_hf_client_send_at_btrh(tBTA_HF_CLIENT_CB* client_cb, bool query, uint32_t val) { char buf[BTA_HF_CLIENT_AT_MAX_LEN]; int at_len; @@ -2200,8 +2119,8 @@ void bta_hf_client_send_at_bia(tBTA_HF_CLIENT_CB* client_cb) { at_len = snprintf(buf, sizeof(buf), "AT+BIA="); - const int32_t position = osi_property_get_int32( - "bluetooth.headset_client.disable_indicator.position", -1); + const int32_t position = + osi_property_get_int32("bluetooth.headset_client.disable_indicator.position", -1); for (i = 0; i < BTA_HF_CLIENT_AT_INDICATOR_COUNT; i++) { int sup = client_cb->at_cb.indicator_lookup[i] == -1 ? 0 : 1; @@ -2227,8 +2146,7 @@ void bta_hf_client_send_at_bia(tBTA_HF_CLIENT_CB* client_cb) { bta_hf_client_send_at(client_cb, BTA_HF_CLIENT_AT_BIA, buf, at_len); } -void bta_hf_client_send_at_vendor_specific_cmd(tBTA_HF_CLIENT_CB* client_cb, - const char* str) { +void bta_hf_client_send_at_vendor_specific_cmd(tBTA_HF_CLIENT_CB* client_cb, const char* str) { char buf[BTA_HF_CLIENT_AT_MAX_LEN]; log::verbose(""); @@ -2242,12 +2160,10 @@ void bta_hf_client_send_at_vendor_specific_cmd(tBTA_HF_CLIENT_CB* client_cb, buf[at_len - 1] = '\r'; - bta_hf_client_send_at(client_cb, BTA_HF_CLIENT_AT_VENDOR_SPECIFIC, buf, - at_len); + bta_hf_client_send_at(client_cb, BTA_HF_CLIENT_AT_VENDOR_SPECIFIC, buf, at_len); } -void bta_hf_client_send_at_android(tBTA_HF_CLIENT_CB* client_cb, - const char* str) { +void bta_hf_client_send_at_android(tBTA_HF_CLIENT_CB* client_cb, const char* str) { char buf[BTA_HF_CLIENT_AT_MAX_LEN]; int at_len; @@ -2289,8 +2205,7 @@ void bta_hf_client_at_reset(tBTA_HF_CLIENT_CB* client_cb) { } void bta_hf_client_send_at_cmd(tBTA_HF_CLIENT_DATA* p_data) { - tBTA_HF_CLIENT_CB* client_cb = - bta_hf_client_find_cb_by_handle(p_data->hdr.layer_specific); + tBTA_HF_CLIENT_CB* client_cb = bta_hf_client_find_cb_by_handle(p_data->hdr.layer_specific); if (!client_cb) { log::error("cb not found for handle {}", p_data->hdr.layer_specific); return; @@ -2312,13 +2227,11 @@ void bta_hf_client_send_at_cmd(tBTA_HF_CLIENT_DATA* p_data) { break; case BTA_HF_CLIENT_AT_CMD_CHLD: /* expects ascii code for command */ - bta_hf_client_send_at_chld(client_cb, '0' + p_val->uint32_val1, - p_val->uint32_val2); + bta_hf_client_send_at_chld(client_cb, '0' + p_val->uint32_val1, p_val->uint32_val2); break; case BTA_HF_CLIENT_AT_CMD_BIEV: /* expects ascii code for command */ - bta_hf_client_send_at_biev(client_cb, p_val->uint32_val1, - p_val->uint32_val2); + bta_hf_client_send_at_biev(client_cb, p_val->uint32_val1, p_val->uint32_val2); break; case BTA_HF_CLIENT_AT_CMD_BCC: bta_hf_client_send_at_bcc(client_cb); @@ -2342,8 +2255,7 @@ void bta_hf_client_send_at_cmd(tBTA_HF_CLIENT_DATA* p_data) { bta_hf_client_send_at_vgs(client_cb, p_val->uint32_val1); break; case BTA_HF_CLIENT_AT_CMD_BVRA: - bta_hf_client_send_at_bvra(client_cb, - p_val->uint32_val1 == 0 ? false : true); + bta_hf_client_send_at_bvra(client_cb, p_val->uint32_val1 == 0 ? false : true); break; case BTA_HF_CLIENT_AT_CMD_CLCC: bta_hf_client_send_at_clcc(client_cb); @@ -2365,9 +2277,8 @@ void bta_hf_client_send_at_cmd(tBTA_HF_CLIENT_DATA* p_data) { break; default: log::error("Default case"); - snprintf(buf, BTA_HF_CLIENT_AT_MAX_LEN, - "Cmd %d 1st arg %u 2nd arg %u string arg %s", p_val->uint8_val, - p_val->uint32_val1, p_val->uint32_val2, p_val->str); + snprintf(buf, BTA_HF_CLIENT_AT_MAX_LEN, "Cmd %d 1st arg %u 2nd arg %u string arg %s", + p_val->uint8_val, p_val->uint32_val1, p_val->uint32_val2, p_val->str); log::error("AT buffer: {}", buf); break; } diff --git a/system/bta/hf_client/bta_hf_client_at.h b/system/bta/hf_client/bta_hf_client_at.h index 11a0d0b0d38..e4d4b2342ee 100644 --- a/system/bta/hf_client/bta_hf_client_at.h +++ b/system/bta/hf_client/bta_hf_client_at.h @@ -22,6 +22,7 @@ ****************************************************************************/ #include + #include "osi/include/alarm.h" /* ASCII character string of arguments to the AT command */ @@ -46,8 +47,7 @@ typedef struct queued_at_cmd tBTA_HF_CLIENT_AT_QCMD; /* AT command parsing control block */ typedef struct { - char buf[BTA_HF_CLIENT_AT_PARSER_MAX_LEN + - 1]; /* extra byte to always have \0 at the end */ + char buf[BTA_HF_CLIENT_AT_PARSER_MAX_LEN + 1]; /* extra byte to always have \0 at the end */ unsigned int offset; tBTA_HF_CLIENT_AT_CMD current_cmd; tBTA_HF_CLIENT_AT_QCMD* queued_cmd; diff --git a/system/bta/hf_client/bta_hf_client_int.h b/system/bta/hf_client/bta_hf_client_int.h index 121a543b8f6..9c3dc56044e 100644 --- a/system/bta/hf_client/bta_hf_client_int.h +++ b/system/bta/hf_client/bta_hf_client_int.h @@ -169,30 +169,28 @@ enum { /* type for HF control block */ typedef struct { // Fields useful for particular control block. - uint8_t handle; /* Handle of the control block to be - used by upper layer */ - RawAddress peer_addr; /* peer bd address */ - tSDP_DISCOVERY_DB* p_disc_db; /* pointer to discovery database */ - uint16_t conn_handle; /* RFCOMM handle of connected service */ - tBTA_HF_CLIENT_PEER_FEAT peer_features; /* peer device features */ - tBTA_HF_CLIENT_CHLD_FEAT chld_features; /* call handling features */ - uint16_t peer_version; /* profile version of peer device */ - uint8_t peer_scn; /* peer scn */ - uint8_t role; /* initiator/acceptor role */ - uint16_t sco_idx; /* SCO handle */ - uint8_t sco_state; /* SCO state variable */ - bool sco_close_rfc; /* true if also close RFCOMM after SCO */ - tBTM_SCO_CODEC_TYPE negotiated_codec; /* negotiated codec */ - bool svc_conn; /* set to true when service level connection is up */ - bool send_at_reply; /* set to true to notify framework about AT results */ - tBTA_HF_CLIENT_AT_CB at_cb; /* AT Parser control block */ - uint8_t state; /* state machine state */ - bool is_allocated; /* if the control block is already allocated */ - alarm_t* collision_timer; /* Collision timer */ - std::unordered_set - peer_hf_indicators; /* peer supported hf indicator indices (HFP1.7) */ - std::unordered_set - enabled_hf_indicators; /* enabled hf indicator indices (HFP1.7) */ + uint8_t handle; /* Handle of the control block to be + used by upper layer */ + RawAddress peer_addr; /* peer bd address */ + tSDP_DISCOVERY_DB* p_disc_db; /* pointer to discovery database */ + uint16_t conn_handle; /* RFCOMM handle of connected service */ + tBTA_HF_CLIENT_PEER_FEAT peer_features; /* peer device features */ + tBTA_HF_CLIENT_CHLD_FEAT chld_features; /* call handling features */ + uint16_t peer_version; /* profile version of peer device */ + uint8_t peer_scn; /* peer scn */ + uint8_t role; /* initiator/acceptor role */ + uint16_t sco_idx; /* SCO handle */ + uint8_t sco_state; /* SCO state variable */ + bool sco_close_rfc; /* true if also close RFCOMM after SCO */ + tBTM_SCO_CODEC_TYPE negotiated_codec; /* negotiated codec */ + bool svc_conn; /* set to true when service level connection is up */ + bool send_at_reply; /* set to true to notify framework about AT results */ + tBTA_HF_CLIENT_AT_CB at_cb; /* AT Parser control block */ + uint8_t state; /* state machine state */ + bool is_allocated; /* if the control block is already allocated */ + alarm_t* collision_timer; /* Collision timer */ + std::unordered_set peer_hf_indicators; /* peer supported hf indicator indices (HFP1.7) */ + std::unordered_set enabled_hf_indicators; /* enabled hf indicator indices (HFP1.7) */ } tBTA_HF_CLIENT_CB; typedef struct { @@ -223,14 +221,12 @@ tBTA_HF_CLIENT_CB* bta_hf_client_find_cb_by_sco_handle(uint16_t handle); bool bta_hf_client_hdl_event(const BT_HDR_RIGID* p_msg); void bta_hf_client_sm_execute(uint16_t event, tBTA_HF_CLIENT_DATA* p_data); void bta_hf_client_slc_seq(tBTA_HF_CLIENT_CB* client_cb, bool error); -bool bta_hf_client_allocate_handle(const RawAddress& bd_addr, - uint16_t* p_handle); +bool bta_hf_client_allocate_handle(const RawAddress& bd_addr, uint16_t* p_handle); void bta_hf_client_app_callback(uint16_t event, tBTA_HF_CLIENT* data); -void bta_hf_client_collision_cback(tBTA_SYS_CONN_STATUS status, tBTA_SYS_ID id, - uint8_t app_id, const RawAddress& peer_addr); +void bta_hf_client_collision_cback(tBTA_SYS_CONN_STATUS status, tBTA_SYS_ID id, uint8_t app_id, + const RawAddress& peer_addr); void bta_hf_client_resume_open(tBTA_HF_CLIENT_CB* client_cb); -tBTA_STATUS bta_hf_client_api_enable(tBTA_HF_CLIENT_CBACK* p_cback, - tBTA_HF_CLIENT_FEAT features, +tBTA_STATUS bta_hf_client_api_enable(tBTA_HF_CLIENT_CBACK* p_cback, tBTA_HF_CLIENT_FEAT features, const char* p_service_name); void bta_hf_client_api_disable(void); @@ -238,11 +234,9 @@ void bta_hf_client_dump_statistics(int fd); void bta_hf_client_cb_arr_init(void); /* SDP functions */ -bool bta_hf_client_add_record(const char* p_service_name, uint8_t scn, - tBTA_HF_CLIENT_FEAT features, +bool bta_hf_client_add_record(const char* p_service_name, uint8_t scn, tBTA_HF_CLIENT_FEAT features, uint32_t sdp_handle); -void bta_hf_client_create_record(tBTA_HF_CLIENT_CB_ARR* client_cb, - const char* p_data); +void bta_hf_client_create_record(tBTA_HF_CLIENT_CB_ARR* client_cb, const char* p_data); void bta_hf_client_del_record(tBTA_HF_CLIENT_CB_ARR* client_cb); bool bta_hf_client_sdp_find_attr(tBTA_HF_CLIENT_CB* client_cb); void bta_hf_client_do_disc(tBTA_HF_CLIENT_CB* client_cb); @@ -265,18 +259,14 @@ void bta_hf_client_sco_shutdown(tBTA_HF_CLIENT_CB* client_cb); void bta_hf_client_cback_sco(tBTA_HF_CLIENT_CB* client_cb, uint8_t event); /* AT command functions */ -void bta_hf_client_at_parse(tBTA_HF_CLIENT_CB* client_cb, char* buf, - unsigned int len); -void bta_hf_client_send_at_brsf(tBTA_HF_CLIENT_CB* client_cb, - tBTA_HF_CLIENT_FEAT features); +void bta_hf_client_at_parse(tBTA_HF_CLIENT_CB* client_cb, char* buf, unsigned int len); +void bta_hf_client_send_at_brsf(tBTA_HF_CLIENT_CB* client_cb, tBTA_HF_CLIENT_FEAT features); void bta_hf_client_send_at_bac(tBTA_HF_CLIENT_CB* client_cb); void bta_hf_client_send_at_cind(tBTA_HF_CLIENT_CB* client_cb, bool status); void bta_hf_client_send_at_cmer(tBTA_HF_CLIENT_CB* client_cb, bool activate); -void bta_hf_client_send_at_chld(tBTA_HF_CLIENT_CB* client_cb, char cmd, - uint32_t idx); +void bta_hf_client_send_at_chld(tBTA_HF_CLIENT_CB* client_cb, char cmd, uint32_t idx); void bta_hf_client_send_at_bind(tBTA_HF_CLIENT_CB* client_cb, int step); -void bta_hf_client_send_at_biev(tBTA_HF_CLIENT_CB* client_cb, int ind_id, - int value); +void bta_hf_client_send_at_biev(tBTA_HF_CLIENT_CB* client_cb, int ind_id, int value); void bta_hf_client_send_at_clip(tBTA_HF_CLIENT_CB* client_cb, bool activate); void bta_hf_client_send_at_ccwa(tBTA_HF_CLIENT_CB* client_cb, bool activate); void bta_hf_client_send_at_cmee(tBTA_HF_CLIENT_CB* client_cb, bool activate); @@ -285,13 +275,11 @@ void bta_hf_client_send_at_clcc(tBTA_HF_CLIENT_CB* client_cb); void bta_hf_client_send_at_bvra(tBTA_HF_CLIENT_CB* client_cb, bool enable); void bta_hf_client_send_at_vgs(tBTA_HF_CLIENT_CB* client_cb, uint32_t volume); void bta_hf_client_send_at_vgm(tBTA_HF_CLIENT_CB* client_cb, uint32_t volume); -void bta_hf_client_send_at_atd(tBTA_HF_CLIENT_CB* client_cb, char* number, - uint32_t memory); +void bta_hf_client_send_at_atd(tBTA_HF_CLIENT_CB* client_cb, char* number, uint32_t memory); void bta_hf_client_send_at_bldn(tBTA_HF_CLIENT_CB* client_cb); void bta_hf_client_send_at_ata(tBTA_HF_CLIENT_CB* client_cb); void bta_hf_client_send_at_chup(tBTA_HF_CLIENT_CB* client_cb); -void bta_hf_client_send_at_btrh(tBTA_HF_CLIENT_CB* client_cb, bool query, - uint32_t val); +void bta_hf_client_send_at_btrh(tBTA_HF_CLIENT_CB* client_cb, bool query, uint32_t val); void bta_hf_client_send_at_vts(tBTA_HF_CLIENT_CB* client_cb, char code); void bta_hf_client_send_at_bcc(tBTA_HF_CLIENT_CB* client_cb); void bta_hf_client_send_at_bcs(tBTA_HF_CLIENT_CB* client_cb, uint32_t codec); @@ -303,19 +291,16 @@ void bta_hf_client_send_at_bia(tBTA_HF_CLIENT_CB* client_cb); /* AT API Functions */ void bta_hf_client_at_init(tBTA_HF_CLIENT_CB* client_cb); void bta_hf_client_at_reset(tBTA_HF_CLIENT_CB* client_cb); -void bta_hf_client_ind(tBTA_HF_CLIENT_CB* client_cb, - tBTA_HF_CLIENT_IND_TYPE type, uint16_t value); -void bta_hf_client_evt_val(tBTA_HF_CLIENT_CB* client_cb, - tBTA_HF_CLIENT_EVT type, uint16_t value); +void bta_hf_client_ind(tBTA_HF_CLIENT_CB* client_cb, tBTA_HF_CLIENT_IND_TYPE type, uint16_t value); +void bta_hf_client_evt_val(tBTA_HF_CLIENT_CB* client_cb, tBTA_HF_CLIENT_EVT type, uint16_t value); void bta_hf_client_operator_name(tBTA_HF_CLIENT_CB* client_name, char* name); void bta_hf_client_clip(tBTA_HF_CLIENT_CB* client_cb, char* number); void bta_hf_client_ccwa(tBTA_HF_CLIENT_CB* client_cb, char* number); -void bta_hf_client_at_result(tBTA_HF_CLIENT_CB* client_cb, - tBTA_HF_CLIENT_AT_RESULT_TYPE type, uint16_t cme); -void bta_hf_client_clcc(tBTA_HF_CLIENT_CB* client_cb, uint32_t idx, - bool incoming, uint8_t status, bool mpty, char* number); -void bta_hf_client_cnum(tBTA_HF_CLIENT_CB* client_cb, char* number, - uint16_t service); +void bta_hf_client_at_result(tBTA_HF_CLIENT_CB* client_cb, tBTA_HF_CLIENT_AT_RESULT_TYPE type, + uint16_t cme); +void bta_hf_client_clcc(tBTA_HF_CLIENT_CB* client_cb, uint32_t idx, bool incoming, uint8_t status, + bool mpty, char* number); +void bta_hf_client_cnum(tBTA_HF_CLIENT_CB* client_cb, char* number, uint16_t service); void bta_hf_client_binp(tBTA_HF_CLIENT_CB* client_cb, char* number); /* Action functions */ diff --git a/system/bta/hf_client/bta_hf_client_main.cc b/system/bta/hf_client/bta_hf_client_main.cc index 8f59c560d0e..5317c064878 100644 --- a/system/bta/hf_client/bta_hf_client_main.cc +++ b/system/bta/hf_client/bta_hf_client_main.cc @@ -79,27 +79,27 @@ typedef void (*tBTA_HF_CLIENT_ACTION)(tBTA_HF_CLIENT_DATA* p_data); /* action functions table, indexed with action enum */ const tBTA_HF_CLIENT_ACTION bta_hf_client_action[] = { - /* BTA_HF_CLIENT_RFC_DO_CLOSE */ bta_hf_client_rfc_do_close, - /* BTA_HF_CLIENT_START_CLOSE */ bta_hf_client_start_close, - /* BTA_HF_CLIENT_START_OPEN */ bta_hf_client_start_open, - /* BTA_HF_CLIENT_RFC_ACP_OPEN */ bta_hf_client_rfc_acp_open, - /* BTA_HF_CLIENT_SCO_LISTEN */ NULL, - /* BTA_HF_CLIENT_SCO_CONN_OPEN */ bta_hf_client_sco_conn_open, - /* BTA_HF_CLIENT_SCO_CONN_CLOSE*/ bta_hf_client_sco_conn_close, - /* BTA_HF_CLIENT_SCO_OPEN */ bta_hf_client_sco_open, - /* BTA_HF_CLIENT_SCO_CLOSE */ bta_hf_client_sco_close, - /* BTA_HF_CLIENT_FREE_DB */ bta_hf_client_free_db, - /* BTA_HF_CLIENT_OPEN_FAIL */ bta_hf_client_open_fail, - /* BTA_HF_CLIENT_RFC_OPEN */ bta_hf_client_rfc_open, - /* BTA_HF_CLIENT_RFC_FAIL */ bta_hf_client_rfc_fail, - /* BTA_HF_CLIENT_DISC_INT_RES */ bta_hf_client_disc_int_res, - /* BTA_HF_CLIENT_RFC_DO_OPEN */ bta_hf_client_rfc_do_open, - /* BTA_HF_CLIENT_DISC_FAIL */ bta_hf_client_disc_fail, - /* BTA_HF_CLIENT_RFC_CLOSE */ bta_hf_client_rfc_close, - /* BTA_HF_CLIENT_RFC_DATA */ bta_hf_client_rfc_data, - /* BTA_HF_CLIENT_DISC_ACP_RES */ bta_hf_client_disc_acp_res, - /* BTA_HF_CLIENT_SVC_CONN_OPEN */ bta_hf_client_svc_conn_open, - /* BTA_HF_CLIENT_SEND_AT_CMD */ bta_hf_client_send_at_cmd, + /* BTA_HF_CLIENT_RFC_DO_CLOSE */ bta_hf_client_rfc_do_close, + /* BTA_HF_CLIENT_START_CLOSE */ bta_hf_client_start_close, + /* BTA_HF_CLIENT_START_OPEN */ bta_hf_client_start_open, + /* BTA_HF_CLIENT_RFC_ACP_OPEN */ bta_hf_client_rfc_acp_open, + /* BTA_HF_CLIENT_SCO_LISTEN */ NULL, + /* BTA_HF_CLIENT_SCO_CONN_OPEN */ bta_hf_client_sco_conn_open, + /* BTA_HF_CLIENT_SCO_CONN_CLOSE*/ bta_hf_client_sco_conn_close, + /* BTA_HF_CLIENT_SCO_OPEN */ bta_hf_client_sco_open, + /* BTA_HF_CLIENT_SCO_CLOSE */ bta_hf_client_sco_close, + /* BTA_HF_CLIENT_FREE_DB */ bta_hf_client_free_db, + /* BTA_HF_CLIENT_OPEN_FAIL */ bta_hf_client_open_fail, + /* BTA_HF_CLIENT_RFC_OPEN */ bta_hf_client_rfc_open, + /* BTA_HF_CLIENT_RFC_FAIL */ bta_hf_client_rfc_fail, + /* BTA_HF_CLIENT_DISC_INT_RES */ bta_hf_client_disc_int_res, + /* BTA_HF_CLIENT_RFC_DO_OPEN */ bta_hf_client_rfc_do_open, + /* BTA_HF_CLIENT_DISC_FAIL */ bta_hf_client_disc_fail, + /* BTA_HF_CLIENT_RFC_CLOSE */ bta_hf_client_rfc_close, + /* BTA_HF_CLIENT_RFC_DATA */ bta_hf_client_rfc_data, + /* BTA_HF_CLIENT_DISC_ACP_RES */ bta_hf_client_disc_acp_res, + /* BTA_HF_CLIENT_SVC_CONN_OPEN */ bta_hf_client_svc_conn_open, + /* BTA_HF_CLIENT_SEND_AT_CMD */ bta_hf_client_send_at_cmd, }; /* state table information */ @@ -109,146 +109,112 @@ const tBTA_HF_CLIENT_ACTION bta_hf_client_action[] = { /* state table for init state */ const uint8_t bta_hf_client_st_init[][BTA_HF_CLIENT_NUM_COLS] = { - /* Event Action 1 Action 2 - Next state */ - /* API_OPEN_EVT */ {BTA_HF_CLIENT_START_OPEN, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_OPENING_ST}, - /* API_CLOSE_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_INIT_ST}, - /* API_AUDIO_OPEN_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_INIT_ST}, - /* API_AUDIO_CLOSE_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_INIT_ST}, - /* RFC_OPEN_EVT */ {BTA_HF_CLIENT_RFC_ACP_OPEN, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_OPEN_ST}, - /* RFC_CLOSE_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_INIT_ST}, - /* RFC_SRV_CLOSE_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_INIT_ST}, - /* RFC_DATA_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_INIT_ST}, - /* DISC_ACP_RES_EVT */ {BTA_HF_CLIENT_FREE_DB, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_INIT_ST}, - /* DISC_INT_RES_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_INIT_ST}, - /* DISC_OK_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_INIT_ST}, - /* DISC_FAIL_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_INIT_ST}, - /* SCO_OPEN_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_INIT_ST}, - /* SCO_CLOSE_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_INIT_ST}, - /* SEND_AT_CMD_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_INIT_ST}, + /* Event Action 1 Action 2 + Next state */ + /* API_OPEN_EVT */ {BTA_HF_CLIENT_START_OPEN, BTA_HF_CLIENT_IGNORE, + BTA_HF_CLIENT_OPENING_ST}, + /* API_CLOSE_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_INIT_ST}, + /* API_AUDIO_OPEN_EVT */ + {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_INIT_ST}, + /* API_AUDIO_CLOSE_EVT */ + {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_INIT_ST}, + /* RFC_OPEN_EVT */ + {BTA_HF_CLIENT_RFC_ACP_OPEN, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_OPEN_ST}, + /* RFC_CLOSE_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_INIT_ST}, + /* RFC_SRV_CLOSE_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_INIT_ST}, + /* RFC_DATA_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_INIT_ST}, + /* DISC_ACP_RES_EVT */ {BTA_HF_CLIENT_FREE_DB, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_INIT_ST}, + /* DISC_INT_RES_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_INIT_ST}, + /* DISC_OK_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_INIT_ST}, + /* DISC_FAIL_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_INIT_ST}, + /* SCO_OPEN_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_INIT_ST}, + /* SCO_CLOSE_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_INIT_ST}, + /* SEND_AT_CMD_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_INIT_ST}, }; /* state table for opening state */ const uint8_t bta_hf_client_st_opening[][BTA_HF_CLIENT_NUM_COLS] = { - /* Event Action 1 Action 2 - Next state */ - /* API_OPEN_EVT */ {BTA_HF_CLIENT_OPEN_FAIL, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_OPENING_ST}, - /* API_CLOSE_EVT */ {BTA_HF_CLIENT_RFC_DO_CLOSE, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_CLOSING_ST}, - /* API_AUDIO_OPEN_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_OPENING_ST}, - /* API_AUDIO_CLOSE_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_OPENING_ST}, - /* RFC_OPEN_EVT */ {BTA_HF_CLIENT_RFC_OPEN, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_OPEN_ST}, - /* RFC_CLOSE_EVT */ {BTA_HF_CLIENT_RFC_FAIL, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_INIT_ST}, - /* RFC_SRV_CLOSE_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_OPENING_ST}, - /* RFC_DATA_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_OPENING_ST}, - /* DISC_ACP_RES_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_OPENING_ST}, - /* DISC_INT_RES_EVT */ {BTA_HF_CLIENT_DISC_INT_RES, BTA_HF_CLIENT_IGNORE, + /* Event Action 1 Action 2 + Next state */ + /* API_OPEN_EVT */ {BTA_HF_CLIENT_OPEN_FAIL, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_OPENING_ST}, - /* DISC_OK_EVT */ {BTA_HF_CLIENT_RFC_DO_OPEN, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_OPENING_ST}, - /* DISC_FAIL_EVT */ {BTA_HF_CLIENT_DISC_FAIL, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_INIT_ST}, - /* SCO_OPEN_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_OPENING_ST}, - /* SCO_CLOSE_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_OPENING_ST}, - /* SEND_AT_CMD_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_OPENING_ST}, + /* API_CLOSE_EVT */ + {BTA_HF_CLIENT_RFC_DO_CLOSE, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_CLOSING_ST}, + /* API_AUDIO_OPEN_EVT */ + {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_OPENING_ST}, + /* API_AUDIO_CLOSE_EVT */ + {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_OPENING_ST}, + /* RFC_OPEN_EVT */ {BTA_HF_CLIENT_RFC_OPEN, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_OPEN_ST}, + /* RFC_CLOSE_EVT */ {BTA_HF_CLIENT_RFC_FAIL, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_INIT_ST}, + /* RFC_SRV_CLOSE_EVT */ + {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_OPENING_ST}, + /* RFC_DATA_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_OPENING_ST}, + /* DISC_ACP_RES_EVT */ + {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_OPENING_ST}, + /* DISC_INT_RES_EVT */ + {BTA_HF_CLIENT_DISC_INT_RES, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_OPENING_ST}, + /* DISC_OK_EVT */ + {BTA_HF_CLIENT_RFC_DO_OPEN, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_OPENING_ST}, + /* DISC_FAIL_EVT */ {BTA_HF_CLIENT_DISC_FAIL, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_INIT_ST}, + /* SCO_OPEN_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_OPENING_ST}, + /* SCO_CLOSE_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_OPENING_ST}, + /* SEND_AT_CMD_EVT */ + {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_OPENING_ST}, }; /* state table for open state */ const uint8_t bta_hf_client_st_open[][BTA_HF_CLIENT_NUM_COLS] = { - /* Event Action 1 Action 2 - Next state */ - /* API_OPEN_EVT */ {BTA_HF_CLIENT_OPEN_FAIL, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_OPEN_ST}, - /* API_CLOSE_EVT */ {BTA_HF_CLIENT_START_CLOSE, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_CLOSING_ST}, - /* API_AUDIO_OPEN_EVT */ {BTA_HF_CLIENT_SCO_OPEN, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_OPEN_ST}, - /* API_AUDIO_CLOSE_EVT */ {BTA_HF_CLIENT_SCO_CLOSE, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_OPEN_ST}, - /* RFC_OPEN_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_OPEN_ST}, - /* RFC_CLOSE_EVT */ {BTA_HF_CLIENT_RFC_CLOSE, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_INIT_ST}, - /* RFC_SRV_CLOSE_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_OPEN_ST}, - /* RFC_DATA_EVT */ {BTA_HF_CLIENT_RFC_DATA, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_OPEN_ST}, - /* DISC_ACP_RES_EVT */ {BTA_HF_CLIENT_DISC_ACP_RES, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_OPEN_ST}, - /* DISC_INT_RES_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_OPEN_ST}, - /* DISC_OK_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_OPEN_ST}, - /* DISC_FAIL_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_OPEN_ST}, - /* SCO_OPEN_EVT */ {BTA_HF_CLIENT_SCO_CONN_OPEN, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_OPEN_ST}, - /* SCO_CLOSE_EVT */ {BTA_HF_CLIENT_SCO_CONN_CLOSE, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_OPEN_ST}, - /* SEND_AT_CMD_EVT */ {BTA_HF_CLIENT_SEND_AT_CMD, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_OPEN_ST}, + /* Event Action 1 Action 2 + Next state */ + /* API_OPEN_EVT */ {BTA_HF_CLIENT_OPEN_FAIL, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_OPEN_ST}, + /* API_CLOSE_EVT */ + {BTA_HF_CLIENT_START_CLOSE, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_CLOSING_ST}, + /* API_AUDIO_OPEN_EVT */ + {BTA_HF_CLIENT_SCO_OPEN, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_OPEN_ST}, + /* API_AUDIO_CLOSE_EVT */ + {BTA_HF_CLIENT_SCO_CLOSE, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_OPEN_ST}, + /* RFC_OPEN_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_OPEN_ST}, + /* RFC_CLOSE_EVT */ {BTA_HF_CLIENT_RFC_CLOSE, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_INIT_ST}, + /* RFC_SRV_CLOSE_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_OPEN_ST}, + /* RFC_DATA_EVT */ {BTA_HF_CLIENT_RFC_DATA, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_OPEN_ST}, + /* DISC_ACP_RES_EVT */ + {BTA_HF_CLIENT_DISC_ACP_RES, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_OPEN_ST}, + /* DISC_INT_RES_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_OPEN_ST}, + /* DISC_OK_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_OPEN_ST}, + /* DISC_FAIL_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_OPEN_ST}, + /* SCO_OPEN_EVT */ + {BTA_HF_CLIENT_SCO_CONN_OPEN, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_OPEN_ST}, + /* SCO_CLOSE_EVT */ + {BTA_HF_CLIENT_SCO_CONN_CLOSE, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_OPEN_ST}, + /* SEND_AT_CMD_EVT */ + {BTA_HF_CLIENT_SEND_AT_CMD, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_OPEN_ST}, }; /* state table for closing state */ const uint8_t bta_hf_client_st_closing[][BTA_HF_CLIENT_NUM_COLS] = { - /* Event Action 1 Action 2 - Next state */ - /* API_OPEN_EVT */ {BTA_HF_CLIENT_OPEN_FAIL, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_CLOSING_ST}, - /* API_CLOSE_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_CLOSING_ST}, - /* API_AUDIO_OPEN_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_CLOSING_ST}, - /* API_AUDIO_CLOSE_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_CLOSING_ST}, - /* RFC_OPEN_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_CLOSING_ST}, - /* RFC_CLOSE_EVT */ {BTA_HF_CLIENT_RFC_CLOSE, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_INIT_ST}, - /* RFC_SRV_CLOSE_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_CLOSING_ST}, - /* RFC_DATA_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_CLOSING_ST}, - /* DISC_ACP_RES_EVT */ {BTA_HF_CLIENT_FREE_DB, BTA_HF_CLIENT_IGNORE, + /* Event Action 1 Action 2 + Next state */ + /* API_OPEN_EVT */ {BTA_HF_CLIENT_OPEN_FAIL, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_CLOSING_ST}, - /* DISC_INT_RES_EVT */ {BTA_HF_CLIENT_FREE_DB, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_INIT_ST}, - /* DISC_OK_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_CLOSING_ST}, - /* DISC_FAIL_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_CLOSING_ST}, - /* SCO_OPEN_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_CLOSING_ST}, - /* SCO_CLOSE_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_CLOSING_ST}, - /* SEND_AT_CMD_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, - BTA_HF_CLIENT_CLOSING_ST}, + /* API_CLOSE_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_CLOSING_ST}, + /* API_AUDIO_OPEN_EVT */ + {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_CLOSING_ST}, + /* API_AUDIO_CLOSE_EVT */ + {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_CLOSING_ST}, + /* RFC_OPEN_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_CLOSING_ST}, + /* RFC_CLOSE_EVT */ {BTA_HF_CLIENT_RFC_CLOSE, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_INIT_ST}, + /* RFC_SRV_CLOSE_EVT */ + {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_CLOSING_ST}, + /* RFC_DATA_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_CLOSING_ST}, + /* DISC_ACP_RES_EVT */ + {BTA_HF_CLIENT_FREE_DB, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_CLOSING_ST}, + /* DISC_INT_RES_EVT */ {BTA_HF_CLIENT_FREE_DB, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_INIT_ST}, + /* DISC_OK_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_CLOSING_ST}, + /* DISC_FAIL_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_CLOSING_ST}, + /* SCO_OPEN_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_CLOSING_ST}, + /* SCO_CLOSE_EVT */ {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_CLOSING_ST}, + /* SEND_AT_CMD_EVT */ + {BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_IGNORE, BTA_HF_CLIENT_CLOSING_ST}, }; /* type for state table */ @@ -256,15 +222,14 @@ typedef const uint8_t (*tBTA_HF_CLIENT_ST_TBL)[BTA_HF_CLIENT_NUM_COLS]; /* state table */ const tBTA_HF_CLIENT_ST_TBL bta_hf_client_st_tbl[] = { - bta_hf_client_st_init, bta_hf_client_st_opening, bta_hf_client_st_open, - bta_hf_client_st_closing}; + bta_hf_client_st_init, bta_hf_client_st_opening, bta_hf_client_st_open, + bta_hf_client_st_closing}; /* HF Client control block */ tBTA_HF_CLIENT_CB_ARR bta_hf_client_cb_arr; /* Event handler for the state machine */ -static const tBTA_SYS_REG bta_hf_client_reg = {bta_hf_client_hdl_event, - BTA_HfClientDisable}; +static const tBTA_SYS_REG bta_hf_client_reg = {bta_hf_client_hdl_event, BTA_HfClientDisable}; /******************************************************************************* * @@ -370,9 +335,8 @@ static void bta_hf_client_collision_timer_cback(void* data) { * Returns void * ******************************************************************************/ -void bta_hf_client_collision_cback(tBTA_SYS_CONN_STATUS /* status */, - tBTA_SYS_ID id, uint8_t /* app_id */, - const RawAddress& peer_addr) { +void bta_hf_client_collision_cback(tBTA_SYS_CONN_STATUS /* status */, tBTA_SYS_ID id, + uint8_t /* app_id */, const RawAddress& peer_addr) { tBTA_HF_CLIENT_CB* client_cb = bta_hf_client_find_cb_by_bda(peer_addr); if (client_cb != NULL && client_cb->state == BTA_HF_CLIENT_OPENING_ST) { if (id == BTA_ID_SYS) /* ACL collision */ @@ -389,8 +353,7 @@ void bta_hf_client_collision_cback(tBTA_SYS_CONN_STATUS /* status */, /* Cancel SDP if it had been started. */ if (client_cb->p_disc_db) { - if (!get_legacy_stack_sdp_api()->service.SDP_CancelServiceSearch( - client_cb->p_disc_db)) { + if (!get_legacy_stack_sdp_api()->service.SDP_CancelServiceSearch(client_cb->p_disc_db)) { log::warn("Unable to cancel SDP service discovery peer:{}", peer_addr); } osi_free_and_reset((void**)&client_cb->p_disc_db); @@ -401,8 +364,7 @@ void bta_hf_client_collision_cback(tBTA_SYS_CONN_STATUS /* status */, bta_hf_client_start_server(); /* Start timer to handle connection opening restart */ - alarm_set_on_mloop(client_cb->collision_timer, - BTA_HF_CLIENT_COLLISION_TIMER_MS, + alarm_set_on_mloop(client_cb->collision_timer, BTA_HF_CLIENT_COLLISION_TIMER_MS, bta_hf_client_collision_timer_cback, (void*)client_cb); } } @@ -417,8 +379,7 @@ void bta_hf_client_collision_cback(tBTA_SYS_CONN_STATUS /* status */, * Returns void * ******************************************************************************/ -tBTA_STATUS bta_hf_client_api_enable(tBTA_HF_CLIENT_CBACK* p_cback, - tBTA_HF_CLIENT_FEAT features, +tBTA_STATUS bta_hf_client_api_enable(tBTA_HF_CLIENT_CBACK* p_cback, tBTA_HF_CLIENT_FEAT features, const char* p_service_name) { /* If already registered then return error */ if (bta_sys_is_register(BTA_ID_HS)) { @@ -446,9 +407,9 @@ tBTA_STATUS bta_hf_client_api_enable(tBTA_HF_CLIENT_CBACK* p_cback, /* Set the Audio service class bit */ tBTA_UTL_COD cod = { - .minor = BTM_COD_MINOR_UNCLASSIFIED, - .major = BTM_COD_MAJOR_UNCLASSIFIED, - .service = BTM_COD_SERVICE_AUDIO, + .minor = BTM_COD_MINOR_UNCLASSIFIED, + .major = BTM_COD_MAJOR_UNCLASSIFIED, + .service = BTM_COD_SERVICE_AUDIO, }; utl_set_device_class(&cod, BTA_UTL_SET_COD_SERVICE_CLASS); @@ -474,14 +435,14 @@ tBTA_STATUS bta_hf_client_api_enable(tBTA_HF_CLIENT_CBACK* p_cback, tBTA_HF_CLIENT_CB* bta_hf_client_find_cb_by_handle(uint16_t handle) { // Handles are limited from 1 through HF_CLIENT_MAX_DEVICES if (handle < 1 || handle > HF_CLIENT_MAX_DEVICES) { - log::error("handle out of range ({}, {}) {}", 1, HF_CLIENT_MAX_DEVICES, - handle); + log::error("handle out of range ({}, {}) {}", 1, HF_CLIENT_MAX_DEVICES, handle); return NULL; } // Check if the associated index is allocated. Index is (handle - 1). - if (bta_hf_client_cb_arr.cb[handle - 1].is_allocated) + if (bta_hf_client_cb_arr.cb[handle - 1].is_allocated) { return &(bta_hf_client_cb_arr.cb[handle - 1]); + } log::error("block not found for handle {}", handle); return NULL; @@ -508,8 +469,7 @@ tBTA_HF_CLIENT_CB* bta_hf_client_find_cb_by_bda(const RawAddress& peer_addr) { if (client_cb->is_allocated && peer_addr == client_cb->peer_addr) { return client_cb; } else { - log::warn("bdaddr mismatch for handle {} alloc {}", i, - client_cb->is_allocated); + log::warn("bdaddr mismatch for handle {} alloc {}", i, client_cb->is_allocated); } } log::error("block not found"); @@ -535,15 +495,13 @@ tBTA_HF_CLIENT_CB* bta_hf_client_find_cb_by_rfc_handle(uint16_t handle) { bool is_allocated = client_cb->is_allocated; uint16_t conn_handle = client_cb->conn_handle; - log::verbose("cb rfc_handle {} alloc {} conn_handle {}", handle, - is_allocated, conn_handle); + log::verbose("cb rfc_handle {} alloc {} conn_handle {}", handle, is_allocated, conn_handle); if (is_allocated && conn_handle == handle) { return client_cb; } - log::warn("no cb yet {} alloc {} conn_handle {}", handle, is_allocated, - conn_handle); + log::warn("no cb yet {} alloc {} conn_handle {}", handle, is_allocated, conn_handle); } log::error("no cb found for rfc handle {}", handle); @@ -591,8 +549,7 @@ tBTA_HF_CLIENT_CB* bta_hf_client_find_cb_by_sco_handle(uint16_t handle) { * Returns true if the creation of p_handle succeeded, false otherwise * ******************************************************************************/ -bool bta_hf_client_allocate_handle(const RawAddress& bd_addr, - uint16_t* p_handle) { +bool bta_hf_client_allocate_handle(const RawAddress& bd_addr, uint16_t* p_handle) { tBTA_HF_CLIENT_CB* existing_cb = bta_hf_client_find_cb_by_bda(bd_addr); if (existing_cb != NULL) { log::error("cannot allocate handle since BDADDR already exists"); @@ -688,8 +645,7 @@ void bta_hf_client_api_disable() { * ******************************************************************************/ bool bta_hf_client_hdl_event(const BT_HDR_RIGID* p_msg) { - log::verbose("{} (0x{:x})", bta_hf_client_evt_str(p_msg->event), - p_msg->event); + log::verbose("{} (0x{:x})", bta_hf_client_evt_str(p_msg->event), p_msg->event); bta_hf_client_sm_execute(p_msg->event, (tBTA_HF_CLIENT_DATA*)p_msg); return true; } @@ -705,8 +661,7 @@ bool bta_hf_client_hdl_event(const BT_HDR_RIGID* p_msg) { * ******************************************************************************/ void bta_hf_client_sm_execute(uint16_t event, tBTA_HF_CLIENT_DATA* p_data) { - tBTA_HF_CLIENT_CB* client_cb = - bta_hf_client_find_cb_by_handle(p_data->hdr.layer_specific); + tBTA_HF_CLIENT_CB* client_cb = bta_hf_client_find_cb_by_handle(p_data->hdr.layer_specific); if (client_cb == NULL) { log::error("cb not found for handle {}", p_data->hdr.layer_specific); return; @@ -722,9 +677,8 @@ void bta_hf_client_sm_execute(uint16_t event, tBTA_HF_CLIENT_DATA* p_data) { /* Ignore displaying of AT results when not connected (Ignored in state * machine) */ if (client_cb->state == BTA_HF_CLIENT_OPEN_ST) { - log::verbose("HF Client evt : State {} ({}), Event 0x{:04x} ({})", - client_cb->state, bta_hf_client_state_str(client_cb->state), - event, bta_hf_client_evt_str(event)); + log::verbose("HF Client evt : State {} ({}), Event 0x{:04x} ({})", client_cb->state, + bta_hf_client_state_str(client_cb->state), event, bta_hf_client_evt_str(event)); } event &= 0x00FF; @@ -751,8 +705,8 @@ void bta_hf_client_sm_execute(uint16_t event, tBTA_HF_CLIENT_DATA* p_data) { /* If the state has changed then notify the app of the corresponding change */ if (in_state != client_cb->state) { - log::verbose("notifying state change to {} -> {} device {}", in_state, - client_cb->state, client_cb->peer_addr); + log::verbose("notifying state change to {} -> {} device {}", in_state, client_cb->state, + client_cb->peer_addr); tBTA_HF_CLIENT evt; memset(&evt, 0, sizeof(evt)); evt.bd_addr = client_cb->peer_addr; @@ -766,9 +720,8 @@ void bta_hf_client_sm_execute(uint16_t event, tBTA_HF_CLIENT_DATA* p_data) { } } - log::verbose("device {} state change: [{}] -> [{}] after Event [{}]", - client_cb->peer_addr, bta_hf_client_state_str(in_state), - bta_hf_client_state_str(client_cb->state), + log::verbose("device {} state change: [{}] -> [{}] after Event [{}]", client_cb->peer_addr, + bta_hf_client_state_str(in_state), bta_hf_client_state_str(client_cb->state), bta_hf_client_evt_str(in_event)); } @@ -801,9 +754,8 @@ void bta_hf_client_slc_seq(tBTA_HF_CLIENT_CB* client_cb, bool error) { if (error) { /* SLC establishment error, sent close rfcomm event */ - log::error( - "HFPClient: Failed to create SLC due to AT error, disconnecting ({})", - client_cb->at_cb.current_cmd); + log::error("HFPClient: Failed to create SLC due to AT error, disconnecting ({})", + client_cb->at_cb.current_cmd); tBTA_HF_CLIENT_DATA msg; msg.hdr.layer_specific = client_cb->handle; @@ -888,9 +840,9 @@ void bta_hf_client_slc_seq(tBTA_HF_CLIENT_CB* client_cb, bool error) { default: { /* If happen there is a bug in SLC creation procedure... */ log::error( - "HFPClient: Failed to create SLCdue to unexpected AT command, " - "disconnecting ({})", - client_cb->at_cb.current_cmd); + "HFPClient: Failed to create SLCdue to unexpected AT command, " + "disconnecting ({})", + client_cb->at_cb.current_cmd); tBTA_HF_CLIENT_DATA msg; msg.hdr.layer_specific = client_cb->handle; @@ -956,12 +908,11 @@ void bta_hf_client_dump_statistics(int fd) { uint8_t* a = client_cb->peer_addr.address; // Device name - dprintf(fd, " Peer Device: %02x:%02x:%02x:%02x:%02x:%02x\n", a[0], a[1], - a[2], a[3], a[4], a[5]); + dprintf(fd, " Peer Device: %02x:%02x:%02x:%02x:%02x:%02x\n", a[0], a[1], a[2], a[3], a[4], + a[5]); // State machine state - dprintf(fd, " State Machine State: %s\n", - bta_hf_client_state_str(client_cb->state)); + dprintf(fd, " State Machine State: %s\n", bta_hf_client_state_str(client_cb->state)); // Local RFC channelfor communication dprintf(fd, " RFCOMM Channel (local) %d\n", client_cb->conn_handle); diff --git a/system/bta/hf_client/bta_hf_client_rfc.cc b/system/bta/hf_client/bta_hf_client_rfc.cc index a07d864d983..262d31d2675 100644 --- a/system/bta/hf_client/bta_hf_client_rfc.cc +++ b/system/bta/hf_client/bta_hf_client_rfc.cc @@ -50,18 +50,15 @@ using namespace bluetooth; * Returns void * ******************************************************************************/ -static void bta_hf_client_port_cback(uint32_t /* code */, - uint16_t port_handle) { +static void bta_hf_client_port_cback(uint32_t /* code */, uint16_t port_handle) { /* ignore port events for port handles other than connected handle */ - tBTA_HF_CLIENT_CB* client_cb = - bta_hf_client_find_cb_by_rfc_handle(port_handle); + tBTA_HF_CLIENT_CB* client_cb = bta_hf_client_find_cb_by_rfc_handle(port_handle); if (client_cb == NULL) { log::error("cb not found for handle {}", port_handle); return; } - tBTA_HF_CLIENT_RFC* p_buf = - (tBTA_HF_CLIENT_RFC*)osi_malloc(sizeof(tBTA_HF_CLIENT_RFC)); + tBTA_HF_CLIENT_RFC* p_buf = (tBTA_HF_CLIENT_RFC*)osi_malloc(sizeof(tBTA_HF_CLIENT_RFC)); p_buf->hdr.event = BTA_HF_CLIENT_RFC_DATA_EVT; p_buf->hdr.layer_specific = client_cb->handle; bta_sys_sendmsg(p_buf); @@ -77,23 +74,19 @@ static void bta_hf_client_port_cback(uint32_t /* code */, * Returns void * ******************************************************************************/ -static void bta_hf_client_mgmt_cback(const tPORT_RESULT code, - uint16_t port_handle) { - tBTA_HF_CLIENT_CB* client_cb = - bta_hf_client_find_cb_by_rfc_handle(port_handle); +static void bta_hf_client_mgmt_cback(const tPORT_RESULT code, uint16_t port_handle) { + tBTA_HF_CLIENT_CB* client_cb = bta_hf_client_find_cb_by_rfc_handle(port_handle); log::verbose("code = {}, port_handle = {} serv = {}", code, port_handle, bta_hf_client_cb_arr.serv_handle); /* ignore close event for port handles other than connected handle */ - if (code != PORT_SUCCESS && client_cb != NULL && - port_handle != client_cb->conn_handle) { + if (code != PORT_SUCCESS && client_cb != NULL && port_handle != client_cb->conn_handle) { log::verbose("bta_hf_client_mgmt_cback ignoring handle:{}", port_handle); return; } - tBTA_HF_CLIENT_RFC* p_buf = - (tBTA_HF_CLIENT_RFC*)osi_malloc(sizeof(tBTA_HF_CLIENT_RFC)); + tBTA_HF_CLIENT_RFC* p_buf = (tBTA_HF_CLIENT_RFC*)osi_malloc(sizeof(tBTA_HF_CLIENT_RFC)); if (code == PORT_SUCCESS) { if (client_cb && port_handle == client_cb->conn_handle) { /* out conn */ @@ -120,8 +113,7 @@ static void bta_hf_client_mgmt_cback(const tPORT_RESULT code, log::error("error allocating a new handle"); p_buf->hdr.event = BTA_HF_CLIENT_RFC_CLOSE_EVT; if (RFCOMM_RemoveConnection(port_handle) != PORT_SUCCESS) { - log::warn("Unable to remote RFCOMM server connection handle:{}", - port_handle); + log::warn("Unable to remote RFCOMM server connection handle:{}", port_handle); } } else { @@ -139,14 +131,11 @@ static void bta_hf_client_mgmt_cback(const tPORT_RESULT code, osi_free(p_buf); return; } - } else if (client_cb != NULL && - port_handle == client_cb->conn_handle) { /* code != PORT_SUC */ - log::error("closing port handle {} dev {}", port_handle, - client_cb->peer_addr); + } else if (client_cb != NULL && port_handle == client_cb->conn_handle) { /* code != PORT_SUC */ + log::error("closing port handle {} dev {}", port_handle, client_cb->peer_addr); if (RFCOMM_RemoveServer(port_handle) != PORT_SUCCESS) { - log::warn("Unable to remote RFCOMM server connection handle:{}", - port_handle); + log::warn("Unable to remote RFCOMM server connection handle:{}", port_handle); } p_buf->hdr.event = BTA_HF_CLIENT_RFC_CLOSE_EVT; } else if (client_cb == NULL) { @@ -170,8 +159,8 @@ static void bta_hf_client_mgmt_cback(const tPORT_RESULT code, * ******************************************************************************/ void bta_hf_client_setup_port(uint16_t handle) { - if (PORT_SetEventMaskAndCallback(handle, PORT_EV_RXCHAR, - bta_hf_client_port_cback) != PORT_SUCCESS) { + if (PORT_SetEventMaskAndCallback(handle, PORT_EV_RXCHAR, bta_hf_client_port_cback) != + PORT_SUCCESS) { log::warn("Unable to set RFCOMM event mask and callbackhandle:{}", handle); } } @@ -190,18 +179,16 @@ void bta_hf_client_start_server() { int port_status; if (bta_hf_client_cb_arr.serv_handle > 0) { - log::verbose("already started, handle: {}", - bta_hf_client_cb_arr.serv_handle); + log::verbose("already started, handle: {}", bta_hf_client_cb_arr.serv_handle); return; } port_status = RFCOMM_CreateConnectionWithSecurity( - UUID_SERVCLASS_HF_HANDSFREE, bta_hf_client_cb_arr.scn, true, - BTA_HF_CLIENT_MTU, RawAddress::kAny, &(bta_hf_client_cb_arr.serv_handle), - bta_hf_client_mgmt_cback, BTA_SEC_AUTHENTICATE | BTA_SEC_ENCRYPT); + UUID_SERVCLASS_HF_HANDSFREE, bta_hf_client_cb_arr.scn, true, BTA_HF_CLIENT_MTU, + RawAddress::kAny, &(bta_hf_client_cb_arr.serv_handle), bta_hf_client_mgmt_cback, + BTA_SEC_AUTHENTICATE | BTA_SEC_ENCRYPT); - log::verbose("started rfcomm server with handle {}", - bta_hf_client_cb_arr.serv_handle); + log::verbose("started rfcomm server with handle {}", bta_hf_client_cb_arr.serv_handle); if (port_status == PORT_SUCCESS) { bta_hf_client_setup_port(bta_hf_client_cb_arr.serv_handle); @@ -229,8 +216,7 @@ void bta_hf_client_close_server() { } if (RFCOMM_RemoveServer(bta_hf_client_cb_arr.serv_handle) != PORT_SUCCESS) { - log::warn("Unable to remove RFCOMM servier handle:{}", - bta_hf_client_cb_arr.serv_handle); + log::warn("Unable to remove RFCOMM servier handle:{}", bta_hf_client_cb_arr.serv_handle); } bta_hf_client_cb_arr.serv_handle = 0; } @@ -246,21 +232,18 @@ void bta_hf_client_close_server() { * ******************************************************************************/ void bta_hf_client_rfc_do_open(tBTA_HF_CLIENT_DATA* p_data) { - tBTA_HF_CLIENT_CB* client_cb = - bta_hf_client_find_cb_by_handle(p_data->hdr.layer_specific); + tBTA_HF_CLIENT_CB* client_cb = bta_hf_client_find_cb_by_handle(p_data->hdr.layer_specific); if (client_cb == NULL) { log::error("cb not found for handle {}", p_data->hdr.layer_specific); return; } - if (RFCOMM_CreateConnectionWithSecurity( - UUID_SERVCLASS_HF_HANDSFREE, client_cb->peer_scn, false, - BTA_HF_CLIENT_MTU, client_cb->peer_addr, &(client_cb->conn_handle), - bta_hf_client_mgmt_cback, - BTA_SEC_AUTHENTICATE | BTA_SEC_ENCRYPT) == PORT_SUCCESS) { + if (RFCOMM_CreateConnectionWithSecurity(UUID_SERVCLASS_HF_HANDSFREE, client_cb->peer_scn, false, + BTA_HF_CLIENT_MTU, client_cb->peer_addr, + &(client_cb->conn_handle), bta_hf_client_mgmt_cback, + BTA_SEC_AUTHENTICATE | BTA_SEC_ENCRYPT) == PORT_SUCCESS) { bta_hf_client_setup_port(client_cb->conn_handle); - log::verbose("bta_hf_client_rfc_do_open : conn_handle = {}", - client_cb->conn_handle); + log::verbose("bta_hf_client_rfc_do_open : conn_handle = {}", client_cb->conn_handle); } /* RFCOMM create connection failed; send ourselves RFCOMM close event */ else { @@ -279,8 +262,7 @@ void bta_hf_client_rfc_do_open(tBTA_HF_CLIENT_DATA* p_data) { * ******************************************************************************/ void bta_hf_client_rfc_do_close(tBTA_HF_CLIENT_DATA* p_data) { - tBTA_HF_CLIENT_CB* client_cb = - bta_hf_client_find_cb_by_handle(p_data->hdr.layer_specific); + tBTA_HF_CLIENT_CB* client_cb = bta_hf_client_find_cb_by_handle(p_data->hdr.layer_specific); if (client_cb == NULL) { log::error("cb not found for handle {}", p_data->hdr.layer_specific); return; @@ -288,22 +270,20 @@ void bta_hf_client_rfc_do_close(tBTA_HF_CLIENT_DATA* p_data) { if (client_cb->conn_handle) { if (RFCOMM_RemoveConnection(client_cb->conn_handle) != PORT_SUCCESS) { - log::warn("Unable to remove RFCOMM connection peer:{} handle:{}", - client_cb->peer_addr, client_cb->conn_handle); + log::warn("Unable to remove RFCOMM connection peer:{} handle:{}", client_cb->peer_addr, + client_cb->conn_handle); } } else { /* Close API was called while HF Client is in Opening state. */ /* Need to trigger the state machine to send callback to the app */ /* and move back to INIT state. */ - tBTA_HF_CLIENT_RFC* p_buf = - (tBTA_HF_CLIENT_RFC*)osi_malloc(sizeof(tBTA_HF_CLIENT_RFC)); + tBTA_HF_CLIENT_RFC* p_buf = (tBTA_HF_CLIENT_RFC*)osi_malloc(sizeof(tBTA_HF_CLIENT_RFC)); p_buf->hdr.event = BTA_HF_CLIENT_RFC_CLOSE_EVT; bta_sys_sendmsg(p_buf); /* Cancel SDP if it had been started. */ if (client_cb->p_disc_db) { - (void)get_legacy_stack_sdp_api()->service.SDP_CancelServiceSearch( - client_cb->p_disc_db); + (void)get_legacy_stack_sdp_api()->service.SDP_CancelServiceSearch(client_cb->p_disc_db); osi_free_and_reset((void**)&client_cb->p_disc_db); } } diff --git a/system/bta/hf_client/bta_hf_client_sco.cc b/system/bta/hf_client/bta_hf_client_sco.cc index e52e79bb4a4..a6ab8137d65 100644 --- a/system/bta/hf_client/bta_hf_client_sco.cc +++ b/system/bta/hf_client/bta_hf_client_sco.cc @@ -27,9 +27,9 @@ #include "stack/include/btm_api.h" #include "stack/include/btm_client_interface.h" -#define BTA_HF_CLIENT_NO_EDR_ESCO \ - (ESCO_PKT_TYPES_MASK_NO_2_EV3 | ESCO_PKT_TYPES_MASK_NO_3_EV3 | \ - ESCO_PKT_TYPES_MASK_NO_2_EV5 | ESCO_PKT_TYPES_MASK_NO_3_EV5) +#define BTA_HF_CLIENT_NO_EDR_ESCO \ + (ESCO_PKT_TYPES_MASK_NO_2_EV3 | ESCO_PKT_TYPES_MASK_NO_3_EV3 | ESCO_PKT_TYPES_MASK_NO_2_EV5 | \ + ESCO_PKT_TYPES_MASK_NO_3_EV5) using namespace bluetooth; @@ -147,15 +147,12 @@ static void bta_hf_client_sco_conn_rsp(tBTA_HF_CLIENT_CB* client_cb, * Returns void * ******************************************************************************/ -static void bta_hf_client_esco_connreq_cback(tBTM_ESCO_EVT event, - tBTM_ESCO_EVT_DATA* p_data) { +static void bta_hf_client_esco_connreq_cback(tBTM_ESCO_EVT event, tBTM_ESCO_EVT_DATA* p_data) { log::verbose("{}", event); - tBTA_HF_CLIENT_CB* client_cb = - bta_hf_client_find_cb_by_sco_handle(p_data->conn_evt.sco_inx); + tBTA_HF_CLIENT_CB* client_cb = bta_hf_client_find_cb_by_sco_handle(p_data->conn_evt.sco_inx); if (client_cb == NULL) { - log::error("wrong SCO handle to control block {}", - p_data->conn_evt.sco_inx); + log::error("wrong SCO handle to control block {}", p_data->conn_evt.sco_inx); return; } @@ -228,8 +225,7 @@ static void bta_hf_client_sco_disc_cback(uint16_t sco_idx) { * Returns void * ******************************************************************************/ -static void bta_hf_client_sco_create(tBTA_HF_CLIENT_CB* client_cb, - bool is_orig) { +static void bta_hf_client_sco_create(tBTA_HF_CLIENT_CB* client_cb, bool is_orig) { tBTM_STATUS status; log::verbose("{}", is_orig); @@ -256,25 +252,23 @@ static void bta_hf_client_sco_create(tBTA_HF_CLIENT_CB* client_cb, /* if initiating set current scb and peer bd addr */ if (is_orig) { - if (get_btm_client_interface().sco.BTM_SetEScoMode(¶ms) != - BTM_SUCCESS) { + if (get_btm_client_interface().sco.BTM_SetEScoMode(¶ms) != BTM_SUCCESS) { log::warn("Unable to set ESCO mode"); } /* tell sys to stop av if any */ bta_sys_sco_use(BTA_ID_HS, 1, client_cb->peer_addr); } - status = BTM_CreateSco(&client_cb->peer_addr, is_orig, params.packet_types, - &client_cb->sco_idx, bta_hf_client_sco_conn_cback, - bta_hf_client_sco_disc_cback); + status = BTM_CreateSco(&client_cb->peer_addr, is_orig, params.packet_types, &client_cb->sco_idx, + bta_hf_client_sco_conn_cback, bta_hf_client_sco_disc_cback); if (status == BTM_CMD_STARTED && !is_orig) { - if (!BTM_RegForEScoEvts(client_cb->sco_idx, - bta_hf_client_esco_connreq_cback)) + if (!BTM_RegForEScoEvts(client_cb->sco_idx, bta_hf_client_esco_connreq_cback)) { log::verbose("SCO registration success"); + } } - log::verbose("orig {}, inx 0x{:04x}, status 0x{:x}, pkt types 0x{:04x}", - is_orig, client_cb->sco_idx, status, params.packet_types); + log::verbose("orig {}, inx 0x{:04x}, status 0x{:x}, pkt types 0x{:04x}", is_orig, + client_cb->sco_idx, status, params.packet_types); } /******************************************************************************* @@ -287,8 +281,7 @@ static void bta_hf_client_sco_create(tBTA_HF_CLIENT_CB* client_cb, * Returns void * ******************************************************************************/ -static void bta_hf_client_sco_event(tBTA_HF_CLIENT_CB* client_cb, - uint8_t event) { +static void bta_hf_client_sco_event(tBTA_HF_CLIENT_CB* client_cb, uint8_t event) { log::verbose("before state: {} event: {}", client_cb->sco_state, event); switch (client_cb->sco_state) { @@ -521,8 +514,7 @@ static void bta_hf_client_sco_event(tBTA_HF_CLIENT_CB* client_cb, void bta_hf_client_sco_listen(tBTA_HF_CLIENT_DATA* p_data) { log::verbose(""); - tBTA_HF_CLIENT_CB* client_cb = - bta_hf_client_find_cb_by_handle(p_data->hdr.layer_specific); + tBTA_HF_CLIENT_CB* client_cb = bta_hf_client_find_cb_by_handle(p_data->hdr.layer_specific); if (client_cb == NULL) { log::error("wrong handle to control block {}", p_data->hdr.layer_specific); return; @@ -560,8 +552,7 @@ void bta_hf_client_sco_shutdown(tBTA_HF_CLIENT_CB* client_cb) { void bta_hf_client_sco_conn_open(tBTA_HF_CLIENT_DATA* p_data) { log::verbose(""); - tBTA_HF_CLIENT_CB* client_cb = - bta_hf_client_find_cb_by_handle(p_data->hdr.layer_specific); + tBTA_HF_CLIENT_CB* client_cb = bta_hf_client_find_cb_by_handle(p_data->hdr.layer_specific); if (client_cb == NULL) { log::error("wrong handle to control block {}", p_data->hdr.layer_specific); return; @@ -593,8 +584,7 @@ void bta_hf_client_sco_conn_open(tBTA_HF_CLIENT_DATA* p_data) { void bta_hf_client_sco_conn_close(tBTA_HF_CLIENT_DATA* p_data) { log::verbose(""); - tBTA_HF_CLIENT_CB* client_cb = - bta_hf_client_find_cb_by_handle(p_data->hdr.layer_specific); + tBTA_HF_CLIENT_CB* client_cb = bta_hf_client_find_cb_by_handle(p_data->hdr.layer_specific); if (client_cb == NULL) { log::error("wrong handle to control block {}", p_data->hdr.layer_specific); return; @@ -631,8 +621,7 @@ void bta_hf_client_sco_conn_close(tBTA_HF_CLIENT_DATA* p_data) { void bta_hf_client_sco_open(tBTA_HF_CLIENT_DATA* p_data) { log::verbose(""); - tBTA_HF_CLIENT_CB* client_cb = - bta_hf_client_find_cb_by_handle(p_data->hdr.layer_specific); + tBTA_HF_CLIENT_CB* client_cb = bta_hf_client_find_cb_by_handle(p_data->hdr.layer_specific); if (client_cb == NULL) { log::error("wrong handle to control block {}", p_data->hdr.layer_specific); return; @@ -652,8 +641,7 @@ void bta_hf_client_sco_open(tBTA_HF_CLIENT_DATA* p_data) { * ******************************************************************************/ void bta_hf_client_sco_close(tBTA_HF_CLIENT_DATA* p_data) { - tBTA_HF_CLIENT_CB* client_cb = - bta_hf_client_find_cb_by_handle(p_data->hdr.layer_specific); + tBTA_HF_CLIENT_CB* client_cb = bta_hf_client_find_cb_by_handle(p_data->hdr.layer_specific); if (client_cb == NULL) { log::error("wrong handle to control block {}", p_data->hdr.layer_specific); return; diff --git a/system/bta/hf_client/bta_hf_client_sdp.cc b/system/bta/hf_client/bta_hf_client_sdp.cc index 70f53d16801..d755b69d07f 100644 --- a/system/bta/hf_client/bta_hf_client_sdp.cc +++ b/system/bta/hf_client/bta_hf_client_sdp.cc @@ -61,20 +61,20 @@ using namespace bluetooth; * Returns void * ******************************************************************************/ -static void bta_hf_client_sdp_cback(tBTA_HF_CLIENT_CB* client_cb, - const RawAddress& /* bd_addr */, +static void bta_hf_client_sdp_cback(tBTA_HF_CLIENT_CB* client_cb, const RawAddress& /* bd_addr */, tSDP_STATUS status) { uint16_t event; - tBTA_HF_CLIENT_DISC_RESULT* p_buf = (tBTA_HF_CLIENT_DISC_RESULT*)osi_malloc( - sizeof(tBTA_HF_CLIENT_DISC_RESULT)); + tBTA_HF_CLIENT_DISC_RESULT* p_buf = + (tBTA_HF_CLIENT_DISC_RESULT*)osi_malloc(sizeof(tBTA_HF_CLIENT_DISC_RESULT)); log::verbose("bta_hf_client_sdp_cback status:0x{:x}", status); /* set event according to int/acp */ - if (client_cb->role == BTA_HF_CLIENT_ACP) + if (client_cb->role == BTA_HF_CLIENT_ACP) { event = BTA_HF_CLIENT_DISC_ACP_RES_EVT; - else + } else { event = BTA_HF_CLIENT_DISC_INT_RES_EVT; + } p_buf->hdr.event = event; p_buf->hdr.layer_specific = client_cb->handle; @@ -97,8 +97,7 @@ static void bta_hf_client_sdp_cback(tBTA_HF_CLIENT_CB* client_cb, * false if function execution failed. * *****************************************************************************/ -bool bta_hf_client_add_record(const char* p_service_name, uint8_t scn, - tBTA_HF_CLIENT_FEAT features, +bool bta_hf_client_add_record(const char* p_service_name, uint8_t scn, tBTA_HF_CLIENT_FEAT features, uint32_t sdp_handle) { tSDP_PROTOCOL_ELEM proto_elem_list[BTA_HF_CLIENT_NUM_PROTO_ELEMS]; uint16_t svc_class_id_list[BTA_HF_CLIENT_NUM_SVC_ELEMS]; @@ -112,8 +111,7 @@ bool bta_hf_client_add_record(const char* p_service_name, uint8_t scn, log::verbose("bta_hf_client_add_record"); log::info("features: {}", features); - memset(proto_elem_list, 0, - BTA_HF_CLIENT_NUM_PROTO_ELEMS * sizeof(tSDP_PROTOCOL_ELEM)); + memset(proto_elem_list, 0, BTA_HF_CLIENT_NUM_PROTO_ELEMS * sizeof(tSDP_PROTOCOL_ELEM)); /* add the protocol element sequence */ proto_elem_list[0].protocol_uuid = UUID_PROTOCOL_L2CAP; @@ -122,57 +120,66 @@ bool bta_hf_client_add_record(const char* p_service_name, uint8_t scn, proto_elem_list[1].num_params = 1; proto_elem_list[1].params[0] = scn; result &= get_legacy_stack_sdp_api()->handle.SDP_AddProtocolList( - sdp_handle, BTA_HF_CLIENT_NUM_PROTO_ELEMS, proto_elem_list); + sdp_handle, BTA_HF_CLIENT_NUM_PROTO_ELEMS, proto_elem_list); /* add service class id list */ svc_class_id_list[0] = UUID_SERVCLASS_HF_HANDSFREE; svc_class_id_list[1] = UUID_SERVCLASS_GENERIC_AUDIO; result &= get_legacy_stack_sdp_api()->handle.SDP_AddServiceClassIdList( - sdp_handle, BTA_HF_CLIENT_NUM_SVC_ELEMS, svc_class_id_list); + sdp_handle, BTA_HF_CLIENT_NUM_SVC_ELEMS, svc_class_id_list); /* add profile descriptor list */ profile_uuid = UUID_SERVCLASS_HF_HANDSFREE; version = get_default_hfp_version(); - result &= get_legacy_stack_sdp_api()->handle.SDP_AddProfileDescriptorList( - sdp_handle, profile_uuid, version); + result &= get_legacy_stack_sdp_api()->handle.SDP_AddProfileDescriptorList(sdp_handle, + profile_uuid, version); /* add service name */ if (p_service_name != NULL && p_service_name[0] != 0) { result &= get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - sdp_handle, ATTR_ID_SERVICE_NAME, TEXT_STR_DESC_TYPE, - (uint32_t)(strlen(p_service_name) + 1), (uint8_t*)p_service_name); + sdp_handle, ATTR_ID_SERVICE_NAME, TEXT_STR_DESC_TYPE, + (uint32_t)(strlen(p_service_name) + 1), (uint8_t*)p_service_name); } /* add features */ - if (features & BTA_HF_CLIENT_FEAT_ECNR) + if (features & BTA_HF_CLIENT_FEAT_ECNR) { sdp_features |= BTA_HF_CLIENT_FEAT_ECNR; + } - if (features & BTA_HF_CLIENT_FEAT_3WAY) + if (features & BTA_HF_CLIENT_FEAT_3WAY) { sdp_features |= BTA_HF_CLIENT_FEAT_3WAY; + } - if (features & BTA_HF_CLIENT_FEAT_CLI) sdp_features |= BTA_HF_CLIENT_FEAT_CLI; + if (features & BTA_HF_CLIENT_FEAT_CLI) { + sdp_features |= BTA_HF_CLIENT_FEAT_CLI; + } - if (features & BTA_HF_CLIENT_FEAT_VREC) + if (features & BTA_HF_CLIENT_FEAT_VREC) { sdp_features |= BTA_HF_CLIENT_FEAT_VREC; + } - if (features & BTA_HF_CLIENT_FEAT_VOL) sdp_features |= BTA_HF_CLIENT_FEAT_VOL; + if (features & BTA_HF_CLIENT_FEAT_VOL) { + sdp_features |= BTA_HF_CLIENT_FEAT_VOL; + } /* Codec bit position is different in SDP (bit 5) and in BRSF (bit 7) */ - if (features & BTA_HF_CLIENT_FEAT_CODEC) + if (features & BTA_HF_CLIENT_FEAT_CODEC) { sdp_features |= BTA_HF_CLIENT_WBS_SUPPORT; + } /* Support swb */ - if (features & BTA_HF_CLIENT_FEAT_SWB) + if (features & BTA_HF_CLIENT_FEAT_SWB) { features |= BTA_HF_CLIENT_FEAT_SWB_SUPPORT; + } UINT16_TO_BE_FIELD(buf, sdp_features); result &= get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - sdp_handle, ATTR_ID_SUPPORTED_FEATURES, UINT_DESC_TYPE, 2, buf); + sdp_handle, ATTR_ID_SUPPORTED_FEATURES, UINT_DESC_TYPE, 2, buf); /* add browse group list */ result &= get_legacy_stack_sdp_api()->handle.SDP_AddUuidSequence( - sdp_handle, ATTR_ID_BROWSE_GROUP_LIST, 1, browse_list); + sdp_handle, ATTR_ID_BROWSE_GROUP_LIST, 1, browse_list); return result; } @@ -187,15 +194,12 @@ bool bta_hf_client_add_record(const char* p_service_name, uint8_t scn, * Returns void * ******************************************************************************/ -void bta_hf_client_create_record(tBTA_HF_CLIENT_CB_ARR* client_cb_arr, - const char* p_service_name) { +void bta_hf_client_create_record(tBTA_HF_CLIENT_CB_ARR* client_cb_arr, const char* p_service_name) { /* add sdp record if not already registered */ if (client_cb_arr->sdp_handle == 0) { - client_cb_arr->sdp_handle = - get_legacy_stack_sdp_api()->handle.SDP_CreateRecord(); + client_cb_arr->sdp_handle = get_legacy_stack_sdp_api()->handle.SDP_CreateRecord(); client_cb_arr->scn = BTA_AllocateSCN(); - bta_hf_client_add_record(p_service_name, client_cb_arr->scn, - client_cb_arr->features, + bta_hf_client_add_record(p_service_name, client_cb_arr->scn, client_cb_arr->features, client_cb_arr->sdp_handle); bta_sys_add_uuid(UUID_SERVCLASS_HF_HANDSFREE); @@ -216,8 +220,7 @@ void bta_hf_client_del_record(tBTA_HF_CLIENT_CB_ARR* client_cb) { log::verbose(""); if (client_cb->sdp_handle != 0) { - if (get_legacy_stack_sdp_api()->handle.SDP_DeleteRecord( - client_cb->sdp_handle)) { + if (get_legacy_stack_sdp_api()->handle.SDP_DeleteRecord(client_cb->sdp_handle)) { log::warn("Unable to delete SDP record handle:{}", client_cb->sdp_handle); } client_cb->sdp_handle = 0; @@ -247,8 +250,8 @@ bool bta_hf_client_sdp_find_attr(tBTA_HF_CLIENT_CB* client_cb) { /* loop through all records we found */ while (true) { /* get next record; if none found, we're done */ - p_rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb( - client_cb->p_disc_db, UUID_SERVCLASS_AG_HANDSFREE, p_rec); + p_rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb(client_cb->p_disc_db, + UUID_SERVCLASS_AG_HANDSFREE, p_rec); if (p_rec == NULL) { break; } @@ -256,7 +259,7 @@ bool bta_hf_client_sdp_find_attr(tBTA_HF_CLIENT_CB* client_cb) { /* get scn from proto desc list if initiator */ if (client_cb->role == BTA_HF_CLIENT_INT) { if (get_legacy_stack_sdp_api()->record.SDP_FindProtocolListElemInRec( - p_rec, UUID_PROTOCOL_RFCOMM, &pe)) { + p_rec, UUID_PROTOCOL_RFCOMM, &pe)) { client_cb->peer_scn = (uint8_t)pe.params[0]; } else { continue; @@ -265,16 +268,14 @@ bool bta_hf_client_sdp_find_attr(tBTA_HF_CLIENT_CB* client_cb) { /* get profile version (if failure, version parameter is not updated) */ if (!get_legacy_stack_sdp_api()->record.SDP_FindProfileVersionInRec( - p_rec, UUID_SERVCLASS_HF_HANDSFREE, &client_cb->peer_version)) { - log::warn("Uable to find HFP profile version in SDP record peer:{}", - p_rec->remote_bd_addr); + p_rec, UUID_SERVCLASS_HF_HANDSFREE, &client_cb->peer_version)) { + log::warn("Uable to find HFP profile version in SDP record peer:{}", p_rec->remote_bd_addr); } /* get features */ - p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - p_rec, ATTR_ID_SUPPORTED_FEATURES); - if (p_attr != NULL && - SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == UINT_DESC_TYPE && + p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec(p_rec, + ATTR_ID_SUPPORTED_FEATURES); + if (p_attr != NULL && SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == UINT_DESC_TYPE && SDP_DISC_ATTR_LEN(p_attr->attr_len_type) >= 2) { /* Found attribute. Get value. */ /* There might be race condition between SDP and BRSF. */ @@ -289,10 +290,8 @@ bool bta_hf_client_sdp_find_attr(tBTA_HF_CLIENT_CB* client_cb) { } /* get network for ability to reject calls */ - p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - p_rec, ATTR_ID_NETWORK); - if (p_attr != NULL && - SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == UINT_DESC_TYPE && + p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec(p_rec, ATTR_ID_NETWORK); + if (p_attr != NULL && SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == UINT_DESC_TYPE && SDP_DISC_ATTR_LEN(p_attr->attr_len_type) >= 2) { if (p_attr->attr_value.v.u16 == 0x01) { client_cb->peer_features |= BTA_HF_CLIENT_PEER_REJECT; @@ -306,8 +305,8 @@ bool bta_hf_client_sdp_find_attr(tBTA_HF_CLIENT_CB* client_cb) { break; } - log::verbose("peer_version=0x{:x} peer_features=0x{:x}", - client_cb->peer_version, client_cb->peer_features); + log::verbose("peer_version=0x{:x} peer_features=0x{:x}", client_cb->peer_version, + client_cb->peer_features); return result; } @@ -352,20 +351,17 @@ void bta_hf_client_do_disc(tBTA_HF_CLIENT_CB* client_cb) { /* set up service discovery database; attr happens to be attr_list len */ db_inited = get_legacy_stack_sdp_api()->service.SDP_InitDiscoveryDb( - client_cb->p_disc_db, BT_DEFAULT_BUFFER_SIZE, num_uuid, uuid_list, - num_attr, attr_list); + client_cb->p_disc_db, BT_DEFAULT_BUFFER_SIZE, num_uuid, uuid_list, num_attr, attr_list); if (db_inited) { /*Service discovery not initiated */ - db_inited = - get_legacy_stack_sdp_api()->service.SDP_ServiceSearchAttributeRequest2( + db_inited = get_legacy_stack_sdp_api()->service.SDP_ServiceSearchAttributeRequest2( client_cb->peer_addr, client_cb->p_disc_db, base::BindRepeating(&bta_hf_client_sdp_cback, client_cb)); } if (!db_inited) { - log::warn("Unable to start SDP service search request peer:{}", - client_cb->peer_addr); + log::warn("Unable to start SDP service search request peer:{}", client_cb->peer_addr); /*free discover db */ osi_free_and_reset((void**)&client_cb->p_disc_db); /* sent failed event */ @@ -387,8 +383,7 @@ void bta_hf_client_do_disc(tBTA_HF_CLIENT_CB* client_cb) { ******************************************************************************/ void bta_hf_client_free_db(tBTA_HF_CLIENT_DATA* p_data) { log::assert_that(p_data != NULL, "assert failed: p_data != NULL"); - tBTA_HF_CLIENT_CB* client_cb = - bta_hf_client_find_cb_by_handle(p_data->hdr.layer_specific); + tBTA_HF_CLIENT_CB* client_cb = bta_hf_client_find_cb_by_handle(p_data->hdr.layer_specific); if (client_cb == NULL) { log::error("cb not found for handle {}", p_data->hdr.layer_specific); return; diff --git a/system/bta/hh/bta_hh_act.cc b/system/bta/hh/bta_hh_act.cc index 805c6ecc02b..f175dd75ecd 100644 --- a/system/bta/hh/bta_hh_act.cc +++ b/system/bta/hh/bta_hh_act.cc @@ -63,8 +63,8 @@ constexpr char kBtmLogTag[] = "HIDH"; /***************************************************************************** * Local Function prototypes ****************************************************************************/ -static void bta_hh_cback(uint8_t dev_handle, const RawAddress& addr, - uint8_t event, uint32_t data, BT_HDR* pdata); +static void bta_hh_cback(uint8_t dev_handle, const RawAddress& addr, uint8_t event, uint32_t data, + BT_HDR* pdata); static tBTA_HH_STATUS bta_hh_get_trans_status(uint32_t result); static const char* bta_hh_hid_event_name(uint16_t event); @@ -140,7 +140,9 @@ void bta_hh_api_disable(void) { uint8_t xx; /* service is not enabled */ - if (bta_hh_cb.p_cback == NULL) return; + if (bta_hh_cb.p_cback == NULL) { + return; + } /* no live connection, signal DISC_CMPL_EVT directly */ if (!bta_hh_cb.cnt_num) { @@ -176,7 +178,9 @@ void bta_hh_disc_cmpl(void) { tBTA_HH_STATUS status = BTA_HH_OK; /* Deregister with lower layer */ - if (HID_HostDeregister() != HID_SUCCESS) status = BTA_HH_ERR; + if (HID_HostDeregister() != HID_SUCCESS) { + status = BTA_HH_ERR; + } if (bta_hh_cb.gatt_if != BTA_GATTS_INVALID_IF) { log::debug("Deregister HOGP host before cleanup"); @@ -195,8 +199,7 @@ void bta_hh_disc_cmpl(void) { * Returns void * ******************************************************************************/ -static void bta_hh_sdp_cback(uint16_t result, uint16_t attr_mask, - tHID_DEV_SDP_INFO* sdp_rec) { +static void bta_hh_sdp_cback(uint16_t result, uint16_t attr_mask, tHID_DEV_SDP_INFO* sdp_rec) { tBTA_HH_DEV_CB* p_cb = bta_hh_cb.p_cur; uint8_t hdl = 0; tBTA_HH_STATUS status = BTA_HH_ERR_SDP; @@ -206,8 +209,8 @@ static void bta_hh_sdp_cback(uint16_t result, uint16_t attr_mask, /* security is required for the connection, add attr_mask bit*/ attr_mask |= HID_SEC_REQUIRED; - log::verbose("p_cb:{} result:0x{:02x}, attr_mask:0x{:02x}, handle:0x{:x}", - fmt::ptr(p_cb), result, attr_mask, p_cb->hid_handle); + log::verbose("p_cb:{} result:0x{:02x}, attr_mask:0x{:02x}, handle:0x{:x}", fmt::ptr(p_cb), + result, attr_mask, p_cb->hid_handle); /* check to see type of device is supported , and should not been added * before */ @@ -215,8 +218,7 @@ static void bta_hh_sdp_cback(uint16_t result, uint16_t attr_mask, /* if not added before */ if (p_cb->hid_handle == BTA_HH_INVALID_HANDLE) { /* add device/update attr_mask information */ - if (HID_HostAddDev(p_cb->link_spec.addrt.bda, attr_mask, &hdl) == - HID_SUCCESS) { + if (HID_HostAddDev(p_cb->link_spec.addrt.bda, attr_mask, &hdl) == HID_SUCCESS) { status = BTA_HH_OK; /* update cb_index[] map */ bta_hh_cb.cb_index[hdl] = p_cb->index; @@ -231,17 +233,17 @@ static void bta_hh_sdp_cback(uint16_t result, uint16_t attr_mask, if (p_cb->app_id != 0) { /* update cb information with attr_mask, dscp_info etc. */ - bta_hh_add_device_to_list(p_cb, hdl, attr_mask, &sdp_rec->dscp_info, - sdp_rec->sub_class, sdp_rec->ssr_max_latency, - sdp_rec->ssr_min_tout, p_cb->app_id); + bta_hh_add_device_to_list(p_cb, hdl, attr_mask, &sdp_rec->dscp_info, sdp_rec->sub_class, + sdp_rec->ssr_max_latency, sdp_rec->ssr_min_tout, p_cb->app_id); p_cb->dscp_info.ctry_code = sdp_rec->ctry_code; status = BTA_HH_OK; } - } else /* type of device is not supported */ + } else { /* type of device is not supported */ status = BTA_HH_ERR_TOD_UNSPT; + } } /* free disc_db when SDP is completed */ @@ -263,8 +265,7 @@ static void bta_hh_sdp_cback(uint16_t result, uint16_t attr_mask, * Returns void * ******************************************************************************/ -static void bta_hh_di_sdp_cback(const RawAddress& /* bd_addr */, - tSDP_RESULT result) { +static void bta_hh_di_sdp_cback(const RawAddress& /* bd_addr */, tSDP_RESULT result) { tBTA_HH_DEV_CB* p_cb = bta_hh_cb.p_cur; tBTA_HH_STATUS status = BTA_HH_ERR_SDP; tSDP_DI_GET_RECORD di_rec; @@ -277,19 +278,17 @@ static void bta_hh_di_sdp_cback(const RawAddress& /* bd_addr */, * HID devices do not set this. So for IOP purposes, we allow the connection * to go through and update the DI record to invalid DI entry. */ - if (((result == SDP_SUCCESS) || (result == SDP_NO_RECS_MATCH)) && - (p_cb != NULL)) { + if (((result == SDP_SUCCESS) || (result == SDP_NO_RECS_MATCH)) && (p_cb != NULL)) { if (result == SDP_SUCCESS && - get_legacy_stack_sdp_api()->device_id.SDP_GetNumDiRecords( - bta_hh_cb.p_disc_db) != 0) { + get_legacy_stack_sdp_api()->device_id.SDP_GetNumDiRecords(bta_hh_cb.p_disc_db) != 0) { /* always update information with primary DI record */ - if (get_legacy_stack_sdp_api()->device_id.SDP_GetDiRecord( - 1, &di_rec, bta_hh_cb.p_disc_db) == SDP_SUCCESS) { - bta_hh_update_di_info(p_cb, di_rec.rec.vendor, di_rec.rec.product, - di_rec.rec.version, 0, 0); + if (get_legacy_stack_sdp_api()->device_id.SDP_GetDiRecord(1, &di_rec, bta_hh_cb.p_disc_db) == + SDP_SUCCESS) { + bta_hh_update_di_info(p_cb, di_rec.rec.vendor, di_rec.rec.product, di_rec.rec.version, 0, + 0); } - } else /* no DI recrod available */ + } else /* no DI record available */ { bta_hh_update_di_info(p_cb, BTA_HH_VENDOR_ID_INVALID, 0, 0, 0, 0); } @@ -327,13 +326,12 @@ static void bta_hh_di_sdp_cback(const RawAddress& /* bd_addr */, ******************************************************************************/ static void bta_hh_start_sdp(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* p_data) { if (!bta_hh_cb.p_disc_db) { - bta_hh_cb.p_disc_db = - (tSDP_DISCOVERY_DB*)osi_malloc(p_bta_hh_cfg->sdp_db_size); + bta_hh_cb.p_disc_db = (tSDP_DISCOVERY_DB*)osi_malloc(p_bta_hh_cfg->sdp_db_size); /* Do DI discovery first */ if (get_legacy_stack_sdp_api()->device_id.SDP_DiDiscover( - p_data->api_conn.link_spec.addrt.bda, bta_hh_cb.p_disc_db, - p_bta_hh_cfg->sdp_db_size, bta_hh_di_sdp_cback) == SDP_SUCCESS) { + p_data->api_conn.link_spec.addrt.bda, bta_hh_cb.p_disc_db, + p_bta_hh_cfg->sdp_db_size, bta_hh_di_sdp_cback) == SDP_SUCCESS) { /* SDP search started successfully * Connection will be triggered at the end of successful SDP search */ @@ -416,10 +414,8 @@ void bta_hh_sdp_cmpl(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* p_data) { * In above condition, disconnect the link as well as remove the * device from list of HID devices */ - if ((status == BTA_HH_ERR_SDP) && (p_cb->incoming_conn) && - (p_cb->app_id == 0)) { - log::error("SDP failed for incoming conn hndl:{}", - p_cb->incoming_hid_handle); + if ((status == BTA_HH_ERR_SDP) && (p_cb->incoming_conn) && (p_cb->app_id == 0)) { + log::error("SDP failed for incoming conn hndl:{}", p_cb->incoming_hid_handle); HID_HostRemoveDev(p_cb->incoming_hid_handle); } conn_dat.status = status; @@ -463,13 +459,11 @@ static void bta_hh_bredr_conn(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* p_data) if (p_cb->hid_handle == BTA_HH_INVALID_HANDLE) { uint8_t hdl; - if (HID_HostAddDev(p_cb->link_spec.addrt.bda, p_cb->attr_mask, &hdl) == - HID_SUCCESS) { + if (HID_HostAddDev(p_cb->link_spec.addrt.bda, p_cb->attr_mask, &hdl) == HID_SUCCESS) { /* update device CB with newly register device handle */ - bta_hh_add_device_to_list(p_cb, hdl, p_cb->attr_mask, NULL, - p_cb->sub_class, - p_cb->dscp_info.ssr_max_latency, - p_cb->dscp_info.ssr_min_tout, p_cb->app_id); + bta_hh_add_device_to_list(p_cb, hdl, p_cb->attr_mask, NULL, p_cb->sub_class, + p_cb->dscp_info.ssr_max_latency, p_cb->dscp_info.ssr_min_tout, + p_cb->app_id); /* update cb_index[] map */ bta_hh_cb.cb_index[hdl] = p_cb->index; } else { @@ -478,8 +472,7 @@ static void bta_hh_bredr_conn(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* p_data) } bta_hh_sm_execute(p_cb, BTA_HH_SDP_CMPL_EVT, &bta_hh_data); - } - else { /* First time connection, start SDP */ + } else { /* First time connection, start SDP */ bta_hh_start_sdp(p_cb, p_data); } } @@ -525,9 +518,9 @@ void bta_hh_api_disc_act(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* p_data) { bta_hh_le_api_disc_act(p_cb); } else { - const uint8_t hid_handle = - (p_data != nullptr) ? static_cast(p_data->hdr.layer_specific) - : p_cb->hid_handle; + const uint8_t hid_handle = (p_data != nullptr) + ? static_cast(p_data->hdr.layer_specific) + : p_cb->hid_handle; tHID_STATUS status = HID_HostCloseDev(hid_handle); if (status != HID_SUCCESS) { log::warn("Failed closing classic device:{} status:{}", p_cb->link_spec, @@ -536,9 +529,8 @@ void bta_hh_api_disc_act(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* p_data) { log::debug("Host initiated close to classic device:{}", p_cb->link_spec); } tBTA_HH bta_hh = { - .dev_status = {.status = - (status == HID_SUCCESS) ? BTA_HH_OK : BTA_HH_ERR, - .handle = hid_handle}, + .dev_status = {.status = (status == HID_SUCCESS) ? BTA_HH_OK : BTA_HH_ERR, + .handle = hid_handle}, }; (*bta_hh_cb.p_cback)(BTA_HH_CLOSE_EVT, &bta_hh); } @@ -556,8 +548,7 @@ void bta_hh_api_disc_act(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* p_data) { ******************************************************************************/ void bta_hh_open_cmpl_act(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* p_data) { tBTA_HH_CONN conn; - uint8_t dev_handle = - p_data ? (uint8_t)p_data->hid_cback.hdr.layer_specific : p_cb->hid_handle; + uint8_t dev_handle = p_data ? (uint8_t)p_data->hid_cback.hdr.layer_specific : p_cb->hid_handle; memset((void*)&conn, 0, sizeof(tBTA_HH_CONN)); conn.handle = dev_handle; @@ -572,11 +563,10 @@ void bta_hh_open_cmpl_act(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* p_data) { conn.attr_mask = p_cb->attr_mask; conn.app_id = p_cb->app_id; - BTM_LogHistory( - kBtmLogTag, p_cb->link_spec.addrt.bda, "Opened", - base::StringPrintf("%s initiator:%s", - bt_transport_text(p_cb->link_spec.transport).c_str(), - (p_cb->incoming_conn) ? "remote" : "local")); + BTM_LogHistory(kBtmLogTag, p_cb->link_spec.addrt.bda, "Opened", + base::StringPrintf("%s initiator:%s", + bt_transport_text(p_cb->link_spec.transport).c_str(), + (p_cb->incoming_conn) ? "remote" : "local")); if (p_cb->link_spec.transport != BT_TRANSPORT_LE) { /* inform role manager */ @@ -584,9 +574,8 @@ void bta_hh_open_cmpl_act(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* p_data) { /* set protocol mode when not default report mode */ if (p_cb->mode != BTA_HH_PROTO_RPT_MODE) { - tHID_STATUS status = - HID_HostWriteDev(dev_handle, HID_TRANS_SET_PROTOCOL, - HID_PAR_PROTOCOL_BOOT_MODE, 0, 0, NULL); + tHID_STATUS status = HID_HostWriteDev(dev_handle, HID_TRANS_SET_PROTOCOL, + HID_PAR_PROTOCOL_BOOT_MODE, 0, 0, NULL); if (status == HID_SUCCESS) { p_cb->w4_evt = BTA_HH_SET_PROTO_EVT; @@ -614,8 +603,7 @@ void bta_hh_open_cmpl_act(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* p_data) { void bta_hh_open_act(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* p_data) { tBTA_HH_API_CONN conn_data; - uint8_t dev_handle = - p_data ? (uint8_t)p_data->hid_cback.hdr.layer_specific : p_cb->hid_handle; + uint8_t dev_handle = p_data ? (uint8_t)p_data->hid_cback.hdr.layer_specific : p_cb->hid_handle; log::verbose("Device[{}] connected", dev_handle); @@ -654,8 +642,7 @@ void bta_hh_data_act(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* p_data) { BT_HDR* pdata = p_data->hid_cback.p_data; uint8_t* p_rpt = (uint8_t*)(pdata + 1) + pdata->offset; - bta_hh_co_data((uint8_t)p_data->hid_cback.hdr.layer_specific, p_rpt, - pdata->len); + bta_hh_co_data((uint8_t)p_data->hid_cback.hdr.layer_specific, p_rpt, pdata->len); osi_free_and_reset((void**)&pdata); } @@ -671,8 +658,8 @@ void bta_hh_data_act(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* p_data) { * ******************************************************************************/ void bta_hh_handsk_act(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* p_data) { - log::verbose("HANDSHAKE received for: event={} data={}", - bta_hh_event_text(p_cb->w4_evt), p_data->hid_cback.data); + log::verbose("HANDSHAKE received for: event={} data={}", bta_hh_event_text(p_cb->w4_evt), + p_data->hid_cback.data); tBTA_HH bta_hh; memset(&bta_hh, 0, sizeof(tBTA_HH)); @@ -687,8 +674,9 @@ void bta_hh_handsk_act(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* p_data) { bta_hh.hs_data.handle = p_cb->hid_handle; /* if handshake gives an OK code for these transaction, fill in UNSUPT */ bta_hh.hs_data.status = bta_hh_get_trans_status(p_data->hid_cback.data); - if (bta_hh.hs_data.status == BTA_HH_OK) + if (bta_hh.hs_data.status == BTA_HH_OK) { bta_hh.hs_data.status = BTA_HH_HS_TRANS_NOT_SPT; + } (*bta_hh_cb.p_cback)(p_cb->w4_evt, &bta_hh); p_cb->w4_evt = BTA_HH_EMPTY_EVT; break; @@ -698,16 +686,14 @@ void bta_hh_handsk_act(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* p_data) { case BTA_HH_SET_PROTO_EVT: case BTA_HH_SET_IDLE_EVT: bta_hh.dev_status.handle = p_cb->hid_handle; - bta_hh.dev_status.status = - bta_hh_get_trans_status(p_data->hid_cback.data); + bta_hh.dev_status.status = bta_hh_get_trans_status(p_data->hid_cback.data); (*bta_hh_cb.p_cback)(p_cb->w4_evt, &bta_hh); p_cb->w4_evt = BTA_HH_EMPTY_EVT; break; /* SET_PROTOCOL when open connection */ case BTA_HH_OPEN_EVT: - bta_hh.conn.status = - p_data->hid_cback.data ? BTA_HH_ERR_PROTO : BTA_HH_OK; + bta_hh.conn.status = p_data->hid_cback.data ? BTA_HH_ERR_PROTO : BTA_HH_OK; bta_hh.conn.handle = p_cb->hid_handle; bta_hh.conn.link_spec = p_cb->link_spec; (*bta_hh_cb.p_cback)(p_cb->w4_evt, &bta_hh); @@ -717,8 +703,7 @@ void bta_hh_handsk_act(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* p_data) { default: /* unknow transaction handshake response */ - log::verbose("unknown transaction type {}", - bta_hh_event_text(p_cb->w4_evt)); + log::verbose("unknown transaction type {}", bta_hh_event_text(p_cb->w4_evt)); break; } @@ -741,8 +726,7 @@ void bta_hh_ctrl_dat_act(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* p_data) { uint8_t* data = (uint8_t*)(pdata + 1) + pdata->offset; tBTA_HH_HSDATA hs_data; - log::verbose("Ctrl DATA received w4: event[{}]", - bta_hh_event_text(p_cb->w4_evt)); + log::verbose("Ctrl DATA received w4: event[{}]", bta_hh_event_text(p_cb->w4_evt)); if (pdata->len == 0) { p_cb->w4_evt = BTA_HH_EMPTY_EVT; osi_free_and_reset((void**)&pdata); @@ -760,13 +744,10 @@ void bta_hh_ctrl_dat_act(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* p_data) { break; case BTA_HH_GET_PROTO_EVT: /* match up BTE/BTA report/boot mode def*/ - hs_data.rsp_data.proto_mode = ((*data) == HID_PAR_PROTOCOL_REPORT) - ? BTA_HH_PROTO_RPT_MODE - : BTA_HH_PROTO_BOOT_MODE; + hs_data.rsp_data.proto_mode = + ((*data) == HID_PAR_PROTOCOL_REPORT) ? BTA_HH_PROTO_RPT_MODE : BTA_HH_PROTO_BOOT_MODE; log::verbose("GET_PROTOCOL Mode = [{}]", - (hs_data.rsp_data.proto_mode == BTA_HH_PROTO_RPT_MODE) - ? "Report" - : "Boot"); + (hs_data.rsp_data.proto_mode == BTA_HH_PROTO_RPT_MODE) ? "Report" : "Boot"); break; /* should not expect control DATA for SET_ transaction */ case BTA_HH_SET_PROTO_EVT: @@ -808,8 +789,7 @@ void bta_hh_open_failure(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* p_data) { memset(&conn_dat, 0, sizeof(tBTA_HH_CONN)); conn_dat.handle = p_cb->hid_handle; - conn_dat.status = - (reason == HID_ERR_AUTH_FAILED) ? BTA_HH_ERR_AUTH_FAILED : BTA_HH_ERR; + conn_dat.status = (reason == HID_ERR_AUTH_FAILED) ? BTA_HH_ERR_AUTH_FAILED : BTA_HH_ERR; conn_dat.link_spec = p_cb->link_spec; HID_HostCloseDev(p_cb->hid_handle); @@ -856,23 +836,23 @@ void bta_hh_close_act(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* p_data) { disc_dat.handle = p_cb->hid_handle; disc_dat.status = to_bta_hh_status(p_data->hid_cback.data); - std::string overlay_fail = - base::StringPrintf("%s %s %s", (l2cap_conn_fail) ? "l2cap_conn_fail" : "", - (l2cap_req_fail) ? "l2cap_req_fail" : "", - (l2cap_cfg_fail) ? "l2cap_cfg_fail" : ""); + std::string overlay_fail = base::StringPrintf( + "%s %s %s", (l2cap_conn_fail) ? "l2cap_conn_fail" : "", + (l2cap_req_fail) ? "l2cap_req_fail" : "", (l2cap_cfg_fail) ? "l2cap_cfg_fail" : ""); BTM_LogHistory( - kBtmLogTag, p_cb->link_spec.addrt.bda, "Closed", - base::StringPrintf( - "%s reason %s %s", - (p_cb->link_spec.transport == BT_TRANSPORT_LE) ? "le" : "classic", - hid_status_text(hid_status).c_str(), overlay_fail.c_str())); + kBtmLogTag, p_cb->link_spec.addrt.bda, "Closed", + base::StringPrintf("%s reason %s %s", + (p_cb->link_spec.transport == BT_TRANSPORT_LE) ? "le" : "classic", + hid_status_text(hid_status).c_str(), overlay_fail.c_str())); /* inform role manager */ bta_sys_conn_close(BTA_ID_HH, p_cb->app_id, p_cb->link_spec.addrt.bda); /* update total conn number */ bta_hh_cb.cnt_num--; - if (disc_dat.status) disc_dat.status = BTA_HH_ERR; + if (disc_dat.status) { + disc_dat.status = BTA_HH_ERR; + } (*bta_hh_cb.p_cback)(event, (tBTA_HH*)&disc_dat); @@ -906,8 +886,7 @@ void bta_hh_close_act(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* p_data) { * Returns void * ******************************************************************************/ -void bta_hh_get_dscp_act(tBTA_HH_DEV_CB* p_cb, - const tBTA_HH_DATA* /* p_data */) { +void bta_hh_get_dscp_act(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* /* p_data */) { if (p_cb->link_spec.transport == BT_TRANSPORT_LE) { if (p_cb->hid_srvc.state >= BTA_HH_SERVICE_DISCOVERED) { p_cb->dscp_info.hid_handle = p_cb->hid_handle; @@ -944,41 +923,37 @@ void bta_hh_maint_dev_act(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* p_data) { if (p_cb->hid_handle == BTA_HH_INVALID_HANDLE) { tBT_TRANSPORT transport = p_data->api_maintdev.link_spec.transport; if (!com::android::bluetooth::flags::allow_switching_hid_and_hogp()) { - transport = BTM_UseLeLink(p_data->api_maintdev.link_spec.addrt.bda) - ? BT_TRANSPORT_LE - : BT_TRANSPORT_BR_EDR; + transport = BTM_UseLeLink(p_data->api_maintdev.link_spec.addrt.bda) ? BT_TRANSPORT_LE + : BT_TRANSPORT_BR_EDR; } if (transport == BT_TRANSPORT_LE) { p_cb->link_spec.transport = BT_TRANSPORT_LE; dev_info.handle = bta_hh_le_add_device(p_cb, p_dev_info); - if (dev_info.handle != BTA_HH_INVALID_HANDLE) + if (dev_info.handle != BTA_HH_INVALID_HANDLE) { dev_info.status = BTA_HH_OK; + } } else if (transport == BT_TRANSPORT_BR_EDR) { - if (HID_HostAddDev(p_dev_info->link_spec.addrt.bda, - p_dev_info->attr_mask, - &dev_handle) == HID_SUCCESS) { + if (HID_HostAddDev(p_dev_info->link_spec.addrt.bda, p_dev_info->attr_mask, &dev_handle) == + HID_SUCCESS) { dev_info.handle = dev_handle; dev_info.status = BTA_HH_OK; p_cb->link_spec.transport = BT_TRANSPORT_BR_EDR; /* update DI information */ - bta_hh_update_di_info( - p_cb, p_dev_info->dscp_info.vendor_id, - p_dev_info->dscp_info.product_id, p_dev_info->dscp_info.version, - p_dev_info->dscp_info.flag, p_dev_info->dscp_info.ctry_code); + bta_hh_update_di_info(p_cb, p_dev_info->dscp_info.vendor_id, + p_dev_info->dscp_info.product_id, p_dev_info->dscp_info.version, + p_dev_info->dscp_info.flag, p_dev_info->dscp_info.ctry_code); /* add to BTA device list */ - bta_hh_add_device_to_list( - p_cb, dev_handle, p_dev_info->attr_mask, - &p_dev_info->dscp_info.descriptor, p_dev_info->sub_class, - p_dev_info->dscp_info.ssr_max_latency, - p_dev_info->dscp_info.ssr_min_tout, p_dev_info->app_id); + bta_hh_add_device_to_list(p_cb, dev_handle, p_dev_info->attr_mask, + &p_dev_info->dscp_info.descriptor, p_dev_info->sub_class, + p_dev_info->dscp_info.ssr_max_latency, + p_dev_info->dscp_info.ssr_min_tout, p_dev_info->app_id); /* update cb_index[] map */ bta_hh_cb.cb_index[dev_handle] = p_cb->index; } } else { - log::error("unexpected BT transport: {}", - bt_transport_text(transport)); + log::error("unexpected BT transport: {}", bt_transport_text(transport)); break; } } else /* device already been added */ @@ -1026,64 +1001,61 @@ void bta_hh_maint_dev_act(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* p_data) { static uint8_t convert_api_sndcmd_param(const tBTA_HH_CMD_DATA& api_sndcmd) { uint8_t api_sndcmd_param = api_sndcmd.param; if (api_sndcmd.t_type == HID_TRANS_SET_PROTOCOL) { - api_sndcmd_param = (api_sndcmd.param == BTA_HH_PROTO_RPT_MODE) - ? HID_PAR_PROTOCOL_REPORT - : HID_PAR_PROTOCOL_BOOT_MODE; + api_sndcmd_param = (api_sndcmd.param == BTA_HH_PROTO_RPT_MODE) ? HID_PAR_PROTOCOL_REPORT + : HID_PAR_PROTOCOL_BOOT_MODE; } return api_sndcmd_param; } void bta_hh_write_dev_act(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* p_data) { - uint16_t event = - (p_data->api_sndcmd.t_type - HID_TRANS_GET_REPORT) + BTA_HH_GET_RPT_EVT; + uint16_t event = (p_data->api_sndcmd.t_type - HID_TRANS_GET_REPORT) + BTA_HH_GET_RPT_EVT; - if (p_cb->link_spec.transport == BT_TRANSPORT_LE) + if (p_cb->link_spec.transport == BT_TRANSPORT_LE) { bta_hh_le_write_dev_act(p_cb, p_data); - else { + } else { /* match up BTE/BTA report/boot mode def */ - const uint8_t api_sndcmd_param = - convert_api_sndcmd_param(p_data->api_sndcmd); - - tHID_STATUS status = HID_HostWriteDev(p_cb->hid_handle, - p_data->api_sndcmd.t_type, - api_sndcmd_param, - p_data->api_sndcmd.data, - p_data->api_sndcmd.rpt_id, - p_data->api_sndcmd.p_data); + const uint8_t api_sndcmd_param = convert_api_sndcmd_param(p_data->api_sndcmd); + + tHID_STATUS status = HID_HostWriteDev(p_cb->hid_handle, p_data->api_sndcmd.t_type, + api_sndcmd_param, p_data->api_sndcmd.data, + p_data->api_sndcmd.rpt_id, p_data->api_sndcmd.p_data); if (status != HID_SUCCESS) { log::error("HID_HostWriteDev Error, status:{}", status); if (p_data->api_sndcmd.t_type != HID_TRANS_CONTROL && p_data->api_sndcmd.t_type != HID_TRANS_DATA) { BT_HDR cbhdr = { - .event = BTA_HH_GET_RPT_EVT, - .len = 0, - .offset = 0, - .layer_specific = 0, + .event = BTA_HH_GET_RPT_EVT, + .len = 0, + .offset = 0, + .layer_specific = 0, }; tBTA_HH cbdata = { - .hs_data = { - .status = BTA_HH_ERR, - .handle = p_cb->hid_handle, - .rsp_data = { - .p_rpt_data = &cbhdr, - }, - }, + .hs_data = + { + .status = BTA_HH_ERR, + .handle = p_cb->hid_handle, + .rsp_data = + { + .p_rpt_data = &cbhdr, + }, + }, }; (*bta_hh_cb.p_cback)(event, &cbdata); } else if (api_sndcmd_param == BTA_HH_CTRL_VIRTUAL_CABLE_UNPLUG) { tBTA_HH cbdata = { - .dev_status = { - .status = BTA_HH_ERR, - .handle = p_cb->hid_handle, - }, + .dev_status = + { + .status = BTA_HH_ERR, + .handle = p_cb->hid_handle, + }, }; (*bta_hh_cb.p_cback)(BTA_HH_VC_UNPLUG_EVT, &cbdata); } else { log::error( - "skipped executing callback in hid host error handling. command " - "type:{}, param:{}", - p_data->api_sndcmd.t_type, p_data->api_sndcmd.param); + "skipped executing callback in hid host error handling. command " + "type:{}, param:{}", + p_data->api_sndcmd.t_type, p_data->api_sndcmd.param); } } else { switch (p_data->api_sndcmd.t_type) { @@ -1101,13 +1073,14 @@ void bta_hh_write_dev_act(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* p_data) { function use */ p_cb->w4_evt = event; break; - case HID_TRANS_DATA: /* output report */ + case HID_TRANS_DATA: /* output report */ FALLTHROUGH_INTENDED; /* FALLTHROUGH */ case HID_TRANS_CONTROL: /* no handshake event will be generated */ /* if VC_UNPLUG is issued, set flag */ - if (api_sndcmd_param == BTA_HH_CTRL_VIRTUAL_CABLE_UNPLUG) + if (api_sndcmd_param == BTA_HH_CTRL_VIRTUAL_CABLE_UNPLUG) { p_cb->vp = true; + } break; /* currently not expected */ @@ -1145,8 +1118,8 @@ void bta_hh_write_dev_act(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* p_data) { * Returns void * ******************************************************************************/ -static void bta_hh_cback(uint8_t dev_handle, const RawAddress& addr, - uint8_t event, uint32_t data, BT_HDR* pdata) { +static void bta_hh_cback(uint8_t dev_handle, const RawAddress& addr, uint8_t event, uint32_t data, + BT_HDR* pdata) { uint16_t sm_event = BTA_HH_INVALID_EVT; uint8_t xx = 0; @@ -1186,8 +1159,8 @@ static void bta_hh_cback(uint8_t dev_handle, const RawAddress& addr, } if (sm_event != BTA_HH_INVALID_EVT) { - tBTA_HH_CBACK_DATA* p_buf = (tBTA_HH_CBACK_DATA*)osi_malloc( - sizeof(tBTA_HH_CBACK_DATA) + sizeof(BT_HDR)); + tBTA_HH_CBACK_DATA* p_buf = + (tBTA_HH_CBACK_DATA*)osi_malloc(sizeof(tBTA_HH_CBACK_DATA) + sizeof(BT_HDR)); p_buf->hdr.event = sm_event; p_buf->hdr.layer_specific = (uint16_t)dev_handle; p_buf->data = data; diff --git a/system/bta/hh/bta_hh_api.cc b/system/bta/hh/bta_hh_api.cc index 73afdbe5cbd..ff1ef18e7ce 100644 --- a/system/bta/hh/bta_hh_api.cc +++ b/system/bta/hh/bta_hh_api.cc @@ -46,13 +46,13 @@ using namespace bluetooth; * Android Headtracker Service UUIDs */ const Uuid ANDROID_HEADTRACKER_SERVICE_UUID = - Uuid::FromString(ANDROID_HEADTRACKER_SERVICE_UUID_STRING); + Uuid::FromString(ANDROID_HEADTRACKER_SERVICE_UUID_STRING); const Uuid ANDROID_HEADTRACKER_VERSION_CHARAC_UUID = - Uuid::FromString(ANDROID_HEADTRACKER_VERSION_CHARAC_UUID_STRING); + Uuid::FromString(ANDROID_HEADTRACKER_VERSION_CHARAC_UUID_STRING); const Uuid ANDROID_HEADTRACKER_CONTROL_CHARAC_UUID = - Uuid::FromString(ANDROID_HEADTRACKER_CONTROL_CHARAC_UUID_STRING); + Uuid::FromString(ANDROID_HEADTRACKER_CONTROL_CHARAC_UUID_STRING); const Uuid ANDROID_HEADTRACKER_REPORT_CHARAC_UUID = - Uuid::FromString(ANDROID_HEADTRACKER_REPORT_CHARAC_UUID_STRING); + Uuid::FromString(ANDROID_HEADTRACKER_REPORT_CHARAC_UUID_STRING); static const tBTA_SYS_REG bta_hh_reg = {bta_hh_hdl_event, BTA_HhDisable}; @@ -123,8 +123,7 @@ void BTA_HhClose(uint8_t dev_handle) { * ******************************************************************************/ void BTA_HhOpen(const tAclLinkSpec& link_spec) { - tBTA_HH_API_CONN* p_buf = - (tBTA_HH_API_CONN*)osi_calloc(sizeof(tBTA_HH_API_CONN)); + tBTA_HH_API_CONN* p_buf = (tBTA_HH_API_CONN*)osi_calloc(sizeof(tBTA_HH_API_CONN)); tBTA_HH_PROTO_MODE mode = BTA_HH_PROTO_RPT_MODE; p_buf->hdr.event = BTA_HH_API_OPEN_EVT; @@ -140,11 +139,9 @@ void BTA_HhOpen(const tAclLinkSpec& link_spec) { * Function bta_hh_snd_write_dev * ******************************************************************************/ -static void bta_hh_snd_write_dev(uint8_t dev_handle, uint8_t t_type, - uint8_t param, uint16_t data, uint8_t rpt_id, - BT_HDR* p_data) { - tBTA_HH_CMD_DATA* p_buf = - (tBTA_HH_CMD_DATA*)osi_calloc(sizeof(tBTA_HH_CMD_DATA)); +static void bta_hh_snd_write_dev(uint8_t dev_handle, uint8_t t_type, uint8_t param, uint16_t data, + uint8_t rpt_id, BT_HDR* p_data) { + tBTA_HH_CMD_DATA* p_buf = (tBTA_HH_CMD_DATA*)osi_calloc(sizeof(tBTA_HH_CMD_DATA)); p_buf->hdr.event = BTA_HH_API_WRITE_DEV_EVT; p_buf->hdr.layer_specific = (uint16_t)dev_handle; @@ -169,8 +166,7 @@ static void bta_hh_snd_write_dev(uint8_t dev_handle, uint8_t t_type, * Returns void * ******************************************************************************/ -void BTA_HhSetReport(uint8_t dev_handle, tBTA_HH_RPT_TYPE r_type, - BT_HDR* p_data) { +void BTA_HhSetReport(uint8_t dev_handle, tBTA_HH_RPT_TYPE r_type, BT_HDR* p_data) { bta_hh_snd_write_dev(dev_handle, HID_TRANS_SET_REPORT, r_type, 0, 0, p_data); } /******************************************************************************* @@ -182,12 +178,11 @@ void BTA_HhSetReport(uint8_t dev_handle, tBTA_HH_RPT_TYPE r_type, * Returns void * ******************************************************************************/ -void BTA_HhGetReport(uint8_t dev_handle, tBTA_HH_RPT_TYPE r_type, - uint8_t rpt_id, uint16_t buf_size) { +void BTA_HhGetReport(uint8_t dev_handle, tBTA_HH_RPT_TYPE r_type, uint8_t rpt_id, + uint16_t buf_size) { uint8_t param = (buf_size) ? (r_type | 0x08) : r_type; - bta_hh_snd_write_dev(dev_handle, HID_TRANS_GET_REPORT, param, buf_size, - rpt_id, NULL); + bta_hh_snd_write_dev(dev_handle, HID_TRANS_GET_REPORT, param, buf_size, rpt_id, NULL); } /******************************************************************************* * @@ -199,8 +194,7 @@ void BTA_HhGetReport(uint8_t dev_handle, tBTA_HH_RPT_TYPE r_type, * ******************************************************************************/ void BTA_HhSetProtoMode(uint8_t dev_handle, tBTA_HH_PROTO_MODE p_type) { - bta_hh_snd_write_dev(dev_handle, HID_TRANS_SET_PROTOCOL, (uint8_t)p_type, 0, - 0, NULL); + bta_hh_snd_write_dev(dev_handle, HID_TRANS_SET_PROTOCOL, (uint8_t)p_type, 0, 0, NULL); } /******************************************************************************* * @@ -249,8 +243,7 @@ void BTA_HhGetIdle(uint8_t dev_handle) { * ******************************************************************************/ void BTA_HhSendCtrl(uint8_t dev_handle, tBTA_HH_TRANS_CTRL_TYPE c_type) { - bta_hh_snd_write_dev(dev_handle, HID_TRANS_CONTROL, (uint8_t)c_type, 0, 0, - NULL); + bta_hh_snd_write_dev(dev_handle, HID_TRANS_CONTROL, (uint8_t)c_type, 0, 0, NULL); } /******************************************************************************* * @@ -271,16 +264,12 @@ void BTA_HhSendCtrl(uint8_t dev_handle, tBTA_HH_TRANS_CTRL_TYPE c_type) { * Returns void * ******************************************************************************/ -void BTA_HhSendData(uint8_t dev_handle, const tAclLinkSpec& /* link_spec */, - BT_HDR* p_data) { +void BTA_HhSendData(uint8_t dev_handle, const tAclLinkSpec& /* link_spec */, BT_HDR* p_data) { if (p_data->layer_specific != BTA_HH_RPTT_OUTPUT) { - log::error( - "ERROR! Wrong report type! Write Command only valid for output " - "report!"); + log::error("ERROR! Wrong report type! Write Command only valid for output report!"); return; } - bta_hh_snd_write_dev(dev_handle, HID_TRANS_DATA, - (uint8_t)p_data->layer_specific, 0, 0, p_data); + bta_hh_snd_write_dev(dev_handle, HID_TRANS_DATA, (uint8_t)p_data->layer_specific, 0, 0, p_data); } /******************************************************************************* @@ -313,9 +302,8 @@ void BTA_HhGetDscpInfo(uint8_t dev_handle) { * Returns void * ******************************************************************************/ -void BTA_HhAddDev(const tAclLinkSpec& link_spec, tBTA_HH_ATTR_MASK attr_mask, - uint8_t sub_class, uint8_t app_id, - tBTA_HH_DEV_DSCP_INFO dscp_info) { +void BTA_HhAddDev(const tAclLinkSpec& link_spec, tBTA_HH_ATTR_MASK attr_mask, uint8_t sub_class, + uint8_t app_id, tBTA_HH_DEV_DSCP_INFO dscp_info) { size_t len = sizeof(tBTA_HH_MAINT_DEV) + dscp_info.descriptor.dl_len; tBTA_HH_MAINT_DEV* p_buf = (tBTA_HH_MAINT_DEV*)osi_calloc(len); @@ -352,8 +340,7 @@ void BTA_HhAddDev(const tAclLinkSpec& link_spec, tBTA_HH_ATTR_MASK attr_mask, * ******************************************************************************/ void BTA_HhRemoveDev(uint8_t dev_handle) { - tBTA_HH_MAINT_DEV* p_buf = - (tBTA_HH_MAINT_DEV*)osi_calloc(sizeof(tBTA_HH_MAINT_DEV)); + tBTA_HH_MAINT_DEV* p_buf = (tBTA_HH_MAINT_DEV*)osi_calloc(sizeof(tBTA_HH_MAINT_DEV)); p_buf->hdr.event = BTA_HH_API_MAINT_DEV_EVT; p_buf->sub_event = BTA_HH_RMV_DEV_EVT; diff --git a/system/bta/hh/bta_hh_cfg.cc b/system/bta/hh/bta_hh_cfg.cc index caecb4a6d55..98cda37b8dc 100644 --- a/system/bta/hh/bta_hh_cfg.cc +++ b/system/bta/hh/bta_hh_cfg.cc @@ -36,20 +36,20 @@ /* The type of devices supported by BTA HH and corresponding application ID */ tBTA_HH_SPT_TOD p_devt_list[BTA_HH_MAX_DEVT_SPT] = { - {BTA_HH_DEVT_MIC, BTA_HH_APP_ID_MI}, - {BTA_HH_DEVT_KBD, BTA_HH_APP_ID_KB}, - {BTA_HH_DEVT_KBD | BTA_HH_DEVT_MIC, BTA_HH_APP_ID_KB}, - {BTA_HH_DEVT_RMC, BTA_HH_APP_ID_RMC}, - {BTA_HH_DEVT_RMC | BTA_HH_DEVT_KBD, BTA_HH_APP_ID_RMC}, - {BTA_HH_DEVT_MIC | BTA_HH_DEVT_DGT, BTA_HH_APP_ID_MI}, - {BTA_HH_DEVT_JOS, BTA_HH_APP_ID_JOY}, - {BTA_HH_DEVT_GPD, BTA_HH_APP_ID_GPAD}, - {BTA_HH_DEVT_UNKNOWN, BTA_HH_APP_ID_3DSG}}; + {BTA_HH_DEVT_MIC, BTA_HH_APP_ID_MI}, + {BTA_HH_DEVT_KBD, BTA_HH_APP_ID_KB}, + {BTA_HH_DEVT_KBD | BTA_HH_DEVT_MIC, BTA_HH_APP_ID_KB}, + {BTA_HH_DEVT_RMC, BTA_HH_APP_ID_RMC}, + {BTA_HH_DEVT_RMC | BTA_HH_DEVT_KBD, BTA_HH_APP_ID_RMC}, + {BTA_HH_DEVT_MIC | BTA_HH_DEVT_DGT, BTA_HH_APP_ID_MI}, + {BTA_HH_DEVT_JOS, BTA_HH_APP_ID_JOY}, + {BTA_HH_DEVT_GPD, BTA_HH_APP_ID_GPAD}, + {BTA_HH_DEVT_UNKNOWN, BTA_HH_APP_ID_3DSG}}; const tBTA_HH_CFG bta_hh_cfg = { - BTA_HH_MAX_DEVT_SPT, /* number of supported type of devices */ - p_devt_list, /* ToD & AppID list */ - BTA_HH_DISC_BUF_SIZE /* HH SDP discovery database size */ + BTA_HH_MAX_DEVT_SPT, /* number of supported type of devices */ + p_devt_list, /* ToD & AppID list */ + BTA_HH_DISC_BUF_SIZE /* HH SDP discovery database size */ }; const tBTA_HH_CFG* p_bta_hh_cfg = &bta_hh_cfg; diff --git a/system/bta/hh/bta_hh_headtracker.cc b/system/bta/hh/bta_hh_headtracker.cc index b759414ee65..e52dd122a03 100644 --- a/system/bta/hh/bta_hh_headtracker.cc +++ b/system/bta/hh/bta_hh_headtracker.cc @@ -28,11 +28,10 @@ using bluetooth::Uuid; using namespace bluetooth; -static bool bta_hh_headtracker_parse_version_charac( - tBTA_HH_DEV_CB* p_dev_cb, const gatt::Characteristic& charac) { +static bool bta_hh_headtracker_parse_version_charac(tBTA_HH_DEV_CB* p_dev_cb, + const gatt::Characteristic& charac) { tBTA_HH_LE_RPT* p_rpt = bta_hh_le_find_alloc_report_entry( - p_dev_cb, p_dev_cb->hid_srvc.srvc_inst_id, GATT_UUID_HID_REPORT, - charac.value_handle); + p_dev_cb, p_dev_cb->hid_srvc.srvc_inst_id, GATT_UUID_HID_REPORT, charac.value_handle); if (p_rpt == nullptr) { log::error("Add report entry failed !!!"); return false; @@ -42,11 +41,10 @@ static bool bta_hh_headtracker_parse_version_charac( return true; } -static bool bta_hh_headtracker_prase_control_charac( - tBTA_HH_DEV_CB* p_dev_cb, const gatt::Characteristic& charac) { +static bool bta_hh_headtracker_prase_control_charac(tBTA_HH_DEV_CB* p_dev_cb, + const gatt::Characteristic& charac) { tBTA_HH_LE_RPT* p_rpt = bta_hh_le_find_alloc_report_entry( - p_dev_cb, p_dev_cb->hid_srvc.srvc_inst_id, GATT_UUID_HID_REPORT, - charac.value_handle); + p_dev_cb, p_dev_cb->hid_srvc.srvc_inst_id, GATT_UUID_HID_REPORT, charac.value_handle); if (p_rpt == nullptr) { log::error("Add report entry failed !!!"); return false; @@ -56,11 +54,10 @@ static bool bta_hh_headtracker_prase_control_charac( return true; } -static bool bta_hh_headtracker_parse_report_charac( - tBTA_HH_DEV_CB* p_dev_cb, const gatt::Characteristic& charac) { +static bool bta_hh_headtracker_parse_report_charac(tBTA_HH_DEV_CB* p_dev_cb, + const gatt::Characteristic& charac) { tBTA_HH_LE_RPT* p_rpt = bta_hh_le_find_alloc_report_entry( - p_dev_cb, p_dev_cb->hid_srvc.srvc_inst_id, GATT_UUID_HID_REPORT, - charac.value_handle); + p_dev_cb, p_dev_cb->hid_srvc.srvc_inst_id, GATT_UUID_HID_REPORT, charac.value_handle); if (p_rpt == nullptr) { log::error("Add report entry failed !!!"); return false; @@ -72,23 +69,19 @@ static bool bta_hh_headtracker_parse_report_charac( /* Hardcoded Android Headtracker HID descriptor */ static const uint8_t ANDROID_HEADTRACKER_DESCRIPTOR[] = { - 0x05, 0x20, 0x09, 0xe1, 0xa1, 0x01, 0x85, 0x02, 0x0a, 0x08, 0x03, 0x15, - 0x00, 0x25, 0xff, 0x75, 0x08, 0x95, 0x19, 0xb1, 0x03, 0x0a, 0x02, 0x03, - 0x15, 0x00, 0x25, 0xff, 0x75, 0x08, 0x95, 0x10, 0xb1, 0x03, 0x85, 0x01, - 0x0a, 0x16, 0x03, 0x15, 0x00, 0x25, 0x01, 0x75, 0x01, 0x95, 0x01, 0xa1, - 0x02, 0x0a, 0x40, 0x08, 0x0a, 0x41, 0x08, 0xb1, 0x00, 0xc0, 0x0a, 0x19, - 0x03, 0x15, 0x00, 0x25, 0x01, 0x75, 0x01, 0x95, 0x01, 0xa1, 0x02, 0x0a, - 0x55, 0x08, 0x0a, 0x51, 0x08, 0xb1, 0x00, 0xc0, 0x0a, 0x0e, 0x03, 0x15, - 0x00, 0x25, 0x3f, 0x35, 0x0a, 0x45, 0x64, 0x75, 0x06, 0x95, 0x01, 0x66, - 0x01, 0x10, 0x55, 0x0d, 0xb1, 0x02, 0x0a, 0x10, 0xf4, 0x15, 0x00, 0x25, - 0x01, 0x75, 0x01, 0x95, 0x01, 0xa1, 0x02, 0x0a, 0x00, 0xf8, 0x0a, 0x01, - 0xf8, 0xb1, 0x00, 0xc0, 0xb1, 0x02, 0x0a, 0x44, 0x5, 0x16, 0x01, 0x80, - 0x26, 0xff, 0x7f, 0x37, 0x60, 0x4f, 0x46, 0xed, 0x47, 0xa1, 0xb0, 0xb9, - 0x12, 0x55, 0x08, 0x75, 0x10, 0x95, 0x03, 0x81, 0x02, 0x0a, 0x45, 0x05, - 0x16, 0x01, 0x80, 0x26, 0xff, 0x7f, 0x35, 0xe0, 0x45, 0x20, 0x55, 0x00, - 0x75, 0x10, 0x95, 0x03, 0x81, 0x02, 0x0a, 0x46, 0x05, 0x15, 0x00, 0x25, - 0xff, 0x35, 0x00, 0x45, 0xff, 0x55, 0x00, 0x75, 0x08, 0x95, 0x01, 0x81, - 0x02, 0xc0}; + 0x05, 0x20, 0x09, 0xe1, 0xa1, 0x01, 0x85, 0x02, 0x0a, 0x08, 0x03, 0x15, 0x00, 0x25, 0xff, + 0x75, 0x08, 0x95, 0x19, 0xb1, 0x03, 0x0a, 0x02, 0x03, 0x15, 0x00, 0x25, 0xff, 0x75, 0x08, + 0x95, 0x10, 0xb1, 0x03, 0x85, 0x01, 0x0a, 0x16, 0x03, 0x15, 0x00, 0x25, 0x01, 0x75, 0x01, + 0x95, 0x01, 0xa1, 0x02, 0x0a, 0x40, 0x08, 0x0a, 0x41, 0x08, 0xb1, 0x00, 0xc0, 0x0a, 0x19, + 0x03, 0x15, 0x00, 0x25, 0x01, 0x75, 0x01, 0x95, 0x01, 0xa1, 0x02, 0x0a, 0x55, 0x08, 0x0a, + 0x51, 0x08, 0xb1, 0x00, 0xc0, 0x0a, 0x0e, 0x03, 0x15, 0x00, 0x25, 0x3f, 0x35, 0x0a, 0x45, + 0x64, 0x75, 0x06, 0x95, 0x01, 0x66, 0x01, 0x10, 0x55, 0x0d, 0xb1, 0x02, 0x0a, 0x10, 0xf4, + 0x15, 0x00, 0x25, 0x01, 0x75, 0x01, 0x95, 0x01, 0xa1, 0x02, 0x0a, 0x00, 0xf8, 0x0a, 0x01, + 0xf8, 0xb1, 0x00, 0xc0, 0xb1, 0x02, 0x0a, 0x44, 0x5, 0x16, 0x01, 0x80, 0x26, 0xff, 0x7f, + 0x37, 0x60, 0x4f, 0x46, 0xed, 0x47, 0xa1, 0xb0, 0xb9, 0x12, 0x55, 0x08, 0x75, 0x10, 0x95, + 0x03, 0x81, 0x02, 0x0a, 0x45, 0x05, 0x16, 0x01, 0x80, 0x26, 0xff, 0x7f, 0x35, 0xe0, 0x45, + 0x20, 0x55, 0x00, 0x75, 0x10, 0x95, 0x03, 0x81, 0x02, 0x0a, 0x46, 0x05, 0x15, 0x00, 0x25, + 0xff, 0x35, 0x00, 0x45, 0xff, 0x55, 0x00, 0x75, 0x08, 0x95, 0x01, 0x81, 0x02, 0xc0}; /******************************************************************************* * @@ -100,15 +93,13 @@ static const uint8_t ANDROID_HEADTRACKER_DESCRIPTOR[] = { * Parameters: * ******************************************************************************/ -void bta_hh_headtracker_parse_service(tBTA_HH_DEV_CB* p_dev_cb, - const gatt::Service* service) { +void bta_hh_headtracker_parse_service(tBTA_HH_DEV_CB* p_dev_cb, const gatt::Service* service) { log::info(""); bta_hh_le_srvc_init(p_dev_cb, service->handle); p_dev_cb->mode = BTA_HH_PROTO_RPT_MODE; p_dev_cb->hid_srvc.headtracker_support = BTA_HH_AVAILABLE; - bta_hh_le_save_report_map(p_dev_cb, - (uint16_t)sizeof(ANDROID_HEADTRACKER_DESCRIPTOR), + bta_hh_le_save_report_map(p_dev_cb, (uint16_t)sizeof(ANDROID_HEADTRACKER_DESCRIPTOR), (uint8_t*)&ANDROID_HEADTRACKER_DESCRIPTOR); bool version_found = false; @@ -127,9 +118,7 @@ void bta_hh_headtracker_parse_service(tBTA_HH_DEV_CB* p_dev_cb, } } - tGATT_STATUS status = (version_found && control_found && data_found) - ? GATT_SUCCESS - : GATT_ERROR; + tGATT_STATUS status = (version_found && control_found && data_found) ? GATT_SUCCESS : GATT_ERROR; bta_hh_le_service_parsed(p_dev_cb, status); } @@ -149,8 +138,7 @@ bool bta_hh_headtracker_supported(tBTA_HH_DEV_CB* p_dev_cb) { if (p_dev_cb->hid_srvc.headtracker_support == BTA_HH_UNKNOWN) { bluetooth::Uuid remote_uuids[BT_MAX_NUM_UUIDS] = {}; - bt_property_t remote_properties = {BT_PROPERTY_UUIDS, sizeof(remote_uuids), - &remote_uuids}; + bt_property_t remote_properties = {BT_PROPERTY_UUIDS, sizeof(remote_uuids), &remote_uuids}; const RawAddress& bd_addr = p_dev_cb->link_spec.addrt.bda; p_dev_cb->hid_srvc.headtracker_support = BTA_HH_UNAVAILABLE; @@ -170,7 +158,7 @@ bool bta_hh_headtracker_supported(tBTA_HH_DEV_CB* p_dev_cb) { (p_dev_cb->hid_srvc.headtracker_support == BTA_HH_AVAILABLE)); } - return (p_dev_cb->hid_srvc.headtracker_support == BTA_HH_AVAILABLE); + return p_dev_cb->hid_srvc.headtracker_support == BTA_HH_AVAILABLE; } /******************************************************************************* @@ -183,10 +171,9 @@ bool bta_hh_headtracker_supported(tBTA_HH_DEV_CB* p_dev_cb) { * ******************************************************************************/ uint16_t bta_hh_get_uuid16(tBTA_HH_DEV_CB* p_dev_cb, Uuid uuid) { - if (bta_hh_headtracker_supported(p_dev_cb) && - (uuid == ANDROID_HEADTRACKER_VERSION_CHARAC_UUID || - uuid == ANDROID_HEADTRACKER_CONTROL_CHARAC_UUID || - uuid == ANDROID_HEADTRACKER_REPORT_CHARAC_UUID)) { + if (bta_hh_headtracker_supported(p_dev_cb) && (uuid == ANDROID_HEADTRACKER_VERSION_CHARAC_UUID || + uuid == ANDROID_HEADTRACKER_CONTROL_CHARAC_UUID || + uuid == ANDROID_HEADTRACKER_REPORT_CHARAC_UUID)) { return GATT_UUID_HID_REPORT; } else if (!uuid.Is16Bit()) { log::warn("UUID is not 16 bit"); diff --git a/system/bta/hh/bta_hh_int.h b/system/bta/hh/bta_hh_int.h index b39ac1b998e..7a011b8f510 100644 --- a/system/bta/hh/bta_hh_int.h +++ b/system/bta/hh/bta_hh_int.h @@ -157,11 +157,7 @@ enum tBTA_HH_SERVICE_STATE { BTA_HH_SERVICE_DISCOVERED, }; -enum tBTA_HH_AVAILABLE { - BTA_HH_UNKNOWN = 0, - BTA_HH_AVAILABLE, - BTA_HH_UNAVAILABLE -}; +enum tBTA_HH_AVAILABLE { BTA_HH_UNKNOWN = 0, BTA_HH_AVAILABLE, BTA_HH_UNAVAILABLE }; typedef struct { tBTA_HH_SERVICE_STATE state; @@ -171,8 +167,7 @@ typedef struct { uint16_t proto_mode_handle; uint8_t control_point_handle; - uint8_t - incl_srvc_inst; /* assuming only one included service : battery service */ + uint8_t incl_srvc_inst; /* assuming only one included service : battery service */ uint8_t cur_expl_char_idx; /* currently discovering service index */ uint8_t* rpt_map; uint16_t ext_rpt_ref; @@ -186,28 +181,28 @@ typedef struct { * uint8_t */ #define BTA_HH_GET_LE_DEV_HDL(x) (uint8_t)(((x) + 1) << 4) /* check to see if th edevice handle is a LE device handle */ -#define BTA_HH_IS_LE_DEV_HDL(x) ((x)&0xf0) +#define BTA_HH_IS_LE_DEV_HDL(x) ((x) & 0xf0) #define BTA_HH_IS_LE_DEV_HDL_VALID(x) (((x) >> 4) <= BTA_HH_LE_MAX_KNOWN) /* device control block */ typedef struct { tBTA_HH_DEV_DSCP_INFO dscp_info; /* report descriptor and DI information */ - tAclLinkSpec link_spec; /* ACL link specification of the HID device */ + tAclLinkSpec link_spec; /* ACL link specification of the HID device */ uint16_t attr_mask; /* attribute mask */ uint16_t w4_evt; /* W4_handshake event name */ uint8_t index; /* index number referenced to handle index */ uint8_t sub_class; /* Cod sub class */ uint8_t app_id; /* application ID for this connection */ - uint8_t hid_handle; /* device handle : low 4 bits for regular HID: - HID_HOST_MAX_DEVICES can not exceed 15; - high 4 bits for LE HID: - GATT_MAX_PHY_CHANNEL can not exceed 15 */ - bool vp; /* virtually unplug flag */ - bool in_use; /* control block currently in use */ - bool incoming_conn; /* is incoming connection? */ - uint8_t incoming_hid_handle; /* temporary handle for incoming connection? */ - tBTA_HH_PROTO_MODE mode; /* protocol mode */ - tBTA_HH_STATE state; /* CB state */ + uint8_t hid_handle; /* device handle : low 4 bits for regular HID: + HID_HOST_MAX_DEVICES can not exceed 15; + high 4 bits for LE HID: + GATT_MAX_PHY_CHANNEL can not exceed 15 */ + bool vp; /* virtually unplug flag */ + bool in_use; /* control block currently in use */ + bool incoming_conn; /* is incoming connection? */ + uint8_t incoming_hid_handle; /* temporary handle for incoming connection? */ + tBTA_HH_PROTO_MODE mode; /* protocol mode */ + tBTA_HH_STATE state; /* CB state */ #define BTA_HH_LE_DISC_NONE 0x00 #define BTA_HH_LE_DISC_HIDS 0x01 @@ -234,18 +229,18 @@ typedef struct { * Main Control Block ******************************************************************************/ typedef struct { - tBTA_HH_DEV_CB kdev[BTA_HH_MAX_DEVICE]; /* device control block */ - tBTA_HH_DEV_CB* p_cur; /* current device control - block idx, used in sdp */ - uint8_t cb_index[BTA_HH_MAX_KNOWN]; /* maintain a CB index - map to dev handle */ + tBTA_HH_DEV_CB kdev[BTA_HH_MAX_DEVICE]; /* device control block */ + tBTA_HH_DEV_CB* p_cur; /* current device control + block idx, used in sdp */ + uint8_t cb_index[BTA_HH_MAX_KNOWN]; /* maintain a CB index + map to dev handle */ uint8_t le_cb_index[BTA_HH_LE_MAX_KNOWN]; /* maintain a CB index map to LE dev handle */ tGATT_IF gatt_if; tBTA_HH_CBACK* p_cback; /* Application callbacks */ tSDP_DISCOVERY_DB* p_disc_db; - uint8_t cnt_num; /* connected device number */ - bool w4_disable; /* w4 disable flag */ + uint8_t cnt_num; /* connected device number */ + bool w4_disable; /* w4 disable flag */ } tBTA_HH_CB; extern tBTA_HH_CB bta_hh_cb; @@ -257,8 +252,7 @@ extern tBTA_HH_CFG* p_bta_hh_cfg; * Function prototypes ****************************************************************************/ bool bta_hh_hdl_event(const BT_HDR_RIGID* p_msg); -void bta_hh_sm_execute(tBTA_HH_DEV_CB* p_cb, uint16_t event, - const tBTA_HH_DATA* p_data); +void bta_hh_sm_execute(tBTA_HH_DEV_CB* p_cb, uint16_t event, const tBTA_HH_DATA* p_data); /* action functions */ void bta_hh_api_disc_act(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* p_data); @@ -281,26 +275,21 @@ tBTA_HH_DEV_CB* bta_hh_get_cb(const tAclLinkSpec& link_spec); bool bta_hh_tod_spt(tBTA_HH_DEV_CB* p_cb, uint8_t sub_class); void bta_hh_clean_up_kdev(tBTA_HH_DEV_CB* p_cb); -void bta_hh_add_device_to_list(tBTA_HH_DEV_CB* p_cb, uint8_t handle, - uint16_t attr_mask, - const tHID_DEV_DSCP_INFO* p_dscp_info, - uint8_t sub_class, uint16_t max_latency, - uint16_t min_tout, uint8_t app_id); -void bta_hh_update_di_info(tBTA_HH_DEV_CB* p_cb, uint16_t vendor_id, - uint16_t product_id, uint16_t version, uint8_t flag, - uint8_t ctry_code); +void bta_hh_add_device_to_list(tBTA_HH_DEV_CB* p_cb, uint8_t handle, uint16_t attr_mask, + const tHID_DEV_DSCP_INFO* p_dscp_info, uint8_t sub_class, + uint16_t max_latency, uint16_t min_tout, uint8_t app_id); +void bta_hh_update_di_info(tBTA_HH_DEV_CB* p_cb, uint16_t vendor_id, uint16_t product_id, + uint16_t version, uint8_t flag, uint8_t ctry_code); void bta_hh_cleanup_disable(tBTA_HH_STATUS status); uint8_t bta_hh_dev_handle_to_cb_idx(uint8_t dev_handle); /* action functions used outside state machine */ -void bta_hh_api_enable(tBTA_HH_CBACK* p_cback, bool enable_hid, - bool enable_hogp); +void bta_hh_api_enable(tBTA_HH_CBACK* p_cback, bool enable_hid, bool enable_hogp); void bta_hh_api_disable(void); void bta_hh_disc_cmpl(void); -tBTA_HH_STATUS bta_hh_read_ssr_param(const tAclLinkSpec& link_spec, - uint16_t* p_max_ssr_lat, +tBTA_HH_STATUS bta_hh_read_ssr_param(const tAclLinkSpec& link_spec, uint16_t* p_max_ssr_lat, uint16_t* p_min_ssr_tout); /* functions for LE HID */ @@ -310,8 +299,7 @@ void bta_hh_le_open_conn(tBTA_HH_DEV_CB* p_cb, const tAclLinkSpec& link_spec); void bta_hh_le_api_disc_act(tBTA_HH_DEV_CB* p_cb); void bta_hh_le_get_dscp_act(tBTA_HH_DEV_CB* p_cb); void bta_hh_le_write_dev_act(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* p_data); -uint8_t bta_hh_le_add_device(tBTA_HH_DEV_CB* p_cb, - const tBTA_HH_MAINT_DEV* p_dev_info); +uint8_t bta_hh_le_add_device(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_MAINT_DEV* p_dev_info); void bta_hh_le_remove_dev_bg_conn(tBTA_HH_DEV_CB* p_cb); void bta_hh_le_open_fail(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* p_data); void bta_hh_gatt_open(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* p_data); @@ -320,22 +308,17 @@ void bta_hh_start_security(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* p_buf); void bta_hh_start_security(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* p_buf); void bta_hh_security_cmpl(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* p_buf); -void bta_hh_le_notify_enc_cmpl(tBTA_HH_DEV_CB* p_cb, - const tBTA_HH_DATA* p_data); - -tBTA_HH_LE_RPT* bta_hh_le_find_alloc_report_entry(tBTA_HH_DEV_CB* p_cb, - uint8_t srvc_inst_id, - uint16_t rpt_uuid, - uint16_t inst_id); -void bta_hh_le_save_report_ref(tBTA_HH_DEV_CB* p_dev_cb, tBTA_HH_LE_RPT* p_rpt, - uint8_t rpt_type, uint8_t rpt_id); +void bta_hh_le_notify_enc_cmpl(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* p_data); + +tBTA_HH_LE_RPT* bta_hh_le_find_alloc_report_entry(tBTA_HH_DEV_CB* p_cb, uint8_t srvc_inst_id, + uint16_t rpt_uuid, uint16_t inst_id); +void bta_hh_le_save_report_ref(tBTA_HH_DEV_CB* p_dev_cb, tBTA_HH_LE_RPT* p_rpt, uint8_t rpt_type, + uint8_t rpt_id); void bta_hh_le_srvc_init(tBTA_HH_DEV_CB* p_dev_cb, uint16_t handle); -void bta_hh_le_save_report_map(tBTA_HH_DEV_CB* p_dev_cb, uint16_t len, - uint8_t* desc); +void bta_hh_le_save_report_map(tBTA_HH_DEV_CB* p_dev_cb, uint16_t len, uint8_t* desc); void bta_hh_le_service_parsed(tBTA_HH_DEV_CB* p_dev_cb, tGATT_STATUS status); -void bta_hh_headtracker_parse_service(tBTA_HH_DEV_CB* p_dev_cb, - const gatt::Service* service); +void bta_hh_headtracker_parse_service(tBTA_HH_DEV_CB* p_dev_cb, const gatt::Service* service); bool bta_hh_headtracker_supported(tBTA_HH_DEV_CB* p_dev_cb); uint16_t bta_hh_get_uuid16(tBTA_HH_DEV_CB* p_dev_cb, bluetooth::Uuid uuid); @@ -345,8 +328,7 @@ void bta_hh_trace_dev_db(void); namespace fmt { template <> -struct formatter - : enum_formatter {}; +struct formatter : enum_formatter {}; } // namespace fmt #endif diff --git a/system/bta/hh/bta_hh_le.cc b/system/bta/hh/bta_hh_le.cc index c0ebbd5a82c..4b3c2099c44 100644 --- a/system/bta/hh/bta_hh_le.cc +++ b/system/bta/hh/bta_hh_le.cc @@ -73,23 +73,20 @@ constexpr char kBtmLogTag[] = "LE HIDH"; } static const uint16_t bta_hh_uuid_to_rtp_type[BTA_LE_HID_RTP_UUID_MAX][2] = { - {GATT_UUID_HID_REPORT, BTA_HH_RPTT_INPUT}, - {GATT_UUID_HID_BT_KB_INPUT, BTA_HH_RPTT_INPUT}, - {GATT_UUID_HID_BT_KB_OUTPUT, BTA_HH_RPTT_OUTPUT}, - {GATT_UUID_HID_BT_MOUSE_INPUT, BTA_HH_RPTT_INPUT}, - {GATT_UUID_BATTERY_LEVEL, BTA_HH_RPTT_INPUT}}; + {GATT_UUID_HID_REPORT, BTA_HH_RPTT_INPUT}, + {GATT_UUID_HID_BT_KB_INPUT, BTA_HH_RPTT_INPUT}, + {GATT_UUID_HID_BT_KB_OUTPUT, BTA_HH_RPTT_OUTPUT}, + {GATT_UUID_HID_BT_MOUSE_INPUT, BTA_HH_RPTT_INPUT}, + {GATT_UUID_BATTERY_LEVEL, BTA_HH_RPTT_INPUT}}; static void bta_hh_gattc_callback(tBTA_GATTC_EVT event, tBTA_GATTC* p_data); static void bta_hh_le_add_dev_bg_conn(tBTA_HH_DEV_CB* p_cb); -static void bta_hh_process_cache_rpt(tBTA_HH_DEV_CB* p_cb, - tBTA_HH_RPT_CACHE_ENTRY* p_rpt_cache, +static void bta_hh_process_cache_rpt(tBTA_HH_DEV_CB* p_cb, tBTA_HH_RPT_CACHE_ENTRY* p_rpt_cache, uint8_t num_rpt); -static bool bta_hh_le_iso_data_callback(const RawAddress& addr, - uint16_t cis_conn_hdl, uint8_t* data, - uint16_t size, uint32_t timestamp); +static bool bta_hh_le_iso_data_callback(const RawAddress& addr, uint16_t cis_conn_hdl, + uint8_t* data, uint16_t size, uint32_t timestamp); -static const char* bta_hh_le_rpt_name[4] = {"UNKNOWN", "INPUT", "OUTPUT", - "FEATURE"}; +static const char* bta_hh_le_rpt_name[4] = {"UNKNOWN", "INPUT", "OUTPUT", "FEATURE"}; /******************************************************************************* * @@ -104,28 +101,38 @@ static const char* bta_hh_le_rpt_name[4] = {"UNKNOWN", "INPUT", "OUTPUT", static void bta_hh_le_hid_report_dbg(tBTA_HH_DEV_CB* p_cb) { log::verbose("HID Report DB"); - if (p_cb->hid_srvc.state < BTA_HH_SERVICE_DISCOVERED) return; + if (p_cb->hid_srvc.state < BTA_HH_SERVICE_DISCOVERED) { + return; + } tBTA_HH_LE_RPT* p_rpt = &p_cb->hid_srvc.report[0]; for (int j = 0; j < BTA_HH_LE_RPT_MAX; j++, p_rpt++) { const char* rpt_name = "Unknown"; - if (!p_rpt->in_use) break; + if (!p_rpt->in_use) { + break; + } - if (p_rpt->uuid == GATT_UUID_HID_REPORT) rpt_name = "Report"; - if (p_rpt->uuid == GATT_UUID_HID_BT_KB_INPUT) rpt_name = "Boot KB Input"; - if (p_rpt->uuid == GATT_UUID_HID_BT_KB_OUTPUT) rpt_name = "Boot KB Output"; - if (p_rpt->uuid == GATT_UUID_HID_BT_MOUSE_INPUT) rpt_name = "Boot MI Input"; + if (p_rpt->uuid == GATT_UUID_HID_REPORT) { + rpt_name = "Report"; + } + if (p_rpt->uuid == GATT_UUID_HID_BT_KB_INPUT) { + rpt_name = "Boot KB Input"; + } + if (p_rpt->uuid == GATT_UUID_HID_BT_KB_OUTPUT) { + rpt_name = "Boot KB Output"; + } + if (p_rpt->uuid == GATT_UUID_HID_BT_MOUSE_INPUT) { + rpt_name = "Boot MI Input"; + } log::verbose( - "\t\t[{}-0x{:04x}] [Type:{}], [ReportID:{}] [srvc_inst_id:{}] " - "[char_inst_id:{}] [Clt_cfg:{}]", - rpt_name, p_rpt->uuid, - ((p_rpt->rpt_type < 4) ? bta_hh_le_rpt_name[p_rpt->rpt_type] - : "UNKNOWN"), - p_rpt->rpt_id, p_rpt->srvc_inst_id, p_rpt->char_inst_id, - p_rpt->client_cfg_value); + "\t\t[{}-0x{:04x}] [Type:{}], [ReportID:{}] [srvc_inst_id:{}] " + "[char_inst_id:{}] [Clt_cfg:{}]", + rpt_name, p_rpt->uuid, + ((p_rpt->rpt_type < 4) ? bta_hh_le_rpt_name[p_rpt->rpt_type] : "UNKNOWN"), + p_rpt->rpt_id, p_rpt->srvc_inst_id, p_rpt->char_inst_id, p_rpt->client_cfg_value); } } @@ -182,11 +189,11 @@ void bta_hh_le_enable(void) { bta_hh_cb.gatt_if = BTA_GATTS_INVALID_IF; - for (xx = 0; xx < ARRAY_SIZE(bta_hh_cb.le_cb_index); xx++) + for (xx = 0; xx < ARRAY_SIZE(bta_hh_cb.le_cb_index); xx++) { bta_hh_cb.le_cb_index[xx] = BTA_HH_IDX_INVALID; + } - BTA_GATTC_AppRegister(bta_hh_gattc_callback, - base::Bind([](uint8_t client_id, uint8_t r_status) { + BTA_GATTC_AppRegister(bta_hh_gattc_callback, base::Bind([](uint8_t client_id, uint8_t r_status) { tBTA_HH bta_hh; bta_hh.status = BTA_HH_ERR; @@ -203,7 +210,8 @@ void bta_hh_le_enable(void) { /* signal BTA call back event */ (*bta_hh_cb.p_cback)(BTA_HH_ENABLE_EVT, &bta_hh); } - }), false); + }), + false); if (com::android::bluetooth::flags::leaudio_dynamic_spatial_audio()) { LeAudioClient::RegisterIsoDataConsumer(bta_hh_le_iso_data_callback); @@ -234,12 +242,15 @@ void bta_hh_le_deregister(void) { BTA_GATTC_AppDeregister(bta_hh_cb.gatt_if); } static uint8_t bta_hh_le_get_le_dev_hdl(uint8_t cb_index) { uint8_t i; for (i = 0; i < ARRAY_SIZE(bta_hh_cb.le_cb_index); i++) { - if (bta_hh_cb.le_cb_index[i] == cb_index) return BTA_HH_GET_LE_DEV_HDL(i); + if (bta_hh_cb.le_cb_index[i] == cb_index) { + return BTA_HH_GET_LE_DEV_HDL(i); + } } for (i = 0; i < ARRAY_SIZE(bta_hh_cb.le_cb_index); i++) { - if (bta_hh_cb.le_cb_index[i] == BTA_HH_IDX_INVALID) + if (bta_hh_cb.le_cb_index[i] == BTA_HH_IDX_INVALID) { return BTA_HH_GET_LE_DEV_HDL(i); + } } return BTA_HH_IDX_INVALID; } @@ -267,8 +278,7 @@ void bta_hh_le_open_conn(tBTA_HH_DEV_CB* p_cb, const tAclLinkSpec& link_spec) { bta_hh_cb.le_cb_index[BTA_HH_GET_LE_CB_IDX(p_cb->hid_handle)] = p_cb->index; p_cb->in_use = true; - BTA_GATTC_Open(bta_hh_cb.gatt_if, link_spec.addrt.bda, - BTM_BLE_DIRECT_CONNECTION, false); + BTA_GATTC_Open(bta_hh_cb.gatt_if, link_spec.addrt.bda, BTM_BLE_DIRECT_CONNECTION, false); } /******************************************************************************* @@ -284,7 +294,9 @@ static tBTA_HH_DEV_CB* bta_hh_le_find_dev_cb_by_conn_id(uint16_t conn_id) { tBTA_HH_DEV_CB* p_dev_cb = &bta_hh_cb.kdev[0]; for (i = 0; i < BTA_HH_MAX_DEVICE; i++, p_dev_cb++) { - if (p_dev_cb->in_use && p_dev_cb->conn_id == conn_id) return p_dev_cb; + if (p_dev_cb->in_use && p_dev_cb->conn_id == conn_id) { + return p_dev_cb; + } } return NULL; } @@ -297,16 +309,15 @@ static tBTA_HH_DEV_CB* bta_hh_le_find_dev_cb_by_conn_id(uint16_t conn_id) { * specification. * ******************************************************************************/ -static tBTA_HH_DEV_CB* bta_hh_le_find_dev_cb_by_bda( - const tAclLinkSpec& link_spec) { +static tBTA_HH_DEV_CB* bta_hh_le_find_dev_cb_by_bda(const tAclLinkSpec& link_spec) { uint8_t i; tBTA_HH_DEV_CB* p_dev_cb = &bta_hh_cb.kdev[0]; for (i = 0; i < BTA_HH_MAX_DEVICE; i++, p_dev_cb++) { - if (p_dev_cb->in_use && - p_dev_cb->link_spec.addrt.bda == link_spec.addrt.bda && - p_dev_cb->link_spec.transport == BT_TRANSPORT_LE) + if (p_dev_cb->in_use && p_dev_cb->link_spec.addrt.bda == link_spec.addrt.bda && + p_dev_cb->link_spec.transport == BT_TRANSPORT_LE) { return p_dev_cb; + } } return NULL; } @@ -318,8 +329,8 @@ static tBTA_HH_DEV_CB* bta_hh_le_find_dev_cb_by_bda( * Description find HID service instance ID by battery service instance ID * ******************************************************************************/ -static uint8_t bta_hh_le_find_service_inst_by_battery_inst_id( - tBTA_HH_DEV_CB* p_cb, uint8_t ba_inst_id) { +static uint8_t bta_hh_le_find_service_inst_by_battery_inst_id(tBTA_HH_DEV_CB* p_cb, + uint8_t ba_inst_id) { if (p_cb->hid_srvc.state >= BTA_HH_SERVICE_DISCOVERED && p_cb->hid_srvc.incl_srvc_inst == ba_inst_id) { return p_cb->hid_srvc.srvc_inst_id; @@ -335,18 +346,19 @@ static uint8_t bta_hh_le_find_service_inst_by_battery_inst_id( * and instance ID * ******************************************************************************/ -static tBTA_HH_LE_RPT* bta_hh_le_find_report_entry( - tBTA_HH_DEV_CB* p_cb, uint8_t srvc_inst_id, /* service instance ID */ - uint16_t rpt_uuid, uint16_t char_inst_id) { +static tBTA_HH_LE_RPT* bta_hh_le_find_report_entry(tBTA_HH_DEV_CB* p_cb, + uint8_t srvc_inst_id, /* service instance ID */ + uint16_t rpt_uuid, uint16_t char_inst_id) { uint8_t i; uint8_t hid_inst_id = srvc_inst_id; tBTA_HH_LE_RPT* p_rpt; if (rpt_uuid == GATT_UUID_BATTERY_LEVEL) { - hid_inst_id = - bta_hh_le_find_service_inst_by_battery_inst_id(p_cb, srvc_inst_id); + hid_inst_id = bta_hh_le_find_service_inst_by_battery_inst_id(p_cb, srvc_inst_id); - if (hid_inst_id == BTA_HH_IDX_INVALID) return NULL; + if (hid_inst_id == BTA_HH_IDX_INVALID) { + return NULL; + } } p_rpt = &p_cb->hid_srvc.report[0]; @@ -369,10 +381,8 @@ static tBTA_HH_LE_RPT* bta_hh_le_find_report_entry( * Returns void * ******************************************************************************/ -static tBTA_HH_LE_RPT* bta_hh_le_find_rpt_by_idtype(tBTA_HH_LE_RPT* p_head, - uint8_t mode, - tBTA_HH_RPT_TYPE r_type, - uint8_t rpt_id) { +static tBTA_HH_LE_RPT* bta_hh_le_find_rpt_by_idtype(tBTA_HH_LE_RPT* p_head, uint8_t mode, + tBTA_HH_RPT_TYPE r_type, uint8_t rpt_id) { tBTA_HH_LE_RPT* p_rpt = p_head; uint8_t i; @@ -381,15 +391,18 @@ static tBTA_HH_LE_RPT* bta_hh_le_find_rpt_by_idtype(tBTA_HH_LE_RPT* p_head, for (i = 0; i < BTA_HH_LE_RPT_MAX; i++, p_rpt++) { if (p_rpt->in_use && p_rpt->rpt_id == rpt_id && r_type == p_rpt->rpt_type) { /* return battery report w/o condition */ - if (p_rpt->uuid == GATT_UUID_BATTERY_LEVEL) return p_rpt; + if (p_rpt->uuid == GATT_UUID_BATTERY_LEVEL) { + return p_rpt; + } - if (mode == BTA_HH_PROTO_RPT_MODE && p_rpt->uuid == GATT_UUID_HID_REPORT) + if (mode == BTA_HH_PROTO_RPT_MODE && p_rpt->uuid == GATT_UUID_HID_REPORT) { return p_rpt; + } - if (mode == BTA_HH_PROTO_BOOT_MODE && - (p_rpt->uuid >= GATT_UUID_HID_BT_KB_INPUT && - p_rpt->uuid <= GATT_UUID_HID_BT_MOUSE_INPUT)) + if (mode == BTA_HH_PROTO_BOOT_MODE && (p_rpt->uuid >= GATT_UUID_HID_BT_KB_INPUT && + p_rpt->uuid <= GATT_UUID_HID_BT_MOUSE_INPUT)) { return p_rpt; + } } } return NULL; @@ -403,25 +416,23 @@ static tBTA_HH_LE_RPT* bta_hh_le_find_rpt_by_idtype(tBTA_HH_LE_RPT* p_head, * list. * ******************************************************************************/ -tBTA_HH_LE_RPT* bta_hh_le_find_alloc_report_entry(tBTA_HH_DEV_CB* p_cb, - uint8_t srvc_inst_id, - uint16_t rpt_uuid, - uint16_t inst_id) { +tBTA_HH_LE_RPT* bta_hh_le_find_alloc_report_entry(tBTA_HH_DEV_CB* p_cb, uint8_t srvc_inst_id, + uint16_t rpt_uuid, uint16_t inst_id) { uint8_t i, hid_inst_id = srvc_inst_id; tBTA_HH_LE_RPT* p_rpt; if (rpt_uuid == GATT_UUID_BATTERY_LEVEL) { - hid_inst_id = - bta_hh_le_find_service_inst_by_battery_inst_id(p_cb, srvc_inst_id); + hid_inst_id = bta_hh_le_find_service_inst_by_battery_inst_id(p_cb, srvc_inst_id); - if (hid_inst_id == BTA_HH_IDX_INVALID) return NULL; + if (hid_inst_id == BTA_HH_IDX_INVALID) { + return NULL; + } } p_rpt = &p_cb->hid_srvc.report[0]; for (i = 0; i < BTA_HH_LE_RPT_MAX; i++, p_rpt++) { - if (!p_rpt->in_use || - (p_rpt->uuid == rpt_uuid && p_rpt->srvc_inst_id == srvc_inst_id && - p_rpt->char_inst_id == inst_id)) { + if (!p_rpt->in_use || (p_rpt->uuid == rpt_uuid && p_rpt->srvc_inst_id == srvc_inst_id && + p_rpt->char_inst_id == inst_id)) { if (!p_rpt->in_use) { p_rpt->in_use = true; p_rpt->index = i; @@ -434,12 +445,13 @@ tBTA_HH_LE_RPT* bta_hh_le_find_alloc_report_entry(tBTA_HH_DEV_CB* p_cb, if (bta_hh_uuid_to_rtp_type[i][0] == rpt_uuid) { p_rpt->rpt_type = (tBTA_HH_RPT_TYPE)bta_hh_uuid_to_rtp_type[i][1]; - if (rpt_uuid == GATT_UUID_HID_BT_KB_INPUT || - rpt_uuid == GATT_UUID_HID_BT_KB_OUTPUT) + if (rpt_uuid == GATT_UUID_HID_BT_KB_INPUT || rpt_uuid == GATT_UUID_HID_BT_KB_OUTPUT) { p_rpt->rpt_id = BTA_HH_KEYBD_RPT_ID; + } - if (rpt_uuid == GATT_UUID_HID_BT_MOUSE_INPUT) + if (rpt_uuid == GATT_UUID_HID_BT_MOUSE_INPUT) { p_rpt->rpt_id = BTA_HH_MOUSE_RPT_ID; + } break; } @@ -451,10 +463,9 @@ tBTA_HH_LE_RPT* bta_hh_le_find_alloc_report_entry(tBTA_HH_DEV_CB* p_cb, return NULL; } -static const gatt::Descriptor* find_descriptor_by_short_uuid( - uint16_t conn_id, uint16_t char_handle, uint16_t short_uuid) { - const gatt::Characteristic* p_char = - BTA_GATTC_GetCharacteristic(conn_id, char_handle); +static const gatt::Descriptor* find_descriptor_by_short_uuid(uint16_t conn_id, uint16_t char_handle, + uint16_t short_uuid) { + const gatt::Characteristic* p_char = BTA_GATTC_GetCharacteristic(conn_id, char_handle); if (!p_char) { log::warn("No such characteristic:{}", char_handle); @@ -462,7 +473,9 @@ static const gatt::Descriptor* find_descriptor_by_short_uuid( } for (const gatt::Descriptor& desc : p_char->descriptors) { - if (desc.uuid == Uuid::From16Bit(short_uuid)) return &desc; + if (desc.uuid == Uuid::From16Bit(short_uuid)) { + return &desc; + } } return NULL; @@ -475,14 +488,14 @@ static const gatt::Descriptor* find_descriptor_by_short_uuid( * Description read characteristic descriptor * ******************************************************************************/ -static tBTA_HH_STATUS bta_hh_le_read_char_descriptor(tBTA_HH_DEV_CB* p_cb, - uint16_t char_handle, - uint16_t short_uuid, - GATT_READ_OP_CB cb, +static tBTA_HH_STATUS bta_hh_le_read_char_descriptor(tBTA_HH_DEV_CB* p_cb, uint16_t char_handle, + uint16_t short_uuid, GATT_READ_OP_CB cb, void* cb_data) { const gatt::Descriptor* p_desc = - find_descriptor_by_short_uuid(p_cb->conn_id, char_handle, short_uuid); - if (!p_desc) return BTA_HH_ERR; + find_descriptor_by_short_uuid(p_cb->conn_id, char_handle, short_uuid); + if (!p_desc) { + return BTA_HH_ERR; + } BtaGattQueue::ReadDescriptor(p_cb->conn_id, p_desc->handle, cb, cb_data); return BTA_HH_OK; @@ -497,14 +510,15 @@ static tBTA_HH_STATUS bta_hh_le_read_char_descriptor(tBTA_HH_DEV_CB* p_cb, * Parameters: * ******************************************************************************/ -void bta_hh_le_save_report_ref(tBTA_HH_DEV_CB* p_dev_cb, tBTA_HH_LE_RPT* p_rpt, - uint8_t rpt_type, uint8_t rpt_id) { +void bta_hh_le_save_report_ref(tBTA_HH_DEV_CB* p_dev_cb, tBTA_HH_LE_RPT* p_rpt, uint8_t rpt_type, + uint8_t rpt_id) { log::verbose("report ID:{}, report type: {}", rpt_id, rpt_type); p_rpt->rpt_id = rpt_id; p_rpt->rpt_type = rpt_type; - if (p_rpt->rpt_type > BTA_HH_RPTT_FEATURE) /* invalid report type */ + if (p_rpt->rpt_type > BTA_HH_RPTT_FEATURE) { /* invalid report type */ p_rpt->rpt_type = BTA_HH_RPTT_RESRV; + } tBTA_HH_RPT_CACHE_ENTRY rpt_entry; rpt_entry.rpt_id = p_rpt->rpt_id; @@ -526,8 +540,7 @@ void bta_hh_le_save_report_ref(tBTA_HH_DEV_CB* p_dev_cb, tBTA_HH_LE_RPT* p_rpt, * Parameters: * ******************************************************************************/ -static void bta_hh_le_register_input_notif(tBTA_HH_DEV_CB* p_dev_cb, - uint8_t proto_mode, +static void bta_hh_le_register_input_notif(tBTA_HH_DEV_CB* p_dev_cb, uint8_t proto_mode, bool register_ba) { tBTA_HH_LE_RPT* p_rpt = &p_dev_cb->hid_srvc.report[0]; @@ -536,8 +549,7 @@ static void bta_hh_le_register_input_notif(tBTA_HH_DEV_CB* p_dev_cb, for (int i = 0; i < BTA_HH_LE_RPT_MAX; i++, p_rpt++) { if (p_rpt->rpt_type == BTA_HH_RPTT_INPUT) { if (register_ba && p_rpt->uuid == GATT_UUID_BATTERY_LEVEL) { - BTA_GATTC_RegisterForNotifications(bta_hh_cb.gatt_if, - p_dev_cb->link_spec.addrt.bda, + BTA_GATTC_RegisterForNotifications(bta_hh_cb.gatt_if, p_dev_cb->link_spec.addrt.bda, p_rpt->char_inst_id); } /* boot mode, deregister report input notification */ @@ -545,16 +557,14 @@ static void bta_hh_le_register_input_notif(tBTA_HH_DEV_CB* p_dev_cb, if (p_rpt->uuid == GATT_UUID_HID_REPORT && p_rpt->client_cfg_value == GATT_CLT_CONFIG_NOTIFICATION) { log::verbose("---> Deregister Report ID:{}", p_rpt->rpt_id); - BTA_GATTC_DeregisterForNotifications(bta_hh_cb.gatt_if, - p_dev_cb->link_spec.addrt.bda, + BTA_GATTC_DeregisterForNotifications(bta_hh_cb.gatt_if, p_dev_cb->link_spec.addrt.bda, p_rpt->char_inst_id); } /* register boot reports notification */ else if (p_rpt->uuid == GATT_UUID_HID_BT_KB_INPUT || p_rpt->uuid == GATT_UUID_HID_BT_MOUSE_INPUT) { log::verbose("<--- Register Boot Report ID:{}", p_rpt->rpt_id); - BTA_GATTC_RegisterForNotifications(bta_hh_cb.gatt_if, - p_dev_cb->link_spec.addrt.bda, + BTA_GATTC_RegisterForNotifications(bta_hh_cb.gatt_if, p_dev_cb->link_spec.addrt.bda, p_rpt->char_inst_id); } } else if (proto_mode == BTA_HH_PROTO_RPT_MODE) { @@ -562,14 +572,12 @@ static void bta_hh_le_register_input_notif(tBTA_HH_DEV_CB* p_dev_cb, p_rpt->uuid == GATT_UUID_HID_BT_MOUSE_INPUT) && p_rpt->client_cfg_value == GATT_CLT_CONFIG_NOTIFICATION) { log::verbose("--> Deregister Boot Report ID:{}", p_rpt->rpt_id); - BTA_GATTC_DeregisterForNotifications(bta_hh_cb.gatt_if, - p_dev_cb->link_spec.addrt.bda, + BTA_GATTC_DeregisterForNotifications(bta_hh_cb.gatt_if, p_dev_cb->link_spec.addrt.bda, p_rpt->char_inst_id); } else if (p_rpt->uuid == GATT_UUID_HID_REPORT && p_rpt->client_cfg_value == GATT_CLT_CONFIG_NOTIFICATION) { log::verbose("<--- Register Report ID:{}", p_rpt->rpt_id); - BTA_GATTC_RegisterForNotifications(bta_hh_cb.gatt_if, - p_dev_cb->link_spec.addrt.bda, + BTA_GATTC_RegisterForNotifications(bta_hh_cb.gatt_if, p_dev_cb->link_spec.addrt.bda, p_rpt->char_inst_id); } } @@ -594,15 +602,13 @@ static void bta_hh_le_deregister_input_notif(tBTA_HH_DEV_CB* p_dev_cb) { if (p_rpt->uuid == GATT_UUID_HID_REPORT && p_rpt->client_cfg_value == GATT_CLT_CONFIG_NOTIFICATION) { log::verbose("---> Deregister Report ID:{}", p_rpt->rpt_id); - BTA_GATTC_DeregisterForNotifications(bta_hh_cb.gatt_if, - p_dev_cb->link_spec.addrt.bda, + BTA_GATTC_DeregisterForNotifications(bta_hh_cb.gatt_if, p_dev_cb->link_spec.addrt.bda, p_rpt->char_inst_id); } else if ((p_rpt->uuid == GATT_UUID_HID_BT_KB_INPUT || p_rpt->uuid == GATT_UUID_HID_BT_MOUSE_INPUT) && p_rpt->client_cfg_value == GATT_CLT_CONFIG_NOTIFICATION) { log::verbose("---> Deregister Boot Report ID:{}", p_rpt->rpt_id); - BTA_GATTC_DeregisterForNotifications(bta_hh_cb.gatt_if, - p_dev_cb->link_spec.addrt.bda, + BTA_GATTC_DeregisterForNotifications(bta_hh_cb.gatt_if, p_dev_cb->link_spec.addrt.bda, p_rpt->char_inst_id); } } @@ -622,8 +628,7 @@ static void bta_hh_le_open_cmpl(tBTA_HH_DEV_CB* p_cb) { bta_hh_le_register_input_notif(p_cb, p_cb->mode, true); bta_hh_sm_execute(p_cb, BTA_HH_OPEN_CMPL_EVT, NULL); - if (!com::android::bluetooth::flags:: - prevent_hogp_reconnect_when_connected()) { + if (!com::android::bluetooth::flags::prevent_hogp_reconnect_when_connected()) { if (kBTA_HH_LE_RECONN && p_cb->status == BTA_HH_OK) { bta_hh_le_add_dev_bg_conn(p_cb); } @@ -640,39 +645,37 @@ static void bta_hh_le_open_cmpl(tBTA_HH_DEV_CB* p_cb) { * a characteristic * ******************************************************************************/ -static bool bta_hh_le_write_ccc(tBTA_HH_DEV_CB* p_cb, uint16_t char_handle, - uint16_t clt_cfg_value, GATT_WRITE_OP_CB cb, - void* cb_data) { - const gatt::Descriptor* p_desc = find_descriptor_by_short_uuid( - p_cb->conn_id, char_handle, GATT_UUID_CHAR_CLIENT_CONFIG); - if (!p_desc) return false; +static bool bta_hh_le_write_ccc(tBTA_HH_DEV_CB* p_cb, uint16_t char_handle, uint16_t clt_cfg_value, + GATT_WRITE_OP_CB cb, void* cb_data) { + const gatt::Descriptor* p_desc = + find_descriptor_by_short_uuid(p_cb->conn_id, char_handle, GATT_UUID_CHAR_CLIENT_CONFIG); + if (!p_desc) { + return false; + } vector value(2); uint8_t* ptr = value.data(); UINT16_TO_STREAM(ptr, clt_cfg_value); - BtaGattQueue::WriteDescriptor(p_cb->conn_id, p_desc->handle, std::move(value), - GATT_WRITE, cb, cb_data); + BtaGattQueue::WriteDescriptor(p_cb->conn_id, p_desc->handle, std::move(value), GATT_WRITE, cb, + cb_data); return true; } static bool bta_hh_le_write_rpt_clt_cfg(tBTA_HH_DEV_CB* p_cb); -static void write_rpt_clt_cfg_cb(uint16_t conn_id, tGATT_STATUS status, - uint16_t handle, uint16_t len, - const uint8_t* value, void* data) { +static void write_rpt_clt_cfg_cb(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, + uint16_t len, const uint8_t* value, void* data) { uint8_t srvc_inst_id; tBTA_HH_DEV_CB* p_dev_cb = (tBTA_HH_DEV_CB*)data; - const gatt::Characteristic* characteristic = - BTA_GATTC_GetOwningCharacteristic(conn_id, handle); + const gatt::Characteristic* characteristic = BTA_GATTC_GetOwningCharacteristic(conn_id, handle); if (characteristic == nullptr) { log::error("Characteristic with handle {} not found clt cfg", handle); return; } if (!characteristic->uuid.Is16Bit()) { - log::error("Unexpected len characteristic ID clt cfg: {}", - characteristic->uuid.ToString()); + log::error("Unexpected len characteristic ID clt cfg: {}", characteristic->uuid.ToString()); return; } @@ -686,9 +689,10 @@ static void write_rpt_clt_cfg_cb(uint16_t conn_id, tGATT_STATUS status, case GATT_UUID_HID_BT_KB_INPUT: case GATT_UUID_HID_BT_MOUSE_INPUT: case GATT_UUID_HID_REPORT: - if (status == GATT_SUCCESS) + if (status == GATT_SUCCESS) { p_dev_cb->hid_srvc.report[p_dev_cb->clt_cfg_idx].client_cfg_value = - GATT_CLT_CONFIG_NOTIFICATION; + GATT_CLT_CONFIG_NOTIFICATION; + } p_dev_cb->clt_cfg_idx++; bta_hh_le_write_rpt_clt_cfg(p_dev_cb); break; @@ -710,12 +714,10 @@ static bool bta_hh_le_write_rpt_clt_cfg(tBTA_HH_DEV_CB* p_cb) { uint8_t i; tBTA_HH_LE_RPT* p_rpt = &p_cb->hid_srvc.report[p_cb->clt_cfg_idx]; - for (i = p_cb->clt_cfg_idx; i < BTA_HH_LE_RPT_MAX && p_rpt->in_use; - i++, p_rpt++) { + for (i = p_cb->clt_cfg_idx; i < BTA_HH_LE_RPT_MAX && p_rpt->in_use; i++, p_rpt++) { /* enable notification for all input report, regardless mode */ if (p_rpt->rpt_type == BTA_HH_RPTT_INPUT) { - if (bta_hh_le_write_ccc(p_cb, p_rpt->char_inst_id, - GATT_CLT_CONFIG_NOTIFICATION, + if (bta_hh_le_write_ccc(p_cb, p_rpt->char_inst_id, GATT_CLT_CONFIG_NOTIFICATION, write_rpt_clt_cfg_cb, p_cb)) { p_cb->clt_cfg_idx = i; return true; @@ -745,29 +747,32 @@ void bta_hh_le_service_parsed(tBTA_HH_DEV_CB* p_dev_cb, tGATT_STATUS status) { /* Set protocol finished in CONN state*/ uint16_t cb_evt = p_dev_cb->w4_evt; - if (cb_evt == BTA_HH_EMPTY_EVT) return; + if (cb_evt == BTA_HH_EMPTY_EVT) { + return; + } tBTA_HH_CBDATA cback_data; cback_data.handle = p_dev_cb->hid_handle; cback_data.status = (status == GATT_SUCCESS) ? BTA_HH_OK : BTA_HH_ERR; - if (status == GATT_SUCCESS) + if (status == GATT_SUCCESS) { bta_hh_le_register_input_notif(p_dev_cb, p_dev_cb->mode, false); + } p_dev_cb->w4_evt = BTA_HH_EMPTY_EVT; (*bta_hh_cb.p_cback)(cb_evt, (tBTA_HH*)&cback_data); } else if (p_dev_cb->state == BTA_HH_W4_CONN_ST) { p_dev_cb->status = (status == GATT_SUCCESS) ? BTA_HH_OK : BTA_HH_ERR_PROTO; - if ((p_dev_cb->disc_active & BTA_HH_LE_DISC_HIDS) == 0) + if ((p_dev_cb->disc_active & BTA_HH_LE_DISC_HIDS) == 0) { bta_hh_le_open_cmpl(p_dev_cb); + } } } -static void write_proto_mode_cb(uint16_t conn_id, tGATT_STATUS status, - uint16_t handle, uint16_t len, - const uint8_t* value, void* data) { +static void write_proto_mode_cb(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, + uint16_t len, const uint8_t* value, void* data) { tBTA_HH_DEV_CB* p_dev_cb = (tBTA_HH_DEV_CB*)data; bta_hh_le_service_parsed(p_dev_cb, status); } @@ -779,17 +784,14 @@ static void write_proto_mode_cb(uint16_t conn_id, tGATT_STATUS status, * Description Set remote device protocol mode. * ******************************************************************************/ -static bool bta_hh_le_set_protocol_mode(tBTA_HH_DEV_CB* p_cb, - tBTA_HH_PROTO_MODE mode) { +static bool bta_hh_le_set_protocol_mode(tBTA_HH_DEV_CB* p_cb, tBTA_HH_PROTO_MODE mode) { tBTA_HH_CBDATA cback_data; - log::verbose("attempt mode:{}", - (mode == BTA_HH_PROTO_RPT_MODE) ? "Report" : "Boot"); + log::verbose("attempt mode:{}", (mode == BTA_HH_PROTO_RPT_MODE) ? "Report" : "Boot"); cback_data.handle = p_cb->hid_handle; /* boot mode is not supported in the remote device */ - if (p_cb->hid_srvc.proto_mode_handle == 0 || - bta_hh_headtracker_supported(p_cb)) { + if (p_cb->hid_srvc.proto_mode_handle == 0 || bta_hh_headtracker_supported(p_cb)) { p_cb->mode = BTA_HH_PROTO_RPT_MODE; if (mode == BTA_HH_PROTO_BOOT_MODE) { @@ -802,18 +804,17 @@ static bool bta_hh_le_set_protocol_mode(tBTA_HH_DEV_CB* p_cb, cback_data.status = BTA_HH_OK; } if (p_cb->state == BTA_HH_W4_CONN_ST) { - p_cb->status = - (cback_data.status == BTA_HH_OK) ? BTA_HH_OK : BTA_HH_ERR_PROTO; - } else + p_cb->status = (cback_data.status == BTA_HH_OK) ? BTA_HH_OK : BTA_HH_ERR_PROTO; + } else { (*bta_hh_cb.p_cback)(BTA_HH_SET_PROTO_EVT, (tBTA_HH*)&cback_data); + } } else if (p_cb->mode != mode) { p_cb->mode = mode; mode = (mode == BTA_HH_PROTO_BOOT_MODE) ? BTA_HH_LE_PROTO_BOOT_MODE : BTA_HH_LE_PROTO_REPORT_MODE; - BtaGattQueue::WriteCharacteristic( - p_cb->conn_id, p_cb->hid_srvc.proto_mode_handle, {mode}, - GATT_WRITE_NO_RSP, write_proto_mode_cb, p_cb); + BtaGattQueue::WriteCharacteristic(p_cb->conn_id, p_cb->hid_srvc.proto_mode_handle, {mode}, + GATT_WRITE_NO_RSP, write_proto_mode_cb, p_cb); return true; } @@ -827,9 +828,8 @@ static bool bta_hh_le_set_protocol_mode(tBTA_HH_DEV_CB* p_cb, * application with the protocol mode. * ******************************************************************************/ -static void get_protocol_mode_cb(uint16_t conn_id, tGATT_STATUS status, - uint16_t handle, uint16_t len, uint8_t* value, - void* data) { +static void get_protocol_mode_cb(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, + uint16_t len, uint8_t* value, void* data) { tBTA_HH_DEV_CB* p_dev_cb = (tBTA_HH_DEV_CB*)data; tBTA_HH_HSDATA hs_data; @@ -843,17 +843,17 @@ static void get_protocol_mode_cb(uint16_t conn_id, tGATT_STATUS status, hs_data.rsp_data.proto_mode = *(value); /* LE repot mode is the opposite value of BR/EDR report mode, flip it here */ - if (hs_data.rsp_data.proto_mode == 0) + if (hs_data.rsp_data.proto_mode == 0) { hs_data.rsp_data.proto_mode = BTA_HH_PROTO_BOOT_MODE; - else + } else { hs_data.rsp_data.proto_mode = BTA_HH_PROTO_RPT_MODE; + } p_dev_cb->mode = hs_data.rsp_data.proto_mode; } log::verbose("LE GET_PROTOCOL Mode=[{}]", - (hs_data.rsp_data.proto_mode == BTA_HH_PROTO_RPT_MODE) ? "Report" - : "Boot"); + (hs_data.rsp_data.proto_mode == BTA_HH_PROTO_RPT_MODE) ? "Report" : "Boot"); p_dev_cb->w4_evt = BTA_HH_EMPTY_EVT; (*bta_hh_cb.p_cback)(BTA_HH_GET_PROTO_EVT, (tBTA_HH*)&hs_data); @@ -870,11 +870,9 @@ static void bta_hh_le_get_protocol_mode(tBTA_HH_DEV_CB* p_cb) { tBTA_HH_HSDATA hs_data; p_cb->w4_evt = BTA_HH_GET_PROTO_EVT; - if (p_cb->hid_srvc.state >= BTA_HH_SERVICE_DISCOVERED && - p_cb->hid_srvc.proto_mode_handle != 0 && + if (p_cb->hid_srvc.state >= BTA_HH_SERVICE_DISCOVERED && p_cb->hid_srvc.proto_mode_handle != 0 && !bta_hh_headtracker_supported(p_cb)) { - BtaGattQueue::ReadCharacteristic(p_cb->conn_id, - p_cb->hid_srvc.proto_mode_handle, + BtaGattQueue::ReadCharacteristic(p_cb->conn_id, p_cb->hid_srvc.proto_mode_handle, get_protocol_mode_cb, p_cb); return; } @@ -896,8 +894,7 @@ static void bta_hh_le_get_protocol_mode(tBTA_HH_DEV_CB* p_cb) { * Parameters: * ******************************************************************************/ -static void bta_hh_le_dis_cback(const RawAddress& addr, - tDIS_VALUE* p_dis_value) { +static void bta_hh_le_dis_cback(const RawAddress& addr, tDIS_VALUE* p_dis_value) { tAclLinkSpec link_spec; link_spec.addrt.bda = addr; link_spec.addrt.type = BLE_ADDR_PUBLIC; @@ -922,10 +919,9 @@ static void bta_hh_le_dis_cback(const RawAddress& addr, p_cb->disc_active &= ~BTA_HH_LE_DISC_DIS; /* plug in the PnP info for this device */ if (p_dis_value->attr_mask & DIS_ATTR_PNP_ID_BIT) { - log::verbose( - "Plug in PnP info: product_id={:02x}, vendor_id={:04x}, version={:04x}", - p_dis_value->pnp_id.product_id, p_dis_value->pnp_id.vendor_id, - p_dis_value->pnp_id.product_version); + log::verbose("Plug in PnP info: product_id={:02x}, vendor_id={:04x}, version={:04x}", + p_dis_value->pnp_id.product_id, p_dis_value->pnp_id.vendor_id, + p_dis_value->pnp_id.product_version); p_cb->dscp_info.product_id = p_dis_value->pnp_id.product_id; p_cb->dscp_info.vendor_id = p_dis_value->pnp_id.vendor_id; p_cb->dscp_info.version = p_dis_value->pnp_id.product_version; @@ -949,8 +945,7 @@ static void bta_hh_le_pri_service_discovery(tBTA_HH_DEV_CB* p_cb) { p_cb->disc_active |= (BTA_HH_LE_DISC_HIDS | BTA_HH_LE_DISC_DIS); /* read DIS info */ - if (!DIS_ReadDISInfo(p_cb->link_spec.addrt.bda, bta_hh_le_dis_cback, - DIS_ATTR_PNP_ID_BIT)) { + if (!DIS_ReadDISInfo(p_cb->link_spec.addrt.bda, bta_hh_le_dis_cback, DIS_ATTR_PNP_ID_BIT)) { log::error("read DIS failed"); p_cb->disc_active &= ~BTA_HH_LE_DISC_DIS; } @@ -972,8 +967,7 @@ static void bta_hh_le_pri_service_discovery(tBTA_HH_DEV_CB* p_cb) { * ******************************************************************************/ static void bta_hh_le_encrypt_cback(RawAddress bd_addr, tBT_TRANSPORT transport, - void* /* p_ref_data */, - tBTM_STATUS result) { + void* /* p_ref_data */, tBTM_STATUS result) { tAclLinkSpec link_spec; link_spec.addrt.bda = bd_addr; link_spec.addrt.type = BLE_ADDR_PUBLIC; @@ -1003,8 +997,7 @@ static void bta_hh_le_encrypt_cback(RawAddress bd_addr, tBT_TRANSPORT transport, * Parameters: * ******************************************************************************/ -void bta_hh_security_cmpl(tBTA_HH_DEV_CB* p_cb, - const tBTA_HH_DATA* /* p_buf */) { +void bta_hh_security_cmpl(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* /* p_buf */) { log::verbose("addr:{}, status:{}", p_cb->link_spec, p_cb->status); if (p_cb->status == BTA_HH_OK) { if (p_cb->hid_srvc.state < BTA_HH_SERVICE_DISCOVERED) { @@ -1013,16 +1006,15 @@ void bta_hh_security_cmpl(tBTA_HH_DEV_CB* p_cb, /* start loading the cache if not in stack */ tBTA_HH_RPT_CACHE_ENTRY* p_rpt_cache; uint8_t num_rpt = 0; - if ((p_rpt_cache = bta_hh_le_co_cache_load(p_cb->link_spec, &num_rpt, - p_cb->app_id)) != NULL) { + if ((p_rpt_cache = bta_hh_le_co_cache_load(p_cb->link_spec, &num_rpt, p_cb->app_id)) != + NULL) { log::debug("Cache found, no need to perform service discovery"); bta_hh_process_cache_rpt(p_cb, p_rpt_cache, num_rpt); } } /* discovery has been done for HID service */ - if (p_cb->app_id != 0 && - p_cb->hid_srvc.state >= BTA_HH_SERVICE_DISCOVERED) { + if (p_cb->app_id != 0 && p_cb->hid_srvc.state >= BTA_HH_SERVICE_DISCOVERED) { log::verbose("discovery has been done for HID service"); /* configure protocol mode */ if (!bta_hh_le_set_protocol_mode(p_cb, p_cb->mode)) { @@ -1034,22 +1026,19 @@ void bta_hh_security_cmpl(tBTA_HH_DEV_CB* p_cb, log::verbose("Starting service discovery"); bta_hh_le_pri_service_discovery(p_cb); } - } - else if(p_cb->btm_status == BTM_ERR_KEY_MISSING) { + } else if (p_cb->btm_status == BTM_ERR_KEY_MISSING) { log::error("Received encryption failed status:{} btm_status:{}", - bta_hh_status_text(p_cb->status), - btm_status_text(p_cb->btm_status)); + bta_hh_status_text(p_cb->status), btm_status_text(p_cb->btm_status)); bta_hh_le_api_disc_act(p_cb); } else { - log::error("Encryption failed status:{} btm_status:{}", - bta_hh_status_text(p_cb->status), + log::error("Encryption failed status:{} btm_status:{}", bta_hh_status_text(p_cb->status), btm_status_text(p_cb->btm_status)); if (!(p_cb->status == BTA_HH_ERR_SEC && - (p_cb->btm_status == BTM_ERR_PROCESSING || - p_cb->btm_status == BTM_FAILED_ON_SECURITY || - p_cb->btm_status == BTM_WRONG_MODE))) + (p_cb->btm_status == BTM_ERR_PROCESSING || p_cb->btm_status == BTM_FAILED_ON_SECURITY || + p_cb->btm_status == BTM_WRONG_MODE))) { bta_hh_le_api_disc_act(p_cb); } + } } /******************************************************************************* @@ -1061,8 +1050,7 @@ void bta_hh_security_cmpl(tBTA_HH_DEV_CB* p_cb, * Returns * ******************************************************************************/ -void bta_hh_le_notify_enc_cmpl(tBTA_HH_DEV_CB* p_cb, - const tBTA_HH_DATA* p_buf) { +void bta_hh_le_notify_enc_cmpl(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* p_buf) { if (p_cb == NULL || !p_cb->security_pending || p_buf == NULL || p_buf->le_enc_cmpl.client_if != bta_hh_cb.gatt_if) { return; @@ -1100,8 +1088,7 @@ static void bta_hh_clear_service_cache(tBTA_HH_DEV_CB* p_cb) { * Parameters: * ******************************************************************************/ -void bta_hh_start_security(tBTA_HH_DEV_CB* p_cb, - const tBTA_HH_DATA* /* p_buf */) { +void bta_hh_start_security(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* /* p_buf */) { log::verbose("addr:{}", p_cb->link_spec.addrt.bda); if (BTM_SecIsSecurityPending(p_cb->link_spec.addrt.bda)) { /* if security collision happened, wait for encryption done */ @@ -1119,16 +1106,15 @@ void bta_hh_start_security(tBTA_HH_DEV_CB* p_cb, else if (BTM_IsLinkKeyKnown(p_cb->link_spec.addrt.bda, BT_TRANSPORT_LE)) { log::debug("addr:{} bonded, not encrypted", p_cb->link_spec.addrt.bda); p_cb->status = BTA_HH_ERR_AUTH_FAILED; - BTM_SetEncryption(p_cb->link_spec.addrt.bda, BT_TRANSPORT_LE, - bta_hh_le_encrypt_cback, NULL, BTM_BLE_SEC_ENCRYPT); + BTM_SetEncryption(p_cb->link_spec.addrt.bda, BT_TRANSPORT_LE, bta_hh_le_encrypt_cback, NULL, + BTM_BLE_SEC_ENCRYPT); } /* unbonded device, report security error here */ else { log::debug("addr:{} not bonded", p_cb->link_spec.addrt.bda); p_cb->status = BTA_HH_ERR_AUTH_FAILED; bta_hh_clear_service_cache(p_cb); - BTM_SetEncryption(p_cb->link_spec.addrt.bda, BT_TRANSPORT_LE, - bta_hh_le_encrypt_cback, NULL, + BTM_SetEncryption(p_cb->link_spec.addrt.bda, BT_TRANSPORT_LE, bta_hh_le_encrypt_cback, NULL, BTM_BLE_SEC_ENCRYPT_NO_MITM); } } @@ -1146,10 +1132,11 @@ void bta_hh_gatt_open(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* p_buf) { const tBTA_GATTC_OPEN* p_data = &p_buf->le_open; /* if received invalid callback data , ignore it */ - if (p_cb == NULL || p_data == NULL) return; + if (p_cb == NULL || p_data == NULL) { + return; + } - log::verbose("BTA_GATTC_OPEN_EVT bda={} status={}", p_data->remote_bda, - p_data->status); + log::verbose("BTA_GATTC_OPEN_EVT bda={} status={}", p_data->remote_bda, p_data->status); if (p_data->status == GATT_SUCCESS) { p_cb->hid_handle = bta_hh_le_get_le_dev_hdl(p_cb->index); @@ -1165,8 +1152,8 @@ void bta_hh_gatt_open(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* p_buf) { BtaGattQueue::Clean(p_cb->conn_id); - log::verbose("hid_handle=0x{:2x} conn_id=0x{:04x} cb_index={}", - p_cb->hid_handle, p_cb->conn_id, p_cb->index); + log::verbose("hid_handle=0x{:2x} conn_id=0x{:04x} cb_index={}", p_cb->hid_handle, p_cb->conn_id, + p_cb->index); bta_hh_sm_execute(p_cb, BTA_HH_START_ENC_EVT, NULL); @@ -1200,8 +1187,7 @@ static void bta_hh_le_close(const tBTA_GATTC_CLOSE& gattc_data) { if (p_cb->hid_srvc.state == BTA_HH_SERVICE_CHANGED) { /* Service change would have already prompted a local disconnection */ - log::warn("Disconnected after service changed indication:{}", - gattc_data.remote_bda); + log::warn("Disconnected after service changed indication:{}", gattc_data.remote_bda); return; } @@ -1210,17 +1196,17 @@ static void bta_hh_le_close(const tBTA_GATTC_CLOSE& gattc_data) { post_on_bt_main([=]() { const tBTA_HH_DATA data = { - .le_close = - { - .hdr = + .le_close = { - .event = BTA_HH_GATT_CLOSE_EVT, - .layer_specific = - static_cast(p_cb->hid_handle), + .hdr = + { + .event = BTA_HH_GATT_CLOSE_EVT, + .layer_specific = + static_cast(p_cb->hid_handle), + }, + .conn_id = gattc_data.conn_id, + .reason = gattc_data.reason, }, - .conn_id = gattc_data.conn_id, - .reason = gattc_data.reason, - }, }; bta_hh_sm_execute(p_cb, BTA_HH_GATT_CLOSE_EVT, &data); }); @@ -1235,8 +1221,7 @@ static void bta_hh_le_close(const tBTA_GATTC_CLOSE& gattc_data) { * Parameters: * ******************************************************************************/ -static void bta_hh_le_gatt_disc_cmpl(tBTA_HH_DEV_CB* p_cb, - tBTA_HH_STATUS status) { +static void bta_hh_le_gatt_disc_cmpl(tBTA_HH_DEV_CB* p_cb, tBTA_HH_STATUS status) { log::verbose("status:{}", status); /* if open sucessful or protocol mode not desired, keep the connection open @@ -1255,9 +1240,8 @@ static void bta_hh_le_gatt_disc_cmpl(tBTA_HH_DEV_CB* p_cb, } } -static void read_hid_info_cb(uint16_t conn_id, tGATT_STATUS status, - uint16_t handle, uint16_t len, uint8_t* value, - void* data) { +static void read_hid_info_cb(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, uint16_t len, + uint8_t* value, void* data) { if (status != GATT_SUCCESS) { log::error("error:{}", status); return; @@ -1276,8 +1260,7 @@ static void read_hid_info_cb(uint16_t conn_id, tGATT_STATUS status, STREAM_TO_UINT8(p_dev_cb->dscp_info.flag, pp); } -void bta_hh_le_save_report_map(tBTA_HH_DEV_CB* p_dev_cb, uint16_t len, - uint8_t* desc) { +void bta_hh_le_save_report_map(tBTA_HH_DEV_CB* p_dev_cb, uint16_t len, uint8_t* desc) { tBTA_HH_LE_HID_SRVC* p_srvc = &p_dev_cb->hid_srvc; osi_free_and_reset((void**)&p_srvc->rpt_map); @@ -1292,9 +1275,8 @@ void bta_hh_le_save_report_map(tBTA_HH_DEV_CB* p_dev_cb, uint16_t len, } } -static void read_hid_report_map_cb(uint16_t conn_id, tGATT_STATUS status, - uint16_t handle, uint16_t len, - uint8_t* value, void* data) { +static void read_hid_report_map_cb(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, + uint16_t len, uint8_t* value, void* data) { if (status != GATT_SUCCESS) { log::error("error reading characteristic:{}", status); return; @@ -1304,9 +1286,8 @@ static void read_hid_report_map_cb(uint16_t conn_id, tGATT_STATUS status, bta_hh_le_save_report_map(p_dev_cb, len, value); } -static void read_ext_rpt_ref_desc_cb(uint16_t conn_id, tGATT_STATUS status, - uint16_t handle, uint16_t len, - uint8_t* value, void* data) { +static void read_ext_rpt_ref_desc_cb(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, + uint16_t len, uint8_t* value, void* data) { if (status != GATT_SUCCESS) { log::error("error:{}", status); return; @@ -1324,13 +1305,11 @@ static void read_ext_rpt_ref_desc_cb(uint16_t conn_id, tGATT_STATUS status, STREAM_TO_UINT16(p_dev_cb->hid_srvc.ext_rpt_ref, pp); - log::verbose("External Report Reference UUID 0x{:04x}", - p_dev_cb->hid_srvc.ext_rpt_ref); + log::verbose("External Report Reference UUID 0x{:04x}", p_dev_cb->hid_srvc.ext_rpt_ref); } -static void read_report_ref_desc_cb(uint16_t conn_id, tGATT_STATUS status, - uint16_t handle, uint16_t len, - uint8_t* value, void* data) { +static void read_report_ref_desc_cb(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, + uint16_t len, uint8_t* value, void* data) { if (status != GATT_SUCCESS) { log::error("error:{}", status); return; @@ -1349,14 +1328,11 @@ static void read_report_ref_desc_cb(uint16_t conn_id, tGATT_STATUS status, return; } - const gatt::Characteristic* characteristic = - BTA_GATTC_GetOwningCharacteristic(conn_id, handle); - const gatt::Service* service = - BTA_GATTC_GetOwningService(conn_id, characteristic->value_handle); + const gatt::Characteristic* characteristic = BTA_GATTC_GetOwningCharacteristic(conn_id, handle); + const gatt::Service* service = BTA_GATTC_GetOwningService(conn_id, characteristic->value_handle); tBTA_HH_LE_RPT* p_rpt; - p_rpt = bta_hh_le_find_report_entry(p_dev_cb, service->handle, - GATT_UUID_HID_REPORT, + p_rpt = bta_hh_le_find_report_entry(p_dev_cb, service->handle, GATT_UUID_HID_REPORT, characteristic->value_handle); if (p_rpt == nullptr) { log::error("No such report"); @@ -1372,9 +1348,8 @@ static void read_report_ref_desc_cb(uint16_t conn_id, tGATT_STATUS status, bta_hh_le_save_report_ref(p_dev_cb, p_rpt, rpt_type, rpt_id); } -static void read_pref_conn_params_cb(uint16_t conn_id, tGATT_STATUS status, - uint16_t handle, uint16_t len, - uint8_t* value, void* data) { +static void read_pref_conn_params_cb(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, + uint16_t len, uint8_t* value, void* data) { if (status != GATT_SUCCESS) { log::error("error:{}", status); return; @@ -1396,22 +1371,19 @@ static void read_pref_conn_params_cb(uint16_t conn_id, tGATT_STATUS status, // Make sure both min, and max are bigger than 11.25ms, lower values can // introduce audio issues if A2DP is also active. - L2CA_AdjustConnectionIntervals(&min_interval, &max_interval, - BTM_BLE_CONN_INT_MIN_LIMIT); + L2CA_AdjustConnectionIntervals(&min_interval, &max_interval, BTM_BLE_CONN_INT_MIN_LIMIT); // If the device has no preferred connection timeout, use the default. - if (timeout == BTM_BLE_CONN_PARAM_UNDEF) timeout = BTM_BLE_CONN_TIMEOUT_DEF; - - if (min_interval < BTM_BLE_CONN_INT_MIN || - min_interval > BTM_BLE_CONN_INT_MAX || - max_interval < BTM_BLE_CONN_INT_MIN || - max_interval > BTM_BLE_CONN_INT_MAX || - latency > BTM_BLE_CONN_LATENCY_MAX || - timeout < BTM_BLE_CONN_SUP_TOUT_MIN || + if (timeout == BTM_BLE_CONN_PARAM_UNDEF) { + timeout = BTM_BLE_CONN_TIMEOUT_DEF; + } + + if (min_interval < BTM_BLE_CONN_INT_MIN || min_interval > BTM_BLE_CONN_INT_MAX || + max_interval < BTM_BLE_CONN_INT_MIN || max_interval > BTM_BLE_CONN_INT_MAX || + latency > BTM_BLE_CONN_LATENCY_MAX || timeout < BTM_BLE_CONN_SUP_TOUT_MIN || timeout > BTM_BLE_CONN_SUP_TOUT_MAX || max_interval < min_interval) { - log::error( - "Invalid connection parameters. min={}, max={}, latency={}, timeout={}", - min_interval, max_interval, latency, timeout); + log::error("Invalid connection parameters. min={}, max={}, latency={}, timeout={}", + min_interval, max_interval, latency, timeout); return; } @@ -1419,7 +1391,9 @@ static void read_pref_conn_params_cb(uint16_t conn_id, tGATT_STATUS status, if (interop_match_addr(INTEROP_HID_PREF_CONN_SUP_TIMEOUT_3S, (RawAddress*)&p_dev_cb->link_spec.addrt.bda)) { - if (timeout < 300) timeout = 300; + if (timeout < 300) { + timeout = 300; + } } if (interop_match_addr(INTEROP_HID_PREF_CONN_ZERO_LATENCY, @@ -1427,10 +1401,10 @@ static void read_pref_conn_params_cb(uint16_t conn_id, tGATT_STATUS status, latency = 0; } - BTM_BleSetPrefConnParams(p_dev_cb->link_spec.addrt.bda, min_interval, - max_interval, latency, timeout); - if (!L2CA_UpdateBleConnParams(p_dev_cb->link_spec.addrt.bda, min_interval, - max_interval, latency, timeout, 0, 0)) { + BTM_BleSetPrefConnParams(p_dev_cb->link_spec.addrt.bda, min_interval, max_interval, latency, + timeout); + if (!L2CA_UpdateBleConnParams(p_dev_cb->link_spec.addrt.bda, min_interval, max_interval, latency, + timeout, 0, 0)) { log::warn("Unable to update L2CAP ble connection params peer:{}", p_dev_cb->link_spec.addrt.bda); } @@ -1446,14 +1420,15 @@ static void read_pref_conn_params_cb(uint16_t conn_id, tGATT_STATUS status, * Parameters: * ******************************************************************************/ -static void bta_hh_le_parse_hogp_service(tBTA_HH_DEV_CB* p_dev_cb, - const gatt::Service* service) { +static void bta_hh_le_parse_hogp_service(tBTA_HH_DEV_CB* p_dev_cb, const gatt::Service* service) { tBTA_HH_LE_RPT* p_rpt; bta_hh_le_srvc_init(p_dev_cb, service->handle); for (const gatt::Characteristic& charac : service->characteristics) { - if (!charac.uuid.Is16Bit()) continue; + if (!charac.uuid.Is16Bit()) { + continue; + } uint16_t uuid16 = charac.uuid.As16Bit(); log::info("{} {}", bta_hh_uuid_to_str(uuid16), charac.uuid.ToString()); @@ -1464,32 +1439,31 @@ static void bta_hh_le_parse_hogp_service(tBTA_HH_DEV_CB* p_dev_cb, break; case GATT_UUID_HID_INFORMATION: /* only one instance per HID service */ - BtaGattQueue::ReadCharacteristic(p_dev_cb->conn_id, charac.value_handle, - read_hid_info_cb, p_dev_cb); + BtaGattQueue::ReadCharacteristic(p_dev_cb->conn_id, charac.value_handle, read_hid_info_cb, + p_dev_cb); break; case GATT_UUID_HID_REPORT_MAP: /* only one instance per HID service */ BtaGattQueue::ReadCharacteristic(p_dev_cb->conn_id, charac.value_handle, read_hid_report_map_cb, p_dev_cb); /* descriptor is optional */ - bta_hh_le_read_char_descriptor(p_dev_cb, charac.value_handle, - GATT_UUID_EXT_RPT_REF_DESCR, + bta_hh_le_read_char_descriptor(p_dev_cb, charac.value_handle, GATT_UUID_EXT_RPT_REF_DESCR, read_ext_rpt_ref_desc_cb, p_dev_cb); break; case GATT_UUID_HID_REPORT: - p_rpt = bta_hh_le_find_alloc_report_entry( - p_dev_cb, p_dev_cb->hid_srvc.srvc_inst_id, GATT_UUID_HID_REPORT, - charac.value_handle); + p_rpt = bta_hh_le_find_alloc_report_entry(p_dev_cb, p_dev_cb->hid_srvc.srvc_inst_id, + GATT_UUID_HID_REPORT, charac.value_handle); if (p_rpt == NULL) { log::error("Add report entry failed !!!"); break; } - if (p_rpt->rpt_type != BTA_HH_RPTT_INPUT) break; + if (p_rpt->rpt_type != BTA_HH_RPTT_INPUT) { + break; + } - bta_hh_le_read_char_descriptor(p_dev_cb, charac.value_handle, - GATT_UUID_RPT_REF_DESCR, + bta_hh_le_read_char_descriptor(p_dev_cb, charac.value_handle, GATT_UUID_RPT_REF_DESCR, read_report_ref_desc_cb, p_dev_cb); break; @@ -1498,14 +1472,14 @@ static void bta_hh_le_parse_hogp_service(tBTA_HH_DEV_CB* p_dev_cb, case GATT_UUID_HID_BT_MOUSE_INPUT: case GATT_UUID_HID_BT_KB_INPUT: if (bta_hh_le_find_alloc_report_entry(p_dev_cb, service->handle, uuid16, - charac.value_handle) == NULL) + charac.value_handle) == NULL) { log::error("Add report entry failed !!!"); + } break; default: - log::verbose("not processing {} 0x{:04d}", bta_hh_uuid_to_str(uuid16), - uuid16); + log::verbose("not processing {} 0x{:04d}", bta_hh_uuid_to_str(uuid16), uuid16); } } @@ -1539,7 +1513,9 @@ static void bta_hh_le_srvc_search_cmpl(tBTA_GATTC_SEARCH_CMPL* p_data) { tBTA_HH_DEV_CB* p_dev_cb = bta_hh_le_find_dev_cb_by_conn_id(p_data->conn_id); /* service search exception or no HID service is supported on remote */ - if (p_dev_cb == NULL) return; + if (p_dev_cb == NULL) { + return; + } if (p_data->status != GATT_SUCCESS) { log::error("Service discovery failed {}", p_data->status); @@ -1556,16 +1532,16 @@ static void bta_hh_le_srvc_search_cmpl(tBTA_GATTC_SEARCH_CMPL* p_data) { int num_hid_service = 0; for (const gatt::Service& service : *services) { - if (service.uuid == Uuid::From16Bit(UUID_SERVCLASS_LE_HID) && - service.is_primary && hogp_service == nullptr) { + if (service.uuid == Uuid::From16Bit(UUID_SERVCLASS_LE_HID) && service.is_primary && + hogp_service == nullptr) { // TODO(b/286413526): The current implementation connects to the first HID // service, in the case of multiple HID services being present. As a // temporary mitigation, connect to the third HID service for some // particular devices. The long-term fix should refactor HID stack to // connect to multiple HID services simultaneously. - if (interop_match_vendor_product_ids( - INTEROP_MULTIPLE_HOGP_SERVICE_CHOOSE_THIRD, - p_dev_cb->dscp_info.vendor_id, p_dev_cb->dscp_info.product_id)) { + if (interop_match_vendor_product_ids(INTEROP_MULTIPLE_HOGP_SERVICE_CHOOSE_THIRD, + p_dev_cb->dscp_info.vendor_id, + p_dev_cb->dscp_info.product_id)) { num_hid_service++; if (num_hid_service < HID_PREFERRED_SERVICE_INDEX_3) { continue; @@ -1585,12 +1561,10 @@ static void bta_hh_le_srvc_search_cmpl(tBTA_GATTC_SEARCH_CMPL* p_data) { } if (hogp_service != nullptr) { - log::verbose("have HOGP service inst_id={}", - p_dev_cb->hid_srvc.srvc_inst_id); + log::verbose("have HOGP service inst_id={}", p_dev_cb->hid_srvc.srvc_inst_id); bta_hh_le_parse_hogp_service(p_dev_cb, hogp_service); } else if (headtracker_service != nullptr) { - log::verbose("have Android Headtracker service inst_id={}", - p_dev_cb->hid_srvc.srvc_inst_id); + log::verbose("have Android Headtracker service inst_id={}", p_dev_cb->hid_srvc.srvc_inst_id); bta_hh_headtracker_parse_service(p_dev_cb, headtracker_service); } else { log::error("HID service not found"); @@ -1647,27 +1621,25 @@ static void bta_hh_le_input_rpt_notify(tBTA_GATTC_NOTIFY* p_data) { } const gatt::Characteristic* p_char = - BTA_GATTC_GetCharacteristic(p_dev_cb->conn_id, p_data->handle); + BTA_GATTC_GetCharacteristic(p_dev_cb->conn_id, p_data->handle); if (p_char == NULL) { - log::error("Unknown Characteristic, conn_id:0x{:04x}, handle:0x{:04x}", - p_dev_cb->conn_id, p_data->handle); + log::error("Unknown Characteristic, conn_id:0x{:04x}, handle:0x{:04x}", p_dev_cb->conn_id, + p_data->handle); return; } - const gatt::Service* p_svc = - BTA_GATTC_GetOwningService(p_dev_cb->conn_id, p_char->value_handle); + const gatt::Service* p_svc = BTA_GATTC_GetOwningService(p_dev_cb->conn_id, p_char->value_handle); if (!p_char->uuid.Is16Bit()) { log::error("Unexpected characteristic len: {}", p_char->uuid.ToString()); return; } - p_rpt = bta_hh_le_find_report_entry(p_dev_cb, p_svc->handle, - bta_hh_get_uuid16(p_dev_cb, p_char->uuid), - p_char->value_handle); + p_rpt = bta_hh_le_find_report_entry( + p_dev_cb, p_svc->handle, bta_hh_get_uuid16(p_dev_cb, p_char->uuid), p_char->value_handle); if (p_rpt == NULL) { - log::error("Unknown Report, uuid:{}, handle:0x{:04x}", - p_char->uuid.ToString(), p_char->value_handle); + log::error("Unknown Report, uuid:{}, handle:0x{:04x}", p_char->uuid.ToString(), + p_char->value_handle); return; } @@ -1686,7 +1658,9 @@ static void bta_hh_le_input_rpt_notify(tBTA_GATTC_NOTIFY* p_data) { bta_hh_co_data((uint8_t)p_dev_cb->hid_handle, p_buf, p_data->len); - if (p_buf != p_data->value) osi_free(p_buf); + if (p_buf != p_data->value) { + osi_free(p_buf); + } } /******************************************************************************* @@ -1702,10 +1676,9 @@ void bta_hh_le_open_fail(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* p_data) { const tBTA_HH_LE_CLOSE* le_close = &p_data->le_close; BTM_LogHistory( - kBtmLogTag, p_cb->link_spec.addrt.bda, "Open failed", - base::StringPrintf( - "%s reason %s", bt_transport_text(p_cb->link_spec.transport).c_str(), - gatt_disconnection_reason_text(le_close->reason).c_str())); + kBtmLogTag, p_cb->link_spec.addrt.bda, "Open failed", + base::StringPrintf("%s reason %s", bt_transport_text(p_cb->link_spec.transport).c_str(), + gatt_disconnection_reason_text(le_close->reason).c_str())); log::warn("Open failed for device:{}", p_cb->link_spec.addrt.bda); /* open failure in the middle of service discovery, clear all services */ @@ -1723,14 +1696,13 @@ void bta_hh_le_open_fail(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* p_data) { p_cb->disc_active = BTA_HH_LE_DISC_NONE; /* Failure in opening connection or GATT discovery failure */ tBTA_HH data = { - .conn = - { - .link_spec = p_cb->link_spec, - .status = (le_close->reason != GATT_CONN_OK) ? BTA_HH_ERR - : p_cb->status, - .handle = p_cb->hid_handle, - .scps_supported = p_cb->scps_supported, - }, + .conn = + { + .link_spec = p_cb->link_spec, + .status = (le_close->reason != GATT_CONN_OK) ? BTA_HH_ERR : p_cb->status, + .handle = p_cb->hid_handle, + .scps_supported = p_cb->scps_supported, + }, }; /* Report OPEN fail event */ @@ -1751,10 +1723,9 @@ void bta_hh_gatt_close(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* p_data) { const tBTA_HH_LE_CLOSE* le_close = &p_data->le_close; BTM_LogHistory( - kBtmLogTag, p_cb->link_spec.addrt.bda, "Closed", - base::StringPrintf( - "%s reason %s", bt_transport_text(p_cb->link_spec.transport).c_str(), - gatt_disconnection_reason_text(le_close->reason).c_str())); + kBtmLogTag, p_cb->link_spec.addrt.bda, "Closed", + base::StringPrintf("%s reason %s", bt_transport_text(p_cb->link_spec.transport).c_str(), + gatt_disconnection_reason_text(le_close->reason).c_str())); /* deregister all notification */ bta_hh_le_deregister_input_notif(p_cb); @@ -1763,8 +1734,8 @@ void bta_hh_gatt_close(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* p_data) { bta_hh_cb.cnt_num--; tBTA_HH_CBDATA disc_dat = { - .status = p_cb->status, - .handle = p_cb->hid_handle, + .status = p_cb->status, + .handle = p_cb->hid_handle, }; (*bta_hh_cb.p_cback)(BTA_HH_CLOSE_EVT, (tBTA_HH*)&disc_dat); @@ -1776,9 +1747,8 @@ void bta_hh_gatt_close(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* p_data) { case GATT_CONN_FAILED_ESTABLISHMENT: case GATT_CONN_TERMINATE_PEER_USER: case GATT_CONN_TIMEOUT: - log::debug( - "gd_acl: add into acceptlist for reconnection device:{} reason:{}", - p_cb->link_spec, gatt_disconnection_reason_text(le_close->reason)); + log::debug("gd_acl: add into acceptlist for reconnection device:{} reason:{}", + p_cb->link_spec, gatt_disconnection_reason_text(le_close->reason)); // gd removes from bg list after successful connection // Correct the cached state to allow re-add to acceptlist. bta_hh_le_add_dev_bg_conn(p_cb); @@ -1791,9 +1761,9 @@ void bta_hh_gatt_close(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* p_data) { case GATT_CONN_TERMINATE_LOCAL_HOST: default: log::debug( - "gd_acl: SKIP add into acceptlist for reconnection device:{} " - "reason:{}", - p_cb->link_spec, gatt_disconnection_reason_text(le_close->reason)); + "gd_acl: SKIP add into acceptlist for reconnection device:{} " + "reason:{}", + p_cb->link_spec, gatt_disconnection_reason_text(le_close->reason)); break; } } @@ -1831,18 +1801,15 @@ void bta_hh_le_api_disc_act(tBTA_HH_DEV_CB* p_cb) { * Parameters: * ******************************************************************************/ -static void read_report_cb(uint16_t conn_id, tGATT_STATUS status, - uint16_t handle, uint16_t len, uint8_t* value, - void* data) { +static void read_report_cb(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, uint16_t len, + uint8_t* value, void* data) { tBTA_HH_DEV_CB* p_dev_cb = (tBTA_HH_DEV_CB*)data; if (p_dev_cb->w4_evt != BTA_HH_GET_RPT_EVT) { - log::warn("Unexpected Read response, w4_evt={}", - bta_hh_event_text(p_dev_cb->w4_evt)); + log::warn("Unexpected Read response, w4_evt={}", bta_hh_event_text(p_dev_cb->w4_evt)); return; } - const gatt::Characteristic* p_char = - BTA_GATTC_GetCharacteristic(conn_id, handle); + const gatt::Characteristic* p_char = BTA_GATTC_GetCharacteristic(conn_id, handle); if (p_char == nullptr) { log::error("Unknown handle"); return; @@ -1871,11 +1838,9 @@ static void read_report_cb(uint16_t conn_id, tGATT_STATUS status, hs_data.handle = p_dev_cb->hid_handle; if (status == GATT_SUCCESS) { tBTA_HH_LE_RPT* p_rpt; - const gatt::Service* p_svc = - BTA_GATTC_GetOwningService(conn_id, p_char->value_handle); + const gatt::Service* p_svc = BTA_GATTC_GetOwningService(conn_id, p_char->value_handle); - p_rpt = bta_hh_le_find_report_entry(p_dev_cb, p_svc->handle, char_uuid, - p_char->value_handle); + p_rpt = bta_hh_le_find_report_entry(p_dev_cb, p_svc->handle, char_uuid, p_char->value_handle); if (p_rpt != nullptr && len) { BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + len + 1); /* pack data send to app */ @@ -1908,10 +1873,9 @@ static void read_report_cb(uint16_t conn_id, tGATT_STATUS status, * Returns void * ******************************************************************************/ -static void bta_hh_le_get_rpt(tBTA_HH_DEV_CB* p_cb, tBTA_HH_RPT_TYPE r_type, - uint8_t rpt_id) { - tBTA_HH_LE_RPT* p_rpt = bta_hh_le_find_rpt_by_idtype( - p_cb->hid_srvc.report, p_cb->mode, r_type, rpt_id); +static void bta_hh_le_get_rpt(tBTA_HH_DEV_CB* p_cb, tBTA_HH_RPT_TYPE r_type, uint8_t rpt_id) { + tBTA_HH_LE_RPT* p_rpt = + bta_hh_le_find_rpt_by_idtype(p_cb->hid_srvc.report, p_cb->mode, r_type, rpt_id); if (p_rpt == NULL) { log::error("no matching report"); @@ -1919,24 +1883,25 @@ static void bta_hh_le_get_rpt(tBTA_HH_DEV_CB* p_cb, tBTA_HH_RPT_TYPE r_type, } p_cb->w4_evt = BTA_HH_GET_RPT_EVT; - BtaGattQueue::ReadCharacteristic(p_cb->conn_id, p_rpt->char_inst_id, - read_report_cb, p_cb); + BtaGattQueue::ReadCharacteristic(p_cb->conn_id, p_rpt->char_inst_id, read_report_cb, p_cb); } -static void write_report_cb(uint16_t conn_id, tGATT_STATUS status, - uint16_t handle, uint16_t len, const uint8_t* value, - void* data) { +static void write_report_cb(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, uint16_t len, + const uint8_t* value, void* data) { tBTA_HH_CBDATA cback_data; tBTA_HH_DEV_CB* p_dev_cb = (tBTA_HH_DEV_CB*)data; uint16_t cb_evt = p_dev_cb->w4_evt; - if (cb_evt == BTA_HH_EMPTY_EVT) return; + if (cb_evt == BTA_HH_EMPTY_EVT) { + return; + } log::verbose("w4_evt:{}", bta_hh_event_text(p_dev_cb->w4_evt)); - const gatt::Characteristic* p_char = - BTA_GATTC_GetCharacteristic(conn_id, handle); + const gatt::Characteristic* p_char = BTA_GATTC_GetCharacteristic(conn_id, handle); - if (p_char == nullptr) return; + if (p_char == nullptr) { + return; + } if (!p_char->uuid.Is16Bit()) { log::error("Unexpected characteristic len: {}", p_char->uuid.ToString()); return; @@ -1944,8 +1909,7 @@ static void write_report_cb(uint16_t conn_id, tGATT_STATUS status, uint16_t uuid16 = bta_hh_get_uuid16(p_dev_cb, p_char->uuid); if (uuid16 != GATT_UUID_HID_REPORT && uuid16 != GATT_UUID_HID_BT_KB_INPUT && - uuid16 != GATT_UUID_HID_BT_MOUSE_INPUT && - uuid16 != GATT_UUID_HID_BT_KB_OUTPUT) { + uuid16 != GATT_UUID_HID_BT_MOUSE_INPUT && uuid16 != GATT_UUID_HID_BT_KB_OUTPUT) { return; } @@ -1964,8 +1928,8 @@ static void write_report_cb(uint16_t conn_id, tGATT_STATUS status, * Returns void * ******************************************************************************/ -static void bta_hh_le_write_rpt(tBTA_HH_DEV_CB* p_cb, tBTA_HH_RPT_TYPE r_type, - BT_HDR* p_buf, uint16_t w4_evt) { +static void bta_hh_le_write_rpt(tBTA_HH_DEV_CB* p_cb, tBTA_HH_RPT_TYPE r_type, BT_HDR* p_buf, + uint16_t w4_evt) { tBTA_HH_LE_RPT* p_rpt; uint8_t rpt_id; @@ -1979,8 +1943,7 @@ static void bta_hh_le_write_rpt(tBTA_HH_DEV_CB* p_cb, tBTA_HH_RPT_TYPE r_type, STREAM_TO_UINT8(rpt_id, vec_start); vector value(vec_start, vec_start + p_buf->len - 1); - p_rpt = bta_hh_le_find_rpt_by_idtype(p_cb->hid_srvc.report, p_cb->mode, - r_type, rpt_id); + p_rpt = bta_hh_le_find_rpt_by_idtype(p_cb->hid_srvc.report, p_cb->mode, r_type, rpt_id); if (p_rpt == NULL) { log::error("no matching report"); osi_free(p_buf); @@ -1990,15 +1953,15 @@ static void bta_hh_le_write_rpt(tBTA_HH_DEV_CB* p_cb, tBTA_HH_RPT_TYPE r_type, p_cb->w4_evt = w4_evt; const gatt::Characteristic* p_char = - BTA_GATTC_GetCharacteristic(p_cb->conn_id, p_rpt->char_inst_id); + BTA_GATTC_GetCharacteristic(p_cb->conn_id, p_rpt->char_inst_id); tGATT_WRITE_TYPE write_type = GATT_WRITE; - if (p_char && (p_char->properties & GATT_CHAR_PROP_BIT_WRITE_NR)) + if (p_char && (p_char->properties & GATT_CHAR_PROP_BIT_WRITE_NR)) { write_type = GATT_WRITE_NO_RSP; + } - BtaGattQueue::WriteCharacteristic(p_cb->conn_id, p_rpt->char_inst_id, - std::move(value), write_type, - write_report_cb, p_cb); + BtaGattQueue::WriteCharacteristic(p_cb->conn_id, p_rpt->char_inst_id, std::move(value), + write_type, write_report_cb, p_cb); } /******************************************************************************* @@ -2010,8 +1973,7 @@ static void bta_hh_le_write_rpt(tBTA_HH_DEV_CB* p_cb, tBTA_HH_RPT_TYPE r_type, * Returns void * ******************************************************************************/ -static void bta_hh_le_suspend(tBTA_HH_DEV_CB* p_cb, - tBTA_HH_TRANS_CTRL_TYPE ctrl_type) { +static void bta_hh_le_suspend(tBTA_HH_DEV_CB* p_cb, tBTA_HH_TRANS_CTRL_TYPE ctrl_type) { if (bta_hh_headtracker_supported(p_cb)) { log::warn("Suspend not applicable for headtracker service"); return; @@ -2020,9 +1982,8 @@ static void bta_hh_le_suspend(tBTA_HH_DEV_CB* p_cb, ctrl_type -= BTA_HH_CTRL_SUSPEND; // We don't care about response - BtaGattQueue::WriteCharacteristic( - p_cb->conn_id, p_cb->hid_srvc.control_point_handle, {(uint8_t)ctrl_type}, - GATT_WRITE_NO_RSP, NULL, NULL); + BtaGattQueue::WriteCharacteristic(p_cb->conn_id, p_cb->hid_srvc.control_point_handle, + {(uint8_t)ctrl_type}, GATT_WRITE_NO_RSP, NULL, NULL); } /******************************************************************************* @@ -2046,19 +2007,18 @@ void bta_hh_le_write_dev_act(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* p_data) { break; case HID_TRANS_GET_REPORT: - bta_hh_le_get_rpt(p_cb, p_data->api_sndcmd.param, - p_data->api_sndcmd.rpt_id); + bta_hh_le_get_rpt(p_cb, p_data->api_sndcmd.param, p_data->api_sndcmd.rpt_id); break; case HID_TRANS_SET_REPORT: - bta_hh_le_write_rpt(p_cb, p_data->api_sndcmd.param, - p_data->api_sndcmd.p_data, BTA_HH_SET_RPT_EVT); + bta_hh_le_write_rpt(p_cb, p_data->api_sndcmd.param, p_data->api_sndcmd.p_data, + BTA_HH_SET_RPT_EVT); break; case HID_TRANS_DATA: /* output report */ - bta_hh_le_write_rpt(p_cb, p_data->api_sndcmd.param, - p_data->api_sndcmd.p_data, BTA_HH_DATA_EVT); + bta_hh_le_write_rpt(p_cb, p_data->api_sndcmd.param, p_data->api_sndcmd.p_data, + BTA_HH_DATA_EVT); break; case HID_TRANS_CONTROL: @@ -2071,8 +2031,7 @@ void bta_hh_le_write_dev_act(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* p_data) { break; default: - log::error("unsupported transaction for BLE HID device:{}", - p_data->api_sndcmd.t_type); + log::error("unsupported transaction for BLE HID device:{}", p_data->api_sndcmd.t_type); break; } } @@ -2111,8 +2070,8 @@ void bta_hh_le_get_dscp_act(tBTA_HH_DEV_CB* p_cb) { ******************************************************************************/ static void bta_hh_le_add_dev_bg_conn(tBTA_HH_DEV_CB* p_cb) { /* Add device into BG connection to accept remote initiated connection */ - BTA_GATTC_Open(bta_hh_cb.gatt_if, p_cb->link_spec.addrt.bda, - BTM_BLE_BKG_CONNECT_ALLOW_LIST, false); + BTA_GATTC_Open(bta_hh_cb.gatt_if, p_cb->link_spec.addrt.bda, BTM_BLE_BKG_CONNECT_ALLOW_LIST, + false); p_cb->in_bg_conn = true; } @@ -2127,24 +2086,23 @@ static void bta_hh_le_add_dev_bg_conn(tBTA_HH_DEV_CB* p_cb) { * Returns void * ******************************************************************************/ -uint8_t bta_hh_le_add_device(tBTA_HH_DEV_CB* p_cb, - const tBTA_HH_MAINT_DEV* p_dev_info) { +uint8_t bta_hh_le_add_device(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_MAINT_DEV* p_dev_info) { p_cb->hid_handle = bta_hh_le_get_le_dev_hdl(p_cb->index); - if (p_cb->hid_handle == BTA_HH_INVALID_HANDLE) return BTA_HH_INVALID_HANDLE; + if (p_cb->hid_handle == BTA_HH_INVALID_HANDLE) { + return BTA_HH_INVALID_HANDLE; + } bta_hh_cb.le_cb_index[BTA_HH_GET_LE_CB_IDX(p_cb->hid_handle)] = p_cb->index; /* update DI information */ - bta_hh_update_di_info( - p_cb, p_dev_info->dscp_info.vendor_id, p_dev_info->dscp_info.product_id, - p_dev_info->dscp_info.version, p_dev_info->dscp_info.flag, - p_dev_info->dscp_info.ctry_code); + bta_hh_update_di_info(p_cb, p_dev_info->dscp_info.vendor_id, p_dev_info->dscp_info.product_id, + p_dev_info->dscp_info.version, p_dev_info->dscp_info.flag, + p_dev_info->dscp_info.ctry_code); /* add to BTA device list */ - bta_hh_add_device_to_list( - p_cb, p_cb->hid_handle, p_dev_info->attr_mask, - &p_dev_info->dscp_info.descriptor, p_dev_info->sub_class, - p_dev_info->dscp_info.ssr_max_latency, p_dev_info->dscp_info.ssr_min_tout, - p_dev_info->app_id); + bta_hh_add_device_to_list(p_cb, p_cb->hid_handle, p_dev_info->attr_mask, + &p_dev_info->dscp_info.descriptor, p_dev_info->sub_class, + p_dev_info->dscp_info.ssr_max_latency, + p_dev_info->dscp_info.ssr_min_tout, p_dev_info->app_id); bta_hh_le_add_dev_bg_conn(p_cb); @@ -2163,12 +2121,10 @@ uint8_t bta_hh_le_add_device(tBTA_HH_DEV_CB* p_cb, ******************************************************************************/ void bta_hh_le_remove_dev_bg_conn(tBTA_HH_DEV_CB* p_dev_cb) { if (p_dev_cb->in_bg_conn) { - log::debug("Removing from background connection device:{}", - p_dev_cb->link_spec); + log::debug("Removing from background connection device:{}", p_dev_cb->link_spec); p_dev_cb->in_bg_conn = false; - BTA_GATTC_CancelOpen(bta_hh_cb.gatt_if, p_dev_cb->link_spec.addrt.bda, - false); + BTA_GATTC_CancelOpen(bta_hh_cb.gatt_if, p_dev_cb->link_spec.addrt.bda, false); } /* deregister all notifications */ @@ -2193,16 +2149,16 @@ static void bta_hh_le_service_changed(tAclLinkSpec link_spec) { /* Pretend that the HOGP device disconnected so that higher layers don't try to communicate with it while the GATT database is rediscovered. */ const tBTA_HH_DATA data = { - .le_close = - { - .hdr = + .le_close = { - .event = BTA_HH_GATT_CLOSE_EVT, - .layer_specific = static_cast(p_cb->hid_handle), + .hdr = + { + .event = BTA_HH_GATT_CLOSE_EVT, + .layer_specific = static_cast(p_cb->hid_handle), + }, + .conn_id = p_cb->conn_id, + .reason = GATT_CONN_OK, }, - .conn_id = p_cb->conn_id, - .reason = GATT_CONN_OK, - }, }; bta_hh_sm_execute(p_cb, BTA_HH_GATT_CLOSE_EVT, &data); } @@ -2219,12 +2175,12 @@ static void bta_hh_le_service_discovery_done(tAclLinkSpec link_spec) { Pretend to have connected with a new HOGP device. */ p_cb->hid_srvc.state = BTA_HH_SERVICE_UNKNOWN; const tBTA_GATTC_OPEN open = { - .status = GATT_SUCCESS, - .conn_id = p_cb->conn_id, - .client_if = bta_hh_cb.gatt_if, - .remote_bda = link_spec.addrt.bda, - .transport = BT_TRANSPORT_LE, - .mtu = 0, + .status = GATT_SUCCESS, + .conn_id = p_cb->conn_id, + .client_if = bta_hh_cb.gatt_if, + .remote_bda = link_spec.addrt.bda, + .transport = BT_TRANSPORT_LE, + .mtu = 0, }; bta_hh_sm_execute(p_cb, BTA_HH_GATT_OPEN_EVT, (tBTA_HH_DATA*)&open); } else { @@ -2248,12 +2204,13 @@ static void bta_hh_gattc_callback(tBTA_GATTC_EVT event, tBTA_GATTC* p_data) { link_spec.transport = BT_TRANSPORT_LE; log::verbose("event:{}", gatt_client_event_text(event)); - if (p_data == NULL) return; + if (p_data == NULL) { + return; + } switch (event) { case BTA_GATTC_DEREG_EVT: /* 1 */ - bta_hh_cleanup_disable( - static_cast(p_data->reg_oper.status)); + bta_hh_cleanup_disable(static_cast(p_data->reg_oper.status)); break; case BTA_GATTC_OPEN_EVT: /* 2 */ @@ -2261,8 +2218,7 @@ static void bta_hh_gattc_callback(tBTA_GATTC_EVT event, tBTA_GATTC* p_data) { link_spec.transport = p_data->open.transport; p_dev_cb = bta_hh_le_find_dev_cb_by_bda(link_spec); if (p_dev_cb) { - bta_hh_sm_execute(p_dev_cb, BTA_HH_GATT_OPEN_EVT, - (tBTA_HH_DATA*)&p_data->open); + bta_hh_sm_execute(p_dev_cb, BTA_HH_GATT_OPEN_EVT, (tBTA_HH_DATA*)&p_data->open); } break; @@ -2292,8 +2248,7 @@ static void bta_hh_gattc_callback(tBTA_GATTC_EVT event, tBTA_GATTC* p_data) { link_spec.addrt.bda = p_data->enc_cmpl.remote_bda; p_dev_cb = bta_hh_le_find_dev_cb_by_bda(link_spec); if (p_dev_cb) { - bta_hh_sm_execute(p_dev_cb, BTA_HH_GATT_ENC_CMPL_EVT, - (tBTA_HH_DATA*)&p_data->enc_cmpl); + bta_hh_sm_execute(p_dev_cb, BTA_HH_GATT_ENC_CMPL_EVT, (tBTA_HH_DATA*)&p_data->enc_cmpl); } break; @@ -2311,8 +2266,7 @@ static void bta_hh_gattc_callback(tBTA_GATTC_EVT event, tBTA_GATTC* p_data) { * Parameters: * ******************************************************************************/ -static void bta_hh_process_cache_rpt(tBTA_HH_DEV_CB* p_cb, - tBTA_HH_RPT_CACHE_ENTRY* p_rpt_cache, +static void bta_hh_process_cache_rpt(tBTA_HH_DEV_CB* p_cb, tBTA_HH_RPT_CACHE_ENTRY* p_rpt_cache, uint8_t num_rpt) { uint8_t i = 0; tBTA_HH_LE_RPT* p_rpt; @@ -2326,9 +2280,9 @@ static void bta_hh_process_cache_rpt(tBTA_HH_DEV_CB* p_cb, p_cb->hid_srvc.descriptor.dsc_list = p_cb->dscp_info.descriptor.dsc_list; for (; i < num_rpt; i++, p_rpt_cache++) { - if ((p_rpt = bta_hh_le_find_alloc_report_entry( - p_cb, p_rpt_cache->srvc_inst_id, p_rpt_cache->rpt_uuid, - p_rpt_cache->char_inst_id)) == NULL) { + if ((p_rpt = bta_hh_le_find_alloc_report_entry(p_cb, p_rpt_cache->srvc_inst_id, + p_rpt_cache->rpt_uuid, + p_rpt_cache->char_inst_id)) == NULL) { log::error("allocation report entry failure"); break; } else { @@ -2337,8 +2291,7 @@ static void bta_hh_process_cache_rpt(tBTA_HH_DEV_CB* p_cb, if (p_rpt->uuid == GATT_UUID_HID_BT_KB_INPUT || p_rpt->uuid == GATT_UUID_HID_BT_MOUSE_INPUT || - (p_rpt->uuid == GATT_UUID_HID_REPORT && - p_rpt->rpt_type == BTA_HH_RPTT_INPUT)) { + (p_rpt->uuid == GATT_UUID_HID_REPORT && p_rpt->rpt_type == BTA_HH_RPTT_INPUT)) { p_rpt->client_cfg_value = GATT_CLT_CONFIG_NOTIFICATION; } } @@ -2346,9 +2299,8 @@ static void bta_hh_process_cache_rpt(tBTA_HH_DEV_CB* p_cb, } } -static bool bta_hh_le_iso_data_callback(const RawAddress& addr, - uint16_t cis_conn_hdl, uint8_t* data, - uint16_t size, uint32_t timestamp) { +static bool bta_hh_le_iso_data_callback(const RawAddress& addr, uint16_t cis_conn_hdl, + uint8_t* data, uint16_t size, uint32_t timestamp) { if (!com::android::bluetooth::flags::leaudio_dynamic_spatial_audio()) { log::warn("DSA not supported"); return false; diff --git a/system/bta/hh/bta_hh_main.cc b/system/bta/hh/bta_hh_main.cc index f734aa62682..0b14004c654 100644 --- a/system/bta/hh/bta_hh_main.cc +++ b/system/bta/hh/bta_hh_main.cc @@ -191,8 +191,7 @@ static void bta_hh_better_state_machine(tBTA_HH_DEV_CB* p_cb, uint16_t event, * Returns void * ******************************************************************************/ -void bta_hh_sm_execute(tBTA_HH_DEV_CB* p_cb, uint16_t event, - const tBTA_HH_DATA* p_data) { +void bta_hh_sm_execute(tBTA_HH_DEV_CB* p_cb, uint16_t event, const tBTA_HH_DATA* p_data) { tBTA_HH cback_data; tBTA_HH_EVT cback_event = 0; tBTA_HH_STATE in_state; @@ -225,59 +224,57 @@ void bta_hh_sm_execute(tBTA_HH_DEV_CB* p_cb, uint16_t event, cback_data.dev_info.handle = BTA_HH_INVALID_HANDLE; } else { cback_data.dev_info.status = BTA_HH_ERR_HDL; - cback_data.dev_info.handle = - (uint8_t)p_data->api_maintdev.hdr.layer_specific; + cback_data.dev_info.handle = (uint8_t)p_data->api_maintdev.hdr.layer_specific; } break; case BTA_HH_API_WRITE_DEV_EVT: - cback_event = (p_data->api_sndcmd.t_type - HID_TRANS_GET_REPORT) + - BTA_HH_GET_RPT_EVT; + cback_event = (p_data->api_sndcmd.t_type - HID_TRANS_GET_REPORT) + BTA_HH_GET_RPT_EVT; osi_free_and_reset((void**)&p_data->api_sndcmd.p_data); if (p_data->api_sndcmd.t_type == HID_TRANS_SET_PROTOCOL || p_data->api_sndcmd.t_type == HID_TRANS_SET_REPORT || p_data->api_sndcmd.t_type == HID_TRANS_SET_IDLE) { cback_data.dev_status.status = BTA_HH_ERR_HDL; - cback_data.dev_status.handle = - (uint8_t)p_data->api_sndcmd.hdr.layer_specific; + cback_data.dev_status.handle = (uint8_t)p_data->api_sndcmd.hdr.layer_specific; } else if (p_data->api_sndcmd.t_type != HID_TRANS_DATA && p_data->api_sndcmd.t_type != HID_TRANS_CONTROL) { - cback_data.hs_data.handle = - (uint8_t)p_data->api_sndcmd.hdr.layer_specific; + cback_data.hs_data.handle = (uint8_t)p_data->api_sndcmd.hdr.layer_specific; cback_data.hs_data.status = BTA_HH_ERR_HDL; /* hs_data.rsp_data will be all zero, which is not valid value */ } else if (p_data->api_sndcmd.t_type == HID_TRANS_CONTROL && - p_data->api_sndcmd.param == - BTA_HH_CTRL_VIRTUAL_CABLE_UNPLUG) { + p_data->api_sndcmd.param == BTA_HH_CTRL_VIRTUAL_CABLE_UNPLUG) { cback_data.status = BTA_HH_ERR_HDL; cback_event = BTA_HH_VC_UNPLUG_EVT; - } else + } else { cback_event = 0; + } break; case BTA_HH_API_CLOSE_EVT: cback_event = BTA_HH_CLOSE_EVT; cback_data.dev_status.status = BTA_HH_ERR_HDL; - cback_data.dev_status.handle = - (uint8_t)p_data->api_sndcmd.hdr.layer_specific; + cback_data.dev_status.handle = (uint8_t)p_data->api_sndcmd.hdr.layer_specific; break; default: /* invalid handle, call bad API event */ log::error("wrong device handle:{}", p_data->hdr.layer_specific); /* Free the callback buffer now */ - if (p_data != NULL) + if (p_data != NULL) { osi_free_and_reset((void**)&p_data->hid_cback.p_data); + } break; } - if (cback_event) (*bta_hh_cb.p_cback)(cback_event, &cback_data); + if (cback_event) { + (*bta_hh_cb.p_cback)(cback_event, &cback_data); + } } } /* corresponding CB is found, go to state machine */ else { in_state = p_cb->state; - log::verbose("State 0x{:02x} [{}], Event [{}]", in_state, - bta_hh_state_code(in_state), bta_hh_evt_code(debug_event)); + log::verbose("State 0x{:02x} [{}], Event [{}]", in_state, bta_hh_state_code(in_state), + bta_hh_evt_code(debug_event)); if ((p_cb->state == BTA_HH_NULL_ST) || (p_cb->state >= BTA_HH_INVALID_ST)) { log::error("Invalid state State=0x{:x}, Event={}", p_cb->state, event); @@ -287,9 +284,8 @@ void bta_hh_sm_execute(tBTA_HH_DEV_CB* p_cb, uint16_t event, bta_hh_better_state_machine(p_cb, event, p_data); if (in_state != p_cb->state) { - log::debug("HHID State Change: [{}] -> [{}] after Event [{}]", - bta_hh_state_code(in_state), bta_hh_state_code(p_cb->state), - bta_hh_evt_code(debug_event)); + log::debug("HHID State Change: [{}] -> [{}] after Event [{}]", bta_hh_state_code(in_state), + bta_hh_state_code(p_cb->state), bta_hh_evt_code(debug_event)); } } } @@ -338,12 +334,14 @@ bool bta_hh_hdl_event(const BT_HDR_RIGID* p_msg) { index = bta_hh_dev_handle_to_cb_idx((uint8_t)p_msg->layer_specific); } - if (index != BTA_HH_IDX_INVALID) p_cb = &bta_hh_cb.kdev[index]; + if (index != BTA_HH_IDX_INVALID) { + p_cb = &bta_hh_cb.kdev[index]; + } log::verbose("handle={} dev_cb[{}]", p_msg->layer_specific, index); bta_hh_sm_execute(p_cb, p_msg->event, (tBTA_HH_DATA*)p_msg); - return (true); + return true; } /***************************************************************************** diff --git a/system/bta/hh/bta_hh_utils.cc b/system/bta/hh/bta_hh_utils.cc index 79d5ff9596b..2191f0c0565 100644 --- a/system/bta/hh/bta_hh_utils.cc +++ b/system/bta/hh/bta_hh_utils.cc @@ -66,19 +66,16 @@ uint8_t bta_hh_find_cb(const tAclLinkSpec& link_spec) { /* See how many active devices there are. */ for (xx = 0; xx < BTA_HH_MAX_DEVICE; xx++) { /* check if any active/known devices is a match */ - if ((link_spec == bta_hh_cb.kdev[xx].link_spec && - !link_spec.addrt.bda.IsEmpty())) { + if (link_spec == bta_hh_cb.kdev[xx].link_spec && !link_spec.addrt.bda.IsEmpty()) { #if (BTA_HH_DEBUG == TRUE) - log::verbose("found kdev_cb[{}] hid_handle={}", xx, - bta_hh_cb.kdev[xx].hid_handle); + log::verbose("found kdev_cb[{}] hid_handle={}", xx, bta_hh_cb.kdev[xx].hid_handle); #endif return xx; } #if (BTA_HH_DEBUG == TRUE) else - log::verbose("in_use ? [{}] kdev[{}].hid_handle={} state=[{}]", - bta_hh_cb.kdev[xx].in_use, xx, bta_hh_cb.kdev[xx].hid_handle, - bta_hh_cb.kdev[xx].state); + log::verbose("in_use ? [{}] kdev[{}].hid_handle={} state=[{}]", bta_hh_cb.kdev[xx].in_use, xx, + bta_hh_cb.kdev[xx].hid_handle, bta_hh_cb.kdev[xx].state); #endif } @@ -94,7 +91,9 @@ uint8_t bta_hh_find_cb(const tAclLinkSpec& link_spec) { log::verbose("index={} while max={}", xx, BTA_HH_MAX_DEVICE); #endif - if (xx == BTA_HH_MAX_DEVICE) xx = BTA_HH_IDX_INVALID; + if (xx == BTA_HH_MAX_DEVICE) { + xx = BTA_HH_IDX_INVALID; + } return xx; } @@ -156,12 +155,11 @@ void bta_hh_clean_up_kdev(tBTA_HH_DEV_CB* p_cb) { * Returns void * ******************************************************************************/ -void bta_hh_update_di_info(tBTA_HH_DEV_CB* p_cb, uint16_t vendor_id, - uint16_t product_id, uint16_t version, uint8_t flag, - uint8_t ctry_code) { +void bta_hh_update_di_info(tBTA_HH_DEV_CB* p_cb, uint16_t vendor_id, uint16_t product_id, + uint16_t version, uint8_t flag, uint8_t ctry_code) { #if (BTA_HH_DEBUG == TRUE) - log::verbose("vendor_id=0x{:2x} product_id=0x{:2x} version=0x{:2x}", - vendor_id, product_id, version); + log::verbose("vendor_id=0x{:2x} product_id=0x{:2x} version=0x{:2x}", vendor_id, product_id, + version); #endif p_cb->dscp_info.vendor_id = vendor_id; p_cb->dscp_info.product_id = product_id; @@ -178,11 +176,9 @@ void bta_hh_update_di_info(tBTA_HH_DEV_CB* p_cb, uint16_t vendor_id, * Returns void * ******************************************************************************/ -void bta_hh_add_device_to_list(tBTA_HH_DEV_CB* p_cb, uint8_t handle, - uint16_t attr_mask, - const tHID_DEV_DSCP_INFO* p_dscp_info, - uint8_t sub_class, uint16_t ssr_max_latency, - uint16_t ssr_min_tout, uint8_t app_id) { +void bta_hh_add_device_to_list(tBTA_HH_DEV_CB* p_cb, uint8_t handle, uint16_t attr_mask, + const tHID_DEV_DSCP_INFO* p_dscp_info, uint8_t sub_class, + uint16_t ssr_max_latency, uint16_t ssr_min_tout, uint8_t app_id) { #if (BTA_HH_DEBUG == TRUE) log::verbose("subclass=0x{:2x}", sub_class); #endif @@ -202,11 +198,9 @@ void bta_hh_add_device_to_list(tBTA_HH_DEV_CB* p_cb, uint8_t handle, osi_free_and_reset((void**)&p_cb->dscp_info.descriptor.dsc_list); if (p_dscp_info->dl_len) { - p_cb->dscp_info.descriptor.dsc_list = - (uint8_t*)osi_malloc(p_dscp_info->dl_len); + p_cb->dscp_info.descriptor.dsc_list = (uint8_t*)osi_malloc(p_dscp_info->dl_len); p_cb->dscp_info.descriptor.dl_len = p_dscp_info->dl_len; - memcpy(p_cb->dscp_info.descriptor.dsc_list, p_dscp_info->dsc_list, - p_dscp_info->dl_len); + memcpy(p_cb->dscp_info.descriptor.dsc_list, p_dscp_info->dsc_list, p_dscp_info->dl_len); } } } @@ -239,7 +233,6 @@ bool bta_hh_tod_spt(tBTA_HH_DEV_CB* p_cb, uint8_t sub_class) { return false; } - /******************************************************************************* * * Function bta_hh_read_ssr_param @@ -249,8 +242,7 @@ bool bta_hh_tod_spt(tBTA_HH_DEV_CB* p_cb, uint8_t sub_class) { * Returns tBTA_HH_STATUS operation status * ******************************************************************************/ -tBTA_HH_STATUS bta_hh_read_ssr_param(const tAclLinkSpec& link_spec, - uint16_t* p_max_ssr_lat, +tBTA_HH_STATUS bta_hh_read_ssr_param(const tAclLinkSpec& link_spec, uint16_t* p_max_ssr_lat, uint16_t* p_min_ssr_tout) { tBTA_HH_DEV_CB* p_cb = bta_hh_get_cb(link_spec); if (p_cb == nullptr) { @@ -265,9 +257,8 @@ tBTA_HH_STATUS bta_hh_read_ssr_param(const tAclLinkSpec& link_spec, uint16_t ssr_max_latency; if (get_btm_client_interface().link_controller.BTM_GetLinkSuperTout( - p_cb->link_spec.addrt.bda, &ssr_max_latency) != BTM_SUCCESS) { - log::warn("Unable to get supervision timeout for peer:{}", - p_cb->link_spec); + p_cb->link_spec.addrt.bda, &ssr_max_latency) != BTM_SUCCESS) { + log::warn("Unable to get supervision timeout for peer:{}", p_cb->link_spec); return BTA_HH_ERR; } ssr_max_latency = BTA_HH_GET_DEF_SSR_MAX_LAT(ssr_max_latency); @@ -275,13 +266,13 @@ tBTA_HH_STATUS bta_hh_read_ssr_param(const tAclLinkSpec& link_spec, /* per 1.1 spec, if the newly calculated max latency is greater than BTA_HH_SSR_MAX_LATENCY_DEF which is 500ms, use BTA_HH_SSR_MAX_LATENCY_DEF */ - if (ssr_max_latency > BTA_HH_SSR_MAX_LATENCY_DEF) + if (ssr_max_latency > BTA_HH_SSR_MAX_LATENCY_DEF) { ssr_max_latency = BTA_HH_SSR_MAX_LATENCY_DEF; + } char remote_name[BD_NAME_LEN] = ""; if (btif_storage_get_stored_remote_name(link_spec.addrt.bda, remote_name)) { - if (interop_match_name(INTEROP_HID_HOST_LIMIT_SNIFF_INTERVAL, - remote_name)) { + if (interop_match_name(INTEROP_HID_HOST_LIMIT_SNIFF_INTERVAL, remote_name)) { if (ssr_max_latency > kSsrMaxLatency /* slots * 0.625ms */) { ssr_max_latency = kSsrMaxLatency; } @@ -289,13 +280,15 @@ tBTA_HH_STATUS bta_hh_read_ssr_param(const tAclLinkSpec& link_spec, } *p_max_ssr_lat = ssr_max_latency; - } else + } else { *p_max_ssr_lat = p_cb->dscp_info.ssr_max_latency; + } - if (p_cb->dscp_info.ssr_min_tout == HID_SSR_PARAM_INVALID) + if (p_cb->dscp_info.ssr_min_tout == HID_SSR_PARAM_INVALID) { *p_min_ssr_tout = BTA_HH_SSR_MIN_TOUT_DEF; - else + } else { *p_min_ssr_tout = p_cb->dscp_info.ssr_min_tout; + } return BTA_HH_OK; } @@ -315,14 +308,12 @@ void bta_hh_cleanup_disable(tBTA_HH_STATUS status) { uint8_t xx; /* free buffer in CB holding report descriptors */ for (xx = 0; xx < BTA_HH_MAX_DEVICE; xx++) { - osi_free_and_reset( - (void**)&bta_hh_cb.kdev[xx].dscp_info.descriptor.dsc_list); + osi_free_and_reset((void**)&bta_hh_cb.kdev[xx].dscp_info.descriptor.dsc_list); } if (bta_hh_cb.p_disc_db) { /* Cancel SDP if it had been started. */ - (void)get_legacy_stack_sdp_api()->service.SDP_CancelServiceSearch( - bta_hh_cb.p_disc_db); + (void)get_legacy_stack_sdp_api()->service.SDP_CancelServiceSearch(bta_hh_cb.p_disc_db); osi_free_and_reset((void**)&bta_hh_cb.p_disc_db); } @@ -350,15 +341,17 @@ uint8_t bta_hh_dev_handle_to_cb_idx(uint8_t dev_handle) { uint8_t index = BTA_HH_IDX_INVALID; if (BTA_HH_IS_LE_DEV_HDL(dev_handle)) { - if (BTA_HH_IS_LE_DEV_HDL_VALID(dev_handle)) + if (BTA_HH_IS_LE_DEV_HDL_VALID(dev_handle)) { index = bta_hh_cb.le_cb_index[BTA_HH_GET_LE_CB_IDX(dev_handle)]; + } #if (BTA_HH_DEBUG == TRUE) log::verbose("dev_handle={} index={}", dev_handle, index); #endif } else - /* regular HID device checking */ - if (dev_handle < BTA_HH_MAX_KNOWN) - index = bta_hh_cb.cb_index[dev_handle]; + /* regular HID device checking */ + if (dev_handle < BTA_HH_MAX_KNOWN) { + index = bta_hh_cb.cb_index[dev_handle]; + } return index; } @@ -378,13 +371,12 @@ void bta_hh_trace_dev_db(void) { log::verbose("bta_hh_trace_dev_db:: Device DB list********************"); for (xx = 0; xx < BTA_HH_MAX_DEVICE; xx++) { - log::verbose("kdev[{}] in_use[{}] handle[{}]", xx, - bta_hh_cb.kdev[xx].in_use, bta_hh_cb.kdev[xx].hid_handle); + log::verbose("kdev[{}] in_use[{}] handle[{}]", xx, bta_hh_cb.kdev[xx].in_use, + bta_hh_cb.kdev[xx].hid_handle); - log::verbose( - "\t\t\t attr_mask[{:04x}] state [{}] sub_class[{:02x}] index = {}", - bta_hh_cb.kdev[xx].attr_mask, bta_hh_cb.kdev[xx].state, - bta_hh_cb.kdev[xx].sub_class, bta_hh_cb.kdev[xx].index); + log::verbose("\t\t\t attr_mask[{:04x}] state [{}] sub_class[{:02x}] index = {}", + bta_hh_cb.kdev[xx].attr_mask, bta_hh_cb.kdev[xx].state, + bta_hh_cb.kdev[xx].sub_class, bta_hh_cb.kdev[xx].index); } log::verbose("*********************************************************"); } diff --git a/system/bta/include/bta_ag_api.h b/system/bta/include/bta_ag_api.h index 429003829c9..36b77d76d3f 100644 --- a/system/bta/include/bta_ag_api.h +++ b/system/bta/include/bta_ag_api.h @@ -66,7 +66,7 @@ #define HFP_1_6_FEAT_MASK 0x000003FF /* HFP 1.7+ */ -#define BTA_AG_FEAT_HF_IND 0x00000400 /* HF Indicators */ +#define BTA_AG_FEAT_HF_IND 0x00000400 /* HF Indicators */ #define BTA_AG_FEAT_ESCO_S4 0x00000800 /* eSCO S4 setting supported */ /* Proprietary features: using 31 ~ 16 bits */ @@ -111,18 +111,18 @@ typedef uint8_t tBTA_AG_STATUS; typedef enum : uint8_t { /* AG result codes used with BTA_AgResult */ - BTA_AG_SPK_RES = 0, /* Update speaker volume */ - BTA_AG_MIC_RES = 1, /* Update microphone volume */ - BTA_AG_INBAND_RING_RES = 2, /* Update inband ring state */ - BTA_AG_CIND_RES = 3, /* Send indicator response for AT+CIND */ - BTA_AG_BINP_RES = 4, /* Send phone number for voice tag for AT+BINP */ - BTA_AG_IND_RES = 5, /* Update an indicator value */ - BTA_AG_BVRA_RES = 6, /* Update voice recognition state */ - BTA_AG_CNUM_RES = 7, /* Send subscriber number response for AT+CNUM */ - BTA_AG_BTRH_RES = 8, /* Send CCAP incoming call hold */ - BTA_AG_CLCC_RES = 9, /* Query list of calls */ - BTA_AG_COPS_RES = 10, /* Read network operator */ - BTA_AG_IN_CALL_RES = 11, /* Indicate incoming phone call */ + BTA_AG_SPK_RES = 0, /* Update speaker volume */ + BTA_AG_MIC_RES = 1, /* Update microphone volume */ + BTA_AG_INBAND_RING_RES = 2, /* Update inband ring state */ + BTA_AG_CIND_RES = 3, /* Send indicator response for AT+CIND */ + BTA_AG_BINP_RES = 4, /* Send phone number for voice tag for AT+BINP */ + BTA_AG_IND_RES = 5, /* Update an indicator value */ + BTA_AG_BVRA_RES = 6, /* Update voice recognition state */ + BTA_AG_CNUM_RES = 7, /* Send subscriber number response for AT+CNUM */ + BTA_AG_BTRH_RES = 8, /* Send CCAP incoming call hold */ + BTA_AG_CLCC_RES = 9, /* Query list of calls */ + BTA_AG_COPS_RES = 10, /* Read network operator */ + BTA_AG_IN_CALL_RES = 11, /* Indicate incoming phone call */ BTA_AG_IN_CALL_CONN_RES = 12, /* Incoming phone call connected */ BTA_AG_CALL_WAIT_RES = 13, /* Call waiting notification */ BTA_AG_OUT_CALL_ORIG_RES = 14, /* Outgoing phone call origination */ @@ -175,15 +175,15 @@ inline std::string bta_ag_result_text(const tBTA_AG_RES& result) { } /* HFP peer features */ -#define BTA_AG_PEER_FEAT_ECNR 0x0001 /* Echo cancellation/noise reduction */ -#define BTA_AG_PEER_FEAT_3WAY 0x0002 /* Call waiting and three-way calling */ -#define BTA_AG_PEER_FEAT_CLI 0x0004 /* Caller ID presentation capability */ -#define BTA_AG_PEER_FEAT_VREC 0x0008 /* Voice recognition activation */ -#define BTA_AG_PEER_FEAT_VOL 0x0010 /* Remote volume control */ -#define BTA_AG_PEER_FEAT_ECS 0x0020 /* Enhanced Call Status */ -#define BTA_AG_PEER_FEAT_ECC 0x0040 /* Enhanced Call Control */ -#define BTA_AG_PEER_FEAT_CODEC 0x0080 /* Codec Negotiation */ -#define BTA_AG_PEER_FEAT_HF_IND 0x0100 /* HF Indicators */ +#define BTA_AG_PEER_FEAT_ECNR 0x0001 /* Echo cancellation/noise reduction */ +#define BTA_AG_PEER_FEAT_3WAY 0x0002 /* Call waiting and three-way calling */ +#define BTA_AG_PEER_FEAT_CLI 0x0004 /* Caller ID presentation capability */ +#define BTA_AG_PEER_FEAT_VREC 0x0008 /* Voice recognition activation */ +#define BTA_AG_PEER_FEAT_VOL 0x0010 /* Remote volume control */ +#define BTA_AG_PEER_FEAT_ECS 0x0020 /* Enhanced Call Status */ +#define BTA_AG_PEER_FEAT_ECC 0x0040 /* Enhanced Call Control */ +#define BTA_AG_PEER_FEAT_CODEC 0x0080 /* Codec Negotiation */ +#define BTA_AG_PEER_FEAT_HF_IND 0x0100 /* HF Indicators */ #define BTA_AG_PEER_FEAT_ESCO_S4 0x0200 /* eSCO S4 setting supported */ /* Proprietary features: using bits after 12 */ @@ -227,7 +227,7 @@ typedef uint16_t tBTA_AG_PEER_CODEC; #define BTA_AG_ERR_NOT_FOR_VOIP 34 /* Not supported on this call type(VoIP) */ #define BTA_AG_ERR_SIP_RESP_CODE 35 /* SIP 3 digit response code */ -#if 0 /* Not Used in Bluetooth HFP 1.5 Specification */ +#if 0 /* Not Used in Bluetooth HFP 1.5 Specification */ #define BTA_AG_ERR_PHADAP_LNK_RES 2 /* Phone-adapter link reserved */ #define BTA_AG_ERR_PHFSIM_PIN_REQ 6 /* PH-FSIM PIN required */ #define BTA_AG_ERR_PHFSIM_PUK_REQ 7 /* PH-FSIM PUK required */ @@ -248,11 +248,11 @@ typedef uint16_t tBTA_AG_PEER_CODEC; #define BTA_AG_ERR_CORP_PIN_REQ 46 /* Corporate personalization PUK required */ #define BTA_AG_ERR_CORP_PUK_REQ 47 -#define BTA_AG_ERR_UNKNOWN 100 /* Unknown error */ +#define BTA_AG_ERR_UNKNOWN 100 /* Unknown error */ /* GPRS-related errors */ -#define BTA_AG_ERR_ILL_MS 103 /* Illegal MS (#3) */ -#define BTA_AG_ERR_ILL_ME 106 /* Illegal ME (#6) */ +#define BTA_AG_ERR_ILL_MS 103 /* Illegal MS (#3) */ +#define BTA_AG_ERR_ILL_ME 106 /* Illegal ME (#6) */ #define BTA_AG_ERR_GPRS_NOT_ALLOWED 107 /* GPRS services not allowed (#7) */ #define BTA_AG_ERR_PLMN_NOT_ALLOWED 111 /* PLMN services not allowed (#11) */ #define BTA_AG_ERR_LOC_NOT_ALLOWED 112 /* Location area not allowed (#12) */ @@ -324,8 +324,7 @@ struct tBTA_AG_RES_DATA { uint16_t num; uint16_t audio_handle; uint16_t errcode; /* Valid only if 'ok_flag' is set to BTA_AG_OK_ERROR */ - uint8_t - ok_flag; /* Indicates if response is finished, and if error occurred */ + uint8_t ok_flag; /* Indicates if response is finished, and if error occurred */ bool state; static const tBTA_AG_RES_DATA kEmpty; }; @@ -536,8 +535,7 @@ void BTA_AgDisable(); * ******************************************************************************/ void BTA_AgRegister(tBTA_SERVICE_MASK services, tBTA_AG_FEAT features, - const std::vector& service_names, - uint8_t app_id); + const std::vector& service_names, uint8_t app_id); /******************************************************************************* * @@ -618,8 +616,7 @@ void BTA_AgAudioClose(uint16_t handle); * Returns void * ******************************************************************************/ -void BTA_AgResult(uint16_t handle, tBTA_AG_RES result, - const tBTA_AG_RES_DATA& data); +void BTA_AgResult(uint16_t handle, tBTA_AG_RES result, const tBTA_AG_RES_DATA& data); /******************************************************************************* * diff --git a/system/bta/include/bta_ag_swb_aptx.h b/system/bta/include/bta_ag_swb_aptx.h index 151c68b16f0..46ca5a83c2e 100644 --- a/system/bta/include/bta_ag_swb_aptx.h +++ b/system/bta/include/bta_ag_swb_aptx.h @@ -33,13 +33,12 @@ bool is_hfp_aptx_voice_enabled(); -void bta_ag_swb_handle_vs_at_events(tBTA_AG_SCB* p_scb, uint16_t cmd, - int16_t int_arg, tBTA_AG_VAL* val); +void bta_ag_swb_handle_vs_at_events(tBTA_AG_SCB* p_scb, uint16_t cmd, int16_t int_arg, + tBTA_AG_VAL* val); tBTA_AG_PEER_CODEC bta_ag_parse_qac(char* p_s); -bool get_swb_codec_status(bluetooth::headset::bthf_swb_codec_t swb_codec, - RawAddress* bd_addr); +bool get_swb_codec_status(bluetooth::headset::bthf_swb_codec_t swb_codec, RawAddress* bd_addr); bt_status_t enable_aptx_swb_codec(bool enable, RawAddress* bd_addr); -#endif //_BTA_AG_SWB_H_ +#endif // _BTA_AG_SWB_H_ diff --git a/system/bta/include/bta_api.h b/system/bta/include/bta_api.h index f8920085ecb..95cc697c96a 100644 --- a/system/bta/include/bta_api.h +++ b/system/bta/include/bta_api.h @@ -81,10 +81,10 @@ typedef uint8_t tBTA_SERVICE_ID; /* Service ID Mask */ -#define BTA_RES_SERVICE_MASK 0x00000001 /* Reserved */ -#define BTA_HSP_SERVICE_MASK 0x00000020 /* HSP AG role. */ -#define BTA_HFP_SERVICE_MASK 0x00000040 /* HFP AG role */ -#define BTA_HL_SERVICE_MASK 0x08000000 /* Health Device Profile */ +#define BTA_RES_SERVICE_MASK 0x00000001 /* Reserved */ +#define BTA_HSP_SERVICE_MASK 0x00000020 /* HSP AG role. */ +#define BTA_HFP_SERVICE_MASK 0x00000040 /* HFP AG role */ +#define BTA_HL_SERVICE_MASK 0x08000000 /* Health Device Profile */ #define BTA_BLE_SERVICE_MASK 0x40000000 /* GATT based service */ #define BTA_ALL_SERVICE_MASK 0x7FFFFFFF /* All services supported by BTA. */ @@ -96,9 +96,8 @@ typedef uint32_t tBTA_SERVICE_MASK; #define BTA_ALL_APP_ID 0xFF /* Discoverable Modes */ -typedef uint16_t - tBTA_DM_DISC; /* this discoverability mode is a bit mask among BR mode and - LE mode */ +typedef uint16_t tBTA_DM_DISC; /* this discoverability mode is a bit mask among BR mode and + LE mode */ /* Connectable Modes */ typedef uint16_t tBTA_DM_CONN; @@ -113,10 +112,9 @@ typedef enum : uint8_t { } tBTA_PREF_ROLES; inline tBTA_PREF_ROLES toBTA_PREF_ROLES(uint8_t role) { - bluetooth::log::assert_that( - role <= BTA_PERIPHERAL_ROLE_ONLY, - "Passing illegal preferred role:0x{:02x} [0x{:02x}<=>0x{:02x}]", role, - int(BTA_ANY_ROLE), int(BTA_PERIPHERAL_ROLE_ONLY)); + bluetooth::log::assert_that(role <= BTA_PERIPHERAL_ROLE_ONLY, + "Passing illegal preferred role:0x{:02x} [0x{:02x}<=>0x{:02x}]", role, + int(BTA_ANY_ROLE), int(BTA_PERIPHERAL_ROLE_ONLY)); return static_cast(role); } @@ -140,32 +138,32 @@ enum { BTA_DM_PARTIAL_SCATTERNET, /* Device supports partial scatternet. It can have simultaneous connection in Central and Peripheral roles for short period of time */ - BTA_DM_FULL_SCATTERNET /* Device can have simultaneous connection in central - and peripheral roles */ + BTA_DM_FULL_SCATTERNET /* Device can have simultaneous connection in central + and peripheral roles */ }; typedef struct { - uint8_t bta_dm_eir_min_name_len; /* minimum length of local name when it is - shortened */ + uint8_t bta_dm_eir_min_name_len; /* minimum length of local name when it is + shortened */ uint32_t uuid_mask[BTM_EIR_SERVICE_ARRAY_SIZE]; /* mask of UUID list in EIR */ - int8_t* bta_dm_eir_inq_tx_power; /* Inquiry TX power */ - uint8_t bta_dm_eir_flag_len; /* length of flags in bytes */ - uint8_t* bta_dm_eir_flags; /* flags for EIR */ - uint8_t bta_dm_eir_manufac_spec_len; /* length of manufacturer specific in - bytes */ - uint8_t* bta_dm_eir_manufac_spec; /* manufacturer specific */ - uint8_t bta_dm_eir_additional_len; /* length of additional data in bytes */ - uint8_t* bta_dm_eir_additional; /* additional data */ + int8_t* bta_dm_eir_inq_tx_power; /* Inquiry TX power */ + uint8_t bta_dm_eir_flag_len; /* length of flags in bytes */ + uint8_t* bta_dm_eir_flags; /* flags for EIR */ + uint8_t bta_dm_eir_manufac_spec_len; /* length of manufacturer specific in + bytes */ + uint8_t* bta_dm_eir_manufac_spec; /* manufacturer specific */ + uint8_t bta_dm_eir_additional_len; /* length of additional data in bytes */ + uint8_t* bta_dm_eir_additional; /* additional data */ } tBTA_DM_EIR_CONF; typedef uint8_t tBTA_DM_BLE_RSSI_ALERT_TYPE; -typedef enum: uint8_t { - BTA_DM_LINK_UP_EVT = 5, /* Connection UP event */ - BTA_DM_LINK_DOWN_EVT = 6, /* Connection DOWN event */ - BTA_DM_LE_FEATURES_READ = 27, /* Cotroller specific LE features are read */ - BTA_DM_LINK_UP_FAILED_EVT = 34, /* Create connection failed event */ +typedef enum : uint8_t { + BTA_DM_LINK_UP_EVT = 5, /* Connection UP event */ + BTA_DM_LINK_DOWN_EVT = 6, /* Connection DOWN event */ + BTA_DM_LE_FEATURES_READ = 27, /* Cotroller specific LE features are read */ + BTA_DM_LINK_UP_FAILED_EVT = 34, /* Create connection failed event */ } tBTA_DM_ACL_EVT; /* Structure associated with BTA_DM_LINK_UP_EVT */ @@ -190,9 +188,9 @@ typedef struct { } tBTA_DM_LINK_DOWN; typedef union { - tBTA_DM_LINK_UP link_up; /* ACL connection up event */ + tBTA_DM_LINK_UP link_up; /* ACL connection up event */ tBTA_DM_LINK_UP_FAILED link_up_failed; /* ACL connection up failure event */ - tBTA_DM_LINK_DOWN link_down; /* ACL connection down event */ + tBTA_DM_LINK_DOWN link_down; /* ACL connection down event */ } tBTA_DM_ACL; typedef void(tBTA_DM_ACL_CBACK)(tBTA_DM_ACL_EVT event, tBTA_DM_ACL* p_data); @@ -202,10 +200,10 @@ typedef void(tBTA_DM_ACL_CBACK)(tBTA_DM_ACL_EVT event, tBTA_DM_ACL* p_data); /* Search callback events */ typedef enum : uint8_t { - BTA_DM_INQ_RES_EVT = 0, /* Inquiry result for a peer device. */ - BTA_DM_INQ_CMPL_EVT = 1, /* Inquiry complete. */ - BTA_DM_DISC_RES_EVT = 2, /* Service Discovery result for a peer device. */ - BTA_DM_DISC_CMPL_EVT = 3, /* Discovery complete. */ + BTA_DM_INQ_RES_EVT = 0, /* Inquiry result for a peer device. */ + BTA_DM_INQ_CMPL_EVT = 1, /* Inquiry complete. */ + BTA_DM_DISC_RES_EVT = 2, /* Service Discovery result for a peer device. */ + BTA_DM_DISC_CMPL_EVT = 3, /* Discovery complete. */ BTA_DM_SEARCH_CANCEL_CMPL_EVT = 4, /* Search cancelled */ BTA_DM_NAME_READ_EVT = 5, /* Name read complete. */ BTA_DM_OBSERVE_CMPL_EVT = 6, /* Observe complete. */ @@ -233,10 +231,10 @@ typedef struct { the name of the device */ /* If the device name is known to application BTA skips the remote name * request */ - bool is_limited; /* true, if the limited inquiry bit is set in the CoD */ - int8_t rssi; /* The rssi value */ + bool is_limited; /* true, if the limited inquiry bit is set in the CoD */ + int8_t rssi; /* The rssi value */ const uint8_t* p_eir; /* received EIR */ - uint16_t eir_len; /* received EIR length */ + uint16_t eir_len; /* received EIR length */ uint8_t inq_result_type; tBLE_ADDR_TYPE ble_addr_type; uint16_t ble_evt_type; @@ -247,7 +245,7 @@ typedef struct { uint16_t ble_periodic_adv_int; tBT_DEVICE_TYPE device_type; uint8_t flag; - bool include_rsi; /* true, if ADV contains RSI data */ + bool include_rsi; /* true, if ADV contains RSI data */ RawAddress original_bda; /* original address to pass up to GattService#onScanResult */ uint16_t clock_offset; @@ -260,35 +258,30 @@ typedef struct { /* Structure associated with BTA_DM_NAME_READ_EVT */ typedef struct { - RawAddress bd_addr; /* BD address peer device. */ - BD_NAME bd_name; /* Name of peer device. */ + RawAddress bd_addr; /* BD address peer device. */ + BD_NAME bd_name; /* Name of peer device. */ } tBTA_DM_NAME_READ_CMPL; /* Union of all search callback structures */ typedef union { - tBTA_DM_INQ_RES inq_res; /* Inquiry result for a peer device. */ + tBTA_DM_INQ_RES inq_res; /* Inquiry result for a peer device. */ tBTA_DM_NAME_READ_CMPL name_res; /* Name read result for a peer device. */ tBTA_DM_OBSERVE_CMPL observe_cmpl; /* Observe complete. */ } tBTA_DM_SEARCH; /* Search callback */ -typedef void(tBTA_DM_SEARCH_CBACK)(tBTA_DM_SEARCH_EVT event, - tBTA_DM_SEARCH* p_data); +typedef void(tBTA_DM_SEARCH_CBACK)(tBTA_DM_SEARCH_EVT event, tBTA_DM_SEARCH* p_data); // TODO: delete bd_name parameter after separate_service_and_device_discovery // rolls out typedef void(tBTA_DM_GATT_DISC_CBACK)(RawAddress bd_addr, BD_NAME bd_name, - std::vector& services, - bool transport_le); -typedef void(tBTA_DM_DID_RES_CBACK)(RawAddress bd_addr, uint8_t vendor_id_src, - uint16_t vendor_id, uint16_t product_id, - uint16_t version); + std::vector& services, bool transport_le); +typedef void(tBTA_DM_DID_RES_CBACK)(RawAddress bd_addr, uint8_t vendor_id_src, uint16_t vendor_id, + uint16_t product_id, uint16_t version); // TODO: delete after separate_service_and_device_discovery rolls out -typedef void(tBTA_DM_NAME_READ_CBACK)(RawAddress bd_addr, - tHCI_ERROR_CODE hci_status, +typedef void(tBTA_DM_NAME_READ_CBACK)(RawAddress bd_addr, tHCI_ERROR_CODE hci_status, const BD_NAME bd_name); -typedef void(tBTA_DM_DISC_CBACK)(RawAddress bd_addr, - const std::vector& uuids, +typedef void(tBTA_DM_DISC_CBACK)(RawAddress bd_addr, const std::vector& uuids, tBTA_STATUS result); struct service_discovery_callbacks { tBTA_DM_GATT_DISC_CBACK* on_gatt_results; @@ -301,37 +294,33 @@ struct service_discovery_callbacks { /* Execute call back */ typedef void(tBTA_DM_EXEC_CBACK)(void* p_param); -typedef void(tBTA_BLE_ENERGY_INFO_CBACK)(tBTM_BLE_TX_TIME_MS tx_time, - tBTM_BLE_RX_TIME_MS rx_time, +typedef void(tBTA_BLE_ENERGY_INFO_CBACK)(tBTM_BLE_TX_TIME_MS tx_time, tBTM_BLE_RX_TIME_MS rx_time, tBTM_BLE_IDLE_TIME_MS idle_time, tBTM_BLE_ENERGY_USED energy_used, - tBTM_CONTRL_STATE ctrl_state, - tBTA_STATUS status); + tBTM_CONTRL_STATE ctrl_state, tBTA_STATUS status); /* Maximum service name length */ #define BTA_SERVICE_NAME_LEN 35 typedef enum : uint8_t { /* power mode actions */ - BTA_DM_PM_NO_ACTION = 0x00, /* no change to the current pm setting */ - BTA_DM_PM_PARK = 0x10, /* prefers park mode */ - BTA_DM_PM_SNIFF = 0x20, /* prefers sniff mode */ - BTA_DM_PM_SNIFF1 = 0x21, /* prefers sniff1 mode */ - BTA_DM_PM_SNIFF2 = 0x22, /* prefers sniff2 mode */ - BTA_DM_PM_SNIFF3 = 0x23, /* prefers sniff3 mode */ - BTA_DM_PM_SNIFF4 = 0x24, /* prefers sniff4 mode */ - BTA_DM_PM_SNIFF5 = 0x25, /* prefers sniff5 mode */ - BTA_DM_PM_SNIFF6 = 0x26, /* prefers sniff6 mode */ - BTA_DM_PM_SNIFF7 = 0x27, /* prefers sniff7 mode */ - BTA_DM_PM_SNIFF_USER0 = - 0x28, /* prefers user-defined sniff0 mode (testtool only) */ - BTA_DM_PM_SNIFF_USER1 = - 0x29, /* prefers user-defined sniff1 mode (testtool only) */ - BTA_DM_PM_ACTIVE = 0x40, /* prefers active mode */ - BTA_DM_PM_RETRY = 0x80, /* retry power mode based on current settings */ - BTA_DM_PM_SUSPEND = 0x04, /* prefers suspend mode */ - BTA_DM_PM_NO_PREF = 0x01, /* service has no preference on power mode setting. - eg. connection to \ service got closed */ + BTA_DM_PM_NO_ACTION = 0x00, /* no change to the current pm setting */ + BTA_DM_PM_PARK = 0x10, /* prefers park mode */ + BTA_DM_PM_SNIFF = 0x20, /* prefers sniff mode */ + BTA_DM_PM_SNIFF1 = 0x21, /* prefers sniff1 mode */ + BTA_DM_PM_SNIFF2 = 0x22, /* prefers sniff2 mode */ + BTA_DM_PM_SNIFF3 = 0x23, /* prefers sniff3 mode */ + BTA_DM_PM_SNIFF4 = 0x24, /* prefers sniff4 mode */ + BTA_DM_PM_SNIFF5 = 0x25, /* prefers sniff5 mode */ + BTA_DM_PM_SNIFF6 = 0x26, /* prefers sniff6 mode */ + BTA_DM_PM_SNIFF7 = 0x27, /* prefers sniff7 mode */ + BTA_DM_PM_SNIFF_USER0 = 0x28, /* prefers user-defined sniff0 mode (testtool only) */ + BTA_DM_PM_SNIFF_USER1 = 0x29, /* prefers user-defined sniff1 mode (testtool only) */ + BTA_DM_PM_ACTIVE = 0x40, /* prefers active mode */ + BTA_DM_PM_RETRY = 0x80, /* retry power mode based on current settings */ + BTA_DM_PM_SUSPEND = 0x04, /* prefers suspend mode */ + BTA_DM_PM_NO_PREF = 0x01, /* service has no preference on power mode setting. + eg. connection to \ service got closed */ BTA_DM_PM_SNIFF_MASK = 0x0f, // Masks the sniff submode } tBTA_DM_PM_ACTION_BITMASK; typedef uint8_t tBTA_DM_PM_ACTION; @@ -350,8 +339,7 @@ enum { #define BTA_DM_PM_NUM_EVTS 9 #ifndef BTA_DM_PM_PARK_IDX -#define BTA_DM_PM_PARK_IDX \ - 7 /* the actual index to bta_dm_pm_md[] for PARK mode */ +#define BTA_DM_PM_PARK_IDX 7 /* the actual index to bta_dm_pm_md[] for PARK mode */ #endif #ifndef BTA_DM_PM_SNIFF_A2DP_IDX @@ -457,7 +445,7 @@ enum { #endif /* Device Identification (DI) data structure -*/ + */ #ifndef BTA_DI_NUM_MAX #define BTA_DI_NUM_MAX 3 @@ -553,8 +541,8 @@ void BTA_DmSearchCancel(void); * Returns void * ******************************************************************************/ -void BTA_DmDiscover(const RawAddress& bd_addr, - service_discovery_callbacks cback, tBT_TRANSPORT transport); +void BTA_DmDiscover(const RawAddress& bd_addr, service_discovery_callbacks cback, + tBT_TRANSPORT transport); /******************************************************************************* * @@ -566,8 +554,7 @@ void BTA_DmDiscover(const RawAddress& bd_addr, * BTA_FAILURE if cached name is not available * ******************************************************************************/ -tBTA_STATUS BTA_DmGetCachedRemoteName(const RawAddress& remote_device, - uint8_t** pp_cached_name); +tBTA_STATUS BTA_DmGetCachedRemoteName(const RawAddress& remote_device, uint8_t** pp_cached_name); /******************************************************************************* * @@ -589,8 +576,7 @@ bool BTA_DmGetConnectionState(const RawAddress& bd_addr); * Returns BTA_SUCCESS if record set sucessfully, otherwise error code. * ******************************************************************************/ -tBTA_STATUS BTA_DmSetLocalDiRecord(tSDP_DI_RECORD* p_device_info, - uint32_t* p_handle); +tBTA_STATUS BTA_DmSetLocalDiRecord(tSDP_DI_RECORD* p_device_info, uint32_t* p_handle); /******************************************************************************* * @@ -609,9 +595,8 @@ tBTA_STATUS BTA_DmSetLocalDiRecord(tSDP_DI_RECORD* p_device_info, * Returns void * ******************************************************************************/ -void BTA_DmSetBlePrefConnParams(const RawAddress& bd_addr, - uint16_t min_conn_int, uint16_t max_conn_int, - uint16_t peripheral_latency, +void BTA_DmSetBlePrefConnParams(const RawAddress& bd_addr, uint16_t min_conn_int, + uint16_t max_conn_int, uint16_t peripheral_latency, uint16_t supervision_tout); /******************************************************************************* @@ -671,8 +656,7 @@ void BTA_DmBleConfigLocalPrivacy(bool privacy_enable); * Returns void * ******************************************************************************/ -void BTA_DmBleEnableRemotePrivacy(const RawAddress& bd_addr, - bool privacy_enable); +void BTA_DmBleEnableRemotePrivacy(const RawAddress& bd_addr, bool privacy_enable); /******************************************************************************* * @@ -690,10 +674,9 @@ void BTA_DmBleEnableRemotePrivacy(const RawAddress& bd_addr, * Returns void * ******************************************************************************/ -void BTA_DmBleUpdateConnectionParams(const RawAddress& bd_addr, - uint16_t min_int, uint16_t max_int, - uint16_t latency, uint16_t timeout, - uint16_t min_ce_len, uint16_t max_ce_len); +void BTA_DmBleUpdateConnectionParams(const RawAddress& bd_addr, uint16_t min_int, uint16_t max_int, + uint16_t latency, uint16_t timeout, uint16_t min_ce_len, + uint16_t max_ce_len); /******************************************************************************* * @@ -794,9 +777,8 @@ void BTA_DmSetEventFilterConnectionSetupAllDevices(); * Parameters * *******************************************************************************/ -void BTA_DmAllowWakeByHid( - std::vector classic_hid_devices, - std::vector> le_hid_devices); +void BTA_DmAllowWakeByHid(std::vector classic_hid_devices, + std::vector> le_hid_devices); /******************************************************************************* * @@ -807,8 +789,7 @@ void BTA_DmAllowWakeByHid( * Parameters * *******************************************************************************/ -void BTA_DmRestoreFilterAcceptList( - std::vector> le_devices); +void BTA_DmRestoreFilterAcceptList(std::vector> le_devices); /******************************************************************************* * @@ -862,9 +843,8 @@ void BTA_DmBleResetId(void); * Returns void * ******************************************************************************/ -void BTA_DmBleSubrateRequest(const RawAddress& bd_addr, uint16_t subrate_min, - uint16_t subrate_max, uint16_t max_latency, - uint16_t cont_num, uint16_t timeout); +void BTA_DmBleSubrateRequest(const RawAddress& bd_addr, uint16_t subrate_min, uint16_t subrate_max, + uint16_t max_latency, uint16_t cont_num, uint16_t timeout); /******************************************************************************* * diff --git a/system/bta/include/bta_ar_api.h b/system/bta/include/bta_ar_api.h index f71d58d0040..c6c95f2b56a 100644 --- a/system/bta/include/bta_ar_api.h +++ b/system/bta/include/bta_ar_api.h @@ -84,8 +84,7 @@ void bta_ar_dereg_avdt(); * Returns void * ******************************************************************************/ -void bta_ar_avdt_conn(tBTA_SYS_ID sys_id, const RawAddress& bd_addr, - uint8_t scb_index); +void bta_ar_avdt_conn(tBTA_SYS_ID sys_id, const RawAddress& bd_addr, uint8_t scb_index); /******************************************************************************* * @@ -118,9 +117,8 @@ void bta_ar_dereg_avct(); * Returns void * *****************************************************************************/ -void bta_ar_reg_avrc(uint16_t service_uuid, const char* p_service_name, - const char* p_provider_name, uint16_t categories, - bool browse_supported, uint16_t profile_version); +void bta_ar_reg_avrc(uint16_t service_uuid, const char* p_service_name, const char* p_provider_name, + uint16_t categories, bool browse_supported, uint16_t profile_version); /****************************************************************************** * @@ -145,9 +143,9 @@ void bta_ar_dereg_avrc(uint16_t service_uuid); * Returns void * *****************************************************************************/ -extern void bta_ar_reg_avrc_for_src_sink_coexist( - uint16_t service_uuid, const char* service_name, const char* provider_name, - uint16_t categories, tBTA_SYS_ID sys_id, bool browse_supported, - uint16_t profile_version); +extern void bta_ar_reg_avrc_for_src_sink_coexist(uint16_t service_uuid, const char* service_name, + const char* provider_name, uint16_t categories, + tBTA_SYS_ID sys_id, bool browse_supported, + uint16_t profile_version); #endif /* BTA_AR_API_H */ diff --git a/system/bta/include/bta_av_api.h b/system/bta/include/bta_av_api.h index c2c3c7d74b8..068a594fe88 100644 --- a/system/bta/include/bta_av_api.h +++ b/system/bta/include/bta_av_api.h @@ -43,9 +43,8 @@ #define BTA_AV_FAIL_SDP 2 /* service not found */ #define BTA_AV_FAIL_STREAM 3 /* stream connection failed */ #define BTA_AV_FAIL_RESOURCES 4 /* no resources */ -#define BTA_AV_FAIL_ROLE 5 /* failed due to role management related issues */ -#define BTA_AV_FAIL_GET_CAP \ - 6 /* get capability failed due to no SEP availale on the peer */ +#define BTA_AV_FAIL_ROLE 5 /* failed due to role management related issues */ +#define BTA_AV_FAIL_GET_CAP 6 /* get capability failed due to no SEP availale on the peer */ typedef uint8_t tBTA_AV_STATUS; @@ -53,22 +52,18 @@ typedef uint8_t tBTA_AV_STATUS; #define BTA_AV_FEAT_RCTG 0x0001 /* remote control target */ #define BTA_AV_FEAT_RCCT 0x0002 /* remote control controller */ #define BTA_AV_FEAT_PROTECT 0x0004 /* streaming media contect protection */ -#define BTA_AV_FEAT_VENDOR \ - 0x0008 /* remote control vendor dependent commands \ - */ -#define BTA_AV_FEAT_REPORT 0x0020 /* use reporting service for VDP */ -#define BTA_AV_FEAT_METADATA \ - 0x0040 /* remote control Metadata Transfer command/response */ -#define BTA_AV_FEAT_MULTI_AV \ - 0x0080 /* use multi-av, if controller supports it */ -#define BTA_AV_FEAT_BROWSE 0x0010 /* use browsing channel */ -#define BTA_AV_FEAT_ADV_CTRL \ - 0x0200 /* remote control Advanced Control command/response */ -#define BTA_AV_FEAT_DELAY_RPT 0x0400 /* allow delay reporting */ -#define BTA_AV_FEAT_ACP_START \ - 0x0800 /* start stream when 2nd SNK was accepted */ +#define BTA_AV_FEAT_VENDOR \ + 0x0008 /* remote control vendor dependent commands \ + */ +#define BTA_AV_FEAT_REPORT 0x0020 /* use reporting service for VDP */ +#define BTA_AV_FEAT_METADATA 0x0040 /* remote control Metadata Transfer command/response */ +#define BTA_AV_FEAT_MULTI_AV 0x0080 /* use multi-av, if controller supports it */ +#define BTA_AV_FEAT_BROWSE 0x0010 /* use browsing channel */ +#define BTA_AV_FEAT_ADV_CTRL 0x0200 /* remote control Advanced Control command/response */ +#define BTA_AV_FEAT_DELAY_RPT 0x0400 /* allow delay reporting */ +#define BTA_AV_FEAT_ACP_START 0x0800 /* start stream when 2nd SNK was accepted */ #define BTA_AV_FEAT_COVER_ARTWORK 0x1000 /* use cover art feature */ -#define BTA_AV_FEAT_APP_SETTING 0x2000 /* Player app setting support */ +#define BTA_AV_FEAT_APP_SETTING 0x2000 /* Player app setting support */ /* Internal features */ #define BTA_AV_FEAT_NO_SCO_SSPD \ @@ -127,18 +122,17 @@ typedef uint8_t tBTA_AV_ERR; #define BTA_AV_VENDOR_CMD_EVT 12 /* vendor dependent remote control command */ #define BTA_AV_VENDOR_RSP_EVT \ 13 /* vendor dependent remote control response \ - */ + */ #define BTA_AV_RECONFIG_EVT 14 /* reconfigure response */ #define BTA_AV_SUSPEND_EVT 15 /* suspend response */ -#define BTA_AV_PENDING_EVT \ - 16 /* incoming connection pending: \ - * signal channel is open and stream is \ - * not open after \ - * BTA_AV_SIGNALLING_TIMEOUT_MS */ -#define BTA_AV_META_MSG_EVT 17 /* metadata messages */ -#define BTA_AV_REJECT_EVT 18 /* incoming connection rejected */ -#define BTA_AV_RC_FEAT_EVT \ - 19 /* remote control channel peer supported features update */ +#define BTA_AV_PENDING_EVT \ + 16 /* incoming connection pending: \ + * signal channel is open and stream is \ + * not open after \ + * BTA_AV_SIGNALLING_TIMEOUT_MS */ +#define BTA_AV_META_MSG_EVT 17 /* metadata messages */ +#define BTA_AV_REJECT_EVT 18 /* incoming connection rejected */ +#define BTA_AV_RC_FEAT_EVT 19 /* remote control channel peer supported features update */ #define BTA_AV_SINK_MEDIA_CFG_EVT 20 /* command to configure codec */ #define BTA_AV_SINK_MEDIA_DATA_EVT 21 /* sending data to Media Task */ #define BTA_AV_OFFLOAD_START_RSP_EVT 22 /* a2dp offload start response */ @@ -161,7 +155,9 @@ typedef enum { } tBTA_AV_CODEC_TYPE; /* Event associated with BTA_AV_ENABLE_EVT */ -typedef struct { tBTA_AV_FEAT features; } tBTA_AV_ENABLE; +typedef struct { + tBTA_AV_FEAT features; +} tBTA_AV_ENABLE; /* Event associated with BTA_AV_REGISTER_EVT */ typedef struct { @@ -324,7 +320,9 @@ typedef struct { } tBTA_AV_META_MSG; /* data associated with BTA_AV_PENDING_EVT */ -typedef struct { RawAddress bd_addr; } tBTA_AV_PEND; +typedef struct { + RawAddress bd_addr; +} tBTA_AV_PEND; /* data associated with BTA_AV_REJECT_EVT */ typedef struct { @@ -376,8 +374,7 @@ typedef union { /* AV callback */ typedef void(tBTA_AV_CBACK)(tBTA_AV_EVT event, tBTA_AV* p_data); -typedef void(tBTA_AV_SINK_DATA_CBACK)(const RawAddress&, tBTA_AV_EVT event, - tBTA_AV_MEDIA* p_data); +typedef void(tBTA_AV_SINK_DATA_CBACK)(const RawAddress&, tBTA_AV_EVT event, tBTA_AV_MEDIA* p_data); /* type for stream state machine action functions */ struct tBTA_AV_SCB; @@ -386,22 +383,20 @@ typedef void (*tBTA_AV_ACT)(tBTA_AV_SCB* p_cb, tBTA_AV_DATA* p_data); /* AV configuration structure */ typedef struct { - uint32_t company_id; /* AVRCP Company ID */ - uint16_t avrc_ct_cat; /* AVRCP controller categories */ - uint16_t avrc_tg_cat; /* AVRCP target categories */ - uint16_t audio_mqs; /* AVDTP audio channel max data queue size */ - bool avrc_group; /* true, to accept AVRC 1.3 group nevigation command */ - uint8_t num_co_ids; /* company id count in p_meta_co_ids */ - uint8_t num_evt_ids; /* event id count in p_meta_evt_ids */ - tBTA_AV_CODE - rc_pass_rsp; /* the default response code for pass through commands */ - const uint32_t* - p_meta_co_ids; /* the metadata Get Capabilities response for company id */ + uint32_t company_id; /* AVRCP Company ID */ + uint16_t avrc_ct_cat; /* AVRCP controller categories */ + uint16_t avrc_tg_cat; /* AVRCP target categories */ + uint16_t audio_mqs; /* AVDTP audio channel max data queue size */ + bool avrc_group; /* true, to accept AVRC 1.3 group nevigation command */ + uint8_t num_co_ids; /* company id count in p_meta_co_ids */ + uint8_t num_evt_ids; /* event id count in p_meta_evt_ids */ + tBTA_AV_CODE rc_pass_rsp; /* the default response code for pass through commands */ + const uint32_t* p_meta_co_ids; /* the metadata Get Capabilities response for company id */ const uint8_t* p_meta_evt_ids; /* the the metadata Get Capabilities response for event id */ char avrc_controller_name[BTA_SERVICE_NAME_LEN]; /* Default AVRCP controller name */ - char avrc_target_name[BTA_SERVICE_NAME_LEN]; /* Default AVRCP target name*/ + char avrc_target_name[BTA_SERVICE_NAME_LEN]; /* Default AVRCP target name*/ } tBTA_AV_CFG; /***************************************************************************** @@ -448,9 +443,8 @@ void BTA_AvDisable(void); * Returns void * ******************************************************************************/ -void BTA_AvRegister(tBTA_AV_CHNL chnl, const char* p_service_name, - uint8_t app_id, tBTA_AV_SINK_DATA_CBACK* p_sink_data_cback, - uint16_t service_uuid); +void BTA_AvRegister(tBTA_AV_CHNL chnl, const char* p_service_name, uint8_t app_id, + tBTA_AV_SINK_DATA_CBACK* p_sink_data_cback, uint16_t service_uuid); /******************************************************************************* * @@ -474,8 +468,7 @@ void BTA_AvDeregister(tBTA_AV_HNDL hndl); * Returns void * ******************************************************************************/ -void BTA_AvOpen(const RawAddress& bd_addr, tBTA_AV_HNDL handle, bool use_rc, - uint16_t uuid); +void BTA_AvOpen(const RawAddress& bd_addr, tBTA_AV_HNDL handle, bool use_rc, uint16_t uuid); /******************************************************************************* * @@ -536,9 +529,8 @@ void BTA_AvStop(tBTA_AV_HNDL handle, bool suspend); * Returns void * ******************************************************************************/ -void BTA_AvReconfig(tBTA_AV_HNDL hndl, bool suspend, uint8_t sep_info_idx, - uint8_t* p_codec_info, uint8_t num_protect, - const uint8_t* p_protect_info); +void BTA_AvReconfig(tBTA_AV_HNDL hndl, bool suspend, uint8_t sep_info_idx, uint8_t* p_codec_info, + uint8_t num_protect, const uint8_t* p_protect_info); /******************************************************************************* * @@ -564,8 +556,7 @@ void BTA_AvProtectReq(tBTA_AV_HNDL hndl, uint8_t* p_data, uint16_t len); * Returns void * ******************************************************************************/ -void BTA_AvProtectRsp(tBTA_AV_HNDL hndl, uint8_t error_code, uint8_t* p_data, - uint16_t len); +void BTA_AvProtectRsp(tBTA_AV_HNDL hndl, uint8_t error_code, uint8_t* p_data, uint16_t len); /******************************************************************************* * @@ -577,8 +568,7 @@ void BTA_AvProtectRsp(tBTA_AV_HNDL hndl, uint8_t error_code, uint8_t* p_data, * Returns void * ******************************************************************************/ -void BTA_AvRemoteCmd(uint8_t rc_handle, uint8_t label, tBTA_AV_RC rc_id, - tBTA_AV_STATE key_state); +void BTA_AvRemoteCmd(uint8_t rc_handle, uint8_t label, tBTA_AV_RC rc_id, tBTA_AV_STATE key_state); /******************************************************************************* * @@ -591,9 +581,8 @@ void BTA_AvRemoteCmd(uint8_t rc_handle, uint8_t label, tBTA_AV_RC rc_id, * Returns void * ******************************************************************************/ -void BTA_AvRemoteVendorUniqueCmd(uint8_t rc_handle, uint8_t label, - tBTA_AV_STATE key_state, uint8_t* p_msg, - uint8_t buf_len); +void BTA_AvRemoteVendorUniqueCmd(uint8_t rc_handle, uint8_t label, tBTA_AV_STATE key_state, + uint8_t* p_msg, uint8_t buf_len); /******************************************************************************* * @@ -606,8 +595,8 @@ void BTA_AvRemoteVendorUniqueCmd(uint8_t rc_handle, uint8_t label, * Returns void * ******************************************************************************/ -void BTA_AvVendorCmd(uint8_t rc_handle, uint8_t label, tBTA_AV_CODE cmd_code, - uint8_t* p_data, uint16_t len); +void BTA_AvVendorCmd(uint8_t rc_handle, uint8_t label, tBTA_AV_CODE cmd_code, uint8_t* p_data, + uint16_t len); /******************************************************************************* * @@ -621,8 +610,8 @@ void BTA_AvVendorCmd(uint8_t rc_handle, uint8_t label, tBTA_AV_CODE cmd_code, * Returns void * ******************************************************************************/ -void BTA_AvVendorRsp(uint8_t rc_handle, uint8_t label, tBTA_AV_CODE rsp_code, - uint8_t* p_data, uint16_t len, uint32_t company_id); +void BTA_AvVendorRsp(uint8_t rc_handle, uint8_t label, tBTA_AV_CODE rsp_code, uint8_t* p_data, + uint16_t len, uint32_t company_id); /******************************************************************************* * @@ -659,28 +648,26 @@ void BTA_AvCloseRc(uint8_t rc_handle); * Returns void * ******************************************************************************/ -void BTA_AvMetaRsp(uint8_t rc_handle, uint8_t label, tBTA_AV_CODE rsp_code, - BT_HDR* p_pkt); +void BTA_AvMetaRsp(uint8_t rc_handle, uint8_t label, tBTA_AV_CODE rsp_code, BT_HDR* p_pkt); /******************************************************************************* * * Function BTA_AvMetaCmd * * Description Send a Metadata/Advanced Control command. The message -*contained + *contained * in p_pkt can be composed with AVRC utility functions. * This function can only be used if AV is enabled with feature * BTA_AV_FEAT_METADATA. * This message is sent only when the peer supports the TG -*role. -*8 The only command makes sense right now is the absolute -*volume command. + *role. + *8 The only command makes sense right now is the absolute + *volume command. * * Returns void * ******************************************************************************/ -void BTA_AvMetaCmd(uint8_t rc_handle, uint8_t label, tBTA_AV_CMD cmd_code, - BT_HDR* p_pkt); +void BTA_AvMetaCmd(uint8_t rc_handle, uint8_t label, tBTA_AV_CMD cmd_code, BT_HDR* p_pkt); /******************************************************************************* * diff --git a/system/bta/include/bta_av_ci.h b/system/bta/include/bta_av_ci.h index 73f16b46ac3..70c8e6c980d 100644 --- a/system/bta/include/bta_av_ci.h +++ b/system/bta/include/bta_av_ci.h @@ -57,8 +57,7 @@ void bta_av_ci_src_data_ready(tBTA_AV_CHNL chnl); * Returns void * ******************************************************************************/ -void bta_av_ci_setconfig(tBTA_AV_HNDL bta_av_handle, uint8_t err_code, - uint8_t category, uint8_t num_seid, uint8_t* p_seid, - bool recfg_needed, uint8_t avdt_handle); +void bta_av_ci_setconfig(tBTA_AV_HNDL bta_av_handle, uint8_t err_code, uint8_t category, + uint8_t num_seid, uint8_t* p_seid, bool recfg_needed, uint8_t avdt_handle); #endif /* BTA_AV_CI_H */ diff --git a/system/bta/include/bta_av_co.h b/system/bta/include/bta_av_co.h index 1ea71578eb4..ccf7f091647 100644 --- a/system/bta/include/bta_av_co.h +++ b/system/bta/include/bta_av_co.h @@ -50,8 +50,7 @@ * Returns Stream codec and content protection capabilities info. * ******************************************************************************/ -bool bta_av_co_audio_init(btav_a2dp_codec_index_t codec_index, - AvdtpSepConfig* p_cfg); +bool bta_av_co_audio_init(btav_a2dp_codec_index_t codec_index, AvdtpSepConfig* p_cfg); /******************************************************************************* * @@ -65,9 +64,8 @@ bool bta_av_co_audio_init(btav_a2dp_codec_index_t codec_index, * Returns void. * ******************************************************************************/ -void bta_av_co_audio_disc_res(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_address, uint8_t num_seps, - uint8_t num_sinks, uint8_t num_sources, +void bta_av_co_audio_disc_res(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, + uint8_t num_seps, uint8_t num_sinks, uint8_t num_sources, uint16_t uuid_local); /******************************************************************************* @@ -82,12 +80,9 @@ void bta_av_co_audio_disc_res(tBTA_AV_HNDL bta_av_handle, * Returns Stream codec and content protection configuration info. * ******************************************************************************/ -tA2DP_STATUS bta_av_co_audio_getconfig(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_address, - uint8_t* p_codec_info, - uint8_t* p_sep_info_idx, uint8_t seid, - uint8_t* p_num_protect, - uint8_t* p_protect_info); +tA2DP_STATUS bta_av_co_audio_getconfig(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, + uint8_t* p_codec_info, uint8_t* p_sep_info_idx, uint8_t seid, + uint8_t* p_num_protect, uint8_t* p_protect_info); /******************************************************************************* * @@ -101,12 +96,10 @@ tA2DP_STATUS bta_av_co_audio_getconfig(tBTA_AV_HNDL bta_av_handle, * Returns void * ******************************************************************************/ -void bta_av_co_audio_setconfig(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_address, - const uint8_t* p_codec_info, uint8_t seid, - uint8_t num_protect, - const uint8_t* p_protect_info, - uint8_t t_local_sep, uint8_t avdt_handle); +void bta_av_co_audio_setconfig(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, + const uint8_t* p_codec_info, uint8_t seid, uint8_t num_protect, + const uint8_t* p_protect_info, uint8_t t_local_sep, + uint8_t avdt_handle); /******************************************************************************* * @@ -121,8 +114,7 @@ void bta_av_co_audio_setconfig(tBTA_AV_HNDL bta_av_handle, * Returns void * ******************************************************************************/ -void bta_av_co_audio_open(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_address, uint16_t mtu); +void bta_av_co_audio_open(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, uint16_t mtu); /******************************************************************************* * @@ -138,8 +130,7 @@ void bta_av_co_audio_open(tBTA_AV_HNDL bta_av_handle, * Returns void * ******************************************************************************/ -void bta_av_co_audio_close(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_address); +void bta_av_co_audio_close(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address); /******************************************************************************* * @@ -152,8 +143,7 @@ void bta_av_co_audio_close(tBTA_AV_HNDL bta_av_handle, * Returns void * ******************************************************************************/ -void bta_av_co_audio_start(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_address, +void bta_av_co_audio_start(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, const uint8_t* p_codec_info, bool* p_no_rtp_header); /******************************************************************************* @@ -167,8 +157,7 @@ void bta_av_co_audio_start(tBTA_AV_HNDL bta_av_handle, * Returns void * ******************************************************************************/ -void bta_av_co_audio_stop(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_address); +void bta_av_co_audio_stop(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address); /******************************************************************************* * @@ -181,8 +170,7 @@ void bta_av_co_audio_stop(tBTA_AV_HNDL bta_av_handle, * Otherwise, a buffer (BT_HDR*) containing the audio data. * ******************************************************************************/ -BT_HDR* bta_av_co_audio_source_data_path(const uint8_t* p_codec_info, - uint32_t* p_timestamp); +BT_HDR* bta_av_co_audio_source_data_path(const uint8_t* p_codec_info, uint32_t* p_timestamp); /******************************************************************************* * @@ -196,8 +184,7 @@ BT_HDR* bta_av_co_audio_source_data_path(const uint8_t* p_codec_info, * Returns void * ******************************************************************************/ -void bta_av_co_audio_drop(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_address); +void bta_av_co_audio_drop(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address); /******************************************************************************* * @@ -211,8 +198,8 @@ void bta_av_co_audio_drop(tBTA_AV_HNDL bta_av_handle, * Returns void * ******************************************************************************/ -void bta_av_co_audio_delay(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_address, uint16_t delay); +void bta_av_co_audio_delay(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, + uint16_t delay); /******************************************************************************* * @@ -227,8 +214,8 @@ void bta_av_co_audio_delay(tBTA_AV_HNDL bta_av_handle, * Returns void * ******************************************************************************/ -void bta_av_co_audio_update_mtu(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_address, uint16_t mtu); +void bta_av_co_audio_update_mtu(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, + uint16_t mtu); /******************************************************************************* ** diff --git a/system/bta/include/bta_csis_api.h b/system/bta/include/bta_csis_api.h index a3b555f954b..db0efbe065f 100644 --- a/system/bta/include/bta_csis_api.h +++ b/system/bta/include/bta_csis_api.h @@ -26,16 +26,13 @@ namespace bluetooth { namespace csis { -using CsisLockCb = base::OnceCallback; +using CsisLockCb = base::OnceCallback; class CsisClient { - public: +public: virtual ~CsisClient() = default; - static void Initialize(bluetooth::csis::CsisClientCallbacks* callbacks, - base::Closure initCb); - static void AddFromStorage(const RawAddress& addr, - const std::vector& in); + static void Initialize(bluetooth::csis::CsisClientCallbacks* callbacks, base::Closure initCb); + static void AddFromStorage(const RawAddress& addr, const std::vector& in); static bool GetForStorage(const RawAddress& addr, std::vector& out); static void CleanUp(); static CsisClient* Get(); @@ -44,9 +41,8 @@ class CsisClient { virtual void Connect(const RawAddress& addr) = 0; virtual void Disconnect(const RawAddress& addr) = 0; virtual void RemoveDevice(const RawAddress& address) = 0; - virtual int GetGroupId( - const RawAddress& addr, - bluetooth::Uuid uuid = bluetooth::groups::kGenericContextUuid) = 0; + virtual int GetGroupId(const RawAddress& addr, + bluetooth::Uuid uuid = bluetooth::groups::kGenericContextUuid) = 0; virtual void LockGroup(int group_id, bool lock, CsisLockCb cb) = 0; virtual std::vector GetDeviceList(int group_id) = 0; virtual int GetDesiredSize(int group_id) const = 0; diff --git a/system/bta/include/bta_dm_acl.h b/system/bta/include/bta_dm_acl.h index 44cf3cf73ba..68af490ce8b 100644 --- a/system/bta/include/bta_dm_acl.h +++ b/system/bta/include/bta_dm_acl.h @@ -23,8 +23,7 @@ #include "types/hci_role.h" #include "types/raw_address.h" -void BTA_dm_acl_up(const RawAddress bd_addr, tBT_TRANSPORT transport, - uint16_t acl_handle); +void BTA_dm_acl_up(const RawAddress bd_addr, tBT_TRANSPORT transport, uint16_t acl_handle); void BTA_dm_acl_up_failed(const RawAddress bd_addr, tBT_TRANSPORT transport, tHCI_STATUS hci_status); void BTA_dm_acl_down(const RawAddress bd_addr, tBT_TRANSPORT transport); diff --git a/system/bta/include/bta_dm_ci.h b/system/bta/include/bta_dm_ci.h index 3989eb061ef..de09d7c9f38 100644 --- a/system/bta/include/bta_dm_ci.h +++ b/system/bta/include/bta_dm_ci.h @@ -44,8 +44,7 @@ * Returns void * ******************************************************************************/ -void bta_dm_ci_rmt_oob(bool accept, const RawAddress& bd_addr, const Octet16& c, - const Octet16& r); +void bta_dm_ci_rmt_oob(bool accept, const RawAddress& bd_addr, const Octet16& c, const Octet16& r); /******************************************************************************* * * Function bta_dm_sco_ci_data_ready diff --git a/system/bta/include/bta_gatt_api.h b/system/bta/include/bta_gatt_api.h index 3d2dcfa72d4..afdde8905f5 100644 --- a/system/bta/include/bta_gatt_api.h +++ b/system/bta/include/bta_gatt_api.h @@ -273,15 +273,13 @@ typedef void(tBTA_GATTC_CBACK)(tBTA_GATTC_EVT event, tBTA_GATTC* p_data); /* GATT Server Data Structure */ /* Server callback function events */ #define BTA_GATTS_REG_EVT 0 -#define BTA_GATTS_READ_CHARACTERISTIC_EVT \ - GATTS_REQ_TYPE_READ_CHARACTERISTIC /* 1 */ -#define BTA_GATTS_READ_DESCRIPTOR_EVT GATTS_REQ_TYPE_READ_DESCRIPTOR /* 2 */ -#define BTA_GATTS_WRITE_CHARACTERISTIC_EVT \ - GATTS_REQ_TYPE_WRITE_CHARACTERISTIC /* 3 */ -#define BTA_GATTS_WRITE_DESCRIPTOR_EVT GATTS_REQ_TYPE_WRITE_DESCRIPTOR /* 4 */ -#define BTA_GATTS_EXEC_WRITE_EVT GATTS_REQ_TYPE_WRITE_EXEC /* 5 */ -#define BTA_GATTS_MTU_EVT GATTS_REQ_TYPE_MTU /* 6 */ -#define BTA_GATTS_CONF_EVT GATTS_REQ_TYPE_CONF /* 7 */ +#define BTA_GATTS_READ_CHARACTERISTIC_EVT GATTS_REQ_TYPE_READ_CHARACTERISTIC /* 1 */ +#define BTA_GATTS_READ_DESCRIPTOR_EVT GATTS_REQ_TYPE_READ_DESCRIPTOR /* 2 */ +#define BTA_GATTS_WRITE_CHARACTERISTIC_EVT GATTS_REQ_TYPE_WRITE_CHARACTERISTIC /* 3 */ +#define BTA_GATTS_WRITE_DESCRIPTOR_EVT GATTS_REQ_TYPE_WRITE_DESCRIPTOR /* 4 */ +#define BTA_GATTS_EXEC_WRITE_EVT GATTS_REQ_TYPE_WRITE_EXEC /* 5 */ +#define BTA_GATTS_MTU_EVT GATTS_REQ_TYPE_MTU /* 6 */ +#define BTA_GATTS_CONF_EVT GATTS_REQ_TYPE_CONF /* 7 */ #define BTA_GATTS_DEREG_EVT 8 #define BTA_GATTS_DELETE_EVT 11 #define BTA_GATTS_STOP_EVT 13 @@ -385,8 +383,8 @@ typedef struct { } tBTA_GATTS_CONGEST; typedef struct { - uint16_t conn_id; /* connection ID */ - tGATT_STATUS status; /* notification/indication status */ + uint16_t conn_id; /* connection ID */ + tGATT_STATUS status; /* notification/indication status */ } tBTA_GATTS_CONF; typedef struct { @@ -423,12 +421,11 @@ typedef union { tBTA_GATTS_SRVC_OPER srvc_oper; tGATT_STATUS status; /* BTA_GATTS_LISTEN_EVT */ tBTA_GATTS_REQ req_data; - tBTA_GATTS_CONN conn; /* BTA_GATTS_CONN_EVT */ - tBTA_GATTS_CONGEST congest; /* BTA_GATTS_CONGEST_EVT callback data */ - tBTA_GATTS_CONF confirm; /* BTA_GATTS_CONF_EVT callback data */ - tBTA_GATTS_PHY_UPDATE phy_update; /* BTA_GATTS_PHY_UPDATE_EVT callback data */ - tBTA_GATTS_CONN_UPDATE - conn_update; /* BTA_GATTS_CONN_UPDATE_EVT callback data */ + tBTA_GATTS_CONN conn; /* BTA_GATTS_CONN_EVT */ + tBTA_GATTS_CONGEST congest; /* BTA_GATTS_CONGEST_EVT callback data */ + tBTA_GATTS_CONF confirm; /* BTA_GATTS_CONF_EVT callback data */ + tBTA_GATTS_PHY_UPDATE phy_update; /* BTA_GATTS_PHY_UPDATE_EVT callback data */ + tBTA_GATTS_CONN_UPDATE conn_update; /* BTA_GATTS_CONN_UPDATE_EVT callback data */ tBTA_GATTS_SUBRATE_CHG subrate_chg; /* BTA_GATTS_SUBRATE_CHG_EVT */ } tBTA_GATTS; @@ -459,16 +456,15 @@ typedef void(tBTA_GATTS_CBACK)(tBTA_GATTS_EVT event, tBTA_GATTS* p_data); ******************************************************************************/ void BTA_GATTC_Disable(void); -using BtaAppRegisterCallback = - base::Callback; +using BtaAppRegisterCallback = base::Callback; /** * This function is called to register application callbacks with BTA GATTC *module. * p_client_cb - pointer to the application callback function. **/ -void BTA_GATTC_AppRegister(tBTA_GATTC_CBACK* p_client_cb, - BtaAppRegisterCallback cb, bool eatt_support); +void BTA_GATTC_AppRegister(tBTA_GATTC_CBACK* p_client_cb, BtaAppRegisterCallback cb, + bool eatt_support); /******************************************************************************* * @@ -500,12 +496,11 @@ void BTA_GATTC_AppDeregister(tGATT_IF client_if); void BTA_GATTC_Open(tGATT_IF client_if, const RawAddress& remote_bda, tBTM_BLE_CONN_TYPE connection_type, bool opportunistic); void BTA_GATTC_Open(tGATT_IF client_if, const RawAddress& remote_bda, - tBTM_BLE_CONN_TYPE connection_type, tBT_TRANSPORT transport, - bool opportunistic, uint8_t initiating_phys); -void BTA_GATTC_Open(tGATT_IF client_if, const RawAddress& remote_bda, - tBLE_ADDR_TYPE addr_type, - tBTM_BLE_CONN_TYPE connection_type, tBT_TRANSPORT transport, - bool opportunistic, uint8_t initiating_phys); + tBTM_BLE_CONN_TYPE connection_type, tBT_TRANSPORT transport, bool opportunistic, + uint8_t initiating_phys); +void BTA_GATTC_Open(tGATT_IF client_if, const RawAddress& remote_bda, tBLE_ADDR_TYPE addr_type, + tBTM_BLE_CONN_TYPE connection_type, tBT_TRANSPORT transport, bool opportunistic, + uint8_t initiating_phys); /******************************************************************************* * @@ -521,8 +516,7 @@ void BTA_GATTC_Open(tGATT_IF client_if, const RawAddress& remote_bda, * Returns void * ******************************************************************************/ -void BTA_GATTC_CancelOpen(tGATT_IF client_if, const RawAddress& remote_bda, - bool is_direct); +void BTA_GATTC_CancelOpen(tGATT_IF client_if, const RawAddress& remote_bda, bool is_direct); /******************************************************************************* * @@ -568,15 +562,13 @@ void BTA_GATTC_ServiceSearchAllRequest(uint16_t conn_id); * Returns None * ******************************************************************************/ -void BTA_GATTC_ServiceSearchRequest(uint16_t conn_id, - bluetooth::Uuid p_srvc_uuid); +void BTA_GATTC_ServiceSearchRequest(uint16_t conn_id, bluetooth::Uuid p_srvc_uuid); /** * This function is called to send "Find service by UUID" request. Used only for * PTS tests. */ -void BTA_GATTC_DiscoverServiceByUuid(uint16_t conn_id, - const bluetooth::Uuid& srvc_uuid); +void BTA_GATTC_DiscoverServiceByUuid(uint16_t conn_id, const bluetooth::Uuid& srvc_uuid); /******************************************************************************* * @@ -605,8 +597,7 @@ const std::list* BTA_GATTC_GetServices(uint16_t conn_id); * Returns returns pointer to gatt::Characteristic or NULL. * ******************************************************************************/ -const gatt::Characteristic* BTA_GATTC_GetCharacteristic(uint16_t conn_id, - uint16_t handle); +const gatt::Characteristic* BTA_GATTC_GetCharacteristic(uint16_t conn_id, uint16_t handle); /******************************************************************************* * @@ -621,18 +612,15 @@ const gatt::Characteristic* BTA_GATTC_GetCharacteristic(uint16_t conn_id, * Returns returns pointer to gatt::Descriptor or NULL. * ******************************************************************************/ -const gatt::Descriptor* BTA_GATTC_GetDescriptor(uint16_t conn_id, - uint16_t handle); +const gatt::Descriptor* BTA_GATTC_GetDescriptor(uint16_t conn_id, uint16_t handle); /* Return characteristic that owns descriptor with handle equal to |handle|, or * NULL */ -const gatt::Characteristic* BTA_GATTC_GetOwningCharacteristic(uint16_t conn_id, - uint16_t handle); +const gatt::Characteristic* BTA_GATTC_GetOwningCharacteristic(uint16_t conn_id, uint16_t handle); /* Return service that owns descriptor or characteristic with handle equal to * |handle|, or NULL */ -const gatt::Service* BTA_GATTC_GetOwningService(uint16_t conn_id, - uint16_t handle); +const gatt::Service* BTA_GATTC_GetOwningService(uint16_t conn_id, uint16_t handle); /******************************************************************************* * @@ -646,21 +634,17 @@ const gatt::Service* BTA_GATTC_GetOwningService(uint16_t conn_id, * count: number of elements in db. * ******************************************************************************/ -void BTA_GATTC_GetGattDb(uint16_t conn_id, uint16_t start_handle, - uint16_t end_handle, btgatt_db_element_t** db, - int* count); - -typedef void (*GATT_READ_OP_CB)(uint16_t conn_id, tGATT_STATUS status, - uint16_t handle, uint16_t len, uint8_t* value, - void* data); -typedef void (*GATT_WRITE_OP_CB)(uint16_t conn_id, tGATT_STATUS status, - uint16_t handle, uint16_t len, - const uint8_t* value, void* data); -typedef void (*GATT_CONFIGURE_MTU_OP_CB)(uint16_t conn_id, tGATT_STATUS status, - void* data); +void BTA_GATTC_GetGattDb(uint16_t conn_id, uint16_t start_handle, uint16_t end_handle, + btgatt_db_element_t** db, int* count); + +typedef void (*GATT_READ_OP_CB)(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, + uint16_t len, uint8_t* value, void* data); +typedef void (*GATT_WRITE_OP_CB)(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, + uint16_t len, const uint8_t* value, void* data); +typedef void (*GATT_CONFIGURE_MTU_OP_CB)(uint16_t conn_id, tGATT_STATUS status, void* data); typedef void (*GATT_READ_MULTI_OP_CB)(uint16_t conn_id, tGATT_STATUS status, - tBTA_GATTC_MULTI& handles, uint16_t len, - uint8_t* value, void* data); + tBTA_GATTC_MULTI& handles, uint16_t len, uint8_t* value, + void* data); /******************************************************************************* * * Function BTA_GATTC_ReadCharacteristic @@ -673,17 +657,15 @@ typedef void (*GATT_READ_MULTI_OP_CB)(uint16_t conn_id, tGATT_STATUS status, * Returns None * ******************************************************************************/ -void BTA_GATTC_ReadCharacteristic(uint16_t conn_id, uint16_t handle, - tGATT_AUTH_REQ auth_req, +void BTA_GATTC_ReadCharacteristic(uint16_t conn_id, uint16_t handle, tGATT_AUTH_REQ auth_req, GATT_READ_OP_CB callback, void* cb_data); /** * This function is called to read a value of characteristic with uuid equal to * |uuid| */ -void BTA_GATTC_ReadUsingCharUuid(uint16_t conn_id, const bluetooth::Uuid& uuid, - uint16_t s_handle, uint16_t e_handle, - tGATT_AUTH_REQ auth_req, +void BTA_GATTC_ReadUsingCharUuid(uint16_t conn_id, const bluetooth::Uuid& uuid, uint16_t s_handle, + uint16_t e_handle, tGATT_AUTH_REQ auth_req, GATT_READ_OP_CB callback, void* cb_data); /******************************************************************************* @@ -698,9 +680,8 @@ void BTA_GATTC_ReadUsingCharUuid(uint16_t conn_id, const bluetooth::Uuid& uuid, * Returns None * ******************************************************************************/ -void BTA_GATTC_ReadCharDescr(uint16_t conn_id, uint16_t handle, - tGATT_AUTH_REQ auth_req, GATT_READ_OP_CB callback, - void* cb_data); +void BTA_GATTC_ReadCharDescr(uint16_t conn_id, uint16_t handle, tGATT_AUTH_REQ auth_req, + GATT_READ_OP_CB callback, void* cb_data); /******************************************************************************* * @@ -716,10 +697,8 @@ void BTA_GATTC_ReadCharDescr(uint16_t conn_id, uint16_t handle, * Returns None * ******************************************************************************/ -void BTA_GATTC_WriteCharValue(uint16_t conn_id, uint16_t handle, - tGATT_WRITE_TYPE write_type, - std::vector value, - tGATT_AUTH_REQ auth_req, +void BTA_GATTC_WriteCharValue(uint16_t conn_id, uint16_t handle, tGATT_WRITE_TYPE write_type, + std::vector value, tGATT_AUTH_REQ auth_req, GATT_WRITE_OP_CB callback, void* cb_data); /******************************************************************************* @@ -735,10 +714,8 @@ void BTA_GATTC_WriteCharValue(uint16_t conn_id, uint16_t handle, * Returns None * ******************************************************************************/ -void BTA_GATTC_WriteCharDescr(uint16_t conn_id, uint16_t handle, - std::vector value, - tGATT_AUTH_REQ auth_req, - GATT_WRITE_OP_CB callback, void* cb_data); +void BTA_GATTC_WriteCharDescr(uint16_t conn_id, uint16_t handle, std::vector value, + tGATT_AUTH_REQ auth_req, GATT_WRITE_OP_CB callback, void* cb_data); /******************************************************************************* * @@ -768,8 +745,7 @@ void BTA_GATTC_SendIndConfirm(uint16_t conn_id, uint16_t cid); * Returns OK if registration succeed, otherwise failed. * ******************************************************************************/ -tGATT_STATUS BTA_GATTC_RegisterForNotifications(tGATT_IF client_if, - const RawAddress& remote_bda, +tGATT_STATUS BTA_GATTC_RegisterForNotifications(tGATT_IF client_if, const RawAddress& remote_bda, uint16_t handle); /******************************************************************************* @@ -786,8 +762,7 @@ tGATT_STATUS BTA_GATTC_RegisterForNotifications(tGATT_IF client_if, * Returns OK if deregistration succeed, otherwise failed. * ******************************************************************************/ -tGATT_STATUS BTA_GATTC_DeregisterForNotifications(tGATT_IF client_if, - const RawAddress& remote_bda, +tGATT_STATUS BTA_GATTC_DeregisterForNotifications(tGATT_IF client_if, const RawAddress& remote_bda, uint16_t handle); /******************************************************************************* @@ -839,9 +814,8 @@ void BTA_GATTC_ExecuteWrite(uint16_t conn_id, bool is_execute); * Returns None * ******************************************************************************/ -void BTA_GATTC_ReadMultiple(uint16_t conn_id, tBTA_GATTC_MULTI& p_read_multi, - bool variable_len, tGATT_AUTH_REQ auth_req, - GATT_READ_MULTI_OP_CB callback, void* cb_data); +void BTA_GATTC_ReadMultiple(uint16_t conn_id, tBTA_GATTC_MULTI& p_read_multi, bool variable_len, + tGATT_AUTH_REQ auth_req, GATT_READ_MULTI_OP_CB callback, void* cb_data); /******************************************************************************* * @@ -870,8 +844,8 @@ void BTA_GATTC_Refresh(const RawAddress& remote_bda); * ******************************************************************************/ void BTA_GATTC_ConfigureMTU(uint16_t conn_id, uint16_t mtu); -void BTA_GATTC_ConfigureMTU(uint16_t conn_id, uint16_t mtu, - GATT_CONFIGURE_MTU_OP_CB callback, void* cb_data); +void BTA_GATTC_ConfigureMTU(uint16_t conn_id, uint16_t mtu, GATT_CONFIGURE_MTU_OP_CB callback, + void* cb_data); /******************************************************************************* * BTA GATT Server API @@ -881,7 +855,7 @@ void BTA_GATTC_ConfigureMTU(uint16_t conn_id, uint16_t mtu, * * Function BTA_GATTS_Init * - * Description This function is called to initalize GATTS module + * Description This function is called to initialize GATTS module * * Parameters None * @@ -910,15 +884,15 @@ void BTA_GATTS_Disable(void); * Description This function is called to register application callbacks * with BTA GATTS module. * - * Parameters p_app_uuid - applicaiton UUID + * Parameters p_app_uuid - application UUID * p_cback - pointer to the application callback function. * eatt_support: indicate eatt support. * * Returns None * ******************************************************************************/ -void BTA_GATTS_AppRegister(const bluetooth::Uuid& app_uuid, - tBTA_GATTS_CBACK* p_cback, bool eatt_support); +void BTA_GATTS_AppRegister(const bluetooth::Uuid& app_uuid, tBTA_GATTS_CBACK* p_cback, + bool eatt_support); /******************************************************************************* * @@ -950,10 +924,9 @@ void BTA_GATTS_AppDeregister(tGATT_IF server_if); ******************************************************************************/ typedef base::Callback service)> - BTA_GATTS_AddServiceCb; + BTA_GATTS_AddServiceCb; -void BTA_GATTS_AddService(tGATT_IF server_if, - std::vector service, +void BTA_GATTS_AddService(tGATT_IF server_if, std::vector service, BTA_GATTS_AddServiceCb cb); /******************************************************************************* @@ -1000,8 +973,7 @@ void BTA_GATTS_StopService(uint16_t service_id); * Returns None * ******************************************************************************/ -void BTA_GATTS_HandleValueIndication(uint16_t conn_id, uint16_t attr_id, - std::vector value, +void BTA_GATTS_HandleValueIndication(uint16_t conn_id, uint16_t attr_id, std::vector value, bool need_confirm); /******************************************************************************* @@ -1018,8 +990,7 @@ void BTA_GATTS_HandleValueIndication(uint16_t conn_id, uint16_t attr_id, * Returns None * ******************************************************************************/ -void BTA_GATTS_SendRsp(uint16_t conn_id, uint32_t trans_id, tGATT_STATUS status, - tGATTS_RSP* p_msg); +void BTA_GATTS_SendRsp(uint16_t conn_id, uint32_t trans_id, tGATT_STATUS status, tGATTS_RSP* p_msg); /******************************************************************************* * @@ -1037,9 +1008,8 @@ void BTA_GATTS_SendRsp(uint16_t conn_id, uint32_t trans_id, tGATT_STATUS status, * Returns void * ******************************************************************************/ -void BTA_GATTS_Open(tGATT_IF server_if, const RawAddress& remote_bda, - tBLE_ADDR_TYPE addr_type, bool is_direct, - tBT_TRANSPORT transport); +void BTA_GATTS_Open(tGATT_IF server_if, const RawAddress& remote_bda, tBLE_ADDR_TYPE addr_type, + bool is_direct, tBT_TRANSPORT transport); /******************************************************************************* * @@ -1055,8 +1025,7 @@ void BTA_GATTS_Open(tGATT_IF server_if, const RawAddress& remote_bda, * Returns void * ******************************************************************************/ -void BTA_GATTS_CancelOpen(tGATT_IF server_if, const RawAddress& remote_bda, - bool is_direct); +void BTA_GATTS_CancelOpen(tGATT_IF server_if, const RawAddress& remote_bda, bool is_direct); /******************************************************************************* * diff --git a/system/bta/include/bta_gatt_queue.h b/system/bta/include/bta_gatt_queue.h index bf6a52ef661..c694cecee85 100644 --- a/system/bta/include/bta_gatt_queue.h +++ b/system/bta/include/bta_gatt_queue.h @@ -34,25 +34,18 @@ * existing BTA_GATTC_* API. */ class BtaGattQueue { - public: +public: static void Clean(uint16_t conn_id); - static void ReadCharacteristic(uint16_t conn_id, uint16_t handle, - GATT_READ_OP_CB cb, void* cb_data); - static void ReadDescriptor(uint16_t conn_id, uint16_t handle, - GATT_READ_OP_CB cb, void* cb_data); - static void WriteCharacteristic(uint16_t conn_id, uint16_t handle, - std::vector value, - tGATT_WRITE_TYPE write_type, - GATT_WRITE_OP_CB cb, void* cb_data); - static void WriteDescriptor(uint16_t conn_id, uint16_t handle, - std::vector value, - tGATT_WRITE_TYPE write_type, GATT_WRITE_OP_CB cb, - void* cb_data); + static void ReadCharacteristic(uint16_t conn_id, uint16_t handle, GATT_READ_OP_CB cb, + void* cb_data); + static void ReadDescriptor(uint16_t conn_id, uint16_t handle, GATT_READ_OP_CB cb, void* cb_data); + static void WriteCharacteristic(uint16_t conn_id, uint16_t handle, std::vector value, + tGATT_WRITE_TYPE write_type, GATT_WRITE_OP_CB cb, void* cb_data); + static void WriteDescriptor(uint16_t conn_id, uint16_t handle, std::vector value, + tGATT_WRITE_TYPE write_type, GATT_WRITE_OP_CB cb, void* cb_data); static void ConfigureMtu(uint16_t conn_id, uint16_t mtu); - static void ReadMultiCharacteristic(uint16_t conn_id, - tBTA_GATTC_MULTI& p_read_multi, - bool variable_len, - GATT_READ_MULTI_OP_CB cb, void* cb_data); + static void ReadMultiCharacteristic(uint16_t conn_id, tBTA_GATTC_MULTI& p_read_multi, + bool variable_len, GATT_READ_MULTI_OP_CB cb, void* cb_data); /* Holds pending GATT operations */ struct gatt_operation { @@ -73,20 +66,16 @@ class BtaGattQueue { std::vector value; }; - private: +private: static void mark_as_not_executing(uint16_t conn_id); static void gatt_execute_next_op(uint16_t conn_id); - static void gatt_read_op_finished(uint16_t conn_id, tGATT_STATUS status, - uint16_t handle, uint16_t len, - uint8_t* value, void* data); - static void gatt_write_op_finished(uint16_t conn_id, tGATT_STATUS status, - uint16_t handle, uint16_t len, - const uint8_t* value, void* data); - static void gatt_configure_mtu_op_finished(uint16_t conn_id, - tGATT_STATUS status, void* data); + static void gatt_read_op_finished(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, + uint16_t len, uint8_t* value, void* data); + static void gatt_write_op_finished(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, + uint16_t len, const uint8_t* value, void* data); + static void gatt_configure_mtu_op_finished(uint16_t conn_id, tGATT_STATUS status, void* data); static void gatt_read_multi_op_finished(uint16_t conn_id, tGATT_STATUS status, - tBTA_GATTC_MULTI& handle, - uint16_t len, uint8_t* value, + tBTA_GATTC_MULTI& handle, uint16_t len, uint8_t* value, void* data); // maps connection id to operations waiting for execution static std::unordered_map> gatt_op_queue; diff --git a/system/bta/include/bta_gatt_server_queue.h b/system/bta/include/bta_gatt_server_queue.h index a8bb4b4442e..91909a4085f 100644 --- a/system/bta/include/bta_gatt_server_queue.h +++ b/system/bta/include/bta_gatt_server_queue.h @@ -22,10 +22,10 @@ #include "bta_gatt_api.h" class BtaGattServerQueue { - public: +public: static void Clean(uint16_t conn_id); - static void SendNotification(uint16_t conn_id, uint16_t handle, - std::vector value, bool need_confirm); + static void SendNotification(uint16_t conn_id, uint16_t handle, std::vector value, + bool need_confirm); static void NotificationCallback(uint16_t conn_id); static void CongestionCallback(uint16_t conn_id, bool congested); @@ -37,14 +37,13 @@ class BtaGattServerQueue { bool need_confirm; }; - private: +private: static bool is_congested; static void mark_as_not_executing(uint16_t conn_id); static void gatts_execute_next_op(uint16_t conn_id); // maps connection id to operations waiting for execution - static std::unordered_map> - gatts_op_queue; + static std::unordered_map> gatts_op_queue; // maps connection id to congestion status of each device static std::unordered_map congestion_queue; diff --git a/system/bta/include/bta_groups.h b/system/bta/include/bta_groups.h index 8e63a365b05..c212f20f0d5 100644 --- a/system/bta/include/bta_groups.h +++ b/system/bta/include/bta_groups.h @@ -26,43 +26,37 @@ namespace bluetooth { namespace groups { static constexpr int kGroupUnknown = -1; -static const bluetooth::Uuid kGenericContextUuid = - bluetooth::Uuid::From16Bit(0x0000); +static const bluetooth::Uuid kGenericContextUuid = bluetooth::Uuid::From16Bit(0x0000); class DeviceGroupsCallbacks { - public: +public: virtual ~DeviceGroupsCallbacks() = default; /* Notifies first group appearance. * This callback also contains first group member and uuid of the group. */ - virtual void OnGroupAdded(const RawAddress& address, - const bluetooth::Uuid& group_uuid, + virtual void OnGroupAdded(const RawAddress& address, const bluetooth::Uuid& group_uuid, int group_id) = 0; /* Followed group members are notified with this callback */ virtual void OnGroupMemberAdded(const RawAddress& address, int group_id) = 0; /* Group removal callback */ - virtual void OnGroupRemoved(const bluetooth::Uuid& group_uuid, - int group_id) = 0; + virtual void OnGroupRemoved(const bluetooth::Uuid& group_uuid, int group_id) = 0; /* Callback with group status update */ - virtual void OnGroupMemberRemoved(const RawAddress& address, - int group_id) = 0; + virtual void OnGroupMemberRemoved(const RawAddress& address, int group_id) = 0; /* Callback with group information added from storage */ - virtual void OnGroupAddFromStorage(const RawAddress& address, - const bluetooth::Uuid& group_uuid, + virtual void OnGroupAddFromStorage(const RawAddress& address, const bluetooth::Uuid& group_uuid, int group_id) = 0; }; class DeviceGroups { - public: +public: virtual ~DeviceGroups() = default; static void Initialize(DeviceGroupsCallbacks* callbacks); - static void AddFromStorage(const RawAddress& addr, - const std::vector& in); + static void AddFromStorage(const RawAddress& addr, const std::vector& in); static bool GetForStorage(const RawAddress& addr, std::vector& out); static void CleanUp(DeviceGroupsCallbacks* callbacks); static DeviceGroups* Get(); @@ -70,16 +64,13 @@ class DeviceGroups { /** To add to the existing group, group_id needs to be provided. * Otherwise a new group for the given context uuid will be created. */ - virtual int AddDevice( - const RawAddress& addr, - bluetooth::Uuid uuid = bluetooth::groups::kGenericContextUuid, - int group_id = bluetooth::groups::kGroupUnknown) = 0; - virtual int GetGroupId( - const RawAddress& addr, - bluetooth::Uuid uuid = bluetooth::groups::kGenericContextUuid) const = 0; - virtual void RemoveDevice( - const RawAddress& addr, - int group_id = bluetooth::groups::kGroupUnknown) = 0; + virtual int AddDevice(const RawAddress& addr, + bluetooth::Uuid uuid = bluetooth::groups::kGenericContextUuid, + int group_id = bluetooth::groups::kGroupUnknown) = 0; + virtual int GetGroupId(const RawAddress& addr, + bluetooth::Uuid uuid = bluetooth::groups::kGenericContextUuid) const = 0; + virtual void RemoveDevice(const RawAddress& addr, + int group_id = bluetooth::groups::kGroupUnknown) = 0; }; } // namespace groups diff --git a/system/bta/include/bta_has_api.h b/system/bta/include/bta_has_api.h index be3f7ca16bc..4abf10d6dce 100644 --- a/system/bta/include/bta_has_api.h +++ b/system/bta/include/bta_has_api.h @@ -26,28 +26,24 @@ namespace bluetooth::le_audio { namespace has { class HasClient { - public: +public: virtual ~HasClient() = default; - static void Initialize(bluetooth::has::HasClientCallbacks* callbacks, - base::Closure initCb); + static void Initialize(bluetooth::has::HasClientCallbacks* callbacks, base::Closure initCb); static void CleanUp(); static HasClient* Get(); static void DebugDump(int fd); static bool IsHasClientRunning(); - static void AddFromStorage(const RawAddress& addr, uint8_t features, - uint16_t is_acceptlisted); + static void AddFromStorage(const RawAddress& addr, uint8_t features, uint16_t is_acceptlisted); virtual void Connect(const RawAddress& addr) = 0; virtual void Disconnect(const RawAddress& addr) = 0; - virtual void SelectActivePreset( - std::variant addr_or_group_id, uint8_t preset_index) = 0; - virtual void NextActivePreset( - std::variant addr_or_group_id) = 0; - virtual void PreviousActivePreset( - std::variant addr_or_group_id) = 0; + virtual void SelectActivePreset(std::variant addr_or_group_id, + uint8_t preset_index) = 0; + virtual void NextActivePreset(std::variant addr_or_group_id) = 0; + virtual void PreviousActivePreset(std::variant addr_or_group_id) = 0; virtual void GetPresetInfo(const RawAddress& addr, uint8_t preset_index) = 0; - virtual void SetPresetName(std::variant addr_or_group_id, - uint8_t preset_index, std::string name) = 0; + virtual void SetPresetName(std::variant addr_or_group_id, uint8_t preset_index, + std::string name) = 0; }; } // namespace has diff --git a/system/bta/include/bta_hd_api.h b/system/bta/include/bta_hd_api.h index 00bd75783dd..f2ce71312f0 100644 --- a/system/bta/include/bta_hd_api.h +++ b/system/bta/include/bta_hd_api.h @@ -165,7 +165,7 @@ void BTA_HdDisable(void); * Function BTA_HdRegisterApp * * Description This function is called when application should be -*registered + *registered * * Returns void * @@ -178,7 +178,7 @@ void BTA_HdRegisterApp(tBTA_HD_APP_INFO* p_app_info, tBTA_HD_QOS_INFO* p_in_qos, * Function BTA_HdUnregisterApp * * Description This function is called when application should be -*unregistered + *unregistered * * Returns void * diff --git a/system/bta/include/bta_hearing_aid_api.h b/system/bta/include/bta_hearing_aid_api.h index 6f0541ac04e..3cd34612712 100644 --- a/system/bta/include/bta_hearing_aid_api.h +++ b/system/bta/include/bta_hearing_aid_api.h @@ -44,7 +44,7 @@ const static uint8_t kPhyUpdateRetryLimit = 5; /** Implementations of HearingAid will also implement this interface */ class HearingAidAudioReceiver { - public: +public: virtual ~HearingAidAudioReceiver() = default; virtual void OnAudioDataReady(const std::vector& data) = 0; @@ -53,16 +53,14 @@ class HearingAidAudioReceiver { // // @param stop_audio_ticks a callable function calls out to stop the media // timer for reading data. - virtual void OnAudioSuspend( - const std::function& stop_audio_ticks) = 0; + virtual void OnAudioSuspend(const std::function& stop_audio_ticks) = 0; // To notify hearing aid devices to be ready for streaming, and start the // media timer to feed the audio data. // // @param start_audio_ticks a callable function calls out to start a periodic // timer for feeding data from the audio HAL. - virtual void OnAudioResume( - const std::function& start_audio_ticks) = 0; + virtual void OnAudioResume(const std::function& start_audio_ticks) = 0; }; // Number of rssi reads to attempt when requested @@ -231,7 +229,7 @@ struct HearingDevice { }; class HearingAid { - public: +public: virtual ~HearingAid() = default; static void Initialize(bluetooth::hearing_aid::HearingAidCallbacks* callbacks, @@ -240,8 +238,7 @@ class HearingAid { static bool IsHearingAidRunning(); static void DebugDump(int fd); - static void AddFromStorage(const HearingDevice& dev_info, - bool is_acceptlisted); + static void AddFromStorage(const HearingDevice& dev_info, bool is_acceptlisted); static int GetDeviceCount(); @@ -275,10 +272,9 @@ struct CodecConfiguration { /** Represents source of audio for hearing aids */ class HearingAidAudioSource { - public: +public: static void Start(const CodecConfiguration& codecConfiguration, - HearingAidAudioReceiver* audioReceiver, - uint16_t remote_delay_ms); + HearingAidAudioReceiver* audioReceiver, uint16_t remote_delay_ms); static void Stop(); static void Initialize(); static void CleanUp(); @@ -287,6 +283,5 @@ class HearingAidAudioSource { namespace fmt { template <> -struct formatter - : enum_formatter {}; +struct formatter : enum_formatter {}; } // namespace fmt diff --git a/system/bta/include/bta_hf_client_api.h b/system/bta/include/bta_hf_client_api.h index 035a128786c..5c3c436fcef 100644 --- a/system/bta/include/bta_hf_client_api.h +++ b/system/bta/include/bta_hf_client_api.h @@ -37,35 +37,29 @@ /* HFP peer (AG) features*/ #define BTA_HF_CLIENT_PEER_FEAT_3WAY 0x00000001 /* Three-way calling */ -#define BTA_HF_CLIENT_PEER_FEAT_ECNR \ - 0x00000002 /* Echo cancellation and/or noise reduction */ +#define BTA_HF_CLIENT_PEER_FEAT_ECNR 0x00000002 /* Echo cancellation and/or noise reduction */ #define BTA_HF_CLIENT_PEER_FEAT_VREC 0x00000004 /* Voice recognition */ #define BTA_HF_CLIENT_PEER_INBAND 0x00000008 /* In-band ring tone */ -#define BTA_HF_CLIENT_PEER_VTAG \ - 0x00000010 /* Attach a phone number to a voice tag */ -#define BTA_HF_CLIENT_PEER_REJECT \ - 0x00000020 /* Ability to reject incoming call */ -#define BTA_HF_CLIENT_PEER_ECS 0x00000040 /* Enhanced Call Status */ -#define BTA_HF_CLIENT_PEER_ECC 0x00000080 /* Enhanced Call Control */ -#define BTA_HF_CLIENT_PEER_EXTERR 0x00000100 /* Extended error codes */ -#define BTA_HF_CLIENT_PEER_CODEC 0x00000200 /* Codec Negotiation */ -#define BTA_HF_CLIENT_PEER_HF_IND 0x00000400 /* HF Indicators */ -#define BTA_HF_CLIENT_PEER_ESCO_S4 0x00000800 /* ESCO S4 link setting */ +#define BTA_HF_CLIENT_PEER_VTAG 0x00000010 /* Attach a phone number to a voice tag */ +#define BTA_HF_CLIENT_PEER_REJECT 0x00000020 /* Ability to reject incoming call */ +#define BTA_HF_CLIENT_PEER_ECS 0x00000040 /* Enhanced Call Status */ +#define BTA_HF_CLIENT_PEER_ECC 0x00000080 /* Enhanced Call Control */ +#define BTA_HF_CLIENT_PEER_EXTERR 0x00000100 /* Extended error codes */ +#define BTA_HF_CLIENT_PEER_CODEC 0x00000200 /* Codec Negotiation */ +#define BTA_HF_CLIENT_PEER_HF_IND 0x00000400 /* HF Indicators */ +#define BTA_HF_CLIENT_PEER_ESCO_S4 0x00000800 /* ESCO S4 link setting */ typedef uint16_t tBTA_HF_CLIENT_PEER_FEAT; /* HFP HF features */ -#define BTA_HF_CLIENT_FEAT_ECNR \ - 0x00000001 /* Echo cancellation and/or noise reduction */ -#define BTA_HF_CLIENT_FEAT_3WAY \ - 0x00000002 /* Call waiting and three-way calling */ -#define BTA_HF_CLIENT_FEAT_CLI \ - 0x00000004 /* Caller ID presentation capability */ -#define BTA_HF_CLIENT_FEAT_VREC 0x00000008 /* Voice recognition activation */ -#define BTA_HF_CLIENT_FEAT_VOL 0x00000010 /* Remote volume control */ -#define BTA_HF_CLIENT_FEAT_ECS 0x00000020 /* Enhanced Call Status */ -#define BTA_HF_CLIENT_FEAT_ECC 0x00000040 /* Enhanced Call Control */ -#define BTA_HF_CLIENT_FEAT_CODEC 0x00000080 /* Codec Negotiation */ +#define BTA_HF_CLIENT_FEAT_ECNR 0x00000001 /* Echo cancellation and/or noise reduction */ +#define BTA_HF_CLIENT_FEAT_3WAY 0x00000002 /* Call waiting and three-way calling */ +#define BTA_HF_CLIENT_FEAT_CLI 0x00000004 /* Caller ID presentation capability */ +#define BTA_HF_CLIENT_FEAT_VREC 0x00000008 /* Voice recognition activation */ +#define BTA_HF_CLIENT_FEAT_VOL 0x00000010 /* Remote volume control */ +#define BTA_HF_CLIENT_FEAT_ECS 0x00000020 /* Enhanced Call Status */ +#define BTA_HF_CLIENT_FEAT_ECC 0x00000040 /* Enhanced Call Control */ +#define BTA_HF_CLIENT_FEAT_CODEC 0x00000080 /* Codec Negotiation */ #define BTA_HF_CLIENT_FEAT_HF_IND 0x00000100 /* HF Indicators */ #define BTA_HF_CLIENT_FEAT_ESCO_S4 0x00000200 /* ESCO S4 link setting */ #define BTA_HF_CLIENT_FEAT_SWB 0x00000400 /* SWB feature (HFP 1.9) */ @@ -75,21 +69,17 @@ typedef uint16_t tBTA_HF_CLIENT_PEER_FEAT; #define BTA_HF_CLIENT_FEAT_SWB_SUPPORT 0x0100 /* Supports SWB */ /* HFP HF extended call handling - masks not related to any spec */ -#define BTA_HF_CLIENT_CHLD_REL \ - 0x00000001 /* 0 Release waiting call or held calls */ +#define BTA_HF_CLIENT_CHLD_REL 0x00000001 /* 0 Release waiting call or held calls */ #define BTA_HF_CLIENT_CHLD_REL_ACC \ 0x00000002 /* 1 Release active calls and accept other (waiting or held) cal \ - */ -#define BTA_HF_CLIENT_CHLD_REL_X 0x00000004 /* 1x Release x call*/ -#define BTA_HF_CLIENT_CHLD_HOLD_ACC \ - 0x00000008 /* 2 Active calls on hold and accept other call */ -#define BTA_HF_CLIENT_CHLD_PRIV_X \ - 0x00000010 /* 2x Active multiparty call on hold except call x */ -#define BTA_HF_CLIENT_CHLD_MERGE \ - 0x00000020 /* 3 Add held call to multiparty \ - */ -#define BTA_HF_CLIENT_CHLD_MERGE_DETACH \ - 0x00000040 /* 4 Add held call to multiparty */ + */ +#define BTA_HF_CLIENT_CHLD_REL_X 0x00000004 /* 1x Release x call*/ +#define BTA_HF_CLIENT_CHLD_HOLD_ACC 0x00000008 /* 2 Active calls on hold and accept other call */ +#define BTA_HF_CLIENT_CHLD_PRIV_X 0x00000010 /* 2x Active multiparty call on hold except call x */ +#define BTA_HF_CLIENT_CHLD_MERGE \ + 0x00000020 /* 3 Add held call to multiparty \ + */ +#define BTA_HF_CLIENT_CHLD_MERGE_DETACH 0x00000040 /* 4 Add held call to multiparty */ typedef uint16_t tBTA_HF_CLIENT_CHLD_FEAT; @@ -106,37 +96,34 @@ typedef uint16_t tBTA_HF_CLIENT_CHLD_FEAT; typedef uint8_t tBTA_HF_CLIENT_AT_RESULT_TYPE; /* HF Client callback events */ -#define BTA_HF_CLIENT_ENABLE_EVT 0 /* HF Client enabled */ -#define BTA_HF_CLIENT_REGISTER_EVT 1 /* HF Client registered */ -#define BTA_HF_CLIENT_OPEN_EVT 2 /* HF Client connection open */ -#define BTA_HF_CLIENT_CLOSE_EVT 3 /* HF Client connection closed */ -#define BTA_HF_CLIENT_CONN_EVT 4 /* Service level connection opened */ -#define BTA_HF_CLIENT_AUDIO_OPEN_EVT 5 /* Audio connection open */ -#define BTA_HF_CLIENT_AUDIO_MSBC_OPEN_EVT \ - 6 /* Audio connection with mSBC codec open */ -#define BTA_HF_CLIENT_AUDIO_CLOSE_EVT 7 /* Audio connection closed */ -#define BTA_HF_CLIENT_SPK_EVT 8 /* Speaker volume changed */ -#define BTA_HF_CLIENT_MIC_EVT 9 /* Microphone volume changed */ -#define BTA_HF_CLIENT_IND_EVT 10 /* Indicator */ -#define BTA_HF_CLIENT_VOICE_REC_EVT \ - 11 /* AG changed voice recognition setting */ -#define BTA_HF_CLIENT_OPERATOR_NAME_EVT 12 /* Operator name acquired */ -#define BTA_HF_CLIENT_CLIP_EVT 13 /* Calling line identification event */ -#define BTA_HF_CLIENT_CCWA_EVT 14 /* Call waiting notification */ -#define BTA_HF_CLIENT_AT_RESULT_EVT 15 /* Call waiting notification */ -#define BTA_HF_CLIENT_CLCC_EVT 16 /* current call event */ -#define BTA_HF_CLIENT_CNUM_EVT 17 /* subscriber information event */ -#define BTA_HF_CLIENT_BTRH_EVT 18 /* bluetooth response and hold event */ -#define BTA_HF_CLIENT_BSIR_EVT \ - 19 /* in-band ring tone setting changed event \ - */ -#define BTA_HF_CLIENT_BINP_EVT 20 /* binp number event */ +#define BTA_HF_CLIENT_ENABLE_EVT 0 /* HF Client enabled */ +#define BTA_HF_CLIENT_REGISTER_EVT 1 /* HF Client registered */ +#define BTA_HF_CLIENT_OPEN_EVT 2 /* HF Client connection open */ +#define BTA_HF_CLIENT_CLOSE_EVT 3 /* HF Client connection closed */ +#define BTA_HF_CLIENT_CONN_EVT 4 /* Service level connection opened */ +#define BTA_HF_CLIENT_AUDIO_OPEN_EVT 5 /* Audio connection open */ +#define BTA_HF_CLIENT_AUDIO_MSBC_OPEN_EVT 6 /* Audio connection with mSBC codec open */ +#define BTA_HF_CLIENT_AUDIO_CLOSE_EVT 7 /* Audio connection closed */ +#define BTA_HF_CLIENT_SPK_EVT 8 /* Speaker volume changed */ +#define BTA_HF_CLIENT_MIC_EVT 9 /* Microphone volume changed */ +#define BTA_HF_CLIENT_IND_EVT 10 /* Indicator */ +#define BTA_HF_CLIENT_VOICE_REC_EVT 11 /* AG changed voice recognition setting */ +#define BTA_HF_CLIENT_OPERATOR_NAME_EVT 12 /* Operator name acquired */ +#define BTA_HF_CLIENT_CLIP_EVT 13 /* Calling line identification event */ +#define BTA_HF_CLIENT_CCWA_EVT 14 /* Call waiting notification */ +#define BTA_HF_CLIENT_AT_RESULT_EVT 15 /* Call waiting notification */ +#define BTA_HF_CLIENT_CLCC_EVT 16 /* current call event */ +#define BTA_HF_CLIENT_CNUM_EVT 17 /* subscriber information event */ +#define BTA_HF_CLIENT_BTRH_EVT 18 /* bluetooth response and hold event */ +#define BTA_HF_CLIENT_BSIR_EVT \ + 19 /* in-band ring tone setting changed event \ + */ +#define BTA_HF_CLIENT_BINP_EVT 20 /* binp number event */ #define BTA_HF_CLIENT_RING_INDICATION 21 /* HF Client ring indication */ -#define BTA_HF_CLIENT_UNKNOWN_EVT 22 /* Unknown or vendor specific Event */ -#define BTA_HF_CLIENT_AUDIO_LC3_OPEN_EVT \ - 23 /* Audio connection with LC3 codec open */ -#define BTA_HF_CLIENT_DISABLE_EVT 30 /* HF Client disabled */ +#define BTA_HF_CLIENT_UNKNOWN_EVT 22 /* Unknown or vendor specific Event */ +#define BTA_HF_CLIENT_AUDIO_LC3_OPEN_EVT 23 /* Audio connection with LC3 codec open */ +#define BTA_HF_CLIENT_DISABLE_EVT 30 /* HF Client disabled */ typedef uint8_t tBTA_HF_CLIENT_EVT; @@ -281,8 +268,7 @@ typedef union { typedef uint32_t tBTA_HF_CLIENT_FEAT; /* HF Client callback */ -typedef void(tBTA_HF_CLIENT_CBACK)(tBTA_HF_CLIENT_EVT event, - tBTA_HF_CLIENT* p_data); +typedef void(tBTA_HF_CLIENT_CBACK)(tBTA_HF_CLIENT_EVT event, tBTA_HF_CLIENT* p_data); /***************************************************************************** * External Function Declarations @@ -301,8 +287,7 @@ typedef void(tBTA_HF_CLIENT_CBACK)(tBTA_HF_CLIENT_EVT event, * Returns BTA_SUCCESS if OK, BTA_FAILURE otherwise. * ******************************************************************************/ -tBTA_STATUS BTA_HfClientEnable(tBTA_HF_CLIENT_CBACK* p_cback, - tBTA_HF_CLIENT_FEAT features, +tBTA_STATUS BTA_HfClientEnable(tBTA_HF_CLIENT_CBACK* p_cback, tBTA_HF_CLIENT_FEAT features, const char* p_service_name); /******************************************************************************* @@ -382,8 +367,8 @@ void BTA_HfClientAudioClose(uint16_t handle); * Returns void * ******************************************************************************/ -void BTA_HfClientSendAT(uint16_t handle, tBTA_HF_CLIENT_AT_CMD_TYPE at, - uint32_t val1, uint32_t val2, const char* str); +void BTA_HfClientSendAT(uint16_t handle, tBTA_HF_CLIENT_AT_CMD_TYPE at, uint32_t val1, + uint32_t val2, const char* str); /******************************************************************************* * diff --git a/system/bta/include/bta_hh_api.h b/system/bta/include/bta_hh_api.h index 26b085614de..8864cf0e381 100644 --- a/system/bta/include/bta_hh_api.h +++ b/system/bta/include/bta_hh_api.h @@ -213,7 +213,7 @@ enum { typedef uint8_t tBTA_HH_RPT_TYPE; /* HID_CONTROL operation code used in BTA_HhSendCtrl() -*/ + */ enum { BTA_HH_CTRL_NOP = 0 + HID_PAR_CONTROL_NOP, /* mapping from BTE */ BTA_HH_CTRL_HARD_RESET, /* hard reset */ @@ -239,9 +239,8 @@ typedef struct { uint16_t version; /* version */ uint16_t ssr_max_latency; /* SSR max latency, BTA_HH_SSR_PARAM_INVALID if unknown */ - uint16_t - ssr_min_tout; /* SSR min timeout, BTA_HH_SSR_PARAM_INVALID if unknown */ - uint8_t ctry_code; /*Country Code.*/ + uint16_t ssr_min_tout; /* SSR min timeout, BTA_HH_SSR_PARAM_INVALID if unknown */ + uint8_t ctry_code; /*Country Code.*/ #define BTA_HH_LE_REMOTE_WAKE 0x01 #define BTA_HH_LE_NORMAL_CONN 0x02 @@ -250,19 +249,18 @@ typedef struct { uint8_t hid_handle; std::string ToString() const { - return base::StringPrintf("%04x::%04x::%04x", vendor_id, product_id, - version); + return base::StringPrintf("%04x::%04x::%04x", vendor_id, product_id, version); } } tBTA_HH_DEV_DSCP_INFO; /* callback event data for BTA_HH_OPEN_EVT */ typedef struct { tAclLinkSpec link_spec; /* HID device ACL link specification */ - tBTA_HH_STATUS status; /* operation status */ - uint8_t handle; /* device handle */ - bool scps_supported; /* scan parameter service supported */ - uint8_t sub_class; /* Cod sub class */ - uint16_t attr_mask; /* attribute mask */ + tBTA_HH_STATUS status; /* operation status */ + uint8_t handle; /* device handle */ + bool scps_supported; /* scan parameter service supported */ + uint8_t sub_class; /* Cod sub class */ + uint16_t attr_mask; /* attribute mask */ uint8_t app_id; } tBTA_HH_CONN; @@ -344,14 +342,10 @@ typedef union { /** * Android Headtracker Service UUIDs */ -#define ANDROID_HEADTRACKER_SERVICE_UUID_STRING \ - "109b862f-50e3-45cc-8ea1-ac62de4846d1" -#define ANDROID_HEADTRACKER_VERSION_CHARAC_UUID_STRING \ - "b4eb9919-a910-46a2-a9dd-fec2525196fd" -#define ANDROID_HEADTRACKER_CONTROL_CHARAC_UUID_STRING \ - "8584cbb5-2d58-45a3-ab9d-583e0958b067" -#define ANDROID_HEADTRACKER_REPORT_CHARAC_UUID_STRING \ - "e66dd173-b2ae-4f5a-ae16-0162af8038ae" +#define ANDROID_HEADTRACKER_SERVICE_UUID_STRING "109b862f-50e3-45cc-8ea1-ac62de4846d1" +#define ANDROID_HEADTRACKER_VERSION_CHARAC_UUID_STRING "b4eb9919-a910-46a2-a9dd-fec2525196fd" +#define ANDROID_HEADTRACKER_CONTROL_CHARAC_UUID_STRING "8584cbb5-2d58-45a3-ab9d-583e0958b067" +#define ANDROID_HEADTRACKER_REPORT_CHARAC_UUID_STRING "e66dd173-b2ae-4f5a-ae16-0162af8038ae" extern const bluetooth::Uuid ANDROID_HEADTRACKER_SERVICE_UUID; extern const bluetooth::Uuid ANDROID_HEADTRACKER_VERSION_CHARAC_UUID; @@ -443,8 +437,7 @@ void BTA_HhGetProtoMode(uint8_t dev_handle); * Returns void * ******************************************************************************/ -void BTA_HhSetReport(uint8_t dev_handle, tBTA_HH_RPT_TYPE r_type, - BT_HDR* p_data); +void BTA_HhSetReport(uint8_t dev_handle, tBTA_HH_RPT_TYPE r_type, BT_HDR* p_data); /******************************************************************************* * @@ -455,8 +448,8 @@ void BTA_HhSetReport(uint8_t dev_handle, tBTA_HH_RPT_TYPE r_type, * Returns void * ******************************************************************************/ -void BTA_HhGetReport(uint8_t dev_handle, tBTA_HH_RPT_TYPE r_type, - uint8_t rpt_id, uint16_t buf_size); +void BTA_HhGetReport(uint8_t dev_handle, tBTA_HH_RPT_TYPE r_type, uint8_t rpt_id, + uint16_t buf_size); /******************************************************************************* * * Function BTA_HhSetIdle @@ -521,8 +514,7 @@ void BTA_HhGetIdle(uint8_t dev_handle); * Returns void * ******************************************************************************/ -void BTA_HhSendData(uint8_t dev_handle, const tAclLinkSpec& link_spec, - BT_HDR* p_buf); +void BTA_HhSendData(uint8_t dev_handle, const tAclLinkSpec& link_spec, BT_HDR* p_buf); /******************************************************************************* * @@ -546,9 +538,8 @@ void BTA_HhGetDscpInfo(uint8_t dev_handle); * Returns void * ******************************************************************************/ -void BTA_HhAddDev(const tAclLinkSpec& link_spec, tBTA_HH_ATTR_MASK attr_mask, - uint8_t sub_class, uint8_t app_id, - tBTA_HH_DEV_DSCP_INFO dscp_info); +void BTA_HhAddDev(const tAclLinkSpec& link_spec, tBTA_HH_ATTR_MASK attr_mask, uint8_t sub_class, + uint8_t app_id, tBTA_HH_DEV_DSCP_INFO dscp_info); /******************************************************************************* * * Function BTA_HhRemoveDev diff --git a/system/bta/include/bta_hh_co.h b/system/bta/include/bta_hh_co.h index a4b1f0a52c4..0ade782c2c5 100644 --- a/system/bta/include/bta_hh_co.h +++ b/system/bta/include/bta_hh_co.h @@ -65,8 +65,8 @@ void bta_hh_co_data(uint8_t dev_handle, uint8_t* p_rpt, uint16_t len); * Returns True if platform specific initialization is successful * ******************************************************************************/ -bool bta_hh_co_open(uint8_t dev_handle, uint8_t sub_class, uint16_t attr_mask, - uint8_t app_id, tAclLinkSpec& link_spec); +bool bta_hh_co_open(uint8_t dev_handle, uint8_t sub_class, uint16_t attr_mask, uint8_t app_id, + tAclLinkSpec& link_spec); /******************************************************************************* * @@ -90,8 +90,7 @@ void bta_hh_co_set_rpt_rsp(uint8_t dev_handle, uint8_t status); * Returns void. * ******************************************************************************/ -void bta_hh_co_get_rpt_rsp(uint8_t dev_handle, uint8_t status, - const uint8_t* p_rpt, uint16_t len); +void bta_hh_co_get_rpt_rsp(uint8_t dev_handle, uint8_t status, const uint8_t* p_rpt, uint16_t len); /******************************************************************************* * @@ -109,8 +108,8 @@ void bta_hh_co_get_rpt_rsp(uint8_t dev_handle, uint8_t status, * Returns void. * ******************************************************************************/ -void bta_hh_le_co_rpt_info(const tAclLinkSpec& link_spec, - tBTA_HH_RPT_CACHE_ENTRY* p_entry, uint8_t app_id); +void bta_hh_le_co_rpt_info(const tAclLinkSpec& link_spec, tBTA_HH_RPT_CACHE_ENTRY* p_entry, + uint8_t app_id); /******************************************************************************* * @@ -128,8 +127,7 @@ void bta_hh_le_co_rpt_info(const tAclLinkSpec& link_spec, * Returns the acched report array * ******************************************************************************/ -tBTA_HH_RPT_CACHE_ENTRY* bta_hh_le_co_cache_load(const tAclLinkSpec& link_spec, - uint8_t* p_num_rpt, +tBTA_HH_RPT_CACHE_ENTRY* bta_hh_le_co_cache_load(const tAclLinkSpec& link_spec, uint8_t* p_num_rpt, uint8_t app_id); /******************************************************************************* @@ -143,7 +141,6 @@ tBTA_HH_RPT_CACHE_ENTRY* bta_hh_le_co_cache_load(const tAclLinkSpec& link_spec, * Returns none * ******************************************************************************/ -void bta_hh_le_co_reset_rpt_cache(const tAclLinkSpec& link_spec, - uint8_t app_id); +void bta_hh_le_co_reset_rpt_cache(const tAclLinkSpec& link_spec, uint8_t app_id); #endif /* BTA_HH_CO_H */ diff --git a/system/bta/include/bta_jv_api.h b/system/bta/include/bta_jv_api.h index 8becb7bcc60..3eabbad6dba 100644 --- a/system/bta/include/bta_jv_api.h +++ b/system/bta/include/bta_jv_api.h @@ -99,8 +99,7 @@ typedef uint8_t tBTA_JV_L2CAP_REASON; #define BTA_JV_FIRST_SERVICE_ID BTA_FIRST_JV_SERVICE_ID #define BTA_JV_LAST_SERVICE_ID BTA_LAST_JV_SERVICE_ID -#define BTA_JV_NUM_SERVICE_ID \ - (BTA_LAST_JV_SERVICE_ID - BTA_FIRST_JV_SERVICE_ID + 1) +#define BTA_JV_NUM_SERVICE_ID (BTA_LAST_JV_SERVICE_ID - BTA_FIRST_JV_SERVICE_ID + 1) /* Discoverable modes */ enum { BTA_JV_DISC_NONE, BTA_JV_DISC_LIMITED, BTA_JV_DISC_GENERAL }; @@ -113,8 +112,7 @@ typedef uint16_t tBTA_JV_DISC; #define BTA_JV_PM_ALL 0xFF /* Generic match all id, see bta_dm_cfg.c */ typedef uint8_t tBTA_JV_PM_ID; -#define BTA_JV_PM_HANDLE_CLEAR \ - 0xFF /* Special JV ID used to clear PM profile */ +#define BTA_JV_PM_HANDLE_CLEAR 0xFF /* Special JV ID used to clear PM profile */ /* define maximum number of registered PM entities. should be in sync with bta * pm! */ @@ -203,8 +201,8 @@ enum tBTA_JV_EVT : uint16_t { BTA_JV_RFCOMM_START_EVT = 28, // RFCOMM server started BTA_JV_RFCOMM_CL_INIT_EVT = 29, // RFCOMM client initiated a connection BTA_JV_RFCOMM_DATA_IND_EVT = 30, // RFCOMM connection received data - BTA_JV_RFCOMM_CONG_EVT = 31, // RFCOMM connection congestion status changed - BTA_JV_RFCOMM_WRITE_EVT = 33, // the result for BTA_JvRfcommWrite + BTA_JV_RFCOMM_CONG_EVT = 31, // RFCOMM connection congestion status changed + BTA_JV_RFCOMM_WRITE_EVT = 33, // the result for BTA_JvRfcommWrite BTA_JV_RFCOMM_SRV_OPEN_EVT = 34, // open status of Server RFCOMM connection BTA_JV_MAX_EVT = 35, // max number of JV events }; @@ -313,7 +311,7 @@ typedef struct { uint32_t handle; /* The connection handle */ uint32_t req_id; /* The req_id in the associated BTA_JvL2capRead() */ uint8_t* p_data; /* This points the same location as the p_data - * parameter in BTA_JvL2capRead () */ + * parameter in BTA_JvL2capRead () */ uint16_t len; /* The length of the data read. */ } tBTA_JV_L2CAP_READ; @@ -405,42 +403,40 @@ typedef struct { /* union of data associated with JV callback */ typedef union { - tBTA_JV_STATUS status; /* BTA_JV_ENABLE_EVT */ - tBTA_JV_DISCOVERY_COMP disc_comp; /* BTA_JV_DISCOVERY_COMP_EVT */ - tBTA_JV_SET_DISCOVER set_discover; /* BTA_JV_SET_DISCOVER_EVT */ - uint8_t scn; /* BTA_JV_GET_SCN_EVT */ - uint16_t psm; /* BTA_JV_GET_PSM_EVT */ - tBTA_JV_CREATE_RECORD create_rec; /* BTA_JV_CREATE_RECORD_EVT */ - tBTA_JV_L2CAP_OPEN l2c_open; /* BTA_JV_L2CAP_OPEN_EVT */ - tBTA_JV_L2CAP_CLOSE l2c_close; /* BTA_JV_L2CAP_CLOSE_EVT */ - tBTA_JV_L2CAP_START l2c_start; /* BTA_JV_L2CAP_START_EVT */ - tBTA_JV_L2CAP_CL_INIT l2c_cl_init; /* BTA_JV_L2CAP_CL_INIT_EVT */ - tBTA_JV_L2CAP_CONG l2c_cong; /* BTA_JV_L2CAP_CONG_EVT */ - tBTA_JV_L2CAP_READ l2c_read; /* BTA_JV_L2CAP_READ_EVT */ - tBTA_JV_L2CAP_WRITE l2c_write; /* BTA_JV_L2CAP_WRITE_EVT */ - tBTA_JV_RFCOMM_OPEN rfc_open; /* BTA_JV_RFCOMM_OPEN_EVT */ - tBTA_JV_RFCOMM_SRV_OPEN rfc_srv_open; /* BTA_JV_RFCOMM_SRV_OPEN_EVT */ - tBTA_JV_RFCOMM_CLOSE rfc_close; /* BTA_JV_RFCOMM_CLOSE_EVT */ - tBTA_JV_RFCOMM_START rfc_start; /* BTA_JV_RFCOMM_START_EVT */ - tBTA_JV_RFCOMM_CL_INIT rfc_cl_init; /* BTA_JV_RFCOMM_CL_INIT_EVT */ - tBTA_JV_RFCOMM_CONG rfc_cong; /* BTA_JV_RFCOMM_CONG_EVT */ - tBTA_JV_RFCOMM_WRITE rfc_write; /* BTA_JV_RFCOMM_WRITE_EVT */ - tBTA_JV_DATA_IND data_ind; /* BTA_JV_L2CAP_DATA_IND_EVT - BTA_JV_RFCOMM_DATA_IND_EVT */ - tBTA_JV_LE_DATA_IND le_data_ind; /* BTA_JV_L2CAP_LE_DATA_IND_EVT */ - tBTA_JV_L2CAP_LE_OPEN l2c_le_open; /* BTA_JV_L2CAP_OPEN_EVT */ + tBTA_JV_STATUS status; /* BTA_JV_ENABLE_EVT */ + tBTA_JV_DISCOVERY_COMP disc_comp; /* BTA_JV_DISCOVERY_COMP_EVT */ + tBTA_JV_SET_DISCOVER set_discover; /* BTA_JV_SET_DISCOVER_EVT */ + uint8_t scn; /* BTA_JV_GET_SCN_EVT */ + uint16_t psm; /* BTA_JV_GET_PSM_EVT */ + tBTA_JV_CREATE_RECORD create_rec; /* BTA_JV_CREATE_RECORD_EVT */ + tBTA_JV_L2CAP_OPEN l2c_open; /* BTA_JV_L2CAP_OPEN_EVT */ + tBTA_JV_L2CAP_CLOSE l2c_close; /* BTA_JV_L2CAP_CLOSE_EVT */ + tBTA_JV_L2CAP_START l2c_start; /* BTA_JV_L2CAP_START_EVT */ + tBTA_JV_L2CAP_CL_INIT l2c_cl_init; /* BTA_JV_L2CAP_CL_INIT_EVT */ + tBTA_JV_L2CAP_CONG l2c_cong; /* BTA_JV_L2CAP_CONG_EVT */ + tBTA_JV_L2CAP_READ l2c_read; /* BTA_JV_L2CAP_READ_EVT */ + tBTA_JV_L2CAP_WRITE l2c_write; /* BTA_JV_L2CAP_WRITE_EVT */ + tBTA_JV_RFCOMM_OPEN rfc_open; /* BTA_JV_RFCOMM_OPEN_EVT */ + tBTA_JV_RFCOMM_SRV_OPEN rfc_srv_open; /* BTA_JV_RFCOMM_SRV_OPEN_EVT */ + tBTA_JV_RFCOMM_CLOSE rfc_close; /* BTA_JV_RFCOMM_CLOSE_EVT */ + tBTA_JV_RFCOMM_START rfc_start; /* BTA_JV_RFCOMM_START_EVT */ + tBTA_JV_RFCOMM_CL_INIT rfc_cl_init; /* BTA_JV_RFCOMM_CL_INIT_EVT */ + tBTA_JV_RFCOMM_CONG rfc_cong; /* BTA_JV_RFCOMM_CONG_EVT */ + tBTA_JV_RFCOMM_WRITE rfc_write; /* BTA_JV_RFCOMM_WRITE_EVT */ + tBTA_JV_DATA_IND data_ind; /* BTA_JV_L2CAP_DATA_IND_EVT + BTA_JV_RFCOMM_DATA_IND_EVT */ + tBTA_JV_LE_DATA_IND le_data_ind; /* BTA_JV_L2CAP_LE_DATA_IND_EVT */ + tBTA_JV_L2CAP_LE_OPEN l2c_le_open; /* BTA_JV_L2CAP_OPEN_EVT */ } tBTA_JV; /* JAVA DM Interface callback */ typedef void(tBTA_JV_DM_CBACK)(tBTA_JV_EVT event, tBTA_JV* p_data, uint32_t id); /* JAVA RFCOMM interface callback */ -typedef uint32_t(tBTA_JV_RFCOMM_CBACK)(tBTA_JV_EVT event, tBTA_JV* p_data, - uint32_t rfcomm_slot_id); +typedef uint32_t(tBTA_JV_RFCOMM_CBACK)(tBTA_JV_EVT event, tBTA_JV* p_data, uint32_t rfcomm_slot_id); /* JAVA L2CAP interface callback */ -typedef void(tBTA_JV_L2CAP_CBACK)(tBTA_JV_EVT event, tBTA_JV* p_data, - uint32_t l2cap_socket_id); +typedef void(tBTA_JV_L2CAP_CBACK)(tBTA_JV_EVT event, tBTA_JV* p_data, uint32_t l2cap_socket_id); /******************************************************************************* * @@ -489,8 +485,7 @@ void BTA_JvDisable(void); * Returns void * ******************************************************************************/ -void BTA_JvGetChannelId(tBTA_JV_CONN_TYPE conn_type, uint32_t id, - int32_t channel); +void BTA_JvGetChannelId(tBTA_JV_CONN_TYPE conn_type, uint32_t id, int32_t channel); /******************************************************************************* * @@ -518,10 +513,8 @@ tBTA_JV_STATUS BTA_JvFreeChannel(uint16_t channel, tBTA_JV_CONN_TYPE conn_type); * BTA_JV_FAILURE, otherwise. * ******************************************************************************/ -tBTA_JV_STATUS BTA_JvStartDiscovery(const RawAddress& bd_addr, - uint16_t num_uuid, - const bluetooth::Uuid* p_uuid_list, - uint32_t rfcomm_slot_id); +tBTA_JV_STATUS BTA_JvStartDiscovery(const RawAddress& bd_addr, uint16_t num_uuid, + const bluetooth::Uuid* p_uuid_list, uint32_t rfcomm_slot_id); /******************************************************************************* * @@ -561,11 +554,10 @@ tBTA_JV_STATUS BTA_JvDeleteRecord(uint32_t handle); * ******************************************************************************/ void BTA_JvL2capConnect(tBTA_JV_CONN_TYPE conn_type, tBTA_SEC sec_mask, - std::unique_ptr ertm_info, - uint16_t remote_psm, uint16_t rx_mtu, - std::unique_ptr cfg, - const RawAddress& peer_bd_addr, - tBTA_JV_L2CAP_CBACK* p_cback, uint32_t l2cap_socket_id); + std::unique_ptr ertm_info, uint16_t remote_psm, + uint16_t rx_mtu, std::unique_ptr cfg, + const RawAddress& peer_bd_addr, tBTA_JV_L2CAP_CBACK* p_cback, + uint32_t l2cap_socket_id); /******************************************************************************* * @@ -594,11 +586,9 @@ tBTA_JV_STATUS BTA_JvL2capClose(uint32_t handle); * ******************************************************************************/ void BTA_JvL2capStartServer(tBTA_JV_CONN_TYPE conn_type, tBTA_SEC sec_mask, - std::unique_ptr ertm_info, - uint16_t local_psm, uint16_t rx_mtu, - std::unique_ptr cfg, - tBTA_JV_L2CAP_CBACK* p_cback, - uint32_t l2cap_socket_id); + std::unique_ptr ertm_info, uint16_t local_psm, + uint16_t rx_mtu, std::unique_ptr cfg, + tBTA_JV_L2CAP_CBACK* p_cback, uint32_t l2cap_socket_id); /******************************************************************************* * @@ -611,8 +601,7 @@ void BTA_JvL2capStartServer(tBTA_JV_CONN_TYPE conn_type, tBTA_SEC sec_mask, * BTA_JV_FAILURE, otherwise. * ******************************************************************************/ -tBTA_JV_STATUS BTA_JvL2capStopServer(uint16_t local_psm, - uint32_t l2cap_socket_id); +tBTA_JV_STATUS BTA_JvL2capStopServer(uint16_t local_psm, uint32_t l2cap_socket_id); /******************************************************************************* * @@ -626,8 +615,7 @@ tBTA_JV_STATUS BTA_JvL2capStopServer(uint16_t local_psm, * BTA_JV_FAILURE, otherwise. * ******************************************************************************/ -tBTA_JV_STATUS BTA_JvL2capRead(uint32_t handle, uint32_t req_id, - uint8_t* p_data, uint16_t len); +tBTA_JV_STATUS BTA_JvL2capRead(uint32_t handle, uint32_t req_id, uint8_t* p_data, uint16_t len); /******************************************************************************* * @@ -655,8 +643,7 @@ tBTA_JV_STATUS BTA_JvL2capReady(uint32_t handle, uint32_t* p_data_size); * BTA_JV_FAILURE, otherwise. * ******************************************************************************/ -tBTA_JV_STATUS BTA_JvL2capWrite(uint32_t handle, uint32_t req_id, BT_HDR* msg, - uint32_t user_id); +tBTA_JV_STATUS BTA_JvL2capWrite(uint32_t handle, uint32_t req_id, BT_HDR* msg, uint32_t user_id); /******************************************************************************* * @@ -675,8 +662,7 @@ tBTA_JV_STATUS BTA_JvL2capWrite(uint32_t handle, uint32_t req_id, BT_HDR* msg, * ******************************************************************************/ tBTA_JV_STATUS BTA_JvRfcommConnect(tBTA_SEC sec_mask, uint8_t remote_scn, - const RawAddress& peer_bd_addr, - tBTA_JV_RFCOMM_CBACK* p_cback, + const RawAddress& peer_bd_addr, tBTA_JV_RFCOMM_CBACK* p_cback, uint32_t rfcomm_slot_id); /******************************************************************************* @@ -706,10 +692,8 @@ tBTA_JV_STATUS BTA_JvRfcommClose(uint32_t handle, uint32_t rfcomm_slot_id); * BTA_JV_FAILURE, otherwise. * ******************************************************************************/ -tBTA_JV_STATUS BTA_JvRfcommStartServer(tBTA_SEC sec_mask, uint8_t local_scn, - uint8_t max_session, - tBTA_JV_RFCOMM_CBACK* p_cback, - uint32_t rfcomm_slot_id); +tBTA_JV_STATUS BTA_JvRfcommStartServer(tBTA_SEC sec_mask, uint8_t local_scn, uint8_t max_session, + tBTA_JV_RFCOMM_CBACK* p_cback, uint32_t rfcomm_slot_id); /******************************************************************************* * diff --git a/system/bta/include/bta_jv_co.h b/system/bta/include/bta_jv_co.h index e170f2fb968..6a329503b4b 100644 --- a/system/bta/include/bta_jv_co.h +++ b/system/bta/include/bta_jv_co.h @@ -45,7 +45,6 @@ int bta_co_rfc_data_incoming(uint32_t rfcomm_slot_id, BT_HDR* p_buf); int bta_co_rfc_data_outgoing_size(uint32_t rfcomm_slot_id, int* size); -int bta_co_rfc_data_outgoing(uint32_t rfcomm_slot_id, uint8_t* buf, - uint16_t size); +int bta_co_rfc_data_outgoing(uint32_t rfcomm_slot_id, uint8_t* buf, uint16_t size); #endif /* BTA_DG_CO_H */ diff --git a/system/bta/include/bta_le_audio_api.h b/system/bta/include/bta_le_audio_api.h index 14cdb4575e9..e4df7660fa1 100644 --- a/system/bta/include/bta_le_audio_api.h +++ b/system/bta/include/bta_le_audio_api.h @@ -25,26 +25,24 @@ #include class LeAudioHalVerifier { - public: +public: static bool SupportsLeAudio(); static bool SupportsLeAudioHardwareOffload(); static bool SupportsLeAudioBroadcast(); static bool SupportsStreamActiveApi(); }; -typedef bool(LeAudioIsoDataCallback)(const RawAddress& address, - uint16_t cis_conn_hdl, uint8_t* data, - uint16_t size, uint32_t timestamp); +typedef bool(LeAudioIsoDataCallback)(const RawAddress& address, uint16_t cis_conn_hdl, + uint8_t* data, uint16_t size, uint32_t timestamp); /* Interface class */ class LeAudioClient { - public: +public: virtual ~LeAudioClient(void) = default; static void Initialize( - bluetooth::le_audio::LeAudioClientCallbacks* callbacks, - base::Closure initCb, base::Callback hal_2_1_verifier, - const std::vector& - offloading_preference); + bluetooth::le_audio::LeAudioClientCallbacks* callbacks, base::Closure initCb, + base::Callback hal_2_1_verifier, + const std::vector& offloading_preference); static void Cleanup(void); static LeAudioClient* Get(void); static void DebugDump(int fd); @@ -61,9 +59,8 @@ class LeAudioClient { virtual void GroupDestroy(const int group_id) = 0; virtual void GroupSetActive(const int group_id) = 0; virtual void SetCodecConfigPreference( - int group_id, - bluetooth::le_audio::btle_audio_codec_config_t input_codec_config, - bluetooth::le_audio::btle_audio_codec_config_t output_codec_config) = 0; + int group_id, bluetooth::le_audio::btle_audio_codec_config_t input_codec_config, + bluetooth::le_audio::btle_audio_codec_config_t output_codec_config) = 0; virtual void SetCcidInformation(int ccid, int context_type) = 0; virtual void SetInCall(bool in_call) = 0; virtual bool IsInCall() = 0; @@ -71,9 +68,8 @@ class LeAudioClient { virtual void SetUnicastMonitorMode(uint8_t direction, bool enable) = 0; virtual bool IsInVoipCall() = 0; virtual bool IsInStreaming() = 0; - virtual void SendAudioProfilePreferences( - const int group_id, bool is_output_preference_le_audio, - bool is_duplex_preference_le_audio) = 0; + virtual void SendAudioProfilePreferences(const int group_id, bool is_output_preference_le_audio, + bool is_duplex_preference_le_audio) = 0; virtual void SetGroupAllowedContextMask(int group_id, int sink_context_types, int source_context_types) = 0; @@ -83,22 +79,17 @@ class LeAudioClient { static bool RegisterIsoDataConsumer(LeAudioIsoDataCallback callback); - static void AddFromStorage(const RawAddress& addr, bool autoconnect, - int sink_audio_location, int source_audio_location, - int sink_supported_context_types, + static void AddFromStorage(const RawAddress& addr, bool autoconnect, int sink_audio_location, + int source_audio_location, int sink_supported_context_types, int source_supported_context_types, const std::vector& handles, const std::vector& sink_pacs, const std::vector& source_pacs, const std::vector& ases); - static bool GetHandlesForStorage(const RawAddress& addr, - std::vector& out); - static bool GetSinkPacsForStorage(const RawAddress& addr, - std::vector& out); - static bool GetSourcePacsForStorage(const RawAddress& addr, - std::vector& out); - static bool GetAsesForStorage(const RawAddress& addr, - std::vector& out); + static bool GetHandlesForStorage(const RawAddress& addr, std::vector& out); + static bool GetSinkPacsForStorage(const RawAddress& addr, std::vector& out); + static bool GetSourcePacsForStorage(const RawAddress& addr, std::vector& out); + static bool GetAsesForStorage(const RawAddress& addr, std::vector& out); static bool IsLeAudioClientRunning(); static bool IsLeAudioClientInStreaming(); }; diff --git a/system/bta/include/bta_le_audio_broadcaster_api.h b/system/bta/include/bta_le_audio_broadcaster_api.h index 5fcad5b522f..c84107c54b8 100644 --- a/system/bta/include/bta_le_audio_broadcaster_api.h +++ b/system/bta/include/bta_le_audio_broadcaster_api.h @@ -25,14 +25,13 @@ /* Interface class */ class LeAudioBroadcaster { - public: +public: static constexpr uint8_t kInstanceIdUndefined = 0xFF; virtual ~LeAudioBroadcaster(void) = default; - static void Initialize( - bluetooth::le_audio::LeAudioBroadcasterCallbacks* callbacks, - base::Callback hal_2_1_verifier); + static void Initialize(bluetooth::le_audio::LeAudioBroadcasterCallbacks* callbacks, + base::Callback hal_2_1_verifier); static void Stop(void); static void Cleanup(void); static LeAudioBroadcaster* Get(void); @@ -40,26 +39,24 @@ class LeAudioBroadcaster { static void DebugDump(int fd); virtual void CreateAudioBroadcast( - bool is_public, const std::string& broadcast_name, - const std::optional& broadcast_code, - const std::vector& public_metadata, - const std::vector& subgroup_quality, - const std::vector>& subgroup_metadata) = 0; + bool is_public, const std::string& broadcast_name, + const std::optional& broadcast_code, + const std::vector& public_metadata, const std::vector& subgroup_quality, + const std::vector>& subgroup_metadata) = 0; virtual void SuspendAudioBroadcast(uint32_t broadcast_id) = 0; virtual void StartAudioBroadcast(uint32_t broadcast_id) = 0; virtual void StopAudioBroadcast(uint32_t broadcast_id) = 0; virtual void DestroyAudioBroadcast(uint32_t broadcast_id) = 0; virtual void GetBroadcastMetadata(uint32_t broadcast_id) = 0; virtual void GetAllBroadcastStates(void) = 0; - virtual void UpdateMetadata( - uint32_t broadcast_id, const std::string& broadcast_name, - const std::vector& public_metadata, - const std::vector>& subgroup_metadata) = 0; + virtual void UpdateMetadata(uint32_t broadcast_id, const std::string& broadcast_name, + const std::vector& public_metadata, + const std::vector>& subgroup_metadata) = 0; virtual void IsValidBroadcast( - uint32_t broadcast_id, uint8_t addr_type, RawAddress addr, - base::Callback - cb) = 0; + uint32_t broadcast_id, uint8_t addr_type, RawAddress addr, + base::Callback + cb) = 0; virtual void SetStreamingPhy(uint8_t phy) = 0; virtual uint8_t GetStreamingPhy(void) const = 0; diff --git a/system/bta/include/bta_pan_api.h b/system/bta/include/bta_pan_api.h index da41c97a114..ad7f1167861 100644 --- a/system/bta/include/bta_pan_api.h +++ b/system/bta/include/bta_pan_api.h @@ -67,7 +67,7 @@ typedef struct { /* Event associated with BTA_PAN_OPENING_EVT */ typedef struct { RawAddress bd_addr; /* BD address of peer device. */ - uint16_t handle; /* Handle associated with this connection. */ + uint16_t handle; /* Handle associated with this connection. */ } tBTA_PAN_OPENING; @@ -157,8 +157,7 @@ void BTA_PanSetRole(tBTA_PAN_ROLE role, const tBTA_PAN_ROLE_INFO p_user_info, * Returns void * ******************************************************************************/ -void BTA_PanOpen(const RawAddress& bd_addr, tBTA_PAN_ROLE local_role, - tBTA_PAN_ROLE peer_role); +void BTA_PanOpen(const RawAddress& bd_addr, tBTA_PAN_ROLE local_role, tBTA_PAN_ROLE peer_role); /******************************************************************************* * diff --git a/system/bta/include/bta_pan_ci.h b/system/bta/include/bta_pan_ci.h index d58a24cd387..6edc30f7f63 100644 --- a/system/bta/include/bta_pan_ci.h +++ b/system/bta/include/bta_pan_ci.h @@ -95,9 +95,8 @@ void bta_pan_ci_tx_flow(uint16_t handle, bool enable); * Returns true if flow enabled * ******************************************************************************/ -void bta_pan_ci_rx_writebuf(uint16_t handle, const RawAddress& src, - const RawAddress& dst, uint16_t protocol, - BT_HDR* p_buf, bool ext); +void bta_pan_ci_rx_writebuf(uint16_t handle, const RawAddress& src, const RawAddress& dst, + uint16_t protocol, BT_HDR* p_buf, bool ext); /******************************************************************************* * @@ -112,7 +111,7 @@ void bta_pan_ci_rx_writebuf(uint16_t handle, const RawAddress& src, * Returns void * ******************************************************************************/ -BT_HDR* bta_pan_ci_readbuf(uint16_t handle, RawAddress& src, RawAddress& dst, - uint16_t* p_protocol, bool* p_ext, bool* p_forward); +BT_HDR* bta_pan_ci_readbuf(uint16_t handle, RawAddress& src, RawAddress& dst, uint16_t* p_protocol, + bool* p_ext, bool* p_forward); #endif /* BTA_PAN_CI_H */ diff --git a/system/bta/include/bta_pan_co.h b/system/bta/include/bta_pan_co.h index 63f778439b4..d1c6b7460af 100644 --- a/system/bta/include/bta_pan_co.h +++ b/system/bta/include/bta_pan_co.h @@ -130,8 +130,7 @@ void bta_pan_co_rx_flow(uint16_t handle, uint8_t app_id, bool enable); * Returns void * ******************************************************************************/ -void bta_pan_co_pfilt_ind(uint16_t handle, bool indication, - tBTA_PAN_STATUS result, uint16_t len, +void bta_pan_co_pfilt_ind(uint16_t handle, bool indication, tBTA_PAN_STATUS result, uint16_t len, uint8_t* p_filters); /******************************************************************************* @@ -143,8 +142,7 @@ void bta_pan_co_pfilt_ind(uint16_t handle, bool indication, * Returns void * ******************************************************************************/ -void bta_pan_co_mfilt_ind(uint16_t handle, bool indication, - tBTA_PAN_STATUS result, uint16_t len, +void bta_pan_co_mfilt_ind(uint16_t handle, bool indication, tBTA_PAN_STATUS result, uint16_t len, uint8_t* p_filters); #endif /* BTA_PAN_CO_H */ diff --git a/system/bta/include/bta_ras_api.h b/system/bta/include/bta_ras_api.h index ccd1258a5cf..8d82db6760b 100644 --- a/system/bta/include/bta_ras_api.h +++ b/system/bta/include/bta_ras_api.h @@ -32,52 +32,46 @@ struct VendorSpecificCharacteristic { }; class RasServerCallbacks { - public: +public: virtual ~RasServerCallbacks() = default; virtual void OnVendorSpecificReply( - const RawAddress& address, - const std::vector& - vendor_specific_reply) = 0; + const RawAddress& address, + const std::vector& vendor_specific_reply) = 0; }; class RasServer { - public: +public: virtual ~RasServer() = default; virtual void Initialize() = 0; virtual void RegisterCallbacks(RasServerCallbacks* callbacks) = 0; virtual void SetVendorSpecificCharacteristic( - const std::vector& - vendor_specific_characteristics) = 0; - virtual void HandleVendorSpecificReplyComplete(RawAddress address, - bool success) = 0; - virtual void PushProcedureData(RawAddress address, uint16_t procedure_count, - bool is_last, std::vector data) = 0; + const std::vector& vendor_specific_characteristics) = 0; + virtual void HandleVendorSpecificReplyComplete(RawAddress address, bool success) = 0; + virtual void PushProcedureData(RawAddress address, uint16_t procedure_count, bool is_last, + std::vector data) = 0; }; RasServer* GetRasServer(); class RasClientCallbacks { - public: +public: virtual ~RasClientCallbacks() = default; - virtual void OnConnected(const RawAddress& address, uint16_t att_handle, - const std::vector& - vendor_specific_characteristics) = 0; - virtual void OnWriteVendorSpecificReplyComplete(const RawAddress& address, - bool success) = 0; - virtual void OnRemoteData(const RawAddress& address, - const std::vector& data) = 0; + virtual void OnConnected( + const RawAddress& address, uint16_t att_handle, + const std::vector& vendor_specific_characteristics) = 0; + virtual void OnWriteVendorSpecificReplyComplete(const RawAddress& address, bool success) = 0; + virtual void OnRemoteData(const RawAddress& address, const std::vector& data) = 0; }; class RasClient { - public: +public: virtual ~RasClient() = default; virtual void Initialize() = 0; virtual void RegisterCallbacks(RasClientCallbacks* callbacks) = 0; virtual void Connect(const RawAddress& address) = 0; virtual void SendVendorSpecificReply( - const RawAddress& address, - const std::vector& - vendor_specific_data) = 0; + const RawAddress& address, + const std::vector& vendor_specific_data) = 0; }; RasClient* GetRasClient(); diff --git a/system/bta/include/bta_sdp_api.h b/system/bta/include/bta_sdp_api.h index 25352bfa393..5eaf66bfb86 100644 --- a/system/bta/include/bta_sdp_api.h +++ b/system/bta/include/bta_sdp_api.h @@ -82,8 +82,7 @@ typedef union { } tBTA_SDP; /* SDP DM Interface callback */ -typedef void(tBTA_SDP_DM_CBACK)(tBTA_SDP_EVT event, tBTA_SDP* p_data, - void* user_data); +typedef void(tBTA_SDP_DM_CBACK)(tBTA_SDP_EVT event, tBTA_SDP* p_data, void* user_data); /* MCE configuration structure */ typedef struct { @@ -119,8 +118,7 @@ tBTA_SDP_STATUS BTA_SdpEnable(tBTA_SDP_DM_CBACK* p_cback); * BTA_SDP_FAIL if internal failure. * ******************************************************************************/ -tBTA_SDP_STATUS BTA_SdpSearch(const RawAddress& bd_addr, - const bluetooth::Uuid& uuid); +tBTA_SDP_STATUS BTA_SdpSearch(const RawAddress& bd_addr, const bluetooth::Uuid& uuid); /******************************************************************************* * diff --git a/system/bta/include/bta_sec_api.h b/system/bta/include/bta_sec_api.h index 6123aedd017..acba2188dc6 100644 --- a/system/bta/include/bta_sec_api.h +++ b/system/bta/include/bta_sec_api.h @@ -38,32 +38,29 @@ /* Security Setting Mask */ #define BTA_SEC_AUTHENTICATE \ - (BTM_SEC_IN_AUTHENTICATE | \ - BTM_SEC_OUT_AUTHENTICATE) /* Authentication required. */ -#define BTA_SEC_ENCRYPT \ - (BTM_SEC_IN_ENCRYPT | BTM_SEC_OUT_ENCRYPT) /* Encryption required. */ + (BTM_SEC_IN_AUTHENTICATE | BTM_SEC_OUT_AUTHENTICATE) /* Authentication required. */ +#define BTA_SEC_ENCRYPT (BTM_SEC_IN_ENCRYPT | BTM_SEC_OUT_ENCRYPT) /* Encryption required. */ typedef uint16_t tBTA_SEC; typedef enum : uint8_t { /* Security Callback Events */ - BTA_DM_PIN_REQ_EVT = 2, /* PIN request. */ - BTA_DM_AUTH_CMPL_EVT = 3, /* Authentication complete indication. */ - BTA_DM_AUTHORIZE_EVT = 4, /* Authorization request. */ - BTA_DM_BOND_CANCEL_CMPL_EVT = 9, /* Bond cancel complete indication */ - BTA_DM_SP_CFM_REQ_EVT = 10, /* Simple Pairing User Confirmation request */ - BTA_DM_SP_KEY_NOTIF_EVT = 11, /* Simple Pairing Passkey Notification */ - BTA_DM_BLE_KEY_EVT = 15, /* BLE SMP key event for peer device keys */ - BTA_DM_BLE_SEC_REQ_EVT = 16, /* BLE SMP security request */ + BTA_DM_PIN_REQ_EVT = 2, /* PIN request. */ + BTA_DM_AUTH_CMPL_EVT = 3, /* Authentication complete indication. */ + BTA_DM_AUTHORIZE_EVT = 4, /* Authorization request. */ + BTA_DM_BOND_CANCEL_CMPL_EVT = 9, /* Bond cancel complete indication */ + BTA_DM_SP_CFM_REQ_EVT = 10, /* Simple Pairing User Confirmation request */ + BTA_DM_SP_KEY_NOTIF_EVT = 11, /* Simple Pairing Passkey Notification */ + BTA_DM_BLE_KEY_EVT = 15, /* BLE SMP key event for peer device keys */ + BTA_DM_BLE_SEC_REQ_EVT = 16, /* BLE SMP security request */ BTA_DM_BLE_PASSKEY_NOTIF_EVT = 17, /* SMP passkey notification event */ BTA_DM_BLE_PASSKEY_REQ_EVT = 18, /* SMP passkey request event */ BTA_DM_BLE_OOB_REQ_EVT = 19, /* SMP OOB request event */ BTA_DM_BLE_LOCAL_IR_EVT = 20, /* BLE local IR event */ BTA_DM_BLE_LOCAL_ER_EVT = 21, /* BLE local ER event */ BTA_DM_BLE_NC_REQ_EVT = 22, /* SMP Numeric Comparison request event */ - BTA_DM_SP_RMT_OOB_EXT_EVT = - 23, /* Simple Pairing Remote OOB Extended Data request. */ - BTA_DM_BLE_AUTH_CMPL_EVT = 24, /* BLE Auth complete */ + BTA_DM_SP_RMT_OOB_EXT_EVT = 23, /* Simple Pairing Remote OOB Extended Data request. */ + BTA_DM_BLE_AUTH_CMPL_EVT = 24, /* BLE Auth complete */ BTA_DM_DEV_UNPAIRED_EVT = 25, BTA_DM_ENER_INFO_READ = 28, /* Energy info read */ BTA_DM_BLE_SC_OOB_REQ_EVT = 29, /* SMP SC OOB request event */ @@ -93,26 +90,21 @@ typedef struct { */ #define BTA_DM_AUTH_CONVERT_SMP_CODE(x) (BTA_DM_AUTH_FAIL_BASE + (x)) -#define BTA_DM_AUTH_SMP_PAIR_AUTH_FAIL \ - (BTA_DM_AUTH_FAIL_BASE + SMP_PAIR_AUTH_FAIL) -#define BTA_DM_AUTH_SMP_CONFIRM_VALUE_FAIL \ - (BTA_DM_AUTH_FAIL_BASE + SMP_CONFIRM_VALUE_ERR) -#define BTA_DM_AUTH_SMP_PAIR_NOT_SUPPORT \ - (BTA_DM_AUTH_FAIL_BASE + SMP_PAIR_NOT_SUPPORT) -#define BTA_DM_AUTH_SMP_UNKNOWN_ERR \ - (BTA_DM_AUTH_FAIL_BASE + SMP_PAIR_FAIL_UNKNOWN) +#define BTA_DM_AUTH_SMP_PAIR_AUTH_FAIL (BTA_DM_AUTH_FAIL_BASE + SMP_PAIR_AUTH_FAIL) +#define BTA_DM_AUTH_SMP_CONFIRM_VALUE_FAIL (BTA_DM_AUTH_FAIL_BASE + SMP_CONFIRM_VALUE_ERR) +#define BTA_DM_AUTH_SMP_PAIR_NOT_SUPPORT (BTA_DM_AUTH_FAIL_BASE + SMP_PAIR_NOT_SUPPORT) +#define BTA_DM_AUTH_SMP_UNKNOWN_ERR (BTA_DM_AUTH_FAIL_BASE + SMP_PAIR_FAIL_UNKNOWN) #define BTA_DM_AUTH_SMP_CONN_TOUT (BTA_DM_AUTH_FAIL_BASE + SMP_CONN_TOUT) typedef uint8_t tBTA_LE_KEY_TYPE; /* can be used as a bit mask */ typedef union { - tBTM_LE_PENC_KEYS penc_key; /* received peer encryption key */ - tBTM_LE_PCSRK_KEYS psrk_key; /* received peer device SRK */ - tBTM_LE_PID_KEYS pid_key; /* peer device ID key */ - tBTM_LE_LENC_KEYS - lenc_key; /* local encryption reproduction keys LTK = = d1(ER,DIV,0)*/ + tBTM_LE_PENC_KEYS penc_key; /* received peer encryption key */ + tBTM_LE_PCSRK_KEYS psrk_key; /* received peer device SRK */ + tBTM_LE_PID_KEYS pid_key; /* peer device ID key */ + tBTM_LE_LENC_KEYS lenc_key; /* local encryption reproduction keys LTK = = d1(ER,DIV,0)*/ tBTM_LE_LCSRK_KEYS lcsrk_key; /* local device CSRK = d1(ER,DIV,1)*/ - tBTM_LE_PID_KEYS lid_key; /* local device ID key for the particular remote */ + tBTM_LE_PID_KEYS lid_key; /* local device ID key for the particular remote */ } tBTA_LE_KEY_VALUE; #define BTA_BLE_LOCAL_KEY_TYPE_ID 1 @@ -132,7 +124,7 @@ typedef uint8_t tBTA_DM_BLE_SEC_GRANT; /* Structure associated with BTA_DM_BLE_SEC_REQ_EVT */ typedef struct { RawAddress bd_addr; /* peer address */ - BD_NAME bd_name; /* peer device name */ + BD_NAME bd_name; /* peer device name */ } tBTA_DM_BLE_SEC_REQ; typedef struct { @@ -143,14 +135,13 @@ typedef struct { /* Structure associated with BTA_DM_AUTH_CMPL_EVT */ typedef struct { - RawAddress bd_addr; /* BD address peer device. */ - BD_NAME bd_name; /* Name of peer device. */ - bool key_present; /* Valid link key value in key element */ - LinkKey key; /* Link key associated with peer device. */ - uint8_t key_type; /* The type of Link Key */ - bool success; /* true of authentication succeeded, false if failed. */ - tHCI_REASON - fail_reason; /* The HCI reason/error code for when success=false */ + RawAddress bd_addr; /* BD address peer device. */ + BD_NAME bd_name; /* Name of peer device. */ + bool key_present; /* Valid link key value in key element */ + LinkKey key; /* Link key associated with peer device. */ + uint8_t key_type; /* The type of Link Key */ + bool success; /* true of authentication succeeded, false if failed. */ + tHCI_REASON fail_reason; /* The HCI reason/error code for when success=false */ tBLE_ADDR_TYPE addr_type; /* Peer device address type */ tBT_DEVICE_TYPE dev_type; bool is_ctkd; /* True if key is derived using CTKD procedure */ @@ -167,12 +158,9 @@ typedef struct { Use IO Capabilities to determine authentication procedure \ */ -#define BTA_AUTH_DD_BOND \ - BTM_AUTH_DD_BOND /* 2 this bit is set for dedicated bonding */ -#define BTA_AUTH_GEN_BOND \ - BTM_AUTH_SPGB_NO /* 4 this bit is set for general bonding */ -#define BTA_AUTH_BONDS \ - BTM_AUTH_BONDS /* 6 the general/dedicated bonding bits */ +#define BTA_AUTH_DD_BOND BTM_AUTH_DD_BOND /* 2 this bit is set for dedicated bonding */ +#define BTA_AUTH_GEN_BOND BTM_AUTH_SPGB_NO /* 4 this bit is set for general bonding */ +#define BTA_AUTH_BONDS BTM_AUTH_BONDS /* 6 the general/dedicated bonding bits */ #define BTA_LE_AUTH_REQ_SC_MITM_BOND BTM_LE_AUTH_REQ_SC_MITM_BOND /* 1101 */ @@ -180,12 +168,12 @@ typedef struct { typedef struct { /* Note: First 3 data members must be, bd_addr, dev_class, and bd_name in * order */ - RawAddress bd_addr; /* peer address */ - DEV_CLASS dev_class; /* peer CoD */ - BD_NAME bd_name; /* peer device name */ - uint32_t num_val; /* the numeric value for comparison. If just_works, do not - show this number to UI */ - bool just_works; /* true, if "Just Works" association model */ + RawAddress bd_addr; /* peer address */ + DEV_CLASS dev_class; /* peer CoD */ + BD_NAME bd_name; /* peer device name */ + uint32_t num_val; /* the numeric value for comparison. If just_works, do not + show this number to UI */ + bool just_works; /* true, if "Just Works" association model */ tBTM_AUTH_REQ loc_auth_req; /* Authentication required for local device */ tBTM_AUTH_REQ rmt_auth_req; /* Authentication required for peer device */ tBTM_IO_CAP loc_io_caps; /* IO Capabilities of local device */ @@ -199,8 +187,8 @@ typedef struct { RawAddress bd_addr; /* peer address */ DEV_CLASS dev_class; /* peer CoD */ BD_NAME bd_name; /* peer device name */ - uint32_t passkey; /* the numeric value for comparison. If just_works, do not - show this number to UI */ + uint32_t passkey; /* the numeric value for comparison. If just_works, do not + show this number to UI */ } tBTA_DM_SP_KEY_NOTIF; /* Structure associated with BTA_DM_SP_RMT_OOB_EVT */ @@ -229,19 +217,18 @@ typedef struct { /* Union of all security callback structures */ typedef union { - tBTA_DM_PIN_REQ pin_req; /* PIN request. */ - tBTA_DM_AUTH_CMPL auth_cmpl; /* Authentication complete indication. */ - tBTA_DM_UNPAIR dev_unpair; /* Remove bonding complete indication */ - tBTA_DM_SP_CFM_REQ cfm_req; /* user confirm request */ - tBTA_DM_SP_KEY_NOTIF key_notif; /* passkey notification */ - tBTA_DM_SP_RMT_OOB rmt_oob; /* remote oob */ - tBTA_DM_BOND_CANCEL_CMPL - bond_cancel_cmpl; /* Bond Cancel Complete indication */ - tBTA_DM_BLE_SEC_REQ ble_req; /* BLE SMP related request */ - tBTA_DM_BLE_KEY ble_key; /* BLE SMP keys used when pairing */ - tBTA_BLE_LOCAL_ID_KEYS ble_id_keys; /* IR event */ - Octet16 ble_er; /* ER event data */ - tBTA_DM_LOC_OOB_DATA local_oob_data; /* Local OOB data generated by us */ + tBTA_DM_PIN_REQ pin_req; /* PIN request. */ + tBTA_DM_AUTH_CMPL auth_cmpl; /* Authentication complete indication. */ + tBTA_DM_UNPAIR dev_unpair; /* Remove bonding complete indication */ + tBTA_DM_SP_CFM_REQ cfm_req; /* user confirm request */ + tBTA_DM_SP_KEY_NOTIF key_notif; /* passkey notification */ + tBTA_DM_SP_RMT_OOB rmt_oob; /* remote oob */ + tBTA_DM_BOND_CANCEL_CMPL bond_cancel_cmpl; /* Bond Cancel Complete indication */ + tBTA_DM_BLE_SEC_REQ ble_req; /* BLE SMP related request */ + tBTA_DM_BLE_KEY ble_key; /* BLE SMP keys used when pairing */ + tBTA_BLE_LOCAL_ID_KEYS ble_id_keys; /* IR event */ + Octet16 ble_er; /* ER event data */ + tBTA_DM_LOC_OOB_DATA local_oob_data; /* Local OOB data generated by us */ tBTA_DM_RC_UNPAIR delete_key_RC_to_unpair; tBTA_DM_PROC_ID_ADDR proc_id_addr; /* Identity address event */ tBTA_DM_KEY_MISSING key_missing; @@ -251,8 +238,7 @@ typedef union { typedef void(tBTA_DM_SEC_CBACK)(tBTA_DM_SEC_EVT event, tBTA_DM_SEC* p_data); /* Encryption callback*/ -typedef void(tBTA_DM_ENCRYPT_CBACK)(const RawAddress& bd_addr, - tBT_TRANSPORT transport, +typedef void(tBTA_DM_ENCRYPT_CBACK)(const RawAddress& bd_addr, tBT_TRANSPORT transport, tBTA_STATUS result); /******************************************************************************* @@ -268,8 +254,8 @@ typedef void(tBTA_DM_ENCRYPT_CBACK)(const RawAddress& bd_addr, * Returns void * ******************************************************************************/ -void BTA_DmBond(const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type, - tBT_TRANSPORT transport, tBT_DEVICE_TYPE device_type); +void BTA_DmBond(const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type, tBT_TRANSPORT transport, + tBT_DEVICE_TYPE device_type); /******************************************************************************* * @@ -297,8 +283,7 @@ void BTA_DmBondCancel(const RawAddress& bd_addr); * Returns void * ******************************************************************************/ -void BTA_DmPinReply(const RawAddress& bd_addr, bool accept, uint8_t pin_len, - uint8_t* p_pin); +void BTA_DmPinReply(const RawAddress& bd_addr, bool accept, uint8_t pin_len, uint8_t* p_pin); /******************************************************************************* * @@ -337,8 +322,8 @@ void BTA_DmConfirm(const RawAddress& bd_addr, bool accept); * Returns void * ******************************************************************************/ -void BTA_DmAddDevice(RawAddress bd_addr, DEV_CLASS dev_class, LinkKey link_key, - uint8_t key_type, uint8_t pin_length); +void BTA_DmAddDevice(RawAddress bd_addr, DEV_CLASS dev_class, LinkKey link_key, uint8_t key_type, + uint8_t pin_length); /******************************************************************************* * @@ -355,7 +340,6 @@ void BTA_DmAddDevice(RawAddress bd_addr, DEV_CLASS dev_class, LinkKey link_key, ******************************************************************************/ tBTA_STATUS BTA_DmRemoveDevice(const RawAddress& bd_addr); - /* BLE related API functions */ /******************************************************************************* * @@ -369,8 +353,7 @@ tBTA_STATUS BTA_DmRemoveDevice(const RawAddress& bd_addr); * Returns void * ******************************************************************************/ -void BTA_DmBleSecurityGrant(const RawAddress& bd_addr, - tBTA_DM_BLE_SEC_GRANT res); +void BTA_DmBleSecurityGrant(const RawAddress& bd_addr, tBTA_DM_BLE_SEC_GRANT res); /******************************************************************************* * @@ -386,8 +369,7 @@ void BTA_DmBleSecurityGrant(const RawAddress& bd_addr, * Returns void * ******************************************************************************/ -void BTA_DmBlePasskeyReply(const RawAddress& bd_addr, bool accept, - uint32_t passkey); +void BTA_DmBlePasskeyReply(const RawAddress& bd_addr, bool accept, uint32_t passkey); /******************************************************************************* * @@ -464,8 +446,7 @@ void BTA_DmAddBleKey(const RawAddress& bd_addr, tBTA_LE_KEY_VALUE* p_le_key, * ******************************************************************************/ void BTA_DmSetEncryption(const RawAddress& bd_addr, tBT_TRANSPORT transport, - tBTA_DM_ENCRYPT_CBACK* p_callback, - tBTM_BLE_SEC_ACT sec_act); + tBTA_DM_ENCRYPT_CBACK* p_callback, tBTM_BLE_SEC_ACT sec_act); /******************************************************************************* * diff --git a/system/bta/include/bta_vc_api.h b/system/bta/include/bta_vc_api.h index 55046a6791f..6bb515dcb90 100644 --- a/system/bta/include/bta_vc_api.h +++ b/system/bta/include/bta_vc_api.h @@ -22,7 +22,7 @@ #include "types/raw_address.h" class VolumeControl { - public: +public: virtual ~VolumeControl() = default; static void Initialize(bluetooth::vc::VolumeControlCallbacks* callbacks, @@ -39,27 +39,20 @@ class VolumeControl { virtual void Connect(const RawAddress& address) = 0; virtual void Disconnect(const RawAddress& address) = 0; virtual void Remove(const RawAddress& address) = 0; - virtual void SetVolume(std::variant addr_or_group_id, - uint8_t volume) = 0; + virtual void SetVolume(std::variant addr_or_group_id, uint8_t volume) = 0; virtual void Mute(std::variant addr_or_group_id) = 0; virtual void UnMute(std::variant addr_or_group_id) = 0; /* Volume Offset Control Service (VOCS) */ - virtual void SetExtAudioOutVolumeOffset(const RawAddress& address, - uint8_t ext_output_id, + virtual void SetExtAudioOutVolumeOffset(const RawAddress& address, uint8_t ext_output_id, int16_t offset) = 0; - virtual void GetExtAudioOutVolumeOffset(const RawAddress& address, - uint8_t ext_output_id) = 0; + virtual void GetExtAudioOutVolumeOffset(const RawAddress& address, uint8_t ext_output_id) = 0; /* Location as per Bluetooth Assigned Numbers.*/ - virtual void SetExtAudioOutLocation(const RawAddress& address, - uint8_t ext_output_id, + virtual void SetExtAudioOutLocation(const RawAddress& address, uint8_t ext_output_id, uint32_t location) = 0; - virtual void GetExtAudioOutLocation(const RawAddress& address, - uint8_t ext_output_id) = 0; - virtual void GetExtAudioOutDescription(const RawAddress& address, - uint8_t ext_output_id) = 0; - virtual void SetExtAudioOutDescription(const RawAddress& address, - uint8_t ext_output_id, + virtual void GetExtAudioOutLocation(const RawAddress& address, uint8_t ext_output_id) = 0; + virtual void GetExtAudioOutDescription(const RawAddress& address, uint8_t ext_output_id) = 0; + virtual void SetExtAudioOutDescription(const RawAddress& address, uint8_t ext_output_id, std::string descr) = 0; }; diff --git a/system/bta/include/utl.h b/system/bta/include/utl.h index 75f293ba0eb..0c48d9ce059 100644 --- a/system/bta/include/utl.h +++ b/system/bta/include/utl.h @@ -33,10 +33,9 @@ #define BTA_UTL_SET_COD_MAJOR_MINOR 0x01 #define BTA_UTL_SET_COD_SERVICE_CLASS \ 0x02 /* only set the bits in the input \ - */ + */ #define BTA_UTL_CLR_COD_SERVICE_CLASS 0x04 -#define BTA_UTL_SET_COD_ALL \ - 0x08 /* take service class as the input (may clear some set bits!!) */ +#define BTA_UTL_SET_COD_ALL 0x08 /* take service class as the input (may clear some set bits!!) */ #define BTA_UTL_INIT_COD 0x0a /***************************************************************************** diff --git a/system/bta/jv/bta_jv_act.cc b/system/bta/jv/bta_jv_act.cc index 919f9ebeab3..5c201230b5e 100644 --- a/system/bta/jv/bta_jv_act.cc +++ b/system/bta/jv/bta_jv_act.cc @@ -60,13 +60,11 @@ using namespace bluetooth; tBTA_JV_CB bta_jv_cb; std::unordered_set used_l2cap_classic_dynamic_psm; -static tBTA_JV_PCB* bta_jv_add_rfc_port(tBTA_JV_RFC_CB* p_cb, - tBTA_JV_PCB* p_pcb_open); +static tBTA_JV_PCB* bta_jv_add_rfc_port(tBTA_JV_RFC_CB* p_cb, tBTA_JV_PCB* p_pcb_open); static tBTA_JV_STATUS bta_jv_free_set_pm_profile_cb(uint32_t jv_handle); static void bta_jv_pm_conn_busy(tBTA_JV_PM_CB* p_cb); static void bta_jv_pm_conn_idle(tBTA_JV_PM_CB* p_cb); -static void bta_jv_pm_state_change(tBTA_JV_PM_CB* p_cb, - const tBTA_JV_CONN_STATE state); +static void bta_jv_pm_state_change(tBTA_JV_PM_CB* p_cb, const tBTA_JV_CONN_STATE state); static void bta_jv_reset_sniff_timer(tBTA_JV_PM_CB* p_cb); #ifndef BTA_JV_SDP_DB_SIZE @@ -78,8 +76,7 @@ static void bta_jv_reset_sniff_timer(tBTA_JV_PM_CB* p_cb); #endif static uint8_t bta_jv_sdp_raw_data[BTA_JV_SDP_RAW_DATA_SIZE]; -static tSDP_DISCOVERY_DB - bta_jv_sdp_db_data[BTA_JV_SDP_DB_SIZE / sizeof(tSDP_DISCOVERY_DB)]; +static tSDP_DISCOVERY_DB bta_jv_sdp_db_data[BTA_JV_SDP_DB_SIZE / sizeof(tSDP_DISCOVERY_DB)]; /* JV configuration structure */ struct tBTA_JV_CFG { @@ -88,11 +85,11 @@ struct tBTA_JV_CFG { uint8_t* p_sdp_raw_data; /* The data buffer to keep raw data */ tSDP_DISCOVERY_DB* p_sdp_db; /* The data buffer to keep SDP database */ } bta_jv_cfg = { - BTA_JV_SDP_RAW_DATA_SIZE, /* The size of p_sdp_raw_data */ - (BTA_JV_SDP_DB_SIZE / sizeof(tSDP_DISCOVERY_DB)) * - sizeof(tSDP_DISCOVERY_DB), /* The size of p_sdp_db_data */ - bta_jv_sdp_raw_data, /* The data buffer to keep raw data */ - bta_jv_sdp_db_data /* The data buffer to keep SDP database */ + BTA_JV_SDP_RAW_DATA_SIZE, /* The size of p_sdp_raw_data */ + (BTA_JV_SDP_DB_SIZE / sizeof(tSDP_DISCOVERY_DB)) * + sizeof(tSDP_DISCOVERY_DB), /* The size of p_sdp_db_data */ + bta_jv_sdp_raw_data, /* The data buffer to keep raw data */ + bta_jv_sdp_db_data /* The data buffer to keep SDP database */ }; tBTA_JV_CFG* p_bta_jv_cfg = &bta_jv_cfg; @@ -122,20 +119,26 @@ static int get_sec_id_used(void) { int i; int used = 0; for (i = 0; i < BTA_JV_NUM_SERVICE_ID; i++) { - if (bta_jv_cb.sec_id[i]) used++; + if (bta_jv_cb.sec_id[i]) { + used++; + } } - if (used == BTA_JV_NUM_SERVICE_ID) + if (used == BTA_JV_NUM_SERVICE_ID) { log::error("sec id exceeds the limit={}", BTA_JV_NUM_SERVICE_ID); + } return used; } static int get_rfc_cb_used(void) { int i; int used = 0; for (i = 0; i < BTA_JV_MAX_RFC_CONN; i++) { - if (bta_jv_cb.rfc_cb[i].handle) used++; + if (bta_jv_cb.rfc_cb[i].handle) { + used++; + } } - if (used == BTA_JV_MAX_RFC_CONN) + if (used == BTA_JV_MAX_RFC_CONN) { log::error("rfc ctrl block exceeds the limit={}", BTA_JV_MAX_RFC_CONN); + } return used; } @@ -213,8 +216,7 @@ static tBTA_JV_L2CAP_REASON bta_jv_from_gap_l2cap_err(uint16_t l2cap_result) { * Returns * ******************************************************************************/ -tBTA_JV_RFC_CB* bta_jv_alloc_rfc_cb(uint16_t port_handle, - tBTA_JV_PCB** pp_pcb) { +tBTA_JV_RFC_CB* bta_jv_alloc_rfc_cb(uint16_t port_handle, tBTA_JV_PCB** pp_pcb) { tBTA_JV_RFC_CB* p_cb = NULL; tBTA_JV_PCB* p_pcb; int i, j; @@ -226,7 +228,9 @@ tBTA_JV_RFC_CB* bta_jv_alloc_rfc_cb(uint16_t port_handle, p_cb->max_sess = 1; p_cb->curr_sess = 1; - for (j = 0; j < BTA_JV_MAX_RFC_SR_SESSION; j++) p_cb->rfc_hdl[j] = 0; + for (j = 0; j < BTA_JV_MAX_RFC_SR_SESSION; j++) { + p_cb->rfc_hdl[j] = 0; + } p_cb->rfc_hdl[0] = port_handle; log::verbose("port_handle={}, handle=0x{:x}", port_handle, p_cb->handle); @@ -239,8 +243,7 @@ tBTA_JV_RFC_CB* bta_jv_alloc_rfc_cb(uint16_t port_handle, } } if (p_cb == NULL) { - log::error("port_handle={} ctrl block exceeds limit:{}", port_handle, - BTA_JV_MAX_RFC_CONN); + log::error("port_handle={} ctrl block exceeds limit:{}", port_handle, BTA_JV_MAX_RFC_CONN); } return p_cb; } @@ -285,15 +288,16 @@ tBTA_JV_RFC_CB* bta_jv_rfc_port_to_cb(uint16_t port_handle) { handle = bta_jv_cb.port_cb[port_handle - 1].handle; handle &= BTA_JV_RFC_HDL_MASK; handle &= ~BTA_JV_RFCOMM_MASK; - if (handle) p_cb = &bta_jv_cb.rfc_cb[handle - 1]; + if (handle) { + p_cb = &bta_jv_cb.rfc_cb[handle - 1]; + } } else { log::warn("jv handle not found port_handle:{}", port_handle); } return p_cb; } -static tBTA_JV_STATUS bta_jv_free_rfc_cb(tBTA_JV_RFC_CB* p_cb, - tBTA_JV_PCB* p_pcb) { +static tBTA_JV_STATUS bta_jv_free_rfc_cb(tBTA_JV_RFC_CB* p_cb, tBTA_JV_PCB* p_pcb) { tBTA_JV_STATUS status = tBTA_JV_STATUS::SUCCESS; bool remove_server = false; int close_pending = 0; @@ -302,20 +306,19 @@ static tBTA_JV_STATUS bta_jv_free_rfc_cb(tBTA_JV_RFC_CB* p_cb, log::error("p_cb or p_pcb cannot be null"); return tBTA_JV_STATUS::FAILURE; } - log::verbose( - "max_sess={}, curr_sess={}, p_pcb={}, user={}, state={}, jv " - "handle=0x{:x}", - p_cb->max_sess, p_cb->curr_sess, fmt::ptr(p_pcb), p_pcb->rfcomm_slot_id, - p_pcb->state, p_pcb->handle); + log::verbose("max_sess={}, curr_sess={}, p_pcb={}, user={}, state={}, jv handle=0x{:x}", + p_cb->max_sess, p_cb->curr_sess, fmt::ptr(p_pcb), p_pcb->rfcomm_slot_id, + p_pcb->state, p_pcb->handle); - if (p_cb->curr_sess <= 0) return tBTA_JV_STATUS::SUCCESS; + if (p_cb->curr_sess <= 0) { + return tBTA_JV_STATUS::SUCCESS; + } switch (p_pcb->state) { case BTA_JV_ST_CL_CLOSING: case BTA_JV_ST_SR_CLOSING: - log::warn( - "return on closing, port state={}, scn={}, p_pcb={}, user_data={}", - p_pcb->state, p_cb->scn, fmt::ptr(p_pcb), p_pcb->rfcomm_slot_id); + log::warn("return on closing, port state={}, scn={}, p_pcb={}, user_data={}", p_pcb->state, + p_cb->scn, fmt::ptr(p_pcb), p_pcb->rfcomm_slot_id); status = tBTA_JV_STATUS::FAILURE; return status; case BTA_JV_ST_CL_OPEN: @@ -327,8 +330,8 @@ static tBTA_JV_STATUS bta_jv_free_rfc_cb(tBTA_JV_RFC_CB* p_cb, case BTA_JV_ST_SR_LISTEN: p_pcb->state = BTA_JV_ST_SR_CLOSING; remove_server = true; - log::verbose("state: BTA_JV_ST_SR_LISTEN, scn={}, user_data={}", - p_cb->scn, p_pcb->rfcomm_slot_id); + log::verbose("state: BTA_JV_ST_SR_LISTEN, scn={}, user_data={}", p_cb->scn, + p_pcb->rfcomm_slot_id); break; case BTA_JV_ST_SR_OPEN: p_pcb->state = BTA_JV_ST_SR_CLOSING; @@ -337,27 +340,26 @@ static tBTA_JV_STATUS bta_jv_free_rfc_cb(tBTA_JV_RFC_CB* p_cb, break; default: log::warn( - "failed, ignore port state= {}, scn={}, p_pcb= {}, jv handle=0x{:x}, " - "port_handle={}, user_data={}", - p_pcb->state, p_cb->scn, fmt::ptr(p_pcb), p_pcb->handle, - p_pcb->port_handle, p_pcb->rfcomm_slot_id); + "failed, ignore port state= {}, scn={}, p_pcb= {}, jv handle=0x{:x}, " + "port_handle={}, user_data={}", + p_pcb->state, p_cb->scn, fmt::ptr(p_pcb), p_pcb->handle, p_pcb->port_handle, + p_pcb->rfcomm_slot_id); status = tBTA_JV_STATUS::FAILURE; break; } if (tBTA_JV_STATUS::SUCCESS == status) { int port_status; - if (!remove_server) + if (!remove_server) { port_status = RFCOMM_RemoveConnection(p_pcb->port_handle); - else + } else { port_status = RFCOMM_RemoveServer(p_pcb->port_handle); + } if (port_status != PORT_SUCCESS) { status = tBTA_JV_STATUS::FAILURE; log::warn( - "Remove jv handle=0x{:x}, state={}, port_status={}, port_handle={}, " - "close_pending={}", - p_pcb->handle, p_pcb->state, port_status, p_pcb->port_handle, - close_pending); + "Remove jv handle=0x{:x}, state={}, port_status={}, port_handle={}, close_pending={}", + p_pcb->handle, p_pcb->state, port_status, p_pcb->port_handle, close_pending); } } if (!close_pending) { @@ -369,7 +371,9 @@ static tBTA_JV_STATUS bta_jv_free_rfc_cb(tBTA_JV_RFC_CB* p_cb, p_pcb->cong = false; p_pcb->rfcomm_slot_id = 0; int si = BTA_JV_RFC_HDL_TO_SIDX(p_pcb->handle); - if (0 <= si && si < BTA_JV_MAX_RFC_SR_SESSION) p_cb->rfc_hdl[si] = 0; + if (0 <= si && si < BTA_JV_MAX_RFC_SR_SESSION) { + p_cb->rfc_hdl[si] = 0; + } p_pcb->handle = 0; p_cb->curr_sess--; if (p_cb->curr_sess == 0) { @@ -396,8 +400,9 @@ tBTA_JV_STATUS bta_jv_free_l2c_cb(tBTA_JV_L2C_CB* p_cb) { if (BTA_JV_ST_NONE != p_cb->state) { bta_jv_free_set_pm_profile_cb((uint32_t)p_cb->handle); - if (GAP_ConnClose(p_cb->handle) != BT_PASS) + if (GAP_ConnClose(p_cb->handle) != BT_PASS) { status = tBTA_JV_STATUS::FAILURE; + } } p_cb->psm = 0; p_cb->state = BTA_JV_ST_NONE; @@ -426,8 +431,9 @@ tBTA_JV_STATUS bta_jv_free_l2c_cb(tBTA_JV_L2C_CB* p_cb) { static void bta_jv_clear_pm_cb(tBTA_JV_PM_CB* p_pm_cb, bool close_conn) { /* needs to be called if registered with bta pm, otherwise we may run out of * dm pm slots! */ - if (close_conn) + if (close_conn) { bta_sys_conn_close(BTA_ID_JV, p_pm_cb->app_id, p_pm_cb->peer_bd_addr); + } p_pm_cb->state = BTA_JV_PM_FREE_ST; p_pm_cb->app_id = BTA_JV_PM_ALL; p_pm_cb->handle = BTA_JV_PM_HANDLE_CLEAR; @@ -455,15 +461,16 @@ static tBTA_JV_STATUS bta_jv_free_set_pm_profile_cb(uint32_t jv_handle) { if ((bta_jv_cb.pm_cb[i].state != BTA_JV_PM_FREE_ST) && (jv_handle == bta_jv_cb.pm_cb[i].handle)) { for (j = 0; j < BTA_JV_PM_MAX_NUM; j++) { - if (bta_jv_cb.pm_cb[j].peer_bd_addr == bta_jv_cb.pm_cb[i].peer_bd_addr) + if (bta_jv_cb.pm_cb[j].peer_bd_addr == bta_jv_cb.pm_cb[i].peer_bd_addr) { bd_counter++; - if (bta_jv_cb.pm_cb[j].app_id == bta_jv_cb.pm_cb[i].app_id) + } + if (bta_jv_cb.pm_cb[j].app_id == bta_jv_cb.pm_cb[i].app_id) { appid_counter++; + } } - log::verbose( - "jv_handle=0x{:x}, idx={}app_id={}, bd_counter={}, appid_counter={}", - jv_handle, i, bta_jv_cb.pm_cb[i].app_id, bd_counter, appid_counter); + log::verbose("jv_handle=0x{:x}, idx={}app_id={}, bd_counter={}, appid_counter={}", jv_handle, + i, bta_jv_cb.pm_cb[i].app_id, bd_counter, appid_counter); if (bd_counter > 1) { bta_jv_pm_conn_idle(&bta_jv_cb.pm_cb[i]); } @@ -475,27 +482,25 @@ static tBTA_JV_STATUS bta_jv_free_set_pm_profile_cb(uint32_t jv_handle) { } if (BTA_JV_RFCOMM_MASK & jv_handle) { - uint32_t hi = - ((jv_handle & BTA_JV_RFC_HDL_MASK) & ~BTA_JV_RFCOMM_MASK) - 1; + uint32_t hi = ((jv_handle & BTA_JV_RFC_HDL_MASK) & ~BTA_JV_RFCOMM_MASK) - 1; uint32_t si = BTA_JV_RFC_HDL_TO_SIDX(jv_handle); if (hi < BTA_JV_MAX_RFC_CONN && bta_jv_cb.rfc_cb[hi].p_cback && - si < BTA_JV_MAX_RFC_SR_SESSION && - bta_jv_cb.rfc_cb[hi].rfc_hdl[si]) { - tBTA_JV_PCB* p_pcb = - bta_jv_rfc_port_to_pcb(bta_jv_cb.rfc_cb[hi].rfc_hdl[si]); + si < BTA_JV_MAX_RFC_SR_SESSION && bta_jv_cb.rfc_cb[hi].rfc_hdl[si]) { + tBTA_JV_PCB* p_pcb = bta_jv_rfc_port_to_pcb(bta_jv_cb.rfc_cb[hi].rfc_hdl[si]); if (p_pcb) { - if (NULL == p_pcb->p_pm_cb) - log::warn( - "jv_handle=0x{:x}, port_handle={}, i={}, no link to pm_cb?", - jv_handle, p_pcb->port_handle, i); + if (NULL == p_pcb->p_pm_cb) { + log::warn("jv_handle=0x{:x}, port_handle={}, i={}, no link to pm_cb?", jv_handle, + p_pcb->port_handle, i); + } p_cb = &p_pcb->p_pm_cb; } } } else { if (jv_handle < BTA_JV_MAX_L2C_CONN) { tBTA_JV_L2C_CB* p_l2c_cb = &bta_jv_cb.l2c_cb[jv_handle]; - if (NULL == p_l2c_cb->p_pm_cb) + if (NULL == p_l2c_cb->p_pm_cb) { log::warn("jv_handle=0x{:x}, i={} no link to pm_cb?", jv_handle, i); + } p_cb = &p_l2c_cb->p_pm_cb; } } @@ -517,8 +522,7 @@ static tBTA_JV_STATUS bta_jv_free_set_pm_profile_cb(uint32_t jv_handle) { * Returns pointer to allocated cb or NULL in case of failure * ******************************************************************************/ -static tBTA_JV_PM_CB* bta_jv_alloc_set_pm_profile_cb(uint32_t jv_handle, - tBTA_JV_PM_ID app_id) { +static tBTA_JV_PM_CB* bta_jv_alloc_set_pm_profile_cb(uint32_t jv_handle, tBTA_JV_PM_ID app_id) { bool bRfcHandle = (jv_handle & BTA_JV_RFCOMM_MASK) != 0; RawAddress peer_bd_addr = RawAddress::kEmpty; int i, j; @@ -533,8 +537,7 @@ static tBTA_JV_PM_CB* bta_jv_alloc_set_pm_profile_cb(uint32_t jv_handle, if (jv_handle == bta_jv_cb.port_cb[j].handle) { pp_cb = &bta_jv_cb.port_cb[j].p_pm_cb; if (PORT_SUCCESS != - PORT_CheckConnection(bta_jv_cb.port_cb[j].port_handle, - &peer_bd_addr, NULL)) { + PORT_CheckConnection(bta_jv_cb.port_cb[j].port_handle, &peer_bd_addr, NULL)) { i = BTA_JV_PM_MAX_NUM; } break; @@ -545,19 +548,18 @@ static tBTA_JV_PM_CB* bta_jv_alloc_set_pm_profile_cb(uint32_t jv_handle, for (j = 0; j < BTA_JV_MAX_L2C_CONN; j++) { if (jv_handle == bta_jv_cb.l2c_cb[j].handle) { pp_cb = &bta_jv_cb.l2c_cb[j].p_pm_cb; - const RawAddress* p_bd_addr = - GAP_ConnGetRemoteAddr((uint16_t)jv_handle); - if (p_bd_addr) + const RawAddress* p_bd_addr = GAP_ConnGetRemoteAddr((uint16_t)jv_handle); + if (p_bd_addr) { peer_bd_addr = *p_bd_addr; - else + } else { i = BTA_JV_PM_MAX_NUM; + } break; } } } - log::verbose( - "handle=0x{:x}, app_id={}, idx={}, BTA_JV_PM_MAX_NUM={}, pp_cb={}", - jv_handle, app_id, i, BTA_JV_PM_MAX_NUM, fmt::ptr(pp_cb)); + log::verbose("handle=0x{:x}, app_id={}, idx={}, BTA_JV_PM_MAX_NUM={}, pp_cb={}", jv_handle, + app_id, i, BTA_JV_PM_MAX_NUM, fmt::ptr(pp_cb)); break; } } @@ -597,26 +599,30 @@ bool bta_jv_check_psm(uint16_t psm) { case BT_PSM_TCS: case BT_PSM_CTP: - if (!bta_sys_is_register(BTA_ID_CT) && - !bta_sys_is_register(BTA_ID_CG)) + if (!bta_sys_is_register(BTA_ID_CT) && !bta_sys_is_register(BTA_ID_CG)) { ret = true; + } break; case BT_PSM_BNEP: /* F */ - if (!bta_sys_is_register(BTA_ID_PAN)) ret = true; + if (!bta_sys_is_register(BTA_ID_PAN)) { + ret = true; + } break; case BT_PSM_HIDC: case BT_PSM_HIDI: // FIX: allow HID Device and HID Host to coexist - if (!bta_sys_is_register(BTA_ID_HD) || - !bta_sys_is_register(BTA_ID_HH)) + if (!bta_sys_is_register(BTA_ID_HD) || !bta_sys_is_register(BTA_ID_HH)) { ret = true; + } break; case AVCT_PSM: /* 0x17 */ case AVDT_PSM: /* 0x19 */ - if (!bta_sys_is_register(BTA_ID_AV)) ret = true; + if (!bta_sys_is_register(BTA_ID_AV)) { + ret = true; + } break; default: @@ -635,7 +641,7 @@ void bta_jv_enable(tBTA_JV_DM_CBACK* p_cback) { bta_jv_cb.p_dm_cback = p_cback; if (bta_jv_cb.p_dm_cback) { tBTA_JV bta_jv = { - .status = tBTA_JV_STATUS::SUCCESS, + .status = tBTA_JV_STATUS::SUCCESS, }; bta_jv_cb.p_dm_cback(BTA_JV_ENABLE_EVT, &bta_jv, 0); } @@ -654,8 +660,7 @@ void bta_jv_disable() { log::info(""); } * If no free PSMs exist, 0 will be returned. */ static uint16_t bta_jv_get_free_psm() { - const int cnt = - sizeof(bta_jv_cb.free_psm_list) / sizeof(bta_jv_cb.free_psm_list[0]); + const int cnt = sizeof(bta_jv_cb.free_psm_list) / sizeof(bta_jv_cb.free_psm_list[0]); for (int i = 0; i < cnt; i++) { uint16_t psm = bta_jv_cb.free_psm_list[i]; if (psm != 0) { @@ -669,8 +674,7 @@ static uint16_t bta_jv_get_free_psm() { static void bta_jv_set_free_psm(uint16_t psm) { int free_index = -1; - const int cnt = - sizeof(bta_jv_cb.free_psm_list) / sizeof(bta_jv_cb.free_psm_list[0]); + const int cnt = sizeof(bta_jv_cb.free_psm_list) / sizeof(bta_jv_cb.free_psm_list[0]); for (int i = 0; i < cnt; i++) { if (bta_jv_cb.free_psm_list[i] == 0) { free_index = i; @@ -700,22 +704,24 @@ static uint16_t bta_jv_allocate_l2cap_classic_psm() { } /* if psm is in range of reserved BRCM Aware features */ - if ((BRCM_RESERVED_PSM_START <= psm) && (psm <= BRCM_RESERVED_PSM_END)) + if ((BRCM_RESERVED_PSM_START <= psm) && (psm <= BRCM_RESERVED_PSM_END)) { continue; + } /* make sure the newlly allocated psm is not used right now */ - if (used_l2cap_classic_dynamic_psm.count(psm) == 0) done = true; + if (used_l2cap_classic_dynamic_psm.count(psm) == 0) { + done = true; + } } bta_jv_cb.dyn_psm = psm; - return (psm); + return psm; } /** Obtain a free SCN (Server Channel Number) (RFCOMM channel or L2CAP PSM) */ -void bta_jv_get_channel_id( - tBTA_JV_CONN_TYPE type /* One of BTA_JV_CONN_TYPE_ */, - int32_t channel /* optionally request a specific channel */, - uint32_t l2cap_socket_id, uint32_t rfcomm_slot_id) { +void bta_jv_get_channel_id(tBTA_JV_CONN_TYPE type /* One of BTA_JV_CONN_TYPE_ */, + int32_t channel /* optionally request a specific channel */, + uint32_t l2cap_socket_id, uint32_t rfcomm_slot_id) { uint16_t psm = 0; switch (type) { @@ -765,8 +771,7 @@ void bta_jv_get_channel_id( } /** free a SCN */ -void bta_jv_free_scn(tBTA_JV_CONN_TYPE type /* One of BTA_JV_CONN_TYPE_ */, - uint16_t scn) { +void bta_jv_free_scn(tBTA_JV_CONN_TYPE type /* One of BTA_JV_CONN_TYPE_ */, uint16_t scn) { switch (type) { case tBTA_JV_CONN_TYPE::RFCOMM: BTA_FreeSCN(scn); @@ -792,103 +797,88 @@ void bta_jv_free_scn(tBTA_JV_CONN_TYPE type /* One of BTA_JV_CONN_TYPE_ */, * Returns void * ******************************************************************************/ -static void bta_jv_start_discovery_cback(uint32_t rfcomm_slot_id, - const RawAddress& bd_addr, +static void bta_jv_start_discovery_cback(uint32_t rfcomm_slot_id, const RawAddress& bd_addr, tSDP_RESULT result) { if (!bta_jv_cb.sdp_cb.sdp_active) { - log::warn( - "Received unexpected service discovery callback bd_addr:{} result:{}", - bd_addr, sdp_result_text(result), bta_jv_cb.sdp_cb.sdp_active); + log::warn("Received unexpected service discovery callback bd_addr:{} result:{}", bd_addr, + sdp_result_text(result), bta_jv_cb.sdp_cb.sdp_active); } if (bta_jv_cb.sdp_cb.bd_addr != bta_jv_cb.sdp_cb.bd_addr) { log::warn( - "Received incorrect service discovery callback expected_bd_addr:{} " - "actual_bd_addr:{} result:{}", - bta_jv_cb.sdp_cb.bd_addr, bd_addr, sdp_result_text(result), - bta_jv_cb.sdp_cb.sdp_active); + "Received incorrect service discovery callback expected_bd_addr:{} " + "actual_bd_addr:{} result:{}", + bta_jv_cb.sdp_cb.bd_addr, bd_addr, sdp_result_text(result), + bta_jv_cb.sdp_cb.sdp_active); } if (bta_jv_cb.p_dm_cback) { tBTA_JV bta_jv = { - .disc_comp = - { - .status = tBTA_JV_STATUS::FAILURE, - .scn = 0, - }, + .disc_comp = + { + .status = tBTA_JV_STATUS::FAILURE, + .scn = 0, + }, }; if (result == SDP_SUCCESS || result == SDP_DB_FULL) { - log::info( - "Received service discovery callback success bd_addr:{} result:{}", - bd_addr, sdp_result_text(result)); + log::info("Received service discovery callback success bd_addr:{} result:{}", bd_addr, + sdp_result_text(result)); tSDP_PROTOCOL_ELEM pe; tSDP_DISC_REC* p_sdp_rec = NULL; p_sdp_rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceUUIDInDb( - p_bta_jv_cfg->p_sdp_db, bta_jv_cb.sdp_cb.uuid, p_sdp_rec); - log::verbose("bta_jv_cb.uuid={} p_sdp_rec={}", bta_jv_cb.sdp_cb.uuid, - fmt::ptr(p_sdp_rec)); - if (p_sdp_rec && - get_legacy_stack_sdp_api()->record.SDP_FindProtocolListElemInRec( - p_sdp_rec, UUID_PROTOCOL_RFCOMM, &pe)) { + p_bta_jv_cfg->p_sdp_db, bta_jv_cb.sdp_cb.uuid, p_sdp_rec); + log::verbose("bta_jv_cb.uuid={} p_sdp_rec={}", bta_jv_cb.sdp_cb.uuid, fmt::ptr(p_sdp_rec)); + if (p_sdp_rec && get_legacy_stack_sdp_api()->record.SDP_FindProtocolListElemInRec( + p_sdp_rec, UUID_PROTOCOL_RFCOMM, &pe)) { bta_jv = { - .disc_comp = - { - .status = tBTA_JV_STATUS::SUCCESS, - .scn = (uint8_t)pe.params[0], - }, + .disc_comp = + { + .status = tBTA_JV_STATUS::SUCCESS, + .scn = (uint8_t)pe.params[0], + }, }; } } else { - log::warn( - "Received service discovery callback failed bd_addr:{} result:{}", - bd_addr, sdp_result_text(result)); + log::warn("Received service discovery callback failed bd_addr:{} result:{}", bd_addr, + sdp_result_text(result)); } - log::info( - "Issuing service discovery complete callback bd_addr:{} result:{} " - "status:{} scn:{}", - bd_addr, sdp_result_text(result), - bta_jv_status_text(bta_jv.disc_comp.status), bta_jv.disc_comp.scn); + log::info("Issuing service discovery complete callback bd_addr:{} result:{} status:{} scn:{}", + bd_addr, sdp_result_text(result), bta_jv_status_text(bta_jv.disc_comp.status), + bta_jv.disc_comp.scn); bta_jv_cb.p_dm_cback(BTA_JV_DISCOVERY_COMP_EVT, &bta_jv, rfcomm_slot_id); } else { - log::warn( - "Received service discovery callback when disabled bd_addr:{} " - "result:{}", - bd_addr, sdp_result_text(result)); + log::warn("Received service discovery callback when disabled bd_addr:{} result:{}", bd_addr, + sdp_result_text(result)); } bta_jv_cb.sdp_cb = {}; } /* Discovers services on a remote device */ void bta_jv_start_discovery(const RawAddress& bd_addr, uint16_t num_uuid, - bluetooth::Uuid* uuid_list, - uint32_t rfcomm_slot_id) { + bluetooth::Uuid* uuid_list, uint32_t rfcomm_slot_id) { log::assert_that(uuid_list != nullptr, "assert failed: uuid_list != nullptr"); if (bta_jv_cb.sdp_cb.sdp_active) { log::warn( - "Unable to start discovery as already in progress active_bd_addr{} " - "request_bd_addr:{} num:uuid:{} rfcomm_slot_id:{}", - bta_jv_cb.sdp_cb.bd_addr, bd_addr, num_uuid, rfcomm_slot_id); + "Unable to start discovery as already in progress active_bd_addr{} " + "request_bd_addr:{} num:uuid:{} rfcomm_slot_id:{}", + bta_jv_cb.sdp_cb.bd_addr, bd_addr, num_uuid, rfcomm_slot_id); if (bta_jv_cb.p_dm_cback) { tBTA_JV bta_jv = { - .status = tBTA_JV_STATUS::BUSY, + .status = tBTA_JV_STATUS::BUSY, }; bta_jv_cb.p_dm_cback(BTA_JV_DISCOVERY_COMP_EVT, &bta_jv, rfcomm_slot_id); } else { log::warn( - "bta::jv module DISABLED so unable to inform caller service " - "discovery is " - "unavailable"); + "bta::jv module DISABLED so unable to inform caller service discovery is " + "unavailable"); } return; } /* init the database/set up the filter */ if (!get_legacy_stack_sdp_api()->service.SDP_InitDiscoveryDb( - p_bta_jv_cfg->p_sdp_db, p_bta_jv_cfg->sdp_db_size, num_uuid, - uuid_list, 0, NULL)) { - log::warn( - "Unable to initialize service discovery db bd_addr:{} num:uuid:{} " - "rfcomm_slot_id:{}", - bd_addr, num_uuid, rfcomm_slot_id); + p_bta_jv_cfg->p_sdp_db, p_bta_jv_cfg->sdp_db_size, num_uuid, uuid_list, 0, NULL)) { + log::warn("Unable to initialize service discovery db bd_addr:{} num:uuid:{} rfcomm_slot_id:{}", + bd_addr, num_uuid, rfcomm_slot_id); } /* tell SDP to keep the raw data */ @@ -897,32 +887,29 @@ void bta_jv_start_discovery(const RawAddress& bd_addr, uint16_t num_uuid, // Optimistically set this as active bta_jv_cb.sdp_cb = { - .sdp_active = true, - .bd_addr = bd_addr, - .uuid = uuid_list[0], + .sdp_active = true, + .bd_addr = bd_addr, + .uuid = uuid_list[0], }; if (!get_legacy_stack_sdp_api()->service.SDP_ServiceSearchAttributeRequest2( - bd_addr, p_bta_jv_cfg->p_sdp_db, - base::BindRepeating(&bta_jv_start_discovery_cback, rfcomm_slot_id))) { + bd_addr, p_bta_jv_cfg->p_sdp_db, + base::BindRepeating(&bta_jv_start_discovery_cback, rfcomm_slot_id))) { bta_jv_cb.sdp_cb = {}; - log::warn( - "Unable to original service discovery bd_addr:{} num:uuid:{} " - "rfcomm_slot_id:{}", - bd_addr, num_uuid, rfcomm_slot_id); + log::warn("Unable to original service discovery bd_addr:{} num:uuid:{} rfcomm_slot_id:{}", + bd_addr, num_uuid, rfcomm_slot_id); /* failed to start SDP. report the failure right away */ if (bta_jv_cb.p_dm_cback) { tBTA_JV bta_jv = { - .status = tBTA_JV_STATUS::FAILURE, + .status = tBTA_JV_STATUS::FAILURE, }; bta_jv_cb.p_dm_cback(BTA_JV_DISCOVERY_COMP_EVT, &bta_jv, rfcomm_slot_id); } else { log::warn("No callback set for discovery complete event"); } } else { - log::info( - "Started service discovery bd_addr:{} num_uuid:{} rfcomm_slot_id:{}", - bd_addr, num_uuid, rfcomm_slot_id); + log::info("Started service discovery bd_addr:{} num_uuid:{} rfcomm_slot_id:{}", bd_addr, + num_uuid, rfcomm_slot_id); } } @@ -957,12 +944,13 @@ void bta_jv_delete_record(uint32_t handle) { * Returns void * ******************************************************************************/ -static void bta_jv_l2cap_client_cback(uint16_t gap_handle, uint16_t event, - tGAP_CB_DATA* data) { +static void bta_jv_l2cap_client_cback(uint16_t gap_handle, uint16_t event, tGAP_CB_DATA* data) { tBTA_JV_L2C_CB* p_cb = &bta_jv_cb.l2c_cb[gap_handle]; tBTA_JV evt_data; - if (gap_handle >= BTA_JV_MAX_L2C_CONN && !p_cb->p_cback) return; + if (gap_handle >= BTA_JV_MAX_L2C_CONN && !p_cb->p_cback) { + return; + } log::verbose("gap_handle={}, evt=0x{:x}", gap_handle, event); evt_data.l2c_open.status = tBTA_JV_STATUS::SUCCESS; @@ -984,9 +972,8 @@ static void bta_jv_l2cap_client_cback(uint16_t gap_handle, uint16_t event, p_cb->state = BTA_JV_ST_NONE; bta_jv_free_sec_id(&p_cb->sec_id); evt_data.l2c_close.async = true; - evt_data.l2c_close.reason = - data != nullptr ? bta_jv_from_gap_l2cap_err(data->l2cap_result) - : BTA_JV_L2CAP_REASON_EMPTY; + evt_data.l2c_close.reason = data != nullptr ? bta_jv_from_gap_l2cap_err(data->l2cap_result) + : BTA_JV_L2CAP_REASON_EMPTY; p_cb->p_cback(BTA_JV_L2CAP_CLOSE_EVT, &evt_data, p_cb->l2cap_socket_id); p_cb->p_cback = NULL; break; @@ -995,8 +982,7 @@ static void bta_jv_l2cap_client_cback(uint16_t gap_handle, uint16_t event, evt_data.data_ind.handle = gap_handle; /* Reset idle timer to avoid requesting sniff mode while receiving data */ bta_jv_pm_conn_busy(p_cb->p_pm_cb); - p_cb->p_cback(BTA_JV_L2CAP_DATA_IND_EVT, &evt_data, - p_cb->l2cap_socket_id); + p_cb->p_cback(BTA_JV_L2CAP_DATA_IND_EVT, &evt_data, p_cb->l2cap_socket_id); bta_jv_pm_conn_idle(p_cb->p_pm_cb); break; @@ -1017,12 +1003,10 @@ static void bta_jv_l2cap_client_cback(uint16_t gap_handle, uint16_t event, } /* makes an l2cap client connection */ -void bta_jv_l2cap_connect(tBTA_JV_CONN_TYPE type, tBTA_SEC sec_mask, - uint16_t remote_psm, uint16_t rx_mtu, - const RawAddress& peer_bd_addr, +void bta_jv_l2cap_connect(tBTA_JV_CONN_TYPE type, tBTA_SEC sec_mask, uint16_t remote_psm, + uint16_t rx_mtu, const RawAddress& peer_bd_addr, std::unique_ptr cfg_param, - std::unique_ptr ertm_info, - tBTA_JV_L2CAP_CBACK* p_cback, + std::unique_ptr ertm_info, tBTA_JV_L2CAP_CBACK* p_cback, uint32_t l2cap_socket_id) { uint16_t handle = GAP_INVALID_HANDLE; @@ -1044,13 +1028,11 @@ void bta_jv_l2cap_connect(tBTA_JV_CONN_TYPE type, tBTA_SEC sec_mask, if (sec_id) { /* PSM checking is not required for LE COC */ - if ((type != tBTA_JV_CONN_TYPE::L2CAP) || - (bta_jv_check_psm(remote_psm))) /* allowed */ + if ((type != tBTA_JV_CONN_TYPE::L2CAP) || (bta_jv_check_psm(remote_psm))) /* allowed */ { // Given a client socket type // return the associated transport - const tBT_TRANSPORT transport = - [](tBTA_JV_CONN_TYPE type) -> tBT_TRANSPORT { + const tBT_TRANSPORT transport = [](tBTA_JV_CONN_TYPE type) -> tBT_TRANSPORT { switch (type) { case tBTA_JV_CONN_TYPE::L2CAP: return BT_TRANSPORT_BR_EDR; @@ -1065,9 +1047,8 @@ void bta_jv_l2cap_connect(tBTA_JV_CONN_TYPE type, tBTA_SEC sec_mask, }(type); uint16_t max_mps = 0xffff; // Let GAP_ConnOpen set the max_mps. - handle = GAP_ConnOpen("", sec_id, 0, &peer_bd_addr, remote_psm, max_mps, - &cfg, ertm_info.get(), sec_mask, - bta_jv_l2cap_client_cback, transport); + handle = GAP_ConnOpen("", sec_id, 0, &peer_bd_addr, remote_psm, max_mps, &cfg, + ertm_info.get(), sec_mask, bta_jv_l2cap_client_cback, transport); if (handle != GAP_INVALID_HANDLE) { evt_data.status = tBTA_JV_STATUS::SUCCESS; } @@ -1121,14 +1102,15 @@ void bta_jv_l2cap_close(uint32_t handle, tBTA_JV_L2C_CB* p_cb) { * Returns void * ******************************************************************************/ -static void bta_jv_l2cap_server_cback(uint16_t gap_handle, uint16_t event, - tGAP_CB_DATA* data) { +static void bta_jv_l2cap_server_cback(uint16_t gap_handle, uint16_t event, tGAP_CB_DATA* data) { tBTA_JV_L2C_CB* p_cb = &bta_jv_cb.l2c_cb[gap_handle]; tBTA_JV evt_data; tBTA_JV_L2CAP_CBACK* p_cback; uint32_t socket_id; - if (gap_handle >= BTA_JV_MAX_L2C_CONN && !p_cb->p_cback) return; + if (gap_handle >= BTA_JV_MAX_L2C_CONN && !p_cb->p_cback) { + return; + } log::verbose("gap_handle={}, evt=0x{:x}", gap_handle, event); evt_data.l2c_open.status = tBTA_JV_STATUS::SUCCESS; @@ -1159,8 +1141,7 @@ static void bta_jv_l2cap_server_cback(uint16_t gap_handle, uint16_t event, evt_data.data_ind.handle = gap_handle; /* Reset idle timer to avoid requesting sniff mode while receiving data */ bta_jv_pm_conn_busy(p_cb->p_pm_cb); - p_cb->p_cback(BTA_JV_L2CAP_DATA_IND_EVT, &evt_data, - p_cb->l2cap_socket_id); + p_cb->p_cback(BTA_JV_L2CAP_DATA_IND_EVT, &evt_data, p_cb->l2cap_socket_id); bta_jv_pm_conn_idle(p_cb->p_pm_cb); break; @@ -1181,12 +1162,10 @@ static void bta_jv_l2cap_server_cback(uint16_t gap_handle, uint16_t event, } /** starts an L2CAP server */ -void bta_jv_l2cap_start_server(tBTA_JV_CONN_TYPE type, tBTA_SEC sec_mask, - uint16_t local_psm, uint16_t rx_mtu, - std::unique_ptr cfg_param, +void bta_jv_l2cap_start_server(tBTA_JV_CONN_TYPE type, tBTA_SEC sec_mask, uint16_t local_psm, + uint16_t rx_mtu, std::unique_ptr cfg_param, std::unique_ptr ertm_info, - tBTA_JV_L2CAP_CBACK* p_cback, - uint32_t l2cap_socket_id) { + tBTA_JV_L2CAP_CBACK* p_cback, uint32_t l2cap_socket_id) { uint16_t handle; tBTA_JV_L2CAP_START evt_data; @@ -1225,12 +1204,10 @@ void bta_jv_l2cap_start_server(tBTA_JV_CONN_TYPE type, tBTA_SEC sec_mask, return BT_TRANSPORT_AUTO; }(type); - if (0 == sec_id || - ((type == tBTA_JV_CONN_TYPE::L2CAP) && (!bta_jv_check_psm(local_psm))) || - (handle = GAP_ConnOpen("JV L2CAP", sec_id, 1, nullptr, local_psm, max_mps, - &cfg, ertm_info.get(), sec_mask, - bta_jv_l2cap_server_cback, transport)) == - GAP_INVALID_HANDLE) { + if (0 == sec_id || ((type == tBTA_JV_CONN_TYPE::L2CAP) && (!bta_jv_check_psm(local_psm))) || + (handle = GAP_ConnOpen("JV L2CAP", sec_id, 1, nullptr, local_psm, max_mps, &cfg, + ertm_info.get(), sec_mask, bta_jv_l2cap_server_cback, transport)) == + GAP_INVALID_HANDLE) { bta_jv_free_sec_id(&sec_id); evt_data.status = tBTA_JV_STATUS::FAILURE; } else { @@ -1254,8 +1231,7 @@ void bta_jv_l2cap_start_server(tBTA_JV_CONN_TYPE type, tBTA_SEC sec_mask, } /* stops an L2CAP server */ -void bta_jv_l2cap_stop_server(uint16_t /* local_psm */, - uint32_t l2cap_socket_id) { +void bta_jv_l2cap_stop_server(uint16_t /* local_psm */, uint32_t l2cap_socket_id) { for (int i = 0; i < BTA_JV_MAX_L2C_CONN; i++) { if (bta_jv_cb.l2c_cb[i].l2cap_socket_id == l2cap_socket_id) { tBTA_JV_L2C_CB* p_cb = &bta_jv_cb.l2c_cb[i]; @@ -1275,8 +1251,8 @@ void bta_jv_l2cap_stop_server(uint16_t /* local_psm */, } /* Write data to an L2CAP connection */ -void bta_jv_l2cap_write(uint32_t handle, uint32_t req_id, BT_HDR* msg, - uint32_t user_id, tBTA_JV_L2C_CB* p_cb) { +void bta_jv_l2cap_write(uint32_t handle, uint32_t req_id, BT_HDR* msg, uint32_t user_id, + tBTA_JV_L2C_CB* p_cb) { /* As we check this callback exists before the tBTA_JV_API_L2CAP_WRITE can be * send through the API this check should not be needed. But the API is not * designed to be used (safely at least) in a multi-threaded scheduler, hence @@ -1316,8 +1292,9 @@ void bta_jv_l2cap_write(uint32_t handle, uint32_t req_id, BT_HDR* msg, if (evt_data.cong) { osi_free(msg); } else { - if (GAP_ConnWriteData(handle, msg) == BT_PASS) + if (GAP_ConnWriteData(handle, msg) == BT_PASS) { evt_data.status = tBTA_JV_STATUS::SUCCESS; + } } tBTA_JV bta_jv; @@ -1335,18 +1312,15 @@ void bta_jv_l2cap_write(uint32_t handle, uint32_t req_id, BT_HDR* msg, * Returns void * ******************************************************************************/ -static int bta_jv_port_data_co_cback(uint16_t port_handle, uint8_t* buf, - uint16_t len, int type) { +static int bta_jv_port_data_co_cback(uint16_t port_handle, uint8_t* buf, uint16_t len, int type) { tBTA_JV_RFC_CB* p_cb = bta_jv_rfc_port_to_cb(port_handle); tBTA_JV_PCB* p_pcb = bta_jv_rfc_port_to_pcb(port_handle); - log::verbose("p_cb={}, p_pcb={}, len={}, type={}", fmt::ptr(p_cb), - fmt::ptr(p_pcb), len, type); + log::verbose("p_cb={}, p_pcb={}, len={}, type={}", fmt::ptr(p_cb), fmt::ptr(p_pcb), len, type); if (p_pcb != NULL) { switch (type) { case DATA_CO_CALLBACK_TYPE_INCOMING: // Reset sniff timer when receiving data by sysproxy - if (osi_property_get_bool("bluetooth.rfcomm.sysproxy.rx.exit_sniff", - false)) { + if (osi_property_get_bool("bluetooth.rfcomm.sysproxy.rx.exit_sniff", false)) { bta_jv_reset_sniff_timer(p_pcb->p_pm_cb); } return bta_co_rfc_data_incoming(p_pcb->rfcomm_slot_id, (BT_HDR*)buf); @@ -1372,8 +1346,7 @@ static int bta_jv_port_data_co_cback(uint16_t port_handle, uint8_t* buf, * Returns void * ******************************************************************************/ -static void bta_jv_port_mgmt_cl_cback(const tPORT_RESULT code, - uint16_t port_handle) { +static void bta_jv_port_mgmt_cl_cback(const tPORT_RESULT code, uint16_t port_handle) { tBTA_JV_RFC_CB* p_cb = bta_jv_rfc_port_to_cb(port_handle); tBTA_JV_PCB* p_pcb = bta_jv_rfc_port_to_pcb(port_handle); RawAddress rem_bda = RawAddress::kEmpty; @@ -1384,39 +1357,36 @@ static void bta_jv_port_mgmt_cl_cback(const tPORT_RESULT code, log::warn("p_cb is NULL, code={}, port_handle={}", code, port_handle); return; } else if (p_cb->p_cback == NULL) { - log::warn("p_cb->p_cback is null, code={}, port_handle={}", code, - port_handle); + log::warn("p_cb->p_cback is null, code={}, port_handle={}", code, port_handle); return; } - log::verbose("code={}, port_handle={}, handle={}", code, port_handle, - p_cb->handle); + log::verbose("code={}, port_handle={}, handle={}", code, port_handle, p_cb->handle); if (PORT_CheckConnection(port_handle, &rem_bda, &lcid) != PORT_SUCCESS) { - log::warn("Unable to check RFCOMM connection peer:{} handle:{}", rem_bda, - port_handle); + log::warn("Unable to check RFCOMM connection peer:{} handle:{}", rem_bda, port_handle); } if (code == PORT_SUCCESS) { tBTA_JV evt_data = { - .rfc_open = - { - .status = tBTA_JV_STATUS::SUCCESS, - .handle = p_cb->handle, - .rem_bda = rem_bda, - }, + .rfc_open = + { + .status = tBTA_JV_STATUS::SUCCESS, + .handle = p_cb->handle, + .rem_bda = rem_bda, + }, }; p_pcb->state = BTA_JV_ST_CL_OPEN; p_cb->p_cback(BTA_JV_RFCOMM_OPEN_EVT, &evt_data, p_pcb->rfcomm_slot_id); } else { tBTA_JV evt_data = { - .rfc_close = - { - .status = tBTA_JV_STATUS::FAILURE, - .port_status = code, - .handle = p_cb->handle, - .async = (p_pcb->state == BTA_JV_ST_CL_CLOSING) ? false : true, - }, + .rfc_close = + { + .status = tBTA_JV_STATUS::FAILURE, + .port_status = code, + .handle = p_cb->handle, + .async = (p_pcb->state == BTA_JV_ST_CL_CLOSING) ? false : true, + }, }; // p_pcb->state = BTA_JV_ST_NONE; // p_pcb->cong = false; @@ -1441,10 +1411,11 @@ static void bta_jv_port_event_cl_cback(uint32_t code, uint16_t port_handle) { tBTA_JV evt_data; log::verbose("port_handle={}", port_handle); - if (NULL == p_cb || NULL == p_cb->p_cback) return; + if (NULL == p_cb || NULL == p_cb->p_cback) { + return; + } - log::verbose("code=0x{:x}, port_handle={}, handle={}", code, port_handle, - p_cb->handle); + log::verbose("code=0x{:x}, port_handle={}, handle={}", code, port_handle, p_cb->handle); if (code & PORT_EV_RXCHAR) { evt_data.data_ind.handle = p_cb->handle; p_cb->p_cback(BTA_JV_RFCOMM_DATA_IND_EVT, &evt_data, p_pcb->rfcomm_slot_id); @@ -1464,22 +1435,20 @@ static void bta_jv_port_event_cl_cback(uint32_t code, uint16_t port_handle) { } /* Client initiates an RFCOMM connection */ -void bta_jv_rfcomm_connect(tBTA_SEC sec_mask, uint8_t remote_scn, - const RawAddress& peer_bd_addr, - tBTA_JV_RFCOMM_CBACK* p_cback, - uint32_t rfcomm_slot_id) { +void bta_jv_rfcomm_connect(tBTA_SEC sec_mask, uint8_t remote_scn, const RawAddress& peer_bd_addr, + tBTA_JV_RFCOMM_CBACK* p_cback, uint32_t rfcomm_slot_id) { uint16_t handle = 0; uint32_t event_mask = BTA_JV_RFC_EV_MASK; tPORT_STATE port_state; tBTA_JV bta_jv = { - .rfc_cl_init = - { - .status = tBTA_JV_STATUS::SUCCESS, - .handle = 0, - .sec_id = 0, - .use_co = false, - }, + .rfc_cl_init = + { + .status = tBTA_JV_STATUS::SUCCESS, + .handle = 0, + .sec_id = 0, + .use_co = false, + }, }; if (com::android::bluetooth::flags::rfcomm_always_use_mitm()) { @@ -1487,14 +1456,13 @@ void bta_jv_rfcomm_connect(tBTA_SEC sec_mask, uint8_t remote_scn, // secure RFCOMM connection will be authenticated with MTIM protection // while creating the L2CAP connection. get_btm_client_interface().security.BTM_SetSecurityLevel( - true, "RFC_MUX", BTM_SEC_SERVICE_RFC_MUX, sec_mask, BT_PSM_RFCOMM, - BTM_SEC_PROTO_RFCOMM, 0); + true, "RFC_MUX", BTM_SEC_SERVICE_RFC_MUX, sec_mask, BT_PSM_RFCOMM, BTM_SEC_PROTO_RFCOMM, + 0); } - if (RFCOMM_CreateConnectionWithSecurity( - UUID_SERVCLASS_SERIAL_PORT, remote_scn, false, BTA_JV_DEF_RFC_MTU, - peer_bd_addr, &handle, bta_jv_port_mgmt_cl_cback, - sec_mask) != PORT_SUCCESS) { + if (RFCOMM_CreateConnectionWithSecurity(UUID_SERVCLASS_SERIAL_PORT, remote_scn, false, + BTA_JV_DEF_RFC_MTU, peer_bd_addr, &handle, + bta_jv_port_mgmt_cl_cback, sec_mask) != PORT_SUCCESS) { log::error("RFCOMM_CreateConnection failed"); bta_jv.rfc_cl_init.status = tBTA_JV_STATUS::FAILURE; } else { @@ -1507,16 +1475,12 @@ void bta_jv_rfcomm_connect(tBTA_SEC sec_mask, uint8_t remote_scn, p_pcb->rfcomm_slot_id = rfcomm_slot_id; bta_jv.rfc_cl_init.use_co = true; - if (PORT_SetEventMaskAndCallback( - handle, event_mask, bta_jv_port_event_cl_cback) != PORT_SUCCESS) { - log::warn( - "Unable to set RFCOMM client event mask and callback handle:{}", - handle); - } - if (PORT_SetDataCOCallback(handle, bta_jv_port_data_co_cback) != + if (PORT_SetEventMaskAndCallback(handle, event_mask, bta_jv_port_event_cl_cback) != PORT_SUCCESS) { - log::warn("Unable to set RFCOMM client data callback handle:{}", - handle); + log::warn("Unable to set RFCOMM client event mask and callback handle:{}", handle); + } + if (PORT_SetDataCOCallback(handle, bta_jv_port_data_co_cback) != PORT_SUCCESS) { + log::warn("Unable to set RFCOMM client data callback handle:{}", handle); } if (PORT_GetState(handle, &port_state) != PORT_SUCCESS) { log::warn("Unable to get RFCOMM client state handle:{}", handle); @@ -1545,8 +1509,7 @@ void bta_jv_rfcomm_connect(tBTA_SEC sec_mask, uint8_t remote_scn, } } -static int find_rfc_pcb(uint32_t rfcomm_slot_id, tBTA_JV_RFC_CB** cb, - tBTA_JV_PCB** pcb) { +static int find_rfc_pcb(uint32_t rfcomm_slot_id, tBTA_JV_RFC_CB** cb, tBTA_JV_PCB** pcb) { *cb = NULL; *pcb = NULL; int i; @@ -1557,9 +1520,8 @@ static int find_rfc_pcb(uint32_t rfcomm_slot_id, tBTA_JV_RFC_CB** cb, *pcb = &bta_jv_cb.port_cb[i]; *cb = &bta_jv_cb.rfc_cb[rfc_handle - 1]; log::verbose( - "FOUND rfc_cb_handle=0x{:x}, port.jv_handle=0x{:x}, state={}, " - "rfc_cb->handle=0x{:x}", - rfc_handle, (*pcb)->handle, (*pcb)->state, (*cb)->handle); + "FOUND rfc_cb_handle=0x{:x}, port.jv_handle=0x{:x}, state={}, rfc_cb->handle=0x{:x}", + rfc_handle, (*pcb)->handle, (*pcb)->state, (*cb)->handle); return 1; } } @@ -1579,7 +1541,9 @@ void bta_jv_rfcomm_close(uint32_t handle, uint32_t rfcomm_slot_id) { tBTA_JV_RFC_CB* p_cb = NULL; tBTA_JV_PCB* p_pcb = NULL; - if (!find_rfc_pcb(rfcomm_slot_id, &p_cb, &p_pcb)) return; + if (!find_rfc_pcb(rfcomm_slot_id, &p_cb, &p_pcb)) { + return; + } bta_jv_free_rfc_cb(p_cb, p_pcb); } @@ -1593,8 +1557,7 @@ void bta_jv_rfcomm_close(uint32_t handle, uint32_t rfcomm_slot_id) { * Returns void * ******************************************************************************/ -static void bta_jv_port_mgmt_sr_cback(const tPORT_RESULT code, - uint16_t port_handle) { +static void bta_jv_port_mgmt_sr_cback(const tPORT_RESULT code, uint16_t port_handle) { tBTA_JV_PCB* p_pcb = bta_jv_rfc_port_to_pcb(port_handle); tBTA_JV_RFC_CB* p_cb = bta_jv_rfc_port_to_cb(port_handle); tBTA_JV evt_data; @@ -1607,18 +1570,15 @@ static void bta_jv_port_mgmt_sr_cback(const tPORT_RESULT code, return; } uint32_t rfcomm_slot_id = p_pcb->rfcomm_slot_id; - log::verbose("code={}, port_handle=0x{:x}, handle=0x{:x}, p_pcb{}, user={}", - code, port_handle, p_cb->handle, fmt::ptr(p_pcb), - p_pcb->rfcomm_slot_id); + log::verbose("code={}, port_handle=0x{:x}, handle=0x{:x}, p_pcb{}, user={}", code, port_handle, + p_cb->handle, fmt::ptr(p_pcb), p_pcb->rfcomm_slot_id); int status = PORT_CheckConnection(port_handle, &rem_bda, &lcid); int failed = true; if (code == PORT_SUCCESS) { if (status != PORT_SUCCESS) { - log::error( - "PORT_CheckConnection returned {}, although port is supposed to be " - "connected", - status); + log::error("PORT_CheckConnection returned {}, although port is supposed to be connected", + status); } evt_data.rfc_srv_open.handle = p_pcb->handle; evt_data.rfc_srv_open.status = tBTA_JV_STATUS::SUCCESS; @@ -1627,16 +1587,16 @@ static void bta_jv_port_mgmt_sr_cback(const tPORT_RESULT code, if (p_pcb_new_listen) { evt_data.rfc_srv_open.new_listen_handle = p_pcb_new_listen->handle; p_pcb_new_listen->rfcomm_slot_id = - p_cb->p_cback(BTA_JV_RFCOMM_SRV_OPEN_EVT, &evt_data, rfcomm_slot_id); + p_cb->p_cback(BTA_JV_RFCOMM_SRV_OPEN_EVT, &evt_data, rfcomm_slot_id); if (p_pcb_new_listen->rfcomm_slot_id == 0) { log::error("rfcomm_slot_id == {}", p_pcb_new_listen->rfcomm_slot_id); } else { - log::verbose("curr_sess={}, max_sess={}", p_cb->curr_sess, - p_cb->max_sess); + log::verbose("curr_sess={}, max_sess={}", p_cb->curr_sess, p_cb->max_sess); failed = false; } - } else + } else { log::error("failed to create new listen port"); + } } if (failed) { evt_data.rfc_close.handle = p_cb->handle; @@ -1646,9 +1606,8 @@ static void bta_jv_port_mgmt_sr_cback(const tPORT_RESULT code, p_pcb->cong = false; tBTA_JV_RFCOMM_CBACK* p_cback = p_cb->p_cback; - log::verbose( - "PORT_CLOSED before BTA_JV_RFCOMM_CLOSE_EVT: curr_sess={}, max_sess={}", - p_cb->curr_sess, p_cb->max_sess); + log::verbose("PORT_CLOSED before BTA_JV_RFCOMM_CLOSE_EVT: curr_sess={}, max_sess={}", + p_cb->curr_sess, p_cb->max_sess); if (BTA_JV_ST_SR_CLOSING == p_pcb->state) { evt_data.rfc_close.async = false; evt_data.rfc_close.status = tBTA_JV_STATUS::SUCCESS; @@ -1657,9 +1616,8 @@ static void bta_jv_port_mgmt_sr_cback(const tPORT_RESULT code, p_cback(BTA_JV_RFCOMM_CLOSE_EVT, &evt_data, rfcomm_slot_id); // bta_jv_free_rfc_cb(p_cb, p_pcb); - log::verbose( - "PORT_CLOSED after BTA_JV_RFCOMM_CLOSE_EVT: curr_sess={}, max_sess={}", - p_cb->curr_sess, p_cb->max_sess); + log::verbose("PORT_CLOSED after BTA_JV_RFCOMM_CLOSE_EVT: curr_sess={}, max_sess={}", + p_cb->curr_sess, p_cb->max_sess); } } @@ -1683,8 +1641,7 @@ static void bta_jv_port_event_sr_cback(uint32_t code, uint16_t port_handle) { return; } - log::verbose("code=0x{:x}, port_handle={}, handle={}", code, port_handle, - p_cb->handle); + log::verbose("code=0x{:x}, port_handle={}, handle={}", code, port_handle, p_cb->handle); uint32_t user_data = p_pcb->rfcomm_slot_id; if (code & PORT_EV_RXCHAR) { @@ -1714,8 +1671,7 @@ static void bta_jv_port_event_sr_cback(uint32_t code, uint16_t port_handle) { * Returns return a pointer to tBTA_JV_PCB just added * ******************************************************************************/ -static tBTA_JV_PCB* bta_jv_add_rfc_port(tBTA_JV_RFC_CB* p_cb, - tBTA_JV_PCB* p_pcb_open) { +static tBTA_JV_PCB* bta_jv_add_rfc_port(tBTA_JV_RFC_CB* p_cb, tBTA_JV_PCB* p_pcb_open) { uint8_t used = 0, i, listen = 0; uint32_t si = 0; tPORT_STATE port_state; @@ -1735,9 +1691,8 @@ static tBTA_JV_PCB* bta_jv_add_rfc_port(tBTA_JV_RFC_CB* p_cb, } else { log::error( - "open pcb not matching listen one, count={}, listen pcb " - "handle={}, open pcb={}", - listen, p_pcb->port_handle, p_pcb_open->handle); + "open pcb not matching listen one, count={}, listen pcb handle={}, open pcb={}", + listen, p_pcb->port_handle, p_pcb_open->handle); return NULL; } } @@ -1747,19 +1702,17 @@ static tBTA_JV_PCB* bta_jv_add_rfc_port(tBTA_JV_RFC_CB* p_cb, } } - log::verbose("max_sess={}, used={}, curr_sess={}, listen={}, si={}", - p_cb->max_sess, used, p_cb->curr_sess, listen, si); + log::verbose("max_sess={}, used={}, curr_sess={}, listen={}, si={}", p_cb->max_sess, used, + p_cb->curr_sess, listen, si); if (used < p_cb->max_sess && listen == 1 && si) { si--; - if (PORT_GetSecurityMask(p_pcb_open->port_handle, &sec_mask) != - PORT_SUCCESS) { + if (PORT_GetSecurityMask(p_pcb_open->port_handle, &sec_mask) != PORT_SUCCESS) { log::error("RFCOMM_CreateConnection failed: invalid port_handle"); } if (RFCOMM_CreateConnectionWithSecurity( - p_cb->sec_id, p_cb->scn, true, BTA_JV_DEF_RFC_MTU, - RawAddress::kAny, &(p_cb->rfc_hdl[si]), bta_jv_port_mgmt_sr_cback, - sec_mask) == PORT_SUCCESS) { + p_cb->sec_id, p_cb->scn, true, BTA_JV_DEF_RFC_MTU, RawAddress::kAny, + &(p_cb->rfc_hdl[si]), bta_jv_port_mgmt_sr_cback, sec_mask) == PORT_SUCCESS) { p_cb->curr_sess++; p_pcb = &bta_jv_cb.port_cb[p_cb->rfc_hdl[si] - 1]; p_pcb->state = BTA_JV_ST_SR_LISTEN; @@ -1767,24 +1720,18 @@ static tBTA_JV_PCB* bta_jv_add_rfc_port(tBTA_JV_RFC_CB* p_cb, p_pcb->rfcomm_slot_id = p_pcb_open->rfcomm_slot_id; if (PORT_ClearKeepHandleFlag(p_pcb->port_handle) != PORT_SUCCESS) { - log::warn("Unable to clear RFCOMM server keep handle flag handle:{}", - p_pcb->port_handle); + log::warn("Unable to clear RFCOMM server keep handle flag handle:{}", p_pcb->port_handle); } if (PORT_SetEventMaskAndCallback(p_pcb->port_handle, event_mask, - bta_jv_port_event_sr_cback) != - PORT_SUCCESS) { - log::warn( - "Unable to set RFCOMM server event mask and callback handle:{}", - p_pcb->port_handle); - } - if (PORT_SetDataCOCallback(p_pcb->port_handle, - bta_jv_port_data_co_cback) != PORT_SUCCESS) { - log::warn("Unable to set RFCOMM server data callback handle:{}", + bta_jv_port_event_sr_cback) != PORT_SUCCESS) { + log::warn("Unable to set RFCOMM server event mask and callback handle:{}", p_pcb->port_handle); } + if (PORT_SetDataCOCallback(p_pcb->port_handle, bta_jv_port_data_co_cback) != PORT_SUCCESS) { + log::warn("Unable to set RFCOMM server data callback handle:{}", p_pcb->port_handle); + } if (PORT_GetState(p_pcb->port_handle, &port_state) != PORT_SUCCESS) { - log::warn("Unable to get RFCOMM server state handle:{}", - p_pcb->port_handle); + log::warn("Unable to get RFCOMM server state handle:{}", p_pcb->port_handle); } port_state.fc_type = (PORT_FC_CTS_ON_INPUT | PORT_FC_CTS_ON_OUTPUT); @@ -1792,8 +1739,7 @@ static tBTA_JV_PCB* bta_jv_add_rfc_port(tBTA_JV_RFC_CB* p_cb, if (PORT_SetState(p_pcb->port_handle, &port_state) != PORT_SUCCESS) { } p_pcb->handle = BTA_JV_RFC_H_S_TO_HDL(p_cb->handle, si); - log::verbose("p_pcb->handle=0x{:x}, curr_sess={}", p_pcb->handle, - p_cb->curr_sess); + log::verbose("p_pcb->handle=0x{:x}, curr_sess={}", p_pcb->handle, p_cb->curr_sess); } else { log::error("RFCOMM_CreateConnection failed"); return NULL; @@ -1803,16 +1749,13 @@ static tBTA_JV_PCB* bta_jv_add_rfc_port(tBTA_JV_RFC_CB* p_cb, return NULL; } } - log::verbose("sec id in use={}, rfc_cb in use={}", get_sec_id_used(), - get_rfc_cb_used()); + log::verbose("sec id in use={}, rfc_cb in use={}", get_sec_id_used(), get_rfc_cb_used()); return p_pcb; } /* waits for an RFCOMM client to connect */ -void bta_jv_rfcomm_start_server(tBTA_SEC sec_mask, uint8_t local_scn, - uint8_t max_session, - tBTA_JV_RFCOMM_CBACK* p_cback, - uint32_t rfcomm_slot_id) { +void bta_jv_rfcomm_start_server(tBTA_SEC sec_mask, uint8_t local_scn, uint8_t max_session, + tBTA_JV_RFCOMM_CBACK* p_cback, uint32_t rfcomm_slot_id) { uint16_t handle = 0; uint32_t event_mask = BTA_JV_RFC_EV_MASK; tPORT_STATE port_state; @@ -1824,9 +1767,9 @@ void bta_jv_rfcomm_start_server(tBTA_SEC sec_mask, uint8_t local_scn, evt_data.status = tBTA_JV_STATUS::FAILURE; do { - if (RFCOMM_CreateConnectionWithSecurity( - 0, local_scn, true, BTA_JV_DEF_RFC_MTU, RawAddress::kAny, &handle, - bta_jv_port_mgmt_sr_cback, sec_mask) != PORT_SUCCESS) { + if (RFCOMM_CreateConnectionWithSecurity(0, local_scn, true, BTA_JV_DEF_RFC_MTU, + RawAddress::kAny, &handle, bta_jv_port_mgmt_sr_cback, + sec_mask) != PORT_SUCCESS) { log::error("RFCOMM_CreateConnection failed"); break; } @@ -1847,13 +1790,11 @@ void bta_jv_rfcomm_start_server(tBTA_SEC sec_mask, uint8_t local_scn, evt_data.use_co = true; if (PORT_ClearKeepHandleFlag(handle) != PORT_SUCCESS) { - log::warn("Unable to clear RFCOMM server keep handle flag handle:{}", - handle); + log::warn("Unable to clear RFCOMM server keep handle flag handle:{}", handle); } - if (PORT_SetEventMaskAndCallback( - handle, event_mask, bta_jv_port_event_sr_cback) != PORT_SUCCESS) { - log::warn("Unable to set RFCOMM server event mask and callback handle:{}", - handle); + if (PORT_SetEventMaskAndCallback(handle, event_mask, bta_jv_port_event_sr_cback) != + PORT_SUCCESS) { + log::warn("Unable to set RFCOMM server event mask and callback handle:{}", handle); } if (PORT_GetState(handle, &port_state) != PORT_SUCCESS) { log::warn("Unable to get RFCOMM server state handle:{}", handle); @@ -1870,15 +1811,13 @@ void bta_jv_rfcomm_start_server(tBTA_SEC sec_mask, uint8_t local_scn, bta_jv.rfc_start = evt_data; p_cback(BTA_JV_RFCOMM_START_EVT, &bta_jv, rfcomm_slot_id); if (bta_jv.rfc_start.status == tBTA_JV_STATUS::SUCCESS) { - if (PORT_SetDataCOCallback(handle, bta_jv_port_data_co_cback) != - PORT_SUCCESS) { + if (PORT_SetDataCOCallback(handle, bta_jv_port_data_co_cback) != PORT_SUCCESS) { log::error("Unable to set RFCOMM server data callback handle:{}", handle); } } else { if (handle) { if (RFCOMM_RemoveConnection(handle) != PORT_SUCCESS) { - log::warn("Unable to remote RFCOMM server connection handle:{}", - handle); + log::warn("Unable to remote RFCOMM server connection handle:{}", handle); } } } @@ -1895,9 +1834,10 @@ void bta_jv_rfcomm_stop_server(uint32_t handle, uint32_t rfcomm_slot_id) { tBTA_JV_RFC_CB* p_cb = NULL; tBTA_JV_PCB* p_pcb = NULL; - if (!find_rfc_pcb(rfcomm_slot_id, &p_cb, &p_pcb)) return; - log::verbose("p_pcb={}, p_pcb->port_handle={}", fmt::ptr(p_pcb), - p_pcb->port_handle); + if (!find_rfc_pcb(rfcomm_slot_id, &p_cb, &p_pcb)) { + return; + } + log::verbose("p_pcb={}, p_pcb->port_handle={}", fmt::ptr(p_pcb), p_pcb->port_handle); bta_jv_free_rfc_cb(p_cb, p_pcb); } @@ -1918,8 +1858,7 @@ void bta_jv_rfcomm_write(uint32_t handle, uint32_t req_id, tBTA_JV_RFC_CB* p_cb, bta_jv_pm_conn_busy(p_pcb->p_pm_cb); - if (!evt_data.cong && - PORT_WriteDataCO(p_pcb->port_handle, &evt_data.len) == PORT_SUCCESS) { + if (!evt_data.cong && PORT_WriteDataCO(p_pcb->port_handle, &evt_data.len) == PORT_SUCCESS) { evt_data.status = tBTA_JV_STATUS::SUCCESS; } @@ -1937,8 +1876,7 @@ void bta_jv_rfcomm_write(uint32_t handle, uint32_t req_id, tBTA_JV_RFC_CB* p_cb, } /* Set or free power mode profile for a JV application */ -void bta_jv_set_pm_profile(uint32_t handle, tBTA_JV_PM_ID app_id, - tBTA_JV_CONN_STATE init_st) { +void bta_jv_set_pm_profile(uint32_t handle, tBTA_JV_PM_ID app_id, tBTA_JV_CONN_STATE init_st) { tBTA_JV_STATUS status; tBTA_JV_PM_CB* p_cb; @@ -1956,10 +1894,11 @@ void bta_jv_set_pm_profile(uint32_t handle, tBTA_JV_PM_ID app_id, { p_cb = bta_jv_alloc_set_pm_profile_cb(handle, app_id); - if (NULL != p_cb) + if (NULL != p_cb) { bta_jv_pm_state_change(p_cb, init_st); - else + } else { log::warn("failed"); + } } } @@ -1975,8 +1914,9 @@ void bta_jv_set_pm_profile(uint32_t handle, tBTA_JV_PM_ID app_id, * ******************************************************************************/ static void bta_jv_pm_conn_busy(tBTA_JV_PM_CB* p_cb) { - if ((NULL != p_cb) && (BTA_JV_PM_IDLE_ST == p_cb->state)) + if ((NULL != p_cb) && (BTA_JV_PM_IDLE_ST == p_cb->state)) { bta_jv_pm_state_change(p_cb, BTA_JV_CONN_BUSY); + } } /******************************************************************************* @@ -1991,8 +1931,9 @@ static void bta_jv_pm_conn_busy(tBTA_JV_PM_CB* p_cb) { * ******************************************************************************/ static void bta_jv_pm_conn_idle(tBTA_JV_PM_CB* p_cb) { - if ((NULL != p_cb) && (BTA_JV_PM_IDLE_ST != p_cb->state)) + if ((NULL != p_cb) && (BTA_JV_PM_IDLE_ST != p_cb->state)) { bta_jv_pm_state_change(p_cb, BTA_JV_CONN_IDLE); + } } /******************************************************************************* @@ -2006,12 +1947,10 @@ static void bta_jv_pm_conn_idle(tBTA_JV_PM_CB* p_cb) { * Returns void * ******************************************************************************/ -static void bta_jv_pm_state_change(tBTA_JV_PM_CB* p_cb, - const tBTA_JV_CONN_STATE state) { - log::verbose( - "p_cb={}, handle=0x{:x}, busy/idle_state={}, app_id={}, conn_state={}", - fmt::ptr(p_cb), p_cb->handle, p_cb->state, p_cb->app_id, - bta_jv_conn_state_text(state)); +static void bta_jv_pm_state_change(tBTA_JV_PM_CB* p_cb, const tBTA_JV_CONN_STATE state) { + log::verbose("p_cb={}, handle=0x{:x}, busy/idle_state={}, app_id={}, conn_state={}", + fmt::ptr(p_cb), p_cb->handle, p_cb->state, p_cb->app_id, + bta_jv_conn_state_text(state)); switch (state) { case BTA_JV_CONN_OPEN: @@ -2075,8 +2014,7 @@ static void bta_jv_reset_sniff_timer(tBTA_JV_PM_CB* p_cb) { namespace bluetooth::legacy::testing { -void bta_jv_start_discovery_cback(uint32_t rfcomm_slot_id, - const RawAddress& bd_addr, +void bta_jv_start_discovery_cback(uint32_t rfcomm_slot_id, const RawAddress& bd_addr, tSDP_RESULT result) { ::bta_jv_start_discovery_cback(rfcomm_slot_id, bd_addr, result); } diff --git a/system/bta/jv/bta_jv_api.cc b/system/bta/jv/bta_jv_api.cc index c2ce066dab4..877a234953c 100644 --- a/system/bta/jv/bta_jv_api.cc +++ b/system/bta/jv/bta_jv_api.cc @@ -114,13 +114,10 @@ void BTA_JvDisable(void) { * Returns void * ******************************************************************************/ -void BTA_JvGetChannelId(tBTA_JV_CONN_TYPE conn_type, uint32_t id, - int32_t channel) { - log::verbose("conn_type:{}, id:{}, channel:{}", - bta_jv_conn_type_text(conn_type), id, channel); +void BTA_JvGetChannelId(tBTA_JV_CONN_TYPE conn_type, uint32_t id, int32_t channel) { + log::verbose("conn_type:{}, id:{}, channel:{}", bta_jv_conn_type_text(conn_type), id, channel); - do_in_main_thread(FROM_HERE, - Bind(&bta_jv_get_channel_id, conn_type, channel, id, id)); + do_in_main_thread(FROM_HERE, Bind(&bta_jv_get_channel_id, conn_type, channel, id, id)); } /******************************************************************************* @@ -137,10 +134,8 @@ void BTA_JvGetChannelId(tBTA_JV_CONN_TYPE conn_type, uint32_t id, * tBTA_JV_STATUS::FAILURE, otherwise. * ******************************************************************************/ -tBTA_JV_STATUS BTA_JvFreeChannel(uint16_t channel, - tBTA_JV_CONN_TYPE conn_type) { - log::verbose("channel:{}, conn_type:{}", channel, - bta_jv_conn_type_text(conn_type)); +tBTA_JV_STATUS BTA_JvFreeChannel(uint16_t channel, tBTA_JV_CONN_TYPE conn_type) { + log::verbose("channel:{}, conn_type:{}", channel, bta_jv_conn_type_text(conn_type)); do_in_main_thread(FROM_HERE, Bind(&bta_jv_free_scn, conn_type, channel)); return tBTA_JV_STATUS::SUCCESS; @@ -159,18 +154,15 @@ tBTA_JV_STATUS BTA_JvFreeChannel(uint16_t channel, * tBTA_JV_STATUS::FAILURE, otherwise. * ******************************************************************************/ -tBTA_JV_STATUS BTA_JvStartDiscovery(const RawAddress& bd_addr, - uint16_t num_uuid, const Uuid* p_uuid_list, - uint32_t rfcomm_slot_id) { - log::verbose("bd_addr:{}, rfcomm_slot_id:{}, num_uuid:{}", bd_addr, - rfcomm_slot_id, num_uuid); +tBTA_JV_STATUS BTA_JvStartDiscovery(const RawAddress& bd_addr, uint16_t num_uuid, + const Uuid* p_uuid_list, uint32_t rfcomm_slot_id) { + log::verbose("bd_addr:{}, rfcomm_slot_id:{}, num_uuid:{}", bd_addr, rfcomm_slot_id, num_uuid); Uuid* uuid_list_copy = new Uuid[num_uuid]; memcpy(uuid_list_copy, p_uuid_list, num_uuid * sizeof(Uuid)); - do_in_main_thread(FROM_HERE, - Bind(&bta_jv_start_discovery, bd_addr, num_uuid, - base::Owned(uuid_list_copy), rfcomm_slot_id)); + do_in_main_thread(FROM_HERE, Bind(&bta_jv_start_discovery, bd_addr, num_uuid, + base::Owned(uuid_list_copy), rfcomm_slot_id)); return tBTA_JV_STATUS::SUCCESS; } @@ -223,23 +215,17 @@ tBTA_JV_STATUS BTA_JvDeleteRecord(uint32_t handle) { * ******************************************************************************/ void BTA_JvL2capConnect(tBTA_JV_CONN_TYPE conn_type, tBTA_SEC sec_mask, - std::unique_ptr ertm_info, - uint16_t remote_psm, uint16_t rx_mtu, - std::unique_ptr cfg, - const RawAddress& peer_bd_addr, - tBTA_JV_L2CAP_CBACK* p_cback, + std::unique_ptr ertm_info, uint16_t remote_psm, + uint16_t rx_mtu, std::unique_ptr cfg, + const RawAddress& peer_bd_addr, tBTA_JV_L2CAP_CBACK* p_cback, uint32_t l2cap_socket_id) { - log::verbose( - "conn_type:{}, remote_psm:{}, peer_bd_addr:{}, " - "l2cap_socket_id:{}", - bta_jv_conn_type_text(conn_type), remote_psm, peer_bd_addr, - l2cap_socket_id); + log::verbose("conn_type:{}, remote_psm:{}, peer_bd_addr:{}, l2cap_socket_id:{}", + bta_jv_conn_type_text(conn_type), remote_psm, peer_bd_addr, l2cap_socket_id); log::assert_that(p_cback != nullptr, "assert failed: p_cback != nullptr"); - do_in_main_thread(FROM_HERE, - Bind(&bta_jv_l2cap_connect, conn_type, sec_mask, remote_psm, - rx_mtu, peer_bd_addr, base::Passed(&cfg), - base::Passed(&ertm_info), p_cback, l2cap_socket_id)); + do_in_main_thread(FROM_HERE, Bind(&bta_jv_l2cap_connect, conn_type, sec_mask, remote_psm, rx_mtu, + peer_bd_addr, base::Passed(&cfg), base::Passed(&ertm_info), + p_cback, l2cap_socket_id)); } /******************************************************************************* @@ -255,11 +241,11 @@ void BTA_JvL2capConnect(tBTA_JV_CONN_TYPE conn_type, tBTA_SEC sec_mask, tBTA_JV_STATUS BTA_JvL2capClose(uint32_t handle) { log::verbose("handle:{}", handle); - if (handle >= BTA_JV_MAX_L2C_CONN || !bta_jv_cb.l2c_cb[handle].p_cback) + if (handle >= BTA_JV_MAX_L2C_CONN || !bta_jv_cb.l2c_cb[handle].p_cback) { return tBTA_JV_STATUS::FAILURE; + } - do_in_main_thread( - FROM_HERE, Bind(&bta_jv_l2cap_close, handle, &bta_jv_cb.l2c_cb[handle])); + do_in_main_thread(FROM_HERE, Bind(&bta_jv_l2cap_close, handle, &bta_jv_cb.l2c_cb[handle])); return tBTA_JV_STATUS::SUCCESS; } @@ -278,19 +264,16 @@ tBTA_JV_STATUS BTA_JvL2capClose(uint32_t handle) { * ******************************************************************************/ void BTA_JvL2capStartServer(tBTA_JV_CONN_TYPE conn_type, tBTA_SEC sec_mask, - std::unique_ptr ertm_info, - uint16_t local_psm, uint16_t rx_mtu, - std::unique_ptr cfg, - tBTA_JV_L2CAP_CBACK* p_cback, - uint32_t l2cap_socket_id) { - log::verbose("conn_type:{}, local_psm:{}, l2cap_socket_id:{}", - bta_jv_conn_type_text(conn_type), local_psm, l2cap_socket_id); + std::unique_ptr ertm_info, uint16_t local_psm, + uint16_t rx_mtu, std::unique_ptr cfg, + tBTA_JV_L2CAP_CBACK* p_cback, uint32_t l2cap_socket_id) { + log::verbose("conn_type:{}, local_psm:{}, l2cap_socket_id:{}", bta_jv_conn_type_text(conn_type), + local_psm, l2cap_socket_id); CHECK(p_cback); do_in_main_thread(FROM_HERE, - Bind(&bta_jv_l2cap_start_server, conn_type, sec_mask, - local_psm, rx_mtu, base::Passed(&cfg), - base::Passed(&ertm_info), p_cback, l2cap_socket_id)); + Bind(&bta_jv_l2cap_start_server, conn_type, sec_mask, local_psm, rx_mtu, + base::Passed(&cfg), base::Passed(&ertm_info), p_cback, l2cap_socket_id)); } /******************************************************************************* @@ -304,12 +287,10 @@ void BTA_JvL2capStartServer(tBTA_JV_CONN_TYPE conn_type, tBTA_SEC sec_mask, * tBTA_JV_STATUS::FAILURE, otherwise. * ******************************************************************************/ -tBTA_JV_STATUS BTA_JvL2capStopServer(uint16_t local_psm, - uint32_t l2cap_socket_id) { +tBTA_JV_STATUS BTA_JvL2capStopServer(uint16_t local_psm, uint32_t l2cap_socket_id) { log::verbose("local_psm:{}, l2cap_socket_id:{}", local_psm, l2cap_socket_id); - do_in_main_thread( - FROM_HERE, Bind(&bta_jv_l2cap_stop_server, local_psm, l2cap_socket_id)); + do_in_main_thread(FROM_HERE, Bind(&bta_jv_l2cap_stop_server, local_psm, l2cap_socket_id)); return tBTA_JV_STATUS::SUCCESS; } @@ -325,12 +306,12 @@ tBTA_JV_STATUS BTA_JvL2capStopServer(uint16_t local_psm, * tBTA_JV_STATUS::FAILURE, otherwise. * ******************************************************************************/ -tBTA_JV_STATUS BTA_JvL2capRead(uint32_t handle, uint32_t req_id, - uint8_t* p_data, uint16_t len) { +tBTA_JV_STATUS BTA_JvL2capRead(uint32_t handle, uint32_t req_id, uint8_t* p_data, uint16_t len) { log::verbose("handle:{}, req_id:{}, len:{}", handle, req_id, len); - if (handle >= BTA_JV_MAX_L2C_CONN || !bta_jv_cb.l2c_cb[handle].p_cback) + if (handle >= BTA_JV_MAX_L2C_CONN || !bta_jv_cb.l2c_cb[handle].p_cback) { return tBTA_JV_STATUS::FAILURE; + } tBTA_JV_L2CAP_READ evt_data; evt_data.status = tBTA_JV_STATUS::FAILURE; @@ -339,8 +320,7 @@ tBTA_JV_STATUS BTA_JvL2capRead(uint32_t handle, uint32_t req_id, evt_data.p_data = p_data; evt_data.len = 0; - if (BT_PASS == - GAP_ConnReadData((uint16_t)handle, p_data, len, &evt_data.len)) { + if (BT_PASS == GAP_ConnReadData((uint16_t)handle, p_data, len, &evt_data.len)) { evt_data.status = tBTA_JV_STATUS::SUCCESS; } bta_jv_cb.l2c_cb[handle].p_cback(BTA_JV_L2CAP_READ_EVT, (tBTA_JV*)&evt_data, @@ -364,15 +344,14 @@ tBTA_JV_STATUS BTA_JvL2capReady(uint32_t handle, uint32_t* p_data_size) { tBTA_JV_STATUS status = tBTA_JV_STATUS::FAILURE; log::verbose("handle:{}", handle); - if (p_data_size && handle < BTA_JV_MAX_L2C_CONN && - bta_jv_cb.l2c_cb[handle].p_cback) { + if (p_data_size && handle < BTA_JV_MAX_L2C_CONN && bta_jv_cb.l2c_cb[handle].p_cback) { *p_data_size = 0; if (BT_PASS == GAP_GetRxQueueCnt((uint16_t)handle, p_data_size)) { status = tBTA_JV_STATUS::SUCCESS; } } - return (status); + return status; } /******************************************************************************* @@ -390,8 +369,7 @@ tBTA_JV_STATUS BTA_JvL2capReady(uint32_t handle, uint32_t* p_data_size) { * tBTA_JV_STATUS::FAILURE, otherwise. * ******************************************************************************/ -tBTA_JV_STATUS BTA_JvL2capWrite(uint32_t handle, uint32_t req_id, BT_HDR* msg, - uint32_t user_id) { +tBTA_JV_STATUS BTA_JvL2capWrite(uint32_t handle, uint32_t req_id, BT_HDR* msg, uint32_t user_id) { log::verbose("handle:{}, user_id:{}", handle, user_id); if (handle >= BTA_JV_MAX_L2C_CONN || !bta_jv_cb.l2c_cb[handle].p_cback) { @@ -399,8 +377,8 @@ tBTA_JV_STATUS BTA_JvL2capWrite(uint32_t handle, uint32_t req_id, BT_HDR* msg, return tBTA_JV_STATUS::FAILURE; } - do_in_main_thread(FROM_HERE, Bind(&bta_jv_l2cap_write, handle, req_id, msg, - user_id, &bta_jv_cb.l2c_cb[handle])); + do_in_main_thread(FROM_HERE, Bind(&bta_jv_l2cap_write, handle, req_id, msg, user_id, + &bta_jv_cb.l2c_cb[handle])); return tBTA_JV_STATUS::SUCCESS; } @@ -421,17 +399,17 @@ tBTA_JV_STATUS BTA_JvL2capWrite(uint32_t handle, uint32_t req_id, BT_HDR* msg, * ******************************************************************************/ tBTA_JV_STATUS BTA_JvRfcommConnect(tBTA_SEC sec_mask, uint8_t remote_scn, - const RawAddress& peer_bd_addr, - tBTA_JV_RFCOMM_CBACK* p_cback, + const RawAddress& peer_bd_addr, tBTA_JV_RFCOMM_CBACK* p_cback, uint32_t rfcomm_slot_id) { - log::verbose("remote_scn:{}, peer_bd_addr:{}, rfcomm_slot_id:{}", remote_scn, - peer_bd_addr, rfcomm_slot_id); + log::verbose("remote_scn:{}, peer_bd_addr:{}, rfcomm_slot_id:{}", remote_scn, peer_bd_addr, + rfcomm_slot_id); - if (!p_cback) return tBTA_JV_STATUS::FAILURE; /* Nothing to do */ + if (!p_cback) { + return tBTA_JV_STATUS::FAILURE; /* Nothing to do */ + } - do_in_main_thread(FROM_HERE, - Bind(&bta_jv_rfcomm_connect, sec_mask, remote_scn, - peer_bd_addr, p_cback, rfcomm_slot_id)); + do_in_main_thread(FROM_HERE, Bind(&bta_jv_rfcomm_connect, sec_mask, remote_scn, peer_bd_addr, + p_cback, rfcomm_slot_id)); return tBTA_JV_STATUS::SUCCESS; } @@ -452,11 +430,11 @@ tBTA_JV_STATUS BTA_JvRfcommClose(uint32_t handle, uint32_t rfcomm_slot_id) { log::verbose("handle:{}, rfcomm_slot_id:{}", handle, rfcomm_slot_id); if (hi >= BTA_JV_MAX_RFC_CONN || !bta_jv_cb.rfc_cb[hi].p_cback || - si >= BTA_JV_MAX_RFC_SR_SESSION || !bta_jv_cb.rfc_cb[hi].rfc_hdl[si]) + si >= BTA_JV_MAX_RFC_SR_SESSION || !bta_jv_cb.rfc_cb[hi].rfc_hdl[si]) { return tBTA_JV_STATUS::FAILURE; + } - do_in_main_thread(FROM_HERE, - Bind(&bta_jv_rfcomm_close, handle, rfcomm_slot_id)); + do_in_main_thread(FROM_HERE, Bind(&bta_jv_rfcomm_close, handle, rfcomm_slot_id)); return tBTA_JV_STATUS::SUCCESS; } @@ -475,23 +453,24 @@ tBTA_JV_STATUS BTA_JvRfcommClose(uint32_t handle, uint32_t rfcomm_slot_id) { * tBTA_JV_STATUS::FAILURE, otherwise. * ******************************************************************************/ -tBTA_JV_STATUS BTA_JvRfcommStartServer(tBTA_SEC sec_mask, uint8_t local_scn, - uint8_t max_session, - tBTA_JV_RFCOMM_CBACK* p_cback, - uint32_t rfcomm_slot_id) { +tBTA_JV_STATUS BTA_JvRfcommStartServer(tBTA_SEC sec_mask, uint8_t local_scn, uint8_t max_session, + tBTA_JV_RFCOMM_CBACK* p_cback, uint32_t rfcomm_slot_id) { log::verbose("local_scn:{}, rfcomm_slot_id:{}", local_scn, rfcomm_slot_id); - if (p_cback == NULL) return tBTA_JV_STATUS::FAILURE; /* Nothing to do */ + if (p_cback == NULL) { + return tBTA_JV_STATUS::FAILURE; /* Nothing to do */ + } - if (max_session == 0) max_session = 1; + if (max_session == 0) { + max_session = 1; + } if (max_session > BTA_JV_MAX_RFC_SR_SESSION) { log::info("max_session is too big. use max {}", BTA_JV_MAX_RFC_SR_SESSION); max_session = BTA_JV_MAX_RFC_SR_SESSION; } - do_in_main_thread(FROM_HERE, - Bind(&bta_jv_rfcomm_start_server, sec_mask, local_scn, - max_session, p_cback, rfcomm_slot_id)); + do_in_main_thread(FROM_HERE, Bind(&bta_jv_rfcomm_start_server, sec_mask, local_scn, max_session, + p_cback, rfcomm_slot_id)); return tBTA_JV_STATUS::SUCCESS; } @@ -506,12 +485,10 @@ tBTA_JV_STATUS BTA_JvRfcommStartServer(tBTA_SEC sec_mask, uint8_t local_scn, * tBTA_JV_STATUS::FAILURE, otherwise. * ******************************************************************************/ -tBTA_JV_STATUS BTA_JvRfcommStopServer(uint32_t handle, - uint32_t rfcomm_slot_id) { +tBTA_JV_STATUS BTA_JvRfcommStopServer(uint32_t handle, uint32_t rfcomm_slot_id) { log::verbose("handle:{}, rfcomm_slot_id:{}", handle, rfcomm_slot_id); - do_in_main_thread(FROM_HERE, - Bind(&bta_jv_rfcomm_stop_server, handle, rfcomm_slot_id)); + do_in_main_thread(FROM_HERE, Bind(&bta_jv_rfcomm_stop_server, handle, rfcomm_slot_id)); return tBTA_JV_STATUS::SUCCESS; } @@ -529,10 +506,11 @@ uint16_t BTA_JvRfcommGetPortHdl(uint32_t handle) { uint32_t si = BTA_JV_RFC_HDL_TO_SIDX(handle); if (hi < BTA_JV_MAX_RFC_CONN && si < BTA_JV_MAX_RFC_SR_SESSION && - bta_jv_cb.rfc_cb[hi].rfc_hdl[si]) + bta_jv_cb.rfc_cb[hi].rfc_hdl[si]) { return bta_jv_cb.port_cb[bta_jv_cb.rfc_cb[hi].rfc_hdl[si] - 1].port_handle; - else + } else { return 0xffff; + } } /******************************************************************************* @@ -590,7 +568,6 @@ tBTA_JV_STATUS BTA_JvSetPmProfile(uint32_t handle, tBTA_JV_PM_ID app_id, tBTA_JV_CONN_STATE init_st) { log::verbose("handle:{}, app_id:{}, init_st:{}", handle, app_id, handle); - do_in_main_thread(FROM_HERE, - Bind(&bta_jv_set_pm_profile, handle, app_id, init_st)); + do_in_main_thread(FROM_HERE, Bind(&bta_jv_set_pm_profile, handle, app_id, init_st)); return tBTA_JV_STATUS::SUCCESS; } diff --git a/system/bta/jv/bta_jv_int.h b/system/bta/jv/bta_jv_int.h index ae8380ed182..bffa2b029f5 100644 --- a/system/bta/jv/bta_jv_int.h +++ b/system/bta/jv/bta_jv_int.h @@ -40,8 +40,7 @@ ****************************************************************************/ #ifndef BTA_JV_RFC_EV_MASK -#define BTA_JV_RFC_EV_MASK \ - (PORT_EV_RXCHAR | PORT_EV_TXEMPTY | PORT_EV_FC | PORT_EV_FCS) +#define BTA_JV_RFC_EV_MASK (PORT_EV_RXCHAR | PORT_EV_TXEMPTY | PORT_EV_FC | PORT_EV_FCS) #endif enum { @@ -52,9 +51,9 @@ enum { /* BTA JV PM control block */ typedef struct { - uint32_t handle; /* The connection handle */ - uint8_t state; /* state: see above enum */ - tBTA_JV_PM_ID app_id; /* JV app specific id indicating power table to use */ + uint32_t handle; /* The connection handle */ + uint8_t state; /* state: see above enum */ + tBTA_JV_PM_ID app_id; /* JV app specific id indicating power table to use */ RawAddress peer_bd_addr; /* Peer BD address */ } tBTA_JV_PM_CB; @@ -75,16 +74,16 @@ typedef struct { uint16_t psm; /* the psm used for this server connection */ tBTA_JV_STATE state; /* the state of this control block */ tBTA_SERVICE_ID sec_id; /* service id */ - uint32_t handle; /* the handle reported to java app (same as gap handle) */ - bool cong; /* true, if congested */ - tBTA_JV_PM_CB* p_pm_cb; /* ptr to pm control block, NULL: unused */ + uint32_t handle; /* the handle reported to java app (same as gap handle) */ + bool cong; /* true, if congested */ + tBTA_JV_PM_CB* p_pm_cb; /* ptr to pm control block, NULL: unused */ uint32_t l2cap_socket_id; } tBTA_JV_L2C_CB; #define BTA_JV_RFC_HDL_MASK 0xFF #define BTA_JV_RFCOMM_MASK 0x80 #define BTA_JV_ALL_APP_ID 0xFF -#define BTA_JV_RFC_HDL_TO_SIDX(r) (((r)&0xFF00) >> 8) +#define BTA_JV_RFC_HDL_TO_SIDX(r) (((r) & 0xFF00) >> 8) #define BTA_JV_RFC_H_S_TO_HDL(h, s) ((h) | ((s) << 8)) /* port control block */ @@ -128,9 +127,8 @@ struct tBTA_JV_CB { struct sdp_cb { bool sdp_active{false}; - RawAddress bd_addr{RawAddress::kEmpty}; // current bd_addr of sdp discovery - bluetooth::Uuid uuid{ - bluetooth::Uuid::kEmpty}; // current uuid of sdp discovery + RawAddress bd_addr{RawAddress::kEmpty}; // current bd_addr of sdp discovery + bluetooth::Uuid uuid{bluetooth::Uuid::kEmpty}; // current uuid of sdp discovery } sdp_cb; tBTA_JV_PM_CB pm_cb[BTA_JV_PM_MAX_NUM]; /* PM on a per JV handle bases */ @@ -145,45 +143,35 @@ extern std::unordered_set used_l2cap_classic_dynamic_psm; void bta_jv_enable(tBTA_JV_DM_CBACK* p_cback); void bta_jv_disable(); -void bta_jv_get_channel_id(tBTA_JV_CONN_TYPE type, int32_t channel, - uint32_t l2cap_socket_id, uint32_t rfcomm_slot_id); +void bta_jv_get_channel_id(tBTA_JV_CONN_TYPE type, int32_t channel, uint32_t l2cap_socket_id, + uint32_t rfcomm_slot_id); void bta_jv_free_scn(tBTA_JV_CONN_TYPE type, uint16_t scn); void bta_jv_start_discovery(const RawAddress& bd_addr, uint16_t num_uuid, - bluetooth::Uuid* uuid_list, - uint32_t rfcomm_slot_id); + bluetooth::Uuid* uuid_list, uint32_t rfcomm_slot_id); void bta_jv_create_record(uint32_t rfcomm_slot_id); void bta_jv_delete_record(uint32_t handle); -void bta_jv_l2cap_connect(tBTA_JV_CONN_TYPE type, tBTA_SEC sec_mask, - uint16_t remote_psm, uint16_t rx_mtu, - const RawAddress& peer_bd_addr, +void bta_jv_l2cap_connect(tBTA_JV_CONN_TYPE type, tBTA_SEC sec_mask, uint16_t remote_psm, + uint16_t rx_mtu, const RawAddress& peer_bd_addr, std::unique_ptr cfg, - std::unique_ptr ertm_info, - tBTA_JV_L2CAP_CBACK* p_cback, + std::unique_ptr ertm_info, tBTA_JV_L2CAP_CBACK* p_cback, uint32_t l2cap_socket_id); void bta_jv_l2cap_close(uint32_t handle, tBTA_JV_L2C_CB* p_cb); -void bta_jv_l2cap_start_server(tBTA_JV_CONN_TYPE type, tBTA_SEC sec_mask, - uint16_t local_psm, uint16_t rx_mtu, - std::unique_ptr cfg_param, +void bta_jv_l2cap_start_server(tBTA_JV_CONN_TYPE type, tBTA_SEC sec_mask, uint16_t local_psm, + uint16_t rx_mtu, std::unique_ptr cfg_param, std::unique_ptr ertm_info, - tBTA_JV_L2CAP_CBACK* p_cback, - uint32_t l2cap_socket_id); + tBTA_JV_L2CAP_CBACK* p_cback, uint32_t l2cap_socket_id); void bta_jv_l2cap_stop_server(uint16_t local_psm, uint32_t l2cap_socket_id); -void bta_jv_l2cap_write(uint32_t handle, uint32_t req_id, BT_HDR* msg, - uint32_t user_id, tBTA_JV_L2C_CB* p_cb); -void bta_jv_rfcomm_connect(tBTA_SEC sec_mask, uint8_t remote_scn, - const RawAddress& peer_bd_addr, - tBTA_JV_RFCOMM_CBACK* p_cback, - uint32_t rfcomm_slot_id); +void bta_jv_l2cap_write(uint32_t handle, uint32_t req_id, BT_HDR* msg, uint32_t user_id, + tBTA_JV_L2C_CB* p_cb); +void bta_jv_rfcomm_connect(tBTA_SEC sec_mask, uint8_t remote_scn, const RawAddress& peer_bd_addr, + tBTA_JV_RFCOMM_CBACK* p_cback, uint32_t rfcomm_slot_id); void bta_jv_rfcomm_close(uint32_t handle, uint32_t rfcomm_slot_id); -void bta_jv_rfcomm_start_server(tBTA_SEC sec_mask, uint8_t local_scn, - uint8_t max_session, - tBTA_JV_RFCOMM_CBACK* p_cback, - uint32_t rfcomm_slot_id); +void bta_jv_rfcomm_start_server(tBTA_SEC sec_mask, uint8_t local_scn, uint8_t max_session, + tBTA_JV_RFCOMM_CBACK* p_cback, uint32_t rfcomm_slot_id); void bta_jv_rfcomm_stop_server(uint32_t handle, uint32_t rfcomm_slot_id); void bta_jv_rfcomm_write(uint32_t handle, uint32_t req_id, tBTA_JV_RFC_CB* p_cb, tBTA_JV_PCB* p_pcb); -void bta_jv_set_pm_profile(uint32_t handle, tBTA_JV_PM_ID app_id, - tBTA_JV_CONN_STATE init_st); +void bta_jv_set_pm_profile(uint32_t handle, tBTA_JV_PM_ID app_id, tBTA_JV_CONN_STATE init_st); void bta_jv_l2cap_stop_server_le(uint16_t local_chan); diff --git a/system/bta/le_audio/audio_hal_client/audio_hal_client.h b/system/bta/le_audio/audio_hal_client/audio_hal_client.h index b98f87b32a3..decfe5e0b34 100644 --- a/system/bta/le_audio/audio_hal_client/audio_hal_client.h +++ b/system/bta/le_audio/audio_hal_client/audio_hal_client.h @@ -30,30 +30,19 @@ namespace bluetooth::le_audio { * the software codecs in case of a software coding sessions. */ struct LeAudioCodecConfiguration { - static constexpr uint8_t kChannelNumberMono = - bluetooth::audio::le_audio::kChannelNumberMono; - static constexpr uint8_t kChannelNumberStereo = - bluetooth::audio::le_audio::kChannelNumberStereo; - - static constexpr uint32_t kSampleRate48000 = - bluetooth::audio::le_audio::kSampleRate48000; - static constexpr uint32_t kSampleRate44100 = - bluetooth::audio::le_audio::kSampleRate44100; - static constexpr uint32_t kSampleRate32000 = - bluetooth::audio::le_audio::kSampleRate32000; - static constexpr uint32_t kSampleRate24000 = - bluetooth::audio::le_audio::kSampleRate24000; - static constexpr uint32_t kSampleRate16000 = - bluetooth::audio::le_audio::kSampleRate16000; - static constexpr uint32_t kSampleRate8000 = - bluetooth::audio::le_audio::kSampleRate8000; - - static constexpr uint8_t kBitsPerSample16 = - bluetooth::audio::le_audio::kBitsPerSample16; - static constexpr uint8_t kBitsPerSample24 = - bluetooth::audio::le_audio::kBitsPerSample24; - static constexpr uint8_t kBitsPerSample32 = - bluetooth::audio::le_audio::kBitsPerSample32; + static constexpr uint8_t kChannelNumberMono = bluetooth::audio::le_audio::kChannelNumberMono; + static constexpr uint8_t kChannelNumberStereo = bluetooth::audio::le_audio::kChannelNumberStereo; + + static constexpr uint32_t kSampleRate48000 = bluetooth::audio::le_audio::kSampleRate48000; + static constexpr uint32_t kSampleRate44100 = bluetooth::audio::le_audio::kSampleRate44100; + static constexpr uint32_t kSampleRate32000 = bluetooth::audio::le_audio::kSampleRate32000; + static constexpr uint32_t kSampleRate24000 = bluetooth::audio::le_audio::kSampleRate24000; + static constexpr uint32_t kSampleRate16000 = bluetooth::audio::le_audio::kSampleRate16000; + static constexpr uint32_t kSampleRate8000 = bluetooth::audio::le_audio::kSampleRate8000; + + static constexpr uint8_t kBitsPerSample16 = bluetooth::audio::le_audio::kBitsPerSample16; + static constexpr uint8_t kBitsPerSample24 = bluetooth::audio::le_audio::kBitsPerSample24; + static constexpr uint8_t kBitsPerSample32 = bluetooth::audio::le_audio::kBitsPerSample32; static constexpr uint32_t kInterval7500Us = 7500; static constexpr uint32_t kInterval10000Us = 10000; @@ -76,60 +65,53 @@ struct LeAudioCodecConfiguration { uint32_t data_interval_us = 0; bool operator!=(const LeAudioCodecConfiguration& other) { - return !((num_channels == other.num_channels) && - (sample_rate == other.sample_rate) && + return !((num_channels == other.num_channels) && (sample_rate == other.sample_rate) && (bits_per_sample == other.bits_per_sample) && (data_interval_us == other.data_interval_us)); } bool operator==(const LeAudioCodecConfiguration& other) const { - return ((num_channels == other.num_channels) && - (sample_rate == other.sample_rate) && - (bits_per_sample == other.bits_per_sample) && - (data_interval_us == other.data_interval_us)); + return (num_channels == other.num_channels) && (sample_rate == other.sample_rate) && + (bits_per_sample == other.bits_per_sample) && + (data_interval_us == other.data_interval_us); } bool IsInvalid() const { - return (num_channels == 0) || (sample_rate == 0) || - (bits_per_sample == 0) || (data_interval_us == 0); + return (num_channels == 0) || (sample_rate == 0) || (bits_per_sample == 0) || + (data_interval_us == 0); } }; class LeAudioCommonAudioHalClient { - public: +public: virtual ~LeAudioCommonAudioHalClient() = default; virtual std::optional GetBroadcastConfig( - const std::vector>& - subgroup_quality, - const std::optional< - std::vector<::bluetooth::le_audio::types::acs_ac_record>>& pacs) - const = 0; - virtual std::optional< - ::bluetooth::le_audio::set_configurations::AudioSetConfiguration> - GetUnicastConfig(const CodecManager::UnicastConfigurationRequirements& - requirements) const = 0; + const std::vector>& subgroup_quality, + const std::optional>& pacs) + const = 0; + virtual std::optional<::bluetooth::le_audio::set_configurations::AudioSetConfiguration> + GetUnicastConfig(const CodecManager::UnicastConfigurationRequirements& requirements) const = 0; }; /* Used by the local BLE Audio Sink device to pass the audio data * received from a remote BLE Audio Source to the Audio HAL. */ class LeAudioSinkAudioHalClient { - public: +public: class Callbacks { - public: + public: Callbacks() = default; virtual ~Callbacks() = default; virtual void OnAudioSuspend(void) = 0; virtual void OnAudioResume(void) = 0; virtual void OnAudioMetadataUpdate( - const std::vector sink_metadata) = 0; + const std::vector sink_metadata) = 0; base::WeakPtrFactory weak_factory_{this}; }; virtual ~LeAudioSinkAudioHalClient() = default; - virtual bool Start(const LeAudioCodecConfiguration& codecConfiguration, - Callbacks* audioReceiver, + virtual bool Start(const LeAudioCodecConfiguration& codecConfiguration, Callbacks* audioReceiver, DsaModes dsa_modes = {DsaMode::DISABLED}) = 0; virtual void Stop() = 0; virtual size_t SendData(uint8_t* data, uint16_t size) = 0; @@ -138,15 +120,14 @@ class LeAudioSinkAudioHalClient { virtual void CancelStreamingRequest() = 0; virtual void UpdateRemoteDelay(uint16_t remote_delay_ms) = 0; - virtual void UpdateAudioConfigToHal( - const ::bluetooth::le_audio::offload_config& config) = 0; + virtual void UpdateAudioConfigToHal(const ::bluetooth::le_audio::offload_config& config) = 0; virtual void SuspendedForReconfiguration() = 0; virtual void ReconfigurationComplete() = 0; static std::unique_ptr AcquireUnicast(); static void DebugDump(int fd); - protected: +protected: LeAudioSinkAudioHalClient() = default; }; @@ -154,34 +135,32 @@ class LeAudioSinkAudioHalClient { * Audio HAL, so we could send it over to a remote BLE Audio Sink device. */ class LeAudioSourceAudioHalClient : public LeAudioCommonAudioHalClient { - public: +public: class Callbacks { - public: + public: Callbacks() = default; virtual ~Callbacks() = default; virtual void OnAudioDataReady(const std::vector& data) = 0; virtual void OnAudioSuspend(void) = 0; virtual void OnAudioResume(void) = 0; virtual void OnAudioMetadataUpdate( - const std::vector source_metadata, - DsaMode dsa_mode) = 0; + const std::vector source_metadata, + DsaMode dsa_mode) = 0; base::WeakPtrFactory weak_factory_{this}; }; virtual ~LeAudioSourceAudioHalClient() = default; - virtual bool Start(const LeAudioCodecConfiguration& codecConfiguration, - Callbacks* audioReceiver, + virtual bool Start(const LeAudioCodecConfiguration& codecConfiguration, Callbacks* audioReceiver, DsaModes dsa_modes = {DsaMode::DISABLED}) = 0; virtual void Stop() = 0; virtual size_t SendData(uint8_t* data, uint16_t size) { return 0; } virtual void ConfirmStreamingRequest() = 0; virtual void CancelStreamingRequest() = 0; virtual void UpdateRemoteDelay(uint16_t remote_delay_ms) = 0; - virtual void UpdateAudioConfigToHal( - const ::bluetooth::le_audio::offload_config& config) = 0; + virtual void UpdateAudioConfigToHal(const ::bluetooth::le_audio::offload_config& config) = 0; virtual void UpdateBroadcastAudioConfigToHal( - const ::bluetooth::le_audio::broadcast_offload_config& config) = 0; + const ::bluetooth::le_audio::broadcast_offload_config& config) = 0; virtual void SuspendedForReconfiguration() = 0; virtual void ReconfigurationComplete() = 0; @@ -189,7 +168,7 @@ class LeAudioSourceAudioHalClient : public LeAudioCommonAudioHalClient { static std::unique_ptr AcquireBroadcast(); static void DebugDump(int fd); - protected: +protected: LeAudioSourceAudioHalClient() = default; }; } // namespace bluetooth::le_audio diff --git a/system/bta/le_audio/audio_hal_client/audio_hal_client_test.cc b/system/bta/le_audio/audio_hal_client/audio_hal_client_test.cc index 49de31fdd48..7c9c4c8b468 100644 --- a/system/bta/le_audio/audio_hal_client/audio_hal_client_test.cc +++ b/system/bta/le_audio/audio_hal_client/audio_hal_client_test.cc @@ -52,11 +52,8 @@ using bluetooth::le_audio::LeAudioSourceAudioHalClient; using namespace bluetooth; bluetooth::common::MessageLoopThread message_loop_thread("test message loop"); -bluetooth::common::MessageLoopThread* get_main_thread() { - return &message_loop_thread; -} -bt_status_t do_in_main_thread(const base::Location& from_here, - base::OnceClosure task) { +bluetooth::common::MessageLoopThread* get_main_thread() { return &message_loop_thread; } +bt_status_t do_in_main_thread(const base::Location& from_here, base::OnceClosure task) { if (!message_loop_thread.DoInThread(from_here, std::move(task))) { log::error("failed from {}", from_here.ToString()); return BT_STATUS_FAIL; @@ -73,11 +70,14 @@ static void init_message_loop_thread() { FAIL() << "unable to create message loop thread."; } - if (!message_loop_thread.EnableRealTimeScheduling()) + if (!message_loop_thread.EnableRealTimeScheduling()) { log::error("Unable to set real time scheduling"); + } message_loop_ = message_loop_thread.message_loop(); - if (message_loop_ == nullptr) FAIL() << "unable to get message loop."; + if (message_loop_ == nullptr) { + FAIL() << "unable to get message loop."; + } } static void cleanup_message_loop_thread() { @@ -88,54 +88,45 @@ static void cleanup_message_loop_thread() { using bluetooth::audio::le_audio::LeAudioClientInterface; class MockLeAudioClientInterfaceSink : public LeAudioClientInterface::Sink { - public: +public: MOCK_METHOD((void), Cleanup, (), (override)); - MOCK_METHOD((void), SetPcmParameters, - (const LeAudioClientInterface::PcmParameters& params), + MOCK_METHOD((void), SetPcmParameters, (const LeAudioClientInterface::PcmParameters& params), (override)); MOCK_METHOD((void), SetRemoteDelay, (uint16_t delay_report_ms), (override)); MOCK_METHOD((void), StartSession, (), (override)); MOCK_METHOD((void), StopSession, (), (override)); MOCK_METHOD((void), ConfirmStreamingRequest, (), (override)); MOCK_METHOD((void), CancelStreamingRequest, (), (override)); - MOCK_METHOD((void), UpdateAudioConfigToHal, - (const ::bluetooth::le_audio::offload_config&)); - MOCK_METHOD((std::optional<::le_audio::broadcaster::BroadcastConfiguration>), - GetBroadcastConfig, - ((const std::vector< - std::pair<::le_audio::types::LeAudioContextType, uint8_t>>&), - (const std::optional< - std::vector<::bluetooth::le_audio::types::acs_ac_record>>&)), + MOCK_METHOD((void), UpdateAudioConfigToHal, (const ::bluetooth::le_audio::offload_config&)); + MOCK_METHOD((std::optional<::le_audio::broadcaster::BroadcastConfiguration>), GetBroadcastConfig, + ((const std::vector>&), + (const std::optional>&)), + (const)); + MOCK_METHOD((std::optional<::le_audio::set_configurations::AudioSetConfiguration>), + GetUnicastConfig, + (const ::bluetooth::le_audio::CodecManager::UnicastConfigurationRequirements&), (const)); - MOCK_METHOD( - (std::optional<::le_audio::set_configurations::AudioSetConfiguration>), - GetUnicastConfig, - (const ::bluetooth::le_audio::CodecManager:: - UnicastConfigurationRequirements&), - (const)); MOCK_METHOD((void), UpdateBroadcastAudioConfigToHal, (const ::bluetooth::le_audio::broadcast_offload_config&)); - MOCK_METHOD((size_t), Read, (uint8_t * p_buf, uint32_t len)); + MOCK_METHOD((size_t), Read, (uint8_t* p_buf, uint32_t len)); }; class MockLeAudioClientInterfaceSource : public LeAudioClientInterface::Source { - public: +public: MOCK_METHOD((void), Cleanup, (), (override)); - MOCK_METHOD((void), SetPcmParameters, - (const LeAudioClientInterface::PcmParameters& params), + MOCK_METHOD((void), SetPcmParameters, (const LeAudioClientInterface::PcmParameters& params), (override)); MOCK_METHOD((void), SetRemoteDelay, (uint16_t delay_report_ms), (override)); MOCK_METHOD((void), StartSession, (), (override)); MOCK_METHOD((void), StopSession, (), (override)); MOCK_METHOD((void), ConfirmStreamingRequest, (), (override)); MOCK_METHOD((void), CancelStreamingRequest, (), (override)); - MOCK_METHOD((void), UpdateAudioConfigToHal, - (const ::bluetooth::le_audio::offload_config&)); + MOCK_METHOD((void), UpdateAudioConfigToHal, (const ::bluetooth::le_audio::offload_config&)); MOCK_METHOD((size_t), Write, (const uint8_t* p_buf, uint32_t len)); }; class MockLeAudioClientInterface : public LeAudioClientInterface { - public: +public: MockLeAudioClientInterface() = default; ~MockLeAudioClientInterface() = default; @@ -162,77 +153,64 @@ MockLeAudioClientInterfaceSource* source_mock; LeAudioClientInterface* LeAudioClientInterface::Get() { return interface_mock; } LeAudioClientInterface::Sink* LeAudioClientInterface::GetSink( - StreamCallbacks stream_cb, - bluetooth::common::MessageLoopThread* message_loop, - bool is_broadcasting_session_type) { - return interface_mock->GetSink(stream_cb, message_loop, - is_broadcasting_session_type); + StreamCallbacks stream_cb, bluetooth::common::MessageLoopThread* message_loop, + bool is_broadcasting_session_type) { + return interface_mock->GetSink(stream_cb, message_loop, is_broadcasting_session_type); } LeAudioClientInterface::Source* LeAudioClientInterface::GetSource( - StreamCallbacks stream_cb, - bluetooth::common::MessageLoopThread* message_loop) { + StreamCallbacks stream_cb, bluetooth::common::MessageLoopThread* message_loop) { return interface_mock->GetSource(stream_cb, message_loop); } -bool LeAudioClientInterface::ReleaseSink(LeAudioClientInterface::Sink* sink) { - return true; -} -bool LeAudioClientInterface::ReleaseSource( - LeAudioClientInterface::Source* source) { - return true; -} +bool LeAudioClientInterface::ReleaseSink(LeAudioClientInterface::Sink* sink) { return true; } +bool LeAudioClientInterface::ReleaseSource(LeAudioClientInterface::Source* source) { return true; } void LeAudioClientInterface::SetAllowedDsaModes(DsaModes dsa_modes) { return; } void LeAudioClientInterface::Sink::Cleanup() {} -void LeAudioClientInterface::Sink::SetPcmParameters( - const PcmParameters& params) {} +void LeAudioClientInterface::Sink::SetPcmParameters(const PcmParameters& params) {} void LeAudioClientInterface::Sink::SetRemoteDelay(uint16_t delay_report_ms) {} void LeAudioClientInterface::Sink::StartSession() {} void LeAudioClientInterface::Sink::StopSession() {} -void LeAudioClientInterface::Sink::ConfirmStreamingRequest(){}; -void LeAudioClientInterface::Sink::CancelStreamingRequest(){}; -void LeAudioClientInterface::Sink::ConfirmStreamingRequestV2(){}; -void LeAudioClientInterface::Sink::CancelStreamingRequestV2(){}; +void LeAudioClientInterface::Sink::ConfirmStreamingRequest() {} +void LeAudioClientInterface::Sink::CancelStreamingRequest() {} +void LeAudioClientInterface::Sink::ConfirmStreamingRequestV2() {} +void LeAudioClientInterface::Sink::CancelStreamingRequestV2() {} void LeAudioClientInterface::Sink::UpdateAudioConfigToHal( - const ::bluetooth::le_audio::offload_config& config){}; + const ::bluetooth::le_audio::offload_config& config) {} void LeAudioClientInterface::Sink::UpdateBroadcastAudioConfigToHal( - const ::bluetooth::le_audio::broadcast_offload_config& config){}; + const ::bluetooth::le_audio::broadcast_offload_config& config) {} std::optional<::le_audio::broadcaster::BroadcastConfiguration> LeAudioClientInterface::Sink::GetBroadcastConfig( - const std::vector< - std::pair<::le_audio::types::LeAudioContextType, uint8_t>>& quality, - const std::optional< - std::vector<::bluetooth::le_audio::types::acs_ac_record>>& pacs) const { + const std::vector>& quality, + const std::optional>& pacs) const { return sink_mock->GetBroadcastConfig(quality, pacs); -}; +} std::optional<::le_audio::set_configurations::AudioSetConfiguration> LeAudioClientInterface::Sink::GetUnicastConfig( - const ::bluetooth::le_audio::CodecManager::UnicastConfigurationRequirements& - requirements) const { + const ::bluetooth::le_audio::CodecManager::UnicastConfigurationRequirements& requirements) + const { return sink_mock->GetUnicastConfig(requirements); -}; +} void LeAudioClientInterface::Sink::SuspendedForReconfiguration() {} void LeAudioClientInterface::Sink::ReconfigurationComplete() {} void LeAudioClientInterface::Source::Cleanup() {} -void LeAudioClientInterface::Source::SetPcmParameters( - const PcmParameters& params) {} +void LeAudioClientInterface::Source::SetPcmParameters(const PcmParameters& params) {} void LeAudioClientInterface::Source::SetRemoteDelay(uint16_t delay_report_ms) {} void LeAudioClientInterface::Source::StartSession() {} void LeAudioClientInterface::Source::StopSession() {} -void LeAudioClientInterface::Source::ConfirmStreamingRequest(){}; -void LeAudioClientInterface::Source::CancelStreamingRequest(){}; -void LeAudioClientInterface::Source::ConfirmStreamingRequestV2(){}; -void LeAudioClientInterface::Source::CancelStreamingRequestV2(){}; +void LeAudioClientInterface::Source::ConfirmStreamingRequest() {} +void LeAudioClientInterface::Source::CancelStreamingRequest() {} +void LeAudioClientInterface::Source::ConfirmStreamingRequestV2() {} +void LeAudioClientInterface::Source::CancelStreamingRequestV2() {} void LeAudioClientInterface::Source::UpdateAudioConfigToHal( - const ::bluetooth::le_audio::offload_config& config){}; + const ::bluetooth::le_audio::offload_config& config) {} void LeAudioClientInterface::Source::SuspendedForReconfiguration() {} void LeAudioClientInterface::Source::ReconfigurationComplete() {} -size_t LeAudioClientInterface::Source::Write(const uint8_t* p_buf, - uint32_t len) { +size_t LeAudioClientInterface::Source::Write(const uint8_t* p_buf, uint32_t len) { return source_mock->Write(p_buf, len); } @@ -243,33 +221,27 @@ size_t LeAudioClientInterface::Sink::Read(uint8_t* p_buf, uint32_t len) { } // namespace audio } // namespace bluetooth -class MockLeAudioClientAudioSinkEventReceiver - : public LeAudioSourceAudioHalClient::Callbacks { - public: - MOCK_METHOD((void), OnAudioDataReady, (const std::vector& data), - (override)); +class MockLeAudioClientAudioSinkEventReceiver : public LeAudioSourceAudioHalClient::Callbacks { +public: + MOCK_METHOD((void), OnAudioDataReady, (const std::vector& data), (override)); MOCK_METHOD((void), OnAudioSuspend, (), (override)); MOCK_METHOD((void), OnAudioResume, (), (override)); - MOCK_METHOD( - (void), OnAudioMetadataUpdate, - (const std::vector source_metadata, - DsaMode dsa_mode), - (override)); + MOCK_METHOD((void), OnAudioMetadataUpdate, + (const std::vector source_metadata, + DsaMode dsa_mode), + (override)); }; -class MockAudioHalClientEventReceiver - : public LeAudioSinkAudioHalClient::Callbacks { - public: +class MockAudioHalClientEventReceiver : public LeAudioSinkAudioHalClient::Callbacks { +public: MOCK_METHOD((void), OnAudioSuspend, (), (override)); MOCK_METHOD((void), OnAudioResume, (), (override)); - MOCK_METHOD( - (void), OnAudioMetadataUpdate, - (const std::vector sink_metadata), - (override)); + MOCK_METHOD((void), OnAudioMetadataUpdate, + (const std::vector sink_metadata), (override)); }; class LeAudioClientAudioTest : public ::testing::Test { - protected: +protected: void SetUp(void) override { init_message_loop_thread(); bluetooth::audio::le_audio::interface_mock = &mock_client_interface_; @@ -281,23 +253,22 @@ class LeAudioClientAudioTest : public ::testing::Test { sink_audio_hal_stream_cb = {.on_resume_ = nullptr, .on_suspend_ = nullptr}; ON_CALL(mock_client_interface_, GetSink(_, _, _)) - .WillByDefault(DoAll(SaveArg<0>(&sink_audio_hal_stream_cb), - Assign(&is_sink_audio_hal_acquired, true), - Return(bluetooth::audio::le_audio::sink_mock))); + .WillByDefault(DoAll(SaveArg<0>(&sink_audio_hal_stream_cb), + Assign(&is_sink_audio_hal_acquired, true), + Return(bluetooth::audio::le_audio::sink_mock))); ON_CALL(mock_hal_interface_audio_sink_, Cleanup()) - .WillByDefault(Assign(&is_sink_audio_hal_acquired, false)); + .WillByDefault(Assign(&is_sink_audio_hal_acquired, false)); // Init source Audio HAL mock is_source_audio_hal_acquired = false; - source_audio_hal_stream_cb = {.on_resume_ = nullptr, - .on_suspend_ = nullptr}; + source_audio_hal_stream_cb = {.on_resume_ = nullptr, .on_suspend_ = nullptr}; ON_CALL(mock_client_interface_, GetSource(_, _)) - .WillByDefault(DoAll(SaveArg<0>(&source_audio_hal_stream_cb), - Assign(&is_source_audio_hal_acquired, true), - Return(bluetooth::audio::le_audio::source_mock))); + .WillByDefault(DoAll(SaveArg<0>(&source_audio_hal_stream_cb), + Assign(&is_source_audio_hal_acquired, true), + Return(bluetooth::audio::le_audio::source_mock))); ON_CALL(mock_hal_interface_audio_source_, Cleanup()) - .WillByDefault(Assign(&is_source_audio_hal_acquired, false)); + .WillByDefault(Assign(&is_source_audio_hal_acquired, false)); } bool AcquireLeAudioSinkHalClient(void) { @@ -325,8 +296,12 @@ class LeAudioClientAudioTest : public ::testing::Test { * If on the HAL end Source is running it means we are running the Sink * on our end, and vice versa. */ - if (is_source_audio_hal_acquired == true) ReleaseLeAudioSinkHalClient(); - if (is_sink_audio_hal_acquired == true) ReleaseLeAudioSourceHalClient(); + if (is_source_audio_hal_acquired == true) { + ReleaseLeAudioSinkHalClient(); + } + if (is_sink_audio_hal_acquired == true) { + ReleaseLeAudioSourceHalClient(); + } cleanup_message_loop_thread(); @@ -350,10 +325,10 @@ class LeAudioClientAudioTest : public ::testing::Test { bluetooth::audio::le_audio::StreamCallbacks sink_audio_hal_stream_cb; const LeAudioCodecConfiguration default_codec_conf{ - .num_channels = LeAudioCodecConfiguration::kChannelNumberMono, - .sample_rate = LeAudioCodecConfiguration::kSampleRate44100, - .bits_per_sample = LeAudioCodecConfiguration::kBitsPerSample24, - .data_interval_us = LeAudioCodecConfiguration::kInterval10000Us, + .num_channels = LeAudioCodecConfiguration::kChannelNumberMono, + .sample_rate = LeAudioCodecConfiguration::kSampleRate44100, + .bits_per_sample = LeAudioCodecConfiguration::kBitsPerSample24, + .data_interval_us = LeAudioCodecConfiguration::kInterval10000Us, }; }; @@ -376,19 +351,16 @@ TEST_F(LeAudioClientAudioTest, testAudioHalClientInitializeCleanup) { TEST_F(LeAudioClientAudioTest, testLeAudioClientAudioSinkStartStop) { LeAudioClientInterface::PcmParameters params; EXPECT_CALL(mock_hal_interface_audio_source_, SetPcmParameters(_)) - .Times(1) - .WillOnce(SaveArg<0>(¶ms)); + .Times(1) + .WillOnce(SaveArg<0>(¶ms)); EXPECT_CALL(mock_hal_interface_audio_source_, StartSession()).Times(1); ASSERT_TRUE(AcquireLeAudioSinkHalClient()); - ASSERT_TRUE(audio_sink_instance_->Start(default_codec_conf, - &mock_hal_source_event_receiver_)); + ASSERT_TRUE(audio_sink_instance_->Start(default_codec_conf, &mock_hal_source_event_receiver_)); - ASSERT_EQ(params.channels_count, - bluetooth::audio::le_audio::kChannelNumberMono); + ASSERT_EQ(params.channels_count, bluetooth::audio::le_audio::kChannelNumberMono); ASSERT_EQ(params.sample_rate, bluetooth::audio::le_audio::kSampleRate44100); - ASSERT_EQ(params.bits_per_sample, - bluetooth::audio::le_audio::kBitsPerSample24); + ASSERT_EQ(params.bits_per_sample, bluetooth::audio::le_audio::kBitsPerSample24); ASSERT_EQ(params.data_interval_us, 10000u); EXPECT_CALL(mock_hal_interface_audio_source_, StopSession()).Times(1); @@ -399,19 +371,16 @@ TEST_F(LeAudioClientAudioTest, testLeAudioClientAudioSinkStartStop) { TEST_F(LeAudioClientAudioTest, testAudioHalClientStartStop) { LeAudioClientInterface::PcmParameters params; EXPECT_CALL(mock_hal_interface_audio_sink_, SetPcmParameters(_)) - .Times(1) - .WillOnce(SaveArg<0>(¶ms)); + .Times(1) + .WillOnce(SaveArg<0>(¶ms)); EXPECT_CALL(mock_hal_interface_audio_sink_, StartSession()).Times(1); ASSERT_TRUE(AcquireLeAudioSourceHalClient()); - ASSERT_TRUE(audio_source_instance_->Start(default_codec_conf, - &mock_hal_sink_event_receiver_)); + ASSERT_TRUE(audio_source_instance_->Start(default_codec_conf, &mock_hal_sink_event_receiver_)); - ASSERT_EQ(params.channels_count, - bluetooth::audio::le_audio::kChannelNumberMono); + ASSERT_EQ(params.channels_count, bluetooth::audio::le_audio::kChannelNumberMono); ASSERT_EQ(params.sample_rate, bluetooth::audio::le_audio::kSampleRate44100); - ASSERT_EQ(params.bits_per_sample, - bluetooth::audio::le_audio::kBitsPerSample24); + ASSERT_EQ(params.bits_per_sample, bluetooth::audio::le_audio::kBitsPerSample24); ASSERT_EQ(params.data_interval_us, 10000u); EXPECT_CALL(mock_hal_interface_audio_sink_, StopSession()).Times(1); @@ -421,23 +390,20 @@ TEST_F(LeAudioClientAudioTest, testAudioHalClientStartStop) { TEST_F(LeAudioClientAudioTest, testLeAudioClientAudioSinkSendData) { ASSERT_TRUE(AcquireLeAudioSinkHalClient()); - ASSERT_TRUE(audio_sink_instance_->Start(default_codec_conf, - &mock_hal_source_event_receiver_)); + ASSERT_TRUE(audio_sink_instance_->Start(default_codec_conf, &mock_hal_source_event_receiver_)); const uint8_t* exp_p = nullptr; uint32_t exp_len = 0; uint8_t input_buf[] = { - 0x02, - 0x03, - 0x05, - 0x19, + 0x02, + 0x03, + 0x05, + 0x19, }; ON_CALL(mock_hal_interface_audio_source_, Write(_, _)) - .WillByDefault(DoAll(SaveArg<0>(&exp_p), SaveArg<1>(&exp_len), - ReturnPointee(&exp_len))); + .WillByDefault(DoAll(SaveArg<0>(&exp_p), SaveArg<1>(&exp_len), ReturnPointee(&exp_len))); - ASSERT_EQ(audio_sink_instance_->SendData(input_buf, sizeof(input_buf)), - sizeof(input_buf)); + ASSERT_EQ(audio_sink_instance_->SendData(input_buf, sizeof(input_buf)), sizeof(input_buf)); ASSERT_EQ(exp_len, sizeof(input_buf)); ASSERT_EQ(exp_p, input_buf); @@ -446,8 +412,7 @@ TEST_F(LeAudioClientAudioTest, testLeAudioClientAudioSinkSendData) { TEST_F(LeAudioClientAudioTest, testLeAudioClientAudioSinkSuspend) { ASSERT_TRUE(AcquireLeAudioSinkHalClient()); - ASSERT_TRUE(audio_sink_instance_->Start(default_codec_conf, - &mock_hal_source_event_receiver_)); + ASSERT_TRUE(audio_sink_instance_->Start(default_codec_conf, &mock_hal_source_event_receiver_)); ASSERT_NE(source_audio_hal_stream_cb.on_suspend_, nullptr); @@ -460,8 +425,7 @@ TEST_F(LeAudioClientAudioTest, testLeAudioClientAudioSinkSuspend) { TEST_F(LeAudioClientAudioTest, testAudioHalClientSuspend) { ASSERT_TRUE(AcquireLeAudioSourceHalClient()); - ASSERT_TRUE(audio_source_instance_->Start(default_codec_conf, - &mock_hal_sink_event_receiver_)); + ASSERT_TRUE(audio_source_instance_->Start(default_codec_conf, &mock_hal_sink_event_receiver_)); ASSERT_NE(sink_audio_hal_stream_cb.on_suspend_, nullptr); @@ -474,8 +438,7 @@ TEST_F(LeAudioClientAudioTest, testAudioHalClientSuspend) { TEST_F(LeAudioClientAudioTest, testLeAudioClientAudioSinkResume) { ASSERT_TRUE(AcquireLeAudioSinkHalClient()); - ASSERT_TRUE(audio_sink_instance_->Start(default_codec_conf, - &mock_hal_source_event_receiver_)); + ASSERT_TRUE(audio_sink_instance_->Start(default_codec_conf, &mock_hal_source_event_receiver_)); ASSERT_NE(source_audio_hal_stream_cb.on_resume_, nullptr); @@ -489,40 +452,39 @@ TEST_F(LeAudioClientAudioTest, testLeAudioClientAudioSinkResume) { TEST_F(LeAudioClientAudioTest, testAudioHalClientResumeStartSourceTask) { const LeAudioCodecConfiguration codec_conf{ - .num_channels = LeAudioCodecConfiguration::kChannelNumberStereo, - .sample_rate = LeAudioCodecConfiguration::kSampleRate16000, - .bits_per_sample = LeAudioCodecConfiguration::kBitsPerSample24, - .data_interval_us = LeAudioCodecConfiguration::kInterval10000Us, + .num_channels = LeAudioCodecConfiguration::kChannelNumberStereo, + .sample_rate = LeAudioCodecConfiguration::kSampleRate16000, + .bits_per_sample = LeAudioCodecConfiguration::kBitsPerSample24, + .data_interval_us = LeAudioCodecConfiguration::kInterval10000Us, }; ASSERT_TRUE(AcquireLeAudioSourceHalClient()); - ASSERT_TRUE(audio_source_instance_->Start(codec_conf, - &mock_hal_sink_event_receiver_)); + ASSERT_TRUE(audio_source_instance_->Start(codec_conf, &mock_hal_sink_event_receiver_)); std::promise promise; auto future = promise.get_future(); uint32_t calculated_bytes_per_tick = 0; EXPECT_CALL(mock_hal_interface_audio_sink_, Read(_, _)) - .Times(AtLeast(1)) - .WillOnce(Invoke([&](uint8_t* p_buf, uint32_t len) -> uint32_t { - calculated_bytes_per_tick = len; - - // fake some data from audio framework - for (uint32_t i = 0u; i < len; ++i) { - p_buf[i] = i; - } - - // Return exactly as much data as requested - promise.set_value(); - return len; - })) - .WillRepeatedly(Invoke([](uint8_t* p_buf, uint32_t len) -> uint32_t { - // fake some data from audio framework - for (uint32_t i = 0u; i < len; ++i) { - p_buf[i] = i; - } - return len; - })); + .Times(AtLeast(1)) + .WillOnce(Invoke([&](uint8_t* p_buf, uint32_t len) -> uint32_t { + calculated_bytes_per_tick = len; + + // fake some data from audio framework + for (uint32_t i = 0u; i < len; ++i) { + p_buf[i] = i; + } + + // Return exactly as much data as requested + promise.set_value(); + return len; + })) + .WillRepeatedly(Invoke([](uint8_t* p_buf, uint32_t len) -> uint32_t { + // fake some data from audio framework + for (uint32_t i = 0u; i < len; ++i) { + p_buf[i] = i; + } + return len; + })); std::promise data_promise; auto data_future = data_promise.get_future(); @@ -530,12 +492,12 @@ TEST_F(LeAudioClientAudioTest, testAudioHalClientResumeStartSourceTask) { /* Expect this callback to be called to Client by the HAL glue layer */ std::vector media_data_to_send; EXPECT_CALL(mock_hal_sink_event_receiver_, OnAudioDataReady(_)) - .Times(AtLeast(1)) - .WillOnce(Invoke([&](const std::vector& data) -> void { - media_data_to_send = std::move(data); - data_promise.set_value(); - })) - .WillRepeatedly(DoDefault()); + .Times(AtLeast(1)) + .WillOnce(Invoke([&](const std::vector& data) -> void { + media_data_to_send = std::move(data); + data_promise.set_value(); + })) + .WillRepeatedly(DoDefault()); /* Expect LeAudio registered event listener to get called when HAL calls the * audio_hal_client's internal resume callback. @@ -546,18 +508,15 @@ TEST_F(LeAudioClientAudioTest, testAudioHalClientResumeStartSourceTask) { ASSERT_TRUE(sink_audio_hal_stream_cb.on_resume_(start_media_task)); audio_source_instance_->ConfirmStreamingRequest(); - ASSERT_EQ(future.wait_for(std::chrono::seconds(1)), - std::future_status::ready); + ASSERT_EQ(future.wait_for(std::chrono::seconds(1)), std::future_status::ready); - ASSERT_EQ(data_future.wait_for(std::chrono::seconds(1)), - std::future_status::ready); + ASSERT_EQ(data_future.wait_for(std::chrono::seconds(1)), std::future_status::ready); // Check agains expected payload size // 24 bit audio stream is sent as unpacked, each sample takes 4 bytes. const uint32_t channel_bytes_per_sample = 4; const uint32_t channel_bytes_per_10ms_at_16000Hz = - ((10ms).count() * channel_bytes_per_sample * 16000 /*Hz*/) / - (1000ms).count(); + ((10ms).count() * channel_bytes_per_sample * 16000 /*Hz*/) / (1000ms).count(); // Expect 2 channel (stereo) data ASSERT_EQ(calculated_bytes_per_tick, 2 * channel_bytes_per_10ms_at_16000Hz); @@ -568,8 +527,7 @@ TEST_F(LeAudioClientAudioTest, testAudioHalClientResumeStartSourceTask) { TEST_F(LeAudioClientAudioTest, testAudioHalClientResume) { ASSERT_TRUE(AcquireLeAudioSourceHalClient()); - ASSERT_TRUE(audio_source_instance_->Start(default_codec_conf, - &mock_hal_sink_event_receiver_)); + ASSERT_TRUE(audio_source_instance_->Start(default_codec_conf, &mock_hal_sink_event_receiver_)); ASSERT_NE(sink_audio_hal_stream_cb.on_resume_, nullptr); diff --git a/system/bta/le_audio/audio_hal_client/audio_sink_hal_client.cc b/system/bta/le_audio/audio_hal_client/audio_sink_hal_client.cc index b69cc0d86a8..5678852a39c 100644 --- a/system/bta/le_audio/audio_hal_client/audio_sink_hal_client.cc +++ b/system/bta/le_audio/audio_hal_client/audio_sink_hal_client.cc @@ -38,25 +38,25 @@ enum { } le_audio_source_hal_state; class SinkImpl : public LeAudioSinkAudioHalClient { - public: +public: // Interface implementation bool Start(const LeAudioCodecConfiguration& codecConfiguration, - LeAudioSinkAudioHalClient::Callbacks* audioReceiver, - DsaModes dsa_modes) override; + LeAudioSinkAudioHalClient::Callbacks* audioReceiver, DsaModes dsa_modes) override; void Stop(); size_t SendData(uint8_t* data, uint16_t size) override; void ConfirmStreamingRequest() override; void CancelStreamingRequest() override; void UpdateRemoteDelay(uint16_t remote_delay_ms) override; - void UpdateAudioConfigToHal( - const ::bluetooth::le_audio::offload_config& config) override; + void UpdateAudioConfigToHal(const ::bluetooth::le_audio::offload_config& config) override; void SuspendedForReconfiguration() override; void ReconfigurationComplete() override; // Internal functionality SinkImpl() = default; ~SinkImpl() override { - if (le_audio_source_hal_state != HAL_UNINITIALIZED) Release(); + if (le_audio_source_hal_state != HAL_UNINITIALIZED) { + Release(); + } } bool OnResumeReq(bool start_media_task); @@ -65,18 +65,16 @@ class SinkImpl : public LeAudioSinkAudioHalClient { bool Acquire(); void Release(); - bluetooth::audio::le_audio::LeAudioClientInterface::Source* - halSourceInterface_ = nullptr; + bluetooth::audio::le_audio::LeAudioClientInterface::Source* halSourceInterface_ = nullptr; LeAudioSinkAudioHalClient::Callbacks* audioSinkCallbacks_ = nullptr; }; bool SinkImpl::Acquire() { auto source_stream_cb = bluetooth::audio::le_audio::StreamCallbacks{ - .on_resume_ = - std::bind(&SinkImpl::OnResumeReq, this, std::placeholders::_1), - .on_suspend_ = std::bind(&SinkImpl::OnSuspendReq, this), - .on_sink_metadata_update_ = std::bind(&SinkImpl::OnMetadataUpdateReq, - this, std::placeholders::_1), + .on_resume_ = std::bind(&SinkImpl::OnResumeReq, this, std::placeholders::_1), + .on_suspend_ = std::bind(&SinkImpl::OnSuspendReq, this), + .on_sink_metadata_update_ = + std::bind(&SinkImpl::OnMetadataUpdateReq, this, std::placeholders::_1), }; auto halInterface = audio::le_audio::LeAudioClientInterface::Get(); @@ -85,8 +83,7 @@ bool SinkImpl::Acquire() { return false; } - halSourceInterface_ = - halInterface->GetSource(source_stream_cb, get_main_thread()); + halSourceInterface_ = halInterface->GetSource(source_stream_cb, get_main_thread()); if (halSourceInterface_ == nullptr) { log::error("Can't get Audio HAL Audio source interface"); @@ -132,9 +129,8 @@ bool SinkImpl::OnResumeReq(bool start_media_task) { } bt_status_t status = do_in_main_thread( - FROM_HERE, - base::BindOnce(&LeAudioSinkAudioHalClient::Callbacks::OnAudioResume, - audioSinkCallbacks_->weak_factory_.GetWeakPtr())); + FROM_HERE, base::BindOnce(&LeAudioSinkAudioHalClient::Callbacks::OnAudioResume, + audioSinkCallbacks_->weak_factory_.GetWeakPtr())); if (status == BT_STATUS_SUCCESS) { return true; } @@ -150,9 +146,8 @@ bool SinkImpl::OnSuspendReq() { } bt_status_t status = do_in_main_thread( - FROM_HERE, - base::BindOnce(&LeAudioSinkAudioHalClient::Callbacks::OnAudioSuspend, - audioSinkCallbacks_->weak_factory_.GetWeakPtr())); + FROM_HERE, base::BindOnce(&LeAudioSinkAudioHalClient::Callbacks::OnAudioSuspend, + audioSinkCallbacks_->weak_factory_.GetWeakPtr())); if (status == BT_STATUS_SUCCESS) { return true; } @@ -168,14 +163,12 @@ bool SinkImpl::OnMetadataUpdateReq(const sink_metadata_v7_t& sink_metadata) { } std::vector metadata( - sink_metadata.tracks, sink_metadata.tracks + sink_metadata.track_count); + sink_metadata.tracks, sink_metadata.tracks + sink_metadata.track_count); bt_status_t status = do_in_main_thread( - FROM_HERE, - base::BindOnce( - &LeAudioSinkAudioHalClient::Callbacks::OnAudioMetadataUpdate, - audioSinkCallbacks_->weak_factory_.GetWeakPtr(), - std::move(metadata))); + FROM_HERE, + base::BindOnce(&LeAudioSinkAudioHalClient::Callbacks::OnAudioMetadataUpdate, + audioSinkCallbacks_->weak_factory_.GetWeakPtr(), std::move(metadata))); if (status == BT_STATUS_SUCCESS) { return true; } @@ -185,8 +178,7 @@ bool SinkImpl::OnMetadataUpdateReq(const sink_metadata_v7_t& sink_metadata) { } bool SinkImpl::Start(const LeAudioCodecConfiguration& codec_configuration, - LeAudioSinkAudioHalClient::Callbacks* audioReceiver, - DsaModes dsa_modes) { + LeAudioSinkAudioHalClient::Callbacks* audioReceiver, DsaModes dsa_modes) { if (!halSourceInterface_) { log::error("Audio HAL Audio source interface not acquired"); return false; @@ -197,16 +189,15 @@ bool SinkImpl::Start(const LeAudioCodecConfiguration& codec_configuration, return false; } - log::info( - "bit rate: {}, num channels: {}, sample rate: {}, data interval: {}", - codec_configuration.bits_per_sample, codec_configuration.num_channels, - codec_configuration.sample_rate, codec_configuration.data_interval_us); + log::info("bit rate: {}, num channels: {}, sample rate: {}, data interval: {}", + codec_configuration.bits_per_sample, codec_configuration.num_channels, + codec_configuration.sample_rate, codec_configuration.data_interval_us); audio::le_audio::LeAudioClientInterface::PcmParameters pcmParameters = { - .data_interval_us = codec_configuration.data_interval_us, - .sample_rate = codec_configuration.sample_rate, - .bits_per_sample = codec_configuration.bits_per_sample, - .channels_count = codec_configuration.num_channels}; + .data_interval_us = codec_configuration.data_interval_us, + .sample_rate = codec_configuration.sample_rate, + .bits_per_sample = codec_configuration.bits_per_sample, + .channels_count = codec_configuration.num_channels}; halSourceInterface_->SetPcmParameters(pcmParameters); audio::le_audio::LeAudioClientInterface::Get()->SetAllowedDsaModes(dsa_modes); @@ -250,17 +241,15 @@ size_t SinkImpl::SendData(uint8_t* data, uint16_t size) { /* TODO: What to do if not all data is written ? */ bytes_written = halSourceInterface_->Write(data, size); if (bytes_written != size) { - log::error( - "Not all data is written to source HAL. Bytes written: {}, total: {}", - bytes_written, size); + log::error("Not all data is written to source HAL. Bytes written: {}, total: {}", bytes_written, + size); } return bytes_written; } void SinkImpl::ConfirmStreamingRequest() { - if ((halSourceInterface_ == nullptr) || - (le_audio_source_hal_state != HAL_STARTED)) { + if ((halSourceInterface_ == nullptr) || (le_audio_source_hal_state != HAL_STARTED)) { log::error("Audio HAL Audio source was not started!"); return; } @@ -274,8 +263,7 @@ void SinkImpl::ConfirmStreamingRequest() { } void SinkImpl::SuspendedForReconfiguration() { - if ((halSourceInterface_ == nullptr) || - (le_audio_source_hal_state != HAL_STARTED)) { + if ((halSourceInterface_ == nullptr) || (le_audio_source_hal_state != HAL_STARTED)) { log::error("Audio HAL Audio source was not started!"); return; } @@ -285,8 +273,7 @@ void SinkImpl::SuspendedForReconfiguration() { } void SinkImpl::ReconfigurationComplete() { - if ((halSourceInterface_ == nullptr) || - (le_audio_source_hal_state != HAL_STARTED)) { + if ((halSourceInterface_ == nullptr) || (le_audio_source_hal_state != HAL_STARTED)) { log::error("Audio HAL Audio source was not started!"); return; } @@ -296,8 +283,7 @@ void SinkImpl::ReconfigurationComplete() { } void SinkImpl::CancelStreamingRequest() { - if ((halSourceInterface_ == nullptr) || - (le_audio_source_hal_state != HAL_STARTED)) { + if ((halSourceInterface_ == nullptr) || (le_audio_source_hal_state != HAL_STARTED)) { log::error("Audio HAL Audio source was not started!"); return; } @@ -311,8 +297,7 @@ void SinkImpl::CancelStreamingRequest() { } void SinkImpl::UpdateRemoteDelay(uint16_t remote_delay_ms) { - if ((halSourceInterface_ == nullptr) || - (le_audio_source_hal_state != HAL_STARTED)) { + if ((halSourceInterface_ == nullptr) || (le_audio_source_hal_state != HAL_STARTED)) { log::error("Audio HAL Audio source was not started!"); return; } @@ -321,10 +306,8 @@ void SinkImpl::UpdateRemoteDelay(uint16_t remote_delay_ms) { halSourceInterface_->SetRemoteDelay(remote_delay_ms); } -void SinkImpl::UpdateAudioConfigToHal( - const ::bluetooth::le_audio::offload_config& config) { - if ((halSourceInterface_ == nullptr) || - (le_audio_source_hal_state != HAL_STARTED)) { +void SinkImpl::UpdateAudioConfigToHal(const ::bluetooth::le_audio::offload_config& config) { + if ((halSourceInterface_ == nullptr) || (le_audio_source_hal_state != HAL_STARTED)) { log::error("Audio HAL Audio source was not started!"); return; } @@ -334,8 +317,7 @@ void SinkImpl::UpdateAudioConfigToHal( } } // namespace -std::unique_ptr -LeAudioSinkAudioHalClient::AcquireUnicast() { +std::unique_ptr LeAudioSinkAudioHalClient::AcquireUnicast() { std::unique_ptr impl(new SinkImpl()); if (!impl->Acquire()) { log::error("Could not acquire Unicast Sink on LE Audio HAL enpoint"); diff --git a/system/bta/le_audio/audio_hal_client/audio_source_hal_client.cc b/system/bta/le_audio/audio_hal_client/audio_source_hal_client.cc index 48bcce92c85..94ca1f4cbcf 100644 --- a/system/bta/le_audio/audio_hal_client/audio_source_hal_client.cc +++ b/system/bta/le_audio/audio_hal_client/audio_source_hal_client.cc @@ -57,29 +57,23 @@ class SourceImpl : public LeAudioSourceAudioHalClient { HAL_STARTED, } le_audio_sink_hal_state_; - public: +public: // Interface implementation bool Start(const LeAudioCodecConfiguration& codec_configuration, - LeAudioSourceAudioHalClient::Callbacks* audioReceiver, - DsaModes dsa_modes) override; + LeAudioSourceAudioHalClient::Callbacks* audioReceiver, DsaModes dsa_modes) override; void Stop() override; void ConfirmStreamingRequest() override; void CancelStreamingRequest() override; void UpdateRemoteDelay(uint16_t remote_delay_ms) override; - void UpdateAudioConfigToHal( - const ::bluetooth::le_audio::offload_config& config) override; + void UpdateAudioConfigToHal(const ::bluetooth::le_audio::offload_config& config) override; std::optional GetBroadcastConfig( - const std::vector>& - subgroup_quality, - const std::optional< - std::vector<::bluetooth::le_audio::types::acs_ac_record>>& pacs) - const override; - std::optional< - ::bluetooth::le_audio::set_configurations::AudioSetConfiguration> - GetUnicastConfig(const CodecManager::UnicastConfigurationRequirements& - requirements) const override; + const std::vector>& subgroup_quality, + const std::optional>& pacs) + const override; + std::optional<::bluetooth::le_audio::set_configurations::AudioSetConfiguration> GetUnicastConfig( + const CodecManager::UnicastConfigurationRequirements& requirements) const override; void UpdateBroadcastAudioConfigToHal( - const ::bluetooth::le_audio::broadcast_offload_config& config) override; + const ::bluetooth::le_audio::broadcast_offload_config& config) override; void SuspendedForReconfiguration() override; void ReconfigurationComplete() override; @@ -87,17 +81,17 @@ class SourceImpl : public LeAudioSourceAudioHalClient { SourceImpl(bool is_broadcaster) : le_audio_sink_hal_state_(HAL_UNINITIALIZED), audio_timer_( - /* clock_tick_us= */ bluetooth::common:: - time_get_audio_server_tick_us), + /* clock_tick_us= */ bluetooth::common::time_get_audio_server_tick_us), is_broadcaster_(is_broadcaster) {} ~SourceImpl() override { - if (le_audio_sink_hal_state_ != HAL_UNINITIALIZED) Release(); + if (le_audio_sink_hal_state_ != HAL_UNINITIALIZED) { + Release(); + } } bool OnResumeReq(bool start_media_task); bool OnSuspendReq(); - bool OnMetadataUpdateReq(const source_metadata_v7_t& source_metadata, - DsaMode latency_mode); + bool OnMetadataUpdateReq(const source_metadata_v7_t& source_metadata, DsaMode latency_mode); bool Acquire(); void Release(); bool InitAudioSinkThread(); @@ -111,8 +105,7 @@ class SourceImpl : public LeAudioSourceAudioHalClient { bool is_broadcaster_; - bluetooth::audio::le_audio::LeAudioClientInterface::Sink* halSinkInterface_ = - nullptr; + bluetooth::audio::le_audio::LeAudioClientInterface::Sink* halSinkInterface_ = nullptr; LeAudioSourceAudioHalClient::Callbacks* audioSourceCallbacks_ = nullptr; std::mutex audioSourceCallbacksMutex_; std::unique_ptr asrc_; @@ -120,17 +113,15 @@ class SourceImpl : public LeAudioSourceAudioHalClient { bool SourceImpl::Acquire() { auto sink_stream_cb = bluetooth::audio::le_audio::StreamCallbacks{ - .on_resume_ = - std::bind(&SourceImpl::OnResumeReq, this, std::placeholders::_1), - .on_suspend_ = std::bind(&SourceImpl::OnSuspendReq, this), - .on_metadata_update_ = - std::bind(&SourceImpl::OnMetadataUpdateReq, this, - std::placeholders::_1, std::placeholders::_2), - .on_sink_metadata_update_ = - [](const sink_metadata_v7_t& sink_metadata) { - // TODO: update microphone configuration based on sink metadata - return true; - }, + .on_resume_ = std::bind(&SourceImpl::OnResumeReq, this, std::placeholders::_1), + .on_suspend_ = std::bind(&SourceImpl::OnSuspendReq, this), + .on_metadata_update_ = std::bind(&SourceImpl::OnMetadataUpdateReq, this, + std::placeholders::_1, std::placeholders::_2), + .on_sink_metadata_update_ = + [](const sink_metadata_v7_t& sink_metadata) { + // TODO: update microphone configuration based on sink metadata + return true; + }, }; /* Get pointer to singleton LE audio client interface */ @@ -140,8 +131,7 @@ bool SourceImpl::Acquire() { return false; } - halSinkInterface_ = - halInterface->GetSink(sink_stream_cb, get_main_thread(), is_broadcaster_); + halSinkInterface_ = halInterface->GetSink(sink_stream_cb, get_main_thread(), is_broadcaster_); if (halSinkInterface_ == nullptr) { log::error("Can't get Audio HAL Audio sink interface"); @@ -189,9 +179,8 @@ bool SourceImpl::OnResumeReq(bool start_media_task) { return false; } bt_status_t status = do_in_main_thread( - FROM_HERE, - base::BindOnce(&LeAudioSourceAudioHalClient::Callbacks::OnAudioResume, - audioSourceCallbacks_->weak_factory_.GetWeakPtr())); + FROM_HERE, base::BindOnce(&LeAudioSourceAudioHalClient::Callbacks::OnAudioResume, + audioSourceCallbacks_->weak_factory_.GetWeakPtr())); if (status == BT_STATUS_SUCCESS) { return true; } @@ -208,20 +197,18 @@ void SourceImpl::SendAudioData() { // 24 bit audio is aligned to 32bit int bytes_per_sample = (source_codec_config_.bits_per_sample == 24) - ? 4 - : (source_codec_config_.bits_per_sample / 8); - uint32_t bytes_per_tick = - (source_codec_config_.num_channels * source_codec_config_.sample_rate * - source_codec_config_.data_interval_us / 1000 * bytes_per_sample) / - 1000; + ? 4 + : (source_codec_config_.bits_per_sample / 8); + uint32_t bytes_per_tick = (source_codec_config_.num_channels * source_codec_config_.sample_rate * + source_codec_config_.data_interval_us / 1000 * bytes_per_sample) / + 1000; std::vector data(bytes_per_tick); uint32_t bytes_read = halSinkInterface_->Read(data.data(), bytes_per_tick); if (bytes_read < bytes_per_tick) { sStats.media_read_total_underflow_bytes += bytes_per_tick - bytes_read; sStats.media_read_total_underflow_count++; - sStats.media_read_last_underflow_us = - bluetooth::common::time_get_os_boottime_us(); + sStats.media_read_last_underflow_us = bluetooth::common::time_get_os_boottime_us(); } if (com::android::bluetooth::flags::leaudio_hal_client_asrc()) { @@ -242,9 +229,8 @@ void SourceImpl::SendAudioData() { } bool SourceImpl::InitAudioSinkThread() { - const std::string thread_name = - is_broadcaster_ ? "bt_le_audio_broadcast_sink_worker_thread" - : "bt_le_audio_unicast_sink_worker_thread"; + const std::string thread_name = is_broadcaster_ ? "bt_le_audio_broadcast_sink_worker_thread" + : "bt_le_audio_unicast_sink_worker_thread"; worker_thread_ = new bluetooth::common::MessageLoopThread(thread_name); worker_thread_->StartUp(); @@ -267,14 +253,13 @@ void SourceImpl::StartAudioTicks() { wakelock_acquire(); if (com::android::bluetooth::flags::leaudio_hal_client_asrc()) { asrc_ = std::make_unique( - worker_thread_, source_codec_config_.num_channels, - source_codec_config_.sample_rate, source_codec_config_.bits_per_sample, - source_codec_config_.data_interval_us); + worker_thread_, source_codec_config_.num_channels, source_codec_config_.sample_rate, + source_codec_config_.bits_per_sample, source_codec_config_.data_interval_us); } audio_timer_.SchedulePeriodic( - worker_thread_->GetWeakPtr(), FROM_HERE, - base::BindRepeating(&SourceImpl::SendAudioData, base::Unretained(this)), - std::chrono::microseconds(source_codec_config_.data_interval_us)); + worker_thread_->GetWeakPtr(), FROM_HERE, + base::BindRepeating(&SourceImpl::SendAudioData, base::Unretained(this)), + std::chrono::microseconds(source_codec_config_.data_interval_us)); } void SourceImpl::StopAudioTicks() { @@ -285,13 +270,10 @@ void SourceImpl::StopAudioTicks() { bool SourceImpl::OnSuspendReq() { std::lock_guard guard(audioSourceCallbacksMutex_); - if (CodecManager::GetInstance()->GetCodecLocation() == - types::CodecLocation::HOST) { - if (com::android::bluetooth::flags:: - run_ble_audio_ticks_in_worker_thread()) { + if (CodecManager::GetInstance()->GetCodecLocation() == types::CodecLocation::HOST) { + if (com::android::bluetooth::flags::run_ble_audio_ticks_in_worker_thread()) { worker_thread_->DoInThread( - FROM_HERE, - base::BindOnce(&SourceImpl::StopAudioTicks, base::Unretained(this))); + FROM_HERE, base::BindOnce(&SourceImpl::StopAudioTicks, base::Unretained(this))); } else { StopAudioTicks(); } @@ -303,9 +285,8 @@ bool SourceImpl::OnSuspendReq() { } bt_status_t status = do_in_main_thread( - FROM_HERE, - base::BindOnce(&LeAudioSourceAudioHalClient::Callbacks::OnAudioSuspend, - audioSourceCallbacks_->weak_factory_.GetWeakPtr())); + FROM_HERE, base::BindOnce(&LeAudioSourceAudioHalClient::Callbacks::OnAudioSuspend, + audioSourceCallbacks_->weak_factory_.GetWeakPtr())); if (status == BT_STATUS_SUCCESS) { return true; } @@ -314,8 +295,8 @@ bool SourceImpl::OnSuspendReq() { return false; } -bool SourceImpl::OnMetadataUpdateReq( - const source_metadata_v7_t& source_metadata, DsaMode dsa_mode) { +bool SourceImpl::OnMetadataUpdateReq(const source_metadata_v7_t& source_metadata, + DsaMode dsa_mode) { std::lock_guard guard(audioSourceCallbacksMutex_); if (audioSourceCallbacks_ == nullptr) { log::error("audio receiver not started"); @@ -323,15 +304,12 @@ bool SourceImpl::OnMetadataUpdateReq( } std::vector metadata( - source_metadata.tracks, - source_metadata.tracks + source_metadata.track_count); + source_metadata.tracks, source_metadata.tracks + source_metadata.track_count); bt_status_t status = do_in_main_thread( - FROM_HERE, - base::BindOnce( - &LeAudioSourceAudioHalClient::Callbacks::OnAudioMetadataUpdate, - audioSourceCallbacks_->weak_factory_.GetWeakPtr(), - std::move(metadata), dsa_mode)); + FROM_HERE, base::BindOnce(&LeAudioSourceAudioHalClient::Callbacks::OnAudioMetadataUpdate, + audioSourceCallbacks_->weak_factory_.GetWeakPtr(), + std::move(metadata), dsa_mode)); if (status == BT_STATUS_SUCCESS) { return true; } @@ -341,8 +319,7 @@ bool SourceImpl::OnMetadataUpdateReq( } bool SourceImpl::Start(const LeAudioCodecConfiguration& codec_configuration, - LeAudioSourceAudioHalClient::Callbacks* audioReceiver, - DsaModes dsa_modes) { + LeAudioSourceAudioHalClient::Callbacks* audioReceiver, DsaModes dsa_modes) { if (!halSinkInterface_) { log::error("Audio HAL Audio sink interface not acquired"); return false; @@ -353,20 +330,19 @@ bool SourceImpl::Start(const LeAudioCodecConfiguration& codec_configuration, return false; } - log::info( - "bit rate: {}, num channels: {}, sample rate: {}, data interval: {}", - codec_configuration.bits_per_sample, codec_configuration.num_channels, - codec_configuration.sample_rate, codec_configuration.data_interval_us); + log::info("bit rate: {}, num channels: {}, sample rate: {}, data interval: {}", + codec_configuration.bits_per_sample, codec_configuration.num_channels, + codec_configuration.sample_rate, codec_configuration.data_interval_us); sStats.Reset(); /* Global config for periodic audio data */ source_codec_config_ = codec_configuration; audio::le_audio::LeAudioClientInterface::PcmParameters pcmParameters = { - .data_interval_us = codec_configuration.data_interval_us, - .sample_rate = codec_configuration.sample_rate, - .bits_per_sample = codec_configuration.bits_per_sample, - .channels_count = codec_configuration.num_channels}; + .data_interval_us = codec_configuration.data_interval_us, + .sample_rate = codec_configuration.sample_rate, + .bits_per_sample = codec_configuration.bits_per_sample, + .channels_count = codec_configuration.num_channels}; halSinkInterface_->SetPcmParameters(pcmParameters); audio::le_audio::LeAudioClientInterface::Get()->SetAllowedDsaModes(dsa_modes); @@ -394,13 +370,10 @@ void SourceImpl::Stop() { halSinkInterface_->StopSession(); le_audio_sink_hal_state_ = HAL_STOPPED; - if (CodecManager::GetInstance()->GetCodecLocation() == - types::CodecLocation::HOST) { - if (com::android::bluetooth::flags:: - run_ble_audio_ticks_in_worker_thread()) { + if (CodecManager::GetInstance()->GetCodecLocation() == types::CodecLocation::HOST) { + if (com::android::bluetooth::flags::run_ble_audio_ticks_in_worker_thread()) { worker_thread_->DoInThread( - FROM_HERE, - base::BindOnce(&SourceImpl::StopAudioTicks, base::Unretained(this))); + FROM_HERE, base::BindOnce(&SourceImpl::StopAudioTicks, base::Unretained(this))); } else { StopAudioTicks(); } @@ -411,8 +384,7 @@ void SourceImpl::Stop() { } void SourceImpl::ConfirmStreamingRequest() { - if ((halSinkInterface_ == nullptr) || - (le_audio_sink_hal_state_ != HAL_STARTED)) { + if ((halSinkInterface_ == nullptr) || (le_audio_sink_hal_state_ != HAL_STARTED)) { log::error("Audio HAL Audio sink was not started!"); return; } @@ -423,22 +395,20 @@ void SourceImpl::ConfirmStreamingRequest() { } else { halSinkInterface_->ConfirmStreamingRequest(); } - if (CodecManager::GetInstance()->GetCodecLocation() != - types::CodecLocation::HOST) + if (CodecManager::GetInstance()->GetCodecLocation() != types::CodecLocation::HOST) { return; + } if (com::android::bluetooth::flags::run_ble_audio_ticks_in_worker_thread()) { worker_thread_->DoInThread( - FROM_HERE, - base::BindOnce(&SourceImpl::StartAudioTicks, base::Unretained(this))); + FROM_HERE, base::BindOnce(&SourceImpl::StartAudioTicks, base::Unretained(this))); } else { StartAudioTicks(); } } void SourceImpl::SuspendedForReconfiguration() { - if ((halSinkInterface_ == nullptr) || - (le_audio_sink_hal_state_ != HAL_STARTED)) { + if ((halSinkInterface_ == nullptr) || (le_audio_sink_hal_state_ != HAL_STARTED)) { log::error("Audio HAL Audio sink was not started!"); return; } @@ -448,8 +418,7 @@ void SourceImpl::SuspendedForReconfiguration() { } void SourceImpl::ReconfigurationComplete() { - if ((halSinkInterface_ == nullptr) || - (le_audio_sink_hal_state_ != HAL_STARTED)) { + if ((halSinkInterface_ == nullptr) || (le_audio_sink_hal_state_ != HAL_STARTED)) { log::error("Audio HAL Audio sink was not started!"); return; } @@ -459,8 +428,7 @@ void SourceImpl::ReconfigurationComplete() { } void SourceImpl::CancelStreamingRequest() { - if ((halSinkInterface_ == nullptr) || - (le_audio_sink_hal_state_ != HAL_STARTED)) { + if ((halSinkInterface_ == nullptr) || (le_audio_sink_hal_state_ != HAL_STARTED)) { log::error("Audio HAL Audio sink was not started!"); return; } @@ -474,8 +442,7 @@ void SourceImpl::CancelStreamingRequest() { } void SourceImpl::UpdateRemoteDelay(uint16_t remote_delay_ms) { - if ((halSinkInterface_ == nullptr) || - (le_audio_sink_hal_state_ != HAL_STARTED)) { + if ((halSinkInterface_ == nullptr) || (le_audio_sink_hal_state_ != HAL_STARTED)) { log::error("Audio HAL Audio sink was not started!"); return; } @@ -484,10 +451,8 @@ void SourceImpl::UpdateRemoteDelay(uint16_t remote_delay_ms) { halSinkInterface_->SetRemoteDelay(remote_delay_ms); } -void SourceImpl::UpdateAudioConfigToHal( - const ::bluetooth::le_audio::offload_config& config) { - if ((halSinkInterface_ == nullptr) || - (le_audio_sink_hal_state_ != HAL_STARTED)) { +void SourceImpl::UpdateAudioConfigToHal(const ::bluetooth::le_audio::offload_config& config) { + if ((halSinkInterface_ == nullptr) || (le_audio_sink_hal_state_ != HAL_STARTED)) { log::error("Audio HAL Audio sink was not started!"); return; } @@ -496,12 +461,9 @@ void SourceImpl::UpdateAudioConfigToHal( halSinkInterface_->UpdateAudioConfigToHal(config); } -std::optional -SourceImpl::GetBroadcastConfig( - const std::vector>& - subgroup_quality, - const std::optional< - std::vector<::bluetooth::le_audio::types::acs_ac_record>>& pacs) const { +std::optional SourceImpl::GetBroadcastConfig( + const std::vector>& subgroup_quality, + const std::optional>& pacs) const { if (halSinkInterface_ == nullptr) { log::error("Audio HAL Audio sink is null!"); return std::nullopt; @@ -513,7 +475,7 @@ SourceImpl::GetBroadcastConfig( std::optional<::bluetooth::le_audio::set_configurations::AudioSetConfiguration> SourceImpl::GetUnicastConfig( - const CodecManager::UnicastConfigurationRequirements& requirements) const { + const CodecManager::UnicastConfigurationRequirements& requirements) const { if (halSinkInterface_ == nullptr) { log::error("Audio HAL Audio sink is null!"); return std::nullopt; @@ -521,10 +483,10 @@ SourceImpl::GetUnicastConfig( log::info(""); return halSinkInterface_->GetUnicastConfig(requirements); -}; +} void SourceImpl::UpdateBroadcastAudioConfigToHal( - const ::bluetooth::le_audio::broadcast_offload_config& config) { + const ::bluetooth::le_audio::broadcast_offload_config& config) { if (halSinkInterface_ == nullptr) { log::error("Audio HAL Audio sink interface not acquired"); return; @@ -535,8 +497,7 @@ void SourceImpl::UpdateBroadcastAudioConfigToHal( } } // namespace -std::unique_ptr -LeAudioSourceAudioHalClient::AcquireUnicast() { +std::unique_ptr LeAudioSourceAudioHalClient::AcquireUnicast() { std::unique_ptr impl(new SourceImpl(false)); if (!impl->Acquire()) { log::error("Could not acquire Unicast Source on LE Audio HAL enpoint"); @@ -548,8 +509,7 @@ LeAudioSourceAudioHalClient::AcquireUnicast() { return std::move(impl); } -std::unique_ptr -LeAudioSourceAudioHalClient::AcquireBroadcast() { +std::unique_ptr LeAudioSourceAudioHalClient::AcquireBroadcast() { std::unique_ptr impl(new SourceImpl(true)); if (!impl->Acquire()) { log::error("Could not acquire Broadcast Source on LE Audio HAL enpoint"); @@ -571,10 +531,8 @@ void LeAudioSourceAudioHalClient::DebugDump(int fd) { << sStats.media_read_total_underflow_bytes << "\n Last update time ago in ms (underflow) : " << (sStats.media_read_last_underflow_us > 0 - ? (unsigned long long)(now_us - - sStats.media_read_last_underflow_us) / - 1000 - : 0) + ? (unsigned long long)(now_us - sStats.media_read_last_underflow_us) / 1000 + : 0) << std::endl; dprintf(fd, "%s", stream.str().c_str()); } diff --git a/system/bta/le_audio/broadcaster/broadcast_configuration_provider.cc b/system/bta/le_audio/broadcaster/broadcast_configuration_provider.cc index ac237178c17..3f6c2ae600f 100644 --- a/system/bta/le_audio/broadcaster/broadcast_configuration_provider.cc +++ b/system/bta/le_audio/broadcaster/broadcast_configuration_provider.cc @@ -22,43 +22,55 @@ namespace bluetooth::le_audio { namespace broadcaster { /* Software codec configuration provider */ BroadcastConfiguration GetBroadcastConfig( - const std::vector>& - subgroup_quality) { + const std::vector>& subgroup_quality) { // Select the SW codec parameters based on the first subgroup audio context // Note that the HW offloader may support more quality subgroups. // TODO: Unify the quality selection logic with GetBroadcastOffloadConfig() auto context = types::AudioContexts(subgroup_quality.at(0).first); const std::string* options = - stack_config_get_interface()->get_pts_broadcast_audio_config_options(); + stack_config_get_interface()->get_pts_broadcast_audio_config_options(); if (options) { - if (!options->compare("lc3_stereo_48_1_2")) return lc3_stereo_48_1_2; - if (!options->compare("lc3_stereo_48_2_2")) return lc3_stereo_48_2_2; - if (!options->compare("lc3_stereo_48_3_2")) return lc3_stereo_48_3_2; - if (!options->compare("lc3_stereo_48_4_2")) return lc3_stereo_48_4_2; + if (!options->compare("lc3_stereo_48_1_2")) { + return lc3_stereo_48_1_2; + } + if (!options->compare("lc3_stereo_48_2_2")) { + return lc3_stereo_48_2_2; + } + if (!options->compare("lc3_stereo_48_3_2")) { + return lc3_stereo_48_3_2; + } + if (!options->compare("lc3_stereo_48_4_2")) { + return lc3_stereo_48_4_2; + } } // High quality, Low Latency - if (context.test_any(types::LeAudioContextType::GAME | - types::LeAudioContextType::LIVE)) + if (context.test_any(types::LeAudioContextType::GAME | types::LeAudioContextType::LIVE)) { return lc3_stereo_24_2_1; + } // Standard quality, Low Latency - if (context.test(types::LeAudioContextType::INSTRUCTIONAL)) + if (context.test(types::LeAudioContextType::INSTRUCTIONAL)) { return lc3_mono_16_2_1; + } // Standard quality, High Reliability if (context.test_any(types::LeAudioContextType::SOUNDEFFECTS | - types::LeAudioContextType::UNSPECIFIED)) + types::LeAudioContextType::UNSPECIFIED)) { return lc3_stereo_16_2_2; + } if (context.test_any(types::LeAudioContextType::ALERTS | types::LeAudioContextType::NOTIFICATIONS | - types::LeAudioContextType::EMERGENCYALARM)) + types::LeAudioContextType::EMERGENCYALARM)) { return lc3_mono_16_2_2; + } // High quality, High Reliability - if (context.test(types::LeAudioContextType::MEDIA)) return lc3_stereo_24_2_2; + if (context.test(types::LeAudioContextType::MEDIA)) { + return lc3_stereo_24_2_2; + } // Defaults: Standard quality, High Reliability return lc3_mono_16_2_2; diff --git a/system/bta/le_audio/broadcaster/broadcast_configuration_provider.h b/system/bta/le_audio/broadcaster/broadcast_configuration_provider.h index c5e62722dfe..a4a3ab755dc 100644 --- a/system/bta/le_audio/broadcaster/broadcast_configuration_provider.h +++ b/system/bta/le_audio/broadcaster/broadcast_configuration_provider.h @@ -22,161 +22,140 @@ namespace bluetooth::le_audio { namespace broadcaster { constexpr types::LeAudioCodecId kLeAudioCodecIdLc3 = { - .coding_format = types::kLeAudioCodingFormatLC3, - .vendor_company_id = types::kLeAudioVendorCompanyIdUndefined, - .vendor_codec_id = types::kLeAudioVendorCodecIdUndefined}; + .coding_format = types::kLeAudioCodingFormatLC3, + .vendor_company_id = types::kLeAudioVendorCompanyIdUndefined, + .vendor_codec_id = types::kLeAudioVendorCodecIdUndefined}; // Quality subgroup configurations -static const BroadcastSubgroupCodecConfig lc3_mono_16_2 = - BroadcastSubgroupCodecConfig( +static const BroadcastSubgroupCodecConfig lc3_mono_16_2 = BroadcastSubgroupCodecConfig( kLeAudioCodecIdLc3, {BroadcastSubgroupBisCodecConfig{ - // num_bis - 1, - // bis_channel_cnt_ - 1, - // codec_specific - types::LeAudioLtvMap({ - LTV_ENTRY_SAMPLING_FREQUENCY( - codec_spec_conf::kLeAudioSamplingFreq16000Hz), - LTV_ENTRY_FRAME_DURATION( - codec_spec_conf::kLeAudioCodecFrameDur10000us), - LTV_ENTRY_OCTETS_PER_CODEC_FRAME(40), - }), + // num_bis + 1, + // bis_channel_cnt_ + 1, + // codec_specific + types::LeAudioLtvMap({ + LTV_ENTRY_SAMPLING_FREQUENCY(codec_spec_conf::kLeAudioSamplingFreq16000Hz), + LTV_ENTRY_FRAME_DURATION(codec_spec_conf::kLeAudioCodecFrameDur10000us), + LTV_ENTRY_OCTETS_PER_CODEC_FRAME(40), + }), }}, // bits_per_sample 16); -static const BroadcastSubgroupCodecConfig lc3_stereo_16_2 = - BroadcastSubgroupCodecConfig( +static const BroadcastSubgroupCodecConfig lc3_stereo_16_2 = BroadcastSubgroupCodecConfig( kLeAudioCodecIdLc3, {BroadcastSubgroupBisCodecConfig{ - // num_bis - 2, - // bis_channel_cnt_ - 1, - // codec_specific - types::LeAudioLtvMap({ - LTV_ENTRY_SAMPLING_FREQUENCY( - codec_spec_conf::kLeAudioSamplingFreq16000Hz), - LTV_ENTRY_FRAME_DURATION( - codec_spec_conf::kLeAudioCodecFrameDur10000us), - LTV_ENTRY_OCTETS_PER_CODEC_FRAME(40), - }), + // num_bis + 2, + // bis_channel_cnt_ + 1, + // codec_specific + types::LeAudioLtvMap({ + LTV_ENTRY_SAMPLING_FREQUENCY(codec_spec_conf::kLeAudioSamplingFreq16000Hz), + LTV_ENTRY_FRAME_DURATION(codec_spec_conf::kLeAudioCodecFrameDur10000us), + LTV_ENTRY_OCTETS_PER_CODEC_FRAME(40), + }), }}, // bits_per_sample 16); -static const BroadcastSubgroupCodecConfig lc3_stereo_24_2 = - BroadcastSubgroupCodecConfig( +static const BroadcastSubgroupCodecConfig lc3_stereo_24_2 = BroadcastSubgroupCodecConfig( kLeAudioCodecIdLc3, {BroadcastSubgroupBisCodecConfig{ - // num_bis - 2, - // bis_channel_cnt_ - 1, - // codec_specific - types::LeAudioLtvMap({ - LTV_ENTRY_SAMPLING_FREQUENCY( - codec_spec_conf::kLeAudioSamplingFreq24000Hz), - LTV_ENTRY_FRAME_DURATION( - codec_spec_conf::kLeAudioCodecFrameDur10000us), - LTV_ENTRY_OCTETS_PER_CODEC_FRAME(60), - }), + // num_bis + 2, + // bis_channel_cnt_ + 1, + // codec_specific + types::LeAudioLtvMap({ + LTV_ENTRY_SAMPLING_FREQUENCY(codec_spec_conf::kLeAudioSamplingFreq24000Hz), + LTV_ENTRY_FRAME_DURATION(codec_spec_conf::kLeAudioCodecFrameDur10000us), + LTV_ENTRY_OCTETS_PER_CODEC_FRAME(60), + }), }}, // bits_per_sample 16); -static const BroadcastSubgroupCodecConfig lc3_stereo_48_1 = - BroadcastSubgroupCodecConfig( +static const BroadcastSubgroupCodecConfig lc3_stereo_48_1 = BroadcastSubgroupCodecConfig( kLeAudioCodecIdLc3, {BroadcastSubgroupBisCodecConfig{ - // num_bis - 2, - // bis_channel_cnt_ - 1, - // codec_specific - types::LeAudioLtvMap({ - LTV_ENTRY_SAMPLING_FREQUENCY( - codec_spec_conf::kLeAudioSamplingFreq48000Hz), - LTV_ENTRY_FRAME_DURATION( - codec_spec_conf::kLeAudioCodecFrameDur7500us), - LTV_ENTRY_OCTETS_PER_CODEC_FRAME(75), - }), + // num_bis + 2, + // bis_channel_cnt_ + 1, + // codec_specific + types::LeAudioLtvMap({ + LTV_ENTRY_SAMPLING_FREQUENCY(codec_spec_conf::kLeAudioSamplingFreq48000Hz), + LTV_ENTRY_FRAME_DURATION(codec_spec_conf::kLeAudioCodecFrameDur7500us), + LTV_ENTRY_OCTETS_PER_CODEC_FRAME(75), + }), }}, // bits_per_sample 16); -static const BroadcastSubgroupCodecConfig lc3_stereo_48_2 = - BroadcastSubgroupCodecConfig( +static const BroadcastSubgroupCodecConfig lc3_stereo_48_2 = BroadcastSubgroupCodecConfig( kLeAudioCodecIdLc3, {BroadcastSubgroupBisCodecConfig{ - // num_bis - 2, - // bis_channel_cnt_ - 1, - // codec_specific - types::LeAudioLtvMap({ - LTV_ENTRY_SAMPLING_FREQUENCY( - codec_spec_conf::kLeAudioSamplingFreq48000Hz), - LTV_ENTRY_FRAME_DURATION( - codec_spec_conf::kLeAudioCodecFrameDur10000us), - LTV_ENTRY_OCTETS_PER_CODEC_FRAME(100), - }), + // num_bis + 2, + // bis_channel_cnt_ + 1, + // codec_specific + types::LeAudioLtvMap({ + LTV_ENTRY_SAMPLING_FREQUENCY(codec_spec_conf::kLeAudioSamplingFreq48000Hz), + LTV_ENTRY_FRAME_DURATION(codec_spec_conf::kLeAudioCodecFrameDur10000us), + LTV_ENTRY_OCTETS_PER_CODEC_FRAME(100), + }), }}, // bits_per_sample 16); -static const BroadcastSubgroupCodecConfig lc3_stereo_48_3 = - BroadcastSubgroupCodecConfig( +static const BroadcastSubgroupCodecConfig lc3_stereo_48_3 = BroadcastSubgroupCodecConfig( kLeAudioCodecIdLc3, {BroadcastSubgroupBisCodecConfig{ - // num_bis - 2, - // bis_channel_cnt_ - 1, - // codec_specific - types::LeAudioLtvMap({ - LTV_ENTRY_SAMPLING_FREQUENCY( - codec_spec_conf::kLeAudioSamplingFreq48000Hz), - LTV_ENTRY_FRAME_DURATION( - codec_spec_conf::kLeAudioCodecFrameDur7500us), - LTV_ENTRY_OCTETS_PER_CODEC_FRAME(90), - }), + // num_bis + 2, + // bis_channel_cnt_ + 1, + // codec_specific + types::LeAudioLtvMap({ + LTV_ENTRY_SAMPLING_FREQUENCY(codec_spec_conf::kLeAudioSamplingFreq48000Hz), + LTV_ENTRY_FRAME_DURATION(codec_spec_conf::kLeAudioCodecFrameDur7500us), + LTV_ENTRY_OCTETS_PER_CODEC_FRAME(90), + }), }}, // bits_per_sample 16); -static const BroadcastSubgroupCodecConfig lc3_stereo_48_4 = - BroadcastSubgroupCodecConfig( +static const BroadcastSubgroupCodecConfig lc3_stereo_48_4 = BroadcastSubgroupCodecConfig( kLeAudioCodecIdLc3, {BroadcastSubgroupBisCodecConfig{ - // num_bis - 2, - // bis_channel_cnt_ - 1, - // codec_specific - types::LeAudioLtvMap({ - LTV_ENTRY_SAMPLING_FREQUENCY( - codec_spec_conf::kLeAudioSamplingFreq48000Hz), - LTV_ENTRY_FRAME_DURATION( - codec_spec_conf::kLeAudioCodecFrameDur10000us), - LTV_ENTRY_OCTETS_PER_CODEC_FRAME(120), - }), + // num_bis + 2, + // bis_channel_cnt_ + 1, + // codec_specific + types::LeAudioLtvMap({ + LTV_ENTRY_SAMPLING_FREQUENCY(codec_spec_conf::kLeAudioSamplingFreq48000Hz), + LTV_ENTRY_FRAME_DURATION(codec_spec_conf::kLeAudioCodecFrameDur10000us), + LTV_ENTRY_OCTETS_PER_CODEC_FRAME(120), + }), }}, // bits_per_sample 16); static const types::DataPathConfiguration lc3_data_path = { - .dataPathId = bluetooth::hci::iso_manager::kIsoDataPathHci, - .dataPathConfig = {}, - .isoDataPathConfig = - { - .codecId = kLeAudioCodecIdLc3, - .isTransparent = true, - .controllerDelayUs = 0x00000000, // irrlevant for transparent mode - .configuration = {}, - }, + .dataPathId = bluetooth::hci::iso_manager::kIsoDataPathHci, + .dataPathConfig = {}, + .isoDataPathConfig = + { + .codecId = kLeAudioCodecIdLc3, + .isTransparent = true, + .controllerDelayUs = 0x00000000, // irrlevant for transparent mode + .configuration = {}, + }, }; static const BroadcastQosConfig qos_config_2_10 = BroadcastQosConfig(2, 10); @@ -187,117 +166,116 @@ static const BroadcastQosConfig qos_config_4_65 = BroadcastQosConfig(4, 65); // Standard single subgroup configurations static const BroadcastConfiguration lc3_mono_16_2_1 = { - // subgroup list, qos configuration, data path configuration - .subgroups = {lc3_mono_16_2}, - .qos = qos_config_2_10, - .data_path = lc3_data_path, - .sduIntervalUs = 10000, - .maxSduOctets = 40, - .phy = 0x02, // PHY_LE_2M - .packing = 0, // Sequential - .framing = 0, // Unframed + // subgroup list, qos configuration, data path configuration + .subgroups = {lc3_mono_16_2}, + .qos = qos_config_2_10, + .data_path = lc3_data_path, + .sduIntervalUs = 10000, + .maxSduOctets = 40, + .phy = 0x02, // PHY_LE_2M + .packing = 0, // Sequential + .framing = 0, // Unframed }; static const BroadcastConfiguration lc3_mono_16_2_2 = { - // subgroup list, qos configuration, data path configuration - .subgroups = {lc3_mono_16_2}, - .qos = qos_config_4_60, - .data_path = lc3_data_path, - .sduIntervalUs = 10000, - .maxSduOctets = 40, - .phy = 0x02, // PHY_LE_2M - .packing = 0, // Sequential - .framing = 0, // Unframed + // subgroup list, qos configuration, data path configuration + .subgroups = {lc3_mono_16_2}, + .qos = qos_config_4_60, + .data_path = lc3_data_path, + .sduIntervalUs = 10000, + .maxSduOctets = 40, + .phy = 0x02, // PHY_LE_2M + .packing = 0, // Sequential + .framing = 0, // Unframed }; static const BroadcastConfiguration lc3_stereo_16_2_2 = { - // subgroup list, qos configuration, data path configuration - .subgroups = {lc3_stereo_16_2}, - .qos = qos_config_4_60, - .data_path = lc3_data_path, - .sduIntervalUs = 10000, - .maxSduOctets = 80, - .phy = 0x02, // PHY_LE_2M - .packing = 0, // Sequential - .framing = 0, // Unframed + // subgroup list, qos configuration, data path configuration + .subgroups = {lc3_stereo_16_2}, + .qos = qos_config_4_60, + .data_path = lc3_data_path, + .sduIntervalUs = 10000, + .maxSduOctets = 80, + .phy = 0x02, // PHY_LE_2M + .packing = 0, // Sequential + .framing = 0, // Unframed }; static const BroadcastConfiguration lc3_stereo_24_2_1 = { - // subgroup list, qos configuration, data path configuration - .subgroups = {lc3_stereo_24_2}, - .qos = qos_config_2_10, - .data_path = lc3_data_path, - .sduIntervalUs = 10000, - .maxSduOctets = 120, - .phy = 0x02, // PHY_LE_2M - .packing = 0, // Sequential - .framing = 0, // Unframed + // subgroup list, qos configuration, data path configuration + .subgroups = {lc3_stereo_24_2}, + .qos = qos_config_2_10, + .data_path = lc3_data_path, + .sduIntervalUs = 10000, + .maxSduOctets = 120, + .phy = 0x02, // PHY_LE_2M + .packing = 0, // Sequential + .framing = 0, // Unframed }; static const BroadcastConfiguration lc3_stereo_24_2_2 = { - // subgroup list, qos configuration, data path configuration - .subgroups = {lc3_stereo_24_2}, - .qos = qos_config_4_60, - .data_path = lc3_data_path, - .sduIntervalUs = 10000, - .maxSduOctets = 120, - .phy = 0x02, // PHY_LE_2M - .packing = 0, // Sequential - .framing = 0, // Unframed + // subgroup list, qos configuration, data path configuration + .subgroups = {lc3_stereo_24_2}, + .qos = qos_config_4_60, + .data_path = lc3_data_path, + .sduIntervalUs = 10000, + .maxSduOctets = 120, + .phy = 0x02, // PHY_LE_2M + .packing = 0, // Sequential + .framing = 0, // Unframed }; static const BroadcastConfiguration lc3_stereo_48_1_2 = { - // subgroup list, qos configuration, data path configuration - .subgroups = {lc3_stereo_48_1}, - .qos = qos_config_4_50, - .data_path = lc3_data_path, - .sduIntervalUs = 10000, - .maxSduOctets = 150, - .phy = 0x02, // PHY_LE_2M - .packing = 0, // Sequential - .framing = 0 // Unframed, + // subgroup list, qos configuration, data path configuration + .subgroups = {lc3_stereo_48_1}, + .qos = qos_config_4_50, + .data_path = lc3_data_path, + .sduIntervalUs = 10000, + .maxSduOctets = 150, + .phy = 0x02, // PHY_LE_2M + .packing = 0, // Sequential + .framing = 0 // Unframed, }; static const BroadcastConfiguration lc3_stereo_48_2_2 = { - // subgroup list, qos configuration, data path configuration - .subgroups = {lc3_stereo_48_2}, - .qos = qos_config_4_65, - .data_path = lc3_data_path, - .sduIntervalUs = 10000, - .maxSduOctets = 200, - .phy = 0x02, // PHY_LE_2M - .packing = 0, // Sequential - .framing = 0 // Unframed, + // subgroup list, qos configuration, data path configuration + .subgroups = {lc3_stereo_48_2}, + .qos = qos_config_4_65, + .data_path = lc3_data_path, + .sduIntervalUs = 10000, + .maxSduOctets = 200, + .phy = 0x02, // PHY_LE_2M + .packing = 0, // Sequential + .framing = 0 // Unframed, }; static const BroadcastConfiguration lc3_stereo_48_3_2 = { - // subgroup list, qos configuration, data path configuration - .subgroups = {lc3_stereo_48_3}, - .qos = qos_config_4_50, - .data_path = lc3_data_path, - .sduIntervalUs = 10000, - .maxSduOctets = 180, - .phy = 0x02, // PHY_LE_2M - .packing = 0, // Sequential - .framing = 0 // Unframed, + // subgroup list, qos configuration, data path configuration + .subgroups = {lc3_stereo_48_3}, + .qos = qos_config_4_50, + .data_path = lc3_data_path, + .sduIntervalUs = 10000, + .maxSduOctets = 180, + .phy = 0x02, // PHY_LE_2M + .packing = 0, // Sequential + .framing = 0 // Unframed, }; static const BroadcastConfiguration lc3_stereo_48_4_2 = { - // subgroup list, qos configuration, data path configuration - .subgroups = {lc3_stereo_48_4}, - .qos = qos_config_4_65, - .data_path = lc3_data_path, - .sduIntervalUs = 10000, - .maxSduOctets = 240, - .phy = 0x02, // PHY_LE_2M - .packing = 0, // Sequential - .framing = 0 // Unframed, + // subgroup list, qos configuration, data path configuration + .subgroups = {lc3_stereo_48_4}, + .qos = qos_config_4_65, + .data_path = lc3_data_path, + .sduIntervalUs = 10000, + .maxSduOctets = 240, + .phy = 0x02, // PHY_LE_2M + .packing = 0, // Sequential + .framing = 0 // Unframed, }; // Takes a list of subgroup requirements (audio context, quality index) BroadcastConfiguration GetBroadcastConfig( - const std::vector>& - subgroup_quality); + const std::vector>& subgroup_quality); } // namespace broadcaster } // namespace bluetooth::le_audio diff --git a/system/bta/le_audio/broadcaster/broadcaster.cc b/system/bta/le_audio/broadcaster/broadcaster.cc index e78f5112b32..a494e1ca3f4 100644 --- a/system/bta/le_audio/broadcaster/broadcaster.cc +++ b/system/bta/le_audio/broadcaster/broadcaster.cc @@ -97,8 +97,7 @@ public: log::info(""); /* Register State machine callbacks */ - BroadcastStateMachine::Initialize(&state_machine_callbacks_, - &state_machine_adv_callbacks_); + BroadcastStateMachine::Initialize(&state_machine_callbacks_, &state_machine_adv_callbacks_); GenerateBroadcastIds(); } @@ -110,7 +109,9 @@ public: void GenerateBroadcastIds(void) { btsnd_hcic_ble_rand(base::Bind([](BT_OCTET8 rand) { - if (!instance) return; + if (!instance) { + return; + } /* LE Rand returns 8 octets. Lets' make 2 outstanding Broadcast Ids out * of it */ @@ -118,7 +119,9 @@ public: BroadcastId broadcast_id = 0; /* Broadcast ID should be 3 octets long (BAP v1.0 spec.) */ STREAM_TO_UINT24(broadcast_id, rand); - if (broadcast_id == bluetooth::le_audio::kBroadcastIdInvalid) continue; + if (broadcast_id == bluetooth::le_audio::kBroadcastIdInvalid) { + continue; + } instance->available_broadcast_ids_.emplace_back(broadcast_id); } @@ -134,8 +137,9 @@ public: callbacks_ = nullptr; is_iso_running_ = false; - if (!LeAudioClient::IsLeAudioClientRunning()) + if (!LeAudioClient::IsLeAudioClientRunning()) { IsoManager::GetInstance()->Stop(); + } queued_start_broadcast_request_ = std::nullopt; queued_create_broadcast_request_ = std::nullopt; @@ -143,7 +147,7 @@ public: if (le_audio_source_hal_client_) { le_audio_source_hal_client_->Stop(); CodecManager::GetInstance()->UpdateActiveBroadcastAudioHalClient( - le_audio_source_hal_client_.get(), false); + le_audio_source_hal_client_.get(), false); le_audio_source_hal_client_.reset(); } audio_state_ = AudioState::SUSPENDED; @@ -158,8 +162,8 @@ public: } } - static PublicBroadcastAnnouncementData preparePublicAnnouncement( - uint8_t features, const LeAudioLtvMap& metadata) { + static PublicBroadcastAnnouncementData preparePublicAnnouncement(uint8_t features, + const LeAudioLtvMap& metadata) { PublicBroadcastAnnouncementData announcement; /* Prepare the announcement */ @@ -169,8 +173,8 @@ public: } static BasicAudioAnnouncementData prepareBasicAnnouncement( - const std::vector& subgroup_configs, - const std::vector& metadata_group) { + const std::vector& subgroup_configs, + const std::vector& metadata_group) { BasicAudioAnnouncementData announcement; /* Prepare the announcement */ @@ -183,14 +187,12 @@ public: uint8_t subgroup_idx = 0; uint8_t bis_index = 0; - while (subgroup_idx < subgroup_configs.size() && - subgroup_idx < metadata_group.size()) { + while (subgroup_idx < subgroup_configs.size() && subgroup_idx < metadata_group.size()) { const auto& subgroup_config = subgroup_configs.at(subgroup_idx); const auto& metadata = metadata_group.at(subgroup_idx); auto const& codec_id = subgroup_config.GetLeAudioCodecId(); - auto const subgroup_codec_spec = - subgroup_config.GetCommonBisCodecSpecData(); + auto const subgroup_codec_spec = subgroup_config.GetCommonBisCodecSpecData(); auto opt_vendor_spec_data = subgroup_config.GetVendorCodecSpecData(); /* Note: Currently we have a single audio source configured with a one @@ -199,24 +201,22 @@ public: * subgroup level. */ BasicAudioAnnouncementSubgroup config = { - .codec_config = - { - .codec_id = codec_id.coding_format, - .vendor_company_id = codec_id.vendor_company_id, - .vendor_codec_id = codec_id.vendor_codec_id, - .codec_specific_params = - opt_vendor_spec_data.has_value() - ? std::map>{} - : subgroup_codec_spec.Values(), - .vendor_codec_specific_params = - std::move(opt_vendor_spec_data), - }, - .metadata = metadata.Values(), - .bis_configs = {}, + .codec_config = + { + .codec_id = codec_id.coding_format, + .vendor_company_id = codec_id.vendor_company_id, + .vendor_codec_id = codec_id.vendor_codec_id, + .codec_specific_params = + opt_vendor_spec_data.has_value() + ? std::map>{} + : subgroup_codec_spec.Values(), + .vendor_codec_specific_params = std::move(opt_vendor_spec_data), + }, + .metadata = metadata.Values(), + .bis_configs = {}, }; - for (uint8_t bis_cfg_idx = 0; - bis_cfg_idx < subgroup_config.GetAllBisConfigCount(); + for (uint8_t bis_cfg_idx = 0; bis_cfg_idx < subgroup_config.GetAllBisConfigCount(); ++bis_cfg_idx) { auto bis_cfg_num_of_bises = subgroup_config.GetNumBis(bis_cfg_idx); for (uint8_t bis_num = 0; bis_num < bis_cfg_num_of_bises; ++bis_num) { @@ -226,15 +226,13 @@ public: // Check for vendor byte array bluetooth::le_audio::BasicAudioAnnouncementBisConfig bis_config; - auto vendor_config = - subgroup_config.GetBisVendorCodecSpecData(bis_num); + auto vendor_config = subgroup_config.GetBisVendorCodecSpecData(bis_num); if (vendor_config) { bis_config.vendor_codec_specific_params = vendor_config.value(); } // Check for non vendor LTVs - auto config_ltv = - subgroup_config.GetBisCodecSpecData(bis_num, bis_cfg_idx); + auto config_ltv = subgroup_config.GetBisCodecSpecData(bis_num, bis_cfg_idx); if (config_ltv) { // Remove the part which is common with the parent subgroup // parameters @@ -259,8 +257,7 @@ public: auto ccids = ContentControlIdKeeper::GetInstance()->GetAllCcids(contexts); if (ccids.empty()) { - log::warn("No content providers available for context_type_map={}.", - contexts.to_string()); + log::warn("No content providers available for context_type_map={}.", contexts.to_string()); } std::vector stream_context_vec(2); @@ -278,43 +275,36 @@ public: auto subgroup_ltv = LeAudioLtvMap(subgroup.metadata); bool subgroup_update = false; - auto existing_context = - subgroup_ltv.Find(bluetooth::le_audio::types:: - kLeAudioMetadataTypeStreamingAudioContext); + auto existing_context = subgroup_ltv.Find( + bluetooth::le_audio::types::kLeAudioMetadataTypeStreamingAudioContext); if (existing_context) { if (memcmp(stream_context_vec.data(), existing_context->data(), existing_context->size()) != 0) { - subgroup_ltv.Add(bluetooth::le_audio::types:: - kLeAudioMetadataTypeStreamingAudioContext, - stream_context_vec); + subgroup_ltv.Add( + bluetooth::le_audio::types::kLeAudioMetadataTypeStreamingAudioContext, + stream_context_vec); subgroup_update = true; } } else { - subgroup_ltv.Add(bluetooth::le_audio::types:: - kLeAudioMetadataTypeStreamingAudioContext, + subgroup_ltv.Add(bluetooth::le_audio::types::kLeAudioMetadataTypeStreamingAudioContext, stream_context_vec); subgroup_update = true; } - auto existing_ccid_list = subgroup_ltv.Find( - bluetooth::le_audio::types::kLeAudioMetadataTypeCcidList); + auto existing_ccid_list = + subgroup_ltv.Find(bluetooth::le_audio::types::kLeAudioMetadataTypeCcidList); if (existing_ccid_list) { if (ccids.empty()) { - subgroup_ltv.Remove( - bluetooth::le_audio::types::kLeAudioMetadataTypeCcidList); + subgroup_ltv.Remove(bluetooth::le_audio::types::kLeAudioMetadataTypeCcidList); subgroup_update = true; } else if (!std::is_permutation(ccids.begin(), ccids.end(), existing_ccid_list->begin())) { - subgroup_ltv.Add( - bluetooth::le_audio::types::kLeAudioMetadataTypeCcidList, - ccids); + subgroup_ltv.Add(bluetooth::le_audio::types::kLeAudioMetadataTypeCcidList, ccids); subgroup_update = true; } } else if (!ccids.empty()) { - subgroup_ltv.Add( - bluetooth::le_audio::types::kLeAudioMetadataTypeCcidList, - ccids); + subgroup_ltv.Add(bluetooth::le_audio::types::kLeAudioMetadataTypeCcidList, ccids); subgroup_update = true; } @@ -371,10 +361,9 @@ public: } } - void UpdateMetadata( - uint32_t broadcast_id, const std::string& broadcast_name, - const std::vector& public_metadata, - const std::vector>& subgroup_metadata) override { + void UpdateMetadata(uint32_t broadcast_id, const std::string& broadcast_name, + const std::vector& public_metadata, + const std::vector>& subgroup_metadata) override { std::vector subgroup_ltvs; if (broadcasts_.count(broadcast_id) == 0) { @@ -400,13 +389,10 @@ public: * Conversational context. Even though we are not broadcasting * Conversational streams, some PTS test cases wants multiple CCIDs. */ - if (stack_config_get_interface() - ->get_pts_force_le_audio_multiple_contexts_metadata()) { - context_type = - LeAudioContextType::MEDIA | LeAudioContextType::CONVERSATIONAL; + if (stack_config_get_interface()->get_pts_force_le_audio_multiple_contexts_metadata()) { + context_type = LeAudioContextType::MEDIA | LeAudioContextType::CONVERSATIONAL; auto stream_context_vec = - ltv.Find(bluetooth::le_audio::types:: - kLeAudioMetadataTypeStreamingAudioContext); + ltv.Find(bluetooth::le_audio::types::kLeAudioMetadataTypeStreamingAudioContext); if (stream_context_vec) { auto pp = stream_context_vec.value().data(); if (stream_context_vec.value().size() < 2) { @@ -418,8 +404,7 @@ public: } auto stream_context_vec = - ltv.Find(bluetooth::le_audio::types:: - kLeAudioMetadataTypeStreamingAudioContext); + ltv.Find(bluetooth::le_audio::types::kLeAudioMetadataTypeStreamingAudioContext); if (stream_context_vec) { auto pp = stream_context_vec.value().data(); if (stream_context_vec.value().size() < 2) { @@ -430,11 +415,9 @@ public: } // Append the CCID list - auto ccid_vec = - ContentControlIdKeeper::GetInstance()->GetAllCcids(context_type); + auto ccid_vec = ContentControlIdKeeper::GetInstance()->GetAllCcids(context_type); if (!ccid_vec.empty()) { - ltv.Add(bluetooth::le_audio::types::kLeAudioMetadataTypeCcidList, - ccid_vec); + ltv.Add(bluetooth::le_audio::types::kLeAudioMetadataTypeCcidList, ccid_vec); } // Push to subgroup ltvs @@ -445,9 +428,8 @@ public: // Only update broadcast name and public metadata if current broadcast is // public Otherwise ignore those fields bool is_public_metadata_valid; - LeAudioLtvMap public_ltv = - LeAudioLtvMap::Parse(public_metadata.data(), public_metadata.size(), - is_public_metadata_valid); + LeAudioLtvMap public_ltv = LeAudioLtvMap::Parse( + public_metadata.data(), public_metadata.size(), is_public_metadata_valid); if (!is_public_metadata_valid) { log::error("Invalid public metadata provided."); return; @@ -462,36 +444,31 @@ public: audio_active_state); } - PublicBroadcastAnnouncementData pb_announcement = - preparePublicAnnouncement(broadcasts_[broadcast_id] - ->GetPublicBroadcastAnnouncement() - .features, - public_ltv); + PublicBroadcastAnnouncementData pb_announcement = preparePublicAnnouncement( + broadcasts_[broadcast_id]->GetPublicBroadcastAnnouncement().features, public_ltv); - broadcasts_[broadcast_id]->UpdatePublicBroadcastAnnouncement( - broadcast_id, broadcast_name, pb_announcement); + broadcasts_[broadcast_id]->UpdatePublicBroadcastAnnouncement(broadcast_id, broadcast_name, + pb_announcement); } auto& subgroup_configs = broadcasts_[broadcast_id]->GetCodecConfig(); BasicAudioAnnouncementData announcement = - prepareBasicAnnouncement(subgroup_configs, subgroup_ltvs); + prepareBasicAnnouncement(subgroup_configs, subgroup_ltvs); - broadcasts_[broadcast_id]->UpdateBroadcastAnnouncement( - std::move(announcement)); + broadcasts_[broadcast_id]->UpdateBroadcastAnnouncement(std::move(announcement)); } /* Choose the dominating audio context when multiple contexts are mixed */ - LeAudioContextType ChooseConfigurationContextType( - AudioContexts audio_contexts) { + LeAudioContextType ChooseConfigurationContextType(AudioContexts audio_contexts) { log::debug("Got contexts={}", bluetooth::common::ToString(audio_contexts)); /* Prioritize the most common use cases. */ if (audio_contexts.any()) { LeAudioContextType context_priority_list[] = { - LeAudioContextType::LIVE, LeAudioContextType::GAME, - LeAudioContextType::MEDIA, LeAudioContextType::EMERGENCYALARM, - LeAudioContextType::ALERTS, LeAudioContextType::INSTRUCTIONAL, - LeAudioContextType::NOTIFICATIONS, LeAudioContextType::SOUNDEFFECTS, + LeAudioContextType::LIVE, LeAudioContextType::GAME, + LeAudioContextType::MEDIA, LeAudioContextType::EMERGENCYALARM, + LeAudioContextType::ALERTS, LeAudioContextType::INSTRUCTIONAL, + LeAudioContextType::NOTIFICATIONS, LeAudioContextType::SOUNDEFFECTS, }; for (auto ct : context_priority_list) { if (audio_contexts.test(ct)) { @@ -502,37 +479,33 @@ public: } auto fallback_config = LeAudioContextType::MEDIA; - log::debug("Selecting configuration context type: {}", - ToString(fallback_config)); + log::debug("Selecting configuration context type: {}", ToString(fallback_config)); return fallback_config; } - void CreateAudioBroadcast( - bool is_public, const std::string& broadcast_name, - const std::optional& broadcast_code, - const std::vector& public_metadata, - const std::vector& subgroup_quality, - const std::vector>& subgroup_metadata) override { + void CreateAudioBroadcast(bool is_public, const std::string& broadcast_name, + const std::optional& broadcast_code, + const std::vector& public_metadata, + const std::vector& subgroup_quality, + const std::vector>& subgroup_metadata) override { uint8_t public_features = 0; LeAudioLtvMap public_ltv; std::vector subgroup_ltvs; if (queued_create_broadcast_request_) { log::error("Not processed yet queued broadcast"); - callbacks_->OnBroadcastCreated(bluetooth::le_audio::kBroadcastIdInvalid, - false); + callbacks_->OnBroadcastCreated(bluetooth::le_audio::kBroadcastIdInvalid, false); return; } if (is_public) { // Prepare public broadcast announcement format bool is_metadata_valid; - public_ltv = LeAudioLtvMap::Parse( - public_metadata.data(), public_metadata.size(), is_metadata_valid); + public_ltv = LeAudioLtvMap::Parse(public_metadata.data(), public_metadata.size(), + is_metadata_valid); if (!is_metadata_valid) { log::error("Invalid metadata provided."); - callbacks_->OnBroadcastCreated(bluetooth::le_audio::kBroadcastIdInvalid, - false); + callbacks_->OnBroadcastCreated(bluetooth::le_audio::kBroadcastIdInvalid, false); return; } @@ -550,7 +523,9 @@ public: auto broadcast_id = available_broadcast_ids_.back(); available_broadcast_ids_.pop_back(); - if (available_broadcast_ids_.size() == 0) GenerateBroadcastIds(); + if (available_broadcast_ids_.size() == 0) { + GenerateBroadcastIds(); + } auto context_type = AudioContexts(LeAudioContextType::MEDIA); @@ -559,10 +534,8 @@ public: * Conversational context. Even though we are not broadcasting * Conversational streams, some PTS test cases wants multiple CCIDs. */ - if (stack_config_get_interface() - ->get_pts_force_le_audio_multiple_contexts_metadata()) { - context_type = - LeAudioContextType::MEDIA | LeAudioContextType::CONVERSATIONAL; + if (stack_config_get_interface()->get_pts_force_le_audio_multiple_contexts_metadata()) { + context_type = LeAudioContextType::MEDIA | LeAudioContextType::CONVERSATIONAL; } for (const uint8_t quality : subgroup_quality) { @@ -579,21 +552,17 @@ public: auto ltv = LeAudioLtvMap::Parse(metadata.data(), metadata.size(), is_metadata_valid); if (!is_metadata_valid) { log::error("Invalid metadata provided."); - callbacks_->OnBroadcastCreated(bluetooth::le_audio::kBroadcastIdInvalid, - false); + callbacks_->OnBroadcastCreated(bluetooth::le_audio::kBroadcastIdInvalid, false); return; } - if (stack_config_get_interface() - ->get_pts_force_le_audio_multiple_contexts_metadata()) { + if (stack_config_get_interface()->get_pts_force_le_audio_multiple_contexts_metadata()) { auto stream_context_vec = - ltv.Find(bluetooth::le_audio::types:: - kLeAudioMetadataTypeStreamingAudioContext); + ltv.Find(bluetooth::le_audio::types::kLeAudioMetadataTypeStreamingAudioContext); if (stream_context_vec) { if (stream_context_vec.value().size() < 2) { log::error("kLeAudioMetadataTypeStreamingAudioContext size < 2"); - callbacks_->OnBroadcastCreated( - bluetooth::le_audio::kBroadcastIdInvalid, false); + callbacks_->OnBroadcastCreated(bluetooth::le_audio::kBroadcastIdInvalid, false); return; } auto pp = stream_context_vec.value().data(); @@ -602,13 +571,11 @@ public: } auto stream_context_vec = - ltv.Find(bluetooth::le_audio::types:: - kLeAudioMetadataTypeStreamingAudioContext); + ltv.Find(bluetooth::le_audio::types::kLeAudioMetadataTypeStreamingAudioContext); if (stream_context_vec) { if (stream_context_vec.value().size() < 2) { log::error("kLeAudioMetadataTypeStreamingAudioContext size < 2"); - callbacks_->OnBroadcastCreated( - bluetooth::le_audio::kBroadcastIdInvalid, false); + callbacks_->OnBroadcastCreated(bluetooth::le_audio::kBroadcastIdInvalid, false); return; } @@ -617,11 +584,9 @@ public: } // Append the CCID list - auto ccid_vec = - ContentControlIdKeeper::GetInstance()->GetAllCcids(context_type); + auto ccid_vec = ContentControlIdKeeper::GetInstance()->GetAllCcids(context_type); if (!ccid_vec.empty()) { - ltv.Add(bluetooth::le_audio::types::kLeAudioMetadataTypeCcidList, - ccid_vec); + ltv.Add(bluetooth::le_audio::types::kLeAudioMetadataTypeCcidList, ccid_vec); } // Push to subgroup ltvs @@ -633,19 +598,16 @@ public: // differs in codec configuration. CodecManager::BroadcastConfigurationRequirements requirements; for (auto& idx : subgroup_quality) { - requirements.subgroup_quality.push_back( - {ChooseConfigurationContextType(context_type), idx}); + requirements.subgroup_quality.push_back({ChooseConfigurationContextType(context_type), idx}); } if (!le_audio_source_hal_client_) { - le_audio_source_hal_client_ = - LeAudioSourceAudioHalClient::AcquireBroadcast(); + le_audio_source_hal_client_ = LeAudioSourceAudioHalClient::AcquireBroadcast(); if (!le_audio_source_hal_client_) { log::error("Could not acquire le audio"); return; } - auto result = - CodecManager::GetInstance()->UpdateActiveBroadcastAudioHalClient( + auto result = CodecManager::GetInstance()->UpdateActiveBroadcastAudioHalClient( le_audio_source_hal_client_.get(), true); log::assert_that(result, "Could not update session in codec manager"); } @@ -653,41 +615,34 @@ public: auto config = CodecManager::GetInstance()->GetBroadcastConfig(requirements); if (!config) { log::error("No valid broadcast offload config"); - callbacks_->OnBroadcastCreated(bluetooth::le_audio::kBroadcastIdInvalid, - false); + callbacks_->OnBroadcastCreated(bluetooth::le_audio::kBroadcastIdInvalid, false); return; } if (public_features & bluetooth::le_audio::kLeAudioQualityHigh && config->GetSamplingFrequencyHzMax() < 48000) { - log::warn( - "Preferred quality isn't supported. Fallback to standard audio " - "quality"); + log::warn("Preferred quality isn't supported. Fallback to standard audio quality"); public_features &= (0xFFFF & ~bluetooth::le_audio::kLeAudioQualityHigh); public_features |= bluetooth::le_audio::kLeAudioQualityStandard; } BroadcastStateMachineConfig msg = { - .is_public = is_public, - .broadcast_id = broadcast_id, - .broadcast_name = broadcast_name, - .streaming_phy = GetStreamingPhy(), - .config = *config, - .announcement = - prepareBasicAnnouncement(config->subgroups, subgroup_ltvs), - .broadcast_code = std::move(broadcast_code)}; + .is_public = is_public, + .broadcast_id = broadcast_id, + .broadcast_name = broadcast_name, + .streaming_phy = GetStreamingPhy(), + .config = *config, + .announcement = prepareBasicAnnouncement(config->subgroups, subgroup_ltvs), + .broadcast_code = std::move(broadcast_code)}; if (is_public) { - msg.public_announcement = - preparePublicAnnouncement(public_features, public_ltv); + msg.public_announcement = preparePublicAnnouncement(public_features, public_ltv); } // If there is ongoing ISO traffic, it might be a unicast stream if (is_iso_running_) { log::info("Iso is still active. Queueing broadcast creation for later."); if (queued_create_broadcast_request_) { - log::warn( - "Already queued. Updating queued broadcast creation with the new " - "configuration."); + log::warn("Already queued. Updating queued broadcast creation with the new configuration."); } queued_create_broadcast_request_ = std::move(msg); return; @@ -702,12 +657,10 @@ public: /* Put the new broadcast on the initialization queue, notify the error and * drop the pending broadcast data if init fails. */ - pending_broadcasts_.push_back( - BroadcastStateMachine::CreateInstance(std::move(msg))); + pending_broadcasts_.push_back(BroadcastStateMachine::CreateInstance(std::move(msg))); if (!pending_broadcasts_.back()->Initialize()) { pending_broadcasts_.pop_back(); - callbacks_->OnBroadcastCreated(bluetooth::le_audio::kBroadcastIdInvalid, - false); + callbacks_->OnBroadcastCreated(bluetooth::le_audio::kBroadcastIdInvalid, false); } } @@ -723,23 +676,22 @@ public: } audio_state_ = AudioState::SUSPENDED; broadcasts_[broadcast_id]->SetMuted(true); - broadcasts_[broadcast_id]->ProcessMessage( - BroadcastStateMachine::Message::SUSPEND, nullptr); + broadcasts_[broadcast_id]->ProcessMessage(BroadcastStateMachine::Message::SUSPEND, nullptr); } else { log::error("No such broadcast_id={}", broadcast_id); } } static bool IsAnyoneStreaming() { - if (!instance) return false; - - auto const& iter = - std::find_if(instance->broadcasts_.cbegin(), - instance->broadcasts_.cend(), [](auto const& sm) { - return sm.second->GetState() == - BroadcastStateMachine::State::STREAMING; - }); - return (iter != instance->broadcasts_.cend()); + if (!instance) { + return false; + } + + auto const& iter = std::find_if( + instance->broadcasts_.cbegin(), instance->broadcasts_.cend(), [](auto const& sm) { + return sm.second->GetState() == BroadcastStateMachine::State::STREAMING; + }); + return iter != instance->broadcasts_.cend(); } void StartAudioBroadcast(uint32_t broadcast_id) override { @@ -762,23 +714,19 @@ public: if (broadcasts_.count(broadcast_id) != 0) { if (!le_audio_source_hal_client_) { - le_audio_source_hal_client_ = - LeAudioSourceAudioHalClient::AcquireBroadcast(); + le_audio_source_hal_client_ = LeAudioSourceAudioHalClient::AcquireBroadcast(); if (!le_audio_source_hal_client_) { log::error("Could not acquire le audio"); return; } - auto result = - CodecManager::GetInstance()->UpdateActiveBroadcastAudioHalClient( + auto result = CodecManager::GetInstance()->UpdateActiveBroadcastAudioHalClient( le_audio_source_hal_client_.get(), true); log::assert_that(result, "Could not update session in codec manager"); } - broadcasts_[broadcast_id]->ProcessMessage( - BroadcastStateMachine::Message::START, nullptr); - bluetooth::le_audio::MetricsCollector::Get()->OnBroadcastStateChanged( - true); + broadcasts_[broadcast_id]->ProcessMessage(BroadcastStateMachine::Message::START, nullptr); + bluetooth::le_audio::MetricsCollector::Get()->OnBroadcastStateChanged(true); } else { log::error("No such broadcast_id={}", broadcast_id); } @@ -792,13 +740,13 @@ public: log::info("Stopping AudioHalClient, broadcast_id={}", broadcast_id); - if (le_audio_source_hal_client_) le_audio_source_hal_client_->Stop(); + if (le_audio_source_hal_client_) { + le_audio_source_hal_client_->Stop(); + } audio_state_ = AudioState::SUSPENDED; broadcasts_[broadcast_id]->SetMuted(true); - broadcasts_[broadcast_id]->ProcessMessage( - BroadcastStateMachine::Message::STOP, nullptr); - bluetooth::le_audio::MetricsCollector::Get()->OnBroadcastStateChanged( - false); + broadcasts_[broadcast_id]->ProcessMessage(BroadcastStateMachine::Message::STOP, nullptr); + bluetooth::le_audio::MetricsCollector::Get()->OnBroadcastStateChanged(false); } void DestroyAudioBroadcast(uint32_t broadcast_id) override { @@ -806,8 +754,7 @@ public: broadcasts_.erase(broadcast_id); if (broadcasts_.empty() && le_audio_source_hal_client_) { - auto result = - CodecManager::GetInstance()->UpdateActiveBroadcastAudioHalClient( + auto result = CodecManager::GetInstance()->UpdateActiveBroadcastAudioHalClient( le_audio_source_hal_client_.get(), false); log::assert_that(result, "Could not update session in codec manager"); le_audio_source_hal_client_.reset(); @@ -815,7 +762,7 @@ public: } std::optional GetBroadcastMetadataOpt( - bluetooth::le_audio::BroadcastId broadcast_id) { + bluetooth::le_audio::BroadcastId broadcast_id) { bluetooth::le_audio::BroadcastMetadata metadata; for (auto const& kv_it : broadcasts_) { if (kv_it.second->GetBroadcastId() == broadcast_id) { @@ -827,10 +774,8 @@ public: metadata.addr = kv_it.second->GetOwnAddress(); metadata.addr_type = kv_it.second->GetOwnAddressType(); metadata.broadcast_code = kv_it.second->GetBroadcastCode(); - metadata.basic_audio_announcement = - kv_it.second->GetBroadcastAnnouncement(); - metadata.public_announcement = - kv_it.second->GetPublicBroadcastAnnouncement(); + metadata.basic_audio_announcement = kv_it.second->GetBroadcastAnnouncement(); + metadata.public_announcement = kv_it.second->GetPublicBroadcastAnnouncement(); return metadata; } } @@ -848,24 +793,21 @@ public: log::error("No metadata for broadcast_id={}", broadcast_id); return; } - callbacks_->OnBroadcastMetadataChanged(broadcast_id, - std::move(meta.value())); + callbacks_->OnBroadcastMetadataChanged(broadcast_id, std::move(meta.value())); } void GetAllBroadcastStates(void) override { for (auto const& kv_it : broadcasts_) { callbacks_->OnBroadcastStateChanged( - kv_it.second->GetBroadcastId(), - static_cast( - kv_it.second->GetState())); + kv_it.second->GetBroadcastId(), + static_cast(kv_it.second->GetState())); } } - void IsValidBroadcast( - uint32_t broadcast_id, uint8_t addr_type, RawAddress addr, - base::Callback - cb) override { + void IsValidBroadcast(uint32_t broadcast_id, uint8_t addr_type, RawAddress addr, + base::Callback + cb) override { if (broadcasts_.count(broadcast_id) == 0) { log::error("No such broadcast_id={}", broadcast_id); std::move(cb).Run(broadcast_id, addr_type, addr, false); @@ -873,19 +815,16 @@ public: } broadcasts_[broadcast_id]->RequestOwnAddress(base::Bind( - [](uint32_t broadcast_id, uint8_t req_address_type, - RawAddress req_address, - base::Callback - cb, - uint8_t rcv_address_type, RawAddress rcv_address) { - bool is_local = (req_address_type == rcv_address_type) && - (req_address == rcv_address); - std::move(cb).Run(broadcast_id, req_address_type, req_address, - is_local); - }, - broadcast_id, addr_type, addr, std::move(cb))); + [](uint32_t broadcast_id, uint8_t req_address_type, RawAddress req_address, + base::Callback + cb, + uint8_t rcv_address_type, RawAddress rcv_address) { + bool is_local = + (req_address_type == rcv_address_type) && (req_address == rcv_address); + std::move(cb).Run(broadcast_id, req_address_type, req_address, is_local); + }, + broadcast_id, addr_type, addr, std::move(cb))); } void SetStreamingPhy(uint8_t phy) override { current_phy_ = phy; } @@ -894,26 +833,23 @@ public: BroadcastId BroadcastIdFromBigHandle(uint8_t big_handle) const { auto pair_it = - std::find_if(broadcasts_.begin(), broadcasts_.end(), - [big_handle](auto const& entry) { - return entry.second->GetAdvertisingSid() == big_handle; - }); + std::find_if(broadcasts_.begin(), broadcasts_.end(), [big_handle](auto const& entry) { + return entry.second->GetAdvertisingSid() == big_handle; + }); if (pair_it != broadcasts_.end()) { return pair_it->second->GetBroadcastId(); } return bluetooth::le_audio::kBroadcastIdInvalid; } - void OnSetupIsoDataPath(uint8_t status, uint16_t conn_handle, - uint8_t big_handle) override { + void OnSetupIsoDataPath(uint8_t status, uint16_t conn_handle, uint8_t big_handle) override { auto broadcast_id = BroadcastIdFromBigHandle(big_handle); log::assert_that(broadcasts_.count(broadcast_id) != 0, "assert failed: broadcasts_.count(broadcast_id) != 0"); broadcasts_[broadcast_id]->OnSetupIsoDataPath(status, conn_handle); } - void OnRemoveIsoDataPath(uint8_t status, uint16_t conn_handle, - uint8_t big_handle) override { + void OnRemoveIsoDataPath(uint8_t status, uint16_t conn_handle, uint8_t big_handle) override { auto broadcast_id = BroadcastIdFromBigHandle(big_handle); log::assert_that(broadcasts_.count(broadcast_id) != 0, "assert failed: broadcasts_.count(broadcast_id) != 0"); @@ -927,8 +863,7 @@ public: auto broadcast_id = BroadcastIdFromBigHandle(evt->big_id); log::assert_that(broadcasts_.count(broadcast_id) != 0, "assert failed: broadcasts_.count(broadcast_id) != 0"); - broadcasts_[broadcast_id]->HandleHciEvent(HCI_BLE_CREATE_BIG_CPL_EVT, - evt); + broadcasts_[broadcast_id]->HandleHciEvent(HCI_BLE_CREATE_BIG_CPL_EVT, evt); } break; case bluetooth::hci::iso_manager::kIsoEventBigOnTerminateCmpl: { @@ -936,8 +871,7 @@ public: auto broadcast_id = BroadcastIdFromBigHandle(evt->big_id); log::assert_that(broadcasts_.count(broadcast_id) != 0, "assert failed: broadcasts_.count(broadcast_id) != 0"); - broadcasts_[broadcast_id]->HandleHciEvent(HCI_BLE_TERM_BIG_CPL_EVT, - evt); + broadcasts_[broadcast_id]->HandleHciEvent(HCI_BLE_TERM_BIG_CPL_EVT, evt); if (!com::android::bluetooth::flags::leaudio_big_depends_on_audio_state()) { auto result = CodecManager::GetInstance()->UpdateActiveBroadcastAudioHalClient( le_audio_source_hal_client_.get(), false); @@ -977,79 +911,76 @@ public: stream << " Number of broadcasts: " << broadcasts_.size() << "\n"; for (auto& broadcast_pair : broadcasts_) { auto& broadcast = broadcast_pair.second; - if (broadcast) stream << *broadcast; + if (broadcast) { + stream << *broadcast; + } } dprintf(fd, "%s", stream.str().c_str()); } - private: - void SuspendAudioBroadcasts() { - log::info(""); - for (auto& broadcast_pair : broadcasts_) { - auto& broadcast = broadcast_pair.second; - broadcast->SetMuted(true); - broadcast->ProcessMessage(BroadcastStateMachine::Message::SUSPEND, nullptr); - } - } - - void StopAudioBroadcasts() { - log::info(""); - if (le_audio_source_hal_client_) { - le_audio_source_hal_client_->Stop(); - } - for (auto& broadcast_pair : broadcasts_) { - auto& broadcast = broadcast_pair.second; - broadcast->SetMuted(true); - broadcast->ProcessMessage(BroadcastStateMachine::Message::STOP, nullptr); - } - bluetooth::le_audio::MetricsCollector::Get()->OnBroadcastStateChanged(false); - } - - void setBroadcastTimers() { - if (audio_state_ == AudioState::SUSPENDED) { - log::info(" Started"); - alarm_set_on_mloop( - big_terminate_timer_, kBigTerminateTimeoutMs, - [](void*) { - if (instance) { - instance->SuspendAudioBroadcasts(); - } - }, - nullptr); - - alarm_set_on_mloop( - broadcast_stop_timer_, kBroadcastStopTimeoutMs, - [](void*) { - if (instance) { - instance->StopAudioBroadcasts(); - } - }, - nullptr); - } - } - - void cancelBroadcastTimers() { - log::info(""); - alarm_cancel(big_terminate_timer_); - alarm_cancel(broadcast_stop_timer_); - } - - static class BroadcastStateMachineCallbacks - : public IBroadcastStateMachineCallbacks { - void OnStateMachineCreateStatus(uint32_t broadcast_id, - bool initialized) override { +private: + void SuspendAudioBroadcasts() { + log::info(""); + for (auto& broadcast_pair : broadcasts_) { + auto& broadcast = broadcast_pair.second; + broadcast->SetMuted(true); + broadcast->ProcessMessage(BroadcastStateMachine::Message::SUSPEND, nullptr); + } + } + + void StopAudioBroadcasts() { + log::info(""); + if (le_audio_source_hal_client_) { + le_audio_source_hal_client_->Stop(); + } + for (auto& broadcast_pair : broadcasts_) { + auto& broadcast = broadcast_pair.second; + broadcast->SetMuted(true); + broadcast->ProcessMessage(BroadcastStateMachine::Message::STOP, nullptr); + } + bluetooth::le_audio::MetricsCollector::Get()->OnBroadcastStateChanged(false); + } + + void setBroadcastTimers() { + if (audio_state_ == AudioState::SUSPENDED) { + log::info(" Started"); + alarm_set_on_mloop( + big_terminate_timer_, kBigTerminateTimeoutMs, + [](void*) { + if (instance) { + instance->SuspendAudioBroadcasts(); + } + }, + nullptr); + + alarm_set_on_mloop( + broadcast_stop_timer_, kBroadcastStopTimeoutMs, + [](void*) { + if (instance) { + instance->StopAudioBroadcasts(); + } + }, + nullptr); + } + } + + void cancelBroadcastTimers() { + log::info(""); + alarm_cancel(big_terminate_timer_); + alarm_cancel(broadcast_stop_timer_); + } + + static class BroadcastStateMachineCallbacks : public IBroadcastStateMachineCallbacks { + void OnStateMachineCreateStatus(uint32_t broadcast_id, bool initialized) override { auto pending_broadcast = std::find_if( - instance->pending_broadcasts_.begin(), - instance->pending_broadcasts_.end(), [broadcast_id](auto& sm) { - return (sm->GetBroadcastId() == broadcast_id); - }); + instance->pending_broadcasts_.begin(), instance->pending_broadcasts_.end(), + [broadcast_id](auto& sm) { return sm->GetBroadcastId() == broadcast_id; }); log::assert_that(pending_broadcast != instance->pending_broadcasts_.end(), "assert failed: pending_broadcast != " "instance->pending_broadcasts_.end()"); - log::assert_that( - instance->broadcasts_.count(broadcast_id) == 0, - "assert failed: instance->broadcasts_.count(broadcast_id) == 0"); + log::assert_that(instance->broadcasts_.count(broadcast_id) == 0, + "assert failed: instance->broadcasts_.count(broadcast_id) == 0"); if (initialized) { const uint32_t broadcast_id = (*pending_broadcast)->GetBroadcastId(); @@ -1070,22 +1001,21 @@ public: * machines are erased and instance can already be set to null to avoid * unnecessary calls. */ - if (instance) instance->callbacks_->OnBroadcastDestroyed(broadcast_id); + if (instance) { + instance->callbacks_->OnBroadcastDestroyed(broadcast_id); + } } static int getStreamerCount() { - return std::count_if(instance->broadcasts_.begin(), - instance->broadcasts_.end(), [](auto const& sm) { - log::verbose("broadcast_id={}, state={}", - sm.second->GetBroadcastId(), - ToString(sm.second->GetState())); - return sm.second->GetState() == - BroadcastStateMachine::State::STREAMING; - }); - } - - void OnStateMachineEvent(uint32_t broadcast_id, - BroadcastStateMachine::State state, + return std::count_if( + instance->broadcasts_.begin(), instance->broadcasts_.end(), [](auto const& sm) { + log::verbose("broadcast_id={}, state={}", sm.second->GetBroadcastId(), + ToString(sm.second->GetState())); + return sm.second->GetState() == BroadcastStateMachine::State::STREAMING; + }); + } + + void OnStateMachineEvent(uint32_t broadcast_id, BroadcastStateMachine::State state, const void* data) override { log::info("broadcast_id={} state={}", broadcast_id, ToString(state)); @@ -1114,7 +1044,7 @@ public: broadcast->SetMuted(false); auto is_started = instance->le_audio_source_hal_client_->Start( - broadcast_config.GetAudioHalClientConfig(), &audio_receiver_); + broadcast_config.GetAudioHalClientConfig(), &audio_receiver_); if (!com::android::bluetooth::flags::leaudio_big_depends_on_audio_state()) { if (!is_started) { /* Audio Source setup failed - stop the broadcast */ @@ -1133,22 +1063,18 @@ public: }; instance->callbacks_->OnBroadcastStateChanged( - broadcast_id, - static_cast(state)); + broadcast_id, static_cast(state)); } - void OnOwnAddressResponse(uint32_t broadcast_id, uint8_t addr_type, - RawAddress addr) override { + void OnOwnAddressResponse(uint32_t broadcast_id, uint8_t addr_type, RawAddress addr) override { /* Not used currently */ } void OnBigCreated(const std::vector& conn_handle) { CodecManager::GetInstance()->UpdateBroadcastConnHandle( - conn_handle, - std::bind( - &LeAudioSourceAudioHalClient::UpdateBroadcastAudioConfigToHal, - instance->le_audio_source_hal_client_.get(), - std::placeholders::_1)); + conn_handle, + std::bind(&LeAudioSourceAudioHalClient::UpdateBroadcastAudioConfigToHal, + instance->le_audio_source_hal_client_.get(), std::placeholders::_1)); } void OnAnnouncementUpdated(uint32_t broadcast_id) { @@ -1157,136 +1083,116 @@ public: } state_machine_callbacks_; static class BroadcastAdvertisingCallbacks : public ::AdvertisingCallbacks { - void OnAdvertisingSetStarted(int reg_id, uint8_t advertiser_id, - int8_t tx_power, uint8_t status) { - if (!instance) return; + void OnAdvertisingSetStarted(int reg_id, uint8_t advertiser_id, int8_t tx_power, + uint8_t status) { + if (!instance) { + return; + } if (reg_id == BroadcastStateMachine::kLeAudioBroadcastRegId && !instance->pending_broadcasts_.empty()) { - instance->pending_broadcasts_.back()->OnCreateAnnouncement( - advertiser_id, tx_power, status); + instance->pending_broadcasts_.back()->OnCreateAnnouncement(advertiser_id, tx_power, status); } else { - log::warn( - "Ignored OnAdvertisingSetStarted callback reg_id:{} " - "advertiser_id:{}", - reg_id, advertiser_id); + log::warn("Ignored OnAdvertisingSetStarted callback reg_id:{} advertiser_id:{}", reg_id, + advertiser_id); } } - void OnAdvertisingEnabled(uint8_t advertiser_id, bool enable, - uint8_t status) { - if (!instance) return; + void OnAdvertisingEnabled(uint8_t advertiser_id, bool enable, uint8_t status) { + if (!instance) { + return; + } - auto const& iter = std::find_if( - instance->broadcasts_.cbegin(), instance->broadcasts_.cend(), - [advertiser_id](auto const& sm) { - return sm.second->GetAdvertisingSid() == advertiser_id; - }); + auto const& iter = std::find_if(instance->broadcasts_.cbegin(), instance->broadcasts_.cend(), + [advertiser_id](auto const& sm) { + return sm.second->GetAdvertisingSid() == advertiser_id; + }); if (iter != instance->broadcasts_.cend()) { iter->second->OnEnableAnnouncement(enable, status); } else { - log::warn("Ignored OnAdvertisingEnabled callback advertiser_id:{}", - advertiser_id); + log::warn("Ignored OnAdvertisingEnabled callback advertiser_id:{}", advertiser_id); } } void OnAdvertisingDataSet(uint8_t advertiser_id, uint8_t status) { - if (com::android::bluetooth::flags:: - leaudio_broadcast_update_metadata_callback()) { - if (!instance) return; - - auto const& iter = std::find_if( - instance->broadcasts_.cbegin(), instance->broadcasts_.cend(), - [advertiser_id](auto const& sm) { - return sm.second->GetAdvertisingSid() == advertiser_id; - }); + if (com::android::bluetooth::flags::leaudio_broadcast_update_metadata_callback()) { + if (!instance) { + return; + } + + auto const& iter = + std::find_if(instance->broadcasts_.cbegin(), instance->broadcasts_.cend(), + [advertiser_id](auto const& sm) { + return sm.second->GetAdvertisingSid() == advertiser_id; + }); if (iter != instance->broadcasts_.cend()) { iter->second->OnUpdateAnnouncement(status); } else { - log::warn("Ignored OnAdvertisingDataSet callback advertiser_id:{}", - advertiser_id); + log::warn("Ignored OnAdvertisingDataSet callback advertiser_id:{}", advertiser_id); } } else { - log::warn( - "Not being used, ignored OnAdvertisingDataSet callback " - "advertiser_id:{}", - advertiser_id); + log::warn("Not being used, ignored OnAdvertisingDataSet callback advertiser_id:{}", + advertiser_id); } } void OnScanResponseDataSet(uint8_t advertiser_id, uint8_t status) { - log::warn( - "Not being used, ignored OnScanResponseDataSet callback " - "advertiser_id:{}", - advertiser_id); + log::warn("Not being used, ignored OnScanResponseDataSet callback advertiser_id:{}", + advertiser_id); } - void OnAdvertisingParametersUpdated(uint8_t advertiser_id, int8_t tx_power, - uint8_t status) { - log::warn( - "Not being used, ignored OnAdvertisingParametersUpdated callback " - "advertiser_id:{}", - advertiser_id); + void OnAdvertisingParametersUpdated(uint8_t advertiser_id, int8_t tx_power, uint8_t status) { + log::warn("Not being used, ignored OnAdvertisingParametersUpdated callback advertiser_id:{}", + advertiser_id); } - void OnPeriodicAdvertisingParametersUpdated(uint8_t advertiser_id, - uint8_t status) { + void OnPeriodicAdvertisingParametersUpdated(uint8_t advertiser_id, uint8_t status) { log::warn( - "Not being used, ignored OnPeriodicAdvertisingParametersUpdated " - "callback advertiser_id:{}", - advertiser_id); + "Not being used, ignored OnPeriodicAdvertisingParametersUpdated " + "callback advertiser_id:{}", + advertiser_id); } void OnPeriodicAdvertisingDataSet(uint8_t advertiser_id, uint8_t status) { - if (com::android::bluetooth::flags:: - leaudio_broadcast_update_metadata_callback()) { - if (!instance) return; - - auto const& iter = std::find_if( - instance->broadcasts_.cbegin(), instance->broadcasts_.cend(), - [advertiser_id](auto const& sm) { - return sm.second->GetAdvertisingSid() == advertiser_id; - }); + if (com::android::bluetooth::flags::leaudio_broadcast_update_metadata_callback()) { + if (!instance) { + return; + } + + auto const& iter = + std::find_if(instance->broadcasts_.cbegin(), instance->broadcasts_.cend(), + [advertiser_id](auto const& sm) { + return sm.second->GetAdvertisingSid() == advertiser_id; + }); if (iter != instance->broadcasts_.cend()) { iter->second->OnUpdateAnnouncement(status); } else { - log::warn( - "Ignored OnPeriodicAdvertisingDataSet callback advertiser_id:{}", - advertiser_id); + log::warn("Ignored OnPeriodicAdvertisingDataSet callback advertiser_id:{}", + advertiser_id); } } else { - log::warn( - "Not being used, ignored OnPeriodicAdvertisingDataSet callback " - "advertiser_id:{}", - advertiser_id); + log::warn("Not being used, ignored OnPeriodicAdvertisingDataSet callback advertiser_id:{}", + advertiser_id); } } - void OnPeriodicAdvertisingEnabled(uint8_t advertiser_id, bool enable, - uint8_t status) { - log::warn( - "Not being used, ignored OnPeriodicAdvertisingEnabled callback " - "advertiser_id:{}", - advertiser_id); + void OnPeriodicAdvertisingEnabled(uint8_t advertiser_id, bool enable, uint8_t status) { + log::warn("Not being used, ignored OnPeriodicAdvertisingEnabled callback advertiser_id:{}", + advertiser_id); } - void OnOwnAddressRead(uint8_t advertiser_id, uint8_t address_type, - RawAddress address) { - log::warn( - "Not being used, ignored OnOwnAddressRead callback advertiser_id:{}", - advertiser_id); + void OnOwnAddressRead(uint8_t advertiser_id, uint8_t address_type, RawAddress address) { + log::warn("Not being used, ignored OnOwnAddressRead callback advertiser_id:{}", + advertiser_id); } } state_machine_adv_callbacks_; - static class LeAudioSourceCallbacksImpl - : public LeAudioSourceAudioHalClient::Callbacks { - public: + static class LeAudioSourceCallbacksImpl : public LeAudioSourceAudioHalClient::Callbacks { + public: LeAudioSourceCallbacksImpl() = default; - void CheckAndReconfigureEncoders( - const BroadcastConfiguration& broadcast_config) { + void CheckAndReconfigureEncoders(const BroadcastConfiguration& broadcast_config) { /* TODO: Move software codec instance management to the Codec Manager */ - if (CodecManager::GetInstance()->GetCodecLocation() == - CodecLocation::ADSP) { + if (CodecManager::GetInstance()->GetCodecLocation() == CodecLocation::ADSP) { return; } @@ -1302,14 +1208,12 @@ public: /* TODO: We should act smart and reuse current configurations */ sw_enc_.clear(); while (sw_enc_.size() != subgroup_config.GetNumChannelsTotal()) { - auto codec = - bluetooth::le_audio::CodecInterface::CreateInstance(codec_id); + auto codec = bluetooth::le_audio::CodecInterface::CreateInstance(codec_id); auto codec_status = codec->InitEncoder(codec_config, codec_config); - if (codec_status != - bluetooth::le_audio::CodecInterface::Status::STATUS_OK) { - log::error("Channel {} codec setup failed with err: {}", - (uint32_t)sw_enc_.size(), codec_status); + if (codec_status != bluetooth::le_audio::CodecInterface::Status::STATUS_OK) { + log::error("Channel {} codec setup failed with err: {}", (uint32_t)sw_enc_.size(), + codec_status); return; } @@ -1320,15 +1224,12 @@ public: } static void sendBroadcastData( - const std::unique_ptr& broadcast, - std::vector>& - encoders) { + const std::unique_ptr& broadcast, + std::vector>& encoders) { auto const& config = broadcast->GetBigConfig(); if (config == std::nullopt) { - log::error( - "Broadcast broadcast_id={} has no valid BIS configurations in " - "state={}", - broadcast->GetBroadcastId(), ToString(broadcast->GetState())); + log::error("Broadcast broadcast_id={} has no valid BIS configurations in state={}", + broadcast->GetBroadcastId(), ToString(broadcast->GetState())); return; } @@ -1339,19 +1240,20 @@ public: for (uint8_t chan = 0; chan < encoders.size(); ++chan) { IsoManager::GetInstance()->SendIsoData( - config->connection_handles[chan], - (const uint8_t*)encoders[chan]->GetDecodedSamples().data(), - encoders[chan]->GetDecodedSamples().size() * 2); + config->connection_handles[chan], + (const uint8_t*)encoders[chan]->GetDecodedSamples().data(), + encoders[chan]->GetDecodedSamples().size() * 2); } } virtual void OnAudioDataReady(const std::vector& data) override { - if (!instance) return; + if (!instance) { + return; + } log::verbose("Received {} bytes.", data.size()); - if (!broadcast_config_.has_value() || - (broadcast_config_->subgroups.size() == 0)) { + if (!broadcast_config_.has_value() || (broadcast_config_->subgroups.size() == 0)) { log::error("Codec was not configured properly"); return; } @@ -1369,9 +1271,8 @@ public: /* Prepare encoded data for all channels */ for (uint8_t bis_idx = 0; bis_idx < num_bis; ++bis_idx) { auto initial_channel_offset = bis_idx * bytes_per_sample; - sw_enc_[bis_idx]->Encode( - data.data() + initial_channel_offset, num_bis, - subgroup_config.GetBisOctetsPerCodecFrame(bis_idx)); + sw_enc_[bis_idx]->Encode(data.data() + initial_channel_offset, num_bis, + subgroup_config.GetBisOctetsPerCodecFrame(bis_idx)); } /* Currently there is no way to broadcast multiple distinct streams. @@ -1380,10 +1281,10 @@ public: */ for (auto& broadcast_pair : instance->broadcasts_) { auto& broadcast = broadcast_pair.second; - if ((broadcast->GetState() == - BroadcastStateMachine::State::STREAMING) && - !broadcast->IsMuted()) + if ((broadcast->GetState() == BroadcastStateMachine::State::STREAMING) && + !broadcast->IsMuted()) { sendBroadcastData(broadcast, sw_enc_); + } } log::verbose("All data sent."); } @@ -1403,7 +1304,9 @@ public: virtual void OnAudioResume(void) override { log::info(""); - if (!instance) return; + if (!instance) { + return; + } instance->audio_state_ = AudioState::ACTIVE; if (com::android::bluetooth::flags::leaudio_big_depends_on_audio_state()) { @@ -1427,10 +1330,12 @@ public: } virtual void OnAudioMetadataUpdate( - const std::vector source_metadata, - DsaMode dsa_mode) override { + const std::vector source_metadata, + DsaMode dsa_mode) override { log::info(""); - if (!instance) return; + if (!instance) { + return; + } /* TODO: Should we take supported contexts from ASCS? */ auto contexts = GetAudioContextsFromSourceMetadata(source_metadata); @@ -1445,7 +1350,7 @@ public: } } - private: + private: std::optional broadcast_config_; std::vector> sw_enc_; } audio_receiver_; @@ -1475,16 +1380,14 @@ public: /* Static members definitions */ LeAudioBroadcasterImpl::BroadcastStateMachineCallbacks - LeAudioBroadcasterImpl::state_machine_callbacks_; -LeAudioBroadcasterImpl::LeAudioSourceCallbacksImpl - LeAudioBroadcasterImpl::audio_receiver_; + LeAudioBroadcasterImpl::state_machine_callbacks_; +LeAudioBroadcasterImpl::LeAudioSourceCallbacksImpl LeAudioBroadcasterImpl::audio_receiver_; LeAudioBroadcasterImpl::BroadcastAdvertisingCallbacks - LeAudioBroadcasterImpl::state_machine_adv_callbacks_; + LeAudioBroadcasterImpl::state_machine_adv_callbacks_; } /* namespace */ -void LeAudioBroadcaster::Initialize( - bluetooth::le_audio::LeAudioBroadcasterCallbacks* callbacks, - base::Callback audio_hal_verifier) { +void LeAudioBroadcaster::Initialize(bluetooth::le_audio::LeAudioBroadcasterCallbacks* callbacks, + base::Callback audio_hal_verifier) { std::scoped_lock lock(instance_mutex); log::info(""); if (instance) { @@ -1508,10 +1411,11 @@ void LeAudioBroadcaster::Initialize( /* Register HCI event handlers */ IsoManager::GetInstance()->RegisterBigCallbacks(instance); /* Register for active traffic */ - IsoManager::GetInstance()->RegisterOnIsoTrafficActiveCallback( - [](bool is_active) { - if (instance) instance->IsoTrafficEventCb(is_active); - }); + IsoManager::GetInstance()->RegisterOnIsoTrafficActiveCallback([](bool is_active) { + if (instance) { + instance->IsoTrafficEventCb(is_active); + } + }); } bool LeAudioBroadcaster::IsLeAudioBroadcasterRunning() { return instance; } @@ -1534,7 +1438,9 @@ void LeAudioBroadcaster::Cleanup(void) { std::scoped_lock lock(instance_mutex); log::info(""); - if (instance == nullptr) return; + if (instance == nullptr) { + return; + } LeAudioBroadcasterImpl* ptr = instance; instance = nullptr; @@ -1546,6 +1452,8 @@ void LeAudioBroadcaster::Cleanup(void) { void LeAudioBroadcaster::DebugDump(int fd) { std::scoped_lock lock(instance_mutex); dprintf(fd, "Le Audio Broadcaster:\n"); - if (instance) instance->Dump(fd); + if (instance) { + instance->Dump(fd); + } dprintf(fd, "\n"); } diff --git a/system/bta/le_audio/broadcaster/broadcaster_test.cc b/system/bta/le_audio/broadcaster/broadcaster_test.cc index 7c907c96ba5..6e86a504e4d 100644 --- a/system/bta/le_audio/broadcaster/broadcaster_test.cc +++ b/system/bta/le_audio/broadcaster/broadcaster_test.cc @@ -68,9 +68,7 @@ using bluetooth::le_audio::broadcaster::BigConfig; using bluetooth::le_audio::broadcaster::BroadcastSubgroupCodecConfig; // Disables most likely false-positives from base::SplitString() -extern "C" const char* __asan_default_options() { - return "detect_container_overflow=0"; -} +extern "C" const char* __asan_default_options() { return "detect_container_overflow=0"; } struct alarm_t { alarm_callback_t cb; @@ -84,37 +82,31 @@ struct alarm_t { static base::Callback generator_cb; -void btsnd_hcic_ble_rand(base::Callback cb) { - generator_cb = cb; -} +void btsnd_hcic_ble_rand(base::Callback cb) { generator_cb = cb; } namespace server_configurable_flags { -std::string GetServerConfigurableFlag( - const std::string& experiment_category_name, - const std::string& experiment_flag_name, const std::string& default_value) { +std::string GetServerConfigurableFlag(const std::string& experiment_category_name, + const std::string& experiment_flag_name, + const std::string& default_value) { return ""; } } // namespace server_configurable_flags std::atomic num_async_tasks; bluetooth::common::MessageLoopThread message_loop_thread("test message loop"); -bluetooth::common::MessageLoopThread* get_main_thread() { - return &message_loop_thread; -} +bluetooth::common::MessageLoopThread* get_main_thread() { return &message_loop_thread; } void invoke_switch_buffer_size_cb(bool is_low_latency_buffer_size) {} -bt_status_t do_in_main_thread(const base::Location& from_here, - base::OnceClosure task) { +bt_status_t do_in_main_thread(const base::Location& from_here, base::OnceClosure task) { // Wrap the task with task counter so we could later know if there are // any callbacks scheduled and we should wait before performing some actions if (!message_loop_thread.DoInThread( - from_here, - base::BindOnce( - [](base::OnceClosure task, std::atomic& num_async_tasks) { - std::move(task).Run(); - num_async_tasks--; - }, - std::move(task), std::ref(num_async_tasks)))) { + from_here, base::BindOnce( + [](base::OnceClosure task, std::atomic& num_async_tasks) { + std::move(task).Run(); + num_async_tasks--; + }, + std::move(task), std::ref(num_async_tasks)))) { log::error("failed from {}", from_here.ToString()); return BT_STATUS_FAIL; } @@ -132,11 +124,14 @@ static void init_message_loop_thread() { FAIL() << "unable to create message loop thread."; } - if (!message_loop_thread.EnableRealTimeScheduling()) + if (!message_loop_thread.EnableRealTimeScheduling()) { log::error("Unable to set real time scheduling"); + } message_loop_ = message_loop_thread.message_loop(); - if (message_loop_ == nullptr) FAIL() << "unable to get message loop."; + if (message_loop_ == nullptr) { + FAIL() << "unable to get message loop."; + } } static void cleanup_message_loop_thread() { @@ -149,24 +144,23 @@ bool LeAudioClient::IsLeAudioClientRunning(void) { return false; } namespace bluetooth::le_audio { namespace broadcaster { BroadcastConfiguration GetBroadcastConfig( - const std::vector>& - subgroup_quality) { + const std::vector>& subgroup_quality) { BroadcastConfiguration config = { - .subgroups = {}, - .qos = qos_config_4_60, // default QoS value for reliability - .data_path = lc3_data_path, - .sduIntervalUs = 10000, - .phy = 0x02, // PHY_LE_2M - .packing = 0, // Sequential - .framing = 0, // Unframed + .subgroups = {}, + .qos = qos_config_4_60, // default QoS value for reliability + .data_path = lc3_data_path, + .sduIntervalUs = 10000, + .phy = 0x02, // PHY_LE_2M + .packing = 0, // Sequential + .framing = 0, // Unframed }; for (auto [context, quality] : subgroup_quality) { // Select QoS - Check for low latency contexts - if (AudioContexts(context).test_any( - types::LeAudioContextType::GAME | types::LeAudioContextType::LIVE | - types::LeAudioContextType::INSTRUCTIONAL | - types::LeAudioContextType::SOUNDEFFECTS)) { + if (AudioContexts(context).test_any(types::LeAudioContextType::GAME | + types::LeAudioContextType::LIVE | + types::LeAudioContextType::INSTRUCTIONAL | + types::LeAudioContextType::SOUNDEFFECTS)) { config.qos = qos_config_2_10; } @@ -188,11 +182,10 @@ MockAudioHalClientEndpoint* mock_audio_source_; bool is_audio_hal_acquired; void (*iso_active_callback)(bool); -std::unique_ptr -LeAudioSourceAudioHalClient::AcquireBroadcast() { +std::unique_ptr LeAudioSourceAudioHalClient::AcquireBroadcast() { if (mock_audio_source_) { std::unique_ptr ptr( - (LeAudioSourceAudioHalClient*)mock_audio_source_); + (LeAudioSourceAudioHalClient*)mock_audio_source_); is_audio_hal_acquired = true; return std::move(ptr); } @@ -201,21 +194,16 @@ LeAudioSourceAudioHalClient::AcquireBroadcast() { static constexpr uint8_t default_ccid = 0xDE; static constexpr auto default_context = - static_cast::type>( - LeAudioContextType::ALERTS); -std::vector default_subgroup_qualities = { - bluetooth::le_audio::QUALITY_STANDARD}; -static constexpr BroadcastCode default_code = { - 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, - 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10}; + static_cast::type>(LeAudioContextType::ALERTS); +std::vector default_subgroup_qualities = {bluetooth::le_audio::QUALITY_STANDARD}; +static constexpr BroadcastCode default_code = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, + 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10}; static const std::vector default_metadata = { - bluetooth::le_audio::types::kLeAudioMetadataStreamingAudioContextLen + 1, - bluetooth::le_audio::types::kLeAudioMetadataTypeStreamingAudioContext, - default_context & 0x00FF, (default_context & 0xFF00) >> 8}; + bluetooth::le_audio::types::kLeAudioMetadataStreamingAudioContextLen + 1, + bluetooth::le_audio::types::kLeAudioMetadataTypeStreamingAudioContext, + default_context & 0x00FF, (default_context & 0xFF00) >> 8}; static const std::vector default_public_metadata = { - 5, bluetooth::le_audio::types::kLeAudioMetadataTypeProgramInfo, - 0x1, 0x2, - 0x3, 0x4}; + 5, bluetooth::le_audio::types::kLeAudioMetadataTypeProgramInfo, 0x1, 0x2, 0x3, 0x4}; static const std::vector audio_active_state_false = { 2, bluetooth::le_audio::types::kLeAudioMetadataTypeAudioActiveState, 0x00}; static const std::vector audio_active_state_true = { @@ -225,36 +213,28 @@ static const uint8_t test_public_broadcast_features = 0x3; static constexpr uint8_t media_ccid = 0xC0; static constexpr auto media_context = - static_cast::type>( - LeAudioContextType::MEDIA); + static_cast::type>(LeAudioContextType::MEDIA); static const std::vector media_metadata = { - bluetooth::le_audio::types::kLeAudioMetadataStreamingAudioContextLen + 1, - bluetooth::le_audio::types::kLeAudioMetadataTypeStreamingAudioContext, - media_context & 0x00FF, (media_context & 0xFF00) >> 8}; + bluetooth::le_audio::types::kLeAudioMetadataStreamingAudioContextLen + 1, + bluetooth::le_audio::types::kLeAudioMetadataTypeStreamingAudioContext, + media_context & 0x00FF, (media_context & 0xFF00) >> 8}; static const std::string test_broadcast_name = "Test"; static const std::string big_terminate_timer_name = "BigTerminateTimer"; static const std::string broadcast_stop_timer_name = "BroadcastStopTimer"; -class MockLeAudioBroadcasterCallbacks - : public bluetooth::le_audio::LeAudioBroadcasterCallbacks { - public: - MOCK_METHOD((void), OnBroadcastCreated, (uint32_t broadcast_id, bool success), - (override)); - MOCK_METHOD((void), OnBroadcastDestroyed, (uint32_t broadcast_id), - (override)); +class MockLeAudioBroadcasterCallbacks : public bluetooth::le_audio::LeAudioBroadcasterCallbacks { +public: + MOCK_METHOD((void), OnBroadcastCreated, (uint32_t broadcast_id, bool success), (override)); + MOCK_METHOD((void), OnBroadcastDestroyed, (uint32_t broadcast_id), (override)); MOCK_METHOD((void), OnBroadcastStateChanged, - (uint32_t broadcast_id, - bluetooth::le_audio::BroadcastState state), - (override)); + (uint32_t broadcast_id, bluetooth::le_audio::BroadcastState state), (override)); MOCK_METHOD((void), OnBroadcastMetadataChanged, - (uint32_t broadcast_id, - const BroadcastMetadata& broadcast_metadata), - (override)); + (uint32_t broadcast_id, const BroadcastMetadata& broadcast_metadata), (override)); }; class MockAudioHalClientEndpoint : public LeAudioSourceAudioHalClient { - public: +public: MockAudioHalClientEndpoint() = default; MOCK_METHOD((bool), Start, (const LeAudioCodecConfiguration& codecConfiguration, @@ -265,22 +245,18 @@ class MockAudioHalClientEndpoint : public LeAudioSourceAudioHalClient { MOCK_METHOD((void), ConfirmStreamingRequest, (), (override)); MOCK_METHOD((void), CancelStreamingRequest, (), (override)); MOCK_METHOD((void), UpdateRemoteDelay, (uint16_t delay), (override)); - MOCK_METHOD((void), UpdateAudioConfigToHal, - (const ::bluetooth::le_audio::offload_config&), (override)); - MOCK_METHOD( - (std::optional), GetBroadcastConfig, - ((const std::vector>&), - (const std::optional< - std::vector<::bluetooth::le_audio::types::acs_ac_record>>&)), - (const override)); - MOCK_METHOD( - (std::optional<::le_audio::set_configurations::AudioSetConfiguration>), - GetUnicastConfig, - (const CodecManager::UnicastConfigurationRequirements& requirements), - (const override)); - MOCK_METHOD((void), UpdateBroadcastAudioConfigToHal, - (const ::bluetooth::le_audio::broadcast_offload_config&), + MOCK_METHOD((void), UpdateAudioConfigToHal, (const ::bluetooth::le_audio::offload_config&), (override)); + MOCK_METHOD((std::optional), GetBroadcastConfig, + ((const std::vector>&), + (const std::optional>&)), + (const override)); + MOCK_METHOD((std::optional<::le_audio::set_configurations::AudioSetConfiguration>), + GetUnicastConfig, + (const CodecManager::UnicastConfigurationRequirements& requirements), + (const override)); + MOCK_METHOD((void), UpdateBroadcastAudioConfigToHal, + (const ::bluetooth::le_audio::broadcast_offload_config&), (override)); MOCK_METHOD((void), SuspendedForReconfiguration, (), (override)); MOCK_METHOD((void), ReconfigurationComplete, (), (override)); @@ -289,7 +265,7 @@ class MockAudioHalClientEndpoint : public LeAudioSourceAudioHalClient { }; class BroadcasterTest : public Test { - protected: +protected: void SetUp() override { test::mock::osi_alarm::alarm_free.body = [](alarm_t* alarm) { if (alarm) { @@ -326,30 +302,26 @@ class BroadcasterTest : public Test { reset_mock_function_count_map(); bluetooth::hci::testing::mock_controller_ = &mock_controller_; - ON_CALL(mock_controller_, SupportsBleIsochronousBroadcaster) - .WillByDefault(Return(true)); + ON_CALL(mock_controller_, SupportsBleIsochronousBroadcaster).WillByDefault(Return(true)); iso_manager_ = bluetooth::hci::IsoManager::GetInstance(); ASSERT_NE(iso_manager_, nullptr); iso_manager_->Start(); mock_iso_manager_ = MockIsoManager::GetInstance(); - ON_CALL(*mock_iso_manager_, RegisterBigCallbacks(_)) - .WillByDefault(SaveArg<0>(&big_callbacks_)); + ON_CALL(*mock_iso_manager_, RegisterBigCallbacks(_)).WillByDefault(SaveArg<0>(&big_callbacks_)); ConfigAudioHalClientMock(); - EXPECT_CALL(*MockIsoManager::GetInstance(), - RegisterOnIsoTrafficActiveCallbacks) - .WillOnce(SaveArg<0>(&iso_active_callback)); + EXPECT_CALL(*MockIsoManager::GetInstance(), RegisterOnIsoTrafficActiveCallbacks) + .WillOnce(SaveArg<0>(&iso_active_callback)); ASSERT_FALSE(LeAudioBroadcaster::IsLeAudioBroadcasterRunning()); LeAudioBroadcaster::Initialize(&mock_broadcaster_callbacks_, base::Bind([]() -> bool { return true; })); ContentControlIdKeeper::GetInstance()->Start(); - ContentControlIdKeeper::GetInstance()->SetCcid(LeAudioContextType::MEDIA, - media_ccid); + ContentControlIdKeeper::GetInstance()->SetCcid(LeAudioContextType::MEDIA, media_ccid); /* Simulate random generator */ uint8_t random[] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}; @@ -358,17 +330,17 @@ class BroadcasterTest : public Test { ConfigCodecManagerMock(types::CodecLocation::HOST); ON_CALL(*mock_codec_manager_, UpdateActiveUnicastAudioHalClient(_, _, _)) - .WillByDefault(Return(true)); + .WillByDefault(Return(true)); ON_CALL(*mock_codec_manager_, UpdateActiveBroadcastAudioHalClient(_, _)) - .WillByDefault(Return(true)); + .WillByDefault(Return(true)); ON_CALL(*mock_codec_manager_, GetBroadcastConfig) - .WillByDefault( - Invoke([](const bluetooth::le_audio::CodecManager:: - BroadcastConfigurationRequirements& requirements) { - return std::make_unique( - bluetooth::le_audio::broadcaster::GetBroadcastConfig( - requirements.subgroup_quality)); - })); + .WillByDefault(Invoke( + [](const bluetooth::le_audio::CodecManager::BroadcastConfigurationRequirements& + requirements) { + return std::make_unique( + bluetooth::le_audio::broadcaster::GetBroadcastConfig( + requirements.subgroup_quality)); + })); } void ConfigAudioHalClientMock() { @@ -384,13 +356,11 @@ class BroadcasterTest : public Test { void ConfigCodecManagerMock(types::CodecLocation location) { codec_manager_ = le_audio::CodecManager::GetInstance(); ASSERT_NE(codec_manager_, nullptr); - std::vector - mock_offloading_preference(0); + std::vector mock_offloading_preference(0); codec_manager_->Start(mock_offloading_preference); mock_codec_manager_ = MockCodecManager::GetInstance(); ASSERT_NE(mock_codec_manager_, nullptr); - ON_CALL(*mock_codec_manager_, GetCodecLocation()) - .WillByDefault(Return(location)); + ON_CALL(*mock_codec_manager_, GetCodecLocation()).WillByDefault(Return(location)); } void TearDown() override { @@ -402,8 +372,7 @@ class BroadcasterTest : public Test { Mock::VerifyAndClearExpectations(&mock_broadcaster_callbacks_); Mock::VerifyAndClearExpectations(MockIsoManager::GetInstance()); - Mock::VerifyAndClearExpectations( - MockBroadcastStateMachine::GetLastInstance()); + Mock::VerifyAndClearExpectations(MockBroadcastStateMachine::GetLastInstance()); LeAudioBroadcaster::Stop(); LeAudioBroadcaster::Cleanup(); @@ -429,15 +398,14 @@ class BroadcasterTest : public Test { broadcast_stop_timer_ = nullptr; } - uint32_t InstantiateBroadcast( - std::vector metadata = default_metadata, - BroadcastCode code = default_code, - std::vector quality_array = default_subgroup_qualities, - bool is_queued = false) { + uint32_t InstantiateBroadcast(std::vector metadata = default_metadata, + BroadcastCode code = default_code, + std::vector quality_array = default_subgroup_qualities, + bool is_queued = false) { uint32_t broadcast_id = LeAudioBroadcaster::kInstanceIdUndefined; if (!is_queued) { EXPECT_CALL(mock_broadcaster_callbacks_, OnBroadcastCreated(_, true)) - .WillOnce(SaveArg<0>(&broadcast_id)); + .WillOnce(SaveArg<0>(&broadcast_id)); } std::vector> metadata_array; @@ -447,9 +415,9 @@ class BroadcasterTest : public Test { } // Add multiple subgroup settings with the same content - LeAudioBroadcaster::Get()->CreateAudioBroadcast( - true, test_broadcast_name, code, default_public_metadata, quality_array, - metadata_array); + LeAudioBroadcaster::Get()->CreateAudioBroadcast(true, test_broadcast_name, code, + default_public_metadata, quality_array, + metadata_array); return broadcast_id; } @@ -458,32 +426,29 @@ class BroadcasterTest : public Test { std::vector conn_handles = {0x10, 0x12}; hci::iso_manager::big_create_cmpl_evt evt = { - .status = status, - .big_id = big_id, - .big_sync_delay = 1231, - .transport_latency_big = 1234, - .phy = 2, - .nse = 3, - .bn = 2, - .pto = 2, - .irc = 2, - .max_pdu = 128, - .iso_interval = 10, - .conn_handles = conn_handles, + .status = status, + .big_id = big_id, + .big_sync_delay = 1231, + .transport_latency_big = 1234, + .phy = 2, + .nse = 3, + .bn = 2, + .pto = 2, + .irc = 2, + .max_pdu = 128, + .iso_interval = 10, + .conn_handles = conn_handles, }; - big_callbacks_->OnBigEvent( - bluetooth::hci::iso_manager::kIsoEventBigOnCreateCmpl, &evt); + big_callbacks_->OnBigEvent(bluetooth::hci::iso_manager::kIsoEventBigOnCreateCmpl, &evt); } void InjectBigTerminateComplete(uint8_t big_id, uint8_t reason) { - hci::iso_manager::big_terminate_cmpl_evt evt = {.big_id = big_id, - .reason = reason}; - big_callbacks_->OnBigEvent( - bluetooth::hci::iso_manager::kIsoEventBigOnTerminateCmpl, &evt); + hci::iso_manager::big_terminate_cmpl_evt evt = {.big_id = big_id, .reason = reason}; + big_callbacks_->OnBigEvent(bluetooth::hci::iso_manager::kIsoEventBigOnTerminateCmpl, &evt); } - protected: +protected: MockLeAudioBroadcasterCallbacks mock_broadcaster_callbacks_; bluetooth::hci::testing::MockControllerInterface mock_controller_; bluetooth::hci::IsoManager* iso_manager_; @@ -505,9 +470,8 @@ TEST_F(BroadcasterTest, Initialize) { TEST_F(BroadcasterTest, CleanupWithBroadcastInstance) { auto broadcast_id = InstantiateBroadcast(); ASSERT_NE(broadcast_id, LeAudioBroadcaster::kInstanceIdUndefined); - EXPECT_CALL(*mock_codec_manager_, - UpdateActiveBroadcastAudioHalClient(mock_audio_source_, false)) - .WillOnce(Return(false)); + EXPECT_CALL(*mock_codec_manager_, UpdateActiveBroadcastAudioHalClient(mock_audio_source_, false)) + .WillOnce(Return(false)); } TEST_F(BroadcasterTest, GetStreamingPhy) { @@ -520,79 +484,69 @@ TEST_F(BroadcasterTest, GetStreamingPhy) { TEST_F(BroadcasterTest, CreateAudioBroadcast) { auto broadcast_id = InstantiateBroadcast(); ASSERT_NE(broadcast_id, LeAudioBroadcaster::kInstanceIdUndefined); - ASSERT_EQ(broadcast_id, - MockBroadcastStateMachine::GetLastInstance()->GetBroadcastId()); + ASSERT_EQ(broadcast_id, MockBroadcastStateMachine::GetLastInstance()->GetBroadcastId()); auto& instance_config = MockBroadcastStateMachine::GetLastInstance()->cfg; ASSERT_EQ(instance_config.broadcast_code, default_code); for (auto& subgroup : instance_config.announcement.subgroup_configs) { - ASSERT_EQ(types::LeAudioLtvMap(subgroup.metadata).RawPacket(), - default_metadata); + ASSERT_EQ(types::LeAudioLtvMap(subgroup.metadata).RawPacket(), default_metadata); } // Note: There shall be a separate test to verify audio parameters } TEST_F(BroadcasterTest, CreateAudioBroadcastMultiGroups) { // Test with two subgroups - auto broadcast_id = - InstantiateBroadcast(default_metadata, default_code, - {bluetooth::le_audio::QUALITY_STANDARD, - bluetooth::le_audio::QUALITY_STANDARD}); + auto broadcast_id = InstantiateBroadcast( + default_metadata, default_code, + {bluetooth::le_audio::QUALITY_STANDARD, bluetooth::le_audio::QUALITY_STANDARD}); ASSERT_NE(broadcast_id, LeAudioBroadcaster::kInstanceIdUndefined); - ASSERT_EQ(broadcast_id, - MockBroadcastStateMachine::GetLastInstance()->GetBroadcastId()); + ASSERT_EQ(broadcast_id, MockBroadcastStateMachine::GetLastInstance()->GetBroadcastId()); auto& instance_config = MockBroadcastStateMachine::GetLastInstance()->cfg; ASSERT_EQ(instance_config.broadcast_code, default_code); - ASSERT_EQ(instance_config.announcement.subgroup_configs.size(), (uint8_t) 2); + ASSERT_EQ(instance_config.announcement.subgroup_configs.size(), (uint8_t)2); for (auto& subgroup : instance_config.announcement.subgroup_configs) { - ASSERT_EQ(types::LeAudioLtvMap(subgroup.metadata).RawPacket(), - default_metadata); + ASSERT_EQ(types::LeAudioLtvMap(subgroup.metadata).RawPacket(), default_metadata); } } TEST_F(BroadcasterTest, SuspendAudioBroadcast) { - EXPECT_CALL(*mock_codec_manager_, - UpdateActiveBroadcastAudioHalClient(mock_audio_source_, true)) - .Times(1); + EXPECT_CALL(*mock_codec_manager_, UpdateActiveBroadcastAudioHalClient(mock_audio_source_, true)) + .Times(1); auto broadcast_id = InstantiateBroadcast(); LeAudioBroadcaster::Get()->StartAudioBroadcast(broadcast_id); Mock::VerifyAndClearExpectations(mock_codec_manager_); EXPECT_CALL(mock_broadcaster_callbacks_, OnBroadcastStateChanged(broadcast_id, BroadcastState::CONFIGURED)) - .Times(1); + .Times(1); EXPECT_CALL(*mock_audio_source_, Stop).Times(AtLeast(1)); - EXPECT_CALL(*mock_codec_manager_, - UpdateActiveBroadcastAudioHalClient(mock_audio_source_, _)) - .Times(0); + EXPECT_CALL(*mock_codec_manager_, UpdateActiveBroadcastAudioHalClient(mock_audio_source_, _)) + .Times(0); LeAudioBroadcaster::Get()->SuspendAudioBroadcast(broadcast_id); Mock::VerifyAndClearExpectations(mock_codec_manager_); } TEST_F(BroadcasterTest, StartAudioBroadcast) { - EXPECT_CALL(*mock_codec_manager_, - UpdateActiveBroadcastAudioHalClient(mock_audio_source_, true)) - .Times(1); + EXPECT_CALL(*mock_codec_manager_, UpdateActiveBroadcastAudioHalClient(mock_audio_source_, true)) + .Times(1); auto broadcast_id = InstantiateBroadcast(); Mock::VerifyAndClearExpectations(mock_codec_manager_); - EXPECT_CALL(*mock_codec_manager_, - UpdateActiveBroadcastAudioHalClient(mock_audio_source_, true)) - .Times(0); - EXPECT_CALL(*mock_codec_manager_, - UpdateActiveBroadcastAudioHalClient(mock_audio_source_, false)) - .Times(0); + EXPECT_CALL(*mock_codec_manager_, UpdateActiveBroadcastAudioHalClient(mock_audio_source_, true)) + .Times(0); + EXPECT_CALL(*mock_codec_manager_, UpdateActiveBroadcastAudioHalClient(mock_audio_source_, false)) + .Times(0); LeAudioBroadcaster::Get()->StopAudioBroadcast(broadcast_id); EXPECT_CALL(mock_broadcaster_callbacks_, OnBroadcastStateChanged(broadcast_id, BroadcastState::STREAMING)) - .Times(1); + .Times(1); LeAudioSourceAudioHalClient::Callbacks* audio_receiver; EXPECT_CALL(*mock_audio_source_, Start) - .WillOnce(DoAll(SaveArg<1>(&audio_receiver), Return(true))); + .WillOnce(DoAll(SaveArg<1>(&audio_receiver), Return(true))); LeAudioBroadcaster::Get()->StartAudioBroadcast(broadcast_id); ASSERT_NE(audio_receiver, nullptr); @@ -602,8 +556,7 @@ TEST_F(BroadcasterTest, StartAudioBroadcast) { // IsoManager to prepare one (and that's good since IsoManager is also // a mocked one). BigConfig big_cfg; - big_cfg.big_id = - MockBroadcastStateMachine::GetLastInstance()->GetAdvertisingSid(); + big_cfg.big_id = MockBroadcastStateMachine::GetLastInstance()->GetAdvertisingSid(); big_cfg.connection_handles = {0x10, 0x12}; big_cfg.max_pdu = 128; MockBroadcastStateMachine::GetLastInstance()->SetExpectedBigConfig(big_cfg); @@ -617,28 +570,25 @@ TEST_F(BroadcasterTest, StartAudioBroadcast) { } TEST_F(BroadcasterTest, StartAudioBroadcastMedia) { - EXPECT_CALL(*mock_codec_manager_, - UpdateActiveBroadcastAudioHalClient(mock_audio_source_, true)) - .Times(1); - auto broadcast_id = InstantiateBroadcast(media_metadata, default_code, - {bluetooth::le_audio::QUALITY_HIGH}); + EXPECT_CALL(*mock_codec_manager_, UpdateActiveBroadcastAudioHalClient(mock_audio_source_, true)) + .Times(1); + auto broadcast_id = + InstantiateBroadcast(media_metadata, default_code, {bluetooth::le_audio::QUALITY_HIGH}); Mock::VerifyAndClearExpectations(mock_codec_manager_); LeAudioBroadcaster::Get()->StopAudioBroadcast(broadcast_id); EXPECT_CALL(mock_broadcaster_callbacks_, OnBroadcastStateChanged(broadcast_id, BroadcastState::STREAMING)) - .Times(1); + .Times(1); LeAudioSourceAudioHalClient::Callbacks* audio_receiver; EXPECT_CALL(*mock_audio_source_, Start) - .WillOnce(DoAll(SaveArg<1>(&audio_receiver), Return(true))); - EXPECT_CALL(*mock_codec_manager_, - UpdateActiveBroadcastAudioHalClient(mock_audio_source_, true)) - .Times(0); - EXPECT_CALL(*mock_codec_manager_, - UpdateActiveBroadcastAudioHalClient(mock_audio_source_, false)) - .Times(0); + .WillOnce(DoAll(SaveArg<1>(&audio_receiver), Return(true))); + EXPECT_CALL(*mock_codec_manager_, UpdateActiveBroadcastAudioHalClient(mock_audio_source_, true)) + .Times(0); + EXPECT_CALL(*mock_codec_manager_, UpdateActiveBroadcastAudioHalClient(mock_audio_source_, false)) + .Times(0); LeAudioBroadcaster::Get()->StartAudioBroadcast(broadcast_id); ASSERT_NE(audio_receiver, nullptr); @@ -683,7 +633,7 @@ TEST_F(BroadcasterTest, StopAudioBroadcast) { InjectBigCreateComplete(big_cfg.big_id, 0x00); EXPECT_CALL(mock_broadcaster_callbacks_, OnBroadcastStateChanged(broadcast_id, BroadcastState::STOPPED)) - .Times(1); + .Times(1); EXPECT_CALL(*mock_audio_source_, Stop).Times(AtLeast(1)); LeAudioBroadcaster::Get()->StopAudioBroadcast(broadcast_id); @@ -698,19 +648,16 @@ TEST_F(BroadcasterTest, StopAudioBroadcast) { } TEST_F(BroadcasterTest, DestroyAudioBroadcast) { - EXPECT_CALL(*mock_codec_manager_, - UpdateActiveBroadcastAudioHalClient(mock_audio_source_, true)) - .Times(1); + EXPECT_CALL(*mock_codec_manager_, UpdateActiveBroadcastAudioHalClient(mock_audio_source_, true)) + .Times(1); auto broadcast_id = InstantiateBroadcast(); Mock::VerifyAndClearExpectations(mock_codec_manager_); - EXPECT_CALL(*mock_codec_manager_, - UpdateActiveBroadcastAudioHalClient(mock_audio_source_, false)) - .Times(1); - EXPECT_CALL(mock_broadcaster_callbacks_, OnBroadcastDestroyed(broadcast_id)) - .Times(1); + EXPECT_CALL(*mock_codec_manager_, UpdateActiveBroadcastAudioHalClient(mock_audio_source_, false)) + .Times(1); + EXPECT_CALL(mock_broadcaster_callbacks_, OnBroadcastDestroyed(broadcast_id)).Times(1); LeAudioBroadcaster::Get()->DestroyAudioBroadcast(broadcast_id); Mock::VerifyAndClearExpectations(mock_codec_manager_); @@ -719,14 +666,11 @@ TEST_F(BroadcasterTest, DestroyAudioBroadcast) { /* Create a mock again for the test purpose */ ConfigAudioHalClientMock(); - EXPECT_CALL(*mock_codec_manager_, - UpdateActiveBroadcastAudioHalClient(mock_audio_source_, _)) - .Times(0); + EXPECT_CALL(*mock_codec_manager_, UpdateActiveBroadcastAudioHalClient(mock_audio_source_, _)) + .Times(0); // Expect not being able to interact with this Broadcast - EXPECT_CALL(mock_broadcaster_callbacks_, - OnBroadcastStateChanged(broadcast_id, _)) - .Times(0); + EXPECT_CALL(mock_broadcaster_callbacks_, OnBroadcastStateChanged(broadcast_id, _)).Times(0); EXPECT_CALL(*mock_audio_source_, Stop).Times(0); LeAudioBroadcaster::Get()->StopAudioBroadcast(broadcast_id); @@ -754,12 +698,8 @@ TEST_F(BroadcasterTest, GetBroadcastAllStates) { * on itself, therefore here when we use mocked state machine this is not * being verified. */ - EXPECT_CALL(mock_broadcaster_callbacks_, - OnBroadcastStateChanged(broadcast_id, _)) - .Times(1); - EXPECT_CALL(mock_broadcaster_callbacks_, - OnBroadcastStateChanged(broadcast_id2, _)) - .Times(1); + EXPECT_CALL(mock_broadcaster_callbacks_, OnBroadcastStateChanged(broadcast_id, _)).Times(1); + EXPECT_CALL(mock_broadcaster_callbacks_, OnBroadcastStateChanged(broadcast_id2, _)).Times(1); LeAudioBroadcaster::Get()->GetAllBroadcastStates(); } @@ -770,36 +710,28 @@ TEST_F(BroadcasterTest, UpdateMetadata) { std::vector expected_public_meta; std::string expected_broadcast_name; - EXPECT_CALL(*MockBroadcastStateMachine::GetLastInstance(), - UpdateBroadcastAnnouncement) - .WillOnce( - [&](bluetooth::le_audio::BasicAudioAnnouncementData announcement) { + EXPECT_CALL(*MockBroadcastStateMachine::GetLastInstance(), UpdateBroadcastAnnouncement) + .WillOnce([&](bluetooth::le_audio::BasicAudioAnnouncementData announcement) { for (auto subgroup : announcement.subgroup_configs) { - if (subgroup.metadata.count( - types::kLeAudioMetadataTypeCcidList)) { - ccid_list = - subgroup.metadata.at(types::kLeAudioMetadataTypeCcidList); + if (subgroup.metadata.count(types::kLeAudioMetadataTypeCcidList)) { + ccid_list = subgroup.metadata.at(types::kLeAudioMetadataTypeCcidList); break; } } }); - EXPECT_CALL(*MockBroadcastStateMachine::GetLastInstance(), - UpdatePublicBroadcastAnnouncement) - .WillOnce([&](uint32_t broadcast_id, const std::string& broadcast_name, - const bluetooth::le_audio::PublicBroadcastAnnouncementData& - announcement) { - expected_broadcast_name = broadcast_name; - expected_public_meta = - types::LeAudioLtvMap(announcement.metadata).RawPacket(); - }); + EXPECT_CALL(*MockBroadcastStateMachine::GetLastInstance(), UpdatePublicBroadcastAnnouncement) + .WillOnce([&](uint32_t broadcast_id, const std::string& broadcast_name, + const bluetooth::le_audio::PublicBroadcastAnnouncementData& announcement) { + expected_broadcast_name = broadcast_name; + expected_public_meta = types::LeAudioLtvMap(announcement.metadata).RawPacket(); + }); - ContentControlIdKeeper::GetInstance()->SetCcid(LeAudioContextType::ALERTS, - default_ccid); + ContentControlIdKeeper::GetInstance()->SetCcid(LeAudioContextType::ALERTS, default_ccid); LeAudioBroadcaster::Get()->UpdateMetadata( - broadcast_id, test_broadcast_name, default_public_metadata, - {std::vector({0x02, 0x01, 0x02, 0x03, 0x02, 0x04, 0x04})}); + broadcast_id, test_broadcast_name, default_public_metadata, + {std::vector({0x02, 0x01, 0x02, 0x03, 0x02, 0x04, 0x04})}); std::vector public_metadata(default_public_metadata); public_metadata.insert(public_metadata.end(), audio_active_state_false.begin(), @@ -817,8 +749,8 @@ TEST_F(BroadcasterTest, UpdateMetadata) { } static BasicAudioAnnouncementData prepareAnnouncement( - const BroadcastSubgroupCodecConfig& codec_config, - std::map> metadata) { + const BroadcastSubgroupCodecConfig& codec_config, + std::map> metadata) { BasicAudioAnnouncementData announcement; announcement.presentation_delay_us = 40000; @@ -827,22 +759,20 @@ static BasicAudioAnnouncementData prepareAnnouncement( // Note: This is a single subgroup announcement. announcement.subgroup_configs = {{ - .codec_config = - { - .codec_id = codec_id.coding_format, - .vendor_company_id = codec_id.vendor_company_id, - .vendor_codec_id = codec_id.vendor_codec_id, - .codec_specific_params = subgroup_codec_spec.Values(), - }, - .metadata = std::move(metadata), - .bis_configs = {}, + .codec_config = + { + .codec_id = codec_id.coding_format, + .vendor_company_id = codec_id.vendor_company_id, + .vendor_codec_id = codec_id.vendor_codec_id, + .codec_specific_params = subgroup_codec_spec.Values(), + }, + .metadata = std::move(metadata), + .bis_configs = {}, }}; uint8_t bis_count = 0; - for (uint8_t cfg_idx = 0; cfg_idx < codec_config.GetAllBisConfigCount(); - ++cfg_idx) { - for (uint8_t bis_num = 0; bis_num < codec_config.GetNumBis(cfg_idx); - ++bis_num) { + for (uint8_t cfg_idx = 0; cfg_idx < codec_config.GetAllBisConfigCount(); ++cfg_idx) { + for (uint8_t bis_num = 0; bis_num < codec_config.GetNumBis(cfg_idx); ++bis_num) { ++bis_count; // Check for vendor byte array @@ -861,8 +791,7 @@ static BasicAudioAnnouncementData prepareAnnouncement( // Internally BISes are indexed from 0 in each subgroup, but the BT spec // requires the indices to be indexed from 1 in the entire BIG. bis_config.bis_index = bis_count; - announcement.subgroup_configs[0].bis_configs.push_back( - std::move(bis_config)); + announcement.subgroup_configs[0].bis_configs.push_back(std::move(bis_config)); } } @@ -870,13 +799,12 @@ static BasicAudioAnnouncementData prepareAnnouncement( } TEST_F(BroadcasterTest, UpdateMetadataFromAudioTrackMetadata) { - ContentControlIdKeeper::GetInstance()->SetCcid(LeAudioContextType::MEDIA, - media_ccid); + ContentControlIdKeeper::GetInstance()->SetCcid(LeAudioContextType::MEDIA, media_ccid); auto broadcast_id = InstantiateBroadcast(); LeAudioSourceAudioHalClient::Callbacks* audio_receiver; EXPECT_CALL(*mock_audio_source_, Start) - .WillOnce(DoAll(SaveArg<1>(&audio_receiver), Return(true))); + .WillOnce(DoAll(SaveArg<1>(&audio_receiver), Return(true))); LeAudioBroadcaster::Get()->StartAudioBroadcast(broadcast_id); ASSERT_NE(audio_receiver, nullptr); @@ -885,18 +813,14 @@ TEST_F(BroadcasterTest, UpdateMetadataFromAudioTrackMetadata) { std::vector ccid_list; std::vector context_types_map; EXPECT_CALL(*sm, UpdateBroadcastAnnouncement) - .WillOnce( - [&](bluetooth::le_audio::BasicAudioAnnouncementData announcement) { + .WillOnce([&](bluetooth::le_audio::BasicAudioAnnouncementData announcement) { for (auto subgroup : announcement.subgroup_configs) { - if (subgroup.metadata.count( - types::kLeAudioMetadataTypeCcidList)) { - ccid_list = - subgroup.metadata.at(types::kLeAudioMetadataTypeCcidList); + if (subgroup.metadata.count(types::kLeAudioMetadataTypeCcidList)) { + ccid_list = subgroup.metadata.at(types::kLeAudioMetadataTypeCcidList); } - if (subgroup.metadata.count( - types::kLeAudioMetadataTypeStreamingAudioContext)) { - context_types_map = subgroup.metadata.at( - types::kLeAudioMetadataTypeStreamingAudioContext); + if (subgroup.metadata.count(types::kLeAudioMetadataTypeStreamingAudioContext)) { + context_types_map = + subgroup.metadata.at(types::kLeAudioMetadataTypeStreamingAudioContext); } } }); @@ -905,46 +829,40 @@ TEST_F(BroadcasterTest, UpdateMetadataFromAudioTrackMetadata) { auto codec_config = broadcaster::lc3_mono_16_2; auto announcement = prepareAnnouncement(codec_config, meta); - ON_CALL(*sm, GetBroadcastAnnouncement()) - .WillByDefault(ReturnRef(announcement)); + ON_CALL(*sm, GetBroadcastAnnouncement()).WillByDefault(ReturnRef(announcement)); std::vector multitrack_source_metadata = { - {{AUDIO_USAGE_GAME, AUDIO_CONTENT_TYPE_SONIFICATION, 0}, - {AUDIO_USAGE_MEDIA, AUDIO_CONTENT_TYPE_MUSIC, 0}, - {AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING, AUDIO_CONTENT_TYPE_SPEECH, - 0}, - {AUDIO_USAGE_UNKNOWN, AUDIO_CONTENT_TYPE_UNKNOWN, 0}}}; + {{AUDIO_USAGE_GAME, AUDIO_CONTENT_TYPE_SONIFICATION, 0}, + {AUDIO_USAGE_MEDIA, AUDIO_CONTENT_TYPE_MUSIC, 0}, + {AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING, AUDIO_CONTENT_TYPE_SPEECH, 0}, + {AUDIO_USAGE_UNKNOWN, AUDIO_CONTENT_TYPE_UNKNOWN, 0}}}; std::vector tracks_vec; tracks_vec.reserve(multitrack_source_metadata.size()); for (const auto& track : multitrack_source_metadata) { playback_track_metadata_v7 desc_track = { - .base = - { - .usage = static_cast(track.usage), - .content_type = - static_cast(track.content_type), - .gain = track.gain, - }, + .base = + { + .usage = static_cast(track.usage), + .content_type = static_cast(track.content_type), + .gain = track.gain, + }, }; tracks_vec.push_back(desc_track); } - audio_receiver->OnAudioMetadataUpdate(std::move(tracks_vec), - DsaMode::DISABLED); + audio_receiver->OnAudioMetadataUpdate(std::move(tracks_vec), DsaMode::DISABLED); // Verify ccid ASSERT_NE(ccid_list.size(), 0u); - ASSERT_TRUE(std::find(ccid_list.begin(), ccid_list.end(), media_ccid) != - ccid_list.end()); + ASSERT_TRUE(std::find(ccid_list.begin(), ccid_list.end(), media_ccid) != ccid_list.end()); // Verify context type ASSERT_NE(context_types_map.size(), 0u); AudioContexts context_type; auto pp = context_types_map.data(); STREAM_TO_UINT16(context_type.value_ref(), pp); - ASSERT_TRUE(context_type.test_all(LeAudioContextType::MEDIA | - LeAudioContextType::GAME)); + ASSERT_TRUE(context_type.test_all(LeAudioContextType::MEDIA | LeAudioContextType::GAME)); } TEST_F(BroadcasterTest, GetMetadata) { @@ -953,7 +871,7 @@ TEST_F(BroadcasterTest, GetMetadata) { static const uint8_t test_adv_sid = 0x14; std::optional test_broadcast_code = - bluetooth::le_audio::BroadcastCode({1, 2, 3, 4, 5, 6}); + bluetooth::le_audio::BroadcastCode({1, 2, 3, 4, 5, 6}); auto sm = MockBroadcastStateMachine::GetLastInstance(); @@ -963,25 +881,20 @@ TEST_F(BroadcasterTest, GetMetadata) { bool is_public_metadata_valid; types::LeAudioLtvMap public_ltv = types::LeAudioLtvMap::Parse( - default_public_metadata.data(), default_public_metadata.size(), - is_public_metadata_valid); - PublicBroadcastAnnouncementData pb_announcement = { - .features = test_public_broadcast_features, - .metadata = public_ltv.Values()}; + default_public_metadata.data(), default_public_metadata.size(), is_public_metadata_valid); + PublicBroadcastAnnouncementData pb_announcement = {.features = test_public_broadcast_features, + .metadata = public_ltv.Values()}; ON_CALL(*sm, IsPublicBroadcast()).WillByDefault(Return(true)); ON_CALL(*sm, GetBroadcastName()).WillByDefault(Return(test_broadcast_name)); ON_CALL(*sm, GetBroadcastCode()).WillByDefault(Return(test_broadcast_code)); ON_CALL(*sm, GetAdvertisingSid()).WillByDefault(Return(test_adv_sid)); - ON_CALL(*sm, GetBroadcastAnnouncement()) - .WillByDefault(ReturnRef(announcement)); - ON_CALL(*sm, GetPublicBroadcastAnnouncement()) - .WillByDefault(ReturnRef(pb_announcement)); + ON_CALL(*sm, GetBroadcastAnnouncement()).WillByDefault(ReturnRef(announcement)); + ON_CALL(*sm, GetPublicBroadcastAnnouncement()).WillByDefault(ReturnRef(pb_announcement)); - EXPECT_CALL(mock_broadcaster_callbacks_, - OnBroadcastMetadataChanged(broadcast_id, _)) - .Times(1) - .WillOnce(SaveArg<1>(&metadata)); + EXPECT_CALL(mock_broadcaster_callbacks_, OnBroadcastMetadataChanged(broadcast_id, _)) + .Times(1) + .WillOnce(SaveArg<1>(&metadata)); LeAudioBroadcaster::Get()->GetBroadcastMetadata(broadcast_id); ASSERT_NE(LeAudioBroadcaster::kInstanceIdUndefined, metadata.broadcast_id); @@ -1016,33 +929,26 @@ TEST_F(BroadcasterTest, StreamParamsAlerts) { auto config = MockBroadcastStateMachine::GetLastInstance()->cfg; // Check audio configuration - ASSERT_EQ(config.config.subgroups.at(0).GetNumChannelsTotal(), - expected_channels); + ASSERT_EQ(config.config.subgroups.at(0).GetNumChannelsTotal(), expected_channels); // Matches number of bises in the announcement - ASSERT_EQ(config.announcement.subgroup_configs[0].bis_configs.size(), - expected_channels); + ASSERT_EQ(config.announcement.subgroup_configs[0].bis_configs.size(), expected_channels); // Note: Num of bises at IsoManager level is verified by state machine tests } TEST_F(BroadcasterTest, StreamParamsMedia) { uint8_t expected_channels = 2u; - ContentControlIdKeeper::GetInstance()->SetCcid(LeAudioContextType::MEDIA, - media_ccid); - InstantiateBroadcast(media_metadata, default_code, - {bluetooth::le_audio::QUALITY_HIGH}); + ContentControlIdKeeper::GetInstance()->SetCcid(LeAudioContextType::MEDIA, media_ccid); + InstantiateBroadcast(media_metadata, default_code, {bluetooth::le_audio::QUALITY_HIGH}); auto config = MockBroadcastStateMachine::GetLastInstance()->cfg; // Check audio configuration ASSERT_EQ(config.config.subgroups.at(0).GetNumBis(), expected_channels); - ASSERT_EQ(config.config.subgroups.at(0).GetNumChannelsTotal(), - expected_channels); + ASSERT_EQ(config.config.subgroups.at(0).GetNumChannelsTotal(), expected_channels); // Note there is one BIS configuration applied to both (stereo) BISes - ASSERT_EQ(config.config.subgroups.at(0).GetAllBisConfigCount(), - (unsigned long)1); - ASSERT_EQ(config.config.subgroups.at(0).GetNumBis(0), - (unsigned long)expected_channels); + ASSERT_EQ(config.config.subgroups.at(0).GetAllBisConfigCount(), (unsigned long)1); + ASSERT_EQ(config.config.subgroups.at(0).GetNumBis(0), (unsigned long)expected_channels); // Matches number of bises in the announcement ASSERT_EQ(config.announcement.subgroup_configs.size(), 1ul); @@ -1050,9 +956,8 @@ TEST_F(BroadcasterTest, StreamParamsMedia) { auto& announcement_subgroup = config.announcement.subgroup_configs[0]; ASSERT_EQ(announcement_subgroup.bis_configs.size(), expected_channels); // Verify CCID for Media - auto ccid_list_opt = - types::LeAudioLtvMap(announcement_subgroup.metadata) - .Find(bluetooth::le_audio::types::kLeAudioMetadataTypeCcidList); + auto ccid_list_opt = types::LeAudioLtvMap(announcement_subgroup.metadata) + .Find(bluetooth::le_audio::types::kLeAudioMetadataTypeCcidList); ASSERT_TRUE(ccid_list_opt.has_value()); auto ccid_list = ccid_list_opt.value(); ASSERT_EQ(1u, ccid_list.size()); @@ -1066,96 +971,90 @@ TEST_F(BroadcasterTest, QueuedBroadcast) { iso_active_callback(true); EXPECT_CALL(mock_broadcaster_callbacks_, OnBroadcastCreated(_, true)) - .WillOnce(SaveArg<0>(&broadcast_id)); + .WillOnce(SaveArg<0>(&broadcast_id)); /* Trigger broadcast create but due to active ISO, queue request */ - InstantiateBroadcast(default_metadata, default_code, - default_subgroup_qualities, true); + InstantiateBroadcast(default_metadata, default_code, default_subgroup_qualities, true); /* Notify about ISO being free, check if broadcast would be created */ iso_active_callback(false); ASSERT_NE(broadcast_id, LeAudioBroadcaster::kInstanceIdUndefined); - ASSERT_EQ(broadcast_id, - MockBroadcastStateMachine::GetLastInstance()->GetBroadcastId()); + ASSERT_EQ(broadcast_id, MockBroadcastStateMachine::GetLastInstance()->GetBroadcastId()); auto& instance_config = MockBroadcastStateMachine::GetLastInstance()->cfg; ASSERT_EQ(instance_config.broadcast_code, default_code); for (auto& subgroup : instance_config.announcement.subgroup_configs) { - ASSERT_EQ(types::LeAudioLtvMap(subgroup.metadata).RawPacket(), - default_metadata); + ASSERT_EQ(types::LeAudioLtvMap(subgroup.metadata).RawPacket(), default_metadata); } } TEST_F(BroadcasterTest, QueuedBroadcastBusyIso) { iso_active_callback(true); - EXPECT_CALL(mock_broadcaster_callbacks_, OnBroadcastCreated(_, true)) - .Times(0); + EXPECT_CALL(mock_broadcaster_callbacks_, OnBroadcastCreated(_, true)).Times(0); /* Trigger broadcast create but due to active ISO, queue request */ - InstantiateBroadcast(default_metadata, default_code, - default_subgroup_qualities, true); + InstantiateBroadcast(default_metadata, default_code, default_subgroup_qualities, true); } constexpr types::LeAudioCodecId kLeAudioCodecIdVendor1 = { - .coding_format = types::kLeAudioCodingFormatVendorSpecific, - // Not a particualr vendor - just some random numbers - .vendor_company_id = 0xC0, - .vendor_codec_id = 0xDE, + .coding_format = types::kLeAudioCodingFormatVendorSpecific, + // Not a particualr vendor - just some random numbers + .vendor_company_id = 0xC0, + .vendor_codec_id = 0xDE, }; static const types::DataPathConfiguration vendor_data_path = { - .dataPathId = bluetooth::hci::iso_manager::kIsoDataPathHci, - .dataPathConfig = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, - 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, - .isoDataPathConfig = - { - .codecId = kLeAudioCodecIdVendor1, - .isTransparent = true, - .controllerDelayUs = 0x00000000, // irrlevant for transparent mode - .configuration = {0x1F, 0x2E, 0x3D, 0x4C, 0x5B, 0x6A, 0x79, 0x88, - 0x97, 0xA6, 0xB5, 0xC4, 0xD3, 0xE2, 0xF1}, - }, + .dataPathId = bluetooth::hci::iso_manager::kIsoDataPathHci, + .dataPathConfig = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, + 0x0C, 0x0D, 0x0E, 0x0F}, + .isoDataPathConfig = + { + .codecId = kLeAudioCodecIdVendor1, + .isTransparent = true, + .controllerDelayUs = 0x00000000, // irrlevant for transparent mode + .configuration = {0x1F, 0x2E, 0x3D, 0x4C, 0x5B, 0x6A, 0x79, 0x88, 0x97, + 0xA6, 0xB5, 0xC4, 0xD3, 0xE2, 0xF1}, + }, }; // Quality subgroup configurations static const broadcaster::BroadcastSubgroupCodecConfig vendor_stereo_16_2 = - broadcaster::BroadcastSubgroupCodecConfig( - kLeAudioCodecIdVendor1, - {broadcaster::BroadcastSubgroupBisCodecConfig{ - // num_bis - 2, - // bis_channel_cnt - 1, - // codec_specific - types::LeAudioLtvMap({ - LTV_ENTRY_SAMPLING_FREQUENCY( - codec_spec_conf::kLeAudioSamplingFreq16000Hz), - LTV_ENTRY_FRAME_DURATION( - codec_spec_conf::kLeAudioCodecFrameDur10000us), - LTV_ENTRY_OCTETS_PER_CODEC_FRAME(50), - }), - // vendor_codec_specific - std::vector{0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, - 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, - 0xF0}, - }}, - // bits_per_sample - 24, - // vendor_codec_specific - std::vector{0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, - 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF}); + broadcaster::BroadcastSubgroupCodecConfig( + kLeAudioCodecIdVendor1, + {broadcaster::BroadcastSubgroupBisCodecConfig{ + // num_bis + 2, + // bis_channel_cnt + 1, + // codec_specific + types::LeAudioLtvMap({ + LTV_ENTRY_SAMPLING_FREQUENCY( + codec_spec_conf::kLeAudioSamplingFreq16000Hz), + LTV_ENTRY_FRAME_DURATION( + codec_spec_conf::kLeAudioCodecFrameDur10000us), + LTV_ENTRY_OCTETS_PER_CODEC_FRAME(50), + }), + // vendor_codec_specific + std::vector{0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80, + 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0}, + }}, + // bits_per_sample + 24, + // vendor_codec_specific + std::vector{0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, + 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF}); static const broadcaster::BroadcastConfiguration vendor_stereo_16_2_1 = { - // subgroup list, qos configuration, data path configuration - .subgroups = {vendor_stereo_16_2}, - .qos = broadcaster::qos_config_2_10, - .data_path = vendor_data_path, - .sduIntervalUs = 5000, - .maxSduOctets = 128, - .phy = 0x01, // PHY_LE_1M - .packing = 1, // Interleaved - .framing = 1, // Framed + // subgroup list, qos configuration, data path configuration + .subgroups = {vendor_stereo_16_2}, + .qos = broadcaster::qos_config_2_10, + .data_path = vendor_data_path, + .sduIntervalUs = 5000, + .maxSduOctets = 128, + .phy = 0x01, // PHY_LE_1M + .packing = 1, // Interleaved + .framing = 1, // Framed }; TEST_F(BroadcasterTest, SanityTest) { @@ -1165,17 +1064,16 @@ TEST_F(BroadcasterTest, SanityTest) { TEST_F(BroadcasterTest, VendorCodecConfig) { ON_CALL(*mock_codec_manager_, GetBroadcastConfig) - .WillByDefault(Invoke([](const bluetooth::le_audio::CodecManager:: - BroadcastConfigurationRequirements&) { - return std::make_unique( - vendor_stereo_16_2_1); - })); - ContentControlIdKeeper::GetInstance()->SetCcid(LeAudioContextType::MEDIA, - media_ccid); + .WillByDefault(Invoke( + [](const bluetooth::le_audio::CodecManager::BroadcastConfigurationRequirements&) { + return std::make_unique( + vendor_stereo_16_2_1); + })); + ContentControlIdKeeper::GetInstance()->SetCcid(LeAudioContextType::MEDIA, media_ccid); // iso_active_callback(false); - auto broadcast_id = InstantiateBroadcast(media_metadata, default_code, - {bluetooth::le_audio::QUALITY_HIGH}); + auto broadcast_id = + InstantiateBroadcast(media_metadata, default_code, {bluetooth::le_audio::QUALITY_HIGH}); ASSERT_NE(LeAudioBroadcaster::kInstanceIdUndefined, broadcast_id); auto mock_state_machine = MockBroadcastStateMachine::GetLastInstance(); @@ -1189,13 +1087,10 @@ TEST_F(BroadcasterTest, VendorCodecConfig) { // One subgroup ASSERT_EQ(1lu, mock_state_machine->cfg.announcement.subgroup_configs.size()); - auto const& subgroup = - mock_state_machine->cfg.announcement.subgroup_configs.at(0); + auto const& subgroup = mock_state_machine->cfg.announcement.subgroup_configs.at(0); - auto const& expected_subgroup_codec_conf = - vendor_stereo_16_2_1.subgroups.at(0); - ASSERT_EQ(expected_subgroup_codec_conf.GetNumBis(), - subgroup.bis_configs.size()); + auto const& expected_subgroup_codec_conf = vendor_stereo_16_2_1.subgroups.at(0); + ASSERT_EQ(expected_subgroup_codec_conf.GetNumBis(), subgroup.bis_configs.size()); // Subgroup level codec configuration ASSERT_EQ(expected_subgroup_codec_conf.GetLeAudioCodecId().coding_format, @@ -1209,17 +1104,15 @@ TEST_F(BroadcasterTest, VendorCodecConfig) { // a vendor specific configuration ASSERT_TRUE(subgroup.codec_config.codec_specific_params.empty()); ASSERT_TRUE(subgroup.codec_config.vendor_codec_specific_params.has_value()); - ASSERT_EQ( - 0, memcmp(expected_subgroup_codec_conf.GetVendorCodecSpecData()->data(), - subgroup.codec_config.vendor_codec_specific_params->data(), - subgroup.codec_config.vendor_codec_specific_params->size())); + ASSERT_EQ(0, memcmp(expected_subgroup_codec_conf.GetVendorCodecSpecData()->data(), + subgroup.codec_config.vendor_codec_specific_params->data(), + subgroup.codec_config.vendor_codec_specific_params->size())); // Subgroup metadata ASSERT_NE(0lu, subgroup.metadata.size()); // Verify the BISes - ASSERT_EQ(expected_subgroup_codec_conf.GetNumBis(), - subgroup.bis_configs.size()); + ASSERT_EQ(expected_subgroup_codec_conf.GetNumBis(), subgroup.bis_configs.size()); // Verify BIS 1 uint8_t bis_idx = 1; @@ -1227,17 +1120,13 @@ TEST_F(BroadcasterTest, VendorCodecConfig) { // Expect only the vendor specific data ASSERT_TRUE(subgroup.bis_configs.at(0).codec_specific_params.empty()); ASSERT_TRUE(subgroup.bis_configs.at(0) - .vendor_codec_specific_params - .has_value()); // BIS vendor specific parameters - ASSERT_NE(0lu, - subgroup.bis_configs.at(0).vendor_codec_specific_params->size()); + .vendor_codec_specific_params.has_value()); // BIS vendor specific parameters + ASSERT_NE(0lu, subgroup.bis_configs.at(0).vendor_codec_specific_params->size()); ASSERT_EQ(expected_subgroup_codec_conf.GetBisVendorCodecSpecData(0)->size(), subgroup.bis_configs.at(0).vendor_codec_specific_params->size()); - ASSERT_EQ( - 0, - memcmp(expected_subgroup_codec_conf.GetBisVendorCodecSpecData(0)->data(), - subgroup.bis_configs.at(0).vendor_codec_specific_params->data(), - subgroup.bis_configs.at(0).vendor_codec_specific_params->size())); + ASSERT_EQ(0, memcmp(expected_subgroup_codec_conf.GetBisVendorCodecSpecData(0)->data(), + subgroup.bis_configs.at(0).vendor_codec_specific_params->data(), + subgroup.bis_configs.at(0).vendor_codec_specific_params->size())); // Verify BIS 2 bis_idx = 2; @@ -1245,17 +1134,13 @@ TEST_F(BroadcasterTest, VendorCodecConfig) { // Expect only the vendor specific data ASSERT_TRUE(subgroup.bis_configs.at(1).codec_specific_params.empty()); ASSERT_TRUE(subgroup.bis_configs.at(1) - .vendor_codec_specific_params - .has_value()); // BIS vendor specific parameters - ASSERT_NE(0lu, - subgroup.bis_configs.at(1).vendor_codec_specific_params->size()); + .vendor_codec_specific_params.has_value()); // BIS vendor specific parameters + ASSERT_NE(0lu, subgroup.bis_configs.at(1).vendor_codec_specific_params->size()); ASSERT_EQ(expected_subgroup_codec_conf.GetBisVendorCodecSpecData(1)->size(), subgroup.bis_configs.at(1).vendor_codec_specific_params->size()); - ASSERT_EQ( - 0, - memcmp(expected_subgroup_codec_conf.GetBisVendorCodecSpecData(1)->data(), - subgroup.bis_configs.at(1).vendor_codec_specific_params->data(), - subgroup.bis_configs.at(1).vendor_codec_specific_params->size())); + ASSERT_EQ(0, memcmp(expected_subgroup_codec_conf.GetBisVendorCodecSpecData(1)->data(), + subgroup.bis_configs.at(1).vendor_codec_specific_params->data(), + subgroup.bis_configs.at(1).vendor_codec_specific_params->size())); } TEST_F_WITH_FLAGS(BroadcasterTest, AudioActiveState, diff --git a/system/bta/le_audio/broadcaster/broadcaster_types.cc b/system/bta/le_audio/broadcaster/broadcaster_types.cc index 542d8811b28..718327f612f 100644 --- a/system/bta/le_audio/broadcaster/broadcaster_types.cc +++ b/system/bta/le_audio/broadcaster/broadcaster_types.cc @@ -48,9 +48,9 @@ static void EmitHeader(const BasicAudioAnnouncementData& announcement_data, UINT24_TO_STREAM(p_value, announcement_data.presentation_delay_us); } -static void EmitCodecConfiguration( - const BasicAudioAnnouncementCodecConfig& config, std::vector& data, - const BasicAudioAnnouncementCodecConfig* lower_lvl_config) { +static void EmitCodecConfiguration(const BasicAudioAnnouncementCodecConfig& config, + std::vector& data, + const BasicAudioAnnouncementCodecConfig* lower_lvl_config) { size_t old_size = data.size(); // Add 5 for full, or 1 for short Codec ID @@ -77,17 +77,15 @@ static void EmitCodecConfiguration( // Codec specific config length and data (either vendor specific or the LTVs) UINT8_TO_STREAM(p_value, codec_spec_raw_sz); if (config.vendor_codec_specific_params) { - ARRAY_TO_STREAM( - p_value, config.vendor_codec_specific_params->data(), - static_cast(config.vendor_codec_specific_params->size())); + ARRAY_TO_STREAM(p_value, config.vendor_codec_specific_params->data(), + static_cast(config.vendor_codec_specific_params->size())); } else { p_value = ltv.RawPacket(p_value); } } -static void EmitMetadata( - const std::map>& metadata, - std::vector& data) { +static void EmitMetadata(const std::map>& metadata, + std::vector& data) { auto ltv = types::LeAudioLtvMap(metadata); auto ltv_raw_sz = ltv.RawPacketSize(); @@ -103,8 +101,7 @@ static void EmitMetadata( } } -static void EmitBroadcastName(const std::string& name, - std::vector& data) { +static void EmitBroadcastName(const std::string& name, std::vector& data) { int name_len = name.length(); size_t old_size = data.size(); data.resize(old_size + name_len + 2); @@ -118,9 +115,8 @@ static void EmitBroadcastName(const std::string& name, ARRAY_TO_STREAM(p_value, vec.data(), name_len); } -static void EmitBisConfigs( - const std::vector& bis_configs, - std::vector& data) { +static void EmitBisConfigs(const std::vector& bis_configs, + std::vector& data) { // Emit each BIS config - that's the level 3 data for (auto const& bis_config : bis_configs) { auto ltv = types::LeAudioLtvMap(bis_config.codec_specific_params); @@ -162,8 +158,7 @@ static void EmitSubgroup(const BasicAudioAnnouncementSubgroup& subgroup_config, EmitBisConfigs(subgroup_config.bis_configs, data); } -bool ToRawPacket(BasicAudioAnnouncementData const& in, - std::vector& data) { +bool ToRawPacket(BasicAudioAnnouncementData const& in, std::vector& data) { EmitHeader(in, data); // Set the cursor behind the old data and resize @@ -183,11 +178,10 @@ bool ToRawPacket(BasicAudioAnnouncementData const& in, } void PrepareAdvertisingData( - bool is_public, const std::string& broadcast_name, - bluetooth::le_audio::BroadcastId& broadcast_id, - const bluetooth::le_audio::PublicBroadcastAnnouncementData& - public_announcement, - std::vector& adv_data) { + bool is_public, const std::string& broadcast_name, + bluetooth::le_audio::BroadcastId& broadcast_id, + const bluetooth::le_audio::PublicBroadcastAnnouncementData& public_announcement, + std::vector& adv_data) { adv_data.resize(7); uint8_t* data_ptr = adv_data.data(); UINT8_TO_STREAM(data_ptr, 6); @@ -236,27 +230,24 @@ void PreparePeriodicData(const BasicAudioAnnouncementData& announcement, UINT8_TO_STREAM(data_ptr, periodic_data.size() - 1); } -le_audio::LeAudioCodecConfiguration -BroadcastConfiguration::GetAudioHalClientConfig() const { +le_audio::LeAudioCodecConfiguration BroadcastConfiguration::GetAudioHalClientConfig() const { return { - // Get the maximum number of channels - .num_channels = GetNumChannelsMax(), - // Get the max sampling frequency - .sample_rate = GetSamplingFrequencyHzMax(), - // Use the default 16 bits per sample resolution in the audio framework - .bits_per_sample = 16, - // Get the data interval - .data_interval_us = GetSduIntervalUs(), + // Get the maximum number of channels + .num_channels = GetNumChannelsMax(), + // Get the max sampling frequency + .sample_rate = GetSamplingFrequencyHzMax(), + // Use the default 16 bits per sample resolution in the audio framework + .bits_per_sample = 16, + // Get the data interval + .data_interval_us = GetSduIntervalUs(), }; } std::ostream& operator<<( - std::ostream& os, - const bluetooth::le_audio::broadcaster::BroadcastSubgroupCodecConfig& - config) { + std::ostream& os, + const bluetooth::le_audio::broadcaster::BroadcastSubgroupCodecConfig& config) { os << " BroadcastSubgroupCodecConfig={"; - os << "CodecID=" - << "{" << +config.GetLeAudioCodecId().coding_format << ":" + os << "CodecID=" << "{" << +config.GetLeAudioCodecId().coding_format << ":" << +config.GetLeAudioCodecId().vendor_company_id << ":" << +config.GetLeAudioCodecId().vendor_codec_id << "}, "; os << "BISes=["; @@ -272,9 +263,8 @@ std::ostream& operator<<( return os; } -std::ostream& operator<<( - std::ostream& os, - const le_audio::broadcaster::BroadcastSubgroupBisCodecConfig& config) { +std::ostream& operator<<(std::ostream& os, + const le_audio::broadcaster::BroadcastSubgroupBisCodecConfig& config) { os << "BisCfg={numBis=" << +config.GetNumBis() << ", NumChannelsPerBis=" << +config.GetNumChannelsPerBis() << ", CodecSpecific=" << config.GetCodecSpecData().GetAsCoreCodecConfig(); @@ -290,9 +280,8 @@ std::ostream& operator<<( return os; } -std::ostream& operator<<( - std::ostream& os, - const bluetooth::le_audio::broadcaster::BroadcastQosConfig& config) { +std::ostream& operator<<(std::ostream& os, + const bluetooth::le_audio::broadcaster::BroadcastQosConfig& config) { os << " BroadcastQosConfig=["; os << "RTN=" << +config.getRetransmissionNumber(); os << ", MaxTransportLatency=" << config.getMaxTransportLatency(); @@ -300,9 +289,8 @@ std::ostream& operator<<( return os; } -std::ostream& operator<<( - std::ostream& os, - const le_audio::broadcaster::BroadcastConfiguration& config) { +std::ostream& operator<<(std::ostream& os, + const le_audio::broadcaster::BroadcastConfiguration& config) { os << "BroadcastCfg={"; for (const auto& subgroup_cfg : config.subgroups) { os << subgroup_cfg << std::endl; @@ -327,59 +315,75 @@ namespace bluetooth::le_audio { static bool isMetadataSame(std::map> m1, std::map> m2) { - if (m1.size() != m2.size()) return false; + if (m1.size() != m2.size()) { + return false; + } for (auto& m1pair : m1) { - if (m2.count(m1pair.first) == 0) return false; + if (m2.count(m1pair.first) == 0) { + return false; + } auto& m2val = m2.at(m1pair.first); - if (m1pair.second.size() != m2val.size()) return false; + if (m1pair.second.size() != m2val.size()) { + return false; + } if (m1pair.second.size() != 0) { - if (memcmp(m1pair.second.data(), m2val.data(), m2val.size()) != 0) + if (memcmp(m1pair.second.data(), m2val.data(), m2val.size()) != 0) { return false; + } } } return true; } -bool operator==(const BasicAudioAnnouncementData& lhs, - const BasicAudioAnnouncementData& rhs) { - if (lhs.presentation_delay_us != rhs.presentation_delay_us) return false; +bool operator==(const BasicAudioAnnouncementData& lhs, const BasicAudioAnnouncementData& rhs) { + if (lhs.presentation_delay_us != rhs.presentation_delay_us) { + return false; + } - if (lhs.subgroup_configs.size() != rhs.subgroup_configs.size()) return false; + if (lhs.subgroup_configs.size() != rhs.subgroup_configs.size()) { + return false; + } for (auto i = 0lu; i < lhs.subgroup_configs.size(); ++i) { auto& lhs_subgroup = lhs.subgroup_configs[i]; auto& rhs_subgroup = rhs.subgroup_configs[i]; - if (lhs_subgroup.codec_config.codec_id != - rhs_subgroup.codec_config.codec_id) + if (lhs_subgroup.codec_config.codec_id != rhs_subgroup.codec_config.codec_id) { return false; + } if (lhs_subgroup.codec_config.vendor_company_id != - rhs_subgroup.codec_config.vendor_company_id) + rhs_subgroup.codec_config.vendor_company_id) { return false; + } - if (lhs_subgroup.codec_config.vendor_codec_id != - rhs_subgroup.codec_config.vendor_codec_id) + if (lhs_subgroup.codec_config.vendor_codec_id != rhs_subgroup.codec_config.vendor_codec_id) { return false; + } if (!isMetadataSame(lhs_subgroup.codec_config.codec_specific_params, - rhs_subgroup.codec_config.codec_specific_params)) + rhs_subgroup.codec_config.codec_specific_params)) { return false; + } - if (!isMetadataSame(lhs_subgroup.metadata, rhs_subgroup.metadata)) + if (!isMetadataSame(lhs_subgroup.metadata, rhs_subgroup.metadata)) { return false; + } for (auto j = 0lu; j < lhs_subgroup.bis_configs.size(); ++j) { auto& lhs_bis_config = lhs_subgroup.bis_configs[i]; auto& rhs_bis_config = rhs_subgroup.bis_configs[i]; - if (lhs_bis_config.bis_index != rhs_bis_config.bis_index) return false; + if (lhs_bis_config.bis_index != rhs_bis_config.bis_index) { + return false; + } if (!isMetadataSame(lhs_bis_config.codec_specific_params, - rhs_bis_config.codec_specific_params)) + rhs_bis_config.codec_specific_params)) { return false; + } } } @@ -388,8 +392,12 @@ bool operator==(const BasicAudioAnnouncementData& lhs, bool operator==(const PublicBroadcastAnnouncementData& lhs, const PublicBroadcastAnnouncementData& rhs) { - if (lhs.features != rhs.features) return false; - if (!isMetadataSame(lhs.metadata, rhs.metadata)) return false; + if (lhs.features != rhs.features) { + return false; + } + if (!isMetadataSame(lhs.metadata, rhs.metadata)) { + return false; + } return true; } diff --git a/system/bta/le_audio/broadcaster/broadcaster_types.h b/system/bta/le_audio/broadcaster/broadcaster_types.h index 01ad419863b..add3d57b5cb 100644 --- a/system/bta/le_audio/broadcaster/broadcaster_types.h +++ b/system/bta/le_audio/broadcaster/broadcaster_types.h @@ -39,53 +39,42 @@ static const uint16_t kPublicBroadcastAnnouncementServiceUuid = 0x1856; static const uint8_t kBisIndexInvalid = 0; -bool ToRawPacket(bluetooth::le_audio::BasicAudioAnnouncementData const&, - std::vector&); +bool ToRawPacket(bluetooth::le_audio::BasicAudioAnnouncementData const&, std::vector&); void PrepareAdvertisingData( - bool is_public, const std::string& broadcast_name, - bluetooth::le_audio::BroadcastId& broadcast_id, - const bluetooth::le_audio::PublicBroadcastAnnouncementData& - public_announcement, - std::vector& adv_data); -void PreparePeriodicData( - const bluetooth::le_audio::BasicAudioAnnouncementData& announcement, - std::vector& periodic_data); + bool is_public, const std::string& broadcast_name, + bluetooth::le_audio::BroadcastId& broadcast_id, + const bluetooth::le_audio::PublicBroadcastAnnouncementData& public_announcement, + std::vector& adv_data); +void PreparePeriodicData(const bluetooth::le_audio::BasicAudioAnnouncementData& announcement, + std::vector& periodic_data); struct BroadcastSubgroupBisCodecConfig { BroadcastSubgroupBisCodecConfig( - uint8_t num_bis, uint8_t bis_channel_cnt, - types::LeAudioLtvMap codec_specific, - std::optional> vendor_codec_specific = std::nullopt) + uint8_t num_bis, uint8_t bis_channel_cnt, types::LeAudioLtvMap codec_specific, + std::optional> vendor_codec_specific = std::nullopt) : num_bis_(num_bis), bis_channel_cnt_(bis_channel_cnt), codec_specific_(codec_specific), vendor_codec_specific_(vendor_codec_specific) {} bool operator==(const BroadcastSubgroupBisCodecConfig& other) const { - return (num_bis_ == other.num_bis_) && - (bis_channel_cnt_ == other.bis_channel_cnt_) && + return (num_bis_ == other.num_bis_) && (bis_channel_cnt_ == other.bis_channel_cnt_) && (codec_specific_ == other.codec_specific_) && (vendor_codec_specific_ == other.vendor_codec_specific_); } - bool operator!=(const BroadcastSubgroupBisCodecConfig& other) const { - return !(*this == other); - } + bool operator!=(const BroadcastSubgroupBisCodecConfig& other) const { return !(*this == other); } uint8_t GetNumBis() const { return num_bis_; } - const types::LeAudioLtvMap& GetCodecSpecData() const { - return codec_specific_; - }; + const types::LeAudioLtvMap& GetCodecSpecData() const { return codec_specific_; } const std::optional>& GetVendorCodecSpecific() const { return vendor_codec_specific_; } - bool HasVendorCodecSpecific() const { - return vendor_codec_specific_.has_value(); - } + bool HasVendorCodecSpecific() const { return vendor_codec_specific_.has_value(); } uint8_t GetNumChannels() const { return num_bis_ * GetNumChannelsPerBis(); } @@ -95,7 +84,7 @@ struct BroadcastSubgroupBisCodecConfig { uint8_t GetNumChannelsPerBis() const { return bis_channel_cnt_; } - private: +private: uint8_t num_bis_; uint8_t bis_channel_cnt_; /* Codec Specific Configuration */ @@ -103,17 +92,14 @@ struct BroadcastSubgroupBisCodecConfig { std::optional> vendor_codec_specific_; }; -std::ostream& operator<<( - std::ostream& os, - const le_audio::broadcaster::BroadcastSubgroupBisCodecConfig& config); +std::ostream& operator<<(std::ostream& os, + const le_audio::broadcaster::BroadcastSubgroupBisCodecConfig& config); struct BroadcastSubgroupCodecConfig { BroadcastSubgroupCodecConfig( - types::LeAudioCodecId codec_id, - std::vector bis_codec_configs, - uint8_t bits_per_sample, - std::optional> subgroup_vendor_codec_config = - std::nullopt) + types::LeAudioCodecId codec_id, + std::vector bis_codec_configs, uint8_t bits_per_sample, + std::optional> subgroup_vendor_codec_config = std::nullopt) : codec_id_(codec_id), bis_codec_configs_(bis_codec_configs), subgroup_vendor_codec_config_(subgroup_vendor_codec_config), @@ -121,12 +107,12 @@ struct BroadcastSubgroupCodecConfig { bool operator==(const BroadcastSubgroupCodecConfig& other) const { if (subgroup_vendor_codec_config_.has_value() != - other.subgroup_vendor_codec_config_.has_value()) + other.subgroup_vendor_codec_config_.has_value()) { return false; + } if (subgroup_vendor_codec_config_.has_value()) { - if (subgroup_vendor_codec_config_->size() != - other.subgroup_vendor_codec_config_->size()) { + if (subgroup_vendor_codec_config_->size() != other.subgroup_vendor_codec_config_->size()) { return false; } @@ -137,20 +123,18 @@ struct BroadcastSubgroupCodecConfig { } } - return (codec_id_ == other.codec_id_) && - (bis_codec_configs_ == other.bis_codec_configs_) && + return (codec_id_ == other.codec_id_) && (bis_codec_configs_ == other.bis_codec_configs_) && (bits_per_sample_ == other.bits_per_sample_); } - bool operator!=(const BroadcastSubgroupCodecConfig& other) const { - return !(*this == other); - } + bool operator!=(const BroadcastSubgroupCodecConfig& other) const { return !(*this == other); } types::LeAudioLtvMap GetCommonBisCodecSpecData() const { - if (bis_codec_configs_.empty()) return types::LeAudioLtvMap(); + if (bis_codec_configs_.empty()) { + return types::LeAudioLtvMap(); + } auto common_ltv = bis_codec_configs_[0].GetCodecSpecData(); - for (auto it = bis_codec_configs_.begin() + 1; - it != bis_codec_configs_.end(); ++it) { + for (auto it = bis_codec_configs_.begin() + 1; it != bis_codec_configs_.end(); ++it) { common_ltv = it->GetCodecSpecData().GetIntersection(common_ltv); } return common_ltv; @@ -160,9 +144,10 @@ struct BroadcastSubgroupCodecConfig { return subgroup_vendor_codec_config_; } - std::optional> GetBisVendorCodecSpecData( - uint8_t bis_idx) const { - if (bis_codec_configs_.empty()) return std::nullopt; + std::optional> GetBisVendorCodecSpecData(uint8_t bis_idx) const { + if (bis_codec_configs_.empty()) { + return std::nullopt; + } auto config = bis_codec_configs_.at(0); if ((bis_idx != 0) && (bis_idx < bis_codec_configs_.size())) { config = bis_codec_configs_.at(bis_idx); @@ -177,35 +162,34 @@ struct BroadcastSubgroupCodecConfig { uint16_t GetBisOctetsPerCodecFrame(uint8_t bis_idx) const { // Check the subgroup level parameters first, then the specific BIS - auto num_octets = GetCommonBisCodecSpecData() - .GetAsCoreCodecConfig() - .octets_per_codec_frame.value_or(0); - if (num_octets) return num_octets; + auto num_octets = + GetCommonBisCodecSpecData().GetAsCoreCodecConfig().octets_per_codec_frame.value_or(0); + if (num_octets) { + return num_octets; + } // Currently not a single software vendor codec was integrated and only the // LTVs parameters are understood by the BT stack. auto opt_ltvs = GetBisCodecSpecData(bis_idx, 0); if (opt_ltvs) { - return opt_ltvs->GetAsCoreCodecConfig().octets_per_codec_frame.value_or( - 0) * - opt_ltvs->GetAsCoreCodecConfig() - .codec_frames_blocks_per_sdu.value_or(0); + return opt_ltvs->GetAsCoreCodecConfig().octets_per_codec_frame.value_or(0) * + opt_ltvs->GetAsCoreCodecConfig().codec_frames_blocks_per_sdu.value_or(0); } return 0; } /* Note: this should be used for tests only */ - const std::vector& GetBisCodecConfigs() - const { + const std::vector& GetBisCodecConfigs() const { return bis_codec_configs_; } - std::optional GetBisCodecSpecData( - uint8_t bis_idx, uint8_t bis_config_idx) const { - if (bis_codec_configs_.empty()) return std::nullopt; - log::assert_that(bis_config_idx < bis_codec_configs_.size(), - "Invalid bis config index"); + std::optional GetBisCodecSpecData(uint8_t bis_idx, + uint8_t bis_config_idx) const { + if (bis_codec_configs_.empty()) { + return std::nullopt; + } + log::assert_that(bis_config_idx < bis_codec_configs_.size(), "Invalid bis config index"); auto config = bis_codec_configs_.at(bis_config_idx); if ((bis_idx != 0) && (bis_idx < bis_codec_configs_.size())) { config = bis_codec_configs_.at(bis_idx); @@ -276,10 +260,9 @@ struct BroadcastSubgroupCodecConfig { size_t GetAllBisConfigCount() const { return bis_codec_configs_.size(); } friend std::ostream& operator<<( - std::ostream& os, - const le_audio::broadcaster::BroadcastSubgroupCodecConfig& config); + std::ostream& os, const le_audio::broadcaster::BroadcastSubgroupCodecConfig& config); - private: +private: types::LeAudioCodecId codec_id_; /* A list of distinct BIS configurations - each config can be allied to * num_bis number of BISes @@ -294,13 +277,11 @@ struct BroadcastSubgroupCodecConfig { }; std::ostream& operator<<( - std::ostream& os, - const bluetooth::le_audio::broadcaster::BroadcastSubgroupCodecConfig& - config); + std::ostream& os, + const bluetooth::le_audio::broadcaster::BroadcastSubgroupCodecConfig& config); struct BroadcastQosConfig { - BroadcastQosConfig(uint8_t retransmission_number, - uint16_t max_transport_latency) + BroadcastQosConfig(uint8_t retransmission_number, uint16_t max_transport_latency) : retransmission_number_(retransmission_number), max_transport_latency_(max_transport_latency) {} @@ -309,33 +290,35 @@ struct BroadcastQosConfig { (max_transport_latency_ == other.max_transport_latency_); } - bool operator!=(const BroadcastQosConfig& other) const { - return !(*this == other); - } + bool operator!=(const BroadcastQosConfig& other) const { return !(*this == other); } uint8_t getRetransmissionNumber() const { return retransmission_number_; } uint16_t getMaxTransportLatency() const { return max_transport_latency_; } - private: +private: uint8_t retransmission_number_; uint16_t max_transport_latency_; }; -std::ostream& operator<<( - std::ostream& os, - const bluetooth::le_audio::broadcaster::BroadcastQosConfig& config); +std::ostream& operator<<(std::ostream& os, + const bluetooth::le_audio::broadcaster::BroadcastQosConfig& config); struct BroadcastConfiguration { bool operator==(const BroadcastConfiguration& other) const { - if ((sduIntervalUs != other.sduIntervalUs) || - (maxSduOctets != other.maxSduOctets) || (phy != other.phy) || - (packing != other.packing) || (framing != other.framing)) { + if ((sduIntervalUs != other.sduIntervalUs) || (maxSduOctets != other.maxSduOctets) || + (phy != other.phy) || (packing != other.packing) || (framing != other.framing)) { return false; } - if (qos != other.qos) return false; - if (data_path != other.data_path) return false; - if (subgroups.size() != other.subgroups.size()) return false; + if (qos != other.qos) { + return false; + } + if (data_path != other.data_path) { + return false; + } + if (subgroups.size() != other.subgroups.size()) { + return false; + } for (auto const& subgroup : subgroups) { if (std::find(other.subgroups.begin(), other.subgroups.end(), subgroup) == @@ -347,9 +330,7 @@ struct BroadcastConfiguration { return true; } - bool operator!=(const BroadcastConfiguration& other) const { - return !(*this == other); - } + bool operator!=(const BroadcastConfiguration& other) const { return !(*this == other); } uint8_t GetNumBisTotal() const { auto count = 0; @@ -363,7 +344,9 @@ struct BroadcastConfiguration { uint8_t GetNumChannelsMax() const { uint8_t value = 0; for (auto const& cfg : subgroups) { - if (cfg.GetNumChannelsTotal() > value) value = cfg.GetNumChannelsTotal(); + if (cfg.GetNumChannelsTotal() > value) { + value = cfg.GetNumChannelsTotal(); + } } return value; } @@ -371,8 +354,9 @@ struct BroadcastConfiguration { uint32_t GetSamplingFrequencyHzMax() const { uint32_t value = 0; for (auto const& cfg : subgroups) { - if (cfg.GetSamplingFrequencyHzMax() > value) + if (cfg.GetSamplingFrequencyHzMax() > value) { value = cfg.GetSamplingFrequencyHzMax(); + } } return value; } @@ -395,17 +379,15 @@ struct BroadcastConfiguration { uint8_t framing; }; -std::ostream& operator<<( - std::ostream& os, - const le_audio::broadcaster::BroadcastConfiguration& config); +std::ostream& operator<<(std::ostream& os, + const le_audio::broadcaster::BroadcastConfiguration& config); } // namespace broadcaster } // namespace bluetooth::le_audio /* BroadcastAnnouncements compare helper */ namespace bluetooth::le_audio { -bool operator==(const BasicAudioAnnouncementData& lhs, - const BasicAudioAnnouncementData& rhs); +bool operator==(const BasicAudioAnnouncementData& lhs, const BasicAudioAnnouncementData& rhs); bool operator==(const PublicBroadcastAnnouncementData& lhs, const PublicBroadcastAnnouncementData& rhs); } // namespace bluetooth::le_audio diff --git a/system/bta/le_audio/broadcaster/mock_state_machine.cc b/system/bta/le_audio/broadcaster/mock_state_machine.cc index 5e293e0e550..391786b20b5 100644 --- a/system/bta/le_audio/broadcaster/mock_state_machine.cc +++ b/system/bta/le_audio/broadcaster/mock_state_machine.cc @@ -28,9 +28,9 @@ void BroadcastStateMachine::Initialize(IBroadcastStateMachineCallbacks* cb, } std::unique_ptr BroadcastStateMachine::CreateInstance( - BroadcastStateMachineConfig msg) { - auto instance = std::make_unique( - std::move(msg), callbacks, adv_callbacks); + BroadcastStateMachineConfig msg) { + auto instance = + std::make_unique(std::move(msg), callbacks, adv_callbacks); MockBroadcastStateMachine::last_instance_ = instance.get(); return std::move(instance); } @@ -38,35 +38,25 @@ std::unique_ptr BroadcastStateMachine::CreateInstance( namespace bluetooth::le_audio { namespace broadcaster { -std::ostream& operator<<(std::ostream& os, - const BroadcastStateMachine::Message& state) { - static const char* char_value_[BroadcastStateMachine::MESSAGE_COUNT] = { - "START", "SUSPEND", "STOP"}; +std::ostream& operator<<(std::ostream& os, const BroadcastStateMachine::Message& state) { + static const char* char_value_[BroadcastStateMachine::MESSAGE_COUNT] = {"START", "SUSPEND", + "STOP"}; os << char_value_[static_cast(state)]; return os; } -std::ostream& operator<<(std::ostream& os, - const BroadcastStateMachine::State& state) { +std::ostream& operator<<(std::ostream& os, const BroadcastStateMachine::State& state) { static const char* char_value_[BroadcastStateMachine::STATE_COUNT] = { - "STOPPED", "CONFIGURING", "CONFIGURED", "STOPPING", "STREAMING"}; + "STOPPED", "CONFIGURING", "CONFIGURED", "STOPPING", "STREAMING"}; os << char_value_[static_cast(state)]; return os; } -std::ostream& operator<<(std::ostream& os, const BigConfig& config) { - return os; -} +std::ostream& operator<<(std::ostream& os, const BigConfig& config) { return os; } -std::ostream& operator<<(std::ostream& os, - const BroadcastStateMachineConfig& config) { - return os; -} +std::ostream& operator<<(std::ostream& os, const BroadcastStateMachineConfig& config) { return os; } -std::ostream& operator<<(std::ostream& os, - const BroadcastStateMachine& machine) { - return os; -} +std::ostream& operator<<(std::ostream& os, const BroadcastStateMachine& machine) { return os; } } // namespace broadcaster } // namespace bluetooth::le_audio diff --git a/system/bta/le_audio/broadcaster/mock_state_machine.h b/system/bta/le_audio/broadcaster/mock_state_machine.h index 8c46b8fafdb..f0445fb27ac 100644 --- a/system/bta/le_audio/broadcaster/mock_state_machine.h +++ b/system/bta/le_audio/broadcaster/mock_state_machine.h @@ -21,13 +21,11 @@ #include "state_machine.h" -class MockBroadcastStateMachine - : public bluetooth::le_audio::broadcaster::BroadcastStateMachine { - public: - MockBroadcastStateMachine( - bluetooth::le_audio::broadcaster::BroadcastStateMachineConfig cfg, - bluetooth::le_audio::broadcaster::IBroadcastStateMachineCallbacks* cb, - AdvertisingCallbacks* adv_cb) +class MockBroadcastStateMachine : public bluetooth::le_audio::broadcaster::BroadcastStateMachine { +public: + MockBroadcastStateMachine(bluetooth::le_audio::broadcaster::BroadcastStateMachineConfig cfg, + bluetooth::le_audio::broadcaster::IBroadcastStateMachineCallbacks* cb, + AdvertisingCallbacks* adv_cb) : cfg(cfg), cb(cb), adv_cb(adv_cb) { advertising_sid_ = ++instance_counter_; @@ -37,34 +35,34 @@ class MockBroadcastStateMachine }); ON_CALL(*this, ProcessMessage) - .WillByDefault( - [this]( - bluetooth::le_audio::broadcaster::BroadcastStateMachine::Message - event, - const void* data) { - const void* sent_data = nullptr; - switch (event) { - case Message::START: - if (GetState() != State::STREAMING && result_) { - SetState(State::STREAMING); - this->cb->OnStateMachineEvent(this->cfg.broadcast_id, GetState(), - &this->cfg.config.subgroups); - } - break; - case Message::STOP: - if (GetState() != State::STOPPED && result_) { - SetState(State::STOPPED); - this->cb->OnStateMachineEvent(this->cfg.broadcast_id, GetState(), nullptr); - } - break; - case Message::SUSPEND: - if (GetState() != State::CONFIGURED && result_) { - SetState(State::CONFIGURED); - this->cb->OnStateMachineEvent(this->cfg.broadcast_id, GetState(), nullptr); - } - break; - }; - }); + .WillByDefault( + [this](bluetooth::le_audio::broadcaster::BroadcastStateMachine::Message event, + const void* data) { + const void* sent_data = nullptr; + switch (event) { + case Message::START: + if (GetState() != State::STREAMING && result_) { + SetState(State::STREAMING); + this->cb->OnStateMachineEvent(this->cfg.broadcast_id, GetState(), + &this->cfg.config.subgroups); + } + break; + case Message::STOP: + if (GetState() != State::STOPPED && result_) { + SetState(State::STOPPED); + this->cb->OnStateMachineEvent(this->cfg.broadcast_id, GetState(), + nullptr); + } + break; + case Message::SUSPEND: + if (GetState() != State::CONFIGURED && result_) { + SetState(State::CONFIGURED); + this->cb->OnStateMachineEvent(this->cfg.broadcast_id, GetState(), + nullptr); + } + break; + }; + }); ON_CALL(*this, GetBigConfig).WillByDefault(testing::ReturnRef(big_config_)); @@ -73,26 +71,23 @@ class MockBroadcastStateMachine }); ON_CALL(*this, GetCodecConfig()) - .WillByDefault( - [this]() -> const std::vector& { + .WillByDefault([this]() -> const std::vector& { return this->cfg.config.subgroups; }); ON_CALL(*this, GetBroadcastConfig()) - .WillByDefault( - [this]() -> const bluetooth::le_audio::broadcaster:: - BroadcastConfiguration& { return this->cfg.config; }); - - ON_CALL(*this, GetBroadcastId()) - .WillByDefault([this]() -> bluetooth::le_audio::BroadcastId { - return this->cfg.broadcast_id; - }); + .WillByDefault( + [this]() -> const bluetooth::le_audio::broadcaster::BroadcastConfiguration& { + return this->cfg.config; + }); - ON_CALL(*this, GetOwnAddress()).WillByDefault([this]() -> RawAddress { - return this->addr_; + ON_CALL(*this, GetBroadcastId()).WillByDefault([this]() -> bluetooth::le_audio::BroadcastId { + return this->cfg.broadcast_id; }); + ON_CALL(*this, GetOwnAddress()).WillByDefault([this]() -> RawAddress { return this->addr_; }); + ON_CALL(*this, GetOwnAddressType()).WillByDefault([this]() -> uint8_t { return this->addr_type_; }); @@ -110,84 +105,65 @@ class MockBroadcastStateMachine }); ON_CALL(*this, GetPublicBroadcastAnnouncement()) - .WillByDefault( - [this]() -> bluetooth::le_audio::PublicBroadcastAnnouncementData& { + .WillByDefault([this]() -> bluetooth::le_audio::PublicBroadcastAnnouncementData& { return this->cfg.public_announcement; }); - }; - - ~MockBroadcastStateMachine() { - cb->OnStateMachineDestroyed(this->cfg.broadcast_id); } + ~MockBroadcastStateMachine() { cb->OnStateMachineDestroyed(this->cfg.broadcast_id); } + MOCK_METHOD((bool), Initialize, (), (override)); - MOCK_METHOD( - (const std::vector< - bluetooth::le_audio::broadcaster::BroadcastSubgroupCodecConfig>&), - GetCodecConfig, (), (const override)); - MOCK_METHOD( - (std::optional const&), - GetBigConfig, (), (const override)); - MOCK_METHOD( - (bluetooth::le_audio::broadcaster::BroadcastStateMachineConfig const&), - GetStateMachineConfig, (), (const override)); - MOCK_METHOD( - (void), RequestOwnAddress, - (base::Callback - cb), - (override)); - MOCK_METHOD((const bluetooth::le_audio::broadcaster::BroadcastConfiguration&), - GetBroadcastConfig, (), (const override)); + MOCK_METHOD((const std::vector&), + GetCodecConfig, (), (const override)); + MOCK_METHOD((std::optional const&), GetBigConfig, (), + (const override)); + MOCK_METHOD((bluetooth::le_audio::broadcaster::BroadcastStateMachineConfig const&), + GetStateMachineConfig, (), (const override)); + MOCK_METHOD((void), RequestOwnAddress, + (base::Callback cb), + (override)); + MOCK_METHOD((const bluetooth::le_audio::broadcaster::BroadcastConfiguration&), GetBroadcastConfig, + (), (const override)); MOCK_METHOD((void), RequestOwnAddress, (), (override)); MOCK_METHOD((RawAddress), GetOwnAddress, (), (override)); MOCK_METHOD((uint8_t), GetOwnAddressType, (), (override)); - MOCK_METHOD((std::optional), - GetBroadcastCode, (), (const override)); - MOCK_METHOD((bluetooth::le_audio::BroadcastId), GetBroadcastId, (), + MOCK_METHOD((std::optional), GetBroadcastCode, (), (const override)); + MOCK_METHOD((bluetooth::le_audio::BroadcastId), GetBroadcastId, (), (const override)); MOCK_METHOD((bool), IsPublicBroadcast, (), (override)); MOCK_METHOD((std::string), GetBroadcastName, (), (override)); - MOCK_METHOD((bluetooth::le_audio::BasicAudioAnnouncementData&), - GetBroadcastAnnouncement, (), (const override)); + MOCK_METHOD((bluetooth::le_audio::BasicAudioAnnouncementData&), GetBroadcastAnnouncement, (), + (const override)); MOCK_METHOD((bluetooth::le_audio::PublicBroadcastAnnouncementData&), GetPublicBroadcastAnnouncement, (), (const override)); MOCK_METHOD((void), UpdateBroadcastAnnouncement, - (bluetooth::le_audio::BasicAudioAnnouncementData announcement), - (override)); + (bluetooth::le_audio::BasicAudioAnnouncementData announcement), (override)); MOCK_METHOD((void), UpdatePublicBroadcastAnnouncement, (uint32_t broadcast_id, const std::string& broadcast_name, - const bluetooth::le_audio::PublicBroadcastAnnouncementData& - announcement), + const bluetooth::le_audio::PublicBroadcastAnnouncementData& announcement), (override)); MOCK_METHOD((uint8_t), GetPaInterval, (), (const override)); MOCK_METHOD((void), HandleHciEvent, (uint16_t event, void* data), (override)); - MOCK_METHOD((void), OnSetupIsoDataPath, - (uint8_t status, uint16_t conn_handle), (override)); - MOCK_METHOD((void), OnRemoveIsoDataPath, - (uint8_t status, uint16_t conn_handle), (override)); - MOCK_METHOD( - (void), ProcessMessage, - (bluetooth::le_audio::broadcaster::BroadcastStateMachine::Message event, - const void* data), - (override)); + MOCK_METHOD((void), OnSetupIsoDataPath, (uint8_t status, uint16_t conn_handle), (override)); + MOCK_METHOD((void), OnRemoveIsoDataPath, (uint8_t status, uint16_t conn_handle), (override)); + MOCK_METHOD((void), ProcessMessage, + (bluetooth::le_audio::broadcaster::BroadcastStateMachine::Message event, + const void* data), + (override)); MOCK_METHOD((uint8_t), GetAdvertisingSid, (), (const override)); MOCK_METHOD((void), OnCreateAnnouncement, - (uint8_t advertising_sid, int8_t tx_power, uint8_t status), - (override)); - MOCK_METHOD((void), OnEnableAnnouncement, (bool enable, uint8_t status), - (override)); + (uint8_t advertising_sid, int8_t tx_power, uint8_t status), (override)); + MOCK_METHOD((void), OnEnableAnnouncement, (bool enable, uint8_t status), (override)); MOCK_METHOD((void), OnUpdateAnnouncement, (uint8_t status), (override)); bool result_ = true; - std::optional big_config_ = - std::nullopt; + std::optional big_config_ = std::nullopt; bluetooth::le_audio::broadcaster::BroadcastStateMachineConfig cfg; bluetooth::le_audio::broadcaster::IBroadcastStateMachineCallbacks* cb; AdvertisingCallbacks* adv_cb; void SetExpectedState(BroadcastStateMachine::State state) { SetState(state); } void SetExpectedResult(bool result) { result_ = result; } - void SetExpectedBigConfig( - std::optional big_cfg) { + void SetExpectedBigConfig(std::optional big_cfg) { big_config_ = big_cfg; } diff --git a/system/bta/le_audio/broadcaster/state_machine.cc b/system/bta/le_audio/broadcaster/state_machine.cc index 1cfad7f4e9c..82ed556da7d 100644 --- a/system/bta/le_audio/broadcaster/state_machine.cc +++ b/system/bta/le_audio/broadcaster/state_machine.cc @@ -53,19 +53,21 @@ const int kAdvertisingChannel37 = (1 << 0); const int kAdvertisingChannel38 = (1 << 1); const int kAdvertisingChannel39 = (1 << 2); const int kAdvertisingChannelAll = - (kAdvertisingChannel37 | kAdvertisingChannel38 | kAdvertisingChannel39); + (kAdvertisingChannel37 | kAdvertisingChannel38 | kAdvertisingChannel39); class BroadcastStateMachineImpl : public BroadcastStateMachine { - public: +public: BroadcastStateMachineImpl(BroadcastStateMachineConfig msg) - : active_config_(std::nullopt), - sm_config_(std::move(msg)), - suspending_(false) {} + : active_config_(std::nullopt), sm_config_(std::move(msg)), suspending_(false) {} ~BroadcastStateMachineImpl() { - if (GetState() == State::STREAMING) TerminateBig(); + if (GetState() == State::STREAMING) { + TerminateBig(); + } DestroyBroadcastAnnouncement(); - if (callbacks_) callbacks_->OnStateMachineDestroyed(GetBroadcastId()); + if (callbacks_) { + callbacks_->OnStateMachineDestroyed(GetBroadcastId()); + } } bool Initialize() override { @@ -73,48 +75,38 @@ class BroadcastStateMachineImpl : public BroadcastStateMachine { if (sm_config_.config.GetNumBisTotal() > sNumBisMax) { log::error( - "Channel count of {} exceeds the maximum number of possible BISes, " - "which is {}", - sm_config_.config.GetNumBisTotal(), sNumBisMax); + "Channel count of {} exceeds the maximum number of possible BISes, " + "which is {}", + sm_config_.config.GetNumBisTotal(), sNumBisMax); return false; } - CreateBroadcastAnnouncement( - sm_config_.is_public, sm_config_.broadcast_name, - sm_config_.broadcast_id, sm_config_.public_announcement, - sm_config_.announcement, sm_config_.streaming_phy); + CreateBroadcastAnnouncement(sm_config_.is_public, sm_config_.broadcast_name, + sm_config_.broadcast_id, sm_config_.public_announcement, + sm_config_.announcement, sm_config_.streaming_phy); return true; } - const std::vector& GetCodecConfig() - const override { + const std::vector& GetCodecConfig() const override { return sm_config_.config.subgroups; } - const BroadcastConfiguration& GetBroadcastConfig() const override { - return sm_config_.config; - } + const BroadcastConfiguration& GetBroadcastConfig() const override { return sm_config_.config; } - std::optional const& GetBigConfig() const override { - return active_config_; - } + std::optional const& GetBigConfig() const override { return active_config_; } - BroadcastStateMachineConfig const& GetStateMachineConfig() const override { - return sm_config_; - } + BroadcastStateMachineConfig const& GetStateMachineConfig() const override { return sm_config_; } void RequestOwnAddress( - base::Callback - cb) override { + base::Callback cb) override { uint8_t advertising_sid = GetAdvertisingSid(); advertiser_if_->GetOwnAddress(advertising_sid, cb); } void RequestOwnAddress(void) override { auto broadcast_id = GetBroadcastId(); - RequestOwnAddress( - base::Bind(&IBroadcastStateMachineCallbacks::OnOwnAddressResponse, - base::Unretained(this->callbacks_), broadcast_id)); + RequestOwnAddress(base::Bind(&IBroadcastStateMachineCallbacks::OnOwnAddressResponse, + base::Unretained(this->callbacks_), broadcast_id)); } RawAddress GetOwnAddress() override { return addr_; } @@ -125,13 +117,11 @@ class BroadcastStateMachineImpl : public BroadcastStateMachine { return sm_config_.broadcast_id; } - std::optional GetBroadcastCode() - const override { + std::optional GetBroadcastCode() const override { return sm_config_.broadcast_code; } - const bluetooth::le_audio::BasicAudioAnnouncementData& - GetBroadcastAnnouncement() const override { + const bluetooth::le_audio::BasicAudioAnnouncementData& GetBroadcastAnnouncement() const override { return sm_config_.announcement; } @@ -139,40 +129,35 @@ class BroadcastStateMachineImpl : public BroadcastStateMachine { std::string GetBroadcastName() override { return sm_config_.broadcast_name; } - const bluetooth::le_audio::PublicBroadcastAnnouncementData& - GetPublicBroadcastAnnouncement() const override { + const bluetooth::le_audio::PublicBroadcastAnnouncementData& GetPublicBroadcastAnnouncement() + const override { return sm_config_.public_announcement; } - void OnCreateAnnouncement(uint8_t advertising_sid, int8_t tx_power, - uint8_t status) { - log::info("advertising_sid={} tx_power={} status={}", advertising_sid, - tx_power, status); + void OnCreateAnnouncement(uint8_t advertising_sid, int8_t tx_power, uint8_t status) { + log::info("advertising_sid={} tx_power={} status={}", advertising_sid, tx_power, status); /* If this callback gets called the advertising_sid is valid even though the * status can be other than SUCCESS. */ advertising_sid_ = advertising_sid; - if (status != - bluetooth::hci::AdvertisingCallback::AdvertisingStatus::SUCCESS) { + if (status != bluetooth::hci::AdvertisingCallback::AdvertisingStatus::SUCCESS) { log::error("Creating Announcement failed"); callbacks_->OnStateMachineCreateStatus(GetBroadcastId(), false); return; } advertiser_if_->GetOwnAddress( - advertising_sid, - base::Bind(&BroadcastStateMachineImpl::OnAddressResponse, - base::Unretained(this))); + advertising_sid, + base::Bind(&BroadcastStateMachineImpl::OnAddressResponse, base::Unretained(this))); } void OnEnableAnnouncement(bool enable, uint8_t status) { - log::info("operation={}, broadcast_id={}, status={}", - enable ? "enable" : "disable", GetBroadcastId(), status); + log::info("operation={}, broadcast_id={}, status={}", enable ? "enable" : "disable", + GetBroadcastId(), status); - if (status == - bluetooth::hci::AdvertisingCallback::AdvertisingStatus::SUCCESS) { + if (status == bluetooth::hci::AdvertisingCallback::AdvertisingStatus::SUCCESS) { /* Periodic is enabled but without BIGInfo. Stream is suspended. */ if (enable) { SetState(State::CONFIGURED); @@ -199,8 +184,7 @@ class BroadcastStateMachineImpl : public BroadcastStateMachine { void OnUpdateAnnouncement(uint8_t status) { log::info("broadcast_id={}, status={}", GetBroadcastId(), status); - if (status == - bluetooth::hci::AdvertisingCallback::AdvertisingStatus::SUCCESS) { + if (status == bluetooth::hci::AdvertisingCallback::AdvertisingStatus::SUCCESS) { callbacks_->OnAnnouncementUpdated(GetBroadcastId()); } else { log::error("Updating Announcement failed"); @@ -208,32 +192,28 @@ class BroadcastStateMachineImpl : public BroadcastStateMachine { } void UpdatePublicBroadcastAnnouncement( - uint32_t broadcast_id, const std::string& broadcast_name, - const bluetooth::le_audio::PublicBroadcastAnnouncementData& announcement) - override { + uint32_t broadcast_id, const std::string& broadcast_name, + const bluetooth::le_audio::PublicBroadcastAnnouncementData& announcement) override { std::vector adv_data; - PrepareAdvertisingData(true, broadcast_name, broadcast_id, announcement, - adv_data); + PrepareAdvertisingData(true, broadcast_name, broadcast_id, announcement, adv_data); sm_config_.broadcast_name = broadcast_name; sm_config_.public_announcement = announcement; - advertiser_if_->SetData(advertising_sid_, false, adv_data, - base::DoNothing()); + advertiser_if_->SetData(advertising_sid_, false, adv_data, base::DoNothing()); } void UpdateBroadcastAnnouncement( - bluetooth::le_audio::BasicAudioAnnouncementData announcement) override { + bluetooth::le_audio::BasicAudioAnnouncementData announcement) override { std::vector periodic_data; PreparePeriodicData(announcement, periodic_data); sm_config_.announcement = std::move(announcement); - advertiser_if_->SetPeriodicAdvertisingData(advertising_sid_, periodic_data, - base::DoNothing()); + advertiser_if_->SetPeriodicAdvertisingData(advertising_sid_, periodic_data, base::DoNothing()); } void ProcessMessage(Message msg, const void* data = nullptr) override { - log::info("broadcast_id={}, state={}, message={}", GetBroadcastId(), - ToString(GetState()), ToString(msg)); + log::info("broadcast_id={}, state={}, message={}", GetBroadcastId(), ToString(GetState()), + ToString(msg)); switch (msg) { case Message::START: start_msg_handlers[StateMachine::GetState()](data); @@ -250,15 +230,14 @@ class BroadcastStateMachineImpl : public BroadcastStateMachine { static IBroadcastStateMachineCallbacks* callbacks_; static BleAdvertiserInterface* advertiser_if_; - private: +private: std::optional active_config_; BroadcastStateMachineConfig sm_config_; bool suspending_; /* Message handlers for each possible state */ typedef std::function msg_handler_t; - const std::array - start_msg_handlers{ + const std::array start_msg_handlers{ /* in STOPPED state */ [this](const void*) { SetState(State::CONFIGURING); @@ -274,8 +253,7 @@ class BroadcastStateMachineImpl : public BroadcastStateMachine { /* in STREAMING state */ [](const void*) { /* Do nothing */ }}; - const std::array - stop_msg_handlers{ + const std::array stop_msg_handlers{ /* in STOPPED state */ [](const void*) { /* Already stopped */ }, /* in CONFIGURING state */ @@ -298,8 +276,7 @@ class BroadcastStateMachineImpl : public BroadcastStateMachine { } }}; - const std::array - suspend_msg_handlers{ + const std::array suspend_msg_handlers{ /* in STOPPED state */ [](const void*) { /* Do nothing */ }, /* in CONFIGURING state */ @@ -316,17 +293,17 @@ class BroadcastStateMachineImpl : public BroadcastStateMachine { } }}; - const std::array - resume_msg_handlers{/* in STOPPED state */ - [](const void*) { /* Do nothing */ }, - /* in CONFIGURING state */ - [](const void*) { /* Do nothing */ }, - /* in CONFIGURED state */ - [this](const void*) { CreateBig(); }, - /* in STOPPING state */ - [](const void*) { /* Do nothing */ }, - /* in STREAMING state */ - [](const void*) { /* Already streaming */ }}; + const std::array resume_msg_handlers{ + /* in STOPPED state */ + [](const void*) { /* Do nothing */ }, + /* in CONFIGURING state */ + [](const void*) { /* Do nothing */ }, + /* in CONFIGURED state */ + [this](const void*) { CreateBig(); }, + /* in STOPPING state */ + [](const void*) { /* Do nothing */ }, + /* in STREAMING state */ + [](const void*) { /* Already streaming */ }}; void OnAddressResponse(uint8_t addr_type, RawAddress addr) { log::info("own address={}, type={}", addr, addr_type); @@ -341,23 +318,21 @@ class BroadcastStateMachineImpl : public BroadcastStateMachine { } void CreateBroadcastAnnouncement( - bool is_public, const std::string& broadcast_name, - bluetooth::le_audio::BroadcastId& broadcast_id, - const bluetooth::le_audio::PublicBroadcastAnnouncementData& - public_announcement, - const bluetooth::le_audio::BasicAudioAnnouncementData& announcement, - uint8_t streaming_phy) { + bool is_public, const std::string& broadcast_name, + bluetooth::le_audio::BroadcastId& broadcast_id, + const bluetooth::le_audio::PublicBroadcastAnnouncementData& public_announcement, + const bluetooth::le_audio::BasicAudioAnnouncementData& announcement, + uint8_t streaming_phy) { log::info("is_public={}, broadcast_name={}, public_features={}", - is_public ? "public" : "non-public", broadcast_name, - public_announcement.features); + is_public ? "public" : "non-public", broadcast_name, public_announcement.features); if (advertiser_if_ != nullptr) { AdvertiseParameters adv_params; PeriodicAdvertisingParameters periodic_params; std::vector adv_data; std::vector periodic_data; - PrepareAdvertisingData(is_public, broadcast_name, broadcast_id, - public_announcement, adv_data); + PrepareAdvertisingData(is_public, broadcast_name, broadcast_id, public_announcement, + adv_data); PreparePeriodicData(announcement, periodic_data); adv_params.min_interval = 0x00A0; /* 160 * 0,625 = 100ms */ @@ -380,16 +355,13 @@ class BroadcastStateMachineImpl : public BroadcastStateMachine { * command. */ advertiser_if_->StartAdvertisingSet( - kAdvertiserClientIdLeAudio, kLeAudioBroadcastRegId, base::DoNothing(), - adv_params, adv_data, std::vector(), periodic_params, - periodic_data, 0 /* duration */, 0 /* maxExtAdvEvents */, - base::DoNothing()); + kAdvertiserClientIdLeAudio, kLeAudioBroadcastRegId, base::DoNothing(), adv_params, + adv_data, std::vector(), periodic_params, periodic_data, 0 /* duration */, + 0 /* maxExtAdvEvents */, base::DoNothing()); } } - void DestroyBroadcastAnnouncement() { - advertiser_if_->Unregister(GetAdvertisingSid()); - } + void DestroyBroadcastAnnouncement() { advertiser_if_->Unregister(GetAdvertisingSid()); } void EnableAnnouncement() { log::info("broadcast_id={}", GetBroadcastId()); @@ -403,29 +375,27 @@ class BroadcastStateMachineImpl : public BroadcastStateMachine { log::info("broadcast_id={}", GetBroadcastId()); /* TODO: Figure out how to decide on the currently hard-codded params. */ struct bluetooth::hci::iso_manager::big_create_params big_params = { - .adv_handle = GetAdvertisingSid(), - .num_bis = sm_config_.config.GetNumBisTotal(), - .sdu_itv = sm_config_.config.GetSduIntervalUs(), - .max_sdu_size = sm_config_.config.GetMaxSduOctets(), - .max_transport_latency = sm_config_.config.qos.getMaxTransportLatency(), - .rtn = sm_config_.config.qos.getRetransmissionNumber(), - .phy = sm_config_.streaming_phy, - .packing = 0x00, /* Sequencial */ - .framing = 0x00, /* Unframed */ - .enc = static_cast(sm_config_.broadcast_code ? 1 : 0), - .enc_code = sm_config_.broadcast_code ? *sm_config_.broadcast_code - : std::array({0}), + .adv_handle = GetAdvertisingSid(), + .num_bis = sm_config_.config.GetNumBisTotal(), + .sdu_itv = sm_config_.config.GetSduIntervalUs(), + .max_sdu_size = sm_config_.config.GetMaxSduOctets(), + .max_transport_latency = sm_config_.config.qos.getMaxTransportLatency(), + .rtn = sm_config_.config.qos.getRetransmissionNumber(), + .phy = sm_config_.streaming_phy, + .packing = 0x00, /* Sequencial */ + .framing = 0x00, /* Unframed */ + .enc = static_cast(sm_config_.broadcast_code ? 1 : 0), + .enc_code = sm_config_.broadcast_code ? *sm_config_.broadcast_code + : std::array({0}), }; - IsoManager::GetInstance()->CreateBig(GetAdvertisingSid(), - std::move(big_params)); + IsoManager::GetInstance()->CreateBig(GetAdvertisingSid(), std::move(big_params)); } void DisableAnnouncement(void) { log::info("broadcast_id={}", GetBroadcastId()); // Callback is handled by OnAdvertisingEnabled() which returns the status - advertiser_if_->Enable(GetAdvertisingSid(), false, base::DoNothing(), 0, 0, - base::DoNothing()); + advertiser_if_->Enable(GetAdvertisingSid(), false, base::DoNothing(), 0, 0, base::DoNothing()); } void TerminateBig() { @@ -446,13 +416,11 @@ class BroadcastStateMachineImpl : public BroadcastStateMachine { } /* Look for the next BIS handle */ - auto handle_it = std::find_if( - active_config_->connection_handles.begin(), - active_config_->connection_handles.end(), - [conn_hdl](const auto& handle) { return conn_hdl == handle; }); - log::assert_that( - handle_it != active_config_->connection_handles.end(), - "assert failed: handle_it != active_config_->connection_handles.end()"); + auto handle_it = std::find_if(active_config_->connection_handles.begin(), + active_config_->connection_handles.end(), + [conn_hdl](const auto& handle) { return conn_hdl == handle; }); + log::assert_that(handle_it != active_config_->connection_handles.end(), + "assert failed: handle_it != active_config_->connection_handles.end()"); handle_it = std::next(handle_it); if (handle_it == active_config_->connection_handles.end()) { @@ -479,12 +447,10 @@ class BroadcastStateMachineImpl : public BroadcastStateMachine { /* Look for the next BIS handle */ auto handle_it = std::find_if( - active_config_->connection_handles.begin(), - active_config_->connection_handles.end(), - [conn_handle](const auto& handle) { return conn_handle == handle; }); - log::assert_that( - handle_it != active_config_->connection_handles.end(), - "assert failed: handle_it != active_config_->connection_handles.end()"); + active_config_->connection_handles.begin(), active_config_->connection_handles.end(), + [conn_handle](const auto& handle) { return conn_handle == handle; }); + log::assert_that(handle_it != active_config_->connection_handles.end(), + "assert failed: handle_it != active_config_->connection_handles.end()"); handle_it = std::next(handle_it); if (handle_it == active_config_->connection_handles.end()) { @@ -508,23 +474,21 @@ class BroadcastStateMachineImpl : public BroadcastStateMachine { */ auto& iso_datapath_config = sm_config_.config.data_path.isoDataPathConfig; bluetooth::hci::iso_manager::iso_data_path_params param = { - .data_path_dir = bluetooth::hci::iso_manager::kIsoDataPathDirectionIn, - .data_path_id = - static_cast(sm_config_.config.data_path.dataPathId), - .codec_id_format = static_cast( - iso_datapath_config.isTransparent - ? bluetooth::hci::kIsoCodingFormatTransparent - : iso_datapath_config.codecId.coding_format), - .codec_id_company = static_cast( - iso_datapath_config.isTransparent - ? 0x0000 - : iso_datapath_config.codecId.vendor_company_id), - .codec_id_vendor = static_cast( - iso_datapath_config.isTransparent - ? 0x0000 - : iso_datapath_config.codecId.vendor_codec_id), - .controller_delay = iso_datapath_config.controllerDelayUs, - .codec_conf = iso_datapath_config.configuration, + .data_path_dir = bluetooth::hci::iso_manager::kIsoDataPathDirectionIn, + .data_path_id = static_cast(sm_config_.config.data_path.dataPathId), + .codec_id_format = static_cast( + iso_datapath_config.isTransparent ? bluetooth::hci::kIsoCodingFormatTransparent + : iso_datapath_config.codecId.coding_format), + .codec_id_company = + static_cast(iso_datapath_config.isTransparent + ? 0x0000 + : iso_datapath_config.codecId.vendor_company_id), + .codec_id_vendor = + static_cast(iso_datapath_config.isTransparent + ? 0x0000 + : iso_datapath_config.codecId.vendor_codec_id), + .controller_delay = iso_datapath_config.controllerDelayUs, + .codec_conf = iso_datapath_config.configuration, }; IsoManager::GetInstance()->SetupIsoDataPath(conn_handle, std::move(param)); } @@ -536,8 +500,7 @@ class BroadcastStateMachineImpl : public BroadcastStateMachine { SetMuted(true); IsoManager::GetInstance()->RemoveIsoDataPath( - conn_handle, - bluetooth::hci::iso_manager::kRemoveIsoDataPathDirectionInput); + conn_handle, bluetooth::hci::iso_manager::kRemoveIsoDataPathDirectionInput); } void HandleHciEvent(uint16_t event, void* data) override { @@ -546,44 +509,42 @@ class BroadcastStateMachineImpl : public BroadcastStateMachine { auto* evt = static_cast(data); if (evt->big_id != GetAdvertisingSid()) { - log::error("State={}, Event={}, Unknown big, big_id={}", - ToString(GetState()), event, evt->big_id); + log::error("State={}, Event={}, Unknown big, big_id={}", ToString(GetState()), event, + evt->big_id); break; } if (evt->status == 0x00) { log::info("BIG create BIG complete, big_id={}", evt->big_id); active_config_ = { - .status = evt->status, - .big_id = evt->big_id, - .big_sync_delay = evt->big_sync_delay, - .transport_latency_big = evt->transport_latency_big, - .phy = evt->phy, - .nse = evt->nse, - .bn = evt->bn, - .pto = evt->pto, - .irc = evt->irc, - .max_pdu = evt->max_pdu, - .iso_interval = evt->iso_interval, - .connection_handles = evt->conn_handles, + .status = evt->status, + .big_id = evt->big_id, + .big_sync_delay = evt->big_sync_delay, + .transport_latency_big = evt->transport_latency_big, + .phy = evt->phy, + .nse = evt->nse, + .bn = evt->bn, + .pto = evt->pto, + .irc = evt->irc, + .max_pdu = evt->max_pdu, + .iso_interval = evt->iso_interval, + .connection_handles = evt->conn_handles, }; callbacks_->OnBigCreated(evt->conn_handles); TriggerIsoDatapathSetup(evt->conn_handles[0]); } else { - log::error( - "State={} Event={}. Unable to create big, big_id={}, status={}", - ToString(GetState()), event, evt->big_id, evt->status); + log::error("State={} Event={}. Unable to create big, big_id={}, status={}", + ToString(GetState()), event, evt->big_id, evt->status); } } break; case HCI_BLE_TERM_BIG_CPL_EVT: { auto* evt = static_cast(data); - log::info("BIG terminate BIG cmpl, reason={} big_id={}", evt->reason, - evt->big_id); + log::info("BIG terminate BIG cmpl, reason={} big_id={}", evt->reason, evt->big_id); if (evt->big_id != GetAdvertisingSid()) { - log::error("State={} Event={}, unknown adv.sid={}", - ToString(GetState()), event, evt->big_id); + log::error("State={} Event={}, unknown adv.sid={}", ToString(GetState()), event, + evt->big_id); break; } @@ -607,27 +568,24 @@ class BroadcastStateMachineImpl : public BroadcastStateMachine { } }; -IBroadcastStateMachineCallbacks* BroadcastStateMachineImpl::callbacks_ = - nullptr; +IBroadcastStateMachineCallbacks* BroadcastStateMachineImpl::callbacks_ = nullptr; BleAdvertiserInterface* BroadcastStateMachineImpl::advertiser_if_ = nullptr; } /* namespace */ std::unique_ptr BroadcastStateMachine::CreateInstance( - BroadcastStateMachineConfig msg) { + BroadcastStateMachineConfig msg) { return std::make_unique(std::move(msg)); } -void BroadcastStateMachine::Initialize( - IBroadcastStateMachineCallbacks* callbacks, - AdvertisingCallbacks* adv_callbacks) { +void BroadcastStateMachine::Initialize(IBroadcastStateMachineCallbacks* callbacks, + AdvertisingCallbacks* adv_callbacks) { BroadcastStateMachineImpl::callbacks_ = callbacks; /* Get gd le advertiser interface */ - BroadcastStateMachineImpl::advertiser_if_ = - bluetooth::shim::get_ble_advertiser_instance(); + BroadcastStateMachineImpl::advertiser_if_ = bluetooth::shim::get_ble_advertiser_instance(); if (BroadcastStateMachineImpl::advertiser_if_ != nullptr) { log::info("Advertiser_instance acquired"); - BroadcastStateMachineImpl::advertiser_if_->RegisterCallbacksNative( - adv_callbacks, kAdvertiserClientIdLeAudio); + BroadcastStateMachineImpl::advertiser_if_->RegisterCallbacksNative(adv_callbacks, + kAdvertiserClientIdLeAudio); } else { log::error("Could not acquire advertiser_instance!"); BroadcastStateMachineImpl::advertiser_if_ = nullptr; @@ -637,25 +595,22 @@ void BroadcastStateMachine::Initialize( namespace bluetooth::le_audio { namespace broadcaster { -std::ostream& operator<<(std::ostream& os, - const BroadcastStateMachine::Message& msg) { - static const char* char_value_[BroadcastStateMachine::MESSAGE_COUNT] = { - "START", "SUSPEND", "STOP"}; +std::ostream& operator<<(std::ostream& os, const BroadcastStateMachine::Message& msg) { + static const char* char_value_[BroadcastStateMachine::MESSAGE_COUNT] = {"START", "SUSPEND", + "STOP"}; os << char_value_[static_cast(msg)]; return os; } -std::ostream& operator<<(std::ostream& os, - const BroadcastStateMachine::State& state) { +std::ostream& operator<<(std::ostream& os, const BroadcastStateMachine::State& state) { static const char* char_value_[BroadcastStateMachine::STATE_COUNT] = { - "STOPPED", "CONFIGURING", "CONFIGURED", "STOPPING", "STREAMING"}; + "STOPPED", "CONFIGURING", "CONFIGURED", "STOPPING", "STREAMING"}; os << char_value_[static_cast(state)]; return os; } -std::ostream& operator<<( - std::ostream& os, - const bluetooth::le_audio::broadcaster::BigConfig& config) { +std::ostream& operator<<(std::ostream& os, + const bluetooth::le_audio::broadcaster::BigConfig& config) { os << "\n"; os << " Status: 0x" << std::hex << +config.status << std::dec << "\n"; os << " BIG ID: " << +config.big_id << "\n"; @@ -677,9 +632,8 @@ std::ostream& operator<<( } std::ostream& operator<<( - std::ostream& os, - const bluetooth::le_audio::broadcaster::BroadcastStateMachineConfig& - config) { + std::ostream& os, + const bluetooth::le_audio::broadcaster::BroadcastStateMachineConfig& config) { const char* const PHYS[] = {"NONE", "1M", "2M", "CODED"}; os << "\n"; @@ -715,14 +669,12 @@ std::ostream& operator<<( return os; } -std::ostream& operator<<( - std::ostream& os, - const bluetooth::le_audio::broadcaster::BroadcastStateMachine& machine) { +std::ostream& operator<<(std::ostream& os, + const bluetooth::le_audio::broadcaster::BroadcastStateMachine& machine) { os << " Broadcast state machine: {" << " Advertising SID: " << +machine.GetAdvertisingSid() << "\n" << " State: " << machine.GetState() << "\n"; - os << " State Machine Config: " << machine.GetStateMachineConfig() - << "\n"; + os << " State Machine Config: " << machine.GetStateMachineConfig() << "\n"; if (machine.GetBigConfig()) { os << " BigConfig: " << *machine.GetBigConfig() << "\n"; diff --git a/system/bta/le_audio/broadcaster/state_machine.h b/system/bta/le_audio/broadcaster/state_machine.h index bd404bc2b2d..72cc349a687 100644 --- a/system/bta/le_audio/broadcaster/state_machine.h +++ b/system/bta/le_audio/broadcaster/state_machine.h @@ -31,16 +31,18 @@ namespace { template class StateMachine { - public: +public: StateMachine() : state_(std::numeric_limits::min()) {} - protected: +protected: StateT GetState() const { return state_; } void SetState(StateT state) { - if (state < S) state_ = state; + if (state < S) { + state_ = state; + } } - private: +private: StateT state_; }; } /* namespace */ @@ -107,7 +109,7 @@ struct BroadcastStateMachineConfig { }; class BroadcastStateMachine : public StateMachine<5> { - public: +public: static constexpr uint8_t kAdvSidUndefined = 0xFF; static constexpr uint8_t kPaIntervalMax = 0xA0; /* 160 * 0.625 = 100ms */ static constexpr uint8_t kPaIntervalMin = 0x50; /* 80 * 0.625 = 50ms */ @@ -120,10 +122,8 @@ class BroadcastStateMachine : public StateMachine<5> { // ADDRESS_TYPE_RANDOM_NON_RESOLVABLE = 2 static constexpr int8_t kBroadcastAdvertisingType = 0x2; - static void Initialize(IBroadcastStateMachineCallbacks*, - AdvertisingCallbacks* adv_callbacks); - static std::unique_ptr CreateInstance( - BroadcastStateMachineConfig msg); + static void Initialize(IBroadcastStateMachineCallbacks*, AdvertisingCallbacks* adv_callbacks); + static std::unique_ptr CreateInstance(BroadcastStateMachineConfig msg); enum class Message : uint8_t { START = 0, @@ -131,7 +131,7 @@ class BroadcastStateMachine : public StateMachine<5> { STOP, }; static const std::underlying_type::type MESSAGE_COUNT = - static_cast::type>(Message::STOP) + 1; + static_cast::type>(Message::STOP) + 1; enum class State : uint8_t { STOPPED = 0, @@ -141,48 +141,41 @@ class BroadcastStateMachine : public StateMachine<5> { STREAMING, }; static const std::underlying_type::type STATE_COUNT = - static_cast::type>(State::STREAMING) + 1; + static_cast::type>(State::STREAMING) + 1; - inline State GetState(void) const { - return static_cast(StateMachine::GetState()); - } + inline State GetState(void) const { return static_cast(StateMachine::GetState()); } virtual uint8_t GetAdvertisingSid() const { return advertising_sid_; } virtual uint8_t GetPaInterval() const { return kPaIntervalMax; } virtual bool Initialize() = 0; - virtual const std::vector& GetCodecConfig() - const = 0; + virtual const std::vector& GetCodecConfig() const = 0; virtual const BroadcastConfiguration& GetBroadcastConfig() const = 0; virtual std::optional const& GetBigConfig() const = 0; virtual BroadcastStateMachineConfig const& GetStateMachineConfig() const = 0; virtual void RequestOwnAddress( - base::Callback - cb) = 0; + base::Callback cb) = 0; virtual void RequestOwnAddress() = 0; virtual RawAddress GetOwnAddress() = 0; virtual uint8_t GetOwnAddressType() = 0; - virtual std::optional GetBroadcastCode() - const = 0; + virtual std::optional GetBroadcastCode() const = 0; virtual bluetooth::le_audio::BroadcastId GetBroadcastId() const = 0; - virtual const bluetooth::le_audio::BasicAudioAnnouncementData& - GetBroadcastAnnouncement() const = 0; + virtual const bluetooth::le_audio::BasicAudioAnnouncementData& GetBroadcastAnnouncement() + const = 0; virtual void UpdateBroadcastAnnouncement( - bluetooth::le_audio::BasicAudioAnnouncementData announcement) = 0; + bluetooth::le_audio::BasicAudioAnnouncementData announcement) = 0; virtual bool IsPublicBroadcast() = 0; virtual std::string GetBroadcastName() = 0; virtual const bluetooth::le_audio::PublicBroadcastAnnouncementData& GetPublicBroadcastAnnouncement() const = 0; virtual void UpdatePublicBroadcastAnnouncement( - uint32_t broadcast_id, const std::string& broadcast_name, - const bluetooth::le_audio::PublicBroadcastAnnouncementData& - announcement) = 0; - virtual void OnCreateAnnouncement(uint8_t advertising_sid, int8_t tx_power, - uint8_t status) = 0; + uint32_t broadcast_id, const std::string& broadcast_name, + const bluetooth::le_audio::PublicBroadcastAnnouncementData& announcement) = 0; + virtual void OnCreateAnnouncement(uint8_t advertising_sid, int8_t tx_power, uint8_t status) = 0; virtual void OnEnableAnnouncement(bool enable, uint8_t status) = 0; virtual void OnUpdateAnnouncement(uint8_t status) = 0; - void SetMuted(bool muted) { is_muted_ = muted; }; - bool IsMuted() const { return is_muted_; }; + void SetMuted(bool muted) { is_muted_ = muted; } + bool IsMuted() const { return is_muted_; } virtual void HandleHciEvent(uint16_t event, void* data) = 0; virtual void OnSetupIsoDataPath(uint8_t status, uint16_t conn_handle) = 0; @@ -191,12 +184,11 @@ class BroadcastStateMachine : public StateMachine<5> { virtual void ProcessMessage(Message event, const void* data = nullptr) = 0; virtual ~BroadcastStateMachine() {} - protected: +protected: BroadcastStateMachine() = default; void SetState(State state) { - StateMachine::SetState( - static_cast::type>(state)); + StateMachine::SetState(static_cast::type>(state)); } uint8_t advertising_sid_ = kAdvSidUndefined; @@ -207,14 +199,12 @@ class BroadcastStateMachine : public StateMachine<5> { }; class IBroadcastStateMachineCallbacks { - public: +public: IBroadcastStateMachineCallbacks() = default; virtual ~IBroadcastStateMachineCallbacks() = default; - virtual void OnStateMachineCreateStatus(uint32_t broadcast_id, - bool initialized) = 0; + virtual void OnStateMachineCreateStatus(uint32_t broadcast_id, bool initialized) = 0; virtual void OnStateMachineDestroyed(uint32_t broadcast_id) = 0; - virtual void OnStateMachineEvent(uint32_t broadcast_id, - BroadcastStateMachine::State state, + virtual void OnStateMachineEvent(uint32_t broadcast_id, BroadcastStateMachine::State state, const void* data = nullptr) = 0; virtual void OnOwnAddressResponse(uint32_t broadcast_id, uint8_t addr_type, RawAddress address) = 0; @@ -223,27 +213,22 @@ class IBroadcastStateMachineCallbacks { }; std::ostream& operator<<( - std::ostream& os, - const bluetooth::le_audio::broadcaster::BroadcastStateMachine::Message& - state); + std::ostream& os, + const bluetooth::le_audio::broadcaster::BroadcastStateMachine::Message& state); std::ostream& operator<<( - std::ostream& os, - const bluetooth::le_audio::broadcaster::BroadcastStateMachine::State& - state); + std::ostream& os, + const bluetooth::le_audio::broadcaster::BroadcastStateMachine::State& state); -std::ostream& operator<<( - std::ostream& os, - const bluetooth::le_audio::broadcaster::BroadcastStateMachine& machine); +std::ostream& operator<<(std::ostream& os, + const bluetooth::le_audio::broadcaster::BroadcastStateMachine& machine); -std::ostream& operator<<( - std::ostream& os, - const bluetooth::le_audio::broadcaster::BigConfig& machine); +std::ostream& operator<<(std::ostream& os, + const bluetooth::le_audio::broadcaster::BigConfig& machine); std::ostream& operator<<( - std::ostream& os, - const bluetooth::le_audio::broadcaster::BroadcastStateMachineConfig& - machine); + std::ostream& os, + const bluetooth::le_audio::broadcaster::BroadcastStateMachineConfig& machine); } /* namespace broadcaster */ } // namespace bluetooth::le_audio diff --git a/system/bta/le_audio/broadcaster/state_machine_test.cc b/system/bta/le_audio/broadcaster/state_machine_test.cc index b3d1e2b5f48..74034322333 100644 --- a/system/bta/le_audio/broadcaster/state_machine_test.cc +++ b/system/bta/le_audio/broadcaster/state_machine_test.cc @@ -45,9 +45,7 @@ using testing::SaveArg; using testing::Test; // Disables most likely false-positives from base::SplitString() -extern "C" const char* __asan_default_options() { - return "detect_container_overflow=0"; -} +extern "C" const char* __asan_default_options() { return "detect_container_overflow=0"; } void btsnd_hcic_ble_rand(base::Callback cb) {} @@ -58,74 +56,56 @@ namespace { static const uint8_t test_public_broadcast_features = 0x3; static const std::string test_broadcast_name = "Test"; static const std::vector default_public_metadata = { - 5, bluetooth::le_audio::types::kLeAudioMetadataTypeProgramInfo, - 0x1, 0x2, - 0x3, 0x4}; + 5, bluetooth::le_audio::types::kLeAudioMetadataTypeProgramInfo, 0x1, 0x2, 0x3, 0x4}; -class MockBroadcastStatMachineCallbacks - : public IBroadcastStateMachineCallbacks { - public: +class MockBroadcastStatMachineCallbacks : public IBroadcastStateMachineCallbacks { +public: MockBroadcastStatMachineCallbacks() = default; - MockBroadcastStatMachineCallbacks(const MockBroadcastStatMachineCallbacks&) = - delete; - MockBroadcastStatMachineCallbacks& operator=( - const MockBroadcastStatMachineCallbacks&) = delete; + MockBroadcastStatMachineCallbacks(const MockBroadcastStatMachineCallbacks&) = delete; + MockBroadcastStatMachineCallbacks& operator=(const MockBroadcastStatMachineCallbacks&) = delete; ~MockBroadcastStatMachineCallbacks() override = default; - MOCK_METHOD((void), OnStateMachineCreateStatus, - (uint32_t broadcast_id, bool initialized), (override)); - MOCK_METHOD((void), OnStateMachineDestroyed, (uint32_t broadcast_id), + MOCK_METHOD((void), OnStateMachineCreateStatus, (uint32_t broadcast_id, bool initialized), (override)); + MOCK_METHOD((void), OnStateMachineDestroyed, (uint32_t broadcast_id), (override)); MOCK_METHOD((void), OnStateMachineEvent, - (uint32_t broadcast_id, BroadcastStateMachine::State state, - const void* data), + (uint32_t broadcast_id, BroadcastStateMachine::State state, const void* data), (override)); MOCK_METHOD((void), OnOwnAddressResponse, - (uint32_t broadcast_id, uint8_t addr_type, RawAddress addr), - (override)); - MOCK_METHOD((void), OnBigCreated, (const std::vector& conn_handle), - (override)); - MOCK_METHOD((void), OnAnnouncementUpdated, (uint32_t broadcast_id), - (override)); + (uint32_t broadcast_id, uint8_t addr_type, RawAddress addr), (override)); + MOCK_METHOD((void), OnBigCreated, (const std::vector& conn_handle), (override)); + MOCK_METHOD((void), OnAnnouncementUpdated, (uint32_t broadcast_id), (override)); }; class MockBroadcastAdvertisingCallbacks : public AdvertisingCallbacks { - public: +public: MockBroadcastAdvertisingCallbacks() = default; - MockBroadcastAdvertisingCallbacks(const MockBroadcastAdvertisingCallbacks&) = - delete; - MockBroadcastAdvertisingCallbacks& operator=( - const MockBroadcastAdvertisingCallbacks&) = delete; + MockBroadcastAdvertisingCallbacks(const MockBroadcastAdvertisingCallbacks&) = delete; + MockBroadcastAdvertisingCallbacks& operator=(const MockBroadcastAdvertisingCallbacks&) = delete; ~MockBroadcastAdvertisingCallbacks() override = default; MOCK_METHOD((void), OnAdvertisingSetStarted, - (int reg_id, uint8_t advertiser_id, int8_t tx_power, - uint8_t status), + (int reg_id, uint8_t advertiser_id, int8_t tx_power, uint8_t status), (override)); + MOCK_METHOD((void), OnAdvertisingEnabled, (uint8_t advertiser_id, bool enable, uint8_t status), (override)); - MOCK_METHOD((void), OnAdvertisingEnabled, - (uint8_t advertiser_id, bool enable, uint8_t status), (override)); - MOCK_METHOD((void), OnAdvertisingDataSet, - (uint8_t advertiser_id, uint8_t status), (override)); - MOCK_METHOD((void), OnScanResponseDataSet, - (uint8_t advertiser_id, uint8_t status), (override)); + MOCK_METHOD((void), OnAdvertisingDataSet, (uint8_t advertiser_id, uint8_t status), (override)); + MOCK_METHOD((void), OnScanResponseDataSet, (uint8_t advertiser_id, uint8_t status), (override)); MOCK_METHOD((void), OnAdvertisingParametersUpdated, - (uint8_t advertiser_id, int8_t tx_power, uint8_t status), - (override)); + (uint8_t advertiser_id, int8_t tx_power, uint8_t status), (override)); MOCK_METHOD((void), OnPeriodicAdvertisingParametersUpdated, (uint8_t advertiser_id, uint8_t status), (override)); - MOCK_METHOD((void), OnPeriodicAdvertisingDataSet, - (uint8_t advertiser_id, uint8_t status), (override)); + MOCK_METHOD((void), OnPeriodicAdvertisingDataSet, (uint8_t advertiser_id, uint8_t status), + (override)); MOCK_METHOD((void), OnPeriodicAdvertisingEnabled, (uint8_t advertiser_id, bool enable, uint8_t status), (override)); MOCK_METHOD((void), OnOwnAddressRead, - (uint8_t advertiser_id, uint8_t address_type, RawAddress address), - (override)); + (uint8_t advertiser_id, uint8_t address_type, RawAddress address), (override)); }; class StateMachineTest : public Test { - protected: +protected: void SetUp() override { reset_mock_function_count_map(); MockBleAdvertisingManager::Initialize(); @@ -134,42 +114,36 @@ class StateMachineTest : public Test { sm_callbacks_.reset(new MockBroadcastStatMachineCallbacks()); adv_callbacks_.reset(new MockBroadcastAdvertisingCallbacks()); - BroadcastStateMachine::Initialize(sm_callbacks_.get(), - adv_callbacks_.get()); + BroadcastStateMachine::Initialize(sm_callbacks_.get(), adv_callbacks_.get()); ON_CALL(*mock_ble_advertising_manager_, StartAdvertisingSet) - .WillByDefault( - [this](uint8_t client_id, int reg_id, - BleAdvertiserInterface::IdTxPowerStatusCallback register_cb, - AdvertiseParameters params, - std::vector advertise_data, - std::vector scan_response_data, - PeriodicAdvertisingParameters periodic_params, - std::vector periodic_data, uint16_t duration, - uint8_t maxExtAdvEvents, - BleAdvertiserInterface::IdStatusCallback timeout_cb) { + .WillByDefault([this](uint8_t client_id, int reg_id, + BleAdvertiserInterface::IdTxPowerStatusCallback register_cb, + AdvertiseParameters params, std::vector advertise_data, + std::vector scan_response_data, + PeriodicAdvertisingParameters periodic_params, + std::vector periodic_data, uint16_t duration, + uint8_t maxExtAdvEvents, + BleAdvertiserInterface::IdStatusCallback timeout_cb) { static uint8_t advertiser_id = 1; uint8_t tx_power = 32; uint8_t status = 0; this->adv_callbacks_->OnAdvertisingSetStarted( - BroadcastStateMachine::kLeAudioBroadcastRegId, - advertiser_id++, tx_power, status); + BroadcastStateMachine::kLeAudioBroadcastRegId, advertiser_id++, tx_power, + status); }); ON_CALL(*mock_ble_advertising_manager_, Enable) - .WillByDefault( - [this](uint8_t advertiser_id, bool enable, - BleAdvertiserInterface::StatusCallback cb, uint16_t duration, - uint8_t maxExtAdvEvents, - BleAdvertiserInterface::StatusCallback timeout_cb) { + .WillByDefault([this](uint8_t advertiser_id, bool enable, + BleAdvertiserInterface::StatusCallback cb, uint16_t duration, + uint8_t maxExtAdvEvents, + BleAdvertiserInterface::StatusCallback timeout_cb) { uint8_t status = 0; - this->adv_callbacks_->OnAdvertisingEnabled(advertiser_id, enable, - status); + this->adv_callbacks_->OnAdvertisingEnabled(advertiser_id, enable, status); }); ON_CALL(*mock_ble_advertising_manager_, GetOwnAddress) - .WillByDefault( - [](uint8_t inst_id, BleAdvertiserInterface::GetAddressCallback cb) { + .WillByDefault([](uint8_t inst_id, BleAdvertiserInterface::GetAddressCallback cb) { uint8_t address_type = 0x02; RawAddress address; const uint8_t addr[] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66}; @@ -178,87 +152,78 @@ class StateMachineTest : public Test { }); ON_CALL(*mock_ble_advertising_manager_, SetData) - .WillByDefault([this](int advertiser_id, bool set_scan_rsp, - std::vector data, - BleAdvertiserInterface::StatusCallback cb) { - uint8_t status = 0; - this->adv_callbacks_->OnAdvertisingDataSet(advertiser_id, status); - }); + .WillByDefault([this](int advertiser_id, bool set_scan_rsp, std::vector data, + BleAdvertiserInterface::StatusCallback cb) { + uint8_t status = 0; + this->adv_callbacks_->OnAdvertisingDataSet(advertiser_id, status); + }); ON_CALL(*mock_ble_advertising_manager_, SetPeriodicAdvertisingData) - .WillByDefault([this](int advertiser_id, std::vector data, - BleAdvertiserInterface::StatusCallback cb) { - uint8_t status = 0; - this->adv_callbacks_->OnPeriodicAdvertisingDataSet(advertiser_id, - status); - }); + .WillByDefault([this](int advertiser_id, std::vector data, + BleAdvertiserInterface::StatusCallback cb) { + uint8_t status = 0; + this->adv_callbacks_->OnPeriodicAdvertisingDataSet(advertiser_id, status); + }); ON_CALL(*(sm_callbacks_.get()), OnStateMachineCreateStatus) - .WillByDefault([this](uint32_t broadcast_id, bool initialized) { - auto instance_it = - std::find_if(pending_broadcasts_.begin(), - pending_broadcasts_.end(), [broadcast_id](auto& up) { - return (up->GetBroadcastId() == broadcast_id); - }); - if (instance_it != pending_broadcasts_.end()) { - if (initialized) { - broadcasts_[broadcast_id] = std::move(*instance_it); - } - pending_broadcasts_.erase(instance_it); - } - instance_creation_promise_.set_value(broadcast_id); - }); + .WillByDefault([this](uint32_t broadcast_id, bool initialized) { + auto instance_it = std::find_if( + pending_broadcasts_.begin(), pending_broadcasts_.end(), + [broadcast_id](auto& up) { return up->GetBroadcastId() == broadcast_id; }); + if (instance_it != pending_broadcasts_.end()) { + if (initialized) { + broadcasts_[broadcast_id] = std::move(*instance_it); + } + pending_broadcasts_.erase(instance_it); + } + instance_creation_promise_.set_value(broadcast_id); + }); ON_CALL(*(sm_callbacks_.get()), OnStateMachineDestroyed) - .WillByDefault([this](uint32_t broadcast_id) { - if (broadcasts_.count(broadcast_id)) { - instance_destruction_promise_.set_value(broadcast_id); - } - }); + .WillByDefault([this](uint32_t broadcast_id) { + if (broadcasts_.count(broadcast_id)) { + instance_destruction_promise_.set_value(broadcast_id); + } + }); ON_CALL(*(adv_callbacks_.get()), OnAdvertisingSetStarted) - .WillByDefault([this](int reg_id, uint8_t advertiser_id, - int8_t tx_power, uint8_t status) { - pending_broadcasts_.back()->OnCreateAnnouncement(advertiser_id, - tx_power, status); - }); + .WillByDefault([this](int reg_id, uint8_t advertiser_id, int8_t tx_power, + uint8_t status) { + pending_broadcasts_.back()->OnCreateAnnouncement(advertiser_id, tx_power, status); + }); ON_CALL(*(adv_callbacks_.get()), OnAdvertisingEnabled) - .WillByDefault( - [this](uint8_t advertiser_id, bool enable, uint8_t status) { + .WillByDefault([this](uint8_t advertiser_id, bool enable, uint8_t status) { auto const& iter = std::find_if( - broadcasts_.cbegin(), broadcasts_.cend(), - [advertiser_id](auto const& sm) { - return sm.second->GetAdvertisingSid() == advertiser_id; - }); + broadcasts_.cbegin(), broadcasts_.cend(), [advertiser_id](auto const& sm) { + return sm.second->GetAdvertisingSid() == advertiser_id; + }); if (iter != broadcasts_.cend()) { iter->second->OnEnableAnnouncement(enable, status); } }); ON_CALL(*(adv_callbacks_.get()), OnAdvertisingDataSet) - .WillByDefault([this](uint8_t advertiser_id, uint8_t status) { - auto const& iter = std::find_if( - broadcasts_.cbegin(), broadcasts_.cend(), - [advertiser_id](auto const& sm) { - return sm.second->GetAdvertisingSid() == advertiser_id; - }); - if (iter != broadcasts_.cend()) { - iter->second->OnUpdateAnnouncement(status); - } - }); + .WillByDefault([this](uint8_t advertiser_id, uint8_t status) { + auto const& iter = std::find_if( + broadcasts_.cbegin(), broadcasts_.cend(), [advertiser_id](auto const& sm) { + return sm.second->GetAdvertisingSid() == advertiser_id; + }); + if (iter != broadcasts_.cend()) { + iter->second->OnUpdateAnnouncement(status); + } + }); ON_CALL(*(adv_callbacks_.get()), OnPeriodicAdvertisingDataSet) - .WillByDefault([this](uint8_t advertiser_id, uint8_t status) { - auto const& iter = std::find_if( - broadcasts_.cbegin(), broadcasts_.cend(), - [advertiser_id](auto const& sm) { - return sm.second->GetAdvertisingSid() == advertiser_id; - }); - if (iter != broadcasts_.cend()) { - iter->second->OnUpdateAnnouncement(status); - } - }); + .WillByDefault([this](uint8_t advertiser_id, uint8_t status) { + auto const& iter = std::find_if( + broadcasts_.cbegin(), broadcasts_.cend(), [advertiser_id](auto const& sm) { + return sm.second->GetAdvertisingSid() == advertiser_id; + }); + if (iter != broadcasts_.cend()) { + iter->second->OnUpdateAnnouncement(status); + } + }); ConfigureIsoManagerMock(); } @@ -272,71 +237,73 @@ class StateMachineTest : public Test { ASSERT_NE(mock_iso_manager_, nullptr); ON_CALL(*mock_iso_manager_, CreateBig) - .WillByDefault([this](uint8_t big_id, big_create_params p) { - auto bit = - std::find_if(broadcasts_.begin(), broadcasts_.end(), - [big_id](auto const& entry) { - return entry.second->GetAdvertisingSid() == big_id; - }); - if (bit == broadcasts_.end()) return; - - big_create_cmpl_evt evt; - evt.big_id = big_id; - - // For test convenience lets encode big_id into conn_hdl MSB. - // NOTE: In current implementation big_id is equal to advertising SID. - // This is an important detail exploited by the IsoManager mock - static uint8_t conn_lsb = 1; - uint16_t conn_msb = ((uint16_t)big_id) << 8; - for (auto i = 0; i < p.num_bis; ++i) { - evt.conn_handles.push_back(conn_msb | conn_lsb++); - } - - bit->second->HandleHciEvent(HCI_BLE_CREATE_BIG_CPL_EVT, &evt); - }); + .WillByDefault([this](uint8_t big_id, big_create_params p) { + auto bit = std::find_if(broadcasts_.begin(), broadcasts_.end(), + [big_id](auto const& entry) { + return entry.second->GetAdvertisingSid() == big_id; + }); + if (bit == broadcasts_.end()) { + return; + } + + big_create_cmpl_evt evt; + evt.big_id = big_id; + + // For test convenience lets encode big_id into conn_hdl MSB. + // NOTE: In current implementation big_id is equal to advertising SID. + // This is an important detail exploited by the IsoManager mock + static uint8_t conn_lsb = 1; + uint16_t conn_msb = ((uint16_t)big_id) << 8; + for (auto i = 0; i < p.num_bis; ++i) { + evt.conn_handles.push_back(conn_msb | conn_lsb++); + } + + bit->second->HandleHciEvent(HCI_BLE_CREATE_BIG_CPL_EVT, &evt); + }); ON_CALL(*mock_iso_manager_, SetupIsoDataPath) - .WillByDefault([this](uint16_t conn_handle, iso_data_path_params p) { - // Get the big_id encoded in conn_handle's MSB - uint8_t big_id = conn_handle >> 8; - auto bit = - std::find_if(broadcasts_.begin(), broadcasts_.end(), - [big_id](auto const& entry) { - return entry.second->GetAdvertisingSid() == big_id; - }); - if (bit == broadcasts_.end()) return; - bit->second->OnSetupIsoDataPath(0, conn_handle); - }); + .WillByDefault([this](uint16_t conn_handle, iso_data_path_params p) { + // Get the big_id encoded in conn_handle's MSB + uint8_t big_id = conn_handle >> 8; + auto bit = std::find_if(broadcasts_.begin(), broadcasts_.end(), + [big_id](auto const& entry) { + return entry.second->GetAdvertisingSid() == big_id; + }); + if (bit == broadcasts_.end()) { + return; + } + bit->second->OnSetupIsoDataPath(0, conn_handle); + }); ON_CALL(*mock_iso_manager_, RemoveIsoDataPath) - .WillByDefault([this](uint16_t conn_handle, uint8_t iso_direction) { - // Get the big_id encoded in conn_handle's MSB - uint8_t big_id = conn_handle >> 8; - auto bit = - std::find_if(broadcasts_.begin(), broadcasts_.end(), - [big_id](auto const& entry) { - return entry.second->GetAdvertisingSid() == big_id; - }); - if (bit == broadcasts_.end()) return; - bit->second->OnRemoveIsoDataPath(0, conn_handle); - }); - - ON_CALL(*mock_iso_manager_, TerminateBig) - .WillByDefault([this](uint8_t big_id, uint8_t reason) { - // Get the big_id encoded in conn_handle's MSB - auto bit = - std::find_if(broadcasts_.begin(), broadcasts_.end(), - [big_id](auto const& entry) { - return entry.second->GetAdvertisingSid() == big_id; - }); - if (bit == broadcasts_.end()) return; - - big_terminate_cmpl_evt evt; - evt.big_id = big_id; - evt.reason = reason; - - bit->second->HandleHciEvent(HCI_BLE_TERM_BIG_CPL_EVT, &evt); - }); + .WillByDefault([this](uint16_t conn_handle, uint8_t iso_direction) { + // Get the big_id encoded in conn_handle's MSB + uint8_t big_id = conn_handle >> 8; + auto bit = std::find_if(broadcasts_.begin(), broadcasts_.end(), + [big_id](auto const& entry) { + return entry.second->GetAdvertisingSid() == big_id; + }); + if (bit == broadcasts_.end()) { + return; + } + bit->second->OnRemoveIsoDataPath(0, conn_handle); + }); + + ON_CALL(*mock_iso_manager_, TerminateBig).WillByDefault([this](uint8_t big_id, uint8_t reason) { + // Get the big_id encoded in conn_handle's MSB + auto bit = std::find_if(broadcasts_.begin(), broadcasts_.end(), [big_id](auto const& entry) { + return entry.second->GetAdvertisingSid() == big_id; + }); + if (bit == broadcasts_.end()) { + return; + } + + big_terminate_cmpl_evt evt; + evt.big_id = big_id; + evt.reason = reason; + + bit->second->HandleHciEvent(HCI_BLE_TERM_BIG_CPL_EVT, &evt); + }); } void TearDown() override { @@ -355,27 +322,26 @@ class StateMachineTest : public Test { } uint32_t InstantiateStateMachine( - bluetooth::le_audio::types::LeAudioContextType context = - bluetooth::le_audio::types::LeAudioContextType::UNSPECIFIED) { + bluetooth::le_audio::types::LeAudioContextType context = + bluetooth::le_audio::types::LeAudioContextType::UNSPECIFIED) { // We will get the state machine create status update in an async callback // so let's wait for it here. instance_creation_promise_ = std::promise(); - std::future instance_future = - instance_creation_promise_.get_future(); + std::future instance_future = instance_creation_promise_.get_future(); static uint8_t broadcast_id_lsb = 1; - const std::vector>& - subgroup_quality = {{context, 1}}; + const std::vector>& subgroup_quality = { + {context, 1}}; auto config = GetBroadcastConfig(subgroup_quality); auto broadcast_id = broadcast_id_lsb++; pending_broadcasts_.push_back(BroadcastStateMachine::CreateInstance({ - .is_public = true, - .broadcast_id = broadcast_id, - .broadcast_name = test_broadcast_name, - .config = config, - // .announcement = , - // .broadcast_code = , + .is_public = true, + .broadcast_id = broadcast_id, + .broadcast_name = test_broadcast_name, + .config = config, + // .announcement = , + // .broadcast_code = , })); pending_broadcasts_.back()->Initialize(); return instance_future.get(); @@ -395,26 +361,22 @@ class StateMachineTest : public Test { TEST_F(StateMachineTest, CreateInstanceFailed) { EXPECT_CALL(*mock_ble_advertising_manager_, StartAdvertisingSet) - .WillOnce( - [this](uint8_t client_id, int reg_id, - BleAdvertiserInterface::IdTxPowerStatusCallback register_cb, - AdvertiseParameters params, - std::vector advertise_data, - std::vector scan_response_data, - PeriodicAdvertisingParameters periodic_params, - std::vector periodic_data, uint16_t duration, - uint8_t maxExtAdvEvents, - BleAdvertiserInterface::IdStatusCallback timeout_cb) { + .WillOnce([this](uint8_t client_id, int reg_id, + BleAdvertiserInterface::IdTxPowerStatusCallback register_cb, + AdvertiseParameters params, std::vector advertise_data, + std::vector scan_response_data, + PeriodicAdvertisingParameters periodic_params, + std::vector periodic_data, uint16_t duration, + uint8_t maxExtAdvEvents, + BleAdvertiserInterface::IdStatusCallback timeout_cb) { uint8_t advertiser_id = 1; uint8_t tx_power = 0; uint8_t status = 1; this->adv_callbacks_->OnAdvertisingSetStarted( - BroadcastStateMachine::kLeAudioBroadcastRegId, advertiser_id, - tx_power, status); + BroadcastStateMachine::kLeAudioBroadcastRegId, advertiser_id, tx_power, status); }); - EXPECT_CALL(*(sm_callbacks_.get()), OnStateMachineCreateStatus(_, false)) - .Times(1); + EXPECT_CALL(*(sm_callbacks_.get()), OnStateMachineCreateStatus(_, false)).Times(1); auto broadcast_id = InstantiateStateMachine(); ASSERT_NE(broadcast_id, BroadcastStateMachine::kAdvSidUndefined); @@ -423,47 +385,40 @@ TEST_F(StateMachineTest, CreateInstanceFailed) { } TEST_F(StateMachineTest, CreateInstanceSuccess) { - EXPECT_CALL(*(sm_callbacks_.get()), OnStateMachineCreateStatus(_, true)) - .Times(1); + EXPECT_CALL(*(sm_callbacks_.get()), OnStateMachineCreateStatus(_, true)).Times(1); auto broadcast_id = InstantiateStateMachine(); ASSERT_NE(broadcast_id, BroadcastStateMachine::kAdvSidUndefined); ASSERT_TRUE(pending_broadcasts_.empty()); ASSERT_FALSE(broadcasts_.empty()); ASSERT_EQ(broadcasts_[broadcast_id]->GetBroadcastId(), broadcast_id); - ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), - BroadcastStateMachine::State::CONFIGURED); + ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), BroadcastStateMachine::State::CONFIGURED); } TEST_F(StateMachineTest, DestroyInstanceSuccess) { - EXPECT_CALL(*(sm_callbacks_.get()), OnStateMachineCreateStatus(_, true)) - .Times(1); + EXPECT_CALL(*(sm_callbacks_.get()), OnStateMachineCreateStatus(_, true)).Times(1); auto broadcast_id = InstantiateStateMachine(); ASSERT_NE(broadcast_id, BroadcastStateMachine::kAdvSidUndefined); ASSERT_FALSE(broadcasts_.empty()); instance_destruction_promise_ = std::promise(); - std::future instance_future = - instance_destruction_promise_.get_future(); + std::future instance_future = instance_destruction_promise_.get_future(); broadcasts_.clear(); EXPECT_EQ(instance_future.get(), broadcast_id); } TEST_F(StateMachineTest, GetAdvertisingAddress) { - EXPECT_CALL(*(sm_callbacks_.get()), OnStateMachineCreateStatus(_, true)) - .Times(1); + EXPECT_CALL(*(sm_callbacks_.get()), OnStateMachineCreateStatus(_, true)).Times(1); auto broadcast_id = InstantiateStateMachine(); - EXPECT_CALL(*(sm_callbacks_.get()), OnOwnAddressResponse(broadcast_id, _, _)) - .Times(1); + EXPECT_CALL(*(sm_callbacks_.get()), OnOwnAddressResponse(broadcast_id, _, _)).Times(1); broadcasts_[broadcast_id]->RequestOwnAddress(); } TEST_F(StateMachineTest, Mute) { - EXPECT_CALL(*(sm_callbacks_.get()), OnStateMachineCreateStatus(_, true)) - .Times(1); + EXPECT_CALL(*(sm_callbacks_.get()), OnStateMachineCreateStatus(_, true)).Times(1); auto broadcast_id = InstantiateStateMachine(); ASSERT_TRUE(pending_broadcasts_.empty()); @@ -477,8 +432,8 @@ TEST_F(StateMachineTest, Mute) { } static BasicAudioAnnouncementData prepareAnnouncement( - const BroadcastSubgroupCodecConfig& codec_config, - std::map> metadata) { + const BroadcastSubgroupCodecConfig& codec_config, + std::map> metadata) { BasicAudioAnnouncementData announcement; announcement.presentation_delay_us = 40000; @@ -486,22 +441,20 @@ static BasicAudioAnnouncementData prepareAnnouncement( auto const subgroup_codec_spec = codec_config.GetCommonBisCodecSpecData(); announcement.subgroup_configs = {{ - .codec_config = - { - .codec_id = codec_id.coding_format, - .vendor_company_id = codec_id.vendor_company_id, - .vendor_codec_id = codec_id.vendor_codec_id, - .codec_specific_params = subgroup_codec_spec.Values(), - }, - .metadata = std::move(metadata), - .bis_configs = {}, + .codec_config = + { + .codec_id = codec_id.coding_format, + .vendor_company_id = codec_id.vendor_company_id, + .vendor_codec_id = codec_id.vendor_codec_id, + .codec_specific_params = subgroup_codec_spec.Values(), + }, + .metadata = std::move(metadata), + .bis_configs = {}, }}; uint8_t bis_count = 0; - for (uint8_t bis_idx = 0; bis_idx < codec_config.GetAllBisConfigCount(); - ++bis_idx) { - for (uint8_t bis_num = 0; bis_num < codec_config.GetNumBis(bis_idx); - ++bis_num) { + for (uint8_t bis_idx = 0; bis_idx < codec_config.GetAllBisConfigCount(); ++bis_idx) { + for (uint8_t bis_num = 0; bis_num < codec_config.GetNumBis(bis_idx); ++bis_num) { ++bis_count; // Check for vendor byte array @@ -520,8 +473,7 @@ static BasicAudioAnnouncementData prepareAnnouncement( // Internally BISes are indexed from 0 in each subgroup, but the BT spec // requires the indices to be indexed from 1 in the entire BIG. bis_config.bis_index = bis_count; - announcement.subgroup_configs[0].bis_configs.push_back( - std::move(bis_config)); + announcement.subgroup_configs[0].bis_configs.push_back(std::move(bis_config)); } } @@ -529,22 +481,19 @@ static BasicAudioAnnouncementData prepareAnnouncement( } TEST_F(StateMachineTest, UpdateAnnouncement) { - EXPECT_CALL(*(sm_callbacks_.get()), OnStateMachineCreateStatus(_, true)) - .Times(1); + EXPECT_CALL(*(sm_callbacks_.get()), OnStateMachineCreateStatus(_, true)).Times(1); auto broadcast_id = InstantiateStateMachine(); auto adv_sid = broadcasts_[broadcast_id]->GetAdvertisingSid(); std::vector data; - EXPECT_CALL(*mock_ble_advertising_manager_, - SetPeriodicAdvertisingData(adv_sid, _, _)) - .Times(2) - .WillRepeatedly(SaveArg<1>(&data)); + EXPECT_CALL(*mock_ble_advertising_manager_, SetPeriodicAdvertisingData(adv_sid, _, _)) + .Times(2) + .WillRepeatedly(SaveArg<1>(&data)); std::map> metadata = {}; auto codec_config = lc3_mono_16_2; auto announcement = prepareAnnouncement(codec_config, metadata); - broadcasts_[broadcast_id]->UpdateBroadcastAnnouncement( - std::move(announcement)); + broadcasts_[broadcast_id]->UpdateBroadcastAnnouncement(std::move(announcement)); uint8_t first_len = data.size(); ASSERT_NE(first_len, 0); // Non-zero length @@ -556,437 +505,366 @@ TEST_F(StateMachineTest, UpdateAnnouncement) { // Verify that changes in the announcement makes a difference metadata = {{0x01, {0x03}}}; announcement = prepareAnnouncement(codec_config, metadata); - broadcasts_[broadcast_id]->UpdateBroadcastAnnouncement( - std::move(announcement)); + broadcasts_[broadcast_id]->UpdateBroadcastAnnouncement(std::move(announcement)); uint8_t second_len = data.size(); // These should differ by the difference in metadata - ASSERT_EQ(first_len + types::LeAudioLtvMap(metadata).RawPacketSize(), - second_len); + ASSERT_EQ(first_len + types::LeAudioLtvMap(metadata).RawPacketSize(), second_len); } -TEST_F_WITH_FLAGS(StateMachineTest, UpdateBroadcastAnnouncementWithCallback, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG( - TEST_BT, leaudio_broadcast_update_metadata_callback))) { - EXPECT_CALL(*(sm_callbacks_.get()), OnStateMachineCreateStatus(_, true)) - .Times(1); +TEST_F_WITH_FLAGS( + StateMachineTest, UpdateBroadcastAnnouncementWithCallback, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, leaudio_broadcast_update_metadata_callback))) { + EXPECT_CALL(*(sm_callbacks_.get()), OnStateMachineCreateStatus(_, true)).Times(1); auto broadcast_id = InstantiateStateMachine(); auto adv_sid = broadcasts_[broadcast_id]->GetAdvertisingSid(); - EXPECT_CALL(*mock_ble_advertising_manager_, - SetPeriodicAdvertisingData(adv_sid, _, _)) - .Times(1) - .WillRepeatedly(testing::DoDefault()); + EXPECT_CALL(*mock_ble_advertising_manager_, SetPeriodicAdvertisingData(adv_sid, _, _)) + .Times(1) + .WillRepeatedly(testing::DoDefault()); - EXPECT_CALL(*(sm_callbacks_.get()), OnAnnouncementUpdated(broadcast_id)) - .Times(1); + EXPECT_CALL(*(sm_callbacks_.get()), OnAnnouncementUpdated(broadcast_id)).Times(1); std::map> metadata = {}; auto codec_config = lc3_mono_16_2; auto announcement = prepareAnnouncement(codec_config, metadata); broadcasts_[broadcast_id]->UpdateBroadcastAnnouncement(announcement); - ASSERT_EQ(announcement, - broadcasts_[broadcast_id]->GetBroadcastAnnouncement()); + ASSERT_EQ(announcement, broadcasts_[broadcast_id]->GetBroadcastAnnouncement()); } -TEST_F_WITH_FLAGS(StateMachineTest, - UpdatePublicBroadcastAnnouncementWithCallback, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG( - TEST_BT, leaudio_broadcast_update_metadata_callback))) { - EXPECT_CALL(*(sm_callbacks_.get()), OnStateMachineCreateStatus(_, true)) - .Times(1); +TEST_F_WITH_FLAGS( + StateMachineTest, UpdatePublicBroadcastAnnouncementWithCallback, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, leaudio_broadcast_update_metadata_callback))) { + EXPECT_CALL(*(sm_callbacks_.get()), OnStateMachineCreateStatus(_, true)).Times(1); auto broadcast_id = InstantiateStateMachine(); auto adv_sid = broadcasts_[broadcast_id]->GetAdvertisingSid(); EXPECT_CALL(*mock_ble_advertising_manager_, SetData(adv_sid, _, _, _)) - .Times(1) - .WillRepeatedly(testing::DoDefault()); + .Times(1) + .WillRepeatedly(testing::DoDefault()); - EXPECT_CALL(*(sm_callbacks_.get()), OnAnnouncementUpdated(broadcast_id)) - .Times(1); + EXPECT_CALL(*(sm_callbacks_.get()), OnAnnouncementUpdated(broadcast_id)).Times(1); bool is_public_metadata_valid; types::LeAudioLtvMap public_ltv = types::LeAudioLtvMap::Parse( - default_public_metadata.data(), default_public_metadata.size(), - is_public_metadata_valid); + default_public_metadata.data(), default_public_metadata.size(), is_public_metadata_valid); bluetooth::le_audio::PublicBroadcastAnnouncementData pb_announcement = { - .features = test_public_broadcast_features, - .metadata = public_ltv.Values()}; + .features = test_public_broadcast_features, .metadata = public_ltv.Values()}; - broadcasts_[broadcast_id]->UpdatePublicBroadcastAnnouncement( - broadcast_id, test_broadcast_name, pb_announcement); + broadcasts_[broadcast_id]->UpdatePublicBroadcastAnnouncement(broadcast_id, test_broadcast_name, + pb_announcement); - ASSERT_EQ(pb_announcement, - broadcasts_[broadcast_id]->GetPublicBroadcastAnnouncement()); + ASSERT_EQ(pb_announcement, broadcasts_[broadcast_id]->GetPublicBroadcastAnnouncement()); } TEST_F(StateMachineTest, ProcessMessageStartWhenConfigured) { - EXPECT_CALL(*(sm_callbacks_.get()), OnStateMachineCreateStatus(_, true)) - .Times(1); + EXPECT_CALL(*(sm_callbacks_.get()), OnStateMachineCreateStatus(_, true)).Times(1); auto sound_context = bluetooth::le_audio::types::LeAudioContextType::MEDIA; uint8_t num_channels = 2; auto broadcast_id = InstantiateStateMachine(sound_context); - ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), - BroadcastStateMachine::State::CONFIGURED); + ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), BroadcastStateMachine::State::CONFIGURED); uint8_t num_bises = 0; EXPECT_CALL(*mock_iso_manager_, CreateBig) - .WillOnce([this, &num_bises](uint8_t big_id, big_create_params p) { - auto bit = - std::find_if(broadcasts_.begin(), broadcasts_.end(), - [big_id](auto const& entry) { - return entry.second->GetAdvertisingSid() == big_id; - }); - if (bit == broadcasts_.end()) return; - - num_bises = p.num_bis; - - big_create_cmpl_evt evt; - evt.big_id = big_id; - - // For test convenience lets encode big_id into conn_hdl's - // MSB - static uint8_t conn_lsb = 1; - uint16_t conn_msb = ((uint16_t)big_id) << 8; - for (auto i = 0; i < p.num_bis; ++i) { - evt.conn_handles.push_back(conn_msb | conn_lsb++); - } - - bit->second->HandleHciEvent(HCI_BLE_CREATE_BIG_CPL_EVT, &evt); - }); + .WillOnce([this, &num_bises](uint8_t big_id, big_create_params p) { + auto bit = std::find_if(broadcasts_.begin(), broadcasts_.end(), + [big_id](auto const& entry) { + return entry.second->GetAdvertisingSid() == big_id; + }); + if (bit == broadcasts_.end()) { + return; + } + + num_bises = p.num_bis; + + big_create_cmpl_evt evt; + evt.big_id = big_id; + + // For test convenience lets encode big_id into conn_hdl's + // MSB + static uint8_t conn_lsb = 1; + uint16_t conn_msb = ((uint16_t)big_id) << 8; + for (auto i = 0; i < p.num_bis; ++i) { + evt.conn_handles.push_back(conn_msb | conn_lsb++); + } + + bit->second->HandleHciEvent(HCI_BLE_CREATE_BIG_CPL_EVT, &evt); + }); EXPECT_CALL(*mock_iso_manager_, SetupIsoDataPath).Times(num_channels); EXPECT_CALL(*mock_iso_manager_, RemoveIsoDataPath).Times(0); EXPECT_CALL(*(sm_callbacks_.get()), - OnStateMachineEvent(broadcast_id, - BroadcastStateMachine::State::STREAMING, _)) - .Times(1); - broadcasts_[broadcast_id]->ProcessMessage( - BroadcastStateMachine::Message::START); + OnStateMachineEvent(broadcast_id, BroadcastStateMachine::State::STREAMING, _)) + .Times(1); + broadcasts_[broadcast_id]->ProcessMessage(BroadcastStateMachine::Message::START); // Verify the right number of BISes in the BIG being created ASSERT_EQ(num_bises, num_channels); - ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), - BroadcastStateMachine::State::STREAMING); + ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), BroadcastStateMachine::State::STREAMING); } TEST_F(StateMachineTest, ProcessMessageStopWhenConfigured) { - EXPECT_CALL(*(sm_callbacks_.get()), OnStateMachineCreateStatus(_, true)) - .Times(1); + EXPECT_CALL(*(sm_callbacks_.get()), OnStateMachineCreateStatus(_, true)).Times(1); - auto broadcast_id = InstantiateStateMachine( - bluetooth::le_audio::types::LeAudioContextType::MEDIA); - ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), - BroadcastStateMachine::State::CONFIGURED); + auto broadcast_id = + InstantiateStateMachine(bluetooth::le_audio::types::LeAudioContextType::MEDIA); + ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), BroadcastStateMachine::State::CONFIGURED); EXPECT_CALL(*mock_iso_manager_, SetupIsoDataPath).Times(0); EXPECT_CALL(*mock_iso_manager_, RemoveIsoDataPath).Times(0); EXPECT_CALL(*(sm_callbacks_.get()), - OnStateMachineEvent(broadcast_id, - BroadcastStateMachine::State::STOPPING, _)) - .Times(1); + OnStateMachineEvent(broadcast_id, BroadcastStateMachine::State::STOPPING, _)) + .Times(1); EXPECT_CALL(*(sm_callbacks_.get()), - OnStateMachineEvent(broadcast_id, - BroadcastStateMachine::State::STOPPED, _)) - .Times(1); - broadcasts_[broadcast_id]->ProcessMessage( - BroadcastStateMachine::Message::STOP); - - ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), - BroadcastStateMachine::State::STOPPED); + OnStateMachineEvent(broadcast_id, BroadcastStateMachine::State::STOPPED, _)) + .Times(1); + broadcasts_[broadcast_id]->ProcessMessage(BroadcastStateMachine::Message::STOP); + + ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), BroadcastStateMachine::State::STOPPED); } TEST_F(StateMachineTest, ProcessMessageSuspendWhenConfigured) { - EXPECT_CALL(*(sm_callbacks_.get()), OnStateMachineCreateStatus(_, true)) - .Times(1); + EXPECT_CALL(*(sm_callbacks_.get()), OnStateMachineCreateStatus(_, true)).Times(1); - auto broadcast_id = InstantiateStateMachine( - bluetooth::le_audio::types::LeAudioContextType::MEDIA); - ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), - BroadcastStateMachine::State::CONFIGURED); + auto broadcast_id = + InstantiateStateMachine(bluetooth::le_audio::types::LeAudioContextType::MEDIA); + ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), BroadcastStateMachine::State::CONFIGURED); EXPECT_CALL(*mock_iso_manager_, SetupIsoDataPath).Times(0); EXPECT_CALL(*mock_iso_manager_, RemoveIsoDataPath).Times(0); - EXPECT_CALL(*(sm_callbacks_.get()), OnStateMachineEvent(broadcast_id, _, _)) - .Times(0); - broadcasts_[broadcast_id]->ProcessMessage( - BroadcastStateMachine::Message::SUSPEND); + EXPECT_CALL(*(sm_callbacks_.get()), OnStateMachineEvent(broadcast_id, _, _)).Times(0); + broadcasts_[broadcast_id]->ProcessMessage(BroadcastStateMachine::Message::SUSPEND); // There shall be no change in state - ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), - BroadcastStateMachine::State::CONFIGURED); + ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), BroadcastStateMachine::State::CONFIGURED); } TEST_F(StateMachineTest, ProcessMessageStartWhenStreaming) { - auto broadcast_id = InstantiateStateMachine( - bluetooth::le_audio::types::LeAudioContextType::MEDIA); + auto broadcast_id = + InstantiateStateMachine(bluetooth::le_audio::types::LeAudioContextType::MEDIA); - broadcasts_[broadcast_id]->ProcessMessage( - BroadcastStateMachine::Message::START); - ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), - BroadcastStateMachine::State::STREAMING); + broadcasts_[broadcast_id]->ProcessMessage(BroadcastStateMachine::Message::START); + ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), BroadcastStateMachine::State::STREAMING); EXPECT_CALL(*mock_iso_manager_, SetupIsoDataPath).Times(0); EXPECT_CALL(*mock_iso_manager_, RemoveIsoDataPath).Times(0); - EXPECT_CALL(*(sm_callbacks_.get()), OnStateMachineEvent(broadcast_id, _, _)) - .Times(0); - broadcasts_[broadcast_id]->ProcessMessage( - BroadcastStateMachine::Message::START); + EXPECT_CALL(*(sm_callbacks_.get()), OnStateMachineEvent(broadcast_id, _, _)).Times(0); + broadcasts_[broadcast_id]->ProcessMessage(BroadcastStateMachine::Message::START); // There shall be no change in state - ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), - BroadcastStateMachine::State::STREAMING); + ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), BroadcastStateMachine::State::STREAMING); } TEST_F(StateMachineTest, ProcessMessageStopWhenStreaming) { - auto broadcast_id = InstantiateStateMachine( - bluetooth::le_audio::types::LeAudioContextType::MEDIA); + auto broadcast_id = + InstantiateStateMachine(bluetooth::le_audio::types::LeAudioContextType::MEDIA); - broadcasts_[broadcast_id]->ProcessMessage( - BroadcastStateMachine::Message::START); - ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), - BroadcastStateMachine::State::STREAMING); + broadcasts_[broadcast_id]->ProcessMessage(BroadcastStateMachine::Message::START); + ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), BroadcastStateMachine::State::STREAMING); EXPECT_CALL(*mock_iso_manager_, SetupIsoDataPath).Times(0); EXPECT_CALL(*mock_iso_manager_, RemoveIsoDataPath).Times(2); EXPECT_CALL(*(sm_callbacks_.get()), - OnStateMachineEvent(broadcast_id, - BroadcastStateMachine::State::STOPPING, _)) - .Times(1); + OnStateMachineEvent(broadcast_id, BroadcastStateMachine::State::STOPPING, _)) + .Times(1); EXPECT_CALL(*(sm_callbacks_.get()), - OnStateMachineEvent(broadcast_id, - BroadcastStateMachine::State::STOPPED, _)) - .Times(1); - broadcasts_[broadcast_id]->ProcessMessage( - BroadcastStateMachine::Message::STOP); - - ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), - BroadcastStateMachine::State::STOPPED); + OnStateMachineEvent(broadcast_id, BroadcastStateMachine::State::STOPPED, _)) + .Times(1); + broadcasts_[broadcast_id]->ProcessMessage(BroadcastStateMachine::Message::STOP); + + ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), BroadcastStateMachine::State::STOPPED); } TEST_F(StateMachineTest, ProcessMessageSuspendWhenStreaming) { - auto broadcast_id = InstantiateStateMachine( - bluetooth::le_audio::types::LeAudioContextType::MEDIA); + auto broadcast_id = + InstantiateStateMachine(bluetooth::le_audio::types::LeAudioContextType::MEDIA); - broadcasts_[broadcast_id]->ProcessMessage( - BroadcastStateMachine::Message::START); - ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), - BroadcastStateMachine::State::STREAMING); + broadcasts_[broadcast_id]->ProcessMessage(BroadcastStateMachine::Message::START); + ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), BroadcastStateMachine::State::STREAMING); EXPECT_CALL(*mock_iso_manager_, SetupIsoDataPath).Times(0); EXPECT_CALL(*mock_iso_manager_, RemoveIsoDataPath).Times(2); EXPECT_CALL(*(sm_callbacks_.get()), - OnStateMachineEvent(broadcast_id, - BroadcastStateMachine::State::CONFIGURED, _)) - .Times(1); - broadcasts_[broadcast_id]->ProcessMessage( - BroadcastStateMachine::Message::SUSPEND); - - ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), - BroadcastStateMachine::State::CONFIGURED); + OnStateMachineEvent(broadcast_id, BroadcastStateMachine::State::CONFIGURED, _)) + .Times(1); + broadcasts_[broadcast_id]->ProcessMessage(BroadcastStateMachine::Message::SUSPEND); + + ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), BroadcastStateMachine::State::CONFIGURED); } TEST_F(StateMachineTest, ProcessMessageStartWhenStopped) { - auto broadcast_id = InstantiateStateMachine( - bluetooth::le_audio::types::LeAudioContextType::MEDIA); + auto broadcast_id = + InstantiateStateMachine(bluetooth::le_audio::types::LeAudioContextType::MEDIA); - broadcasts_[broadcast_id]->ProcessMessage( - BroadcastStateMachine::Message::STOP); - ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), - BroadcastStateMachine::State::STOPPED); + broadcasts_[broadcast_id]->ProcessMessage(BroadcastStateMachine::Message::STOP); + ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), BroadcastStateMachine::State::STOPPED); EXPECT_CALL(*mock_iso_manager_, SetupIsoDataPath).Times(2); EXPECT_CALL(*mock_iso_manager_, RemoveIsoDataPath).Times(0); EXPECT_CALL(*(sm_callbacks_.get()), - OnStateMachineEvent(broadcast_id, - BroadcastStateMachine::State::CONFIGURING, _)) - .Times(1); + OnStateMachineEvent(broadcast_id, BroadcastStateMachine::State::CONFIGURING, _)) + .Times(1); EXPECT_CALL(*(sm_callbacks_.get()), - OnStateMachineEvent(broadcast_id, - BroadcastStateMachine::State::STREAMING, _)) - .Times(1); - broadcasts_[broadcast_id]->ProcessMessage( - BroadcastStateMachine::Message::START); - - ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), - BroadcastStateMachine::State::STREAMING); + OnStateMachineEvent(broadcast_id, BroadcastStateMachine::State::STREAMING, _)) + .Times(1); + broadcasts_[broadcast_id]->ProcessMessage(BroadcastStateMachine::Message::START); + + ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), BroadcastStateMachine::State::STREAMING); } TEST_F(StateMachineTest, ProcessMessageStopWhenStopped) { - auto broadcast_id = InstantiateStateMachine( - bluetooth::le_audio::types::LeAudioContextType::MEDIA); + auto broadcast_id = + InstantiateStateMachine(bluetooth::le_audio::types::LeAudioContextType::MEDIA); - broadcasts_[broadcast_id]->ProcessMessage( - BroadcastStateMachine::Message::STOP); - ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), - BroadcastStateMachine::State::STOPPED); + broadcasts_[broadcast_id]->ProcessMessage(BroadcastStateMachine::Message::STOP); + ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), BroadcastStateMachine::State::STOPPED); EXPECT_CALL(*mock_iso_manager_, SetupIsoDataPath).Times(0); EXPECT_CALL(*mock_iso_manager_, RemoveIsoDataPath).Times(0); - EXPECT_CALL(*(sm_callbacks_.get()), OnStateMachineEvent(broadcast_id, _, _)) - .Times(0); - broadcasts_[broadcast_id]->ProcessMessage( - BroadcastStateMachine::Message::STOP); + EXPECT_CALL(*(sm_callbacks_.get()), OnStateMachineEvent(broadcast_id, _, _)).Times(0); + broadcasts_[broadcast_id]->ProcessMessage(BroadcastStateMachine::Message::STOP); // There shall be no change in state - ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), - BroadcastStateMachine::State::STOPPED); + ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), BroadcastStateMachine::State::STOPPED); } TEST_F(StateMachineTest, ProcessMessageSuspendWhenStopped) { - auto broadcast_id = InstantiateStateMachine( - bluetooth::le_audio::types::LeAudioContextType::MEDIA); + auto broadcast_id = + InstantiateStateMachine(bluetooth::le_audio::types::LeAudioContextType::MEDIA); - broadcasts_[broadcast_id]->ProcessMessage( - BroadcastStateMachine::Message::STOP); - ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), - BroadcastStateMachine::State::STOPPED); + broadcasts_[broadcast_id]->ProcessMessage(BroadcastStateMachine::Message::STOP); + ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), BroadcastStateMachine::State::STOPPED); EXPECT_CALL(*mock_iso_manager_, SetupIsoDataPath).Times(0); EXPECT_CALL(*mock_iso_manager_, RemoveIsoDataPath).Times(0); - EXPECT_CALL(*(sm_callbacks_.get()), OnStateMachineEvent(broadcast_id, _, _)) - .Times(0); - broadcasts_[broadcast_id]->ProcessMessage( - BroadcastStateMachine::Message::SUSPEND); + EXPECT_CALL(*(sm_callbacks_.get()), OnStateMachineEvent(broadcast_id, _, _)).Times(0); + broadcasts_[broadcast_id]->ProcessMessage(BroadcastStateMachine::Message::SUSPEND); // There shall be no change in state - ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), - BroadcastStateMachine::State::STOPPED); + ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), BroadcastStateMachine::State::STOPPED); } TEST_F(StateMachineTest, OnSetupIsoDataPathError) { - EXPECT_CALL(*(sm_callbacks_.get()), OnStateMachineCreateStatus(_, true)) - .Times(1); + EXPECT_CALL(*(sm_callbacks_.get()), OnStateMachineCreateStatus(_, true)).Times(1); - auto broadcast_id = InstantiateStateMachine( - bluetooth::le_audio::types::LeAudioContextType::MEDIA); - ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), - BroadcastStateMachine::State::CONFIGURED); + auto broadcast_id = + InstantiateStateMachine(bluetooth::le_audio::types::LeAudioContextType::MEDIA); + ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), BroadcastStateMachine::State::CONFIGURED); EXPECT_CALL(*mock_iso_manager_, SetupIsoDataPath) - .WillOnce([this](uint16_t conn_handle, iso_data_path_params p) { - // Get the big_id encoded in conn_handle's MSB - uint8_t big_id = conn_handle >> 8; - auto bit = - std::find_if(broadcasts_.begin(), broadcasts_.end(), - [big_id](auto const& entry) { - return entry.second->GetAdvertisingSid() == big_id; - }); - if (bit == broadcasts_.end()) return; - bit->second->OnSetupIsoDataPath(0, conn_handle); - }) - .WillOnce([this](uint16_t conn_handle, iso_data_path_params p) { - // Get the big_id encoded in conn_handle's MSB - uint8_t big_id = conn_handle >> 8; - auto bit = - std::find_if(broadcasts_.begin(), broadcasts_.end(), - [big_id](auto const& entry) { - return entry.second->GetAdvertisingSid() == big_id; - }); - if (bit == broadcasts_.end()) return; - bit->second->OnSetupIsoDataPath(1, conn_handle); - }) - .RetiresOnSaturation(); - broadcasts_[broadcast_id]->ProcessMessage( - BroadcastStateMachine::Message::START); + .WillOnce([this](uint16_t conn_handle, iso_data_path_params p) { + // Get the big_id encoded in conn_handle's MSB + uint8_t big_id = conn_handle >> 8; + auto bit = std::find_if(broadcasts_.begin(), broadcasts_.end(), + [big_id](auto const& entry) { + return entry.second->GetAdvertisingSid() == big_id; + }); + if (bit == broadcasts_.end()) { + return; + } + bit->second->OnSetupIsoDataPath(0, conn_handle); + }) + .WillOnce([this](uint16_t conn_handle, iso_data_path_params p) { + // Get the big_id encoded in conn_handle's MSB + uint8_t big_id = conn_handle >> 8; + auto bit = std::find_if(broadcasts_.begin(), broadcasts_.end(), + [big_id](auto const& entry) { + return entry.second->GetAdvertisingSid() == big_id; + }); + if (bit == broadcasts_.end()) { + return; + } + bit->second->OnSetupIsoDataPath(1, conn_handle); + }) + .RetiresOnSaturation(); + broadcasts_[broadcast_id]->ProcessMessage(BroadcastStateMachine::Message::START); // On datapath setup failure we should go back to configured with BIG being // destroyed. Maybe it will work out next time for the new BIG. - ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), - BroadcastStateMachine::State::CONFIGURED); + ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), BroadcastStateMachine::State::CONFIGURED); // And still be able to start again ON_CALL(*mock_iso_manager_, SetupIsoDataPath) - .WillByDefault([this](uint16_t conn_handle, iso_data_path_params p) { - // Get the big_id encoded in conn_handle's MSB - uint8_t big_id = conn_handle >> 8; - auto bit = - std::find_if(broadcasts_.begin(), broadcasts_.end(), - [big_id](auto const& entry) { - return entry.second->GetAdvertisingSid() == big_id; - }); - if (bit == broadcasts_.end()) return; - bit->second->OnSetupIsoDataPath(0, conn_handle); - }); + .WillByDefault([this](uint16_t conn_handle, iso_data_path_params p) { + // Get the big_id encoded in conn_handle's MSB + uint8_t big_id = conn_handle >> 8; + auto bit = std::find_if(broadcasts_.begin(), broadcasts_.end(), + [big_id](auto const& entry) { + return entry.second->GetAdvertisingSid() == big_id; + }); + if (bit == broadcasts_.end()) { + return; + } + bit->second->OnSetupIsoDataPath(0, conn_handle); + }); EXPECT_CALL(*mock_iso_manager_, SetupIsoDataPath).Times(2); - broadcasts_[broadcast_id]->ProcessMessage( - BroadcastStateMachine::Message::START); - ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), - BroadcastStateMachine::State::STREAMING); + broadcasts_[broadcast_id]->ProcessMessage(BroadcastStateMachine::Message::START); + ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), BroadcastStateMachine::State::STREAMING); } TEST_F(StateMachineTest, OnRemoveIsoDataPathError) { - auto broadcast_id = InstantiateStateMachine( - bluetooth::le_audio::types::LeAudioContextType::MEDIA); + auto broadcast_id = + InstantiateStateMachine(bluetooth::le_audio::types::LeAudioContextType::MEDIA); - broadcasts_[broadcast_id]->ProcessMessage( - BroadcastStateMachine::Message::START); - ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), - BroadcastStateMachine::State::STREAMING); + broadcasts_[broadcast_id]->ProcessMessage(BroadcastStateMachine::Message::START); + ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), BroadcastStateMachine::State::STREAMING); EXPECT_CALL(*mock_iso_manager_, RemoveIsoDataPath) - .WillOnce([this](uint16_t conn_handle, uint8_t iso_direction) { - // Get the big_id encoded in conn_handle's MSB - uint8_t big_id = conn_handle >> 8; - auto bit = - std::find_if(broadcasts_.begin(), broadcasts_.end(), - [big_id](auto const& entry) { - return entry.second->GetAdvertisingSid() == big_id; - }); - if (bit == broadcasts_.end()) return; - bit->second->OnRemoveIsoDataPath(0, conn_handle); - }) - .WillOnce([this](uint16_t conn_handle, uint8_t iso_direction) { - // Get the big_id encoded in conn_handle's MSB - uint8_t big_id = conn_handle >> 8; - auto bit = - std::find_if(broadcasts_.begin(), broadcasts_.end(), - [big_id](auto const& entry) { - return entry.second->GetAdvertisingSid() == big_id; - }); - if (bit == broadcasts_.end()) return; - bit->second->OnRemoveIsoDataPath(1, conn_handle); - }) - .RetiresOnSaturation(); - broadcasts_[broadcast_id]->ProcessMessage( - BroadcastStateMachine::Message::SUSPEND); + .WillOnce([this](uint16_t conn_handle, uint8_t iso_direction) { + // Get the big_id encoded in conn_handle's MSB + uint8_t big_id = conn_handle >> 8; + auto bit = std::find_if(broadcasts_.begin(), broadcasts_.end(), + [big_id](auto const& entry) { + return entry.second->GetAdvertisingSid() == big_id; + }); + if (bit == broadcasts_.end()) { + return; + } + bit->second->OnRemoveIsoDataPath(0, conn_handle); + }) + .WillOnce([this](uint16_t conn_handle, uint8_t iso_direction) { + // Get the big_id encoded in conn_handle's MSB + uint8_t big_id = conn_handle >> 8; + auto bit = std::find_if(broadcasts_.begin(), broadcasts_.end(), + [big_id](auto const& entry) { + return entry.second->GetAdvertisingSid() == big_id; + }); + if (bit == broadcasts_.end()) { + return; + } + bit->second->OnRemoveIsoDataPath(1, conn_handle); + }) + .RetiresOnSaturation(); + broadcasts_[broadcast_id]->ProcessMessage(BroadcastStateMachine::Message::SUSPEND); // On datapath teardown failure we should stay in CONFIGURED with BIG being // destroyed. - ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), - BroadcastStateMachine::State::CONFIGURED); + ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), BroadcastStateMachine::State::CONFIGURED); // And still be able to start again - broadcasts_[broadcast_id]->ProcessMessage( - BroadcastStateMachine::Message::START); - ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), - BroadcastStateMachine::State::STREAMING); + broadcasts_[broadcast_id]->ProcessMessage(BroadcastStateMachine::Message::START); + ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), BroadcastStateMachine::State::STREAMING); } TEST_F(StateMachineTest, GetConfig) { - EXPECT_CALL(*(sm_callbacks_.get()), OnStateMachineCreateStatus(_, true)) - .Times(1); + EXPECT_CALL(*(sm_callbacks_.get()), OnStateMachineCreateStatus(_, true)).Times(1); auto sound_context = bluetooth::le_audio::types::LeAudioContextType::MEDIA; uint8_t num_channels = 2; auto broadcast_id = InstantiateStateMachine(sound_context); - ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), - BroadcastStateMachine::State::CONFIGURED); + ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), BroadcastStateMachine::State::CONFIGURED); - std::optional const& big_cfg = - broadcasts_[broadcast_id]->GetBigConfig(); + std::optional const& big_cfg = broadcasts_[broadcast_id]->GetBigConfig(); ASSERT_FALSE(big_cfg.has_value()); - broadcasts_[broadcast_id]->ProcessMessage( - BroadcastStateMachine::Message::START); - ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), - BroadcastStateMachine::State::STREAMING); + broadcasts_[broadcast_id]->ProcessMessage(BroadcastStateMachine::Message::START); + ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), BroadcastStateMachine::State::STREAMING); ASSERT_TRUE(big_cfg.has_value()); ASSERT_EQ(big_cfg->status, 0); @@ -996,34 +874,29 @@ TEST_F(StateMachineTest, GetConfig) { } TEST_F(StateMachineTest, GetBroadcastId) { - EXPECT_CALL(*(sm_callbacks_.get()), OnStateMachineCreateStatus(_, true)) - .Times(1); + EXPECT_CALL(*(sm_callbacks_.get()), OnStateMachineCreateStatus(_, true)).Times(1); auto broadcast_id = InstantiateStateMachine(); ASSERT_NE(bluetooth::le_audio::kBroadcastIdInvalid, broadcast_id); - ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), - BroadcastStateMachine::State::CONFIGURED); + ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), BroadcastStateMachine::State::CONFIGURED); } TEST_F(StateMachineTest, IsPublicBroadcast) { - EXPECT_CALL(*(sm_callbacks_.get()), OnStateMachineCreateStatus(_, true)) - .Times(1); + EXPECT_CALL(*(sm_callbacks_.get()), OnStateMachineCreateStatus(_, true)).Times(1); auto broadcast_id = InstantiateStateMachine(); ASSERT_EQ(broadcasts_[broadcast_id]->IsPublicBroadcast(), true); } TEST_F(StateMachineTest, GetBroadcastName) { - EXPECT_CALL(*(sm_callbacks_.get()), OnStateMachineCreateStatus(_, true)) - .Times(1); + EXPECT_CALL(*(sm_callbacks_.get()), OnStateMachineCreateStatus(_, true)).Times(1); auto broadcast_id = InstantiateStateMachine(); ASSERT_EQ(broadcasts_[broadcast_id]->GetBroadcastName(), test_broadcast_name); } TEST_F(StateMachineTest, GetBroadcastAnnouncement) { - EXPECT_CALL(*(sm_callbacks_.get()), OnStateMachineCreateStatus(_, true)) - .Times(1); + EXPECT_CALL(*(sm_callbacks_.get()), OnStateMachineCreateStatus(_, true)).Times(1); auto broadcast_id = InstantiateStateMachine(); std::map> metadata = {}; @@ -1031,28 +904,23 @@ TEST_F(StateMachineTest, GetBroadcastAnnouncement) { auto announcement = prepareAnnouncement(codec_config, metadata); broadcasts_[broadcast_id]->UpdateBroadcastAnnouncement(announcement); - ASSERT_EQ(announcement, - broadcasts_[broadcast_id]->GetBroadcastAnnouncement()); + ASSERT_EQ(announcement, broadcasts_[broadcast_id]->GetBroadcastAnnouncement()); } TEST_F(StateMachineTest, GetPublicBroadcastAnnouncement) { - EXPECT_CALL(*(sm_callbacks_.get()), OnStateMachineCreateStatus(_, true)) - .Times(1); + EXPECT_CALL(*(sm_callbacks_.get()), OnStateMachineCreateStatus(_, true)).Times(1); auto broadcast_id = InstantiateStateMachine(); bool is_public_metadata_valid; types::LeAudioLtvMap public_ltv = types::LeAudioLtvMap::Parse( - default_public_metadata.data(), default_public_metadata.size(), - is_public_metadata_valid); + default_public_metadata.data(), default_public_metadata.size(), is_public_metadata_valid); bluetooth::le_audio::PublicBroadcastAnnouncementData pb_announcement = { - .features = test_public_broadcast_features, - .metadata = public_ltv.Values()}; + .features = test_public_broadcast_features, .metadata = public_ltv.Values()}; - broadcasts_[broadcast_id]->UpdatePublicBroadcastAnnouncement( - broadcast_id, test_broadcast_name, pb_announcement); + broadcasts_[broadcast_id]->UpdatePublicBroadcastAnnouncement(broadcast_id, test_broadcast_name, + pb_announcement); - ASSERT_EQ(pb_announcement, - broadcasts_[broadcast_id]->GetPublicBroadcastAnnouncement()); + ASSERT_EQ(pb_announcement, broadcasts_[broadcast_id]->GetPublicBroadcastAnnouncement()); } TEST_F(StateMachineTest, AnnouncementTest) { @@ -1061,34 +929,31 @@ TEST_F(StateMachineTest, AnnouncementTest) { std::vector p_data; EXPECT_CALL(*mock_ble_advertising_manager_, StartAdvertisingSet) - .WillOnce([this, &p_data, &a_data, &adv_params]( - uint8_t client_id, int reg_id, - BleAdvertiserInterface::IdTxPowerStatusCallback register_cb, - AdvertiseParameters params, - std::vector advertise_data, - std::vector scan_response_data, - PeriodicAdvertisingParameters periodic_params, - std::vector periodic_data, uint16_t duration, - uint8_t maxExtAdvEvents, - BleAdvertiserInterface::IdStatusCallback timeout_cb) { - uint8_t advertiser_id = 1; - uint8_t tx_power = 0; - uint8_t status = 0; - - // Since we are not using these buffers in this callback it is safe to - // move them. - a_data = std::move(advertise_data); - p_data = std::move(periodic_data); - - adv_params = params; - - this->adv_callbacks_->OnAdvertisingSetStarted( - BroadcastStateMachine::kLeAudioBroadcastRegId, advertiser_id, - tx_power, status); - }); + .WillOnce([this, &p_data, &a_data, &adv_params]( + uint8_t client_id, int reg_id, + BleAdvertiserInterface::IdTxPowerStatusCallback register_cb, + AdvertiseParameters params, std::vector advertise_data, + std::vector scan_response_data, + PeriodicAdvertisingParameters periodic_params, + std::vector periodic_data, uint16_t duration, + uint8_t maxExtAdvEvents, + BleAdvertiserInterface::IdStatusCallback timeout_cb) { + uint8_t advertiser_id = 1; + uint8_t tx_power = 0; + uint8_t status = 0; - EXPECT_CALL(*(sm_callbacks_.get()), OnStateMachineCreateStatus(_, true)) - .Times(1); + // Since we are not using these buffers in this callback it is safe to + // move them. + a_data = std::move(advertise_data); + p_data = std::move(periodic_data); + + adv_params = params; + + this->adv_callbacks_->OnAdvertisingSetStarted( + BroadcastStateMachine::kLeAudioBroadcastRegId, advertiser_id, tx_power, status); + }); + + EXPECT_CALL(*(sm_callbacks_.get()), OnStateMachineCreateStatus(_, true)).Times(1); auto broadcast_id = InstantiateStateMachine(); ASSERT_NE(broadcast_id, BroadcastStateMachine::kAdvSidUndefined); @@ -1097,8 +962,7 @@ TEST_F(StateMachineTest, AnnouncementTest) { ASSERT_NE(a_data[0], 0); // size ASSERT_EQ(a_data[1], 0x16); // BTM_BLE_AD_TYPE_SERVICE_DATA_TYPE ASSERT_EQ(a_data[2], (kBroadcastAudioAnnouncementServiceUuid & 0x00FF)); - ASSERT_EQ(a_data[3], - ((kBroadcastAudioAnnouncementServiceUuid >> 8) & 0x00FF)); + ASSERT_EQ(a_data[3], ((kBroadcastAudioAnnouncementServiceUuid >> 8) & 0x00FF)); ASSERT_EQ(a_data[4], (broadcast_id & 0x0000FF)); ASSERT_EQ(a_data[5], ((broadcast_id >> 8) & 0x0000FF)); ASSERT_EQ(a_data[6], ((broadcast_id >> 16) & 0x0000FF)); @@ -1106,8 +970,7 @@ TEST_F(StateMachineTest, AnnouncementTest) { ASSERT_NE(a_data[7], 0); // size ASSERT_EQ(a_data[8], 0x16); // BTM_BLE_AD_TYPE_SERVICE_DATA_TYPE ASSERT_EQ(a_data[9], (kPublicBroadcastAnnouncementServiceUuid & 0x00FF)); - ASSERT_EQ(a_data[10], - ((kPublicBroadcastAnnouncementServiceUuid >> 8) & 0x00FF)); + ASSERT_EQ(a_data[10], ((kPublicBroadcastAnnouncementServiceUuid >> 8) & 0x00FF)); // Check periodic data for Basic Announcement UUID ASSERT_NE(p_data[0], 0); // size @@ -1116,8 +979,7 @@ TEST_F(StateMachineTest, AnnouncementTest) { ASSERT_EQ(p_data[3], ((kBasicAudioAnnouncementServiceUuid >> 8) & 0x00FF)); // Check advertising parameters - ASSERT_EQ(adv_params.own_address_type, - BroadcastStateMachine::kBroadcastAdvertisingType); + ASSERT_EQ(adv_params.own_address_type, BroadcastStateMachine::kBroadcastAdvertisingType); } TEST_F(StateMachineTest, GetMetadataBeforeGettingAddress) { @@ -1126,17 +988,15 @@ TEST_F(StateMachineTest, GetMetadataBeforeGettingAddress) { BleAdvertiserInterface::GetAddressCallback cb; /* Address should be already known after notifying callback recipients */ - EXPECT_CALL( - *(sm_callbacks_.get()), - OnStateMachineEvent(_, BroadcastStateMachine::State::CONFIGURED, _)) - .WillOnce([this](uint32_t broadcast_id, - BroadcastStateMachine::State state, const void* data) { - RawAddress test_address; - - RawAddress::FromString("00:00:00:00:00:00", test_address); - ASSERT_NE(test_address, - this->broadcasts_[broadcast_id]->GetOwnAddress()); - }); + EXPECT_CALL(*(sm_callbacks_.get()), + OnStateMachineEvent(_, BroadcastStateMachine::State::CONFIGURED, _)) + .WillOnce([this](uint32_t broadcast_id, BroadcastStateMachine::State state, + const void* data) { + RawAddress test_address; + + RawAddress::FromString("00:00:00:00:00:00", test_address); + ASSERT_NE(test_address, this->broadcasts_[broadcast_id]->GetOwnAddress()); + }); broadcast_id = InstantiateStateMachine(); ASSERT_NE(broadcast_id, 0u); diff --git a/system/bta/le_audio/client.cc b/system/bta/le_audio/client.cc index 04d871ee72f..ef291bb9725 100644 --- a/system/bta/le_audio/client.cc +++ b/system/bta/le_audio/client.cc @@ -127,8 +127,7 @@ enum class AudioState { RELEASING, }; -std::ostream& operator<<(std::ostream& os, - const AudioReconfigurationResult& state) { +std::ostream& operator<<(std::ostream& os, const AudioReconfigurationResult& state) { switch (state) { case AudioReconfigurationResult::RECONFIGURATION_NEEDED: os << "RECONFIGURATION_NEEDED"; @@ -178,8 +177,7 @@ struct formatter : ostream_formatter {}; namespace { void le_audio_gattc_callback(tBTA_GATTC_EVT event, tBTA_GATTC* p_data); -static void le_audio_health_status_callback(const RawAddress& addr, - int group_id, +static void le_audio_health_status_callback(const RawAddress& addr, int group_id, LeAudioHealthBasedAction action); class LeAudioClientImpl; @@ -223,23 +221,21 @@ LeAudioIsoDataCallback* iso_data_callback; * for test purposes. */ class LeAudioClientImpl : public LeAudioClient { - public: +public: ~LeAudioClientImpl() { alarm_free(close_vbc_timeout_); alarm_free(disable_timer_); alarm_free(suspend_timeout_); - }; + } - LeAudioClientImpl( - bluetooth::le_audio::LeAudioClientCallbacks* callbacks_, - LeAudioGroupStateMachine::Callbacks* state_machine_callbacks_, - base::Closure initCb) + LeAudioClientImpl(bluetooth::le_audio::LeAudioClientCallbacks* callbacks_, + LeAudioGroupStateMachine::Callbacks* state_machine_callbacks_, + base::Closure initCb) : gatt_if_(0), callbacks_(callbacks_), active_group_id_(bluetooth::groups::kGroupUnknown), configuration_context_type_(LeAudioContextType::UNINITIALIZED), - local_metadata_context_types_( - {.sink = AudioContexts(), .source = AudioContexts()}), + local_metadata_context_types_({.sink = AudioContexts(), .source = AudioContexts()}), stream_setup_start_timestamp_(0), stream_setup_end_timestamp_(0), audio_receiver_state_(AudioState::IDLE), @@ -257,8 +253,7 @@ class LeAudioClientImpl : public LeAudioClient { LeAudioGroupStateMachine::Initialize(state_machine_callbacks_); groupStateMachine_ = LeAudioGroupStateMachine::Get(); - if (bluetooth::common::InitFlags:: - IsTargetedAnnouncementReconnectionMode()) { + if (bluetooth::common::InitFlags::IsTargetedAnnouncementReconnectionMode()) { log::info("Reconnection mode: TARGETED_ANNOUNCEMENTS"); reconnection_mode_ = BTM_BLE_BKG_CONNECT_TARGETED_ANNOUNCEMENTS; } else { @@ -268,23 +263,21 @@ class LeAudioClientImpl : public LeAudioClient { log::info("Loading health status module"); leAudioHealthStatus_ = LeAudioHealthStatus::Get(); - leAudioHealthStatus_->RegisterCallback( - base::BindRepeating(le_audio_health_status_callback)); + leAudioHealthStatus_->RegisterCallback(base::BindRepeating(le_audio_health_status_callback)); BTA_GATTC_AppRegister( - le_audio_gattc_callback, - base::Bind( - [](base::Closure initCb, uint8_t client_id, uint8_t status) { - if (status != GATT_SUCCESS) { - log::error( - "Can't start LeAudio profile - no gatt clients left!"); - return; - } - instance->gatt_if_ = client_id; - initCb.Run(); - }, - initCb), - true); + le_audio_gattc_callback, + base::Bind( + [](base::Closure initCb, uint8_t client_id, uint8_t status) { + if (status != GATT_SUCCESS) { + log::error("Can't start LeAudio profile - no gatt clients left!"); + return; + } + instance->gatt_if_ = client_id; + initCb.Run(); + }, + initCb), + true); DeviceGroups::Get()->Initialize(device_group_callbacks); } @@ -314,28 +307,23 @@ class LeAudioClientImpl : public LeAudioClient { if ((configuration_context_type_ != LeAudioContextType::MEDIA) && (configuration_context_type_ != LeAudioContextType::GAME)) { - log::info( - "Keeping the old configuration as no HQ Media playback is needed " - "right now."); + log::info("Keeping the old configuration as no HQ Media playback is needed right now."); return; } /* Test the existing metadata against the recent availability */ - local_metadata_context_types_.source &= group->GetAvailableContexts( - bluetooth::le_audio::types::kLeAudioDirectionSink); + local_metadata_context_types_.source &= + group->GetAvailableContexts(bluetooth::le_audio::types::kLeAudioDirectionSink); if (local_metadata_context_types_.source.none()) { log::warn("invalid/unknown context metadata, using 'MEDIA' instead"); - local_metadata_context_types_.source = - AudioContexts(LeAudioContextType::MEDIA); + local_metadata_context_types_.source = AudioContexts(LeAudioContextType::MEDIA); } /* Choose the right configuration context */ auto new_configuration_context = AdjustForVoiceAssistant( - group, - ChooseConfigurationContextType(local_metadata_context_types_.source)); + group, ChooseConfigurationContextType(local_metadata_context_types_.source)); - log::debug("new_configuration_context= {}", - ToString(new_configuration_context)); + log::debug("new_configuration_context= {}", ToString(new_configuration_context)); ReconfigureOrUpdateMetadata(group, new_configuration_context, {.sink = local_metadata_context_types_.source, .source = local_metadata_context_types_.sink}); @@ -347,15 +335,16 @@ class LeAudioClientImpl : public LeAudioClient { } static const uint64_t timeoutMs = 2000; - log::debug("Start VBC close timeout with {} ms", - static_cast(timeoutMs)); + log::debug("Start VBC close timeout with {} ms", static_cast(timeoutMs)); alarm_set_on_mloop( - close_vbc_timeout_, timeoutMs, - [](void*) { - if (instance) instance->ReconfigureAfterVbcClose(); - }, - nullptr); + close_vbc_timeout_, timeoutMs, + [](void*) { + if (instance) { + instance->ReconfigureAfterVbcClose(); + } + }, + nullptr); } void StopVbcCloseTimeout() { @@ -374,28 +363,28 @@ class LeAudioClientImpl : public LeAudioClient { * to upper layer */ - if (leAudioDevice->notify_connected_after_read_ && - (i == (ases_num - 1))) { - notify_flag_ptr = - INT_TO_PTR(leAudioDevice->notify_connected_after_read_); + if (leAudioDevice->notify_connected_after_read_ && (i == (ases_num - 1))) { + notify_flag_ptr = INT_TO_PTR(leAudioDevice->notify_connected_after_read_); } BtaGattQueue::ReadCharacteristic(leAudioDevice->conn_id_, - leAudioDevice->ases_[i].hdls.val_hdl, - OnGattReadRspStatic, notify_flag_ptr); + leAudioDevice->ases_[i].hdls.val_hdl, OnGattReadRspStatic, + notify_flag_ptr); } } - void OnGroupAddedCb(const RawAddress& address, const bluetooth::Uuid& uuid, - int group_id) { - log::info("address: {} group uuid {} group_id: {}", address, uuid, - group_id); + void OnGroupAddedCb(const RawAddress& address, const bluetooth::Uuid& uuid, int group_id) { + log::info("address: {} group uuid {} group_id: {}", address, uuid, group_id); /* We are interested in the groups which are in the context of CAP */ - if (uuid != bluetooth::le_audio::uuid::kCapServiceUuid) return; + if (uuid != bluetooth::le_audio::uuid::kCapServiceUuid) { + return; + } LeAudioDevice* leAudioDevice = leAudioDevices_.FindByAddress(address); - if (!leAudioDevice) return; + if (!leAudioDevice) { + return; + } if (leAudioDevice->group_id_ != bluetooth::groups::kGroupUnknown) { log::info("group already set: {}", leAudioDevice->group_id_); return; @@ -425,15 +414,17 @@ class LeAudioClientImpl : public LeAudioClient { } LeAudioDevice* leAudioDevice = leAudioDevices_.FindByAddress(address); - if (!leAudioDevice) return; + if (!leAudioDevice) { + return; + } if (leAudioDevice->group_id_ != bluetooth::groups::kGroupUnknown) { log::info("group already set: {}", leAudioDevice->group_id_); return; } if (leAudioHealthStatus_) { - leAudioHealthStatus_->AddStatisticForDevice( - leAudioDevice, LeAudioHealthDeviceStatType::VALID_CSIS); + leAudioHealthStatus_->AddStatisticForDevice(leAudioDevice, + LeAudioHealthDeviceStatType::VALID_CSIS); } group_add_node(group_id, address); @@ -443,17 +434,17 @@ class LeAudioClientImpl : public LeAudioClient { log::info("address: {} group_id: {}", address, group_id); LeAudioDevice* leAudioDevice = leAudioDevices_.FindByAddress(address); - if (!leAudioDevice) return; + if (!leAudioDevice) { + return; + } if (leAudioDevice->group_id_ != group_id) { - log::warn("Device: {} not assigned to the group.", - leAudioDevice->address_); + log::warn("Device: {} not assigned to the group.", leAudioDevice->address_); return; } LeAudioDeviceGroup* group = aseGroups_.FindById(group_id); if (group == NULL) { - log::info("device not in the group: {}, {}", leAudioDevice->address_, - group_id); + log::info("device not in the group: {}, {}", leAudioDevice->address_, group_id); return; } @@ -481,24 +472,24 @@ class LeAudioClientImpl : public LeAudioClient { } bool check_if_recovery_needed = - group->GetTargetState() == AseState::BTA_LE_AUDIO_ASE_STATE_IDLE; + group->GetTargetState() == AseState::BTA_LE_AUDIO_ASE_STATE_IDLE; if (leAudioHealthStatus_) { leAudioHealthStatus_->AddStatisticForGroup( - group, LeAudioHealthGroupStatType::STREAM_CREATE_SIGNALING_FAILED); + group, LeAudioHealthGroupStatType::STREAM_CREATE_SIGNALING_FAILED); } log::error( - "State not achieved on time for group: group id {}, current state {}, " - "target state: {}, check_if_recovery_needed: {}", - group_id, ToString(group->GetState()), - ToString(group->GetTargetState()), check_if_recovery_needed); + "State not achieved on time for group: group id {}, current state {}, " + "target state: {}, check_if_recovery_needed: {}", + group_id, ToString(group->GetState()), ToString(group->GetTargetState()), + check_if_recovery_needed); group->SetTargetState(AseState::BTA_LE_AUDIO_ASE_STATE_IDLE); group->ClearAllCises(); group->PrintDebugState(); /* There is an issue with a setting up stream or any other operation which - * are gatt operations. It means peer is not responsable. Lets close ACL + * are gatt operations. It means peer is not responsible. Lets close ACL */ CancelStreamingRequest(); LeAudioDevice* leAudioDevice = group->GetFirstActiveDevice(); @@ -506,8 +497,7 @@ class LeAudioClientImpl : public LeAudioClient { log::error("Shouldn't be called without an active device."); leAudioDevice = group->GetFirstDevice(); if (leAudioDevice == nullptr) { - log::error("Front device is null. Number of devices: {}", - group->Size()); + log::error("Front device is null. Number of devices: {}", group->Size()); return; } } @@ -538,8 +528,7 @@ class LeAudioClientImpl : public LeAudioClient { } } - void UpdateLocationsAndContextsAvailability(LeAudioDeviceGroup* group, - bool force = false) { + void UpdateLocationsAndContextsAvailability(LeAudioDeviceGroup* group, bool force = false) { bool group_conf_changed = group->ReloadAudioLocations(); group_conf_changed |= group->ReloadAudioDirections(); group_conf_changed |= group->UpdateAudioContextAvailability(); @@ -547,48 +536,43 @@ class LeAudioClientImpl : public LeAudioClient { /* All the configurations should be recalculated for the new conditions */ group->InvalidateCachedConfigurations(); group->InvalidateGroupStrategy(); - callbacks_->OnAudioConf(group->audio_directions_, group->group_id_, - group->snk_audio_locations_.to_ulong(), - group->src_audio_locations_.to_ulong(), - group->GetAvailableContexts().value()); + callbacks_->OnAudioConf( + group->audio_directions_, group->group_id_, group->snk_audio_locations_.to_ulong(), + group->src_audio_locations_.to_ulong(), group->GetAvailableContexts().value()); } } void SuspendedForReconfiguration() { if (audio_sender_state_ > AudioState::IDLE) { - LeAudioLogHistory::Get()->AddLogHistory( - kLogBtCallAf, active_group_id_, RawAddress::kEmpty, - kLogAfSuspendForReconfig + "LocalSource", - "r_state: " + ToString(audio_receiver_state_) + - "s_state: " + ToString(audio_sender_state_)); + LeAudioLogHistory::Get()->AddLogHistory(kLogBtCallAf, active_group_id_, RawAddress::kEmpty, + kLogAfSuspendForReconfig + "LocalSource", + "r_state: " + ToString(audio_receiver_state_) + + "s_state: " + ToString(audio_sender_state_)); le_audio_source_hal_client_->SuspendedForReconfiguration(); } if (audio_receiver_state_ > AudioState::IDLE) { - LeAudioLogHistory::Get()->AddLogHistory( - kLogBtCallAf, active_group_id_, RawAddress::kEmpty, - kLogAfSuspendForReconfig + "LocalSink", - "r_state: " + ToString(audio_receiver_state_) + - "s_state: " + ToString(audio_sender_state_)); + LeAudioLogHistory::Get()->AddLogHistory(kLogBtCallAf, active_group_id_, RawAddress::kEmpty, + kLogAfSuspendForReconfig + "LocalSink", + "r_state: " + ToString(audio_receiver_state_) + + "s_state: " + ToString(audio_sender_state_)); le_audio_sink_hal_client_->SuspendedForReconfiguration(); } } void ReconfigurationComplete(uint8_t directions) { if (directions & bluetooth::le_audio::types::kLeAudioDirectionSink) { - LeAudioLogHistory::Get()->AddLogHistory( - kLogBtCallAf, active_group_id_, RawAddress::kEmpty, - kLogAfReconfigComplete + "LocalSource", - "r_state: " + ToString(audio_receiver_state_) + - "s_state: " + ToString(audio_sender_state_)); + LeAudioLogHistory::Get()->AddLogHistory(kLogBtCallAf, active_group_id_, RawAddress::kEmpty, + kLogAfReconfigComplete + "LocalSource", + "r_state: " + ToString(audio_receiver_state_) + + "s_state: " + ToString(audio_sender_state_)); le_audio_source_hal_client_->ReconfigurationComplete(); } if (directions & bluetooth::le_audio::types::kLeAudioDirectionSource) { - LeAudioLogHistory::Get()->AddLogHistory( - kLogBtCallAf, active_group_id_, RawAddress::kEmpty, - kLogAfReconfigComplete + "LocalSink", - "r_state: " + ToString(audio_receiver_state_) + - "s_state: " + ToString(audio_sender_state_)); + LeAudioLogHistory::Get()->AddLogHistory(kLogBtCallAf, active_group_id_, RawAddress::kEmpty, + kLogAfReconfigComplete + "LocalSink", + "r_state: " + ToString(audio_receiver_state_) + + "s_state: " + ToString(audio_sender_state_)); le_audio_sink_hal_client_->ReconfigurationComplete(); } @@ -597,10 +581,9 @@ class LeAudioClientImpl : public LeAudioClient { void CancelLocalAudioSourceStreamingRequest() { le_audio_source_hal_client_->CancelStreamingRequest(); - LeAudioLogHistory::Get()->AddLogHistory( - kLogBtCallAf, active_group_id_, RawAddress::kEmpty, - kLogAfCancel + "LocalSource", - "s_state: " + ToString(audio_sender_state_)); + LeAudioLogHistory::Get()->AddLogHistory(kLogBtCallAf, active_group_id_, RawAddress::kEmpty, + kLogAfCancel + "LocalSource", + "s_state: " + ToString(audio_sender_state_)); audio_sender_state_ = AudioState::IDLE; } @@ -608,10 +591,9 @@ class LeAudioClientImpl : public LeAudioClient { void CancelLocalAudioSinkStreamingRequest() { le_audio_sink_hal_client_->CancelStreamingRequest(); - LeAudioLogHistory::Get()->AddLogHistory( - kLogBtCallAf, active_group_id_, RawAddress::kEmpty, - kLogAfCancel + "LocalSink", - "s_state: " + ToString(audio_receiver_state_)); + LeAudioLogHistory::Get()->AddLogHistory(kLogBtCallAf, active_group_id_, RawAddress::kEmpty, + kLogAfCancel + "LocalSink", + "s_state: " + ToString(audio_receiver_state_)); audio_receiver_state_ = AudioState::IDLE; } @@ -636,10 +618,11 @@ class LeAudioClientImpl : public LeAudioClient { /* TODO This part possible to remove as this is to handle adding device to * the group which is unknown and not connected. */ - log::info("leAudioDevice unknown , address: {} group: 0x{:x}", address, - group_id); + log::info("leAudioDevice unknown , address: {} group: 0x{:x}", address, group_id); - if (group_id == bluetooth::groups::kGroupUnknown) return; + if (group_id == bluetooth::groups::kGroupUnknown) { + return; + } log::info("Set member adding ..."); leAudioDevices_.Add(address, DeviceConnectState::CONNECTING_BY_USER); @@ -650,12 +633,10 @@ class LeAudioClientImpl : public LeAudioClient { } } - auto id = DeviceGroups::Get()->GetGroupId( - address, bluetooth::le_audio::uuid::kCapServiceUuid); + auto id = DeviceGroups::Get()->GetGroupId(address, bluetooth::le_audio::uuid::kCapServiceUuid); if (group_id == bluetooth::groups::kGroupUnknown) { if (id == bluetooth::groups::kGroupUnknown) { - DeviceGroups::Get()->AddDevice( - address, bluetooth::le_audio::uuid::kCapServiceUuid); + DeviceGroups::Get()->AddDevice(address, bluetooth::le_audio::uuid::kCapServiceUuid); /* We will get back here when group will be created */ return; } @@ -666,33 +647,35 @@ class LeAudioClientImpl : public LeAudioClient { return; } } else { - log::assert_that(id == group_id, - "group id missmatch? leaudio id: {}, groups module {}", + log::assert_that(id == group_id, "group id missmatch? leaudio id: {}, groups module {}", group_id, id); new_group = aseGroups_.FindById(group_id); if (!new_group) { new_group = aseGroups_.Add(group_id); } else { - if (new_group->IsDeviceInTheGroup(leAudioDevice)) return; + if (new_group->IsDeviceInTheGroup(leAudioDevice)) { + return; + } } } - log::debug("New group {}, id: {}", fmt::ptr(new_group), - new_group->group_id_); + log::debug("New group {}, id: {}", fmt::ptr(new_group), new_group->group_id_); /* If device was in the group and it was not removed by the application, * lets do it now */ - if (old_group) group_remove_node(old_group, address, update_group_module); + if (old_group) { + group_remove_node(old_group, address, update_group_module); + } new_group->AddNode(leAudioDevices_.GetByAddress(address)); - callbacks_->OnGroupNodeStatus(address, new_group->group_id_, - GroupNodeStatus::ADDED); + callbacks_->OnGroupNodeStatus(address, new_group->group_id_, GroupNodeStatus::ADDED); /* If device is connected and added to the group, lets read ASE states */ - if (leAudioDevice->conn_id_ != GATT_INVALID_CONN_ID) + if (leAudioDevice->conn_id_ != GATT_INVALID_CONN_ID) { AseInitialStateReadRequest(leAudioDevice); + } if (leAudioDevice->GetConnectionState() == DeviceConnectState::CONNECTED) { UpdateLocationsAndContextsAvailability(new_group); @@ -700,16 +683,16 @@ class LeAudioClientImpl : public LeAudioClient { } void GroupAddNode(const int group_id, const RawAddress& address) override { - auto id = DeviceGroups::Get()->GetGroupId( - address, bluetooth::le_audio::uuid::kCapServiceUuid); - if (id == group_id) return; + auto id = DeviceGroups::Get()->GetGroupId(address, bluetooth::le_audio::uuid::kCapServiceUuid); + if (id == group_id) { + return; + } if (id != bluetooth::groups::kGroupUnknown) { DeviceGroups::Get()->RemoveDevice(address, id); } - DeviceGroups::Get()->AddDevice( - address, bluetooth::le_audio::uuid::kCapServiceUuid, group_id); + DeviceGroups::Get()->AddDevice(address, bluetooth::le_audio::uuid::kCapServiceUuid, group_id); } void remove_group_if_possible(LeAudioDeviceGroup* group) { @@ -717,11 +700,9 @@ class LeAudioClientImpl : public LeAudioClient { log::debug("group is null"); return; } - log::debug("Group {}, id: {}, size: {}, is cig_state {}", fmt::ptr(group), - group->group_id_, group->Size(), - ToString(group->cig.GetState())); - if (group->IsEmpty() && - (group->cig.GetState() == bluetooth::le_audio::types::CigState::NONE)) { + log::debug("Group {}, id: {}, size: {}, is cig_state {}", fmt::ptr(group), group->group_id_, + group->Size(), ToString(group->cig.GetState())); + if (group->IsEmpty() && (group->cig.GetState() == bluetooth::le_audio::types::CigState::NONE)) { lastNotifiedGroupStreamStatusMap_.erase(group->group_id_); aseGroups_.Remove(group->group_id_); } @@ -733,8 +714,8 @@ class LeAudioClientImpl : public LeAudioClient { group->RemoveNode(leAudioDevices_.GetByAddress(address)); if (update_group_module) { - int groups_group_id = DeviceGroups::Get()->GetGroupId( - address, bluetooth::le_audio::uuid::kCapServiceUuid); + int groups_group_id = + DeviceGroups::Get()->GetGroupId(address, bluetooth::le_audio::uuid::kCapServiceUuid); if (groups_group_id == group_id) { DeviceGroups::Get()->RemoveDevice(address, group_id); } @@ -794,24 +775,18 @@ class LeAudioClientImpl : public LeAudioClient { return metadata_context_type; } - log::debug("Converting to single context type: {}", - metadata_context_type.to_string()); + log::debug("Converting to single context type: {}", metadata_context_type.to_string()); /* Mini policy */ if (metadata_context_type.any()) { LeAudioContextType context_priority_list[] = { - /* Highest priority first */ - LeAudioContextType::CONVERSATIONAL, - LeAudioContextType::RINGTONE, - LeAudioContextType::LIVE, - LeAudioContextType::VOICEASSISTANTS, - LeAudioContextType::GAME, - LeAudioContextType::MEDIA, - LeAudioContextType::EMERGENCYALARM, - LeAudioContextType::ALERTS, - LeAudioContextType::INSTRUCTIONAL, - LeAudioContextType::NOTIFICATIONS, - LeAudioContextType::SOUNDEFFECTS, + /* Highest priority first */ + LeAudioContextType::CONVERSATIONAL, LeAudioContextType::RINGTONE, + LeAudioContextType::LIVE, LeAudioContextType::VOICEASSISTANTS, + LeAudioContextType::GAME, LeAudioContextType::MEDIA, + LeAudioContextType::EMERGENCYALARM, LeAudioContextType::ALERTS, + LeAudioContextType::INSTRUCTIONAL, LeAudioContextType::NOTIFICATIONS, + LeAudioContextType::SOUNDEFFECTS, }; for (auto ct : context_priority_list) { if (metadata_context_type.test(ct)) { @@ -831,8 +806,7 @@ class LeAudioClientImpl : public LeAudioClient { BidirectionalPair remote_contexts) { LeAudioDeviceGroup* group = aseGroups_.FindById(group_id); - log::debug("configuration_context_type= {}", - ToString(configuration_context_type)); + log::debug("configuration_context_type= {}", ToString(configuration_context_type)); log::debug(""); if (configuration_context_type >= LeAudioContextType::RFU) { @@ -863,8 +837,8 @@ class LeAudioClientImpl : public LeAudioClient { * reconfiguration is needed once the group reaches streaming state. */ log::warn( - "Group is already in the transition state. Waiting for the target " - "state to be reached."); + "Group is already in the transition state. Waiting for the target " + "state to be reached."); return false; } @@ -883,39 +857,33 @@ class LeAudioClientImpl : public LeAudioClient { } BidirectionalPair> ccids = { - .sink = ContentControlIdKeeper::GetInstance()->GetAllCcids( - ccid_contexts.sink), - .source = ContentControlIdKeeper::GetInstance()->GetAllCcids( - ccid_contexts.source)}; + .sink = ContentControlIdKeeper::GetInstance()->GetAllCcids(ccid_contexts.sink), + .source = ContentControlIdKeeper::GetInstance()->GetAllCcids(ccid_contexts.source)}; if (group->IsPendingConfiguration()) { - return groupStateMachine_->ConfigureStream( - group, configuration_context_type_, remote_contexts, ccids); - } else if (group->GetState() != - AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) { - stream_setup_start_timestamp_ = - bluetooth::common::time_get_os_boottime_us(); + return groupStateMachine_->ConfigureStream(group, configuration_context_type_, + remote_contexts, ccids); + } else if (group->GetState() != AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) { + stream_setup_start_timestamp_ = bluetooth::common::time_get_os_boottime_us(); } /* If assistant have some connected delegators that needs to be informed * when there would be request to stream unicast. */ - if (com::android::bluetooth::flags:: - leaudio_broadcast_audio_handover_policies() && + if (com::android::bluetooth::flags::leaudio_broadcast_audio_handover_policies() && !sink_monitor_mode_ && source_monitor_mode_ && !group->IsStreaming()) { - callbacks_->OnUnicastMonitorModeStatus( - bluetooth::le_audio::types::kLeAudioDirectionSource, - UnicastMonitorModeStatus::STREAMING_REQUESTED); + callbacks_->OnUnicastMonitorModeStatus(bluetooth::le_audio::types::kLeAudioDirectionSource, + UnicastMonitorModeStatus::STREAMING_REQUESTED); } - bool result = groupStateMachine_->StartStream( - group, configuration_context_type, remote_contexts, ccids); + bool result = groupStateMachine_->StartStream(group, configuration_context_type, + remote_contexts, ccids); return result; } void GroupStream(const int group_id, uint16_t context_type) override { - BidirectionalPair initial_contexts = { - AudioContexts(context_type), AudioContexts(context_type)}; + BidirectionalPair initial_contexts = {AudioContexts(context_type), + AudioContexts(context_type)}; GroupStream(group_id, LeAudioContextType(context_type), initial_contexts); } @@ -933,14 +901,13 @@ class LeAudioClientImpl : public LeAudioClient { } if (group->IsInTransition()) { - log::info(", group is in transition from: {} to: {}", - ToString(group->GetState()), ToString(group->GetTargetState())); + log::info(", group is in transition from: {} to: {}", ToString(group->GetState()), + ToString(group->GetTargetState())); return; } if (group->GetState() != AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) { - log::error(", invalid current state of group: {}", - ToString(group->GetState())); + log::error(", invalid current state of group: {}", ToString(group->GetState())); return; } @@ -962,12 +929,11 @@ class LeAudioClientImpl : public LeAudioClient { if (group->GetState() == AseState::BTA_LE_AUDIO_ASE_STATE_IDLE) { if (group->GetTargetState() != AseState::BTA_LE_AUDIO_ASE_STATE_IDLE) { - log::warn("group {} was about to stream, but got canceled: {}", - group_id, ToString(group->GetTargetState())); + log::warn("group {} was about to stream, but got canceled: {}", group_id, + ToString(group->GetTargetState())); group->SetTargetState(AseState::BTA_LE_AUDIO_ASE_STATE_IDLE); } else { - log::warn(", group {} already stopped: {}", group_id, - ToString(group->GetState())); + log::warn(", group {} already stopped: {}", group_id, ToString(group->GetState())); } return; } @@ -993,18 +959,15 @@ class LeAudioClientImpl : public LeAudioClient { } void SetCodecConfigPreference( - int group_id, - bluetooth::le_audio::btle_audio_codec_config_t input_codec_config, - bluetooth::le_audio::btle_audio_codec_config_t output_codec_config) - override { + int group_id, bluetooth::le_audio::btle_audio_codec_config_t input_codec_config, + bluetooth::le_audio::btle_audio_codec_config_t output_codec_config) override { // TODO Implement } void SetCcidInformation(int ccid, int context_type) override { log::debug("Ccid: {}, context type {}", ccid, context_type); - ContentControlIdKeeper::GetInstance()->SetCcid(AudioContexts(context_type), - ccid); + ContentControlIdKeeper::GetInstance()->SetCcid(AudioContexts(context_type), ccid); } void SetInCall(bool in_call) override { @@ -1027,10 +990,8 @@ class LeAudioClientImpl : public LeAudioClient { } void SetUnicastMonitorMode(uint8_t direction, bool enable) override { - if (!com::android::bluetooth::flags:: - leaudio_broadcast_audio_handover_policies()) { - log::warn( - "Monitor mode is disabled, Set Unicast Monitor mode is ignored"); + if (!com::android::bluetooth::flags::leaudio_broadcast_audio_handover_policies()) { + log::warn("Monitor mode is disabled, Set Unicast Monitor mode is ignored"); return; } @@ -1048,8 +1009,7 @@ class LeAudioClientImpl : public LeAudioClient { log::debug("enable: {}", enable); sink_monitor_mode_ = enable; - } else if (direction == - bluetooth::le_audio::types::kLeAudioDirectionSource) { + } else if (direction == bluetooth::le_audio::types::kLeAudioDirectionSource) { log::debug("enable: {}", enable); source_monitor_mode_ = enable; @@ -1059,34 +1019,30 @@ class LeAudioClientImpl : public LeAudioClient { LeAudioDeviceGroup* group = aseGroups_.FindById(active_group_id_); if (!group) { - callbacks_->OnUnicastMonitorModeStatus( - bluetooth::le_audio::types::kLeAudioDirectionSource, - UnicastMonitorModeStatus::STREAMING_SUSPENDED); + callbacks_->OnUnicastMonitorModeStatus(bluetooth::le_audio::types::kLeAudioDirectionSource, + UnicastMonitorModeStatus::STREAMING_SUSPENDED); return; } if (group->IsStreaming()) { - callbacks_->OnUnicastMonitorModeStatus( - bluetooth::le_audio::types::kLeAudioDirectionSource, - UnicastMonitorModeStatus::STREAMING); + callbacks_->OnUnicastMonitorModeStatus(bluetooth::le_audio::types::kLeAudioDirectionSource, + UnicastMonitorModeStatus::STREAMING); } else { - callbacks_->OnUnicastMonitorModeStatus( - bluetooth::le_audio::types::kLeAudioDirectionSource, - UnicastMonitorModeStatus::STREAMING_SUSPENDED); + callbacks_->OnUnicastMonitorModeStatus(bluetooth::le_audio::types::kLeAudioDirectionSource, + UnicastMonitorModeStatus::STREAMING_SUSPENDED); } } else { log::error("invalid direction: 0x{:02x} monitor mode set", direction); } } - void SendAudioProfilePreferences( - const int group_id, bool is_output_preference_le_audio, - bool is_duplex_preference_le_audio) override { + void SendAudioProfilePreferences(const int group_id, bool is_output_preference_le_audio, + bool is_duplex_preference_le_audio) override { log::info( - "group_id: {}, is_output_preference_le_audio: {}, " - "is_duplex_preference_le_audio: {}", - group_id, is_output_preference_le_audio, is_duplex_preference_le_audio); + "group_id: {}, is_output_preference_le_audio: {}, " + "is_duplex_preference_le_audio: {}", + group_id, is_output_preference_le_audio, is_duplex_preference_le_audio); if (group_id == bluetooth::groups::kGroupUnknown) { log::warn("Unknown group_id"); return; @@ -1103,8 +1059,8 @@ class LeAudioClientImpl : public LeAudioClient { void SetGroupAllowedContextMask(int group_id, int sink_context_types, int source_context_types) override { - log::info("group_id: {}, sink context types: {}, source context types: {}", - group_id, sink_context_types, source_context_types); + log::info("group_id: {}, sink context types: {}, source context types: {}", group_id, + sink_context_types, source_context_types); if (group_id == bluetooth::groups::kGroupUnknown) { log::warn("Unknown group_id"); @@ -1117,8 +1073,8 @@ class LeAudioClientImpl : public LeAudioClient { } BidirectionalPair allowed_contexts = { - .sink = AudioContexts(sink_context_types), - .source = AudioContexts(source_context_types), + .sink = AudioContexts(sink_context_types), + .source = AudioContexts(source_context_types), }; group->SetAllowedContextMask(allowed_contexts); @@ -1131,10 +1087,8 @@ class LeAudioClientImpl : public LeAudioClient { */ log::assert_that(active_group_id_ == bluetooth::groups::kGroupUnknown, "Active group is not set."); - log::assert_that(le_audio_source_hal_client_ != nullptr, - "Source session not acquired"); - log::assert_that(le_audio_sink_hal_client_ != nullptr, - "Sink session not acquired"); + log::assert_that(le_audio_source_hal_client_ != nullptr, "Source session not acquired"); + log::assert_that(le_audio_sink_hal_client_ != nullptr, "Sink session not acquired"); DsaModes dsa_modes = {DsaMode::DISABLED}; if (com::android::bluetooth::flags::leaudio_dynamic_spatial_audio()) { @@ -1155,67 +1109,55 @@ class LeAudioClientImpl : public LeAudioClient { // Scale by the codec frame blocks per SDU if set uint8_t codec_frame_blocks_per_sdu = - group->stream_conf.stream_params.source.codec_frames_blocks_per_sdu - ?: 1; - audio_framework_source_config.data_interval_us = - frame_duration_us * codec_frame_blocks_per_sdu; + group->stream_conf.stream_params.source.codec_frames_blocks_per_sdu ?: 1; + audio_framework_source_config.data_interval_us = frame_duration_us * codec_frame_blocks_per_sdu; - le_audio_source_hal_client_->Start(audio_framework_source_config, - audioSinkReceiver, dsa_modes); + le_audio_source_hal_client_->Start(audio_framework_source_config, audioSinkReceiver, dsa_modes); /* We use same frame duration for sink/source */ - audio_framework_sink_config.data_interval_us = - frame_duration_us * codec_frame_blocks_per_sdu; + audio_framework_sink_config.data_interval_us = frame_duration_us * codec_frame_blocks_per_sdu; /* If group supports more than 16kHz for the microphone in converstional * case let's use that also for Audio Framework. */ auto sink_configuration = group->GetAudioSessionCodecConfigForDirection( - LeAudioContextType::CONVERSATIONAL, - bluetooth::le_audio::types::kLeAudioDirectionSource); + LeAudioContextType::CONVERSATIONAL, + bluetooth::le_audio::types::kLeAudioDirectionSource); if (!sink_configuration.IsInvalid() && - sink_configuration.sample_rate > - bluetooth::audio::le_audio::kSampleRate16000) { + sink_configuration.sample_rate > bluetooth::audio::le_audio::kSampleRate16000) { audio_framework_sink_config.sample_rate = sink_configuration.sample_rate; } - le_audio_sink_hal_client_->Start(audio_framework_sink_config, - audioSourceReceiver, dsa_modes); + le_audio_sink_hal_client_->Start(audio_framework_sink_config, audioSourceReceiver, dsa_modes); } bool isOutputPreferenceLeAudio(const RawAddress& address) { - log::info("address: {}, active_group_id_: {}", address.ToStringForLogging(), - active_group_id_); - std::vector active_leaudio_devices = - GetGroupDevices(active_group_id_); - if (std::find(active_leaudio_devices.begin(), active_leaudio_devices.end(), - address) == active_leaudio_devices.end()) { - log::info("Device {} is not active for LE Audio", - address.ToStringForLogging()); + log::info("address: {}, active_group_id_: {}", address.ToStringForLogging(), active_group_id_); + std::vector active_leaudio_devices = GetGroupDevices(active_group_id_); + if (std::find(active_leaudio_devices.begin(), active_leaudio_devices.end(), address) == + active_leaudio_devices.end()) { + log::info("Device {} is not active for LE Audio", address.ToStringForLogging()); return false; } LeAudioDeviceGroup* group = aseGroups_.FindById(active_group_id_); - log::info("active_group_id: {}, is_output_preference_le_audio_: {}", - group->group_id_, group->is_output_preference_le_audio); + log::info("active_group_id: {}, is_output_preference_le_audio_: {}", group->group_id_, + group->is_output_preference_le_audio); return group->is_output_preference_le_audio; } bool isDuplexPreferenceLeAudio(const RawAddress& address) { - log::info("address: {}, active_group_id_: {}", address.ToStringForLogging(), - active_group_id_); - std::vector active_leaudio_devices = - GetGroupDevices(active_group_id_); - if (std::find(active_leaudio_devices.begin(), active_leaudio_devices.end(), - address) == active_leaudio_devices.end()) { - log::info("Device {} is not active for LE Audio", - address.ToStringForLogging()); + log::info("address: {}, active_group_id_: {}", address.ToStringForLogging(), active_group_id_); + std::vector active_leaudio_devices = GetGroupDevices(active_group_id_); + if (std::find(active_leaudio_devices.begin(), active_leaudio_devices.end(), address) == + active_leaudio_devices.end()) { + log::info("Device {} is not active for LE Audio", address.ToStringForLogging()); return false; } LeAudioDeviceGroup* group = aseGroups_.FindById(active_group_id_); - log::info("active_group_id: {}, is_duplex_preference_le_audio: {}", - group->group_id_, group->is_duplex_preference_le_audio); + log::info("active_group_id: {}, is_duplex_preference_le_audio: {}", group->group_id_, + group->is_duplex_preference_le_audio); return group->is_duplex_preference_le_audio; } @@ -1226,7 +1168,9 @@ class LeAudioClientImpl : public LeAudioClient { sink_monitor_notified_status_ = std::nullopt; log::info("Group id: {}", active_group_id_); - if (alarm_is_scheduled(suspend_timeout_)) alarm_cancel(suspend_timeout_); + if (alarm_is_scheduled(suspend_timeout_)) { + alarm_cancel(suspend_timeout_); + } StopAudio(); ClientAudioInterfaceRelease(); @@ -1261,31 +1205,26 @@ class LeAudioClientImpl : public LeAudioClient { } if (group->NumOfConnected() == 0) { - log::error("Group: {} is not connected anymore", - static_cast(group_id)); + log::error("Group: {} is not connected anymore", static_cast(group_id)); callbacks_->OnGroupStatus(group_id, GroupStatus::INACTIVE); return; } if (active_group_id_ != bluetooth::groups::kGroupUnknown) { if (active_group_id_ == group_id) { - log::info("Group is already active: {}", - static_cast(active_group_id_)); + log::info("Group is already active: {}", static_cast(active_group_id_)); callbacks_->OnGroupStatus(active_group_id_, GroupStatus::ACTIVE); return; } log::info("switching active group to: {}", group_id); - auto result = - CodecManager::GetInstance()->UpdateActiveUnicastAudioHalClient( - le_audio_source_hal_client_.get(), - le_audio_sink_hal_client_.get(), false); + auto result = CodecManager::GetInstance()->UpdateActiveUnicastAudioHalClient( + le_audio_source_hal_client_.get(), le_audio_sink_hal_client_.get(), false); log::assert_that(result, "Could not update session to codec manager"); } if (!le_audio_source_hal_client_) { - le_audio_source_hal_client_ = - LeAudioSourceAudioHalClient::AcquireUnicast(); + le_audio_source_hal_client_ = LeAudioSourceAudioHalClient::AcquireUnicast(); if (!le_audio_source_hal_client_) { log::error("could not acquire audio source interface"); callbacks_->OnGroupStatus(group_id, GroupStatus::INACTIVE); @@ -1302,10 +1241,8 @@ class LeAudioClientImpl : public LeAudioClient { } } - auto result = - CodecManager::GetInstance()->UpdateActiveUnicastAudioHalClient( - le_audio_source_hal_client_.get(), le_audio_sink_hal_client_.get(), - true); + auto result = CodecManager::GetInstance()->UpdateActiveUnicastAudioHalClient( + le_audio_source_hal_client_.get(), le_audio_sink_hal_client_.get(), true); log::assert_that(result, "Could not update session to codec manager"); /* Mini policy: Try configure audio HAL sessions with most recent context. @@ -1314,8 +1251,7 @@ class LeAudioClientImpl : public LeAudioClient { */ LeAudioContextType default_context_type = configuration_context_type_; if (!group->IsAudioSetConfigurationAvailable(default_context_type)) { - if (group->IsAudioSetConfigurationAvailable( - LeAudioContextType::UNSPECIFIED)) { + if (group->IsAudioSetConfigurationAvailable(LeAudioContextType::UNSPECIFIED)) { default_context_type = LeAudioContextType::UNSPECIFIED; default_context_type = LeAudioContextType::UNSPECIFIED; } else { @@ -1334,8 +1270,7 @@ class LeAudioClientImpl : public LeAudioClient { UpdateConfigAndCheckIfReconfigurationIsNeeded(group, default_context_type); auto previous_active_group = active_group_id_; - log::info("Active group_id changed {} -> {}", previous_active_group, - group_id); + log::info("Active group_id changed {} -> {}", previous_active_group, group_id); if (previous_active_group == bluetooth::groups::kGroupUnknown) { /* Expose audio sessions if there was no previous active group */ @@ -1352,8 +1287,7 @@ class LeAudioClientImpl : public LeAudioClient { /* Reset sink listener notified status */ sink_monitor_notified_status_ = std::nullopt; - if (com::android::bluetooth::flags:: - leaudio_codec_config_callback_order_fix()) { + if (com::android::bluetooth::flags::leaudio_codec_config_callback_order_fix()) { SendAudioGroupSelectableCodecConfigChanged(group); SendAudioGroupCurrentCodecConfigChanged(group); callbacks_->OnGroupStatus(active_group_id_, GroupStatus::ACTIVE); @@ -1469,8 +1403,8 @@ class LeAudioClientImpl : public LeAudioClient { leAudioDevice->SetConnectionState(DeviceConnectState::CONNECTING_BY_USER); bluetooth::le_audio::MetricsCollector::Get()->OnConnectionStateChanged( - leAudioDevice->group_id_, address, ConnectionState::CONNECTING, - bluetooth::le_audio::ConnectionStatus::SUCCESS); + leAudioDevice->group_id_, address, ConnectionState::CONNECTING, + bluetooth::le_audio::ConnectionStatus::SUCCESS); } BTA_GATTC_Open(gatt_if_, address, BTM_BLE_DIRECT_CONNECTION, false); @@ -1492,14 +1426,11 @@ class LeAudioClientImpl : public LeAudioClient { } /* Restore paired device from storage to recreate groups */ - void AddFromStorage(const RawAddress& address, bool autoconnect, - int sink_audio_location, int source_audio_location, - int sink_supported_context_types, - int source_supported_context_types, - const std::vector& handles, + void AddFromStorage(const RawAddress& address, bool autoconnect, int sink_audio_location, + int source_audio_location, int sink_supported_context_types, + int source_supported_context_types, const std::vector& handles, const std::vector& sink_pacs, - const std::vector& source_pacs, - const std::vector& ases) { + const std::vector& source_pacs, const std::vector& ases) { LeAudioDevice* leAudioDevice = leAudioDevices_.FindByAddress(address); if (leAudioDevice) { @@ -1508,40 +1439,37 @@ class LeAudioClientImpl : public LeAudioClient { } log::info( - "restoring: {}, autoconnect {}, sink_audio_location: {}, " - "source_audio_location: {}, sink_supported_context_types : 0x{:04x}, " - "source_supported_context_types 0x{:04x}", - address, autoconnect, sink_audio_location, source_audio_location, - sink_supported_context_types, source_supported_context_types); + "restoring: {}, autoconnect {}, sink_audio_location: {}, " + "source_audio_location: {}, sink_supported_context_types : 0x{:04x}, " + "source_supported_context_types 0x{:04x}", + address, autoconnect, sink_audio_location, source_audio_location, + sink_supported_context_types, source_supported_context_types); leAudioDevices_.Add(address, DeviceConnectState::DISCONNECTED); leAudioDevice = leAudioDevices_.FindByAddress(address); - int group_id = DeviceGroups::Get()->GetGroupId( - address, bluetooth::le_audio::uuid::kCapServiceUuid); + int group_id = + DeviceGroups::Get()->GetGroupId(address, bluetooth::le_audio::uuid::kCapServiceUuid); if (group_id != bluetooth::groups::kGroupUnknown) { group_add_node(group_id, address); } leAudioDevice->snk_audio_locations_ = sink_audio_location; if (sink_audio_location != 0) { - leAudioDevice->audio_directions_ |= - bluetooth::le_audio::types::kLeAudioDirectionSink; + leAudioDevice->audio_directions_ |= bluetooth::le_audio::types::kLeAudioDirectionSink; } - callbacks_->OnSinkAudioLocationAvailable( - leAudioDevice->address_, - leAudioDevice->snk_audio_locations_.to_ulong()); + callbacks_->OnSinkAudioLocationAvailable(leAudioDevice->address_, + leAudioDevice->snk_audio_locations_.to_ulong()); leAudioDevice->src_audio_locations_ = source_audio_location; if (source_audio_location != 0) { - leAudioDevice->audio_directions_ |= - bluetooth::le_audio::types::kLeAudioDirectionSource; + leAudioDevice->audio_directions_ |= bluetooth::le_audio::types::kLeAudioDirectionSource; } BidirectionalPair supported_contexts = { - .sink = AudioContexts(sink_supported_context_types), - .source = AudioContexts(source_supported_context_types), + .sink = AudioContexts(sink_supported_context_types), + .source = AudioContexts(source_supported_context_types), }; leAudioDevice->SetSupportedContexts(supported_contexts); @@ -1575,8 +1503,8 @@ class LeAudioClientImpl : public LeAudioClient { /* When adding from storage, make sure that autoconnect is used * by all the devices in the group. */ - leAudioDevices_.SetInitialGroupAutoconnectState( - group_id, gatt_if_, reconnection_mode_, autoconnect); + leAudioDevices_.SetInitialGroupAutoconnectState(group_id, gatt_if_, reconnection_mode_, + autoconnect); } bool GetHandlesForStorage(const RawAddress& addr, std::vector& out) { @@ -1584,14 +1512,12 @@ class LeAudioClientImpl : public LeAudioClient { return SerializeHandles(leAudioDevice, out); } - bool GetSinkPacsForStorage(const RawAddress& addr, - std::vector& out) { + bool GetSinkPacsForStorage(const RawAddress& addr, std::vector& out) { LeAudioDevice* leAudioDevice = leAudioDevices_.FindByAddress(addr); return SerializeSinkPacs(leAudioDevice, out); } - bool GetSourcePacsForStorage(const RawAddress& addr, - std::vector& out) { + bool GetSourcePacsForStorage(const RawAddress& addr, std::vector& out) { LeAudioDevice* leAudioDevice = leAudioDevices_.FindByAddress(addr); return SerializeSourcePacs(leAudioDevice, out); } @@ -1604,8 +1530,7 @@ class LeAudioClientImpl : public LeAudioClient { void BackgroundConnectIfNeeded(LeAudioDevice* leAudioDevice) { if (!leAudioDevice->autoconnect_flag_) { - log::debug("Device {} not in the background connect", - leAudioDevice->address_); + log::debug("Device {} not in the background connect", leAudioDevice->address_); return; } AddToBackgroundConnectCheckGroupConnected(leAudioDevice); @@ -1622,8 +1547,7 @@ class LeAudioClientImpl : public LeAudioClient { } auto connection_state = leAudioDevice->GetConnectionState(); - log::info("{}, state: {}", address, - bluetooth::common::ToString(connection_state)); + log::info("{}, state: {}", address, bluetooth::common::ToString(connection_state)); switch (connection_state) { case DeviceConnectState::CONNECTING_BY_USER: @@ -1643,11 +1567,10 @@ class LeAudioClientImpl : public LeAudioClient { /* If target announcement is used, do not remove autoconnect */ bool remove_from_autoconnect = - (reconnection_mode_ != BTM_BLE_BKG_CONNECT_TARGETED_ANNOUNCEMENTS); + (reconnection_mode_ != BTM_BLE_BKG_CONNECT_TARGETED_ANNOUNCEMENTS); if (leAudioDevice->autoconnect_flag_ && remove_from_autoconnect) { - log::info("Removing autoconnect flag for group_id {}", - leAudioDevice->group_id_); + log::info("Removing autoconnect flag for group_id {}", leAudioDevice->group_id_); /* Removes device from background connect */ BTA_GATTC_CancelOpen(gatt_if_, address, false); @@ -1663,11 +1586,9 @@ class LeAudioClientImpl : public LeAudioClient { auto group = aseGroups_.FindById(leAudioDevice->group_id_); if (group) { /* Remove devices from auto connect mode */ - for (auto dev = group->GetFirstDevice(); dev; - dev = group->GetNextDevice(dev)) { + for (auto dev = group->GetFirstDevice(); dev; dev = group->GetNextDevice(dev)) { if (remove_from_autoconnect && - (dev->GetConnectionState() == - DeviceConnectState::CONNECTING_AUTOCONNECT)) { + (dev->GetConnectionState() == DeviceConnectState::CONNECTING_AUTOCONNECT)) { btif_storage_set_leaudio_autoconnect(dev->address_, false); dev->autoconnect_flag_ = false; BTA_GATTC_CancelOpen(gatt_if_, dev->address_, false); @@ -1702,14 +1623,12 @@ class LeAudioClientImpl : public LeAudioClient { case DeviceConnectState::DISCONNECTING_AND_RECOVER: case DeviceConnectState::CONNECTING_AUTOCONNECT: case DeviceConnectState::REMOVING: - log::warn("{}, invalid state {}", address, - bluetooth::common::ToString(connection_state)); + log::warn("{}, invalid state {}", address, bluetooth::common::ToString(connection_state)); return; } } - void DisconnectDevice(LeAudioDevice* leAudioDevice, - bool acl_force_disconnect = false, + void DisconnectDevice(LeAudioDevice* leAudioDevice, bool acl_force_disconnect = false, bool recover = false) { if (leAudioDevice->conn_id_ == GATT_INVALID_CONN_ID) { return; @@ -1725,8 +1644,7 @@ class LeAudioClientImpl : public LeAudioClient { if (acl_force_disconnect) { leAudioDevice->DisconnectAcl(); if (recover) { - leAudioDevice->SetConnectionState( - DeviceConnectState::DISCONNECTING_AND_RECOVER); + leAudioDevice->SetConnectionState(DeviceConnectState::DISCONNECTING_AND_RECOVER); } } else { BTA_GATTC_Close(leAudioDevice->conn_id_); @@ -1734,7 +1652,7 @@ class LeAudioClientImpl : public LeAudioClient { } void DeregisterNotifications(LeAudioDevice* leAudioDevice) { - /* GATTC will ommit not registered previously handles */ + /* GATTC will omit not registered previously handles */ for (auto pac_tuple : leAudioDevice->snk_pacs_) { BTA_GATTC_DeregisterForNotifications(gatt_if_, leAudioDevice->address_, std::get<0>(pac_tuple).val_hdl); @@ -1744,42 +1662,42 @@ class LeAudioClientImpl : public LeAudioClient { std::get<0>(pac_tuple).val_hdl); } - if (leAudioDevice->snk_audio_locations_hdls_.val_hdl != 0) - BTA_GATTC_DeregisterForNotifications( - gatt_if_, leAudioDevice->address_, - leAudioDevice->snk_audio_locations_hdls_.val_hdl); - if (leAudioDevice->src_audio_locations_hdls_.val_hdl != 0) - BTA_GATTC_DeregisterForNotifications( - gatt_if_, leAudioDevice->address_, - leAudioDevice->src_audio_locations_hdls_.val_hdl); - if (leAudioDevice->audio_avail_hdls_.val_hdl != 0) - BTA_GATTC_DeregisterForNotifications( - gatt_if_, leAudioDevice->address_, - leAudioDevice->audio_avail_hdls_.val_hdl); - if (leAudioDevice->audio_supp_cont_hdls_.val_hdl != 0) - BTA_GATTC_DeregisterForNotifications( - gatt_if_, leAudioDevice->address_, - leAudioDevice->audio_supp_cont_hdls_.val_hdl); - if (leAudioDevice->ctp_hdls_.val_hdl != 0) + if (leAudioDevice->snk_audio_locations_hdls_.val_hdl != 0) { + BTA_GATTC_DeregisterForNotifications(gatt_if_, leAudioDevice->address_, + leAudioDevice->snk_audio_locations_hdls_.val_hdl); + } + if (leAudioDevice->src_audio_locations_hdls_.val_hdl != 0) { + BTA_GATTC_DeregisterForNotifications(gatt_if_, leAudioDevice->address_, + leAudioDevice->src_audio_locations_hdls_.val_hdl); + } + if (leAudioDevice->audio_avail_hdls_.val_hdl != 0) { + BTA_GATTC_DeregisterForNotifications(gatt_if_, leAudioDevice->address_, + leAudioDevice->audio_avail_hdls_.val_hdl); + } + if (leAudioDevice->audio_supp_cont_hdls_.val_hdl != 0) { + BTA_GATTC_DeregisterForNotifications(gatt_if_, leAudioDevice->address_, + leAudioDevice->audio_supp_cont_hdls_.val_hdl); + } + if (leAudioDevice->ctp_hdls_.val_hdl != 0) { BTA_GATTC_DeregisterForNotifications(gatt_if_, leAudioDevice->address_, leAudioDevice->ctp_hdls_.val_hdl); + } - for (struct ase& ase : leAudioDevice->ases_) - BTA_GATTC_DeregisterForNotifications(gatt_if_, leAudioDevice->address_, - ase.hdls.val_hdl); + for (struct ase& ase : leAudioDevice->ases_) { + BTA_GATTC_DeregisterForNotifications(gatt_if_, leAudioDevice->address_, ase.hdls.val_hdl); + } } /* This is a generic read/notify/indicate handler for gatt. Here messages * are dispatched to correct elements e.g. ASEs, PACs, audio locations etc. */ - void LeAudioCharValueHandle(uint16_t conn_id, uint16_t hdl, uint16_t len, - uint8_t* value, bool notify = false) { + void LeAudioCharValueHandle(uint16_t conn_id, uint16_t hdl, uint16_t len, uint8_t* value, + bool notify = false) { LeAudioDevice* leAudioDevice = leAudioDevices_.FindByConnId(conn_id); struct ase* ase; if (!leAudioDevice) { - log::error("no leAudioDevice assigned to connection id: {}", - static_cast(conn_id)); + log::error("no leAudioDevice assigned to connection id: {}", static_cast(conn_id)); return; } @@ -1787,22 +1705,21 @@ class LeAudioClientImpl : public LeAudioClient { LeAudioDeviceGroup* group = aseGroups_.FindById(leAudioDevice->group_id_); if (ase) { - groupStateMachine_->ProcessGattNotifEvent(value, len, ase, leAudioDevice, - group); + groupStateMachine_->ProcessGattNotifEvent(value, len, ase, leAudioDevice, group); return; } - auto snk_pac_ent = std::find_if( - leAudioDevice->snk_pacs_.begin(), leAudioDevice->snk_pacs_.end(), - [&hdl](auto& pac_ent) { return std::get<0>(pac_ent).val_hdl == hdl; }); + auto snk_pac_ent = + std::find_if(leAudioDevice->snk_pacs_.begin(), leAudioDevice->snk_pacs_.end(), + [&hdl](auto& pac_ent) { return std::get<0>(pac_ent).val_hdl == hdl; }); if (snk_pac_ent != leAudioDevice->snk_pacs_.end()) { std::vector pac_recs; /* Guard consistency of PAC records structure */ - if (!bluetooth::le_audio::client_parser::pacs::ParsePacs(pac_recs, len, - value)) + if (!bluetooth::le_audio::client_parser::pacs::ParsePacs(pac_recs, len, value)) { return; + } log::info("Registering sink PACs"); leAudioDevice->RegisterPACs(&std::get<1>(*snk_pac_ent), &pac_recs); @@ -1821,16 +1738,16 @@ class LeAudioClientImpl : public LeAudioClient { return; } - auto src_pac_ent = std::find_if( - leAudioDevice->src_pacs_.begin(), leAudioDevice->src_pacs_.end(), - [&hdl](auto& pac_ent) { return std::get<0>(pac_ent).val_hdl == hdl; }); + auto src_pac_ent = + std::find_if(leAudioDevice->src_pacs_.begin(), leAudioDevice->src_pacs_.end(), + [&hdl](auto& pac_ent) { return std::get<0>(pac_ent).val_hdl == hdl; }); if (src_pac_ent != leAudioDevice->src_pacs_.end()) { std::vector pac_recs; /* Guard consistency of PAC records structure */ - if (!bluetooth::le_audio::client_parser::pacs::ParsePacs(pac_recs, len, - value)) + if (!bluetooth::le_audio::client_parser::pacs::ParsePacs(pac_recs, len, value)) { return; + } log::info("Registering source PACs"); leAudioDevice->RegisterPACs(&std::get<1>(*src_pac_ent), &pac_recs); @@ -1852,30 +1769,28 @@ class LeAudioClientImpl : public LeAudioClient { if (hdl == leAudioDevice->snk_audio_locations_hdls_.val_hdl) { AudioLocations snk_audio_locations; - bluetooth::le_audio::client_parser::pacs::ParseAudioLocations( - snk_audio_locations, len, value); + bluetooth::le_audio::client_parser::pacs::ParseAudioLocations(snk_audio_locations, len, + value); /* Value may not change */ - if ((leAudioDevice->audio_directions_ & - bluetooth::le_audio::types::kLeAudioDirectionSink) && - (leAudioDevice->snk_audio_locations_ ^ snk_audio_locations).none()) + if ((leAudioDevice->audio_directions_ & bluetooth::le_audio::types::kLeAudioDirectionSink) && + (leAudioDevice->snk_audio_locations_ ^ snk_audio_locations).none()) { return; + } /* Presence of PAC characteristic for source means support for source * audio location. Value of 0x00000000 means mono/unspecified */ - leAudioDevice->audio_directions_ |= - bluetooth::le_audio::types::kLeAudioDirectionSink; + leAudioDevice->audio_directions_ |= bluetooth::le_audio::types::kLeAudioDirectionSink; leAudioDevice->snk_audio_locations_ = snk_audio_locations; callbacks_->OnSinkAudioLocationAvailable(leAudioDevice->address_, snk_audio_locations.to_ulong()); if (notify) { - btif_storage_set_leaudio_audio_location( - leAudioDevice->address_, - leAudioDevice->snk_audio_locations_.to_ulong(), - leAudioDevice->src_audio_locations_.to_ulong()); + btif_storage_set_leaudio_audio_location(leAudioDevice->address_, + leAudioDevice->snk_audio_locations_.to_ulong(), + leAudioDevice->src_audio_locations_.to_ulong()); if (group && group->IsReleasingOrIdle()) { UpdateLocationsAndContextsAvailability(group); } @@ -1883,35 +1798,34 @@ class LeAudioClientImpl : public LeAudioClient { } else if (hdl == leAudioDevice->src_audio_locations_hdls_.val_hdl) { AudioLocations src_audio_locations; - bluetooth::le_audio::client_parser::pacs::ParseAudioLocations( - src_audio_locations, len, value); + bluetooth::le_audio::client_parser::pacs::ParseAudioLocations(src_audio_locations, len, + value); /* Value may not change */ if ((leAudioDevice->audio_directions_ & bluetooth::le_audio::types::kLeAudioDirectionSource) && - (leAudioDevice->src_audio_locations_ ^ src_audio_locations).none()) + (leAudioDevice->src_audio_locations_ ^ src_audio_locations).none()) { return; + } /* Presence of PAC characteristic for source means support for source * audio location. Value of 0x00000000 means mono/unspecified */ - leAudioDevice->audio_directions_ |= - bluetooth::le_audio::types::kLeAudioDirectionSource; + leAudioDevice->audio_directions_ |= bluetooth::le_audio::types::kLeAudioDirectionSource; leAudioDevice->src_audio_locations_ = src_audio_locations; if (notify) { - btif_storage_set_leaudio_audio_location( - leAudioDevice->address_, - leAudioDevice->snk_audio_locations_.to_ulong(), - leAudioDevice->src_audio_locations_.to_ulong()); + btif_storage_set_leaudio_audio_location(leAudioDevice->address_, + leAudioDevice->snk_audio_locations_.to_ulong(), + leAudioDevice->src_audio_locations_.to_ulong()); if (group && group->IsReleasingOrIdle()) { UpdateLocationsAndContextsAvailability(group); } } } else if (hdl == leAudioDevice->audio_avail_hdls_.val_hdl) { BidirectionalPair contexts; - if (!bluetooth::le_audio::client_parser::pacs:: - ParseAvailableAudioContexts(contexts, len, value)) { + if (!bluetooth::le_audio::client_parser::pacs::ParseAvailableAudioContexts(contexts, len, + value)) { return; } @@ -1927,8 +1841,7 @@ class LeAudioClientImpl : public LeAudioClient { * group. */ - if (group->GetTargetState() == - AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) { + if (group->GetTargetState() == AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) { AttachToStreamingGroupIfNeeded(leAudioDevice); } return; @@ -1947,8 +1860,7 @@ class LeAudioClientImpl : public LeAudioClient { return; } - if (leAudioDevice->GetConnectionState() != - DeviceConnectState::CONNECTED) { + if (leAudioDevice->GetConnectionState() != DeviceConnectState::CONNECTED) { /* Do nothing, wait until device is connected */ return; } @@ -1957,27 +1869,27 @@ class LeAudioClientImpl : public LeAudioClient { } else if (hdl == leAudioDevice->audio_supp_cont_hdls_.val_hdl) { BidirectionalPair supp_audio_contexts; - if (bluetooth::le_audio::client_parser::pacs::ParseSupportedAudioContexts( - supp_audio_contexts, len, value)) { + if (bluetooth::le_audio::client_parser::pacs::ParseSupportedAudioContexts(supp_audio_contexts, + len, value)) { /* Just store if for now */ leAudioDevice->SetSupportedContexts(supp_audio_contexts); - btif_storage_set_leaudio_supported_context_types( - leAudioDevice->address_, supp_audio_contexts.sink.value(), - supp_audio_contexts.source.value()); + btif_storage_set_leaudio_supported_context_types(leAudioDevice->address_, + supp_audio_contexts.sink.value(), + supp_audio_contexts.source.value()); } } else if (hdl == leAudioDevice->ctp_hdls_.val_hdl) { groupStateMachine_->ProcessGattCtpNotification(group, value, len); } else if (hdl == leAudioDevice->tmap_role_hdl_) { - bluetooth::le_audio::client_parser::tmap::ParseTmapRole( - leAudioDevice->tmap_role_, len, value); + bluetooth::le_audio::client_parser::tmap::ParseTmapRole(leAudioDevice->tmap_role_, len, + value); } else { log::error("Unknown attribute read: 0x{:x}", hdl); } } - void OnGattReadRsp(uint16_t conn_id, tGATT_STATUS status, uint16_t hdl, - uint16_t len, uint8_t* value, void* data) { + void OnGattReadRsp(uint16_t conn_id, tGATT_STATUS status, uint16_t hdl, uint16_t len, + uint8_t* value, void* data) { LeAudioCharValueHandle(conn_id, hdl, len, value); } @@ -2003,45 +1915,40 @@ class LeAudioClientImpl : public LeAudioClient { return; } - leAudioDevice->SetConnectionState( - DeviceConnectState::CONNECTING_AUTOCONNECT); + leAudioDevice->SetConnectionState(DeviceConnectState::CONNECTING_AUTOCONNECT); /* Cancel previous bakcground connect */ BTA_GATTC_CancelOpen(gatt_if_, address, false); if (group->IsAnyDeviceConnected()) { - log::info("Group {} in connected state. Adding {} to allow list", - leAudioDevice->group_id_, address); + log::info("Group {} in connected state. Adding {} to allow list", leAudioDevice->group_id_, + address); BTA_GATTC_Open(gatt_if_, address, BTM_BLE_BKG_CONNECT_ALLOW_LIST, false); } else { - log::info( - "Adding {} to backgroud connect (default reconnection_mode " - "(0x{:02x}))", - address, reconnection_mode_); + log::info("Adding {} to background connect (default reconnection_mode (0x{:02x}))", address, + reconnection_mode_); BTA_GATTC_Open(gatt_if_, address, reconnection_mode_, false); } } - void OnGattConnected(tGATT_STATUS status, uint16_t conn_id, - tGATT_IF client_if, RawAddress address, - tBT_TRANSPORT transport, uint16_t mtu) { + void OnGattConnected(tGATT_STATUS status, uint16_t conn_id, tGATT_IF client_if, + RawAddress address, tBT_TRANSPORT transport, uint16_t mtu) { LeAudioDevice* leAudioDevice = leAudioDevices_.FindByAddress(address); - log::info("{}, conn_id=0x{:04x}, transport={}, status={} (0x{:02x})", - address, conn_id, bt_transport_text(transport), - gatt_status_text(status), status); + log::info("{}, conn_id=0x{:04x}, transport={}, status={} (0x{:02x})", address, conn_id, + bt_transport_text(transport), gatt_status_text(status), status); if (transport != BT_TRANSPORT_LE) { - log::warn("Only LE connection is allowed (transport {})", - bt_transport_text(transport)); + log::warn("Only LE connection is allowed (transport {})", bt_transport_text(transport)); BTA_GATTC_Close(conn_id); return; } - if (!leAudioDevice) return; + if (!leAudioDevice) { + return; + } if (leAudioDevice->conn_id_ != GATT_INVALID_CONN_ID) { - log::debug("Already connected {}, conn_id=0x{:04x}", address, - leAudioDevice->conn_id_); + log::debug("Already connected {}, conn_id=0x{:04x}", address, leAudioDevice->conn_id_); return; } @@ -2051,8 +1958,7 @@ class LeAudioClientImpl : public LeAudioClient { /* autoconnect connection failed, that's ok */ if (status != GATT_ILLEGAL_PARAMETER && - (leAudioDevice->GetConnectionState() == - DeviceConnectState::CONNECTING_AUTOCONNECT || + (leAudioDevice->GetConnectionState() == DeviceConnectState::CONNECTING_AUTOCONNECT || leAudioDevice->autoconnect_flag_)) { log::info("Device not available now, do background connect."); leAudioDevice->SetConnectionState(DeviceConnectState::DISCONNECTED); @@ -2062,12 +1968,11 @@ class LeAudioClientImpl : public LeAudioClient { leAudioDevice->SetConnectionState(DeviceConnectState::DISCONNECTED); - log::error("Failed to connect to LeAudio leAudioDevice, status: 0x{:02x}", - status); + log::error("Failed to connect to LeAudio leAudioDevice, status: 0x{:02x}", status); callbacks_->OnConnectionState(ConnectionState::DISCONNECTED, address); bluetooth::le_audio::MetricsCollector::Get()->OnConnectionStateChanged( - leAudioDevice->group_id_, address, ConnectionState::CONNECTED, - bluetooth::le_audio::ConnectionStatus::FAILED); + leAudioDevice->group_id_, address, ConnectionState::CONNECTED, + bluetooth::le_audio::ConnectionStatus::FAILED); return; } @@ -2076,9 +1981,8 @@ class LeAudioClientImpl : public LeAudioClient { if (group == nullptr) { BTA_GATTC_CancelOpen(gatt_if_, address, false); - log::warn( - "LeAudio profile is disabled for group_id: {}. {} is not connected", - leAudioDevice->group_id_, address); + log::warn("LeAudio profile is disabled for group_id: {}. {} is not connected", + leAudioDevice->group_id_, address); return; } } @@ -2101,13 +2005,10 @@ class LeAudioClientImpl : public LeAudioClient { get_btm_client_interface().peer.BTM_RequestPeerSCA(leAudioDevice->address_, transport); - if (leAudioDevice->GetConnectionState() == - DeviceConnectState::CONNECTING_AUTOCONNECT) { - leAudioDevice->SetConnectionState( - DeviceConnectState::CONNECTED_AUTOCONNECT_GETTING_READY); + if (leAudioDevice->GetConnectionState() == DeviceConnectState::CONNECTING_AUTOCONNECT) { + leAudioDevice->SetConnectionState(DeviceConnectState::CONNECTED_AUTOCONNECT_GETTING_READY); } else { - leAudioDevice->SetConnectionState( - DeviceConnectState::CONNECTED_BY_USER_GETTING_READY); + leAudioDevice->SetConnectionState(DeviceConnectState::CONNECTED_BY_USER_GETTING_READY); } /* Check if the device is in allow list and update the flag */ @@ -2125,74 +2026,70 @@ class LeAudioClientImpl : public LeAudioClient { return; } - int result = BTM_SetEncryption(address, BT_TRANSPORT_LE, nullptr, nullptr, - BTM_BLE_SEC_ENCRYPT); + int result = BTM_SetEncryption(address, BT_TRANSPORT_LE, nullptr, nullptr, BTM_BLE_SEC_ENCRYPT); - log::info("Encryption required for {}. Request result: 0x{:02x}", address, - result); + log::info("Encryption required for {}. Request result: 0x{:02x}", address, result); if (result == BTM_ERR_KEY_MISSING) { log::error("Link key unknown for {}, disconnect profile", address); bluetooth::le_audio::MetricsCollector::Get()->OnConnectionStateChanged( - leAudioDevice->group_id_, address, ConnectionState::CONNECTED, - bluetooth::le_audio::ConnectionStatus::FAILED); + leAudioDevice->group_id_, address, ConnectionState::CONNECTED, + bluetooth::le_audio::ConnectionStatus::FAILED); /* If link cannot be enctypted, disconnect profile */ BTA_GATTC_Close(conn_id); } } - void RegisterKnownNotifications(LeAudioDevice* leAudioDevice, - bool gatt_register, bool write_ccc) { + void RegisterKnownNotifications(LeAudioDevice* leAudioDevice, bool gatt_register, + bool write_ccc) { log::info("device: {}", leAudioDevice->address_); if (leAudioDevice->ctp_hdls_.val_hdl == 0) { - log::error( - "Control point characteristic is mandatory - disconnecting device {}", - leAudioDevice->address_); + log::error("Control point characteristic is mandatory - disconnecting device {}", + leAudioDevice->address_); DisconnectDevice(leAudioDevice); return; } - /* GATTC will ommit not registered previously handles */ + /* GATTC will omit not registered previously handles */ for (auto pac_tuple : leAudioDevice->snk_pacs_) { - subscribe_for_notification( - leAudioDevice->conn_id_, leAudioDevice->address_, - std::get<0>(pac_tuple), gatt_register, write_ccc); + subscribe_for_notification(leAudioDevice->conn_id_, leAudioDevice->address_, + std::get<0>(pac_tuple), gatt_register, write_ccc); } for (auto pac_tuple : leAudioDevice->src_pacs_) { - subscribe_for_notification( - leAudioDevice->conn_id_, leAudioDevice->address_, - std::get<0>(pac_tuple), gatt_register, write_ccc); - } - - if (leAudioDevice->snk_audio_locations_hdls_.val_hdl != 0) - subscribe_for_notification( - leAudioDevice->conn_id_, leAudioDevice->address_, - leAudioDevice->snk_audio_locations_hdls_, gatt_register, write_ccc); - if (leAudioDevice->src_audio_locations_hdls_.val_hdl != 0) - subscribe_for_notification( - leAudioDevice->conn_id_, leAudioDevice->address_, - leAudioDevice->src_audio_locations_hdls_, gatt_register, write_ccc); - - if (leAudioDevice->audio_avail_hdls_.val_hdl != 0) - subscribe_for_notification( - leAudioDevice->conn_id_, leAudioDevice->address_, - leAudioDevice->audio_avail_hdls_, gatt_register, write_ccc); - - if (leAudioDevice->audio_supp_cont_hdls_.val_hdl != 0) - subscribe_for_notification( - leAudioDevice->conn_id_, leAudioDevice->address_, - leAudioDevice->audio_supp_cont_hdls_, gatt_register, write_ccc); - - for (struct ase& ase : leAudioDevice->ases_) - subscribe_for_notification(leAudioDevice->conn_id_, - leAudioDevice->address_, ase.hdls, + subscribe_for_notification(leAudioDevice->conn_id_, leAudioDevice->address_, + std::get<0>(pac_tuple), gatt_register, write_ccc); + } + + if (leAudioDevice->snk_audio_locations_hdls_.val_hdl != 0) { + subscribe_for_notification(leAudioDevice->conn_id_, leAudioDevice->address_, + leAudioDevice->snk_audio_locations_hdls_, gatt_register, + write_ccc); + } + if (leAudioDevice->src_audio_locations_hdls_.val_hdl != 0) { + subscribe_for_notification(leAudioDevice->conn_id_, leAudioDevice->address_, + leAudioDevice->src_audio_locations_hdls_, gatt_register, + write_ccc); + } + + if (leAudioDevice->audio_avail_hdls_.val_hdl != 0) { + subscribe_for_notification(leAudioDevice->conn_id_, leAudioDevice->address_, + leAudioDevice->audio_avail_hdls_, gatt_register, write_ccc); + } + + if (leAudioDevice->audio_supp_cont_hdls_.val_hdl != 0) { + subscribe_for_notification(leAudioDevice->conn_id_, leAudioDevice->address_, + leAudioDevice->audio_supp_cont_hdls_, gatt_register, write_ccc); + } + + for (struct ase& ase : leAudioDevice->ases_) { + subscribe_for_notification(leAudioDevice->conn_id_, leAudioDevice->address_, ase.hdls, gatt_register, write_ccc); + } subscribe_for_notification(leAudioDevice->conn_id_, leAudioDevice->address_, - leAudioDevice->ctp_hdls_, gatt_register, - write_ccc); + leAudioDevice->ctp_hdls_, gatt_register, write_ccc); } void changeMtuIfPossible(LeAudioDevice* leAudioDevice) { @@ -2209,8 +2106,7 @@ class LeAudioClientImpl : public LeAudioClient { void OnEncryptionComplete(const RawAddress& address, uint8_t status) { log::info("{} status 0x{:02x}", address, status); LeAudioDevice* leAudioDevice = leAudioDevices_.FindByAddress(address); - if (leAudioDevice == NULL || - (leAudioDevice->conn_id_ == GATT_INVALID_CONN_ID)) { + if (leAudioDevice == NULL || (leAudioDevice->conn_id_ == GATT_INVALID_CONN_ID)) { log::warn("Skipping device which is {}", leAudioDevice ? " not connected by service." : " null"); return; @@ -2222,8 +2118,8 @@ class LeAudioClientImpl : public LeAudioClient { DeviceConnectState::CONNECTED_BY_USER_GETTING_READY) { callbacks_->OnConnectionState(ConnectionState::DISCONNECTED, address); bluetooth::le_audio::MetricsCollector::Get()->OnConnectionStateChanged( - leAudioDevice->group_id_, address, ConnectionState::CONNECTED, - bluetooth::le_audio::ConnectionStatus::FAILED); + leAudioDevice->group_id_, address, ConnectionState::CONNECTED, + bluetooth::le_audio::ConnectionStatus::FAILED); } leAudioDevice->SetConnectionState(DeviceConnectState::DISCONNECTING); @@ -2262,30 +2158,27 @@ class LeAudioClientImpl : public LeAudioClient { * We read only ctp_ccc value. If that one is good, we assume * remote keeps CCC values correctly. */ - BtaGattQueue::ReadCharacteristic(leAudioDevice->conn_id_, - leAudioDevice->ctp_hdls_.ccc_hdl, + BtaGattQueue::ReadCharacteristic(leAudioDevice->conn_id_, leAudioDevice->ctp_hdls_.ccc_hdl, OnGattCtpCccReadRspStatic, NULL); } /* If we know services and read is not ongoing, this is reconnection and * just notify connected */ - if (leAudioDevice->known_service_handles_ && - !leAudioDevice->notify_connected_after_read_) { + if (leAudioDevice->known_service_handles_ && !leAudioDevice->notify_connected_after_read_) { log::info("Wait for CCC registration and MTU change request"); return; } - BTA_GATTC_ServiceSearchRequest( - leAudioDevice->conn_id_, - bluetooth::le_audio::uuid::kPublishedAudioCapabilityServiceUuid); + BTA_GATTC_ServiceSearchRequest(leAudioDevice->conn_id_, + bluetooth::le_audio::uuid::kPublishedAudioCapabilityServiceUuid); } void checkGroupConnectionStateAfterMemberDisconnect(int group_id) { /* This is fired t=kGroupConnectedWatchDelayMs after group member - * got disconencted while ather group members were connected. + * got disconnected while either group members were connected. * We want to check here if there is any group member connected. * If so we should add other group members to allow list for better - * reconnection experiance. If all group members are disconnected + * reconnection experience. If all group members are disconnected * i e.g. devices intentionally disconnected for other * purposes like pairing with other device, then we do nothing here and * device stay on the default reconnection policy (i.e. targeted @@ -2314,11 +2207,10 @@ class LeAudioClientImpl : public LeAudioClient { void scheduleGroupConnectedCheck(int group_id) { log::info("Schedule group_id {} connected check.", group_id); do_in_main_thread_delayed( - FROM_HERE, - base::BindOnce( - &LeAudioClientImpl::checkGroupConnectionStateAfterMemberDisconnect, - weak_factory_.GetWeakPtr(), group_id), - std::chrono::milliseconds(kGroupConnectedWatchDelayMs)); + FROM_HERE, + base::BindOnce(&LeAudioClientImpl::checkGroupConnectionStateAfterMemberDisconnect, + weak_factory_.GetWeakPtr(), group_id), + std::chrono::milliseconds(kGroupConnectedWatchDelayMs)); } void autoConnect(RawAddress address) { @@ -2334,10 +2226,9 @@ class LeAudioClientImpl : public LeAudioClient { void scheduleAutoConnect(RawAddress& address) { log::info("Schedule auto connect {}", address); do_in_main_thread_delayed( - FROM_HERE, - base::BindOnce(&LeAudioClientImpl::autoConnect, - weak_factory_.GetWeakPtr(), address), - std::chrono::milliseconds(kAutoConnectAfterOwnDisconnectDelayMs)); + FROM_HERE, + base::BindOnce(&LeAudioClientImpl::autoConnect, weak_factory_.GetWeakPtr(), address), + std::chrono::milliseconds(kAutoConnectAfterOwnDisconnectDelayMs)); } void recoveryReconnect(RawAddress address) { @@ -2345,18 +2236,15 @@ class LeAudioClientImpl : public LeAudioClient { LeAudioDevice* leAudioDevice = leAudioDevices_.FindByAddress(address); if (leAudioDevice == nullptr || - leAudioDevice->GetConnectionState() != - DeviceConnectState::DISCONNECTING_AND_RECOVER) { - log::warn("Device {}, not interested in recovery connect anymore", - address); + leAudioDevice->GetConnectionState() != DeviceConnectState::DISCONNECTING_AND_RECOVER) { + log::warn("Device {}, not interested in recovery connect anymore", address); return; } auto group = GetGroupIfEnabled(leAudioDevice->group_id_); if (group != nullptr) { - leAudioDevice->SetConnectionState( - DeviceConnectState::CONNECTING_AUTOCONNECT); + leAudioDevice->SetConnectionState(DeviceConnectState::CONNECTING_AUTOCONNECT); BTA_GATTC_Open(gatt_if_, address, BTM_BLE_DIRECT_CONNECTION, false); } else { leAudioDevice->SetConnectionState(DeviceConnectState::DISCONNECTED); @@ -2364,13 +2252,11 @@ class LeAudioClientImpl : public LeAudioClient { } void scheduleRecoveryReconnect(RawAddress& address) { - log::info("Schedule reconnecting to {} after timeout on state machine.", - address); - do_in_main_thread_delayed( - FROM_HERE, - base::BindOnce(&LeAudioClientImpl::recoveryReconnect, - weak_factory_.GetWeakPtr(), address), - std::chrono::milliseconds(kRecoveryReconnectDelayMs)); + log::info("Schedule reconnecting to {} after timeout on state machine.", address); + do_in_main_thread_delayed(FROM_HERE, + base::BindOnce(&LeAudioClientImpl::recoveryReconnect, + weak_factory_.GetWeakPtr(), address), + std::chrono::milliseconds(kRecoveryReconnectDelayMs)); } void checkIfGroupMember(RawAddress address) { @@ -2383,8 +2269,7 @@ class LeAudioClientImpl : public LeAudioClient { } if (leAudioDevice->group_id_ == bluetooth::groups::kGroupUnknown) { - disconnectInvalidDevice(leAudioDevice, - ", device not a valid group member", + disconnectInvalidDevice(leAudioDevice, ", device not a valid group member", LeAudioHealthDeviceStatType::INVALID_CSIS); return; } @@ -2398,17 +2283,15 @@ class LeAudioClientImpl : public LeAudioClient { * side. */ void scheduleGuardForCsisAdd(RawAddress& address) { - log::info("Schedule reconnecting to {} after timeout on state machine.", - address); - do_in_main_thread_delayed( - FROM_HERE, - base::BindOnce(&LeAudioClientImpl::checkIfGroupMember, - weak_factory_.GetWeakPtr(), address), - std::chrono::milliseconds(kCsisGroupMemberDelayMs)); + log::info("Schedule reconnecting to {} after timeout on state machine.", address); + do_in_main_thread_delayed(FROM_HERE, + base::BindOnce(&LeAudioClientImpl::checkIfGroupMember, + weak_factory_.GetWeakPtr(), address), + std::chrono::milliseconds(kCsisGroupMemberDelayMs)); } - void OnGattDisconnected(uint16_t conn_id, tGATT_IF client_if, - RawAddress address, tGATT_DISCONN_REASON reason) { + void OnGattDisconnected(uint16_t conn_id, tGATT_IF client_if, RawAddress address, + tGATT_DISCONN_REASON reason) { LeAudioDevice* leAudioDevice = leAudioDevices_.FindByConnId(conn_id); if (!leAudioDevice) { @@ -2432,8 +2315,8 @@ class LeAudioClientImpl : public LeAudioClient { groupStateMachine_->ProcessHciNotifAclDisconnected(group, leAudioDevice); bluetooth::le_audio::MetricsCollector::Get()->OnConnectionStateChanged( - leAudioDevice->group_id_, address, ConnectionState::DISCONNECTED, - bluetooth::le_audio::ConnectionStatus::SUCCESS); + leAudioDevice->group_id_, address, ConnectionState::DISCONNECTED, + bluetooth::le_audio::ConnectionStatus::SUCCESS); if (leAudioDevice->GetConnectionState() == DeviceConnectState::REMOVING) { if (leAudioDevice->group_id_ != bluetooth::groups::kGroupUnknown) { @@ -2445,8 +2328,8 @@ class LeAudioClientImpl : public LeAudioClient { } auto connection_state = leAudioDevice->GetConnectionState(); - log::info("{}, autoconnect {}, reason 0x{:02x}, connection state {}", - leAudioDevice->address_, leAudioDevice->autoconnect_flag_, reason, + log::info("{}, autoconnect {}, reason 0x{:02x}, connection state {}", leAudioDevice->address_, + leAudioDevice->autoconnect_flag_, reason, bluetooth::common::ToString(connection_state)); if (connection_state == DeviceConnectState::DISCONNECTING_AND_RECOVER) { @@ -2467,8 +2350,7 @@ class LeAudioClientImpl : public LeAudioClient { * issues */ if (group == nullptr || !group->IsEnabled()) { - log::error("Group id {} ({}) disabled or null", leAudioDevice->group_id_, - fmt::ptr(group)); + log::error("Group id {} ({}) disabled or null", leAudioDevice->group_id_, fmt::ptr(group)); return; } @@ -2483,8 +2365,7 @@ class LeAudioClientImpl : public LeAudioClient { /* Remote disconnects from us or Timeout happens */ /* In this case ACL is disconnected */ if (reason == GATT_CONN_TIMEOUT) { - leAudioDevice->SetConnectionState( - DeviceConnectState::CONNECTING_AUTOCONNECT); + leAudioDevice->SetConnectionState(DeviceConnectState::CONNECTING_AUTOCONNECT); /* If timeout try to reconnect for 30 sec.*/ BTA_GATTC_Open(gatt_if_, address, BTM_BLE_DIRECT_CONNECTION, false); @@ -2505,39 +2386,38 @@ class LeAudioClientImpl : public LeAudioClient { } } - bool subscribe_for_notification( - uint16_t conn_id, const RawAddress& address, - struct bluetooth::le_audio::types::hdl_pair handle_pair, - bool gatt_register = true, bool write_ccc = true) { + bool subscribe_for_notification(uint16_t conn_id, const RawAddress& address, + struct bluetooth::le_audio::types::hdl_pair handle_pair, + bool gatt_register = true, bool write_ccc = true) { std::vector value(2); uint8_t* ptr = value.data(); uint16_t handle = handle_pair.val_hdl; uint16_t ccc_handle = handle_pair.ccc_hdl; - log::info("conn id {}, gatt_register: {}, write_ccc: {}", conn_id, - gatt_register, write_ccc); - if (gatt_register && BTA_GATTC_RegisterForNotifications( - gatt_if_, address, handle) != GATT_SUCCESS) { - log::error("cannot register for notification: {}", - static_cast(handle)); + log::info("conn id {}, gatt_register: {}, write_ccc: {}", conn_id, gatt_register, write_ccc); + if (gatt_register && + BTA_GATTC_RegisterForNotifications(gatt_if_, address, handle) != GATT_SUCCESS) { + log::error("cannot register for notification: {}", static_cast(handle)); return false; } if (write_ccc == false) { - log::verbose("CCC is not written to {} (0x{:04x}), handle 0x{:04x}", - address, conn_id, ccc_handle); + log::verbose("CCC is not written to {} (0x{:04x}), handle 0x{:04x}", address, conn_id, + ccc_handle); return true; } UINT16_TO_STREAM(ptr, GATT_CHAR_CLIENT_CONFIG_NOTIFICATION); BtaGattQueue::WriteDescriptor( - conn_id, ccc_handle, std::move(value), GATT_WRITE, - [](uint16_t conn_id, tGATT_STATUS status, uint16_t handle, uint16_t len, - const uint8_t* value, void* data) { - if (instance) instance->OnGattWriteCcc(conn_id, status, handle, data); - }, - nullptr); + conn_id, ccc_handle, std::move(value), GATT_WRITE, + [](uint16_t conn_id, tGATT_STATUS status, uint16_t handle, uint16_t len, + const uint8_t* value, void* data) { + if (instance) { + instance->OnGattWriteCcc(conn_id, status, handle, data); + } + }, + nullptr); return true; } @@ -2545,11 +2425,10 @@ class LeAudioClientImpl : public LeAudioClient { * characteristics. */ uint16_t find_ccc_handle(const gatt::Characteristic& charac) { - auto iter = std::find_if( - charac.descriptors.begin(), charac.descriptors.end(), - [](const auto& desc) { - return desc.uuid == Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG); - }); + auto iter = std::find_if(charac.descriptors.begin(), charac.descriptors.end(), + [](const auto& desc) { + return desc.uuid == Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG); + }); return iter == charac.descriptors.end() ? 0 : (*iter).handle; } @@ -2573,22 +2452,19 @@ class LeAudioClientImpl : public LeAudioClient { DeregisterNotifications(leAudioDevice); if (leAudioDevice->GetConnectionState() == DeviceConnectState::CONNECTED) { - leAudioDevice->SetConnectionState( - DeviceConnectState::CONNECTED_BY_USER_GETTING_READY); + leAudioDevice->SetConnectionState(DeviceConnectState::CONNECTED_BY_USER_GETTING_READY); } btif_storage_leaudio_clear_service_data(leAudioDevice->address_); - BTA_GATTC_ServiceSearchRequest( - leAudioDevice->conn_id_, - bluetooth::le_audio::uuid::kPublishedAudioCapabilityServiceUuid); + BTA_GATTC_ServiceSearchRequest(leAudioDevice->conn_id_, + bluetooth::le_audio::uuid::kPublishedAudioCapabilityServiceUuid); } void OnServiceChangeEvent(const RawAddress& address) { LeAudioDevice* leAudioDevice = leAudioDevices_.FindByAddress(address); if (!leAudioDevice) { - log::warn("Skipping unknown leAudioDevice {} ({})", address, - fmt::ptr(leAudioDevice)); + log::warn("Skipping unknown leAudioDevice {} ({})", address, fmt::ptr(leAudioDevice)); return; } @@ -2628,16 +2504,15 @@ class LeAudioClientImpl : public LeAudioClient { leAudioDevice->mtu_ = mtu; } - void OnPhyUpdate(uint16_t conn_id, uint8_t tx_phy, uint8_t rx_phy, - tGATT_STATUS status) { + void OnPhyUpdate(uint16_t conn_id, uint8_t tx_phy, uint8_t rx_phy, tGATT_STATUS status) { LeAudioDevice* leAudioDevice = leAudioDevices_.FindByConnId(conn_id); if (leAudioDevice == nullptr) { log::debug("Unknown conn_id {:#x}", conn_id); return; } - log::info("{}, tx_phy: {:#x}, rx_phy: {:#x} , status: {:#x}", - leAudioDevice->address_, tx_phy, rx_phy, status); + log::info("{}, tx_phy: {:#x}, rx_phy: {:#x} , status: {:#x}", leAudioDevice->address_, tx_phy, + rx_phy, status); if (status == 0) { leAudioDevice->acl_phy_update_done_ = true; @@ -2657,14 +2532,14 @@ class LeAudioClientImpl : public LeAudioClient { return; } - if (!leAudioDevice->known_service_handles_) + if (!leAudioDevice->known_service_handles_) { BTA_GATTC_ServiceSearchRequest( - leAudioDevice->conn_id_, - bluetooth::le_audio::uuid::kPublishedAudioCapabilityServiceUuid); + leAudioDevice->conn_id_, + bluetooth::le_audio::uuid::kPublishedAudioCapabilityServiceUuid); + } } - void disconnectInvalidDevice(LeAudioDevice* leAudioDevice, - std::string error_string, + void disconnectInvalidDevice(LeAudioDevice* leAudioDevice, std::string error_string, LeAudioHealthDeviceStatType stat) { log::error("{}, {}", leAudioDevice->address_, error_string); if (leAudioHealthStatus_) { @@ -2710,23 +2585,20 @@ class LeAudioClientImpl : public LeAudioClient { uint16_t cas_csis_included_handle = 0; for (const gatt::Service& tmp : *services) { - if (tmp.uuid == - bluetooth::le_audio::uuid::kPublishedAudioCapabilityServiceUuid) { - log::info( - "Found Audio Capability service, handle: 0x{:04x}, device: {}", - tmp.handle, leAudioDevice->address_); + if (tmp.uuid == bluetooth::le_audio::uuid::kPublishedAudioCapabilityServiceUuid) { + log::info("Found Audio Capability service, handle: 0x{:04x}, device: {}", tmp.handle, + leAudioDevice->address_); pac_svc = &tmp; - } else if (tmp.uuid == - bluetooth::le_audio::uuid::kAudioStreamControlServiceUuid) { - log::info( - "Found Audio Stream Endpoint service, handle: 0x{:04x}, device: {}", - tmp.handle, leAudioDevice->address_); + } else if (tmp.uuid == bluetooth::le_audio::uuid::kAudioStreamControlServiceUuid) { + log::info("Found Audio Stream Endpoint service, handle: 0x{:04x}, device: {}", tmp.handle, + leAudioDevice->address_); ase_svc = &tmp; } else if (tmp.uuid == bluetooth::csis::kCsisServiceUuid) { - log::info( - "Found CSIS service, handle: 0x{:04x}, is primary: {}, device: {}", - tmp.handle, tmp.is_primary, leAudioDevice->address_); - if (tmp.is_primary) csis_primary_handles.push_back(tmp.handle); + log::info("Found CSIS service, handle: 0x{:04x}, is primary: {}, device: {}", tmp.handle, + tmp.is_primary, leAudioDevice->address_); + if (tmp.is_primary) { + csis_primary_handles.push_back(tmp.handle); + } } else if (tmp.uuid == bluetooth::le_audio::uuid::kCapServiceUuid) { log::info("Found CAP service, handle: 0x{:04x}, device: {}", tmp.handle, leAudioDevice->address_); @@ -2735,35 +2607,32 @@ class LeAudioClientImpl : public LeAudioClient { for (auto& included_srvc : tmp.included_services) { if (included_srvc.uuid == bluetooth::csis::kCsisServiceUuid) { log::info("CSIS included into CAS"); - if (bluetooth::csis::CsisClient::IsCsisClientRunning()) + if (bluetooth::csis::CsisClient::IsCsisClientRunning()) { cas_csis_included_handle = included_srvc.start_handle; + } break; } } - } else if (tmp.uuid == - bluetooth::le_audio::uuid::kTelephonyMediaAudioServiceUuid) { - log::info( - "Found Telephony and Media Audio service, handle: 0x{:04x}, " - "device: {}", - tmp.handle, leAudioDevice->address_); + } else if (tmp.uuid == bluetooth::le_audio::uuid::kTelephonyMediaAudioServiceUuid) { + log::info("Found Telephony and Media Audio service, handle: 0x{:04x}, device: {}", + tmp.handle, leAudioDevice->address_); tmas_svc = &tmp; } } /* Check if CAS includes primary CSIS service */ if (!csis_primary_handles.empty() && cas_csis_included_handle) { - auto iter = - std::find(csis_primary_handles.begin(), csis_primary_handles.end(), - cas_csis_included_handle); - if (iter != csis_primary_handles.end()) + auto iter = std::find(csis_primary_handles.begin(), csis_primary_handles.end(), + cas_csis_included_handle); + if (iter != csis_primary_handles.end()) { leAudioDevice->csis_member_ = true; + } } if (!pac_svc || !ase_svc) { - disconnectInvalidDevice( - leAudioDevice, "No mandatory le audio services found (pacs or ascs)", - LeAudioHealthDeviceStatType::INVALID_DB); + disconnectInvalidDevice(leAudioDevice, "No mandatory le audio services found (pacs or ascs)", + LeAudioHealthDeviceStatType::INVALID_DB); return; } @@ -2771,8 +2640,8 @@ class LeAudioClientImpl : public LeAudioClient { leAudioDevice->ClearPACs(); for (const gatt::Characteristic& charac : pac_svc->characteristics) { - if (charac.uuid == bluetooth::le_audio::uuid:: - kSinkPublishedAudioCapabilityCharacteristicUuid) { + if (charac.uuid == + bluetooth::le_audio::uuid::kSinkPublishedAudioCapabilityCharacteristicUuid) { struct hdl_pair hdl_pair; hdl_pair.val_hdl = charac.value_handle; hdl_pair.ccc_hdl = find_ccc_handle(charac); @@ -2782,29 +2651,22 @@ class LeAudioClientImpl : public LeAudioClient { } if (hdl_pair.ccc_hdl != 0 && - !subscribe_for_notification(conn_id, leAudioDevice->address_, - hdl_pair)) { - disconnectInvalidDevice(leAudioDevice, - ", cound not subscribe for snk pac char", + !subscribe_for_notification(conn_id, leAudioDevice->address_, hdl_pair)) { + disconnectInvalidDevice(leAudioDevice, ", could not subscribe for snk pac char", LeAudioHealthDeviceStatType::INVALID_DB); return; } /* Obtain initial state of sink PACs */ - BtaGattQueue::ReadCharacteristic(conn_id, hdl_pair.val_hdl, - OnGattReadRspStatic, NULL); + BtaGattQueue::ReadCharacteristic(conn_id, hdl_pair.val_hdl, OnGattReadRspStatic, NULL); leAudioDevice->snk_pacs_.push_back(std::make_tuple( - hdl_pair, - std::vector())); + hdl_pair, std::vector())); - log::info( - "Found Sink PAC characteristic, handle: 0x{:04x}, ccc handle: " - "0x{:04x}, addr: {}", - charac.value_handle, hdl_pair.ccc_hdl, leAudioDevice->address_); + log::info("Found Sink PAC characteristic, handle: 0x{:04x}, ccc handle: 0x{:04x}, addr: {}", + charac.value_handle, hdl_pair.ccc_hdl, leAudioDevice->address_); } else if (charac.uuid == - bluetooth::le_audio::uuid:: - kSourcePublishedAudioCapabilityCharacteristicUuid) { + bluetooth::le_audio::uuid::kSourcePublishedAudioCapabilityCharacteristicUuid) { struct hdl_pair hdl_pair; hdl_pair.val_hdl = charac.value_handle; hdl_pair.ccc_hdl = find_ccc_handle(charac); @@ -2814,121 +2676,100 @@ class LeAudioClientImpl : public LeAudioClient { } if (hdl_pair.ccc_hdl != 0 && - !subscribe_for_notification(conn_id, leAudioDevice->address_, - hdl_pair)) { - disconnectInvalidDevice(leAudioDevice, - ", could not subscribe for src pac char", + !subscribe_for_notification(conn_id, leAudioDevice->address_, hdl_pair)) { + disconnectInvalidDevice(leAudioDevice, ", could not subscribe for src pac char", LeAudioHealthDeviceStatType::INVALID_DB); return; } /* Obtain initial state of source PACs */ - BtaGattQueue::ReadCharacteristic(conn_id, hdl_pair.val_hdl, - OnGattReadRspStatic, NULL); + BtaGattQueue::ReadCharacteristic(conn_id, hdl_pair.val_hdl, OnGattReadRspStatic, NULL); leAudioDevice->src_pacs_.push_back(std::make_tuple( - hdl_pair, - std::vector())); + hdl_pair, std::vector())); log::info( - "Found Source PAC characteristic, handle: 0x{:04x}, ccc handle: " - "0x{:04x}, addr: {}", - charac.value_handle, hdl_pair.ccc_hdl, leAudioDevice->address_); - } else if (charac.uuid == bluetooth::le_audio::uuid:: - kSinkAudioLocationCharacteristicUuid) { + "Found Source PAC characteristic, handle: 0x{:04x}, ccc handle: 0x{:04x}, addr: {}", + charac.value_handle, hdl_pair.ccc_hdl, leAudioDevice->address_); + } else if (charac.uuid == bluetooth::le_audio::uuid::kSinkAudioLocationCharacteristicUuid) { leAudioDevice->snk_audio_locations_hdls_.val_hdl = charac.value_handle; - leAudioDevice->snk_audio_locations_hdls_.ccc_hdl = - find_ccc_handle(charac); + leAudioDevice->snk_audio_locations_hdls_.ccc_hdl = find_ccc_handle(charac); if (leAudioDevice->snk_audio_locations_hdls_.ccc_hdl == 0) { log::info(", snk audio locations char doesn't have ccc"); } if (leAudioDevice->snk_audio_locations_hdls_.ccc_hdl != 0 && - !subscribe_for_notification( - conn_id, leAudioDevice->address_, - leAudioDevice->snk_audio_locations_hdls_)) { - disconnectInvalidDevice( - leAudioDevice, ", could not subscribe for snk locations char", - LeAudioHealthDeviceStatType::INVALID_DB); + !subscribe_for_notification(conn_id, leAudioDevice->address_, + leAudioDevice->snk_audio_locations_hdls_)) { + disconnectInvalidDevice(leAudioDevice, ", could not subscribe for snk locations char", + LeAudioHealthDeviceStatType::INVALID_DB); return; } /* Obtain initial state of sink audio locations */ - BtaGattQueue::ReadCharacteristic( - conn_id, leAudioDevice->snk_audio_locations_hdls_.val_hdl, - OnGattReadRspStatic, NULL); + BtaGattQueue::ReadCharacteristic(conn_id, leAudioDevice->snk_audio_locations_hdls_.val_hdl, + OnGattReadRspStatic, NULL); log::info( - "Found Sink audio locations characteristic, handle: 0x{:04x}, ccc " - "handle: 0x{:04x}, addr: {}", - charac.value_handle, - leAudioDevice->snk_audio_locations_hdls_.ccc_hdl, - leAudioDevice->address_); - } else if (charac.uuid == bluetooth::le_audio::uuid:: - kSourceAudioLocationCharacteristicUuid) { + "Found Sink audio locations characteristic, handle: 0x{:04x}, ccc " + "handle: 0x{:04x}, addr: {}", + charac.value_handle, leAudioDevice->snk_audio_locations_hdls_.ccc_hdl, + leAudioDevice->address_); + } else if (charac.uuid == bluetooth::le_audio::uuid::kSourceAudioLocationCharacteristicUuid) { leAudioDevice->src_audio_locations_hdls_.val_hdl = charac.value_handle; - leAudioDevice->src_audio_locations_hdls_.ccc_hdl = - find_ccc_handle(charac); + leAudioDevice->src_audio_locations_hdls_.ccc_hdl = find_ccc_handle(charac); if (leAudioDevice->src_audio_locations_hdls_.ccc_hdl == 0) { log::info(", src audio locations char doesn't have ccc"); } if (leAudioDevice->src_audio_locations_hdls_.ccc_hdl != 0 && - !subscribe_for_notification( - conn_id, leAudioDevice->address_, - leAudioDevice->src_audio_locations_hdls_)) { - disconnectInvalidDevice( - leAudioDevice, ", could not subscribe for src locations char", - LeAudioHealthDeviceStatType::INVALID_DB); + !subscribe_for_notification(conn_id, leAudioDevice->address_, + leAudioDevice->src_audio_locations_hdls_)) { + disconnectInvalidDevice(leAudioDevice, ", could not subscribe for src locations char", + LeAudioHealthDeviceStatType::INVALID_DB); return; } /* Obtain initial state of source audio locations */ - BtaGattQueue::ReadCharacteristic( - conn_id, leAudioDevice->src_audio_locations_hdls_.val_hdl, - OnGattReadRspStatic, NULL); + BtaGattQueue::ReadCharacteristic(conn_id, leAudioDevice->src_audio_locations_hdls_.val_hdl, + OnGattReadRspStatic, NULL); log::info( - "Found Source audio locations characteristic, handle: 0x{:04x}, " - "ccc handle: 0x{:04x}, addr: {}", - charac.value_handle, - leAudioDevice->src_audio_locations_hdls_.ccc_hdl, - leAudioDevice->address_); + "Found Source audio locations characteristic, handle: 0x{:04x}, " + "ccc handle: 0x{:04x}, addr: {}", + charac.value_handle, leAudioDevice->src_audio_locations_hdls_.ccc_hdl, + leAudioDevice->address_); } else if (charac.uuid == - bluetooth::le_audio::uuid:: - kAudioContextAvailabilityCharacteristicUuid) { + bluetooth::le_audio::uuid::kAudioContextAvailabilityCharacteristicUuid) { leAudioDevice->audio_avail_hdls_.val_hdl = charac.value_handle; leAudioDevice->audio_avail_hdls_.ccc_hdl = find_ccc_handle(charac); if (leAudioDevice->audio_avail_hdls_.ccc_hdl == 0) { - disconnectInvalidDevice(leAudioDevice, - ", audio avails char doesn't have ccc", + disconnectInvalidDevice(leAudioDevice, ", audio avails char doesn't have ccc", LeAudioHealthDeviceStatType::INVALID_DB); return; } if (!subscribe_for_notification(conn_id, leAudioDevice->address_, leAudioDevice->audio_avail_hdls_)) { - disconnectInvalidDevice(leAudioDevice, - ", could not subscribe for audio avails char", + disconnectInvalidDevice(leAudioDevice, ", could not subscribe for audio avails char", LeAudioHealthDeviceStatType::INVALID_DB); return; } /* Obtain initial state */ - BtaGattQueue::ReadCharacteristic( - conn_id, leAudioDevice->audio_avail_hdls_.val_hdl, - OnGattReadRspStatic, NULL); + BtaGattQueue::ReadCharacteristic(conn_id, leAudioDevice->audio_avail_hdls_.val_hdl, + OnGattReadRspStatic, NULL); log::info( - "Found Audio Availability Context characteristic, handle: " - "0x{:04x}, ccc handle: 0x{:04x}, addr: {}", - charac.value_handle, leAudioDevice->audio_avail_hdls_.ccc_hdl, - leAudioDevice->address_); - } else if (charac.uuid == bluetooth::le_audio::uuid:: - kAudioSupportedContextCharacteristicUuid) { + "Found Audio Availability Context characteristic, handle: " + "0x{:04x}, ccc handle: 0x{:04x}, addr: {}", + charac.value_handle, leAudioDevice->audio_avail_hdls_.ccc_hdl, + leAudioDevice->address_); + } else if (charac.uuid == + bluetooth::le_audio::uuid::kAudioSupportedContextCharacteristicUuid) { leAudioDevice->audio_supp_cont_hdls_.val_hdl = charac.value_handle; leAudioDevice->audio_supp_cont_hdls_.ccc_hdl = find_ccc_handle(charac); @@ -2939,23 +2780,21 @@ class LeAudioClientImpl : public LeAudioClient { if (leAudioDevice->audio_supp_cont_hdls_.ccc_hdl != 0 && !subscribe_for_notification(conn_id, leAudioDevice->address_, leAudioDevice->audio_supp_cont_hdls_)) { - disconnectInvalidDevice( - leAudioDevice, - ", could not subscribe for audio supported ctx char", - LeAudioHealthDeviceStatType::INVALID_DB); + disconnectInvalidDevice(leAudioDevice, + ", could not subscribe for audio supported ctx char", + LeAudioHealthDeviceStatType::INVALID_DB); return; } /* Obtain initial state */ - BtaGattQueue::ReadCharacteristic( - conn_id, leAudioDevice->audio_supp_cont_hdls_.val_hdl, - OnGattReadRspStatic, NULL); + BtaGattQueue::ReadCharacteristic(conn_id, leAudioDevice->audio_supp_cont_hdls_.val_hdl, + OnGattReadRspStatic, NULL); log::info( - "Found Audio Supported Context characteristic, handle: 0x{:04x}, " - "ccc handle: 0x{:04x}, addr: {}", - charac.value_handle, leAudioDevice->audio_supp_cont_hdls_.ccc_hdl, - leAudioDevice->address_); + "Found Audio Supported Context characteristic, handle: 0x{:04x}, " + "ccc handle: 0x{:04x}, addr: {}", + charac.value_handle, leAudioDevice->audio_supp_cont_hdls_.ccc_hdl, + leAudioDevice->address_); } } @@ -2964,43 +2803,33 @@ class LeAudioClientImpl : public LeAudioClient { for (const gatt::Characteristic& charac : ase_svc->characteristics) { log::info("Found characteristic, uuid: {}", charac.uuid.ToString()); - if (charac.uuid == - bluetooth::le_audio::uuid::kSinkAudioStreamEndpointUuid || - charac.uuid == - bluetooth::le_audio::uuid::kSourceAudioStreamEndpointUuid) { + if (charac.uuid == bluetooth::le_audio::uuid::kSinkAudioStreamEndpointUuid || + charac.uuid == bluetooth::le_audio::uuid::kSourceAudioStreamEndpointUuid) { uint16_t ccc_handle = find_ccc_handle(charac); if (ccc_handle == 0) { disconnectInvalidDevice(leAudioDevice, ", ASE char doesn't have ccc", LeAudioHealthDeviceStatType::INVALID_DB); return; } - struct bluetooth::le_audio::types::hdl_pair hdls(charac.value_handle, - ccc_handle); - if (!subscribe_for_notification(conn_id, leAudioDevice->address_, - hdls)) { - disconnectInvalidDevice(leAudioDevice, - ", could not subscribe ASE char", + struct bluetooth::le_audio::types::hdl_pair hdls(charac.value_handle, ccc_handle); + if (!subscribe_for_notification(conn_id, leAudioDevice->address_, hdls)) { + disconnectInvalidDevice(leAudioDevice, ", could not subscribe ASE char", LeAudioHealthDeviceStatType::INVALID_DB); return; } - int direction = - charac.uuid == - bluetooth::le_audio::uuid::kSinkAudioStreamEndpointUuid - ? bluetooth::le_audio::types::kLeAudioDirectionSink - : bluetooth::le_audio::types::kLeAudioDirectionSource; + int direction = charac.uuid == bluetooth::le_audio::uuid::kSinkAudioStreamEndpointUuid + ? bluetooth::le_audio::types::kLeAudioDirectionSink + : bluetooth::le_audio::types::kLeAudioDirectionSource; - leAudioDevice->ases_.emplace_back(charac.value_handle, ccc_handle, - direction); + leAudioDevice->ases_.emplace_back(charac.value_handle, ccc_handle, direction); log::info( - "Found ASE characteristic, handle: 0x{:04x}, ccc handle: 0x{:04x}, " - "direction: {}, addr: {}", - charac.value_handle, ccc_handle, direction, - leAudioDevice->address_); + "Found ASE characteristic, handle: 0x{:04x}, ccc handle: 0x{:04x}, " + "direction: {}, addr: {}", + charac.value_handle, ccc_handle, direction, leAudioDevice->address_); } else if (charac.uuid == - bluetooth::le_audio::uuid:: - kAudioStreamEndpointControlPointCharacteristicUuid) { + bluetooth::le_audio::uuid::kAudioStreamEndpointControlPointCharacteristicUuid) { leAudioDevice->ctp_hdls_.val_hdl = charac.value_handle; leAudioDevice->ctp_hdls_.ccc_hdl = find_ccc_handle(charac); @@ -3012,36 +2841,31 @@ class LeAudioClientImpl : public LeAudioClient { if (!subscribe_for_notification(conn_id, leAudioDevice->address_, leAudioDevice->ctp_hdls_)) { - disconnectInvalidDevice(leAudioDevice, - ", could not subscribe ASE char", + disconnectInvalidDevice(leAudioDevice, ", could not subscribe ASE char", LeAudioHealthDeviceStatType::INVALID_DB); return; } log::info( - "Found ASE Control Point characteristic, handle: 0x{:04x}, ccc " - "handle: 0x{:04x}, addr: {}", - charac.value_handle, leAudioDevice->ctp_hdls_.ccc_hdl, - leAudioDevice->address_); + "Found ASE Control Point characteristic, handle: 0x{:04x}, ccc " + "handle: 0x{:04x}, addr: {}", + charac.value_handle, leAudioDevice->ctp_hdls_.ccc_hdl, leAudioDevice->address_); } } if (tmas_svc) { for (const gatt::Characteristic& charac : tmas_svc->characteristics) { if (charac.uuid == - bluetooth::le_audio::uuid:: - kTelephonyMediaAudioProfileRoleCharacteristicUuid) { + bluetooth::le_audio::uuid::kTelephonyMediaAudioProfileRoleCharacteristicUuid) { leAudioDevice->tmap_role_hdl_ = charac.value_handle; /* Obtain initial state of TMAP role */ - BtaGattQueue::ReadCharacteristic(conn_id, - leAudioDevice->tmap_role_hdl_, + BtaGattQueue::ReadCharacteristic(conn_id, leAudioDevice->tmap_role_hdl_, OnGattReadRspStatic, NULL); log::info( - "Found Telephony and Media Profile characteristic, handle: " - "0x{:04x}, device: {}", - leAudioDevice->tmap_role_hdl_, leAudioDevice->address_); + "Found Telephony and Media Profile characteristic, handle: 0x{:04x}, device: {}", + leAudioDevice->tmap_role_hdl_, leAudioDevice->address_); } } } @@ -3049,8 +2873,8 @@ class LeAudioClientImpl : public LeAudioClient { leAudioDevice->known_service_handles_ = true; leAudioDevice->notify_connected_after_read_ = true; if (leAudioHealthStatus_) { - leAudioHealthStatus_->AddStatisticForDevice( - leAudioDevice, LeAudioHealthDeviceStatType::VALID_DB); + leAudioHealthStatus_->AddStatisticForDevice(leAudioDevice, + LeAudioHealthDeviceStatType::VALID_DB); } /* If already known group id */ @@ -3060,11 +2884,11 @@ class LeAudioClientImpl : public LeAudioClient { } /* If device does not belong to any group yet we either add it to the - * group by our selfs now or wait for Csis to do it. In both cases, let's + * group by our self now or wait for Csis to do it. In both cases, let's * check if group is already assigned. */ - int group_id = DeviceGroups::Get()->GetGroupId( - leAudioDevice->address_, bluetooth::le_audio::uuid::kCapServiceUuid); + int group_id = DeviceGroups::Get()->GetGroupId(leAudioDevice->address_, + bluetooth::le_audio::uuid::kCapServiceUuid); if (group_id != bluetooth::groups::kGroupUnknown) { instance->group_add_node(group_id, leAudioDevice->address_); return; @@ -3072,22 +2896,19 @@ class LeAudioClientImpl : public LeAudioClient { /* CSIS will trigger adding to group */ if (leAudioDevice->csis_member_) { - log::info("{}, waiting for CSIS to create group for device", - leAudioDevice->address_); + log::info("{}, waiting for CSIS to create group for device", leAudioDevice->address_); scheduleGuardForCsisAdd(leAudioDevice->address_); return; } - log::info("{} Not a CSIS member. Create group by our own", - leAudioDevice->address_); + log::info("{} Not a CSIS member. Create group by our own", leAudioDevice->address_); /* If there is no Csis just add device by our own */ DeviceGroups::Get()->AddDevice(leAudioDevice->address_, bluetooth::le_audio::uuid::kCapServiceUuid); } - void OnGattWriteCcc(uint16_t conn_id, tGATT_STATUS status, uint16_t hdl, - void* data) { + void OnGattWriteCcc(uint16_t conn_id, tGATT_STATUS status, uint16_t hdl, void* data) { LeAudioDevice* leAudioDevice = leAudioDevices_.FindByConnId(conn_id); std::vector::iterator ase_it; @@ -3097,8 +2918,7 @@ class LeAudioClientImpl : public LeAudioClient { } if (status == GATT_DATABASE_OUT_OF_SYNC) { - log::info("Database out of sync for {}, conn_id: 0x{:04x}", - leAudioDevice->address_, conn_id); + log::info("Database out of sync for {}, conn_id: 0x{:04x}", leAudioDevice->address_, conn_id); ClearDeviceInformationAndStartSearch(leAudioDevice); return; } @@ -3107,8 +2927,7 @@ class LeAudioClientImpl : public LeAudioClient { log::info("Successfully registered on ccc: 0x{:04x}, device: {}", hdl, leAudioDevice->address_); - if (leAudioDevice->ctp_hdls_.ccc_hdl == hdl && - leAudioDevice->known_service_handles_ && + if (leAudioDevice->ctp_hdls_.ccc_hdl == hdl && leAudioDevice->known_service_handles_ && !leAudioDevice->notify_connected_after_read_) { /* Reconnection case. Control point is the last CCC LeAudio is * registering for on reconnection */ @@ -3118,56 +2937,45 @@ class LeAudioClientImpl : public LeAudioClient { return; } - log::error( - "Failed to register for notifications: 0x{:04x}, device: {}, status: " - "0x{:02x}", - hdl, leAudioDevice->address_, status); + log::error("Failed to register for notifications: 0x{:04x}, device: {}, status: 0x{:02x}", hdl, + leAudioDevice->address_, status); ase_it = - std::find_if(leAudioDevice->ases_.begin(), leAudioDevice->ases_.end(), - [&hdl](const struct ase& ase) -> bool { - return ase.hdls.ccc_hdl == hdl; - }); + std::find_if(leAudioDevice->ases_.begin(), leAudioDevice->ases_.end(), + [&hdl](const struct ase& ase) -> bool { return ase.hdls.ccc_hdl == hdl; }); if (ase_it == leAudioDevice->ases_.end()) { - log::error("Unknown ccc handle: 0x{:04x}, device: {}", hdl, - leAudioDevice->address_); + log::error("Unknown ccc handle: 0x{:04x}, device: {}", hdl, leAudioDevice->address_); return; } - BTA_GATTC_DeregisterForNotifications(gatt_if_, leAudioDevice->address_, - ase_it->hdls.val_hdl); + BTA_GATTC_DeregisterForNotifications(gatt_if_, leAudioDevice->address_, ase_it->hdls.val_hdl); } void AttachToStreamingGroupIfNeeded(LeAudioDevice* leAudioDevice) { if (leAudioDevice->group_id_ != active_group_id_) { - log::info("group {} is not streaming. Nothing to do", - leAudioDevice->group_id_); + log::info("group {} is not streaming. Nothing to do", leAudioDevice->group_id_); return; } if (leAudioDevice->HaveActiveAse()) { - log::debug("{} is already configured, nothing to do", - leAudioDevice->address_); + log::debug("{} is already configured, nothing to do", leAudioDevice->address_); return; } LeAudioDeviceGroup* group = aseGroups_.FindById(active_group_id_); - auto group_metadata_contexts = - get_bidirectional(group->GetMetadataContexts()); + auto group_metadata_contexts = get_bidirectional(group->GetMetadataContexts()); auto device_available_contexts = leAudioDevice->GetAvailableContexts(); if (!group_metadata_contexts.test_any(device_available_contexts)) { - log::info("{} does is not have required context type", - leAudioDevice->address_); + log::info("{} does is not have required context type", leAudioDevice->address_); return; } /* Restore configuration */ auto* stream_conf = &group->stream_conf; - if (audio_sender_state_ == AudioState::IDLE && - audio_receiver_state_ == AudioState::IDLE) { + if (audio_sender_state_ == AudioState::IDLE && audio_receiver_state_ == AudioState::IDLE) { log::debug("Device not streaming but active - nothing to do"); return; } @@ -3177,30 +2985,24 @@ class LeAudioClientImpl : public LeAudioClient { return; } - log::info("Attaching {} to group: {}", leAudioDevice->address_, - leAudioDevice->group_id_); + log::info("Attaching {} to group: {}", leAudioDevice->address_, leAudioDevice->group_id_); - for (auto direction : - {bluetooth::le_audio::types::kLeAudioDirectionSink, - bluetooth::le_audio::types::kLeAudioDirectionSource}) { + for (auto direction : {bluetooth::le_audio::types::kLeAudioDirectionSink, + bluetooth::le_audio::types::kLeAudioDirectionSource}) { log::info("Looking for requirements: {} - {}", stream_conf->conf->name, - ((direction == 1 ? "snk" : "src"))); - const auto& pacs = - (direction == bluetooth::le_audio::types::kLeAudioDirectionSink) - ? leAudioDevice->snk_pacs_ - : leAudioDevice->src_pacs_; + (direction == 1 ? "snk" : "src")); + const auto& pacs = (direction == bluetooth::le_audio::types::kLeAudioDirectionSink) + ? leAudioDevice->snk_pacs_ + : leAudioDevice->src_pacs_; for (const auto& ent : stream_conf->conf->confs.get(direction)) { - if (!bluetooth::le_audio::utils::GetConfigurationSupportedPac( - pacs, ent.codec)) { - log::info("Configuration is not supported by device {}", - leAudioDevice->address_); + if (!bluetooth::le_audio::utils::GetConfigurationSupportedPac(pacs, ent.codec)) { + log::info("Configuration is not supported by device {}", leAudioDevice->address_); /* Reconfigure if newly connected member device cannot support * current codec configuration */ group->SetPendingConfiguration(); groupStateMachine_->StopStream(group); - stream_setup_start_timestamp_ = - bluetooth::common::time_get_os_boottime_us(); + stream_setup_start_timestamp_ = bluetooth::common::time_get_os_boottime_us(); return; } } @@ -3213,26 +3015,21 @@ class LeAudioClientImpl : public LeAudioClient { ccid_contexts.source.unset(LeAudioContextType::CONVERSATIONAL); } BidirectionalPair> ccids = { - .sink = ContentControlIdKeeper::GetInstance()->GetAllCcids( - ccid_contexts.sink), - .source = ContentControlIdKeeper::GetInstance()->GetAllCcids( - ccid_contexts.source)}; - - if (!groupStateMachine_->AttachToStream(group, leAudioDevice, - std::move(ccids))) { - log::warn("Could not add device {} to the group {} streaming.", - leAudioDevice->address_, group->group_id_); + .sink = ContentControlIdKeeper::GetInstance()->GetAllCcids(ccid_contexts.sink), + .source = ContentControlIdKeeper::GetInstance()->GetAllCcids(ccid_contexts.source)}; + + if (!groupStateMachine_->AttachToStream(group, leAudioDevice, std::move(ccids))) { + log::warn("Could not add device {} to the group {} streaming.", leAudioDevice->address_, + group->group_id_); scheduleAttachDeviceToTheStream(leAudioDevice->address_); } else { - stream_setup_start_timestamp_ = - bluetooth::common::time_get_os_boottime_us(); + stream_setup_start_timestamp_ = bluetooth::common::time_get_os_boottime_us(); } } void restartAttachToTheStream(const RawAddress& addr) { LeAudioDevice* leAudioDevice = leAudioDevices_.FindByAddress(addr); - if (leAudioDevice == nullptr || - leAudioDevice->conn_id_ == GATT_INVALID_CONN_ID) { + if (leAudioDevice == nullptr || leAudioDevice->conn_id_ == GATT_INVALID_CONN_ID) { log::info("Device {} not available anymore", addr); return; } @@ -3241,21 +3038,20 @@ class LeAudioClientImpl : public LeAudioClient { void scheduleAttachDeviceToTheStream(const RawAddress& addr) { log::info("Device {} scheduler for stream", addr); - do_in_main_thread_delayed( - FROM_HERE, - base::BindOnce(&LeAudioClientImpl::restartAttachToTheStream, - weak_factory_.GetWeakPtr(), addr), - std::chrono::milliseconds(kDeviceAttachDelayMs)); + do_in_main_thread_delayed(FROM_HERE, + base::BindOnce(&LeAudioClientImpl::restartAttachToTheStream, + weak_factory_.GetWeakPtr(), addr), + std::chrono::milliseconds(kDeviceAttachDelayMs)); } void SendAudioGroupSelectableCodecConfigChanged(LeAudioDeviceGroup* group) { auto leAudioDevice = group->GetFirstDevice(); callbacks_->OnAudioGroupSelectableCodecConf( - group->group_id_, - bluetooth::le_audio::utils::GetRemoteBtLeAudioCodecConfigFromPac( - leAudioDevice->src_pacs_), - bluetooth::le_audio::utils::GetRemoteBtLeAudioCodecConfigFromPac( - leAudioDevice->snk_pacs_)); + group->group_id_, + bluetooth::le_audio::utils::GetRemoteBtLeAudioCodecConfigFromPac( + leAudioDevice->src_pacs_), + bluetooth::le_audio::utils::GetRemoteBtLeAudioCodecConfigFromPac( + leAudioDevice->snk_pacs_)); } void SendAudioGroupCurrentCodecConfigChanged(LeAudioDeviceGroup* group) { @@ -3264,32 +3060,29 @@ class LeAudioClientImpl : public LeAudioClient { auto audio_set_conf = group->GetConfiguration(configuration_context_type_); if (!audio_set_conf) { - log::warn("Stream configuration is not valid for group id {}", - group->group_id_); + log::warn("Stream configuration is not valid for group id {}", group->group_id_); return; } bluetooth::le_audio::btle_audio_codec_config_t input_config{}; - bluetooth::le_audio::utils::fillStreamParamsToBtLeAudioCodecConfig( - audio_set_conf->confs.source, input_config); + bluetooth::le_audio::utils::fillStreamParamsToBtLeAudioCodecConfig(audio_set_conf->confs.source, + input_config); bluetooth::le_audio::btle_audio_codec_config_t output_config{}; - bluetooth::le_audio::utils::fillStreamParamsToBtLeAudioCodecConfig( - audio_set_conf->confs.sink, output_config); + bluetooth::le_audio::utils::fillStreamParamsToBtLeAudioCodecConfig(audio_set_conf->confs.sink, + output_config); - callbacks_->OnAudioGroupCurrentCodecConf(group->group_id_, input_config, - output_config); + callbacks_->OnAudioGroupCurrentCodecConf(group->group_id_, input_config, output_config); } void connectionReady(LeAudioDevice* leAudioDevice) { - log::debug( - "{}, {}", leAudioDevice->address_, - bluetooth::common::ToString(leAudioDevice->GetConnectionState())); + log::debug("{}, {}", leAudioDevice->address_, + bluetooth::common::ToString(leAudioDevice->GetConnectionState())); L2CA_LockBleConnParamsForProfileConnection(leAudioDevice->address_, false); if (leAudioDevice->GetConnectionState() == - DeviceConnectState::CONNECTED_BY_USER_GETTING_READY && + DeviceConnectState::CONNECTED_BY_USER_GETTING_READY && (leAudioDevice->autoconnect_flag_ == false)) { btif_storage_set_leaudio_autoconnect(leAudioDevice->address_, true); leAudioDevice->autoconnect_flag_ = true; @@ -3297,15 +3090,12 @@ class LeAudioClientImpl : public LeAudioClient { leAudioDevice->SetConnectionState(DeviceConnectState::CONNECTED); bluetooth::le_audio::MetricsCollector::Get()->OnConnectionStateChanged( - leAudioDevice->group_id_, leAudioDevice->address_, - ConnectionState::CONNECTED, - bluetooth::le_audio::ConnectionStatus::SUCCESS); + leAudioDevice->group_id_, leAudioDevice->address_, ConnectionState::CONNECTED, + bluetooth::le_audio::ConnectionStatus::SUCCESS); if (leAudioDevice->group_id_ == bluetooth::groups::kGroupUnknown) { - log::warn("LeAudio device {} connected with no group", - leAudioDevice->address_); - callbacks_->OnConnectionState(ConnectionState::CONNECTED, - leAudioDevice->address_); + log::warn("LeAudio device {} connected with no group", leAudioDevice->address_); + callbacks_->OnConnectionState(ConnectionState::CONNECTED, leAudioDevice->address_); return; } @@ -3315,8 +3105,7 @@ class LeAudioClientImpl : public LeAudioClient { } /* Notify connected after contexts are notified */ - callbacks_->OnConnectionState(ConnectionState::CONNECTED, - leAudioDevice->address_); + callbacks_->OnConnectionState(ConnectionState::CONNECTED, leAudioDevice->address_); AttachToStreamingGroupIfNeeded(leAudioDevice); @@ -3329,16 +3118,22 @@ class LeAudioClientImpl : public LeAudioClient { } bool IsAseAcceptingAudioData(struct ase* ase) { - if (ase == nullptr) return false; - if (ase->state != AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) return false; - if (ase->data_path_state != DataPathState::CONFIGURED) return false; + if (ase == nullptr) { + return false; + } + if (ase->state != AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) { + return false; + } + if (ase->data_path_state != DataPathState::CONFIGURED) { + return false; + } return true; } // mix stero signal into mono - std::vector mono_blend(const std::vector& buf, - int bytes_per_sample, size_t frames) { + std::vector mono_blend(const std::vector& buf, int bytes_per_sample, + size_t frames) { std::vector mono_out; mono_out.resize(frames * bytes_per_sample); @@ -3369,41 +3164,39 @@ class LeAudioClientImpl : public LeAudioClient { } void PrepareAndSendToTwoCises( - const std::vector& data, - const struct bluetooth::le_audio::stream_parameters& stream_params) { + const std::vector& data, + const struct bluetooth::le_audio::stream_parameters& stream_params) { uint16_t left_cis_handle = 0; uint16_t right_cis_handle = 0; - uint16_t number_of_required_samples_per_channel = - sw_enc_left->GetNumOfSamplesPerChannel(); + uint16_t number_of_required_samples_per_channel = sw_enc_left->GetNumOfSamplesPerChannel(); uint8_t bytes_per_sample = sw_enc_left->GetNumOfBytesPerSample(); - if (data.size() < bytes_per_sample * 2 /* channels */ * - number_of_required_samples_per_channel) { + if (data.size() < + bytes_per_sample * 2 /* channels */ * number_of_required_samples_per_channel) { log::error("Missing samples. Data size: {} expected: {}", data.size(), bytes_per_sample * 2 * number_of_required_samples_per_channel); return; } for (auto [cis_handle, audio_location] : stream_params.stream_locations) { - if (audio_location & - bluetooth::le_audio::codec_spec_conf::kLeAudioLocationAnyLeft) + if (audio_location & bluetooth::le_audio::codec_spec_conf::kLeAudioLocationAnyLeft) { left_cis_handle = cis_handle; - if (audio_location & - bluetooth::le_audio::codec_spec_conf::kLeAudioLocationAnyRight) + } + if (audio_location & bluetooth::le_audio::codec_spec_conf::kLeAudioLocationAnyRight) { right_cis_handle = cis_handle; + } } if (stream_params.codec_frames_blocks_per_sdu != 1) { - log::error( - "Codec Frame Blocks of {} is not supported by the software encoding", - +stream_params.codec_frames_blocks_per_sdu); + log::error("Codec Frame Blocks of {} is not supported by the software encoding", + +stream_params.codec_frames_blocks_per_sdu); } uint16_t byte_count = stream_params.octets_per_codec_frame; bool mix_to_mono = (left_cis_handle == 0) || (right_cis_handle == 0); if (mix_to_mono) { - std::vector mono = mono_blend( - data, bytes_per_sample, number_of_required_samples_per_channel); + std::vector mono = + mono_blend(data, bytes_per_sample, number_of_required_samples_per_channel); if (left_cis_handle) { sw_enc_left->Encode(mono.data(), 1, byte_count); } @@ -3416,41 +3209,38 @@ class LeAudioClientImpl : public LeAudioClient { sw_enc_right->Encode(data.data() + bytes_per_sample, 2, byte_count); } - log::debug("left_cis_handle: {} right_cis_handle: {}", left_cis_handle, - right_cis_handle); + log::debug("left_cis_handle: {} right_cis_handle: {}", left_cis_handle, right_cis_handle); /* Send data to the controller */ - if (left_cis_handle) + if (left_cis_handle) { IsoManager::GetInstance()->SendIsoData( - left_cis_handle, - (const uint8_t*)sw_enc_left->GetDecodedSamples().data(), - sw_enc_left->GetDecodedSamples().size() * 2); + left_cis_handle, (const uint8_t*)sw_enc_left->GetDecodedSamples().data(), + sw_enc_left->GetDecodedSamples().size() * 2); + } - if (right_cis_handle) + if (right_cis_handle) { IsoManager::GetInstance()->SendIsoData( - right_cis_handle, - (const uint8_t*)sw_enc_right->GetDecodedSamples().data(), - sw_enc_right->GetDecodedSamples().size() * 2); + right_cis_handle, (const uint8_t*)sw_enc_right->GetDecodedSamples().data(), + sw_enc_right->GetDecodedSamples().size() * 2); + } } void PrepareAndSendToSingleCis( - const std::vector& data, - const struct bluetooth::le_audio::stream_parameters& stream_params) { + const std::vector& data, + const struct bluetooth::le_audio::stream_parameters& stream_params) { uint16_t num_channels = stream_params.num_of_channels; uint16_t cis_handle = stream_params.stream_locations.front().first; - uint16_t number_of_required_samples_per_channel = - sw_enc_left->GetNumOfSamplesPerChannel(); + uint16_t number_of_required_samples_per_channel = sw_enc_left->GetNumOfSamplesPerChannel(); uint8_t bytes_per_sample = sw_enc_left->GetNumOfBytesPerSample(); - if ((int)data.size() < (bytes_per_sample * num_channels * - number_of_required_samples_per_channel)) { + if ((int)data.size() < + (bytes_per_sample * num_channels * number_of_required_samples_per_channel)) { log::error("Missing samples"); return; } if (stream_params.codec_frames_blocks_per_sdu != 1) { - log::error( - "Codec Frame Blocks of {} is not supported by the software encoding", - +stream_params.codec_frames_blocks_per_sdu); + log::error("Codec Frame Blocks of {} is not supported by the software encoding", + +stream_params.codec_frames_blocks_per_sdu); } uint16_t byte_count = stream_params.octets_per_codec_frame; @@ -3458,8 +3248,8 @@ class LeAudioClientImpl : public LeAudioClient { if (mix_to_mono) { /* Since we always get two channels from framework, lets make it mono here */ - std::vector mono = mono_blend( - data, bytes_per_sample, number_of_required_samples_per_channel); + std::vector mono = + mono_blend(data, bytes_per_sample, number_of_required_samples_per_channel); sw_enc_left->Encode(mono.data(), 1, byte_count); } else { sw_enc_left->Encode((const uint8_t*)data.data(), 2, byte_count); @@ -3468,15 +3258,14 @@ class LeAudioClientImpl : public LeAudioClient { &sw_enc_left->GetDecodedSamples(), byte_count); } - IsoManager::GetInstance()->SendIsoData( - cis_handle, (const uint8_t*)sw_enc_left->GetDecodedSamples().data(), - sw_enc_left->GetDecodedSamples().size() * 2); + IsoManager::GetInstance()->SendIsoData(cis_handle, + (const uint8_t*)sw_enc_left->GetDecodedSamples().data(), + sw_enc_left->GetDecodedSamples().size() * 2); } - const struct bluetooth::le_audio::stream_configuration* - GetStreamSinkConfiguration(LeAudioDeviceGroup* group) { - const struct bluetooth::le_audio::stream_configuration* stream_conf = - &group->stream_conf; + const struct bluetooth::le_audio::stream_configuration* GetStreamSinkConfiguration( + LeAudioDeviceGroup* group) { + const struct bluetooth::le_audio::stream_configuration* stream_conf = &group->stream_conf; log::info("group_id: {}", group->group_id_); if (stream_conf->stream_params.sink.stream_locations.size() == 0) { return nullptr; @@ -3488,8 +3277,9 @@ class LeAudioClientImpl : public LeAudioClient { void OnAudioDataReady(const std::vector& data) { if ((active_group_id_ == bluetooth::groups::kGroupUnknown) || - (audio_sender_state_ != AudioState::STARTED)) + (audio_sender_state_ != AudioState::STARTED)) { return; + } LeAudioDeviceGroup* group = aseGroups_.FindById(active_group_id_); if (!group) { @@ -3521,13 +3311,14 @@ class LeAudioClientImpl : public LeAudioClient { } /* Handles audio data packets coming from the controller */ - void HandleIncomingCisData(uint8_t* data, uint16_t size, - uint16_t cis_conn_hdl, uint32_t timestamp) { + void HandleIncomingCisData(uint8_t* data, uint16_t size, uint16_t cis_conn_hdl, + uint32_t timestamp) { /* Get only one channel for MONO microphone */ /* Gather data for channel */ if ((active_group_id_ == bluetooth::groups::kGroupUnknown) || - (audio_receiver_state_ != AudioState::STARTED)) + (audio_receiver_state_ != AudioState::STARTED)) { return; + } LeAudioDeviceGroup* group = aseGroups_.FindById(active_group_id_); if (!group) { @@ -3539,12 +3330,10 @@ class LeAudioClientImpl : public LeAudioClient { uint16_t right_cis_handle = 0; for (auto [cis_handle, audio_location] : group->stream_conf.stream_params.source.stream_locations) { - if (audio_location & - bluetooth::le_audio::codec_spec_conf::kLeAudioLocationAnyLeft) { + if (audio_location & bluetooth::le_audio::codec_spec_conf::kLeAudioLocationAnyLeft) { left_cis_handle = cis_handle; } - if (audio_location & - bluetooth::le_audio::codec_spec_conf::kLeAudioLocationAnyRight) { + if (audio_location & bluetooth::le_audio::codec_spec_conf::kLeAudioLocationAnyRight) { right_cis_handle = cis_handle; } } @@ -3567,8 +3356,7 @@ class LeAudioClientImpl : public LeAudioClient { } /* both devices are connected */ - if (cached_channel_ == nullptr || - cached_channel_->GetDecodedSamples().empty()) { + if (cached_channel_ == nullptr || cached_channel_->GetDecodedSamples().empty()) { /* First packet received, cache it. We need both channel data to send it * to AF. */ decoder->Decode(data, size); @@ -3584,8 +3372,7 @@ class LeAudioClientImpl : public LeAudioClient { if (timestamp == cached_channel_timestamp_) { /* Ready to mix data and send out to AF */ decoder->Decode(data, size); - SendAudioDataToAF(&sw_dec_left->GetDecodedSamples(), - &sw_dec_right->GetDecodedSamples()); + SendAudioDataToAF(&sw_dec_left->GetDecodedSamples(), &sw_dec_right->GetDecodedSamples()); CleanCachedMicrophoneData(); return; @@ -3614,8 +3401,7 @@ class LeAudioClientImpl : public LeAudioClient { cached_channel_ = decoder; } - void SendAudioDataToAF(std::vector* left, - std::vector* right = nullptr) { + void SendAudioDataToAF(std::vector* left, std::vector* right = nullptr) { uint16_t to_write = 0; uint16_t written = 0; @@ -3627,16 +3413,14 @@ class LeAudioClientImpl : public LeAudioClient { std::vector* mono = left ? left : right; /* mono audio over bluetooth, audio framework expects mono */ to_write = sizeof(int16_t) * mono->size(); - written = le_audio_sink_hal_client_->SendData((uint8_t*)mono->data(), - to_write); + written = le_audio_sink_hal_client_->SendData((uint8_t*)mono->data(), to_write); } else { /* stereo audio over bluetooth, audio framework expects mono */ for (size_t i = 0; i < left->size(); i++) { (*left)[i] = ((*left)[i] + (*right)[i]) / 2; } to_write = sizeof(int16_t) * left->size(); - written = le_audio_sink_hal_client_->SendData((uint8_t*)left->data(), - to_write); + written = le_audio_sink_hal_client_->SendData((uint8_t*)left->data(), to_write); } } else { /* mono audio over bluetooth, audio framework expects stereo @@ -3650,21 +3434,21 @@ class LeAudioClientImpl : public LeAudioClient { mixed[2 * i + 1] = right ? (*right)[i] : (*left)[i]; } to_write = sizeof(int16_t) * mixed.size(); - written = - le_audio_sink_hal_client_->SendData((uint8_t*)mixed.data(), to_write); + written = le_audio_sink_hal_client_->SendData((uint8_t*)mixed.data(), to_write); } /* TODO: What to do if not all data sinked ? */ - if (written != to_write) log::error("not all data sinked"); + if (written != to_write) { + log::error("not all data sinked"); + } } void ConfirmLocalAudioSourceStreamingRequest() { le_audio_source_hal_client_->ConfirmStreamingRequest(); LeAudioLogHistory::Get()->AddLogHistory( - kLogBtCallAf, active_group_id_, RawAddress::kEmpty, - kLogAfResumeConfirm + "LocalSource", - "s_state: " + ToString(audio_sender_state_) + "-> STARTED"); + kLogBtCallAf, active_group_id_, RawAddress::kEmpty, kLogAfResumeConfirm + "LocalSource", + "s_state: " + ToString(audio_sender_state_) + "-> STARTED"); audio_sender_state_ = AudioState::STARTED; } @@ -3673,9 +3457,8 @@ class LeAudioClientImpl : public LeAudioClient { le_audio_sink_hal_client_->ConfirmStreamingRequest(); LeAudioLogHistory::Get()->AddLogHistory( - kLogBtCallAf, active_group_id_, RawAddress::kEmpty, - kLogAfResumeConfirm + "LocalSink", - "r_state: " + ToString(audio_receiver_state_) + "-> STARTED"); + kLogBtCallAf, active_group_id_, RawAddress::kEmpty, kLogAfResumeConfirm + "LocalSink", + "r_state: " + ToString(audio_receiver_state_) + "-> STARTED"); audio_receiver_state_ = AudioState::STARTED; } @@ -3696,47 +3479,37 @@ class LeAudioClientImpl : public LeAudioClient { } log::debug("Sink stream config (#{}):\n", - static_cast( - stream_conf->stream_params.sink.stream_locations.size())); + static_cast(stream_conf->stream_params.sink.stream_locations.size())); for (auto stream : stream_conf->stream_params.sink.stream_locations) { - log::debug("Cis handle: 0x{:02x}, allocation 0x{:04x}\n", stream.first, - stream.second); + log::debug("Cis handle: 0x{:02x}, allocation 0x{:04x}\n", stream.first, stream.second); } log::debug("Source stream config (#{}):\n", - static_cast( - stream_conf->stream_params.source.stream_locations.size())); + static_cast(stream_conf->stream_params.source.stream_locations.size())); for (auto stream : stream_conf->stream_params.source.stream_locations) { - log::debug("Cis handle: 0x{:02x}, allocation 0x{:04x}\n", stream.first, - stream.second); + log::debug("Cis handle: 0x{:02x}, allocation 0x{:04x}\n", stream.first, stream.second); } - uint16_t remote_delay_ms = group->GetRemoteDelay( - bluetooth::le_audio::types::kLeAudioDirectionSink); + uint16_t remote_delay_ms = + group->GetRemoteDelay(bluetooth::le_audio::types::kLeAudioDirectionSink); if (CodecManager::GetInstance()->GetCodecLocation() == bluetooth::le_audio::types::CodecLocation::HOST) { if (sw_enc_left || sw_enc_right) { log::warn("The encoder instance should have been already released."); } - sw_enc_left = bluetooth::le_audio::CodecInterface::CreateInstance( - stream_conf->codec_id); - auto codec_status = sw_enc_left->InitEncoder( - audio_framework_source_config, current_encoder_config_); - if (codec_status != - bluetooth::le_audio::CodecInterface::Status::STATUS_OK) { - log::error("Left channel codec setup failed with err: {}", - codec_status); + sw_enc_left = bluetooth::le_audio::CodecInterface::CreateInstance(stream_conf->codec_id); + auto codec_status = + sw_enc_left->InitEncoder(audio_framework_source_config, current_encoder_config_); + if (codec_status != bluetooth::le_audio::CodecInterface::Status::STATUS_OK) { + log::error("Left channel codec setup failed with err: {}", codec_status); groupStateMachine_->StopStream(group); return; } - sw_enc_right = bluetooth::le_audio::CodecInterface::CreateInstance( - stream_conf->codec_id); - codec_status = sw_enc_right->InitEncoder(audio_framework_source_config, - current_encoder_config_); - if (codec_status != - bluetooth::le_audio::CodecInterface::Status::STATUS_OK) { - log::error("Right channel codec setup failed with err: {}", - codec_status); + sw_enc_right = bluetooth::le_audio::CodecInterface::CreateInstance(stream_conf->codec_id); + codec_status = + sw_enc_right->InitEncoder(audio_framework_source_config, current_encoder_config_); + if (codec_status != bluetooth::le_audio::CodecInterface::Status::STATUS_OK) { + log::error("Right channel codec setup failed with err: {}", codec_status); groupStateMachine_->StopStream(group); return; } @@ -3749,22 +3522,18 @@ class LeAudioClientImpl : public LeAudioClient { /* We update the target audio allocation before streamStarted so that the * CodecManager would know how to configure the encoder. */ BidirectionalPair delays_pair = { - .sink = group->GetRemoteDelay( - bluetooth::le_audio::types::kLeAudioDirectionSink), - .source = group->GetRemoteDelay( - bluetooth::le_audio::types::kLeAudioDirectionSource)}; + .sink = group->GetRemoteDelay(bluetooth::le_audio::types::kLeAudioDirectionSink), + .source = group->GetRemoteDelay(bluetooth::le_audio::types::kLeAudioDirectionSource)}; CodecManager::GetInstance()->UpdateActiveAudioConfig( - group->stream_conf.stream_params, delays_pair, - std::bind(&LeAudioClientImpl::UpdateAudioConfigToHal, - weak_factory_.GetWeakPtr(), std::placeholders::_1, - std::placeholders::_2)); + group->stream_conf.stream_params, delays_pair, + std::bind(&LeAudioClientImpl::UpdateAudioConfigToHal, weak_factory_.GetWeakPtr(), + std::placeholders::_1, std::placeholders::_2)); } } - const struct bluetooth::le_audio::stream_configuration* - GetStreamSourceConfiguration(LeAudioDeviceGroup* group) { - const struct bluetooth::le_audio::stream_configuration* stream_conf = - &group->stream_conf; + const struct bluetooth::le_audio::stream_configuration* GetStreamSourceConfiguration( + LeAudioDeviceGroup* group) { + const struct bluetooth::le_audio::stream_configuration* stream_conf = &group->stream_conf; if (stream_conf->stream_params.source.stream_locations.size() == 0) { return nullptr; } @@ -3780,15 +3549,14 @@ class LeAudioClientImpl : public LeAudioClient { auto* stream_conf = GetStreamSourceConfiguration(group); if (!stream_conf) { log::warn( - "Could not get source configuration for group {} probably microphone " - "not configured", - active_group_id_); + "Could not get source configuration for group {} probably microphone not configured", + active_group_id_); groupStateMachine_->StopStream(group); return; } - uint16_t remote_delay_ms = group->GetRemoteDelay( - bluetooth::le_audio::types::kLeAudioDirectionSource); + uint16_t remote_delay_ms = + group->GetRemoteDelay(bluetooth::le_audio::types::kLeAudioDirectionSource); CleanCachedMicrophoneData(); @@ -3797,26 +3565,20 @@ class LeAudioClientImpl : public LeAudioClient { if (sw_dec_left.get() || sw_dec_right.get()) { log::warn("The decoder instance should have been already released."); } - sw_dec_left = bluetooth::le_audio::CodecInterface::CreateInstance( - stream_conf->codec_id); - auto codec_status = sw_dec_left->InitDecoder(current_decoder_config_, - audio_framework_sink_config); - if (codec_status != - bluetooth::le_audio::CodecInterface::Status::STATUS_OK) { - log::error("Left channel codec setup failed with err: {}", - codec_status); + sw_dec_left = bluetooth::le_audio::CodecInterface::CreateInstance(stream_conf->codec_id); + auto codec_status = + sw_dec_left->InitDecoder(current_decoder_config_, audio_framework_sink_config); + if (codec_status != bluetooth::le_audio::CodecInterface::Status::STATUS_OK) { + log::error("Left channel codec setup failed with err: {}", codec_status); groupStateMachine_->StopStream(group); return; } - sw_dec_right = bluetooth::le_audio::CodecInterface::CreateInstance( - stream_conf->codec_id); - codec_status = sw_dec_right->InitDecoder(current_decoder_config_, - audio_framework_sink_config); - if (codec_status != - bluetooth::le_audio::CodecInterface::Status::STATUS_OK) { - log::error("Right channel codec setup failed with err: {}", - codec_status); + sw_dec_right = bluetooth::le_audio::CodecInterface::CreateInstance(stream_conf->codec_id); + codec_status = + sw_dec_right->InitDecoder(current_decoder_config_, audio_framework_sink_config); + if (codec_status != bluetooth::le_audio::CodecInterface::Status::STATUS_OK) { + log::error("Right channel codec setup failed with err: {}", codec_status); groupStateMachine_->StopStream(group); return; } @@ -3828,25 +3590,30 @@ class LeAudioClientImpl : public LeAudioClient { /* We update the target audio allocation before streamStarted so that the * CodecManager would know how to configure the encoder. */ BidirectionalPair delays_pair = { - .sink = group->GetRemoteDelay( - bluetooth::le_audio::types::kLeAudioDirectionSink), - .source = group->GetRemoteDelay( - bluetooth::le_audio::types::kLeAudioDirectionSource)}; + .sink = group->GetRemoteDelay(bluetooth::le_audio::types::kLeAudioDirectionSink), + .source = group->GetRemoteDelay(bluetooth::le_audio::types::kLeAudioDirectionSource)}; CodecManager::GetInstance()->UpdateActiveAudioConfig( - group->stream_conf.stream_params, delays_pair, - std::bind(&LeAudioClientImpl::UpdateAudioConfigToHal, - weak_factory_.GetWeakPtr(), std::placeholders::_1, - std::placeholders::_2)); + group->stream_conf.stream_params, delays_pair, + std::bind(&LeAudioClientImpl::UpdateAudioConfigToHal, weak_factory_.GetWeakPtr(), + std::placeholders::_1, std::placeholders::_2)); } } void SuspendAudio(void) { CancelStreamingRequest(); - if (sw_enc_left) sw_enc_left.reset(); - if (sw_enc_right) sw_enc_right.reset(); - if (sw_dec_left) sw_dec_left.reset(); - if (sw_dec_right) sw_dec_right.reset(); + if (sw_enc_left) { + sw_enc_left.reset(); + } + if (sw_enc_right) { + sw_enc_right.reset(); + } + if (sw_dec_left) { + sw_dec_left.reset(); + } + if (sw_dec_right) { + sw_dec_right.reset(); + } CleanCachedMicrophoneData(); } @@ -3858,8 +3625,7 @@ class LeAudioClientImpl : public LeAudioClient { void printCurrentStreamConfiguration(int fd) { std::stringstream stream; auto config_printer = [&stream](LeAudioCodecConfiguration& conf) { - stream << "\tsample rate: " << +conf.sample_rate - << ",\tchan: " << +conf.num_channels + stream << "\tsample rate: " << +conf.sample_rate << ",\tchan: " << +conf.num_channels << ",\tbits: " << +conf.bits_per_sample << ",\tdata_interval_us: " << +conf.data_interval_us << "\n"; }; @@ -3885,9 +3651,8 @@ class LeAudioClientImpl : public LeAudioClient { dprintf(fd, " APP ID: %d \n", gatt_if_); dprintf(fd, " Active group: %d\n", active_group_id_); dprintf(fd, " reconnection mode: %s \n", - (reconnection_mode_ == BTM_BLE_BKG_CONNECT_ALLOW_LIST - ? "Allow List" - : "Targeted Announcements")); + (reconnection_mode_ == BTM_BLE_BKG_CONNECT_ALLOW_LIST ? "Allow List" + : "Targeted Announcements")); dprintf(fd, " configuration: %s (0x%08x)\n", bluetooth::common::ToString(configuration_context_type_).c_str(), static_cast(configuration_context_type_)); @@ -3896,17 +3661,14 @@ class LeAudioClientImpl : public LeAudioClient { dprintf(fd, " local sink metadata context type mask: %s\n", local_metadata_context_types_.sink.to_string().c_str()); dprintf(fd, " TBS state: %s\n", in_call_ ? " In call" : "No calls"); - dprintf(fd, " Sink listening mode: %s\n", - sink_monitor_mode_ ? "true" : "false"); + dprintf(fd, " Sink listening mode: %s\n", sink_monitor_mode_ ? "true" : "false"); if (sink_monitor_notified_status_) { dprintf(fd, " Local sink notified state: %d\n", static_cast(sink_monitor_notified_status_.value())); } - dprintf(fd, " Source monitor mode: %s\n", - source_monitor_mode_ ? "true" : "false"); + dprintf(fd, " Source monitor mode: %s\n", source_monitor_mode_ ? "true" : "false"); dprintf(fd, " Codec extensibility: %s\n", - CodecManager::GetInstance()->IsUsingCodecExtensibility() ? "true" - : "false"); + CodecManager::GetInstance()->IsUsingCodecExtensibility() ? "true" : "false"); dprintf(fd, " Start time: "); for (auto t : stream_start_history_queue_) { dprintf(fd, ", %d ms", static_cast(t)); @@ -3926,26 +3688,28 @@ class LeAudioClientImpl : public LeAudioClient { void Cleanup() { StopVbcCloseTimeout(); - if (alarm_is_scheduled(suspend_timeout_)) alarm_cancel(suspend_timeout_); + if (alarm_is_scheduled(suspend_timeout_)) { + alarm_cancel(suspend_timeout_); + } if (active_group_id_ != bluetooth::groups::kGroupUnknown) { /* Bluetooth turned off while streaming */ StopAudio(); - SetUnicastMonitorMode(bluetooth::le_audio::types::kLeAudioDirectionSink, - false); + SetUnicastMonitorMode(bluetooth::le_audio::types::kLeAudioDirectionSink, false); ClientAudioInterfaceRelease(); } else { /* There may be not stopped Sink HAL client due to set Listening mode */ if (sink_monitor_mode_) { - SetUnicastMonitorMode(bluetooth::le_audio::types::kLeAudioDirectionSink, - false); + SetUnicastMonitorMode(bluetooth::le_audio::types::kLeAudioDirectionSink, false); } } groupStateMachine_->Cleanup(); aseGroups_.Cleanup(); lastNotifiedGroupStreamStatusMap_.clear(); leAudioDevices_.Cleanup(gatt_if_); - if (gatt_if_) BTA_GATTC_AppDeregister(gatt_if_); + if (gatt_if_) { + BTA_GATTC_AppDeregister(gatt_if_); + } if (leAudioHealthStatus_) { leAudioHealthStatus_->Cleanup(); @@ -3953,7 +3717,7 @@ class LeAudioClientImpl : public LeAudioClient { } AudioReconfigurationResult UpdateConfigAndCheckIfReconfigurationIsNeeded( - LeAudioDeviceGroup* group, LeAudioContextType context_type) { + LeAudioDeviceGroup* group, LeAudioContextType context_type) { log::debug("Checking whether to reconfigure from {} to {}", ToString(configuration_context_type_), ToString(context_type)); @@ -3962,9 +3726,8 @@ class LeAudioClientImpl : public LeAudioClient { return AudioReconfigurationResult::RECONFIGURATION_NOT_POSSIBLE; } - if (group->IsGroupConfiguredTo(*audio_set_conf) && - !DsaReconfigureNeeded(group, context_type)) { - // Assign the new configuration context as it reprents the current + if (group->IsGroupConfiguredTo(*audio_set_conf) && !DsaReconfigureNeeded(group, context_type)) { + // Assign the new configuration context as it represennts the current // use case even when it eventually ends up being the exact same // codec and qos configuration. if (configuration_context_type_ != context_type) { @@ -3974,31 +3737,28 @@ class LeAudioClientImpl : public LeAudioClient { return AudioReconfigurationResult::RECONFIGURATION_NOT_NEEDED; } - log::info("Session reconfiguration needed group: {} for context type: {}", - group->group_id_, ToHexString(context_type)); + log::info("Session reconfiguration needed group: {} for context type: {}", group->group_id_, + ToHexString(context_type)); configuration_context_type_ = context_type; // Note: The local sink config is based on remote device's source config // and vice versa. current_decoder_config_ = group->GetAudioSessionCodecConfigForDirection( - context_type, bluetooth::le_audio::types::kLeAudioDirectionSource); + context_type, bluetooth::le_audio::types::kLeAudioDirectionSource); current_encoder_config_ = group->GetAudioSessionCodecConfigForDirection( - context_type, bluetooth::le_audio::types::kLeAudioDirectionSink); + context_type, bluetooth::le_audio::types::kLeAudioDirectionSink); return AudioReconfigurationResult::RECONFIGURATION_NEEDED; } /* Returns true if stream is started */ bool OnAudioResume(LeAudioDeviceGroup* group, int local_direction) { - auto remote_direction = - (local_direction == bluetooth::le_audio::types::kLeAudioDirectionSink - ? bluetooth::le_audio::types::kLeAudioDirectionSource - : bluetooth::le_audio::types::kLeAudioDirectionSink); + auto remote_direction = (local_direction == bluetooth::le_audio::types::kLeAudioDirectionSink + ? bluetooth::le_audio::types::kLeAudioDirectionSource + : bluetooth::le_audio::types::kLeAudioDirectionSink); - auto remote_contexts = - DirectionalRealignMetadataAudioContexts(group, remote_direction); - ApplyRemoteMetadataAudioContextPolicy(group, remote_contexts, - remote_direction); + auto remote_contexts = DirectionalRealignMetadataAudioContexts(group, remote_direction); + ApplyRemoteMetadataAudioContextPolicy(group, remote_contexts, remote_direction); if (!remote_contexts.sink.any() && !remote_contexts.source.any()) { log::warn("Requested context type not available on the remote side"); @@ -4006,21 +3766,20 @@ class LeAudioClientImpl : public LeAudioClient { if (com::android::bluetooth::flags::leaudio_no_context_validate_streaming_request() && source_monitor_mode_) { callbacks_->OnUnicastMonitorModeStatus( - bluetooth::le_audio::types::kLeAudioDirectionSource, - UnicastMonitorModeStatus::STREAMING_REQUESTED_NO_CONTEXT_VALIDATE); + bluetooth::le_audio::types::kLeAudioDirectionSource, + UnicastMonitorModeStatus::STREAMING_REQUESTED_NO_CONTEXT_VALIDATE); return false; } if (leAudioHealthStatus_) { leAudioHealthStatus_->AddStatisticForGroup( - group, LeAudioHealthGroupStatType::STREAM_CONTEXT_NOT_AVAILABLE); + group, LeAudioHealthGroupStatType::STREAM_CONTEXT_NOT_AVAILABLE); } return false; } - return GroupStream(active_group_id_, configuration_context_type_, - remote_contexts); + return GroupStream(active_group_id_, configuration_context_type_, remote_contexts); } void OnAudioSuspend() { @@ -4029,52 +3788,52 @@ class LeAudioClientImpl : public LeAudioClient { return; } - if (stack_config_get_interface() - ->get_pts_le_audio_disable_ases_before_stopping()) { + if (stack_config_get_interface()->get_pts_le_audio_disable_ases_before_stopping()) { log::info("Stream disable_timer_ started"); - if (alarm_is_scheduled(disable_timer_)) alarm_cancel(disable_timer_); + if (alarm_is_scheduled(disable_timer_)) { + alarm_cancel(disable_timer_); + } alarm_set_on_mloop( - disable_timer_, kAudioDisableTimeoutMs, - [](void* data) { - if (instance) instance->GroupSuspend(PTR_TO_INT(data)); - }, - INT_TO_PTR(active_group_id_)); + disable_timer_, kAudioDisableTimeoutMs, + [](void* data) { + if (instance) { + instance->GroupSuspend(PTR_TO_INT(data)); + } + }, + INT_TO_PTR(active_group_id_)); } /* Group should tie in time to get requested status */ uint64_t timeoutMs = kAudioSuspentKeepIsoAliveTimeoutMs; - timeoutMs = osi_property_get_int32(kAudioSuspentKeepIsoAliveTimeoutMsProp, - timeoutMs); + timeoutMs = osi_property_get_int32(kAudioSuspentKeepIsoAliveTimeoutMsProp, timeoutMs); - if (stack_config_get_interface() - ->get_pts_le_audio_disable_ases_before_stopping()) { + if (stack_config_get_interface()->get_pts_le_audio_disable_ases_before_stopping()) { timeoutMs += kAudioDisableTimeoutMs; } - log::debug("Stream suspend_timeout_ started: {} ms", - static_cast(timeoutMs)); - if (alarm_is_scheduled(suspend_timeout_)) alarm_cancel(suspend_timeout_); + log::debug("Stream suspend_timeout_ started: {} ms", static_cast(timeoutMs)); + if (alarm_is_scheduled(suspend_timeout_)) { + alarm_cancel(suspend_timeout_); + } alarm_set_on_mloop( - suspend_timeout_, timeoutMs, - [](void* data) { - if (instance) instance->GroupStop(PTR_TO_INT(data)); - }, - INT_TO_PTR(active_group_id_)); + suspend_timeout_, timeoutMs, + [](void* data) { + if (instance) { + instance->GroupStop(PTR_TO_INT(data)); + } + }, + INT_TO_PTR(active_group_id_)); } void OnLocalAudioSourceSuspend() { - log::info( - "active group_id: {}, IN: audio_receiver_state_: {}, " - "audio_sender_state_: {}", - active_group_id_, ToString(audio_receiver_state_), - ToString(audio_sender_state_)); - LeAudioLogHistory::Get()->AddLogHistory( - kLogAfCallBt, active_group_id_, RawAddress::kEmpty, - kLogAfSuspend + "LocalSource", - "r_state: " + ToString(audio_receiver_state_) + - ", s_state: " + ToString(audio_sender_state_)); + log::info("active group_id: {}, IN: audio_receiver_state_: {}, audio_sender_state_: {}", + active_group_id_, ToString(audio_receiver_state_), ToString(audio_sender_state_)); + LeAudioLogHistory::Get()->AddLogHistory(kLogAfCallBt, active_group_id_, RawAddress::kEmpty, + kLogAfSuspend + "LocalSource", + "r_state: " + ToString(audio_receiver_state_) + + ", s_state: " + ToString(audio_sender_state_)); /* Note: This callback is from audio hal driver. * Bluetooth peer is a Sink for Audio Framework. @@ -4100,31 +3859,25 @@ class LeAudioClientImpl : public LeAudioClient { if ((audio_receiver_state_ == AudioState::IDLE) || (audio_receiver_state_ == AudioState::READY_TO_RELEASE)) { OnAudioSuspend(); - bluetooth::le_audio::MetricsCollector::Get()->OnStreamEnded( - active_group_id_); + bluetooth::le_audio::MetricsCollector::Get()->OnStreamEnded(active_group_id_); } log::info("OUT: audio_receiver_state_: {}, audio_sender_state_: {}", ToString(audio_receiver_state_), ToString(audio_sender_state_)); - LeAudioLogHistory::Get()->AddLogHistory( - kLogBtCallAf, active_group_id_, RawAddress::kEmpty, - kLogAfSuspendConfirm + "LocalSource", - "r_state: " + ToString(audio_receiver_state_) + - "s_state: " + ToString(audio_sender_state_)); + LeAudioLogHistory::Get()->AddLogHistory(kLogBtCallAf, active_group_id_, RawAddress::kEmpty, + kLogAfSuspendConfirm + "LocalSource", + "r_state: " + ToString(audio_receiver_state_) + + "s_state: " + ToString(audio_sender_state_)); } void OnLocalAudioSourceResume() { - log::info( - "active group_id: {}, IN: audio_receiver_state_: {}, " - "audio_sender_state_: {}", - active_group_id_, ToString(audio_receiver_state_), - ToString(audio_sender_state_)); - LeAudioLogHistory::Get()->AddLogHistory( - kLogAfCallBt, active_group_id_, RawAddress::kEmpty, - kLogAfResume + "LocalSource", - "r_state: " + ToString(audio_receiver_state_) + - ", s_state: " + ToString(audio_sender_state_)); + log::info("active group_id: {}, IN: audio_receiver_state_: {}, audio_sender_state_: {}", + active_group_id_, ToString(audio_receiver_state_), ToString(audio_sender_state_)); + LeAudioLogHistory::Get()->AddLogHistory(kLogAfCallBt, active_group_id_, RawAddress::kEmpty, + kLogAfResume + "LocalSource", + "r_state: " + ToString(audio_receiver_state_) + + ", s_state: " + ToString(audio_sender_state_)); /* Note: This callback is from audio hal driver. * Bluetooth peer is a Sink for Audio Framework. @@ -4138,18 +3891,15 @@ class LeAudioClientImpl : public LeAudioClient { /* Check if the device resume is allowed */ if (!group->HasCodecConfigurationForDirection( - configuration_context_type_, - bluetooth::le_audio::types::kLeAudioDirectionSink)) { + configuration_context_type_, bluetooth::le_audio::types::kLeAudioDirectionSink)) { log::error("invalid resume request for context type: {}", ToHexString(configuration_context_type_)); CancelLocalAudioSourceStreamingRequest(); return; } - if (!group - ->GetAllowedContextMask( - bluetooth::le_audio::types::kLeAudioDirectionSink) - .test(configuration_context_type_)) { + if (!group->GetAllowedContextMask(bluetooth::le_audio::types::kLeAudioDirectionSink) + .test(configuration_context_type_)) { log::warn("Block source resume request context type: {}", ToHexString(configuration_context_type_)); CancelLocalAudioSourceStreamingRequest(); @@ -4157,11 +3907,10 @@ class LeAudioClientImpl : public LeAudioClient { } log::debug( - "active_group_id: {}\n audio_receiver_state: {}\n audio_sender_state: " - "{}\n configuration_context_type_: {}\n group {}\n", - active_group_id_, audio_receiver_state_, audio_sender_state_, - ToHexString(configuration_context_type_), - group ? " exist " : " does not exist "); + "active_group_id: {}\n audio_receiver_state: {}\n audio_sender_state: " + "{}\n configuration_context_type_: {}\n group {}\n", + active_group_id_, audio_receiver_state_, audio_sender_state_, + ToHexString(configuration_context_type_), group ? " exist " : " does not exist "); switch (audio_sender_state_) { case AudioState::STARTED: @@ -4172,9 +3921,7 @@ class LeAudioClientImpl : public LeAudioClient { switch (audio_receiver_state_) { case AudioState::IDLE: /* Stream is not started. Try to do it.*/ - if (OnAudioResume( - group, - bluetooth::le_audio::types::kLeAudioDirectionSource)) { + if (OnAudioResume(group, bluetooth::le_audio::types::kLeAudioDirectionSource)) { audio_sender_state_ = AudioState::READY_TO_START; } else { CancelLocalAudioSourceStreamingRequest(); @@ -4183,18 +3930,15 @@ class LeAudioClientImpl : public LeAudioClient { case AudioState::READY_TO_START: audio_sender_state_ = AudioState::READY_TO_START; if (!IsDirectionAvailableForCurrentConfiguration( - group, bluetooth::le_audio::types::kLeAudioDirectionSink)) { + group, bluetooth::le_audio::types::kLeAudioDirectionSink)) { log::warn( - "sink is not configured. \n audio_receiver_state: {} " - "\naudio_sender_state: {} \n isPendingConfiguration: {} \n " - "Reconfiguring to {}", - ToString(audio_receiver_state_), - ToString(audio_sender_state_), - group->IsPendingConfiguration(), - ToString(configuration_context_type_)); + "sink is not configured. \n audio_receiver_state: {} " + "\naudio_sender_state: {} \n isPendingConfiguration: {} \n " + "Reconfiguring to {}", + ToString(audio_receiver_state_), ToString(audio_sender_state_), + group->IsPendingConfiguration(), ToString(configuration_context_type_)); group->PrintDebugState(); - SetConfigurationAndStopStreamWhenNeeded( - group, configuration_context_type_); + SetConfigurationAndStopStreamWhenNeeded(group, configuration_context_type_); } break; case AudioState::STARTED: @@ -4202,34 +3946,27 @@ class LeAudioClientImpl : public LeAudioClient { /* If signalling part is completed trigger start sending audio * here, otherwise it'll be called on group streaming state callback */ - if (group->GetState() == - AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) { + if (group->GetState() == AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) { if (IsDirectionAvailableForCurrentConfiguration( - group, - bluetooth::le_audio::types::kLeAudioDirectionSink)) { + group, bluetooth::le_audio::types::kLeAudioDirectionSink)) { StartSendingAudio(active_group_id_); } else { log::warn( - "sink is not configured. \n audio_receiver_state: {} " - "\naudio_sender_state: {} \n isPendingConfiguration: {} \n " - "Reconfiguring to {}", - ToString(audio_receiver_state_), - ToString(audio_sender_state_), - group->IsPendingConfiguration(), - ToString(configuration_context_type_)); + "sink is not configured. \n audio_receiver_state: {} " + "\naudio_sender_state: {} \n isPendingConfiguration: {} \n " + "Reconfiguring to {}", + ToString(audio_receiver_state_), ToString(audio_sender_state_), + group->IsPendingConfiguration(), ToString(configuration_context_type_)); group->PrintDebugState(); - SetConfigurationAndStopStreamWhenNeeded( - group, configuration_context_type_); + SetConfigurationAndStopStreamWhenNeeded(group, configuration_context_type_); } } else { log::error( - "called in wrong state. \n audio_receiver_state: {} " - "\naudio_sender_state: {} \n isPendingConfiguration: {} \n " - "Reconfiguring to {}", - ToString(audio_receiver_state_), - ToString(audio_sender_state_), - group->IsPendingConfiguration(), - ToString(configuration_context_type_)); + "called in wrong state. \n audio_receiver_state: {} " + "\naudio_sender_state: {} \n isPendingConfiguration: {} \n " + "Reconfiguring to {}", + ToString(audio_receiver_state_), ToString(audio_sender_state_), + group->IsPendingConfiguration(), ToString(configuration_context_type_)); group->PrintDebugState(); CancelStreamingRequest(); } @@ -4242,34 +3979,27 @@ class LeAudioClientImpl : public LeAudioClient { break; case AudioState::READY_TO_RELEASE: /* If the other direction is streaming we can start sending audio */ - if (group->GetState() == - AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) { + if (group->GetState() == AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) { if (IsDirectionAvailableForCurrentConfiguration( - group, - bluetooth::le_audio::types::kLeAudioDirectionSink)) { + group, bluetooth::le_audio::types::kLeAudioDirectionSink)) { StartSendingAudio(active_group_id_); } else { log::warn( - "sink is not configured. \n audio_receiver_state: {} " - "\naudio_sender_state: {} \n isPendingConfiguration: {} \n " - "Reconfiguring to {}", - ToString(audio_receiver_state_), - ToString(audio_sender_state_), - group->IsPendingConfiguration(), - ToString(configuration_context_type_)); + "sink is not configured. \n audio_receiver_state: {} " + "\naudio_sender_state: {} \n isPendingConfiguration: {} \n " + "Reconfiguring to {}", + ToString(audio_receiver_state_), ToString(audio_sender_state_), + group->IsPendingConfiguration(), ToString(configuration_context_type_)); group->PrintDebugState(); - SetConfigurationAndStopStreamWhenNeeded( - group, configuration_context_type_); + SetConfigurationAndStopStreamWhenNeeded(group, configuration_context_type_); } } else { log::error( - "called in wrong state. \n audio_receiver_state: {} " - "\naudio_sender_state: {} \n isPendingConfiguration: {} \n " - "Reconfiguring to {}", - ToString(audio_receiver_state_), - ToString(audio_sender_state_), - group->IsPendingConfiguration(), - ToString(configuration_context_type_)); + "called in wrong state. \n audio_receiver_state: {} " + "\naudio_sender_state: {} \n isPendingConfiguration: {} \n " + "Reconfiguring to {}", + ToString(audio_receiver_state_), ToString(audio_sender_state_), + group->IsPendingConfiguration(), ToString(configuration_context_type_)); group->PrintDebugState(); CancelStreamingRequest(); } @@ -4278,12 +4008,11 @@ class LeAudioClientImpl : public LeAudioClient { break; case AudioState::READY_TO_START: log::error( - "called in wrong state, ignoring double start request. \n " - "audio_receiver_state: {} \naudio_sender_state: {} \n " - "isPendingConfiguration: {} \n Reconfiguring to {}", - ToString(audio_receiver_state_), ToString(audio_sender_state_), - group->IsPendingConfiguration(), - ToString(configuration_context_type_)); + "called in wrong state, ignoring double start request. \n " + "audio_receiver_state: {} \naudio_sender_state: {} \n " + "isPendingConfiguration: {} \n Reconfiguring to {}", + ToString(audio_receiver_state_), ToString(audio_sender_state_), + group->IsPendingConfiguration(), ToString(configuration_context_type_)); group->PrintDebugState(); break; case AudioState::READY_TO_RELEASE: @@ -4293,35 +4022,32 @@ class LeAudioClientImpl : public LeAudioClient { case AudioState::IDLE: case AudioState::READY_TO_RELEASE: /* Stream is up just restore it */ - if (alarm_is_scheduled(suspend_timeout_)) + if (alarm_is_scheduled(suspend_timeout_)) { alarm_cancel(suspend_timeout_); + } ConfirmLocalAudioSourceStreamingRequest(); bluetooth::le_audio::MetricsCollector::Get()->OnStreamStarted( - active_group_id_, configuration_context_type_); + active_group_id_, configuration_context_type_); break; case AudioState::RELEASING: - /* Keep wainting. After release is done, Audio Hal will be notified + /* Keep waiting. After release is done, Audio Hal will be notified */ break; } break; case AudioState::RELEASING: - /* Keep wainting. After release is done, Audio Hal will be notified */ + /* Keep waiting. After release is done, Audio Hal will be notified */ break; } } void OnLocalAudioSinkSuspend() { - log::info( - "active group_id: {}, IN: audio_receiver_state_: {}, " - "audio_sender_state_: {}", - active_group_id_, ToString(audio_receiver_state_), - ToString(audio_sender_state_)); - LeAudioLogHistory::Get()->AddLogHistory( - kLogAfCallBt, active_group_id_, RawAddress::kEmpty, - kLogAfSuspend + "LocalSink", - "r_state: " + ToString(audio_receiver_state_) + - ", s_state: " + ToString(audio_sender_state_)); + log::info("active group_id: {}, IN: audio_receiver_state_: {}, audio_sender_state_: {}", + active_group_id_, ToString(audio_receiver_state_), ToString(audio_sender_state_)); + LeAudioLogHistory::Get()->AddLogHistory(kLogAfCallBt, active_group_id_, RawAddress::kEmpty, + kLogAfSuspend + "LocalSink", + "r_state: " + ToString(audio_receiver_state_) + + ", s_state: " + ToString(audio_sender_state_)); StartVbcCloseTimeout(); @@ -4347,54 +4073,47 @@ class LeAudioClientImpl : public LeAudioClient { /* Last suspends group - triggers group stop */ if ((audio_sender_state_ == AudioState::IDLE) || - (audio_sender_state_ == AudioState::READY_TO_RELEASE)) + (audio_sender_state_ == AudioState::READY_TO_RELEASE)) { OnAudioSuspend(); + } log::info("OUT: audio_receiver_state_: {}, audio_sender_state_: {}", ToString(audio_receiver_state_), ToString(audio_sender_state_)); - LeAudioLogHistory::Get()->AddLogHistory( - kLogBtCallAf, active_group_id_, RawAddress::kEmpty, - kLogAfSuspendConfirm + "LocalSink", - "r_state: " + ToString(audio_receiver_state_) + - "s_state: " + ToString(audio_sender_state_)); - } - - inline bool IsDirectionAvailableForCurrentConfiguration( - const LeAudioDeviceGroup* group, uint8_t direction) const { - auto current_config = - group->GetCachedConfiguration(configuration_context_type_); - if (current_config) - return (current_config->confs.get(direction).size() != 0); + LeAudioLogHistory::Get()->AddLogHistory(kLogBtCallAf, active_group_id_, RawAddress::kEmpty, + kLogAfSuspendConfirm + "LocalSink", + "r_state: " + ToString(audio_receiver_state_) + + "s_state: " + ToString(audio_sender_state_)); + } + + inline bool IsDirectionAvailableForCurrentConfiguration(const LeAudioDeviceGroup* group, + uint8_t direction) const { + auto current_config = group->GetCachedConfiguration(configuration_context_type_); + if (current_config) { + return current_config->confs.get(direction).size() != 0; + } return false; } void notifyAudioLocalSink(UnicastMonitorModeStatus status) { if (sink_monitor_notified_status_ != status) { - log::info("Stream monitoring status changed to: {}", - static_cast(status)); + log::info("Stream monitoring status changed to: {}", static_cast(status)); sink_monitor_notified_status_ = status; - callbacks_->OnUnicastMonitorModeStatus( - bluetooth::le_audio::types::kLeAudioDirectionSink, status); + callbacks_->OnUnicastMonitorModeStatus(bluetooth::le_audio::types::kLeAudioDirectionSink, + status); } } void OnLocalAudioSinkResume() { - log::info( - "active group_id: {} IN: audio_receiver_state_: {}, " - "audio_sender_state_: {}", - active_group_id_, ToString(audio_receiver_state_), - ToString(audio_sender_state_)); - LeAudioLogHistory::Get()->AddLogHistory( - kLogAfCallBt, active_group_id_, RawAddress::kEmpty, - kLogAfResume + "LocalSink", - "r_state: " + ToString(audio_receiver_state_) + - ", s_state: " + ToString(audio_sender_state_)); - - if (sink_monitor_mode_ && - active_group_id_ == bluetooth::groups::kGroupUnknown) { - if (sink_monitor_notified_status_ != - UnicastMonitorModeStatus::STREAMING_REQUESTED) { + log::info("active group_id: {} IN: audio_receiver_state_: {}, audio_sender_state_: {}", + active_group_id_, ToString(audio_receiver_state_), ToString(audio_sender_state_)); + LeAudioLogHistory::Get()->AddLogHistory(kLogAfCallBt, active_group_id_, RawAddress::kEmpty, + kLogAfResume + "LocalSink", + "r_state: " + ToString(audio_receiver_state_) + + ", s_state: " + ToString(audio_sender_state_)); + + if (sink_monitor_mode_ && active_group_id_ == bluetooth::groups::kGroupUnknown) { + if (sink_monitor_notified_status_ != UnicastMonitorModeStatus::STREAMING_REQUESTED) { notifyAudioLocalSink(UnicastMonitorModeStatus::STREAMING_REQUESTED); } CancelLocalAudioSinkStreamingRequest(); @@ -4418,24 +4137,20 @@ class LeAudioClientImpl : public LeAudioClient { * further. */ if (audio_receiver_state_ == AudioState::IDLE) { - ReconfigureOrUpdateRemote( - group, bluetooth::le_audio::types::kLeAudioDirectionSource); + ReconfigureOrUpdateRemote(group, bluetooth::le_audio::types::kLeAudioDirectionSource); } /* Check if the device resume is allowed */ if (!group->HasCodecConfigurationForDirection( - configuration_context_type_, - bluetooth::le_audio::types::kLeAudioDirectionSource)) { + configuration_context_type_, bluetooth::le_audio::types::kLeAudioDirectionSource)) { log::error("invalid resume request for context type: {}", ToHexString(configuration_context_type_)); CancelLocalAudioSinkStreamingRequest(); return; } - if (!group - ->GetAllowedContextMask( - bluetooth::le_audio::types::kLeAudioDirectionSource) - .test(configuration_context_type_)) { + if (!group->GetAllowedContextMask(bluetooth::le_audio::types::kLeAudioDirectionSource) + .test(configuration_context_type_)) { log::warn("Block sink resume request context type: {}", ToHexString(configuration_context_type_)); CancelLocalAudioSourceStreamingRequest(); @@ -4443,11 +4158,10 @@ class LeAudioClientImpl : public LeAudioClient { } log::debug( - "active_group_id: {}\n audio_receiver_state: {}\n audio_sender_state: " - "{}\n configuration_context_type_: {}\n group {}\n", - active_group_id_, audio_receiver_state_, audio_sender_state_, - ToHexString(configuration_context_type_), - group ? " exist " : " does not exist "); + "active_group_id: {}\n audio_receiver_state: {}\n audio_sender_state: " + "{}\n configuration_context_type_: {}\n group {}\n", + active_group_id_, audio_receiver_state_, audio_sender_state_, + ToHexString(configuration_context_type_), group ? " exist " : " does not exist "); switch (audio_receiver_state_) { case AudioState::STARTED: @@ -4456,8 +4170,7 @@ class LeAudioClientImpl : public LeAudioClient { case AudioState::IDLE: switch (audio_sender_state_) { case AudioState::IDLE: - if (OnAudioResume( - group, bluetooth::le_audio::types::kLeAudioDirectionSink)) { + if (OnAudioResume(group, bluetooth::le_audio::types::kLeAudioDirectionSink)) { audio_receiver_state_ = AudioState::READY_TO_START; } else { CancelLocalAudioSinkStreamingRequest(); @@ -4466,19 +4179,15 @@ class LeAudioClientImpl : public LeAudioClient { case AudioState::READY_TO_START: audio_receiver_state_ = AudioState::READY_TO_START; if (!IsDirectionAvailableForCurrentConfiguration( - group, - bluetooth::le_audio::types::kLeAudioDirectionSource)) { + group, bluetooth::le_audio::types::kLeAudioDirectionSource)) { log::warn( - "source is not configured. \n audio_receiver_state: {} " - "\naudio_sender_state: {} \n isPendingConfiguration: {} \n " - "Reconfiguring to {}", - ToString(audio_receiver_state_), - ToString(audio_sender_state_), - group->IsPendingConfiguration(), - ToString(configuration_context_type_)); + "source is not configured. \n audio_receiver_state: {} " + "\naudio_sender_state: {} \n isPendingConfiguration: {} \n " + "Reconfiguring to {}", + ToString(audio_receiver_state_), ToString(audio_sender_state_), + group->IsPendingConfiguration(), ToString(configuration_context_type_)); group->PrintDebugState(); - SetConfigurationAndStopStreamWhenNeeded( - group, configuration_context_type_); + SetConfigurationAndStopStreamWhenNeeded(group, configuration_context_type_); } break; case AudioState::STARTED: @@ -4486,34 +4195,27 @@ class LeAudioClientImpl : public LeAudioClient { /* If signalling part is completed trigger start receiving audio * here, otherwise it'll be called on group streaming state callback */ - if (group->GetState() == - AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) { + if (group->GetState() == AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) { if (IsDirectionAvailableForCurrentConfiguration( - group, - bluetooth::le_audio::types::kLeAudioDirectionSource)) { + group, bluetooth::le_audio::types::kLeAudioDirectionSource)) { StartReceivingAudio(active_group_id_); } else { log::warn( - "source is not configured. \n audio_receiver_state: {} " - "\naudio_sender_state: {} \n isPendingConfiguration: {} \n " - "Reconfiguring to {}", - ToString(audio_receiver_state_), - ToString(audio_sender_state_), - group->IsPendingConfiguration(), - ToString(configuration_context_type_)); + "source is not configured. \n audio_receiver_state: {} " + "\naudio_sender_state: {} \n isPendingConfiguration: {} \n " + "Reconfiguring to {}", + ToString(audio_receiver_state_), ToString(audio_sender_state_), + group->IsPendingConfiguration(), ToString(configuration_context_type_)); group->PrintDebugState(); - SetConfigurationAndStopStreamWhenNeeded( - group, configuration_context_type_); + SetConfigurationAndStopStreamWhenNeeded(group, configuration_context_type_); } } else { log::error( - "called in wrong state. \n audio_receiver_state: {} " - "\naudio_sender_state: {} \n isPendingConfiguration: {} \n " - "Reconfiguring to {}", - ToString(audio_receiver_state_), - ToString(audio_sender_state_), - group->IsPendingConfiguration(), - ToString(configuration_context_type_)); + "called in wrong state. \n audio_receiver_state: {} " + "\naudio_sender_state: {} \n isPendingConfiguration: {} \n " + "Reconfiguring to {}", + ToString(audio_receiver_state_), ToString(audio_sender_state_), + group->IsPendingConfiguration(), ToString(configuration_context_type_)); group->PrintDebugState(); CancelStreamingRequest(); } @@ -4527,34 +4229,27 @@ class LeAudioClientImpl : public LeAudioClient { case AudioState::READY_TO_RELEASE: /* If the other direction is streaming we can start receiving audio */ - if (group->GetState() == - AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) { + if (group->GetState() == AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) { if (IsDirectionAvailableForCurrentConfiguration( - group, - bluetooth::le_audio::types::kLeAudioDirectionSource)) { + group, bluetooth::le_audio::types::kLeAudioDirectionSource)) { StartReceivingAudio(active_group_id_); } else { log::warn( - "source is not configured. \n audio_receiver_state: {} " - "\naudio_sender_state: {} \n isPendingConfiguration: {} \n " - "Reconfiguring to {}", - ToString(audio_receiver_state_), - ToString(audio_sender_state_), - group->IsPendingConfiguration(), - ToString(configuration_context_type_)); + "source is not configured. \n audio_receiver_state: {} " + "\naudio_sender_state: {} \n isPendingConfiguration: {} \n " + "Reconfiguring to {}", + ToString(audio_receiver_state_), ToString(audio_sender_state_), + group->IsPendingConfiguration(), ToString(configuration_context_type_)); group->PrintDebugState(); - SetConfigurationAndStopStreamWhenNeeded( - group, configuration_context_type_); + SetConfigurationAndStopStreamWhenNeeded(group, configuration_context_type_); } } else { log::error( - "called in wrong state. \n audio_receiver_state: {} " - "\naudio_sender_state: {} \n isPendingConfiguration: {} \n " - "Reconfiguring to {}", - ToString(audio_receiver_state_), - ToString(audio_sender_state_), - group->IsPendingConfiguration(), - ToString(configuration_context_type_)); + "called in wrong state. \n audio_receiver_state: {} " + "\naudio_sender_state: {} \n isPendingConfiguration: {} \n " + "Reconfiguring to {}", + ToString(audio_receiver_state_), ToString(audio_sender_state_), + group->IsPendingConfiguration(), ToString(configuration_context_type_)); group->PrintDebugState(); CancelStreamingRequest(); } @@ -4563,12 +4258,10 @@ class LeAudioClientImpl : public LeAudioClient { break; case AudioState::READY_TO_START: log::error( - "Double resume request, just ignore it.. \n audio_receiver_state: " - "{} \naudio_sender_state: {} \n isPendingConfiguration: {} \n " - "Reconfiguring to {}", - ToString(audio_receiver_state_), ToString(audio_sender_state_), - group->IsPendingConfiguration(), - ToString(configuration_context_type_)); + "Double resume request, just ignore it.. \n audio_receiver_state: " + "{} \naudio_sender_state: {} \n isPendingConfiguration: {} \n Reconfiguring to {}", + ToString(audio_receiver_state_), ToString(audio_sender_state_), + group->IsPendingConfiguration(), ToString(configuration_context_type_)); group->PrintDebugState(); break; case AudioState::READY_TO_RELEASE: @@ -4578,8 +4271,9 @@ class LeAudioClientImpl : public LeAudioClient { case AudioState::READY_TO_START: case AudioState::READY_TO_RELEASE: /* Stream is up just restore it */ - if (alarm_is_scheduled(suspend_timeout_)) + if (alarm_is_scheduled(suspend_timeout_)) { alarm_cancel(suspend_timeout_); + } ConfirmLocalAudioSinkStreamingRequest(); break; case AudioState::RELEASING: @@ -4599,8 +4293,7 @@ class LeAudioClientImpl : public LeAudioClient { * than this, but it's reasonable to select a configuration context from * the metadata context types. */ - LeAudioContextType ChooseConfigurationContextType( - AudioContexts available_remote_contexts) { + LeAudioContextType ChooseConfigurationContextType(AudioContexts available_remote_contexts) { log::debug("Got contexts={} in config_context={}", bluetooth::common::ToString(available_remote_contexts), bluetooth::common::ToString(configuration_context_type_)); @@ -4615,21 +4308,21 @@ class LeAudioClientImpl : public LeAudioClient { */ if (available_remote_contexts.any()) { LeAudioContextType context_priority_list[] = { - /* Highest priority first */ - LeAudioContextType::CONVERSATIONAL, - /* Handling RINGTONE will cause the ringtone volume slider to trigger - * reconfiguration. This will be fixed in b/283349711. - */ - LeAudioContextType::RINGTONE, - LeAudioContextType::LIVE, - LeAudioContextType::VOICEASSISTANTS, - LeAudioContextType::GAME, - LeAudioContextType::MEDIA, - LeAudioContextType::EMERGENCYALARM, - LeAudioContextType::ALERTS, - LeAudioContextType::INSTRUCTIONAL, - LeAudioContextType::NOTIFICATIONS, - LeAudioContextType::SOUNDEFFECTS, + /* Highest priority first */ + LeAudioContextType::CONVERSATIONAL, + /* Handling RINGTONE will cause the ringtone volume slider to trigger + * reconfiguration. This will be fixed in b/283349711. + */ + LeAudioContextType::RINGTONE, + LeAudioContextType::LIVE, + LeAudioContextType::VOICEASSISTANTS, + LeAudioContextType::GAME, + LeAudioContextType::MEDIA, + LeAudioContextType::EMERGENCYALARM, + LeAudioContextType::ALERTS, + LeAudioContextType::INSTRUCTIONAL, + LeAudioContextType::NOTIFICATIONS, + LeAudioContextType::SOUNDEFFECTS, }; for (auto ct : context_priority_list) { if (available_remote_contexts.test(ct)) { @@ -4647,30 +4340,25 @@ class LeAudioClientImpl : public LeAudioClient { fallback_config = configuration_context_type_; } - log::debug("Selecting configuration context type: {}", - ToString(fallback_config)); + log::debug("Selecting configuration context type: {}", ToString(fallback_config)); return fallback_config; } - bool SetConfigurationAndStopStreamWhenNeeded( - LeAudioDeviceGroup* group, LeAudioContextType new_context_type) { - auto reconfig_result = - UpdateConfigAndCheckIfReconfigurationIsNeeded(group, new_context_type); + bool SetConfigurationAndStopStreamWhenNeeded(LeAudioDeviceGroup* group, + LeAudioContextType new_context_type) { + auto reconfig_result = UpdateConfigAndCheckIfReconfigurationIsNeeded(group, new_context_type); /* Even though the reconfiguration may not be needed, this has * to be set here as it might be the initial configuration. */ configuration_context_type_ = new_context_type; - log::info("group_id {}, context type {} ({}), {}", group->group_id_, - ToString(new_context_type), ToHexString(new_context_type), - ToString(reconfig_result)); - if (reconfig_result == - AudioReconfigurationResult::RECONFIGURATION_NOT_NEEDED) { + log::info("group_id {}, context type {} ({}), {}", group->group_id_, ToString(new_context_type), + ToHexString(new_context_type), ToString(reconfig_result)); + if (reconfig_result == AudioReconfigurationResult::RECONFIGURATION_NOT_NEEDED) { return false; } - if (reconfig_result == - AudioReconfigurationResult::RECONFIGURATION_NOT_POSSIBLE) { + if (reconfig_result == AudioReconfigurationResult::RECONFIGURATION_NOT_POSSIBLE) { return false; } @@ -4679,7 +4367,9 @@ class LeAudioClientImpl : public LeAudioClient { return false; } - if (alarm_is_scheduled(suspend_timeout_)) alarm_cancel(suspend_timeout_); + if (alarm_is_scheduled(suspend_timeout_)) { + alarm_cancel(suspend_timeout_); + } /* Need to reconfigure stream */ group->SetPendingConfiguration(); @@ -4688,8 +4378,7 @@ class LeAudioClientImpl : public LeAudioClient { } void OnLocalAudioSourceMetadataUpdate( - const std::vector& source_metadata, - DsaMode dsa_mode) { + const std::vector& source_metadata, DsaMode dsa_mode) { if (active_group_id_ == bluetooth::groups::kGroupUnknown) { log::warn(", cannot start streaming if no active group set"); return; @@ -4707,52 +4396,45 @@ class LeAudioClientImpl : public LeAudioClient { StopVbcCloseTimeout(); log::info( - "group_id {} state={}, target_state={}, audio_receiver_state_: {}, " - "audio_sender_state_: {}, dsa_mode: {}", - group->group_id_, ToString(group->GetState()), - ToString(group->GetTargetState()), ToString(audio_receiver_state_), - ToString(audio_sender_state_), static_cast(dsa_mode)); + "group_id {} state={}, target_state={}, audio_receiver_state_: {}, " + "audio_sender_state_: {}, dsa_mode: {}", + group->group_id_, ToString(group->GetState()), ToString(group->GetTargetState()), + ToString(audio_receiver_state_), ToString(audio_sender_state_), + static_cast(dsa_mode)); group->dsa_.mode = dsa_mode; /* Set the remote sink metadata context from the playback tracks metadata */ - local_metadata_context_types_.source = - GetAudioContextsFromSourceMetadata(source_metadata); + local_metadata_context_types_.source = GetAudioContextsFromSourceMetadata(source_metadata); local_metadata_context_types_.sink = - ChooseMetadataContextType(local_metadata_context_types_.sink); + ChooseMetadataContextType(local_metadata_context_types_.sink); local_metadata_context_types_.source = - ChooseMetadataContextType(local_metadata_context_types_.source); + ChooseMetadataContextType(local_metadata_context_types_.source); - ReconfigureOrUpdateRemote( - group, bluetooth::le_audio::types::kLeAudioDirectionSink); + ReconfigureOrUpdateRemote(group, bluetooth::le_audio::types::kLeAudioDirectionSink); } /* Applies some predefined policy on the audio context metadata, including * special handling of UNSPECIFIED context, which also involves checking * context support and availability. */ - void ApplyRemoteMetadataAudioContextPolicy( - LeAudioDeviceGroup* group, - BidirectionalPair& contexts_pair, int remote_dir) { + void ApplyRemoteMetadataAudioContextPolicy(LeAudioDeviceGroup* group, + BidirectionalPair& contexts_pair, + int remote_dir) { // We expect at least some context when this direction gets enabled if (contexts_pair.get(remote_dir).none()) { - log::warn( - "invalid/unknown {} context metadata, using 'UNSPECIFIED' instead", - (remote_dir == bluetooth::le_audio::types::kLeAudioDirectionSink) - ? "sink" - : "source"); - contexts_pair.get(remote_dir) = - AudioContexts(LeAudioContextType::UNSPECIFIED); + log::warn("invalid/unknown {} context metadata, using 'UNSPECIFIED' instead", + (remote_dir == bluetooth::le_audio::types::kLeAudioDirectionSink) ? "sink" + : "source"); + contexts_pair.get(remote_dir) = AudioContexts(LeAudioContextType::UNSPECIFIED); } std::tuple remote_directions[] = { - {bluetooth::le_audio::types::kLeAudioDirectionSink, - bluetooth::le_audio::types::kLeAudioDirectionSource, - &audio_sender_state_}, - {bluetooth::le_audio::types::kLeAudioDirectionSource, - bluetooth::le_audio::types::kLeAudioDirectionSink, - &audio_receiver_state_}, + {bluetooth::le_audio::types::kLeAudioDirectionSink, + bluetooth::le_audio::types::kLeAudioDirectionSource, &audio_sender_state_}, + {bluetooth::le_audio::types::kLeAudioDirectionSource, + bluetooth::le_audio::types::kLeAudioDirectionSink, &audio_receiver_state_}, }; /* Align with the context availability */ @@ -4772,15 +4454,14 @@ class LeAudioClientImpl : public LeAudioClient { } log::debug("Checking contexts: {}, against the available contexts: {}", - ToString(contexts_pair.get(dir)), - ToString(group_available_contexts)); - auto unavail_contexts = - contexts_pair.get(dir) & ~group_available_contexts; - if (unavail_contexts.none()) continue; + ToString(contexts_pair.get(dir)), ToString(group_available_contexts)); + auto unavail_contexts = contexts_pair.get(dir) & ~group_available_contexts; + if (unavail_contexts.none()) { + continue; + } contexts_pair.get(dir) &= group_available_contexts; - auto unavail_but_supported = - (unavail_contexts & group->GetSupportedContexts(dir)); + auto unavail_but_supported = (unavail_contexts & group->GetSupportedContexts(dir)); if (unavail_but_supported.none() && group_available_contexts.test(LeAudioContextType::UNSPECIFIED)) { log::debug("Replaced the unsupported contexts: {} with UNSPECIFIED", @@ -4812,18 +4493,15 @@ class LeAudioClientImpl : public LeAudioClient { if (contexts_pair.get(dir).test(LeAudioContextType::UNSPECIFIED)) { /* Try to use the other direction context if not UNSPECIFIED and active */ - if (contexts_pair.get(dir) == - AudioContexts(LeAudioContextType::UNSPECIFIED)) { - auto is_other_direction_streaming = - (*local_hal_state == AudioState::STARTED) || - (*local_hal_state == AudioState::READY_TO_START); + if (contexts_pair.get(dir) == AudioContexts(LeAudioContextType::UNSPECIFIED)) { + auto is_other_direction_streaming = (*local_hal_state == AudioState::STARTED) || + (*local_hal_state == AudioState::READY_TO_START); if (is_other_direction_streaming && - (contexts_pair.get(other_dir) != - AudioContexts(LeAudioContextType::UNSPECIFIED))) { + (contexts_pair.get(other_dir) != AudioContexts(LeAudioContextType::UNSPECIFIED))) { log::info( - "Other direction is streaming. Aligning other direction " - "metadata to match the current direciton context: {}", - ToString(contexts_pair.get(other_dir))); + "Other direction is streaming. Aligning other direction " + "metadata to match the current direction context: {}", + ToString(contexts_pair.get(other_dir))); contexts_pair.get(dir) = contexts_pair.get(other_dir); } } else { @@ -4841,8 +4519,7 @@ class LeAudioClientImpl : public LeAudioClient { ToString(contexts_pair.sink), ToString(contexts_pair.source)); } - void OnLocalAudioSinkMetadataUpdate( - const std::vector& sink_metadata) { + void OnLocalAudioSinkMetadataUpdate(const std::vector& sink_metadata) { if (active_group_id_ == bluetooth::groups::kGroupUnknown) { log::warn(", cannot start streaming if no active group set"); return; @@ -4855,60 +4532,52 @@ class LeAudioClientImpl : public LeAudioClient { } log::info( - "group_id {} state={}, target_state={}, audio_receiver_state_: {}, " - "audio_sender_state_: {}", - group->group_id_, ToString(group->GetState()), - ToString(group->GetTargetState()), ToString(audio_receiver_state_), - ToString(audio_sender_state_)); + "group_id {} state={}, target_state={}, audio_receiver_state_: {}, " + "audio_sender_state_: {}", + group->group_id_, ToString(group->GetState()), ToString(group->GetTargetState()), + ToString(audio_receiver_state_), ToString(audio_sender_state_)); /* Set remote source metadata context from the recording tracks metadata */ - local_metadata_context_types_.sink = - GetAudioContextsFromSinkMetadata(sink_metadata); + local_metadata_context_types_.sink = GetAudioContextsFromSinkMetadata(sink_metadata); local_metadata_context_types_.sink = - ChooseMetadataContextType(local_metadata_context_types_.sink); + ChooseMetadataContextType(local_metadata_context_types_.sink); local_metadata_context_types_.source = - ChooseMetadataContextType(local_metadata_context_types_.source); + ChooseMetadataContextType(local_metadata_context_types_.source); /* Reconfigure or update only if the stream is already started * otherwise wait for the local sink to resume. */ if (audio_receiver_state_ == AudioState::STARTED) { - ReconfigureOrUpdateRemote( - group, bluetooth::le_audio::types::kLeAudioDirectionSource); + ReconfigureOrUpdateRemote(group, bluetooth::le_audio::types::kLeAudioDirectionSource); } } BidirectionalPair DirectionalRealignMetadataAudioContexts( - LeAudioDeviceGroup* group, int remote_direction) { + LeAudioDeviceGroup* group, int remote_direction) { auto remote_other_direction = - (remote_direction == bluetooth::le_audio::types::kLeAudioDirectionSink - ? bluetooth::le_audio::types::kLeAudioDirectionSource - : bluetooth::le_audio::types::kLeAudioDirectionSink); + (remote_direction == bluetooth::le_audio::types::kLeAudioDirectionSink + ? bluetooth::le_audio::types::kLeAudioDirectionSource + : bluetooth::le_audio::types::kLeAudioDirectionSink); auto other_direction_hal = - (remote_other_direction == - bluetooth::le_audio::types::kLeAudioDirectionSource - ? audio_receiver_state_ - : audio_sender_state_); - auto is_streaming_other_direction = - (other_direction_hal == AudioState::STARTED) || - (other_direction_hal == AudioState::READY_TO_START); + (remote_other_direction == bluetooth::le_audio::types::kLeAudioDirectionSource + ? audio_receiver_state_ + : audio_sender_state_); + auto is_streaming_other_direction = (other_direction_hal == AudioState::STARTED) || + (other_direction_hal == AudioState::READY_TO_START); auto is_releasing_for_reconfiguration = - (((audio_receiver_state_ == AudioState::RELEASING) || - (audio_sender_state_ == AudioState::RELEASING)) && - group->IsPendingConfiguration() && - IsDirectionAvailableForCurrentConfiguration(group, - remote_other_direction)); + (((audio_receiver_state_ == AudioState::RELEASING) || + (audio_sender_state_ == AudioState::RELEASING)) && + group->IsPendingConfiguration() && + IsDirectionAvailableForCurrentConfiguration(group, remote_other_direction)); // Inject conversational when ringtone is played - this is required for all // the VoIP applications which are not using the telecom API. constexpr AudioContexts possible_voip_contexts = - LeAudioContextType::RINGTONE | LeAudioContextType::CONVERSATIONAL; + LeAudioContextType::RINGTONE | LeAudioContextType::CONVERSATIONAL; if (local_metadata_context_types_.source.test_any(possible_voip_contexts) && - ((remote_direction == - bluetooth::le_audio::types::kLeAudioDirectionSink) || - (remote_direction == - bluetooth::le_audio::types::kLeAudioDirectionSource && + ((remote_direction == bluetooth::le_audio::types::kLeAudioDirectionSink) || + (remote_direction == bluetooth::le_audio::types::kLeAudioDirectionSource && is_streaming_other_direction))) { /* Simulate, we are already in the call. Sending RINGTONE when there is * no incoming call to accept or reject on TBS could confuse the remote @@ -4925,19 +4594,16 @@ class LeAudioClientImpl : public LeAudioClient { * with any other bidirectional context */ if (IsInCall() || IsInVoipCall()) { - log::debug("In Call preference used: {}, voip call: {}", IsInCall(), - IsInVoipCall()); + log::debug("In Call preference used: {}, voip call: {}", IsInCall(), IsInVoipCall()); local_metadata_context_types_.sink.unset_all(kLeAudioContextAllBidir); local_metadata_context_types_.source.unset_all(kLeAudioContextAllBidir); - local_metadata_context_types_.sink.set( - LeAudioContextType::CONVERSATIONAL); - local_metadata_context_types_.source.set( - LeAudioContextType::CONVERSATIONAL); + local_metadata_context_types_.sink.set(LeAudioContextType::CONVERSATIONAL); + local_metadata_context_types_.source.set(LeAudioContextType::CONVERSATIONAL); } BidirectionalPair remote_metadata = { - .sink = local_metadata_context_types_.source, - .source = local_metadata_context_types_.sink}; + .sink = local_metadata_context_types_.source, + .source = local_metadata_context_types_.sink}; if (IsInVoipCall()) { log::debug("Unsetting RINGTONE from remote sink"); @@ -4945,7 +4611,7 @@ class LeAudioClientImpl : public LeAudioClient { } auto is_ongoing_call_on_other_direction = - is_streaming_other_direction && (IsInVoipCall() || IsInCall()); + is_streaming_other_direction && (IsInVoipCall() || IsInCall()); log::debug("local_metadata_context_types_.source= {}", ToString(local_metadata_context_types_.source)); @@ -4953,24 +4619,18 @@ class LeAudioClientImpl : public LeAudioClient { ToString(local_metadata_context_types_.sink)); log::debug("remote_metadata.source= {}", ToString(remote_metadata.source)); log::debug("remote_metadata.sink= {}", ToString(remote_metadata.sink)); - log::debug( - "remote_direction= {}", - (remote_direction == bluetooth::le_audio::types::kLeAudioDirectionSource - ? "Source" - : "Sink")); - log::debug("is_streaming_other_direction= {}", - is_streaming_other_direction ? "True" : "False"); + log::debug("remote_direction= {}", + (remote_direction == bluetooth::le_audio::types::kLeAudioDirectionSource ? "Source" + : "Sink")); + log::debug("is_streaming_other_direction= {}", is_streaming_other_direction ? "True" : "False"); log::debug("is_releasing_for_reconfiguration= {}", is_releasing_for_reconfiguration ? "True" : "False"); log::debug("is_ongoing_call_on_other_direction={}", is_ongoing_call_on_other_direction ? "True" : "False"); - if (remote_metadata.get(remote_other_direction) - .test_any(kLeAudioContextAllBidir) && + if (remote_metadata.get(remote_other_direction).test_any(kLeAudioContextAllBidir) && !is_streaming_other_direction) { - log::debug( - "The other direction is not streaming bidirectional, ignore that " - "context."); + log::debug("The other direction is not streaming bidirectional, ignore that context."); remote_metadata.get(remote_other_direction).clear(); } @@ -4978,30 +4638,22 @@ class LeAudioClientImpl : public LeAudioClient { * on how to configure each channel. We should align the other direction * metadata for the remote device. */ - if (remote_metadata.get(remote_direction) - .test_any(kLeAudioContextAllBidir)) { - log::debug( - "Aligning the other direction remote metadata to add this direction " - "context"); + if (remote_metadata.get(remote_direction).test_any(kLeAudioContextAllBidir)) { + log::debug("Aligning the other direction remote metadata to add this direction context"); if (is_ongoing_call_on_other_direction) { /* Other direction is streaming and is in call */ - remote_metadata.get(remote_direction) - .unset_all(kLeAudioContextAllBidir); - remote_metadata.get(remote_direction) - .set(LeAudioContextType::CONVERSATIONAL); + remote_metadata.get(remote_direction).unset_all(kLeAudioContextAllBidir); + remote_metadata.get(remote_direction).set(LeAudioContextType::CONVERSATIONAL); } else { if (!is_streaming_other_direction) { // Do not take the obsolete metadata remote_metadata.get(remote_other_direction).clear(); } + remote_metadata.get(remote_other_direction).unset_all(kLeAudioContextAllBidir); + remote_metadata.get(remote_other_direction).unset_all(kLeAudioContextAllRemoteSinkOnly); remote_metadata.get(remote_other_direction) - .unset_all(kLeAudioContextAllBidir); - remote_metadata.get(remote_other_direction) - .unset_all(kLeAudioContextAllRemoteSinkOnly); - remote_metadata.get(remote_other_direction) - .set_all(remote_metadata.get(remote_direction) & - ~kLeAudioContextAllRemoteSinkOnly); + .set_all(remote_metadata.get(remote_direction) & ~kLeAudioContextAllRemoteSinkOnly); } } log::debug("remote_metadata.source= {}", ToString(remote_metadata.source)); @@ -5015,18 +4667,13 @@ class LeAudioClientImpl : public LeAudioClient { */ if ((remote_metadata.get(remote_direction).none() && remote_metadata.get(remote_other_direction).any()) || - remote_metadata.get(remote_other_direction) - .test_any(kLeAudioContextAllBidir)) { - log::debug( - "Aligning this direction remote metadata to add the other " - "direction context"); + remote_metadata.get(remote_other_direction).test_any(kLeAudioContextAllBidir)) { + log::debug("Aligning this direction remote metadata to add the other direction context"); /* Turn off bidirectional contexts on this direction to avoid mixing * with the other direction bidirectional context */ - remote_metadata.get(remote_direction) - .unset_all(kLeAudioContextAllBidir); - remote_metadata.get(remote_direction) - .set_all(remote_metadata.get(remote_other_direction)); + remote_metadata.get(remote_direction).unset_all(kLeAudioContextAllBidir); + remote_metadata.get(remote_direction).set_all(remote_metadata.get(remote_other_direction)); } } @@ -5039,12 +4686,10 @@ class LeAudioClientImpl : public LeAudioClient { return remote_metadata; } - LeAudioContextType AdjustForVoiceAssistant( - LeAudioDeviceGroup* group, LeAudioContextType new_configuration_context) { - if (!com::android::bluetooth::flags:: - le_audio_support_unidirectional_voice_assistant()) { - log::debug( - "Flag le_audio_support_unidirectional_voice_assistant NOT enabled"); + LeAudioContextType AdjustForVoiceAssistant(LeAudioDeviceGroup* group, + LeAudioContextType new_configuration_context) { + if (!com::android::bluetooth::flags::le_audio_support_unidirectional_voice_assistant()) { + log::debug("Flag le_audio_support_unidirectional_voice_assistant NOT enabled"); return new_configuration_context; } @@ -5054,14 +4699,13 @@ class LeAudioClientImpl : public LeAudioClient { return new_configuration_context; } - auto sink_supported_contexts = group->GetSupportedContexts( - bluetooth::le_audio::types::kLeAudioDirectionSink); - auto source_supported_contexts = group->GetSupportedContexts( - bluetooth::le_audio::types::kLeAudioDirectionSource); + auto sink_supported_contexts = + group->GetSupportedContexts(bluetooth::le_audio::types::kLeAudioDirectionSink); + auto source_supported_contexts = + group->GetSupportedContexts(bluetooth::le_audio::types::kLeAudioDirectionSource); - log::debug("group_id: {}, sink_supported: {}, source_supported {}", - group->group_id_, ToString(sink_supported_contexts), - ToString(source_supported_contexts)); + log::debug("group_id: {}, sink_supported: {}, source_supported {}", group->group_id_, + ToString(sink_supported_contexts), ToString(source_supported_contexts)); if (sink_supported_contexts.test(LeAudioContextType::VOICEASSISTANTS) && source_supported_contexts.test(LeAudioContextType::VOICEASSISTANTS)) { return new_configuration_context; @@ -5069,26 +4713,22 @@ class LeAudioClientImpl : public LeAudioClient { if (sink_supported_contexts.test(LeAudioContextType::VOICEASSISTANTS)) { log::info( - "group_id {} supports only Sink direction for Voice Assistant. " - "Selecting configurarion context type {}", - group->group_id_, ToString(LeAudioContextType::INSTRUCTIONAL)); + "group_id {} supports only Sink direction for Voice Assistant. " + "Selecting configurarion context type {}", + group->group_id_, ToString(LeAudioContextType::INSTRUCTIONAL)); return LeAudioContextType::INSTRUCTIONAL; } - log::warn( - "group_id: {}, unexpected configuration, sink_supported: {}, " - "source_supported {}", - group->group_id_, ToString(sink_supported_contexts), - ToString(source_supported_contexts)); + log::warn("group_id: {}, unexpected configuration, sink_supported: {}, source_supported {}", + group->group_id_, ToString(sink_supported_contexts), + ToString(source_supported_contexts)); return new_configuration_context; } /* Return true if stream is started */ - bool ReconfigureOrUpdateRemote(LeAudioDeviceGroup* group, - int remote_direction) { - if (stack_config_get_interface() - ->get_pts_force_le_audio_multiple_contexts_metadata()) { + bool ReconfigureOrUpdateRemote(LeAudioDeviceGroup* group, int remote_direction) { + if (stack_config_get_interface()->get_pts_force_le_audio_multiple_contexts_metadata()) { // Use common audio stream contexts exposed by the PTS auto override_contexts = AudioContexts(0xFFFF); for (auto device = group->GetFirstDevice(); device != nullptr; @@ -5099,19 +4739,16 @@ class LeAudioClientImpl : public LeAudioClient { override_contexts = AudioContexts(LeAudioContextType::UNSPECIFIED); } log::warn("Overriding local_metadata_context_types_: {} with: {}", - local_metadata_context_types_.source.to_string(), - override_contexts.to_string()); + local_metadata_context_types_.source.to_string(), override_contexts.to_string()); /* Choose the right configuration context */ - auto new_configuration_context = AdjustForVoiceAssistant( - group, ChooseConfigurationContextType(override_contexts)); + auto new_configuration_context = + AdjustForVoiceAssistant(group, ChooseConfigurationContextType(override_contexts)); - log::debug("new_configuration_context= {}.", - ToString(new_configuration_context)); - BidirectionalPair remote_contexts = { - .sink = override_contexts, .source = override_contexts}; - return GroupStream(active_group_id_, new_configuration_context, - remote_contexts); + log::debug("new_configuration_context= {}.", ToString(new_configuration_context)); + BidirectionalPair remote_contexts = {.sink = override_contexts, + .source = override_contexts}; + return GroupStream(active_group_id_, new_configuration_context, remote_contexts); } /* When the local sink and source update their metadata, we need to come up @@ -5119,13 +4756,12 @@ class LeAudioClientImpl : public LeAudioClient { * especially when bidirectional scenarios can be triggered be either sink * or source metadata update event. */ - auto remote_metadata = - DirectionalRealignMetadataAudioContexts(group, remote_direction); + auto remote_metadata = DirectionalRealignMetadataAudioContexts(group, remote_direction); /* Choose the right configuration context */ auto config_context_candids = get_bidirectional(remote_metadata); - auto new_config_context = AdjustForVoiceAssistant( - group, ChooseConfigurationContextType(config_context_candids)); + auto new_config_context = + AdjustForVoiceAssistant(group, ChooseConfigurationContextType(config_context_candids)); log::debug("config_context_candids= {}, new_config_context= {}", ToString(config_context_candids), ToString(new_config_context)); @@ -5140,19 +4776,19 @@ class LeAudioClientImpl : public LeAudioClient { * quality and these are the only contributors to the current audio stream. */ auto no_reconfigure_contexts = - LeAudioContextType::NOTIFICATIONS | LeAudioContextType::SOUNDEFFECTS | - LeAudioContextType::INSTRUCTIONAL | LeAudioContextType::ALERTS | - LeAudioContextType::EMERGENCYALARM | LeAudioContextType::UNSPECIFIED; + LeAudioContextType::NOTIFICATIONS | LeAudioContextType::SOUNDEFFECTS | + LeAudioContextType::INSTRUCTIONAL | LeAudioContextType::ALERTS | + LeAudioContextType::EMERGENCYALARM | LeAudioContextType::UNSPECIFIED; if (group->IsStreaming() && config_context_candids.any() && (config_context_candids & ~no_reconfigure_contexts).none() && (configuration_context_type_ != LeAudioContextType::UNINITIALIZED) && (configuration_context_type_ != LeAudioContextType::UNSPECIFIED) && IsDirectionAvailableForCurrentConfiguration( - group, bluetooth::le_audio::types::kLeAudioDirectionSink)) { + group, bluetooth::le_audio::types::kLeAudioDirectionSink)) { log::info( - "There is no need to reconfigure for the sonification events, " - "staying with the existing configuration context of {}", - ToString(configuration_context_type_)); + "There is no need to reconfigure for the sonification events, " + "staying with the existing configuration context of {}", + ToString(configuration_context_type_)); new_config_context = configuration_context_type_; } @@ -5161,18 +4797,16 @@ class LeAudioClientImpl : public LeAudioClient { * lead to unsatisfying audio quality when that direction was * already configured with a lower quality. */ - if (remote_direction == - bluetooth::le_audio::types::kLeAudioDirectionSource) { + if (remote_direction == bluetooth::le_audio::types::kLeAudioDirectionSource) { const auto has_audio_source_configured = - IsDirectionAvailableForCurrentConfiguration( - group, bluetooth::le_audio::types::kLeAudioDirectionSource) && - (group->GetState() == AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + IsDirectionAvailableForCurrentConfiguration( + group, bluetooth::le_audio::types::kLeAudioDirectionSource) && + (group->GetState() == AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); if (has_audio_source_configured) { log::info( - "Audio source is already available in the current configuration " - "context in {}. Not switching to {} right now.", - ToString(configuration_context_type_), - ToString(new_config_context)); + "Audio source is already available in the current configuration " + "context in {}. Not switching to {} right now.", + ToString(configuration_context_type_), ToString(new_config_context)); new_config_context = configuration_context_type_; } } @@ -5182,14 +4816,11 @@ class LeAudioClientImpl : public LeAudioClient { * we could choose the correct configuration for the use case. Now we can * align it to meet the metadata usage. */ - ApplyRemoteMetadataAudioContextPolicy(group, remote_metadata, - remote_direction); - return ReconfigureOrUpdateMetadata(group, new_config_context, - remote_metadata); + ApplyRemoteMetadataAudioContextPolicy(group, remote_metadata, remote_direction); + return ReconfigureOrUpdateMetadata(group, new_config_context, remote_metadata); } - bool DsaReconfigureNeeded(LeAudioDeviceGroup* group, - LeAudioContextType context) { + bool DsaReconfigureNeeded(LeAudioDeviceGroup* group, LeAudioContextType context) { if (!com::android::bluetooth::flags::leaudio_dynamic_spatial_audio()) { return false; } @@ -5199,8 +4830,7 @@ class LeAudioClientImpl : public LeAudioClient { return false; } - if (group->dsa_.mode != DsaMode::ISO_SW && - group->dsa_.mode != DsaMode::ISO_HW) { + if (group->dsa_.mode != DsaMode::ISO_SW && group->dsa_.mode != DsaMode::ISO_HW) { return false; } @@ -5213,56 +4843,49 @@ class LeAudioClientImpl : public LeAudioClient { } /* Return true if stream is started */ - bool ReconfigureOrUpdateMetadata( - LeAudioDeviceGroup* group, LeAudioContextType new_configuration_context, - BidirectionalPair remote_contexts) { + bool ReconfigureOrUpdateMetadata(LeAudioDeviceGroup* group, + LeAudioContextType new_configuration_context, + BidirectionalPair remote_contexts) { if (new_configuration_context != configuration_context_type_ || DsaReconfigureNeeded(group, new_configuration_context)) { - log::info( - "Checking whether to change configuration context from {} to {}", - ToString(configuration_context_type_), - ToString(new_configuration_context)); + log::info("Checking whether to change configuration context from {} to {}", + ToString(configuration_context_type_), ToString(new_configuration_context)); LeAudioLogHistory::Get()->AddLogHistory( - kLogAfCallBt, active_group_id_, RawAddress::kEmpty, - kLogAfMetadataUpdate + "Reconfigure", - ToString(configuration_context_type_) + "->" + - ToString(new_configuration_context)); - auto is_stopping = SetConfigurationAndStopStreamWhenNeeded( - group, new_configuration_context); + kLogAfCallBt, active_group_id_, RawAddress::kEmpty, + kLogAfMetadataUpdate + "Reconfigure", + ToString(configuration_context_type_) + "->" + ToString(new_configuration_context)); + auto is_stopping = SetConfigurationAndStopStreamWhenNeeded(group, new_configuration_context); if (is_stopping) { return false; } } if (group->GetTargetState() == AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) { - log::info( - "The {} configuration did not change. Updating the metadata to " - "sink={}, source={}", - ToString(configuration_context_type_), ToString(remote_contexts.sink), - ToString(remote_contexts.source)); + log::info("The {} configuration did not change. Updating the metadata to sink={}, source={}", + ToString(configuration_context_type_), ToString(remote_contexts.sink), + ToString(remote_contexts.source)); LeAudioLogHistory::Get()->AddLogHistory( - kLogAfCallBt, active_group_id_, RawAddress::kEmpty, - kLogAfMetadataUpdate + "Updating...", - "Sink: " + ToString(remote_contexts.sink) + - "Source: " + ToString(remote_contexts.source)); + kLogAfCallBt, active_group_id_, RawAddress::kEmpty, + kLogAfMetadataUpdate + "Updating...", + "Sink: " + ToString(remote_contexts.sink) + + "Source: " + ToString(remote_contexts.source)); - return GroupStream(group->group_id_, configuration_context_type_, - remote_contexts); + return GroupStream(group->group_id_, configuration_context_type_, remote_contexts); } return false; } - static void OnGattCtpCccReadRspStatic(uint16_t conn_id, tGATT_STATUS status, - uint16_t hdl, uint16_t len, - uint8_t* value, void* data) { - if (!instance) return; + static void OnGattCtpCccReadRspStatic(uint16_t conn_id, tGATT_STATUS status, uint16_t hdl, + uint16_t len, uint8_t* value, void* data) { + if (!instance) { + return; + } log::debug("conn_id: 0x{:04x}, status: 0x{:02x}", conn_id, status); - LeAudioDevice* leAudioDevice = - instance->leAudioDevices_.FindByConnId(conn_id); + LeAudioDevice* leAudioDevice = instance->leAudioDevices_.FindByConnId(conn_id); if (!leAudioDevice) { log::error("LeAudioDevice not found"); @@ -5270,36 +4893,33 @@ class LeAudioClientImpl : public LeAudioClient { } if (status == GATT_DATABASE_OUT_OF_SYNC) { - log::info("Database out of sync for {}, re-discovering", - leAudioDevice->address_); + log::info("Database out of sync for {}, re-discovering", leAudioDevice->address_); instance->ClearDeviceInformationAndStartSearch(leAudioDevice); return; } if (status != GATT_SUCCESS || len != 2) { - log::error("Could not read CCC for {}, disconnecting", - leAudioDevice->address_); + log::error("Could not read CCC for {}, disconnecting", leAudioDevice->address_); instance->Disconnect(leAudioDevice->address_); return; } uint16_t val = *(uint16_t*)value; if (val == 0) { - log::info("{} forgot CCC values. Re-subscribing", - leAudioDevice->address_); + log::info("{} forgot CCC values. Re-subscribing", leAudioDevice->address_); instance->RegisterKnownNotifications(leAudioDevice, false, true); } else { instance->connectionReady(leAudioDevice); } } - static void OnGattReadRspStatic(uint16_t conn_id, tGATT_STATUS status, - uint16_t hdl, uint16_t len, uint8_t* value, - void* data) { - if (!instance) return; + static void OnGattReadRspStatic(uint16_t conn_id, tGATT_STATUS status, uint16_t hdl, uint16_t len, + uint8_t* value, void* data) { + if (!instance) { + return; + } - LeAudioDevice* leAudioDevice = - instance->leAudioDevices_.FindByConnId(conn_id); + LeAudioDevice* leAudioDevice = instance->leAudioDevices_.FindByConnId(conn_id); if (status == GATT_SUCCESS) { instance->LeAudioCharValueHandle(conn_id, hdl, len, value); @@ -5307,8 +4927,8 @@ class LeAudioClientImpl : public LeAudioClient { instance->ClearDeviceInformationAndStartSearch(leAudioDevice); return; } else { - log::error("Failed to read attribute, hdl: 0x{:04x}, status: 0x{:02x}", - hdl, static_cast(status)); + log::error("Failed to read attribute, hdl: 0x{:04x}, status: 0x{:02x}", hdl, + static_cast(status)); return; } @@ -5321,10 +4941,9 @@ class LeAudioClientImpl : public LeAudioClient { btif_storage_leaudio_update_pacs_bin(leAudioDevice->address_); btif_storage_leaudio_update_ase_bin(leAudioDevice->address_); - btif_storage_set_leaudio_audio_location( - leAudioDevice->address_, - leAudioDevice->snk_audio_locations_.to_ulong(), - leAudioDevice->src_audio_locations_.to_ulong()); + btif_storage_set_leaudio_audio_location(leAudioDevice->address_, + leAudioDevice->snk_audio_locations_.to_ulong(), + leAudioDevice->src_audio_locations_.to_ulong()); instance->connectionReady(leAudioDevice); } @@ -5334,13 +4953,11 @@ class LeAudioClientImpl : public LeAudioClient { LeAudioHealthBasedAction action) { log::debug("{}, {}, {}", address, group_id, ToString(action)); - if (address != RawAddress::kEmpty && - leAudioDevices_.FindByAddress(address)) { + if (address != RawAddress::kEmpty && leAudioDevices_.FindByAddress(address)) { callbacks_->OnHealthBasedRecommendationAction(address, action); } - if (group_id != bluetooth::groups::kGroupUnknown && - aseGroups_.FindById(group_id)) { + if (group_id != bluetooth::groups::kGroupUnknown && aseGroups_.FindById(group_id)) { callbacks_->OnHealthBasedGroupRecommendationAction(group_id, action); } } @@ -5351,8 +4968,8 @@ class LeAudioClientImpl : public LeAudioClient { auto* evt = static_cast(data); LeAudioDeviceGroup* group = aseGroups_.FindById(evt->cig_id); log::assert_that(group, "Group id: {} is null", evt->cig_id); - groupStateMachine_->ProcessHciNotifOnCigCreate( - group, evt->status, evt->cig_id, evt->conn_handles); + groupStateMachine_->ProcessHciNotifOnCigCreate(group, evt->status, evt->cig_id, + evt->conn_handles); } break; case bluetooth::hci::iso_manager::kIsoEventCigOnRemoveCmpl: { auto* evt = static_cast(data); @@ -5369,138 +4986,116 @@ class LeAudioClientImpl : public LeAudioClient { void IsoCisEventsCb(uint16_t event_type, void* data) { switch (event_type) { case bluetooth::hci::iso_manager::kIsoEventCisDataAvailable: { - auto* event = - static_cast(data); + auto* event = static_cast(data); if (DsaDataConsume(event)) { return; } if (audio_receiver_state_ != AudioState::STARTED) { - log::error("receiver state not ready, current state={}", - ToString(audio_receiver_state_)); + log::error("receiver state not ready, current state={}", ToString(audio_receiver_state_)); break; } HandleIncomingCisData(event->p_msg->data + event->p_msg->offset, - event->p_msg->len - event->p_msg->offset, - event->cis_conn_hdl, event->ts); + event->p_msg->len - event->p_msg->offset, event->cis_conn_hdl, + event->ts); } break; case bluetooth::hci::iso_manager::kIsoEventCisEstablishCmpl: { - auto* event = - static_cast( - data); + auto* event = static_cast(data); - LeAudioDevice* leAudioDevice = leAudioDevices_.FindByCisConnHdl( - event->cig_id, event->cis_conn_hdl); + LeAudioDevice* leAudioDevice = + leAudioDevices_.FindByCisConnHdl(event->cig_id, event->cis_conn_hdl); if (!leAudioDevice) { - log::error("no bonded Le Audio Device with CIS: {}", - event->cis_conn_hdl); + log::error("no bonded Le Audio Device with CIS: {}", event->cis_conn_hdl); break; } - LeAudioDeviceGroup* group = - aseGroups_.FindById(leAudioDevice->group_id_); - - if (event->max_pdu_mtos > 0) - group->SetTransportLatency( - bluetooth::le_audio::types::kLeAudioDirectionSink, - event->trans_lat_mtos); - if (event->max_pdu_stom > 0) - group->SetTransportLatency( - bluetooth::le_audio::types::kLeAudioDirectionSource, - event->trans_lat_stom); + LeAudioDeviceGroup* group = aseGroups_.FindById(leAudioDevice->group_id_); + + if (event->max_pdu_mtos > 0) { + group->SetTransportLatency(bluetooth::le_audio::types::kLeAudioDirectionSink, + event->trans_lat_mtos); + } + if (event->max_pdu_stom > 0) { + group->SetTransportLatency(bluetooth::le_audio::types::kLeAudioDirectionSource, + event->trans_lat_stom); + } if (leAudioHealthStatus_ && (event->status != HCI_SUCCESS)) { leAudioHealthStatus_->AddStatisticForGroup( - group, LeAudioHealthGroupStatType::STREAM_CREATE_CIS_FAILED); + group, LeAudioHealthGroupStatType::STREAM_CREATE_CIS_FAILED); } - groupStateMachine_->ProcessHciNotifCisEstablished(group, leAudioDevice, - event); + groupStateMachine_->ProcessHciNotifCisEstablished(group, leAudioDevice, event); } break; case bluetooth::hci::iso_manager::kIsoEventCisDisconnected: { - auto* event = - static_cast( - data); + auto* event = static_cast(data); - LeAudioDevice* leAudioDevice = leAudioDevices_.FindByCisConnHdl( - event->cig_id, event->cis_conn_hdl); + LeAudioDevice* leAudioDevice = + leAudioDevices_.FindByCisConnHdl(event->cig_id, event->cis_conn_hdl); if (!leAudioDevice) { - log::error("no bonded Le Audio Device with CIS: {}", - event->cis_conn_hdl); + log::error("no bonded Le Audio Device with CIS: {}", event->cis_conn_hdl); break; } - LeAudioDeviceGroup* group = - aseGroups_.FindById(leAudioDevice->group_id_); + LeAudioDeviceGroup* group = aseGroups_.FindById(leAudioDevice->group_id_); - groupStateMachine_->ProcessHciNotifCisDisconnected(group, leAudioDevice, - event); + groupStateMachine_->ProcessHciNotifCisDisconnected(group, leAudioDevice, event); } break; default: - log::info(", Not handeled ISO event"); + log::info(", Not handled ISO event"); break; } } - void IsoSetupIsoDataPathCb(uint8_t status, uint16_t conn_handle, - uint8_t cig_id) { - LeAudioDevice* leAudioDevice = - leAudioDevices_.FindByCisConnHdl(cig_id, conn_handle); + void IsoSetupIsoDataPathCb(uint8_t status, uint16_t conn_handle, uint8_t cig_id) { + LeAudioDevice* leAudioDevice = leAudioDevices_.FindByCisConnHdl(cig_id, conn_handle); /* In case device has been disconnected before data path was setup */ if (!leAudioDevice) { - log::warn( - "Device for CIG {} and using cis_handle 0x{:04x} is disconnected.", - cig_id, conn_handle); + log::warn("Device for CIG {} and using cis_handle 0x{:04x} is disconnected.", cig_id, + conn_handle); return; } LeAudioDeviceGroup* group = aseGroups_.FindById(leAudioDevice->group_id_); - instance->groupStateMachine_->ProcessHciNotifSetupIsoDataPath( - group, leAudioDevice, status, conn_handle); + instance->groupStateMachine_->ProcessHciNotifSetupIsoDataPath(group, leAudioDevice, status, + conn_handle); } - void IsoRemoveIsoDataPathCb(uint8_t status, uint16_t conn_handle, - uint8_t cig_id) { - LeAudioDevice* leAudioDevice = - leAudioDevices_.FindByCisConnHdl(cig_id, conn_handle); + void IsoRemoveIsoDataPathCb(uint8_t status, uint16_t conn_handle, uint8_t cig_id) { + LeAudioDevice* leAudioDevice = leAudioDevices_.FindByCisConnHdl(cig_id, conn_handle); /* If CIS has been disconnected just before ACL being disconnected by the * remote device, leAudioDevice might be already cleared i.e. has no * information about conn_handle, when the data path remove compete arrives. */ if (!leAudioDevice) { - log::warn( - "Device for CIG {} and using cis_handle 0x{:04x} is disconnected.", - cig_id, conn_handle); + log::warn("Device for CIG {} and using cis_handle 0x{:04x} is disconnected.", cig_id, + conn_handle); return; } LeAudioDeviceGroup* group = aseGroups_.FindById(leAudioDevice->group_id_); - instance->groupStateMachine_->ProcessHciNotifRemoveIsoDataPath( - group, leAudioDevice, status, conn_handle); + instance->groupStateMachine_->ProcessHciNotifRemoveIsoDataPath(group, leAudioDevice, status, + conn_handle); } - void IsoLinkQualityReadCb( - uint8_t conn_handle, uint8_t cig_id, uint32_t txUnackedPackets, - uint32_t txFlushedPackets, uint32_t txLastSubeventPackets, - uint32_t retransmittedPackets, uint32_t crcErrorPackets, - uint32_t rxUnreceivedPackets, uint32_t duplicatePackets) { - LeAudioDevice* leAudioDevice = - leAudioDevices_.FindByCisConnHdl(cig_id, conn_handle); + void IsoLinkQualityReadCb(uint8_t conn_handle, uint8_t cig_id, uint32_t txUnackedPackets, + uint32_t txFlushedPackets, uint32_t txLastSubeventPackets, + uint32_t retransmittedPackets, uint32_t crcErrorPackets, + uint32_t rxUnreceivedPackets, uint32_t duplicatePackets) { + LeAudioDevice* leAudioDevice = leAudioDevices_.FindByCisConnHdl(cig_id, conn_handle); if (!leAudioDevice) { - log::warn( - "device under connection handle: 0x{:x}, has been disconnecected in " - "meantime", - conn_handle); + log::warn("device under connection handle: 0x{:x}, has been disconnecected in meantime", + conn_handle); return; } LeAudioDeviceGroup* group = aseGroups_.FindById(leAudioDevice->group_id_); instance->groupStateMachine_->ProcessHciNotifIsoLinkQualityRead( - group, leAudioDevice, conn_handle, txUnackedPackets, txFlushedPackets, - txLastSubeventPackets, retransmittedPackets, crcErrorPackets, - rxUnreceivedPackets, duplicatePackets); + group, leAudioDevice, conn_handle, txUnackedPackets, txFlushedPackets, + txLastSubeventPackets, retransmittedPackets, crcErrorPackets, rxUnreceivedPackets, + duplicatePackets); } void HandlePendingDeviceRemove(LeAudioDeviceGroup* group) { @@ -5509,10 +5104,8 @@ class LeAudioClientImpl : public LeAudioClient { if (device->GetConnectionState() == DeviceConnectState::REMOVING) { if (device->closing_stream_for_disconnection_) { device->closing_stream_for_disconnection_ = false; - log::info("Disconnecting group id: {}, address: {}", group->group_id_, - device->address_); - bool force_acl_disconnect = - device->autoconnect_flag_ && group->IsEnabled(); + log::info("Disconnecting group id: {}, address: {}", group->group_id_, device->address_); + bool force_acl_disconnect = device->autoconnect_flag_ && group->IsEnabled(); DisconnectDevice(device, force_acl_disconnect); } group_remove_node(group, device->address_, true); @@ -5529,32 +5122,27 @@ class LeAudioClientImpl : public LeAudioClient { leAudioDevice->closing_stream_for_disconnection_ = false; log::debug("Disconnecting group id: {}, address: {}", group->group_id_, leAudioDevice->address_); - bool force_acl_disconnect = - leAudioDevice->autoconnect_flag_ && group->IsEnabled(); + bool force_acl_disconnect = leAudioDevice->autoconnect_flag_ && group->IsEnabled(); DisconnectDevice(leAudioDevice, force_acl_disconnect); } leAudioDevice = group->GetNextDevice(leAudioDevice); } } - void UpdateAudioConfigToHal( - const ::bluetooth::le_audio::offload_config& config, - uint8_t remote_direction) { - if ((remote_direction & - bluetooth::le_audio::types::kLeAudioDirectionSink) && + void UpdateAudioConfigToHal(const ::bluetooth::le_audio::offload_config& config, + uint8_t remote_direction) { + if ((remote_direction & bluetooth::le_audio::types::kLeAudioDirectionSink) && le_audio_source_hal_client_) { le_audio_source_hal_client_->UpdateAudioConfigToHal(config); } - if ((remote_direction & - bluetooth::le_audio::types::kLeAudioDirectionSource) && + if ((remote_direction & bluetooth::le_audio::types::kLeAudioDirectionSource) && le_audio_sink_hal_client_) { le_audio_sink_hal_client_->UpdateAudioConfigToHal(config); } } void NotifyUpperLayerGroupTurnedIdleDuringCall(int group_id) { - if (!osi_property_get_bool(kNotifyUpperLayerAboutGroupBeingInIdleDuringCall, - false)) { + if (!osi_property_get_bool(kNotifyUpperLayerAboutGroupBeingInIdleDuringCall, false)) { return; } @@ -5562,8 +5150,7 @@ class LeAudioClientImpl : public LeAudioClient { * connected, notify upper layer about it, so it can decide to create SCO if * it is in the handover case */ - if ((IsInCall() || IsInVoipCall()) && - active_group_id_ == bluetooth::groups::kGroupUnknown) { + if ((IsInCall() || IsInVoipCall()) && active_group_id_ == bluetooth::groups::kGroupUnknown) { callbacks_->OnGroupStatus(group_id, GroupStatus::TURNED_IDLE_DURING_CALL); } } @@ -5579,16 +5166,14 @@ class LeAudioClientImpl : public LeAudioClient { stream_setup_end_timestamp_ = bluetooth::common::time_get_os_boottime_us(); stream_start_history_queue_.emplace_front( - (stream_setup_end_timestamp_ - stream_setup_start_timestamp_) / 1000); + (stream_setup_end_timestamp_ - stream_setup_start_timestamp_) / 1000); stream_setup_end_timestamp_ = 0; stream_setup_start_timestamp_ = 0; } - void notifyGroupStreamStatus(int group_id, - GroupStreamStatus groupStreamStatus) { - if (!com::android::bluetooth::flags:: - leaudio_callback_on_group_stream_status()) { + void notifyGroupStreamStatus(int group_id, GroupStreamStatus groupStreamStatus) { + if (!com::android::bluetooth::flags::leaudio_callback_on_group_stream_status()) { return; } @@ -5611,7 +5196,9 @@ class LeAudioClientImpl : public LeAudioClient { } void handleAsymmetricPhyForUnicast(LeAudioDeviceGroup* group) { - if (!group->asymmetric_phy_for_unidirectional_cis_supported) return; + if (!group->asymmetric_phy_for_unidirectional_cis_supported) { + return; + } auto it = lastNotifiedGroupStreamStatusMap_.find(group->group_id_); @@ -5626,12 +5213,9 @@ class LeAudioClientImpl : public LeAudioClient { } void OnStateMachineStatusReportCb(int group_id, GroupStreamStatus status) { - log::info( - "status: {} , group_id: {}, audio_sender_state {}, " - "audio_receiver_state {}", - static_cast(status), group_id, - bluetooth::common::ToString(audio_sender_state_), - bluetooth::common::ToString(audio_receiver_state_)); + log::info("status: {}, group_id: {}, audio_sender_state {}, audio_receiver_state {}", + static_cast(status), group_id, bluetooth::common::ToString(audio_sender_state_), + bluetooth::common::ToString(audio_receiver_state_)); LeAudioDeviceGroup* group = aseGroups_.FindById(group_id); notifyGroupStreamStatus(group_id, status); @@ -5639,25 +5223,23 @@ class LeAudioClientImpl : public LeAudioClient { switch (status) { case GroupStreamStatus::STREAMING: { if (group_id != active_group_id_) { - log::error("Streaming group {} is no longer active. Stop the group.", - group_id); + log::error("Streaming group {} is no longer active. Stop the group.", group_id); GroupStop(group_id); return; } take_stream_time(); - bluetooth::le_audio::MetricsCollector::Get()->OnStreamStarted( - active_group_id_, configuration_context_type_); + bluetooth::le_audio::MetricsCollector::Get()->OnStreamStarted(active_group_id_, + configuration_context_type_); if (leAudioHealthStatus_) { leAudioHealthStatus_->AddStatisticForGroup( - group, LeAudioHealthGroupStatType::STREAM_CREATE_SUCCESS); + group, LeAudioHealthGroupStatType::STREAM_CREATE_SUCCESS); } if (!group) { - log::error("Group {} does not exist anymore. This shall not happen", - group_id); + log::error("Group {} does not exist anymore. This shall not happen", group_id); return; } @@ -5668,8 +5250,7 @@ class LeAudioClientImpl : public LeAudioClient { /* Audio Framework is not interested in the stream anymore. * Just stop streaming */ - log::warn("Stopping stream for group {} as AF not interested.", - group_id); + log::warn("Stopping stream for group {} as AF not interested.", group_id); groupStateMachine_->StopStream(group); return; } @@ -5678,30 +5259,26 @@ class LeAudioClientImpl : public LeAudioClient { * the group was in the ongoing reconfiguration. We should stop the * stream and reconfigure once again. */ - if (group->GetConfigurationContextType() != - configuration_context_type_) { + if (group->GetConfigurationContextType() != configuration_context_type_) { log::debug( - "The configuration {} is no longer valid. Stopping the stream to " - "reconfigure to {}", - ToString(group->GetConfigurationContextType()), - ToString(configuration_context_type_)); + "The configuration {} is no longer valid. Stopping the stream to " + "reconfigure to {}", + ToString(group->GetConfigurationContextType()), + ToString(configuration_context_type_)); group->SetPendingConfiguration(); groupStateMachine_->StopStream(group); - stream_setup_start_timestamp_ = - bluetooth::common::time_get_os_boottime_us(); + stream_setup_start_timestamp_ = bluetooth::common::time_get_os_boottime_us(); return; } BidirectionalPair delays_pair = { - .sink = group->GetRemoteDelay( - bluetooth::le_audio::types::kLeAudioDirectionSink), - .source = group->GetRemoteDelay( - bluetooth::le_audio::types::kLeAudioDirectionSource)}; + .sink = group->GetRemoteDelay(bluetooth::le_audio::types::kLeAudioDirectionSink), + .source = + group->GetRemoteDelay(bluetooth::le_audio::types::kLeAudioDirectionSource)}; CodecManager::GetInstance()->UpdateActiveAudioConfig( - group->stream_conf.stream_params, delays_pair, - std::bind(&LeAudioClientImpl::UpdateAudioConfigToHal, - weak_factory_.GetWeakPtr(), std::placeholders::_1, - std::placeholders::_2)); + group->stream_conf.stream_params, delays_pair, + std::bind(&LeAudioClientImpl::UpdateAudioConfigToHal, weak_factory_.GetWeakPtr(), + std::placeholders::_1, std::placeholders::_2)); /* When at least one direction is started we can assume new * configuration here */ @@ -5732,12 +5309,10 @@ class LeAudioClientImpl : public LeAudioClient { // Check which directions were suspended uint8_t previously_active_directions = 0; if (audio_sender_state_ >= AudioState::READY_TO_START) { - previously_active_directions |= - bluetooth::le_audio::types::kLeAudioDirectionSink; + previously_active_directions |= bluetooth::le_audio::types::kLeAudioDirectionSink; } if (audio_receiver_state_ >= AudioState::READY_TO_START) { - previously_active_directions |= - bluetooth::le_audio::types::kLeAudioDirectionSource; + previously_active_directions |= bluetooth::le_audio::types::kLeAudioDirectionSource; } /* We are done with reconfiguration. @@ -5754,10 +5329,18 @@ class LeAudioClientImpl : public LeAudioClient { * it is handled same as IDLE */ case GroupStreamStatus::IDLE: { - if (sw_enc_left) sw_enc_left.reset(); - if (sw_enc_right) sw_enc_right.reset(); - if (sw_dec_left) sw_dec_left.reset(); - if (sw_dec_right) sw_dec_right.reset(); + if (sw_enc_left) { + sw_enc_left.reset(); + } + if (sw_enc_right) { + sw_enc_right.reset(); + } + if (sw_dec_left) { + sw_dec_left.reset(); + } + if (sw_dec_right) { + sw_dec_right.reset(); + } CleanCachedMicrophoneData(); if (group) { @@ -5765,41 +5348,33 @@ class LeAudioClientImpl : public LeAudioClient { UpdateLocationsAndContextsAvailability(group); if (group->IsPendingConfiguration()) { SuspendedForReconfiguration(); - auto remote_direction = - kLeAudioContextAllRemoteSource.test(configuration_context_type_) - ? bluetooth::le_audio::types::kLeAudioDirectionSource - : bluetooth::le_audio::types::kLeAudioDirectionSink; + auto remote_direction = kLeAudioContextAllRemoteSource.test(configuration_context_type_) + ? bluetooth::le_audio::types::kLeAudioDirectionSource + : bluetooth::le_audio::types::kLeAudioDirectionSink; /* Reconfiguration to non requiring source scenario */ if (sink_monitor_mode_ && - (remote_direction == - bluetooth::le_audio::types::kLeAudioDirectionSink)) { - notifyAudioLocalSink( - UnicastMonitorModeStatus::STREAMING_SUSPENDED); + (remote_direction == bluetooth::le_audio::types::kLeAudioDirectionSink)) { + notifyAudioLocalSink(UnicastMonitorModeStatus::STREAMING_SUSPENDED); } - auto remote_contexts = - DirectionalRealignMetadataAudioContexts(group, remote_direction); - ApplyRemoteMetadataAudioContextPolicy(group, remote_contexts, - remote_direction); - if (GroupStream(group->group_id_, configuration_context_type_, - remote_contexts)) { + auto remote_contexts = DirectionalRealignMetadataAudioContexts(group, remote_direction); + ApplyRemoteMetadataAudioContextPolicy(group, remote_contexts, remote_direction); + if (GroupStream(group->group_id_, configuration_context_type_, remote_contexts)) { /* If configuration succeed wait for new status. */ return; } - log::info("Clear pending configuration flag for group {}", - group->group_id_); + log::info("Clear pending configuration flag for group {}", group->group_id_); group->ClearPendingConfiguration(); } else { if (sink_monitor_mode_) { - notifyAudioLocalSink( - UnicastMonitorModeStatus::STREAMING_SUSPENDED); + notifyAudioLocalSink(UnicastMonitorModeStatus::STREAMING_SUSPENDED); } if (source_monitor_mode_) { callbacks_->OnUnicastMonitorModeStatus( - bluetooth::le_audio::types::kLeAudioDirectionSource, - UnicastMonitorModeStatus::STREAMING_SUSPENDED); + bluetooth::le_audio::types::kLeAudioDirectionSource, + UnicastMonitorModeStatus::STREAMING_SUSPENDED); } } } @@ -5832,11 +5407,13 @@ class LeAudioClientImpl : public LeAudioClient { groupSetAndNotifyInactive(); } - if (audio_sender_state_ != AudioState::IDLE) + if (audio_sender_state_ != AudioState::IDLE) { audio_sender_state_ = AudioState::RELEASING; + } - if (audio_receiver_state_ != AudioState::IDLE) + if (audio_receiver_state_ != AudioState::IDLE) { audio_receiver_state_ = AudioState::RELEASING; + } break; default: @@ -5853,7 +5430,7 @@ class LeAudioClientImpl : public LeAudioClient { group->UpdateCisConfiguration(direction); } - private: +private: tGATT_IF gatt_if_; bluetooth::le_audio::LeAudioClientCallbacks* callbacks_; LeAudioDevices leAudioDevices_; @@ -5862,7 +5439,7 @@ class LeAudioClientImpl : public LeAudioClient { int active_group_id_; LeAudioContextType configuration_context_type_; static constexpr char kAllowMultipleContextsInMetadata[] = - "persist.bluetooth.leaudio.allow.multiple.contexts"; + "persist.bluetooth.leaudio.allow.multiple.contexts"; BidirectionalPair local_metadata_context_types_; uint64_t stream_setup_start_timestamp_; uint64_t stream_setup_end_timestamp_; @@ -5893,7 +5470,7 @@ class LeAudioClientImpl : public LeAudioClient { LeAudioHealthStatus* leAudioHealthStatus_ = nullptr; static constexpr char kNotifyUpperLayerAboutGroupBeingInIdleDuringCall[] = - "persist.bluetooth.leaudio.notify.idle.during.call"; + "persist.bluetooth.leaudio.notify.idle.during.call"; static constexpr uint16_t kBapMinimumAttMtu = 64; @@ -5905,17 +5482,17 @@ class LeAudioClientImpl : public LeAudioClient { * Resampling will be done inside the bt stack */ LeAudioCodecConfiguration audio_framework_source_config = { - .num_channels = 2, - .sample_rate = bluetooth::audio::le_audio::kSampleRate48000, - .bits_per_sample = bluetooth::audio::le_audio::kBitsPerSample16, - .data_interval_us = LeAudioCodecConfiguration::kInterval10000Us, + .num_channels = 2, + .sample_rate = bluetooth::audio::le_audio::kSampleRate48000, + .bits_per_sample = bluetooth::audio::le_audio::kBitsPerSample16, + .data_interval_us = LeAudioCodecConfiguration::kInterval10000Us, }; LeAudioCodecConfiguration audio_framework_sink_config = { - .num_channels = 2, - .sample_rate = bluetooth::audio::le_audio::kSampleRate16000, - .bits_per_sample = bluetooth::audio::le_audio::kBitsPerSample16, - .data_interval_us = LeAudioCodecConfiguration::kInterval10000Us, + .num_channels = 2, + .sample_rate = bluetooth::audio::le_audio::kSampleRate16000, + .bits_per_sample = bluetooth::audio::le_audio::kBitsPerSample16, + .data_interval_us = LeAudioCodecConfiguration::kInterval10000Us, }; std::unique_ptr sw_enc_left; @@ -5930,7 +5507,7 @@ class LeAudioClientImpl : public LeAudioClient { static constexpr uint64_t kAudioSuspentKeepIsoAliveTimeoutMs = 500; static constexpr uint64_t kAudioDisableTimeoutMs = 3000; static constexpr char kAudioSuspentKeepIsoAliveTimeoutMsProp[] = - "persist.bluetooth.leaudio.audio.suspend.timeoutms"; + "persist.bluetooth.leaudio.audio.suspend.timeoutms"; alarm_t* close_vbc_timeout_; alarm_t* suspend_timeout_; alarm_t* disable_timer_; @@ -5952,10 +5529,8 @@ class LeAudioClientImpl : public LeAudioClient { log::info("ClientAudioInterfaceRelease - cleanup"); } - auto result = - CodecManager::GetInstance()->UpdateActiveUnicastAudioHalClient( - le_audio_source_hal_client_.get(), le_audio_sink_hal_client_.get(), - false); + auto result = CodecManager::GetInstance()->UpdateActiveUnicastAudioHalClient( + le_audio_source_hal_client_.get(), le_audio_sink_hal_client_.get(), false); log::assert_that(result, "Could not update session to codec manager"); if (le_audio_source_hal_client_) { @@ -5978,8 +5553,7 @@ class LeAudioClientImpl : public LeAudioClient { local_metadata_context_types_.source.clear(); configuration_context_type_ = LeAudioContextType::UNINITIALIZED; - bluetooth::le_audio::MetricsCollector::Get()->OnStreamEnded( - active_group_id_); + bluetooth::le_audio::MetricsCollector::Get()->OnStreamEnded(active_group_id_); } bool DsaDataConsume(bluetooth::hci::iso_manager::cis_data_evt* event) { @@ -5996,8 +5570,7 @@ class LeAudioClientImpl : public LeAudioClient { } if (group->dsa_.mode != DsaMode::ISO_SW) { - log::warn("ISO packets received over HCI in DSA mode: {}", - group->dsa_.mode); + log::warn("ISO packets received over HCI in DSA mode: {}", group->dsa_.mode); return false; } @@ -6025,8 +5598,7 @@ class LeAudioClientImpl : public LeAudioClient { return false; } - bool consumed = iso_data_callback(leAudioDevice->address_, cis_conn_hdl, - data, size, timestamp); + bool consumed = iso_data_callback(leAudioDevice->address_, cis_conn_hdl, data, size, timestamp); if (consumed) { return true; } else { @@ -6044,27 +5616,22 @@ class LeAudioClientImpl : public LeAudioClient { for (auto tmpDevice = leAudioDevice; tmpDevice != nullptr; tmpDevice = group->GetNextDevice(tmpDevice)) { - log::info( - "tmpDevice->acl_asymmetric_: {}, asymmetric: {}, address: {}, " - "acl_connected: {}", - tmpDevice->acl_asymmetric_ == asymmetric, asymmetric, - tmpDevice->address_, - BTM_IsAclConnectionUp(tmpDevice->address_, BT_TRANSPORT_LE)); + log::info("tmpDevice->acl_asymmetric_: {}, asymmetric: {}, address: {}, acl_connected: {}", + tmpDevice->acl_asymmetric_ == asymmetric, asymmetric, tmpDevice->address_, + BTM_IsAclConnectionUp(tmpDevice->address_, BT_TRANSPORT_LE)); if (tmpDevice->acl_asymmetric_ == asymmetric || - !BTM_IsAclConnectionUp(tmpDevice->address_, BT_TRANSPORT_LE)) + !BTM_IsAclConnectionUp(tmpDevice->address_, BT_TRANSPORT_LE)) { continue; + } - log::info("SetAsymmetricBlePhy: {} for {}", asymmetric, - tmpDevice->address_); - BTM_BleSetPhy(tmpDevice->address_, PHY_LE_2M, - asymmetric ? PHY_LE_1M : PHY_LE_2M, 0); + log::info("SetAsymmetricBlePhy: {} for {}", asymmetric, tmpDevice->address_); + BTM_BleSetPhy(tmpDevice->address_, PHY_LE_2M, asymmetric ? PHY_LE_1M : PHY_LE_2M, 0); tmpDevice->acl_asymmetric_ = asymmetric; } } }; -static void le_audio_health_status_callback(const RawAddress& addr, - int group_id, +static void le_audio_health_status_callback(const RawAddress& addr, int group_id, LeAudioHealthBasedAction action) { if (instance) { instance->LeAudioHealthSendRecommendation(addr, group_id, action); @@ -6075,7 +5642,9 @@ static void le_audio_health_status_callback(const RawAddress& addr, * application events. */ void le_audio_gattc_callback(tBTA_GATTC_EVT event, tBTA_GATTC* p_data) { - if (!p_data || !instance) return; + if (!p_data || !instance) { + return; + } log::info("event = {}", static_cast(event)); @@ -6084,19 +5653,19 @@ void le_audio_gattc_callback(tBTA_GATTC_EVT event, tBTA_GATTC* p_data) { break; case BTA_GATTC_NOTIF_EVT: - instance->LeAudioCharValueHandle( - p_data->notify.conn_id, p_data->notify.handle, p_data->notify.len, - static_cast(p_data->notify.value), true); + instance->LeAudioCharValueHandle(p_data->notify.conn_id, p_data->notify.handle, + p_data->notify.len, + static_cast(p_data->notify.value), true); - if (!p_data->notify.is_notify) + if (!p_data->notify.is_notify) { BTA_GATTC_SendIndConfirm(p_data->notify.conn_id, p_data->notify.handle); + } break; case BTA_GATTC_OPEN_EVT: - instance->OnGattConnected(p_data->open.status, p_data->open.conn_id, - p_data->open.client_if, p_data->open.remote_bda, - p_data->open.transport, p_data->open.mtu); + instance->OnGattConnected(p_data->open.status, p_data->open.conn_id, p_data->open.client_if, + p_data->open.remote_bda, p_data->open.transport, p_data->open.mtu); break; case BTA_GATTC_ENC_CMPL_CB_EVT: { @@ -6106,19 +5675,16 @@ void le_audio_gattc_callback(tBTA_GATTC_EVT event, tBTA_GATTC* p_data) { } else { encryption_status = BTM_FAILED_ON_SECURITY; } - instance->OnEncryptionComplete(p_data->enc_cmpl.remote_bda, - encryption_status); + instance->OnEncryptionComplete(p_data->enc_cmpl.remote_bda, encryption_status); } break; case BTA_GATTC_CLOSE_EVT: - instance->OnGattDisconnected( - p_data->close.conn_id, p_data->close.client_if, - p_data->close.remote_bda, p_data->close.reason); + instance->OnGattDisconnected(p_data->close.conn_id, p_data->close.client_if, + p_data->close.remote_bda, p_data->close.reason); break; case BTA_GATTC_SEARCH_CMPL_EVT: - instance->OnServiceSearchComplete(p_data->search_cmpl.conn_id, - p_data->search_cmpl.status); + instance->OnServiceSearchComplete(p_data->search_cmpl.conn_id, p_data->search_cmpl.status); break; case BTA_GATTC_SRVC_DISC_DONE_EVT: @@ -6132,9 +5698,8 @@ void le_audio_gattc_callback(tBTA_GATTC_EVT event, tBTA_GATTC* p_data) { instance->OnMtuChanged(p_data->cfg_mtu.conn_id, p_data->cfg_mtu.mtu); break; case BTA_GATTC_PHY_UPDATE_EVT: - instance->OnPhyUpdate( - p_data->phy_update.conn_id, p_data->phy_update.tx_phy, - p_data->phy_update.rx_phy, p_data->phy_update.status); + instance->OnPhyUpdate(p_data->phy_update.conn_id, p_data->phy_update.tx_phy, + p_data->phy_update.rx_phy, p_data->phy_update.status); break; default: break; @@ -6142,90 +5707,112 @@ void le_audio_gattc_callback(tBTA_GATTC_EVT event, tBTA_GATTC* p_data) { } class LeAudioStateMachineHciCallbacksImpl : public CigCallbacks { - public: +public: void OnCigEvent(uint8_t event, void* data) override { - if (instance) instance->IsoCigEventsCb(event, data); + if (instance) { + instance->IsoCigEventsCb(event, data); + } } void OnCisEvent(uint8_t event, void* data) override { - if (instance) instance->IsoCisEventsCb(event, data); + if (instance) { + instance->IsoCisEventsCb(event, data); + } } - void OnSetupIsoDataPath(uint8_t status, uint16_t conn_handle, - uint8_t cig_id) override { - if (instance) instance->IsoSetupIsoDataPathCb(status, conn_handle, cig_id); + void OnSetupIsoDataPath(uint8_t status, uint16_t conn_handle, uint8_t cig_id) override { + if (instance) { + instance->IsoSetupIsoDataPathCb(status, conn_handle, cig_id); + } } - void OnRemoveIsoDataPath(uint8_t status, uint16_t conn_handle, - uint8_t cig_id) override { - if (instance) instance->IsoRemoveIsoDataPathCb(status, conn_handle, cig_id); + void OnRemoveIsoDataPath(uint8_t status, uint16_t conn_handle, uint8_t cig_id) override { + if (instance) { + instance->IsoRemoveIsoDataPathCb(status, conn_handle, cig_id); + } } - void OnIsoLinkQualityRead( - uint8_t conn_handle, uint8_t cig_id, uint32_t txUnackedPackets, - uint32_t txFlushedPackets, uint32_t txLastSubeventPackets, - uint32_t retransmittedPackets, uint32_t crcErrorPackets, - uint32_t rxUnreceivedPackets, uint32_t duplicatePackets) { - if (instance) - instance->IsoLinkQualityReadCb(conn_handle, cig_id, txUnackedPackets, - txFlushedPackets, txLastSubeventPackets, - retransmittedPackets, crcErrorPackets, + void OnIsoLinkQualityRead(uint8_t conn_handle, uint8_t cig_id, uint32_t txUnackedPackets, + uint32_t txFlushedPackets, uint32_t txLastSubeventPackets, + uint32_t retransmittedPackets, uint32_t crcErrorPackets, + uint32_t rxUnreceivedPackets, uint32_t duplicatePackets) { + if (instance) { + instance->IsoLinkQualityReadCb(conn_handle, cig_id, txUnackedPackets, txFlushedPackets, + txLastSubeventPackets, retransmittedPackets, crcErrorPackets, rxUnreceivedPackets, duplicatePackets); + } } }; LeAudioStateMachineHciCallbacksImpl stateMachineHciCallbacksImpl; class CallbacksImpl : public LeAudioGroupStateMachine::Callbacks { - public: +public: void StatusReportCb(int group_id, GroupStreamStatus status) override { - if (instance) instance->OnStateMachineStatusReportCb(group_id, status); + if (instance) { + instance->OnStateMachineStatusReportCb(group_id, status); + } } void OnStateTransitionTimeout(int group_id) override { - if (instance) instance->OnLeAudioDeviceSetStateTimeout(group_id); + if (instance) { + instance->OnLeAudioDeviceSetStateTimeout(group_id); + } } void OnUpdatedCisConfiguration(int group_id, uint8_t direction) { - if (instance) instance->OnUpdatedCisConfiguration(group_id, direction); + if (instance) { + instance->OnUpdatedCisConfiguration(group_id, direction); + } } }; CallbacksImpl stateMachineCallbacksImpl; class SourceCallbacksImpl : public LeAudioSourceAudioHalClient::Callbacks { - public: +public: void OnAudioDataReady(const std::vector& data) override { - if (instance) instance->OnAudioDataReady(data); + if (instance) { + instance->OnAudioDataReady(data); + } } void OnAudioSuspend(void) override { - if (instance) instance->OnLocalAudioSourceSuspend(); + if (instance) { + instance->OnLocalAudioSourceSuspend(); + } } void OnAudioResume(void) override { - if (instance) instance->OnLocalAudioSourceResume(); + if (instance) { + instance->OnLocalAudioSourceResume(); + } } - void OnAudioMetadataUpdate( - std::vector source_metadata, - DsaMode dsa_mode) override { - if (instance) + void OnAudioMetadataUpdate(std::vector source_metadata, + DsaMode dsa_mode) override { + if (instance) { instance->OnLocalAudioSourceMetadataUpdate(source_metadata, dsa_mode); + } } }; class SinkCallbacksImpl : public LeAudioSinkAudioHalClient::Callbacks { - public: +public: void OnAudioSuspend(void) override { - if (instance) instance->OnLocalAudioSinkSuspend(); + if (instance) { + instance->OnLocalAudioSinkSuspend(); + } } void OnAudioResume(void) override { - if (instance) instance->OnLocalAudioSinkResume(); + if (instance) { + instance->OnLocalAudioSinkResume(); + } } - void OnAudioMetadataUpdate( - std::vector sink_metadata) override { - if (instance) instance->OnLocalAudioSinkMetadataUpdate(sink_metadata); + void OnAudioMetadataUpdate(std::vector sink_metadata) override { + if (instance) { + instance->OnLocalAudioSinkMetadataUpdate(sink_metadata); + } } }; @@ -6233,22 +5820,24 @@ SourceCallbacksImpl audioSinkReceiverImpl; SinkCallbacksImpl audioSourceReceiverImpl; class DeviceGroupsCallbacksImpl : public DeviceGroupsCallbacks { - public: - void OnGroupAdded(const RawAddress& address, const bluetooth::Uuid& uuid, - int group_id) override { - if (instance) instance->OnGroupAddedCb(address, uuid, group_id); +public: + void OnGroupAdded(const RawAddress& address, const bluetooth::Uuid& uuid, int group_id) override { + if (instance) { + instance->OnGroupAddedCb(address, uuid, group_id); + } } void OnGroupMemberAdded(const RawAddress& address, int group_id) override { - if (instance) instance->OnGroupMemberAddedCb(address, group_id); + if (instance) { + instance->OnGroupMemberAddedCb(address, group_id); + } } void OnGroupMemberRemoved(const RawAddress& address, int group_id) override { - if (instance) instance->OnGroupMemberRemovedCb(address, group_id); - } - void OnGroupRemoved(const bluetooth::Uuid& uuid, int group_id) { - /* to implement if needed */ + if (instance) { + instance->OnGroupMemberRemovedCb(address, group_id); + } } - void OnGroupAddFromStorage(const RawAddress& address, - const bluetooth::Uuid& uuid, int group_id) { + void OnGroupRemoved(const bluetooth::Uuid& uuid, int group_id) { /* to implement if needed */ } + void OnGroupAddFromStorage(const RawAddress& address, const bluetooth::Uuid& uuid, int group_id) { /* to implement if needed */ } }; @@ -6258,25 +5847,25 @@ DeviceGroupsCallbacksImpl deviceGroupsCallbacksImpl; } // namespace -void LeAudioClient::AddFromStorage( - const RawAddress& addr, bool autoconnect, int sink_audio_location, - int source_audio_location, int sink_supported_context_types, - int source_supported_context_types, const std::vector& handles, - const std::vector& sink_pacs, - const std::vector& source_pacs, const std::vector& ases) { +void LeAudioClient::AddFromStorage(const RawAddress& addr, bool autoconnect, + int sink_audio_location, int source_audio_location, + int sink_supported_context_types, + int source_supported_context_types, + const std::vector& handles, + const std::vector& sink_pacs, + const std::vector& source_pacs, + const std::vector& ases) { if (!instance) { log::error("Not initialized yet"); return; } - instance->AddFromStorage(addr, autoconnect, sink_audio_location, - source_audio_location, sink_supported_context_types, - source_supported_context_types, handles, sink_pacs, - source_pacs, ases); + instance->AddFromStorage(addr, autoconnect, sink_audio_location, source_audio_location, + sink_supported_context_types, source_supported_context_types, handles, + sink_pacs, source_pacs, ases); } -bool LeAudioClient::GetHandlesForStorage(const RawAddress& addr, - std::vector& out) { +bool LeAudioClient::GetHandlesForStorage(const RawAddress& addr, std::vector& out) { if (!instance) { log::error("Not initialized yet"); return false; @@ -6285,8 +5874,7 @@ bool LeAudioClient::GetHandlesForStorage(const RawAddress& addr, return instance->GetHandlesForStorage(addr, out); } -bool LeAudioClient::GetSinkPacsForStorage(const RawAddress& addr, - std::vector& out) { +bool LeAudioClient::GetSinkPacsForStorage(const RawAddress& addr, std::vector& out) { if (!instance) { log::error("Not initialized yet"); return false; @@ -6295,8 +5883,7 @@ bool LeAudioClient::GetSinkPacsForStorage(const RawAddress& addr, return instance->GetSinkPacsForStorage(addr, out); } -bool LeAudioClient::GetSourcePacsForStorage(const RawAddress& addr, - std::vector& out) { +bool LeAudioClient::GetSourcePacsForStorage(const RawAddress& addr, std::vector& out) { if (!instance) { log::error("Not initialized yet"); return false; @@ -6305,8 +5892,7 @@ bool LeAudioClient::GetSourcePacsForStorage(const RawAddress& addr, return instance->GetSourcePacsForStorage(addr, out); } -bool LeAudioClient::GetAsesForStorage(const RawAddress& addr, - std::vector& out) { +bool LeAudioClient::GetAsesForStorage(const RawAddress& addr, std::vector& out) { if (!instance) { log::error("Not initialized yet"); return false; @@ -6331,29 +5917,24 @@ LeAudioClient* LeAudioClient::Get() { /* Initializer of main le audio implementation class and its instance */ void LeAudioClient::Initialize( - bluetooth::le_audio::LeAudioClientCallbacks* callbacks_, - base::Closure initCb, base::Callback hal_2_1_verifier, - const std::vector& - offloading_preference) { + bluetooth::le_audio::LeAudioClientCallbacks* callbacks_, base::Closure initCb, + base::Callback hal_2_1_verifier, + const std::vector& offloading_preference) { std::scoped_lock lock(instance_mutex); if (instance) { log::error("Already initialized"); return; } - if (!bluetooth::shim::GetController() - ->SupportsBleConnectedIsochronousStreamCentral() && - !bluetooth::shim::GetController() - ->SupportsBleConnectedIsochronousStreamPeripheral()) { - log::error( - "Controller reports no ISO support. LeAudioClient Init aborted."); + if (!bluetooth::shim::GetController()->SupportsBleConnectedIsochronousStreamCentral() && + !bluetooth::shim::GetController()->SupportsBleConnectedIsochronousStreamPeripheral()) { + log::error("Controller reports no ISO support. LeAudioClient Init aborted."); return; } - log::assert_that( - std::move(hal_2_1_verifier).Run(), - "LE Audio Client requires Bluetooth Audio HAL V2.1 at least. Either " - "disable LE Audio Profile, or update your HAL"); + log::assert_that(std::move(hal_2_1_verifier).Run(), + "LE Audio Client requires Bluetooth Audio HAL V2.1 at least. Either " + "disable LE Audio Profile, or update your HAL"); IsoManager::GetInstance()->Start(); @@ -6380,10 +5961,11 @@ void LeAudioClient::DebugDump(int fd) { DeviceGroups::DebugDump(fd); dprintf(fd, "LeAudio Manager: \n"); - if (instance) + if (instance) { instance->Dump(fd); - else + } else { dprintf(fd, " Not initialized \n"); + } LeAudioSinkAudioHalClient::DebugDump(fd); LeAudioSourceAudioHalClient::DebugDump(fd); @@ -6410,8 +5992,9 @@ void LeAudioClient::Cleanup(void) { ContentControlIdKeeper::GetInstance()->Stop(); LeAudioGroupStateMachine::Cleanup(); - if (!LeAudioBroadcaster::IsLeAudioBroadcasterRunning()) + if (!LeAudioBroadcaster::IsLeAudioBroadcasterRunning()) { IsoManager::GetInstance()->Stop(); + } bluetooth::le_audio::MetricsCollector::Get()->Flush(); } diff --git a/system/bta/le_audio/client_linux.cc b/system/bta/le_audio/client_linux.cc index 946deeda15c..ff56a555b80 100644 --- a/system/bta/le_audio/client_linux.cc +++ b/system/bta/le_audio/client_linux.cc @@ -19,7 +19,7 @@ #include "bta_le_audio_api.h" class LeAudioClientImpl : public LeAudioClient { - public: +public: LeAudioClientImpl(void) = default; ~LeAudioClientImpl(void) override = default; @@ -34,48 +34,38 @@ class LeAudioClientImpl : public LeAudioClient { void GroupDestroy(const int group_id) override {} void GroupSetActive(const int group_id) override {} void SetCodecConfigPreference( - int group_id, - bluetooth::le_audio::btle_audio_codec_config_t input_codec_config, - bluetooth::le_audio::btle_audio_codec_config_t output_codec_config) - override {} + int group_id, bluetooth::le_audio::btle_audio_codec_config_t input_codec_config, + bluetooth::le_audio::btle_audio_codec_config_t output_codec_config) override {} void SetCcidInformation(int ccid, int context_type) override {} void SetInCall(bool in_call) override {} - std::vector GetGroupDevices(const int group_id) override { - return {}; - } + std::vector GetGroupDevices(const int group_id) override { return {}; } }; void LeAudioClient::Initialize( - bluetooth::le_audio::LeAudioClientCallbacks* callbacks, - base::Closure initCb, base::Callback hal_2_1_verifier, - const std::vector& - offloading_preference) {} + bluetooth::le_audio::LeAudioClientCallbacks* callbacks, base::Closure initCb, + base::Callback hal_2_1_verifier, + const std::vector& offloading_preference) {} void LeAudioClient::Cleanup(void) {} LeAudioClient* LeAudioClient::Get(void) { return nullptr; } void LeAudioClient::DebugDump(int fd) {} void LeAudioClient::AddFromStorage(const RawAddress& addr, bool autoconnect, - int sink_audio_location, - int source_audio_location, + int sink_audio_location, int source_audio_location, int sink_supported_context_types, int source_supported_context_types, const std::vector& handles, const std::vector& sink_pacs, const std::vector& source_pacs, const std::vector& ases) {} -bool LeAudioClient::GetHandlesForStorage(const RawAddress& addr, - std::vector& out) { +bool LeAudioClient::GetHandlesForStorage(const RawAddress& addr, std::vector& out) { return false; } -bool LeAudioClient::GetSinkPacsForStorage(const RawAddress& addr, - std::vector& out) { +bool LeAudioClient::GetSinkPacsForStorage(const RawAddress& addr, std::vector& out) { return false; } -bool LeAudioClient::GetSourcePacsForStorage(const RawAddress& addr, - std::vector& out) { +bool LeAudioClient::GetSourcePacsForStorage(const RawAddress& addr, std::vector& out) { return false; } -bool LeAudioClient::GetAsesForStorage(const RawAddress& addr, - std::vector& out) { +bool LeAudioClient::GetAsesForStorage(const RawAddress& addr, std::vector& out) { return false; } bool LeAudioClient::IsLeAudioClientRunning() { return false; } diff --git a/system/bta/le_audio/client_parser.cc b/system/bta/le_audio/client_parser.cc index 05fbbc105aa..f3b3b669252 100644 --- a/system/bta/le_audio/client_parser.cc +++ b/system/bta/le_audio/client_parser.cc @@ -42,90 +42,84 @@ namespace bluetooth::le_audio { namespace client_parser { namespace ascs { static std::map ase_state_map_string = { - {kAseStateIdle, "Idle"}, - {kAseStateCodecConfigured, "Codec Configured"}, - {kAseStateQosConfigured, "QoS Configured"}, - {kAseStateEnabling, "Enabling"}, - {kAseStateStreaming, "Streaming"}, - {kAseStateDisabling, "Disabling"}, - {kAseStateReleasing, "Releasing"}, + {kAseStateIdle, "Idle"}, + {kAseStateCodecConfigured, "Codec Configured"}, + {kAseStateQosConfigured, "QoS Configured"}, + {kAseStateEnabling, "Enabling"}, + {kAseStateStreaming, "Streaming"}, + {kAseStateDisabling, "Disabling"}, + {kAseStateReleasing, "Releasing"}, }; static std::map ctp_opcode_map_string = { - {kCtpOpcodeCodecConfiguration, "Config Codec"}, - {kCtpOpcodeQosConfiguration, "Config QoS"}, - {kCtpOpcodeEnable, "Enable"}, - {kCtpOpcodeReceiverStartReady, "Receiver Start Ready"}, - {kCtpOpcodeDisable, "Disable"}, - {kCtpOpcodeReceiverStopReady, "Receiver Stop Ready"}, - {kCtpOpcodeUpdateMetadata, "Update Metadata"}, - {kCtpOpcodeRelease, "Release"}, + {kCtpOpcodeCodecConfiguration, "Config Codec"}, + {kCtpOpcodeQosConfiguration, "Config QoS"}, + {kCtpOpcodeEnable, "Enable"}, + {kCtpOpcodeReceiverStartReady, "Receiver Start Ready"}, + {kCtpOpcodeDisable, "Disable"}, + {kCtpOpcodeReceiverStopReady, "Receiver Stop Ready"}, + {kCtpOpcodeUpdateMetadata, "Update Metadata"}, + {kCtpOpcodeRelease, "Release"}, }; static std::map ctp_configuration_reason_map_string = { - {kCtpResponseNoReason, ""}, - {kCtpResponseCodecId, "Codec ID"}, - {kCtpResponseCodecSpecificConfiguration, "Codec specific configuration"}, - {kCtpResponseSduInterval, "SDU interval"}, - {kCtpResponseFraming, "Framing"}, - {kCtpResponsePhy, "PHY"}, - {kCtpResponseMaximumSduSize, "Maximum SDU size"}, - {kCtpResponseRetransmissionNumber, "Retransmission number"}, - {kCtpResponseMaxTransportLatency, "Max Transport latency"}, - {kCtpResponsePresentationDelay, "Presentation delay"}, - {kCtpResponseInvalidAseCisMapping, "Invalid ASE CIS mapping"}, + {kCtpResponseNoReason, ""}, + {kCtpResponseCodecId, "Codec ID"}, + {kCtpResponseCodecSpecificConfiguration, "Codec specific configuration"}, + {kCtpResponseSduInterval, "SDU interval"}, + {kCtpResponseFraming, "Framing"}, + {kCtpResponsePhy, "PHY"}, + {kCtpResponseMaximumSduSize, "Maximum SDU size"}, + {kCtpResponseRetransmissionNumber, "Retransmission number"}, + {kCtpResponseMaxTransportLatency, "Max Transport latency"}, + {kCtpResponsePresentationDelay, "Presentation delay"}, + {kCtpResponseInvalidAseCisMapping, "Invalid ASE CIS mapping"}, }; static std::map ctp_response_code_map_string = { - {kCtpResponseCodeSuccess, "Success"}, - {kCtpResponseCodeUnsupportedOpcode, "Unsupported Opcode"}, - {kCtpResponseCodeInvalidLength, "Invalid Length"}, - {kCtpResponseCodeInvalidAseId, "Invalid ASE ID"}, - {kCtpResponseCodeInvalidAseStateMachineTransition, - "Invalid ASE State Machine Transition"}, - {kCtpResponseCodeInvalidAseDirection, "Invalid ASE Direction"}, - {kCtpResponseCodeUnsupportedAudioCapabilities, - "Unsupported Audio Capabilities"}, - {kCtpResponseCodeUnsupportedConfigurationParameterValue, - "Unsupported Configuration Parameter Value"}, - {kCtpResponseCodeRejectedConfigurationParameterValue, - "Rejected Configuration Parameter Value"}, - {kCtpResponseCodeInvalidConfigurationParameterValue, - "Invalid Configuration Parameter Value"}, - {kCtpResponseCodeUnsupportedMetadata, "Unsupported Metadata"}, - {kCtpResponseCodeRejectedMetadata, "Rejected Metadata"}, - {kCtpResponseCodeInvalidMetadata, "Invalid Metadata"}, - {kCtpResponseCodeInsufficientResources, "Insufficient Resources"}, - {kCtpResponseCodeUnspecifiedError, "Unspecified Error"}, + {kCtpResponseCodeSuccess, "Success"}, + {kCtpResponseCodeUnsupportedOpcode, "Unsupported Opcode"}, + {kCtpResponseCodeInvalidLength, "Invalid Length"}, + {kCtpResponseCodeInvalidAseId, "Invalid ASE ID"}, + {kCtpResponseCodeInvalidAseStateMachineTransition, "Invalid ASE State Machine Transition"}, + {kCtpResponseCodeInvalidAseDirection, "Invalid ASE Direction"}, + {kCtpResponseCodeUnsupportedAudioCapabilities, "Unsupported Audio Capabilities"}, + {kCtpResponseCodeUnsupportedConfigurationParameterValue, + "Unsupported Configuration Parameter Value"}, + {kCtpResponseCodeRejectedConfigurationParameterValue, + "Rejected Configuration Parameter Value"}, + {kCtpResponseCodeInvalidConfigurationParameterValue, + "Invalid Configuration Parameter Value"}, + {kCtpResponseCodeUnsupportedMetadata, "Unsupported Metadata"}, + {kCtpResponseCodeRejectedMetadata, "Rejected Metadata"}, + {kCtpResponseCodeInvalidMetadata, "Invalid Metadata"}, + {kCtpResponseCodeInsufficientResources, "Insufficient Resources"}, + {kCtpResponseCodeUnspecifiedError, "Unspecified Error"}, }; static std::map ctp_metadata_reason_map_string = { - {kCtpMetadataResponsePreferredAudioContexts, "Preferred Audio Contexts"}, - {kCtpMetadataResponseStreamingAudioContexts, "Streaming Audio Contexts"}, - {kCtpMetadataResponseProgramInfo, "Program Info"}, - {kCtpMetadataResponseLanguage, "Language"}, - {kCtpMetadataResponseCcidList, "CCID List"}, - {kCtpMetadataResponseParentalRating, "Parental Rating"}, - {kCtpMetadataResponseProgramInfoUri, "Program Info URI"}, - {kCtpMetadataResponseExtendedMetadata, "Extended Metadata"}, - {kCtpMetadataResponseVendorSpecific, "Vendor Specific"}, + {kCtpMetadataResponsePreferredAudioContexts, "Preferred Audio Contexts"}, + {kCtpMetadataResponseStreamingAudioContexts, "Streaming Audio Contexts"}, + {kCtpMetadataResponseProgramInfo, "Program Info"}, + {kCtpMetadataResponseLanguage, "Language"}, + {kCtpMetadataResponseCcidList, "CCID List"}, + {kCtpMetadataResponseParentalRating, "Parental Rating"}, + {kCtpMetadataResponseProgramInfoUri, "Program Info URI"}, + {kCtpMetadataResponseExtendedMetadata, "Extended Metadata"}, + {kCtpMetadataResponseVendorSpecific, "Vendor Specific"}, }; -static std::map*> - ctp_response_code_map = { +static std::map*> ctp_response_code_map = { {kCtpResponseCodeUnsupportedConfigurationParameterValue, &ctp_configuration_reason_map_string}, - {kCtpResponseCodeRejectedConfigurationParameterValue, - &ctp_configuration_reason_map_string}, - {kCtpResponseCodeInvalidConfigurationParameterValue, - &ctp_configuration_reason_map_string}, + {kCtpResponseCodeRejectedConfigurationParameterValue, &ctp_configuration_reason_map_string}, + {kCtpResponseCodeInvalidConfigurationParameterValue, &ctp_configuration_reason_map_string}, {kCtpResponseCodeUnsupportedMetadata, &ctp_metadata_reason_map_string}, {kCtpResponseCodeRejectedMetadata, &ctp_metadata_reason_map_string}, {kCtpResponseCodeInvalidMetadata, &ctp_metadata_reason_map_string}, }; -bool ParseAseStatusHeader(ase_rsp_hdr& arh, uint16_t len, - const uint8_t* value) { +bool ParseAseStatusHeader(ase_rsp_hdr& arh, uint16_t len, const uint8_t* value) { if (len < kAseRspHdrMinLen) { log::error("wrong len of ASE char (header): {}", static_cast(len)); @@ -141,9 +135,8 @@ bool ParseAseStatusHeader(ase_rsp_hdr& arh, uint16_t len, return true; } -bool ParseAseStatusCodecConfiguredStateParams( - struct ase_codec_configured_state_params& rsp, uint16_t len, - const uint8_t* value) { +bool ParseAseStatusCodecConfiguredStateParams(struct ase_codec_configured_state_params& rsp, + uint16_t len, const uint8_t* value) { uint8_t codec_spec_conf_len; if (len < kAseStatusCodecConfMinLen) { @@ -170,31 +163,29 @@ bool ParseAseStatusCodecConfiguredStateParams( log::error("Wrong len of codec conf status (Codec spec conf)"); return false; } - if (codec_spec_conf_len) - rsp.codec_spec_conf = - std::vector(value, value + codec_spec_conf_len); + if (codec_spec_conf_len) { + rsp.codec_spec_conf = std::vector(value, value + codec_spec_conf_len); + } log::info( - "Codec configuration\n\tFraming: 0x{:x}\n\tPreferred PHY: " - "0x{:x}\n\tPreferred retransmission number: 0x{:x}\n\tMax transport " - "latency: 0x{:x}\n\tPresence delay min: 0x{:x}\n\tPresence delay max: " - "0x{:x}\n\tPreferredPresentationDelayMin: " - "0x{:x}\n\tPreferredPresentationDelayMax: 0x{:x}\n\tCoding format: " - "0x{:x}\n\tVendor codec company ID: 0x{:x}\n\tVendor codec ID: " - "0x{:x}\n\tCodec specific conf len: {}\n\tCodec specific conf: {}", - rsp.framing, rsp.preferred_phy, rsp.preferred_retrans_nb, - rsp.max_transport_latency, rsp.pres_delay_min, rsp.pres_delay_max, - rsp.preferred_pres_delay_min, rsp.preferred_pres_delay_max, - rsp.codec_id.coding_format, rsp.codec_id.vendor_company_id, - rsp.codec_id.vendor_codec_id, (int)codec_spec_conf_len, - base::HexEncode(rsp.codec_spec_conf.data(), rsp.codec_spec_conf.size())); + "Codec configuration\n\tFraming: 0x{:x}\n\tPreferred PHY: " + "0x{:x}\n\tPreferred retransmission number: 0x{:x}\n\tMax transport " + "latency: 0x{:x}\n\tPresence delay min: 0x{:x}\n\tPresence delay max: " + "0x{:x}\n\tPreferredPresentationDelayMin: " + "0x{:x}\n\tPreferredPresentationDelayMax: 0x{:x}\n\tCoding format: " + "0x{:x}\n\tVendor codec company ID: 0x{:x}\n\tVendor codec ID: " + "0x{:x}\n\tCodec specific conf len: {}\n\tCodec specific conf: {}", + rsp.framing, rsp.preferred_phy, rsp.preferred_retrans_nb, rsp.max_transport_latency, + rsp.pres_delay_min, rsp.pres_delay_max, rsp.preferred_pres_delay_min, + rsp.preferred_pres_delay_max, rsp.codec_id.coding_format, rsp.codec_id.vendor_company_id, + rsp.codec_id.vendor_codec_id, (int)codec_spec_conf_len, + base::HexEncode(rsp.codec_spec_conf.data(), rsp.codec_spec_conf.size())); return true; } -bool ParseAseStatusQosConfiguredStateParams( - struct ase_qos_configured_state_params& rsp, uint16_t len, - const uint8_t* value) { +bool ParseAseStatusQosConfiguredStateParams(struct ase_qos_configured_state_params& rsp, + uint16_t len, const uint8_t* value) { if (len != kAseStatusCodecQosConfMinLen) { log::error("Wrong len of ASE characteristic (QOS conf header)"); return false; @@ -211,18 +202,18 @@ bool ParseAseStatusQosConfiguredStateParams( STREAM_TO_UINT24(rsp.pres_delay, value); log::info( - "Codec QoS Configured\n\tCIG: 0x{:x}\n\tCIS: 0x{:x}\n\tSDU interval: " - "0x{:x}\n\tFraming: 0x{:x}\n\tPHY: 0x{:x}\n\tMax SDU: " - "0x{:x}\n\tRetransmission number: 0x{:x}\n\tMax transport latency: " - "0x{:x}\n\tPresentation delay: 0x{:x}", - rsp.cig_id, rsp.cis_id, rsp.sdu_interval, rsp.framing, rsp.phy, - rsp.max_sdu, rsp.retrans_nb, rsp.max_transport_latency, rsp.pres_delay); + "Codec QoS Configured\n\tCIG: 0x{:x}\n\tCIS: 0x{:x}\n\tSDU interval: " + "0x{:x}\n\tFraming: 0x{:x}\n\tPHY: 0x{:x}\n\tMax SDU: " + "0x{:x}\n\tRetransmission number: 0x{:x}\n\tMax transport latency: " + "0x{:x}\n\tPresentation delay: 0x{:x}", + rsp.cig_id, rsp.cis_id, rsp.sdu_interval, rsp.framing, rsp.phy, rsp.max_sdu, + rsp.retrans_nb, rsp.max_transport_latency, rsp.pres_delay); return true; } -bool ParseAseStatusTransientStateParams(struct ase_transient_state_params& rsp, - uint16_t len, const uint8_t* value) { +bool ParseAseStatusTransientStateParams(struct ase_transient_state_params& rsp, uint16_t len, + const uint8_t* value) { uint8_t metadata_len; if (len < kAseStatusTransMinLen) { @@ -240,20 +231,19 @@ bool ParseAseStatusTransientStateParams(struct ase_transient_state_params& rsp, return false; } - if (metadata_len > 0) + if (metadata_len > 0) { rsp.metadata = std::vector(value, value + metadata_len); + } log::info( - "Status enabling/streaming/disabling\n\tCIG: 0x{:x}\n\tCIS: " - "0x{:x}\n\tMetadata: {}", - rsp.cig_id, rsp.cis_id, - base::HexEncode(rsp.metadata.data(), rsp.metadata.size())); + "Status enabling/streaming/disabling\n\tCIG: 0x{:x}\n\tCIS: " + "0x{:x}\n\tMetadata: {}", + rsp.cig_id, rsp.cis_id, base::HexEncode(rsp.metadata.data(), rsp.metadata.size())); return true; } -bool ParseAseCtpNotification(struct ctp_ntf& ntf, uint16_t len, - const uint8_t* value) { +bool ParseAseCtpNotification(struct ctp_ntf& ntf, uint16_t len, const uint8_t* value) { uint8_t num_entries; if (len < kCtpNtfMinLen) { @@ -279,52 +269,50 @@ bool ParseAseCtpNotification(struct ctp_ntf& ntf, uint16_t len, ntf.entries.push_back(std::move(entry)); } - log::info( - "Control point notification\n\tOpcode: {} (0x{:x})\n\tNum ASE IDs: {}", - ctp_opcode_map_string[ntf.op], ntf.op, (int)num_entries); - for (size_t i = 0; i < num_entries; i++) - log::info("\n\tASE ID[0x{:x}] response: {} (0x{:x}) reason: {} (0x{:x})", - ntf.entries[i].ase_id, - ctp_response_code_map_string[ntf.entries[i].response_code], - ntf.entries[i].response_code, - ((ctp_response_code_map.count(ntf.entries[i].response_code) != 0) - ? (*ctp_response_code_map[ntf.entries[i].response_code]) - [ntf.entries[i].reason] - : ""), - ntf.entries[i].reason); + log::info("Control point notification\n\tOpcode: {} (0x{:x})\n\tNum ASE IDs: {}", + ctp_opcode_map_string[ntf.op], ntf.op, (int)num_entries); + for (size_t i = 0; i < num_entries; i++) { + log::info( + "\n\tASE ID[0x{:x}] response: {} (0x{:x}) reason: {} (0x{:x})", ntf.entries[i].ase_id, + ctp_response_code_map_string[ntf.entries[i].response_code], + ntf.entries[i].response_code, + ((ctp_response_code_map.count(ntf.entries[i].response_code) != 0) + ? (*ctp_response_code_map[ntf.entries[i].response_code])[ntf.entries[i].reason] + : ""), + ntf.entries[i].reason); + } return true; } bool PrepareAseCtpCodecConfig(const std::vector& confs, std::vector& value) { - if (confs.size() == 0) return false; + if (confs.size() == 0) { + return false; + } std::stringstream conf_ents_str; size_t msg_len = std::accumulate( - confs.begin(), confs.end(), - confs.size() * kCtpCodecConfMinLen + kAseNumSize + kCtpOpSize, - [&conf_ents_str](size_t cur_len, auto const& conf) { - if (utils::IsCodecUsingLtvFormat(conf.codec_id)) { - types::LeAudioLtvMap ltv; - if (ltv.Parse(conf.codec_config.data(), conf.codec_config.size())) { - for (const auto& [type, value] : ltv.Values()) { - conf_ents_str - << "\ttype: " << std::to_string(type) - << "\tlen: " << std::to_string(value.size()) - << "\tdata: " << base::HexEncode(value.data(), value.size()) - << "\n"; + confs.begin(), confs.end(), confs.size() * kCtpCodecConfMinLen + kAseNumSize + kCtpOpSize, + [&conf_ents_str](size_t cur_len, auto const& conf) { + if (utils::IsCodecUsingLtvFormat(conf.codec_id)) { + types::LeAudioLtvMap ltv; + if (ltv.Parse(conf.codec_config.data(), conf.codec_config.size())) { + for (const auto& [type, value] : ltv.Values()) { + conf_ents_str << "\ttype: " << std::to_string(type) + << "\tlen: " << std::to_string(value.size()) + << "\tdata: " << base::HexEncode(value.data(), value.size()) + << "\n"; + } + return cur_len + conf.codec_config.size(); + } + log::error("Error parsing codec configuration LTV data."); } - return cur_len + conf.codec_config.size(); - } - log::error("Error parsing codec configuration LTV data."); - } - conf_ents_str << "\t" - << base::HexEncode(conf.codec_config.data(), - conf.codec_config.size()); - return cur_len + conf.codec_config.size(); - }); + conf_ents_str << "\t" + << base::HexEncode(conf.codec_config.data(), conf.codec_config.size()); + return cur_len + conf.codec_config.size(); + }); value.resize(msg_len); uint8_t* msg = value.data(); @@ -340,18 +328,16 @@ bool PrepareAseCtpCodecConfig(const std::vector& confs, UINT16_TO_STREAM(msg, conf.codec_id.vendor_codec_id); UINT8_TO_STREAM(msg, conf.codec_config.size()); - ARRAY_TO_STREAM(msg, conf.codec_config.data(), - static_cast(conf.codec_config.size())); + ARRAY_TO_STREAM(msg, conf.codec_config.data(), static_cast(conf.codec_config.size())); log::info( - "Codec configuration\n\tAse id: 0x{:x}\n\tTarget latency: " - "0x{:x}\n\tTarget PHY: 0x{:x}\n\tCoding format: 0x{:x}\n\tVendor codec " - "company ID: 0x{:x}\n\tVendor codec ID: 0x{:x}\n\tCodec config len: " - "{}\n\tCodec spec conf: \n{}", - conf.ase_id, conf.target_latency, conf.target_phy, - conf.codec_id.coding_format, conf.codec_id.vendor_company_id, - conf.codec_id.vendor_codec_id, - static_cast(conf.codec_config.size()), conf_ents_str.str()); + "Codec configuration\n\tAse id: 0x{:x}\n\tTarget latency: " + "0x{:x}\n\tTarget PHY: 0x{:x}\n\tCoding format: 0x{:x}\n\tVendor codec " + "company ID: 0x{:x}\n\tVendor codec ID: 0x{:x}\n\tCodec config len: " + "{}\n\tCodec spec conf: \n{}", + conf.ase_id, conf.target_latency, conf.target_phy, conf.codec_id.coding_format, + conf.codec_id.vendor_company_id, conf.codec_id.vendor_codec_id, + static_cast(conf.codec_config.size()), conf_ents_str.str()); } return true; @@ -359,7 +345,9 @@ bool PrepareAseCtpCodecConfig(const std::vector& confs, bool PrepareAseCtpConfigQos(const std::vector& confs, std::vector& value) { - if (confs.size() == 0) return false; + if (confs.size() == 0) { + return false; + } value.resize(confs.size() * kCtpQosConfMinLen + kAseNumSize + kCtpOpSize); uint8_t* msg = value.data(); @@ -379,21 +367,21 @@ bool PrepareAseCtpConfigQos(const std::vector& confs, UINT24_TO_STREAM(msg, conf.pres_delay); log::info( - "QoS configuration\n\tAse id: 0x{:x}\n\tcig: 0x{:x}\n\tCis: " - "0x{:x}\n\tSDU interval: 0x{:x}\n\tFraming: 0x{:x}\n\tPhy: " - "0x{:x}\n\tMax sdu size: 0x{:x}\n\tRetrans nb: 0x{:x}\n\tMax Transport " - "latency: 0x{:x}\n\tPres delay: 0x{:x}", - conf.ase_id, conf.cig, conf.cis, conf.sdu_interval, conf.framing, - conf.phy, conf.max_sdu, conf.retrans_nb, conf.max_transport_latency, - conf.pres_delay); + "QoS configuration\n\tAse id: 0x{:x}\n\tcig: 0x{:x}\n\tCis: " + "0x{:x}\n\tSDU interval: 0x{:x}\n\tFraming: 0x{:x}\n\tPhy: " + "0x{:x}\n\tMax sdu size: 0x{:x}\n\tRetrans nb: 0x{:x}\n\tMax Transport " + "latency: 0x{:x}\n\tPres delay: 0x{:x}", + conf.ase_id, conf.cig, conf.cis, conf.sdu_interval, conf.framing, conf.phy, + conf.max_sdu, conf.retrans_nb, conf.max_transport_latency, conf.pres_delay); } return true; } -bool PrepareAseCtpEnable(const std::vector& confs, - std::vector& value) { - if (confs.size() == 0) return false; +bool PrepareAseCtpEnable(const std::vector& confs, std::vector& value) { + if (confs.size() == 0) { + return false; + } if (confs.size() > UINT8_MAX) { log::error("To many ASEs to update metadata"); @@ -422,8 +410,7 @@ bool PrepareAseCtpEnable(const std::vector& confs, for (const struct ctp_enable& conf : confs) { UINT8_TO_STREAM(msg, conf.ase_id); UINT8_TO_STREAM(msg, conf.metadata.size()); - ARRAY_TO_STREAM(msg, conf.metadata.data(), - static_cast(conf.metadata.size())); + ARRAY_TO_STREAM(msg, conf.metadata.data(), static_cast(conf.metadata.size())); log::info("Enable\n\tAse id: 0x{:x}\n\tMetadata: {}", conf.ase_id, base::HexEncode(conf.metadata.data(), conf.metadata.size())); @@ -434,7 +421,9 @@ bool PrepareAseCtpEnable(const std::vector& confs, bool PrepareAseCtpAudioReceiverStartReady(const std::vector& ase_ids, std::vector& value) { - if (ase_ids.size() == 0) return false; + if (ase_ids.size() == 0) { + return false; + } value.resize(ase_ids.size() * kAseIdSize + kAseNumSize + kCtpOpSize); uint8_t* msg = value.data(); @@ -450,9 +439,10 @@ bool PrepareAseCtpAudioReceiverStartReady(const std::vector& ase_ids, return true; } -bool PrepareAseCtpDisable(const std::vector& ase_ids, - std::vector& value) { - if (ase_ids.size() == 0) return false; +bool PrepareAseCtpDisable(const std::vector& ase_ids, std::vector& value) { + if (ase_ids.size() == 0) { + return false; + } value.resize(ase_ids.size() * kAseIdSize + kAseNumSize + kCtpOpSize); uint8_t* msg = value.data(); @@ -470,7 +460,9 @@ bool PrepareAseCtpDisable(const std::vector& ase_ids, bool PrepareAseCtpAudioReceiverStopReady(const std::vector& ase_ids, std::vector& value) { - if (ase_ids.size() == 0) return false; + if (ase_ids.size() == 0) { + return false; + } value.resize(ase_ids.size() * kAseIdSize + kAseNumSize + kCtpOpSize); uint8_t* msg = value.data(); @@ -486,18 +478,18 @@ bool PrepareAseCtpAudioReceiverStopReady(const std::vector& ase_ids, return true; } -bool PrepareAseCtpUpdateMetadata( - const std::vector& confs, - std::vector& value) { - if (confs.size() == 0) return false; +bool PrepareAseCtpUpdateMetadata(const std::vector& confs, + std::vector& value) { + if (confs.size() == 0) { + return false; + } if (confs.size() > UINT8_MAX) { log::error("To many ASEs to update metadata"); return false; } - uint16_t msg_len = - confs.size() * kCtpUpdateMetadataMinLen + kAseNumSize + kCtpOpSize; + uint16_t msg_len = confs.size() * kCtpUpdateMetadataMinLen + kAseNumSize + kCtpOpSize; for (auto& conf : confs) { if (msg_len > GATT_MAX_ATTR_LEN) { log::error("Message length above GATT maximum"); @@ -519,8 +511,7 @@ bool PrepareAseCtpUpdateMetadata( for (const struct ctp_update_metadata& conf : confs) { UINT8_TO_STREAM(msg, conf.ase_id); UINT8_TO_STREAM(msg, conf.metadata.size()); - ARRAY_TO_STREAM(msg, conf.metadata.data(), - static_cast(conf.metadata.size())); + ARRAY_TO_STREAM(msg, conf.metadata.data(), static_cast(conf.metadata.size())); log::info("Update Metadata\n\tAse id: 0x{:x}\n\tMetadata: {}", conf.ase_id, base::HexEncode(conf.metadata.data(), conf.metadata.size())); @@ -529,9 +520,10 @@ bool PrepareAseCtpUpdateMetadata( return true; } -bool PrepareAseCtpRelease(const std::vector& ase_ids, - std::vector& value) { - if (ase_ids.size() == 0) return true; +bool PrepareAseCtpRelease(const std::vector& ase_ids, std::vector& value) { + if (ase_ids.size() == 0) { + return true; + } value.resize(ase_ids.size() * kAseIdSize + kAseNumSize + kCtpOpSize); uint8_t* msg = value.data(); @@ -568,8 +560,8 @@ int ParseSinglePac(std::vector& pac_recs, uint16_t len, len -= kAcsPacRecordMinLen - kAcsPacMetadataLenLen; if (len < codec_spec_cap_len + kAcsPacMetadataLenLen) { - log::error("Wrong len of PAC record (codec specific capabilities) ({}!={})", - len, codec_spec_cap_len + kAcsPacMetadataLenLen); + log::error("Wrong len of PAC record (codec specific capabilities) ({}!={})", len, + codec_spec_cap_len + kAcsPacMetadataLenLen); pac_recs.clear(); return -1; } @@ -578,9 +570,10 @@ int ParseSinglePac(std::vector& pac_recs, uint16_t len, if (utils::IsCodecUsingLtvFormat(rec.codec_id)) { bool parsed; - rec.codec_spec_caps = - types::LeAudioLtvMap::Parse(value, codec_spec_cap_len, parsed); - if (!parsed) return -1; + rec.codec_spec_caps = types::LeAudioLtvMap::Parse(value, codec_spec_cap_len, parsed); + if (!parsed) { + return -1; + } } value += codec_spec_cap_len; @@ -590,8 +583,7 @@ int ParseSinglePac(std::vector& pac_recs, uint16_t len, len -= kAcsPacMetadataLenLen; if (len < metadata_len) { - log::error("Wrong len of PAC record (metadata) ({}!={})", len, - metadata_len); + log::error("Wrong len of PAC record (metadata) ({}!={})", len, metadata_len); pac_recs.clear(); return -1; } @@ -605,11 +597,9 @@ int ParseSinglePac(std::vector& pac_recs, uint16_t len, return len; } -bool ParsePacs(std::vector& pac_recs, uint16_t len, - const uint8_t* value) { +bool ParsePacs(std::vector& pac_recs, uint16_t len, const uint8_t* value) { if (len < kAcsPacDiscoverRspMinLen) { - log::error("Wrong len of PAC characteristic ({}!={})", len, - kAcsPacDiscoverRspMinLen); + log::error("Wrong len of PAC characteristic ({}!={})", len, kAcsPacDiscoverRspMinLen); return false; } @@ -620,7 +610,9 @@ bool ParsePacs(std::vector& pac_recs, uint16_t len, pac_recs.reserve(pac_rec_nb); for (int i = 0; i < pac_rec_nb; i++) { int remaining_len = ParseSinglePac(pac_recs, len, value); - if (remaining_len < 0) return false; + if (remaining_len < 0) { + return false; + } value += (len - remaining_len); len = remaining_len; @@ -643,9 +635,8 @@ bool ParseAudioLocations(types::AudioLocations& audio_locations, uint16_t len, return true; } -bool ParseSupportedAudioContexts( - types::BidirectionalPair& contexts, uint16_t len, - const uint8_t* value) { +bool ParseSupportedAudioContexts(types::BidirectionalPair& contexts, + uint16_t len, const uint8_t* value) { if (len != kAseAudioSuppContRspMinLen) { log::error("Wrong len of Audio Supported Context characteristic"); return false; @@ -655,16 +646,15 @@ bool ParseSupportedAudioContexts( STREAM_TO_UINT16(contexts.source.value_ref(), value); log::info( - "Supported Audio Contexts: \n\tSupported Sink Contexts: {}\n\tSupported " - "Source Contexts: {}", - contexts.sink.to_string(), contexts.source.to_string()); + "Supported Audio Contexts: \n\tSupported Sink Contexts: {}\n\tSupported " + "Source Contexts: {}", + contexts.sink.to_string(), contexts.source.to_string()); return true; } -bool ParseAvailableAudioContexts( - types::BidirectionalPair& contexts, uint16_t len, - const uint8_t* value) { +bool ParseAvailableAudioContexts(types::BidirectionalPair& contexts, + uint16_t len, const uint8_t* value) { if (len != kAseAudioAvailRspMinLen) { log::error("Wrong len of Audio Availability characteristic"); return false; @@ -674,9 +664,9 @@ bool ParseAvailableAudioContexts( STREAM_TO_UINT16(contexts.source.value_ref(), value); log::info( - "Available Audio Contexts: \n\tAvailable Sink Contexts: {}\n\tAvailable " - "Source Contexts: {}", - contexts.sink.to_string(), contexts.source.to_string()); + "Available Audio Contexts: \n\tAvailable Sink Contexts: {}\n\tAvailable " + "Source Contexts: {}", + contexts.sink.to_string(), contexts.source.to_string()); return true; } @@ -686,15 +676,13 @@ namespace tmap { bool ParseTmapRole(std::bitset<16>& role, uint16_t len, const uint8_t* value) { if (len != kTmapRoleLen) { - log::error( - ", Wrong len of Telephony Media Audio Profile Role, characteristic"); + log::error(", Wrong len of Telephony Media Audio Profile Role, characteristic"); return false; } STREAM_TO_UINT16(role, value); - log::info(", Telephony Media Audio Profile Role:\n\tRole: {}", - role.to_string()); + log::info(", Telephony Media Audio Profile Role:\n\tRole: {}", role.to_string()); return true; } diff --git a/system/bta/le_audio/client_parser.h b/system/bta/le_audio/client_parser.h index fbdbb5f97d3..1aaf4b3b8ac 100644 --- a/system/bta/le_audio/client_parser.h +++ b/system/bta/le_audio/client_parser.h @@ -194,33 +194,26 @@ struct ctp_update_metadata { /* Device control and common functions */ bool ParseAseStatusHeader(ase_rsp_hdr& rsp, uint16_t len, const uint8_t* value); -bool ParseAseStatusCodecConfiguredStateParams( - struct ase_codec_configured_state_params& rsp, uint16_t len, - const uint8_t* value); -bool ParseAseStatusQosConfiguredStateParams( - struct ase_qos_configured_state_params& rsp, uint16_t len, - const uint8_t* value); -bool ParseAseStatusTransientStateParams(struct ase_transient_state_params& rsp, - uint16_t len, const uint8_t* value); -bool ParseAseCtpNotification(struct ctp_ntf& ntf, uint16_t len, - const uint8_t* value); +bool ParseAseStatusCodecConfiguredStateParams(struct ase_codec_configured_state_params& rsp, + uint16_t len, const uint8_t* value); +bool ParseAseStatusQosConfiguredStateParams(struct ase_qos_configured_state_params& rsp, + uint16_t len, const uint8_t* value); +bool ParseAseStatusTransientStateParams(struct ase_transient_state_params& rsp, uint16_t len, + const uint8_t* value); +bool ParseAseCtpNotification(struct ctp_ntf& ntf, uint16_t len, const uint8_t* value); bool PrepareAseCtpCodecConfig(const std::vector& confs, std::vector& value); bool PrepareAseCtpConfigQos(const std::vector& confs, std::vector& value); -bool PrepareAseCtpEnable(const std::vector& confs, - std::vector& value); +bool PrepareAseCtpEnable(const std::vector& confs, std::vector& value); bool PrepareAseCtpAudioReceiverStartReady(const std::vector& ids, std::vector& value); -bool PrepareAseCtpDisable(const std::vector& ids, - std::vector& value); +bool PrepareAseCtpDisable(const std::vector& ids, std::vector& value); bool PrepareAseCtpAudioReceiverStopReady(const std::vector& ids, std::vector& value); -bool PrepareAseCtpUpdateMetadata( - const std::vector& confs, - std::vector& value); -bool PrepareAseCtpRelease(const std::vector& ids, - std::vector& value); +bool PrepareAseCtpUpdateMetadata(const std::vector& confs, + std::vector& value); +bool PrepareAseCtpRelease(const std::vector& ids, std::vector& value); } // namespace ascs namespace pacs { @@ -235,18 +228,16 @@ constexpr uint16_t kAseAudioAvailRspMinLen = 4; constexpr uint16_t kAseAudioSuppContRspMinLen = 4; -int ParseSinglePac(std::vector& pac_recs, - uint16_t len, const uint8_t* value); +int ParseSinglePac(std::vector& pac_recs, uint16_t len, + const uint8_t* value); bool ParsePacs(std::vector& pac_recs, uint16_t len, const uint8_t* value); bool ParseAudioLocations(types::AudioLocations& audio_locations, uint16_t len, const uint8_t* value); -bool ParseAvailableAudioContexts( - types::BidirectionalPair& rsp, uint16_t len, - const uint8_t* value); -bool ParseSupportedAudioContexts( - types::BidirectionalPair& rsp, uint16_t len, - const uint8_t* value); +bool ParseAvailableAudioContexts(types::BidirectionalPair& rsp, uint16_t len, + const uint8_t* value); +bool ParseSupportedAudioContexts(types::BidirectionalPair& rsp, uint16_t len, + const uint8_t* value); } // namespace pacs namespace tmap { diff --git a/system/bta/le_audio/client_parser_test.cc b/system/bta/le_audio/client_parser_test.cc index f53a9dfbba2..5ce04a2daa7 100644 --- a/system/bta/le_audio/client_parser_test.cc +++ b/system/bta/le_audio/client_parser_test.cc @@ -30,32 +30,31 @@ TEST(LeAudioClientParserTest, testParsePacsInvalidLength) { std::vector pac_recs; const uint8_t invalid_num_records[] = {0x01}; - ASSERT_FALSE( - ParsePacs(pac_recs, sizeof(invalid_num_records), invalid_num_records)); + ASSERT_FALSE(ParsePacs(pac_recs, sizeof(invalid_num_records), invalid_num_records)); const uint8_t no_caps_len[] = { - // Num records - 0x01, - // Codec_ID - 0x01, - 0x02, - 0x03, - 0x04, - 0x05, + // Num records + 0x01, + // Codec_ID + 0x01, + 0x02, + 0x03, + 0x04, + 0x05, }; ASSERT_FALSE(ParsePacs(pac_recs, sizeof(no_caps_len), no_caps_len)); const uint8_t no_metalen[] = { - // Num records - 0x01, - // Codec_ID - 0x01, - 0x02, - 0x03, - 0x04, - 0x05, - // Codec Spec. Caps. Len - 0x00, + // Num records + 0x01, + // Codec_ID + 0x01, + 0x02, + 0x03, + 0x04, + 0x05, + // Codec Spec. Caps. Len + 0x00, }; ASSERT_FALSE(ParsePacs(pac_recs, sizeof(no_metalen), no_metalen)); } @@ -71,18 +70,18 @@ TEST(LeAudioClientParserTest, testParsePacsEmptyCapsEmptyMeta) { std::vector pac_recs; const uint8_t value[] = { - // Num records - 0x01, - // Codec_ID - 0x01, - 0x03, - 0x02, - 0x05, - 0x04, - // Codec Spec. Caps. Len - 0x00, - // Metadata Length - 0x00, + // Num records + 0x01, + // Codec_ID + 0x01, + 0x03, + 0x02, + 0x05, + 0x04, + // Codec Spec. Caps. Len + 0x00, + // Metadata Length + 0x00, }; ASSERT_TRUE(ParsePacs(pac_recs, sizeof(value), value)); @@ -96,52 +95,52 @@ TEST(LeAudioClientParserTest, testParsePacsInvalidCapsLen) { std::vector pac_recs; const uint8_t bad_capslem[] = { - // Num records - 0x01, - // Codec_ID - 0x01, - 0x03, - 0x02, - 0x05, - 0x04, - // Codec Spec. Caps. Len - 0x05, - // Codec Spec. Caps. - 0x02, // [0].length, - 0x02, // [0].type, - 0x03, // [0].value[0] - 0x03, // [1].length - 0x03, // [1].type - 0x04, // [1].value[0] - 0x05, // [1].value[1] - // Metadata Length - 0x00, + // Num records + 0x01, + // Codec_ID + 0x01, + 0x03, + 0x02, + 0x05, + 0x04, + // Codec Spec. Caps. Len + 0x05, + // Codec Spec. Caps. + 0x02, // [0].length, + 0x02, // [0].type, + 0x03, // [0].value[0] + 0x03, // [1].length + 0x03, // [1].type + 0x04, // [1].value[0] + 0x05, // [1].value[1] + // Metadata Length + 0x00, }; ASSERT_FALSE(ParsePacs(pac_recs, sizeof(bad_capslem), bad_capslem)); std::vector pac_recs2; const uint8_t bad_capslen2[] = { - // Num records - 0x01, - // Codec_ID - 0x01, - 0x03, - 0x02, - 0x05, - 0x04, - // Codec Spec. Caps. Len - 0x20, - // Codec Spec. Caps. - 0x02, // [0].length - 0x02, // [0].type - 0x03, // [0].value[0] - 0x03, // [1].length - 0x03, // [1].type - 0x04, // [1].value[0] - 0x05, // [1].value[1] - // Metadata Length - 0x00, + // Num records + 0x01, + // Codec_ID + 0x01, + 0x03, + 0x02, + 0x05, + 0x04, + // Codec Spec. Caps. Len + 0x20, + // Codec Spec. Caps. + 0x02, // [0].length + 0x02, // [0].type + 0x03, // [0].value[0] + 0x03, // [1].length + 0x03, // [1].type + 0x04, // [1].value[0] + 0x05, // [1].value[1] + // Metadata Length + 0x00, }; ASSERT_FALSE(ParsePacs(pac_recs2, sizeof(bad_capslen2), bad_capslen2)); } @@ -150,50 +149,50 @@ TEST(LeAudioClientParserTest, testParsePacsInvalidCapsLtvLen) { std::vector pac_recs; const uint8_t bad_ltv_len[] = { - // Num records - 0x01, - // Codec_ID - 0x06, - 0x00, - 0x00, - 0x00, - 0x00, - // Codec Spec. Caps. Len - 0x07, - // Codec Spec. Caps. - 0x02, // [0].length - 0x02, // [0].type - 0x03, // [0].value[0] - 0x06, // [1].bad_length - 0x03, // [1].type - 0x04, // [1].value[0] - 0x05, // [1].value[1] - // Metadata Length - 0x00, + // Num records + 0x01, + // Codec_ID + 0x06, + 0x00, + 0x00, + 0x00, + 0x00, + // Codec Spec. Caps. Len + 0x07, + // Codec Spec. Caps. + 0x02, // [0].length + 0x02, // [0].type + 0x03, // [0].value[0] + 0x06, // [1].bad_length + 0x03, // [1].type + 0x04, // [1].value[0] + 0x05, // [1].value[1] + // Metadata Length + 0x00, }; ASSERT_FALSE(ParsePacs(pac_recs, sizeof(bad_ltv_len), bad_ltv_len)); const uint8_t bad_ltv_len2[] = { - // Num records - 0x01, - // Codec_ID - 0x06, - 0x00, - 0x00, - 0x00, - 0x00, - // Codec Spec. Caps. Len - 0x07, - // Codec Spec. Caps. - 0x02, // [0].length - 0x02, // [0].type - 0x03, // [0].value[0] - 0x04, // [1].bad_length - 0x03, // [1].type - 0x04, // [1].value[0] - 0x05, // [1].value[1] - // Metadata Length - 0x00, + // Num records + 0x01, + // Codec_ID + 0x06, + 0x00, + 0x00, + 0x00, + 0x00, + // Codec Spec. Caps. Len + 0x07, + // Codec Spec. Caps. + 0x02, // [0].length + 0x02, // [0].type + 0x03, // [0].value[0] + 0x04, // [1].bad_length + 0x03, // [1].type + 0x04, // [1].value[0] + 0x05, // [1].value[1] + // Metadata Length + 0x00, }; ASSERT_FALSE(ParsePacs(pac_recs, sizeof(bad_ltv_len2), bad_ltv_len2)); } @@ -202,29 +201,29 @@ TEST(LeAudioClientParserTest, testParsePacsNullLtv) { std::vector pac_recs; const uint8_t value[] = { - // Num records - 0x01, - // Codec_ID - 0x06, - 0x00, - 0x00, - 0x00, - 0x00, - // Codec Spec. Caps. Len - 0x0A, - // Codec Spec. Caps. - 0x02, // [0].length - 0x02, // [0].type - 0x03, // [0].value[0] - 0x03, // [1].length - 0x03, // [1].type - 0x04, // [1].value[0] - 0x05, // [1].value[1] - 0x01, // [2].length <-- a capability without a value - 0x04, // [2].type - 0x00, // [3]length <-- this seems possible although useless - // Metadata Length - 0x00, + // Num records + 0x01, + // Codec_ID + 0x06, + 0x00, + 0x00, + 0x00, + 0x00, + // Codec Spec. Caps. Len + 0x0A, + // Codec Spec. Caps. + 0x02, // [0].length + 0x02, // [0].type + 0x03, // [0].value[0] + 0x03, // [1].length + 0x03, // [1].type + 0x04, // [1].value[0] + 0x05, // [1].value[1] + 0x01, // [2].length <-- a capability without a value + 0x04, // [2].type + 0x00, // [3]length <-- this seems possible although useless + // Metadata Length + 0x00, }; ASSERT_TRUE(ParsePacs(pac_recs, sizeof(value), value)); @@ -256,26 +255,26 @@ TEST(LeAudioClientParserTest, testParsePacsEmptyMeta) { std::vector pac_recs; const uint8_t value[] = { - // Num records - 0x01, - // Codec_ID - 0x06, - 0x00, - 0x00, - 0x00, - 0x00, - // Codec Spec. Caps. Len - 0x07, - // Codec Spec. Caps. - 0x02, // [0].length - 0x02, // [0].type - 0x03, // [0].value[0] - 0x03, // [1].length - 0x03, // [1].type - 0x04, // [1].value[0] - 0x05, // [1].value[1] - // Metadata Length - 0x00, + // Num records + 0x01, + // Codec_ID + 0x06, + 0x00, + 0x00, + 0x00, + 0x00, + // Codec Spec. Caps. Len + 0x07, + // Codec Spec. Caps. + 0x02, // [0].length + 0x02, // [0].type + 0x03, // [0].value[0] + 0x03, // [1].length + 0x03, // [1].type + 0x04, // [1].value[0] + 0x05, // [1].value[1] + // Metadata Length + 0x00, }; ASSERT_TRUE(ParsePacs(pac_recs, sizeof(value), value)); @@ -295,35 +294,34 @@ TEST(LeAudioClientParserTest, testParsePacsEmptyMeta) { ASSERT_EQ(codec_spec_caps[0x03u][1], 0x05u); // Validate the raw data from ltv matches the original pac record data buffer - ASSERT_EQ(pac_recs[0].codec_spec_caps.RawPacket(), - pac_recs[0].codec_spec_caps_raw); + ASSERT_EQ(pac_recs[0].codec_spec_caps.RawPacket(), pac_recs[0].codec_spec_caps_raw); } TEST(LeAudioClientParserTest, testParsePacsInvalidMetaLength) { std::vector pac_recs; const uint8_t value[] = { - // Num records - 0x01, - // Codec_ID - 0x01, 0x03, 0x02, 0x05, 0x04, - // Codec Spec. Caps. Len - 0x07, - // Codec Spec. Caps. - 0x02, // [0].length - 0x02, // [0].type - 0x03, // [0].value[0] - 0x03, // [1].length - 0x03, // [1].type - 0x04, // [1].value[0] - 0x05, // [1].value[1] - // Metadata Length - 0x05, - // Metadata - 0x03, // [0].length - 0x02, // [0].type - 0x01, // [0].value[0] - 0x00, // [0].value[1] + // Num records + 0x01, + // Codec_ID + 0x01, 0x03, 0x02, 0x05, 0x04, + // Codec Spec. Caps. Len + 0x07, + // Codec Spec. Caps. + 0x02, // [0].length + 0x02, // [0].type + 0x03, // [0].value[0] + 0x03, // [1].length + 0x03, // [1].type + 0x04, // [1].value[0] + 0x05, // [1].value[1] + // Metadata Length + 0x05, + // Metadata + 0x03, // [0].length + 0x02, // [0].type + 0x01, // [0].value[0] + 0x00, // [0].value[1] }; ASSERT_FALSE(ParsePacs(pac_recs, sizeof(value), value)); } @@ -332,27 +330,27 @@ TEST(LeAudioClientParserTest, testParsePacsValidMeta) { std::vector pac_recs; const uint8_t value[] = { - // Num records - 0x01, - // Codec_ID - 0x06, 0x00, 0x00, 0x00, 0x00, - // Codec Spec. Caps. Len - 0x07, - // Codec Spec. Caps. - 0x02, // [0].length - 0x02, // [0].type - 0x03, // [0].value[0] - 0x03, // [1].length - 0x03, // [1].type - 0x04, // [1].value[0] - 0x05, // [1].value[1] - // Metadata Length - 0x04, - // Metadata - 0x03, // [0].length - 0x02, // [0].type - 0x01, // [0].value[0] - 0x00, // [0].value[1] + // Num records + 0x01, + // Codec_ID + 0x06, 0x00, 0x00, 0x00, 0x00, + // Codec Spec. Caps. Len + 0x07, + // Codec Spec. Caps. + 0x02, // [0].length + 0x02, // [0].type + 0x03, // [0].value[0] + 0x03, // [1].length + 0x03, // [1].type + 0x04, // [1].value[0] + 0x05, // [1].value[1] + // Metadata Length + 0x04, + // Metadata + 0x03, // [0].length + 0x02, // [0].type + 0x01, // [0].value[0] + 0x00, // [0].value[1] }; ASSERT_TRUE(ParsePacs(pac_recs, sizeof(value), value)); @@ -378,35 +376,34 @@ TEST(LeAudioClientParserTest, testParsePacsValidMeta) { ASSERT_EQ(pac_recs[0].metadata[3], 0x00u); // Validate the raw data from ltv matches the original pac record data buffer - ASSERT_EQ(pac_recs[0].codec_spec_caps.RawPacket(), - pac_recs[0].codec_spec_caps_raw); + ASSERT_EQ(pac_recs[0].codec_spec_caps.RawPacket(), pac_recs[0].codec_spec_caps_raw); } TEST(LeAudioClientParserTest, testParsePacsInvalidNumRecords) { std::vector pac_recs; const uint8_t value[] = { - // Num records - 0x02, - // Codec_ID - 0x01, 0x03, 0x02, 0x05, 0x04, - // Codec Spec. Caps. Len - 0x07, - // Codec Spec. Caps. - 0x02, // [0].length - 0x02, // [0].type - 0x03, // [0].value[0] - 0x03, // [1].length - 0x03, // [1].type - 0x04, // [1].value[0] - 0x05, // [1].value[1] - // Metadata Length - 0x04, - // Metadata - 0x03, // [0].length - 0x02, // [0].type - 0x01, // [0].value[0] - 0x00, // [0].value[1] + // Num records + 0x02, + // Codec_ID + 0x01, 0x03, 0x02, 0x05, 0x04, + // Codec Spec. Caps. Len + 0x07, + // Codec Spec. Caps. + 0x02, // [0].length + 0x02, // [0].type + 0x03, // [0].value[0] + 0x03, // [1].length + 0x03, // [1].type + 0x04, // [1].value[0] + 0x05, // [1].value[1] + // Metadata Length + 0x04, + // Metadata + 0x03, // [0].length + 0x02, // [0].type + 0x01, // [0].value[0] + 0x00, // [0].value[1] }; ASSERT_FALSE(ParsePacs(pac_recs, sizeof(value), value)); } @@ -415,48 +412,48 @@ TEST(LeAudioClientParserTest, testParsePacsMultipleRecords) { std::vector pac_recs; const uint8_t value[] = { - // Num records - 0x03, - // Codec_ID - 0x01, 0x03, 0x02, 0x05, 0x04, - // Codec Spec. Caps. Len - 0x00, - // Metadata Length - 0x00, - // Codec_ID - 0x06, 0x00, 0x00, 0x00, 0x00, - // Codec Spec. Caps. Len - 0x03, - // Codec Spec. Caps. - 0x02, // [0].length - 0x02, // [0].type - 0x03, // [0].value[0] - // Metadata Length - 0x04, - // Metadata - 0x03, // [0].length - 0x02, // [0].type - 0x01, // [0].value[0] - 0x00, // [0].value[1], - // Codec_ID - 0x11, 0x13, 0x12, 0x15, 0x14, - // Codec Spec. Caps. Len - 0x07, - // Codec Spec. Caps. - 0x02, // [0].length - 0x12, // [0].type - 0x13, // [0].value[0] - 0x03, // [1].length - 0x13, // [1].type - 0x14, // [1].value[0] - 0x15, // [1].value[1] - // Metadata Length - 0x04, - // Metadata - 0x03, // [0].length - 0x12, // [0].type - 0x11, // [0].value[0] - 0x10, // [0].value[1] + // Num records + 0x03, + // Codec_ID + 0x01, 0x03, 0x02, 0x05, 0x04, + // Codec Spec. Caps. Len + 0x00, + // Metadata Length + 0x00, + // Codec_ID + 0x06, 0x00, 0x00, 0x00, 0x00, + // Codec Spec. Caps. Len + 0x03, + // Codec Spec. Caps. + 0x02, // [0].length + 0x02, // [0].type + 0x03, // [0].value[0] + // Metadata Length + 0x04, + // Metadata + 0x03, // [0].length + 0x02, // [0].type + 0x01, // [0].value[0] + 0x00, // [0].value[1], + // Codec_ID + 0x11, 0x13, 0x12, 0x15, 0x14, + // Codec Spec. Caps. Len + 0x07, + // Codec Spec. Caps. + 0x02, // [0].length + 0x12, // [0].type + 0x13, // [0].value[0] + 0x03, // [1].length + 0x13, // [1].type + 0x14, // [1].value[0] + 0x15, // [1].value[1] + // Metadata Length + 0x04, + // Metadata + 0x03, // [0].length + 0x12, // [0].type + 0x11, // [0].value[0] + 0x10, // [0].value[1] }; ASSERT_TRUE(ParsePacs(pac_recs, sizeof(value), value)); ASSERT_EQ(pac_recs.size(), 3u); @@ -516,29 +513,29 @@ TEST(LeAudioClientParserTest, testParsePacsVendorCodecRecords) { std::vector pac_recs; const uint8_t value[] = { - // Num records - 0x01, - // Vendor Codec_ID - 0x01, - 0x03, - 0x02, - 0x05, - 0x04, - // Codec Spec. Caps. Len - 0x0A, - // Codec Spec. Caps. - proprietary format - 0x01, - 0x02, - 0x03, - 0x04, - 0x05, - 0x06, - 0x07, - 0x08, - 0x09, - 0x0A, - // Metadata Length - 0x00, + // Num records + 0x01, + // Vendor Codec_ID + 0x01, + 0x03, + 0x02, + 0x05, + 0x04, + // Codec Spec. Caps. Len + 0x0A, + // Codec Spec. Caps. - proprietary format + 0x01, + 0x02, + 0x03, + 0x04, + 0x05, + 0x06, + 0x07, + 0x08, + 0x09, + 0x0A, + // Metadata Length + 0x00, }; ASSERT_TRUE(ParsePacs(pac_recs, sizeof(value), value)); @@ -553,9 +550,9 @@ TEST(LeAudioClientParserTest, testParsePacsVendorCodecRecords) { TEST(LeAudioClientParserTest, testParseAudioLocationsInvalidLength) { types::AudioLocations locations = codec_spec_conf::kLeAudioLocationNotAllowed; const uint8_t value1[] = { - 0x01, - 0x02, - 0x03, + 0x01, + 0x02, + 0x03, }; ParseAudioLocations(locations, sizeof(value1), value1); ASSERT_EQ(locations, 0u); @@ -575,9 +572,9 @@ TEST(LeAudioClientParserTest, testParseAudioLocations) { TEST(LeAudioClientParserTest, testParseAvailableAudioContextsInvalidLength) { types::BidirectionalPair avail_contexts; const uint8_t value1[] = { - // Sink available contexts - 0x01, 0x02, - // Missing Source available contexts + // Sink available contexts + 0x01, 0x02, + // Missing Source available contexts }; ParseAvailableAudioContexts(avail_contexts, sizeof(value1), value1); @@ -588,12 +585,12 @@ TEST(LeAudioClientParserTest, testParseAvailableAudioContextsInvalidLength) { TEST(LeAudioClientParserTest, testParseAvailableAudioContexts) { types::BidirectionalPair avail_contexts; const uint8_t value1[] = { - // Sink available contexts - 0x01, - 0x02, - // Source available contexts - 0x03, - 0x04, + // Sink available contexts + 0x01, + 0x02, + // Source available contexts + 0x03, + 0x04, }; ParseAvailableAudioContexts(avail_contexts, sizeof(value1), value1); @@ -604,9 +601,9 @@ TEST(LeAudioClientParserTest, testParseAvailableAudioContexts) { TEST(LeAudioClientParserTest, testParseSupportedAudioContextsInvalidLength) { types::BidirectionalPair supp_contexts; const uint8_t value1[] = { - // Sink supported contexts - 0x01, 0x02, - // Missing Source supported contexts + // Sink supported contexts + 0x01, 0x02, + // Missing Source supported contexts }; ParseSupportedAudioContexts(supp_contexts, sizeof(value1), value1); @@ -617,12 +614,12 @@ TEST(LeAudioClientParserTest, testParseSupportedAudioContextsInvalidLength) { TEST(LeAudioClientParserTest, testParseSupportedAudioContexts) { types::BidirectionalPair supp_contexts; const uint8_t value1[] = { - // Sink supported contexts - 0x01, - 0x02, - // Source supported contexts - 0x03, - 0x04, + // Sink supported contexts + 0x01, + 0x02, + // Source supported contexts + 0x03, + 0x04, }; ParseSupportedAudioContexts(supp_contexts, sizeof(value1), value1); @@ -637,9 +634,9 @@ namespace ascs { TEST(LeAudioClientParserTest, testParseAseStatusHeaderInvalidLength) { ase_rsp_hdr arh; const uint8_t value1[] = { - // Ase ID - 0x01, - // ASE State is missing here + // Ase ID + 0x01, + // ASE State is missing here }; ASSERT_FALSE(ParseAseStatusHeader(arh, sizeof(value1), value1)); } @@ -647,29 +644,29 @@ TEST(LeAudioClientParserTest, testParseAseStatusHeaderInvalidLength) { TEST(LeAudioClientParserTest, testParseAseStatusHeader) { ase_rsp_hdr arh; const uint8_t value1[] = { - // Ase ID - 0x01, - // ASE State - 0x00, // 'Idle' state - // No additional ASE Params for the 'Idle' state + // Ase ID + 0x01, + // ASE State + 0x00, // 'Idle' state + // No additional ASE Params for the 'Idle' state }; ASSERT_TRUE(ParseAseStatusHeader(arh, sizeof(value1), value1)); ASSERT_EQ(arh.id, 0x01u); ASSERT_EQ(arh.state, 0x00u); const uint8_t value2[] = { - // Ase ID - 0x02, - // ASE State - 0x04, // 'Streaming' state - // Additional ASE Params for the 'Streaming' state - // Metadata Len - 0x03, - // Metadata - 0x03, // [0].length - 0x02, // [0].type - 0x01, // [0].value[0] - 0x00, // [0].value[1] + // Ase ID + 0x02, + // ASE State + 0x04, // 'Streaming' state + // Additional ASE Params for the 'Streaming' state + // Metadata Len + 0x03, + // Metadata + 0x03, // [0].length + 0x02, // [0].type + 0x01, // [0].value[0] + 0x00, // [0].value[1] }; ASSERT_TRUE(ParseAseStatusHeader(arh, sizeof(value2), value2)); ASSERT_EQ(arh.id, 0x02u); @@ -677,84 +674,83 @@ TEST(LeAudioClientParserTest, testParseAseStatusHeader) { // Currently additional state parameters are not handled } -TEST(LeAudioClientParserTest, - testParseAseStatusCodecConfiguredStateParamsInvalidLength) { +TEST(LeAudioClientParserTest, testParseAseStatusCodecConfiguredStateParamsInvalidLength) { ase_codec_configured_state_params codec_configured_state_params; const uint8_t value1[] = { - // Ase ID - 0x02, - // ASE State - 0x01, // 'Codec Configured' state - // Framing - 0x01, // Unframed - // Peferred PHY - 0x02, // 2M PHY - // Preferred retransimssion Num. - 0x04, - // Max transport Latency - 0x05, 0x00, - // Pressentation delay min. - 0x00, 0x01, 0x02, 0x03, - // Pressentation delay max. - 0x00, 0x01, 0x02, 0x03, - // Preferred presentation delay min. - 0x01, 0x02, 0x03, - // Preferred presentation delay max. - 0x01, 0x02, 0x03, - // Codec ID - 0x01, 0x02, 0x03, 0x04, 0x05, - // Missing Codec spec. conf. length + // Ase ID + 0x02, + // ASE State + 0x01, // 'Codec Configured' state + // Framing + 0x01, // Unframed + // Peferred PHY + 0x02, // 2M PHY + // Preferred retransimssion Num. + 0x04, + // Max transport Latency + 0x05, 0x00, + // Pressentation delay min. + 0x00, 0x01, 0x02, 0x03, + // Pressentation delay max. + 0x00, 0x01, 0x02, 0x03, + // Preferred presentation delay min. + 0x01, 0x02, 0x03, + // Preferred presentation delay max. + 0x01, 0x02, 0x03, + // Codec ID + 0x01, 0x02, 0x03, 0x04, 0x05, + // Missing Codec spec. conf. length }; - ASSERT_FALSE(ParseAseStatusCodecConfiguredStateParams( - codec_configured_state_params, sizeof(value1) - 2, value1 + 2)); + ASSERT_FALSE(ParseAseStatusCodecConfiguredStateParams(codec_configured_state_params, + sizeof(value1) - 2, value1 + 2)); } TEST(LeAudioClientParserTest, testParseAseStatusCodecConfiguredStateParams) { ase_codec_configured_state_params codec_configured_state_params; const uint8_t value1[] = { - // Ase ID - 0x01, - // ASE State - 0x01, // 'Codec Configured' state - // Framing - 0x01, // Unframed - // Peferred PHY - 0x02, // 2M PHY - // Preferred retransimssion Num. - 0x04, - // Max transport Latency - 0x05, - 0x00, - // Pressentation delay min. - 0x00, - 0x01, - 0x02, - // Pressentation delay max. - 0x10, - 0x11, - 0x12, - // Preferred presentation delay min. - 0x01, - 0x02, - 0x03, - // Preferred presentation delay max. - 0x09, - 0x10, - 0x11, - // Codec ID - 0x01, - 0x02, - 0x03, - 0x04, - 0x05, - // Codec spec. conf. length - 0x00, + // Ase ID + 0x01, + // ASE State + 0x01, // 'Codec Configured' state + // Framing + 0x01, // Unframed + // Peferred PHY + 0x02, // 2M PHY + // Preferred retransimssion Num. + 0x04, + // Max transport Latency + 0x05, + 0x00, + // Pressentation delay min. + 0x00, + 0x01, + 0x02, + // Pressentation delay max. + 0x10, + 0x11, + 0x12, + // Preferred presentation delay min. + 0x01, + 0x02, + 0x03, + // Preferred presentation delay max. + 0x09, + 0x10, + 0x11, + // Codec ID + 0x01, + 0x02, + 0x03, + 0x04, + 0x05, + // Codec spec. conf. length + 0x00, }; // State additional parameters are right after the ASE ID and state bytes - ASSERT_TRUE(ParseAseStatusCodecConfiguredStateParams( - codec_configured_state_params, sizeof(value1) - 2, value1 + 2)); + ASSERT_TRUE(ParseAseStatusCodecConfiguredStateParams(codec_configured_state_params, + sizeof(value1) - 2, value1 + 2)); ASSERT_EQ(codec_configured_state_params.framing, 0x01u); ASSERT_EQ(codec_configured_state_params.preferred_phy, 0x02u); ASSERT_EQ(codec_configured_state_params.preferred_retrans_nb, 0x04u); @@ -769,54 +765,54 @@ TEST(LeAudioClientParserTest, testParseAseStatusCodecConfiguredStateParams) { ASSERT_EQ(codec_configured_state_params.codec_spec_conf.size(), 0u); const uint8_t value2[] = { - // Ase ID - 0x02, - // ASE State - 0x01, // 'Codec Configured' state - // Framing - 0x01, // Unframed - // Peferred PHY - 0x02, // 2M PHY - // Preferred retransimssion Num. - 0x04, - // Max transport Latency - 0x05, - 0x00, - // Pressentation delay min. - 0x00, - 0x01, - 0x02, - // Pressentation delay max. - 0x10, - 0x11, - 0x12, - // Preferred presentation delay min. - 0x01, - 0x02, - 0x03, - // Preferred presentation delay max. - 0x09, - 0x10, - 0x11, - // Codec ID - 0x01, - 0x02, - 0x03, - 0x04, - 0x05, - // Codec spec. conf. length - 0x05, - // Codec spec. conf. - 0x0A, - 0x0B, - 0x0C, - 0x0D, - 0x0E, + // Ase ID + 0x02, + // ASE State + 0x01, // 'Codec Configured' state + // Framing + 0x01, // Unframed + // Peferred PHY + 0x02, // 2M PHY + // Preferred retransimssion Num. + 0x04, + // Max transport Latency + 0x05, + 0x00, + // Pressentation delay min. + 0x00, + 0x01, + 0x02, + // Pressentation delay max. + 0x10, + 0x11, + 0x12, + // Preferred presentation delay min. + 0x01, + 0x02, + 0x03, + // Preferred presentation delay max. + 0x09, + 0x10, + 0x11, + // Codec ID + 0x01, + 0x02, + 0x03, + 0x04, + 0x05, + // Codec spec. conf. length + 0x05, + // Codec spec. conf. + 0x0A, + 0x0B, + 0x0C, + 0x0D, + 0x0E, }; // State additional parameters are right after the ASE ID and state bytes - ASSERT_TRUE(ParseAseStatusCodecConfiguredStateParams( - codec_configured_state_params, sizeof(value2) - 2, value2 + 2)); + ASSERT_TRUE(ParseAseStatusCodecConfiguredStateParams(codec_configured_state_params, + sizeof(value2) - 2, value2 + 2)); ASSERT_EQ(codec_configured_state_params.framing, 0x01u); ASSERT_EQ(codec_configured_state_params.preferred_phy, 0x02u); ASSERT_EQ(codec_configured_state_params.preferred_retrans_nb, 0x04u); @@ -836,18 +832,17 @@ TEST(LeAudioClientParserTest, testParseAseStatusCodecConfiguredStateParams) { ASSERT_EQ(codec_configured_state_params.codec_spec_conf[4], 0x0Eu); } -TEST(LeAudioClientParserTest, - testParseAseStatusQosConfiguredStateParamsInvalidLength) { +TEST(LeAudioClientParserTest, testParseAseStatusQosConfiguredStateParamsInvalidLength) { struct ase_qos_configured_state_params rsp { .cig_id = 0, .cis_id = 0 }; const uint8_t value1[] = { - // Ase ID - 0x01, - // ASE State - 0x02, // 'QoS Configured' state - 0x03, // CIG_ID - 0x04, // CIS_ID + // Ase ID + 0x01, + // ASE State + 0x02, // 'QoS Configured' state + 0x03, // CIG_ID + 0x04, // CIS_ID }; ParseAseStatusQosConfiguredStateParams(rsp, sizeof(value1) - 2, value1 + 2); @@ -855,29 +850,29 @@ TEST(LeAudioClientParserTest, ASSERT_EQ(rsp.cis_id, 0); const uint8_t value2[] = { - // Ase ID - 0x01, - // ASE State - 0x02, // 'QoS Configured' state - // CIG_ID - 0x03, - // CIS_ID - 0x04, - // SDU Interval - 0x05, 0x06, 0x07, - // Framing - 0x01, - // PHY - 0x02, - // Max SDU - 0x08, 0x09, - // Retransmission Num. - 0x0A, - // Max Transport Latency - 0x0B, 0x0C, - // Presentation Delay - 0x0D, 0x0E, - // Missing Byte + // Ase ID + 0x01, + // ASE State + 0x02, // 'QoS Configured' state + // CIG_ID + 0x03, + // CIS_ID + 0x04, + // SDU Interval + 0x05, 0x06, 0x07, + // Framing + 0x01, + // PHY + 0x02, + // Max SDU + 0x08, 0x09, + // Retransmission Num. + 0x0A, + // Max Transport Latency + 0x0B, 0x0C, + // Presentation Delay + 0x0D, 0x0E, + // Missing Byte }; ParseAseStatusQosConfiguredStateParams(rsp, sizeof(value2) - 2, value2 + 2); @@ -888,34 +883,34 @@ TEST(LeAudioClientParserTest, TEST(LeAudioClientParserTest, testParseAseStatusQosConfiguredStateParams) { struct ase_qos_configured_state_params rsp; const uint8_t value[] = { - // Ase ID - 0x01, - // ASE State - 'QoS Configured' - 0x02, - // CIG_ID - 0x03, - // CIS_ID - 0x04, - // SDU Interval - 0x05, - 0x06, - 0x07, - // Framing - 0x01, - // PHY - 0x02, - // Max SDU - 0x18, - 0x19, - // Retransmission Num. - 0x1A, - // Max Transport Latency - 0x1B, - 0x1C, - // Presentation Delay - 0x1D, - 0x1E, - 0x1F, + // Ase ID + 0x01, + // ASE State - 'QoS Configured' + 0x02, + // CIG_ID + 0x03, + // CIS_ID + 0x04, + // SDU Interval + 0x05, + 0x06, + 0x07, + // Framing + 0x01, + // PHY + 0x02, + // Max SDU + 0x18, + 0x19, + // Retransmission Num. + 0x1A, + // Max Transport Latency + 0x1B, + 0x1C, + // Presentation Delay + 0x1D, + 0x1E, + 0x1F, }; ParseAseStatusQosConfiguredStateParams(rsp, sizeof(value) - 2, value + 2); @@ -930,16 +925,15 @@ TEST(LeAudioClientParserTest, testParseAseStatusQosConfiguredStateParams) { ASSERT_EQ(rsp.pres_delay, 0x1F1E1Du); } -TEST(LeAudioClientParserTest, - testParseAseStatusTransientStateParamsInvalidLength) { +TEST(LeAudioClientParserTest, testParseAseStatusTransientStateParamsInvalidLength) { ase_transient_state_params params; const uint8_t value1[] = { - // Ase ID - 0x01, - // ASE State - 0x03, // 'Enabling' state - // missing Metadata length - // missing Metadata + // Ase ID + 0x01, + // ASE State + 0x03, // 'Enabling' state + // missing Metadata length + // missing Metadata }; ParseAseStatusTransientStateParams(params, sizeof(value1) - 2, value1 + 2); } @@ -947,31 +941,31 @@ TEST(LeAudioClientParserTest, TEST(LeAudioClientParserTest, testParseAseStatusTransientStateParams) { ase_transient_state_params params; const uint8_t value1[] = { - // Ase ID - 0x01, - // ASE State - 0x03, // 'Enabling' state - // Metadata length - 0x00, + // Ase ID + 0x01, + // ASE State + 0x03, // 'Enabling' state + // Metadata length + 0x00, }; ParseAseStatusTransientStateParams(params, sizeof(value1) - 2, value1 + 2); ASSERT_EQ(params.metadata.size(), 0u); const uint8_t value2[] = { - // Ase ID - 0x01, - // ASE State - 0x03, // 'Enabling' state - // CIG_ID - 0x03, - // CIS_ID - 0x04, - // Metadata length - 0x03, - // Metadata - 0x02, // [0].length - 0x01, // [0].type - 0x00, // [0].value[0] + // Ase ID + 0x01, + // ASE State + 0x03, // 'Enabling' state + // CIG_ID + 0x03, + // CIS_ID + 0x04, + // Metadata length + 0x03, + // Metadata + 0x02, // [0].length + 0x01, // [0].type + 0x00, // [0].value[0] }; ParseAseStatusTransientStateParams(params, sizeof(value2) - 2, value2 + 2); @@ -984,21 +978,21 @@ TEST(LeAudioClientParserTest, testParseAseStatusTransientStateParams) { TEST(LeAudioClientParserTest, testParseAseCtpNotificationInvalidLength) { ctp_ntf ntf; const uint8_t value1[] = { - // Opcode - 0x01, - // Number of ASEs - 0x02, - // ASE ID - 0x01, - // Response Code - 0x01, - // Reason - 0x01, - // ASE ID - 0x02, - // Response Code - 0x02, - // Missing Reason + // Opcode + 0x01, + // Number of ASEs + 0x02, + // ASE ID + 0x01, + // Response Code + 0x01, + // Reason + 0x01, + // ASE ID + 0x02, + // Response Code + 0x02, + // Missing Reason }; ParseAseCtpNotification(ntf, sizeof(value1), value1); @@ -1007,15 +1001,15 @@ TEST(LeAudioClientParserTest, testParseAseCtpNotificationInvalidLength) { ASSERT_EQ(ntf.entries.size(), 0u); const uint8_t value2[] = { - // Opcode - 0x01, - // Missing Number of ASEs - // Missing ASE ID - // Missing Response Code - // Missing Reason - // Missing ASE ID - // Missing Response Code - // Missing Reason + // Opcode + 0x01, + // Missing Number of ASEs + // Missing ASE ID + // Missing Response Code + // Missing Reason + // Missing ASE ID + // Missing Response Code + // Missing Reason }; ntf.entries.clear(); ParseAseCtpNotification(ntf, sizeof(value2), value2); @@ -1025,23 +1019,23 @@ TEST(LeAudioClientParserTest, testParseAseCtpNotificationInvalidLength) { ASSERT_EQ(ntf.entries.size(), 0u); const uint8_t value3[] = { - // Opcode - 0x01, - // Number of ASEs - 0x03, - // ASE ID - 0x01, - // Response Code - 0x01, - // Reason - 0x01, - // ASE ID - 0x02, - // Response Code - 0x02, - // Reason - 0x03, - // Missing the entire ASE entry + // Opcode + 0x01, + // Number of ASEs + 0x03, + // ASE ID + 0x01, + // Response Code + 0x01, + // Reason + 0x01, + // ASE ID + 0x02, + // Response Code + 0x02, + // Reason + 0x03, + // Missing the entire ASE entry }; ntf.entries.clear(); @@ -1054,22 +1048,22 @@ TEST(LeAudioClientParserTest, testParseAseCtpNotificationInvalidLength) { TEST(LeAudioClientParserTest, testParseAseCtpNotification) { ctp_ntf ntf; const uint8_t value1[] = { - // Opcode - 0x01, - // Number of ASEs - 0x02, - // ASE ID - 0x01, - // Response Code - 0x01, - // Reason - 0x01, - // ASE ID - 0x03, - // Response Code - 0x02, - // Reason - 0x03, + // Opcode + 0x01, + // Number of ASEs + 0x02, + // ASE ID + 0x01, + // Response Code + 0x01, + // Reason + 0x01, + // ASE ID + 0x03, + // Response Code + 0x02, + // Reason + 0x03, }; ParseAseCtpNotification(ntf, sizeof(value1), value1); @@ -1086,22 +1080,22 @@ TEST(LeAudioClientParserTest, testParseAseCtpNotification) { TEST(LeAudioClientParserTest, testParseAseCtpNotificationConfigurationIssue) { ctp_ntf ntf; const uint8_t value1[] = { - // Opcode - 0x01, - // Number of ASEs - 0x02, - // ASE ID - 0x01, - // Response Code - 0x07, - // Reason - 0x01, - // ASE ID - 0x03, - // Response Code - 0x05, - // Reason - 0x05, + // Opcode + 0x01, + // Number of ASEs + 0x02, + // ASE ID + 0x01, + // Response Code + 0x07, + // Reason + 0x01, + // ASE ID + 0x03, + // Response Code + 0x05, + // Reason + 0x05, }; ParseAseCtpNotification(ntf, sizeof(value1), value1); @@ -1118,22 +1112,22 @@ TEST(LeAudioClientParserTest, testParseAseCtpNotificationConfigurationIssue) { TEST(LeAudioClientParserTest, testParseAseCtpNotificationMetadataIssue) { ctp_ntf ntf; const uint8_t value1[] = { - // Opcode - 0x01, - // Number of ASEs - 0x02, - // ASE ID - 0x01, - // Response Code - 0x0A, - // Reason - 0x01, - // ASE ID - 0x03, - // Response Code - 0x0D, - // Reason - 0xFF, + // Opcode + 0x01, + // Number of ASEs + 0x02, + // ASE ID + 0x01, + // Response Code + 0x0A, + // Reason + 0x01, + // ASE ID + 0x03, + // Response Code + 0x0D, + // Reason + 0xFF, }; ParseAseCtpNotification(ntf, sizeof(value1), value1); @@ -1160,24 +1154,21 @@ TEST(LeAudioClientParserTest, testPrepareAseCtpCodecConfigSingle) { std::vector confs; std::vector value; - types::LeAudioCodecId codec_id{.coding_format = 0x06, - .vendor_company_id = 0x0203, - .vendor_codec_id = 0x0405}; + types::LeAudioCodecId codec_id{ + .coding_format = 0x06, .vendor_company_id = 0x0203, .vendor_codec_id = 0x0405}; types::LeAudioLtvMap codec_conf = - types::LeAudioLtvMap() - .Add(codec_spec_conf::kLeAudioLtvTypeSamplingFreq, (uint8_t)0x10) - .Add(codec_spec_conf::kLeAudioLtvTypeFrameDuration, (uint8_t)0x03) - .Add(codec_spec_conf::kLeAudioLtvTypeAudioChannelAllocation, - (uint32_t)0x04050607) - .Add(codec_spec_conf::kLeAudioLtvTypeOctetsPerCodecFrame, - (uint16_t)0x0203); + types::LeAudioLtvMap() + .Add(codec_spec_conf::kLeAudioLtvTypeSamplingFreq, (uint8_t)0x10) + .Add(codec_spec_conf::kLeAudioLtvTypeFrameDuration, (uint8_t)0x03) + .Add(codec_spec_conf::kLeAudioLtvTypeAudioChannelAllocation, (uint32_t)0x04050607) + .Add(codec_spec_conf::kLeAudioLtvTypeOctetsPerCodecFrame, (uint16_t)0x0203); confs.push_back(ctp_codec_conf{ - .ase_id = 0x05, - .target_latency = 0x03, - .target_phy = 0x02, - .codec_id = codec_id, - .codec_config = codec_conf.RawPacket(), + .ase_id = 0x05, + .target_latency = 0x03, + .target_phy = 0x02, + .codec_id = codec_id, + .codec_config = codec_conf.RawPacket(), }); PrepareAseCtpCodecConfig(confs, value); @@ -1220,24 +1211,21 @@ TEST(LeAudioClientParserTest, testPrepareAseCtpCodecConfigMultiple) { std::vector confs; std::vector value; - types::LeAudioCodecId codec_id{.coding_format = 0x06, - .vendor_company_id = 0x0203, - .vendor_codec_id = 0x0405}; + types::LeAudioCodecId codec_id{ + .coding_format = 0x06, .vendor_company_id = 0x0203, .vendor_codec_id = 0x0405}; types::LeAudioLtvMap codec_conf = - types::LeAudioLtvMap() - .Add(codec_spec_conf::kLeAudioLtvTypeSamplingFreq, (uint8_t)0x10) - .Add(codec_spec_conf::kLeAudioLtvTypeFrameDuration, (uint8_t)0x03) - .Add(codec_spec_conf::kLeAudioLtvTypeAudioChannelAllocation, - (uint32_t)0x04050607) - .Add(codec_spec_conf::kLeAudioLtvTypeOctetsPerCodecFrame, - (uint16_t)0x0203); + types::LeAudioLtvMap() + .Add(codec_spec_conf::kLeAudioLtvTypeSamplingFreq, (uint8_t)0x10) + .Add(codec_spec_conf::kLeAudioLtvTypeFrameDuration, (uint8_t)0x03) + .Add(codec_spec_conf::kLeAudioLtvTypeAudioChannelAllocation, (uint32_t)0x04050607) + .Add(codec_spec_conf::kLeAudioLtvTypeOctetsPerCodecFrame, (uint16_t)0x0203); confs.push_back(ctp_codec_conf{ - .ase_id = 0x05, - .target_latency = 0x03, - .target_phy = 0x02, - .codec_id = codec_id, - .codec_config = codec_conf.RawPacket(), + .ase_id = 0x05, + .target_latency = 0x03, + .target_phy = 0x02, + .codec_id = codec_id, + .codec_config = codec_conf.RawPacket(), }); PrepareAseCtpCodecConfig(confs, value); @@ -1275,24 +1263,21 @@ TEST(LeAudioClientParserTest, testPrepareAseCtpCodecConfigMultiple) { ASSERT_EQ(value[i++], 0x02); // Octets Per Frame Value[1] ASSERT_EQ(value.size(), i); - types::LeAudioCodecId codec_id2{.coding_format = 0x16, - .vendor_company_id = 0x1213, - .vendor_codec_id = 0x1415}; + types::LeAudioCodecId codec_id2{ + .coding_format = 0x16, .vendor_company_id = 0x1213, .vendor_codec_id = 0x1415}; types::LeAudioLtvMap codec_conf2 = - types::LeAudioLtvMap() - .Add(codec_spec_conf::kLeAudioLtvTypeSamplingFreq, (uint8_t)0x11) - .Add(codec_spec_conf::kLeAudioLtvTypeFrameDuration, (uint8_t)0x13) - .Add(codec_spec_conf::kLeAudioLtvTypeAudioChannelAllocation, - (uint32_t)0x14151617) - .Add(codec_spec_conf::kLeAudioLtvTypeOctetsPerCodecFrame, - (uint16_t)0x1213); + types::LeAudioLtvMap() + .Add(codec_spec_conf::kLeAudioLtvTypeSamplingFreq, (uint8_t)0x11) + .Add(codec_spec_conf::kLeAudioLtvTypeFrameDuration, (uint8_t)0x13) + .Add(codec_spec_conf::kLeAudioLtvTypeAudioChannelAllocation, (uint32_t)0x14151617) + .Add(codec_spec_conf::kLeAudioLtvTypeOctetsPerCodecFrame, (uint16_t)0x1213); confs.push_back(ctp_codec_conf{ - .ase_id = 0x15, - .target_latency = 0x13, - .target_phy = 0x01, - .codec_id = codec_id2, - .codec_config = codec_conf2.RawPacket(), + .ase_id = 0x15, + .target_latency = 0x13, + .target_phy = 0x01, + .codec_id = codec_id2, + .codec_config = codec_conf2.RawPacket(), }); PrepareAseCtpCodecConfig(confs, value); @@ -1565,8 +1550,7 @@ TEST(LeAudioClientParserTest, testPrepareAseCtpAudioReceiverStartReadySingle) { ASSERT_EQ(i, value.size()); } -TEST(LeAudioClientParserTest, - testPrepareAseCtpAudioReceiverStartReadyMultiple) { +TEST(LeAudioClientParserTest, testPrepareAseCtpAudioReceiverStartReadyMultiple) { std::vector ase_ids; std::vector value; @@ -1704,8 +1688,7 @@ TEST(LeAudioClientParserTest, testPrepareAseCtpUpdateMetadataMultiple) { ctp_update_metadata conf{.ase_id = 0x11, .metadata = {0x02, 0x22, 0x21}}; confs.push_back(conf); - ctp_update_metadata conf2{.ase_id = 0x21, - .metadata = {0x03, 0x35, 0x36, 0x37}}; + ctp_update_metadata conf2{.ase_id = 0x21, .metadata = {0x03, 0x35, 0x36, 0x37}}; confs.push_back(conf2); PrepareAseCtpUpdateMetadata(confs, value); diff --git a/system/bta/le_audio/codec_interface.cc b/system/bta/le_audio/codec_interface.cc index ee5d0f2e80d..b5c75c6e1c1 100644 --- a/system/bta/le_audio/codec_interface.cc +++ b/system/bta/le_audio/codec_interface.cc @@ -33,11 +33,10 @@ struct CodecInterface::Impl { Impl(const types::LeAudioCodecId& codec_id) : codec_id_(codec_id) {} ~Impl() { Cleanup(); } - bool IsReady() { return pcm_config_.has_value(); }; + bool IsReady() { return pcm_config_.has_value(); } - CodecInterface::Status InitEncoder( - const LeAudioCodecConfiguration& pcm_config, - const LeAudioCodecConfiguration& codec_config) { + CodecInterface::Status InitEncoder(const LeAudioCodecConfiguration& pcm_config, + const LeAudioCodecConfiguration& codec_config) { // Output codec configuration bt_codec_config_ = codec_config; @@ -48,29 +47,27 @@ struct CodecInterface::Impl { } pcm_config_ = pcm_config; - lc3_.pcm_format_ = (pcm_config_->bits_per_sample == 24) - ? LC3_PCM_FORMAT_S24 - : LC3_PCM_FORMAT_S16; + lc3_.pcm_format_ = + (pcm_config_->bits_per_sample == 24) ? LC3_PCM_FORMAT_S24 : LC3_PCM_FORMAT_S16; // Prepare the encoder - const auto encoder_size = lc3_encoder_size( - bt_codec_config_.data_interval_us, pcm_config_->sample_rate); + const auto encoder_size = + lc3_encoder_size(bt_codec_config_.data_interval_us, pcm_config_->sample_rate); lc3_.codec_mem_.reset(malloc(encoder_size)); - lc3_.encoder_ = lc3_setup_encoder( - bt_codec_config_.data_interval_us, bt_codec_config_.sample_rate, - pcm_config_->sample_rate, lc3_.codec_mem_.get()); + lc3_.encoder_ = + lc3_setup_encoder(bt_codec_config_.data_interval_us, bt_codec_config_.sample_rate, + pcm_config_->sample_rate, lc3_.codec_mem_.get()); return Status::STATUS_OK; } - log::error("Invalid codec ID: [{}:{}:{}]", codec_id_.coding_format, - codec_id_.vendor_company_id, codec_id_.vendor_codec_id); + log::error("Invalid codec ID: [{}:{}:{}]", codec_id_.coding_format, codec_id_.vendor_company_id, + codec_id_.vendor_codec_id); return Status::STATUS_ERR_INVALID_CODEC_ID; } - CodecInterface::Status InitDecoder( - const LeAudioCodecConfiguration& codec_config, - const LeAudioCodecConfiguration& pcm_config) { + CodecInterface::Status InitDecoder(const LeAudioCodecConfiguration& codec_config, + const LeAudioCodecConfiguration& pcm_config) { // Input codec configuration bt_codec_config_ = codec_config; @@ -81,28 +78,27 @@ struct CodecInterface::Impl { } pcm_config_ = pcm_config; - lc3_.pcm_format_ = (pcm_config_->bits_per_sample == 24) - ? LC3_PCM_FORMAT_S24 - : LC3_PCM_FORMAT_S16; + lc3_.pcm_format_ = + (pcm_config_->bits_per_sample == 24) ? LC3_PCM_FORMAT_S24 : LC3_PCM_FORMAT_S16; // Prepare the decoded output buffer - output_channel_samples_ = lc3_frame_samples( - bt_codec_config_.data_interval_us, pcm_config_->sample_rate); + output_channel_samples_ = + lc3_frame_samples(bt_codec_config_.data_interval_us, pcm_config_->sample_rate); adjustOutputBufferSizeIfNeeded(&output_channel_data_); // Prepare the decoder - const auto decoder_size = lc3_decoder_size( - bt_codec_config_.data_interval_us, pcm_config_->sample_rate); + const auto decoder_size = + lc3_decoder_size(bt_codec_config_.data_interval_us, pcm_config_->sample_rate); lc3_.codec_mem_.reset(malloc(decoder_size)); - lc3_.decoder_ = lc3_setup_decoder( - bt_codec_config_.data_interval_us, bt_codec_config_.sample_rate, - pcm_config_->sample_rate, lc3_.codec_mem_.get()); + lc3_.decoder_ = + lc3_setup_decoder(bt_codec_config_.data_interval_us, bt_codec_config_.sample_rate, + pcm_config_->sample_rate, lc3_.codec_mem_.get()); return Status::STATUS_OK; } - log::error("Invalid codec ID: [{}:{}:{}]", codec_id_.coding_format, - codec_id_.vendor_company_id, codec_id_.vendor_codec_id); + log::error("Invalid codec ID: [{}:{}:{}]", codec_id_.coding_format, codec_id_.vendor_company_id, + codec_id_.vendor_codec_id); return Status::STATUS_ERR_INVALID_CODEC_ID; } @@ -126,13 +122,12 @@ struct CodecInterface::Impl { return Status::STATUS_OK; } - log::error("Invalid codec ID: [{}:{}:{}]", codec_id_.coding_format, - codec_id_.vendor_company_id, codec_id_.vendor_codec_id); + log::error("Invalid codec ID: [{}:{}:{}]", codec_id_.coding_format, codec_id_.vendor_company_id, + codec_id_.vendor_codec_id); return Status::STATUS_ERR_INVALID_CODEC_ID; } - CodecInterface::Status Encode(const uint8_t* data, int stride, - uint16_t out_size, + CodecInterface::Status Encode(const uint8_t* data, int stride, uint16_t out_size, std::vector* out_buffer = nullptr, uint16_t out_offset = 0) { if (!IsReady()) { @@ -161,9 +156,8 @@ struct CodecInterface::Impl { adjustOutputBufferSizeIfNeeded(out_buffer); // Encode - auto err = - lc3_encode(lc3_.encoder_, lc3_.pcm_format_, data, stride, out_size, - ((uint8_t*)out_buffer->data()) + out_offset); + auto err = lc3_encode(lc3_.encoder_, lc3_.pcm_format_, data, stride, out_size, + ((uint8_t*)out_buffer->data()) + out_offset); if (err < 0) { log::error("bad encoding parameters: {}", static_cast(err)); return Status::STATUS_ERR_CODING_ERROR; @@ -172,8 +166,8 @@ struct CodecInterface::Impl { return Status::STATUS_OK; } - log::error("Invalid codec ID: [{}:{}:{}]", codec_id_.coding_format, - codec_id_.vendor_company_id, codec_id_.vendor_codec_id); + log::error("Invalid codec ID: [{}:{}:{}]", codec_id_.coding_format, codec_id_.vendor_company_id, + codec_id_.vendor_codec_id); return Status::STATUS_ERR_INVALID_CODEC_ID; } @@ -193,12 +187,11 @@ struct CodecInterface::Impl { } if (codec_id_.coding_format == types::kLeAudioCodingFormatLC3) { - return lc3_frame_samples(bt_codec_config_.data_interval_us, - pcm_config_->sample_rate); + return lc3_frame_samples(bt_codec_config_.data_interval_us, pcm_config_->sample_rate); } - log::error("Invalid codec ID: [{}:{}:{}]", codec_id_.coding_format, - codec_id_.vendor_company_id, codec_id_.vendor_codec_id); + log::error("Invalid codec ID: [{}:{}:{}]", codec_id_.coding_format, codec_id_.vendor_company_id, + codec_id_.vendor_codec_id); return 0; } @@ -207,12 +200,12 @@ struct CodecInterface::Impl { return lc3_.bits_to_bytes_per_sample(bt_codec_config_.bits_per_sample); } - log::error("Invalid codec ID: [{}:{}:{}]", codec_id_.coding_format, - codec_id_.vendor_company_id, codec_id_.vendor_codec_id); + log::error("Invalid codec ID: [{}:{}:{}]", codec_id_.coding_format, codec_id_.vendor_company_id, + codec_id_.vendor_codec_id); return 0; } - private: +private: inline void adjustOutputBufferSizeIfNeeded(std::vector* out_buffer) { if (out_buffer->size() < output_channel_samples_) { out_buffer->resize(output_channel_samples_); @@ -232,7 +225,9 @@ struct CodecInterface::Impl { struct lc3_t { static inline uint8_t bits_to_bytes_per_sample(uint8_t bits_per_sample) { // 24 bit audio stream is sent as unpacked, each sample takes 4 bytes. - if (bits_per_sample == 24) return 4; + if (bits_per_sample == 24) { + return 4; + } return bits_per_sample / 8; } @@ -256,43 +251,34 @@ CodecInterface::CodecInterface(const types::LeAudioCodecId& codec_id) { if (codec_id.coding_format == types::kLeAudioCodingFormatLC3) { impl = new Impl(codec_id); } else { - log::error("Invalid codec ID: [{}:{}:{}]", codec_id.coding_format, - codec_id.vendor_company_id, codec_id.vendor_codec_id); + log::error("Invalid codec ID: [{}:{}:{}]", codec_id.coding_format, codec_id.vendor_company_id, + codec_id.vendor_codec_id); } } CodecInterface::~CodecInterface() { delete impl; } -bool CodecInterface::IsReady() { return impl->IsReady(); }; -CodecInterface::Status CodecInterface::InitEncoder( - const LeAudioCodecConfiguration& pcm_config, - const LeAudioCodecConfiguration& codec_config) { +bool CodecInterface::IsReady() { return impl->IsReady(); } +CodecInterface::Status CodecInterface::InitEncoder(const LeAudioCodecConfiguration& pcm_config, + const LeAudioCodecConfiguration& codec_config) { return impl->InitEncoder(pcm_config, codec_config); } -CodecInterface::Status CodecInterface::InitDecoder( - const LeAudioCodecConfiguration& codec_config, - const LeAudioCodecConfiguration& pcm_config) { +CodecInterface::Status CodecInterface::InitDecoder(const LeAudioCodecConfiguration& codec_config, + const LeAudioCodecConfiguration& pcm_config) { return impl->InitDecoder(codec_config, pcm_config); } -std::vector& CodecInterface::GetDecodedSamples() { - return impl->GetDecodedSamples(); -} +std::vector& CodecInterface::GetDecodedSamples() { return impl->GetDecodedSamples(); } CodecInterface::Status CodecInterface::Decode(uint8_t* data, uint16_t size) { return impl->Decode(data, size); } -CodecInterface::Status CodecInterface::Encode(const uint8_t* data, int stride, - uint16_t out_size, +CodecInterface::Status CodecInterface::Encode(const uint8_t* data, int stride, uint16_t out_size, std::vector* out_buffer, uint16_t out_offset) { return impl->Encode(data, stride, out_size, out_buffer, out_offset); } void CodecInterface::Cleanup() { return impl->Cleanup(); } -uint16_t CodecInterface::GetNumOfSamplesPerChannel() { - return impl->GetNumOfSamplesPerChannel(); -}; -uint8_t CodecInterface::GetNumOfBytesPerSample() { - return impl->GetNumOfBytesPerSample(); -}; +uint16_t CodecInterface::GetNumOfSamplesPerChannel() { return impl->GetNumOfSamplesPerChannel(); } +uint8_t CodecInterface::GetNumOfBytesPerSample() { return impl->GetNumOfBytesPerSample(); } } // namespace bluetooth::le_audio diff --git a/system/bta/le_audio/codec_interface.h b/system/bta/le_audio/codec_interface.h index ee953f203dd..7e99fc91898 100644 --- a/system/bta/le_audio/codec_interface.h +++ b/system/bta/le_audio/codec_interface.h @@ -39,7 +39,7 @@ namespace bluetooth::le_audio { * */ class CodecInterface { - public: +public: enum class Status { STATUS_ERR_CODEC_NOT_READY = -128, STATUS_ERR_INVALID_CODEC_ID = -127, @@ -49,19 +49,16 @@ class CodecInterface { CodecInterface(const types::LeAudioCodecId& codec_id); virtual ~CodecInterface(); - static std::unique_ptr CreateInstance( - const types::LeAudioCodecId& codec_id) { + static std::unique_ptr CreateInstance(const types::LeAudioCodecId& codec_id) { return std::make_unique(codec_id); } - virtual CodecInterface::Status InitEncoder( - const LeAudioCodecConfiguration& pcm_config, - const LeAudioCodecConfiguration& codec_config); - virtual CodecInterface::Status InitDecoder( - const LeAudioCodecConfiguration& codec_config, - const LeAudioCodecConfiguration& pcm_config); - virtual CodecInterface::Status Encode( - const uint8_t* data, int stride, uint16_t out_size, - std::vector* out_buffer = nullptr, uint16_t out_offset = 0); + virtual CodecInterface::Status InitEncoder(const LeAudioCodecConfiguration& pcm_config, + const LeAudioCodecConfiguration& codec_config); + virtual CodecInterface::Status InitDecoder(const LeAudioCodecConfiguration& codec_config, + const LeAudioCodecConfiguration& pcm_config); + virtual CodecInterface::Status Encode(const uint8_t* data, int stride, uint16_t out_size, + std::vector* out_buffer = nullptr, + uint16_t out_offset = 0); virtual CodecInterface::Status Decode(uint8_t* data, uint16_t size); virtual void Cleanup(); virtual bool IsReady(); @@ -69,7 +66,7 @@ class CodecInterface { virtual uint8_t GetNumOfBytesPerSample(); virtual std::vector& GetDecodedSamples(); - private: +private: struct Impl; Impl* impl; }; diff --git a/system/bta/le_audio/codec_manager.cc b/system/bta/le_audio/codec_manager.cc index fe710773aaa..fda45e79462 100644 --- a/system/bta/le_audio/codec_manager.cc +++ b/system/bta/le_audio/codec_manager.cc @@ -60,8 +60,7 @@ typedef struct offloader_stream_maps { namespace bluetooth::le_audio { template <> -offloader_stream_maps_t& types::BidirectionalPair::get( - uint8_t direction) { +offloader_stream_maps_t& types::BidirectionalPair::get(uint8_t direction) { log::assert_that(direction < types::kLeAudioDirectionBoth, "Unsupported complex direction. Reference to a single " "complex direction value is not supported."); @@ -70,37 +69,33 @@ offloader_stream_maps_t& types::BidirectionalPair::get( // The mapping for sampling rate, frame duration, and the QoS config static std::unordered_map< - int, std::unordered_map< - int, bluetooth::le_audio::broadcaster::BroadcastQosConfig>> - bcast_high_reliability_qos = { - {LeAudioCodecConfiguration::kSampleRate16000, - {{LeAudioCodecConfiguration::kInterval7500Us, - bluetooth::le_audio::broadcaster::qos_config_4_45}, - {LeAudioCodecConfiguration::kInterval10000Us, - bluetooth::le_audio::broadcaster::qos_config_4_60}}}, - {LeAudioCodecConfiguration::kSampleRate24000, - {{LeAudioCodecConfiguration::kInterval7500Us, - bluetooth::le_audio::broadcaster::qos_config_4_45}, - {LeAudioCodecConfiguration::kInterval10000Us, - bluetooth::le_audio::broadcaster::qos_config_4_60}}}, - {LeAudioCodecConfiguration::kSampleRate32000, - {{LeAudioCodecConfiguration::kInterval7500Us, - bluetooth::le_audio::broadcaster::qos_config_4_45}, - {LeAudioCodecConfiguration::kInterval10000Us, - bluetooth::le_audio::broadcaster::qos_config_4_60}}}, - {LeAudioCodecConfiguration::kSampleRate48000, - {{LeAudioCodecConfiguration::kInterval7500Us, - bluetooth::le_audio::broadcaster::qos_config_4_50}, - {LeAudioCodecConfiguration::kInterval10000Us, - bluetooth::le_audio::broadcaster::qos_config_4_65}}}}; + int, std::unordered_map> + bcast_high_reliability_qos = {{LeAudioCodecConfiguration::kSampleRate16000, + {{LeAudioCodecConfiguration::kInterval7500Us, + bluetooth::le_audio::broadcaster::qos_config_4_45}, + {LeAudioCodecConfiguration::kInterval10000Us, + bluetooth::le_audio::broadcaster::qos_config_4_60}}}, + {LeAudioCodecConfiguration::kSampleRate24000, + {{LeAudioCodecConfiguration::kInterval7500Us, + bluetooth::le_audio::broadcaster::qos_config_4_45}, + {LeAudioCodecConfiguration::kInterval10000Us, + bluetooth::le_audio::broadcaster::qos_config_4_60}}}, + {LeAudioCodecConfiguration::kSampleRate32000, + {{LeAudioCodecConfiguration::kInterval7500Us, + bluetooth::le_audio::broadcaster::qos_config_4_45}, + {LeAudioCodecConfiguration::kInterval10000Us, + bluetooth::le_audio::broadcaster::qos_config_4_60}}}, + {LeAudioCodecConfiguration::kSampleRate48000, + {{LeAudioCodecConfiguration::kInterval7500Us, + bluetooth::le_audio::broadcaster::qos_config_4_50}, + {LeAudioCodecConfiguration::kInterval10000Us, + bluetooth::le_audio::broadcaster::qos_config_4_65}}}}; struct codec_manager_impl { - public: +public: codec_manager_impl() { - offload_enable_ = osi_property_get_bool( - "ro.bluetooth.leaudio_offload.supported", false) && - !osi_property_get_bool( - "persist.bluetooth.leaudio_offload.disabled", true); + offload_enable_ = osi_property_get_bool("ro.bluetooth.leaudio_offload.supported", false) && + !osi_property_get_bool("persist.bluetooth.leaudio_offload.disabled", true); if (offload_enable_ == false) { log::info("offload disabled"); return; @@ -112,7 +107,7 @@ struct codec_manager_impl { } if (!bluetooth::shim::GetController()->IsSupported( - bluetooth::hci::OpCode::CONFIGURE_DATA_PATH)) { + bluetooth::hci::OpCode::CONFIGURE_DATA_PATH)) { log::warn("Controller does not support config data path command"); return; } @@ -124,20 +119,18 @@ struct codec_manager_impl { kIsoDataPathPlatformDefault, {}); SetCodecLocation(CodecLocation::ADSP); } - void start( - const std::vector& offloading_preference) { - dual_bidirection_swb_supported_ = osi_property_get_bool( - "bluetooth.leaudio.dual_bidirection_swb.supported", false); - bluetooth::le_audio::AudioSetConfigurationProvider::Initialize( - GetCodecLocation()); + void start(const std::vector& offloading_preference) { + dual_bidirection_swb_supported_ = + osi_property_get_bool("bluetooth.leaudio.dual_bidirection_swb.supported", false); + bluetooth::le_audio::AudioSetConfigurationProvider::Initialize(GetCodecLocation()); UpdateOffloadCapability(offloading_preference); } ~codec_manager_impl() { if (GetCodecLocation() != CodecLocation::HOST) { - GetInterface().ConfigureDataPath(hci_data_direction_t::HOST_TO_CONTROLLER, - kIsoDataPathHci, {}); - GetInterface().ConfigureDataPath(hci_data_direction_t::CONTROLLER_TO_HOST, - kIsoDataPathHci, {}); + GetInterface().ConfigureDataPath(hci_data_direction_t::HOST_TO_CONTROLLER, kIsoDataPathHci, + {}); + GetInterface().ConfigureDataPath(hci_data_direction_t::CONTROLLER_TO_HOST, kIsoDataPathHci, + {}); } bluetooth::le_audio::AudioSetConfigurationProvider::Cleanup(); } @@ -155,28 +148,24 @@ struct codec_manager_impl { return false; } - std::vector - GetLocalAudioOutputCodecCapa() { + std::vector GetLocalAudioOutputCodecCapa() { return codec_output_capa; } - std::vector - GetLocalAudioInputCodecCapa() { + std::vector GetLocalAudioInputCodecCapa() { return codec_input_capa; } void UpdateActiveAudioConfig( - const types::BidirectionalPair& stream_params, - types::BidirectionalPair delays_ms, - std::function - update_receiver) { + const types::BidirectionalPair& stream_params, + types::BidirectionalPair delays_ms, + std::function update_receiver) { if (GetCodecLocation() != bluetooth::le_audio::types::CodecLocation::ADSP) { return; } - for (auto direction : - {bluetooth::le_audio::types::kLeAudioDirectionSink, - bluetooth::le_audio::types::kLeAudioDirectionSource}) { + for (auto direction : {bluetooth::le_audio::types::kLeAudioDirectionSink, + bluetooth::le_audio::types::kLeAudioDirectionSource}) { auto& stream_map = offloader_stream_maps.get(direction); if (!stream_map.has_changed && !stream_map.is_initial) { continue; @@ -186,32 +175,28 @@ struct codec_manager_impl { } bluetooth::le_audio::offload_config unicast_cfg = { - .stream_map = (stream_map.is_initial || - LeAudioHalVerifier::SupportsStreamActiveApi()) - ? stream_map.streams_map_target - : stream_map.streams_map_current, - // TODO: set the default value 16 for now, would change it if we - // support mode bits_per_sample - .bits_per_sample = 16, - .sampling_rate = stream_params.get(direction).sample_frequency_hz, - .frame_duration = stream_params.get(direction).frame_duration_us, - .octets_per_frame = - stream_params.get(direction).octets_per_codec_frame, - .blocks_per_sdu = - stream_params.get(direction).codec_frames_blocks_per_sdu, - .peer_delay_ms = delays_ms.get(direction), + .stream_map = (stream_map.is_initial || LeAudioHalVerifier::SupportsStreamActiveApi()) + ? stream_map.streams_map_target + : stream_map.streams_map_current, + // TODO: set the default value 16 for now, would change it if we + // support mode bits_per_sample + .bits_per_sample = 16, + .sampling_rate = stream_params.get(direction).sample_frequency_hz, + .frame_duration = stream_params.get(direction).frame_duration_us, + .octets_per_frame = stream_params.get(direction).octets_per_codec_frame, + .blocks_per_sdu = stream_params.get(direction).codec_frames_blocks_per_sdu, + .peer_delay_ms = delays_ms.get(direction), }; update_receiver(unicast_cfg, direction); stream_map.is_initial = false; } } - bool UpdateActiveUnicastAudioHalClient( - LeAudioSourceAudioHalClient* source_unicast_client, - LeAudioSinkAudioHalClient* sink_unicast_client, bool is_active) { - log::debug("local_source: {}, local_sink: {}, is_active: {}", - fmt::ptr(source_unicast_client), fmt::ptr(sink_unicast_client), - is_active); + bool UpdateActiveUnicastAudioHalClient(LeAudioSourceAudioHalClient* source_unicast_client, + LeAudioSinkAudioHalClient* sink_unicast_client, + bool is_active) { + log::debug("local_source: {}, local_sink: {}, is_active: {}", fmt::ptr(source_unicast_client), + fmt::ptr(sink_unicast_client), is_active); if (source_unicast_client == nullptr && sink_unicast_client == nullptr) { return false; @@ -241,18 +226,14 @@ struct codec_manager_impl { return true; } - if (source_unicast_client && - source_unicast_client != unicast_local_source_hal_client) { - log::error("local source session does not match {} != {}", - fmt::ptr(source_unicast_client), + if (source_unicast_client && source_unicast_client != unicast_local_source_hal_client) { + log::error("local source session does not match {} != {}", fmt::ptr(source_unicast_client), fmt::ptr(unicast_local_source_hal_client)); return false; } - if (sink_unicast_client && - sink_unicast_client != unicast_local_sink_hal_client) { - log::error("local source session does not match {} != {}", - fmt::ptr(sink_unicast_client), + if (sink_unicast_client && sink_unicast_client != unicast_local_sink_hal_client) { + log::error("local source session does not match {} != {}", fmt::ptr(sink_unicast_client), fmt::ptr(unicast_local_sink_hal_client)); return false; } @@ -268,10 +249,9 @@ struct codec_manager_impl { return true; } - bool UpdateActiveBroadcastAudioHalClient( - LeAudioSourceAudioHalClient* source_broadcast_client, bool is_active) { - log::debug("local_source: {},is_active: {}", - fmt::ptr(source_broadcast_client), is_active); + bool UpdateActiveBroadcastAudioHalClient(LeAudioSourceAudioHalClient* source_broadcast_client, + bool is_active) { + log::debug("local_source: {},is_active: {}", fmt::ptr(source_broadcast_client), is_active); if (source_broadcast_client == nullptr) { return false; @@ -288,8 +268,7 @@ struct codec_manager_impl { } if (source_broadcast_client != broadcast_local_source_hal_client) { - log::error("local source session does not match {} != {}", - fmt::ptr(source_broadcast_client), + log::error("local source session does not match {} != {}", fmt::ptr(source_broadcast_client), fmt::ptr(broadcast_local_source_hal_client)); return false; } @@ -300,30 +279,26 @@ struct codec_manager_impl { } AudioSetConfigurations GetSupportedCodecConfigurations( - const CodecManager::UnicastConfigurationRequirements& requirements) - const { + const CodecManager::UnicastConfigurationRequirements& requirements) const { if (GetCodecLocation() == le_audio::types::CodecLocation::ADSP) { log::verbose("Get offload config for the context type: {}", (int)requirements.audio_context_type); // TODO: Need to have a mechanism to switch to software session if offload // doesn't support. - return context_type_offload_config_map_.count( - requirements.audio_context_type) - ? context_type_offload_config_map_.at( - requirements.audio_context_type) - : AudioSetConfigurations(); + return context_type_offload_config_map_.count(requirements.audio_context_type) + ? context_type_offload_config_map_.at(requirements.audio_context_type) + : AudioSetConfigurations(); } log::verbose("Get software config for the context type: {}", (int)requirements.audio_context_type); return *AudioSetConfigurationProvider::Get()->GetConfigurations( - requirements.audio_context_type); + requirements.audio_context_type); } void PrintDebugState() const { - for (types::LeAudioContextType ctx_type : - types::kLeAudioContextAllTypesArray) { + for (types::LeAudioContextType ctx_type : types::kLeAudioContextAllTypesArray) { std::stringstream os; os << ctx_type << ": "; if (context_type_offload_config_map_.count(ctx_type) == 0) { @@ -341,46 +316,44 @@ struct codec_manager_impl { bool IsUsingCodecExtensibility() const { auto codec_ext_status = - osi_property_get_bool( - "bluetooth.core.le_audio.codec_extension_aidl.enabled", false) && - com::android::bluetooth::flags::leaudio_multicodec_aidl_support(); + osi_property_get_bool("bluetooth.core.le_audio.codec_extension_aidl.enabled", false) && + com::android::bluetooth::flags::leaudio_multicodec_aidl_support(); log::debug("Using codec extensibility AIDL: {}", codec_ext_status); return codec_ext_status; } std::unique_ptr GetCodecConfig( - const CodecManager::UnicastConfigurationRequirements& requirements, - CodecManager::UnicastConfigurationVerifier verifier) { + const CodecManager::UnicastConfigurationRequirements& requirements, + CodecManager::UnicastConfigurationVerifier verifier) { if (IsUsingCodecExtensibility()) { - auto hal_config = - unicast_local_source_hal_client->GetUnicastConfig(requirements); + auto hal_config = unicast_local_source_hal_client->GetUnicastConfig(requirements); if (hal_config) { return std::make_unique(*hal_config); } log::debug( - "No configuration received from AIDL, fall back to static " - "configuration."); + "No configuration received from AIDL, fall back to static " + "configuration."); } auto configs = GetSupportedCodecConfigurations(requirements); if (configs.empty()) { - log::error("No valid configuration matching the requirements: {}", - requirements); + log::error("No valid configuration matching the requirements: {}", requirements); PrintDebugState(); return nullptr; } // Remove the dual bidir SWB config if not supported if (!IsDualBiDirSwbSupported()) { - configs.erase( - std::remove_if(configs.begin(), configs.end(), - [](auto const& el) { - if (el->confs.source.empty()) return false; - return AudioSetConfigurationProvider::Get() - ->CheckConfigurationIsDualBiDirSwb(*el); - }), - configs.end()); + configs.erase(std::remove_if(configs.begin(), configs.end(), + [](auto const& el) { + if (el->confs.source.empty()) { + return false; + } + return AudioSetConfigurationProvider::Get() + ->CheckConfigurationIsDualBiDirSwb(*el); + }), + configs.end()); } // Note: For the only supported right now legacy software configuration @@ -393,29 +366,25 @@ struct codec_manager_impl { } bool CheckCodecConfigIsBiDirSwb(const AudioSetConfiguration& config) { - return AudioSetConfigurationProvider::Get()->CheckConfigurationIsBiDirSwb( - config); + return AudioSetConfigurationProvider::Get()->CheckConfigurationIsBiDirSwb(config); } bool CheckCodecConfigIsDualBiDirSwb(const AudioSetConfiguration& config) { - return AudioSetConfigurationProvider::Get() - ->CheckConfigurationIsDualBiDirSwb(config); + return AudioSetConfigurationProvider::Get()->CheckConfigurationIsDualBiDirSwb(config); } - void UpdateSupportedBroadcastConfig( - const std::vector& adsp_capabilities) { + void UpdateSupportedBroadcastConfig(const std::vector& adsp_capabilities) { log::info("UpdateSupportedBroadcastConfig"); for (const auto& adsp_audio_set_conf : adsp_capabilities) { - if (adsp_audio_set_conf.confs.sink.empty() || - !adsp_audio_set_conf.confs.source.empty()) { + if (adsp_audio_set_conf.confs.sink.empty() || !adsp_audio_set_conf.confs.source.empty()) { continue; } auto& adsp_config = adsp_audio_set_conf.confs.sink[0]; const types::LeAudioCoreCodecConfig core_config = - adsp_config.codec.params.GetAsCoreCodecConfig(); + adsp_config.codec.params.GetAsCoreCodecConfig(); bluetooth::le_audio::broadcast_offload_config broadcast_config; broadcast_config.stream_map.resize(adsp_audio_set_conf.confs.sink.size()); @@ -429,8 +398,7 @@ struct codec_manager_impl { } } - broadcast_config.bits_per_sample = - LeAudioCodecConfiguration::kBitsPerSample16; + broadcast_config.bits_per_sample = LeAudioCodecConfiguration::kBitsPerSample16; broadcast_config.sampling_rate = core_config.GetSamplingFrequencyHz(); broadcast_config.frame_duration = core_config.GetFrameDurationUs(); broadcast_config.octets_per_frame = *(core_config.octets_per_codec_frame); @@ -439,28 +407,25 @@ struct codec_manager_impl { int sample_rate = broadcast_config.sampling_rate; int frame_duration = broadcast_config.frame_duration; - if (bcast_high_reliability_qos.find(sample_rate) != - bcast_high_reliability_qos.end() && + if (bcast_high_reliability_qos.find(sample_rate) != bcast_high_reliability_qos.end() && bcast_high_reliability_qos[sample_rate].find(frame_duration) != - bcast_high_reliability_qos[sample_rate].end()) { + bcast_high_reliability_qos[sample_rate].end()) { auto qos = bcast_high_reliability_qos[sample_rate].at(frame_duration); broadcast_config.retransmission_number = qos.getRetransmissionNumber(); broadcast_config.max_transport_latency = qos.getMaxTransportLatency(); supported_broadcast_config.push_back(broadcast_config); } else { log::error( - "Cannot find the correspoding QoS config for the sampling_rate: " - "{}, frame_duration: {}", - sample_rate, frame_duration); + "Cannot find the correspoding QoS config for the sampling_rate: " + "{}, frame_duration: {}", + sample_rate, frame_duration); } - log::info("broadcast_config sampling_rate: {}", - broadcast_config.sampling_rate); + log::info("broadcast_config sampling_rate: {}", broadcast_config.sampling_rate); } } - const broadcast_offload_config* GetBroadcastOffloadConfig( - uint8_t preferred_quality) { + const broadcast_offload_config* GetBroadcastOffloadConfig(uint8_t preferred_quality) { if (supported_broadcast_config.empty()) { log::error("There is no valid broadcast offload config"); return nullptr; @@ -505,36 +470,33 @@ struct codec_manager_impl { supported_broadcast_config[i].octets_per_frame == 40)) { // 16_2 if (broadcast_target_config == -1 || (supported_broadcast_config[i].sampling_rate > - supported_broadcast_config[broadcast_target_config].sampling_rate)) + supported_broadcast_config[broadcast_target_config].sampling_rate)) { broadcast_target_config = i; + } } } if (broadcast_target_config == -1) { - log::error( - "There is no valid broadcast offload config with preferred_quality"); + log::error("There is no valid broadcast offload config with preferred_quality"); return nullptr; } log::info( - "stream_map.size(): {}, sampling_rate: {}, frame_duration(us): {}, " - "octets_per_frame: {}, blocks_per_sdu {}, retransmission_number: {}, " - "max_transport_latency: {}", - supported_broadcast_config[broadcast_target_config].stream_map.size(), - supported_broadcast_config[broadcast_target_config].sampling_rate, - supported_broadcast_config[broadcast_target_config].frame_duration, - supported_broadcast_config[broadcast_target_config].octets_per_frame, - (int)supported_broadcast_config[broadcast_target_config].blocks_per_sdu, - (int)supported_broadcast_config[broadcast_target_config] - .retransmission_number, - supported_broadcast_config[broadcast_target_config] - .max_transport_latency); + "stream_map.size(): {}, sampling_rate: {}, frame_duration(us): {}, " + "octets_per_frame: {}, blocks_per_sdu {}, retransmission_number: {}, " + "max_transport_latency: {}", + supported_broadcast_config[broadcast_target_config].stream_map.size(), + supported_broadcast_config[broadcast_target_config].sampling_rate, + supported_broadcast_config[broadcast_target_config].frame_duration, + supported_broadcast_config[broadcast_target_config].octets_per_frame, + (int)supported_broadcast_config[broadcast_target_config].blocks_per_sdu, + (int)supported_broadcast_config[broadcast_target_config].retransmission_number, + supported_broadcast_config[broadcast_target_config].max_transport_latency); return &supported_broadcast_config[broadcast_target_config]; } - void UpdateBroadcastOffloadConfig( - const broadcaster::BroadcastConfiguration& config) { + void UpdateBroadcastOffloadConfig(const broadcaster::BroadcastConfiguration& config) { if (config.subgroups.empty()) { broadcast_target_config = -1; return; @@ -546,37 +508,34 @@ struct codec_manager_impl { // Note: Currently only a single subgroup offloading is supported auto const& subgroup = config.subgroups.at(0); - auto subgroup_config = - subgroup.GetCommonBisCodecSpecData().GetAsCoreCodecConfig(); + auto subgroup_config = subgroup.GetCommonBisCodecSpecData().GetAsCoreCodecConfig(); offload_cfg.sampling_rate = subgroup_config.GetSamplingFrequencyHz(); offload_cfg.frame_duration = subgroup_config.GetFrameDurationUs(); - offload_cfg.octets_per_frame = subgroup_config.GetOctectsPerFrame(); + offload_cfg.octets_per_frame = subgroup_config.GetOctetsPerFrame(); offload_cfg.blocks_per_sdu = 1; offload_cfg.stream_map.resize(subgroup.GetNumBis()); log::info( - "stream_map.size(): {}, sampling_rate: {}, frame_duration(us): {}, " - "octets_per_frame: {}, blocks_per_sdu {}, retransmission_number: {}, " - "max_transport_latency: {}", - supported_broadcast_config[broadcast_target_config].stream_map.size(), - supported_broadcast_config[broadcast_target_config].sampling_rate, - supported_broadcast_config[broadcast_target_config].frame_duration, - supported_broadcast_config[broadcast_target_config].octets_per_frame, - (int)supported_broadcast_config[broadcast_target_config].blocks_per_sdu, - (int)supported_broadcast_config[broadcast_target_config] - .retransmission_number, - supported_broadcast_config[broadcast_target_config] - .max_transport_latency); + "stream_map.size(): {}, sampling_rate: {}, frame_duration(us): {}, " + "octets_per_frame: {}, blocks_per_sdu {}, retransmission_number: {}, " + "max_transport_latency: {}", + supported_broadcast_config[broadcast_target_config].stream_map.size(), + supported_broadcast_config[broadcast_target_config].sampling_rate, + supported_broadcast_config[broadcast_target_config].frame_duration, + supported_broadcast_config[broadcast_target_config].octets_per_frame, + (int)supported_broadcast_config[broadcast_target_config].blocks_per_sdu, + (int)supported_broadcast_config[broadcast_target_config].retransmission_number, + supported_broadcast_config[broadcast_target_config].max_transport_latency); } std::unique_ptr GetBroadcastConfig( - const CodecManager::BroadcastConfigurationRequirements& requirements) { + const CodecManager::BroadcastConfigurationRequirements& requirements) { if (GetCodecLocation() != types::CodecLocation::ADSP) { // Get the software supported broadcast configuration return std::make_unique( - ::bluetooth::le_audio::broadcaster::GetBroadcastConfig( - requirements.subgroup_quality)); + ::bluetooth::le_audio::broadcaster::GetBroadcastConfig( + requirements.subgroup_quality)); } /* Subgroups with different audio qualities is not being supported now, @@ -594,39 +553,35 @@ struct codec_manager_impl { log::assert_that(broadcast_local_source_hal_client != nullptr, "audio source hal client is NULL"); auto hal_config = broadcast_local_source_hal_client->GetBroadcastConfig( - requirements.subgroup_quality, requirements.sink_pacs); + requirements.subgroup_quality, requirements.sink_pacs); if (hal_config.has_value()) { UpdateBroadcastOffloadConfig(hal_config.value()); - return std::make_unique( - hal_config.value()); + return std::make_unique(hal_config.value()); } log::debug( - "No configuration received from AIDL, fall back to static " - "configuration."); + "No configuration received from AIDL, fall back to static " + "configuration."); } auto offload_config = GetBroadcastOffloadConfig(BIG_audio_quality); if (offload_config == nullptr) { - log::error("No Offload configuration supported for quality index: {}.", - BIG_audio_quality); + log::error("No Offload configuration supported for quality index: {}.", BIG_audio_quality); return nullptr; } types::LeAudioLtvMap codec_params; // Map sample freq. value to LE Audio codec specific config value - if (types::LeAudioCoreCodecConfig::sample_rate_map.count( - offload_config->sampling_rate)) { - codec_params.Add(codec_spec_conf::kLeAudioLtvTypeSamplingFreq, - types::LeAudioCoreCodecConfig::sample_rate_map.at( - offload_config->sampling_rate)); + if (types::LeAudioCoreCodecConfig::sample_rate_map.count(offload_config->sampling_rate)) { + codec_params.Add( + codec_spec_conf::kLeAudioLtvTypeSamplingFreq, + types::LeAudioCoreCodecConfig::sample_rate_map.at(offload_config->sampling_rate)); } // Map data interval value to LE Audio codec specific config value - if (types::LeAudioCoreCodecConfig::data_interval_map.count( - offload_config->frame_duration)) { - codec_params.Add(codec_spec_conf::kLeAudioLtvTypeFrameDuration, - types::LeAudioCoreCodecConfig::data_interval_map.at( - offload_config->frame_duration)); + if (types::LeAudioCoreCodecConfig::data_interval_map.count(offload_config->frame_duration)) { + codec_params.Add( + codec_spec_conf::kLeAudioLtvTypeFrameDuration, + types::LeAudioCoreCodecConfig::data_interval_map.at(offload_config->frame_duration)); } codec_params.Add(codec_spec_conf::kLeAudioLtvTypeOctetsPerCodecFrame, offload_config->octets_per_frame); @@ -634,31 +589,31 @@ struct codec_manager_impl { // Note: We do not support a different channel count on each BIS within the // same subgroup. uint8_t allocated_channel_count = - offload_config->stream_map.size() - ? std::bitset<32>{offload_config->stream_map.at(0).second}.count() - : 1; + offload_config->stream_map.size() + ? std::bitset<32>{offload_config->stream_map.at(0).second}.count() + : 1; bluetooth::le_audio::broadcaster::BroadcastSubgroupCodecConfig codec_config( - bluetooth::le_audio::broadcaster::kLeAudioCodecIdLc3, - {bluetooth::le_audio::broadcaster::BroadcastSubgroupBisCodecConfig( - static_cast(offload_config->stream_map.size()), - allocated_channel_count, codec_params)}, - offload_config->bits_per_sample); + bluetooth::le_audio::broadcaster::kLeAudioCodecIdLc3, + {bluetooth::le_audio::broadcaster::BroadcastSubgroupBisCodecConfig( + static_cast(offload_config->stream_map.size()), + allocated_channel_count, codec_params)}, + offload_config->bits_per_sample); bluetooth::le_audio::broadcaster::BroadcastQosConfig qos_config( - offload_config->retransmission_number, - offload_config->max_transport_latency); + offload_config->retransmission_number, offload_config->max_transport_latency); // Change the default software encoder config data path ID auto data_path = broadcaster::lc3_data_path; - data_path.dataPathId = - bluetooth::hci::iso_manager::kIsoDataPathPlatformDefault; + data_path.dataPathId = bluetooth::hci::iso_manager::kIsoDataPathPlatformDefault; uint16_t max_sdu_octets = 0; for (auto [_, allocation] : offload_config->stream_map) { auto alloc_channels_per_bis = std::bitset<32>{allocation}.count() ?: 1; - auto sdu_octets = offload_config->octets_per_frame * - offload_config->blocks_per_sdu * alloc_channels_per_bis; - if (max_sdu_octets < sdu_octets) max_sdu_octets = sdu_octets; + auto sdu_octets = offload_config->octets_per_frame * offload_config->blocks_per_sdu * + alloc_channels_per_bis; + if (max_sdu_octets < sdu_octets) { + max_sdu_octets = sdu_octets; + } } if (requirements.subgroup_quality.size() > 1) { @@ -666,23 +621,22 @@ struct codec_manager_impl { } return std::make_unique( - broadcaster::BroadcastConfiguration({ - .subgroups = {codec_config}, - .qos = qos_config, - .data_path = data_path, - .sduIntervalUs = offload_config->frame_duration, - .maxSduOctets = max_sdu_octets, - .phy = 0x02, // PHY_LE_2M - .packing = 0, // Sequential - .framing = 0 // Unframed, - })); + broadcaster::BroadcastConfiguration({ + .subgroups = {codec_config}, + .qos = qos_config, + .data_path = data_path, + .sduIntervalUs = offload_config->frame_duration, + .maxSduOctets = max_sdu_octets, + .phy = 0x02, // PHY_LE_2M + .packing = 0, // Sequential + .framing = 0 // Unframed, + })); } void UpdateBroadcastConnHandle( - const std::vector& conn_handle, - std::function< - void(const ::bluetooth::le_audio::broadcast_offload_config& config)> - update_receiver) { + const std::vector& conn_handle, + std::function + update_receiver) { if (GetCodecLocation() != le_audio::types::CodecLocation::ADSP) { return; } @@ -698,16 +652,15 @@ struct codec_manager_impl { "assert failed: conn_handle.size() == " "broadcast_config.stream_map.size()"); - if (broadcast_config.stream_map.size() == - LeAudioCodecConfiguration::kChannelNumberStereo) { + if (broadcast_config.stream_map.size() == LeAudioCodecConfiguration::kChannelNumberStereo) { broadcast_config.stream_map[0] = std::pair{ - conn_handle[0], codec_spec_conf::kLeAudioLocationFrontLeft}; + conn_handle[0], codec_spec_conf::kLeAudioLocationFrontLeft}; broadcast_config.stream_map[1] = std::pair{ - conn_handle[1], codec_spec_conf::kLeAudioLocationFrontRight}; + conn_handle[1], codec_spec_conf::kLeAudioLocationFrontRight}; } else if (broadcast_config.stream_map.size() == LeAudioCodecConfiguration::kChannelNumberMono) { broadcast_config.stream_map[0] = std::pair{ - conn_handle[0], codec_spec_conf::kLeAudioLocationFrontCenter}; + conn_handle[0], codec_spec_conf::kLeAudioLocationFrontCenter}; } update_receiver(broadcast_config); @@ -738,14 +691,13 @@ struct codec_manager_impl { } void UpdateCisConfiguration(const std::vector& cises, - const stream_parameters& stream_params, - uint8_t direction) { + const stream_parameters& stream_params, uint8_t direction) { if (GetCodecLocation() != bluetooth::le_audio::types::CodecLocation::ADSP) { return; } auto available_allocations = - AdjustAllocationForOffloader(stream_params.audio_channel_allocation); + AdjustAllocationForOffloader(stream_params.audio_channel_allocation); if (available_allocations == 0) { log::error("There is no CIS connected"); return; @@ -754,8 +706,7 @@ struct codec_manager_impl { auto& stream_map = offloader_stream_maps.get(direction); if (stream_map.streams_map_target.empty()) { stream_map.is_initial = true; - } else if (stream_map.is_initial || - LeAudioHalVerifier::SupportsStreamActiveApi()) { + } else if (stream_map.is_initial || LeAudioHalVerifier::SupportsStreamActiveApi()) { /* As multiple CISes phone call case, the target_allocation already have * the previous data, but the is_initial flag not be cleared. We need to * clear here to avoid make duplicated target allocation stream map. */ @@ -764,8 +715,7 @@ struct codec_manager_impl { stream_map.streams_map_current.clear(); stream_map.has_changed = true; - bool all_cises_connected = - (available_allocations == codec_spec_conf::kLeAudioLocationStereo); + bool all_cises_connected = (available_allocations == codec_spec_conf::kLeAudioLocationStereo); /* If all the cises are connected as stream started, reset changed_flag that * the bt stack wouldn't send another audio configuration for the connection @@ -774,13 +724,13 @@ struct codec_manager_impl { stream_map.has_changed = false; } - const std::string tag = types::BidirectionalPair( - {.sink = "Sink", .source = "Source"}) - .get(direction); + const std::string tag = + types::BidirectionalPair({.sink = "Sink", .source = "Source"}) + .get(direction); constexpr types::BidirectionalPair cis_types = { - .sink = types::CisType::CIS_TYPE_UNIDIRECTIONAL_SINK, - .source = types::CisType::CIS_TYPE_UNIDIRECTIONAL_SOURCE}; + .sink = types::CisType::CIS_TYPE_UNIDIRECTIONAL_SINK, + .source = types::CisType::CIS_TYPE_UNIDIRECTIONAL_SOURCE}; auto cis_type = cis_types.get(direction); for (auto const& cis_entry : cises) { @@ -805,53 +755,47 @@ struct codec_manager_impl { if (target_allocation == 0) { /* Take missing allocation for that one .*/ - target_allocation = - codec_spec_conf::kLeAudioLocationStereo & ~available_allocations; + target_allocation = codec_spec_conf::kLeAudioLocationStereo & ~available_allocations; } log::info( - "{}: Cis handle 0x{:04x}, target allocation 0x{:08x}, current " - "allocation 0x{:08x}, active: {}", - tag, cis_entry.conn_handle, target_allocation, current_allocation, - is_active); - - if (stream_map.is_initial || - LeAudioHalVerifier::SupportsStreamActiveApi()) { - stream_map.streams_map_target.emplace_back(stream_map_info( - cis_entry.conn_handle, target_allocation, is_active)); + "{}: Cis handle 0x{:04x}, target allocation 0x{:08x}, current " + "allocation 0x{:08x}, active: {}", + tag, cis_entry.conn_handle, target_allocation, current_allocation, is_active); + + if (stream_map.is_initial || LeAudioHalVerifier::SupportsStreamActiveApi()) { + stream_map.streams_map_target.emplace_back( + stream_map_info(cis_entry.conn_handle, target_allocation, is_active)); } - stream_map.streams_map_current.emplace_back(stream_map_info( - cis_entry.conn_handle, current_allocation, is_active)); + stream_map.streams_map_current.emplace_back( + stream_map_info(cis_entry.conn_handle, current_allocation, is_active)); } } } - private: +private: void SetCodecLocation(CodecLocation location) { - if (offload_enable_ == false) return; + if (offload_enable_ == false) { + return; + } codec_location_ = location; } - bool IsLc3ConfigMatched( - const set_configurations::CodecConfigSetting& target_config, - const set_configurations::CodecConfigSetting& adsp_config) { + bool IsLc3ConfigMatched(const set_configurations::CodecConfigSetting& target_config, + const set_configurations::CodecConfigSetting& adsp_config) { if (adsp_config.id.coding_format != types::kLeAudioCodingFormatLC3 || target_config.id.coding_format != types::kLeAudioCodingFormatLC3) { return false; } - const types::LeAudioCoreCodecConfig adsp_lc3_config = - adsp_config.params.GetAsCoreCodecConfig(); + const types::LeAudioCoreCodecConfig adsp_lc3_config = adsp_config.params.GetAsCoreCodecConfig(); const types::LeAudioCoreCodecConfig target_lc3_config = - target_config.params.GetAsCoreCodecConfig(); + target_config.params.GetAsCoreCodecConfig(); - if (adsp_lc3_config.sampling_frequency != - target_lc3_config.sampling_frequency || + if (adsp_lc3_config.sampling_frequency != target_lc3_config.sampling_frequency || adsp_lc3_config.frame_duration != target_lc3_config.frame_duration || - adsp_config.GetChannelCountPerIsoStream() != - target_config.GetChannelCountPerIsoStream() || - adsp_lc3_config.octets_per_codec_frame != - target_lc3_config.octets_per_codec_frame) { + adsp_config.GetChannelCountPerIsoStream() != target_config.GetChannelCountPerIsoStream() || + adsp_lc3_config.octets_per_codec_frame != target_lc3_config.octets_per_codec_frame) { return false; } @@ -864,18 +808,17 @@ struct codec_manager_impl { return IsLc3ConfigMatched(software_ase_config.codec, adsp_ase_config.codec); } - bool IsAudioSetConfigurationMatched( - const AudioSetConfiguration* software_audio_set_conf, - std::unordered_set& offload_preference_set, - const std::vector& adsp_capabilities) { + bool IsAudioSetConfigurationMatched(const AudioSetConfiguration* software_audio_set_conf, + std::unordered_set& offload_preference_set, + const std::vector& adsp_capabilities) { if (software_audio_set_conf->confs.sink.empty() && software_audio_set_conf->confs.source.empty()) { return false; } // No match if the codec is not on the preference list - for (auto direction : {le_audio::types::kLeAudioDirectionSink, - le_audio::types::kLeAudioDirectionSource}) { + for (auto direction : + {le_audio::types::kLeAudioDirectionSink, le_audio::types::kLeAudioDirectionSource}) { for (auto const& conf : software_audio_set_conf->confs.get(direction)) { if (offload_preference_set.find(conf.codec.id.coding_format) == offload_preference_set.end()) { @@ -889,12 +832,10 @@ struct codec_manager_impl { size_t match_cnt = 0; size_t expected_match_cnt = 0; - for (auto direction : {le_audio::types::kLeAudioDirectionSink, - le_audio::types::kLeAudioDirectionSource}) { - auto const& software_set_ase_confs = - software_audio_set_conf->confs.get(direction); - auto const& adsp_set_ase_confs = - adsp_audio_set_conf.confs.get(direction); + for (auto direction : + {le_audio::types::kLeAudioDirectionSink, le_audio::types::kLeAudioDirectionSource}) { + auto const& software_set_ase_confs = software_audio_set_conf->confs.get(direction); + auto const& adsp_set_ase_confs = adsp_audio_set_conf.confs.get(direction); if (!software_set_ase_confs.size() || !adsp_set_ase_confs.size()) { continue; @@ -902,10 +843,9 @@ struct codec_manager_impl { // Check for number of ASEs mismatch if (adsp_set_ase_confs.size() != software_set_ase_confs.size()) { - log::error( - "{}: ADSP config size mismatches the software: {} != {}", - direction == types::kLeAudioDirectionSink ? "Sink" : "Source", - adsp_set_ase_confs.size(), software_set_ase_confs.size()); + log::error("{}: ADSP config size mismatches the software: {} != {}", + direction == types::kLeAudioDirectionSink ? "Sink" : "Source", + adsp_set_ase_confs.size(), software_set_ase_confs.size()); continue; } @@ -957,74 +897,57 @@ struct codec_manager_impl { case 8000: return bluetooth::le_audio::codec_spec_caps::kLeAudioSamplingFreq8000Hz; case 16000: - return bluetooth::le_audio::codec_spec_caps:: - kLeAudioSamplingFreq16000Hz; + return bluetooth::le_audio::codec_spec_caps::kLeAudioSamplingFreq16000Hz; case 24000: - return bluetooth::le_audio::codec_spec_caps:: - kLeAudioSamplingFreq24000Hz; + return bluetooth::le_audio::codec_spec_caps::kLeAudioSamplingFreq24000Hz; case 32000: - return bluetooth::le_audio::codec_spec_caps:: - kLeAudioSamplingFreq32000Hz; + return bluetooth::le_audio::codec_spec_caps::kLeAudioSamplingFreq32000Hz; case 44100: - return bluetooth::le_audio::codec_spec_caps:: - kLeAudioSamplingFreq44100Hz; + return bluetooth::le_audio::codec_spec_caps::kLeAudioSamplingFreq44100Hz; case 48000: - return bluetooth::le_audio::codec_spec_caps:: - kLeAudioSamplingFreq48000Hz; + return bluetooth::le_audio::codec_spec_caps::kLeAudioSamplingFreq48000Hz; } return bluetooth::le_audio::codec_spec_caps::kLeAudioSamplingFreq8000Hz; } - void storeLocalCapa( - std::vector< - ::bluetooth::le_audio::set_configurations::AudioSetConfiguration>& - adsp_capabilities, - const std::vector& offload_preference_set) { + void storeLocalCapa(std::vector<::bluetooth::le_audio::set_configurations::AudioSetConfiguration>& + adsp_capabilities, + const std::vector& offload_preference_set) { log::debug("Print adsp_capabilities:"); for (auto& adsp : adsp_capabilities) { log::debug("'{}':", adsp.name); - for (auto direction : {le_audio::types::kLeAudioDirectionSink, - le_audio::types::kLeAudioDirectionSource}) { - log::debug( - "dir: {}: number of confs {}:", - direction == types::kLeAudioDirectionSink ? "sink" : "source", - (int)(adsp.confs.get(direction).size())); + for (auto direction : + {le_audio::types::kLeAudioDirectionSink, le_audio::types::kLeAudioDirectionSource}) { + log::debug("dir: {}: number of confs {}:", + direction == types::kLeAudioDirectionSink ? "sink" : "source", + (int)(adsp.confs.get(direction).size())); for (auto conf : adsp.confs.sink) { - log::debug( - "codecId: {}, sample_freq: {}, interval {}, channel_cnt: {}", - conf.codec.id.coding_format, conf.codec.GetSamplingFrequencyHz(), - conf.codec.GetDataIntervalUs(), - conf.codec.GetChannelCountPerIsoStream()); + log::debug("codecId: {}, sample_freq: {}, interval {}, channel_cnt: {}", + conf.codec.id.coding_format, conf.codec.GetSamplingFrequencyHz(), + conf.codec.GetDataIntervalUs(), conf.codec.GetChannelCountPerIsoStream()); /* TODO: How to get bits_per_sample ? */ btle_audio_codec_config_t capa_to_add = { - .codec_type = (conf.codec.id.coding_format == - types::kLeAudioCodingFormatLC3) - ? btle_audio_codec_index_t:: - LE_AUDIO_CODEC_INDEX_SOURCE_LC3 - : btle_audio_codec_index_t:: - LE_AUDIO_CODEC_INDEX_SOURCE_INVALID, - .sample_rate = utils::translateToBtLeAudioCodecConfigSampleRate( - conf.codec.GetSamplingFrequencyHz()), - .bits_per_sample = - utils::translateToBtLeAudioCodecConfigBitPerSample(16), - .channel_count = - utils::translateToBtLeAudioCodecConfigChannelCount( - conf.codec.GetChannelCountPerIsoStream()), - .frame_duration = - utils::translateToBtLeAudioCodecConfigFrameDuration( - conf.codec.GetDataIntervalUs()), + .codec_type = + (conf.codec.id.coding_format == types::kLeAudioCodingFormatLC3) + ? btle_audio_codec_index_t::LE_AUDIO_CODEC_INDEX_SOURCE_LC3 + : btle_audio_codec_index_t::LE_AUDIO_CODEC_INDEX_SOURCE_INVALID, + .sample_rate = utils::translateToBtLeAudioCodecConfigSampleRate( + conf.codec.GetSamplingFrequencyHz()), + .bits_per_sample = utils::translateToBtLeAudioCodecConfigBitPerSample(16), + .channel_count = utils::translateToBtLeAudioCodecConfigChannelCount( + conf.codec.GetChannelCountPerIsoStream()), + .frame_duration = utils::translateToBtLeAudioCodecConfigFrameDuration( + conf.codec.GetDataIntervalUs()), }; - auto& capa_container = (direction == types::kLeAudioDirectionSink) - ? codec_output_capa - : codec_input_capa; - if (std::find(capa_container.begin(), capa_container.end(), - capa_to_add) == capa_container.end()) { + auto& capa_container = (direction == types::kLeAudioDirectionSink) ? codec_output_capa + : codec_input_capa; + if (std::find(capa_container.begin(), capa_container.end(), capa_to_add) == + capa_container.end()) { log::debug("Adding {} capa {}", - (direction == types::kLeAudioDirectionSink) ? "output" - : "input", + (direction == types::kLeAudioDirectionSink) ? "output" : "input", static_cast(capa_container.size())); capa_container.push_back(capa_to_add); } @@ -1032,12 +955,10 @@ struct codec_manager_impl { } } - log::debug("Output capa: {}, Input capa: {}", - static_cast(codec_output_capa.size()), + log::debug("Output capa: {}, Input capa: {}", static_cast(codec_output_capa.size()), static_cast(codec_input_capa.size())); - log::debug("Print offload_preference_set: {}", - (int)(offload_preference_set.size())); + log::debug("Print offload_preference_set: {}", (int)(offload_preference_set.size())); int i = 0; for (auto set : offload_preference_set) { @@ -1046,7 +967,7 @@ struct codec_manager_impl { } void UpdateOffloadCapability( - const std::vector& offloading_preference) { + const std::vector& offloading_preference) { log::info(""); std::unordered_set offload_preference_set; @@ -1055,11 +976,9 @@ struct codec_manager_impl { return; } - auto adsp_capabilities = - ::bluetooth::audio::le_audio::get_offload_capabilities(); + auto adsp_capabilities = ::bluetooth::audio::le_audio::get_offload_capabilities(); - storeLocalCapa(adsp_capabilities.unicast_offload_capabilities, - offloading_preference); + storeLocalCapa(adsp_capabilities.unicast_offload_capabilities, offloading_preference); for (auto codec : offloading_preference) { auto it = btle_audio_codec_type_map_.find(codec.codec_type); @@ -1069,32 +988,27 @@ struct codec_manager_impl { } } - for (types::LeAudioContextType ctx_type : - types::kLeAudioContextAllTypesArray) { + for (types::LeAudioContextType ctx_type : types::kLeAudioContextAllTypesArray) { // Gets the software supported context type and the corresponding config // priority const AudioSetConfigurations* software_audio_set_confs = - AudioSetConfigurationProvider::Get()->GetConfigurations(ctx_type); + AudioSetConfigurationProvider::Get()->GetConfigurations(ctx_type); for (const auto& software_audio_set_conf : *software_audio_set_confs) { - if (IsAudioSetConfigurationMatched( - software_audio_set_conf, offload_preference_set, - adsp_capabilities.unicast_offload_capabilities)) { - log::info("Offload supported conf, context type: {}, settings -> {}", - (int)ctx_type, software_audio_set_conf->name); + if (IsAudioSetConfigurationMatched(software_audio_set_conf, offload_preference_set, + adsp_capabilities.unicast_offload_capabilities)) { + log::info("Offload supported conf, context type: {}, settings -> {}", (int)ctx_type, + software_audio_set_conf->name); if (dual_bidirection_swb_supported_ && - AudioSetConfigurationProvider::Get() - ->CheckConfigurationIsDualBiDirSwb( + AudioSetConfigurationProvider::Get()->CheckConfigurationIsDualBiDirSwb( *software_audio_set_conf)) { offload_dual_bidirection_swb_supported_ = true; } - context_type_offload_config_map_[ctx_type].push_back( - software_audio_set_conf); + context_type_offload_config_map_[ctx_type].push_back(software_audio_set_conf); } } } - UpdateSupportedBroadcastConfig( - adsp_capabilities.broadcast_offload_capabilities); + UpdateSupportedBroadcastConfig(adsp_capabilities.broadcast_offload_capabilities); } CodecLocation codec_location_ = CodecLocation::HOST; @@ -1102,14 +1016,11 @@ struct codec_manager_impl { bool offload_dual_bidirection_swb_supported_ = false; bool dual_bidirection_swb_supported_ = false; types::BidirectionalPair offloader_stream_maps; - std::vector - supported_broadcast_config; + std::vector supported_broadcast_config; std::unordered_map - context_type_offload_config_map_; - std::unordered_map - btle_audio_codec_type_map_ = { - {::bluetooth::le_audio::LE_AUDIO_CODEC_INDEX_SOURCE_LC3, - types::kLeAudioCodingFormatLC3}}; + context_type_offload_config_map_; + std::unordered_map btle_audio_codec_type_map_ = { + {::bluetooth::le_audio::LE_AUDIO_CODEC_INDEX_SOURCE_LC3, types::kLeAudioCodingFormatLC3}}; std::vector codec_input_capa = {}; std::vector codec_output_capa = {}; @@ -1120,9 +1031,8 @@ struct codec_manager_impl { LeAudioSourceAudioHalClient* broadcast_local_source_hal_client = nullptr; }; -std::ostream& operator<<( - std::ostream& os, - const CodecManager::UnicastConfigurationRequirements& req) { +std::ostream& operator<<(std::ostream& os, + const CodecManager::UnicastConfigurationRequirements& req) { os << "{audio context type: " << req.audio_context_type; if (req.sink_pacs.has_value()) { os << ", sink_pacs: ["; @@ -1136,8 +1046,7 @@ std::ostream& operator<<( } os << "\b\b]"; } else { - os << ", sink_pacs: " - << "None"; + os << ", sink_pacs: " << "None"; } if (req.source_pacs.has_value()) { @@ -1152,8 +1061,7 @@ std::ostream& operator<<( } os << "\b\b]"; } else { - os << ", source_pacs: " - << "None"; + os << ", source_pacs: " << "None"; } if (req.sink_requirements.has_value()) { @@ -1187,10 +1095,8 @@ std::ostream& operator<<( struct CodecManager::impl { impl(const CodecManager& codec_manager) : codec_manager_(codec_manager) {} - void Start( - const std::vector& offloading_preference) { - log::assert_that(!codec_manager_impl_, - "assert failed: !codec_manager_impl_"); + void Start(const std::vector& offloading_preference) { + log::assert_that(!codec_manager_impl_, "assert failed: !codec_manager_impl_"); codec_manager_impl_ = std::make_unique(); codec_manager_impl_->start(offloading_preference); } @@ -1209,13 +1115,16 @@ struct CodecManager::impl { CodecManager::CodecManager() : pimpl_(std::make_unique(*this)) {} -void CodecManager::Start( - const std::vector& offloading_preference) { - if (!pimpl_->IsRunning()) pimpl_->Start(offloading_preference); +void CodecManager::Start(const std::vector& offloading_preference) { + if (!pimpl_->IsRunning()) { + pimpl_->Start(offloading_preference); + } } void CodecManager::Stop() { - if (pimpl_->IsRunning()) pimpl_->Stop(); + if (pimpl_->IsRunning()) { + pimpl_->Stop(); + } } types::CodecLocation CodecManager::GetCodecLocation(void) const { @@ -1254,37 +1163,36 @@ CodecManager::GetLocalAudioInputCodecCapa() { } void CodecManager::UpdateActiveAudioConfig( - const types::BidirectionalPair& stream_params, - types::BidirectionalPair delays_ms, - std::function - update_receiver) { - if (pimpl_->IsRunning()) - pimpl_->codec_manager_impl_->UpdateActiveAudioConfig( - stream_params, delays_ms, update_receiver); + const types::BidirectionalPair& stream_params, + types::BidirectionalPair delays_ms, + std::function update_receiver) { + if (pimpl_->IsRunning()) { + pimpl_->codec_manager_impl_->UpdateActiveAudioConfig(stream_params, delays_ms, update_receiver); + } } bool CodecManager::UpdateActiveUnicastAudioHalClient( - LeAudioSourceAudioHalClient* source_unicast_client, - LeAudioSinkAudioHalClient* sink_unicast_client, bool is_active) { + LeAudioSourceAudioHalClient* source_unicast_client, + LeAudioSinkAudioHalClient* sink_unicast_client, bool is_active) { if (pimpl_->IsRunning()) { return pimpl_->codec_manager_impl_->UpdateActiveUnicastAudioHalClient( - source_unicast_client, sink_unicast_client, is_active); + source_unicast_client, sink_unicast_client, is_active); } return false; } bool CodecManager::UpdateActiveBroadcastAudioHalClient( - LeAudioSourceAudioHalClient* source_broadcast_client, bool is_active) { + LeAudioSourceAudioHalClient* source_broadcast_client, bool is_active) { if (pimpl_->IsRunning()) { - return pimpl_->codec_manager_impl_->UpdateActiveBroadcastAudioHalClient( - source_broadcast_client, is_active); + return pimpl_->codec_manager_impl_->UpdateActiveBroadcastAudioHalClient(source_broadcast_client, + is_active); } return false; } std::unique_ptr CodecManager::GetCodecConfig( - const CodecManager::UnicastConfigurationRequirements& requirements, - CodecManager::UnicastConfigurationVerifier verifier) { + const CodecManager::UnicastConfigurationRequirements& requirements, + CodecManager::UnicastConfigurationVerifier verifier) { if (pimpl_->IsRunning()) { return pimpl_->codec_manager_impl_->GetCodecConfig(requirements, verifier); } @@ -1293,7 +1201,7 @@ std::unique_ptr CodecManager::GetCodecConfig( } bool CodecManager::CheckCodecConfigIsBiDirSwb( - const set_configurations::AudioSetConfiguration& config) const { + const set_configurations::AudioSetConfiguration& config) const { if (pimpl_->IsRunning()) { return pimpl_->codec_manager_impl_->CheckCodecConfigIsBiDirSwb(config); } @@ -1301,17 +1209,15 @@ bool CodecManager::CheckCodecConfigIsBiDirSwb( } bool CodecManager::CheckCodecConfigIsDualBiDirSwb( - const set_configurations::AudioSetConfiguration& config) const { + const set_configurations::AudioSetConfiguration& config) const { if (pimpl_->IsRunning()) { return pimpl_->codec_manager_impl_->CheckCodecConfigIsDualBiDirSwb(config); } return false; } -std::unique_ptr -CodecManager::GetBroadcastConfig( - const CodecManager::BroadcastConfigurationRequirements& requirements) - const { +std::unique_ptr CodecManager::GetBroadcastConfig( + const CodecManager::BroadcastConfigurationRequirements& requirements) const { if (pimpl_->IsRunning()) { return pimpl_->codec_manager_impl_->GetBroadcastConfig(requirements); } @@ -1320,22 +1226,19 @@ CodecManager::GetBroadcastConfig( } void CodecManager::UpdateBroadcastConnHandle( - const std::vector& conn_handle, - std::function< - void(const ::bluetooth::le_audio::broadcast_offload_config& config)> - update_receiver) { + const std::vector& conn_handle, + std::function + update_receiver) { if (pimpl_->IsRunning()) { - return pimpl_->codec_manager_impl_->UpdateBroadcastConnHandle( - conn_handle, update_receiver); + return pimpl_->codec_manager_impl_->UpdateBroadcastConnHandle(conn_handle, update_receiver); } } -void CodecManager::UpdateCisConfiguration( - const std::vector& cises, - const stream_parameters& stream_params, uint8_t direction) { +void CodecManager::UpdateCisConfiguration(const std::vector& cises, + const stream_parameters& stream_params, + uint8_t direction) { if (pimpl_->IsRunning()) { - return pimpl_->codec_manager_impl_->UpdateCisConfiguration( - cises, stream_params, direction); + return pimpl_->codec_manager_impl_->UpdateCisConfiguration(cises, stream_params, direction); } } diff --git a/system/bta/le_audio/codec_manager.h b/system/bta/le_audio/codec_manager.h index 59fa3bd3a14..92c0e0e2795 100644 --- a/system/bta/le_audio/codec_manager.h +++ b/system/bta/le_audio/codec_manager.h @@ -30,8 +30,7 @@ class LeAudioSinkAudioHalClient; class LeAudioSourceAudioHalClient; struct stream_map_info { - stream_map_info(uint16_t stream_handle, uint32_t audio_channel_allocation, - bool is_stream_active) + stream_map_info(uint16_t stream_handle, uint32_t audio_channel_allocation, bool is_stream_active) : stream_handle(stream_handle), audio_channel_allocation(audio_channel_allocation), is_stream_active(is_stream_active) {} @@ -62,7 +61,7 @@ struct broadcast_offload_config { }; class CodecManager { - public: +public: struct UnicastConfigurationRequirements { ::bluetooth::le_audio::types::LeAudioContextType audio_context_type; std::optional> sink_pacs; @@ -85,14 +84,13 @@ class CodecManager { * Note: Used only with the legacy AudioSetConfigurationProvider. */ typedef std::function - UnicastConfigurationVerifier; + const UnicastConfigurationRequirements& requirements, + const set_configurations::AudioSetConfigurations* confs)> + UnicastConfigurationVerifier; struct BroadcastConfigurationRequirements { - std::vector< - std::pair> - subgroup_quality; + std::vector> + subgroup_quality; std::optional> sink_pacs; }; @@ -101,64 +99,54 @@ class CodecManager { static CodecManager* instance = new CodecManager(); return instance; } - void Start(const std::vector& - offloading_preference); + void Start( + const std::vector& offloading_preference); void Stop(void); virtual types::CodecLocation GetCodecLocation(void) const; virtual bool IsDualBiDirSwbSupported(void) const; - virtual void UpdateCisConfiguration( - const std::vector& cises, - const stream_parameters& stream_params, uint8_t direction); + virtual void UpdateCisConfiguration(const std::vector& cises, + const stream_parameters& stream_params, uint8_t direction); virtual void ClearCisConfiguration(uint8_t direction); virtual bool IsUsingCodecExtensibility() const; - virtual bool UpdateActiveUnicastAudioHalClient( - LeAudioSourceAudioHalClient* source_unicast_client, - LeAudioSinkAudioHalClient* sink_unicast_client, bool is_active); + virtual bool UpdateActiveUnicastAudioHalClient(LeAudioSourceAudioHalClient* source_unicast_client, + LeAudioSinkAudioHalClient* sink_unicast_client, + bool is_active); virtual bool UpdateActiveBroadcastAudioHalClient( - LeAudioSourceAudioHalClient* source_broadcast_client, bool is_active); + LeAudioSourceAudioHalClient* source_broadcast_client, bool is_active); virtual void UpdateActiveAudioConfig( - const types::BidirectionalPair& stream_params, - types::BidirectionalPair delays_ms, - std::function - update_receiver); - virtual std::unique_ptr< - ::bluetooth::le_audio::set_configurations::AudioSetConfiguration> + const types::BidirectionalPair& stream_params, + types::BidirectionalPair delays_ms, + std::function update_receiver); + virtual std::unique_ptr<::bluetooth::le_audio::set_configurations::AudioSetConfiguration> GetCodecConfig(const UnicastConfigurationRequirements& requirements, UnicastConfigurationVerifier verifier); virtual bool CheckCodecConfigIsBiDirSwb( - const ::bluetooth::le_audio::set_configurations::AudioSetConfiguration& - config) const; + const ::bluetooth::le_audio::set_configurations::AudioSetConfiguration& config) const; virtual bool CheckCodecConfigIsDualBiDirSwb( - const ::bluetooth::le_audio::set_configurations::AudioSetConfiguration& - config) const; - virtual std::unique_ptr - GetBroadcastConfig( - const BroadcastConfigurationRequirements& requirements) const; + const ::bluetooth::le_audio::set_configurations::AudioSetConfiguration& config) const; + virtual std::unique_ptr GetBroadcastConfig( + const BroadcastConfigurationRequirements& requirements) const; virtual void UpdateBroadcastConnHandle( - const std::vector& conn_handle, - std::function< - void(const ::bluetooth::le_audio::broadcast_offload_config& config)> - update_receiver); + const std::vector& conn_handle, + std::function + update_receiver); virtual std::vector GetLocalAudioOutputCodecCapa(); - virtual std::vector - GetLocalAudioInputCodecCapa(); + virtual std::vector GetLocalAudioInputCodecCapa(); - private: +private: CodecManager(); struct impl; std::unique_ptr pimpl_; }; -std::ostream& operator<<( - std::ostream& os, - const CodecManager::UnicastConfigurationRequirements& req); +std::ostream& operator<<(std::ostream& os, + const CodecManager::UnicastConfigurationRequirements& req); } // namespace bluetooth::le_audio namespace fmt { template <> -struct formatter< - bluetooth::le_audio::CodecManager::UnicastConfigurationRequirements> +struct formatter : ostream_formatter {}; } // namespace fmt diff --git a/system/bta/le_audio/codec_manager_test.cc b/system/bta/le_audio/codec_manager_test.cc index 44faaa58f1f..5eda56c35ec 100644 --- a/system/bta/le_audio/codec_manager_test.cc +++ b/system/bta/le_audio/codec_manager_test.cc @@ -49,19 +49,16 @@ void osi_property_set_bool(const char* key, bool value); template T& bluetooth::le_audio::types::BidirectionalPair::get(uint8_t direction) { - return (direction == bluetooth::le_audio::types::kLeAudioDirectionSink) - ? sink - : source; + return (direction == bluetooth::le_audio::types::kLeAudioDirectionSink) ? sink : source; } static const std::vector offload_capabilities_none(0); -const std::vector* offload_capabilities = - &offload_capabilities_none; +const std::vector* offload_capabilities = &offload_capabilities_none; static const char* test_flags[] = { - "INIT_default_log_level_str=LOG_VERBOSE", - nullptr, + "INIT_default_log_level_str=LOG_VERBOSE", + nullptr, }; const std::string kSmpOptions("mock smp options"); @@ -81,36 +78,30 @@ bool get_pts_le_audio_disable_ases_before_stopping(void) { return false; } config_t* get_all(void) { return nullptr; } stack_config_t mock_stack_config{ - .get_pts_avrcp_test = get_pts_avrcp_test, - .get_pts_secure_only_mode = get_pts_secure_only_mode, - .get_pts_conn_updates_disabled = get_pts_conn_updates_disabled, - .get_pts_crosskey_sdp_disable = get_pts_crosskey_sdp_disable, - .get_pts_smp_options = get_pts_smp_options, - .get_pts_smp_failure_case = get_pts_smp_failure_case, - .get_pts_force_eatt_for_notifications = - get_pts_force_eatt_for_notifications, - .get_pts_connect_eatt_unconditionally = - get_pts_connect_eatt_unconditionally, - .get_pts_connect_eatt_before_encryption = - get_pts_connect_eatt_before_encryption, - .get_pts_unencrypt_broadcast = get_pts_unencrypt_broadcast, - .get_pts_eatt_peripheral_collision_support = - get_pts_eatt_peripheral_collision_support, - .get_pts_force_le_audio_multiple_contexts_metadata = - get_pts_force_le_audio_multiple_contexts_metadata, - .get_pts_le_audio_disable_ases_before_stopping = - get_pts_le_audio_disable_ases_before_stopping, - .get_all = get_all, + .get_pts_avrcp_test = get_pts_avrcp_test, + .get_pts_secure_only_mode = get_pts_secure_only_mode, + .get_pts_conn_updates_disabled = get_pts_conn_updates_disabled, + .get_pts_crosskey_sdp_disable = get_pts_crosskey_sdp_disable, + .get_pts_smp_options = get_pts_smp_options, + .get_pts_smp_failure_case = get_pts_smp_failure_case, + .get_pts_force_eatt_for_notifications = get_pts_force_eatt_for_notifications, + .get_pts_connect_eatt_unconditionally = get_pts_connect_eatt_unconditionally, + .get_pts_connect_eatt_before_encryption = get_pts_connect_eatt_before_encryption, + .get_pts_unencrypt_broadcast = get_pts_unencrypt_broadcast, + .get_pts_eatt_peripheral_collision_support = get_pts_eatt_peripheral_collision_support, + .get_pts_force_le_audio_multiple_contexts_metadata = + get_pts_force_le_audio_multiple_contexts_metadata, + .get_pts_le_audio_disable_ases_before_stopping = + get_pts_le_audio_disable_ases_before_stopping, + .get_all = get_all, }; -const stack_config_t* stack_config_get_interface(void) { - return &mock_stack_config; -} +const stack_config_t* stack_config_get_interface(void) { return &mock_stack_config; } namespace server_configurable_flags { -std::string GetServerConfigurableFlag( - const std::string& experiment_category_name, - const std::string& experiment_flag_name, const std::string& default_value) { +std::string GetServerConfigurableFlag(const std::string& experiment_category_name, + const std::string& experiment_flag_name, + const std::string& default_value) { return ""; } } // namespace server_configurable_flags @@ -129,25 +120,25 @@ namespace bluetooth::le_audio { class MockLeAudioSourceHalClient; MockLeAudioSourceHalClient* mock_le_audio_source_hal_client_; -std::unique_ptr - owned_mock_le_audio_source_hal_client_; +std::unique_ptr owned_mock_le_audio_source_hal_client_; bool is_audio_unicast_source_acquired; bool is_audio_broadcast_source_acquired; -std::unique_ptr -LeAudioSourceAudioHalClient::AcquireUnicast() { - if (is_audio_unicast_source_acquired) return nullptr; +std::unique_ptr LeAudioSourceAudioHalClient::AcquireUnicast() { + if (is_audio_unicast_source_acquired) { + return nullptr; + } is_audio_unicast_source_acquired = true; return std::move(owned_mock_le_audio_source_hal_client_); } MockLeAudioSourceHalClient* mock_broadcast_le_audio_source_hal_client_; -std::unique_ptr - owned_mock_broadcast_le_audio_source_hal_client_; +std::unique_ptr owned_mock_broadcast_le_audio_source_hal_client_; -std::unique_ptr -LeAudioSourceAudioHalClient::AcquireBroadcast() { - if (is_audio_broadcast_source_acquired) return nullptr; +std::unique_ptr LeAudioSourceAudioHalClient::AcquireBroadcast() { + if (is_audio_broadcast_source_acquired) { + return nullptr; + } is_audio_broadcast_source_acquired = true; return std::move(owned_mock_broadcast_le_audio_source_hal_client_); } @@ -159,161 +150,138 @@ MockLeAudioSinkHalClient* mock_le_audio_sink_hal_client_; std::unique_ptr owned_mock_le_audio_sink_hal_client_; bool is_audio_unicast_sink_acquired; -std::unique_ptr -LeAudioSinkAudioHalClient::AcquireUnicast() { - if (is_audio_unicast_sink_acquired) return nullptr; +std::unique_ptr LeAudioSinkAudioHalClient::AcquireUnicast() { + if (is_audio_unicast_sink_acquired) { + return nullptr; + } is_audio_unicast_sink_acquired = true; return std::move(owned_mock_le_audio_sink_hal_client_); } class MockLeAudioSinkHalClient : public LeAudioSinkAudioHalClient { - public: +public: MockLeAudioSinkHalClient() = default; MOCK_METHOD((bool), Start, (const LeAudioCodecConfiguration& codecConfiguration, - LeAudioSinkAudioHalClient::Callbacks* audioReceiver, - DsaModes dsa_modes), + LeAudioSinkAudioHalClient::Callbacks* audioReceiver, DsaModes dsa_modes), (override)); MOCK_METHOD((void), Stop, (), (override)); - MOCK_METHOD((size_t), SendData, (uint8_t * data, uint16_t size), (override)); + MOCK_METHOD((size_t), SendData, (uint8_t* data, uint16_t size), (override)); MOCK_METHOD((void), ConfirmStreamingRequest, (), (override)); MOCK_METHOD((void), CancelStreamingRequest, (), (override)); MOCK_METHOD((void), UpdateRemoteDelay, (uint16_t delay), (override)); - MOCK_METHOD((void), UpdateAudioConfigToHal, - (const ::bluetooth::le_audio::offload_config&), (override)); + MOCK_METHOD((void), UpdateAudioConfigToHal, (const ::bluetooth::le_audio::offload_config&), + (override)); MOCK_METHOD((void), SuspendedForReconfiguration, (), (override)); MOCK_METHOD((void), ReconfigurationComplete, (), (override)); - MOCK_METHOD( - (std::optional), GetBroadcastConfig, - ((const std::vector>&), - (const std::optional< - std::vector<::bluetooth::le_audio::types::acs_ac_record>>&)), - (const override)); - - MOCK_METHOD( - (std::optional< - ::bluetooth::le_audio::set_configurations::AudioSetConfiguration>), - GetUnicastConfig, - (types::LeAudioContextType, - std::optional< - const ::bluetooth::le_audio::types::PublishedAudioCapabilities*>, - std::optional< - const ::bluetooth::le_audio::types::PublishedAudioCapabilities*>), - (const override)); + MOCK_METHOD((std::optional), GetBroadcastConfig, + ((const std::vector>&), + (const std::optional>&)), + (const override)); + + MOCK_METHOD((std::optional<::bluetooth::le_audio::set_configurations::AudioSetConfiguration>), + GetUnicastConfig, + (types::LeAudioContextType, + std::optional, + std::optional), + (const override)); MOCK_METHOD((void), OnDestroyed, ()); virtual ~MockLeAudioSinkHalClient() override { OnDestroyed(); } }; class MockLeAudioSourceHalClient : public LeAudioSourceAudioHalClient { - public: +public: MockLeAudioSourceHalClient() = default; MOCK_METHOD((bool), Start, (const LeAudioCodecConfiguration& codecConfiguration, - LeAudioSourceAudioHalClient::Callbacks* audioReceiver, - DsaModes dsa_modes), + LeAudioSourceAudioHalClient::Callbacks* audioReceiver, DsaModes dsa_modes), (override)); MOCK_METHOD((void), Stop, (), (override)); MOCK_METHOD((void), ConfirmStreamingRequest, (), (override)); MOCK_METHOD((void), CancelStreamingRequest, (), (override)); MOCK_METHOD((void), UpdateRemoteDelay, (uint16_t delay), (override)); - MOCK_METHOD((void), UpdateAudioConfigToHal, - (const ::bluetooth::le_audio::offload_config&), (override)); - MOCK_METHOD((void), UpdateBroadcastAudioConfigToHal, - (const ::bluetooth::le_audio::broadcast_offload_config&), + MOCK_METHOD((void), UpdateAudioConfigToHal, (const ::bluetooth::le_audio::offload_config&), (override)); + MOCK_METHOD((void), UpdateBroadcastAudioConfigToHal, + (const ::bluetooth::le_audio::broadcast_offload_config&), (override)); MOCK_METHOD((void), SuspendedForReconfiguration, (), (override)); MOCK_METHOD((void), ReconfigurationComplete, (), (override)); - MOCK_METHOD( - (std::optional), GetBroadcastConfig, - ((const std::vector>&), - (const std::optional< - std::vector<::bluetooth::le_audio::types::acs_ac_record>>&)), - (const override)); + MOCK_METHOD((std::optional), GetBroadcastConfig, + ((const std::vector>&), + (const std::optional>&)), + (const override)); - MOCK_METHOD( - (std::optional< - ::bluetooth::le_audio::set_configurations::AudioSetConfiguration>), - GetUnicastConfig, (const CodecManager::UnicastConfigurationRequirements&), - (const override)); + MOCK_METHOD((std::optional<::bluetooth::le_audio::set_configurations::AudioSetConfiguration>), + GetUnicastConfig, (const CodecManager::UnicastConfigurationRequirements&), + (const override)); MOCK_METHOD((void), OnDestroyed, ()); virtual ~MockLeAudioSourceHalClient() override { OnDestroyed(); } }; static const types::LeAudioCodecId kLeAudioCodecIdLc3 = { - .coding_format = types::kLeAudioCodingFormatLC3, - .vendor_company_id = types::kLeAudioVendorCompanyIdUndefined, - .vendor_codec_id = types::kLeAudioVendorCodecIdUndefined}; + .coding_format = types::kLeAudioCodingFormatLC3, + .vendor_company_id = types::kLeAudioVendorCompanyIdUndefined, + .vendor_codec_id = types::kLeAudioVendorCodecIdUndefined}; static const set_configurations::CodecConfigSetting lc3_16_2 = { - .id = kLeAudioCodecIdLc3, - .params = types::LeAudioLtvMap({ - LTV_ENTRY_SAMPLING_FREQUENCY( - codec_spec_conf::kLeAudioSamplingFreq16000Hz), - LTV_ENTRY_FRAME_DURATION(codec_spec_conf::kLeAudioCodecFrameDur10000us), - LTV_ENTRY_AUDIO_CHANNEL_ALLOCATION( - codec_spec_conf::kLeAudioLocationStereo), - LTV_ENTRY_OCTETS_PER_CODEC_FRAME(40), - }), - .channel_count_per_iso_stream = 1, + .id = kLeAudioCodecIdLc3, + .params = types::LeAudioLtvMap({ + LTV_ENTRY_SAMPLING_FREQUENCY(codec_spec_conf::kLeAudioSamplingFreq16000Hz), + LTV_ENTRY_FRAME_DURATION(codec_spec_conf::kLeAudioCodecFrameDur10000us), + LTV_ENTRY_AUDIO_CHANNEL_ALLOCATION(codec_spec_conf::kLeAudioLocationStereo), + LTV_ENTRY_OCTETS_PER_CODEC_FRAME(40), + }), + .channel_count_per_iso_stream = 1, }; static const set_configurations::CodecConfigSetting lc3_24_2 = { - .id = kLeAudioCodecIdLc3, - .params = types::LeAudioLtvMap({ - LTV_ENTRY_SAMPLING_FREQUENCY( - codec_spec_conf::kLeAudioSamplingFreq24000Hz), - LTV_ENTRY_FRAME_DURATION(codec_spec_conf::kLeAudioCodecFrameDur10000us), - LTV_ENTRY_AUDIO_CHANNEL_ALLOCATION( - codec_spec_conf::kLeAudioLocationStereo), - LTV_ENTRY_OCTETS_PER_CODEC_FRAME(60), - }), - .channel_count_per_iso_stream = 1, + .id = kLeAudioCodecIdLc3, + .params = types::LeAudioLtvMap({ + LTV_ENTRY_SAMPLING_FREQUENCY(codec_spec_conf::kLeAudioSamplingFreq24000Hz), + LTV_ENTRY_FRAME_DURATION(codec_spec_conf::kLeAudioCodecFrameDur10000us), + LTV_ENTRY_AUDIO_CHANNEL_ALLOCATION(codec_spec_conf::kLeAudioLocationStereo), + LTV_ENTRY_OCTETS_PER_CODEC_FRAME(60), + }), + .channel_count_per_iso_stream = 1, }; static const set_configurations::CodecConfigSetting lc3_32_2 = { - .id = kLeAudioCodecIdLc3, - .params = types::LeAudioLtvMap({ - LTV_ENTRY_SAMPLING_FREQUENCY( - codec_spec_conf::kLeAudioSamplingFreq32000Hz), - LTV_ENTRY_FRAME_DURATION(codec_spec_conf::kLeAudioCodecFrameDur10000us), - LTV_ENTRY_AUDIO_CHANNEL_ALLOCATION( - codec_spec_conf::kLeAudioLocationStereo), - LTV_ENTRY_OCTETS_PER_CODEC_FRAME(80), - }), - .channel_count_per_iso_stream = 1, + .id = kLeAudioCodecIdLc3, + .params = types::LeAudioLtvMap({ + LTV_ENTRY_SAMPLING_FREQUENCY(codec_spec_conf::kLeAudioSamplingFreq32000Hz), + LTV_ENTRY_FRAME_DURATION(codec_spec_conf::kLeAudioCodecFrameDur10000us), + LTV_ENTRY_AUDIO_CHANNEL_ALLOCATION(codec_spec_conf::kLeAudioLocationStereo), + LTV_ENTRY_OCTETS_PER_CODEC_FRAME(80), + }), + .channel_count_per_iso_stream = 1, }; static const set_configurations::CodecConfigSetting lc3_48_2 = { - .id = kLeAudioCodecIdLc3, - .params = types::LeAudioLtvMap({ - LTV_ENTRY_SAMPLING_FREQUENCY( - codec_spec_conf::kLeAudioSamplingFreq48000Hz), - LTV_ENTRY_FRAME_DURATION(codec_spec_conf::kLeAudioCodecFrameDur10000us), - LTV_ENTRY_AUDIO_CHANNEL_ALLOCATION( - codec_spec_conf::kLeAudioLocationStereo), - LTV_ENTRY_OCTETS_PER_CODEC_FRAME(100), - }), - .channel_count_per_iso_stream = 1, + .id = kLeAudioCodecIdLc3, + .params = types::LeAudioLtvMap({ + LTV_ENTRY_SAMPLING_FREQUENCY(codec_spec_conf::kLeAudioSamplingFreq48000Hz), + LTV_ENTRY_FRAME_DURATION(codec_spec_conf::kLeAudioCodecFrameDur10000us), + LTV_ENTRY_AUDIO_CHANNEL_ALLOCATION(codec_spec_conf::kLeAudioLocationStereo), + LTV_ENTRY_OCTETS_PER_CODEC_FRAME(100), + }), + .channel_count_per_iso_stream = 1, }; -void set_mock_offload_capabilities( - const std::vector& caps) { +void set_mock_offload_capabilities(const std::vector& caps) { offload_capabilities = ∩︀ } -static constexpr char kPropLeAudioOffloadSupported[] = - "ro.bluetooth.leaudio_offload.supported"; -static constexpr char kPropLeAudioOffloadDisabled[] = - "persist.bluetooth.leaudio_offload.disabled"; +static constexpr char kPropLeAudioOffloadSupported[] = "ro.bluetooth.leaudio_offload.supported"; +static constexpr char kPropLeAudioOffloadDisabled[] = "persist.bluetooth.leaudio_offload.disabled"; static constexpr char kPropLeAudioBidirSwbSupported[] = - "bluetooth.leaudio.dual_bidirection_swb.supported"; + "bluetooth.leaudio.dual_bidirection_swb.supported"; class CodecManagerTestBase : public Test { - public: +public: virtual void SetUp() override { __android_log_set_minimum_priority(ANDROID_LOG_VERBOSE); bluetooth::common::InitFlags::Load(test_flags); @@ -321,10 +289,9 @@ class CodecManagerTestBase : public Test { bluetooth::legacy::hci::testing::SetMock(legacy_hci_mock_); - ON_CALL(controller_interface, SupportsBleIsochronousBroadcaster) - .WillByDefault(Return(true)); + ON_CALL(controller_interface, SupportsBleIsochronousBroadcaster).WillByDefault(Return(true)); ON_CALL(controller_interface, IsSupported(OpCode::CONFIGURE_DATA_PATH)) - .WillByDefault(Return(true)); + .WillByDefault(Return(true)); bluetooth::hci::testing::mock_controller_ = &controller_interface; codec_manager = CodecManager::GetInstance(); @@ -335,26 +302,22 @@ class CodecManagerTestBase : public Test { virtual void TearDown() override { codec_manager->Stop(); } - NiceMock - controller_interface; + NiceMock controller_interface; CodecManager* codec_manager; bluetooth::legacy::hci::testing::MockInterface legacy_hci_mock_; - protected: +protected: void RegisterSourceHalClientMock() { - owned_mock_le_audio_source_hal_client_.reset( - new NiceMock()); + owned_mock_le_audio_source_hal_client_.reset(new NiceMock()); mock_le_audio_source_hal_client_ = - (MockLeAudioSourceHalClient*) - owned_mock_le_audio_source_hal_client_.get(); + (MockLeAudioSourceHalClient*)owned_mock_le_audio_source_hal_client_.get(); is_audio_unicast_source_acquired = false; owned_mock_broadcast_le_audio_source_hal_client_.reset( - new NiceMock()); + new NiceMock()); mock_broadcast_le_audio_source_hal_client_ = - (MockLeAudioSourceHalClient*) - owned_mock_broadcast_le_audio_source_hal_client_.get(); + (MockLeAudioSourceHalClient*)owned_mock_broadcast_le_audio_source_hal_client_.get(); is_audio_broadcast_source_acquired = false; ON_CALL(*mock_le_audio_source_hal_client_, OnDestroyed).WillByDefault([]() { @@ -364,10 +327,9 @@ class CodecManagerTestBase : public Test { } void RegisterSinkHalClientMock() { - owned_mock_le_audio_sink_hal_client_.reset( - new NiceMock()); + owned_mock_le_audio_sink_hal_client_.reset(new NiceMock()); mock_le_audio_sink_hal_client_ = - (MockLeAudioSinkHalClient*)owned_mock_le_audio_sink_hal_client_.get(); + (MockLeAudioSinkHalClient*)owned_mock_le_audio_sink_hal_client_.get(); is_audio_unicast_sink_acquired = false; @@ -380,7 +342,7 @@ class CodecManagerTestBase : public Test { /*----------------- ADSP codec manager tests ------------------*/ class CodecManagerTestAdsp : public CodecManagerTestBase { - public: +public: virtual void SetUp() override { // Enable the HW offloader osi_property_set_bool(kPropLeAudioOffloadSupported, true); @@ -394,7 +356,7 @@ class CodecManagerTestAdsp : public CodecManagerTestBase { }; class CodecManagerTestAdspNoSwb : public CodecManagerTestBase { - public: +public: virtual void SetUp() override { // Enable the HW offloader osi_property_set_bool(kPropLeAudioOffloadSupported, true); @@ -407,105 +369,93 @@ class CodecManagerTestAdspNoSwb : public CodecManagerTestBase { } }; -TEST_F(CodecManagerTestAdsp, test_init) { - ASSERT_EQ(codec_manager, CodecManager::GetInstance()); -} +TEST_F(CodecManagerTestAdsp, test_init) { ASSERT_EQ(codec_manager, CodecManager::GetInstance()); } TEST_F(CodecManagerTestAdsp, test_start) { - EXPECT_CALL(legacy_hci_mock_, - ConfigureDataPath(hci_data_direction_t::HOST_TO_CONTROLLER, - kIsoDataPathPlatformDefault, _)) - .Times(1); - EXPECT_CALL(legacy_hci_mock_, - ConfigureDataPath(hci_data_direction_t::CONTROLLER_TO_HOST, - kIsoDataPathPlatformDefault, _)) - .Times(1); + EXPECT_CALL(legacy_hci_mock_, ConfigureDataPath(hci_data_direction_t::HOST_TO_CONTROLLER, + kIsoDataPathPlatformDefault, _)) + .Times(1); + EXPECT_CALL(legacy_hci_mock_, ConfigureDataPath(hci_data_direction_t::CONTROLLER_TO_HOST, + kIsoDataPathPlatformDefault, _)) + .Times(1); // Verify data path is reset on Stop() EXPECT_CALL(legacy_hci_mock_, - ConfigureDataPath(hci_data_direction_t::HOST_TO_CONTROLLER, - kIsoDataPathHci, _)) - .Times(1); + ConfigureDataPath(hci_data_direction_t::HOST_TO_CONTROLLER, kIsoDataPathHci, _)) + .Times(1); EXPECT_CALL(legacy_hci_mock_, - ConfigureDataPath(hci_data_direction_t::CONTROLLER_TO_HOST, - kIsoDataPathHci, _)) - .Times(1); + ConfigureDataPath(hci_data_direction_t::CONTROLLER_TO_HOST, kIsoDataPathHci, _)) + .Times(1); - const std::vector - offloading_preference(0); + const std::vector offloading_preference(0); codec_manager->Start(offloading_preference); ASSERT_EQ(codec_manager->GetCodecLocation(), CodecLocation::ADSP); } TEST_F(CodecManagerTestAdsp, testStreamConfigurationAdspDownMix) { - const std::vector - offloading_preference(0); + const std::vector offloading_preference(0); codec_manager->Start(offloading_preference); // Current CIS configuration for two earbuds std::vector cises{ - { - .id = 0x00, - .type = types::CisType::CIS_TYPE_BIDIRECTIONAL, - .conn_handle = 96, - }, - { - .id = 0x01, - .type = types::CisType::CIS_TYPE_BIDIRECTIONAL, - .conn_handle = 97, - }, + { + .id = 0x00, + .type = types::CisType::CIS_TYPE_BIDIRECTIONAL, + .conn_handle = 96, + }, + { + .id = 0x01, + .type = types::CisType::CIS_TYPE_BIDIRECTIONAL, + .conn_handle = 97, + }, }; // Stream parameters types::BidirectionalPair stream_params{ - .sink = - { - .sample_frequency_hz = 16000, - .frame_duration_us = 10000, - .octets_per_codec_frame = 40, - .audio_channel_allocation = - codec_spec_conf::kLeAudioLocationFrontLeft, - .codec_frames_blocks_per_sdu = 1, - .num_of_channels = 1, - .num_of_devices = 1, - .stream_locations = + .sink = { - std::pair{ - 97 /*conn_handle*/, - codec_spec_conf::kLeAudioLocationFrontLeft}, + .sample_frequency_hz = 16000, + .frame_duration_us = 10000, + .octets_per_codec_frame = 40, + .audio_channel_allocation = codec_spec_conf::kLeAudioLocationFrontLeft, + .codec_frames_blocks_per_sdu = 1, + .num_of_channels = 1, + .num_of_devices = 1, + .stream_locations = + { + std::pair{ + 97 /*conn_handle*/, + codec_spec_conf::kLeAudioLocationFrontLeft}, + }, + }, + .source = + { + .sample_frequency_hz = 16000, + .frame_duration_us = 10000, + .octets_per_codec_frame = 40, + .audio_channel_allocation = codec_spec_conf::kLeAudioLocationFrontLeft, + .codec_frames_blocks_per_sdu = 1, + .num_of_channels = 1, + .num_of_devices = 1, + { + std::pair{ + 97 /*conn_handle*/, + codec_spec_conf::kLeAudioLocationBackLeft}, + }, }, - }, - .source = - { - .sample_frequency_hz = 16000, - .frame_duration_us = 10000, - .octets_per_codec_frame = 40, - .audio_channel_allocation = - codec_spec_conf::kLeAudioLocationFrontLeft, - .codec_frames_blocks_per_sdu = 1, - .num_of_channels = 1, - .num_of_devices = 1, - { - std::pair{ - 97 /*conn_handle*/, - codec_spec_conf::kLeAudioLocationBackLeft}, - }, - }, }; - codec_manager->UpdateCisConfiguration(cises, stream_params.sink, - kLeAudioDirectionSink); - codec_manager->UpdateCisConfiguration(cises, stream_params.source, - kLeAudioDirectionSource); + codec_manager->UpdateCisConfiguration(cises, stream_params.sink, kLeAudioDirectionSink); + codec_manager->UpdateCisConfiguration(cises, stream_params.source, kLeAudioDirectionSource); // Verify the offloader config content types::BidirectionalPair> out_offload_configs; codec_manager->UpdateActiveAudioConfig( - stream_params, {.sink = 44, .source = 44}, - [&out_offload_configs](const offload_config& config, uint8_t direction) { - out_offload_configs.get(direction) = config; - }); + stream_params, {.sink = 44, .source = 44}, + [&out_offload_configs](const offload_config& config, uint8_t direction) { + out_offload_configs.get(direction) = config; + }); // Expect the same configuration for sink and source ASSERT_TRUE(out_offload_configs.sink.has_value()); @@ -517,14 +467,12 @@ TEST_F(CodecManagerTestAdsp, testStreamConfigurationAdspDownMix) { ASSERT_EQ(2lu, config.stream_map.size()); for (const auto& info : config.stream_map) { if (info.stream_handle == 96) { - ASSERT_EQ(codec_spec_conf::kLeAudioLocationFrontRight, - info.audio_channel_allocation); + ASSERT_EQ(codec_spec_conf::kLeAudioLocationFrontRight, info.audio_channel_allocation); // The disconnected should be inactive ASSERT_FALSE(info.is_stream_active); } else if (info.stream_handle == 97) { - ASSERT_EQ(codec_spec_conf::kLeAudioLocationFrontLeft, - info.audio_channel_allocation); + ASSERT_EQ(codec_spec_conf::kLeAudioLocationFrontLeft, info.audio_channel_allocation); // The connected should be active ASSERT_TRUE(info.is_stream_active); @@ -549,10 +497,10 @@ TEST_F(CodecManagerTestAdsp, testStreamConfigurationAdspDownMix) { out_offload_configs.sink = std::nullopt; out_offload_configs.source = std::nullopt; codec_manager->UpdateActiveAudioConfig( - stream_params, {.sink = 44, .source = 44}, - [&out_offload_configs](const offload_config& config, uint8_t direction) { - out_offload_configs.get(direction) = config; - }); + stream_params, {.sink = 44, .source = 44}, + [&out_offload_configs](const offload_config& config, uint8_t direction) { + out_offload_configs.get(direction) = config; + }); // Expect sink & source configurations with empty CIS channel allocation map. ASSERT_TRUE(out_offload_configs.sink.has_value()); @@ -571,15 +519,13 @@ TEST_F(CodecManagerTestAdsp, testStreamConfigurationAdspDownMix) { } TEST_F(CodecManagerTestAdsp, test_capabilities_none) { - const std::vector - offloading_preference(0); + const std::vector offloading_preference(0); codec_manager->Start(offloading_preference); bool has_null_config = false; - auto match_first_config = - [&](const CodecManager::UnicastConfigurationRequirements& requirements, - const set_configurations::AudioSetConfigurations* confs) - -> const set_configurations::AudioSetConfiguration* { + auto match_first_config = [&](const CodecManager::UnicastConfigurationRequirements& requirements, + const set_configurations::AudioSetConfigurations* confs) + -> const set_configurations::AudioSetConfiguration* { // Don't expect the matcher being called on nullptr if (confs == nullptr) { has_null_config = true; @@ -597,24 +543,20 @@ TEST_F(CodecManagerTestAdsp, test_capabilities_none) { ::bluetooth::le_audio::types::kLeAudioContextAllTypesArray) { has_null_config = false; CodecManager::UnicastConfigurationRequirements requirements = { - .audio_context_type = ctx_type, + .audio_context_type = ctx_type, }; - ASSERT_EQ(nullptr, - codec_manager->GetCodecConfig(requirements, match_first_config)); + ASSERT_EQ(nullptr, codec_manager->GetCodecConfig(requirements, match_first_config)); ASSERT_FALSE(has_null_config); } } TEST_F(CodecManagerTestAdsp, test_capabilities) { - for (auto test_context : - ::bluetooth::le_audio::types::kLeAudioContextAllTypesArray) { + for (auto test_context : ::bluetooth::le_audio::types::kLeAudioContextAllTypesArray) { // Build the offloader capabilities vector using the configuration provider // in HOST mode to get all the .json filce configuration entries. std::vector offload_capabilities; - AudioSetConfigurationProvider::Initialize( - bluetooth::le_audio::types::CodecLocation::HOST); - for (auto& cap : *AudioSetConfigurationProvider::Get()->GetConfigurations( - test_context)) { + AudioSetConfigurationProvider::Initialize(bluetooth::le_audio::types::CodecLocation::HOST); + for (auto& cap : *AudioSetConfigurationProvider::Get()->GetConfigurations(test_context)) { offload_capabilities.push_back(*cap); } ASSERT_NE(0u, offload_capabilities.size()); @@ -622,18 +564,16 @@ TEST_F(CodecManagerTestAdsp, test_capabilities) { // Clean up before the codec manager starts it in ADSP mode. AudioSetConfigurationProvider::Cleanup(); - const std::vector - offloading_preference = { - {.codec_type = - bluetooth::le_audio::LE_AUDIO_CODEC_INDEX_SOURCE_LC3}}; + const std::vector offloading_preference = { + {.codec_type = bluetooth::le_audio::LE_AUDIO_CODEC_INDEX_SOURCE_LC3}}; codec_manager->Start(offloading_preference); size_t available_configs_size = 0; auto match_first_config = - [&available_configs_size]( - const CodecManager::UnicastConfigurationRequirements& requirements, - const set_configurations::AudioSetConfigurations* confs) - -> const set_configurations::AudioSetConfiguration* { + [&available_configs_size]( + const CodecManager::UnicastConfigurationRequirements& requirements, + const set_configurations::AudioSetConfigurations* confs) + -> const set_configurations::AudioSetConfiguration* { if (confs && confs->size()) { available_configs_size = confs->size(); // For simplicity return the first element, the real matcher should @@ -644,7 +584,7 @@ TEST_F(CodecManagerTestAdsp, test_capabilities) { }; CodecManager::UnicastConfigurationRequirements requirements = { - .audio_context_type = test_context, + .audio_context_type = test_context, }; auto cfg = codec_manager->GetCodecConfig(requirements, match_first_config); ASSERT_NE(nullptr, cfg); @@ -657,34 +597,30 @@ TEST_F(CodecManagerTestAdsp, test_capabilities) { TEST_F(CodecManagerTestAdsp, test_broadcast_config) { static const set_configurations::CodecConfigSetting bc_lc3_48_2 = { - .id = kLeAudioCodecIdLc3, - .params = types::LeAudioLtvMap({ - LTV_ENTRY_SAMPLING_FREQUENCY( - codec_spec_conf::kLeAudioSamplingFreq48000Hz), - LTV_ENTRY_FRAME_DURATION( - codec_spec_conf::kLeAudioCodecFrameDur10000us), - LTV_ENTRY_AUDIO_CHANNEL_ALLOCATION( - codec_spec_conf::kLeAudioLocationStereo), - LTV_ENTRY_OCTETS_PER_CODEC_FRAME(100), - }), - .channel_count_per_iso_stream = 2, + .id = kLeAudioCodecIdLc3, + .params = types::LeAudioLtvMap({ + LTV_ENTRY_SAMPLING_FREQUENCY(codec_spec_conf::kLeAudioSamplingFreq48000Hz), + LTV_ENTRY_FRAME_DURATION(codec_spec_conf::kLeAudioCodecFrameDur10000us), + LTV_ENTRY_AUDIO_CHANNEL_ALLOCATION(codec_spec_conf::kLeAudioLocationStereo), + LTV_ENTRY_OCTETS_PER_CODEC_FRAME(100), + }), + .channel_count_per_iso_stream = 2, }; std::vector offload_capabilities = {{ - .name = "Test_Broadcast_Config_No_Dev_lc3_48_2", - .confs = {.sink = {set_configurations::AseConfiguration(bc_lc3_48_2), - set_configurations::AseConfiguration(bc_lc3_48_2)}, - .source = {}}, + .name = "Test_Broadcast_Config_No_Dev_lc3_48_2", + .confs = {.sink = {set_configurations::AseConfiguration(bc_lc3_48_2), + set_configurations::AseConfiguration(bc_lc3_48_2)}, + .source = {}}, }}; set_mock_offload_capabilities(offload_capabilities); - const std::vector - offloading_preference = { + const std::vector offloading_preference = { {.codec_type = bluetooth::le_audio::LE_AUDIO_CODEC_INDEX_SOURCE_LC3}}; codec_manager->Start(offloading_preference); CodecManager::BroadcastConfigurationRequirements requirements = { - .subgroup_quality = {{types::LeAudioContextType::MEDIA, 1}}}; + .subgroup_quality = {{types::LeAudioContextType::MEDIA, 1}}}; auto cfg = codec_manager->GetBroadcastConfig(requirements); ASSERT_EQ(2, cfg->GetNumBisTotal()); ASSERT_EQ(2, cfg->GetNumChannelsMax()); @@ -696,11 +632,8 @@ TEST_F(CodecManagerTestAdsp, test_broadcast_config) { ASSERT_EQ(2lu, cfg->subgroups.at(0).GetNumChannelsTotal()); ASSERT_EQ(2lu, cfg->subgroups.at(0).GetBisCodecConfigs().at(0).GetNumBis()); - ASSERT_EQ(2lu, - cfg->subgroups.at(0).GetBisCodecConfigs().at(0).GetNumChannels()); - ASSERT_EQ( - 1lu, - cfg->subgroups.at(0).GetBisCodecConfigs().at(0).GetNumChannelsPerBis()); + ASSERT_EQ(2lu, cfg->subgroups.at(0).GetBisCodecConfigs().at(0).GetNumChannels()); + ASSERT_EQ(1lu, cfg->subgroups.at(0).GetBisCodecConfigs().at(0).GetNumChannelsPerBis()); // Clean up the before testing any other offload capabilities. codec_manager->Stop(); @@ -708,43 +641,38 @@ TEST_F(CodecManagerTestAdsp, test_broadcast_config) { TEST_F(CodecManagerTestAdsp, test_update_broadcast_offloader) { static const set_configurations::CodecConfigSetting bc_lc3_48_2 = { - .id = kLeAudioCodecIdLc3, - .params = types::LeAudioLtvMap({ - LTV_ENTRY_SAMPLING_FREQUENCY( - codec_spec_conf::kLeAudioSamplingFreq48000Hz), - LTV_ENTRY_FRAME_DURATION( - codec_spec_conf::kLeAudioCodecFrameDur10000us), - LTV_ENTRY_AUDIO_CHANNEL_ALLOCATION( - codec_spec_conf::kLeAudioLocationStereo), - LTV_ENTRY_OCTETS_PER_CODEC_FRAME(100), - }), - .channel_count_per_iso_stream = 2, + .id = kLeAudioCodecIdLc3, + .params = types::LeAudioLtvMap({ + LTV_ENTRY_SAMPLING_FREQUENCY(codec_spec_conf::kLeAudioSamplingFreq48000Hz), + LTV_ENTRY_FRAME_DURATION(codec_spec_conf::kLeAudioCodecFrameDur10000us), + LTV_ENTRY_AUDIO_CHANNEL_ALLOCATION(codec_spec_conf::kLeAudioLocationStereo), + LTV_ENTRY_OCTETS_PER_CODEC_FRAME(100), + }), + .channel_count_per_iso_stream = 2, }; std::vector offload_capabilities = {{ - .name = "Test_Broadcast_Config_For_Offloader", - .confs = {.sink = {set_configurations::AseConfiguration(bc_lc3_48_2), - set_configurations::AseConfiguration(bc_lc3_48_2)}, - .source = {}}, + .name = "Test_Broadcast_Config_For_Offloader", + .confs = {.sink = {set_configurations::AseConfiguration(bc_lc3_48_2), + set_configurations::AseConfiguration(bc_lc3_48_2)}, + .source = {}}, }}; set_mock_offload_capabilities(offload_capabilities); - const std::vector - offloading_preference = { + const std::vector offloading_preference = { {.codec_type = bluetooth::le_audio::LE_AUDIO_CODEC_INDEX_SOURCE_LC3}}; codec_manager->Start(offloading_preference); CodecManager::BroadcastConfigurationRequirements requirements = { - .subgroup_quality = {{types::LeAudioContextType::MEDIA, 1}}}; + .subgroup_quality = {{types::LeAudioContextType::MEDIA, 1}}}; codec_manager->GetBroadcastConfig(requirements); bool was_called = false; bluetooth::le_audio::broadcast_offload_config bcast_config; codec_manager->UpdateBroadcastConnHandle( - {0x0001, 0x0002}, - [&](const bluetooth::le_audio::broadcast_offload_config& config) { - was_called = true; - bcast_config = config; - }); + {0x0001, 0x0002}, [&](const bluetooth::le_audio::broadcast_offload_config& config) { + was_called = true; + bcast_config = config; + }); // Expect a call for ADSP encoding ASSERT_TRUE(was_called); @@ -760,7 +688,7 @@ TEST_F(CodecManagerTestAdsp, test_update_broadcast_offloader) { /*----------------- HOST codec manager tests ------------------*/ class CodecManagerTestHost : public CodecManagerTestBase { - public: +public: virtual void SetUp() override { // Enable the HW offloader osi_property_set_bool(kPropLeAudioOffloadSupported, false); @@ -774,7 +702,7 @@ class CodecManagerTestHost : public CodecManagerTestBase { }; class CodecManagerTestHostNoSwb : public CodecManagerTestBase { - public: +public: virtual void SetUp() override { // Enable the HW offloader osi_property_set_bool(kPropLeAudioOffloadSupported, true); @@ -787,9 +715,7 @@ class CodecManagerTestHostNoSwb : public CodecManagerTestBase { } }; -TEST_F(CodecManagerTestHost, test_init) { - ASSERT_EQ(codec_manager, CodecManager::GetInstance()); -} +TEST_F(CodecManagerTestHost, test_init) { ASSERT_EQ(codec_manager, CodecManager::GetInstance()); } TEST_F(CodecManagerTestHost, test_audio_session_update) { ASSERT_EQ(codec_manager, CodecManager::GetInstance()); @@ -799,298 +725,275 @@ TEST_F(CodecManagerTestHost, test_audio_session_update) { auto broadcast_source = LeAudioSourceAudioHalClient::AcquireBroadcast(); // codec manager not started - ASSERT_FALSE(codec_manager->UpdateActiveUnicastAudioHalClient( - unicast_source.get(), unicast_sink.get(), true)); - ASSERT_FALSE(codec_manager->UpdateActiveUnicastAudioHalClient( - unicast_source.get(), unicast_sink.get(), false)); - ASSERT_FALSE(codec_manager->UpdateActiveBroadcastAudioHalClient( - broadcast_source.get(), true)); - ASSERT_FALSE(codec_manager->UpdateActiveBroadcastAudioHalClient( - broadcast_source.get(), false)); - - std::vector - offloading_preference(0); + ASSERT_FALSE(codec_manager->UpdateActiveUnicastAudioHalClient(unicast_source.get(), + unicast_sink.get(), true)); + ASSERT_FALSE(codec_manager->UpdateActiveUnicastAudioHalClient(unicast_source.get(), + unicast_sink.get(), false)); + ASSERT_FALSE(codec_manager->UpdateActiveBroadcastAudioHalClient(broadcast_source.get(), true)); + ASSERT_FALSE(codec_manager->UpdateActiveBroadcastAudioHalClient(broadcast_source.get(), false)); + + std::vector offloading_preference(0); // Start codec manager codec_manager->Start(offloading_preference); - ASSERT_TRUE(codec_manager->UpdateActiveUnicastAudioHalClient( - unicast_source.get(), unicast_sink.get(), true)); - ASSERT_FALSE(codec_manager->UpdateActiveUnicastAudioHalClient( - unicast_source.get(), unicast_sink.get(), true)); - ASSERT_TRUE(codec_manager->UpdateActiveUnicastAudioHalClient( - unicast_source.get(), unicast_sink.get(), false)); - ASSERT_TRUE(codec_manager->UpdateActiveUnicastAudioHalClient( - unicast_source.get(), nullptr, true)); - ASSERT_TRUE(codec_manager->UpdateActiveUnicastAudioHalClient( - nullptr, unicast_sink.get(), true)); - ASSERT_FALSE(codec_manager->UpdateActiveUnicastAudioHalClient( - nullptr, nullptr, false)); - ASSERT_FALSE( - codec_manager->UpdateActiveUnicastAudioHalClient(nullptr, nullptr, true)); - ASSERT_TRUE(codec_manager->UpdateActiveUnicastAudioHalClient( - nullptr, unicast_sink.get(), false)); - ASSERT_TRUE(codec_manager->UpdateActiveUnicastAudioHalClient( - unicast_source.get(), nullptr, false)); - - ASSERT_TRUE(codec_manager->UpdateActiveBroadcastAudioHalClient( - broadcast_source.get(), true)); - ASSERT_TRUE(codec_manager->UpdateActiveBroadcastAudioHalClient( - broadcast_source.get(), false)); - ASSERT_TRUE(codec_manager->UpdateActiveBroadcastAudioHalClient( - broadcast_source.get(), true)); - ASSERT_FALSE(codec_manager->UpdateActiveBroadcastAudioHalClient( - broadcast_source.get(), true)); - ASSERT_FALSE(codec_manager->UpdateActiveBroadcastAudioHalClient( - unicast_source.get(), true)); - ASSERT_FALSE(codec_manager->UpdateActiveBroadcastAudioHalClient( - unicast_source.get(), false)); - ASSERT_FALSE( - codec_manager->UpdateActiveBroadcastAudioHalClient(nullptr, false)); - ASSERT_FALSE( - codec_manager->UpdateActiveBroadcastAudioHalClient(nullptr, true)); + ASSERT_TRUE(codec_manager->UpdateActiveUnicastAudioHalClient(unicast_source.get(), + unicast_sink.get(), true)); + ASSERT_FALSE(codec_manager->UpdateActiveUnicastAudioHalClient(unicast_source.get(), + unicast_sink.get(), true)); + ASSERT_TRUE(codec_manager->UpdateActiveUnicastAudioHalClient(unicast_source.get(), + unicast_sink.get(), false)); + ASSERT_TRUE( + codec_manager->UpdateActiveUnicastAudioHalClient(unicast_source.get(), nullptr, true)); + ASSERT_TRUE(codec_manager->UpdateActiveUnicastAudioHalClient(nullptr, unicast_sink.get(), true)); + ASSERT_FALSE(codec_manager->UpdateActiveUnicastAudioHalClient(nullptr, nullptr, false)); + ASSERT_FALSE(codec_manager->UpdateActiveUnicastAudioHalClient(nullptr, nullptr, true)); + ASSERT_TRUE(codec_manager->UpdateActiveUnicastAudioHalClient(nullptr, unicast_sink.get(), false)); + ASSERT_TRUE( + codec_manager->UpdateActiveUnicastAudioHalClient(unicast_source.get(), nullptr, false)); + + ASSERT_TRUE(codec_manager->UpdateActiveBroadcastAudioHalClient(broadcast_source.get(), true)); + ASSERT_TRUE(codec_manager->UpdateActiveBroadcastAudioHalClient(broadcast_source.get(), false)); + ASSERT_TRUE(codec_manager->UpdateActiveBroadcastAudioHalClient(broadcast_source.get(), true)); + ASSERT_FALSE(codec_manager->UpdateActiveBroadcastAudioHalClient(broadcast_source.get(), true)); + ASSERT_FALSE(codec_manager->UpdateActiveBroadcastAudioHalClient(unicast_source.get(), true)); + ASSERT_FALSE(codec_manager->UpdateActiveBroadcastAudioHalClient(unicast_source.get(), false)); + ASSERT_FALSE(codec_manager->UpdateActiveBroadcastAudioHalClient(nullptr, false)); + ASSERT_FALSE(codec_manager->UpdateActiveBroadcastAudioHalClient(nullptr, true)); } TEST_F(CodecManagerTestHost, test_start) { - EXPECT_CALL(legacy_hci_mock_, - ConfigureDataPath(hci_data_direction_t::HOST_TO_CONTROLLER, - kIsoDataPathPlatformDefault, _)) - .Times(0); - EXPECT_CALL(legacy_hci_mock_, - ConfigureDataPath(hci_data_direction_t::CONTROLLER_TO_HOST, - kIsoDataPathPlatformDefault, _)) - .Times(0); + EXPECT_CALL(legacy_hci_mock_, ConfigureDataPath(hci_data_direction_t::HOST_TO_CONTROLLER, + kIsoDataPathPlatformDefault, _)) + .Times(0); + EXPECT_CALL(legacy_hci_mock_, ConfigureDataPath(hci_data_direction_t::CONTROLLER_TO_HOST, + kIsoDataPathPlatformDefault, _)) + .Times(0); // Verify data path is NOT reset on Stop() for the Host encoding session EXPECT_CALL(legacy_hci_mock_, - ConfigureDataPath(hci_data_direction_t::HOST_TO_CONTROLLER, - kIsoDataPathHci, _)) - .Times(0); + ConfigureDataPath(hci_data_direction_t::HOST_TO_CONTROLLER, kIsoDataPathHci, _)) + .Times(0); EXPECT_CALL(legacy_hci_mock_, - ConfigureDataPath(hci_data_direction_t::CONTROLLER_TO_HOST, - kIsoDataPathHci, _)) - .Times(0); + ConfigureDataPath(hci_data_direction_t::CONTROLLER_TO_HOST, kIsoDataPathHci, _)) + .Times(0); - const std::vector - offloading_preference(0); + const std::vector offloading_preference(0); codec_manager->Start(offloading_preference); ASSERT_EQ(codec_manager->GetCodecLocation(), CodecLocation::HOST); } TEST_F(CodecManagerTestHost, test_non_bidir_swb) { - const std::vector - offloading_preference = { + const std::vector offloading_preference = { {.codec_type = bluetooth::le_audio::LE_AUDIO_CODEC_INDEX_SOURCE_LC3}}; codec_manager->Start(offloading_preference); // NON-SWB configs ASSERT_FALSE(codec_manager->CheckCodecConfigIsBiDirSwb({ - .confs = {.sink = {set_configurations::AseConfiguration(lc3_16_2), - set_configurations::AseConfiguration(lc3_16_2)}, - .source = {set_configurations::AseConfiguration(lc3_16_2), - set_configurations::AseConfiguration(lc3_16_2)}}, + .confs = {.sink = {set_configurations::AseConfiguration(lc3_16_2), + set_configurations::AseConfiguration(lc3_16_2)}, + .source = {set_configurations::AseConfiguration(lc3_16_2), + set_configurations::AseConfiguration(lc3_16_2)}}, })); ASSERT_FALSE(codec_manager->CheckCodecConfigIsBiDirSwb({ - .confs = {.sink = {set_configurations::AseConfiguration(lc3_24_2), - set_configurations::AseConfiguration(lc3_24_2)}, - .source = {set_configurations::AseConfiguration(lc3_16_2), - set_configurations::AseConfiguration(lc3_16_2)}}, + .confs = {.sink = {set_configurations::AseConfiguration(lc3_24_2), + set_configurations::AseConfiguration(lc3_24_2)}, + .source = {set_configurations::AseConfiguration(lc3_16_2), + set_configurations::AseConfiguration(lc3_16_2)}}, })); ASSERT_FALSE(codec_manager->CheckCodecConfigIsBiDirSwb({ - .confs = {.sink = {set_configurations::AseConfiguration(lc3_16_2), - set_configurations::AseConfiguration(lc3_16_2)}, - .source = {set_configurations::AseConfiguration(lc3_24_2), - set_configurations::AseConfiguration(lc3_24_2)}}, + .confs = {.sink = {set_configurations::AseConfiguration(lc3_16_2), + set_configurations::AseConfiguration(lc3_16_2)}, + .source = {set_configurations::AseConfiguration(lc3_24_2), + set_configurations::AseConfiguration(lc3_24_2)}}, })); ASSERT_FALSE(codec_manager->CheckCodecConfigIsBiDirSwb({ - .confs = {.sink = {set_configurations::AseConfiguration(lc3_16_2), - set_configurations::AseConfiguration(lc3_16_2)}, - .source = {set_configurations::AseConfiguration(lc3_32_2), - set_configurations::AseConfiguration(lc3_32_2)}}, + .confs = {.sink = {set_configurations::AseConfiguration(lc3_16_2), + set_configurations::AseConfiguration(lc3_16_2)}, + .source = {set_configurations::AseConfiguration(lc3_32_2), + set_configurations::AseConfiguration(lc3_32_2)}}, })); ASSERT_FALSE(codec_manager->CheckCodecConfigIsBiDirSwb({ - .confs = {.sink = {set_configurations::AseConfiguration(lc3_32_2), - set_configurations::AseConfiguration(lc3_32_2)}, - .source = {set_configurations::AseConfiguration(lc3_16_2), - set_configurations::AseConfiguration(lc3_16_2)}}, + .confs = {.sink = {set_configurations::AseConfiguration(lc3_32_2), + set_configurations::AseConfiguration(lc3_32_2)}, + .source = {set_configurations::AseConfiguration(lc3_16_2), + set_configurations::AseConfiguration(lc3_16_2)}}, })); ASSERT_FALSE(codec_manager->CheckCodecConfigIsBiDirSwb({ - .confs = {.sink = {set_configurations::AseConfiguration(lc3_24_2), - set_configurations::AseConfiguration(lc3_24_2)}, - .source = {set_configurations::AseConfiguration(lc3_24_2), - set_configurations::AseConfiguration(lc3_24_2)}}, + .confs = {.sink = {set_configurations::AseConfiguration(lc3_24_2), + set_configurations::AseConfiguration(lc3_24_2)}, + .source = {set_configurations::AseConfiguration(lc3_24_2), + set_configurations::AseConfiguration(lc3_24_2)}}, })); ASSERT_FALSE(codec_manager->CheckCodecConfigIsBiDirSwb({ - .confs = {.sink = {set_configurations::AseConfiguration(lc3_24_2), - set_configurations::AseConfiguration(lc3_24_2)}, - .source = {set_configurations::AseConfiguration(lc3_32_2), - set_configurations::AseConfiguration(lc3_32_2)}}, + .confs = {.sink = {set_configurations::AseConfiguration(lc3_24_2), + set_configurations::AseConfiguration(lc3_24_2)}, + .source = {set_configurations::AseConfiguration(lc3_32_2), + set_configurations::AseConfiguration(lc3_32_2)}}, })); ASSERT_FALSE(codec_manager->CheckCodecConfigIsBiDirSwb({ - .confs = {.sink = {set_configurations::AseConfiguration(lc3_32_2), - set_configurations::AseConfiguration(lc3_32_2)}, - .source = {set_configurations::AseConfiguration(lc3_24_2), - set_configurations::AseConfiguration(lc3_24_2)}}, + .confs = {.sink = {set_configurations::AseConfiguration(lc3_32_2), + set_configurations::AseConfiguration(lc3_32_2)}, + .source = {set_configurations::AseConfiguration(lc3_24_2), + set_configurations::AseConfiguration(lc3_24_2)}}, })); ASSERT_FALSE(codec_manager->CheckCodecConfigIsBiDirSwb({ - .confs = {.sink = {set_configurations::AseConfiguration(lc3_16_2), - set_configurations::AseConfiguration(lc3_16_2)}}, + .confs = {.sink = {set_configurations::AseConfiguration(lc3_16_2), + set_configurations::AseConfiguration(lc3_16_2)}}, })); ASSERT_FALSE(codec_manager->CheckCodecConfigIsBiDirSwb({ - .confs = {.source = {set_configurations::AseConfiguration(lc3_16_2), - set_configurations::AseConfiguration(lc3_16_2)}}, + .confs = {.source = {set_configurations::AseConfiguration(lc3_16_2), + set_configurations::AseConfiguration(lc3_16_2)}}, })); ASSERT_FALSE(codec_manager->CheckCodecConfigIsBiDirSwb({ - .confs = {.sink = {set_configurations::AseConfiguration(lc3_24_2), - set_configurations::AseConfiguration(lc3_24_2)}}, + .confs = {.sink = {set_configurations::AseConfiguration(lc3_24_2), + set_configurations::AseConfiguration(lc3_24_2)}}, })); ASSERT_FALSE(codec_manager->CheckCodecConfigIsBiDirSwb({ - .confs = {.source = {set_configurations::AseConfiguration(lc3_24_2), - set_configurations::AseConfiguration(lc3_24_2)}}, + .confs = {.source = {set_configurations::AseConfiguration(lc3_24_2), + set_configurations::AseConfiguration(lc3_24_2)}}, })); ASSERT_FALSE(codec_manager->CheckCodecConfigIsBiDirSwb({ - .confs = {.sink = {set_configurations::AseConfiguration(lc3_32_2), - set_configurations::AseConfiguration(lc3_32_2)}}, + .confs = {.sink = {set_configurations::AseConfiguration(lc3_32_2), + set_configurations::AseConfiguration(lc3_32_2)}}, })); ASSERT_FALSE(codec_manager->CheckCodecConfigIsBiDirSwb({ - .confs = {.source = {set_configurations::AseConfiguration(lc3_32_2), - set_configurations::AseConfiguration(lc3_32_2)}}, + .confs = {.source = {set_configurations::AseConfiguration(lc3_32_2), + set_configurations::AseConfiguration(lc3_32_2)}}, })); ASSERT_FALSE(codec_manager->CheckCodecConfigIsBiDirSwb({ - .confs = {.sink = {set_configurations::AseConfiguration(lc3_48_2), - set_configurations::AseConfiguration(lc3_48_2)}}, + .confs = {.sink = {set_configurations::AseConfiguration(lc3_48_2), + set_configurations::AseConfiguration(lc3_48_2)}}, })); ASSERT_FALSE(codec_manager->CheckCodecConfigIsBiDirSwb({ - .confs = {.source = {set_configurations::AseConfiguration(lc3_48_2), - set_configurations::AseConfiguration(lc3_48_2)}}, + .confs = {.source = {set_configurations::AseConfiguration(lc3_48_2), + set_configurations::AseConfiguration(lc3_48_2)}}, })); // NON-DUAL-SWB configs ASSERT_FALSE(codec_manager->CheckCodecConfigIsDualBiDirSwb({ - .confs = {.sink = {set_configurations::AseConfiguration(lc3_16_2), - set_configurations::AseConfiguration(lc3_16_2)}, - .source = {set_configurations::AseConfiguration(lc3_16_2), - set_configurations::AseConfiguration(lc3_16_2)}}, + .confs = {.sink = {set_configurations::AseConfiguration(lc3_16_2), + set_configurations::AseConfiguration(lc3_16_2)}, + .source = {set_configurations::AseConfiguration(lc3_16_2), + set_configurations::AseConfiguration(lc3_16_2)}}, })); ASSERT_FALSE(codec_manager->CheckCodecConfigIsDualBiDirSwb({ - .confs = {.sink = {set_configurations::AseConfiguration(lc3_24_2), - set_configurations::AseConfiguration(lc3_24_2)}, - .source = {set_configurations::AseConfiguration(lc3_16_2), - set_configurations::AseConfiguration(lc3_16_2)}}, + .confs = {.sink = {set_configurations::AseConfiguration(lc3_24_2), + set_configurations::AseConfiguration(lc3_24_2)}, + .source = {set_configurations::AseConfiguration(lc3_16_2), + set_configurations::AseConfiguration(lc3_16_2)}}, })); ASSERT_FALSE(codec_manager->CheckCodecConfigIsDualBiDirSwb({ - .confs = {.sink = {set_configurations::AseConfiguration(lc3_16_2), - set_configurations::AseConfiguration(lc3_16_2)}, - .source = {set_configurations::AseConfiguration(lc3_24_2), - set_configurations::AseConfiguration(lc3_24_2)}}, + .confs = {.sink = {set_configurations::AseConfiguration(lc3_16_2), + set_configurations::AseConfiguration(lc3_16_2)}, + .source = {set_configurations::AseConfiguration(lc3_24_2), + set_configurations::AseConfiguration(lc3_24_2)}}, })); ASSERT_FALSE(codec_manager->CheckCodecConfigIsDualBiDirSwb({ - .confs = {.sink = {set_configurations::AseConfiguration(lc3_16_2), - set_configurations::AseConfiguration(lc3_16_2)}, - .source = {set_configurations::AseConfiguration(lc3_32_2), - set_configurations::AseConfiguration(lc3_32_2)}}, + .confs = {.sink = {set_configurations::AseConfiguration(lc3_16_2), + set_configurations::AseConfiguration(lc3_16_2)}, + .source = {set_configurations::AseConfiguration(lc3_32_2), + set_configurations::AseConfiguration(lc3_32_2)}}, })); ASSERT_FALSE(codec_manager->CheckCodecConfigIsDualBiDirSwb({ - .confs = {.sink = {set_configurations::AseConfiguration(lc3_32_2), - set_configurations::AseConfiguration(lc3_32_2)}, - .source = {set_configurations::AseConfiguration(lc3_16_2), - set_configurations::AseConfiguration(lc3_16_2)}}, + .confs = {.sink = {set_configurations::AseConfiguration(lc3_32_2), + set_configurations::AseConfiguration(lc3_32_2)}, + .source = {set_configurations::AseConfiguration(lc3_16_2), + set_configurations::AseConfiguration(lc3_16_2)}}, })); ASSERT_FALSE(codec_manager->CheckCodecConfigIsDualBiDirSwb({ - .confs = {.sink = {set_configurations::AseConfiguration(lc3_24_2), - set_configurations::AseConfiguration(lc3_24_2)}, - .source = {set_configurations::AseConfiguration(lc3_24_2), - set_configurations::AseConfiguration(lc3_24_2)}}, + .confs = {.sink = {set_configurations::AseConfiguration(lc3_24_2), + set_configurations::AseConfiguration(lc3_24_2)}, + .source = {set_configurations::AseConfiguration(lc3_24_2), + set_configurations::AseConfiguration(lc3_24_2)}}, })); ASSERT_FALSE(codec_manager->CheckCodecConfigIsDualBiDirSwb({ - .confs = {.sink = {set_configurations::AseConfiguration(lc3_24_2), - set_configurations::AseConfiguration(lc3_24_2)}, - .source = {set_configurations::AseConfiguration(lc3_32_2), - set_configurations::AseConfiguration(lc3_32_2)}}, + .confs = {.sink = {set_configurations::AseConfiguration(lc3_24_2), + set_configurations::AseConfiguration(lc3_24_2)}, + .source = {set_configurations::AseConfiguration(lc3_32_2), + set_configurations::AseConfiguration(lc3_32_2)}}, })); ASSERT_FALSE(codec_manager->CheckCodecConfigIsDualBiDirSwb({ - .confs = {.sink = {set_configurations::AseConfiguration(lc3_32_2), - set_configurations::AseConfiguration(lc3_32_2)}, - .source = {set_configurations::AseConfiguration(lc3_24_2), - set_configurations::AseConfiguration(lc3_24_2)}}, + .confs = {.sink = {set_configurations::AseConfiguration(lc3_32_2), + set_configurations::AseConfiguration(lc3_32_2)}, + .source = {set_configurations::AseConfiguration(lc3_24_2), + set_configurations::AseConfiguration(lc3_24_2)}}, })); ASSERT_FALSE(codec_manager->CheckCodecConfigIsDualBiDirSwb({ - .confs = {.sink = {set_configurations::AseConfiguration(lc3_16_2), - set_configurations::AseConfiguration(lc3_16_2)}}, + .confs = {.sink = {set_configurations::AseConfiguration(lc3_16_2), + set_configurations::AseConfiguration(lc3_16_2)}}, })); ASSERT_FALSE(codec_manager->CheckCodecConfigIsDualBiDirSwb({ - .confs = {.source = {set_configurations::AseConfiguration(lc3_16_2), - set_configurations::AseConfiguration(lc3_16_2)}}, + .confs = {.source = {set_configurations::AseConfiguration(lc3_16_2), + set_configurations::AseConfiguration(lc3_16_2)}}, })); ASSERT_FALSE(codec_manager->CheckCodecConfigIsDualBiDirSwb({ - .confs = {.sink = {set_configurations::AseConfiguration(lc3_24_2), - set_configurations::AseConfiguration(lc3_24_2)}}, + .confs = {.sink = {set_configurations::AseConfiguration(lc3_24_2), + set_configurations::AseConfiguration(lc3_24_2)}}, })); ASSERT_FALSE(codec_manager->CheckCodecConfigIsDualBiDirSwb({ - .confs = {.source = {set_configurations::AseConfiguration(lc3_24_2), - set_configurations::AseConfiguration(lc3_24_2)}}, + .confs = {.source = {set_configurations::AseConfiguration(lc3_24_2), + set_configurations::AseConfiguration(lc3_24_2)}}, })); ASSERT_FALSE(codec_manager->CheckCodecConfigIsDualBiDirSwb({ - .confs = {.sink = {set_configurations::AseConfiguration(lc3_32_2), - set_configurations::AseConfiguration(lc3_32_2)}}, + .confs = {.sink = {set_configurations::AseConfiguration(lc3_32_2), + set_configurations::AseConfiguration(lc3_32_2)}}, })); ASSERT_FALSE(codec_manager->CheckCodecConfigIsDualBiDirSwb({ - .confs = {.source = {set_configurations::AseConfiguration(lc3_32_2), - set_configurations::AseConfiguration(lc3_32_2)}}, + .confs = {.source = {set_configurations::AseConfiguration(lc3_32_2), + set_configurations::AseConfiguration(lc3_32_2)}}, })); ASSERT_FALSE(codec_manager->CheckCodecConfigIsDualBiDirSwb({ - .confs = {.sink = {set_configurations::AseConfiguration(lc3_48_2), - set_configurations::AseConfiguration(lc3_48_2)}}, + .confs = {.sink = {set_configurations::AseConfiguration(lc3_48_2), + set_configurations::AseConfiguration(lc3_48_2)}}, })); ASSERT_FALSE(codec_manager->CheckCodecConfigIsDualBiDirSwb({ - .confs = {.source = {set_configurations::AseConfiguration(lc3_48_2), - set_configurations::AseConfiguration(lc3_48_2)}}, + .confs = {.source = {set_configurations::AseConfiguration(lc3_48_2), + set_configurations::AseConfiguration(lc3_48_2)}}, })); } TEST_F(CodecManagerTestHost, test_dual_bidir_swb) { - const std::vector - offloading_preference = { + const std::vector offloading_preference = { {.codec_type = bluetooth::le_audio::LE_AUDIO_CODEC_INDEX_SOURCE_LC3}}; codec_manager->Start(offloading_preference); // Single Dev BiDir SWB configs ASSERT_TRUE(codec_manager->CheckCodecConfigIsDualBiDirSwb({ - .confs = {.sink = {set_configurations::AseConfiguration(lc3_32_2), - set_configurations::AseConfiguration(lc3_32_2)}, - .source = {set_configurations::AseConfiguration(lc3_32_2), - set_configurations::AseConfiguration(lc3_32_2)}}, + .confs = {.sink = {set_configurations::AseConfiguration(lc3_32_2), + set_configurations::AseConfiguration(lc3_32_2)}, + .source = {set_configurations::AseConfiguration(lc3_32_2), + set_configurations::AseConfiguration(lc3_32_2)}}, })); ASSERT_TRUE(codec_manager->CheckCodecConfigIsDualBiDirSwb({ - .confs = {.sink = {set_configurations::AseConfiguration(lc3_48_2), - set_configurations::AseConfiguration(lc3_48_2)}, - .source = {set_configurations::AseConfiguration(lc3_32_2), - set_configurations::AseConfiguration(lc3_32_2)}}, + .confs = {.sink = {set_configurations::AseConfiguration(lc3_48_2), + set_configurations::AseConfiguration(lc3_48_2)}, + .source = {set_configurations::AseConfiguration(lc3_32_2), + set_configurations::AseConfiguration(lc3_32_2)}}, })); ASSERT_TRUE(codec_manager->CheckCodecConfigIsDualBiDirSwb({ - .confs = {.sink = {set_configurations::AseConfiguration(lc3_32_2), - set_configurations::AseConfiguration(lc3_32_2)}, - .source = {set_configurations::AseConfiguration(lc3_48_2), - set_configurations::AseConfiguration(lc3_48_2)}}, + .confs = {.sink = {set_configurations::AseConfiguration(lc3_32_2), + set_configurations::AseConfiguration(lc3_32_2)}, + .source = {set_configurations::AseConfiguration(lc3_48_2), + set_configurations::AseConfiguration(lc3_48_2)}}, })); ASSERT_TRUE(codec_manager->CheckCodecConfigIsDualBiDirSwb({ - .confs = {.sink = {set_configurations::AseConfiguration(lc3_48_2), - set_configurations::AseConfiguration(lc3_48_2)}, - .source = {set_configurations::AseConfiguration(lc3_48_2), - set_configurations::AseConfiguration(lc3_48_2)}}, + .confs = {.sink = {set_configurations::AseConfiguration(lc3_48_2), + set_configurations::AseConfiguration(lc3_48_2)}, + .source = {set_configurations::AseConfiguration(lc3_48_2), + set_configurations::AseConfiguration(lc3_48_2)}}, })); } TEST_F(CodecManagerTestHost, test_dual_bidir_swb_supported) { - const std::vector - offloading_preference = { + const std::vector offloading_preference = { {.codec_type = bluetooth::le_audio::LE_AUDIO_CODEC_INDEX_SOURCE_LC3}}; codec_manager->Start(offloading_preference); @@ -1098,23 +1001,22 @@ TEST_F(CodecManagerTestHost, test_dual_bidir_swb_supported) { for (auto context : types::kLeAudioContextAllTypesArray) { bool got_null_cfgs_container = false; auto ptr = codec_manager->GetCodecConfig( - {.audio_context_type = context}, - [&](const CodecManager::UnicastConfigurationRequirements& requirements, - const set_configurations::AudioSetConfigurations* confs) - -> const set_configurations::AudioSetConfiguration* { - if (confs == nullptr) { - got_null_cfgs_container = true; - } else { - num_of_dual_bidir_swb_configs += std::count_if( - confs->begin(), confs->end(), [&](auto const& cfg) { - bool is_bidir = - codec_manager->CheckCodecConfigIsDualBiDirSwb(*cfg); - return codec_manager->CheckCodecConfigIsDualBiDirSwb(*cfg); - }); - } - // In this case the chosen configuration doesn't matter - select none - return nullptr; - }); + {.audio_context_type = context}, + [&](const CodecManager::UnicastConfigurationRequirements& requirements, + const set_configurations::AudioSetConfigurations* confs) + -> const set_configurations::AudioSetConfiguration* { + if (confs == nullptr) { + got_null_cfgs_container = true; + } else { + num_of_dual_bidir_swb_configs += + std::count_if(confs->begin(), confs->end(), [&](auto const& cfg) { + bool is_bidir = codec_manager->CheckCodecConfigIsDualBiDirSwb(*cfg); + return codec_manager->CheckCodecConfigIsDualBiDirSwb(*cfg); + }); + } + // In this case the chosen configuration doesn't matter - select none + return nullptr; + }); ASSERT_FALSE(got_null_cfgs_container); } @@ -1125,24 +1027,23 @@ TEST_F(CodecManagerTestHost, test_dual_bidir_swb_supported) { TEST_F(CodecManagerTestAdsp, test_dual_bidir_swb_supported) { // Set the offloader capabilities std::vector offload_capabilities = { - { - .name = "Test_Bidir_SWB_Config_No_Dev_lc3_32_2", - .confs = {.sink = {set_configurations::AseConfiguration(lc3_32_2), - set_configurations::AseConfiguration(lc3_32_2)}, - .source = {set_configurations::AseConfiguration(lc3_32_2), - set_configurations::AseConfiguration(lc3_32_2)}}, - }, - { - .name = "Test_Bidir_Non_SWB_Config_No_Dev_lc3_16_2", - .confs = {.sink = {set_configurations::AseConfiguration(lc3_16_2), - set_configurations::AseConfiguration(lc3_16_2)}, - .source = {set_configurations::AseConfiguration(lc3_16_2), - set_configurations::AseConfiguration(lc3_16_2)}}, - }}; + { + .name = "Test_Bidir_SWB_Config_No_Dev_lc3_32_2", + .confs = {.sink = {set_configurations::AseConfiguration(lc3_32_2), + set_configurations::AseConfiguration(lc3_32_2)}, + .source = {set_configurations::AseConfiguration(lc3_32_2), + set_configurations::AseConfiguration(lc3_32_2)}}, + }, + { + .name = "Test_Bidir_Non_SWB_Config_No_Dev_lc3_16_2", + .confs = {.sink = {set_configurations::AseConfiguration(lc3_16_2), + set_configurations::AseConfiguration(lc3_16_2)}, + .source = {set_configurations::AseConfiguration(lc3_16_2), + set_configurations::AseConfiguration(lc3_16_2)}}, + }}; set_mock_offload_capabilities(offload_capabilities); - const std::vector - offloading_preference = { + const std::vector offloading_preference = { {.codec_type = bluetooth::le_audio::LE_AUDIO_CODEC_INDEX_SOURCE_LC3}}; codec_manager->Start(offloading_preference); @@ -1150,23 +1051,22 @@ TEST_F(CodecManagerTestAdsp, test_dual_bidir_swb_supported) { for (auto context : types::kLeAudioContextAllTypesArray) { bool got_null_cfgs_container = false; auto ptr = codec_manager->GetCodecConfig( - {.audio_context_type = context}, - [&](const CodecManager::UnicastConfigurationRequirements& requirements, - const set_configurations::AudioSetConfigurations* confs) - -> const set_configurations::AudioSetConfiguration* { - if (confs == nullptr) { - got_null_cfgs_container = true; - } else { - num_of_dual_bidir_swb_configs += std::count_if( - confs->begin(), confs->end(), [&](auto const& cfg) { - bool is_bidir = - codec_manager->CheckCodecConfigIsDualBiDirSwb(*cfg); - return codec_manager->CheckCodecConfigIsDualBiDirSwb(*cfg); - }); - } - // In this case the chosen configuration doesn't matter - select none - return nullptr; - }); + {.audio_context_type = context}, + [&](const CodecManager::UnicastConfigurationRequirements& requirements, + const set_configurations::AudioSetConfigurations* confs) + -> const set_configurations::AudioSetConfiguration* { + if (confs == nullptr) { + got_null_cfgs_container = true; + } else { + num_of_dual_bidir_swb_configs += + std::count_if(confs->begin(), confs->end(), [&](auto const& cfg) { + bool is_bidir = codec_manager->CheckCodecConfigIsDualBiDirSwb(*cfg); + return codec_manager->CheckCodecConfigIsDualBiDirSwb(*cfg); + }); + } + // In this case the chosen configuration doesn't matter - select none + return nullptr; + }); ASSERT_FALSE(got_null_cfgs_container); } @@ -1175,8 +1075,7 @@ TEST_F(CodecManagerTestAdsp, test_dual_bidir_swb_supported) { } TEST_F(CodecManagerTestHostNoSwb, test_dual_bidir_swb_not_supported) { - const std::vector - offloading_preference = { + const std::vector offloading_preference = { {.codec_type = bluetooth::le_audio::LE_AUDIO_CODEC_INDEX_SOURCE_LC3}}; codec_manager->Start(offloading_preference); @@ -1184,21 +1083,21 @@ TEST_F(CodecManagerTestHostNoSwb, test_dual_bidir_swb_not_supported) { for (auto context : types::kLeAudioContextAllTypesArray) { bool got_null_cfgs_container = false; auto ptr = codec_manager->GetCodecConfig( - {.audio_context_type = context}, - [&](const CodecManager::UnicastConfigurationRequirements& requirements, - const set_configurations::AudioSetConfigurations* confs) - -> const set_configurations::AudioSetConfiguration* { - if (confs == nullptr) { - got_null_cfgs_container = true; - } else { - num_of_dual_bidir_swb_configs += std::count_if( - confs->begin(), confs->end(), [&](auto const& cfg) { - return codec_manager->CheckCodecConfigIsDualBiDirSwb(*cfg); - }); - } - // In this case the chosen configuration doesn't matter - select none - return nullptr; - }); + {.audio_context_type = context}, + [&](const CodecManager::UnicastConfigurationRequirements& requirements, + const set_configurations::AudioSetConfigurations* confs) + -> const set_configurations::AudioSetConfiguration* { + if (confs == nullptr) { + got_null_cfgs_container = true; + } else { + num_of_dual_bidir_swb_configs += + std::count_if(confs->begin(), confs->end(), [&](auto const& cfg) { + return codec_manager->CheckCodecConfigIsDualBiDirSwb(*cfg); + }); + } + // In this case the chosen configuration doesn't matter - select none + return nullptr; + }); ASSERT_FALSE(got_null_cfgs_container); } @@ -1209,24 +1108,23 @@ TEST_F(CodecManagerTestHostNoSwb, test_dual_bidir_swb_not_supported) { TEST_F(CodecManagerTestAdspNoSwb, test_dual_bidir_swb_not_supported) { // Set the offloader capabilities std::vector offload_capabilities = { - { - .name = "Test_Bidir_SWB_Config_No_Dev_lc3_32_2", - .confs = {.sink = {set_configurations::AseConfiguration(lc3_32_2), - set_configurations::AseConfiguration(lc3_32_2)}, - .source = {set_configurations::AseConfiguration(lc3_32_2), - set_configurations::AseConfiguration(lc3_32_2)}}, - }, - { - .name = "Test_Bidir_Non_SWB_Config_No_Dev_lc3_16_2", - .confs = {.sink = {set_configurations::AseConfiguration(lc3_16_2), - set_configurations::AseConfiguration(lc3_16_2)}, - .source = {set_configurations::AseConfiguration(lc3_16_2), - set_configurations::AseConfiguration(lc3_16_2)}}, - }}; + { + .name = "Test_Bidir_SWB_Config_No_Dev_lc3_32_2", + .confs = {.sink = {set_configurations::AseConfiguration(lc3_32_2), + set_configurations::AseConfiguration(lc3_32_2)}, + .source = {set_configurations::AseConfiguration(lc3_32_2), + set_configurations::AseConfiguration(lc3_32_2)}}, + }, + { + .name = "Test_Bidir_Non_SWB_Config_No_Dev_lc3_16_2", + .confs = {.sink = {set_configurations::AseConfiguration(lc3_16_2), + set_configurations::AseConfiguration(lc3_16_2)}, + .source = {set_configurations::AseConfiguration(lc3_16_2), + set_configurations::AseConfiguration(lc3_16_2)}}, + }}; set_mock_offload_capabilities(offload_capabilities); - const std::vector - offloading_preference = { + const std::vector offloading_preference = { {.codec_type = bluetooth::le_audio::LE_AUDIO_CODEC_INDEX_SOURCE_LC3}}; codec_manager->Start(offloading_preference); @@ -1234,21 +1132,21 @@ TEST_F(CodecManagerTestAdspNoSwb, test_dual_bidir_swb_not_supported) { for (auto context : types::kLeAudioContextAllTypesArray) { bool got_null_cfgs_container = false; auto ptr = codec_manager->GetCodecConfig( - {.audio_context_type = context}, - [&](const CodecManager::UnicastConfigurationRequirements& requirements, - const set_configurations::AudioSetConfigurations* confs) - -> const set_configurations::AudioSetConfiguration* { - if (confs == nullptr) { - got_null_cfgs_container = true; - } else { - num_of_dual_bidir_swb_configs += std::count_if( - confs->begin(), confs->end(), [&](auto const& cfg) { - return codec_manager->CheckCodecConfigIsDualBiDirSwb(*cfg); - }); - } - // In this case the chosen configuration doesn't matter - select none - return nullptr; - }); + {.audio_context_type = context}, + [&](const CodecManager::UnicastConfigurationRequirements& requirements, + const set_configurations::AudioSetConfigurations* confs) + -> const set_configurations::AudioSetConfiguration* { + if (confs == nullptr) { + got_null_cfgs_container = true; + } else { + num_of_dual_bidir_swb_configs += + std::count_if(confs->begin(), confs->end(), [&](auto const& cfg) { + return codec_manager->CheckCodecConfigIsDualBiDirSwb(*cfg); + }); + } + // In this case the chosen configuration doesn't matter - select none + return nullptr; + }); ASSERT_FALSE(got_null_cfgs_container); } @@ -1257,17 +1155,14 @@ TEST_F(CodecManagerTestAdspNoSwb, test_dual_bidir_swb_not_supported) { } TEST_F(CodecManagerTestHost, test_dont_update_broadcast_offloader) { - const std::vector - offloading_preference = { + const std::vector offloading_preference = { {.codec_type = bluetooth::le_audio::LE_AUDIO_CODEC_INDEX_SOURCE_LC3}}; codec_manager->Start(offloading_preference); bool was_called = false; codec_manager->UpdateBroadcastConnHandle( - {0x0001, 0x0002}, - [&](const bluetooth::le_audio::broadcast_offload_config& config) { - was_called = true; - }); + {0x0001, 0x0002}, + [&](const bluetooth::le_audio::broadcast_offload_config& config) { was_called = true; }); // Expect no call for HOST encoding ASSERT_FALSE(was_called); diff --git a/system/bta/le_audio/content_control_id_keeper.cc b/system/bta/le_audio/content_control_id_keeper.cc index 3f5d410368a..7bc7dc810f6 100644 --- a/system/bta/le_audio/content_control_id_keeper.cc +++ b/system/bta/le_audio/content_control_id_keeper.cc @@ -34,7 +34,7 @@ using bluetooth::le_audio::types::LeAudioContextType; namespace bluetooth::le_audio { struct ccid_keeper { - public: +public: ccid_keeper() {} ~ccid_keeper() {} @@ -56,7 +56,9 @@ struct ccid_keeper { } for (auto ctx : types::kLeAudioContextAllTypesArray) { - if (contexts.test(ctx)) SetCcid(ctx, ccid); + if (contexts.test(ctx)) { + SetCcid(ctx, ccid); + } } } @@ -87,7 +89,7 @@ struct ccid_keeper { return ccids_.at(context_type); } - private: +private: /* Ccid informations */ std::map ccids_; }; @@ -96,14 +98,12 @@ struct ContentControlIdKeeper::impl { impl(const ContentControlIdKeeper& ccid_keeper) : ccid_keeper_(ccid_keeper) {} void Start() { - log::assert_that(ccid_keeper_impl_ == nullptr, - "assert failed: ccid_keeper_impl_ == nullptr"); + log::assert_that(ccid_keeper_impl_ == nullptr, "assert failed: ccid_keeper_impl_ == nullptr"); ccid_keeper_impl_ = std::make_unique(); } void Stop() { - log::assert_that(ccid_keeper_impl_ != nullptr, - "assert failed: ccid_keeper_impl_ != nullptr"); + log::assert_that(ccid_keeper_impl_ != nullptr, "assert failed: ccid_keeper_impl_ != nullptr"); ccid_keeper_impl_.reset(); } @@ -113,19 +113,21 @@ struct ContentControlIdKeeper::impl { std::unique_ptr ccid_keeper_impl_; }; -ContentControlIdKeeper::ContentControlIdKeeper() - : pimpl_(std::make_unique(*this)) {} +ContentControlIdKeeper::ContentControlIdKeeper() : pimpl_(std::make_unique(*this)) {} void ContentControlIdKeeper::Start() { - if (!pimpl_->IsRunning()) pimpl_->Start(); + if (!pimpl_->IsRunning()) { + pimpl_->Start(); + } } void ContentControlIdKeeper::Stop() { - if (pimpl_->IsRunning()) pimpl_->Stop(); + if (pimpl_->IsRunning()) { + pimpl_->Stop(); + } } -int ContentControlIdKeeper::GetCcid( - types::LeAudioContextType context_type) const { +int ContentControlIdKeeper::GetCcid(types::LeAudioContextType context_type) const { if (!pimpl_->IsRunning()) { return -1; } @@ -133,8 +135,7 @@ int ContentControlIdKeeper::GetCcid( return pimpl_->ccid_keeper_impl_->GetCcid(context_type); } -void ContentControlIdKeeper::SetCcid(types::LeAudioContextType context_type, - int ccid) { +void ContentControlIdKeeper::SetCcid(types::LeAudioContextType context_type, int ccid) { if (pimpl_->IsRunning()) { if (context_type == types::LeAudioContextType::UNINITIALIZED) { pimpl_->ccid_keeper_impl_->RemoveCcid(ccid); @@ -144,16 +145,19 @@ void ContentControlIdKeeper::SetCcid(types::LeAudioContextType context_type, } } -void ContentControlIdKeeper::SetCcid(const types::AudioContexts& contexts, - int ccid) { - if (pimpl_->IsRunning()) pimpl_->ccid_keeper_impl_->SetCcid(contexts, ccid); +void ContentControlIdKeeper::SetCcid(const types::AudioContexts& contexts, int ccid) { + if (pimpl_->IsRunning()) { + pimpl_->ccid_keeper_impl_->SetCcid(contexts, ccid); + } } std::vector ContentControlIdKeeper::GetAllCcids( - const types::AudioContexts& contexts) const { + const types::AudioContexts& contexts) const { std::vector ccid_vec; for (LeAudioContextType context : types::kLeAudioContextAllTypesArray) { - if (!contexts.test(context)) continue; + if (!contexts.test(context)) { + continue; + } auto ccid = GetCcid(context); if (ccid != -1) { // Remove duplicates in case more than one context maps to the same CCID diff --git a/system/bta/le_audio/content_control_id_keeper.h b/system/bta/le_audio/content_control_id_keeper.h index 20b50a5c8f8..9ab4a33531b 100644 --- a/system/bta/le_audio/content_control_id_keeper.h +++ b/system/bta/le_audio/content_control_id_keeper.h @@ -24,7 +24,7 @@ namespace bluetooth::le_audio { class ContentControlIdKeeper { - public: +public: ContentControlIdKeeper(); ~ContentControlIdKeeper() = default; static ContentControlIdKeeper* GetInstance(void) { @@ -38,7 +38,7 @@ class ContentControlIdKeeper { int GetCcid(types::LeAudioContextType context_type) const; std::vector GetAllCcids(const types::AudioContexts& contexts) const; - private: +private: struct impl; std::unique_ptr pimpl_; }; diff --git a/system/bta/le_audio/content_control_id_keeper_test.cc b/system/bta/le_audio/content_control_id_keeper_test.cc index 0a9898fadea..830e3bf02d5 100644 --- a/system/bta/le_audio/content_control_id_keeper_test.cc +++ b/system/bta/le_audio/content_control_id_keeper_test.cc @@ -39,29 +39,25 @@ TEST(ContentControlIdKeeperTest, testMultipleSetGetOneCcid) { int ccid_one = 1; - ccid_keeper->SetCcid( - types::LeAudioContextType::MEDIA | types::LeAudioContextType::ALERTS, - ccid_one); + ccid_keeper->SetCcid(types::LeAudioContextType::MEDIA | types::LeAudioContextType::ALERTS, + ccid_one); ASSERT_EQ(ccid_one, ccid_keeper->GetCcid(types::LeAudioContextType::MEDIA)); ASSERT_EQ(ccid_one, ccid_keeper->GetCcid(types::LeAudioContextType::ALERTS)); - auto media_ccids = ccid_keeper->GetAllCcids( - types::AudioContexts(types::LeAudioContextType::MEDIA)); + auto media_ccids = + ccid_keeper->GetAllCcids(types::AudioContexts(types::LeAudioContextType::MEDIA)); ASSERT_EQ(1LU, media_ccids.size()); - ASSERT_NE(media_ccids.end(), - std::find(media_ccids.begin(), media_ccids.end(), ccid_one)); + ASSERT_NE(media_ccids.end(), std::find(media_ccids.begin(), media_ccids.end(), ccid_one)); - auto allerts_ccids = ccid_keeper->GetAllCcids( - types::AudioContexts(types::LeAudioContextType::ALERTS)); + auto allerts_ccids = + ccid_keeper->GetAllCcids(types::AudioContexts(types::LeAudioContextType::ALERTS)); ASSERT_EQ(1LU, allerts_ccids.size()); - ASSERT_NE(allerts_ccids.end(), - std::find(allerts_ccids.begin(), allerts_ccids.end(), ccid_one)); + ASSERT_NE(allerts_ccids.end(), std::find(allerts_ccids.begin(), allerts_ccids.end(), ccid_one)); auto all_ccids = ccid_keeper->GetAllCcids(types::LeAudioContextType::MEDIA | types::LeAudioContextType::ALERTS); ASSERT_EQ(1LU, all_ccids.size()); - ASSERT_NE(all_ccids.end(), - std::find(all_ccids.begin(), all_ccids.end(), ccid_one)); + ASSERT_NE(all_ccids.end(), std::find(all_ccids.begin(), all_ccids.end(), ccid_one)); ccid_keeper->Stop(); } @@ -77,28 +73,23 @@ TEST(ContentControlIdKeeperTest, testMultipleSetGetMultipleCcids) { ccid_keeper->SetCcid(types::LeAudioContextType::MEDIA, ccid_two); ASSERT_EQ(ccid_two, ccid_keeper->GetCcid(types::LeAudioContextType::MEDIA)); ccid_keeper->SetCcid(types::LeAudioContextType::ALERTS, ccid_three); - ASSERT_EQ(ccid_three, - ccid_keeper->GetCcid(types::LeAudioContextType::ALERTS)); + ASSERT_EQ(ccid_three, ccid_keeper->GetCcid(types::LeAudioContextType::ALERTS)); - auto media_ccids = ccid_keeper->GetAllCcids( - types::AudioContexts(types::LeAudioContextType::MEDIA)); + auto media_ccids = + ccid_keeper->GetAllCcids(types::AudioContexts(types::LeAudioContextType::MEDIA)); ASSERT_EQ(1LU, media_ccids.size()); - ASSERT_NE(media_ccids.end(), - std::find(media_ccids.begin(), media_ccids.end(), ccid_two)); + ASSERT_NE(media_ccids.end(), std::find(media_ccids.begin(), media_ccids.end(), ccid_two)); - auto allerts_ccids = ccid_keeper->GetAllCcids( - types::AudioContexts(types::LeAudioContextType::ALERTS)); + auto allerts_ccids = + ccid_keeper->GetAllCcids(types::AudioContexts(types::LeAudioContextType::ALERTS)); ASSERT_EQ(1LU, allerts_ccids.size()); - ASSERT_NE(allerts_ccids.end(), - std::find(allerts_ccids.begin(), allerts_ccids.end(), ccid_three)); + ASSERT_NE(allerts_ccids.end(), std::find(allerts_ccids.begin(), allerts_ccids.end(), ccid_three)); auto all_ccids = ccid_keeper->GetAllCcids(types::LeAudioContextType::MEDIA | types::LeAudioContextType::ALERTS); ASSERT_EQ(2LU, all_ccids.size()); - ASSERT_NE(all_ccids.end(), - std::find(all_ccids.begin(), all_ccids.end(), ccid_two)); - ASSERT_NE(all_ccids.end(), - std::find(all_ccids.begin(), all_ccids.end(), ccid_three)); + ASSERT_NE(all_ccids.end(), std::find(all_ccids.begin(), all_ccids.end(), ccid_two)); + ASSERT_NE(all_ccids.end(), std::find(all_ccids.begin(), all_ccids.end(), ccid_three)); ccid_keeper->Stop(); } diff --git a/system/bta/le_audio/device_groups.cc b/system/bta/le_audio/device_groups.cc index 40adba79aa8..c4f41a26f37 100644 --- a/system/bta/le_audio/device_groups.cc +++ b/system/bta/le_audio/device_groups.cc @@ -50,15 +50,13 @@ using types::LeAudioContextType; using types::LeAudioCoreCodecConfig; /* LeAudioDeviceGroup Class methods implementation */ -void LeAudioDeviceGroup::AddNode( - const std::shared_ptr& leAudioDevice) { +void LeAudioDeviceGroup::AddNode(const std::shared_ptr& leAudioDevice) { leAudioDevice->group_id_ = group_id_; leAudioDevices_.push_back(std::weak_ptr(leAudioDevice)); MetricsCollector::Get()->OnGroupSizeUpdate(group_id_, leAudioDevices_.size()); } -void LeAudioDeviceGroup::RemoveNode( - const std::shared_ptr& leAudioDevice) { +void LeAudioDeviceGroup::RemoveNode(const std::shared_ptr& leAudioDevice) { /* Group information cleaning in the device. */ leAudioDevice->group_id_ = bluetooth::groups::kGroupUnknown; for (auto ase : leAudioDevice->ases_) { @@ -67,20 +65,15 @@ void LeAudioDeviceGroup::RemoveNode( } leAudioDevices_.erase( - std::remove_if( - leAudioDevices_.begin(), leAudioDevices_.end(), - [&leAudioDevice](auto& d) { return d.lock() == leAudioDevice; }), - leAudioDevices_.end()); + std::remove_if(leAudioDevices_.begin(), leAudioDevices_.end(), + [&leAudioDevice](auto& d) { return d.lock() == leAudioDevice; }), + leAudioDevices_.end()); MetricsCollector::Get()->OnGroupSizeUpdate(group_id_, leAudioDevices_.size()); } -bool LeAudioDeviceGroup::IsEmpty(void) const { - return leAudioDevices_.size() == 0; -} +bool LeAudioDeviceGroup::IsEmpty(void) const { return leAudioDevices_.size() == 0; } -bool LeAudioDeviceGroup::IsAnyDeviceConnected(void) const { - return (NumOfConnected() != 0); -} +bool LeAudioDeviceGroup::IsAnyDeviceConnected(void) const { return NumOfConnected() != 0; } int LeAudioDeviceGroup::Size(void) const { return leAudioDevices_.size(); } @@ -95,33 +88,31 @@ int LeAudioDeviceGroup::DesiredSize(void) const { int LeAudioDeviceGroup::NumOfConnected() const { /* return number of connected devices from the set*/ - return std::count_if( - leAudioDevices_.begin(), leAudioDevices_.end(), [](auto& iter) { - auto dev = iter.lock(); - if (dev) { - return (dev->conn_id_ != GATT_INVALID_CONN_ID) && - (dev->GetConnectionState() == DeviceConnectState::CONNECTED); - } - return false; - }); + return std::count_if(leAudioDevices_.begin(), leAudioDevices_.end(), [](auto& iter) { + auto dev = iter.lock(); + if (dev) { + return (dev->conn_id_ != GATT_INVALID_CONN_ID) && + (dev->GetConnectionState() == DeviceConnectState::CONNECTED); + } + return false; + }); } int LeAudioDeviceGroup::NumOfAvailableForDirection(int direction) const { bool check_ase_count = direction < types::kLeAudioDirectionBoth; /* return number of connected devices from the set with supported context */ - return std::count_if( - leAudioDevices_.begin(), leAudioDevices_.end(), [&](auto& iter) { - auto dev = iter.lock(); - if (dev) { - if (check_ase_count && (dev->GetAseCount(direction) == 0)) { - return false; - } - return (dev->conn_id_ != GATT_INVALID_CONN_ID) && - (dev->GetConnectionState() == DeviceConnectState::CONNECTED); - } + return std::count_if(leAudioDevices_.begin(), leAudioDevices_.end(), [&](auto& iter) { + auto dev = iter.lock(); + if (dev) { + if (check_ase_count && (dev->GetAseCount(direction) == 0)) { return false; - }); + } + return (dev->conn_id_ != GATT_INVALID_CONN_ID) && + (dev->GetConnectionState() == DeviceConnectState::CONNECTED); + } + return false; + }); } void LeAudioDeviceGroup::ClearSinksFromConfiguration(void) { @@ -149,40 +140,35 @@ void LeAudioDeviceGroup::ClearAllCises(void) { void LeAudioDeviceGroup::UpdateCisConfiguration(uint8_t direction) { CodecManager::GetInstance()->UpdateCisConfiguration( - cig.cises, stream_conf.stream_params.get(direction), direction); + cig.cises, stream_conf.stream_params.get(direction), direction); } void LeAudioDeviceGroup::Cleanup(void) { /* Bluetooth is off while streaming - disconnect CISes and remove CIG */ if (GetState() == AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) { - auto& sink_stream_locations = - stream_conf.stream_params.sink.stream_locations; - auto& source_stream_locations = - stream_conf.stream_params.source.stream_locations; + auto& sink_stream_locations = stream_conf.stream_params.sink.stream_locations; + auto& source_stream_locations = stream_conf.stream_params.source.stream_locations; if (!sink_stream_locations.empty()) { for (const auto kv_pair : sink_stream_locations) { auto cis_handle = kv_pair.first; - bluetooth::hci::IsoManager::GetInstance()->DisconnectCis( - cis_handle, HCI_ERR_PEER_USER); + bluetooth::hci::IsoManager::GetInstance()->DisconnectCis(cis_handle, HCI_ERR_PEER_USER); /* Check the other direction if disconnecting bidirectional CIS */ if (source_stream_locations.empty()) { continue; } source_stream_locations.erase( - std::remove_if( - source_stream_locations.begin(), source_stream_locations.end(), - [&cis_handle](auto& pair) { return pair.first == cis_handle; }), - source_stream_locations.end()); + std::remove_if(source_stream_locations.begin(), source_stream_locations.end(), + [&cis_handle](auto& pair) { return pair.first == cis_handle; }), + source_stream_locations.end()); } } /* Take care of the non-bidirectional CISes */ if (!source_stream_locations.empty()) { for (auto [cis_handle, _] : source_stream_locations) { - bluetooth::hci::IsoManager::GetInstance()->DisconnectCis( - cis_handle, HCI_ERR_PEER_USER); + bluetooth::hci::IsoManager::GetInstance()->DisconnectCis(cis_handle, HCI_ERR_PEER_USER); } } } @@ -207,16 +193,17 @@ void LeAudioDeviceGroup::Deactivate(void) { } } -bool LeAudioDeviceGroup::Activate( - LeAudioContextType context_type, - const BidirectionalPair& metadata_context_types, - BidirectionalPair> ccid_lists) { +bool LeAudioDeviceGroup::Activate(LeAudioContextType context_type, + const BidirectionalPair& metadata_context_types, + BidirectionalPair> ccid_lists) { bool is_activate = false; for (auto leAudioDevice : leAudioDevices_) { - if (leAudioDevice.expired()) continue; + if (leAudioDevice.expired()) { + continue; + } bool activated = leAudioDevice.lock()->ActivateConfiguredAses( - context_type, metadata_context_types, ccid_lists); + context_type, metadata_context_types, ccid_lists); log::info("Device {} is {}", leAudioDevice.lock().get()->address_, activated ? "activated" : " not activated"); if (activated) { @@ -244,202 +231,221 @@ LeAudioDevice* LeAudioDeviceGroup::GetFirstDevice(void) const { auto iter = std::find_if(leAudioDevices_.begin(), leAudioDevices_.end(), [](auto& iter) { return !iter.expired(); }); - if (iter == leAudioDevices_.end()) return nullptr; + if (iter == leAudioDevices_.end()) { + return nullptr; + } return (iter->lock()).get(); } LeAudioDevice* LeAudioDeviceGroup::GetFirstDeviceWithAvailableContext( - LeAudioContextType context_type) const { - auto iter = std::find_if( - leAudioDevices_.begin(), leAudioDevices_.end(), - [&context_type](auto& iter) { - if (iter.expired()) return false; - return iter.lock()->GetAvailableContexts().test(context_type); - }); - - if ((iter == leAudioDevices_.end()) || (iter->expired())) return nullptr; + LeAudioContextType context_type) const { + auto iter = + std::find_if(leAudioDevices_.begin(), leAudioDevices_.end(), [&context_type](auto& iter) { + if (iter.expired()) { + return false; + } + return iter.lock()->GetAvailableContexts().test(context_type); + }); + + if ((iter == leAudioDevices_.end()) || (iter->expired())) { + return nullptr; + } return (iter->lock()).get(); } -LeAudioDevice* LeAudioDeviceGroup::GetNextDevice( - LeAudioDevice* leAudioDevice) const { - auto iter = std::find_if(leAudioDevices_.begin(), leAudioDevices_.end(), - [&leAudioDevice](auto& d) { - if (d.expired()) - return false; - else - return (d.lock()).get() == leAudioDevice; - }); +LeAudioDevice* LeAudioDeviceGroup::GetNextDevice(LeAudioDevice* leAudioDevice) const { + auto iter = + std::find_if(leAudioDevices_.begin(), leAudioDevices_.end(), [&leAudioDevice](auto& d) { + if (d.expired()) { + return false; + } else { + return (d.lock()).get() == leAudioDevice; + } + }); /* If reference device not found */ - if (iter == leAudioDevices_.end()) return nullptr; + if (iter == leAudioDevices_.end()) { + return nullptr; + } std::advance(iter, 1); /* If reference device is last in group */ - if (iter == leAudioDevices_.end()) return nullptr; + if (iter == leAudioDevices_.end()) { + return nullptr; + } - if (iter->expired()) return nullptr; + if (iter->expired()) { + return nullptr; + } return (iter->lock()).get(); } LeAudioDevice* LeAudioDeviceGroup::GetNextDeviceWithAvailableContext( - LeAudioDevice* leAudioDevice, LeAudioContextType context_type) const { - auto iter = std::find_if(leAudioDevices_.begin(), leAudioDevices_.end(), - [&leAudioDevice](auto& d) { - if (d.expired()) - return false; - else - return (d.lock()).get() == leAudioDevice; - }); + LeAudioDevice* leAudioDevice, LeAudioContextType context_type) const { + auto iter = + std::find_if(leAudioDevices_.begin(), leAudioDevices_.end(), [&leAudioDevice](auto& d) { + if (d.expired()) { + return false; + } else { + return (d.lock()).get() == leAudioDevice; + } + }); /* If reference device not found */ - if (iter == leAudioDevices_.end()) return nullptr; + if (iter == leAudioDevices_.end()) { + return nullptr; + } std::advance(iter, 1); /* If reference device is last in group */ - if (iter == leAudioDevices_.end()) return nullptr; + if (iter == leAudioDevices_.end()) { + return nullptr; + } iter = std::find_if(iter, leAudioDevices_.end(), [&context_type](auto& d) { - if (d.expired()) + if (d.expired()) { return false; - else + } else { return d.lock()->GetAvailableContexts().test(context_type); - ; + }; }); return (iter == leAudioDevices_.end()) ? nullptr : (iter->lock()).get(); } -bool LeAudioDeviceGroup::IsDeviceInTheGroup( - LeAudioDevice* leAudioDevice) const { - auto iter = std::find_if(leAudioDevices_.begin(), leAudioDevices_.end(), - [&leAudioDevice](auto& d) { - if (d.expired()) - return false; - else - return (d.lock()).get() == leAudioDevice; - }); - - if ((iter == leAudioDevices_.end()) || (iter->expired())) return false; +bool LeAudioDeviceGroup::IsDeviceInTheGroup(LeAudioDevice* leAudioDevice) const { + auto iter = + std::find_if(leAudioDevices_.begin(), leAudioDevices_.end(), [&leAudioDevice](auto& d) { + if (d.expired()) { + return false; + } else { + return (d.lock()).get() == leAudioDevice; + } + }); + + if ((iter == leAudioDevices_.end()) || (iter->expired())) { + return false; + } return true; } bool LeAudioDeviceGroup::IsGroupReadyToCreateStream(void) const { - auto iter = - std::find_if(leAudioDevices_.begin(), leAudioDevices_.end(), [](auto& d) { - if (d.expired()) - return false; - else - return !(((d.lock()).get())->IsReadyToCreateStream()); - }); + auto iter = std::find_if(leAudioDevices_.begin(), leAudioDevices_.end(), [](auto& d) { + if (d.expired()) { + return false; + } else { + return !(((d.lock()).get())->IsReadyToCreateStream()); + } + }); return iter == leAudioDevices_.end(); } bool LeAudioDeviceGroup::IsGroupReadyToSuspendStream(void) const { - auto iter = - std::find_if(leAudioDevices_.begin(), leAudioDevices_.end(), [](auto& d) { - if (d.expired()) - return false; - else - return !(((d.lock()).get())->IsReadyToSuspendStream()); - }); + auto iter = std::find_if(leAudioDevices_.begin(), leAudioDevices_.end(), [](auto& d) { + if (d.expired()) { + return false; + } else { + return !(((d.lock()).get())->IsReadyToSuspendStream()); + } + }); return iter == leAudioDevices_.end(); } bool LeAudioDeviceGroup::HaveAnyActiveDeviceInStreamingState() const { - auto iter = - std::find_if(leAudioDevices_.begin(), leAudioDevices_.end(), [](auto& d) { - if (d.expired()) - return false; - else - return (((d.lock()).get())->HaveAnyStreamingAses()); - }); + auto iter = std::find_if(leAudioDevices_.begin(), leAudioDevices_.end(), [](auto& d) { + if (d.expired()) { + return false; + } else { + return ((d.lock()).get())->HaveAnyStreamingAses(); + } + }); return iter != leAudioDevices_.end(); } bool LeAudioDeviceGroup::HaveAnyActiveDeviceInUnconfiguredState() const { - auto iter = - std::find_if(leAudioDevices_.begin(), leAudioDevices_.end(), [](auto& d) { - if (d.expired()) - return false; - else - return (((d.lock()).get())->HaveAnyUnconfiguredAses()); - }); + auto iter = std::find_if(leAudioDevices_.begin(), leAudioDevices_.end(), [](auto& d) { + if (d.expired()) { + return false; + } else { + return ((d.lock()).get())->HaveAnyUnconfiguredAses(); + } + }); return iter != leAudioDevices_.end(); } -bool LeAudioDeviceGroup::HaveAllActiveDevicesAsesTheSameState( - AseState state) const { - auto iter = std::find_if( - leAudioDevices_.begin(), leAudioDevices_.end(), [&state](auto& d) { - if (d.expired()) - return false; - else - return !(((d.lock()).get())->HaveAllActiveAsesSameState(state)); - }); +bool LeAudioDeviceGroup::HaveAllActiveDevicesAsesTheSameState(AseState state) const { + auto iter = std::find_if(leAudioDevices_.begin(), leAudioDevices_.end(), [&state](auto& d) { + if (d.expired()) { + return false; + } else { + return !(((d.lock()).get())->HaveAllActiveAsesSameState(state)); + } + }); return iter == leAudioDevices_.end(); } LeAudioDevice* LeAudioDeviceGroup::GetFirstActiveDevice(void) const { - auto iter = - std::find_if(leAudioDevices_.begin(), leAudioDevices_.end(), [](auto& d) { - if (d.expired()) - return false; - else - return ((d.lock()).get())->HaveActiveAse(); - }); + auto iter = std::find_if(leAudioDevices_.begin(), leAudioDevices_.end(), [](auto& d) { + if (d.expired()) { + return false; + } else { + return ((d.lock()).get())->HaveActiveAse(); + } + }); - if (iter == leAudioDevices_.end() || iter->expired()) return nullptr; + if (iter == leAudioDevices_.end() || iter->expired()) { + return nullptr; + } return (iter->lock()).get(); } -LeAudioDevice* LeAudioDeviceGroup::GetNextActiveDevice( - LeAudioDevice* leAudioDevice) const { - auto iter = std::find_if(leAudioDevices_.begin(), leAudioDevices_.end(), - [&leAudioDevice](auto& d) { - if (d.expired()) - return false; - else - return (d.lock()).get() == leAudioDevice; - }); - - if (iter == leAudioDevices_.end() || - std::distance(iter, leAudioDevices_.end()) < 1) +LeAudioDevice* LeAudioDeviceGroup::GetNextActiveDevice(LeAudioDevice* leAudioDevice) const { + auto iter = + std::find_if(leAudioDevices_.begin(), leAudioDevices_.end(), [&leAudioDevice](auto& d) { + if (d.expired()) { + return false; + } else { + return (d.lock()).get() == leAudioDevice; + } + }); + + if (iter == leAudioDevices_.end() || std::distance(iter, leAudioDevices_.end()) < 1) { return nullptr; + } iter = std::find_if(std::next(iter, 1), leAudioDevices_.end(), [](auto& d) { - if (d.expired()) + if (d.expired()) { return false; - else + } else { return ((d.lock()).get())->HaveActiveAse(); + } }); return (iter == leAudioDevices_.end()) ? nullptr : (iter->lock()).get(); } LeAudioDevice* LeAudioDeviceGroup::GetFirstActiveDeviceByCisAndDataPathState( - CisState cis_state, DataPathState data_path_state) const { - auto iter = - std::find_if(leAudioDevices_.begin(), leAudioDevices_.end(), - [&data_path_state, &cis_state](auto& d) { - if (d.expired()) { - return false; - } + CisState cis_state, DataPathState data_path_state) const { + auto iter = std::find_if( + leAudioDevices_.begin(), leAudioDevices_.end(), [&data_path_state, &cis_state](auto& d) { + if (d.expired()) { + return false; + } - return (((d.lock()).get()) - ->GetFirstActiveAseByCisAndDataPathState( - cis_state, data_path_state) != nullptr); - }); + return ((d.lock()).get()) + ->GetFirstActiveAseByCisAndDataPathState(cis_state, data_path_state) != + nullptr; + }); if (iter == leAudioDevices_.end()) { return nullptr; @@ -449,31 +455,30 @@ LeAudioDevice* LeAudioDeviceGroup::GetFirstActiveDeviceByCisAndDataPathState( } LeAudioDevice* LeAudioDeviceGroup::GetNextActiveDeviceByCisAndDataPathState( - LeAudioDevice* leAudioDevice, CisState cis_state, - DataPathState data_path_state) const { - auto iter = std::find_if(leAudioDevices_.begin(), leAudioDevices_.end(), - [&leAudioDevice](auto& d) { - if (d.expired()) { - return false; - } + LeAudioDevice* leAudioDevice, CisState cis_state, DataPathState data_path_state) const { + auto iter = + std::find_if(leAudioDevices_.begin(), leAudioDevices_.end(), [&leAudioDevice](auto& d) { + if (d.expired()) { + return false; + } - return d.lock().get() == leAudioDevice; - }); + return d.lock().get() == leAudioDevice; + }); if (std::distance(iter, leAudioDevices_.end()) < 1) { return nullptr; } - iter = std::find_if(std::next(iter, 1), leAudioDevices_.end(), - [&cis_state, &data_path_state](auto& d) { - if (d.expired()) { - return false; - } + iter = std::find_if( + std::next(iter, 1), leAudioDevices_.end(), [&cis_state, &data_path_state](auto& d) { + if (d.expired()) { + return false; + } - return (((d.lock()).get()) - ->GetFirstActiveAseByCisAndDataPathState( - cis_state, data_path_state) != nullptr); - }); + return ((d.lock()).get()) + ->GetFirstActiveAseByCisAndDataPathState(cis_state, data_path_state) != + nullptr; + }); if (iter == leAudioDevices_.end()) { return nullptr; @@ -483,11 +488,12 @@ LeAudioDevice* LeAudioDeviceGroup::GetNextActiveDeviceByCisAndDataPathState( } uint32_t LeAudioDeviceGroup::GetSduInterval(uint8_t direction) const { - for (LeAudioDevice* leAudioDevice = GetFirstActiveDevice(); - leAudioDevice != nullptr; + for (LeAudioDevice* leAudioDevice = GetFirstActiveDevice(); leAudioDevice != nullptr; leAudioDevice = GetNextActiveDevice(leAudioDevice)) { struct ase* ase = leAudioDevice->GetFirstActiveAseByDirection(direction); - if (!ase) continue; + if (!ase) { + continue; + } return ase->qos_config.sdu_interval; } @@ -504,7 +510,9 @@ uint8_t LeAudioDeviceGroup::GetSCA(void) const { /* If we could not read SCA from the peer device or sca is 0, * then there is no reason to continue. */ - if ((dev_sca == 0xFF) || (dev_sca == 0)) return 0; + if ((dev_sca == 0xFF) || (dev_sca == 0)) { + return 0; + } /* The Slaves_Clock_Accuracy parameter shall be the worst-case sleep clock *accuracy of all the slaves that will participate in the CIG. @@ -527,17 +535,18 @@ uint8_t LeAudioDeviceGroup::GetPacking(void) const { uint8_t LeAudioDeviceGroup::GetFraming(void) const { LeAudioDevice* leAudioDevice = GetFirstActiveDevice(); - log::assert_that(leAudioDevice, - "Shouldn't be called without an active device."); + log::assert_that(leAudioDevice, "Shouldn't be called without an active device."); do { struct ase* ase = leAudioDevice->GetFirstActiveAse(); - if (!ase) continue; + if (!ase) { + continue; + } do { - if (ase->qos_preferences.supported_framing == - types::kFramingUnframedPduUnsupported) + if (ase->qos_preferences.supported_framing == types::kFramingUnframedPduUnsupported) { return bluetooth::hci::kIsoCigFramingFramed; + } } while ((ase = leAudioDevice->GetNextActiveAse(ase))); } while ((leAudioDevice = GetNextActiveDevice(leAudioDevice))); @@ -545,23 +554,21 @@ uint8_t LeAudioDeviceGroup::GetFraming(void) const { } /* TODO: Preferred parameter may be other than minimum */ -static uint16_t find_max_transport_latency(const LeAudioDeviceGroup* group, - uint8_t direction) { +static uint16_t find_max_transport_latency(const LeAudioDeviceGroup* group, uint8_t direction) { uint16_t max_transport_latency = 0; - for (LeAudioDevice* leAudioDevice = group->GetFirstActiveDevice(); - leAudioDevice != nullptr; + for (LeAudioDevice* leAudioDevice = group->GetFirstActiveDevice(); leAudioDevice != nullptr; leAudioDevice = group->GetNextActiveDevice(leAudioDevice)) { - for (ase* ase = leAudioDevice->GetFirstActiveAseByDirection(direction); - ase != nullptr; + for (ase* ase = leAudioDevice->GetFirstActiveAseByDirection(direction); ase != nullptr; ase = leAudioDevice->GetNextActiveAseWithSameDirection(ase)) { - if (!ase) break; + if (!ase) { + break; + } if (max_transport_latency == 0) { // first assignment max_transport_latency = ase->qos_config.max_transport_latency; - } else if (ase->qos_config.max_transport_latency < - max_transport_latency) { + } else if (ase->qos_config.max_transport_latency < max_transport_latency) { if (ase->qos_config.max_transport_latency != 0) { max_transport_latency = ase->qos_config.max_transport_latency; } else { @@ -599,8 +606,7 @@ uint32_t LeAudioDeviceGroup::GetTransportLatencyUs(uint8_t direction) const { } } -void LeAudioDeviceGroup::SetTransportLatency( - uint8_t direction, uint32_t new_transport_latency_us) { +void LeAudioDeviceGroup::SetTransportLatency(uint8_t direction, uint32_t new_transport_latency_us) { uint32_t* transport_latency_us; if (direction == types::kLeAudioDirectionSink) { @@ -612,35 +618,31 @@ void LeAudioDeviceGroup::SetTransportLatency( return; } - if (*transport_latency_us == new_transport_latency_us) return; + if (*transport_latency_us == new_transport_latency_us) { + return; + } - if ((*transport_latency_us != 0) && - (*transport_latency_us != new_transport_latency_us)) { - log::warn( - "Different transport latency for group: old: {} [us], new: {} [us]", - static_cast(*transport_latency_us), - static_cast(new_transport_latency_us)); + if ((*transport_latency_us != 0) && (*transport_latency_us != new_transport_latency_us)) { + log::warn("Different transport latency for group: old: {} [us], new: {} [us]", + static_cast(*transport_latency_us), static_cast(new_transport_latency_us)); return; } - log::info("updated group {} transport latency: {} [us]", - static_cast(group_id_), + log::info("updated group {} transport latency: {} [us]", static_cast(group_id_), static_cast(new_transport_latency_us)); *transport_latency_us = new_transport_latency_us; } uint8_t LeAudioDeviceGroup::GetRtn(uint8_t direction, uint8_t cis_id) const { LeAudioDevice* leAudioDevice = GetFirstActiveDevice(); - log::assert_that(leAudioDevice, - "Shouldn't be called without an active device."); + log::assert_that(leAudioDevice, "Shouldn't be called without an active device."); do { auto ases_pair = leAudioDevice->GetAsesByCisId(cis_id); if (ases_pair.sink && direction == types::kLeAudioDirectionSink) { return ases_pair.sink->qos_config.retrans_nb; - } else if (ases_pair.source && - direction == types::kLeAudioDirectionSource) { + } else if (ases_pair.source && direction == types::kLeAudioDirectionSource) { return ases_pair.source->qos_config.retrans_nb; } } while ((leAudioDevice = GetNextActiveDevice(leAudioDevice))); @@ -648,19 +650,16 @@ uint8_t LeAudioDeviceGroup::GetRtn(uint8_t direction, uint8_t cis_id) const { return 0; } -uint16_t LeAudioDeviceGroup::GetMaxSduSize(uint8_t direction, - uint8_t cis_id) const { +uint16_t LeAudioDeviceGroup::GetMaxSduSize(uint8_t direction, uint8_t cis_id) const { LeAudioDevice* leAudioDevice = GetFirstActiveDevice(); - log::assert_that(leAudioDevice, - "Shouldn't be called without an active device."); + log::assert_that(leAudioDevice, "Shouldn't be called without an active device."); do { auto ases_pair = leAudioDevice->GetAsesByCisId(cis_id); if (ases_pair.sink && direction == types::kLeAudioDirectionSink) { return ases_pair.sink->qos_config.max_sdu_size; - } else if (ases_pair.source && - direction == types::kLeAudioDirectionSource) { + } else if (ases_pair.source && direction == types::kLeAudioDirectionSource) { return ases_pair.source->qos_config.max_sdu_size; } } while ((leAudioDevice = GetNextActiveDevice(leAudioDevice))); @@ -670,14 +669,14 @@ uint16_t LeAudioDeviceGroup::GetMaxSduSize(uint8_t direction, uint8_t LeAudioDeviceGroup::GetPhyBitmask(uint8_t direction) const { LeAudioDevice* leAudioDevice = GetFirstActiveDevice(); - log::assert_that(leAudioDevice, - "Shouldn't be called without an active device."); + log::assert_that(leAudioDevice, "Shouldn't be called without an active device."); // local supported PHY's uint8_t phy_bitfield = bluetooth::hci::kIsoCigPhy1M; auto controller = bluetooth::shim::GetController(); - if (controller && controller->SupportsBle2mPhy()) + if (controller && controller->SupportsBle2mPhy()) { phy_bitfield |= bluetooth::hci::kIsoCigPhy2M; + } if (!leAudioDevice) { log::error("No active leaudio device for direction?: {}", direction); @@ -686,7 +685,9 @@ uint8_t LeAudioDeviceGroup::GetPhyBitmask(uint8_t direction) const { do { struct ase* ase = leAudioDevice->GetFirstActiveAseByDirection(direction); - if (!ase) return phy_bitfield; + if (!ase) { + return phy_bitfield; + } do { if (direction == ase->direction) { @@ -696,14 +697,13 @@ uint8_t LeAudioDeviceGroup::GetPhyBitmask(uint8_t direction) const { if (ase->qos_preferences.preferred_phy && (phy_bitfield & ase->qos_preferences.preferred_phy)) { phy_bitfield &= ase->qos_preferences.preferred_phy; - log::debug("Using ASE preferred phy 0x{:02x}", - static_cast(phy_bitfield)); + log::debug("Using ASE preferred phy 0x{:02x}", static_cast(phy_bitfield)); } else { log::warn( - "ASE preferred 0x{:02x} has nothing common with phy_bitfield " - "0x{:02x}", - static_cast(ase->qos_preferences.preferred_phy), - static_cast(phy_bitfield)); + "ASE preferred 0x{:02x} has nothing common with phy_bitfield " + "0x{:02x}", + static_cast(ase->qos_preferences.preferred_phy), + static_cast(phy_bitfield)); } } } while ((ase = leAudioDevice->GetNextActiveAseWithSameDirection(ase))); @@ -716,50 +716,55 @@ uint8_t LeAudioDeviceGroup::GetTargetPhy(uint8_t direction) const { uint8_t phy_bitfield = GetPhyBitmask(direction); // prefer to use 2M if supported - if (phy_bitfield & bluetooth::hci::kIsoCigPhy2M) + if (phy_bitfield & bluetooth::hci::kIsoCigPhy2M) { return types::kTargetPhy2M; - else if (phy_bitfield & bluetooth::hci::kIsoCigPhy1M) + } else if (phy_bitfield & bluetooth::hci::kIsoCigPhy1M) { return types::kTargetPhy1M; - else + } else { return 0; + } } -bool LeAudioDeviceGroup::GetPresentationDelay(uint32_t* delay, - uint8_t direction) const { +bool LeAudioDeviceGroup::GetPresentationDelay(uint32_t* delay, uint8_t direction) const { uint32_t delay_min = 0; uint32_t delay_max = UINT32_MAX; uint32_t preferred_delay_min = delay_min; uint32_t preferred_delay_max = delay_max; LeAudioDevice* leAudioDevice = GetFirstActiveDevice(); - log::assert_that(leAudioDevice, - "Shouldn't be called without an active device."); + log::assert_that(leAudioDevice, "Shouldn't be called without an active device."); do { struct ase* ase = leAudioDevice->GetFirstActiveAseByDirection(direction); - if (!ase) continue; // device has no active ASEs in this direction + if (!ase) { + continue; // device has no active ASEs in this direction + } do { /* No common range check */ if (ase->qos_preferences.pres_delay_min > delay_max || - ase->qos_preferences.pres_delay_max < delay_min) + ase->qos_preferences.pres_delay_max < delay_min) { return false; + } - if (ase->qos_preferences.pres_delay_min > delay_min) + if (ase->qos_preferences.pres_delay_min > delay_min) { delay_min = ase->qos_preferences.pres_delay_min; - if (ase->qos_preferences.pres_delay_max < delay_max) + } + if (ase->qos_preferences.pres_delay_max < delay_max) { delay_max = ase->qos_preferences.pres_delay_max; - if (ase->qos_preferences.preferred_pres_delay_min > preferred_delay_min) + } + if (ase->qos_preferences.preferred_pres_delay_min > preferred_delay_min) { preferred_delay_min = ase->qos_preferences.preferred_pres_delay_min; + } if (ase->qos_preferences.preferred_pres_delay_max < preferred_delay_max && - ase->qos_preferences.preferred_pres_delay_max != - types::kPresDelayNoPreference) + ase->qos_preferences.preferred_pres_delay_max != types::kPresDelayNoPreference) { preferred_delay_max = ase->qos_preferences.preferred_pres_delay_max; + } } while ((ase = leAudioDevice->GetNextActiveAseWithSameDirection(ase))); } while ((leAudioDevice = GetNextActiveDevice(leAudioDevice))); - if (preferred_delay_min <= preferred_delay_max && - preferred_delay_min > delay_min && preferred_delay_min < delay_max) { + if (preferred_delay_min <= preferred_delay_max && preferred_delay_min > delay_min && + preferred_delay_min < delay_max) { *delay = preferred_delay_min; } else { *delay = delay_min; @@ -772,8 +777,7 @@ uint16_t LeAudioDeviceGroup::GetRemoteDelay(uint8_t direction) const { uint16_t remote_delay_ms = 0; uint32_t presentation_delay; - if (!GetFirstActiveDevice() || - !GetPresentationDelay(&presentation_delay, direction)) { + if (!GetFirstActiveDevice() || !GetPresentationDelay(&presentation_delay, direction)) { /* This should never happens at stream request time but to be safe return * some sample value to not break streaming */ @@ -796,10 +800,9 @@ bool LeAudioDeviceGroup::UpdateAudioContextAvailability(void) { } CodecManager::UnicastConfigurationRequirements -LeAudioDeviceGroup::GetAudioSetConfigurationRequirements( - types::LeAudioContextType ctx_type) const { +LeAudioDeviceGroup::GetAudioSetConfigurationRequirements(types::LeAudioContextType ctx_type) const { auto new_req = CodecManager::UnicastConfigurationRequirements{ - .audio_context_type = ctx_type, + .audio_context_type = ctx_type, }; // Define a requirement for each location. Knowing codec specific @@ -809,8 +812,7 @@ LeAudioDeviceGroup::GetAudioSetConfigurationRequirements( auto device = weak_dev_ptr.lock(); BidirectionalPair has_location = {false, false}; - for (auto direction : - {types::kLeAudioDirectionSink, types::kLeAudioDirectionSource}) { + for (auto direction : {types::kLeAudioDirectionSink, types::kLeAudioDirectionSource}) { // Do not put any requirements on the Source if Sink only scenario is used // Note: With the RINGTONE we should already prepare for a call. if ((direction == types::kLeAudioDirectionSource) && @@ -822,43 +824,36 @@ LeAudioDeviceGroup::GetAudioSetConfigurationRequirements( } if (device->GetAseCount(direction) == 0) { - log::warn("Device {} has no ASEs for direction: {}", device->address_, - (int)direction); + log::warn("Device {} has no ASEs for direction: {}", device->address_, (int)direction); continue; } auto& dev_locations = (direction == types::kLeAudioDirectionSink) - ? device->snk_audio_locations_ - : device->src_audio_locations_; + ? device->snk_audio_locations_ + : device->src_audio_locations_; if (dev_locations.none()) { - log::warn("Device {} has no locations for direction: {}", - device->address_, (int)direction); + log::warn("Device {} has no locations for direction: {}", device->address_, (int)direction); continue; } has_location.get(direction) = true; auto& direction_req = (direction == types::kLeAudioDirectionSink) - ? new_req.sink_requirements - : new_req.source_requirements; + ? new_req.sink_requirements + : new_req.source_requirements; if (!direction_req) { - direction_req = - std::vector(); + direction_req = std::vector< + CodecManager::UnicastConfigurationRequirements::DeviceDirectionRequirements>(); } // Pass the audio channel allocation requirement according to TMAP - auto locations = dev_locations.to_ulong() & - (codec_spec_conf::kLeAudioLocationFrontLeft | - codec_spec_conf::kLeAudioLocationFrontRight); - CodecManager::UnicastConfigurationRequirements:: - DeviceDirectionRequirements config_req; - config_req.params.Add( - codec_spec_conf::kLeAudioLtvTypeAudioChannelAllocation, - (uint32_t)locations); - config_req.target_latency = - utils::GetTargetLatencyForAudioContext(ctx_type); - log::warn("Device {} pushes requirement, location: {}, direction: {}", - device->address_, (int)locations, (int)direction); + auto locations = dev_locations.to_ulong() & (codec_spec_conf::kLeAudioLocationFrontLeft | + codec_spec_conf::kLeAudioLocationFrontRight); + CodecManager::UnicastConfigurationRequirements::DeviceDirectionRequirements config_req; + config_req.params.Add(codec_spec_conf::kLeAudioLtvTypeAudioChannelAllocation, + (uint32_t)locations); + config_req.target_latency = utils::GetTargetLatencyForAudioContext(ctx_type); + log::warn("Device {} pushes requirement, location: {}, direction: {}", device->address_, + (int)locations, (int)direction); direction_req->push_back(std::move(config_req)); } @@ -890,18 +885,15 @@ LeAudioDeviceGroup::GetAudioSetConfigurationRequirements( return new_req; } -bool LeAudioDeviceGroup::UpdateAudioSetConfigurationCache( - LeAudioContextType ctx_type) const { +bool LeAudioDeviceGroup::UpdateAudioSetConfigurationCache(LeAudioContextType ctx_type) const { auto requirements = GetAudioSetConfigurationRequirements(ctx_type); auto new_conf = CodecManager::GetInstance()->GetCodecConfig( - requirements, - std::bind(&LeAudioDeviceGroup::FindFirstSupportedConfiguration, this, - std::placeholders::_1, std::placeholders::_2)); + requirements, std::bind(&LeAudioDeviceGroup::FindFirstSupportedConfiguration, this, + std::placeholders::_1, std::placeholders::_2)); auto update_config = true; if (context_to_configuration_cache_map.count(ctx_type) != 0) { - auto& [is_valid, existing_conf] = - context_to_configuration_cache_map.at(ctx_type); + auto& [is_valid, existing_conf] = context_to_configuration_cache_map.at(ctx_type); update_config = (new_conf.get() != existing_conf.get()); /* Just mark it as still valid */ if (!update_config && !is_valid) { @@ -914,9 +906,10 @@ bool LeAudioDeviceGroup::UpdateAudioSetConfigurationCache( log::info("config: {} -> {}", ToHexString(ctx_type), (new_conf ? new_conf->name.c_str() : "(none)")); context_to_configuration_cache_map.erase(ctx_type); - if (new_conf) + if (new_conf) { context_to_configuration_cache_map.insert( - std::make_pair(ctx_type, std::make_pair(true, std::move(new_conf)))); + std::make_pair(ctx_type, std::make_pair(true, std::move(new_conf)))); + } } return update_config; } @@ -926,40 +919,36 @@ void LeAudioDeviceGroup::InvalidateCachedConfigurations(void) { context_to_configuration_cache_map.clear(); } -types::BidirectionalPair -LeAudioDeviceGroup::GetLatestAvailableContexts() const { +types::BidirectionalPair LeAudioDeviceGroup::GetLatestAvailableContexts() const { types::BidirectionalPair contexts; for (const auto& device : leAudioDevices_) { auto shared_ptr = device.lock(); - if (shared_ptr && - shared_ptr->GetConnectionState() == DeviceConnectState::CONNECTED) { - contexts.sink |= - shared_ptr->GetAvailableContexts(types::kLeAudioDirectionSink); - contexts.source |= - shared_ptr->GetAvailableContexts(types::kLeAudioDirectionSource); + if (shared_ptr && shared_ptr->GetConnectionState() == DeviceConnectState::CONNECTED) { + contexts.sink |= shared_ptr->GetAvailableContexts(types::kLeAudioDirectionSink); + contexts.source |= shared_ptr->GetAvailableContexts(types::kLeAudioDirectionSource); } } return contexts; } bool LeAudioDeviceGroup::ReloadAudioLocations(void) { - AudioLocations updated_snk_audio_locations_ = - codec_spec_conf::kLeAudioLocationNotAllowed; - AudioLocations updated_src_audio_locations_ = - codec_spec_conf::kLeAudioLocationNotAllowed; + AudioLocations updated_snk_audio_locations_ = codec_spec_conf::kLeAudioLocationNotAllowed; + AudioLocations updated_src_audio_locations_ = codec_spec_conf::kLeAudioLocationNotAllowed; for (const auto& device : leAudioDevices_) { - if (device.expired() || (device.lock().get()->GetConnectionState() != - DeviceConnectState::CONNECTED)) + if (device.expired() || + (device.lock().get()->GetConnectionState() != DeviceConnectState::CONNECTED)) { continue; + } updated_snk_audio_locations_ |= device.lock().get()->snk_audio_locations_; updated_src_audio_locations_ |= device.lock().get()->src_audio_locations_; } /* Nothing has changed */ if ((updated_snk_audio_locations_ == snk_audio_locations_) && - (updated_src_audio_locations_ == src_audio_locations_)) + (updated_src_audio_locations_ == src_audio_locations_)) { return false; + } snk_audio_locations_ = updated_snk_audio_locations_; src_audio_locations_ = updated_src_audio_locations_; @@ -971,14 +960,17 @@ bool LeAudioDeviceGroup::ReloadAudioDirections(void) { uint8_t updated_audio_directions = 0x00; for (const auto& device : leAudioDevices_) { - if (device.expired() || (device.lock().get()->GetConnectionState() != - DeviceConnectState::CONNECTED)) + if (device.expired() || + (device.lock().get()->GetConnectionState() != DeviceConnectState::CONNECTED)) { continue; + } updated_audio_directions |= device.lock().get()->audio_directions_; } /* Nothing has changed */ - if (updated_audio_directions == audio_directions_) return false; + if (updated_audio_directions == audio_directions_) { + return false; + } audio_directions_ = updated_audio_directions; @@ -1002,12 +994,13 @@ bool LeAudioDeviceGroup::IsGroupStreamReady(void) const { /* All connected devices must be ready */ for (auto& weak : leAudioDevices_) { auto dev = weak.lock(); - if (!dev) return false; + if (!dev) { + return false; + } /* We are interested here in devices which are connected on profile level * and devices which are configured (meaning, have actived ASE(s))*/ - if (dev->GetConnectionState() == DeviceConnectState::CONNECTED && - dev->HaveActiveAse()) { + if (dev->GetConnectionState() == DeviceConnectState::CONNECTED && dev->HaveActiveAse()) { if (!dev->IsReadyToStream()) { return false; } @@ -1019,16 +1012,19 @@ bool LeAudioDeviceGroup::IsGroupStreamReady(void) const { bool LeAudioDeviceGroup::HaveAllCisesDisconnected(void) const { for (auto const dev : leAudioDevices_) { - if (dev.expired()) continue; - if (dev.lock().get()->HaveAnyCisConnected()) return false; + if (dev.expired()) { + continue; + } + if (dev.lock().get()->HaveAnyCisConnected()) { + return false; + } } return true; } -uint8_t LeAudioDeviceGroup::CigConfiguration::GetFirstFreeCisId( - CisType cis_type) const { - log::info("Group: {}, group_id: {} cis_type: {}", fmt::ptr(group_), - group_->group_id_, static_cast(cis_type)); +uint8_t LeAudioDeviceGroup::CigConfiguration::GetFirstFreeCisId(CisType cis_type) const { + log::info("Group: {}, group_id: {} cis_type: {}", fmt::ptr(group_), group_->group_id_, + static_cast(cis_type)); for (size_t id = 0; id < cises.size(); id++) { if (cises[id].addr.IsEmpty() && cises[id].type == cis_type) { return id; @@ -1037,8 +1033,7 @@ uint8_t LeAudioDeviceGroup::CigConfiguration::GetFirstFreeCisId( return kInvalidCisId; } -types::LeAudioConfigurationStrategy LeAudioDeviceGroup::GetGroupSinkStrategy() - const { +types::LeAudioConfigurationStrategy LeAudioDeviceGroup::GetGroupSinkStrategy() const { /* Update the strategy if not set yet or was invalidated */ if (!strategy_) { /* Choose the group configuration strategy based on PAC records */ @@ -1052,10 +1047,8 @@ types::LeAudioConfigurationStrategy LeAudioDeviceGroup::GetGroupSinkStrategy() } log::debug("audio location 0x{:04x}", snk_audio_locations_.to_ulong()); - if (!(snk_audio_locations_.to_ulong() & - codec_spec_conf::kLeAudioLocationAnyLeft) || - !(snk_audio_locations_.to_ulong() & - codec_spec_conf::kLeAudioLocationAnyRight)) { + if (!(snk_audio_locations_.to_ulong() & codec_spec_conf::kLeAudioLocationAnyLeft) || + !(snk_audio_locations_.to_ulong() & codec_spec_conf::kLeAudioLocationAnyRight)) { return types::LeAudioConfigurationStrategy::MONO_ONE_CIS_PER_DEVICE; } @@ -1063,9 +1056,9 @@ types::LeAudioConfigurationStrategy LeAudioDeviceGroup::GetGroupSinkStrategy() /* Note: Currently, the audio channel counts LTV is only mandatory for * LC3. */ auto channel_count_bitmap = - device->GetSupportedAudioChannelCounts(types::kLeAudioDirectionSink); - log::debug("Supported channel counts for group {} (device {}) is {}", - group_id_, device->address_, channel_count_bitmap); + device->GetSupportedAudioChannelCounts(types::kLeAudioDirectionSink); + log::debug("Supported channel counts for group {} (device {}) is {}", group_id_, + device->address_, channel_count_bitmap); if (channel_count_bitmap == 1) { return types::LeAudioConfigurationStrategy::STEREO_TWO_CISES_PER_DEVICE; } @@ -1073,21 +1066,18 @@ types::LeAudioConfigurationStrategy LeAudioDeviceGroup::GetGroupSinkStrategy() return types::LeAudioConfigurationStrategy::STEREO_ONE_CIS_PER_DEVICE; }(); - log::info( - "Group strategy set to: {}", - [](types::LeAudioConfigurationStrategy strategy) { - switch (strategy) { - case types::LeAudioConfigurationStrategy::MONO_ONE_CIS_PER_DEVICE: - return "MONO_ONE_CIS_PER_DEVICE"; - case types::LeAudioConfigurationStrategy:: - STEREO_TWO_CISES_PER_DEVICE: - return "STEREO_TWO_CISES_PER_DEVICE"; - case types::LeAudioConfigurationStrategy::STEREO_ONE_CIS_PER_DEVICE: - return "STEREO_ONE_CIS_PER_DEVICE"; - default: - return "RFU"; - } - }(*strategy_)); + log::info("Group strategy set to: {}", [](types::LeAudioConfigurationStrategy strategy) { + switch (strategy) { + case types::LeAudioConfigurationStrategy::MONO_ONE_CIS_PER_DEVICE: + return "MONO_ONE_CIS_PER_DEVICE"; + case types::LeAudioConfigurationStrategy::STEREO_TWO_CISES_PER_DEVICE: + return "STEREO_TWO_CISES_PER_DEVICE"; + case types::LeAudioConfigurationStrategy::STEREO_ONE_CIS_PER_DEVICE: + return "STEREO_ONE_CIS_PER_DEVICE"; + default: + return "RFU"; + } + }(*strategy_)); } return *strategy_; } @@ -1101,10 +1091,9 @@ int LeAudioDeviceGroup::GetAseCount(uint8_t direction) const { return result; } -void LeAudioDeviceGroup::CigConfiguration::GenerateCisIds( - LeAudioContextType context_type) { - log::info("Group {}, group_id: {}, context_type: {}", fmt::ptr(group_), - group_->group_id_, bluetooth::common::ToString(context_type)); +void LeAudioDeviceGroup::CigConfiguration::GenerateCisIds(LeAudioContextType context_type) { + log::info("Group {}, group_id: {}, context_type: {}", fmt::ptr(group_), group_->group_id_, + bluetooth::common::ToString(context_type)); if (cises.size() > 0) { log::info("CIS IDs already generated"); @@ -1116,19 +1105,19 @@ void LeAudioDeviceGroup::CigConfiguration::GenerateCisIds( uint8_t cis_count_unidir_source = 0; int group_size = group_->DesiredSize(); - set_configurations::get_cis_count( - context_type, group_size, group_->GetGroupSinkStrategy(), - group_->GetAseCount(types::kLeAudioDirectionSink), - group_->GetAseCount(types::kLeAudioDirectionSource), cis_count_bidir, - cis_count_unidir_sink, cis_count_unidir_source); + set_configurations::get_cis_count(context_type, group_size, group_->GetGroupSinkStrategy(), + group_->GetAseCount(types::kLeAudioDirectionSink), + group_->GetAseCount(types::kLeAudioDirectionSource), + cis_count_bidir, cis_count_unidir_sink, + cis_count_unidir_source); uint8_t idx = 0; while (cis_count_bidir > 0) { struct bluetooth::le_audio::types::cis cis_entry = { - .id = idx, - .type = CisType::CIS_TYPE_BIDIRECTIONAL, - .conn_handle = 0, - .addr = RawAddress::kEmpty, + .id = idx, + .type = CisType::CIS_TYPE_BIDIRECTIONAL, + .conn_handle = 0, + .addr = RawAddress::kEmpty, }; cises.push_back(cis_entry); cis_count_bidir--; @@ -1137,10 +1126,10 @@ void LeAudioDeviceGroup::CigConfiguration::GenerateCisIds( while (cis_count_unidir_sink > 0) { struct bluetooth::le_audio::types::cis cis_entry = { - .id = idx, - .type = CisType::CIS_TYPE_UNIDIRECTIONAL_SINK, - .conn_handle = 0, - .addr = RawAddress::kEmpty, + .id = idx, + .type = CisType::CIS_TYPE_UNIDIRECTIONAL_SINK, + .conn_handle = 0, + .addr = RawAddress::kEmpty, }; cises.push_back(cis_entry); cis_count_unidir_sink--; @@ -1149,10 +1138,10 @@ void LeAudioDeviceGroup::CigConfiguration::GenerateCisIds( while (cis_count_unidir_source > 0) { struct bluetooth::le_audio::types::cis cis_entry = { - .id = idx, - .type = CisType::CIS_TYPE_UNIDIRECTIONAL_SOURCE, - .conn_handle = 0, - .addr = RawAddress::kEmpty, + .id = idx, + .type = CisType::CIS_TYPE_UNIDIRECTIONAL_SOURCE, + .conn_handle = 0, + .addr = RawAddress::kEmpty, }; cises.push_back(cis_entry); cis_count_unidir_source--; @@ -1160,15 +1149,13 @@ void LeAudioDeviceGroup::CigConfiguration::GenerateCisIds( } } -bool LeAudioDeviceGroup::CigConfiguration::AssignCisIds( - LeAudioDevice* leAudioDevice) { +bool LeAudioDeviceGroup::CigConfiguration::AssignCisIds(LeAudioDevice* leAudioDevice) { log::assert_that(leAudioDevice, "invalid device"); log::info("device: {}", leAudioDevice->address_); struct ase* ase = leAudioDevice->GetFirstActiveAse(); if (!ase) { - log::error("Device {} shouldn't be called without an active ASE", - leAudioDevice->address_); + log::error("Device {} shouldn't be called without an active ASE", leAudioDevice->address_); return false; } @@ -1176,8 +1163,8 @@ bool LeAudioDeviceGroup::CigConfiguration::AssignCisIds( uint8_t cis_id = kInvalidCisId; /* CIS ID already set */ if (ase->cis_id != kInvalidCisId) { - log::info("ASE ID: {}, is already assigned CIS ID: {}, type {}", ase->id, - ase->cis_id, cises[ase->cis_id].type); + log::info("ASE ID: {}, is already assigned CIS ID: {}, type {}", ase->id, ase->cis_id, + cises[ase->cis_id].type); if (!cises[ase->cis_id].addr.IsEmpty()) { log::info("Bi-Directional CIS already assigned"); continue; @@ -1187,14 +1174,12 @@ bool LeAudioDeviceGroup::CigConfiguration::AssignCisIds( } /* First check if we have bidirectional ASEs. If so, assign same CIS ID.*/ - struct ase* matching_bidir_ase = - leAudioDevice->GetNextActiveAseWithDifferentDirection(ase); + struct ase* matching_bidir_ase = leAudioDevice->GetNextActiveAseWithDifferentDirection(ase); for (; matching_bidir_ase != nullptr; - matching_bidir_ase = leAudioDevice->GetNextActiveAseWithSameDirection( - matching_bidir_ase)) { - if ((matching_bidir_ase->cis_id != kInvalidCisId) && - (matching_bidir_ase->cis_id != cis_id)) { + matching_bidir_ase = + leAudioDevice->GetNextActiveAseWithSameDirection(matching_bidir_ase)) { + if ((matching_bidir_ase->cis_id != kInvalidCisId) && (matching_bidir_ase->cis_id != cis_id)) { log::info("Bi-Directional CIS is already used. ASE Id: {} cis_id={}", matching_bidir_ase->id, matching_bidir_ase->cis_id); continue; @@ -1212,16 +1197,15 @@ bool LeAudioDeviceGroup::CigConfiguration::AssignCisIds( matching_bidir_ase->cis_id = cis_id; cises[cis_id].addr = leAudioDevice->address_; - log::info( - "ASE ID: {} and ASE ID: {}, assigned Bi-Directional CIS ID: {}", - ase->id, matching_bidir_ase->id, ase->cis_id); + log::info("ASE ID: {} and ASE ID: {}, assigned Bi-Directional CIS ID: {}", ase->id, + matching_bidir_ase->id, ase->cis_id); continue; } log::warn( - "ASE ID: {}, unable to get free Bi-Directional CIS ID but maybe " - "thats fine. Try using unidirectional.", - ase->id); + "ASE ID: {}, unable to get free Bi-Directional CIS ID but maybe " + "thats fine. Try using unidirectional.", + ase->id); } if (ase->direction == types::kLeAudioDirectionSink) { @@ -1231,8 +1215,8 @@ bool LeAudioDeviceGroup::CigConfiguration::AssignCisIds( if (cis_id == kInvalidCisId) { log::warn( - "Unable to get free Uni-Directional Sink CIS ID - maybe there is " - "bi-directional available"); + "Unable to get free Uni-Directional Sink CIS ID - maybe there is " + "bi-directional available"); /* This could happen when scenarios for given context type allows for * Sink and Source configuration but also only Sink configuration. */ @@ -1245,8 +1229,7 @@ bool LeAudioDeviceGroup::CigConfiguration::AssignCisIds( ase->cis_id = cis_id; cises[cis_id].addr = leAudioDevice->address_; - log::info("ASE ID: {}, assigned Uni-Directional Sink CIS ID: {}", ase->id, - ase->cis_id); + log::info("ASE ID: {}, assigned Uni-Directional Sink CIS ID: {}", ase->id, ase->cis_id); continue; } @@ -1263,8 +1246,8 @@ bool LeAudioDeviceGroup::CigConfiguration::AssignCisIds( * Sink and Source configuration but also only Sink configuration. */ log::warn( - "Unable to get free Uni-Directional Source CIS ID - maybe there is " - "bi-directional available"); + "Unable to get free Uni-Directional Source CIS ID - maybe there is " + "bi-directional available"); cis_id = GetFirstFreeCisId(CisType::CIS_TYPE_BIDIRECTIONAL); if (cis_id == kInvalidCisId) { log::error("Unable to get free Uni-Directional Source CIS ID"); @@ -1274,41 +1257,37 @@ bool LeAudioDeviceGroup::CigConfiguration::AssignCisIds( ase->cis_id = cis_id; cises[cis_id].addr = leAudioDevice->address_; - log::info("ASE ID: {}, assigned Uni-Directional Source CIS ID: {}", ase->id, - ase->cis_id); + log::info("ASE ID: {}, assigned Uni-Directional Source CIS ID: {}", ase->id, ase->cis_id); } return true; } void LeAudioDeviceGroup::CigConfiguration::AssignCisConnHandles( - const std::vector& conn_handles) { + const std::vector& conn_handles) { log::info("num of cis handles {}", static_cast(conn_handles.size())); for (size_t i = 0; i < cises.size(); i++) { cises[i].conn_handle = conn_handles[i]; - log::info("assigning cis[{}] conn_handle: {}", cises[i].id, - cises[i].conn_handle); + log::info("assigning cis[{}] conn_handle: {}", cises[i].id, cises[i].conn_handle); } } -void LeAudioDeviceGroup::AssignCisConnHandlesToAses( - LeAudioDevice* leAudioDevice) { +void LeAudioDeviceGroup::AssignCisConnHandlesToAses(LeAudioDevice* leAudioDevice) { log::assert_that(leAudioDevice, "Invalid device"); log::info("group: {}, group_id: {}, device: {}", fmt::ptr(this), group_id_, leAudioDevice->address_); /* Assign all CIS connection handles to ases */ struct bluetooth::le_audio::types::ase* ase = - leAudioDevice->GetFirstActiveAseByCisAndDataPathState( - CisState::IDLE, DataPathState::IDLE); + leAudioDevice->GetFirstActiveAseByCisAndDataPathState(CisState::IDLE, + DataPathState::IDLE); if (!ase) { log::warn("No active ASE with Cis and Data path state set to IDLE"); return; } - for (; ase != nullptr; - ase = leAudioDevice->GetFirstActiveAseByCisAndDataPathState( - CisState::IDLE, DataPathState::IDLE)) { + for (; ase != nullptr; ase = leAudioDevice->GetFirstActiveAseByCisAndDataPathState( + CisState::IDLE, DataPathState::IDLE)) { auto ases_pair = leAudioDevice->GetAsesByCisId(ase->cis_id); if (ases_pair.sink && ases_pair.sink->active) { @@ -1324,24 +1303,21 @@ void LeAudioDeviceGroup::AssignCisConnHandlesToAses( void LeAudioDeviceGroup::AssignCisConnHandlesToAses(void) { LeAudioDevice* leAudioDevice = GetFirstActiveDevice(); - log::assert_that(leAudioDevice, - "Shouldn't be called without an active device."); + log::assert_that(leAudioDevice, "Shouldn't be called without an active device."); log::info("Group {}, group_id {}", fmt::ptr(this), group_id_); /* Assign all CIS connection handles to ases */ - for (; leAudioDevice != nullptr; - leAudioDevice = GetNextActiveDevice(leAudioDevice)) { + for (; leAudioDevice != nullptr; leAudioDevice = GetNextActiveDevice(leAudioDevice)) { AssignCisConnHandlesToAses(leAudioDevice); } } -void LeAudioDeviceGroup::CigConfiguration::UnassignCis( - LeAudioDevice* leAudioDevice) { +void LeAudioDeviceGroup::CigConfiguration::UnassignCis(LeAudioDevice* leAudioDevice) { log::assert_that(leAudioDevice, "Invalid device"); - log::info("Group {}, group_id {}, device: {}", fmt::ptr(group_), - group_->group_id_, leAudioDevice->address_); + log::info("Group {}, group_id {}, device: {}", fmt::ptr(group_), group_->group_id_, + leAudioDevice->address_); for (struct bluetooth::le_audio::types::cis& cis_entry : cises) { if (cis_entry.addr == leAudioDevice->address_) { @@ -1351,38 +1327,34 @@ void LeAudioDeviceGroup::CigConfiguration::UnassignCis( } bool CheckIfStrategySupported(types::LeAudioConfigurationStrategy strategy, - const set_configurations::AseConfiguration& conf, - uint8_t direction, const LeAudioDevice& device) { + const set_configurations::AseConfiguration& conf, uint8_t direction, + const LeAudioDevice& device) { /* Check direction and if audio location allows to create more cises to a * single device. */ - types::AudioLocations audio_locations = - (direction == types::kLeAudioDirectionSink) ? device.snk_audio_locations_ + types::AudioLocations audio_locations = (direction == types::kLeAudioDirectionSink) + ? device.snk_audio_locations_ : device.src_audio_locations_; - log::debug("strategy: {}, locations: {}", (int)strategy, - audio_locations.to_ulong()); + log::debug("strategy: {}, locations: {}", (int)strategy, audio_locations.to_ulong()); switch (strategy) { case types::LeAudioConfigurationStrategy::MONO_ONE_CIS_PER_DEVICE: return audio_locations.any(); case types::LeAudioConfigurationStrategy::STEREO_TWO_CISES_PER_DEVICE: - if ((audio_locations.to_ulong() & - codec_spec_conf::kLeAudioLocationAnyLeft) && - (audio_locations.to_ulong() & - codec_spec_conf::kLeAudioLocationAnyRight)) + if ((audio_locations.to_ulong() & codec_spec_conf::kLeAudioLocationAnyLeft) && + (audio_locations.to_ulong() & codec_spec_conf::kLeAudioLocationAnyRight)) { return true; - else + } else { return false; + } case types::LeAudioConfigurationStrategy::STEREO_ONE_CIS_PER_DEVICE: { - if (!(audio_locations.to_ulong() & - codec_spec_conf::kLeAudioLocationAnyLeft) || - !(audio_locations.to_ulong() & - codec_spec_conf::kLeAudioLocationAnyRight)) + if (!(audio_locations.to_ulong() & codec_spec_conf::kLeAudioLocationAnyLeft) || + !(audio_locations.to_ulong() & codec_spec_conf::kLeAudioLocationAnyRight)) { return false; + } - auto channel_count_mask = - device.GetSupportedAudioChannelCounts(direction); + auto channel_count_mask = device.GetSupportedAudioChannelCounts(direction); auto requested_channel_count = conf.codec.GetChannelCountPerIsoStream(); log::debug("Requested channel count: {}, supp. channel counts: 0x{:x}", requested_channel_count, channel_count_mask); @@ -1391,7 +1363,7 @@ bool CheckIfStrategySupported(types::LeAudioConfigurationStrategy strategy, * counts. In the channel_count_mask, bit 0 is set when 1 channel is * supported. */ - return ((1 << (requested_channel_count - 1)) & channel_count_mask); + return (1 << (requested_channel_count - 1)) & channel_count_mask; } default: return false; @@ -1405,8 +1377,8 @@ bool CheckIfStrategySupported(types::LeAudioConfigurationStrategy strategy, * (no matter on the ASE state) and for given context type */ bool LeAudioDeviceGroup::IsAudioSetConfigurationSupported( - const CodecManager::UnicastConfigurationRequirements& requirements, - const set_configurations::AudioSetConfiguration* audio_set_conf) const { + const CodecManager::UnicastConfigurationRequirements& requirements, + const set_configurations::AudioSetConfiguration* audio_set_conf) const { /* TODO For now: set ase if matching with first pac. * 1) We assume as well that devices will match requirements in order * e.g. 1 Device - 1 Requirement, 2 Device - 2 Requirement etc. @@ -1416,14 +1388,12 @@ bool LeAudioDeviceGroup::IsAudioSetConfigurationSupported( */ auto required_snk_strategy = GetGroupSinkStrategy(); bool status = false; - for (auto direction : - {types::kLeAudioDirectionSink, types::kLeAudioDirectionSource}) { + for (auto direction : {types::kLeAudioDirectionSink, types::kLeAudioDirectionSource}) { log::debug("Looking for configuration: {} - {}", audio_set_conf->name, direction == types::kLeAudioDirectionSink ? "Sink" : "Source"); auto const& ase_confs = audio_set_conf->confs.get(direction); if (ase_confs.empty()) { - log::debug("No configurations for direction {}, skip it.", - (int)direction); + log::debug("No configurations for direction {}, skip it.", (int)direction); continue; } @@ -1445,50 +1415,43 @@ bool LeAudioDeviceGroup::IsAudioSetConfigurationSupported( continue; } - uint8_t const max_required_ase_per_dev = - ase_cnt / device_cnt + (ase_cnt % device_cnt); + uint8_t const max_required_ase_per_dev = ase_cnt / device_cnt + (ase_cnt % device_cnt); // Use strategy for the whole group (not only the connected devices) auto const strategy = utils::GetStrategyForAseConfig(ase_confs, device_cnt); log::debug( - "Number of devices: {}, number of ASEs: {}, Max ASE per device: {} " - "config strategy: {}, group strategy: {}", - device_cnt, ase_cnt, max_required_ase_per_dev, - static_cast(strategy), (int)required_snk_strategy); + "Number of devices: {}, number of ASEs: {}, Max ASE per device: {} " + "config strategy: {}, group strategy: {}", + device_cnt, ase_cnt, max_required_ase_per_dev, static_cast(strategy), + (int)required_snk_strategy); - if (direction == types::kLeAudioDirectionSink && - strategy != required_snk_strategy) { + if (direction == types::kLeAudioDirectionSink && strategy != required_snk_strategy) { log::debug("Sink strategy mismatch group!=cfg.entry ({}!={})", - static_cast(required_snk_strategy), - static_cast(strategy)); + static_cast(required_snk_strategy), static_cast(strategy)); return false; } uint8_t required_device_cnt = device_cnt; uint8_t active_ase_cnt = 0; - for (auto* device = GetFirstDevice(); - device != nullptr && required_device_cnt > 0; + for (auto* device = GetFirstDevice(); device != nullptr && required_device_cnt > 0; device = GetNextDevice(device)) { if (device->ases_.empty()) { log::error("Device has no ASEs."); continue; } - int needed_ase_per_dev = - std::min(static_cast(max_required_ase_per_dev), - static_cast(ase_cnt - active_ase_cnt)); + int needed_ase_per_dev = std::min(static_cast(max_required_ase_per_dev), + static_cast(ase_cnt - active_ase_cnt)); for (auto const& ent : ase_confs) { // Verify PACS only if this is transparent LTV format - auto const& pacs = (direction == types::kLeAudioDirectionSink) - ? device->snk_pacs_ - : device->src_pacs_; + auto const& pacs = + (direction == types::kLeAudioDirectionSink) ? device->snk_pacs_ : device->src_pacs_; if (utils::IsCodecUsingLtvFormat(ent.codec.id) && !utils::GetConfigurationSupportedPac(pacs, ent.codec)) { - log::debug( - "Insufficient PAC for {}", - direction == types::kLeAudioDirectionSink ? "sink" : "source"); + log::debug("Insufficient PAC for {}", + direction == types::kLeAudioDirectionSink ? "sink" : "source"); continue; } @@ -1497,18 +1460,21 @@ bool LeAudioDeviceGroup::IsAudioSetConfigurationSupported( continue; } for (auto& ase : device->ases_) { - if (ase.direction != direction) continue; + if (ase.direction != direction) { + continue; + } active_ase_cnt++; needed_ase_per_dev--; - if (needed_ase_per_dev == 0) break; + if (needed_ase_per_dev == 0) { + break; + } } } if (needed_ase_per_dev > 0) { - log::debug("Not enough ASEs on the device (needs {} more).", - needed_ase_per_dev); + log::debug("Not enough ASEs on the device (needs {} more).", needed_ase_per_dev); return false; } @@ -1531,19 +1497,17 @@ bool LeAudioDeviceGroup::IsAudioSetConfigurationSupported( * sampling rate matches with the sampling rate which is used * when all devices in the group are connected. */ - bool dual_bidirection_swb_supported_ = - CodecManager::GetInstance()->IsDualBiDirSwbSupported(); + bool dual_bidirection_swb_supported_ = CodecManager::GetInstance()->IsDualBiDirSwbSupported(); if (DesiredSize() > 1 && - CodecManager::GetInstance()->CheckCodecConfigIsBiDirSwb( - *audio_set_conf)) { + CodecManager::GetInstance()->CheckCodecConfigIsBiDirSwb(*audio_set_conf)) { if (!dual_bidirection_swb_supported_) { return false; } } if (status) { - log::debug("Chosen ASE Configuration for group: {}, configuration: {}", - group_id_, audio_set_conf->name); + log::debug("Chosen ASE Configuration for group: {}, configuration: {}", group_id_, + audio_set_conf->name); } else { log::error("Could not configure either direction for group {}", group_id_); } @@ -1554,12 +1518,11 @@ bool LeAudioDeviceGroup::IsAudioSetConfigurationSupported( * configuration for codec and qos. */ bool LeAudioDeviceGroup::ConfigureAses( - const set_configurations::AudioSetConfiguration* audio_set_conf, - LeAudioContextType context_type, - const types::BidirectionalPair& metadata_context_types, - const types::BidirectionalPair>& ccid_lists) { - bool reuse_cis_id = - GetState() == AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED; + const set_configurations::AudioSetConfiguration* audio_set_conf, + LeAudioContextType context_type, + const types::BidirectionalPair& metadata_context_types, + const types::BidirectionalPair>& ccid_lists) { + bool reuse_cis_id = GetState() == AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED; /* TODO For now: set ase if matching with first pac. * 1) We assume as well that devices will match requirements in order @@ -1572,15 +1535,11 @@ bool LeAudioDeviceGroup::ConfigureAses( // WARNING: This may look like the results stored here are unused, but it // actually shares the intermediate values between the multiple // configuration calls within the configuration loop. - BidirectionalPair group_audio_locations_memo = { - .sink = 0, .source = 0}; - - for (auto direction : - {types::kLeAudioDirectionSink, types::kLeAudioDirectionSource}) { - auto direction_str = - (direction == types::kLeAudioDirectionSink ? "Sink" : "Source"); - log::debug("{}: Looking for requirements: {}", direction_str, - audio_set_conf->name); + BidirectionalPair group_audio_locations_memo = {.sink = 0, .source = 0}; + + for (auto direction : {types::kLeAudioDirectionSink, types::kLeAudioDirectionSource}) { + auto direction_str = (direction == types::kLeAudioDirectionSink ? "Sink" : "Source"); + log::debug("{}: Looking for requirements: {}", direction_str, audio_set_conf->name); if (audio_set_conf->confs.get(direction).empty()) { log::warn("No {} configuration available.", direction_str); @@ -1602,11 +1561,10 @@ bool LeAudioDeviceGroup::ConfigureAses( return; } - if (!dev->ConfigureAses(audio_set_conf, max_required_device_cnt, - direction, context_type, &active_ase_cnt, - group_audio_locations_memo.get(direction), - metadata_context_types.get(direction), - ccid_lists.get(direction), reuse_cis_id)) { + if (!dev->ConfigureAses(audio_set_conf, max_required_device_cnt, direction, context_type, + &active_ase_cnt, group_audio_locations_memo.get(direction), + metadata_context_types.get(direction), ccid_lists.get(direction), + reuse_cis_id)) { return; } @@ -1623,8 +1581,7 @@ bool LeAudioDeviceGroup::ConfigureAses( // they are required for the scenario - we will not put this context into // their metadata anyway if (required_device_cnt > 0) { - for (auto* device = GetFirstDevice(); - device != nullptr && required_device_cnt > 0; + for (auto* device = GetFirstDevice(); device != nullptr && required_device_cnt > 0; device = GetNextDevice(device)) { configuration_closure(device); } @@ -1638,8 +1595,8 @@ bool LeAudioDeviceGroup::ConfigureAses( } } - log::info("Choosed ASE Configuration for group: {}, configuration: {}", - group_id_, audio_set_conf->name); + log::info("Choosed ASE Configuration for group: {}, configuration: {}", group_id_, + audio_set_conf->name); configuration_context_type_ = context_type; metadata_context_type_ = metadata_context_types; @@ -1647,8 +1604,7 @@ bool LeAudioDeviceGroup::ConfigureAses( } std::shared_ptr -LeAudioDeviceGroup::GetCachedConfiguration( - LeAudioContextType context_type) const { +LeAudioDeviceGroup::GetCachedConfiguration(LeAudioContextType context_type) const { if (context_to_configuration_cache_map.count(context_type) != 0) { return context_to_configuration_cache_map.at(context_type).second; } @@ -1671,8 +1627,7 @@ LeAudioDeviceGroup::GetConfiguration(LeAudioContextType context_type) const { /* Refresh the cache if there is no valid configuration */ if (context_to_configuration_cache_map.count(context_type) != 0) { - auto& valid_config_pair = - context_to_configuration_cache_map.at(context_type); + auto& valid_config_pair = context_to_configuration_cache_map.at(context_type); is_valid = valid_config_pair.first; conf = valid_config_pair.second.get(); } @@ -1683,16 +1638,14 @@ LeAudioDeviceGroup::GetConfiguration(LeAudioContextType context_type) const { return GetCachedConfiguration(context_type); } -LeAudioCodecConfiguration -LeAudioDeviceGroup::GetAudioSessionCodecConfigForDirection( - LeAudioContextType context_type, uint8_t direction) const { +LeAudioCodecConfiguration LeAudioDeviceGroup::GetAudioSessionCodecConfigForDirection( + LeAudioContextType context_type, uint8_t direction) const { const set_configurations::AudioSetConfiguration* conf = nullptr; bool is_valid = false; /* Refresh the cache if there is no valid configuration */ if (context_to_configuration_cache_map.count(context_type) != 0) { - auto& valid_config_pair = - context_to_configuration_cache_map.at(context_type); + auto& valid_config_pair = context_to_configuration_cache_map.at(context_type); is_valid = valid_config_pair.first; conf = valid_config_pair.second.get(); } @@ -1701,32 +1654,33 @@ LeAudioDeviceGroup::GetAudioSessionCodecConfigForDirection( } auto audio_set_conf = GetCachedConfiguration(context_type); - if (!audio_set_conf) return {0, 0, 0, 0}; + if (!audio_set_conf) { + return {0, 0, 0, 0}; + } - auto group_config = - utils::GetAudioSessionCodecConfigFromAudioSetConfiguration( + auto group_config = utils::GetAudioSessionCodecConfigFromAudioSetConfiguration( *audio_set_conf.get(), direction); return group_config; } -bool LeAudioDeviceGroup::HasCodecConfigurationForDirection( - types::LeAudioContextType context_type, uint8_t direction) const { +bool LeAudioDeviceGroup::HasCodecConfigurationForDirection(types::LeAudioContextType context_type, + uint8_t direction) const { auto audio_set_conf = GetConfiguration(context_type); return audio_set_conf ? !audio_set_conf->confs.get(direction).empty() : false; } -bool LeAudioDeviceGroup::IsAudioSetConfigurationAvailable( - LeAudioContextType group_context_type) { +bool LeAudioDeviceGroup::IsAudioSetConfigurationAvailable(LeAudioContextType group_context_type) { return GetConfiguration(group_context_type) != nullptr; } bool LeAudioDeviceGroup::IsMetadataChanged( - const BidirectionalPair& context_types, - const BidirectionalPair>& ccid_lists) const { + const BidirectionalPair& context_types, + const BidirectionalPair>& ccid_lists) const { for (auto* leAudioDevice = GetFirstActiveDevice(); leAudioDevice; leAudioDevice = GetNextActiveDevice(leAudioDevice)) { - if (leAudioDevice->IsMetadataChanged(context_types, ccid_lists)) + if (leAudioDevice->IsMetadataChanged(context_types, ccid_lists)) { return true; + } } return false; @@ -1734,59 +1688,58 @@ bool LeAudioDeviceGroup::IsMetadataChanged( bool LeAudioDeviceGroup::IsCisPartOfCurrentStream(uint16_t cis_conn_hdl) const { auto& sink_stream_locations = stream_conf.stream_params.sink.stream_locations; - auto iter = std::find_if( - sink_stream_locations.begin(), sink_stream_locations.end(), - [cis_conn_hdl](auto& pair) { return cis_conn_hdl == pair.first; }); + auto iter = std::find_if(sink_stream_locations.begin(), sink_stream_locations.end(), + [cis_conn_hdl](auto& pair) { return cis_conn_hdl == pair.first; }); - if (iter != sink_stream_locations.end()) return true; + if (iter != sink_stream_locations.end()) { + return true; + } - auto& source_stream_locations = - stream_conf.stream_params.source.stream_locations; - iter = std::find_if( - source_stream_locations.begin(), source_stream_locations.end(), - [cis_conn_hdl](auto& pair) { return cis_conn_hdl == pair.first; }); + auto& source_stream_locations = stream_conf.stream_params.source.stream_locations; + iter = std::find_if(source_stream_locations.begin(), source_stream_locations.end(), + [cis_conn_hdl](auto& pair) { return cis_conn_hdl == pair.first; }); - return (iter != source_stream_locations.end()); + return iter != source_stream_locations.end(); } -void LeAudioDeviceGroup::RemoveCisFromStreamIfNeeded( - LeAudioDevice* leAudioDevice, uint16_t cis_conn_hdl) { +void LeAudioDeviceGroup::RemoveCisFromStreamIfNeeded(LeAudioDevice* leAudioDevice, + uint16_t cis_conn_hdl) { log::info("CIS Connection Handle: {}", cis_conn_hdl); - if (!IsCisPartOfCurrentStream(cis_conn_hdl)) return; + if (!IsCisPartOfCurrentStream(cis_conn_hdl)) { + return; + } /* Cache the old values for comparison */ auto old_sink_channels = stream_conf.stream_params.sink.num_of_channels; auto old_source_channels = stream_conf.stream_params.source.num_of_channels; - for (auto dir : - {types::kLeAudioDirectionSink, types::kLeAudioDirectionSource}) { + for (auto dir : {types::kLeAudioDirectionSink, types::kLeAudioDirectionSource}) { auto& params = stream_conf.stream_params.get(dir); params.stream_locations.erase( - std::remove_if( - params.stream_locations.begin(), params.stream_locations.end(), - [leAudioDevice, &cis_conn_hdl, ¶ms, dir](auto& pair) { - if (!cis_conn_hdl) { - cis_conn_hdl = pair.first; - } - auto ases_pair = leAudioDevice->GetAsesByCisConnHdl(cis_conn_hdl); - if (ases_pair.get(dir) && cis_conn_hdl == pair.first) { - params.num_of_devices--; - params.num_of_channels -= ases_pair.get(dir)->channel_count; - params.audio_channel_allocation &= ~pair.second; - } - return (ases_pair.get(dir) && cis_conn_hdl == pair.first); - }), - params.stream_locations.end()); + std::remove_if(params.stream_locations.begin(), params.stream_locations.end(), + [leAudioDevice, &cis_conn_hdl, ¶ms, dir](auto& pair) { + if (!cis_conn_hdl) { + cis_conn_hdl = pair.first; + } + auto ases_pair = leAudioDevice->GetAsesByCisConnHdl(cis_conn_hdl); + if (ases_pair.get(dir) && cis_conn_hdl == pair.first) { + params.num_of_devices--; + params.num_of_channels -= ases_pair.get(dir)->channel_count; + params.audio_channel_allocation &= ~pair.second; + } + return ases_pair.get(dir) && cis_conn_hdl == pair.first; + }), + params.stream_locations.end()); } log::info( - "Sink Number Of Devices: {}, Sink Number Of Channels: {}, Source Number " - "Of Devices: {}, Source Number Of Channels: {}", - stream_conf.stream_params.sink.num_of_devices, - stream_conf.stream_params.sink.num_of_channels, - stream_conf.stream_params.source.num_of_devices, - stream_conf.stream_params.source.num_of_channels); + "Sink Number Of Devices: {}, Sink Number Of Channels: {}, Source Number " + "Of Devices: {}, Source Number Of Channels: {}", + stream_conf.stream_params.sink.num_of_devices, + stream_conf.stream_params.sink.num_of_channels, + stream_conf.stream_params.source.num_of_devices, + stream_conf.stream_params.source.num_of_channels); if (stream_conf.stream_params.sink.num_of_channels == 0) { ClearSinksFromConfiguration(); @@ -1799,17 +1752,15 @@ void LeAudioDeviceGroup::RemoveCisFromStreamIfNeeded( /* Update CodecManager CIS configuration */ if (old_sink_channels > stream_conf.stream_params.sink.num_of_channels) { CodecManager::GetInstance()->UpdateCisConfiguration( - cig.cises, - stream_conf.stream_params.get( - bluetooth::le_audio::types::kLeAudioDirectionSink), - bluetooth::le_audio::types::kLeAudioDirectionSink); + cig.cises, + stream_conf.stream_params.get(bluetooth::le_audio::types::kLeAudioDirectionSink), + bluetooth::le_audio::types::kLeAudioDirectionSink); } if (old_source_channels > stream_conf.stream_params.source.num_of_channels) { CodecManager::GetInstance()->UpdateCisConfiguration( - cig.cises, - stream_conf.stream_params.get( - bluetooth::le_audio::types::kLeAudioDirectionSource), - bluetooth::le_audio::types::kLeAudioDirectionSource); + cig.cises, + stream_conf.stream_params.get(bluetooth::le_audio::types::kLeAudioDirectionSource), + bluetooth::le_audio::types::kLeAudioDirectionSource); } cig.UnassignCis(leAudioDevice); @@ -1819,9 +1770,7 @@ bool LeAudioDeviceGroup::IsPendingConfiguration(void) const { return stream_conf.pending_configuration; } -void LeAudioDeviceGroup::SetPendingConfiguration(void) { - stream_conf.pending_configuration = true; -} +void LeAudioDeviceGroup::SetPendingConfiguration(void) { stream_conf.pending_configuration = true; } void LeAudioDeviceGroup::ClearPendingConfiguration(void) { stream_conf.pending_configuration = false; @@ -1841,8 +1790,8 @@ void LeAudioDeviceGroup::Disable(int gatt_if) { btif_storage_set_leaudio_autoconnect(address, false); device_iter.lock()->autoconnect_flag_ = false; - log::info("Group {} in state {}. Removing {} from background connect", - group_id_, bluetooth::common::ToString(GetState()), address); + log::info("Group {} in state {}. Removing {} from background connect", group_id_, + bluetooth::common::ToString(GetState()), address); BTA_GATTC_CancelOpen(gatt_if, address, false); @@ -1852,8 +1801,7 @@ void LeAudioDeviceGroup::Disable(int gatt_if) { } } -void LeAudioDeviceGroup::Enable(int gatt_if, - tBTM_BLE_CONN_TYPE reconnection_mode) { +void LeAudioDeviceGroup::Enable(int gatt_if, tBTM_BLE_CONN_TYPE reconnection_mode) { is_enabled_ = true; for (auto& device_iter : leAudioDevices_) { if (device_iter.lock()->autoconnect_flag_) { @@ -1866,28 +1814,25 @@ void LeAudioDeviceGroup::Enable(int gatt_if, btif_storage_set_leaudio_autoconnect(address, true); device_iter.lock()->autoconnect_flag_ = true; - log::info("Group {} in state {}. Adding {} from background connect", - group_id_, bluetooth::common::ToString(GetState()), address); + log::info("Group {} in state {}. Adding {} from background connect", group_id_, + bluetooth::common::ToString(GetState()), address); if (connection_state == DeviceConnectState::DISCONNECTED) { BTA_GATTC_Open(gatt_if, address, reconnection_mode, false); - device_iter.lock()->SetConnectionState( - DeviceConnectState::CONNECTING_AUTOCONNECT); + device_iter.lock()->SetConnectionState(DeviceConnectState::CONNECTING_AUTOCONNECT); } } } -bool LeAudioDeviceGroup::IsEnabled(void) const { return is_enabled_; }; +bool LeAudioDeviceGroup::IsEnabled(void) const { return is_enabled_; } void LeAudioDeviceGroup::AddToAllowListNotConnectedGroupMembers(int gatt_if) { for (const auto& device_iter : leAudioDevices_) { auto connection_state = device_iter.lock()->GetConnectionState(); if (connection_state == DeviceConnectState::CONNECTED || connection_state == DeviceConnectState::CONNECTING_BY_USER || - connection_state == - DeviceConnectState::CONNECTED_BY_USER_GETTING_READY || - connection_state == - DeviceConnectState::CONNECTED_AUTOCONNECT_GETTING_READY) { + connection_state == DeviceConnectState::CONNECTED_BY_USER_GETTING_READY || + connection_state == DeviceConnectState::CONNECTED_AUTOCONNECT_GETTING_READY) { continue; } @@ -1903,47 +1848,42 @@ void LeAudioDeviceGroup::AddToAllowListNotConnectedGroupMembers(int gatt_if) { */ BTA_GATTC_CancelOpen(gatt_if, address, false); BTA_GATTC_Open(gatt_if, address, BTM_BLE_DIRECT_CONNECTION, false); - device_iter.lock()->SetConnectionState( - DeviceConnectState::CONNECTING_AUTOCONNECT); + device_iter.lock()->SetConnectionState(DeviceConnectState::CONNECTING_AUTOCONNECT); } } -void LeAudioDeviceGroup::ApplyReconnectionMode( - int gatt_if, tBTM_BLE_CONN_TYPE reconnection_mode) { +void LeAudioDeviceGroup::ApplyReconnectionMode(int gatt_if, tBTM_BLE_CONN_TYPE reconnection_mode) { for (const auto& device_iter : leAudioDevices_) { BTA_GATTC_CancelOpen(gatt_if, device_iter.lock()->address_, false); - BTA_GATTC_Open(gatt_if, device_iter.lock()->address_, reconnection_mode, - false); - log::info("Group {} in state {}. Adding {} to default reconnection mode", - group_id_, bluetooth::common::ToString(GetState()), - device_iter.lock()->address_); - device_iter.lock()->SetConnectionState( - DeviceConnectState::CONNECTING_AUTOCONNECT); + BTA_GATTC_Open(gatt_if, device_iter.lock()->address_, reconnection_mode, false); + log::info("Group {} in state {}. Adding {} to default reconnection mode", group_id_, + bluetooth::common::ToString(GetState()), device_iter.lock()->address_); + device_iter.lock()->SetConnectionState(DeviceConnectState::CONNECTING_AUTOCONNECT); } } -bool LeAudioDeviceGroup::IsConfiguredForContext( - LeAudioContextType context_type) const { +bool LeAudioDeviceGroup::IsConfiguredForContext(LeAudioContextType context_type) const { /* Check if all connected group members are configured */ if (GetConfigurationContextType() != context_type) { return false; } - if (!stream_conf.conf) return false; + if (!stream_conf.conf) { + return false; + } /* Check if used configuration is same as the active one.*/ - return (stream_conf.conf.get() == GetActiveConfiguration().get()); + return stream_conf.conf.get() == GetActiveConfiguration().get(); } const set_configurations::AudioSetConfiguration* LeAudioDeviceGroup::FindFirstSupportedConfiguration( - const CodecManager::UnicastConfigurationRequirements& requirements, - const set_configurations::AudioSetConfigurations* confs) const { + const CodecManager::UnicastConfigurationRequirements& requirements, + const set_configurations::AudioSetConfigurations* confs) const { log::assert_that(confs != nullptr, "confs should not be null"); log::debug("context type: {}, number of connected devices: {}", - bluetooth::common::ToString(requirements.audio_context_type), - NumOfConnected()); + bluetooth::common::ToString(requirements.audio_context_type), NumOfConnected()); /* Filter out device set for each end every scenario */ for (const auto& conf : *confs) { @@ -1961,27 +1901,25 @@ LeAudioDeviceGroup::FindFirstSupportedConfiguration( * configuration for codec and qos. */ bool LeAudioDeviceGroup::Configure( - LeAudioContextType context_type, - const types::BidirectionalPair& metadata_context_types, - types::BidirectionalPair> ccid_lists) { + LeAudioContextType context_type, + const types::BidirectionalPair& metadata_context_types, + types::BidirectionalPair> ccid_lists) { auto conf = GetConfiguration(context_type); if (!conf) { log::error( - ", requested context type: {} , is in mismatch with cached available " - "contexts", - bluetooth::common::ToString(context_type)); + ", requested context type: {} , is in mismatch with cached available " + "contexts", + bluetooth::common::ToString(context_type)); return false; } - log::debug("setting context type: {}", - bluetooth::common::ToString(context_type)); + log::debug("setting context type: {}", bluetooth::common::ToString(context_type)); - if (!ConfigureAses(conf.get(), context_type, metadata_context_types, - ccid_lists)) { + if (!ConfigureAses(conf.get(), context_type, metadata_context_types, ccid_lists)) { log::error( - ", requested context type: {}, is in mismatch with cached available " - "contexts", - bluetooth::common::ToString(context_type)); + ", requested context type: {}, is in mismatch with cached available " + "contexts", + bluetooth::common::ToString(context_type)); return false; } @@ -1998,11 +1936,9 @@ void LeAudioDeviceGroup::PrintDebugState(void) const { auto active_conf = GetActiveConfiguration(); std::stringstream debug_str; - debug_str << "\n Groupd id: " << group_id_ - << (is_enabled_ ? " enabled" : " disabled") + debug_str << "\n Groupd id: " << group_id_ << (is_enabled_ ? " enabled" : " disabled") << ", state: " << bluetooth::common::ToString(GetState()) - << ", target state: " - << bluetooth::common::ToString(GetTargetState()) + << ", target state: " << bluetooth::common::ToString(GetTargetState()) << ", cig state: " << bluetooth::common::ToString(cig.GetState()) << ", \n group supported contexts: " << bluetooth::common::ToString(GetSupportedContexts()) @@ -2012,42 +1948,33 @@ void LeAudioDeviceGroup::PrintDebugState(void) const { << bluetooth::common::ToString(GetAllowedContextMask()) << ", \n configuration context type: " << bluetooth::common::ToString(GetConfigurationContextType()) - << ", \n active configuration name: " - << (active_conf ? active_conf->name : " not set"); + << ", \n active configuration name: " << (active_conf ? active_conf->name : " not set"); if (cig.cises.size() > 0) { log::info("\n Allocated CISes: {}", static_cast(cig.cises.size())); for (auto cis : cig.cises) { - log::info("\n cis id: {}, type: {}, conn_handle {}, addr: {}", cis.id, - cis.type, cis.conn_handle, cis.addr.ToString()); + log::info("\n cis id: {}, type: {}, conn_handle {}, addr: {}", cis.id, cis.type, + cis.conn_handle, cis.addr.ToString()); } } if (GetFirstActiveDevice() != nullptr) { uint32_t sink_delay = 0; uint32_t source_delay = 0; - GetPresentationDelay(&sink_delay, - bluetooth::le_audio::types::kLeAudioDirectionSink); - GetPresentationDelay(&source_delay, - bluetooth::le_audio::types::kLeAudioDirectionSource); - auto phy_mtos = - GetPhyBitmask(bluetooth::le_audio::types::kLeAudioDirectionSink); - auto phy_stom = - GetPhyBitmask(bluetooth::le_audio::types::kLeAudioDirectionSource); + GetPresentationDelay(&sink_delay, bluetooth::le_audio::types::kLeAudioDirectionSink); + GetPresentationDelay(&source_delay, bluetooth::le_audio::types::kLeAudioDirectionSource); + auto phy_mtos = GetPhyBitmask(bluetooth::le_audio::types::kLeAudioDirectionSink); + auto phy_stom = GetPhyBitmask(bluetooth::le_audio::types::kLeAudioDirectionSource); auto max_transport_latency_mtos = GetMaxTransportLatencyMtos(); auto max_transport_latency_stom = GetMaxTransportLatencyStom(); - auto sdu_mts = - GetSduInterval(bluetooth::le_audio::types::kLeAudioDirectionSink); - auto sdu_stom = - GetSduInterval(bluetooth::le_audio::types::kLeAudioDirectionSource); + auto sdu_mts = GetSduInterval(bluetooth::le_audio::types::kLeAudioDirectionSink); + auto sdu_stom = GetSduInterval(bluetooth::le_audio::types::kLeAudioDirectionSource); debug_str << "\n presentation_delay for sink (speaker): " << +sink_delay - << " us, presentation_delay for source (microphone): " - << +source_delay << "us, \n MtoS transport latency: " - << +max_transport_latency_mtos + << " us, presentation_delay for source (microphone): " << +source_delay + << "us, \n MtoS transport latency: " << +max_transport_latency_mtos << ", StoM transport latency: " << +max_transport_latency_stom - << ", \n MtoS Phy: " << loghex(phy_mtos) - << ", MtoS sdu: " << loghex(phy_stom) + << ", \n MtoS Phy: " << loghex(phy_mtos) << ", MtoS sdu: " << loghex(phy_stom) << " \n MtoS sdu: " << +sdu_mts << ", StoM sdu: " << +sdu_stom; } @@ -2063,34 +1990,25 @@ void LeAudioDeviceGroup::Dump(int fd, int active_group_id) const { std::stringstream stream, stream_pacs; auto active_conf = GetActiveConfiguration(); - stream << "\n == Group id: " << group_id_ - << (is_enabled_ ? " enabled" : " disabled") - << " == " << (is_active ? ",\tActive\n" : ",\tInactive\n") - << " state: " << GetState() - << ",\ttarget state: " << GetTargetState() - << ",\tcig state: " << cig.GetState() << "\n" + stream << "\n == Group id: " << group_id_ << (is_enabled_ ? " enabled" : " disabled") + << " == " << (is_active ? ",\tActive\n" : ",\tInactive\n") << " state: " << GetState() + << ",\ttarget state: " << GetTargetState() << ",\tcig state: " << cig.GetState() << "\n" << " group supported contexts: " << GetSupportedContexts() << "\n" << " group available contexts: " << GetAvailableContexts() << "\n" << " group allowed contexts: " << GetAllowedContextMask() << "\n" << " configuration context type: " - << bluetooth::common::ToString(GetConfigurationContextType()).c_str() + << bluetooth::common::ToString(GetConfigurationContextType()).c_str() << "\n" + << " active configuration name: " << (active_conf ? active_conf->name : " not set") << "\n" - << " active configuration name: " - << (active_conf ? active_conf->name : " not set") << "\n" << " stream configuration: " - << (stream_conf.conf != nullptr ? stream_conf.conf->name : " unknown ") - << "\n" + << (stream_conf.conf != nullptr ? stream_conf.conf->name : " unknown ") << "\n" << " codec id: " << +(stream_conf.codec_id.coding_format) - << ",\tpending_configuration: " << stream_conf.pending_configuration - << "\n" - << " num of devices(connected): " << Size() << "(" - << NumOfConnected() << ")\n" - << ", num of sinks(connected): " - << stream_conf.stream_params.sink.num_of_devices << "(" - << stream_conf.stream_params.sink.stream_locations.size() << ")\n" - << " num of sources(connected): " - << stream_conf.stream_params.source.num_of_devices << "(" - << stream_conf.stream_params.source.stream_locations.size() << ")\n" + << ",\tpending_configuration: " << stream_conf.pending_configuration << "\n" + << " num of devices(connected): " << Size() << "(" << NumOfConnected() << ")\n" + << ", num of sinks(connected): " << stream_conf.stream_params.sink.num_of_devices + << "(" << stream_conf.stream_params.sink.stream_locations.size() << ")\n" + << " num of sources(connected): " << stream_conf.stream_params.source.num_of_devices + << "(" << stream_conf.stream_params.source.stream_locations.size() << ")\n" << " allocated CISes: " << static_cast(cig.cises.size()); if (cig.cises.size() > 0) { @@ -2106,18 +2024,13 @@ void LeAudioDeviceGroup::Dump(int fd, int active_group_id) const { if (GetFirstActiveDevice() != nullptr) { uint32_t sink_delay; - if (GetPresentationDelay( - &sink_delay, bluetooth::le_audio::types::kLeAudioDirectionSink)) { - stream << "\n presentation_delay for sink (speaker): " << sink_delay - << " us"; + if (GetPresentationDelay(&sink_delay, bluetooth::le_audio::types::kLeAudioDirectionSink)) { + stream << "\n presentation_delay for sink (speaker): " << sink_delay << " us"; } uint32_t source_delay; - if (GetPresentationDelay( - &source_delay, - bluetooth::le_audio::types::kLeAudioDirectionSource)) { - stream << "\n presentation_delay for source (microphone): " - << source_delay << " us"; + if (GetPresentationDelay(&source_delay, bluetooth::le_audio::types::kLeAudioDirectionSource)) { + stream << "\n presentation_delay for source (microphone): " << source_delay << " us"; } } @@ -2144,14 +2057,12 @@ LeAudioDeviceGroup* LeAudioDeviceGroups::Add(int group_id) { return nullptr; } - return (groups_.emplace_back(std::make_unique(group_id))) - .get(); + return (groups_.emplace_back(std::make_unique(group_id))).get(); } void LeAudioDeviceGroups::Remove(int group_id) { - auto iter = std::find_if( - groups_.begin(), groups_.end(), - [&group_id](auto const& group) { return group->group_id_ == group_id; }); + auto iter = std::find_if(groups_.begin(), groups_.end(), + [&group_id](auto const& group) { return group->group_id_ == group_id; }); if (iter == groups_.end()) { log::error("no such group_id: {}", group_id); @@ -2162,9 +2073,8 @@ void LeAudioDeviceGroups::Remove(int group_id) { } LeAudioDeviceGroup* LeAudioDeviceGroups::FindById(int group_id) const { - auto iter = std::find_if( - groups_.begin(), groups_.end(), - [&group_id](auto const& group) { return group->group_id_ == group_id; }); + auto iter = std::find_if(groups_.begin(), groups_.end(), + [&group_id](auto const& group) { return group->group_id_ == group_id; }); return (iter == groups_.end()) ? nullptr : iter->get(); } @@ -2204,7 +2114,7 @@ bool LeAudioDeviceGroups::IsAnyInTransition(void) const { return false; } -size_t LeAudioDeviceGroups::Size() const { return (groups_.size()); } +size_t LeAudioDeviceGroups::Size() const { return groups_.size(); } std::vector LeAudioDeviceGroups::GetGroupsIds(void) const { std::vector result; diff --git a/system/bta/le_audio/device_groups.h b/system/bta/le_audio/device_groups.h index 2a2b1b920a6..0a4fa95f400 100644 --- a/system/bta/le_audio/device_groups.h +++ b/system/bta/le_audio/device_groups.h @@ -46,14 +46,13 @@ namespace bluetooth::le_audio { class LeAudioDeviceGroup { - public: +public: const int group_id_; class CigConfiguration { - public: + public: CigConfiguration() = delete; - CigConfiguration(LeAudioDeviceGroup* group) - : group_(group), state_(types::CigState::NONE) {} + CigConfiguration(LeAudioDeviceGroup* group) : group_(group), state_(types::CigState::NONE) {} types::CigState GetState(void) const { return state_; } void SetState(bluetooth::le_audio::types::CigState state) { @@ -69,22 +68,22 @@ class LeAudioDeviceGroup { std::vector cises; - private: + private: uint8_t GetFirstFreeCisId(types::CisType cis_type) const; LeAudioDeviceGroup* group_; types::CigState state_; } cig; - bool IsGroupConfiguredTo( - const set_configurations::AudioSetConfiguration& cfg) { - if (!stream_conf.conf) return false; + bool IsGroupConfiguredTo(const set_configurations::AudioSetConfiguration& cfg) { + if (!stream_conf.conf) { + return false; + } return cfg == *stream_conf.conf; } /* Current configuration strategy - recalculated on demand */ - mutable std::optional strategy_ = - std::nullopt; + mutable std::optional strategy_ = std::nullopt; /* Current audio stream configuration */ struct stream_configuration stream_conf; @@ -115,37 +114,33 @@ class LeAudioDeviceGroup { transport_latency_mtos_us_(0), transport_latency_stom_us_(0), configuration_context_type_(types::LeAudioContextType::UNINITIALIZED), - metadata_context_type_({.sink = types::AudioContexts( - types::LeAudioContextType::UNINITIALIZED), - .source = types::AudioContexts( - types::LeAudioContextType::UNINITIALIZED)}), + metadata_context_type_( + {.sink = types::AudioContexts(types::LeAudioContextType::UNINITIALIZED), + .source = types::AudioContexts(types::LeAudioContextType::UNINITIALIZED)}), group_available_contexts_( - {.sink = - types::AudioContexts(types::LeAudioContextType::UNINITIALIZED), - .source = types::AudioContexts( - types::LeAudioContextType::UNINITIALIZED)}), - pending_group_available_contexts_change_( - types::LeAudioContextType::UNINITIALIZED), + {.sink = types::AudioContexts(types::LeAudioContextType::UNINITIALIZED), + .source = types::AudioContexts(types::LeAudioContextType::UNINITIALIZED)}), + pending_group_available_contexts_change_(types::LeAudioContextType::UNINITIALIZED), group_user_allowed_context_mask_( - {.sink = types::AudioContexts(types::kLeAudioContextAllTypes), - .source = types::AudioContexts(types::kLeAudioContextAllTypes)}), + {.sink = types::AudioContexts(types::kLeAudioContextAllTypes), + .source = types::AudioContexts(types::kLeAudioContextAllTypes)}), target_state_(types::AseState::BTA_LE_AUDIO_ASE_STATE_IDLE), current_state_(types::AseState::BTA_LE_AUDIO_ASE_STATE_IDLE), in_transition_(false) { #ifdef __ANDROID__ // 22 maps to BluetoothProfile#LE_AUDIO - is_output_preference_le_audio = android::sysprop::BluetoothProperties:: - getDefaultOutputOnlyAudioProfile() == - LE_AUDIO_PROFILE_CONSTANT; + is_output_preference_le_audio = + android::sysprop::BluetoothProperties::getDefaultOutputOnlyAudioProfile() == + LE_AUDIO_PROFILE_CONSTANT; is_duplex_preference_le_audio = - android::sysprop::BluetoothProperties::getDefaultDuplexAudioProfile() == - LE_AUDIO_PROFILE_CONSTANT; + android::sysprop::BluetoothProperties::getDefaultDuplexAudioProfile() == + LE_AUDIO_PROFILE_CONSTANT; #else is_output_preference_le_audio = true; is_duplex_preference_le_audio = true; #endif asymmetric_phy_for_unidirectional_cis_supported = - com::android::bluetooth::flags::asymmetric_phy_for_unidirectional_cis(); + com::android::bluetooth::flags::asymmetric_phy_for_unidirectional_cis(); } ~LeAudioDeviceGroup(void); @@ -158,30 +153,27 @@ class LeAudioDeviceGroup { int NumOfConnected() const; int NumOfAvailableForDirection(int direction) const; bool Activate(types::LeAudioContextType context_type, - const types::BidirectionalPair& - metadata_context_types, + const types::BidirectionalPair& metadata_context_types, types::BidirectionalPair> ccid_lists); void Deactivate(void); void ClearSinksFromConfiguration(void); void ClearSourcesFromConfiguration(void); void Cleanup(void); LeAudioDevice* GetFirstDevice(void) const; - LeAudioDevice* GetFirstDeviceWithAvailableContext( - types::LeAudioContextType context_type) const; + LeAudioDevice* GetFirstDeviceWithAvailableContext(types::LeAudioContextType context_type) const; types::LeAudioConfigurationStrategy GetGroupSinkStrategy(void) const; inline void InvalidateGroupStrategy(void) { strategy_ = std::nullopt; } int GetAseCount(uint8_t direction) const; LeAudioDevice* GetNextDevice(LeAudioDevice* leAudioDevice) const; - LeAudioDevice* GetNextDeviceWithAvailableContext( - LeAudioDevice* leAudioDevice, - types::LeAudioContextType context_type) const; + LeAudioDevice* GetNextDeviceWithAvailableContext(LeAudioDevice* leAudioDevice, + types::LeAudioContextType context_type) const; LeAudioDevice* GetFirstActiveDevice(void) const; LeAudioDevice* GetNextActiveDevice(LeAudioDevice* leAudioDevice) const; LeAudioDevice* GetFirstActiveDeviceByCisAndDataPathState( - types::CisState cis_state, types::DataPathState data_path_state) const; + types::CisState cis_state, types::DataPathState data_path_state) const; LeAudioDevice* GetNextActiveDeviceByCisAndDataPathState( - LeAudioDevice* leAudioDevice, types::CisState cis_state, - types::DataPathState data_path_state) const; + LeAudioDevice* leAudioDevice, types::CisState cis_state, + types::DataPathState data_path_state) const; bool IsDeviceInTheGroup(LeAudioDevice* leAudioDevice) const; bool HaveAllActiveDevicesAsesTheSameState(types::AseState state) const; bool HaveAnyActiveDeviceInStreamingState() const; @@ -195,10 +187,9 @@ class LeAudioDeviceGroup { void AssignCisConnHandlesToAses(LeAudioDevice* leAudioDevice); void AssignCisConnHandlesToAses(void); bool Configure(types::LeAudioContextType context_type, - const types::BidirectionalPair& - metadata_context_types, - types::BidirectionalPair> ccid_lists = { - .sink = {}, .source = {}}); + const types::BidirectionalPair& metadata_context_types, + types::BidirectionalPair> ccid_lists = {.sink = {}, + .source = {}}); uint32_t GetSduInterval(uint8_t direction) const; uint8_t GetSCA(void) const; uint8_t GetPacking(void) const; @@ -213,20 +204,18 @@ class LeAudioDeviceGroup { bool GetPresentationDelay(uint32_t* delay, uint8_t direction) const; uint16_t GetRemoteDelay(uint8_t direction) const; bool UpdateAudioContextAvailability(void); - bool UpdateAudioSetConfigurationCache( - types::LeAudioContextType ctx_type) const; - CodecManager::UnicastConfigurationRequirements - GetAudioSetConfigurationRequirements( - types::LeAudioContextType ctx_type) const; + bool UpdateAudioSetConfigurationCache(types::LeAudioContextType ctx_type) const; + CodecManager::UnicastConfigurationRequirements GetAudioSetConfigurationRequirements( + types::LeAudioContextType ctx_type) const; bool ReloadAudioLocations(void); bool ReloadAudioDirections(void); - std::shared_ptr - GetActiveConfiguration(void) const; + std::shared_ptr GetActiveConfiguration( + void) const; bool IsPendingConfiguration(void) const; - std::shared_ptr - GetConfiguration(types::LeAudioContextType ctx_type) const; - std::shared_ptr - GetCachedConfiguration(types::LeAudioContextType ctx_type) const; + std::shared_ptr GetConfiguration( + types::LeAudioContextType ctx_type) const; + std::shared_ptr GetCachedConfiguration( + types::LeAudioContextType ctx_type) const; void InvalidateCachedConfigurations(void); void SetPendingConfiguration(void); void ClearPendingConfiguration(void); @@ -236,27 +225,24 @@ class LeAudioDeviceGroup { void Enable(int gatt_if, tBTM_BLE_CONN_TYPE reconnection_mode); bool IsEnabled(void) const; LeAudioCodecConfiguration GetAudioSessionCodecConfigForDirection( - types::LeAudioContextType group_context_type, uint8_t direction) const; - bool HasCodecConfigurationForDirection( - types::LeAudioContextType group_context_type, uint8_t direction) const; - bool IsAudioSetConfigurationAvailable( - types::LeAudioContextType group_context_type); - bool IsMetadataChanged( - const types::BidirectionalPair& context_types, - const types::BidirectionalPair>& ccid_lists) const; + types::LeAudioContextType group_context_type, uint8_t direction) const; + bool HasCodecConfigurationForDirection(types::LeAudioContextType group_context_type, + uint8_t direction) const; + bool IsAudioSetConfigurationAvailable(types::LeAudioContextType group_context_type); + bool IsMetadataChanged(const types::BidirectionalPair& context_types, + const types::BidirectionalPair>& ccid_lists) const; bool IsConfiguredForContext(types::LeAudioContextType context_type) const; - void RemoveCisFromStreamIfNeeded(LeAudioDevice* leAudioDevice, - uint16_t cis_conn_hdl); + void RemoveCisFromStreamIfNeeded(LeAudioDevice* leAudioDevice, uint16_t cis_conn_hdl); inline types::AseState GetState(void) const { return current_state_; } void SetState(types::AseState state) { log::info("current state: {}, new state {}, in_transition_ {}", - bluetooth::common::ToString(current_state_), - bluetooth::common::ToString(state), in_transition_); - LeAudioLogHistory::Get()->AddLogHistory( - kLogStateMachineTag, group_id_, RawAddress::kEmpty, kLogStateChangedOp, - bluetooth::common::ToString(current_state_) + "->" + - bluetooth::common::ToString(state)); + bluetooth::common::ToString(current_state_), bluetooth::common::ToString(state), + in_transition_); + LeAudioLogHistory::Get()->AddLogHistory(kLogStateMachineTag, group_id_, RawAddress::kEmpty, + kLogStateChangedOp, + bluetooth::common::ToString(current_state_) + "->" + + bluetooth::common::ToString(state)); current_state_ = state; if (target_state_ == current_state_) { @@ -274,13 +260,11 @@ class LeAudioDeviceGroup { } void SetTargetState(types::AseState state) { log::info("target state: {}, new target state: {}, in_transition_ {}", - bluetooth::common::ToString(target_state_), - bluetooth::common::ToString(state), in_transition_); + bluetooth::common::ToString(target_state_), bluetooth::common::ToString(state), + in_transition_); LeAudioLogHistory::Get()->AddLogHistory( - kLogStateMachineTag, group_id_, RawAddress::kEmpty, - kLogTargetStateChangedOp, - bluetooth::common::ToString(target_state_) + "->" + - bluetooth::common::ToString(state)); + kLogStateMachineTag, group_id_, RawAddress::kEmpty, kLogTargetStateChangedOp, + bluetooth::common::ToString(target_state_) + "->" + bluetooth::common::ToString(state)); target_state_ = state; @@ -294,8 +278,7 @@ class LeAudioDeviceGroup { } /* Set which context types were recently added or removed */ - inline void SetPendingAvailableContextsChange( - types::AudioContexts audio_contexts) { + inline void SetPendingAvailableContextsChange(types::AudioContexts audio_contexts) { pending_group_available_contexts_change_ = audio_contexts; } @@ -303,8 +286,7 @@ class LeAudioDeviceGroup { pending_group_available_contexts_change_.clear(); } - inline void SetConfigurationContextType( - types::LeAudioContextType context_type) { + inline void SetConfigurationContextType(types::LeAudioContextType context_type) { configuration_context_type_ = context_type; } @@ -312,65 +294,49 @@ class LeAudioDeviceGroup { return configuration_context_type_; } - inline types::BidirectionalPair GetMetadataContexts() - const { + inline types::BidirectionalPair GetMetadataContexts() const { return metadata_context_type_; } - inline void SetAvailableContexts( - types::BidirectionalPair new_contexts) { + inline void SetAvailableContexts(types::BidirectionalPair new_contexts) { group_available_contexts_ = new_contexts; - log::debug( - "group id: {}, available contexts sink: {}, available contexts source: " - "{}", - group_id_, group_available_contexts_.sink.to_string(), - group_available_contexts_.source.to_string()); + log::debug("group id: {}, available contexts sink: {}, available contexts source: {}", + group_id_, group_available_contexts_.sink.to_string(), + group_available_contexts_.source.to_string()); } - types::AudioContexts GetAvailableContexts( - int direction = types::kLeAudioDirectionBoth) const { - log::assert_that(direction <= (types::kLeAudioDirectionBoth), - "Invalid direction used."); + types::AudioContexts GetAvailableContexts(int direction = types::kLeAudioDirectionBoth) const { + log::assert_that(direction <= (types::kLeAudioDirectionBoth), "Invalid direction used."); if (direction < types::kLeAudioDirectionBoth) { - log::debug( - "group id: {}, available contexts sink: {}, available contexts " - "source: {}", - group_id_, group_available_contexts_.sink.to_string(), - group_available_contexts_.source.to_string()); + log::debug("group id: {}, available contexts sink: {}, available contexts source: {}", + group_id_, group_available_contexts_.sink.to_string(), + group_available_contexts_.source.to_string()); return group_available_contexts_.get(direction); } else { return types::get_bidirectional(group_available_contexts_); } } - inline void SetAllowedContextMask( - types::BidirectionalPair& context_types) { + inline void SetAllowedContextMask(types::BidirectionalPair& context_types) { group_user_allowed_context_mask_ = context_types; - log::debug( - "group id: {}, allowed contexts sink: {}, allowed contexts source: " - "{}", - group_id_, group_user_allowed_context_mask_.sink.to_string(), - group_user_allowed_context_mask_.source.to_string()); + log::debug("group id: {}, allowed contexts sink: {}, allowed contexts source: {}", group_id_, + group_user_allowed_context_mask_.sink.to_string(), + group_user_allowed_context_mask_.source.to_string()); } - types::AudioContexts GetAllowedContextMask( - int direction = types::kLeAudioDirectionBoth) const { - log::assert_that(direction <= (types::kLeAudioDirectionBoth), - "Invalid direction used."); + types::AudioContexts GetAllowedContextMask(int direction = types::kLeAudioDirectionBoth) const { + log::assert_that(direction <= (types::kLeAudioDirectionBoth), "Invalid direction used."); if (direction < types::kLeAudioDirectionBoth) { - log::debug( - "group id: {}, allowed contexts sink: {}, allowed contexts " - "source: {}", - group_id_, group_user_allowed_context_mask_.sink.to_string(), - group_user_allowed_context_mask_.source.to_string()); + log::debug("group id: {}, allowed contexts sink: {}, allowed contexts source: {}", group_id_, + group_user_allowed_context_mask_.sink.to_string(), + group_user_allowed_context_mask_.source.to_string()); return group_user_allowed_context_mask_.get(direction); } else { return types::get_bidirectional(group_user_allowed_context_mask_); } } - types::AudioContexts GetSupportedContexts( - int direction = types::kLeAudioDirectionBoth) const; + types::AudioContexts GetSupportedContexts(int direction = types::kLeAudioDirectionBoth) const; DsaModes GetAllowedDsaModes() { if (!com::android::bluetooth::flags::leaudio_dynamic_spatial_audio()) { @@ -381,7 +347,9 @@ class LeAudioDeviceGroup { std::set dsa_mode_set{}; for (auto leAudioDevice : leAudioDevices_) { - if (leAudioDevice.expired()) continue; + if (leAudioDevice.expired()) { + continue; + } auto device_dsa_modes = leAudioDevice.lock()->GetDsaModes(); @@ -406,8 +374,7 @@ class LeAudioDeviceGroup { return dsa_modes_list; } - types::BidirectionalPair GetLatestAvailableContexts( - void) const; + types::BidirectionalPair GetLatestAvailableContexts(void) const; bool IsInTransition(void) const; bool IsStreaming(void) const; @@ -423,27 +390,23 @@ class LeAudioDeviceGroup { * configurations. This will not be used for finding best possible vendor * codec configuration. */ - const set_configurations::AudioSetConfiguration* - FindFirstSupportedConfiguration( - const CodecManager::UnicastConfigurationRequirements& requirements, - const set_configurations::AudioSetConfigurations* confs) const; + const set_configurations::AudioSetConfiguration* FindFirstSupportedConfiguration( + const CodecManager::UnicastConfigurationRequirements& requirements, + const set_configurations::AudioSetConfigurations* confs) const; - private: +private: bool is_enabled_; uint32_t transport_latency_mtos_us_; uint32_t transport_latency_stom_us_; - bool ConfigureAses( - const set_configurations::AudioSetConfiguration* audio_set_conf, - types::LeAudioContextType context_type, - const types::BidirectionalPair& - metadata_context_types, - const types::BidirectionalPair>& ccid_lists); + bool ConfigureAses(const set_configurations::AudioSetConfiguration* audio_set_conf, + types::LeAudioContextType context_type, + const types::BidirectionalPair& metadata_context_types, + const types::BidirectionalPair>& ccid_lists); bool IsAudioSetConfigurationSupported( - const CodecManager::UnicastConfigurationRequirements& requirements, - const set_configurations::AudioSetConfiguration* audio_set_configuration) - const; + const CodecManager::UnicastConfigurationRequirements& requirements, + const set_configurations::AudioSetConfiguration* audio_set_configuration) const; uint32_t GetTransportLatencyUs(uint8_t direction) const; bool IsCisPartOfCurrentStream(uint16_t cis_conn_hdl) const; @@ -466,18 +429,16 @@ class LeAudioDeviceGroup { /* Mask of currently allowed context types. Not set a value not set will * result in streaming rejection. */ - types::BidirectionalPair - group_user_allowed_context_mask_; + types::BidirectionalPair group_user_allowed_context_mask_; /* Possible configuration cache - refreshed on each group context availability * change. Stored as a pair of (is_valid_cache, configuration*). `pair.first` * being `false` means that the cached value should be refreshed. */ mutable std::map< - types::LeAudioContextType, - std::pair>> - context_to_configuration_cache_map; + types::LeAudioContextType, + std::pair>> + context_to_configuration_cache_map; types::AseState target_state_; types::AseState current_state_; @@ -490,7 +451,7 @@ class LeAudioDeviceGroup { * (vector container) using determinants like id. */ class LeAudioDeviceGroups { - public: +public: LeAudioDeviceGroup* Add(int group_id); void Remove(const int group_id); LeAudioDeviceGroup* FindById(int group_id) const; @@ -500,7 +461,7 @@ class LeAudioDeviceGroups { void Cleanup(void); void Dump(int fd, int active_group_id) const; - private: +private: std::vector> groups_; }; diff --git a/system/bta/le_audio/devices.cc b/system/bta/le_audio/devices.cc index 55a13817c3e..298e8d90e4c 100644 --- a/system/bta/le_audio/devices.cc +++ b/system/bta/le_audio/devices.cc @@ -83,8 +83,7 @@ std::ostream& operator<<(std::ostream& os, const DeviceConnectState& state) { break; } - os << char_value_ << " (" - << "0x" << std::setfill('0') << std::setw(2) << static_cast(state) + os << char_value_ << " (" << "0x" << std::setfill('0') << std::setw(2) << static_cast(state) << ")"; return os; } @@ -92,35 +91,45 @@ std::ostream& operator<<(std::ostream& os, const DeviceConnectState& state) { static uint32_t GetFirstLeft(const AudioLocations& audio_locations) { uint32_t audio_location_ulong = audio_locations.to_ulong(); - if (audio_location_ulong & codec_spec_conf::kLeAudioLocationFrontLeft) + if (audio_location_ulong & codec_spec_conf::kLeAudioLocationFrontLeft) { return codec_spec_conf::kLeAudioLocationFrontLeft; + } - if (audio_location_ulong & codec_spec_conf::kLeAudioLocationBackLeft) + if (audio_location_ulong & codec_spec_conf::kLeAudioLocationBackLeft) { return codec_spec_conf::kLeAudioLocationBackLeft; + } - if (audio_location_ulong & codec_spec_conf::kLeAudioLocationFrontLeftOfCenter) + if (audio_location_ulong & codec_spec_conf::kLeAudioLocationFrontLeftOfCenter) { return codec_spec_conf::kLeAudioLocationFrontLeftOfCenter; + } - if (audio_location_ulong & codec_spec_conf::kLeAudioLocationSideLeft) + if (audio_location_ulong & codec_spec_conf::kLeAudioLocationSideLeft) { return codec_spec_conf::kLeAudioLocationSideLeft; + } - if (audio_location_ulong & codec_spec_conf::kLeAudioLocationTopFrontLeft) + if (audio_location_ulong & codec_spec_conf::kLeAudioLocationTopFrontLeft) { return codec_spec_conf::kLeAudioLocationTopFrontLeft; + } - if (audio_location_ulong & codec_spec_conf::kLeAudioLocationTopBackLeft) + if (audio_location_ulong & codec_spec_conf::kLeAudioLocationTopBackLeft) { return codec_spec_conf::kLeAudioLocationTopBackLeft; + } - if (audio_location_ulong & codec_spec_conf::kLeAudioLocationTopSideLeft) + if (audio_location_ulong & codec_spec_conf::kLeAudioLocationTopSideLeft) { return codec_spec_conf::kLeAudioLocationTopSideLeft; + } - if (audio_location_ulong & codec_spec_conf::kLeAudioLocationBottomFrontLeft) + if (audio_location_ulong & codec_spec_conf::kLeAudioLocationBottomFrontLeft) { return codec_spec_conf::kLeAudioLocationBottomFrontLeft; + } - if (audio_location_ulong & codec_spec_conf::kLeAudioLocationFrontLeftWide) + if (audio_location_ulong & codec_spec_conf::kLeAudioLocationFrontLeftWide) { return codec_spec_conf::kLeAudioLocationFrontLeftWide; + } - if (audio_location_ulong & codec_spec_conf::kLeAudioLocationLeftSurround) + if (audio_location_ulong & codec_spec_conf::kLeAudioLocationLeftSurround) { return codec_spec_conf::kLeAudioLocationLeftSurround; + } return 0; } @@ -128,36 +137,45 @@ static uint32_t GetFirstLeft(const AudioLocations& audio_locations) { static uint32_t GetFirstRight(const AudioLocations& audio_locations) { uint32_t audio_location_ulong = audio_locations.to_ulong(); - if (audio_location_ulong & codec_spec_conf::kLeAudioLocationFrontRight) + if (audio_location_ulong & codec_spec_conf::kLeAudioLocationFrontRight) { return codec_spec_conf::kLeAudioLocationFrontRight; + } - if (audio_location_ulong & codec_spec_conf::kLeAudioLocationBackRight) + if (audio_location_ulong & codec_spec_conf::kLeAudioLocationBackRight) { return codec_spec_conf::kLeAudioLocationBackRight; + } - if (audio_location_ulong & - codec_spec_conf::kLeAudioLocationFrontRightOfCenter) + if (audio_location_ulong & codec_spec_conf::kLeAudioLocationFrontRightOfCenter) { return codec_spec_conf::kLeAudioLocationFrontRightOfCenter; + } - if (audio_location_ulong & codec_spec_conf::kLeAudioLocationSideRight) + if (audio_location_ulong & codec_spec_conf::kLeAudioLocationSideRight) { return codec_spec_conf::kLeAudioLocationSideRight; + } - if (audio_location_ulong & codec_spec_conf::kLeAudioLocationTopFrontRight) + if (audio_location_ulong & codec_spec_conf::kLeAudioLocationTopFrontRight) { return codec_spec_conf::kLeAudioLocationTopFrontRight; + } - if (audio_location_ulong & codec_spec_conf::kLeAudioLocationTopBackRight) + if (audio_location_ulong & codec_spec_conf::kLeAudioLocationTopBackRight) { return codec_spec_conf::kLeAudioLocationTopBackRight; + } - if (audio_location_ulong & codec_spec_conf::kLeAudioLocationTopSideRight) + if (audio_location_ulong & codec_spec_conf::kLeAudioLocationTopSideRight) { return codec_spec_conf::kLeAudioLocationTopSideRight; + } - if (audio_location_ulong & codec_spec_conf::kLeAudioLocationBottomFrontRight) + if (audio_location_ulong & codec_spec_conf::kLeAudioLocationBottomFrontRight) { return codec_spec_conf::kLeAudioLocationBottomFrontRight; + } - if (audio_location_ulong & codec_spec_conf::kLeAudioLocationFrontRightWide) + if (audio_location_ulong & codec_spec_conf::kLeAudioLocationFrontRightWide) { return codec_spec_conf::kLeAudioLocationFrontRightWide; + } - if (audio_location_ulong & codec_spec_conf::kLeAudioLocationRightSurround) + if (audio_location_ulong & codec_spec_conf::kLeAudioLocationRightSurround) { return codec_spec_conf::kLeAudioLocationRightSurround; + } return 0; } @@ -165,14 +183,13 @@ static uint32_t GetFirstRight(const AudioLocations& audio_locations) { uint32_t PickAudioLocation(types::LeAudioConfigurationStrategy strategy, const AudioLocations& device_locations, AudioLocations& group_locations) { - log::debug("strategy: {}, locations: 0x{:x}, input group locations: 0x{:x}", - (int)strategy, device_locations.to_ulong(), - group_locations.to_ulong()); + log::debug("strategy: {}, locations: 0x{:x}, input group locations: 0x{:x}", (int)strategy, + device_locations.to_ulong(), group_locations.to_ulong()); auto is_left_not_yet_assigned = - !(group_locations.to_ulong() & codec_spec_conf::kLeAudioLocationAnyLeft); + !(group_locations.to_ulong() & codec_spec_conf::kLeAudioLocationAnyLeft); auto is_right_not_yet_assigned = - !(group_locations.to_ulong() & codec_spec_conf::kLeAudioLocationAnyRight); + !(group_locations.to_ulong() & codec_spec_conf::kLeAudioLocationAnyRight); uint32_t left_device_loc = GetFirstLeft(device_locations); uint32_t right_device_loc = GetFirstRight(device_locations); @@ -206,9 +223,9 @@ uint32_t PickAudioLocation(types::LeAudioConfigurationStrategy strategy, } log::error( - "Can't find device for left/right channel. Strategy: {}, " - "device_locations: {:x}, output group_locations: {:x}.", - strategy, device_locations.to_ulong(), group_locations.to_ulong()); + "Can't find device for left/right channel. Strategy: {}, " + "device_locations: {:x}, output group_locations: {:x}.", + strategy, device_locations.to_ulong(), group_locations.to_ulong()); /* Return either any left or any right audio location. It might result with * multiple devices within the group having the same location. @@ -217,17 +234,18 @@ uint32_t PickAudioLocation(types::LeAudioConfigurationStrategy strategy, } bool LeAudioDevice::IsAudioSetConfigurationSupported( - const set_configurations::AudioSetConfiguration* audio_set_conf) const { - for (auto direction : {le_audio::types::kLeAudioDirectionSink, - le_audio::types::kLeAudioDirectionSource}) { + const set_configurations::AudioSetConfiguration* audio_set_conf) const { + for (auto direction : + {le_audio::types::kLeAudioDirectionSink, le_audio::types::kLeAudioDirectionSource}) { const auto& confs = audio_set_conf->confs.get(direction); - if (confs.size() == 0) continue; + if (confs.size() == 0) { + continue; + } log::info("Looking for requirements: {} - {}", audio_set_conf->name, direction == 1 ? "snk" : "src"); - auto const& pacs = - (direction == types::kLeAudioDirectionSink) ? snk_pacs_ : src_pacs_; + auto const& pacs = (direction == types::kLeAudioDirectionSink) ? snk_pacs_ : src_pacs_; for (const auto& ent : confs) { if (!utils::GetConfigurationSupportedPac(pacs, ent.codec)) { log::info("Configuration is NOT supported by device {}", address_); @@ -240,13 +258,13 @@ bool LeAudioDevice::IsAudioSetConfigurationSupported( return true; } -bool LeAudioDevice::ConfigureAses( - const set_configurations::AudioSetConfiguration* audio_set_conf, - uint8_t num_of_devices, uint8_t direction, LeAudioContextType context_type, - uint8_t* number_of_already_active_group_ase, - AudioLocations& group_audio_locations_memo, - const AudioContexts& metadata_context_types, - const std::vector& ccid_lists, bool reuse_cis_id) { +bool LeAudioDevice::ConfigureAses(const set_configurations::AudioSetConfiguration* audio_set_conf, + uint8_t num_of_devices, uint8_t direction, + LeAudioContextType context_type, + uint8_t* number_of_already_active_group_ase, + AudioLocations& group_audio_locations_memo, + const AudioContexts& metadata_context_types, + const std::vector& ccid_lists, bool reuse_cis_id) { /* First try to use the already configured ASE */ auto ase = GetFirstActiveAseByDirection(direction); if (ase) { @@ -261,15 +279,13 @@ bool LeAudioDevice::ConfigureAses( return false; } - auto audio_locations = (direction == types::kLeAudioDirectionSink) - ? snk_audio_locations_ - : src_audio_locations_; + auto audio_locations = + (direction == types::kLeAudioDirectionSink) ? snk_audio_locations_ : src_audio_locations_; auto const& group_ase_configs = audio_set_conf->confs.get(direction); std::vector ase_configs; std::copy_if(group_ase_configs.cbegin(), group_ase_configs.cend(), - std::back_inserter(ase_configs), - [&audio_locations](auto const& cfg) { + std::back_inserter(ase_configs), [&audio_locations](auto const& cfg) { /* Pass as matching if config has no allocation to match * (the legacy json config provider). Otherwise, with the codec * extensibility feature enabled, we receive ASE configurations @@ -278,16 +294,16 @@ bool LeAudioDevice::ConfigureAses( * particular device. */ auto config = cfg.codec.params.GetAsCoreCodecConfig(); - if (!config.audio_channel_allocation.has_value()) return true; + if (!config.audio_channel_allocation.has_value()) { + return true; + } // Filter-out not matching audio locations - return (cfg.codec.params.GetAsCoreCodecConfig() - .audio_channel_allocation.value() & + return (cfg.codec.params.GetAsCoreCodecConfig().audio_channel_allocation.value() & audio_locations.to_ulong()) != 0; }); - auto const& pacs = - (direction == types::kLeAudioDirectionSink) ? snk_pacs_ : src_pacs_; + auto const& pacs = (direction == types::kLeAudioDirectionSink) ? snk_pacs_ : src_pacs_; for (size_t i = 0; i < ase_configs.size() && ase; ++i) { auto const& ase_cfg = ase_configs.at(i); if (utils::IsCodecUsingLtvFormat(ase_cfg.codec.id) && @@ -306,10 +322,9 @@ bool LeAudioDevice::ConfigureAses( // Before we activate the ASEs, make sure we have the right configuration // Check for matching PACs only if we know that the LTV format is being used. - uint8_t max_required_ase_per_dev = ase_configs.size() / num_of_devices + - (ase_configs.size() % num_of_devices); - int needed_ase = - std::min((int)(max_required_ase_per_dev), (int)(ase_configs.size())); + uint8_t max_required_ase_per_dev = + ase_configs.size() / num_of_devices + (ase_configs.size() % num_of_devices); + int needed_ase = std::min((int)(max_required_ase_per_dev), (int)(ase_configs.size())); for (int i = 0; i < needed_ase; ++i) { auto const& ase_cfg = ase_configs.at(i); @@ -320,20 +335,17 @@ bool LeAudioDevice::ConfigureAses( } } - auto strategy = - utils::GetStrategyForAseConfig(group_ase_configs, num_of_devices); + auto strategy = utils::GetStrategyForAseConfig(group_ase_configs, num_of_devices); // Make sure we configure a single microphone if Dual Bidir SWB is not // supported. if (direction == types::kLeAudioDirectionSource && - !CodecManager::GetInstance()->IsDualBiDirSwbSupported() && - (active_ases != 0)) { - if (CodecManager::GetInstance()->CheckCodecConfigIsDualBiDirSwb( - *audio_set_conf)) { + !CodecManager::GetInstance()->IsDualBiDirSwbSupported() && (active_ases != 0)) { + if (CodecManager::GetInstance()->CheckCodecConfigIsDualBiDirSwb(*audio_set_conf)) { log::error( - "{}, trying to configure the dual bidir SWB, but the feature is " - "disabled. This should not happen! Skipping ASE activation.", - address_); + "{}, trying to configure the dual bidir SWB, but the feature is " + "disabled. This should not happen! Skipping ASE activation.", + address_); return true; } } @@ -351,8 +363,9 @@ bool LeAudioDevice::ConfigureAses( * Nothing more to do is needed here. */ if (ase->state != AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) { - if (ase->state == AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED) + if (ase->state == AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED) { ase->reconfigure = true; + } ase->target_latency = ase_cfg.qos.target_latency; ase->codec_id = ase_cfg.codec.id; @@ -362,19 +375,16 @@ bool LeAudioDevice::ConfigureAses( /* Let's choose audio channel allocation if not set */ ase->codec_config.Add( - codec_spec_conf::kLeAudioLtvTypeAudioChannelAllocation, - PickAudioLocation(strategy, audio_locations, - group_audio_locations_memo)); + codec_spec_conf::kLeAudioLtvTypeAudioChannelAllocation, + PickAudioLocation(strategy, audio_locations, group_audio_locations_memo)); /* Get default value if no requirement for specific frame blocks per sdu */ if (utils::IsCodecUsingLtvFormat(ase->codec_id) && - !ase->codec_config.Find( - codec_spec_conf::kLeAudioLtvTypeCodecFrameBlocksPerSdu)) { - ase->codec_config.Add( - codec_spec_conf::kLeAudioLtvTypeCodecFrameBlocksPerSdu, - GetMaxCodecFramesPerSduFromPac( - utils::GetConfigurationSupportedPac(pacs, ase_cfg.codec))); + !ase->codec_config.Find(codec_spec_conf::kLeAudioLtvTypeCodecFrameBlocksPerSdu)) { + ase->codec_config.Add(codec_spec_conf::kLeAudioLtvTypeCodecFrameBlocksPerSdu, + GetMaxCodecFramesPerSduFromPac( + utils::GetConfigurationSupportedPac(pacs, ase_cfg.codec))); } ase->qos_config.sdu_interval = ase_cfg.qos.sduIntervalUs; @@ -386,10 +396,10 @@ bool LeAudioDevice::ConfigureAses( } log::debug( - "device={}, activated ASE id={}, direction={}, max_sdu_size={}, " - "cis_id={}, target_latency={}", - address_, ase->id, direction == 1 ? "snk" : "src", - ase->qos_config.max_sdu_size, ase->cis_id, ase_cfg.qos.target_latency); + "device={}, activated ASE id={}, direction={}, max_sdu_size={}, " + "cis_id={}, target_latency={}", + address_, ase->id, direction == 1 ? "snk" : "src", ase->qos_config.max_sdu_size, + ase->cis_id, ase_cfg.qos.target_latency); /* Try to use the already active ASE */ ase = GetNextActiveAseWithSameDirection(ase); @@ -404,19 +414,15 @@ bool LeAudioDevice::ConfigureAses( /* LeAudioDevice Class methods implementation */ void LeAudioDevice::SetConnectionState(DeviceConnectState state) { - log::debug("{}, {} --> {}", address_, - bluetooth::common::ToString(connection_state_), + log::debug("{}, {} --> {}", address_, bluetooth::common::ToString(connection_state_), bluetooth::common::ToString(state)); - LeAudioLogHistory::Get()->AddLogHistory( - kLogConnectionTag, group_id_, address_, - bluetooth::common::ToString(connection_state_) + " -> ", - "->" + bluetooth::common::ToString(state)); + LeAudioLogHistory::Get()->AddLogHistory(kLogConnectionTag, group_id_, address_, + bluetooth::common::ToString(connection_state_) + " -> ", + "->" + bluetooth::common::ToString(state)); connection_state_ = state; } -DeviceConnectState LeAudioDevice::GetConnectionState(void) { - return connection_state_; -} +DeviceConnectState LeAudioDevice::GetConnectionState(void) { return connection_state_; } void LeAudioDevice::ClearPACs(void) { snk_pacs_.clear(); @@ -428,8 +434,7 @@ LeAudioDevice::~LeAudioDevice(void) { this->ClearPACs(); } -void LeAudioDevice::ParseHeadtrackingCodec( - const struct types::acs_ac_record& pac) { +void LeAudioDevice::ParseHeadtrackingCodec(const struct types::acs_ac_record& pac) { if (!com::android::bluetooth::flags::leaudio_dynamic_spatial_audio()) { return; } @@ -439,9 +444,9 @@ void LeAudioDevice::ParseHeadtrackingCodec( // Assume LE-ISO is supported if metadata is not available dsa_.modes = { - DsaMode::DISABLED, - DsaMode::ISO_SW, - DsaMode::ISO_HW, + DsaMode::DISABLED, + DsaMode::ISO_SW, + DsaMode::ISO_HW, }; if (!com::android::bluetooth::flags::headtracker_codec_capability()) { @@ -479,14 +484,12 @@ void LeAudioDevice::ParseHeadtrackingCodec( uint8_t supported_transports = ltv[6]; DsaModes dsa_modes = {DsaMode::DISABLED}; - if ((supported_transports & - types::kLeAudioMetadataHeadtrackerTransportLeAcl) != 0) { + if ((supported_transports & types::kLeAudioMetadataHeadtrackerTransportLeAcl) != 0) { log::debug("{}, headtracking supported over LE-ACL", address_); dsa_modes.push_back(DsaMode::ACL); } - if ((supported_transports & - types::kLeAudioMetadataHeadtrackerTransportLeIso) != 0) { + if ((supported_transports & types::kLeAudioMetadataHeadtrackerTransportLeIso) != 0) { log::debug("{}, headtracking supported over LE-ISO", address_); dsa_modes.push_back(DsaMode::ISO_SW); dsa_modes.push_back(DsaMode::ISO_HW); @@ -496,9 +499,8 @@ void LeAudioDevice::ParseHeadtrackingCodec( } } -void LeAudioDevice::RegisterPACs( - std::vector* pac_db, - std::vector* pac_recs) { +void LeAudioDevice::RegisterPACs(std::vector* pac_db, + std::vector* pac_recs) { /* Clear PAC database for characteristic in case if re-read, indicated */ if (!pac_db->empty()) { log::debug("{}, upgrade PACs for characteristic", address_); @@ -510,22 +512,16 @@ void LeAudioDevice::RegisterPACs( /* TODO wrap this logging part with debug flag */ for (const struct types::acs_ac_record& pac : *pac_recs) { std::stringstream debug_str; - debug_str << "Registering PAC" - << "\n\tCoding format: " << loghex(pac.codec_id.coding_format) - << "\n\tVendor codec company ID: " - << loghex(pac.codec_id.vendor_company_id) + debug_str << "Registering PAC" << "\n\tCoding format: " << loghex(pac.codec_id.coding_format) + << "\n\tVendor codec company ID: " << loghex(pac.codec_id.vendor_company_id) << "\n\tVendor codec ID: " << loghex(pac.codec_id.vendor_codec_id) << "\n\tCodec spec caps:\n"; - if (utils::IsCodecUsingLtvFormat(pac.codec_id) && - !pac.codec_spec_caps.IsEmpty()) { - debug_str << pac.codec_spec_caps.ToString( - "", types::CodecCapabilitiesLtvFormat); + if (utils::IsCodecUsingLtvFormat(pac.codec_id) && !pac.codec_spec_caps.IsEmpty()) { + debug_str << pac.codec_spec_caps.ToString("", types::CodecCapabilitiesLtvFormat); } else { - debug_str << base::HexEncode(pac.codec_spec_caps_raw.data(), - pac.codec_spec_caps_raw.size()); + debug_str << base::HexEncode(pac.codec_spec_caps_raw.data(), pac.codec_spec_caps_raw.size()); } - debug_str << "\n\tMetadata: " - << base::HexEncode(pac.metadata.data(), pac.metadata.size()); + debug_str << "\n\tMetadata: " << base::HexEncode(pac.metadata.data(), pac.metadata.size()); log::debug("{}", debug_str.str()); ParseHeadtrackingCodec(pac); @@ -535,78 +531,68 @@ void LeAudioDevice::RegisterPACs( } struct ase* LeAudioDevice::GetAseByValHandle(uint16_t val_hdl) { - auto iter = std::find_if( - ases_.begin(), ases_.end(), - [&val_hdl](const auto& ase) { return ase.hdls.val_hdl == val_hdl; }); + auto iter = std::find_if(ases_.begin(), ases_.end(), + [&val_hdl](const auto& ase) { return ase.hdls.val_hdl == val_hdl; }); return (iter == ases_.end()) ? nullptr : &(*iter); } int LeAudioDevice::GetAseCount(uint8_t direction) { - return std::count_if(ases_.begin(), ases_.end(), [direction](const auto& a) { - return a.direction == direction; - }); + return std::count_if(ases_.begin(), ases_.end(), + [direction](const auto& a) { return a.direction == direction; }); } -struct ase* LeAudioDevice::GetFirstAseWithState(uint8_t direction, - AseState state) { - auto iter = std::find_if( - ases_.begin(), ases_.end(), [direction, state](const auto& ase) { - return ((ase.direction == direction) && (ase.state == state)); - }); +struct ase* LeAudioDevice::GetFirstAseWithState(uint8_t direction, AseState state) { + auto iter = std::find_if(ases_.begin(), ases_.end(), [direction, state](const auto& ase) { + return (ase.direction == direction) && (ase.state == state); + }); return (iter == ases_.end()) ? nullptr : &(*iter); } struct ase* LeAudioDevice::GetFirstActiveAse(void) { - auto iter = std::find_if(ases_.begin(), ases_.end(), - [](const auto& ase) { return ase.active; }); + auto iter = std::find_if(ases_.begin(), ases_.end(), [](const auto& ase) { return ase.active; }); return (iter == ases_.end()) ? nullptr : &(*iter); } struct ase* LeAudioDevice::GetFirstActiveAseByDirection(uint8_t direction) { - auto iter = - std::find_if(ases_.begin(), ases_.end(), [direction](const auto& ase) { - return (ase.active && (ase.direction == direction)); - }); + auto iter = std::find_if(ases_.begin(), ases_.end(), [direction](const auto& ase) { + return ase.active && (ase.direction == direction); + }); return (iter == ases_.end()) ? nullptr : &(*iter); } -struct ase* LeAudioDevice::GetNextActiveAseWithSameDirection( - struct ase* base_ase) { +struct ase* LeAudioDevice::GetNextActiveAseWithSameDirection(struct ase* base_ase) { auto iter = std::find_if(ases_.begin(), ases_.end(), [&base_ase](auto& ase) { return base_ase == &ase; }); /* Invalid ase given */ - if (iter == ases_.end() || std::distance(iter, ases_.end()) < 1) + if (iter == ases_.end() || std::distance(iter, ases_.end()) < 1) { return nullptr; + } - iter = - std::find_if(std::next(iter, 1), ases_.end(), [&iter](const auto& ase) { - return ase.active && (*iter).direction == ase.direction; - }); + iter = std::find_if(std::next(iter, 1), ases_.end(), [&iter](const auto& ase) { + return ase.active && (*iter).direction == ase.direction; + }); return (iter == ases_.end()) ? nullptr : &(*iter); } -struct ase* LeAudioDevice::GetNextActiveAseWithDifferentDirection( - struct ase* base_ase) { +struct ase* LeAudioDevice::GetNextActiveAseWithDifferentDirection(struct ase* base_ase) { auto iter = std::find_if(ases_.begin(), ases_.end(), [&base_ase](auto& ase) { return base_ase == &ase; }); /* Invalid ase given */ if (std::distance(iter, ases_.end()) < 1) { - log::debug("{}, ASE {} does not use bidirectional CIS", address_, - base_ase->id); + log::debug("{}, ASE {} does not use bidirectional CIS", address_, base_ase->id); return nullptr; } - iter = - std::find_if(std::next(iter, 1), ases_.end(), [&iter](const auto& ase) { - return ase.active && iter->direction != ase.direction; - }); + iter = std::find_if(std::next(iter, 1), ases_.end(), [&iter](const auto& ase) { + return ase.active && iter->direction != ase.direction; + }); if (iter == ases_.end()) { return nullptr; @@ -615,44 +601,48 @@ struct ase* LeAudioDevice::GetNextActiveAseWithDifferentDirection( return &(*iter); } -struct ase* LeAudioDevice::GetFirstActiveAseByCisAndDataPathState( - CisState cis_state, DataPathState data_path_state) { - auto iter = std::find_if(ases_.begin(), ases_.end(), - [cis_state, data_path_state](const auto& ase) { - return (ase.active && - (ase.data_path_state == data_path_state) && - (ase.cis_state == cis_state)); - }); +struct ase* LeAudioDevice::GetFirstActiveAseByCisAndDataPathState(CisState cis_state, + DataPathState data_path_state) { + auto iter = + std::find_if(ases_.begin(), ases_.end(), [cis_state, data_path_state](const auto& ase) { + return ase.active && (ase.data_path_state == data_path_state) && + (ase.cis_state == cis_state); + }); return (iter == ases_.end()) ? nullptr : &(*iter); } -struct ase* LeAudioDevice::GetFirstInactiveAse(uint8_t direction, - bool reuse_cis_id) { - auto iter = std::find_if(ases_.begin(), ases_.end(), - [direction, reuse_cis_id](const auto& ase) { - if (ase.active || (ase.direction != direction)) - return false; +struct ase* LeAudioDevice::GetFirstInactiveAse(uint8_t direction, bool reuse_cis_id) { + auto iter = std::find_if(ases_.begin(), ases_.end(), [direction, reuse_cis_id](const auto& ase) { + if (ase.active || (ase.direction != direction)) { + return false; + } - if (!reuse_cis_id) return true; + if (!reuse_cis_id) { + return true; + } - return (ase.cis_id != kInvalidCisId); - }); + return ase.cis_id != kInvalidCisId; + }); /* If ASE is found, return it */ - if (iter != ases_.end()) return &(*iter); + if (iter != ases_.end()) { + return &(*iter); + } /* If reuse was not set, that means there is no inactive ASE available. */ - if (!reuse_cis_id) return nullptr; + if (!reuse_cis_id) { + return nullptr; + } /* Since there is no ASE with assigned CIS ID, it means new configuration * needs more ASEs then it was configured before. * Let's find just inactive one */ - iter = std::find_if(ases_.begin(), ases_.end(), - [direction](const auto& ase) { - if (ase.active || (ase.direction != direction)) - return false; - return true; - }); + iter = std::find_if(ases_.begin(), ases_.end(), [direction](const auto& ase) { + if (ase.active || (ase.direction != direction)) { + return false; + } + return true; + }); return (iter == ases_.end()) ? nullptr : &(*iter); } @@ -662,25 +652,23 @@ struct ase* LeAudioDevice::GetNextActiveAse(struct ase* base_ase) { [&base_ase](auto& ase) { return base_ase == &ase; }); /* Invalid ase given */ - if (iter == ases_.end() || std::distance(iter, ases_.end()) < 1) + if (iter == ases_.end() || std::distance(iter, ases_.end()) < 1) { return nullptr; + } - iter = std::find_if(std::next(iter, 1), ases_.end(), - [](const auto& ase) { return ase.active; }); + iter = std::find_if(std::next(iter, 1), ases_.end(), [](const auto& ase) { return ase.active; }); return (iter == ases_.end()) ? nullptr : &(*iter); } struct ase* LeAudioDevice::GetAseToMatchBidirectionCis(struct ase* base_ase) { auto iter = std::find_if(ases_.begin(), ases_.end(), [&base_ase](auto& ase) { - return (base_ase->cis_conn_hdl == ase.cis_conn_hdl) && - (base_ase->direction != ase.direction); + return (base_ase->cis_conn_hdl == ase.cis_conn_hdl) && (base_ase->direction != ase.direction); }); return (iter == ases_.end()) ? nullptr : &(*iter); } -BidirectionalPair LeAudioDevice::GetAsesByCisConnHdl( - uint16_t conn_hdl) { +BidirectionalPair LeAudioDevice::GetAsesByCisConnHdl(uint16_t conn_hdl) { BidirectionalPair ases = {nullptr, nullptr}; for (auto& ase : ases_) { @@ -713,8 +701,7 @@ BidirectionalPair LeAudioDevice::GetAsesByCisId(uint8_t cis_id) { } bool LeAudioDevice::HaveActiveAse(void) { - auto iter = std::find_if(ases_.begin(), ases_.end(), - [](const auto& ase) { return ase.active; }); + auto iter = std::find_if(ases_.begin(), ases_.end(), [](const auto& ase) { return ase.active; }); return iter != ases_.end(); } @@ -734,9 +721,13 @@ bool LeAudioDevice::HaveAnyReleasingAse(void) { bool LeAudioDevice::HaveAnyStreamingAses(void) { /* In configuring state when active in Idle or Configured and reconfigure */ auto iter = std::find_if(ases_.begin(), ases_.end(), [](const auto& ase) { - if (!ase.active) return false; + if (!ase.active) { + return false; + } - if (ase.state == AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) return true; + if (ase.state == AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) { + return true; + } return false; }); @@ -747,12 +738,14 @@ bool LeAudioDevice::HaveAnyStreamingAses(void) { bool LeAudioDevice::HaveAnyUnconfiguredAses(void) { /* In configuring state when active in Idle or Configured and reconfigure */ auto iter = std::find_if(ases_.begin(), ases_.end(), [](const auto& ase) { - if (!ase.active) return false; + if (!ase.active) { + return false; + } if (ase.state == AseState::BTA_LE_AUDIO_ASE_STATE_IDLE || - ((ase.state == AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED) && - ase.reconfigure)) + ((ase.state == AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED) && ase.reconfigure)) { return true; + } return false; }); @@ -762,25 +755,22 @@ bool LeAudioDevice::HaveAnyUnconfiguredAses(void) { bool LeAudioDevice::HaveAllActiveAsesSameState(AseState state) { log::verbose("{}", address_); - auto iter = - std::find_if(ases_.begin(), ases_.end(), [&state](const auto& ase) { - log::verbose("ASE id: {}, active: {}, state: {}", ase.id, ase.active, - bluetooth::common::ToString(ase.state)); - return ase.active && (ase.state != state); - }); + auto iter = std::find_if(ases_.begin(), ases_.end(), [&state](const auto& ase) { + log::verbose("ASE id: {}, active: {}, state: {}", ase.id, ase.active, + bluetooth::common::ToString(ase.state)); + return ase.active && (ase.state != state); + }); return iter == ases_.end(); } -bool LeAudioDevice::HaveAllActiveAsesSameDataPathState( - types::DataPathState state) const { +bool LeAudioDevice::HaveAllActiveAsesSameDataPathState(types::DataPathState state) const { log::verbose("{}", address_); - auto iter = - std::find_if(ases_.begin(), ases_.end(), [&state](const auto& ase) { - log::verbose("ASE id: {}, active: {}, state: {}", ase.id, ase.active, - bluetooth::common::ToString(ase.data_path_state)); - return ase.active && (ase.data_path_state != state); - }); + auto iter = std::find_if(ases_.begin(), ases_.end(), [&state](const auto& ase) { + log::verbose("ASE id: {}, active: {}, state: {}", ase.id, ase.active, + bluetooth::common::ToString(ase.data_path_state)); + return ase.active && (ase.data_path_state != state); + }); return iter == ases_.end(); } @@ -788,18 +778,22 @@ bool LeAudioDevice::HaveAllActiveAsesSameDataPathState( bool LeAudioDevice::IsReadyToCreateStream(void) { log::verbose("{}", address_); auto iter = std::find_if(ases_.begin(), ases_.end(), [](const auto& ase) { - if (!ase.active) return false; + if (!ase.active) { + return false; + } log::verbose("ASE id: {}, state: {}, direction: {}", ase.id, bluetooth::common::ToString(ase.state), ase.direction); if (ase.direction == types::kLeAudioDirectionSink && (ase.state != AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING && - ase.state != AseState::BTA_LE_AUDIO_ASE_STATE_ENABLING)) + ase.state != AseState::BTA_LE_AUDIO_ASE_STATE_ENABLING)) { return true; + } if (ase.direction == types::kLeAudioDirectionSource && - ase.state != AseState::BTA_LE_AUDIO_ASE_STATE_ENABLING) + ase.state != AseState::BTA_LE_AUDIO_ASE_STATE_ENABLING) { return true; + } return false; }); @@ -809,15 +803,19 @@ bool LeAudioDevice::IsReadyToCreateStream(void) { bool LeAudioDevice::IsReadyToSuspendStream(void) { auto iter = std::find_if(ases_.begin(), ases_.end(), [](const auto& ase) { - if (!ase.active) return false; + if (!ase.active) { + return false; + } if (ase.direction == types::kLeAudioDirectionSink && - ase.state != AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED) + ase.state != AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED) { return true; + } if (ase.direction == types::kLeAudioDirectionSource && - ase.state != AseState::BTA_LE_AUDIO_ASE_STATE_DISABLING) + ase.state != AseState::BTA_LE_AUDIO_ASE_STATE_DISABLING) { return true; + } return false; }); @@ -853,8 +851,7 @@ bool LeAudioDevice::HaveAllActiveAsesCisEst(void) const { bool LeAudioDevice::HaveAnyCisConnected(void) { /* Pending and Disconnecting is considered as connected in this function */ for (auto const ase : ases_) { - if (ase.cis_state == CisState::CONNECTED || - ase.cis_state == CisState::CONNECTING || + if (ase.cis_state == CisState::CONNECTED || ase.cis_state == CisState::CONNECTING || ase.cis_state == CisState::DISCONNECTING) { return true; } @@ -863,8 +860,7 @@ bool LeAudioDevice::HaveAnyCisConnected(void) { } uint8_t LeAudioDevice::GetSupportedAudioChannelCounts(uint8_t direction) const { - auto& pacs = - direction == types::kLeAudioDirectionSink ? snk_pacs_ : src_pacs_; + auto& pacs = direction == types::kLeAudioDirectionSink ? snk_pacs_ : src_pacs_; if (pacs.size() == 0) { log::error("{}, missing PAC for direction {}", address_, direction); @@ -881,12 +877,11 @@ uint8_t LeAudioDevice::GetSupportedAudioChannelCounts(uint8_t direction) const { bluetooth::common::ToString(pac.codec_id)); continue; } - log::assert_that( - !pac.codec_spec_caps.IsEmpty(), - "Codec specific capabilities are not parsed approprietly."); + log::assert_that(!pac.codec_spec_caps.IsEmpty(), + "Codec specific capabilities are not parsed appropriately."); - auto supported_channel_count_ltv = pac.codec_spec_caps.Find( - codec_spec_caps::kLeAudioLtvTypeSupportedAudioChannelCounts); + auto supported_channel_count_ltv = + pac.codec_spec_caps.Find(codec_spec_caps::kLeAudioLtvTypeSupportedAudioChannelCounts); if (supported_channel_count_ltv == std::nullopt || supported_channel_count_ltv->size() == 0L) { @@ -916,32 +911,27 @@ uint8_t LeAudioDevice::GetPhyBitmask(void) const { void LeAudioDevice::PrintDebugState(void) { std::stringstream debug_str; - debug_str << " address: " << address_ << ", " - << bluetooth::common::ToString(connection_state_) + debug_str << " address: " << address_ << ", " << bluetooth::common::ToString(connection_state_) << ", conn_id: " << +conn_id_ << ", mtu: " << +mtu_ << ", num_of_ase: " << static_cast(ases_.size()); if (ases_.size() > 0) { debug_str << "\n == ASEs == "; for (auto& ase : ases_) { - debug_str - << "\n id: " << +ase.id << ", active: " << ase.active << ", dir: " - << (ase.direction == types::kLeAudioDirectionSink ? "sink" : "source") - << ", state: " << bluetooth::common::ToString(ase.state) - << ", cis_id: " << +ase.cis_id - << ", cis_handle: " << +ase.cis_conn_hdl - << ", cis_state: " << bluetooth::common::ToString(ase.cis_state) - << ", data_path_state: " - << bluetooth::common::ToString(ase.data_path_state) - << "\n ase max_latency: " << +ase.qos_config.max_transport_latency - << ", rtn: " << +ase.qos_config.retrans_nb - << ", max_sdu: " << +ase.qos_config.max_sdu_size - << ", sdu_interval: " << +ase.qos_config.sdu_interval - << ", presentation_delay: " << +ase.qos_config.presentation_delay - << ", framing: " << +ase.qos_config.framing - << ", phy: " << +ase.qos_config.phy - << ", target latency: " << +ase.target_latency - << ", reconfigure: " << ase.reconfigure << "\n"; + debug_str << "\n id: " << +ase.id << ", active: " << ase.active + << ", dir: " << (ase.direction == types::kLeAudioDirectionSink ? "sink" : "source") + << ", state: " << bluetooth::common::ToString(ase.state) + << ", cis_id: " << +ase.cis_id << ", cis_handle: " << +ase.cis_conn_hdl + << ", cis_state: " << bluetooth::common::ToString(ase.cis_state) + << ", data_path_state: " << bluetooth::common::ToString(ase.data_path_state) + << "\n ase max_latency: " << +ase.qos_config.max_transport_latency + << ", rtn: " << +ase.qos_config.retrans_nb + << ", max_sdu: " << +ase.qos_config.max_sdu_size + << ", sdu_interval: " << +ase.qos_config.sdu_interval + << ", presentation_delay: " << +ase.qos_config.presentation_delay + << ", framing: " << +ase.qos_config.framing << ", phy: " << +ase.qos_config.phy + << ", target latency: " << +ase.target_latency + << ", reconfigure: " << ase.reconfigure << "\n"; } } @@ -951,10 +941,12 @@ void LeAudioDevice::PrintDebugState(void) { uint8_t LeAudioDevice::GetPreferredPhyBitmask(uint8_t preferred_phy) const { // Start with full local phy support uint8_t phy_bitmask = bluetooth::hci::kIsoCigPhy1M; - if (bluetooth::shim::GetController()->SupportsBle2mPhy()) + if (bluetooth::shim::GetController()->SupportsBle2mPhy()) { phy_bitmask |= bluetooth::hci::kIsoCigPhy2M; - if (bluetooth::shim::GetController()->SupportsBleCodedPhy()) + } + if (bluetooth::shim::GetController()->SupportsBleCodedPhy()) { phy_bitmask |= bluetooth::hci::kIsoCigPhyC; + } // Check against the remote device support phy_bitmask &= GetPhyBitmask(); @@ -962,14 +954,12 @@ uint8_t LeAudioDevice::GetPreferredPhyBitmask(uint8_t preferred_phy) const { // Take the preferences if possible if (preferred_phy && (phy_bitmask & preferred_phy)) { phy_bitmask &= preferred_phy; - log::debug("{}, using ASE preferred phy 0x{:02x}", address_, - static_cast(phy_bitmask)); + log::debug("{}, using ASE preferred phy 0x{:02x}", address_, static_cast(phy_bitmask)); } else { log::warn( - " {}, ASE preferred 0x{:02x} has nothing common with phy_bitfield " - "0x{:02x}", - address_, static_cast(preferred_phy), - static_cast(phy_bitmask)); + " {}, ASE preferred 0x{:02x} has nothing common with phy_bitfield " + "0x{:02x}", + address_, static_cast(preferred_phy), static_cast(phy_bitmask)); } return phy_bitmask; } @@ -984,22 +974,18 @@ void LeAudioDevice::DumpPacsDebugState(std::stringstream& stream, for (auto& record : std::get<1>(pac)) { stream << "\n\n\t\tCodecId(Coding format: " << static_cast(record.codec_id.coding_format) - << ", Vendor company ID: " - << static_cast(record.codec_id.vendor_company_id) - << ", Vendor codec ID: " - << static_cast(record.codec_id.vendor_codec_id) << ")"; + << ", Vendor company ID: " << static_cast(record.codec_id.vendor_company_id) + << ", Vendor codec ID: " << static_cast(record.codec_id.vendor_codec_id) << ")"; stream << "\n\t\tCodec specific capabilities:\n"; if (utils::IsCodecUsingLtvFormat(record.codec_id)) { - stream << record.codec_spec_caps.ToString( - "\t\t\t", types::CodecCapabilitiesLtvFormat); + stream << record.codec_spec_caps.ToString("\t\t\t", types::CodecCapabilitiesLtvFormat); } else { stream << "\t\t\t" << base::HexEncode(record.codec_spec_caps_raw.data(), record.codec_spec_caps_raw.size()); } stream << "\t\tMetadata: " - << base::HexEncode(record.metadata.data(), - record.metadata.size()); + << base::HexEncode(record.metadata.data(), record.metadata.size()); } } } @@ -1037,13 +1023,10 @@ void LeAudioDevice::Dump(int fd) { std::string src_location = locationToString(src_audio_locations_.to_ulong()); std::stringstream stream; - stream << "\n\taddress: " << ADDRESS_TO_LOGGABLE_STR(address_) << ": " - << connection_state_ << ": " - << (conn_id_ == GATT_INVALID_CONN_ID ? "" : std::to_string(conn_id_)) - << ", acl_handle: " << std::to_string(acl_handle) - << ", snk_location: " << snk_location - << ", src_location: " << src_location << ",\t" - << (encrypted_ ? "Encrypted" : "Unecrypted") + stream << "\n\taddress: " << ADDRESS_TO_LOGGABLE_STR(address_) << ": " << connection_state_ + << ": " << (conn_id_ == GATT_INVALID_CONN_ID ? "" : std::to_string(conn_id_)) + << ", acl_handle: " << std::to_string(acl_handle) << ", snk_location: " << snk_location + << ", src_location: " << src_location << ",\t" << (encrypted_ ? "Encrypted" : "Unecrypted") << ",mtu: " << std::to_string(mtu_) << "\n\tnumber of ases_: " << static_cast(ases_.size()); @@ -1055,16 +1038,12 @@ void LeAudioDevice::Dump(int fd) { stream << std::setfill('\x20') << "\n\t" << std::left << std::setw(4) << static_cast(ase.id) << std::left << std::setw(7) << (ase.active ? "true" : "false") << std::left << std::setw(8) - << (ase.direction == types::kLeAudioDirectionSink ? "sink" - : "source") - << std::left << std::setw(8) << static_cast(ase.cis_id) - << std::left << std::setw(12) << ase.cis_conn_hdl << std::left - << std::setw(5) << ase.qos_config.max_sdu_size << std::left - << std::setw(8) << ase.qos_config.max_transport_latency - << std::left << std::setw(5) - << static_cast(ase.qos_config.retrans_nb) << std::left - << std::setw(10) << bluetooth::common::ToString(ase.cis_state) - << std::setw(12) + << (ase.direction == types::kLeAudioDirectionSink ? "sink" : "source") << std::left + << std::setw(8) << static_cast(ase.cis_id) << std::left << std::setw(12) + << ase.cis_conn_hdl << std::left << std::setw(5) << ase.qos_config.max_sdu_size + << std::left << std::setw(8) << ase.qos_config.max_transport_latency << std::left + << std::setw(5) << static_cast(ase.qos_config.retrans_nb) << std::left + << std::setw(10) << bluetooth::common::ToString(ase.cis_state) << std::setw(12) << bluetooth::common::ToString(ase.data_path_state); } } @@ -1075,7 +1054,9 @@ void LeAudioDevice::Dump(int fd) { } void LeAudioDevice::DisconnectAcl(void) { - if (conn_id_ == GATT_INVALID_CONN_ID) return; + if (conn_id_ == GATT_INVALID_CONN_ID) { + return; + } uint16_t acl_handle = get_btm_client_interface().peer.BTM_GetHCIConnHandle(address_, BT_TRANSPORT_LE); @@ -1085,38 +1066,35 @@ void LeAudioDevice::DisconnectAcl(void) { } } -void LeAudioDevice::SetAvailableContexts( - BidirectionalPair contexts) { +void LeAudioDevice::SetAvailableContexts(BidirectionalPair contexts) { log::debug( - "{}: \n\t previous_contexts_.sink: {} \n\t previous_contexts_.source: {} " - " " - "\n\t new_contexts.sink: {} \n\t new_contexts.source: {} \n\t", - address_, avail_contexts_.sink.to_string(), - avail_contexts_.source.to_string(), contexts.sink.to_string(), - contexts.source.to_string()); + "{}: \n\t previous_contexts_.sink: {} \n\t previous_contexts_.source: {} " + " " + "\n\t new_contexts.sink: {} \n\t new_contexts.source: {} \n\t", + address_, avail_contexts_.sink.to_string(), avail_contexts_.source.to_string(), + contexts.sink.to_string(), contexts.source.to_string()); avail_contexts_.sink = contexts.sink; avail_contexts_.source = contexts.source; } -void LeAudioDevice::SetMetadataToAse( - struct types::ase* ase, const AudioContexts& metadata_context_types, - const std::vector& ccid_lists) { +void LeAudioDevice::SetMetadataToAse(struct types::ase* ase, + const AudioContexts& metadata_context_types, + const std::vector& ccid_lists) { /* Filter multidirectional audio context for each ase direction */ - auto directional_audio_context = - metadata_context_types & GetAvailableContexts(ase->direction); + auto directional_audio_context = metadata_context_types & GetAvailableContexts(ase->direction); if (directional_audio_context.any()) { ase->metadata = GetMetadata(directional_audio_context, ccid_lists); } else { - ase->metadata = GetMetadata(AudioContexts(LeAudioContextType::UNSPECIFIED), - std::vector()); + ase->metadata = + GetMetadata(AudioContexts(LeAudioContextType::UNSPECIFIED), std::vector()); } } bool LeAudioDevice::ActivateConfiguredAses( - LeAudioContextType context_type, - const BidirectionalPair& metadata_context_types, - BidirectionalPair> ccid_lists) { + LeAudioContextType context_type, + const BidirectionalPair& metadata_context_types, + BidirectionalPair> ccid_lists) { if (conn_id_ == GATT_INVALID_CONN_ID) { log::warn("Device {} is not connected", address_); return false; @@ -1129,9 +1107,9 @@ bool LeAudioDevice::ActivateConfiguredAses( if (ase.state == AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED && ase.configured_for_context_type == context_type) { log::info( - "conn_id: {}, ase id {}, cis id {}, cis_handle 0x{:04x} is " - "activated.", - conn_id_, ase.id, ase.cis_id, ase.cis_conn_hdl); + "conn_id: {}, ase id {}, cis id {}, cis_handle 0x{:04x} is " + "activated.", + conn_id_, ase.id, ase.cis_id, ase.cis_conn_hdl); ase.active = true; ret = true; /* update metadata */ @@ -1148,11 +1126,11 @@ void LeAudioDevice::DeactivateAllAses(void) { if (ase.active == false && ase.cis_state != CisState::IDLE && ase.data_path_state != DataPathState::IDLE) { log::warn( - "{}, ase_id: {}, ase.cis_id: {}, cis_handle: 0x{:02x}, " - "ase.cis_state={}, ase.data_path_state={}", - address_, ase.id, ase.cis_id, ase.cis_conn_hdl, - bluetooth::common::ToString(ase.cis_state), - bluetooth::common::ToString(ase.data_path_state)); + "{}, ase_id: {}, ase.cis_id: {}, cis_handle: 0x{:02x}, " + "ase.cis_state={}, ase.data_path_state={}", + address_, ase.id, ase.cis_id, ase.cis_conn_hdl, + bluetooth::common::ToString(ase.cis_state), + bluetooth::common::ToString(ase.data_path_state)); } log::verbose("{}, ase_id {}", address_, ase.id); @@ -1167,8 +1145,8 @@ void LeAudioDevice::DeactivateAllAses(void) { } } -std::vector LeAudioDevice::GetMetadata( - AudioContexts context_type, const std::vector& ccid_list) { +std::vector LeAudioDevice::GetMetadata(AudioContexts context_type, + const std::vector& ccid_list) { std::vector metadata; AppendMetadataLtvEntryForStreamingContext(metadata, context_type); @@ -1177,14 +1155,13 @@ std::vector LeAudioDevice::GetMetadata( return std::move(metadata); } -bool LeAudioDevice::IsMetadataChanged( - const BidirectionalPair& context_types, - const BidirectionalPair>& ccid_lists) { - for (auto* ase = this->GetFirstActiveAse(); ase; - ase = this->GetNextActiveAse(ase)) { - if (this->GetMetadata(context_types.get(ase->direction), - ccid_lists.get(ase->direction)) != ase->metadata) +bool LeAudioDevice::IsMetadataChanged(const BidirectionalPair& context_types, + const BidirectionalPair>& ccid_lists) { + for (auto* ase = this->GetFirstActiveAse(); ase; ase = this->GetNextActiveAse(ase)) { + if (this->GetMetadata(context_types.get(ase->direction), ccid_lists.get(ase->direction)) != + ase->metadata) { return true; + } } return false; @@ -1194,10 +1171,9 @@ void LeAudioDevice::GetDeviceModelName(void) { bt_property_t prop_name; bt_bdname_t prop_value = {0}; // Retrieve model name from storage - BTIF_STORAGE_FILL_PROPERTY(&prop_name, BT_PROPERTY_REMOTE_MODEL_NUM, - sizeof(bt_bdname_t), &prop_value); - if (btif_storage_get_remote_device_property(&address_, &prop_name) == - BT_STATUS_SUCCESS) { + BTIF_STORAGE_FILL_PROPERTY(&prop_name, BT_PROPERTY_REMOTE_MODEL_NUM, sizeof(bt_bdname_t), + &prop_value); + if (btif_storage_get_remote_device_property(&address_, &prop_name) == BT_STATUS_SUCCESS) { model_name_.assign((char*)prop_value.name); } } @@ -1224,39 +1200,29 @@ void LeAudioDevice::UpdateDeviceAllowlistFlag(void) { DsaModes LeAudioDevice::GetDsaModes(void) { return dsa_.modes; } -types::DataPathState LeAudioDevice::GetDsaDataPathState(void) { - return dsa_.state; -} +types::DataPathState LeAudioDevice::GetDsaDataPathState(void) { return dsa_.state; } -void LeAudioDevice::SetDsaDataPathState(types::DataPathState state) { - dsa_.state = state; -} +void LeAudioDevice::SetDsaDataPathState(types::DataPathState state) { dsa_.state = state; } uint16_t LeAudioDevice::GetDsaCisHandle(void) { return dsa_.cis_handle; } -void LeAudioDevice::SetDsaCisHandle(uint16_t cis_handle) { - dsa_.cis_handle = cis_handle; -} +void LeAudioDevice::SetDsaCisHandle(uint16_t cis_handle) { dsa_.cis_handle = cis_handle; } /* LeAudioDevices Class methods implementation */ -void LeAudioDevices::Add(const RawAddress& address, DeviceConnectState state, - int group_id) { +void LeAudioDevices::Add(const RawAddress& address, DeviceConnectState state, int group_id) { auto device = FindByAddress(address); if (device != nullptr) { - log::error("address: {} is already assigned to group: {}", address, - device->group_id_); + log::error("address: {} is already assigned to group: {}", address, device->group_id_); return; } - leAudioDevices_.emplace_back( - std::make_shared(address, state, group_id)); + leAudioDevices_.emplace_back(std::make_shared(address, state, group_id)); } void LeAudioDevices::Remove(const RawAddress& address) { - auto iter = std::find_if(leAudioDevices_.begin(), leAudioDevices_.end(), - [&address](auto const& leAudioDevice) { - return leAudioDevice->address_ == address; - }); + auto iter = std::find_if( + leAudioDevices_.begin(), leAudioDevices_.end(), + [&address](auto const& leAudioDevice) { return leAudioDevice->address_ == address; }); if (iter == leAudioDevices_.end()) { log::error("no such address: {}", address); @@ -1267,35 +1233,30 @@ void LeAudioDevices::Remove(const RawAddress& address) { } LeAudioDevice* LeAudioDevices::FindByAddress(const RawAddress& address) const { - auto iter = std::find_if(leAudioDevices_.begin(), leAudioDevices_.end(), - [&address](auto const& leAudioDevice) { - return leAudioDevice->address_ == address; - }); + auto iter = std::find_if( + leAudioDevices_.begin(), leAudioDevices_.end(), + [&address](auto const& leAudioDevice) { return leAudioDevice->address_ == address; }); return (iter == leAudioDevices_.end()) ? nullptr : iter->get(); } -std::shared_ptr LeAudioDevices::GetByAddress( - const RawAddress& address) const { - auto iter = std::find_if(leAudioDevices_.begin(), leAudioDevices_.end(), - [&address](auto const& leAudioDevice) { - return leAudioDevice->address_ == address; - }); +std::shared_ptr LeAudioDevices::GetByAddress(const RawAddress& address) const { + auto iter = std::find_if( + leAudioDevices_.begin(), leAudioDevices_.end(), + [&address](auto const& leAudioDevice) { return leAudioDevice->address_ == address; }); return (iter == leAudioDevices_.end()) ? nullptr : *iter; } LeAudioDevice* LeAudioDevices::FindByConnId(uint16_t conn_id) const { - auto iter = std::find_if(leAudioDevices_.begin(), leAudioDevices_.end(), - [&conn_id](auto const& leAudioDevice) { - return leAudioDevice->conn_id_ == conn_id; - }); + auto iter = std::find_if( + leAudioDevices_.begin(), leAudioDevices_.end(), + [&conn_id](auto const& leAudioDevice) { return leAudioDevice->conn_id_ == conn_id; }); return (iter == leAudioDevices_.end()) ? nullptr : iter->get(); } -LeAudioDevice* LeAudioDevices::FindByCisConnHdl(uint8_t cig_id, - uint16_t conn_hdl) const { +LeAudioDevice* LeAudioDevices::FindByCisConnHdl(uint8_t cig_id, uint16_t conn_hdl) const { auto iter = std::find_if(leAudioDevices_.begin(), leAudioDevices_.end(), [&conn_hdl, &cig_id](auto& d) { LeAudioDevice* dev; @@ -1307,34 +1268,36 @@ LeAudioDevice* LeAudioDevices::FindByCisConnHdl(uint8_t cig_id, } ases = dev->GetAsesByCisConnHdl(conn_hdl); - if (ases.sink || ases.source) + if (ases.sink || ases.source) { return true; - else + } else { return false; + } }); - if (iter == leAudioDevices_.end()) return nullptr; + if (iter == leAudioDevices_.end()) { + return nullptr; + } return iter->get(); } -void LeAudioDevices::SetInitialGroupAutoconnectState( - int group_id, int gatt_if, tBTM_BLE_CONN_TYPE reconnection_mode, - bool current_dev_autoconnect_flag) { +void LeAudioDevices::SetInitialGroupAutoconnectState(int group_id, int gatt_if, + tBTM_BLE_CONN_TYPE reconnection_mode, + bool current_dev_autoconnect_flag) { if (!current_dev_autoconnect_flag) { /* If current device autoconnect flag is false, check if there is other * device in the group which is in autoconnect mode. * If yes, assume whole group is in autoconnect. */ - auto iter = std::find_if(leAudioDevices_.begin(), leAudioDevices_.end(), - [&group_id](auto& d) { - LeAudioDevice* dev; - dev = d.get(); - if (dev->group_id_ != group_id) { - return false; - } - return dev->autoconnect_flag_; - }); + auto iter = std::find_if(leAudioDevices_.begin(), leAudioDevices_.end(), [&group_id](auto& d) { + LeAudioDevice* dev; + dev = d.get(); + if (dev->group_id_ != group_id) { + return false; + } + return dev->autoconnect_flag_; + }); current_dev_autoconnect_flag = !(iter == leAudioDevices_.end()); } @@ -1357,7 +1320,7 @@ void LeAudioDevices::SetInitialGroupAutoconnectState( } } -size_t LeAudioDevices::Size() const { return (leAudioDevices_.size()); } +size_t LeAudioDevices::Size() const { return leAudioDevices_.size(); } void LeAudioDevices::Dump(int fd, int group_id) const { std::stringstream stream, stream_pacs; diff --git a/system/bta/le_audio/devices.h b/system/bta/le_audio/devices.h index 35a3b52b95b..d34f10915f9 100644 --- a/system/bta/le_audio/devices.h +++ b/system/bta/le_audio/devices.h @@ -74,7 +74,7 @@ std::ostream& operator<<(std::ostream& os, const DeviceConnectState& state); * according to requested by upper context type. */ class LeAudioDevice { - public: +public: RawAddress address_; DeviceConnectState connection_state_; @@ -132,9 +132,7 @@ class LeAudioDevice { acl_asymmetric_(false), acl_phy_update_done_(false), link_quality_timer(nullptr), - dsa_({{DsaMode::DISABLED}, - types::DataPathState::IDLE, - GATT_INVALID_CONN_ID}) {} + dsa_({{DsaMode::DISABLED}, types::DataPathState::IDLE, GATT_INVALID_CONN_ID}) {} ~LeAudioDevice(void); void SetConnectionState(DeviceConnectState state); @@ -146,20 +144,15 @@ class LeAudioDevice { int GetAseCount(uint8_t direction); struct types::ase* GetFirstActiveAse(void); struct types::ase* GetFirstActiveAseByDirection(uint8_t direction); - struct types::ase* GetNextActiveAseWithSameDirection( - struct types::ase* base_ase); - struct types::ase* GetNextActiveAseWithDifferentDirection( - struct types::ase* base_ase); - struct types::ase* GetFirstActiveAseByCisAndDataPathState( - types::CisState cis_state, types::DataPathState data_path_state); - struct types::ase* GetFirstInactiveAse(uint8_t direction, - bool reconnect = false); - struct types::ase* GetFirstAseWithState(uint8_t direction, - types::AseState state); + struct types::ase* GetNextActiveAseWithSameDirection(struct types::ase* base_ase); + struct types::ase* GetNextActiveAseWithDifferentDirection(struct types::ase* base_ase); + struct types::ase* GetFirstActiveAseByCisAndDataPathState(types::CisState cis_state, + types::DataPathState data_path_state); + struct types::ase* GetFirstInactiveAse(uint8_t direction, bool reconnect = false); + struct types::ase* GetFirstAseWithState(uint8_t direction, types::AseState state); struct types::ase* GetNextActiveAse(struct types::ase* ase); struct types::ase* GetAseToMatchBidirectionCis(struct types::ase* ase); - types::BidirectionalPair GetAsesByCisConnHdl( - uint16_t conn_hdl); + types::BidirectionalPair GetAsesByCisConnHdl(uint16_t conn_hdl); types::BidirectionalPair GetAsesByCisId(uint8_t cis_id); bool HaveActiveAse(void); bool HaveAllActiveAsesSameState(types::AseState state); @@ -179,52 +172,46 @@ class LeAudioDevice { uint8_t GetPhyBitmask(void) const; uint8_t GetPreferredPhyBitmask(uint8_t preferred_phy) const; bool IsAudioSetConfigurationSupported( - const set_configurations::AudioSetConfiguration* audio_set_conf) const; - bool ConfigureAses( - const set_configurations::AudioSetConfiguration* audio_set_conf, - uint8_t group_size, uint8_t direction, - types::LeAudioContextType context_type, - uint8_t* number_of_already_active_group_ase, - types::AudioLocations& group_audio_locations_out, - const types::AudioContexts& metadata_context_types, - const std::vector& ccid_lists, bool reuse_cis_id); + const set_configurations::AudioSetConfiguration* audio_set_conf) const; + bool ConfigureAses(const set_configurations::AudioSetConfiguration* audio_set_conf, + uint8_t group_size, uint8_t direction, types::LeAudioContextType context_type, + uint8_t* number_of_already_active_group_ase, + types::AudioLocations& group_audio_locations_out, + const types::AudioContexts& metadata_context_types, + const std::vector& ccid_lists, bool reuse_cis_id); inline types::AudioContexts GetSupportedContexts( - int direction = types::kLeAudioDirectionBoth) const { - log::assert_that(direction <= (types::kLeAudioDirectionBoth), - "Invalid direction used."); + int direction = types::kLeAudioDirectionBoth) const { + log::assert_that(direction <= (types::kLeAudioDirectionBoth), "Invalid direction used."); - if (direction < types::kLeAudioDirectionBoth) + if (direction < types::kLeAudioDirectionBoth) { return supp_contexts_.get(direction); - else + } else { return types::get_bidirectional(supp_contexts_); + } } - inline void SetSupportedContexts( - types::BidirectionalPair contexts) { + inline void SetSupportedContexts(types::BidirectionalPair contexts) { supp_contexts_ = contexts; } inline types::AudioContexts GetAvailableContexts( - int direction = types::kLeAudioDirectionBoth) const { - log::assert_that(direction <= (types::kLeAudioDirectionBoth), - "Invalid direction used."); + int direction = types::kLeAudioDirectionBoth) const { + log::assert_that(direction <= (types::kLeAudioDirectionBoth), "Invalid direction used."); - if (direction < types::kLeAudioDirectionBoth) + if (direction < types::kLeAudioDirectionBoth) { return avail_contexts_.get(direction); - else + } else { return types::get_bidirectional(avail_contexts_); + } } - void SetAvailableContexts( - types::BidirectionalPair cont_val); + void SetAvailableContexts(types::BidirectionalPair cont_val); void DeactivateAllAses(void); bool ActivateConfiguredAses( - types::LeAudioContextType context_type, - const types::BidirectionalPair& - metadata_context_types, - types::BidirectionalPair> ccid_lists); - void SetMetadataToAse(struct types::ase* ase, - const types::AudioContexts& metadata_context_types, + types::LeAudioContextType context_type, + const types::BidirectionalPair& metadata_context_types, + types::BidirectionalPair> ccid_lists); + void SetMetadataToAse(struct types::ase* ase, const types::AudioContexts& metadata_context_types, const std::vector& ccid_lists); void PrintDebugState(void); @@ -234,9 +221,8 @@ class LeAudioDevice { void DisconnectAcl(void); std::vector GetMetadata(types::AudioContexts context_type, const std::vector& ccid_list); - bool IsMetadataChanged( - const types::BidirectionalPair& context_types, - const types::BidirectionalPair>& ccid_lists); + bool IsMetadataChanged(const types::BidirectionalPair& context_types, + const types::BidirectionalPair>& ccid_lists); void GetDeviceModelName(void); void UpdateDeviceAllowlistFlag(void); @@ -246,7 +232,7 @@ class LeAudioDevice { uint16_t GetDsaCisHandle(void); void SetDsaCisHandle(uint16_t cis_handle); - private: +private: types::BidirectionalPair avail_contexts_; types::BidirectionalPair supp_contexts_; struct { @@ -255,11 +241,9 @@ class LeAudioDevice { uint16_t cis_handle; } dsa_; - static constexpr char kLeAudioDeviceAllowListProp[] = - "persist.bluetooth.leaudio.allow_list"; + static constexpr char kLeAudioDeviceAllowListProp[] = "persist.bluetooth.leaudio.allow_list"; - void DumpPacsDebugState(std::stringstream& stream, - types::PublishedAudioCapabilities pacs); + void DumpPacsDebugState(std::stringstream& stream, types::PublishedAudioCapabilities pacs); void ParseHeadtrackingCodec(const struct types::acs_ac_record& pac); }; @@ -268,9 +252,8 @@ class LeAudioDevice { * using determinants like address, connection id etc. */ class LeAudioDevices { - public: - void Add(const RawAddress& address, - bluetooth::le_audio::DeviceConnectState state, +public: + void Add(const RawAddress& address, bluetooth::le_audio::DeviceConnectState state, int group_id = bluetooth::groups::kGroupUnknown); void Remove(const RawAddress& address); LeAudioDevice* FindByAddress(const RawAddress& address) const; @@ -284,7 +267,7 @@ class LeAudioDevices { void Dump(int fd, int group_id) const; void Cleanup(tGATT_IF client_if); - private: +private: std::vector> leAudioDevices_; }; diff --git a/system/bta/le_audio/devices_test.cc b/system/bta/le_audio/devices_test.cc index ea6f4421a1d..0a6b45c9d97 100644 --- a/system/bta/le_audio/devices_test.cc +++ b/system/bta/le_audio/devices_test.cc @@ -36,9 +36,7 @@ #include "stack/btm/btm_int_types.h" #include "test/mock/mock_main_shim_entry.h" -tACL_CONN* btm_bda_to_acl(const RawAddress& bda, tBT_TRANSPORT transport) { - return nullptr; -} +tACL_CONN* btm_bda_to_acl(const RawAddress& bda, tBT_TRANSPORT transport) { return nullptr; } namespace bluetooth { namespace le_audio { @@ -62,45 +60,44 @@ using testing::Return; using testing::Test; auto constexpr kVendorCodecIdOne = bluetooth::le_audio::types::LeAudioCodecId( - {.coding_format = types::kLeAudioCodingFormatVendorSpecific, - .vendor_company_id = 0xF00D, - .vendor_codec_id = 0x0001}); + {.coding_format = types::kLeAudioCodingFormatVendorSpecific, + .vendor_company_id = 0xF00D, + .vendor_codec_id = 0x0001}); set_configurations::CodecConfigSetting kVendorCodecOne = { - .id = kVendorCodecIdOne, - .params = types::LeAudioLtvMap({ - // Add the Sampling Freq and AudioChannelAllocation which are - // mandatory even for the Vendor codec provider (multicodec AIDL) - {codec_spec_conf::kLeAudioLtvTypeSamplingFreq, - UINT8_TO_VEC_UINT8(codec_spec_conf::kLeAudioSamplingFreq16000Hz)}, - }), - // Some opaque data buffer - .vendor_params = std::vector({0x01, 0xC0, 0xDE, 0xF0, 0x0D}), - .channel_count_per_iso_stream = 1, + .id = kVendorCodecIdOne, + .params = types::LeAudioLtvMap({ + // Add the Sampling Freq and AudioChannelAllocation which are + // mandatory even for the Vendor codec provider (multicodec AIDL) + {codec_spec_conf::kLeAudioLtvTypeSamplingFreq, + UINT8_TO_VEC_UINT8(codec_spec_conf::kLeAudioSamplingFreq16000Hz)}, + }), + // Some opaque data buffer + .vendor_params = std::vector({0x01, 0xC0, 0xDE, 0xF0, 0x0D}), + .channel_count_per_iso_stream = 1, }; set_configurations::CodecConfigSetting kVendorCodecOneSwb = { - .id = kVendorCodecIdOne, - .params = types::LeAudioLtvMap({ - // Add the Sampling Freq and AudioChannelAllocation which are - // mandatory even for the Vendor codec provider (multicodec AIDL) - {codec_spec_conf::kLeAudioLtvTypeSamplingFreq, - UINT8_TO_VEC_UINT8(codec_spec_conf::kLeAudioSamplingFreq32000Hz)}, - }), - // Some opaque data buffer - .vendor_params = std::vector({0x01, 0xC0, 0xDE, 0xF0, 0x0F}), - .channel_count_per_iso_stream = 1, + .id = kVendorCodecIdOne, + .params = types::LeAudioLtvMap({ + // Add the Sampling Freq and AudioChannelAllocation which are + // mandatory even for the Vendor codec provider (multicodec AIDL) + {codec_spec_conf::kLeAudioLtvTypeSamplingFreq, + UINT8_TO_VEC_UINT8(codec_spec_conf::kLeAudioSamplingFreq32000Hz)}, + }), + // Some opaque data buffer + .vendor_params = std::vector({0x01, 0xC0, 0xDE, 0xF0, 0x0F}), + .channel_count_per_iso_stream = 1, }; RawAddress GetTestAddress(int index) { EXPECT_LT(index, UINT8_MAX); - RawAddress result = { - {0xC0, 0xDE, 0xC0, 0xDE, 0x00, static_cast(index)}}; + RawAddress result = {{0xC0, 0xDE, 0xC0, 0xDE, 0x00, static_cast(index)}}; return result; } class LeAudioDevicesTest : public Test { - protected: +protected: void SetUp() override { __android_log_set_minimum_priority(ANDROID_LOG_VERBOSE); devices_ = new LeAudioDevices(); @@ -176,8 +173,7 @@ TEST_F(LeAudioDevicesTest, test_get_by_address_success) { devices_->Add(test_address_1, DeviceConnectState::DISCONNECTED); RawAddress test_address_2 = GetTestAddress(2); devices_->Add(test_address_2, DeviceConnectState::CONNECTING_BY_USER); - std::shared_ptr device = - devices_->GetByAddress(test_address_1); + std::shared_ptr device = devices_->GetByAddress(test_address_1); ASSERT_NE(nullptr, device); ASSERT_EQ(test_address_1, device->address_); } @@ -187,8 +183,7 @@ TEST_F(LeAudioDevicesTest, test_get_by_address_failed) { devices_->Add(test_address_0, DeviceConnectState::CONNECTING_BY_USER); RawAddress test_address_2 = GetTestAddress(2); devices_->Add(test_address_2, DeviceConnectState::CONNECTING_BY_USER); - std::shared_ptr device = - devices_->GetByAddress(GetTestAddress(1)); + std::shared_ptr device = devices_->GetByAddress(GetTestAddress(1)); ASSERT_EQ(nullptr, device); } @@ -212,12 +207,11 @@ TEST_F(LeAudioDevicesTest, test_find_by_conn_id_failed) { TEST_F(LeAudioDevicesTest, test_get_device_model_name_success) { RawAddress test_address_0 = GetTestAddress(0); devices_->Add(test_address_0, DeviceConnectState::CONNECTING_BY_USER); - std::shared_ptr device = - devices_->GetByAddress(test_address_0); + std::shared_ptr device = devices_->GetByAddress(test_address_0); ASSERT_NE(nullptr, device); device->model_name_ = "Test"; ON_CALL(mock_btif_storage_, GetRemoteDeviceProperty(_, _)) - .WillByDefault(Return(BT_STATUS_SUCCESS)); + .WillByDefault(Return(BT_STATUS_SUCCESS)); device->GetDeviceModelName(); ASSERT_EQ("", device->model_name_); } @@ -225,12 +219,10 @@ TEST_F(LeAudioDevicesTest, test_get_device_model_name_success) { TEST_F(LeAudioDevicesTest, test_get_device_model_name_failed) { RawAddress test_address_0 = GetTestAddress(0); devices_->Add(test_address_0, DeviceConnectState::CONNECTING_BY_USER); - std::shared_ptr device = - devices_->GetByAddress(test_address_0); + std::shared_ptr device = devices_->GetByAddress(test_address_0); ASSERT_NE(nullptr, device); device->model_name_ = "Test"; - ON_CALL(mock_btif_storage_, GetRemoteDeviceProperty(_, _)) - .WillByDefault(Return(BT_STATUS_FAIL)); + ON_CALL(mock_btif_storage_, GetRemoteDeviceProperty(_, _)).WillByDefault(Return(BT_STATUS_FAIL)); device->GetDeviceModelName(); ASSERT_EQ("Test", device->model_name_); } @@ -281,8 +273,9 @@ bool IsLc3SettingSupported(LeAudioContextType context_type, Lc3SettingId id) { id == Lc3SettingId::LC3_32_1 || id == Lc3SettingId::LC3_32_2 || id == Lc3SettingId::LC3_48_1 || id == Lc3SettingId::LC3_48_2 || id == Lc3SettingId::LC3_48_3 || id == Lc3SettingId::LC3_48_4 || - id == Lc3SettingId::LC3_VND_1) + id == Lc3SettingId::LC3_VND_1) { return true; + } break; @@ -295,13 +288,16 @@ bool IsLc3SettingSupported(LeAudioContextType context_type, Lc3SettingId id) { if (id == Lc3SettingId::LC3_16_1 || id == Lc3SettingId::LC3_16_2 || id == Lc3SettingId::LC3_48_4 || id == Lc3SettingId::LC3_48_1 || id == Lc3SettingId::LC3_48_2 || id == Lc3SettingId::LC3_VND_1 || - id == Lc3SettingId::LC3_24_2) + id == Lc3SettingId::LC3_24_2) { return true; + } break; default: - if (id == Lc3SettingId::LC3_16_2) return true; + if (id == Lc3SettingId::LC3_16_2) { + return true; + } break; }; @@ -317,20 +313,16 @@ uint8_t GetSamplingFrequency(Lc3SettingId id) { return ::bluetooth::le_audio::codec_spec_conf::kLeAudioSamplingFreq8000Hz; case Lc3SettingId::LC3_16_1: case Lc3SettingId::LC3_16_2: - return ::bluetooth::le_audio::codec_spec_conf:: - kLeAudioSamplingFreq16000Hz; + return ::bluetooth::le_audio::codec_spec_conf::kLeAudioSamplingFreq16000Hz; case Lc3SettingId::LC3_24_1: case Lc3SettingId::LC3_24_2: - return ::bluetooth::le_audio::codec_spec_conf:: - kLeAudioSamplingFreq24000Hz; + return ::bluetooth::le_audio::codec_spec_conf::kLeAudioSamplingFreq24000Hz; case Lc3SettingId::LC3_32_1: case Lc3SettingId::LC3_32_2: - return ::bluetooth::le_audio::codec_spec_conf:: - kLeAudioSamplingFreq32000Hz; + return ::bluetooth::le_audio::codec_spec_conf::kLeAudioSamplingFreq32000Hz; case Lc3SettingId::LC3_441_1: case Lc3SettingId::LC3_441_2: - return ::bluetooth::le_audio::codec_spec_conf:: - kLeAudioSamplingFreq44100Hz; + return ::bluetooth::le_audio::codec_spec_conf::kLeAudioSamplingFreq44100Hz; case Lc3SettingId::LC3_48_1: case Lc3SettingId::LC3_48_2: case Lc3SettingId::LC3_48_3: @@ -338,8 +330,7 @@ uint8_t GetSamplingFrequency(Lc3SettingId id) { case Lc3SettingId::LC3_48_5: case Lc3SettingId::LC3_48_6: case Lc3SettingId::LC3_VND_1: - return ::bluetooth::le_audio::codec_spec_conf:: - kLeAudioSamplingFreq48000Hz; + return ::bluetooth::le_audio::codec_spec_conf::kLeAudioSamplingFreq48000Hz; case Lc3SettingId::UNSUPPORTED: return kLeAudioSamplingFreqRfu; } @@ -356,8 +347,7 @@ uint8_t GetFrameDuration(Lc3SettingId id) { case Lc3SettingId::LC3_48_1: case Lc3SettingId::LC3_48_3: case Lc3SettingId::LC3_48_5: - return ::bluetooth::le_audio::codec_spec_conf:: - kLeAudioCodecFrameDur7500us; + return ::bluetooth::le_audio::codec_spec_conf::kLeAudioCodecFrameDur7500us; case Lc3SettingId::LC3_8_2: case Lc3SettingId::LC3_16_2: case Lc3SettingId::LC3_24_2: @@ -367,8 +357,7 @@ uint8_t GetFrameDuration(Lc3SettingId id) { case Lc3SettingId::LC3_48_4: case Lc3SettingId::LC3_48_6: case Lc3SettingId::LC3_VND_1: - return ::bluetooth::le_audio::codec_spec_conf:: - kLeAudioCodecFrameDur10000us; + return ::bluetooth::le_audio::codec_spec_conf::kLeAudioCodecFrameDur10000us; case Lc3SettingId::UNSUPPORTED: return kLeAudioCodecFrameDurRfu; } @@ -414,84 +403,71 @@ uint16_t GetOctetsPerCodecFrame(Lc3SettingId id) { } class PublishedAudioCapabilitiesBuilder { - public: +public: PublishedAudioCapabilitiesBuilder() {} - void Add(LeAudioCodecId codec_id, uint8_t conf_sampling_frequency, - uint8_t conf_frame_duration, uint8_t audio_channel_counts, - uint16_t octets_per_frame, uint8_t codec_frames_per_sdu = 0) { - uint16_t sampling_frequencies = - SamplingFreqConfig2Capability(conf_sampling_frequency); - uint8_t frame_durations = - FrameDurationConfig2Capability(conf_frame_duration); + void Add(LeAudioCodecId codec_id, uint8_t conf_sampling_frequency, uint8_t conf_frame_duration, + uint8_t audio_channel_counts, uint16_t octets_per_frame, + uint8_t codec_frames_per_sdu = 0) { + uint16_t sampling_frequencies = SamplingFreqConfig2Capability(conf_sampling_frequency); + uint8_t frame_durations = FrameDurationConfig2Capability(conf_frame_duration); uint8_t max_codec_frames_per_sdu = codec_frames_per_sdu; - uint32_t octets_per_frame_range = - octets_per_frame | (octets_per_frame << 16); + uint32_t octets_per_frame_range = octets_per_frame | (octets_per_frame << 16); auto ltv_map = LeAudioLtvMap(); - ltv_map - .Add(kLeAudioLtvTypeSupportedSamplingFrequencies, - (uint16_t)sampling_frequencies) - .Add(kLeAudioLtvTypeSupportedFrameDurations, (uint8_t)frame_durations) - .Add(kLeAudioLtvTypeSupportedAudioChannelCounts, - (uint8_t)audio_channel_counts) - .Add(kLeAudioLtvTypeSupportedOctetsPerCodecFrame, - (uint32_t)octets_per_frame_range) - .Add(kLeAudioLtvTypeSupportedMaxCodecFramesPerSdu, - (uint8_t)max_codec_frames_per_sdu); + ltv_map.Add(kLeAudioLtvTypeSupportedSamplingFrequencies, (uint16_t)sampling_frequencies) + .Add(kLeAudioLtvTypeSupportedFrameDurations, (uint8_t)frame_durations) + .Add(kLeAudioLtvTypeSupportedAudioChannelCounts, (uint8_t)audio_channel_counts) + .Add(kLeAudioLtvTypeSupportedOctetsPerCodecFrame, (uint32_t)octets_per_frame_range) + .Add(kLeAudioLtvTypeSupportedMaxCodecFramesPerSdu, (uint8_t)max_codec_frames_per_sdu); auto record = acs_ac_record( - {.codec_id = codec_id, - .codec_spec_caps = - (codec_id.coding_format != kLeAudioCodingFormatVendorSpecific - ? ltv_map - : LeAudioLtvMap()), - .codec_spec_caps_raw = ltv_map.RawPacket(), - .metadata = std::vector(0)}); + {.codec_id = codec_id, + .codec_spec_caps = (codec_id.coding_format != kLeAudioCodingFormatVendorSpecific + ? ltv_map + : LeAudioLtvMap()), + .codec_spec_caps_raw = ltv_map.RawPacket(), + .metadata = std::vector(0)}); pac_records_.push_back(record); } - void Add(LeAudioCodecId codec_id, uint16_t capa_sampling_frequency, - uint8_t capa_frame_duration, uint8_t audio_channel_counts, - uint16_t octets_per_frame_min, uint16_t ocets_per_frame_max, - uint8_t codec_frames_per_sdu = 1) { - uint32_t octets_per_frame_range = - octets_per_frame_min | (ocets_per_frame_max << 16); + void Add(LeAudioCodecId codec_id, uint16_t capa_sampling_frequency, uint8_t capa_frame_duration, + uint8_t audio_channel_counts, uint16_t octets_per_frame_min, + uint16_t ocets_per_frame_max, uint8_t codec_frames_per_sdu = 1) { + uint32_t octets_per_frame_range = octets_per_frame_min | (ocets_per_frame_max << 16); auto ltv_map = LeAudioLtvMap({ - {kLeAudioLtvTypeSupportedSamplingFrequencies, - UINT16_TO_VEC_UINT8(capa_sampling_frequency)}, - {kLeAudioLtvTypeSupportedFrameDurations, - UINT8_TO_VEC_UINT8(capa_frame_duration)}, - {kLeAudioLtvTypeSupportedAudioChannelCounts, - UINT8_TO_VEC_UINT8(audio_channel_counts)}, - {kLeAudioLtvTypeSupportedOctetsPerCodecFrame, - UINT32_TO_VEC_UINT8(octets_per_frame_range)}, - {kLeAudioLtvTypeSupportedMaxCodecFramesPerSdu, - UINT8_TO_VEC_UINT8(codec_frames_per_sdu)}, + {kLeAudioLtvTypeSupportedSamplingFrequencies, + UINT16_TO_VEC_UINT8(capa_sampling_frequency)}, + {kLeAudioLtvTypeSupportedFrameDurations, UINT8_TO_VEC_UINT8(capa_frame_duration)}, + {kLeAudioLtvTypeSupportedAudioChannelCounts, UINT8_TO_VEC_UINT8(audio_channel_counts)}, + {kLeAudioLtvTypeSupportedOctetsPerCodecFrame, + UINT32_TO_VEC_UINT8(octets_per_frame_range)}, + {kLeAudioLtvTypeSupportedMaxCodecFramesPerSdu, + UINT8_TO_VEC_UINT8(codec_frames_per_sdu)}, }); - pac_records_.push_back(acs_ac_record( - {.codec_id = codec_id, - // Transparent LTV map capabilities only for the LC3 codec - .codec_spec_caps = (codec_id.coding_format == kLeAudioCodingFormatLC3) - ? ltv_map - : LeAudioLtvMap(), - .codec_spec_caps_raw = ltv_map.RawPacket(), - .metadata = std::vector(0)})); + pac_records_.push_back( + acs_ac_record({.codec_id = codec_id, + // Transparent LTV map capabilities only for the LC3 codec + .codec_spec_caps = (codec_id.coding_format == kLeAudioCodingFormatLC3) + ? ltv_map + : LeAudioLtvMap(), + .codec_spec_caps_raw = ltv_map.RawPacket(), + .metadata = std::vector(0)})); } void Add(LeAudioCodecId codec_id, const std::vector& vendor_data, uint8_t audio_channel_counts) { - pac_records_.push_back(acs_ac_record( - {.codec_id = codec_id, - .codec_spec_caps = LeAudioLtvMap({ - {kLeAudioLtvTypeSupportedAudioChannelCounts, - UINT8_TO_VEC_UINT8(audio_channel_counts)}, - }), - // For now assume that vendor representation of codec capabilities - // equals the representation of codec settings - .codec_spec_caps_raw = vendor_data, - .metadata = std::vector(0)})); + pac_records_.push_back( + acs_ac_record({.codec_id = codec_id, + .codec_spec_caps = LeAudioLtvMap({ + {kLeAudioLtvTypeSupportedAudioChannelCounts, + UINT8_TO_VEC_UINT8(audio_channel_counts)}, + }), + // For now assume that vendor representation of codec capabilities + // equals the representation of codec settings + .codec_spec_caps_raw = vendor_data, + .metadata = std::vector(0)})); } void Add(const CodecConfigSetting& setting, uint8_t audio_channel_counts) { @@ -500,11 +476,9 @@ class PublishedAudioCapabilitiesBuilder { return; } - const LeAudioCoreCodecConfig core_config = - setting.params.GetAsCoreCodecConfig(); - Add(setting.id, *core_config.sampling_frequency, - *core_config.frame_duration, audio_channel_counts, - *core_config.octets_per_codec_frame); + const LeAudioCoreCodecConfig core_config = setting.params.GetAsCoreCodecConfig(); + Add(setting.id, *core_config.sampling_frequency, *core_config.frame_duration, + audio_channel_counts, *core_config.octets_per_codec_frame); } void Reset() { pac_records_.clear(); } @@ -513,7 +487,7 @@ class PublishedAudioCapabilitiesBuilder { return PublishedAudioCapabilities({{hdl_pair_nil, pac_records_}}); } - private: +private: std::vector pac_records_; }; @@ -527,10 +501,8 @@ struct TestGroupAseConfigurationData { uint8_t expected_active_channel_num_src; }; -class LeAudioAseConfigurationTest - : public Test, - public ::testing::WithParamInterface { - protected: +class LeAudioAseConfigurationTest : public Test, public ::testing::WithParamInterface { +protected: uint16_t codec_coding_format_ = 0x0000; void SetUp() override { @@ -544,40 +516,32 @@ class LeAudioAseConfigurationTest bluetooth::hci::testing::mock_controller_ = &controller_interface_; auto codec_location = ::bluetooth::le_audio::types::CodecLocation::HOST; - bluetooth::le_audio::AudioSetConfigurationProvider::Initialize( - codec_location); + bluetooth::le_audio::AudioSetConfigurationProvider::Initialize(codec_location); MockCsisClient::SetMockInstanceForTesting(&mock_csis_client_module_); - ON_CALL(mock_csis_client_module_, Get()) - .WillByDefault(Return(&mock_csis_client_module_)); - ON_CALL(mock_csis_client_module_, IsCsisClientRunning()) - .WillByDefault(Return(true)); - ON_CALL(mock_csis_client_module_, GetDeviceList(_)) - .WillByDefault(Invoke([this](int group_id) { return addresses_; })); - ON_CALL(mock_csis_client_module_, GetDesiredSize(_)) - .WillByDefault(Invoke([this](int group_id) { - return desired_group_size_ > 0 ? desired_group_size_ - : (int)(addresses_.size()); - })); + ON_CALL(mock_csis_client_module_, Get()).WillByDefault(Return(&mock_csis_client_module_)); + ON_CALL(mock_csis_client_module_, IsCsisClientRunning()).WillByDefault(Return(true)); + ON_CALL(mock_csis_client_module_, GetDeviceList(_)).WillByDefault(Invoke([this](int group_id) { + return addresses_; + })); + ON_CALL(mock_csis_client_module_, GetDesiredSize(_)).WillByDefault(Invoke([this](int group_id) { + return desired_group_size_ > 0 ? desired_group_size_ : (int)(addresses_.size()); + })); SetUpMockCodecManager(codec_location); } - static std::vector - GetVendorAseConfigurationsForRequirements( - const bluetooth::le_audio::CodecManager::UnicastConfigurationRequirements& - requirements, - const CodecConfigSetting& codec, uint8_t direction) { + static std::vector GetVendorAseConfigurationsForRequirements( + const bluetooth::le_audio::CodecManager::UnicastConfigurationRequirements& requirements, + const CodecConfigSetting& codec, uint8_t direction) { std::vector ase_confs; - auto const& required_pacs = (direction == kLeAudioDirectionSink) - ? requirements.sink_pacs - : requirements.source_pacs; + auto const& required_pacs = (direction == kLeAudioDirectionSink) ? requirements.sink_pacs + : requirements.source_pacs; auto direction_requirements = (direction == kLeAudioDirectionSink) - ? requirements.sink_requirements - : requirements.source_requirements; + ? requirements.sink_requirements + : requirements.source_requirements; - if (std::count_if( - required_pacs->begin(), required_pacs->end(), - [](auto const& pac) { return pac.codec_spec_caps_raw.empty(); })) { + if (std::count_if(required_pacs->begin(), required_pacs->end(), + [](auto const& pac) { return pac.codec_spec_caps_raw.empty(); })) { return ase_confs; } @@ -585,14 +549,12 @@ class LeAudioAseConfigurationTest return ase_confs; } - AseConfiguration endpoint_cfg( - codec, {.target_latency = kTargetLatencyLower, - .retransmission_number = 3, - .max_transport_latency = kMaxTransportLatencyMin}); + AseConfiguration endpoint_cfg(codec, {.target_latency = kTargetLatencyLower, + .retransmission_number = 3, + .max_transport_latency = kMaxTransportLatencyMin}); // Finding the max channel count - uint32_t target_max_channel_counts_per_ase_bitmap = - 0b1; // bit 0 - one channel + uint32_t target_max_channel_counts_per_ase_bitmap = 0b1; // bit 0 - one channel for (auto const& pac : *required_pacs) { auto caps = pac.codec_spec_caps.GetAsCoreCodecCapabilities(); if (caps.HasSupportedAudioChannelCounts()) { @@ -606,25 +568,22 @@ class LeAudioAseConfigurationTest uint8_t target_max_channel_counts_per_ase = 0; while (target_max_channel_counts_per_ase_bitmap) { ++target_max_channel_counts_per_ase; - target_max_channel_counts_per_ase_bitmap = - target_max_channel_counts_per_ase_bitmap >> 1; + target_max_channel_counts_per_ase_bitmap = target_max_channel_counts_per_ase_bitmap >> 1; } // For sink we always put a requirement here, but for source there are // some conditions auto sourceAsesNeeded = - (!kLeAudioContextAllRemoteSinkOnly.test( - requirements.audio_context_type) || - (requirements.audio_context_type == LeAudioContextType::RINGTONE)) && - (requirements.audio_context_type != - types::LeAudioContextType::UNSPECIFIED); + (!kLeAudioContextAllRemoteSinkOnly.test(requirements.audio_context_type) || + (requirements.audio_context_type == LeAudioContextType::RINGTONE)) && + (requirements.audio_context_type != types::LeAudioContextType::UNSPECIFIED); if ((direction == kLeAudioDirectionSink) || sourceAsesNeeded) { // Create ASE configurations with the proper audio channel allocation uint8_t count = 0; uint32_t allocations = 0; for (auto const& req : *direction_requirements) { - auto req_allocations = VEC_UINT8_TO_UINT32(req.params.At( - codec_spec_conf::kLeAudioLtvTypeAudioChannelAllocation)); + auto req_allocations = VEC_UINT8_TO_UINT32( + req.params.At(codec_spec_conf::kLeAudioLtvTypeAudioChannelAllocation)); // Create the list of requested audio allocations std::list split_allocations; @@ -641,12 +600,10 @@ class LeAudioAseConfigurationTest // channel counts per ASE) and create an ASE configuration. while (split_allocations.size()) { auto num_of_allocations_per_ase = - std::min(target_max_channel_counts_per_ase, - (uint8_t)split_allocations.size()); + std::min(target_max_channel_counts_per_ase, (uint8_t)split_allocations.size()); // Note: This is very important to set for the unit test // Configuration verifier - endpoint_cfg.codec.channel_count_per_iso_stream = - num_of_allocations_per_ase; + endpoint_cfg.codec.channel_count_per_iso_stream = num_of_allocations_per_ase; // Consume the `num_of_allocations_per_ase` amount of allocations for // this particular ASE @@ -656,9 +613,8 @@ class LeAudioAseConfigurationTest split_allocations.pop_front(); --num_of_allocations_per_ase; } - endpoint_cfg.codec.params.Add( - codec_spec_conf::kLeAudioLtvTypeAudioChannelAllocation, - ase_allocations); + endpoint_cfg.codec.params.Add(codec_spec_conf::kLeAudioLtvTypeAudioChannelAllocation, + ase_allocations); // Add the ASE configuration ase_confs.push_back(endpoint_cfg); @@ -670,101 +626,98 @@ class LeAudioAseConfigurationTest } static auto MockVendorCodecProvider( - const bluetooth::le_audio::CodecManager::UnicastConfigurationRequirements& - requirements) { + const bluetooth::le_audio::CodecManager::UnicastConfigurationRequirements& requirements) { AudioSetConfiguration cfg = { - .name = "Example Vendor Codec Configuration", - .packing = bluetooth::hci::kIsoCigPackingSequential, - .confs = {.sink = {}, .source = {}}, + .name = "Example Vendor Codec Configuration", + .packing = bluetooth::hci::kIsoCigPackingSequential, + .confs = {.sink = {}, .source = {}}, }; - CodecConfigSetting codec = bluetooth::le_audio::CodecManager::GetInstance() - ->IsDualBiDirSwbSupported() - ? kVendorCodecOneSwb - : kVendorCodecOne; + CodecConfigSetting codec = + bluetooth::le_audio::CodecManager::GetInstance()->IsDualBiDirSwbSupported() + ? kVendorCodecOneSwb + : kVendorCodecOne; if (requirements.sink_requirements) { - cfg.confs.sink = GetVendorAseConfigurationsForRequirements( - requirements, codec, kLeAudioDirectionSink); + cfg.confs.sink = + GetVendorAseConfigurationsForRequirements(requirements, codec, kLeAudioDirectionSink); } if (requirements.source_requirements) { - cfg.confs.source = GetVendorAseConfigurationsForRequirements( - requirements, codec, kLeAudioDirectionSource); + cfg.confs.source = GetVendorAseConfigurationsForRequirements(requirements, codec, + kLeAudioDirectionSource); } log::debug("snk confs size: {}", cfg.confs.sink.size()); log::debug("src confs size: {}", cfg.confs.source.size()); return (!cfg.confs.sink.empty() || !cfg.confs.source.empty()) - ? std::make_unique(cfg) - : nullptr; + ? std::make_unique(cfg) + : nullptr; } - void SetUpMockCodecManager( - bluetooth::le_audio::types::CodecLocation location) { + void SetUpMockCodecManager(bluetooth::le_audio::types::CodecLocation location) { codec_manager_ = bluetooth::le_audio::CodecManager::GetInstance(); ASSERT_NE(codec_manager_, nullptr); - std::vector - mock_offloading_preference(0); + std::vector mock_offloading_preference(0); codec_manager_->Start(mock_offloading_preference); mock_codec_manager_ = MockCodecManager::GetInstance(); ASSERT_NE((void*)mock_codec_manager_, (void*)codec_manager_); ASSERT_NE(mock_codec_manager_, nullptr); - ON_CALL(*mock_codec_manager_, GetCodecLocation()) - .WillByDefault(Return(location)); + ON_CALL(*mock_codec_manager_, GetCodecLocation()).WillByDefault(Return(location)); // Set up the config provider for the Lc3 codec if (codec_coding_format_ == kLeAudioCodingFormatLC3) { // Regardless of the codec location, return all the possible // configurations - ON_CALL(*mock_codec_manager_, IsDualBiDirSwbSupported) - .WillByDefault(Return(true)); + ON_CALL(*mock_codec_manager_, IsDualBiDirSwbSupported).WillByDefault(Return(true)); } ON_CALL(*mock_codec_manager_, GetCodecConfig) - .WillByDefault(Invoke( - [&](const bluetooth::le_audio::CodecManager:: - UnicastConfigurationRequirements& requirements, - bluetooth::le_audio::CodecManager::UnicastConfigurationVerifier - verifier) { - if (codec_coding_format_ == kLeAudioCodingFormatLC3) { - auto filtered = - *bluetooth::le_audio::AudioSetConfigurationProvider::Get() - ->GetConfigurations(requirements.audio_context_type); - // Filter out the dual bidir SWB configurations - if (!bluetooth::le_audio::CodecManager::GetInstance() - ->IsDualBiDirSwbSupported()) { - filtered.erase( - std::remove_if( - filtered.begin(), filtered.end(), - [](auto const& el) { - if (el->confs.source.empty()) return false; - return AudioSetConfigurationProvider::Get() - ->CheckConfigurationIsDualBiDirSwb(*el); - }), - filtered.end()); - } - auto cfg = verifier(requirements, &filtered); - if (cfg == nullptr) { - return std::unique_ptr(nullptr); - } - return std::make_unique(*cfg); - } else { - return MockVendorCodecProvider(requirements); - } - })); + .WillByDefault(Invoke( + [&](const bluetooth::le_audio::CodecManager::UnicastConfigurationRequirements& + requirements, + bluetooth::le_audio::CodecManager::UnicastConfigurationVerifier verifier) { + if (codec_coding_format_ == kLeAudioCodingFormatLC3) { + auto filtered = + *bluetooth::le_audio::AudioSetConfigurationProvider::Get() + ->GetConfigurations(requirements.audio_context_type); + // Filter out the dual bidir SWB configurations + if (!bluetooth::le_audio::CodecManager::GetInstance() + ->IsDualBiDirSwbSupported()) { + filtered.erase( + std::remove_if(filtered.begin(), filtered.end(), + [](auto const& el) { + if (el->confs.source.empty()) { + return false; + } + return AudioSetConfigurationProvider::Get() + ->CheckConfigurationIsDualBiDirSwb(*el); + }), + filtered.end()); + } + auto cfg = verifier(requirements, &filtered); + if (cfg == nullptr) { + return std::unique_ptr(nullptr); + } + return std::make_unique(*cfg); + } else { + return MockVendorCodecProvider(requirements); + } + })); ON_CALL(*mock_codec_manager_, CheckCodecConfigIsBiDirSwb) - .WillByDefault(Invoke([](const bluetooth::le_audio::set_configurations:: - AudioSetConfiguration& config) { - return AudioSetConfigurationProvider::Get() - ->CheckConfigurationIsBiDirSwb(config); - })); + .WillByDefault( + Invoke([](const bluetooth::le_audio::set_configurations::AudioSetConfiguration& + config) { + return AudioSetConfigurationProvider::Get()->CheckConfigurationIsBiDirSwb( + config); + })); ON_CALL(*mock_codec_manager_, CheckCodecConfigIsDualBiDirSwb) - .WillByDefault(Invoke([](const bluetooth::le_audio::set_configurations:: - AudioSetConfiguration& config) { - return AudioSetConfigurationProvider::Get() - ->CheckConfigurationIsDualBiDirSwb(config); - })); + .WillByDefault( + Invoke([](const bluetooth::le_audio::set_configurations::AudioSetConfiguration& + config) { + return AudioSetConfigurationProvider::Get()->CheckConfigurationIsDualBiDirSwb( + config); + })); } void TearDown() override { @@ -783,16 +736,15 @@ class LeAudioAseConfigurationTest } LeAudioDevice* AddTestDevice( - int snk_ase_num, int src_ase_num, int snk_ase_num_cached = 0, - int src_ase_num_cached = 0, bool invert_ases_emplacement = false, - bool out_of_range_device = false, - uint8_t snk_allocation = codec_spec_conf::kLeAudioLocationFrontLeft | - codec_spec_conf::kLeAudioLocationFrontRight, - uint8_t src_allocation = codec_spec_conf::kLeAudioLocationFrontLeft | - codec_spec_conf::kLeAudioLocationFrontRight) { + int snk_ase_num, int src_ase_num, int snk_ase_num_cached = 0, int src_ase_num_cached = 0, + bool invert_ases_emplacement = false, bool out_of_range_device = false, + uint8_t snk_allocation = codec_spec_conf::kLeAudioLocationFrontLeft | + codec_spec_conf::kLeAudioLocationFrontRight, + uint8_t src_allocation = codec_spec_conf::kLeAudioLocationFrontLeft | + codec_spec_conf::kLeAudioLocationFrontRight) { int index = group_->Size() + 1; - auto device = (std::make_shared( - GetTestAddress(index), DeviceConnectState::DISCONNECTED)); + auto device = (std::make_shared(GetTestAddress(index), + DeviceConnectState::DISCONNECTED)); devices_.push_back(device); addresses_.push_back(device->address_); log::info("Number of devices {}", (int)(addresses_.size())); @@ -802,70 +754,59 @@ class LeAudioAseConfigurationTest } int ase_id = 1; - for (int i = 0; i < (invert_ases_emplacement ? snk_ase_num : src_ase_num); - i++) { - device->ases_.emplace_back(0x0000, 0x0000, - invert_ases_emplacement - ? kLeAudioDirectionSink - : kLeAudioDirectionSource, - ase_id++); + for (int i = 0; i < (invert_ases_emplacement ? snk_ase_num : src_ase_num); i++) { + device->ases_.emplace_back( + 0x0000, 0x0000, + invert_ases_emplacement ? kLeAudioDirectionSink : kLeAudioDirectionSource, ase_id++); } - for (int i = 0; i < (invert_ases_emplacement ? src_ase_num : snk_ase_num); - i++) { - device->ases_.emplace_back(0x0000, 0x0000, - invert_ases_emplacement - ? kLeAudioDirectionSource - : kLeAudioDirectionSink, - ase_id++); + for (int i = 0; i < (invert_ases_emplacement ? src_ase_num : snk_ase_num); i++) { + device->ases_.emplace_back( + 0x0000, 0x0000, + invert_ases_emplacement ? kLeAudioDirectionSource : kLeAudioDirectionSink, ase_id++); } - for (int i = 0; i < (invert_ases_emplacement ? snk_ase_num_cached - : src_ase_num_cached); - i++) { + for (int i = 0; i < (invert_ases_emplacement ? snk_ase_num_cached : src_ase_num_cached); i++) { struct ase ase(0x0000, 0x0000, - invert_ases_emplacement ? kLeAudioDirectionSink - : kLeAudioDirectionSource, + invert_ases_emplacement ? kLeAudioDirectionSink : kLeAudioDirectionSource, ase_id++); ase.state = AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED; device->ases_.push_back(ase); } - for (int i = 0; i < (invert_ases_emplacement ? src_ase_num_cached - : snk_ase_num_cached); - i++) { + for (int i = 0; i < (invert_ases_emplacement ? src_ase_num_cached : snk_ase_num_cached); i++) { struct ase ase(0x0000, 0x0000, - invert_ases_emplacement ? kLeAudioDirectionSource - : kLeAudioDirectionSink, + invert_ases_emplacement ? kLeAudioDirectionSource : kLeAudioDirectionSink, ase_id++); ase.state = AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED; device->ases_.push_back(ase); } - device->SetSupportedContexts( - {.sink = AudioContexts(kLeAudioContextAllTypes), - .source = AudioContexts(kLeAudioContextAllTypes)}); - device->SetAvailableContexts( - {.sink = AudioContexts(kLeAudioContextAllTypes), - .source = AudioContexts(kLeAudioContextAllTypes)}); + device->SetSupportedContexts({.sink = AudioContexts(kLeAudioContextAllTypes), + .source = AudioContexts(kLeAudioContextAllTypes)}); + device->SetAvailableContexts({.sink = AudioContexts(kLeAudioContextAllTypes), + .source = AudioContexts(kLeAudioContextAllTypes)}); device->snk_audio_locations_ = snk_allocation; device->src_audio_locations_ = src_allocation; device->conn_id_ = index; - device->SetConnectionState(out_of_range_device - ? DeviceConnectState::DISCONNECTED - : DeviceConnectState::CONNECTED); + device->SetConnectionState(out_of_range_device ? DeviceConnectState::DISCONNECTED + : DeviceConnectState::CONNECTED); group_->ReloadAudioDirections(); group_->ReloadAudioLocations(); return device.get(); } - bool TestGroupAseConfigurationVerdict( - const TestGroupAseConfigurationData& data, uint8_t directions_to_verify) { + bool TestGroupAseConfigurationVerdict(const TestGroupAseConfigurationData& data, + uint8_t directions_to_verify) { BidirectionalPair active_channel_num = {0, 0}; - if (directions_to_verify == 0) return false; - if (data.device->HaveActiveAse() == 0) return false; + if (directions_to_verify == 0) { + return false; + } + if (data.device->HaveActiveAse() == 0) { + return false; + } for (ase* ase = data.device->GetFirstActiveAse(); ase; ase = data.device->GetNextActiveAse(ase)) { @@ -899,8 +840,7 @@ class LeAudioAseConfigurationTest } void TestSingleAseConfiguration(LeAudioContextType context_type, - TestGroupAseConfigurationData* data, - uint8_t data_size, + TestGroupAseConfigurationData* data, uint8_t data_size, const AudioSetConfiguration* audio_set_conf, uint8_t directions_to_verify) { // the configuration should fail if there are no active ases expected @@ -927,34 +867,30 @@ class LeAudioAseConfigurationTest } BidirectionalPair group_audio_locations = { - .sink = AudioContexts(context_type), - .source = AudioContexts(context_type)}; + .sink = AudioContexts(context_type), .source = AudioContexts(context_type)}; /* Stimulate update of available context map */ group_->UpdateAudioContextAvailability(); - ASSERT_EQ(success_expected, - group_->Configure(context_type, group_audio_locations)); + ASSERT_EQ(success_expected, group_->Configure(context_type, group_audio_locations)); bool result = true; for (int i = 0; i < data_size; i++) { - result &= TestGroupAseConfigurationVerdict( - data[i], directions_to_verify & configuration_directions); + result &= TestGroupAseConfigurationVerdict(data[i], + directions_to_verify & configuration_directions); } ASSERT_TRUE(result); } int getNumOfAses(LeAudioDevice* device, uint8_t direction) { - return std::count_if( - device->ases_.begin(), device->ases_.end(), - [direction](auto& a) { return a.direction == direction; }); + return std::count_if(device->ases_.begin(), device->ases_.end(), + [direction](auto& a) { return a.direction == direction; }); } - void TestGroupAseVendorConfiguration( - LeAudioContextType context_type, TestGroupAseConfigurationData* data, - uint8_t data_size, - uint8_t directions_to_verify = kLeAudioDirectionSink | - kLeAudioDirectionSource) { + void TestGroupAseVendorConfiguration(LeAudioContextType context_type, + TestGroupAseConfigurationData* data, uint8_t data_size, + uint8_t directions_to_verify = kLeAudioDirectionSink | + kLeAudioDirectionSource) { for (int i = 0; i < data_size; i++) { /* Add PACs and check if each of the devices has activated ASEs as * expected */ @@ -962,10 +898,9 @@ class LeAudioAseConfigurationTest // Prepare the PACs for (auto direction : {kLeAudioDirectionSink, kLeAudioDirectionSource}) { - auto const& data_channel_counts = - (direction == kLeAudioDirectionSink) - ? data[i].audio_channel_counts_snk - : data[i].audio_channel_counts_src; + auto const& data_channel_counts = (direction == kLeAudioDirectionSink) + ? data[i].audio_channel_counts_snk + : data[i].audio_channel_counts_src; PublishedAudioCapabilitiesBuilder pac_builder; for (auto codec : {kVendorCodecOne, kVendorCodecOneSwb}) { @@ -974,41 +909,36 @@ class LeAudioAseConfigurationTest } // Set the PACs - auto& dest_pacs = (direction == kLeAudioDirectionSink) - ? data[i].device->snk_pacs_ - : data[i].device->src_pacs_; + auto& dest_pacs = (direction == kLeAudioDirectionSink) ? data[i].device->snk_pacs_ + : data[i].device->src_pacs_; dest_pacs = pac_builder.Get(); } } // Verify if ASEs are configured - BidirectionalPair metadata = { - .sink = AudioContexts(context_type), - .source = AudioContexts(context_type)}; + BidirectionalPair metadata = {.sink = AudioContexts(context_type), + .source = AudioContexts(context_type)}; ASSERT_EQ(true, group_->Configure(context_type, metadata)); for (int i = 0; i < data_size; i++) { - ASSERT_TRUE( - TestGroupAseConfigurationVerdict(data[i], directions_to_verify)); + ASSERT_TRUE(TestGroupAseConfigurationVerdict(data[i], directions_to_verify)); } group_->Deactivate(); TestAsesInactive(); } - void TestGroupAseConfiguration( - LeAudioContextType context_type, TestGroupAseConfigurationData* data, - uint8_t data_size, - uint8_t directions_to_verify = kLeAudioDirectionSink | - kLeAudioDirectionSource) { + void TestGroupAseConfiguration(LeAudioContextType context_type, + TestGroupAseConfigurationData* data, uint8_t data_size, + uint8_t directions_to_verify = kLeAudioDirectionSink | + kLeAudioDirectionSource) { if (codec_coding_format_ != kLeAudioCodingFormatLC3) { - return TestGroupAseVendorConfiguration(context_type, data, data_size, - directions_to_verify); + return TestGroupAseVendorConfiguration(context_type, data, data_size, directions_to_verify); } const auto* configurations = - ::bluetooth::le_audio::AudioSetConfigurationProvider::Get() - ->GetConfigurations(context_type); + ::bluetooth::le_audio::AudioSetConfigurationProvider::Get()->GetConfigurations( + context_type); bool success_expected = directions_to_verify != 0; int num_of_matching_configurations = 0; @@ -1027,11 +957,9 @@ class LeAudioAseConfigurationTest /* Prepare PAC's for each device. Also make sure configuration is in our * interest to test */ - for (auto direction : - {kLeAudioDirectionSink, kLeAudioDirectionSource}) { + for (auto direction : {kLeAudioDirectionSink, kLeAudioDirectionSource}) { auto const& ase_confs = audio_set_conf->confs.get(direction); - auto strategy = bluetooth::le_audio::utils::GetStrategyForAseConfig( - ase_confs, data_size); + auto strategy = bluetooth::le_audio::utils::GetStrategyForAseConfig(ase_confs, data_size); auto const ase_cnt = ase_confs.size(); if (ase_cnt == 0) { @@ -1040,8 +968,7 @@ class LeAudioAseConfigurationTest } /* Make sure the strategy is the expected one */ - if (direction == kLeAudioDirectionSink && - group_->GetGroupSinkStrategy() != strategy) { + if (direction == kLeAudioDirectionSink && group_->GetGroupSinkStrategy() != strategy) { log::debug("Sink strategy mismatch group!=cfg.entry ({}!={})", static_cast(group_->GetGroupSinkStrategy()), static_cast(strategy)); @@ -1050,16 +977,13 @@ class LeAudioAseConfigurationTest configuration_directions |= direction; - auto& pac_builder = (direction == kLeAudioDirectionSink) - ? snk_pac_builder - : src_pac_builder; - auto& dest_pacs = (direction == kLeAudioDirectionSink) - ? data[i].device->snk_pacs_ - : data[i].device->src_pacs_; - auto const& data_channel_counts = - (direction == kLeAudioDirectionSink) - ? data[i].audio_channel_counts_snk - : data[i].audio_channel_counts_src; + auto& pac_builder = + (direction == kLeAudioDirectionSink) ? snk_pac_builder : src_pac_builder; + auto& dest_pacs = (direction == kLeAudioDirectionSink) ? data[i].device->snk_pacs_ + : data[i].device->src_pacs_; + auto const& data_channel_counts = (direction == kLeAudioDirectionSink) + ? data[i].audio_channel_counts_snk + : data[i].audio_channel_counts_src; for (const auto& entry : ase_confs) { num_of_ase.get(direction)++; @@ -1070,42 +994,38 @@ class LeAudioAseConfigurationTest } /* Make sure configuration can satisfy number of expected active ASEs*/ - if (num_of_ase.sink > - data[i].device->GetAseCount(kLeAudioDirectionSink)) { + if (num_of_ase.sink > data[i].device->GetAseCount(kLeAudioDirectionSink)) { interesting_configuration = false; } - if (num_of_ase.source > - data[i].device->GetAseCount(kLeAudioDirectionSource)) { + if (num_of_ase.source > data[i].device->GetAseCount(kLeAudioDirectionSource)) { interesting_configuration = false; } } BidirectionalPair group_audio_locations = { - .sink = AudioContexts(context_type), - .source = AudioContexts(context_type)}; + .sink = AudioContexts(context_type), .source = AudioContexts(context_type)}; /* Stimulate update of available context map */ group_->UpdateAudioContextAvailability(); group_->UpdateAudioSetConfigurationCache(context_type); - auto configuration_result = - group_->Configure(context_type, group_audio_locations); + auto configuration_result = group_->Configure(context_type, group_audio_locations); /* In case of configuration #ase is same as the one we expected to be * activated verify, ASEs are actually active */ - if (interesting_configuration && - (directions_to_verify == configuration_directions)) { + if (interesting_configuration && (directions_to_verify == configuration_directions)) { ASSERT_TRUE(configuration_result); bool matching_conf = true; /* Check if each of the devices has activated ASEs as expected */ for (int i = 0; i < data_size; i++) { - matching_conf &= TestGroupAseConfigurationVerdict( - data[i], configuration_directions); + matching_conf &= TestGroupAseConfigurationVerdict(data[i], configuration_directions); } - if (matching_conf) num_of_matching_configurations++; + if (matching_conf) { + num_of_matching_configurations++; + } } group_->Deactivate(); @@ -1113,23 +1033,26 @@ class LeAudioAseConfigurationTest } if (success_expected) { - ASSERT_TRUE((num_of_matching_configurations > 0)); + ASSERT_TRUE(num_of_matching_configurations > 0); } else { ASSERT_TRUE(num_of_matching_configurations == 0); } } - void TestAsesActive(LeAudioCodecId codec_id, uint8_t sampling_frequency, - uint8_t frame_duration, uint16_t octets_per_frame, - uint8_t codec_frame_blocks_per_sdu = 1) { + void TestAsesActive(LeAudioCodecId codec_id, uint8_t sampling_frequency, uint8_t frame_duration, + uint16_t octets_per_frame, uint8_t codec_frame_blocks_per_sdu = 1) { bool active_ase = false; for (const auto& device : devices_) { for (const auto& ase : device->ases_) { - if (!ase.active) continue; + if (!ase.active) { + continue; + } /* Configure may request only partial ases to be activated */ - if (!active_ase && ase.active) active_ase = true; + if (!active_ase && ase.active) { + active_ase = true; + } ASSERT_EQ(ase.codec_id, codec_id); @@ -1175,15 +1098,14 @@ class LeAudioAseConfigurationTest } } - void TestLc3CodecConfig(LeAudioContextType context_type, - uint8_t max_codec_frames_per_sdu = 1) { + void TestLc3CodecConfig(LeAudioContextType context_type, uint8_t max_codec_frames_per_sdu = 1) { for (int i = Lc3SettingIdBegin; i < Lc3SettingIdEnd; i++) { // test each configuration parameter against valid and invalid value std::array test_variants = {static_cast(i), Lc3SettingId::UNSUPPORTED}; const bool is_lc3_setting_supported = - IsLc3SettingSupported(context_type, static_cast(i)); + IsLc3SettingSupported(context_type, static_cast(i)); for (const auto sf_variant : test_variants) { uint8_t sampling_frequency = GetSamplingFrequency(sf_variant); @@ -1193,11 +1115,10 @@ class LeAudioAseConfigurationTest uint16_t octets_per_frame = GetOctetsPerCodecFrame(opcf_variant); PublishedAudioCapabilitiesBuilder pac_builder; - pac_builder.Add(LeAudioCodecIdLc3, sampling_frequency, - frame_duration, - kLeAudioCodecChannelCountSingleChannel | - kLeAudioCodecChannelCountTwoChannel, - octets_per_frame, max_codec_frames_per_sdu); + pac_builder.Add( + LeAudioCodecIdLc3, sampling_frequency, frame_duration, + kLeAudioCodecChannelCountSingleChannel | kLeAudioCodecChannelCountTwoChannel, + octets_per_frame, max_codec_frames_per_sdu); for (auto& device : devices_) { /* For simplicity configure both PACs with the same parameters*/ @@ -1206,10 +1127,9 @@ class LeAudioAseConfigurationTest } bool success_expected = is_lc3_setting_supported; - if (is_lc3_setting_supported && - (sf_variant == Lc3SettingId::UNSUPPORTED || - fd_variant == Lc3SettingId::UNSUPPORTED || - opcf_variant == Lc3SettingId::UNSUPPORTED)) { + if (is_lc3_setting_supported && (sf_variant == Lc3SettingId::UNSUPPORTED || + fd_variant == Lc3SettingId::UNSUPPORTED || + opcf_variant == Lc3SettingId::UNSUPPORTED)) { success_expected = false; } @@ -1217,14 +1137,11 @@ class LeAudioAseConfigurationTest group_->UpdateAudioContextAvailability(); group_->UpdateAudioSetConfigurationCache(context_type); BidirectionalPair group_audio_locations = { - .sink = AudioContexts(context_type), - .source = AudioContexts(context_type)}; - ASSERT_EQ(success_expected, - group_->Configure(context_type, group_audio_locations)); + .sink = AudioContexts(context_type), .source = AudioContexts(context_type)}; + ASSERT_EQ(success_expected, group_->Configure(context_type, group_audio_locations)); if (success_expected) { - TestAsesActive(LeAudioCodecIdLc3, sampling_frequency, - frame_duration, octets_per_frame, - max_codec_frames_per_sdu); + TestAsesActive(LeAudioCodecIdLc3, sampling_frequency, frame_duration, + octets_per_frame, max_codec_frames_per_sdu); group_->Deactivate(); } @@ -1235,8 +1152,7 @@ class LeAudioAseConfigurationTest } } - void TestSingleDevDualBidir(LeAudioDevice* device, - LeAudioContextType context_type) { + void TestSingleDevDualBidir(LeAudioDevice* device, LeAudioContextType context_type) { // Build PACs for device PublishedAudioCapabilitiesBuilder snk_pac_builder, src_pac_builder; snk_pac_builder.Reset(); @@ -1246,105 +1162,93 @@ class LeAudioAseConfigurationTest const uint32_t supported_octets_per_codec_frame_40 = 40; const uint32_t supported_codec_frames_per_sdu = 1; CodecConfigSetting swb = { - .id = LeAudioCodecIdLc3, - .params = LeAudioLtvMap({ - {codec_spec_conf::kLeAudioLtvTypeSamplingFreq, - UINT8_TO_VEC_UINT8(codec_spec_conf::kLeAudioSamplingFreq32000Hz)}, - {codec_spec_conf::kLeAudioLtvTypeFrameDuration, - UINT8_TO_VEC_UINT8(codec_spec_conf::kLeAudioCodecFrameDur10000us)}, - {codec_spec_conf::kLeAudioLtvTypeOctetsPerCodecFrame, - UINT16_TO_VEC_UINT8(supported_octets_per_codec_frame_80)}, - {codec_spec_conf::kLeAudioLtvTypeCodecFrameBlocksPerSdu, - UINT8_TO_VEC_UINT8(supported_codec_frames_per_sdu)}, - }), - .channel_count_per_iso_stream = 1}; + .id = LeAudioCodecIdLc3, + .params = LeAudioLtvMap({ + {codec_spec_conf::kLeAudioLtvTypeSamplingFreq, + UINT8_TO_VEC_UINT8(codec_spec_conf::kLeAudioSamplingFreq32000Hz)}, + {codec_spec_conf::kLeAudioLtvTypeFrameDuration, + UINT8_TO_VEC_UINT8(codec_spec_conf::kLeAudioCodecFrameDur10000us)}, + {codec_spec_conf::kLeAudioLtvTypeOctetsPerCodecFrame, + UINT16_TO_VEC_UINT8(supported_octets_per_codec_frame_80)}, + {codec_spec_conf::kLeAudioLtvTypeCodecFrameBlocksPerSdu, + UINT8_TO_VEC_UINT8(supported_codec_frames_per_sdu)}, + }), + .channel_count_per_iso_stream = 1}; auto swb_config = AudioSetConfiguration({ - .name = "Two-OneChan-SnkAse-Lc3_32_2-Two-OneChan-SrcAse-Lc3_32_2_SWB", - .confs = {.sink = {AseConfiguration(swb), AseConfiguration(swb)}, - .source = {AseConfiguration(swb), AseConfiguration(swb)}}, + .name = "Two-OneChan-SnkAse-Lc3_32_2-Two-OneChan-SrcAse-Lc3_32_2_SWB", + .confs = {.sink = {AseConfiguration(swb), AseConfiguration(swb)}, + .source = {AseConfiguration(swb), AseConfiguration(swb)}}, }); auto swb_config_single = AudioSetConfiguration({ - .name = "One-OneChan-SnkAse-Lc3_32_2-One-OneChan-SrcAse-Lc3_32_2_SWB", - .confs = {.sink = - { - AseConfiguration(swb), - }, - .source = - { - AseConfiguration(swb), - }}, + .name = "One-OneChan-SnkAse-Lc3_32_2-One-OneChan-SrcAse-Lc3_32_2_SWB", + .confs = {.sink = + { + AseConfiguration(swb), + }, + .source = + { + AseConfiguration(swb), + }}, }); ASSERT_FALSE(swb.params.IsEmpty()); - ASSERT_TRUE(swb.params.Find(codec_spec_conf::kLeAudioLtvTypeSamplingFreq) - .has_value()); + ASSERT_TRUE(swb.params.Find(codec_spec_conf::kLeAudioLtvTypeSamplingFreq).has_value()); CodecConfigSetting non_swb = { - .id = LeAudioCodecIdLc3, - .params = LeAudioLtvMap({ - {codec_spec_conf::kLeAudioLtvTypeSamplingFreq, - UINT8_TO_VEC_UINT8(codec_spec_conf::kLeAudioSamplingFreq16000Hz)}, - {codec_spec_conf::kLeAudioLtvTypeFrameDuration, - UINT8_TO_VEC_UINT8(codec_spec_conf::kLeAudioCodecFrameDur10000us)}, - {codec_spec_conf::kLeAudioLtvTypeOctetsPerCodecFrame, - UINT16_TO_VEC_UINT8(supported_octets_per_codec_frame_40)}, - {codec_spec_conf::kLeAudioLtvTypeCodecFrameBlocksPerSdu, - UINT8_TO_VEC_UINT8(supported_codec_frames_per_sdu)}, - }), - .channel_count_per_iso_stream = 1}; + .id = LeAudioCodecIdLc3, + .params = LeAudioLtvMap({ + {codec_spec_conf::kLeAudioLtvTypeSamplingFreq, + UINT8_TO_VEC_UINT8(codec_spec_conf::kLeAudioSamplingFreq16000Hz)}, + {codec_spec_conf::kLeAudioLtvTypeFrameDuration, + UINT8_TO_VEC_UINT8(codec_spec_conf::kLeAudioCodecFrameDur10000us)}, + {codec_spec_conf::kLeAudioLtvTypeOctetsPerCodecFrame, + UINT16_TO_VEC_UINT8(supported_octets_per_codec_frame_40)}, + {codec_spec_conf::kLeAudioLtvTypeCodecFrameBlocksPerSdu, + UINT8_TO_VEC_UINT8(supported_codec_frames_per_sdu)}, + }), + .channel_count_per_iso_stream = 1}; auto non_swb_config = AudioSetConfiguration({ - .name = - "Two-OneChan-SnkAse-Lc3_16_2-Two-OneChan-SrcAse-Lc3_16_2_NON_SWB", - .confs = {.sink = {AseConfiguration(non_swb), - AseConfiguration(non_swb)}, - .source = {AseConfiguration(non_swb), - AseConfiguration(non_swb)}}, + .name = "Two-OneChan-SnkAse-Lc3_16_2-Two-OneChan-SrcAse-Lc3_16_2_NON_SWB", + .confs = {.sink = {AseConfiguration(non_swb), AseConfiguration(non_swb)}, + .source = {AseConfiguration(non_swb), AseConfiguration(non_swb)}}, }); auto non_swb_config_single = AudioSetConfiguration({ - .name = - "One-OneChan-SnkAse-Lc3_16_2-One-OneChan-SrcAse-Lc3_16_2_NON_SWB", - .confs = {.sink = {AseConfiguration(non_swb)}, - .source = {AseConfiguration(non_swb)}}, + .name = "One-OneChan-SnkAse-Lc3_16_2-One-OneChan-SrcAse-Lc3_16_2_NON_SWB", + .confs = {.sink = {AseConfiguration(non_swb)}, .source = {AseConfiguration(non_swb)}}, }); - AudioSetConfigurations configs = {{&swb_config, &swb_config_single, - &non_swb_config, - &non_swb_config_single}}; + AudioSetConfigurations configs = { + {&swb_config, &swb_config_single, &non_swb_config, &non_swb_config_single}}; // Support single channel per ASE to activate two ASES on both direction for (auto config : configs) { for (const auto& entry : config->confs.sink) { - snk_pac_builder.Add(entry.codec, - kLeAudioCodecChannelCountSingleChannel); + snk_pac_builder.Add(entry.codec, kLeAudioCodecChannelCountSingleChannel); } for (const auto& entry : config->confs.source) { - src_pac_builder.Add(entry.codec, - kLeAudioCodecChannelCountSingleChannel); + src_pac_builder.Add(entry.codec, kLeAudioCodecChannelCountSingleChannel); } } // Inject `configs` as there's no such config in the json file ON_CALL(*mock_codec_manager_, GetCodecConfig) - .WillByDefault(Invoke( - [&configs]( - const bluetooth::le_audio::CodecManager:: - UnicastConfigurationRequirements& requirements, - bluetooth::le_audio::CodecManager::UnicastConfigurationVerifier - verifier) { + .WillByDefault(Invoke([&configs](const bluetooth::le_audio::CodecManager:: + UnicastConfigurationRequirements& requirements, + bluetooth::le_audio::CodecManager:: + UnicastConfigurationVerifier verifier) { auto filtered = configs; // Filter out the dual bidir SWB configurations - if (!bluetooth::le_audio::CodecManager::GetInstance() - ->IsDualBiDirSwbSupported()) { - filtered.erase( - std::remove_if(filtered.begin(), filtered.end(), - [](auto const& el) { - if (el->confs.source.empty()) return false; - return AudioSetConfigurationProvider::Get() - ->CheckConfigurationIsDualBiDirSwb( - *el); - }), - filtered.end()); + if (!bluetooth::le_audio::CodecManager::GetInstance()->IsDualBiDirSwbSupported()) { + filtered.erase(std::remove_if(filtered.begin(), filtered.end(), + [](auto const& el) { + if (el->confs.source.empty()) { + return false; + } + return AudioSetConfigurationProvider::Get() + ->CheckConfigurationIsDualBiDirSwb(*el); + }), + filtered.end()); } auto cfg = verifier(requirements, &filtered); if (cfg == nullptr) { @@ -1357,35 +1261,34 @@ class LeAudioAseConfigurationTest device->snk_pacs_ = snk_pac_builder.Get(); device->src_pacs_ = src_pac_builder.Get(); - ASSERT_TRUE(group_->Configure(context_type, - {.sink = AudioContexts(context_type), - .source = AudioContexts(context_type)})); + ASSERT_TRUE(group_->Configure(context_type, {.sink = AudioContexts(context_type), + .source = AudioContexts(context_type)})); // Verify Dual-Bidir - the amount of ASES configured - TestGroupAseConfigurationData data[] = { - {device, kLeAudioCodecChannelCountSingleChannel, - kLeAudioCodecChannelCountSingleChannel, 2, 2}}; - TestGroupAseConfigurationVerdict( - data[0], kLeAudioDirectionSink | kLeAudioDirectionSource); + TestGroupAseConfigurationData data[] = {{device, kLeAudioCodecChannelCountSingleChannel, + kLeAudioCodecChannelCountSingleChannel, 2, 2}}; + TestGroupAseConfigurationVerdict(data[0], kLeAudioDirectionSink | kLeAudioDirectionSource); } /* Helper */ - static const AudioSetConfiguration* getSpecificConfiguration( - const char* config_name, LeAudioContextType context) { + static const AudioSetConfiguration* getSpecificConfiguration(const char* config_name, + LeAudioContextType context) { auto all_configurations = - ::bluetooth::le_audio::AudioSetConfigurationProvider::Get() - ->GetConfigurations(context); + ::bluetooth::le_audio::AudioSetConfigurationProvider::Get()->GetConfigurations(context); - if (all_configurations == nullptr) return nullptr; - if (all_configurations->end() == all_configurations->begin()) + if (all_configurations == nullptr) { return nullptr; + } + if (all_configurations->end() == all_configurations->begin()) { + return nullptr; + } - auto iter = - std::find_if(all_configurations->begin(), all_configurations->end(), - [config_name](auto& configuration) { - return configuration->name == config_name; - }); - if (iter == all_configurations->end()) return nullptr; + auto iter = std::find_if( + all_configurations->begin(), all_configurations->end(), + [config_name](auto& configuration) { return configuration->name == config_name; }); + if (iter == all_configurations->end()) { + return nullptr; + } return *iter; } @@ -1398,20 +1301,16 @@ class LeAudioAseConfigurationTest /* Create PACs for conversational scenario, SWB and non SWB */ for (auto config : - {getSpecificConfiguration( - "Two-OneChan-SnkAse-Lc3_16_2-Two-OneChan-SrcAse-Lc3_16_2_1", - context_type), - getSpecificConfiguration( - "Two-OneChan-SnkAse-Lc3_32_2-Two-OneChan-SrcAse-Lc3_32_2_1", - context_type)}) { + {getSpecificConfiguration("Two-OneChan-SnkAse-Lc3_16_2-Two-OneChan-SrcAse-Lc3_16_2_1", + context_type), + getSpecificConfiguration("Two-OneChan-SnkAse-Lc3_32_2-Two-OneChan-SrcAse-Lc3_32_2_1", + context_type)}) { ASSERT_NE(nullptr, config); for (const auto& entry : (*config).confs.sink) { - snk_pac_builder.Add(entry.codec, - kLeAudioCodecChannelCountSingleChannel); + snk_pac_builder.Add(entry.codec, kLeAudioCodecChannelCountSingleChannel); } for (const auto& entry : (*config).confs.source) { - src_pac_builder.Add(entry.codec, - kLeAudioCodecChannelCountSingleChannel); + src_pac_builder.Add(entry.codec, kLeAudioCodecChannelCountSingleChannel); } } @@ -1422,34 +1321,27 @@ class LeAudioAseConfigurationTest } /* Change location as by default it is stereo */ - left->snk_audio_locations_ = - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; - left->src_audio_locations_ = - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; + left->snk_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; + left->src_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; right->snk_audio_locations_ = - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight; + ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight; right->src_audio_locations_ = - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight; + ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight; group_->ReloadAudioLocations(); - ASSERT_TRUE(group_->Configure(context_type, - {.sink = AudioContexts(context_type), - .source = AudioContexts(context_type)})); + ASSERT_TRUE(group_->Configure(context_type, {.sink = AudioContexts(context_type), + .source = AudioContexts(context_type)})); // Verify the amount of ASES configured - TestGroupAseConfigurationData data[] = { - {left, kLeAudioCodecChannelCountSingleChannel, - kLeAudioCodecChannelCountSingleChannel, 1, 1}, - {right, kLeAudioCodecChannelCountSingleChannel, - kLeAudioCodecChannelCountSingleChannel, 1, 1}}; - TestGroupAseConfigurationVerdict( - data[0], kLeAudioDirectionSink | kLeAudioDirectionSource); - TestGroupAseConfigurationVerdict( - data[1], kLeAudioDirectionSink | kLeAudioDirectionSource); + TestGroupAseConfigurationData data[] = {{left, kLeAudioCodecChannelCountSingleChannel, + kLeAudioCodecChannelCountSingleChannel, 1, 1}, + {right, kLeAudioCodecChannelCountSingleChannel, + kLeAudioCodecChannelCountSingleChannel, 1, 1}}; + TestGroupAseConfigurationVerdict(data[0], kLeAudioDirectionSink | kLeAudioDirectionSource); + TestGroupAseConfigurationVerdict(data[1], kLeAudioDirectionSink | kLeAudioDirectionSource); } - void SetAsesToCachedConfiguration(LeAudioDevice* device, - LeAudioContextType context_type, + void SetAsesToCachedConfiguration(LeAudioDevice* device, LeAudioContextType context_type, uint8_t directions) { for (struct ase& ase : device->ases_) { if (ase.direction & directions) { @@ -1468,8 +1360,7 @@ class LeAudioAseConfigurationTest LeAudioDeviceGroup* group_ = nullptr; bluetooth::manager::MockBtmInterface btm_interface_; MockCsisClient mock_csis_client_module_; - NiceMock - controller_interface_; + NiceMock controller_interface_; bluetooth::le_audio::CodecManager* codec_manager_; MockCodecManager* mock_codec_manager_; @@ -1481,23 +1372,18 @@ TEST_P(LeAudioAseConfigurationTest, test_context_update) { ASSERT_EQ(2, group_->Size()); /* Change locations */ - left->snk_audio_locations_ = - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; - left->src_audio_locations_ = - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; - right->snk_audio_locations_ = - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight; - right->src_audio_locations_ = - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight; + left->snk_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; + left->src_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; + right->snk_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight; + right->src_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight; group_->ReloadAudioLocations(); /* Put the PACS */ auto conversational_configuration = getSpecificConfiguration( - "Two-OneChan-SnkAse-Lc3_16_2-One-OneChan-SrcAse-Lc3_16_2_Low_Latency", - LeAudioContextType::CONVERSATIONAL); - auto media_configuration = - getSpecificConfiguration("One-TwoChan-SnkAse-Lc3_48_4_High_Reliability", - LeAudioContextType::MEDIA); + "Two-OneChan-SnkAse-Lc3_16_2-One-OneChan-SrcAse-Lc3_16_2_Low_Latency", + LeAudioContextType::CONVERSATIONAL); + auto media_configuration = getSpecificConfiguration( + "One-TwoChan-SnkAse-Lc3_48_4_High_Reliability", LeAudioContextType::MEDIA); ASSERT_NE(nullptr, conversational_configuration); ASSERT_NE(nullptr, media_configuration); @@ -1517,38 +1403,33 @@ TEST_P(LeAudioAseConfigurationTest, test_context_update) { right->src_pacs_ = src_pac_builder.Get(); /* UNSPECIFIED must be supported, MEDIA is on the remote sink only... */ - auto remote_snk_supp_contexts = AudioContexts( - LeAudioContextType::MEDIA | LeAudioContextType::CONVERSATIONAL | - LeAudioContextType::SOUNDEFFECTS | LeAudioContextType::UNSPECIFIED); - auto remote_src_supp_contexts = AudioContexts( - LeAudioContextType::CONVERSATIONAL | LeAudioContextType::UNSPECIFIED); + auto remote_snk_supp_contexts = + AudioContexts(LeAudioContextType::MEDIA | LeAudioContextType::CONVERSATIONAL | + LeAudioContextType::SOUNDEFFECTS | LeAudioContextType::UNSPECIFIED); + auto remote_src_supp_contexts = + AudioContexts(LeAudioContextType::CONVERSATIONAL | LeAudioContextType::UNSPECIFIED); left->SetSupportedContexts( - {.sink = remote_snk_supp_contexts, .source = remote_src_supp_contexts}); + {.sink = remote_snk_supp_contexts, .source = remote_src_supp_contexts}); auto right_bud_only_context = LeAudioContextType::ALERTS; - right->SetSupportedContexts( - {.sink = remote_snk_supp_contexts | right_bud_only_context, - .source = remote_src_supp_contexts | right_bud_only_context}); + right->SetSupportedContexts({.sink = remote_snk_supp_contexts | right_bud_only_context, + .source = remote_src_supp_contexts | right_bud_only_context}); /* ...but UNSPECIFIED and SOUNDEFFECTS are unavailable */ - auto remote_snk_avail_contexts = AudioContexts( - LeAudioContextType::MEDIA | LeAudioContextType::CONVERSATIONAL); - auto remote_src_avail_contexts = - AudioContexts(LeAudioContextType::CONVERSATIONAL); + auto remote_snk_avail_contexts = + AudioContexts(LeAudioContextType::MEDIA | LeAudioContextType::CONVERSATIONAL); + auto remote_src_avail_contexts = AudioContexts(LeAudioContextType::CONVERSATIONAL); left->SetAvailableContexts( - {.sink = remote_snk_avail_contexts, .source = remote_src_avail_contexts}); - ASSERT_EQ(left->GetAvailableContexts(), - remote_snk_avail_contexts | remote_src_avail_contexts); + {.sink = remote_snk_avail_contexts, .source = remote_src_avail_contexts}); + ASSERT_EQ(left->GetAvailableContexts(), remote_snk_avail_contexts | remote_src_avail_contexts); // Make an additional context available on the right earbud sink - right->SetAvailableContexts( - {.sink = remote_snk_avail_contexts | right_bud_only_context, - .source = remote_src_avail_contexts}); - ASSERT_EQ(right->GetAvailableContexts(), remote_snk_avail_contexts | - remote_src_avail_contexts | - right_bud_only_context); + right->SetAvailableContexts({.sink = remote_snk_avail_contexts | right_bud_only_context, + .source = remote_src_avail_contexts}); + ASSERT_EQ(right->GetAvailableContexts(), + remote_snk_avail_contexts | remote_src_avail_contexts | right_bud_only_context); /* Now add the right earbud contexts - mind the extra context on that bud */ group_->UpdateAudioContextAvailability(); @@ -1566,86 +1447,59 @@ TEST_P(LeAudioAseConfigurationTest, test_context_update) { /* MEDIA Available on remote sink direction only */ auto config = group_->GetConfiguration(LeAudioContextType::MEDIA); ASSERT_NE(nullptr, config); - ASSERT_TRUE( - config->confs.get(bluetooth::le_audio::types::kLeAudioDirectionSink) - .size()); - ASSERT_FALSE( - config->confs.get(bluetooth::le_audio::types::kLeAudioDirectionSource) - .size()); - ASSERT_EQ( - config->confs.get(bluetooth::le_audio::types::kLeAudioDirectionSink) - .at(0) - .codec.GetChannelCountPerIsoStream(), - ::bluetooth::le_audio::LeAudioCodecConfiguration::kChannelNumberMono); + ASSERT_TRUE(config->confs.get(bluetooth::le_audio::types::kLeAudioDirectionSink).size()); + ASSERT_FALSE(config->confs.get(bluetooth::le_audio::types::kLeAudioDirectionSource).size()); + ASSERT_EQ(config->confs.get(bluetooth::le_audio::types::kLeAudioDirectionSink) + .at(0) + .codec.GetChannelCountPerIsoStream(), + ::bluetooth::le_audio::LeAudioCodecConfiguration::kChannelNumberMono); /* CONVERSATIONAL Available on both directions */ config = group_->GetConfiguration(LeAudioContextType::CONVERSATIONAL); ASSERT_NE(nullptr, config); - ASSERT_TRUE( - config->confs.get(bluetooth::le_audio::types::kLeAudioDirectionSink) - .size()); - ASSERT_TRUE( - config->confs.get(bluetooth::le_audio::types::kLeAudioDirectionSource) - .size()); + ASSERT_TRUE(config->confs.get(bluetooth::le_audio::types::kLeAudioDirectionSink).size()); + ASSERT_TRUE(config->confs.get(bluetooth::le_audio::types::kLeAudioDirectionSource).size()); /* UNSPECIFIED Unavailable yet supported */ config = group_->GetConfiguration(LeAudioContextType::UNSPECIFIED); ASSERT_NE(nullptr, config); - ASSERT_TRUE( - config->confs.get(bluetooth::le_audio::types::kLeAudioDirectionSink) - .size()); - ASSERT_FALSE( - config->confs.get(bluetooth::le_audio::types::kLeAudioDirectionSource) - .size()); + ASSERT_TRUE(config->confs.get(bluetooth::le_audio::types::kLeAudioDirectionSink).size()); + ASSERT_FALSE(config->confs.get(bluetooth::le_audio::types::kLeAudioDirectionSource).size()); /* SOUNDEFFECTS Unavailable yet supported on sink only */ config = group_->GetConfiguration(LeAudioContextType::SOUNDEFFECTS); ASSERT_NE(nullptr, config); - ASSERT_TRUE( - config->confs.get(bluetooth::le_audio::types::kLeAudioDirectionSink) - .size()); - ASSERT_FALSE( - config->confs.get(bluetooth::le_audio::types::kLeAudioDirectionSource) - .size()); + ASSERT_TRUE(config->confs.get(bluetooth::le_audio::types::kLeAudioDirectionSink).size()); + ASSERT_FALSE(config->confs.get(bluetooth::le_audio::types::kLeAudioDirectionSource).size()); /* INSTRUCTIONAL Unavailable and not supported, while UNSPECIFIED not * available */ config = group_->GetConfiguration(LeAudioContextType::INSTRUCTIONAL); ASSERT_NE(nullptr, config); - ASSERT_TRUE( - config->confs.get(bluetooth::le_audio::types::kLeAudioDirectionSink) - .size()); - ASSERT_FALSE( - config->confs.get(bluetooth::le_audio::types::kLeAudioDirectionSource) - .size()); + ASSERT_TRUE(config->confs.get(bluetooth::le_audio::types::kLeAudioDirectionSink).size()); + ASSERT_FALSE(config->confs.get(bluetooth::le_audio::types::kLeAudioDirectionSource).size()); /* ALERTS on sink only */ config = group_->GetConfiguration(LeAudioContextType::ALERTS); ASSERT_NE(nullptr, config); - ASSERT_TRUE( - config->confs.get(bluetooth::le_audio::types::kLeAudioDirectionSink) - .size()); - ASSERT_FALSE( - config->confs.get(bluetooth::le_audio::types::kLeAudioDirectionSource) - .size()); + ASSERT_TRUE(config->confs.get(bluetooth::le_audio::types::kLeAudioDirectionSink).size()); + ASSERT_FALSE(config->confs.get(bluetooth::le_audio::types::kLeAudioDirectionSource).size()); /* We should get the config for ALERTS for both channels as the other has * UNSPECIFIED context supported. */ - auto sink_configs = - group_->GetConfiguration(LeAudioContextType::ALERTS) - ->confs.get(bluetooth::le_audio::types::kLeAudioDirectionSink); + auto sink_configs = group_->GetConfiguration(LeAudioContextType::ALERTS) + ->confs.get(bluetooth::le_audio::types::kLeAudioDirectionSink); ASSERT_EQ(2lu, sink_configs.size()); - ASSERT_TRUE( - group_->IsAudioSetConfigurationAvailable(LeAudioContextType::ALERTS)); + ASSERT_TRUE(group_->IsAudioSetConfigurationAvailable(LeAudioContextType::ALERTS)); /* Turn off the ALERTS context */ right->SetAvailableContexts( - {.sink = right->GetAvailableContexts( - ::bluetooth::le_audio::types::kLeAudioDirectionSink) & - ~AudioContexts(LeAudioContextType::ALERTS), - .source = right->GetAvailableContexts( - ::bluetooth::le_audio::types::kLeAudioDirectionSource)}); + {.sink = right->GetAvailableContexts( + ::bluetooth::le_audio::types::kLeAudioDirectionSink) & + ~AudioContexts(LeAudioContextType::ALERTS), + .source = right->GetAvailableContexts( + ::bluetooth::le_audio::types::kLeAudioDirectionSource)}); /* Right one was changed but the config exist, just not available */ group_->UpdateAudioContextAvailability(); @@ -1653,130 +1507,110 @@ TEST_P(LeAudioAseConfigurationTest, test_context_update) { left->GetAvailableContexts() | right->GetAvailableContexts()); ASSERT_FALSE(group_->GetAvailableContexts().test(LeAudioContextType::ALERTS)); ASSERT_TRUE(group_->GetConfiguration(LeAudioContextType::ALERTS) - ->confs.get(bluetooth::le_audio::types::kLeAudioDirectionSink) - .size()); - ASSERT_TRUE( - group_->IsAudioSetConfigurationAvailable(LeAudioContextType::ALERTS)); + ->confs.get(bluetooth::le_audio::types::kLeAudioDirectionSink) + .size()); + ASSERT_TRUE(group_->IsAudioSetConfigurationAvailable(LeAudioContextType::ALERTS)); } TEST_P(LeAudioAseConfigurationTest, test_mono_speaker_ringtone) { LeAudioDevice* mono_speaker = AddTestDevice(1, 0); - TestGroupAseConfigurationData data( - {mono_speaker, kLeAudioCodecChannelCountSingleChannel, - kLeAudioCodecChannelCountSingleChannel, 1, 0}); + TestGroupAseConfigurationData data({mono_speaker, kLeAudioCodecChannelCountSingleChannel, + kLeAudioCodecChannelCountSingleChannel, 1, 0}); /* mono, change location as by default it is stereo */ mono_speaker->snk_audio_locations_ = - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; + ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; group_->ReloadAudioLocations(); uint8_t direction_to_verify = kLeAudioDirectionSink; - TestGroupAseConfiguration(LeAudioContextType::RINGTONE, &data, 1, - direction_to_verify); + TestGroupAseConfiguration(LeAudioContextType::RINGTONE, &data, 1, direction_to_verify); } TEST_P(LeAudioAseConfigurationTest, test_mono_speaker_conversational) { LeAudioDevice* mono_speaker = AddTestDevice(1, 0); - TestGroupAseConfigurationData data({mono_speaker, - kLeAudioCodecChannelCountSingleChannel, + TestGroupAseConfigurationData data({mono_speaker, kLeAudioCodecChannelCountSingleChannel, kLeAudioCodecChannelCountNone, 1, 0}); /* mono, change location as by default it is stereo */ mono_speaker->snk_audio_locations_ = - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; + ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; group_->ReloadAudioLocations(); /* Microphone should be used on the phone */ uint8_t direction_to_verify = kLeAudioDirectionSink; - TestGroupAseConfiguration(LeAudioContextType::CONVERSATIONAL, &data, 1, - direction_to_verify); + TestGroupAseConfiguration(LeAudioContextType::CONVERSATIONAL, &data, 1, direction_to_verify); } TEST_P(LeAudioAseConfigurationTest, test_mono_speaker_media) { LeAudioDevice* mono_speaker = AddTestDevice(1, 0); - TestGroupAseConfigurationData data({mono_speaker, - kLeAudioCodecChannelCountSingleChannel, + TestGroupAseConfigurationData data({mono_speaker, kLeAudioCodecChannelCountSingleChannel, kLeAudioCodecChannelCountNone, 1, 0}); /* mono, change location as by default it is stereo */ mono_speaker->snk_audio_locations_ = - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; + ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; group_->ReloadAudioLocations(); uint8_t direction_to_verify = kLeAudioDirectionSink; - TestGroupAseConfiguration(LeAudioContextType::MEDIA, &data, 1, - direction_to_verify); + TestGroupAseConfiguration(LeAudioContextType::MEDIA, &data, 1, direction_to_verify); } TEST_P(LeAudioAseConfigurationTest, test_banded_headphones_ringtone) { LeAudioDevice* banded_headphones = AddTestDevice(2, 0); - TestGroupAseConfigurationData data( - {banded_headphones, kLeAudioCodecChannelCountTwoChannel, - kLeAudioCodecChannelCountSingleChannel, 2, 0}); + TestGroupAseConfigurationData data({banded_headphones, kLeAudioCodecChannelCountTwoChannel, + kLeAudioCodecChannelCountSingleChannel, 2, 0}); uint8_t direction_to_verify = kLeAudioDirectionSink; - TestGroupAseConfiguration(LeAudioContextType::RINGTONE, &data, 1, - direction_to_verify); + TestGroupAseConfiguration(LeAudioContextType::RINGTONE, &data, 1, direction_to_verify); } TEST_P(LeAudioAseConfigurationTest, test_banded_headphones_conversational) { LeAudioDevice* banded_headphones = AddTestDevice(2, 0); - TestGroupAseConfigurationData data({banded_headphones, - kLeAudioCodecChannelCountTwoChannel, + TestGroupAseConfigurationData data({banded_headphones, kLeAudioCodecChannelCountTwoChannel, kLeAudioCodecChannelCountNone, 2, 0}); uint8_t direction_to_verify = kLeAudioDirectionSink; - TestGroupAseConfiguration(LeAudioContextType::CONVERSATIONAL, &data, 1, - direction_to_verify); + TestGroupAseConfiguration(LeAudioContextType::CONVERSATIONAL, &data, 1, direction_to_verify); } TEST_P(LeAudioAseConfigurationTest, test_banded_headphones_media) { LeAudioDevice* banded_headphones = AddTestDevice(2, 0); - TestGroupAseConfigurationData data({banded_headphones, - kLeAudioCodecChannelCountTwoChannel, + TestGroupAseConfigurationData data({banded_headphones, kLeAudioCodecChannelCountTwoChannel, kLeAudioCodecChannelCountNone, 2, 0}); uint8_t direction_to_verify = kLeAudioDirectionSink; - TestGroupAseConfiguration(LeAudioContextType::MEDIA, &data, 1, - direction_to_verify); + TestGroupAseConfiguration(LeAudioContextType::MEDIA, &data, 1, direction_to_verify); } -TEST_P(LeAudioAseConfigurationTest, - test_banded_headset_ringtone_mono_microphone) { - LeAudioDevice* banded_headset = AddTestDevice( - 2, 1, 0, 0, false, false, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationFrontLeft); - TestGroupAseConfigurationData data( - {banded_headset, kLeAudioCodecChannelCountTwoChannel, - kLeAudioCodecChannelCountSingleChannel, 2, 1}); +TEST_P(LeAudioAseConfigurationTest, test_banded_headset_ringtone_mono_microphone) { + LeAudioDevice* banded_headset = + AddTestDevice(2, 1, 0, 0, false, false, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationFrontLeft); + TestGroupAseConfigurationData data({banded_headset, kLeAudioCodecChannelCountTwoChannel, + kLeAudioCodecChannelCountSingleChannel, 2, 1}); /* mono, change location as by default it is stereo */ banded_headset->src_audio_locations_ = - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; + ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; group_->ReloadAudioLocations(); TestGroupAseConfiguration(LeAudioContextType::RINGTONE, &data, 1); } -TEST_P(LeAudioAseConfigurationTest, - test_banded_headset_ringtone_stereo_microphone) { +TEST_P(LeAudioAseConfigurationTest, test_banded_headset_ringtone_stereo_microphone) { LeAudioDevice* banded_headset = AddTestDevice(2, 2); - TestGroupAseConfigurationData data({banded_headset, - kLeAudioCodecChannelCountSingleChannel | - kLeAudioCodecChannelCountTwoChannel, - kLeAudioCodecChannelCountSingleChannel | - kLeAudioCodecChannelCountTwoChannel, - 2, 2}); + TestGroupAseConfigurationData data( + {banded_headset, + kLeAudioCodecChannelCountSingleChannel | kLeAudioCodecChannelCountTwoChannel, + kLeAudioCodecChannelCountSingleChannel | kLeAudioCodecChannelCountTwoChannel, 2, 2}); TestGroupAseConfiguration(LeAudioContextType::RINGTONE, &data, 1); } -TEST_P(LeAudioAseConfigurationTest, - test_earbuds_conversational_stereo_microphone_no_swb) { +TEST_P(LeAudioAseConfigurationTest, test_earbuds_conversational_stereo_microphone_no_swb) { // Turn off the dual bidir SWB support - ON_CALL(*mock_codec_manager_, IsDualBiDirSwbSupported) - .WillByDefault(Return(false)); + ON_CALL(*mock_codec_manager_, IsDualBiDirSwbSupported).WillByDefault(Return(false)); ASSERT_FALSE(CodecManager::GetInstance()->IsDualBiDirSwbSupported()); const auto context_type = LeAudioContextType::CONVERSATIONAL; @@ -1785,8 +1619,7 @@ TEST_P(LeAudioAseConfigurationTest, // Verify non-SWB config was selected auto config = group_->GetCachedConfiguration(context_type).get(); ASSERT_NE(nullptr, config); - ASSERT_FALSE( - CodecManager::GetInstance()->CheckCodecConfigIsDualBiDirSwb(*config)); + ASSERT_FALSE(CodecManager::GetInstance()->CheckCodecConfigIsDualBiDirSwb(*config)); } TEST_P(LeAudioAseConfigurationTest, @@ -1795,31 +1628,25 @@ TEST_P(LeAudioAseConfigurationTest, * Turn off the dual bidir SWB support */ desired_group_size_ = 2; - ON_CALL(*mock_codec_manager_, IsDualBiDirSwbSupported) - .WillByDefault(Return(false)); + ON_CALL(*mock_codec_manager_, IsDualBiDirSwbSupported).WillByDefault(Return(false)); ASSERT_FALSE(CodecManager::GetInstance()->IsDualBiDirSwbSupported()); const auto context_type = LeAudioContextType::CONVERSATIONAL; TestSingleDevDualBidir( - AddTestDevice(1, 1, 0, 0, false, false, - codec_spec_conf::kLeAudioLocationFrontLeft, - codec_spec_conf::kLeAudioLocationFrontLeft), - context_type); + AddTestDevice(1, 1, 0, 0, false, false, codec_spec_conf::kLeAudioLocationFrontLeft, + codec_spec_conf::kLeAudioLocationFrontLeft), + context_type); // Verify non-SWB config was selected auto config = group_->GetCachedConfiguration(context_type).get(); ASSERT_NE(nullptr, config); - ASSERT_FALSE( - CodecManager::GetInstance()->CheckCodecConfigIsDualBiDirSwb(*config)); - ASSERT_FALSE( - CodecManager::GetInstance()->CheckCodecConfigIsBiDirSwb(*config)); + ASSERT_FALSE(CodecManager::GetInstance()->CheckCodecConfigIsDualBiDirSwb(*config)); + ASSERT_FALSE(CodecManager::GetInstance()->CheckCodecConfigIsBiDirSwb(*config)); } -TEST_P(LeAudioAseConfigurationTest, - test_earbuds_conversational_stereo_microphone_swb) { +TEST_P(LeAudioAseConfigurationTest, test_earbuds_conversational_stereo_microphone_swb) { // Turn on the dual bidir SWB support - ON_CALL(*mock_codec_manager_, IsDualBiDirSwbSupported) - .WillByDefault(Return(true)); + ON_CALL(*mock_codec_manager_, IsDualBiDirSwbSupported).WillByDefault(Return(true)); ASSERT_TRUE(CodecManager::GetInstance()->IsDualBiDirSwbSupported()); const auto context_type = LeAudioContextType::CONVERSATIONAL; @@ -1828,15 +1655,12 @@ TEST_P(LeAudioAseConfigurationTest, // Verify SWB config was selected auto config = group_->GetCachedConfiguration(context_type).get(); ASSERT_NE(nullptr, config); - ASSERT_TRUE( - CodecManager::GetInstance()->CheckCodecConfigIsDualBiDirSwb(*config)); + ASSERT_TRUE(CodecManager::GetInstance()->CheckCodecConfigIsDualBiDirSwb(*config)); } -TEST_P(LeAudioAseConfigurationTest, - test_banded_headset_ringtone_stereo_microphone_no_swb) { +TEST_P(LeAudioAseConfigurationTest, test_banded_headset_ringtone_stereo_microphone_no_swb) { // Turn off the dual bidir SWB support - ON_CALL(*mock_codec_manager_, IsDualBiDirSwbSupported) - .WillByDefault(Return(false)); + ON_CALL(*mock_codec_manager_, IsDualBiDirSwbSupported).WillByDefault(Return(false)); ASSERT_FALSE(CodecManager::GetInstance()->IsDualBiDirSwbSupported()); // Verify non-SWB config was selected @@ -1844,15 +1668,12 @@ TEST_P(LeAudioAseConfigurationTest, TestSingleDevDualBidir(AddTestDevice(2, 2), context_type); auto config = group_->GetCachedConfiguration(context_type).get(); ASSERT_NE(nullptr, config); - ASSERT_FALSE( - CodecManager::GetInstance()->CheckCodecConfigIsDualBiDirSwb(*config)); + ASSERT_FALSE(CodecManager::GetInstance()->CheckCodecConfigIsDualBiDirSwb(*config)); } -TEST_P(LeAudioAseConfigurationTest, - test_banded_headset_ringtone_stereo_microphone_swb) { +TEST_P(LeAudioAseConfigurationTest, test_banded_headset_ringtone_stereo_microphone_swb) { // Turn on the dual bidir SWB support - ON_CALL(*mock_codec_manager_, IsDualBiDirSwbSupported) - .WillByDefault(Return(true)); + ON_CALL(*mock_codec_manager_, IsDualBiDirSwbSupported).WillByDefault(Return(true)); ASSERT_TRUE(CodecManager::GetInstance()->IsDualBiDirSwbSupported()); // Verify SWB config was selected @@ -1860,48 +1681,39 @@ TEST_P(LeAudioAseConfigurationTest, TestSingleDevDualBidir(AddTestDevice(2, 2), context_type); auto config = group_->GetCachedConfiguration(context_type).get(); ASSERT_NE(nullptr, config); - ASSERT_TRUE( - CodecManager::GetInstance()->CheckCodecConfigIsDualBiDirSwb(*config)); + ASSERT_TRUE(CodecManager::GetInstance()->CheckCodecConfigIsDualBiDirSwb(*config)); } TEST_P(LeAudioAseConfigurationTest, test_banded_headset_conversational) { LeAudioDevice* banded_headset = AddTestDevice(2, 1); - TestGroupAseConfigurationData data( - {banded_headset, kLeAudioCodecChannelCountTwoChannel, - kLeAudioCodecChannelCountSingleChannel, 2, 1}); + TestGroupAseConfigurationData data({banded_headset, kLeAudioCodecChannelCountTwoChannel, + kLeAudioCodecChannelCountSingleChannel, 2, 1}); TestGroupAseConfiguration(LeAudioContextType::CONVERSATIONAL, &data, 1); } TEST_P(LeAudioAseConfigurationTest, test_banded_headset_media) { LeAudioDevice* banded_headset = AddTestDevice(2, 1); - TestGroupAseConfigurationData data( - {banded_headset, kLeAudioCodecChannelCountTwoChannel, - kLeAudioCodecChannelCountSingleChannel, 2, 0}); + TestGroupAseConfigurationData data({banded_headset, kLeAudioCodecChannelCountTwoChannel, + kLeAudioCodecChannelCountSingleChannel, 2, 0}); uint8_t directions_to_verify = kLeAudioDirectionSink; - TestGroupAseConfiguration(LeAudioContextType::MEDIA, &data, 1, - directions_to_verify); + TestGroupAseConfiguration(LeAudioContextType::MEDIA, &data, 1, directions_to_verify); } TEST_P(LeAudioAseConfigurationTest, test_earbuds_ringtone) { LeAudioDevice* left = AddTestDevice(1, 1); LeAudioDevice* right = AddTestDevice(1, 1); - TestGroupAseConfigurationData data[] = { - {left, kLeAudioCodecChannelCountSingleChannel, - kLeAudioCodecChannelCountSingleChannel, 1, 1}, - {right, kLeAudioCodecChannelCountSingleChannel, - kLeAudioCodecChannelCountSingleChannel, 1, 1}}; + TestGroupAseConfigurationData data[] = {{left, kLeAudioCodecChannelCountSingleChannel, + kLeAudioCodecChannelCountSingleChannel, 1, 1}, + {right, kLeAudioCodecChannelCountSingleChannel, + kLeAudioCodecChannelCountSingleChannel, 1, 1}}; /* Change location as by default it is stereo */ - left->snk_audio_locations_ = - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; - left->src_audio_locations_ = - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; - right->snk_audio_locations_ = - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight; - right->src_audio_locations_ = - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight; + left->snk_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; + left->src_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; + right->snk_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight; + right->src_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight; group_->ReloadAudioLocations(); TestGroupAseConfiguration(LeAudioContextType::RINGTONE, data, 2); @@ -1910,21 +1722,16 @@ TEST_P(LeAudioAseConfigurationTest, test_earbuds_ringtone) { TEST_P(LeAudioAseConfigurationTest, test_earbuds_conversational) { LeAudioDevice* left = AddTestDevice(1, 1); LeAudioDevice* right = AddTestDevice(1, 1); - TestGroupAseConfigurationData data[] = { - {left, kLeAudioCodecChannelCountSingleChannel, - kLeAudioCodecChannelCountSingleChannel, 1, 1}, - {right, kLeAudioCodecChannelCountSingleChannel, - kLeAudioCodecChannelCountSingleChannel, 1, 1}}; + TestGroupAseConfigurationData data[] = {{left, kLeAudioCodecChannelCountSingleChannel, + kLeAudioCodecChannelCountSingleChannel, 1, 1}, + {right, kLeAudioCodecChannelCountSingleChannel, + kLeAudioCodecChannelCountSingleChannel, 1, 1}}; /* Change location as by default it is stereo */ - left->snk_audio_locations_ = - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; - left->src_audio_locations_ = - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; - right->snk_audio_locations_ = - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight; - right->src_audio_locations_ = - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight; + left->snk_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; + left->src_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; + right->snk_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight; + right->src_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight; group_->ReloadAudioLocations(); TestGroupAseConfiguration(LeAudioContextType::CONVERSATIONAL, data, 2); @@ -1933,68 +1740,57 @@ TEST_P(LeAudioAseConfigurationTest, test_earbuds_conversational) { TEST_P(LeAudioAseConfigurationTest, test_earbuds_media) { LeAudioDevice* left = AddTestDevice(1, 1); LeAudioDevice* right = AddTestDevice(1, 1); - TestGroupAseConfigurationData data[] = { - {left, kLeAudioCodecChannelCountSingleChannel, - kLeAudioCodecChannelCountSingleChannel, 1, 0}, - {right, kLeAudioCodecChannelCountSingleChannel, - kLeAudioCodecChannelCountSingleChannel, 1, 0}}; + TestGroupAseConfigurationData data[] = {{left, kLeAudioCodecChannelCountSingleChannel, + kLeAudioCodecChannelCountSingleChannel, 1, 0}, + {right, kLeAudioCodecChannelCountSingleChannel, + kLeAudioCodecChannelCountSingleChannel, 1, 0}}; /* Change location as by default it is stereo */ - left->snk_audio_locations_ = - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; - left->src_audio_locations_ = - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; - right->snk_audio_locations_ = - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight; - right->src_audio_locations_ = - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight; + left->snk_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; + left->src_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; + right->snk_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight; + right->src_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight; group_->ReloadAudioLocations(); uint8_t directions_to_verify = kLeAudioDirectionSink; - TestGroupAseConfiguration(LeAudioContextType::MEDIA, data, 2, - directions_to_verify); + TestGroupAseConfiguration(LeAudioContextType::MEDIA, data, 2, directions_to_verify); } TEST_P(LeAudioAseConfigurationTest, test_handsfree_mono_ringtone) { LeAudioDevice* handsfree = AddTestDevice(1, 1); - TestGroupAseConfigurationData data( - {handsfree, kLeAudioCodecChannelCountSingleChannel, - kLeAudioCodecChannelCountSingleChannel, 1, 1}); + TestGroupAseConfigurationData data({handsfree, kLeAudioCodecChannelCountSingleChannel, + kLeAudioCodecChannelCountSingleChannel, 1, 1}); handsfree->snk_audio_locations_ = - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; + ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; handsfree->src_audio_locations_ = - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; + ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; group_->ReloadAudioLocations(); TestGroupAseConfiguration(LeAudioContextType::RINGTONE, &data, 1); } TEST_P(LeAudioAseConfigurationTest, test_handsfree_stereo_ringtone) { - LeAudioDevice* handsfree = - AddTestDevice(1, 1, 0, 0, false, false, - codec_spec_conf::kLeAudioLocationFrontLeft | - codec_spec_conf::kLeAudioLocationFrontRight, - codec_spec_conf::kLeAudioLocationFrontLeft); - TestGroupAseConfigurationData data({handsfree, - kLeAudioCodecChannelCountSingleChannel | - kLeAudioCodecChannelCountTwoChannel, - kLeAudioCodecChannelCountSingleChannel, 2, - 1}); + LeAudioDevice* handsfree = AddTestDevice( + 1, 1, 0, 0, false, false, + codec_spec_conf::kLeAudioLocationFrontLeft | codec_spec_conf::kLeAudioLocationFrontRight, + codec_spec_conf::kLeAudioLocationFrontLeft); + TestGroupAseConfigurationData data( + {handsfree, kLeAudioCodecChannelCountSingleChannel | kLeAudioCodecChannelCountTwoChannel, + kLeAudioCodecChannelCountSingleChannel, 2, 1}); TestGroupAseConfiguration(LeAudioContextType::RINGTONE, &data, 1); } TEST_P(LeAudioAseConfigurationTest, test_handsfree_mono_conversational) { LeAudioDevice* handsfree = AddTestDevice(1, 1); - TestGroupAseConfigurationData data( - {handsfree, kLeAudioCodecChannelCountSingleChannel, - kLeAudioCodecChannelCountSingleChannel, 1, 1}); + TestGroupAseConfigurationData data({handsfree, kLeAudioCodecChannelCountSingleChannel, + kLeAudioCodecChannelCountSingleChannel, 1, 1}); handsfree->snk_audio_locations_ = - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; + ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; handsfree->src_audio_locations_ = - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; + ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; group_->ReloadAudioLocations(); TestGroupAseConfiguration(LeAudioContextType::CONVERSATIONAL, &data, 1); @@ -2002,54 +1798,45 @@ TEST_P(LeAudioAseConfigurationTest, test_handsfree_mono_conversational) { TEST_P(LeAudioAseConfigurationTest, test_handsfree_stereo_conversational) { LeAudioDevice* handsfree = AddTestDevice(1, 1); - TestGroupAseConfigurationData data({handsfree, - kLeAudioCodecChannelCountSingleChannel | - kLeAudioCodecChannelCountTwoChannel, - kLeAudioCodecChannelCountSingleChannel, 2, - 1}); + TestGroupAseConfigurationData data( + {handsfree, kLeAudioCodecChannelCountSingleChannel | kLeAudioCodecChannelCountTwoChannel, + kLeAudioCodecChannelCountSingleChannel, 2, 1}); TestGroupAseConfiguration(LeAudioContextType::CONVERSATIONAL, &data, 1); } TEST_P(LeAudioAseConfigurationTest, test_handsfree_full_cached_conversational) { LeAudioDevice* handsfree = AddTestDevice(0, 0, 1, 1); - TestGroupAseConfigurationData data({handsfree, - kLeAudioCodecChannelCountSingleChannel | - kLeAudioCodecChannelCountTwoChannel, - kLeAudioCodecChannelCountSingleChannel, 2, - 1}); + TestGroupAseConfigurationData data( + {handsfree, kLeAudioCodecChannelCountSingleChannel | kLeAudioCodecChannelCountTwoChannel, + kLeAudioCodecChannelCountSingleChannel, 2, 1}); TestGroupAseConfiguration(LeAudioContextType::CONVERSATIONAL, &data, 1); } -TEST_P(LeAudioAseConfigurationTest, - test_handsfree_partial_cached_conversational) { +TEST_P(LeAudioAseConfigurationTest, test_handsfree_partial_cached_conversational) { LeAudioDevice* handsfree = AddTestDevice(1, 0, 0, 1); - TestGroupAseConfigurationData data({handsfree, - kLeAudioCodecChannelCountSingleChannel | - kLeAudioCodecChannelCountTwoChannel, - kLeAudioCodecChannelCountSingleChannel, 2, - 1}); + TestGroupAseConfigurationData data( + {handsfree, kLeAudioCodecChannelCountSingleChannel | kLeAudioCodecChannelCountTwoChannel, + kLeAudioCodecChannelCountSingleChannel, 2, 1}); TestGroupAseConfiguration(LeAudioContextType::CONVERSATIONAL, &data, 1); } -TEST_P(LeAudioAseConfigurationTest, - test_handsfree_media_two_channels_allocation_stereo) { +TEST_P(LeAudioAseConfigurationTest, test_handsfree_media_two_channels_allocation_stereo) { LeAudioDevice* handsfree = AddTestDevice(1, 1); - TestGroupAseConfigurationData data({handsfree, - kLeAudioCodecChannelCountSingleChannel | - kLeAudioCodecChannelCountTwoChannel, - kLeAudioCodecChannelCountSingleChannel, 2, - 0}); + TestGroupAseConfigurationData data( + {handsfree, kLeAudioCodecChannelCountSingleChannel | kLeAudioCodecChannelCountTwoChannel, + kLeAudioCodecChannelCountSingleChannel, 2, 0}); uint8_t directions_to_verify = kLeAudioDirectionSink; - TestGroupAseConfiguration(LeAudioContextType::MEDIA, &data, 1, - directions_to_verify); + TestGroupAseConfiguration(LeAudioContextType::MEDIA, &data, 1, directions_to_verify); } TEST_P(LeAudioAseConfigurationTest, test_lc3_config_ringtone) { - if (codec_coding_format_ != kLeAudioCodingFormatLC3) GTEST_SKIP(); + if (codec_coding_format_ != kLeAudioCodingFormatLC3) { + GTEST_SKIP(); + } AddTestDevice(1, 1); @@ -2057,7 +1844,9 @@ TEST_P(LeAudioAseConfigurationTest, test_lc3_config_ringtone) { } TEST_P(LeAudioAseConfigurationTest, test_lc3_config_conversational) { - if (codec_coding_format_ != kLeAudioCodingFormatLC3) GTEST_SKIP(); + if (codec_coding_format_ != kLeAudioCodingFormatLC3) { + GTEST_SKIP(); + } AddTestDevice(1, 1); @@ -2065,16 +1854,19 @@ TEST_P(LeAudioAseConfigurationTest, test_lc3_config_conversational) { } TEST_P(LeAudioAseConfigurationTest, test_lc3_config_media) { - if (codec_coding_format_ != kLeAudioCodingFormatLC3) GTEST_SKIP(); + if (codec_coding_format_ != kLeAudioCodingFormatLC3) { + GTEST_SKIP(); + } AddTestDevice(1, 1); TestLc3CodecConfig(LeAudioContextType::MEDIA); } -TEST_P(LeAudioAseConfigurationTest, - test_lc3_config_media_codec_extensibility_fb2) { - if (codec_coding_format_ != kLeAudioCodingFormatLC3) GTEST_SKIP(); +TEST_P(LeAudioAseConfigurationTest, test_lc3_config_media_codec_extensibility_fb2) { + if (codec_coding_format_ != kLeAudioCodingFormatLC3) { + GTEST_SKIP(); + } bool is_fb2_passed_as_requirement = false; auto max_codec_frames_per_sdu = 2; @@ -2084,53 +1876,53 @@ TEST_P(LeAudioAseConfigurationTest, // ON_CALL(*mock_codec_manager_, IsUsingCodecExtensibility) // .WillByDefault(Return(true)); ON_CALL(*mock_codec_manager_, GetCodecConfig) - .WillByDefault(Invoke([&](const bluetooth::le_audio::CodecManager:: - UnicastConfigurationRequirements& - requirements, - bluetooth::le_audio::CodecManager:: - UnicastConfigurationVerifier verifier) { - auto filtered = - *bluetooth::le_audio::AudioSetConfigurationProvider::Get() - ->GetConfigurations(requirements.audio_context_type); - // Filter out the dual bidir SWB configurations - if (!bluetooth::le_audio::CodecManager::GetInstance() - ->IsDualBiDirSwbSupported()) { - filtered.erase( - std::remove_if(filtered.begin(), filtered.end(), - [](auto const& el) { - if (el->confs.source.empty()) return false; - return AudioSetConfigurationProvider::Get() - ->CheckConfigurationIsDualBiDirSwb(*el); - }), - filtered.end()); - } - auto cfg = verifier(requirements, &filtered); - if (cfg == nullptr) { - return std::unique_ptr(nullptr); - } - - auto config = *cfg; - - if (requirements.sink_pacs.has_value()) { - for (auto const& rec : requirements.sink_pacs.value()) { - auto caps = rec.codec_spec_caps.GetAsCoreCodecCapabilities(); - if (caps.HasSupportedMaxCodecFramesPerSdu()) { - if (caps.supported_max_codec_frames_per_sdu.value() == - max_codec_frames_per_sdu) { - // Inject the proper Codec Frames Per SDU as the json - // configs are conservative and will always give us 1 - for (auto& entry : config.confs.sink) { - entry.codec.params.Add( - codec_spec_conf::kLeAudioLtvTypeCodecFrameBlocksPerSdu, - (uint8_t)max_codec_frames_per_sdu); - } - is_fb2_passed_as_requirement = true; - } - } - } - } - return std::make_unique(config); - })); + .WillByDefault(Invoke( + [&](const bluetooth::le_audio::CodecManager::UnicastConfigurationRequirements& + requirements, + bluetooth::le_audio::CodecManager::UnicastConfigurationVerifier verifier) { + auto filtered = *bluetooth::le_audio::AudioSetConfigurationProvider::Get() + ->GetConfigurations(requirements.audio_context_type); + // Filter out the dual bidir SWB configurations + if (!bluetooth::le_audio::CodecManager::GetInstance() + ->IsDualBiDirSwbSupported()) { + filtered.erase( + std::remove_if(filtered.begin(), filtered.end(), + [](auto const& el) { + if (el->confs.source.empty()) { + return false; + } + return AudioSetConfigurationProvider::Get() + ->CheckConfigurationIsDualBiDirSwb(*el); + }), + filtered.end()); + } + auto cfg = verifier(requirements, &filtered); + if (cfg == nullptr) { + return std::unique_ptr(nullptr); + } + + auto config = *cfg; + + if (requirements.sink_pacs.has_value()) { + for (auto const& rec : requirements.sink_pacs.value()) { + auto caps = rec.codec_spec_caps.GetAsCoreCodecCapabilities(); + if (caps.HasSupportedMaxCodecFramesPerSdu()) { + if (caps.supported_max_codec_frames_per_sdu.value() == + max_codec_frames_per_sdu) { + // Inject the proper Codec Frames Per SDU as the json + // configs are conservative and will always give us 1 + for (auto& entry : config.confs.sink) { + entry.codec.params.Add( + codec_spec_conf::kLeAudioLtvTypeCodecFrameBlocksPerSdu, + (uint8_t)max_codec_frames_per_sdu); + } + is_fb2_passed_as_requirement = true; + } + } + } + } + return std::make_unique(config); + })); AddTestDevice(1, 1); @@ -2141,29 +1933,28 @@ TEST_P(LeAudioAseConfigurationTest, } TEST_P(LeAudioAseConfigurationTest, test_unsupported_codec) { - if (codec_coding_format_ == kLeAudioCodingFormatVendorSpecific) GTEST_SKIP(); + if (codec_coding_format_ == kLeAudioCodingFormatVendorSpecific) { + GTEST_SKIP(); + } const LeAudioCodecId UnsupportedCodecId = { - .coding_format = kLeAudioCodingFormatVendorSpecific, - .vendor_company_id = 0xBAD, - .vendor_codec_id = 0xC0DE, + .coding_format = kLeAudioCodingFormatVendorSpecific, + .vendor_company_id = 0xBAD, + .vendor_codec_id = 0xC0DE, }; LeAudioDevice* device = AddTestDevice(1, 0); PublishedAudioCapabilitiesBuilder pac_builder; - pac_builder.Add(UnsupportedCodecId, - GetSamplingFrequency(Lc3SettingId::LC3_16_2), - GetFrameDuration(Lc3SettingId::LC3_16_2), - kLeAudioCodecChannelCountSingleChannel, + pac_builder.Add(UnsupportedCodecId, GetSamplingFrequency(Lc3SettingId::LC3_16_2), + GetFrameDuration(Lc3SettingId::LC3_16_2), kLeAudioCodecChannelCountSingleChannel, GetOctetsPerCodecFrame(Lc3SettingId::LC3_16_2)); device->snk_pacs_ = pac_builder.Get(); device->src_pacs_ = pac_builder.Get(); - ASSERT_FALSE( - group_->Configure(LeAudioContextType::RINGTONE, - {AudioContexts(LeAudioContextType::RINGTONE), - AudioContexts(LeAudioContextType::RINGTONE)})); + ASSERT_FALSE(group_->Configure(LeAudioContextType::RINGTONE, + {AudioContexts(LeAudioContextType::RINGTONE), + AudioContexts(LeAudioContextType::RINGTONE)})); TestAsesInactive(); } @@ -2172,25 +1963,20 @@ TEST_P(LeAudioAseConfigurationTest, test_reconnection_media) { LeAudioDevice* right = AddTestDevice(2, 1); /* Change location as by default it is stereo */ - left->snk_audio_locations_ = - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; - left->src_audio_locations_ = - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; - right->snk_audio_locations_ = - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight; - right->src_audio_locations_ = - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight; + left->snk_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; + left->src_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; + right->snk_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight; + right->src_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight; group_->ReloadAudioLocations(); - TestGroupAseConfigurationData data[] = { - {left, kLeAudioCodecChannelCountSingleChannel, - kLeAudioCodecChannelCountSingleChannel, 1, 0}, - {right, kLeAudioCodecChannelCountSingleChannel, - kLeAudioCodecChannelCountSingleChannel, 1, 0}}; + TestGroupAseConfigurationData data[] = {{left, kLeAudioCodecChannelCountSingleChannel, + kLeAudioCodecChannelCountSingleChannel, 1, 0}, + {right, kLeAudioCodecChannelCountSingleChannel, + kLeAudioCodecChannelCountSingleChannel, 1, 0}}; auto all_configurations = - ::bluetooth::le_audio::AudioSetConfigurationProvider::Get() - ->GetConfigurations(LeAudioContextType::MEDIA); + ::bluetooth::le_audio::AudioSetConfigurationProvider::Get()->GetConfigurations( + LeAudioContextType::MEDIA); ASSERT_NE(nullptr, all_configurations); ASSERT_NE(all_configurations->end(), all_configurations->begin()); auto configuration = *all_configurations->begin(); @@ -2225,25 +2011,22 @@ TEST_P(LeAudioAseConfigurationTest, test_reconnection_media) { auto core_config = ase->codec_config.GetAsCoreCodecConfig(); BidirectionalPair group_audio_locations = { - .sink = *core_config.audio_channel_allocation, - .source = *core_config.audio_channel_allocation}; + .sink = *core_config.audio_channel_allocation, + .source = *core_config.audio_channel_allocation}; /* Get entry for the sink direction and use it to set configuration */ BidirectionalPair> ccid_lists = {{}, {}}; - BidirectionalPair audio_contexts = {AudioContexts(), - AudioContexts()}; + BidirectionalPair audio_contexts = {AudioContexts(), AudioContexts()}; if (!configuration->confs.sink.empty()) { left->ConfigureAses(configuration, group_->Size(), kLeAudioDirectionSink, - group_->GetConfigurationContextType(), - &number_of_active_ases, + group_->GetConfigurationContextType(), &number_of_active_ases, group_audio_locations.get(kLeAudioDirectionSink), audio_contexts.get(kLeAudioDirectionSink), ccid_lists.get(kLeAudioDirectionSink), false); } if (!configuration->confs.source.empty()) { left->ConfigureAses(configuration, group_->Size(), kLeAudioDirectionSource, - group_->GetConfigurationContextType(), - &number_of_active_ases, + group_->GetConfigurationContextType(), &number_of_active_ases, group_audio_locations.get(kLeAudioDirectionSource), audio_contexts.get(kLeAudioDirectionSource), ccid_lists.get(kLeAudioDirectionSource), false); @@ -2252,8 +2035,7 @@ TEST_P(LeAudioAseConfigurationTest, test_reconnection_media) { ASSERT_EQ(number_of_active_ases, 2); ASSERT_EQ(group_audio_locations.sink, kChannelAllocationStereo); - uint8_t directions_to_verify = - ::bluetooth::le_audio::types::kLeAudioDirectionSink; + uint8_t directions_to_verify = ::bluetooth::le_audio::types::kLeAudioDirectionSink; for (int i = 0; i < 2; i++) { TestGroupAseConfigurationVerdict(data[i], directions_to_verify); } @@ -2291,12 +2073,12 @@ TEST_P(LeAudioAseConfigurationTest, test_reactivation_conversational) { /* Change location as by default it is stereo */ tws_headset->snk_audio_locations_ = kChannelAllocationStereo; tws_headset->src_audio_locations_ = - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; + ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; group_->ReloadAudioLocations(); auto conversational_configuration = getSpecificConfiguration( - "Two-OneChan-SnkAse-Lc3_16_2-One-OneChan-SrcAse-Lc3_16_2_Low_Latency", - LeAudioContextType::CONVERSATIONAL); + "Two-OneChan-SnkAse-Lc3_16_2-One-OneChan-SrcAse-Lc3_16_2_Low_Latency", + LeAudioContextType::CONVERSATIONAL); ASSERT_NE(nullptr, conversational_configuration); // Build PACs for device @@ -2321,32 +2103,29 @@ TEST_P(LeAudioAseConfigurationTest, test_reactivation_conversational) { ::bluetooth::le_audio::types::AudioLocations group_src_audio_locations = 0; BidirectionalPair number_of_already_active_ases = {0, 0}; - BidirectionalPair group_audio_locations = { - .sink = group_snk_audio_locations, .source = group_src_audio_locations}; + BidirectionalPair group_audio_locations = {.sink = group_snk_audio_locations, + .source = group_src_audio_locations}; /* Get entry for the sink direction and use it to set configuration */ BidirectionalPair> ccid_lists = {{}, {}}; - BidirectionalPair audio_contexts = {AudioContexts(), - AudioContexts()}; + BidirectionalPair audio_contexts = {AudioContexts(), AudioContexts()}; /* Get entry for the sink direction and use it to set configuration */ if (!conversational_configuration->confs.sink.empty()) { - tws_headset->ConfigureAses( - conversational_configuration, group_->Size(), kLeAudioDirectionSink, - group_->GetConfigurationContextType(), - &number_of_already_active_ases.get(kLeAudioDirectionSink), - group_audio_locations.get(kLeAudioDirectionSink), - audio_contexts.get(kLeAudioDirectionSink), - ccid_lists.get(kLeAudioDirectionSink), false); + tws_headset->ConfigureAses(conversational_configuration, group_->Size(), kLeAudioDirectionSink, + group_->GetConfigurationContextType(), + &number_of_already_active_ases.get(kLeAudioDirectionSink), + group_audio_locations.get(kLeAudioDirectionSink), + audio_contexts.get(kLeAudioDirectionSink), + ccid_lists.get(kLeAudioDirectionSink), false); } if (!conversational_configuration->confs.source.empty()) { - tws_headset->ConfigureAses( - conversational_configuration, group_->Size(), kLeAudioDirectionSource, - group_->GetConfigurationContextType(), - &number_of_already_active_ases.get(kLeAudioDirectionSource), - group_audio_locations.get(kLeAudioDirectionSource), - audio_contexts.get(kLeAudioDirectionSource), - ccid_lists.get(kLeAudioDirectionSource), false); + tws_headset->ConfigureAses(conversational_configuration, group_->Size(), + kLeAudioDirectionSource, group_->GetConfigurationContextType(), + &number_of_already_active_ases.get(kLeAudioDirectionSource), + group_audio_locations.get(kLeAudioDirectionSource), + audio_contexts.get(kLeAudioDirectionSource), + ccid_lists.get(kLeAudioDirectionSource), false); } /* Generate CISes, simulate CIG creation and assign cis handles to ASEs.*/ @@ -2366,17 +2145,15 @@ TEST_P(LeAudioAseConfigurationTest, test_reactivation_conversational) { * the same CIS ID can be used. This would lead to only activating group * without reconfiguring CIG. */ - group_->Activate(LeAudioContextType::CONVERSATIONAL, audio_contexts, - ccid_lists); + group_->Activate(LeAudioContextType::CONVERSATIONAL, audio_contexts, ccid_lists); TestActiveAses(); /* Verify ASEs assigned CISes by counting assigned to bi-directional CISes */ - int bi_dir_ases_count = std::count_if( - tws_headset->ases_.begin(), tws_headset->ases_.end(), [this](auto& ase) { - return this->group_->cig.cises[ase.cis_id].type == - CisType::CIS_TYPE_BIDIRECTIONAL; - }); + int bi_dir_ases_count = + std::count_if(tws_headset->ases_.begin(), tws_headset->ases_.end(), [this](auto& ase) { + return this->group_->cig.cises[ase.cis_id].type == CisType::CIS_TYPE_BIDIRECTIONAL; + }); /* Only two ASEs can be bonded to one bi-directional CIS */ ASSERT_EQ(bi_dir_ases_count, 2); @@ -2419,9 +2196,8 @@ TEST_P(LeAudioAseConfigurationTest, test_getting_cis_count) { right->snk_audio_locations_ = kChannelAllocationStereo; group_->ReloadAudioLocations(); - auto media_configuration = - getSpecificConfiguration("One-TwoChan-SnkAse-Lc3_48_4_High_Reliability", - LeAudioContextType::MEDIA); + auto media_configuration = getSpecificConfiguration( + "One-TwoChan-SnkAse-Lc3_48_4_High_Reliability", LeAudioContextType::MEDIA); ASSERT_NE(nullptr, media_configuration); // Build PACs for device @@ -2431,8 +2207,7 @@ TEST_P(LeAudioAseConfigurationTest, test_getting_cis_count) { /* Create PACs for media. Single PAC for each direction is enough. */ if (media_configuration->confs.sink.size()) { - snk_pac_builder.Add(LeAudioCodecIdLc3, 0x00b5, 0x03, 0x03, 0x001a, 0x00f0, - 2); + snk_pac_builder.Add(LeAudioCodecIdLc3, 0x00b5, 0x03, 0x03, 0x001a, 0x00f0, 2); } left->snk_pacs_ = snk_pac_builder.Get(); @@ -2442,22 +2217,20 @@ TEST_P(LeAudioAseConfigurationTest, test_getting_cis_count) { ::bluetooth::le_audio::types::AudioLocations group_src_audio_locations = 0; uint8_t number_of_already_active_ases = 0; - BidirectionalPair group_audio_locations = { - .sink = group_snk_audio_locations, .source = group_src_audio_locations}; + BidirectionalPair group_audio_locations = {.sink = group_snk_audio_locations, + .source = group_src_audio_locations}; /* Get entry for the sink direction and use it to set configuration */ BidirectionalPair> ccid_lists = {{}, {}}; - BidirectionalPair audio_contexts = {AudioContexts(), - AudioContexts()}; + BidirectionalPair audio_contexts = {AudioContexts(), AudioContexts()}; /* Get entry for the sink direction and use it to set configuration */ if (!media_configuration->confs.sink.empty()) { - left->ConfigureAses( - media_configuration, group_->Size(), kLeAudioDirectionSink, - group_->GetConfigurationContextType(), &number_of_already_active_ases, - group_audio_locations.get(kLeAudioDirectionSink), - audio_contexts.get(kLeAudioDirectionSink), - ccid_lists.get(kLeAudioDirectionSink), false); + left->ConfigureAses(media_configuration, group_->Size(), kLeAudioDirectionSink, + group_->GetConfigurationContextType(), &number_of_already_active_ases, + group_audio_locations.get(kLeAudioDirectionSink), + audio_contexts.get(kLeAudioDirectionSink), + ccid_lists.get(kLeAudioDirectionSink), false); } /* Generate CIS, simulate CIG creation and assign cis handles to ASEs.*/ @@ -2465,11 +2238,9 @@ TEST_P(LeAudioAseConfigurationTest, test_getting_cis_count) { group_->cig.GenerateCisIds(LeAudioContextType::MEDIA); /* Verify prepared CISes by counting generated entries */ - int snk_cis_count = - std::count_if(this->group_->cig.cises.begin(), - this->group_->cig.cises.end(), [](auto& cis) { - return cis.type == CisType::CIS_TYPE_UNIDIRECTIONAL_SINK; - }); + int snk_cis_count = std::count_if( + this->group_->cig.cises.begin(), this->group_->cig.cises.end(), + [](auto& cis) { return cis.type == CisType::CIS_TYPE_UNIDIRECTIONAL_SINK; }); /* Two CIS should be prepared for dual dev expected set */ ASSERT_EQ(snk_cis_count, 2); @@ -2485,9 +2256,8 @@ TEST_P(LeAudioAseConfigurationTest, test_config_support) { group_->ReloadAudioLocations(); auto test_config = getSpecificConfiguration( - "One-OneChan-SnkAse-Lc3_48_4-One-OneChan-SrcAse-Lc3_16_2_Balanced_" - "Reliability", - LeAudioContextType::VOICEASSISTANTS); + "One-OneChan-SnkAse-Lc3_48_4-One-OneChan-SrcAse-Lc3_16_2_Balanced_Reliability", + LeAudioContextType::VOICEASSISTANTS); ASSERT_NE(nullptr, test_config); /* Create PACs for sink */ @@ -2515,21 +2285,16 @@ TEST_P(LeAudioAseConfigurationTest, test_config_support) { ASSERT_TRUE(right->IsAudioSetConfigurationSupported(test_config)); } -TEST_P(LeAudioAseConfigurationTest, - test_vendor_codec_configure_incomplete_group) { +TEST_P(LeAudioAseConfigurationTest, test_vendor_codec_configure_incomplete_group) { // A group of two earbuds LeAudioDevice* left = AddTestDevice(2, 1); LeAudioDevice* right = AddTestDevice(2, 1); /* Change location as by default it is stereo */ - left->snk_audio_locations_ = - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; - left->src_audio_locations_ = - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; - right->snk_audio_locations_ = - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight; - right->src_audio_locations_ = - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight; + left->snk_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; + left->src_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; + right->snk_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight; + right->src_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight; group_->ReloadAudioLocations(); // The Right earbud is currently disconnected @@ -2537,11 +2302,10 @@ TEST_P(LeAudioAseConfigurationTest, uint8_t direction_to_verify = kLeAudioDirectionSink; uint8_t devices_to_verify = 1; - TestGroupAseConfigurationData data[] = { - {left, kLeAudioCodecChannelCountSingleChannel, - kLeAudioCodecChannelCountSingleChannel, 1, 0}, - {right, kLeAudioCodecChannelCountSingleChannel, - kLeAudioCodecChannelCountSingleChannel, 0, 0}}; + TestGroupAseConfigurationData data[] = {{left, kLeAudioCodecChannelCountSingleChannel, + kLeAudioCodecChannelCountSingleChannel, 1, 0}, + {right, kLeAudioCodecChannelCountSingleChannel, + kLeAudioCodecChannelCountSingleChannel, 0, 0}}; TestGroupAseConfiguration(LeAudioContextType::MEDIA, data, devices_to_verify, direction_to_verify); diff --git a/system/bta/le_audio/hal_verifier.cc b/system/bta/le_audio/hal_verifier.cc index 96cc3ad93f4..a498f06ff65 100644 --- a/system/bta/le_audio/hal_verifier.cc +++ b/system/bta/le_audio/hal_verifier.cc @@ -19,9 +19,9 @@ bool LeAudioHalVerifier::SupportsLeAudio() { return bluetooth::audio::HalVersionManager::GetHalTransport() == - bluetooth::audio::BluetoothAudioHalTransport::AIDL || + bluetooth::audio::BluetoothAudioHalTransport::AIDL || bluetooth::audio::HalVersionManager::GetHalVersion() >= - bluetooth::audio::BluetoothAudioHalVersion::VERSION_2_1; + bluetooth::audio::BluetoothAudioHalVersion::VERSION_2_1; } bool LeAudioHalVerifier::SupportsLeAudioHardwareOffload() { diff --git a/system/bta/le_audio/le_audio_client_test.cc b/system/bta/le_audio/le_audio_client_test.cc index a216a4acc49..bbd42167c84 100644 --- a/system/bta/le_audio/le_audio_client_test.cc +++ b/system/bta/le_audio/le_audio_client_test.cc @@ -94,54 +94,49 @@ using bluetooth::le_audio::types::LeAudioContextType; extern struct fake_osi_alarm_set_on_mloop fake_osi_alarm_set_on_mloop_; constexpr int max_num_of_ases = 5; -constexpr bluetooth::le_audio::types::LeAudioContextType - kLeAudioDefaultConfigurationContext = +constexpr bluetooth::le_audio::types::LeAudioContextType kLeAudioDefaultConfigurationContext = bluetooth::le_audio::types::LeAudioContextType::UNSPECIFIED; static constexpr char kNotifyUpperLayerAboutGroupBeingInIdleDuringCall[] = - "persist.bluetooth.leaudio.notify.idle.during.call"; + "persist.bluetooth.leaudio.notify.idle.during.call"; const char* test_flags[] = { - "INIT_default_log_level_str=LOG_VERBOSE", - "INIT_leaudio_targeted_announcement_reconnection_mode=true", - "INIT_leaudio_broadcast_audio_handover_policies=false", - nullptr, + "INIT_default_log_level_str=LOG_VERBOSE", + "INIT_leaudio_targeted_announcement_reconnection_mode=true", + "INIT_leaudio_broadcast_audio_handover_policies=false", + nullptr, }; const char* test_flags_with_handover_mode[] = { - "INIT_default_log_level_str=LOG_VERBOSE", - "INIT_leaudio_targeted_announcement_reconnection_mode=true", - "INIT_leaudio_broadcast_audio_handover_policies=true", - nullptr, + "INIT_default_log_level_str=LOG_VERBOSE", + "INIT_leaudio_targeted_announcement_reconnection_mode=true", + "INIT_leaudio_broadcast_audio_handover_policies=true", + nullptr, }; void osi_property_set_bool(const char* key, bool value); // Disables most likely false-positives from base::SplitString() -extern "C" const char* __asan_default_options() { - return "detect_container_overflow=0"; -} +extern "C" const char* __asan_default_options() { return "detect_container_overflow=0"; } std::atomic num_async_tasks; static base::MessageLoop* message_loop_; bluetooth::common::MessageLoopThread message_loop_thread("test message loop"); -bluetooth::common::MessageLoopThread* get_main_thread() { - return &message_loop_thread; -} +bluetooth::common::MessageLoopThread* get_main_thread() { return &message_loop_thread; } -bt_status_t do_in_main_thread(const base::Location& from_here, - base::OnceClosure task) { - if (!message_loop_) return BT_STATUS_FAIL; +bt_status_t do_in_main_thread(const base::Location& from_here, base::OnceClosure task) { + if (!message_loop_) { + return BT_STATUS_FAIL; + } // Wrap the task with task counter so we could later know if there are // any callbacks scheduled and we should wait before performing some actions if (!message_loop_thread.DoInThread( - from_here, - base::BindOnce( - [](base::OnceClosure task, std::atomic& num_async_tasks) { - std::move(task).Run(); - num_async_tasks--; - }, - std::move(task), std::ref(num_async_tasks)))) { + from_here, base::BindOnce( + [](base::OnceClosure task, std::atomic& num_async_tasks) { + std::move(task).Run(); + num_async_tasks--; + }, + std::move(task), std::ref(num_async_tasks)))) { bluetooth::log::error("failed from {}", from_here.ToString()); return BT_STATUS_FAIL; } @@ -149,8 +144,7 @@ bt_status_t do_in_main_thread(const base::Location& from_here, return BT_STATUS_SUCCESS; } -bt_status_t do_in_main_thread_delayed(const base::Location& from_here, - base::OnceClosure task, +bt_status_t do_in_main_thread_delayed(const base::Location& from_here, base::OnceClosure task, std::chrono::microseconds delay) { /* For testing purpose it is ok to just skip delay */ return do_in_main_thread(from_here, std::move(task)); @@ -165,11 +159,14 @@ static void init_message_loop_thread() { FAIL() << "unable to create message loop thread."; } - if (!message_loop_thread.EnableRealTimeScheduling()) + if (!message_loop_thread.EnableRealTimeScheduling()) { bluetooth::log::error("Unable to set real time scheduling"); + } message_loop_ = message_loop_thread.message_loop(); - if (message_loop_ == nullptr) FAIL() << "unable to get message loop."; + if (message_loop_ == nullptr) { + FAIL() << "unable to get message loop."; + } } static void cleanup_message_loop_thread() { @@ -197,37 +194,31 @@ bool get_pts_le_audio_disable_ases_before_stopping(void) { return false; } config_t* get_all(void) { return nullptr; } stack_config_t mock_stack_config{ - .get_pts_avrcp_test = get_pts_avrcp_test, - .get_pts_secure_only_mode = get_pts_secure_only_mode, - .get_pts_conn_updates_disabled = get_pts_conn_updates_disabled, - .get_pts_crosskey_sdp_disable = get_pts_crosskey_sdp_disable, - .get_pts_smp_options = get_pts_smp_options, - .get_pts_smp_failure_case = get_pts_smp_failure_case, - .get_pts_force_eatt_for_notifications = - get_pts_force_eatt_for_notifications, - .get_pts_connect_eatt_unconditionally = - get_pts_connect_eatt_unconditionally, - .get_pts_connect_eatt_before_encryption = - get_pts_connect_eatt_before_encryption, - .get_pts_unencrypt_broadcast = get_pts_unencrypt_broadcast, - .get_pts_eatt_peripheral_collision_support = - get_pts_eatt_peripheral_collision_support, - .get_pts_force_le_audio_multiple_contexts_metadata = - get_pts_force_le_audio_multiple_contexts_metadata, - .get_pts_le_audio_disable_ases_before_stopping = - get_pts_le_audio_disable_ases_before_stopping, - .get_all = get_all, + .get_pts_avrcp_test = get_pts_avrcp_test, + .get_pts_secure_only_mode = get_pts_secure_only_mode, + .get_pts_conn_updates_disabled = get_pts_conn_updates_disabled, + .get_pts_crosskey_sdp_disable = get_pts_crosskey_sdp_disable, + .get_pts_smp_options = get_pts_smp_options, + .get_pts_smp_failure_case = get_pts_smp_failure_case, + .get_pts_force_eatt_for_notifications = get_pts_force_eatt_for_notifications, + .get_pts_connect_eatt_unconditionally = get_pts_connect_eatt_unconditionally, + .get_pts_connect_eatt_before_encryption = get_pts_connect_eatt_before_encryption, + .get_pts_unencrypt_broadcast = get_pts_unencrypt_broadcast, + .get_pts_eatt_peripheral_collision_support = get_pts_eatt_peripheral_collision_support, + .get_pts_force_le_audio_multiple_contexts_metadata = + get_pts_force_le_audio_multiple_contexts_metadata, + .get_pts_le_audio_disable_ases_before_stopping = + get_pts_le_audio_disable_ases_before_stopping, + .get_all = get_all, }; -const stack_config_t* stack_config_get_interface(void) { - return &mock_stack_config; -} +const stack_config_t* stack_config_get_interface(void) { return &mock_stack_config; } bool LeAudioBroadcaster::IsLeAudioBroadcasterRunning() { return false; } namespace server_configurable_flags { -std::string GetServerConfigurableFlag( - const std::string& experiment_category_name, - const std::string& experiment_flag_name, const std::string& default_value) { +std::string GetServerConfigurableFlag(const std::string& experiment_category_name, + const std::string& experiment_flag_name, + const std::string& default_value) { return ""; } } // namespace server_configurable_flags @@ -235,13 +226,13 @@ std::string GetServerConfigurableFlag( namespace bluetooth::le_audio { class MockLeAudioSourceHalClient; MockLeAudioSourceHalClient* mock_le_audio_source_hal_client_; -std::unique_ptr - owned_mock_le_audio_source_hal_client_; +std::unique_ptr owned_mock_le_audio_source_hal_client_; bool is_audio_unicast_source_acquired; -std::unique_ptr -LeAudioSourceAudioHalClient::AcquireUnicast() { - if (is_audio_unicast_source_acquired) return nullptr; +std::unique_ptr LeAudioSourceAudioHalClient::AcquireUnicast() { + if (is_audio_unicast_source_acquired) { + return nullptr; + } is_audio_unicast_source_acquired = true; return std::move(owned_mock_le_audio_source_hal_client_); } @@ -253,55 +244,46 @@ MockLeAudioSinkHalClient* mock_le_audio_sink_hal_client_; std::unique_ptr owned_mock_le_audio_sink_hal_client_; bool is_audio_unicast_sink_acquired; -std::unique_ptr -LeAudioSinkAudioHalClient::AcquireUnicast() { - if (is_audio_unicast_sink_acquired) return nullptr; +std::unique_ptr LeAudioSinkAudioHalClient::AcquireUnicast() { + if (is_audio_unicast_sink_acquired) { + return nullptr; + } is_audio_unicast_sink_acquired = true; return std::move(owned_mock_le_audio_sink_hal_client_); } void LeAudioSinkAudioHalClient::DebugDump(int fd) {} -class MockAudioHalClientCallbacks - : public bluetooth::le_audio::LeAudioClientCallbacks { - public: +class MockAudioHalClientCallbacks : public bluetooth::le_audio::LeAudioClientCallbacks { +public: MOCK_METHOD((void), OnInitialized, (), (override)); - MOCK_METHOD((void), OnConnectionState, - (ConnectionState state, const RawAddress& address), (override)); - MOCK_METHOD((void), OnGroupStatus, (int group_id, GroupStatus group_status), + MOCK_METHOD((void), OnConnectionState, (ConnectionState state, const RawAddress& address), (override)); - MOCK_METHOD((void), OnGroupStreamStatus, - (int group_id, GroupStreamStatus group_stream_status), + MOCK_METHOD((void), OnGroupStatus, (int group_id, GroupStatus group_status), (override)); + MOCK_METHOD((void), OnGroupStreamStatus, (int group_id, GroupStreamStatus group_stream_status), (override)); MOCK_METHOD((void), OnGroupNodeStatus, - (const RawAddress& bd_addr, int group_id, - GroupNodeStatus node_status), - (override)); + (const RawAddress& bd_addr, int group_id, GroupNodeStatus node_status), (override)); MOCK_METHOD((void), OnAudioConf, (uint8_t direction, int group_id, uint32_t snk_audio_location, uint32_t src_audio_location, uint16_t avail_cont), (override)); MOCK_METHOD((void), OnSinkAudioLocationAvailable, - (const RawAddress& bd_addr, uint32_t snk_audio_location), + (const RawAddress& bd_addr, uint32_t snk_audio_location), (override)); + MOCK_METHOD((void), OnAudioLocalCodecCapabilities, + (std::vector local_input_capa_codec_conf, + std::vector local_output_capa_codec_conf), (override)); - MOCK_METHOD( - (void), OnAudioLocalCodecCapabilities, - (std::vector local_input_capa_codec_conf, - std::vector local_output_capa_codec_conf), - (override)); MOCK_METHOD((void), OnAudioGroupCurrentCodecConf, (int group_id, btle_audio_codec_config_t input_codec_conf, btle_audio_codec_config_t output_codec_conf), (override)); - MOCK_METHOD( - (void), OnAudioGroupSelectableCodecConf, - (int group_id, - std::vector input_selectable_codec_conf, - std::vector output_selectable_codec_conf), - (override)); - MOCK_METHOD((void), OnHealthBasedRecommendationAction, - (const RawAddress& address, LeAudioHealthBasedAction action), + MOCK_METHOD((void), OnAudioGroupSelectableCodecConf, + (int group_id, std::vector input_selectable_codec_conf, + std::vector output_selectable_codec_conf), (override)); + MOCK_METHOD((void), OnHealthBasedRecommendationAction, + (const RawAddress& address, LeAudioHealthBasedAction action), (override)); MOCK_METHOD((void), OnHealthBasedGroupRecommendationAction, (int group_id, LeAudioHealthBasedAction action), (override)); MOCK_METHOD((void), OnUnicastMonitorModeStatus, @@ -309,20 +291,19 @@ class MockAudioHalClientCallbacks }; class MockLeAudioSinkHalClient : public LeAudioSinkAudioHalClient { - public: +public: MockLeAudioSinkHalClient() = default; MOCK_METHOD((bool), Start, (const LeAudioCodecConfiguration& codecConfiguration, - LeAudioSinkAudioHalClient::Callbacks* audioReceiver, - DsaModes dsa_modes), + LeAudioSinkAudioHalClient::Callbacks* audioReceiver, DsaModes dsa_modes), (override)); MOCK_METHOD((void), Stop, (), (override)); - MOCK_METHOD((size_t), SendData, (uint8_t * data, uint16_t size), (override)); + MOCK_METHOD((size_t), SendData, (uint8_t* data, uint16_t size), (override)); MOCK_METHOD((void), ConfirmStreamingRequest, (), (override)); MOCK_METHOD((void), CancelStreamingRequest, (), (override)); MOCK_METHOD((void), UpdateRemoteDelay, (uint16_t delay), (override)); - MOCK_METHOD((void), UpdateAudioConfigToHal, - (const ::bluetooth::le_audio::offload_config&), (override)); + MOCK_METHOD((void), UpdateAudioConfigToHal, (const ::bluetooth::le_audio::offload_config&), + (override)); MOCK_METHOD((void), SuspendedForReconfiguration, (), (override)); MOCK_METHOD((void), ReconfigurationComplete, (), (override)); @@ -331,33 +312,27 @@ class MockLeAudioSinkHalClient : public LeAudioSinkAudioHalClient { }; class MockLeAudioSourceHalClient : public LeAudioSourceAudioHalClient { - public: +public: MockLeAudioSourceHalClient() = default; MOCK_METHOD((bool), Start, (const LeAudioCodecConfiguration& codecConfiguration, - LeAudioSourceAudioHalClient::Callbacks* audioReceiver, - DsaModes dsa_modes), + LeAudioSourceAudioHalClient::Callbacks* audioReceiver, DsaModes dsa_modes), (override)); MOCK_METHOD((void), Stop, (), (override)); MOCK_METHOD((void), ConfirmStreamingRequest, (), (override)); MOCK_METHOD((void), CancelStreamingRequest, (), (override)); MOCK_METHOD((void), UpdateRemoteDelay, (uint16_t delay), (override)); - MOCK_METHOD((void), UpdateAudioConfigToHal, - (const ::bluetooth::le_audio::offload_config&), (override)); - MOCK_METHOD( - (std::optional), GetBroadcastConfig, - ((const std::vector>&), - (const std::optional< - std::vector<::bluetooth::le_audio::types::acs_ac_record>>&)), - (const override)); - MOCK_METHOD( - (std::optional< - ::bluetooth::le_audio::set_configurations::AudioSetConfiguration>), - GetUnicastConfig, (const CodecManager::UnicastConfigurationRequirements&), - (const override)); - MOCK_METHOD((void), UpdateBroadcastAudioConfigToHal, - (const ::bluetooth::le_audio::broadcast_offload_config&), + MOCK_METHOD((void), UpdateAudioConfigToHal, (const ::bluetooth::le_audio::offload_config&), (override)); + MOCK_METHOD((std::optional), GetBroadcastConfig, + ((const std::vector>&), + (const std::optional>&)), + (const override)); + MOCK_METHOD((std::optional<::bluetooth::le_audio::set_configurations::AudioSetConfiguration>), + GetUnicastConfig, (const CodecManager::UnicastConfigurationRequirements&), + (const override)); + MOCK_METHOD((void), UpdateBroadcastAudioConfigToHal, + (const ::bluetooth::le_audio::broadcast_offload_config&), (override)); MOCK_METHOD((void), SuspendedForReconfiguration, (), (override)); MOCK_METHOD((void), ReconfigurationComplete, (), (override)); @@ -366,23 +341,20 @@ class MockLeAudioSourceHalClient : public LeAudioSourceAudioHalClient { }; class UnicastTestNoInit : public Test { - public: +public: bool use_handover_mode = false; - protected: +protected: void RegisterSourceHalClientMock() { - owned_mock_le_audio_source_hal_client_.reset( - new NiceMock()); + owned_mock_le_audio_source_hal_client_.reset(new NiceMock()); mock_le_audio_source_hal_client_ = - (MockLeAudioSourceHalClient*) - owned_mock_le_audio_source_hal_client_.get(); + (MockLeAudioSourceHalClient*)owned_mock_le_audio_source_hal_client_.get(); is_audio_unicast_source_acquired = false; ON_CALL(*mock_le_audio_source_hal_client_, Start(_, _, _)) - .WillByDefault( - [this](const LeAudioCodecConfiguration& codec_configuration, - LeAudioSourceAudioHalClient::Callbacks* audioReceiver, - DsaModes dsa_modes) { + .WillByDefault([this](const LeAudioCodecConfiguration& codec_configuration, + LeAudioSourceAudioHalClient::Callbacks* audioReceiver, + DsaModes dsa_modes) { unicast_source_hal_cb_ = audioReceiver; return true; }); @@ -393,17 +365,15 @@ class UnicastTestNoInit : public Test { } void RegisterSinkHalClientMock() { - owned_mock_le_audio_sink_hal_client_.reset( - new NiceMock()); + owned_mock_le_audio_sink_hal_client_.reset(new NiceMock()); mock_le_audio_sink_hal_client_ = - (MockLeAudioSinkHalClient*)owned_mock_le_audio_sink_hal_client_.get(); + (MockLeAudioSinkHalClient*)owned_mock_le_audio_sink_hal_client_.get(); is_audio_unicast_sink_acquired = false; ON_CALL(*mock_le_audio_sink_hal_client_, Start(_, _, _)) - .WillByDefault( - [this](const LeAudioCodecConfiguration& codec_configuration, - LeAudioSinkAudioHalClient::Callbacks* audioReceiver, - DsaModes dsa_modes) { + .WillByDefault([this](const LeAudioCodecConfiguration& codec_configuration, + LeAudioSinkAudioHalClient::Callbacks* audioReceiver, + DsaModes dsa_modes) { unicast_sink_hal_cb_ = audioReceiver; return true; }); @@ -425,23 +395,19 @@ class UnicastTestNoInit : public Test { */ RegisterSourceHalClientMock(); - owned_mock_le_audio_sink_hal_client_.reset( - new NiceMock()); + owned_mock_le_audio_sink_hal_client_.reset(new NiceMock()); mock_le_audio_sink_hal_client_ = - (MockLeAudioSinkHalClient*)owned_mock_le_audio_sink_hal_client_.get(); + (MockLeAudioSinkHalClient*)owned_mock_le_audio_sink_hal_client_.get(); - owned_mock_le_audio_source_hal_client_.reset( - new NiceMock()); + owned_mock_le_audio_source_hal_client_.reset(new NiceMock()); mock_le_audio_source_hal_client_ = - (MockLeAudioSourceHalClient*) - owned_mock_le_audio_source_hal_client_.get(); + (MockLeAudioSourceHalClient*)owned_mock_le_audio_source_hal_client_.get(); is_audio_unicast_source_acquired = false; ON_CALL(*mock_le_audio_source_hal_client_, Start(_, _, _)) - .WillByDefault( - [this](const LeAudioCodecConfiguration& codec_configuration, - LeAudioSourceAudioHalClient::Callbacks* audioReceiver, - DsaModes dsa_modes) { + .WillByDefault([this](const LeAudioCodecConfiguration& codec_configuration, + LeAudioSourceAudioHalClient::Callbacks* audioReceiver, + DsaModes dsa_modes) { unicast_source_hal_cb_ = audioReceiver; return true; }); @@ -452,10 +418,9 @@ class UnicastTestNoInit : public Test { is_audio_unicast_sink_acquired = false; ON_CALL(*mock_le_audio_sink_hal_client_, Start(_, _, _)) - .WillByDefault( - [this](const LeAudioCodecConfiguration& codec_configuration, - LeAudioSinkAudioHalClient::Callbacks* audioReceiver, - DsaModes dsa_modes) { + .WillByDefault([this](const LeAudioCodecConfiguration& codec_configuration, + LeAudioSinkAudioHalClient::Callbacks* audioReceiver, + DsaModes dsa_modes) { unicast_sink_hal_cb_ = audioReceiver; return true; }); @@ -465,12 +430,10 @@ class UnicastTestNoInit : public Test { }); ON_CALL(*mock_le_audio_sink_hal_client_, SendData) - .WillByDefault([](uint8_t* data, uint16_t size) { return size; }); + .WillByDefault([](uint8_t* data, uint16_t size) { return size; }); // HAL - ON_CALL(mock_hal_2_1_verifier, Call()).WillByDefault([]() -> bool { - return true; - }); + ON_CALL(mock_hal_2_1_verifier, Call()).WillByDefault([]() -> bool { return true; }); } void InjectGroupDeviceRemoved(const RawAddress& address, int group_id) { @@ -482,50 +445,49 @@ class UnicastTestNoInit : public Test { int group_members_num = 0; for (const auto& [addr, id] : groups) { - if (id == group_id) group_members_num++; + if (id == group_id) { + group_members_num++; + } } bool first_device = (group_members_num == 1); - do_in_main_thread( - FROM_HERE, - base::BindOnce( - [](const RawAddress& addr, int group_id, bluetooth::Uuid uuid, - bluetooth::groups::DeviceGroupsCallbacks* group_callbacks, - bool first_device) { - if (first_device) { - group_callbacks->OnGroupAdded(addr, uuid, group_id); - } else { - group_callbacks->OnGroupMemberAdded(addr, group_id); - } - }, - address, group_id, uuid, base::Unretained(this->group_callbacks_), - first_device)); + do_in_main_thread(FROM_HERE, + base::BindOnce( + [](const RawAddress& addr, int group_id, bluetooth::Uuid uuid, + bluetooth::groups::DeviceGroupsCallbacks* group_callbacks, + bool first_device) { + if (first_device) { + group_callbacks->OnGroupAdded(addr, uuid, group_id); + } else { + group_callbacks->OnGroupMemberAdded(addr, group_id); + } + }, + address, group_id, uuid, base::Unretained(this->group_callbacks_), + first_device)); } void InjectServiceChangedEvent(const RawAddress& address, uint16_t conn_id) { - tBTA_GATTC_SERVICE_CHANGED event_data = {.remote_bda = address, - .conn_id = conn_id}; + tBTA_GATTC_SERVICE_CHANGED event_data = {.remote_bda = address, .conn_id = conn_id}; - do_in_main_thread(FROM_HERE, - base::BindOnce( - [](tBTA_GATTC_CBACK* gatt_callback, - tBTA_GATTC_SERVICE_CHANGED event_data) { - gatt_callback(BTA_GATTC_SRVC_CHG_EVT, - (tBTA_GATTC*)&event_data); - }, - base::Unretained(this->gatt_callback), event_data)); + do_in_main_thread( + FROM_HERE, + base::BindOnce( + [](tBTA_GATTC_CBACK* gatt_callback, tBTA_GATTC_SERVICE_CHANGED event_data) { + gatt_callback(BTA_GATTC_SRVC_CHG_EVT, (tBTA_GATTC*)&event_data); + }, + base::Unretained(this->gatt_callback), event_data)); } void InjectConnectedEvent(const RawAddress& address, uint16_t conn_id, tGATT_STATUS status = GATT_SUCCESS) { ASSERT_NE(conn_id, GATT_INVALID_CONN_ID); tBTA_GATTC_OPEN event_data = { - .status = status, - .conn_id = conn_id, - .client_if = gatt_if, - .remote_bda = address, - .transport = GATT_TRANSPORT_LE, - .mtu = 240, + .status = status, + .conn_id = conn_id, + .client_if = gatt_if, + .remote_bda = address, + .transport = GATT_TRANSPORT_LE, + .mtu = 240, }; if (status == GATT_SUCCESS) { @@ -533,134 +495,124 @@ class UnicastTestNoInit : public Test { peer_devices.at(conn_id)->connected = true; } - do_in_main_thread( - FROM_HERE, - base::BindOnce( - [](tBTA_GATTC_CBACK* gatt_callback, tBTA_GATTC_OPEN event_data) { - gatt_callback(BTA_GATTC_OPEN_EVT, (tBTA_GATTC*)&event_data); - }, - base::Unretained(this->gatt_callback), event_data)); + do_in_main_thread(FROM_HERE, + base::BindOnce( + [](tBTA_GATTC_CBACK* gatt_callback, tBTA_GATTC_OPEN event_data) { + gatt_callback(BTA_GATTC_OPEN_EVT, (tBTA_GATTC*)&event_data); + }, + base::Unretained(this->gatt_callback), event_data)); } void InjectEncryptionChangedEvent(const RawAddress& address) { tBTA_GATTC_ENC_CMPL_CB event_data = { - .client_if = gatt_if, - .remote_bda = address, + .client_if = gatt_if, + .remote_bda = address, }; - do_in_main_thread(FROM_HERE, - base::BindOnce( - [](tBTA_GATTC_CBACK* gatt_callback, - tBTA_GATTC_ENC_CMPL_CB event_data) { - gatt_callback(BTA_GATTC_ENC_CMPL_CB_EVT, - (tBTA_GATTC*)&event_data); - }, - base::Unretained(this->gatt_callback), event_data)); + do_in_main_thread( + FROM_HERE, + base::BindOnce( + [](tBTA_GATTC_CBACK* gatt_callback, tBTA_GATTC_ENC_CMPL_CB event_data) { + gatt_callback(BTA_GATTC_ENC_CMPL_CB_EVT, (tBTA_GATTC*)&event_data); + }, + base::Unretained(this->gatt_callback), event_data)); } - void InjectDisconnectedEvent( - uint16_t conn_id, - tGATT_DISCONN_REASON reason = GATT_CONN_TERMINATE_LOCAL_HOST) { + void InjectDisconnectedEvent(uint16_t conn_id, + tGATT_DISCONN_REASON reason = GATT_CONN_TERMINATE_LOCAL_HOST) { ASSERT_NE(conn_id, GATT_INVALID_CONN_ID); ASSERT_NE(peer_devices.count(conn_id), 0u); tBTA_GATTC_CLOSE event_data = { - .conn_id = conn_id, - .status = GATT_SUCCESS, - .client_if = gatt_if, - .remote_bda = peer_devices.at(conn_id)->addr, - .reason = reason, + .conn_id = conn_id, + .status = GATT_SUCCESS, + .client_if = gatt_if, + .remote_bda = peer_devices.at(conn_id)->addr, + .reason = reason, }; peer_devices.at(conn_id)->connected = false; - do_in_main_thread( - FROM_HERE, - base::BindOnce( - [](tBTA_GATTC_CBACK* gatt_callback, tBTA_GATTC_CLOSE event_data) { - gatt_callback(BTA_GATTC_CLOSE_EVT, (tBTA_GATTC*)&event_data); - }, - base::Unretained(this->gatt_callback), event_data)); + do_in_main_thread(FROM_HERE, + base::BindOnce( + [](tBTA_GATTC_CBACK* gatt_callback, tBTA_GATTC_CLOSE event_data) { + gatt_callback(BTA_GATTC_CLOSE_EVT, (tBTA_GATTC*)&event_data); + }, + base::Unretained(this->gatt_callback), event_data)); } void InjectPhyChangedEvent(uint16_t conn_id, uint8_t tx_phy, uint8_t rx_phy, tGATT_STATUS status) { ASSERT_NE(conn_id, GATT_INVALID_CONN_ID); tBTA_GATTC_PHY_UPDATE event_data = { - .conn_id = conn_id, - .tx_phy = tx_phy, - .rx_phy = rx_phy, - .status = status, + .conn_id = conn_id, + .tx_phy = tx_phy, + .rx_phy = rx_phy, + .status = status, }; - do_in_main_thread(FROM_HERE, - base::BindOnce( - [](tBTA_GATTC_CBACK* gatt_callback, - tBTA_GATTC_PHY_UPDATE event_data) { - gatt_callback(BTA_GATTC_PHY_UPDATE_EVT, - (tBTA_GATTC*)&event_data); - }, - base::Unretained(this->gatt_callback), event_data)); + do_in_main_thread( + FROM_HERE, + base::BindOnce( + [](tBTA_GATTC_CBACK* gatt_callback, tBTA_GATTC_PHY_UPDATE event_data) { + gatt_callback(BTA_GATTC_PHY_UPDATE_EVT, (tBTA_GATTC*)&event_data); + }, + base::Unretained(this->gatt_callback), event_data)); } void InjectSearchCompleteEvent(uint16_t conn_id) { ASSERT_NE(conn_id, GATT_INVALID_CONN_ID); tBTA_GATTC_SEARCH_CMPL event_data = { - .conn_id = conn_id, - .status = GATT_SUCCESS, + .conn_id = conn_id, + .status = GATT_SUCCESS, }; - do_in_main_thread(FROM_HERE, - base::BindOnce( - [](tBTA_GATTC_CBACK* gatt_callback, - tBTA_GATTC_SEARCH_CMPL event_data) { - gatt_callback(BTA_GATTC_SEARCH_CMPL_EVT, - (tBTA_GATTC*)&event_data); - }, - base::Unretained(this->gatt_callback), event_data)); + do_in_main_thread( + FROM_HERE, + base::BindOnce( + [](tBTA_GATTC_CBACK* gatt_callback, tBTA_GATTC_SEARCH_CMPL event_data) { + gatt_callback(BTA_GATTC_SEARCH_CMPL_EVT, (tBTA_GATTC*)&event_data); + }, + base::Unretained(this->gatt_callback), event_data)); } - void InjectNotificationEvent(const RawAddress& test_address, uint16_t conn_id, - uint16_t handle, std::vector value) { + void InjectNotificationEvent(const RawAddress& test_address, uint16_t conn_id, uint16_t handle, + std::vector value) { ASSERT_NE(conn_id, GATT_INVALID_CONN_ID); tBTA_GATTC_NOTIFY event_data = { - .conn_id = conn_id, - .bda = test_address, - .handle = handle, - .len = (uint8_t)value.size(), - .is_notify = true, + .conn_id = conn_id, + .bda = test_address, + .handle = handle, + .len = (uint8_t)value.size(), + .is_notify = true, }; std::copy(value.begin(), value.end(), event_data.value); - do_in_main_thread( - FROM_HERE, - base::BindOnce( - [](tBTA_GATTC_CBACK* gatt_callback, tBTA_GATTC_NOTIFY event_data) { - gatt_callback(BTA_GATTC_NOTIF_EVT, (tBTA_GATTC*)&event_data); - }, - base::Unretained(this->gatt_callback), event_data)); + do_in_main_thread(FROM_HERE, + base::BindOnce( + [](tBTA_GATTC_CBACK* gatt_callback, tBTA_GATTC_NOTIFY event_data) { + gatt_callback(BTA_GATTC_NOTIF_EVT, (tBTA_GATTC*)&event_data); + }, + base::Unretained(this->gatt_callback), event_data)); } - void InjectContextTypes(const RawAddress& test_address, uint16_t conn_id, - uint16_t handle, AudioContexts sink_ctxs, - AudioContexts source_ctxs) { + void InjectContextTypes(const RawAddress& test_address, uint16_t conn_id, uint16_t handle, + AudioContexts sink_ctxs, AudioContexts source_ctxs) { std::vector contexts = { - (uint8_t)(sink_ctxs.value()), (uint8_t)(sink_ctxs.value() >> 8), - (uint8_t)(source_ctxs.value()), (uint8_t)(source_ctxs.value() >> 8)}; + (uint8_t)(sink_ctxs.value()), (uint8_t)(sink_ctxs.value() >> 8), + (uint8_t)(source_ctxs.value()), (uint8_t)(source_ctxs.value() >> 8)}; InjectNotificationEvent(test_address, conn_id, handle, contexts); } - void InjectSupportedContextTypes(const RawAddress& test_address, - uint16_t conn_id, AudioContexts sink_ctxs, - AudioContexts source_ctxs) { + void InjectSupportedContextTypes(const RawAddress& test_address, uint16_t conn_id, + AudioContexts sink_ctxs, AudioContexts source_ctxs) { /* 0x0077 pacs->supp_contexts_char + 1 */ InjectContextTypes(test_address, conn_id, 0x0077, sink_ctxs, source_ctxs); SyncOnMainLoop(); } - void InjectAvailableContextTypes(const RawAddress& test_address, - uint16_t conn_id, AudioContexts sink_ctxs, - AudioContexts source_ctxs, + void InjectAvailableContextTypes(const RawAddress& test_address, uint16_t conn_id, + AudioContexts sink_ctxs, AudioContexts source_ctxs, bool sync_on_mainloop = true) { /* 0x0074 is pacs->avail_contexts_char + 1 */ InjectContextTypes(test_address, conn_id, 0x0074, sink_ctxs, source_ctxs); @@ -672,28 +624,24 @@ class UnicastTestNoInit : public Test { void SetUpMockGatt() { // default action for GetCharacteristic function call ON_CALL(mock_gatt_interface_, GetCharacteristic(_, _)) - .WillByDefault( - Invoke([&](uint16_t conn_id, - uint16_t handle) -> const gatt::Characteristic* { - std::list& services = - peer_devices.at(conn_id)->services; - for (auto const& service : services) { - for (auto const& characteristic : service.characteristics) { - if (characteristic.value_handle == handle) { - return &characteristic; - } - } - } + .WillByDefault( + Invoke([&](uint16_t conn_id, uint16_t handle) -> const gatt::Characteristic* { + std::list& services = peer_devices.at(conn_id)->services; + for (auto const& service : services) { + for (auto const& characteristic : service.characteristics) { + if (characteristic.value_handle == handle) { + return &characteristic; + } + } + } - return nullptr; - })); + return nullptr; + })); // default action for GetOwningService function call ON_CALL(mock_gatt_interface_, GetOwningService(_, _)) - .WillByDefault(Invoke( - [&](uint16_t conn_id, uint16_t handle) -> const gatt::Service* { - std::list& services = - peer_devices.at(conn_id)->services; + .WillByDefault(Invoke([&](uint16_t conn_id, uint16_t handle) -> const gatt::Service* { + std::list& services = peer_devices.at(conn_id)->services; for (auto const& service : services) { if (service.handle <= handle && service.end_handle >= handle) { return &service; @@ -705,161 +653,155 @@ class UnicastTestNoInit : public Test { // default action for ServiceSearchRequest function call ON_CALL(mock_gatt_interface_, ServiceSearchRequest(_, _)) - .WillByDefault(WithArg<0>(Invoke( - [&](uint16_t conn_id) { InjectSearchCompleteEvent(conn_id); }))); + .WillByDefault(WithArg<0>( + Invoke([&](uint16_t conn_id) { InjectSearchCompleteEvent(conn_id); }))); // default action for GetServices function call ON_CALL(mock_gatt_interface_, GetServices(_)) - .WillByDefault(WithArg<0>( - Invoke([&](uint16_t conn_id) -> std::list* { + .WillByDefault(WithArg<0>(Invoke([&](uint16_t conn_id) -> std::list* { return &peer_devices.at(conn_id)->services; }))); // default action for RegisterForNotifications function call ON_CALL(mock_gatt_interface_, RegisterForNotifications(gatt_if, _, _)) - .WillByDefault(Return(GATT_SUCCESS)); + .WillByDefault(Return(GATT_SUCCESS)); // default action for DeregisterForNotifications function call ON_CALL(mock_gatt_interface_, DeregisterForNotifications(gatt_if, _, _)) - .WillByDefault(Return(GATT_SUCCESS)); + .WillByDefault(Return(GATT_SUCCESS)); // default action for WriteDescriptor function call ON_CALL(mock_gatt_queue_, WriteDescriptor(_, _, _, _, _, _)) - .WillByDefault(Invoke([this](uint16_t conn_id, uint16_t handle, - std::vector value, - tGATT_WRITE_TYPE write_type, - GATT_WRITE_OP_CB cb, - void* cb_data) -> void { - auto& ascs = peer_devices.at(conn_id)->ascs; - uint8_t idx; - - if (handle == ascs->ctp_ccc) { - value = UINT16_TO_VEC_UINT8(ascs->ctp_ccc_val); - } else { - for (idx = 0; idx < max_num_of_ases; idx++) { - if (handle == ascs->sink_ase_ccc[idx] + 1) { - value = UINT16_TO_VEC_UINT8(ascs->sink_ase_ccc_val[idx]); - break; - } - if (handle == ascs->source_ase_char[idx] + 1) { - value = UINT16_TO_VEC_UINT8(ascs->source_ase_ccc_val[idx]); - break; + .WillByDefault(Invoke([this](uint16_t conn_id, uint16_t handle, + std::vector value, tGATT_WRITE_TYPE write_type, + GATT_WRITE_OP_CB cb, void* cb_data) -> void { + auto& ascs = peer_devices.at(conn_id)->ascs; + uint8_t idx; + + if (handle == ascs->ctp_ccc) { + value = UINT16_TO_VEC_UINT8(ascs->ctp_ccc_val); + } else { + for (idx = 0; idx < max_num_of_ases; idx++) { + if (handle == ascs->sink_ase_ccc[idx] + 1) { + value = UINT16_TO_VEC_UINT8(ascs->sink_ase_ccc_val[idx]); + break; + } + if (handle == ascs->source_ase_char[idx] + 1) { + value = UINT16_TO_VEC_UINT8(ascs->source_ase_ccc_val[idx]); + break; + } + } } - } - } - if (cb) - do_in_main_thread( - FROM_HERE, - base::BindOnce( - [](GATT_WRITE_OP_CB cb, uint16_t conn_id, uint16_t handle, - uint16_t len, uint8_t* value, void* cb_data) { - cb(conn_id, GATT_SUCCESS, handle, len, value, cb_data); - }, - cb, conn_id, handle, value.size(), value.data(), cb_data)); - })); + if (cb) { + do_in_main_thread( + FROM_HERE, + base::BindOnce( + [](GATT_WRITE_OP_CB cb, uint16_t conn_id, uint16_t handle, + uint16_t len, uint8_t* value, void* cb_data) { + cb(conn_id, GATT_SUCCESS, handle, len, value, cb_data); + }, + cb, conn_id, handle, value.size(), value.data(), cb_data)); + } + })); global_conn_id = 1; ON_CALL(mock_gatt_interface_, Open(_, _, BTM_BLE_DIRECT_CONNECTION, _)) - .WillByDefault( - Invoke([&](tGATT_IF client_if, const RawAddress& remote_bda, - bool is_direct, bool opportunistic) { + .WillByDefault(Invoke([&](tGATT_IF client_if, const RawAddress& remote_bda, + bool is_direct, bool opportunistic) { InjectConnectedEvent(remote_bda, global_conn_id++); })); - ON_CALL(mock_gatt_interface_, Close(_)) - .WillByDefault(Invoke([&](uint16_t conn_id) { - ASSERT_NE(conn_id, GATT_INVALID_CONN_ID); - InjectDisconnectedEvent(conn_id); - })); + ON_CALL(mock_gatt_interface_, Close(_)).WillByDefault(Invoke([&](uint16_t conn_id) { + ASSERT_NE(conn_id, GATT_INVALID_CONN_ID); + InjectDisconnectedEvent(conn_id); + })); // default Characteristic read handler dispatches requests to service mocks ON_CALL(mock_gatt_queue_, ReadCharacteristic(_, _, _, _)) - .WillByDefault(Invoke([&](uint16_t conn_id, uint16_t handle, - GATT_READ_OP_CB cb, void* cb_data) { - do_in_main_thread( - FROM_HERE, - base::BindOnce( - [](std::map>>* - peer_devices, - uint16_t conn_id, uint16_t handle, GATT_READ_OP_CB cb, - void* cb_data) -> void { - if (peer_devices->count(conn_id)) { - auto& device = peer_devices->at(conn_id); - auto svc = std::find_if( - device->services.begin(), device->services.end(), - [handle](const gatt::Service& svc) { - return (handle >= svc.handle) && - (handle <= svc.end_handle); - }); - if (svc == device->services.end()) return; - - // Dispatch to mockable handler functions - if (svc->handle == device->csis->start) { - device->csis->OnReadCharacteristic(handle, cb, cb_data); - } else if (svc->handle == device->cas->start) { - device->cas->OnReadCharacteristic(handle, cb, cb_data); - } else if (svc->handle == device->ascs->start) { - device->ascs->OnReadCharacteristic(handle, cb, cb_data); - } else if (svc->handle == device->pacs->start) { - device->pacs->OnReadCharacteristic(handle, cb, cb_data); - } - } - }, - &peer_devices, conn_id, handle, cb, cb_data)); - })); + .WillByDefault(Invoke([&](uint16_t conn_id, uint16_t handle, GATT_READ_OP_CB cb, + void* cb_data) { + do_in_main_thread( + FROM_HERE, + base::BindOnce( + [](std::map>>* + peer_devices, + uint16_t conn_id, uint16_t handle, GATT_READ_OP_CB cb, + void* cb_data) -> void { + if (peer_devices->count(conn_id)) { + auto& device = peer_devices->at(conn_id); + auto svc = std::find_if(device->services.begin(), + device->services.end(), + [handle](const gatt::Service& svc) { + return (handle >= svc.handle) && + (handle <= svc.end_handle); + }); + if (svc == device->services.end()) { + return; + } + + // Dispatch to mockable handler functions + if (svc->handle == device->csis->start) { + device->csis->OnReadCharacteristic(handle, cb, cb_data); + } else if (svc->handle == device->cas->start) { + device->cas->OnReadCharacteristic(handle, cb, cb_data); + } else if (svc->handle == device->ascs->start) { + device->ascs->OnReadCharacteristic(handle, cb, cb_data); + } else if (svc->handle == device->pacs->start) { + device->pacs->OnReadCharacteristic(handle, cb, cb_data); + } + } + }, + &peer_devices, conn_id, handle, cb, cb_data)); + })); } void SetUpMockGroups() { MockCsisClient::SetMockInstanceForTesting(&mock_csis_client_module_); MockDeviceGroups::SetMockInstanceForTesting(&mock_groups_module_); - MockLeAudioGroupStateMachine::SetMockInstanceForTesting( - &mock_state_machine_); + MockLeAudioGroupStateMachine::SetMockInstanceForTesting(&mock_state_machine_); - ON_CALL(mock_csis_client_module_, Get()) - .WillByDefault(Return(&mock_csis_client_module_)); + ON_CALL(mock_csis_client_module_, Get()).WillByDefault(Return(&mock_csis_client_module_)); // Store group callbacks so that we could inject grouping events group_callbacks_ = nullptr; - ON_CALL(mock_groups_module_, Initialize(_)) - .WillByDefault(SaveArg<0>(&group_callbacks_)); + ON_CALL(mock_groups_module_, Initialize(_)).WillByDefault(SaveArg<0>(&group_callbacks_)); ON_CALL(mock_groups_module_, GetGroupId(_, _)) - .WillByDefault([this](const RawAddress& addr, bluetooth::Uuid uuid) { - if (groups.find(addr) != groups.end()) return groups.at(addr); - return bluetooth::groups::kGroupUnknown; - }); + .WillByDefault([this](const RawAddress& addr, bluetooth::Uuid uuid) { + if (groups.find(addr) != groups.end()) { + return groups.at(addr); + } + return bluetooth::groups::kGroupUnknown; + }); ON_CALL(mock_groups_module_, RemoveDevice(_, _)) - .WillByDefault([this](const RawAddress& addr, int group_id_) { - int group_id = -1; - if (groups.find(addr) != groups.end()) { - group_id = groups[addr]; - groups.erase(addr); - } - if (group_id < 0) return; + .WillByDefault([this](const RawAddress& addr, int group_id_) { + int group_id = -1; + if (groups.find(addr) != groups.end()) { + group_id = groups[addr]; + groups.erase(addr); + } + if (group_id < 0) { + return; + } - do_in_main_thread( - FROM_HERE, - base::BindOnce( - [](const RawAddress& address, int group_id, - bluetooth::groups::DeviceGroupsCallbacks* - group_callbacks) { - group_callbacks->OnGroupMemberRemoved(address, group_id); - }, - addr, group_id, base::Unretained(group_callbacks_))); - }); + do_in_main_thread( + FROM_HERE, + base::BindOnce( + [](const RawAddress& address, int group_id, + bluetooth::groups::DeviceGroupsCallbacks* group_callbacks) { + group_callbacks->OnGroupMemberRemoved(address, group_id); + }, + addr, group_id, base::Unretained(group_callbacks_))); + }); // Our test devices have unique LSB - use it for unique grouping when // devices added with a non-CIS context and no grouping info - ON_CALL(mock_groups_module_, - AddDevice(_, bluetooth::le_audio::uuid::kCapServiceUuid, _)) - .WillByDefault( - [this](const RawAddress& addr, - bluetooth::Uuid uuid = - bluetooth::le_audio::uuid::kCapServiceUuid, - int group_id = bluetooth::groups::kGroupUnknown) -> int { + ON_CALL(mock_groups_module_, AddDevice(_, bluetooth::le_audio::uuid::kCapServiceUuid, _)) + .WillByDefault([this](const RawAddress& addr, + bluetooth::Uuid uuid = bluetooth::le_audio::uuid::kCapServiceUuid, + int group_id = bluetooth::groups::kGroupUnknown) -> int { if (group_id == bluetooth::groups::kGroupUnknown) { /* Generate group id from address */ groups[addr] = addr.address[RawAddress::kLength - 1]; @@ -873,675 +815,610 @@ class UnicastTestNoInit : public Test { }); ON_CALL(mock_state_machine_, Initialize(_)) - .WillByDefault(SaveArg<0>(&state_machine_callbacks_)); + .WillByDefault(SaveArg<0>(&state_machine_callbacks_)); ON_CALL(mock_state_machine_, ConfigureStream(_, _, _, _)) - .WillByDefault( - [this](LeAudioDeviceGroup* group, - types::LeAudioContextType context_type, - types::BidirectionalPair - metadata_context_types, - types::BidirectionalPair> ccid_lists) { - bool isReconfiguration = group->IsPendingConfiguration(); + .WillByDefault( + [this](LeAudioDeviceGroup* group, types::LeAudioContextType context_type, + types::BidirectionalPair metadata_context_types, + types::BidirectionalPair> ccid_lists) { + bool isReconfiguration = group->IsPendingConfiguration(); + + /* This shall be called only for user reconfiguration */ + if (!isReconfiguration) { + return false; + } + + /* Do what ReleaseCisIds(group) does: start */ + LeAudioDevice* leAudioDevice = group->GetFirstDevice(); + while (leAudioDevice != nullptr) { + for (auto& ase : leAudioDevice->ases_) { + ase.cis_id = bluetooth::le_audio::kInvalidCisId; + } + leAudioDevice = group->GetNextDevice(leAudioDevice); + } + group->ClearAllCises(); + /* end */ - /* This shall be called only for user reconfiguration */ - if (!isReconfiguration) return false; + if (!group->Configure(context_type, metadata_context_types, ccid_lists)) { + log::error("Could not configure ASEs for group {} content type {}", + group->group_id_, int(context_type)); - /* Do what ReleaseCisIds(group) does: start */ - LeAudioDevice* leAudioDevice = group->GetFirstDevice(); - while (leAudioDevice != nullptr) { - for (auto& ase : leAudioDevice->ases_) { - ase.cis_id = bluetooth::le_audio::kInvalidCisId; + return false; + } + + group->cig.GenerateCisIds(context_type); + + for (LeAudioDevice* device = group->GetFirstDevice(); device != nullptr; + device = group->GetNextDevice(device)) { + for (auto& ase : device->ases_) { + ase.cis_state = types::CisState::IDLE; + ase.data_path_state = types::DataPathState::IDLE; + ase.active = false; + ase.state = types::AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED; + } + } + + // Inject the state + group->SetTargetState( + types::AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED); + group->SetState(group->GetTargetState()); + group->ClearPendingConfiguration(); + do_in_main_thread( + FROM_HERE, + base::BindOnce( + [](int group_id, + bluetooth::le_audio::LeAudioGroupStateMachine::Callbacks* + state_machine_callbacks) { + state_machine_callbacks->StatusReportCb( + group_id, GroupStreamStatus::CONFIGURED_BY_USER); + }, + group->group_id_, + base::Unretained(this->state_machine_callbacks_))); + return true; + }); + + ON_CALL(mock_state_machine_, AttachToStream(_, _, _)) + .WillByDefault([this](LeAudioDeviceGroup* group, LeAudioDevice* leAudioDevice, + types::BidirectionalPair> ccids) { + if (group->GetState() != types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) { + if (group->GetTargetState() == types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) { + attach_to_stream_scheduled = true; } - leAudioDevice = group->GetNextDevice(leAudioDevice); - } - group->ClearAllCises(); - /* end */ - if (!group->Configure(context_type, metadata_context_types, - ccid_lists)) { - log::error( - "Could not configure ASEs for group {} content type {}", - group->group_id_, int(context_type)); + return false; + } + group->Configure(group->GetConfigurationContextType(), group->GetMetadataContexts(), + ccids); + if (!group->cig.AssignCisIds(leAudioDevice)) { return false; } + group->AssignCisConnHandlesToAses(leAudioDevice); - group->cig.GenerateCisIds(context_type); + auto* stream_conf = &group->stream_conf; - for (LeAudioDevice* device = group->GetFirstDevice(); - device != nullptr; device = group->GetNextDevice(device)) { - for (auto& ase : device->ases_) { - ase.cis_state = types::CisState::IDLE; - ase.data_path_state = types::DataPathState::IDLE; - ase.active = false; - ase.state = - types::AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED; + for (auto& ase : leAudioDevice->ases_) { + if (!ase.active) { + continue; + } + + // And also skip the ase establishment procedure which should + // be tested as part of the state machine unit tests + ase.cis_state = types::CisState::CONNECTED; + ase.data_path_state = types::DataPathState::CONFIGURED; + ase.state = types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING; + + uint16_t cis_conn_hdl = ase.cis_conn_hdl; + auto core_config = ase.codec_config.GetAsCoreCodecConfig(); + + /* Copied from state_machine.cc ProcessHciNotifSetupIsoDataPath */ + if (ase.direction == bluetooth::le_audio::types::kLeAudioDirectionSource) { + auto iter = std::find_if( + stream_conf->stream_params.source.stream_locations.begin(), + stream_conf->stream_params.source.stream_locations.end(), + [cis_conn_hdl](auto& pair) { return cis_conn_hdl == pair.first; }); + + if (iter == stream_conf->stream_params.source.stream_locations.end()) { + stream_conf->stream_params.source.stream_locations.emplace_back(std::make_pair( + ase.cis_conn_hdl, *core_config.audio_channel_allocation)); + + stream_conf->stream_params.source.num_of_devices++; + stream_conf->stream_params.source.num_of_channels += ase.channel_count; + + log::info( + "Added Source Stream Configuration. CIS Connection Handle: " + "{}, Audio Channel Allocation: {}, Source Number Of " + "Devices: {}, Source Number Of Channels: {}", + ase.cis_conn_hdl, *core_config.audio_channel_allocation, + stream_conf->stream_params.source.num_of_devices, + stream_conf->stream_params.source.num_of_channels); + } + } else { + auto iter = std::find_if( + stream_conf->stream_params.sink.stream_locations.begin(), + stream_conf->stream_params.sink.stream_locations.end(), + [cis_conn_hdl](auto& pair) { return cis_conn_hdl == pair.first; }); + + if (iter == stream_conf->stream_params.sink.stream_locations.end()) { + stream_conf->stream_params.sink.stream_locations.emplace_back(std::make_pair( + ase.cis_conn_hdl, *core_config.audio_channel_allocation)); + + stream_conf->stream_params.sink.num_of_devices++; + stream_conf->stream_params.sink.num_of_channels += ase.channel_count; + + log::info( + "Added Sink Stream Configuration. CIS Connection Handle: " + "{}, Audio Channel Allocation: {}, Sink Number Of Devices: " + "{}, Sink Number Of Channels: {}", + ase.cis_conn_hdl, *core_config.audio_channel_allocation, + stream_conf->stream_params.sink.num_of_devices, + stream_conf->stream_params.sink.num_of_channels); + } } } - // Inject the state - group->SetTargetState( - types::AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED); - group->SetState(group->GetTargetState()); - group->ClearPendingConfiguration(); - do_in_main_thread( - FROM_HERE, - base::BindOnce( - [](int group_id, - bluetooth::le_audio::LeAudioGroupStateMachine:: - Callbacks* state_machine_callbacks) { - state_machine_callbacks->StatusReportCb( - group_id, GroupStreamStatus::CONFIGURED_BY_USER); - }, - group->group_id_, - base::Unretained(this->state_machine_callbacks_))); return true; }); - ON_CALL(mock_state_machine_, AttachToStream(_, _, _)) - .WillByDefault([this](LeAudioDeviceGroup* group, - LeAudioDevice* leAudioDevice, - types::BidirectionalPair> - ccids) { - if (group->GetState() != - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) { - if (group->GetTargetState() == - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) { - attach_to_stream_scheduled = true; - } - - return false; - } - - group->Configure(group->GetConfigurationContextType(), - group->GetMetadataContexts(), ccids); - if (!group->cig.AssignCisIds(leAudioDevice)) return false; - group->AssignCisConnHandlesToAses(leAudioDevice); - - auto* stream_conf = &group->stream_conf; - - for (auto& ase : leAudioDevice->ases_) { - if (!ase.active) continue; - - // And also skip the ase establishment procedure which should - // be tested as part of the state machine unit tests - ase.cis_state = types::CisState::CONNECTED; - ase.data_path_state = types::DataPathState::CONFIGURED; - ase.state = types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING; - - uint16_t cis_conn_hdl = ase.cis_conn_hdl; - auto core_config = ase.codec_config.GetAsCoreCodecConfig(); - - /* Copied from state_machine.cc ProcessHciNotifSetupIsoDataPath */ - if (ase.direction == - bluetooth::le_audio::types::kLeAudioDirectionSource) { - auto iter = std::find_if( - stream_conf->stream_params.source.stream_locations.begin(), - stream_conf->stream_params.source.stream_locations.end(), - [cis_conn_hdl](auto& pair) { - return cis_conn_hdl == pair.first; - }); - - if (iter == - stream_conf->stream_params.source.stream_locations.end()) { - stream_conf->stream_params.source.stream_locations.emplace_back( - std::make_pair(ase.cis_conn_hdl, - *core_config.audio_channel_allocation)); - - stream_conf->stream_params.source.num_of_devices++; - stream_conf->stream_params.source.num_of_channels += - ase.channel_count; - - log::info( - "Added Source Stream Configuration. CIS Connection Handle: " - "{}, Audio Channel Allocation: {}, Source Number Of " - "Devices: {}, Source Number Of Channels: {}", - ase.cis_conn_hdl, *core_config.audio_channel_allocation, - stream_conf->stream_params.source.num_of_devices, - stream_conf->stream_params.source.num_of_channels); + ON_CALL(mock_state_machine_, StartStream(_, _, _, _)) + .WillByDefault([this](LeAudioDeviceGroup* group, types::LeAudioContextType context_type, + types::BidirectionalPair + metadata_context_types, + types::BidirectionalPair> ccid_lists) { + /* Do nothing if already streaming - the implementation would + * probably update the metadata. + */ + if (group->GetState() == types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) { + return true; } - } else { - auto iter = std::find_if( - stream_conf->stream_params.sink.stream_locations.begin(), - stream_conf->stream_params.sink.stream_locations.end(), - [cis_conn_hdl](auto& pair) { - return cis_conn_hdl == pair.first; - }); - if (iter == - stream_conf->stream_params.sink.stream_locations.end()) { - stream_conf->stream_params.sink.stream_locations.emplace_back( - std::make_pair(ase.cis_conn_hdl, - *core_config.audio_channel_allocation)); - - stream_conf->stream_params.sink.num_of_devices++; - stream_conf->stream_params.sink.num_of_channels += - ase.channel_count; - - log::info( - "Added Sink Stream Configuration. CIS Connection Handle: " - "{}, Audio Channel Allocation: {}, Sink Number Of Devices: " - "{}, Sink Number Of Channels: {}", - ase.cis_conn_hdl, *core_config.audio_channel_allocation, - stream_conf->stream_params.sink.num_of_devices, - stream_conf->stream_params.sink.num_of_channels); + /* Do what ReleaseCisIds(group) does: start */ + LeAudioDevice* leAudioDevice = group->GetFirstDevice(); + while (leAudioDevice != nullptr) { + for (auto& ase : leAudioDevice->ases_) { + ase.cis_id = bluetooth::le_audio::kInvalidCisId; + } + leAudioDevice = group->GetNextDevice(leAudioDevice); } - } - } - - return true; - }); - - ON_CALL(mock_state_machine_, StartStream(_, _, _, _)) - .WillByDefault([this](LeAudioDeviceGroup* group, - types::LeAudioContextType context_type, - types::BidirectionalPair - metadata_context_types, - types::BidirectionalPair> - ccid_lists) { - /* Do nothing if already streaming - the implementation would - * probably update the metadata. - */ - if (group->GetState() == - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) { - return true; - } - - /* Do what ReleaseCisIds(group) does: start */ - LeAudioDevice* leAudioDevice = group->GetFirstDevice(); - while (leAudioDevice != nullptr) { - for (auto& ase : leAudioDevice->ases_) { - ase.cis_id = bluetooth::le_audio::kInvalidCisId; - } - leAudioDevice = group->GetNextDevice(leAudioDevice); - } - group->ClearAllCises(); - /* end */ - - if (!group->Configure(context_type, metadata_context_types, - ccid_lists)) { - log::error("failed to set ASE configuration"); - return false; - } - - if (group->GetState() == - types::AseState::BTA_LE_AUDIO_ASE_STATE_IDLE) { - group->cig.GenerateCisIds(context_type); + group->ClearAllCises(); + /* end */ - std::vector conn_handles; - for (uint8_t i = 0; i < (uint8_t)(group->cig.cises.size()); i++) { - conn_handles.push_back(iso_con_counter_++); - } - group->cig.AssignCisConnHandles(conn_handles); - for (LeAudioDevice* device = group->GetFirstActiveDevice(); - device != nullptr; - device = group->GetNextActiveDevice(device)) { - if (!group->cig.AssignCisIds(device)) return false; - group->AssignCisConnHandlesToAses(device); - } - } + if (!group->Configure(context_type, metadata_context_types, ccid_lists)) { + log::error("failed to set ASE configuration"); + return false; + } - auto* stream_conf = &group->stream_conf; - - // Fake ASE configuration - for (LeAudioDevice* device = group->GetFirstActiveDevice(); - device != nullptr; device = group->GetNextActiveDevice(device)) { - for (auto& ase : device->ases_) { - if (!ase.active) continue; - - // And also skip the ase establishment procedure which should - // be tested as part of the state machine unit tests - ase.cis_state = types::CisState::CONNECTED; - ase.data_path_state = types::DataPathState::CONFIGURED; - ase.state = types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING; - ase.qos_preferences.pres_delay_min = 2500; - ase.qos_preferences.pres_delay_max = 2500; - ase.qos_preferences.preferred_pres_delay_min = 2500; - ase.qos_preferences.preferred_pres_delay_max = 2500; - auto core_config = ase.codec_config.GetAsCoreCodecConfig(); - - uint16_t cis_conn_hdl = ase.cis_conn_hdl; - - /* Copied from state_machine.cc ProcessHciNotifSetupIsoDataPath */ - if (ase.direction == - bluetooth::le_audio::types::kLeAudioDirectionSource) { - auto iter = std::find_if( - stream_conf->stream_params.source.stream_locations.begin(), - stream_conf->stream_params.source.stream_locations.end(), - [cis_conn_hdl](auto& pair) { - return cis_conn_hdl == pair.first; - }); + if (group->GetState() == types::AseState::BTA_LE_AUDIO_ASE_STATE_IDLE) { + group->cig.GenerateCisIds(context_type); - if (iter == - stream_conf->stream_params.source.stream_locations.end()) { - stream_conf->stream_params.source.stream_locations - .emplace_back(std::make_pair( - ase.cis_conn_hdl, - *core_config.audio_channel_allocation)); - - stream_conf->stream_params.source.num_of_devices++; - stream_conf->stream_params.source.num_of_channels += - ase.channel_count; - stream_conf->stream_params.source.audio_channel_allocation |= - *core_config.audio_channel_allocation; - - if (stream_conf->stream_params.source.sample_frequency_hz == - 0) { - stream_conf->stream_params.source.sample_frequency_hz = - core_config.GetSamplingFrequencyHz(); - } else { - log::assert_that( - stream_conf->stream_params.source.sample_frequency_hz == - core_config.GetSamplingFrequencyHz(), - "sample freq mismatch: {}!={}", - stream_conf->stream_params.source.sample_frequency_hz, - core_config.GetSamplingFrequencyHz()); + std::vector conn_handles; + for (uint8_t i = 0; i < (uint8_t)(group->cig.cises.size()); i++) { + conn_handles.push_back(iso_con_counter_++); + } + group->cig.AssignCisConnHandles(conn_handles); + for (LeAudioDevice* device = group->GetFirstActiveDevice(); device != nullptr; + device = group->GetNextActiveDevice(device)) { + if (!group->cig.AssignCisIds(device)) { + return false; } + group->AssignCisConnHandlesToAses(device); + } + } - if (stream_conf->stream_params.source - .octets_per_codec_frame == 0) { - stream_conf->stream_params.source.octets_per_codec_frame = - *core_config.octets_per_codec_frame; - } else { - log::assert_that(stream_conf->stream_params.source - .octets_per_codec_frame == - *core_config.octets_per_codec_frame, - "octets per frame mismatch: {}!={}", - stream_conf->stream_params.source - .octets_per_codec_frame, - *core_config.octets_per_codec_frame); - } + auto* stream_conf = &group->stream_conf; - if (stream_conf->stream_params.source - .codec_frames_blocks_per_sdu == 0) { - stream_conf->stream_params.source - .codec_frames_blocks_per_sdu = - *core_config.codec_frames_blocks_per_sdu; - stream_conf->stream_params.source.frame_duration_us = - core_config.GetFrameDurationUs(); - } else { - log::assert_that( - stream_conf->stream_params.source - .codec_frames_blocks_per_sdu == - *core_config.codec_frames_blocks_per_sdu, - "codec_frames_blocks_per_sdu: {}!={}", - stream_conf->stream_params.source - .codec_frames_blocks_per_sdu, - *core_config.codec_frames_blocks_per_sdu); + // Fake ASE configuration + for (LeAudioDevice* device = group->GetFirstActiveDevice(); device != nullptr; + device = group->GetNextActiveDevice(device)) { + for (auto& ase : device->ases_) { + if (!ase.active) { + continue; } - log::info( - "Added Source Stream Configuration. CIS Connection " - "Handle: {}, Audio Channel Allocation: {}, Source Number " - "Of Devices: {}, Source Number Of Channels: {}", - ase.cis_conn_hdl, *core_config.audio_channel_allocation, - stream_conf->stream_params.source.num_of_devices, - stream_conf->stream_params.source.num_of_channels); - } - } else { - auto iter = std::find_if( - stream_conf->stream_params.sink.stream_locations.begin(), - stream_conf->stream_params.sink.stream_locations.end(), - [cis_conn_hdl](auto& pair) { - return cis_conn_hdl == pair.first; - }); - - if (iter == - stream_conf->stream_params.sink.stream_locations.end()) { - stream_conf->stream_params.sink.stream_locations.emplace_back( - std::make_pair(ase.cis_conn_hdl, - *core_config.audio_channel_allocation)); + // And also skip the ase establishment procedure which should + // be tested as part of the state machine unit tests + ase.cis_state = types::CisState::CONNECTED; + ase.data_path_state = types::DataPathState::CONFIGURED; + ase.state = types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING; + ase.qos_preferences.pres_delay_min = 2500; + ase.qos_preferences.pres_delay_max = 2500; + ase.qos_preferences.preferred_pres_delay_min = 2500; + ase.qos_preferences.preferred_pres_delay_max = 2500; + auto core_config = ase.codec_config.GetAsCoreCodecConfig(); + + uint16_t cis_conn_hdl = ase.cis_conn_hdl; + + /* Copied from state_machine.cc ProcessHciNotifSetupIsoDataPath */ + if (ase.direction == bluetooth::le_audio::types::kLeAudioDirectionSource) { + auto iter = std::find_if( + stream_conf->stream_params.source.stream_locations.begin(), + stream_conf->stream_params.source.stream_locations.end(), + [cis_conn_hdl](auto& pair) { return cis_conn_hdl == pair.first; }); + + if (iter == stream_conf->stream_params.source.stream_locations.end()) { + stream_conf->stream_params.source.stream_locations.emplace_back( + std::make_pair(ase.cis_conn_hdl, + *core_config.audio_channel_allocation)); + + stream_conf->stream_params.source.num_of_devices++; + stream_conf->stream_params.source.num_of_channels += ase.channel_count; + stream_conf->stream_params.source.audio_channel_allocation |= + *core_config.audio_channel_allocation; + + if (stream_conf->stream_params.source.sample_frequency_hz == 0) { + stream_conf->stream_params.source.sample_frequency_hz = + core_config.GetSamplingFrequencyHz(); + } else { + log::assert_that(stream_conf->stream_params.source.sample_frequency_hz == + core_config.GetSamplingFrequencyHz(), + "sample freq mismatch: {}!={}", + stream_conf->stream_params.source.sample_frequency_hz, + core_config.GetSamplingFrequencyHz()); + } - stream_conf->stream_params.sink.num_of_devices++; - stream_conf->stream_params.sink.num_of_channels += - ase.channel_count; + if (stream_conf->stream_params.source.octets_per_codec_frame == 0) { + stream_conf->stream_params.source.octets_per_codec_frame = + *core_config.octets_per_codec_frame; + } else { + log::assert_that(stream_conf->stream_params.source.octets_per_codec_frame == + *core_config.octets_per_codec_frame, + "octets per frame mismatch: {}!={}", + stream_conf->stream_params.source.octets_per_codec_frame, + *core_config.octets_per_codec_frame); + } - stream_conf->stream_params.sink.audio_channel_allocation |= - *core_config.audio_channel_allocation; + if (stream_conf->stream_params.source.codec_frames_blocks_per_sdu == 0) { + stream_conf->stream_params.source.codec_frames_blocks_per_sdu = + *core_config.codec_frames_blocks_per_sdu; + stream_conf->stream_params.source.frame_duration_us = + core_config.GetFrameDurationUs(); + } else { + log::assert_that( + stream_conf->stream_params.source.codec_frames_blocks_per_sdu == + *core_config.codec_frames_blocks_per_sdu, + "codec_frames_blocks_per_sdu: {}!={}", + stream_conf->stream_params.source.codec_frames_blocks_per_sdu, + *core_config.codec_frames_blocks_per_sdu); + } - if (stream_conf->stream_params.sink.sample_frequency_hz == - 0) { - stream_conf->stream_params.sink.sample_frequency_hz = - core_config.GetSamplingFrequencyHz(); + log::info( + "Added Source Stream Configuration. CIS Connection " + "Handle: {}, Audio Channel Allocation: {}, Source Number " + "Of Devices: {}, Source Number Of Channels: {}", + ase.cis_conn_hdl, *core_config.audio_channel_allocation, + stream_conf->stream_params.source.num_of_devices, + stream_conf->stream_params.source.num_of_channels); + } } else { - log::assert_that( - stream_conf->stream_params.sink.sample_frequency_hz == - core_config.GetSamplingFrequencyHz(), - "sample freq mismatch: {}!={}", - stream_conf->stream_params.sink.sample_frequency_hz, - core_config.GetSamplingFrequencyHz()); - } + auto iter = std::find_if( + stream_conf->stream_params.sink.stream_locations.begin(), + stream_conf->stream_params.sink.stream_locations.end(), + [cis_conn_hdl](auto& pair) { return cis_conn_hdl == pair.first; }); + + if (iter == stream_conf->stream_params.sink.stream_locations.end()) { + stream_conf->stream_params.sink.stream_locations.emplace_back(std::make_pair( + ase.cis_conn_hdl, *core_config.audio_channel_allocation)); + + stream_conf->stream_params.sink.num_of_devices++; + stream_conf->stream_params.sink.num_of_channels += ase.channel_count; + + stream_conf->stream_params.sink.audio_channel_allocation |= + *core_config.audio_channel_allocation; + + if (stream_conf->stream_params.sink.sample_frequency_hz == 0) { + stream_conf->stream_params.sink.sample_frequency_hz = + core_config.GetSamplingFrequencyHz(); + } else { + log::assert_that(stream_conf->stream_params.sink.sample_frequency_hz == + core_config.GetSamplingFrequencyHz(), + "sample freq mismatch: {}!={}", + stream_conf->stream_params.sink.sample_frequency_hz, + core_config.GetSamplingFrequencyHz()); + } - if (stream_conf->stream_params.sink.octets_per_codec_frame == - 0) { - stream_conf->stream_params.sink.octets_per_codec_frame = - *core_config.octets_per_codec_frame; - } else { - log::assert_that( - stream_conf->stream_params.sink - .octets_per_codec_frame == - *core_config.octets_per_codec_frame, - "octets per frame mismatch: {}!={}", - stream_conf->stream_params.sink.octets_per_codec_frame, - *core_config.octets_per_codec_frame); - } + if (stream_conf->stream_params.sink.octets_per_codec_frame == 0) { + stream_conf->stream_params.sink.octets_per_codec_frame = + *core_config.octets_per_codec_frame; + } else { + log::assert_that(stream_conf->stream_params.sink.octets_per_codec_frame == + *core_config.octets_per_codec_frame, + "octets per frame mismatch: {}!={}", + stream_conf->stream_params.sink.octets_per_codec_frame, + *core_config.octets_per_codec_frame); + } - if (stream_conf->stream_params.sink - .codec_frames_blocks_per_sdu == 0) { - stream_conf->stream_params.sink - .codec_frames_blocks_per_sdu = - *core_config.codec_frames_blocks_per_sdu; - stream_conf->stream_params.sink.frame_duration_us = - core_config.GetFrameDurationUs(); - } else { - log::assert_that( - stream_conf->stream_params.sink - .codec_frames_blocks_per_sdu == - *core_config.codec_frames_blocks_per_sdu, - "codec_frames_blocks_per_sdu: {}!={}", - stream_conf->stream_params.sink - .codec_frames_blocks_per_sdu, - *core_config.codec_frames_blocks_per_sdu); - } + if (stream_conf->stream_params.sink.codec_frames_blocks_per_sdu == 0) { + stream_conf->stream_params.sink.codec_frames_blocks_per_sdu = + *core_config.codec_frames_blocks_per_sdu; + stream_conf->stream_params.sink.frame_duration_us = + core_config.GetFrameDurationUs(); + } else { + log::assert_that( + stream_conf->stream_params.sink.codec_frames_blocks_per_sdu == + *core_config.codec_frames_blocks_per_sdu, + "codec_frames_blocks_per_sdu: {}!={}", + stream_conf->stream_params.sink.codec_frames_blocks_per_sdu, + *core_config.codec_frames_blocks_per_sdu); + } - log::info( - "Added Sink Stream Configuration. CIS Connection Handle: " - "{}, Audio Channel Allocation: {}, Sink Number Of " - "Devices: {}, Sink Number Of Channels: {}", - ase.cis_conn_hdl, *core_config.audio_channel_allocation, - stream_conf->stream_params.sink.num_of_devices, - stream_conf->stream_params.sink.num_of_channels); + log::info( + "Added Sink Stream Configuration. CIS Connection Handle: " + "{}, Audio Channel Allocation: {}, Sink Number Of " + "Devices: {}, Sink Number Of Channels: {}", + ase.cis_conn_hdl, *core_config.audio_channel_allocation, + stream_conf->stream_params.sink.num_of_devices, + stream_conf->stream_params.sink.num_of_channels); + } + } } } - } - } - // Inject the state - group->SetTargetState( - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); - group->SetState( - types::AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED); - streaming_groups[group->group_id_] = group; + // Inject the state + group->SetTargetState(types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + group->SetState(types::AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED); + streaming_groups[group->group_id_] = group; - /* Assume CIG is created */ - group->cig.SetState(bluetooth::le_audio::types::CigState::CREATED); + /* Assume CIG is created */ + group->cig.SetState(bluetooth::le_audio::types::CigState::CREATED); - if (block_streaming_state_callback) return true; + if (block_streaming_state_callback) { + return true; + } - group->SetState(types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); - do_in_main_thread( - FROM_HERE, - base::BindOnce( - [](int group_id, - bluetooth::le_audio::LeAudioGroupStateMachine::Callbacks* - state_machine_callbacks) { - state_machine_callbacks->StatusReportCb( - group_id, GroupStreamStatus::STREAMING); - }, - group->group_id_, - base::Unretained(this->state_machine_callbacks_))); - return true; - }); - - ON_CALL(mock_state_machine_, SuspendStream(_)) - .WillByDefault([this](LeAudioDeviceGroup* group) { - // Fake ASE state - for (LeAudioDevice* device = group->GetFirstDevice(); - device != nullptr; device = group->GetNextDevice(device)) { - for (auto& ase : device->ases_) { - ase.cis_state = types::CisState::CONNECTED; - ase.active = false; - ase.state = - types::AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED; - } - } + group->SetState(types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + do_in_main_thread( + FROM_HERE, + base::BindOnce( + [](int group_id, + bluetooth::le_audio::LeAudioGroupStateMachine::Callbacks* + state_machine_callbacks) { + state_machine_callbacks->StatusReportCb( + group_id, GroupStreamStatus::STREAMING); + }, + group->group_id_, base::Unretained(this->state_machine_callbacks_))); + return true; + }); + + ON_CALL(mock_state_machine_, SuspendStream(_)).WillByDefault([this](LeAudioDeviceGroup* group) { + // Fake ASE state + for (LeAudioDevice* device = group->GetFirstDevice(); device != nullptr; + device = group->GetNextDevice(device)) { + for (auto& ase : device->ases_) { + ase.cis_state = types::CisState::CONNECTED; + ase.active = false; + ase.state = types::AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED; + } + } - // Inject the state - group->SetTargetState( - types::AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED); - group->SetState(group->GetTargetState()); - state_machine_callbacks_->StatusReportCb( - group->group_id_, GroupStreamStatus::SUSPENDED); - }); + // Inject the state + group->SetTargetState(types::AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED); + group->SetState(group->GetTargetState()); + state_machine_callbacks_->StatusReportCb(group->group_id_, GroupStreamStatus::SUSPENDED); + }); ON_CALL(mock_state_machine_, ProcessHciNotifAclDisconnected(_, _)) - .WillByDefault([this](LeAudioDeviceGroup* group, - LeAudioDevice* leAudioDevice) { - if (!group) return; - auto* stream_conf = &group->stream_conf; - if (!stream_conf->stream_params.sink.stream_locations.empty() || - !stream_conf->stream_params.source.stream_locations.empty()) { - stream_conf->stream_params.sink.stream_locations.erase( - std::remove_if( - stream_conf->stream_params.sink.stream_locations.begin(), - stream_conf->stream_params.sink.stream_locations.end(), - [leAudioDevice, &stream_conf](auto& pair) { - auto ases = - leAudioDevice->GetAsesByCisConnHdl(pair.first); - if (ases.sink) { - stream_conf->stream_params.sink.num_of_devices--; - stream_conf->stream_params.sink.num_of_channels -= - ases.sink->channel_count; - - log::info( - ", Source Number Of Devices: {}" - ", Source Number Of Channels: {}", - stream_conf->stream_params.source.num_of_devices, - stream_conf->stream_params.source.num_of_channels); - } - return ases.sink; - }), - stream_conf->stream_params.sink.stream_locations.end()); - - stream_conf->stream_params.source.stream_locations.erase( - std::remove_if( - stream_conf->stream_params.source.stream_locations.begin(), - stream_conf->stream_params.source.stream_locations.end(), - [leAudioDevice, &stream_conf](auto& pair) { - auto ases = - leAudioDevice->GetAsesByCisConnHdl(pair.first); - if (ases.source) { - stream_conf->stream_params.source.num_of_devices--; - stream_conf->stream_params.source.num_of_channels -= - ases.source->channel_count; - - log::info( - ", Source Number Of Devices: {}, Source Number Of " - "Channels: {}", - stream_conf->stream_params.source.num_of_devices, - stream_conf->stream_params.source.num_of_channels); - } - return ases.source; - }), - stream_conf->stream_params.source.stream_locations.end()); - } + .WillByDefault([this](LeAudioDeviceGroup* group, LeAudioDevice* leAudioDevice) { + if (!group) { + return; + } + auto* stream_conf = &group->stream_conf; + if (!stream_conf->stream_params.sink.stream_locations.empty() || + !stream_conf->stream_params.source.stream_locations.empty()) { + stream_conf->stream_params.sink.stream_locations.erase( + std::remove_if( + stream_conf->stream_params.sink.stream_locations.begin(), + stream_conf->stream_params.sink.stream_locations.end(), + [leAudioDevice, &stream_conf](auto& pair) { + auto ases = leAudioDevice->GetAsesByCisConnHdl(pair.first); + if (ases.sink) { + stream_conf->stream_params.sink.num_of_devices--; + stream_conf->stream_params.sink.num_of_channels -= + ases.sink->channel_count; + + log::info( + ", Source Number Of Devices: {}" + ", Source Number Of Channels: {}", + stream_conf->stream_params.source.num_of_devices, + stream_conf->stream_params.source.num_of_channels); + } + return ases.sink; + }), + stream_conf->stream_params.sink.stream_locations.end()); + + stream_conf->stream_params.source.stream_locations.erase( + std::remove_if( + stream_conf->stream_params.source.stream_locations.begin(), + stream_conf->stream_params.source.stream_locations.end(), + [leAudioDevice, &stream_conf](auto& pair) { + auto ases = leAudioDevice->GetAsesByCisConnHdl(pair.first); + if (ases.source) { + stream_conf->stream_params.source.num_of_devices--; + stream_conf->stream_params.source.num_of_channels -= + ases.source->channel_count; + + log::info( + ", Source Number Of Devices: {}, Source Number Of " + "Channels: {}", + stream_conf->stream_params.source.num_of_devices, + stream_conf->stream_params.source.num_of_channels); + } + return ases.source; + }), + stream_conf->stream_params.source.stream_locations.end()); + } - group->cig.UnassignCis(leAudioDevice); + group->cig.UnassignCis(leAudioDevice); - if (group->IsEmpty()) { - group->cig.SetState(bluetooth::le_audio::types::CigState::NONE); - InjectCigRemoved(group->group_id_); - } - }); + if (group->IsEmpty()) { + group->cig.SetState(bluetooth::le_audio::types::CigState::NONE); + InjectCigRemoved(group->group_id_); + } + }); ON_CALL(mock_state_machine_, ProcessHciNotifCisDisconnected(_, _, _)) - .WillByDefault([](LeAudioDeviceGroup* group, - LeAudioDevice* leAudioDevice, - const bluetooth::hci::iso_manager:: - cis_disconnected_evt* event) { - if (!group) return; - auto ases_pair = - leAudioDevice->GetAsesByCisConnHdl(event->cis_conn_hdl); - if (ases_pair.sink) { - ases_pair.sink->cis_state = types::CisState::ASSIGNED; - ases_pair.sink->active = false; - } - if (ases_pair.source) { - ases_pair.source->active = false; - ases_pair.source->cis_state = types::CisState::ASSIGNED; - } - /* Invalidate stream configuration if needed */ - auto* stream_conf = &group->stream_conf; - if (!stream_conf->stream_params.sink.stream_locations.empty() || - !stream_conf->stream_params.source.stream_locations.empty()) { - stream_conf->stream_params.sink.stream_locations.erase( - std::remove_if( - stream_conf->stream_params.sink.stream_locations.begin(), - stream_conf->stream_params.sink.stream_locations.end(), - [leAudioDevice, &stream_conf](auto& pair) { - auto ases = - leAudioDevice->GetAsesByCisConnHdl(pair.first); - - log::info( - ", sink ase to delete. Cis handle: {}, ase pointer: " - "{}", - (int)(pair.first), fmt::ptr(+ases.sink)); - if (ases.sink) { - stream_conf->stream_params.sink.num_of_devices--; - stream_conf->stream_params.sink.num_of_channels -= - ases.sink->channel_count; - - log::info( - "Sink Number Of Devices: {}, Sink Number Of " - "Channels: {}", - stream_conf->stream_params.sink.num_of_devices, - stream_conf->stream_params.sink.num_of_channels); - } - return ases.sink; - }), - stream_conf->stream_params.sink.stream_locations.end()); - - stream_conf->stream_params.source.stream_locations.erase( - std::remove_if( - stream_conf->stream_params.source.stream_locations.begin(), - stream_conf->stream_params.source.stream_locations.end(), - [leAudioDevice, &stream_conf](auto& pair) { - auto ases = - leAudioDevice->GetAsesByCisConnHdl(pair.first); + .WillByDefault([](LeAudioDeviceGroup* group, LeAudioDevice* leAudioDevice, + const bluetooth::hci::iso_manager::cis_disconnected_evt* event) { + if (!group) { + return; + } + auto ases_pair = leAudioDevice->GetAsesByCisConnHdl(event->cis_conn_hdl); + if (ases_pair.sink) { + ases_pair.sink->cis_state = types::CisState::ASSIGNED; + ases_pair.sink->active = false; + } + if (ases_pair.source) { + ases_pair.source->active = false; + ases_pair.source->cis_state = types::CisState::ASSIGNED; + } + /* Invalidate stream configuration if needed */ + auto* stream_conf = &group->stream_conf; + if (!stream_conf->stream_params.sink.stream_locations.empty() || + !stream_conf->stream_params.source.stream_locations.empty()) { + stream_conf->stream_params.sink.stream_locations.erase( + std::remove_if( + stream_conf->stream_params.sink.stream_locations.begin(), + stream_conf->stream_params.sink.stream_locations.end(), + [leAudioDevice, &stream_conf](auto& pair) { + auto ases = leAudioDevice->GetAsesByCisConnHdl(pair.first); + + log::info( + ", sink ase to delete. Cis handle: {}, ase pointer: " + "{}", + (int)(pair.first), fmt::ptr(+ases.sink)); + if (ases.sink) { + stream_conf->stream_params.sink.num_of_devices--; + stream_conf->stream_params.sink.num_of_channels -= + ases.sink->channel_count; + + log::info( + "Sink Number Of Devices: {}, Sink Number Of " + "Channels: {}", + stream_conf->stream_params.sink.num_of_devices, + stream_conf->stream_params.sink.num_of_channels); + } + return ases.sink; + }), + stream_conf->stream_params.sink.stream_locations.end()); + + stream_conf->stream_params.source.stream_locations.erase( + std::remove_if( + stream_conf->stream_params.source.stream_locations.begin(), + stream_conf->stream_params.source.stream_locations.end(), + [leAudioDevice, &stream_conf](auto& pair) { + auto ases = leAudioDevice->GetAsesByCisConnHdl(pair.first); + + log::info(", source to delete. Cis handle: {}, ase pointer: {}", + (int)(pair.first), fmt::ptr(ases.source)); + if (ases.source) { + stream_conf->stream_params.source.num_of_devices--; + stream_conf->stream_params.source.num_of_channels -= + ases.source->channel_count; + + log::info( + ", Source Number Of Devices: {}, Source Number Of " + "Channels: {}", + stream_conf->stream_params.source.num_of_devices, + stream_conf->stream_params.source.num_of_channels); + } + return ases.source; + }), + stream_conf->stream_params.source.stream_locations.end()); + } - log::info( - ", source to delete. Cis handle: {}, ase pointer: {}", - (int)(pair.first), fmt::ptr(ases.source)); - if (ases.source) { - stream_conf->stream_params.source.num_of_devices--; - stream_conf->stream_params.source.num_of_channels -= - ases.source->channel_count; - - log::info( - ", Source Number Of Devices: {}, Source Number Of " - "Channels: {}", - stream_conf->stream_params.source.num_of_devices, - stream_conf->stream_params.source.num_of_channels); - } - return ases.source; - }), - stream_conf->stream_params.source.stream_locations.end()); - } + group->cig.UnassignCis(leAudioDevice); + }); - group->cig.UnassignCis(leAudioDevice); - }); - - ON_CALL(mock_state_machine_, StopStream(_)) - .WillByDefault([this](LeAudioDeviceGroup* group) { - for (LeAudioDevice* device = group->GetFirstDevice(); - device != nullptr; device = group->GetNextDevice(device)) { - /* Invalidate stream configuration if needed */ - auto* stream_conf = &group->stream_conf; - if (!stream_conf->stream_params.sink.stream_locations.empty() || - !stream_conf->stream_params.source.stream_locations.empty()) { - stream_conf->stream_params.sink.stream_locations.erase( - std::remove_if( - stream_conf->stream_params.sink.stream_locations.begin(), - stream_conf->stream_params.sink.stream_locations.end(), - [device, &stream_conf](auto& pair) { - auto ases = device->GetAsesByCisConnHdl(pair.first); - - log::info( - ", sink ase to delete. Cis handle: {}, ase " - "pointer: {}", - (int)(pair.first), fmt::ptr(+ases.sink)); - if (ases.sink) { - stream_conf->stream_params.sink.num_of_devices--; - stream_conf->stream_params.sink.num_of_channels -= - ases.sink->channel_count; - - log::info( - "Sink Number Of Devices: {}, Sink Number Of " - "Channels: {}", - stream_conf->stream_params.sink.num_of_devices, - stream_conf->stream_params.sink.num_of_channels); - } - return ases.sink; - }), + ON_CALL(mock_state_machine_, StopStream(_)).WillByDefault([this](LeAudioDeviceGroup* group) { + for (LeAudioDevice* device = group->GetFirstDevice(); device != nullptr; + device = group->GetNextDevice(device)) { + /* Invalidate stream configuration if needed */ + auto* stream_conf = &group->stream_conf; + if (!stream_conf->stream_params.sink.stream_locations.empty() || + !stream_conf->stream_params.source.stream_locations.empty()) { + stream_conf->stream_params.sink.stream_locations.erase( + std::remove_if(stream_conf->stream_params.sink.stream_locations.begin(), + stream_conf->stream_params.sink.stream_locations.end(), + [device, &stream_conf](auto& pair) { + auto ases = device->GetAsesByCisConnHdl(pair.first); + + log::info( + ", sink ase to delete. Cis handle: {}, ase " + "pointer: {}", + (int)(pair.first), fmt::ptr(+ases.sink)); + if (ases.sink) { + stream_conf->stream_params.sink.num_of_devices--; + stream_conf->stream_params.sink.num_of_channels -= + ases.sink->channel_count; + + log::info( + "Sink Number Of Devices: {}, Sink Number Of " + "Channels: {}", + stream_conf->stream_params.sink.num_of_devices, + stream_conf->stream_params.sink.num_of_channels); + } + return ases.sink; + }), stream_conf->stream_params.sink.stream_locations.end()); - stream_conf->stream_params.source.stream_locations.erase( - std::remove_if( - stream_conf->stream_params.source.stream_locations - .begin(), - stream_conf->stream_params.source.stream_locations.end(), - [device, &stream_conf](auto& pair) { - auto ases = device->GetAsesByCisConnHdl(pair.first); - - log::info( - ", source to delete. Cis handle: {}, ase pointer: " - "{}", - (int)(pair.first), fmt::ptr(+ases.source)); - if (ases.source) { - stream_conf->stream_params.source.num_of_devices--; - stream_conf->stream_params.source.num_of_channels -= - ases.source->channel_count; - - log::info( - ", Source Number Of Devices: {}, Source Number " - "Of Channels: {}", - stream_conf->stream_params.source.num_of_devices, - stream_conf->stream_params.source - .num_of_channels); - } - return ases.source; - }), + stream_conf->stream_params.source.stream_locations.erase( + std::remove_if(stream_conf->stream_params.source.stream_locations.begin(), + stream_conf->stream_params.source.stream_locations.end(), + [device, &stream_conf](auto& pair) { + auto ases = device->GetAsesByCisConnHdl(pair.first); + + log::info( + ", source to delete. Cis handle: {}, ase pointer: " + "{}", + (int)(pair.first), fmt::ptr(+ases.source)); + if (ases.source) { + stream_conf->stream_params.source.num_of_devices--; + stream_conf->stream_params.source.num_of_channels -= + ases.source->channel_count; + + log::info( + ", Source Number Of Devices: {}, Source Number " + "Of Channels: {}", + stream_conf->stream_params.source.num_of_devices, + stream_conf->stream_params.source.num_of_channels); + } + return ases.source; + }), stream_conf->stream_params.source.stream_locations.end()); - } + } - group->cig.UnassignCis(device); + group->cig.UnassignCis(device); - for (auto& ase : device->ases_) { - ase.cis_state = types::CisState::IDLE; - ase.data_path_state = types::DataPathState::IDLE; - ase.active = false; - ase.state = types::AseState::BTA_LE_AUDIO_ASE_STATE_IDLE; - ase.cis_id = 0; - ase.cis_conn_hdl = 0; - } - } + for (auto& ase : device->ases_) { + ase.cis_state = types::CisState::IDLE; + ase.data_path_state = types::DataPathState::IDLE; + ase.active = false; + ase.state = types::AseState::BTA_LE_AUDIO_ASE_STATE_IDLE; + ase.cis_id = 0; + ase.cis_conn_hdl = 0; + } + } - // Inject the state - group->SetTargetState(types::AseState::BTA_LE_AUDIO_ASE_STATE_IDLE); - group->SetState(group->GetTargetState()); - state_machine_callbacks_->StatusReportCb( - group->group_id_, GroupStreamStatus::RELEASING); + // Inject the state + group->SetTargetState(types::AseState::BTA_LE_AUDIO_ASE_STATE_IDLE); + group->SetState(group->GetTargetState()); + state_machine_callbacks_->StatusReportCb(group->group_id_, GroupStreamStatus::RELEASING); - do_in_main_thread( + do_in_main_thread( FROM_HERE, base::BindOnce( - [](bluetooth::le_audio::LeAudioGroupStateMachine::Callbacks* - cb, - int group_id) { - cb->StatusReportCb(group_id, GroupStreamStatus::IDLE); - }, - state_machine_callbacks_, group->group_id_)); - }); + [](bluetooth::le_audio::LeAudioGroupStateMachine::Callbacks* cb, + int group_id) { cb->StatusReportCb(group_id, GroupStreamStatus::IDLE); }, + state_machine_callbacks_, group->group_id_)); + }); } void SetUp() override { __android_log_set_minimum_priority(ANDROID_LOG_VERBOSE); init_message_loop_thread(); - ON_CALL(controller_, SupportsBleConnectedIsochronousStreamCentral) - .WillByDefault(Return(true)); + ON_CALL(controller_, SupportsBleConnectedIsochronousStreamCentral).WillByDefault(Return(true)); ON_CALL(controller_, SupportsBleConnectedIsochronousStreamPeripheral) - .WillByDefault(Return(true)); + .WillByDefault(Return(true)); ON_CALL(controller_, SupportsBle2mPhy).WillByDefault(Return(true)); bluetooth::hci::testing::mock_controller_ = &controller_; bluetooth::manager::SetMockBtmInterface(&mock_btm_interface_); @@ -1554,15 +1431,12 @@ class UnicastTestNoInit : public Test { iso_manager_->Start(); mock_iso_manager_ = MockIsoManager::GetInstance(); - ON_CALL(*mock_iso_manager_, RegisterCigCallbacks(_)) - .WillByDefault(SaveArg<0>(&cig_callbacks_)); + ON_CALL(*mock_iso_manager_, RegisterCigCallbacks(_)).WillByDefault(SaveArg<0>(&cig_callbacks_)); - ON_CALL(mock_btm_interface_, IsLinkKeyKnown(_, _)) - .WillByDefault(DoAll(Return(true))); + ON_CALL(mock_btm_interface_, IsLinkKeyKnown(_, _)).WillByDefault(DoAll(Return(true))); // Required since we call OnAudioDataReady() - const auto codec_location = - ::bluetooth::le_audio::types::CodecLocation::HOST; + const auto codec_location = ::bluetooth::le_audio::types::CodecLocation::HOST; SetUpMockAudioHal(); SetUpMockGroups(); @@ -1579,56 +1453,47 @@ class UnicastTestNoInit : public Test { empty_source_pack_ = false; empty_sink_pack_ = false; - bluetooth::le_audio::AudioSetConfigurationProvider::Initialize( - codec_location); + bluetooth::le_audio::AudioSetConfigurationProvider::Initialize(codec_location); ASSERT_FALSE(LeAudioClient::IsLeAudioClientRunning()); } void SetUpMockCodecManager(types::CodecLocation location) { codec_manager_ = bluetooth::le_audio::CodecManager::GetInstance(); ASSERT_NE(codec_manager_, nullptr); - std::vector - mock_offloading_preference(0); + std::vector mock_offloading_preference(0); codec_manager_->Start(mock_offloading_preference); mock_codec_manager_ = MockCodecManager::GetInstance(); ASSERT_NE((void*)mock_codec_manager_, (void*)codec_manager_); ASSERT_NE(mock_codec_manager_, nullptr); - ON_CALL(*mock_codec_manager_, GetCodecLocation()) - .WillByDefault(Return(location)); + ON_CALL(*mock_codec_manager_, GetCodecLocation()).WillByDefault(Return(location)); ON_CALL(*mock_codec_manager_, UpdateActiveUnicastAudioHalClient(_, _, _)) - .WillByDefault(Return(true)); + .WillByDefault(Return(true)); ON_CALL(*mock_codec_manager_, UpdateActiveBroadcastAudioHalClient(_, _)) - .WillByDefault(Return(true)); + .WillByDefault(Return(true)); // Turn on the dual bidir SWB support - ON_CALL(*mock_codec_manager_, IsDualBiDirSwbSupported) - .WillByDefault(Return(true)); + ON_CALL(*mock_codec_manager_, IsDualBiDirSwbSupported).WillByDefault(Return(true)); // Regardless of the codec location, return all the possible configurations ON_CALL(*mock_codec_manager_, GetCodecConfig) - .WillByDefault( - Invoke([](const CodecManager::UnicastConfigurationRequirements& - requirements, - CodecManager::UnicastConfigurationVerifier verifier) { - auto filtered = - *le_audio::AudioSetConfigurationProvider::Get() - ->GetConfigurations(requirements.audio_context_type); + .WillByDefault(Invoke([](const CodecManager::UnicastConfigurationRequirements& + requirements, + CodecManager::UnicastConfigurationVerifier verifier) { + auto filtered = *le_audio::AudioSetConfigurationProvider::Get()->GetConfigurations( + requirements.audio_context_type); // Filter out the dual bidir SWB configurations - if (!bluetooth::le_audio::CodecManager::GetInstance() - ->IsDualBiDirSwbSupported()) { - filtered.erase( - std::remove_if(filtered.begin(), filtered.end(), - [](auto const& el) { - if (el->confs.source.empty()) return false; - return AudioSetConfigurationProvider::Get() - ->CheckConfigurationIsDualBiDirSwb( - *el); - }), - filtered.end()); + if (!bluetooth::le_audio::CodecManager::GetInstance()->IsDualBiDirSwbSupported()) { + filtered.erase(std::remove_if(filtered.begin(), filtered.end(), + [](auto const& el) { + if (el->confs.source.empty()) { + return false; + } + return AudioSetConfigurationProvider::Get() + ->CheckConfigurationIsDualBiDirSwb(*el); + }), + filtered.end()); } auto cptr = verifier(requirements, &filtered); - return cptr - ? std::make_unique< - set_configurations::AudioSetConfiguration>(*cptr) - : nullptr; + return cptr ? std::make_unique(*cptr) + : nullptr; })); } @@ -1665,29 +1530,27 @@ class UnicastTestNoInit : public Test { owned_mock_le_audio_sink_hal_client_.reset(); owned_mock_le_audio_source_hal_client_.reset(); - if (bluetooth::le_audio::AudioSetConfigurationProvider::Get()) + if (bluetooth::le_audio::AudioSetConfigurationProvider::Get()) { bluetooth::le_audio::AudioSetConfigurationProvider::Cleanup(); + } iso_manager_->Stop(); bluetooth::hci::testing::mock_controller_ = nullptr; } - protected: +protected: class MockDeviceWrapper { class IGattHandlers { - public: + public: // IGattHandlers() = default; virtual ~IGattHandlers() = default; - virtual void OnReadCharacteristic(uint16_t handle, GATT_READ_OP_CB cb, - void* cb_data) = 0; - virtual void OnWriteCharacteristic(uint16_t handle, - std::vector value, - tGATT_WRITE_TYPE write_type, - GATT_WRITE_OP_CB cb, + virtual void OnReadCharacteristic(uint16_t handle, GATT_READ_OP_CB cb, void* cb_data) = 0; + virtual void OnWriteCharacteristic(uint16_t handle, std::vector value, + tGATT_WRITE_TYPE write_type, GATT_WRITE_OP_CB cb, void* cb_data) = 0; }; - public: + public: struct csis_mock : public IGattHandlers { uint16_t start = 0; uint16_t end = 0; @@ -1703,12 +1566,10 @@ class UnicastTestNoInit : public Test { int size = 0; MOCK_METHOD((void), OnReadCharacteristic, - (uint16_t handle, GATT_READ_OP_CB cb, void* cb_data), - (override)); + (uint16_t handle, GATT_READ_OP_CB cb, void* cb_data), (override)); MOCK_METHOD((void), OnWriteCharacteristic, - (uint16_t handle, std::vector value, - tGATT_WRITE_TYPE write_type, GATT_WRITE_OP_CB cb, - void* cb_data), + (uint16_t handle, std::vector value, tGATT_WRITE_TYPE write_type, + GATT_WRITE_OP_CB cb, void* cb_data), (override)); }; @@ -1718,12 +1579,10 @@ class UnicastTestNoInit : public Test { uint16_t csis_include = 0; MOCK_METHOD((void), OnReadCharacteristic, - (uint16_t handle, GATT_READ_OP_CB cb, void* cb_data), - (override)); + (uint16_t handle, GATT_READ_OP_CB cb, void* cb_data), (override)); MOCK_METHOD((void), OnWriteCharacteristic, - (uint16_t handle, std::vector value, - tGATT_WRITE_TYPE write_type, GATT_WRITE_OP_CB cb, - void* cb_data), + (uint16_t handle, std::vector value, tGATT_WRITE_TYPE write_type, + GATT_WRITE_OP_CB cb, void* cb_data), (override)); }; @@ -1744,12 +1603,10 @@ class UnicastTestNoInit : public Test { uint16_t end = 0; MOCK_METHOD((void), OnReadCharacteristic, - (uint16_t handle, GATT_READ_OP_CB cb, void* cb_data), - (override)); + (uint16_t handle, GATT_READ_OP_CB cb, void* cb_data), (override)); MOCK_METHOD((void), OnWriteCharacteristic, - (uint16_t handle, std::vector value, - tGATT_WRITE_TYPE write_type, GATT_WRITE_OP_CB cb, - void* cb_data), + (uint16_t handle, std::vector value, tGATT_WRITE_TYPE write_type, + GATT_WRITE_OP_CB cb, void* cb_data), (override)); }; @@ -1767,21 +1624,18 @@ class UnicastTestNoInit : public Test { uint16_t end = 0; MOCK_METHOD((void), OnReadCharacteristic, - (uint16_t handle, GATT_READ_OP_CB cb, void* cb_data), - (override)); + (uint16_t handle, GATT_READ_OP_CB cb, void* cb_data), (override)); MOCK_METHOD((void), OnWriteCharacteristic, - (uint16_t handle, std::vector value, - tGATT_WRITE_TYPE write_type, GATT_WRITE_OP_CB cb, - void* cb_data), + (uint16_t handle, std::vector value, tGATT_WRITE_TYPE write_type, + GATT_WRITE_OP_CB cb, void* cb_data), (override)); }; - MockDeviceWrapper( - RawAddress addr, const std::list& services, - std::unique_ptr> csis, - std::unique_ptr> cas, - std::unique_ptr> ascs, - std::unique_ptr> pacs) + MockDeviceWrapper(RawAddress addr, const std::list& services, + std::unique_ptr> csis, + std::unique_ptr> cas, + std::unique_ptr> ascs, + std::unique_ptr> pacs) : addr(addr) { this->services = services; this->csis = std::move(csis); @@ -1819,29 +1673,24 @@ class UnicastTestNoInit : public Test { bool expect_connected_event = true) { // by default indicate link as encrypted ON_CALL(mock_btm_interface_, BTM_IsEncrypted(address, _)) - .WillByDefault(DoAll(Return(isEncrypted))); + .WillByDefault(DoAll(Return(isEncrypted))); - ON_CALL(mock_btm_interface_, IsLinkKeyKnown(address, _)) - .WillByDefault(DoAll(Return(true))); + ON_CALL(mock_btm_interface_, IsLinkKeyKnown(address, _)).WillByDefault(DoAll(Return(true))); - EXPECT_CALL(mock_gatt_interface_, - Open(gatt_if, address, BTM_BLE_DIRECT_CONNECTION, _)) - .Times(1); + EXPECT_CALL(mock_gatt_interface_, Open(gatt_if, address, BTM_BLE_DIRECT_CONNECTION, _)) + .Times(1); /* If connected event is not expected to arrive, don't test those two below */ if (expect_connected_event) { EXPECT_CALL(mock_gatt_interface_, CancelOpen(gatt_if, address, false)); - EXPECT_CALL( - mock_gatt_interface_, - Open(gatt_if, address, BTM_BLE_BKG_CONNECT_TARGETED_ANNOUNCEMENTS, _)) - .Times(1); + EXPECT_CALL(mock_gatt_interface_, + Open(gatt_if, address, BTM_BLE_BKG_CONNECT_TARGETED_ANNOUNCEMENTS, _)) + .Times(1); } - do_in_main_thread( - FROM_HERE, - base::BindOnce(&LeAudioClient::Connect, - base::Unretained(LeAudioClient::Get()), address)); + do_in_main_thread(FROM_HERE, base::BindOnce(&LeAudioClient::Connect, + base::Unretained(LeAudioClient::Get()), address)); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_btm_interface_); @@ -1850,78 +1699,68 @@ class UnicastTestNoInit : public Test { } void DisconnectLeAudioWithGattClose( - const RawAddress& address, uint16_t conn_id, - tGATT_DISCONN_REASON reason = GATT_CONN_TERMINATE_LOCAL_HOST) { + const RawAddress& address, uint16_t conn_id, + tGATT_DISCONN_REASON reason = GATT_CONN_TERMINATE_LOCAL_HOST) { EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::DISCONNECTED, address)) - .Times(1); + .Times(1); // For test purpose use the acl handle same as conn_id ON_CALL(mock_btm_interface_, GetHCIConnHandle(address, _)) - .WillByDefault([conn_id](RawAddress const& bd_addr, - tBT_TRANSPORT transport) { return conn_id; }); - EXPECT_CALL(mock_btm_interface_, AclDisconnectFromHandle(conn_id, _)) - .Times(0); + .WillByDefault([conn_id](RawAddress const& bd_addr, tBT_TRANSPORT transport) { + return conn_id; + }); + EXPECT_CALL(mock_btm_interface_, AclDisconnectFromHandle(conn_id, _)).Times(0); EXPECT_CALL(mock_gatt_interface_, Close(conn_id)).Times(1); - do_in_main_thread( - FROM_HERE, base::Bind(&LeAudioClient::Disconnect, - base::Unretained(LeAudioClient::Get()), address)); + do_in_main_thread(FROM_HERE, base::Bind(&LeAudioClient::Disconnect, + base::Unretained(LeAudioClient::Get()), address)); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_btm_interface_); Mock::VerifyAndClearExpectations(&mock_gatt_interface_); Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); } - void DisconnectLeAudioWithAclClose( - const RawAddress& address, uint16_t conn_id, - tGATT_DISCONN_REASON reason = GATT_CONN_TERMINATE_LOCAL_HOST) { + void DisconnectLeAudioWithAclClose(const RawAddress& address, uint16_t conn_id, + tGATT_DISCONN_REASON reason = GATT_CONN_TERMINATE_LOCAL_HOST) { EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::DISCONNECTED, address)) - .Times(1); + .Times(1); // For test purpose use the acl handle same as conn_id ON_CALL(mock_btm_interface_, GetHCIConnHandle(address, _)) - .WillByDefault([conn_id](RawAddress const& bd_addr, - tBT_TRANSPORT transport) { return conn_id; }); + .WillByDefault([conn_id](RawAddress const& bd_addr, tBT_TRANSPORT transport) { + return conn_id; + }); EXPECT_CALL(mock_btm_interface_, AclDisconnectFromHandle(conn_id, _)) - .WillOnce([this, &reason](uint16_t handle, tHCI_STATUS rs) { - InjectDisconnectedEvent(handle, reason); - }); + .WillOnce([this, &reason](uint16_t handle, tHCI_STATUS rs) { + InjectDisconnectedEvent(handle, reason); + }); EXPECT_CALL(mock_gatt_interface_, Close(conn_id)).Times(0); - do_in_main_thread( - FROM_HERE, base::Bind(&LeAudioClient::Disconnect, - base::Unretained(LeAudioClient::Get()), address)); + do_in_main_thread(FROM_HERE, base::Bind(&LeAudioClient::Disconnect, + base::Unretained(LeAudioClient::Get()), address)); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_btm_interface_); Mock::VerifyAndClearExpectations(&mock_gatt_interface_); Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); } - void DisconnectLeAudioNoDisconnectedEvtExpected(const RawAddress& address, - uint16_t conn_id) { + void DisconnectLeAudioNoDisconnectedEvtExpected(const RawAddress& address, uint16_t conn_id) { EXPECT_CALL(mock_gatt_interface_, Close(conn_id)).Times(0); - EXPECT_CALL(mock_btm_interface_, AclDisconnectFromHandle(conn_id, _)) - .Times(1); - do_in_main_thread( - FROM_HERE, - base::BindOnce(&LeAudioClient::Disconnect, - base::Unretained(LeAudioClient::Get()), address)); + EXPECT_CALL(mock_btm_interface_, AclDisconnectFromHandle(conn_id, _)).Times(1); + do_in_main_thread(FROM_HERE, base::BindOnce(&LeAudioClient::Disconnect, + base::Unretained(LeAudioClient::Get()), address)); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_gatt_interface_); Mock::VerifyAndClearExpectations(&mock_btm_interface_); } - void ConnectCsisDevice(const RawAddress& addr, uint16_t conn_id, - uint32_t sink_audio_allocation, - uint32_t source_audio_allocation, uint8_t group_size, - int group_id, uint8_t rank, - bool connect_through_csis = false, - bool new_device = true) { - SetSampleDatabaseEarbudsValid(conn_id, addr, sink_audio_allocation, - source_audio_allocation, default_channel_cnt, - default_channel_cnt, + void ConnectCsisDevice(const RawAddress& addr, uint16_t conn_id, uint32_t sink_audio_allocation, + uint32_t source_audio_allocation, uint8_t group_size, int group_id, + uint8_t rank, bool connect_through_csis = false, bool new_device = true) { + SetSampleDatabaseEarbudsValid(conn_id, addr, sink_audio_allocation, source_audio_allocation, + default_channel_cnt, default_channel_cnt, 0x0004, /* source sample freq 16khz */ true, /*add_csis*/ true, /*add_cas*/ @@ -1930,20 +1769,19 @@ class UnicastTestNoInit : public Test { group_size, rank); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, addr)) - .Times(1); + .Times(1); if (new_device) { EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupNodeStatus(addr, group_id, GroupNodeStatus::ADDED)) - .Times(1); + .Times(1); } if (connect_through_csis) { // Add it the way CSIS would do: add to group and then connect do_in_main_thread(FROM_HERE, base::BindOnce(&LeAudioClient::GroupAddNode, - base::Unretained(LeAudioClient::Get()), - group_id, addr)); + base::Unretained(LeAudioClient::Get()), group_id, addr)); ConnectLeAudio(addr); } else { // The usual connect @@ -1955,37 +1793,33 @@ class UnicastTestNoInit : public Test { } void ConnectNonCsisDevice(const RawAddress& addr, uint16_t conn_id, - uint32_t sink_audio_allocation, - uint32_t source_audio_allocation) { - SetSampleDatabaseEarbudsValid( - conn_id, addr, sink_audio_allocation, source_audio_allocation, - default_channel_cnt, default_channel_cnt, 0x0004, - /* source sample freq 16khz */ false, /*add_csis*/ - true, /*add_cas*/ - true, /*add_pacs*/ - true, /*add_ascs*/ - 0, 0); + uint32_t sink_audio_allocation, uint32_t source_audio_allocation) { + SetSampleDatabaseEarbudsValid(conn_id, addr, sink_audio_allocation, source_audio_allocation, + default_channel_cnt, default_channel_cnt, 0x0004, + /* source sample freq 16khz */ false, /*add_csis*/ + true, /*add_cas*/ + true, /*add_pacs*/ + true, /*add_ascs*/ + 0, 0); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, addr)) - .Times(1); + .Times(1); ConnectLeAudio(addr); } - void UpdateLocalSourceMetadata( - std::vector tracks, - bool reconfigure_existing_stream = false) { + void UpdateLocalSourceMetadata(std::vector tracks, + bool reconfigure_existing_stream = false) { std::vector tracks_vec; tracks_vec.reserve(tracks.size()); for (const auto& track : tracks) { playback_track_metadata_v7 desc_track = { - .base = - { - .usage = static_cast(track.usage), - .content_type = - static_cast(track.content_type), - .gain = track.gain, - }, + .base = + { + .usage = static_cast(track.usage), + .content_type = static_cast(track.content_type), + .gain = track.gain, + }, }; if (test_tags_ptr_) { memcpy(desc_track.tags, test_tags_ptr_, strlen(test_tags_ptr_)); @@ -1997,33 +1831,27 @@ class UnicastTestNoInit : public Test { ASSERT_NE(nullptr, mock_le_audio_source_hal_client_); /* Local Source may reconfigure once the metadata is updated */ if (reconfigure_existing_stream) { - Expectation reconfigure = EXPECT_CALL(*mock_le_audio_source_hal_client_, - SuspendedForReconfiguration()) - .Times(1); - EXPECT_CALL(*mock_le_audio_source_hal_client_, CancelStreamingRequest()) - .Times(1); + Expectation reconfigure = + EXPECT_CALL(*mock_le_audio_source_hal_client_, SuspendedForReconfiguration()) + .Times(1); + EXPECT_CALL(*mock_le_audio_source_hal_client_, CancelStreamingRequest()).Times(1); EXPECT_CALL(*mock_le_audio_source_hal_client_, ReconfigurationComplete()) - .Times(1) - .After(reconfigure); + .Times(1) + .After(reconfigure); } else { - EXPECT_CALL(*mock_le_audio_source_hal_client_, - SuspendedForReconfiguration()) - .Times(0); - EXPECT_CALL(*mock_le_audio_source_hal_client_, ReconfigurationComplete()) - .Times(0); + EXPECT_CALL(*mock_le_audio_source_hal_client_, SuspendedForReconfiguration()).Times(0); + EXPECT_CALL(*mock_le_audio_source_hal_client_, ReconfigurationComplete()).Times(0); } ASSERT_NE(unicast_source_hal_cb_, nullptr); - unicast_source_hal_cb_->OnAudioMetadataUpdate(std::move(tracks_vec), - DsaMode::DISABLED); + unicast_source_hal_cb_->OnAudioMetadataUpdate(std::move(tracks_vec), DsaMode::DISABLED); } - void UpdateLocalSourceMetadata(audio_usage_t usage, - audio_content_type_t content_type, + void UpdateLocalSourceMetadata(audio_usage_t usage, audio_content_type_t content_type, bool reconfigure_existing_stream = false) { std::vector tracks = { - {{AUDIO_USAGE_UNKNOWN, AUDIO_CONTENT_TYPE_UNKNOWN, 0}, - {AUDIO_USAGE_UNKNOWN, AUDIO_CONTENT_TYPE_UNKNOWN, 0}}}; + {{AUDIO_USAGE_UNKNOWN, AUDIO_CONTENT_TYPE_UNKNOWN, 0}, + {AUDIO_USAGE_UNKNOWN, AUDIO_CONTENT_TYPE_UNKNOWN, 0}}}; tracks[0].usage = usage; tracks[0].content_type = content_type; @@ -2032,9 +1860,8 @@ class UnicastTestNoInit : public Test { void UpdateLocalSinkMetadata(audio_source_t audio_source) { std::vector tracks = { - {{AUDIO_SOURCE_INVALID, 0.5, AUDIO_DEVICE_NONE, "00:11:22:33:44:55"}, - {AUDIO_SOURCE_MIC, 0.7, AUDIO_DEVICE_OUT_BLE_HEADSET, - "AA:BB:CC:DD:EE:FF"}}}; + {{AUDIO_SOURCE_INVALID, 0.5, AUDIO_DEVICE_NONE, "00:11:22:33:44:55"}, + {AUDIO_SOURCE_MIC, 0.7, AUDIO_DEVICE_OUT_BLE_HEADSET, "AA:BB:CC:DD:EE:FF"}}}; tracks[1].source = audio_source; @@ -2042,13 +1869,12 @@ class UnicastTestNoInit : public Test { tracks_vec.reserve(tracks.size()); for (const auto& track : tracks) { record_track_metadata_v7 desc_track = { - .base = - { - .source = static_cast(track.source), - .gain = track.gain, - .dest_device = - static_cast(track.dest_device), - }, + .base = + { + .source = static_cast(track.source), + .gain = track.gain, + .dest_device = static_cast(track.dest_device), + }, }; strcpy(desc_track.base.dest_device_address, track.dest_device_address); @@ -2065,25 +1891,23 @@ class UnicastTestNoInit : public Test { SyncOnMainLoop(); } - void LocalAudioSourceResume(bool expected_confirmation = true, - bool expected_cancel = false) { + void LocalAudioSourceResume(bool expected_confirmation = true, bool expected_cancel = false) { ASSERT_NE(nullptr, mock_le_audio_source_hal_client_); if (expected_confirmation) { - EXPECT_CALL(*mock_le_audio_source_hal_client_, ConfirmStreamingRequest()) - .Times(1); + EXPECT_CALL(*mock_le_audio_source_hal_client_, ConfirmStreamingRequest()).Times(1); } if (expected_cancel) { - EXPECT_CALL(*mock_le_audio_source_hal_client_, CancelStreamingRequest()) - .Times(1); + EXPECT_CALL(*mock_le_audio_source_hal_client_, CancelStreamingRequest()).Times(1); } - do_in_main_thread(FROM_HERE, - base::BindOnce( - [](LeAudioSourceAudioHalClient::Callbacks* cb) { - if (cb) cb->OnAudioResume(); - }, - unicast_source_hal_cb_)); + do_in_main_thread(FROM_HERE, base::BindOnce( + [](LeAudioSourceAudioHalClient::Callbacks* cb) { + if (cb) { + cb->OnAudioResume(); + } + }, + unicast_source_hal_cb_)); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&*mock_le_audio_source_hal_client_); @@ -2097,19 +1921,16 @@ class UnicastTestNoInit : public Test { void LocalAudioSinkResume(void) { ASSERT_NE(unicast_sink_hal_cb_, nullptr); - do_in_main_thread(FROM_HERE, - base::BindOnce( - [](LeAudioSinkAudioHalClient::Callbacks* cb) { - cb->OnAudioResume(); - }, - unicast_sink_hal_cb_)); + do_in_main_thread( + FROM_HERE, + base::BindOnce([](LeAudioSinkAudioHalClient::Callbacks* cb) { cb->OnAudioResume(); }, + unicast_sink_hal_cb_)); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(mock_le_audio_sink_hal_client_); } - void StartStreaming(audio_usage_t usage, audio_content_type_t content_type, - int group_id, + void StartStreaming(audio_usage_t usage, audio_content_type_t content_type, int group_id, audio_source_t audio_source = AUDIO_SOURCE_INVALID, bool reconfigure_existing_stream = false, bool expected_resume_confirmation = true) { @@ -2121,21 +1942,20 @@ class UnicastTestNoInit : public Test { } /* Stream has been automatically restarted on UpdateLocalSourceMetadata */ - if (reconfigure_existing_stream) return; + if (reconfigure_existing_stream) { + return; + } LocalAudioSourceResume(expected_resume_confirmation); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_state_machine_); - if (usage == AUDIO_USAGE_VOICE_COMMUNICATION || - audio_source != AUDIO_SOURCE_INVALID) { + if (usage == AUDIO_USAGE_VOICE_COMMUNICATION || audio_source != AUDIO_SOURCE_INVALID) { ASSERT_NE(unicast_sink_hal_cb_, nullptr); - do_in_main_thread(FROM_HERE, - base::BindOnce( - [](LeAudioSinkAudioHalClient::Callbacks* cb) { - cb->OnAudioResume(); - }, - unicast_sink_hal_cb_)); + do_in_main_thread( + FROM_HERE, + base::BindOnce([](LeAudioSinkAudioHalClient::Callbacks* cb) { cb->OnAudioResume(); }, + unicast_sink_hal_cb_)); } SyncOnMainLoop(); } @@ -2163,184 +1983,166 @@ class UnicastTestNoInit : public Test { SyncOnMainLoop(); } - void set_sample_database( - uint16_t conn_id, RawAddress addr, - std::unique_ptr> csis, - std::unique_ptr> cas, - std::unique_ptr> ascs, - std::unique_ptr> pacs) { + void set_sample_database(uint16_t conn_id, RawAddress addr, + std::unique_ptr> csis, + std::unique_ptr> cas, + std::unique_ptr> ascs, + std::unique_ptr> pacs) { gatt::DatabaseBuilder bob; /* Generic Access Service */ bob.AddService(0x0001, 0x0003, Uuid::From16Bit(0x1800), true); /* Device Name Char. */ - bob.AddCharacteristic(0x0002, 0x0003, Uuid::From16Bit(0x2a00), - GATT_CHAR_PROP_BIT_READ); + bob.AddCharacteristic(0x0002, 0x0003, Uuid::From16Bit(0x2a00), GATT_CHAR_PROP_BIT_READ); if (csis->start) { bool is_primary = true; - bob.AddService(csis->start, csis->end, bluetooth::csis::kCsisServiceUuid, - is_primary); + bob.AddService(csis->start, csis->end, bluetooth::csis::kCsisServiceUuid, is_primary); if (csis->sirk_char) { - bob.AddCharacteristic( - csis->sirk_char, csis->sirk_char + 1, - bluetooth::csis::kCsisSirkUuid, - GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY); - if (csis->sirk_ccc) - bob.AddDescriptor(csis->sirk_ccc, - Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); + bob.AddCharacteristic(csis->sirk_char, csis->sirk_char + 1, bluetooth::csis::kCsisSirkUuid, + GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY); + if (csis->sirk_ccc) { + bob.AddDescriptor(csis->sirk_ccc, Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); + } } if (csis->size_char) { - bob.AddCharacteristic( - csis->size_char, csis->size_char + 1, - bluetooth::csis::kCsisSizeUuid, - GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY); - if (csis->size_ccc) - bob.AddDescriptor(csis->size_ccc, - Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); + bob.AddCharacteristic(csis->size_char, csis->size_char + 1, bluetooth::csis::kCsisSizeUuid, + GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY); + if (csis->size_ccc) { + bob.AddDescriptor(csis->size_ccc, Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); + } } if (csis->lock_char) { - bob.AddCharacteristic(csis->lock_char, csis->lock_char + 1, - bluetooth::csis::kCsisLockUuid, - GATT_CHAR_PROP_BIT_READ | - GATT_CHAR_PROP_BIT_NOTIFY | - GATT_CHAR_PROP_BIT_WRITE); - if (csis->lock_ccc) - bob.AddDescriptor(csis->lock_ccc, - Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); + bob.AddCharacteristic( + csis->lock_char, csis->lock_char + 1, bluetooth::csis::kCsisLockUuid, + GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY | GATT_CHAR_PROP_BIT_WRITE); + if (csis->lock_ccc) { + bob.AddDescriptor(csis->lock_ccc, Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); + } } - if (csis->rank_char) - bob.AddCharacteristic(csis->rank_char, csis->rank_char + 1, - bluetooth::csis::kCsisRankUuid, + if (csis->rank_char) { + bob.AddCharacteristic(csis->rank_char, csis->rank_char + 1, bluetooth::csis::kCsisRankUuid, GATT_CHAR_PROP_BIT_READ); + } } if (cas->start) { bool is_primary = true; - bob.AddService(cas->start, cas->end, - bluetooth::le_audio::uuid::kCapServiceUuid, is_primary); + bob.AddService(cas->start, cas->end, bluetooth::le_audio::uuid::kCapServiceUuid, is_primary); // Include CSIS service inside - if (cas->csis_include) - bob.AddIncludedService(cas->csis_include, - bluetooth::csis::kCsisServiceUuid, csis->start, + if (cas->csis_include) { + bob.AddIncludedService(cas->csis_include, bluetooth::csis::kCsisServiceUuid, csis->start, csis->end); + } } if (pacs->start) { bool is_primary = true; - bob.AddService( - pacs->start, pacs->end, - bluetooth::le_audio::uuid::kPublishedAudioCapabilityServiceUuid, - is_primary); + bob.AddService(pacs->start, pacs->end, + bluetooth::le_audio::uuid::kPublishedAudioCapabilityServiceUuid, is_primary); if (pacs->sink_pac_char) { bob.AddCharacteristic( - pacs->sink_pac_char, pacs->sink_pac_char + 1, - bluetooth::le_audio::uuid:: - kSinkPublishedAudioCapabilityCharacteristicUuid, - GATT_CHAR_PROP_BIT_READ); - if (pacs->sink_pac_ccc) - bob.AddDescriptor(pacs->sink_pac_ccc, - Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); + pacs->sink_pac_char, pacs->sink_pac_char + 1, + bluetooth::le_audio::uuid::kSinkPublishedAudioCapabilityCharacteristicUuid, + GATT_CHAR_PROP_BIT_READ); + if (pacs->sink_pac_ccc) { + bob.AddDescriptor(pacs->sink_pac_ccc, Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); + } } if (pacs->sink_audio_loc_char) { - bob.AddCharacteristic( - pacs->sink_audio_loc_char, pacs->sink_audio_loc_char + 1, - bluetooth::le_audio::uuid::kSinkAudioLocationCharacteristicUuid, - GATT_CHAR_PROP_BIT_READ); - if (pacs->sink_audio_loc_ccc) + bob.AddCharacteristic(pacs->sink_audio_loc_char, pacs->sink_audio_loc_char + 1, + bluetooth::le_audio::uuid::kSinkAudioLocationCharacteristicUuid, + GATT_CHAR_PROP_BIT_READ); + if (pacs->sink_audio_loc_ccc) { bob.AddDescriptor(pacs->sink_audio_loc_ccc, Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); + } } if (pacs->source_pac_char) { bob.AddCharacteristic( - pacs->source_pac_char, pacs->source_pac_char + 1, - bluetooth::le_audio::uuid:: - kSourcePublishedAudioCapabilityCharacteristicUuid, - GATT_CHAR_PROP_BIT_READ); - if (pacs->source_pac_ccc) - bob.AddDescriptor(pacs->source_pac_ccc, - Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); + pacs->source_pac_char, pacs->source_pac_char + 1, + bluetooth::le_audio::uuid::kSourcePublishedAudioCapabilityCharacteristicUuid, + GATT_CHAR_PROP_BIT_READ); + if (pacs->source_pac_ccc) { + bob.AddDescriptor(pacs->source_pac_ccc, Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); + } } if (pacs->source_audio_loc_char) { - bob.AddCharacteristic( - pacs->source_audio_loc_char, pacs->source_audio_loc_char + 1, - bluetooth::le_audio::uuid::kSourceAudioLocationCharacteristicUuid, - GATT_CHAR_PROP_BIT_READ); - if (pacs->source_audio_loc_ccc) + bob.AddCharacteristic(pacs->source_audio_loc_char, pacs->source_audio_loc_char + 1, + bluetooth::le_audio::uuid::kSourceAudioLocationCharacteristicUuid, + GATT_CHAR_PROP_BIT_READ); + if (pacs->source_audio_loc_ccc) { bob.AddDescriptor(pacs->source_audio_loc_ccc, Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); + } } if (pacs->avail_contexts_char) { - bob.AddCharacteristic(pacs->avail_contexts_char, - pacs->avail_contexts_char + 1, - bluetooth::le_audio::uuid:: - kAudioContextAvailabilityCharacteristicUuid, - GATT_CHAR_PROP_BIT_READ); - if (pacs->avail_contexts_ccc) + bob.AddCharacteristic( + pacs->avail_contexts_char, pacs->avail_contexts_char + 1, + bluetooth::le_audio::uuid::kAudioContextAvailabilityCharacteristicUuid, + GATT_CHAR_PROP_BIT_READ); + if (pacs->avail_contexts_ccc) { bob.AddDescriptor(pacs->avail_contexts_ccc, Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); + } } if (pacs->supp_contexts_char) { - bob.AddCharacteristic( - pacs->supp_contexts_char, pacs->supp_contexts_char + 1, - bluetooth::le_audio::uuid::kAudioSupportedContextCharacteristicUuid, - GATT_CHAR_PROP_BIT_READ); - if (pacs->supp_contexts_ccc) - bob.AddDescriptor(pacs->supp_contexts_ccc, - Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); + bob.AddCharacteristic(pacs->supp_contexts_char, pacs->supp_contexts_char + 1, + bluetooth::le_audio::uuid::kAudioSupportedContextCharacteristicUuid, + GATT_CHAR_PROP_BIT_READ); + if (pacs->supp_contexts_ccc) { + bob.AddDescriptor(pacs->supp_contexts_ccc, Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); + } } } if (ascs->start) { bool is_primary = true; bob.AddService(ascs->start, ascs->end, - bluetooth::le_audio::uuid::kAudioStreamControlServiceUuid, - is_primary); + bluetooth::le_audio::uuid::kAudioStreamControlServiceUuid, is_primary); for (int i = 0; i < max_num_of_ases; i++) { if (ascs->sink_ase_char[i]) { - bob.AddCharacteristic( - ascs->sink_ase_char[i], ascs->sink_ase_char[i] + 1, - bluetooth::le_audio::uuid::kSinkAudioStreamEndpointUuid, - GATT_CHAR_PROP_BIT_READ); - if (ascs->sink_ase_ccc[i]) - bob.AddDescriptor(ascs->sink_ase_ccc[i], - Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); + bob.AddCharacteristic(ascs->sink_ase_char[i], ascs->sink_ase_char[i] + 1, + bluetooth::le_audio::uuid::kSinkAudioStreamEndpointUuid, + GATT_CHAR_PROP_BIT_READ); + if (ascs->sink_ase_ccc[i]) { + bob.AddDescriptor(ascs->sink_ase_ccc[i], Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); + } } if (ascs->source_ase_char[i]) { - bob.AddCharacteristic( - ascs->source_ase_char[i], ascs->source_ase_char[i] + 1, - bluetooth::le_audio::uuid::kSourceAudioStreamEndpointUuid, - GATT_CHAR_PROP_BIT_READ); - if (ascs->source_ase_ccc[i]) + bob.AddCharacteristic(ascs->source_ase_char[i], ascs->source_ase_char[i] + 1, + bluetooth::le_audio::uuid::kSourceAudioStreamEndpointUuid, + GATT_CHAR_PROP_BIT_READ); + if (ascs->source_ase_ccc[i]) { bob.AddDescriptor(ascs->source_ase_ccc[i], Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); + } } } if (ascs->ctp_char) { bob.AddCharacteristic( - ascs->ctp_char, ascs->ctp_char + 1, - bluetooth::le_audio::uuid:: - kAudioStreamEndpointControlPointCharacteristicUuid, - GATT_CHAR_PROP_BIT_READ); - if (ascs->ctp_ccc) - bob.AddDescriptor(ascs->ctp_ccc, - Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); + ascs->ctp_char, ascs->ctp_char + 1, + bluetooth::le_audio::uuid::kAudioStreamEndpointControlPointCharacteristicUuid, + GATT_CHAR_PROP_BIT_READ); + if (ascs->ctp_ccc) { + bob.AddDescriptor(ascs->ctp_ccc, Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); + } } } // Assign conn_id to a certain device - this does not mean it is connected auto dev_wrapper = std::make_unique>( - addr, bob.Build().Services(), std::move(csis), std::move(cas), - std::move(ascs), std::move(pacs)); + addr, bob.Build().Services(), std::move(csis), std::move(cas), std::move(ascs), + std::move(pacs)); peer_devices.emplace(conn_id, std::move(dev_wrapper)); } @@ -2349,8 +2151,8 @@ class UnicastTestNoInit : public Test { auto cas = std::make_unique>(); auto pacs = std::make_unique>(); auto ascs = std::make_unique>(); - set_sample_database(conn_id, addr, std::move(csis), std::move(cas), - std::move(ascs), std::move(pacs)); + set_sample_database(conn_id, addr, std::move(csis), std::move(cas), std::move(ascs), + std::move(pacs)); } struct SampleDatabaseParameters { @@ -2373,28 +2175,27 @@ class UnicastTestNoInit : public Test { }; void SetSampleDatabaseEarbudsValid( - uint16_t conn_id, RawAddress addr, uint32_t sink_audio_allocation, - uint32_t source_audio_allocation, uint8_t sink_channel_cnt = 0x03, - uint8_t source_channel_cnt = 0x03, uint16_t sample_freq_mask = 0x0004, - bool add_csis = true, bool add_cas = true, bool add_pacs = true, - int add_ascs_cnt = 1, uint8_t set_size = 2, uint8_t rank = 1, - GattStatus gatt_status = GATT_SUCCESS) { + uint16_t conn_id, RawAddress addr, uint32_t sink_audio_allocation, + uint32_t source_audio_allocation, uint8_t sink_channel_cnt = 0x03, + uint8_t source_channel_cnt = 0x03, uint16_t sample_freq_mask = 0x0004, + bool add_csis = true, bool add_cas = true, bool add_pacs = true, int add_ascs_cnt = 1, + uint8_t set_size = 2, uint8_t rank = 1, GattStatus gatt_status = GATT_SUCCESS) { SetSampleDatabaseEarbudsValid(SampleDatabaseParameters{ - .conn_id = conn_id, - .addr = addr, - .sink_audio_allocation = sink_audio_allocation, - .source_audio_allocation = source_audio_allocation, - .sink_channel_cnt = sink_channel_cnt, - .source_channel_cnt = source_channel_cnt, - .sample_freq_mask = sample_freq_mask, - .add_csis = add_csis, - .add_cas = add_cas, - .add_pacs = add_pacs, - .add_ascs_cnt = add_ascs_cnt, - .set_size = set_size, - .rank = rank, - .gatt_status = gatt_status, - .max_supported_codec_frames_per_sdu = 1, + .conn_id = conn_id, + .addr = addr, + .sink_audio_allocation = sink_audio_allocation, + .source_audio_allocation = source_audio_allocation, + .sink_channel_cnt = sink_channel_cnt, + .source_channel_cnt = source_channel_cnt, + .sample_freq_mask = sample_freq_mask, + .add_csis = add_csis, + .add_cas = add_cas, + .add_pacs = add_pacs, + .add_ascs_cnt = add_ascs_cnt, + .set_size = set_size, + .rank = rank, + .gatt_status = gatt_status, + .max_supported_codec_frames_per_sdu = 1, }); } @@ -2413,8 +2214,7 @@ class UnicastTestNoInit : public Test { auto set_size = params.set_size; auto rank = params.rank; auto gatt_status = params.gatt_status; - auto max_supported_codec_frames_per_sdu = - params.max_supported_codec_frames_per_sdu; + auto max_supported_codec_frames_per_sdu = params.max_supported_codec_frames_per_sdu; auto csis = std::make_unique>(); if (add_csis) { @@ -2437,7 +2237,9 @@ class UnicastTestNoInit : public Test { if (add_cas) { // attribute handles cas->start = 0x0040; - if (add_csis) cas->csis_include = 0x0041; + if (add_csis) { + cas->csis_include = 0x0041; + } cas->end = 0x0050; // other params } @@ -2490,8 +2292,8 @@ class UnicastTestNoInit : public Test { // other params } - set_sample_database(conn_id, addr, std::move(csis), std::move(cas), - std::move(ascs), std::move(pacs)); + set_sample_database(conn_id, addr, std::move(csis), std::move(cas), std::move(ascs), + std::move(pacs)); if (add_pacs) { uint8_t snk_allocation[4]; @@ -2513,253 +2315,247 @@ class UnicastTestNoInit : public Test { // Set pacs default read values ON_CALL(*peer_devices.at(conn_id)->pacs, OnReadCharacteristic(_, _, _)) - .WillByDefault([=, this](uint16_t handle, GATT_READ_OP_CB cb, - void* cb_data) { - auto& pacs = peer_devices.at(conn_id)->pacs; - std::vector value; - if (gatt_status == GATT_SUCCESS) { - if (handle == pacs->sink_pac_char + 1) { - if (empty_sink_pack_) { - value = {0x00}; - } else { - value = { - // Num records - 0x02, - // Codec_ID - 0x06, - 0x00, - 0x00, - 0x00, - 0x00, - // Codec Spec. Caps. Len - 0x10, - 0x03, /* sample freq */ - 0x01, - sample_freq[0], - sample_freq[1], - 0x02, - 0x02, /* frame duration */ - 0x03, - 0x02, /* channel count */ - 0x03, - sink_channel_cnt, - 0x05, - 0x04, - 0x1E, - 0x00, - 0x78, - 0x00, - // Metadata Length - 0x00, - // Codec_ID - 0x06, - 0x00, - 0x00, - 0x00, - 0x00, - // Codec Spec. Caps. Len - 0x13, - 0x03, /* sample freq */ - 0x01, - 0x80, /* 48kHz */ - 0x00, - 0x02, /* frame duration */ - 0x02, - 0x03, - 0x02, /* channel count */ - 0x03, - sink_channel_cnt, - 0x05, /* octects per frame */ - 0x04, - 0x78, - 0x00, - 0x78, - 0x00, - 0x02, /* Max supported codec frames per SDU */ - 0x05, - max_supported_codec_frames_per_sdu, - // Metadata Length - 0x00, - }; - } - } else if (handle == pacs->sink_audio_loc_char + 1) { - value = { - // Audio Locations - snk_allocation[0], - snk_allocation[1], - snk_allocation[2], - snk_allocation[3], - }; - } else if (handle == pacs->source_pac_char + 1) { - if (empty_source_pack_) { - value = {0x00}; - } else { - value = { - // Num records - 0x02, - // Codec_ID - 0x06, - 0x00, - 0x00, - 0x00, - 0x00, - // Codec Spec. Caps. Len - 0x10, - 0x03, - 0x01, - sample_freq[0], - sample_freq[1], - 0x02, - 0x02, - 0x03, - 0x02, - 0x03, - source_channel_cnt, - 0x05, - 0x04, - 0x1E, - 0x00, - 0x78, - 0x00, - // Metadata Length - 0x00, - // Codec_ID - 0x06, - 0x00, - 0x00, - 0x00, - 0x00, - // Codec Spec. Caps. Len - 0x10, - 0x03, - 0x01, - 0x24, - 0x00, - 0x02, - 0x02, - 0x03, - 0x02, - 0x03, - source_channel_cnt, - 0x05, - 0x04, - 0x1E, - 0x00, - 0x50, - 0x00, - // Metadata Length - 0x00, - }; + .WillByDefault([=, this](uint16_t handle, GATT_READ_OP_CB cb, void* cb_data) { + auto& pacs = peer_devices.at(conn_id)->pacs; + std::vector value; + if (gatt_status == GATT_SUCCESS) { + if (handle == pacs->sink_pac_char + 1) { + if (empty_sink_pack_) { + value = {0x00}; + } else { + value = { + // Num records + 0x02, + // Codec_ID + 0x06, + 0x00, + 0x00, + 0x00, + 0x00, + // Codec Spec. Caps. Len + 0x10, + 0x03, /* sample freq */ + 0x01, + sample_freq[0], + sample_freq[1], + 0x02, + 0x02, /* frame duration */ + 0x03, + 0x02, /* channel count */ + 0x03, + sink_channel_cnt, + 0x05, + 0x04, + 0x1E, + 0x00, + 0x78, + 0x00, + // Metadata Length + 0x00, + // Codec_ID + 0x06, + 0x00, + 0x00, + 0x00, + 0x00, + // Codec Spec. Caps. Len + 0x13, + 0x03, /* sample freq */ + 0x01, + 0x80, /* 48kHz */ + 0x00, + 0x02, /* frame duration */ + 0x02, + 0x03, + 0x02, /* channel count */ + 0x03, + sink_channel_cnt, + 0x05, /* octects per frame */ + 0x04, + 0x78, + 0x00, + 0x78, + 0x00, + 0x02, /* Max supported codec frames per SDU */ + 0x05, + max_supported_codec_frames_per_sdu, + // Metadata Length + 0x00, + }; + } + } else if (handle == pacs->sink_audio_loc_char + 1) { + value = { + // Audio Locations + snk_allocation[0], + snk_allocation[1], + snk_allocation[2], + snk_allocation[3], + }; + } else if (handle == pacs->source_pac_char + 1) { + if (empty_source_pack_) { + value = {0x00}; + } else { + value = { + // Num records + 0x02, + // Codec_ID + 0x06, + 0x00, + 0x00, + 0x00, + 0x00, + // Codec Spec. Caps. Len + 0x10, + 0x03, + 0x01, + sample_freq[0], + sample_freq[1], + 0x02, + 0x02, + 0x03, + 0x02, + 0x03, + source_channel_cnt, + 0x05, + 0x04, + 0x1E, + 0x00, + 0x78, + 0x00, + // Metadata Length + 0x00, + // Codec_ID + 0x06, + 0x00, + 0x00, + 0x00, + 0x00, + // Codec Spec. Caps. Len + 0x10, + 0x03, + 0x01, + 0x24, + 0x00, + 0x02, + 0x02, + 0x03, + 0x02, + 0x03, + source_channel_cnt, + 0x05, + 0x04, + 0x1E, + 0x00, + 0x50, + 0x00, + // Metadata Length + 0x00, + }; + } + } else if (handle == pacs->source_audio_loc_char + 1) { + value = { + // Audio Locations + src_allocation[0], + src_allocation[1], + src_allocation[2], + src_allocation[3], + }; + } else if (handle == pacs->avail_contexts_char + 1) { + value = { + // Sink Avail Contexts + (uint8_t)(available_snk_context_types_), + (uint8_t)(available_snk_context_types_ >> 8), + // Source Avail Contexts + (uint8_t)(available_src_context_types_), + (uint8_t)(available_src_context_types_ >> 8), + }; + } else if (handle == pacs->supp_contexts_char + 1) { + value = { + // Sink Supp Contexts + (uint8_t)(supported_snk_context_types_), + (uint8_t)(supported_snk_context_types_ >> 8), + // Source Supp Contexts + (uint8_t)(supported_src_context_types_), + (uint8_t)(supported_src_context_types_ >> 8), + }; + } } - } else if (handle == pacs->source_audio_loc_char + 1) { - value = { - // Audio Locations - src_allocation[0], - src_allocation[1], - src_allocation[2], - src_allocation[3], - }; - } else if (handle == pacs->avail_contexts_char + 1) { - value = { - // Sink Avail Contexts - (uint8_t)(available_snk_context_types_), - (uint8_t)(available_snk_context_types_ >> 8), - // Source Avail Contexts - (uint8_t)(available_src_context_types_), - (uint8_t)(available_src_context_types_ >> 8), - }; - } else if (handle == pacs->supp_contexts_char + 1) { - value = { - // Sink Supp Contexts - (uint8_t)(supported_snk_context_types_), - (uint8_t)(supported_snk_context_types_ >> 8), - // Source Supp Contexts - (uint8_t)(supported_src_context_types_), - (uint8_t)(supported_src_context_types_ >> 8), - }; - } - } - cb(conn_id, gatt_status, handle, value.size(), value.data(), - cb_data); - }); + cb(conn_id, gatt_status, handle, value.size(), value.data(), cb_data); + }); } if (add_ascs_cnt > 0) { // Set ascs default read values ON_CALL(*peer_devices.at(conn_id)->ascs, OnReadCharacteristic(_, _, _)) - .WillByDefault([this, conn_id, gatt_status](uint16_t handle, - GATT_READ_OP_CB cb, - void* cb_data) { - auto& ascs = peer_devices.at(conn_id)->ascs; - std::vector value; - bool is_ase_sink_request = false; - bool is_ase_src_request = false; - uint8_t idx; - - if (handle == ascs->ctp_ccc && ccc_stored_byte_val_.has_value()) { - value = {*ccc_stored_byte_val_, 00}; - cb(conn_id, gatt_read_ctp_ccc_status_, handle, value.size(), - value.data(), cb_data); - return; - } + .WillByDefault([this, conn_id, gatt_status](uint16_t handle, GATT_READ_OP_CB cb, + void* cb_data) { + auto& ascs = peer_devices.at(conn_id)->ascs; + std::vector value; + bool is_ase_sink_request = false; + bool is_ase_src_request = false; + uint8_t idx; + + if (handle == ascs->ctp_ccc && ccc_stored_byte_val_.has_value()) { + value = {*ccc_stored_byte_val_, 00}; + cb(conn_id, gatt_read_ctp_ccc_status_, handle, value.size(), value.data(), + cb_data); + return; + } - if (gatt_status == GATT_SUCCESS) { - if (handle == ascs->ctp_ccc) { - value = UINT16_TO_VEC_UINT8(ascs->ctp_ccc_val); - } else { - for (idx = 0; idx < max_num_of_ases; idx++) { - if (handle == ascs->sink_ase_ccc[idx] + 1) { - value = UINT16_TO_VEC_UINT8(ascs->sink_ase_ccc_val[idx]); - break; + if (gatt_status == GATT_SUCCESS) { + if (handle == ascs->ctp_ccc) { + value = UINT16_TO_VEC_UINT8(ascs->ctp_ccc_val); + } else { + for (idx = 0; idx < max_num_of_ases; idx++) { + if (handle == ascs->sink_ase_ccc[idx] + 1) { + value = UINT16_TO_VEC_UINT8(ascs->sink_ase_ccc_val[idx]); + break; + } + if (handle == ascs->source_ase_char[idx] + 1) { + value = UINT16_TO_VEC_UINT8(ascs->source_ase_ccc_val[idx]); + break; + } + } } - if (handle == ascs->source_ase_char[idx] + 1) { - value = UINT16_TO_VEC_UINT8(ascs->source_ase_ccc_val[idx]); - break; + + for (idx = 0; idx < max_num_of_ases; idx++) { + if (handle == ascs->sink_ase_char[idx] + 1) { + is_ase_sink_request = true; + break; + } + if (handle == ascs->source_ase_char[idx] + 1) { + is_ase_src_request = true; + break; + } } - } - } - for (idx = 0; idx < max_num_of_ases; idx++) { - if (handle == ascs->sink_ase_char[idx] + 1) { - is_ase_sink_request = true; - break; - } - if (handle == ascs->source_ase_char[idx] + 1) { - is_ase_src_request = true; - break; + if (is_ase_sink_request) { + value = { + // ASE ID + static_cast(idx + 1), + // State + static_cast(bluetooth::le_audio::types::AseState:: + BTA_LE_AUDIO_ASE_STATE_IDLE), + // No Additional ASE params for IDLE state + }; + } else if (is_ase_src_request) { + value = { + // ASE ID + static_cast(idx + 6), + // State + static_cast(bluetooth::le_audio::types::AseState:: + BTA_LE_AUDIO_ASE_STATE_IDLE), + // No Additional ASE params for IDLE state + }; + } } - } - - if (is_ase_sink_request) { - value = { - // ASE ID - static_cast(idx + 1), - // State - static_cast(bluetooth::le_audio::types::AseState:: - BTA_LE_AUDIO_ASE_STATE_IDLE), - // No Additional ASE params for IDLE state - }; - } else if (is_ase_src_request) { - value = { - // ASE ID - static_cast(idx + 6), - // State - static_cast(bluetooth::le_audio::types::AseState:: - BTA_LE_AUDIO_ASE_STATE_IDLE), - // No Additional ASE params for IDLE state - }; - } - } - cb(conn_id, gatt_status, handle, value.size(), value.data(), - cb_data); - }); + cb(conn_id, gatt_status, handle, value.size(), value.data(), cb_data); + }); } } - void TestAudioDataTransfer(int group_id, uint8_t cis_count_out, - uint8_t cis_count_in, int data_len, - int in_data_len = 40, - uint16_t decoded_in_data_len = 0) { + void TestAudioDataTransfer(int group_id, uint8_t cis_count_out, uint8_t cis_count_in, + int data_len, int in_data_len = 40, uint16_t decoded_in_data_len = 0) { ASSERT_NE(unicast_source_hal_cb_, nullptr); ASSERT_NE(mock_le_audio_sink_hal_client_, nullptr); @@ -2767,22 +2563,19 @@ class UnicastTestNoInit : public Test { std::vector handles; if (cis_count_out) { EXPECT_CALL(*mock_iso_manager_, SendIsoData(_, _, _)) - .Times(cis_count_out) - .WillRepeatedly( - [&handles](uint16_t iso_handle, const uint8_t* data, - uint16_t data_len) { handles.push_back(iso_handle); }); + .Times(cis_count_out) + .WillRepeatedly([&handles](uint16_t iso_handle, const uint8_t* data, + uint16_t data_len) { handles.push_back(iso_handle); }); } std::vector data(data_len); unicast_source_hal_cb_->OnAudioDataReady(data); // Inject microphone data from group (2 CISes - pass stereo data in 1 call) if (decoded_in_data_len) { - EXPECT_CALL(*mock_le_audio_sink_hal_client_, - SendData(_, decoded_in_data_len)) - .Times(cis_count_in > 0 ? 1 : 0); + EXPECT_CALL(*mock_le_audio_sink_hal_client_, SendData(_, decoded_in_data_len)) + .Times(cis_count_in > 0 ? 1 : 0); } else { - EXPECT_CALL(*mock_le_audio_sink_hal_client_, SendData(_, _)) - .Times(cis_count_in > 0 ? 1 : 0); + EXPECT_CALL(*mock_le_audio_sink_hal_client_, SendData(_, _)).Times(cis_count_in > 0 ? 1 : 0); } ASSERT_EQ(streaming_groups.count(group_id), 1u); @@ -2794,14 +2587,17 @@ class UnicastTestNoInit : public Test { for (LeAudioDevice* device = group->GetFirstDevice(); device != nullptr; device = group->GetNextDevice(device)) { for (auto& ase : device->ases_) { - if (ase.direction == - bluetooth::le_audio::types::kLeAudioDirectionSource) { + if (ase.direction == bluetooth::le_audio::types::kLeAudioDirectionSource) { InjectIncomingIsoData(group_id, ase.cis_conn_hdl, in_data_len); --cis_count_in; - if (!cis_count_in) break; + if (!cis_count_in) { + break; + } } } - if (!cis_count_in) break; + if (!cis_count_in) { + break; + } } } @@ -2814,8 +2610,7 @@ class UnicastTestNoInit : public Test { Mock::VerifyAndClearExpectations(mock_le_audio_sink_hal_client_); } - void InjectIncomingIsoData(uint16_t cig_id, uint16_t cis_con_hdl, - size_t payload_size) { + void InjectIncomingIsoData(uint16_t cig_id, uint16_t cis_con_hdl, size_t payload_size) { BT_HDR* bt_hdr = (BT_HDR*)malloc(sizeof(BT_HDR) + payload_size); bt_hdr->offset = 0; @@ -2829,21 +2624,18 @@ class UnicastTestNoInit : public Test { cis_evt.p_msg = bt_hdr; ASSERT_NE(cig_callbacks_, nullptr); - cig_callbacks_->OnCisEvent( - bluetooth::hci::iso_manager::kIsoEventCisDataAvailable, &cis_evt); + cig_callbacks_->OnCisEvent(bluetooth::hci::iso_manager::kIsoEventCisDataAvailable, &cis_evt); free(bt_hdr); } - void InjectCisDisconnected(uint16_t cig_id, uint16_t cis_con_hdl, - uint8_t reason = 0) { + void InjectCisDisconnected(uint16_t cig_id, uint16_t cis_con_hdl, uint8_t reason = 0) { bluetooth::hci::iso_manager::cis_disconnected_evt cis_evt; cis_evt.cig_id = cig_id; cis_evt.cis_conn_hdl = cis_con_hdl; cis_evt.reason = reason; ASSERT_NE(cig_callbacks_, nullptr); - cig_callbacks_->OnCisEvent( - bluetooth::hci::iso_manager::kIsoEventCisDisconnected, &cis_evt); + cig_callbacks_->OnCisEvent(bluetooth::hci::iso_manager::kIsoEventCisDisconnected, &cis_evt); } void InjectCigRemoved(uint8_t cig_id) { @@ -2852,8 +2644,7 @@ class UnicastTestNoInit : public Test { evt.cig_id = cig_id; ASSERT_NE(cig_callbacks_, nullptr); - cig_callbacks_->OnCisEvent( - bluetooth::hci::iso_manager::kIsoEventCigOnRemoveCmpl, &evt); + cig_callbacks_->OnCisEvent(bluetooth::hci::iso_manager::kIsoEventCigOnRemoveCmpl, &evt); } NiceMock mock_audio_hal_client_callbacks_; @@ -2877,8 +2668,7 @@ class UnicastTestNoInit : public Test { tBTA_GATTC_CBACK* gatt_callback; const uint8_t gatt_if = 0xfe; uint16_t global_conn_id = 1; - bluetooth::le_audio::LeAudioGroupStateMachine::Callbacks* - state_machine_callbacks_; + bluetooth::le_audio::LeAudioGroupStateMachine::Callbacks* state_machine_callbacks_; std::map streaming_groups; bool block_streaming_state_callback = false; @@ -2916,7 +2706,7 @@ class UnicastTestNoInit : public Test { }; class UnicastTest : public UnicastTestNoInit { - protected: +protected: void SetUp() override { UnicastTestNoInit::SetUp(); @@ -2924,35 +2714,31 @@ class UnicastTest : public UnicastTestNoInit { EXPECT_CALL(mock_storage_load, Call()).Times(1); ON_CALL(mock_btm_interface_, GetHCIConnHandle(_, _)) - .WillByDefault([this](RawAddress const& bd_addr, - tBT_TRANSPORT transport) -> uint16_t { - for (auto const& [conn_id, dev_wrapper] : peer_devices) { - if (dev_wrapper->addr == bd_addr) { - return conn_id; - } - } - log::error("GetHCIConnHandle Mock: not a valid test device!"); - return 0x00FE; - }); + .WillByDefault([this](RawAddress const& bd_addr, tBT_TRANSPORT transport) -> uint16_t { + for (auto const& [conn_id, dev_wrapper] : peer_devices) { + if (dev_wrapper->addr == bd_addr) { + return conn_id; + } + } + log::error("GetHCIConnHandle Mock: not a valid test device!"); + return 0x00FE; + }); ON_CALL(mock_btm_interface_, AclDisconnectFromHandle(_, _)) - .WillByDefault([this](uint16_t handle, tHCI_STATUS rs) { - ASSERT_NE(handle, GATT_INVALID_CONN_ID); - InjectDisconnectedEvent(handle, GATT_CONN_TERMINATE_LOCAL_HOST); - }); + .WillByDefault([this](uint16_t handle, tHCI_STATUS rs) { + ASSERT_NE(handle, GATT_INVALID_CONN_ID); + InjectDisconnectedEvent(handle, GATT_CONN_TERMINATE_LOCAL_HOST); + }); - std::vector<::bluetooth::le_audio::btle_audio_codec_config_t> - framework_encode_preference; + std::vector<::bluetooth::le_audio::btle_audio_codec_config_t> framework_encode_preference; BtaAppRegisterCallback app_register_callback; EXPECT_CALL(mock_gatt_interface_, AppRegister(_, _, _)) - .WillOnce(DoAll(SaveArg<0>(&gatt_callback), - SaveArg<1>(&app_register_callback))); + .WillOnce(DoAll(SaveArg<0>(&gatt_callback), SaveArg<1>(&app_register_callback))); LeAudioClient::Initialize( - &mock_audio_hal_client_callbacks_, - base::Bind([](MockFunction* foo) { foo->Call(); }, - &mock_storage_load), - base::Bind([](MockFunction* foo) { return foo->Call(); }, - &mock_hal_2_1_verifier), - framework_encode_preference); + &mock_audio_hal_client_callbacks_, + base::Bind([](MockFunction* foo) { foo->Call(); }, &mock_storage_load), + base::Bind([](MockFunction* foo) { return foo->Call(); }, + &mock_hal_2_1_verifier), + framework_encode_preference); SyncOnMainLoop(); ASSERT_TRUE(gatt_callback); @@ -2975,7 +2761,7 @@ class UnicastTest : public UnicastTestNoInit { }; class UnicastTestHealthStatus : public UnicastTest { - protected: +protected: void SetUp() override { UnicastTest::SetUp(); group_ = new LeAudioDeviceGroup(group_id_); @@ -2991,7 +2777,7 @@ class UnicastTestHealthStatus : public UnicastTest { }; class UnicastTestHandoverMode : public UnicastTest { - protected: +protected: void SetUp() override { use_handover_mode = true; UnicastTest::SetUp(); @@ -3022,54 +2808,44 @@ TEST_F(UnicastTestNoInit, InitializeNoHal_2_1) { ASSERT_FALSE(LeAudioClient::IsLeAudioClientRunning()); // Report False when asked for Audio HAL 2.1 support - ON_CALL(mock_hal_2_1_verifier, Call()).WillByDefault([]() -> bool { - return false; - }); + ON_CALL(mock_hal_2_1_verifier, Call()).WillByDefault([]() -> bool { return false; }); BtaAppRegisterCallback app_register_callback; ON_CALL(mock_gatt_interface_, AppRegister(_, _, _)) - .WillByDefault(DoAll(SaveArg<0>(&gatt_callback), - SaveArg<1>(&app_register_callback))); - std::vector<::bluetooth::le_audio::btle_audio_codec_config_t> - framework_encode_preference; + .WillByDefault(DoAll(SaveArg<0>(&gatt_callback), SaveArg<1>(&app_register_callback))); + std::vector<::bluetooth::le_audio::btle_audio_codec_config_t> framework_encode_preference; EXPECT_DEATH( - LeAudioClient::Initialize( - &mock_audio_hal_client_callbacks_, - base::Bind([](MockFunction* foo) { foo->Call(); }, - &mock_storage_load), - base::Bind([](MockFunction* foo) { return foo->Call(); }, - &mock_hal_2_1_verifier), - framework_encode_preference), - "LE Audio Client requires Bluetooth Audio HAL V2.1 at least. Either " - "disable LE Audio Profile, or update your HAL"); + LeAudioClient::Initialize( + &mock_audio_hal_client_callbacks_, + base::Bind([](MockFunction* foo) { foo->Call(); }, &mock_storage_load), + base::Bind([](MockFunction* foo) { return foo->Call(); }, + &mock_hal_2_1_verifier), + framework_encode_preference), + "LE Audio Client requires Bluetooth Audio HAL V2.1 at least. Either " + "disable LE Audio Profile, or update your HAL"); } TEST_F(UnicastTest, ConnectAndSetupPhy) { const RawAddress test_address0 = GetTestAddress(0); uint16_t conn_id = 1; - SetSampleDatabaseEarbudsValid( - 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, - default_channel_cnt, 0x0004, - /* source sample freq 16khz */ true, /*add_csis*/ - true, /*add_cas*/ - true, /*add_pacs*/ - default_ase_cnt /*add_ascs*/); - - EXPECT_CALL(mock_btm_interface_, - BleSetPhy(test_address0, PHY_LE_2M, PHY_LE_2M, 0)) - .Times(1); + SetSampleDatabaseEarbudsValid(1, test_address0, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, + default_channel_cnt, 0x0004, + /* source sample freq 16khz */ true, /*add_csis*/ + true, /*add_cas*/ + true, /*add_pacs*/ + default_ase_cnt /*add_ascs*/); + + EXPECT_CALL(mock_btm_interface_, BleSetPhy(test_address0, PHY_LE_2M, PHY_LE_2M, 0)).Times(1); ConnectLeAudio(test_address0, false); Mock::VerifyAndClearExpectations(&mock_btm_interface_); - EXPECT_CALL(mock_btm_interface_, - BleSetPhy(test_address0, PHY_LE_2M, PHY_LE_2M, 0)) - .Times(1); + EXPECT_CALL(mock_btm_interface_, BleSetPhy(test_address0, PHY_LE_2M, PHY_LE_2M, 0)).Times(1); InjectPhyChangedEvent(conn_id, 0, 0, GATT_REQ_NOT_SUPPORTED); SyncOnMainLoop(); ON_CALL(mock_btm_interface_, BTM_IsEncrypted(test_address0, _)) - .WillByDefault(DoAll(Return(true))); + .WillByDefault(DoAll(Return(true))); InjectEncryptionChangedEvent(test_address0); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_btm_interface_); @@ -3080,23 +2856,19 @@ TEST_F(UnicastTest, ConnectAndSetupPhy) { InjectDisconnectedEvent(conn_id); SyncOnMainLoop(); - EXPECT_CALL(mock_btm_interface_, - BleSetPhy(test_address0, PHY_LE_2M, PHY_LE_2M, 0)) - .Times(1); + EXPECT_CALL(mock_btm_interface_, BleSetPhy(test_address0, PHY_LE_2M, PHY_LE_2M, 0)).Times(1); ON_CALL(mock_btm_interface_, BTM_IsEncrypted(test_address0, _)) - .WillByDefault(DoAll(Return(false))); + .WillByDefault(DoAll(Return(false))); InjectConnectedEvent(test_address0, 1); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_btm_interface_); - EXPECT_CALL(mock_btm_interface_, - BleSetPhy(test_address0, PHY_LE_2M, PHY_LE_2M, 0)) - .Times(1); + EXPECT_CALL(mock_btm_interface_, BleSetPhy(test_address0, PHY_LE_2M, PHY_LE_2M, 0)).Times(1); InjectPhyChangedEvent(conn_id, 0, 0, GATT_REQ_NOT_SUPPORTED); SyncOnMainLoop(); ON_CALL(mock_btm_interface_, BTM_IsEncrypted(test_address0, _)) - .WillByDefault(DoAll(Return(true))); + .WillByDefault(DoAll(Return(true))); InjectEncryptionChangedEvent(test_address0); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_btm_interface_); @@ -3107,41 +2879,39 @@ TEST_F(UnicastTest, ConnectOneEarbudEmpty) { SetSampleDatabaseEmpty(1, test_address0); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::DISCONNECTED, test_address0)) - .Times(1); + .Times(1); EXPECT_CALL(mock_gatt_interface_, Close(_)).Times(1); ConnectLeAudio(test_address0); } TEST_F(UnicastTest, ConnectOneEarbudNoPacs) { const RawAddress test_address0 = GetTestAddress(0); - SetSampleDatabaseEarbudsValid( - 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, - default_channel_cnt, 0x0004, - /* source sample freq 16khz */ true, /*add_csis*/ - true, /*add_cas*/ - false, /*add_pacs*/ - default_ase_cnt /*add_ascs*/); + SetSampleDatabaseEarbudsValid(1, test_address0, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, + default_channel_cnt, 0x0004, + /* source sample freq 16khz */ true, /*add_csis*/ + true, /*add_cas*/ + false, /*add_pacs*/ + default_ase_cnt /*add_ascs*/); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::DISCONNECTED, test_address0)) - .Times(1); + .Times(1); EXPECT_CALL(mock_gatt_interface_, Close(_)).Times(1); ConnectLeAudio(test_address0); } TEST_F(UnicastTest, ConnectOneEarbudNoAscs) { const RawAddress test_address0 = GetTestAddress(0); - SetSampleDatabaseEarbudsValid( - 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, - default_channel_cnt, 0x0004, - /* source sample freq 16khz */ true, /*add_csis*/ - true, /*add_cas*/ - true, /*add_pacs*/ - 0 /*add_ascs*/); + SetSampleDatabaseEarbudsValid(1, test_address0, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, + default_channel_cnt, 0x0004, + /* source sample freq 16khz */ true, /*add_csis*/ + true, /*add_cas*/ + true, /*add_pacs*/ + 0 /*add_ascs*/); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::DISCONNECTED, test_address0)) - .Times(1); + .Times(1); EXPECT_CALL(mock_gatt_interface_, Close(_)).Times(1); ConnectLeAudio(test_address0); } @@ -3149,61 +2919,57 @@ TEST_F(UnicastTest, ConnectOneEarbudNoAscs) { TEST_F(UnicastTest, ConnectOneEarbudNoCas) { const RawAddress test_address0 = GetTestAddress(0); uint16_t conn_id = 1; - SetSampleDatabaseEarbudsValid( - conn_id, test_address0, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, - default_channel_cnt, 0x0004, - /* source sample freq 16khz */ true, /*add_csis*/ - false, /*add_cas*/ - true, /*add_pacs*/ - default_ase_cnt /*add_ascs*/); + SetSampleDatabaseEarbudsValid(conn_id, test_address0, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, + default_channel_cnt, 0x0004, + /* source sample freq 16khz */ true, /*add_csis*/ + false, /*add_cas*/ + true, /*add_pacs*/ + default_ase_cnt /*add_ascs*/); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); ConnectLeAudio(test_address0); } TEST_F(UnicastTest, ConnectOneEarbudNoCsis) { const RawAddress test_address0 = GetTestAddress(0); - SetSampleDatabaseEarbudsValid( - 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, - default_channel_cnt, 0x0004, - /* source sample freq 16khz */ false, /*add_csis*/ - true, /*add_cas*/ - true, /*add_pacs*/ - default_ase_cnt /*add_ascs*/); + SetSampleDatabaseEarbudsValid(1, test_address0, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, + default_channel_cnt, 0x0004, + /* source sample freq 16khz */ false, /*add_csis*/ + true, /*add_cas*/ + true, /*add_pacs*/ + default_ase_cnt /*add_ascs*/); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); ConnectLeAudio(test_address0); } TEST_F(UnicastTest, ConnectOneEarbudWithInvalidCsis) { const RawAddress test_address0 = GetTestAddress(0); - SetSampleDatabaseEarbudsValid( - 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, - default_channel_cnt, 0x0004, - /* source sample freq 16khz */ true, /*add_csis*/ - true, /*add_cas*/ - true, /*add_pacs*/ - default_ase_cnt /*add_ascs*/); + SetSampleDatabaseEarbudsValid(1, test_address0, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, + default_channel_cnt, 0x0004, + /* source sample freq 16khz */ true, /*add_csis*/ + true, /*add_cas*/ + true, /*add_pacs*/ + default_ase_cnt /*add_ascs*/); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::DISCONNECTED, test_address0)) - .Times(1); + .Times(1); EXPECT_CALL(mock_gatt_interface_, Close(_)).Times(1); // Report working CSIS - ON_CALL(mock_csis_client_module_, IsCsisClientRunning()) - .WillByDefault(Return(true)); + ON_CALL(mock_csis_client_module_, IsCsisClientRunning()).WillByDefault(Return(true)); /* Make sure Group has not knowledge about the device */ ON_CALL(mock_groups_module_, GetGroupId(_, _)) - .WillByDefault([](const RawAddress& addr, bluetooth::Uuid uuid) { - return bluetooth::groups::kGroupUnknown; - }); + .WillByDefault([](const RawAddress& addr, bluetooth::Uuid uuid) { + return bluetooth::groups::kGroupUnknown; + }); ConnectLeAudio(test_address0); SyncOnMainLoop(); @@ -3215,187 +2981,166 @@ TEST_F(UnicastTestHealthStatus, ConnectOneEarbudEmpty_withHealthStatus) { const RawAddress test_address0 = GetTestAddress(0); SetSampleDatabaseEmpty(1, test_address0); EXPECT_CALL(mock_audio_hal_client_callbacks_, - OnHealthBasedRecommendationAction( - test_address0, LeAudioHealthBasedAction::DISABLE)) - .Times(1); + OnHealthBasedRecommendationAction(test_address0, LeAudioHealthBasedAction::DISABLE)) + .Times(1); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::DISCONNECTED, test_address0)) - .Times(1); + .Times(1); EXPECT_CALL(mock_gatt_interface_, Close(_)).Times(1); ConnectLeAudio(test_address0); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); Mock::VerifyAndClearExpectations(&mock_gatt_interface_); - LeAudioHealthStatus::Get()->RemoveStatistics( - test_address0, bluetooth::groups::kGroupUnknown); + LeAudioHealthStatus::Get()->RemoveStatistics(test_address0, bluetooth::groups::kGroupUnknown); } TEST_F(UnicastTestHealthStatus, ConnectOneEarbudNoPacs_withHealthStatus) { const RawAddress test_address0 = GetTestAddress(0); - SetSampleDatabaseEarbudsValid( - 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, - default_channel_cnt, 0x0004, - /* source sample freq 16khz */ true, /*add_csis*/ - true, /*add_cas*/ - false, /*add_pacs*/ - default_ase_cnt /*add_ascs*/); - EXPECT_CALL(mock_audio_hal_client_callbacks_, - OnHealthBasedRecommendationAction( - test_address0, LeAudioHealthBasedAction::DISABLE)) - .Times(1); + SetSampleDatabaseEarbudsValid(1, test_address0, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, + default_channel_cnt, 0x0004, + /* source sample freq 16khz */ true, /*add_csis*/ + true, /*add_cas*/ + false, /*add_pacs*/ + default_ase_cnt /*add_ascs*/); + EXPECT_CALL(mock_audio_hal_client_callbacks_, + OnHealthBasedRecommendationAction(test_address0, LeAudioHealthBasedAction::DISABLE)) + .Times(1); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::DISCONNECTED, test_address0)) - .Times(1); + .Times(1); EXPECT_CALL(mock_gatt_interface_, Close(_)).Times(1); ConnectLeAudio(test_address0); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); Mock::VerifyAndClearExpectations(&mock_gatt_interface_); - LeAudioHealthStatus::Get()->RemoveStatistics( - test_address0, bluetooth::groups::kGroupUnknown); + LeAudioHealthStatus::Get()->RemoveStatistics(test_address0, bluetooth::groups::kGroupUnknown); } TEST_F(UnicastTestHealthStatus, ConnectOneEarbudNoAscs_withHealthStatus) { const RawAddress test_address0 = GetTestAddress(0); - SetSampleDatabaseEarbudsValid( - 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, - default_channel_cnt, 0x0004, - /* source sample freq 16khz */ true, /*add_csis*/ - true, /*add_cas*/ - true, /*add_pacs*/ - 0 /*add_ascs*/); - EXPECT_CALL(mock_audio_hal_client_callbacks_, - OnHealthBasedRecommendationAction( - test_address0, LeAudioHealthBasedAction::DISABLE)) - .Times(1); + SetSampleDatabaseEarbudsValid(1, test_address0, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, + default_channel_cnt, 0x0004, + /* source sample freq 16khz */ true, /*add_csis*/ + true, /*add_cas*/ + true, /*add_pacs*/ + 0 /*add_ascs*/); + EXPECT_CALL(mock_audio_hal_client_callbacks_, + OnHealthBasedRecommendationAction(test_address0, LeAudioHealthBasedAction::DISABLE)) + .Times(1); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::DISCONNECTED, test_address0)) - .Times(1); + .Times(1); EXPECT_CALL(mock_gatt_interface_, Close(_)).Times(1); ConnectLeAudio(test_address0); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); Mock::VerifyAndClearExpectations(&mock_gatt_interface_); - LeAudioHealthStatus::Get()->RemoveStatistics( - test_address0, bluetooth::groups::kGroupUnknown); + LeAudioHealthStatus::Get()->RemoveStatistics(test_address0, bluetooth::groups::kGroupUnknown); } TEST_F(UnicastTestHealthStatus, ConnectOneEarbudNoCas_withHealthStatus) { const RawAddress test_address0 = GetTestAddress(0); uint16_t conn_id = 1; - SetSampleDatabaseEarbudsValid( - conn_id, test_address0, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, - default_channel_cnt, 0x0004, - /* source sample freq 16khz */ true, /*add_csis*/ - false, /*add_cas*/ - true, /*add_pacs*/ - default_ase_cnt /*add_ascs*/); + SetSampleDatabaseEarbudsValid(conn_id, test_address0, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, + default_channel_cnt, 0x0004, + /* source sample freq 16khz */ true, /*add_csis*/ + false, /*add_cas*/ + true, /*add_pacs*/ + default_ase_cnt /*add_ascs*/); EXPECT_CALL(mock_audio_hal_client_callbacks_, - OnHealthBasedRecommendationAction( - test_address0, LeAudioHealthBasedAction::DISABLE)) - .Times(0); + OnHealthBasedRecommendationAction(test_address0, LeAudioHealthBasedAction::DISABLE)) + .Times(0); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); ConnectLeAudio(test_address0); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); - LeAudioHealthStatus::Get()->RemoveStatistics( - test_address0, bluetooth::groups::kGroupUnknown); + LeAudioHealthStatus::Get()->RemoveStatistics(test_address0, bluetooth::groups::kGroupUnknown); } TEST_F(UnicastTestHealthStatus, ConnectOneEarbudNoCsis_withHealthStatus) { const RawAddress test_address0 = GetTestAddress(0); - SetSampleDatabaseEarbudsValid( - 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, - default_channel_cnt, 0x0004, - /* source sample freq 16khz */ false, /*add_csis*/ - true, /*add_cas*/ - true, /*add_pacs*/ - default_ase_cnt /*add_ascs*/); - EXPECT_CALL(mock_audio_hal_client_callbacks_, - OnHealthBasedRecommendationAction( - test_address0, LeAudioHealthBasedAction::DISABLE)) - .Times(0); + SetSampleDatabaseEarbudsValid(1, test_address0, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, + default_channel_cnt, 0x0004, + /* source sample freq 16khz */ false, /*add_csis*/ + true, /*add_cas*/ + true, /*add_pacs*/ + default_ase_cnt /*add_ascs*/); + EXPECT_CALL(mock_audio_hal_client_callbacks_, + OnHealthBasedRecommendationAction(test_address0, LeAudioHealthBasedAction::DISABLE)) + .Times(0); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); ConnectLeAudio(test_address0); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); - LeAudioHealthStatus::Get()->RemoveStatistics( - test_address0, bluetooth::groups::kGroupUnknown); + LeAudioHealthStatus::Get()->RemoveStatistics(test_address0, bluetooth::groups::kGroupUnknown); } -TEST_F(UnicastTestHealthStatus, - ConnectOneEarbudWithInvalidCsis_withHealthStatus) { +TEST_F(UnicastTestHealthStatus, ConnectOneEarbudWithInvalidCsis_withHealthStatus) { const RawAddress test_address0 = GetTestAddress(0); - SetSampleDatabaseEarbudsValid( - 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, - default_channel_cnt, 0x0004, - /* source sample freq 16khz */ true, /*add_csis*/ - true, /*add_cas*/ - true, /*add_pacs*/ - default_ase_cnt /*add_ascs*/); + SetSampleDatabaseEarbudsValid(1, test_address0, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, + default_channel_cnt, 0x0004, + /* source sample freq 16khz */ true, /*add_csis*/ + true, /*add_cas*/ + true, /*add_pacs*/ + default_ase_cnt /*add_ascs*/); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::DISCONNECTED, test_address0)) - .Times(1); + .Times(1); EXPECT_CALL(mock_audio_hal_client_callbacks_, - OnHealthBasedRecommendationAction( - test_address0, LeAudioHealthBasedAction::DISABLE)) - .Times(1); + OnHealthBasedRecommendationAction(test_address0, LeAudioHealthBasedAction::DISABLE)) + .Times(1); EXPECT_CALL(mock_gatt_interface_, Close(_)).Times(1); // Report working CSIS - ON_CALL(mock_csis_client_module_, IsCsisClientRunning()) - .WillByDefault(Return(true)); + ON_CALL(mock_csis_client_module_, IsCsisClientRunning()).WillByDefault(Return(true)); /* Make sure Group has not knowledge about the device */ ON_CALL(mock_groups_module_, GetGroupId(_, _)) - .WillByDefault([](const RawAddress& addr, bluetooth::Uuid uuid) { - return bluetooth::groups::kGroupUnknown; - }); + .WillByDefault([](const RawAddress& addr, bluetooth::Uuid uuid) { + return bluetooth::groups::kGroupUnknown; + }); ConnectLeAudio(test_address0); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_gatt_interface_); Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); - LeAudioHealthStatus::Get()->RemoveStatistics( - test_address0, bluetooth::groups::kGroupUnknown); + LeAudioHealthStatus::Get()->RemoveStatistics(test_address0, bluetooth::groups::kGroupUnknown); } TEST_F(UnicastTestHealthStatus, ConnectOneEarbudDisable_withHealthStatus) { const RawAddress test_address0 = GetTestAddress(0); int conn_id = 1; - SetSampleDatabaseEarbudsValid( - conn_id, test_address0, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, - default_channel_cnt, 0x0004, false); + SetSampleDatabaseEarbudsValid(conn_id, test_address0, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, + default_channel_cnt, 0x0004, false); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); ConnectLeAudio(test_address0); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); LeAudioClient::Get()->GroupSetActive(group_id_); - auto device = std::make_shared( - test_address0, DeviceConnectState::DISCONNECTED); + auto device = std::make_shared(test_address0, DeviceConnectState::DISCONNECTED); group_->AddNode(device); SyncOnMainLoop(); @@ -3403,55 +3148,45 @@ TEST_F(UnicastTestHealthStatus, ConnectOneEarbudDisable_withHealthStatus) { /* Inject stream error */ EXPECT_CALL(mock_audio_hal_client_callbacks_, - OnHealthBasedGroupRecommendationAction( - group_id_, LeAudioHealthBasedAction::DISABLE)) - .Times(1); - health_status->AddStatisticForGroup( - group_, LeAudioHealthGroupStatType::STREAM_CREATE_CIS_FAILED); - health_status->AddStatisticForGroup( - group_, LeAudioHealthGroupStatType::STREAM_CREATE_CIS_FAILED); + OnHealthBasedGroupRecommendationAction(group_id_, LeAudioHealthBasedAction::DISABLE)) + .Times(1); + health_status->AddStatisticForGroup(group_, LeAudioHealthGroupStatType::STREAM_CREATE_CIS_FAILED); + health_status->AddStatisticForGroup(group_, LeAudioHealthGroupStatType::STREAM_CREATE_CIS_FAILED); /* Do not act on disconnect */ ON_CALL(mock_gatt_interface_, Close(_)).WillByDefault(DoAll(Return())); - ON_CALL(mock_btm_interface_, AclDisconnectFromHandle(_, _)) - .WillByDefault(DoAll(Return())); + ON_CALL(mock_btm_interface_, AclDisconnectFromHandle(_, _)).WillByDefault(DoAll(Return())); state_machine_callbacks_->OnStateTransitionTimeout(group_id_); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); EXPECT_CALL(mock_audio_hal_client_callbacks_, - OnHealthBasedGroupRecommendationAction( - group_id_, LeAudioHealthBasedAction::DISABLE)) - .Times(0); - health_status->AddStatisticForGroup( - group_, LeAudioHealthGroupStatType::STREAM_CREATE_CIS_FAILED); - health_status->AddStatisticForGroup( - group_, LeAudioHealthGroupStatType::STREAM_CREATE_CIS_FAILED); + OnHealthBasedGroupRecommendationAction(group_id_, LeAudioHealthBasedAction::DISABLE)) + .Times(0); + health_status->AddStatisticForGroup(group_, LeAudioHealthGroupStatType::STREAM_CREATE_CIS_FAILED); + health_status->AddStatisticForGroup(group_, LeAudioHealthGroupStatType::STREAM_CREATE_CIS_FAILED); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); } -TEST_F(UnicastTestHealthStatus, - ConnectOneEarbudConsiderDisabling_withHealthStatus) { +TEST_F(UnicastTestHealthStatus, ConnectOneEarbudConsiderDisabling_withHealthStatus) { const RawAddress test_address0 = GetTestAddress(0); int conn_id = 1; - SetSampleDatabaseEarbudsValid( - conn_id, test_address0, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, - default_channel_cnt, 0x0004, false); + SetSampleDatabaseEarbudsValid(conn_id, test_address0, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, + default_channel_cnt, 0x0004, false); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); ConnectLeAudio(test_address0); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); LeAudioClient::Get()->GroupSetActive(group_id_); - auto device = std::make_shared( - test_address0, DeviceConnectState::DISCONNECTED); + auto device = std::make_shared(test_address0, DeviceConnectState::DISCONNECTED); group_->AddNode(device); SyncOnMainLoop(); @@ -3459,45 +3194,38 @@ TEST_F(UnicastTestHealthStatus, /* Inject stream success and error */ EXPECT_CALL(mock_audio_hal_client_callbacks_, - OnHealthBasedGroupRecommendationAction( - group_id_, LeAudioHealthBasedAction::CONSIDER_DISABLING)) - .Times(1); - health_status->AddStatisticForGroup( - group_, LeAudioHealthGroupStatType::STREAM_CREATE_SUCCESS); - health_status->AddStatisticForGroup( - group_, LeAudioHealthGroupStatType::STREAM_CREATE_CIS_FAILED); - health_status->AddStatisticForGroup( - group_, LeAudioHealthGroupStatType::STREAM_CREATE_CIS_FAILED); + OnHealthBasedGroupRecommendationAction(group_id_, + LeAudioHealthBasedAction::CONSIDER_DISABLING)) + .Times(1); + health_status->AddStatisticForGroup(group_, LeAudioHealthGroupStatType::STREAM_CREATE_SUCCESS); + health_status->AddStatisticForGroup(group_, LeAudioHealthGroupStatType::STREAM_CREATE_CIS_FAILED); + health_status->AddStatisticForGroup(group_, LeAudioHealthGroupStatType::STREAM_CREATE_CIS_FAILED); /* Do not act on disconnect */ ON_CALL(mock_gatt_interface_, Close(_)).WillByDefault(DoAll(Return())); - ON_CALL(mock_btm_interface_, AclDisconnectFromHandle(_, _)) - .WillByDefault(DoAll(Return())); + ON_CALL(mock_btm_interface_, AclDisconnectFromHandle(_, _)).WillByDefault(DoAll(Return())); state_machine_callbacks_->OnStateTransitionTimeout(group_id_); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); - EXPECT_CALL(mock_audio_hal_client_callbacks_, - OnHealthBasedGroupRecommendationAction( - 1, LeAudioHealthBasedAction::CONSIDER_DISABLING)) - .Times(0); - health_status->AddStatisticForGroup( - group_, LeAudioHealthGroupStatType::STREAM_CREATE_CIS_FAILED); - health_status->AddStatisticForGroup( - group_, LeAudioHealthGroupStatType::STREAM_CREATE_CIS_FAILED); + EXPECT_CALL( + mock_audio_hal_client_callbacks_, + OnHealthBasedGroupRecommendationAction(1, LeAudioHealthBasedAction::CONSIDER_DISABLING)) + .Times(0); + health_status->AddStatisticForGroup(group_, LeAudioHealthGroupStatType::STREAM_CREATE_CIS_FAILED); + health_status->AddStatisticForGroup(group_, LeAudioHealthGroupStatType::STREAM_CREATE_CIS_FAILED); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); } TEST_F(UnicastTest, ConnectDisconnectOneEarbud) { const RawAddress test_address0 = GetTestAddress(0); - SetSampleDatabaseEarbudsValid(1, test_address0, - codec_spec_conf::kLeAudioLocationStereo, + SetSampleDatabaseEarbudsValid(1, test_address0, codec_spec_conf::kLeAudioLocationStereo, codec_spec_conf::kLeAudioLocationStereo); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); ConnectLeAudio(test_address0); DisconnectLeAudioWithAclClose(test_address0, 1); } @@ -3505,12 +3233,11 @@ TEST_F(UnicastTest, ConnectDisconnectOneEarbud) { TEST_F(UnicastTest, ConnectRemoteServiceDiscoveryCompleteBeforeEncryption) { const RawAddress test_address0 = GetTestAddress(0); uint16_t conn_id = 1; - SetSampleDatabaseEarbudsValid(conn_id, test_address0, - codec_spec_conf::kLeAudioLocationStereo, + SetSampleDatabaseEarbudsValid(conn_id, test_address0, codec_spec_conf::kLeAudioLocationStereo, codec_spec_conf::kLeAudioLocationStereo); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(0); + .Times(0); ConnectLeAudio(test_address0, false); InjectSearchCompleteEvent(conn_id); @@ -3519,9 +3246,9 @@ TEST_F(UnicastTest, ConnectRemoteServiceDiscoveryCompleteBeforeEncryption) { EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); ON_CALL(mock_btm_interface_, BTM_IsEncrypted(test_address0, _)) - .WillByDefault(DoAll(Return(true))); + .WillByDefault(DoAll(Return(true))); InjectEncryptionChangedEvent(test_address0); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); @@ -3530,24 +3257,22 @@ TEST_F(UnicastTest, ConnectRemoteServiceDiscoveryCompleteBeforeEncryption) { TEST_F(UnicastTest, DisconnectWhenLinkKeyIsGone) { const RawAddress test_address0 = GetTestAddress(0); uint16_t conn_id = 1; - SetSampleDatabaseEarbudsValid(conn_id, test_address0, - codec_spec_conf::kLeAudioLocationStereo, + SetSampleDatabaseEarbudsValid(conn_id, test_address0, codec_spec_conf::kLeAudioLocationStereo, codec_spec_conf::kLeAudioLocationStereo); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::DISCONNECTED, test_address0)) - .Times(1); + .Times(1); ON_CALL(mock_btm_interface_, BTM_IsEncrypted(test_address0, _)) - .WillByDefault(DoAll(Return(false))); + .WillByDefault(DoAll(Return(false))); ON_CALL(mock_btm_interface_, SetEncryption(test_address0, _, _, _, _)) - .WillByDefault(Return(BTM_ERR_KEY_MISSING)); + .WillByDefault(Return(BTM_ERR_KEY_MISSING)); EXPECT_CALL(mock_gatt_interface_, Close(conn_id)).Times(1); - do_in_main_thread( - FROM_HERE, - base::BindOnce(&LeAudioClient::Connect, - base::Unretained(LeAudioClient::Get()), test_address0)); + do_in_main_thread(FROM_HERE, + base::BindOnce(&LeAudioClient::Connect, base::Unretained(LeAudioClient::Get()), + test_address0)); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_btm_interface_); @@ -3557,25 +3282,22 @@ TEST_F(UnicastTest, DisconnectWhenLinkKeyIsGone) { /* same as above case except the disconnect is initiated by remote */ TEST_F(UnicastTest, ConnectRemoteDisconnectOneEarbud) { const RawAddress test_address0 = GetTestAddress(0); - SetSampleDatabaseEarbudsValid(1, test_address0, - codec_spec_conf::kLeAudioLocationStereo, + SetSampleDatabaseEarbudsValid(1, test_address0, codec_spec_conf::kLeAudioLocationStereo, codec_spec_conf::kLeAudioLocationStereo); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); ConnectLeAudio(test_address0); Mock::VerifyAndClearExpectations(&mock_gatt_interface_); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::DISCONNECTED, test_address0)) - .Times(1); + .Times(1); /* Make sure when remote device disconnects us, TA is used */ - EXPECT_CALL(mock_gatt_interface_, CancelOpen(gatt_if, test_address0, _)) - .Times(1); + EXPECT_CALL(mock_gatt_interface_, CancelOpen(gatt_if, test_address0, _)).Times(1); EXPECT_CALL(mock_gatt_interface_, - Open(gatt_if, test_address0, - BTM_BLE_BKG_CONNECT_TARGETED_ANNOUNCEMENTS, _)) - .Times(1); + Open(gatt_if, test_address0, BTM_BLE_BKG_CONNECT_TARGETED_ANNOUNCEMENTS, _)) + .Times(1); InjectDisconnectedEvent(1, GATT_CONN_TERMINATE_PEER_USER); SyncOnMainLoop(); @@ -3584,17 +3306,15 @@ TEST_F(UnicastTest, ConnectRemoteDisconnectOneEarbud) { EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); /* When reconnected, we always remove background connect, as we do not track * which type (allow list or TA) was used and then make sure the TA is used. */ - EXPECT_CALL(mock_gatt_interface_, CancelOpen(gatt_if, test_address0, _)) - .Times(1); + EXPECT_CALL(mock_gatt_interface_, CancelOpen(gatt_if, test_address0, _)).Times(1); EXPECT_CALL(mock_gatt_interface_, - Open(gatt_if, test_address0, - BTM_BLE_BKG_CONNECT_TARGETED_ANNOUNCEMENTS, _)) - .Times(1); + Open(gatt_if, test_address0, BTM_BLE_BKG_CONNECT_TARGETED_ANNOUNCEMENTS, _)) + .Times(1); /* For background connect, test needs to Inject Connected Event */ InjectConnectedEvent(test_address0, 1); @@ -3605,25 +3325,22 @@ TEST_F(UnicastTest, ConnectRemoteDisconnectOneEarbud) { /* same as above case except the disconnect is initiated by remote */ TEST_F(UnicastTest, ConnectRemoteDisconnectOnTimeoutOneEarbud) { const RawAddress test_address0 = GetTestAddress(0); - SetSampleDatabaseEarbudsValid(1, test_address0, - codec_spec_conf::kLeAudioLocationStereo, + SetSampleDatabaseEarbudsValid(1, test_address0, codec_spec_conf::kLeAudioLocationStereo, codec_spec_conf::kLeAudioLocationStereo); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); ConnectLeAudio(test_address0); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::DISCONNECTED, test_address0)) - .Times(1); + .Times(1); /* Remove default action on the direct connect */ - ON_CALL(mock_gatt_interface_, Open(_, _, BTM_BLE_DIRECT_CONNECTION, _)) - .WillByDefault(Return()); + ON_CALL(mock_gatt_interface_, Open(_, _, BTM_BLE_DIRECT_CONNECTION, _)).WillByDefault(Return()); /* For remote disconnection, expect stack to try background re-connect */ - EXPECT_CALL(mock_gatt_interface_, - Open(gatt_if, test_address0, BTM_BLE_DIRECT_CONNECTION, _)) - .Times(1); + EXPECT_CALL(mock_gatt_interface_, Open(gatt_if, test_address0, BTM_BLE_DIRECT_CONNECTION, _)) + .Times(1); InjectDisconnectedEvent(1, GATT_CONN_TIMEOUT); SyncOnMainLoop(); @@ -3632,7 +3349,7 @@ TEST_F(UnicastTest, ConnectRemoteDisconnectOnTimeoutOneEarbud) { EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); /* For background connect, test needs to Inject Connected Event */ InjectConnectedEvent(test_address0, 1); @@ -3644,40 +3361,31 @@ TEST_F(UnicastTest, ConnectTwoEarbudsCsisGrouped) { int group_id = 2; // Report working CSIS - ON_CALL(mock_csis_client_module_, IsCsisClientRunning()) - .WillByDefault(Return(true)); + ON_CALL(mock_csis_client_module_, IsCsisClientRunning()).WillByDefault(Return(true)); // First earbud const RawAddress test_address0 = GetTestAddress(0); - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, true)) - .Times(1); - ConnectCsisDevice(test_address0, 1 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontLeft, - codec_spec_conf::kLeAudioLocationFrontLeft, group_size, - group_id, 1 /* rank*/); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, true)).Times(1); + ConnectCsisDevice(test_address0, 1 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontLeft, + codec_spec_conf::kLeAudioLocationFrontLeft, group_size, group_id, 1 /* rank*/); // Second earbud const RawAddress test_address1 = GetTestAddress(1); - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, true)) - .Times(1); - ConnectCsisDevice(test_address1, 2 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontRight, - codec_spec_conf::kLeAudioLocationFrontRight, group_size, - group_id, 2 /* rank*/, true /*connect_through_csis*/); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, true)).Times(1); + ConnectCsisDevice(test_address1, 2 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontRight, + codec_spec_conf::kLeAudioLocationFrontRight, group_size, group_id, 2 /* rank*/, + true /*connect_through_csis*/); Mock::VerifyAndClearExpectations(&mock_btif_storage_); /* for Target announcements AutoConnect is always there, until * device is removed */ - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, false)) - .Times(0); - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, false)) - .Times(0); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, false)).Times(0); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, false)).Times(0); // Verify grouping information - std::vector devs = - LeAudioClient::Get()->GetGroupDevices(group_id); + std::vector devs = LeAudioClient::Get()->GetGroupDevices(group_id); ASSERT_NE(std::find(devs.begin(), devs.end(), test_address0), devs.end()); ASSERT_NE(std::find(devs.begin(), devs.end(), test_address1), devs.end()); @@ -3690,42 +3398,33 @@ TEST_F(UnicastTest, ConnectTwoEarbudsCsisGroupUnknownAtConnect) { uint8_t group_id = 2; // Report working CSIS - ON_CALL(mock_csis_client_module_, IsCsisClientRunning()) - .WillByDefault(Return(true)); + ON_CALL(mock_csis_client_module_, IsCsisClientRunning()).WillByDefault(Return(true)); // First earbud connects without known grouping const RawAddress test_address0 = GetTestAddress(0); - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, true)) - .Times(1); - ConnectCsisDevice(test_address0, 1 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontLeft, - codec_spec_conf::kLeAudioLocationFrontLeft, group_size, - group_id, 1 /* rank*/); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, true)).Times(1); + ConnectCsisDevice(test_address0, 1 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontLeft, + codec_spec_conf::kLeAudioLocationFrontLeft, group_size, group_id, 1 /* rank*/); // Second earbud const RawAddress test_address1 = GetTestAddress(1); - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, true)) - .Times(1); - ConnectCsisDevice(test_address1, 2 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontRight, - codec_spec_conf::kLeAudioLocationFrontRight, group_size, - group_id, 2 /* rank*/, true /*connect_through_csis*/); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, true)).Times(1); + ConnectCsisDevice(test_address1, 2 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontRight, + codec_spec_conf::kLeAudioLocationFrontRight, group_size, group_id, 2 /* rank*/, + true /*connect_through_csis*/); Mock::VerifyAndClearExpectations(&mock_btif_storage_); // Verify grouping information - std::vector devs = - LeAudioClient::Get()->GetGroupDevices(group_id); + std::vector devs = LeAudioClient::Get()->GetGroupDevices(group_id); ASSERT_NE(std::find(devs.begin(), devs.end(), test_address0), devs.end()); ASSERT_NE(std::find(devs.begin(), devs.end(), test_address1), devs.end()); /* for Target announcements AutoConnect is always there, until * device is removed */ - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, false)) - .Times(0); - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, false)) - .Times(0); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, false)).Times(0); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, false)).Times(0); DisconnectLeAudioWithAclClose(test_address0, 1); DisconnectLeAudioWithAclClose(test_address1, 2); } @@ -3738,29 +3437,27 @@ TEST_F(UnicastTestNoInit, ConnectFailedDueToInvalidParameters) { /* Prepare mock to not inject connect event so the device can stay in * CONNECTING state*/ ON_CALL(mock_gatt_interface_, Open(_, _, BTM_BLE_DIRECT_CONNECTION, false)) - .WillByDefault(DoAll(Return())); + .WillByDefault(DoAll(Return())); const RawAddress test_address0 = GetTestAddress(0); - SetSampleDatabaseEarbudsValid( - 1, test_address0, codec_spec_conf::kLeAudioLocationFrontLeft, - codec_spec_conf::kLeAudioLocationFrontLeft, default_channel_cnt, - default_channel_cnt, 0x0004, - /* source sample freq 16khz */ true, /*add_csis*/ - true, /*add_cas*/ - true, /*add_pacs*/ - default_ase_cnt, /*add_ascs_cnt*/ - group_size, 1); + SetSampleDatabaseEarbudsValid(1, test_address0, codec_spec_conf::kLeAudioLocationFrontLeft, + codec_spec_conf::kLeAudioLocationFrontLeft, default_channel_cnt, + default_channel_cnt, 0x0004, + /* source sample freq 16khz */ true, /*add_csis*/ + true, /*add_cas*/ + true, /*add_pacs*/ + default_ase_cnt, /*add_ascs_cnt*/ + group_size, 1); const RawAddress test_address1 = GetTestAddress(1); - SetSampleDatabaseEarbudsValid( - 2, test_address1, codec_spec_conf::kLeAudioLocationFrontRight, - codec_spec_conf::kLeAudioLocationFrontRight, default_channel_cnt, - default_channel_cnt, 0x0004, - /* source sample freq 16khz */ true, /*add_csis*/ - true, /*add_cas*/ - true, /*add_pacs*/ - default_ase_cnt, /*add_ascs_cnt*/ - group_size, 2); + SetSampleDatabaseEarbudsValid(2, test_address1, codec_spec_conf::kLeAudioLocationFrontRight, + codec_spec_conf::kLeAudioLocationFrontRight, default_channel_cnt, + default_channel_cnt, 0x0004, + /* source sample freq 16khz */ true, /*add_csis*/ + true, /*add_cas*/ + true, /*add_pacs*/ + default_ase_cnt, /*add_ascs_cnt*/ + group_size, 2); // Load devices from the storage when storage API is called bool autoconnect = true; @@ -3779,61 +3476,51 @@ TEST_F(UnicastTestNoInit, ConnectFailedDueToInvalidParameters) { LeAudioClient::GetSinkPacsForStorage(test_address0, snk_pacs); EXPECT_CALL(mock_storage_load, Call()).WillOnce([&]() { + do_in_main_thread(FROM_HERE, base::Bind(&LeAudioClient::AddFromStorage, test_address0, + autoconnect, codec_spec_conf::kLeAudioLocationFrontLeft, + codec_spec_conf::kLeAudioLocationFrontLeft, 0xff, 0xff, + std::move(handles), std::move(snk_pacs), + std::move(src_pacs), std::move(ases))); do_in_main_thread( - FROM_HERE, - base::Bind(&LeAudioClient::AddFromStorage, test_address0, autoconnect, - codec_spec_conf::kLeAudioLocationFrontLeft, - codec_spec_conf::kLeAudioLocationFrontLeft, 0xff, 0xff, - std::move(handles), std::move(snk_pacs), std::move(src_pacs), - std::move(ases))); - do_in_main_thread( - FROM_HERE, - base::Bind(&LeAudioClient::AddFromStorage, test_address1, autoconnect, - codec_spec_conf::kLeAudioLocationFrontRight, - codec_spec_conf::kLeAudioLocationFrontRight, 0xff, 0xff, - std::move(handles), std::move(snk_pacs), std::move(src_pacs), - std::move(ases))); + FROM_HERE, + base::Bind(&LeAudioClient::AddFromStorage, test_address1, autoconnect, + codec_spec_conf::kLeAudioLocationFrontRight, + codec_spec_conf::kLeAudioLocationFrontRight, 0xff, 0xff, std::move(handles), + std::move(snk_pacs), std::move(src_pacs), std::move(ases))); }); // Expect stored device0 to connect automatically (first directed connection ) - EXPECT_CALL(mock_gatt_interface_, - Open(gatt_if, test_address0, BTM_BLE_DIRECT_CONNECTION, _)) - .Times(1); + EXPECT_CALL(mock_gatt_interface_, Open(gatt_if, test_address0, BTM_BLE_DIRECT_CONNECTION, _)) + .Times(1); // Expect stored device1 to connect automatically (first direct connection) - EXPECT_CALL(mock_gatt_interface_, - Open(gatt_if, test_address1, BTM_BLE_DIRECT_CONNECTION, _)) - .Times(1); + EXPECT_CALL(mock_gatt_interface_, Open(gatt_if, test_address1, BTM_BLE_DIRECT_CONNECTION, _)) + .Times(1); ON_CALL(mock_btm_interface_, BTM_IsEncrypted(test_address1, _)) - .WillByDefault(DoAll(Return(true))); + .WillByDefault(DoAll(Return(true))); ON_CALL(mock_btm_interface_, BTM_IsEncrypted(test_address0, _)) - .WillByDefault(DoAll(Return(true))); + .WillByDefault(DoAll(Return(true))); - ON_CALL(mock_groups_module_, GetGroupId(_, _)) - .WillByDefault(DoAll(Return(group_id))); + ON_CALL(mock_groups_module_, GetGroupId(_, _)).WillByDefault(DoAll(Return(group_id))); - ON_CALL(mock_btm_interface_, - GetSecurityFlagsByTransport(test_address0, NotNull(), _)) - .WillByDefault( - DoAll(SetArgPointee<1>(BTM_SEC_FLAG_ENCRYPTED), Return(true))); + ON_CALL(mock_btm_interface_, GetSecurityFlagsByTransport(test_address0, NotNull(), _)) + .WillByDefault(DoAll(SetArgPointee<1>(BTM_SEC_FLAG_ENCRYPTED), Return(true))); - std::vector<::bluetooth::le_audio::btle_audio_codec_config_t> - framework_encode_preference; + std::vector<::bluetooth::le_audio::btle_audio_codec_config_t> framework_encode_preference; // Initialize BtaAppRegisterCallback app_register_callback; ON_CALL(mock_gatt_interface_, AppRegister(_, _, _)) - .WillByDefault(DoAll(SaveArg<0>(&gatt_callback), - SaveArg<1>(&app_register_callback))); + .WillByDefault(DoAll(SaveArg<0>(&gatt_callback), SaveArg<1>(&app_register_callback))); LeAudioClient::Initialize( - &mock_audio_hal_client_callbacks_, - base::Bind([](MockFunction* foo) { foo->Call(); }, - &mock_storage_load), - base::Bind([](MockFunction* foo) { return foo->Call(); }, - &mock_hal_2_1_verifier), - framework_encode_preference); - if (app_register_callback) app_register_callback.Run(gatt_if, GATT_SUCCESS); + &mock_audio_hal_client_callbacks_, + base::Bind([](MockFunction* foo) { foo->Call(); }, &mock_storage_load), + base::Bind([](MockFunction* foo) { return foo->Call(); }, &mock_hal_2_1_verifier), + framework_encode_preference); + if (app_register_callback) { + app_register_callback.Run(gatt_if, GATT_SUCCESS); + } // We need to wait for the storage callback before verifying stuff SyncOnMainLoop(); @@ -3843,14 +3530,12 @@ TEST_F(UnicastTestNoInit, ConnectFailedDueToInvalidParameters) { // Simulate connect parameters are invalid and phone does not fallback // to background connect. EXPECT_CALL(mock_gatt_interface_, - Open(gatt_if, test_address0, - BTM_BLE_BKG_CONNECT_TARGETED_ANNOUNCEMENTS, _)) - .Times(0); + Open(gatt_if, test_address0, BTM_BLE_BKG_CONNECT_TARGETED_ANNOUNCEMENTS, _)) + .Times(0); EXPECT_CALL(mock_gatt_interface_, - Open(gatt_if, test_address1, - BTM_BLE_BKG_CONNECT_TARGETED_ANNOUNCEMENTS, _)) - .Times(0); + Open(gatt_if, test_address1, BTM_BLE_BKG_CONNECT_TARGETED_ANNOUNCEMENTS, _)) + .Times(0); // Devices not found InjectConnectedEvent(test_address0, 0, GATT_ILLEGAL_PARAMETER); @@ -3871,91 +3556,80 @@ TEST_F(UnicastTestNoInit, LoadStoredEarbudsBroakenStorage) { /* Prepare mock to not inject connect event so the device can stay in * CONNECTING state*/ ON_CALL(mock_gatt_interface_, Open(_, _, BTM_BLE_DIRECT_CONNECTION, false)) - .WillByDefault(DoAll(Return())); + .WillByDefault(DoAll(Return())); const RawAddress test_address0 = GetTestAddress(0); - SetSampleDatabaseEarbudsValid( - 1, test_address0, codec_spec_conf::kLeAudioLocationFrontLeft, - codec_spec_conf::kLeAudioLocationFrontLeft, default_channel_cnt, - default_channel_cnt, 0x0004, - /* source sample freq 16khz */ true, /*add_csis*/ - true, /*add_cas*/ - true, /*add_pacs*/ - default_ase_cnt, /*add_ascs_cnt*/ - group_size, 1); + SetSampleDatabaseEarbudsValid(1, test_address0, codec_spec_conf::kLeAudioLocationFrontLeft, + codec_spec_conf::kLeAudioLocationFrontLeft, default_channel_cnt, + default_channel_cnt, 0x0004, + /* source sample freq 16khz */ true, /*add_csis*/ + true, /*add_cas*/ + true, /*add_pacs*/ + default_ase_cnt, /*add_ascs_cnt*/ + group_size, 1); const RawAddress test_address1 = GetTestAddress(1); - SetSampleDatabaseEarbudsValid( - 2, test_address1, codec_spec_conf::kLeAudioLocationFrontRight, - codec_spec_conf::kLeAudioLocationFrontRight, default_channel_cnt, - default_channel_cnt, 0x0004, - /* source sample freq 16khz */ true, /*add_csis*/ - true, /*add_cas*/ - true, /*add_pacs*/ - default_ase_cnt, /*add_ascs_cnt*/ - group_size, 2); + SetSampleDatabaseEarbudsValid(2, test_address1, codec_spec_conf::kLeAudioLocationFrontRight, + codec_spec_conf::kLeAudioLocationFrontRight, default_channel_cnt, + default_channel_cnt, 0x0004, + /* source sample freq 16khz */ true, /*add_csis*/ + true, /*add_cas*/ + true, /*add_pacs*/ + default_ase_cnt, /*add_ascs_cnt*/ + group_size, 2); // Load devices from the storage when storage API is called bool autoconnect = true; std::vector empty_buf; EXPECT_CALL(mock_storage_load, Call()).WillOnce([&]() { - do_in_main_thread( - FROM_HERE, - base::BindOnce(&LeAudioClient::AddFromStorage, test_address0, - autoconnect, codec_spec_conf::kLeAudioLocationFrontLeft, - codec_spec_conf::kLeAudioLocationFrontLeft, 0xff, 0xff, - std::move(empty_buf), std::move(empty_buf), - std::move(empty_buf), std::move(empty_buf))); - do_in_main_thread( - FROM_HERE, - base::BindOnce(&LeAudioClient::AddFromStorage, test_address1, - autoconnect, codec_spec_conf::kLeAudioLocationFrontRight, - codec_spec_conf::kLeAudioLocationFrontRight, 0xff, 0xff, - std::move(empty_buf), std::move(empty_buf), - std::move(empty_buf), std::move(empty_buf))); + do_in_main_thread(FROM_HERE, + base::BindOnce(&LeAudioClient::AddFromStorage, test_address0, autoconnect, + codec_spec_conf::kLeAudioLocationFrontLeft, + codec_spec_conf::kLeAudioLocationFrontLeft, 0xff, 0xff, + std::move(empty_buf), std::move(empty_buf), + std::move(empty_buf), std::move(empty_buf))); + do_in_main_thread(FROM_HERE, + base::BindOnce(&LeAudioClient::AddFromStorage, test_address1, autoconnect, + codec_spec_conf::kLeAudioLocationFrontRight, + codec_spec_conf::kLeAudioLocationFrontRight, 0xff, 0xff, + std::move(empty_buf), std::move(empty_buf), + std::move(empty_buf), std::move(empty_buf))); SyncOnMainLoop(); }); // Expect stored device0 to connect automatically (first directed connection ) - EXPECT_CALL(mock_gatt_interface_, - Open(gatt_if, test_address0, BTM_BLE_DIRECT_CONNECTION, _)) - .Times(1); + EXPECT_CALL(mock_gatt_interface_, Open(gatt_if, test_address0, BTM_BLE_DIRECT_CONNECTION, _)) + .Times(1); // Expect stored device1 to connect automatically (first direct connection) - EXPECT_CALL(mock_gatt_interface_, - Open(gatt_if, test_address1, BTM_BLE_DIRECT_CONNECTION, _)) - .Times(1); + EXPECT_CALL(mock_gatt_interface_, Open(gatt_if, test_address1, BTM_BLE_DIRECT_CONNECTION, _)) + .Times(1); ON_CALL(mock_btm_interface_, BTM_IsEncrypted(test_address1, _)) - .WillByDefault(DoAll(Return(true))); + .WillByDefault(DoAll(Return(true))); ON_CALL(mock_btm_interface_, BTM_IsEncrypted(test_address0, _)) - .WillByDefault(DoAll(Return(true))); + .WillByDefault(DoAll(Return(true))); - ON_CALL(mock_groups_module_, GetGroupId(_, _)) - .WillByDefault(DoAll(Return(group_id))); + ON_CALL(mock_groups_module_, GetGroupId(_, _)).WillByDefault(DoAll(Return(group_id))); - ON_CALL(mock_btm_interface_, - GetSecurityFlagsByTransport(test_address0, NotNull(), _)) - .WillByDefault( - DoAll(SetArgPointee<1>(BTM_SEC_FLAG_ENCRYPTED), Return(true))); + ON_CALL(mock_btm_interface_, GetSecurityFlagsByTransport(test_address0, NotNull(), _)) + .WillByDefault(DoAll(SetArgPointee<1>(BTM_SEC_FLAG_ENCRYPTED), Return(true))); - std::vector<::bluetooth::le_audio::btle_audio_codec_config_t> - framework_encode_preference; + std::vector<::bluetooth::le_audio::btle_audio_codec_config_t> framework_encode_preference; // Initialize BtaAppRegisterCallback app_register_callback; ON_CALL(mock_gatt_interface_, AppRegister(_, _, _)) - .WillByDefault(DoAll(SaveArg<0>(&gatt_callback), - SaveArg<1>(&app_register_callback))); + .WillByDefault(DoAll(SaveArg<0>(&gatt_callback), SaveArg<1>(&app_register_callback))); LeAudioClient::Initialize( - &mock_audio_hal_client_callbacks_, - base::Bind([](MockFunction* foo) { foo->Call(); }, - &mock_storage_load), - base::Bind([](MockFunction* foo) { return foo->Call(); }, - &mock_hal_2_1_verifier), - framework_encode_preference); - if (app_register_callback) app_register_callback.Run(gatt_if, GATT_SUCCESS); + &mock_audio_hal_client_callbacks_, + base::Bind([](MockFunction* foo) { foo->Call(); }, &mock_storage_load), + base::Bind([](MockFunction* foo) { return foo->Call(); }, &mock_hal_2_1_verifier), + framework_encode_preference); + if (app_register_callback) { + app_register_callback.Run(gatt_if, GATT_SUCCESS); + } // We need to wait for the storage callback before verifying stuff SyncOnMainLoop(); @@ -3965,14 +3639,12 @@ TEST_F(UnicastTestNoInit, LoadStoredEarbudsBroakenStorage) { // Simulate devices are not there and phone fallbacks to targeted // announcements EXPECT_CALL(mock_gatt_interface_, - Open(gatt_if, test_address0, - BTM_BLE_BKG_CONNECT_TARGETED_ANNOUNCEMENTS, _)) - .Times(1); + Open(gatt_if, test_address0, BTM_BLE_BKG_CONNECT_TARGETED_ANNOUNCEMENTS, _)) + .Times(1); EXPECT_CALL(mock_gatt_interface_, - Open(gatt_if, test_address1, - BTM_BLE_BKG_CONNECT_TARGETED_ANNOUNCEMENTS, _)) - .Times(1); + Open(gatt_if, test_address1, BTM_BLE_BKG_CONNECT_TARGETED_ANNOUNCEMENTS, _)) + .Times(1); // Devices not found InjectConnectedEvent(test_address0, 0, GATT_ERROR); @@ -3987,11 +3659,11 @@ TEST_F(UnicastTestNoInit, LoadStoredEarbudsBroakenStorage) { EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address1)) - .Times(1); + .Times(1); /* For background connect, test needs to Inject Connected Event */ InjectConnectedEvent(test_address0, 1); @@ -3999,8 +3671,7 @@ TEST_F(UnicastTestNoInit, LoadStoredEarbudsBroakenStorage) { SyncOnMainLoop(); // Verify if all went well and we got the proper group - std::vector devs = - LeAudioClient::Get()->GetGroupDevices(group_id); + std::vector devs = LeAudioClient::Get()->GetGroupDevices(group_id); ASSERT_NE(std::find(devs.begin(), devs.end(), test_address0), devs.end()); ASSERT_NE(std::find(devs.begin(), devs.end(), test_address1), devs.end()); @@ -4016,29 +3687,27 @@ TEST_F(UnicastTestNoInit, LoadStoredEarbudsCsisGrouped) { /* Prepare mock to not inject connect event so the device can stay in * CONNECTING state*/ ON_CALL(mock_gatt_interface_, Open(_, _, BTM_BLE_DIRECT_CONNECTION, false)) - .WillByDefault(DoAll(Return())); + .WillByDefault(DoAll(Return())); const RawAddress test_address0 = GetTestAddress(0); - SetSampleDatabaseEarbudsValid( - 1, test_address0, codec_spec_conf::kLeAudioLocationFrontLeft, - codec_spec_conf::kLeAudioLocationFrontLeft, default_channel_cnt, - default_channel_cnt, 0x0004, - /* source sample freq 16khz */ true, /*add_csis*/ - true, /*add_cas*/ - true, /*add_pacs*/ - default_ase_cnt, /*add_ascs_cnt*/ - group_size, 1); + SetSampleDatabaseEarbudsValid(1, test_address0, codec_spec_conf::kLeAudioLocationFrontLeft, + codec_spec_conf::kLeAudioLocationFrontLeft, default_channel_cnt, + default_channel_cnt, 0x0004, + /* source sample freq 16khz */ true, /*add_csis*/ + true, /*add_cas*/ + true, /*add_pacs*/ + default_ase_cnt, /*add_ascs_cnt*/ + group_size, 1); const RawAddress test_address1 = GetTestAddress(1); - SetSampleDatabaseEarbudsValid( - 2, test_address1, codec_spec_conf::kLeAudioLocationFrontRight, - codec_spec_conf::kLeAudioLocationFrontRight, default_channel_cnt, - default_channel_cnt, 0x0004, - /* source sample freq 16khz */ true, /*add_csis*/ - true, /*add_cas*/ - true, /*add_pacs*/ - default_ase_cnt, /*add_ascs_cnt*/ - group_size, 2); + SetSampleDatabaseEarbudsValid(2, test_address1, codec_spec_conf::kLeAudioLocationFrontRight, + codec_spec_conf::kLeAudioLocationFrontRight, default_channel_cnt, + default_channel_cnt, 0x0004, + /* source sample freq 16khz */ true, /*add_csis*/ + true, /*add_cas*/ + true, /*add_pacs*/ + default_ase_cnt, /*add_ascs_cnt*/ + group_size, 2); // Load devices from the storage when storage API is called bool autoconnect = true; @@ -4057,62 +3726,53 @@ TEST_F(UnicastTestNoInit, LoadStoredEarbudsCsisGrouped) { LeAudioClient::GetSinkPacsForStorage(test_address0, snk_pacs); EXPECT_CALL(mock_storage_load, Call()).WillOnce([&]() { - do_in_main_thread( - FROM_HERE, - base::BindOnce(&LeAudioClient::AddFromStorage, test_address0, - autoconnect, codec_spec_conf::kLeAudioLocationFrontLeft, - codec_spec_conf::kLeAudioLocationFrontLeft, 0xff, 0xff, - std::move(handles), std::move(snk_pacs), - std::move(src_pacs), std::move(ases))); - do_in_main_thread( - FROM_HERE, - base::BindOnce(&LeAudioClient::AddFromStorage, test_address1, - autoconnect, codec_spec_conf::kLeAudioLocationFrontRight, - codec_spec_conf::kLeAudioLocationFrontRight, 0xff, 0xff, - std::move(handles), std::move(snk_pacs), - std::move(src_pacs), std::move(ases))); + do_in_main_thread(FROM_HERE, + base::BindOnce(&LeAudioClient::AddFromStorage, test_address0, autoconnect, + codec_spec_conf::kLeAudioLocationFrontLeft, + codec_spec_conf::kLeAudioLocationFrontLeft, 0xff, 0xff, + std::move(handles), std::move(snk_pacs), std::move(src_pacs), + std::move(ases))); + do_in_main_thread(FROM_HERE, + base::BindOnce(&LeAudioClient::AddFromStorage, test_address1, autoconnect, + codec_spec_conf::kLeAudioLocationFrontRight, + codec_spec_conf::kLeAudioLocationFrontRight, 0xff, 0xff, + std::move(handles), std::move(snk_pacs), std::move(src_pacs), + std::move(ases))); SyncOnMainLoop(); }); // Expect stored device0 to connect automatically (first directed connection ) - EXPECT_CALL(mock_gatt_interface_, - Open(gatt_if, test_address0, BTM_BLE_DIRECT_CONNECTION, _)) - .Times(1); + EXPECT_CALL(mock_gatt_interface_, Open(gatt_if, test_address0, BTM_BLE_DIRECT_CONNECTION, _)) + .Times(1); // Expect stored device1 to connect automatically (first direct connection) - EXPECT_CALL(mock_gatt_interface_, - Open(gatt_if, test_address1, BTM_BLE_DIRECT_CONNECTION, _)) - .Times(1); + EXPECT_CALL(mock_gatt_interface_, Open(gatt_if, test_address1, BTM_BLE_DIRECT_CONNECTION, _)) + .Times(1); ON_CALL(mock_btm_interface_, BTM_IsEncrypted(test_address1, _)) - .WillByDefault(DoAll(Return(true))); + .WillByDefault(DoAll(Return(true))); ON_CALL(mock_btm_interface_, BTM_IsEncrypted(test_address0, _)) - .WillByDefault(DoAll(Return(true))); + .WillByDefault(DoAll(Return(true))); - ON_CALL(mock_groups_module_, GetGroupId(_, _)) - .WillByDefault(DoAll(Return(group_id))); + ON_CALL(mock_groups_module_, GetGroupId(_, _)).WillByDefault(DoAll(Return(group_id))); - ON_CALL(mock_btm_interface_, - GetSecurityFlagsByTransport(test_address0, NotNull(), _)) - .WillByDefault( - DoAll(SetArgPointee<1>(BTM_SEC_FLAG_ENCRYPTED), Return(true))); + ON_CALL(mock_btm_interface_, GetSecurityFlagsByTransport(test_address0, NotNull(), _)) + .WillByDefault(DoAll(SetArgPointee<1>(BTM_SEC_FLAG_ENCRYPTED), Return(true))); - std::vector<::bluetooth::le_audio::btle_audio_codec_config_t> - framework_encode_preference; + std::vector<::bluetooth::le_audio::btle_audio_codec_config_t> framework_encode_preference; // Initialize BtaAppRegisterCallback app_register_callback; ON_CALL(mock_gatt_interface_, AppRegister(_, _, _)) - .WillByDefault(DoAll(SaveArg<0>(&gatt_callback), - SaveArg<1>(&app_register_callback))); + .WillByDefault(DoAll(SaveArg<0>(&gatt_callback), SaveArg<1>(&app_register_callback))); LeAudioClient::Initialize( - &mock_audio_hal_client_callbacks_, - base::Bind([](MockFunction* foo) { foo->Call(); }, - &mock_storage_load), - base::Bind([](MockFunction* foo) { return foo->Call(); }, - &mock_hal_2_1_verifier), - framework_encode_preference); - if (app_register_callback) app_register_callback.Run(gatt_if, GATT_SUCCESS); + &mock_audio_hal_client_callbacks_, + base::Bind([](MockFunction* foo) { foo->Call(); }, &mock_storage_load), + base::Bind([](MockFunction* foo) { return foo->Call(); }, &mock_hal_2_1_verifier), + framework_encode_preference); + if (app_register_callback) { + app_register_callback.Run(gatt_if, GATT_SUCCESS); + } // We need to wait for the storage callback before verifying stuff SyncOnMainLoop(); @@ -4122,14 +3782,12 @@ TEST_F(UnicastTestNoInit, LoadStoredEarbudsCsisGrouped) { // Simulate devices are not there and phone fallbacks to targeted // announcements EXPECT_CALL(mock_gatt_interface_, - Open(gatt_if, test_address0, - BTM_BLE_BKG_CONNECT_TARGETED_ANNOUNCEMENTS, _)) - .Times(1); + Open(gatt_if, test_address0, BTM_BLE_BKG_CONNECT_TARGETED_ANNOUNCEMENTS, _)) + .Times(1); EXPECT_CALL(mock_gatt_interface_, - Open(gatt_if, test_address1, - BTM_BLE_BKG_CONNECT_TARGETED_ANNOUNCEMENTS, _)) - .Times(1); + Open(gatt_if, test_address1, BTM_BLE_BKG_CONNECT_TARGETED_ANNOUNCEMENTS, _)) + .Times(1); // Devices not found InjectConnectedEvent(test_address0, 0, GATT_ERROR); @@ -4140,11 +3798,11 @@ TEST_F(UnicastTestNoInit, LoadStoredEarbudsCsisGrouped) { EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address1)) - .Times(1); + .Times(1); /* For background connect, test needs to Inject Connected Event */ InjectConnectedEvent(test_address0, 1); @@ -4152,8 +3810,7 @@ TEST_F(UnicastTestNoInit, LoadStoredEarbudsCsisGrouped) { SyncOnMainLoop(); // Verify if all went well and we got the proper group - std::vector devs = - LeAudioClient::Get()->GetGroupDevices(group_id); + std::vector devs = LeAudioClient::Get()->GetGroupDevices(group_id); ASSERT_NE(std::find(devs.begin(), devs.end(), test_address0), devs.end()); ASSERT_NE(std::find(devs.begin(), devs.end(), test_address1), devs.end()); @@ -4169,29 +3826,27 @@ TEST_F(UnicastTestNoInit, ServiceChangedBeforeServiceIsConnected) { /* Prepare mock to not inject connect event so the device can stay in * CONNECTING state*/ ON_CALL(mock_gatt_interface_, Open(_, _, BTM_BLE_DIRECT_CONNECTION, false)) - .WillByDefault(DoAll(Return())); + .WillByDefault(DoAll(Return())); const RawAddress test_address0 = GetTestAddress(0); - SetSampleDatabaseEarbudsValid( - 1, test_address0, codec_spec_conf::kLeAudioLocationFrontLeft, - codec_spec_conf::kLeAudioLocationFrontLeft, default_channel_cnt, - default_channel_cnt, 0x0004, - /* source sample freq 16khz */ true, /*add_csis*/ - true, /*add_cas*/ - true, /*add_pacs*/ - default_ase_cnt, /*add_ascs_cnt*/ - group_size, 1); + SetSampleDatabaseEarbudsValid(1, test_address0, codec_spec_conf::kLeAudioLocationFrontLeft, + codec_spec_conf::kLeAudioLocationFrontLeft, default_channel_cnt, + default_channel_cnt, 0x0004, + /* source sample freq 16khz */ true, /*add_csis*/ + true, /*add_cas*/ + true, /*add_pacs*/ + default_ase_cnt, /*add_ascs_cnt*/ + group_size, 1); const RawAddress test_address1 = GetTestAddress(1); - SetSampleDatabaseEarbudsValid( - 2, test_address1, codec_spec_conf::kLeAudioLocationFrontRight, - codec_spec_conf::kLeAudioLocationFrontRight, default_channel_cnt, - default_channel_cnt, 0x0004, - /* source sample freq 16khz */ true, /*add_csis*/ - true, /*add_cas*/ - true, /*add_pacs*/ - default_ase_cnt, /*add_ascs_cnt*/ - group_size, 2); + SetSampleDatabaseEarbudsValid(2, test_address1, codec_spec_conf::kLeAudioLocationFrontRight, + codec_spec_conf::kLeAudioLocationFrontRight, default_channel_cnt, + default_channel_cnt, 0x0004, + /* source sample freq 16khz */ true, /*add_csis*/ + true, /*add_cas*/ + true, /*add_pacs*/ + default_ase_cnt, /*add_ascs_cnt*/ + group_size, 2); // Load devices from the storage when storage API is called bool autoconnect = true; @@ -4210,62 +3865,53 @@ TEST_F(UnicastTestNoInit, ServiceChangedBeforeServiceIsConnected) { LeAudioClient::GetSinkPacsForStorage(test_address0, snk_pacs); EXPECT_CALL(mock_storage_load, Call()).WillOnce([&]() { - do_in_main_thread( - FROM_HERE, - base::BindOnce(&LeAudioClient::AddFromStorage, test_address0, - autoconnect, codec_spec_conf::kLeAudioLocationFrontLeft, - codec_spec_conf::kLeAudioLocationFrontLeft, 0xff, 0xff, - std::move(handles), std::move(snk_pacs), - std::move(src_pacs), std::move(ases))); - do_in_main_thread( - FROM_HERE, - base::BindOnce(&LeAudioClient::AddFromStorage, test_address1, - autoconnect, codec_spec_conf::kLeAudioLocationFrontRight, - codec_spec_conf::kLeAudioLocationFrontRight, 0xff, 0xff, - std::move(handles), std::move(snk_pacs), - std::move(src_pacs), std::move(ases))); + do_in_main_thread(FROM_HERE, + base::BindOnce(&LeAudioClient::AddFromStorage, test_address0, autoconnect, + codec_spec_conf::kLeAudioLocationFrontLeft, + codec_spec_conf::kLeAudioLocationFrontLeft, 0xff, 0xff, + std::move(handles), std::move(snk_pacs), std::move(src_pacs), + std::move(ases))); + do_in_main_thread(FROM_HERE, + base::BindOnce(&LeAudioClient::AddFromStorage, test_address1, autoconnect, + codec_spec_conf::kLeAudioLocationFrontRight, + codec_spec_conf::kLeAudioLocationFrontRight, 0xff, 0xff, + std::move(handles), std::move(snk_pacs), std::move(src_pacs), + std::move(ases))); SyncOnMainLoop(); }); // Expect stored device0 to connect automatically (first directed connection ) - EXPECT_CALL(mock_gatt_interface_, - Open(gatt_if, test_address0, BTM_BLE_DIRECT_CONNECTION, _)) - .Times(1); + EXPECT_CALL(mock_gatt_interface_, Open(gatt_if, test_address0, BTM_BLE_DIRECT_CONNECTION, _)) + .Times(1); // Expect stored device1 to connect automatically (first direct connection) - EXPECT_CALL(mock_gatt_interface_, - Open(gatt_if, test_address1, BTM_BLE_DIRECT_CONNECTION, _)) - .Times(1); + EXPECT_CALL(mock_gatt_interface_, Open(gatt_if, test_address1, BTM_BLE_DIRECT_CONNECTION, _)) + .Times(1); ON_CALL(mock_btm_interface_, BTM_IsEncrypted(test_address1, _)) - .WillByDefault(DoAll(Return(true))); + .WillByDefault(DoAll(Return(true))); ON_CALL(mock_btm_interface_, BTM_IsEncrypted(test_address0, _)) - .WillByDefault(DoAll(Return(true))); + .WillByDefault(DoAll(Return(true))); - ON_CALL(mock_groups_module_, GetGroupId(_, _)) - .WillByDefault(DoAll(Return(group_id))); + ON_CALL(mock_groups_module_, GetGroupId(_, _)).WillByDefault(DoAll(Return(group_id))); - ON_CALL(mock_btm_interface_, - GetSecurityFlagsByTransport(test_address0, NotNull(), _)) - .WillByDefault( - DoAll(SetArgPointee<1>(BTM_SEC_FLAG_ENCRYPTED), Return(true))); + ON_CALL(mock_btm_interface_, GetSecurityFlagsByTransport(test_address0, NotNull(), _)) + .WillByDefault(DoAll(SetArgPointee<1>(BTM_SEC_FLAG_ENCRYPTED), Return(true))); - std::vector<::bluetooth::le_audio::btle_audio_codec_config_t> - framework_encode_preference; + std::vector<::bluetooth::le_audio::btle_audio_codec_config_t> framework_encode_preference; // Initialize BtaAppRegisterCallback app_register_callback; ON_CALL(mock_gatt_interface_, AppRegister(_, _, _)) - .WillByDefault(DoAll(SaveArg<0>(&gatt_callback), - SaveArg<1>(&app_register_callback))); + .WillByDefault(DoAll(SaveArg<0>(&gatt_callback), SaveArg<1>(&app_register_callback))); LeAudioClient::Initialize( - &mock_audio_hal_client_callbacks_, - base::Bind([](MockFunction* foo) { foo->Call(); }, - &mock_storage_load), - base::Bind([](MockFunction* foo) { return foo->Call(); }, - &mock_hal_2_1_verifier), - framework_encode_preference); - if (app_register_callback) app_register_callback.Run(gatt_if, GATT_SUCCESS); + &mock_audio_hal_client_callbacks_, + base::Bind([](MockFunction* foo) { foo->Call(); }, &mock_storage_load), + base::Bind([](MockFunction* foo) { return foo->Call(); }, &mock_hal_2_1_verifier), + framework_encode_preference); + if (app_register_callback) { + app_register_callback.Run(gatt_if, GATT_SUCCESS); + } // We need to wait for the storage callback before verifying stuff SyncOnMainLoop(); @@ -4283,11 +3929,11 @@ TEST_F(UnicastTestNoInit, ServiceChangedBeforeServiceIsConnected) { EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address1)) - .Times(1); + .Times(1); /* For background connect, test needs to Inject Connected Event */ InjectConnectedEvent(test_address0, 1); @@ -4306,34 +3952,32 @@ TEST_F(UnicastTestNoInit, LoadStoredEarbudsCsisGroupedDifferently) { uint8_t group_id0 = 2; bool autoconnect0 = true; const RawAddress test_address0 = GetTestAddress(0); - SetSampleDatabaseEarbudsValid( - 1, test_address0, codec_spec_conf::kLeAudioLocationFrontLeft, - codec_spec_conf::kLeAudioLocationFrontLeft, 0x0004, - /* source sample freq 16khz */ true, /*add_csis*/ - true, /*add_cas*/ - true, /*add_pacs*/ - true, /*add_ascs*/ - group_size, 1); + SetSampleDatabaseEarbudsValid(1, test_address0, codec_spec_conf::kLeAudioLocationFrontLeft, + codec_spec_conf::kLeAudioLocationFrontLeft, 0x0004, + /* source sample freq 16khz */ true, /*add_csis*/ + true, /*add_cas*/ + true, /*add_pacs*/ + true, /*add_ascs*/ + group_size, 1); ON_CALL(mock_groups_module_, GetGroupId(test_address0, _)) - .WillByDefault(DoAll(Return(group_id0))); + .WillByDefault(DoAll(Return(group_id0))); // Device 1 uint8_t group_id1 = 3; bool autoconnect1 = false; const RawAddress test_address1 = GetTestAddress(1); - SetSampleDatabaseEarbudsValid( - 2, test_address1, codec_spec_conf::kLeAudioLocationFrontRight, - codec_spec_conf::kLeAudioLocationFrontRight, default_channel_cnt, - default_channel_cnt, 0x0004, - /* source sample freq 16khz */ true, /*add_csis*/ - true, /*add_cas*/ - true, /*add_pacs*/ - default_ase_cnt, /*add_ascs_cnt*/ - group_size, 2); + SetSampleDatabaseEarbudsValid(2, test_address1, codec_spec_conf::kLeAudioLocationFrontRight, + codec_spec_conf::kLeAudioLocationFrontRight, default_channel_cnt, + default_channel_cnt, 0x0004, + /* source sample freq 16khz */ true, /*add_csis*/ + true, /*add_cas*/ + true, /*add_pacs*/ + default_ase_cnt, /*add_ascs_cnt*/ + group_size, 2); ON_CALL(mock_groups_module_, GetGroupId(test_address1, _)) - .WillByDefault(DoAll(Return(group_id1))); + .WillByDefault(DoAll(Return(group_id1))); /* Commont storage values */ std::vector handles; @@ -4350,67 +3994,58 @@ TEST_F(UnicastTestNoInit, LoadStoredEarbudsCsisGroupedDifferently) { // Load devices from the storage when storage API is called EXPECT_CALL(mock_storage_load, Call()).WillOnce([&]() { - do_in_main_thread( - FROM_HERE, - base::BindOnce(&LeAudioClient::AddFromStorage, test_address0, - autoconnect0, codec_spec_conf::kLeAudioLocationFrontLeft, - codec_spec_conf::kLeAudioLocationFrontLeft, 0xff, 0xff, - std::move(handles), std::move(snk_pacs), - std::move(src_pacs), std::move(ases))); - do_in_main_thread( - FROM_HERE, - base::BindOnce(&LeAudioClient::AddFromStorage, test_address1, - autoconnect1, - codec_spec_conf::kLeAudioLocationFrontRight, - codec_spec_conf::kLeAudioLocationFrontRight, 0xff, 0xff, - std::move(handles), std::move(snk_pacs), - std::move(src_pacs), std::move(ases))); + do_in_main_thread(FROM_HERE, + base::BindOnce(&LeAudioClient::AddFromStorage, test_address0, autoconnect0, + codec_spec_conf::kLeAudioLocationFrontLeft, + codec_spec_conf::kLeAudioLocationFrontLeft, 0xff, 0xff, + std::move(handles), std::move(snk_pacs), std::move(src_pacs), + std::move(ases))); + do_in_main_thread(FROM_HERE, + base::BindOnce(&LeAudioClient::AddFromStorage, test_address1, autoconnect1, + codec_spec_conf::kLeAudioLocationFrontRight, + codec_spec_conf::kLeAudioLocationFrontRight, 0xff, 0xff, + std::move(handles), std::move(snk_pacs), std::move(src_pacs), + std::move(ases))); }); // Expect stored device0 to connect automatically EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); ON_CALL(mock_btm_interface_, BTM_IsEncrypted(test_address0, _)) - .WillByDefault(DoAll(Return(true))); + .WillByDefault(DoAll(Return(true))); // First device will got connected + EXPECT_CALL(mock_gatt_interface_, Open(gatt_if, test_address0, BTM_BLE_DIRECT_CONNECTION, _)) + .Times(1); + EXPECT_CALL(mock_gatt_interface_, CancelOpen(gatt_if, test_address0, _)).Times(1); EXPECT_CALL(mock_gatt_interface_, - Open(gatt_if, test_address0, BTM_BLE_DIRECT_CONNECTION, _)) - .Times(1); - EXPECT_CALL(mock_gatt_interface_, CancelOpen(gatt_if, test_address0, _)) - .Times(1); - EXPECT_CALL(mock_gatt_interface_, - Open(gatt_if, test_address0, - BTM_BLE_BKG_CONNECT_TARGETED_ANNOUNCEMENTS, _)) - .Times(1); + Open(gatt_if, test_address0, BTM_BLE_BKG_CONNECT_TARGETED_ANNOUNCEMENTS, _)) + .Times(1); // Expect stored device1 to NOT connect automatically EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address1)) - .Times(0); + .Times(0); ON_CALL(mock_btm_interface_, BTM_IsEncrypted(test_address1, _)) - .WillByDefault(DoAll(Return(true))); + .WillByDefault(DoAll(Return(true))); - EXPECT_CALL(mock_gatt_interface_, - Open(gatt_if, test_address1, BTM_BLE_DIRECT_CONNECTION, _)) - .Times(0); + EXPECT_CALL(mock_gatt_interface_, Open(gatt_if, test_address1, BTM_BLE_DIRECT_CONNECTION, _)) + .Times(0); // Initialize BtaAppRegisterCallback app_register_callback; ON_CALL(mock_gatt_interface_, AppRegister(_, _, _)) - .WillByDefault(DoAll(SaveArg<0>(&gatt_callback), - SaveArg<1>(&app_register_callback))); - std::vector<::bluetooth::le_audio::btle_audio_codec_config_t> - framework_encode_preference; + .WillByDefault(DoAll(SaveArg<0>(&gatt_callback), SaveArg<1>(&app_register_callback))); + std::vector<::bluetooth::le_audio::btle_audio_codec_config_t> framework_encode_preference; LeAudioClient::Initialize( - &mock_audio_hal_client_callbacks_, - base::Bind([](MockFunction* foo) { foo->Call(); }, - &mock_storage_load), - base::Bind([](MockFunction* foo) { return foo->Call(); }, - &mock_hal_2_1_verifier), - framework_encode_preference); - if (app_register_callback) app_register_callback.Run(gatt_if, GATT_SUCCESS); + &mock_audio_hal_client_callbacks_, + base::Bind([](MockFunction* foo) { foo->Call(); }, &mock_storage_load), + base::Bind([](MockFunction* foo) { return foo->Call(); }, &mock_hal_2_1_verifier), + framework_encode_preference); + if (app_register_callback) { + app_register_callback.Run(gatt_if, GATT_SUCCESS); + } // We need to wait for the storage callback before verifying stuff SyncOnMainLoop(); @@ -4420,9 +4055,8 @@ TEST_F(UnicastTestNoInit, LoadStoredEarbudsCsisGroupedDifferently) { // Simulate device is not there and phone fallbacks to targeted announcements EXPECT_CALL(mock_gatt_interface_, - Open(gatt_if, test_address0, - BTM_BLE_BKG_CONNECT_TARGETED_ANNOUNCEMENTS, _)) - .Times(1); + Open(gatt_if, test_address0, BTM_BLE_BKG_CONNECT_TARGETED_ANNOUNCEMENTS, _)) + .Times(1); // Devices 0 is connected. Disconnect it InjectDisconnectedEvent(1, GATT_CONN_TERMINATE_PEER_USER); @@ -4430,18 +4064,16 @@ TEST_F(UnicastTestNoInit, LoadStoredEarbudsCsisGroupedDifferently) { SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_gatt_interface_); - EXPECT_CALL(mock_gatt_interface_, CancelOpen(gatt_if, test_address0, _)) - .Times(1); + EXPECT_CALL(mock_gatt_interface_, CancelOpen(gatt_if, test_address0, _)).Times(1); EXPECT_CALL(mock_gatt_interface_, - Open(gatt_if, test_address0, - BTM_BLE_BKG_CONNECT_TARGETED_ANNOUNCEMENTS, _)) - .Times(1); + Open(gatt_if, test_address0, BTM_BLE_BKG_CONNECT_TARGETED_ANNOUNCEMENTS, _)) + .Times(1); /* Keep device in Getting Ready state */ ON_CALL(mock_btm_interface_, BTM_IsEncrypted(test_address0, _)) - .WillByDefault(DoAll(Return(false))); + .WillByDefault(DoAll(Return(false))); ON_CALL(mock_btm_interface_, SetEncryption(test_address0, _, _, _, _)) - .WillByDefault(Return(BTM_SUCCESS)); + .WillByDefault(Return(BTM_SUCCESS)); /* For background connect, test needs to Inject Connected Event */ InjectConnectedEvent(test_address0, 1); @@ -4451,8 +4083,7 @@ TEST_F(UnicastTestNoInit, LoadStoredEarbudsCsisGroupedDifferently) { ASSERT_TRUE(LeAudioClient::IsLeAudioClientRunning()); Mock::VerifyAndClearExpectations(&mock_gatt_interface_); - std::vector devs = - LeAudioClient::Get()->GetGroupDevices(group_id0); + std::vector devs = LeAudioClient::Get()->GetGroupDevices(group_id0); ASSERT_NE(std::find(devs.begin(), devs.end(), test_address0), devs.end()); ASSERT_EQ(std::find(devs.begin(), devs.end(), test_address1), devs.end()); @@ -4469,10 +4100,8 @@ TEST_F(UnicastTest, GroupingAddRemove) { uint8_t group_id0 = bluetooth::groups::kGroupUnknown; const RawAddress test_address0 = GetTestAddress(0); - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, true)) - .Times(1); - ConnectNonCsisDevice(test_address0, 1 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontLeft, + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, true)).Times(1); + ConnectNonCsisDevice(test_address0, 1 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontLeft, codec_spec_conf::kLeAudioLocationFrontLeft); group_id0 = MockDeviceGroups::DeviceGroups::Get()->GetGroupId(test_address0); @@ -4480,10 +4109,8 @@ TEST_F(UnicastTest, GroupingAddRemove) { // Earbud connects without known grouping uint8_t group_id1 = bluetooth::groups::kGroupUnknown; const RawAddress test_address1 = GetTestAddress(1); - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, true)) - .Times(1); - ConnectNonCsisDevice(test_address1, 2 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontRight, + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, true)).Times(1); + ConnectNonCsisDevice(test_address1, 2 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontRight, codec_spec_conf::kLeAudioLocationFrontRight); group_id1 = MockDeviceGroups::DeviceGroups::Get()->GetGroupId(test_address1); @@ -4501,17 +4128,14 @@ TEST_F(UnicastTest, GroupingAddRemove) { int dev1_storage_group = bluetooth::groups::kGroupUnknown; int dev1_new_group = bluetooth::groups::kGroupUnknown; - EXPECT_CALL( - mock_audio_hal_client_callbacks_, - OnGroupNodeStatus(test_address1, group_id1, GroupNodeStatus::REMOVED)) - .Times(AtLeast(1)); + EXPECT_CALL(mock_audio_hal_client_callbacks_, + OnGroupNodeStatus(test_address1, group_id1, GroupNodeStatus::REMOVED)) + .Times(AtLeast(1)); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupNodeStatus(test_address1, _, GroupNodeStatus::ADDED)) - .WillRepeatedly(SaveArg<1>(&dev1_new_group)); - EXPECT_CALL(mock_groups_module_, RemoveDevice(test_address1, group_id1)) - .Times(AtLeast(1)); - EXPECT_CALL(mock_groups_module_, AddDevice(test_address1, _, _)) - .Times(AnyNumber()); + .WillRepeatedly(SaveArg<1>(&dev1_new_group)); + EXPECT_CALL(mock_groups_module_, RemoveDevice(test_address1, group_id1)).Times(AtLeast(1)); + EXPECT_CALL(mock_groups_module_, AddDevice(test_address1, _, _)).Times(AnyNumber()); LeAudioClient::Get()->GroupRemoveNode(group_id1, test_address1); SyncOnMainLoop(); @@ -4519,23 +4143,20 @@ TEST_F(UnicastTest, GroupingAddRemove) { Mock::VerifyAndClearExpectations(&mock_groups_module_); Mock::VerifyAndClearExpectations(&mock_btif_storage_); - EXPECT_CALL(mock_groups_module_, AddDevice(test_address1, _, group_id0)) - .Times(1); + EXPECT_CALL(mock_groups_module_, AddDevice(test_address1, _, group_id0)).Times(1); LeAudioClient::Get()->GroupAddNode(group_id0, test_address1); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_groups_module_); - dev1_storage_group = - MockDeviceGroups::DeviceGroups::Get()->GetGroupId(test_address1); + dev1_storage_group = MockDeviceGroups::DeviceGroups::Get()->GetGroupId(test_address1); // Verify regrouping results EXPECT_EQ(dev1_new_group, group_id0); EXPECT_EQ(dev1_new_group, dev1_storage_group); ASSERT_EQ(LeAudioClient::Get()->GetGroupDevices(group_id1).size(), 0u); ASSERT_EQ(LeAudioClient::Get()->GetGroupDevices(group_id0).size(), 2u); - std::vector devs = - LeAudioClient::Get()->GetGroupDevices(group_id0); + std::vector devs = LeAudioClient::Get()->GetGroupDevices(group_id0); ASSERT_NE(std::find(devs.begin(), devs.end(), test_address0), devs.end()); ASSERT_NE(std::find(devs.begin(), devs.end(), test_address1), devs.end()); } @@ -4545,18 +4166,16 @@ TEST_F(UnicastTest, DoubleResumeFromAF) { int group_id = bluetooth::groups::kGroupUnknown; SetSampleDatabaseEarbudsValid( - 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, - default_channel_cnt, 0x0004, - /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, - true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, - 0 /*rank*/); + 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, default_channel_cnt, 0x0004, + /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, true /*add_pacs*/, + default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, 0 /*rank*/); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupNodeStatus(test_address0, _, GroupNodeStatus::ADDED)) - .WillOnce(DoAll(SaveArg<1>(&group_id))); + .WillOnce(DoAll(SaveArg<1>(&group_id))); ConnectLeAudio(test_address0); ASSERT_NE(group_id, bluetooth::groups::kGroupUnknown); @@ -4572,8 +4191,7 @@ TEST_F(UnicastTest, DoubleResumeFromAF) { LeAudioClient::Get()->GroupSetActive(group_id); SyncOnMainLoop(); - types::BidirectionalPair> ccids = {.sink = {gmcs_ccid}, - .source = {}}; + types::BidirectionalPair> ccids = {.sink = {gmcs_ccid}, .source = {}}; EXPECT_CALL(mock_state_machine_, StartStream(_, _, _, ccids)).Times(1); block_streaming_state_callback = true; @@ -4591,15 +4209,13 @@ TEST_F(UnicastTest, DoubleResumeFromAF) { EXPECT_CALL(mock_state_machine_, StopStream(_)).Times(0); do_in_main_thread( - FROM_HERE, - base::BindOnce( - [](int group_id, - bluetooth::le_audio::LeAudioGroupStateMachine::Callbacks* - state_machine_callbacks) { - state_machine_callbacks->StatusReportCb( - group_id, GroupStreamStatus::STREAMING); - }, - group_id, base::Unretained(state_machine_callbacks_))); + FROM_HERE, + base::BindOnce( + [](int group_id, bluetooth::le_audio::LeAudioGroupStateMachine::Callbacks* + state_machine_callbacks) { + state_machine_callbacks->StatusReportCb(group_id, GroupStreamStatus::STREAMING); + }, + group_id, base::Unretained(state_machine_callbacks_))); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_state_machine_); @@ -4616,18 +4232,16 @@ TEST_F(UnicastTest, DoubleResumeFromAFOnLocalSink) { default_channel_cnt = 1; SetSampleDatabaseEarbudsValid( - 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, - default_channel_cnt, 0x0004, - /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, - true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, - 0 /*rank*/); + 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, default_channel_cnt, 0x0004, + /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, true /*add_pacs*/, + default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, 0 /*rank*/); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupNodeStatus(test_address0, _, GroupNodeStatus::ADDED)) - .WillOnce(DoAll(SaveArg<1>(&group_id))); + .WillOnce(DoAll(SaveArg<1>(&group_id))); ConnectLeAudio(test_address0); ASSERT_NE(group_id, bluetooth::groups::kGroupUnknown); @@ -4649,8 +4263,7 @@ TEST_F(UnicastTest, DoubleResumeFromAFOnLocalSink) { Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); Mock::VerifyAndClearExpectations(mock_le_audio_source_hal_client_); - EXPECT_CALL(*mock_le_audio_sink_hal_client_, CancelStreamingRequest()) - .Times(0); + EXPECT_CALL(*mock_le_audio_sink_hal_client_, CancelStreamingRequest()).Times(0); // Actuall test here: send additional resume which shall be ignored. LocalAudioSinkResume(); @@ -4658,15 +4271,13 @@ TEST_F(UnicastTest, DoubleResumeFromAFOnLocalSink) { EXPECT_CALL(mock_state_machine_, StopStream(_)).Times(0); do_in_main_thread( - FROM_HERE, - base::BindOnce( - [](int group_id, - bluetooth::le_audio::LeAudioGroupStateMachine::Callbacks* - state_machine_callbacks) { - state_machine_callbacks->StatusReportCb( - group_id, GroupStreamStatus::STREAMING); - }, - group_id, base::Unretained(state_machine_callbacks_))); + FROM_HERE, + base::BindOnce( + [](int group_id, bluetooth::le_audio::LeAudioGroupStateMachine::Callbacks* + state_machine_callbacks) { + state_machine_callbacks->StatusReportCb(group_id, GroupStreamStatus::STREAMING); + }, + group_id, base::Unretained(state_machine_callbacks_))); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_state_machine_); @@ -4689,18 +4300,16 @@ TEST_F(UnicastTest, HandleResumeWithoutMetadataUpdateOnLocalSink) { default_channel_cnt = 1; SetSampleDatabaseEarbudsValid( - 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, - default_channel_cnt, 0x0004, - /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, - true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, - 0 /*rank*/); + 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, default_channel_cnt, 0x0004, + /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, true /*add_pacs*/, + default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, 0 /*rank*/); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupNodeStatus(test_address0, _, GroupNodeStatus::ADDED)) - .WillOnce(DoAll(SaveArg<1>(&group_id))); + .WillOnce(DoAll(SaveArg<1>(&group_id))); ConnectLeAudio(test_address0); ASSERT_NE(group_id, bluetooth::groups::kGroupUnknown); @@ -4732,8 +4341,7 @@ TEST_F(UnicastTest, HandleResumeWithoutMetadataUpdateOnLocalSink) { */ auto sink_available_context = types::kLeAudioContextAllRemoteSinkOnly; auto source_available_context = types::kLeAudioContextAllRemoteSource; - InjectAvailableContextTypes(test_address0, 1, sink_available_context, - source_available_context); + InjectAvailableContextTypes(test_address0, 1, sink_available_context, source_available_context); StopStreaming(group_id, true); SyncOnMainLoop(); @@ -4762,38 +4370,33 @@ TEST_F(UnicastTest, GroupSetActiveNonConnectedGroup) { default_channel_cnt = 1; int conn_id = 1; SetSampleDatabaseEarbudsValid( - conn_id, test_address0, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, - default_channel_cnt, 0x0004, - /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, - true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, - 0 /*rank*/); + conn_id, test_address0, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, default_channel_cnt, 0x0004, + /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, true /*add_pacs*/, + default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, 0 /*rank*/); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupNodeStatus(test_address0, _, GroupNodeStatus::ADDED)) - .WillOnce(DoAll(SaveArg<1>(&group_id))); + .WillOnce(DoAll(SaveArg<1>(&group_id))); ConnectLeAudio(test_address0); ASSERT_NE(group_id, bluetooth::groups::kGroupUnknown); Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); - EXPECT_CALL(mock_audio_hal_client_callbacks_, - OnGroupStatus(group_id, GroupStatus::INACTIVE)) - .Times(1); + EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupStatus(group_id, GroupStatus::INACTIVE)) + .Times(1); InjectDisconnectedEvent(conn_id); SyncOnMainLoop(); // Audio sessions are started only when device gets active - EXPECT_CALL(mock_audio_hal_client_callbacks_, - OnAudioGroupSelectableCodecConf(group_id, _, _)) - .Times(0); - EXPECT_CALL(mock_audio_hal_client_callbacks_, - OnAudioGroupCurrentCodecConf(group_id, _, _)) - .Times(0); + EXPECT_CALL(mock_audio_hal_client_callbacks_, OnAudioGroupSelectableCodecConf(group_id, _, _)) + .Times(0); + EXPECT_CALL(mock_audio_hal_client_callbacks_, OnAudioGroupCurrentCodecConf(group_id, _, _)) + .Times(0); EXPECT_CALL(*mock_le_audio_source_hal_client_, Start(_, _, _)).Times(0); EXPECT_CALL(*mock_le_audio_sink_hal_client_, Start(_, _, _)).Times(0); @@ -4806,8 +4409,8 @@ TEST_F(UnicastTest, GroupSetActiveNonConnectedGroup) { } TEST_F_WITH_FLAGS(UnicastTest, GroupSetActive_CurrentCodecSentOfActive, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG( - TEST_BT, leaudio_codec_config_callback_order_fix))) { + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, + leaudio_codec_config_callback_order_fix))) { const RawAddress test_address0 = GetTestAddress(0); int group_id = bluetooth::groups::kGroupUnknown; @@ -4819,38 +4422,35 @@ TEST_F_WITH_FLAGS(UnicastTest, GroupSetActive_CurrentCodecSentOfActive, default_channel_cnt = 1; SetSampleDatabaseEarbudsValid( - 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, - default_channel_cnt, 0x0004, - /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, - true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, - 0 /*rank*/); + 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, default_channel_cnt, 0x0004, + /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, true /*add_pacs*/, + default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, 0 /*rank*/); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupNodeStatus(test_address0, _, GroupNodeStatus::ADDED)) - .WillOnce(DoAll(SaveArg<1>(&group_id))); + .WillOnce(DoAll(SaveArg<1>(&group_id))); ConnectLeAudio(test_address0); ASSERT_NE(group_id, bluetooth::groups::kGroupUnknown); // Audio sessions are started only when device gets active - EXPECT_CALL(mock_audio_hal_client_callbacks_, - OnAudioGroupSelectableCodecConf(group_id, _, _)) - .Times(1); + EXPECT_CALL(mock_audio_hal_client_callbacks_, OnAudioGroupSelectableCodecConf(group_id, _, _)) + .Times(1); btle_audio_codec_config_t empty_conf{}; btle_audio_codec_config_t output_config = { - .codec_type = LE_AUDIO_CODEC_INDEX_SOURCE_LC3, - .sample_rate = LE_AUDIO_SAMPLE_RATE_INDEX_48000HZ, - .bits_per_sample = LE_AUDIO_BITS_PER_SAMPLE_INDEX_16, - .channel_count = LE_AUDIO_CHANNEL_COUNT_INDEX_1, - .frame_duration = LE_AUDIO_FRAME_DURATION_INDEX_10000US, - .octets_per_frame = 120}; + .codec_type = LE_AUDIO_CODEC_INDEX_SOURCE_LC3, + .sample_rate = LE_AUDIO_SAMPLE_RATE_INDEX_48000HZ, + .bits_per_sample = LE_AUDIO_BITS_PER_SAMPLE_INDEX_16, + .channel_count = LE_AUDIO_CHANNEL_COUNT_INDEX_1, + .frame_duration = LE_AUDIO_FRAME_DURATION_INDEX_10000US, + .octets_per_frame = 120}; EXPECT_CALL(mock_audio_hal_client_callbacks_, OnAudioGroupCurrentCodecConf(group_id, empty_conf, output_config)) - .Times(1); + .Times(1); EXPECT_CALL(*mock_le_audio_source_hal_client_, Start(_, _, _)).Times(1); EXPECT_CALL(*mock_le_audio_sink_hal_client_, Start(_, _, _)).Times(1); @@ -4872,39 +4472,33 @@ TEST_F(UnicastTest, GroupSetActive) { default_channel_cnt = 1; SetSampleDatabaseEarbudsValid( - 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, - default_channel_cnt, 0x0004, - /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, - true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, - 0 /*rank*/); + 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, default_channel_cnt, 0x0004, + /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, true /*add_pacs*/, + default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, 0 /*rank*/); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupNodeStatus(test_address0, _, GroupNodeStatus::ADDED)) - .WillOnce(DoAll(SaveArg<1>(&group_id))); + .WillOnce(DoAll(SaveArg<1>(&group_id))); ConnectLeAudio(test_address0); ASSERT_NE(group_id, bluetooth::groups::kGroupUnknown); // Audio sessions are started only when device gets active - EXPECT_CALL(mock_audio_hal_client_callbacks_, - OnAudioGroupSelectableCodecConf(group_id, _, _)) - .Times(1); - EXPECT_CALL(mock_audio_hal_client_callbacks_, - OnGroupStatus(group_id, GroupStatus::ACTIVE)) - .Times(1); - EXPECT_CALL(mock_audio_hal_client_callbacks_, - OnGroupStatus(_, GroupStatus::INACTIVE)) - .Times(0); + EXPECT_CALL(mock_audio_hal_client_callbacks_, OnAudioGroupSelectableCodecConf(group_id, _, _)) + .Times(1); + EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupStatus(group_id, GroupStatus::ACTIVE)) + .Times(1); + EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupStatus(_, GroupStatus::INACTIVE)).Times(0); EXPECT_CALL(*mock_le_audio_source_hal_client_, Start(_, _, _)).Times(1); EXPECT_CALL(*mock_le_audio_sink_hal_client_, Start(_, _, _)).Times(1); - EXPECT_CALL(*mock_codec_manager_, UpdateActiveUnicastAudioHalClient( - mock_le_audio_source_hal_client_, - mock_le_audio_sink_hal_client_, true)) - .Times(1); + EXPECT_CALL(*mock_codec_manager_, + UpdateActiveUnicastAudioHalClient(mock_le_audio_source_hal_client_, + mock_le_audio_sink_hal_client_, true)) + .Times(1); LeAudioClient::Get()->GroupSetActive(group_id); SyncOnMainLoop(); @@ -4926,18 +4520,16 @@ TEST_F(UnicastTest, GroupSetActive_SinkPacksEmpty) { default_channel_cnt = 1; SetSampleDatabaseEarbudsValid( - 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, - default_channel_cnt, 0x0004, - /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, - true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, - 0 /*rank*/); + 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, default_channel_cnt, 0x0004, + /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, true /*add_pacs*/, + default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, 0 /*rank*/); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupNodeStatus(test_address0, _, GroupNodeStatus::ADDED)) - .WillOnce(DoAll(SaveArg<1>(&group_id))); + .WillOnce(DoAll(SaveArg<1>(&group_id))); ConnectLeAudio(test_address0); ASSERT_NE(group_id, bluetooth::groups::kGroupUnknown); @@ -4947,14 +4539,14 @@ TEST_F(UnicastTest, GroupSetActive_SinkPacksEmpty) { EXPECT_CALL(mock_audio_hal_client_callbacks_, OnAudioGroupSelectableCodecConf(group_id, _, empty_confs)) - .Times(1); + .Times(1); EXPECT_CALL(*mock_le_audio_source_hal_client_, Start(_, _, _)).Times(1); EXPECT_CALL(*mock_le_audio_sink_hal_client_, Start(_, _, _)).Times(1); - EXPECT_CALL(*mock_codec_manager_, UpdateActiveUnicastAudioHalClient( - mock_le_audio_source_hal_client_, - mock_le_audio_sink_hal_client_, true)) - .Times(1); + EXPECT_CALL(*mock_codec_manager_, + UpdateActiveUnicastAudioHalClient(mock_le_audio_source_hal_client_, + mock_le_audio_sink_hal_client_, true)) + .Times(1); LeAudioClient::Get()->GroupSetActive(group_id); SyncOnMainLoop(); @@ -4976,18 +4568,16 @@ TEST_F(UnicastTest, GroupSetActive_SourcePacksEmpty) { default_channel_cnt = 1; SetSampleDatabaseEarbudsValid( - 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, - default_channel_cnt, 0x0004, - /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, - true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, - 0 /*rank*/); + 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, default_channel_cnt, 0x0004, + /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, true /*add_pacs*/, + default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, 0 /*rank*/); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupNodeStatus(test_address0, _, GroupNodeStatus::ADDED)) - .WillOnce(DoAll(SaveArg<1>(&group_id))); + .WillOnce(DoAll(SaveArg<1>(&group_id))); ConnectLeAudio(test_address0); ASSERT_NE(group_id, bluetooth::groups::kGroupUnknown); @@ -4997,7 +4587,7 @@ TEST_F(UnicastTest, GroupSetActive_SourcePacksEmpty) { EXPECT_CALL(mock_audio_hal_client_callbacks_, OnAudioGroupSelectableCodecConf(group_id, empty_confs, _)) - .Times(1); + .Times(1); EXPECT_CALL(*mock_le_audio_source_hal_client_, Start(_, _, _)).Times(1); EXPECT_CALL(*mock_le_audio_sink_hal_client_, Start(_, _, _)).Times(1); LeAudioClient::Get()->GroupSetActive(group_id); @@ -5018,18 +4608,16 @@ TEST_F(UnicastTest, ChangeAvailableContextTypeWhenInCodecConfigured) { default_channel_cnt = 1; SetSampleDatabaseEarbudsValid( - 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, - default_channel_cnt, 0x0004, - /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, - true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, - 0 /*rank*/); + 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, default_channel_cnt, 0x0004, + /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, true /*add_pacs*/, + default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, 0 /*rank*/); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupNodeStatus(test_address0, _, GroupNodeStatus::ADDED)) - .WillOnce(DoAll(SaveArg<1>(&group_id))); + .WillOnce(DoAll(SaveArg<1>(&group_id))); ConnectLeAudio(test_address0); ASSERT_NE(group_id, bluetooth::groups::kGroupUnknown); @@ -5076,8 +4664,7 @@ TEST_F(UnicastTest, ChangeAvailableContextTypeWhenInCodecConfigured) { auto sink_available_context = types::kLeAudioContextAllRemoteSinkOnly; auto source_available_context = types::kLeAudioContextAllRemoteSource; - InjectAvailableContextTypes(test_address0, 1, sink_available_context, - source_available_context); + InjectAvailableContextTypes(test_address0, 1, sink_available_context, source_available_context); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); @@ -5088,18 +4675,16 @@ TEST_F(UnicastTest, TestUpdateConfigurationCallbackWhileStreaming) { int group_id = bluetooth::groups::kGroupUnknown; SetSampleDatabaseEarbudsValid( - 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, - default_channel_cnt, 0x0004, - /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, - true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, - 0 /*rank*/); + 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, default_channel_cnt, 0x0004, + /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, true /*add_pacs*/, + default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, 0 /*rank*/); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupNodeStatus(test_address0, _, GroupNodeStatus::ADDED)) - .WillOnce(DoAll(SaveArg<1>(&group_id))); + .WillOnce(DoAll(SaveArg<1>(&group_id))); ConnectLeAudio(test_address0); ASSERT_NE(group_id, bluetooth::groups::kGroupUnknown); @@ -5109,9 +4694,8 @@ TEST_F(UnicastTest, TestUpdateConfigurationCallbackWhileStreaming) { SyncOnMainLoop(); EXPECT_CALL(mock_state_machine_, StartStream(_, _, _, _)).Times(1); - EXPECT_CALL(mock_audio_hal_client_callbacks_, - OnAudioGroupCurrentCodecConf(group_id, _, _)) - .Times(1); + EXPECT_CALL(mock_audio_hal_client_callbacks_, OnAudioGroupCurrentCodecConf(group_id, _, _)) + .Times(1); StartStreaming(AUDIO_USAGE_MEDIA, AUDIO_CONTENT_TYPE_MUSIC, group_id); SyncOnMainLoop(); @@ -5121,9 +4705,8 @@ TEST_F(UnicastTest, TestUpdateConfigurationCallbackWhileStreaming) { // When metadata update happen, there should be no configuration change // callback sent - EXPECT_CALL(mock_audio_hal_client_callbacks_, - OnAudioGroupCurrentCodecConf(group_id, _, _)) - .Times(0); + EXPECT_CALL(mock_audio_hal_client_callbacks_, OnAudioGroupCurrentCodecConf(group_id, _, _)) + .Times(0); EXPECT_CALL(mock_state_machine_, StartStream(_, _, _, _)).Times(1); UpdateLocalSourceMetadata(AUDIO_USAGE_ALARM, AUDIO_CONTENT_TYPE_UNKNOWN); @@ -5131,17 +4714,15 @@ TEST_F(UnicastTest, TestUpdateConfigurationCallbackWhileStreaming) { // Inject STREAMING Status from state machine. auto group = streaming_groups.at(group_id); do_in_main_thread( - FROM_HERE, - base::BindOnce( - [](int group_id, - bluetooth::le_audio::LeAudioGroupStateMachine::Callbacks* - state_machine_callbacks, - LeAudioDeviceGroup* group) { - state_machine_callbacks->StatusReportCb( - group_id, GroupStreamStatus::STREAMING); - }, - group_id, base::Unretained(this->state_machine_callbacks_), - std::move(group))); + FROM_HERE, + base::BindOnce( + [](int group_id, + bluetooth::le_audio::LeAudioGroupStateMachine::Callbacks* + state_machine_callbacks, + LeAudioDeviceGroup* group) { + state_machine_callbacks->StatusReportCb(group_id, GroupStreamStatus::STREAMING); + }, + group_id, base::Unretained(this->state_machine_callbacks_), std::move(group))); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_state_machine_); @@ -5153,15 +4734,13 @@ TEST_F(UnicastTest, TestDeactivateWhileStartingStream) { int group_id = bluetooth::groups::kGroupUnknown; SetSampleDatabaseEarbudsValid( - 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, - default_channel_cnt, 0x0004, - /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, - true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, - 0 /*rank*/); + 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, default_channel_cnt, 0x0004, + /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, true /*add_pacs*/, + default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, 0 /*rank*/); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupNodeStatus(test_address0, _, GroupNodeStatus::ADDED)) - .WillOnce(DoAll(SaveArg<1>(&group_id))); + .WillOnce(DoAll(SaveArg<1>(&group_id))); ConnectLeAudio(test_address0); ASSERT_NE(group_id, bluetooth::groups::kGroupUnknown); @@ -5177,17 +4756,15 @@ TEST_F(UnicastTest, TestDeactivateWhileStartingStream) { // Inject STREAMING Status from state machine. auto group = streaming_groups.at(group_id); do_in_main_thread( - FROM_HERE, - base::BindOnce( - [](int group_id, - bluetooth::le_audio::LeAudioGroupStateMachine::Callbacks* - state_machine_callbacks, - LeAudioDeviceGroup* group) { - state_machine_callbacks->StatusReportCb( - group_id, GroupStreamStatus::STREAMING); - }, - group_id, base::Unretained(this->state_machine_callbacks_), - std::move(group))); + FROM_HERE, + base::BindOnce( + [](int group_id, + bluetooth::le_audio::LeAudioGroupStateMachine::Callbacks* + state_machine_callbacks, + LeAudioDeviceGroup* group) { + state_machine_callbacks->StatusReportCb(group_id, GroupStreamStatus::STREAMING); + }, + group_id, base::Unretained(this->state_machine_callbacks_), std::move(group))); SyncOnMainLoop(); } @@ -5196,18 +4773,16 @@ TEST_F(UnicastTest, RemoveNodeWhileStreaming) { int group_id = bluetooth::groups::kGroupUnknown; SetSampleDatabaseEarbudsValid( - 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, - default_channel_cnt, 0x0004, - /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, - true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, - 0 /*rank*/); + 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, default_channel_cnt, 0x0004, + /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, true /*add_pacs*/, + default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, 0 /*rank*/); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupNodeStatus(test_address0, _, GroupNodeStatus::ADDED)) - .WillOnce(DoAll(SaveArg<1>(&group_id))); + .WillOnce(DoAll(SaveArg<1>(&group_id))); ConnectLeAudio(test_address0); ASSERT_NE(group_id, bluetooth::groups::kGroupUnknown); @@ -5227,8 +4802,7 @@ TEST_F(UnicastTest, RemoveNodeWhileStreaming) { LeAudioClient::Get()->GroupSetActive(group_id); SyncOnMainLoop(); - types::BidirectionalPair> ccids = {.sink = {gmcs_ccid}, - .source = {}}; + types::BidirectionalPair> ccids = {.sink = {gmcs_ccid}, .source = {}}; EXPECT_CALL(mock_state_machine_, StartStream(_, _, _, ccids)).Times(1); StartStreaming(AUDIO_USAGE_MEDIA, AUDIO_CONTENT_TYPE_MUSIC, group_id); @@ -5242,17 +4816,14 @@ TEST_F(UnicastTest, RemoveNodeWhileStreaming) { // Verify Data transfer on one audio source cis TestAudioDataTransfer(group_id, cis_count_out, cis_count_in, 1920); - EXPECT_CALL(mock_groups_module_, RemoveDevice(test_address0, group_id)) - .Times(1); + EXPECT_CALL(mock_groups_module_, RemoveDevice(test_address0, group_id)).Times(1); EXPECT_CALL(mock_state_machine_, StopStream(_)).Times(1); - EXPECT_CALL(mock_state_machine_, ProcessHciNotifAclDisconnected(_, _)) - .Times(1); - EXPECT_CALL( - mock_audio_hal_client_callbacks_, - OnGroupNodeStatus(test_address0, group_id, GroupNodeStatus::REMOVED)); + EXPECT_CALL(mock_state_machine_, ProcessHciNotifAclDisconnected(_, _)).Times(1); + EXPECT_CALL(mock_audio_hal_client_callbacks_, + OnGroupNodeStatus(test_address0, group_id, GroupNodeStatus::REMOVED)); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::DISCONNECTED, test_address0)) - .Times(1); + .Times(1); LeAudioClient::Get()->GroupRemoveNode(group_id, test_address0); @@ -5267,18 +4838,16 @@ TEST_F(UnicastTest, InactiveDeviceOnInternalStateMachineError) { int group_id = bluetooth::groups::kGroupUnknown; SetSampleDatabaseEarbudsValid( - 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, - default_channel_cnt, 0x0004, - /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, - true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, - 0 /*rank*/); + 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, default_channel_cnt, 0x0004, + /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, true /*add_pacs*/, + default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, 0 /*rank*/); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupNodeStatus(test_address0, _, GroupNodeStatus::ADDED)) - .WillOnce(DoAll(SaveArg<1>(&group_id))); + .WillOnce(DoAll(SaveArg<1>(&group_id))); ConnectLeAudio(test_address0); ASSERT_NE(group_id, bluetooth::groups::kGroupUnknown); @@ -5298,22 +4867,21 @@ TEST_F(UnicastTest, InactiveDeviceOnInternalStateMachineError) { LeAudioClient::Get()->GroupSetActive(group_id); SyncOnMainLoop(); - types::BidirectionalPair> ccids = {.sink = {gmcs_ccid}, - .source = {}}; + types::BidirectionalPair> ccids = {.sink = {gmcs_ccid}, .source = {}}; EXPECT_CALL(mock_state_machine_, StartStream(_, _, _, ccids)).Times(1); btle_audio_codec_config_t empty_conf{}; btle_audio_codec_config_t output_config = { - .codec_type = LE_AUDIO_CODEC_INDEX_SOURCE_LC3, - .sample_rate = LE_AUDIO_SAMPLE_RATE_INDEX_48000HZ, - .bits_per_sample = LE_AUDIO_BITS_PER_SAMPLE_INDEX_16, - .channel_count = LE_AUDIO_CHANNEL_COUNT_INDEX_2, - .frame_duration = LE_AUDIO_FRAME_DURATION_INDEX_10000US, - .octets_per_frame = 120}; + .codec_type = LE_AUDIO_CODEC_INDEX_SOURCE_LC3, + .sample_rate = LE_AUDIO_SAMPLE_RATE_INDEX_48000HZ, + .bits_per_sample = LE_AUDIO_BITS_PER_SAMPLE_INDEX_16, + .channel_count = LE_AUDIO_CHANNEL_COUNT_INDEX_2, + .frame_duration = LE_AUDIO_FRAME_DURATION_INDEX_10000US, + .octets_per_frame = 120}; EXPECT_CALL(mock_audio_hal_client_callbacks_, OnAudioGroupCurrentCodecConf(group_id, empty_conf, output_config)) - .Times(1); + .Times(1); StartStreaming(AUDIO_USAGE_MEDIA, AUDIO_CONTENT_TYPE_MUSIC, group_id); @@ -5330,13 +4898,11 @@ TEST_F(UnicastTest, InactiveDeviceOnInternalStateMachineError) { EXPECT_CALL(*mock_le_audio_source_hal_client_, Stop()).Times(1); EXPECT_CALL(*mock_le_audio_sink_hal_client_, Stop()).Times(1); - EXPECT_CALL(mock_audio_hal_client_callbacks_, - OnGroupStatus(group_id, GroupStatus::INACTIVE)) - .Times(1); + EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupStatus(group_id, GroupStatus::INACTIVE)) + .Times(1); /* This is internal error of the state machine */ - state_machine_callbacks_->StatusReportCb(group_id, - GroupStreamStatus::RELEASING); + state_machine_callbacks_->StatusReportCb(group_id, GroupStreamStatus::RELEASING); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); @@ -5349,10 +4915,9 @@ TEST_F(UnicastTest, GroupingAddTwiceNoRemove) { uint8_t group_id0 = bluetooth::groups::kGroupUnknown; const RawAddress test_address0 = GetTestAddress(0); EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, true)) - .WillOnce(Return()) - .RetiresOnSaturation(); - ConnectNonCsisDevice(test_address0, 1 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontLeft, + .WillOnce(Return()) + .RetiresOnSaturation(); + ConnectNonCsisDevice(test_address0, 1 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontLeft, codec_spec_conf::kLeAudioLocationFrontLeft); group_id0 = MockDeviceGroups::DeviceGroups::Get()->GetGroupId(test_address0); @@ -5361,10 +4926,9 @@ TEST_F(UnicastTest, GroupingAddTwiceNoRemove) { uint8_t group_id1 = bluetooth::groups::kGroupUnknown; const RawAddress test_address1 = GetTestAddress(1); EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, true)) - .WillOnce(Return()) - .RetiresOnSaturation(); - ConnectNonCsisDevice(test_address1, 2 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontRight, + .WillOnce(Return()) + .RetiresOnSaturation(); + ConnectNonCsisDevice(test_address1, 2 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontRight, codec_spec_conf::kLeAudioLocationFrontRight); Mock::VerifyAndClearExpectations(&mock_btif_storage_); @@ -5381,37 +4945,31 @@ TEST_F(UnicastTest, GroupingAddTwiceNoRemove) { int dev1_storage_group = bluetooth::groups::kGroupUnknown; int dev1_new_group = bluetooth::groups::kGroupUnknown; - EXPECT_CALL( - mock_audio_hal_client_callbacks_, - OnGroupNodeStatus(test_address1, group_id1, GroupNodeStatus::REMOVED)) - .Times(AtLeast(1)); + EXPECT_CALL(mock_audio_hal_client_callbacks_, + OnGroupNodeStatus(test_address1, group_id1, GroupNodeStatus::REMOVED)) + .Times(AtLeast(1)); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupNodeStatus(test_address1, _, GroupNodeStatus::ADDED)) - .WillRepeatedly(SaveArg<1>(&dev1_new_group)); + .WillRepeatedly(SaveArg<1>(&dev1_new_group)); // FIXME: We should expect removal with group_id context. No such API exists. - EXPECT_CALL(mock_groups_module_, RemoveDevice(test_address1, group_id1)) - .Times(AtLeast(1)); - EXPECT_CALL(mock_groups_module_, AddDevice(test_address1, _, _)) - .Times(AnyNumber()); - EXPECT_CALL(mock_groups_module_, AddDevice(test_address1, _, group_id0)) - .Times(1); + EXPECT_CALL(mock_groups_module_, RemoveDevice(test_address1, group_id1)).Times(AtLeast(1)); + EXPECT_CALL(mock_groups_module_, AddDevice(test_address1, _, _)).Times(AnyNumber()); + EXPECT_CALL(mock_groups_module_, AddDevice(test_address1, _, group_id0)).Times(1); // Regroup device: assign new group without removing it from the first one LeAudioClient::Get()->GroupAddNode(group_id0, test_address1); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_groups_module_); - dev1_storage_group = - MockDeviceGroups::DeviceGroups::Get()->GetGroupId(test_address1); + dev1_storage_group = MockDeviceGroups::DeviceGroups::Get()->GetGroupId(test_address1); // Verify regrouping results EXPECT_EQ(dev1_new_group, group_id0); EXPECT_EQ(dev1_new_group, dev1_storage_group); ASSERT_EQ(LeAudioClient::Get()->GetGroupDevices(group_id1).size(), 0u); ASSERT_EQ(LeAudioClient::Get()->GetGroupDevices(group_id0).size(), 2u); - std::vector devs = - LeAudioClient::Get()->GetGroupDevices(group_id0); + std::vector devs = LeAudioClient::Get()->GetGroupDevices(group_id0); ASSERT_NE(std::find(devs.begin(), devs.end(), test_address0), devs.end()); ASSERT_NE(std::find(devs.begin(), devs.end(), test_address1), devs.end()); } @@ -5422,100 +4980,76 @@ TEST_F(UnicastTest, RemoveTwoEarbudsCsisGrouped) { int group_id1 = 3; // Report working CSIS - ON_CALL(mock_csis_client_module_, IsCsisClientRunning()) - .WillByDefault(Return(true)); + ON_CALL(mock_csis_client_module_, IsCsisClientRunning()).WillByDefault(Return(true)); // First group - First earbud const RawAddress test_address0 = GetTestAddress(0); - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, true)) - .Times(1); - ConnectCsisDevice(test_address0, 1 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontLeft, - codec_spec_conf::kLeAudioLocationFrontLeft, group_size, - group_id0, 1 /* rank*/); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, true)).Times(1); + ConnectCsisDevice(test_address0, 1 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontLeft, + codec_spec_conf::kLeAudioLocationFrontLeft, group_size, group_id0, 1 /* rank*/); // First group - Second earbud const RawAddress test_address1 = GetTestAddress(1); - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, true)) - .Times(1); - ConnectCsisDevice(test_address1, 2 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontRight, - codec_spec_conf::kLeAudioLocationFrontRight, group_size, - group_id0, 2 /* rank*/, true /*connect_through_csis*/); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, true)).Times(1); + ConnectCsisDevice(test_address1, 2 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontRight, + codec_spec_conf::kLeAudioLocationFrontRight, group_size, group_id0, 2 /* rank*/, + true /*connect_through_csis*/); // Second group - First earbud const RawAddress test_address2 = GetTestAddress(2); - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address2, true)) - .Times(1); - ConnectCsisDevice(test_address2, 3 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontLeft, - codec_spec_conf::kLeAudioLocationFrontLeft, group_size, - group_id1, 1 /* rank*/); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address2, true)).Times(1); + ConnectCsisDevice(test_address2, 3 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontLeft, + codec_spec_conf::kLeAudioLocationFrontLeft, group_size, group_id1, 1 /* rank*/); // Second group - Second earbud const RawAddress test_address3 = GetTestAddress(3); - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address3, true)) - .Times(1); - ConnectCsisDevice(test_address3, 4 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontRight, - codec_spec_conf::kLeAudioLocationFrontRight, group_size, - group_id1, 2 /* rank*/, true /*connect_through_csis*/); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address3, true)).Times(1); + ConnectCsisDevice(test_address3, 4 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontRight, + codec_spec_conf::kLeAudioLocationFrontRight, group_size, group_id1, 2 /* rank*/, + true /*connect_through_csis*/); // First group - verify grouping information - std::vector group0_devs = - LeAudioClient::Get()->GetGroupDevices(group_id0); - ASSERT_NE(std::find(group0_devs.begin(), group0_devs.end(), test_address0), - group0_devs.end()); - ASSERT_NE(std::find(group0_devs.begin(), group0_devs.end(), test_address1), - group0_devs.end()); + std::vector group0_devs = LeAudioClient::Get()->GetGroupDevices(group_id0); + ASSERT_NE(std::find(group0_devs.begin(), group0_devs.end(), test_address0), group0_devs.end()); + ASSERT_NE(std::find(group0_devs.begin(), group0_devs.end(), test_address1), group0_devs.end()); // Second group - verify grouping information - std::vector group1_devs = - LeAudioClient::Get()->GetGroupDevices(group_id1); - ASSERT_NE(std::find(group1_devs.begin(), group1_devs.end(), test_address2), - group1_devs.end()); - ASSERT_NE(std::find(group1_devs.begin(), group1_devs.end(), test_address3), - group1_devs.end()); + std::vector group1_devs = LeAudioClient::Get()->GetGroupDevices(group_id1); + ASSERT_NE(std::find(group1_devs.begin(), group1_devs.end(), test_address2), group1_devs.end()); + ASSERT_NE(std::find(group1_devs.begin(), group1_devs.end(), test_address3), group1_devs.end()); Mock::VerifyAndClearExpectations(&mock_btif_storage_); // Expect one of the groups to be dropped and devices to be disconnected - EXPECT_CALL(mock_groups_module_, RemoveDevice(test_address0, group_id0)) - .Times(1); - EXPECT_CALL(mock_groups_module_, RemoveDevice(test_address1, group_id0)) - .Times(1); - EXPECT_CALL( - mock_audio_hal_client_callbacks_, - OnGroupNodeStatus(test_address0, group_id0, GroupNodeStatus::REMOVED)); - EXPECT_CALL( - mock_audio_hal_client_callbacks_, - OnGroupNodeStatus(test_address1, group_id0, GroupNodeStatus::REMOVED)); + EXPECT_CALL(mock_groups_module_, RemoveDevice(test_address0, group_id0)).Times(1); + EXPECT_CALL(mock_groups_module_, RemoveDevice(test_address1, group_id0)).Times(1); + EXPECT_CALL(mock_audio_hal_client_callbacks_, + OnGroupNodeStatus(test_address0, group_id0, GroupNodeStatus::REMOVED)); + EXPECT_CALL(mock_audio_hal_client_callbacks_, + OnGroupNodeStatus(test_address1, group_id0, GroupNodeStatus::REMOVED)); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::DISCONNECTED, test_address0)) - .Times(1); + .Times(1); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::DISCONNECTED, test_address1)) - .Times(1); + .Times(1); EXPECT_CALL(mock_btm_interface_, AclDisconnectFromHandle(1, _)).Times(1); EXPECT_CALL(mock_btm_interface_, AclDisconnectFromHandle(2, _)).Times(1); // Expect the other groups to be left as is - EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupStatus(group_id1, _)) - .Times(0); + EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupStatus(group_id1, _)).Times(0); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::DISCONNECTED, test_address2)) - .Times(0); + .Times(0); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::DISCONNECTED, test_address3)) - .Times(0); + .Times(0); EXPECT_CALL(mock_btm_interface_, AclDisconnectFromHandle(3, _)).Times(0); EXPECT_CALL(mock_btm_interface_, AclDisconnectFromHandle(4, _)).Times(0); - do_in_main_thread( - FROM_HERE, - base::BindOnce(&LeAudioClient::GroupDestroy, - base::Unretained(LeAudioClient::Get()), group_id0)); + do_in_main_thread(FROM_HERE, base::BindOnce(&LeAudioClient::GroupDestroy, + base::Unretained(LeAudioClient::Get()), group_id0)); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_btif_storage_); @@ -5528,32 +5062,27 @@ TEST_F(UnicastTest, ConnectAfterRemove) { uint16_t conn_id = 1; SetSampleDatabaseEarbudsValid( - conn_id, test_address0, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, - default_channel_cnt, 0x0004, - /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, - true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, - 0 /*rank*/); + conn_id, test_address0, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, default_channel_cnt, 0x0004, + /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, true /*add_pacs*/, + default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, 0 /*rank*/); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::DISCONNECTED, test_address0)) - .Times(1); + .Times(1); /* RemoveDevice */ do_in_main_thread(FROM_HERE, base::BindOnce( - [](LeAudioClient* client, - const RawAddress& test_address0) { - client->RemoveDevice(test_address0); - }, - LeAudioClient::Get(), test_address0)); + [](LeAudioClient* client, const RawAddress& test_address0) { + client->RemoveDevice(test_address0); + }, + LeAudioClient::Get(), test_address0)); SyncOnMainLoop(); - ON_CALL(mock_btm_interface_, IsLinkKeyKnown(_, _)) - .WillByDefault(DoAll(Return(false))); + ON_CALL(mock_btm_interface_, IsLinkKeyKnown(_, _)).WillByDefault(DoAll(Return(false))); - do_in_main_thread( - FROM_HERE, - base::BindOnce(&LeAudioClient::Connect, - base::Unretained(LeAudioClient::Get()), test_address0)); + do_in_main_thread(FROM_HERE, + base::BindOnce(&LeAudioClient::Connect, base::Unretained(LeAudioClient::Get()), + test_address0)); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_btif_storage_); @@ -5567,28 +5096,24 @@ TEST_F(UnicastTest, RemoveDeviceWhenConnected) { uint16_t conn_id = 1; SetSampleDatabaseEarbudsValid( - conn_id, test_address0, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, - default_channel_cnt, 0x0004, - /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, - true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, - 0 /*rank*/); + conn_id, test_address0, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, default_channel_cnt, 0x0004, + /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, true /*add_pacs*/, + default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, 0 /*rank*/); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupNodeStatus(test_address0, _, GroupNodeStatus::ADDED)) - .WillOnce(DoAll(SaveArg<1>(&group_id))); - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, true)) - .Times(1); + .WillOnce(DoAll(SaveArg<1>(&group_id))); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, true)).Times(1); ConnectLeAudio(test_address0); ASSERT_NE(group_id, bluetooth::groups::kGroupUnknown); Mock::VerifyAndClearExpectations(&mock_btif_storage_); Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, false)) - .Times(1); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, false)).Times(1); EXPECT_CALL(mock_gatt_queue_, Clean(conn_id)).Times(AtLeast(1)); EXPECT_CALL(mock_btm_interface_, AclDisconnectFromHandle(1, _)).Times(1); @@ -5598,11 +5123,10 @@ TEST_F(UnicastTest, RemoveDeviceWhenConnected) { * well. */ do_in_main_thread(FROM_HERE, base::BindOnce( - [](LeAudioClient* client, - const RawAddress& test_address0) { - client->RemoveDevice(test_address0); - }, - LeAudioClient::Get(), test_address0)); + [](LeAudioClient* client, const RawAddress& test_address0) { + client->RemoveDevice(test_address0); + }, + LeAudioClient::Get(), test_address0)); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_btif_storage_); @@ -5617,28 +5141,23 @@ TEST_F(UnicastTest, RemoveDeviceWhenConnecting) { /* Prepare mock to not inject connect event so the device can stay in * CONNECTING state*/ ON_CALL(mock_gatt_interface_, Open(_, _, BTM_BLE_DIRECT_CONNECTION, _)) - .WillByDefault(DoAll(Return())); + .WillByDefault(DoAll(Return())); SetSampleDatabaseEarbudsValid( - conn_id, test_address0, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, - default_channel_cnt, 0x0004, - /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, - true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, - 0 /*rank*/); + conn_id, test_address0, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, default_channel_cnt, 0x0004, + /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, true /*add_pacs*/, + default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, 0 /*rank*/); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(0); + .Times(0); ConnectLeAudio(test_address0, true, false); Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); - EXPECT_CALL(mock_gatt_interface_, CancelOpen(gatt_if, test_address0, true)) - .Times(1); - EXPECT_CALL(mock_gatt_interface_, CancelOpen(gatt_if, test_address0, false)) - .Times(1); - EXPECT_CALL(mock_gatt_interface_, Open(gatt_if, test_address0, _, _)) - .Times(0); + EXPECT_CALL(mock_gatt_interface_, CancelOpen(gatt_if, test_address0, true)).Times(1); + EXPECT_CALL(mock_gatt_interface_, CancelOpen(gatt_if, test_address0, false)).Times(1); + EXPECT_CALL(mock_gatt_interface_, Open(gatt_if, test_address0, _, _)).Times(0); /* * StopStream will put calls on main_loop so to keep the correct order @@ -5646,11 +5165,10 @@ TEST_F(UnicastTest, RemoveDeviceWhenConnecting) { * well. */ do_in_main_thread(FROM_HERE, base::BindOnce( - [](LeAudioClient* client, - const RawAddress& test_address0) { - client->RemoveDevice(test_address0); - }, - LeAudioClient::Get(), test_address0)); + [](LeAudioClient* client, const RawAddress& test_address0) { + client->RemoveDevice(test_address0); + }, + LeAudioClient::Get(), test_address0)); SyncOnMainLoop(); @@ -5662,21 +5180,17 @@ TEST_F(UnicastTest, RemoveDeviceWhenGettingConnectionReady) { uint16_t conn_id = 1; /* Prepare mock to not inject Service Search Complete*/ - ON_CALL(mock_gatt_interface_, ServiceSearchRequest(_, _)) - .WillByDefault(DoAll(Return())); + ON_CALL(mock_gatt_interface_, ServiceSearchRequest(_, _)).WillByDefault(DoAll(Return())); SetSampleDatabaseEarbudsValid( - conn_id, test_address0, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, - default_channel_cnt, 0x0004, - /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, - true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, - 0 /*rank*/); + conn_id, test_address0, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, default_channel_cnt, 0x0004, + /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, true /*add_pacs*/, + default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, 0 /*rank*/); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(0); - EXPECT_CALL(mock_gatt_interface_, CancelOpen(gatt_if, test_address0, false)) - .Times(0); + .Times(0); + EXPECT_CALL(mock_gatt_interface_, CancelOpen(gatt_if, test_address0, false)).Times(0); ConnectLeAudio(test_address0); Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); @@ -5686,10 +5200,8 @@ TEST_F(UnicastTest, RemoveDeviceWhenGettingConnectionReady) { EXPECT_CALL(mock_gatt_interface_, Close(conn_id)).Times(1); /* Cancel should be called in RemoveDevice */ - EXPECT_CALL(mock_gatt_interface_, CancelOpen(gatt_if, test_address0, false)) - .Times(1); - EXPECT_CALL(mock_gatt_interface_, Open(gatt_if, test_address0, _, _)) - .Times(0); + EXPECT_CALL(mock_gatt_interface_, CancelOpen(gatt_if, test_address0, false)).Times(1); + EXPECT_CALL(mock_gatt_interface_, Open(gatt_if, test_address0, _, _)).Times(0); /* * StopStream will put calls on main_loop so to keep the correct order @@ -5697,11 +5209,10 @@ TEST_F(UnicastTest, RemoveDeviceWhenGettingConnectionReady) { * well. */ do_in_main_thread(FROM_HERE, base::BindOnce( - [](LeAudioClient* client, - const RawAddress& test_address0) { - client->RemoveDevice(test_address0); - }, - LeAudioClient::Get(), test_address0)); + [](LeAudioClient* client, const RawAddress& test_address0) { + client->RemoveDevice(test_address0); + }, + LeAudioClient::Get(), test_address0)); SyncOnMainLoop(); @@ -5715,20 +5226,17 @@ TEST_F(UnicastTest, DisconnectDeviceWhenConnected) { uint16_t conn_id = 1; SetSampleDatabaseEarbudsValid( - conn_id, test_address0, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, - default_channel_cnt, 0x0004, - /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, - true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, - 0 /*rank*/); + conn_id, test_address0, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, default_channel_cnt, 0x0004, + /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, true /*add_pacs*/, + default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, 0 /*rank*/); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupNodeStatus(test_address0, _, GroupNodeStatus::ADDED)) - .WillOnce(DoAll(SaveArg<1>(&group_id))); - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, true)) - .Times(1); + .WillOnce(DoAll(SaveArg<1>(&group_id))); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, true)).Times(1); ConnectLeAudio(test_address0); ASSERT_NE(group_id, bluetooth::groups::kGroupUnknown); @@ -5738,8 +5246,7 @@ TEST_F(UnicastTest, DisconnectDeviceWhenConnected) { /* for Target announcements AutoConnect is always there, until * device is removed */ - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, false)) - .Times(0); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, false)).Times(0); EXPECT_CALL(mock_gatt_queue_, Clean(conn_id)).Times(AtLeast(1)); EXPECT_CALL(mock_btm_interface_, AclDisconnectFromHandle(1, _)).Times(1); @@ -5758,18 +5265,16 @@ TEST_F(UnicastTest, DisconnectDeviceWhenConnecting) { /* Prepare mock to not inject connect event so the device can stay in * CONNECTING state*/ ON_CALL(mock_gatt_interface_, Open(_, _, BTM_BLE_DIRECT_CONNECTION, _)) - .WillByDefault(DoAll(Return())); + .WillByDefault(DoAll(Return())); SetSampleDatabaseEarbudsValid( - conn_id, test_address0, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, - default_channel_cnt, 0x0004, - /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, - true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, - 0 /*rank*/); + conn_id, test_address0, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, default_channel_cnt, 0x0004, + /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, true /*add_pacs*/, + default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, 0 /*rank*/); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(0); + .Times(0); ConnectLeAudio(test_address0, true, false); Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); @@ -5778,10 +5283,8 @@ TEST_F(UnicastTest, DisconnectDeviceWhenConnecting) { * is done in default mock. */ ON_CALL(mock_gatt_interface_, Close(_)).WillByDefault(DoAll(Return())); - EXPECT_CALL(mock_gatt_interface_, CancelOpen(gatt_if, test_address0, true)) - .Times(1); - EXPECT_CALL(mock_gatt_interface_, Open(gatt_if, test_address0, _, _)) - .Times(0); + EXPECT_CALL(mock_gatt_interface_, CancelOpen(gatt_if, test_address0, true)).Times(1); + EXPECT_CALL(mock_gatt_interface_, Open(gatt_if, test_address0, _, _)).Times(0); LeAudioClient::Get()->Disconnect(test_address0); SyncOnMainLoop(); @@ -5794,19 +5297,16 @@ TEST_F(UnicastTest, DisconnectDeviceWhenGettingConnectionReady) { uint16_t conn_id = global_conn_id; /* Prepare mock to not inject Service Search Complete*/ - ON_CALL(mock_gatt_interface_, ServiceSearchRequest(_, _)) - .WillByDefault(DoAll(Return())); + ON_CALL(mock_gatt_interface_, ServiceSearchRequest(_, _)).WillByDefault(DoAll(Return())); SetSampleDatabaseEarbudsValid( - conn_id, test_address0, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, - default_channel_cnt, 0x0004, - /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, - true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, - 0 /*rank*/); + conn_id, test_address0, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, default_channel_cnt, 0x0004, + /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, true /*add_pacs*/, + default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, 0 /*rank*/); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(0); + .Times(0); ConnectLeAudio(test_address0); Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); @@ -5815,10 +5315,8 @@ TEST_F(UnicastTest, DisconnectDeviceWhenGettingConnectionReady) { /* TA reconnect is enabled in ConnectLeAudio. Make sure this is not removed */ EXPECT_CALL(mock_gatt_queue_, Clean(conn_id)).Times(AtLeast(1)); EXPECT_CALL(mock_gatt_interface_, Close(conn_id)).Times(1); - EXPECT_CALL(mock_gatt_interface_, CancelOpen(gatt_if, test_address0, _)) - .Times(0); - EXPECT_CALL(mock_gatt_interface_, Open(gatt_if, test_address0, _, _)) - .Times(0); + EXPECT_CALL(mock_gatt_interface_, CancelOpen(gatt_if, test_address0, _)).Times(0); + EXPECT_CALL(mock_gatt_interface_, Open(gatt_if, test_address0, _, _)).Times(0); LeAudioClient::Get()->Disconnect(test_address0); SyncOnMainLoop(); @@ -5832,18 +5330,16 @@ TEST_F(UnicastTest, RemoveWhileStreaming) { int group_id = bluetooth::groups::kGroupUnknown; SetSampleDatabaseEarbudsValid( - 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, - default_channel_cnt, 0x0004, - /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, - true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, - 0 /*rank*/); + 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, default_channel_cnt, 0x0004, + /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, true /*add_pacs*/, + default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, 0 /*rank*/); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupNodeStatus(test_address0, _, GroupNodeStatus::ADDED)) - .WillOnce(DoAll(SaveArg<1>(&group_id))); + .WillOnce(DoAll(SaveArg<1>(&group_id))); ConnectLeAudio(test_address0); ASSERT_NE(group_id, bluetooth::groups::kGroupUnknown); @@ -5863,8 +5359,7 @@ TEST_F(UnicastTest, RemoveWhileStreaming) { LeAudioClient::Get()->GroupSetActive(group_id); SyncOnMainLoop(); - types::BidirectionalPair> ccids = {.sink = {gmcs_ccid}, - .source = {}}; + types::BidirectionalPair> ccids = {.sink = {gmcs_ccid}, .source = {}}; EXPECT_CALL(mock_state_machine_, StartStream(_, _, _, ccids)).Times(1); StartStreaming(AUDIO_USAGE_MEDIA, AUDIO_CONTENT_TYPE_MUSIC, group_id); @@ -5878,19 +5373,17 @@ TEST_F(UnicastTest, RemoveWhileStreaming) { // Verify Data transfer on one audio source cis TestAudioDataTransfer(group_id, cis_count_out, cis_count_in, 1920); - EXPECT_CALL(mock_groups_module_, RemoveDevice(test_address0, group_id)) - .Times(1); + EXPECT_CALL(mock_groups_module_, RemoveDevice(test_address0, group_id)).Times(1); LeAudioDeviceGroup* group = nullptr; EXPECT_CALL(mock_state_machine_, ProcessHciNotifAclDisconnected(_, _)) - .WillOnce(DoAll(SaveArg<0>(&group))); - EXPECT_CALL( - mock_audio_hal_client_callbacks_, - OnGroupNodeStatus(test_address0, group_id, GroupNodeStatus::REMOVED)); + .WillOnce(DoAll(SaveArg<0>(&group))); + EXPECT_CALL(mock_audio_hal_client_callbacks_, + OnGroupNodeStatus(test_address0, group_id, GroupNodeStatus::REMOVED)); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::DISCONNECTED, test_address0)) - .Times(1); + .Times(1); /* * StopStream will put calls on main_loop so to keep the correct order @@ -5898,11 +5391,10 @@ TEST_F(UnicastTest, RemoveWhileStreaming) { * well. */ do_in_main_thread(FROM_HERE, base::BindOnce( - [](LeAudioClient* client, - const RawAddress& test_address0) { - client->RemoveDevice(test_address0); - }, - LeAudioClient::Get(), test_address0)); + [](LeAudioClient* client, const RawAddress& test_address0) { + client->RemoveDevice(test_address0); + }, + LeAudioClient::Get(), test_address0)); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_groups_module_); @@ -5917,18 +5409,16 @@ TEST_F(UnicastTest, DisconnecteWhileAlmostStreaming) { int group_id = bluetooth::groups::kGroupUnknown; SetSampleDatabaseEarbudsValid( - 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, - default_channel_cnt, 0x0004, - /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, - true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, - 0 /*rank*/); + 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, default_channel_cnt, 0x0004, + /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, true /*add_pacs*/, + default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, 0 /*rank*/); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupNodeStatus(test_address0, _, GroupNodeStatus::ADDED)) - .WillOnce(DoAll(SaveArg<1>(&group_id))); + .WillOnce(DoAll(SaveArg<1>(&group_id))); ConnectLeAudio(test_address0); ASSERT_NE(group_id, bluetooth::groups::kGroupUnknown); @@ -5944,8 +5434,7 @@ TEST_F(UnicastTest, DisconnecteWhileAlmostStreaming) { LeAudioClient::Get()->GroupSetActive(group_id); SyncOnMainLoop(); - types::BidirectionalPair> ccids = {.sink = {gmcs_ccid}, - .source = {}}; + types::BidirectionalPair> ccids = {.sink = {gmcs_ccid}, .source = {}}; EXPECT_CALL(mock_state_machine_, StartStream(_, _, _, ccids)).Times(1); /* We want here to CIS be established but device not being yet in streaming @@ -5970,11 +5459,11 @@ TEST_F(UnicastTest, DisconnecteWhileAlmostStreaming) { LeAudioDeviceGroup* group = nullptr; EXPECT_CALL(mock_state_machine_, ProcessHciNotifAclDisconnected(_, _)) - .WillOnce(DoAll(SaveArg<0>(&group))); + .WillOnce(DoAll(SaveArg<0>(&group))); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::DISCONNECTED, test_address0)) - .Times(1); + .Times(1); /* * StopStream will put calls on main_loop so to keep the correct order @@ -5982,11 +5471,10 @@ TEST_F(UnicastTest, DisconnecteWhileAlmostStreaming) { * well. */ do_in_main_thread(FROM_HERE, base::BindOnce( - [](LeAudioClient* client, - const RawAddress& test_address0) { - client->Disconnect(test_address0); - }, - LeAudioClient::Get(), test_address0)); + [](LeAudioClient* client, const RawAddress& test_address0) { + client->Disconnect(test_address0); + }, + LeAudioClient::Get(), test_address0)); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_groups_module_); @@ -6000,18 +5488,17 @@ TEST_F(UnicastTest, EarbudsTwsStyleStreaming) { const RawAddress test_address0 = GetTestAddress(0); int group_id = bluetooth::groups::kGroupUnknown; - SetSampleDatabaseEarbudsValid( - 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationStereo, 0x01, 0x01, - codec_spec_caps::kLeAudioSamplingFreq16000Hz, false /*add_csis*/, - true /*add_cas*/, true /*add_pacs*/, 2 /*add_asc_cnt*/, 1 /*set_size*/, - 0 /*rank*/); + SetSampleDatabaseEarbudsValid(1, test_address0, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationStereo, 0x01, 0x01, + codec_spec_caps::kLeAudioSamplingFreq16000Hz, false /*add_csis*/, + true /*add_cas*/, true /*add_pacs*/, 2 /*add_asc_cnt*/, + 1 /*set_size*/, 0 /*rank*/); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupNodeStatus(test_address0, _, GroupNodeStatus::ADDED)) - .WillOnce(DoAll(SaveArg<1>(&group_id))); + .WillOnce(DoAll(SaveArg<1>(&group_id))); ConnectLeAudio(test_address0); ASSERT_NE(group_id, bluetooth::groups::kGroupUnknown); @@ -6052,10 +5539,10 @@ TEST_F(UnicastTest, EarbudsTwsStyleStreaming) { // Release EXPECT_CALL(*mock_le_audio_source_hal_client_, Stop()).Times(1); - EXPECT_CALL(*mock_codec_manager_, UpdateActiveUnicastAudioHalClient( - mock_le_audio_source_hal_client_, - mock_le_audio_sink_hal_client_, false)) - .Times(1); + EXPECT_CALL(*mock_codec_manager_, + UpdateActiveUnicastAudioHalClient(mock_le_audio_source_hal_client_, + mock_le_audio_sink_hal_client_, false)) + .Times(1); EXPECT_CALL(*mock_le_audio_source_hal_client_, OnDestroyed()).Times(1); EXPECT_CALL(*mock_le_audio_sink_hal_client_, OnDestroyed()).Times(1); @@ -6071,25 +5558,24 @@ TEST_F(UnicastTest, SpeakerFailedConversationalStreaming) { available_src_context_types_ = 0; supported_src_context_types_ = - available_src_context_types_ | - types::AudioContexts(types::LeAudioContextType::UNSPECIFIED).value(); + available_src_context_types_ | + types::AudioContexts(types::LeAudioContextType::UNSPECIFIED).value(); available_snk_context_types_ = 0x0004; supported_snk_context_types_ = - available_snk_context_types_ | - types::AudioContexts(types::LeAudioContextType::UNSPECIFIED).value(); + available_snk_context_types_ | + types::AudioContexts(types::LeAudioContextType::UNSPECIFIED).value(); - SetSampleDatabaseEarbudsValid( - 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, 0, - default_channel_cnt, default_channel_cnt, 0x0004, - /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, - true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, - 0 /*rank*/); + SetSampleDatabaseEarbudsValid(1, test_address0, codec_spec_conf::kLeAudioLocationStereo, 0, + default_channel_cnt, default_channel_cnt, 0x0004, + /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, + true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, + 0 /*rank*/); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupNodeStatus(test_address0, _, GroupNodeStatus::ADDED)) - .WillOnce(DoAll(SaveArg<1>(&group_id))); + .WillOnce(DoAll(SaveArg<1>(&group_id))); ConnectLeAudio(test_address0); ASSERT_NE(group_id, bluetooth::groups::kGroupUnknown); @@ -6106,18 +5592,16 @@ TEST_F(UnicastTest, SpeakerStreaming) { int group_id = bluetooth::groups::kGroupUnknown; SetSampleDatabaseEarbudsValid( - 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, - default_channel_cnt, 0x0004, - /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, - true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, - 0 /*rank*/); + 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, default_channel_cnt, 0x0004, + /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, true /*add_pacs*/, + default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, 0 /*rank*/); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupNodeStatus(test_address0, _, GroupNodeStatus::ADDED)) - .WillOnce(DoAll(SaveArg<1>(&group_id))); + .WillOnce(DoAll(SaveArg<1>(&group_id))); ConnectLeAudio(test_address0); ASSERT_NE(group_id, bluetooth::groups::kGroupUnknown); @@ -6159,10 +5643,10 @@ TEST_F(UnicastTest, SpeakerStreaming) { // Release EXPECT_CALL(*mock_le_audio_source_hal_client_, Stop()).Times(1); - EXPECT_CALL(*mock_codec_manager_, UpdateActiveUnicastAudioHalClient( - mock_le_audio_source_hal_client_, - mock_le_audio_sink_hal_client_, false)) - .Times(1); + EXPECT_CALL(*mock_codec_manager_, + UpdateActiveUnicastAudioHalClient(mock_le_audio_source_hal_client_, + mock_le_audio_sink_hal_client_, false)) + .Times(1); EXPECT_CALL(*mock_le_audio_source_hal_client_, OnDestroyed()).Times(1); EXPECT_CALL(*mock_le_audio_sink_hal_client_, OnDestroyed()).Times(1); @@ -6185,25 +5669,23 @@ TEST_F(UnicastTest, SpeakerStreamingNonDefault) { * 5. Verify that UNSPECIFIED context type is used. */ - available_snk_context_types_ = (types::LeAudioContextType::VOICEASSISTANTS | - types::LeAudioContextType::MEDIA | - types::LeAudioContextType::UNSPECIFIED) - .value(); + available_snk_context_types_ = + (types::LeAudioContextType::VOICEASSISTANTS | types::LeAudioContextType::MEDIA | + types::LeAudioContextType::UNSPECIFIED) + .value(); supported_snk_context_types_ = available_snk_context_types_; SetSampleDatabaseEarbudsValid( - 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, - default_channel_cnt, 0x0004, - /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, - true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, - 0 /*rank*/); + 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, default_channel_cnt, 0x0004, + /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, true /*add_pacs*/, + default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, 0 /*rank*/); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupNodeStatus(test_address0, _, GroupNodeStatus::ADDED)) - .WillOnce(DoAll(SaveArg<1>(&group_id))); + .WillOnce(DoAll(SaveArg<1>(&group_id))); ConnectLeAudio(test_address0); ASSERT_NE(group_id, bluetooth::groups::kGroupUnknown); @@ -6256,19 +5738,16 @@ TEST_F(UnicastTest, SpeakerStreamingNonDefault) { /* Expect the previous release to clear the old audio session metadata */ LeAudioClient::Get()->GroupSetActive(group_id); SyncOnMainLoop(); - EXPECT_CALL(mock_state_machine_, - StartStream(_, types::LeAudioContextType::VOICEASSISTANTS, _, _)) - .Times(0); - EXPECT_CALL(mock_state_machine_, - StartStream(_, kLeAudioDefaultConfigurationContext, _, _)) - .Times(1); + EXPECT_CALL(mock_state_machine_, StartStream(_, types::LeAudioContextType::VOICEASSISTANTS, _, _)) + .Times(0); + EXPECT_CALL(mock_state_machine_, StartStream(_, kLeAudioDefaultConfigurationContext, _, _)) + .Times(1); LocalAudioSourceResume(); } TEST_F_WITH_FLAGS(UnicastTest, TestUnidirectionalVoiceAssistant_Sink, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG( - TEST_BT, - le_audio_support_unidirectional_voice_assistant))) { + REQUIRES_FLAGS_ENABLED( + ACONFIG_FLAG(TEST_BT, le_audio_support_unidirectional_voice_assistant))) { const RawAddress test_address0 = GetTestAddress(0); int group_id = bluetooth::groups::kGroupUnknown; @@ -6279,38 +5758,34 @@ TEST_F_WITH_FLAGS(UnicastTest, TestUnidirectionalVoiceAssistant_Sink, * 5. Verify that Unidirectional VOICEASSISTANT has been created */ - available_snk_context_types_ = (types::LeAudioContextType::VOICEASSISTANTS | - types::LeAudioContextType::MEDIA | - types::LeAudioContextType::UNSPECIFIED) - .value(); + available_snk_context_types_ = + (types::LeAudioContextType::VOICEASSISTANTS | types::LeAudioContextType::MEDIA | + types::LeAudioContextType::UNSPECIFIED) + .value(); supported_snk_context_types_ = available_snk_context_types_; available_src_context_types_ = - (types::LeAudioContextType::LIVE | types::LeAudioContextType::UNSPECIFIED) - .value(); + (types::LeAudioContextType::LIVE | types::LeAudioContextType::UNSPECIFIED).value(); supported_src_context_types_ = available_src_context_types_; SetSampleDatabaseEarbudsValid( - 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, - default_channel_cnt, 0x0004, - /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, - true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, - 0 /*rank*/); + 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, default_channel_cnt, 0x0004, + /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, true /*add_pacs*/, + default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, 0 /*rank*/); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupNodeStatus(test_address0, _, GroupNodeStatus::ADDED)) - .WillOnce(DoAll(SaveArg<1>(&group_id))); + .WillOnce(DoAll(SaveArg<1>(&group_id))); types::BidirectionalPair metadata_contexts = { - .sink = types::AudioContexts(types::LeAudioContextType::VOICEASSISTANTS), - .source = types::AudioContexts()}; + .sink = types::AudioContexts(types::LeAudioContextType::VOICEASSISTANTS), + .source = types::AudioContexts()}; EXPECT_CALL(mock_state_machine_, - StartStream(_, types::LeAudioContextType::INSTRUCTIONAL, - metadata_contexts, _)) - .Times(1); + StartStream(_, types::LeAudioContextType::INSTRUCTIONAL, metadata_contexts, _)) + .Times(1); ConnectLeAudio(test_address0); ASSERT_NE(group_id, bluetooth::groups::kGroupUnknown); @@ -6322,10 +5797,10 @@ TEST_F_WITH_FLAGS(UnicastTest, TestUnidirectionalVoiceAssistant_Sink, EXPECT_CALL(*mock_le_audio_source_hal_client_, Start(_, _, _)).Times(1); EXPECT_CALL(*mock_le_audio_sink_hal_client_, Start(_, _, _)).Times(1); - EXPECT_CALL(*mock_codec_manager_, UpdateActiveUnicastAudioHalClient( - mock_le_audio_source_hal_client_, - mock_le_audio_sink_hal_client_, true)) - .Times(1); + EXPECT_CALL(*mock_codec_manager_, + UpdateActiveUnicastAudioHalClient(mock_le_audio_source_hal_client_, + mock_le_audio_sink_hal_client_, true)) + .Times(1); LeAudioClient::Get()->GroupSetActive(group_id); SyncOnMainLoop(); @@ -6344,9 +5819,8 @@ TEST_F_WITH_FLAGS(UnicastTest, TestUnidirectionalVoiceAssistant_Sink, } TEST_F_WITH_FLAGS(UnicastTest, TestUnidirectionalVoiceAssistant_Source, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG( - TEST_BT, - le_audio_support_unidirectional_voice_assistant))) { + REQUIRES_FLAGS_ENABLED( + ACONFIG_FLAG(TEST_BT, le_audio_support_unidirectional_voice_assistant))) { const RawAddress test_address0 = GetTestAddress(0); int group_id = bluetooth::groups::kGroupUnknown; @@ -6357,39 +5831,35 @@ TEST_F_WITH_FLAGS(UnicastTest, TestUnidirectionalVoiceAssistant_Source, * 5. Verify that bi-direction VOICEASSISTANT has been created */ - available_snk_context_types_ = (types::LeAudioContextType::MEDIA | - types::LeAudioContextType::UNSPECIFIED) - .value(); + available_snk_context_types_ = + (types::LeAudioContextType::MEDIA | types::LeAudioContextType::UNSPECIFIED).value(); supported_snk_context_types_ = available_snk_context_types_; available_src_context_types_ = - (types::LeAudioContextType::VOICEASSISTANTS | - types::LeAudioContextType::LIVE | types::LeAudioContextType::UNSPECIFIED) - .value(); + (types::LeAudioContextType::VOICEASSISTANTS | types::LeAudioContextType::LIVE | + types::LeAudioContextType::UNSPECIFIED) + .value(); supported_src_context_types_ = available_src_context_types_; SetSampleDatabaseEarbudsValid( - 1, test_address0, codec_spec_conf::kLeAudioLocationFrontLeftOfCenter, - codec_spec_conf::kLeAudioLocationFrontLeftOfCenter, default_channel_cnt, - default_channel_cnt, 0x0004, - /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, - true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 2 /*set_size*/, - 1 /*rank*/); + 1, test_address0, codec_spec_conf::kLeAudioLocationFrontLeftOfCenter, + codec_spec_conf::kLeAudioLocationFrontLeftOfCenter, default_channel_cnt, + default_channel_cnt, 0x0004, + /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, true /*add_pacs*/, + default_ase_cnt /*add_ascs_cnt*/, 2 /*set_size*/, 1 /*rank*/); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupNodeStatus(test_address0, _, GroupNodeStatus::ADDED)) - .WillOnce(DoAll(SaveArg<1>(&group_id))); + .WillOnce(DoAll(SaveArg<1>(&group_id))); types::BidirectionalPair metadata_contexts = { - .sink = types::AudioContexts(types::LeAudioContextType::UNSPECIFIED), - .source = - types::AudioContexts(types::LeAudioContextType::VOICEASSISTANTS)}; + .sink = types::AudioContexts(types::LeAudioContextType::UNSPECIFIED), + .source = types::AudioContexts(types::LeAudioContextType::VOICEASSISTANTS)}; EXPECT_CALL(mock_state_machine_, - StartStream(_, types::LeAudioContextType::VOICEASSISTANTS, - metadata_contexts, _)) - .Times(1); + StartStream(_, types::LeAudioContextType::VOICEASSISTANTS, metadata_contexts, _)) + .Times(1); ConnectLeAudio(test_address0); ASSERT_NE(group_id, bluetooth::groups::kGroupUnknown); @@ -6419,18 +5889,16 @@ TEST_F(UnicastTest, SpeakerStreamingAutonomousRelease) { int group_id = bluetooth::groups::kGroupUnknown; SetSampleDatabaseEarbudsValid( - 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, - default_channel_cnt, 0x0004, - /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, - true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, - 0 /*rank*/); + 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, default_channel_cnt, 0x0004, + /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, true /*add_pacs*/, + default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, 0 /*rank*/); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupNodeStatus(test_address0, _, GroupNodeStatus::ADDED)) - .WillOnce(DoAll(SaveArg<1>(&group_id))); + .WillOnce(DoAll(SaveArg<1>(&group_id))); ConnectLeAudio(test_address0); ASSERT_NE(group_id, bluetooth::groups::kGroupUnknown); @@ -6448,8 +5916,7 @@ TEST_F(UnicastTest, SpeakerStreamingAutonomousRelease) { SyncOnMainLoop(); // Verify Data transfer on one audio source cis - TestAudioDataTransfer(group_id, 1 /* cis_count_out */, 0 /* cis_count_in */, - 1920); + TestAudioDataTransfer(group_id, 1 /* cis_count_out */, 0 /* cis_count_in */, 1920); // Inject the IDLE state as if an autonomous release happened ASSERT_NE(0lu, streaming_groups.count(group_id)); @@ -6466,8 +5933,7 @@ TEST_F(UnicastTest, SpeakerStreamingAutonomousRelease) { } // Verify no Data transfer after the autonomous release - TestAudioDataTransfer(group_id, 0 /* cis_count_out */, 0 /* cis_count_in */, - 1920); + TestAudioDataTransfer(group_id, 0 /* cis_count_out */, 0 /* cis_count_in */, 1920); } TEST_F(UnicastTest, TwoEarbudsStreaming) { @@ -6475,28 +5941,22 @@ TEST_F(UnicastTest, TwoEarbudsStreaming) { int group_id = 2; // Report working CSIS - ON_CALL(mock_csis_client_module_, IsCsisClientRunning()) - .WillByDefault(Return(true)); + ON_CALL(mock_csis_client_module_, IsCsisClientRunning()).WillByDefault(Return(true)); ON_CALL(mock_csis_client_module_, GetDesiredSize(group_id)) - .WillByDefault(Invoke([&](int group_id) { return group_size; })); + .WillByDefault(Invoke([&](int group_id) { return group_size; })); // First earbud const RawAddress test_address0 = GetTestAddress(0); - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, true)) - .Times(1); - ConnectCsisDevice(test_address0, 1 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontLeft, - codec_spec_conf::kLeAudioLocationFrontLeft, group_size, - group_id, 1 /* rank*/); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, true)).Times(1); + ConnectCsisDevice(test_address0, 1 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontLeft, + codec_spec_conf::kLeAudioLocationFrontLeft, group_size, group_id, 1 /* rank*/); // Second earbud const RawAddress test_address1 = GetTestAddress(1); - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, true)) - .Times(1); - ConnectCsisDevice(test_address1, 2 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontRight, - codec_spec_conf::kLeAudioLocationFrontRight, group_size, - group_id, 2 /* rank*/, true /*connect_through_csis*/); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, true)).Times(1); + ConnectCsisDevice(test_address1, 2 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontRight, + codec_spec_conf::kLeAudioLocationFrontRight, group_size, group_id, 2 /* rank*/, + true /*connect_through_csis*/); // Start streaming EXPECT_CALL(*mock_le_audio_source_hal_client_, Start(_, _, _)).Times(1); @@ -6507,20 +5967,18 @@ TEST_F(UnicastTest, TwoEarbudsStreaming) { Mock::VerifyAndClearExpectations(mock_le_audio_source_hal_client_); /* Make sure configurations are non empty */ - btle_audio_codec_config_t call_config = { - .codec_type = LE_AUDIO_CODEC_INDEX_SOURCE_LC3, - .sample_rate = LE_AUDIO_SAMPLE_RATE_INDEX_16000HZ, - .bits_per_sample = LE_AUDIO_BITS_PER_SAMPLE_INDEX_16, - .channel_count = LE_AUDIO_CHANNEL_COUNT_INDEX_1, - .frame_duration = LE_AUDIO_FRAME_DURATION_INDEX_10000US, - .octets_per_frame = 40}; + btle_audio_codec_config_t call_config = {.codec_type = LE_AUDIO_CODEC_INDEX_SOURCE_LC3, + .sample_rate = LE_AUDIO_SAMPLE_RATE_INDEX_16000HZ, + .bits_per_sample = LE_AUDIO_BITS_PER_SAMPLE_INDEX_16, + .channel_count = LE_AUDIO_CHANNEL_COUNT_INDEX_1, + .frame_duration = LE_AUDIO_FRAME_DURATION_INDEX_10000US, + .octets_per_frame = 40}; EXPECT_CALL(mock_audio_hal_client_callbacks_, OnAudioGroupCurrentCodecConf(group_id, call_config, call_config)) - .Times(1); + .Times(1); - StartStreaming(AUDIO_USAGE_VOICE_COMMUNICATION, AUDIO_CONTENT_TYPE_SPEECH, - group_id); + StartStreaming(AUDIO_USAGE_VOICE_COMMUNICATION, AUDIO_CONTENT_TYPE_SPEECH, group_id); Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); Mock::VerifyAndClearExpectations(mock_le_audio_source_hal_client_); @@ -6536,8 +5994,7 @@ TEST_F(UnicastTest, TwoEarbudsStreaming) { SyncOnMainLoop(); // Resume - StartStreaming(AUDIO_USAGE_VOICE_COMMUNICATION, AUDIO_CONTENT_TYPE_SPEECH, - group_id); + StartStreaming(AUDIO_USAGE_VOICE_COMMUNICATION, AUDIO_CONTENT_TYPE_SPEECH, group_id); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(mock_le_audio_source_hal_client_); @@ -6552,14 +6009,12 @@ TEST_F(UnicastTest, TwoEarbudsStreaming) { Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); // Check if cache configuration is still present - ASSERT_TRUE( - group->GetCachedConfiguration(types::LeAudioContextType::CONVERSATIONAL) - ->confs.get(le_audio::types::kLeAudioDirectionSink) - .size()); - ASSERT_TRUE( - group->GetCachedConfiguration(types::LeAudioContextType::CONVERSATIONAL) - ->confs.get(le_audio::types::kLeAudioDirectionSource) - .size()); + ASSERT_TRUE(group->GetCachedConfiguration(types::LeAudioContextType::CONVERSATIONAL) + ->confs.get(le_audio::types::kLeAudioDirectionSink) + .size()); + ASSERT_TRUE(group->GetCachedConfiguration(types::LeAudioContextType::CONVERSATIONAL) + ->confs.get(le_audio::types::kLeAudioDirectionSource) + .size()); // Release EXPECT_CALL(*mock_le_audio_source_hal_client_, Stop()).Times(1); @@ -6572,14 +6027,12 @@ TEST_F(UnicastTest, TwoEarbudsStreaming) { Mock::VerifyAndClearExpectations(mock_le_audio_source_hal_client_); // Setting group inactive, shall not change cached configuration - ASSERT_TRUE( - group->GetCachedConfiguration(types::LeAudioContextType::CONVERSATIONAL) - ->confs.get(le_audio::types::kLeAudioDirectionSink) - .size()); - ASSERT_TRUE( - group->GetCachedConfiguration(types::LeAudioContextType::CONVERSATIONAL) - ->confs.get(le_audio::types::kLeAudioDirectionSource) - .size()); + ASSERT_TRUE(group->GetCachedConfiguration(types::LeAudioContextType::CONVERSATIONAL) + ->confs.get(le_audio::types::kLeAudioDirectionSink) + .size()); + ASSERT_TRUE(group->GetCachedConfiguration(types::LeAudioContextType::CONVERSATIONAL) + ->confs.get(le_audio::types::kLeAudioDirectionSource) + .size()); } TEST_F(UnicastTest, StreamingVxAospSampleSound) { @@ -6591,29 +6044,23 @@ TEST_F(UnicastTest, StreamingVxAospSampleSound) { */ // Report working CSIS - ON_CALL(mock_csis_client_module_, IsCsisClientRunning()) - .WillByDefault(Return(true)); + ON_CALL(mock_csis_client_module_, IsCsisClientRunning()).WillByDefault(Return(true)); ON_CALL(mock_csis_client_module_, GetDesiredSize(group_id)) - .WillByDefault(Invoke([&](int group_id) { return group_size; })); + .WillByDefault(Invoke([&](int group_id) { return group_size; })); // First earbud const RawAddress test_address0 = GetTestAddress(0); - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, true)) - .Times(1); - ConnectCsisDevice(test_address0, 1 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontLeft, - codec_spec_conf::kLeAudioLocationFrontLeft, group_size, - group_id, 1 /* rank*/); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, true)).Times(1); + ConnectCsisDevice(test_address0, 1 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontLeft, + codec_spec_conf::kLeAudioLocationFrontLeft, group_size, group_id, 1 /* rank*/); // Second earbud const RawAddress test_address1 = GetTestAddress(1); - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, true)) - .Times(1); - ConnectCsisDevice(test_address1, 2 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontRight, - codec_spec_conf::kLeAudioLocationFrontRight, group_size, - group_id, 2 /* rank*/, true /*connect_through_csis*/); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, true)).Times(1); + ConnectCsisDevice(test_address1, 2 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontRight, + codec_spec_conf::kLeAudioLocationFrontRight, group_size, group_id, 2 /* rank*/, + true /*connect_through_csis*/); // Start streaming EXPECT_CALL(*mock_le_audio_source_hal_client_, Start(_, _, _)).Times(1); @@ -6629,12 +6076,9 @@ TEST_F(UnicastTest, StreamingVxAospSampleSound) { test_tags_ptr_ = test_tag; auto initial_context = types::LeAudioContextType::SOUNDEFFECTS; - types::BidirectionalPair> ccids = {.sink = {}, - .source = {}}; - EXPECT_CALL(mock_state_machine_, StartStream(_, initial_context, _, ccids)) - .Times(1); - StartStreaming(AUDIO_USAGE_VOICE_COMMUNICATION, AUDIO_CONTENT_TYPE_SPEECH, - group_id); + types::BidirectionalPair> ccids = {.sink = {}, .source = {}}; + EXPECT_CALL(mock_state_machine_, StartStream(_, initial_context, _, ccids)).Times(1); + StartStreaming(AUDIO_USAGE_VOICE_COMMUNICATION, AUDIO_CONTENT_TYPE_SPEECH, group_id); Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); Mock::VerifyAndClearExpectations(mock_le_audio_source_hal_client_); @@ -6651,29 +6095,23 @@ TEST_F(UnicastTest, UpdateActiveAudioConfigForLocalSinkSource) { int group_id = 2; // Report working CSIS - ON_CALL(mock_csis_client_module_, IsCsisClientRunning()) - .WillByDefault(Return(true)); + ON_CALL(mock_csis_client_module_, IsCsisClientRunning()).WillByDefault(Return(true)); ON_CALL(mock_csis_client_module_, GetDesiredSize(group_id)) - .WillByDefault(Invoke([&](int group_id) { return group_size; })); + .WillByDefault(Invoke([&](int group_id) { return group_size; })); // First earbud const RawAddress test_address0 = GetTestAddress(0); - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, true)) - .Times(1); - ConnectCsisDevice(test_address0, 1 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontLeft, - codec_spec_conf::kLeAudioLocationFrontLeft, group_size, - group_id, 1 /* rank*/); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, true)).Times(1); + ConnectCsisDevice(test_address0, 1 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontLeft, + codec_spec_conf::kLeAudioLocationFrontLeft, group_size, group_id, 1 /* rank*/); // Second earbud const RawAddress test_address1 = GetTestAddress(1); - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, true)) - .Times(1); - ConnectCsisDevice(test_address1, 2 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontRight, - codec_spec_conf::kLeAudioLocationFrontRight, group_size, - group_id, 2 /* rank*/, true /*connect_through_csis*/); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, true)).Times(1); + ConnectCsisDevice(test_address1, 2 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontRight, + codec_spec_conf::kLeAudioLocationFrontRight, group_size, group_id, 2 /* rank*/, + true /*connect_through_csis*/); // Set group as active EXPECT_CALL(*mock_le_audio_sink_hal_client_, Start(_, _, _)).Times(1); @@ -6682,32 +6120,23 @@ TEST_F(UnicastTest, UpdateActiveAudioConfigForLocalSinkSource) { Mock::VerifyAndClearExpectations(mock_le_audio_source_hal_client_); // Start streaming - EXPECT_CALL(*mock_le_audio_sink_hal_client_, UpdateAudioConfigToHal(_)) - .Times(1); - EXPECT_CALL(*mock_le_audio_source_hal_client_, UpdateAudioConfigToHal(_)) - .Times(1); + EXPECT_CALL(*mock_le_audio_sink_hal_client_, UpdateAudioConfigToHal(_)).Times(1); + EXPECT_CALL(*mock_le_audio_source_hal_client_, UpdateAudioConfigToHal(_)).Times(1); EXPECT_CALL(*mock_codec_manager_, UpdateActiveAudioConfig(_, _, _)) - .Times(1) - .WillOnce( - [](const types::BidirectionalPair& stream_params, - types::BidirectionalPair delays_ms, - std::function - update_receiver) { + .Times(1) + .WillOnce([](const types::BidirectionalPair& stream_params, + types::BidirectionalPair delays_ms, + std::function + update_receiver) { bluetooth::le_audio::offload_config unicast_cfg; if (delays_ms.sink != 0) { - update_receiver( - unicast_cfg, - bluetooth::le_audio::types::kLeAudioDirectionSink); + update_receiver(unicast_cfg, bluetooth::le_audio::types::kLeAudioDirectionSink); } if (delays_ms.source != 0) { - update_receiver( - unicast_cfg, - bluetooth::le_audio::types::kLeAudioDirectionSource); + update_receiver(unicast_cfg, bluetooth::le_audio::types::kLeAudioDirectionSource); } }); - StartStreaming(AUDIO_USAGE_VOICE_COMMUNICATION, AUDIO_CONTENT_TYPE_SPEECH, - group_id); + StartStreaming(AUDIO_USAGE_VOICE_COMMUNICATION, AUDIO_CONTENT_TYPE_SPEECH, group_id); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(mock_le_audio_sink_hal_client_); @@ -6729,29 +6158,23 @@ TEST_F(UnicastTest, UpdateActiveAudioConfigForLocalSource) { int group_id = 2; // Report working CSIS - ON_CALL(mock_csis_client_module_, IsCsisClientRunning()) - .WillByDefault(Return(true)); + ON_CALL(mock_csis_client_module_, IsCsisClientRunning()).WillByDefault(Return(true)); ON_CALL(mock_csis_client_module_, GetDesiredSize(group_id)) - .WillByDefault(Invoke([&](int group_id) { return group_size; })); + .WillByDefault(Invoke([&](int group_id) { return group_size; })); // First earbud const RawAddress test_address0 = GetTestAddress(0); - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, true)) - .Times(1); - ConnectCsisDevice(test_address0, 1 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontLeft, - codec_spec_conf::kLeAudioLocationFrontLeft, group_size, - group_id, 1 /* rank*/); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, true)).Times(1); + ConnectCsisDevice(test_address0, 1 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontLeft, + codec_spec_conf::kLeAudioLocationFrontLeft, group_size, group_id, 1 /* rank*/); // Second earbud const RawAddress test_address1 = GetTestAddress(1); - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, true)) - .Times(1); - ConnectCsisDevice(test_address1, 2 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontRight, - codec_spec_conf::kLeAudioLocationFrontRight, group_size, - group_id, 2 /* rank*/, true /*connect_through_csis*/); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, true)).Times(1); + ConnectCsisDevice(test_address1, 2 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontRight, + codec_spec_conf::kLeAudioLocationFrontRight, group_size, group_id, 2 /* rank*/, + true /*connect_through_csis*/); // Set group as active EXPECT_CALL(*mock_le_audio_source_hal_client_, Start(_, _, _)).Times(1); @@ -6759,28 +6182,20 @@ TEST_F(UnicastTest, UpdateActiveAudioConfigForLocalSource) { Mock::VerifyAndClearExpectations(mock_le_audio_source_hal_client_); // Start streaming - EXPECT_CALL(*mock_le_audio_source_hal_client_, UpdateAudioConfigToHal(_)) - .Times(1); - EXPECT_CALL(*mock_le_audio_sink_hal_client_, UpdateAudioConfigToHal(_)) - .Times(0); + EXPECT_CALL(*mock_le_audio_source_hal_client_, UpdateAudioConfigToHal(_)).Times(1); + EXPECT_CALL(*mock_le_audio_sink_hal_client_, UpdateAudioConfigToHal(_)).Times(0); EXPECT_CALL(*mock_codec_manager_, UpdateActiveAudioConfig(_, _, _)) - .Times(1) - .WillOnce( - [](const types::BidirectionalPair& stream_params, - types::BidirectionalPair delays_ms, - std::function - update_receiver) { + .Times(1) + .WillOnce([](const types::BidirectionalPair& stream_params, + types::BidirectionalPair delays_ms, + std::function + update_receiver) { bluetooth::le_audio::offload_config unicast_cfg; if (delays_ms.sink != 0) { - update_receiver( - unicast_cfg, - bluetooth::le_audio::types::kLeAudioDirectionSink); + update_receiver(unicast_cfg, bluetooth::le_audio::types::kLeAudioDirectionSink); } if (delays_ms.source != 0) { - update_receiver( - unicast_cfg, - bluetooth::le_audio::types::kLeAudioDirectionSource); + update_receiver(unicast_cfg, bluetooth::le_audio::types::kLeAudioDirectionSource); } }); StartStreaming(AUDIO_USAGE_MEDIA, AUDIO_CONTENT_TYPE_MUSIC, group_id); @@ -6804,29 +6219,23 @@ TEST_F(UnicastTest, TwoEarbudsStreamingContextSwitchNoReconfigure) { int group_id = 2; // Report working CSIS - ON_CALL(mock_csis_client_module_, IsCsisClientRunning()) - .WillByDefault(Return(true)); + ON_CALL(mock_csis_client_module_, IsCsisClientRunning()).WillByDefault(Return(true)); ON_CALL(mock_csis_client_module_, GetDesiredSize(group_id)) - .WillByDefault(Invoke([&](int group_id) { return group_size; })); + .WillByDefault(Invoke([&](int group_id) { return group_size; })); // First earbud const RawAddress test_address0 = GetTestAddress(0); - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, true)) - .Times(1); - ConnectCsisDevice(test_address0, 1 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontLeft, - codec_spec_conf::kLeAudioLocationFrontLeft, group_size, - group_id, 1 /* rank*/); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, true)).Times(1); + ConnectCsisDevice(test_address0, 1 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontLeft, + codec_spec_conf::kLeAudioLocationFrontLeft, group_size, group_id, 1 /* rank*/); // Second earbud const RawAddress test_address1 = GetTestAddress(1); - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, true)) - .Times(1); - ConnectCsisDevice(test_address1, 2 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontRight, - codec_spec_conf::kLeAudioLocationFrontRight, group_size, - group_id, 2 /* rank*/, true /*connect_through_csis*/); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, true)).Times(1); + ConnectCsisDevice(test_address1, 2 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontRight, + codec_spec_conf::kLeAudioLocationFrontRight, group_size, group_id, 2 /* rank*/, + true /*connect_through_csis*/); // Start streaming EXPECT_CALL(*mock_le_audio_source_hal_client_, Start(_, _, _)).Times(1); @@ -6839,13 +6248,10 @@ TEST_F(UnicastTest, TwoEarbudsStreamingContextSwitchNoReconfigure) { // with this new configuration auto initial_context = types::LeAudioContextType::NOTIFICATIONS; types::BidirectionalPair contexts = { - .sink = types::AudioContexts(initial_context), - .source = types::AudioContexts()}; - EXPECT_CALL(mock_state_machine_, StartStream(_, initial_context, contexts, _)) - .Times(1); + .sink = types::AudioContexts(initial_context), .source = types::AudioContexts()}; + EXPECT_CALL(mock_state_machine_, StartStream(_, initial_context, contexts, _)).Times(1); - StartStreaming(AUDIO_USAGE_NOTIFICATION, AUDIO_CONTENT_TYPE_UNKNOWN, - group_id); + StartStreaming(AUDIO_USAGE_NOTIFICATION, AUDIO_CONTENT_TYPE_UNKNOWN, group_id); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_state_machine_); @@ -6858,8 +6264,7 @@ TEST_F(UnicastTest, TwoEarbudsStreamingContextSwitchNoReconfigure) { EXPECT_CALL(*mock_le_audio_source_hal_client_, Start).Times(0); contexts = {.sink = types::AudioContexts(types::LeAudioContextType::ALERTS), .source = types::AudioContexts()}; - EXPECT_CALL(mock_state_machine_, StartStream(_, initial_context, contexts, _)) - .Times(1); + EXPECT_CALL(mock_state_machine_, StartStream(_, initial_context, contexts, _)).Times(1); UpdateLocalSourceMetadata(AUDIO_USAGE_ALARM, AUDIO_CONTENT_TYPE_UNKNOWN); SyncOnMainLoop(); @@ -6873,11 +6278,9 @@ TEST_F(UnicastTest, TwoEarbudsStreamingContextSwitchNoReconfigure) { EXPECT_CALL(*mock_le_audio_source_hal_client_, Stop).Times(0); EXPECT_CALL(*mock_le_audio_source_hal_client_, Start).Times(0); - contexts = { - .sink = types::AudioContexts(types::LeAudioContextType::EMERGENCYALARM), - .source = types::AudioContexts()}; - EXPECT_CALL(mock_state_machine_, StartStream(_, initial_context, contexts, _)) - .Times(1); + contexts = {.sink = types::AudioContexts(types::LeAudioContextType::EMERGENCYALARM), + .source = types::AudioContexts()}; + EXPECT_CALL(mock_state_machine_, StartStream(_, initial_context, contexts, _)).Times(1); UpdateLocalSourceMetadata(AUDIO_USAGE_EMERGENCY, AUDIO_CONTENT_TYPE_UNKNOWN); SyncOnMainLoop(); @@ -6889,13 +6292,10 @@ TEST_F(UnicastTest, TwoEarbudsStreamingContextSwitchNoReconfigure) { EXPECT_CALL(*mock_le_audio_source_hal_client_, OnDestroyed()).Times(0); EXPECT_CALL(*mock_le_audio_source_hal_client_, Stop).Times(0); EXPECT_CALL(*mock_le_audio_source_hal_client_, Start).Times(0); - contexts = { - .sink = types::AudioContexts(types::LeAudioContextType::INSTRUCTIONAL), - .source = types::AudioContexts()}; - EXPECT_CALL(mock_state_machine_, StartStream(_, initial_context, contexts, _)) - .Times(1); - UpdateLocalSourceMetadata(AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE, - AUDIO_CONTENT_TYPE_UNKNOWN); + contexts = {.sink = types::AudioContexts(types::LeAudioContextType::INSTRUCTIONAL), + .source = types::AudioContexts()}; + EXPECT_CALL(mock_state_machine_, StartStream(_, initial_context, contexts, _)).Times(1); + UpdateLocalSourceMetadata(AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE, AUDIO_CONTENT_TYPE_UNKNOWN); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); @@ -6907,29 +6307,23 @@ TEST_F(UnicastTest, TwoEarbudsStopConversational_StartStreamSonification) { int group_id = 2; // Report working CSIS - ON_CALL(mock_csis_client_module_, IsCsisClientRunning()) - .WillByDefault(Return(true)); + ON_CALL(mock_csis_client_module_, IsCsisClientRunning()).WillByDefault(Return(true)); ON_CALL(mock_csis_client_module_, GetDesiredSize(group_id)) - .WillByDefault(Invoke([&](int group_id) { return group_size; })); + .WillByDefault(Invoke([&](int group_id) { return group_size; })); // First earbud const RawAddress test_address0 = GetTestAddress(0); - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, true)) - .Times(1); - ConnectCsisDevice(test_address0, 1 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontLeft, - codec_spec_conf::kLeAudioLocationFrontLeft, group_size, - group_id, 1 /* rank*/); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, true)).Times(1); + ConnectCsisDevice(test_address0, 1 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontLeft, + codec_spec_conf::kLeAudioLocationFrontLeft, group_size, group_id, 1 /* rank*/); // Second earbud const RawAddress test_address1 = GetTestAddress(1); - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, true)) - .Times(1); - ConnectCsisDevice(test_address1, 2 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontRight, - codec_spec_conf::kLeAudioLocationFrontRight, group_size, - group_id, 2 /* rank*/, true /*connect_through_csis*/); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, true)).Times(1); + ConnectCsisDevice(test_address1, 2 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontRight, + codec_spec_conf::kLeAudioLocationFrontRight, group_size, group_id, 2 /* rank*/, + true /*connect_through_csis*/); // Start streaming EXPECT_CALL(*mock_le_audio_source_hal_client_, Start(_, _, _)).Times(1); @@ -6942,13 +6336,11 @@ TEST_F(UnicastTest, TwoEarbudsStopConversational_StartStreamSonification) { // with this new configuration auto initial_context = types::LeAudioContextType::CONVERSATIONAL; types::BidirectionalPair contexts = { - .sink = types::AudioContexts(initial_context), - .source = types::AudioContexts(initial_context)}; - EXPECT_CALL(mock_state_machine_, StartStream(_, initial_context, contexts, _)) - .Times(1); + .sink = types::AudioContexts(initial_context), + .source = types::AudioContexts(initial_context)}; + EXPECT_CALL(mock_state_machine_, StartStream(_, initial_context, contexts, _)).Times(1); - StartStreaming(AUDIO_USAGE_VOICE_COMMUNICATION, AUDIO_CONTENT_TYPE_SPEECH, - group_id); + StartStreaming(AUDIO_USAGE_VOICE_COMMUNICATION, AUDIO_CONTENT_TYPE_SPEECH, group_id); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_state_machine_); @@ -6961,12 +6353,11 @@ TEST_F(UnicastTest, TwoEarbudsStopConversational_StartStreamSonification) { Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); types::BidirectionalPair reconfigure_contexts = { - .sink = types::AudioContexts(types::LeAudioContextType::ALERTS), - .source = types::AudioContexts()}; + .sink = types::AudioContexts(types::LeAudioContextType::ALERTS), + .source = types::AudioContexts()}; - EXPECT_CALL(mock_state_machine_, - StartStream(_, initial_context, reconfigure_contexts, _)) - .Times(1); + EXPECT_CALL(mock_state_machine_, StartStream(_, initial_context, reconfigure_contexts, _)) + .Times(1); // Change context type but expect configuration to by as previous StartStreaming(AUDIO_USAGE_ALARM, AUDIO_CONTENT_TYPE_UNKNOWN, group_id); @@ -6983,9 +6374,8 @@ TEST_F(UnicastTest, TwoEarbudsStopConversational_StartStreamSonification) { auto reconfigure_context = types::LeAudioContextType::ALERTS; - EXPECT_CALL(mock_state_machine_, - StartStream(_, reconfigure_context, reconfigure_contexts, _)) - .Times(1); + EXPECT_CALL(mock_state_machine_, StartStream(_, reconfigure_context, reconfigure_contexts, _)) + .Times(1); // Update metadata StartStreaming(AUDIO_USAGE_ALARM, AUDIO_CONTENT_TYPE_UNKNOWN, group_id); @@ -6998,29 +6388,23 @@ TEST_F(UnicastTest, TwoEarbudsStreamingContextSwitchReconfigure) { int group_id = 2; // Report working CSIS - ON_CALL(mock_csis_client_module_, IsCsisClientRunning()) - .WillByDefault(Return(true)); + ON_CALL(mock_csis_client_module_, IsCsisClientRunning()).WillByDefault(Return(true)); ON_CALL(mock_csis_client_module_, GetDesiredSize(group_id)) - .WillByDefault(Invoke([&](int group_id) { return group_size; })); + .WillByDefault(Invoke([&](int group_id) { return group_size; })); // First earbud const RawAddress test_address0 = GetTestAddress(0); - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, true)) - .Times(1); - ConnectCsisDevice(test_address0, 1 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontLeft, - codec_spec_conf::kLeAudioLocationFrontLeft, group_size, - group_id, 1 /* rank*/); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, true)).Times(1); + ConnectCsisDevice(test_address0, 1 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontLeft, + codec_spec_conf::kLeAudioLocationFrontLeft, group_size, group_id, 1 /* rank*/); // Second earbud const RawAddress test_address1 = GetTestAddress(1); - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, true)) - .Times(1); - ConnectCsisDevice(test_address1, 2 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontRight, - codec_spec_conf::kLeAudioLocationFrontRight, group_size, - group_id, 2 /* rank*/, true /*connect_through_csis*/); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, true)).Times(1); + ConnectCsisDevice(test_address1, 2 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontRight, + codec_spec_conf::kLeAudioLocationFrontRight, group_size, group_id, 2 /* rank*/, + true /*connect_through_csis*/); constexpr int gmcs_ccid = 1; constexpr int gtbs_ccid = 2; @@ -7033,8 +6417,7 @@ TEST_F(UnicastTest, TwoEarbudsStreamingContextSwitchReconfigure) { LeAudioClient::Get()->GroupSetActive(group_id); SyncOnMainLoop(); - types::BidirectionalPair> ccids = {.sink = {gmcs_ccid}, - .source = {}}; + types::BidirectionalPair> ccids = {.sink = {gmcs_ccid}, .source = {}}; EXPECT_CALL(mock_state_machine_, StartStream(_, _, _, ccids)).Times(1); StartStreaming(AUDIO_USAGE_MEDIA, AUDIO_CONTENT_TYPE_MUSIC, group_id); @@ -7061,12 +6444,10 @@ TEST_F(UnicastTest, TwoEarbudsStreamingContextSwitchReconfigure) { // in the metadata for both directions. Can be called twice when one // direction resume after the other and metadata is updated. ccids = {.sink = {gtbs_ccid}, .source = {gtbs_ccid}}; - EXPECT_CALL( - mock_state_machine_, - StartStream(_, types::LeAudioContextType::CONVERSATIONAL, _, ccids)) - .Times(AtLeast(1)); - StartStreaming(AUDIO_USAGE_VOICE_COMMUNICATION, AUDIO_CONTENT_TYPE_SPEECH, - group_id); + EXPECT_CALL(mock_state_machine_, + StartStream(_, types::LeAudioContextType::CONVERSATIONAL, _, ccids)) + .Times(AtLeast(1)); + StartStreaming(AUDIO_USAGE_VOICE_COMMUNICATION, AUDIO_CONTENT_TYPE_SPEECH, group_id); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); @@ -7084,15 +6465,13 @@ TEST_F(UnicastTest, TwoEarbudsStreamingContextSwitchReconfigure) { // Switch back to MEDIA ccids = {.sink = {gmcs_ccid}, .source = {}}; types::BidirectionalPair contexts = { - .sink = types::AudioContexts(types::LeAudioContextType::MEDIA), - .source = types::AudioContexts()}; - EXPECT_CALL( - mock_state_machine_, - ConfigureStream(_, bluetooth::le_audio::types::LeAudioContextType::MEDIA, - contexts, ccids)) - .Times(1); - StartStreaming(AUDIO_USAGE_MEDIA, AUDIO_CONTENT_TYPE_MUSIC, group_id, - AUDIO_SOURCE_INVALID, true); + .sink = types::AudioContexts(types::LeAudioContextType::MEDIA), + .source = types::AudioContexts()}; + EXPECT_CALL(mock_state_machine_, + ConfigureStream(_, bluetooth::le_audio::types::LeAudioContextType::MEDIA, contexts, + ccids)) + .Times(1); + StartStreaming(AUDIO_USAGE_MEDIA, AUDIO_CONTENT_TYPE_MUSIC, group_id, AUDIO_SOURCE_INVALID, true); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_state_machine_); @@ -7113,29 +6492,23 @@ TEST_F(UnicastTest, TwoEarbudsVoipStreamingVerifyMetadataUpdate) { */ // Report working CSIS - ON_CALL(mock_csis_client_module_, IsCsisClientRunning()) - .WillByDefault(Return(true)); + ON_CALL(mock_csis_client_module_, IsCsisClientRunning()).WillByDefault(Return(true)); ON_CALL(mock_csis_client_module_, GetDesiredSize(group_id)) - .WillByDefault(Invoke([&](int group_id) { return group_size; })); + .WillByDefault(Invoke([&](int group_id) { return group_size; })); // First earbud const RawAddress test_address0 = GetTestAddress(0); - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, true)) - .Times(1); - ConnectCsisDevice(test_address0, 1 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontLeft, - codec_spec_conf::kLeAudioLocationFrontLeft, group_size, - group_id, 1 /* rank*/); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, true)).Times(1); + ConnectCsisDevice(test_address0, 1 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontLeft, + codec_spec_conf::kLeAudioLocationFrontLeft, group_size, group_id, 1 /* rank*/); // Second earbud const RawAddress test_address1 = GetTestAddress(1); - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, true)) - .Times(1); - ConnectCsisDevice(test_address1, 2 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontRight, - codec_spec_conf::kLeAudioLocationFrontRight, group_size, - group_id, 2 /* rank*/, true /*connect_through_csis*/); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, true)).Times(1); + ConnectCsisDevice(test_address1, 2 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontRight, + codec_spec_conf::kLeAudioLocationFrontRight, group_size, group_id, 2 /* rank*/, + true /*connect_through_csis*/); constexpr int gtbs_ccid = 2; @@ -7144,15 +6517,12 @@ TEST_F(UnicastTest, TwoEarbudsVoipStreamingVerifyMetadataUpdate) { SyncOnMainLoop(); // VOIP not using Telecom API has no ccids. - types::BidirectionalPair> ccids = {.sink = {}, - .source = {}}; - EXPECT_CALL( - mock_state_machine_, - StartStream(_, types::LeAudioContextType::CONVERSATIONAL, _, ccids)) - .Times(AtLeast(1)); + types::BidirectionalPair> ccids = {.sink = {}, .source = {}}; + EXPECT_CALL(mock_state_machine_, + StartStream(_, types::LeAudioContextType::CONVERSATIONAL, _, ccids)) + .Times(AtLeast(1)); - UpdateLocalSourceMetadata(AUDIO_USAGE_VOICE_COMMUNICATION, - AUDIO_CONTENT_TYPE_SPEECH); + UpdateLocalSourceMetadata(AUDIO_USAGE_VOICE_COMMUNICATION, AUDIO_CONTENT_TYPE_SPEECH); UpdateLocalSinkMetadata(AUDIO_SOURCE_MIC); LocalAudioSourceResume(); @@ -7169,13 +6539,11 @@ TEST_F(UnicastTest, TwoEarbudsVoipStreamingVerifyMetadataUpdate) { TestAudioDataTransfer(group_id, cis_count_out, cis_count_in, 1920, 0); types::BidirectionalPair contexts = { - .sink = types::AudioContexts(types::LeAudioContextType::CONVERSATIONAL), - .source = - types::AudioContexts(types::LeAudioContextType::CONVERSATIONAL)}; + .sink = types::AudioContexts(types::LeAudioContextType::CONVERSATIONAL), + .source = types::AudioContexts(types::LeAudioContextType::CONVERSATIONAL)}; EXPECT_CALL(mock_state_machine_, - StartStream(_, types::LeAudioContextType::CONVERSATIONAL, - contexts, ccids)) - .Times(AtLeast(1)); + StartStream(_, types::LeAudioContextType::CONVERSATIONAL, contexts, ccids)) + .Times(AtLeast(1)); LocalAudioSinkResume(); SyncOnMainLoop(); @@ -7193,29 +6561,23 @@ TEST_F(UnicastTest, TwoReconfigureAndVerifyEnableContextType) { */ // Report working CSIS - ON_CALL(mock_csis_client_module_, IsCsisClientRunning()) - .WillByDefault(Return(true)); + ON_CALL(mock_csis_client_module_, IsCsisClientRunning()).WillByDefault(Return(true)); ON_CALL(mock_csis_client_module_, GetDesiredSize(group_id)) - .WillByDefault(Invoke([&](int group_id) { return group_size; })); + .WillByDefault(Invoke([&](int group_id) { return group_size; })); // First earbud const RawAddress test_address0 = GetTestAddress(0); - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, true)) - .Times(1); - ConnectCsisDevice(test_address0, 1 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontLeft, - codec_spec_conf::kLeAudioLocationFrontLeft, group_size, - group_id, 1 /* rank*/); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, true)).Times(1); + ConnectCsisDevice(test_address0, 1 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontLeft, + codec_spec_conf::kLeAudioLocationFrontLeft, group_size, group_id, 1 /* rank*/); // Second earbud const RawAddress test_address1 = GetTestAddress(1); - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, true)) - .Times(1); - ConnectCsisDevice(test_address1, 2 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontRight, - codec_spec_conf::kLeAudioLocationFrontRight, group_size, - group_id, 2 /* rank*/, true /*connect_through_csis*/); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, true)).Times(1); + ConnectCsisDevice(test_address1, 2 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontRight, + codec_spec_conf::kLeAudioLocationFrontRight, group_size, group_id, 2 /* rank*/, + true /*connect_through_csis*/); constexpr int gmcs_ccid = 1; constexpr int gtbs_ccid = 2; @@ -7231,8 +6593,7 @@ TEST_F(UnicastTest, TwoReconfigureAndVerifyEnableContextType) { // Update metadata on local audio sink UpdateLocalSinkMetadata(AUDIO_SOURCE_MIC); - types::BidirectionalPair> ccids = {.sink = {gmcs_ccid}, - .source = {}}; + types::BidirectionalPair> ccids = {.sink = {gmcs_ccid}, .source = {}}; EXPECT_CALL(mock_state_machine_, StartStream(_, _, _, ccids)).Times(1); StartStreaming(AUDIO_USAGE_MEDIA, AUDIO_CONTENT_TYPE_MUSIC, group_id); @@ -7251,28 +6612,24 @@ TEST_F(UnicastTest, TwoReconfigureAndVerifyEnableContextType) { // direction resume after the other and metadata is updated. ccids = {.sink = {gtbs_ccid}, .source = {gtbs_ccid}}; types::BidirectionalPair conversiational_contexts = { - .sink = types::AudioContexts(types::LeAudioContextType::CONVERSATIONAL), - .source = - types::AudioContexts(types::LeAudioContextType::CONVERSATIONAL)}; + .sink = types::AudioContexts(types::LeAudioContextType::CONVERSATIONAL), + .source = types::AudioContexts(types::LeAudioContextType::CONVERSATIONAL)}; - EXPECT_CALL( - mock_state_machine_, - ConfigureStream(_, types::LeAudioContextType::CONVERSATIONAL, _, _)) - .Times(AtLeast(1)); + EXPECT_CALL(mock_state_machine_, + ConfigureStream(_, types::LeAudioContextType::CONVERSATIONAL, _, _)) + .Times(AtLeast(1)); // Update metadata and resume - UpdateLocalSourceMetadata(AUDIO_USAGE_VOICE_COMMUNICATION, - AUDIO_CONTENT_TYPE_SPEECH, true); + UpdateLocalSourceMetadata(AUDIO_USAGE_VOICE_COMMUNICATION, AUDIO_CONTENT_TYPE_SPEECH, true); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_state_machine_); Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); Mock::VerifyAndClearExpectations(mock_le_audio_source_hal_client_); - EXPECT_CALL(mock_state_machine_, - StartStream(_, types::LeAudioContextType::CONVERSATIONAL, - conversiational_contexts, ccids)) - .Times(AtLeast(1)); + EXPECT_CALL(mock_state_machine_, StartStream(_, types::LeAudioContextType::CONVERSATIONAL, + conversiational_contexts, ccids)) + .Times(AtLeast(1)); LeAudioClient::Get()->SetInCall(true); @@ -7287,20 +6644,17 @@ TEST_F(UnicastTest, TwoEarbuds2ndLateConnect) { int group_id = 2; // Report working CSIS - ON_CALL(mock_csis_client_module_, IsCsisClientRunning()) - .WillByDefault(Return(true)); + ON_CALL(mock_csis_client_module_, IsCsisClientRunning()).WillByDefault(Return(true)); ON_CALL(mock_csis_client_module_, GetDesiredSize(group_id)) - .WillByDefault(Invoke([&](int group_id) { return group_size; })); + .WillByDefault(Invoke([&](int group_id) { return group_size; })); const RawAddress test_address0 = GetTestAddress(0); const RawAddress test_address1 = GetTestAddress(1); // First earbud - ConnectCsisDevice(test_address0, 1 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontLeft, - codec_spec_conf::kLeAudioLocationFrontLeft, group_size, - group_id, 1 /* rank*/); + ConnectCsisDevice(test_address0, 1 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontLeft, + codec_spec_conf::kLeAudioLocationFrontLeft, group_size, group_id, 1 /* rank*/); // Start streaming EXPECT_CALL(*mock_le_audio_source_hal_client_, Start(_, _, _)).Times(1); @@ -7320,10 +6674,9 @@ TEST_F(UnicastTest, TwoEarbuds2ndLateConnect) { TestAudioDataTransfer(group_id, cis_count_out, cis_count_in, 1920); // Second earbud connects during stream - ConnectCsisDevice(test_address1, 2 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontRight, - codec_spec_conf::kLeAudioLocationFrontRight, group_size, - group_id, 2 /* rank*/, true /*connect_through_csis*/); + ConnectCsisDevice(test_address1, 2 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontRight, + codec_spec_conf::kLeAudioLocationFrontRight, group_size, group_id, 2 /* rank*/, + true /*connect_through_csis*/); cis_count_out = 2; cis_count_in = 0; @@ -7349,26 +6702,22 @@ TEST_F(UnicastTest, LateStreamConnectBasedOnContextType) { */ // Report working CSIS - ON_CALL(mock_csis_client_module_, IsCsisClientRunning()) - .WillByDefault(Return(true)); + ON_CALL(mock_csis_client_module_, IsCsisClientRunning()).WillByDefault(Return(true)); ON_CALL(mock_csis_client_module_, GetDesiredSize(group_id)) - .WillByDefault(Invoke([&](int group_id) { return group_size; })); + .WillByDefault(Invoke([&](int group_id) { return group_size; })); const RawAddress test_address0 = GetTestAddress(0); const RawAddress test_address1 = GetTestAddress(1); // First earbud connects - ConnectCsisDevice(test_address0, 1 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontLeft, - codec_spec_conf::kLeAudioLocationFrontLeft, group_size, - group_id, 1 /* rank*/); + ConnectCsisDevice(test_address0, 1 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontLeft, + codec_spec_conf::kLeAudioLocationFrontLeft, group_size, group_id, 1 /* rank*/); // Second earbud connects - ConnectCsisDevice(test_address1, 2 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontRight, - codec_spec_conf::kLeAudioLocationFrontRight, group_size, - group_id, 2 /* rank*/, true /*connect_through_csis*/); + ConnectCsisDevice(test_address1, 2 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontRight, + codec_spec_conf::kLeAudioLocationFrontRight, group_size, group_id, 2 /* rank*/, + true /*connect_through_csis*/); // Start streaming EXPECT_CALL(*mock_le_audio_source_hal_client_, Start(_, _, _)).Times(1); @@ -7377,8 +6726,7 @@ TEST_F(UnicastTest, LateStreamConnectBasedOnContextType) { SyncOnMainLoop(); /* Simulate available context type being cleared */ - InjectAvailableContextTypes(test_address1, 2, types::AudioContexts(0), - types::AudioContexts(0)); + InjectAvailableContextTypes(test_address1, 2, types::AudioContexts(0), types::AudioContexts(0)); // Block streaming state block_streaming_state_callback = true; @@ -7389,26 +6737,23 @@ TEST_F(UnicastTest, LateStreamConnectBasedOnContextType) { SyncOnMainLoop(); Mock::VerifyAndClearExpectations(mock_le_audio_source_hal_client_); - InjectAvailableContextTypes(test_address1, 2, - types::kLeAudioContextAllRemoteSinkOnly, + InjectAvailableContextTypes(test_address1, 2, types::kLeAudioContextAllRemoteSinkOnly, types::AudioContexts(0), false); // Now simulate group is finally streaming auto group = streaming_groups.at(group_id); do_in_main_thread( - FROM_HERE, - base::BindOnce( - [](int group_id, - bluetooth::le_audio::LeAudioGroupStateMachine::Callbacks* - state_machine_callbacks, - LeAudioDeviceGroup* group) { - group->SetState(types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + FROM_HERE, + base::BindOnce( + [](int group_id, + bluetooth::le_audio::LeAudioGroupStateMachine::Callbacks* + state_machine_callbacks, + LeAudioDeviceGroup* group) { + group->SetState(types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); - state_machine_callbacks->StatusReportCb( - group_id, GroupStreamStatus::STREAMING); - }, - group_id, base::Unretained(this->state_machine_callbacks_), - std::move(group))); + state_machine_callbacks->StatusReportCb(group_id, GroupStreamStatus::STREAMING); + }, + group_id, base::Unretained(this->state_machine_callbacks_), std::move(group))); SyncOnMainLoop(); @@ -7437,26 +6782,22 @@ TEST_F(UnicastTest, CheckDeviceIsNotAttachedToStreamWhenNotNeeded) { */ // Report working CSIS - ON_CALL(mock_csis_client_module_, IsCsisClientRunning()) - .WillByDefault(Return(true)); + ON_CALL(mock_csis_client_module_, IsCsisClientRunning()).WillByDefault(Return(true)); ON_CALL(mock_csis_client_module_, GetDesiredSize(group_id)) - .WillByDefault(Invoke([&](int group_id) { return group_size; })); + .WillByDefault(Invoke([&](int group_id) { return group_size; })); const RawAddress test_address0 = GetTestAddress(0); const RawAddress test_address1 = GetTestAddress(1); // First earbud connects - ConnectCsisDevice(test_address0, 1 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontLeft, - codec_spec_conf::kLeAudioLocationFrontLeft, group_size, - group_id, 1 /* rank*/); + ConnectCsisDevice(test_address0, 1 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontLeft, + codec_spec_conf::kLeAudioLocationFrontLeft, group_size, group_id, 1 /* rank*/); // Second earbud connects - ConnectCsisDevice(test_address1, 2 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontRight, - codec_spec_conf::kLeAudioLocationFrontRight, group_size, - group_id, 2 /* rank*/, true /*connect_through_csis*/); + ConnectCsisDevice(test_address1, 2 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontRight, + codec_spec_conf::kLeAudioLocationFrontRight, group_size, group_id, 2 /* rank*/, + true /*connect_through_csis*/); // Start streaming EXPECT_CALL(*mock_le_audio_source_hal_client_, Start(_, _, _)).Times(1); @@ -7473,26 +6814,23 @@ TEST_F(UnicastTest, CheckDeviceIsNotAttachedToStreamWhenNotNeeded) { SyncOnMainLoop(); Mock::VerifyAndClearExpectations(mock_le_audio_source_hal_client_); - InjectAvailableContextTypes(test_address1, 2, - types::kLeAudioContextAllRemoteSinkOnly, + InjectAvailableContextTypes(test_address1, 2, types::kLeAudioContextAllRemoteSinkOnly, types::AudioContexts(0), false); // Now simulate group is finally streaming auto group = streaming_groups.at(group_id); do_in_main_thread( - FROM_HERE, - base::BindOnce( - [](int group_id, - bluetooth::le_audio::LeAudioGroupStateMachine::Callbacks* - state_machine_callbacks, - LeAudioDeviceGroup* group) { - group->SetState(types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + FROM_HERE, + base::BindOnce( + [](int group_id, + bluetooth::le_audio::LeAudioGroupStateMachine::Callbacks* + state_machine_callbacks, + LeAudioDeviceGroup* group) { + group->SetState(types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); - state_machine_callbacks->StatusReportCb( - group_id, GroupStreamStatus::STREAMING); - }, - group_id, base::Unretained(this->state_machine_callbacks_), - std::move(group))); + state_machine_callbacks->StatusReportCb(group_id, GroupStreamStatus::STREAMING); + }, + group_id, base::Unretained(this->state_machine_callbacks_), std::move(group))); SyncOnMainLoop(); @@ -7506,8 +6844,7 @@ TEST_F(UnicastTest, CheckDeviceIsNotAttachedToStreamWhenNotNeeded) { SyncOnMainLoop(); } -TEST_F(UnicastTest, - ReconnectedDeviceNotAttachedToStreamBecauseOfNotAvailableContext) { +TEST_F(UnicastTest, ReconnectedDeviceNotAttachedToStreamBecauseOfNotAvailableContext) { uint8_t group_size = 2; int group_id = 2; @@ -7520,26 +6857,22 @@ TEST_F(UnicastTest, */ // Report working CSIS - ON_CALL(mock_csis_client_module_, IsCsisClientRunning()) - .WillByDefault(Return(true)); + ON_CALL(mock_csis_client_module_, IsCsisClientRunning()).WillByDefault(Return(true)); ON_CALL(mock_csis_client_module_, GetDesiredSize(group_id)) - .WillByDefault(Invoke([&](int group_id) { return group_size; })); + .WillByDefault(Invoke([&](int group_id) { return group_size; })); const RawAddress test_address0 = GetTestAddress(0); const RawAddress test_address1 = GetTestAddress(1); // First earbud connects - ConnectCsisDevice(test_address0, 1 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontLeft, - codec_spec_conf::kLeAudioLocationFrontLeft, group_size, - group_id, 1 /* rank*/); + ConnectCsisDevice(test_address0, 1 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontLeft, + codec_spec_conf::kLeAudioLocationFrontLeft, group_size, group_id, 1 /* rank*/); // Second earbud connects - ConnectCsisDevice(test_address1, 2 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontRight, - codec_spec_conf::kLeAudioLocationFrontRight, group_size, - group_id, 2 /* rank*/, true /*connect_through_csis*/); + ConnectCsisDevice(test_address1, 2 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontRight, + codec_spec_conf::kLeAudioLocationFrontRight, group_size, group_id, 2 /* rank*/, + true /*connect_through_csis*/); // Start streaming EXPECT_CALL(*mock_le_audio_source_hal_client_, Start(_, _, _)).Times(1); @@ -7565,8 +6898,8 @@ TEST_F(UnicastTest, auto device = group->GetFirstDevice(); /* Simulate available context type being cleared */ - InjectAvailableContextTypes(device->address_, device->conn_id_, - types::AudioContexts(0), types::AudioContexts(0)); + InjectAvailableContextTypes(device->address_, device->conn_id_, types::AudioContexts(0), + types::AudioContexts(0)); /* Simulate ASE releasing and CIS Disconnection */ for (auto& ase : device->ases_) { @@ -7576,10 +6909,8 @@ TEST_F(UnicastTest, } std::vector releasing_state = { - ase.id, static_cast( - types::AseState::BTA_LE_AUDIO_ASE_STATE_RELEASING)}; - InjectNotificationEvent(device->address_, device->conn_id_, - ase.hdls.val_hdl, releasing_state); + ase.id, static_cast(types::AseState::BTA_LE_AUDIO_ASE_STATE_RELEASING)}; + InjectNotificationEvent(device->address_, device->conn_id_, ase.hdls.val_hdl, releasing_state); SyncOnMainLoop(); InjectCisDisconnected(group_id, ase.cis_conn_hdl); SyncOnMainLoop(); @@ -7590,9 +6921,8 @@ TEST_F(UnicastTest, TestAudioDataTransfer(group_id, cis_count_out, cis_count_in, 1920); /* Device A will disconnect, and do not reconnect automatically */ - ON_CALL(mock_gatt_interface_, - Open(_, device->address_, BTM_BLE_DIRECT_CONNECTION, _)) - .WillByDefault(Return()); + ON_CALL(mock_gatt_interface_, Open(_, device->address_, BTM_BLE_DIRECT_CONNECTION, _)) + .WillByDefault(Return()); /* Disconnect first device */ auto conn_id = device->conn_id_; @@ -7622,26 +6952,22 @@ TEST_F(UnicastTest, TwoEarbuds2ndReleaseAseRemoveAvailableContextAndBack) { */ // Report working CSIS - ON_CALL(mock_csis_client_module_, IsCsisClientRunning()) - .WillByDefault(Return(true)); + ON_CALL(mock_csis_client_module_, IsCsisClientRunning()).WillByDefault(Return(true)); ON_CALL(mock_csis_client_module_, GetDesiredSize(group_id)) - .WillByDefault(Invoke([&](int group_id) { return group_size; })); + .WillByDefault(Invoke([&](int group_id) { return group_size; })); const RawAddress test_address0 = GetTestAddress(0); const RawAddress test_address1 = GetTestAddress(1); // First earbud connects - ConnectCsisDevice(test_address0, 1 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontLeft, - codec_spec_conf::kLeAudioLocationFrontLeft, group_size, - group_id, 1 /* rank*/); + ConnectCsisDevice(test_address0, 1 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontLeft, + codec_spec_conf::kLeAudioLocationFrontLeft, group_size, group_id, 1 /* rank*/); // Second earbud connects - ConnectCsisDevice(test_address1, 2 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontRight, - codec_spec_conf::kLeAudioLocationFrontRight, group_size, - group_id, 2 /* rank*/, true /*connect_through_csis*/); + ConnectCsisDevice(test_address1, 2 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontRight, + codec_spec_conf::kLeAudioLocationFrontRight, group_size, group_id, 2 /* rank*/, + true /*connect_through_csis*/); // Start streaming EXPECT_CALL(*mock_le_audio_source_hal_client_, Start(_, _, _)).Times(1); @@ -7667,8 +6993,8 @@ TEST_F(UnicastTest, TwoEarbuds2ndReleaseAseRemoveAvailableContextAndBack) { auto device = group->GetFirstDevice(); /* Simulate available context type being cleared */ - InjectAvailableContextTypes(device->address_, device->conn_id_, - types::AudioContexts(0), types::AudioContexts(0)); + InjectAvailableContextTypes(device->address_, device->conn_id_, types::AudioContexts(0), + types::AudioContexts(0)); /* Simulate ASE releasing and CIS Disconnection */ for (auto& ase : device->ases_) { @@ -7678,10 +7004,8 @@ TEST_F(UnicastTest, TwoEarbuds2ndReleaseAseRemoveAvailableContextAndBack) { } std::vector releasing_state = { - ase.id, static_cast( - types::AseState::BTA_LE_AUDIO_ASE_STATE_RELEASING)}; - InjectNotificationEvent(device->address_, device->conn_id_, - ase.hdls.val_hdl, releasing_state); + ase.id, static_cast(types::AseState::BTA_LE_AUDIO_ASE_STATE_RELEASING)}; + InjectNotificationEvent(device->address_, device->conn_id_, ase.hdls.val_hdl, releasing_state); SyncOnMainLoop(); InjectCisDisconnected(group_id, ase.cis_conn_hdl); SyncOnMainLoop(); @@ -7692,8 +7016,7 @@ TEST_F(UnicastTest, TwoEarbuds2ndReleaseAseRemoveAvailableContextAndBack) { TestAudioDataTransfer(group_id, cis_count_out, cis_count_in, 1920); /* Bring back available context types */ - InjectAvailableContextTypes(device->address_, device->conn_id_, - types::kLeAudioContextAllTypes, + InjectAvailableContextTypes(device->address_, device->conn_id_, types::kLeAudioContextAllTypes, types::kLeAudioContextAllTypes); /* Check both devices are streaming */ @@ -7717,35 +7040,29 @@ TEST_F(UnicastTest, StartStream_AvailableContextTypeNotifiedLater) { */ // Report working CSIS - ON_CALL(mock_csis_client_module_, IsCsisClientRunning()) - .WillByDefault(Return(true)); + ON_CALL(mock_csis_client_module_, IsCsisClientRunning()).WillByDefault(Return(true)); ON_CALL(mock_csis_client_module_, GetDesiredSize(group_id)) - .WillByDefault(Invoke([&](int group_id) { return group_size; })); + .WillByDefault(Invoke([&](int group_id) { return group_size; })); const RawAddress test_address0 = GetTestAddress(0); const RawAddress test_address1 = GetTestAddress(1); // First earbud connects - ConnectCsisDevice(test_address0, 1 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontLeft, - codec_spec_conf::kLeAudioLocationFrontLeft, group_size, - group_id, 1 /* rank*/); + ConnectCsisDevice(test_address0, 1 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontLeft, + codec_spec_conf::kLeAudioLocationFrontLeft, group_size, group_id, 1 /* rank*/); // Second earbud connects - ConnectCsisDevice(test_address1, 2 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontRight, - codec_spec_conf::kLeAudioLocationFrontRight, group_size, - group_id, 2 /* rank*/, true /*connect_through_csis*/); + ConnectCsisDevice(test_address1, 2 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontRight, + codec_spec_conf::kLeAudioLocationFrontRight, group_size, group_id, 2 /* rank*/, + true /*connect_through_csis*/); // Inject Supported and available context types auto sink_available_contexts = types::kLeAudioContextAllRemoteSinkOnly; auto source_available_contexts = types::kLeAudioContextAllRemoteSource; - InjectAvailableContextTypes(test_address0, 1, sink_available_contexts, - source_available_contexts); - InjectAvailableContextTypes(test_address1, 2, sink_available_contexts, - source_available_contexts); + InjectAvailableContextTypes(test_address0, 1, sink_available_contexts, source_available_contexts); + InjectAvailableContextTypes(test_address1, 2, sink_available_contexts, source_available_contexts); // Start streaming EXPECT_CALL(*mock_le_audio_source_hal_client_, Start(_, _, _)).Times(1); EXPECT_CALL(*mock_le_audio_sink_hal_client_, Start(_, _, _)).Times(1); @@ -7753,14 +7070,12 @@ TEST_F(UnicastTest, StartStream_AvailableContextTypeNotifiedLater) { SyncOnMainLoop(); BidirectionalPair contexts = { - .sink = types::AudioContexts(types::LeAudioContextType::MEDIA), - .source = types::AudioContexts()}; + .sink = types::AudioContexts(types::LeAudioContextType::MEDIA), + .source = types::AudioContexts()}; - EXPECT_CALL( - mock_state_machine_, - StartStream(_, bluetooth::le_audio::types::LeAudioContextType::MEDIA, - contexts, _)) - .Times(1); + EXPECT_CALL(mock_state_machine_, + StartStream(_, bluetooth::le_audio::types::LeAudioContextType::MEDIA, contexts, _)) + .Times(1); StartStreaming(AUDIO_USAGE_MEDIA, AUDIO_CONTENT_TYPE_MUSIC, group_id); Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); @@ -7786,26 +7101,22 @@ TEST_F(UnicastTest, ModifyContextTypeOnDeviceA_WhileDeviceB_IsDisconnected) { */ // Report working CSIS - ON_CALL(mock_csis_client_module_, IsCsisClientRunning()) - .WillByDefault(Return(true)); + ON_CALL(mock_csis_client_module_, IsCsisClientRunning()).WillByDefault(Return(true)); ON_CALL(mock_csis_client_module_, GetDesiredSize(group_id)) - .WillByDefault(Invoke([&](int group_id) { return group_size; })); + .WillByDefault(Invoke([&](int group_id) { return group_size; })); const RawAddress test_address0 = GetTestAddress(0); const RawAddress test_address1 = GetTestAddress(1); // First earbud connects - ConnectCsisDevice(test_address0, 1 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontLeft, - codec_spec_conf::kLeAudioLocationFrontLeft, group_size, - group_id, 1 /* rank*/); + ConnectCsisDevice(test_address0, 1 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontLeft, + codec_spec_conf::kLeAudioLocationFrontLeft, group_size, group_id, 1 /* rank*/); // Second earbud connects - ConnectCsisDevice(test_address1, 2 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontRight, - codec_spec_conf::kLeAudioLocationFrontRight, group_size, - group_id, 2 /* rank*/, true /*connect_through_csis*/); + ConnectCsisDevice(test_address1, 2 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontRight, + codec_spec_conf::kLeAudioLocationFrontRight, group_size, group_id, 2 /* rank*/, + true /*connect_through_csis*/); // Start streaming EXPECT_CALL(*mock_le_audio_source_hal_client_, Start(_, _, _)).Times(1); @@ -7814,14 +7125,12 @@ TEST_F(UnicastTest, ModifyContextTypeOnDeviceA_WhileDeviceB_IsDisconnected) { SyncOnMainLoop(); BidirectionalPair contexts = { - .sink = types::AudioContexts(types::LeAudioContextType::MEDIA), - .source = types::AudioContexts()}; + .sink = types::AudioContexts(types::LeAudioContextType::MEDIA), + .source = types::AudioContexts()}; - EXPECT_CALL( - mock_state_machine_, - StartStream(_, bluetooth::le_audio::types::LeAudioContextType::MEDIA, - contexts, _)) - .Times(1); + EXPECT_CALL(mock_state_machine_, + StartStream(_, bluetooth::le_audio::types::LeAudioContextType::MEDIA, contexts, _)) + .Times(1); StartStreaming(AUDIO_USAGE_MEDIA, AUDIO_CONTENT_TYPE_MUSIC, group_id); @@ -7842,9 +7151,8 @@ TEST_F(UnicastTest, ModifyContextTypeOnDeviceA_WhileDeviceB_IsDisconnected) { Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); // Device B got disconnected and will not reconnect. - ON_CALL(mock_gatt_interface_, - Open(_, test_address1, BTM_BLE_DIRECT_CONNECTION, _)) - .WillByDefault(Return()); + ON_CALL(mock_gatt_interface_, Open(_, test_address1, BTM_BLE_DIRECT_CONNECTION, _)) + .WillByDefault(Return()); InjectDisconnectedEvent(2, GATT_CONN_TERMINATE_PEER_USER); SyncOnMainLoop(); @@ -7857,16 +7165,14 @@ TEST_F(UnicastTest, ModifyContextTypeOnDeviceA_WhileDeviceB_IsDisconnected) { auto source_supported_context = types::kLeAudioContextAllRemoteSource; source_supported_context.set(LeAudioContextType::UNSPECIFIED); - InjectSupportedContextTypes(test_address0, 1, sink_supported_context, - source_supported_context); - InjectAvailableContextTypes(test_address0, 1, sink_supported_context, - source_supported_context); + InjectSupportedContextTypes(test_address0, 1, sink_supported_context, source_supported_context); + InjectAvailableContextTypes(test_address0, 1, sink_supported_context, source_supported_context); /* Android starts stream. */ EXPECT_CALL(mock_state_machine_, StartStream(_, _, _, _)).Times(0); - StartStreaming(AUDIO_USAGE_MEDIA, AUDIO_CONTENT_TYPE_MUSIC, group_id, - AUDIO_SOURCE_INVALID, false, false); + StartStreaming(AUDIO_USAGE_MEDIA, AUDIO_CONTENT_TYPE_MUSIC, group_id, AUDIO_SOURCE_INVALID, false, + false); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_state_machine_); @@ -7885,26 +7191,22 @@ TEST_F(UnicastTest, StartStreamToUnsupportedContextTypeUsingUnspecified) { */ // Report working CSIS - ON_CALL(mock_csis_client_module_, IsCsisClientRunning()) - .WillByDefault(Return(true)); + ON_CALL(mock_csis_client_module_, IsCsisClientRunning()).WillByDefault(Return(true)); ON_CALL(mock_csis_client_module_, GetDesiredSize(group_id)) - .WillByDefault(Invoke([&](int group_id) { return group_size; })); + .WillByDefault(Invoke([&](int group_id) { return group_size; })); const RawAddress test_address0 = GetTestAddress(0); const RawAddress test_address1 = GetTestAddress(1); // First earbud connects - ConnectCsisDevice(test_address0, 1 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontLeft, - codec_spec_conf::kLeAudioLocationFrontLeft, group_size, - group_id, 1 /* rank*/); + ConnectCsisDevice(test_address0, 1 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontLeft, + codec_spec_conf::kLeAudioLocationFrontLeft, group_size, group_id, 1 /* rank*/); // Second earbud connects - ConnectCsisDevice(test_address1, 2 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontRight, - codec_spec_conf::kLeAudioLocationFrontRight, group_size, - group_id, 2 /* rank*/, true /*connect_through_csis*/); + ConnectCsisDevice(test_address1, 2 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontRight, + codec_spec_conf::kLeAudioLocationFrontRight, group_size, group_id, 2 /* rank*/, + true /*connect_through_csis*/); // Inject Supported and available context types auto sink_supported_context = types::kLeAudioContextAllRemoteSinkOnly; @@ -7914,14 +7216,10 @@ TEST_F(UnicastTest, StartStreamToUnsupportedContextTypeUsingUnspecified) { auto source_supported_context = types::kLeAudioContextAllRemoteSource; source_supported_context.set(LeAudioContextType::UNSPECIFIED); - InjectSupportedContextTypes(test_address0, 1, sink_supported_context, - source_supported_context); - InjectAvailableContextTypes(test_address0, 1, sink_supported_context, - source_supported_context); - InjectSupportedContextTypes(test_address1, 2, sink_supported_context, - source_supported_context); - InjectAvailableContextTypes(test_address1, 2, sink_supported_context, - source_supported_context); + InjectSupportedContextTypes(test_address0, 1, sink_supported_context, source_supported_context); + InjectAvailableContextTypes(test_address0, 1, sink_supported_context, source_supported_context); + InjectSupportedContextTypes(test_address1, 2, sink_supported_context, source_supported_context); + InjectAvailableContextTypes(test_address1, 2, sink_supported_context, source_supported_context); // Start streaming EXPECT_CALL(*mock_le_audio_source_hal_client_, Start(_, _, _)).Times(1); EXPECT_CALL(*mock_le_audio_sink_hal_client_, Start(_, _, _)).Times(1); @@ -7929,18 +7227,15 @@ TEST_F(UnicastTest, StartStreamToUnsupportedContextTypeUsingUnspecified) { SyncOnMainLoop(); BidirectionalPair contexts = { - .sink = types::AudioContexts(types::LeAudioContextType::UNSPECIFIED), - .source = types::AudioContexts(0)}; + .sink = types::AudioContexts(types::LeAudioContextType::UNSPECIFIED), + .source = types::AudioContexts(0)}; EXPECT_CALL( - mock_state_machine_, - StartStream(_, - bluetooth::le_audio::types::LeAudioContextType::SOUNDEFFECTS, - contexts, _)) - .Times(1); + mock_state_machine_, + StartStream(_, bluetooth::le_audio::types::LeAudioContextType::SOUNDEFFECTS, contexts, _)) + .Times(1); - StartStreaming(AUDIO_USAGE_ASSISTANCE_SONIFICATION, - AUDIO_CONTENT_TYPE_SONIFICATION, group_id); + StartStreaming(AUDIO_USAGE_ASSISTANCE_SONIFICATION, AUDIO_CONTENT_TYPE_SONIFICATION, group_id); Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); Mock::VerifyAndClearExpectations(mock_le_audio_source_hal_client_); @@ -7952,8 +7247,7 @@ TEST_F(UnicastTest, StartStreamToUnsupportedContextTypeUsingUnspecified) { TestAudioDataTransfer(group_id, cis_count_out, cis_count_in, 1920); } -TEST_F(UnicastTest, - StartStreamToUnsupportedContextTypeUnspecifiedNotAvailable) { +TEST_F(UnicastTest, StartStreamToUnsupportedContextTypeUnspecifiedNotAvailable) { uint8_t group_size = 2; int group_id = 2; @@ -7966,26 +7260,22 @@ TEST_F(UnicastTest, */ // Report working CSIS - ON_CALL(mock_csis_client_module_, IsCsisClientRunning()) - .WillByDefault(Return(true)); + ON_CALL(mock_csis_client_module_, IsCsisClientRunning()).WillByDefault(Return(true)); ON_CALL(mock_csis_client_module_, GetDesiredSize(group_id)) - .WillByDefault(Invoke([&](int group_id) { return group_size; })); + .WillByDefault(Invoke([&](int group_id) { return group_size; })); const RawAddress test_address0 = GetTestAddress(0); const RawAddress test_address1 = GetTestAddress(1); // First earbud connects - ConnectCsisDevice(test_address0, 1 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontLeft, - codec_spec_conf::kLeAudioLocationFrontLeft, group_size, - group_id, 1 /* rank*/); + ConnectCsisDevice(test_address0, 1 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontLeft, + codec_spec_conf::kLeAudioLocationFrontLeft, group_size, group_id, 1 /* rank*/); // Second earbud connects - ConnectCsisDevice(test_address1, 2 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontRight, - codec_spec_conf::kLeAudioLocationFrontRight, group_size, - group_id, 2 /* rank*/, true /*connect_through_csis*/); + ConnectCsisDevice(test_address1, 2 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontRight, + codec_spec_conf::kLeAudioLocationFrontRight, group_size, group_id, 2 /* rank*/, + true /*connect_through_csis*/); // Inject Supported and available context types auto sink_supported_context = types::kLeAudioContextAllRemoteSinkOnly; @@ -7995,10 +7285,8 @@ TEST_F(UnicastTest, auto source_supported_context = types::kLeAudioContextAllRemoteSource; source_supported_context.set(LeAudioContextType::UNSPECIFIED); - InjectSupportedContextTypes(test_address0, 1, sink_supported_context, - source_supported_context); - InjectSupportedContextTypes(test_address1, 2, sink_supported_context, - source_supported_context); + InjectSupportedContextTypes(test_address0, 1, sink_supported_context, source_supported_context); + InjectSupportedContextTypes(test_address1, 2, sink_supported_context, source_supported_context); auto sink_available_context = sink_supported_context; sink_available_context.unset(LeAudioContextType::UNSPECIFIED); @@ -8006,10 +7294,8 @@ TEST_F(UnicastTest, auto source_available_context = source_supported_context; source_available_context.unset(LeAudioContextType::UNSPECIFIED); - InjectAvailableContextTypes(test_address0, 1, sink_available_context, - source_available_context); - InjectAvailableContextTypes(test_address1, 2, sink_available_context, - source_available_context); + InjectAvailableContextTypes(test_address0, 1, sink_available_context, source_available_context); + InjectAvailableContextTypes(test_address1, 2, sink_available_context, source_available_context); // Start streaming EXPECT_CALL(*mock_le_audio_source_hal_client_, Start(_, _, _)).Times(1); EXPECT_CALL(*mock_le_audio_sink_hal_client_, Start(_, _, _)).Times(1); @@ -8017,18 +7303,15 @@ TEST_F(UnicastTest, SyncOnMainLoop(); BidirectionalPair contexts = { - .sink = types::AudioContexts(types::LeAudioContextType::UNSPECIFIED), - .source = types::AudioContexts()}; + .sink = types::AudioContexts(types::LeAudioContextType::UNSPECIFIED), + .source = types::AudioContexts()}; EXPECT_CALL( - mock_state_machine_, - StartStream(_, - bluetooth::le_audio::types::LeAudioContextType::SOUNDEFFECTS, - contexts, _)) - .Times(0); - - StartStreaming(AUDIO_USAGE_ASSISTANCE_SONIFICATION, - AUDIO_CONTENT_TYPE_SONIFICATION, group_id, + mock_state_machine_, + StartStream(_, bluetooth::le_audio::types::LeAudioContextType::SOUNDEFFECTS, contexts, _)) + .Times(0); + + StartStreaming(AUDIO_USAGE_ASSISTANCE_SONIFICATION, AUDIO_CONTENT_TYPE_SONIFICATION, group_id, AUDIO_SOURCE_INVALID, false, false); Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); @@ -8056,26 +7339,22 @@ TEST_F(UnicastTest, StartStreamToSupportedContextTypeThenMixUnavailable) { */ // Report working CSIS - ON_CALL(mock_csis_client_module_, IsCsisClientRunning()) - .WillByDefault(Return(true)); + ON_CALL(mock_csis_client_module_, IsCsisClientRunning()).WillByDefault(Return(true)); ON_CALL(mock_csis_client_module_, GetDesiredSize(group_id)) - .WillByDefault(Invoke([&](int group_id) { return group_size; })); + .WillByDefault(Invoke([&](int group_id) { return group_size; })); const RawAddress test_address0 = GetTestAddress(0); const RawAddress test_address1 = GetTestAddress(1); // First earbud connects - ConnectCsisDevice(test_address0, 1 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontLeft, - codec_spec_conf::kLeAudioLocationFrontLeft, group_size, - group_id, 1 /* rank*/); + ConnectCsisDevice(test_address0, 1 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontLeft, + codec_spec_conf::kLeAudioLocationFrontLeft, group_size, group_id, 1 /* rank*/); // Second earbud connects - ConnectCsisDevice(test_address1, 2 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontRight, - codec_spec_conf::kLeAudioLocationFrontRight, group_size, - group_id, 2 /* rank*/, true /*connect_through_csis*/); + ConnectCsisDevice(test_address1, 2 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontRight, + codec_spec_conf::kLeAudioLocationFrontRight, group_size, group_id, 2 /* rank*/, + true /*connect_through_csis*/); // Start streaming EXPECT_CALL(*mock_le_audio_source_hal_client_, Start(_, _, _)).Times(1); @@ -8084,14 +7363,12 @@ TEST_F(UnicastTest, StartStreamToSupportedContextTypeThenMixUnavailable) { SyncOnMainLoop(); BidirectionalPair contexts = { - .sink = types::AudioContexts(types::LeAudioContextType::MEDIA), - .source = types::AudioContexts()}; + .sink = types::AudioContexts(types::LeAudioContextType::MEDIA), + .source = types::AudioContexts()}; - EXPECT_CALL( - mock_state_machine_, - StartStream(_, bluetooth::le_audio::types::LeAudioContextType::MEDIA, - contexts, _)) - .Times(1); + EXPECT_CALL(mock_state_machine_, + StartStream(_, bluetooth::le_audio::types::LeAudioContextType::MEDIA, contexts, _)) + .Times(1); StartStreaming(AUDIO_USAGE_MEDIA, AUDIO_CONTENT_TYPE_MUSIC, group_id); @@ -8110,17 +7387,14 @@ TEST_F(UnicastTest, StartStreamToSupportedContextTypeThenMixUnavailable) { contexts.sink = types::AudioContexts(types::LeAudioContextType::MEDIA | types::LeAudioContextType::SOUNDEFFECTS); - EXPECT_CALL( - mock_state_machine_, - StartStream(_, bluetooth::le_audio::types::LeAudioContextType::MEDIA, - contexts, _)) - .Times(1); + EXPECT_CALL(mock_state_machine_, + StartStream(_, bluetooth::le_audio::types::LeAudioContextType::MEDIA, contexts, _)) + .Times(1); /* Simulate metadata update, expect upadate , metadata */ std::vector tracks = { - {{AUDIO_USAGE_MEDIA, AUDIO_CONTENT_TYPE_MUSIC, 0}, - {AUDIO_USAGE_ASSISTANCE_SONIFICATION, AUDIO_CONTENT_TYPE_SONIFICATION, - 0}}}; + {{AUDIO_USAGE_MEDIA, AUDIO_CONTENT_TYPE_MUSIC, 0}, + {AUDIO_USAGE_ASSISTANCE_SONIFICATION, AUDIO_CONTENT_TYPE_SONIFICATION, 0}}}; UpdateLocalSourceMetadata(tracks); SyncOnMainLoop(); @@ -8142,36 +7416,28 @@ TEST_F(UnicastTest, StartStreamToSupportedContextTypeThenMixUnavailable) { auto source_supported_context = types::kLeAudioContextAllRemoteSource; source_supported_context.set(LeAudioContextType::UNSPECIFIED); - InjectSupportedContextTypes(test_address0, 1, sink_supported_context, - source_supported_context); - InjectAvailableContextTypes(test_address0, 1, sink_supported_context, - source_supported_context); - InjectSupportedContextTypes(test_address1, 2, sink_supported_context, - source_supported_context); - InjectAvailableContextTypes(test_address1, 2, sink_supported_context, - source_supported_context); + InjectSupportedContextTypes(test_address0, 1, sink_supported_context, source_supported_context); + InjectAvailableContextTypes(test_address0, 1, sink_supported_context, source_supported_context); + InjectSupportedContextTypes(test_address1, 2, sink_supported_context, source_supported_context); + InjectAvailableContextTypes(test_address1, 2, sink_supported_context, source_supported_context); // Verify cache has been removed due to available context change - ASSERT_EQ(nullptr, - group->GetCachedConfiguration(types::LeAudioContextType::MEDIA)); + ASSERT_EQ(nullptr, group->GetCachedConfiguration(types::LeAudioContextType::MEDIA)); /* Start Media again */ contexts.sink = types::AudioContexts(types::LeAudioContextType::MEDIA); - EXPECT_CALL( - mock_state_machine_, - StartStream(_, bluetooth::le_audio::types::LeAudioContextType::MEDIA, - contexts, _)) - .Times(1); + EXPECT_CALL(mock_state_machine_, + StartStream(_, bluetooth::le_audio::types::LeAudioContextType::MEDIA, contexts, _)) + .Times(1); StartStreaming(AUDIO_USAGE_MEDIA, AUDIO_CONTENT_TYPE_MUSIC, group_id); SyncOnMainLoop(); // Verify cache has been rebuilt - ASSERT_NE(nullptr, - group->GetCachedConfiguration(types::LeAudioContextType::MEDIA)); + ASSERT_NE(nullptr, group->GetCachedConfiguration(types::LeAudioContextType::MEDIA)); ASSERT_TRUE(group->GetCachedConfiguration(types::LeAudioContextType::MEDIA) - ->confs.get(le_audio::types::kLeAudioDirectionSink) - .size()); + ->confs.get(le_audio::types::kLeAudioDirectionSink) + .size()); Mock::VerifyAndClearExpectations(&mock_state_machine_); Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); @@ -8181,11 +7447,9 @@ TEST_F(UnicastTest, StartStreamToSupportedContextTypeThenMixUnavailable) { TestAudioDataTransfer(group_id, cis_count_out, cis_count_in, 1920); /* Update metadata, and do not expect new context type*/ - EXPECT_CALL( - mock_state_machine_, - StartStream(_, bluetooth::le_audio::types::LeAudioContextType::MEDIA, - contexts, _)) - .Times(1); + EXPECT_CALL(mock_state_machine_, + StartStream(_, bluetooth::le_audio::types::LeAudioContextType::MEDIA, contexts, _)) + .Times(1); /* Simulate metadata update */ UpdateLocalSourceMetadata(tracks); @@ -8198,25 +7462,21 @@ TEST_F(UnicastTest, TwoEarbuds2ndDisconnected) { int group_id = 2; // Report working CSIS - ON_CALL(mock_csis_client_module_, IsCsisClientRunning()) - .WillByDefault(Return(true)); + ON_CALL(mock_csis_client_module_, IsCsisClientRunning()).WillByDefault(Return(true)); ON_CALL(mock_csis_client_module_, GetDesiredSize(group_id)) - .WillByDefault(Invoke([&](int group_id) { return group_size; })); + .WillByDefault(Invoke([&](int group_id) { return group_size; })); // First earbud const RawAddress test_address0 = GetTestAddress(0); - ConnectCsisDevice(test_address0, 1 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontLeft, - codec_spec_conf::kLeAudioLocationFrontLeft, group_size, - group_id, 1 /* rank*/); + ConnectCsisDevice(test_address0, 1 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontLeft, + codec_spec_conf::kLeAudioLocationFrontLeft, group_size, group_id, 1 /* rank*/); // Second earbud const RawAddress test_address1 = GetTestAddress(1); - ConnectCsisDevice(test_address1, 2 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontRight, - codec_spec_conf::kLeAudioLocationFrontRight, group_size, - group_id, 2 /* rank*/, true /*connect_through_csis*/); + ConnectCsisDevice(test_address1, 2 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontRight, + codec_spec_conf::kLeAudioLocationFrontRight, group_size, group_id, 2 /* rank*/, + true /*connect_through_csis*/); // Audio sessions are started only when device gets active EXPECT_CALL(*mock_le_audio_source_hal_client_, Start(_, _, _)).Times(1); @@ -8246,21 +7506,19 @@ TEST_F(UnicastTest, TwoEarbuds2ndDisconnected) { } /* Disconnect ACL and do not reconnect. */ - ON_CALL(mock_gatt_interface_, - Open(_, device->address_, BTM_BLE_DIRECT_CONNECTION, _)) - .WillByDefault(Return()); - EXPECT_CALL(mock_gatt_interface_, - Open(_, device->address_, BTM_BLE_DIRECT_CONNECTION, false)) - .Times(1); + ON_CALL(mock_gatt_interface_, Open(_, device->address_, BTM_BLE_DIRECT_CONNECTION, _)) + .WillByDefault(Return()); + EXPECT_CALL(mock_gatt_interface_, Open(_, device->address_, BTM_BLE_DIRECT_CONNECTION, false)) + .Times(1); // Record NumOfConnected when groupStateMachine_ gets notified about the // disconnection int num_of_connected = 0; ON_CALL(mock_state_machine_, ProcessHciNotifAclDisconnected(_, _)) - .WillByDefault([&num_of_connected](LeAudioDeviceGroup* group, - LeAudioDevice* leAudioDevice) { - num_of_connected = group->NumOfConnected(); - }); + .WillByDefault( + [&num_of_connected](LeAudioDeviceGroup* group, LeAudioDevice* leAudioDevice) { + num_of_connected = group->NumOfConnected(); + }); auto conn_id = device->conn_id_; InjectDisconnectedEvent(device->conn_id_, GATT_CONN_TERMINATE_PEER_USER); @@ -8291,25 +7549,21 @@ TEST_F(UnicastTest, TwoEarbudsStreamingProfileDisconnect) { int group_id = 2; // Report working CSIS - ON_CALL(mock_csis_client_module_, IsCsisClientRunning()) - .WillByDefault(Return(true)); + ON_CALL(mock_csis_client_module_, IsCsisClientRunning()).WillByDefault(Return(true)); ON_CALL(mock_csis_client_module_, GetDesiredSize(group_id)) - .WillByDefault(Invoke([&](int group_id) { return group_size; })); + .WillByDefault(Invoke([&](int group_id) { return group_size; })); // First earbud const RawAddress test_address0 = GetTestAddress(0); - ConnectCsisDevice(test_address0, 1 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontLeft, - codec_spec_conf::kLeAudioLocationFrontLeft, group_size, - group_id, 1 /* rank*/); + ConnectCsisDevice(test_address0, 1 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontLeft, + codec_spec_conf::kLeAudioLocationFrontLeft, group_size, group_id, 1 /* rank*/); // Second earbud const RawAddress test_address1 = GetTestAddress(1); - ConnectCsisDevice(test_address1, 2 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontRight, - codec_spec_conf::kLeAudioLocationFrontRight, group_size, - group_id, 2 /* rank*/, true /*connect_through_csis*/); + ConnectCsisDevice(test_address1, 2 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontRight, + codec_spec_conf::kLeAudioLocationFrontRight, group_size, group_id, 2 /* rank*/, + true /*connect_through_csis*/); // Audio sessions are started only when device gets active EXPECT_CALL(*mock_le_audio_source_hal_client_, Start(_, _, _)).Times(1); @@ -8331,18 +7585,15 @@ TEST_F(UnicastTest, TwoEarbudsStreamingProfileDisconnect) { EXPECT_CALL(mock_state_machine_, StopStream(_)).Times(1); /* Do not inject OPEN_EVENT by default */ - ON_CALL(mock_gatt_interface_, Open(_, _, _, _)) - .WillByDefault(DoAll(Return())); + ON_CALL(mock_gatt_interface_, Open(_, _, _, _)).WillByDefault(DoAll(Return())); ON_CALL(mock_gatt_interface_, Close(_)).WillByDefault(DoAll(Return())); - ON_CALL(mock_btm_interface_, AclDisconnectFromHandle(_, _)) - .WillByDefault(DoAll(Return())); + ON_CALL(mock_btm_interface_, AclDisconnectFromHandle(_, _)).WillByDefault(DoAll(Return())); DisconnectLeAudioNoDisconnectedEvtExpected(test_address0, 1); DisconnectLeAudioNoDisconnectedEvtExpected(test_address1, 2); - EXPECT_CALL(mock_gatt_interface_, - Open(_, _, BTM_BLE_BKG_CONNECT_TARGETED_ANNOUNCEMENTS, _)) - .Times(2); + EXPECT_CALL(mock_gatt_interface_, Open(_, _, BTM_BLE_BKG_CONNECT_TARGETED_ANNOUNCEMENTS, _)) + .Times(2); InjectDisconnectedEvent(1); InjectDisconnectedEvent(2); @@ -8357,25 +7608,21 @@ TEST_F(UnicastTest, TwoEarbudsStreamingProfileDisconnectStreamStopTimeout) { int group_id = 2; // Report working CSIS - ON_CALL(mock_csis_client_module_, IsCsisClientRunning()) - .WillByDefault(Return(true)); + ON_CALL(mock_csis_client_module_, IsCsisClientRunning()).WillByDefault(Return(true)); ON_CALL(mock_csis_client_module_, GetDesiredSize(group_id)) - .WillByDefault(Invoke([&](int group_id) { return group_size; })); + .WillByDefault(Invoke([&](int group_id) { return group_size; })); // First earbud const RawAddress test_address0 = GetTestAddress(0); - ConnectCsisDevice(test_address0, 1 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontLeft, - codec_spec_conf::kLeAudioLocationFrontLeft, group_size, - group_id, 1 /* rank*/); + ConnectCsisDevice(test_address0, 1 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontLeft, + codec_spec_conf::kLeAudioLocationFrontLeft, group_size, group_id, 1 /* rank*/); // Second earbud const RawAddress test_address1 = GetTestAddress(1); - ConnectCsisDevice(test_address1, 2 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontRight, - codec_spec_conf::kLeAudioLocationFrontRight, group_size, - group_id, 2 /* rank*/, true /*connect_through_csis*/); + ConnectCsisDevice(test_address1, 2 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontRight, + codec_spec_conf::kLeAudioLocationFrontRight, group_size, group_id, 2 /* rank*/, + true /*connect_through_csis*/); // Audio sessions are started only when device gets active EXPECT_CALL(*mock_le_audio_source_hal_client_, Start(_, _, _)).Times(1); @@ -8395,26 +7642,21 @@ TEST_F(UnicastTest, TwoEarbudsStreamingProfileDisconnectStreamStopTimeout) { TestAudioDataTransfer(group_id, cis_count_out, cis_count_in, 1920); // Expect StopStream to be called before Close or ACL Disconnect is called. - ON_CALL(mock_state_machine_, StopStream(_)) - .WillByDefault([](LeAudioDeviceGroup* group) { - /* Stub the process of stopping stream, just set the target state. - * this simulates issue with stopping the stream - */ - group->SetTargetState(types::AseState::BTA_LE_AUDIO_ASE_STATE_IDLE); - }); + ON_CALL(mock_state_machine_, StopStream(_)).WillByDefault([](LeAudioDeviceGroup* group) { + /* Stub the process of stopping stream, just set the target state. + * this simulates issue with stopping the stream + */ + group->SetTargetState(types::AseState::BTA_LE_AUDIO_ASE_STATE_IDLE); + }); EXPECT_CALL(mock_state_machine_, StopStream(_)).Times(2); EXPECT_CALL(mock_gatt_interface_, Close(_)).Times(0); EXPECT_CALL(mock_btm_interface_, AclDisconnectFromHandle(_, _)).Times(0); - do_in_main_thread( - FROM_HERE, - base::Bind(&LeAudioClient::Disconnect, - base::Unretained(LeAudioClient::Get()), test_address0)); - do_in_main_thread( - FROM_HERE, - base::Bind(&LeAudioClient::Disconnect, - base::Unretained(LeAudioClient::Get()), test_address1)); + do_in_main_thread(FROM_HERE, base::Bind(&LeAudioClient::Disconnect, + base::Unretained(LeAudioClient::Get()), test_address0)); + do_in_main_thread(FROM_HERE, base::Bind(&LeAudioClient::Disconnect, + base::Unretained(LeAudioClient::Get()), test_address1)); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_gatt_interface_); @@ -8425,8 +7667,7 @@ TEST_F(UnicastTest, TwoEarbudsStreamingProfileDisconnectStreamStopTimeout) { * disconnected. Simulate stop stream failure and timeout fired. Make sure * code will not try to do recovery connect */ - ON_CALL(mock_btm_interface_, AclDisconnectFromHandle(_, _)) - .WillByDefault(DoAll(Return())); + ON_CALL(mock_btm_interface_, AclDisconnectFromHandle(_, _)).WillByDefault(DoAll(Return())); EXPECT_CALL(mock_gatt_interface_, Close(_)).Times(0); EXPECT_CALL(mock_btm_interface_, AclDisconnectFromHandle(_, _)).Times(2); @@ -8443,43 +7684,38 @@ TEST_F(UnicastTest, TwoEarbudsStreamingProfileDisconnectStreamStopTimeout) { auto device = group->GetFirstDevice(); ASSERT_TRUE(device != nullptr); - ASSERT_NE(device->GetConnectionState(), - DeviceConnectState::DISCONNECTING_AND_RECOVER); + ASSERT_NE(device->GetConnectionState(), DeviceConnectState::DISCONNECTING_AND_RECOVER); device = group->GetNextDevice(device); ASSERT_TRUE(device != nullptr); - ASSERT_NE(device->GetConnectionState(), - DeviceConnectState::DISCONNECTING_AND_RECOVER); + ASSERT_NE(device->GetConnectionState(), DeviceConnectState::DISCONNECTING_AND_RECOVER); } TEST_F(UnicastTest, EarbudsWithStereoSinkMonoSourceSupporting32kHz) { const RawAddress test_address0 = GetTestAddress(0); int group_id = 0; - SetSampleDatabaseEarbudsValid( - 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationFrontLeft, default_channel_cnt, - default_channel_cnt, 0x0024, - /* source sample freq 32/16khz */ true, /*add_csis*/ - true, /*add_cas*/ - true, /*add_pacs*/ - default_ase_cnt /*add_ascs_cnt*/); + SetSampleDatabaseEarbudsValid(1, test_address0, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationFrontLeft, default_channel_cnt, + default_channel_cnt, 0x0024, + /* source sample freq 32/16khz */ true, /*add_csis*/ + true, /*add_cas*/ + true, /*add_pacs*/ + default_ase_cnt /*add_ascs_cnt*/); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); ConnectLeAudio(test_address0); // LeAudioCodecConfiguration received_af_sink_config; const LeAudioCodecConfiguration expected_af_sink_config = { - .num_channels = 2, - .sample_rate = bluetooth::audio::le_audio::kSampleRate32000, - .bits_per_sample = bluetooth::audio::le_audio::kBitsPerSample16, - .data_interval_us = LeAudioCodecConfiguration::kInterval10000Us, + .num_channels = 2, + .sample_rate = bluetooth::audio::le_audio::kSampleRate32000, + .bits_per_sample = bluetooth::audio::le_audio::kBitsPerSample16, + .data_interval_us = LeAudioCodecConfiguration::kInterval10000Us, }; // Audio sessions are started only when device gets active EXPECT_CALL(*mock_le_audio_source_hal_client_, Start(_, _, _)).Times(1); - EXPECT_CALL(*mock_le_audio_sink_hal_client_, - Start(expected_af_sink_config, _, _)) - .Times(1); + EXPECT_CALL(*mock_le_audio_sink_hal_client_, Start(expected_af_sink_config, _, _)).Times(1); LeAudioClient::Get()->GroupSetActive(group_id); SyncOnMainLoop(); } @@ -8487,32 +7723,29 @@ TEST_F(UnicastTest, EarbudsWithStereoSinkMonoSourceSupporting32kHz) { TEST_F(UnicastTest, TwoEarbudsWithSourceSupporting32kHz) { const RawAddress test_address0 = GetTestAddress(0); int group_id = 0; - SetSampleDatabaseEarbudsValid( - 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, - default_channel_cnt, 0x0024, - /* source sample freq 32/16khz */ true, /*add_csis*/ - true, /*add_cas*/ - true, /*add_pacs*/ - default_ase_cnt /*add_ascs_cnt*/); + SetSampleDatabaseEarbudsValid(1, test_address0, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, + default_channel_cnt, 0x0024, + /* source sample freq 32/16khz */ true, /*add_csis*/ + true, /*add_cas*/ + true, /*add_pacs*/ + default_ase_cnt /*add_ascs_cnt*/); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); ConnectLeAudio(test_address0); // LeAudioCodecConfiguration received_af_sink_config; const LeAudioCodecConfiguration expected_af_sink_config = { - .num_channels = 2, - .sample_rate = bluetooth::audio::le_audio::kSampleRate32000, - .bits_per_sample = bluetooth::audio::le_audio::kBitsPerSample16, - .data_interval_us = LeAudioCodecConfiguration::kInterval10000Us, + .num_channels = 2, + .sample_rate = bluetooth::audio::le_audio::kSampleRate32000, + .bits_per_sample = bluetooth::audio::le_audio::kBitsPerSample16, + .data_interval_us = LeAudioCodecConfiguration::kInterval10000Us, }; // Audio sessions are started only when device gets active EXPECT_CALL(*mock_le_audio_source_hal_client_, Start(_, _, _)).Times(1); - EXPECT_CALL(*mock_le_audio_sink_hal_client_, - Start(expected_af_sink_config, _, _)) - .Times(1); + EXPECT_CALL(*mock_le_audio_sink_hal_client_, Start(expected_af_sink_config, _, _)).Times(1); LeAudioClient::Get()->GroupSetActive(group_id); SyncOnMainLoop(); } @@ -8521,18 +7754,17 @@ TEST_F(UnicastTest, MicrophoneAttachToCurrentMediaScenario) { const RawAddress test_address0 = GetTestAddress(0); int group_id = bluetooth::groups::kGroupUnknown; - SetSampleDatabaseEarbudsValid( - 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, - default_channel_cnt, 0x0024, false /*add_csis*/, true /*add_cas*/, - true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, - 0 /*rank*/); + SetSampleDatabaseEarbudsValid(1, test_address0, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, + default_channel_cnt, 0x0024, false /*add_csis*/, true /*add_cas*/, + true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, + 0 /*rank*/); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupNodeStatus(test_address0, _, GroupNodeStatus::ADDED)) - .WillOnce(DoAll(SaveArg<1>(&group_id))); + .WillOnce(DoAll(SaveArg<1>(&group_id))); ConnectLeAudio(test_address0); ASSERT_NE(group_id, bluetooth::groups::kGroupUnknown); @@ -8544,14 +7776,11 @@ TEST_F(UnicastTest, MicrophoneAttachToCurrentMediaScenario) { SyncOnMainLoop(); // When the local audio source resumes we have no knowledge of recording - EXPECT_CALL( - mock_state_machine_, - StartStream(_, bluetooth::le_audio::types::LeAudioContextType::MEDIA, _, - _)) - .Times(1); + EXPECT_CALL(mock_state_machine_, + StartStream(_, bluetooth::le_audio::types::LeAudioContextType::MEDIA, _, _)) + .Times(1); - StartStreaming(AUDIO_USAGE_MEDIA, AUDIO_CONTENT_TYPE_MUSIC, group_id, - AUDIO_SOURCE_INVALID); + StartStreaming(AUDIO_USAGE_MEDIA, AUDIO_CONTENT_TYPE_MUSIC, group_id, AUDIO_SOURCE_INVALID); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); @@ -8563,13 +7792,10 @@ TEST_F(UnicastTest, MicrophoneAttachToCurrentMediaScenario) { TestAudioDataTransfer(group_id, cis_count_out, cis_count_in, 1920); // When the local audio sink resumes we should reconfigure - EXPECT_CALL( - mock_state_machine_, - ConfigureStream(_, bluetooth::le_audio::types::LeAudioContextType::LIVE, - _, _)) - .Times(1); - EXPECT_CALL(*mock_le_audio_source_hal_client_, ReconfigurationComplete()) - .Times(1); + EXPECT_CALL(mock_state_machine_, + ConfigureStream(_, bluetooth::le_audio::types::LeAudioContextType::LIVE, _, _)) + .Times(1); + EXPECT_CALL(*mock_le_audio_source_hal_client_, ReconfigurationComplete()).Times(1); // Update metadata on local audio sink UpdateLocalSinkMetadata(AUDIO_SOURCE_MIC); @@ -8577,10 +7803,9 @@ TEST_F(UnicastTest, MicrophoneAttachToCurrentMediaScenario) { // Resume on local audio sink ASSERT_NE(unicast_sink_hal_cb_, nullptr); do_in_main_thread( - FROM_HERE, - base::BindOnce( - [](LeAudioSinkAudioHalClient::Callbacks* cb) { cb->OnAudioResume(); }, - unicast_sink_hal_cb_)); + FROM_HERE, + base::BindOnce([](LeAudioSinkAudioHalClient::Callbacks* cb) { cb->OnAudioResume(); }, + unicast_sink_hal_cb_)); /* The above will trigger reconfiguration. After that Audio Hal action * is needed to restart the stream */ @@ -8591,10 +7816,9 @@ TEST_F(UnicastTest, MicrophoneAttachToCurrentMediaScenario) { LocalAudioSourceResume(); do_in_main_thread( - FROM_HERE, - base::BindOnce( - [](LeAudioSinkAudioHalClient::Callbacks* cb) { cb->OnAudioResume(); }, - unicast_sink_hal_cb_)); + FROM_HERE, + base::BindOnce([](LeAudioSinkAudioHalClient::Callbacks* cb) { cb->OnAudioResume(); }, + unicast_sink_hal_cb_)); SyncOnMainLoop(); // Verify Data transfer on one audio source and sink cis @@ -8610,12 +7834,11 @@ TEST_F(UnicastTest, MicrophoneAttachToCurrentMediaScenario) { EXPECT_CALL(*mock_le_audio_source_hal_client_, Stop()).Times(1); EXPECT_CALL(*mock_le_audio_source_hal_client_, OnDestroyed()).Times(1); EXPECT_CALL(*mock_le_audio_sink_hal_client_, OnDestroyed()).Times(1); - do_in_main_thread( - FROM_HERE, base::BindOnce( - [](LeAudioClient* client) { - client->GroupSetActive(bluetooth::groups::kGroupUnknown); - }, - LeAudioClient::Get())); + do_in_main_thread(FROM_HERE, base::BindOnce( + [](LeAudioClient* client) { + client->GroupSetActive(bluetooth::groups::kGroupUnknown); + }, + LeAudioClient::Get())); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(mock_le_audio_source_hal_client_); @@ -8631,27 +7854,25 @@ TEST_F(UnicastTest, UpdateNotSupportedContextTypeUnspecifiedAvailable) { const RawAddress test_address0 = GetTestAddress(0); int group_id = bluetooth::groups::kGroupUnknown; - available_snk_context_types_ = (types::LeAudioContextType::RINGTONE | - types::LeAudioContextType::CONVERSATIONAL | - types::LeAudioContextType::UNSPECIFIED | - types::LeAudioContextType::MEDIA) - .value(); + available_snk_context_types_ = + (types::LeAudioContextType::RINGTONE | types::LeAudioContextType::CONVERSATIONAL | + types::LeAudioContextType::UNSPECIFIED | types::LeAudioContextType::MEDIA) + .value(); supported_snk_context_types_ = available_snk_context_types_; available_src_context_types_ = available_snk_context_types_; supported_src_context_types_ = available_src_context_types_; - SetSampleDatabaseEarbudsValid( - 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, - default_channel_cnt, 0x0004, false /*add_csis*/, true /*add_cas*/, - true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, - 0 /*rank*/); + SetSampleDatabaseEarbudsValid(1, test_address0, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, + default_channel_cnt, 0x0004, false /*add_csis*/, true /*add_cas*/, + true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, + 0 /*rank*/); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupNodeStatus(test_address0, _, GroupNodeStatus::ADDED)) - .WillOnce(DoAll(SaveArg<1>(&group_id))); + .WillOnce(DoAll(SaveArg<1>(&group_id))); ConnectLeAudio(test_address0); ASSERT_NE(group_id, bluetooth::groups::kGroupUnknown); @@ -8668,8 +7889,7 @@ TEST_F(UnicastTest, UpdateNotSupportedContextTypeUnspecifiedAvailable) { LeAudioClient::Get()->GroupSetActive(group_id); SyncOnMainLoop(); - StartStreaming(AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE, - AUDIO_CONTENT_TYPE_UNKNOWN, group_id); + StartStreaming(AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE, AUDIO_CONTENT_TYPE_UNKNOWN, group_id); LocalAudioSourceResume(); LocalAudioSinkResume(); @@ -8688,13 +7908,11 @@ TEST_F(UnicastTest, UpdateNotSupportedContextTypeUnspecifiedAvailable) { */ EXPECT_CALL(mock_state_machine_, StopStream(_)).Times(0); types::BidirectionalPair contexts = { - .sink = types::AudioContexts(types::LeAudioContextType::UNSPECIFIED), - .source = types::AudioContexts(types::LeAudioContextType::UNSPECIFIED)}; - EXPECT_CALL(mock_state_machine_, - StartStream(_, types::LeAudioContextType::GAME, contexts, _)) - .Times(1); - UpdateLocalSourceMetadata(AUDIO_USAGE_GAME, AUDIO_CONTENT_TYPE_UNKNOWN, - false); + .sink = types::AudioContexts(types::LeAudioContextType::UNSPECIFIED), + .source = types::AudioContexts(types::LeAudioContextType::UNSPECIFIED)}; + EXPECT_CALL(mock_state_machine_, StartStream(_, types::LeAudioContextType::GAME, contexts, _)) + .Times(1); + UpdateLocalSourceMetadata(AUDIO_USAGE_GAME, AUDIO_CONTENT_TYPE_UNKNOWN, false); SyncOnMainLoop(); } @@ -8708,30 +7926,28 @@ TEST_F(UnicastTest, UpdateMultipleBidirContextTypes) { const RawAddress test_address0 = GetTestAddress(0); int group_id = bluetooth::groups::kGroupUnknown; - available_snk_context_types_ = - (types::LeAudioContextType::CONVERSATIONAL | - types::LeAudioContextType::GAME | types::LeAudioContextType::LIVE) - .value(); + available_snk_context_types_ = (types::LeAudioContextType::CONVERSATIONAL | + types::LeAudioContextType::GAME | types::LeAudioContextType::LIVE) + .value(); supported_snk_context_types_ = - available_snk_context_types_ | - types::AudioContexts(types::LeAudioContextType::UNSPECIFIED).value(); + available_snk_context_types_ | + types::AudioContexts(types::LeAudioContextType::UNSPECIFIED).value(); available_src_context_types_ = available_snk_context_types_; supported_src_context_types_ = - available_src_context_types_ | - types::AudioContexts(types::LeAudioContextType::UNSPECIFIED).value(); + available_src_context_types_ | + types::AudioContexts(types::LeAudioContextType::UNSPECIFIED).value(); - SetSampleDatabaseEarbudsValid( - 1, test_address0, codec_spec_conf::kLeAudioLocationAnyLeft, - codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, - default_channel_cnt, 0x0024, false /*add_csis*/, true /*add_cas*/, - true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, - 0 /*rank*/); + SetSampleDatabaseEarbudsValid(1, test_address0, codec_spec_conf::kLeAudioLocationAnyLeft, + codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, + default_channel_cnt, 0x0024, false /*add_csis*/, true /*add_cas*/, + true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, + 0 /*rank*/); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupNodeStatus(test_address0, _, GroupNodeStatus::ADDED)) - .WillOnce(DoAll(SaveArg<1>(&group_id))); + .WillOnce(DoAll(SaveArg<1>(&group_id))); ConnectLeAudio(test_address0); ASSERT_NE(group_id, bluetooth::groups::kGroupUnknown); @@ -8744,13 +7960,11 @@ TEST_F(UnicastTest, UpdateMultipleBidirContextTypes) { // When the local audio sink resumes expect only LIVE context types::BidirectionalPair contexts = { - .sink = types::AudioContexts(types::LeAudioContextType::LIVE), - .source = types::AudioContexts(types::LeAudioContextType::LIVE)}; - EXPECT_CALL( - mock_state_machine_, - StartStream(_, bluetooth::le_audio::types::LeAudioContextType::LIVE, - contexts, _)) - .Times(1); + .sink = types::AudioContexts(types::LeAudioContextType::LIVE), + .source = types::AudioContexts(types::LeAudioContextType::LIVE)}; + EXPECT_CALL(mock_state_machine_, + StartStream(_, bluetooth::le_audio::types::LeAudioContextType::LIVE, contexts, _)) + .Times(1); // 1) Start the recording. Sink resume will trigger the reconfiguration // --------------------------------------------------------------------- @@ -8784,21 +7998,16 @@ TEST_F(UnicastTest, UpdateMultipleBidirContextTypes) { LeAudioClient::Get()->SetInCall(true); // Verify that we only got CONVERSATIONAL context and no LIVE - contexts = { - .sink = types::AudioContexts(types::LeAudioContextType::CONVERSATIONAL), - .source = - types::AudioContexts(types::LeAudioContextType::CONVERSATIONAL)}; - EXPECT_CALL( - mock_state_machine_, - StartStream( - _, bluetooth::le_audio::types::LeAudioContextType::CONVERSATIONAL, - contexts, _)) - .Times(1); + contexts = {.sink = types::AudioContexts(types::LeAudioContextType::CONVERSATIONAL), + .source = types::AudioContexts(types::LeAudioContextType::CONVERSATIONAL)}; + EXPECT_CALL(mock_state_machine_, + StartStream(_, bluetooth::le_audio::types::LeAudioContextType::CONVERSATIONAL, + contexts, _)) + .Times(1); // Start with ringtone on local source ASSERT_NE(nullptr, unicast_sink_hal_cb_); - StartStreaming(AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE, - AUDIO_CONTENT_TYPE_UNKNOWN, group_id); + StartStreaming(AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE, AUDIO_CONTENT_TYPE_UNKNOWN, group_id); // Resume both directions LocalAudioSourceResume(); @@ -8821,11 +8030,9 @@ TEST_F(UnicastTest, UpdateMultipleBidirContextTypes) { EXPECT_CALL(mock_state_machine_, StopStream(_)).Times(0); contexts = {.sink = types::AudioContexts(types::LeAudioContextType::GAME), .source = types::AudioContexts(types::LeAudioContextType::GAME)}; - EXPECT_CALL(mock_state_machine_, - StartStream(_, types::LeAudioContextType::GAME, contexts, _)) - .Times(1); - UpdateLocalSourceMetadata(AUDIO_USAGE_GAME, AUDIO_CONTENT_TYPE_UNKNOWN, - false); + EXPECT_CALL(mock_state_machine_, StartStream(_, types::LeAudioContextType::GAME, contexts, _)) + .Times(1); + UpdateLocalSourceMetadata(AUDIO_USAGE_GAME, AUDIO_CONTENT_TYPE_UNKNOWN, false); /* If the above triggers reconfiguration, Audio Hal action is needed to * restart the stream. @@ -8843,12 +8050,11 @@ TEST_F(UnicastTest, UpdateMultipleBidirContextTypes) { EXPECT_CALL(*mock_le_audio_source_hal_client_, Stop()).Times(1); EXPECT_CALL(*mock_le_audio_source_hal_client_, OnDestroyed()).Times(1); EXPECT_CALL(*mock_le_audio_sink_hal_client_, OnDestroyed()).Times(1); - do_in_main_thread( - FROM_HERE, base::BindOnce( - [](LeAudioClient* client) { - client->GroupSetActive(bluetooth::groups::kGroupUnknown); - }, - LeAudioClient::Get())); + do_in_main_thread(FROM_HERE, base::BindOnce( + [](LeAudioClient* client) { + client->GroupSetActive(bluetooth::groups::kGroupUnknown); + }, + LeAudioClient::Get())); SyncOnMainLoop(); } @@ -8856,30 +8062,28 @@ TEST_F(UnicastTest, UpdateDisableLocalAudioSinkOnGame) { const RawAddress test_address0 = GetTestAddress(0); int group_id = bluetooth::groups::kGroupUnknown; - available_snk_context_types_ = - (types::LeAudioContextType::CONVERSATIONAL | - types::LeAudioContextType::GAME | types::LeAudioContextType::LIVE) - .value(); + available_snk_context_types_ = (types::LeAudioContextType::CONVERSATIONAL | + types::LeAudioContextType::GAME | types::LeAudioContextType::LIVE) + .value(); supported_snk_context_types_ = - available_snk_context_types_ | - types::AudioContexts(types::LeAudioContextType::UNSPECIFIED).value(); + available_snk_context_types_ | + types::AudioContexts(types::LeAudioContextType::UNSPECIFIED).value(); available_src_context_types_ = available_snk_context_types_; supported_src_context_types_ = - available_src_context_types_ | - types::AudioContexts(types::LeAudioContextType::UNSPECIFIED).value(); + available_src_context_types_ | + types::AudioContexts(types::LeAudioContextType::UNSPECIFIED).value(); - SetSampleDatabaseEarbudsValid( - 1, test_address0, codec_spec_conf::kLeAudioLocationAnyLeft, - codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, - default_channel_cnt, 0x0024, false /*add_csis*/, true /*add_cas*/, - true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, - 0 /*rank*/); + SetSampleDatabaseEarbudsValid(1, test_address0, codec_spec_conf::kLeAudioLocationAnyLeft, + codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, + default_channel_cnt, 0x0024, false /*add_csis*/, true /*add_cas*/, + true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, + 0 /*rank*/); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupNodeStatus(test_address0, _, GroupNodeStatus::ADDED)) - .WillOnce(DoAll(SaveArg<1>(&group_id))); + .WillOnce(DoAll(SaveArg<1>(&group_id))); ConnectLeAudio(test_address0); ASSERT_NE(group_id, bluetooth::groups::kGroupUnknown); @@ -8892,18 +8096,15 @@ TEST_F(UnicastTest, UpdateDisableLocalAudioSinkOnGame) { // Start GAME stream types::BidirectionalPair contexts = { - .sink = types::AudioContexts(types::LeAudioContextType::GAME), - .source = types::AudioContexts(types::LeAudioContextType::GAME)}; - EXPECT_CALL( - mock_state_machine_, - StartStream(_, bluetooth::le_audio::types::LeAudioContextType::GAME, - contexts, _)) - .Times(1); + .sink = types::AudioContexts(types::LeAudioContextType::GAME), + .source = types::AudioContexts(types::LeAudioContextType::GAME)}; + EXPECT_CALL(mock_state_machine_, + StartStream(_, bluetooth::le_audio::types::LeAudioContextType::GAME, contexts, _)) + .Times(1); // 1) Start the recording. Sink resume will trigger the reconfiguration // --------------------------------------------------------------------- - StartStreaming(AUDIO_USAGE_GAME, AUDIO_CONTENT_TYPE_MUSIC, group_id, - AUDIO_SOURCE_MIC); + StartStreaming(AUDIO_USAGE_GAME, AUDIO_CONTENT_TYPE_MUSIC, group_id, AUDIO_SOURCE_MIC); SyncOnMainLoop(); @@ -8935,30 +8136,29 @@ TEST_F(UnicastTest, MusicDuringCallContextTypes) { int group_id = bluetooth::groups::kGroupUnknown; available_snk_context_types_ = - (types::LeAudioContextType::CONVERSATIONAL | - types::LeAudioContextType::RINGTONE | types::LeAudioContextType::GAME | - types::LeAudioContextType::MEDIA | types::LeAudioContextType::LIVE) - .value(); + (types::LeAudioContextType::CONVERSATIONAL | types::LeAudioContextType::RINGTONE | + types::LeAudioContextType::GAME | types::LeAudioContextType::MEDIA | + types::LeAudioContextType::LIVE) + .value(); supported_snk_context_types_ = - available_snk_context_types_ | - types::AudioContexts(types::LeAudioContextType::UNSPECIFIED).value(); + available_snk_context_types_ | + types::AudioContexts(types::LeAudioContextType::UNSPECIFIED).value(); available_src_context_types_ = available_snk_context_types_; supported_src_context_types_ = - available_src_context_types_ | - types::AudioContexts(types::LeAudioContextType::UNSPECIFIED).value(); + available_src_context_types_ | + types::AudioContexts(types::LeAudioContextType::UNSPECIFIED).value(); - SetSampleDatabaseEarbudsValid( - 1, test_address0, codec_spec_conf::kLeAudioLocationAnyLeft, - codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, - default_channel_cnt, 0x0024, false /*add_csis*/, true /*add_cas*/, - true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, - 0 /*rank*/); + SetSampleDatabaseEarbudsValid(1, test_address0, codec_spec_conf::kLeAudioLocationAnyLeft, + codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, + default_channel_cnt, 0x0024, false /*add_csis*/, true /*add_cas*/, + true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, + 0 /*rank*/); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupNodeStatus(test_address0, _, GroupNodeStatus::ADDED)) - .WillOnce(DoAll(SaveArg<1>(&group_id))); + .WillOnce(DoAll(SaveArg<1>(&group_id))); ConnectLeAudio(test_address0); ASSERT_NE(group_id, bluetooth::groups::kGroupUnknown); @@ -8974,18 +8174,14 @@ TEST_F(UnicastTest, MusicDuringCallContextTypes) { // CONVERSATIONAL is from In Call preference, and RINGTONE is from metadata LeAudioClient::Get()->SetInCall(true); types::BidirectionalPair contexts = { - .sink = types::AudioContexts(types::LeAudioContextType::RINGTONE | - types::LeAudioContextType::CONVERSATIONAL), - .source = - types::AudioContexts(types::LeAudioContextType::CONVERSATIONAL)}; - EXPECT_CALL( - mock_state_machine_, - StartStream( - _, bluetooth::le_audio::types::LeAudioContextType::CONVERSATIONAL, - contexts, _)) - .Times(1); - StartStreaming(AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE, - AUDIO_CONTENT_TYPE_UNKNOWN, group_id); + .sink = types::AudioContexts(types::LeAudioContextType::RINGTONE | + types::LeAudioContextType::CONVERSATIONAL), + .source = types::AudioContexts(types::LeAudioContextType::CONVERSATIONAL)}; + EXPECT_CALL(mock_state_machine_, + StartStream(_, bluetooth::le_audio::types::LeAudioContextType::CONVERSATIONAL, + contexts, _)) + .Times(1); + StartStreaming(AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE, AUDIO_CONTENT_TYPE_UNKNOWN, group_id); LocalAudioSourceResume(); LocalAudioSinkResume(); @@ -9000,17 +8196,13 @@ TEST_F(UnicastTest, MusicDuringCallContextTypes) { TestAudioDataTransfer(group_id, cis_count_out, cis_count_in, 1920, 40); // 2) Start MEDIA during the call, expect MEDIA only on the remote sink - contexts = { - .sink = types::AudioContexts(types::LeAudioContextType::CONVERSATIONAL | - types::LeAudioContextType::MEDIA), - .source = - types::AudioContexts(types::LeAudioContextType::CONVERSATIONAL)}; - EXPECT_CALL( - mock_state_machine_, - StartStream( - _, bluetooth::le_audio::types::LeAudioContextType::CONVERSATIONAL, - contexts, _)) - .Times(1); + contexts = {.sink = types::AudioContexts(types::LeAudioContextType::CONVERSATIONAL | + types::LeAudioContextType::MEDIA), + .source = types::AudioContexts(types::LeAudioContextType::CONVERSATIONAL)}; + EXPECT_CALL(mock_state_machine_, + StartStream(_, bluetooth::le_audio::types::LeAudioContextType::CONVERSATIONAL, + contexts, _)) + .Times(1); UpdateLocalSourceMetadata(AUDIO_USAGE_MEDIA, AUDIO_CONTENT_TYPE_MUSIC, false); SyncOnMainLoop(); @@ -9024,15 +8216,12 @@ TEST_F(UnicastTest, MusicDuringCallContextTypes) { LeAudioClient::Get()->SetInCall(false); EXPECT_CALL(mock_state_machine_, StopStream(_)).Times(0); - contexts = { - .sink = types::AudioContexts(types::LeAudioContextType::MEDIA | - types::LeAudioContextType::CONVERSATIONAL), - .source = - types::AudioContexts(types::LeAudioContextType::CONVERSATIONAL)}; - EXPECT_CALL( - mock_state_machine_, - StartStream(_, types::LeAudioContextType::CONVERSATIONAL, contexts, _)) - .Times(1); + contexts = {.sink = types::AudioContexts(types::LeAudioContextType::MEDIA | + types::LeAudioContextType::CONVERSATIONAL), + .source = types::AudioContexts(types::LeAudioContextType::CONVERSATIONAL)}; + EXPECT_CALL(mock_state_machine_, + StartStream(_, types::LeAudioContextType::CONVERSATIONAL, contexts, _)) + .Times(1); UpdateLocalSourceMetadata(AUDIO_USAGE_MEDIA, AUDIO_CONTENT_TYPE_MUSIC, /*reconfigure=*/false); Mock::VerifyAndClearExpectations(&mock_state_machine_); @@ -9052,9 +8241,8 @@ TEST_F(UnicastTest, MusicDuringCallContextTypes) { // Restart the stream with MEDIA contexts = {.sink = types::AudioContexts(types::LeAudioContextType::MEDIA), .source = types::AudioContexts()}; - EXPECT_CALL(mock_state_machine_, - StartStream(_, types::LeAudioContextType::MEDIA, contexts, _)) - .Times(1); + EXPECT_CALL(mock_state_machine_, StartStream(_, types::LeAudioContextType::MEDIA, contexts, _)) + .Times(1); UpdateLocalSourceMetadata(AUDIO_USAGE_MEDIA, AUDIO_CONTENT_TYPE_MUSIC, /*reconfigure=*/false); Mock::VerifyAndClearExpectations(mock_le_audio_source_hal_client_); @@ -9076,12 +8264,11 @@ TEST_F(UnicastTest, MusicDuringCallContextTypes) { EXPECT_CALL(*mock_le_audio_source_hal_client_, Stop()).Times(1); EXPECT_CALL(*mock_le_audio_source_hal_client_, OnDestroyed()).Times(1); EXPECT_CALL(*mock_le_audio_sink_hal_client_, OnDestroyed()).Times(1); - do_in_main_thread( - FROM_HERE, base::BindOnce( - [](LeAudioClient* client) { - client->GroupSetActive(bluetooth::groups::kGroupUnknown); - }, - LeAudioClient::Get())); + do_in_main_thread(FROM_HERE, base::BindOnce( + [](LeAudioClient* client) { + client->GroupSetActive(bluetooth::groups::kGroupUnknown); + }, + LeAudioClient::Get())); SyncOnMainLoop(); } @@ -9097,29 +8284,26 @@ TEST_F(UnicastTest, StartNotAvailableSupportedContextType) { int group_id = bluetooth::groups::kGroupUnknown; // EMERGENCYALARM is not available, but supported - available_snk_context_types_ = (types::LeAudioContextType::RINGTONE | - types::LeAudioContextType::CONVERSATIONAL | - types::LeAudioContextType::UNSPECIFIED | - types::LeAudioContextType::MEDIA) - .value(); + available_snk_context_types_ = + (types::LeAudioContextType::RINGTONE | types::LeAudioContextType::CONVERSATIONAL | + types::LeAudioContextType::UNSPECIFIED | types::LeAudioContextType::MEDIA) + .value(); available_src_context_types_ = available_snk_context_types_; supported_snk_context_types_ = types::kLeAudioContextAllTypes.value(); - supported_src_context_types_ = (types::kLeAudioContextAllRemoteSource | - types::LeAudioContextType::UNSPECIFIED) - .value(); + supported_src_context_types_ = + (types::kLeAudioContextAllRemoteSource | types::LeAudioContextType::UNSPECIFIED).value(); - SetSampleDatabaseEarbudsValid( - 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, - default_channel_cnt, 0x0004, false /*add_csis*/, true /*add_cas*/, - true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, - 0 /*rank*/); + SetSampleDatabaseEarbudsValid(1, test_address0, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, + default_channel_cnt, 0x0004, false /*add_csis*/, true /*add_cas*/, + true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, + 0 /*rank*/); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupNodeStatus(test_address0, _, GroupNodeStatus::ADDED)) - .WillOnce(DoAll(SaveArg<1>(&group_id))); + .WillOnce(DoAll(SaveArg<1>(&group_id))); ConnectLeAudio(test_address0); ASSERT_NE(group_id, bluetooth::groups::kGroupUnknown); @@ -9129,18 +8313,17 @@ TEST_F(UnicastTest, StartNotAvailableSupportedContextType) { // Since the initial config is UNSPECIFIED, then even for sonification events // we should reconfigure to less generic EMERGENCYALARM scenario EXPECT_CALL(*mock_le_audio_source_hal_client_, Start(_, _, _)).Times(1); - types::BidirectionalPair metadata = { - .sink = types::AudioContexts(), .source = types::AudioContexts()}; - EXPECT_CALL( - mock_state_machine_, - StartStream(_, types::LeAudioContextType::EMERGENCYALARM, metadata, _)) - .Times(0); + types::BidirectionalPair metadata = {.sink = types::AudioContexts(), + .source = types::AudioContexts()}; + EXPECT_CALL(mock_state_machine_, + StartStream(_, types::LeAudioContextType::EMERGENCYALARM, metadata, _)) + .Times(0); LeAudioClient::Get()->GroupSetActive(group_id); SyncOnMainLoop(); - StartStreaming(AUDIO_USAGE_EMERGENCY, AUDIO_CONTENT_TYPE_UNKNOWN, group_id, - AUDIO_SOURCE_INVALID, false, false); + StartStreaming(AUDIO_USAGE_EMERGENCY, AUDIO_CONTENT_TYPE_UNKNOWN, group_id, AUDIO_SOURCE_INVALID, + false, false); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); @@ -9157,30 +8340,27 @@ TEST_F(UnicastTest, StartNotAvailableUnsupportedContextTypeUnspecifiedUnavail) { int group_id = bluetooth::groups::kGroupUnknown; // EMERGENCYALARM is not available, nor supported - available_snk_context_types_ = (types::LeAudioContextType::RINGTONE | - types::LeAudioContextType::CONVERSATIONAL | - types::LeAudioContextType::MEDIA) - .value(); + available_snk_context_types_ = + (types::LeAudioContextType::RINGTONE | types::LeAudioContextType::CONVERSATIONAL | + types::LeAudioContextType::MEDIA) + .value(); available_src_context_types_ = available_snk_context_types_; supported_snk_context_types_ = - (available_snk_context_types_ | types::LeAudioContextType::UNSPECIFIED) - .value(); + (available_snk_context_types_ | types::LeAudioContextType::UNSPECIFIED).value(); supported_src_context_types_ = - (available_src_context_types_ | types::LeAudioContextType::UNSPECIFIED) - .value(); + (available_src_context_types_ | types::LeAudioContextType::UNSPECIFIED).value(); - SetSampleDatabaseEarbudsValid( - 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, - default_channel_cnt, 0x0004, false /*add_csis*/, true /*add_cas*/, - true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, - 0 /*rank*/); + SetSampleDatabaseEarbudsValid(1, test_address0, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, + default_channel_cnt, 0x0004, false /*add_csis*/, true /*add_cas*/, + true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, + 0 /*rank*/); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupNodeStatus(test_address0, _, GroupNodeStatus::ADDED)) - .WillOnce(DoAll(SaveArg<1>(&group_id))); + .WillOnce(DoAll(SaveArg<1>(&group_id))); ConnectLeAudio(test_address0); ASSERT_NE(group_id, bluetooth::groups::kGroupUnknown); @@ -9189,18 +8369,17 @@ TEST_F(UnicastTest, StartNotAvailableUnsupportedContextTypeUnspecifiedUnavail) { // not on the list of supported contexts and UNSPECIFIED should not be // in the metadata as it is unavailable. EXPECT_CALL(*mock_le_audio_source_hal_client_, Start(_, _, _)).Times(1); - types::BidirectionalPair metadata = { - .sink = types::AudioContexts(), .source = types::AudioContexts()}; - EXPECT_CALL( - mock_state_machine_, - StartStream(_, types::LeAudioContextType::EMERGENCYALARM, metadata, _)) - .Times(0); + types::BidirectionalPair metadata = {.sink = types::AudioContexts(), + .source = types::AudioContexts()}; + EXPECT_CALL(mock_state_machine_, + StartStream(_, types::LeAudioContextType::EMERGENCYALARM, metadata, _)) + .Times(0); LeAudioClient::Get()->GroupSetActive(group_id); SyncOnMainLoop(); - StartStreaming(AUDIO_USAGE_EMERGENCY, AUDIO_CONTENT_TYPE_UNKNOWN, group_id, - AUDIO_SOURCE_INVALID, false, false); + StartStreaming(AUDIO_USAGE_EMERGENCY, AUDIO_CONTENT_TYPE_UNKNOWN, group_id, AUDIO_SOURCE_INVALID, + false, false); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); @@ -9215,27 +8394,25 @@ TEST_F(UnicastTest, StartNotAvailableUnsupportedContextTypeUnspecifiedAvail) { int group_id = bluetooth::groups::kGroupUnknown; // EMERGENCYALARM is not available, nor supported - available_snk_context_types_ = (types::LeAudioContextType::RINGTONE | - types::LeAudioContextType::CONVERSATIONAL | - types::LeAudioContextType::UNSPECIFIED | - types::LeAudioContextType::MEDIA) - .value(); + available_snk_context_types_ = + (types::LeAudioContextType::RINGTONE | types::LeAudioContextType::CONVERSATIONAL | + types::LeAudioContextType::UNSPECIFIED | types::LeAudioContextType::MEDIA) + .value(); available_src_context_types_ = available_snk_context_types_; supported_snk_context_types_ = available_snk_context_types_; supported_src_context_types_ = available_src_context_types_; - SetSampleDatabaseEarbudsValid( - 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, - default_channel_cnt, 0x0004, false /*add_csis*/, true /*add_cas*/, - true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, - 0 /*rank*/); + SetSampleDatabaseEarbudsValid(1, test_address0, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, + default_channel_cnt, 0x0004, false /*add_csis*/, true /*add_cas*/, + true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, + 0 /*rank*/); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupNodeStatus(test_address0, _, GroupNodeStatus::ADDED)) - .WillOnce(DoAll(SaveArg<1>(&group_id))); + .WillOnce(DoAll(SaveArg<1>(&group_id))); ConnectLeAudio(test_address0); ASSERT_NE(group_id, bluetooth::groups::kGroupUnknown); @@ -9245,12 +8422,11 @@ TEST_F(UnicastTest, StartNotAvailableUnsupportedContextTypeUnspecifiedAvail) { // the metadata. EXPECT_CALL(*mock_le_audio_source_hal_client_, Start(_, _, _)).Times(1); types::BidirectionalPair metadata = { - .sink = types::AudioContexts(types::LeAudioContextType::UNSPECIFIED), - .source = types::AudioContexts()}; - EXPECT_CALL( - mock_state_machine_, - StartStream(_, types::LeAudioContextType::EMERGENCYALARM, metadata, _)) - .Times(1); + .sink = types::AudioContexts(types::LeAudioContextType::UNSPECIFIED), + .source = types::AudioContexts()}; + EXPECT_CALL(mock_state_machine_, + StartStream(_, types::LeAudioContextType::EMERGENCYALARM, metadata, _)) + .Times(1); LeAudioClient::Get()->GroupSetActive(group_id); SyncOnMainLoop(); @@ -9273,18 +8449,17 @@ TEST_F(UnicastTest, NotifyAboutGroupTunrnedIdleEnabled) { osi_property_set_bool(kNotifyUpperLayerAboutGroupBeingInIdleDuringCall, true); - SetSampleDatabaseEarbudsValid( - 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, - default_channel_cnt, 0x0004, false /*add_csis*/, true /*add_cas*/, - true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, - 0 /*rank*/); + SetSampleDatabaseEarbudsValid(1, test_address0, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, + default_channel_cnt, 0x0004, false /*add_csis*/, true /*add_cas*/, + true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, + 0 /*rank*/); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupNodeStatus(test_address0, _, GroupNodeStatus::ADDED)) - .WillOnce(DoAll(SaveArg<1>(&group_id))); + .WillOnce(DoAll(SaveArg<1>(&group_id))); ConnectLeAudio(test_address0); ASSERT_NE(group_id, bluetooth::groups::kGroupUnknown); @@ -9301,8 +8476,7 @@ TEST_F(UnicastTest, NotifyAboutGroupTunrnedIdleEnabled) { LeAudioClient::Get()->GroupSetActive(group_id); SyncOnMainLoop(); - StartStreaming(AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE, - AUDIO_CONTENT_TYPE_UNKNOWN, group_id); + StartStreaming(AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE, AUDIO_CONTENT_TYPE_UNKNOWN, group_id); Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); Mock::VerifyAndClearExpectations(mock_le_audio_source_hal_client_); @@ -9317,44 +8491,40 @@ TEST_F(UnicastTest, NotifyAboutGroupTunrnedIdleEnabled) { * 1. GroupStatus::INACTIVE * 2. GroupStatus::TURNED_IDLE_DURING_CALL */ - EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupStatus(group_id, _)) - .Times(2); + EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupStatus(group_id, _)).Times(2); EXPECT_CALL(*mock_le_audio_source_hal_client_, Stop()).Times(1); EXPECT_CALL(*mock_le_audio_source_hal_client_, OnDestroyed()).Times(1); EXPECT_CALL(*mock_le_audio_sink_hal_client_, OnDestroyed()).Times(1); - do_in_main_thread( - FROM_HERE, base::BindOnce( - [](LeAudioClient* client) { - client->GroupSetActive(bluetooth::groups::kGroupUnknown); - }, - LeAudioClient::Get())); + do_in_main_thread(FROM_HERE, base::BindOnce( + [](LeAudioClient* client) { + client->GroupSetActive(bluetooth::groups::kGroupUnknown); + }, + LeAudioClient::Get())); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(mock_le_audio_source_hal_client_); LeAudioClient::Get()->SetInCall(false); - osi_property_set_bool(kNotifyUpperLayerAboutGroupBeingInIdleDuringCall, - false); + osi_property_set_bool(kNotifyUpperLayerAboutGroupBeingInIdleDuringCall, false); } TEST_F(UnicastTest, NotifyAboutGroupTunrnedIdleDisabled) { const RawAddress test_address0 = GetTestAddress(0); int group_id = bluetooth::groups::kGroupUnknown; - SetSampleDatabaseEarbudsValid( - 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, - default_channel_cnt, 0x0004, false /*add_csis*/, true /*add_cas*/, - true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, - 0 /*rank*/); + SetSampleDatabaseEarbudsValid(1, test_address0, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, + default_channel_cnt, 0x0004, false /*add_csis*/, true /*add_cas*/, + true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, + 0 /*rank*/); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupNodeStatus(test_address0, _, GroupNodeStatus::ADDED)) - .WillOnce(DoAll(SaveArg<1>(&group_id))); + .WillOnce(DoAll(SaveArg<1>(&group_id))); ConnectLeAudio(test_address0); ASSERT_NE(group_id, bluetooth::groups::kGroupUnknown); @@ -9371,8 +8541,7 @@ TEST_F(UnicastTest, NotifyAboutGroupTunrnedIdleDisabled) { LeAudioClient::Get()->GroupSetActive(group_id); SyncOnMainLoop(); - StartStreaming(AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE, - AUDIO_CONTENT_TYPE_UNKNOWN, group_id); + StartStreaming(AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE, AUDIO_CONTENT_TYPE_UNKNOWN, group_id); Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); Mock::VerifyAndClearExpectations(mock_le_audio_source_hal_client_); @@ -9386,19 +8555,17 @@ TEST_F(UnicastTest, NotifyAboutGroupTunrnedIdleDisabled) { /* To be called once only * 1. GroupStatus::INACTIVE */ - EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupStatus(group_id, _)) - .Times(1); + EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupStatus(group_id, _)).Times(1); EXPECT_CALL(*mock_le_audio_source_hal_client_, Stop()).Times(1); EXPECT_CALL(*mock_le_audio_source_hal_client_, OnDestroyed()).Times(1); EXPECT_CALL(*mock_le_audio_sink_hal_client_, OnDestroyed()).Times(1); - do_in_main_thread( - FROM_HERE, base::BindOnce( - [](LeAudioClient* client) { - client->GroupSetActive(bluetooth::groups::kGroupUnknown); - }, - LeAudioClient::Get())); + do_in_main_thread(FROM_HERE, base::BindOnce( + [](LeAudioClient* client) { + client->GroupSetActive(bluetooth::groups::kGroupUnknown); + }, + LeAudioClient::Get())); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(mock_le_audio_source_hal_client_); @@ -9410,18 +8577,17 @@ TEST_F(UnicastTest, HandleDatabaseOutOfSync) { const RawAddress test_address0 = GetTestAddress(0); int group_id = bluetooth::groups::kGroupUnknown; - SetSampleDatabaseEarbudsValid( - 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, - default_channel_cnt, 0x0004, false /*add_csis*/, true /*add_cas*/, - true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, - 0 /*rank*/); + SetSampleDatabaseEarbudsValid(1, test_address0, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, + default_channel_cnt, 0x0004, false /*add_csis*/, true /*add_cas*/, + true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, + 0 /*rank*/); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupNodeStatus(test_address0, _, GroupNodeStatus::ADDED)) - .WillOnce(DoAll(SaveArg<1>(&group_id))); + .WillOnce(DoAll(SaveArg<1>(&group_id))); ConnectLeAudio(test_address0); ASSERT_NE(group_id, bluetooth::groups::kGroupUnknown); @@ -9431,7 +8597,7 @@ TEST_F(UnicastTest, HandleDatabaseOutOfSync) { EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::DISCONNECTED, test_address0)) - .Times(1); + .Times(1); InjectDisconnectedEvent(1, GATT_CONN_TERMINATE_PEER_USER); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); @@ -9442,8 +8608,7 @@ TEST_F(UnicastTest, HandleDatabaseOutOfSync) { gatt_read_ctp_ccc_status_ = GATT_DATABASE_OUT_OF_SYNC; EXPECT_CALL(mock_gatt_queue_, WriteDescriptor(_, _, _, _, _, _)).Times(0); - ON_CALL(mock_gatt_interface_, ServiceSearchRequest(_, _)) - .WillByDefault(Return()); + ON_CALL(mock_gatt_interface_, ServiceSearchRequest(_, _)).WillByDefault(Return()); EXPECT_CALL(mock_gatt_interface_, ServiceSearchRequest(_, _)); InjectConnectedEvent(test_address0, 1); @@ -9456,18 +8621,17 @@ TEST_F(UnicastTest, TestRemoteDeviceKeepCccValues) { const RawAddress test_address0 = GetTestAddress(0); int group_id = bluetooth::groups::kGroupUnknown; - SetSampleDatabaseEarbudsValid( - 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, - default_channel_cnt, 0x0004, false /*add_csis*/, true /*add_cas*/, - true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, - 0 /*rank*/); + SetSampleDatabaseEarbudsValid(1, test_address0, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, + default_channel_cnt, 0x0004, false /*add_csis*/, true /*add_cas*/, + true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, + 0 /*rank*/); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupNodeStatus(test_address0, _, GroupNodeStatus::ADDED)) - .WillOnce(DoAll(SaveArg<1>(&group_id))); + .WillOnce(DoAll(SaveArg<1>(&group_id))); ConnectLeAudio(test_address0); ASSERT_NE(group_id, bluetooth::groups::kGroupUnknown); @@ -9477,7 +8641,7 @@ TEST_F(UnicastTest, TestRemoteDeviceKeepCccValues) { EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::DISCONNECTED, test_address0)) - .Times(1); + .Times(1); InjectDisconnectedEvent(1, GATT_CONN_TERMINATE_PEER_USER); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); @@ -9489,7 +8653,7 @@ TEST_F(UnicastTest, TestRemoteDeviceKeepCccValues) { EXPECT_CALL(mock_gatt_queue_, WriteDescriptor(_, _, _, _, _, _)).Times(0); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); InjectConnectedEvent(test_address0, 1); SyncOnMainLoop(); @@ -9501,18 +8665,17 @@ TEST_F(UnicastTest, TestRemoteDeviceForgetsCccValues) { const RawAddress test_address0 = GetTestAddress(0); int group_id = bluetooth::groups::kGroupUnknown; - SetSampleDatabaseEarbudsValid( - 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, - default_channel_cnt, 0x0004, false /*add_csis*/, true /*add_cas*/, - true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, - 0 /*rank*/); + SetSampleDatabaseEarbudsValid(1, test_address0, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, + default_channel_cnt, 0x0004, false /*add_csis*/, true /*add_cas*/, + true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, + 0 /*rank*/); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupNodeStatus(test_address0, _, GroupNodeStatus::ADDED)) - .WillOnce(DoAll(SaveArg<1>(&group_id))); + .WillOnce(DoAll(SaveArg<1>(&group_id))); ConnectLeAudio(test_address0); ASSERT_NE(group_id, bluetooth::groups::kGroupUnknown); @@ -9522,7 +8685,7 @@ TEST_F(UnicastTest, TestRemoteDeviceForgetsCccValues) { EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::DISCONNECTED, test_address0)) - .Times(1); + .Times(1); InjectDisconnectedEvent(1, GATT_CONN_TERMINATE_PEER_USER); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); @@ -9530,11 +8693,10 @@ TEST_F(UnicastTest, TestRemoteDeviceForgetsCccValues) { /* Simulate remote cache is broken */ ccc_stored_byte_val_ = 0; - EXPECT_CALL(mock_gatt_queue_, WriteDescriptor(_, _, _, _, _, _)) - .Times(AtLeast(1)); + EXPECT_CALL(mock_gatt_queue_, WriteDescriptor(_, _, _, _, _, _)).Times(AtLeast(1)); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); InjectConnectedEvent(test_address0, 1); SyncOnMainLoop(); @@ -9547,18 +8709,16 @@ TEST_F(UnicastTest, SpeakerStreamingTimeout) { int group_id = bluetooth::groups::kGroupUnknown; SetSampleDatabaseEarbudsValid( - 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, - default_channel_cnt, 0x0004, - /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, - true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, - 0 /*rank*/); + 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, default_channel_cnt, 0x0004, + /* source sample freq 16khz */ false /*add_csis*/, true /*add_cas*/, true /*add_pacs*/, + default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, 0 /*rank*/); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupNodeStatus(test_address0, _, GroupNodeStatus::ADDED)) - .WillOnce(DoAll(SaveArg<1>(&group_id))); + .WillOnce(DoAll(SaveArg<1>(&group_id))); ConnectLeAudio(test_address0); ASSERT_NE(group_id, bluetooth::groups::kGroupUnknown); @@ -9583,8 +8743,7 @@ TEST_F(UnicastTest, SpeakerStreamingTimeout) { TestAudioDataTransfer(group_id, cis_count_out, cis_count_in, 1920); // Do not accept direct connect, but expect it to arrive. - ON_CALL(mock_gatt_interface_, Open(_, _, BTM_BLE_DIRECT_CONNECTION, _)) - .WillByDefault(Return()); + ON_CALL(mock_gatt_interface_, Open(_, _, BTM_BLE_DIRECT_CONNECTION, _)).WillByDefault(Return()); state_machine_callbacks_->OnStateTransitionTimeout(group_id); SyncOnMainLoop(); @@ -9607,30 +8766,24 @@ TEST_F(UnicastTest, AddMemberToAllowListWhenOneDeviceConnected) { * 3. verify Device B is in the allow list with direct connect. */ // Report working CSIS - ON_CALL(mock_csis_client_module_, IsCsisClientRunning()) - .WillByDefault(Return(true)); + ON_CALL(mock_csis_client_module_, IsCsisClientRunning()).WillByDefault(Return(true)); ON_CALL(mock_csis_client_module_, GetDesiredSize(group_id)) - .WillByDefault(Invoke([&](int group_id) { return group_size; })); + .WillByDefault(Invoke([&](int group_id) { return group_size; })); // First earbud const RawAddress test_address0 = GetTestAddress(0); - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, true)) - .Times(1); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, true)).Times(1); - ConnectCsisDevice(test_address0, conn_id_dev_0, - codec_spec_conf::kLeAudioLocationFrontLeft, - codec_spec_conf::kLeAudioLocationFrontLeft, group_size, - group_id, 1 /* rank*/); + ConnectCsisDevice(test_address0, conn_id_dev_0, codec_spec_conf::kLeAudioLocationFrontLeft, + codec_spec_conf::kLeAudioLocationFrontLeft, group_size, group_id, 1 /* rank*/); SyncOnMainLoop(); - EXPECT_CALL(mock_gatt_interface_, CancelOpen(gatt_if, test_address0, _)) - .Times(1); + EXPECT_CALL(mock_gatt_interface_, CancelOpen(gatt_if, test_address0, _)).Times(1); EXPECT_CALL(mock_gatt_interface_, - Open(gatt_if, test_address0, - BTM_BLE_BKG_CONNECT_TARGETED_ANNOUNCEMENTS, _)) - .Times(1); + Open(gatt_if, test_address0, BTM_BLE_BKG_CONNECT_TARGETED_ANNOUNCEMENTS, _)) + .Times(1); InjectDisconnectedEvent(conn_id_dev_0); @@ -9639,23 +8792,18 @@ TEST_F(UnicastTest, AddMemberToAllowListWhenOneDeviceConnected) { // Second earbud const RawAddress test_address1 = GetTestAddress(1); - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, true)) - .Times(1); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, true)).Times(1); /* Do not connect first device but expect Open will arrive.*/ - EXPECT_CALL(mock_gatt_interface_, CancelOpen(gatt_if, test_address0, false)) - .Times(1); - EXPECT_CALL(mock_gatt_interface_, - Open(gatt_if, test_address0, BTM_BLE_DIRECT_CONNECTION, _)) - .Times(1); - ON_CALL(mock_gatt_interface_, - Open(_, test_address0, BTM_BLE_DIRECT_CONNECTION, _)) - .WillByDefault(Return()); + EXPECT_CALL(mock_gatt_interface_, CancelOpen(gatt_if, test_address0, false)).Times(1); + EXPECT_CALL(mock_gatt_interface_, Open(gatt_if, test_address0, BTM_BLE_DIRECT_CONNECTION, _)) + .Times(1); + ON_CALL(mock_gatt_interface_, Open(_, test_address0, BTM_BLE_DIRECT_CONNECTION, _)) + .WillByDefault(Return()); - ConnectCsisDevice(test_address1, conn_id_dev_1, - codec_spec_conf::kLeAudioLocationFrontRight, - codec_spec_conf::kLeAudioLocationFrontRight, group_size, - group_id, 2 /* rank*/, true /*connect_through_csis*/); + ConnectCsisDevice(test_address1, conn_id_dev_1, codec_spec_conf::kLeAudioLocationFrontRight, + codec_spec_conf::kLeAudioLocationFrontRight, group_size, group_id, 2 /* rank*/, + true /*connect_through_csis*/); Mock::VerifyAndClearExpectations(&mock_gatt_interface_); } @@ -9675,30 +8823,24 @@ TEST_F(UnicastTest, ResetToDefaultReconnectionMode) { * mode */ // Report working CSIS - ON_CALL(mock_csis_client_module_, IsCsisClientRunning()) - .WillByDefault(Return(true)); + ON_CALL(mock_csis_client_module_, IsCsisClientRunning()).WillByDefault(Return(true)); ON_CALL(mock_csis_client_module_, GetDesiredSize(group_id)) - .WillByDefault(Invoke([&](int group_id) { return group_size; })); + .WillByDefault(Invoke([&](int group_id) { return group_size; })); // First earbud const RawAddress test_address0 = GetTestAddress(0); - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, true)) - .Times(1); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, true)).Times(1); - ConnectCsisDevice(test_address0, conn_id_dev_0, - codec_spec_conf::kLeAudioLocationFrontLeft, - codec_spec_conf::kLeAudioLocationFrontLeft, group_size, - group_id, 1 /* rank*/); + ConnectCsisDevice(test_address0, conn_id_dev_0, codec_spec_conf::kLeAudioLocationFrontLeft, + codec_spec_conf::kLeAudioLocationFrontLeft, group_size, group_id, 1 /* rank*/); SyncOnMainLoop(); - EXPECT_CALL(mock_gatt_interface_, CancelOpen(gatt_if, test_address0, _)) - .Times(1); + EXPECT_CALL(mock_gatt_interface_, CancelOpen(gatt_if, test_address0, _)).Times(1); EXPECT_CALL(mock_gatt_interface_, - Open(gatt_if, test_address0, - BTM_BLE_BKG_CONNECT_TARGETED_ANNOUNCEMENTS, _)) - .Times(1); + Open(gatt_if, test_address0, BTM_BLE_BKG_CONNECT_TARGETED_ANNOUNCEMENTS, _)) + .Times(1); InjectDisconnectedEvent(conn_id_dev_0); @@ -9707,40 +8849,31 @@ TEST_F(UnicastTest, ResetToDefaultReconnectionMode) { // Second earbud const RawAddress test_address1 = GetTestAddress(1); - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, true)) - .Times(1); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, true)).Times(1); /* Verify first earbud will start doing direct connect first */ - EXPECT_CALL(mock_gatt_interface_, CancelOpen(gatt_if, test_address0, false)) - .Times(1); - ON_CALL(mock_gatt_interface_, - Open(_, test_address0, BTM_BLE_DIRECT_CONNECTION, _)) - .WillByDefault(Return()); - EXPECT_CALL(mock_gatt_interface_, - Open(gatt_if, test_address0, BTM_BLE_DIRECT_CONNECTION, _)) - .Times(1); + EXPECT_CALL(mock_gatt_interface_, CancelOpen(gatt_if, test_address0, false)).Times(1); + ON_CALL(mock_gatt_interface_, Open(_, test_address0, BTM_BLE_DIRECT_CONNECTION, _)) + .WillByDefault(Return()); + EXPECT_CALL(mock_gatt_interface_, Open(gatt_if, test_address0, BTM_BLE_DIRECT_CONNECTION, _)) + .Times(1); - ConnectCsisDevice(test_address1, conn_id_dev_1, - codec_spec_conf::kLeAudioLocationFrontRight, - codec_spec_conf::kLeAudioLocationFrontRight, group_size, - group_id, 2 /* rank*/, true /*connect_through_csis*/); + ConnectCsisDevice(test_address1, conn_id_dev_1, codec_spec_conf::kLeAudioLocationFrontRight, + codec_spec_conf::kLeAudioLocationFrontRight, group_size, group_id, 2 /* rank*/, + true /*connect_through_csis*/); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_gatt_interface_); // Disconnect Device B, expect default reconnection mode for Device A. - EXPECT_CALL(mock_gatt_interface_, CancelOpen(gatt_if, test_address0, false)) - .Times(1); + EXPECT_CALL(mock_gatt_interface_, CancelOpen(gatt_if, test_address0, false)).Times(1); EXPECT_CALL(mock_gatt_interface_, - Open(gatt_if, test_address0, - BTM_BLE_BKG_CONNECT_TARGETED_ANNOUNCEMENTS, _)) - .Times(1); + Open(gatt_if, test_address0, BTM_BLE_BKG_CONNECT_TARGETED_ANNOUNCEMENTS, _)) + .Times(1); EXPECT_CALL(mock_gatt_interface_, - Open(gatt_if, test_address1, - BTM_BLE_BKG_CONNECT_TARGETED_ANNOUNCEMENTS, _)) - .Times(1); - EXPECT_CALL(mock_gatt_interface_, CancelOpen(gatt_if, test_address1, false)) - .Times(1); + Open(gatt_if, test_address1, BTM_BLE_BKG_CONNECT_TARGETED_ANNOUNCEMENTS, _)) + .Times(1); + EXPECT_CALL(mock_gatt_interface_, CancelOpen(gatt_if, test_address1, false)).Times(1); InjectDisconnectedEvent(conn_id_dev_1, GATT_CONN_TERMINATE_PEER_USER); SyncOnMainLoop(); @@ -9753,8 +8886,7 @@ TEST_F(UnicastTest, DisconnectAclBeforeGettingReadResponses) { int group_id = 2; // Report working CSIS - ON_CALL(mock_csis_client_module_, IsCsisClientRunning()) - .WillByDefault(Return(true)); + ON_CALL(mock_csis_client_module_, IsCsisClientRunning()).WillByDefault(Return(true)); const RawAddress test_address0 = GetTestAddress(0); const RawAddress test_address1 = GetTestAddress(1); @@ -9764,43 +8896,38 @@ TEST_F(UnicastTest, DisconnectAclBeforeGettingReadResponses) { */ EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(0); - EXPECT_CALL(mock_audio_hal_client_callbacks_, - OnSinkAudioLocationAvailable( - test_address0, codec_spec_conf::kLeAudioLocationFrontLeft)) - .Times(0); + .Times(0); + EXPECT_CALL( + mock_audio_hal_client_callbacks_, + OnSinkAudioLocationAvailable(test_address0, codec_spec_conf::kLeAudioLocationFrontLeft)) + .Times(0); // First earbud initial connection SetSampleDatabaseEarbudsValid(1 /* conn_id */, test_address0, codec_spec_conf::kLeAudioLocationFrontLeft, - codec_spec_conf::kLeAudioLocationFrontLeft, - default_channel_cnt, default_channel_cnt, - 0x0004, /* source sample freq 16khz */ - true, /*add_csis*/ - true, /*add_cas*/ - true, /*add_pacs*/ - true, /*add_ascs*/ + codec_spec_conf::kLeAudioLocationFrontLeft, default_channel_cnt, + default_channel_cnt, 0x0004, /* source sample freq 16khz */ + true, /*add_csis*/ + true, /*add_cas*/ + true, /*add_pacs*/ + true, /*add_ascs*/ group_size, 1 /* rank */, GATT_INTERNAL_ERROR); groups[test_address0] = group_id; // by default indicate link as encrypted ON_CALL(mock_btm_interface_, BTM_IsEncrypted(test_address0, _)) - .WillByDefault(DoAll(Return(true))); + .WillByDefault(DoAll(Return(true))); - EXPECT_CALL(mock_gatt_interface_, - Open(gatt_if, test_address0, BTM_BLE_DIRECT_CONNECTION, _)) - .Times(1); + EXPECT_CALL(mock_gatt_interface_, Open(gatt_if, test_address0, BTM_BLE_DIRECT_CONNECTION, _)) + .Times(1); /* When connected it will got to TA */ - EXPECT_CALL(mock_gatt_interface_, CancelOpen(gatt_if, test_address0, _)) - .Times(1); + EXPECT_CALL(mock_gatt_interface_, CancelOpen(gatt_if, test_address0, _)).Times(1); EXPECT_CALL(mock_gatt_interface_, - Open(gatt_if, test_address0, - BTM_BLE_BKG_CONNECT_TARGETED_ANNOUNCEMENTS, _)) - .Times(1); + Open(gatt_if, test_address0, BTM_BLE_BKG_CONNECT_TARGETED_ANNOUNCEMENTS, _)) + .Times(1); - do_in_main_thread( - FROM_HERE, - base::BindOnce(&LeAudioClient::Connect, - base::Unretained(LeAudioClient::Get()), test_address0)); + do_in_main_thread(FROM_HERE, + base::BindOnce(&LeAudioClient::Connect, base::Unretained(LeAudioClient::Get()), + test_address0)); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_btm_interface_); @@ -9809,37 +8936,31 @@ TEST_F(UnicastTest, DisconnectAclBeforeGettingReadResponses) { InjectGroupDeviceAdded(test_address0, group_id); // Second earbud initial connection - EXPECT_CALL(mock_audio_hal_client_callbacks_, - OnSinkAudioLocationAvailable( - test_address1, codec_spec_conf::kLeAudioLocationFrontRight)) - .Times(1); + EXPECT_CALL( + mock_audio_hal_client_callbacks_, + OnSinkAudioLocationAvailable(test_address1, codec_spec_conf::kLeAudioLocationFrontRight)) + .Times(1); - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, true)) - .Times(1); - ConnectCsisDevice(test_address1, 2 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontRight, - codec_spec_conf::kLeAudioLocationFrontRight, group_size, - group_id, 2 /* rank*/, true /*connect_through_csis*/); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, true)).Times(1); + ConnectCsisDevice(test_address1, 2 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontRight, + codec_spec_conf::kLeAudioLocationFrontRight, group_size, group_id, 2 /* rank*/, + true /*connect_through_csis*/); Mock::VerifyAndClearExpectations(&mock_btif_storage_); /* for Target announcements AutoConnect is always there, until * device is removed */ - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, false)) - .Times(0); - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, false)) - .Times(0); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, false)).Times(0); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, false)).Times(0); // Verify grouping information - std::vector devs = - LeAudioClient::Get()->GetGroupDevices(group_id); + std::vector devs = LeAudioClient::Get()->GetGroupDevices(group_id); ASSERT_NE(std::find(devs.begin(), devs.end(), test_address0), devs.end()); ASSERT_NE(std::find(devs.begin(), devs.end(), test_address1), devs.end()); /* Remove default action on the direct connect */ - ON_CALL(mock_gatt_interface_, Open(_, _, BTM_BLE_DIRECT_CONNECTION, _)) - .WillByDefault(Return()); + ON_CALL(mock_gatt_interface_, Open(_, _, BTM_BLE_DIRECT_CONNECTION, _)).WillByDefault(Return()); /* Initiate disconnection with timeout reason, the possible reason why GATT * read attribute operation may be not handled @@ -9852,22 +8973,21 @@ TEST_F(UnicastTest, DisconnectAclBeforeGettingReadResponses) { */ EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); - EXPECT_CALL(mock_audio_hal_client_callbacks_, - OnSinkAudioLocationAvailable( - test_address0, codec_spec_conf::kLeAudioLocationFrontLeft)) - .Times(1); + .Times(1); + EXPECT_CALL( + mock_audio_hal_client_callbacks_, + OnSinkAudioLocationAvailable(test_address0, codec_spec_conf::kLeAudioLocationFrontLeft)) + .Times(1); /* Prepare valid GATT status responsing attributes */ SetSampleDatabaseEarbudsValid(1 /* conn_id */, test_address0, codec_spec_conf::kLeAudioLocationFrontLeft, - codec_spec_conf::kLeAudioLocationFrontLeft, - default_channel_cnt, default_channel_cnt, - 0x0004, /* source sample freq 16khz */ - true, /*add_csis*/ - true, /*add_cas*/ - true, /*add_pacs*/ - true, /*add_ascs*/ + codec_spec_conf::kLeAudioLocationFrontLeft, default_channel_cnt, + default_channel_cnt, 0x0004, /* source sample freq 16khz */ + true, /*add_csis*/ + true, /*add_cas*/ + true, /*add_pacs*/ + true, /*add_ascs*/ group_size, 1 /* rank */); /* For background connect, test needs to Inject Connected Event */ @@ -9876,8 +8996,8 @@ TEST_F(UnicastTest, DisconnectAclBeforeGettingReadResponses) { } TEST_F_WITH_FLAGS(UnicastTest, GroupStreamStatus, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG( - TEST_BT, leaudio_callback_on_group_stream_status))) { + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, + leaudio_callback_on_group_stream_status))) { int group_id = bluetooth::groups::kGroupUnknown; InSequence s; @@ -9885,171 +9005,142 @@ TEST_F_WITH_FLAGS(UnicastTest, GroupStreamStatus, /* Check if all states are properly notified */ EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupStreamStatus(group_id, GroupStreamStatus::IDLE)) - .Times(1); + .Times(1); state_machine_callbacks_->StatusReportCb(group_id, GroupStreamStatus::IDLE); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupStreamStatus(group_id, GroupStreamStatus::STREAMING)) - .Times(1); - state_machine_callbacks_->StatusReportCb(group_id, - GroupStreamStatus::STREAMING); + .Times(1); + state_machine_callbacks_->StatusReportCb(group_id, GroupStreamStatus::STREAMING); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupStreamStatus(group_id, GroupStreamStatus::IDLE)) - .Times(1); - state_machine_callbacks_->StatusReportCb(group_id, - GroupStreamStatus::RELEASING); + .Times(1); + state_machine_callbacks_->StatusReportCb(group_id, GroupStreamStatus::RELEASING); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupStreamStatus(group_id, GroupStreamStatus::STREAMING)) - .Times(1); - state_machine_callbacks_->StatusReportCb(group_id, - GroupStreamStatus::STREAMING); + .Times(1); + state_machine_callbacks_->StatusReportCb(group_id, GroupStreamStatus::STREAMING); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupStreamStatus(group_id, GroupStreamStatus::IDLE)) - .Times(1); - state_machine_callbacks_->StatusReportCb(group_id, - GroupStreamStatus::SUSPENDING); + .Times(1); + state_machine_callbacks_->StatusReportCb(group_id, GroupStreamStatus::SUSPENDING); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupStreamStatus(group_id, GroupStreamStatus::STREAMING)) - .Times(1); - state_machine_callbacks_->StatusReportCb(group_id, - GroupStreamStatus::STREAMING); + .Times(1); + state_machine_callbacks_->StatusReportCb(group_id, GroupStreamStatus::STREAMING); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupStreamStatus(group_id, GroupStreamStatus::IDLE)) - .Times(1); - state_machine_callbacks_->StatusReportCb(group_id, - GroupStreamStatus::SUSPENDED); + .Times(1); + state_machine_callbacks_->StatusReportCb(group_id, GroupStreamStatus::SUSPENDED); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupStreamStatus(group_id, GroupStreamStatus::STREAMING)) - .Times(1); - state_machine_callbacks_->StatusReportCb(group_id, - GroupStreamStatus::STREAMING); + .Times(1); + state_machine_callbacks_->StatusReportCb(group_id, GroupStreamStatus::STREAMING); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupStreamStatus(group_id, GroupStreamStatus::IDLE)) - .Times(1); - state_machine_callbacks_->StatusReportCb( - group_id, GroupStreamStatus::CONFIGURED_AUTONOMOUS); + .Times(1); + state_machine_callbacks_->StatusReportCb(group_id, GroupStreamStatus::CONFIGURED_AUTONOMOUS); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupStreamStatus(group_id, GroupStreamStatus::STREAMING)) - .Times(1); - state_machine_callbacks_->StatusReportCb(group_id, - GroupStreamStatus::STREAMING); + .Times(1); + state_machine_callbacks_->StatusReportCb(group_id, GroupStreamStatus::STREAMING); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupStreamStatus(group_id, GroupStreamStatus::IDLE)) - .Times(1); - state_machine_callbacks_->StatusReportCb( - group_id, GroupStreamStatus::CONFIGURED_BY_USER); + .Times(1); + state_machine_callbacks_->StatusReportCb(group_id, GroupStreamStatus::CONFIGURED_BY_USER); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupStreamStatus(group_id, GroupStreamStatus::STREAMING)) - .Times(1); - state_machine_callbacks_->StatusReportCb(group_id, - GroupStreamStatus::STREAMING); + .Times(1); + state_machine_callbacks_->StatusReportCb(group_id, GroupStreamStatus::STREAMING); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupStreamStatus(group_id, GroupStreamStatus::IDLE)) - .Times(1); - state_machine_callbacks_->StatusReportCb(group_id, - GroupStreamStatus::DESTROYED); + .Times(1); + state_machine_callbacks_->StatusReportCb(group_id, GroupStreamStatus::DESTROYED); /* Check if there are no resending of the same state */ - state_machine_callbacks_->StatusReportCb(group_id, - GroupStreamStatus::RELEASING); - state_machine_callbacks_->StatusReportCb(group_id, - GroupStreamStatus::SUSPENDING); - state_machine_callbacks_->StatusReportCb(group_id, - GroupStreamStatus::SUSPENDED); - state_machine_callbacks_->StatusReportCb( - group_id, GroupStreamStatus::CONFIGURED_AUTONOMOUS); - state_machine_callbacks_->StatusReportCb( - group_id, GroupStreamStatus::CONFIGURED_BY_USER); + state_machine_callbacks_->StatusReportCb(group_id, GroupStreamStatus::RELEASING); + state_machine_callbacks_->StatusReportCb(group_id, GroupStreamStatus::SUSPENDING); + state_machine_callbacks_->StatusReportCb(group_id, GroupStreamStatus::SUSPENDED); + state_machine_callbacks_->StatusReportCb(group_id, GroupStreamStatus::CONFIGURED_AUTONOMOUS); + state_machine_callbacks_->StatusReportCb(group_id, GroupStreamStatus::CONFIGURED_BY_USER); state_machine_callbacks_->StatusReportCb(group_id, GroupStreamStatus::IDLE); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupStreamStatus(group_id, GroupStreamStatus::STREAMING)) - .Times(1); - state_machine_callbacks_->StatusReportCb(group_id, - GroupStreamStatus::STREAMING); - state_machine_callbacks_->StatusReportCb(group_id, - GroupStreamStatus::STREAMING); + .Times(1); + state_machine_callbacks_->StatusReportCb(group_id, GroupStreamStatus::STREAMING); + state_machine_callbacks_->StatusReportCb(group_id, GroupStreamStatus::STREAMING); } TEST_F_WITH_FLAGS(UnicastTest, GroupStreamStatusManyGroups, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG( - TEST_BT, leaudio_callback_on_group_stream_status))) { + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, + leaudio_callback_on_group_stream_status))) { uint8_t group_size = 2; int group_id_1 = 1; int group_id_2 = 2; // Report working CSIS - ON_CALL(mock_csis_client_module_, IsCsisClientRunning()) - .WillByDefault(Return(true)); + ON_CALL(mock_csis_client_module_, IsCsisClientRunning()).WillByDefault(Return(true)); - ON_CALL(mock_csis_client_module_, GetDesiredSize(_)) - .WillByDefault(Return(group_size)); + ON_CALL(mock_csis_client_module_, GetDesiredSize(_)).WillByDefault(Return(group_size)); // First group - First earbud const RawAddress test_address0 = GetTestAddress(0); - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, true)) - .Times(1); - ConnectCsisDevice(test_address0, 1 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontLeft, - codec_spec_conf::kLeAudioLocationFrontLeft, group_size, - group_id_1, 1 /* rank*/); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, true)).Times(1); + ConnectCsisDevice(test_address0, 1 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontLeft, + codec_spec_conf::kLeAudioLocationFrontLeft, group_size, group_id_1, + 1 /* rank*/); // First group - Second earbud const RawAddress test_address1 = GetTestAddress(1); - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, true)) - .Times(1); - ConnectCsisDevice(test_address1, 2 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontRight, - codec_spec_conf::kLeAudioLocationFrontRight, group_size, - group_id_1, 2 /* rank*/, true /*connect_through_csis*/); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, true)).Times(1); + ConnectCsisDevice(test_address1, 2 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontRight, + codec_spec_conf::kLeAudioLocationFrontRight, group_size, group_id_1, + 2 /* rank*/, true /*connect_through_csis*/); // Second group - First earbud const RawAddress test_address2 = GetTestAddress(2); - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address2, true)) - .Times(1); - ConnectCsisDevice(test_address2, 3 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontLeft, - codec_spec_conf::kLeAudioLocationFrontLeft, group_size, - group_id_2, 1 /* rank*/); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address2, true)).Times(1); + ConnectCsisDevice(test_address2, 3 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontLeft, + codec_spec_conf::kLeAudioLocationFrontLeft, group_size, group_id_2, + 1 /* rank*/); // Second group - Second earbud const RawAddress test_address3 = GetTestAddress(3); - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address3, true)) - .Times(1); - ConnectCsisDevice(test_address3, 4 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontRight, - codec_spec_conf::kLeAudioLocationFrontRight, group_size, - group_id_2, 2 /* rank*/, true /*connect_through_csis*/); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address3, true)).Times(1); + ConnectCsisDevice(test_address3, 4 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontRight, + codec_spec_conf::kLeAudioLocationFrontRight, group_size, group_id_2, + 2 /* rank*/, true /*connect_through_csis*/); InSequence s; // Group 1 IDLE EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupStreamStatus(group_id_1, GroupStreamStatus::IDLE)) - .Times(1); + .Times(1); state_machine_callbacks_->StatusReportCb(group_id_1, GroupStreamStatus::IDLE); // Group 2 IDLE EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupStreamStatus(group_id_2, GroupStreamStatus::IDLE)) - .Times(1); + .Times(1); state_machine_callbacks_->StatusReportCb(group_id_2, GroupStreamStatus::IDLE); // Group 1 active and start streaming EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupStreamStatus(group_id_1, GroupStreamStatus::STREAMING)) - .Times(1); + .Times(1); LeAudioClient::Get()->GroupSetActive(group_id_1); SyncOnMainLoop(); StartStreaming(AUDIO_USAGE_MEDIA, AUDIO_CONTENT_TYPE_MUSIC, group_id_1); @@ -10059,7 +9150,7 @@ TEST_F_WITH_FLAGS(UnicastTest, GroupStreamStatusManyGroups, // Group 2 active EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupStreamStatus(group_id_1, GroupStreamStatus::IDLE)) - .Times(1); + .Times(1); LeAudioClient::Get()->GroupSetActive(group_id_2); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); @@ -10067,42 +9158,35 @@ TEST_F_WITH_FLAGS(UnicastTest, GroupStreamStatusManyGroups, // Group 2 start streaming EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupStreamStatus(group_id_2, GroupStreamStatus::STREAMING)) - .Times(1); + .Times(1); StartStreaming(AUDIO_USAGE_MEDIA, AUDIO_CONTENT_TYPE_MUSIC, group_id_2); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); } TEST_F_WITH_FLAGS(UnicastTest, GroupStreamStatusResendAfterRemove, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG( - TEST_BT, leaudio_callback_on_group_stream_status))) { + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, + leaudio_callback_on_group_stream_status))) { uint8_t group_size = 2; int group_id = 1; // Report working CSIS - ON_CALL(mock_csis_client_module_, IsCsisClientRunning()) - .WillByDefault(Return(true)); + ON_CALL(mock_csis_client_module_, IsCsisClientRunning()).WillByDefault(Return(true)); - ON_CALL(mock_csis_client_module_, GetDesiredSize(_)) - .WillByDefault(Return(group_size)); + ON_CALL(mock_csis_client_module_, GetDesiredSize(_)).WillByDefault(Return(group_size)); // First earbud const RawAddress test_address0 = GetTestAddress(0); - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, true)) - .Times(1); - ConnectCsisDevice(test_address0, 1 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontLeft, - codec_spec_conf::kLeAudioLocationFrontLeft, group_size, - group_id, 1 /* rank*/); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, true)).Times(1); + ConnectCsisDevice(test_address0, 1 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontLeft, + codec_spec_conf::kLeAudioLocationFrontLeft, group_size, group_id, 1 /* rank*/); // Second earbud const RawAddress test_address1 = GetTestAddress(1); - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, true)) - .Times(1); - ConnectCsisDevice(test_address1, 2 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontRight, - codec_spec_conf::kLeAudioLocationFrontRight, group_size, - group_id, 2 /* rank*/, true /*connect_through_csis*/); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, true)).Times(1); + ConnectCsisDevice(test_address1, 2 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontRight, + codec_spec_conf::kLeAudioLocationFrontRight, group_size, group_id, 2 /* rank*/, + true /*connect_through_csis*/); Mock::VerifyAndClearExpectations(&mock_btif_storage_); @@ -10111,20 +9195,19 @@ TEST_F_WITH_FLAGS(UnicastTest, GroupStreamStatusResendAfterRemove, // Activate group, start streaming and immediately stop EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupStreamStatus(group_id, GroupStreamStatus::STREAMING)) - .Times(1); + .Times(1); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupStreamStatus(group_id, GroupStreamStatus::IDLE)) - .Times(1); + .Times(1); LeAudioClient::Get()->GroupSetActive(group_id); SyncOnMainLoop(); - state_machine_callbacks_->StatusReportCb(group_id, - GroupStreamStatus::STREAMING); + state_machine_callbacks_->StatusReportCb(group_id, GroupStreamStatus::STREAMING); Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); // No resend EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupStreamStatus(group_id, GroupStreamStatus::IDLE)) - .Times(0); + .Times(0); state_machine_callbacks_->StatusReportCb(group_id, GroupStreamStatus::IDLE); // No resend after removing only one device @@ -10134,15 +9217,14 @@ TEST_F_WITH_FLAGS(UnicastTest, GroupStreamStatusResendAfterRemove, * well. */ do_in_main_thread(FROM_HERE, base::BindOnce( - [](LeAudioClient* client, - const RawAddress& test_address0) { - client->RemoveDevice(test_address0); - }, - LeAudioClient::Get(), test_address0)); + [](LeAudioClient* client, const RawAddress& test_address0) { + client->RemoveDevice(test_address0); + }, + LeAudioClient::Get(), test_address0)); SyncOnMainLoop(); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupStreamStatus(group_id, GroupStreamStatus::IDLE)) - .Times(0); + .Times(0); state_machine_callbacks_->StatusReportCb(group_id, GroupStreamStatus::IDLE); Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); @@ -10153,50 +9235,42 @@ TEST_F_WITH_FLAGS(UnicastTest, GroupStreamStatusResendAfterRemove, * well. */ do_in_main_thread(FROM_HERE, base::BindOnce( - [](LeAudioClient* client, - const RawAddress& test_address1) { - client->RemoveDevice(test_address1); - }, - LeAudioClient::Get(), test_address1)); + [](LeAudioClient* client, const RawAddress& test_address1) { + client->RemoveDevice(test_address1); + }, + LeAudioClient::Get(), test_address1)); SyncOnMainLoop(); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupStreamStatus(group_id, GroupStreamStatus::IDLE)) - .Times(1); + .Times(1); state_machine_callbacks_->StatusReportCb(group_id, GroupStreamStatus::IDLE); Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); } -TEST_F_WITH_FLAGS(UnicastTestHandoverMode, - SetSinkMonitorModeWhileUnicastIsActive, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG( - TEST_BT, leaudio_broadcast_audio_handover_policies))) { +TEST_F_WITH_FLAGS(UnicastTestHandoverMode, SetSinkMonitorModeWhileUnicastIsActive, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, + leaudio_broadcast_audio_handover_policies))) { uint8_t group_size = 2; int group_id = 2; // Report working CSIS - ON_CALL(mock_csis_client_module_, IsCsisClientRunning()) - .WillByDefault(Return(true)); + ON_CALL(mock_csis_client_module_, IsCsisClientRunning()).WillByDefault(Return(true)); ON_CALL(mock_csis_client_module_, GetDesiredSize(group_id)) - .WillByDefault(Invoke([&](int group_id) { return group_size; })); + .WillByDefault(Invoke([&](int group_id) { return group_size; })); // First earbud const RawAddress test_address0 = GetTestAddress(0); - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, true)) - .Times(1); - ConnectCsisDevice(test_address0, 1 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontLeft, - codec_spec_conf::kLeAudioLocationFrontLeft, group_size, - group_id, 1 /* rank*/); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, true)).Times(1); + ConnectCsisDevice(test_address0, 1 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontLeft, + codec_spec_conf::kLeAudioLocationFrontLeft, group_size, group_id, 1 /* rank*/); // Second earbud const RawAddress test_address1 = GetTestAddress(1); - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, true)) - .Times(1); - ConnectCsisDevice(test_address1, 2 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontRight, - codec_spec_conf::kLeAudioLocationFrontRight, group_size, - group_id, 2 /* rank*/, true /*connect_through_csis*/); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, true)).Times(1); + ConnectCsisDevice(test_address1, 2 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontRight, + codec_spec_conf::kLeAudioLocationFrontRight, group_size, group_id, 2 /* rank*/, + true /*connect_through_csis*/); // Start streaming EXPECT_CALL(*mock_le_audio_source_hal_client_, Start(_, _, _)).Times(1); @@ -10206,8 +9280,7 @@ TEST_F_WITH_FLAGS(UnicastTestHandoverMode, Mock::VerifyAndClearExpectations(mock_le_audio_source_hal_client_); - StartStreaming(AUDIO_USAGE_VOICE_COMMUNICATION, AUDIO_CONTENT_TYPE_SPEECH, - group_id); + StartStreaming(AUDIO_USAGE_VOICE_COMMUNICATION, AUDIO_CONTENT_TYPE_SPEECH, group_id); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); @@ -10219,35 +9292,30 @@ TEST_F_WITH_FLAGS(UnicastTestHandoverMode, TestAudioDataTransfer(group_id, cis_count_out, cis_count_in, 1920, 40); // Imitate activation of monitor mode - do_in_main_thread( - FROM_HERE, - base::BindOnce(&LeAudioClient::SetUnicastMonitorMode, - base::Unretained(LeAudioClient::Get()), - bluetooth::le_audio::types::kLeAudioDirectionSink, - true /* enable */)); + do_in_main_thread(FROM_HERE, base::BindOnce(&LeAudioClient::SetUnicastMonitorMode, + base::Unretained(LeAudioClient::Get()), + bluetooth::le_audio::types::kLeAudioDirectionSink, + true /* enable */)); ASSERT_NE(0lu, streaming_groups.count(group_id)); auto group = streaming_groups.at(group_id); // Stop streaming and expect Service to be informed about straming suspension EXPECT_CALL(mock_audio_hal_client_callbacks_, - OnUnicastMonitorModeStatus( - bluetooth::le_audio::types::kLeAudioDirectionSink, - UnicastMonitorModeStatus::STREAMING_SUSPENDED)) - .Times(1); + OnUnicastMonitorModeStatus(bluetooth::le_audio::types::kLeAudioDirectionSink, + UnicastMonitorModeStatus::STREAMING_SUSPENDED)) + .Times(1); // Stop StopStreaming(group_id, true); // Check if cache configuration is still present - ASSERT_TRUE( - group->GetCachedConfiguration(types::LeAudioContextType::CONVERSATIONAL) - ->confs.get(le_audio::types::kLeAudioDirectionSink) - .size()); - ASSERT_TRUE( - group->GetCachedConfiguration(types::LeAudioContextType::CONVERSATIONAL) - ->confs.get(le_audio::types::kLeAudioDirectionSource) - .size()); + ASSERT_TRUE(group->GetCachedConfiguration(types::LeAudioContextType::CONVERSATIONAL) + ->confs.get(le_audio::types::kLeAudioDirectionSink) + .size()); + ASSERT_TRUE(group->GetCachedConfiguration(types::LeAudioContextType::CONVERSATIONAL) + ->confs.get(le_audio::types::kLeAudioDirectionSource) + .size()); // Release, Sink HAL client should remain in monitor mode EXPECT_CALL(*mock_le_audio_source_hal_client_, Stop()).Times(1); @@ -10265,20 +9333,17 @@ TEST_F_WITH_FLAGS(UnicastTestHandoverMode, RegisterSourceHalClientMock(); // Setting group inactive, shall not change cached configuration - ASSERT_TRUE( - group->GetCachedConfiguration(types::LeAudioContextType::CONVERSATIONAL) - ->confs.get(le_audio::types::kLeAudioDirectionSink) - .size()); - ASSERT_TRUE( - group->GetCachedConfiguration(types::LeAudioContextType::CONVERSATIONAL) - ->confs.get(le_audio::types::kLeAudioDirectionSource) - .size()); + ASSERT_TRUE(group->GetCachedConfiguration(types::LeAudioContextType::CONVERSATIONAL) + ->confs.get(le_audio::types::kLeAudioDirectionSink) + .size()); + ASSERT_TRUE(group->GetCachedConfiguration(types::LeAudioContextType::CONVERSATIONAL) + ->confs.get(le_audio::types::kLeAudioDirectionSource) + .size()); EXPECT_CALL(mock_audio_hal_client_callbacks_, - OnUnicastMonitorModeStatus( - bluetooth::le_audio::types::kLeAudioDirectionSink, - UnicastMonitorModeStatus::STREAMING_REQUESTED)) - .Times(1); + OnUnicastMonitorModeStatus(bluetooth::le_audio::types::kLeAudioDirectionSink, + UnicastMonitorModeStatus::STREAMING_REQUESTED)) + .Times(1); // Start streaming to trigger next group going to IDLE state LocalAudioSinkResume(); @@ -10291,17 +9356,15 @@ TEST_F_WITH_FLAGS(UnicastTestHandoverMode, Mock::VerifyAndClearExpectations(mock_le_audio_source_hal_client_); - StartStreaming(AUDIO_USAGE_VOICE_COMMUNICATION, AUDIO_CONTENT_TYPE_SPEECH, - group_id); + StartStreaming(AUDIO_USAGE_VOICE_COMMUNICATION, AUDIO_CONTENT_TYPE_SPEECH, group_id); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(mock_le_audio_source_hal_client_); // Stop streaming and expect Service to be informed about straming suspension EXPECT_CALL(mock_audio_hal_client_callbacks_, - OnUnicastMonitorModeStatus( - bluetooth::le_audio::types::kLeAudioDirectionSink, - UnicastMonitorModeStatus::STREAMING_SUSPENDED)) - .Times(1); + OnUnicastMonitorModeStatus(bluetooth::le_audio::types::kLeAudioDirectionSink, + UnicastMonitorModeStatus::STREAMING_SUSPENDED)) + .Times(1); // Stop StopStreaming(group_id, true); @@ -10321,55 +9384,44 @@ TEST_F_WITH_FLAGS(UnicastTestHandoverMode, // De-activate monitoring mode EXPECT_CALL(*mock_le_audio_sink_hal_client_, Stop()).Times(1); EXPECT_CALL(*mock_le_audio_sink_hal_client_, OnDestroyed()).Times(1); - do_in_main_thread( - FROM_HERE, - base::BindOnce(&LeAudioClient::SetUnicastMonitorMode, - base::Unretained(LeAudioClient::Get()), - bluetooth::le_audio::types::kLeAudioDirectionSink, - false /* enable */)); + do_in_main_thread(FROM_HERE, base::BindOnce(&LeAudioClient::SetUnicastMonitorMode, + base::Unretained(LeAudioClient::Get()), + bluetooth::le_audio::types::kLeAudioDirectionSink, + false /* enable */)); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(mock_le_audio_sink_hal_client_); } -TEST_F_WITH_FLAGS(UnicastTestHandoverMode, - SetSinkMonitorModeWhileUnicastIsInactive, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG( - TEST_BT, leaudio_broadcast_audio_handover_policies))) { +TEST_F_WITH_FLAGS(UnicastTestHandoverMode, SetSinkMonitorModeWhileUnicastIsInactive, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, + leaudio_broadcast_audio_handover_policies))) { uint8_t group_size = 2; int group_id = 2; // Imitate activation of monitor mode - do_in_main_thread( - FROM_HERE, - base::BindOnce(&LeAudioClient::SetUnicastMonitorMode, - base::Unretained(LeAudioClient::Get()), - bluetooth::le_audio::types::kLeAudioDirectionSink, - true /* enable */)); + do_in_main_thread(FROM_HERE, base::BindOnce(&LeAudioClient::SetUnicastMonitorMode, + base::Unretained(LeAudioClient::Get()), + bluetooth::le_audio::types::kLeAudioDirectionSink, + true /* enable */)); // Report working CSIS - ON_CALL(mock_csis_client_module_, IsCsisClientRunning()) - .WillByDefault(Return(true)); + ON_CALL(mock_csis_client_module_, IsCsisClientRunning()).WillByDefault(Return(true)); ON_CALL(mock_csis_client_module_, GetDesiredSize(group_id)) - .WillByDefault(Invoke([&](int group_id) { return group_size; })); + .WillByDefault(Invoke([&](int group_id) { return group_size; })); // First earbud const RawAddress test_address0 = GetTestAddress(0); - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, true)) - .Times(1); - ConnectCsisDevice(test_address0, 1 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontLeft, - codec_spec_conf::kLeAudioLocationFrontLeft, group_size, - group_id, 1 /* rank*/); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, true)).Times(1); + ConnectCsisDevice(test_address0, 1 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontLeft, + codec_spec_conf::kLeAudioLocationFrontLeft, group_size, group_id, 1 /* rank*/); // Second earbud const RawAddress test_address1 = GetTestAddress(1); - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, true)) - .Times(1); - ConnectCsisDevice(test_address1, 2 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontRight, - codec_spec_conf::kLeAudioLocationFrontRight, group_size, - group_id, 2 /* rank*/, true /*connect_through_csis*/); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, true)).Times(1); + ConnectCsisDevice(test_address1, 2 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontRight, + codec_spec_conf::kLeAudioLocationFrontRight, group_size, group_id, 2 /* rank*/, + true /*connect_through_csis*/); // Start streaming EXPECT_CALL(*mock_le_audio_source_hal_client_, Start(_, _, _)).Times(1); @@ -10381,13 +9433,11 @@ TEST_F_WITH_FLAGS(UnicastTestHandoverMode, // Expect no streaming request on stream resume when group is already active EXPECT_CALL(mock_audio_hal_client_callbacks_, - OnUnicastMonitorModeStatus( - bluetooth::le_audio::types::kLeAudioDirectionSink, - UnicastMonitorModeStatus::STREAMING_REQUESTED)) - .Times(0); + OnUnicastMonitorModeStatus(bluetooth::le_audio::types::kLeAudioDirectionSink, + UnicastMonitorModeStatus::STREAMING_REQUESTED)) + .Times(0); - StartStreaming(AUDIO_USAGE_VOICE_COMMUNICATION, AUDIO_CONTENT_TYPE_SPEECH, - group_id); + StartStreaming(AUDIO_USAGE_VOICE_COMMUNICATION, AUDIO_CONTENT_TYPE_SPEECH, group_id); Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); Mock::VerifyAndClearExpectations(mock_le_audio_source_hal_client_); @@ -10403,23 +9453,20 @@ TEST_F_WITH_FLAGS(UnicastTestHandoverMode, // Stop streaming and expect Service to be informed about straming suspension EXPECT_CALL(mock_audio_hal_client_callbacks_, - OnUnicastMonitorModeStatus( - bluetooth::le_audio::types::kLeAudioDirectionSink, - UnicastMonitorModeStatus::STREAMING_SUSPENDED)) - .Times(1); + OnUnicastMonitorModeStatus(bluetooth::le_audio::types::kLeAudioDirectionSink, + UnicastMonitorModeStatus::STREAMING_SUSPENDED)) + .Times(1); // Stop StopStreaming(group_id, true); // Check if cache configuration is still present - ASSERT_TRUE( - group->GetCachedConfiguration(types::LeAudioContextType::CONVERSATIONAL) - ->confs.get(le_audio::types::kLeAudioDirectionSink) - .size()); - ASSERT_TRUE( - group->GetCachedConfiguration(types::LeAudioContextType::CONVERSATIONAL) - ->confs.get(le_audio::types::kLeAudioDirectionSource) - .size()); + ASSERT_TRUE(group->GetCachedConfiguration(types::LeAudioContextType::CONVERSATIONAL) + ->confs.get(le_audio::types::kLeAudioDirectionSink) + .size()); + ASSERT_TRUE(group->GetCachedConfiguration(types::LeAudioContextType::CONVERSATIONAL) + ->confs.get(le_audio::types::kLeAudioDirectionSource) + .size()); // Release, Sink HAL client should remain in monitor mode EXPECT_CALL(*mock_le_audio_source_hal_client_, Stop()).Times(1); @@ -10434,55 +9481,44 @@ TEST_F_WITH_FLAGS(UnicastTestHandoverMode, Mock::VerifyAndClearExpectations(mock_le_audio_sink_hal_client_); // Setting group inactive, shall not change cached configuration - ASSERT_TRUE( - group->GetCachedConfiguration(types::LeAudioContextType::CONVERSATIONAL) - ->confs.get(le_audio::types::kLeAudioDirectionSink) - .size()); - ASSERT_TRUE( - group->GetCachedConfiguration(types::LeAudioContextType::CONVERSATIONAL) - ->confs.get(le_audio::types::kLeAudioDirectionSource) - .size()); + ASSERT_TRUE(group->GetCachedConfiguration(types::LeAudioContextType::CONVERSATIONAL) + ->confs.get(le_audio::types::kLeAudioDirectionSink) + .size()); + ASSERT_TRUE(group->GetCachedConfiguration(types::LeAudioContextType::CONVERSATIONAL) + ->confs.get(le_audio::types::kLeAudioDirectionSource) + .size()); } -TEST_F_WITH_FLAGS(UnicastTestHandoverMode, - ClearSinkMonitorModeWhileUnicastIsActive, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG( - TEST_BT, leaudio_broadcast_audio_handover_policies))) { +TEST_F_WITH_FLAGS(UnicastTestHandoverMode, ClearSinkMonitorModeWhileUnicastIsActive, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, + leaudio_broadcast_audio_handover_policies))) { uint8_t group_size = 2; int group_id = 2; // Imitate activation of monitor mode - do_in_main_thread( - FROM_HERE, - base::BindOnce(&LeAudioClient::SetUnicastMonitorMode, - base::Unretained(LeAudioClient::Get()), - bluetooth::le_audio::types::kLeAudioDirectionSink, - true /* enable */)); + do_in_main_thread(FROM_HERE, base::BindOnce(&LeAudioClient::SetUnicastMonitorMode, + base::Unretained(LeAudioClient::Get()), + bluetooth::le_audio::types::kLeAudioDirectionSink, + true /* enable */)); // Report working CSIS - ON_CALL(mock_csis_client_module_, IsCsisClientRunning()) - .WillByDefault(Return(true)); + ON_CALL(mock_csis_client_module_, IsCsisClientRunning()).WillByDefault(Return(true)); ON_CALL(mock_csis_client_module_, GetDesiredSize(group_id)) - .WillByDefault(Invoke([&](int group_id) { return group_size; })); + .WillByDefault(Invoke([&](int group_id) { return group_size; })); // First earbud const RawAddress test_address0 = GetTestAddress(0); - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, true)) - .Times(1); - ConnectCsisDevice(test_address0, 1 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontLeft, - codec_spec_conf::kLeAudioLocationFrontLeft, group_size, - group_id, 1 /* rank*/); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, true)).Times(1); + ConnectCsisDevice(test_address0, 1 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontLeft, + codec_spec_conf::kLeAudioLocationFrontLeft, group_size, group_id, 1 /* rank*/); // Second earbud const RawAddress test_address1 = GetTestAddress(1); - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, true)) - .Times(1); - ConnectCsisDevice(test_address1, 2 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontRight, - codec_spec_conf::kLeAudioLocationFrontRight, group_size, - group_id, 2 /* rank*/, true /*connect_through_csis*/); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, true)).Times(1); + ConnectCsisDevice(test_address1, 2 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontRight, + codec_spec_conf::kLeAudioLocationFrontRight, group_size, group_id, 2 /* rank*/, + true /*connect_through_csis*/); // Start streaming EXPECT_CALL(*mock_le_audio_source_hal_client_, Start(_, _, _)).Times(1); @@ -10494,13 +9530,11 @@ TEST_F_WITH_FLAGS(UnicastTestHandoverMode, // Expect no streaming request on stream resume when group is already active EXPECT_CALL(mock_audio_hal_client_callbacks_, - OnUnicastMonitorModeStatus( - bluetooth::le_audio::types::kLeAudioDirectionSink, - UnicastMonitorModeStatus::STREAMING_REQUESTED)) - .Times(0); + OnUnicastMonitorModeStatus(bluetooth::le_audio::types::kLeAudioDirectionSink, + UnicastMonitorModeStatus::STREAMING_REQUESTED)) + .Times(0); - StartStreaming(AUDIO_USAGE_VOICE_COMMUNICATION, AUDIO_CONTENT_TYPE_SPEECH, - group_id); + StartStreaming(AUDIO_USAGE_VOICE_COMMUNICATION, AUDIO_CONTENT_TYPE_SPEECH, group_id); Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); Mock::VerifyAndClearExpectations(mock_le_audio_source_hal_client_); @@ -10515,26 +9549,22 @@ TEST_F_WITH_FLAGS(UnicastTestHandoverMode, auto group = streaming_groups.at(group_id); // De-activate monitoring mode - do_in_main_thread( - FROM_HERE, - base::BindOnce(&LeAudioClient::SetUnicastMonitorMode, - base::Unretained(LeAudioClient::Get()), - bluetooth::le_audio::types::kLeAudioDirectionSink, - false /* enable */)); + do_in_main_thread(FROM_HERE, base::BindOnce(&LeAudioClient::SetUnicastMonitorMode, + base::Unretained(LeAudioClient::Get()), + bluetooth::le_audio::types::kLeAudioDirectionSink, + false /* enable */)); // Stop StopStreaming(group_id, true); Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); // Check if cache configuration is still present - ASSERT_TRUE( - group->GetCachedConfiguration(types::LeAudioContextType::CONVERSATIONAL) - ->confs.get(le_audio::types::kLeAudioDirectionSink) - .size()); - ASSERT_TRUE( - group->GetCachedConfiguration(types::LeAudioContextType::CONVERSATIONAL) - ->confs.get(le_audio::types::kLeAudioDirectionSource) - .size()); + ASSERT_TRUE(group->GetCachedConfiguration(types::LeAudioContextType::CONVERSATIONAL) + ->confs.get(le_audio::types::kLeAudioDirectionSink) + .size()); + ASSERT_TRUE(group->GetCachedConfiguration(types::LeAudioContextType::CONVERSATIONAL) + ->confs.get(le_audio::types::kLeAudioDirectionSource) + .size()); // Release of sink and source hals due to de-activating monitor mode EXPECT_CALL(*mock_le_audio_source_hal_client_, Stop()).Times(1); @@ -10548,20 +9578,17 @@ TEST_F_WITH_FLAGS(UnicastTestHandoverMode, Mock::VerifyAndClearExpectations(mock_le_audio_sink_hal_client_); // Setting group inactive, shall not change cached configuration - ASSERT_TRUE( - group->GetCachedConfiguration(types::LeAudioContextType::CONVERSATIONAL) - ->confs.get(le_audio::types::kLeAudioDirectionSink) - .size()); - ASSERT_TRUE( - group->GetCachedConfiguration(types::LeAudioContextType::CONVERSATIONAL) - ->confs.get(le_audio::types::kLeAudioDirectionSource) - .size()); + ASSERT_TRUE(group->GetCachedConfiguration(types::LeAudioContextType::CONVERSATIONAL) + ->confs.get(le_audio::types::kLeAudioDirectionSink) + .size()); + ASSERT_TRUE(group->GetCachedConfiguration(types::LeAudioContextType::CONVERSATIONAL) + ->confs.get(le_audio::types::kLeAudioDirectionSource) + .size()); } -TEST_F_WITH_FLAGS(UnicastTestHandoverMode, - SetAndClearSinkMonitorModeWhileUnicastIsInactive, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG( - TEST_BT, leaudio_broadcast_audio_handover_policies))) { +TEST_F_WITH_FLAGS(UnicastTestHandoverMode, SetAndClearSinkMonitorModeWhileUnicastIsInactive, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, + leaudio_broadcast_audio_handover_policies))) { EXPECT_CALL(*mock_le_audio_source_hal_client_, Start(_, _, _)).Times(0); EXPECT_CALL(*mock_le_audio_source_hal_client_, Stop()).Times(0); EXPECT_CALL(*mock_le_audio_source_hal_client_, OnDestroyed()).Times(0); @@ -10570,18 +9597,14 @@ TEST_F_WITH_FLAGS(UnicastTestHandoverMode, EXPECT_CALL(*mock_le_audio_sink_hal_client_, OnDestroyed()).Times(0); // Imitate activation of monitor mode - do_in_main_thread( - FROM_HERE, - base::BindOnce(&LeAudioClient::SetUnicastMonitorMode, - base::Unretained(LeAudioClient::Get()), - bluetooth::le_audio::types::kLeAudioDirectionSink, - true /* enable */)); - do_in_main_thread( - FROM_HERE, - base::BindOnce(&LeAudioClient::SetUnicastMonitorMode, - base::Unretained(LeAudioClient::Get()), - bluetooth::le_audio::types::kLeAudioDirectionSink, - false /* enable */)); + do_in_main_thread(FROM_HERE, base::BindOnce(&LeAudioClient::SetUnicastMonitorMode, + base::Unretained(LeAudioClient::Get()), + bluetooth::le_audio::types::kLeAudioDirectionSink, + true /* enable */)); + do_in_main_thread(FROM_HERE, base::BindOnce(&LeAudioClient::SetUnicastMonitorMode, + base::Unretained(LeAudioClient::Get()), + bluetooth::le_audio::types::kLeAudioDirectionSink, + false /* enable */)); SyncOnMainLoop(); @@ -10589,34 +9612,29 @@ TEST_F_WITH_FLAGS(UnicastTestHandoverMode, Mock::VerifyAndClearExpectations(mock_le_audio_sink_hal_client_); } -TEST_F_WITH_FLAGS(UnicastTestHandoverMode, - SetSourceMonitorModeWhileUnicastIsInactive, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG( - TEST_BT, leaudio_broadcast_audio_handover_policies))) { +TEST_F_WITH_FLAGS(UnicastTestHandoverMode, SetSourceMonitorModeWhileUnicastIsInactive, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, + leaudio_broadcast_audio_handover_policies))) { /* Enabling monitor mode for source while group is not active should result in * sending STREAMING_SUSPENDED notification. */ EXPECT_CALL(mock_audio_hal_client_callbacks_, - OnUnicastMonitorModeStatus( - bluetooth::le_audio::types::kLeAudioDirectionSource, - UnicastMonitorModeStatus::STREAMING_SUSPENDED)) - .Times(1); + OnUnicastMonitorModeStatus(bluetooth::le_audio::types::kLeAudioDirectionSource, + UnicastMonitorModeStatus::STREAMING_SUSPENDED)) + .Times(1); // Imitate activation of monitor mode - do_in_main_thread( - FROM_HERE, - base::BindOnce(&LeAudioClient::SetUnicastMonitorMode, - base::Unretained(LeAudioClient::Get()), - bluetooth::le_audio::types::kLeAudioDirectionSource, - true /* enable */)); + do_in_main_thread(FROM_HERE, base::BindOnce(&LeAudioClient::SetUnicastMonitorMode, + base::Unretained(LeAudioClient::Get()), + bluetooth::le_audio::types::kLeAudioDirectionSource, + true /* enable */)); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); } -TEST_F_WITH_FLAGS(UnicastTestHandoverMode, - SetSourceMonitorModeWhileUnicastIsNotStreaming, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG( - TEST_BT, leaudio_broadcast_audio_handover_policies))) { +TEST_F_WITH_FLAGS(UnicastTestHandoverMode, SetSourceMonitorModeWhileUnicastIsNotStreaming, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, + leaudio_broadcast_audio_handover_policies))) { int group_id = 2; LeAudioClient::Get()->GroupSetActive(group_id); @@ -10625,53 +9643,43 @@ TEST_F_WITH_FLAGS(UnicastTestHandoverMode, * sending STREAMING_SUSPENDED notification. */ EXPECT_CALL(mock_audio_hal_client_callbacks_, - OnUnicastMonitorModeStatus( - bluetooth::le_audio::types::kLeAudioDirectionSource, - UnicastMonitorModeStatus::STREAMING_SUSPENDED)) - .Times(1); + OnUnicastMonitorModeStatus(bluetooth::le_audio::types::kLeAudioDirectionSource, + UnicastMonitorModeStatus::STREAMING_SUSPENDED)) + .Times(1); // Imitate activation of monitor mode - do_in_main_thread( - FROM_HERE, - base::BindOnce(&LeAudioClient::SetUnicastMonitorMode, - base::Unretained(LeAudioClient::Get()), - bluetooth::le_audio::types::kLeAudioDirectionSource, - true /* enable */)); + do_in_main_thread(FROM_HERE, base::BindOnce(&LeAudioClient::SetUnicastMonitorMode, + base::Unretained(LeAudioClient::Get()), + bluetooth::le_audio::types::kLeAudioDirectionSource, + true /* enable */)); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); } -TEST_F_WITH_FLAGS(UnicastTestHandoverMode, - SetSourceMonitorModeWhileUnicastIsActive, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG( - TEST_BT, leaudio_broadcast_audio_handover_policies))) { +TEST_F_WITH_FLAGS(UnicastTestHandoverMode, SetSourceMonitorModeWhileUnicastIsActive, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, + leaudio_broadcast_audio_handover_policies))) { uint8_t group_size = 2; int group_id = 2; // Report working CSIS - ON_CALL(mock_csis_client_module_, IsCsisClientRunning()) - .WillByDefault(Return(true)); + ON_CALL(mock_csis_client_module_, IsCsisClientRunning()).WillByDefault(Return(true)); // First earbud const RawAddress test_address0 = GetTestAddress(0); - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, true)) - .Times(1); - ConnectCsisDevice(test_address0, 1 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontLeft, - codec_spec_conf::kLeAudioLocationFrontLeft, group_size, - group_id, 1 /* rank*/); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, true)).Times(1); + ConnectCsisDevice(test_address0, 1 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontLeft, + codec_spec_conf::kLeAudioLocationFrontLeft, group_size, group_id, 1 /* rank*/); // Second earbud const RawAddress test_address1 = GetTestAddress(1); - EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, true)) - .Times(1); - ConnectCsisDevice(test_address1, 2 /*conn_id*/, - codec_spec_conf::kLeAudioLocationFrontRight, - codec_spec_conf::kLeAudioLocationFrontRight, group_size, - group_id, 2 /* rank*/, true /*connect_through_csis*/); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, true)).Times(1); + ConnectCsisDevice(test_address1, 2 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontRight, + codec_spec_conf::kLeAudioLocationFrontRight, group_size, group_id, 2 /* rank*/, + true /*connect_through_csis*/); ON_CALL(mock_csis_client_module_, GetDesiredSize(group_id)) - .WillByDefault(Invoke([&](int group_id) { return 2; })); + .WillByDefault(Invoke([&](int group_id) { return 2; })); // Start streaming EXPECT_CALL(*mock_le_audio_source_hal_client_, Start(_, _, _)).Times(1); @@ -10679,8 +9687,7 @@ TEST_F_WITH_FLAGS(UnicastTestHandoverMode, LeAudioClient::Get()->GroupSetActive(group_id); SyncOnMainLoop(); - StartStreaming(AUDIO_USAGE_VOICE_COMMUNICATION, AUDIO_CONTENT_TYPE_SPEECH, - group_id); + StartStreaming(AUDIO_USAGE_VOICE_COMMUNICATION, AUDIO_CONTENT_TYPE_SPEECH, group_id); Mock::VerifyAndClearExpectations(mock_le_audio_source_hal_client_); Mock::VerifyAndClearExpectations(mock_le_audio_sink_hal_client_); @@ -10695,18 +9702,15 @@ TEST_F_WITH_FLAGS(UnicastTestHandoverMode, * sending STREAMING notification. */ EXPECT_CALL(mock_audio_hal_client_callbacks_, - OnUnicastMonitorModeStatus( - bluetooth::le_audio::types::kLeAudioDirectionSource, - UnicastMonitorModeStatus::STREAMING)) - .Times(1); + OnUnicastMonitorModeStatus(bluetooth::le_audio::types::kLeAudioDirectionSource, + UnicastMonitorModeStatus::STREAMING)) + .Times(1); // Imitate activation of monitor mode - do_in_main_thread( - FROM_HERE, - base::BindOnce(&LeAudioClient::SetUnicastMonitorMode, - base::Unretained(LeAudioClient::Get()), - bluetooth::le_audio::types::kLeAudioDirectionSource, - true /* enable */)); + do_in_main_thread(FROM_HERE, base::BindOnce(&LeAudioClient::SetUnicastMonitorMode, + base::Unretained(LeAudioClient::Get()), + bluetooth::le_audio::types::kLeAudioDirectionSource, + true /* enable */)); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); @@ -10715,23 +9719,20 @@ TEST_F_WITH_FLAGS(UnicastTestHandoverMode, // Stop streaming and expect Service to be informed about straming suspension EXPECT_CALL(mock_audio_hal_client_callbacks_, - OnUnicastMonitorModeStatus( - bluetooth::le_audio::types::kLeAudioDirectionSource, - UnicastMonitorModeStatus::STREAMING_SUSPENDED)) - .Times(1); + OnUnicastMonitorModeStatus(bluetooth::le_audio::types::kLeAudioDirectionSource, + UnicastMonitorModeStatus::STREAMING_SUSPENDED)) + .Times(1); // Stop StopStreaming(group_id, true); // Check if cache configuration is still present - ASSERT_TRUE( - group->GetCachedConfiguration(types::LeAudioContextType::CONVERSATIONAL) - ->confs.get(le_audio::types::kLeAudioDirectionSink) - .size()); - ASSERT_TRUE( - group->GetCachedConfiguration(types::LeAudioContextType::CONVERSATIONAL) - ->confs.get(le_audio::types::kLeAudioDirectionSource) - .size()); + ASSERT_TRUE(group->GetCachedConfiguration(types::LeAudioContextType::CONVERSATIONAL) + ->confs.get(le_audio::types::kLeAudioDirectionSink) + .size()); + ASSERT_TRUE(group->GetCachedConfiguration(types::LeAudioContextType::CONVERSATIONAL) + ->confs.get(le_audio::types::kLeAudioDirectionSource) + .size()); // Both Sink and Source HAL clients should be stopped EXPECT_CALL(*mock_le_audio_source_hal_client_, Stop()).Times(1); @@ -10750,28 +9751,24 @@ TEST_F_WITH_FLAGS(UnicastTestHandoverMode, RegisterSinkHalClientMock(); // Setting group inactive, shall not change cached configuration - ASSERT_TRUE( - group->GetCachedConfiguration(types::LeAudioContextType::CONVERSATIONAL) - ->confs.get(le_audio::types::kLeAudioDirectionSink) - .size()); - ASSERT_TRUE( - group->GetCachedConfiguration(types::LeAudioContextType::CONVERSATIONAL) - ->confs.get(le_audio::types::kLeAudioDirectionSource) - .size()); + ASSERT_TRUE(group->GetCachedConfiguration(types::LeAudioContextType::CONVERSATIONAL) + ->confs.get(le_audio::types::kLeAudioDirectionSink) + .size()); + ASSERT_TRUE(group->GetCachedConfiguration(types::LeAudioContextType::CONVERSATIONAL) + ->confs.get(le_audio::types::kLeAudioDirectionSource) + .size()); EXPECT_CALL(mock_audio_hal_client_callbacks_, - OnUnicastMonitorModeStatus( - bluetooth::le_audio::types::kLeAudioDirectionSource, - UnicastMonitorModeStatus::STREAMING_REQUESTED)) - .Times(1); + OnUnicastMonitorModeStatus(bluetooth::le_audio::types::kLeAudioDirectionSource, + UnicastMonitorModeStatus::STREAMING_REQUESTED)) + .Times(1); EXPECT_CALL(*mock_le_audio_source_hal_client_, Start(_, _, _)).Times(1); EXPECT_CALL(*mock_le_audio_sink_hal_client_, Start(_, _, _)).Times(1); LeAudioClient::Get()->GroupSetActive(group_id); // Start streaming to trigger next group going to IDLE state - StartStreaming(AUDIO_USAGE_VOICE_COMMUNICATION, AUDIO_CONTENT_TYPE_SPEECH, - group_id); + StartStreaming(AUDIO_USAGE_VOICE_COMMUNICATION, AUDIO_CONTENT_TYPE_SPEECH, group_id); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); @@ -10780,10 +9777,9 @@ TEST_F_WITH_FLAGS(UnicastTestHandoverMode, // Stop streaming and expect Service to be informed about straming suspension EXPECT_CALL(mock_audio_hal_client_callbacks_, - OnUnicastMonitorModeStatus( - bluetooth::le_audio::types::kLeAudioDirectionSource, - UnicastMonitorModeStatus::STREAMING_SUSPENDED)) - .Times(1); + OnUnicastMonitorModeStatus(bluetooth::le_audio::types::kLeAudioDirectionSource, + UnicastMonitorModeStatus::STREAMING_SUSPENDED)) + .Times(1); // Stop StopStreaming(group_id, true); @@ -10802,75 +9798,66 @@ TEST_F_WITH_FLAGS(UnicastTestHandoverMode, // De-activate monitoring mode EXPECT_CALL(mock_audio_hal_client_callbacks_, - OnUnicastMonitorModeStatus( - bluetooth::le_audio::types::kLeAudioDirectionSource, - UnicastMonitorModeStatus::STREAMING_SUSPENDED)) - .Times(0); + OnUnicastMonitorModeStatus(bluetooth::le_audio::types::kLeAudioDirectionSource, + UnicastMonitorModeStatus::STREAMING_SUSPENDED)) + .Times(0); - do_in_main_thread( - FROM_HERE, - base::BindOnce(&LeAudioClient::SetUnicastMonitorMode, - base::Unretained(LeAudioClient::Get()), - bluetooth::le_audio::types::kLeAudioDirectionSink, - false /* enable */)); + do_in_main_thread(FROM_HERE, base::BindOnce(&LeAudioClient::SetUnicastMonitorMode, + base::Unretained(LeAudioClient::Get()), + bluetooth::le_audio::types::kLeAudioDirectionSink, + false /* enable */)); } TEST_F(UnicastTestHandoverMode, SetAllowedContextMask) { const RawAddress test_address0 = GetTestAddress(0); int group_id = bluetooth::groups::kGroupUnknown; - available_snk_context_types_ = (types::LeAudioContextType::RINGTONE | - types::LeAudioContextType::CONVERSATIONAL | - types::LeAudioContextType::UNSPECIFIED | - types::LeAudioContextType::MEDIA | - types::LeAudioContextType::SOUNDEFFECTS) - .value(); + available_snk_context_types_ = + (types::LeAudioContextType::RINGTONE | types::LeAudioContextType::CONVERSATIONAL | + types::LeAudioContextType::UNSPECIFIED | types::LeAudioContextType::MEDIA | + types::LeAudioContextType::SOUNDEFFECTS) + .value(); available_src_context_types_ = available_snk_context_types_; supported_snk_context_types_ = types::kLeAudioContextAllTypes.value(); - supported_src_context_types_ = (types::kLeAudioContextAllRemoteSource | - types::LeAudioContextType::UNSPECIFIED) - .value(); + supported_src_context_types_ = + (types::kLeAudioContextAllRemoteSource | types::LeAudioContextType::UNSPECIFIED).value(); /* Don't allow SOUNDEFFECTS context type to be streamed */ - int allowed_context_types = (types::LeAudioContextType::RINGTONE | - types::LeAudioContextType::CONVERSATIONAL | - types::LeAudioContextType::UNSPECIFIED | - types::LeAudioContextType::MEDIA) - .value(); + int allowed_context_types = + (types::LeAudioContextType::RINGTONE | types::LeAudioContextType::CONVERSATIONAL | + types::LeAudioContextType::UNSPECIFIED | types::LeAudioContextType::MEDIA) + .value(); - SetSampleDatabaseEarbudsValid( - 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, - default_channel_cnt, 0x0004, false /*add_csis*/, true /*add_cas*/, - true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, - 0 /*rank*/); + SetSampleDatabaseEarbudsValid(1, test_address0, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, + default_channel_cnt, 0x0004, false /*add_csis*/, true /*add_cas*/, + true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, + 0 /*rank*/); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupNodeStatus(test_address0, _, GroupNodeStatus::ADDED)) - .WillOnce(DoAll(SaveArg<1>(&group_id))); + .WillOnce(DoAll(SaveArg<1>(&group_id))); ConnectLeAudio(test_address0); ASSERT_NE(group_id, bluetooth::groups::kGroupUnknown); EXPECT_CALL(*mock_le_audio_source_hal_client_, Start(_, _, _)).Times(1); - types::BidirectionalPair metadata = { - .sink = types::AudioContexts(), .source = types::AudioContexts()}; - EXPECT_CALL( - mock_state_machine_, - StartStream(_, types::LeAudioContextType::SOUNDEFFECTS, metadata, _)) - .Times(0); + types::BidirectionalPair metadata = {.sink = types::AudioContexts(), + .source = types::AudioContexts()}; + EXPECT_CALL(mock_state_machine_, + StartStream(_, types::LeAudioContextType::SOUNDEFFECTS, metadata, _)) + .Times(0); LeAudioClient::Get()->GroupSetActive(group_id); SyncOnMainLoop(); /* Set the same allowed context mask for sink and source */ - LeAudioClient::Get()->SetGroupAllowedContextMask( - group_id, allowed_context_types, allowed_context_types); + LeAudioClient::Get()->SetGroupAllowedContextMask(group_id, allowed_context_types, + allowed_context_types); - StartStreaming(AUDIO_USAGE_ASSISTANCE_SONIFICATION, - AUDIO_CONTENT_TYPE_UNKNOWN, group_id, AUDIO_SOURCE_INVALID, - false, false); + StartStreaming(AUDIO_USAGE_ASSISTANCE_SONIFICATION, AUDIO_CONTENT_TYPE_UNKNOWN, group_id, + AUDIO_SOURCE_INVALID, false, false); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); @@ -10878,70 +9865,61 @@ TEST_F(UnicastTestHandoverMode, SetAllowedContextMask) { } TEST_F_WITH_FLAGS(UnicastTest, NoContextvalidateStreamingRequest, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG( - TEST_BT, - leaudio_no_context_validate_streaming_request))) { + REQUIRES_FLAGS_ENABLED( + ACONFIG_FLAG(TEST_BT, leaudio_no_context_validate_streaming_request))) { const RawAddress test_address0 = GetTestAddress(0); int group_id = bluetooth::groups::kGroupUnknown; - available_snk_context_types_ = (types::LeAudioContextType::RINGTONE | - types::LeAudioContextType::CONVERSATIONAL | - types::LeAudioContextType::UNSPECIFIED | - types::LeAudioContextType::MEDIA) - .value(); + available_snk_context_types_ = + (types::LeAudioContextType::RINGTONE | types::LeAudioContextType::CONVERSATIONAL | + types::LeAudioContextType::UNSPECIFIED | types::LeAudioContextType::MEDIA) + .value(); available_src_context_types_ = available_snk_context_types_; supported_snk_context_types_ = types::kLeAudioContextAllTypes.value(); - supported_src_context_types_ = (types::kLeAudioContextAllRemoteSource | - types::LeAudioContextType::UNSPECIFIED) - .value(); + supported_src_context_types_ = + (types::kLeAudioContextAllRemoteSource | types::LeAudioContextType::UNSPECIFIED).value(); - SetSampleDatabaseEarbudsValid( - 1, test_address0, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, - default_channel_cnt, 0x0004, false /*add_csis*/, true /*add_cas*/, - true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, - 0 /*rank*/); + SetSampleDatabaseEarbudsValid(1, test_address0, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationStereo, default_channel_cnt, + default_channel_cnt, 0x0004, false /*add_csis*/, true /*add_cas*/, + true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, + 0 /*rank*/); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupNodeStatus(test_address0, _, GroupNodeStatus::ADDED)) - .WillOnce(DoAll(SaveArg<1>(&group_id))); + .WillOnce(DoAll(SaveArg<1>(&group_id))); ConnectLeAudio(test_address0); ASSERT_NE(group_id, bluetooth::groups::kGroupUnknown); EXPECT_CALL(*mock_le_audio_source_hal_client_, Start(_, _, _)).Times(1); - types::BidirectionalPair metadata = { - .sink = types::AudioContexts(), .source = types::AudioContexts()}; - EXPECT_CALL( - mock_state_machine_, - StartStream(_, types::LeAudioContextType::SOUNDEFFECTS, metadata, _)) - .Times(0); + types::BidirectionalPair metadata = {.sink = types::AudioContexts(), + .source = types::AudioContexts()}; + EXPECT_CALL(mock_state_machine_, + StartStream(_, types::LeAudioContextType::SOUNDEFFECTS, metadata, _)) + .Times(0); LeAudioClient::Get()->GroupSetActive(group_id); // Imitate activation of monitor mode - do_in_main_thread( - FROM_HERE, - base::BindOnce(&LeAudioClient::SetUnicastMonitorMode, - base::Unretained(LeAudioClient::Get()), - bluetooth::le_audio::types::kLeAudioDirectionSource, - true /* enable */)); + do_in_main_thread(FROM_HERE, base::BindOnce(&LeAudioClient::SetUnicastMonitorMode, + base::Unretained(LeAudioClient::Get()), + bluetooth::le_audio::types::kLeAudioDirectionSource, + true /* enable */)); Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); SyncOnMainLoop(); // Stop streaming and expect Service to be informed about straming suspension - EXPECT_CALL( - mock_audio_hal_client_callbacks_, - OnUnicastMonitorModeStatus( - bluetooth::le_audio::types::kLeAudioDirectionSource, - UnicastMonitorModeStatus::STREAMING_REQUESTED_NO_CONTEXT_VALIDATE)) - .Times(1); - - StartStreaming(AUDIO_USAGE_ASSISTANCE_SONIFICATION, - AUDIO_CONTENT_TYPE_UNKNOWN, group_id, AUDIO_SOURCE_INVALID, - false, false); + EXPECT_CALL(mock_audio_hal_client_callbacks_, + OnUnicastMonitorModeStatus( + bluetooth::le_audio::types::kLeAudioDirectionSource, + UnicastMonitorModeStatus::STREAMING_REQUESTED_NO_CONTEXT_VALIDATE)) + .Times(1); + + StartStreaming(AUDIO_USAGE_ASSISTANCE_SONIFICATION, AUDIO_CONTENT_TYPE_UNKNOWN, group_id, + AUDIO_SOURCE_INVALID, false, false); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); @@ -10955,18 +9933,16 @@ TEST_F(UnicastTest, CodecFrameBlocks2) { // Register a on-the-fly hook for codec interface mock mutation to prepare the // codec mock for encoding std::list codec_mocks; - MockCodecInterface::RegisterMockInstanceHook([&](MockCodecInterface* mock, - bool is_destroyed) { + MockCodecInterface::RegisterMockInstanceHook([&](MockCodecInterface* mock, bool is_destroyed) { if (is_destroyed) { log::debug("Codec Interface Destroyed: {}", (long)mock); codec_mocks.remove(mock); } else { log::debug("Codec Interface Created: {}", (long)mock); ON_CALL(*mock, GetNumOfSamplesPerChannel()).WillByDefault(Return(960)); - ON_CALL(*mock, GetNumOfBytesPerSample()) - .WillByDefault(Return(2)); // 16bits samples + ON_CALL(*mock, GetNumOfBytesPerSample()).WillByDefault(Return(2)); // 16bits samples ON_CALL(*mock, Encode(_, _, _, _, _)) - .WillByDefault(Return(CodecInterface::Status::STATUS_OK)); + .WillByDefault(Return(CodecInterface::Status::STATUS_OK)); codec_mocks.push_back(mock); } }); @@ -10974,84 +9950,81 @@ TEST_F(UnicastTest, CodecFrameBlocks2) { // Add a frame block PAC passing verifier bool is_fb2_passed_as_requirement = false; ON_CALL(*mock_codec_manager_, GetCodecConfig) - .WillByDefault(Invoke([&](const bluetooth::le_audio::CodecManager:: - UnicastConfigurationRequirements& - requirements, - bluetooth::le_audio::CodecManager:: - UnicastConfigurationVerifier verifier) { - auto filtered = - *bluetooth::le_audio::AudioSetConfigurationProvider::Get() - ->GetConfigurations(requirements.audio_context_type); - // Filter out the dual bidir SWB configurations - if (!bluetooth::le_audio::CodecManager::GetInstance() - ->IsDualBiDirSwbSupported()) { - filtered.erase( - std::remove_if(filtered.begin(), filtered.end(), - [](auto const& el) { - if (el->confs.source.empty()) return false; - return AudioSetConfigurationProvider::Get() - ->CheckConfigurationIsDualBiDirSwb(*el); - }), - filtered.end()); - } - auto cfg = verifier(requirements, &filtered); - if (cfg == nullptr) { - return std::unique_ptr( - nullptr); - } + .WillByDefault(Invoke( + [&](const bluetooth::le_audio::CodecManager::UnicastConfigurationRequirements& + requirements, + bluetooth::le_audio::CodecManager::UnicastConfigurationVerifier verifier) { + auto filtered = *bluetooth::le_audio::AudioSetConfigurationProvider::Get() + ->GetConfigurations(requirements.audio_context_type); + // Filter out the dual bidir SWB configurations + if (!bluetooth::le_audio::CodecManager::GetInstance() + ->IsDualBiDirSwbSupported()) { + filtered.erase( + std::remove_if(filtered.begin(), filtered.end(), + [](auto const& el) { + if (el->confs.source.empty()) { + return false; + } + return AudioSetConfigurationProvider::Get() + ->CheckConfigurationIsDualBiDirSwb(*el); + }), + filtered.end()); + } + auto cfg = verifier(requirements, &filtered); + if (cfg == nullptr) { + return std::unique_ptr(nullptr); + } - auto config = *cfg; - - if (requirements.sink_pacs.has_value()) { - for (auto const& rec : requirements.sink_pacs.value()) { - auto caps = rec.codec_spec_caps.GetAsCoreCodecCapabilities(); - if (caps.HasSupportedMaxCodecFramesPerSdu()) { - if (caps.supported_max_codec_frames_per_sdu.value() == - max_codec_frames_per_sdu) { - // Inject the proper Codec Frames Per SDU as the json - // configs are conservative and will always give us 1 - for (auto& entry : config.confs.sink) { - entry.codec.params.Add( - codec_spec_conf::kLeAudioLtvTypeCodecFrameBlocksPerSdu, - (uint8_t)max_codec_frames_per_sdu); - } - is_fb2_passed_as_requirement = true; - } - } - } - } - return std::make_unique( - config); - })); + auto config = *cfg; + + if (requirements.sink_pacs.has_value()) { + for (auto const& rec : requirements.sink_pacs.value()) { + auto caps = rec.codec_spec_caps.GetAsCoreCodecCapabilities(); + if (caps.HasSupportedMaxCodecFramesPerSdu()) { + if (caps.supported_max_codec_frames_per_sdu.value() == + max_codec_frames_per_sdu) { + // Inject the proper Codec Frames Per SDU as the json + // configs are conservative and will always give us 1 + for (auto& entry : config.confs.sink) { + entry.codec.params.Add( + codec_spec_conf::kLeAudioLtvTypeCodecFrameBlocksPerSdu, + (uint8_t)max_codec_frames_per_sdu); + } + is_fb2_passed_as_requirement = true; + } + } + } + } + return std::make_unique(config); + })); types::BidirectionalPair codec_manager_stream_params; ON_CALL(*mock_codec_manager_, UpdateActiveAudioConfig) - .WillByDefault(Invoke( - [&](const types::BidirectionalPair& stream_params, - types::BidirectionalPair delays_ms, - std::function - updater) { codec_manager_stream_params = stream_params; })); + .WillByDefault( + Invoke([&](const types::BidirectionalPair& stream_params, + types::BidirectionalPair delays_ms, + std::function + updater) { codec_manager_stream_params = stream_params; })); const RawAddress test_address0 = GetTestAddress(0); int group_id = bluetooth::groups::kGroupUnknown; SampleDatabaseParameters remote_params{ - .conn_id = 1, - .addr = test_address0, - .add_csis = false, - .set_size = 0, - .rank = 0, - .max_supported_codec_frames_per_sdu = 2, + .conn_id = 1, + .addr = test_address0, + .add_csis = false, + .set_size = 0, + .rank = 0, + .max_supported_codec_frames_per_sdu = 2, }; SetSampleDatabaseEarbudsValid(remote_params); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) - .Times(1); + .Times(1); EXPECT_CALL(mock_audio_hal_client_callbacks_, OnGroupNodeStatus(test_address0, _, GroupNodeStatus::ADDED)) - .WillOnce(DoAll(SaveArg<1>(&group_id))); + .WillOnce(DoAll(SaveArg<1>(&group_id))); ConnectLeAudio(test_address0); ASSERT_NE(group_id, bluetooth::groups::kGroupUnknown); @@ -11067,8 +10040,7 @@ TEST_F(UnicastTest, CodecFrameBlocks2) { LeAudioClient::Get()->GroupSetActive(group_id); SyncOnMainLoop(); - types::BidirectionalPair> ccids = {.sink = {gmcs_ccid}, - .source = {}}; + types::BidirectionalPair> ccids = {.sink = {gmcs_ccid}, .source = {}}; EXPECT_CALL(mock_state_machine_, StartStream(_, _, _, ccids)).Times(1); block_streaming_state_callback = true; @@ -11091,8 +10063,7 @@ TEST_F(UnicastTest, CodecFrameBlocks2) { if (ase.active) { auto cfg = ase.codec_config.GetAsCoreCodecConfig(); ASSERT_TRUE(cfg.codec_frames_blocks_per_sdu.has_value()); - device_configured_codec_frame_blocks_per_sdu = - cfg.codec_frames_blocks_per_sdu.value(); + device_configured_codec_frame_blocks_per_sdu = cfg.codec_frames_blocks_per_sdu.value(); } } } @@ -11103,30 +10074,26 @@ TEST_F(UnicastTest, CodecFrameBlocks2) { EXPECT_CALL(mock_state_machine_, StopStream(_)).Times(0); do_in_main_thread( - FROM_HERE, - base::BindOnce( - [](int group_id, - bluetooth::le_audio::LeAudioGroupStateMachine::Callbacks* - state_machine_callbacks) { - state_machine_callbacks->StatusReportCb( - group_id, GroupStreamStatus::STREAMING); - }, - group_id, base::Unretained(state_machine_callbacks_))); + FROM_HERE, + base::BindOnce( + [](int group_id, bluetooth::le_audio::LeAudioGroupStateMachine::Callbacks* + state_machine_callbacks) { + state_machine_callbacks->StatusReportCb(group_id, GroupStreamStatus::STREAMING); + }, + group_id, base::Unretained(state_machine_callbacks_))); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(&mock_state_machine_); // Verify Data transfer on one audio source cis constexpr uint8_t cis_count_out = 1; constexpr uint8_t cis_count_in = 0; - TestAudioDataTransfer( - group_id, cis_count_out, cis_count_in, - data_len * device_configured_codec_frame_blocks_per_sdu); + TestAudioDataTransfer(group_id, cis_count_out, cis_count_in, + data_len * device_configured_codec_frame_blocks_per_sdu); ASSERT_NE(codec_mocks.size(), 0ul); // Verify that the initially started session was updated with the new params - ASSERT_EQ(codec_manager_stream_params.sink.codec_frames_blocks_per_sdu, - max_codec_frames_per_sdu); + ASSERT_EQ(codec_manager_stream_params.sink.codec_frames_blocks_per_sdu, max_codec_frames_per_sdu); } } // namespace bluetooth::le_audio diff --git a/system/bta/le_audio/le_audio_health_status.cc b/system/bta/le_audio/le_audio_health_status.cc index 027254b22c1..3b349e81797 100644 --- a/system/bta/le_audio/le_audio_health_status.cc +++ b/system/bta/le_audio/le_audio_health_status.cc @@ -37,7 +37,7 @@ class LeAudioHealthStatusImpl; LeAudioHealthStatusImpl* instance; class LeAudioHealthStatusImpl : public LeAudioHealthStatus { - public: +public: LeAudioHealthStatusImpl(void) { log::debug("Initiated"); } ~LeAudioHealthStatusImpl(void) { clear_module(); } @@ -123,8 +123,7 @@ class LeAudioHealthStatusImpl : public LeAudioHealthStatus { LeAudioDevice* device = device_group->GetFirstDevice(); if (device == nullptr) { - log::error("Front device is null. Number of devices: {}", - device_group->Size()); + log::error("Front device is null. Number of devices: {}", device_group->Size()); return; } // log counter metrics @@ -153,8 +152,7 @@ class LeAudioHealthStatusImpl : public LeAudioHealthStatus { LeAudioHealthBasedAction action = LeAudioHealthBasedAction::NONE; if (group->stream_success_cnt_ == 0) { /* Never succeed in stream creation */ - if ((group->stream_failures_cnt_ >= - MAX_ALLOWED_FAILURES_IN_A_ROW_WITHOUT_SUCCESS)) { + if (group->stream_failures_cnt_ >= MAX_ALLOWED_FAILURES_IN_A_ROW_WITHOUT_SUCCESS) { action = LeAudioHealthBasedAction::DISABLE; } else if (group->stream_context_not_avail_cnt_ >= MAX_ALLOWED_FAILURES_IN_A_ROW_WITHOUT_SUCCESS) { @@ -191,7 +189,7 @@ class LeAudioHealthStatusImpl : public LeAudioHealthStatus { dprintf(fd, "\n"); } - private: +private: static constexpr int MAX_ALLOWED_FAILURES_IN_A_ROW_WITHOUT_SUCCESS = 3; static constexpr int THRESHOLD_FOR_DISABLE_CONSIDERATION = 70; @@ -202,8 +200,7 @@ class LeAudioHealthStatusImpl : public LeAudioHealthStatus { void dumpsys_group(int fd, const group_stats& group) { std::stringstream stream; - stream << "\n group_id: " << group.group_id_ << ": " - << group.latest_recommendation_ + stream << "\n group_id: " << group.group_id_ << ": " << group.latest_recommendation_ << ", success: " << group.stream_success_cnt_ << ", fail total: " << group.stream_failures_cnt_ << ", fail cis: " << group.stream_cis_failures_cnt_ @@ -216,8 +213,7 @@ class LeAudioHealthStatusImpl : public LeAudioHealthStatus { void dumpsys_dev(int fd, const device_stats& dev) { std::stringstream stream; - stream << "\n " << ADDRESS_TO_LOGGABLE_STR(dev.address_) << ": " - << dev.latest_recommendation_ + stream << "\n " << ADDRESS_TO_LOGGABLE_STR(dev.address_) << ": " << dev.latest_recommendation_ << (dev.is_valid_service_ ? " service: OK" : " service : NOK") << (dev.is_valid_group_member_ ? " csis: OK" : " csis : NOK"); @@ -239,8 +235,7 @@ class LeAudioHealthStatusImpl : public LeAudioHealthStatus { } } - void send_recommendation_for_group( - int group_id, const LeAudioHealthBasedAction recommendation) { + void send_recommendation_for_group(int group_id, const LeAudioHealthBasedAction recommendation) { log::debug("group_id: {}, {}", group_id, ToString(recommendation)); /* Notify new user about known groups */ for (auto& cb : callbacks_) { @@ -248,59 +243,52 @@ class LeAudioHealthStatusImpl : public LeAudioHealthStatus { } } - void add_device(const RawAddress& address) { - devices_stats_.emplace_back(device_stats(address)); - } + void add_device(const RawAddress& address) { devices_stats_.emplace_back(device_stats(address)); } - void add_group(int group_id) { - group_stats_.emplace_back(group_stats(group_id)); - } + void add_group(int group_id) { group_stats_.emplace_back(group_stats(group_id)); } void remove_group(int group_id) { if (group_id == kGroupUnknown) { return; } - auto iter = std::find_if( - group_stats_.begin(), group_stats_.end(), - [group_id](const auto& g) { return g.group_id_ == group_id; }); + auto iter = std::find_if(group_stats_.begin(), group_stats_.end(), + [group_id](const auto& g) { return g.group_id_ == group_id; }); if (iter != group_stats_.end()) { group_stats_.erase(iter); } } void remove_device(const RawAddress& address) { - auto iter = std::find_if( - devices_stats_.begin(), devices_stats_.end(), - [address](const auto& d) { return d.address_ == address; }); + auto iter = std::find_if(devices_stats_.begin(), devices_stats_.end(), + [address](const auto& d) { return d.address_ == address; }); if (iter != devices_stats_.end()) { devices_stats_.erase(iter); } } - void register_callback(LeAudioRecommendationActionCb cb) { - callbacks_.push_back(std::move(cb)); - } + void register_callback(LeAudioRecommendationActionCb cb) { callbacks_.push_back(std::move(cb)); } device_stats* find_device(const RawAddress& address) { - auto iter = std::find_if( - devices_stats_.begin(), devices_stats_.end(), - [address](const auto& d) { return d.address_ == address; }); - if (iter == devices_stats_.end()) return nullptr; + auto iter = std::find_if(devices_stats_.begin(), devices_stats_.end(), + [address](const auto& d) { return d.address_ == address; }); + if (iter == devices_stats_.end()) { + return nullptr; + } return &(*iter); } group_stats* find_group(int group_id) { - auto iter = std::find_if( - group_stats_.begin(), group_stats_.end(), - [group_id](const auto& g) { return g.group_id_ == group_id; }); - if (iter == group_stats_.end()) return nullptr; + auto iter = std::find_if(group_stats_.begin(), group_stats_.end(), + [group_id](const auto& g) { return g.group_id_ == group_id; }); + if (iter == group_stats_.end()) { + return nullptr; + } return &(*iter); } - void log_counter_metrics_for_device(LeAudioHealthDeviceStatType type, - bool in_allowlist) { + void log_counter_metrics_for_device(LeAudioHealthDeviceStatType type, bool in_allowlist) { log::debug("in_allowlist: {}, type: {}", in_allowlist, ToString(type)); android::bluetooth::CodePathCounterKeyEnum key; if (in_allowlist) { @@ -308,15 +296,15 @@ class LeAudioHealthStatusImpl : public LeAudioHealthStatus { case LeAudioHealthDeviceStatType::VALID_DB: case LeAudioHealthDeviceStatType::VALID_CSIS: key = android::bluetooth::CodePathCounterKeyEnum:: - LE_AUDIO_ALLOWLIST_DEVICE_HEALTH_STATUS_GOOD; + LE_AUDIO_ALLOWLIST_DEVICE_HEALTH_STATUS_GOOD; break; case LeAudioHealthDeviceStatType::INVALID_DB: key = android::bluetooth::CodePathCounterKeyEnum:: - LE_AUDIO_ALLOWLIST_DEVICE_HEALTH_STATUS_BAD_INVALID_DB; + LE_AUDIO_ALLOWLIST_DEVICE_HEALTH_STATUS_BAD_INVALID_DB; break; case LeAudioHealthDeviceStatType::INVALID_CSIS: key = android::bluetooth::CodePathCounterKeyEnum:: - LE_AUDIO_ALLOWLIST_DEVICE_HEALTH_STATUS_BAD_INVALID_CSIS; + LE_AUDIO_ALLOWLIST_DEVICE_HEALTH_STATUS_BAD_INVALID_CSIS; break; default: log::error("Metric unhandled {}", type); @@ -327,15 +315,15 @@ class LeAudioHealthStatusImpl : public LeAudioHealthStatus { case LeAudioHealthDeviceStatType::VALID_DB: case LeAudioHealthDeviceStatType::VALID_CSIS: key = android::bluetooth::CodePathCounterKeyEnum:: - LE_AUDIO_NONALLOWLIST_DEVICE_HEALTH_STATUS_GOOD; + LE_AUDIO_NONALLOWLIST_DEVICE_HEALTH_STATUS_GOOD; break; case LeAudioHealthDeviceStatType::INVALID_DB: key = android::bluetooth::CodePathCounterKeyEnum:: - LE_AUDIO_NONALLOWLIST_DEVICE_HEALTH_STATUS_BAD_INVALID_DB; + LE_AUDIO_NONALLOWLIST_DEVICE_HEALTH_STATUS_BAD_INVALID_DB; break; case LeAudioHealthDeviceStatType::INVALID_CSIS: key = android::bluetooth::CodePathCounterKeyEnum:: - LE_AUDIO_NONALLOWLIST_DEVICE_HEALTH_STATUS_BAD_INVALID_CSIS; + LE_AUDIO_NONALLOWLIST_DEVICE_HEALTH_STATUS_BAD_INVALID_CSIS; break; default: log::error("Metric unhandled {}", type); @@ -345,23 +333,22 @@ class LeAudioHealthStatusImpl : public LeAudioHealthStatus { bluetooth::shim::CountCounterMetrics(key, 1); } - void log_counter_metrics_for_group(LeAudioHealthGroupStatType type, - bool in_allowlist) { + void log_counter_metrics_for_group(LeAudioHealthGroupStatType type, bool in_allowlist) { log::debug("in_allowlist: {}, type: {}", in_allowlist, ToString(type)); android::bluetooth::CodePathCounterKeyEnum key; if (in_allowlist) { switch (type) { case LeAudioHealthGroupStatType::STREAM_CREATE_SUCCESS: key = android::bluetooth::CodePathCounterKeyEnum:: - LE_AUDIO_ALLOWLIST_GROUP_HEALTH_STATUS_GOOD; + LE_AUDIO_ALLOWLIST_GROUP_HEALTH_STATUS_GOOD; break; case LeAudioHealthGroupStatType::STREAM_CREATE_CIS_FAILED: key = android::bluetooth::CodePathCounterKeyEnum:: - LE_AUDIO_ALLOWLIST_GROUP_HEALTH_STATUS_BAD_ONCE_CIS_FAILED; + LE_AUDIO_ALLOWLIST_GROUP_HEALTH_STATUS_BAD_ONCE_CIS_FAILED; break; case LeAudioHealthGroupStatType::STREAM_CREATE_SIGNALING_FAILED: key = android::bluetooth::CodePathCounterKeyEnum:: - LE_AUDIO_ALLOWLIST_GROUP_HEALTH_STATUS_BAD_ONCE_SIGNALING_FAILED; + LE_AUDIO_ALLOWLIST_GROUP_HEALTH_STATUS_BAD_ONCE_SIGNALING_FAILED; break; default: log::error("Metric unhandled {}", type); @@ -371,15 +358,15 @@ class LeAudioHealthStatusImpl : public LeAudioHealthStatus { switch (type) { case LeAudioHealthGroupStatType::STREAM_CREATE_SUCCESS: key = android::bluetooth::CodePathCounterKeyEnum:: - LE_AUDIO_NONALLOWLIST_GROUP_HEALTH_STATUS_GOOD; + LE_AUDIO_NONALLOWLIST_GROUP_HEALTH_STATUS_GOOD; break; case LeAudioHealthGroupStatType::STREAM_CREATE_CIS_FAILED: key = android::bluetooth::CodePathCounterKeyEnum:: - LE_AUDIO_NONALLOWLIST_GROUP_HEALTH_STATUS_BAD_ONCE_CIS_FAILED; + LE_AUDIO_NONALLOWLIST_GROUP_HEALTH_STATUS_BAD_ONCE_CIS_FAILED; break; case LeAudioHealthGroupStatType::STREAM_CREATE_SIGNALING_FAILED: key = android::bluetooth::CodePathCounterKeyEnum:: - LE_AUDIO_NONALLOWLIST_GROUP_HEALTH_STATUS_BAD_ONCE_SIGNALING_FAILED; + LE_AUDIO_NONALLOWLIST_GROUP_HEALTH_STATUS_BAD_ONCE_SIGNALING_FAILED; break; default: log::error("Metric unhandled {}", type); diff --git a/system/bta/le_audio/le_audio_health_status.h b/system/bta/le_audio/le_audio_health_status.h index d7d833a0060..62b6a17ec17 100644 --- a/system/bta/le_audio/le_audio_health_status.h +++ b/system/bta/le_audio/le_audio_health_status.h @@ -29,7 +29,7 @@ using bluetooth::le_audio::LeAudioHealthBasedAction; namespace bluetooth::le_audio { using LeAudioRecommendationActionCb = base::RepeatingCallback; + const RawAddress& address, int group_id, LeAudioHealthBasedAction action)>; /* This should be set by the client of this module to provide information about * basic LeAudio support of the device which is exposing ASCS UUIDs. Should be @@ -67,7 +67,7 @@ enum class LeAudioHealthGroupStatType { }; class LeAudioHealthStatus { - public: +public: virtual ~LeAudioHealthStatus(void) = default; static LeAudioHealthStatus* Get(void); static void Cleanup(void); @@ -88,7 +88,7 @@ class LeAudioHealthStatus { stream_failures_cnt_(0), stream_cis_failures_cnt_(0), stream_signaling_failures_cnt_(0), - stream_context_not_avail_cnt_(0){}; + stream_context_not_avail_cnt_(0) {} int group_id_; LeAudioHealthBasedAction latest_recommendation_; @@ -105,7 +105,7 @@ class LeAudioHealthStatus { : address_(address), latest_recommendation_(LeAudioHealthBasedAction::NONE), is_valid_service_(true), - is_valid_group_member_(true){}; + is_valid_group_member_(true) {} RawAddress address_; LeAudioHealthBasedAction latest_recommendation_; @@ -114,23 +114,19 @@ class LeAudioHealthStatus { }; }; -inline std::ostream& operator<<( - std::ostream& os, - const bluetooth::le_audio::LeAudioHealthGroupStatType& stat) { +inline std::ostream& operator<<(std::ostream& os, + const bluetooth::le_audio::LeAudioHealthGroupStatType& stat) { switch (stat) { case bluetooth::le_audio::LeAudioHealthGroupStatType::STREAM_CREATE_SUCCESS: os << "STREAM_CREATE_SUCCESS"; break; - case bluetooth::le_audio::LeAudioHealthGroupStatType:: - STREAM_CREATE_CIS_FAILED: + case bluetooth::le_audio::LeAudioHealthGroupStatType::STREAM_CREATE_CIS_FAILED: os << "STREAM_CREATE_CIS_FAILED"; break; - case bluetooth::le_audio::LeAudioHealthGroupStatType:: - STREAM_CREATE_SIGNALING_FAILED: + case bluetooth::le_audio::LeAudioHealthGroupStatType::STREAM_CREATE_SIGNALING_FAILED: os << "STREAM_CREATE_SIGNALING_FAILED"; break; - case bluetooth::le_audio::LeAudioHealthGroupStatType:: - STREAM_CONTEXT_NOT_AVAILABLE: + case bluetooth::le_audio::LeAudioHealthGroupStatType::STREAM_CONTEXT_NOT_AVAILABLE: os << "STREAM_CONTEXT_NOT_AVAILABLE"; break; default: @@ -140,9 +136,8 @@ inline std::ostream& operator<<( return os; } -inline std::ostream& operator<<( - std::ostream& os, - const bluetooth::le_audio::LeAudioHealthDeviceStatType& stat) { +inline std::ostream& operator<<(std::ostream& os, + const bluetooth::le_audio::LeAudioHealthDeviceStatType& stat) { switch (stat) { case bluetooth::le_audio::LeAudioHealthDeviceStatType::INVALID_DB: os << "INVALID_DB"; diff --git a/system/bta/le_audio/le_audio_health_status_test.cc b/system/bta/le_audio/le_audio_health_status_test.cc index 0819f6c0882..12a306e0c6b 100644 --- a/system/bta/le_audio/le_audio_health_status_test.cc +++ b/system/bta/le_audio/le_audio_health_status_test.cc @@ -37,8 +37,7 @@ using bluetooth::le_audio::LeAudioHealthDeviceStatType; using bluetooth::le_audio::LeAudioHealthGroupStatType; using bluetooth::le_audio::LeAudioHealthStatus; -LeAudioHealthBasedAction recommendation_in_callback = - LeAudioHealthBasedAction::NONE; +LeAudioHealthBasedAction recommendation_in_callback = LeAudioHealthBasedAction::NONE; RawAddress address_in_callback = RawAddress::kEmpty; int group_id_in_callback = kGroupUnknown; @@ -50,13 +49,12 @@ static void healthCallback(const RawAddress& address, int group_id, } class LeAudioHealthStatusTest : public ::testing::Test { - protected: +protected: void SetUp() override { reset_mock_function_count_map(); group_ = new LeAudioDeviceGroup(group_id_); le_audio_health_status_instance_ = LeAudioHealthStatus::Get(); - le_audio_health_status_instance_->RegisterCallback( - base::BindRepeating(healthCallback)); + le_audio_health_status_instance_->RegisterCallback(base::BindRepeating(healthCallback)); } void TearDown() override { @@ -83,40 +81,37 @@ TEST_F(LeAudioHealthStatusTest, test_initialize) { TEST_F(LeAudioHealthStatusTest, test_invalid_db) { const RawAddress test_address0 = GetTestAddress(0); - auto device = std::make_shared( - test_address0, DeviceConnectState::DISCONNECTED); - le_audio_health_status_instance_->AddStatisticForDevice( - device.get(), LeAudioHealthDeviceStatType::INVALID_DB); + auto device = std::make_shared(test_address0, DeviceConnectState::DISCONNECTED); + le_audio_health_status_instance_->AddStatisticForDevice(device.get(), + LeAudioHealthDeviceStatType::INVALID_DB); ASSERT_TRUE(address_in_callback == test_address0); ASSERT_TRUE(recommendation_in_callback == LeAudioHealthBasedAction::DISABLE); } TEST_F(LeAudioHealthStatusTest, test_invalid_csis_member) { const RawAddress test_address0 = GetTestAddress(0); - auto device = std::make_shared( - test_address0, DeviceConnectState::DISCONNECTED); + auto device = std::make_shared(test_address0, DeviceConnectState::DISCONNECTED); le_audio_health_status_instance_->AddStatisticForDevice( - device.get(), LeAudioHealthDeviceStatType::INVALID_CSIS); + device.get(), LeAudioHealthDeviceStatType::INVALID_CSIS); ASSERT_TRUE(address_in_callback == test_address0); ASSERT_TRUE(recommendation_in_callback == LeAudioHealthBasedAction::DISABLE); } TEST_F(LeAudioHealthStatusTest, test_remove_statistic) { const RawAddress test_address0 = GetTestAddress(0); - auto device = std::make_shared( - test_address0, DeviceConnectState::DISCONNECTED); + auto device = std::make_shared(test_address0, DeviceConnectState::DISCONNECTED); group_->AddNode(device); le_audio_health_status_instance_->AddStatisticForDevice( - device.get(), LeAudioHealthDeviceStatType::INVALID_CSIS); + device.get(), LeAudioHealthDeviceStatType::INVALID_CSIS); le_audio_health_status_instance_->AddStatisticForGroup( - group_, LeAudioHealthGroupStatType::STREAM_CREATE_SUCCESS); + group_, LeAudioHealthGroupStatType::STREAM_CREATE_SUCCESS); le_audio_health_status_instance_->RemoveStatistics(test_address0, group_id_); } TEST_F(LeAudioHealthStatusTest, test_all_is_good) { for (int i = 0; i < 100; i++) { le_audio_health_status_instance_->AddStatisticForGroup( - group_, LeAudioHealthGroupStatType::STREAM_CREATE_SUCCESS); + group_, LeAudioHealthGroupStatType::STREAM_CREATE_SUCCESS); } ASSERT_TRUE(address_in_callback == RawAddress::kEmpty); @@ -125,12 +120,11 @@ TEST_F(LeAudioHealthStatusTest, test_all_is_good) { TEST_F(LeAudioHealthStatusTest, test_disable_cis_no_stream_creation) { const RawAddress test_address0 = GetTestAddress(0); - auto device = std::make_shared(test_address0, - DeviceConnectState::CONNECTED); + auto device = std::make_shared(test_address0, DeviceConnectState::CONNECTED); group_->AddNode(device); for (int i = 0; i < 3; i++) { le_audio_health_status_instance_->AddStatisticForGroup( - group_, LeAudioHealthGroupStatType::STREAM_CREATE_CIS_FAILED); + group_, LeAudioHealthGroupStatType::STREAM_CREATE_CIS_FAILED); } ASSERT_TRUE(address_in_callback == RawAddress::kEmpty); ASSERT_TRUE(group_id_in_callback == group_id_); @@ -139,12 +133,11 @@ TEST_F(LeAudioHealthStatusTest, test_disable_cis_no_stream_creation) { TEST_F(LeAudioHealthStatusTest, test_disable_signaling_no_stream_creation) { const RawAddress test_address0 = GetTestAddress(0); - auto device = std::make_shared(test_address0, - DeviceConnectState::CONNECTED); + auto device = std::make_shared(test_address0, DeviceConnectState::CONNECTED); group_->AddNode(device); for (int i = 0; i < 3; i++) { le_audio_health_status_instance_->AddStatisticForGroup( - group_, LeAudioHealthGroupStatType::STREAM_CREATE_SIGNALING_FAILED); + group_, LeAudioHealthGroupStatType::STREAM_CREATE_SIGNALING_FAILED); } /* No recommendation shall be sent */ ASSERT_TRUE(address_in_callback == RawAddress::kEmpty); @@ -154,15 +147,14 @@ TEST_F(LeAudioHealthStatusTest, test_disable_signaling_no_stream_creation) { TEST_F(LeAudioHealthStatusTest, test_disable_signaling_cis_no_stream_creation) { const RawAddress test_address0 = GetTestAddress(0); - auto device = std::make_shared(test_address0, - DeviceConnectState::CONNECTED); + auto device = std::make_shared(test_address0, DeviceConnectState::CONNECTED); group_->AddNode(device); for (int i = 0; i < 2; i++) { le_audio_health_status_instance_->AddStatisticForGroup( - group_, LeAudioHealthGroupStatType::STREAM_CREATE_SIGNALING_FAILED); + group_, LeAudioHealthGroupStatType::STREAM_CREATE_SIGNALING_FAILED); } le_audio_health_status_instance_->AddStatisticForGroup( - group_, LeAudioHealthGroupStatType::STREAM_CREATE_CIS_FAILED); + group_, LeAudioHealthGroupStatType::STREAM_CREATE_CIS_FAILED); /* No recommendation shall be sent */ ASSERT_TRUE(address_in_callback == RawAddress::kEmpty); @@ -172,63 +164,59 @@ TEST_F(LeAudioHealthStatusTest, test_disable_signaling_cis_no_stream_creation) { TEST_F(LeAudioHealthStatusTest, test_consider_disabling) { const RawAddress test_address0 = GetTestAddress(0); - auto device = std::make_shared(test_address0, - DeviceConnectState::CONNECTED); + auto device = std::make_shared(test_address0, DeviceConnectState::CONNECTED); group_->AddNode(device); for (int i = 0; i < 10; i++) { le_audio_health_status_instance_->AddStatisticForGroup( - group_, LeAudioHealthGroupStatType::STREAM_CREATE_SUCCESS); + group_, LeAudioHealthGroupStatType::STREAM_CREATE_SUCCESS); } for (int i = 0; i < 2; i++) { le_audio_health_status_instance_->AddStatisticForGroup( - group_, LeAudioHealthGroupStatType::STREAM_CREATE_CIS_FAILED); + group_, LeAudioHealthGroupStatType::STREAM_CREATE_CIS_FAILED); } ASSERT_TRUE(address_in_callback == RawAddress::kEmpty); for (int i = 0; i < 2; i++) { le_audio_health_status_instance_->AddStatisticForGroup( - group_, LeAudioHealthGroupStatType::STREAM_CREATE_SIGNALING_FAILED); + group_, LeAudioHealthGroupStatType::STREAM_CREATE_SIGNALING_FAILED); } ASSERT_TRUE(address_in_callback == RawAddress::kEmpty); for (int i = 0; i < 3; i++) { le_audio_health_status_instance_->AddStatisticForGroup( - group_, LeAudioHealthGroupStatType::STREAM_CREATE_CIS_FAILED); + group_, LeAudioHealthGroupStatType::STREAM_CREATE_CIS_FAILED); } ASSERT_TRUE(address_in_callback == RawAddress::kEmpty); ASSERT_TRUE(group_id_in_callback == group_id_); - ASSERT_TRUE(recommendation_in_callback == - LeAudioHealthBasedAction::CONSIDER_DISABLING); + ASSERT_TRUE(recommendation_in_callback == LeAudioHealthBasedAction::CONSIDER_DISABLING); } TEST_F(LeAudioHealthStatusTest, test_inactivate_group) { const RawAddress test_address0 = GetTestAddress(0); - auto device = std::make_shared(test_address0, - DeviceConnectState::CONNECTED); + auto device = std::make_shared(test_address0, DeviceConnectState::CONNECTED); group_->AddNode(device); for (int i = 0; i < 10; i++) { le_audio_health_status_instance_->AddStatisticForGroup( - group_, LeAudioHealthGroupStatType::STREAM_CREATE_SUCCESS); + group_, LeAudioHealthGroupStatType::STREAM_CREATE_SUCCESS); } for (int i = 0; i < 2; i++) { le_audio_health_status_instance_->AddStatisticForGroup( - group_, LeAudioHealthGroupStatType::STREAM_CONTEXT_NOT_AVAILABLE); + group_, LeAudioHealthGroupStatType::STREAM_CONTEXT_NOT_AVAILABLE); } ASSERT_TRUE(address_in_callback == RawAddress::kEmpty); for (int i = 0; i < 1; i++) { le_audio_health_status_instance_->AddStatisticForGroup( - group_, LeAudioHealthGroupStatType::STREAM_CONTEXT_NOT_AVAILABLE); + group_, LeAudioHealthGroupStatType::STREAM_CONTEXT_NOT_AVAILABLE); } ASSERT_TRUE(address_in_callback == RawAddress::kEmpty); ASSERT_TRUE(group_id_in_callback == group_id_); - ASSERT_TRUE(recommendation_in_callback == - LeAudioHealthBasedAction::INACTIVATE_GROUP); + ASSERT_TRUE(recommendation_in_callback == LeAudioHealthBasedAction::INACTIVATE_GROUP); } diff --git a/system/bta/le_audio/le_audio_log_history.cc b/system/bta/le_audio/le_audio_log_history.cc index 707cedeb9b8..0022d7b7daf 100644 --- a/system/bta/le_audio/le_audio_log_history.cc +++ b/system/bta/le_audio/le_audio_log_history.cc @@ -36,21 +36,19 @@ constexpr size_t kLeAudioLogHistoryBufferSize = 200; class TimestampedStringCircularBuffer : public bluetooth::common::TimestampedCircularBuffer { - public: +public: explicit TimestampedStringCircularBuffer(size_t size) : bluetooth::common::TimestampedCircularBuffer(size) {} void Push(const std::string& s) { - bluetooth::common::TimestampedCircularBuffer::Push( - s.substr(0, kMaxLogSize)); + bluetooth::common::TimestampedCircularBuffer::Push(s.substr(0, kMaxLogSize)); } template void Push(Args... args) { char buf[kMaxLogSize]; std::snprintf(buf, sizeof(buf), args...); - bluetooth::common::TimestampedCircularBuffer::Push( - std::string(buf)); + bluetooth::common::TimestampedCircularBuffer::Push(std::string(buf)); } }; @@ -64,12 +62,11 @@ const std::string kTimeFormat("%Y-%m-%d %H:%M:%S"); using Record = bluetooth::common::TimestampedEntry; class LeAudioLogHistoryImpl : public LeAudioLogHistory { - public: +public: ~LeAudioLogHistoryImpl(void) { history_.reset(); } LeAudioLogHistoryImpl(void) { - history_ = std::make_shared( - kLeAudioLogHistoryBufferSize); + history_ = std::make_shared(kLeAudioLogHistoryBufferSize); log::assert_that(history_ != nullptr, "assert failed: history_ != nullptr"); history_->Push(std::string("Initialized le_audio history")); } @@ -87,38 +84,33 @@ class LeAudioLogHistoryImpl : public LeAudioLogHistory { struct tm tm; localtime_r(&then, &tm); auto s2 = bluetooth::common::StringFormatTime(kTimeFormat, tm); - LOG_DUMPSYS(fd, " %s.%03u %s", s2.c_str(), - static_cast(record.timestamp % 1000), + LOG_DUMPSYS(fd, " %s.%03u %s", s2.c_str(), static_cast(record.timestamp % 1000), record.entry.c_str()); } #undef DUMPSYS_TAG } - void AddLogHistory(const std::string& tag, int group_id, - const RawAddress& addr, const std::string& msg, - const std::string& extra) { + void AddLogHistory(const std::string& tag, int group_id, const RawAddress& addr, + const std::string& msg, const std::string& extra) { add_logs_history_common(tag, group_id, addr, msg, extra); } - void AddLogHistory(const std::string& tag, int group_id, - const RawAddress& addr, const std::string& msg) { + void AddLogHistory(const std::string& tag, int group_id, const RawAddress& addr, + const std::string& msg) { AddLogHistory(tag, group_id, addr, msg, std::string()); } - private: - void add_logs_history_common(const std::string& tag, int group_id, - const RawAddress& addr, const std::string& msg, - const std::string& extra) { +private: + void add_logs_history_common(const std::string& tag, int group_id, const RawAddress& addr, + const std::string& msg, const std::string& extra) { if (history_ == nullptr) { - log::error( - "LeAudioLogHistory has not been constructed or already destroyed !"); + log::error("LeAudioLogHistory has not been constructed or already destroyed !"); return; } history_->Push("%-*s GID %-3d %-*s: %-22s %s", kMaxLogHistoryTagLength, tag.substr(0, kMaxLogHistoryTagLength).c_str(), group_id, - kMaxLogHistoryMsgLength, - msg.substr(0, kMaxLogHistoryMsgLength).c_str(), + kMaxLogHistoryMsgLength, msg.substr(0, kMaxLogHistoryMsgLength).c_str(), ADDRESS_TO_LOGGABLE_CSTR(addr), extra.c_str()); } diff --git a/system/bta/le_audio/le_audio_log_history.h b/system/bta/le_audio/le_audio_log_history.h index 42b8a3dd22c..5fa17350e20 100644 --- a/system/bta/le_audio/le_audio_log_history.h +++ b/system/bta/le_audio/le_audio_log_history.h @@ -65,16 +65,14 @@ static std::string kLogAfReconfigComplete("RECONFIG_COMPLETE_EVT: "); static std::string kLogAfSuspendForReconfig("SUSPEND_FOR_RECONFIG_EVT: "); class LeAudioLogHistory { - public: +public: virtual ~LeAudioLogHistory(void) = default; static LeAudioLogHistory* Get(void); static void Cleanup(void); static void DebugDump(int fd); - virtual void AddLogHistory(const std::string& tag, int group_id, - const RawAddress& addr, + virtual void AddLogHistory(const std::string& tag, int group_id, const RawAddress& addr, const std::string& msg) = 0; - virtual void AddLogHistory(const std::string& tag, int group_id, - const RawAddress& addr, const std::string& msg, - const std::string& extra) = 0; + virtual void AddLogHistory(const std::string& tag, int group_id, const RawAddress& addr, + const std::string& msg, const std::string& extra) = 0; }; \ No newline at end of file diff --git a/system/bta/le_audio/le_audio_set_configuration_provider.h b/system/bta/le_audio/le_audio_set_configuration_provider.h index 9d030603cb4..50e31bfce4c 100644 --- a/system/bta/le_audio/le_audio_set_configuration_provider.h +++ b/system/bta/le_audio/le_audio_set_configuration_provider.h @@ -23,7 +23,7 @@ namespace bluetooth::le_audio { /* Audio set configurations provider interface. */ class AudioSetConfigurationProvider { - public: +public: AudioSetConfigurationProvider(); virtual ~AudioSetConfigurationProvider() = default; static AudioSetConfigurationProvider* Get(); @@ -31,13 +31,13 @@ class AudioSetConfigurationProvider { static void DebugDump(int fd); static void Cleanup(); virtual const set_configurations::AudioSetConfigurations* GetConfigurations( - ::bluetooth::le_audio::types::LeAudioContextType content_type) const; + ::bluetooth::le_audio::types::LeAudioContextType content_type) const; virtual bool CheckConfigurationIsBiDirSwb( - const set_configurations::AudioSetConfiguration& set_configuration) const; + const set_configurations::AudioSetConfiguration& set_configuration) const; virtual bool CheckConfigurationIsDualBiDirSwb( - const set_configurations::AudioSetConfiguration& set_configuration) const; + const set_configurations::AudioSetConfiguration& set_configuration) const; - private: +private: struct impl; std::unique_ptr pimpl_; }; diff --git a/system/bta/le_audio/le_audio_set_configuration_provider_json.cc b/system/bta/le_audio/le_audio_set_configuration_provider_json.cc index 2a9b2635db9..d99e681a486 100644 --- a/system/bta/le_audio/le_audio_set_configuration_provider_json.cc +++ b/system/bta/le_audio/le_audio_set_configuration_provider_json.cc @@ -44,39 +44,28 @@ using bluetooth::le_audio::types::LeAudioContextType; namespace bluetooth::le_audio { #ifdef __ANDROID__ -static const std::vector< - std::pair> - kLeAudioSetConfigs = { - {"/apex/com.android.btservices/etc/bluetooth/le_audio/" - "audio_set_configurations.bfbs", - "/apex/com.android.btservices/etc/bluetooth/le_audio/" - "audio_set_configurations.json"}}; -static const std::vector< - std::pair> - kLeAudioSetScenarios = {{"/apex/com.android.btservices/etc/bluetooth/" - "le_audio/audio_set_scenarios.bfbs", - "/apex/com.android.btservices/etc/bluetooth/" - "le_audio/audio_set_scenarios.json"}}; +static const std::vector> + kLeAudioSetConfigs = {{"/apex/com.android.btservices/etc/bluetooth/le_audio/" + "audio_set_configurations.bfbs", + "/apex/com.android.btservices/etc/bluetooth/le_audio/" + "audio_set_configurations.json"}}; +static const std::vector> + kLeAudioSetScenarios = {{"/apex/com.android.btservices/etc/bluetooth/" + "le_audio/audio_set_scenarios.bfbs", + "/apex/com.android.btservices/etc/bluetooth/" + "le_audio/audio_set_scenarios.json"}}; #elif defined(TARGET_FLOSS) -static const std::vector< - std::pair> - kLeAudioSetConfigs = { - {"/etc/bluetooth/le_audio/audio_set_configurations.bfbs", - "/etc/bluetooth/le_audio/audio_set_configurations.json"}}; -static const std::vector< - std::pair> - kLeAudioSetScenarios = { - {"/etc/bluetooth/le_audio/audio_set_scenarios.bfbs", - "/etc/bluetooth/le_audio/audio_set_scenarios.json"}}; +static const std::vector> + kLeAudioSetConfigs = {{"/etc/bluetooth/le_audio/audio_set_configurations.bfbs", + "/etc/bluetooth/le_audio/audio_set_configurations.json"}}; +static const std::vector> + kLeAudioSetScenarios = {{"/etc/bluetooth/le_audio/audio_set_scenarios.bfbs", + "/etc/bluetooth/le_audio/audio_set_scenarios.json"}}; #else -static const std::vector< - std::pair> - kLeAudioSetConfigs = { - {"audio_set_configurations.bfbs", "audio_set_configurations.json"}}; -static const std::vector< - std::pair> - kLeAudioSetScenarios = { - {"audio_set_scenarios.bfbs", "audio_set_scenarios.json"}}; +static const std::vector> + kLeAudioSetConfigs = {{"audio_set_configurations.bfbs", "audio_set_configurations.json"}}; +static const std::vector> + kLeAudioSetScenarios = {{"audio_set_scenarios.bfbs", "audio_set_scenarios.json"}}; #endif /** Provides a set configurations for the given context type */ @@ -84,9 +73,8 @@ struct AudioSetConfigurationProviderJson { static constexpr auto kDefaultScenario = "Media"; AudioSetConfigurationProviderJson(types::CodecLocation location) { - log::assert_that( - LoadContent(kLeAudioSetConfigs, kLeAudioSetScenarios, location), - ": Unable to load le audio set configuration files."); + log::assert_that(LoadContent(kLeAudioSetConfigs, kLeAudioSetScenarios, location), + ": Unable to load le audio set configuration files."); } /* Use the same scenario configurations for different contexts to avoid @@ -95,26 +83,25 @@ struct AudioSetConfigurationProviderJson { * the same while changing to same scenario based context type. */ static auto ScenarioToContextTypes(const std::string& scenario) { - static const std::multimap - scenarios = { - {"Media", types::LeAudioContextType::ALERTS}, - {"Media", types::LeAudioContextType::INSTRUCTIONAL}, - {"Media", types::LeAudioContextType::NOTIFICATIONS}, - {"Media", types::LeAudioContextType::EMERGENCYALARM}, - {"Media", types::LeAudioContextType::UNSPECIFIED}, - {"Media", types::LeAudioContextType::MEDIA}, - {"Conversational", types::LeAudioContextType::RINGTONE}, - {"Conversational", types::LeAudioContextType::CONVERSATIONAL}, - {"Live", types::LeAudioContextType::LIVE}, - {"Game", types::LeAudioContextType::GAME}, - {"VoiceAssistants", types::LeAudioContextType::VOICEASSISTANTS}, - }; + static const std::multimap + scenarios = { + {"Media", types::LeAudioContextType::ALERTS}, + {"Media", types::LeAudioContextType::INSTRUCTIONAL}, + {"Media", types::LeAudioContextType::NOTIFICATIONS}, + {"Media", types::LeAudioContextType::EMERGENCYALARM}, + {"Media", types::LeAudioContextType::UNSPECIFIED}, + {"Media", types::LeAudioContextType::MEDIA}, + {"Conversational", types::LeAudioContextType::RINGTONE}, + {"Conversational", types::LeAudioContextType::CONVERSATIONAL}, + {"Live", types::LeAudioContextType::LIVE}, + {"Game", types::LeAudioContextType::GAME}, + {"VoiceAssistants", types::LeAudioContextType::VOICEASSISTANTS}, + }; return scenarios.equal_range(scenario); } static std::string ContextTypeToScenario( - ::bluetooth::le_audio::types::LeAudioContextType context_type) { + ::bluetooth::le_audio::types::LeAudioContextType context_type) { switch (context_type) { case types::LeAudioContextType::ALERTS: FALLTHROUGH_INTENDED; @@ -146,12 +133,12 @@ struct AudioSetConfigurationProviderJson { } const AudioSetConfigurations* GetConfigurationsByContextType( - LeAudioContextType context_type) const { - if (context_configurations_.count(context_type)) + LeAudioContextType context_type) const { + if (context_configurations_.count(context_type)) { return &context_configurations_.at(context_type); + } - log::warn(": No predefined scenario for the context {} was found.", - (int)context_type); + log::warn(": No predefined scenario for the context {} was found.", (int)context_type); auto [it_begin, it_end] = ScenarioToContextTypes(kDefaultScenario); if (it_begin != it_end) { @@ -160,55 +147,50 @@ struct AudioSetConfigurationProviderJson { } log::error( - ": No valid configuration for the default '{}' scenario, or no audio " - "set configurations loaded at all.", - kDefaultScenario); + ": No valid configuration for the default '{}' scenario, or no audio " + "set configurations loaded at all.", + kDefaultScenario); return nullptr; - }; + } - private: +private: /* Codec configurations */ std::map configurations_; /* Maps of context types to a set of configuration structs */ - std::map<::bluetooth::le_audio::types::LeAudioContextType, - AudioSetConfigurations> - context_configurations_; + std::map<::bluetooth::le_audio::types::LeAudioContextType, AudioSetConfigurations> + context_configurations_; static CodecConfigSetting CodecConfigSettingFromFlat( - const fbs::le_audio::CodecId* flat_codec_id, - const flatbuffers::Vector< - flatbuffers::Offset>* - flat_codec_specific_params) { + const fbs::le_audio::CodecId* flat_codec_id, + const flatbuffers::Vector>* + flat_codec_specific_params) { CodecConfigSetting codec; /* Cache the bluetooth::le_audio::types::CodecId type value */ codec.id = types::LeAudioCodecId({ - .coding_format = flat_codec_id->coding_format(), - .vendor_company_id = flat_codec_id->vendor_company_id(), - .vendor_codec_id = flat_codec_id->vendor_codec_id(), + .coding_format = flat_codec_id->coding_format(), + .vendor_company_id = flat_codec_id->vendor_company_id(), + .vendor_codec_id = flat_codec_id->vendor_codec_id(), }); /* Cache all the codec specific parameters */ for (auto const& param : *flat_codec_specific_params) { auto const value = param->compound_value()->value(); - codec.params.Add( - param->type(), - std::vector(value->data(), value->data() + value->size())); + codec.params.Add(param->type(), + std::vector(value->data(), value->data() + value->size())); } return codec; } void SetConfigurationFromFlatSubconfig( - const fbs::le_audio::AudioSetSubConfiguration* flat_subconfig, - QosConfigSetting qos, std::vector& subconfigs, - types::CodecLocation location) { - auto codec_config = CodecConfigSettingFromFlat( - flat_subconfig->codec_id(), flat_subconfig->codec_configuration()); + const fbs::le_audio::AudioSetSubConfiguration* flat_subconfig, QosConfigSetting qos, + std::vector& subconfigs, types::CodecLocation location) { + auto codec_config = CodecConfigSettingFromFlat(flat_subconfig->codec_id(), + flat_subconfig->codec_configuration()); // Fill in the remaining params - codec_config.channel_count_per_iso_stream = - flat_subconfig->ase_channel_cnt(); + codec_config.channel_count_per_iso_stream = flat_subconfig->ase_channel_cnt(); auto config = AseConfiguration(codec_config, qos); @@ -217,37 +199,35 @@ struct AudioSetConfigurationProviderJson { switch (location) { case types::CodecLocation::ADSP: config.data_path_configuration.dataPathId = - bluetooth::hci::iso_manager::kIsoDataPathPlatformDefault; + bluetooth::hci::iso_manager::kIsoDataPathPlatformDefault; config.data_path_configuration.dataPathConfig = {}; config.data_path_configuration.isoDataPathConfig.isTransparent = true; config.data_path_configuration.isoDataPathConfig.controllerDelayUs = 0; config.data_path_configuration.isoDataPathConfig.codecId = { - .coding_format = bluetooth::hci::kIsoCodingFormatTransparent, - .vendor_company_id = 0, - .vendor_codec_id = 0}; + .coding_format = bluetooth::hci::kIsoCodingFormatTransparent, + .vendor_company_id = 0, + .vendor_codec_id = 0}; config.data_path_configuration.isoDataPathConfig.configuration = {}; break; case types::CodecLocation::HOST: - config.data_path_configuration.dataPathId = - bluetooth::hci::iso_manager::kIsoDataPathHci; + config.data_path_configuration.dataPathId = bluetooth::hci::iso_manager::kIsoDataPathHci; config.data_path_configuration.dataPathConfig = {}; config.data_path_configuration.isoDataPathConfig.isTransparent = true; config.data_path_configuration.isoDataPathConfig.codecId = { - .coding_format = bluetooth::hci::kIsoCodingFormatTransparent, - .vendor_company_id = 0, - .vendor_codec_id = 0}; + .coding_format = bluetooth::hci::kIsoCodingFormatTransparent, + .vendor_company_id = 0, + .vendor_codec_id = 0}; config.data_path_configuration.isoDataPathConfig.controllerDelayUs = 0; config.data_path_configuration.isoDataPathConfig.configuration = {}; break; case types::CodecLocation::CONTROLLER: config.data_path_configuration.dataPathId = - bluetooth::hci::iso_manager::kIsoDataPathPlatformDefault; + bluetooth::hci::iso_manager::kIsoDataPathPlatformDefault; config.data_path_configuration.dataPathConfig = {}; config.data_path_configuration.isoDataPathConfig.isTransparent = false; // Note: The data path codecId matches the used codec, but for now there // is no support for the custom path configuration data buffer. - config.data_path_configuration.isoDataPathConfig.codecId = - codec_config.id; + config.data_path_configuration.isoDataPathConfig.codecId = codec_config.id; config.data_path_configuration.isoDataPathConfig.controllerDelayUs = 0; config.data_path_configuration.isoDataPathConfig.configuration = {}; break; @@ -262,20 +242,18 @@ struct AudioSetConfigurationProviderJson { static uint8_t ValidateTargetLatency(int flat_target_latency) { auto target_latency_int = static_cast(flat_target_latency); - bool valid_target_latency = - (target_latency_int >= (int)types::kTargetLatencyLower && - target_latency_int <= (int)types::kTargetLatencyHigherReliability); + bool valid_target_latency = (target_latency_int >= (int)types::kTargetLatencyLower && + target_latency_int <= (int)types::kTargetLatencyHigherReliability); - return valid_target_latency - ? static_cast(target_latency_int) - : types::kTargetLatencyBalancedLatencyReliability; + return valid_target_latency ? static_cast(target_latency_int) + : types::kTargetLatencyBalancedLatencyReliability; } AudioSetConfiguration AudioSetConfigurationFromFlat( - const fbs::le_audio::AudioSetConfiguration* flat_cfg, - std::vector* codec_cfgs, - std::vector* qos_cfgs, - types::CodecLocation location) { + const fbs::le_audio::AudioSetConfiguration* flat_cfg, + std::vector* codec_cfgs, + std::vector* qos_cfgs, + types::CodecLocation location) { log::assert_that(flat_cfg != nullptr, "flat_cfg cannot be null"); std::string codec_config_key = flat_cfg->codec_config_name()->str(); auto* qos_config_key_array = flat_cfg->qos_config_name(); @@ -296,10 +274,8 @@ struct AudioSetConfigurationProviderJson { } } - log::info( - "Audio set config {}: codec config {}, qos_sink {}, qos_source {}", - flat_cfg->name()->c_str(), codec_config_key, qos_sink_key, - qos_source_key); + log::info("Audio set config {}: codec config {}, qos_sink {}, qos_source {}", + flat_cfg->name()->c_str(), codec_config_key, qos_sink_key, qos_source_key); const fbs::le_audio::QosConfiguration* qos_sink_cfg = nullptr; for (auto i = qos_cfgs->begin(); i != qos_cfgs->end(); ++i) { @@ -320,8 +296,7 @@ struct AudioSetConfigurationProviderJson { types::BidirectionalPair qos; if (qos_sink_cfg != nullptr) { - qos.sink.target_latency = - ValidateTargetLatency(qos_sink_cfg->target_latency()); + qos.sink.target_latency = ValidateTargetLatency(qos_sink_cfg->target_latency()); qos.sink.retransmission_number = qos_sink_cfg->retransmission_number(); qos.sink.max_transport_latency = qos_sink_cfg->max_transport_latency(); } else { @@ -329,12 +304,9 @@ struct AudioSetConfigurationProviderJson { } if (qos_source_cfg != nullptr) { - qos.source.target_latency = - ValidateTargetLatency(qos_source_cfg->target_latency()); - qos.source.retransmission_number = - qos_source_cfg->retransmission_number(); - qos.source.max_transport_latency = - qos_source_cfg->max_transport_latency(); + qos.source.target_latency = ValidateTargetLatency(qos_source_cfg->target_latency()); + qos.source.retransmission_number = qos_source_cfg->retransmission_number(); + qos.source.max_transport_latency = qos_source_cfg->max_transport_latency(); } else { log::error("No qos config matching key {} found", qos_source_key); } @@ -352,77 +324,78 @@ struct AudioSetConfigurationProviderJson { /* Load subconfigurations */ for (auto subconfig : *codec_cfg->subconfigurations()) { auto direction = subconfig->direction(); - processSubconfig(*subconfig, qos.get(direction), - subconfigs.get(direction), location); + processSubconfig(*subconfig, qos.get(direction), subconfigs.get(direction), location); } } else { if (codec_cfg == nullptr) { log::error("No codec config matching key {} found", codec_config_key); } else { - log::error("Configuration '{}' has no valid subconfigurations.", - flat_cfg->name()->c_str()); + log::error("Configuration '{}' has no valid subconfigurations.", flat_cfg->name()->c_str()); } } return { - .name = flat_cfg->name()->c_str(), - .packing = bluetooth::hci::kIsoCigPackingSequential, - .confs = std::move(subconfigs), + .name = flat_cfg->name()->c_str(), + .packing = bluetooth::hci::kIsoCigPackingSequential, + .confs = std::move(subconfigs), }; } - void processSubconfig( - const fbs::le_audio::AudioSetSubConfiguration& subconfig, - const QosConfigSetting& qos_setting, - std::vector& subconfigs, - types::CodecLocation location) { - SetConfigurationFromFlatSubconfig(&subconfig, qos_setting, subconfigs, - location); + void processSubconfig(const fbs::le_audio::AudioSetSubConfiguration& subconfig, + const QosConfigSetting& qos_setting, + std::vector& subconfigs, types::CodecLocation location) { + SetConfigurationFromFlatSubconfig(&subconfig, qos_setting, subconfigs, location); // Recalculate some qos params based on the Core Codec Configuration for (auto& subconfig : subconfigs) { const auto& core_config = subconfig.codec.params.GetAsCoreCodecConfig(); - subconfig.qos.maxSdu = - subconfig.codec.GetChannelCountPerIsoStream() * - core_config.octets_per_codec_frame.value_or(0) * - core_config.codec_frames_blocks_per_sdu.value_or(1); + subconfig.qos.maxSdu = subconfig.codec.GetChannelCountPerIsoStream() * + core_config.octets_per_codec_frame.value_or(0) * + core_config.codec_frames_blocks_per_sdu.value_or(1); subconfig.qos.sduIntervalUs = core_config.GetFrameDurationUs(); } } - bool LoadConfigurationsFromFiles(const char* schema_file, - const char* content_file, + bool LoadConfigurationsFromFiles(const char* schema_file, const char* content_file, types::CodecLocation location) { flatbuffers::Parser configurations_parser_; std::string configurations_schema_binary_content; - bool ok = flatbuffers::LoadFile(schema_file, true, - &configurations_schema_binary_content); - if (!ok) return ok; + bool ok = flatbuffers::LoadFile(schema_file, true, &configurations_schema_binary_content); + if (!ok) { + return ok; + } /* Load the binary schema */ - ok = configurations_parser_.Deserialize( - (uint8_t*)configurations_schema_binary_content.c_str(), - configurations_schema_binary_content.length()); - if (!ok) return ok; + ok = configurations_parser_.Deserialize((uint8_t*)configurations_schema_binary_content.c_str(), + configurations_schema_binary_content.length()); + if (!ok) { + return ok; + } /* Load the content from JSON */ std::string configurations_json_content; - ok = flatbuffers::LoadFile(content_file, false, - &configurations_json_content); - if (!ok) return ok; + ok = flatbuffers::LoadFile(content_file, false, &configurations_json_content); + if (!ok) { + return ok; + } /* Parse */ ok = configurations_parser_.Parse(configurations_json_content.c_str()); - if (!ok) return ok; + if (!ok) { + return ok; + } /* Import from flatbuffers */ auto configurations_root = fbs::le_audio::GetAudioSetConfigurations( - configurations_parser_.builder_.GetBufferPointer()); - if (!configurations_root) return false; + configurations_parser_.builder_.GetBufferPointer()); + if (!configurations_root) { + return false; + } auto flat_qos_configs = configurations_root->qos_configurations(); - if ((flat_qos_configs == nullptr) || (flat_qos_configs->size() == 0)) + if ((flat_qos_configs == nullptr) || (flat_qos_configs->size() == 0)) { return false; + } log::debug(": Updating {} qos config entries.", flat_qos_configs->size()); std::vector qos_cfgs; @@ -431,25 +404,26 @@ struct AudioSetConfigurationProviderJson { } auto flat_codec_configs = configurations_root->codec_configurations(); - if ((flat_codec_configs == nullptr) || (flat_codec_configs->size() == 0)) + if ((flat_codec_configs == nullptr) || (flat_codec_configs->size() == 0)) { return false; + } - log::debug(": Updating {} codec config entries.", - flat_codec_configs->size()); + log::debug(": Updating {} codec config entries.", flat_codec_configs->size()); std::vector codec_cfgs; for (auto const& flat_codec_cfg : *flat_codec_configs) { codec_cfgs.push_back(flat_codec_cfg); } auto flat_configs = configurations_root->configurations(); - if ((flat_configs == nullptr) || (flat_configs->size() == 0)) return false; + if ((flat_configs == nullptr) || (flat_configs->size() == 0)) { + return false; + } log::debug(": Updating {} config entries.", flat_configs->size()); for (auto const& flat_cfg : *flat_configs) { - auto configuration = AudioSetConfigurationFromFlat(flat_cfg, &codec_cfgs, - &qos_cfgs, location); - if (!configuration.confs.sink.empty() || - !configuration.confs.source.empty()) { + auto configuration = + AudioSetConfigurationFromFlat(flat_cfg, &codec_cfgs, &qos_cfgs, location); + if (!configuration.confs.sink.empty() || !configuration.confs.source.empty()) { configurations_.insert({flat_cfg->name()->str(), configuration}); } } @@ -458,12 +432,16 @@ struct AudioSetConfigurationProviderJson { } AudioSetConfigurations AudioSetConfigurationsFromFlatScenario( - const fbs::le_audio::AudioSetScenario* const flat_scenario) { + const fbs::le_audio::AudioSetScenario* const flat_scenario) { AudioSetConfigurations items; - if (!flat_scenario->configurations()) return items; + if (!flat_scenario->configurations()) { + return items; + } for (auto config_name : *flat_scenario->configurations()) { - if (configurations_.count(config_name->str()) == 0) continue; + if (configurations_.count(config_name->str()) == 0) { + continue; + } auto& cfg = configurations_.at(config_name->str()); items.push_back(&cfg); @@ -472,37 +450,45 @@ struct AudioSetConfigurationProviderJson { return items; } - bool LoadScenariosFromFiles(const char* schema_file, - const char* content_file) { + bool LoadScenariosFromFiles(const char* schema_file, const char* content_file) { flatbuffers::Parser scenarios_parser_; std::string scenarios_schema_binary_content; - bool ok = flatbuffers::LoadFile(schema_file, true, - &scenarios_schema_binary_content); - if (!ok) return ok; + bool ok = flatbuffers::LoadFile(schema_file, true, &scenarios_schema_binary_content); + if (!ok) { + return ok; + } /* Load the binary schema */ - ok = scenarios_parser_.Deserialize( - (uint8_t*)scenarios_schema_binary_content.c_str(), - scenarios_schema_binary_content.length()); - if (!ok) return ok; + ok = scenarios_parser_.Deserialize((uint8_t*)scenarios_schema_binary_content.c_str(), + scenarios_schema_binary_content.length()); + if (!ok) { + return ok; + } /* Load the content from JSON */ std::string scenarios_json_content; ok = flatbuffers::LoadFile(content_file, false, &scenarios_json_content); - if (!ok) return ok; + if (!ok) { + return ok; + } /* Parse */ ok = scenarios_parser_.Parse(scenarios_json_content.c_str()); - if (!ok) return ok; + if (!ok) { + return ok; + } /* Import from flatbuffers */ - auto scenarios_root = fbs::le_audio::GetAudioSetScenarios( - scenarios_parser_.builder_.GetBufferPointer()); - if (!scenarios_root) return false; + auto scenarios_root = + fbs::le_audio::GetAudioSetScenarios(scenarios_parser_.builder_.GetBufferPointer()); + if (!scenarios_root) { + return false; + } auto flat_scenarios = scenarios_root->scenarios(); - if ((flat_scenarios == nullptr) || (flat_scenarios->size() == 0)) + if ((flat_scenarios == nullptr) || (flat_scenarios->size() == 0)) { return false; + } log::debug(": Updating {} scenarios.", flat_scenarios->size()); for (auto const& scenario : *flat_scenarios) { @@ -512,11 +498,10 @@ struct AudioSetConfigurationProviderJson { log::debug("\t\t Audio set config: {}", config->name); } - auto [it_begin, it_end] = - ScenarioToContextTypes(scenario->name()->c_str()); + auto [it_begin, it_end] = ScenarioToContextTypes(scenario->name()->c_str()); for (auto it = it_begin; it != it_end; ++it) { - context_configurations_.insert_or_assign( - it->second, AudioSetConfigurationsFromFlatScenario(scenario)); + context_configurations_.insert_or_assign(it->second, + AudioSetConfigurationsFromFlatScenario(scenario)); } } @@ -524,35 +509,34 @@ struct AudioSetConfigurationProviderJson { } bool LoadContent( - std::vector> - config_files, - std::vector> - scenario_files, - types::CodecLocation location) { + std::vector> config_files, + std::vector> scenario_files, + types::CodecLocation location) { for (auto [schema, content] : config_files) { - if (!LoadConfigurationsFromFiles(schema, content, location)) return false; + if (!LoadConfigurationsFromFiles(schema, content, location)) { + return false; + } } for (auto [schema, content] : scenario_files) { - if (!LoadScenariosFromFiles(schema, content)) return false; + if (!LoadScenariosFromFiles(schema, content)) { + return false; + } } return true; } }; struct AudioSetConfigurationProvider::impl { - impl(const AudioSetConfigurationProvider& config_provider) - : config_provider_(config_provider) {} + impl(const AudioSetConfigurationProvider& config_provider) : config_provider_(config_provider) {} void Initialize(types::CodecLocation location) { log::assert_that(!config_provider_impl_, "Config provider not available."); - config_provider_impl_ = - std::make_unique(location); + config_provider_impl_ = std::make_unique(location); } void Cleanup() { - log::assert_that(config_provider_impl_ != nullptr, - "Config provider not available."); + log::assert_that(config_provider_impl_ != nullptr, "Config provider not available."); config_provider_impl_.reset(); } @@ -571,17 +555,15 @@ struct AudioSetConfigurationProvider::impl { for (const auto direction : {types::kLeAudioDirectionSink, types::kLeAudioDirectionSource}) { stream << " ASE configs for direction: " - << (direction == types::kLeAudioDirectionSink - ? "Sink (speaker)\n" - : "Source (microphone)\n"); + << (direction == types::kLeAudioDirectionSink ? "Sink (speaker)\n" + : "Source (microphone)\n"); for (const auto& ent : conf->confs.get(direction)) { - stream << " ASE config: " - << " qos->target latency: " << +ent.qos.target_latency + stream << " ASE config: " << " qos->target latency: " + << +ent.qos.target_latency << " \n" + << " qos->retransmission_number: " << +ent.qos.retransmission_number + << " \n" + << " qos->max_transport_latency: " << +ent.qos.max_transport_latency << " \n" - << " qos->retransmission_number: " - << +ent.qos.retransmission_number << " \n" - << " qos->max_transport_latency: " - << +ent.qos.max_transport_latency << " \n" << " channel count per ISO stream: " << +ent.codec.GetChannelCountPerIsoStream() << "\n"; } @@ -604,23 +586,23 @@ AudioSetConfigurationProvider::AudioSetConfigurationProvider() void AudioSetConfigurationProvider::Initialize(types::CodecLocation location) { std::scoped_lock lock(instance_mutex); - if (!config_provider) + if (!config_provider) { config_provider = std::make_unique(); + } - if (!config_provider->pimpl_->IsRunning()) + if (!config_provider->pimpl_->IsRunning()) { config_provider->pimpl_->Initialize(location); + } } void AudioSetConfigurationProvider::DebugDump(int fd) { std::scoped_lock lock(instance_mutex); if (!config_provider || !config_provider->pimpl_->IsRunning()) { - dprintf( - fd, - "\n AudioSetConfigurationProvider not initialized: config provider: " - "%d, pimpl: %d \n", - config_provider != nullptr, - (config_provider == nullptr ? 0 - : config_provider->pimpl_->IsRunning())); + dprintf(fd, + "\n AudioSetConfigurationProvider not initialized: config provider: " + "%d, pimpl: %d \n", + config_provider != nullptr, + (config_provider == nullptr ? 0 : config_provider->pimpl_->IsRunning())); return; } dprintf(fd, "\n AudioSetConfigurationProvider: \n"); @@ -629,8 +611,12 @@ void AudioSetConfigurationProvider::DebugDump(int fd) { void AudioSetConfigurationProvider::Cleanup() { std::scoped_lock lock(instance_mutex); - if (!config_provider) return; - if (config_provider->pimpl_->IsRunning()) config_provider->pimpl_->Cleanup(); + if (!config_provider) { + return; + } + if (config_provider->pimpl_->IsRunning()) { + config_provider->pimpl_->Cleanup(); + } config_provider.reset(); } @@ -638,22 +624,21 @@ AudioSetConfigurationProvider* AudioSetConfigurationProvider::Get() { return config_provider.get(); } -const set_configurations::AudioSetConfigurations* -AudioSetConfigurationProvider::GetConfigurations( - ::bluetooth::le_audio::types::LeAudioContextType content_type) const { - if (pimpl_->IsRunning()) - return pimpl_->config_provider_impl_->GetConfigurationsByContextType( - content_type); +const set_configurations::AudioSetConfigurations* AudioSetConfigurationProvider::GetConfigurations( + ::bluetooth::le_audio::types::LeAudioContextType content_type) const { + if (pimpl_->IsRunning()) { + return pimpl_->config_provider_impl_->GetConfigurationsByContextType(content_type); + } return nullptr; } bool AudioSetConfigurationProvider::CheckConfigurationIsBiDirSwb( - const set_configurations::AudioSetConfiguration& set_configuration) const { + const set_configurations::AudioSetConfiguration& set_configuration) const { uint8_t dir = 0; - for (auto direction : {le_audio::types::kLeAudioDirectionSink, - le_audio::types::kLeAudioDirectionSource}) { + for (auto direction : + {le_audio::types::kLeAudioDirectionSink, le_audio::types::kLeAudioDirectionSource}) { for (const auto& conf : set_configuration.confs.get(direction)) { if (conf.codec.GetSamplingFrequencyHz() >= bluetooth::le_audio::LeAudioCodecConfiguration::kSampleRate32000) { @@ -665,18 +650,17 @@ bool AudioSetConfigurationProvider::CheckConfigurationIsBiDirSwb( } bool AudioSetConfigurationProvider::CheckConfigurationIsDualBiDirSwb( - const set_configurations::AudioSetConfiguration& set_configuration) const { + const set_configurations::AudioSetConfiguration& set_configuration) const { types::BidirectionalPair swb_direction_counter = {0, 0}; - for (auto direction : {le_audio::types::kLeAudioDirectionSink, - le_audio::types::kLeAudioDirectionSource}) { + for (auto direction : + {le_audio::types::kLeAudioDirectionSink, le_audio::types::kLeAudioDirectionSource}) { auto const& confs = set_configuration.confs.get(direction); swb_direction_counter.get(direction) += - std::count_if(confs.begin(), confs.end(), [](auto const& cfg) { - return cfg.codec.GetSamplingFrequencyHz() >= - bluetooth::le_audio::LeAudioCodecConfiguration:: - kSampleRate32000; - }); + std::count_if(confs.begin(), confs.end(), [](auto const& cfg) { + return cfg.codec.GetSamplingFrequencyHz() >= + bluetooth::le_audio::LeAudioCodecConfiguration::kSampleRate32000; + }); } return (swb_direction_counter.sink > 1) && (swb_direction_counter.source > 1); diff --git a/system/bta/le_audio/le_audio_types.cc b/system/bta/le_audio/le_audio_types.cc index 21337cba129..a317b0450a1 100644 --- a/system/bta/le_audio/le_audio_types.cc +++ b/system/bta/le_audio/le_audio_types.cc @@ -44,16 +44,14 @@ using types::kLeAudioDirectionSource; using types::LeAudioCoreCodecConfig; void get_cis_count(LeAudioContextType context_type, int expected_device_cnt, - types::LeAudioConfigurationStrategy strategy, - int avail_group_ase_snk_cnt, int avail_group_ase_src_count, - uint8_t& out_cis_count_bidir, - uint8_t& out_cis_count_unidir_sink, - uint8_t& out_cis_count_unidir_source) { + types::LeAudioConfigurationStrategy strategy, int avail_group_ase_snk_cnt, + int avail_group_ase_src_count, uint8_t& out_cis_count_bidir, + uint8_t& out_cis_count_unidir_sink, uint8_t& out_cis_count_unidir_source) { log::info( - "{} strategy {}, group avail sink ases: {}, group avail source ases {} " - "expected_device_count {}", - bluetooth::common::ToString(context_type), static_cast(strategy), - avail_group_ase_snk_cnt, avail_group_ase_src_count, expected_device_cnt); + "{} strategy {}, group avail sink ases: {}, group avail source ases {} " + "expected_device_count {}", + bluetooth::common::ToString(context_type), static_cast(strategy), + avail_group_ase_snk_cnt, avail_group_ase_src_count, expected_device_cnt); bool is_bidirectional = types::kLeAudioContextAllBidir.test(context_type); @@ -109,38 +107,36 @@ void get_cis_count(LeAudioContextType context_type, int expected_device_cnt, } log::info( - "Required cis count: Bi-Directional: {}, Uni-Directional Sink: {}, " - "Uni-Directional Source: {}", - out_cis_count_bidir, out_cis_count_unidir_sink, - out_cis_count_unidir_source); + "Required cis count: Bi-Directional: {}, Uni-Directional Sink: {}, " + "Uni-Directional Source: {}", + out_cis_count_bidir, out_cis_count_unidir_sink, out_cis_count_unidir_source); } -uint16_t CodecConfigSetting::GetOctectsPerFrame() const { +uint16_t CodecConfigSetting::GetOctetsPerFrame() const { switch (id.coding_format) { case kLeAudioCodingFormatLC3: - return params.GetAsCoreCodecConfig().GetOctectsPerFrame(); + return params.GetAsCoreCodecConfig().GetOctetsPerFrame(); default: log::warn(", invalid codec id: 0x{:02x}", id.coding_format); return 0; } -}; +} uint32_t CodecConfigSetting::GetSamplingFrequencyHz() const { // We also mandate the sampling frequency parameter for vendor spec. codecs return params.GetAsCoreCodecConfig().GetSamplingFrequencyHz(); -}; +} uint32_t CodecConfigSetting::GetDataIntervalUs() const { switch (id.coding_format) { case kLeAudioCodingFormatLC3: return params.GetAsCoreCodecConfig().GetFrameDurationUs() * - params.GetAsCoreCodecConfig().codec_frames_blocks_per_sdu.value_or( - 1); + params.GetAsCoreCodecConfig().codec_frames_blocks_per_sdu.value_or(1); default: log::warn(", invalid codec id: 0x{:02x}", id.coding_format); return 0; } -}; +} uint8_t CodecConfigSetting::GetBitsPerSample() const { switch (id.coding_format) { @@ -151,7 +147,7 @@ uint8_t CodecConfigSetting::GetBitsPerSample() const { log::warn(", invalid codec id: 0x{:02x}", id.coding_format); return 0; } -}; +} std::ostream& operator<<(std::ostream& os, const QosConfigSetting& config) { os << "QosConfigSetting{"; @@ -173,8 +169,7 @@ std::ostream& operator<<(std::ostream& os, const AseConfiguration& config) { return os; } -std::ostream& operator<<(std::ostream& os, - const AudioSetConfiguration& config) { +std::ostream& operator<<(std::ostream& os, const AudioSetConfiguration& config) { os << "AudioSetConfiguration{"; os << "name: " << config.name; os << ", packing: " << (int)config.packing; @@ -197,12 +192,10 @@ std::ostream& operator<<(std::ostream& os, const CodecConfigSetting& config) { os << ", id: " << config.id; os << ", codecSpecParams: " << config.params.GetAsCoreCodecConfig(); os << ", bitsPerSample: " << (int)config.GetBitsPerSample(); - os << ", channelCountPerIsoStream: " - << (int)config.GetChannelCountPerIsoStream(); + os << ", channelCountPerIsoStream: " << (int)config.GetChannelCountPerIsoStream(); if (!config.vendor_params.empty()) { os << ", vendorParams: " - << base::HexEncode(config.vendor_params.data(), - config.vendor_params.size()); + << base::HexEncode(config.vendor_params.data(), config.vendor_params.size()); } os << "}"; return os; @@ -213,48 +206,35 @@ std::ostream& operator<<(std::ostream& os, const CodecConfigSetting& config) { namespace types { /* Helper map for matching various frequency notations */ const std::map LeAudioCoreCodecConfig::sampling_freq_map = { - {codec_spec_conf::kLeAudioSamplingFreq8000Hz, - LeAudioCodecConfiguration::kSampleRate8000}, - {codec_spec_conf::kLeAudioSamplingFreq16000Hz, - LeAudioCodecConfiguration::kSampleRate16000}, - {codec_spec_conf::kLeAudioSamplingFreq24000Hz, - LeAudioCodecConfiguration::kSampleRate24000}, - {codec_spec_conf::kLeAudioSamplingFreq32000Hz, - LeAudioCodecConfiguration::kSampleRate32000}, - {codec_spec_conf::kLeAudioSamplingFreq44100Hz, - LeAudioCodecConfiguration::kSampleRate44100}, - {codec_spec_conf::kLeAudioSamplingFreq48000Hz, - LeAudioCodecConfiguration::kSampleRate48000}}; + {codec_spec_conf::kLeAudioSamplingFreq8000Hz, LeAudioCodecConfiguration::kSampleRate8000}, + {codec_spec_conf::kLeAudioSamplingFreq16000Hz, LeAudioCodecConfiguration::kSampleRate16000}, + {codec_spec_conf::kLeAudioSamplingFreq24000Hz, LeAudioCodecConfiguration::kSampleRate24000}, + {codec_spec_conf::kLeAudioSamplingFreq32000Hz, LeAudioCodecConfiguration::kSampleRate32000}, + {codec_spec_conf::kLeAudioSamplingFreq44100Hz, LeAudioCodecConfiguration::kSampleRate44100}, + {codec_spec_conf::kLeAudioSamplingFreq48000Hz, + LeAudioCodecConfiguration::kSampleRate48000}}; /* Helper map for matching various frequency notations */ const std::map LeAudioCoreCodecConfig::sample_rate_map = { - {LeAudioCodecConfiguration::kSampleRate8000, - codec_spec_conf::kLeAudioSamplingFreq8000Hz}, - {LeAudioCodecConfiguration::kSampleRate16000, - codec_spec_conf::kLeAudioSamplingFreq16000Hz}, - {LeAudioCodecConfiguration::kSampleRate24000, - codec_spec_conf::kLeAudioSamplingFreq24000Hz}, - {LeAudioCodecConfiguration::kSampleRate32000, - codec_spec_conf::kLeAudioSamplingFreq32000Hz}, - {LeAudioCodecConfiguration::kSampleRate44100, - codec_spec_conf::kLeAudioSamplingFreq44100Hz}, - {LeAudioCodecConfiguration::kSampleRate48000, - codec_spec_conf::kLeAudioSamplingFreq48000Hz}, + {LeAudioCodecConfiguration::kSampleRate8000, codec_spec_conf::kLeAudioSamplingFreq8000Hz}, + {LeAudioCodecConfiguration::kSampleRate16000, codec_spec_conf::kLeAudioSamplingFreq16000Hz}, + {LeAudioCodecConfiguration::kSampleRate24000, codec_spec_conf::kLeAudioSamplingFreq24000Hz}, + {LeAudioCodecConfiguration::kSampleRate32000, codec_spec_conf::kLeAudioSamplingFreq32000Hz}, + {LeAudioCodecConfiguration::kSampleRate44100, codec_spec_conf::kLeAudioSamplingFreq44100Hz}, + {LeAudioCodecConfiguration::kSampleRate48000, codec_spec_conf::kLeAudioSamplingFreq48000Hz}, }; /* Helper map for matching various frame durations notations */ const std::map LeAudioCoreCodecConfig::frame_duration_map = { - {codec_spec_conf::kLeAudioCodecFrameDur7500us, - LeAudioCodecConfiguration::kInterval7500Us}, - {codec_spec_conf::kLeAudioCodecFrameDur10000us, - LeAudioCodecConfiguration::kInterval10000Us}}; + {codec_spec_conf::kLeAudioCodecFrameDur7500us, LeAudioCodecConfiguration::kInterval7500Us}, + {codec_spec_conf::kLeAudioCodecFrameDur10000us, + LeAudioCodecConfiguration::kInterval10000Us}}; /* Helper map for matching various frame durations notations */ const std::map LeAudioCoreCodecConfig::data_interval_map = { - {LeAudioCodecConfiguration::kInterval7500Us, - codec_spec_conf::kLeAudioCodecFrameDur7500us}, - {LeAudioCodecConfiguration::kInterval10000Us, - codec_spec_conf::kLeAudioCodecFrameDur10000us}, + {LeAudioCodecConfiguration::kInterval7500Us, codec_spec_conf::kLeAudioCodecFrameDur7500us}, + {LeAudioCodecConfiguration::kInterval10000Us, + codec_spec_conf::kLeAudioCodecFrameDur10000us}, }; std::string CapabilityTypeToStr(const uint8_t& type) { @@ -274,8 +254,7 @@ std::string CapabilityTypeToStr(const uint8_t& type) { } } -std::string CapabilityValueToStr(const uint8_t& type, - const std::vector& value) { +std::string CapabilityValueToStr(const uint8_t& type, const std::vector& value) { std::string string = ""; switch (type) { @@ -290,40 +269,40 @@ std::string CapabilityValueToStr(const uint8_t& type, string += "8"; } if (u16_val & codec_spec_caps::kLeAudioSamplingFreq11025Hz) { - string += std::string((string.empty() ? "" : "|")) + "11.025"; + string += std::string(string.empty() ? "" : "|") + "11.025"; } if (u16_val & codec_spec_caps::kLeAudioSamplingFreq16000Hz) { - string += std::string((string.empty() ? "" : "|")) + "16"; + string += std::string(string.empty() ? "" : "|") + "16"; } if (u16_val & codec_spec_caps::kLeAudioSamplingFreq22050Hz) { - string += std::string((string.empty() ? "" : "|")) + "22.050"; + string += std::string(string.empty() ? "" : "|") + "22.050"; } if (u16_val & codec_spec_caps::kLeAudioSamplingFreq24000Hz) { - string += std::string((string.empty() ? "" : "|")) + "24"; + string += std::string(string.empty() ? "" : "|") + "24"; } if (u16_val & codec_spec_caps::kLeAudioSamplingFreq32000Hz) { - string += std::string((string.empty() ? "" : "|")) + "32"; + string += std::string(string.empty() ? "" : "|") + "32"; } if (u16_val & codec_spec_caps::kLeAudioSamplingFreq44100Hz) { - string += std::string((string.empty() ? "" : "|")) + "44.1"; + string += std::string(string.empty() ? "" : "|") + "44.1"; } if (u16_val & codec_spec_caps::kLeAudioSamplingFreq48000Hz) { - string += std::string((string.empty() ? "" : "|")) + "48"; + string += std::string(string.empty() ? "" : "|") + "48"; } if (u16_val & codec_spec_caps::kLeAudioSamplingFreq88200Hz) { - string += std::string((string.empty() ? "" : "|")) + "88.2"; + string += std::string(string.empty() ? "" : "|") + "88.2"; } if (u16_val & codec_spec_caps::kLeAudioSamplingFreq96000Hz) { - string += std::string((string.empty() ? "" : "|")) + "96"; + string += std::string(string.empty() ? "" : "|") + "96"; } if (u16_val & codec_spec_caps::kLeAudioSamplingFreq176400Hz) { - string += std::string((string.empty() ? "" : "|")) + "176.4"; + string += std::string(string.empty() ? "" : "|") + "176.4"; } if (u16_val & codec_spec_caps::kLeAudioSamplingFreq192000Hz) { - string += std::string((string.empty() ? "" : "|")) + "192"; + string += std::string(string.empty() ? "" : "|") + "192"; } if (u16_val & codec_spec_caps::kLeAudioSamplingFreq384000Hz) { - string += std::string((string.empty() ? "" : "|")) + "384"; + string += std::string(string.empty() ? "" : "|") + "384"; } return string += " [kHz]\n"; @@ -339,13 +318,13 @@ std::string CapabilityValueToStr(const uint8_t& type, string += "7.5"; } if (u8_val & codec_spec_caps::kLeAudioCodecFrameDur10000us) { - string += std::string((string.empty() ? "" : "|")) + "10"; + string += std::string(string.empty() ? "" : "|") + "10"; } if (u8_val & codec_spec_caps::kLeAudioCodecFrameDurPrefer7500us) { - string += std::string((string.empty() ? "" : "|")) + "7.5 preferred"; + string += std::string(string.empty() ? "" : "|") + "7.5 preferred"; } if (u8_val & codec_spec_caps::kLeAudioCodecFrameDurPrefer10000us) { - string += std::string((string.empty() ? "" : "|")) + "10 preferred"; + string += std::string(string.empty() ? "" : "|") + "10 preferred"; } return string += " [ms]\n"; @@ -361,28 +340,28 @@ std::string CapabilityValueToStr(const uint8_t& type, string += "0"; } if (u8_val & codec_spec_caps::kLeAudioCodecChannelCountSingleChannel) { - string += std::string((string.empty() ? "" : "|")) + "1"; + string += std::string(string.empty() ? "" : "|") + "1"; } if (u8_val & codec_spec_caps::kLeAudioCodecChannelCountTwoChannel) { - string += std::string((string.empty() ? "" : "|")) + "2"; + string += std::string(string.empty() ? "" : "|") + "2"; } if (u8_val & codec_spec_caps::kLeAudioCodecChannelCountThreeChannel) { - string += std::string((string.empty() ? "" : "|")) + "3"; + string += std::string(string.empty() ? "" : "|") + "3"; } if (u8_val & codec_spec_caps::kLeAudioCodecChannelCountFourChannel) { - string += std::string((string.empty() ? "" : "|")) + "4"; + string += std::string(string.empty() ? "" : "|") + "4"; } if (u8_val & codec_spec_caps::kLeAudioCodecChannelCountFiveChannel) { - string += std::string((string.empty() ? "" : "|")) + "5"; + string += std::string(string.empty() ? "" : "|") + "5"; } if (u8_val & codec_spec_caps::kLeAudioCodecChannelCountSixChannel) { - string += std::string((string.empty() ? "" : "|")) + "6"; + string += std::string(string.empty() ? "" : "|") + "6"; } if (u8_val & codec_spec_caps::kLeAudioCodecChannelCountSevenChannel) { - string += std::string((string.empty() ? "" : "|")) + "7"; + string += std::string(string.empty() ? "" : "|") + "7"; } if (u8_val & codec_spec_caps::kLeAudioCodecChannelCountEightChannel) { - string += std::string((string.empty() ? "" : "|")) + "8"; + string += std::string(string.empty() ? "" : "|") + "8"; } return string += " channel/s\n"; @@ -394,7 +373,7 @@ std::string CapabilityValueToStr(const uint8_t& type, uint16_t u16_min_number_of_octets = VEC_UINT8_TO_UINT16(value); uint16_t u16_max_number_of_octets = - OFF_VEC_UINT8_TO_UINT16(value, sizeof(u16_min_number_of_octets)); + OFF_VEC_UINT8_TO_UINT16(value, sizeof(u16_min_number_of_octets)); string += "Minimum: " + std::to_string(u16_min_number_of_octets); string += ", Maximum: " + std::to_string(u16_max_number_of_octets) + "\n"; @@ -417,8 +396,7 @@ std::string CapabilityValueToStr(const uint8_t& type, } } -std::string CodecCapabilitiesLtvFormat(const uint8_t& type, - const std::vector& value) { +std::string CodecCapabilitiesLtvFormat(const uint8_t& type, const std::vector& value) { std::string string = ""; string += CapabilityTypeToStr(type) + ": "; @@ -428,11 +406,12 @@ std::string CodecCapabilitiesLtvFormat(const uint8_t& type, } std::optional> LeAudioLtvMap::Find(uint8_t type) const { - auto iter = - std::find_if(values.cbegin(), values.cend(), - [type](const auto& value) { return value.first == type; }); + auto iter = std::find_if(values.cbegin(), values.cend(), + [type](const auto& value) { return value.first == type; }); - if (iter == values.cend()) return std::nullopt; + if (iter == values.cend()) { + return std::nullopt; + } return iter->second; } @@ -441,8 +420,7 @@ uint8_t* LeAudioLtvMap::RawPacket(uint8_t* p_buf) const { for (auto const& value : values) { UINT8_TO_STREAM(p_buf, value.second.size() + 1); UINT8_TO_STREAM(p_buf, value.first); - ARRAY_TO_STREAM(p_buf, value.second.data(), - static_cast(value.second.size())); + ARRAY_TO_STREAM(p_buf, value.second.data(), static_cast(value.second.size())); } return p_buf; @@ -463,8 +441,7 @@ void LeAudioLtvMap::Append(const LeAudioLtvMap& other) { invalidate(); } -LeAudioLtvMap LeAudioLtvMap::Parse(const uint8_t* p_value, uint8_t len, - bool& success) { +LeAudioLtvMap LeAudioLtvMap::Parse(const uint8_t* p_value, uint8_t len, bool& success) { LeAudioLtvMap ltv_map; success = ltv_map.Parse(p_value, len); if (!success) { @@ -482,7 +459,9 @@ bool LeAudioLtvMap::Parse(const uint8_t* p_value, uint8_t len) { STREAM_TO_UINT8(ltv_len, p_value); // Unusual, but possible case - if (ltv_len == 0) continue; + if (ltv_len == 0) { + continue; + } if (p_value_end < (p_value + ltv_len)) { log::error("Invalid ltv_len: {}", static_cast(ltv_len)); @@ -516,9 +495,9 @@ size_t LeAudioLtvMap::RawPacketSize() const { return bytes; } -std::string LeAudioLtvMap::ToString( - const std::string& indent_string, - std::string (*format)(const uint8_t&, const std::vector&)) const { +std::string LeAudioLtvMap::ToString(const std::string& indent_string, + std::string (*format)(const uint8_t&, + const std::vector&)) const { std::string debug_str; for (const auto& value : values) { @@ -526,9 +505,8 @@ std::string LeAudioLtvMap::ToString( if (format == nullptr) { sstream << indent_string + "type: " << std::to_string(value.first) - << "\tlen: " << std::to_string(value.second.size()) << "\tdata: " - << base::HexEncode(value.second.data(), value.second.size()) + - "\n"; + << "\tlen: " << std::to_string(value.second.size()) + << "\tdata: " << base::HexEncode(value.second.data(), value.second.size()) + "\n"; } else { sstream << indent_string + format(value.first, value.second); } @@ -539,10 +517,8 @@ std::string LeAudioLtvMap::ToString( return debug_str; } -const struct LeAudioCoreCodecConfig& LeAudioLtvMap::GetAsCoreCodecConfig() - const { - log::assert_that(!core_capabilities, - "LTVs were already parsed for capabilities!"); +const struct LeAudioCoreCodecConfig& LeAudioLtvMap::GetAsCoreCodecConfig() const { + log::assert_that(!core_capabilities, "LTVs were already parsed for capabilities!"); log::assert_that(!metadata, "LTVs were already parsed for metadata!"); if (!core_config) { @@ -551,10 +527,8 @@ const struct LeAudioCoreCodecConfig& LeAudioLtvMap::GetAsCoreCodecConfig() return *core_config; } -const struct LeAudioCoreCodecCapabilities& -LeAudioLtvMap::GetAsCoreCodecCapabilities() const { - log::assert_that(!core_config, - "LTVs were already parsed for configurations!"); +const struct LeAudioCoreCodecCapabilities& LeAudioLtvMap::GetAsCoreCodecCapabilities() const { + log::assert_that(!core_config, "LTVs were already parsed for configurations!"); log::assert_that(!metadata, "LTVs were already parsed for metadata!"); if (!core_capabilities) { @@ -564,10 +538,8 @@ LeAudioLtvMap::GetAsCoreCodecCapabilities() const { } const struct LeAudioMetadata& LeAudioLtvMap::GetAsLeAudioMetadata() const { - log::assert_that(!core_config, - "LTVs were already parsed for configurations!"); - log::assert_that(!core_capabilities, - "LTVs were already parsed for capabilities!"); + log::assert_that(!core_config, "LTVs were already parsed for configurations!"); + log::assert_that(!core_capabilities, "LTVs were already parsed for capabilities!"); if (!metadata) { metadata = LtvMapToMetadata(*this); @@ -585,7 +557,9 @@ LeAudioLtvMap LeAudioLtvMap::GetIntersection(const LeAudioLtvMap& other) const { LeAudioLtvMap result; for (auto const& [key, value] : values) { auto entry = other.Find(key); - if (entry->size() != value.size()) continue; + if (entry->size() != value.size()) { + continue; + } if (memcmp(entry->data(), value.data(), value.size()) == 0) { result.Add(key, value); } @@ -602,25 +576,23 @@ void AppendMetadataLtvEntryForCcidList(std::vector& metadata, return; } - metadata.push_back( - static_cast(types::kLeAudioMetadataTypeLen + ccid_list.size())); + metadata.push_back(static_cast(types::kLeAudioMetadataTypeLen + ccid_list.size())); metadata.push_back(static_cast(types::kLeAudioMetadataTypeCcidList)); metadata.insert(metadata.end(), ccid_list.begin(), ccid_list.end()); } -void AppendMetadataLtvEntryForStreamingContext( - std::vector& metadata, types::AudioContexts context_type) { +void AppendMetadataLtvEntryForStreamingContext(std::vector& metadata, + types::AudioContexts context_type) { std::vector streaming_context_ltv_entry; - streaming_context_ltv_entry.resize( - types::kLeAudioMetadataTypeLen + types::kLeAudioMetadataLenLen + - types::kLeAudioMetadataStreamingAudioContextLen); + streaming_context_ltv_entry.resize(types::kLeAudioMetadataTypeLen + + types::kLeAudioMetadataLenLen + + types::kLeAudioMetadataStreamingAudioContextLen); uint8_t* streaming_context_ltv_entry_buf = streaming_context_ltv_entry.data(); UINT8_TO_STREAM(streaming_context_ltv_entry_buf, - types::kLeAudioMetadataTypeLen + - types::kLeAudioMetadataStreamingAudioContextLen); + types::kLeAudioMetadataTypeLen + types::kLeAudioMetadataStreamingAudioContextLen); UINT8_TO_STREAM(streaming_context_ltv_entry_buf, types::kLeAudioMetadataTypeStreamingAudioContext); UINT16_TO_STREAM(streaming_context_ltv_entry_buf, context_type.value()); @@ -632,9 +604,11 @@ void AppendMetadataLtvEntryForStreamingContext( uint8_t GetMaxCodecFramesPerSduFromPac(const acs_ac_record* pac) { if (utils::IsCodecUsingLtvFormat(pac->codec_id)) { auto tlv_ent = pac->codec_spec_caps.Find( - codec_spec_caps::kLeAudioLtvTypeSupportedMaxCodecFramesPerSdu); + codec_spec_caps::kLeAudioLtvTypeSupportedMaxCodecFramesPerSdu); - if (tlv_ent) return VEC_UINT8_TO_UINT8(tlv_ent.value()); + if (tlv_ent) { + return VEC_UINT8_TO_UINT8(tlv_ent.value()); + } } return 1; @@ -642,41 +616,35 @@ uint8_t GetMaxCodecFramesPerSduFromPac(const acs_ac_record* pac) { namespace types { std::ostream& operator<<(std::ostream& os, const CisState& state) { - static const char* char_value_[5] = {"IDLE", "ASSIGNED", "CONNECTING", - "CONNECTED", "DISCONNECTING"}; + static const char* char_value_[5] = {"IDLE", "ASSIGNED", "CONNECTING", "CONNECTED", + "DISCONNECTING"}; - os << char_value_[static_cast(state)] << " (" - << "0x" << std::setfill('0') << std::setw(2) << static_cast(state) - << ")"; + os << char_value_[static_cast(state)] << " (" << "0x" << std::setfill('0') + << std::setw(2) << static_cast(state) << ")"; return os; } std::ostream& operator<<(std::ostream& os, const DataPathState& state) { - static const char* char_value_[4] = {"IDLE", "CONFIGURING", "CONFIGURED", - "REMOVING"}; + static const char* char_value_[4] = {"IDLE", "CONFIGURING", "CONFIGURED", "REMOVING"}; - os << char_value_[static_cast(state)] << " (" - << "0x" << std::setfill('0') << std::setw(2) << static_cast(state) - << ")"; + os << char_value_[static_cast(state)] << " (" << "0x" << std::setfill('0') + << std::setw(2) << static_cast(state) << ")"; return os; } std::ostream& operator<<(std::ostream& os, const types::CigState& state) { - static const char* char_value_[5] = {"NONE", "CREATING", "CREATED", - "REMOVING", "RECOVERING"}; + static const char* char_value_[5] = {"NONE", "CREATING", "CREATED", "REMOVING", "RECOVERING"}; - os << char_value_[static_cast(state)] << " (" - << "0x" << std::setfill('0') << std::setw(2) << static_cast(state) - << ")"; + os << char_value_[static_cast(state)] << " (" << "0x" << std::setfill('0') + << std::setw(2) << static_cast(state) << ")"; return os; } std::ostream& operator<<(std::ostream& os, const types::AseState& state) { static const char* char_value_[7] = { - "IDLE", "CODEC_CONFIGURED", "QOS_CONFIGURED", "ENABLING", - "STREAMING", "DISABLING", "RELEASING", + "IDLE", "CODEC_CONFIGURED", "QOS_CONFIGURED", "ENABLING", + "STREAMING", "DISABLING", "RELEASING", }; - os << char_value_[static_cast(state)] << " (" - << "0x" << std::setfill('0') << std::setw(2) << static_cast(state) - << ")"; + os << char_value_[static_cast(state)] << " (" << "0x" << std::setfill('0') + << std::setw(2) << static_cast(state) << ")"; return os; } @@ -687,14 +655,11 @@ std::ostream& operator<<(std::ostream& os, const LeAudioCodecId& codec_id) { return os; } -std::ostream& operator<<(std::ostream& os, - const types::LeAudioCoreCodecConfig& config) { - os << "LeAudioCoreCodecConfig{SamplFreq: " - << loghex(*config.sampling_frequency) +std::ostream& operator<<(std::ostream& os, const types::LeAudioCoreCodecConfig& config) { + os << "LeAudioCoreCodecConfig{SamplFreq: " << loghex(*config.sampling_frequency) << ", FrameDur: " << loghex(*config.frame_duration) << ", OctetsPerFrame: " << int(*config.octets_per_codec_frame) - << ", CodecFramesBlocksPerSDU: " - << int(*config.codec_frames_blocks_per_sdu) + << ", CodecFramesBlocksPerSDU: " << int(*config.codec_frames_blocks_per_sdu) << ", AudioChanLoc: " << loghex(*config.audio_channel_allocation) << "}"; return os; } @@ -762,7 +727,9 @@ std::string AudioContexts::to_string() const { std::stringstream s; for (auto ctx : bluetooth::le_audio::types::kLeAudioContextAllTypesArray) { if (test(ctx)) { - if (s.tellp() != 0) s << " | "; + if (s.tellp() != 0) { + s << " | "; + } s << ctx; } } @@ -798,8 +765,7 @@ AudioContexts get_bidirectional(BidirectionalPair p) { } template <> -std::vector get_bidirectional( - BidirectionalPair> bidir) { +std::vector get_bidirectional(BidirectionalPair> bidir) { std::vector res = bidir.sink; res.insert(std::end(res), std::begin(bidir.source), std::end(bidir.source)); return res; @@ -810,17 +776,15 @@ AudioLocations get_bidirectional(BidirectionalPair bidir) { return bidir.sink | bidir.source; } -std::ostream& operator<<( - std::ostream& os, const le_audio::types::IsoDataPathConfiguration& config) { - os << "IsoDataPathCfg{codecId: " << config.codecId - << ", isTransparent: " << config.isTransparent +std::ostream& operator<<(std::ostream& os, + const le_audio::types::IsoDataPathConfiguration& config) { + os << "IsoDataPathCfg{codecId: " << config.codecId << ", isTransparent: " << config.isTransparent << ", controllerDelayUs: " << config.controllerDelayUs << ", configuration.size: " << config.configuration.size() << "}"; return os; } -std::ostream& operator<<(std::ostream& os, - const le_audio::types::DataPathConfiguration& config) { +std::ostream& operator<<(std::ostream& os, const le_audio::types::DataPathConfiguration& config) { os << "DataPathCfg{datapathId: " << +config.dataPathId << ", dataPathCfg.size: " << +config.dataPathConfig.size() << ", isoDataPathCfg: " << config.isoDataPathConfig << "}"; @@ -847,8 +811,7 @@ std::ostream& operator<<(std::ostream& os, const LeAudioMetadata& config) { } if (config.ccid_list) { os << ", ccid_list: "; - os << base::HexEncode(config.ccid_list.value().data(), - config.ccid_list.value().size()); + os << base::HexEncode(config.ccid_list.value().data(), config.ccid_list.value().size()); } if (config.parental_rating) { os << ", parental_rating: "; @@ -893,8 +856,7 @@ template struct BidirectionalPair; template struct BidirectionalPair; template struct BidirectionalPair; template struct BidirectionalPair; -template struct BidirectionalPair< - std::vector>; +template struct BidirectionalPair>; template struct BidirectionalPair; } // namespace types diff --git a/system/bta/le_audio/le_audio_types.h b/system/bta/le_audio/le_audio_types.h index 3540a2858bd..09cd5f22dea 100644 --- a/system/bta/le_audio/le_audio_types.h +++ b/system/bta/le_audio/le_audio_types.h @@ -49,11 +49,9 @@ namespace bluetooth::le_audio { #define VEC_UINT8_TO_UINT8(vec) vec.data()[0] #define VEC_UINT8_TO_UINT16(vec) ((vec.data()[1] << 8) + vec.data()[0]) -#define OFF_VEC_UINT8_TO_UINT16(vec, off) \ - ((vec.data()[1 + off] << 8) + vec.data()[0 + off]) -#define VEC_UINT8_TO_UINT32(vec) \ - ((vec.data()[3] << 24) + (vec.data()[2] << 16) + (vec.data()[1] << 8) + \ - vec.data()[0]) +#define OFF_VEC_UINT8_TO_UINT16(vec, off) ((vec.data()[1 + off] << 8) + vec.data()[0 + off]) +#define VEC_UINT8_TO_UINT32(vec) \ + ((vec.data()[3] << 24) + (vec.data()[2] << 16) + (vec.data()[1] << 8) + vec.data()[0]) enum class DsaMode { DISABLED = 0, ACL, ISO_SW, ISO_HW }; typedef std::vector DsaModes; @@ -65,45 +63,40 @@ namespace uuid { * CSIS */ static const bluetooth::Uuid kCapServiceUuid = - bluetooth::Uuid::From16Bit(UUID_COMMON_AUDIO_SERVICE); + bluetooth::Uuid::From16Bit(UUID_COMMON_AUDIO_SERVICE); /* Assigned numbers for attributes */ static const bluetooth::Uuid kPublishedAudioCapabilityServiceUuid = - bluetooth::Uuid::From16Bit(0x1850); -static const bluetooth::Uuid kAudioStreamControlServiceUuid = - bluetooth::Uuid::From16Bit(0x184E); + bluetooth::Uuid::From16Bit(0x1850); +static const bluetooth::Uuid kAudioStreamControlServiceUuid = bluetooth::Uuid::From16Bit(0x184E); -static const bluetooth::Uuid kTelephonyMediaAudioServiceUuid = - bluetooth::Uuid::From16Bit(0x1855); +static const bluetooth::Uuid kTelephonyMediaAudioServiceUuid = bluetooth::Uuid::From16Bit(0x1855); /* Published Audio Capabilities Service Characteristics */ static const bluetooth::Uuid kSinkPublishedAudioCapabilityCharacteristicUuid = - bluetooth::Uuid::From16Bit(0x2BC9); + bluetooth::Uuid::From16Bit(0x2BC9); static const bluetooth::Uuid kSourcePublishedAudioCapabilityCharacteristicUuid = - bluetooth::Uuid::From16Bit(0x2BCB); + bluetooth::Uuid::From16Bit(0x2BCB); static const bluetooth::Uuid kSinkAudioLocationCharacteristicUuid = - bluetooth::Uuid::From16Bit(0x2BCA); + bluetooth::Uuid::From16Bit(0x2BCA); static const bluetooth::Uuid kSourceAudioLocationCharacteristicUuid = - bluetooth::Uuid::From16Bit(0x2BCC); + bluetooth::Uuid::From16Bit(0x2BCC); /* Audio Stream Control Service Characteristics */ static const bluetooth::Uuid kAudioContextAvailabilityCharacteristicUuid = - bluetooth::Uuid::From16Bit(0x2BCD); + bluetooth::Uuid::From16Bit(0x2BCD); static const bluetooth::Uuid kAudioSupportedContextCharacteristicUuid = - bluetooth::Uuid::From16Bit(0x2BCE); + bluetooth::Uuid::From16Bit(0x2BCE); /* Audio Stream Control Service Characteristics */ -static const bluetooth::Uuid kSinkAudioStreamEndpointUuid = - bluetooth::Uuid::From16Bit(0x2BC4); -static const bluetooth::Uuid kSourceAudioStreamEndpointUuid = - bluetooth::Uuid::From16Bit(0x2BC5); -static const bluetooth::Uuid - kAudioStreamEndpointControlPointCharacteristicUuid = +static const bluetooth::Uuid kSinkAudioStreamEndpointUuid = bluetooth::Uuid::From16Bit(0x2BC4); +static const bluetooth::Uuid kSourceAudioStreamEndpointUuid = bluetooth::Uuid::From16Bit(0x2BC5); +static const bluetooth::Uuid kAudioStreamEndpointControlPointCharacteristicUuid = bluetooth::Uuid::From16Bit(0x2BC6); /* Telephony and Media Audio Service Characteristics */ static const bluetooth::Uuid kTelephonyMediaAudioProfileRoleCharacteristicUuid = - bluetooth::Uuid::From16Bit(0x2B51); + bluetooth::Uuid::From16Bit(0x2B51); } // namespace uuid namespace codec_spec_conf { @@ -165,21 +158,19 @@ constexpr uint32_t kLeAudioLocationLeftSurround = 0x04000000; constexpr uint32_t kLeAudioLocationRightSurround = 0x08000000; constexpr uint32_t kLeAudioLocationAnyLeft = - kLeAudioLocationFrontLeft | kLeAudioLocationBackLeft | - kLeAudioLocationFrontLeftOfCenter | kLeAudioLocationSideLeft | - kLeAudioLocationTopFrontLeft | kLeAudioLocationTopBackLeft | - kLeAudioLocationTopSideLeft | kLeAudioLocationBottomFrontLeft | - kLeAudioLocationFrontLeftWide | kLeAudioLocationLeftSurround; + kLeAudioLocationFrontLeft | kLeAudioLocationBackLeft | kLeAudioLocationFrontLeftOfCenter | + kLeAudioLocationSideLeft | kLeAudioLocationTopFrontLeft | kLeAudioLocationTopBackLeft | + kLeAudioLocationTopSideLeft | kLeAudioLocationBottomFrontLeft | + kLeAudioLocationFrontLeftWide | kLeAudioLocationLeftSurround; constexpr uint32_t kLeAudioLocationAnyRight = - kLeAudioLocationFrontRight | kLeAudioLocationBackRight | - kLeAudioLocationFrontRightOfCenter | kLeAudioLocationSideRight | - kLeAudioLocationTopFrontRight | kLeAudioLocationTopBackRight | - kLeAudioLocationTopSideRight | kLeAudioLocationBottomFrontRight | - kLeAudioLocationFrontRightWide | kLeAudioLocationRightSurround; + kLeAudioLocationFrontRight | kLeAudioLocationBackRight | + kLeAudioLocationFrontRightOfCenter | kLeAudioLocationSideRight | + kLeAudioLocationTopFrontRight | kLeAudioLocationTopBackRight | + kLeAudioLocationTopSideRight | kLeAudioLocationBottomFrontRight | + kLeAudioLocationFrontRightWide | kLeAudioLocationRightSurround; -constexpr uint32_t kLeAudioLocationStereo = - kLeAudioLocationFrontLeft | kLeAudioLocationFrontRight; +constexpr uint32_t kLeAudioLocationStereo = kLeAudioLocationFrontLeft | kLeAudioLocationFrontRight; /* Octets Per Frame */ constexpr uint16_t kLeAudioCodecFrameLen30 = 30; @@ -194,61 +185,57 @@ constexpr uint16_t kLeAudioCodecFrameLen120 = 120; constexpr uint8_t kInvalidCisId = 0xFF; namespace codec_spec_caps { -uint16_t constexpr SamplingFreqConfig2Capability(uint8_t conf) { - return (1 << (conf - 1)); -} +uint16_t constexpr SamplingFreqConfig2Capability(uint8_t conf) { return 1 << (conf - 1); } -uint8_t constexpr FrameDurationConfig2Capability(uint8_t conf) { - return (0x01 << (conf)); -} +uint8_t constexpr FrameDurationConfig2Capability(uint8_t conf) { return 0x01 << (conf); } /* LTV Types - same values as in Codec Specific Configurations but 0x03 is * named differently. */ constexpr uint8_t kLeAudioLtvTypeSupportedSamplingFrequencies = - codec_spec_conf::kLeAudioLtvTypeSamplingFreq; + codec_spec_conf::kLeAudioLtvTypeSamplingFreq; constexpr uint8_t kLeAudioLtvTypeSupportedFrameDurations = - codec_spec_conf::kLeAudioLtvTypeFrameDuration; + codec_spec_conf::kLeAudioLtvTypeFrameDuration; constexpr uint8_t kLeAudioLtvTypeSupportedAudioChannelCounts = - codec_spec_conf::kLeAudioLtvTypeAudioChannelAllocation; + codec_spec_conf::kLeAudioLtvTypeAudioChannelAllocation; constexpr uint8_t kLeAudioLtvTypeSupportedOctetsPerCodecFrame = - codec_spec_conf::kLeAudioLtvTypeOctetsPerCodecFrame; + codec_spec_conf::kLeAudioLtvTypeOctetsPerCodecFrame; constexpr uint8_t kLeAudioLtvTypeSupportedMaxCodecFramesPerSdu = - codec_spec_conf::kLeAudioLtvTypeCodecFrameBlocksPerSdu; + codec_spec_conf::kLeAudioLtvTypeCodecFrameBlocksPerSdu; /* Sampling Frequencies */ constexpr uint16_t kLeAudioSamplingFreq8000Hz = - SamplingFreqConfig2Capability(codec_spec_conf::kLeAudioSamplingFreq8000Hz); + SamplingFreqConfig2Capability(codec_spec_conf::kLeAudioSamplingFreq8000Hz); constexpr uint16_t kLeAudioSamplingFreq11025Hz = - SamplingFreqConfig2Capability(codec_spec_conf::kLeAudioSamplingFreq11025Hz); + SamplingFreqConfig2Capability(codec_spec_conf::kLeAudioSamplingFreq11025Hz); constexpr uint16_t kLeAudioSamplingFreq16000Hz = - SamplingFreqConfig2Capability(codec_spec_conf::kLeAudioSamplingFreq16000Hz); + SamplingFreqConfig2Capability(codec_spec_conf::kLeAudioSamplingFreq16000Hz); constexpr uint16_t kLeAudioSamplingFreq22050Hz = - SamplingFreqConfig2Capability(codec_spec_conf::kLeAudioSamplingFreq22050Hz); + SamplingFreqConfig2Capability(codec_spec_conf::kLeAudioSamplingFreq22050Hz); constexpr uint16_t kLeAudioSamplingFreq24000Hz = - SamplingFreqConfig2Capability(codec_spec_conf::kLeAudioSamplingFreq24000Hz); + SamplingFreqConfig2Capability(codec_spec_conf::kLeAudioSamplingFreq24000Hz); constexpr uint16_t kLeAudioSamplingFreq32000Hz = - SamplingFreqConfig2Capability(codec_spec_conf::kLeAudioSamplingFreq32000Hz); + SamplingFreqConfig2Capability(codec_spec_conf::kLeAudioSamplingFreq32000Hz); constexpr uint16_t kLeAudioSamplingFreq44100Hz = - SamplingFreqConfig2Capability(codec_spec_conf::kLeAudioSamplingFreq44100Hz); + SamplingFreqConfig2Capability(codec_spec_conf::kLeAudioSamplingFreq44100Hz); constexpr uint16_t kLeAudioSamplingFreq48000Hz = - SamplingFreqConfig2Capability(codec_spec_conf::kLeAudioSamplingFreq48000Hz); + SamplingFreqConfig2Capability(codec_spec_conf::kLeAudioSamplingFreq48000Hz); constexpr uint16_t kLeAudioSamplingFreq88200Hz = - SamplingFreqConfig2Capability(codec_spec_conf::kLeAudioSamplingFreq88200Hz); + SamplingFreqConfig2Capability(codec_spec_conf::kLeAudioSamplingFreq88200Hz); constexpr uint16_t kLeAudioSamplingFreq96000Hz = - SamplingFreqConfig2Capability(codec_spec_conf::kLeAudioSamplingFreq96000Hz); -constexpr uint16_t kLeAudioSamplingFreq176400Hz = SamplingFreqConfig2Capability( - codec_spec_conf::kLeAudioSamplingFreq176400Hz); -constexpr uint16_t kLeAudioSamplingFreq192000Hz = SamplingFreqConfig2Capability( - codec_spec_conf::kLeAudioSamplingFreq192000Hz); -constexpr uint16_t kLeAudioSamplingFreq384000Hz = SamplingFreqConfig2Capability( - codec_spec_conf::kLeAudioSamplingFreq384000Hz); + SamplingFreqConfig2Capability(codec_spec_conf::kLeAudioSamplingFreq96000Hz); +constexpr uint16_t kLeAudioSamplingFreq176400Hz = + SamplingFreqConfig2Capability(codec_spec_conf::kLeAudioSamplingFreq176400Hz); +constexpr uint16_t kLeAudioSamplingFreq192000Hz = + SamplingFreqConfig2Capability(codec_spec_conf::kLeAudioSamplingFreq192000Hz); +constexpr uint16_t kLeAudioSamplingFreq384000Hz = + SamplingFreqConfig2Capability(codec_spec_conf::kLeAudioSamplingFreq384000Hz); /* Frame Durations */ -constexpr uint8_t kLeAudioCodecFrameDur7500us = FrameDurationConfig2Capability( - codec_spec_conf::kLeAudioCodecFrameDur7500us); -constexpr uint8_t kLeAudioCodecFrameDur10000us = FrameDurationConfig2Capability( - codec_spec_conf::kLeAudioCodecFrameDur10000us); +constexpr uint8_t kLeAudioCodecFrameDur7500us = + FrameDurationConfig2Capability(codec_spec_conf::kLeAudioCodecFrameDur7500us); +constexpr uint8_t kLeAudioCodecFrameDur10000us = + FrameDurationConfig2Capability(codec_spec_conf::kLeAudioCodecFrameDur10000us); constexpr uint8_t kLeAudioCodecFrameDurPrefer7500us = 0x10; constexpr uint8_t kLeAudioCodecFrameDurPrefer10000us = 0x20; @@ -267,23 +254,18 @@ constexpr uint8_t kLeAudioCodecChannelCountSevenChannel = 0x40; constexpr uint8_t kLeAudioCodecChannelCountEightChannel = 0x80; /* Octets Per Frame */ -constexpr uint16_t kLeAudioCodecFrameLen30 = - codec_spec_conf::kLeAudioCodecFrameLen30; -constexpr uint16_t kLeAudioCodecFrameLen40 = - codec_spec_conf::kLeAudioCodecFrameLen40; -constexpr uint16_t kLeAudioCodecFrameLen60 = - codec_spec_conf::kLeAudioCodecFrameLen60; -constexpr uint16_t kLeAudioCodecFrameLen80 = - codec_spec_conf::kLeAudioCodecFrameLen80; -constexpr uint16_t kLeAudioCodecFrameLen120 = - codec_spec_conf::kLeAudioCodecFrameLen120; +constexpr uint16_t kLeAudioCodecFrameLen30 = codec_spec_conf::kLeAudioCodecFrameLen30; +constexpr uint16_t kLeAudioCodecFrameLen40 = codec_spec_conf::kLeAudioCodecFrameLen40; +constexpr uint16_t kLeAudioCodecFrameLen60 = codec_spec_conf::kLeAudioCodecFrameLen60; +constexpr uint16_t kLeAudioCodecFrameLen80 = codec_spec_conf::kLeAudioCodecFrameLen80; +constexpr uint16_t kLeAudioCodecFrameLen120 = codec_spec_conf::kLeAudioCodecFrameLen120; }; // namespace codec_spec_caps namespace types { constexpr uint8_t kLeAudioCodingFormatLC3 = bluetooth::hci::kIsoCodingFormatLc3; constexpr uint8_t kLeAudioCodingFormatVendorSpecific = - bluetooth::hci::kIsoCodingFormatVendorSpecific; + bluetooth::hci::kIsoCodingFormatVendorSpecific; constexpr uint16_t kLeAudioVendorCompanyIdUndefined = 0x00; constexpr uint16_t kLeAudioVendorCodecIdUndefined = 0x00; @@ -299,8 +281,7 @@ constexpr uint8_t kLeAudioMetadataTypeCcidList = 0x05; constexpr uint8_t kLeAudioMetadataTypeparentalRating = 0x06; constexpr uint8_t kLeAudioMetadataTypeProgramInfoUri = 0x07; constexpr uint8_t kLeAudioMetadataTypeAudioActiveState = 0x08; -constexpr uint8_t kLeAudioMetadataTypeBroadcastAudioImmediateRenderingFlag = - 0x09; +constexpr uint8_t kLeAudioMetadataTypeBroadcastAudioImmediateRenderingFlag = 0x09; constexpr uint8_t kLeAudioMetadataTypeExtendedMetadata = 0xFE; constexpr uint8_t kLeAudioMetadataTypeVendorSpecific = 0xFF; @@ -327,8 +308,7 @@ constexpr uint8_t kDefaultCsisSetSize = 2; constexpr uint8_t kLeAudioDirectionSink = 0x01; constexpr uint8_t kLeAudioDirectionSource = 0x02; -constexpr uint8_t kLeAudioDirectionBoth = - kLeAudioDirectionSink | kLeAudioDirectionSource; +constexpr uint8_t kLeAudioDirectionBoth = kLeAudioDirectionSink | kLeAudioDirectionSource; /* Audio stream config types */ constexpr uint8_t kFramingUnframedPduSupported = 0x00; @@ -418,20 +398,15 @@ class AudioContexts { using T = std::underlying_type::type; T mValue; - public: - explicit constexpr AudioContexts() - : mValue(static_cast(LeAudioContextType::UNINITIALIZED)) {} +public: + explicit constexpr AudioContexts() : mValue(static_cast(LeAudioContextType::UNINITIALIZED)) {} explicit constexpr AudioContexts(const T& v) : mValue(v) {} - explicit constexpr AudioContexts(const LeAudioContextType& v) - : mValue(static_cast(v)) {} - constexpr AudioContexts(const AudioContexts& other) - : mValue(static_cast(other.value())) {} + explicit constexpr AudioContexts(const LeAudioContextType& v) : mValue(static_cast(v)) {} + constexpr AudioContexts(const AudioContexts& other) : mValue(static_cast(other.value())) {} constexpr T value() const { return mValue; } T& value_ref() { return mValue; } - bool none() const { - return mValue == static_cast(LeAudioContextType::UNINITIALIZED); - } + bool none() const { return mValue == static_cast(LeAudioContextType::UNINITIALIZED); } bool any() const { return !none(); } void set(const LeAudioContextType& v) { mValue |= static_cast(v); } @@ -439,27 +414,17 @@ class AudioContexts { void unset(const LeAudioContextType& v) { mValue &= ~static_cast(v); } void unset_all(const AudioContexts& v) { mValue &= ~v.value(); } - bool test(const LeAudioContextType& v) const { - return (mValue & static_cast(v)) != 0; - } - bool test_all(const AudioContexts& v) const { - return (mValue & v.value()) == v.value(); - } - bool test_any(const AudioContexts& v) const { - return (mValue & v.value()) != 0; - } + bool test(const LeAudioContextType& v) const { return (mValue & static_cast(v)) != 0; } + bool test_all(const AudioContexts& v) const { return (mValue & v.value()) == v.value(); } + bool test_any(const AudioContexts& v) const { return (mValue & v.value()) != 0; } void clear() { mValue = static_cast(LeAudioContextType::UNINITIALIZED); } std::string to_string() const; AudioContexts& operator=(AudioContexts&& other) = default; AudioContexts& operator=(const AudioContexts&) = default; - bool operator==(const AudioContexts& other) const { - return value() == other.value(); - }; - bool operator!=(const AudioContexts& other) const { - return value() != other.value(); - }; + bool operator==(const AudioContexts& other) const { return value() == other.value(); } + bool operator!=(const AudioContexts& other) const { return value() != other.value(); } constexpr AudioContexts operator~() const { return AudioContexts(~value()); } }; @@ -468,29 +433,23 @@ AudioContexts operator|(std::underlying_type::type lhs, AudioContexts& operator|=(AudioContexts& lhs, AudioContexts const& rhs); AudioContexts& operator&=(AudioContexts& lhs, AudioContexts const& rhs); -constexpr AudioContexts operator^(const AudioContexts& lhs, - const AudioContexts& rhs) { +constexpr AudioContexts operator^(const AudioContexts& lhs, const AudioContexts& rhs) { return AudioContexts(lhs.value() ^ rhs.value()); } -constexpr AudioContexts operator|(const AudioContexts& lhs, - const AudioContexts& rhs) { +constexpr AudioContexts operator|(const AudioContexts& lhs, const AudioContexts& rhs) { return AudioContexts(lhs.value() | rhs.value()); } -constexpr AudioContexts operator&(const AudioContexts& lhs, - const AudioContexts& rhs) { +constexpr AudioContexts operator&(const AudioContexts& lhs, const AudioContexts& rhs) { return AudioContexts(lhs.value() & rhs.value()); } -constexpr AudioContexts operator|(const LeAudioContextType& lhs, - const LeAudioContextType& rhs) { +constexpr AudioContexts operator|(const LeAudioContextType& lhs, const LeAudioContextType& rhs) { using T = std::underlying_type::type; return AudioContexts(static_cast(lhs) | static_cast(rhs)); } -constexpr AudioContexts operator|(const LeAudioContextType& lhs, - const AudioContexts& rhs) { +constexpr AudioContexts operator|(const LeAudioContextType& lhs, const AudioContexts& rhs) { return AudioContexts(lhs) | rhs; } -constexpr AudioContexts operator|(const AudioContexts& lhs, - const LeAudioContextType& rhs) { +constexpr AudioContexts operator|(const AudioContexts& lhs, const LeAudioContextType& rhs) { return lhs | AudioContexts(rhs); } @@ -509,54 +468,51 @@ template T get_bidirectional(BidirectionalPair p); template -bool operator==(const types::BidirectionalPair& lhs, - const types::BidirectionalPair& rhs) { +bool operator==(const types::BidirectionalPair& lhs, const types::BidirectionalPair& rhs) { return (lhs.sink == rhs.sink) && (lhs.source == rhs.source); } /* Configuration strategy */ enum class LeAudioConfigurationStrategy : uint8_t { - MONO_ONE_CIS_PER_DEVICE = 0x00, /* Common true wireless speakers */ - STEREO_TWO_CISES_PER_DEVICE = - 0x01, /* Requires 2 ASEs and 2 Audio Allocation for left/right */ - STEREO_ONE_CIS_PER_DEVICE = 0x02, /* Requires channel count 2*/ + MONO_ONE_CIS_PER_DEVICE = 0x00, /* Common true wireless speakers */ + STEREO_TWO_CISES_PER_DEVICE = 0x01, /* Requires 2 ASEs and 2 Audio Allocation for left/right */ + STEREO_ONE_CIS_PER_DEVICE = 0x02, /* Requires channel count 2*/ RFU = 0x03, }; constexpr LeAudioContextType kLeAudioContextAllTypesArray[] = { - LeAudioContextType::UNSPECIFIED, LeAudioContextType::CONVERSATIONAL, - LeAudioContextType::MEDIA, LeAudioContextType::GAME, - LeAudioContextType::INSTRUCTIONAL, LeAudioContextType::VOICEASSISTANTS, - LeAudioContextType::LIVE, LeAudioContextType::SOUNDEFFECTS, - LeAudioContextType::NOTIFICATIONS, LeAudioContextType::RINGTONE, - LeAudioContextType::ALERTS, LeAudioContextType::EMERGENCYALARM, + LeAudioContextType::UNSPECIFIED, LeAudioContextType::CONVERSATIONAL, + LeAudioContextType::MEDIA, LeAudioContextType::GAME, + LeAudioContextType::INSTRUCTIONAL, LeAudioContextType::VOICEASSISTANTS, + LeAudioContextType::LIVE, LeAudioContextType::SOUNDEFFECTS, + LeAudioContextType::NOTIFICATIONS, LeAudioContextType::RINGTONE, + LeAudioContextType::ALERTS, LeAudioContextType::EMERGENCYALARM, }; constexpr AudioContexts kLeAudioContextAllTypes = - LeAudioContextType::UNSPECIFIED | LeAudioContextType::CONVERSATIONAL | - LeAudioContextType::MEDIA | LeAudioContextType::GAME | - LeAudioContextType::INSTRUCTIONAL | LeAudioContextType::VOICEASSISTANTS | - LeAudioContextType::LIVE | LeAudioContextType::SOUNDEFFECTS | - LeAudioContextType::NOTIFICATIONS | LeAudioContextType::RINGTONE | - LeAudioContextType::ALERTS | LeAudioContextType::EMERGENCYALARM; + LeAudioContextType::UNSPECIFIED | LeAudioContextType::CONVERSATIONAL | + LeAudioContextType::MEDIA | LeAudioContextType::GAME | LeAudioContextType::INSTRUCTIONAL | + LeAudioContextType::VOICEASSISTANTS | LeAudioContextType::LIVE | + LeAudioContextType::SOUNDEFFECTS | LeAudioContextType::NOTIFICATIONS | + LeAudioContextType::RINGTONE | LeAudioContextType::ALERTS | + LeAudioContextType::EMERGENCYALARM; constexpr AudioContexts kLeAudioContextAllBidir = - LeAudioContextType::GAME | LeAudioContextType::LIVE | - LeAudioContextType::CONVERSATIONAL | LeAudioContextType::VOICEASSISTANTS; + LeAudioContextType::GAME | LeAudioContextType::LIVE | LeAudioContextType::CONVERSATIONAL | + LeAudioContextType::VOICEASSISTANTS; constexpr AudioContexts kLeAudioContextAllRemoteSource = - LeAudioContextType::GAME | LeAudioContextType::LIVE | - LeAudioContextType::CONVERSATIONAL | LeAudioContextType::VOICEASSISTANTS; + LeAudioContextType::GAME | LeAudioContextType::LIVE | LeAudioContextType::CONVERSATIONAL | + LeAudioContextType::VOICEASSISTANTS; constexpr AudioContexts kLeAudioContextAllRemoteSinkOnly = - LeAudioContextType::MEDIA | LeAudioContextType::INSTRUCTIONAL | - LeAudioContextType::SOUNDEFFECTS | LeAudioContextType::NOTIFICATIONS | - LeAudioContextType::RINGTONE | LeAudioContextType::ALERTS | - LeAudioContextType::EMERGENCYALARM; + LeAudioContextType::MEDIA | LeAudioContextType::INSTRUCTIONAL | + LeAudioContextType::SOUNDEFFECTS | LeAudioContextType::NOTIFICATIONS | + LeAudioContextType::RINGTONE | LeAudioContextType::ALERTS | + LeAudioContextType::EMERGENCYALARM; /* Print formaters for LTV data */ -std::string CodecCapabilitiesLtvFormat(const uint8_t& type, - const std::vector& value); +std::string CodecCapabilitiesLtvFormat(const uint8_t& type, const std::vector& value); /* Structures */ /** LE Audio ASE codec configuration parameters, built from LTV types defined @@ -577,36 +533,30 @@ struct LeAudioCoreCodecConfig { std::optional codec_frames_blocks_per_sdu; static uint32_t GetSamplingFrequencyHz(uint8_t sample_freq) { - return sampling_freq_map.count(sample_freq) - ? sampling_freq_map.at(sample_freq) - : 0; + return sampling_freq_map.count(sample_freq) ? sampling_freq_map.at(sample_freq) : 0; } static uint32_t GetFrameDurationUs(uint8_t framn_dur) { - return frame_duration_map.count(framn_dur) - ? frame_duration_map.at(framn_dur) - : 0; + return frame_duration_map.count(framn_dur) ? frame_duration_map.at(framn_dur) : 0; } - uint16_t GetOctectsPerFrame() const { - return octets_per_codec_frame.value_or(0); - } + uint16_t GetOctetsPerFrame() const { return octets_per_codec_frame.value_or(0); } /** Returns the sampling frequency representation in Hz */ uint32_t GetSamplingFrequencyHz() const { - if (sampling_frequency) + if (sampling_frequency) { return sampling_freq_map.count(*sampling_frequency) - ? sampling_freq_map.at(*sampling_frequency) - : 0; + ? sampling_freq_map.at(*sampling_frequency) + : 0; + } return 0; } /** Returns the frame duration representation in us */ uint32_t GetFrameDurationUs() const { - if (frame_duration) - return frame_duration_map.count(*frame_duration) - ? frame_duration_map.at(*frame_duration) - : 0; + if (frame_duration) { + return frame_duration_map.count(*frame_duration) ? frame_duration_map.at(*frame_duration) : 0; + } return 0; } @@ -616,16 +566,12 @@ struct LeAudioCoreCodecCapabilities { bool HasSupportedSamplingFrequencies() const { return supported_sampling_frequencies.has_value(); } - bool HasSupportedFrameDurations() const { - return supported_frame_durations.has_value(); - } + bool HasSupportedFrameDurations() const { return supported_frame_durations.has_value(); } bool HasSupportedOctetsPerCodecFrame() const { return supported_min_octets_per_codec_frame.has_value() && supported_max_octets_per_codec_frame.has_value(); } - bool HasSupportedAudioChannelCounts() const { - return supported_audio_channel_counts.has_value(); - } + bool HasSupportedAudioChannelCounts() const { return supported_audio_channel_counts.has_value(); } bool HasSupportedMaxCodecFramesPerSdu() const { return supported_max_codec_frames_per_sdu.has_value(); } @@ -639,8 +585,9 @@ struct LeAudioCoreCodecCapabilities { codec_spec_caps::FrameDurationConfig2Capability(value); } bool IsAudioChannelCountsSupported(uint8_t value) const { - if (value > 0) + if (value > 0) { return supported_audio_channel_counts.value_or(0) & (0b1 << (value - 1)); + } return false; } @@ -676,42 +623,37 @@ struct LeAudioMetadata { std::ostream& operator<<(std::ostream& os, const LeAudioMetadata& config); -#define LTV_ENTRY_SAMPLING_FREQUENCY(value) \ - { \ - le_audio::codec_spec_conf::kLeAudioLtvTypeSamplingFreq, \ - std::vector({(value) & 0xFF}) \ - } +#define LTV_ENTRY_SAMPLING_FREQUENCY(value) \ + { le_audio::codec_spec_conf::kLeAudioLtvTypeSamplingFreq, std::vector({(value) & 0xFF}) } #define LTV_ENTRY_FRAME_DURATION(value) \ { \ le_audio::codec_spec_conf::kLeAudioLtvTypeFrameDuration, \ - std::vector({(value) & 0xFF}) \ + std::vector({(value) & 0xFF}) \ } -#define LTV_ENTRY_AUDIO_CHANNEL_ALLOCATION(value) \ - { \ - le_audio::codec_spec_conf::kLeAudioLtvTypeAudioChannelAllocation, \ - std::vector({(uint8_t)(value) & 0xFF, \ - (uint8_t)((value) << 8) & 0xFF, \ - (uint8_t)((value) << 16) & 0xFF, \ - (uint8_t)((value) << 24) & 0xFF}) \ +#define LTV_ENTRY_AUDIO_CHANNEL_ALLOCATION(value) \ + { \ + le_audio::codec_spec_conf::kLeAudioLtvTypeAudioChannelAllocation, \ + std::vector({(uint8_t)(value) & 0xFF, (uint8_t)((value) << 8) & 0xFF, \ + (uint8_t)((value) << 16) & 0xFF, \ + (uint8_t)((value) << 24) & 0xFF}) \ } -#define LTV_ENTRY_OCTETS_PER_CODEC_FRAME(value) \ - { \ - le_audio::codec_spec_conf::kLeAudioLtvTypeOctetsPerCodecFrame, \ - std::vector( \ - {(uint8_t)(value) & 0xFF, (uint8_t)((value) << 8) & 0xFF}) \ +#define LTV_ENTRY_OCTETS_PER_CODEC_FRAME(value) \ + { \ + le_audio::codec_spec_conf::kLeAudioLtvTypeOctetsPerCodecFrame, \ + std::vector({(uint8_t)(value) & 0xFF, (uint8_t)((value) << 8) & 0xFF}) \ } #define LTV_ENTRY_FRAME_BLOCKS_PER_SDU(value) \ { \ le_audio::codec_spec_conf::kLeAudioLtvTypeCodecFrameBlocksPerSdu, \ - std::vector({(value) & 0xFF}) \ + std::vector({(value) & 0xFF}) \ } class LeAudioLtvMap { - public: +public: LeAudioLtvMap(std::map> values) : values(values), value_hash(0), @@ -721,13 +663,9 @@ class LeAudioLtvMap { LeAudioLtvMap() = default; ~LeAudioLtvMap() = default; - bool operator==(const LeAudioLtvMap& other) const { - return GetHash() == other.GetHash(); - } + bool operator==(const LeAudioLtvMap& other) const { return GetHash() == other.GetHash(); } - bool operator!=(const LeAudioLtvMap& other) const { - return GetHash() != other.GetHash(); - } + bool operator!=(const LeAudioLtvMap& other) const { return GetHash() != other.GetHash(); } std::optional> Find(uint8_t type) const; const auto& At(uint8_t type) const { return values.at(type); } @@ -739,8 +677,7 @@ class LeAudioLtvMap { } // Add vendor specific data preceded with 2 octets of company ID - LeAudioLtvMap& Add(uint8_t type, uint16_t vendorCompanyId, - std::vector value) { + LeAudioLtvMap& Add(uint8_t type, uint16_t vendorCompanyId, std::vector value) { std::vector data(value.size() + 2); auto ptr = data.data(); UINT16_TO_STREAM(ptr, vendorCompanyId); @@ -804,18 +741,15 @@ class LeAudioLtvMap { values.clear(); } size_t Size() const { return values.size(); } - const std::map>& Values() const { - return values; - } + const std::map>& Values() const { return values; } const struct LeAudioCoreCodecConfig& GetAsCoreCodecConfig() const; const struct LeAudioCoreCodecCapabilities& GetAsCoreCodecCapabilities() const; const struct LeAudioMetadata& GetAsLeAudioMetadata() const; LeAudioLtvMap GetIntersection(const LeAudioLtvMap& other) const; - std::string ToString( - const std::string& indent_string, - std::string (*format)(const uint8_t&, const std::vector&)) const; + std::string ToString(const std::string& indent_string, + std::string (*format)(const uint8_t&, const std::vector&)) const; size_t RawPacketSize() const; uint8_t* RawPacket(uint8_t* p_buf) const; std::vector RawPacket() const; @@ -823,11 +757,13 @@ class LeAudioLtvMap { bool Parse(const uint8_t* value, uint8_t len); void Append(const LeAudioLtvMap& other); size_t GetHash() const { - if (value_hash == 0) RecalculateValueHash(); + if (value_hash == 0) { + RecalculateValueHash(); + } return value_hash; } - private: +private: void invalidate() { core_config = std::nullopt; core_capabilities = std::nullopt; @@ -840,109 +776,94 @@ class LeAudioLtvMap { auto vec_opt = ltvs.Find(types::kLeAudioMetadataTypePreferredAudioContext); if (vec_opt && - (vec_opt->size() == - sizeof(decltype(metadata.preferred_audio_context)::value_type))) { + (vec_opt->size() == sizeof(decltype(metadata.preferred_audio_context)::value_type))) { auto ptr = vec_opt->data(); STREAM_TO_UINT16(metadata.preferred_audio_context, ptr); } vec_opt = ltvs.Find(types::kLeAudioMetadataTypeStreamingAudioContext); if (vec_opt && - (vec_opt->size() == - sizeof(decltype(metadata.streaming_audio_context)::value_type))) { + (vec_opt->size() == sizeof(decltype(metadata.streaming_audio_context)::value_type))) { auto ptr = vec_opt->data(); STREAM_TO_UINT16(metadata.streaming_audio_context, ptr); } vec_opt = ltvs.Find(types::kLeAudioMetadataTypeProgramInfo); if (vec_opt) { - metadata.program_info = std::string( - reinterpret_cast(vec_opt->data()), vec_opt->size()); + metadata.program_info = + std::string(reinterpret_cast(vec_opt->data()), vec_opt->size()); } vec_opt = ltvs.Find(types::kLeAudioMetadataTypeLanguage); if (vec_opt && (vec_opt->size() == 3)) { // it is always 3 in ISO 639-3 - metadata.language = std::string( - reinterpret_cast(vec_opt->data()), vec_opt->size()); + metadata.language = + std::string(reinterpret_cast(vec_opt->data()), vec_opt->size()); } metadata.ccid_list = ltvs.Find(types::kLeAudioMetadataTypeCcidList); vec_opt = ltvs.Find(types::kLeAudioMetadataTypeparentalRating); - if (vec_opt && (vec_opt->size() == - sizeof(decltype(metadata.parental_rating)::value_type))) { + if (vec_opt && (vec_opt->size() == sizeof(decltype(metadata.parental_rating)::value_type))) { auto ptr = vec_opt->data(); STREAM_TO_UINT8(metadata.parental_rating, ptr); } vec_opt = ltvs.Find(types::kLeAudioMetadataTypeProgramInfoUri); if (vec_opt) { - metadata.program_info_uri = std::string( - reinterpret_cast(vec_opt->data()), vec_opt->size()); + metadata.program_info_uri = + std::string(reinterpret_cast(vec_opt->data()), vec_opt->size()); } vec_opt = ltvs.Find(types::kLeAudioMetadataTypeAudioActiveState); - if (vec_opt && - (vec_opt->size() == - sizeof(decltype(metadata.audio_active_state)::value_type))) { + if (vec_opt && (vec_opt->size() == sizeof(decltype(metadata.audio_active_state)::value_type))) { auto ptr = vec_opt->data(); uint8_t val; STREAM_TO_UINT8(val, ptr); metadata.audio_active_state = val ? true : false; } - vec_opt = ltvs.Find( - types::kLeAudioMetadataTypeBroadcastAudioImmediateRenderingFlag); + vec_opt = ltvs.Find(types::kLeAudioMetadataTypeBroadcastAudioImmediateRenderingFlag); if (vec_opt) { metadata.broadcast_audio_immediate_rendering = true; } - metadata.extended_metadata = - ltvs.Find(types::kLeAudioMetadataTypeExtendedMetadata); - metadata.vendor_specific = - ltvs.Find(types::kLeAudioMetadataTypeVendorSpecific); + metadata.extended_metadata = ltvs.Find(types::kLeAudioMetadataTypeExtendedMetadata); + metadata.vendor_specific = ltvs.Find(types::kLeAudioMetadataTypeVendorSpecific); return metadata; } - static LeAudioCoreCodecConfig LtvMapToCoreCodecConfig( - const LeAudioLtvMap& ltvs) { + static LeAudioCoreCodecConfig LtvMapToCoreCodecConfig(const LeAudioLtvMap& ltvs) { LeAudioCoreCodecConfig core; auto vec_opt = ltvs.Find(codec_spec_conf::kLeAudioLtvTypeSamplingFreq); - if (vec_opt && (vec_opt->size() == - sizeof(decltype(core.sampling_frequency)::value_type))) { + if (vec_opt && (vec_opt->size() == sizeof(decltype(core.sampling_frequency)::value_type))) { auto ptr = vec_opt->data(); STREAM_TO_UINT8(core.sampling_frequency, ptr); } vec_opt = ltvs.Find(codec_spec_conf::kLeAudioLtvTypeFrameDuration); - if (vec_opt && (vec_opt->size() == - sizeof(decltype(core.frame_duration)::value_type))) { + if (vec_opt && (vec_opt->size() == sizeof(decltype(core.frame_duration)::value_type))) { auto ptr = vec_opt->data(); STREAM_TO_UINT8(core.frame_duration, ptr); } vec_opt = ltvs.Find(codec_spec_conf::kLeAudioLtvTypeAudioChannelAllocation); if (vec_opt && - (vec_opt->size() == - sizeof(decltype(core.audio_channel_allocation)::value_type))) { + (vec_opt->size() == sizeof(decltype(core.audio_channel_allocation)::value_type))) { auto ptr = vec_opt->data(); STREAM_TO_UINT32(core.audio_channel_allocation, ptr); } vec_opt = ltvs.Find(codec_spec_conf::kLeAudioLtvTypeOctetsPerCodecFrame); - if (vec_opt && - (vec_opt->size() == - sizeof(decltype(core.octets_per_codec_frame)::value_type))) { + if (vec_opt && (vec_opt->size() == sizeof(decltype(core.octets_per_codec_frame)::value_type))) { auto ptr = vec_opt->data(); STREAM_TO_UINT16(core.octets_per_codec_frame, ptr); } vec_opt = ltvs.Find(codec_spec_conf::kLeAudioLtvTypeCodecFrameBlocksPerSdu); if (vec_opt && - (vec_opt->size() == - sizeof(decltype(core.codec_frames_blocks_per_sdu)::value_type))) { + (vec_opt->size() == sizeof(decltype(core.codec_frames_blocks_per_sdu)::value_type))) { auto ptr = vec_opt->data(); STREAM_TO_UINT8(core.codec_frames_blocks_per_sdu, ptr); } @@ -950,38 +871,28 @@ class LeAudioLtvMap { return core; } - static LeAudioCoreCodecCapabilities LtvMapToCoreCodecCapabilities( - const LeAudioLtvMap& pacs) { + static LeAudioCoreCodecCapabilities LtvMapToCoreCodecCapabilities(const LeAudioLtvMap& pacs) { LeAudioCoreCodecCapabilities core; - auto pac = - pacs.Find(codec_spec_caps::kLeAudioLtvTypeSupportedSamplingFrequencies); + auto pac = pacs.Find(codec_spec_caps::kLeAudioLtvTypeSupportedSamplingFrequencies); if (pac && - (pac.value().size() == - sizeof(decltype(core.supported_sampling_frequencies)::value_type))) { + (pac.value().size() == sizeof(decltype(core.supported_sampling_frequencies)::value_type))) { core.supported_sampling_frequencies = VEC_UINT8_TO_UINT16(pac.value()); } pac = pacs.Find(codec_spec_caps::kLeAudioLtvTypeSupportedFrameDurations); - if (pac && (pac.value().size() == - sizeof(decltype(core.supported_frame_durations)::value_type))) { + if (pac && + (pac.value().size() == sizeof(decltype(core.supported_frame_durations)::value_type))) { core.supported_frame_durations = VEC_UINT8_TO_UINT8(pac.value()); } - pac = - pacs.Find(codec_spec_caps::kLeAudioLtvTypeSupportedOctetsPerCodecFrame); - if (pac && - (pac.value().size() == - (sizeof( - decltype(core.supported_min_octets_per_codec_frame)::value_type) + - sizeof(decltype(core.supported_max_octets_per_codec_frame):: - value_type)))) { - core.supported_min_octets_per_codec_frame = - VEC_UINT8_TO_UINT16(pac.value()); + pac = pacs.Find(codec_spec_caps::kLeAudioLtvTypeSupportedOctetsPerCodecFrame); + if (pac && (pac.value().size() == + (sizeof(decltype(core.supported_min_octets_per_codec_frame)::value_type) + + sizeof(decltype(core.supported_max_octets_per_codec_frame)::value_type)))) { + core.supported_min_octets_per_codec_frame = VEC_UINT8_TO_UINT16(pac.value()); core.supported_max_octets_per_codec_frame = OFF_VEC_UINT8_TO_UINT16( - pac.value(), - sizeof( - decltype(core.supported_min_octets_per_codec_frame)::value_type)); + pac.value(), sizeof(decltype(core.supported_min_octets_per_codec_frame)::value_type)); } /* @@ -990,11 +901,9 @@ class LeAudioLtvMap { * interpreted as equivalent to a Supported_Audio_Channel_Counts value of * 0x01 (one Audio Channel supported). */ - pac = - pacs.Find(codec_spec_caps::kLeAudioLtvTypeSupportedAudioChannelCounts); + pac = pacs.Find(codec_spec_caps::kLeAudioLtvTypeSupportedAudioChannelCounts); if (pac && - (pac.value().size() == - sizeof(decltype(core.supported_audio_channel_counts)::value_type))) { + (pac.value().size() == sizeof(decltype(core.supported_audio_channel_counts)::value_type))) { core.supported_audio_channel_counts = VEC_UINT8_TO_UINT8(pac.value()); } else { core.supported_audio_channel_counts = 0b1; @@ -1006,12 +915,9 @@ class LeAudioLtvMap { * be interpreted as equivalent to a Supported_Max_Codec_Frames_Per_SDU * value of 1 codec frame per Audio Channel per SDU maximum. */ - pac = pacs.Find( - codec_spec_caps::kLeAudioLtvTypeSupportedMaxCodecFramesPerSdu); - if (pac && - (pac.value().size() == - sizeof( - decltype(core.supported_max_codec_frames_per_sdu)::value_type))) { + pac = pacs.Find(codec_spec_caps::kLeAudioLtvTypeSupportedMaxCodecFramesPerSdu); + if (pac && (pac.value().size() == + sizeof(decltype(core.supported_max_codec_frames_per_sdu)::value_type))) { core.supported_max_codec_frames_per_sdu = VEC_UINT8_TO_UINT8(pac.value()); } else { core.supported_max_codec_frames_per_sdu = 1; @@ -1028,16 +934,14 @@ class LeAudioLtvMap { auto value_vec = RawPacket(); value_hash = std::hash{}( - {reinterpret_cast(value_vec.data()), value_vec.size()}); + {reinterpret_cast(value_vec.data()), value_vec.size()}); } std::map> values = {}; mutable size_t value_hash = 0; // Lazy-constructed views of the LTV data - mutable std::optional core_config = - std::nullopt; - mutable std::optional core_capabilities = - std::nullopt; + mutable std::optional core_config = std::nullopt; + mutable std::optional core_capabilities = std::nullopt; mutable std::optional metadata = std::nullopt; }; @@ -1047,12 +951,15 @@ struct LeAudioCodecId { uint16_t vendor_codec_id; friend bool operator==(const LeAudioCodecId& lhs, const LeAudioCodecId& rhs) { - if (lhs.coding_format != rhs.coding_format) return false; + if (lhs.coding_format != rhs.coding_format) { + return false; + } if (lhs.coding_format == kLeAudioCodingFormatVendorSpecific && (lhs.vendor_company_id != rhs.vendor_company_id || - lhs.vendor_codec_id != rhs.vendor_codec_id)) + lhs.vendor_codec_id != rhs.vendor_codec_id)) { return false; + } return true; } @@ -1063,9 +970,9 @@ struct LeAudioCodecId { }; /* Google vendor specific codec for Headtracking */ -constexpr LeAudioCodecId kLeAudioCodecHeadtracking = { - kLeAudioCodingFormatVendorSpecific, kLeAudioVendorCompanyIdGoogle, - kLeAudioVendorCodecIdHeadtracking}; +constexpr LeAudioCodecId kLeAudioCodecHeadtracking = {kLeAudioCodingFormatVendorSpecific, + kLeAudioVendorCompanyIdGoogle, + kLeAudioVendorCodecIdHeadtracking}; struct IsoDataPathConfiguration { types::LeAudioCodecId codecId = {0, 0, 0}; @@ -1074,25 +981,29 @@ struct IsoDataPathConfiguration { std::vector configuration = {}; bool operator==(const IsoDataPathConfiguration& other) const { - if (codecId != other.codecId) return false; - if (isTransparent != other.isTransparent) return false; - if (controllerDelayUs != other.controllerDelayUs) return false; - if (configuration.size() != other.configuration.size()) return false; + if (codecId != other.codecId) { + return false; + } + if (isTransparent != other.isTransparent) { + return false; + } + if (controllerDelayUs != other.controllerDelayUs) { + return false; + } + if (configuration.size() != other.configuration.size()) { + return false; + } if ((!other.configuration.empty()) && - memcmp(configuration.data(), other.configuration.data(), - other.configuration.size())) { + memcmp(configuration.data(), other.configuration.data(), other.configuration.size())) { return false; } return true; } - bool operator!=(const IsoDataPathConfiguration& other) const { - return !(*this == other); - } + bool operator!=(const IsoDataPathConfiguration& other) const { return !(*this == other); } }; -std::ostream& operator<<( - std::ostream& os, const le_audio::types::IsoDataPathConfiguration& config); +std::ostream& operator<<(std::ostream& os, const le_audio::types::IsoDataPathConfiguration& config); struct DataPathConfiguration { uint8_t dataPathId = 0; @@ -1100,29 +1011,30 @@ struct DataPathConfiguration { IsoDataPathConfiguration isoDataPathConfig; bool operator==(const DataPathConfiguration& other) const { - if (dataPathId != other.dataPathId) return false; - if (isoDataPathConfig != other.isoDataPathConfig) return false; - if (dataPathConfig.size() != other.dataPathConfig.size()) return false; + if (dataPathId != other.dataPathId) { + return false; + } + if (isoDataPathConfig != other.isoDataPathConfig) { + return false; + } + if (dataPathConfig.size() != other.dataPathConfig.size()) { + return false; + } if ((!other.dataPathConfig.empty()) && - memcmp(dataPathConfig.data(), other.dataPathConfig.data(), - other.dataPathConfig.size())) { + memcmp(dataPathConfig.data(), other.dataPathConfig.data(), other.dataPathConfig.size())) { return false; } return true; } - bool operator!=(const DataPathConfiguration& other) const { - return !(*this == other); - } + bool operator!=(const DataPathConfiguration& other) const { return !(*this == other); } }; -std::ostream& operator<<(std::ostream& os, - const le_audio::types::DataPathConfiguration& config); +std::ostream& operator<<(std::ostream& os, const le_audio::types::DataPathConfiguration& config); struct hdl_pair { hdl_pair() = default; - hdl_pair(uint16_t val_hdl, uint16_t ccc_hdl) - : val_hdl(val_hdl), ccc_hdl(ccc_hdl) {} + hdl_pair(uint16_t val_hdl, uint16_t ccc_hdl) : val_hdl(val_hdl), ccc_hdl(ccc_hdl) {} uint16_t val_hdl = 0; uint16_t ccc_hdl = 0; @@ -1151,8 +1063,7 @@ struct AseQosPreferences { struct ase { static constexpr uint8_t kAseIdInvalid = 0x00; - ase(uint16_t val_hdl, uint16_t ccc_hdl, uint8_t direction, - uint8_t initial_id = kAseIdInvalid) + ase(uint16_t val_hdl, uint16_t ccc_hdl, uint8_t direction, uint8_t initial_id = kAseIdInvalid) : hdls(val_hdl, ccc_hdl), id(initial_id), cis_id(kInvalidCisId), @@ -1205,15 +1116,13 @@ struct acs_ac_record { std::vector metadata; }; -using PublishedAudioCapabilities = - std::vector>>; +using PublishedAudioCapabilities = std::vector>>; using AudioLocations = std::bitset<32>; std::ostream& operator<<(std::ostream& os, const AseState& state); std::ostream& operator<<(std::ostream& os, const CigState& state); std::ostream& operator<<(std::ostream& os, const LeAudioCodecId& codec_id); -std::ostream& operator<<(std::ostream& os, - const LeAudioCoreCodecConfig& config); +std::ostream& operator<<(std::ostream& os, const LeAudioCoreCodecConfig& config); std::string contextTypeToStr(const LeAudioContextType& context); std::ostream& operator<<(std::ostream& os, const LeAudioContextType& context); std::ostream& operator<<(std::ostream& os, const DataPathState& state); @@ -1235,29 +1144,24 @@ struct CodecConfigSetting { /* Channel count per device */ uint8_t channel_count_per_iso_stream; - /* Octects per fram for codec */ - uint16_t GetOctectsPerFrame() const; - /* Sampling freqency requested for codec */ + /* Octets per fram for codec */ + uint16_t GetOctetsPerFrame() const; + /* Sampling frequency requested for codec */ uint32_t GetSamplingFrequencyHz() const; /* Data fetch/feed interval for codec in microseconds */ uint32_t GetDataIntervalUs() const; /* Audio bit depth required for codec */ uint8_t GetBitsPerSample() const; /* Audio channels number for a device */ - uint8_t GetChannelCountPerIsoStream() const { - return channel_count_per_iso_stream; - } + uint8_t GetChannelCountPerIsoStream() const { return channel_count_per_iso_stream; } bool operator==(const CodecConfigSetting& other) const { return (id == other.id) && - (channel_count_per_iso_stream == - other.channel_count_per_iso_stream) && + (channel_count_per_iso_stream == other.channel_count_per_iso_stream) && (vendor_params == other.vendor_params) && (params == other.params); } - bool operator!=(const CodecConfigSetting& other) const { - return !(*this == other); - } + bool operator!=(const CodecConfigSetting& other) const { return !(*this == other); } /* TODO: Add vendor parameter or Ltv map viewers for * vendor specific LTV types. @@ -1276,19 +1180,18 @@ struct QosConfigSetting { bool operator!=(const QosConfigSetting& other) { return !(*this == other); } bool operator==(const QosConfigSetting& other) const { - return ((target_latency == other.target_latency) && - (retransmission_number == other.retransmission_number) && - (max_transport_latency == other.max_transport_latency)); + return (target_latency == other.target_latency) && + (retransmission_number == other.retransmission_number) && + (max_transport_latency == other.max_transport_latency); } }; std::ostream& operator<<(std::ostream& os, const QosConfigSetting& config); struct AseConfiguration { - AseConfiguration(CodecConfigSetting codec, - QosConfigSetting qos = {.target_latency = 0, - .retransmission_number = 0, - .max_transport_latency = 0}) + AseConfiguration(CodecConfigSetting codec, QosConfigSetting qos = {.target_latency = 0, + .retransmission_number = 0, + .max_transport_latency = 0}) : codec(codec), qos(qos) {} types::DataPathConfiguration data_path_configuration; CodecConfigSetting codec; @@ -1297,8 +1200,8 @@ struct AseConfiguration { bool operator!=(const AseConfiguration& other) { return !(*this == other); } bool operator==(const AseConfiguration& other) const { - return ((data_path_configuration == other.data_path_configuration) && - (codec == other.codec) && (qos == other.qos)); + return (data_path_configuration == other.data_path_configuration) && (codec == other.codec) && + (qos == other.qos); } }; @@ -1311,12 +1214,10 @@ struct AudioSetConfiguration { uint8_t packing = bluetooth::hci::kIsoCigPackingSequential; types::BidirectionalPair> confs; - bool operator!=(const AudioSetConfiguration& other) { - return !(*this == other); - } + bool operator!=(const AudioSetConfiguration& other) { return !(*this == other); } bool operator==(const AudioSetConfiguration& other) const { - return ((packing == other.packing) && (confs == other.confs)); + return (packing == other.packing) && (confs == other.confs); } }; @@ -1325,21 +1226,18 @@ std::ostream& operator<<(std::ostream& os, const AudioSetConfiguration& config); using AudioSetConfigurations = std::vector; const types::LeAudioCodecId LeAudioCodecIdLc3 = { - .coding_format = types::kLeAudioCodingFormatLC3, - .vendor_company_id = types::kLeAudioVendorCompanyIdUndefined, - .vendor_codec_id = types::kLeAudioVendorCodecIdUndefined}; + .coding_format = types::kLeAudioCodingFormatLC3, + .vendor_company_id = types::kLeAudioVendorCompanyIdUndefined, + .vendor_codec_id = types::kLeAudioVendorCodecIdUndefined}; static constexpr uint32_t kChannelAllocationStereo = - codec_spec_conf::kLeAudioLocationFrontLeft | - codec_spec_conf::kLeAudioLocationFrontRight; + codec_spec_conf::kLeAudioLocationFrontLeft | codec_spec_conf::kLeAudioLocationFrontRight; /* Declarations */ -void get_cis_count(types::LeAudioContextType context_type, - int expected_device_cnt, - types::LeAudioConfigurationStrategy strategy, - int group_ase_snk_cnt, int group_ase_src_count, - uint8_t& cis_count_bidir, uint8_t& cis_count_unidir_sink, - uint8_t& cis_count_unidir_source); +void get_cis_count(types::LeAudioContextType context_type, int expected_device_cnt, + types::LeAudioConfigurationStrategy strategy, int group_ase_snk_cnt, + int group_ase_src_count, uint8_t& cis_count_bidir, + uint8_t& cis_count_unidir_sink, uint8_t& cis_count_unidir_source); } // namespace set_configurations struct stream_parameters { @@ -1373,9 +1271,7 @@ struct stream_configuration { bool pending_configuration; /* Currently selected remote device set configuration */ - std::shared_ptr< - const bluetooth::le_audio::set_configurations::AudioSetConfiguration> - conf; + std::shared_ptr conf; /* Currently selected local audio codec */ types::LeAudioCodecId codec_id; @@ -1386,20 +1282,18 @@ struct stream_configuration { void AppendMetadataLtvEntryForCcidList(std::vector& metadata, const std::vector& ccid_list); -void AppendMetadataLtvEntryForStreamingContext( - std::vector& metadata, types::AudioContexts context_type); +void AppendMetadataLtvEntryForStreamingContext(std::vector& metadata, + types::AudioContexts context_type); uint8_t GetMaxCodecFramesPerSduFromPac(const types::acs_ac_record* pac_record); } // namespace bluetooth::le_audio namespace fmt { template <> -struct formatter - : enum_formatter {}; +struct formatter : enum_formatter {}; template <> struct formatter : enum_formatter {}; template <> struct formatter - : enum_formatter { -}; + : enum_formatter {}; } // namespace fmt diff --git a/system/bta/le_audio/le_audio_types_test.cc b/system/bta/le_audio/le_audio_types_test.cc index cf24910e0e7..93dee03cc3a 100644 --- a/system/bta/le_audio/le_audio_types_test.cc +++ b/system/bta/le_audio/le_audio_types_test.cc @@ -56,8 +56,7 @@ TEST(LeAudioLtvMapTest, test_serialization) { // Parse bool success; - LeAudioLtvMap ltv_map = - LeAudioLtvMap::Parse(ltv_test_vec.data(), ltv_test_vec.size(), success); + LeAudioLtvMap ltv_map = LeAudioLtvMap::Parse(ltv_test_vec.data(), ltv_test_vec.size(), success); auto hash_one = ltv_map.GetHash(); ASSERT_TRUE(success); ASSERT_NE(hash_one, 0lu); @@ -68,7 +67,7 @@ TEST(LeAudioLtvMapTest, test_serialization) { ASSERT_THAT(*(ltv_map.Find(0x03)), ElementsAre(0xde, 0xc0, 0xd0)); LeAudioLtvMap ltv_map2 = - LeAudioLtvMap::Parse(ltv_test_vec2.data(), ltv_test_vec2.size(), success); + LeAudioLtvMap::Parse(ltv_test_vec2.data(), ltv_test_vec2.size(), success); auto hash_two = ltv_map2.GetHash(); ASSERT_TRUE(success); ASSERT_NE(hash_two, 0lu); @@ -126,8 +125,7 @@ TEST(LeAudioLtvMapTest, test_serialization_ltv_len_is_zero) { // Parse bool success; - LeAudioLtvMap ltv_map = - LeAudioLtvMap::Parse(ltv_test_vec.data(), ltv_test_vec.size(), success); + LeAudioLtvMap ltv_map = LeAudioLtvMap::Parse(ltv_test_vec.data(), ltv_test_vec.size(), success); ASSERT_TRUE(success); ASSERT_FALSE(ltv_map.IsEmpty()); ASSERT_EQ((size_t)3, ltv_map.Size()); @@ -142,8 +140,8 @@ TEST(LeAudioLtvMapTest, test_serialization_ltv_len_is_zero) { // RawPacket std::vector serialized(ltv_map.RawPacketSize()); ASSERT_TRUE(ltv_map.RawPacket(serialized.data())); - ASSERT_THAT(serialized, ElementsAre(0x02, 0x01, 0x0a, 0x03, 0x02, 0xaa, 0xbb, - 0x05, 0x04, 0xc0, 0xde, 0xc0, 0xde)); + ASSERT_THAT(serialized, ElementsAre(0x02, 0x01, 0x0a, 0x03, 0x02, 0xaa, 0xbb, 0x05, 0x04, 0xc0, + 0xde, 0xc0, 0xde)); } TEST(LeAudioLtvMapTest, test_serialization_ltv_len_is_one) { @@ -156,8 +154,7 @@ TEST(LeAudioLtvMapTest, test_serialization_ltv_len_is_one) { // Parse bool success; - LeAudioLtvMap ltv_map = - LeAudioLtvMap::Parse(ltv_test_vec.data(), ltv_test_vec.size(), success); + LeAudioLtvMap ltv_map = LeAudioLtvMap::Parse(ltv_test_vec.data(), ltv_test_vec.size(), success); ASSERT_TRUE(success); ASSERT_FALSE(ltv_map.IsEmpty()); ASSERT_EQ((size_t)2, ltv_map.Size()); @@ -177,7 +174,7 @@ TEST(LeAudioLtvMapTest, test_serialization_ltv_len_is_invalid) { // clang-format off const std::vector ltv_test_vec_1{ 0x02, 0x01, 0x0a, - 0x04, 0x02, 0xaa, 0xbb, // one byte missing + 0x04, 0x02, 0xaa, 0xbb, // one byte missing }; const std::vector ltv_test_vec_2{ 0x02, 0x01, 0x0a, @@ -195,16 +192,13 @@ TEST(LeAudioLtvMapTest, test_serialization_ltv_len_is_invalid) { bool success = true; LeAudioLtvMap ltv_map; - ltv_map = LeAudioLtvMap::Parse(ltv_test_vec_1.data(), ltv_test_vec_1.size(), - success); + ltv_map = LeAudioLtvMap::Parse(ltv_test_vec_1.data(), ltv_test_vec_1.size(), success); ASSERT_FALSE(success); - ltv_map = LeAudioLtvMap::Parse(ltv_test_vec_2.data(), ltv_test_vec_2.size(), - success); + ltv_map = LeAudioLtvMap::Parse(ltv_test_vec_2.data(), ltv_test_vec_2.size(), success); ASSERT_FALSE(success); - ltv_map = LeAudioLtvMap::Parse(ltv_test_vec_3.data(), ltv_test_vec_3.size(), - success); + ltv_map = LeAudioLtvMap::Parse(ltv_test_vec_3.data(), ltv_test_vec_3.size(), success); ASSERT_FALSE(success); } @@ -215,8 +209,7 @@ TEST(LeAudioLtvMapTest, test_configuration_valid) { 0x02, 0x01, 0x08, // FrameDuration = 10000us 0x02, 0x02, 0x01, - // AudioChannelAllocation = kLeAudioLocationFrontLeft | - // kLeAudioLocationFrontRight + // AudioChannelAllocation = kLeAudioLocationFrontLeft | kLeAudioLocationFrontRight 0x05, 0x03, 0x03, 0x00, 0x00, 0x00, // OctetsPerCodecFrame = 40 0x03, 0x04, 40, 0x00, @@ -229,8 +222,8 @@ TEST(LeAudioLtvMapTest, test_configuration_valid) { // Parse bool success = true; - LeAudioLtvMap ltv_map = LeAudioLtvMap::Parse(config_ltv_vec.data(), - config_ltv_vec.size(), success); + LeAudioLtvMap ltv_map = + LeAudioLtvMap::Parse(config_ltv_vec.data(), config_ltv_vec.size(), success); ASSERT_TRUE(success); // Verify the codec configuration values @@ -246,8 +239,7 @@ TEST(LeAudioLtvMapTest, test_configuration_valid) { ASSERT_EQ(0x01, config.frame_duration.value()); ASSERT_EQ(10000u, config.GetFrameDurationUs()); - // AudioChannelAllocation = kLeAudioLocationFrontLeft | - // kLeAudioLocationFrontRight + // AudioChannelAllocation = kLeAudioLocationFrontLeft | kLeAudioLocationFrontRight ASSERT_TRUE(config.audio_channel_allocation.has_value()); ASSERT_EQ(0x00000003u, config.audio_channel_allocation.value()); @@ -286,8 +278,8 @@ TEST(LeAudioLtvMapTest, test_capabilities_valid) { // Parse bool success = true; - LeAudioLtvMap ltv_map = LeAudioLtvMap::Parse( - capabilities_ltv_vec.data(), capabilities_ltv_vec.size(), success); + LeAudioLtvMap ltv_map = + LeAudioLtvMap::Parse(capabilities_ltv_vec.data(), capabilities_ltv_vec.size(), success); ASSERT_TRUE(success); // Verify the codec capabilities values @@ -296,54 +288,52 @@ TEST(LeAudioLtvMapTest, test_capabilities_valid) { // SupportedSamplingFrequencies = 96000 and 16000 ASSERT_TRUE(caps.HasSupportedSamplingFrequencies()); ASSERT_EQ(codec_spec_caps::kLeAudioSamplingFreq16000Hz | - codec_spec_caps::kLeAudioSamplingFreq96000Hz, + codec_spec_caps::kLeAudioSamplingFreq96000Hz, caps.supported_sampling_frequencies.value()); - // Check config values agains the capabilities - ASSERT_FALSE(caps.IsSamplingFrequencyConfigSupported( - codec_spec_conf::kLeAudioSamplingFreq8000Hz)); - ASSERT_FALSE(caps.IsSamplingFrequencyConfigSupported( - codec_spec_conf::kLeAudioSamplingFreq11025Hz)); - ASSERT_TRUE(caps.IsSamplingFrequencyConfigSupported( - codec_spec_conf::kLeAudioSamplingFreq16000Hz)); - ASSERT_FALSE(caps.IsSamplingFrequencyConfigSupported( - codec_spec_conf::kLeAudioSamplingFreq22050Hz)); - ASSERT_FALSE(caps.IsSamplingFrequencyConfigSupported( - codec_spec_conf::kLeAudioSamplingFreq24000Hz)); - ASSERT_FALSE(caps.IsSamplingFrequencyConfigSupported( - codec_spec_conf::kLeAudioSamplingFreq32000Hz)); - ASSERT_FALSE(caps.IsSamplingFrequencyConfigSupported( - codec_spec_conf::kLeAudioSamplingFreq44100Hz)); - ASSERT_FALSE(caps.IsSamplingFrequencyConfigSupported( - codec_spec_conf::kLeAudioSamplingFreq48000Hz)); - ASSERT_FALSE(caps.IsSamplingFrequencyConfigSupported( - codec_spec_conf::kLeAudioSamplingFreq88200Hz)); - ASSERT_TRUE(caps.IsSamplingFrequencyConfigSupported( - codec_spec_conf::kLeAudioSamplingFreq96000Hz)); - ASSERT_FALSE(caps.IsSamplingFrequencyConfigSupported( - codec_spec_conf::kLeAudioSamplingFreq176400Hz)); - ASSERT_FALSE(caps.IsSamplingFrequencyConfigSupported( - codec_spec_conf::kLeAudioSamplingFreq192000Hz)); - ASSERT_FALSE(caps.IsSamplingFrequencyConfigSupported( - codec_spec_conf::kLeAudioSamplingFreq384000Hz)); + // Check config values against the capabilities + ASSERT_FALSE( + caps.IsSamplingFrequencyConfigSupported(codec_spec_conf::kLeAudioSamplingFreq8000Hz)); + ASSERT_FALSE( + caps.IsSamplingFrequencyConfigSupported(codec_spec_conf::kLeAudioSamplingFreq11025Hz)); + ASSERT_TRUE( + caps.IsSamplingFrequencyConfigSupported(codec_spec_conf::kLeAudioSamplingFreq16000Hz)); + ASSERT_FALSE( + caps.IsSamplingFrequencyConfigSupported(codec_spec_conf::kLeAudioSamplingFreq22050Hz)); + ASSERT_FALSE( + caps.IsSamplingFrequencyConfigSupported(codec_spec_conf::kLeAudioSamplingFreq24000Hz)); + ASSERT_FALSE( + caps.IsSamplingFrequencyConfigSupported(codec_spec_conf::kLeAudioSamplingFreq32000Hz)); + ASSERT_FALSE( + caps.IsSamplingFrequencyConfigSupported(codec_spec_conf::kLeAudioSamplingFreq44100Hz)); + ASSERT_FALSE( + caps.IsSamplingFrequencyConfigSupported(codec_spec_conf::kLeAudioSamplingFreq48000Hz)); + ASSERT_FALSE( + caps.IsSamplingFrequencyConfigSupported(codec_spec_conf::kLeAudioSamplingFreq88200Hz)); + ASSERT_TRUE( + caps.IsSamplingFrequencyConfigSupported(codec_spec_conf::kLeAudioSamplingFreq96000Hz)); + ASSERT_FALSE( + caps.IsSamplingFrequencyConfigSupported(codec_spec_conf::kLeAudioSamplingFreq176400Hz)); + ASSERT_FALSE( + caps.IsSamplingFrequencyConfigSupported(codec_spec_conf::kLeAudioSamplingFreq192000Hz)); + ASSERT_FALSE( + caps.IsSamplingFrequencyConfigSupported(codec_spec_conf::kLeAudioSamplingFreq384000Hz)); // SupportedFrameDurations = 10ms, 7.5ms, 10ms preferred ASSERT_TRUE(caps.HasSupportedFrameDurations()); ASSERT_EQ(codec_spec_caps::kLeAudioCodecFrameDur7500us | - codec_spec_caps::kLeAudioCodecFrameDur10000us | - codec_spec_caps::kLeAudioCodecFrameDurPrefer10000us, + codec_spec_caps::kLeAudioCodecFrameDur10000us | + codec_spec_caps::kLeAudioCodecFrameDurPrefer10000us, caps.supported_frame_durations.value()); - // Check config values agains the capabilities - ASSERT_TRUE(caps.IsFrameDurationConfigSupported( - codec_spec_conf::kLeAudioCodecFrameDur7500us)); - ASSERT_TRUE(caps.IsFrameDurationConfigSupported( - codec_spec_conf::kLeAudioCodecFrameDur10000us)); + // Check config values against the capabilities + ASSERT_TRUE(caps.IsFrameDurationConfigSupported(codec_spec_conf::kLeAudioCodecFrameDur7500us)); + ASSERT_TRUE(caps.IsFrameDurationConfigSupported(codec_spec_conf::kLeAudioCodecFrameDur10000us)); // SupportedAudioChannelCounts = 0b1 | 0b2 (one and two channels) ASSERT_TRUE(caps.HasSupportedAudioChannelCounts()); ASSERT_EQ(codec_spec_caps::kLeAudioCodecChannelCountSingleChannel | - codec_spec_caps::kLeAudioCodecChannelCountTwoChannel, + codec_spec_caps::kLeAudioCodecChannelCountTwoChannel, caps.supported_audio_channel_counts.value()); - // Check config values agains the capabilities + // Check config values against the capabilities ASSERT_TRUE(caps.IsAudioChannelCountsSupported(1)); ASSERT_TRUE(caps.IsAudioChannelCountsSupported(2)); for (uint8_t i = 3; i < 8; ++i) { @@ -356,41 +346,35 @@ TEST(LeAudioLtvMapTest, test_capabilities_valid) { caps.supported_min_octets_per_codec_frame.value()); ASSERT_EQ(codec_spec_caps::kLeAudioCodecFrameLen80, caps.supported_max_octets_per_codec_frame.value()); - // Check config values agains the capabilities - ASSERT_FALSE(caps.IsOctetsPerCodecFrameConfigSupported( - codec_spec_conf::kLeAudioCodecFrameLen30)); - ASSERT_TRUE(caps.IsOctetsPerCodecFrameConfigSupported( - codec_spec_conf::kLeAudioCodecFrameLen40)); + // Check config values against the capabilities + ASSERT_FALSE(caps.IsOctetsPerCodecFrameConfigSupported(codec_spec_conf::kLeAudioCodecFrameLen30)); + ASSERT_TRUE(caps.IsOctetsPerCodecFrameConfigSupported(codec_spec_conf::kLeAudioCodecFrameLen40)); // Supported since: 40(min) < 60 < 80(max) - ASSERT_TRUE(caps.IsOctetsPerCodecFrameConfigSupported( - codec_spec_conf::kLeAudioCodecFrameLen60)); - ASSERT_TRUE(caps.IsOctetsPerCodecFrameConfigSupported( - codec_spec_conf::kLeAudioCodecFrameLen80)); - ASSERT_FALSE(caps.IsOctetsPerCodecFrameConfigSupported( - codec_spec_conf::kLeAudioCodecFrameLen120)); + ASSERT_TRUE(caps.IsOctetsPerCodecFrameConfigSupported(codec_spec_conf::kLeAudioCodecFrameLen60)); + ASSERT_TRUE(caps.IsOctetsPerCodecFrameConfigSupported(codec_spec_conf::kLeAudioCodecFrameLen80)); + ASSERT_FALSE( + caps.IsOctetsPerCodecFrameConfigSupported(codec_spec_conf::kLeAudioCodecFrameLen120)); // SupportedMaxCodecFramesPerSdu = 2 ASSERT_TRUE(caps.HasSupportedMaxCodecFramesPerSdu()); ASSERT_EQ(2, caps.supported_max_codec_frames_per_sdu.value()); - // Check config values agains the capabilities: {1,2} <= 2(max) + // Check config values against the capabilities: {1,2} <= 2(max) ASSERT_TRUE(caps.IsCodecFramesPerSduSupported(1)); ASSERT_TRUE(caps.IsCodecFramesPerSduSupported(2)); ASSERT_FALSE(caps.IsCodecFramesPerSduSupported(3)); } TEST(LeAudioLtvMapTest, test_metadata_use_guard1) { - auto default_context = - (uint16_t)bluetooth::le_audio::types::LeAudioContextType::VOICEASSISTANTS; + auto default_context = (uint16_t)bluetooth::le_audio::types::LeAudioContextType::VOICEASSISTANTS; static const std::vector default_metadata = { - bluetooth::le_audio::types::kLeAudioMetadataStreamingAudioContextLen + 1, - bluetooth::le_audio::types::kLeAudioMetadataTypeStreamingAudioContext, - (uint8_t)(default_context & 0x00FF), - (uint8_t)((default_context & 0xFF00) >> 8)}; + bluetooth::le_audio::types::kLeAudioMetadataStreamingAudioContextLen + 1, + bluetooth::le_audio::types::kLeAudioMetadataTypeStreamingAudioContext, + (uint8_t)(default_context & 0x00FF), (uint8_t)((default_context & 0xFF00) >> 8)}; // Parse bool success = true; - LeAudioLtvMap ltv_map = LeAudioLtvMap::Parse( - default_metadata.data(), default_metadata.size(), success); + LeAudioLtvMap ltv_map = + LeAudioLtvMap::Parse(default_metadata.data(), default_metadata.size(), success); ASSERT_TRUE(success); // Verify the codec capabilities values @@ -401,18 +385,16 @@ TEST(LeAudioLtvMapTest, test_metadata_use_guard1) { } TEST(LeAudioLtvMapTest, test_metadata_use_guard2) { - auto default_context = - (uint16_t)bluetooth::le_audio::types::LeAudioContextType::VOICEASSISTANTS; + auto default_context = (uint16_t)bluetooth::le_audio::types::LeAudioContextType::VOICEASSISTANTS; static const std::vector default_metadata = { - bluetooth::le_audio::types::kLeAudioMetadataStreamingAudioContextLen + 1, - bluetooth::le_audio::types::kLeAudioMetadataTypeStreamingAudioContext, - (uint8_t)(default_context & 0x00FF), - (uint8_t)((default_context & 0xFF00) >> 8)}; + bluetooth::le_audio::types::kLeAudioMetadataStreamingAudioContextLen + 1, + bluetooth::le_audio::types::kLeAudioMetadataTypeStreamingAudioContext, + (uint8_t)(default_context & 0x00FF), (uint8_t)((default_context & 0xFF00) >> 8)}; // Parse bool success = true; - LeAudioLtvMap ltv_map = LeAudioLtvMap::Parse( - default_metadata.data(), default_metadata.size(), success); + LeAudioLtvMap ltv_map = + LeAudioLtvMap::Parse(default_metadata.data(), default_metadata.size(), success); ASSERT_TRUE(success); // Verify the codec capabilities values @@ -426,31 +408,25 @@ static auto PrepareMetadataLtv() { ::bluetooth::le_audio::types::LeAudioLtvMap metadata_ltvs; // Prepare the metadata LTVs metadata_ltvs - .Add(::bluetooth::le_audio::types:: - kLeAudioMetadataTypePreferredAudioContext, - (uint16_t)10) - .Add(::bluetooth::le_audio::types:: - kLeAudioMetadataTypeStreamingAudioContext, - (uint16_t)8) - .Add(::bluetooth::le_audio::types::kLeAudioMetadataTypeProgramInfo, - std::string{"ProgramInfo"}) - .Add(::bluetooth::le_audio::types::kLeAudioMetadataTypeLanguage, - std::string{"ice"}) - .Add(::bluetooth::le_audio::types::kLeAudioMetadataTypeCcidList, - std::vector{1, 2, 3}) - .Add(::bluetooth::le_audio::types::kLeAudioMetadataTypeparentalRating, - (uint8_t)0x01) - .Add(::bluetooth::le_audio::types::kLeAudioMetadataTypeProgramInfoUri, - std::string{"ProgramInfoUri"}) - .Add(::bluetooth::le_audio::types::kLeAudioMetadataTypeAudioActiveState, - false) - .Add(::bluetooth::le_audio::types:: - kLeAudioMetadataTypeBroadcastAudioImmediateRenderingFlag, - true) - .Add(::bluetooth::le_audio::types::kLeAudioMetadataTypeExtendedMetadata, - std::vector{1, 2, 3}) - .Add(::bluetooth::le_audio::types::kLeAudioMetadataTypeVendorSpecific, - std::vector{1, 2, 3}); + .Add(::bluetooth::le_audio::types::kLeAudioMetadataTypePreferredAudioContext, + (uint16_t)10) + .Add(::bluetooth::le_audio::types::kLeAudioMetadataTypeStreamingAudioContext, (uint16_t)8) + .Add(::bluetooth::le_audio::types::kLeAudioMetadataTypeProgramInfo, + std::string{"ProgramInfo"}) + .Add(::bluetooth::le_audio::types::kLeAudioMetadataTypeLanguage, std::string{"ice"}) + .Add(::bluetooth::le_audio::types::kLeAudioMetadataTypeCcidList, + std::vector{1, 2, 3}) + .Add(::bluetooth::le_audio::types::kLeAudioMetadataTypeparentalRating, (uint8_t)0x01) + .Add(::bluetooth::le_audio::types::kLeAudioMetadataTypeProgramInfoUri, + std::string{"ProgramInfoUri"}) + .Add(::bluetooth::le_audio::types::kLeAudioMetadataTypeAudioActiveState, false) + .Add(::bluetooth::le_audio::types:: + kLeAudioMetadataTypeBroadcastAudioImmediateRenderingFlag, + true) + .Add(::bluetooth::le_audio::types::kLeAudioMetadataTypeExtendedMetadata, + std::vector{1, 2, 3}) + .Add(::bluetooth::le_audio::types::kLeAudioMetadataTypeVendorSpecific, + std::vector{1, 2, 3}); return metadata_ltvs; } @@ -462,7 +438,7 @@ TEST(LeAudioLtvMapTest, test_metadata_valid) { // Check the Parsing bool success = true; LeAudioLtvMap parsed_ltv_map = - LeAudioLtvMap::Parse(raw_metadata.data(), raw_metadata.size(), success); + LeAudioLtvMap::Parse(raw_metadata.data(), raw_metadata.size(), success); ASSERT_TRUE(success); // Verify the values @@ -470,24 +446,18 @@ TEST(LeAudioLtvMapTest, test_metadata_valid) { auto parsed_metadata = parsed_ltv_map.GetAsLeAudioMetadata(); ASSERT_EQ(parsed_metadata.preferred_audio_context.value(), metadata.preferred_audio_context.value()); - ASSERT_EQ(parsed_metadata.program_info.value(), - metadata.program_info.value()); + ASSERT_EQ(parsed_metadata.program_info.value(), metadata.program_info.value()); ASSERT_TRUE(parsed_metadata.language.has_value()); ASSERT_TRUE(metadata.language.has_value()); ASSERT_EQ(parsed_metadata.language.value(), metadata.language.value()); ASSERT_EQ(parsed_metadata.ccid_list.value(), metadata.ccid_list.value()); - ASSERT_EQ(parsed_metadata.parental_rating.value(), - metadata.parental_rating.value()); - ASSERT_EQ(parsed_metadata.program_info_uri.value(), - metadata.program_info_uri.value()); - ASSERT_EQ(parsed_metadata.audio_active_state.value(), - metadata.audio_active_state.value()); + ASSERT_EQ(parsed_metadata.parental_rating.value(), metadata.parental_rating.value()); + ASSERT_EQ(parsed_metadata.program_info_uri.value(), metadata.program_info_uri.value()); + ASSERT_EQ(parsed_metadata.audio_active_state.value(), metadata.audio_active_state.value()); ASSERT_EQ(parsed_metadata.broadcast_audio_immediate_rendering.value(), metadata.broadcast_audio_immediate_rendering.value()); - ASSERT_EQ(parsed_metadata.extended_metadata.value(), - metadata.extended_metadata.value()); - ASSERT_EQ(parsed_metadata.vendor_specific.value(), - metadata.vendor_specific.value()); + ASSERT_EQ(parsed_metadata.extended_metadata.value(), metadata.extended_metadata.value()); + ASSERT_EQ(parsed_metadata.vendor_specific.value(), metadata.vendor_specific.value()); } TEST(LeAudioLtvMapTest, test_adding_types) { @@ -518,8 +488,7 @@ TEST(LeAudioLtvMapTest, test_adding_types) { ASSERT_EQ((std::vector{1, 2, 3, 4, 5, 6, 7, 8, 9}), ltv_map.At(4)); - ASSERT_EQ(std::string("sample text"), - std::string(ltv_map.At(5).begin(), ltv_map.At(5).end())); + ASSERT_EQ(std::string("sample text"), std::string(ltv_map.At(5).begin(), ltv_map.At(5).end())); ASSERT_EQ(true, (bool)ltv_map.At(6).data()[0]); } @@ -720,30 +689,27 @@ TEST(LeAudioLtvMapTest, test_intersection) { ltv_map_common.Add(2, (uint32_t)65535); ASSERT_NE(ltv_map_common.GetHash(), 0lu); - ASSERT_EQ(ltv_map_one.GetIntersection(ltv_map_two).GetHash(), - ltv_map_common.GetHash()); + ASSERT_EQ(ltv_map_one.GetIntersection(ltv_map_two).GetHash(), ltv_map_common.GetHash()); ASSERT_EQ(ltv_map_two.GetIntersection(ltv_map_one), ltv_map_common); } constexpr types::LeAudioCodecId kLeAudioCodecIdVendor1 = { - .coding_format = types::kLeAudioCodingFormatVendorSpecific, - // Not a particualr vendor - just some random numbers - .vendor_company_id = 0xC0, - .vendor_codec_id = 0xDE, + .coding_format = types::kLeAudioCodingFormatVendorSpecific, + // Not a particular vendor - just some random numbers + .vendor_company_id = 0xC0, + .vendor_codec_id = 0xDE, }; static const set_configurations::CodecConfigSetting vendor_16_2 = { - .id = kLeAudioCodecIdVendor1, - .params = types::LeAudioLtvMap({ - LTV_ENTRY_SAMPLING_FREQUENCY( - codec_spec_conf::kLeAudioSamplingFreq16000Hz), - LTV_ENTRY_FRAME_DURATION(codec_spec_conf::kLeAudioCodecFrameDur10000us), - LTV_ENTRY_AUDIO_CHANNEL_ALLOCATION( - codec_spec_conf::kLeAudioLocationStereo), - LTV_ENTRY_OCTETS_PER_CODEC_FRAME(40), - }), - .vendor_params = {0x01, 0x02, 0x03, 0x04}, - .channel_count_per_iso_stream = 1, + .id = kLeAudioCodecIdVendor1, + .params = types::LeAudioLtvMap({ + LTV_ENTRY_SAMPLING_FREQUENCY(codec_spec_conf::kLeAudioSamplingFreq16000Hz), + LTV_ENTRY_FRAME_DURATION(codec_spec_conf::kLeAudioCodecFrameDur10000us), + LTV_ENTRY_AUDIO_CHANNEL_ALLOCATION(codec_spec_conf::kLeAudioLocationStereo), + LTV_ENTRY_OCTETS_PER_CODEC_FRAME(40), + }), + .vendor_params = {0x01, 0x02, 0x03, 0x04}, + .channel_count_per_iso_stream = 1, }; TEST(CodecConfigSettingTest, test_vendor_codec_type) { diff --git a/system/bta/le_audio/le_audio_utils.cc b/system/bta/le_audio/le_audio_utils.cc index 2e30615adee..da36490e234 100644 --- a/system/bta/le_audio/le_audio_utils.cc +++ b/system/bta/le_audio/le_audio_utils.cc @@ -30,8 +30,7 @@ namespace fmt { template <> struct formatter : enum_formatter {}; template <> -struct formatter : enum_formatter { -}; +struct formatter : enum_formatter {}; template <> struct formatter : enum_formatter {}; template <> @@ -46,8 +45,8 @@ namespace utils { * Otherwise the AudioSetConfigurationProvider will fall back * to default scenario. */ -LeAudioContextType AudioContentToLeAudioContext( - audio_content_type_t content_type, audio_usage_t usage) { +LeAudioContextType AudioContentToLeAudioContext(audio_content_type_t content_type, + audio_usage_t usage) { /* Check audio attribute usage of stream */ switch (usage) { case AUDIO_USAGE_MEDIA: @@ -155,16 +154,16 @@ static std::string contentTypeToString(audio_content_type_t content_type) { } static const char* audioSourceToStr(audio_source_t source) { - const char* strArr[] = { - "AUDIO_SOURCE_DEFAULT", "AUDIO_SOURCE_MIC", - "AUDIO_SOURCE_VOICE_UPLINK", "AUDIO_SOURCE_VOICE_DOWNLINK", - "AUDIO_SOURCE_VOICE_CALL", "AUDIO_SOURCE_CAMCORDER", - "AUDIO_SOURCE_VOICE_RECOGNITION", "AUDIO_SOURCE_VOICE_COMMUNICATION", - "AUDIO_SOURCE_REMOTE_SUBMIX", "AUDIO_SOURCE_UNPROCESSED", - "AUDIO_SOURCE_VOICE_PERFORMANCE"}; - - if (static_cast(source) < (sizeof(strArr) / sizeof(strArr[0]))) + const char* strArr[] = {"AUDIO_SOURCE_DEFAULT", "AUDIO_SOURCE_MIC", + "AUDIO_SOURCE_VOICE_UPLINK", "AUDIO_SOURCE_VOICE_DOWNLINK", + "AUDIO_SOURCE_VOICE_CALL", "AUDIO_SOURCE_CAMCORDER", + "AUDIO_SOURCE_VOICE_RECOGNITION", "AUDIO_SOURCE_VOICE_COMMUNICATION", + "AUDIO_SOURCE_REMOTE_SUBMIX", "AUDIO_SOURCE_UNPROCESSED", + "AUDIO_SOURCE_VOICE_PERFORMANCE"}; + + if (static_cast(source) < (sizeof(strArr) / sizeof(strArr[0]))) { return strArr[source]; + } return "UNKNOWN"; } @@ -181,41 +180,43 @@ static bool isMetadataTagPresent(const char* tags, const char* tag) { } AudioContexts GetAudioContextsFromSourceMetadata( - const std::vector& source_metadata) { + const std::vector& source_metadata) { AudioContexts track_contexts; for (const auto& entry : source_metadata) { auto track = entry.base; - if (track.content_type == 0 && track.usage == 0) continue; + if (track.content_type == 0 && track.usage == 0) { + continue; + } - log::info("usage={}({}), content_type={}({}), gain={:f}, tag:{}", - usageToString(track.usage), track.usage, - contentTypeToString(track.content_type), - track.content_type, track.gain, entry.tags); + log::info("usage={}({}), content_type={}({}), gain={:f}, tag:{}", usageToString(track.usage), + track.usage, contentTypeToString(track.content_type), track.content_type, track.gain, + entry.tags); if (isMetadataTagPresent(entry.tags, "VX_AOSP_SAMPLESOUND")) { track_contexts.set(LeAudioContextType::SOUNDEFFECTS); } else { - track_contexts.set( - AudioContentToLeAudioContext(track.content_type, track.usage)); + track_contexts.set(AudioContentToLeAudioContext(track.content_type, track.usage)); } } return track_contexts; } AudioContexts GetAudioContextsFromSinkMetadata( - const std::vector& sink_metadata) { + const std::vector& sink_metadata) { AudioContexts all_track_contexts; for (const auto& entry : sink_metadata) { auto track = entry.base; - if (track.source == AUDIO_SOURCE_INVALID) continue; + if (track.source == AUDIO_SOURCE_INVALID) { + continue; + } LeAudioContextType track_context; log::debug( - "source={}(0x{:02x}), gain={:f}, destination device=0x{:08x}, " - "destination device address={:32s}", - audioSourceToStr(track.source), track.source, track.gain, - track.dest_device, track.dest_device_address); + "source={}(0x{:02x}), gain={:f}, destination device=0x{:08x}, " + "destination device address={:32s}", + audioSourceToStr(track.source), track.source, track.gain, track.dest_device, + track.dest_device_address); if (track.source == AUDIO_SOURCE_MIC) { track_context = LeAudioContextType::LIVE; @@ -230,31 +231,29 @@ AudioContexts GetAudioContextsFromSinkMetadata( */ track_context = LeAudioContextType::VOICEASSISTANTS; log::warn( - "Could not match the recording track type to group available " - "context. Using context {}.", - ToString(track_context)); + "Could not match the recording track type to group available " + "context. Using context {}.", + ToString(track_context)); } all_track_contexts.set(track_context); } if (all_track_contexts.none()) { - all_track_contexts = AudioContexts( - static_cast::type>( + all_track_contexts = AudioContexts(static_cast::type>( LeAudioContextType::UNSPECIFIED)); log::debug( - "Unable to find supported audio source context for the remote audio " - "sink device. This may result in voice back channel malfunction."); + "Unable to find supported audio source context for the remote audio " + "sink device. This may result in voice back channel malfunction."); } log::info("Allowed contexts from sink metadata: {} (0x{:08x})", - bluetooth::common::ToString(all_track_contexts), - all_track_contexts.value()); + bluetooth::common::ToString(all_track_contexts), all_track_contexts.value()); return all_track_contexts; } -bluetooth::le_audio::btle_audio_codec_index_t -translateBluetoothCodecFormatToCodecType(uint8_t codec_format) { +bluetooth::le_audio::btle_audio_codec_index_t translateBluetoothCodecFormatToCodecType( + uint8_t codec_format) { switch (codec_format) { case types::kLeAudioCodingFormatLC3: return bluetooth::le_audio::LE_AUDIO_CODEC_INDEX_SOURCE_LC3; @@ -262,8 +261,8 @@ translateBluetoothCodecFormatToCodecType(uint8_t codec_format) { return bluetooth::le_audio::LE_AUDIO_CODEC_INDEX_SOURCE_INVALID; } -bluetooth::le_audio::btle_audio_sample_rate_index_t -translateToBtLeAudioCodecConfigSampleRate(uint32_t sample_rate) { +bluetooth::le_audio::btle_audio_sample_rate_index_t translateToBtLeAudioCodecConfigSampleRate( + uint32_t sample_rate) { log::info("{}", sample_rate); switch (sample_rate) { case LeAudioCodecConfiguration::kSampleRate8000: @@ -283,8 +282,8 @@ translateToBtLeAudioCodecConfigSampleRate(uint32_t sample_rate) { return LE_AUDIO_SAMPLE_RATE_INDEX_NONE; } -bluetooth::le_audio::btle_audio_bits_per_sample_index_t -translateToBtLeAudioCodecConfigBitPerSample(uint8_t bits_per_sample) { +bluetooth::le_audio::btle_audio_bits_per_sample_index_t translateToBtLeAudioCodecConfigBitPerSample( + uint8_t bits_per_sample) { switch (bits_per_sample) { case 16: return bluetooth::le_audio::LE_AUDIO_BITS_PER_SAMPLE_INDEX_16; @@ -296,8 +295,8 @@ translateToBtLeAudioCodecConfigBitPerSample(uint8_t bits_per_sample) { return bluetooth::le_audio::LE_AUDIO_BITS_PER_SAMPLE_INDEX_NONE; } -bluetooth::le_audio::btle_audio_channel_count_index_t -translateToBtLeAudioCodecConfigChannelCount(uint8_t channel_count) { +bluetooth::le_audio::btle_audio_channel_count_index_t translateToBtLeAudioCodecConfigChannelCount( + uint8_t channel_count) { switch (channel_count) { case 1: return bluetooth::le_audio::LE_AUDIO_CHANNEL_COUNT_INDEX_1; @@ -307,8 +306,8 @@ translateToBtLeAudioCodecConfigChannelCount(uint8_t channel_count) { return bluetooth::le_audio::LE_AUDIO_CHANNEL_COUNT_INDEX_NONE; } -bluetooth::le_audio::btle_audio_frame_duration_index_t -translateToBtLeAudioCodecConfigFrameDuration(int frame_duration) { +bluetooth::le_audio::btle_audio_frame_duration_index_t translateToBtLeAudioCodecConfigFrameDuration( + int frame_duration) { switch (frame_duration) { case 7500: return bluetooth::le_audio::LE_AUDIO_FRAME_DURATION_INDEX_7500US; @@ -319,8 +318,8 @@ translateToBtLeAudioCodecConfigFrameDuration(int frame_duration) { } void fillStreamParamsToBtLeAudioCodecConfig( - const std::vector& confs, - bluetooth::le_audio::btle_audio_codec_config_t& out_config) { + const std::vector& confs, + bluetooth::le_audio::btle_audio_codec_config_t& out_config) { if (confs.size() == 0) { log::warn("Stream params are null"); return; @@ -328,21 +327,19 @@ void fillStreamParamsToBtLeAudioCodecConfig( auto config = confs.at(0).codec; - out_config.codec_type = - translateBluetoothCodecFormatToCodecType(config.id.coding_format); - if (out_config.codec_type != - bluetooth::le_audio::LE_AUDIO_CODEC_INDEX_SOURCE_LC3) { + out_config.codec_type = translateBluetoothCodecFormatToCodecType(config.id.coding_format); + if (out_config.codec_type != bluetooth::le_audio::LE_AUDIO_CODEC_INDEX_SOURCE_LC3) { return; } - out_config.sample_rate = translateToBtLeAudioCodecConfigSampleRate( - config.GetSamplingFrequencyHz()); + out_config.sample_rate = + translateToBtLeAudioCodecConfigSampleRate(config.GetSamplingFrequencyHz()); out_config.bits_per_sample = translateToBtLeAudioCodecConfigBitPerSample(16); out_config.frame_duration = - translateToBtLeAudioCodecConfigFrameDuration(config.GetDataIntervalUs()); - out_config.octets_per_frame = config.GetOctectsPerFrame(); - out_config.channel_count = translateToBtLeAudioCodecConfigChannelCount( - config.GetChannelCountPerIsoStream()); + translateToBtLeAudioCodecConfigFrameDuration(config.GetDataIntervalUs()); + out_config.octets_per_frame = config.GetOctetsPerFrame(); + out_config.channel_count = + translateToBtLeAudioCodecConfigChannelCount(config.GetChannelCountPerIsoStream()); } static bool is_known_codec(const types::LeAudioCodecId& codec_id) { @@ -353,60 +350,57 @@ static bool is_known_codec(const types::LeAudioCodecId& codec_id) { return false; } -static void fillRemotePacsCapabitiliesToBtLeAudioCodecConfig( - const struct types::acs_ac_record& record, - std::vector& vec) { +static void fillRemotePacsCapabilitiesToBtLeAudioCodecConfig( + const struct types::acs_ac_record& record, + std::vector& vec) { if (!utils::IsCodecUsingLtvFormat(record.codec_id)) { log::warn( - "Unknown codec capability format. Unable to report known codec " - "parameters."); + "Unknown codec capability format. Unable to report known codec " + "parameters."); return; } log::assert_that(!record.codec_spec_caps.IsEmpty(), - "Codec specific capabilities are not parsed approprietly."); + "Codec specific capabilities are not parsed appropriately."); const struct types::LeAudioCoreCodecCapabilities capa = - record.codec_spec_caps.GetAsCoreCodecCapabilities(); + record.codec_spec_caps.GetAsCoreCodecCapabilities(); for (uint8_t freq_bit = codec_spec_conf::kLeAudioSamplingFreq8000Hz; freq_bit <= codec_spec_conf::kLeAudioSamplingFreq384000Hz; freq_bit++) { - if (!capa.IsSamplingFrequencyConfigSupported(freq_bit)) continue; + if (!capa.IsSamplingFrequencyConfigSupported(freq_bit)) { + continue; + } for (uint8_t fd_bit = codec_spec_conf::kLeAudioCodecFrameDur7500us; fd_bit <= codec_spec_conf::kLeAudioCodecFrameDur10000us; fd_bit++) { - if (!capa.IsFrameDurationConfigSupported(fd_bit)) continue; + if (!capa.IsFrameDurationConfigSupported(fd_bit)) { + continue; + } if (!capa.HasSupportedAudioChannelCounts()) { bluetooth::le_audio::btle_audio_codec_config_t config = { - .codec_type = utils::translateBluetoothCodecFormatToCodecType( - record.codec_id.coding_format), - .sample_rate = utils::translateToBtLeAudioCodecConfigSampleRate( - types::LeAudioCoreCodecConfig::GetSamplingFrequencyHz( - freq_bit)), - .bits_per_sample = - utils::translateToBtLeAudioCodecConfigBitPerSample(16), - .channel_count = - utils::translateToBtLeAudioCodecConfigChannelCount(1), - .frame_duration = - utils::translateToBtLeAudioCodecConfigFrameDuration( - types::LeAudioCoreCodecConfig::GetFrameDurationUs(fd_bit)), + .codec_type = utils::translateBluetoothCodecFormatToCodecType( + record.codec_id.coding_format), + .sample_rate = utils::translateToBtLeAudioCodecConfigSampleRate( + types::LeAudioCoreCodecConfig::GetSamplingFrequencyHz(freq_bit)), + .bits_per_sample = utils::translateToBtLeAudioCodecConfigBitPerSample(16), + .channel_count = utils::translateToBtLeAudioCodecConfigChannelCount(1), + .frame_duration = utils::translateToBtLeAudioCodecConfigFrameDuration( + types::LeAudioCoreCodecConfig::GetFrameDurationUs(fd_bit)), }; vec.push_back(config); } else { for (int chan_bit = 1; chan_bit <= 2; chan_bit++) { - if (!capa.IsAudioChannelCountsSupported(chan_bit)) continue; + if (!capa.IsAudioChannelCountsSupported(chan_bit)) { + continue; + } bluetooth::le_audio::btle_audio_codec_config_t config = { - .codec_type = utils::translateBluetoothCodecFormatToCodecType( - record.codec_id.coding_format), - .sample_rate = utils::translateToBtLeAudioCodecConfigSampleRate( - types::LeAudioCoreCodecConfig::GetSamplingFrequencyHz( - freq_bit)), - .bits_per_sample = - utils::translateToBtLeAudioCodecConfigBitPerSample(16), - .channel_count = - utils::translateToBtLeAudioCodecConfigChannelCount(chan_bit), - .frame_duration = - utils::translateToBtLeAudioCodecConfigFrameDuration( - types::LeAudioCoreCodecConfig::GetFrameDurationUs( - fd_bit)), + .codec_type = utils::translateBluetoothCodecFormatToCodecType( + record.codec_id.coding_format), + .sample_rate = utils::translateToBtLeAudioCodecConfigSampleRate( + types::LeAudioCoreCodecConfig::GetSamplingFrequencyHz(freq_bit)), + .bits_per_sample = utils::translateToBtLeAudioCodecConfigBitPerSample(16), + .channel_count = utils::translateToBtLeAudioCodecConfigChannelCount(chan_bit), + .frame_duration = utils::translateToBtLeAudioCodecConfigFrameDuration( + types::LeAudioCoreCodecConfig::GetFrameDurationUs(fd_bit)), }; vec.push_back(config); } @@ -415,16 +409,17 @@ static void fillRemotePacsCapabitiliesToBtLeAudioCodecConfig( } } -std::vector -GetRemoteBtLeAudioCodecConfigFromPac( - const types::PublishedAudioCapabilities& group_pacs) { +std::vector GetRemoteBtLeAudioCodecConfigFromPac( + const types::PublishedAudioCapabilities& group_pacs) { std::vector vec; for (auto& [handles, pacs_record] : group_pacs) { for (auto& pac : pacs_record) { - if (!is_known_codec(pac.codec_id)) continue; + if (!is_known_codec(pac.codec_id)) { + continue; + } - fillRemotePacsCapabitiliesToBtLeAudioCodecConfig(pac, vec); + fillRemotePacsCapabilitiesToBtLeAudioCodecConfig(pac, vec); } } return vec; @@ -439,9 +434,8 @@ bool IsCodecUsingLtvFormat(const types::LeAudioCodecId& codec_id) { ::bluetooth::le_audio::LeAudioCodecConfiguration GetAudioSessionCodecConfigFromAudioSetConfiguration( - const bluetooth::le_audio::set_configurations::AudioSetConfiguration& - audio_set_conf, - uint8_t remote_direction) { + const bluetooth::le_audio::set_configurations::AudioSetConfiguration& audio_set_conf, + uint8_t remote_direction) { /* Note: For now we expect that each ASE in a particular direction needs * exactly the same audio codec parameters. */ @@ -451,9 +445,9 @@ GetAudioSessionCodecConfigFromAudioSetConfiguration( if (group_config.sample_rate != 0 && conf.codec.GetSamplingFrequencyHz() != group_config.sample_rate) { log::warn( - "Stream configuration could not be determined (multiple, different " - "sampling frequencies) for remote_direction: {:#x}", - remote_direction); + "Stream configuration could not be determined (multiple, different " + "sampling frequencies) for remote_direction: {:#x}", + remote_direction); break; } group_config.sample_rate = conf.codec.GetSamplingFrequencyHz(); @@ -461,9 +455,9 @@ GetAudioSessionCodecConfigFromAudioSetConfiguration( if (group_config.data_interval_us != 0 && conf.codec.GetDataIntervalUs() != group_config.data_interval_us) { log::warn( - "Stream configuration could not be determined (multiple, different " - "data intervals) for remote_direction: {:#x}", - remote_direction); + "Stream configuration could not be determined (multiple, different " + "data intervals) for remote_direction: {:#x}", + remote_direction); break; } group_config.data_interval_us = conf.codec.GetDataIntervalUs(); @@ -471,22 +465,24 @@ GetAudioSessionCodecConfigFromAudioSetConfiguration( if (group_config.bits_per_sample != 0 && conf.codec.GetBitsPerSample() != group_config.bits_per_sample) { log::warn( - "Stream configuration could not be determined (multiple, different " - "bits per sample) for remote_direction: {:#x}", - remote_direction); + "Stream configuration could not be determined (multiple, different " + "bits per sample) for remote_direction: {:#x}", + remote_direction); break; } group_config.bits_per_sample = conf.codec.GetBitsPerSample(); group_config.num_channels += conf.codec.GetChannelCountPerIsoStream(); } - if (group_config.num_channels > 2) group_config.num_channels = 2; + if (group_config.num_channels > 2) { + group_config.num_channels = 2; + } return group_config; } types::LeAudioConfigurationStrategy GetStrategyForAseConfig( - const std::vector& cfgs, - uint8_t device_cnt) { + const std::vector& cfgs, + uint8_t device_cnt) { if (cfgs.size() == 0) { return types::LeAudioConfigurationStrategy::RFU; } @@ -517,8 +513,7 @@ types::LeAudioConfigurationStrategy GetStrategyForAseConfig( } static bool IsCodecConfigSupported(const types::LeAudioLtvMap& pacs, - const types::LeAudioLtvMap& reqs, - uint8_t channel_cnt_per_ase) { + const types::LeAudioLtvMap& reqs, uint8_t channel_cnt_per_ase) { auto caps = pacs.GetAsCoreCodecCapabilities(); auto config = reqs.GetAsCoreCodecConfig(); @@ -527,10 +522,8 @@ static bool IsCodecConfigSupported(const types::LeAudioLtvMap& pacs, log::debug("Missing supported sampling frequencies capability"); return false; } - if (!caps.IsSamplingFrequencyConfigSupported( - config.sampling_frequency.value())) { - log::debug("Cfg: SamplingFrequency= {:#x}", - config.sampling_frequency.value()); + if (!caps.IsSamplingFrequencyConfigSupported(config.sampling_frequency.value())) { + log::debug("Cfg: SamplingFrequency= {:#x}", config.sampling_frequency.value()); log::debug("Cap: SupportedSamplingFrequencies= {:#x}", caps.supported_sampling_frequencies.value()); log::debug("Sampling frequency not supported"); @@ -553,26 +546,20 @@ static bool IsCodecConfigSupported(const types::LeAudioLtvMap& pacs, } if (!caps.IsFrameDurationConfigSupported(config.frame_duration.value())) { log::debug("Cfg: FrameDuration= {:#x}", config.frame_duration.value()); - log::debug("Cap: SupportedFrameDurations= {:#x}", - caps.supported_frame_durations.value()); + log::debug("Cap: SupportedFrameDurations= {:#x}", caps.supported_frame_durations.value()); log::debug("Frame duration not supported"); return false; } /* Octets per frame */ - if (!caps.HasSupportedOctetsPerCodecFrame() || - !config.octets_per_codec_frame) { + if (!caps.HasSupportedOctetsPerCodecFrame() || !config.octets_per_codec_frame) { log::debug("Missing supported octets per codec frame"); return false; } - if (!caps.IsOctetsPerCodecFrameConfigSupported( - config.octets_per_codec_frame.value())) { - log::debug("Cfg: Octets per frame={}", - config.octets_per_codec_frame.value()); - log::debug("Cap: Min octets per frame={}", - caps.supported_min_octets_per_codec_frame.value()); - log::debug("Cap: Max octets per frame={}", - caps.supported_max_octets_per_codec_frame.value()); + if (!caps.IsOctetsPerCodecFrameConfigSupported(config.octets_per_codec_frame.value())) { + log::debug("Cfg: Octets per frame={}", config.octets_per_codec_frame.value()); + log::debug("Cap: Min octets per frame={}", caps.supported_min_octets_per_codec_frame.value()); + log::debug("Cap: Max octets per frame={}", caps.supported_max_octets_per_codec_frame.value()); log::debug("Octets per codec frame outside the capabilities"); return false; } @@ -581,38 +568,40 @@ static bool IsCodecConfigSupported(const types::LeAudioLtvMap& pacs, } static bool IsCodecConfigSettingSupported( - const types::acs_ac_record& pac, - const set_configurations::CodecConfigSetting& codec_config_setting) { + const types::acs_ac_record& pac, + const set_configurations::CodecConfigSetting& codec_config_setting) { const auto& codec_id = codec_config_setting.id; - if (codec_id != pac.codec_id) return false; + if (codec_id != pac.codec_id) { + return false; + } log::debug(": Settings for format: 0x{:#02x} ", codec_id.coding_format); if (utils::IsCodecUsingLtvFormat(codec_id)) { - log::assert_that( - !pac.codec_spec_caps.IsEmpty(), - "Codec specific capabilities are not parsed approprietly."); - return IsCodecConfigSupported( - pac.codec_spec_caps, codec_config_setting.params, - codec_config_setting.GetChannelCountPerIsoStream()); + log::assert_that(!pac.codec_spec_caps.IsEmpty(), + "Codec specific capabilities are not parsed appropriately."); + return IsCodecConfigSupported(pac.codec_spec_caps, codec_config_setting.params, + codec_config_setting.GetChannelCountPerIsoStream()); } - log::error("Codec {}, seems to be not supported here.", - bluetooth::common::ToString(codec_id)); + log::error("Codec {}, seems to be not supported here.", bluetooth::common::ToString(codec_id)); return false; } const struct types::acs_ac_record* GetConfigurationSupportedPac( - const types::PublishedAudioCapabilities& pacs, - const set_configurations::CodecConfigSetting& codec_config_setting) { + const types::PublishedAudioCapabilities& pacs, + const set_configurations::CodecConfigSetting& codec_config_setting) { for (const auto& pac_tuple : pacs) { for (const auto& pac : std::get<1>(pac_tuple)) { - if (utils::IsCodecConfigSettingSupported(pac, codec_config_setting)) + if (utils::IsCodecConfigSettingSupported(pac, codec_config_setting)) { return &pac; + } }; } /* Doesn't match required configuration with any PAC */ - if (pacs.size() == 0) log::error("No PAC records"); + if (pacs.size() == 0) { + log::error("No PAC records"); + } return nullptr; } } // namespace utils diff --git a/system/bta/le_audio/le_audio_utils.h b/system/bta/le_audio/le_audio_utils.h index 6307c8cbdd9..4ea21a784f9 100644 --- a/system/bta/le_audio/le_audio_utils.h +++ b/system/bta/le_audio/le_audio_utils.h @@ -32,12 +32,12 @@ namespace bluetooth::le_audio { namespace utils { -types::LeAudioContextType AudioContentToLeAudioContext( - audio_content_type_t content_type, audio_usage_t usage); +types::LeAudioContextType AudioContentToLeAudioContext(audio_content_type_t content_type, + audio_usage_t usage); types::AudioContexts GetAudioContextsFromSourceMetadata( - const std::vector& source_metadata); + const std::vector& source_metadata); types::AudioContexts GetAudioContextsFromSinkMetadata( - const std::vector& sink_metadata); + const std::vector& sink_metadata); inline uint8_t GetTargetLatencyForAudioContext(types::LeAudioContextType ctx) { switch (ctx) { case types::LeAudioContextType::GAME: @@ -59,36 +59,33 @@ inline uint8_t GetTargetLatencyForAudioContext(types::LeAudioContextType ctx) { } /* Helpers to get btle_audio_codec_config_t for Java */ -bluetooth::le_audio::btle_audio_codec_index_t -translateBluetoothCodecFormatToCodecType(uint8_t codec_format); +bluetooth::le_audio::btle_audio_codec_index_t translateBluetoothCodecFormatToCodecType( + uint8_t codec_format); -bluetooth::le_audio::btle_audio_sample_rate_index_t -translateToBtLeAudioCodecConfigSampleRate(uint32_t sample_rate_capa); -bluetooth::le_audio::btle_audio_bits_per_sample_index_t -translateToBtLeAudioCodecConfigBitPerSample(uint8_t bits_per_sample); -bluetooth::le_audio::btle_audio_channel_count_index_t -translateToBtLeAudioCodecConfigChannelCount(uint8_t channel_count); -bluetooth::le_audio::btle_audio_frame_duration_index_t -translateToBtLeAudioCodecConfigFrameDuration(int frame_duration); +bluetooth::le_audio::btle_audio_sample_rate_index_t translateToBtLeAudioCodecConfigSampleRate( + uint32_t sample_rate_capa); +bluetooth::le_audio::btle_audio_bits_per_sample_index_t translateToBtLeAudioCodecConfigBitPerSample( + uint8_t bits_per_sample); +bluetooth::le_audio::btle_audio_channel_count_index_t translateToBtLeAudioCodecConfigChannelCount( + uint8_t channel_count); +bluetooth::le_audio::btle_audio_frame_duration_index_t translateToBtLeAudioCodecConfigFrameDuration( + int frame_duration); void fillStreamParamsToBtLeAudioCodecConfig( - const std::vector& confs, - bluetooth::le_audio::btle_audio_codec_config_t& out_config); + const std::vector& confs, + bluetooth::le_audio::btle_audio_codec_config_t& out_config); -std::vector -GetRemoteBtLeAudioCodecConfigFromPac( - const types::PublishedAudioCapabilities& group_pacs); +std::vector GetRemoteBtLeAudioCodecConfigFromPac( + const types::PublishedAudioCapabilities& group_pacs); bool IsCodecUsingLtvFormat(const types::LeAudioCodecId& codec_id); types::LeAudioConfigurationStrategy GetStrategyForAseConfig( - const std::vector& cfgs, - uint8_t device_cnt); + const std::vector& cfgs, + uint8_t device_cnt); ::bluetooth::le_audio::LeAudioCodecConfiguration GetAudioSessionCodecConfigFromAudioSetConfiguration( - const ::bluetooth::le_audio::set_configurations::AudioSetConfiguration& - audio_set_conf, - uint8_t remote_direction); + const ::bluetooth::le_audio::set_configurations::AudioSetConfiguration& audio_set_conf, + uint8_t remote_direction); const struct types::acs_ac_record* GetConfigurationSupportedPac( - const ::bluetooth::le_audio::types::PublishedAudioCapabilities& pacs, - const ::bluetooth::le_audio::set_configurations::CodecConfigSetting& - codec_config_setting); + const ::bluetooth::le_audio::types::PublishedAudioCapabilities& pacs, + const ::bluetooth::le_audio::set_configurations::CodecConfigSetting& codec_config_setting); } // namespace utils } // namespace bluetooth::le_audio diff --git a/system/bta/le_audio/metrics_collector.cc b/system/bta/le_audio/metrics_collector.cc index 3b0c92ddc67..74bd85f1923 100644 --- a/system/bta/le_audio/metrics_collector.cc +++ b/system/bta/le_audio/metrics_collector.cc @@ -37,33 +37,23 @@ inline int64_t get_timedelta_nanos(const metrics::ClockTimePoint& t1, if (t1 == kInvalidTimePoint || t2 == kInvalidTimePoint) { return -1; } - return std::abs( - std::chrono::duration_cast(t1 - t2).count()); + return std::abs(std::chrono::duration_cast(t1 - t2).count()); } -const static std::unordered_map - kContextTypeTable = { +const static std::unordered_map kContextTypeTable = { {LeAudioContextType::UNINITIALIZED, LeAudioMetricsContextType::INVALID}, - {LeAudioContextType::UNSPECIFIED, - LeAudioMetricsContextType::UNSPECIFIED}, - {LeAudioContextType::CONVERSATIONAL, - LeAudioMetricsContextType::COMMUNICATION}, + {LeAudioContextType::UNSPECIFIED, LeAudioMetricsContextType::UNSPECIFIED}, + {LeAudioContextType::CONVERSATIONAL, LeAudioMetricsContextType::COMMUNICATION}, {LeAudioContextType::MEDIA, LeAudioMetricsContextType::MEDIA}, {LeAudioContextType::GAME, LeAudioMetricsContextType::GAME}, - {LeAudioContextType::INSTRUCTIONAL, - LeAudioMetricsContextType::INSTRUCTIONAL}, - {LeAudioContextType::VOICEASSISTANTS, - LeAudioMetricsContextType::MAN_MACHINE}, + {LeAudioContextType::INSTRUCTIONAL, LeAudioMetricsContextType::INSTRUCTIONAL}, + {LeAudioContextType::VOICEASSISTANTS, LeAudioMetricsContextType::MAN_MACHINE}, {LeAudioContextType::LIVE, LeAudioMetricsContextType::LIVE}, - {LeAudioContextType::SOUNDEFFECTS, - LeAudioMetricsContextType::ATTENTION_SEEKING}, - {LeAudioContextType::NOTIFICATIONS, - LeAudioMetricsContextType::ATTENTION_SEEKING}, + {LeAudioContextType::SOUNDEFFECTS, LeAudioMetricsContextType::ATTENTION_SEEKING}, + {LeAudioContextType::NOTIFICATIONS, LeAudioMetricsContextType::ATTENTION_SEEKING}, {LeAudioContextType::RINGTONE, LeAudioMetricsContextType::RINGTONE}, - {LeAudioContextType::ALERTS, - LeAudioMetricsContextType::IMMEDIATE_ALERT}, - {LeAudioContextType::EMERGENCYALARM, - LeAudioMetricsContextType::EMERGENCY_ALERT}, + {LeAudioContextType::ALERTS, LeAudioMetricsContextType::IMMEDIATE_ALERT}, + {LeAudioContextType::EMERGENCYALARM, LeAudioMetricsContextType::EMERGENCY_ALERT}, {LeAudioContextType::RFU, LeAudioMetricsContextType::RFU}, }; @@ -76,7 +66,7 @@ inline int32_t to_atom_context_type(const LeAudioContextType stack_type) { } class DeviceMetrics { - public: +public: RawAddress address_; metrics::ClockTimePoint connecting_timepoint_ = kInvalidTimePoint; metrics::ClockTimePoint connected_timepoint_ = kInvalidTimePoint; @@ -107,7 +97,7 @@ class DeviceMetrics { }; class GroupMetricsImpl : public GroupMetrics { - private: +private: static constexpr int32_t kInvalidGroupId = -1; int32_t group_id_; int32_t group_size_; @@ -118,7 +108,7 @@ class GroupMetricsImpl : public GroupMetrics { std::vector streaming_duration_nanos_; std::vector streaming_context_type_; - public: +public: GroupMetricsImpl() : group_id_(kInvalidGroupId), group_size_(0) { beginning_timepoint_ = std::chrono::high_resolution_clock::now(); } @@ -127,8 +117,7 @@ class GroupMetricsImpl : public GroupMetrics { beginning_timepoint_ = std::chrono::high_resolution_clock::now(); } - void AddStateChangedEvent(const RawAddress& address, - bluetooth::le_audio::ConnectionState state, + void AddStateChangedEvent(const RawAddress& address, bluetooth::le_audio::ConnectionState state, ConnectionStatus status) override { auto it = opened_devices_.find(address); if (it == opened_devices_.end()) { @@ -144,35 +133,30 @@ class GroupMetricsImpl : public GroupMetrics { } } - void AddStreamStartedEvent( - bluetooth::le_audio::types::LeAudioContextType context_type) override { + void AddStreamStartedEvent(bluetooth::le_audio::types::LeAudioContextType context_type) override { int32_t atom_context_type = to_atom_context_type(context_type); // Make sure events aligned - if (streaming_offset_nanos_.size() - streaming_duration_nanos_.size() != - 0) { + if (streaming_offset_nanos_.size() - streaming_duration_nanos_.size() != 0) { // Allow type switching - if (!streaming_context_type_.empty() && - streaming_context_type_.back() != atom_context_type) { + if (!streaming_context_type_.empty() && streaming_context_type_.back() != atom_context_type) { AddStreamEndedEvent(); } else { return; } } - streaming_offset_nanos_.push_back(get_timedelta_nanos( - std::chrono::high_resolution_clock::now(), beginning_timepoint_)); + streaming_offset_nanos_.push_back( + get_timedelta_nanos(std::chrono::high_resolution_clock::now(), beginning_timepoint_)); streaming_context_type_.push_back(atom_context_type); } void AddStreamEndedEvent() override { // Make sure events aligned - if (streaming_offset_nanos_.size() - streaming_duration_nanos_.size() != - 1) { + if (streaming_offset_nanos_.size() - streaming_duration_nanos_.size() != 1) { return; } streaming_duration_nanos_.push_back( - get_timedelta_nanos(std::chrono::high_resolution_clock::now(), - beginning_timepoint_) - - streaming_offset_nanos_.back()); + get_timedelta_nanos(std::chrono::high_resolution_clock::now(), beginning_timepoint_) - + streaming_offset_nanos_.back()); } void SetGroupSize(int32_t group_size) override { group_size_ = group_size; } @@ -180,8 +164,8 @@ class GroupMetricsImpl : public GroupMetrics { bool IsClosed() override { return opened_devices_.empty(); } void WriteStats() override { - int64_t connection_duration_nanos = get_timedelta_nanos( - beginning_timepoint_, std::chrono::high_resolution_clock::now()); + int64_t connection_duration_nanos = + get_timedelta_nanos(beginning_timepoint_, std::chrono::high_resolution_clock::now()); int len = device_metrics_.size(); std::vector device_connecting_offset_nanos(len); @@ -197,31 +181,28 @@ class GroupMetricsImpl : public GroupMetrics { for (int i = 0; i < len; i++) { auto device_metric = device_metrics_[i].get(); - device_connecting_offset_nanos[i] = get_timedelta_nanos( - device_metric->connecting_timepoint_, beginning_timepoint_); - device_connected_offset_nanos[i] = get_timedelta_nanos( - device_metric->connected_timepoint_, beginning_timepoint_); - device_connection_duration_nanos[i] = - get_timedelta_nanos(device_metric->disconnected_timepoint_, - device_metric->connected_timepoint_); + device_connecting_offset_nanos[i] = + get_timedelta_nanos(device_metric->connecting_timepoint_, beginning_timepoint_); + device_connected_offset_nanos[i] = + get_timedelta_nanos(device_metric->connected_timepoint_, beginning_timepoint_); + device_connection_duration_nanos[i] = get_timedelta_nanos( + device_metric->disconnected_timepoint_, device_metric->connected_timepoint_); device_connection_statuses[i] = device_metric->connection_status_; device_disconnection_statuses[i] = device_metric->disconnection_status_; device_address[i] = device_metric->address_; } bluetooth::common::LogLeAudioConnectionSessionReported( - group_size_, group_id_, connection_duration_nanos, - device_connecting_offset_nanos, device_connected_offset_nanos, - device_connection_duration_nanos, device_connection_statuses, - device_disconnection_statuses, device_address, streaming_offset_nanos_, - streaming_duration_nanos_, streaming_context_type_); + group_size_, group_id_, connection_duration_nanos, device_connecting_offset_nanos, + device_connected_offset_nanos, device_connection_duration_nanos, + device_connection_statuses, device_disconnection_statuses, device_address, + streaming_offset_nanos_, streaming_duration_nanos_, streaming_context_type_); } void Flush() { for (auto& p : opened_devices_) { - p.second->AddStateChangedEvent( - bluetooth::le_audio::ConnectionState::DISCONNECTED, - ConnectionStatus::SUCCESS); + p.second->AddStateChangedEvent(bluetooth::le_audio::ConnectionState::DISCONNECTED, + ConnectionStatus::SUCCESS); } WriteStats(); } @@ -244,18 +225,17 @@ void MetricsCollector::OnGroupSizeUpdate(int32_t group_id, int32_t group_size) { } } -void MetricsCollector::OnConnectionStateChanged( - int32_t group_id, const RawAddress& address, - bluetooth::le_audio::ConnectionState state, ConnectionStatus status) { +void MetricsCollector::OnConnectionStateChanged(int32_t group_id, const RawAddress& address, + bluetooth::le_audio::ConnectionState state, + ConnectionStatus status) { if (address.IsEmpty() || group_id <= 0) { return; } auto it = opened_groups_.find(group_id); if (it == opened_groups_.end()) { it = opened_groups_.insert( - std::begin(opened_groups_), - {group_id, std::make_unique( - group_id, group_size_table_[group_id])}); + std::begin(opened_groups_), + {group_id, std::make_unique(group_id, group_size_table_[group_id])}); } it->second->AddStateChangedEvent(address, state, status); @@ -266,9 +246,10 @@ void MetricsCollector::OnConnectionStateChanged( } void MetricsCollector::OnStreamStarted( - int32_t group_id, - bluetooth::le_audio::types::LeAudioContextType context_type) { - if (group_id <= 0) return; + int32_t group_id, bluetooth::le_audio::types::LeAudioContextType context_type) { + if (group_id <= 0) { + return; + } auto it = opened_groups_.find(group_id); if (it != opened_groups_.end()) { it->second->AddStreamStartedEvent(context_type); @@ -276,7 +257,9 @@ void MetricsCollector::OnStreamStarted( } void MetricsCollector::OnStreamEnded(int32_t group_id) { - if (group_id <= 0) return; + if (group_id <= 0) { + return; + } auto it = opened_groups_.find(group_id); if (it != opened_groups_.end()) { it->second->AddStreamEndedEvent(); @@ -287,10 +270,9 @@ void MetricsCollector::OnBroadcastStateChanged(bool started) { if (started) { broadcast_beginning_timepoint_ = std::chrono::high_resolution_clock::now(); } else { - auto broadcast_ending_timepoint_ = - std::chrono::high_resolution_clock::now(); - bluetooth::common::LogLeAudioBroadcastSessionReported(get_timedelta_nanos( - broadcast_beginning_timepoint_, broadcast_ending_timepoint_)); + auto broadcast_ending_timepoint_ = std::chrono::high_resolution_clock::now(); + bluetooth::common::LogLeAudioBroadcastSessionReported( + get_timedelta_nanos(broadcast_beginning_timepoint_, broadcast_ending_timepoint_)); broadcast_beginning_timepoint_ = kInvalidTimePoint; } } diff --git a/system/bta/le_audio/metrics_collector.h b/system/bta/le_audio/metrics_collector.h index a01cdc543cf..b7a3ea57840 100644 --- a/system/bta/le_audio/metrics_collector.h +++ b/system/bta/le_audio/metrics_collector.h @@ -29,8 +29,7 @@ namespace bluetooth::le_audio { namespace metrics { -using ClockTimePoint = - std::chrono::time_point; +using ClockTimePoint = std::chrono::time_point; } enum ConnectionStatus : int32_t { @@ -58,7 +57,7 @@ enum class LeAudioMetricsContextType : int32_t { }; class GroupMetrics { - public: +public: GroupMetrics() {} virtual ~GroupMetrics() {} @@ -68,7 +67,7 @@ class GroupMetrics { ConnectionStatus status) = 0; virtual void AddStreamStartedEvent( - bluetooth::le_audio::types::LeAudioContextType context_type) = 0; + bluetooth::le_audio::types::LeAudioContextType context_type) = 0; virtual void AddStreamEndedEvent() = 0; @@ -82,7 +81,7 @@ class GroupMetrics { }; class MetricsCollector { - public: +public: static MetricsCollector* Get(); /** @@ -112,9 +111,8 @@ class MetricsCollector { * * @param group_id Group ID of the associated stream. */ - void OnStreamStarted( - int32_t group_id, - bluetooth::le_audio::types::LeAudioContextType context_type); + void OnStreamStarted(int32_t group_id, + bluetooth::le_audio::types::LeAudioContextType context_type); /** * When there is a change in LE Audio stream started @@ -137,10 +135,10 @@ class MetricsCollector { */ void Flush(); - protected: +protected: MetricsCollector() {} - private: +private: static MetricsCollector* instance; std::unordered_map> opened_groups_; diff --git a/system/bta/le_audio/metrics_collector_linux.cc b/system/bta/le_audio/metrics_collector_linux.cc index 7ee0e643868..e505ce0e1ac 100644 --- a/system/bta/le_audio/metrics_collector_linux.cc +++ b/system/bta/le_audio/metrics_collector_linux.cc @@ -28,16 +28,14 @@ MetricsCollector* MetricsCollector::Get() { return MetricsCollector::instance; } -void MetricsCollector::OnGroupSizeUpdate(int32_t group_id, int32_t group_size) { -} +void MetricsCollector::OnGroupSizeUpdate(int32_t group_id, int32_t group_size) {} -void MetricsCollector::OnConnectionStateChanged( - int32_t group_id, const RawAddress& address, - bluetooth::le_audio::ConnectionState state, ConnectionStatus status) {} +void MetricsCollector::OnConnectionStateChanged(int32_t group_id, const RawAddress& address, + bluetooth::le_audio::ConnectionState state, + ConnectionStatus status) {} void MetricsCollector::OnStreamStarted( - int32_t group_id, - bluetooth::le_audio::types::LeAudioContextType context_type) {} + int32_t group_id, bluetooth::le_audio::types::LeAudioContextType context_type) {} void MetricsCollector::OnStreamEnded(int32_t group_id) {} diff --git a/system/bta/le_audio/metrics_collector_test.cc b/system/bta/le_audio/metrics_collector_test.cc index 6e3a679c9d0..b519420fc06 100644 --- a/system/bta/le_audio/metrics_collector_test.cc +++ b/system/bta/le_audio/metrics_collector_test.cc @@ -58,18 +58,17 @@ std::vector last_streaming_context_type; namespace bluetooth { namespace common { -void LogLeAudioConnectionSessionReported( - int32_t group_size, int32_t group_metric_id, - int64_t connection_duration_nanos, - std::vector& device_connecting_offset_nanos, - std::vector& device_connected_offset_nanos, - std::vector& device_connection_duration_nanos, - std::vector& device_connection_status, - std::vector& device_disconnection_status, - std::vector& device_address, - std::vector& streaming_offset_nanos, - std::vector& streaming_duration_nanos, - std::vector& streaming_context_type) { +void LogLeAudioConnectionSessionReported(int32_t group_size, int32_t group_metric_id, + int64_t connection_duration_nanos, + std::vector& device_connecting_offset_nanos, + std::vector& device_connected_offset_nanos, + std::vector& device_connection_duration_nanos, + std::vector& device_connection_status, + std::vector& device_disconnection_status, + std::vector& device_address, + std::vector& streaming_offset_nanos, + std::vector& streaming_duration_nanos, + std::vector& streaming_context_type) { log_count++; last_group_size = group_size; last_group_metric_id = group_metric_id; @@ -102,12 +101,12 @@ const RawAddress device2 = RawAddress({0x11, 0x22, 0x33, 0x44, 0x55, 0x67}); const RawAddress device3 = RawAddress({0x11, 0x22, 0x33, 0x44, 0x55, 0x68}); class MockMetricsCollector : public MetricsCollector { - public: +public: MockMetricsCollector() {} }; class MetricsCollectorTest : public Test { - protected: +protected: std::unique_ptr collector; void SetUp() override { @@ -135,12 +134,12 @@ class MetricsCollectorTest : public Test { TEST_F(MetricsCollectorTest, Initialize) { ASSERT_EQ(log_count, 0); } TEST_F(MetricsCollectorTest, ConnectionFailed) { - collector->OnConnectionStateChanged( - group_id1, device1, bluetooth::le_audio::ConnectionState::CONNECTING, - ConnectionStatus::UNKNOWN); - collector->OnConnectionStateChanged( - group_id1, device1, bluetooth::le_audio::ConnectionState::CONNECTED, - ConnectionStatus::FAILED); + collector->OnConnectionStateChanged(group_id1, device1, + bluetooth::le_audio::ConnectionState::CONNECTING, + ConnectionStatus::UNKNOWN); + collector->OnConnectionStateChanged(group_id1, device1, + bluetooth::le_audio::ConnectionState::CONNECTED, + ConnectionStatus::FAILED); ASSERT_EQ(log_count, 1); ASSERT_EQ(last_group_metric_id, group_id1); @@ -150,15 +149,15 @@ TEST_F(MetricsCollectorTest, ConnectionFailed) { } TEST_F(MetricsCollectorTest, ConnectingConnectedDisconnected) { - collector->OnConnectionStateChanged( - group_id1, device1, bluetooth::le_audio::ConnectionState::CONNECTING, - ConnectionStatus::UNKNOWN); - collector->OnConnectionStateChanged( - group_id1, device1, bluetooth::le_audio::ConnectionState::CONNECTED, - ConnectionStatus::SUCCESS); - collector->OnConnectionStateChanged( - group_id1, device1, bluetooth::le_audio::ConnectionState::DISCONNECTED, - ConnectionStatus::SUCCESS); + collector->OnConnectionStateChanged(group_id1, device1, + bluetooth::le_audio::ConnectionState::CONNECTING, + ConnectionStatus::UNKNOWN); + collector->OnConnectionStateChanged(group_id1, device1, + bluetooth::le_audio::ConnectionState::CONNECTED, + ConnectionStatus::SUCCESS); + collector->OnConnectionStateChanged(group_id1, device1, + bluetooth::le_audio::ConnectionState::DISCONNECTED, + ConnectionStatus::SUCCESS); ASSERT_EQ(log_count, 1); ASSERT_EQ(last_group_metric_id, group_id1); @@ -173,15 +172,15 @@ TEST_F(MetricsCollectorTest, ConnectingConnectedDisconnected) { } TEST_F(MetricsCollectorTest, SingleDeviceTwoConnections) { - collector->OnConnectionStateChanged( - group_id1, device1, bluetooth::le_audio::ConnectionState::CONNECTING, - ConnectionStatus::UNKNOWN); - collector->OnConnectionStateChanged( - group_id1, device1, bluetooth::le_audio::ConnectionState::CONNECTED, - ConnectionStatus::SUCCESS); - collector->OnConnectionStateChanged( - group_id1, device1, bluetooth::le_audio::ConnectionState::DISCONNECTED, - ConnectionStatus::SUCCESS); + collector->OnConnectionStateChanged(group_id1, device1, + bluetooth::le_audio::ConnectionState::CONNECTING, + ConnectionStatus::UNKNOWN); + collector->OnConnectionStateChanged(group_id1, device1, + bluetooth::le_audio::ConnectionState::CONNECTED, + ConnectionStatus::SUCCESS); + collector->OnConnectionStateChanged(group_id1, device1, + bluetooth::le_audio::ConnectionState::DISCONNECTED, + ConnectionStatus::SUCCESS); ASSERT_EQ(log_count, 1); ASSERT_EQ(last_group_metric_id, group_id1); @@ -194,15 +193,15 @@ TEST_F(MetricsCollectorTest, SingleDeviceTwoConnections) { ASSERT_EQ(last_device_connection_status.back(), ConnectionStatus::SUCCESS); ASSERT_EQ(last_device_disconnection_status.back(), ConnectionStatus::SUCCESS); - collector->OnConnectionStateChanged( - group_id1, device1, bluetooth::le_audio::ConnectionState::CONNECTING, - ConnectionStatus::UNKNOWN); - collector->OnConnectionStateChanged( - group_id1, device1, bluetooth::le_audio::ConnectionState::CONNECTED, - ConnectionStatus::SUCCESS); - collector->OnConnectionStateChanged( - group_id1, device1, bluetooth::le_audio::ConnectionState::DISCONNECTED, - ConnectionStatus::SUCCESS); + collector->OnConnectionStateChanged(group_id1, device1, + bluetooth::le_audio::ConnectionState::CONNECTING, + ConnectionStatus::UNKNOWN); + collector->OnConnectionStateChanged(group_id1, device1, + bluetooth::le_audio::ConnectionState::CONNECTED, + ConnectionStatus::SUCCESS); + collector->OnConnectionStateChanged(group_id1, device1, + bluetooth::le_audio::ConnectionState::DISCONNECTED, + ConnectionStatus::SUCCESS); ASSERT_EQ(log_count, 2); ASSERT_EQ(last_group_metric_id, group_id1); @@ -217,21 +216,21 @@ TEST_F(MetricsCollectorTest, SingleDeviceTwoConnections) { } TEST_F(MetricsCollectorTest, StereoGroupBasicTest) { - collector->OnConnectionStateChanged( - group_id2, device2, bluetooth::le_audio::ConnectionState::CONNECTING, - ConnectionStatus::UNKNOWN); - collector->OnConnectionStateChanged( - group_id2, device2, bluetooth::le_audio::ConnectionState::CONNECTED, - ConnectionStatus::SUCCESS); - collector->OnConnectionStateChanged( - group_id2, device3, bluetooth::le_audio::ConnectionState::CONNECTED, - ConnectionStatus::SUCCESS); - collector->OnConnectionStateChanged( - group_id2, device3, bluetooth::le_audio::ConnectionState::DISCONNECTED, - ConnectionStatus::SUCCESS); - collector->OnConnectionStateChanged( - group_id2, device2, bluetooth::le_audio::ConnectionState::DISCONNECTED, - ConnectionStatus::SUCCESS); + collector->OnConnectionStateChanged(group_id2, device2, + bluetooth::le_audio::ConnectionState::CONNECTING, + ConnectionStatus::UNKNOWN); + collector->OnConnectionStateChanged(group_id2, device2, + bluetooth::le_audio::ConnectionState::CONNECTED, + ConnectionStatus::SUCCESS); + collector->OnConnectionStateChanged(group_id2, device3, + bluetooth::le_audio::ConnectionState::CONNECTED, + ConnectionStatus::SUCCESS); + collector->OnConnectionStateChanged(group_id2, device3, + bluetooth::le_audio::ConnectionState::DISCONNECTED, + ConnectionStatus::SUCCESS); + collector->OnConnectionStateChanged(group_id2, device2, + bluetooth::le_audio::ConnectionState::DISCONNECTED, + ConnectionStatus::SUCCESS); ASSERT_EQ(log_count, 1); ASSERT_EQ(last_group_metric_id, group_id2); @@ -244,27 +243,27 @@ TEST_F(MetricsCollectorTest, StereoGroupBasicTest) { } TEST_F(MetricsCollectorTest, StereoGroupMultiReconnections) { - collector->OnConnectionStateChanged( - group_id2, device2, bluetooth::le_audio::ConnectionState::CONNECTING, - ConnectionStatus::UNKNOWN); - collector->OnConnectionStateChanged( - group_id2, device2, bluetooth::le_audio::ConnectionState::CONNECTED, - ConnectionStatus::SUCCESS); - collector->OnConnectionStateChanged( - group_id2, device3, bluetooth::le_audio::ConnectionState::CONNECTED, - ConnectionStatus::SUCCESS); - collector->OnConnectionStateChanged( - group_id2, device3, bluetooth::le_audio::ConnectionState::DISCONNECTED, - ConnectionStatus::SUCCESS); - collector->OnConnectionStateChanged( - group_id2, device3, bluetooth::le_audio::ConnectionState::CONNECTED, - ConnectionStatus::SUCCESS); - collector->OnConnectionStateChanged( - group_id2, device3, bluetooth::le_audio::ConnectionState::DISCONNECTED, - ConnectionStatus::SUCCESS); - collector->OnConnectionStateChanged( - group_id2, device2, bluetooth::le_audio::ConnectionState::DISCONNECTED, - ConnectionStatus::SUCCESS); + collector->OnConnectionStateChanged(group_id2, device2, + bluetooth::le_audio::ConnectionState::CONNECTING, + ConnectionStatus::UNKNOWN); + collector->OnConnectionStateChanged(group_id2, device2, + bluetooth::le_audio::ConnectionState::CONNECTED, + ConnectionStatus::SUCCESS); + collector->OnConnectionStateChanged(group_id2, device3, + bluetooth::le_audio::ConnectionState::CONNECTED, + ConnectionStatus::SUCCESS); + collector->OnConnectionStateChanged(group_id2, device3, + bluetooth::le_audio::ConnectionState::DISCONNECTED, + ConnectionStatus::SUCCESS); + collector->OnConnectionStateChanged(group_id2, device3, + bluetooth::le_audio::ConnectionState::CONNECTED, + ConnectionStatus::SUCCESS); + collector->OnConnectionStateChanged(group_id2, device3, + bluetooth::le_audio::ConnectionState::DISCONNECTED, + ConnectionStatus::SUCCESS); + collector->OnConnectionStateChanged(group_id2, device2, + bluetooth::le_audio::ConnectionState::DISCONNECTED, + ConnectionStatus::SUCCESS); ASSERT_EQ(log_count, 1); ASSERT_EQ(last_group_metric_id, group_id2); @@ -277,27 +276,27 @@ TEST_F(MetricsCollectorTest, StereoGroupMultiReconnections) { } TEST_F(MetricsCollectorTest, MixGroups) { - collector->OnConnectionStateChanged( - group_id1, device1, bluetooth::le_audio::ConnectionState::CONNECTING, - ConnectionStatus::UNKNOWN); - collector->OnConnectionStateChanged( - group_id1, device1, bluetooth::le_audio::ConnectionState::CONNECTED, - ConnectionStatus::SUCCESS); - collector->OnConnectionStateChanged( - group_id2, device2, bluetooth::le_audio::ConnectionState::CONNECTING, - ConnectionStatus::UNKNOWN); - collector->OnConnectionStateChanged( - group_id2, device2, bluetooth::le_audio::ConnectionState::CONNECTED, - ConnectionStatus::SUCCESS); - collector->OnConnectionStateChanged( - group_id2, device3, bluetooth::le_audio::ConnectionState::CONNECTED, - ConnectionStatus::SUCCESS); - collector->OnConnectionStateChanged( - group_id2, device3, bluetooth::le_audio::ConnectionState::DISCONNECTED, - ConnectionStatus::SUCCESS); - collector->OnConnectionStateChanged( - group_id2, device2, bluetooth::le_audio::ConnectionState::DISCONNECTED, - ConnectionStatus::SUCCESS); + collector->OnConnectionStateChanged(group_id1, device1, + bluetooth::le_audio::ConnectionState::CONNECTING, + ConnectionStatus::UNKNOWN); + collector->OnConnectionStateChanged(group_id1, device1, + bluetooth::le_audio::ConnectionState::CONNECTED, + ConnectionStatus::SUCCESS); + collector->OnConnectionStateChanged(group_id2, device2, + bluetooth::le_audio::ConnectionState::CONNECTING, + ConnectionStatus::UNKNOWN); + collector->OnConnectionStateChanged(group_id2, device2, + bluetooth::le_audio::ConnectionState::CONNECTED, + ConnectionStatus::SUCCESS); + collector->OnConnectionStateChanged(group_id2, device3, + bluetooth::le_audio::ConnectionState::CONNECTED, + ConnectionStatus::SUCCESS); + collector->OnConnectionStateChanged(group_id2, device3, + bluetooth::le_audio::ConnectionState::DISCONNECTED, + ConnectionStatus::SUCCESS); + collector->OnConnectionStateChanged(group_id2, device2, + bluetooth::le_audio::ConnectionState::DISCONNECTED, + ConnectionStatus::SUCCESS); ASSERT_EQ(log_count, 1); ASSERT_EQ(last_group_metric_id, group_id2); @@ -308,9 +307,9 @@ TEST_F(MetricsCollectorTest, MixGroups) { ASSERT_EQ(last_device_connected_offset_nanos.size(), 2UL); ASSERT_EQ(last_device_connection_duration_nanos.size(), 2UL); - collector->OnConnectionStateChanged( - group_id1, device1, bluetooth::le_audio::ConnectionState::DISCONNECTED, - ConnectionStatus::SUCCESS); + collector->OnConnectionStateChanged(group_id1, device1, + bluetooth::le_audio::ConnectionState::DISCONNECTED, + ConnectionStatus::SUCCESS); ASSERT_EQ(log_count, 2); ASSERT_EQ(last_group_metric_id, group_id1); @@ -325,15 +324,15 @@ TEST_F(MetricsCollectorTest, MixGroups) { TEST_F(MetricsCollectorTest, GroupSizeUpdated) { collector->OnGroupSizeUpdate(group_id2, 1); collector->OnGroupSizeUpdate(group_id1, 2); - collector->OnConnectionStateChanged( - group_id1, device1, bluetooth::le_audio::ConnectionState::CONNECTING, - ConnectionStatus::UNKNOWN); - collector->OnConnectionStateChanged( - group_id1, device1, bluetooth::le_audio::ConnectionState::CONNECTED, - ConnectionStatus::SUCCESS); - collector->OnConnectionStateChanged( - group_id1, device1, bluetooth::le_audio::ConnectionState::DISCONNECTED, - ConnectionStatus::SUCCESS); + collector->OnConnectionStateChanged(group_id1, device1, + bluetooth::le_audio::ConnectionState::CONNECTING, + ConnectionStatus::UNKNOWN); + collector->OnConnectionStateChanged(group_id1, device1, + bluetooth::le_audio::ConnectionState::CONNECTED, + ConnectionStatus::SUCCESS); + collector->OnConnectionStateChanged(group_id1, device1, + bluetooth::le_audio::ConnectionState::DISCONNECTED, + ConnectionStatus::SUCCESS); ASSERT_EQ(log_count, 1); ASSERT_EQ(last_group_metric_id, group_id1); @@ -341,22 +340,20 @@ TEST_F(MetricsCollectorTest, GroupSizeUpdated) { } TEST_F(MetricsCollectorTest, StreamingSessions) { - collector->OnConnectionStateChanged( - group_id1, device1, bluetooth::le_audio::ConnectionState::CONNECTING, - ConnectionStatus::UNKNOWN); - collector->OnConnectionStateChanged( - group_id1, device1, bluetooth::le_audio::ConnectionState::CONNECTED, - ConnectionStatus::SUCCESS); - collector->OnStreamStarted( - group_id1, bluetooth::le_audio::types::LeAudioContextType::MEDIA); + collector->OnConnectionStateChanged(group_id1, device1, + bluetooth::le_audio::ConnectionState::CONNECTING, + ConnectionStatus::UNKNOWN); + collector->OnConnectionStateChanged(group_id1, device1, + bluetooth::le_audio::ConnectionState::CONNECTED, + ConnectionStatus::SUCCESS); + collector->OnStreamStarted(group_id1, bluetooth::le_audio::types::LeAudioContextType::MEDIA); collector->OnStreamEnded(group_id1); - collector->OnStreamStarted( - group_id1, - bluetooth::le_audio::types::LeAudioContextType::CONVERSATIONAL); + collector->OnStreamStarted(group_id1, + bluetooth::le_audio::types::LeAudioContextType::CONVERSATIONAL); collector->OnStreamEnded(group_id1); - collector->OnConnectionStateChanged( - group_id1, device1, bluetooth::le_audio::ConnectionState::DISCONNECTED, - ConnectionStatus::SUCCESS); + collector->OnConnectionStateChanged(group_id1, device1, + bluetooth::le_audio::ConnectionState::DISCONNECTED, + ConnectionStatus::SUCCESS); ASSERT_EQ(log_count, 1); ASSERT_EQ(last_group_metric_id, group_id1); @@ -368,8 +365,7 @@ TEST_F(MetricsCollectorTest, StreamingSessions) { ASSERT_GT(last_streaming_offset_nanos[1], 0L); ASSERT_GT(last_streaming_duration_nanos[0], 0L); ASSERT_GT(last_streaming_duration_nanos[1], 0L); - ASSERT_EQ(last_streaming_context_type[0], - static_cast(LeAudioMetricsContextType::MEDIA)); + ASSERT_EQ(last_streaming_context_type[0], static_cast(LeAudioMetricsContextType::MEDIA)); ASSERT_EQ(last_streaming_context_type[1], static_cast(LeAudioMetricsContextType::COMMUNICATION)); } diff --git a/system/bta/le_audio/mock_codec_interface.cc b/system/bta/le_audio/mock_codec_interface.cc index 0c8af03767e..67c88d136d3 100644 --- a/system/bta/le_audio/mock_codec_interface.cc +++ b/system/bta/le_audio/mock_codec_interface.cc @@ -18,16 +18,13 @@ #include "le_audio/codec_interface.h" -static std::list> - mock_life_listener_list; +static std::list> mock_life_listener_list; namespace bluetooth::le_audio { struct CodecInterface::Impl : public MockCodecInterface { - public: - Impl(const types::LeAudioCodecId& codec_id) { - output_channel_data_.resize(1); - }; +public: + Impl(const types::LeAudioCodecId& codec_id) { output_channel_data_.resize(1); } ~Impl() = default; std::vector& GetDecodedSamples() { return output_channel_data_; } @@ -46,44 +43,33 @@ CodecInterface::~CodecInterface() { } delete impl; } -bool CodecInterface::IsReady() { return impl->IsReady(); }; -CodecInterface::Status CodecInterface::InitEncoder( - const LeAudioCodecConfiguration& pcm_config, - const LeAudioCodecConfiguration& codec_config) { +bool CodecInterface::IsReady() { return impl->IsReady(); } +CodecInterface::Status CodecInterface::InitEncoder(const LeAudioCodecConfiguration& pcm_config, + const LeAudioCodecConfiguration& codec_config) { return impl->InitEncoder(pcm_config, codec_config); } -CodecInterface::Status CodecInterface::InitDecoder( - const LeAudioCodecConfiguration& codec_config, - const LeAudioCodecConfiguration& pcm_config) { +CodecInterface::Status CodecInterface::InitDecoder(const LeAudioCodecConfiguration& codec_config, + const LeAudioCodecConfiguration& pcm_config) { return impl->InitDecoder(codec_config, pcm_config); } -std::vector& CodecInterface::GetDecodedSamples() { - return impl->GetDecodedSamples(); -} +std::vector& CodecInterface::GetDecodedSamples() { return impl->GetDecodedSamples(); } CodecInterface::Status CodecInterface::Decode(uint8_t* data, uint16_t size) { return impl->Decode(data, size); } -CodecInterface::Status CodecInterface::Encode(const uint8_t* data, int stride, - uint16_t out_size, +CodecInterface::Status CodecInterface::Encode(const uint8_t* data, int stride, uint16_t out_size, std::vector* out_buffer, uint16_t out_offset) { return impl->Encode(data, stride, out_size, out_buffer, out_offset); } void CodecInterface::Cleanup() { return impl->Cleanup(); } -uint16_t CodecInterface::GetNumOfSamplesPerChannel() { - return impl->GetNumOfSamplesPerChannel(); -}; -uint8_t CodecInterface::GetNumOfBytesPerSample() { - return impl->GetNumOfBytesPerSample(); -}; +uint16_t CodecInterface::GetNumOfSamplesPerChannel() { return impl->GetNumOfSamplesPerChannel(); } +uint8_t CodecInterface::GetNumOfBytesPerSample() { return impl->GetNumOfBytesPerSample(); } } // namespace bluetooth::le_audio void MockCodecInterface::RegisterMockInstanceHook( - std::function listener) { + std::function listener) { mock_life_listener_list.push_back(std::move(listener)); } -void MockCodecInterface::ClearMockInstanceHookList() { - mock_life_listener_list.clear(); -} +void MockCodecInterface::ClearMockInstanceHookList() { mock_life_listener_list.clear(); } diff --git a/system/bta/le_audio/mock_codec_interface.h b/system/bta/le_audio/mock_codec_interface.h index 2b3ecaa9585..a19059af161 100644 --- a/system/bta/le_audio/mock_codec_interface.h +++ b/system/bta/le_audio/mock_codec_interface.h @@ -23,9 +23,8 @@ #include "codec_interface.h" class MockCodecInterface { - public: - static void RegisterMockInstanceHook( - std::function); +public: + static void RegisterMockInstanceHook(std::function); static void ClearMockInstanceHookList(); MockCodecInterface() = default; @@ -34,19 +33,16 @@ class MockCodecInterface { virtual ~MockCodecInterface() = default; - MOCK_METHOD( - (bluetooth::le_audio::CodecInterface::Status), InitEncoder, - (const bluetooth::le_audio::LeAudioCodecConfiguration& pcm_config, - const bluetooth::le_audio::LeAudioCodecConfiguration& codec_config)); - MOCK_METHOD( - bluetooth::le_audio::CodecInterface::Status, InitDecoder, - (const bluetooth::le_audio::LeAudioCodecConfiguration& codec_config, - const bluetooth::le_audio::LeAudioCodecConfiguration& pcm_config)); + MOCK_METHOD((bluetooth::le_audio::CodecInterface::Status), InitEncoder, + (const bluetooth::le_audio::LeAudioCodecConfiguration& pcm_config, + const bluetooth::le_audio::LeAudioCodecConfiguration& codec_config)); + MOCK_METHOD(bluetooth::le_audio::CodecInterface::Status, InitDecoder, + (const bluetooth::le_audio::LeAudioCodecConfiguration& codec_config, + const bluetooth::le_audio::LeAudioCodecConfiguration& pcm_config)); MOCK_METHOD(bluetooth::le_audio::CodecInterface::Status, Encode, - (const uint8_t* data, int stride, uint16_t out_size, - std::vector* out_buffer, uint16_t out_offset)); - MOCK_METHOD(bluetooth::le_audio::CodecInterface::Status, Decode, - (uint8_t * data, uint16_t size)); + (const uint8_t* data, int stride, uint16_t out_size, std::vector* out_buffer, + uint16_t out_offset)); + MOCK_METHOD(bluetooth::le_audio::CodecInterface::Status, Decode, (uint8_t* data, uint16_t size)); MOCK_METHOD((void), Cleanup, ()); MOCK_METHOD((bool), IsReady, ()); MOCK_METHOD((uint16_t), GetNumOfSamplesPerChannel, ()); diff --git a/system/bta/le_audio/mock_codec_manager.cc b/system/bta/le_audio/mock_codec_manager.cc index 085c5bcea64..a3c476a252f 100644 --- a/system/bta/le_audio/mock_codec_manager.cc +++ b/system/bta/le_audio/mock_codec_manager.cc @@ -27,7 +27,7 @@ MockCodecManager* MockCodecManager::GetInstance() { namespace bluetooth::le_audio { struct CodecManager::impl : public MockCodecManager { - public: +public: impl() = default; ~impl() = default; }; @@ -35,7 +35,9 @@ struct CodecManager::impl : public MockCodecManager { CodecManager::CodecManager() {} types::CodecLocation CodecManager::GetCodecLocation() const { - if (!pimpl_) return types::CodecLocation::HOST; + if (!pimpl_) { + return types::CodecLocation::HOST; + } return pimpl_->GetCodecLocation(); } @@ -48,93 +50,95 @@ bool CodecManager::IsDualBiDirSwbSupported(void) const { } bool CodecManager::UpdateActiveUnicastAudioHalClient( - LeAudioSourceAudioHalClient* source_unicast_client, - LeAudioSinkAudioHalClient* sink_unicast_client, bool is_active) { + LeAudioSourceAudioHalClient* source_unicast_client, + LeAudioSinkAudioHalClient* sink_unicast_client, bool is_active) { if (pimpl_) { - return pimpl_->UpdateActiveUnicastAudioHalClient( - source_unicast_client, sink_unicast_client, is_active); + return pimpl_->UpdateActiveUnicastAudioHalClient(source_unicast_client, sink_unicast_client, + is_active); } return true; } bool CodecManager::UpdateActiveBroadcastAudioHalClient( - LeAudioSourceAudioHalClient* source_broadcast_client, bool is_active) { + LeAudioSourceAudioHalClient* source_broadcast_client, bool is_active) { if (pimpl_) { - return pimpl_->UpdateActiveBroadcastAudioHalClient(source_broadcast_client, - is_active); + return pimpl_->UpdateActiveBroadcastAudioHalClient(source_broadcast_client, is_active); } return true; } void CodecManager::UpdateActiveAudioConfig( - const types::BidirectionalPair& stream_params, - types::BidirectionalPair delays_ms, - std::function - update_receiver) { - if (pimpl_) - return pimpl_->UpdateActiveAudioConfig(stream_params, delays_ms, - update_receiver); -} - -std::unique_ptr -CodecManager::GetCodecConfig( - const CodecManager::UnicastConfigurationRequirements& requirements, - CodecManager::UnicastConfigurationVerifier verifier) { - if (!pimpl_) return nullptr; + const types::BidirectionalPair& stream_params, + types::BidirectionalPair delays_ms, + std::function + update_receiver) { + if (pimpl_) { + return pimpl_->UpdateActiveAudioConfig(stream_params, delays_ms, update_receiver); + } +} + +std::unique_ptr CodecManager::GetCodecConfig( + const CodecManager::UnicastConfigurationRequirements& requirements, + CodecManager::UnicastConfigurationVerifier verifier) { + if (!pimpl_) { + return nullptr; + } return pimpl_->GetCodecConfig(requirements, verifier); } std::unique_ptr<::bluetooth::le_audio::broadcaster::BroadcastConfiguration> CodecManager::GetBroadcastConfig( - const bluetooth::le_audio::CodecManager::BroadcastConfigurationRequirements& - requirements) const { - if (!pimpl_) - return std::unique_ptr< - bluetooth::le_audio::broadcaster::BroadcastConfiguration>(nullptr); + const bluetooth::le_audio::CodecManager::BroadcastConfigurationRequirements& requirements) + const { + if (!pimpl_) { + return std::unique_ptr(nullptr); + } return pimpl_->GetBroadcastConfig(requirements); } bool CodecManager::CheckCodecConfigIsBiDirSwb( - const bluetooth::le_audio::set_configurations::AudioSetConfiguration& - config) const { - if (!pimpl_) return false; + const bluetooth::le_audio::set_configurations::AudioSetConfiguration& config) const { + if (!pimpl_) { + return false; + } return pimpl_->CheckCodecConfigIsBiDirSwb(config); } bool CodecManager::CheckCodecConfigIsDualBiDirSwb( - const bluetooth::le_audio::set_configurations::AudioSetConfiguration& - config) const { - if (!pimpl_) return false; + const bluetooth::le_audio::set_configurations::AudioSetConfiguration& config) const { + if (!pimpl_) { + return false; + } return pimpl_->CheckCodecConfigIsDualBiDirSwb(config); } std::vector CodecManager::GetLocalAudioOutputCodecCapa() { - if (!pimpl_) + if (!pimpl_) { return std::vector{}; + } return pimpl_->GetLocalAudioOutputCodecCapa(); } std::vector CodecManager::GetLocalAudioInputCodecCapa() { - if (!pimpl_) + if (!pimpl_) { return std::vector{}; + } return pimpl_->GetLocalAudioInputCodecCapa(); } void CodecManager::UpdateBroadcastConnHandle( - const std::vector& conn_handle, - std::function< - void(const ::bluetooth::le_audio::broadcast_offload_config& config)> - update_receiver) { - if (pimpl_) + const std::vector& conn_handle, + std::function + update_receiver) { + if (pimpl_) { return pimpl_->UpdateBroadcastConnHandle(conn_handle, update_receiver); + } } -void CodecManager::Start( - const std::vector& - /*offloading_preference*/) { +void CodecManager::Start(const std::vector& + /*offloading_preference*/) { // It is needed here as CodecManager which is a singleton creates it, but in // this mock we want to destroy and recreate the mock on each test case. if (!pimpl_) { @@ -156,24 +160,28 @@ void CodecManager::Stop() { mock_codec_manager_pimpl_ = nullptr; } -void CodecManager::UpdateCisConfiguration( - const std::vector& cises, - const stream_parameters& stream_params, uint8_t direction) { - if (pimpl_) +void CodecManager::UpdateCisConfiguration(const std::vector& cises, + const stream_parameters& stream_params, + uint8_t direction) { + if (pimpl_) { return pimpl_->UpdateCisConfiguration(cises, stream_params, direction); + } } void CodecManager::ClearCisConfiguration(uint8_t direction) { - if (pimpl_) return pimpl_->ClearCisConfiguration(direction); + if (pimpl_) { + return pimpl_->ClearCisConfiguration(direction); + } } bool CodecManager::IsUsingCodecExtensibility() const { - if (pimpl_) return pimpl_->IsUsingCodecExtensibility(); + if (pimpl_) { + return pimpl_->IsUsingCodecExtensibility(); + } return false; } -std::ostream& operator<<( - std::ostream& os, const CodecManager::UnicastConfigurationRequirements&) { +std::ostream& operator<<(std::ostream& os, const CodecManager::UnicastConfigurationRequirements&) { return os; } diff --git a/system/bta/le_audio/mock_codec_manager.h b/system/bta/le_audio/mock_codec_manager.h index ce38ca5bd4e..ae125a1fe1e 100644 --- a/system/bta/le_audio/mock_codec_manager.h +++ b/system/bta/le_audio/mock_codec_manager.h @@ -28,7 +28,7 @@ class LeAudioSourceAudioHalClient; } // namespace bluetooth::le_audio class MockCodecManager { - public: +public: static MockCodecManager* GetInstance(); MockCodecManager() = default; @@ -37,68 +37,52 @@ class MockCodecManager { virtual ~MockCodecManager() = default; - MOCK_METHOD((bluetooth::le_audio::types::CodecLocation), GetCodecLocation, (), - (const)); + MOCK_METHOD((bluetooth::le_audio::types::CodecLocation), GetCodecLocation, (), (const)); MOCK_METHOD((bool), IsDualBiDirSwbSupported, (), (const)); - MOCK_METHOD( - (bool), UpdateActiveUnicastAudioHalClient, - (::bluetooth::le_audio::LeAudioSourceAudioHalClient * - source_unicast_client, - ::bluetooth::le_audio::LeAudioSinkAudioHalClient* sink_unicast_client, - bool is_active)); + MOCK_METHOD((bool), UpdateActiveUnicastAudioHalClient, + (::bluetooth::le_audio::LeAudioSourceAudioHalClient * source_unicast_client, + ::bluetooth::le_audio::LeAudioSinkAudioHalClient* sink_unicast_client, + bool is_active)); MOCK_METHOD((bool), UpdateActiveBroadcastAudioHalClient, - (::bluetooth::le_audio::LeAudioSourceAudioHalClient * - source_broadcast_client, + (::bluetooth::le_audio::LeAudioSourceAudioHalClient * source_broadcast_client, bool is_active)); + MOCK_METHOD((void), UpdateActiveAudioConfig, + (const bluetooth::le_audio::types::BidirectionalPair< + bluetooth::le_audio::stream_parameters>& stream_params, + bluetooth::le_audio::types::BidirectionalPair delays_ms, + std::function + update_receiver)); MOCK_METHOD( - (void), UpdateActiveAudioConfig, - (const bluetooth::le_audio::types::BidirectionalPair< - bluetooth::le_audio::stream_parameters>& stream_params, - bluetooth::le_audio::types::BidirectionalPair delays_ms, - std::function - update_receiver)); - MOCK_METHOD( - (std::unique_ptr< - bluetooth::le_audio::set_configurations::AudioSetConfiguration>), - GetCodecConfig, - (const bluetooth::le_audio::CodecManager:: - UnicastConfigurationRequirements& requirements, - bluetooth::le_audio::CodecManager::UnicastConfigurationVerifier), - (const)); - MOCK_METHOD( - (bool), CheckCodecConfigIsBiDirSwb, - (const bluetooth::le_audio::set_configurations::AudioSetConfiguration& - config), - (const)); - MOCK_METHOD( - (bool), CheckCodecConfigIsDualBiDirSwb, - (const bluetooth::le_audio::set_configurations::AudioSetConfiguration& - config), - (const)); - MOCK_METHOD((std::unique_ptr< - bluetooth::le_audio::broadcaster::BroadcastConfiguration>), + (std::unique_ptr), + GetCodecConfig, + (const bluetooth::le_audio::CodecManager::UnicastConfigurationRequirements& requirements, + bluetooth::le_audio::CodecManager::UnicastConfigurationVerifier), + (const)); + MOCK_METHOD((bool), CheckCodecConfigIsBiDirSwb, + (const bluetooth::le_audio::set_configurations::AudioSetConfiguration& config), + (const)); + MOCK_METHOD((bool), CheckCodecConfigIsDualBiDirSwb, + (const bluetooth::le_audio::set_configurations::AudioSetConfiguration& config), + (const)); + MOCK_METHOD((std::unique_ptr), GetBroadcastConfig, - (const bluetooth::le_audio::CodecManager:: - BroadcastConfigurationRequirements&), + (const bluetooth::le_audio::CodecManager::BroadcastConfigurationRequirements&), (const)); MOCK_METHOD((std::vector), GetLocalAudioOutputCodecCapa, ()); MOCK_METHOD((std::vector), GetLocalAudioInputCodecCapa, ()); - MOCK_METHOD( - (void), UpdateBroadcastConnHandle, - (const std::vector& conn_handle, - std::function< - void(const ::bluetooth::le_audio::broadcast_offload_config& config)> - update_receiver)); + MOCK_METHOD((void), UpdateBroadcastConnHandle, + (const std::vector& conn_handle, + std::function + update_receiver)); MOCK_METHOD((void), UpdateCisConfiguration, (const std::vector& cises, - const bluetooth::le_audio::stream_parameters& stream_params, - uint8_t direction), + const bluetooth::le_audio::stream_parameters& stream_params, uint8_t direction), (const)); MOCK_METHOD((void), ClearCisConfiguration, (uint8_t direction)); MOCK_METHOD((bool), IsUsingCodecExtensibility, (), (const)); diff --git a/system/bta/le_audio/mock_state_machine.cc b/system/bta/le_audio/mock_state_machine.cc index feafcd3c862..228cf737610 100644 --- a/system/bta/le_audio/mock_state_machine.cc +++ b/system/bta/le_audio/mock_state_machine.cc @@ -20,8 +20,7 @@ static MockLeAudioGroupStateMachine* mock_machine = nullptr; void bluetooth::le_audio::LeAudioGroupStateMachine::Initialize( - bluetooth::le_audio::LeAudioGroupStateMachine::Callbacks* - state_machine_callbacks) { + bluetooth::le_audio::LeAudioGroupStateMachine::Callbacks* state_machine_callbacks) { log::assert_that(mock_machine, "Mock State Machine not set!"); mock_machine->Initialize(state_machine_callbacks); } @@ -31,12 +30,12 @@ void bluetooth::le_audio::LeAudioGroupStateMachine::Cleanup(void) { mock_machine->Cleanup(); } -bluetooth::le_audio::LeAudioGroupStateMachine* -bluetooth::le_audio::LeAudioGroupStateMachine::Get(void) { +bluetooth::le_audio::LeAudioGroupStateMachine* bluetooth::le_audio::LeAudioGroupStateMachine::Get( + void) { return mock_machine; } void MockLeAudioGroupStateMachine::SetMockInstanceForTesting( - MockLeAudioGroupStateMachine* machine) { + MockLeAudioGroupStateMachine* machine) { mock_machine = machine; } diff --git a/system/bta/le_audio/mock_state_machine.h b/system/bta/le_audio/mock_state_machine.h index 0d6d5a6eb7c..90077fddb4a 100644 --- a/system/bta/le_audio/mock_state_machine.h +++ b/system/bta/le_audio/mock_state_machine.h @@ -21,62 +21,49 @@ #include "state_machine.h" -class MockLeAudioGroupStateMachine - : public bluetooth::le_audio::LeAudioGroupStateMachine { - public: - MOCK_METHOD( - (bool), StartStream, - (bluetooth::le_audio::LeAudioDeviceGroup * group, - bluetooth::le_audio::types::LeAudioContextType context_type, - const bluetooth::le_audio::types::BidirectionalPair< - bluetooth::le_audio::types::AudioContexts>& metadata_context_types, - bluetooth::le_audio::types::BidirectionalPair> - ccid_list), - (override)); - MOCK_METHOD( - (bool), AttachToStream, - (bluetooth::le_audio::LeAudioDeviceGroup * group, - bluetooth::le_audio::LeAudioDevice* leAudioDevice, - bluetooth::le_audio::types::BidirectionalPair> - ccids), - (override)); - MOCK_METHOD((void), SuspendStream, - (bluetooth::le_audio::LeAudioDeviceGroup * group), (override)); - MOCK_METHOD( - (bool), ConfigureStream, - (bluetooth::le_audio::LeAudioDeviceGroup * group, - bluetooth::le_audio::types::LeAudioContextType context_type, - const bluetooth::le_audio::types::BidirectionalPair< - bluetooth::le_audio::types::AudioContexts>& metadata_context_types, - bluetooth::le_audio::types::BidirectionalPair> - ccid_lists), - (override)); - MOCK_METHOD((void), StopStream, - (bluetooth::le_audio::LeAudioDeviceGroup * group), (override)); +class MockLeAudioGroupStateMachine : public bluetooth::le_audio::LeAudioGroupStateMachine { +public: + MOCK_METHOD((bool), StartStream, + (bluetooth::le_audio::LeAudioDeviceGroup * group, + bluetooth::le_audio::types::LeAudioContextType context_type, + const bluetooth::le_audio::types::BidirectionalPair< + bluetooth::le_audio::types::AudioContexts>& metadata_context_types, + bluetooth::le_audio::types::BidirectionalPair> ccid_list), + (override)); + MOCK_METHOD((bool), AttachToStream, + (bluetooth::le_audio::LeAudioDeviceGroup * group, + bluetooth::le_audio::LeAudioDevice* leAudioDevice, + bluetooth::le_audio::types::BidirectionalPair> ccids), + (override)); + MOCK_METHOD((void), SuspendStream, (bluetooth::le_audio::LeAudioDeviceGroup * group), (override)); + MOCK_METHOD((bool), ConfigureStream, + (bluetooth::le_audio::LeAudioDeviceGroup * group, + bluetooth::le_audio::types::LeAudioContextType context_type, + const bluetooth::le_audio::types::BidirectionalPair< + bluetooth::le_audio::types::AudioContexts>& metadata_context_types, + bluetooth::le_audio::types::BidirectionalPair> ccid_lists), + (override)); + MOCK_METHOD((void), StopStream, (bluetooth::le_audio::LeAudioDeviceGroup * group), (override)); MOCK_METHOD((void), ProcessGattNotifEvent, - (uint8_t * value, uint16_t len, - bluetooth::le_audio::types::ase* ase, + (uint8_t* value, uint16_t len, bluetooth::le_audio::types::ase* ase, bluetooth::le_audio::LeAudioDevice* leAudioDevice, bluetooth::le_audio::LeAudioDeviceGroup* group), (override)); MOCK_METHOD((void), ProcessGattCtpNotification, - (bluetooth::le_audio::LeAudioDeviceGroup * group, uint8_t* value, - uint16_t len), + (bluetooth::le_audio::LeAudioDeviceGroup * group, uint8_t* value, uint16_t len), (override)); MOCK_METHOD((void), ProcessHciNotifOnCigCreate, - (bluetooth::le_audio::LeAudioDeviceGroup * group, uint8_t status, - uint8_t cig_id, std::vector conn_handles), + (bluetooth::le_audio::LeAudioDeviceGroup * group, uint8_t status, uint8_t cig_id, + std::vector conn_handles), (override)); MOCK_METHOD((void), ProcessHciNotifOnCigRemove, - (uint8_t status, bluetooth::le_audio::LeAudioDeviceGroup* group), + (uint8_t status, bluetooth::le_audio::LeAudioDeviceGroup* group), (override)); + MOCK_METHOD((void), ProcessHciNotifCisEstablished, + (bluetooth::le_audio::LeAudioDeviceGroup * group, + bluetooth::le_audio::LeAudioDevice* leAudioDevice, + const bluetooth::hci::iso_manager::cis_establish_cmpl_evt* event), (override)); - MOCK_METHOD( - (void), ProcessHciNotifCisEstablished, - (bluetooth::le_audio::LeAudioDeviceGroup * group, - bluetooth::le_audio::LeAudioDevice* leAudioDevice, - const bluetooth::hci::iso_manager::cis_establish_cmpl_evt* event), - (override)); MOCK_METHOD((void), ProcessHciNotifCisDisconnected, (bluetooth::le_audio::LeAudioDeviceGroup * group, bluetooth::le_audio::LeAudioDevice* leAudioDevice, @@ -84,23 +71,21 @@ class MockLeAudioGroupStateMachine (override)); MOCK_METHOD((void), ProcessHciNotifSetupIsoDataPath, (bluetooth::le_audio::LeAudioDeviceGroup * group, - bluetooth::le_audio::LeAudioDevice* leAudioDevice, - uint8_t status, uint16_t conn_hdl), + bluetooth::le_audio::LeAudioDevice* leAudioDevice, uint8_t status, + uint16_t conn_hdl), (override)); MOCK_METHOD((void), ProcessHciNotifRemoveIsoDataPath, (bluetooth::le_audio::LeAudioDeviceGroup * group, - bluetooth::le_audio::LeAudioDevice* leAudioDevice, - uint8_t status, uint16_t conn_hdl), + bluetooth::le_audio::LeAudioDevice* leAudioDevice, uint8_t status, + uint16_t conn_hdl), (override)); MOCK_METHOD((void), Initialize, - (bluetooth::le_audio::LeAudioGroupStateMachine::Callbacks * - state_machine_callbacks)); + (bluetooth::le_audio::LeAudioGroupStateMachine::Callbacks * state_machine_callbacks)); MOCK_METHOD((void), Cleanup, ()); MOCK_METHOD((void), ProcessHciNotifIsoLinkQualityRead, (bluetooth::le_audio::LeAudioDeviceGroup * group, - bluetooth::le_audio::LeAudioDevice* leAudioDevice, - uint8_t conn_handle, uint32_t txUnackedPackets, - uint32_t txFlushedPackets, uint32_t txLastSubeventPackets, + bluetooth::le_audio::LeAudioDevice* leAudioDevice, uint8_t conn_handle, + uint32_t txUnackedPackets, uint32_t txFlushedPackets, uint32_t txLastSubeventPackets, uint32_t retransmittedPackets, uint32_t crcErrorPackets, uint32_t rxUnreceivedPackets, uint32_t duplicatePackets), (override)); diff --git a/system/bta/le_audio/state_machine.cc b/system/bta/le_audio/state_machine.cc index 4ed46b2aca1..42d9fbabf8d 100644 --- a/system/bta/le_audio/state_machine.cc +++ b/system/bta/le_audio/state_machine.cc @@ -132,7 +132,7 @@ class LeAudioGroupStateMachineImpl; LeAudioGroupStateMachineImpl* instance; class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { - public: +public: LeAudioGroupStateMachineImpl(Callbacks* state_machine_callbacks_) : state_machine_callbacks_(state_machine_callbacks_), watchdog_(alarm_new("LeAudioStateMachineTimer")) { @@ -148,8 +148,7 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { bool AttachToStream(LeAudioDeviceGroup* group, LeAudioDevice* leAudioDevice, BidirectionalPair> ccids) override { - log::info("group id: {} device: {}", group->group_id_, - leAudioDevice->address_); + log::info("group id: {} device: {}", group->group_id_, leAudioDevice->address_); /* This function is used to attach the device to the stream. * Limitation here is that device should be previously in the streaming @@ -157,29 +156,24 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { */ if (group->GetState() != AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING || group->GetTargetState() != AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) { - log::error( - "group {} no in correct streaming state: {} or target state: {}", - group->group_id_, ToString(group->GetState()), - ToString(group->GetTargetState())); + log::error("group {} no in correct streaming state: {} or target state: {}", group->group_id_, + ToString(group->GetState()), ToString(group->GetTargetState())); return false; } /* This is cautious - mostly needed for unit test only */ - auto group_metadata_contexts = - get_bidirectional(group->GetMetadataContexts()); + auto group_metadata_contexts = get_bidirectional(group->GetMetadataContexts()); auto device_available_contexts = leAudioDevice->GetAvailableContexts(); if (!group_metadata_contexts.test_any(device_available_contexts)) { - log::info("{} does is not have required context type", - leAudioDevice->address_); + log::info("{} does is not have required context type", leAudioDevice->address_); return false; } /* If remote device is in QoS state, go to enabling state. */ if (leAudioDevice->HaveActiveAse() && leAudioDevice->HaveAllActiveAsesSameState( - AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED)) { - log::info("{} in QoS state, proceed to Enable state", - leAudioDevice->address_); + AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED)) { + log::info("{} in QoS state, proceed to Enable state", leAudioDevice->address_); PrepareAndSendEnable(leAudioDevice); return true; } @@ -189,8 +183,8 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { */ group->InvalidateCachedConfigurations(); - if (!group->Configure(group->GetConfigurationContextType(), - group->GetMetadataContexts(), ccids)) { + if (!group->Configure(group->GetConfigurationContextType(), group->GetMetadataContexts(), + ccids)) { log::error("failed to set ASE configuration"); return false; } @@ -199,17 +193,15 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { return true; } - bool StartStream( - LeAudioDeviceGroup* group, LeAudioContextType context_type, - const BidirectionalPair& metadata_context_types, - BidirectionalPair> ccid_lists) override { + bool StartStream(LeAudioDeviceGroup* group, LeAudioContextType context_type, + const BidirectionalPair& metadata_context_types, + BidirectionalPair> ccid_lists) override { log::info("current state: {}", ToString(group->GetState())); switch (group->GetState()) { case AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED: if (group->IsConfiguredForContext(context_type)) { - if (group->Activate(context_type, metadata_context_types, - ccid_lists)) { + if (group->Activate(context_type, metadata_context_types, ccid_lists)) { SetTargetState(group, AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); if (CigCreate(group)) { @@ -232,8 +224,7 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { /* If configuration is needed */ FALLTHROUGH_INTENDED; case AseState::BTA_LE_AUDIO_ASE_STATE_IDLE: - if (!group->Configure(context_type, metadata_context_types, - ccid_lists)) { + if (!group->Configure(context_type, metadata_context_types, ccid_lists)) { log::error("failed to set ASE configuration"); return false; } @@ -265,8 +256,9 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { * stream configuration is satisfied. We can do that already for * all the devices in a group, without any state transitions. */ - if (!group->IsMetadataChanged(metadata_context_types, ccid_lists)) + if (!group->IsMetadataChanged(metadata_context_types, ccid_lists)) { return true; + } LeAudioDevice* leAudioDevice = group->GetFirstActiveDevice(); if (!leAudioDevice) { @@ -275,8 +267,7 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { } while (leAudioDevice) { - PrepareAndSendUpdateMetadata(leAudioDevice, metadata_context_types, - ccid_lists); + PrepareAndSendUpdateMetadata(leAudioDevice, metadata_context_types, ccid_lists); leAudioDevice = group->GetNextActiveDevice(leAudioDevice); } break; @@ -290,14 +281,12 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { return true; } - bool ConfigureStream( - LeAudioDeviceGroup* group, LeAudioContextType context_type, - const BidirectionalPair& metadata_context_types, - BidirectionalPair> ccid_lists) override { + bool ConfigureStream(LeAudioDeviceGroup* group, LeAudioContextType context_type, + const BidirectionalPair& metadata_context_types, + BidirectionalPair> ccid_lists) override { if (group->GetState() > AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED) { - log::error( - "Stream should be stopped or in configured stream. Current state: {}", - ToString(group->GetState())); + log::error("Stream should be stopped or in configured stream. Current state: {}", + ToString(group->GetState())); return false; } @@ -305,8 +294,8 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { ReleaseCisIds(group); if (!group->Configure(context_type, metadata_context_types, ccid_lists)) { - log::error("Could not configure ASEs for group {} content type {}", - group->group_id_, int(context_type)); + log::error("Could not configure ASEs for group {} content type {}", group->group_id_, + int(context_type)); return false; } @@ -336,19 +325,16 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { state_machine_callbacks_->StatusReportCb(group->group_id_, status); } - void notifyLeAudioHealth( - LeAudioDeviceGroup* group, - bluetooth::le_audio::LeAudioHealthGroupStatType stat) { + void notifyLeAudioHealth(LeAudioDeviceGroup* group, + bluetooth::le_audio::LeAudioHealthGroupStatType stat) { auto leAudioHealthStatus = bluetooth::le_audio::LeAudioHealthStatus::Get(); if (leAudioHealthStatus) { leAudioHealthStatus->AddStatisticForGroup(group, stat); } } - void ProcessGattCtpNotification(LeAudioDeviceGroup* group, uint8_t* value, - uint16_t len) { - auto ntf = std::make_unique< - struct bluetooth::le_audio::client_parser::ascs::ctp_ntf>(); + void ProcessGattCtpNotification(LeAudioDeviceGroup* group, uint8_t* value, uint16_t len) { + auto ntf = std::make_unique(); bool valid_notification = ParseAseCtpNotification(*ntf, len, value); if (group == nullptr) { @@ -369,12 +355,9 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { auto target_state = group->GetTargetState(); auto in_transition = group->IsInTransition(); - if (!in_transition || - target_state != AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) { - log::debug( - "Not interested in ctp result for group {} inTransistion: {} , " - "targetState: {}", - group->group_id_, in_transition, ToString(target_state)); + if (!in_transition || target_state != AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) { + log::debug("Not interested in ctp result for group {} inTransition: {} , targetState: {}", + group->group_id_, in_transition, ToString(target_state)); return; } @@ -389,25 +372,24 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { bluetooth::le_audio::client_parser::ascs::kCtpResponseCodeSuccess) { /* Gracefully stop the stream */ log::error( - "Stoping stream due to control point error for ase: {}, error: " - "0x{:02x}, reason: 0x{:02x}", - entry.ase_id, entry.response_code, entry.reason); + "Stopping stream due to control point error for ase: {}, error: " + "0x{:02x}, reason: 0x{:02x}", + entry.ase_id, entry.response_code, entry.reason); - notifyLeAudioHealth(group, - bluetooth::le_audio::LeAudioHealthGroupStatType:: - STREAM_CREATE_SIGNALING_FAILED); + notifyLeAudioHealth( + group, + bluetooth::le_audio::LeAudioHealthGroupStatType::STREAM_CREATE_SIGNALING_FAILED); StopStream(group); return; } } - log::debug("Ctp result OK for group {} inTransistion: {} , targetState: {}", - group->group_id_, in_transition, ToString(target_state)); + log::debug("Ctp result OK for group {} inTransition: {} , targetState: {}", group->group_id_, + in_transition, ToString(target_state)); } void ProcessGattNotifEvent(uint8_t* value, uint16_t len, struct ase* ase, - LeAudioDevice* leAudioDevice, - LeAudioDeviceGroup* group) override { + LeAudioDevice* leAudioDevice, LeAudioDeviceGroup* group) override { struct bluetooth::le_audio::client_parser::ascs::ase_rsp_hdr arh; ParseAseStatusHeader(arh, len, value); @@ -420,14 +402,13 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { auto state = static_cast(arh.state); - log::info("{} , ASE id: {}, state changed {} -> {}", - leAudioDevice->address_, ase->id, ToString(ase->state), - ToString(state)); + log::info("{} , ASE id: {}, state changed {} -> {}", leAudioDevice->address_, ase->id, + ToString(ase->state), ToString(state)); - log_history_->AddLogHistory( - kLogAseStateNotif, leAudioDevice->group_id_, leAudioDevice->address_, - "ASE_ID " + std::to_string(arh.id) + ": " + ToString(state), - "curr: " + ToString(ase->state)); + log_history_->AddLogHistory(kLogAseStateNotif, leAudioDevice->group_id_, + leAudioDevice->address_, + "ASE_ID " + std::to_string(arh.id) + ": " + ToString(state), + "curr: " + ToString(ase->state)); switch (state) { case AseState::BTA_LE_AUDIO_ASE_STATE_IDLE: @@ -435,10 +416,9 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { break; case AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED: AseStateMachineProcessCodecConfigured( - arh, ase, - value + bluetooth::le_audio::client_parser::ascs::kAseRspHdrMinLen, - len - bluetooth::le_audio::client_parser::ascs::kAseRspHdrMinLen, - group, leAudioDevice); + arh, ase, value + bluetooth::le_audio::client_parser::ascs::kAseRspHdrMinLen, + len - bluetooth::le_audio::client_parser::ascs::kAseRspHdrMinLen, group, + leAudioDevice); break; case AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED: AseStateMachineProcessQosConfigured(arh, ase, group, leAudioDevice); @@ -448,10 +428,9 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { break; case AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING: AseStateMachineProcessStreaming( - arh, ase, - value + bluetooth::le_audio::client_parser::ascs::kAseRspHdrMinLen, - len - bluetooth::le_audio::client_parser::ascs::kAseRspHdrMinLen, - group, leAudioDevice); + arh, ase, value + bluetooth::le_audio::client_parser::ascs::kAseRspHdrMinLen, + len - bluetooth::le_audio::client_parser::ascs::kAseRspHdrMinLen, group, + leAudioDevice); break; case AseState::BTA_LE_AUDIO_ASE_STATE_DISABLING: AseStateMachineProcessDisabling(arh, ase, group, leAudioDevice); @@ -466,8 +445,7 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { } } - void ProcessHciNotifOnCigCreate(LeAudioDeviceGroup* group, uint8_t status, - uint8_t cig_id, + void ProcessHciNotifOnCigCreate(LeAudioDeviceGroup* group, uint8_t status, uint8_t cig_id, std::vector conn_handles) override { /* TODO: What if not all cises will be configured ? * conn_handle.size() != active ases in group @@ -478,8 +456,7 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { return; } - log_history_->AddLogHistory(kLogHciEvent, group->group_id_, - RawAddress::kEmpty, + log_history_->AddLogHistory(kLogHciEvent, group->group_id_, RawAddress::kEmpty, kLogCisCreateOp + "STATUS=" + loghex(status)); if (status != HCI_SUCCESS) { @@ -496,28 +473,26 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { } group->cig.SetState(CigState::NONE); - log::error(", failed to create CIG, reason: 0x{:02x}, new cig state: {}", - status, ToString(group->cig.GetState())); + log::error(", failed to create CIG, reason: 0x{:02x}, new cig state: {}", status, + ToString(group->cig.GetState())); StopStream(group); return; } log::assert_that(group->cig.GetState() == CigState::CREATING, - "Unexpected CIG creation group id: {}, cig state: {}", - group->group_id_, ToString(group->cig.GetState())); + "Unexpected CIG creation group id: {}, cig state: {}", group->group_id_, + ToString(group->cig.GetState())); group->cig.SetState(CigState::CREATED); - log::info("Group: {}, id: {} cig state: {}, number of cis handles: {}", - fmt::ptr(group), group->group_id_, - ToString(group->cig.GetState()), + log::info("Group: {}, id: {} cig state: {}, number of cis handles: {}", fmt::ptr(group), + group->group_id_, ToString(group->cig.GetState()), static_cast(conn_handles.size())); if (group->GetTargetState() != AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) { /* Group is not going to stream. It happen while CIG was creating. * Remove CIG in such a case */ - log::warn("group_id {} is not going to stream anymore. Remove CIG.", - group->group_id_); + log::warn("group_id {} is not going to stream anymore. Remove CIG.", group->group_id_); group->PrintDebugState(); RemoveCigForGroup(group); return; @@ -536,62 +511,60 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { } void FreeLinkQualityReports(LeAudioDevice* leAudioDevice) { - if (leAudioDevice->link_quality_timer == nullptr) return; + if (leAudioDevice->link_quality_timer == nullptr) { + return; + } alarm_free(leAudioDevice->link_quality_timer); leAudioDevice->link_quality_timer = nullptr; } - void ProcessHciNotifyOnCigRemoveRecovering(uint8_t status, - LeAudioDeviceGroup* group) { + void ProcessHciNotifyOnCigRemoveRecovering(uint8_t status, LeAudioDeviceGroup* group) { group->cig.SetState(CigState::NONE); - log_history_->AddLogHistory(kLogHciEvent, group->group_id_, - RawAddress::kEmpty, + log_history_->AddLogHistory(kLogHciEvent, group->group_id_, RawAddress::kEmpty, kLogCigRemoveOp + " STATUS=" + loghex(status)); if (status != HCI_SUCCESS) { log::error( - "Could not recover from the COMMAND DISALLOAD on CigCreate. Status " - "on CIG remove is 0x{:02x}", - status); + "Could not recover from the COMMAND DISALLOAD on CigCreate. Status " + "on CIG remove is 0x{:02x}", + status); StopStream(group); return; } log::info("Succeed on CIG Recover - back to creating CIG"); if (!CigCreate(group)) { - log::error("Could not create CIG. Stop the stream for group {}", - group->group_id_); + log::error("Could not create CIG. Stop the stream for group {}", group->group_id_); StopStream(group); } } - void ProcessHciNotifOnCigRemove(uint8_t status, - LeAudioDeviceGroup* group) override { + void ProcessHciNotifOnCigRemove(uint8_t status, LeAudioDeviceGroup* group) override { if (group->cig.GetState() == CigState::RECOVERING) { ProcessHciNotifyOnCigRemoveRecovering(status, group); return; } - log_history_->AddLogHistory(kLogHciEvent, group->group_id_, - RawAddress::kEmpty, + log_history_->AddLogHistory(kLogHciEvent, group->group_id_, RawAddress::kEmpty, kLogCigRemoveOp + " STATUS=" + loghex(status)); if (status != HCI_SUCCESS) { group->cig.SetState(CigState::CREATED); - log::error( - "failed to remove cig, id: {}, status 0x{:02x}, new cig state: {}", - group->group_id_, status, ToString(group->cig.GetState())); + log::error("failed to remove cig, id: {}, status 0x{:02x}, new cig state: {}", + group->group_id_, status, ToString(group->cig.GetState())); return; } log::assert_that(group->cig.GetState() == CigState::REMOVING, - "Unexpected CIG remove group id: {}, cig state {}", - group->group_id_, ToString(group->cig.GetState())); + "Unexpected CIG remove group id: {}, cig state {}", group->group_id_, + ToString(group->cig.GetState())); group->cig.SetState(CigState::NONE); LeAudioDevice* leAudioDevice = group->GetFirstDevice(); - if (!leAudioDevice) return; + if (!leAudioDevice) { + return; + } do { FreeLinkQualityReports(leAudioDevice); @@ -603,14 +576,11 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { } while ((leAudioDevice = group->GetNextDevice(leAudioDevice))); } - void ProcessHciNotifSetupIsoDataPath(LeAudioDeviceGroup* group, - LeAudioDevice* leAudioDevice, - uint8_t status, - uint16_t conn_handle) override { + void ProcessHciNotifSetupIsoDataPath(LeAudioDeviceGroup* group, LeAudioDevice* leAudioDevice, + uint8_t status, uint16_t conn_handle) override { log_history_->AddLogHistory( - kLogHciEvent, group->group_id_, leAudioDevice->address_, - kLogSetDataPathOp + "cis_h:" + loghex(conn_handle) + - " STATUS=" + loghex(status)); + kLogHciEvent, group->group_id_, leAudioDevice->address_, + kLogSetDataPathOp + "cis_h:" + loghex(conn_handle) + " STATUS=" + loghex(status)); if (status) { log::error("failed to setup data path"); @@ -621,8 +591,7 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { if (com::android::bluetooth::flags::leaudio_dynamic_spatial_audio()) { if (group->dsa_.active && - (group->dsa_.mode == DsaMode::ISO_SW || - group->dsa_.mode == DsaMode::ISO_HW) && + (group->dsa_.mode == DsaMode::ISO_SW || group->dsa_.mode == DsaMode::ISO_HW) && leAudioDevice->GetDsaDataPathState() == DataPathState::CONFIGURING) { log::info("Datapath configured for headtracking"); leAudioDevice->SetDsaDataPathState(DataPathState::CONFIGURED); @@ -631,8 +600,8 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { } /* Update state for the given cis.*/ - auto ase = leAudioDevice->GetFirstActiveAseByCisAndDataPathState( - CisState::CONNECTED, DataPathState::CONFIGURING); + auto ase = leAudioDevice->GetFirstActiveAseByCisAndDataPathState(CisState::CONNECTED, + DataPathState::CONFIGURING); if (!ase || ase->cis_conn_hdl != conn_handle) { log::error("Cannot find ase by handle {}", conn_handle); @@ -642,55 +611,46 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { ase->data_path_state = DataPathState::CONFIGURED; if (group->GetTargetState() != AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) { - log::warn("Group {} is not targeting streaming state any more", - group->group_id_); + log::warn("Group {} is not targeting streaming state any more", group->group_id_); return; } AddCisToStreamConfiguration(group, ase); if (group->GetState() == AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING && - !group->GetFirstActiveDeviceByCisAndDataPathState( - CisState::CONNECTED, DataPathState::IDLE)) { + !group->GetFirstActiveDeviceByCisAndDataPathState(CisState::CONNECTED, + DataPathState::IDLE)) { /* No more transition for group. Here we are for the late join device * scenario */ cancel_watchdog_if_needed(group->group_id_); } - if (group->GetNotifyStreamingWhenCisesAreReadyFlag() && - group->IsGroupStreamReady()) { + if (group->GetNotifyStreamingWhenCisesAreReadyFlag() && group->IsGroupStreamReady()) { group->SetNotifyStreamingWhenCisesAreReadyFlag(false); log::info("Ready to notify Group Streaming."); cancel_watchdog_if_needed(group->group_id_); if (group->GetState() != AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) { group->SetState(AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); } - state_machine_callbacks_->StatusReportCb(group->group_id_, - GroupStreamStatus::STREAMING); + state_machine_callbacks_->StatusReportCb(group->group_id_, GroupStreamStatus::STREAMING); }; } - void ProcessHciNotifRemoveIsoDataPath(LeAudioDeviceGroup* group, - LeAudioDevice* leAudioDevice, - uint8_t status, - uint16_t conn_hdl) override { - log_history_->AddLogHistory( - kLogHciEvent, group->group_id_, leAudioDevice->address_, - kLogRemoveDataPathOp + "STATUS=" + loghex(status)); + void ProcessHciNotifRemoveIsoDataPath(LeAudioDeviceGroup* group, LeAudioDevice* leAudioDevice, + uint8_t status, uint16_t conn_hdl) override { + log_history_->AddLogHistory(kLogHciEvent, group->group_id_, leAudioDevice->address_, + kLogRemoveDataPathOp + "STATUS=" + loghex(status)); if (status != HCI_SUCCESS) { - log::error( - "failed to remove ISO data path, reason: 0x{:0x} - contining stream " - "closing", - status); + log::error("failed to remove ISO data path, reason: 0x{:0x} - continuing stream closing", + status); /* Just continue - disconnecting CIS removes data path as well.*/ } bool do_disconnect = false; auto ases_pair = leAudioDevice->GetAsesByCisConnHdl(conn_hdl); - if (ases_pair.sink && - (ases_pair.sink->data_path_state == DataPathState::REMOVING)) { + if (ases_pair.sink && (ases_pair.sink->data_path_state == DataPathState::REMOVING)) { ases_pair.sink->data_path_state = DataPathState::IDLE; if (ases_pair.sink->cis_state == CisState::CONNECTED) { @@ -699,18 +659,15 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { } } - if (ases_pair.source && - (ases_pair.source->data_path_state == DataPathState::REMOVING)) { + if (ases_pair.source && (ases_pair.source->data_path_state == DataPathState::REMOVING)) { ases_pair.source->data_path_state = DataPathState::IDLE; if (ases_pair.source->cis_state == CisState::CONNECTED) { ases_pair.source->cis_state = CisState::DISCONNECTING; do_disconnect = true; } - } else if (com::android::bluetooth::flags:: - leaudio_dynamic_spatial_audio()) { - if (group->dsa_.active && - leAudioDevice->GetDsaDataPathState() == DataPathState::REMOVING) { + } else if (com::android::bluetooth::flags::leaudio_dynamic_spatial_audio()) { + if (group->dsa_.active && leAudioDevice->GetDsaDataPathState() == DataPathState::REMOVING) { log::info("DSA data path removed"); leAudioDevice->SetDsaDataPathState(DataPathState::IDLE); leAudioDevice->SetDsaCisHandle(GATT_INVALID_CONN_ID); @@ -721,26 +678,23 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { group->RemoveCisFromStreamIfNeeded(leAudioDevice, conn_hdl); IsoManager::GetInstance()->DisconnectCis(conn_hdl, HCI_ERR_PEER_USER); - log_history_->AddLogHistory( - kLogStateMachineTag, group->group_id_, leAudioDevice->address_, - kLogCisDisconnectOp + "cis_h:" + loghex(conn_hdl)); + log_history_->AddLogHistory(kLogStateMachineTag, group->group_id_, leAudioDevice->address_, + kLogCisDisconnectOp + "cis_h:" + loghex(conn_hdl)); } } - void ProcessHciNotifIsoLinkQualityRead( - LeAudioDeviceGroup* group, LeAudioDevice* leAudioDevice, - uint8_t conn_handle, uint32_t txUnackedPackets, uint32_t txFlushedPackets, - uint32_t txLastSubeventPackets, uint32_t retransmittedPackets, - uint32_t crcErrorPackets, uint32_t rxUnreceivedPackets, - uint32_t duplicatePackets) { + void ProcessHciNotifIsoLinkQualityRead(LeAudioDeviceGroup* group, LeAudioDevice* leAudioDevice, + uint8_t conn_handle, uint32_t txUnackedPackets, + uint32_t txFlushedPackets, uint32_t txLastSubeventPackets, + uint32_t retransmittedPackets, uint32_t crcErrorPackets, + uint32_t rxUnreceivedPackets, uint32_t duplicatePackets) { log::info( - "conn_handle: 0x{:x}, txUnackedPackets: 0x{:x}, txFlushedPackets: " - "0x{:x}, txLastSubeventPackets: 0x{:x}, retransmittedPackets: 0x{:x}, " - "crcErrorPackets: 0x{:x}, rxUnreceivedPackets: 0x{:x}, " - "duplicatePackets: 0x{:x}", - conn_handle, txUnackedPackets, txFlushedPackets, txLastSubeventPackets, - retransmittedPackets, crcErrorPackets, rxUnreceivedPackets, - duplicatePackets); + "conn_handle: 0x{:x}, txUnackedPackets: 0x{:x}, txFlushedPackets: " + "0x{:x}, txLastSubeventPackets: 0x{:x}, retransmittedPackets: 0x{:x}, " + "crcErrorPackets: 0x{:x}, rxUnreceivedPackets: 0x{:x}, " + "duplicatePackets: 0x{:x}", + conn_handle, txUnackedPackets, txFlushedPackets, txLastSubeventPackets, + retransmittedPackets, crcErrorPackets, rxUnreceivedPackets, duplicatePackets); } void ReleaseCisIds(LeAudioDeviceGroup* group) { @@ -763,29 +717,27 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { } void RemoveCigForGroup(LeAudioDeviceGroup* group) { - log::debug("Group: {}, id: {} cig state: {}", fmt::ptr(group), - group->group_id_, ToString(group->cig.GetState())); + log::debug("Group: {}, id: {} cig state: {}", fmt::ptr(group), group->group_id_, + ToString(group->cig.GetState())); if (group->cig.GetState() != CigState::CREATED) { - log::warn("Group: {}, id: {} cig state: {} cannot be removed", - fmt::ptr(group), group->group_id_, - ToString(group->cig.GetState())); + log::warn("Group: {}, id: {} cig state: {} cannot be removed", fmt::ptr(group), + group->group_id_, ToString(group->cig.GetState())); return; } group->cig.SetState(CigState::REMOVING); IsoManager::GetInstance()->RemoveCig(group->group_id_); - log::debug("Group: {}, id: {} cig state: {}", fmt::ptr(group), - group->group_id_, ToString(group->cig.GetState())); - log_history_->AddLogHistory(kLogStateMachineTag, group->group_id_, - RawAddress::kEmpty, kLogCigRemoveOp); + log::debug("Group: {}, id: {} cig state: {}", fmt::ptr(group), group->group_id_, + ToString(group->cig.GetState())); + log_history_->AddLogHistory(kLogStateMachineTag, group->group_id_, RawAddress::kEmpty, + kLogCigRemoveOp); } - void ProcessHciNotifAclDisconnected(LeAudioDeviceGroup* group, - LeAudioDevice* leAudioDevice) { + void ProcessHciNotifAclDisconnected(LeAudioDeviceGroup* group, LeAudioDevice* leAudioDevice) { FreeLinkQualityReports(leAudioDevice); if (!group) { - log::error("group is null for device: {} group_id: {}", - leAudioDevice->address_, leAudioDevice->group_id_); + log::error("group is null for device: {} group_id: {}", leAudioDevice->address_, + leAudioDevice->group_id_); /* mark ASEs as not used. */ leAudioDevice->DeactivateAllAses(); return; @@ -812,8 +764,7 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { * audio context availability which could change due to disconnected group * member. */ - if ((group->GetState() == AseState::BTA_LE_AUDIO_ASE_STATE_IDLE) && - !group->IsInTransition()) { + if ((group->GetState() == AseState::BTA_LE_AUDIO_ASE_STATE_IDLE) && !group->IsInTransition()) { log::info("group: {} is in IDLE", group->group_id_); /* When OnLeAudioDeviceSetStateTimeout happens, group will transition @@ -823,17 +774,15 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { * Create when starting stream. */ if (group->cig.GetState() == CigState::CREATED) { - log::info("CIG is in CREATED state so removing CIG for Group {}", - group->group_id_); + log::info("CIG is in CREATED state so removing CIG for Group {}", group->group_id_); RemoveCigForGroup(group); } return; } - log::debug( - "device: {}, group connected: {}, all active ase disconnected:: {}", - leAudioDevice->address_, group->IsAnyDeviceConnected(), - group->HaveAllCisesDisconnected()); + log::debug("device: {}, group connected: {}, all active ase disconnected:: {}", + leAudioDevice->address_, group->IsAnyDeviceConnected(), + group->HaveAllCisesDisconnected()); if (group->IsAnyDeviceConnected()) { /* @@ -845,16 +794,13 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { /* some CISes are connected */ if ((group->GetState() == AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) && - (group->GetTargetState() == - AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING)) { + (group->GetTargetState() == AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING)) { /* We keep streaming but want others to let know user that it might * be need to update CodecManager with new CIS configuration */ - state_machine_callbacks_->StatusReportCb( - group->group_id_, GroupStreamStatus::STREAMING); + state_machine_callbacks_->StatusReportCb(group->group_id_, GroupStreamStatus::STREAMING); } else { - log::warn("group_id {} not in streaming, CISes are still there", - group->group_id_); + log::warn("group_id {} not in streaming, CISes are still there", group->group_id_); group->PrintDebugState(); } @@ -870,8 +816,8 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { void cancel_watchdog_if_needed(int group_id) { if (alarm_is_scheduled(watchdog_)) { - log_history_->AddLogHistory(kLogStateMachineTag, group_id, - RawAddress::kEmpty, "WATCHDOG STOPPED"); + log_history_->AddLogHistory(kLogStateMachineTag, group_id, RawAddress::kEmpty, + "WATCHDOG STOPPED"); alarm_cancel(watchdog_); } } @@ -889,18 +835,14 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { DsaModes dsa_modes = leAudioDevice->GetDsaModes(); if (dsa_modes.empty()) { - log::warn("DSA mode not supported by this LE Audio device: {}", - leAudioDevice->address_); + log::warn("DSA mode not supported by this LE Audio device: {}", leAudioDevice->address_); group->dsa_.active = false; return; } - if (std::find(dsa_modes.begin(), dsa_modes.end(), DsaMode::ISO_SW) == - dsa_modes.end() && - std::find(dsa_modes.begin(), dsa_modes.end(), DsaMode::ISO_HW) == - dsa_modes.end()) { - log::warn("DSA mode not supported by this LE Audio device: {}", - leAudioDevice->address_); + if (std::find(dsa_modes.begin(), dsa_modes.end(), DsaMode::ISO_SW) == dsa_modes.end() && + std::find(dsa_modes.begin(), dsa_modes.end(), DsaMode::ISO_HW) == dsa_modes.end()) { + log::warn("DSA mode not supported by this LE Audio device: {}", leAudioDevice->address_); group->dsa_.active = false; return; } @@ -923,68 +865,62 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { leAudioDevice->SetDsaDataPathState(DataPathState::CONFIGURING); leAudioDevice->SetDsaCisHandle(conn_hdl); - log::verbose( - "DSA mode supported on this LE Audio device: {}, apply data path: {}", - leAudioDevice->address_, data_path_id); + log::verbose("DSA mode supported on this LE Audio device: {}, apply data path: {}", + leAudioDevice->address_, data_path_id); LeAudioLogHistory::Get()->AddLogHistory( - kLogStateMachineTag, group->group_id_, RawAddress::kEmpty, - kLogSetDataPathOp + "cis_h:" + loghex(conn_hdl), - "direction: " + - loghex(bluetooth::hci::iso_manager::kIsoDataPathDirectionOut)); + kLogStateMachineTag, group->group_id_, RawAddress::kEmpty, + kLogSetDataPathOp + "cis_h:" + loghex(conn_hdl), + "direction: " + loghex(bluetooth::hci::iso_manager::kIsoDataPathDirectionOut)); bluetooth::hci::iso_manager::iso_data_path_params param = { - .data_path_dir = bluetooth::hci::iso_manager::kIsoDataPathDirectionOut, - .data_path_id = data_path_id, - .codec_id_format = - bluetooth::le_audio::types::kLeAudioCodecHeadtracking.coding_format, - .codec_id_company = - bluetooth::le_audio::types::kLeAudioCodecHeadtracking - .vendor_company_id, - .codec_id_vendor = bluetooth::le_audio::types::kLeAudioCodecHeadtracking - .vendor_codec_id, - .controller_delay = 0x00000000, - .codec_conf = std::vector(), + .data_path_dir = bluetooth::hci::iso_manager::kIsoDataPathDirectionOut, + .data_path_id = data_path_id, + .codec_id_format = bluetooth::le_audio::types::kLeAudioCodecHeadtracking.coding_format, + .codec_id_company = + bluetooth::le_audio::types::kLeAudioCodecHeadtracking.vendor_company_id, + .codec_id_vendor = + bluetooth::le_audio::types::kLeAudioCodecHeadtracking.vendor_codec_id, + .controller_delay = 0x00000000, + .codec_conf = std::vector(), }; IsoManager::GetInstance()->SetupIsoDataPath(conn_hdl, std::move(param)); } void ProcessHciNotifCisEstablished( - LeAudioDeviceGroup* group, LeAudioDevice* leAudioDevice, - const bluetooth::hci::iso_manager::cis_establish_cmpl_evt* event) - override { + LeAudioDeviceGroup* group, LeAudioDevice* leAudioDevice, + const bluetooth::hci::iso_manager::cis_establish_cmpl_evt* event) override { auto ases_pair = leAudioDevice->GetAsesByCisConnHdl(event->cis_conn_hdl); - log_history_->AddLogHistory( - kLogHciEvent, group->group_id_, leAudioDevice->address_, - kLogCisEstablishedOp + "cis_h:" + loghex(event->cis_conn_hdl) + - " STATUS=" + loghex(event->status)); + log_history_->AddLogHistory(kLogHciEvent, group->group_id_, leAudioDevice->address_, + kLogCisEstablishedOp + "cis_h:" + loghex(event->cis_conn_hdl) + + " STATUS=" + loghex(event->status)); if (event->status != HCI_SUCCESS) { - if (ases_pair.sink) ases_pair.sink->cis_state = CisState::ASSIGNED; - if (ases_pair.source) ases_pair.source->cis_state = CisState::ASSIGNED; + if (ases_pair.sink) { + ases_pair.sink->cis_state = CisState::ASSIGNED; + } + if (ases_pair.source) { + ases_pair.source->cis_state = CisState::ASSIGNED; + } - log::warn("{}: failed to create CIS 0x{:04x}, status: {} (0x{:02x})", - leAudioDevice->address_, event->cis_conn_hdl, - ErrorCodeText((ErrorCode)event->status), event->status); + log::warn("{}: failed to create CIS 0x{:04x}, status: {} (0x{:02x})", leAudioDevice->address_, + event->cis_conn_hdl, ErrorCodeText((ErrorCode)event->status), event->status); if (event->status == HCI_ERR_CONN_FAILED_ESTABLISHMENT && - ((leAudioDevice->cis_failed_to_be_established_retry_cnt_++) < - kNumberOfCisRetries) && + ((leAudioDevice->cis_failed_to_be_established_retry_cnt_++) < kNumberOfCisRetries) && (CisCreateForDevice(group, leAudioDevice))) { log::info("Retrying ({}) to create CIS for {}", - leAudioDevice->cis_failed_to_be_established_retry_cnt_, - leAudioDevice->address_); + leAudioDevice->cis_failed_to_be_established_retry_cnt_, leAudioDevice->address_); return; } if (event->status == HCI_ERR_UNSUPPORTED_REM_FEATURE && group->asymmetric_phy_for_unidirectional_cis_supported == true && - group->GetSduInterval( - bluetooth::le_audio::types::kLeAudioDirectionSource) == 0) { + group->GetSduInterval(bluetooth::le_audio::types::kLeAudioDirectionSource) == 0) { log::info( - "Remote device may not support asymmetric phy for CIS, retry " - "symmetric setting again"); + "Remote device may not support asymmetric phy for CIS, retry " + "symmetric setting again"); group->asymmetric_phy_for_unidirectional_cis_supported = false; } @@ -1010,35 +946,33 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { } if (group->GetTargetState() != AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) { - log::error("Unintended CIS establishement event came for group id: {}", - group->group_id_); + log::error("Unintended CIS establishement event came for group id: {}", group->group_id_); StopStream(group); return; } - if (ases_pair.sink) ases_pair.sink->cis_state = CisState::CONNECTED; - if (ases_pair.source) ases_pair.source->cis_state = CisState::CONNECTED; + if (ases_pair.sink) { + ases_pair.sink->cis_state = CisState::CONNECTED; + } + if (ases_pair.source) { + ases_pair.source->cis_state = CisState::CONNECTED; + } - if (ases_pair.sink && - (ases_pair.sink->data_path_state == DataPathState::IDLE)) { + if (ases_pair.sink && (ases_pair.sink->data_path_state == DataPathState::IDLE)) { PrepareDataPath(group->group_id_, ases_pair.sink); } - if (ases_pair.source && - (ases_pair.source->data_path_state == DataPathState::IDLE)) { + if (ases_pair.source && (ases_pair.source->data_path_state == DataPathState::IDLE)) { PrepareDataPath(group->group_id_, ases_pair.source); } else { applyDsaDataPath(group, leAudioDevice, event->cis_conn_hdl); } - if (osi_property_get_bool("persist.bluetooth.iso_link_quality_report", - false)) { - leAudioDevice->link_quality_timer = - alarm_new_periodic("le_audio_cis_link_quality"); + if (osi_property_get_bool("persist.bluetooth.iso_link_quality_report", false)) { + leAudioDevice->link_quality_timer = alarm_new_periodic("le_audio_cis_link_quality"); leAudioDevice->link_quality_timer_data = event->cis_conn_hdl; - alarm_set_on_mloop(leAudioDevice->link_quality_timer, - linkQualityCheckInterval, link_quality_cb, - &leAudioDevice->link_quality_timer_data); + alarm_set_on_mloop(leAudioDevice->link_quality_timer, linkQualityCheckInterval, + link_quality_cb, &leAudioDevice->link_quality_timer_data); } if (!leAudioDevice->HaveAllActiveAsesCisEst()) { @@ -1061,20 +995,18 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { log::assert_that(ase != nullptr, "shouldn't be called without an active ASE, device {}, " "group id: {}, cis handle 0x{:04x}", - ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_), - event->cig_id, event->cis_conn_hdl); + ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_), event->cig_id, + event->cis_conn_hdl); PrepareAndSendReceiverStartReady(leAudioDevice, ase); } - static void WriteToControlPoint(LeAudioDevice* leAudioDevice, - std::vector value) { + static void WriteToControlPoint(LeAudioDevice* leAudioDevice, std::vector value) { tGATT_WRITE_TYPE write_type = GATT_WRITE_NO_RSP; if (value.size() > (leAudioDevice->mtu_ - 3)) { - log::warn("{}, using long write procedure ({} > {})", - leAudioDevice->address_, static_cast(value.size()), - leAudioDevice->mtu_ - 3); + log::warn("{}, using long write procedure ({} > {})", leAudioDevice->address_, + static_cast(value.size()), leAudioDevice->mtu_ - 3); /* Note, that this type is actually LONG WRITE. * Meaning all the Prepare Writes plus Execute is handled in the stack @@ -1082,31 +1014,26 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { write_type = GATT_WRITE_PREPARE; } - BtaGattQueue::WriteCharacteristic(leAudioDevice->conn_id_, - leAudioDevice->ctp_hdls_.val_hdl, value, - write_type, NULL, NULL); + BtaGattQueue::WriteCharacteristic(leAudioDevice->conn_id_, leAudioDevice->ctp_hdls_.val_hdl, + value, write_type, NULL, NULL); } - static void RemoveDataPathByCisHandle(LeAudioDevice* leAudioDevice, - uint16_t cis_conn_hdl) { + static void RemoveDataPathByCisHandle(LeAudioDevice* leAudioDevice, uint16_t cis_conn_hdl) { auto ases_pair = leAudioDevice->GetAsesByCisConnHdl(cis_conn_hdl); uint8_t value = 0; - if (ases_pair.sink && - ases_pair.sink->data_path_state == DataPathState::CONFIGURED) { + if (ases_pair.sink && ases_pair.sink->data_path_state == DataPathState::CONFIGURED) { value |= bluetooth::hci::iso_manager::kRemoveIsoDataPathDirectionInput; ases_pair.sink->data_path_state = DataPathState::REMOVING; } - if (ases_pair.source && - ases_pair.source->data_path_state == DataPathState::CONFIGURED) { + if (ases_pair.source && ases_pair.source->data_path_state == DataPathState::CONFIGURED) { value |= bluetooth::hci::iso_manager::kRemoveIsoDataPathDirectionOutput; ases_pair.source->data_path_state = DataPathState::REMOVING; } else { if (com::android::bluetooth::flags::leaudio_dynamic_spatial_audio()) { if (leAudioDevice->GetDsaDataPathState() == DataPathState::CONFIGURED) { - value |= - bluetooth::hci::iso_manager::kRemoveIsoDataPathDirectionOutput; + value |= bluetooth::hci::iso_manager::kRemoveIsoDataPathDirectionOutput; leAudioDevice->SetDsaDataPathState(DataPathState::REMOVING); } } @@ -1120,23 +1047,22 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { IsoManager::GetInstance()->RemoveIsoDataPath(cis_conn_hdl, value); LeAudioLogHistory::Get()->AddLogHistory( - kLogStateMachineTag, leAudioDevice->group_id_, leAudioDevice->address_, - kLogRemoveDataPathOp + " cis_h:" + loghex(cis_conn_hdl)); + kLogStateMachineTag, leAudioDevice->group_id_, leAudioDevice->address_, + kLogRemoveDataPathOp + " cis_h:" + loghex(cis_conn_hdl)); } void ProcessHciNotifCisDisconnected( - LeAudioDeviceGroup* group, LeAudioDevice* leAudioDevice, - const bluetooth::hci::iso_manager::cis_disconnected_evt* event) override { + LeAudioDeviceGroup* group, LeAudioDevice* leAudioDevice, + const bluetooth::hci::iso_manager::cis_disconnected_evt* event) override { /* Reset the disconnected CIS states */ FreeLinkQualityReports(leAudioDevice); auto ases_pair = leAudioDevice->GetAsesByCisConnHdl(event->cis_conn_hdl); - log_history_->AddLogHistory( - kLogHciEvent, group->group_id_, leAudioDevice->address_, - kLogCisDisconnectedOp + "cis_h:" + loghex(event->cis_conn_hdl) + - " REASON=" + loghex(event->reason)); + log_history_->AddLogHistory(kLogHciEvent, group->group_id_, leAudioDevice->address_, + kLogCisDisconnectedOp + "cis_h:" + loghex(event->cis_conn_hdl) + + " REASON=" + loghex(event->reason)); if (ases_pair.sink) { ases_pair.sink->cis_state = CisState::ASSIGNED; @@ -1150,13 +1076,11 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { /* If this is peer disconnecting CIS, make sure to clear data path */ if (event->reason != HCI_ERR_CONN_CAUSE_LOCAL_HOST) { // Make sure we won't stay in STREAMING state - if (ases_pair.sink && - ases_pair.sink->state == AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) { - SetAseState(leAudioDevice, ases_pair.sink, - AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED); + if (ases_pair.sink && ases_pair.sink->state == AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) { + SetAseState(leAudioDevice, ases_pair.sink, AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED); } - if (ases_pair.source && ases_pair.source->state == - AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) { + if (ases_pair.source && + ases_pair.source->state == AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) { SetAseState(leAudioDevice, ases_pair.source, AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED); } @@ -1177,9 +1101,8 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { */ if (!group->HaveAllCisesDisconnected()) { /* There is ASE streaming for some device. Continue streaming. */ - log::warn( - "Group member disconnected during streaming. Cis handle 0x{:04x}", - event->cis_conn_hdl); + log::warn("Group member disconnected during streaming. Cis handle 0x{:04x}", + event->cis_conn_hdl); return; } @@ -1189,8 +1112,7 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { * that device to continue */ - LeAudioDevice* attaching_device = - getDeviceTryingToAttachTheStream(group); + LeAudioDevice* attaching_device = getDeviceTryingToAttachTheStream(group); if (attaching_device != nullptr) { /* There is a device willitng to stream. Let's wait for it to start * streaming */ @@ -1200,9 +1122,9 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { /* this is just to start timer */ group->SetTargetState(AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); log::info( - "{} is still attaching to stream while other members got " - "disconnected from the group_id: {}", - attaching_device->address_, group->group_id_); + "{} is still attaching to stream while other members got " + "disconnected from the group_id: {}", + attaching_device->address_, group->group_id_); return; } @@ -1213,8 +1135,7 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { group->SetState(AseState::BTA_LE_AUDIO_ASE_STATE_IDLE); group->SetTargetState(AseState::BTA_LE_AUDIO_ASE_STATE_IDLE); /* If there is no more ase to stream. Notify it is in IDLE. */ - state_machine_callbacks_->StatusReportCb(group->group_id_, - GroupStreamStatus::IDLE); + state_machine_callbacks_->StatusReportCb(group->group_id_, GroupStreamStatus::IDLE); return; } @@ -1224,14 +1145,12 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { * If group is already suspended and all CIS are disconnected, we can * report SUSPENDED state. */ - if ((group->GetState() == - AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED) && + if ((group->GetState() == AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED) && group->HaveAllCisesDisconnected()) { /* No more transition for group */ cancel_watchdog_if_needed(group->group_id_); - state_machine_callbacks_->StatusReportCb( - group->group_id_, GroupStreamStatus::SUSPENDED); + state_machine_callbacks_->StatusReportCb(group->group_id_, GroupStreamStatus::SUSPENDED); return; } break; @@ -1240,15 +1159,13 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { /* Those two are used when closing the stream and CIS disconnection is * expected */ if (!group->HaveAllCisesDisconnected()) { - log::debug( - "Still waiting for all CISes being disconnected for group:{}", - group->group_id_); + log::debug("Still waiting for all CISes being disconnected for group:{}", + group->group_id_); return; } auto current_group_state = group->GetState(); - log::info("group {} current state: {}, target state: {}", - group->group_id_, + log::info("group {} current state: {}, target state: {}", group->group_id_, bluetooth::common::ToString(current_group_state), bluetooth::common::ToString(target_state)); /* It might happen that controller notified about CIS disconnection @@ -1259,26 +1176,23 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { cancel_watchdog_if_needed(group->group_id_); if (current_group_state == AseState::BTA_LE_AUDIO_ASE_STATE_IDLE) { - log::info( - "Cises disconnected for group {}, we are good in Idle state.", - group->group_id_); + log::info("Cises disconnected for group {}, we are good in Idle state.", + group->group_id_); ReleaseCisIds(group); - state_machine_callbacks_->StatusReportCb(group->group_id_, - GroupStreamStatus::IDLE); - } else if (current_group_state == - AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED) { + state_machine_callbacks_->StatusReportCb(group->group_id_, GroupStreamStatus::IDLE); + } else if (current_group_state == AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED) { auto reconfig = group->IsPendingConfiguration(); log::info( - "Cises disconnected for group: {}, we are good in Configured " - "state, reconfig={}.", - group->group_id_, reconfig); + "Cises disconnected for group: {}, we are good in Configured " + "state, reconfig={}.", + group->group_id_, reconfig); /* This is Autonomous change if both, target and current state * is CODEC_CONFIGURED */ if (target_state == current_group_state) { - state_machine_callbacks_->StatusReportCb( - group->group_id_, GroupStreamStatus::CONFIGURED_AUTONOMOUS); + state_machine_callbacks_->StatusReportCb(group->group_id_, + GroupStreamStatus::CONFIGURED_AUTONOMOUS); } } RemoveCigForGroup(group); @@ -1288,28 +1202,27 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { } /* We should send Receiver Stop Ready when acting as a source */ - if (ases_pair.source && - ases_pair.source->state == AseState::BTA_LE_AUDIO_ASE_STATE_DISABLING) { + if (ases_pair.source && ases_pair.source->state == AseState::BTA_LE_AUDIO_ASE_STATE_DISABLING) { std::vector ids = {ases_pair.source->id}; std::vector value; - bluetooth::le_audio::client_parser::ascs:: - PrepareAseCtpAudioReceiverStopReady(ids, value); + bluetooth::le_audio::client_parser::ascs::PrepareAseCtpAudioReceiverStopReady(ids, value); WriteToControlPoint(leAudioDevice, value); - log_history_->AddLogHistory(kLogControlPointCmd, leAudioDevice->group_id_, - leAudioDevice->address_, - kLogAseStopReadyOp + "ASE_ID " + - std::to_string(ases_pair.source->id)); + log_history_->AddLogHistory( + kLogControlPointCmd, leAudioDevice->group_id_, leAudioDevice->address_, + kLogAseStopReadyOp + "ASE_ID " + std::to_string(ases_pair.source->id)); } /* Tear down CIS's data paths within the group */ struct ase* ase = leAudioDevice->GetFirstActiveAseByCisAndDataPathState( - CisState::CONNECTED, DataPathState::CONFIGURED); + CisState::CONNECTED, DataPathState::CONFIGURED); if (!ase) { leAudioDevice = group->GetNextActiveDevice(leAudioDevice); /* No more ASEs to disconnect their CISes */ - if (!leAudioDevice) return; + if (!leAudioDevice) { + return; + } ase = leAudioDevice->GetFirstActiveAse(); } @@ -1320,18 +1233,18 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { } } - private: +private: static constexpr uint64_t kStateTransitionTimeoutMs = 3500; static constexpr char kStateTransitionTimeoutMsProp[] = - "persist.bluetooth.leaudio.device.set.state.timeoutms"; + "persist.bluetooth.leaudio.device.set.state.timeoutms"; Callbacks* state_machine_callbacks_; alarm_t* watchdog_; LeAudioLogHistory* log_history_; /* This callback is called on timeout during transition to target state */ void OnStateTransitionTimeout(int group_id) { - log_history_->AddLogHistory(kLogStateMachineTag, group_id, - RawAddress::kEmpty, "WATCHDOG FIRED"); + log_history_->AddLogHistory(kLogStateMachineTag, group_id, RawAddress::kEmpty, + "WATCHDOG FIRED"); state_machine_callbacks_->OnStateTransitionTimeout(group_id); } @@ -1339,46 +1252,43 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { auto current_state = ToString(group->GetTargetState()); auto new_state = ToString(state); - log::debug("Watchdog watch started for group={} transition from {} to {}", - group->group_id_, current_state, new_state); + log::debug("Watchdog watch started for group={} transition from {} to {}", group->group_id_, + current_state, new_state); group->SetTargetState(state); /* Group should tie in time to get requested status */ uint64_t timeoutMs = kStateTransitionTimeoutMs; - timeoutMs = - osi_property_get_int32(kStateTransitionTimeoutMsProp, timeoutMs); + timeoutMs = osi_property_get_int32(kStateTransitionTimeoutMsProp, timeoutMs); cancel_watchdog_if_needed(group->group_id_); alarm_set_on_mloop( - watchdog_, timeoutMs, - [](void* data) { - if (instance) instance->OnStateTransitionTimeout(PTR_TO_INT(data)); - }, - INT_TO_PTR(group->group_id_)); + watchdog_, timeoutMs, + [](void* data) { + if (instance) { + instance->OnStateTransitionTimeout(PTR_TO_INT(data)); + } + }, + INT_TO_PTR(group->group_id_)); - log_history_->AddLogHistory(kLogStateMachineTag, group->group_id_, - RawAddress::kEmpty, "WATCHDOG STARTED"); + log_history_->AddLogHistory(kLogStateMachineTag, group->group_id_, RawAddress::kEmpty, + "WATCHDOG STARTED"); } - void AddCisToStreamConfiguration(LeAudioDeviceGroup* group, - const struct ase* ase) { + void AddCisToStreamConfiguration(LeAudioDeviceGroup* group, const struct ase* ase) { group->stream_conf.codec_id = ase->codec_id; auto cis_conn_hdl = ase->cis_conn_hdl; auto& params = group->stream_conf.stream_params.get(ase->direction); - log::info( - "Adding cis handle 0x{:04x} ({}) to stream list", cis_conn_hdl, - ase->direction == bluetooth::le_audio::types::kLeAudioDirectionSink - ? "sink" - : "source"); + log::info("Adding cis handle 0x{:04x} ({}) to stream list", cis_conn_hdl, + ase->direction == bluetooth::le_audio::types::kLeAudioDirectionSink ? "sink" + : "source"); - auto iter = std::find_if( - params.stream_locations.begin(), params.stream_locations.end(), - [cis_conn_hdl](auto& pair) { return cis_conn_hdl == pair.first; }); - log::assert_that(iter == params.stream_locations.end(), - "Stream is already there 0x{:04x}", cis_conn_hdl); + auto iter = std::find_if(params.stream_locations.begin(), params.stream_locations.end(), + [cis_conn_hdl](auto& pair) { return cis_conn_hdl == pair.first; }); + log::assert_that(iter == params.stream_locations.end(), "Stream is already there 0x{:04x}", + cis_conn_hdl); auto core_config = ase->codec_config.GetAsCoreCodecConfig(); @@ -1388,74 +1298,63 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { if (!core_config.audio_channel_allocation.has_value()) { log::warn("ASE has invalid audio location"); } - auto ase_audio_channel_allocation = - core_config.audio_channel_allocation.value_or(0); + auto ase_audio_channel_allocation = core_config.audio_channel_allocation.value_or(0); params.audio_channel_allocation |= ase_audio_channel_allocation; params.stream_locations.emplace_back( - std::make_pair(ase->cis_conn_hdl, ase_audio_channel_allocation)); + std::make_pair(ase->cis_conn_hdl, ase_audio_channel_allocation)); if (params.sample_frequency_hz == 0) { params.sample_frequency_hz = core_config.GetSamplingFrequencyHz(); } else { - log::assert_that( - params.sample_frequency_hz == core_config.GetSamplingFrequencyHz(), - "sample freq mismatch: {}!={}", params.sample_frequency_hz, - core_config.GetSamplingFrequencyHz()); + log::assert_that(params.sample_frequency_hz == core_config.GetSamplingFrequencyHz(), + "sample freq mismatch: {}!={}", params.sample_frequency_hz, + core_config.GetSamplingFrequencyHz()); } if (params.octets_per_codec_frame == 0) { params.octets_per_codec_frame = *core_config.octets_per_codec_frame; } else { - log::assert_that( - params.octets_per_codec_frame == *core_config.octets_per_codec_frame, - "octets per frame mismatch: {}!={}", params.octets_per_codec_frame, - *core_config.octets_per_codec_frame); + log::assert_that(params.octets_per_codec_frame == *core_config.octets_per_codec_frame, + "octets per frame mismatch: {}!={}", params.octets_per_codec_frame, + *core_config.octets_per_codec_frame); } if (params.codec_frames_blocks_per_sdu == 0) { - params.codec_frames_blocks_per_sdu = - *core_config.codec_frames_blocks_per_sdu; + params.codec_frames_blocks_per_sdu = *core_config.codec_frames_blocks_per_sdu; } else { - log::assert_that(params.codec_frames_blocks_per_sdu == - *core_config.codec_frames_blocks_per_sdu, - "codec_frames_blocks_per_sdu: {}!={}", - params.codec_frames_blocks_per_sdu, - *core_config.codec_frames_blocks_per_sdu); + log::assert_that( + params.codec_frames_blocks_per_sdu == *core_config.codec_frames_blocks_per_sdu, + "codec_frames_blocks_per_sdu: {}!={}", params.codec_frames_blocks_per_sdu, + *core_config.codec_frames_blocks_per_sdu); } if (params.frame_duration_us == 0) { params.frame_duration_us = core_config.GetFrameDurationUs(); } else { - log::assert_that( - params.frame_duration_us == core_config.GetFrameDurationUs(), - "frame_duration_us: {}!={}", params.frame_duration_us, - core_config.GetFrameDurationUs()); + log::assert_that(params.frame_duration_us == core_config.GetFrameDurationUs(), + "frame_duration_us: {}!={}", params.frame_duration_us, + core_config.GetFrameDurationUs()); } log::info( - "Added {} Stream Configuration. CIS Connection Handle: {}, Audio " - "Channel Allocation: {}, Number Of Devices: {}, Number Of Channels: {}", - (ase->direction == bluetooth::le_audio::types::kLeAudioDirectionSink - ? "Sink" - : "Source"), - cis_conn_hdl, ase_audio_channel_allocation, params.num_of_devices, - params.num_of_channels); + "Added {} Stream Configuration. CIS Connection Handle: {}, Audio " + "Channel Allocation: {}, Number Of Devices: {}, Number Of Channels: {}", + (ase->direction == bluetooth::le_audio::types::kLeAudioDirectionSink ? "Sink" + : "Source"), + cis_conn_hdl, ase_audio_channel_allocation, params.num_of_devices, + params.num_of_channels); /* Update CodecManager stream configuration */ - state_machine_callbacks_->OnUpdatedCisConfiguration(group->group_id_, - ase->direction); + state_machine_callbacks_->OnUpdatedCisConfiguration(group->group_id_, ase->direction); } - static bool isIntervalAndLatencyProperlySet(uint32_t sdu_interval_us, - uint16_t max_latency_ms) { - log::verbose("sdu_interval_us: {}, max_latency_ms: {}", sdu_interval_us, - max_latency_ms); + static bool isIntervalAndLatencyProperlySet(uint32_t sdu_interval_us, uint16_t max_latency_ms) { + log::verbose("sdu_interval_us: {}, max_latency_ms: {}", sdu_interval_us, max_latency_ms); if (sdu_interval_us == 0) { - return max_latency_ms == - bluetooth::le_audio::types::kMaxTransportLatencyMin; + return max_latency_ms == bluetooth::le_audio::types::kMaxTransportLatencyMin; } - return ((1000 * max_latency_ms) >= sdu_interval_us); + return (1000 * max_latency_ms) >= sdu_interval_us; } void ApplyDsaParams(LeAudioDeviceGroup* group, @@ -1479,8 +1378,8 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { for (auto dsa_modes : group->GetAllowedDsaModesList()) { if (!dsa_modes.empty() && it != cis_cfgs.end()) { - if (std::find(dsa_modes.begin(), dsa_modes.end(), - group->dsa_.mode) != dsa_modes.end()) { + if (std::find(dsa_modes.begin(), dsa_modes.end(), group->dsa_.mode) != + dsa_modes.end()) { log::info("Device found with support for selected DsaMode"); group->dsa_.active = true; @@ -1520,19 +1419,17 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { uint8_t packing, framing, sca; std::vector cis_cfgs; - log::debug("Group: {}, id: {} cig state: {}", fmt::ptr(group), - group->group_id_, ToString(group->cig.GetState())); + log::debug("Group: {}, id: {} cig state: {}", fmt::ptr(group), group->group_id_, + ToString(group->cig.GetState())); if (group->cig.GetState() != CigState::NONE) { - log::warn("Group {}, id: {} has invalid cig state: {}", fmt::ptr(group), - group->group_id_, ToString(group->cig.GetState())); + log::warn("Group {}, id: {} has invalid cig state: {}", fmt::ptr(group), group->group_id_, + ToString(group->cig.GetState())); return false; } - sdu_interval_mtos = group->GetSduInterval( - bluetooth::le_audio::types::kLeAudioDirectionSink); - sdu_interval_stom = group->GetSduInterval( - bluetooth::le_audio::types::kLeAudioDirectionSource); + sdu_interval_mtos = group->GetSduInterval(bluetooth::le_audio::types::kLeAudioDirectionSink); + sdu_interval_stom = group->GetSduInterval(bluetooth::le_audio::types::kLeAudioDirectionSource); sca = group->GetSCA(); packing = group->GetPacking(); framing = group->GetFraming(); @@ -1541,15 +1438,11 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { uint16_t max_sdu_size_mtos = 0; uint16_t max_sdu_size_stom = 0; - uint8_t phy_mtos = - group->GetPhyBitmask(bluetooth::le_audio::types::kLeAudioDirectionSink); - uint8_t phy_stom = group->GetPhyBitmask( - bluetooth::le_audio::types::kLeAudioDirectionSource); - - if (!isIntervalAndLatencyProperlySet(sdu_interval_mtos, - max_trans_lat_mtos) || - !isIntervalAndLatencyProperlySet(sdu_interval_stom, - max_trans_lat_stom)) { + uint8_t phy_mtos = group->GetPhyBitmask(bluetooth::le_audio::types::kLeAudioDirectionSink); + uint8_t phy_stom = group->GetPhyBitmask(bluetooth::le_audio::types::kLeAudioDirectionSource); + + if (!isIntervalAndLatencyProperlySet(sdu_interval_mtos, max_trans_lat_mtos) || + !isIntervalAndLatencyProperlySet(sdu_interval_stom, max_trans_lat_stom)) { log::error("Latency and interval not properly set"); group->PrintDebugState(); return false; @@ -1557,8 +1450,7 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { // Use 1M Phy for the ACK packet from remote device to phone for better // sensitivity - if (group->asymmetric_phy_for_unidirectional_cis_supported && - sdu_interval_stom == 0 && + if (group->asymmetric_phy_for_unidirectional_cis_supported && sdu_interval_stom == 0 && (phy_stom & bluetooth::hci::kIsoCigPhy1M) != 0) { log::info("Use asymmetric PHY for unidirectional CIS"); phy_stom = bluetooth::hci::kIsoCigPhy1M; @@ -1577,19 +1469,17 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { * supported or not, if not, reconfigure CIG. */ for (struct bluetooth::le_audio::types::cis& cis : group->cig.cises) { - uint16_t max_sdu_size_mtos_temp = group->GetMaxSduSize( - bluetooth::le_audio::types::kLeAudioDirectionSink, cis.id); - uint16_t max_sdu_size_stom_temp = group->GetMaxSduSize( - bluetooth::le_audio::types::kLeAudioDirectionSource, cis.id); - uint8_t rtn_mtos_temp = group->GetRtn( - bluetooth::le_audio::types::kLeAudioDirectionSink, cis.id); - uint8_t rtn_stom_temp = group->GetRtn( - bluetooth::le_audio::types::kLeAudioDirectionSource, cis.id); - - max_sdu_size_mtos = - max_sdu_size_mtos_temp ? max_sdu_size_mtos_temp : max_sdu_size_mtos; - max_sdu_size_stom = - max_sdu_size_stom_temp ? max_sdu_size_stom_temp : max_sdu_size_stom; + uint16_t max_sdu_size_mtos_temp = + group->GetMaxSduSize(bluetooth::le_audio::types::kLeAudioDirectionSink, cis.id); + uint16_t max_sdu_size_stom_temp = + group->GetMaxSduSize(bluetooth::le_audio::types::kLeAudioDirectionSource, cis.id); + uint8_t rtn_mtos_temp = + group->GetRtn(bluetooth::le_audio::types::kLeAudioDirectionSink, cis.id); + uint8_t rtn_stom_temp = + group->GetRtn(bluetooth::le_audio::types::kLeAudioDirectionSource, cis.id); + + max_sdu_size_mtos = max_sdu_size_mtos_temp ? max_sdu_size_mtos_temp : max_sdu_size_mtos; + max_sdu_size_stom = max_sdu_size_stom_temp ? max_sdu_size_stom_temp : max_sdu_size_stom; rtn_mtos = rtn_mtos_temp ? rtn_mtos_temp : rtn_mtos; rtn_stom = rtn_stom_temp ? rtn_stom_temp : rtn_stom; } @@ -1600,15 +1490,13 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { cis_cfg.cis_id = cis.id; cis_cfg.phy_mtos = phy_mtos; cis_cfg.phy_stom = phy_stom; - if (cis.type == - bluetooth::le_audio::types::CisType::CIS_TYPE_BIDIRECTIONAL) { + if (cis.type == bluetooth::le_audio::types::CisType::CIS_TYPE_BIDIRECTIONAL) { cis_cfg.max_sdu_size_mtos = max_sdu_size_mtos; cis_cfg.rtn_mtos = rtn_mtos; cis_cfg.max_sdu_size_stom = max_sdu_size_stom; cis_cfg.rtn_stom = rtn_stom; cis_cfgs.push_back(cis_cfg); - } else if (cis.type == bluetooth::le_audio::types::CisType:: - CIS_TYPE_UNIDIRECTIONAL_SINK) { + } else if (cis.type == bluetooth::le_audio::types::CisType::CIS_TYPE_UNIDIRECTIONAL_SINK) { cis_cfg.max_sdu_size_mtos = max_sdu_size_mtos; cis_cfg.rtn_mtos = rtn_mtos; cis_cfg.max_sdu_size_stom = 0; @@ -1624,10 +1512,8 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { } if ((sdu_interval_mtos == 0 && sdu_interval_stom == 0) || - (max_trans_lat_mtos == - bluetooth::le_audio::types::kMaxTransportLatencyMin && - max_trans_lat_stom == - bluetooth::le_audio::types::kMaxTransportLatencyMin) || + (max_trans_lat_mtos == bluetooth::le_audio::types::kMaxTransportLatencyMin && + max_trans_lat_stom == bluetooth::le_audio::types::kMaxTransportLatencyMin) || (max_sdu_size_mtos == 0 && max_sdu_size_stom == 0)) { log::error("Trying to create invalid group"); group->PrintDebugState(); @@ -1635,31 +1521,29 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { } bluetooth::hci::iso_manager::cig_create_params param = { - .sdu_itv_mtos = sdu_interval_mtos, - .sdu_itv_stom = sdu_interval_stom, - .sca = sca, - .packing = packing, - .framing = framing, - .max_trans_lat_stom = max_trans_lat_stom, - .max_trans_lat_mtos = max_trans_lat_mtos, - .cis_cfgs = std::move(cis_cfgs), + .sdu_itv_mtos = sdu_interval_mtos, + .sdu_itv_stom = sdu_interval_stom, + .sca = sca, + .packing = packing, + .framing = framing, + .max_trans_lat_stom = max_trans_lat_stom, + .max_trans_lat_mtos = max_trans_lat_mtos, + .cis_cfgs = std::move(cis_cfgs), }; ApplyDsaParams(group, param); - log_history_->AddLogHistory( - kLogStateMachineTag, group->group_id_, RawAddress::kEmpty, - kLogCigCreateOp + "#CIS: " + std::to_string(param.cis_cfgs.size())); + log_history_->AddLogHistory(kLogStateMachineTag, group->group_id_, RawAddress::kEmpty, + kLogCigCreateOp + "#CIS: " + std::to_string(param.cis_cfgs.size())); group->cig.SetState(CigState::CREATING); IsoManager::GetInstance()->CreateCig(group->group_id_, std::move(param)); - log::debug("Group: {}, id: {} cig state: {}", fmt::ptr(group), - group->group_id_, ToString(group->cig.GetState())); + log::debug("Group: {}, id: {} cig state: {}", fmt::ptr(group), group->group_id_, + ToString(group->cig.GetState())); return true; } - static bool CisCreateForDevice(LeAudioDeviceGroup* group, - LeAudioDevice* leAudioDevice) { + static bool CisCreateForDevice(LeAudioDeviceGroup* group, LeAudioDevice* leAudioDevice) { std::vector conn_pairs; struct ase* ase = leAudioDevice->GetFirstActiveAse(); @@ -1677,30 +1561,30 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { /* Already in pending state - bi-directional CIS or seconde CIS to same * device */ - if (ase->cis_state == CisState::CONNECTING || - ase->cis_state == CisState::CONNECTED) + if (ase->cis_state == CisState::CONNECTING || ase->cis_state == CisState::CONNECTED) { continue; + } - if (ases_pair.sink) ases_pair.sink->cis_state = CisState::CONNECTING; - if (ases_pair.source) ases_pair.source->cis_state = CisState::CONNECTING; + if (ases_pair.sink) { + ases_pair.sink->cis_state = CisState::CONNECTING; + } + if (ases_pair.source) { + ases_pair.source->cis_state = CisState::CONNECTING; + } uint16_t acl_handle = get_btm_client_interface().peer.BTM_GetHCIConnHandle( leAudioDevice->address_, BT_TRANSPORT_LE); - conn_pairs.push_back({.cis_conn_handle = ase->cis_conn_hdl, - .acl_conn_handle = acl_handle}); - log::info("cis handle: 0x{:04x}, acl handle: 0x{:04x}", ase->cis_conn_hdl, - acl_handle); - extra_stream << "cis_h:" << loghex(ase->cis_conn_hdl) - << " acl_h:" << loghex(acl_handle) << ";;"; + conn_pairs.push_back({.cis_conn_handle = ase->cis_conn_hdl, .acl_conn_handle = acl_handle}); + log::info("cis handle: 0x{:04x}, acl handle: 0x{:04x}", ase->cis_conn_hdl, acl_handle); + extra_stream << "cis_h:" << loghex(ase->cis_conn_hdl) << " acl_h:" << loghex(acl_handle) + << ";;"; } while ((ase = leAudioDevice->GetNextActiveAse(ase))); LeAudioLogHistory::Get()->AddLogHistory( - kLogStateMachineTag, leAudioDevice->group_id_, RawAddress::kEmpty, - kLogCisCreateOp + "#CIS: " + std::to_string(conn_pairs.size()), - extra_stream.str()); + kLogStateMachineTag, leAudioDevice->group_id_, RawAddress::kEmpty, + kLogCisCreateOp + "#CIS: " + std::to_string(conn_pairs.size()), extra_stream.str()); - IsoManager::GetInstance()->EstablishCis( - {.conn_pairs = std::move(conn_pairs)}); + IsoManager::GetInstance()->EstablishCis({.conn_pairs = std::move(conn_pairs)}); return true; } @@ -1710,8 +1594,7 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { struct ase* ase; std::vector conn_pairs; - log::assert_that(leAudioDevice, - "Shouldn't be called without an active device."); + log::assert_that(leAudioDevice, "Shouldn't be called without an active device."); /* Make sure CIG is there */ if (group->cig.GetState() != CigState::CREATED) { @@ -1728,78 +1611,73 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { auto ases_pair = leAudioDevice->GetAsesByCisConnHdl(ase->cis_conn_hdl); /* Already in pending state - bi-directional CIS */ - if (ase->cis_state == CisState::CONNECTING) continue; + if (ase->cis_state == CisState::CONNECTING) { + continue; + } - if (ases_pair.sink) ases_pair.sink->cis_state = CisState::CONNECTING; - if (ases_pair.source) + if (ases_pair.sink) { + ases_pair.sink->cis_state = CisState::CONNECTING; + } + if (ases_pair.source) { ases_pair.source->cis_state = CisState::CONNECTING; + } uint16_t acl_handle = get_btm_client_interface().peer.BTM_GetHCIConnHandle( leAudioDevice->address_, BT_TRANSPORT_LE); - conn_pairs.push_back({.cis_conn_handle = ase->cis_conn_hdl, - .acl_conn_handle = acl_handle}); - log::debug("cis handle: {} acl handle : 0x{:x}", ase->cis_conn_hdl, - acl_handle); + conn_pairs.push_back({.cis_conn_handle = ase->cis_conn_hdl, .acl_conn_handle = acl_handle}); + log::debug("cis handle: {} acl handle : 0x{:x}", ase->cis_conn_hdl, acl_handle); } while ((ase = leAudioDevice->GetNextActiveAse(ase))); } while ((leAudioDevice = group->GetNextActiveDevice(leAudioDevice))); - IsoManager::GetInstance()->EstablishCis( - {.conn_pairs = std::move(conn_pairs)}); + IsoManager::GetInstance()->EstablishCis({.conn_pairs = std::move(conn_pairs)}); return true; } static void PrepareDataPath(int group_id, struct ase* ase) { bluetooth::hci::iso_manager::iso_data_path_params param = { - .data_path_dir = - ase->direction == bluetooth::le_audio::types::kLeAudioDirectionSink - ? bluetooth::hci::iso_manager::kIsoDataPathDirectionIn - : bluetooth::hci::iso_manager::kIsoDataPathDirectionOut, - .data_path_id = ase->data_path_configuration.dataPathId, - .codec_id_format = ase->data_path_configuration.isoDataPathConfig - .codecId.coding_format, - .codec_id_company = ase->data_path_configuration.isoDataPathConfig - .codecId.vendor_company_id, - .codec_id_vendor = ase->data_path_configuration.isoDataPathConfig - .codecId.vendor_codec_id, - .controller_delay = - ase->data_path_configuration.isoDataPathConfig.controllerDelayUs, - .codec_conf = - ase->data_path_configuration.isoDataPathConfig.configuration, + .data_path_dir = ase->direction == bluetooth::le_audio::types::kLeAudioDirectionSink + ? bluetooth::hci::iso_manager::kIsoDataPathDirectionIn + : bluetooth::hci::iso_manager::kIsoDataPathDirectionOut, + .data_path_id = ase->data_path_configuration.dataPathId, + .codec_id_format = ase->data_path_configuration.isoDataPathConfig.codecId.coding_format, + .codec_id_company = + ase->data_path_configuration.isoDataPathConfig.codecId.vendor_company_id, + .codec_id_vendor = + ase->data_path_configuration.isoDataPathConfig.codecId.vendor_codec_id, + .controller_delay = ase->data_path_configuration.isoDataPathConfig.controllerDelayUs, + .codec_conf = ase->data_path_configuration.isoDataPathConfig.configuration, }; LeAudioLogHistory::Get()->AddLogHistory( - kLogStateMachineTag, group_id, RawAddress::kEmpty, - kLogSetDataPathOp + "cis_h:" + loghex(ase->cis_conn_hdl), - "direction: " + loghex(param.data_path_dir) + ", codecId: " + - ToString(ase->data_path_configuration.isoDataPathConfig.codecId)); + kLogStateMachineTag, group_id, RawAddress::kEmpty, + kLogSetDataPathOp + "cis_h:" + loghex(ase->cis_conn_hdl), + "direction: " + loghex(param.data_path_dir) + ", codecId: " + + ToString(ase->data_path_configuration.isoDataPathConfig.codecId)); ase->data_path_state = DataPathState::CONFIGURING; - IsoManager::GetInstance()->SetupIsoDataPath(ase->cis_conn_hdl, - std::move(param)); + IsoManager::GetInstance()->SetupIsoDataPath(ase->cis_conn_hdl, std::move(param)); } static void ReleaseDataPath(LeAudioDeviceGroup* group) { LeAudioDevice* leAudioDevice = group->GetFirstActiveDevice(); - log::assert_that(leAudioDevice, - "Shouldn't be called without an active device."); + log::assert_that(leAudioDevice, "Shouldn't be called without an active device."); - auto ase = leAudioDevice->GetFirstActiveAseByCisAndDataPathState( - CisState::CONNECTED, DataPathState::CONFIGURED); + auto ase = leAudioDevice->GetFirstActiveAseByCisAndDataPathState(CisState::CONNECTED, + DataPathState::CONFIGURED); log::assert_that(ase, "Shouldn't be called without an active ASE."); RemoveDataPathByCisHandle(leAudioDevice, ase->cis_conn_hdl); } - void SetAseState(LeAudioDevice* leAudioDevice, struct ase* ase, - AseState state) { - log::info("{}, ase_id: {}, {} -> {}", leAudioDevice->address_, ase->id, - ToString(ase->state), ToString(state)); + void SetAseState(LeAudioDevice* leAudioDevice, struct ase* ase, AseState state) { + log::info("{}, ase_id: {}, {} -> {}", leAudioDevice->address_, ase->id, ToString(ase->state), + ToString(state)); - log_history_->AddLogHistory( - kLogStateMachineTag, leAudioDevice->group_id_, leAudioDevice->address_, - "ASE_ID " + std::to_string(ase->id) + ": " + kLogStateChangedOp, - ToString(ase->state) + "->" + ToString(state)); + log_history_->AddLogHistory(kLogStateMachineTag, leAudioDevice->group_id_, + leAudioDevice->address_, + "ASE_ID " + std::to_string(ase->id) + ": " + kLogStateChangedOp, + ToString(ase->state) + "->" + ToString(state)); ase->state = state; } @@ -1821,18 +1699,16 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { dev = group->GetNextActiveDevice(dev)) { if (!dev->HaveAllActiveAsesSameState(AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) && !dev->HaveAnyReleasingAse()) { - log::debug("Attaching device {} to group_id: {}", dev->address_, - group->group_id_); + log::debug("Attaching device {} to group_id: {}", dev->address_, group->group_id_); return dev; } } return nullptr; } - void AseStateMachineProcessIdle( - struct bluetooth::le_audio::client_parser::ascs::ase_rsp_hdr& arh, - struct ase* ase, LeAudioDeviceGroup* group, - LeAudioDevice* leAudioDevice) { + void AseStateMachineProcessIdle(struct bluetooth::le_audio::client_parser::ascs::ase_rsp_hdr& arh, + struct ase* ase, LeAudioDeviceGroup* group, + LeAudioDevice* leAudioDevice) { switch (ase->state) { case AseState::BTA_LE_AUDIO_ASE_STATE_IDLE: case AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED: @@ -1841,19 +1717,16 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { SetAseState(leAudioDevice, ase, AseState::BTA_LE_AUDIO_ASE_STATE_IDLE); ase->active = false; ase->configured_for_context_type = - bluetooth::le_audio::types::LeAudioContextType::UNINITIALIZED; + bluetooth::le_audio::types::LeAudioContextType::UNINITIALIZED; - if (!leAudioDevice->HaveAllActiveAsesSameState( - AseState::BTA_LE_AUDIO_ASE_STATE_IDLE)) { + if (!leAudioDevice->HaveAllActiveAsesSameState(AseState::BTA_LE_AUDIO_ASE_STATE_IDLE)) { /* More ASEs notification from this device has to come for this group */ - log::debug("Wait for more ASE to configure for device {}", - leAudioDevice->address_); + log::debug("Wait for more ASE to configure for device {}", leAudioDevice->address_); return; } - if (!group->HaveAllActiveDevicesAsesTheSameState( - AseState::BTA_LE_AUDIO_ASE_STATE_IDLE)) { + if (!group->HaveAllActiveDevicesAsesTheSameState(AseState::BTA_LE_AUDIO_ASE_STATE_IDLE)) { log::debug("Waiting for more devices to get into idle state"); return; } @@ -1866,39 +1739,30 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { * otherwise wait for */ if (!group->HaveAllCisesDisconnected() || getDeviceTryingToAttachTheStream(group) != nullptr) { - log::warn( - "Not all CISes removed before going to IDLE for group {}, " - "waiting...", - group->group_id_); + log::warn("Not all CISes removed before going to IDLE for group {}, waiting...", + group->group_id_); group->PrintDebugState(); return; } cancel_watchdog_if_needed(group->group_id_); ReleaseCisIds(group); - state_machine_callbacks_->StatusReportCb(group->group_id_, - GroupStreamStatus::IDLE); + state_machine_callbacks_->StatusReportCb(group->group_id_, GroupStreamStatus::IDLE); break; } case AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED: case AseState::BTA_LE_AUDIO_ASE_STATE_DISABLING: - log::error( - "Ignore invalid attempt of state transition from {} to {}, {}, " - "ase_id: {}", - ToString(ase->state), - ToString(AseState::BTA_LE_AUDIO_ASE_STATE_IDLE), - leAudioDevice->address_, ase->id); + log::error("Ignore invalid attempt of state transition from {} to {}, {}, ase_id: {}", + ToString(ase->state), ToString(AseState::BTA_LE_AUDIO_ASE_STATE_IDLE), + leAudioDevice->address_, ase->id); group->PrintDebugState(); break; case AseState::BTA_LE_AUDIO_ASE_STATE_ENABLING: case AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING: - log::error( - "Invalid state transition from {} to {}, {}, ase_id: {}. Stopping " - "the stream.", - ToString(ase->state), - ToString(AseState::BTA_LE_AUDIO_ASE_STATE_IDLE), - leAudioDevice->address_, ase->id); + log::error("Invalid state transition from {} to {}, {}, ase_id: {}. Stopping the stream.", + ToString(ase->state), ToString(AseState::BTA_LE_AUDIO_ASE_STATE_IDLE), + leAudioDevice->address_, ase->id); group->PrintDebugState(); StopStream(group); break; @@ -1914,8 +1778,7 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { return; } - for (; leAudioDevice; - leAudioDevice = group->GetNextActiveDevice(leAudioDevice)) { + for (; leAudioDevice; leAudioDevice = group->GetNextActiveDevice(leAudioDevice)) { PrepareAndSendConfigQos(group, leAudioDevice); } } @@ -1928,18 +1791,15 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { return false; } - for (; leAudioDevice; - leAudioDevice = group->GetNextActiveDevice(leAudioDevice)) { + for (; leAudioDevice; leAudioDevice = group->GetNextActiveDevice(leAudioDevice)) { PrepareAndSendCodecConfigure(group, leAudioDevice); } return true; } - void PrepareAndSendCodecConfigure(LeAudioDeviceGroup* group, - LeAudioDevice* leAudioDevice) { + void PrepareAndSendCodecConfigure(LeAudioDeviceGroup* group, LeAudioDevice* leAudioDevice) { struct bluetooth::le_audio::client_parser::ascs::ctp_codec_conf conf; - std::vector - confs; + std::vector confs; struct ase* ase; std::stringstream msg_stream; std::stringstream extra_stream; @@ -1950,17 +1810,17 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { return; } - if (group->cig.GetState() == CigState::CREATED) + if (group->cig.GetState() == CigState::CREATED) { group->AssignCisConnHandlesToAses(leAudioDevice); + } msg_stream << kLogAseConfigOp; ase = leAudioDevice->GetFirstActiveAse(); log::assert_that(ase, "shouldn't be called without an active ASE"); for (; ase != nullptr; ase = leAudioDevice->GetNextActiveAse(ase)) { - log::debug("device: {}, ase_id: {}, cis_id: {}, ase state: {}", - leAudioDevice->address_, ase->id, ase->cis_id, - ToString(ase->state)); + log::debug("device: {}, ase_id: {}, cis_id: {}, ase state: {}", leAudioDevice->address_, + ase->id, ase->cis_id, ToString(ase->state)); conf.ase_id = ase->id; conf.target_latency = ase->target_latency; conf.target_phy = group->GetTargetPhy(ase->direction); @@ -1980,24 +1840,20 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { } else { extra_stream << "src,"; } - extra_stream << +conf.codec_id.coding_format << "," - << +conf.target_latency << ";;"; + extra_stream << +conf.codec_id.coding_format << "," << +conf.target_latency << ";;"; } std::vector value; - bluetooth::le_audio::client_parser::ascs::PrepareAseCtpCodecConfig(confs, - value); + bluetooth::le_audio::client_parser::ascs::PrepareAseCtpCodecConfig(confs, value); WriteToControlPoint(leAudioDevice, value); - log_history_->AddLogHistory(kLogControlPointCmd, group->group_id_, - leAudioDevice->address_, msg_stream.str(), - extra_stream.str()); + log_history_->AddLogHistory(kLogControlPointCmd, group->group_id_, leAudioDevice->address_, + msg_stream.str(), extra_stream.str()); } void AseStateMachineProcessCodecConfigured( - struct bluetooth::le_audio::client_parser::ascs::ase_rsp_hdr& arh, - struct ase* ase, uint8_t* data, uint16_t len, LeAudioDeviceGroup* group, - LeAudioDevice* leAudioDevice) { + struct bluetooth::le_audio::client_parser::ascs::ase_rsp_hdr& arh, struct ase* ase, + uint8_t* data, uint16_t len, LeAudioDeviceGroup* group, LeAudioDevice* leAudioDevice) { if (!group) { log::error("leAudioDevice doesn't belong to any group"); @@ -2012,13 +1868,10 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { * proper state. */ auto qos_config_update = [leAudioDevice]( - const struct bluetooth::le_audio:: - client_parser::ascs:: - ase_codec_configured_state_params& rsp, - bluetooth::le_audio::types::AseQosPreferences& - out_qos, - bluetooth::le_audio::types:: - AseQosConfiguration& out_cfg) { + const struct bluetooth::le_audio::client_parser::ascs:: + ase_codec_configured_state_params& rsp, + bluetooth::le_audio::types::AseQosPreferences& out_qos, + bluetooth::le_audio::types::AseQosConfiguration& out_cfg) { out_qos.supported_framing = rsp.framing; out_qos.preferred_phy = rsp.preferred_phy; out_qos.preferred_retrans_nb = rsp.preferred_retrans_nb; @@ -2035,17 +1888,16 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { out_cfg.retrans_nb = rsp.preferred_retrans_nb; out_cfg.phy = leAudioDevice->GetPreferredPhyBitmask(rsp.preferred_phy); log::info( - "Using server preferred QoS settings. Max Transport Latency: {}, " - "Retransmission Number: {}, Phy: {}", - out_cfg.max_transport_latency, out_cfg.retrans_nb, out_cfg.phy); + "Using server preferred QoS settings. Max Transport Latency: {}, " + "Retransmission Number: {}, Phy: {}", + out_cfg.max_transport_latency, out_cfg.retrans_nb, out_cfg.phy); } }; /* ase contain current ASE state. New state is in "arh" */ switch (ase->state) { case AseState::BTA_LE_AUDIO_ASE_STATE_IDLE: { - struct bluetooth::le_audio::client_parser::ascs:: - ase_codec_configured_state_params rsp; + struct bluetooth::le_audio::client_parser::ascs::ase_codec_configured_state_params rsp; /* Cache codec configured status values for further * configuration/reconfiguration @@ -2055,10 +1907,8 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { return; } - uint16_t cig_curr_max_trans_lat_mtos = - group->GetMaxTransportLatencyMtos(); - uint16_t cig_curr_max_trans_lat_stom = - group->GetMaxTransportLatencyStom(); + uint16_t cig_curr_max_trans_lat_mtos = group->GetMaxTransportLatencyMtos(); + uint16_t cig_curr_max_trans_lat_stom = group->GetMaxTransportLatencyStom(); if (group->GetState() == AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) { /* We are here because of the reconnection of the single device. @@ -2066,11 +1916,9 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { * a direction, cannot be supported by the newly connected member * device's ASE for the direction. */ - if ((ase->direction == - bluetooth::le_audio::types::kLeAudioDirectionSink && + if ((ase->direction == bluetooth::le_audio::types::kLeAudioDirectionSink && cig_curr_max_trans_lat_mtos > rsp.max_transport_latency) || - (ase->direction == - bluetooth::le_audio::types::kLeAudioDirectionSource && + (ase->direction == bluetooth::le_audio::types::kLeAudioDirectionSource && cig_curr_max_trans_lat_stom > rsp.max_transport_latency)) { group->SetPendingConfiguration(); StopStream(group); @@ -2079,16 +1927,14 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { } qos_config_update(rsp, ase->qos_preferences, ase->qos_config); - SetAseState(leAudioDevice, ase, - AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED); + SetAseState(leAudioDevice, ase, AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED); if (group->GetTargetState() == AseState::BTA_LE_AUDIO_ASE_STATE_IDLE) { /* This is autonomus change of the remote device */ - log::debug( - "Autonomus change for device {}, ase id {}. Just store it.", - leAudioDevice->address_, ase->id); + log::debug("Autonomus change for device {}, ase id {}. Just store it.", + leAudioDevice->address_, ase->id); if (group->HaveAllActiveDevicesAsesTheSameState( - AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED)) { + AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED)) { group->SetState(AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED); } return; @@ -2097,8 +1943,7 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { if (leAudioDevice->HaveAnyUnconfiguredAses()) { /* More ASEs notification from this device has to come for this group */ - log::debug("More Ases to be configured for the device {}", - leAudioDevice->address_); + log::debug("More Ases to be configured for the device {}", leAudioDevice->address_); return; } @@ -2113,9 +1958,8 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { PrepareAndSendConfigQos(group, leAudioDevice); } else { log::debug( - "Device {} initiated configured state but it is not yet ready " - "to be configured", - leAudioDevice->address_); + "Device {} initiated configured state but it is not yet ready to be configured", + leAudioDevice->address_); } return; } @@ -2129,48 +1973,42 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { /* Last node configured, process group to codec configured state */ group->SetState(AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED); - if (group->GetTargetState() == - AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) { + if (group->GetTargetState() == AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) { if (group->cig.GetState() == CigState::CREATED) { /* It can happen on the earbuds switch scenario. When one device * is getting remove while other is adding to the stream and CIG is * already created */ PrepareAndSendConfigQos(group, leAudioDevice); } else if (!CigCreate(group)) { - log::error("Could not create CIG. Stop the stream for group {}", - group->group_id_); + log::error("Could not create CIG. Stop the stream for group {}", group->group_id_); StopStream(group); } return; } - if (group->GetTargetState() == - AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED && + if (group->GetTargetState() == AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED && group->IsPendingConfiguration()) { log::info("Configured state completed"); /* If all CISes are disconnected, notify upper layer about IDLE * state, otherwise wait for */ if (!group->HaveAllCisesDisconnected()) { - log::warn( - "Not all CISes removed before going to CONFIGURED for group " - "{}, waiting...", - group->group_id_); + log::warn("Not all CISes removed before going to CONFIGURED for group {}, waiting...", + group->group_id_); group->PrintDebugState(); return; } group->ClearPendingConfiguration(); - state_machine_callbacks_->StatusReportCb( - group->group_id_, GroupStreamStatus::CONFIGURED_BY_USER); + state_machine_callbacks_->StatusReportCb(group->group_id_, + GroupStreamStatus::CONFIGURED_BY_USER); /* No more transition for group */ cancel_watchdog_if_needed(group->group_id_); return; } - log::error(", invalid state transition, from: {} to {}", - ToString(group->GetState()), + log::error(", invalid state transition, from: {} to {}", ToString(group->GetState()), ToString(group->GetTargetState())); StopStream(group); @@ -2181,8 +2019,7 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { * autonomously because of the reconfiguration done by us */ - struct bluetooth::le_audio::client_parser::ascs:: - ase_codec_configured_state_params rsp; + struct bluetooth::le_audio::client_parser::ascs::ase_codec_configured_state_params rsp; /* Cache codec configured status values for further * configuration/reconfiguration @@ -2212,92 +2049,79 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { PrepareAndSendConfigQos(group, leAudioDevice); } else { log::debug( - "Device {} initiated configured state but it is not yet ready " - "to be configured", - leAudioDevice->address_); + "Device {} initiated configured state but it is not yet ready to be configured", + leAudioDevice->address_); } return; } if (group->HaveAnyActiveDeviceInUnconfiguredState()) { - log::debug( - "Waiting for all the devices to be configured for group id {}", - group->group_id_); + log::debug("Waiting for all the devices to be configured for group id {}", + group->group_id_); return; } /* Last node configured, process group to codec configured state */ group->SetState(AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED); - if (group->GetTargetState() == - AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) { + if (group->GetTargetState() == AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) { if (group->cig.GetState() == CigState::CREATED) { /* It can happen on the earbuds switch scenario. When one device * is getting remove while other is adding to the stream and CIG is * already created */ PrepareAndSendConfigQos(group, leAudioDevice); } else if (!CigCreate(group)) { - log::error("Could not create CIG. Stop the stream for group {}", - group->group_id_); + log::error("Could not create CIG. Stop the stream for group {}", group->group_id_); StopStream(group); } return; } - if (group->GetTargetState() == - AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED && + if (group->GetTargetState() == AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED && group->IsPendingConfiguration()) { log::info("Configured state completed"); group->ClearPendingConfiguration(); - state_machine_callbacks_->StatusReportCb( - group->group_id_, GroupStreamStatus::CONFIGURED_BY_USER); + state_machine_callbacks_->StatusReportCb(group->group_id_, + GroupStreamStatus::CONFIGURED_BY_USER); /* No more transition for group */ cancel_watchdog_if_needed(group->group_id_); return; } - log::info("Autonomous change, from: {} to {}", - ToString(group->GetState()), + log::info("Autonomous change, from: {} to {}", ToString(group->GetState()), ToString(group->GetTargetState())); break; } case AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED: - SetAseState(leAudioDevice, ase, - AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED); + SetAseState(leAudioDevice, ase, AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED); group->PrintDebugState(); break; case AseState::BTA_LE_AUDIO_ASE_STATE_DISABLING: - log::error( - "Ignore invalid attempt of state transition from {} to {}, {}, " - "ase_id: {}", - ToString(ase->state), - ToString(AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED), - leAudioDevice->address_, ase->id); + log::error("Ignore invalid attempt of state transition from {} to {}, {}, ase_id: {}", + ToString(ase->state), + ToString(AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED), + leAudioDevice->address_, ase->id); group->PrintDebugState(); break; case AseState::BTA_LE_AUDIO_ASE_STATE_RELEASING: - SetAseState(leAudioDevice, ase, - AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED); + SetAseState(leAudioDevice, ase, AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED); ase->active = false; if (!leAudioDevice->HaveAllActiveAsesSameState( - AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED)) { + AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED)) { /* More ASEs notification from this device has to come for this group */ - log::debug("Wait for more ASE to configure for device {}", - leAudioDevice->address_); + log::debug("Wait for more ASE to configure for device {}", leAudioDevice->address_); return; } { auto activeDevice = group->GetFirstActiveDevice(); if (activeDevice) { - log::debug( - "There is at least one active device {}, wait to become " - "inactive", - activeDevice->address_); + log::debug("There is at least one active device {}, wait to become inactive", + activeDevice->address_); return; } } @@ -2311,27 +2135,23 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { group->SetTargetState(group->GetState()); if (!group->HaveAllCisesDisconnected()) { - log::warn( - "Not all CISes removed before going to IDLE for group {}, " - "waiting...", - group->group_id_); + log::warn("Not all CISes removed before going to IDLE for group {}, waiting...", + group->group_id_); group->PrintDebugState(); return; } cancel_watchdog_if_needed(group->group_id_); - state_machine_callbacks_->StatusReportCb( - group->group_id_, GroupStreamStatus::CONFIGURED_AUTONOMOUS); + state_machine_callbacks_->StatusReportCb(group->group_id_, + GroupStreamStatus::CONFIGURED_AUTONOMOUS); break; case AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING: case AseState::BTA_LE_AUDIO_ASE_STATE_ENABLING: - log::error( - "Invalid state transition from {} to {}, {}, ase_id: {}. Stopping " - "the stream", - ToString(ase->state), - ToString(AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED), - leAudioDevice->address_, ase->id); + log::error("Invalid state transition from {} to {}, {}, ase_id: {}. Stopping the stream", + ToString(ase->state), + ToString(AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED), + leAudioDevice->address_, ase->id); group->PrintDebugState(); StopStream(group); break; @@ -2339,9 +2159,8 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { } void AseStateMachineProcessQosConfigured( - struct bluetooth::le_audio::client_parser::ascs::ase_rsp_hdr& arh, - struct ase* ase, LeAudioDeviceGroup* group, - LeAudioDevice* leAudioDevice) { + struct bluetooth::le_audio::client_parser::ascs::ase_rsp_hdr& arh, struct ase* ase, + LeAudioDeviceGroup* group, LeAudioDevice* leAudioDevice) { if (!group) { log::error("leAudioDevice doesn't belong to any group"); @@ -2351,29 +2170,26 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { switch (ase->state) { case AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED: log::info( - "Unexpected state transition from {} to {}, {}, ase_id: {}, " - "fallback to transition from {} to {}", - ToString(ase->state), - ToString(AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED), - leAudioDevice->address_, ase->id, - ToString(AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED), - ToString(AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED)); + "Unexpected state transition from {} to {}, {}, ase_id: {}, " + "fallback to transition from {} to {}", + ToString(ase->state), ToString(AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED), + leAudioDevice->address_, ase->id, + ToString(AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED), + ToString(AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED)); group->PrintDebugState(); FMT_FALLTHROUGH; case AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED: { - SetAseState(leAudioDevice, ase, - AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED); + SetAseState(leAudioDevice, ase, AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED); - if (group->GetTargetState() != - AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) { - log::warn("{}, ase_id: {}, target state: {}", leAudioDevice->address_, - ase->id, ToString(group->GetTargetState())); + if (group->GetTargetState() != AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) { + log::warn("{}, ase_id: {}, target state: {}", leAudioDevice->address_, ase->id, + ToString(group->GetTargetState())); group->PrintDebugState(); return; } if (!leAudioDevice->HaveAllActiveAsesSameState( - AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED)) { + AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED)) { /* More ASEs notification from this device has to come for this group */ return; @@ -2386,7 +2202,7 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { } if (!group->HaveAllActiveDevicesAsesTheSameState( - AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED)) { + AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED)) { log::debug("Waiting for all the devices to be in QoS state"); return; } @@ -2396,27 +2212,22 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { break; } case AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING: - if (ase->direction == - bluetooth::le_audio::types::kLeAudioDirectionSource) { + if (ase->direction == bluetooth::le_audio::types::kLeAudioDirectionSource) { /* Source ASE cannot go from Streaming to QoS Configured state */ - log::error("invalid state transition, from: {}, to: {}", - static_cast(ase->state), - static_cast( - AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED)); + log::error("invalid state transition, from: {}, to: {}", static_cast(ase->state), + static_cast(AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED)); StopStream(group); return; } - SetAseState(leAudioDevice, ase, - AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED); + SetAseState(leAudioDevice, ase, AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED); if (group->HaveAllActiveDevicesAsesTheSameState( - AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED)) { + AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED)) { group->SetState(AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED); } - if (group->GetTargetState() == - AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED) { + if (group->GetTargetState() == AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED) { /* Process the Disable Transition of the rest of group members if no * more ASE notifications has to come from this device. */ ProcessGroupDisable(group); @@ -2428,28 +2239,27 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { break; case AseState::BTA_LE_AUDIO_ASE_STATE_DISABLING: { - SetAseState(leAudioDevice, ase, - AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED); + SetAseState(leAudioDevice, ase, AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED); /* More ASEs notification from this device has to come for this group */ if (!group->HaveAllActiveDevicesAsesTheSameState( - AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED)) + AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED)) { return; + } group->SetState(AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED); - if (!group->HaveAllCisesDisconnected()) return; + if (!group->HaveAllCisesDisconnected()) { + return; + } - if (group->GetTargetState() == - AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED) { + if (group->GetTargetState() == AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED) { /* No more transition for group */ cancel_watchdog_if_needed(group->group_id_); - state_machine_callbacks_->StatusReportCb( - group->group_id_, GroupStreamStatus::SUSPENDED); + state_machine_callbacks_->StatusReportCb(group->group_id_, GroupStreamStatus::SUSPENDED); } else { - log::error(", invalid state transition, from: {}, to: {}", - ToString(group->GetState()), + log::error(", invalid state transition, from: {}, to: {}", ToString(group->GetState()), ToString(group->GetTargetState())); StopStream(group); return; @@ -2459,21 +2269,15 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { case AseState::BTA_LE_AUDIO_ASE_STATE_IDLE: case AseState::BTA_LE_AUDIO_ASE_STATE_RELEASING: // Do nothing here, just print an error message - log::error( - "Ignore invalid attempt of state transition from {} to {}, {}, " - "ase_id: {}", - ToString(ase->state), - ToString(AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED), - leAudioDevice->address_, ase->id); + log::error("Ignore invalid attempt of state transition from {} to {}, {}, ase_id: {}", + ToString(ase->state), ToString(AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED), + leAudioDevice->address_, ase->id); group->PrintDebugState(); break; case AseState::BTA_LE_AUDIO_ASE_STATE_ENABLING: - log::error( - "Invalid state transition from {} to {}, {}, ase_id: {}. Stopping " - "the stream.", - ToString(ase->state), - ToString(AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED), - leAudioDevice->address_, ase->id); + log::error("Invalid state transition from {} to {}, {}, ase_id: {}. Stopping the stream.", + ToString(ase->state), ToString(AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED), + leAudioDevice->address_, ase->id); StopStream(group); break; } @@ -2493,8 +2297,7 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { RemoveCigForGroup(group); if (report_idle_state) { - state_machine_callbacks_->StatusReportCb(group->group_id_, - GroupStreamStatus::IDLE); + state_machine_callbacks_->StatusReportCb(group->group_id_, GroupStreamStatus::IDLE); } } @@ -2509,16 +2312,14 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { return; } - for (; leAudioDevice; - leAudioDevice = group->GetNextActiveDevice(leAudioDevice)) { + for (; leAudioDevice; leAudioDevice = group->GetNextActiveDevice(leAudioDevice)) { PrepareAndSendEnable(leAudioDevice); } } void PrepareAndSendEnable(LeAudioDevice* leAudioDevice) { struct bluetooth::le_audio::client_parser::ascs::ctp_enable conf; - std::vector - confs; + std::vector confs; std::vector value; struct ase* ase; std::stringstream msg_stream; @@ -2529,18 +2330,15 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { ase = leAudioDevice->GetFirstActiveAse(); log::assert_that(ase, "shouldn't be called without an active ASE"); do { - log::debug("device: {}, ase_id: {}, cis_id: {}, ase state: {}", - leAudioDevice->address_, ase->id, ase->cis_id, - ToString(ase->state)); + log::debug("device: {}, ase_id: {}, cis_id: {}, ase state: {}", leAudioDevice->address_, + ase->id, ase->cis_id, ToString(ase->state)); conf.ase_id = ase->id; conf.metadata = ase->metadata; confs.push_back(conf); /* Below is just for log history */ msg_stream << "ASE_ID " << +ase->id << ","; - extra_stream << "meta: " - << base::HexEncode(conf.metadata.data(), - conf.metadata.size()) + extra_stream << "meta: " << base::HexEncode(conf.metadata.data(), conf.metadata.size()) << ";;"; } while ((ase = leAudioDevice->GetNextActiveAse(ase))); @@ -2548,11 +2346,9 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { bluetooth::le_audio::client_parser::ascs::PrepareAseCtpEnable(confs, value); WriteToControlPoint(leAudioDevice, value); - log::info("group_id: {}, {}", leAudioDevice->group_id_, - leAudioDevice->address_); + log::info("group_id: {}, {}", leAudioDevice->group_id_, leAudioDevice->address_); log_history_->AddLogHistory(kLogControlPointCmd, leAudioDevice->group_id_, - leAudioDevice->address_, msg_stream.str(), - extra_stream.str()); + leAudioDevice->address_, msg_stream.str(), extra_stream.str()); } GroupStreamStatus PrepareAndSendDisableToTheGroup(LeAudioDeviceGroup* group) { @@ -2566,8 +2362,7 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { return GroupStreamStatus::IDLE; } - for (; leAudioDevice; - leAudioDevice = group->GetNextActiveDevice(leAudioDevice)) { + for (; leAudioDevice; leAudioDevice = group->GetNextActiveDevice(leAudioDevice)) { PrepareAndSendDisable(leAudioDevice); } return GroupStreamStatus::SUSPENDING; @@ -2582,16 +2377,14 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { std::vector ids; do { - log::debug("device: {}, ase_id: {}, cis_id: {}, ase state: {}", - leAudioDevice->address_, ase->id, ase->cis_id, - ToString(ase->state)); + log::debug("device: {}, ase_id: {}, cis_id: {}, ase state: {}", leAudioDevice->address_, + ase->id, ase->cis_id, ToString(ase->state)); ids.push_back(ase->id); msg_stream << "ASE_ID " << +ase->id << ", "; } while ((ase = leAudioDevice->GetNextActiveAse(ase))); - log::info("group_id: {}, {}", leAudioDevice->group_id_, - leAudioDevice->address_); + log::info("group_id: {}, {}", leAudioDevice->group_id_, leAudioDevice->address_); std::vector value; bluetooth::le_audio::client_parser::ascs::PrepareAseCtpDisable(ids, value); @@ -2611,8 +2404,7 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { return GroupStreamStatus::IDLE; } - for (; leAudioDevice; - leAudioDevice = group->GetNextActiveDevice(leAudioDevice)) { + for (; leAudioDevice; leAudioDevice = group->GetNextActiveDevice(leAudioDevice)) { PrepareAndSendRelease(leAudioDevice); } @@ -2628,9 +2420,8 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { stream << kLogAseReleaseOp; do { - log::debug("device: {}, ase_id: {}, cis_id: {}, ase state: {}", - leAudioDevice->address_, ase->id, ase->cis_id, - ToString(ase->state)); + log::debug("device: {}, ase_id: {}, cis_id: {}, ase state: {}", leAudioDevice->address_, + ase->id, ase->cis_id, ToString(ase->state)); ids.push_back(ase->id); stream << "ASE_ID " << +ase->id << ","; } while ((ase = leAudioDevice->GetNextActiveAse(ase))); @@ -2639,16 +2430,13 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { bluetooth::le_audio::client_parser::ascs::PrepareAseCtpRelease(ids, value); WriteToControlPoint(leAudioDevice, value); - log::info("group_id: {}, {}", leAudioDevice->group_id_, - leAudioDevice->address_); + log::info("group_id: {}, {}", leAudioDevice->group_id_, leAudioDevice->address_); log_history_->AddLogHistory(kLogControlPointCmd, leAudioDevice->group_id_, leAudioDevice->address_, stream.str()); } - void PrepareAndSendConfigQos(LeAudioDeviceGroup* group, - LeAudioDevice* leAudioDevice) { - std::vector - confs; + void PrepareAndSendConfigQos(LeAudioDeviceGroup* group, LeAudioDevice* leAudioDevice) { + std::vector confs; bool validate_transport_latency = false; bool validate_max_sdu_size = false; @@ -2660,13 +2448,11 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { for (struct ase* ase = leAudioDevice->GetFirstActiveAse(); ase != nullptr; ase = leAudioDevice->GetNextActiveAse(ase)) { - log::debug("device: {}, ase_id: {}, cis_id: {}, ase state: {}", - leAudioDevice->address_, ase->id, ase->cis_id, - ToString(ase->state)); + log::debug("device: {}, ase_id: {}, cis_id: {}, ase state: {}", leAudioDevice->address_, + ase->id, ase->cis_id, ToString(ase->state)); /* Fill in the whole group dependent ASE parameters */ - if (!group->GetPresentationDelay(&ase->qos_config.presentation_delay, - ase->direction)) { + if (!group->GetPresentationDelay(&ase->qos_config.presentation_delay, ase->direction)) { log::error("inconsistent presentation delay for group"); group->PrintDebugState(); StopStream(group); @@ -2701,8 +2487,7 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { extra_stream << "src,"; } - if (conf.max_transport_latency > - bluetooth::le_audio::types::kMaxTransportLatencyMin) { + if (conf.max_transport_latency > bluetooth::le_audio::types::kMaxTransportLatencyMin) { validate_transport_latency = true; } @@ -2712,13 +2497,11 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { confs.push_back(conf); // dir...cis_id,sdu,lat,rtn,phy,frm;; - extra_stream << +conf.cis << "," << +conf.max_sdu << "," - << +conf.max_transport_latency << "," << +conf.retrans_nb - << "," << +conf.phy << "," << +conf.framing << ";;"; + extra_stream << +conf.cis << "," << +conf.max_sdu << "," << +conf.max_transport_latency << "," + << +conf.retrans_nb << "," << +conf.phy << "," << +conf.framing << ";;"; } - if (confs.size() == 0 || !validate_transport_latency || - !validate_max_sdu_size) { + if (confs.size() == 0 || !validate_transport_latency || !validate_max_sdu_size) { log::error("Invalid configuration or latency or sdu size"); group->PrintDebugState(); StopStream(group); @@ -2726,46 +2509,40 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { } std::vector value; - bluetooth::le_audio::client_parser::ascs::PrepareAseCtpConfigQos(confs, - value); + bluetooth::le_audio::client_parser::ascs::PrepareAseCtpConfigQos(confs, value); WriteToControlPoint(leAudioDevice, value); - log::info("group_id: {}, {}", leAudioDevice->group_id_, - leAudioDevice->address_); - log_history_->AddLogHistory(kLogControlPointCmd, group->group_id_, - leAudioDevice->address_, msg_stream.str(), - extra_stream.str()); + log::info("group_id: {}, {}", leAudioDevice->group_id_, leAudioDevice->address_); + log_history_->AddLogHistory(kLogControlPointCmd, group->group_id_, leAudioDevice->address_, + msg_stream.str(), extra_stream.str()); } - void PrepareAndSendUpdateMetadata( - LeAudioDevice* leAudioDevice, - const BidirectionalPair& context_types, - const BidirectionalPair>& ccid_lists) { - std::vector< - struct bluetooth::le_audio::client_parser::ascs::ctp_update_metadata> - confs; + void PrepareAndSendUpdateMetadata(LeAudioDevice* leAudioDevice, + const BidirectionalPair& context_types, + const BidirectionalPair>& ccid_lists) { + std::vector confs; std::stringstream msg_stream; msg_stream << kLogAseUpdateMetadataOp; std::stringstream extra_stream; - if (!leAudioDevice->IsMetadataChanged(context_types, ccid_lists)) return; + if (!leAudioDevice->IsMetadataChanged(context_types, ccid_lists)) { + return; + } /* Request server to update ASEs with new metadata */ for (struct ase* ase = leAudioDevice->GetFirstActiveAse(); ase != nullptr; ase = leAudioDevice->GetNextActiveAse(ase)) { - log::debug("device: {}, ase_id: {}, cis_id: {}, ase state: {}", - leAudioDevice->address_, ase->id, ase->cis_id, - ToString(ase->state)); + log::debug("device: {}, ase_id: {}, cis_id: {}, ase state: {}", leAudioDevice->address_, + ase->id, ase->cis_id, ToString(ase->state)); if (ase->state != AseState::BTA_LE_AUDIO_ASE_STATE_ENABLING && ase->state != AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) { /* This might happen when update metadata happens on late connect */ log::debug( - "Metadata for ase_id {} cannot be updated due to invalid ase state " - "- see log above", - ase->id); + "Metadata for ase_id {} cannot be updated due to invalid ase state - see log above", + ase->id); continue; } @@ -2777,18 +2554,16 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { } /* Filter multidirectional audio context for each ase direction */ - auto directional_audio_context = - context_types.get(ase->direction) & - leAudioDevice->GetAvailableContexts(ase->direction); + auto directional_audio_context = context_types.get(ase->direction) & + leAudioDevice->GetAvailableContexts(ase->direction); std::vector new_metadata; if (directional_audio_context.any()) { - new_metadata = leAudioDevice->GetMetadata( - directional_audio_context, ccid_lists.get(ase->direction)); + new_metadata = leAudioDevice->GetMetadata(directional_audio_context, + ccid_lists.get(ase->direction)); } else { - new_metadata = leAudioDevice->GetMetadata( - AudioContexts(LeAudioContextType::UNSPECIFIED), - std::vector()); + new_metadata = leAudioDevice->GetMetadata(AudioContexts(LeAudioContextType::UNSPECIFIED), + std::vector()); } /* Do not update if metadata did not changed. */ @@ -2804,29 +2579,23 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { conf.metadata = ase->metadata; confs.push_back(conf); - extra_stream << "meta: " - << base::HexEncode(conf.metadata.data(), - conf.metadata.size()) + extra_stream << "meta: " << base::HexEncode(conf.metadata.data(), conf.metadata.size()) << ";;"; } if (confs.size() != 0) { std::vector value; - bluetooth::le_audio::client_parser::ascs::PrepareAseCtpUpdateMetadata( - confs, value); + bluetooth::le_audio::client_parser::ascs::PrepareAseCtpUpdateMetadata(confs, value); WriteToControlPoint(leAudioDevice, value); - log::info("group_id: {}, {}", leAudioDevice->group_id_, - leAudioDevice->address_); + log::info("group_id: {}, {}", leAudioDevice->group_id_, leAudioDevice->address_); log_history_->AddLogHistory(kLogControlPointCmd, leAudioDevice->group_id_, - leAudioDevice->address_, msg_stream.str(), - extra_stream.str()); + leAudioDevice->address_, msg_stream.str(), extra_stream.str()); } } - void PrepareAndSendReceiverStartReady(LeAudioDevice* leAudioDevice, - struct ase* ase) { + void PrepareAndSendReceiverStartReady(LeAudioDevice* leAudioDevice, struct ase* ase) { std::vector ids; std::vector value; std::stringstream stream; @@ -2834,29 +2603,25 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { stream << kLogAseStartReadyOp; do { - if (ase->direction == - bluetooth::le_audio::types::kLeAudioDirectionSource) { + if (ase->direction == bluetooth::le_audio::types::kLeAudioDirectionSource) { stream << "ASE_ID " << +ase->id << ","; ids.push_back(ase->id); } } while ((ase = leAudioDevice->GetNextActiveAse(ase))); if (ids.size() > 0) { - bluetooth::le_audio::client_parser::ascs:: - PrepareAseCtpAudioReceiverStartReady(ids, value); + bluetooth::le_audio::client_parser::ascs::PrepareAseCtpAudioReceiverStartReady(ids, value); WriteToControlPoint(leAudioDevice, value); - log::info("group_id: {}, {}", leAudioDevice->group_id_, - leAudioDevice->address_); + log::info("group_id: {}, {}", leAudioDevice->group_id_, leAudioDevice->address_); log_history_->AddLogHistory(kLogControlPointCmd, leAudioDevice->group_id_, leAudioDevice->address_, stream.str()); } } void AseStateMachineProcessEnabling( - struct bluetooth::le_audio::client_parser::ascs::ase_rsp_hdr& arh, - struct ase* ase, LeAudioDeviceGroup* group, - LeAudioDevice* leAudioDevice) { + struct bluetooth::le_audio::client_parser::ascs::ase_rsp_hdr& arh, struct ase* ase, + LeAudioDeviceGroup* group, LeAudioDevice* leAudioDevice) { if (!group) { log::error("leAudioDevice doesn't belong to any group"); return; @@ -2864,13 +2629,11 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { switch (ase->state) { case AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED: - SetAseState(leAudioDevice, ase, - AseState::BTA_LE_AUDIO_ASE_STATE_ENABLING); + SetAseState(leAudioDevice, ase, AseState::BTA_LE_AUDIO_ASE_STATE_ENABLING); - if (group->GetTargetState() != - AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) { - log::warn("{}, ase_id: {}, target state: {}", leAudioDevice->address_, - ase->id, ToString(group->GetTargetState())); + if (group->GetTargetState() != AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) { + log::warn("{}, ase_id: {}, target state: {}", leAudioDevice->address_, ase->id, + ToString(group->GetTargetState())); group->PrintDebugState(); return; } @@ -2900,17 +2663,16 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { * to streaming state. */ struct ase* ase = leAudioDevice->GetFirstActiveAse(); - log::assert_that( - ase != nullptr, - "shouldn't be called without an active ASE, device {}", - leAudioDevice->address_.ToString()); + log::assert_that(ase != nullptr, "shouldn't be called without an active ASE, device {}", + leAudioDevice->address_.ToString()); PrepareAndSendReceiverStartReady(leAudioDevice, ase); return; } - if (leAudioDevice->IsReadyToCreateStream()) + if (leAudioDevice->IsReadyToCreateStream()) { ProcessGroupEnable(group); + } break; @@ -2918,8 +2680,7 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { /* Enable/Switch Content */ break; default: - log::error("invalid state transition, from: {}, to: {}", - static_cast(ase->state), + log::error("invalid state transition, from: {}, to: {}", static_cast(ase->state), static_cast(AseState::BTA_LE_AUDIO_ASE_STATE_ENABLING)); StopStream(group); break; @@ -2927,9 +2688,8 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { } void AseStateMachineProcessStreaming( - struct bluetooth::le_audio::client_parser::ascs::ase_rsp_hdr& arh, - struct ase* ase, uint8_t* data, uint16_t len, LeAudioDeviceGroup* group, - LeAudioDevice* leAudioDevice) { + struct bluetooth::le_audio::client_parser::ascs::ase_rsp_hdr& arh, struct ase* ase, + uint8_t* data, uint16_t len, LeAudioDeviceGroup* group, LeAudioDevice* leAudioDevice) { if (!group) { log::error("leAudioDevice doesn't belong to any group"); @@ -2938,10 +2698,8 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { switch (ase->state) { case AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED: - log::error( - "{}, ase_id: {}, moving from QoS Configured to Streaming is " - "impossible.", - leAudioDevice->address_, ase->id); + log::error("{}, ase_id: {}, moving from QoS Configured to Streaming is impossible.", + leAudioDevice->address_, ase->id); group->PrintDebugState(); StopStream(group); break; @@ -2949,11 +2707,10 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { case AseState::BTA_LE_AUDIO_ASE_STATE_ENABLING: { std::vector value; - SetAseState(leAudioDevice, ase, - AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + SetAseState(leAudioDevice, ase, AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); if (!group->HaveAllActiveDevicesAsesTheSameState( - AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING)) { + AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING)) { /* More ASEs notification form this device has to come for this group */ return; @@ -2961,11 +2718,10 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { if (group->GetState() == AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) { /* We are here because of the reconnection of the single device */ - log::info("{}, Ase id: {}, ase state: {}", leAudioDevice->address_, - ase->id, bluetooth::common::ToString(ase->state)); + log::info("{}, Ase id: {}, ase state: {}", leAudioDevice->address_, ase->id, + bluetooth::common::ToString(ase->state)); cancel_watchdog_if_needed(group->group_id_); - state_machine_callbacks_->StatusReportCb( - group->group_id_, GroupStreamStatus::STREAMING); + state_machine_callbacks_->StatusReportCb(group->group_id_, GroupStreamStatus::STREAMING); return; } @@ -2976,29 +2732,25 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { return; } - if (group->GetTargetState() == - AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) { + if (group->GetTargetState() == AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) { /* No more transition for group */ cancel_watchdog_if_needed(group->group_id_); /* Last node is in streaming state */ group->SetState(AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); - state_machine_callbacks_->StatusReportCb( - group->group_id_, GroupStreamStatus::STREAMING); + state_machine_callbacks_->StatusReportCb(group->group_id_, GroupStreamStatus::STREAMING); return; } - log::error(", invalid state transition, from: {}, to: {}", - ToString(group->GetState()), + log::error(", invalid state transition, from: {}, to: {}", ToString(group->GetState()), ToString(group->GetTargetState())); StopStream(group); break; } case AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING: { - struct bluetooth::le_audio::client_parser::ascs:: - ase_transient_state_params rsp; + struct bluetooth::le_audio::client_parser::ascs::ase_transient_state_params rsp; if (!ParseAseStatusTransientStateParams(rsp, len, data)) { StopStream(group); @@ -3015,19 +2767,16 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { break; } default: - log::error( - "invalid state transition, from: {}, to: {}", - static_cast(ase->state), - static_cast(AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING)); + log::error("invalid state transition, from: {}, to: {}", static_cast(ase->state), + static_cast(AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING)); StopStream(group); break; } } void AseStateMachineProcessDisabling( - struct bluetooth::le_audio::client_parser::ascs::ase_rsp_hdr& arh, - struct ase* ase, LeAudioDeviceGroup* group, - LeAudioDevice* leAudioDevice) { + struct bluetooth::le_audio::client_parser::ascs::ase_rsp_hdr& arh, struct ase* ase, + LeAudioDeviceGroup* group, LeAudioDevice* leAudioDevice) { if (!group) { log::error("leAudioDevice doesn't belong to any group"); @@ -3036,8 +2785,7 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { if (ase->direction == bluetooth::le_audio::types::kLeAudioDirectionSink) { /* Sink ASE state machine does not have Disabling state */ - log::error(", invalid state transition, from: {} , to: {}", - ToString(group->GetState()), + log::error(", invalid state transition, from: {} , to: {}", ToString(group->GetState()), ToString(group->GetTargetState())); StopStream(group); return; @@ -3048,27 +2796,25 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { /* TODO: Disable */ break; case AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING: - SetAseState(leAudioDevice, ase, - AseState::BTA_LE_AUDIO_ASE_STATE_DISABLING); + SetAseState(leAudioDevice, ase, AseState::BTA_LE_AUDIO_ASE_STATE_DISABLING); /* Remote may autonomously bring ASEs to QoS configured state */ - if (group->GetTargetState() != - AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED) { + if (group->GetTargetState() != AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED) { ProcessAutonomousDisable(group, leAudioDevice, ase); return; } /* Process the Disable Transition of the rest of group members if no * more ASE notifications has to come from this device. */ - if (leAudioDevice->IsReadyToSuspendStream()) ProcessGroupDisable(group); + if (leAudioDevice->IsReadyToSuspendStream()) { + ProcessGroupDisable(group); + } break; default: - log::error( - "invalid state transition, from: {}, to: {}", - static_cast(ase->state), - static_cast(AseState::BTA_LE_AUDIO_ASE_STATE_DISABLING)); + log::error("invalid state transition, from: {}, to: {}", static_cast(ase->state), + static_cast(AseState::BTA_LE_AUDIO_ASE_STATE_DISABLING)); StopStream(group); break; } @@ -3081,20 +2827,16 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { } LocalCisDisconnectResult_t; LocalCisDisconnectResult_t DisconnectCisIfNeeded(LeAudioDeviceGroup* group, - LeAudioDevice* leAudioDevice, - struct ase* ase) { + LeAudioDevice* leAudioDevice, struct ase* ase) { log::debug( - "Group id: {}, {}, ase id: {}, cis_handle: 0x{:04x}, direction: {}, " - "data_path_state: {}, cis_state: {}", - group->group_id_, leAudioDevice->address_, ase->id, ase->cis_conn_hdl, - ase->direction == bluetooth::le_audio::types::kLeAudioDirectionSink - ? "sink" - : "source", - bluetooth::common::ToString(ase->data_path_state), - bluetooth::common::ToString(ase->cis_state)); - - if (ase->cis_state == CisState::IDLE || - ase->cis_state == CisState::ASSIGNED) { + "Group id: {}, {}, ase id: {}, cis_handle: 0x{:04x}, direction: {}, " + "data_path_state: {}, cis_state: {}", + group->group_id_, leAudioDevice->address_, ase->id, ase->cis_conn_hdl, + ase->direction == bluetooth::le_audio::types::kLeAudioDirectionSink ? "sink" : "source", + bluetooth::common::ToString(ase->data_path_state), + bluetooth::common::ToString(ase->cis_state)); + + if (ase->cis_state == CisState::IDLE || ase->cis_state == CisState::ASSIGNED) { return CIS_DISCONNECTED; } @@ -3104,30 +2846,24 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { } auto bidirection_ase = leAudioDevice->GetAseToMatchBidirectionCis(ase); - if (bidirection_ase != nullptr && - bidirection_ase->cis_state == CisState::CONNECTED && + if (bidirection_ase != nullptr && bidirection_ase->cis_state == CisState::CONNECTED && (bidirection_ase->state == AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING || bidirection_ase->state == AseState::BTA_LE_AUDIO_ASE_STATE_ENABLING)) { - log::info( - "Still waiting for the bidirectional ase {} to be released ({})", - bidirection_ase->id, - bluetooth::common::ToString(bidirection_ase->state)); + log::info("Still waiting for the bidirectional ase {} to be released ({})", + bidirection_ase->id, bluetooth::common::ToString(bidirection_ase->state)); return CIS_STILL_NEEDED; } group->RemoveCisFromStreamIfNeeded(leAudioDevice, ase->cis_conn_hdl); - IsoManager::GetInstance()->DisconnectCis(ase->cis_conn_hdl, - HCI_ERR_PEER_USER); - log_history_->AddLogHistory( - kLogStateMachineTag, group->group_id_, leAudioDevice->address_, - kLogCisDisconnectOp + "cis_h:" + loghex(ase->cis_conn_hdl)); + IsoManager::GetInstance()->DisconnectCis(ase->cis_conn_hdl, HCI_ERR_PEER_USER); + log_history_->AddLogHistory(kLogStateMachineTag, group->group_id_, leAudioDevice->address_, + kLogCisDisconnectOp + "cis_h:" + loghex(ase->cis_conn_hdl)); return CIS_DISCONNECTING; } void AseStateMachineProcessReleasing( - struct bluetooth::le_audio::client_parser::ascs::ase_rsp_hdr& arh, - struct ase* ase, LeAudioDeviceGroup* group, - LeAudioDevice* leAudioDevice) { + struct bluetooth::le_audio::client_parser::ascs::ase_rsp_hdr& arh, struct ase* ase, + LeAudioDeviceGroup* group, LeAudioDevice* leAudioDevice) { if (!group) { log::error("leAudioDevice doesn't belong to any group"); @@ -3138,16 +2874,14 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { case AseState::BTA_LE_AUDIO_ASE_STATE_DISABLING: case AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED: case AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED: { - SetAseState(leAudioDevice, ase, - AseState::BTA_LE_AUDIO_ASE_STATE_RELEASING); + SetAseState(leAudioDevice, ase, AseState::BTA_LE_AUDIO_ASE_STATE_RELEASING); if (group->HaveAllActiveDevicesAsesTheSameState( - AseState::BTA_LE_AUDIO_ASE_STATE_RELEASING)) { + AseState::BTA_LE_AUDIO_ASE_STATE_RELEASING)) { group->SetState(AseState::BTA_LE_AUDIO_ASE_STATE_RELEASING); } - bool remove_cig = (DisconnectCisIfNeeded(group, leAudioDevice, ase) == - CIS_DISCONNECTED); + bool remove_cig = (DisconnectCisIfNeeded(group, leAudioDevice, ase) == CIS_DISCONNECTED); if (remove_cig && group->cig.GetState() == CigState::CREATED && group->HaveAllCisesDisconnected() && @@ -3158,14 +2892,12 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { break; } case AseState::BTA_LE_AUDIO_ASE_STATE_ENABLING: { - SetAseState(leAudioDevice, ase, - AseState::BTA_LE_AUDIO_ASE_STATE_RELEASING); + SetAseState(leAudioDevice, ase, AseState::BTA_LE_AUDIO_ASE_STATE_RELEASING); - bool remove_cig = (DisconnectCisIfNeeded(group, leAudioDevice, ase) == - CIS_DISCONNECTED); + bool remove_cig = (DisconnectCisIfNeeded(group, leAudioDevice, ase) == CIS_DISCONNECTED); if (!group->HaveAllActiveDevicesAsesTheSameState( - AseState::BTA_LE_AUDIO_ASE_STATE_RELEASING)) { + AseState::BTA_LE_AUDIO_ASE_STATE_RELEASING)) { return; } group->SetState(AseState::BTA_LE_AUDIO_ASE_STATE_RELEASING); @@ -3178,11 +2910,12 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { break; } case AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING: { - SetAseState(leAudioDevice, ase, - AseState::BTA_LE_AUDIO_ASE_STATE_RELEASING); + SetAseState(leAudioDevice, ase, AseState::BTA_LE_AUDIO_ASE_STATE_RELEASING); /* Happens when bi-directional completive ASE releasing state came */ - if (ase->cis_state == CisState::DISCONNECTING) break; + if (ase->cis_state == CisState::DISCONNECTING) { + break; + } if (ase->data_path_state == DataPathState::CONFIGURED) { RemoveDataPathByCisHandle(leAudioDevice, ase->cis_conn_hdl); @@ -3209,10 +2942,8 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { break; } default: - log::error( - "invalid state transition, from: {}, to: {}", - static_cast(ase->state), - static_cast(AseState::BTA_LE_AUDIO_ASE_STATE_RELEASING)); + log::error("invalid state transition, from: {}, to: {}", static_cast(ase->state), + static_cast(AseState::BTA_LE_AUDIO_ASE_STATE_RELEASING)); break; } } @@ -3221,9 +2952,7 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { if (group->GetState() != AseState::BTA_LE_AUDIO_ASE_STATE_ENABLING) { /* Check if the group is ready to create stream. If not, keep waiting. */ if (!group->IsGroupReadyToCreateStream()) { - log::debug( - "Waiting for more ASEs to be in enabling or directly in streaming " - "state"); + log::debug("Waiting for more ASEs to be in enabling or directly in streaming state"); return; } @@ -3233,8 +2962,7 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { /* If Target State is not streaming, then something is wrong. */ if (group->GetTargetState() != AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) { - log::error(", invalid state transition, from: {} , to: {}", - ToString(group->GetState()), + log::error(", invalid state transition, from: {} , to: {}", ToString(group->GetState()), ToString(group->GetTargetState())); StopStream(group); return; @@ -3261,31 +2989,28 @@ class LeAudioGroupStateMachineImpl : public LeAudioGroupStateMachine { * active ASEs are Sink ASE and will transit to QoS state. So check * the group state, because we might be ready to release data path. */ if (group->HaveAllActiveDevicesAsesTheSameState( - AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED)) { + AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED)) { group->SetState(AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED); } /* Transition to QoS configured is done by CIS disconnection */ - if (group->GetTargetState() == - AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED) { + if (group->GetTargetState() == AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED) { ReleaseDataPath(group); } else { - log::error(", invalid state transition, from: {} , to: {}", - ToString(group->GetState()), + log::error(", invalid state transition, from: {} , to: {}", ToString(group->GetState()), ToString(group->GetTargetState())); StopStream(group); } } - void ProcessAutonomousDisable(LeAudioDeviceGroup* group, - LeAudioDevice* leAudioDevice, struct ase* ase) { + void ProcessAutonomousDisable(LeAudioDeviceGroup* group, LeAudioDevice* leAudioDevice, + struct ase* ase) { /* If there is any streaming ASE and connected CIS, there is nothing to do. * Otherwise, Release all the ASEs. */ log::info("{}, ase {}", leAudioDevice->address_, ase->id); - if (group->HaveAnyActiveDeviceInStreamingState() && - !group->HaveAllCisesDisconnected()) { + if (group->HaveAnyActiveDeviceInStreamingState() && !group->HaveAllCisesDisconnected()) { log::info("There is still some ASE streaming, do nothing"); return; } @@ -3307,7 +3032,9 @@ void LeAudioGroupStateMachine::Initialize(Callbacks* state_machine_callbacks_) { } void LeAudioGroupStateMachine::Cleanup() { - if (!instance) return; + if (!instance) { + return; + } LeAudioGroupStateMachineImpl* ptr = instance; instance = nullptr; diff --git a/system/bta/le_audio/state_machine.h b/system/bta/le_audio/state_machine.h index bc11f0e1983..d5b49aebf6f 100644 --- a/system/bta/le_audio/state_machine.h +++ b/system/bta/le_audio/state_machine.h @@ -30,13 +30,12 @@ namespace bluetooth::le_audio { /* State machine interface */ class LeAudioGroupStateMachine { - public: +public: class Callbacks { - public: + public: virtual ~Callbacks() = default; - virtual void StatusReportCb( - int group_id, bluetooth::le_audio::GroupStreamStatus status) = 0; + virtual void StatusReportCb(int group_id, bluetooth::le_audio::GroupStreamStatus status) = 0; virtual void OnStateTransitionTimeout(int group_id) = 0; virtual void OnUpdatedCisConfiguration(int group_id, uint8_t direction) = 0; }; @@ -47,55 +46,45 @@ class LeAudioGroupStateMachine { static void Cleanup(void); static LeAudioGroupStateMachine* Get(void); - virtual bool AttachToStream( - LeAudioDeviceGroup* group, LeAudioDevice* leAudioDevice, - types::BidirectionalPair> ccids) = 0; + virtual bool AttachToStream(LeAudioDeviceGroup* group, LeAudioDevice* leAudioDevice, + types::BidirectionalPair> ccids) = 0; virtual bool StartStream( - LeAudioDeviceGroup* group, types::LeAudioContextType context_type, - const types::BidirectionalPair& - metadata_context_types, - types::BidirectionalPair> ccid_lists = { - .sink = {}, .source = {}}) = 0; + LeAudioDeviceGroup* group, types::LeAudioContextType context_type, + const types::BidirectionalPair& metadata_context_types, + types::BidirectionalPair> ccid_lists = {.sink = {}, + .source = {}}) = 0; virtual void SuspendStream(LeAudioDeviceGroup* group) = 0; virtual bool ConfigureStream( - LeAudioDeviceGroup* group, types::LeAudioContextType context_type, - const types::BidirectionalPair& - metadata_context_types, - types::BidirectionalPair> ccid_lists = { - .sink = {}, .source = {}}) = 0; + LeAudioDeviceGroup* group, types::LeAudioContextType context_type, + const types::BidirectionalPair& metadata_context_types, + types::BidirectionalPair> ccid_lists = {.sink = {}, + .source = {}}) = 0; virtual void StopStream(LeAudioDeviceGroup* group) = 0; - virtual void ProcessGattCtpNotification(LeAudioDeviceGroup* group, - uint8_t* value, uint16_t len) = 0; - virtual void ProcessGattNotifEvent(uint8_t* value, uint16_t len, - struct types::ase* ase, - LeAudioDevice* leAudioDevice, - LeAudioDeviceGroup* group) = 0; + virtual void ProcessGattCtpNotification(LeAudioDeviceGroup* group, uint8_t* value, + uint16_t len) = 0; + virtual void ProcessGattNotifEvent(uint8_t* value, uint16_t len, struct types::ase* ase, + LeAudioDevice* leAudioDevice, LeAudioDeviceGroup* group) = 0; - virtual void ProcessHciNotifOnCigCreate( - LeAudioDeviceGroup* group, uint8_t status, uint8_t cig_id, - std::vector conn_handles) = 0; - virtual void ProcessHciNotifOnCigRemove(uint8_t status, - LeAudioDeviceGroup* group) = 0; + virtual void ProcessHciNotifOnCigCreate(LeAudioDeviceGroup* group, uint8_t status, uint8_t cig_id, + std::vector conn_handles) = 0; + virtual void ProcessHciNotifOnCigRemove(uint8_t status, LeAudioDeviceGroup* group) = 0; virtual void ProcessHciNotifCisEstablished( - LeAudioDeviceGroup* group, LeAudioDevice* leAudioDevice, - const bluetooth::hci::iso_manager::cis_establish_cmpl_evt* event) = 0; + LeAudioDeviceGroup* group, LeAudioDevice* leAudioDevice, + const bluetooth::hci::iso_manager::cis_establish_cmpl_evt* event) = 0; virtual void ProcessHciNotifCisDisconnected( - LeAudioDeviceGroup* group, LeAudioDevice* leAudioDevice, - const bluetooth::hci::iso_manager::cis_disconnected_evt* event) = 0; + LeAudioDeviceGroup* group, LeAudioDevice* leAudioDevice, + const bluetooth::hci::iso_manager::cis_disconnected_evt* event) = 0; virtual void ProcessHciNotifSetupIsoDataPath(LeAudioDeviceGroup* group, - LeAudioDevice* leAudioDevice, - uint8_t status, + LeAudioDevice* leAudioDevice, uint8_t status, uint16_t conn_hdl) = 0; virtual void ProcessHciNotifRemoveIsoDataPath(LeAudioDeviceGroup* group, - LeAudioDevice* leAudioDevice, - uint8_t status, + LeAudioDevice* leAudioDevice, uint8_t status, uint16_t conn_hdl) = 0; virtual void ProcessHciNotifIsoLinkQualityRead( - LeAudioDeviceGroup* group, LeAudioDevice* leAudioDevice, - uint8_t conn_handle, uint32_t txUnackedPackets, uint32_t txFlushedPackets, - uint32_t txLastSubeventPackets, uint32_t retransmittedPackets, - uint32_t crcErrorPackets, uint32_t rxUnreceivedPackets, - uint32_t duplicatePackets) = 0; + LeAudioDeviceGroup* group, LeAudioDevice* leAudioDevice, uint8_t conn_handle, + uint32_t txUnackedPackets, uint32_t txFlushedPackets, uint32_t txLastSubeventPackets, + uint32_t retransmittedPackets, uint32_t crcErrorPackets, uint32_t rxUnreceivedPackets, + uint32_t duplicatePackets) = 0; virtual void ProcessHciNotifAclDisconnected(LeAudioDeviceGroup* group, LeAudioDevice* leAudioDevice) = 0; }; diff --git a/system/bta/le_audio/state_machine_test.cc b/system/bta/le_audio/state_machine_test.cc index 1907e7c0bee..a3d4bfae683 100644 --- a/system/bta/le_audio/state_machine_test.cc +++ b/system/bta/le_audio/state_machine_test.cc @@ -44,10 +44,8 @@ #include "types/bt_transport.h" using ::bluetooth::le_audio::DeviceConnectState; -using ::bluetooth::le_audio::codec_spec_caps:: - kLeAudioCodecChannelCountSingleChannel; -using ::bluetooth::le_audio::codec_spec_caps:: - kLeAudioCodecChannelCountTwoChannel; +using ::bluetooth::le_audio::codec_spec_caps::kLeAudioCodecChannelCountSingleChannel; +using ::bluetooth::le_audio::codec_spec_caps::kLeAudioCodecChannelCountTwoChannel; using ::bluetooth::le_audio::types::LeAudioContextType; using ::testing::_; using ::testing::AnyNumber; @@ -86,30 +84,24 @@ bool get_pts_le_audio_disable_ases_before_stopping(void) { return false; } config_t* get_all(void) { return nullptr; } stack_config_t mock_stack_config{ - .get_pts_avrcp_test = get_pts_avrcp_test, - .get_pts_secure_only_mode = get_pts_secure_only_mode, - .get_pts_conn_updates_disabled = get_pts_conn_updates_disabled, - .get_pts_crosskey_sdp_disable = get_pts_crosskey_sdp_disable, - .get_pts_smp_options = get_pts_smp_options, - .get_pts_smp_failure_case = get_pts_smp_failure_case, - .get_pts_force_eatt_for_notifications = - get_pts_force_eatt_for_notifications, - .get_pts_connect_eatt_unconditionally = - get_pts_connect_eatt_unconditionally, - .get_pts_connect_eatt_before_encryption = - get_pts_connect_eatt_before_encryption, - .get_pts_unencrypt_broadcast = get_pts_unencrypt_broadcast, - .get_pts_eatt_peripheral_collision_support = - get_pts_eatt_peripheral_collision_support, - .get_pts_force_le_audio_multiple_contexts_metadata = - get_pts_force_le_audio_multiple_contexts_metadata, - .get_pts_le_audio_disable_ases_before_stopping = - get_pts_le_audio_disable_ases_before_stopping, - .get_all = get_all, + .get_pts_avrcp_test = get_pts_avrcp_test, + .get_pts_secure_only_mode = get_pts_secure_only_mode, + .get_pts_conn_updates_disabled = get_pts_conn_updates_disabled, + .get_pts_crosskey_sdp_disable = get_pts_crosskey_sdp_disable, + .get_pts_smp_options = get_pts_smp_options, + .get_pts_smp_failure_case = get_pts_smp_failure_case, + .get_pts_force_eatt_for_notifications = get_pts_force_eatt_for_notifications, + .get_pts_connect_eatt_unconditionally = get_pts_connect_eatt_unconditionally, + .get_pts_connect_eatt_before_encryption = get_pts_connect_eatt_before_encryption, + .get_pts_unencrypt_broadcast = get_pts_unencrypt_broadcast, + .get_pts_eatt_peripheral_collision_support = get_pts_eatt_peripheral_collision_support, + .get_pts_force_le_audio_multiple_contexts_metadata = + get_pts_force_le_audio_multiple_contexts_metadata, + .get_pts_le_audio_disable_ases_before_stopping = + get_pts_le_audio_disable_ases_before_stopping, + .get_all = get_all, }; -const stack_config_t* stack_config_get_interface(void) { - return &mock_stack_config; -} +const stack_config_t* stack_config_get_interface(void) { return &mock_stack_config; } namespace bluetooth::le_audio { namespace internal { @@ -118,18 +110,12 @@ namespace internal { #define ATTR_HANDLE_ASCS_POOL_START (0x0000 | 32) #define ATTR_HANDLE_PACS_POOL_START (0xFF00 | 64) -constexpr LeAudioContextType kContextTypeUnspecified = - static_cast(0x0001); -constexpr LeAudioContextType kContextTypeConversational = - static_cast(0x0002); -constexpr LeAudioContextType kContextTypeMedia = - static_cast(0x0004); -constexpr LeAudioContextType kContextTypeLive = - static_cast(0x0040); -constexpr LeAudioContextType kContextTypeSoundEffects = - static_cast(0x0080); -constexpr LeAudioContextType kContextTypeRingtone = - static_cast(0x0200); +constexpr LeAudioContextType kContextTypeUnspecified = static_cast(0x0001); +constexpr LeAudioContextType kContextTypeConversational = static_cast(0x0002); +constexpr LeAudioContextType kContextTypeMedia = static_cast(0x0004); +constexpr LeAudioContextType kContextTypeLive = static_cast(0x0040); +constexpr LeAudioContextType kContextTypeSoundEffects = static_cast(0x0080); +constexpr LeAudioContextType kContextTypeRingtone = static_cast(0x0200); namespace codec_specific { @@ -185,62 +171,55 @@ constexpr uint8_t kAseCtpOpcodeMaxVal = client_parser::ascs::kCtpOpcodeRelease; } // namespace ascs -static RawAddress GetTestAddress(uint8_t index) { - return {{0xC0, 0xDE, 0xC0, 0xDE, 0x00, index}}; -} +static RawAddress GetTestAddress(uint8_t index) { return {{0xC0, 0xDE, 0xC0, 0xDE, 0x00, index}}; } -class MockLeAudioGroupStateMachineCallbacks - : public LeAudioGroupStateMachine::Callbacks { - public: +class MockLeAudioGroupStateMachineCallbacks : public LeAudioGroupStateMachine::Callbacks { +public: MockLeAudioGroupStateMachineCallbacks() = default; - MockLeAudioGroupStateMachineCallbacks( - const MockLeAudioGroupStateMachineCallbacks&) = delete; - MockLeAudioGroupStateMachineCallbacks& operator=( - const MockLeAudioGroupStateMachineCallbacks&) = delete; + MockLeAudioGroupStateMachineCallbacks(const MockLeAudioGroupStateMachineCallbacks&) = delete; + MockLeAudioGroupStateMachineCallbacks& operator=(const MockLeAudioGroupStateMachineCallbacks&) = + delete; ~MockLeAudioGroupStateMachineCallbacks() override = default; - MOCK_METHOD((void), StatusReportCb, - (int group_id, bluetooth::le_audio::GroupStreamStatus status), + MOCK_METHOD((void), StatusReportCb, (int group_id, bluetooth::le_audio::GroupStreamStatus status), (override)); MOCK_METHOD((void), OnStateTransitionTimeout, (int group_id), (override)); - MOCK_METHOD((void), OnUpdatedCisConfiguration, - (int group_id, uint8_t direction), (override)); + MOCK_METHOD((void), OnUpdatedCisConfiguration, (int group_id, uint8_t direction), (override)); }; class MockAseRemoteStateMachine { - public: +public: MockAseRemoteStateMachine() = default; - MockAseRemoteStateMachine& operator=(const MockAseRemoteStateMachine&) = - delete; + MockAseRemoteStateMachine& operator=(const MockAseRemoteStateMachine&) = delete; ~MockAseRemoteStateMachine() = default; MOCK_METHOD((void), AseCtpConfigureCodecHandler, - (LeAudioDevice * device, std::vector value, - GATT_WRITE_OP_CB cb, void* cb_data)); + (LeAudioDevice * device, std::vector value, GATT_WRITE_OP_CB cb, + void* cb_data)); MOCK_METHOD((void), AseCtpConfigureQosHandler, - (LeAudioDevice * device, std::vector value, - GATT_WRITE_OP_CB cb, void* cb_data)); + (LeAudioDevice * device, std::vector value, GATT_WRITE_OP_CB cb, + void* cb_data)); MOCK_METHOD((void), AseCtpEnableHandler, - (LeAudioDevice * device, std::vector value, - GATT_WRITE_OP_CB cb, void* cb_data)); + (LeAudioDevice * device, std::vector value, GATT_WRITE_OP_CB cb, + void* cb_data)); MOCK_METHOD((void), AseCtpReceiverStartReadyHandler, - (LeAudioDevice * device, std::vector value, - GATT_WRITE_OP_CB cb, void* cb_data)); + (LeAudioDevice * device, std::vector value, GATT_WRITE_OP_CB cb, + void* cb_data)); MOCK_METHOD((void), AseCtpDisableHandler, - (LeAudioDevice * device, std::vector value, - GATT_WRITE_OP_CB cb, void* cb_data)); + (LeAudioDevice * device, std::vector value, GATT_WRITE_OP_CB cb, + void* cb_data)); MOCK_METHOD((void), AseCtpReceiverStopReadyHandler, - (LeAudioDevice * device, std::vector value, - GATT_WRITE_OP_CB cb, void* cb_data)); + (LeAudioDevice * device, std::vector value, GATT_WRITE_OP_CB cb, + void* cb_data)); MOCK_METHOD((void), AseCtpUpdateMetadataHandler, - (LeAudioDevice * device, std::vector value, - GATT_WRITE_OP_CB cb, void* cb_data)); + (LeAudioDevice * device, std::vector value, GATT_WRITE_OP_CB cb, + void* cb_data)); MOCK_METHOD((void), AseCtpReleaseHandler, - (LeAudioDevice * device, std::vector value, - GATT_WRITE_OP_CB cb, void* cb_data)); + (LeAudioDevice * device, std::vector value, GATT_WRITE_OP_CB cb, + void* cb_data)); }; class StateMachineTestBase : public Test { - protected: +protected: uint8_t ase_id_last_assigned = types::ase::kAseIdInvalid; uint8_t additional_snk_ases = 0; uint8_t additional_src_ases = 0; @@ -249,11 +228,11 @@ class StateMachineTestBase : public Test { uint16_t sample_freq_ = codec_specific::kCapSamplingFrequency16000Hz | codec_specific::kCapSamplingFrequency32000Hz; uint8_t channel_allocations_sink_ = - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft | - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight; + ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft | + ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight; uint8_t channel_allocations_source_ = - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft | - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight; + ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft | + ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight; /* Use to simulated error status on Cis creation */ bool overwrite_cis_status_; @@ -291,59 +270,53 @@ class StateMachineTestBase : public Test { ContentControlIdKeeper::GetInstance()->Start(); ON_CALL(mock_callbacks_, StatusReportCb(_, _)) - .WillByDefault(Invoke( - [](int group_id, bluetooth::le_audio::GroupStreamStatus status) { - log::debug("[Testing] StatusReportCb: group id: {}, status: {}", - group_id, status); + .WillByDefault(Invoke([](int group_id, bluetooth::le_audio::GroupStreamStatus status) { + log::debug("[Testing] StatusReportCb: group id: {}, status: {}", group_id, status); })); MockCsisClient::SetMockInstanceForTesting(&mock_csis_client_module_); - ON_CALL(mock_csis_client_module_, Get()) - .WillByDefault(Return(&mock_csis_client_module_)); - ON_CALL(mock_csis_client_module_, IsCsisClientRunning()) - .WillByDefault(Return(true)); - ON_CALL(mock_csis_client_module_, GetDeviceList(_)) - .WillByDefault(Invoke([this](int group_id) { return addresses_; })); - ON_CALL(mock_csis_client_module_, GetDesiredSize(_)) - .WillByDefault( - Invoke([this](int group_id) { return (int)(addresses_.size()); })); + ON_CALL(mock_csis_client_module_, Get()).WillByDefault(Return(&mock_csis_client_module_)); + ON_CALL(mock_csis_client_module_, IsCsisClientRunning()).WillByDefault(Return(true)); + ON_CALL(mock_csis_client_module_, GetDeviceList(_)).WillByDefault(Invoke([this](int group_id) { + return addresses_; + })); + ON_CALL(mock_csis_client_module_, GetDesiredSize(_)).WillByDefault(Invoke([this](int group_id) { + return (int)(addresses_.size()); + })); // Support 2M Phy ON_CALL(btm_interface, IsPhy2mSupported(_, _)).WillByDefault(Return(true)); ON_CALL(btm_interface, GetHCIConnHandle(_, _)) - .WillByDefault( - Invoke([](RawAddress const& remote_bda, tBT_TRANSPORT transport) { + .WillByDefault(Invoke([](RawAddress const& remote_bda, tBT_TRANSPORT transport) { return remote_bda.IsEmpty() - ? HCI_INVALID_HANDLE - : ((uint16_t)(remote_bda.address[0] ^ - remote_bda.address[1] ^ - remote_bda.address[2])) - << 8 | - (remote_bda.address[3] ^ remote_bda.address[4] ^ - remote_bda.address[5]); + ? HCI_INVALID_HANDLE + : ((uint16_t)(remote_bda.address[0] ^ remote_bda.address[1] ^ + remote_bda.address[2])) + << 8 | + (remote_bda.address[3] ^ remote_bda.address[4] ^ + remote_bda.address[5]); })); ON_CALL(gatt_queue, WriteCharacteristic(_, _, _, GATT_WRITE_NO_RSP, _, _)) - .WillByDefault(Invoke([this](uint16_t conn_id, uint16_t handle, - std::vector value, - tGATT_WRITE_TYPE write_type, - GATT_WRITE_OP_CB cb, void* cb_data) { - for (auto& dev : le_audio_devices_) { - if (dev->conn_id_ == conn_id) { - // Control point write handler - if (dev->ctp_hdls_.val_hdl == handle) { - HandleCtpOperation(dev.get(), value, cb, cb_data); - } - break; - } - } - })); + .WillByDefault( + Invoke([this](uint16_t conn_id, uint16_t handle, std::vector value, + tGATT_WRITE_TYPE write_type, GATT_WRITE_OP_CB cb, void* cb_data) { + for (auto& dev : le_audio_devices_) { + if (dev->conn_id_ == conn_id) { + // Control point write handler + if (dev->ctp_hdls_.val_hdl == handle) { + HandleCtpOperation(dev.get(), value, cb, cb_data); + } + break; + } + } + })); ConfigureIsoManagerMock(); } - void HandleCtpOperation(LeAudioDevice* device, std::vector value, - GATT_WRITE_OP_CB cb, void* cb_data) { + void HandleCtpOperation(LeAudioDevice* device, std::vector value, GATT_WRITE_OP_CB cb, + void* cb_data) { auto opcode = value[0]; // Verify against valid opcode range @@ -352,36 +325,28 @@ class StateMachineTestBase : public Test { switch (opcode) { case client_parser::ascs::kCtpOpcodeCodecConfiguration: - ase_ctp_handler.AseCtpConfigureCodecHandler(device, std::move(value), - cb, cb_data); + ase_ctp_handler.AseCtpConfigureCodecHandler(device, std::move(value), cb, cb_data); break; case client_parser::ascs::kCtpOpcodeQosConfiguration: - ase_ctp_handler.AseCtpConfigureQosHandler(device, std::move(value), cb, - cb_data); + ase_ctp_handler.AseCtpConfigureQosHandler(device, std::move(value), cb, cb_data); break; case client_parser::ascs::kCtpOpcodeEnable: - ase_ctp_handler.AseCtpEnableHandler(device, std::move(value), cb, - cb_data); + ase_ctp_handler.AseCtpEnableHandler(device, std::move(value), cb, cb_data); break; case client_parser::ascs::kCtpOpcodeReceiverStartReady: - ase_ctp_handler.AseCtpReceiverStartReadyHandler( - device, std::move(value), cb, cb_data); + ase_ctp_handler.AseCtpReceiverStartReadyHandler(device, std::move(value), cb, cb_data); break; case client_parser::ascs::kCtpOpcodeDisable: - ase_ctp_handler.AseCtpDisableHandler(device, std::move(value), cb, - cb_data); + ase_ctp_handler.AseCtpDisableHandler(device, std::move(value), cb, cb_data); break; case client_parser::ascs::kCtpOpcodeReceiverStopReady: - ase_ctp_handler.AseCtpReceiverStopReadyHandler(device, std::move(value), - cb, cb_data); + ase_ctp_handler.AseCtpReceiverStopReadyHandler(device, std::move(value), cb, cb_data); break; case client_parser::ascs::kCtpOpcodeUpdateMetadata: - ase_ctp_handler.AseCtpUpdateMetadataHandler(device, std::move(value), - cb, cb_data); + ase_ctp_handler.AseCtpUpdateMetadataHandler(device, std::move(value), cb, cb_data); break; case client_parser::ascs::kCtpOpcodeRelease: - ase_ctp_handler.AseCtpReleaseHandler(device, std::move(value), cb, - cb_data); + ase_ctp_handler.AseCtpReleaseHandler(device, std::move(value), cb, cb_data); break; default: break; @@ -402,253 +367,239 @@ class StateMachineTestBase : public Test { ASSERT_NE(mock_iso_manager_, nullptr); ON_CALL(*mock_iso_manager_, CreateCig) - .WillByDefault( - [this](uint8_t cig_id, - bluetooth::hci::iso_manager::cig_create_params p) { - log::debug("CreateCig"); - last_cig_params_ = p; - - auto& group = le_audio_device_groups_[cig_id]; - if (group) { - std::vector conn_handles; - // Fake connection ID for each cis in a request - for (auto i = 0u; i < p.cis_cfgs.size(); ++i) { - conn_handles.push_back(UNIQUE_CIS_CONN_HANDLE(cig_id, i)); - } - auto status = HCI_SUCCESS; - if (group_create_command_disallowed_) { - group_create_command_disallowed_ = false; - status = HCI_ERR_COMMAND_DISALLOWED; - } + .WillByDefault( + [this](uint8_t cig_id, bluetooth::hci::iso_manager::cig_create_params p) { + log::debug("CreateCig"); + last_cig_params_ = p; + + auto& group = le_audio_device_groups_[cig_id]; + if (group) { + std::vector conn_handles; + // Fake connection ID for each cis in a request + for (auto i = 0u; i < p.cis_cfgs.size(); ++i) { + conn_handles.push_back(UNIQUE_CIS_CONN_HANDLE(cig_id, i)); + } + auto status = HCI_SUCCESS; + if (group_create_command_disallowed_) { + group_create_command_disallowed_ = false; + status = HCI_ERR_COMMAND_DISALLOWED; + } + + LeAudioGroupStateMachine::Get()->ProcessHciNotifOnCigCreate( + group.get(), status, cig_id, conn_handles); + } + }); + + ON_CALL(*mock_iso_manager_, RemoveCig).WillByDefault([this](uint8_t cig_id, bool force) { + log::debug("CreateRemove"); + + auto& group = le_audio_device_groups_[cig_id]; + if (group) { + // Fake connection ID for each cis in a request + LeAudioGroupStateMachine::Get()->ProcessHciNotifOnCigRemove(0, group.get()); + } + }); - LeAudioGroupStateMachine::Get()->ProcessHciNotifOnCigCreate( - group.get(), status, cig_id, conn_handles); + ON_CALL(*mock_iso_manager_, SetupIsoDataPath) + .WillByDefault([this](uint16_t conn_handle, + bluetooth::hci::iso_manager::iso_data_path_params p) { + log::debug("SetupIsoDataPath"); + + auto dev_it = std::find_if(le_audio_devices_.begin(), le_audio_devices_.end(), + [&conn_handle](auto& dev) { + auto ases = dev->GetAsesByCisConnHdl(conn_handle); + return ases.sink || ases.source; + }); + if (dev_it == le_audio_devices_.end()) { + log::error("Device not found"); + return; } - }); - - ON_CALL(*mock_iso_manager_, RemoveCig) - .WillByDefault([this](uint8_t cig_id, bool force) { - log::debug("CreateRemove"); - auto& group = le_audio_device_groups_[cig_id]; - if (group) { - // Fake connection ID for each cis in a request - LeAudioGroupStateMachine::Get()->ProcessHciNotifOnCigRemove( - 0, group.get()); - } - }); - - ON_CALL(*mock_iso_manager_, SetupIsoDataPath) - .WillByDefault([this](uint16_t conn_handle, - bluetooth::hci::iso_manager::iso_data_path_params - p) { - log::debug("SetupIsoDataPath"); - - auto dev_it = - std::find_if(le_audio_devices_.begin(), le_audio_devices_.end(), - [&conn_handle](auto& dev) { - auto ases = dev->GetAsesByCisConnHdl(conn_handle); - return (ases.sink || ases.source); - }); - if (dev_it == le_audio_devices_.end()) { - log::error("Device not found"); - return; - } - - for (auto& kv_pair : le_audio_device_groups_) { - auto& group = kv_pair.second; - if (group->IsDeviceInTheGroup(dev_it->get())) { - LeAudioGroupStateMachine::Get()->ProcessHciNotifSetupIsoDataPath( - group.get(), dev_it->get(), 0, conn_handle); - return; - } - } - }); + for (auto& kv_pair : le_audio_device_groups_) { + auto& group = kv_pair.second; + if (group->IsDeviceInTheGroup(dev_it->get())) { + LeAudioGroupStateMachine::Get()->ProcessHciNotifSetupIsoDataPath( + group.get(), dev_it->get(), 0, conn_handle); + return; + } + } + }); ON_CALL(*mock_iso_manager_, RemoveIsoDataPath) - .WillByDefault([this](uint16_t conn_handle, uint8_t iso_direction) { - log::debug("RemoveIsoDataPath"); - - auto dev_it = - std::find_if(le_audio_devices_.begin(), le_audio_devices_.end(), - [&conn_handle](auto& dev) { - auto ases = dev->GetAsesByCisConnHdl(conn_handle); - return (ases.sink || ases.source); - }); - if (dev_it == le_audio_devices_.end()) { - log::error("Device not found"); - return; - } - - for (auto& kv_pair : le_audio_device_groups_) { - auto& group = kv_pair.second; - if (group->IsDeviceInTheGroup(dev_it->get())) { - LeAudioGroupStateMachine::Get()->ProcessHciNotifRemoveIsoDataPath( - group.get(), dev_it->get(), 0, conn_handle); - return; - } - } - }); + .WillByDefault([this](uint16_t conn_handle, uint8_t iso_direction) { + log::debug("RemoveIsoDataPath"); + + auto dev_it = std::find_if(le_audio_devices_.begin(), le_audio_devices_.end(), + [&conn_handle](auto& dev) { + auto ases = dev->GetAsesByCisConnHdl(conn_handle); + return ases.sink || ases.source; + }); + if (dev_it == le_audio_devices_.end()) { + log::error("Device not found"); + return; + } + + for (auto& kv_pair : le_audio_device_groups_) { + auto& group = kv_pair.second; + if (group->IsDeviceInTheGroup(dev_it->get())) { + LeAudioGroupStateMachine::Get()->ProcessHciNotifRemoveIsoDataPath( + group.get(), dev_it->get(), 0, conn_handle); + return; + } + } + }); ON_CALL(*mock_iso_manager_, EstablishCis) - .WillByDefault([this](bluetooth::hci::iso_manager::cis_establish_params - conn_params) { - log::debug("EstablishCis"); - - if (do_not_send_cis_establish_event_) { - log::debug("Don't send cis establish event"); - return; - } - - for (auto& pair : conn_params.conn_pairs) { - auto dev_it = std::find_if( - le_audio_devices_.begin(), le_audio_devices_.end(), - [&pair](auto& dev) { - auto ases = dev->GetAsesByCisConnHdl(pair.cis_conn_handle); - return (ases.sink || ases.source); - }); - if (dev_it == le_audio_devices_.end()) { - log::error("Device not found"); - return; - } + .WillByDefault([this](bluetooth::hci::iso_manager::cis_establish_params conn_params) { + log::debug("EstablishCis"); - for (auto& kv_pair : le_audio_device_groups_) { - auto& group = kv_pair.second; - if (group->IsDeviceInTheGroup(dev_it->get())) { - bluetooth::hci::iso_manager::cis_establish_cmpl_evt evt; + if (do_not_send_cis_establish_event_) { + log::debug("Don't send cis establish event"); + return; + } - // Fill proper values if needed - if (use_cis_retry_cnt_) { - if (retry_cis_established_cnt_ > 0) { - evt.status = HCI_ERR_CONN_FAILED_ESTABLISHMENT; - retry_cis_established_cnt_--; - } else { - evt.status = 0; - } - } else if (overwrite_cis_status_) { - evt.status = cis_status_[overwrite_cis_status_idx_++]; - /* Reset the index */ - if (cis_status_.size() == overwrite_cis_status_idx_) { - overwrite_cis_status_idx_ = 0; - } - } else { - evt.status = 0; + for (auto& pair : conn_params.conn_pairs) { + auto dev_it = std::find_if( + le_audio_devices_.begin(), le_audio_devices_.end(), [&pair](auto& dev) { + auto ases = dev->GetAsesByCisConnHdl(pair.cis_conn_handle); + return ases.sink || ases.source; + }); + if (dev_it == le_audio_devices_.end()) { + log::error("Device not found"); + return; } - evt.cig_id = group->group_id_; - evt.cis_conn_hdl = pair.cis_conn_handle; - evt.cig_sync_delay = 0; - evt.cis_sync_delay = 0; - evt.trans_lat_mtos = 0; - evt.trans_lat_stom = 0; - evt.phy_mtos = 0; - evt.phy_stom = 0; - evt.nse = 0; - evt.bn_mtos = 0; - evt.bn_stom = 0; - evt.ft_mtos = 0; - evt.ft_stom = 0; - evt.max_pdu_mtos = 0; - evt.max_pdu_stom = 0; - evt.iso_itv = 0; - - LeAudioGroupStateMachine::Get()->ProcessHciNotifCisEstablished( - group.get(), dev_it->get(), &evt); - break; + for (auto& kv_pair : le_audio_device_groups_) { + auto& group = kv_pair.second; + if (group->IsDeviceInTheGroup(dev_it->get())) { + bluetooth::hci::iso_manager::cis_establish_cmpl_evt evt; + + // Fill proper values if needed + if (use_cis_retry_cnt_) { + if (retry_cis_established_cnt_ > 0) { + evt.status = HCI_ERR_CONN_FAILED_ESTABLISHMENT; + retry_cis_established_cnt_--; + } else { + evt.status = 0; + } + } else if (overwrite_cis_status_) { + evt.status = cis_status_[overwrite_cis_status_idx_++]; + /* Reset the index */ + if (cis_status_.size() == overwrite_cis_status_idx_) { + overwrite_cis_status_idx_ = 0; + } + } else { + evt.status = 0; + } + + evt.cig_id = group->group_id_; + evt.cis_conn_hdl = pair.cis_conn_handle; + evt.cig_sync_delay = 0; + evt.cis_sync_delay = 0; + evt.trans_lat_mtos = 0; + evt.trans_lat_stom = 0; + evt.phy_mtos = 0; + evt.phy_stom = 0; + evt.nse = 0; + evt.bn_mtos = 0; + evt.bn_stom = 0; + evt.ft_mtos = 0; + evt.ft_stom = 0; + evt.max_pdu_mtos = 0; + evt.max_pdu_stom = 0; + evt.iso_itv = 0; + + LeAudioGroupStateMachine::Get()->ProcessHciNotifCisEstablished( + group.get(), dev_it->get(), &evt); + break; + } + } } - } - } - }); + }); ON_CALL(*mock_iso_manager_, DisconnectCis) - .WillByDefault([this](uint16_t cis_handle, uint8_t reason) { - log::debug("DisconnectCis"); - - auto dev_it = - std::find_if(le_audio_devices_.begin(), le_audio_devices_.end(), - [&cis_handle](auto& dev) { - auto ases = dev->GetAsesByCisConnHdl(cis_handle); - return (ases.sink || ases.source); - }); - if (dev_it == le_audio_devices_.end()) { - log::error("Device not found"); - return; - } - - // When we disconnect the remote with HCI_ERR_PEER_USER, we - // should be getting HCI_ERR_CONN_CAUSE_LOCAL_HOST from HCI. - if (reason == HCI_ERR_PEER_USER) { - reason = HCI_ERR_CONN_CAUSE_LOCAL_HOST; - } - - for (auto& kv_pair : le_audio_device_groups_) { - auto& group = kv_pair.second; - if (group->IsDeviceInTheGroup(dev_it->get())) { - bluetooth::hci::iso_manager::cis_disconnected_evt evt{ - .reason = reason, - .cig_id = static_cast(group->group_id_), - .cis_conn_hdl = cis_handle, - }; - LeAudioGroupStateMachine::Get()->ProcessHciNotifCisDisconnected( - group.get(), dev_it->get(), &evt); - return; - } - } - }); + .WillByDefault([this](uint16_t cis_handle, uint8_t reason) { + log::debug("DisconnectCis"); + + auto dev_it = std::find_if(le_audio_devices_.begin(), le_audio_devices_.end(), + [&cis_handle](auto& dev) { + auto ases = dev->GetAsesByCisConnHdl(cis_handle); + return ases.sink || ases.source; + }); + if (dev_it == le_audio_devices_.end()) { + log::error("Device not found"); + return; + } + + // When we disconnect the remote with HCI_ERR_PEER_USER, we + // should be getting HCI_ERR_CONN_CAUSE_LOCAL_HOST from HCI. + if (reason == HCI_ERR_PEER_USER) { + reason = HCI_ERR_CONN_CAUSE_LOCAL_HOST; + } + + for (auto& kv_pair : le_audio_device_groups_) { + auto& group = kv_pair.second; + if (group->IsDeviceInTheGroup(dev_it->get())) { + bluetooth::hci::iso_manager::cis_disconnected_evt evt{ + .reason = reason, + .cig_id = static_cast(group->group_id_), + .cis_conn_hdl = cis_handle, + }; + LeAudioGroupStateMachine::Get()->ProcessHciNotifCisDisconnected( + group.get(), dev_it->get(), &evt); + return; + } + } + }); } void ConfigCodecManagerMock(types::CodecLocation location) { codec_manager_ = bluetooth::le_audio::CodecManager::GetInstance(); ASSERT_NE(codec_manager_, nullptr); - std::vector - mock_offloading_preference(0); + std::vector mock_offloading_preference(0); codec_manager_->Start(mock_offloading_preference); mock_codec_manager_ = MockCodecManager::GetInstance(); ASSERT_NE(mock_codec_manager_, nullptr); - ON_CALL(*mock_codec_manager_, GetCodecLocation()) - .WillByDefault(Return(location)); + ON_CALL(*mock_codec_manager_, GetCodecLocation()).WillByDefault(Return(location)); // Regardless of the codec location, return all the possible configurations - ON_CALL(*mock_codec_manager_, IsDualBiDirSwbSupported) - .WillByDefault(Return(true)); + ON_CALL(*mock_codec_manager_, IsDualBiDirSwbSupported).WillByDefault(Return(true)); ON_CALL(*mock_codec_manager_, CheckCodecConfigIsBiDirSwb) - .WillByDefault( - Invoke([](const set_configurations::AudioSetConfiguration& config) - -> bool { - return AudioSetConfigurationProvider::Get() - ->CheckConfigurationIsBiDirSwb(config); - })); + .WillByDefault( + Invoke([](const set_configurations::AudioSetConfiguration& config) -> bool { + return AudioSetConfigurationProvider::Get()->CheckConfigurationIsBiDirSwb( + config); + })); ON_CALL(*mock_codec_manager_, GetCodecConfig) - .WillByDefault(Invoke([](const bluetooth::le_audio::CodecManager:: - UnicastConfigurationRequirements& - requirements, - bluetooth::le_audio::CodecManager:: - UnicastConfigurationVerifier verifier) { - auto configs = - *bluetooth::le_audio::AudioSetConfigurationProvider::Get() - ->GetConfigurations(requirements.audio_context_type); - // Note: This dual bidir SWB exclusion logic has to match the - // CodecManager::GetCodecConfig() implementation. - if (!CodecManager::GetInstance()->IsDualBiDirSwbSupported()) { - configs.erase( - std::remove_if(configs.begin(), configs.end(), - [](auto const& el) { - if (el->confs.source.empty()) return false; - return AudioSetConfigurationProvider::Get() - ->CheckConfigurationIsDualBiDirSwb(*el); - }), - configs.end()); - } - - auto cfg = verifier(requirements, &configs); - if (cfg == nullptr) { - return std::unique_ptr< - bluetooth::le_audio::set_configurations::AudioSetConfiguration>( - nullptr); - } - return std::make_unique< - bluetooth::le_audio::set_configurations::AudioSetConfiguration>( - *cfg); - })); + .WillByDefault(Invoke( + [](const bluetooth::le_audio::CodecManager::UnicastConfigurationRequirements& + requirements, + bluetooth::le_audio::CodecManager::UnicastConfigurationVerifier verifier) { + auto configs = *bluetooth::le_audio::AudioSetConfigurationProvider::Get() + ->GetConfigurations(requirements.audio_context_type); + // Note: This dual bidir SWB exclusion logic has to match the + // CodecManager::GetCodecConfig() implementation. + if (!CodecManager::GetInstance()->IsDualBiDirSwbSupported()) { + configs.erase( + std::remove_if(configs.begin(), configs.end(), + [](auto const& el) { + if (el->confs.source.empty()) { + return false; + } + return AudioSetConfigurationProvider::Get() + ->CheckConfigurationIsDualBiDirSwb(*el); + }), + configs.end()); + } + + auto cfg = verifier(requirements, &configs); + if (cfg == nullptr) { + return std::unique_ptr< + bluetooth::le_audio::set_configurations::AudioSetConfiguration>( + nullptr); + } + return std::make_unique< + bluetooth::le_audio::set_configurations::AudioSetConfiguration>(*cfg); + })); } void TearDown() override { @@ -677,11 +628,10 @@ class StateMachineTestBase : public Test { bluetooth::hci::testing::mock_controller_ = nullptr; } - std::shared_ptr PrepareConnectedDevice( - uint8_t id, DeviceConnectState initial_connect_state, uint8_t num_ase_snk, - uint8_t num_ase_src) { - auto leAudioDevice = std::make_shared(GetTestAddress(id), - initial_connect_state); + std::shared_ptr PrepareConnectedDevice(uint8_t id, + DeviceConnectState initial_connect_state, + uint8_t num_ase_snk, uint8_t num_ase_src) { + auto leAudioDevice = std::make_shared(GetTestAddress(id), initial_connect_state); leAudioDevice->conn_id_ = id; leAudioDevice->SetConnectionState(DeviceConnectState::CONNECTED); @@ -723,28 +673,27 @@ class StateMachineTestBase : public Test { return std::move(leAudioDevice); } - LeAudioDeviceGroup* GroupTheDevice( - int group_id, const std::shared_ptr& leAudioDevice) { + LeAudioDeviceGroup* GroupTheDevice(int group_id, + const std::shared_ptr& leAudioDevice) { if (le_audio_device_groups_.count(group_id) == 0) { - le_audio_device_groups_[group_id] = - std::make_unique(group_id); + le_audio_device_groups_[group_id] = std::make_unique(group_id); } auto& group = le_audio_device_groups_[group_id]; group->AddNode(leAudioDevice); - if (group->IsEmpty()) return nullptr; + if (group->IsEmpty()) { + return nullptr; + } return &(*group); } - void InjectAclDisconnected(LeAudioDeviceGroup* group, - LeAudioDevice* leAudioDevice) { + void InjectAclDisconnected(LeAudioDeviceGroup* group, LeAudioDevice* leAudioDevice) { // Do what the client.cc does when handling the disconnection event leAudioDevice->conn_id_ = GATT_INVALID_CONN_ID; leAudioDevice->SetConnectionState(DeviceConnectState::DISCONNECTED); - LeAudioGroupStateMachine::Get()->ProcessHciNotifAclDisconnected( - group, leAudioDevice); + LeAudioGroupStateMachine::Get()->ProcessHciNotifAclDisconnected(group, leAudioDevice); } void InjectReleasingAndIdleState(LeAudioDeviceGroup* group, LeAudioDevice* device, @@ -767,77 +716,62 @@ class StateMachineTestBase : public Test { bool idle = true) { auto leAudioDevice = group->GetFirstActiveDevice(); while (leAudioDevice) { - log::info("Group : {}, dev: {}", group->group_id_, - leAudioDevice->address_); + log::info("Group : {}, dev: {}", group->group_id_, leAudioDevice->address_); InjectReleasingAndIdleState(group, leAudioDevice, release, idle); leAudioDevice = group->GetNextActiveDevice(leAudioDevice); } } - void InjectCachedConfigurationForActiveAses(LeAudioDeviceGroup* group, - LeAudioDevice* device) { + void InjectCachedConfigurationForActiveAses(LeAudioDeviceGroup* group, LeAudioDevice* device) { for (auto& ase : device->ases_) { if (!ase.active) { continue; } - log::info("ID : {}, status {}", ase.id, - bluetooth::common::ToString(ase.state)); + log::info("ID : {}, status {}", ase.id, bluetooth::common::ToString(ase.state)); - InjectAseStateNotification(&ase, device, group, - ascs::kAseStateCodecConfigured, + InjectAseStateNotification(&ase, device, group, ascs::kAseStateCodecConfigured, &cached_codec_configuration_map_[ase.id]); } } - void InjectStreamingStateFroActiveAses(LeAudioDeviceGroup* group, - LeAudioDevice* device) { + void InjectStreamingStateFroActiveAses(LeAudioDeviceGroup* group, LeAudioDevice* device) { for (auto& ase : device->ases_) { if (!ase.active) { continue; } - log::info("ID : {}, status {}", ase.id, - bluetooth::common::ToString(ase.state)); + log::info("ID : {}, status {}", ase.id, bluetooth::common::ToString(ase.state)); client_parser::ascs::ase_transient_state_params params; - InjectAseStateNotification(&ase, device, group, ascs::kAseStateStreaming, - ¶ms); + InjectAseStateNotification(&ase, device, group, ascs::kAseStateStreaming, ¶ms); } } - void InjectEnablingStateFroActiveAses(LeAudioDeviceGroup* group, - LeAudioDevice* device) { + void InjectEnablingStateFroActiveAses(LeAudioDeviceGroup* group, LeAudioDevice* device) { for (auto& ase : device->ases_) { if (!ase.active) { continue; } - log::info("ID : {}, status {}", ase.id, - bluetooth::common::ToString(ase.state)); + log::info("ID : {}, status {}", ase.id, bluetooth::common::ToString(ase.state)); client_parser::ascs::ase_transient_state_params enable_params; - InjectAseStateNotification(&ase, device, group, ascs::kAseStateEnabling, - &enable_params); + InjectAseStateNotification(&ase, device, group, ascs::kAseStateEnabling, &enable_params); } } - void InjectQoSConfigurationForActiveAses(LeAudioDeviceGroup* group, - LeAudioDevice* device) { + void InjectQoSConfigurationForActiveAses(LeAudioDeviceGroup* group, LeAudioDevice* device) { for (auto& ase : device->ases_) { if (!ase.active) { continue; } - log::info("ID : {}, status {}", ase.id, - bluetooth::common::ToString(ase.state)); - - if (ase.direction == - ::bluetooth::le_audio::types::kLeAudioDirectionSource) { - client_parser::ascs::ase_transient_state_params disabling_params = { - .metadata = {}}; - InjectAseStateNotification(&ase, device, group, - ascs::kAseStateDisabling, &disabling_params); + log::info("ID : {}, status {}", ase.id, bluetooth::common::ToString(ase.state)); + + if (ase.direction == ::bluetooth::le_audio::types::kLeAudioDirectionSource) { + client_parser::ascs::ase_transient_state_params disabling_params = {.metadata = {}}; + InjectAseStateNotification(&ase, device, group, ascs::kAseStateDisabling, + &disabling_params); } - InjectAseStateNotification(&ase, device, group, - ascs::kAseStateQoSConfigured, + InjectAseStateNotification(&ase, device, group, ascs::kAseStateQoSConfigured, &cached_qos_configuration_map_[ase.id]); } } @@ -845,29 +779,24 @@ class StateMachineTestBase : public Test { void InjectQoSConfigurationForGroupActiveAses(LeAudioDeviceGroup* group) { auto leAudioDevice = group->GetFirstActiveDevice(); while (leAudioDevice) { - log::info("Group : {}, dev: {}", group->group_id_, - leAudioDevice->address_); + log::info("Group : {}, dev: {}", group->group_id_, leAudioDevice->address_); InjectQoSConfigurationForActiveAses(group, leAudioDevice); leAudioDevice = group->GetNextActiveDevice(leAudioDevice); } } - void InjectAseStateNotification(types::ase* ase, LeAudioDevice* device, - LeAudioDeviceGroup* group, uint8_t new_state, - void* new_state_params) { + void InjectAseStateNotification(types::ase* ase, LeAudioDevice* device, LeAudioDeviceGroup* group, + uint8_t new_state, void* new_state_params) { // Prepare additional params switch (new_state) { case ascs::kAseStateCodecConfigured: { client_parser::ascs::ase_codec_configured_state_params* conf = - static_cast< - client_parser::ascs::ase_codec_configured_state_params*>( - new_state_params); + static_cast( + new_state_params); std::vector notif_value(25 + conf->codec_spec_conf.size()); auto* p = notif_value.data(); - UINT8_TO_STREAM(p, ase->id == types::ase::kAseIdInvalid - ? ++ase_id_last_assigned - : ase->id); + UINT8_TO_STREAM(p, ase->id == types::ase::kAseIdInvalid ? ++ase_id_last_assigned : ase->id); UINT8_TO_STREAM(p, new_state); UINT8_TO_STREAM(p, conf->framing); @@ -889,20 +818,18 @@ class StateMachineTestBase : public Test { memcpy(p, conf->codec_spec_conf.data(), conf->codec_spec_conf.size()); LeAudioGroupStateMachine::Get()->ProcessGattNotifEvent( - notif_value.data(), notif_value.size(), ase, device, group); + notif_value.data(), notif_value.size(), ase, device, group); } break; case ascs::kAseStateQoSConfigured: { client_parser::ascs::ase_qos_configured_state_params* conf = - static_cast( - new_state_params); + static_cast( + new_state_params); std::vector notif_value(17); auto* p = notif_value.data(); // Prepare header - UINT8_TO_STREAM(p, ase->id == types::ase::kAseIdInvalid - ? ++ase_id_last_assigned - : ase->id); + UINT8_TO_STREAM(p, ase->id == types::ase::kAseIdInvalid ? ++ase_id_last_assigned : ase->id); UINT8_TO_STREAM(p, new_state); UINT8_TO_STREAM(p, conf->cig_id); @@ -918,7 +845,7 @@ class StateMachineTestBase : public Test { cached_remote_qos_configuration_for_ase_[ase] = notif_value; LeAudioGroupStateMachine::Get()->ProcessGattNotifEvent( - notif_value.data(), notif_value.size(), ase, device, group); + notif_value.data(), notif_value.size(), ase, device, group); } break; case ascs::kAseStateEnabling: @@ -927,15 +854,12 @@ class StateMachineTestBase : public Test { // fall-through case ascs::kAseStateDisabling: { client_parser::ascs::ase_transient_state_params* params = - static_cast( - new_state_params); + static_cast(new_state_params); std::vector notif_value(5 + params->metadata.size()); auto* p = notif_value.data(); // Prepare header - UINT8_TO_STREAM(p, ase->id == types::ase::kAseIdInvalid - ? ++ase_id_last_assigned - : ase->id); + UINT8_TO_STREAM(p, ase->id == types::ase::kAseIdInvalid ? ++ase_id_last_assigned : ase->id); UINT8_TO_STREAM(p, new_state); @@ -945,7 +869,7 @@ class StateMachineTestBase : public Test { memcpy(p, params->metadata.data(), params->metadata.size()); LeAudioGroupStateMachine::Get()->ProcessGattNotifEvent( - notif_value.data(), notif_value.size(), ase, device, group); + notif_value.data(), notif_value.size(), ase, device, group); } break; case ascs::kAseStateReleasing: @@ -955,13 +879,11 @@ class StateMachineTestBase : public Test { auto* p = notif_value.data(); // Prepare header - UINT8_TO_STREAM(p, ase->id == types::ase::kAseIdInvalid - ? ++ase_id_last_assigned - : ase->id); + UINT8_TO_STREAM(p, ase->id == types::ase::kAseIdInvalid ? ++ase_id_last_assigned : ase->id); UINT8_TO_STREAM(p, new_state); LeAudioGroupStateMachine::Get()->ProcessGattNotifEvent( - notif_value.data(), notif_value.size(), ase, device, group); + notif_value.data(), notif_value.size(), ase, device, group); } break; default: @@ -970,46 +892,41 @@ class StateMachineTestBase : public Test { } static void InsertPacRecord( - std::vector& recs, - uint16_t sampling_frequencies_bitfield, - uint8_t supported_frame_durations_bitfield, - uint8_t audio_channel_count_bitfield, - uint16_t supported_octets_per_codec_frame_min, - uint16_t supported_octets_per_codec_frame_max, - uint8_t codec_frame_blocks_per_sdu_ = 1, - uint8_t coding_format = codec_specific::kLc3CodingFormat, - uint16_t vendor_company_id = 0x0000, uint16_t vendor_codec_id = 0x0000, - std::vector metadata = {}) { + std::vector& recs, uint16_t sampling_frequencies_bitfield, + uint8_t supported_frame_durations_bitfield, uint8_t audio_channel_count_bitfield, + uint16_t supported_octets_per_codec_frame_min, + uint16_t supported_octets_per_codec_frame_max, uint8_t codec_frame_blocks_per_sdu_ = 1, + uint8_t coding_format = codec_specific::kLc3CodingFormat, + uint16_t vendor_company_id = 0x0000, uint16_t vendor_codec_id = 0x0000, + std::vector metadata = {}) { auto ltv_map = types::LeAudioLtvMap({ - {codec_specific::kCapTypeSupportedSamplingFrequencies, - {(uint8_t)(sampling_frequencies_bitfield), - (uint8_t)(sampling_frequencies_bitfield >> 8)}}, - {codec_specific::kCapTypeSupportedFrameDurations, - {supported_frame_durations_bitfield}}, - {codec_specific::kCapTypeAudioChannelCount, - {audio_channel_count_bitfield}}, - {codec_specific::kCapTypeSupportedOctetsPerCodecFrame, - { - // Min - (uint8_t)(supported_octets_per_codec_frame_min), - (uint8_t)(supported_octets_per_codec_frame_min >> 8), - // Max - (uint8_t)(supported_octets_per_codec_frame_max), - (uint8_t)(supported_octets_per_codec_frame_max >> 8), - }}, + {codec_specific::kCapTypeSupportedSamplingFrequencies, + {(uint8_t)(sampling_frequencies_bitfield), + (uint8_t)(sampling_frequencies_bitfield >> 8)}}, + {codec_specific::kCapTypeSupportedFrameDurations, {supported_frame_durations_bitfield}}, + {codec_specific::kCapTypeAudioChannelCount, {audio_channel_count_bitfield}}, + {codec_specific::kCapTypeSupportedOctetsPerCodecFrame, + { + // Min + (uint8_t)(supported_octets_per_codec_frame_min), + (uint8_t)(supported_octets_per_codec_frame_min >> 8), + // Max + (uint8_t)(supported_octets_per_codec_frame_max), + (uint8_t)(supported_octets_per_codec_frame_max >> 8), + }}, }); ltv_map.Add(codec_specific::kCapTypeSupportedLc3CodecFramesPerSdu, (uint8_t)codec_frame_blocks_per_sdu_); recs.push_back({ - .codec_id = - { - .coding_format = coding_format, - .vendor_company_id = vendor_company_id, - .vendor_codec_id = vendor_codec_id, - }, - .codec_spec_caps = ltv_map, - .codec_spec_caps_raw = ltv_map.RawPacket(), - .metadata = std::move(metadata), + .codec_id = + { + .coding_format = coding_format, + .vendor_company_id = vendor_company_id, + .vendor_codec_id = vendor_codec_id, + }, + .codec_spec_caps = ltv_map, + .codec_spec_caps_raw = ltv_map.RawPacket(), + .metadata = std::move(metadata), }); } @@ -1017,8 +934,7 @@ class StateMachineTestBase : public Test { for (auto* device = group->GetFirstDevice(); device != nullptr; device = group->GetNextDevice(device)) { for (auto& ase : device->ases_) { - InjectAseStateNotification(&ase, device, group, ascs::kAseStateIdle, - nullptr); + InjectAseStateNotification(&ase, device, group, ascs::kAseStateIdle, nullptr); } } } @@ -1027,10 +943,8 @@ class StateMachineTestBase : public Test { for (auto* device = group->GetFirstDevice(); device != nullptr; device = group->GetNextDevice(device)) { for (auto& ase : device->ases_) { - client_parser::ascs::ase_codec_configured_state_params - codec_configured_state_params; - InjectAseStateNotification(&ase, device, group, - ascs::kAseStateCodecConfigured, + client_parser::ascs::ase_codec_configured_state_params codec_configured_state_params; + InjectAseStateNotification(&ase, device, group, ascs::kAseStateCodecConfigured, &codec_configured_state_params); } } @@ -1042,13 +956,10 @@ class StateMachineTestBase : public Test { int i = 0; for (auto& ase : device->ases_) { if (i % 2 == 1) { - InjectAseStateNotification(&ase, device, group, ascs::kAseStateIdle, - nullptr); + InjectAseStateNotification(&ase, device, group, ascs::kAseStateIdle, nullptr); } else { - client_parser::ascs::ase_codec_configured_state_params - codec_configured_state_params; - InjectAseStateNotification(&ase, device, group, - ascs::kAseStateCodecConfigured, + client_parser::ascs::ase_codec_configured_state_params codec_configured_state_params; + InjectAseStateNotification(&ase, device, group, ascs::kAseStateCodecConfigured, &codec_configured_state_params); } i++; @@ -1062,30 +973,24 @@ class StateMachineTestBase : public Test { int i = 0; for (auto& ase : device->ases_) { if (i % 2 == 1) { - client_parser::ascs::ase_qos_configured_state_params - qos_configured_state_params; - InjectAseStateNotification(&ase, device, group, - ascs::kAseStateQoSConfigured, + client_parser::ascs::ase_qos_configured_state_params qos_configured_state_params; + InjectAseStateNotification(&ase, device, group, ascs::kAseStateQoSConfigured, &qos_configured_state_params); } else { client_parser::ascs::ase_transient_state_params enable_params; - InjectAseStateNotification(&ase, device, group, - ascs::kAseStateEnabling, &enable_params); + InjectAseStateNotification(&ase, device, group, ascs::kAseStateEnabling, &enable_params); } i++; } } } - void MultipleTestDevicePrepare(int leaudio_group_id, - LeAudioContextType context_type, - uint16_t device_cnt, - types::AudioContexts update_contexts, + void MultipleTestDevicePrepare(int leaudio_group_id, LeAudioContextType context_type, + uint16_t device_cnt, types::AudioContexts update_contexts, bool insert_default_pac_records = true, bool second_device_0_ases = false) { // Prepare fake connected device group - DeviceConnectState initial_connect_state = - DeviceConnectState::CONNECTING_BY_USER; + DeviceConnectState initial_connect_state = DeviceConnectState::CONNECTING_BY_USER; int total_devices = device_cnt; bluetooth::le_audio::LeAudioDeviceGroup* group = nullptr; @@ -1120,11 +1025,10 @@ class StateMachineTestBase : public Test { std::shared_ptr leAudioDevice; if (device_cnt == 2 && second_device_0_ases == true) { - leAudioDevice = - PrepareConnectedDevice(device_cnt--, initial_connect_state, 0, 0); + leAudioDevice = PrepareConnectedDevice(device_cnt--, initial_connect_state, 0, 0); } else { - leAudioDevice = PrepareConnectedDevice( - device_cnt--, initial_connect_state, num_ase_snk, num_ase_src); + leAudioDevice = PrepareConnectedDevice(device_cnt--, initial_connect_state, num_ase_snk, + num_ase_src); } if (insert_default_pac_records) { @@ -1135,58 +1039,53 @@ class StateMachineTestBase : public Test { auto src_context_type = kContextTypeUnspecified | update_contexts; // Prepare Sink Published Audio Capability records - if ((kContextTypeRingtone | kContextTypeMedia | - kContextTypeConversational | kContextTypeLive) - .test(context_type)) { + if ((kContextTypeRingtone | kContextTypeMedia | kContextTypeConversational | + kContextTypeLive) + .test(context_type)) { // Set target ASE configurations std::vector pac_recs; InsertPacRecord(pac_recs, sample_freq_, codec_specific::kCapFrameDuration10ms | - codec_specific::kCapFrameDuration7p5ms | - codec_specific::kCapFrameDuration10msPreferred, + codec_specific::kCapFrameDuration7p5ms | + codec_specific::kCapFrameDuration10msPreferred, channel_count_, 30, 120, codec_frame_blocks_per_sdu_); types::hdl_pair handle_pair; handle_pair.val_hdl = attr_handle++; handle_pair.ccc_hdl = attr_handle++; - leAudioDevice->snk_pacs_.emplace_back( - std::make_tuple(std::move(handle_pair), pac_recs)); + leAudioDevice->snk_pacs_.emplace_back(std::make_tuple(std::move(handle_pair), pac_recs)); snk_context_type.set(context_type); leAudioDevice->snk_audio_locations_ = channel_allocations_sink_; } // Prepare Source Published Audio Capability records - if ((context_type == kContextTypeConversational) || - (context_type == kContextTypeLive)) { + if ((context_type == kContextTypeConversational) || (context_type == kContextTypeLive)) { // Set target ASE configurations std::vector pac_recs; InsertPacRecord(pac_recs, codec_specific::kCapSamplingFrequency16000Hz | - codec_specific::kCapSamplingFrequency32000Hz, + codec_specific::kCapSamplingFrequency32000Hz, codec_specific::kCapFrameDuration10ms | - codec_specific::kCapFrameDuration7p5ms | - codec_specific::kCapFrameDuration10msPreferred, + codec_specific::kCapFrameDuration7p5ms | + codec_specific::kCapFrameDuration10msPreferred, 0b00000001, 30, 120, codec_frame_blocks_per_sdu_); types::hdl_pair handle_pair; handle_pair.val_hdl = attr_handle++; handle_pair.ccc_hdl = attr_handle++; - leAudioDevice->src_pacs_.emplace_back( - std::make_tuple(std::move(handle_pair), pac_recs)); + leAudioDevice->src_pacs_.emplace_back(std::make_tuple(std::move(handle_pair), pac_recs)); src_context_type.set(context_type); leAudioDevice->src_audio_locations_ = channel_allocations_source_; } - leAudioDevice->SetSupportedContexts( - {.sink = snk_context_type, .source = src_context_type}); - leAudioDevice->SetAvailableContexts( - {.sink = snk_context_type, .source = src_context_type}); + leAudioDevice->SetSupportedContexts({.sink = snk_context_type, .source = src_context_type}); + leAudioDevice->SetAvailableContexts({.sink = snk_context_type, .source = src_context_type}); } group = GroupTheDevice(leaudio_group_id, std::move(leAudioDevice)); @@ -1204,183 +1103,168 @@ class StateMachineTestBase : public Test { } LeAudioDeviceGroup* PrepareSingleTestDeviceGroup( - int leaudio_group_id, LeAudioContextType context_type, - uint16_t device_cnt = 1, - types::AudioContexts update_contexts = types::AudioContexts(), - bool second_device_0_ases = false) { - MultipleTestDevicePrepare(leaudio_group_id, context_type, device_cnt, - update_contexts, true, second_device_0_ases); + int leaudio_group_id, LeAudioContextType context_type, uint16_t device_cnt = 1, + types::AudioContexts update_contexts = types::AudioContexts(), + bool second_device_0_ases = false) { + MultipleTestDevicePrepare(leaudio_group_id, context_type, device_cnt, update_contexts, true, + second_device_0_ases); return le_audio_device_groups_.count(leaudio_group_id) - ? le_audio_device_groups_[leaudio_group_id].get() - : nullptr; + ? le_audio_device_groups_[leaudio_group_id].get() + : nullptr; } - void PrepareConfigureCodecHandler(LeAudioDeviceGroup* group, - int verify_ase_count = 0, - bool caching = false, - bool inject_configured = true) { + void PrepareConfigureCodecHandler(LeAudioDeviceGroup* group, int verify_ase_count = 0, + bool caching = false, bool inject_configured = true) { ON_CALL(ase_ctp_handler, AseCtpConfigureCodecHandler) - .WillByDefault(Invoke([group, verify_ase_count, caching, - inject_configured, - this](LeAudioDevice* device, - std::vector value, - GATT_WRITE_OP_CB cb, void* cb_data) { - auto num_ase = value[1]; - - // Verify ase count if needed - if (verify_ase_count) ASSERT_EQ(verify_ase_count, num_ase); - - // Inject Configured ASE state notification for each requested ASE - auto* ase_p = &value[2]; - for (auto i = 0u; i < num_ase; ++i) { - client_parser::ascs::ase_codec_configured_state_params - codec_configured_state_params; - - /* Check if this is a valid ASE ID */ - auto ase_id = *ase_p++; - auto it = std::find_if( - device->ases_.begin(), device->ases_.end(), - [ase_id](auto& ase) { return (ase.id == ase_id); }); - ASSERT_NE(it, device->ases_.end()); - const auto ase = &(*it); - - // Skip target latency param - ase_p++; - - codec_configured_state_params.preferred_phy = *ase_p++; - codec_configured_state_params.codec_id.coding_format = ase_p[0]; - codec_configured_state_params.codec_id.vendor_company_id = - (uint16_t)(ase_p[1] << 8 | ase_p[2]), - codec_configured_state_params.codec_id.vendor_codec_id = - (uint16_t)(ase_p[3] << 8 | ase_p[4]), - ase_p += 5; - - auto codec_spec_param_len = *ase_p++; - auto num_handled_bytes = ase_p - value.data(); - codec_configured_state_params.codec_spec_conf = - std::vector( - value.begin() + num_handled_bytes, - value.begin() + num_handled_bytes + codec_spec_param_len); - ase_p += codec_spec_param_len; - - // Some initial QoS settings - codec_configured_state_params.framing = - ascs::kAseParamFramingUnframedSupported; - codec_configured_state_params.preferred_retrans_nb = 0x04; - codec_configured_state_params.max_transport_latency = 0x0020; - codec_configured_state_params.pres_delay_min = 0xABABAB; - codec_configured_state_params.pres_delay_max = 0xCDCDCD; - codec_configured_state_params.preferred_pres_delay_min = - types::kPresDelayNoPreference; - codec_configured_state_params.preferred_pres_delay_max = - types::kPresDelayNoPreference; - - if (caching) { - cached_codec_configuration_map_[ase_id] = - codec_configured_state_params; - } + .WillByDefault(Invoke([group, verify_ase_count, caching, inject_configured, this]( + LeAudioDevice* device, std::vector value, + GATT_WRITE_OP_CB cb, void* cb_data) { + auto num_ase = value[1]; - if (inject_configured) { - InjectAseStateNotification(ase, device, group, - ascs::kAseStateCodecConfigured, - &codec_configured_state_params); - } + // Verify ase count if needed + if (verify_ase_count) { + ASSERT_EQ(verify_ase_count, num_ase); + } - if (stop_inject_configured_ase_after_first_ase_configured_) { - return; - } - } - })); + // Inject Configured ASE state notification for each requested ASE + auto* ase_p = &value[2]; + for (auto i = 0u; i < num_ase; ++i) { + client_parser::ascs::ase_codec_configured_state_params + codec_configured_state_params; + + /* Check if this is a valid ASE ID */ + auto ase_id = *ase_p++; + auto it = std::find_if(device->ases_.begin(), device->ases_.end(), + [ase_id](auto& ase) { return ase.id == ase_id; }); + ASSERT_NE(it, device->ases_.end()); + const auto ase = &(*it); + + // Skip target latency param + ase_p++; + + codec_configured_state_params.preferred_phy = *ase_p++; + codec_configured_state_params.codec_id.coding_format = ase_p[0]; + codec_configured_state_params.codec_id.vendor_company_id = + (uint16_t)(ase_p[1] << 8 | ase_p[2]), + codec_configured_state_params.codec_id.vendor_codec_id = + (uint16_t)(ase_p[3] << 8 | ase_p[4]), + ase_p += 5; + + auto codec_spec_param_len = *ase_p++; + auto num_handled_bytes = ase_p - value.data(); + codec_configured_state_params.codec_spec_conf = std::vector( + value.begin() + num_handled_bytes, + value.begin() + num_handled_bytes + codec_spec_param_len); + ase_p += codec_spec_param_len; + + // Some initial QoS settings + codec_configured_state_params.framing = ascs::kAseParamFramingUnframedSupported; + codec_configured_state_params.preferred_retrans_nb = 0x04; + codec_configured_state_params.max_transport_latency = 0x0020; + codec_configured_state_params.pres_delay_min = 0xABABAB; + codec_configured_state_params.pres_delay_max = 0xCDCDCD; + codec_configured_state_params.preferred_pres_delay_min = + types::kPresDelayNoPreference; + codec_configured_state_params.preferred_pres_delay_max = + types::kPresDelayNoPreference; + + if (caching) { + cached_codec_configuration_map_[ase_id] = codec_configured_state_params; + } + + if (inject_configured) { + InjectAseStateNotification(ase, device, group, ascs::kAseStateCodecConfigured, + &codec_configured_state_params); + } + + if (stop_inject_configured_ase_after_first_ase_configured_) { + return; + } + } + })); } - void PrepareConfigureQosHandler(LeAudioDeviceGroup* group, - int verify_ase_count = 0, - bool caching = false, - bool inject_qos_configured = true) { + void PrepareConfigureQosHandler(LeAudioDeviceGroup* group, int verify_ase_count = 0, + bool caching = false, bool inject_qos_configured = true) { ON_CALL(ase_ctp_handler, AseCtpConfigureQosHandler) - .WillByDefault(Invoke([group, verify_ase_count, caching, - inject_qos_configured, - this](LeAudioDevice* device, - std::vector value, - GATT_WRITE_OP_CB cb, void* cb_data) { - auto num_ase = value[1]; - - // Verify ase count if needed - if (verify_ase_count) ASSERT_EQ(verify_ase_count, num_ase); - - // Inject Configured QoS state notification for each requested ASE - auto* ase_p = &value[2]; - for (auto i = 0u; i < num_ase; ++i) { - client_parser::ascs::ase_qos_configured_state_params - qos_configured_state_params; - - /* Check if this is a valid ASE ID */ - auto ase_id = *ase_p++; - auto it = std::find_if( - device->ases_.begin(), device->ases_.end(), - [ase_id](auto& ase) { return (ase.id == ase_id); }); - ASSERT_NE(it, device->ases_.end()); - const auto ase = &(*it); - - qos_configured_state_params.cig_id = *ase_p++; - qos_configured_state_params.cis_id = *ase_p++; - - qos_configured_state_params.sdu_interval = - (uint32_t)((ase_p[0] << 16) | (ase_p[1] << 8) | ase_p[2]); - ase_p += 3; - - qos_configured_state_params.framing = *ase_p++; - qos_configured_state_params.phy = *ase_p++; - qos_configured_state_params.max_sdu = - (uint16_t)((ase_p[0] << 8) | ase_p[1]); - ase_p += 2; - - qos_configured_state_params.retrans_nb = *ase_p++; - qos_configured_state_params.max_transport_latency = - (uint16_t)((ase_p[0] << 8) | ase_p[1]); - ase_p += 2; - - qos_configured_state_params.pres_delay = - (uint16_t)((ase_p[0] << 16) | (ase_p[1] << 8) | ase_p[2]); - ase_p += 3; - - if (caching) { - log::info("Device: {}", device->address_); - if (cached_ase_to_cis_id_map_.count(device->address_) > 0) { - auto ase_list = cached_ase_to_cis_id_map_.at(device->address_); - if (ase_list.count(ase_id) > 0) { - auto cis_id = ase_list.at(ase_id); - ASSERT_EQ(cis_id, qos_configured_state_params.cis_id); - } else { - ase_list[ase_id] = qos_configured_state_params.cis_id; - } - } else { - std::map ase_map; - ase_map[ase_id] = qos_configured_state_params.cis_id; + .WillByDefault(Invoke([group, verify_ase_count, caching, inject_qos_configured, this]( + LeAudioDevice* device, std::vector value, + GATT_WRITE_OP_CB cb, void* cb_data) { + auto num_ase = value[1]; - cached_ase_to_cis_id_map_[device->address_] = ase_map; + // Verify ase count if needed + if (verify_ase_count) { + ASSERT_EQ(verify_ase_count, num_ase); } - cached_qos_configuration_map_[ase_id] = - qos_configured_state_params; - } - if (inject_qos_configured) { - InjectAseStateNotification(ase, device, group, - ascs::kAseStateQoSConfigured, - &qos_configured_state_params); - } - } - })); + // Inject Configured QoS state notification for each requested ASE + auto* ase_p = &value[2]; + for (auto i = 0u; i < num_ase; ++i) { + client_parser::ascs::ase_qos_configured_state_params qos_configured_state_params; + + /* Check if this is a valid ASE ID */ + auto ase_id = *ase_p++; + auto it = std::find_if(device->ases_.begin(), device->ases_.end(), + [ase_id](auto& ase) { return ase.id == ase_id; }); + ASSERT_NE(it, device->ases_.end()); + const auto ase = &(*it); + + qos_configured_state_params.cig_id = *ase_p++; + qos_configured_state_params.cis_id = *ase_p++; + + qos_configured_state_params.sdu_interval = + (uint32_t)((ase_p[0] << 16) | (ase_p[1] << 8) | ase_p[2]); + ase_p += 3; + + qos_configured_state_params.framing = *ase_p++; + qos_configured_state_params.phy = *ase_p++; + qos_configured_state_params.max_sdu = (uint16_t)((ase_p[0] << 8) | ase_p[1]); + ase_p += 2; + + qos_configured_state_params.retrans_nb = *ase_p++; + qos_configured_state_params.max_transport_latency = + (uint16_t)((ase_p[0] << 8) | ase_p[1]); + ase_p += 2; + + qos_configured_state_params.pres_delay = + (uint16_t)((ase_p[0] << 16) | (ase_p[1] << 8) | ase_p[2]); + ase_p += 3; + + if (caching) { + log::info("Device: {}", device->address_); + if (cached_ase_to_cis_id_map_.count(device->address_) > 0) { + auto ase_list = cached_ase_to_cis_id_map_.at(device->address_); + if (ase_list.count(ase_id) > 0) { + auto cis_id = ase_list.at(ase_id); + ASSERT_EQ(cis_id, qos_configured_state_params.cis_id); + } else { + ase_list[ase_id] = qos_configured_state_params.cis_id; + } + } else { + std::map ase_map; + ase_map[ase_id] = qos_configured_state_params.cis_id; + + cached_ase_to_cis_id_map_[device->address_] = ase_map; + } + cached_qos_configuration_map_[ase_id] = qos_configured_state_params; + } + + if (inject_qos_configured) { + InjectAseStateNotification(ase, device, group, ascs::kAseStateQoSConfigured, + &qos_configured_state_params); + } + } + })); } - void PrepareCtpNotificationError(LeAudioDeviceGroup* group, uint8_t opcode, - uint8_t response_code, uint8_t reason) { - auto foo = [group, opcode, response_code, reason]( - LeAudioDevice* device, std::vector value, - GATT_WRITE_OP_CB cb, void* cb_data) { + void PrepareCtpNotificationError(LeAudioDeviceGroup* group, uint8_t opcode, uint8_t response_code, + uint8_t reason) { + auto foo = [group, opcode, response_code, reason](LeAudioDevice* device, + std::vector value, + GATT_WRITE_OP_CB cb, void* cb_data) { auto num_ase = value[1]; - std::vector notif_value( - 2 + num_ase * sizeof(struct client_parser::ascs::ctp_ase_entry)); + std::vector notif_value(2 + + num_ase * sizeof(struct client_parser::ascs::ctp_ase_entry)); auto* p = notif_value.data(); UINT8_TO_STREAM(p, opcode); @@ -1390,9 +1274,8 @@ class StateMachineTestBase : public Test { for (auto i = 0u; i < num_ase; ++i) { /* Check if this is a valid ASE ID */ auto ase_id = *ase_p++; - auto it = - std::find_if(device->ases_.begin(), device->ases_.end(), - [ase_id](auto& ase) { return (ase.id == ase_id); }); + auto it = std::find_if(device->ases_.begin(), device->ases_.end(), + [ase_id](auto& ase) { return ase.id == ase_id; }); ASSERT_NE(it, device->ases_.end()); auto meta_len = *ase_p++; @@ -1400,9 +1283,8 @@ class StateMachineTestBase : public Test { ase_p += meta_len; client_parser::ascs::ase_transient_state_params enable_params = { - .metadata = std::vector( - value.begin() + num_handled_bytes, - value.begin() + num_handled_bytes + meta_len)}; + .metadata = std::vector(value.begin() + num_handled_bytes, + value.begin() + num_handled_bytes + meta_len)}; // Inject error response UINT8_TO_STREAM(p, ase_id); @@ -1410,42 +1292,34 @@ class StateMachineTestBase : public Test { UINT8_TO_STREAM(p, reason); } - LeAudioGroupStateMachine::Get()->ProcessGattCtpNotification( - group, notif_value.data(), notif_value.size()); + LeAudioGroupStateMachine::Get()->ProcessGattCtpNotification(group, notif_value.data(), + notif_value.size()); }; switch (opcode) { case client_parser::ascs::kCtpOpcodeCodecConfiguration: - ON_CALL(ase_ctp_handler, AseCtpConfigureCodecHandler) - .WillByDefault(Invoke(foo)); + ON_CALL(ase_ctp_handler, AseCtpConfigureCodecHandler).WillByDefault(Invoke(foo)); break; case client_parser::ascs::kCtpOpcodeQosConfiguration: - ON_CALL(ase_ctp_handler, AseCtpConfigureQosHandler) - .WillByDefault(Invoke(foo)); + ON_CALL(ase_ctp_handler, AseCtpConfigureQosHandler).WillByDefault(Invoke(foo)); break; case client_parser::ascs::kCtpOpcodeEnable: - ON_CALL(ase_ctp_handler, AseCtpEnableHandler) - .WillByDefault(Invoke(foo)); + ON_CALL(ase_ctp_handler, AseCtpEnableHandler).WillByDefault(Invoke(foo)); break; case client_parser::ascs::kCtpOpcodeReceiverStartReady: - ON_CALL(ase_ctp_handler, AseCtpReceiverStartReadyHandler) - .WillByDefault(Invoke(foo)); + ON_CALL(ase_ctp_handler, AseCtpReceiverStartReadyHandler).WillByDefault(Invoke(foo)); break; case client_parser::ascs::kCtpOpcodeDisable: - ON_CALL(ase_ctp_handler, AseCtpDisableHandler) - .WillByDefault(Invoke(foo)); + ON_CALL(ase_ctp_handler, AseCtpDisableHandler).WillByDefault(Invoke(foo)); break; case client_parser::ascs::kCtpOpcodeReceiverStopReady: - ON_CALL(ase_ctp_handler, AseCtpReceiverStopReadyHandler) - .WillByDefault(Invoke(foo)); + ON_CALL(ase_ctp_handler, AseCtpReceiverStopReadyHandler).WillByDefault(Invoke(foo)); break; case client_parser::ascs::kCtpOpcodeUpdateMetadata: - ON_CALL(ase_ctp_handler, AseCtpUpdateMetadataHandler) - .WillByDefault(Invoke(foo)); + ON_CALL(ase_ctp_handler, AseCtpUpdateMetadataHandler).WillByDefault(Invoke(foo)); break; case client_parser::ascs::kCtpOpcodeRelease: - ON_CALL(ase_ctp_handler, AseCtpReleaseHandler) - .WillByDefault(Invoke(foo)); + ON_CALL(ase_ctp_handler, AseCtpReleaseHandler).WillByDefault(Invoke(foo)); break; default: break; @@ -1453,156 +1327,144 @@ class StateMachineTestBase : public Test { } void PrepareEnableHandler(LeAudioDeviceGroup* group, int verify_ase_count = 0, - bool inject_enabling = true, - bool incject_streaming = true) { + bool inject_enabling = true, bool incject_streaming = true) { ON_CALL(ase_ctp_handler, AseCtpEnableHandler) - .WillByDefault(Invoke([group, verify_ase_count, inject_enabling, - incject_streaming, - this](LeAudioDevice* device, - std::vector value, - GATT_WRITE_OP_CB cb, void* cb_data) { - auto num_ase = value[1]; - - // Verify ase count if needed - if (verify_ase_count) ASSERT_EQ(verify_ase_count, num_ase); - - // Inject Streaming ASE state notification for each requested ASE - auto* ase_p = &value[2]; - for (auto i = 0u; i < num_ase; ++i) { - /* Check if this is a valid ASE ID */ - auto ase_id = *ase_p++; - auto it = std::find_if( - device->ases_.begin(), device->ases_.end(), - [ase_id](auto& ase) { return (ase.id == ase_id); }); - ASSERT_NE(it, device->ases_.end()); - const auto ase = &(*it); - - auto meta_len = *ase_p++; - auto num_handled_bytes = ase_p - value.data(); - ase_p += meta_len; - - client_parser::ascs::ase_transient_state_params enable_params = { - .metadata = std::vector( - value.begin() + num_handled_bytes, - value.begin() + num_handled_bytes + meta_len)}; - - // Server does the 'ReceiverStartReady' on its own - goes to - // Streaming, when in Sink role - if (ase->direction & - bluetooth::le_audio::types::kLeAudioDirectionSink) { - if (inject_enabling) - InjectAseStateNotification(ase, device, group, - ascs::kAseStateEnabling, - &enable_params); - if (incject_streaming) { - InjectAseStateNotification(ase, device, group, - ascs::kAseStateStreaming, - &enable_params); + .WillByDefault(Invoke([group, verify_ase_count, inject_enabling, incject_streaming, + this](LeAudioDevice* device, std::vector value, + GATT_WRITE_OP_CB cb, void* cb_data) { + auto num_ase = value[1]; + + // Verify ase count if needed + if (verify_ase_count) { + ASSERT_EQ(verify_ase_count, num_ase); } - } else { - if (inject_enabling) - InjectAseStateNotification(ase, device, group, - ascs::kAseStateEnabling, - &enable_params); - } - } - })); + + // Inject Streaming ASE state notification for each requested ASE + auto* ase_p = &value[2]; + for (auto i = 0u; i < num_ase; ++i) { + /* Check if this is a valid ASE ID */ + auto ase_id = *ase_p++; + auto it = std::find_if(device->ases_.begin(), device->ases_.end(), + [ase_id](auto& ase) { return ase.id == ase_id; }); + ASSERT_NE(it, device->ases_.end()); + const auto ase = &(*it); + + auto meta_len = *ase_p++; + auto num_handled_bytes = ase_p - value.data(); + ase_p += meta_len; + + client_parser::ascs::ase_transient_state_params enable_params = { + .metadata = + std::vector(value.begin() + num_handled_bytes, + value.begin() + num_handled_bytes + meta_len)}; + + // Server does the 'ReceiverStartReady' on its own - goes to + // Streaming, when in Sink role + if (ase->direction & bluetooth::le_audio::types::kLeAudioDirectionSink) { + if (inject_enabling) { + InjectAseStateNotification(ase, device, group, ascs::kAseStateEnabling, + &enable_params); + } + if (incject_streaming) { + InjectAseStateNotification(ase, device, group, ascs::kAseStateStreaming, + &enable_params); + } + } else { + if (inject_enabling) { + InjectAseStateNotification(ase, device, group, ascs::kAseStateEnabling, + &enable_params); + } + } + } + })); } - void PrepareDisableHandler(LeAudioDeviceGroup* group, - int verify_ase_count = 0) { + void PrepareDisableHandler(LeAudioDeviceGroup* group, int verify_ase_count = 0) { ON_CALL(ase_ctp_handler, AseCtpDisableHandler) - .WillByDefault(Invoke([group, verify_ase_count, this]( - LeAudioDevice* device, - std::vector value, - GATT_WRITE_OP_CB cb, void* cb_data) { - auto num_ase = value[1]; - - // Verify ase count if needed - if (verify_ase_count) ASSERT_EQ(verify_ase_count, num_ase); - ASSERT_EQ(value.size(), 2ul + num_ase); - - // Inject Disabling & QoS Conf. ASE state notification for each ASE - auto* ase_p = &value[2]; - for (auto i = 0u; i < num_ase; ++i) { - /* Check if this is a valid ASE ID */ - auto ase_id = *ase_p++; - auto it = std::find_if( - device->ases_.begin(), device->ases_.end(), - [ase_id](auto& ase) { return (ase.id == ase_id); }); - ASSERT_NE(it, device->ases_.end()); - const auto ase = &(*it); - - // The Disabling state is present for Source ASE - if (ase->direction & - bluetooth::le_audio::types::kLeAudioDirectionSource) { - client_parser::ascs::ase_transient_state_params disabling_params = - {.metadata = {}}; - InjectAseStateNotification(ase, device, group, - ascs::kAseStateDisabling, - &disabling_params); - } + .WillByDefault(Invoke([group, verify_ase_count, this]( + LeAudioDevice* device, std::vector value, + GATT_WRITE_OP_CB cb, void* cb_data) { + auto num_ase = value[1]; - // Server does the 'ReceiverStopReady' on its own - goes to - // Streaming, when in Sink role - if (ase->direction & - bluetooth::le_audio::types::kLeAudioDirectionSink) { - // FIXME: For now our fake peer does not remember qos params - client_parser::ascs::ase_qos_configured_state_params - qos_configured_state_params; - InjectAseStateNotification(ase, device, group, - ascs::kAseStateQoSConfigured, - &qos_configured_state_params); - } - } - })); + // Verify ase count if needed + if (verify_ase_count) { + ASSERT_EQ(verify_ase_count, num_ase); + } + ASSERT_EQ(value.size(), 2ul + num_ase); + + // Inject Disabling & QoS Conf. ASE state notification for each ASE + auto* ase_p = &value[2]; + for (auto i = 0u; i < num_ase; ++i) { + /* Check if this is a valid ASE ID */ + auto ase_id = *ase_p++; + auto it = std::find_if(device->ases_.begin(), device->ases_.end(), + [ase_id](auto& ase) { return ase.id == ase_id; }); + ASSERT_NE(it, device->ases_.end()); + const auto ase = &(*it); + + // The Disabling state is present for Source ASE + if (ase->direction & bluetooth::le_audio::types::kLeAudioDirectionSource) { + client_parser::ascs::ase_transient_state_params disabling_params = { + .metadata = {}}; + InjectAseStateNotification(ase, device, group, ascs::kAseStateDisabling, + &disabling_params); + } + + // Server does the 'ReceiverStopReady' on its own - goes to + // Streaming, when in Sink role + if (ase->direction & bluetooth::le_audio::types::kLeAudioDirectionSink) { + // FIXME: For now our fake peer does not remember qos params + client_parser::ascs::ase_qos_configured_state_params qos_configured_state_params; + InjectAseStateNotification(ase, device, group, ascs::kAseStateQoSConfigured, + &qos_configured_state_params); + } + } + })); } - void PrepareReceiverStartReadyHandler(LeAudioDeviceGroup* group, - int verify_ase_count = 0) { + void PrepareReceiverStartReadyHandler(LeAudioDeviceGroup* group, int verify_ase_count = 0) { ON_CALL(ase_ctp_handler, AseCtpReceiverStartReadyHandler) - .WillByDefault(Invoke([group, verify_ase_count, this]( - LeAudioDevice* device, - std::vector value, - GATT_WRITE_OP_CB cb, void* cb_data) { - auto num_ase = value[1]; - - // Verify ase count if needed - if (verify_ase_count) ASSERT_EQ(verify_ase_count, num_ase); - - // Inject Streaming ASE state notification for each Source ASE - auto* ase_p = &value[2]; - for (auto i = 0u; i < num_ase; ++i) { - /* Check if this is a valid ASE ID */ - auto ase_id = *ase_p++; - auto it = std::find_if( - device->ases_.begin(), device->ases_.end(), - [ase_id](auto& ase) { return (ase.id == ase_id); }); - ASSERT_NE(it, device->ases_.end()); - - // Once we did the 'ReceiverStartReady' the server goes to - // Streaming, when in Source role - const auto& ase = &(*it); - client_parser::ascs::ase_transient_state_params streaming_params = { - .metadata = ase->metadata}; - InjectAseStateNotification(ase, device, group, - ascs::kAseStateStreaming, - &streaming_params); - } - })); + .WillByDefault(Invoke([group, verify_ase_count, this]( + LeAudioDevice* device, std::vector value, + GATT_WRITE_OP_CB cb, void* cb_data) { + auto num_ase = value[1]; + + // Verify ase count if needed + if (verify_ase_count) { + ASSERT_EQ(verify_ase_count, num_ase); + } + + // Inject Streaming ASE state notification for each Source ASE + auto* ase_p = &value[2]; + for (auto i = 0u; i < num_ase; ++i) { + /* Check if this is a valid ASE ID */ + auto ase_id = *ase_p++; + auto it = std::find_if(device->ases_.begin(), device->ases_.end(), + [ase_id](auto& ase) { return ase.id == ase_id; }); + ASSERT_NE(it, device->ases_.end()); + + // Once we did the 'ReceiverStartReady' the server goes to + // Streaming, when in Source role + const auto& ase = &(*it); + client_parser::ascs::ase_transient_state_params streaming_params = { + .metadata = ase->metadata}; + InjectAseStateNotification(ase, device, group, ascs::kAseStateStreaming, + &streaming_params); + } + })); } - void PrepareReceiverStopReady(LeAudioDeviceGroup* group, - int verify_ase_count = 0) { + void PrepareReceiverStopReady(LeAudioDeviceGroup* group, int verify_ase_count = 0) { ON_CALL(ase_ctp_handler, AseCtpReceiverStopReadyHandler) - .WillByDefault( - Invoke([group, verify_ase_count, this]( - LeAudioDevice* device, std::vector value, - GATT_WRITE_OP_CB cb, void* cb_data) { + .WillByDefault(Invoke([group, verify_ase_count, this]( + LeAudioDevice* device, std::vector value, + GATT_WRITE_OP_CB cb, void* cb_data) { auto num_ase = value[1]; // Verify ase count if needed - if (verify_ase_count) ASSERT_EQ(verify_ase_count, num_ase); + if (verify_ase_count) { + ASSERT_EQ(verify_ase_count, num_ase); + } // Inject QoS configured ASE state notification for each Source // ASE @@ -1610,32 +1472,26 @@ class StateMachineTestBase : public Test { for (auto i = 0u; i < num_ase; ++i) { /* Check if this is a valid ASE ID */ auto ase_id = *ase_p++; - auto it = std::find_if( - device->ases_.begin(), device->ases_.end(), - [ase_id](auto& ase) { return (ase.id == ase_id); }); + auto it = std::find_if(device->ases_.begin(), device->ases_.end(), + [ase_id](auto& ase) { return ase.id == ase_id; }); ASSERT_NE(it, device->ases_.end()); const auto& ase = &(*it); // FIXME: For now our fake peer does not remember qos params - client_parser::ascs::ase_qos_configured_state_params - qos_configured_state_params; - InjectAseStateNotification(ase, device, group, - ascs::kAseStateQoSConfigured, + client_parser::ascs::ase_qos_configured_state_params qos_configured_state_params; + InjectAseStateNotification(ase, device, group, ascs::kAseStateQoSConfigured, &qos_configured_state_params); } })); } - void PrepareReleaseHandler(LeAudioDeviceGroup* group, - int verify_ase_count = 0, - bool inject_disconnect_device = false, - LeAudioDevice* dev = nullptr) { + void PrepareReleaseHandler(LeAudioDeviceGroup* group, int verify_ase_count = 0, + bool inject_disconnect_device = false, LeAudioDevice* dev = nullptr) { ON_CALL(ase_ctp_handler, AseCtpReleaseHandler) - .WillByDefault( - Invoke([group, verify_ase_count, inject_disconnect_device, dev, - this](LeAudioDevice* device, std::vector value, - GATT_WRITE_OP_CB cb, void* cb_data) { + .WillByDefault(Invoke([group, verify_ase_count, inject_disconnect_device, dev, this]( + LeAudioDevice* device, std::vector value, + GATT_WRITE_OP_CB cb, void* cb_data) { if (dev != nullptr && device != dev) { log::info("Do nothing for {}", dev->address_); return; @@ -1644,7 +1500,9 @@ class StateMachineTestBase : public Test { auto num_ase = value[1]; // Verify ase count if needed - if (verify_ase_count) ASSERT_EQ(verify_ase_count, num_ase); + if (verify_ase_count) { + ASSERT_EQ(verify_ase_count, num_ase); + } ASSERT_EQ(value.size(), 2ul + num_ase); if (inject_disconnect_device) { @@ -1657,14 +1515,12 @@ class StateMachineTestBase : public Test { for (auto i = 0u; i < num_ase; ++i) { /* Check if this is a valid ASE ID */ auto ase_id = *ase_p++; - auto it = std::find_if( - device->ases_.begin(), device->ases_.end(), - [ase_id](auto& ase) { return (ase.id == ase_id); }); + auto it = std::find_if(device->ases_.begin(), device->ases_.end(), + [ase_id](auto& ase) { return ase.id == ase_id; }); ASSERT_NE(it, device->ases_.end()); const auto ase = &(*it); - InjectAseStateNotification(ase, device, group, - ascs::kAseStateReleasing, nullptr); + InjectAseStateNotification(ase, device, group, ascs::kAseStateReleasing, nullptr); if (stay_in_releasing_state_) { continue; @@ -1672,13 +1528,11 @@ class StateMachineTestBase : public Test { /* Check if codec configuration is cached */ if (cached_codec_configuration_map_.count(ase_id) > 0) { - InjectAseStateNotification( - ase, device, group, ascs::kAseStateCodecConfigured, - &cached_codec_configuration_map_[ase_id]); + InjectAseStateNotification(ase, device, group, ascs::kAseStateCodecConfigured, + &cached_codec_configuration_map_[ase_id]); } else { // Release - no caching - InjectAseStateNotification(ase, device, group, - ascs::kAseStateIdle, nullptr); + InjectAseStateNotification(ase, device, group, ascs::kAseStateIdle, nullptr); } } })); @@ -1697,19 +1551,16 @@ class StateMachineTestBase : public Test { MockAseRemoteStateMachine ase_ctp_handler; std::map - cached_codec_configuration_map_; - std::map - cached_qos_configuration_map_; + cached_codec_configuration_map_; + std::map cached_qos_configuration_map_; std::map> cached_ase_to_cis_id_map_; - std::map> - cached_remote_qos_configuration_for_ase_; + std::map> cached_remote_qos_configuration_for_ase_; MockLeAudioGroupStateMachineCallbacks mock_callbacks_; std::vector> le_audio_devices_; std::vector addresses_; - std::map> - le_audio_device_groups_; + std::map> le_audio_device_groups_; bool group_create_command_disallowed_ = false; bluetooth::hci::testing::MockControllerInterface controller_; }; @@ -1718,7 +1569,7 @@ class StateMachineTest : public StateMachineTestBase { void SetUp() override { ConfigCodecManagerMock(types::CodecLocation::HOST); ::bluetooth::le_audio::AudioSetConfigurationProvider::Initialize( - ::bluetooth::le_audio::types::CodecLocation::HOST); + ::bluetooth::le_audio::types::CodecLocation::HOST); StateMachineTestBase::SetUp(); } }; @@ -1727,9 +1578,8 @@ class StateMachineTestNoSwb : public StateMachineTestBase { void SetUp() override { ConfigCodecManagerMock(types::CodecLocation::HOST); ::bluetooth::le_audio::AudioSetConfigurationProvider::Initialize( - ::bluetooth::le_audio::types::CodecLocation::HOST); - ON_CALL(*mock_codec_manager_, IsDualBiDirSwbSupported) - .WillByDefault(Return(false)); + ::bluetooth::le_audio::types::CodecLocation::HOST); + ON_CALL(*mock_codec_manager_, IsDualBiDirSwbSupported).WillByDefault(Return(false)); StateMachineTestBase::SetUp(); } }; @@ -1738,14 +1588,12 @@ class StateMachineTestAdsp : public StateMachineTestBase { void SetUp() override { ConfigCodecManagerMock(types::CodecLocation::ADSP); ::bluetooth::le_audio::AudioSetConfigurationProvider::Initialize( - ::bluetooth::le_audio::types::CodecLocation::ADSP); + ::bluetooth::le_audio::types::CodecLocation::ADSP); StateMachineTestBase::SetUp(); } }; -TEST_F(StateMachineTest, testInit) { - ASSERT_NE(LeAudioGroupStateMachine::Get(), nullptr); -} +TEST_F(StateMachineTest, testInit) { ASSERT_NE(LeAudioGroupStateMachine::Get(), nullptr); } TEST_F(StateMachineTest, testCleanup) { ASSERT_NE(LeAudioGroupStateMachine::Get(), nullptr); @@ -1759,8 +1607,7 @@ TEST_F(StateMachineTest, testConfigureCodecSingle) { */ const auto context_type = kContextTypeRingtone; const int leaudio_group_id = 2; - channel_count_ = kLeAudioCodecChannelCountSingleChannel | - kLeAudioCodecChannelCountTwoChannel; + channel_count_ = kLeAudioCodecChannelCountSingleChannel | kLeAudioCodecChannelCountTwoChannel; // Prepare fake connected device group auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type); @@ -1774,9 +1621,8 @@ TEST_F(StateMachineTest, testConfigureCodecSingle) { /* Start the configuration and stream Media content. * Expect 1 time for the Codec Config call only. */ EXPECT_CALL(gatt_queue, - WriteCharacteristic(1, leAudioDevice->ctp_hdls_.val_hdl, _, - GATT_WRITE_NO_RSP, _, _)) - .Times(1); + WriteCharacteristic(1, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) + .Times(1); /* Do nothing on the CigCreate, so the state machine stays in the configure * state */ @@ -1786,13 +1632,12 @@ TEST_F(StateMachineTest, testConfigureCodecSingle) { InjectInitialIdleNotification(group); ASSERT_TRUE(LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)})); + group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)})); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED); /* Cancel is called when group goes to streaming. */ ASSERT_EQ(0, get_func_call_count("alarm_cancel")); @@ -1804,90 +1649,83 @@ TEST_F(StateMachineTest, testConfigureCodecSingleFb2) { bool is_fb2_passed_as_source_requirement = false; ON_CALL(*mock_codec_manager_, GetCodecConfig) - .WillByDefault(Invoke([&](const bluetooth::le_audio::CodecManager:: - UnicastConfigurationRequirements& - requirements, - bluetooth::le_audio::CodecManager:: - UnicastConfigurationVerifier verifier) { - auto configs = - *bluetooth::le_audio::AudioSetConfigurationProvider::Get() - ->GetConfigurations(requirements.audio_context_type); - // Note: This dual bidir SWB exclusion logic has to match the - // CodecManager::GetCodecConfig() implementation. - if (!CodecManager::GetInstance()->IsDualBiDirSwbSupported()) { - configs.erase( - std::remove_if(configs.begin(), configs.end(), - [](auto const& el) { - if (el->confs.source.empty()) return false; - return AudioSetConfigurationProvider::Get() - ->CheckConfigurationIsDualBiDirSwb(*el); - }), - configs.end()); - } + .WillByDefault(Invoke([&](const bluetooth::le_audio::CodecManager:: + UnicastConfigurationRequirements& requirements, + bluetooth::le_audio::CodecManager::UnicastConfigurationVerifier + verifier) { + auto configs = + *bluetooth::le_audio::AudioSetConfigurationProvider::Get()->GetConfigurations( + requirements.audio_context_type); + // Note: This dual bidir SWB exclusion logic has to match the + // CodecManager::GetCodecConfig() implementation. + if (!CodecManager::GetInstance()->IsDualBiDirSwbSupported()) { + configs.erase(std::remove_if(configs.begin(), configs.end(), + [](auto const& el) { + if (el->confs.source.empty()) { + return false; + } + return AudioSetConfigurationProvider::Get() + ->CheckConfigurationIsDualBiDirSwb(*el); + }), + configs.end()); + } - auto cfg = verifier(requirements, &configs); - if (cfg == nullptr) { - return std::unique_ptr< - bluetooth::le_audio::set_configurations::AudioSetConfiguration>( - nullptr); - } - auto config = *cfg; - - if (requirements.sink_pacs.has_value()) { - for (auto const& rec : requirements.sink_pacs.value()) { - auto caps = rec.codec_spec_caps.GetAsCoreCodecCapabilities(); - if (caps.HasSupportedMaxCodecFramesPerSdu()) { - if (caps.supported_max_codec_frames_per_sdu.value() == - codec_frame_blocks_per_sdu_) { - // Scale by Codec Frames Per SDU = 2 - for (auto& entry : config.confs.sink) { - entry.codec.params.Add( - codec_spec_conf::kLeAudioLtvTypeCodecFrameBlocksPerSdu, - (uint8_t)codec_frame_blocks_per_sdu_); - entry.qos.maxSdu *= codec_frame_blocks_per_sdu_; - entry.qos.sduIntervalUs *= codec_frame_blocks_per_sdu_; - entry.qos.max_transport_latency *= - codec_frame_blocks_per_sdu_; + auto cfg = verifier(requirements, &configs); + if (cfg == nullptr) { + return std::unique_ptr< + bluetooth::le_audio::set_configurations::AudioSetConfiguration>(nullptr); + } + auto config = *cfg; + + if (requirements.sink_pacs.has_value()) { + for (auto const& rec : requirements.sink_pacs.value()) { + auto caps = rec.codec_spec_caps.GetAsCoreCodecCapabilities(); + if (caps.HasSupportedMaxCodecFramesPerSdu()) { + if (caps.supported_max_codec_frames_per_sdu.value() == + codec_frame_blocks_per_sdu_) { + // Scale by Codec Frames Per SDU = 2 + for (auto& entry : config.confs.sink) { + entry.codec.params.Add(codec_spec_conf::kLeAudioLtvTypeCodecFrameBlocksPerSdu, + (uint8_t)codec_frame_blocks_per_sdu_); + entry.qos.maxSdu *= codec_frame_blocks_per_sdu_; + entry.qos.sduIntervalUs *= codec_frame_blocks_per_sdu_; + entry.qos.max_transport_latency *= codec_frame_blocks_per_sdu_; + } + is_fb2_passed_as_sink_requirement = true; + } } - is_fb2_passed_as_sink_requirement = true; } } - } - } - if (requirements.source_pacs.has_value()) { - for (auto const& rec : requirements.source_pacs.value()) { - auto caps = rec.codec_spec_caps.GetAsCoreCodecCapabilities(); - if (caps.HasSupportedMaxCodecFramesPerSdu()) { - if (caps.supported_max_codec_frames_per_sdu.value() == - codec_frame_blocks_per_sdu_) { - // Scale by Codec Frames Per SDU = 2 - for (auto& entry : config.confs.source) { - entry.codec.params.Add( - codec_spec_conf::kLeAudioLtvTypeCodecFrameBlocksPerSdu, - (uint8_t)codec_frame_blocks_per_sdu_); - entry.qos.maxSdu *= codec_frame_blocks_per_sdu_; - entry.qos.sduIntervalUs *= codec_frame_blocks_per_sdu_; - entry.qos.max_transport_latency *= - codec_frame_blocks_per_sdu_; + if (requirements.source_pacs.has_value()) { + for (auto const& rec : requirements.source_pacs.value()) { + auto caps = rec.codec_spec_caps.GetAsCoreCodecCapabilities(); + if (caps.HasSupportedMaxCodecFramesPerSdu()) { + if (caps.supported_max_codec_frames_per_sdu.value() == + codec_frame_blocks_per_sdu_) { + // Scale by Codec Frames Per SDU = 2 + for (auto& entry : config.confs.source) { + entry.codec.params.Add(codec_spec_conf::kLeAudioLtvTypeCodecFrameBlocksPerSdu, + (uint8_t)codec_frame_blocks_per_sdu_); + entry.qos.maxSdu *= codec_frame_blocks_per_sdu_; + entry.qos.sduIntervalUs *= codec_frame_blocks_per_sdu_; + entry.qos.max_transport_latency *= codec_frame_blocks_per_sdu_; + } + is_fb2_passed_as_source_requirement = true; + } } - is_fb2_passed_as_source_requirement = true; } } - } - } - return std::make_unique< - bluetooth::le_audio::set_configurations::AudioSetConfiguration>( - config); - })); + return std::make_unique( + config); + })); /* Device is banded headphones with 1x snk + 0x src ase * (1xunidirectional CIS) with channel count 2 (for stereo */ const auto context_type = kContextTypeRingtone; const int leaudio_group_id = 2; - channel_count_ = kLeAudioCodecChannelCountSingleChannel | - kLeAudioCodecChannelCountTwoChannel; + channel_count_ = kLeAudioCodecChannelCountSingleChannel | kLeAudioCodecChannelCountTwoChannel; /* Prepare the fake connected device group */ auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type); @@ -1901,21 +1739,19 @@ TEST_F(StateMachineTest, testConfigureCodecSingleFb2) { /* Start the configuration and stream Media content. * Expect 2 times: for Codec Configure & QoS Configure */ EXPECT_CALL(gatt_queue, - WriteCharacteristic(1, leAudioDevice->ctp_hdls_.val_hdl, _, - GATT_WRITE_NO_RSP, _, _)) - .Times(2); + WriteCharacteristic(1, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) + .Times(2); InjectInitialIdleNotification(group); EXPECT_CALL(*mock_iso_manager_, CreateCig).Times(1); ASSERT_TRUE(LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)})); + group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)})); /* Check if group has transitioned to a proper state */ - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED); /* Cancel is called when group goes to streaming. */ ASSERT_EQ(0, get_func_call_count("alarm_cancel")); @@ -1923,22 +1759,17 @@ TEST_F(StateMachineTest, testConfigureCodecSingleFb2) { ASSERT_TRUE(is_fb2_passed_as_sink_requirement); /* Make sure that data interval is based on the codec frame blocks count */ - auto data_interval = group->GetActiveConfiguration() - ->confs.sink.at(0) - .codec.GetDataIntervalUs(); + auto data_interval = group->GetActiveConfiguration()->confs.sink.at(0).codec.GetDataIntervalUs(); ASSERT_EQ(data_interval, group->GetActiveConfiguration() - ->confs.sink.at(0) - .codec.params.GetAsCoreCodecConfig() - .GetFrameDurationUs() * - codec_frame_blocks_per_sdu_); + ->confs.sink.at(0) + .codec.params.GetAsCoreCodecConfig() + .GetFrameDurationUs() * + codec_frame_blocks_per_sdu_); /* Verify CIG parameters */ - auto channel_count = group->GetActiveConfiguration() - ->confs.sink.at(0) - .codec.GetChannelCountPerIsoStream(); - auto frame_octets = group->GetActiveConfiguration() - ->confs.sink.at(0) - .codec.GetOctectsPerFrame(); + auto channel_count = + group->GetActiveConfiguration()->confs.sink.at(0).codec.GetChannelCountPerIsoStream(); + auto frame_octets = group->GetActiveConfiguration()->confs.sink.at(0).codec.GetOctetsPerFrame(); ASSERT_NE(last_cig_params_.cis_cfgs.size(), 0lu); ASSERT_EQ(last_cig_params_.sdu_itv_mtos, data_interval); ASSERT_EQ(last_cig_params_.cis_cfgs.at(0).max_sdu_size_mtos, @@ -1951,8 +1782,7 @@ TEST_F(StateMachineTest, testConfigureCodecMulti) { const auto num_devices = 2; // Prepare multiple fake connected devices in a group - auto* group = - PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); ASSERT_EQ(group->Size(), num_devices); PrepareConfigureCodecHandler(group); @@ -1961,10 +1791,9 @@ TEST_F(StateMachineTest, testConfigureCodecMulti) { auto* leAudioDevice = group->GetFirstDevice(); while (leAudioDevice) { EXPECT_CALL(gatt_queue, - WriteCharacteristic(leAudioDevice->conn_id_, - leAudioDevice->ctp_hdls_.val_hdl, _, + WriteCharacteristic(leAudioDevice->conn_id_, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) - .Times(AtLeast(1)); + .Times(AtLeast(1)); expected_devices_written++; leAudioDevice = group->GetNextDevice(leAudioDevice); } @@ -1979,13 +1808,12 @@ TEST_F(StateMachineTest, testConfigureCodecMulti) { // Start the configuration and stream the content ASSERT_TRUE(LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)})); + group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)})); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED); /* Cancel is called when group goes to streaming. */ ASSERT_EQ(0, get_func_call_count("alarm_cancel")); @@ -2012,9 +1840,8 @@ TEST_F(StateMachineTest, testConfigureQosSingle) { // Start the configuration and stream Media content EXPECT_CALL(gatt_queue, - WriteCharacteristic(1, leAudioDevice->ctp_hdls_.val_hdl, _, - GATT_WRITE_NO_RSP, _, _)) - .Times(3); + WriteCharacteristic(1, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) + .Times(3); EXPECT_CALL(*mock_iso_manager_, CreateCig(_, _)).Times(1); EXPECT_CALL(*mock_iso_manager_, EstablishCis(_)).Times(0); @@ -2026,13 +1853,12 @@ TEST_F(StateMachineTest, testConfigureQosSingle) { InjectInitialIdleNotification(group); ASSERT_TRUE(LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)})); + group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)})); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED); ASSERT_EQ(0, get_func_call_count("alarm_cancel")); } @@ -2061,9 +1887,8 @@ TEST_F(StateMachineTest, testConfigureQosSingleRecoverCig) { // Start the configuration and stream Media content EXPECT_CALL(gatt_queue, - WriteCharacteristic(1, leAudioDevice->ctp_hdls_.val_hdl, _, - GATT_WRITE_NO_RSP, _, _)) - .Times(3); + WriteCharacteristic(1, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) + .Times(3); EXPECT_CALL(*mock_iso_manager_, CreateCig(_, _)).Times(2); EXPECT_CALL(*mock_iso_manager_, RemoveCig(_, _)).Times(1); @@ -2075,13 +1900,12 @@ TEST_F(StateMachineTest, testConfigureQosSingleRecoverCig) { InjectInitialIdleNotification(group); ASSERT_TRUE(LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)})); + group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)})); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED); ASSERT_EQ(0, get_func_call_count("alarm_cancel")); } @@ -2091,8 +1915,7 @@ TEST_F(StateMachineTest, testConfigureQosMultiple) { const auto num_devices = 2; // Prepare multiple fake connected devices in a group - auto* group = - PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); ASSERT_EQ(group->Size(), num_devices); PrepareConfigureCodecHandler(group); @@ -2102,10 +1925,9 @@ TEST_F(StateMachineTest, testConfigureQosMultiple) { auto expected_devices_written = 0; while (leAudioDevice) { EXPECT_CALL(gatt_queue, - WriteCharacteristic(leAudioDevice->conn_id_, - leAudioDevice->ctp_hdls_.val_hdl, _, + WriteCharacteristic(leAudioDevice->conn_id_, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) - .Times(AtLeast(2)); + .Times(AtLeast(2)); expected_devices_written++; leAudioDevice = group->GetNextDevice(leAudioDevice); } @@ -2122,13 +1944,12 @@ TEST_F(StateMachineTest, testConfigureQosMultiple) { // Start the configuration and stream Media content ASSERT_TRUE(LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)})); + group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)})); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED); ASSERT_EQ(0, get_func_call_count("alarm_cancel")); } @@ -2140,25 +1961,23 @@ TEST_F(StateMachineTest, testConfigureQosFailed) { // Check if CIG is properly cleared when QoS failed // Prepare multiple fake connected devices in a group - auto* group = - PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); ASSERT_EQ(group->Size(), num_devices); PrepareConfigureCodecHandler(group); PrepareCtpNotificationError( - group, client_parser::ascs::kCtpOpcodeQosConfiguration, - client_parser::ascs::kCtpResponseCodeInvalidConfigurationParameterValue, - client_parser::ascs::kCtpResponsePhy); + group, client_parser::ascs::kCtpOpcodeQosConfiguration, + client_parser::ascs::kCtpResponseCodeInvalidConfigurationParameterValue, + client_parser::ascs::kCtpResponsePhy); PrepareReleaseHandler(group); auto* leAudioDevice = group->GetFirstDevice(); auto expected_devices_written = 0; while (leAudioDevice) { EXPECT_CALL(gatt_queue, - WriteCharacteristic(leAudioDevice->conn_id_, - leAudioDevice->ctp_hdls_.val_hdl, _, + WriteCharacteristic(leAudioDevice->conn_id_, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) - .Times(AtLeast(2)); + .Times(AtLeast(2)); expected_devices_written++; leAudioDevice = group->GetNextDevice(leAudioDevice); } @@ -2175,9 +1994,9 @@ TEST_F(StateMachineTest, testConfigureQosFailed) { // Start the configuration and stream Media content ASSERT_TRUE(LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)})); + group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)})); // Check if group has transitioned to a proper state ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_IDLE); @@ -2194,8 +2013,7 @@ TEST_F(StateMachineTest, testDeviceDisconnectedWhileCigCreated) { // verify proper cleaning when group is disconnected while CIG is creating. // Prepare fake connected device in a group - auto* group = - PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); ASSERT_EQ(group->Size(), num_devices); PrepareConfigureCodecHandler(group); @@ -2203,10 +2021,10 @@ TEST_F(StateMachineTest, testDeviceDisconnectedWhileCigCreated) { ON_CALL(*mock_iso_manager_, CreateCig).WillByDefault(Return()); auto* leAudioDevice = group->GetFirstDevice(); - EXPECT_CALL(gatt_queue, WriteCharacteristic(leAudioDevice->conn_id_, - leAudioDevice->ctp_hdls_.val_hdl, - _, GATT_WRITE_NO_RSP, _, _)) - .Times(1); + EXPECT_CALL(gatt_queue, + WriteCharacteristic(leAudioDevice->conn_id_, leAudioDevice->ctp_hdls_.val_hdl, _, + GATT_WRITE_NO_RSP, _, _)) + .Times(1); EXPECT_CALL(*mock_iso_manager_, CreateCig(_, _)).Times(1); EXPECT_CALL(*mock_iso_manager_, EstablishCis(_)).Times(0); @@ -2218,13 +2036,12 @@ TEST_F(StateMachineTest, testDeviceDisconnectedWhileCigCreated) { // Start the configuration and stream Media content ASSERT_TRUE(LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)})); + group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)})); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED); testing::Mock::VerifyAndClearExpectations(mock_iso_manager_); @@ -2233,8 +2050,8 @@ TEST_F(StateMachineTest, testDeviceDisconnectedWhileCigCreated) { int cig_id = 1; EXPECT_CALL(*mock_iso_manager_, RemoveCig(_, _)).Times(1); - LeAudioGroupStateMachine::Get()->ProcessHciNotifOnCigCreate( - group, HCI_SUCCESS, cig_id, conn_handles); + LeAudioGroupStateMachine::Get()->ProcessHciNotifOnCigCreate(group, HCI_SUCCESS, cig_id, + conn_handles); ASSERT_EQ(1, get_func_call_count("alarm_cancel")); testing::Mock::VerifyAndClearExpectations(mock_iso_manager_); @@ -2246,8 +2063,7 @@ TEST_F(StateMachineTest, testStreamCreationError) { */ const auto context_type = kContextTypeRingtone; const int leaudio_group_id = 4; - channel_count_ = kLeAudioCodecChannelCountSingleChannel | - kLeAudioCodecChannelCountTwoChannel; + channel_count_ = kLeAudioCodecChannelCountSingleChannel | kLeAudioCodecChannelCountTwoChannel; // Prepare fake connected device group auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type); @@ -2257,10 +2073,9 @@ TEST_F(StateMachineTest, testStreamCreationError) { */ PrepareConfigureCodecHandler(group, 1); PrepareConfigureQosHandler(group, 1); - PrepareCtpNotificationError( - group, client_parser::ascs::kCtpOpcodeEnable, - client_parser::ascs::kCtpResponseCodeUnspecifiedError, - client_parser::ascs::kCtpResponseNoReason); + PrepareCtpNotificationError(group, client_parser::ascs::kCtpOpcodeEnable, + client_parser::ascs::kCtpResponseCodeUnspecifiedError, + client_parser::ascs::kCtpResponseNoReason); PrepareReleaseHandler(group); auto* leAudioDevice = group->GetFirstDevice(); @@ -2272,9 +2087,8 @@ TEST_F(StateMachineTest, testStreamCreationError) { * 4 - Release ASE */ EXPECT_CALL(gatt_queue, - WriteCharacteristic(1, leAudioDevice->ctp_hdls_.val_hdl, _, - GATT_WRITE_NO_RSP, _, _)) - .Times(4); + WriteCharacteristic(1, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) + .Times(4); EXPECT_CALL(*mock_iso_manager_, CreateCig(_, _)).Times(1); EXPECT_CALL(*mock_iso_manager_, EstablishCis(_)).Times(0); @@ -2286,19 +2100,16 @@ TEST_F(StateMachineTest, testStreamCreationError) { InjectInitialIdleNotification(group); // Validate GroupStreamStatus - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::RELEASING)); EXPECT_CALL(mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::IDLE)); + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::RELEASING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::IDLE)); // Start the configuration and stream Media content ASSERT_TRUE(LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)})); + group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)})); // Check if group has transitioned to a proper state ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_IDLE); @@ -2311,8 +2122,7 @@ TEST_F(StateMachineTest, testStreamSingle) { */ const auto context_type = kContextTypeRingtone; const int leaudio_group_id = 4; - channel_count_ = kLeAudioCodecChannelCountSingleChannel | - kLeAudioCodecChannelCountTwoChannel; + channel_count_ = kLeAudioCodecChannelCountSingleChannel | kLeAudioCodecChannelCountTwoChannel; // Prepare fake connected device group auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type); @@ -2326,9 +2136,8 @@ TEST_F(StateMachineTest, testStreamSingle) { auto* leAudioDevice = group->GetFirstDevice(); EXPECT_CALL(gatt_queue, - WriteCharacteristic(1, leAudioDevice->ctp_hdls_.val_hdl, _, - GATT_WRITE_NO_RSP, _, _)) - .Times(3); + WriteCharacteristic(1, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) + .Times(3); EXPECT_CALL(*mock_iso_manager_, CreateCig(_, _)).Times(1); EXPECT_CALL(*mock_iso_manager_, EstablishCis(_)).Times(1); @@ -2340,20 +2149,17 @@ TEST_F(StateMachineTest, testStreamSingle) { InjectInitialIdleNotification(group); // Validate GroupStreamStatus - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::STREAMING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::STREAMING)); // Start the configuration and stream Media content ASSERT_TRUE(LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)})); + group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)})); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); ASSERT_EQ(1, get_func_call_count("alarm_cancel")); } @@ -2363,8 +2169,7 @@ TEST_F(StateMachineTest, testStreamSingleRetryCisFailure) { */ const auto context_type = kContextTypeRingtone; const int leaudio_group_id = 4; - channel_count_ = kLeAudioCodecChannelCountSingleChannel | - kLeAudioCodecChannelCountTwoChannel; + channel_count_ = kLeAudioCodecChannelCountSingleChannel | kLeAudioCodecChannelCountTwoChannel; // Prepare fake connected device group auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type); @@ -2382,9 +2187,8 @@ TEST_F(StateMachineTest, testStreamSingleRetryCisFailure) { auto* leAudioDevice = group->GetFirstDevice(); EXPECT_CALL(gatt_queue, - WriteCharacteristic(1, leAudioDevice->ctp_hdls_.val_hdl, _, - GATT_WRITE_NO_RSP, _, _)) - .Times(4); + WriteCharacteristic(1, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) + .Times(4); EXPECT_CALL(*mock_iso_manager_, CreateCig(_, _)).Times(1); EXPECT_CALL(*mock_iso_manager_, EstablishCis(_)).Times(3); @@ -2396,19 +2200,16 @@ TEST_F(StateMachineTest, testStreamSingleRetryCisFailure) { InjectInitialIdleNotification(group); // Validate GroupStreamStatus - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::RELEASING)); EXPECT_CALL(mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::IDLE)); + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::RELEASING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::IDLE)); // Start the configuration and stream Media content ASSERT_TRUE(LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)})); + group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)})); // Check if group has transitioned to a proper state ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_IDLE); @@ -2421,8 +2222,7 @@ TEST_F(StateMachineTest, testStreamSingleRetryCisSuccess) { */ const auto context_type = kContextTypeRingtone; const int leaudio_group_id = 4; - channel_count_ = kLeAudioCodecChannelCountSingleChannel | - kLeAudioCodecChannelCountTwoChannel; + channel_count_ = kLeAudioCodecChannelCountSingleChannel | kLeAudioCodecChannelCountTwoChannel; // Prepare fake connected device group auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type); @@ -2439,9 +2239,8 @@ TEST_F(StateMachineTest, testStreamSingleRetryCisSuccess) { auto* leAudioDevice = group->GetFirstDevice(); EXPECT_CALL(gatt_queue, - WriteCharacteristic(1, leAudioDevice->ctp_hdls_.val_hdl, _, - GATT_WRITE_NO_RSP, _, _)) - .Times(3); + WriteCharacteristic(1, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) + .Times(3); EXPECT_CALL(*mock_iso_manager_, CreateCig(_, _)).Times(1); EXPECT_CALL(*mock_iso_manager_, EstablishCis(_)).Times(3); @@ -2453,20 +2252,17 @@ TEST_F(StateMachineTest, testStreamSingleRetryCisSuccess) { InjectInitialIdleNotification(group); // Validate GroupStreamStatus - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::STREAMING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::STREAMING)); // Start the configuration and stream Media content ASSERT_TRUE(LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)})); + group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)})); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); ASSERT_EQ(1, get_func_call_count("alarm_cancel")); } @@ -2502,9 +2298,8 @@ TEST_F(StateMachineTest, testStreamSkipEnablingSink) { */ auto* leAudioDevice = group->GetFirstDevice(); EXPECT_CALL(gatt_queue, - WriteCharacteristic(1, leAudioDevice->ctp_hdls_.val_hdl, _, - GATT_WRITE_NO_RSP, _, _)) - .Times(4); + WriteCharacteristic(1, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) + .Times(4); EXPECT_CALL(*mock_iso_manager_, CreateCig(_, _)).Times(1); EXPECT_CALL(*mock_iso_manager_, EstablishCis(_)).Times(0); @@ -2517,20 +2312,18 @@ TEST_F(StateMachineTest, testStreamSkipEnablingSink) { // Validate GroupStreamStatus EXPECT_CALL(mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::STREAMING)) - .Times(0); + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::STREAMING)) + .Times(0); EXPECT_CALL(mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::RELEASING)) - .Times(1); + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::RELEASING)) + .Times(1); // Start the configuration and stream Media content ASSERT_TRUE(LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)})); + group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)})); ASSERT_EQ(1, get_func_call_count("alarm_cancel")); } @@ -2563,9 +2356,8 @@ TEST_F(StateMachineTest, testStreamSkipEnablingSinkSource) { */ auto* leAudioDevice = group->GetFirstDevice(); EXPECT_CALL(gatt_queue, - WriteCharacteristic(1, leAudioDevice->ctp_hdls_.val_hdl, _, - GATT_WRITE_NO_RSP, _, _)) - .Times(4); + WriteCharacteristic(1, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) + .Times(4); EXPECT_CALL(*mock_iso_manager_, CreateCig(_, _)).Times(1); EXPECT_CALL(*mock_iso_manager_, EstablishCis(_)).Times(0); @@ -2578,19 +2370,17 @@ TEST_F(StateMachineTest, testStreamSkipEnablingSinkSource) { // Validate GroupStreamStatus EXPECT_CALL(mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::STREAMING)) - .Times(0); + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::STREAMING)) + .Times(0); EXPECT_CALL(mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::RELEASING)) - .Times(1); + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::RELEASING)) + .Times(1); // Start the configuration and stream Media content ASSERT_TRUE(LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)})); + group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)})); ASSERT_EQ(1, get_func_call_count("alarm_cancel")); } @@ -2602,9 +2392,8 @@ TEST_F(StateMachineTest, testStreamMultipleMedia_OneMemberHasNoAses) { // Prepare multiple fake connected devices in a group. This time one device // has 0 Ases - auto* group = - PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices, - types::AudioContexts(), true); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices, + types::AudioContexts(), true); ASSERT_EQ(group->Size(), num_devices); PrepareConfigureCodecHandler(group); @@ -2628,10 +2417,10 @@ TEST_F(StateMachineTest, testStreamMultipleMedia_OneMemberHasNoAses) { * First set member has no ASEs, no operations on control point are expected * 0 */ - EXPECT_CALL(gatt_queue, WriteCharacteristic(leAudioDevice->conn_id_, - leAudioDevice->ctp_hdls_.val_hdl, - _, GATT_WRITE_NO_RSP, _, _)) - .Times(0); + EXPECT_CALL(gatt_queue, + WriteCharacteristic(leAudioDevice->conn_id_, leAudioDevice->ctp_hdls_.val_hdl, _, + GATT_WRITE_NO_RSP, _, _)) + .Times(0); auto expected_devices_written = 0; while (leAudioDevice) { @@ -2647,40 +2436,34 @@ TEST_F(StateMachineTest, testStreamMultipleMedia_OneMemberHasNoAses) { * 2. QoS Config * 3. Enable */ - EXPECT_CALL(gatt_queue, WriteCharacteristic(lastDevice->conn_id_, - lastDevice->ctp_hdls_.val_hdl, _, - GATT_WRITE_NO_RSP, _, _)) - .Times(3); + EXPECT_CALL(gatt_queue, WriteCharacteristic(lastDevice->conn_id_, lastDevice->ctp_hdls_.val_hdl, + _, GATT_WRITE_NO_RSP, _, _)) + .Times(3); // Validate GroupStreamStatus - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::STREAMING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::STREAMING)); // Start the configuration and stream Media content ASSERT_TRUE(LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)})); + group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)})); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); ASSERT_EQ(1, get_func_call_count("alarm_cancel")); } -TEST_F(StateMachineTest, - testStreamMultipleMedia_OneMemberHasNoAsesAndNotConnected) { +TEST_F(StateMachineTest, testStreamMultipleMedia_OneMemberHasNoAsesAndNotConnected) { const auto context_type = kContextTypeMedia; const auto leaudio_group_id = 4; const auto num_devices = 2; // Prepare multiple fake connected devices in a group. This time one device // has 0 Ases - auto* group = - PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices, - types::AudioContexts(), true); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices, + types::AudioContexts(), true); ASSERT_EQ(group->Size(), num_devices); PrepareConfigureCodecHandler(group); @@ -2704,10 +2487,10 @@ TEST_F(StateMachineTest, * First set member has no ASEs, no operations on control point are expected * 0 */ - EXPECT_CALL(gatt_queue, WriteCharacteristic(leAudioDevice->conn_id_, - leAudioDevice->ctp_hdls_.val_hdl, - _, GATT_WRITE_NO_RSP, _, _)) - .Times(0); + EXPECT_CALL(gatt_queue, + WriteCharacteristic(leAudioDevice->conn_id_, leAudioDevice->ctp_hdls_.val_hdl, _, + GATT_WRITE_NO_RSP, _, _)) + .Times(0); /* Device with 0 Ases is disconnected */ InjectAclDisconnected(group, leAudioDevice); @@ -2726,26 +2509,22 @@ TEST_F(StateMachineTest, * 2. QoS Config * 3. Enable */ - EXPECT_CALL(gatt_queue, WriteCharacteristic(lastDevice->conn_id_, - lastDevice->ctp_hdls_.val_hdl, _, - GATT_WRITE_NO_RSP, _, _)) - .Times(3); + EXPECT_CALL(gatt_queue, WriteCharacteristic(lastDevice->conn_id_, lastDevice->ctp_hdls_.val_hdl, + _, GATT_WRITE_NO_RSP, _, _)) + .Times(3); // Validate GroupStreamStatus - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::STREAMING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::STREAMING)); // Start the configuration and stream Media content ASSERT_TRUE(LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)})); + group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)})); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); ASSERT_EQ(1, get_func_call_count("alarm_cancel")); } @@ -2755,8 +2534,7 @@ TEST_F(StateMachineTest, testStreamMultipleConversational) { const auto num_devices = 2; // Prepare multiple fake connected devices in a group - auto* group = - PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); ASSERT_EQ(group->Size(), num_devices); PrepareConfigureCodecHandler(group); @@ -2777,36 +2555,30 @@ TEST_F(StateMachineTest, testStreamMultipleConversational) { auto expected_devices_written = 0; while (leAudioDevice) { EXPECT_CALL(gatt_queue, - WriteCharacteristic(leAudioDevice->conn_id_, - leAudioDevice->ctp_hdls_.val_hdl, _, + WriteCharacteristic(leAudioDevice->conn_id_, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) - .Times(4); + .Times(4); expected_devices_written++; leAudioDevice = group->GetNextDevice(leAudioDevice); } ASSERT_EQ(expected_devices_written, num_devices); // Validate GroupStreamStatus - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::STREAMING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::STREAMING)); // Start the configuration and stream Media content ASSERT_TRUE(LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)})); + group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)})); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); ASSERT_EQ(1, get_func_call_count("alarm_cancel")); } -MATCHER_P(dataPathDirIsEq, expected, "") { - return (arg.data_path_dir == expected); -} +MATCHER_P(dataPathDirIsEq, expected, "") { return arg.data_path_dir == expected; } TEST_F(StateMachineTest, testFailedStreamMultipleConversational) { /* Testing here CIS Failed to be established */ @@ -2820,8 +2592,7 @@ TEST_F(StateMachineTest, testFailedStreamMultipleConversational) { cis_status_[1] = 0x0e; // Failed to be established // Prepare multiple fake connected devices in a group - auto* group = - PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); ASSERT_EQ(group->Size(), num_devices); PrepareConfigureCodecHandler(group); @@ -2838,21 +2609,17 @@ TEST_F(StateMachineTest, testFailedStreamMultipleConversational) { */ EXPECT_CALL(*mock_iso_manager_, SetupIsoDataPath( - _, dataPathDirIsEq( - bluetooth::hci::iso_manager::kIsoDataPathDirectionIn))) - .Times(1); - EXPECT_CALL( - *mock_iso_manager_, - SetupIsoDataPath( - _, dataPathDirIsEq( - bluetooth::hci::iso_manager::kIsoDataPathDirectionOut))) - .Times(1); - EXPECT_CALL( - *mock_iso_manager_, - RemoveIsoDataPath( - _, bluetooth::hci::iso_manager::kRemoveIsoDataPathDirectionOutput | - bluetooth::hci::iso_manager::kRemoveIsoDataPathDirectionInput)) - .Times(1); + _, dataPathDirIsEq(bluetooth::hci::iso_manager::kIsoDataPathDirectionIn))) + .Times(1); + EXPECT_CALL(*mock_iso_manager_, + SetupIsoDataPath( + _, dataPathDirIsEq(bluetooth::hci::iso_manager::kIsoDataPathDirectionOut))) + .Times(1); + EXPECT_CALL(*mock_iso_manager_, + RemoveIsoDataPath( + _, bluetooth::hci::iso_manager::kRemoveIsoDataPathDirectionOutput | + bluetooth::hci::iso_manager::kRemoveIsoDataPathDirectionInput)) + .Times(1); /* This check is the major one in this test, as we want to make sure, * it will not be called twice but only once (when both bidirectional ASEs are @@ -2873,10 +2640,10 @@ TEST_F(StateMachineTest, testFailedStreamMultipleConversational) { * Receiver ready * Release */ - EXPECT_CALL(gatt_queue, WriteCharacteristic(leAudioDevice->conn_id_, - leAudioDevice->ctp_hdls_.val_hdl, - _, GATT_WRITE_NO_RSP, _, _)) - .Times(5); + EXPECT_CALL(gatt_queue, + WriteCharacteristic(leAudioDevice->conn_id_, leAudioDevice->ctp_hdls_.val_hdl, _, + GATT_WRITE_NO_RSP, _, _)) + .Times(5); leAudioDevice = group->GetNextDevice(leAudioDevice); /* Second device Control Point actions @@ -2885,19 +2652,19 @@ TEST_F(StateMachineTest, testFailedStreamMultipleConversational) { * Enable (failed on CIS established - therefore no Receiver Ready) * Release */ - EXPECT_CALL(gatt_queue, WriteCharacteristic(leAudioDevice->conn_id_, - leAudioDevice->ctp_hdls_.val_hdl, - _, GATT_WRITE_NO_RSP, _, _)) - .Times(4); + EXPECT_CALL(gatt_queue, + WriteCharacteristic(leAudioDevice->conn_id_, leAudioDevice->ctp_hdls_.val_hdl, _, + GATT_WRITE_NO_RSP, _, _)) + .Times(4); /* Prepare DisconnectCis mock to not symulate CisDisconnection */ ON_CALL(*mock_iso_manager_, DisconnectCis).WillByDefault(Return()); // Start the configuration and stream Media content ASSERT_TRUE(LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)})); + group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)})); // Check if group has transitioned to a proper state ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_IDLE); @@ -2915,14 +2682,12 @@ TEST_F(StateMachineTest, testAttachToStreamWhileFirstDeviceIsStartingStream) { const auto num_devices = 2; // Prepare multiple fake connected devices in a group - auto* group = - PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); ASSERT_EQ(group->Size(), num_devices); PrepareConfigureCodecHandler(group); PrepareConfigureQosHandler(group); - PrepareEnableHandler(group, 0, true /* inject enabling */, - false /* inject streaming*/); + PrepareEnableHandler(group, 0, true /* inject enabling */, false /* inject streaming*/); PrepareReleaseHandler(group); InjectInitialIdleNotification(group); @@ -2934,9 +2699,9 @@ TEST_F(StateMachineTest, testAttachToStreamWhileFirstDeviceIsStartingStream) { // Start the configuration and stream Media content ASSERT_TRUE(LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)})); + group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)})); // Now, group is not yet in the streaming state. Let's simulated the other // device got connected @@ -2946,14 +2711,12 @@ TEST_F(StateMachineTest, testAttachToStreamWhileFirstDeviceIsStartingStream) { for (auto& ase : lastDevice->ases_) { std::vector params{}; if (ase.active) { - InjectAseStateNotification(&ase, lastDevice, group, - ascs::kAseStateStreaming, ¶ms); + InjectAseStateNotification(&ase, lastDevice, group, ascs::kAseStateStreaming, ¶ms); } } // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); } TEST_F(StateMachineTest, testFailedStreamCreation) { @@ -2963,14 +2726,12 @@ TEST_F(StateMachineTest, testFailedStreamCreation) { const auto num_devices = 2; // Prepare multiple fake connected devices in a group - auto* group = - PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); ASSERT_EQ(group->Size(), num_devices); PrepareConfigureCodecHandler(group); PrepareConfigureQosHandler(group); - PrepareEnableHandler(group, 0, true /* inject enabling */, - false /* inject streaming*/); + PrepareEnableHandler(group, 0, true /* inject enabling */, false /* inject streaming*/); PrepareReleaseHandler(group); EXPECT_CALL(*mock_iso_manager_, CreateCig(_, _)).Times(1); @@ -2993,10 +2754,10 @@ TEST_F(StateMachineTest, testFailedStreamCreation) { * Enable * Release */ - EXPECT_CALL(gatt_queue, WriteCharacteristic(leAudioDevice->conn_id_, - leAudioDevice->ctp_hdls_.val_hdl, - _, GATT_WRITE_NO_RSP, _, _)) - .Times(4); + EXPECT_CALL(gatt_queue, + WriteCharacteristic(leAudioDevice->conn_id_, leAudioDevice->ctp_hdls_.val_hdl, _, + GATT_WRITE_NO_RSP, _, _)) + .Times(4); leAudioDevice = group->GetNextDevice(leAudioDevice); /* Second device Control Point actions @@ -3005,22 +2766,21 @@ TEST_F(StateMachineTest, testFailedStreamCreation) { * Enable (failed on CIS established - therefore no Receiver Ready) * Release */ - EXPECT_CALL(gatt_queue, WriteCharacteristic(leAudioDevice->conn_id_, - leAudioDevice->ctp_hdls_.val_hdl, - _, GATT_WRITE_NO_RSP, _, _)) - .Times(4); + EXPECT_CALL(gatt_queue, + WriteCharacteristic(leAudioDevice->conn_id_, leAudioDevice->ctp_hdls_.val_hdl, _, + GATT_WRITE_NO_RSP, _, _)) + .Times(4); // Start the configuration and stream Media content ASSERT_TRUE(LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)})); + group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)})); bluetooth::hci::iso_manager::cis_establish_cmpl_evt evt; evt.status = HCI_ERR_LMP_RESPONSE_TIMEOUT; - LeAudioGroupStateMachine::Get()->ProcessHciNotifCisEstablished( - group, leAudioDevice, &evt); + LeAudioGroupStateMachine::Get()->ProcessHciNotifCisEstablished(group, leAudioDevice, &evt); // Check if group has transitioned to a proper state ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_IDLE); @@ -3038,16 +2798,14 @@ TEST_F(StateMachineTest, remoteRejectsEnable) { const auto num_devices = 2; // Prepare multiple fake connected devices in a group - auto* group = - PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); ASSERT_EQ(group->Size(), num_devices); PrepareConfigureCodecHandler(group); PrepareConfigureQosHandler(group); - PrepareCtpNotificationError( - group, client_parser::ascs::kCtpOpcodeEnable, - client_parser::ascs::kCtpResponseCodeUnspecifiedError, - client_parser::ascs::kCtpResponseNoReason); + PrepareCtpNotificationError(group, client_parser::ascs::kCtpOpcodeEnable, + client_parser::ascs::kCtpResponseCodeUnspecifiedError, + client_parser::ascs::kCtpResponseNoReason); PrepareReleaseHandler(group); EXPECT_CALL(*mock_iso_manager_, CreateCig(_, _)).Times(1); @@ -3067,10 +2825,10 @@ TEST_F(StateMachineTest, remoteRejectsEnable) { * Enable * Release */ - EXPECT_CALL(gatt_queue, WriteCharacteristic(leAudioDevice->conn_id_, - leAudioDevice->ctp_hdls_.val_hdl, - _, GATT_WRITE_NO_RSP, _, _)) - .Times(4); + EXPECT_CALL(gatt_queue, + WriteCharacteristic(leAudioDevice->conn_id_, leAudioDevice->ctp_hdls_.val_hdl, _, + GATT_WRITE_NO_RSP, _, _)) + .Times(4); leAudioDevice = group->GetNextDevice(leAudioDevice); /* Second device Control Point actions @@ -3078,16 +2836,16 @@ TEST_F(StateMachineTest, remoteRejectsEnable) { * QoS Config * Release */ - EXPECT_CALL(gatt_queue, WriteCharacteristic(leAudioDevice->conn_id_, - leAudioDevice->ctp_hdls_.val_hdl, - _, GATT_WRITE_NO_RSP, _, _)) - .Times(3); + EXPECT_CALL(gatt_queue, + WriteCharacteristic(leAudioDevice->conn_id_, leAudioDevice->ctp_hdls_.val_hdl, _, + GATT_WRITE_NO_RSP, _, _)) + .Times(3); // Start the configuration and stream Media content ASSERT_TRUE(LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)})); + group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)})); // Check if group has transitioned to a proper state ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_IDLE); @@ -3100,8 +2858,7 @@ TEST_F(StateMachineTest, testStreamMultiple) { const auto num_devices = 2; // Prepare multiple fake connected devices in a group - auto* group = - PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); ASSERT_EQ(group->Size(), num_devices); PrepareConfigureCodecHandler(group); @@ -3121,30 +2878,26 @@ TEST_F(StateMachineTest, testStreamMultiple) { auto expected_devices_written = 0; while (leAudioDevice) { EXPECT_CALL(gatt_queue, - WriteCharacteristic(leAudioDevice->conn_id_, - leAudioDevice->ctp_hdls_.val_hdl, _, + WriteCharacteristic(leAudioDevice->conn_id_, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) - .Times(AtLeast(3)); + .Times(AtLeast(3)); expected_devices_written++; leAudioDevice = group->GetNextDevice(leAudioDevice); } ASSERT_EQ(expected_devices_written, num_devices); // Validate GroupStreamStatus - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::STREAMING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::STREAMING)); // Start the configuration and stream Media content ASSERT_TRUE(LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)})); + group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)})); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); ASSERT_EQ(1, get_func_call_count("alarm_cancel")); } @@ -3153,12 +2906,11 @@ TEST_F(StateMachineTest, testUpdateMetadataMultiple) { const auto leaudio_group_id = 4; const auto num_devices = 2; - auto supported_contexts = - types::AudioContexts(kContextTypeMedia | kContextTypeSoundEffects); + auto supported_contexts = types::AudioContexts(kContextTypeMedia | kContextTypeSoundEffects); // Prepare multiple fake connected devices in a group - auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, - num_devices, supported_contexts); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices, + supported_contexts); ASSERT_EQ(group->Size(), num_devices); PrepareConfigureCodecHandler(group); @@ -3178,32 +2930,28 @@ TEST_F(StateMachineTest, testUpdateMetadataMultiple) { auto expected_devices_written = 0; while (leAudioDevice) { EXPECT_CALL(gatt_queue, - WriteCharacteristic(leAudioDevice->conn_id_, - leAudioDevice->ctp_hdls_.val_hdl, _, + WriteCharacteristic(leAudioDevice->conn_id_, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) - .Times(AtLeast(3)); + .Times(AtLeast(3)); expected_devices_written++; leAudioDevice = group->GetNextDevice(leAudioDevice); } ASSERT_EQ(expected_devices_written, num_devices); // Validate GroupStreamStatus - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::STREAMING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::STREAMING)); // Start the configuration and stream Media content ASSERT_TRUE(LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)})); + group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)})); testing::Mock::VerifyAndClearExpectations(&gatt_queue); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); ASSERT_EQ(1, get_func_call_count("alarm_cancel")); reset_mock_function_count_map(); @@ -3213,20 +2961,17 @@ TEST_F(StateMachineTest, testUpdateMetadataMultiple) { expected_devices_written = 0; while (leAudioDevice) { EXPECT_CALL(gatt_queue, - WriteCharacteristic(leAudioDevice->conn_id_, - leAudioDevice->ctp_hdls_.val_hdl, _, + WriteCharacteristic(leAudioDevice->conn_id_, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) - .Times(1); + .Times(1); expected_devices_written++; leAudioDevice = group->GetNextDevice(leAudioDevice); } ASSERT_EQ(expected_devices_written, num_devices); - const auto metadata_context_type = - kContextTypeMedia | kContextTypeSoundEffects; + const auto metadata_context_type = kContextTypeMedia | kContextTypeSoundEffects; ASSERT_TRUE(LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = metadata_context_type, .source = metadata_context_type})); + group, context_type, {.sink = metadata_context_type, .source = metadata_context_type})); /* This is just update metadata - watchdog is not used */ ASSERT_EQ(0, get_func_call_count("alarm_cancel")); @@ -3241,8 +2986,8 @@ TEST_F(StateMachineTest, testUpdateMetadataMultiple_NoUpdatesOnKeyTouch) { auto supported_contexts = types::AudioContexts(kContextTypeMedia); // Prepare multiple fake connected devices in a group - auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, - num_devices, supported_contexts); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices, + supported_contexts); ASSERT_EQ(group->Size(), num_devices); PrepareConfigureCodecHandler(group); @@ -3262,32 +3007,28 @@ TEST_F(StateMachineTest, testUpdateMetadataMultiple_NoUpdatesOnKeyTouch) { auto expected_devices_written = 0; while (leAudioDevice) { EXPECT_CALL(gatt_queue, - WriteCharacteristic(leAudioDevice->conn_id_, - leAudioDevice->ctp_hdls_.val_hdl, _, + WriteCharacteristic(leAudioDevice->conn_id_, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) - .Times(AtLeast(3)); + .Times(AtLeast(3)); expected_devices_written++; leAudioDevice = group->GetNextDevice(leAudioDevice); } ASSERT_EQ(expected_devices_written, num_devices); // Validate GroupStreamStatus - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::STREAMING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::STREAMING)); // Start the configuration and stream Media content ASSERT_TRUE(LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)})); + group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)})); testing::Mock::VerifyAndClearExpectations(&gatt_queue); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); ASSERT_EQ(1, get_func_call_count("alarm_cancel")); reset_mock_function_count_map(); @@ -3297,20 +3038,17 @@ TEST_F(StateMachineTest, testUpdateMetadataMultiple_NoUpdatesOnKeyTouch) { expected_devices_written = 0; while (leAudioDevice) { EXPECT_CALL(gatt_queue, - WriteCharacteristic(leAudioDevice->conn_id_, - leAudioDevice->ctp_hdls_.val_hdl, _, + WriteCharacteristic(leAudioDevice->conn_id_, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) - .Times(0); + .Times(0); expected_devices_written++; leAudioDevice = group->GetNextDevice(leAudioDevice); } ASSERT_EQ(expected_devices_written, num_devices); - const auto metadata_context_type = - kContextTypeMedia | kContextTypeSoundEffects; + const auto metadata_context_type = kContextTypeMedia | kContextTypeSoundEffects; ASSERT_TRUE(LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = metadata_context_type, .source = metadata_context_type})); + group, context_type, {.sink = metadata_context_type, .source = metadata_context_type})); /* This is just update metadata - watchdog is not used */ ASSERT_EQ(0, get_func_call_count("alarm_cancel")); @@ -3337,58 +3075,46 @@ TEST_F(StateMachineTest, testDisableSingle) { auto* leAudioDevice = group->GetFirstDevice(); EXPECT_CALL(gatt_queue, - WriteCharacteristic(1, leAudioDevice->ctp_hdls_.val_hdl, _, - GATT_WRITE_NO_RSP, _, _)) - .Times(4); + WriteCharacteristic(1, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) + .Times(4); EXPECT_CALL(*mock_iso_manager_, CreateCig(_, _)).Times(1); EXPECT_CALL(*mock_iso_manager_, EstablishCis(_)).Times(1); EXPECT_CALL(*mock_iso_manager_, SetupIsoDataPath(_, _)).Times(2); - EXPECT_CALL( - *mock_iso_manager_, - RemoveIsoDataPath( - _, bluetooth::hci::iso_manager::kRemoveIsoDataPathDirectionInput)) - .Times(2); + EXPECT_CALL(*mock_iso_manager_, + RemoveIsoDataPath(_, bluetooth::hci::iso_manager::kRemoveIsoDataPathDirectionInput)) + .Times(2); EXPECT_CALL(*mock_iso_manager_, DisconnectCis(_, _)).Times(2); EXPECT_CALL(*mock_iso_manager_, RemoveCig(_, _)).Times(0); InjectInitialIdleNotification(group); - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::STREAMING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::STREAMING)); // Start the configuration and stream Media content - LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)}); + LeAudioGroupStateMachine::Get()->StartStream(group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)}); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); testing::Mock::VerifyAndClearExpectations(&mock_callbacks_); ASSERT_EQ(1, get_func_call_count("alarm_cancel")); reset_mock_function_count_map(); // Validate GroupStreamStatus - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::SUSPENDING)); - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::SUSPENDED)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::SUSPENDING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::SUSPENDED)); // Suspend the stream LeAudioGroupStateMachine::Get()->SuspendStream(group); // Check if group has transition to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED); testing::Mock::VerifyAndClearExpectations(&mock_callbacks_); ASSERT_EQ(1, get_func_call_count("alarm_cancel")); @@ -3400,8 +3126,7 @@ TEST_F(StateMachineTest, testDisableMultiple) { const auto num_devices = 2; // Prepare multiple fake connected devices in a group - auto* group = - PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); ASSERT_EQ(group->Size(), num_devices); PrepareConfigureCodecHandler(group); @@ -3413,10 +3138,9 @@ TEST_F(StateMachineTest, testDisableMultiple) { auto expected_devices_written = 0; while (leAudioDevice) { EXPECT_CALL(gatt_queue, - WriteCharacteristic(leAudioDevice->conn_id_, - leAudioDevice->ctp_hdls_.val_hdl, _, + WriteCharacteristic(leAudioDevice->conn_id_, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) - .Times(AtLeast(4)); + .Times(AtLeast(4)); expected_devices_written++; leAudioDevice = group->GetNextDevice(leAudioDevice); } @@ -3425,44 +3149,35 @@ TEST_F(StateMachineTest, testDisableMultiple) { EXPECT_CALL(*mock_iso_manager_, CreateCig(_, _)).Times(1); EXPECT_CALL(*mock_iso_manager_, EstablishCis(_)).Times(1); EXPECT_CALL(*mock_iso_manager_, SetupIsoDataPath(_, _)).Times(2); - EXPECT_CALL( - *mock_iso_manager_, - RemoveIsoDataPath( - _, bluetooth::hci::iso_manager::kRemoveIsoDataPathDirectionInput)) - .Times(2); + EXPECT_CALL(*mock_iso_manager_, + RemoveIsoDataPath(_, bluetooth::hci::iso_manager::kRemoveIsoDataPathDirectionInput)) + .Times(2); EXPECT_CALL(*mock_iso_manager_, DisconnectCis(_, _)).Times(2); EXPECT_CALL(*mock_iso_manager_, RemoveCig(_, _)).Times(0); InjectInitialIdleNotification(group); // Start the configuration and stream Media content - LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)}); + LeAudioGroupStateMachine::Get()->StartStream(group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)}); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); ASSERT_EQ(1, get_func_call_count("alarm_cancel")); reset_mock_function_count_map(); // Validate GroupStreamStatus - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::SUSPENDING)); - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::SUSPENDED)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::SUSPENDING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::SUSPENDED)); // Suspend the stream LeAudioGroupStateMachine::Get()->SuspendStream(group); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED); testing::Mock::VerifyAndClearExpectations(&mock_callbacks_); ASSERT_EQ(1, get_func_call_count("alarm_cancel")); } @@ -3490,9 +3205,8 @@ TEST_F(StateMachineTest, testDisableBidirectional) { auto* leAudioDevice = group->GetFirstDevice(); EXPECT_CALL(gatt_queue, - WriteCharacteristic(1, leAudioDevice->ctp_hdls_.val_hdl, _, - GATT_WRITE_NO_RSP, _, _)) - .Times(AtLeast(4)); + WriteCharacteristic(1, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) + .Times(AtLeast(4)); EXPECT_CALL(*mock_iso_manager_, CreateCig(_, _)).Times(1); EXPECT_CALL(*mock_iso_manager_, EstablishCis(_)).Times(1); @@ -3502,73 +3216,63 @@ TEST_F(StateMachineTest, testDisableBidirectional) { /* Check data path removal */ ON_CALL(*mock_iso_manager_, RemoveIsoDataPath) - .WillByDefault(Invoke([&removed_bidirectional, &removed_unidirectional, - this](uint16_t conn_handle, - uint8_t data_path_dir) { - /* Set flags for verification */ - if (data_path_dir == - (bluetooth::hci::iso_manager::kRemoveIsoDataPathDirectionInput | - bluetooth::hci::iso_manager::kRemoveIsoDataPathDirectionOutput)) { - removed_bidirectional = true; - } else if (data_path_dir == bluetooth::hci::iso_manager:: - kRemoveIsoDataPathDirectionInput) { - removed_unidirectional = true; - } + .WillByDefault(Invoke([&removed_bidirectional, &removed_unidirectional, this]( + uint16_t conn_handle, uint8_t data_path_dir) { + /* Set flags for verification */ + if (data_path_dir == (bluetooth::hci::iso_manager::kRemoveIsoDataPathDirectionInput | + bluetooth::hci::iso_manager::kRemoveIsoDataPathDirectionOutput)) { + removed_bidirectional = true; + } else if (data_path_dir == + bluetooth::hci::iso_manager::kRemoveIsoDataPathDirectionInput) { + removed_unidirectional = true; + } - /* Copied from default handler of RemoveIsoDataPath*/ - auto dev_it = - std::find_if(le_audio_devices_.begin(), le_audio_devices_.end(), - [&conn_handle](auto& dev) { - auto ases = dev->GetAsesByCisConnHdl(conn_handle); - return (ases.sink || ases.source); - }); - if (dev_it == le_audio_devices_.end()) { - return; - } + /* Copied from default handler of RemoveIsoDataPath*/ + auto dev_it = std::find_if(le_audio_devices_.begin(), le_audio_devices_.end(), + [&conn_handle](auto& dev) { + auto ases = dev->GetAsesByCisConnHdl(conn_handle); + return ases.sink || ases.source; + }); + if (dev_it == le_audio_devices_.end()) { + return; + } - for (auto& kv_pair : le_audio_device_groups_) { - auto& group = kv_pair.second; - if (group->IsDeviceInTheGroup(dev_it->get())) { - LeAudioGroupStateMachine::Get()->ProcessHciNotifRemoveIsoDataPath( - group.get(), dev_it->get(), 0, conn_handle); - return; - } - } - /* End of copy */ - })); + for (auto& kv_pair : le_audio_device_groups_) { + auto& group = kv_pair.second; + if (group->IsDeviceInTheGroup(dev_it->get())) { + LeAudioGroupStateMachine::Get()->ProcessHciNotifRemoveIsoDataPath( + group.get(), dev_it->get(), 0, conn_handle); + return; + } + } + /* End of copy */ + })); EXPECT_CALL(*mock_iso_manager_, DisconnectCis(_, _)).Times(2); EXPECT_CALL(*mock_iso_manager_, RemoveCig(_, _)).Times(0); // Start the configuration and stream Media content - LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)}); + LeAudioGroupStateMachine::Get()->StartStream(group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)}); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); ASSERT_EQ(1, get_func_call_count("alarm_cancel")); reset_mock_function_count_map(); // Validate GroupStreamStatus - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::SUSPENDING)); - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::SUSPENDED)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::SUSPENDING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::SUSPENDED)); // Suspend the stream LeAudioGroupStateMachine::Get()->SuspendStream(group); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED); ASSERT_EQ(removed_bidirectional, true); ASSERT_EQ(removed_unidirectional, true); @@ -3582,8 +3286,7 @@ TEST_F(StateMachineTest, testReleaseSingle) { */ const auto context_type = kContextTypeRingtone; const int leaudio_group_id = 4; - channel_count_ = kLeAudioCodecChannelCountSingleChannel | - kLeAudioCodecChannelCountTwoChannel; + channel_count_ = kLeAudioCodecChannelCountSingleChannel | kLeAudioCodecChannelCountTwoChannel; // Prepare fake connected device group auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type); @@ -3599,9 +3302,8 @@ TEST_F(StateMachineTest, testReleaseSingle) { auto* leAudioDevice = group->GetFirstDevice(); EXPECT_CALL(gatt_queue, - WriteCharacteristic(1, leAudioDevice->ctp_hdls_.val_hdl, _, - GATT_WRITE_NO_RSP, _, _)) - .Times(4); + WriteCharacteristic(1, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) + .Times(4); EXPECT_CALL(*mock_iso_manager_, CreateCig(_, _)).Times(1); EXPECT_CALL(*mock_iso_manager_, EstablishCis(_)).Times(1); @@ -3613,24 +3315,19 @@ TEST_F(StateMachineTest, testReleaseSingle) { InjectInitialIdleNotification(group); // Start the configuration and stream Media content - LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)}); + LeAudioGroupStateMachine::Get()->StartStream(group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)}); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); ASSERT_EQ(1, get_func_call_count("alarm_cancel")); reset_mock_function_count_map(); // Validate GroupStreamStatus - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::RELEASING)); EXPECT_CALL(mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::IDLE)); + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::RELEASING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::IDLE)); // Stop the stream LeAudioGroupStateMachine::Get()->StopStream(group); @@ -3646,8 +3343,7 @@ TEST_F(StateMachineTest, testReleaseCachingSingle) { */ const auto context_type = kContextTypeRingtone; const int leaudio_group_id = 4; - channel_count_ = kLeAudioCodecChannelCountSingleChannel | - kLeAudioCodecChannelCountTwoChannel; + channel_count_ = kLeAudioCodecChannelCountSingleChannel | kLeAudioCodecChannelCountTwoChannel; // Prepare fake connected device group auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type); @@ -3663,9 +3359,8 @@ TEST_F(StateMachineTest, testReleaseCachingSingle) { auto* leAudioDevice = group->GetFirstDevice(); EXPECT_CALL(gatt_queue, - WriteCharacteristic(1, leAudioDevice->ctp_hdls_.val_hdl, _, - GATT_WRITE_NO_RSP, _, _)) - .Times(4); + WriteCharacteristic(1, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) + .Times(4); EXPECT_CALL(*mock_iso_manager_, CreateCig(_, _)).Times(1); EXPECT_CALL(*mock_iso_manager_, EstablishCis(_)).Times(1); @@ -3677,30 +3372,22 @@ TEST_F(StateMachineTest, testReleaseCachingSingle) { InjectInitialIdleNotification(group); // Validate GroupStreamStatus - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::RELEASING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::RELEASING)); - EXPECT_CALL( - mock_callbacks_, - StatusReportCb( - leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::CONFIGURED_AUTONOMOUS)); - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::STREAMING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, + bluetooth::le_audio::GroupStreamStatus::CONFIGURED_AUTONOMOUS)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::STREAMING)); // Start the configuration and stream Media content - LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)}); + LeAudioGroupStateMachine::Get()->StartStream(group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)}); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); ASSERT_EQ(1, get_func_call_count("alarm_cancel")); reset_mock_function_count_map(); @@ -3709,18 +3396,15 @@ TEST_F(StateMachineTest, testReleaseCachingSingle) { LeAudioGroupStateMachine::Get()->StopStream(group); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED); ASSERT_EQ(1, get_func_call_count("alarm_cancel")); } -TEST_F(StateMachineTest, - testStreamCaching_NoReconfigurationNeeded_SingleDevice) { +TEST_F(StateMachineTest, testStreamCaching_NoReconfigurationNeeded_SingleDevice) { const auto context_type = kContextTypeRingtone; const int leaudio_group_id = 4; - channel_count_ = kLeAudioCodecChannelCountSingleChannel | - kLeAudioCodecChannelCountTwoChannel; + channel_count_ = kLeAudioCodecChannelCountSingleChannel | kLeAudioCodecChannelCountTwoChannel; additional_snk_ases = 2; // Prepare fake connected device group @@ -3745,9 +3429,8 @@ TEST_F(StateMachineTest, */ auto* leAudioDevice = group->GetFirstDevice(); EXPECT_CALL(gatt_queue, - WriteCharacteristic(1, leAudioDevice->ctp_hdls_.val_hdl, _, - GATT_WRITE_NO_RSP, _, _)) - .Times(6); + WriteCharacteristic(1, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) + .Times(6); EXPECT_CALL(*mock_iso_manager_, CreateCig(_, _)).Times(2); EXPECT_CALL(*mock_iso_manager_, EstablishCis(_)).Times(2); @@ -3759,31 +3442,24 @@ TEST_F(StateMachineTest, InjectInitialIdleNotification(group); // Validate GroupStreamStatus - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::RELEASING)); - - EXPECT_CALL( - mock_callbacks_, - StatusReportCb( - leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::CONFIGURED_AUTONOMOUS)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::RELEASING)); EXPECT_CALL(mock_callbacks_, StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::STREAMING)) - .Times(2); + bluetooth::le_audio::GroupStreamStatus::CONFIGURED_AUTONOMOUS)); + + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::STREAMING)) + .Times(2); // Start the configuration and stream Ringtone content - LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)}); + LeAudioGroupStateMachine::Get()->StartStream(group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)}); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); ASSERT_EQ(1, get_func_call_count("alarm_cancel")); reset_mock_function_count_map(); @@ -3792,40 +3468,34 @@ TEST_F(StateMachineTest, LeAudioGroupStateMachine::Get()->StopStream(group); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED); ASSERT_EQ(1, get_func_call_count("alarm_cancel")); reset_mock_function_count_map(); // Start the configuration and stream Media content - LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)}); + LeAudioGroupStateMachine::Get()->StartStream(group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)}); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); ASSERT_EQ(1, get_func_call_count("alarm_cancel")); reset_mock_function_count_map(); } -TEST_F(StateMachineTest, - test_StreamCaching_ReconfigureForContextChange_SingleDevice) { +TEST_F(StateMachineTest, test_StreamCaching_ReconfigureForContextChange_SingleDevice) { auto context_type = kContextTypeConversational; const int leaudio_group_id = 4; - channel_count_ = kLeAudioCodecChannelCountSingleChannel | - kLeAudioCodecChannelCountTwoChannel; + channel_count_ = kLeAudioCodecChannelCountSingleChannel | kLeAudioCodecChannelCountTwoChannel; additional_snk_ases = 2; /* Prepare fake connected device group with update of Media and Conversational * contexts */ - auto* group = PrepareSingleTestDeviceGroup( - leaudio_group_id, context_type, 1, - kContextTypeConversational | kContextTypeMedia); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, 1, + kContextTypeConversational | kContextTypeMedia); /* Don't validate ASE here, as after reconfiguration different ASE number * will be used. @@ -3849,9 +3519,8 @@ TEST_F(StateMachineTest, */ auto* leAudioDevice = group->GetFirstDevice(); EXPECT_CALL(gatt_queue, - WriteCharacteristic(1, leAudioDevice->ctp_hdls_.val_hdl, _, - GATT_WRITE_NO_RSP, _, _)) - .Times(8); + WriteCharacteristic(1, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) + .Times(8); EXPECT_CALL(*mock_iso_manager_, CreateCig(_, _)).Times(2); EXPECT_CALL(*mock_iso_manager_, EstablishCis(_)).Times(2); @@ -3860,9 +3529,8 @@ TEST_F(StateMachineTest, * configuration (1 Sink)*/ EXPECT_CALL(*mock_iso_manager_, SetupIsoDataPath(_, _)).Times(3); - uint8_t value = - bluetooth::hci::iso_manager::kRemoveIsoDataPathDirectionOutput | - bluetooth::hci::iso_manager::kRemoveIsoDataPathDirectionInput; + uint8_t value = bluetooth::hci::iso_manager::kRemoveIsoDataPathDirectionOutput | + bluetooth::hci::iso_manager::kRemoveIsoDataPathDirectionInput; EXPECT_CALL(*mock_iso_manager_, RemoveIsoDataPath(_, value)).Times(1); EXPECT_CALL(*mock_iso_manager_, DisconnectCis(_, _)).Times(1); EXPECT_CALL(*mock_iso_manager_, RemoveCig(_, _)).Times(1); @@ -3870,31 +3538,24 @@ TEST_F(StateMachineTest, InjectInitialIdleNotification(group); // Validate GroupStreamStatus - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::RELEASING)); - - EXPECT_CALL( - mock_callbacks_, - StatusReportCb( - leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::CONFIGURED_AUTONOMOUS)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::RELEASING)); EXPECT_CALL(mock_callbacks_, StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::STREAMING)) - .Times(2); + bluetooth::le_audio::GroupStreamStatus::CONFIGURED_AUTONOMOUS)); + + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::STREAMING)) + .Times(2); // Start the configuration and stream Conversational content - LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)}); + LeAudioGroupStateMachine::Get()->StartStream(group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)}); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); ASSERT_EQ(1, get_func_call_count("alarm_cancel")); reset_mock_function_count_map(); @@ -3903,22 +3564,19 @@ TEST_F(StateMachineTest, LeAudioGroupStateMachine::Get()->StopStream(group); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED); ASSERT_EQ(1, get_func_call_count("alarm_cancel")); reset_mock_function_count_map(); // Start the configuration and stream Media content context_type = kContextTypeMedia; - LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)}); + LeAudioGroupStateMachine::Get()->StartStream(group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)}); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); ASSERT_EQ(1, get_func_call_count("alarm_cancel")); } @@ -3928,8 +3586,7 @@ TEST_F(StateMachineTest, testReleaseMultiple) { const auto num_devices = 2; // Prepare multiple fake connected devices in a group - auto* group = - PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); ASSERT_EQ(group->Size(), num_devices); PrepareConfigureCodecHandler(group); @@ -3942,10 +3599,9 @@ TEST_F(StateMachineTest, testReleaseMultiple) { auto expected_devices_written = 0; while (leAudioDevice) { EXPECT_CALL(gatt_queue, - WriteCharacteristic(leAudioDevice->conn_id_, - leAudioDevice->ctp_hdls_.val_hdl, _, + WriteCharacteristic(leAudioDevice->conn_id_, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) - .Times(AtLeast(4)); + .Times(AtLeast(4)); expected_devices_written++; leAudioDevice = group->GetNextDevice(leAudioDevice); } @@ -3961,35 +3617,28 @@ TEST_F(StateMachineTest, testReleaseMultiple) { InjectInitialIdleNotification(group); EXPECT_CALL(mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::STREAMING)) - .Times(1); + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::STREAMING)) + .Times(1); // Start the configuration and stream Media content - LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)}); + LeAudioGroupStateMachine::Get()->StartStream(group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)}); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); ASSERT_EQ(1, get_func_call_count("alarm_cancel")); reset_mock_function_count_map(); // Validate GroupStreamStatus - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::RELEASING)); EXPECT_CALL(mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::IDLE)); + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::RELEASING)); EXPECT_CALL(mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::STREAMING)) - .Times(0); + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::IDLE)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::STREAMING)) + .Times(0); // Stop the stream LeAudioGroupStateMachine::Get()->StopStream(group); @@ -4116,8 +3765,7 @@ TEST_F(StateMachineTest, testReleaseMultiple_DeviceDisconnectedDuringRelease) { const auto num_devices = 2; // Prepare multiple fake connected devices in a group - auto* group = - PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); ASSERT_EQ(group->Size(), num_devices); PrepareConfigureCodecHandler(group); @@ -4132,10 +3780,9 @@ TEST_F(StateMachineTest, testReleaseMultiple_DeviceDisconnectedDuringRelease) { auto expected_devices_written = 0; while (leAudioDevice) { EXPECT_CALL(gatt_queue, - WriteCharacteristic(leAudioDevice->conn_id_, - leAudioDevice->ctp_hdls_.val_hdl, _, + WriteCharacteristic(leAudioDevice->conn_id_, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) - .Times(AtLeast(4)); + .Times(AtLeast(4)); expected_devices_written++; leAudioDevice = group->GetNextDevice(leAudioDevice); } @@ -4150,19 +3797,16 @@ TEST_F(StateMachineTest, testReleaseMultiple_DeviceDisconnectedDuringRelease) { InjectInitialIdleNotification(group); EXPECT_CALL(mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::STREAMING)) - .Times(1); + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::STREAMING)) + .Times(1); // Start the configuration and stream Media content - LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)}); + LeAudioGroupStateMachine::Get()->StartStream(group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)}); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); ASSERT_EQ(1, get_func_call_count("alarm_cancel")); reset_mock_function_count_map(); @@ -4171,17 +3815,13 @@ TEST_F(StateMachineTest, testReleaseMultiple_DeviceDisconnectedDuringRelease) { EXPECT_CALL(*mock_iso_manager_, RemoveCig(_, _)).Times(1); // Validate GroupStreamStatus - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::RELEASING)); EXPECT_CALL(mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::IDLE)); + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::RELEASING)); EXPECT_CALL(mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::STREAMING)) - .Times(0); + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::IDLE)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::STREAMING)) + .Times(0); // Stop the stream LeAudioGroupStateMachine::Get()->StopStream(group); @@ -4216,9 +3856,8 @@ TEST_F(StateMachineTest, testReleaseBidirectional) { auto* leAudioDevice = group->GetFirstDevice(); EXPECT_CALL(gatt_queue, - WriteCharacteristic(1, leAudioDevice->ctp_hdls_.val_hdl, _, - GATT_WRITE_NO_RSP, _, _)) - .Times(AtLeast(4)); + WriteCharacteristic(1, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) + .Times(AtLeast(4)); EXPECT_CALL(*mock_iso_manager_, CreateCig(_, _)).Times(1); EXPECT_CALL(*mock_iso_manager_, EstablishCis(_)).Times(1); @@ -4230,14 +3869,12 @@ TEST_F(StateMachineTest, testReleaseBidirectional) { InjectInitialIdleNotification(group); // Start the configuration and stream Media content - LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)}); + LeAudioGroupStateMachine::Get()->StartStream(group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)}); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); ASSERT_EQ(1, get_func_call_count("alarm_cancel")); reset_mock_function_count_map(); @@ -4275,9 +3912,8 @@ TEST_F(StateMachineTest, testDisableAndReleaseBidirectional) { auto* leAudioDevice = group->GetFirstDevice(); EXPECT_CALL(gatt_queue, - WriteCharacteristic(1, leAudioDevice->ctp_hdls_.val_hdl, _, - GATT_WRITE_NO_RSP, _, _)) - .Times(AtLeast(4)); + WriteCharacteristic(1, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) + .Times(AtLeast(4)); EXPECT_CALL(*mock_iso_manager_, CreateCig(_, _)).Times(1); EXPECT_CALL(*mock_iso_manager_, EstablishCis(_)).Times(1); @@ -4287,10 +3923,9 @@ TEST_F(StateMachineTest, testDisableAndReleaseBidirectional) { EXPECT_CALL(*mock_iso_manager_, RemoveCig(_, _)).Times(1); // Start the configuration and stream Media content - LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)}); + LeAudioGroupStateMachine::Get()->StartStream(group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)}); // Suspend the stream LeAudioGroupStateMachine::Get()->SuspendStream(group); @@ -4308,8 +3943,7 @@ TEST_F(StateMachineTest, testAseIdAssignmentIdle) { const auto num_devices = 1; // Prepare multiple fake connected devices in a group - auto* group = - PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); ASSERT_EQ(group->Size(), num_devices); // Should not trigger any action on our side @@ -4325,8 +3959,7 @@ TEST_F(StateMachineTest, testAseIdAssignmentIdle) { device = group->GetNextDevice(device)) { for (auto& ase : device->ases_) { ASSERT_EQ(ase.id, bluetooth::le_audio::types::ase::kAseIdInvalid); - InjectAseStateNotification(&ase, device, group, ascs::kAseStateIdle, - nullptr); + InjectAseStateNotification(&ase, device, group, ascs::kAseStateIdle, nullptr); ASSERT_EQ(ase.id, ase_id_last_assigned); } } @@ -4338,8 +3971,7 @@ TEST_F(StateMachineTest, testAseIdAssignmentCodecConfigured) { const auto num_devices = 1; // Prepare multiple fake connected devices in a group - auto* group = - PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); ASSERT_EQ(group->Size(), num_devices); // Should not trigger any action on our side @@ -4354,12 +3986,10 @@ TEST_F(StateMachineTest, testAseIdAssignmentCodecConfigured) { for (auto* device = group->GetFirstDevice(); device != nullptr; device = group->GetNextDevice(device)) { for (auto& ase : device->ases_) { - client_parser::ascs::ase_codec_configured_state_params - codec_configured_state_params; + client_parser::ascs::ase_codec_configured_state_params codec_configured_state_params; ASSERT_EQ(ase.id, bluetooth::le_audio::types::ase::kAseIdInvalid); - InjectAseStateNotification(&ase, device, group, - ascs::kAseStateCodecConfigured, + InjectAseStateNotification(&ase, device, group, ascs::kAseStateCodecConfigured, &codec_configured_state_params); ASSERT_EQ(ase.id, ase_id_last_assigned); } @@ -4391,22 +4021,19 @@ TEST_F(StateMachineTest, testAseAutonomousRelease) { InjectInitialIdleNotification(group); // Validate initial GroupStreamStatus - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::STREAMING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::STREAMING)); // Start the configuration and stream Media content ASSERT_TRUE(LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)})); + group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)})); // Validate new GroupStreamStatus EXPECT_CALL(mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::IDLE)) - .Times(AtLeast(1)); + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::IDLE)) + .Times(AtLeast(1)); /* Single disconnect as it is bidirectional Cis*/ EXPECT_CALL(*mock_iso_manager_, DisconnectCis(_, _)).Times(2); @@ -4417,8 +4044,7 @@ TEST_F(StateMachineTest, testAseAutonomousRelease) { for (auto* device = group->GetFirstDevice(); device != nullptr; device = group->GetNextDevice(device)) { for (auto& ase : device->ases_) { - client_parser::ascs::ase_codec_configured_state_params - codec_configured_state_params; + client_parser::ascs::ase_codec_configured_state_params codec_configured_state_params; ASSERT_EQ(ase.state, types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); @@ -4447,8 +4073,7 @@ TEST_F(StateMachineTest, testAseAutonomousRelease2Devices) { const int num_of_devices = 2; // Prepare fake connected device group - auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, - num_of_devices); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_of_devices); /* Since we prepared device with Conversional context in mind, Sink and Source * ASEs should have been configured. @@ -4464,30 +4089,26 @@ TEST_F(StateMachineTest, testAseAutonomousRelease2Devices) { InjectInitialIdleNotification(group); // Validate initial GroupStreamStatus - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::STREAMING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::STREAMING)); // Start the configuration and stream Media content ASSERT_TRUE(LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)})); + group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)})); // Check streaming will continue EXPECT_CALL(mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::IDLE)) - .Times(0); + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::IDLE)) + .Times(0); /* Single disconnect as it is bidirectional Cis*/ EXPECT_CALL(*mock_iso_manager_, DisconnectCis(_, _)).Times(1); auto device = group->GetFirstDevice(); for (auto& ase : device->ases_) { - client_parser::ascs::ase_codec_configured_state_params - codec_configured_state_params; + client_parser::ascs::ase_codec_configured_state_params codec_configured_state_params; ASSERT_EQ(ase.state, types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); @@ -4510,8 +4131,7 @@ TEST_F(StateMachineTest, testHandlingAutonomousCodecConfigStateOnConnection) { const int num_of_devices = 2; // Prepare fake connected device group - auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, - num_of_devices); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_of_devices); auto* firstDevice = group->GetFirstDevice(); auto* secondDevice = group->GetNextDevice(firstDevice); @@ -4532,15 +4152,14 @@ TEST_F(StateMachineTest, testHandlingAutonomousCodecConfigStateOnConnection) { * 3. Enable * 4. Receiver Start Ready */ - EXPECT_CALL(gatt_queue, WriteCharacteristic(firstDevice->conn_id_, - firstDevice->ctp_hdls_.val_hdl, _, - GATT_WRITE_NO_RSP, _, _)) - .Times(4); - - EXPECT_CALL(gatt_queue, WriteCharacteristic(secondDevice->conn_id_, - secondDevice->ctp_hdls_.val_hdl, + EXPECT_CALL(gatt_queue, WriteCharacteristic(firstDevice->conn_id_, firstDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) - .Times(4); + .Times(4); + + EXPECT_CALL(gatt_queue, + WriteCharacteristic(secondDevice->conn_id_, secondDevice->ctp_hdls_.val_hdl, _, + GATT_WRITE_NO_RSP, _, _)) + .Times(4); InjectInitialIdleAndConfiguredNotification(group); // Call it second time to make sure we get into state that current_state_ is @@ -4551,16 +4170,14 @@ TEST_F(StateMachineTest, testHandlingAutonomousCodecConfigStateOnConnection) { ASSERT_FALSE(group->IsInTransition()); // Validate initial GroupStreamStatus - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::STREAMING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::STREAMING)); // Start the configuration and stream Media content ASSERT_TRUE(LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)})); + group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)})); testing::Mock::VerifyAndClearExpectations(&mock_callbacks_); } @@ -4576,8 +4193,7 @@ TEST_F(StateMachineTest, testHandlingInvalidRemoteAseStateHandling) { const int num_of_devices = 2; // Prepare fake connected device group - auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, - num_of_devices); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_of_devices); auto* firstDevice = group->GetFirstDevice(); auto* secondDevice = group->GetNextDevice(firstDevice); @@ -4598,15 +4214,14 @@ TEST_F(StateMachineTest, testHandlingInvalidRemoteAseStateHandling) { * 3. Enable * 4. Receiver Start Ready */ - EXPECT_CALL(gatt_queue, WriteCharacteristic(firstDevice->conn_id_, - firstDevice->ctp_hdls_.val_hdl, _, - GATT_WRITE_NO_RSP, _, _)) - .Times(4); - - EXPECT_CALL(gatt_queue, WriteCharacteristic(secondDevice->conn_id_, - secondDevice->ctp_hdls_.val_hdl, + EXPECT_CALL(gatt_queue, WriteCharacteristic(firstDevice->conn_id_, firstDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) - .Times(4); + .Times(4); + + EXPECT_CALL(gatt_queue, + WriteCharacteristic(secondDevice->conn_id_, secondDevice->ctp_hdls_.val_hdl, _, + GATT_WRITE_NO_RSP, _, _)) + .Times(4); /* Inject invalid states*/ InjectInitialInvalidNotification(group); @@ -4614,16 +4229,14 @@ TEST_F(StateMachineTest, testHandlingInvalidRemoteAseStateHandling) { ASSERT_FALSE(group->IsInTransition()); // Validate initial GroupStreamStatus - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::STREAMING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::STREAMING)); // Start the configuration and stream Media content ASSERT_TRUE(LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)})); + group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)})); testing::Mock::VerifyAndClearExpectations(&mock_callbacks_); } @@ -4634,8 +4247,7 @@ TEST_F(StateMachineTest, testHandlingCachedCodecConfig2Devices) { const int num_of_devices = 2; // Prepare fake connected device group - auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, - num_of_devices); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_of_devices); auto* firstDevice = group->GetFirstDevice(); auto* secondDevice = group->GetNextDevice(firstDevice); @@ -4659,29 +4271,26 @@ TEST_F(StateMachineTest, testHandlingCachedCodecConfig2Devices) { * 3. Enable * 4. Receiver Start Ready * 5. Release*/ - EXPECT_CALL(gatt_queue, WriteCharacteristic(firstDevice->conn_id_, - firstDevice->ctp_hdls_.val_hdl, _, - GATT_WRITE_NO_RSP, _, _)) - .Times(5); - - EXPECT_CALL(gatt_queue, WriteCharacteristic(secondDevice->conn_id_, - secondDevice->ctp_hdls_.val_hdl, + EXPECT_CALL(gatt_queue, WriteCharacteristic(firstDevice->conn_id_, firstDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) - .Times(5); + .Times(5); + + EXPECT_CALL(gatt_queue, + WriteCharacteristic(secondDevice->conn_id_, secondDevice->ctp_hdls_.val_hdl, _, + GATT_WRITE_NO_RSP, _, _)) + .Times(5); InjectInitialIdleNotification(group); // Validate initial GroupStreamStatus - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::STREAMING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::STREAMING)); // Start the configuration and stream Media content ASSERT_TRUE(LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)})); + group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)})); testing::Mock::VerifyAndClearExpectations(&mock_callbacks_); @@ -4689,16 +4298,13 @@ TEST_F(StateMachineTest, testHandlingCachedCodecConfig2Devices) { EXPECT_CALL(*mock_iso_manager_, DisconnectCis(_, _)).Times(2); // Validate initial GroupStreamStatus + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::RELEASING)) + .Times(1); EXPECT_CALL(mock_callbacks_, StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::RELEASING)) - .Times(1); - EXPECT_CALL( - mock_callbacks_, - StatusReportCb( - leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::CONFIGURED_AUTONOMOUS)) - .Times(0); + bluetooth::le_audio::GroupStreamStatus::CONFIGURED_AUTONOMOUS)) + .Times(0); // Stop the stream LeAudioGroupStateMachine::Get()->StopStream(group); @@ -4708,27 +4314,23 @@ TEST_F(StateMachineTest, testHandlingCachedCodecConfig2Devices) { bluetooth::common::ToString(ase.state)); ASSERT_EQ(ase.state, types::AseState::BTA_LE_AUDIO_ASE_STATE_RELEASING); // Simulate autonomus configured state. - InjectAseStateNotification(&ase, firstDevice, group, - ascs::kAseStateCodecConfigured, + InjectAseStateNotification(&ase, firstDevice, group, ascs::kAseStateCodecConfigured, &cached_codec_configuration_map_[ase.id]); } testing::Mock::VerifyAndClearExpectations(&mock_callbacks_); /* When ALL devices got inactive, we should got the proper group status */ - EXPECT_CALL( - mock_callbacks_, - StatusReportCb( - leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::CONFIGURED_AUTONOMOUS)) - .Times(1); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, + bluetooth::le_audio::GroupStreamStatus::CONFIGURED_AUTONOMOUS)) + .Times(1); for (auto& ase : secondDevice->ases_) { log::debug("{} , {}, {}", firstDevice->address_, ase.id, bluetooth::common::ToString(ase.state)); ASSERT_EQ(ase.state, types::AseState::BTA_LE_AUDIO_ASE_STATE_RELEASING); // Simulate autonomus configured state. - InjectAseStateNotification(&ase, secondDevice, group, - ascs::kAseStateCodecConfigured, + InjectAseStateNotification(&ase, secondDevice, group, ascs::kAseStateCodecConfigured, &cached_codec_configuration_map_[ase.id]); } @@ -4738,29 +4340,26 @@ TEST_F(StateMachineTest, testHandlingCachedCodecConfig2Devices) { TEST_F(StateMachineTest, testStateTransitionTimeoutOnIdleState) { const auto context_type = kContextTypeRingtone; const int leaudio_group_id = 4; - channel_count_ = kLeAudioCodecChannelCountSingleChannel | - kLeAudioCodecChannelCountTwoChannel; + channel_count_ = kLeAudioCodecChannelCountSingleChannel | kLeAudioCodecChannelCountTwoChannel; // Prepare fake connected device group auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type); auto* leAudioDevice = group->GetFirstDevice(); EXPECT_CALL(gatt_queue, - WriteCharacteristic(1, leAudioDevice->ctp_hdls_.val_hdl, _, - GATT_WRITE_NO_RSP, _, _)) - .Times(1); + WriteCharacteristic(1, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) + .Times(1); // Start the configuration and stream Media content ASSERT_TRUE(LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)})); + group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)})); // Disconnect device // in client.cc before this function is called, state of device is changed. leAudioDevice->SetConnectionState(DeviceConnectState::DISCONNECTED); - LeAudioGroupStateMachine::Get()->ProcessHciNotifAclDisconnected( - group, leAudioDevice); + LeAudioGroupStateMachine::Get()->ProcessHciNotifAclDisconnected(group, leAudioDevice); // Make sure timeout is cleared ASSERT_TRUE(fake_osi_alarm_set_on_mloop_.cb == nullptr); @@ -4775,8 +4374,7 @@ TEST_F(StateMachineTest, testStateIdleNotifyAclDisconnectedRemoveCig) { group->cig.SetState(types::CigState::CREATED); // Assert current state - ASSERT_TRUE(group->GetState() == - types::AseState::BTA_LE_AUDIO_ASE_STATE_IDLE); + ASSERT_TRUE(group->GetState() == types::AseState::BTA_LE_AUDIO_ASE_STATE_IDLE); ASSERT_FALSE(group->IsInTransition()); ASSERT_TRUE(group->cig.GetState() == types::CigState::CREATED); @@ -4785,8 +4383,7 @@ TEST_F(StateMachineTest, testStateIdleNotifyAclDisconnectedRemoveCig) { // Disconnect device auto* leAudioDevice = group->GetFirstDevice(); - LeAudioGroupStateMachine::Get()->ProcessHciNotifAclDisconnected( - group, leAudioDevice); + LeAudioGroupStateMachine::Get()->ProcessHciNotifAclDisconnected(group, leAudioDevice); // Assert Cig state transition to NONE after REMOVING ASSERT_TRUE(group->cig.GetState() == types::CigState::NONE); @@ -4795,8 +4392,7 @@ TEST_F(StateMachineTest, testStateIdleNotifyAclDisconnectedRemoveCig) { TEST_F(StateMachineTest, testStateTransitionTimeout) { const auto context_type = kContextTypeRingtone; const int leaudio_group_id = 4; - channel_count_ = kLeAudioCodecChannelCountSingleChannel | - kLeAudioCodecChannelCountTwoChannel; + channel_count_ = kLeAudioCodecChannelCountSingleChannel | kLeAudioCodecChannelCountTwoChannel; // Prepare fake connected device group auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type); @@ -4809,15 +4405,14 @@ TEST_F(StateMachineTest, testStateTransitionTimeout) { auto* leAudioDevice = group->GetFirstDevice(); EXPECT_CALL(gatt_queue, - WriteCharacteristic(1, leAudioDevice->ctp_hdls_.val_hdl, _, - GATT_WRITE_NO_RSP, _, _)) - .Times(3); + WriteCharacteristic(1, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) + .Times(3); // Start the configuration and stream Media content ASSERT_TRUE(LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)})); + group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)})); // Check if timeout is fired EXPECT_CALL(mock_callbacks_, OnStateTransitionTimeout(leaudio_group_id)); @@ -4827,21 +4422,18 @@ TEST_F(StateMachineTest, testStateTransitionTimeout) { ASSERT_EQ(1, get_func_call_count("alarm_set_on_mloop")); } -TEST_F(StateMachineTest, - testStateTransitionTimeoutAndDisconnectWhenConfigured) { +TEST_F(StateMachineTest, testStateTransitionTimeoutAndDisconnectWhenConfigured) { const auto context_type = kContextTypeMedia; const int leaudio_group_id = 4; - channel_count_ = kLeAudioCodecChannelCountSingleChannel | - kLeAudioCodecChannelCountTwoChannel; + channel_count_ = kLeAudioCodecChannelCountSingleChannel | kLeAudioCodecChannelCountTwoChannel; // Prepare fake connected device group auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type); auto* leAudioDevice = group->GetFirstDevice(); EXPECT_CALL(gatt_queue, - WriteCharacteristic(1, leAudioDevice->ctp_hdls_.val_hdl, _, - GATT_WRITE_NO_RSP, _, _)) - .Times(1); + WriteCharacteristic(1, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) + .Times(1); InjectInitialConfiguredNotification(group); @@ -4849,9 +4441,9 @@ TEST_F(StateMachineTest, // Start the configuration and stream Media content ASSERT_TRUE(LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)})); + group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)})); group->PrintDebugState(); @@ -4880,12 +4472,10 @@ TEST_F(StateMachineTest, } } -TEST_F(StateMachineTest, - testStateTransitionTimeoutAndDisconnectWhenQoSConfigured) { +TEST_F(StateMachineTest, testStateTransitionTimeoutAndDisconnectWhenQoSConfigured) { const auto context_type = kContextTypeMedia; const int leaudio_group_id = 4; - channel_count_ = kLeAudioCodecChannelCountSingleChannel | - kLeAudioCodecChannelCountTwoChannel; + channel_count_ = kLeAudioCodecChannelCountSingleChannel | kLeAudioCodecChannelCountTwoChannel; // Prepare fake connected device group auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type); @@ -4893,9 +4483,8 @@ TEST_F(StateMachineTest, auto* leAudioDevice = group->GetFirstDevice(); EXPECT_CALL(gatt_queue, - WriteCharacteristic(1, leAudioDevice->ctp_hdls_.val_hdl, _, - GATT_WRITE_NO_RSP, _, _)) - .Times(2); + WriteCharacteristic(1, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) + .Times(2); InjectInitialConfiguredNotification(group); @@ -4903,9 +4492,9 @@ TEST_F(StateMachineTest, // Start the configuration and stream Media content ASSERT_TRUE(LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)})); + group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)})); group->PrintDebugState(); @@ -4937,8 +4526,7 @@ TEST_F(StateMachineTest, TEST_F(StateMachineTest, testStateTransitionTimeoutAndDisconnectWhenEnabling) { const auto context_type = kContextTypeMedia; const int leaudio_group_id = 4; - channel_count_ = kLeAudioCodecChannelCountSingleChannel | - kLeAudioCodecChannelCountTwoChannel; + channel_count_ = kLeAudioCodecChannelCountSingleChannel | kLeAudioCodecChannelCountTwoChannel; // Prepare fake connected device group auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type); @@ -4947,9 +4535,8 @@ TEST_F(StateMachineTest, testStateTransitionTimeoutAndDisconnectWhenEnabling) { auto* leAudioDevice = group->GetFirstDevice(); EXPECT_CALL(gatt_queue, - WriteCharacteristic(1, leAudioDevice->ctp_hdls_.val_hdl, _, - GATT_WRITE_NO_RSP, _, _)) - .Times(3); + WriteCharacteristic(1, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) + .Times(3); InjectInitialConfiguredNotification(group); @@ -4957,9 +4544,9 @@ TEST_F(StateMachineTest, testStateTransitionTimeoutAndDisconnectWhenEnabling) { // Start the configuration and stream Media content ASSERT_TRUE(LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)})); + group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)})); group->PrintDebugState(); @@ -4988,13 +4575,12 @@ TEST_F(StateMachineTest, testStateTransitionTimeoutAndDisconnectWhenEnabling) { } } -MATCHER_P(dataPathIsEq, expected, "") { return (arg.data_path_id == expected); } +MATCHER_P(dataPathIsEq, expected, "") { return arg.data_path_id == expected; } TEST_F(StateMachineTest, testConfigureDataPathForHost) { const auto context_type = kContextTypeRingtone; const int leaudio_group_id = 4; - channel_count_ = kLeAudioCodecChannelCountSingleChannel | - kLeAudioCodecChannelCountTwoChannel; + channel_count_ = kLeAudioCodecChannelCountSingleChannel | kLeAudioCodecChannelCountTwoChannel; /* Can be called for every context when fetching the configuration */ @@ -5010,26 +4596,23 @@ TEST_F(StateMachineTest, testConfigureDataPathForHost) { PrepareConfigureQosHandler(group, 1); PrepareEnableHandler(group, 1); - EXPECT_CALL( - *mock_iso_manager_, - SetupIsoDataPath( - _, dataPathIsEq(bluetooth::hci::iso_manager::kIsoDataPathHci))) - .Times(1); + EXPECT_CALL(*mock_iso_manager_, + SetupIsoDataPath(_, dataPathIsEq(bluetooth::hci::iso_manager::kIsoDataPathHci))) + .Times(1); InjectInitialIdleNotification(group); // Start the configuration and stream Media content ASSERT_TRUE(LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)})); + group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)})); } TEST_F(StateMachineTestAdsp, testConfigureDataPathForAdsp) { const auto context_type = kContextTypeRingtone; const int leaudio_group_id = 4; - channel_count_ = kLeAudioCodecChannelCountSingleChannel | - kLeAudioCodecChannelCountTwoChannel; + channel_count_ = kLeAudioCodecChannelCountSingleChannel | kLeAudioCodecChannelCountTwoChannel; /* Can be called for every context when fetching the configuration */ @@ -5045,20 +4628,18 @@ TEST_F(StateMachineTestAdsp, testConfigureDataPathForAdsp) { PrepareConfigureQosHandler(group, 1); PrepareEnableHandler(group, 1); - EXPECT_CALL( - *mock_iso_manager_, - SetupIsoDataPath( - _, dataPathIsEq( - bluetooth::hci::iso_manager::kIsoDataPathPlatformDefault))) - .Times(1); + EXPECT_CALL(*mock_iso_manager_, + SetupIsoDataPath( + _, dataPathIsEq(bluetooth::hci::iso_manager::kIsoDataPathPlatformDefault))) + .Times(1); InjectInitialIdleNotification(group); // Start the configuration and stream Media content ASSERT_TRUE(LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)})); + group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)})); } TEST_F(StateMachineTestAdsp, testStreamConfigurationAdspDownMix) { @@ -5067,20 +4648,17 @@ TEST_F(StateMachineTestAdsp, testStreamConfigurationAdspDownMix) { const int num_devices = 2; // Prepare fake connected device group - auto* group = PrepareSingleTestDeviceGroup( - leaudio_group_id, context_type, num_devices, - types::AudioContexts(kContextTypeConversational)); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices, + types::AudioContexts(kContextTypeConversational)); - EXPECT_CALL( - mock_callbacks_, - OnUpdatedCisConfiguration( - group->group_id_, bluetooth::le_audio::types::kLeAudioDirectionSink)) - .Times(1); EXPECT_CALL(mock_callbacks_, - OnUpdatedCisConfiguration( - group->group_id_, - bluetooth::le_audio::types::kLeAudioDirectionSource)) - .Times(1); + OnUpdatedCisConfiguration(group->group_id_, + bluetooth::le_audio::types::kLeAudioDirectionSink)) + .Times(1); + EXPECT_CALL(mock_callbacks_, + OnUpdatedCisConfiguration(group->group_id_, + bluetooth::le_audio::types::kLeAudioDirectionSource)) + .Times(1); /* Can be called for every context when fetching the configuration */ @@ -5098,13 +4676,12 @@ TEST_F(StateMachineTestAdsp, testStreamConfigurationAdspDownMix) { // Start the configuration and stream Media content ASSERT_TRUE(LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)})); + group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)})); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); // Note: The actual channel mixing is verified by the CodecManager unit tests. } @@ -5117,8 +4694,7 @@ TEST_F(StateMachineTest, testAttachDeviceToTheStream) { ContentControlIdKeeper::GetInstance()->SetCcid(media_context, media_ccid); // Prepare multiple fake connected devices in a group - auto* group = - PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); ASSERT_EQ(group->Size(), num_devices); PrepareConfigureCodecHandler(group); @@ -5140,10 +4716,9 @@ TEST_F(StateMachineTest, testAttachDeviceToTheStream) { */ lastDevice = leAudioDevice; EXPECT_CALL(gatt_queue, - WriteCharacteristic(leAudioDevice->conn_id_, - leAudioDevice->ctp_hdls_.val_hdl, _, + WriteCharacteristic(leAudioDevice->conn_id_, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) - .Times(AtLeast(3)); + .Times(AtLeast(3)); expected_devices_written++; leAudioDevice = group->GetNextDevice(leAudioDevice); } @@ -5156,14 +4731,12 @@ TEST_F(StateMachineTest, testAttachDeviceToTheStream) { InjectInitialIdleNotification(group); // Start the configuration and stream Media content - LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)}); + LeAudioGroupStateMachine::Get()->StartStream(group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)}); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); testing::Mock::VerifyAndClearExpectations(mock_iso_manager_); // Inject CIS and ACL disconnection of first device @@ -5171,45 +4744,39 @@ TEST_F(StateMachineTest, testAttachDeviceToTheStream) { InjectAclDisconnected(group, lastDevice); // Check if group keeps streaming - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); lastDevice->conn_id_ = 3; lastDevice->SetConnectionState(DeviceConnectState::CONNECTED); // Make sure ASE with disconnected CIS are not left in STREAMING - ASSERT_EQ(lastDevice->GetFirstAseWithState( - ::bluetooth::le_audio::types::kLeAudioDirectionSink, - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING), + ASSERT_EQ(lastDevice->GetFirstAseWithState(::bluetooth::le_audio::types::kLeAudioDirectionSink, + types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING), nullptr); - ASSERT_EQ(lastDevice->GetFirstAseWithState( - ::bluetooth::le_audio::types::kLeAudioDirectionSource, - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING), + ASSERT_EQ(lastDevice->GetFirstAseWithState(::bluetooth::le_audio::types::kLeAudioDirectionSource, + types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING), nullptr); - EXPECT_CALL(gatt_queue, WriteCharacteristic(lastDevice->conn_id_, - lastDevice->ctp_hdls_.val_hdl, _, - GATT_WRITE_NO_RSP, _, _)) - .Times(AtLeast(3)); + EXPECT_CALL(gatt_queue, WriteCharacteristic(lastDevice->conn_id_, lastDevice->ctp_hdls_.val_hdl, + _, GATT_WRITE_NO_RSP, _, _)) + .Times(AtLeast(3)); EXPECT_CALL(*mock_iso_manager_, EstablishCis(_)).Times(1); EXPECT_CALL(*mock_iso_manager_, SetupIsoDataPath(_, _)).Times(1); - LeAudioGroupStateMachine::Get()->AttachToStream( - group, lastDevice, {.sink = {media_ccid}, .source = {}}); + LeAudioGroupStateMachine::Get()->AttachToStream(group, lastDevice, + {.sink = {media_ccid}, .source = {}}); // Check if group keeps streaming - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); // Verify that the joining device receives the right CCID list auto lastMeta = lastDevice->GetFirstActiveAse()->metadata; bool parsedOk = false; - auto ltv = bluetooth::le_audio::types::LeAudioLtvMap::Parse( - lastMeta.data(), lastMeta.size(), parsedOk); + auto ltv = bluetooth::le_audio::types::LeAudioLtvMap::Parse(lastMeta.data(), lastMeta.size(), + parsedOk); ASSERT_TRUE(parsedOk); - auto ccids = - ltv.Find(bluetooth::le_audio::types::kLeAudioMetadataTypeCcidList); + auto ccids = ltv.Find(bluetooth::le_audio::types::kLeAudioMetadataTypeCcidList); ASSERT_TRUE(ccids.has_value()); ASSERT_NE(std::find(ccids->begin(), ccids->end(), media_ccid), ccids->end()); @@ -5233,8 +4800,7 @@ TEST_F(StateMachineTest, testAttachDeviceToTheStreamV2) { ContentControlIdKeeper::GetInstance()->SetCcid(media_context, media_ccid); // Prepare multiple fake connected devices in a group - auto* group = - PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); ASSERT_EQ(group->Size(), num_devices); PrepareConfigureCodecHandler(group); @@ -5256,10 +4822,9 @@ TEST_F(StateMachineTest, testAttachDeviceToTheStreamV2) { */ lastDevice = leAudioDevice; EXPECT_CALL(gatt_queue, - WriteCharacteristic(leAudioDevice->conn_id_, - leAudioDevice->ctp_hdls_.val_hdl, _, + WriteCharacteristic(leAudioDevice->conn_id_, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) - .Times(AtLeast(3)); + .Times(AtLeast(3)); expected_devices_written++; leAudioDevice = group->GetNextDevice(leAudioDevice); } @@ -5272,14 +4837,12 @@ TEST_F(StateMachineTest, testAttachDeviceToTheStreamV2) { InjectInitialIdleNotification(group); // Start the configuration and stream Media content - LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)}); + LeAudioGroupStateMachine::Get()->StartStream(group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)}); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); testing::Mock::VerifyAndClearExpectations(mock_iso_manager_); // Inject CIS and ACL disconnection of first device @@ -5293,45 +4856,39 @@ TEST_F(StateMachineTest, testAttachDeviceToTheStreamV2) { group->UpdateAudioSetConfigurationCache(context_type); // Check if group keeps streaming - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); lastDevice->conn_id_ = 3; lastDevice->SetConnectionState(DeviceConnectState::CONNECTED); // Make sure ASE with disconnected CIS are not left in STREAMING - ASSERT_EQ(lastDevice->GetFirstAseWithState( - ::bluetooth::le_audio::types::kLeAudioDirectionSink, - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING), + ASSERT_EQ(lastDevice->GetFirstAseWithState(::bluetooth::le_audio::types::kLeAudioDirectionSink, + types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING), nullptr); - ASSERT_EQ(lastDevice->GetFirstAseWithState( - ::bluetooth::le_audio::types::kLeAudioDirectionSource, - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING), + ASSERT_EQ(lastDevice->GetFirstAseWithState(::bluetooth::le_audio::types::kLeAudioDirectionSource, + types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING), nullptr); - EXPECT_CALL(gatt_queue, WriteCharacteristic(lastDevice->conn_id_, - lastDevice->ctp_hdls_.val_hdl, _, - GATT_WRITE_NO_RSP, _, _)) - .Times(AtLeast(3)); + EXPECT_CALL(gatt_queue, WriteCharacteristic(lastDevice->conn_id_, lastDevice->ctp_hdls_.val_hdl, + _, GATT_WRITE_NO_RSP, _, _)) + .Times(AtLeast(3)); EXPECT_CALL(*mock_iso_manager_, EstablishCis(_)).Times(1); EXPECT_CALL(*mock_iso_manager_, SetupIsoDataPath(_, _)).Times(1); - LeAudioGroupStateMachine::Get()->AttachToStream( - group, lastDevice, {.sink = {media_ccid}, .source = {}}); + LeAudioGroupStateMachine::Get()->AttachToStream(group, lastDevice, + {.sink = {media_ccid}, .source = {}}); // Check if group keeps streaming - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); // Verify that the joining device receives the right CCID list auto lastMeta = lastDevice->GetFirstActiveAse()->metadata; bool parsedOk = false; - auto ltv = bluetooth::le_audio::types::LeAudioLtvMap::Parse( - lastMeta.data(), lastMeta.size(), parsedOk); + auto ltv = bluetooth::le_audio::types::LeAudioLtvMap::Parse(lastMeta.data(), lastMeta.size(), + parsedOk); ASSERT_TRUE(parsedOk); - auto ccids = - ltv.Find(bluetooth::le_audio::types::kLeAudioMetadataTypeCcidList); + auto ccids = ltv.Find(bluetooth::le_audio::types::kLeAudioMetadataTypeCcidList); ASSERT_TRUE(ccids.has_value()); ASSERT_NE(std::find(ccids->begin(), ccids->end(), media_ccid), ccids->end()); @@ -5349,8 +4906,7 @@ TEST_F(StateMachineTest, testAttachDeviceToTheStreamDeviceNoAvailableContext) { ContentControlIdKeeper::GetInstance()->SetCcid(media_context, media_ccid); // Prepare multiple fake connected devices in a group - auto* group = - PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); ASSERT_EQ(group->Size(), num_devices); PrepareConfigureCodecHandler(group); @@ -5371,10 +4927,9 @@ TEST_F(StateMachineTest, testAttachDeviceToTheStreamDeviceNoAvailableContext) { */ lastDevice = leAudioDevice; EXPECT_CALL(gatt_queue, - WriteCharacteristic(leAudioDevice->conn_id_, - leAudioDevice->ctp_hdls_.val_hdl, _, + WriteCharacteristic(leAudioDevice->conn_id_, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) - .Times(AtLeast(3)); + .Times(AtLeast(3)); expected_devices_written++; leAudioDevice = group->GetNextDevice(leAudioDevice); } @@ -5387,14 +4942,12 @@ TEST_F(StateMachineTest, testAttachDeviceToTheStreamDeviceNoAvailableContext) { InjectInitialIdleNotification(group); // Start the configuration and stream Media content - LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)}); + LeAudioGroupStateMachine::Get()->StartStream(group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)}); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); testing::Mock::VerifyAndClearExpectations(mock_iso_manager_); // Inject CIS and ACL disconnection of first device @@ -5402,40 +4955,34 @@ TEST_F(StateMachineTest, testAttachDeviceToTheStreamDeviceNoAvailableContext) { InjectAclDisconnected(group, lastDevice); // Check if group keeps streaming - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); // Connect the disconnected device BUT remove MEDIA from available Contex // Types lastDevice->conn_id_ = 3; auto test_context_type = kContextTypeUnspecified | kContextTypeConversational; - lastDevice->SetAvailableContexts( - {.sink = test_context_type, .source = test_context_type}); + lastDevice->SetAvailableContexts({.sink = test_context_type, .source = test_context_type}); lastDevice->SetConnectionState(DeviceConnectState::CONNECTED); // Make sure ASE with disconnected CIS are not left in STREAMING - ASSERT_EQ(lastDevice->GetFirstAseWithState( - ::bluetooth::le_audio::types::kLeAudioDirectionSink, - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING), + ASSERT_EQ(lastDevice->GetFirstAseWithState(::bluetooth::le_audio::types::kLeAudioDirectionSink, + types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING), nullptr); - ASSERT_EQ(lastDevice->GetFirstAseWithState( - ::bluetooth::le_audio::types::kLeAudioDirectionSource, - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING), + ASSERT_EQ(lastDevice->GetFirstAseWithState(::bluetooth::le_audio::types::kLeAudioDirectionSource, + types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING), nullptr); - EXPECT_CALL(gatt_queue, WriteCharacteristic(lastDevice->conn_id_, - lastDevice->ctp_hdls_.val_hdl, _, - GATT_WRITE_NO_RSP, _, _)) - .Times(AtLeast(0)); + EXPECT_CALL(gatt_queue, WriteCharacteristic(lastDevice->conn_id_, lastDevice->ctp_hdls_.val_hdl, + _, GATT_WRITE_NO_RSP, _, _)) + .Times(AtLeast(0)); EXPECT_CALL(*mock_iso_manager_, EstablishCis(_)).Times(0); EXPECT_CALL(*mock_iso_manager_, SetupIsoDataPath(_, _)).Times(0); - ASSERT_EQ(LeAudioGroupStateMachine::Get()->AttachToStream( - group, lastDevice, {.sink = {media_ccid}, .source = {}}), + ASSERT_EQ(LeAudioGroupStateMachine::Get()->AttachToStream(group, lastDevice, + {.sink = {media_ccid}, .source = {}}), false); - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); } TEST_F(StateMachineTest, testQoSConfigureWhileStreaming) { @@ -5444,8 +4991,7 @@ TEST_F(StateMachineTest, testQoSConfigureWhileStreaming) { */ const auto context_type = kContextTypeRingtone; const int leaudio_group_id = 4; - channel_count_ = kLeAudioCodecChannelCountSingleChannel | - kLeAudioCodecChannelCountTwoChannel; + channel_count_ = kLeAudioCodecChannelCountSingleChannel | kLeAudioCodecChannelCountTwoChannel; // Prepare fake connected device group auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type); @@ -5468,9 +5014,8 @@ TEST_F(StateMachineTest, testQoSConfigureWhileStreaming) { */ auto* leAudioDevice = group->GetFirstDevice(); EXPECT_CALL(gatt_queue, - WriteCharacteristic(1, leAudioDevice->ctp_hdls_.val_hdl, _, - GATT_WRITE_NO_RSP, _, _)) - .Times(4); + WriteCharacteristic(1, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) + .Times(4); EXPECT_CALL(*mock_iso_manager_, CreateCig(_, _)).Times(1); EXPECT_CALL(*mock_iso_manager_, EstablishCis(_)).Times(1); @@ -5482,20 +5027,17 @@ TEST_F(StateMachineTest, testQoSConfigureWhileStreaming) { InjectInitialIdleNotification(group); // Validate GroupStreamStatus - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::STREAMING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::STREAMING)); // Start the configuration and stream Media content ASSERT_TRUE(LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)})); + group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)})); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); ASSERT_EQ(1, get_func_call_count("alarm_cancel")); testing::Mock::VerifyAndClearExpectations(&mock_callbacks_); @@ -5503,13 +5045,10 @@ TEST_F(StateMachineTest, testQoSConfigureWhileStreaming) { log::info(" Moving to QoS state"); // Validate GroupStreamStatus - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::RELEASING)); EXPECT_CALL(mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::IDLE)); + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::RELEASING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::IDLE)); InjectQoSConfigurationForGroupActiveAses(group); testing::Mock::VerifyAndClearExpectations(&mock_callbacks_); @@ -5517,8 +5056,7 @@ TEST_F(StateMachineTest, testQoSConfigureWhileStreaming) { testing::Mock::VerifyAndClearExpectations(&gatt_queue); } -TEST_F(StateMachineTest, - testReleaseStreamWithLateAttachToStream_CodecConfigState) { +TEST_F(StateMachineTest, testReleaseStreamWithLateAttachToStream_CodecConfigState) { const auto context_type = kContextTypeMedia; const auto leaudio_group_id = 6; const auto num_devices = 2; @@ -5535,8 +5073,7 @@ TEST_F(StateMachineTest, ContentControlIdKeeper::GetInstance()->SetCcid(media_context, media_ccid); // Prepare multiple fake connected devices in a group - auto* group = - PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); ASSERT_EQ(group->Size(), num_devices); PrepareConfigureCodecHandler(group, 0, true); @@ -5557,10 +5094,9 @@ TEST_F(StateMachineTest, */ lastDevice = leAudioDevice; EXPECT_CALL(gatt_queue, - WriteCharacteristic(leAudioDevice->conn_id_, - leAudioDevice->ctp_hdls_.val_hdl, _, + WriteCharacteristic(leAudioDevice->conn_id_, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) - .Times(3); + .Times(3); expected_devices_written++; leAudioDevice = group->GetNextDevice(leAudioDevice); } @@ -5573,14 +5109,12 @@ TEST_F(StateMachineTest, InjectInitialIdleNotification(group); // Start the configuration and stream Media content - LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)}); + LeAudioGroupStateMachine::Get()->StartStream(group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)}); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); testing::Mock::VerifyAndClearExpectations(mock_iso_manager_); testing::Mock::VerifyAndClearExpectations(&gatt_queue); @@ -5592,22 +5126,18 @@ TEST_F(StateMachineTest, InjectAclDisconnected(group, lastDevice); // Check if group keeps streaming - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); /* Set device is getting ready for the connection */ lastDevice->conn_id_ = 3; - lastDevice->SetConnectionState( - DeviceConnectState::CONNECTED_AUTOCONNECT_GETTING_READY); + lastDevice->SetConnectionState(DeviceConnectState::CONNECTED_AUTOCONNECT_GETTING_READY); // Make sure ASE with disconnected CIS are not left in STREAMING - ASSERT_EQ(lastDevice->GetFirstAseWithState( - ::bluetooth::le_audio::types::kLeAudioDirectionSink, - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING), + ASSERT_EQ(lastDevice->GetFirstAseWithState(::bluetooth::le_audio::types::kLeAudioDirectionSink, + types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING), nullptr); - ASSERT_EQ(lastDevice->GetFirstAseWithState( - ::bluetooth::le_audio::types::kLeAudioDirectionSource, - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING), + ASSERT_EQ(lastDevice->GetFirstAseWithState(::bluetooth::le_audio::types::kLeAudioDirectionSource, + types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING), nullptr); log::info("Set device {} to CONNECTED state", lastDevice->address_); @@ -5617,15 +5147,13 @@ TEST_F(StateMachineTest, * 1. Codec Configure for attaching device * 2. Release for both devices */ - EXPECT_CALL(gatt_queue, WriteCharacteristic(lastDevice->conn_id_, - lastDevice->ctp_hdls_.val_hdl, _, - GATT_WRITE_NO_RSP, _, _)) - .Times(2); + EXPECT_CALL(gatt_queue, WriteCharacteristic(lastDevice->conn_id_, lastDevice->ctp_hdls_.val_hdl, + _, GATT_WRITE_NO_RSP, _, _)) + .Times(2); - EXPECT_CALL(gatt_queue, WriteCharacteristic(firstDevice->conn_id_, - firstDevice->ctp_hdls_.val_hdl, _, - GATT_WRITE_NO_RSP, _, _)) - .Times(1); + EXPECT_CALL(gatt_queue, WriteCharacteristic(firstDevice->conn_id_, firstDevice->ctp_hdls_.val_hdl, + _, GATT_WRITE_NO_RSP, _, _)) + .Times(1); log::info("Block Codec Configured Notification"); PrepareConfigureCodecHandler(group, 0, true, false); @@ -5633,15 +5161,13 @@ TEST_F(StateMachineTest, EXPECT_CALL(*mock_iso_manager_, EstablishCis(_)).Times(0); EXPECT_CALL(*mock_iso_manager_, SetupIsoDataPath(_, _)).Times(0); - LeAudioGroupStateMachine::Get()->AttachToStream( - group, lastDevice, {.sink = {media_ccid}, .source = {}}); + LeAudioGroupStateMachine::Get()->AttachToStream(group, lastDevice, + {.sink = {media_ccid}, .source = {}}); log::info("Stop the stream"); - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::RELEASING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::RELEASING)); // Stop the stream LeAudioGroupStateMachine::Get()->StopStream(group); @@ -5649,30 +5175,26 @@ TEST_F(StateMachineTest, testing::Mock::VerifyAndClearExpectations(&mock_callbacks_); testing::Mock::VerifyAndClearExpectations(&gatt_queue); - EXPECT_CALL(gatt_queue, WriteCharacteristic(lastDevice->conn_id_, - lastDevice->ctp_hdls_.val_hdl, _, - GATT_WRITE_NO_RSP, _, _)) - .Times(0); + EXPECT_CALL(gatt_queue, WriteCharacteristic(lastDevice->conn_id_, lastDevice->ctp_hdls_.val_hdl, + _, GATT_WRITE_NO_RSP, _, _)) + .Times(0); log::info( - "Inject Codec Configured Notification and make sure there is no QoS " - "Config sent"); + "Inject Codec Configured Notification and make sure there is no QoS " + "Config sent"); InjectCachedConfigurationForActiveAses(group, lastDevice); testing::Mock::VerifyAndClearExpectations(&gatt_queue); // Check if group is still in Streaming state - it will change when Release // notification will arrive. - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); - ASSERT_EQ(group->GetTargetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_IDLE); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetTargetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_IDLE); log::info("Inject Release for a group"); EXPECT_CALL(mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::IDLE)); + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::IDLE)); EXPECT_CALL(*mock_iso_manager_, RemoveIsoDataPath(_, _)).Times(1); EXPECT_CALL(*mock_iso_manager_, DisconnectCis(_, _)).Times(1); @@ -5682,13 +5204,11 @@ TEST_F(StateMachineTest, testing::Mock::VerifyAndClearExpectations(&mock_callbacks_); testing::Mock::VerifyAndClearExpectations(mock_iso_manager_); - ASSERT_EQ(group->GetTargetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_IDLE); + ASSERT_EQ(group->GetTargetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_IDLE); ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_IDLE); } -TEST_F(StateMachineTest, - testReleaseStreamWithLateAttachToStream_QoSConfigState) { +TEST_F(StateMachineTest, testReleaseStreamWithLateAttachToStream_QoSConfigState) { const auto context_type = kContextTypeMedia; const auto leaudio_group_id = 6; const auto num_devices = 2; @@ -5705,8 +5225,7 @@ TEST_F(StateMachineTest, ContentControlIdKeeper::GetInstance()->SetCcid(media_context, media_ccid); // Prepare multiple fake connected devices in a group - auto* group = - PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); ASSERT_EQ(group->Size(), num_devices); PrepareConfigureCodecHandler(group, 0, true); @@ -5727,10 +5246,9 @@ TEST_F(StateMachineTest, */ lastDevice = leAudioDevice; EXPECT_CALL(gatt_queue, - WriteCharacteristic(leAudioDevice->conn_id_, - leAudioDevice->ctp_hdls_.val_hdl, _, + WriteCharacteristic(leAudioDevice->conn_id_, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) - .Times(3); + .Times(3); expected_devices_written++; leAudioDevice = group->GetNextDevice(leAudioDevice); } @@ -5743,14 +5261,12 @@ TEST_F(StateMachineTest, InjectInitialIdleNotification(group); // Start the configuration and stream Media content - LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)}); + LeAudioGroupStateMachine::Get()->StartStream(group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)}); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); testing::Mock::VerifyAndClearExpectations(mock_iso_manager_); log::info("Stream is started for group {}, disconnect {}", group->group_id_, @@ -5761,22 +5277,18 @@ TEST_F(StateMachineTest, InjectAclDisconnected(group, lastDevice); // Check if group keeps streaming - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); /* Set device is getting ready for the connection */ lastDevice->conn_id_ = 3; - lastDevice->SetConnectionState( - DeviceConnectState::CONNECTED_AUTOCONNECT_GETTING_READY); + lastDevice->SetConnectionState(DeviceConnectState::CONNECTED_AUTOCONNECT_GETTING_READY); // Make sure ASE with disconnected CIS are not left in STREAMING - ASSERT_EQ(lastDevice->GetFirstAseWithState( - ::bluetooth::le_audio::types::kLeAudioDirectionSink, - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING), + ASSERT_EQ(lastDevice->GetFirstAseWithState(::bluetooth::le_audio::types::kLeAudioDirectionSink, + types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING), nullptr); - ASSERT_EQ(lastDevice->GetFirstAseWithState( - ::bluetooth::le_audio::types::kLeAudioDirectionSource, - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING), + ASSERT_EQ(lastDevice->GetFirstAseWithState(::bluetooth::le_audio::types::kLeAudioDirectionSource, + types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING), nullptr); log::info("Set device {} to CONNECTED state", lastDevice->address_); @@ -5787,14 +5299,12 @@ TEST_F(StateMachineTest, * 2. QoS Configured State for attaching device * 3. Release for both */ - EXPECT_CALL(gatt_queue, WriteCharacteristic(lastDevice->conn_id_, - lastDevice->ctp_hdls_.val_hdl, _, - GATT_WRITE_NO_RSP, _, _)) - .Times(3); - EXPECT_CALL(gatt_queue, WriteCharacteristic(firstDevice->conn_id_, - firstDevice->ctp_hdls_.val_hdl, _, - GATT_WRITE_NO_RSP, _, _)) - .Times(1); + EXPECT_CALL(gatt_queue, WriteCharacteristic(lastDevice->conn_id_, lastDevice->ctp_hdls_.val_hdl, + _, GATT_WRITE_NO_RSP, _, _)) + .Times(3); + EXPECT_CALL(gatt_queue, WriteCharacteristic(firstDevice->conn_id_, firstDevice->ctp_hdls_.val_hdl, + _, GATT_WRITE_NO_RSP, _, _)) + .Times(1); log::info("Block QoS Configured Notification"); PrepareConfigureQosHandler(group, 0, true, false); @@ -5802,15 +5312,13 @@ TEST_F(StateMachineTest, EXPECT_CALL(*mock_iso_manager_, EstablishCis(_)).Times(0); EXPECT_CALL(*mock_iso_manager_, SetupIsoDataPath(_, _)).Times(0); - LeAudioGroupStateMachine::Get()->AttachToStream( - group, lastDevice, {.sink = {media_ccid}, .source = {}}); + LeAudioGroupStateMachine::Get()->AttachToStream(group, lastDevice, + {.sink = {media_ccid}, .source = {}}); log::info("Stop the stream"); - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::RELEASING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::RELEASING)); // Stop the stream LeAudioGroupStateMachine::Get()->StopStream(group); @@ -5819,30 +5327,26 @@ TEST_F(StateMachineTest, testing::Mock::VerifyAndClearExpectations(mock_iso_manager_); testing::Mock::VerifyAndClearExpectations(&mock_callbacks_); - EXPECT_CALL(gatt_queue, WriteCharacteristic(lastDevice->conn_id_, - lastDevice->ctp_hdls_.val_hdl, _, - GATT_WRITE_NO_RSP, _, _)) - .Times(0); + EXPECT_CALL(gatt_queue, WriteCharacteristic(lastDevice->conn_id_, lastDevice->ctp_hdls_.val_hdl, + _, GATT_WRITE_NO_RSP, _, _)) + .Times(0); log::info( - "Inject QoS Config Notification and make sure that Enable Command is not " - "sent"); + "Inject QoS Config Notification and make sure that Enable Command is not " + "sent"); InjectQoSConfigurationForActiveAses(group, lastDevice); testing::Mock::VerifyAndClearExpectations(&gatt_queue); // Check if group is still in Streaming state - it will change when Release // notification will arrive. - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); - ASSERT_EQ(group->GetTargetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_IDLE); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetTargetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_IDLE); log::info("Inject Release for a group"); EXPECT_CALL(mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::IDLE)); + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::IDLE)); EXPECT_CALL(*mock_iso_manager_, RemoveIsoDataPath(_, _)).Times(1); EXPECT_CALL(*mock_iso_manager_, DisconnectCis(_, _)).Times(1); @@ -5852,13 +5356,11 @@ TEST_F(StateMachineTest, testing::Mock::VerifyAndClearExpectations(&mock_callbacks_); testing::Mock::VerifyAndClearExpectations(mock_iso_manager_); - ASSERT_EQ(group->GetTargetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_IDLE); + ASSERT_EQ(group->GetTargetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_IDLE); ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_IDLE); } -TEST_F(StateMachineTest, - testReleaseStreamWithLateAttachToStream_EnablingState) { +TEST_F(StateMachineTest, testReleaseStreamWithLateAttachToStream_EnablingState) { const auto context_type = kContextTypeMedia; const auto leaudio_group_id = 6; const auto num_devices = 2; @@ -5875,8 +5377,7 @@ TEST_F(StateMachineTest, ContentControlIdKeeper::GetInstance()->SetCcid(media_context, media_ccid); // Prepare multiple fake connected devices in a group - auto* group = - PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); ASSERT_EQ(group->Size(), num_devices); PrepareConfigureCodecHandler(group, 0, true); @@ -5897,10 +5398,9 @@ TEST_F(StateMachineTest, */ lastDevice = leAudioDevice; EXPECT_CALL(gatt_queue, - WriteCharacteristic(leAudioDevice->conn_id_, - leAudioDevice->ctp_hdls_.val_hdl, _, + WriteCharacteristic(leAudioDevice->conn_id_, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) - .Times(3); + .Times(3); expected_devices_written++; leAudioDevice = group->GetNextDevice(leAudioDevice); } @@ -5913,14 +5413,12 @@ TEST_F(StateMachineTest, InjectInitialIdleNotification(group); // Start the configuration and stream Media content - LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)}); + LeAudioGroupStateMachine::Get()->StartStream(group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)}); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); testing::Mock::VerifyAndClearExpectations(mock_iso_manager_); log::info("Stream is started for group {}, disconnect {}", group->group_id_, @@ -5931,22 +5429,18 @@ TEST_F(StateMachineTest, InjectAclDisconnected(group, lastDevice); // Check if group keeps streaming - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); /* Set device is getting ready for the connection */ lastDevice->conn_id_ = 3; - lastDevice->SetConnectionState( - DeviceConnectState::CONNECTED_AUTOCONNECT_GETTING_READY); + lastDevice->SetConnectionState(DeviceConnectState::CONNECTED_AUTOCONNECT_GETTING_READY); // Make sure ASE with disconnected CIS are not left in STREAMING - ASSERT_EQ(lastDevice->GetFirstAseWithState( - ::bluetooth::le_audio::types::kLeAudioDirectionSink, - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING), + ASSERT_EQ(lastDevice->GetFirstAseWithState(::bluetooth::le_audio::types::kLeAudioDirectionSink, + types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING), nullptr); - ASSERT_EQ(lastDevice->GetFirstAseWithState( - ::bluetooth::le_audio::types::kLeAudioDirectionSource, - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING), + ASSERT_EQ(lastDevice->GetFirstAseWithState(::bluetooth::le_audio::types::kLeAudioDirectionSource, + types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING), nullptr); log::info("Set device {} to CONNECTED state", lastDevice->address_); @@ -5958,14 +5452,12 @@ TEST_F(StateMachineTest, * 3. Enable for attaching device * 3. Release for both */ - EXPECT_CALL(gatt_queue, WriteCharacteristic(lastDevice->conn_id_, - lastDevice->ctp_hdls_.val_hdl, _, - GATT_WRITE_NO_RSP, _, _)) - .Times(4); - EXPECT_CALL(gatt_queue, WriteCharacteristic(firstDevice->conn_id_, - firstDevice->ctp_hdls_.val_hdl, _, - GATT_WRITE_NO_RSP, _, _)) - .Times(1); + EXPECT_CALL(gatt_queue, WriteCharacteristic(lastDevice->conn_id_, lastDevice->ctp_hdls_.val_hdl, + _, GATT_WRITE_NO_RSP, _, _)) + .Times(4); + EXPECT_CALL(gatt_queue, WriteCharacteristic(firstDevice->conn_id_, firstDevice->ctp_hdls_.val_hdl, + _, GATT_WRITE_NO_RSP, _, _)) + .Times(1); log::info("Block Enable Notification"); PrepareEnableHandler(group, 0, false, false); @@ -5973,15 +5465,13 @@ TEST_F(StateMachineTest, EXPECT_CALL(*mock_iso_manager_, EstablishCis(_)).Times(0); EXPECT_CALL(*mock_iso_manager_, SetupIsoDataPath(_, _)).Times(0); - LeAudioGroupStateMachine::Get()->AttachToStream( - group, lastDevice, {.sink = {media_ccid}, .source = {}}); + LeAudioGroupStateMachine::Get()->AttachToStream(group, lastDevice, + {.sink = {media_ccid}, .source = {}}); log::info("Stop the stream"); - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::RELEASING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::RELEASING)); // Stop the stream LeAudioGroupStateMachine::Get()->StopStream(group); @@ -5990,10 +5480,9 @@ TEST_F(StateMachineTest, testing::Mock::VerifyAndClearExpectations(mock_iso_manager_); testing::Mock::VerifyAndClearExpectations(&mock_callbacks_); - EXPECT_CALL(gatt_queue, WriteCharacteristic(lastDevice->conn_id_, - lastDevice->ctp_hdls_.val_hdl, _, - GATT_WRITE_NO_RSP, _, _)) - .Times(0); + EXPECT_CALL(gatt_queue, WriteCharacteristic(lastDevice->conn_id_, lastDevice->ctp_hdls_.val_hdl, + _, GATT_WRITE_NO_RSP, _, _)) + .Times(0); log::info("Inject Enabling Notification, don't create CIS"); @@ -6005,18 +5494,15 @@ TEST_F(StateMachineTest, // Check if group is still in Streaming state - it will change when Release // notification will arrive. - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); - ASSERT_EQ(group->GetTargetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_IDLE); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetTargetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_IDLE); testing::Mock::VerifyAndClearExpectations(mock_iso_manager_); log::info("Inject Release for a group"); EXPECT_CALL(mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::IDLE)); + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::IDLE)); EXPECT_CALL(*mock_iso_manager_, RemoveIsoDataPath(_, _)).Times(1); EXPECT_CALL(*mock_iso_manager_, DisconnectCis(_, _)).Times(1); @@ -6026,13 +5512,11 @@ TEST_F(StateMachineTest, testing::Mock::VerifyAndClearExpectations(&mock_callbacks_); testing::Mock::VerifyAndClearExpectations(mock_iso_manager_); - ASSERT_EQ(group->GetTargetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_IDLE); + ASSERT_EQ(group->GetTargetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_IDLE); ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_IDLE); } -TEST_F(StateMachineTest, - testReleaseStreamWithLateAttachToStream_BeforeStreamingState) { +TEST_F(StateMachineTest, testReleaseStreamWithLateAttachToStream_BeforeStreamingState) { const auto context_type = kContextTypeMedia; const auto leaudio_group_id = 6; const auto num_devices = 2; @@ -6049,8 +5533,7 @@ TEST_F(StateMachineTest, ContentControlIdKeeper::GetInstance()->SetCcid(media_context, media_ccid); // Prepare multiple fake connected devices in a group - auto* group = - PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); ASSERT_EQ(group->Size(), num_devices); PrepareConfigureCodecHandler(group, 0, true); @@ -6071,10 +5554,9 @@ TEST_F(StateMachineTest, */ lastDevice = leAudioDevice; EXPECT_CALL(gatt_queue, - WriteCharacteristic(leAudioDevice->conn_id_, - leAudioDevice->ctp_hdls_.val_hdl, _, + WriteCharacteristic(leAudioDevice->conn_id_, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) - .Times(3); + .Times(3); expected_devices_written++; leAudioDevice = group->GetNextDevice(leAudioDevice); } @@ -6087,14 +5569,12 @@ TEST_F(StateMachineTest, InjectInitialIdleNotification(group); // Start the configuration and stream Media content - LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)}); + LeAudioGroupStateMachine::Get()->StartStream(group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)}); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); testing::Mock::VerifyAndClearExpectations(mock_iso_manager_); log::info("Stream is started for group {}, disconnect {}", group->group_id_, @@ -6105,22 +5585,18 @@ TEST_F(StateMachineTest, InjectAclDisconnected(group, lastDevice); // Check if group keeps streaming - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); /* Set device is getting ready for the connection */ lastDevice->conn_id_ = 3; - lastDevice->SetConnectionState( - DeviceConnectState::CONNECTED_AUTOCONNECT_GETTING_READY); + lastDevice->SetConnectionState(DeviceConnectState::CONNECTED_AUTOCONNECT_GETTING_READY); // Make sure ASE with disconnected CIS are not left in STREAMING - ASSERT_EQ(lastDevice->GetFirstAseWithState( - ::bluetooth::le_audio::types::kLeAudioDirectionSink, - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING), + ASSERT_EQ(lastDevice->GetFirstAseWithState(::bluetooth::le_audio::types::kLeAudioDirectionSink, + types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING), nullptr); - ASSERT_EQ(lastDevice->GetFirstAseWithState( - ::bluetooth::le_audio::types::kLeAudioDirectionSource, - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING), + ASSERT_EQ(lastDevice->GetFirstAseWithState(::bluetooth::le_audio::types::kLeAudioDirectionSource, + types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING), nullptr); log::info("Set device {} to CONNECTED state", lastDevice->address_); @@ -6132,14 +5608,12 @@ TEST_F(StateMachineTest, * 3. Enable for attaching device * 3. Release for both */ - EXPECT_CALL(gatt_queue, WriteCharacteristic(lastDevice->conn_id_, - lastDevice->ctp_hdls_.val_hdl, _, - GATT_WRITE_NO_RSP, _, _)) - .Times(4); - EXPECT_CALL(gatt_queue, WriteCharacteristic(firstDevice->conn_id_, - firstDevice->ctp_hdls_.val_hdl, _, - GATT_WRITE_NO_RSP, _, _)) - .Times(1); + EXPECT_CALL(gatt_queue, WriteCharacteristic(lastDevice->conn_id_, lastDevice->ctp_hdls_.val_hdl, + _, GATT_WRITE_NO_RSP, _, _)) + .Times(4); + EXPECT_CALL(gatt_queue, WriteCharacteristic(firstDevice->conn_id_, firstDevice->ctp_hdls_.val_hdl, + _, GATT_WRITE_NO_RSP, _, _)) + .Times(1); log::info("Block Streaming Notification"); @@ -6148,15 +5622,13 @@ TEST_F(StateMachineTest, EXPECT_CALL(*mock_iso_manager_, EstablishCis(_)).Times(1); EXPECT_CALL(*mock_iso_manager_, SetupIsoDataPath(_, _)).Times(1); - LeAudioGroupStateMachine::Get()->AttachToStream( - group, lastDevice, {.sink = {media_ccid}, .source = {}}); + LeAudioGroupStateMachine::Get()->AttachToStream(group, lastDevice, + {.sink = {media_ccid}, .source = {}}); log::info("Stop the stream"); - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::RELEASING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::RELEASING)); // Stop the stream LeAudioGroupStateMachine::Get()->StopStream(group); @@ -6165,10 +5637,9 @@ TEST_F(StateMachineTest, testing::Mock::VerifyAndClearExpectations(mock_iso_manager_); testing::Mock::VerifyAndClearExpectations(&mock_callbacks_); - EXPECT_CALL(gatt_queue, WriteCharacteristic(lastDevice->conn_id_, - lastDevice->ctp_hdls_.val_hdl, _, - GATT_WRITE_NO_RSP, _, _)) - .Times(0); + EXPECT_CALL(gatt_queue, WriteCharacteristic(lastDevice->conn_id_, lastDevice->ctp_hdls_.val_hdl, + _, GATT_WRITE_NO_RSP, _, _)) + .Times(0); log::info("Inject Streaming Notification"); @@ -6178,16 +5649,13 @@ TEST_F(StateMachineTest, // Check if group is still in Streaming state - it will change when Release // notification will arrive. - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); - ASSERT_EQ(group->GetTargetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_IDLE); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetTargetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_IDLE); log::info("Inject Release for a group"); EXPECT_CALL(mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::IDLE)); + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::IDLE)); EXPECT_CALL(*mock_iso_manager_, RemoveIsoDataPath(_, _)).Times(2); EXPECT_CALL(*mock_iso_manager_, DisconnectCis(_, _)).Times(2); @@ -6197,8 +5665,7 @@ TEST_F(StateMachineTest, testing::Mock::VerifyAndClearExpectations(&mock_callbacks_); testing::Mock::VerifyAndClearExpectations(mock_iso_manager_); - ASSERT_EQ(group->GetTargetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_IDLE); + ASSERT_EQ(group->GetTargetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_IDLE); ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_IDLE); } @@ -6220,8 +5687,7 @@ TEST_F(StateMachineTest, testAutonomousConfiguredAndAttachToStream) { ContentControlIdKeeper::GetInstance()->SetCcid(media_context, media_ccid); // Prepare multiple fake connected devices in a group - auto* group = - PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); ASSERT_EQ(group->Size(), num_devices); PrepareConfigureCodecHandler(group, 0, true); @@ -6243,10 +5709,9 @@ TEST_F(StateMachineTest, testAutonomousConfiguredAndAttachToStream) { */ lastDevice = leAudioDevice; EXPECT_CALL(gatt_queue, - WriteCharacteristic(leAudioDevice->conn_id_, - leAudioDevice->ctp_hdls_.val_hdl, _, + WriteCharacteristic(leAudioDevice->conn_id_, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) - .Times(AtLeast(3)); + .Times(AtLeast(3)); expected_devices_written++; leAudioDevice = group->GetNextDevice(leAudioDevice); } @@ -6259,14 +5724,12 @@ TEST_F(StateMachineTest, testAutonomousConfiguredAndAttachToStream) { InjectInitialIdleNotification(group); // Start the configuration and stream Media content - LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)}); + LeAudioGroupStateMachine::Get()->StartStream(group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)}); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); testing::Mock::VerifyAndClearExpectations(mock_iso_manager_); // Inject CIS and ACL disconnection of first device @@ -6274,40 +5737,33 @@ TEST_F(StateMachineTest, testAutonomousConfiguredAndAttachToStream) { InjectAclDisconnected(group, lastDevice); // Check if group keeps streaming - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); /* Set device is getting ready for the connection */ lastDevice->conn_id_ = 3; - lastDevice->SetConnectionState( - DeviceConnectState::CONNECTED_AUTOCONNECT_GETTING_READY); + lastDevice->SetConnectionState(DeviceConnectState::CONNECTED_AUTOCONNECT_GETTING_READY); // Make sure ASE with disconnected CIS are not left in STREAMING - ASSERT_EQ(lastDevice->GetFirstAseWithState( - ::bluetooth::le_audio::types::kLeAudioDirectionSink, - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING), + ASSERT_EQ(lastDevice->GetFirstAseWithState(::bluetooth::le_audio::types::kLeAudioDirectionSink, + types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING), nullptr); - ASSERT_EQ(lastDevice->GetFirstAseWithState( - ::bluetooth::le_audio::types::kLeAudioDirectionSource, - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING), + ASSERT_EQ(lastDevice->GetFirstAseWithState(::bluetooth::le_audio::types::kLeAudioDirectionSource, + types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING), nullptr); // Symulate remote autonomous CONFIGURE state - EXPECT_CALL(gatt_queue, WriteCharacteristic(lastDevice->conn_id_, - lastDevice->ctp_hdls_.val_hdl, _, - GATT_WRITE_NO_RSP, _, _)) - .Times(0); + EXPECT_CALL(gatt_queue, WriteCharacteristic(lastDevice->conn_id_, lastDevice->ctp_hdls_.val_hdl, + _, GATT_WRITE_NO_RSP, _, _)) + .Times(0); int num_of_notifications = 0; for (auto& ase : lastDevice->ases_) { if (ase.id == bluetooth::le_audio::types::ase::kAseIdInvalid) { continue; } - log::error("ID : {}, status {}", ase.id, - bluetooth::common::ToString(ase.state)); + log::error("ID : {}, status {}", ase.id, bluetooth::common::ToString(ase.state)); num_of_notifications++; - InjectAseStateNotification(&ase, lastDevice, group, - ascs::kAseStateCodecConfigured, + InjectAseStateNotification(&ase, lastDevice, group, ascs::kAseStateCodecConfigured, &cached_codec_configuration_map_[ase.id]); break; } @@ -6318,29 +5774,26 @@ TEST_F(StateMachineTest, testAutonomousConfiguredAndAttachToStream) { lastDevice->SetConnectionState(DeviceConnectState::CONNECTED); - EXPECT_CALL(gatt_queue, WriteCharacteristic(lastDevice->conn_id_, - lastDevice->ctp_hdls_.val_hdl, _, - GATT_WRITE_NO_RSP, _, _)) - .Times(AtLeast(3)); + EXPECT_CALL(gatt_queue, WriteCharacteristic(lastDevice->conn_id_, lastDevice->ctp_hdls_.val_hdl, + _, GATT_WRITE_NO_RSP, _, _)) + .Times(AtLeast(3)); EXPECT_CALL(*mock_iso_manager_, EstablishCis(_)).Times(1); EXPECT_CALL(*mock_iso_manager_, SetupIsoDataPath(_, _)).Times(1); - LeAudioGroupStateMachine::Get()->AttachToStream( - group, lastDevice, {.sink = {media_ccid}, .source = {}}); + LeAudioGroupStateMachine::Get()->AttachToStream(group, lastDevice, + {.sink = {media_ccid}, .source = {}}); // Check if group keeps streaming - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); // Verify that the joining device receives the right CCID list auto lastMeta = lastDevice->GetFirstActiveAse()->metadata; bool parsedOk = false; - auto ltv = bluetooth::le_audio::types::LeAudioLtvMap::Parse( - lastMeta.data(), lastMeta.size(), parsedOk); + auto ltv = bluetooth::le_audio::types::LeAudioLtvMap::Parse(lastMeta.data(), lastMeta.size(), + parsedOk); ASSERT_TRUE(parsedOk); - auto ccids = - ltv.Find(bluetooth::le_audio::types::kLeAudioMetadataTypeCcidList); + auto ccids = ltv.Find(bluetooth::le_audio::types::kLeAudioMetadataTypeCcidList); ASSERT_TRUE(ccids.has_value()); ASSERT_NE(std::find(ccids->begin(), ccids->end(), media_ccid), ccids->end()); @@ -6350,8 +5803,7 @@ TEST_F(StateMachineTest, testAutonomousConfiguredAndAttachToStream) { ASSERT_NE(ase->qos_config.retrans_nb, 0); } -TEST_F(StateMachineTest, - testAttachDeviceToTheStream_autonomusQoSConfiguredState) { +TEST_F(StateMachineTest, testAttachDeviceToTheStream_autonomusQoSConfiguredState) { const auto context_type = kContextTypeMedia; const auto leaudio_group_id = 6; const auto num_devices = 2; @@ -6359,8 +5811,7 @@ TEST_F(StateMachineTest, ContentControlIdKeeper::GetInstance()->SetCcid(media_context, media_ccid); // Prepare multiple fake connected devices in a group - auto* group = - PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); ASSERT_EQ(group->Size(), num_devices); PrepareConfigureCodecHandler(group); @@ -6382,10 +5833,9 @@ TEST_F(StateMachineTest, */ lastDevice = leAudioDevice; EXPECT_CALL(gatt_queue, - WriteCharacteristic(leAudioDevice->conn_id_, - leAudioDevice->ctp_hdls_.val_hdl, _, + WriteCharacteristic(leAudioDevice->conn_id_, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) - .Times(AtLeast(3)); + .Times(AtLeast(3)); expected_devices_written++; leAudioDevice = group->GetNextDevice(leAudioDevice); } @@ -6398,64 +5848,55 @@ TEST_F(StateMachineTest, InjectInitialIdleNotification(group); // Start the configuration and stream Media content - LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)}, - {.sink = std::vector(1, media_ccid), - .source = std::vector(1, media_ccid)}); + LeAudioGroupStateMachine::Get()->StartStream(group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)}, + {.sink = std::vector(1, media_ccid), + .source = std::vector(1, media_ccid)}); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); testing::Mock::VerifyAndClearExpectations(mock_iso_manager_); // Inject CIS and ACL disconnection of first device InjectCisDisconnected(group, lastDevice, HCI_ERR_CONNECTION_TOUT); // Check if group keeps streaming - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); // Make sure ASE with disconnected CIS are not left in STREAMING - ASSERT_EQ(lastDevice->GetFirstAseWithState( - ::bluetooth::le_audio::types::kLeAudioDirectionSink, - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING), + ASSERT_EQ(lastDevice->GetFirstAseWithState(::bluetooth::le_audio::types::kLeAudioDirectionSink, + types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING), nullptr); - ASSERT_EQ(lastDevice->GetFirstAseWithState( - ::bluetooth::le_audio::types::kLeAudioDirectionSource, - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING), + ASSERT_EQ(lastDevice->GetFirstAseWithState(::bluetooth::le_audio::types::kLeAudioDirectionSource, + types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING), nullptr); - EXPECT_CALL(gatt_queue, WriteCharacteristic(lastDevice->conn_id_, - lastDevice->ctp_hdls_.val_hdl, _, - GATT_WRITE_NO_RSP, _, _)) - .Times(1); + EXPECT_CALL(gatt_queue, WriteCharacteristic(lastDevice->conn_id_, lastDevice->ctp_hdls_.val_hdl, + _, GATT_WRITE_NO_RSP, _, _)) + .Times(1); EXPECT_CALL(*mock_iso_manager_, EstablishCis(_)).Times(1); EXPECT_CALL(*mock_iso_manager_, SetupIsoDataPath(_, _)).Times(1); for (auto& ase : lastDevice->ases_) { if (cached_remote_qos_configuration_for_ase_.count(&ase) > 0) { - InjectAseStateNotification( - &ase, lastDevice, group, ascs::kAseStateQoSConfigured, - &(cached_remote_qos_configuration_for_ase_[&ase])); + InjectAseStateNotification(&ase, lastDevice, group, ascs::kAseStateQoSConfigured, + &(cached_remote_qos_configuration_for_ase_[&ase])); } } // Check if group keeps streaming - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); // Verify that the joining device receives the right CCID list auto lastMeta = lastDevice->GetFirstActiveAse()->metadata; bool parsedOk = false; - auto ltv = bluetooth::le_audio::types::LeAudioLtvMap::Parse( - lastMeta.data(), lastMeta.size(), parsedOk); + auto ltv = bluetooth::le_audio::types::LeAudioLtvMap::Parse(lastMeta.data(), lastMeta.size(), + parsedOk); ASSERT_TRUE(parsedOk); - auto ccids = - ltv.Find(bluetooth::le_audio::types::kLeAudioMetadataTypeCcidList); + auto ccids = ltv.Find(bluetooth::le_audio::types::kLeAudioMetadataTypeCcidList); ASSERT_TRUE(ccids.has_value()); ASSERT_NE(std::find(ccids->begin(), ccids->end(), media_ccid), ccids->end()); @@ -6473,8 +5914,7 @@ TEST_F(StateMachineTest, testAttachDeviceToTheStreamDoNotAttach) { ContentControlIdKeeper::GetInstance()->SetCcid(media_context, media_ccid); // Prepare multiple fake connected devices in a group - auto* group = - PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); ASSERT_EQ(group->Size(), num_devices); PrepareConfigureCodecHandler(group); @@ -6499,32 +5939,27 @@ TEST_F(StateMachineTest, testAttachDeviceToTheStreamDoNotAttach) { EXPECT_CALL(*mock_iso_manager_, CreateCig(_, _)).Times(1); EXPECT_CALL(*mock_iso_manager_, EstablishCis(_)).Times(1); EXPECT_CALL(*mock_iso_manager_, SetupIsoDataPath(_, _)).Times(1); - LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)}); + LeAudioGroupStateMachine::Get()->StartStream(group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)}); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); testing::Mock::VerifyAndClearExpectations(mock_iso_manager_); // Check if group keeps streaming - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); lastDevice->conn_id_ = 3; lastDevice->SetConnectionState(DeviceConnectState::CONNECTED); - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::RELEASING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::RELEASING)); LeAudioGroupStateMachine::Get()->StopStream(group); testing::Mock::VerifyAndClearExpectations(&mock_callbacks_); - ASSERT_FALSE(LeAudioGroupStateMachine::Get()->AttachToStream( - group, lastDevice, {.sink = {}, .source = {}})); + ASSERT_FALSE(LeAudioGroupStateMachine::Get()->AttachToStream(group, lastDevice, + {.sink = {}, .source = {}})); } TEST_F(StateMachineTest, testReconfigureAfterLateDeviceAttached) { @@ -6535,8 +5970,7 @@ TEST_F(StateMachineTest, testReconfigureAfterLateDeviceAttached) { ContentControlIdKeeper::GetInstance()->SetCcid(media_context, media_ccid); // Prepare multiple fake connected devices in a group - auto* group = - PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); ASSERT_EQ(group->Size(), num_devices); PrepareConfigureCodecHandler(group, 0, true); @@ -6566,19 +6000,17 @@ TEST_F(StateMachineTest, testReconfigureAfterLateDeviceAttached) { EXPECT_CALL(*mock_iso_manager_, EstablishCis(_)).Times(1); EXPECT_CALL(*mock_iso_manager_, SetupIsoDataPath(_, _)).Times(1); - types::BidirectionalPair> ccids_list = { - .sink = {media_ccid}, .source = {media_ccid}}; + types::BidirectionalPair> ccids_list = {.sink = {media_ccid}, + .source = {media_ccid}}; // Start the configuration and stream Media content - LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)}, - ccids_list); + LeAudioGroupStateMachine::Get()->StartStream(group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)}, + ccids_list); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); testing::Mock::VerifyAndClearExpectations(mock_iso_manager_); /* Stop the stream and let first device to stay in configured state (caching @@ -6587,8 +6019,7 @@ TEST_F(StateMachineTest, testReconfigureAfterLateDeviceAttached) { testing::Mock::VerifyAndClearExpectations(&mock_callbacks_); /* Verify state in the configured state */ - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED); /* Now when stream is stopped, connect second device. */ lastDevice->conn_id_ = 3; @@ -6604,15 +6035,13 @@ TEST_F(StateMachineTest, testReconfigureAfterLateDeviceAttached) { EXPECT_CALL(*mock_iso_manager_, SetupIsoDataPath(_, _)).Times(2); // Start the configuration and stream Media content - LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)}, - ccids_list); + LeAudioGroupStateMachine::Get()->StartStream(group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)}, + ccids_list); // Check if group keeps streaming - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); // Verify that both devicse receives the right CCID list and both are // streaming @@ -6622,12 +6051,11 @@ TEST_F(StateMachineTest, testReconfigureAfterLateDeviceAttached) { ASSERT_NE(nullptr, ase); auto lastMeta = ase->metadata; bool parsedOk = false; - auto ltv = bluetooth::le_audio::types::LeAudioLtvMap::Parse( - lastMeta.data(), lastMeta.size(), parsedOk); + auto ltv = bluetooth::le_audio::types::LeAudioLtvMap::Parse(lastMeta.data(), lastMeta.size(), + parsedOk); ASSERT_TRUE(parsedOk); - auto ccids = - ltv.Find(bluetooth::le_audio::types::kLeAudioMetadataTypeCcidList); + auto ccids = ltv.Find(bluetooth::le_audio::types::kLeAudioMetadataTypeCcidList); ASSERT_TRUE(ccids.has_value()); ASSERT_NE(std::find(ccids->begin(), ccids->end(), media_ccid), ccids->end()); @@ -6638,8 +6066,7 @@ TEST_F(StateMachineTest, testReconfigureAfterLateDeviceAttached) { ASSERT_NE(ase->qos_config.retrans_nb, 0); } -TEST_F(StateMachineTest, - testReconfigureAfterLateDeviceAttachedConversationalSwb) { +TEST_F(StateMachineTest, testReconfigureAfterLateDeviceAttachedConversationalSwb) { const auto context_type = kContextTypeConversational; const auto leaudio_group_id = 6; const auto num_devices = 2; @@ -6647,8 +6074,7 @@ TEST_F(StateMachineTest, ContentControlIdKeeper::GetInstance()->SetCcid(media_context, media_ccid); // Prepare multiple fake connected devices in a group - auto* group = - PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); ASSERT_EQ(group->Size(), num_devices); PrepareConfigureCodecHandler(group, 0, true); @@ -6678,29 +6104,25 @@ TEST_F(StateMachineTest, EXPECT_CALL(*mock_iso_manager_, EstablishCis(_)).Times(1); EXPECT_CALL(*mock_iso_manager_, SetupIsoDataPath(_, _)).Times(2); - types::BidirectionalPair> ccids_list = { - .sink = {media_ccid}, .source = {media_ccid}}; + types::BidirectionalPair> ccids_list = {.sink = {media_ccid}, + .source = {media_ccid}}; // Start the configuration and stream Media content - LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)}, - ccids_list); + LeAudioGroupStateMachine::Get()->StartStream(group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)}, + ccids_list); auto current_config = group->GetCachedConfiguration(context_type); ASSERT_NE(nullptr, current_config.get()); // With a single device there will be no dual bidir SWB but a single bidir SWB - ASSERT_TRUE( - AudioSetConfigurationProvider::Get()->CheckConfigurationIsBiDirSwb( + ASSERT_TRUE(AudioSetConfigurationProvider::Get()->CheckConfigurationIsBiDirSwb( *current_config.get())); - ASSERT_FALSE( - AudioSetConfigurationProvider::Get()->CheckConfigurationIsDualBiDirSwb( + ASSERT_FALSE(AudioSetConfigurationProvider::Get()->CheckConfigurationIsDualBiDirSwb( *current_config.get())); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); testing::Mock::VerifyAndClearExpectations(mock_iso_manager_); /* Stop the stream and let first device to stay in configured state (caching @@ -6709,8 +6131,7 @@ TEST_F(StateMachineTest, testing::Mock::VerifyAndClearExpectations(&mock_callbacks_); /* Verify state in the configured state */ - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED); /* Now when stream is stopped, connect second device. */ lastDevice->conn_id_ = 3; @@ -6725,15 +6146,13 @@ TEST_F(StateMachineTest, EXPECT_CALL(*mock_iso_manager_, SetupIsoDataPath(_, _)).Times(4); // Start the configuration and stream Media content - LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)}, - ccids_list); + LeAudioGroupStateMachine::Get()->StartStream(group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)}, + ccids_list); // Check if group keeps streaming - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); // Verify that both devicse receives the right CCID list and both are // streaming @@ -6743,12 +6162,11 @@ TEST_F(StateMachineTest, ASSERT_NE(nullptr, ase); auto lastMeta = ase->metadata; bool parsedOk = false; - auto ltv = bluetooth::le_audio::types::LeAudioLtvMap::Parse( - lastMeta.data(), lastMeta.size(), parsedOk); + auto ltv = bluetooth::le_audio::types::LeAudioLtvMap::Parse(lastMeta.data(), lastMeta.size(), + parsedOk); ASSERT_TRUE(parsedOk); - auto ccids = - ltv.Find(bluetooth::le_audio::types::kLeAudioMetadataTypeCcidList); + auto ccids = ltv.Find(bluetooth::le_audio::types::kLeAudioMetadataTypeCcidList); ASSERT_TRUE(ccids.has_value()); ASSERT_NE(std::find(ccids->begin(), ccids->end(), media_ccid), ccids->end()); @@ -6761,13 +6179,11 @@ TEST_F(StateMachineTest, // With both devices we should get the dual bidir SWB configuration current_config = group->GetCachedConfiguration(context_type); ASSERT_NE(nullptr, current_config.get()); - ASSERT_TRUE( - AudioSetConfigurationProvider::Get()->CheckConfigurationIsDualBiDirSwb( + ASSERT_TRUE(AudioSetConfigurationProvider::Get()->CheckConfigurationIsDualBiDirSwb( *current_config.get())); } -TEST_F(StateMachineTestNoSwb, - testReconfigureAfterLateDeviceAttachedConversationalNoSwb) { +TEST_F(StateMachineTestNoSwb, testReconfigureAfterLateDeviceAttachedConversationalNoSwb) { const auto context_type = kContextTypeConversational; const auto leaudio_group_id = 6; const auto num_devices = 2; @@ -6775,8 +6191,7 @@ TEST_F(StateMachineTestNoSwb, ContentControlIdKeeper::GetInstance()->SetCcid(media_context, media_ccid); // Prepare multiple fake connected devices in a group - auto* group = - PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); ASSERT_EQ(group->Size(), num_devices); PrepareConfigureCodecHandler(group, 0, true); @@ -6806,30 +6221,26 @@ TEST_F(StateMachineTestNoSwb, EXPECT_CALL(*mock_iso_manager_, EstablishCis(_)).Times(1); EXPECT_CALL(*mock_iso_manager_, SetupIsoDataPath(_, _)).Times(2); - types::BidirectionalPair> ccids_list = { - .sink = {media_ccid}, .source = {media_ccid}}; + types::BidirectionalPair> ccids_list = {.sink = {media_ccid}, + .source = {media_ccid}}; // Start the configuration and stream Media content - LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)}, - ccids_list); + LeAudioGroupStateMachine::Get()->StartStream(group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)}, + ccids_list); auto current_config = group->GetCachedConfiguration(context_type); ASSERT_NE(nullptr, current_config.get()); // With a single device there shall be no bidir SWB, as we expect the 2nd // device to join the stream seamlessly while dual bidir SWB is disabled. - ASSERT_FALSE( - AudioSetConfigurationProvider::Get()->CheckConfigurationIsBiDirSwb( + ASSERT_FALSE(AudioSetConfigurationProvider::Get()->CheckConfigurationIsBiDirSwb( *current_config.get())); - ASSERT_FALSE( - AudioSetConfigurationProvider::Get()->CheckConfigurationIsDualBiDirSwb( + ASSERT_FALSE(AudioSetConfigurationProvider::Get()->CheckConfigurationIsDualBiDirSwb( *current_config.get())); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); testing::Mock::VerifyAndClearExpectations(mock_iso_manager_); /* Stop the stream and let first device to stay in configured state (caching @@ -6838,8 +6249,7 @@ TEST_F(StateMachineTestNoSwb, testing::Mock::VerifyAndClearExpectations(&mock_callbacks_); /* Verify state in the configured state */ - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED); /* Now when stream is stopped, connect second device. */ lastDevice->conn_id_ = 3; @@ -6854,15 +6264,13 @@ TEST_F(StateMachineTestNoSwb, EXPECT_CALL(*mock_iso_manager_, SetupIsoDataPath(_, _)).Times(4); // Start the configuration and stream Media content - LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)}, - ccids_list); + LeAudioGroupStateMachine::Get()->StartStream(group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)}, + ccids_list); // Check if group keeps streaming - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); // Verify that both devicse receives the right CCID list and both are // streaming @@ -6872,12 +6280,11 @@ TEST_F(StateMachineTestNoSwb, ASSERT_NE(nullptr, ase); auto lastMeta = ase->metadata; bool parsedOk = false; - auto ltv = bluetooth::le_audio::types::LeAudioLtvMap::Parse( - lastMeta.data(), lastMeta.size(), parsedOk); + auto ltv = bluetooth::le_audio::types::LeAudioLtvMap::Parse(lastMeta.data(), lastMeta.size(), + parsedOk); ASSERT_TRUE(parsedOk); - auto ccids = - ltv.Find(bluetooth::le_audio::types::kLeAudioMetadataTypeCcidList); + auto ccids = ltv.Find(bluetooth::le_audio::types::kLeAudioMetadataTypeCcidList); ASSERT_TRUE(ccids.has_value()); ASSERT_NE(std::find(ccids->begin(), ccids->end(), media_ccid), ccids->end()); @@ -6891,8 +6298,7 @@ TEST_F(StateMachineTestNoSwb, // as it is currently disabled. current_config = group->GetCachedConfiguration(context_type); ASSERT_NE(nullptr, current_config.get()); - ASSERT_FALSE( - AudioSetConfigurationProvider::Get()->CheckConfigurationIsDualBiDirSwb( + ASSERT_FALSE(AudioSetConfigurationProvider::Get()->CheckConfigurationIsDualBiDirSwb( *current_config.get())); } @@ -6904,14 +6310,12 @@ TEST_F(StateMachineTest, testStreamToGettingReadyDevice) { ContentControlIdKeeper::GetInstance()->SetCcid(call_context, call_ccid); // Prepare multiple fake connected devices in a group - auto* group = - PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); // Simulate the 2nd device still getting ready auto* firstDevice = group->GetFirstDevice(); auto* secondDevice = group->GetNextDevice(firstDevice); - secondDevice->SetConnectionState( - DeviceConnectState::CONNECTED_BY_USER_GETTING_READY); + secondDevice->SetConnectionState(DeviceConnectState::CONNECTED_BY_USER_GETTING_READY); group->UpdateAudioContextAvailability(); group->UpdateAudioSetConfigurationCache(context_type); @@ -6932,10 +6336,9 @@ TEST_F(StateMachineTest, testStreamToGettingReadyDevice) { * 3: Enabling */ // Expect actions only on the already prepared device - EXPECT_CALL(gatt_queue, WriteCharacteristic(firstDevice->conn_id_, - firstDevice->ctp_hdls_.val_hdl, _, - GATT_WRITE_NO_RSP, _, _)) - .Times(AtLeast(3)); + EXPECT_CALL(gatt_queue, WriteCharacteristic(firstDevice->conn_id_, firstDevice->ctp_hdls_.val_hdl, + _, GATT_WRITE_NO_RSP, _, _)) + .Times(AtLeast(3)); EXPECT_CALL(*mock_iso_manager_, CreateCig(_, _)).Times(1); EXPECT_CALL(*mock_iso_manager_, EstablishCis(_)).Times(1); @@ -6944,15 +6347,13 @@ TEST_F(StateMachineTest, testStreamToGettingReadyDevice) { InjectInitialIdleNotification(group); // Start the configuration and the stream - LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)}); + LeAudioGroupStateMachine::Get()->StartStream(group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)}); // Check if group has transitioned to a proper state with one device still // being in the `CONNECTED_BY_USER_GETTING_READY` state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); testing::Mock::VerifyAndClearExpectations(mock_iso_manager_); } @@ -6964,8 +6365,7 @@ TEST_F(StateMachineTest, testAttachDeviceToTheConversationalStream) { ContentControlIdKeeper::GetInstance()->SetCcid(call_context, call_ccid); // Prepare multiple fake connected devices in a group - auto* group = - PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); ASSERT_EQ(group->Size(), num_devices); PrepareConfigureCodecHandler(group); @@ -6988,10 +6388,9 @@ TEST_F(StateMachineTest, testAttachDeviceToTheConversationalStream) { */ lastDevice = leAudioDevice; EXPECT_CALL(gatt_queue, - WriteCharacteristic(leAudioDevice->conn_id_, - leAudioDevice->ctp_hdls_.val_hdl, _, + WriteCharacteristic(leAudioDevice->conn_id_, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) - .Times(AtLeast(3)); + .Times(AtLeast(3)); expected_devices_written++; leAudioDevice = group->GetNextDevice(leAudioDevice); } @@ -7004,57 +6403,47 @@ TEST_F(StateMachineTest, testAttachDeviceToTheConversationalStream) { EXPECT_CALL(*mock_iso_manager_, SetupIsoDataPath( - _, dataPathDirIsEq( - bluetooth::hci::iso_manager::kIsoDataPathDirectionIn))) - .Times(2); + _, dataPathDirIsEq(bluetooth::hci::iso_manager::kIsoDataPathDirectionIn))) + .Times(2); // Make sure the Out data path is set before we declare that we are ready { ::testing::InSequence seq; EXPECT_CALL(*mock_iso_manager_, SetupIsoDataPath( - UNIQUE_CIS_CONN_HANDLE(leaudio_group_id, 0), - dataPathDirIsEq( - bluetooth::hci::iso_manager::kIsoDataPathDirectionOut))) - .Times(1); - EXPECT_CALL(ase_ctp_handler, - AseCtpReceiverStartReadyHandler(firstDevice, _, _, _)) - .Times(1); + UNIQUE_CIS_CONN_HANDLE(leaudio_group_id, 0), + dataPathDirIsEq(bluetooth::hci::iso_manager::kIsoDataPathDirectionOut))) + .Times(1); + EXPECT_CALL(ase_ctp_handler, AseCtpReceiverStartReadyHandler(firstDevice, _, _, _)).Times(1); } { ::testing::InSequence seq; EXPECT_CALL(*mock_iso_manager_, SetupIsoDataPath( - UNIQUE_CIS_CONN_HANDLE(leaudio_group_id, 1), - dataPathDirIsEq( - bluetooth::hci::iso_manager::kIsoDataPathDirectionOut))) - .Times(1); - EXPECT_CALL(ase_ctp_handler, - AseCtpReceiverStartReadyHandler(lastDevice, _, _, _)) - .Times(1); + UNIQUE_CIS_CONN_HANDLE(leaudio_group_id, 1), + dataPathDirIsEq(bluetooth::hci::iso_manager::kIsoDataPathDirectionOut))) + .Times(1); + EXPECT_CALL(ase_ctp_handler, AseCtpReceiverStartReadyHandler(lastDevice, _, _, _)).Times(1); } InjectInitialIdleNotification(group); // Start the configuration and stream Conversational content - LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)}); + LeAudioGroupStateMachine::Get()->StartStream(group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)}); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); testing::Mock::VerifyAndClearExpectations(mock_iso_manager_); // Verify data path removal on the second bidirectional CIS EXPECT_CALL( - *mock_iso_manager_, - RemoveIsoDataPath( - UNIQUE_CIS_CONN_HANDLE(leaudio_group_id, 1), - bluetooth::hci::iso_manager::kRemoveIsoDataPathDirectionOutput | - bluetooth::hci::iso_manager::kRemoveIsoDataPathDirectionInput)) - .Times(1); + *mock_iso_manager_, + RemoveIsoDataPath(UNIQUE_CIS_CONN_HANDLE(leaudio_group_id, 1), + bluetooth::hci::iso_manager::kRemoveIsoDataPathDirectionOutput | + bluetooth::hci::iso_manager::kRemoveIsoDataPathDirectionInput)) + .Times(1); // Inject CIS and ACL disconnection of first device InjectCisDisconnected(group, lastDevice, HCI_ERR_CONNECTION_TOUT); @@ -7062,63 +6451,53 @@ TEST_F(StateMachineTest, testAttachDeviceToTheConversationalStream) { testing::Mock::VerifyAndClearExpectations(mock_iso_manager_); // Check if group keeps streaming - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); lastDevice->conn_id_ = 3; lastDevice->SetConnectionState(DeviceConnectState::CONNECTED); // Make sure ASE with disconnected CIS are not left in STREAMING - ASSERT_EQ(lastDevice->GetFirstAseWithState( - ::bluetooth::le_audio::types::kLeAudioDirectionSink, - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING), + ASSERT_EQ(lastDevice->GetFirstAseWithState(::bluetooth::le_audio::types::kLeAudioDirectionSink, + types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING), nullptr); - ASSERT_EQ(lastDevice->GetFirstAseWithState( - ::bluetooth::le_audio::types::kLeAudioDirectionSource, - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING), + ASSERT_EQ(lastDevice->GetFirstAseWithState(::bluetooth::le_audio::types::kLeAudioDirectionSource, + types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING), nullptr); - EXPECT_CALL(gatt_queue, WriteCharacteristic(lastDevice->conn_id_, - lastDevice->ctp_hdls_.val_hdl, _, - GATT_WRITE_NO_RSP, _, _)) - .Times(AtLeast(3)); + EXPECT_CALL(gatt_queue, WriteCharacteristic(lastDevice->conn_id_, lastDevice->ctp_hdls_.val_hdl, + _, GATT_WRITE_NO_RSP, _, _)) + .Times(AtLeast(3)); EXPECT_CALL(*mock_iso_manager_, EstablishCis(_)).Times(1); EXPECT_CALL(*mock_iso_manager_, SetupIsoDataPath( - _, dataPathDirIsEq( - bluetooth::hci::iso_manager::kIsoDataPathDirectionIn))) - .Times(1); + _, dataPathDirIsEq(bluetooth::hci::iso_manager::kIsoDataPathDirectionIn))) + .Times(1); // Make sure the Out data path is set before we declare that we are ready { ::testing::InSequence seq; EXPECT_CALL(*mock_iso_manager_, SetupIsoDataPath( - UNIQUE_CIS_CONN_HANDLE(leaudio_group_id, 1), - dataPathDirIsEq( - bluetooth::hci::iso_manager::kIsoDataPathDirectionOut))) - .Times(1); - EXPECT_CALL(ase_ctp_handler, - AseCtpReceiverStartReadyHandler(lastDevice, _, _, _)) - .Times(1); + UNIQUE_CIS_CONN_HANDLE(leaudio_group_id, 1), + dataPathDirIsEq(bluetooth::hci::iso_manager::kIsoDataPathDirectionOut))) + .Times(1); + EXPECT_CALL(ase_ctp_handler, AseCtpReceiverStartReadyHandler(lastDevice, _, _, _)).Times(1); } - LeAudioGroupStateMachine::Get()->AttachToStream( - group, lastDevice, {.sink = {call_ccid}, .source = {call_ccid}}); + LeAudioGroupStateMachine::Get()->AttachToStream(group, lastDevice, + {.sink = {call_ccid}, .source = {call_ccid}}); // Check if group keeps streaming - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); // Verify that the joining device receives the right CCID list auto lastMeta = lastDevice->GetFirstActiveAse()->metadata; bool parsedOk = false; - auto ltv = bluetooth::le_audio::types::LeAudioLtvMap::Parse( - lastMeta.data(), lastMeta.size(), parsedOk); + auto ltv = bluetooth::le_audio::types::LeAudioLtvMap::Parse(lastMeta.data(), lastMeta.size(), + parsedOk); ASSERT_TRUE(parsedOk); - auto ccids = - ltv.Find(bluetooth::le_audio::types::kLeAudioMetadataTypeCcidList); + auto ccids = ltv.Find(bluetooth::le_audio::types::kLeAudioMetadataTypeCcidList); ASSERT_TRUE(ccids.has_value()); ASSERT_NE(std::find(ccids->begin(), ccids->end(), call_ccid), ccids->end()); @@ -7129,7 +6508,7 @@ TEST_F(StateMachineTest, testAttachDeviceToTheConversationalStream) { // Make sure ASEs with reconnected CIS are in STREAMING state ASSERT_TRUE(lastDevice->HaveAllActiveAsesSameState( - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING)); + types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING)); } TEST_F(StateMachineTest, StartStreamAfterConfigure) { @@ -7140,8 +6519,7 @@ TEST_F(StateMachineTest, StartStreamAfterConfigure) { ContentControlIdKeeper::GetInstance()->SetCcid(media_context, media_ccid); // Prepare multiple fake connected devices in a group - auto* group = - PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); ASSERT_EQ(group->Size(), num_devices); PrepareConfigureCodecHandler(group, 0, true); @@ -7161,10 +6539,9 @@ TEST_F(StateMachineTest, StartStreamAfterConfigure) { * 3: Enabling */ EXPECT_CALL(gatt_queue, - WriteCharacteristic(leAudioDevice->conn_id_, - leAudioDevice->ctp_hdls_.val_hdl, _, + WriteCharacteristic(leAudioDevice->conn_id_, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) - .Times(3); + .Times(3); expected_devices_written++; leAudioDevice = group->GetNextDevice(leAudioDevice); } @@ -7172,31 +6549,26 @@ TEST_F(StateMachineTest, StartStreamAfterConfigure) { // Validate GroupStreamStatus EXPECT_CALL(mock_callbacks_, - StatusReportCb( - leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::CONFIGURED_BY_USER)); + StatusReportCb(leaudio_group_id, + bluetooth::le_audio::GroupStreamStatus::CONFIGURED_BY_USER)); // Start the configuration and stream Media content group->SetPendingConfiguration(); - LeAudioGroupStateMachine::Get()->ConfigureStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)}); + LeAudioGroupStateMachine::Get()->ConfigureStream(group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)}); testing::Mock::VerifyAndClearExpectations(&mock_callbacks_); group->ClearPendingConfiguration(); // Validate GroupStreamStatus - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::STREAMING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::STREAMING)); // Start the configuration and stream Media content - LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)}); + LeAudioGroupStateMachine::Get()->StartStream(group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)}); testing::Mock::VerifyAndClearExpectations(&mock_callbacks_); } @@ -7209,8 +6581,7 @@ TEST_F(StateMachineTest, StartStreamCachedConfig) { ContentControlIdKeeper::GetInstance()->SetCcid(media_context, media_ccid); // Prepare multiple fake connected devices in a group - auto* group = - PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); ASSERT_EQ(group->Size(), num_devices); PrepareConfigureCodecHandler(group, 0, true); @@ -7231,26 +6602,22 @@ TEST_F(StateMachineTest, StartStreamCachedConfig) { * 4: Release (1) */ EXPECT_CALL(gatt_queue, - WriteCharacteristic(leAudioDevice->conn_id_, - leAudioDevice->ctp_hdls_.val_hdl, _, + WriteCharacteristic(leAudioDevice->conn_id_, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) - .Times(6); + .Times(6); expected_devices_written++; leAudioDevice = group->GetNextDevice(leAudioDevice); } ASSERT_EQ(expected_devices_written, num_devices); // Validate GroupStreamStatus - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::STREAMING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::STREAMING)); // Start the configuration and stream Media content - LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)}); + LeAudioGroupStateMachine::Get()->StartStream(group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)}); testing::Mock::VerifyAndClearExpectations(&mock_callbacks_); @@ -7258,16 +6625,12 @@ TEST_F(StateMachineTest, StartStreamCachedConfig) { reset_mock_function_count_map(); // Validate GroupStreamStatus - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::RELEASING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::RELEASING)); - EXPECT_CALL( - mock_callbacks_, - StatusReportCb( - leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::CONFIGURED_AUTONOMOUS)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, + bluetooth::le_audio::GroupStreamStatus::CONFIGURED_AUTONOMOUS)); // Start the configuration and stream Media content LeAudioGroupStateMachine::Get()->StopStream(group); @@ -7277,16 +6640,13 @@ TEST_F(StateMachineTest, StartStreamCachedConfig) { reset_mock_function_count_map(); // Restart stream - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::STREAMING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::STREAMING)); // Start the configuration and stream Media content - LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)}); + LeAudioGroupStateMachine::Get()->StartStream(group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)}); testing::Mock::VerifyAndClearExpectations(&mock_callbacks_); ASSERT_EQ(1, get_func_call_count("alarm_cancel")); @@ -7296,8 +6656,7 @@ TEST_F(StateMachineTest, StartStreamCachedConfigReconfigInvalidBehavior) { const auto context_type = kContextTypeConversational; const auto leaudio_group_id = 6; const auto num_devices = 1; - channel_count_ = kLeAudioCodecChannelCountSingleChannel | - kLeAudioCodecChannelCountTwoChannel; + channel_count_ = kLeAudioCodecChannelCountSingleChannel | kLeAudioCodecChannelCountTwoChannel; /* Scenario * 1. Start stream and stop stream so ASEs stays in Configured State @@ -7310,8 +6669,7 @@ TEST_F(StateMachineTest, StartStreamCachedConfigReconfigInvalidBehavior) { ContentControlIdKeeper::GetInstance()->SetCcid(call_context, call_ccid); // Prepare multiple fake connected devices in a group - auto* group = - PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); ASSERT_EQ(group->Size(), num_devices); PrepareConfigureCodecHandler(group, 0, true); @@ -7324,18 +6682,15 @@ TEST_F(StateMachineTest, StartStreamCachedConfigReconfigInvalidBehavior) { InjectInitialIdleNotification(group); // Validate GroupStreamStatus - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::STREAMING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::STREAMING)); EXPECT_CALL(*mock_iso_manager_, CreateCig).Times(1); // Start the configuration and stream call content - LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)}); + LeAudioGroupStateMachine::Get()->StartStream(group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)}); testing::Mock::VerifyAndClearExpectations(&mock_callbacks_); @@ -7343,16 +6698,12 @@ TEST_F(StateMachineTest, StartStreamCachedConfigReconfigInvalidBehavior) { reset_mock_function_count_map(); // Validate GroupStreamStatus - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::RELEASING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::RELEASING)); - EXPECT_CALL( - mock_callbacks_, - StatusReportCb( - leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::CONFIGURED_AUTONOMOUS)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, + bluetooth::le_audio::GroupStreamStatus::CONFIGURED_AUTONOMOUS)); // Start the configuration and stream Media content LeAudioGroupStateMachine::Get()->StopStream(group); @@ -7367,22 +6718,21 @@ TEST_F(StateMachineTest, StartStreamCachedConfigReconfigInvalidBehavior) { auto device = group->GetFirstDevice(); int i = 0; for (auto& ase : device->ases_) { - if (i++ == 0) continue; + if (i++ == 0) { + continue; + } // Simulate autonomus release for one ASE - InjectAseStateNotification(&ase, device, group, ascs::kAseStateReleasing, - nullptr); + InjectAseStateNotification(&ase, device, group, ascs::kAseStateReleasing, nullptr); } // Restart stream and expect it will not be created. EXPECT_CALL(mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::STREAMING)) - .Times(0); + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::STREAMING)) + .Times(0); EXPECT_CALL(mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::RELEASING)) - .Times(0); + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::RELEASING)) + .Times(0); EXPECT_CALL(*mock_iso_manager_, CreateCig(_, _)).Times(0); @@ -7391,9 +6741,9 @@ TEST_F(StateMachineTest, StartStreamCachedConfigReconfigInvalidBehavior) { // Start the configuration and stream Live content bool result = LeAudioGroupStateMachine::Get()->StartStream( - group, kContextTypeLive, - {.sink = types::AudioContexts(kContextTypeLive), - .source = types::AudioContexts(kContextTypeLive)}); + group, kContextTypeLive, + {.sink = types::AudioContexts(kContextTypeLive), + .source = types::AudioContexts(kContextTypeLive)}); // Group internally in releasing state. StartStrean should faile. @@ -7408,8 +6758,7 @@ TEST_F(StateMachineTest, BoundedHeadphonesConversationalToMediaChannelCount_2) { const auto new_context_type = kContextTypeMedia; const auto leaudio_group_id = 6; const auto num_devices = 1; - channel_count_ = kLeAudioCodecChannelCountSingleChannel | - kLeAudioCodecChannelCountTwoChannel; + channel_count_ = kLeAudioCodecChannelCountSingleChannel | kLeAudioCodecChannelCountTwoChannel; sample_freq_ |= codec_specific::kCapSamplingFrequency48000Hz | codec_specific::kCapSamplingFrequency32000Hz; @@ -7420,9 +6769,8 @@ TEST_F(StateMachineTest, BoundedHeadphonesConversationalToMediaChannelCount_2) { ContentControlIdKeeper::GetInstance()->SetCcid(call_context, call_ccid); // Prepare multiple fake connected devices in a group - auto* group = PrepareSingleTestDeviceGroup( - leaudio_group_id, initial_context_type, num_devices, - kContextTypeConversational | kContextTypeMedia); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, initial_context_type, num_devices, + kContextTypeConversational | kContextTypeMedia); ASSERT_EQ(group->Size(), num_devices); PrepareConfigureCodecHandler(group, 0, true); @@ -7445,26 +6793,23 @@ TEST_F(StateMachineTest, BoundedHeadphonesConversationalToMediaChannelCount_2) { * 5: Release */ EXPECT_CALL(gatt_queue, - WriteCharacteristic(leAudioDevice->conn_id_, - leAudioDevice->ctp_hdls_.val_hdl, _, + WriteCharacteristic(leAudioDevice->conn_id_, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) - .Times(8); + .Times(8); expected_devices_written++; leAudioDevice = group->GetNextDevice(leAudioDevice); } ASSERT_EQ(expected_devices_written, num_devices); // Validate GroupStreamStatus - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::STREAMING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::STREAMING)); // Start the configuration and stream Media content LeAudioGroupStateMachine::Get()->StartStream( - group, initial_context_type, - {.sink = types::AudioContexts(initial_context_type), - .source = types::AudioContexts(initial_context_type)}); + group, initial_context_type, + {.sink = types::AudioContexts(initial_context_type), + .source = types::AudioContexts(initial_context_type)}); testing::Mock::VerifyAndClearExpectations(&mock_callbacks_); @@ -7474,32 +6819,25 @@ TEST_F(StateMachineTest, BoundedHeadphonesConversationalToMediaChannelCount_2) { ASSERT_EQ(1lu, current_config->confs.source.size()); // Validate GroupStreamStatus - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::RELEASING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::RELEASING)); - EXPECT_CALL( - mock_callbacks_, - StatusReportCb( - leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::CONFIGURED_AUTONOMOUS)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, + bluetooth::le_audio::GroupStreamStatus::CONFIGURED_AUTONOMOUS)); // Start the configuration and stream Media content LeAudioGroupStateMachine::Get()->StopStream(group); testing::Mock::VerifyAndClearExpectations(&mock_callbacks_); // Restart stream - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::STREAMING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::STREAMING)); // Start the configuration and stream Media content - LeAudioGroupStateMachine::Get()->StartStream( - group, new_context_type, - {.sink = types::AudioContexts(new_context_type), - .source = types::AudioContexts(new_context_type)}); + LeAudioGroupStateMachine::Get()->StartStream(group, new_context_type, + {.sink = types::AudioContexts(new_context_type), + .source = types::AudioContexts(new_context_type)}); testing::Mock::VerifyAndClearExpectations(&mock_callbacks_); @@ -7509,15 +6847,13 @@ TEST_F(StateMachineTest, BoundedHeadphonesConversationalToMediaChannelCount_2) { ASSERT_EQ(0lu, current_config->confs.source.size()); } -TEST_F(StateMachineTest, - BoundedHeadphonesConversationalToMediaChannelCount_1_MonoMic) { +TEST_F(StateMachineTest, BoundedHeadphonesConversationalToMediaChannelCount_1_MonoMic) { const auto initial_context_type = kContextTypeConversational; const auto new_context_type = kContextTypeMedia; const auto leaudio_group_id = 6; const auto num_devices = 1; // Single audio allocation for the mono source - channel_allocations_source_ = - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; + channel_allocations_source_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; channel_count_ = kLeAudioCodecChannelCountSingleChannel; sample_freq_ |= codec_specific::kCapSamplingFrequency48000Hz | @@ -7529,9 +6865,8 @@ TEST_F(StateMachineTest, ContentControlIdKeeper::GetInstance()->SetCcid(call_context, call_ccid); // Prepare one fake connected devices in a group - auto* group = PrepareSingleTestDeviceGroup( - leaudio_group_id, initial_context_type, num_devices, - kContextTypeConversational | kContextTypeMedia); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, initial_context_type, num_devices, + kContextTypeConversational | kContextTypeMedia); ASSERT_EQ(group->Size(), num_devices); // Cannot verify here as we will change the number of ases on reconfigure @@ -7555,26 +6890,23 @@ TEST_F(StateMachineTest, * 5: Release */ EXPECT_CALL(gatt_queue, - WriteCharacteristic(leAudioDevice->conn_id_, - leAudioDevice->ctp_hdls_.val_hdl, _, + WriteCharacteristic(leAudioDevice->conn_id_, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) - .Times(8); + .Times(8); expected_devices_written++; leAudioDevice = group->GetNextDevice(leAudioDevice); } ASSERT_EQ(expected_devices_written, num_devices); // Validate GroupStreamStatus - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::STREAMING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::STREAMING)); // Start the configuration and stream Media content LeAudioGroupStateMachine::Get()->StartStream( - group, initial_context_type, - {.sink = types::AudioContexts(initial_context_type), - .source = types::AudioContexts(initial_context_type)}); + group, initial_context_type, + {.sink = types::AudioContexts(initial_context_type), + .source = types::AudioContexts(initial_context_type)}); testing::Mock::VerifyAndClearExpectations(&mock_callbacks_); @@ -7589,16 +6921,12 @@ TEST_F(StateMachineTest, reset_mock_function_count_map(); // Validate GroupStreamStatus - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::RELEASING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::RELEASING)); - EXPECT_CALL( - mock_callbacks_, - StatusReportCb( - leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::CONFIGURED_AUTONOMOUS)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, + bluetooth::le_audio::GroupStreamStatus::CONFIGURED_AUTONOMOUS)); // Start the configuration and stream Media content LeAudioGroupStateMachine::Get()->StopStream(group); @@ -7607,16 +6935,13 @@ TEST_F(StateMachineTest, reset_mock_function_count_map(); // Restart stream - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::STREAMING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::STREAMING)); // Start the configuration and stream Media content - LeAudioGroupStateMachine::Get()->StartStream( - group, new_context_type, - {.sink = types::AudioContexts(new_context_type), - .source = types::AudioContexts(new_context_type)}); + LeAudioGroupStateMachine::Get()->StartStream(group, new_context_type, + {.sink = types::AudioContexts(new_context_type), + .source = types::AudioContexts(new_context_type)}); testing::Mock::VerifyAndClearExpectations(&mock_callbacks_); ASSERT_EQ(1, get_func_call_count("alarm_cancel")); @@ -7627,16 +6952,13 @@ TEST_F(StateMachineTest, ASSERT_EQ(0lu, current_config->confs.source.size()); } -TEST_F( - StateMachineTest, - DISABLED_BoundedHeadphonesConversationalToMediaChannelCount_1_StereoMic) { +TEST_F(StateMachineTest, DISABLED_BoundedHeadphonesConversationalToMediaChannelCount_1_StereoMic) { const auto initial_context_type = kContextTypeConversational; const auto new_context_type = kContextTypeMedia; const auto leaudio_group_id = 6; const auto num_devices = 1; - channel_allocations_source_ = - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft | - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight; + channel_allocations_source_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft | + ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight; channel_count_ = kLeAudioCodecChannelCountSingleChannel; sample_freq_ |= codec_specific::kCapSamplingFrequency48000Hz | @@ -7648,9 +6970,8 @@ TEST_F( ContentControlIdKeeper::GetInstance()->SetCcid(call_context, call_ccid); // Prepare one fake connected devices in a group - auto* group = PrepareSingleTestDeviceGroup( - leaudio_group_id, initial_context_type, num_devices, - kContextTypeConversational | kContextTypeMedia); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, initial_context_type, num_devices, + kContextTypeConversational | kContextTypeMedia); ASSERT_EQ(group->Size(), num_devices); // Cannot verify here as we will change the number of ases on reconfigure @@ -7674,26 +6995,23 @@ TEST_F( * 5: Release */ EXPECT_CALL(gatt_queue, - WriteCharacteristic(leAudioDevice->conn_id_, - leAudioDevice->ctp_hdls_.val_hdl, _, + WriteCharacteristic(leAudioDevice->conn_id_, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) - .Times(8); + .Times(8); expected_devices_written++; leAudioDevice = group->GetNextDevice(leAudioDevice); } ASSERT_EQ(expected_devices_written, num_devices); // Validate GroupStreamStatus - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::STREAMING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::STREAMING)); // Start the configuration and stream Media content LeAudioGroupStateMachine::Get()->StartStream( - group, initial_context_type, - {.sink = types::AudioContexts(initial_context_type), - .source = types::AudioContexts(initial_context_type)}); + group, initial_context_type, + {.sink = types::AudioContexts(initial_context_type), + .source = types::AudioContexts(initial_context_type)}); testing::Mock::VerifyAndClearExpectations(&mock_callbacks_); @@ -7706,16 +7024,12 @@ TEST_F( ASSERT_EQ(2lu, current_config->confs.source.size()); // Validate GroupStreamStatus - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::RELEASING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::RELEASING)); - EXPECT_CALL( - mock_callbacks_, - StatusReportCb( - leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::CONFIGURED_AUTONOMOUS)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, + bluetooth::le_audio::GroupStreamStatus::CONFIGURED_AUTONOMOUS)); // Start the configuration and stream Media content LeAudioGroupStateMachine::Get()->StopStream(group); @@ -7724,16 +7038,13 @@ TEST_F( reset_mock_function_count_map(); // Restart stream - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::STREAMING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::STREAMING)); // Start the configuration and stream Media content - LeAudioGroupStateMachine::Get()->StartStream( - group, new_context_type, - {.sink = types::AudioContexts(new_context_type), - .source = types::AudioContexts(new_context_type)}); + LeAudioGroupStateMachine::Get()->StartStream(group, new_context_type, + {.sink = types::AudioContexts(new_context_type), + .source = types::AudioContexts(new_context_type)}); testing::Mock::VerifyAndClearExpectations(&mock_callbacks_); ASSERT_EQ(1, get_func_call_count("alarm_cancel")); @@ -7752,8 +7063,7 @@ TEST_F(StateMachineTest, lateCisDisconnectedEvent_DuringReconfiguration) { ContentControlIdKeeper::GetInstance()->SetCcid(media_context, media_ccid); // Prepare multiple fake connected devices in a group - auto* group = - PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); ASSERT_EQ(group->Size(), num_devices); PrepareConfigureCodecHandler(group, 0, true); @@ -7770,10 +7080,10 @@ TEST_F(StateMachineTest, lateCisDisconnectedEvent_DuringReconfiguration) { * 2: Codec QoS * 3: Enabling */ - EXPECT_CALL(gatt_queue, WriteCharacteristic(leAudioDevice->conn_id_, - leAudioDevice->ctp_hdls_.val_hdl, - _, GATT_WRITE_NO_RSP, _, _)) - .Times(AtLeast(3)); + EXPECT_CALL(gatt_queue, + WriteCharacteristic(leAudioDevice->conn_id_, leAudioDevice->ctp_hdls_.val_hdl, _, + GATT_WRITE_NO_RSP, _, _)) + .Times(AtLeast(3)); expected_devices_written++; ASSERT_EQ(expected_devices_written, num_devices); @@ -7785,14 +7095,12 @@ TEST_F(StateMachineTest, lateCisDisconnectedEvent_DuringReconfiguration) { InjectInitialIdleNotification(group); // Start the configuration and stream Media content - LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)}); + LeAudioGroupStateMachine::Get()->StartStream(group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)}); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); testing::Mock::VerifyAndClearExpectations(mock_iso_manager_); ASSERT_EQ(1, get_func_call_count("alarm_cancel")); @@ -7805,28 +7113,22 @@ TEST_F(StateMachineTest, lateCisDisconnectedEvent_DuringReconfiguration) { group->SetPendingConfiguration(); // Validate GroupStreamStatus - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::RELEASING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::RELEASING)); - EXPECT_CALL( - mock_callbacks_, - StatusReportCb( - leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::CONFIGURED_AUTONOMOUS)) - .Times(0); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, + bluetooth::le_audio::GroupStreamStatus::CONFIGURED_AUTONOMOUS)) + .Times(0); LeAudioGroupStateMachine::Get()->StopStream(group); testing::Mock::VerifyAndClearExpectations(&mock_callbacks_); ASSERT_EQ(0, get_func_call_count("alarm_cancel")); - EXPECT_CALL( - mock_callbacks_, - StatusReportCb( - leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::CONFIGURED_AUTONOMOUS)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, + bluetooth::le_audio::GroupStreamStatus::CONFIGURED_AUTONOMOUS)); // Inject CIS and ACL disconnection of first device InjectCisDisconnected(group, leAudioDevice, HCI_ERR_CONN_CAUSE_LOCAL_HOST); @@ -7842,8 +7144,7 @@ TEST_F(StateMachineTest, lateCisDisconnectedEvent_AutonomousConfigured) { ContentControlIdKeeper::GetInstance()->SetCcid(media_context, media_ccid); // Prepare multiple fake connected devices in a group - auto* group = - PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); ASSERT_EQ(group->Size(), num_devices); PrepareConfigureCodecHandler(group, 0, true); @@ -7860,10 +7161,10 @@ TEST_F(StateMachineTest, lateCisDisconnectedEvent_AutonomousConfigured) { * 2: Codec QoS * 3: Enabling */ - EXPECT_CALL(gatt_queue, WriteCharacteristic(leAudioDevice->conn_id_, - leAudioDevice->ctp_hdls_.val_hdl, - _, GATT_WRITE_NO_RSP, _, _)) - .Times(AtLeast(3)); + EXPECT_CALL(gatt_queue, + WriteCharacteristic(leAudioDevice->conn_id_, leAudioDevice->ctp_hdls_.val_hdl, _, + GATT_WRITE_NO_RSP, _, _)) + .Times(AtLeast(3)); expected_devices_written++; ASSERT_EQ(expected_devices_written, num_devices); @@ -7875,14 +7176,12 @@ TEST_F(StateMachineTest, lateCisDisconnectedEvent_AutonomousConfigured) { InjectInitialIdleNotification(group); // Start the configuration and stream Media content - LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)}); + LeAudioGroupStateMachine::Get()->StartStream(group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)}); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); testing::Mock::VerifyAndClearExpectations(mock_iso_manager_); ASSERT_EQ(1, get_func_call_count("alarm_cancel")); @@ -7892,34 +7191,27 @@ TEST_F(StateMachineTest, lateCisDisconnectedEvent_AutonomousConfigured) { ON_CALL(*mock_iso_manager_, DisconnectCis).WillByDefault(Return()); // Validate GroupStreamStatus - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::RELEASING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::RELEASING)); - EXPECT_CALL( - mock_callbacks_, - StatusReportCb( - leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::CONFIGURED_AUTONOMOUS)) - .Times(0); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, + bluetooth::le_audio::GroupStreamStatus::CONFIGURED_AUTONOMOUS)) + .Times(0); // Stop the stream LeAudioGroupStateMachine::Get()->StopStream(group); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED); testing::Mock::VerifyAndClearExpectations(&mock_callbacks_); ASSERT_EQ(0, get_func_call_count("alarm_cancel")); - EXPECT_CALL( - mock_callbacks_, - StatusReportCb( - leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::CONFIGURED_AUTONOMOUS)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, + bluetooth::le_audio::GroupStreamStatus::CONFIGURED_AUTONOMOUS)); // Inject CIS and ACL disconnection of first device InjectCisDisconnected(group, leAudioDevice, HCI_ERR_CONN_CAUSE_LOCAL_HOST); @@ -7935,8 +7227,7 @@ TEST_F(StateMachineTest, lateCisDisconnectedEvent_Idle) { ContentControlIdKeeper::GetInstance()->SetCcid(media_context, media_ccid); // Prepare multiple fake connected devices in a group - auto* group = - PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); ASSERT_EQ(group->Size(), num_devices); PrepareConfigureCodecHandler(group); @@ -7953,10 +7244,10 @@ TEST_F(StateMachineTest, lateCisDisconnectedEvent_Idle) { * 2: Codec QoS * 3: Enabling */ - EXPECT_CALL(gatt_queue, WriteCharacteristic(leAudioDevice->conn_id_, - leAudioDevice->ctp_hdls_.val_hdl, - _, GATT_WRITE_NO_RSP, _, _)) - .Times(AtLeast(3)); + EXPECT_CALL(gatt_queue, + WriteCharacteristic(leAudioDevice->conn_id_, leAudioDevice->ctp_hdls_.val_hdl, _, + GATT_WRITE_NO_RSP, _, _)) + .Times(AtLeast(3)); expected_devices_written++; ASSERT_EQ(expected_devices_written, num_devices); @@ -7968,14 +7259,12 @@ TEST_F(StateMachineTest, lateCisDisconnectedEvent_Idle) { InjectInitialIdleNotification(group); // Start the configuration and stream Media content - LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)}); + LeAudioGroupStateMachine::Get()->StartStream(group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)}); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); testing::Mock::VerifyAndClearExpectations(mock_iso_manager_); ASSERT_EQ(1, get_func_call_count("alarm_cancel")); @@ -7984,15 +7273,12 @@ TEST_F(StateMachineTest, lateCisDisconnectedEvent_Idle) { ON_CALL(*mock_iso_manager_, DisconnectCis).WillByDefault(Return()); // Validate GroupStreamStatus - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::RELEASING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::RELEASING)); EXPECT_CALL(mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::IDLE)) - .Times(0); + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::IDLE)) + .Times(0); // Stop the stream LeAudioGroupStateMachine::Get()->StopStream(group); @@ -8004,8 +7290,7 @@ TEST_F(StateMachineTest, lateCisDisconnectedEvent_Idle) { testing::Mock::VerifyAndClearExpectations(&mock_callbacks_); EXPECT_CALL(mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::IDLE)); + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::IDLE)); // Inject CIS and ACL disconnection of first device InjectCisDisconnected(group, leAudioDevice, HCI_ERR_CONN_CAUSE_LOCAL_HOST); @@ -8019,9 +7304,8 @@ TEST_F(StateMachineTest, StreamReconfigureAfterCisLostTwoDevices) { const auto num_devices = 2; // Prepare multiple fake connected devices in a group - auto* group = PrepareSingleTestDeviceGroup( - leaudio_group_id, context_type, num_devices, - kContextTypeConversational | kContextTypeMedia); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices, + kContextTypeConversational | kContextTypeMedia); ASSERT_EQ(group->Size(), num_devices); PrepareConfigureCodecHandler(group); @@ -8043,31 +7327,27 @@ TEST_F(StateMachineTest, StreamReconfigureAfterCisLostTwoDevices) { auto expected_devices_written = 0; while (leAudioDevice) { EXPECT_CALL(gatt_queue, - WriteCharacteristic(leAudioDevice->conn_id_, - leAudioDevice->ctp_hdls_.val_hdl, _, + WriteCharacteristic(leAudioDevice->conn_id_, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) - .Times(3); + .Times(3); expected_devices_written++; leAudioDevice = group->GetNextDevice(leAudioDevice); } ASSERT_EQ(expected_devices_written, num_devices); // Validate GroupStreamStatus - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::STREAMING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::STREAMING)); // Start the configuration and stream Media content context_type = kContextTypeMedia; ASSERT_TRUE(LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)})); + group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)})); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); ASSERT_EQ(1, get_func_call_count("alarm_cancel")); testing::Mock::VerifyAndClearExpectations(mock_iso_manager_); testing::Mock::VerifyAndClearExpectations(&gatt_queue); @@ -8084,8 +7364,7 @@ TEST_F(StateMachineTest, StreamReconfigureAfterCisLostTwoDevices) { while (leAudioDevice) { InjectCisDisconnected(group, leAudioDevice, HCI_ERR_CONN_CAUSE_LOCAL_HOST); // Disconnect device - LeAudioGroupStateMachine::Get()->ProcessHciNotifAclDisconnected( - group, leAudioDevice); + LeAudioGroupStateMachine::Get()->ProcessHciNotifAclDisconnected(group, leAudioDevice); leAudioDevice = group->GetNextDevice(leAudioDevice); } @@ -8111,31 +7390,27 @@ TEST_F(StateMachineTest, StreamReconfigureAfterCisLostTwoDevices) { expected_devices_written = 0; while (leAudioDevice) { EXPECT_CALL(gatt_queue, - WriteCharacteristic(leAudioDevice->conn_id_, - leAudioDevice->ctp_hdls_.val_hdl, _, + WriteCharacteristic(leAudioDevice->conn_id_, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) - .Times(4); + .Times(4); expected_devices_written++; leAudioDevice = group->GetNextDevice(leAudioDevice); } ASSERT_EQ(expected_devices_written, num_devices); // Validate GroupStreamStatus - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::STREAMING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::STREAMING)); // Start the configuration and stream Conversational content context_type = kContextTypeConversational; ASSERT_TRUE(LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)})); + group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)})); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); ASSERT_EQ(2, get_func_call_count("alarm_cancel")); testing::Mock::VerifyAndClearExpectations(mock_iso_manager_); testing::Mock::VerifyAndClearExpectations(&gatt_queue); @@ -8155,9 +7430,8 @@ TEST_F(StateMachineTest, StreamClearAfterReleaseAndConnectionTimeout) { */ // Prepare multiple fake connected devices in a group - auto* group = PrepareSingleTestDeviceGroup( - leaudio_group_id, context_type, num_devices, - kContextTypeConversational | kContextTypeMedia); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices, + kContextTypeConversational | kContextTypeMedia); ASSERT_EQ(group->Size(), num_devices); PrepareConfigureCodecHandler(group); @@ -8183,31 +7457,25 @@ TEST_F(StateMachineTest, StreamClearAfterReleaseAndConnectionTimeout) { } // Validate GroupStreamStatus - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::STREAMING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::STREAMING)); // Start the configuration and stream Media content context_type = kContextTypeMedia; ASSERT_TRUE(LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)})); + group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)})); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); ASSERT_EQ(1, get_func_call_count("alarm_cancel")); testing::Mock::VerifyAndClearExpectations(&mock_callbacks_); - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::RELEASING)); EXPECT_CALL(mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::IDLE)); + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::RELEASING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::IDLE)); /* Prepare release handler only for first device. */ PrepareReleaseHandler(group, 0, false, firstDevice); @@ -8230,8 +7498,7 @@ TEST_F(StateMachineTest, VerifyThereIsNoDoubleDataPathRemoval) { const auto num_devices = 1; /* Symulate banded headphonse */ - channel_count_ = kLeAudioCodecChannelCountSingleChannel | - kLeAudioCodecChannelCountTwoChannel; + channel_count_ = kLeAudioCodecChannelCountSingleChannel | kLeAudioCodecChannelCountTwoChannel; /* Scenario 1. Phone call to 1 device @@ -8241,9 +7508,8 @@ TEST_F(StateMachineTest, VerifyThereIsNoDoubleDataPathRemoval) { */ // Prepare multiple fake connected devices in a group - auto* group = PrepareSingleTestDeviceGroup( - leaudio_group_id, context_type, num_devices, - kContextTypeConversational | kContextTypeMedia); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices, + kContextTypeConversational | kContextTypeMedia); ASSERT_EQ(group->Size(), num_devices); PrepareConfigureCodecHandler(group); @@ -8264,26 +7530,21 @@ TEST_F(StateMachineTest, VerifyThereIsNoDoubleDataPathRemoval) { InjectInitialIdleNotification(group); // Validate GroupStreamStatus - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::STREAMING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::STREAMING)); ASSERT_TRUE(LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)})); + group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)})); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); ASSERT_EQ(1, get_func_call_count("alarm_cancel")); testing::Mock::VerifyAndClearExpectations(&mock_callbacks_); - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::RELEASING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::RELEASING)); /* Do not trigger any action on removeIsoData path.*/ ON_CALL(*mock_iso_manager_, RemoveIsoDataPath).WillByDefault(Return()); @@ -8302,9 +7563,8 @@ TEST_F(StateMachineTest, StreamStartWithDifferentContextFromConfiguredState) { ContentControlIdKeeper::GetInstance()->SetCcid(media_context, media_ccid); // Prepare multiple fake connected devices in a group - auto* group = PrepareSingleTestDeviceGroup( - leaudio_group_id, context_type, num_devices, - kContextTypeConversational | kContextTypeMedia); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices, + kContextTypeConversational | kContextTypeMedia); ASSERT_EQ(group->Size(), num_devices); PrepareConfigureCodecHandler(group, 0, true); @@ -8325,10 +7585,9 @@ TEST_F(StateMachineTest, StreamStartWithDifferentContextFromConfiguredState) { * 3: Enabling */ EXPECT_CALL(gatt_queue, - WriteCharacteristic(leAudioDevice->conn_id_, - leAudioDevice->ctp_hdls_.val_hdl, _, + WriteCharacteristic(leAudioDevice->conn_id_, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) - .Times(4); + .Times(4); expected_devices_written++; leAudioDevice = group->GetNextDevice(leAudioDevice); } @@ -8336,38 +7595,32 @@ TEST_F(StateMachineTest, StreamStartWithDifferentContextFromConfiguredState) { // Validate GroupStreamStatus EXPECT_CALL(mock_callbacks_, - StatusReportCb( - leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::CONFIGURED_BY_USER)); + StatusReportCb(leaudio_group_id, + bluetooth::le_audio::GroupStreamStatus::CONFIGURED_BY_USER)); // Start the configuration and stream Media content group->SetPendingConfiguration(); - LeAudioGroupStateMachine::Get()->ConfigureStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)}); + LeAudioGroupStateMachine::Get()->ConfigureStream(group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)}); testing::Mock::VerifyAndClearExpectations(&mock_callbacks_); group->ClearPendingConfiguration(); // Validate GroupStreamStatus - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::STREAMING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::STREAMING)); context_type = kContextTypeMedia; // Start the configuration and stream Media content - LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)}); + LeAudioGroupStateMachine::Get()->StartStream(group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)}); testing::Mock::VerifyAndClearExpectations(&mock_callbacks_); } -TEST_F(StateMachineTest, - StreamStartWithSameContextFromConfiguredStateButNewMetadata) { +TEST_F(StateMachineTest, StreamStartWithSameContextFromConfiguredStateButNewMetadata) { auto context_type = kContextTypeConversational; const auto leaudio_group_id = 6; const auto num_devices = 2; @@ -8375,9 +7628,8 @@ TEST_F(StateMachineTest, ContentControlIdKeeper::GetInstance()->SetCcid(media_context, media_ccid); // Prepare multiple fake connected devices in a group - auto* group = PrepareSingleTestDeviceGroup( - leaudio_group_id, context_type, num_devices, - kContextTypeConversational | kContextTypeLive); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices, + kContextTypeConversational | kContextTypeLive); ASSERT_EQ(group->Size(), num_devices); PrepareConfigureCodecHandler(group, 0, true); @@ -8399,10 +7651,9 @@ TEST_F(StateMachineTest, * 3: Enabling */ EXPECT_CALL(gatt_queue, - WriteCharacteristic(leAudioDevice->conn_id_, - leAudioDevice->ctp_hdls_.val_hdl, _, + WriteCharacteristic(leAudioDevice->conn_id_, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) - .Times(4); + .Times(4); expected_devices_written++; leAudioDevice = group->GetNextDevice(leAudioDevice); } @@ -8410,48 +7661,43 @@ TEST_F(StateMachineTest, // Validate GroupStreamStatus EXPECT_CALL(mock_callbacks_, - StatusReportCb( - leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::CONFIGURED_BY_USER)); + StatusReportCb(leaudio_group_id, + bluetooth::le_audio::GroupStreamStatus::CONFIGURED_BY_USER)); // Start the configuration and stream Media content group->SetPendingConfiguration(); - LeAudioGroupStateMachine::Get()->ConfigureStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)}); + LeAudioGroupStateMachine::Get()->ConfigureStream(group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)}); testing::Mock::VerifyAndClearExpectations(&mock_callbacks_); group->ClearPendingConfiguration(); // Validate GroupStreamStatus - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::STREAMING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::STREAMING)); auto metadata_context_type = kContextTypeLive; - types::BidirectionalPair> ccid_lists = { - .sink = {media_ccid}, .source = {media_ccid}}; + types::BidirectionalPair> ccid_lists = {.sink = {media_ccid}, + .source = {media_ccid}}; // Start the configuration and stream Media content LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(metadata_context_type), - .source = types::AudioContexts(metadata_context_type)}, - ccid_lists); + group, context_type, + {.sink = types::AudioContexts(metadata_context_type), + .source = types::AudioContexts(metadata_context_type)}, + ccid_lists); testing::Mock::VerifyAndClearExpectations(&mock_callbacks_); // Verify that the joining device receives the right CCID list auto lastMeta = firstActiveDevice->GetFirstActiveAse()->metadata; bool parsedOk = false; - auto ltv = bluetooth::le_audio::types::LeAudioLtvMap::Parse( - lastMeta.data(), lastMeta.size(), parsedOk); + auto ltv = bluetooth::le_audio::types::LeAudioLtvMap::Parse(lastMeta.data(), lastMeta.size(), + parsedOk); ASSERT_TRUE(parsedOk); - auto ccids = - ltv.Find(bluetooth::le_audio::types::kLeAudioMetadataTypeCcidList); + auto ccids = ltv.Find(bluetooth::le_audio::types::kLeAudioMetadataTypeCcidList); ASSERT_TRUE(ccids.has_value()); ASSERT_NE(std::find(ccids->begin(), ccids->end(), media_ccid), ccids->end()); } @@ -8464,8 +7710,7 @@ TEST_F(StateMachineTest, testAttachDeviceToTheStreamCisFailure) { ContentControlIdKeeper::GetInstance()->SetCcid(media_context, media_ccid); // Prepare multiple fake connected devices in a group - auto* group = - PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); ASSERT_EQ(group->Size(), num_devices); PrepareConfigureCodecHandler(group); @@ -8487,10 +7732,9 @@ TEST_F(StateMachineTest, testAttachDeviceToTheStreamCisFailure) { */ lastDevice = leAudioDevice; EXPECT_CALL(gatt_queue, - WriteCharacteristic(leAudioDevice->conn_id_, - leAudioDevice->ctp_hdls_.val_hdl, _, + WriteCharacteristic(leAudioDevice->conn_id_, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) - .Times(AtLeast(3)); + .Times(AtLeast(3)); expected_devices_written++; leAudioDevice = group->GetNextDevice(leAudioDevice); } @@ -8503,14 +7747,12 @@ TEST_F(StateMachineTest, testAttachDeviceToTheStreamCisFailure) { InjectInitialIdleNotification(group); // Start the configuration and stream Media content - LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)}); + LeAudioGroupStateMachine::Get()->StartStream(group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)}); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); testing::Mock::VerifyAndClearExpectations(mock_iso_manager_); // Inject CIS and ACL disconnection of first device @@ -8518,47 +7760,41 @@ TEST_F(StateMachineTest, testAttachDeviceToTheStreamCisFailure) { InjectAclDisconnected(group, lastDevice); // Check if group keeps streaming - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); lastDevice->conn_id_ = 3; lastDevice->SetConnectionState(DeviceConnectState::CONNECTED); // Make sure ASE with disconnected CIS are not left in STREAMING - ASSERT_EQ(lastDevice->GetFirstAseWithState( - ::bluetooth::le_audio::types::kLeAudioDirectionSink, - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING), + ASSERT_EQ(lastDevice->GetFirstAseWithState(::bluetooth::le_audio::types::kLeAudioDirectionSink, + types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING), nullptr); - ASSERT_EQ(lastDevice->GetFirstAseWithState( - ::bluetooth::le_audio::types::kLeAudioDirectionSource, - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING), + ASSERT_EQ(lastDevice->GetFirstAseWithState(::bluetooth::le_audio::types::kLeAudioDirectionSource, + types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING), nullptr); - EXPECT_CALL(gatt_queue, WriteCharacteristic(lastDevice->conn_id_, - lastDevice->ctp_hdls_.val_hdl, _, - GATT_WRITE_NO_RSP, _, _)) - .Times(AtLeast(3)); + EXPECT_CALL(gatt_queue, WriteCharacteristic(lastDevice->conn_id_, lastDevice->ctp_hdls_.val_hdl, + _, GATT_WRITE_NO_RSP, _, _)) + .Times(AtLeast(3)); do_not_send_cis_establish_event_ = true; EXPECT_CALL(*mock_iso_manager_, EstablishCis(_)).Times(1); EXPECT_CALL(*mock_iso_manager_, SetupIsoDataPath(_, _)).Times(0); - LeAudioGroupStateMachine::Get()->AttachToStream( - group, lastDevice, {.sink = {media_ccid}, .source = {}}); + LeAudioGroupStateMachine::Get()->AttachToStream(group, lastDevice, + {.sink = {media_ccid}, .source = {}}); // Check if group keeps streaming - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); // Verify that the joining device receives the right CCID list auto lastMeta = lastDevice->GetFirstActiveAse()->metadata; bool parsedOk = false; - auto ltv = bluetooth::le_audio::types::LeAudioLtvMap::Parse( - lastMeta.data(), lastMeta.size(), parsedOk); + auto ltv = bluetooth::le_audio::types::LeAudioLtvMap::Parse(lastMeta.data(), lastMeta.size(), + parsedOk); ASSERT_TRUE(parsedOk); - auto ccids = - ltv.Find(bluetooth::le_audio::types::kLeAudioMetadataTypeCcidList); + auto ccids = ltv.Find(bluetooth::le_audio::types::kLeAudioMetadataTypeCcidList); ASSERT_TRUE(ccids.has_value()); ASSERT_NE(std::find(ccids->begin(), ccids->end(), media_ccid), ccids->end()); @@ -8576,8 +7812,7 @@ TEST_F(StateMachineTest, testAttachDeviceWhileSecondDeviceDisconnects) { ContentControlIdKeeper::GetInstance()->SetCcid(media_context, media_ccid); // Prepare multiple fake connected devices in a group - auto* group = - PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); ASSERT_EQ(group->Size(), num_devices); PrepareConfigureCodecHandler(group); @@ -8599,10 +7834,9 @@ TEST_F(StateMachineTest, testAttachDeviceWhileSecondDeviceDisconnects) { */ lastDevice = leAudioDevice; EXPECT_CALL(gatt_queue, - WriteCharacteristic(leAudioDevice->conn_id_, - leAudioDevice->ctp_hdls_.val_hdl, _, + WriteCharacteristic(leAudioDevice->conn_id_, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) - .Times(AtLeast(3)); + .Times(AtLeast(3)); expected_devices_written++; leAudioDevice = group->GetNextDevice(leAudioDevice); } @@ -8615,14 +7849,12 @@ TEST_F(StateMachineTest, testAttachDeviceWhileSecondDeviceDisconnects) { InjectInitialIdleNotification(group); // Start the configuration and stream Media content - LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)}); + LeAudioGroupStateMachine::Get()->StartStream(group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)}); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); testing::Mock::VerifyAndClearExpectations(mock_iso_manager_); // Inject CIS and ACL disconnection of first device @@ -8632,28 +7864,24 @@ TEST_F(StateMachineTest, testAttachDeviceWhileSecondDeviceDisconnects) { log::info(" Device B - Disconnected "); // Check if group keeps streaming - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); // Set second device is connected now. lastDevice->conn_id_ = 3; lastDevice->SetConnectionState(DeviceConnectState::CONNECTED); // Make sure ASE with disconnected CIS are not left in STREAMING - ASSERT_EQ(lastDevice->GetFirstAseWithState( - ::bluetooth::le_audio::types::kLeAudioDirectionSink, - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING), + ASSERT_EQ(lastDevice->GetFirstAseWithState(::bluetooth::le_audio::types::kLeAudioDirectionSink, + types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING), nullptr); - ASSERT_EQ(lastDevice->GetFirstAseWithState( - ::bluetooth::le_audio::types::kLeAudioDirectionSource, - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING), + ASSERT_EQ(lastDevice->GetFirstAseWithState(::bluetooth::le_audio::types::kLeAudioDirectionSource, + types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING), nullptr); // Expect just Codec Configure on ASCS Control Point - EXPECT_CALL(gatt_queue, WriteCharacteristic(lastDevice->conn_id_, - lastDevice->ctp_hdls_.val_hdl, _, - GATT_WRITE_NO_RSP, _, _)) - .Times(AtLeast(1)); + EXPECT_CALL(gatt_queue, WriteCharacteristic(lastDevice->conn_id_, lastDevice->ctp_hdls_.val_hdl, + _, GATT_WRITE_NO_RSP, _, _)) + .Times(AtLeast(1)); EXPECT_CALL(*mock_iso_manager_, EstablishCis(_)).Times(0); EXPECT_CALL(*mock_iso_manager_, SetupIsoDataPath(_, _)).Times(0); @@ -8664,12 +7892,11 @@ TEST_F(StateMachineTest, testAttachDeviceWhileSecondDeviceDisconnects) { log::info("Device B - Attaching to the stream"); - LeAudioGroupStateMachine::Get()->AttachToStream( - group, lastDevice, {.sink = {media_ccid}, .source = {}}); + LeAudioGroupStateMachine::Get()->AttachToStream(group, lastDevice, + {.sink = {media_ccid}, .source = {}}); // Check if group keeps streaming - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); /* Verify that ASE of first device are still good*/ auto ase = firstDevice->GetFirstActiveAse(); @@ -8679,26 +7906,23 @@ TEST_F(StateMachineTest, testAttachDeviceWhileSecondDeviceDisconnects) { testing::Mock::VerifyAndClearExpectations(mock_iso_manager_); testing::Mock::VerifyAndClearExpectations(&gatt_queue); - log::info( - "Device A is disconnecting while Device B is attaching to the stream"); + log::info("Device A is disconnecting while Device B is attaching to the stream"); InjectCisDisconnected(group, firstDevice, HCI_ERR_CONNECTION_TOUT); InjectReleasingAndIdleState(group, firstDevice); // Check if group keeps streaming ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_IDLE); - ASSERT_EQ(group->GetTargetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetTargetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); ASSERT_EQ(group->cig.GetState(), types::CigState::CREATED); log::info("Device B continues configuration and streaming"); // Expect QoS config and Enable on ASCS Control Point - EXPECT_CALL(gatt_queue, WriteCharacteristic(lastDevice->conn_id_, - lastDevice->ctp_hdls_.val_hdl, _, - GATT_WRITE_NO_RSP, _, _)) - .Times(AtLeast(2)); + EXPECT_CALL(gatt_queue, WriteCharacteristic(lastDevice->conn_id_, lastDevice->ctp_hdls_.val_hdl, + _, GATT_WRITE_NO_RSP, _, _)) + .Times(AtLeast(2)); EXPECT_CALL(*mock_iso_manager_, EstablishCis(_)).Times(1); EXPECT_CALL(*mock_iso_manager_, SetupIsoDataPath(_, _)).Times(1); @@ -8706,8 +7930,7 @@ TEST_F(StateMachineTest, testAttachDeviceWhileSecondDeviceDisconnects) { InjectCachedConfigurationForActiveAses(group, lastDevice); // Check if group keeps streaming - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); testing::Mock::VerifyAndClearExpectations(mock_iso_manager_); testing::Mock::VerifyAndClearExpectations(&gatt_queue); @@ -8721,8 +7944,7 @@ TEST_F(StateMachineTest, testAclDropWithoutApriorCisDisconnection) { ContentControlIdKeeper::GetInstance()->SetCcid(media_context, media_ccid); // Prepare multiple fake connected devices in a group - auto* group = - PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); ASSERT_EQ(group->Size(), num_devices); PrepareConfigureCodecHandler(group); @@ -8744,10 +7966,9 @@ TEST_F(StateMachineTest, testAclDropWithoutApriorCisDisconnection) { */ lastDevice = leAudioDevice; EXPECT_CALL(gatt_queue, - WriteCharacteristic(leAudioDevice->conn_id_, - leAudioDevice->ctp_hdls_.val_hdl, _, + WriteCharacteristic(leAudioDevice->conn_id_, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) - .Times(AtLeast(3)); + .Times(AtLeast(3)); expected_devices_written++; leAudioDevice = group->GetNextDevice(leAudioDevice); } @@ -8760,14 +7981,12 @@ TEST_F(StateMachineTest, testAclDropWithoutApriorCisDisconnection) { InjectInitialIdleNotification(group); // Start the configuration and stream Media content - LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)}); + LeAudioGroupStateMachine::Get()->StartStream(group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)}); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); testing::Mock::VerifyAndClearExpectations(mock_iso_manager_); /* Separate CIS for dual CIS device is treated as sink device */ @@ -8784,9 +8003,7 @@ TEST_F(StateMachineTest, testAclDropWithoutApriorCisDisconnection) { ASSERT_EQ(group->stream_conf.stream_params.sink.num_of_channels, 0); } -TEST_F( - StateMachineTest, - testAutonomousDisableOneDeviceAndGoBackToStream_CisDisconnectedOnDisable) { +TEST_F(StateMachineTest, testAutonomousDisableOneDeviceAndGoBackToStream_CisDisconnectedOnDisable) { const auto context_type = kContextTypeConversational; const auto leaudio_group_id = 6; const auto num_devices = 2; @@ -8794,8 +8011,7 @@ TEST_F( ContentControlIdKeeper::GetInstance()->SetCcid(media_context, media_ccid); // Prepare multiple fake connected devices in a group - auto* group = - PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); ASSERT_EQ(group->Size(), num_devices); PrepareConfigureCodecHandler(group); @@ -8819,10 +8035,9 @@ TEST_F( */ lastDevice = leAudioDevice; EXPECT_CALL(gatt_queue, - WriteCharacteristic(leAudioDevice->conn_id_, - leAudioDevice->ctp_hdls_.val_hdl, _, + WriteCharacteristic(leAudioDevice->conn_id_, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) - .Times(AtLeast(3)); + .Times(AtLeast(3)); expected_devices_written++; leAudioDevice = group->GetNextDevice(leAudioDevice); } @@ -8835,17 +8050,15 @@ TEST_F( InjectInitialIdleNotification(group); // Start the configuration and stream Conversational content - LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)}); + LeAudioGroupStateMachine::Get()->StartStream(group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)}); /* First timer started for transition to streaming state */ ASSERT_EQ(1, get_func_call_count("alarm_set_on_mloop")); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); testing::Mock::VerifyAndClearExpectations(mock_iso_manager_); @@ -8858,11 +8071,10 @@ TEST_F( /* Remote initiates autonomous Disable operation */ auto ase = lastDevice->GetFirstActiveAseByDirection( - ::bluetooth::le_audio::types::kLeAudioDirectionSink); + ::bluetooth::le_audio::types::kLeAudioDirectionSink); log::info(" Inject ASE state changed to QoS for {} ", lastDevice->address_); - InjectAseStateNotification(ase, lastDevice, group, - ascs::kAseStateQoSConfigured, + InjectAseStateNotification(ase, lastDevice, group, ascs::kAseStateQoSConfigured, &cached_qos_configuration_map_[ase->id]); /* No action on timer in this moment. */ @@ -8873,8 +8085,7 @@ TEST_F( InjectCisDisconnected(group, lastDevice, HCI_ERR_PEER_USER); /* First device keeps streaming */ - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); testing::Mock::VerifyAndClearExpectations(mock_iso_manager_); testing::Mock::VerifyAndClearExpectations(&gatt_queue); @@ -8882,18 +8093,16 @@ TEST_F( /* Now lets try to attach the device back to the stream (Enabling and Receiver * Start ready to be called)*/ - EXPECT_CALL(gatt_queue, WriteCharacteristic(lastDevice->conn_id_, - firstDevice->ctp_hdls_.val_hdl, _, - GATT_WRITE_NO_RSP, _, _)) - .Times(2); + EXPECT_CALL(gatt_queue, WriteCharacteristic(lastDevice->conn_id_, firstDevice->ctp_hdls_.val_hdl, + _, GATT_WRITE_NO_RSP, _, _)) + .Times(2); EXPECT_CALL(*mock_iso_manager_, EstablishCis(_)).Times(1); EXPECT_CALL(*mock_iso_manager_, SetupIsoDataPath(_, _)).Times(2); - log::info(" Attach {} to the stream, need to establish CIS", - lastDevice->address_); - LeAudioGroupStateMachine::Get()->AttachToStream( - group, lastDevice, {.sink = {media_ccid}, .source = {}}); + log::info(" Attach {} to the stream, need to establish CIS", lastDevice->address_); + LeAudioGroupStateMachine::Get()->AttachToStream(group, lastDevice, + {.sink = {media_ccid}, .source = {}}); testing::Mock::VerifyAndClearExpectations(mock_iso_manager_); testing::Mock::VerifyAndClearExpectations(&gatt_queue); @@ -8902,8 +8111,7 @@ TEST_F( ASSERT_EQ(ase->state, types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); } -TEST_F(StateMachineTest, - testAutonomousDisableOneDeviceAndGoBackToStream_CisConnectedOnDisable) { +TEST_F(StateMachineTest, testAutonomousDisableOneDeviceAndGoBackToStream_CisConnectedOnDisable) { const auto context_type = kContextTypeConversational; const auto leaudio_group_id = 6; const auto num_devices = 2; @@ -8911,8 +8119,7 @@ TEST_F(StateMachineTest, ContentControlIdKeeper::GetInstance()->SetCcid(media_context, media_ccid); // Prepare multiple fake connected devices in a group - auto* group = - PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); ASSERT_EQ(group->Size(), num_devices); PrepareConfigureCodecHandler(group); @@ -8936,10 +8143,9 @@ TEST_F(StateMachineTest, */ lastDevice = leAudioDevice; EXPECT_CALL(gatt_queue, - WriteCharacteristic(leAudioDevice->conn_id_, - leAudioDevice->ctp_hdls_.val_hdl, _, + WriteCharacteristic(leAudioDevice->conn_id_, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) - .Times(AtLeast(3)); + .Times(AtLeast(3)); expected_devices_written++; leAudioDevice = group->GetNextDevice(leAudioDevice); } @@ -8952,17 +8158,15 @@ TEST_F(StateMachineTest, InjectInitialIdleNotification(group); // Start the configuration and stream Conversational content - LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)}); + LeAudioGroupStateMachine::Get()->StartStream(group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)}); /* First timer started for transition to streaming state */ ASSERT_EQ(1, get_func_call_count("alarm_set_on_mloop")); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); testing::Mock::VerifyAndClearExpectations(mock_iso_manager_); @@ -8975,7 +8179,7 @@ TEST_F(StateMachineTest, /* Remote initiates autonomous Disable operation */ auto ase = lastDevice->GetFirstActiveAseByDirection( - ::bluetooth::le_audio::types::kLeAudioDirectionSink); + ::bluetooth::le_audio::types::kLeAudioDirectionSink); log::info(" Inject ASE state changed to QoS for {} ", lastDevice->address_); InjectQoSConfigurationForActiveAses(group, lastDevice); @@ -8984,8 +8188,7 @@ TEST_F(StateMachineTest, ASSERT_EQ(1, get_func_call_count("alarm_set_on_mloop")); /* First device keeps streaming */ - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); testing::Mock::VerifyAndClearExpectations(mock_iso_manager_); testing::Mock::VerifyAndClearExpectations(&gatt_queue); @@ -8999,18 +8202,16 @@ TEST_F(StateMachineTest, /* Now lets try to attach the device back to the stream (Enabling and Receiver * Start ready to be called)*/ - EXPECT_CALL(gatt_queue, WriteCharacteristic(lastDevice->conn_id_, - firstDevice->ctp_hdls_.val_hdl, _, - GATT_WRITE_NO_RSP, _, _)) - .Times(2); + EXPECT_CALL(gatt_queue, WriteCharacteristic(lastDevice->conn_id_, firstDevice->ctp_hdls_.val_hdl, + _, GATT_WRITE_NO_RSP, _, _)) + .Times(2); EXPECT_CALL(*mock_iso_manager_, EstablishCis(_)).Times(0); EXPECT_CALL(*mock_iso_manager_, SetupIsoDataPath(_, _)).Times(0); - log::info(" Attach {} to the stream, need to establish CIS", - lastDevice->address_); - LeAudioGroupStateMachine::Get()->AttachToStream( - group, lastDevice, {.sink = {media_ccid}, .source = {}}); + log::info(" Attach {} to the stream, need to establish CIS", lastDevice->address_); + LeAudioGroupStateMachine::Get()->AttachToStream(group, lastDevice, + {.sink = {media_ccid}, .source = {}}); testing::Mock::VerifyAndClearExpectations(mock_iso_manager_); testing::Mock::VerifyAndClearExpectations(&gatt_queue); @@ -9028,8 +8229,7 @@ TEST_F(StateMachineTest, testAutonomousDisable_GoToIdle) { ContentControlIdKeeper::GetInstance()->SetCcid(media_context, media_ccid); // Prepare multiple fake connected devices in a group - auto* group = - PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); + auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices); ASSERT_EQ(group->Size(), num_devices); PrepareConfigureCodecHandler(group); @@ -9052,10 +8252,9 @@ TEST_F(StateMachineTest, testAutonomousDisable_GoToIdle) { */ lastDevice = leAudioDevice; EXPECT_CALL(gatt_queue, - WriteCharacteristic(leAudioDevice->conn_id_, - leAudioDevice->ctp_hdls_.val_hdl, _, + WriteCharacteristic(leAudioDevice->conn_id_, leAudioDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) - .Times(AtLeast(3)); + .Times(AtLeast(3)); expected_devices_written++; leAudioDevice = group->GetNextDevice(leAudioDevice); } @@ -9067,16 +8266,13 @@ TEST_F(StateMachineTest, testAutonomousDisable_GoToIdle) { InjectInitialIdleNotification(group); - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::STREAMING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::STREAMING)); // Start the configuration and stream Conversational content - LeAudioGroupStateMachine::Get()->StartStream( - group, context_type, - {.sink = types::AudioContexts(context_type), - .source = types::AudioContexts(context_type)}); + LeAudioGroupStateMachine::Get()->StartStream(group, context_type, + {.sink = types::AudioContexts(context_type), + .source = types::AudioContexts(context_type)}); testing::Mock::VerifyAndClearExpectations(&mock_callbacks_); @@ -9086,8 +8282,7 @@ TEST_F(StateMachineTest, testAutonomousDisable_GoToIdle) { ASSERT_EQ(1, get_func_call_count("alarm_set_on_mloop")); // Check if group has transitioned to a proper state - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); testing::Mock::VerifyAndClearExpectations(mock_iso_manager_); @@ -9099,37 +8294,31 @@ TEST_F(StateMachineTest, testAutonomousDisable_GoToIdle) { InjectQoSConfigurationForActiveAses(group, lastDevice); // Check if group still streaming - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); - log::info("{} in QoS configured state, disconnect CIS ", - lastDevice->address_); + log::info("{} in QoS configured state, disconnect CIS ", lastDevice->address_); // Validate GroupStreamStatus or maybe update CIS should be called - /* Inject CIS disconnection of first device, disconenct only first CIS because + /* Inject CIS disconnection of first device, disconnect only first CIS because * while processing first disconnection test will try to bring up this ASEs * to STREAMING state and connect CISes again. */ InjectCisDisconnected(group, lastDevice, HCI_ERR_CONNECTION_TOUT, true); // Check if group still streaming - ASSERT_EQ(group->GetState(), - types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); + ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING); log::info("{} in QoS configured state ", lastDevice->address_); testing::Mock::VerifyAndClearExpectations(mock_iso_manager_); log::info(" device {} also goes to QoS state ", firstDevice->address_); - EXPECT_CALL( - mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::RELEASING)); + EXPECT_CALL(mock_callbacks_, + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::RELEASING)); EXPECT_CALL(mock_callbacks_, - StatusReportCb(leaudio_group_id, - bluetooth::le_audio::GroupStreamStatus::IDLE)); + StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::IDLE)); EXPECT_CALL(*mock_iso_manager_, DisconnectCis(_, _)).Times(1); EXPECT_CALL(*mock_iso_manager_, RemoveIsoDataPath(_, _)).Times(1); diff --git a/system/bta/le_audio/storage_helper.cc b/system/bta/le_audio/storage_helper.cc index 8ad74bf0570..92f85e37d42 100644 --- a/system/bta/le_audio/storage_helper.cc +++ b/system/bta/le_audio/storage_helper.cc @@ -34,41 +34,33 @@ static constexpr uint8_t LEAUDIO_ASE_STORAGE_CURRENT_LAYOUT_MAGIC = 0x00; static constexpr uint8_t LEAUDIO_HANDLES_STORAGE_CURRENT_LAYOUT_MAGIC = 0x00; static constexpr uint8_t LEAUDIO_CODEC_ID_SZ = 5; -static constexpr size_t LEAUDIO_STORAGE_MAGIC_SZ = - sizeof(uint8_t) /* magic is always uint8_t */; +static constexpr size_t LEAUDIO_STORAGE_MAGIC_SZ = sizeof(uint8_t) /* magic is always uint8_t */; static constexpr size_t LEAUDIO_STORAGE_HEADER_WITH_ENTRIES_SZ = - LEAUDIO_STORAGE_MAGIC_SZ + sizeof(uint8_t); /* num_of_entries */ + LEAUDIO_STORAGE_MAGIC_SZ + sizeof(uint8_t); /* num_of_entries */ static constexpr size_t LEAUDIO_PACS_ENTRY_HDR_SZ = - sizeof(uint16_t) /*handle*/ + sizeof(uint16_t) /*ccc handle*/ + - sizeof(uint8_t) /* number of pack records in single characteristic */; + sizeof(uint16_t) /*handle*/ + sizeof(uint16_t) /*ccc handle*/ + + sizeof(uint8_t) /* number of pack records in single characteristic */; static constexpr size_t LEAUDIO_PACS_ENTRY_SZ = - sizeof(uint8_t) /* size of single pac record */ + - LEAUDIO_CODEC_ID_SZ /*codec id*/ + - sizeof(uint8_t) /*codec capabilities len*/ + - sizeof(uint8_t) /*metadata len*/; + sizeof(uint8_t) /* size of single pac record */ + LEAUDIO_CODEC_ID_SZ /*codec id*/ + + sizeof(uint8_t) /*codec capabilities len*/ + sizeof(uint8_t) /*metadata len*/; static constexpr size_t LEAUDIO_ASES_ENTRY_SZ = - sizeof(uint16_t) /*handle*/ + sizeof(uint16_t) /*ccc handle*/ + - sizeof(uint8_t) /*direction*/ + sizeof(uint8_t) /*ase id*/; + sizeof(uint16_t) /*handle*/ + sizeof(uint16_t) /*ccc handle*/ + + sizeof(uint8_t) /*direction*/ + sizeof(uint8_t) /*ase id*/; static constexpr size_t LEAUDIO_STORAGE_HANDLES_ENTRIES_SZ = - LEAUDIO_STORAGE_MAGIC_SZ + sizeof(uint16_t) /*control point handle*/ + - sizeof(uint16_t) /*ccc handle*/ + - sizeof(uint16_t) /*sink audio location handle*/ + - sizeof(uint16_t) /*ccc handle*/ + - sizeof(uint16_t) /*source audio location handle*/ + - sizeof(uint16_t) /*ccc handle*/ + - sizeof(uint16_t) /*supported context type handle*/ + - sizeof(uint16_t) /*ccc handle*/ + - sizeof(uint16_t) /*available context type handle*/ + - sizeof(uint16_t) /*ccc handle*/ + sizeof(uint16_t) /* tmas handle */; - -bool serializePacs( - const bluetooth::le_audio::types::PublishedAudioCapabilities& pacs, - std::vector& out) { + LEAUDIO_STORAGE_MAGIC_SZ + sizeof(uint16_t) /*control point handle*/ + + sizeof(uint16_t) /*ccc handle*/ + sizeof(uint16_t) /*sink audio location handle*/ + + sizeof(uint16_t) /*ccc handle*/ + sizeof(uint16_t) /*source audio location handle*/ + + sizeof(uint16_t) /*ccc handle*/ + sizeof(uint16_t) /*supported context type handle*/ + + sizeof(uint16_t) /*ccc handle*/ + sizeof(uint16_t) /*available context type handle*/ + + sizeof(uint16_t) /*ccc handle*/ + sizeof(uint16_t) /* tmas handle */; + +bool serializePacs(const bluetooth::le_audio::types::PublishedAudioCapabilities& pacs, + std::vector& out) { auto num_of_pacs = pacs.size(); if (num_of_pacs == 0 || (num_of_pacs > std::numeric_limits::max())) { log::warn("No pacs available"); @@ -104,13 +96,12 @@ bool serializePacs( UINT16_TO_STREAM(ptr, ccc_handle); UINT8_TO_STREAM(ptr, pac_recs.size()); - log::verbose("Handle: 0x{:04x}, ccc handle: 0x{:04x}, pac count: {}", - handle, ccc_handle, static_cast(pac_recs.size())); + log::verbose("Handle: 0x{:04x}, ccc handle: 0x{:04x}, pac count: {}", handle, ccc_handle, + static_cast(pac_recs.size())); for (const auto& pac : pac_recs) { /* Pac len */ - auto pac_len = LEAUDIO_PACS_ENTRY_SZ + pac.codec_spec_caps_raw.size() + - pac.metadata.size(); + auto pac_len = LEAUDIO_PACS_ENTRY_SZ + pac.codec_spec_caps_raw.size() + pac.metadata.size(); log::verbose("Pac size {}", static_cast(pac_len)); UINT8_TO_STREAM(ptr, pac_len - 1 /* Minus size */); @@ -120,8 +111,7 @@ bool serializePacs( UINT16_TO_STREAM(ptr, pac.codec_id.vendor_codec_id); /* Codec caps */ - log::verbose("Codec capability size {}", - static_cast(pac.codec_spec_caps_raw.size())); + log::verbose("Codec capability size {}", static_cast(pac.codec_spec_caps_raw.size())); UINT8_TO_STREAM(ptr, pac.codec_spec_caps_raw.size()); if (pac.codec_spec_caps_raw.size() > 0) { ARRAY_TO_STREAM(ptr, pac.codec_spec_caps_raw.data(), @@ -145,30 +135,25 @@ bool SerializeSinkPacs(const bluetooth::le_audio::LeAudioDevice* leAudioDevice, log::warn("Skipping unknown device"); return false; } - log::verbose("Device {}, num of PAC characteristics: {}", - leAudioDevice->address_, + log::verbose("Device {}, num of PAC characteristics: {}", leAudioDevice->address_, static_cast(leAudioDevice->snk_pacs_.size())); return serializePacs(leAudioDevice->snk_pacs_, out); } -bool SerializeSourcePacs( - const bluetooth::le_audio::LeAudioDevice* leAudioDevice, - std::vector& out) { +bool SerializeSourcePacs(const bluetooth::le_audio::LeAudioDevice* leAudioDevice, + std::vector& out) { if (leAudioDevice == nullptr) { log::warn("Skipping unknown device"); return false; } - log::verbose("Device {}, num of PAC characteristics: {}", - leAudioDevice->address_, + log::verbose("Device {}, num of PAC characteristics: {}", leAudioDevice->address_, static_cast(leAudioDevice->src_pacs_.size())); return serializePacs(leAudioDevice->src_pacs_, out); } -bool deserializePacs(LeAudioDevice* leAudioDevice, - types::PublishedAudioCapabilities& pacs_db, +bool deserializePacs(LeAudioDevice* leAudioDevice, types::PublishedAudioCapabilities& pacs_db, const std::vector& in) { - if (in.size() < - LEAUDIO_STORAGE_HEADER_WITH_ENTRIES_SZ + LEAUDIO_PACS_ENTRY_SZ) { + if (in.size() < LEAUDIO_STORAGE_HEADER_WITH_ENTRIES_SZ + LEAUDIO_PACS_ENTRY_SZ) { log::warn("There is not single PACS stored"); return false; } @@ -180,18 +165,16 @@ bool deserializePacs(LeAudioDevice* leAudioDevice, if (magic != LEAUDIO_PACS_STORAGE_CURRENT_LAYOUT_MAGIC) { log::error("Invalid magic ({}!={}) for device {}", magic, - LEAUDIO_PACS_STORAGE_CURRENT_LAYOUT_MAGIC, - leAudioDevice->address_); + LEAUDIO_PACS_STORAGE_CURRENT_LAYOUT_MAGIC, leAudioDevice->address_); return false; } uint8_t num_of_pacs_chars; STREAM_TO_UINT8(num_of_pacs_chars, ptr); - if (in.size() < LEAUDIO_STORAGE_HEADER_WITH_ENTRIES_SZ + - (num_of_pacs_chars * LEAUDIO_PACS_ENTRY_SZ)) { - log::error("Invalid persistent storage data for device {}", - leAudioDevice->address_); + if (in.size() < + LEAUDIO_STORAGE_HEADER_WITH_ENTRIES_SZ + (num_of_pacs_chars * LEAUDIO_PACS_ENTRY_SZ)) { + log::error("Invalid persistent storage data for device {}", leAudioDevice->address_); return false; } @@ -204,17 +187,16 @@ bool deserializePacs(LeAudioDevice* leAudioDevice, STREAM_TO_UINT16(hdl_pair.ccc_hdl, ptr); STREAM_TO_UINT8(pac_count, ptr); - log::verbose("Handle: 0x{:04x}, ccc handle: 0x{:04x}, pac_count: {}", - hdl_pair.val_hdl, hdl_pair.ccc_hdl, pac_count); + log::verbose("Handle: 0x{:04x}, ccc handle: 0x{:04x}, pac_count: {}", hdl_pair.val_hdl, + hdl_pair.ccc_hdl, pac_count); pacs_db.push_back(std::make_tuple( - hdl_pair, - std::vector())); + hdl_pair, std::vector())); auto hdl = hdl_pair.val_hdl; - auto pac_tuple_iter = std::find_if( - pacs_db.begin(), pacs_db.end(), - [&hdl](auto& pac_ent) { return std::get<0>(pac_ent).val_hdl == hdl; }); + auto pac_tuple_iter = std::find_if(pacs_db.begin(), pacs_db.end(), [&hdl](auto& pac_ent) { + return std::get<0>(pac_ent).val_hdl == hdl; + }); std::vector pac_recs; while (pac_count--) { @@ -271,8 +253,7 @@ bool SerializeAses(const bluetooth::le_audio::LeAudioDevice* leAudioDevice, } /* Calculate the total size */ - auto ases_bin_size = LEAUDIO_STORAGE_HEADER_WITH_ENTRIES_SZ + - num_of_ases * LEAUDIO_ASES_ENTRY_SZ; + auto ases_bin_size = LEAUDIO_STORAGE_HEADER_WITH_ENTRIES_SZ + num_of_ases * LEAUDIO_ASES_ENTRY_SZ; out.resize(ases_bin_size); auto* ptr = out.data(); @@ -283,13 +264,9 @@ bool SerializeAses(const bluetooth::le_audio::LeAudioDevice* leAudioDevice, /* pacs entries */ for (const auto& ase : leAudioDevice->ases_) { log::verbose( - "Storing ASE ID: {}, direction {}, handle 0x{:04x}, ccc_handle " - "0x{:04x}", - ase.id, - ase.direction == bluetooth::le_audio::types::kLeAudioDirectionSink - ? "sink " - : "source", - ase.hdls.val_hdl, ase.hdls.ccc_hdl); + "Storing ASE ID: {}, direction {}, handle 0x{:04x}, ccc_handle 0x{:04x}", ase.id, + ase.direction == bluetooth::le_audio::types::kLeAudioDirectionSink ? "sink " : "source", + ase.hdls.val_hdl, ase.hdls.ccc_hdl); UINT16_TO_STREAM(ptr, ase.hdls.val_hdl); UINT16_TO_STREAM(ptr, ase.hdls.ccc_hdl); @@ -307,10 +284,8 @@ bool DeserializeAses(bluetooth::le_audio::LeAudioDevice* leAudioDevice, return false; } - if (in.size() < - LEAUDIO_STORAGE_HEADER_WITH_ENTRIES_SZ + LEAUDIO_ASES_ENTRY_SZ) { - log::warn("There is not single ASE stored for device {}", - leAudioDevice->address_); + if (in.size() < LEAUDIO_STORAGE_HEADER_WITH_ENTRIES_SZ + LEAUDIO_ASES_ENTRY_SZ) { + log::warn("There is not single ASE stored for device {}", leAudioDevice->address_); return false; } @@ -320,23 +295,19 @@ bool DeserializeAses(bluetooth::le_audio::LeAudioDevice* leAudioDevice, STREAM_TO_UINT8(magic, ptr); if (magic != LEAUDIO_ASE_STORAGE_CURRENT_LAYOUT_MAGIC) { - log::error("Invalid magic ({}!={}", magic, - LEAUDIO_PACS_STORAGE_CURRENT_LAYOUT_MAGIC); + log::error("Invalid magic ({}!={}", magic, LEAUDIO_PACS_STORAGE_CURRENT_LAYOUT_MAGIC); return false; } uint8_t num_of_ases; STREAM_TO_UINT8(num_of_ases, ptr); - if (in.size() < LEAUDIO_STORAGE_HEADER_WITH_ENTRIES_SZ + - (num_of_ases * LEAUDIO_ASES_ENTRY_SZ)) { - log::error("Invalid persistent storage data for device {}", - leAudioDevice->address_); + if (in.size() < LEAUDIO_STORAGE_HEADER_WITH_ENTRIES_SZ + (num_of_ases * LEAUDIO_ASES_ENTRY_SZ)) { + log::error("Invalid persistent storage data for device {}", leAudioDevice->address_); return false; } - log::debug("Loading {} Ases for device {}", num_of_ases, - leAudioDevice->address_); + log::debug("Loading {} Ases for device {}", num_of_ases, leAudioDevice->address_); /* sets entries */ while (num_of_ases--) { uint16_t handle; @@ -351,20 +322,15 @@ bool DeserializeAses(bluetooth::le_audio::LeAudioDevice* leAudioDevice, leAudioDevice->ases_.emplace_back(handle, ccc_handle, direction, ase_id); log::verbose( - "Loading ASE ID: {}, direction {}, handle 0x{:04x}, ccc_handle " - "0x{:04x}", - ase_id, - direction == bluetooth::le_audio::types::kLeAudioDirectionSink - ? "sink " - : "source", - handle, ccc_handle); + "Loading ASE ID: {}, direction {}, handle 0x{:04x}, ccc_handle 0x{:04x}", ase_id, + direction == bluetooth::le_audio::types::kLeAudioDirectionSink ? "sink " : "source", + handle, ccc_handle); } return true; } -bool SerializeHandles(const LeAudioDevice* leAudioDevice, - std::vector& out) { +bool SerializeHandles(const LeAudioDevice* leAudioDevice, std::vector& out) { if (leAudioDevice == nullptr) { log::warn("Skipping unknown device"); return false; @@ -377,10 +343,8 @@ bool SerializeHandles(const LeAudioDevice* leAudioDevice, /* header */ UINT8_TO_STREAM(ptr, LEAUDIO_HANDLES_STORAGE_CURRENT_LAYOUT_MAGIC); - if (leAudioDevice->ctp_hdls_.val_hdl == 0 || - leAudioDevice->ctp_hdls_.ccc_hdl == 0) { - log::warn("Invalid control point handles for device {}", - leAudioDevice->address_); + if (leAudioDevice->ctp_hdls_.val_hdl == 0 || leAudioDevice->ctp_hdls_.ccc_hdl == 0) { + log::warn("Invalid control point handles for device {}", leAudioDevice->address_); return false; } @@ -404,16 +368,14 @@ bool SerializeHandles(const LeAudioDevice* leAudioDevice, return true; } -bool DeserializeHandles(LeAudioDevice* leAudioDevice, - const std::vector& in) { +bool DeserializeHandles(LeAudioDevice* leAudioDevice, const std::vector& in) { if (leAudioDevice == nullptr) { log::warn("Skipping unknown device"); return false; } if (in.size() != LEAUDIO_STORAGE_HANDLES_ENTRIES_SZ) { - log::warn("There is not single ASE stored for device {}", - leAudioDevice->address_); + log::warn("There is not single ASE stored for device {}", leAudioDevice->address_); return false; } @@ -424,47 +386,41 @@ bool DeserializeHandles(LeAudioDevice* leAudioDevice, if (magic != LEAUDIO_HANDLES_STORAGE_CURRENT_LAYOUT_MAGIC) { log::error("Invalid magic ({}!={}) for device {}", magic, - LEAUDIO_PACS_STORAGE_CURRENT_LAYOUT_MAGIC, - leAudioDevice->address_); + LEAUDIO_PACS_STORAGE_CURRENT_LAYOUT_MAGIC, leAudioDevice->address_); return false; } STREAM_TO_UINT16(leAudioDevice->ctp_hdls_.val_hdl, ptr); STREAM_TO_UINT16(leAudioDevice->ctp_hdls_.ccc_hdl, ptr); - log::verbose("ctp.val_hdl: 0x{:04x}, ctp.ccc_hdl: 0x{:04x}", - leAudioDevice->ctp_hdls_.val_hdl, + log::verbose("ctp.val_hdl: 0x{:04x}, ctp.ccc_hdl: 0x{:04x}", leAudioDevice->ctp_hdls_.val_hdl, leAudioDevice->ctp_hdls_.ccc_hdl); STREAM_TO_UINT16(leAudioDevice->snk_audio_locations_hdls_.val_hdl, ptr); STREAM_TO_UINT16(leAudioDevice->snk_audio_locations_hdls_.ccc_hdl, ptr); log::verbose( - "snk_audio_locations_hdls_.val_hdl: " - "0x{:04x},snk_audio_locations_hdls_.ccc_hdl: 0x{:04x}", - leAudioDevice->snk_audio_locations_hdls_.val_hdl, - leAudioDevice->snk_audio_locations_hdls_.ccc_hdl); + "snk_audio_locations_hdls_.val_hdl: " + "0x{:04x},snk_audio_locations_hdls_.ccc_hdl: 0x{:04x}", + leAudioDevice->snk_audio_locations_hdls_.val_hdl, + leAudioDevice->snk_audio_locations_hdls_.ccc_hdl); STREAM_TO_UINT16(leAudioDevice->src_audio_locations_hdls_.val_hdl, ptr); STREAM_TO_UINT16(leAudioDevice->src_audio_locations_hdls_.ccc_hdl, ptr); log::verbose( - "src_audio_locations_hdls_.val_hdl: " - "0x{:04x},src_audio_locations_hdls_.ccc_hdl: 0x{:04x}", - leAudioDevice->src_audio_locations_hdls_.val_hdl, - leAudioDevice->src_audio_locations_hdls_.ccc_hdl); + "src_audio_locations_hdls_.val_hdl: " + "0x{:04x},src_audio_locations_hdls_.ccc_hdl: 0x{:04x}", + leAudioDevice->src_audio_locations_hdls_.val_hdl, + leAudioDevice->src_audio_locations_hdls_.ccc_hdl); STREAM_TO_UINT16(leAudioDevice->audio_supp_cont_hdls_.val_hdl, ptr); STREAM_TO_UINT16(leAudioDevice->audio_supp_cont_hdls_.ccc_hdl, ptr); - log::verbose( - "audio_supp_cont_hdls_.val_hdl: 0x{:04x},audio_supp_cont_hdls_.ccc_hdl: " - "0x{:04x}", - leAudioDevice->audio_supp_cont_hdls_.val_hdl, - leAudioDevice->audio_supp_cont_hdls_.ccc_hdl); + log::verbose("audio_supp_cont_hdls_.val_hdl: 0x{:04x},audio_supp_cont_hdls_.ccc_hdl: 0x{:04x}", + leAudioDevice->audio_supp_cont_hdls_.val_hdl, + leAudioDevice->audio_supp_cont_hdls_.ccc_hdl); STREAM_TO_UINT16(leAudioDevice->audio_avail_hdls_.val_hdl, ptr); STREAM_TO_UINT16(leAudioDevice->audio_avail_hdls_.ccc_hdl, ptr); - log::verbose( - "audio_avail_hdls_.val_hdl: 0x{:04x},audio_avail_hdls_.ccc_hdl: 0x{:04x}", - leAudioDevice->audio_avail_hdls_.val_hdl, - leAudioDevice->audio_avail_hdls_.ccc_hdl); + log::verbose("audio_avail_hdls_.val_hdl: 0x{:04x},audio_avail_hdls_.ccc_hdl: 0x{:04x}", + leAudioDevice->audio_avail_hdls_.val_hdl, leAudioDevice->audio_avail_hdls_.ccc_hdl); STREAM_TO_UINT16(leAudioDevice->tmap_role_hdl_, ptr); log::verbose("tmap_role_hdl_: 0x{:04x}", leAudioDevice->tmap_role_hdl_); diff --git a/system/bta/le_audio/storage_helper.h b/system/bta/le_audio/storage_helper.h index 71e51c7da29..0f196024f79 100644 --- a/system/bta/le_audio/storage_helper.h +++ b/system/bta/le_audio/storage_helper.h @@ -23,20 +23,12 @@ #include "devices.h" namespace bluetooth::le_audio { -bool SerializeSinkPacs(const LeAudioDevice* leAudioDevice, - std::vector& out); -bool DeserializeSinkPacs(LeAudioDevice* leAudioDevice, - const std::vector& in); -bool SerializeSourcePacs(const LeAudioDevice* leAudioDevice, - std::vector& out); -bool DeserializeSourcePacs(LeAudioDevice* leAudioDevice, - const std::vector& in); -bool SerializeAses(const LeAudioDevice* leAudioDevice, - std::vector& out); -bool DeserializeAses(LeAudioDevice* leAudioDevice, - const std::vector& in); -bool SerializeHandles(const LeAudioDevice* leAudioDevice, - std::vector& out); -bool DeserializeHandles(LeAudioDevice* leAudioDevice, - const std::vector& in); +bool SerializeSinkPacs(const LeAudioDevice* leAudioDevice, std::vector& out); +bool DeserializeSinkPacs(LeAudioDevice* leAudioDevice, const std::vector& in); +bool SerializeSourcePacs(const LeAudioDevice* leAudioDevice, std::vector& out); +bool DeserializeSourcePacs(LeAudioDevice* leAudioDevice, const std::vector& in); +bool SerializeAses(const LeAudioDevice* leAudioDevice, std::vector& out); +bool DeserializeAses(LeAudioDevice* leAudioDevice, const std::vector& in); +bool SerializeHandles(const LeAudioDevice* leAudioDevice, std::vector& out); +bool DeserializeHandles(LeAudioDevice* leAudioDevice, const std::vector& in); } // namespace bluetooth::le_audio \ No newline at end of file diff --git a/system/bta/le_audio/storage_helper_test.cc b/system/bta/le_audio/storage_helper_test.cc index e24750e2432..20bc48caa24 100644 --- a/system/bta/le_audio/storage_helper_test.cc +++ b/system/bta/le_audio/storage_helper_test.cc @@ -34,63 +34,63 @@ class StorageHelperTest : public ::testing::Test {}; TEST(StorageHelperTest, DeserializeSinkPacs) { // clang-format off const std::vector validSinkPack = { - 0x00, // Magic - 0x01, // Num of PACs - 0x02,0x12, // handle - 0x03,0x12, // cc handle - 0x02, // Number of records in PAC - 0x1e, // PAC entry size - 0x06,0x00,0x00,0x00,0x00, // Codec Id - 0x13, // Codec specific cap. size - 0x03,0x01,0x04,0x00,0x02,0x02,0x01,0x02,0x03,0x01,0x05,0x04,0x1e,0x00,0x1e,0x00,0x02,0x05,0x01, // Codec specific capa - 0x04, // Metadata size - 0x03,0x01,0xff,0x0f, // Metadata - 0x1e, // - 0x06,0x00,0x00,0x00,0x00, // Codec ID - 0x13, // Codec specific cap. size - 0x03,0x01,0x20,0x00,0x02,0x02,0x01,0x02,0x03,0x01,0x05,0x04,0x3c,0x00,0x3c,0x00,0x02,0x05,0x01, // Codec specific capa + 0x00, // Magic + 0x01, // Num of PACs + 0x02,0x12, // handle + 0x03,0x12, // cc handle + 0x02, // Number of records in PAC + 0x1e, // PAC entry size + 0x06,0x00,0x00,0x00,0x00, // Codec Id + 0x13, // Codec specific cap. size + 0x03,0x01,0x04,0x00,0x02,0x02,0x01,0x02,0x03,0x01,0x05,0x04,0x1e,0x00,0x1e,0x00,0x02,0x05,0x01, // Codec specific capa + 0x04, // Metadata size + 0x03,0x01,0xff,0x0f, // Metadata + 0x1e, // + 0x06,0x00,0x00,0x00,0x00, // Codec ID + 0x13, // Codec specific cap. size + 0x03,0x01,0x20,0x00,0x02,0x02,0x01,0x02,0x03,0x01,0x05,0x04,0x3c,0x00,0x3c,0x00,0x02,0x05,0x01, // Codec specific capa 0x04, // Codec specific capa - 0x03,0x01,0xff,0x0f, // Metadata + 0x03,0x01,0xff,0x0f, // Metadata }; const std::vector invalidSinkPackNumOfPacs = { - 0x00, // Magic - 0x05, // Num of PACs - 0x02,0x12, // handle - 0x03,0x12, // cc handle - 0x01, // Number of records in PAC - 0x1e, // PAC entry size - 0x06,0x00,0x00,0x00,0x00, // Codec Id - 0x13, // Codec specific cap. size - 0x03,0x01,0x04,0x00,0x02,0x02,0x01,0x02,0x03,0x01,0x05,0x04,0x1e,0x00,0x1e,0x00,0x02,0x05,0x01, // Codec specific capa - 0x04, // Metadata size - 0x03,0x01,0xff,0x0f, // Metadata - 0x1e, // - 0x06,0x00,0x00,0x00,0x00, // Codec ID - 0x13, // Codec specific cap. size - 0x03,0x01,0x20,0x00,0x02,0x02,0x01,0x02,0x03,0x01,0x05,0x04,0x3c,0x00,0x3c,0x00,0x02,0x05,0x01, // Codec specific capa + 0x00, // Magic + 0x05, // Num of PACs + 0x02,0x12, // handle + 0x03,0x12, // cc handle + 0x01, // Number of records in PAC + 0x1e, // PAC entry size + 0x06,0x00,0x00,0x00,0x00, // Codec Id + 0x13, // Codec specific cap. size + 0x03,0x01,0x04,0x00,0x02,0x02,0x01,0x02,0x03,0x01,0x05,0x04,0x1e,0x00,0x1e,0x00,0x02,0x05,0x01, // Codec specific capa + 0x04, // Metadata size + 0x03,0x01,0xff,0x0f, // Metadata + 0x1e, // + 0x06,0x00,0x00,0x00,0x00, // Codec ID + 0x13, // Codec specific cap. size + 0x03,0x01,0x20,0x00,0x02,0x02,0x01,0x02,0x03,0x01,0x05,0x04,0x3c,0x00,0x3c,0x00,0x02,0x05,0x01, // Codec specific capa 0x04, // Codec specific capa - 0x03,0x01,0xff,0x0f, // Metadata + 0x03,0x01,0xff,0x0f, // Metadata }; const std::vector invalidSinkPackMagic = { - 0x01, // Magic - 0x01, // Num of PACs - 0x02,0x12, // handle - 0x03,0x12, // cc handle - 0x02, // Number of records in PAC - 0x1e, // PAC entry size - 0x06,0x00,0x00,0x00,0x00, // Codec Id - 0x13, // Codec specific cap. size - 0x03,0x01,0x04,0x00,0x02,0x02,0x01,0x02,0x03,0x01,0x05,0x04,0x1e,0x00,0x1e,0x00,0x02,0x05,0x01, // Codec specific capa - 0x04, // Metadata size - 0x03,0x01,0xff,0x0f, // Metadata - 0x1e, // - 0x06,0x00,0x00,0x00,0x00, // Codec ID - 0x13, // Codec specific cap. size - 0x03,0x01,0x20,0x00,0x02,0x02,0x01,0x02,0x03,0x01,0x05,0x04,0x3c,0x00,0x3c,0x00,0x02,0x05,0x01, // Codec specific capa + 0x01, // Magic + 0x01, // Num of PACs + 0x02,0x12, // handle + 0x03,0x12, // cc handle + 0x02, // Number of records in PAC + 0x1e, // PAC entry size + 0x06,0x00,0x00,0x00,0x00, // Codec Id + 0x13, // Codec specific cap. size + 0x03,0x01,0x04,0x00,0x02,0x02,0x01,0x02,0x03,0x01,0x05,0x04,0x1e,0x00,0x1e,0x00,0x02,0x05,0x01, // Codec specific capa + 0x04, // Metadata size + 0x03,0x01,0xff,0x0f, // Metadata + 0x1e, // + 0x06,0x00,0x00,0x00,0x00, // Codec ID + 0x13, // Codec specific cap. size + 0x03,0x01,0x20,0x00,0x02,0x02,0x01,0x02,0x03,0x01,0x05,0x04,0x3c,0x00,0x3c,0x00,0x02,0x05,0x01, // Codec specific capa 0x04, // Codec specific capa - 0x03,0x01,0xff,0x0f, // Metadata + 0x03,0x01,0xff,0x0f, // Metadata }; // clang-format on @@ -108,72 +108,72 @@ TEST(StorageHelperTest, DeserializeSinkPacs) { TEST(StorageHelperTest, DeserializeSourcePacs) { // clang-format off const std::vector validSourcePack = { - 0x00, // Magic - 0x01, // Num of PACs - 0x08,0x12, // handle - 0x09,0x12, // cc handle - 0x02, // Number of records in PAC - 0x1e, // PAC entry size - 0x06,0x00,0x00,0x00,0x00, // Codec Id - 0x13, // Codec specific cap. size + 0x00, // Magic + 0x01, // Num of PACs + 0x08,0x12, // handle + 0x09,0x12, // cc handle + 0x02, // Number of records in PAC + 0x1e, // PAC entry size + 0x06,0x00,0x00,0x00,0x00, // Codec Id + 0x13, // Codec specific cap. size 0x03,0x01,0x04,0x00,0x02,0x02,0x01,0x02,0x03,0x01,0x05,0x04,0x1e,0x00,0x1e,0x00,0x02,0x05,0x01, - 0x04, // Metadata size - 0x03,0x01,0x03,0x00, // Metadata - 0x1e, // PAC entry size - 0x06,0x00,0x00,0x00,0x00, // Codec Id - 0x13, // Codec specific cap. size - 0x03,0x01,0x20,0x00,0x02,0x02,0x01,0x02, // Codec specific capa - 0x03,0x01,0x05,0x04,0x3c,0x00,0x3c,0x00, // Codec specific capa - 0x02,0x05,0x01, // Codec specific capa - 0x04, // Metadata size + 0x04, // Metadata size + 0x03,0x01,0x03,0x00, // Metadata + 0x1e, // PAC entry size + 0x06,0x00,0x00,0x00,0x00, // Codec Id + 0x13, // Codec specific cap. size + 0x03,0x01,0x20,0x00,0x02,0x02,0x01,0x02, // Codec specific capa + 0x03,0x01,0x05,0x04,0x3c,0x00,0x3c,0x00, // Codec specific capa + 0x02,0x05,0x01, // Codec specific capa + 0x04, // Metadata size 0x03,0x01,0x03,0x00 // Metadata }; const std::vector invalidSourcePackNumOfPacs = { - 0x00, // Magic - 0x04, // Num of PACs - 0x08,0x12, // handle - 0x09,0x12, // cc handle - 0x01, // Number of records in PAC - 0x1e, // PAC entry size - 0x06,0x00,0x00,0x00,0x00, // Codec Id - 0x13, // Codec specific cap. size - 0x03,0x01,0x04,0x00,0x02,0x02,0x01,0x02, // Codec specific capa - 0x03,0x01,0x05,0x04,0x1e,0x00,0x1e,0x00, // Codec specific capa - 0x02,0x05,0x01, // Codec specific capa - 0x04, // Metadata size - 0x03,0x01,0x03,0x00, // Metadata - 0x1e, // PAC entry size - 0x06,0x00,0x00,0x00,0x00, // Codec Id - 0x13, // Codec specific cap. size - 0x03,0x01,0x20,0x00,0x02,0x02,0x01,0x02, // Codec specific capa - 0x03,0x01,0x05,0x04,0x3c,0x00,0x3c,0x00, // Codec specific capa - 0x02,0x05,0x01, // Codec specific capa - 0x04, // Metadata size + 0x00, // Magic + 0x04, // Num of PACs + 0x08,0x12, // handle + 0x09,0x12, // cc handle + 0x01, // Number of records in PAC + 0x1e, // PAC entry size + 0x06,0x00,0x00,0x00,0x00, // Codec Id + 0x13, // Codec specific cap. size + 0x03,0x01,0x04,0x00,0x02,0x02,0x01,0x02, // Codec specific capa + 0x03,0x01,0x05,0x04,0x1e,0x00,0x1e,0x00, // Codec specific capa + 0x02,0x05,0x01, // Codec specific capa + 0x04, // Metadata size + 0x03,0x01,0x03,0x00, // Metadata + 0x1e, // PAC entry size + 0x06,0x00,0x00,0x00,0x00, // Codec Id + 0x13, // Codec specific cap. size + 0x03,0x01,0x20,0x00,0x02,0x02,0x01,0x02, // Codec specific capa + 0x03,0x01,0x05,0x04,0x3c,0x00,0x3c,0x00, // Codec specific capa + 0x02,0x05,0x01, // Codec specific capa + 0x04, // Metadata size 0x03,0x01,0x03,0x00 // Metadata }; const std::vector invalidSourcePackMagic = { - 0x01, // Magic - 0x01, // Num of PACs - 0x08,0x12, // handle - 0x09,0x12, // cc handle - 0x02, // Number of records in PAC - 0x1e, // PAC entry size - 0x06,0x00,0x00,0x00,0x00, // Codec Id - 0x13, // Codec specific cap. size - 0x03,0x01,0x04,0x00,0x02,0x02,0x01,0x02, // Codec specific capa - 0x03,0x01,0x05,0x04,0x1e,0x00,0x1e,0x00, // Codec specific capa - 0x02,0x05,0x01, // Codec specific capa - 0x04, // Metadata size - 0x03,0x01,0x03,0x00, // Metadata - 0x1e, // PAC entry size - 0x06,0x00,0x00,0x00,0x00, // Codec Id - 0x13, // Codec specific cap. size - 0x03,0x01,0x20,0x00,0x02,0x02,0x01,0x02, // Codec specific capa - 0x03,0x01,0x05,0x04,0x3c,0x00,0x3c,0x00, // Codec specific capa - 0x02,0x05,0x01, // Codec specific capa - 0x04, // Metadata size + 0x01, // Magic + 0x01, // Num of PACs + 0x08,0x12, // handle + 0x09,0x12, // cc handle + 0x02, // Number of records in PAC + 0x1e, // PAC entry size + 0x06,0x00,0x00,0x00,0x00, // Codec Id + 0x13, // Codec specific cap. size + 0x03,0x01,0x04,0x00,0x02,0x02,0x01,0x02, // Codec specific capa + 0x03,0x01,0x05,0x04,0x1e,0x00,0x1e,0x00, // Codec specific capa + 0x02,0x05,0x01, // Codec specific capa + 0x04, // Metadata size + 0x03,0x01,0x03,0x00, // Metadata + 0x1e, // PAC entry size + 0x06,0x00,0x00,0x00,0x00, // Codec Id + 0x13, // Codec specific cap. size + 0x03,0x01,0x20,0x00,0x02,0x02,0x01,0x02, // Codec specific capa + 0x03,0x01,0x05,0x04,0x3c,0x00,0x3c,0x00, // Codec specific capa + 0x02,0x05,0x01, // Codec specific capa + 0x04, // Metadata size 0x03,0x01,0x03,0x00 // Metadata }; // clang-format on @@ -186,58 +186,57 @@ TEST(StorageHelperTest, DeserializeSourcePacs) { ASSERT_TRUE(serialize == validSourcePack); ASSERT_FALSE(DeserializeSourcePacs(&leAudioDevice, invalidSourcePackMagic)); - ASSERT_FALSE( - DeserializeSourcePacs(&leAudioDevice, invalidSourcePackNumOfPacs)); + ASSERT_FALSE(DeserializeSourcePacs(&leAudioDevice, invalidSourcePackNumOfPacs)); } TEST(StorageHelperTest, DeserializeAses) { // clang-format off const std::vector validAses { - 0x00, // Magic - 0x03, // Num of ASEs - 0x05, 0x11, // handle - 0x06, 0x11, // ccc handle + 0x00, // Magic + 0x03, // Num of ASEs + 0x05, 0x11, // handle + 0x06, 0x11, // ccc handle 0x01, // ASE id 0x01, // direction - 0x08, 0x11, // handle - 0x09, 0x11, // ccc handle - 0x02, // ASE id - 0x01, // direction - 0x0b, 0x11, // handle - 0x0c, 0x11, // ccc handle - 0x03, // ASE id + 0x08, 0x11, // handle + 0x09, 0x11, // ccc handle + 0x02, // ASE id + 0x01, // direction + 0x0b, 0x11, // handle + 0x0c, 0x11, // ccc handle + 0x03, // ASE id 0x02 // direction }; const std::vector invalidAsesNumOfAses { - 0x00, // Magic - 0x05, // Num of ASEs - 0x05, 0x11, // handle - 0x06, 0x11, // ccc handle + 0x00, // Magic + 0x05, // Num of ASEs + 0x05, 0x11, // handle + 0x06, 0x11, // ccc handle 0x01, // ASE id 0x01, // direction - 0x08, 0x11, // handle - 0x09, 0x11, // ccc handle - 0x02, // ASE id - 0x01, // direction - 0x0b, 0x11, // handle - 0x0c, 0x11, // ccc handle - 0x03, // ASE id + 0x08, 0x11, // handle + 0x09, 0x11, // ccc handle + 0x02, // ASE id + 0x01, // direction + 0x0b, 0x11, // handle + 0x0c, 0x11, // ccc handle + 0x03, // ASE id 0x02 // direction }; const std::vector invalidAsesMagic { - 0x01, // Magic - 0x03, // Num of ASEs - 0x05, 0x11, // handle - 0x06, 0x11, // ccc handle + 0x01, // Magic + 0x03, // Num of ASEs + 0x05, 0x11, // handle + 0x06, 0x11, // ccc handle 0x01, // ASE id 0x01, // direction - 0x08, 0x11, // handle - 0x09, 0x11, // ccc handle - 0x02, // ASE id - 0x01, // direction - 0x0b, 0x11, // handle - 0x0c, 0x11, // ccc handle - 0x03, // ASE id + 0x08, 0x11, // handle + 0x09, 0x11, // ccc handle + 0x02, // ASE id + 0x01, // direction + 0x0b, 0x11, // handle + 0x0c, 0x11, // ccc handle + 0x03, // ASE id 0x02 // direction }; // clang-format on @@ -256,47 +255,47 @@ TEST(StorageHelperTest, DeserializeAses) { TEST(StorageHelperTest, DeserializeHandles) { // clang-format off const std::vector validHandles { - 0x00, // Magic - 0x0e, 0x11, // Control point handle - 0x0f, 0x11, // Control point ccc handle - 0x05, 0x12, // Sink audio location handle - 0x06, 0x12, // Sink audio location ccc handle - 0x0b, 0x12, // Source audio location handle - 0x0c, 0x12, // Source audio location ccc handle - 0x11, 0x12, // Supported context types handle - 0x12, 0x12, // Supported context types ccc handle - 0x0e, 0x12, // Available context types handle - 0x0f, 0x12, // Available context types ccc handle + 0x00, // Magic + 0x0e, 0x11, // Control point handle + 0x0f, 0x11, // Control point ccc handle + 0x05, 0x12, // Sink audio location handle + 0x06, 0x12, // Sink audio location ccc handle + 0x0b, 0x12, // Source audio location handle + 0x0c, 0x12, // Source audio location ccc handle + 0x11, 0x12, // Supported context types handle + 0x12, 0x12, // Supported context types ccc handle + 0x0e, 0x12, // Available context types handle + 0x0f, 0x12, // Available context types ccc handle 0x03, 0xa3 // TMAP role handle }; const std::vector invalidHandlesMagic { - 0x01, // Magic - 0x0e, 0x11, // Control point handle - 0x0f, 0x11, // Control point ccc handle - 0x05, 0x12, // Sink audio location handle - 0x06, 0x12, // Sink audio location ccc handle - 0x0b, 0x12, // Source audio location handle - 0x0c, 0x12, // Source audio location ccc handle - 0x11, 0x12, // Supported context types handle - 0x12, 0x12, // Supported context types ccc handle - 0x0e, 0x12, // Available context types handle - 0x0f, 0x12, // Available context types ccc handle + 0x01, // Magic + 0x0e, 0x11, // Control point handle + 0x0f, 0x11, // Control point ccc handle + 0x05, 0x12, // Sink audio location handle + 0x06, 0x12, // Sink audio location ccc handle + 0x0b, 0x12, // Source audio location handle + 0x0c, 0x12, // Source audio location ccc handle + 0x11, 0x12, // Supported context types handle + 0x12, 0x12, // Supported context types ccc handle + 0x0e, 0x12, // Available context types handle + 0x0f, 0x12, // Available context types ccc handle 0x03, 0xa3 // TMAP role handle }; const std::vector invalidHandles { - 0x00, // Magic - 0x0e, 0x11, // Control point handle - 0x0f, 0x11, // Control point ccc handle - 0x05, 0x12, // Sink audio location handle - 0x06, 0x12, // Sink audio location ccc handle - 0x0b, 0x12, // Source audio location handle - 0x0c, 0x12, // Source audio location ccc handle - 0x11, 0x12, // Supported context types handle - 0x12, 0x12, // Supported context types ccc handle - 0x0e, 0x12, // Available context types handle - 0x0f, 0x12, // Available context types ccc handle + 0x00, // Magic + 0x0e, 0x11, // Control point handle + 0x0f, 0x11, // Control point ccc handle + 0x05, 0x12, // Sink audio location handle + 0x06, 0x12, // Sink audio location ccc handle + 0x0b, 0x12, // Source audio location handle + 0x0c, 0x12, // Source audio location ccc handle + 0x11, 0x12, // Supported context types handle + 0x12, 0x12, // Supported context types ccc handle + 0x0e, 0x12, // Available context types handle + 0x0f, 0x12, // Available context types ccc handle 0x03, 0xa3, // TMAP role handle - 0x00, 0x00, // corrupted + 0x00, 0x00, // corrupted }; // clang-format on RawAddress test_address0 = GetTestAddress(0); diff --git a/system/bta/pan/bta_pan_act.cc b/system/bta/pan/bta_pan_act.cc index f0520670d5d..223c9813bf8 100644 --- a/system/bta/pan/bta_pan_act.cc +++ b/system/bta/pan/bta_pan_act.cc @@ -41,8 +41,7 @@ using namespace bluetooth; #if (PAN_INCLUDED == TRUE) -void bta_pan_sm_execute(tBTA_PAN_SCB* p_scb, uint16_t event, - tBTA_PAN_DATA* p_data); +void bta_pan_sm_execute(tBTA_PAN_SCB* p_scb, uint16_t event, tBTA_PAN_DATA* p_data); /* RX and TX data flow mask */ #define BTA_PAN_RX_MASK 0x0F @@ -60,8 +59,9 @@ void bta_pan_sm_execute(tBTA_PAN_SCB* p_scb, uint16_t event, * ******************************************************************************/ static void bta_pan_pm_conn_busy(tBTA_PAN_SCB* p_scb) { - if ((p_scb != NULL) && (p_scb->state != BTA_PAN_IDLE_ST)) + if ((p_scb != NULL) && (p_scb->state != BTA_PAN_IDLE_ST)) { bta_sys_busy(BTA_ID_PAN, p_scb->app_id, p_scb->bd_addr); + } } /******************************************************************************* @@ -76,8 +76,9 @@ static void bta_pan_pm_conn_busy(tBTA_PAN_SCB* p_scb) { * ******************************************************************************/ static void bta_pan_pm_conn_idle(tBTA_PAN_SCB* p_scb) { - if ((p_scb != NULL) && (p_scb->state != BTA_PAN_IDLE_ST)) + if ((p_scb != NULL) && (p_scb->state != BTA_PAN_IDLE_ST)) { bta_sys_idle(BTA_ID_PAN, p_scb->app_id, p_scb->bd_addr); + } } /******************************************************************************* @@ -90,9 +91,8 @@ static void bta_pan_pm_conn_idle(tBTA_PAN_SCB* p_scb) { * Returns void * ******************************************************************************/ -static void bta_pan_conn_state_cback(uint16_t handle, const RawAddress& bd_addr, - tPAN_RESULT state, bool is_role_change, - uint8_t src_role, uint8_t dst_role) { +static void bta_pan_conn_state_cback(uint16_t handle, const RawAddress& bd_addr, tPAN_RESULT state, + bool is_role_change, uint8_t src_role, uint8_t dst_role) { tBTA_PAN_SCB* p_scb; tBTA_PAN_CONN* p_buf = (tBTA_PAN_CONN*)osi_malloc(sizeof(tBTA_PAN_CONN)); @@ -116,10 +116,11 @@ static void bta_pan_conn_state_cback(uint16_t handle, const RawAddress& bd_addr, p_scb->bd_addr = bd_addr; p_scb->data_queue = fixed_queue_new(SIZE_MAX); - if (src_role == PAN_ROLE_CLIENT) + if (src_role == PAN_ROLE_CLIENT) { p_scb->app_id = bta_pan_cb.app_id[0]; - else if (src_role == PAN_ROLE_NAP_SERVER) + } else if (src_role == PAN_ROLE_NAP_SERVER) { p_scb->app_id = bta_pan_cb.app_id[2]; + } } else if ((state != PAN_SUCCESS) && !is_role_change) { p_buf->hdr.event = BTA_PAN_CONN_CLOSE_EVT; } else { @@ -146,7 +147,9 @@ static void bta_pan_data_flow_cb(uint16_t handle, tPAN_RESULT result) { tBTA_PAN_SCB* p_scb; p_scb = bta_pan_scb_by_handle(handle); - if (p_scb == NULL) return; + if (p_scb == NULL) { + return; + } if (result == PAN_TX_FLOW_ON) { BT_HDR_RIGID* p_buf = (BT_HDR_RIGID*)osi_malloc(sizeof(BT_HDR_RIGID)); @@ -171,15 +174,14 @@ static void bta_pan_data_flow_cb(uint16_t handle, tPAN_RESULT result) { * ******************************************************************************/ static void bta_pan_data_buf_ind_cback(uint16_t handle, const RawAddress& src, - const RawAddress& dst, uint16_t protocol, - BT_HDR* p_buf, bool ext, bool forward) { + const RawAddress& dst, uint16_t protocol, BT_HDR* p_buf, + bool ext, bool forward) { tBTA_PAN_SCB* p_scb = bta_pan_scb_by_handle(handle); if (p_scb == NULL) { return; } - if (sizeof(BT_HDR) + sizeof(tBTA_PAN_DATA_PARAMS) + p_buf->len > - PAN_BUF_SIZE) { + if (sizeof(BT_HDR) + sizeof(tBTA_PAN_DATA_PARAMS) + p_buf->len > PAN_BUF_SIZE) { log::error("received buffer length too large: {}", p_buf->len); return; } @@ -214,11 +216,9 @@ static void bta_pan_data_buf_ind_cback(uint16_t handle, const RawAddress& src, * Returns void * ******************************************************************************/ -static void bta_pan_pfilt_ind_cback(uint16_t handle, bool indication, - tPAN_RESULT result, uint16_t num_filters, - uint8_t* p_filters) { - bta_pan_co_pfilt_ind(handle, indication, - (result == PAN_SUCCESS) ? BTA_PAN_SUCCESS : BTA_PAN_FAIL, +static void bta_pan_pfilt_ind_cback(uint16_t handle, bool indication, tPAN_RESULT result, + uint16_t num_filters, uint8_t* p_filters) { + bta_pan_co_pfilt_ind(handle, indication, (result == PAN_SUCCESS) ? BTA_PAN_SUCCESS : BTA_PAN_FAIL, num_filters, p_filters); } @@ -232,11 +232,9 @@ static void bta_pan_pfilt_ind_cback(uint16_t handle, bool indication, * Returns void * ******************************************************************************/ -static void bta_pan_mfilt_ind_cback(uint16_t handle, bool indication, - tPAN_RESULT result, uint16_t num_mfilters, - uint8_t* p_mfilters) { - bta_pan_co_mfilt_ind(handle, indication, - (result == PAN_SUCCESS) ? BTA_PAN_SUCCESS : BTA_PAN_FAIL, +static void bta_pan_mfilt_ind_cback(uint16_t handle, bool indication, tPAN_RESULT result, + uint16_t num_mfilters, uint8_t* p_mfilters) { + bta_pan_co_mfilt_ind(handle, indication, (result == PAN_SUCCESS) ? BTA_PAN_SUCCESS : BTA_PAN_FAIL, num_mfilters, p_mfilters); } @@ -267,15 +265,16 @@ static bool bta_pan_has_multiple_connections(uint8_t app_id) { } /* If cannot find a match then there is no connection at all */ - if (!found) return false; + if (!found) { + return false; + } /* Find whether there is another connection with different device other than PANU. Could be same service or different service */ for (uint8_t index = 0; index < BTA_PAN_NUM_CONN; index++) { p_scb = &bta_pan_cb.scb[index]; - if (p_scb->in_use && p_scb->app_id != bta_pan_cb.app_id[0] && - bd_addr != p_scb->bd_addr) { + if (p_scb->in_use && p_scb->app_id != bta_pan_cb.app_id[0] && bd_addr != p_scb->bd_addr) { return true; } } @@ -326,29 +325,30 @@ void bta_pan_set_role(tBTA_PAN_DATA* p_data) { bta_pan_cb.app_id[2] = p_data->api_set_role.nap_app_id; /* set security correctly in api and here */ - tPAN_RESULT status = PAN_SetRole(p_data->api_set_role.role, - std::string(p_data->api_set_role.user_name), - std::string(p_data->api_set_role.nap_name)); + tPAN_RESULT status = + PAN_SetRole(p_data->api_set_role.role, std::string(p_data->api_set_role.user_name), + std::string(p_data->api_set_role.nap_name)); tBTA_PAN bta_pan = { - .set_role = - { - .status = - (status == PAN_SUCCESS) ? BTA_PAN_SUCCESS : BTA_PAN_FAIL, - .role = p_data->api_set_role.role, - }, + .set_role = + { + .status = (status == PAN_SUCCESS) ? BTA_PAN_SUCCESS : BTA_PAN_FAIL, + .role = p_data->api_set_role.role, + }, }; if (status == PAN_SUCCESS) { - if (p_data->api_set_role.role & PAN_ROLE_NAP_SERVER) + if (p_data->api_set_role.role & PAN_ROLE_NAP_SERVER) { bta_sys_add_uuid(UUID_SERVCLASS_NAP); - else + } else { bta_sys_remove_uuid(UUID_SERVCLASS_NAP); + } - if (p_data->api_set_role.role & PAN_ROLE_CLIENT) + if (p_data->api_set_role.role & PAN_ROLE_CLIENT) { bta_sys_add_uuid(UUID_SERVCLASS_PANU); - else + } else { bta_sys_remove_uuid(UUID_SERVCLASS_PANU); + } } /* if status is not success clear everything */ else { @@ -385,9 +385,9 @@ void bta_pan_disable(void) { /* free all queued up data buffers */ for (i = 0; i < BTA_PAN_NUM_CONN; i++, p_scb++) { if (p_scb->in_use) { - while ((p_buf = (BT_HDR*)fixed_queue_try_dequeue(p_scb->data_queue)) != - NULL) + while ((p_buf = (BT_HDR*)fixed_queue_try_dequeue(p_scb->data_queue)) != NULL) { osi_free(p_buf); + } bta_pan_co_close(p_scb->handle, p_scb->app_id); } @@ -492,8 +492,7 @@ void bta_pan_conn_open(tBTA_PAN_SCB* p_scb, tBTA_PAN_DATA* p_data) { /* If app_id is NAP/GN, check whether there are multiple connections. If there are, provide a special app_id to dm to enforce central role only. */ - if (p_scb->app_id == bta_pan_cb.app_id[2] && - bta_pan_has_multiple_connections(p_scb->app_id)) { + if (p_scb->app_id == bta_pan_cb.app_id[2] && bta_pan_has_multiple_connections(p_scb->app_id)) { p_scb->app_id = BTA_APP_ID_PAN_MULTI; } @@ -521,8 +520,9 @@ void bta_pan_conn_close(tBTA_PAN_SCB* p_scb, tBTA_PAN_DATA* p_data) { bta_sys_conn_close(BTA_ID_PAN, p_scb->app_id, p_scb->bd_addr); /* free all queued up data buffers */ - while ((p_buf = (BT_HDR*)fixed_queue_try_dequeue(p_scb->data_queue)) != NULL) + while ((p_buf = (BT_HDR*)fixed_queue_try_dequeue(p_scb->data_queue)) != NULL) { osi_free(p_buf); + } bta_pan_scb_dealloc(p_scb); @@ -609,9 +609,8 @@ void bta_pan_write_buf(tBTA_PAN_SCB* p_scb, tBTA_PAN_DATA* p_data) { bta_pan_pm_conn_busy(p_scb); PAN_WriteBuf(p_scb->handle, ((tBTA_PAN_DATA_PARAMS*)p_data)->dst, - ((tBTA_PAN_DATA_PARAMS*)p_data)->src, - ((tBTA_PAN_DATA_PARAMS*)p_data)->protocol, (BT_HDR*)p_data, - ((tBTA_PAN_DATA_PARAMS*)p_data)->ext); + ((tBTA_PAN_DATA_PARAMS*)p_data)->src, ((tBTA_PAN_DATA_PARAMS*)p_data)->protocol, + (BT_HDR*)p_data, ((tBTA_PAN_DATA_PARAMS*)p_data)->ext); bta_pan_pm_conn_idle(p_scb); } } @@ -626,8 +625,6 @@ void bta_pan_write_buf(tBTA_PAN_SCB* p_scb, tBTA_PAN_DATA* p_data) { * Returns void * ******************************************************************************/ -void bta_pan_free_buf(tBTA_PAN_SCB* /* p_scb */, tBTA_PAN_DATA* p_data) { - osi_free(p_data); -} +void bta_pan_free_buf(tBTA_PAN_SCB* /* p_scb */, tBTA_PAN_DATA* p_data) { osi_free(p_data); } #endif /* PAN_INCLUDED */ diff --git a/system/bta/pan/bta_pan_api.cc b/system/bta/pan/bta_pan_api.cc index d3d16ebea00..506c9d547ef 100644 --- a/system/bta/pan/bta_pan_api.cc +++ b/system/bta/pan/bta_pan_api.cc @@ -38,17 +38,15 @@ static const tBTA_SYS_REG bta_pan_reg = {bta_pan_hdl_event, BTA_PanDisable}; void bta_pan_api_disable(tBTA_PAN_DATA* p_data); void bta_pan_api_enable(tBTA_PAN_DATA* p_data); void bta_pan_api_open(tBTA_PAN_DATA* p_data); -void bta_pan_sm_execute(tBTA_PAN_SCB* p_scb, uint16_t event, - tBTA_PAN_DATA* p_data); +void bta_pan_sm_execute(tBTA_PAN_SCB* p_scb, uint16_t event, tBTA_PAN_DATA* p_data); std::string user_service_name; /* Service name for PANU role */ std::string gn_service_name; /* Service name for GN role */ std::string nap_service_name; /* Service name for NAP role */ #ifndef PAN_SECURITY -#define PAN_SECURITY \ - (BTM_SEC_IN_AUTHENTICATE | BTM_SEC_OUT_AUTHENTICATE | BTM_SEC_IN_ENCRYPT | \ - BTM_SEC_OUT_ENCRYPT) +#define PAN_SECURITY \ + (BTM_SEC_IN_AUTHENTICATE | BTM_SEC_OUT_AUTHENTICATE | BTM_SEC_IN_ENCRYPT | BTM_SEC_OUT_ENCRYPT) #endif /******************************************************************************* @@ -64,8 +62,7 @@ std::string nap_service_name; /* Service name for NAP role */ * ******************************************************************************/ void BTA_PanEnable(tBTA_PAN_CBACK p_cback) { - tBTA_PAN_API_ENABLE* p_buf = - (tBTA_PAN_API_ENABLE*)osi_malloc(sizeof(tBTA_PAN_API_ENABLE)); + tBTA_PAN_API_ENABLE* p_buf = (tBTA_PAN_API_ENABLE*)osi_malloc(sizeof(tBTA_PAN_API_ENABLE)); /* register with BTA system manager */ bta_sys_register(BTA_ID_PAN, &bta_pan_reg); @@ -110,28 +107,28 @@ void BTA_PanSetRole(tBTA_PAN_ROLE role, const tBTA_PAN_ROLE_INFO user_info, const tBTA_PAN_ROLE_INFO nap_info) { post_on_bt_main([=]() { tBTA_PAN_DATA data = { - .api_set_role = - { - .hdr = + .api_set_role = { - .event = BTA_PAN_API_SET_ROLE_EVT, + .hdr = + { + .event = BTA_PAN_API_SET_ROLE_EVT, + }, + .user_name = {}, + .nap_name = {}, + .role = role, }, - .user_name = {}, - .nap_name = {}, - .role = role, - }, }; if (role & BTA_PAN_ROLE_PANU) { - if (!user_info.p_srv_name.empty()) - strncpy(data.api_set_role.user_name, user_info.p_srv_name.data(), - BTA_SERVICE_NAME_LEN); + if (!user_info.p_srv_name.empty()) { + strncpy(data.api_set_role.user_name, user_info.p_srv_name.data(), BTA_SERVICE_NAME_LEN); + } data.api_set_role.user_app_id = user_info.app_id; } if (role & BTA_PAN_ROLE_NAP) { - if (!nap_info.p_srv_name.empty()) - strncpy(data.api_set_role.nap_name, nap_info.p_srv_name.data(), - BTA_SERVICE_NAME_LEN); + if (!nap_info.p_srv_name.empty()) { + strncpy(data.api_set_role.nap_name, nap_info.p_srv_name.data(), BTA_SERVICE_NAME_LEN); + } data.api_set_role.nap_app_id = nap_info.app_id; } bta_pan_set_role(&data); @@ -150,10 +147,8 @@ void BTA_PanSetRole(tBTA_PAN_ROLE role, const tBTA_PAN_ROLE_INFO user_info, * Returns void * ******************************************************************************/ -void BTA_PanOpen(const RawAddress& bd_addr, tBTA_PAN_ROLE local_role, - tBTA_PAN_ROLE peer_role) { - tBTA_PAN_API_OPEN* p_buf = - (tBTA_PAN_API_OPEN*)osi_malloc(sizeof(tBTA_PAN_API_OPEN)); +void BTA_PanOpen(const RawAddress& bd_addr, tBTA_PAN_ROLE local_role, tBTA_PAN_ROLE peer_role) { + tBTA_PAN_API_OPEN* p_buf = (tBTA_PAN_API_OPEN*)osi_malloc(sizeof(tBTA_PAN_API_OPEN)); p_buf->hdr.event = BTA_PAN_API_OPEN_EVT; p_buf->local_role = local_role; diff --git a/system/bta/pan/bta_pan_ci.cc b/system/bta/pan/bta_pan_ci.cc index 3c3804f859f..833216aa52d 100644 --- a/system/bta/pan/bta_pan_ci.cc +++ b/system/bta/pan/bta_pan_ci.cc @@ -28,8 +28,7 @@ #include "stack/include/bt_hdr.h" #include "types/raw_address.h" -void bta_pan_sm_execute(tBTA_PAN_SCB* p_scb, uint16_t event, - tBTA_PAN_DATA* p_data); +void bta_pan_sm_execute(tBTA_PAN_SCB* p_scb, uint16_t event, tBTA_PAN_DATA* p_data); /******************************************************************************* * @@ -92,8 +91,7 @@ void bta_pan_ci_rx_ready(uint16_t handle) { * ******************************************************************************/ void bta_pan_ci_tx_flow(uint16_t handle, bool enable) { - tBTA_PAN_CI_TX_FLOW* p_buf = - (tBTA_PAN_CI_TX_FLOW*)osi_malloc(sizeof(tBTA_PAN_CI_TX_FLOW)); + tBTA_PAN_CI_TX_FLOW* p_buf = (tBTA_PAN_CI_TX_FLOW*)osi_malloc(sizeof(tBTA_PAN_CI_TX_FLOW)); p_buf->hdr.layer_specific = handle; p_buf->hdr.event = BTA_PAN_CI_TX_FLOW_EVT; @@ -114,9 +112,8 @@ void bta_pan_ci_tx_flow(uint16_t handle, bool enable) { * Returns void * ******************************************************************************/ -void bta_pan_ci_rx_write(uint16_t handle, const RawAddress& dst, - const RawAddress& src, uint16_t protocol, - uint8_t* p_data, uint16_t len, bool ext) { +void bta_pan_ci_rx_write(uint16_t handle, const RawAddress& dst, const RawAddress& src, + uint16_t protocol, uint8_t* p_data, uint16_t len, bool ext) { BT_HDR* p_buf = (BT_HDR*)osi_malloc(PAN_BUF_SIZE); p_buf->offset = PAN_MINIMUM_OFFSET; @@ -151,9 +148,8 @@ void bta_pan_ci_rx_write(uint16_t handle, const RawAddress& dst, * Returns void * ******************************************************************************/ -void bta_pan_ci_rx_writebuf(uint16_t handle, const RawAddress& dst, - const RawAddress& src, uint16_t protocol, - BT_HDR* p_buf, bool ext) { +void bta_pan_ci_rx_writebuf(uint16_t handle, const RawAddress& dst, const RawAddress& src, + uint16_t protocol, BT_HDR* p_buf, bool ext) { /* copy all other params before the data */ ((tBTA_PAN_DATA_PARAMS*)p_buf)->src = src; ((tBTA_PAN_DATA_PARAMS*)p_buf)->dst = dst; @@ -175,12 +171,14 @@ void bta_pan_ci_rx_writebuf(uint16_t handle, const RawAddress& dst, * Returns void * ******************************************************************************/ -BT_HDR* bta_pan_ci_readbuf(uint16_t handle, RawAddress& src, RawAddress& dst, - uint16_t* p_protocol, bool* p_ext, bool* p_forward) { +BT_HDR* bta_pan_ci_readbuf(uint16_t handle, RawAddress& src, RawAddress& dst, uint16_t* p_protocol, + bool* p_ext, bool* p_forward) { tBTA_PAN_SCB* p_scb = bta_pan_scb_by_handle(handle); BT_HDR* p_buf; - if (p_scb == NULL) return NULL; + if (p_scb == NULL) { + return NULL; + } p_buf = (BT_HDR*)fixed_queue_try_dequeue(p_scb->data_queue); if (p_buf != NULL) { diff --git a/system/bta/pan/bta_pan_int.h b/system/bta/pan/bta_pan_int.h index 8bd7d057f2d..09781f4269e 100644 --- a/system/bta/pan/bta_pan_int.h +++ b/system/bta/pan/bta_pan_int.h @@ -27,8 +27,8 @@ #include #include "bta/include/bta_api.h" -#include "bta/include/bta_sec_api.h" #include "bta/include/bta_pan_api.h" +#include "bta/include/bta_sec_api.h" #include "bta/sys/bta_sys.h" #include "osi/include/fixed_queue.h" #include "stack/include/bt_hdr.h" @@ -94,7 +94,7 @@ typedef struct { /* data type for BTA_PAN_CI_TX_FLOW_EVT */ typedef struct { BT_HDR_RIGID hdr; /* Event header */ - bool enable; /* Flow control setting */ + bool enable; /* Flow control setting */ } tBTA_PAN_CI_TX_FLOW; /* data type for BTA_PAN_CONN_OPEN_EVT */ @@ -128,18 +128,17 @@ typedef union { /* state machine control block */ typedef struct { - RawAddress bd_addr; /* peer bdaddr */ - fixed_queue_t* - data_queue; /* Queue of buffers waiting to be passed to application */ - uint16_t handle; /* BTA PAN/BNEP handle */ - bool in_use; /* scb in use */ - tBTA_SEC sec_mask; /* Security mask */ - bool pan_flow_enable; /* BNEP flow control state */ - bool app_flow_enable; /* Application flow control state */ - uint8_t state; /* State machine state */ - tBTA_PAN_ROLE local_role; /* local role */ - tBTA_PAN_ROLE peer_role; /* peer role */ - uint8_t app_id; /* application id for the connection */ + RawAddress bd_addr; /* peer bdaddr */ + fixed_queue_t* data_queue; /* Queue of buffers waiting to be passed to application */ + uint16_t handle; /* BTA PAN/BNEP handle */ + bool in_use; /* scb in use */ + tBTA_SEC sec_mask; /* Security mask */ + bool pan_flow_enable; /* BNEP flow control state */ + bool app_flow_enable; /* Application flow control state */ + uint8_t state; /* State machine state */ + tBTA_PAN_ROLE local_role; /* local role */ + tBTA_PAN_ROLE peer_role; /* peer role */ + uint8_t app_id; /* application id for the connection */ } tBTA_PAN_SCB; @@ -149,7 +148,7 @@ typedef struct { tBTA_PAN_CBACK* p_cback; /* PAN callback function */ uint8_t app_id[3]; /* application id for PAN roles */ uint8_t flow_mask; /* Data flow mask */ - uint8_t q_level; /* queue level set by application for TX data */ + uint8_t q_level; /* queue level set by application for TX data */ } tBTA_PAN_CB; diff --git a/system/bta/pan/bta_pan_main.cc b/system/bta/pan/bta_pan_main.cc index 4b3df8cec08..57c87e9d503 100644 --- a/system/bta/pan/bta_pan_main.cc +++ b/system/bta/pan/bta_pan_main.cc @@ -54,8 +54,8 @@ typedef void (*tBTA_PAN_ACTION)(tBTA_PAN_SCB* p_scb, tBTA_PAN_DATA* p_data); /* action function list */ const tBTA_PAN_ACTION bta_pan_action[] = { - bta_pan_api_close, bta_pan_tx_path, bta_pan_rx_path, bta_pan_tx_flow, - bta_pan_write_buf, bta_pan_conn_open, bta_pan_conn_close, bta_pan_free_buf, + bta_pan_api_close, bta_pan_tx_path, bta_pan_rx_path, bta_pan_tx_flow, + bta_pan_write_buf, bta_pan_conn_open, bta_pan_conn_close, bta_pan_free_buf, }; @@ -66,51 +66,50 @@ const tBTA_PAN_ACTION bta_pan_action[] = { /* state table for listen state */ const uint8_t bta_pan_st_idle[][BTA_PAN_NUM_COLS] = { - /* API_CLOSE */ {BTA_PAN_API_CLOSE, BTA_PAN_IDLE_ST}, - /* CI_TX_READY */ {BTA_PAN_IGNORE, BTA_PAN_IDLE_ST}, - /* CI_RX_READY */ {BTA_PAN_IGNORE, BTA_PAN_IDLE_ST}, - /* CI_TX_FLOW */ {BTA_PAN_IGNORE, BTA_PAN_IDLE_ST}, - /* CI_RX_WRITE */ {BTA_PAN_IGNORE, BTA_PAN_IDLE_ST}, - /* CI_RX_WRITEBUF */ {BTA_PAN_IGNORE, BTA_PAN_IDLE_ST}, - /* PAN_CONN_OPEN */ {BTA_PAN_CONN_OPEN, BTA_PAN_OPEN_ST}, - /* PAN_CONN_CLOSE */ {BTA_PAN_CONN_OPEN, BTA_PAN_IDLE_ST}, - /* FLOW_ENABLE */ {BTA_PAN_IGNORE, BTA_PAN_IDLE_ST}, - /* BNEP_DATA */ {BTA_PAN_IGNORE, BTA_PAN_IDLE_ST} + /* API_CLOSE */ {BTA_PAN_API_CLOSE, BTA_PAN_IDLE_ST}, + /* CI_TX_READY */ {BTA_PAN_IGNORE, BTA_PAN_IDLE_ST}, + /* CI_RX_READY */ {BTA_PAN_IGNORE, BTA_PAN_IDLE_ST}, + /* CI_TX_FLOW */ {BTA_PAN_IGNORE, BTA_PAN_IDLE_ST}, + /* CI_RX_WRITE */ {BTA_PAN_IGNORE, BTA_PAN_IDLE_ST}, + /* CI_RX_WRITEBUF */ {BTA_PAN_IGNORE, BTA_PAN_IDLE_ST}, + /* PAN_CONN_OPEN */ {BTA_PAN_CONN_OPEN, BTA_PAN_OPEN_ST}, + /* PAN_CONN_CLOSE */ {BTA_PAN_CONN_OPEN, BTA_PAN_IDLE_ST}, + /* FLOW_ENABLE */ {BTA_PAN_IGNORE, BTA_PAN_IDLE_ST}, + /* BNEP_DATA */ {BTA_PAN_IGNORE, BTA_PAN_IDLE_ST} }; /* state table for open state */ const uint8_t bta_pan_st_open[][BTA_PAN_NUM_COLS] = { - /* API_CLOSE */ {BTA_PAN_API_CLOSE, BTA_PAN_OPEN_ST}, - /* CI_TX_READY */ {BTA_PAN_TX_PATH, BTA_PAN_OPEN_ST}, - /* CI_RX_READY */ {BTA_PAN_RX_PATH, BTA_PAN_OPEN_ST}, - /* CI_TX_FLOW */ {BTA_PAN_TX_FLOW, BTA_PAN_OPEN_ST}, - /* CI_RX_WRITE */ {BTA_PAN_IGNORE, BTA_PAN_OPEN_ST}, - /* CI_RX_WRITEBUF */ {BTA_PAN_WRITE_BUF, BTA_PAN_OPEN_ST}, - /* PAN_CONN_OPEN */ {BTA_PAN_IGNORE, BTA_PAN_OPEN_ST}, - /* PAN_CONN_CLOSE */ {BTA_PAN_CONN_CLOSE, BTA_PAN_IDLE_ST}, - /* FLOW_ENABLE */ {BTA_PAN_RX_PATH, BTA_PAN_OPEN_ST}, - /* BNEP_DATA */ {BTA_PAN_TX_PATH, BTA_PAN_OPEN_ST}}; + /* API_CLOSE */ {BTA_PAN_API_CLOSE, BTA_PAN_OPEN_ST}, + /* CI_TX_READY */ {BTA_PAN_TX_PATH, BTA_PAN_OPEN_ST}, + /* CI_RX_READY */ {BTA_PAN_RX_PATH, BTA_PAN_OPEN_ST}, + /* CI_TX_FLOW */ {BTA_PAN_TX_FLOW, BTA_PAN_OPEN_ST}, + /* CI_RX_WRITE */ {BTA_PAN_IGNORE, BTA_PAN_OPEN_ST}, + /* CI_RX_WRITEBUF */ {BTA_PAN_WRITE_BUF, BTA_PAN_OPEN_ST}, + /* PAN_CONN_OPEN */ {BTA_PAN_IGNORE, BTA_PAN_OPEN_ST}, + /* PAN_CONN_CLOSE */ {BTA_PAN_CONN_CLOSE, BTA_PAN_IDLE_ST}, + /* FLOW_ENABLE */ {BTA_PAN_RX_PATH, BTA_PAN_OPEN_ST}, + /* BNEP_DATA */ {BTA_PAN_TX_PATH, BTA_PAN_OPEN_ST}}; /* state table for closing state */ const uint8_t bta_pan_st_closing[][BTA_PAN_NUM_COLS] = { - /* API_CLOSE */ {BTA_PAN_IGNORE, BTA_PAN_CLOSING_ST}, - /* CI_TX_READY */ {BTA_PAN_TX_PATH, BTA_PAN_CLOSING_ST}, - /* CI_RX_READY */ {BTA_PAN_RX_PATH, BTA_PAN_CLOSING_ST}, - /* CI_TX_FLOW */ {BTA_PAN_TX_FLOW, BTA_PAN_CLOSING_ST}, - /* CI_RX_WRITE */ {BTA_PAN_IGNORE, BTA_PAN_CLOSING_ST}, - /* CI_RX_WRITEBUF */ {BTA_PAN_FREE_BUF, BTA_PAN_CLOSING_ST}, - /* PAN_CONN_OPEN */ {BTA_PAN_IGNORE, BTA_PAN_CLOSING_ST}, - /* PAN_CONN_CLOSE */ {BTA_PAN_CONN_CLOSE, BTA_PAN_IDLE_ST}, - /* FLOW_ENABLE */ {BTA_PAN_RX_PATH, BTA_PAN_CLOSING_ST}, - /* BNEP_DATA */ {BTA_PAN_TX_PATH, BTA_PAN_CLOSING_ST}}; + /* API_CLOSE */ {BTA_PAN_IGNORE, BTA_PAN_CLOSING_ST}, + /* CI_TX_READY */ {BTA_PAN_TX_PATH, BTA_PAN_CLOSING_ST}, + /* CI_RX_READY */ {BTA_PAN_RX_PATH, BTA_PAN_CLOSING_ST}, + /* CI_TX_FLOW */ {BTA_PAN_TX_FLOW, BTA_PAN_CLOSING_ST}, + /* CI_RX_WRITE */ {BTA_PAN_IGNORE, BTA_PAN_CLOSING_ST}, + /* CI_RX_WRITEBUF */ {BTA_PAN_FREE_BUF, BTA_PAN_CLOSING_ST}, + /* PAN_CONN_OPEN */ {BTA_PAN_IGNORE, BTA_PAN_CLOSING_ST}, + /* PAN_CONN_CLOSE */ {BTA_PAN_CONN_CLOSE, BTA_PAN_IDLE_ST}, + /* FLOW_ENABLE */ {BTA_PAN_RX_PATH, BTA_PAN_CLOSING_ST}, + /* BNEP_DATA */ {BTA_PAN_TX_PATH, BTA_PAN_CLOSING_ST}}; /* type for state table */ typedef const uint8_t (*tBTA_PAN_ST_TBL)[BTA_PAN_NUM_COLS]; /* state table */ -const tBTA_PAN_ST_TBL bta_pan_st_tbl[] = {bta_pan_st_idle, bta_pan_st_open, - bta_pan_st_closing}; +const tBTA_PAN_ST_TBL bta_pan_st_tbl[] = {bta_pan_st_idle, bta_pan_st_open, bta_pan_st_closing}; /***************************************************************************** * Global data @@ -159,14 +158,12 @@ tBTA_PAN_SCB* bta_pan_scb_alloc(void) { * Returns void * ******************************************************************************/ -void bta_pan_sm_execute(tBTA_PAN_SCB* p_scb, uint16_t event, - tBTA_PAN_DATA* p_data) { +void bta_pan_sm_execute(tBTA_PAN_SCB* p_scb, uint16_t event, tBTA_PAN_DATA* p_data) { tBTA_PAN_ST_TBL state_table; uint8_t action; int i; - log::verbose("PAN scb={} event=0x{:x} state={}", bta_pan_scb_to_idx(p_scb), - event, p_scb->state); + log::verbose("PAN scb={} event=0x{:x} state={}", bta_pan_scb_to_idx(p_scb), event, p_scb->state); /* look up the state table for the current state */ state_table = bta_pan_st_tbl[p_scb->state]; @@ -179,9 +176,10 @@ void bta_pan_sm_execute(tBTA_PAN_SCB* p_scb, uint16_t event, /* execute action functions */ for (i = 0; i < BTA_PAN_ACTIONS; i++) { action = state_table[event][i]; - log::assert_that(action < BTA_PAN_MAX_ACTIONS, - "assert failed: action < BTA_PAN_MAX_ACTIONS"); - if (action == BTA_PAN_IGNORE) continue; + log::assert_that(action < BTA_PAN_MAX_ACTIONS, "assert failed: action < BTA_PAN_MAX_ACTIONS"); + if (action == BTA_PAN_IGNORE) { + continue; + } (*bta_pan_action[action])(p_scb, p_data); } } @@ -267,9 +265,7 @@ void bta_pan_scb_dealloc(tBTA_PAN_SCB* p_scb) { * Returns Index of scb. * ******************************************************************************/ -uint8_t bta_pan_scb_to_idx(tBTA_PAN_SCB* p_scb) { - return ((uint8_t)(p_scb - bta_pan_cb.scb)) + 1; -} +uint8_t bta_pan_scb_to_idx(tBTA_PAN_SCB* p_scb) { return ((uint8_t)(p_scb - bta_pan_cb.scb)) + 1; } /******************************************************************************* * diff --git a/system/bta/pb/bta_pbs_int.h b/system/bta/pb/bta_pbs_int.h index 524963a5db0..4a061999834 100644 --- a/system/bta/pb/bta_pbs_int.h +++ b/system/bta/pb/bta_pbs_int.h @@ -40,19 +40,17 @@ #define BTA_PBS_REPOSIT_LOCAL 0x01 /* Local PhoneBook */ #define BTA_PBS_REPOSIT_SIM 0x02 /* SIM card PhoneBook */ -#define BTA_PBS_TARGET_UUID \ - "\x79\x61\x35\xf0\xf0\xc5\x11\xd8\x09\x66\x08\x00\x20\x0c\x9a\x66" +#define BTA_PBS_TARGET_UUID "\x79\x61\x35\xf0\xf0\xc5\x11\xd8\x09\x66\x08\x00\x20\x0c\x9a\x66" #define BTA_PBS_UUID_LENGTH 16 -#define BTA_PBS_MAX_AUTH_KEY_SIZE \ - 16 /* Must not be greater than OBX_MAX_AUTH_KEY_SIZE */ +#define BTA_PBS_MAX_AUTH_KEY_SIZE 16 /* Must not be greater than OBX_MAX_AUTH_KEY_SIZE */ #define BTA_PBS_DEFAULT_VERSION 0x0101 /* for PBAP PSE version 1.1 */ /* Configuration structure */ typedef struct { - uint8_t realm_charset; /* Server only */ - bool userid_req; /* true if user id is required during obex authentication - (Server only) */ + uint8_t realm_charset; /* Server only */ + bool userid_req; /* true if user id is required during obex authentication + (Server only) */ uint8_t supported_features; /* Server supported features */ uint8_t supported_repositories; /* Server supported repositories */ diff --git a/system/bta/ras/ras_client.cc b/system/bta/ras/ras_client.cc index 84ee87c562a..dd4ea43ca75 100644 --- a/system/bta/ras/ras_client.cc +++ b/system/bta/ras/ras_client.cc @@ -37,7 +37,7 @@ RasClientImpl* instance; enum CallbackDataType { VENDOR_SPECIFIC_REPLY }; class RasClientImpl : public bluetooth::ras::RasClient { - public: +public: struct GattWriteCallbackData { const CallbackDataType type_; }; @@ -74,8 +74,7 @@ class RasClientImpl : public bluetooth::ras::RasClient { return nullptr; } - VendorSpecificCharacteristic* GetVendorSpecificCharacteristic( - const bluetooth::Uuid& uuid) { + VendorSpecificCharacteristic* GetVendorSpecificCharacteristic(const bluetooth::Uuid& uuid) { for (auto& characteristic : vendor_specific_characteristics_) { if (characteristic.characteristicUuid_ == uuid) { return &characteristic; @@ -87,23 +86,23 @@ class RasClientImpl : public bluetooth::ras::RasClient { void Initialize() override { BTA_GATTC_AppRegister( - [](tBTA_GATTC_EVT event, tBTA_GATTC* p_data) { - if (instance && p_data) instance->GattcCallback(event, p_data); - }, - base::Bind([](uint8_t client_id, uint8_t status) { - if (status != GATT_SUCCESS) { - log::error("Can't start Gatt client for Ranging Service"); - return; - } - log::info("Initialize, client_id {}", client_id); - instance->gatt_if_ = client_id; - }), - true); + [](tBTA_GATTC_EVT event, tBTA_GATTC* p_data) { + if (instance && p_data) { + instance->GattcCallback(event, p_data); + } + }, + base::Bind([](uint8_t client_id, uint8_t status) { + if (status != GATT_SUCCESS) { + log::error("Can't start Gatt client for Ranging Service"); + return; + } + log::info("Initialize, client_id {}", client_id); + instance->gatt_if_ = client_id; + }), + true); } - void RegisterCallbacks(bluetooth::ras::RasClientCallbacks* callbacks) { - callbacks_ = callbacks; - } + void RegisterCallbacks(bluetooth::ras::RasClientCallbacks* callbacks) { callbacks_ = callbacks; } void Connect(const RawAddress& address) override { tBLE_BD_ADDR ble_bd_addr; @@ -112,32 +111,28 @@ class RasClientImpl : public bluetooth::ras::RasClient { auto tracker = FindTrackerByAddress(ble_bd_addr.bda); if (tracker == nullptr) { - trackers_.emplace_back( - std::make_shared(ble_bd_addr.bda, address)); + trackers_.emplace_back(std::make_shared(ble_bd_addr.bda, address)); } else if (tracker->is_connected_) { log::info("Already connected"); - uint16_t att_handle = - tracker - ->FindCharacteristicByUuid(kRasRealTimeRangingDataCharacteristic) - ->value_handle; - callbacks_->OnConnected(address, att_handle, - tracker->vendor_specific_characteristics_); + uint16_t att_handle = tracker->FindCharacteristicByUuid(kRasRealTimeRangingDataCharacteristic) + ->value_handle; + callbacks_->OnConnected(address, att_handle, tracker->vendor_specific_characteristics_); return; } BTA_GATTC_Open(gatt_if_, ble_bd_addr.bda, BTM_BLE_DIRECT_CONNECTION, false); } void SendVendorSpecificReply( - const RawAddress& address, - const std::vector& vendor_specific_data) { + const RawAddress& address, + const std::vector& vendor_specific_data) { tBLE_BD_ADDR ble_bd_addr; ResolveAddress(ble_bd_addr, address); log::info("address {}, resolve {}", address, ble_bd_addr.bda); auto tracker = FindTrackerByAddress(ble_bd_addr.bda); for (auto& vendor_specific_characteristic : vendor_specific_data) { - auto characteristic = tracker->FindCharacteristicByUuid( - vendor_specific_characteristic.characteristicUuid_); + auto characteristic = + tracker->FindCharacteristicByUuid(vendor_specific_characteristic.characteristicUuid_); if (characteristic == nullptr) { log::warn("Can't find characteristic uuid {}", vendor_specific_characteristic.characteristicUuid_); @@ -146,10 +141,9 @@ class RasClientImpl : public bluetooth::ras::RasClient { log::debug("write to remote, uuid {}, len {}", vendor_specific_characteristic.characteristicUuid_, vendor_specific_characteristic.value_.size()); - BTA_GATTC_WriteCharValue( - tracker->conn_id_, characteristic->value_handle, GATT_WRITE, - vendor_specific_characteristic.value_, GATT_AUTH_REQ_NO_MITM, - GattWriteCallback, &gatt_write_callback_data_); + BTA_GATTC_WriteCharValue(tracker->conn_id_, characteristic->value_handle, GATT_WRITE, + vendor_specific_characteristic.value_, GATT_AUTH_REQ_NO_MITM, + GattWriteCallback, &gatt_write_callback_data_); } } @@ -175,13 +169,11 @@ class RasClientImpl : public bluetooth::ras::RasClient { } void OnGattConnected(const tBTA_GATTC_OPEN& evt) { - log::info("{}, conn_id=0x{:04x}, transport:{}, status:{}", evt.remote_bda, - evt.conn_id, bt_transport_text(evt.transport), - gatt_status_text(evt.status)); + log::info("{}, conn_id=0x{:04x}, transport:{}, status:{}", evt.remote_bda, evt.conn_id, + bt_transport_text(evt.transport), gatt_status_text(evt.status)); if (evt.transport != BT_TRANSPORT_LE) { - log::warn("Only LE connection is allowed (transport {})", - bt_transport_text(evt.transport)); + log::warn("Only LE connection is allowed (transport {})", bt_transport_text(evt.transport)); BTA_GATTC_Close(evt.conn_id); return; } @@ -204,9 +196,8 @@ class RasClientImpl : public bluetooth::ras::RasClient { } void OnGattDisconnected(const tBTA_GATTC_CLOSE& evt) { - log::info("{}, conn_id=0x{:04x}, status:{}, reason:{}", evt.remote_bda, - evt.conn_id, gatt_status_text(evt.status), - gatt_disconnection_reason_text(evt.reason)); + log::info("{}, conn_id=0x{:04x}, status:{}, reason:{}", evt.remote_bda, evt.conn_id, + gatt_status_text(evt.status), gatt_disconnection_reason_text(evt.reason)); auto tracker = FindTrackerByAddress(evt.remote_bda); if (tracker == nullptr) { @@ -226,8 +217,7 @@ class RasClientImpl : public bluetooth::ras::RasClient { // Get Ranging Service bool service_found = false; - const std::list* all_services = - BTA_GATTC_GetServices(evt.conn_id); + const std::list* all_services = BTA_GATTC_GetServices(evt.conn_id); for (const auto& service : *all_services) { if (service.uuid == kRangingService) { tracker->service_ = &service; @@ -246,41 +236,36 @@ class RasClientImpl : public bluetooth::ras::RasClient { // Read Vendor Specific Uuid if (!tracker->vendor_specific_characteristics_.empty()) { - for (auto& vendor_specific_characteristic : - tracker->vendor_specific_characteristics_) { + for (auto& vendor_specific_characteristic : tracker->vendor_specific_characteristics_) { log::debug("Read vendor specific characteristic uuid {}", vendor_specific_characteristic.characteristicUuid_); auto characteristic = tracker->FindCharacteristicByUuid( - vendor_specific_characteristic.characteristicUuid_); + vendor_specific_characteristic.characteristicUuid_); BTA_GATTC_ReadCharacteristic( - tracker->conn_id_, characteristic->value_handle, - GATT_AUTH_REQ_NO_MITM, - [](uint16_t conn_id, tGATT_STATUS status, uint16_t handle, - uint16_t len, uint8_t* value, void* data) { - instance->OnReadCharacteristicCallback(conn_id, status, handle, - len, value, data); - }, - nullptr); + tracker->conn_id_, characteristic->value_handle, GATT_AUTH_REQ_NO_MITM, + [](uint16_t conn_id, tGATT_STATUS status, uint16_t handle, uint16_t len, + uint8_t* value, void* data) { + instance->OnReadCharacteristicCallback(conn_id, status, handle, len, value, data); + }, + nullptr); } } // Read Ras Features log::info("Read Ras Features"); - auto characteristic = - tracker->FindCharacteristicByUuid(kRasFeaturesCharacteristic); + auto characteristic = tracker->FindCharacteristicByUuid(kRasFeaturesCharacteristic); if (characteristic == nullptr) { log::error("Can not find Characteristic for Ras Features"); return; } BTA_GATTC_ReadCharacteristic( - tracker->conn_id_, characteristic->value_handle, GATT_AUTH_REQ_NO_MITM, - [](uint16_t conn_id, tGATT_STATUS status, uint16_t handle, uint16_t len, - uint8_t* value, void* data) { - instance->OnReadCharacteristicCallback(conn_id, status, handle, len, - value, data); - }, - nullptr); + tracker->conn_id_, characteristic->value_handle, GATT_AUTH_REQ_NO_MITM, + [](uint16_t conn_id, tGATT_STATUS status, uint16_t handle, uint16_t len, uint8_t* value, + void* data) { + instance->OnReadCharacteristicCallback(conn_id, status, handle, len, value, data); + }, + nullptr); SubscribeCharacteristic(tracker, kRasControlPointCharacteristic); } @@ -298,8 +283,8 @@ class RasClientImpl : public bluetooth::ras::RasClient { } uint16_t uuid_16bit = characteristic->uuid.As16Bit(); - log::debug("Handle uuid 0x{:04x}, {}, size {}", uuid_16bit, - getUuidName(characteristic->uuid), evt.len); + log::debug("Handle uuid 0x{:04x}, {}, size {}", uuid_16bit, getUuidName(characteristic->uuid), + evt.len); switch (uuid_16bit) { case kRasRealTimeRangingDataCharacteristic16bit: @@ -318,23 +303,19 @@ class RasClientImpl : public bluetooth::ras::RasClient { } } - void OnRemoteData(const tBTA_GATTC_NOTIFY& evt, - std::shared_ptr tracker) { + void OnRemoteData(const tBTA_GATTC_NOTIFY& evt, std::shared_ptr tracker) { std::vector data; data.resize(evt.len); std::copy(evt.value, evt.value + evt.len, data.begin()); callbacks_->OnRemoteData(tracker->address_for_cs_, data); } - void OnControlPointEvent(const tBTA_GATTC_NOTIFY& evt, - std::shared_ptr tracker) { + void OnControlPointEvent(const tBTA_GATTC_NOTIFY& evt, std::shared_ptr tracker) { switch (evt.value[0]) { case (uint8_t)EventCode::COMPLETE_RANGING_DATA_RESPONSE: { uint16_t ranging_counter = evt.value[1]; ranging_counter |= (evt.value[2] << 8); - log::debug( - "Received complete ranging data response, ranging_counter: {}", - ranging_counter); + log::debug("Received complete ranging data response, ranging_counter: {}", ranging_counter); AckRangingData(ranging_counter, tracker); } break; case (uint8_t)EventCode::RESPONSE_CODE: { @@ -346,8 +327,7 @@ class RasClientImpl : public bluetooth::ras::RasClient { } } - void OnRangingDataReady(const tBTA_GATTC_NOTIFY& evt, - std::shared_ptr tracker) { + void OnRangingDataReady(const tBTA_GATTC_NOTIFY& evt, std::shared_ptr tracker) { if (evt.len != kRingingCounterSize) { log::error("Invalid len for ranging data ready"); return; @@ -361,16 +341,14 @@ class RasClientImpl : public bluetooth::ras::RasClient { GetRangingData(ranging_counter, tracker); } - void GetRangingData(uint16_t ranging_counter, - std::shared_ptr tracker) { + void GetRangingData(uint16_t ranging_counter, std::shared_ptr tracker) { log::debug("ranging_counter:{}", ranging_counter); if (tracker->handling_on_demand_data_) { log::warn("Handling other procedure, skip"); return; } - auto characteristic = - tracker->FindCharacteristicByUuid(kRasControlPointCharacteristic); + auto characteristic = tracker->FindCharacteristicByUuid(kRasControlPointCharacteristic); if (characteristic == nullptr) { log::warn("Can't find characteristic for RAS-CP"); return; @@ -381,16 +359,13 @@ class RasClientImpl : public bluetooth::ras::RasClient { value[0] = (uint8_t)Opcode::GET_RANGING_DATA; value[1] = (uint8_t)(ranging_counter & 0xFF); value[2] = (uint8_t)((ranging_counter >> 8) & 0xFF); - BTA_GATTC_WriteCharValue(tracker->conn_id_, characteristic->value_handle, - GATT_WRITE, value, GATT_AUTH_REQ_NO_MITM, - GattWriteCallback, nullptr); + BTA_GATTC_WriteCharValue(tracker->conn_id_, characteristic->value_handle, GATT_WRITE, value, + GATT_AUTH_REQ_NO_MITM, GattWriteCallback, nullptr); } - void AckRangingData(uint16_t ranging_counter, - std::shared_ptr tracker) { + void AckRangingData(uint16_t ranging_counter, std::shared_ptr tracker) { log::debug("ranging_counter:{}", ranging_counter); - auto characteristic = - tracker->FindCharacteristicByUuid(kRasControlPointCharacteristic); + auto characteristic = tracker->FindCharacteristicByUuid(kRasControlPointCharacteristic); if (characteristic == nullptr) { log::warn("Can't find characteristic for RAS-CP"); return; @@ -400,22 +375,18 @@ class RasClientImpl : public bluetooth::ras::RasClient { value[0] = (uint8_t)Opcode::ACK_RANGING_DATA; value[1] = (uint8_t)(ranging_counter & 0xFF); value[2] = (uint8_t)((ranging_counter >> 8) & 0xFF); - BTA_GATTC_WriteCharValue(tracker->conn_id_, characteristic->value_handle, - GATT_WRITE, value, GATT_AUTH_REQ_NO_MITM, - GattWriteCallback, nullptr); + BTA_GATTC_WriteCharValue(tracker->conn_id_, characteristic->value_handle, GATT_WRITE, value, + GATT_AUTH_REQ_NO_MITM, GattWriteCallback, nullptr); if (ranging_counter != tracker->latest_ranging_counter_) { GetRangingData(tracker->latest_ranging_counter_, tracker); } } - void GattWriteCallbackForVendorSpecificData(uint16_t conn_id, - tGATT_STATUS status, - uint16_t handle, - const uint8_t* value, + void GattWriteCallbackForVendorSpecificData(uint16_t conn_id, tGATT_STATUS status, + uint16_t handle, const uint8_t* value, GattWriteCallbackData* data) { if (data != nullptr) { - GattWriteCallbackData* structPtr = - static_cast(data); + GattWriteCallbackData* structPtr = static_cast(data); if (structPtr->type_ == CallbackDataType::VENDOR_SPECIFIC_REPLY) { log::info("Write vendor specific reply complete"); auto tracker = FindTrackerByHandle(conn_id); @@ -424,24 +395,22 @@ class RasClientImpl : public bluetooth::ras::RasClient { tracker->writeReplySuccessCounter_++; } else { log::error( - "Fail to write vendor specific reply conn_id {}, status {}, " - "handle {}", - conn_id, gatt_status_text(status), handle); + "Fail to write vendor specific reply conn_id {}, status {}, " + "handle {}", + conn_id, gatt_status_text(status), handle); } // All reply complete - if (tracker->writeReplyCounter_ == - tracker->vendor_specific_characteristics_.size()) { + if (tracker->writeReplyCounter_ == tracker->vendor_specific_characteristics_.size()) { log::info( - "All vendor specific reply write complete, size {} " - "successCounter {}", - tracker->vendor_specific_characteristics_.size(), - tracker->writeReplySuccessCounter_); + "All vendor specific reply write complete, size {} " + "successCounter {}", + tracker->vendor_specific_characteristics_.size(), + tracker->writeReplySuccessCounter_); bool success = tracker->writeReplySuccessCounter_ == tracker->vendor_specific_characteristics_.size(); tracker->writeReplyCounter_ = 0; tracker->writeReplySuccessCounter_ = 0; - callbacks_->OnWriteVendorSpecificReplyComplete( - tracker->address_for_cs_, success); + callbacks_->OnWriteVendorSpecificReplyComplete(tracker->address_for_cs_, success); } return; } @@ -472,16 +441,14 @@ class RasClientImpl : public bluetooth::ras::RasClient { } } - static void GattWriteCallback(uint16_t conn_id, tGATT_STATUS status, - uint16_t handle, uint16_t len, - const uint8_t* value, void* data) { + static void GattWriteCallback(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, + uint16_t len, const uint8_t* value, void* data) { if (instance != nullptr) { if (data != nullptr) { - GattWriteCallbackData* structPtr = - static_cast(data); + GattWriteCallbackData* structPtr = static_cast(data); if (structPtr->type_ == CallbackDataType::VENDOR_SPECIFIC_REPLY) { - instance->GattWriteCallbackForVendorSpecificData( - conn_id, status, handle, value, structPtr); + instance->GattWriteCallbackForVendorSpecificData(conn_id, status, handle, value, + structPtr); return; } } @@ -489,8 +456,7 @@ class RasClientImpl : public bluetooth::ras::RasClient { } } - void SubscribeCharacteristic(std::shared_ptr tracker, - const Uuid uuid) { + void SubscribeCharacteristic(std::shared_ptr tracker, const Uuid uuid) { auto characteristic = tracker->FindCharacteristicByUuid(uuid); if (characteristic == nullptr) { log::warn("Can't find characteristic 0x{:04x}", uuid.As16Bit()); @@ -502,8 +468,8 @@ class RasClientImpl : public bluetooth::ras::RasClient { return; } - tGATT_STATUS register_status = BTA_GATTC_RegisterForNotifications( - gatt_if_, tracker->address_, characteristic->value_handle); + tGATT_STATUS register_status = BTA_GATTC_RegisterForNotifications(gatt_if_, tracker->address_, + characteristic->value_handle); if (register_status != GATT_SUCCESS) { log::error("Fail to register, {}", gatt_status_text(register_status)); return; @@ -518,44 +484,39 @@ class RasClientImpl : public bluetooth::ras::RasClient { UINT16_TO_STREAM(value_ptr, GATT_CHAR_CLIENT_CONFIG_INDICTION); } BTA_GATTC_WriteCharDescr( - tracker->conn_id_, ccc_handle, value, GATT_AUTH_REQ_NONE, - [](uint16_t conn_id, tGATT_STATUS status, uint16_t handle, uint16_t len, - const uint8_t* value, void* data) { - if (instance) - instance->OnDescriptorWrite(conn_id, status, handle, len, value, - data); - }, - nullptr); + tracker->conn_id_, ccc_handle, value, GATT_AUTH_REQ_NONE, + [](uint16_t conn_id, tGATT_STATUS status, uint16_t handle, uint16_t len, + const uint8_t* value, void* data) { + if (instance) { + instance->OnDescriptorWrite(conn_id, status, handle, len, value, data); + } + }, + nullptr); } - void OnDescriptorWrite(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, - uint16_t len, const uint8_t* value, void* data) { - log::info("conn_id:{}, handle:{}, status:{}", conn_id, handle, - gatt_status_text(status)); + void OnDescriptorWrite(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, uint16_t len, + const uint8_t* value, void* data) { + log::info("conn_id:{}, handle:{}, status:{}", conn_id, handle, gatt_status_text(status)); } void ListCharacteristic(std::shared_ptr tracker) { for (auto& characteristic : tracker->service_->characteristics) { - bool vendor_specific = - !IsRangingServiceCharacteristic(characteristic.uuid); + bool vendor_specific = !IsRangingServiceCharacteristic(characteristic.uuid); log::info( - "{}Characteristic uuid:0x{:04x}, handle:0x{:04x}, " - "properties:0x{:02x}, " - "{}", - vendor_specific ? "Vendor Specific " : "", - characteristic.uuid.As16Bit(), characteristic.value_handle, - characteristic.properties, getUuidName(characteristic.uuid)); + "{}Characteristic uuid:0x{:04x}, handle:0x{:04x}, " + "properties:0x{:02x}, " + "{}", + vendor_specific ? "Vendor Specific " : "", characteristic.uuid.As16Bit(), + characteristic.value_handle, characteristic.properties, + getUuidName(characteristic.uuid)); if (vendor_specific) { VendorSpecificCharacteristic vendor_specific_characteristic; - vendor_specific_characteristic.characteristicUuid_ = - characteristic.uuid; - tracker->vendor_specific_characteristics_.emplace_back( - vendor_specific_characteristic); + vendor_specific_characteristic.characteristicUuid_ = characteristic.uuid; + tracker->vendor_specific_characteristics_.emplace_back(vendor_specific_characteristic); } for (auto& descriptor : characteristic.descriptors) { - log::info("\tDescriptor uuid:0x{:04x}, handle:0x{:04x}, {}", - descriptor.uuid.As16Bit(), descriptor.handle, - getUuidName(descriptor.uuid)); + log::info("\tDescriptor uuid:0x{:04x}, handle:0x{:04x}, {}", descriptor.uuid.As16Bit(), + descriptor.handle, getUuidName(descriptor.uuid)); } } } @@ -566,9 +527,8 @@ class RasClientImpl : public bluetooth::ras::RasClient { maybe_resolve_address(&ble_bd_addr.bda, &ble_bd_addr.type); } - void OnReadCharacteristicCallback(uint16_t conn_id, tGATT_STATUS status, - uint16_t handle, uint16_t len, - uint8_t* value, void* data) { + void OnReadCharacteristicCallback(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, + uint16_t len, uint8_t* value, void* data) { log::info("conn_id: {}, handle: {}, len: {}", conn_id, handle, len); if (status != GATT_SUCCESS) { log::error("Fail with status {}", gatt_status_text(status)); @@ -586,7 +546,7 @@ class RasClientImpl : public bluetooth::ras::RasClient { } auto vendor_specific_characteristic = - tracker->GetVendorSpecificCharacteristic(characteristic->uuid); + tracker->GetVendorSpecificCharacteristic(characteristic->uuid); if (vendor_specific_characteristic != nullptr) { log::info("Update vendor specific data, uuid: {}", vendor_specific_characteristic->characteristicUuid_); @@ -597,8 +557,7 @@ class RasClientImpl : public bluetooth::ras::RasClient { } uint16_t uuid_16bit = characteristic->uuid.As16Bit(); - log::info("Handle uuid 0x{:04x}, {}", uuid_16bit, - getUuidName(characteristic->uuid)); + log::info("Handle uuid 0x{:04x}, {}", uuid_16bit, getUuidName(characteristic->uuid)); switch (uuid_16bit) { case kRasFeaturesCharacteristic16bit: { @@ -609,22 +568,18 @@ class RasClientImpl : public bluetooth::ras::RasClient { STREAM_TO_UINT32(tracker->remote_supported_features_, value); log::info("Remote supported features : {}", getFeaturesString(tracker->remote_supported_features_)); - if (tracker->remote_supported_features_ & - feature::kRealTimeRangingData) { + if (tracker->remote_supported_features_ & feature::kRealTimeRangingData) { log::info("Subscribe Real-time Ranging Data"); - SubscribeCharacteristic(tracker, - kRasRealTimeRangingDataCharacteristic); + SubscribeCharacteristic(tracker, kRasRealTimeRangingDataCharacteristic); } else { log::info("Subscribe On-demand Ranging Data"); SubscribeCharacteristic(tracker, kRasOnDemandDataCharacteristic); SubscribeCharacteristic(tracker, kRasRangingDataReadyCharacteristic); - SubscribeCharacteristic(tracker, - kRasRangingDataOverWrittenCharacteristic); + SubscribeCharacteristic(tracker, kRasRangingDataOverWrittenCharacteristic); } - uint16_t att_handle = tracker - ->FindCharacteristicByUuid( - kRasRealTimeRangingDataCharacteristic) - ->value_handle; + uint16_t att_handle = + tracker->FindCharacteristicByUuid(kRasRealTimeRangingDataCharacteristic) + ->value_handle; callbacks_->OnConnected(tracker->address_for_cs_, att_handle, tracker->vendor_specific_characteristics_); } break; @@ -676,8 +631,7 @@ class RasClientImpl : public bluetooth::ras::RasClient { return nullptr; } - std::shared_ptr FindTrackerByAddress( - const RawAddress& address) const { + std::shared_ptr FindTrackerByAddress(const RawAddress& address) const { for (auto tracker : trackers_) { if (tracker->address_ == address) { return tracker; @@ -686,12 +640,11 @@ class RasClientImpl : public bluetooth::ras::RasClient { return nullptr; } - private: +private: uint16_t gatt_if_; std::list> trackers_; bluetooth::ras::RasClientCallbacks* callbacks_; - GattWriteCallbackData gatt_write_callback_data_{ - CallbackDataType::VENDOR_SPECIFIC_REPLY}; + GattWriteCallbackData gatt_write_callback_data_{CallbackDataType::VENDOR_SPECIFIC_REPLY}; }; } // namespace diff --git a/system/bta/ras/ras_server.cc b/system/bta/ras/ras_server.cc index 37a58a35172..cdeb50dec92 100644 --- a/system/bta/ras/ras_server.cc +++ b/system/bta/ras/ras_server.cc @@ -42,7 +42,7 @@ static constexpr uint32_t kSupportedFeatures = feature::kRealTimeRangingData; static constexpr uint16_t kBufferSize = 3; class RasServerImpl : public bluetooth::ras::RasServer { - public: +public: struct RasCharacteristic { bluetooth::Uuid uuid_; uint16_t attribute_handle_; @@ -51,8 +51,7 @@ class RasServerImpl : public bluetooth::ras::RasServer { // Struct to save data of specific ranging counter struct DataBuffer { - DataBuffer(uint16_t ranging_counter) - : ranging_counter_(ranging_counter), segments_() {} + DataBuffer(uint16_t ranging_counter) : ranging_counter_(ranging_counter), segments_() {} uint16_t ranging_counter_; std::vector> segments_; }; @@ -73,26 +72,24 @@ class RasServerImpl : public bluetooth::ras::RasServer { }; void Initialize() { - Uuid uuid = - Uuid::From128BitBE(bluetooth::os::GenerateRandom()); + Uuid uuid = Uuid::From128BitBE(bluetooth::os::GenerateRandom()); app_uuid_ = uuid; log::info("Register server with uuid:{}", app_uuid_.ToString()); BTA_GATTS_AppRegister( - app_uuid_, - [](tBTA_GATTS_EVT event, tBTA_GATTS* p_data) { - if (instance && p_data) instance->GattsCallback(event, p_data); - }, - false); + app_uuid_, + [](tBTA_GATTS_EVT event, tBTA_GATTS* p_data) { + if (instance && p_data) { + instance->GattsCallback(event, p_data); + } + }, + false); } - void RegisterCallbacks(bluetooth::ras::RasServerCallbacks* callbacks) { - callbacks_ = callbacks; - } + void RegisterCallbacks(bluetooth::ras::RasServerCallbacks* callbacks) { callbacks_ = callbacks; } void SetVendorSpecificCharacteristic( - const std::vector& - vendor_specific_characteristics) { + const std::vector& vendor_specific_characteristics) { vendor_specific_characteristics_ = vendor_specific_characteristics; } @@ -111,10 +108,10 @@ class RasServerImpl : public bluetooth::ras::RasServer { BTA_GATTS_SendRsp(response.conn_id_, response.trans_id_, status, &p_msg); } - void PushProcedureData(RawAddress address, uint16_t procedure_counter, - bool is_last, std::vector data) { - log::debug("{}, counter:{}, is_last:{}, with size {}", address, - procedure_counter, is_last, data.size()); + void PushProcedureData(RawAddress address, uint16_t procedure_counter, bool is_last, + std::vector data) { + log::debug("{}, counter:{}, is_last:{}, with size {}", address, procedure_counter, is_last, + data.size()); tBLE_BD_ADDR ble_bd_addr; ResolveAddress(ble_bd_addr, address); @@ -123,71 +120,57 @@ class RasServerImpl : public bluetooth::ras::RasServer { return; } ClientTracker& tracker = trackers_[ble_bd_addr.bda]; - uint16_t ccc_real_time = - tracker.ccc_values_[kRasRealTimeRangingDataCharacteristic]; - uint16_t ccc_data_ready = - tracker.ccc_values_[kRasRangingDataReadyCharacteristic]; - uint16_t ccc_data_over_written = - tracker.ccc_values_[kRasRangingDataOverWrittenCharacteristic]; + uint16_t ccc_real_time = tracker.ccc_values_[kRasRealTimeRangingDataCharacteristic]; + uint16_t ccc_data_ready = tracker.ccc_values_[kRasRangingDataReadyCharacteristic]; + uint16_t ccc_data_over_written = tracker.ccc_values_[kRasRangingDataOverWrittenCharacteristic]; if (ccc_real_time != GATT_CLT_CONFIG_NONE) { bool need_confirm = ccc_real_time & GATT_CLT_CONFIG_INDICATION; uint16_t attr_id = - GetCharacteristic(kRasRealTimeRangingDataCharacteristic) - ->attribute_handle_; + GetCharacteristic(kRasRealTimeRangingDataCharacteristic)->attribute_handle_; log::debug("Send Real-time Ranging Data is_last {}", is_last); - BTA_GATTS_HandleValueIndication(tracker.conn_id_, attr_id, data, - need_confirm); + BTA_GATTS_HandleValueIndication(tracker.conn_id_, attr_id, data, need_confirm); } - if (ccc_data_ready == GATT_CLT_CONFIG_NONE && - ccc_data_over_written == GATT_CLT_CONFIG_NONE) { + if (ccc_data_ready == GATT_CLT_CONFIG_NONE && ccc_data_over_written == GATT_CLT_CONFIG_NONE) { return; } std::lock_guard lock(on_demand_ranging_mutex_); - DataBuffer& data_buffer = - InitDataBuffer(ble_bd_addr.bda, procedure_counter); + DataBuffer& data_buffer = InitDataBuffer(ble_bd_addr.bda, procedure_counter); data_buffer.segments_.push_back(data); // Send data ready if (is_last) { - if (ccc_data_ready == GATT_CLT_CONFIG_NONE || - ccc_real_time != GATT_CLT_CONFIG_NONE) { + if (ccc_data_ready == GATT_CLT_CONFIG_NONE || ccc_real_time != GATT_CLT_CONFIG_NONE) { log::debug("Skip Ranging Data Ready"); } else { bool need_confirm = ccc_data_ready & GATT_CLT_CONFIG_INDICATION; - log::debug("Send data ready, ranging_counter {}, total fragment {}", - procedure_counter, data_buffer.segments_.size()); - uint16_t attr_id = GetCharacteristic(kRasRangingDataReadyCharacteristic) - ->attribute_handle_; + log::debug("Send data ready, ranging_counter {}, total fragment {}", procedure_counter, + data_buffer.segments_.size()); + uint16_t attr_id = GetCharacteristic(kRasRangingDataReadyCharacteristic)->attribute_handle_; std::vector value(kRingingCounterSize); value[0] = (procedure_counter & 0xFF); value[1] = (procedure_counter >> 8) & 0xFF; - BTA_GATTS_HandleValueIndication(tracker.conn_id_, attr_id, value, - need_confirm); + BTA_GATTS_HandleValueIndication(tracker.conn_id_, attr_id, value, need_confirm); } } // Send data overwritten if (tracker.buffers_.size() > kBufferSize) { auto begin = tracker.buffers_.begin(); - if (ccc_data_over_written == GATT_CLT_CONFIG_NONE || - ccc_real_time != GATT_CLT_CONFIG_NONE) { + if (ccc_data_over_written == GATT_CLT_CONFIG_NONE || ccc_real_time != GATT_CLT_CONFIG_NONE) { log::debug("Skip Ranging Data Over Written"); tracker.buffers_.erase(begin); return; } bool need_confirm = ccc_data_over_written & GATT_CLT_CONFIG_INDICATION; - log::debug("Send data over written, ranging_counter {}", - begin->ranging_counter_); + log::debug("Send data over written, ranging_counter {}", begin->ranging_counter_); uint16_t attr_id = - GetCharacteristic(kRasRangingDataOverWrittenCharacteristic) - ->attribute_handle_; + GetCharacteristic(kRasRangingDataOverWrittenCharacteristic)->attribute_handle_; std::vector value(kRingingCounterSize); value[0] = (begin->ranging_counter_ & 0xFF); value[1] = (begin->ranging_counter_ >> 8) & 0xFF; - BTA_GATTS_HandleValueIndication(tracker.conn_id_, attr_id, value, - need_confirm); + BTA_GATTS_HandleValueIndication(tracker.conn_id_, attr_id, value, need_confirm); tracker.buffers_.erase(begin); } } @@ -260,13 +243,11 @@ class RasServerImpl : public bluetooth::ras::RasServer { // Real-time Ranging Data (Optional) btgatt_db_element_t real_time_ranging_data_characteristic; - real_time_ranging_data_characteristic.uuid = - kRasRealTimeRangingDataCharacteristic; + real_time_ranging_data_characteristic.uuid = kRasRealTimeRangingDataCharacteristic; real_time_ranging_data_characteristic.type = BTGATT_DB_CHARACTERISTIC; real_time_ranging_data_characteristic.properties = - GATT_CHAR_PROP_BIT_NOTIFY | GATT_CHAR_PROP_BIT_INDICATE; - real_time_ranging_data_characteristic.permissions = - GATT_PERM_READ_ENCRYPTED | key_mask; + GATT_CHAR_PROP_BIT_NOTIFY | GATT_CHAR_PROP_BIT_INDICATE; + real_time_ranging_data_characteristic.permissions = GATT_PERM_READ_ENCRYPTED | key_mask; service.push_back(real_time_ranging_data_characteristic); btgatt_db_element_t ccc_descriptor; ccc_descriptor.uuid = kClientCharacteristicConfiguration; @@ -279,9 +260,8 @@ class RasServerImpl : public bluetooth::ras::RasServer { on_demand_ranging_data_characteristic.uuid = kRasOnDemandDataCharacteristic; on_demand_ranging_data_characteristic.type = BTGATT_DB_CHARACTERISTIC; on_demand_ranging_data_characteristic.properties = - GATT_CHAR_PROP_BIT_NOTIFY | GATT_CHAR_PROP_BIT_INDICATE; - on_demand_ranging_data_characteristic.permissions = - GATT_PERM_READ_ENCRYPTED | key_mask; + GATT_CHAR_PROP_BIT_NOTIFY | GATT_CHAR_PROP_BIT_INDICATE; + on_demand_ranging_data_characteristic.permissions = GATT_PERM_READ_ENCRYPTED | key_mask; service.push_back(on_demand_ranging_data_characteristic); service.push_back(ccc_descriptor); @@ -289,8 +269,7 @@ class RasServerImpl : public bluetooth::ras::RasServer { btgatt_db_element_t ras_control_point; ras_control_point.uuid = kRasControlPointCharacteristic; ras_control_point.type = BTGATT_DB_CHARACTERISTIC; - ras_control_point.properties = - GATT_CHAR_PROP_BIT_WRITE | GATT_CHAR_PROP_BIT_INDICATE; + ras_control_point.properties = GATT_CHAR_PROP_BIT_WRITE | GATT_CHAR_PROP_BIT_INDICATE; ras_control_point.permissions = GATT_PERM_WRITE_ENCRYPTED | key_mask; service.push_back(ras_control_point); service.push_back(ccc_descriptor); @@ -300,45 +279,38 @@ class RasServerImpl : public bluetooth::ras::RasServer { ranging_data_ready_characteristic.uuid = kRasRangingDataReadyCharacteristic; ranging_data_ready_characteristic.type = BTGATT_DB_CHARACTERISTIC; ranging_data_ready_characteristic.properties = - GATT_CHAR_PROP_BIT_NOTIFY | GATT_CHAR_PROP_BIT_INDICATE; - ranging_data_ready_characteristic.permissions = - GATT_PERM_READ_ENCRYPTED | key_mask; + GATT_CHAR_PROP_BIT_NOTIFY | GATT_CHAR_PROP_BIT_INDICATE; + ranging_data_ready_characteristic.permissions = GATT_PERM_READ_ENCRYPTED | key_mask; service.push_back(ranging_data_ready_characteristic); service.push_back(ccc_descriptor); // Ranging Data Overwritten btgatt_db_element_t ranging_data_overwritten_characteristic; - ranging_data_overwritten_characteristic.uuid = - kRasRangingDataOverWrittenCharacteristic; + ranging_data_overwritten_characteristic.uuid = kRasRangingDataOverWrittenCharacteristic; ranging_data_overwritten_characteristic.type = BTGATT_DB_CHARACTERISTIC; ranging_data_overwritten_characteristic.properties = - GATT_CHAR_PROP_BIT_NOTIFY | GATT_CHAR_PROP_BIT_INDICATE; - ranging_data_overwritten_characteristic.permissions = - GATT_PERM_READ_ENCRYPTED | key_mask; + GATT_CHAR_PROP_BIT_NOTIFY | GATT_CHAR_PROP_BIT_INDICATE; + ranging_data_overwritten_characteristic.permissions = GATT_PERM_READ_ENCRYPTED | key_mask; service.push_back(ranging_data_overwritten_characteristic); service.push_back(ccc_descriptor); - for (auto& vendor_specific_characteristics : - vendor_specific_characteristics_) { + for (auto& vendor_specific_characteristics : vendor_specific_characteristics_) { btgatt_db_element_t characteristics; - characteristics.uuid = - vendor_specific_characteristics.characteristicUuid_; + characteristics.uuid = vendor_specific_characteristics.characteristicUuid_; characteristics.type = BTGATT_DB_CHARACTERISTIC; - characteristics.properties = - GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_WRITE; - characteristics.permissions = - GATT_PERM_READ_ENCRYPTED | GATT_PERM_WRITE_ENCRYPTED | key_mask; + characteristics.properties = GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_WRITE; + characteristics.permissions = GATT_PERM_READ_ENCRYPTED | GATT_PERM_WRITE_ENCRYPTED | key_mask; service.push_back(characteristics); - log::info("Push vendor_specific_characteristics uuid {}", - characteristics.uuid); + log::info("Push vendor_specific_characteristics uuid {}", characteristics.uuid); } - BTA_GATTS_AddService( - server_if_, service, - base::BindRepeating([](tGATT_STATUS status, int server_if, - std::vector service) { - if (instance) instance->OnServiceAdded(status, server_if, service); - })); + BTA_GATTS_AddService(server_if_, service, + base::BindRepeating([](tGATT_STATUS status, int server_if, + std::vector service) { + if (instance) { + instance->OnServiceAdded(status, server_if, service); + } + })); } void OnReadCharacteristic(tBTA_GATTS* p_data) { @@ -349,8 +321,8 @@ class RasServerImpl : public bluetooth::ras::RasServer { p_msg.attr_value.handle = read_req_handle; if (characteristics_.find(read_req_handle) == characteristics_.end()) { log::error("Invalid handle 0x{:04x}", read_req_handle); - BTA_GATTS_SendRsp(p_data->req_data.conn_id, p_data->req_data.trans_id, - GATT_INVALID_HANDLE, &p_msg); + BTA_GATTS_SendRsp(p_data->req_data.conn_id, p_data->req_data.trans_id, GATT_INVALID_HANDLE, + &p_msg); return; } @@ -360,10 +332,8 @@ class RasServerImpl : public bluetooth::ras::RasServer { log::debug("Read vendor_specific_characteristic uuid {}", uuid); p_msg.attr_value.len = vendor_specific_characteristic->value_.size(); std::copy(vendor_specific_characteristic->value_.begin(), - vendor_specific_characteristic->value_.end(), - p_msg.attr_value.value); - BTA_GATTS_SendRsp(p_data->req_data.conn_id, p_data->req_data.trans_id, - GATT_SUCCESS, &p_msg); + vendor_specific_characteristic->value_.end(), p_msg.attr_value.value); + BTA_GATTS_SendRsp(p_data->req_data.conn_id, p_data->req_data.trans_id, GATT_SUCCESS, &p_msg); return; } log::info("Read uuid, {}", getUuidName(uuid)); @@ -380,8 +350,7 @@ class RasServerImpl : public bluetooth::ras::RasServer { GATT_ILLEGAL_PARAMETER, &p_msg); return; } - BTA_GATTS_SendRsp(p_data->req_data.conn_id, p_data->req_data.trans_id, - GATT_SUCCESS, &p_msg); + BTA_GATTS_SendRsp(p_data->req_data.conn_id, p_data->req_data.trans_id, GATT_SUCCESS, &p_msg); } void OnReadDescriptor(tBTA_GATTS* p_data) { @@ -394,13 +363,10 @@ class RasServerImpl : public bluetooth::ras::RasServer { p_msg.attr_value.handle = read_req_handle; // Only Client Characteristic Configuration (CCC) descriptor is expected - RasCharacteristic* characteristic = - GetCharacteristicByCccHandle(read_req_handle); + RasCharacteristic* characteristic = GetCharacteristicByCccHandle(read_req_handle); if (characteristic == nullptr) { - log::warn("Can't find Characteristic for CCC Descriptor, handle 0x{:04x}", - read_req_handle); - BTA_GATTS_SendRsp(conn_id, p_data->req_data.trans_id, GATT_INVALID_HANDLE, - &p_msg); + log::warn("Can't find Characteristic for CCC Descriptor, handle 0x{:04x}", read_req_handle); + BTA_GATTS_SendRsp(conn_id, p_data->req_data.trans_id, GATT_INVALID_HANDLE, &p_msg); return; } log::info("Read CCC for uuid, {}", getUuidName(characteristic->uuid_)); @@ -422,23 +388,22 @@ class RasServerImpl : public bluetooth::ras::RasServer { uint16_t len = p_data->req_data.p_data->write_req.len; bool need_rsp = p_data->req_data.p_data->write_req.need_rsp; RawAddress remote_bda = p_data->req_data.remote_bda; - log::info("conn_id:{}, write_req_handle:0x{:04x}, need_rsp{}, len:{}", - conn_id, write_req_handle, need_rsp, len); + log::info("conn_id:{}, write_req_handle:0x{:04x}, need_rsp{}, len:{}", conn_id, + write_req_handle, need_rsp, len); tGATTS_RSP p_msg; p_msg.handle = write_req_handle; if (characteristics_.find(write_req_handle) == characteristics_.end()) { log::error("Invalid handle {}", write_req_handle); - BTA_GATTS_SendRsp(p_data->req_data.conn_id, p_data->req_data.trans_id, - GATT_INVALID_HANDLE, &p_msg); + BTA_GATTS_SendRsp(p_data->req_data.conn_id, p_data->req_data.trans_id, GATT_INVALID_HANDLE, + &p_msg); return; } auto uuid = characteristics_[write_req_handle].uuid_; auto vendor_specific_characteristic = GetVendorSpecificCharacteristic(uuid); if (vendor_specific_characteristic != nullptr) { - WriteVendorSpecificCharacteristic(vendor_specific_characteristic, p_data, - p_msg); + WriteVendorSpecificCharacteristic(vendor_specific_characteristic, p_data, p_msg); return; } log::info("Write uuid, {}", getUuidName(uuid)); @@ -448,20 +413,17 @@ class RasServerImpl : public bluetooth::ras::RasServer { case kRasControlPointCharacteristic16bit: { if (trackers_.find(p_data->req_data.remote_bda) == trackers_.end()) { log::warn("Can't find trackers for {}", p_data->req_data.remote_bda); - BTA_GATTS_SendRsp(conn_id, p_data->req_data.trans_id, - GATT_ILLEGAL_PARAMETER, &p_msg); + BTA_GATTS_SendRsp(conn_id, p_data->req_data.trans_id, GATT_ILLEGAL_PARAMETER, &p_msg); return; } ClientTracker* tracker = &trackers_[p_data->req_data.remote_bda]; if (tracker->handling_control_point_command_) { log::warn("Procedure Already In Progress"); - BTA_GATTS_SendRsp(conn_id, p_data->req_data.trans_id, - GATT_PRC_IN_PROGRESS, &p_msg); + BTA_GATTS_SendRsp(conn_id, p_data->req_data.trans_id, GATT_PRC_IN_PROGRESS, &p_msg); return; } if (need_rsp) { - BTA_GATTS_SendRsp(conn_id, p_data->req_data.trans_id, GATT_SUCCESS, - &p_msg); + BTA_GATTS_SendRsp(conn_id, p_data->req_data.trans_id, GATT_SUCCESS, &p_msg); } HandleControlPoint(tracker, &p_data->req_data.p_data->write_req); } break; @@ -474,15 +436,15 @@ class RasServerImpl : public bluetooth::ras::RasServer { } void WriteVendorSpecificCharacteristic( - VendorSpecificCharacteristic* vendor_specific_characteristic, - tBTA_GATTS* p_data, tGATTS_RSP& p_msg) { + VendorSpecificCharacteristic* vendor_specific_characteristic, tBTA_GATTS* p_data, + tGATTS_RSP& p_msg) { log::debug("uuid {}", vendor_specific_characteristic->characteristicUuid_); uint16_t len = p_data->req_data.p_data->write_req.len; RawAddress remote_bda = p_data->req_data.remote_bda; if (trackers_.find(remote_bda) == trackers_.end()) { - BTA_GATTS_SendRsp(p_data->req_data.conn_id, p_data->req_data.trans_id, - GATT_INVALID_HANDLE, &p_msg); + BTA_GATTS_SendRsp(p_data->req_data.conn_id, p_data->req_data.trans_id, GATT_INVALID_HANDLE, + &p_msg); log::warn("Can't find tracker for remote_bda {}", remote_bda); return; } @@ -495,8 +457,7 @@ class RasServerImpl : public bluetooth::ras::RasServer { vendor_specific_characteristic->reply_value_.assign(value, value + len); tracker.vendor_specific_reply_counter_++; - if (tracker.vendor_specific_reply_counter_ == - vendor_specific_characteristics_.size()) { + if (tracker.vendor_specific_reply_counter_ == vendor_specific_characteristics_.size()) { log::info("All vendor specific characteristics written"); tBLE_BD_ADDR ble_bd_addr; ble_bd_addr.bda = remote_bda; @@ -506,11 +467,9 @@ class RasServerImpl : public bluetooth::ras::RasServer { tracker.pending_write_response_.conn_id_ = p_data->req_data.conn_id; tracker.pending_write_response_.trans_id_ = p_data->req_data.trans_id; tracker.pending_write_response_.write_req_handle_ = p_msg.handle; - callbacks_->OnVendorSpecificReply(ble_bd_addr.bda, - vendor_specific_characteristics_); + callbacks_->OnVendorSpecificReply(ble_bd_addr.bda, vendor_specific_characteristics_); } else { - BTA_GATTS_SendRsp(p_data->req_data.conn_id, p_data->req_data.trans_id, - GATT_SUCCESS, &p_msg); + BTA_GATTS_SendRsp(p_data->req_data.conn_id, p_data->req_data.trans_id, GATT_SUCCESS, &p_msg); } } @@ -519,26 +478,21 @@ class RasServerImpl : public bluetooth::ras::RasServer { uint16_t write_req_handle = p_data->req_data.p_data->write_req.handle; uint16_t len = p_data->req_data.p_data->write_req.len; RawAddress remote_bda = p_data->req_data.remote_bda; - log::info("conn_id:{}, write_req_handle:0x{:04x}, len:{}", conn_id, - write_req_handle, len); + log::info("conn_id:{}, write_req_handle:0x{:04x}, len:{}", conn_id, write_req_handle, len); tGATTS_RSP p_msg; p_msg.handle = write_req_handle; // Only Client Characteristic Configuration (CCC) descriptor is expected - RasCharacteristic* characteristic = - GetCharacteristicByCccHandle(write_req_handle); + RasCharacteristic* characteristic = GetCharacteristicByCccHandle(write_req_handle); if (characteristic == nullptr) { - log::warn("Can't find Characteristic for CCC Descriptor, handle 0x{:04x}", - write_req_handle); - BTA_GATTS_SendRsp(conn_id, p_data->req_data.trans_id, GATT_INVALID_HANDLE, - &p_msg); + log::warn("Can't find Characteristic for CCC Descriptor, handle 0x{:04x}", write_req_handle); + BTA_GATTS_SendRsp(conn_id, p_data->req_data.trans_id, GATT_INVALID_HANDLE, &p_msg); return; } if (trackers_.find(remote_bda) == trackers_.end()) { - BTA_GATTS_SendRsp(conn_id, p_data->req_data.trans_id, - GATT_ILLEGAL_PARAMETER, &p_msg); + BTA_GATTS_SendRsp(conn_id, p_data->req_data.trans_id, GATT_ILLEGAL_PARAMETER, &p_msg); return; } ClientTracker* tracker = &trackers_[p_data->req_data.remote_bda]; @@ -547,28 +501,22 @@ class RasServerImpl : public bluetooth::ras::RasServer { STREAM_TO_UINT16(ccc_value, value); // Check that On-demand and Real-time are not registered at the same time - uint16_t ccc_on_demand_temp = - tracker->ccc_values_[kRasOnDemandDataCharacteristic]; - uint16_t ccc_real_time_temp = - tracker->ccc_values_[kRasRealTimeRangingDataCharacteristic]; + uint16_t ccc_on_demand_temp = tracker->ccc_values_[kRasOnDemandDataCharacteristic]; + uint16_t ccc_real_time_temp = tracker->ccc_values_[kRasRealTimeRangingDataCharacteristic]; if (characteristic->uuid_ == kRasRealTimeRangingDataCharacteristic) { ccc_real_time_temp = ccc_value; } else if (characteristic->uuid_ == kRasOnDemandDataCharacteristic) { ccc_on_demand_temp = ccc_value; } - if (ccc_real_time_temp != GATT_CLT_CONFIG_NONE && - ccc_on_demand_temp != GATT_CLT_CONFIG_NONE) { - log::warn( - "Client Characteristic Configuration Descriptor Improperly " - "Configured"); - BTA_GATTS_SendRsp(conn_id, p_data->req_data.trans_id, GATT_CCC_CFG_ERR, - &p_msg); + if (ccc_real_time_temp != GATT_CLT_CONFIG_NONE && ccc_on_demand_temp != GATT_CLT_CONFIG_NONE) { + log::warn("Client Characteristic Configuration Descriptor Improperly Configured"); + BTA_GATTS_SendRsp(conn_id, p_data->req_data.trans_id, GATT_CCC_CFG_ERR, &p_msg); return; } trackers_[remote_bda].ccc_values_[characteristic->uuid_] = ccc_value; - log::info("Write CCC for {}, conn_id:{}, value:0x{:04x}", - getUuidName(characteristic->uuid_), conn_id, ccc_value); + log::info("Write CCC for {}, conn_id:{}, value:0x{:04x}", getUuidName(characteristic->uuid_), + conn_id, ccc_value); BTA_GATTS_SendRsp(conn_id, p_data->req_data.trans_id, GATT_SUCCESS, &p_msg); } @@ -611,8 +559,7 @@ class RasServerImpl : public bluetooth::ras::RasServer { log::info("ranging_counter:{}", ranging_counter); uint16_t ccc_value = tracker->ccc_values_[kRasOnDemandDataCharacteristic]; - uint16_t attr_id = - GetCharacteristic(kRasOnDemandDataCharacteristic)->attribute_handle_; + uint16_t attr_id = GetCharacteristic(kRasOnDemandDataCharacteristic)->attribute_handle_; bool need_confirm = ccc_value & GATT_CLT_CONFIG_INDICATION; std::lock_guard lock(on_demand_ranging_mutex_); @@ -627,19 +574,16 @@ class RasServerImpl : public bluetooth::ras::RasServer { break; } log::info("Send On Demand Ranging Data, segment {}", i); - BTA_GATTS_HandleValueIndication(tracker->conn_id_, attr_id, - it->segments_[i], need_confirm); + BTA_GATTS_HandleValueIndication(tracker->conn_id_, attr_id, it->segments_[i], need_confirm); } - log::info("Send COMPLETE_RANGING_DATA_RESPONSE, ranging_counter:{}", - ranging_counter); + log::info("Send COMPLETE_RANGING_DATA_RESPONSE, ranging_counter:{}", ranging_counter); std::vector response(3, 0); response[0] = (uint8_t)EventCode::COMPLETE_RANGING_DATA_RESPONSE; response[1] = (ranging_counter & 0xFF); response[2] = (ranging_counter >> 8) & 0xFF; BTA_GATTS_HandleValueIndication( - tracker->conn_id_, - GetCharacteristic(kRasControlPointCharacteristic)->attribute_handle_, - response, true); + tracker->conn_id_, + GetCharacteristic(kRasControlPointCharacteristic)->attribute_handle_, response, true); tracker->handling_control_point_command_ = false; return; } else { @@ -670,17 +614,15 @@ class RasServerImpl : public bluetooth::ras::RasServer { } } - void SendResponseCode(ResponseCodeValue response_code_value, - ClientTracker* tracker) { + void SendResponseCode(ResponseCodeValue response_code_value, ClientTracker* tracker) { log::info("0x{:02x}, {}", (uint16_t)response_code_value, GetResponseOpcodeValueText(response_code_value)); std::vector response(2, 0); response[0] = (uint8_t)EventCode::RESPONSE_CODE; response[1] = (uint8_t)response_code_value; BTA_GATTS_HandleValueIndication( - tracker->conn_id_, - GetCharacteristic(kRasControlPointCharacteristic)->attribute_handle_, - response, true); + tracker->conn_id_, GetCharacteristic(kRasControlPointCharacteristic)->attribute_handle_, + response, true); tracker->handling_control_point_command_ = false; } @@ -692,14 +634,14 @@ class RasServerImpl : public bluetooth::ras::RasServer { uint16_t attribute_handle = service[i].attribute_handle; Uuid uuid = service[i].uuid; if (service[i].type == BTGATT_DB_CHARACTERISTIC) { - log::info("Characteristic uuid: 0x{:04x}, handle:0x{:04x}, {}", - uuid.As16Bit(), attribute_handle, getUuidName(uuid)); + log::info("Characteristic uuid: 0x{:04x}, handle:0x{:04x}, {}", uuid.As16Bit(), + attribute_handle, getUuidName(uuid)); characteristics_[attribute_handle].attribute_handle_ = attribute_handle; characteristics_[attribute_handle].uuid_ = uuid; current_characteristic = &characteristics_[attribute_handle]; } else if (service[i].type == BTGATT_DB_DESCRIPTOR) { - log::info("\tDescriptor uuid: 0x{:04x}, handle: 0x{:04x}, {}", - uuid.As16Bit(), attribute_handle, getUuidName(uuid)); + log::info("\tDescriptor uuid: 0x{:04x}, handle: 0x{:04x}, {}", uuid.As16Bit(), + attribute_handle, getUuidName(uuid)); if (service[i].uuid == kClientCharacteristicConfiguration) { current_characteristic->attribute_handle_ccc_ = attribute_handle; } @@ -739,14 +681,13 @@ class RasServerImpl : public bluetooth::ras::RasServer { return data_buffer; } } - log::info("Create data for ranging_counter: {}, current size {}", - procedure_counter, buffers.size()); + log::info("Create data for ranging_counter: {}, current size {}", procedure_counter, + buffers.size()); buffers.emplace_back(procedure_counter); return buffers.back(); } - VendorSpecificCharacteristic* GetVendorSpecificCharacteristic( - const bluetooth::Uuid& uuid) { + VendorSpecificCharacteristic* GetVendorSpecificCharacteristic(const bluetooth::Uuid& uuid) { for (auto& characteristic : vendor_specific_characteristics_) { if (characteristic.characteristicUuid_ == uuid) { return &characteristic; @@ -755,7 +696,7 @@ class RasServerImpl : public bluetooth::ras::RasServer { return nullptr; } - private: +private: bluetooth::Uuid app_uuid_; uint16_t server_if_; // A map to associate characteristics with handles diff --git a/system/bta/ras/ras_types.h b/system/bta/ras/ras_types.h index d538a4b4247..54e41f6b89d 100644 --- a/system/bta/ras/ras_types.h +++ b/system/bta/ras/ras_types.h @@ -33,22 +33,21 @@ static const uint16_t kRasRangingDataReadyCharacteristic16bit = 0x7F78; static const uint16_t kRasRangingDataOverWrittenCharacteristic16bit = 0x7F77; static const uint16_t kClientCharacteristicConfiguration16bit = 0x2902; -static const bluetooth::Uuid kRangingService = - bluetooth::Uuid::From16Bit(kRangingService16Bit); +static const bluetooth::Uuid kRangingService = bluetooth::Uuid::From16Bit(kRangingService16Bit); static const bluetooth::Uuid kRasFeaturesCharacteristic = - bluetooth::Uuid::From16Bit(kRasFeaturesCharacteristic16bit); + bluetooth::Uuid::From16Bit(kRasFeaturesCharacteristic16bit); static const bluetooth::Uuid kRasRealTimeRangingDataCharacteristic = - bluetooth::Uuid::From16Bit(kRasRealTimeRangingDataCharacteristic16bit); + bluetooth::Uuid::From16Bit(kRasRealTimeRangingDataCharacteristic16bit); static const bluetooth::Uuid kRasOnDemandDataCharacteristic = - bluetooth::Uuid::From16Bit(kRasOnDemandDataCharacteristic16bit); + bluetooth::Uuid::From16Bit(kRasOnDemandDataCharacteristic16bit); static const bluetooth::Uuid kRasControlPointCharacteristic = - bluetooth::Uuid::From16Bit(kRasControlPointCharacteristic16bit); + bluetooth::Uuid::From16Bit(kRasControlPointCharacteristic16bit); static const bluetooth::Uuid kRasRangingDataReadyCharacteristic = - bluetooth::Uuid::From16Bit(kRasRangingDataReadyCharacteristic16bit); + bluetooth::Uuid::From16Bit(kRasRangingDataReadyCharacteristic16bit); static const bluetooth::Uuid kRasRangingDataOverWrittenCharacteristic = - bluetooth::Uuid::From16Bit(kRasRangingDataOverWrittenCharacteristic16bit); + bluetooth::Uuid::From16Bit(kRasRangingDataOverWrittenCharacteristic16bit); static const bluetooth::Uuid kClientCharacteristicConfiguration = - bluetooth::Uuid::From16Bit(kClientCharacteristicConfiguration16bit); + bluetooth::Uuid::From16Bit(kClientCharacteristicConfiguration16bit); std::string getUuidName(const bluetooth::Uuid& uuid); @@ -106,8 +105,7 @@ struct ControlPointResponse { uint8_t parameter_[4]; }; -bool ParseControlPointCommand(ControlPointCommand* command, - const uint8_t* value, uint16_t len); +bool ParseControlPointCommand(ControlPointCommand* command, const uint8_t* value, uint16_t len); bool IsRangingServiceCharacteristic(const bluetooth::Uuid& uuid); diff --git a/system/bta/ras/ras_utils.cc b/system/bta/ras/ras_utils.cc index 9f7c5ff4090..93befa7e9d9 100644 --- a/system/bta/ras/ras_utils.cc +++ b/system/bta/ras/ras_utils.cc @@ -55,8 +55,7 @@ std::string uuid::getUuidName(const bluetooth::Uuid& uuid) { } } -bool ParseControlPointCommand(ControlPointCommand* command, - const uint8_t* value, uint16_t len) { +bool ParseControlPointCommand(ControlPointCommand* command, const uint8_t* value, uint16_t len) { command->opcode_ = static_cast(value[0]); // Check for minimum expected length switch (value[0]) { diff --git a/system/bta/rfcomm/bta_rfcomm_scn.cc b/system/bta/rfcomm/bta_rfcomm_scn.cc index 721717c18ad..064d95aa2ba 100644 --- a/system/bta/rfcomm/bta_rfcomm_scn.cc +++ b/system/bta/rfcomm/bta_rfcomm_scn.cc @@ -46,14 +46,13 @@ uint8_t BTA_AllocateSCN(void) { bta_jv_cb.scn_in_use[i] = true; bta_jv_cb.scn_search_index = (i + 1); log::debug("Allocating scn: {}", i + 1); - return (i + 1); // allocated scn is index + 1 + return i + 1; // allocated scn is index + 1 } } // In order to avoid OOB, scn_search_index must be no more than // RFCOMM_MAX_SCN. - bta_jv_cb.scn_search_index = - std::min(bta_jv_cb.scn_search_index, (uint8_t)(RFCOMM_MAX_SCN)); + bta_jv_cb.scn_search_index = std::min(bta_jv_cb.scn_search_index, (uint8_t)(RFCOMM_MAX_SCN)); // If there's no empty SCN from scn_search_index to RFCOMM_MAX_SCN // Start from index 1 because index 0 (scn 1) is reserved for HFP @@ -62,11 +61,11 @@ uint8_t BTA_AllocateSCN(void) { bta_jv_cb.scn_in_use[i] = true; bta_jv_cb.scn_search_index = (i + 1); log::debug("Allocating scn: {}", i + 1); - return (i + 1); // allocated scn is index + 1 + return i + 1; // allocated scn is index + 1 } } log::debug("Unable to allocate an scn"); - return (0); /* No free ports */ + return 0; /* No free ports */ } /******************************************************************************* @@ -83,7 +82,9 @@ bool BTA_TryAllocateSCN(uint8_t scn) { /* Make sure we don't exceed max scn range. * Stack reserves scn 1 for HFP and HSP */ - if ((scn > RFCOMM_MAX_SCN) || (scn == 1) || (scn == 0)) return false; + if ((scn > RFCOMM_MAX_SCN) || (scn == 1) || (scn == 0)) { + return false; + } /* check if this scn is available */ if (!bta_jv_cb.scn_in_use[scn - 1]) { @@ -92,7 +93,7 @@ bool BTA_TryAllocateSCN(uint8_t scn) { return true; } log::debug("Unable to allocate scn {}", scn); - return (false); /* scn was busy */ + return false; /* scn was busy */ } /******************************************************************************* @@ -111,9 +112,9 @@ bool BTA_FreeSCN(uint8_t scn) { if (scn < RFCOMM_MAX_SCN && scn > 1) { bta_jv_cb.scn_in_use[scn - 1] = false; log::debug("Freed SCN: {}", scn); - return (true); + return true; } else { log::warn("Invalid SCN: {}", scn); - return (false); /* Illegal SCN passed in */ + return false; /* Illegal SCN passed in */ } } diff --git a/system/bta/sdp/bta_sdp_act.cc b/system/bta/sdp/bta_sdp_act.cc index bb9afea5e6d..03e7eda73af 100644 --- a/system/bta/sdp/bta_sdp_act.cc +++ b/system/bta/sdp/bta_sdp_act.cc @@ -45,8 +45,7 @@ using namespace bluetooth::legacy::stack::sdp; using namespace bluetooth; -static void bta_create_mns_sdp_record(bluetooth_sdp_record* record, - tSDP_DISC_REC* p_rec) { +static void bta_create_mns_sdp_record(bluetooth_sdp_record* record, tSDP_DISC_REC* p_rec) { tSDP_DISC_ATTR* p_attr; tSDP_PROTOCOL_ELEM pe; uint16_t pversion = 0; @@ -59,7 +58,7 @@ static void bta_create_mns_sdp_record(bluetooth_sdp_record* record, record->mns.supported_features = 0x0000001F; // default value if not found p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - p_rec, ATTR_ID_MAP_SUPPORTED_FEATURES); + p_rec, ATTR_ID_MAP_SUPPORTED_FEATURES); if (p_attr != NULL) { if (SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == UINT_DESC_TYPE && SDP_DISC_ATTR_LEN(p_attr->attr_len_type) >= 4) { @@ -71,12 +70,10 @@ static void bta_create_mns_sdp_record(bluetooth_sdp_record* record, log::error("ATTR_ID_MAP_SUPPORTED_FEATURES attr not found!!"); } - p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - p_rec, ATTR_ID_SERVICE_NAME); + p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec(p_rec, ATTR_ID_SERVICE_NAME); if (p_attr != NULL) { if (SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == TEXT_STR_DESC_TYPE) { - record->mns.hdr.service_name_length = - SDP_DISC_ATTR_LEN(p_attr->attr_len_type); + record->mns.hdr.service_name_length = SDP_DISC_ATTR_LEN(p_attr->attr_len_type); record->mns.hdr.service_name = (char*)p_attr->attr_value.v.array; } else { log::error("ATTR_ID_SERVICE_NAME attr type not TEXT_STR_DESC_TYPE!!"); @@ -86,17 +83,16 @@ static void bta_create_mns_sdp_record(bluetooth_sdp_record* record, } if (get_legacy_stack_sdp_api()->record.SDP_FindProfileVersionInRec( - p_rec, UUID_SERVCLASS_MAP_PROFILE, &pversion)) { + p_rec, UUID_SERVCLASS_MAP_PROFILE, &pversion)) { record->mns.hdr.profile_version = pversion; } - if (get_legacy_stack_sdp_api()->record.SDP_FindProtocolListElemInRec( - p_rec, UUID_PROTOCOL_RFCOMM, &pe)) { + if (get_legacy_stack_sdp_api()->record.SDP_FindProtocolListElemInRec(p_rec, UUID_PROTOCOL_RFCOMM, + &pe)) { record->mns.hdr.rfcomm_channel_number = pe.params[0]; } - p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - p_rec, ATTR_ID_GOEP_L2CAP_PSM); + p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec(p_rec, ATTR_ID_GOEP_L2CAP_PSM); if (p_attr != NULL) { if (SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == UINT_DESC_TYPE && SDP_DISC_ATTR_LEN(p_attr->attr_len_type) >= 2) { @@ -109,8 +105,7 @@ static void bta_create_mns_sdp_record(bluetooth_sdp_record* record, } } -static void bta_create_mas_sdp_record(bluetooth_sdp_record* record, - tSDP_DISC_REC* p_rec) { +static void bta_create_mas_sdp_record(bluetooth_sdp_record* record, tSDP_DISC_REC* p_rec) { tSDP_DISC_ATTR* p_attr; tSDP_PROTOCOL_ELEM pe; uint16_t pversion = -1; @@ -125,8 +120,8 @@ static void bta_create_mas_sdp_record(bluetooth_sdp_record* record, record->mas.supported_features = 0x0000001F; record->mas.supported_message_types = 0; - p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - p_rec, ATTR_ID_MAS_INSTANCE_ID); + p_attr = + get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec(p_rec, ATTR_ID_MAS_INSTANCE_ID); if (p_attr != NULL) { if (SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == UINT_DESC_TYPE && SDP_DISC_ATTR_LEN(p_attr->attr_len_type) >= 1) { @@ -138,8 +133,8 @@ static void bta_create_mas_sdp_record(bluetooth_sdp_record* record, log::error("ATTR_ID_MAS_INSTANCE_ID attr not found!!"); } - p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - p_rec, ATTR_ID_SUPPORTED_MSG_TYPE); + p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec(p_rec, + ATTR_ID_SUPPORTED_MSG_TYPE); if (p_attr != NULL) { if (SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == UINT_DESC_TYPE && SDP_DISC_ATTR_LEN(p_attr->attr_len_type) >= 1) { @@ -152,7 +147,7 @@ static void bta_create_mas_sdp_record(bluetooth_sdp_record* record, } p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - p_rec, ATTR_ID_MAP_SUPPORTED_FEATURES); + p_rec, ATTR_ID_MAP_SUPPORTED_FEATURES); if (p_attr != NULL) { if (SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == UINT_DESC_TYPE && SDP_DISC_ATTR_LEN(p_attr->attr_len_type) >= 4) { @@ -164,12 +159,10 @@ static void bta_create_mas_sdp_record(bluetooth_sdp_record* record, log::error("ATTR_ID_MAP_SUPPORTED_FEATURES attr not found!!"); } - p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - p_rec, ATTR_ID_SERVICE_NAME); + p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec(p_rec, ATTR_ID_SERVICE_NAME); if (p_attr != NULL) { if (SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == TEXT_STR_DESC_TYPE) { - record->mas.hdr.service_name_length = - SDP_DISC_ATTR_LEN(p_attr->attr_len_type); + record->mas.hdr.service_name_length = SDP_DISC_ATTR_LEN(p_attr->attr_len_type); record->mas.hdr.service_name = (char*)p_attr->attr_value.v.array; } else { log::error("ATTR_ID_SERVICE_NAME attr type wrong!!"); @@ -179,17 +172,16 @@ static void bta_create_mas_sdp_record(bluetooth_sdp_record* record, } if (get_legacy_stack_sdp_api()->record.SDP_FindProfileVersionInRec( - p_rec, UUID_SERVCLASS_MAP_PROFILE, &pversion)) { + p_rec, UUID_SERVCLASS_MAP_PROFILE, &pversion)) { record->mas.hdr.profile_version = pversion; } - if (get_legacy_stack_sdp_api()->record.SDP_FindProtocolListElemInRec( - p_rec, UUID_PROTOCOL_RFCOMM, &pe)) { + if (get_legacy_stack_sdp_api()->record.SDP_FindProtocolListElemInRec(p_rec, UUID_PROTOCOL_RFCOMM, + &pe)) { record->mas.hdr.rfcomm_channel_number = pe.params[0]; } - p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - p_rec, ATTR_ID_GOEP_L2CAP_PSM); + p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec(p_rec, ATTR_ID_GOEP_L2CAP_PSM); if (p_attr != NULL) { if (SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == UINT_DESC_TYPE && SDP_DISC_ATTR_LEN(p_attr->attr_len_type) >= 2) { @@ -202,8 +194,7 @@ static void bta_create_mas_sdp_record(bluetooth_sdp_record* record, } } -static void bta_create_pse_sdp_record(bluetooth_sdp_record* record, - tSDP_DISC_REC* p_rec) { +static void bta_create_pse_sdp_record(bluetooth_sdp_record* record, tSDP_DISC_REC* p_rec) { tSDP_DISC_ATTR* p_attr; uint16_t pversion; tSDP_PROTOCOL_ELEM pe; @@ -218,7 +209,7 @@ static void bta_create_pse_sdp_record(bluetooth_sdp_record* record, record->pse.supported_repositories = 0; p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - p_rec, ATTR_ID_SUPPORTED_REPOSITORIES); + p_rec, ATTR_ID_SUPPORTED_REPOSITORIES); if (p_attr != NULL) { if (SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == UINT_DESC_TYPE && SDP_DISC_ATTR_LEN(p_attr->attr_len_type) >= 1) { @@ -230,7 +221,7 @@ static void bta_create_pse_sdp_record(bluetooth_sdp_record* record, log::error("ATTR_ID_SUPPORTED_REPOSITORIES attr not found!!"); } p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - p_rec, ATTR_ID_PBAP_SUPPORTED_FEATURES); + p_rec, ATTR_ID_PBAP_SUPPORTED_FEATURES); if (p_attr != NULL) { if (SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == UINT_DESC_TYPE && SDP_DISC_ATTR_LEN(p_attr->attr_len_type) >= 4) { @@ -242,12 +233,10 @@ static void bta_create_pse_sdp_record(bluetooth_sdp_record* record, log::error("ATTR_ID_PBAP_SUPPORTED_FEATURES attr not found!!"); } - p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - p_rec, ATTR_ID_SERVICE_NAME); + p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec(p_rec, ATTR_ID_SERVICE_NAME); if (p_attr != NULL) { if (SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == TEXT_STR_DESC_TYPE) { - record->pse.hdr.service_name_length = - SDP_DISC_ATTR_LEN(p_attr->attr_len_type); + record->pse.hdr.service_name_length = SDP_DISC_ATTR_LEN(p_attr->attr_len_type); // TODO: validate the lifetime of this value record->pse.hdr.service_name = (char*)p_attr->attr_value.v.array; } else { @@ -258,17 +247,16 @@ static void bta_create_pse_sdp_record(bluetooth_sdp_record* record, } if (get_legacy_stack_sdp_api()->record.SDP_FindProfileVersionInRec( - p_rec, UUID_SERVCLASS_PHONE_ACCESS, &pversion)) { + p_rec, UUID_SERVCLASS_PHONE_ACCESS, &pversion)) { record->pse.hdr.profile_version = pversion; } - if (get_legacy_stack_sdp_api()->record.SDP_FindProtocolListElemInRec( - p_rec, UUID_PROTOCOL_RFCOMM, &pe)) { + if (get_legacy_stack_sdp_api()->record.SDP_FindProtocolListElemInRec(p_rec, UUID_PROTOCOL_RFCOMM, + &pe)) { record->pse.hdr.rfcomm_channel_number = pe.params[0]; } - p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - p_rec, ATTR_ID_GOEP_L2CAP_PSM); + p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec(p_rec, ATTR_ID_GOEP_L2CAP_PSM); if (p_attr != NULL) { if (SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == UINT_DESC_TYPE && SDP_DISC_ATTR_LEN(p_attr->attr_len_type) >= 2) { @@ -281,8 +269,7 @@ static void bta_create_pse_sdp_record(bluetooth_sdp_record* record, } } -static void bta_create_ops_sdp_record(bluetooth_sdp_record* record, - tSDP_DISC_REC* p_rec) { +static void bta_create_ops_sdp_record(bluetooth_sdp_record* record, tSDP_DISC_REC* p_rec) { tSDP_DISC_ATTR *p_attr, *p_sattr; tSDP_PROTOCOL_ELEM pe; uint16_t pversion = -1; @@ -295,12 +282,10 @@ static void bta_create_ops_sdp_record(bluetooth_sdp_record* record, record->ops.hdr.profile_version = 0; record->ops.supported_formats_list_len = 0; - p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - p_rec, ATTR_ID_SERVICE_NAME); + p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec(p_rec, ATTR_ID_SERVICE_NAME); if (p_attr != NULL) { if (SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == TEXT_STR_DESC_TYPE) { - record->ops.hdr.service_name_length = - SDP_DISC_ATTR_LEN(p_attr->attr_len_type); + record->ops.hdr.service_name_length = SDP_DISC_ATTR_LEN(p_attr->attr_len_type); record->ops.hdr.service_name = (char*)p_attr->attr_value.v.array; } else { log::error("ATTR_ID_SERVICE_NAME attr type NOT string!!"); @@ -310,17 +295,16 @@ static void bta_create_ops_sdp_record(bluetooth_sdp_record* record, } if (get_legacy_stack_sdp_api()->record.SDP_FindProfileVersionInRec( - p_rec, UUID_SERVCLASS_OBEX_OBJECT_PUSH, &pversion)) { + p_rec, UUID_SERVCLASS_OBEX_OBJECT_PUSH, &pversion)) { record->ops.hdr.profile_version = pversion; } - if (get_legacy_stack_sdp_api()->record.SDP_FindProtocolListElemInRec( - p_rec, UUID_PROTOCOL_RFCOMM, &pe)) { + if (get_legacy_stack_sdp_api()->record.SDP_FindProtocolListElemInRec(p_rec, UUID_PROTOCOL_RFCOMM, + &pe)) { record->ops.hdr.rfcomm_channel_number = pe.params[0]; } - p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - p_rec, ATTR_ID_GOEP_L2CAP_PSM); + p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec(p_rec, ATTR_ID_GOEP_L2CAP_PSM); if (p_attr != NULL) { if (SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == UINT_DESC_TYPE && SDP_DISC_ATTR_LEN(p_attr->attr_len_type) >= 2) { @@ -333,20 +317,17 @@ static void bta_create_ops_sdp_record(bluetooth_sdp_record* record, } p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - p_rec, ATTR_ID_SUPPORTED_FORMATS_LIST); + p_rec, ATTR_ID_SUPPORTED_FORMATS_LIST); if (p_attr != NULL) { /* Safety check - each entry should itself be a sequence */ if (SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) != DATA_ELE_SEQ_DESC_TYPE) { record->ops.supported_formats_list_len = 0; - log::error( - "supported_formats_list - wrong attribute length/type: 0x{:02x} - " - "expected 0x06", - p_attr->attr_len_type); + log::error("supported_formats_list - wrong attribute length/type: 0x{:02x} - expected 0x06", + p_attr->attr_len_type); } else { int count = 0; /* 1 byte for type/length 1 byte for value */ - record->ops.supported_formats_list_len = - SDP_DISC_ATTR_LEN(p_attr->attr_len_type) / 2; + record->ops.supported_formats_list_len = SDP_DISC_ATTR_LEN(p_attr->attr_len_type) / 2; /* Extract each value into */ for (p_sattr = p_attr->attr_value.v.p_sub_attr; p_sattr != NULL; @@ -354,9 +335,7 @@ static void bta_create_ops_sdp_record(bluetooth_sdp_record* record, if ((SDP_DISC_ATTR_TYPE(p_sattr->attr_len_type) == UINT_DESC_TYPE) && (SDP_DISC_ATTR_LEN(p_sattr->attr_len_type) >= 1)) { if (count == sizeof(record->ops.supported_formats_list)) { - log::error( - "supported_formats_list - count overflow - too many sub " - "attributes!!"); + log::error("supported_formats_list - count overflow - too many sub attributes!!"); /* If you hit this, new formats have been added, * update SDP_OPP_SUPPORTED_FORMATS_MAX_LENGTH */ break; @@ -365,26 +344,25 @@ static void bta_create_ops_sdp_record(bluetooth_sdp_record* record, count++; } else { log::error( - "supported_formats_list - wrong sub attribute length/type: " - "0x{:02x} - expected 0x80", - p_sattr->attr_len_type); + "supported_formats_list - wrong sub attribute length/type: " + "0x{:02x} - expected 0x80", + p_sattr->attr_len_type); break; } } if (record->ops.supported_formats_list_len != count) { log::warn( - "supported_formats_list - Length of attribute different from the " - "actual number of sub-attributes in the sequence att-length: {} - " - "number of elements: {}", - record->ops.supported_formats_list_len, count); + "supported_formats_list - Length of attribute different from the " + "actual number of sub-attributes in the sequence att-length: {} - " + "number of elements: {}", + record->ops.supported_formats_list_len, count); } record->ops.supported_formats_list_len = count; } } } -static void bta_create_sap_sdp_record(bluetooth_sdp_record* record, - tSDP_DISC_REC* p_rec) { +static void bta_create_sap_sdp_record(bluetooth_sdp_record* record, tSDP_DISC_REC* p_rec) { tSDP_DISC_ATTR* p_attr; tSDP_PROTOCOL_ELEM pe; uint16_t pversion = -1; @@ -396,12 +374,10 @@ static void bta_create_sap_sdp_record(bluetooth_sdp_record* record, record->sap.hdr.l2cap_psm = -1; record->sap.hdr.profile_version = 0; - p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - p_rec, ATTR_ID_SERVICE_NAME); + p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec(p_rec, ATTR_ID_SERVICE_NAME); if (p_attr != NULL) { if (SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == TEXT_STR_DESC_TYPE) { - record->sap.hdr.service_name_length = - SDP_DISC_ATTR_LEN(p_attr->attr_len_type); + record->sap.hdr.service_name_length = SDP_DISC_ATTR_LEN(p_attr->attr_len_type); record->sap.hdr.service_name = (char*)p_attr->attr_value.v.array; } else { log::error("ATTR_ID_SERVICE_NAME attr type NOT string!!"); @@ -410,19 +386,18 @@ static void bta_create_sap_sdp_record(bluetooth_sdp_record* record, log::error("ATTR_ID_SERVICE_NAME attr not found!!"); } - if (get_legacy_stack_sdp_api()->record.SDP_FindProfileVersionInRec( - p_rec, UUID_SERVCLASS_SAP, &pversion)) { + if (get_legacy_stack_sdp_api()->record.SDP_FindProfileVersionInRec(p_rec, UUID_SERVCLASS_SAP, + &pversion)) { record->sap.hdr.profile_version = pversion; } - if (get_legacy_stack_sdp_api()->record.SDP_FindProtocolListElemInRec( - p_rec, UUID_PROTOCOL_RFCOMM, &pe)) { + if (get_legacy_stack_sdp_api()->record.SDP_FindProtocolListElemInRec(p_rec, UUID_PROTOCOL_RFCOMM, + &pe)) { record->sap.hdr.rfcomm_channel_number = pe.params[0]; } } -static void bta_create_dip_sdp_record(bluetooth_sdp_record* record, - tSDP_DISC_REC* p_rec) { +static void bta_create_dip_sdp_record(bluetooth_sdp_record* record, tSDP_DISC_REC* p_rec) { tSDP_DISC_ATTR* p_attr; log::verbose(""); @@ -435,8 +410,8 @@ static void bta_create_dip_sdp_record(bluetooth_sdp_record* record, record->dip.hdr.l2cap_psm = -1; record->dip.hdr.profile_version = 0; - p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - p_rec, ATTR_ID_SPECIFICATION_ID); + p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec(p_rec, + ATTR_ID_SPECIFICATION_ID); if (p_attr != nullptr) { if (SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == UINT_DESC_TYPE && SDP_DISC_ATTR_LEN(p_attr->attr_len_type) >= 2) { @@ -448,8 +423,7 @@ static void bta_create_dip_sdp_record(bluetooth_sdp_record* record, log::error("ATTR_ID_SPECIFICATION_ID not found"); } - p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - p_rec, ATTR_ID_VENDOR_ID); + p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec(p_rec, ATTR_ID_VENDOR_ID); if (p_attr != nullptr) { if (SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == UINT_DESC_TYPE && SDP_DISC_ATTR_LEN(p_attr->attr_len_type) >= 2) { @@ -461,8 +435,8 @@ static void bta_create_dip_sdp_record(bluetooth_sdp_record* record, log::error("ATTR_ID_VENDOR_ID not found"); } - p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - p_rec, ATTR_ID_VENDOR_ID_SOURCE); + p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec(p_rec, + ATTR_ID_VENDOR_ID_SOURCE); if (p_attr != nullptr) { if (SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == UINT_DESC_TYPE && SDP_DISC_ATTR_LEN(p_attr->attr_len_type) >= 2) { @@ -474,8 +448,7 @@ static void bta_create_dip_sdp_record(bluetooth_sdp_record* record, log::error("ATTR_ID_VENDOR_ID_SOURCE not found"); } - p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - p_rec, ATTR_ID_PRODUCT_ID); + p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec(p_rec, ATTR_ID_PRODUCT_ID); if (p_attr != nullptr) { if (SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == UINT_DESC_TYPE && SDP_DISC_ATTR_LEN(p_attr->attr_len_type) >= 2) { @@ -487,8 +460,8 @@ static void bta_create_dip_sdp_record(bluetooth_sdp_record* record, log::error("ATTR_ID_PRODUCT_ID not found"); } - p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - p_rec, ATTR_ID_PRODUCT_VERSION); + p_attr = + get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec(p_rec, ATTR_ID_PRODUCT_VERSION); if (p_attr != nullptr) { if (SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == UINT_DESC_TYPE && SDP_DISC_ATTR_LEN(p_attr->attr_len_type) >= 2) { @@ -500,8 +473,7 @@ static void bta_create_dip_sdp_record(bluetooth_sdp_record* record, log::error("ATTR_ID_PRODUCT_VERSION not found"); } - p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - p_rec, ATTR_ID_PRIMARY_RECORD); + p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec(p_rec, ATTR_ID_PRIMARY_RECORD); if (p_attr != nullptr) { if (SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == BOOLEAN_DESC_TYPE && SDP_DISC_ATTR_LEN(p_attr->attr_len_type) >= 1) { @@ -514,8 +486,7 @@ static void bta_create_dip_sdp_record(bluetooth_sdp_record* record, } } -static void bta_create_raw_sdp_record(bluetooth_sdp_record* record, - tSDP_DISC_REC* p_rec) { +static void bta_create_raw_sdp_record(bluetooth_sdp_record* record, tSDP_DISC_REC* p_rec) { tSDP_DISC_ATTR* p_attr; tSDP_PROTOCOL_ELEM pe; @@ -527,12 +498,10 @@ static void bta_create_raw_sdp_record(bluetooth_sdp_record* record, record->hdr.profile_version = -1; /* Try to extract a service name */ - p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - p_rec, ATTR_ID_SERVICE_NAME); + p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec(p_rec, ATTR_ID_SERVICE_NAME); if (p_attr != NULL) { if (SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == TEXT_STR_DESC_TYPE) { - record->pse.hdr.service_name_length = - SDP_DISC_ATTR_LEN(p_attr->attr_len_type); + record->pse.hdr.service_name_length = SDP_DISC_ATTR_LEN(p_attr->attr_len_type); record->pse.hdr.service_name = (char*)p_attr->attr_value.v.array; } else { log::error("ATTR_ID_SERVICE_NAME attr type NOT string!!"); @@ -542,8 +511,8 @@ static void bta_create_raw_sdp_record(bluetooth_sdp_record* record, } /* Try to extract an RFCOMM channel */ - if (get_legacy_stack_sdp_api()->record.SDP_FindProtocolListElemInRec( - p_rec, UUID_PROTOCOL_RFCOMM, &pe)) { + if (get_legacy_stack_sdp_api()->record.SDP_FindProtocolListElemInRec(p_rec, UUID_PROTOCOL_RFCOMM, + &pe)) { record->pse.hdr.rfcomm_channel_number = pe.params[0]; } record->hdr.user1_ptr_len = p_bta_sdp_cfg->p_sdp_db->raw_size; @@ -551,15 +520,16 @@ static void bta_create_raw_sdp_record(bluetooth_sdp_record* record, } /** Callback from btm after search is completed */ -static void bta_sdp_search_cback(Uuid uuid, const RawAddress& /* bd_addr */, - tSDP_RESULT result) { +static void bta_sdp_search_cback(Uuid uuid, const RawAddress& /* bd_addr */, tSDP_RESULT result) { tBTA_SDP_STATUS status = BTA_SDP_FAILURE; int count = 0; log::verbose("res: 0x{:x}", result); bta_sdp_cb.sdp_active = false; - if (bta_sdp_cb.p_dm_cback == NULL) return; + if (bta_sdp_cb.p_dm_cback == NULL) { + return; + } tBTA_SDP_SEARCH_COMP evt_data; memset(&evt_data, 0, sizeof(evt_data)); @@ -569,8 +539,8 @@ static void bta_sdp_search_cback(Uuid uuid, const RawAddress& /* bd_addr */, if (result == SDP_SUCCESS || result == SDP_DB_FULL) { tSDP_DISC_REC* p_rec = NULL; do { - p_rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceUUIDInDb( - p_bta_sdp_cfg->p_sdp_db, uuid, p_rec); + p_rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceUUIDInDb(p_bta_sdp_cfg->p_sdp_db, uuid, + p_rec); /* generate the matching record data pointer */ if (!p_rec) { log::verbose("UUID not found"); @@ -599,12 +569,11 @@ static void bta_sdp_search_cback(Uuid uuid, const RawAddress& /* bd_addr */, uint16_t peer_pce_version = 0; if (!get_legacy_stack_sdp_api()->record.SDP_FindProfileVersionInRec( - p_rec, UUID_SERVCLASS_PHONE_ACCESS, &peer_pce_version)) { + p_rec, UUID_SERVCLASS_PHONE_ACCESS, &peer_pce_version)) { log::warn("Unable to find PBAP profile version in SDP record"); } if (peer_pce_version != 0) { - btif_storage_set_pce_profile_version(p_rec->remote_bd_addr, - peer_pce_version); + btif_storage_set_pce_profile_version(p_rec->remote_bd_addr, peer_pce_version); } } else { log::verbose("PCE Record is null"); @@ -633,8 +602,7 @@ static void bta_sdp_search_cback(Uuid uuid, const RawAddress& /* bd_addr */, tBTA_SDP bta_sdp; bta_sdp.sdp_search_comp = evt_data; bta_sdp_cb.p_dm_cback(BTA_SDP_SEARCH_COMP_EVT, &bta_sdp, (void*)&uuid); - bluetooth::shim::CountCounterMetrics( - android::bluetooth::CodePathCounterKeyEnum::SDP_SUCCESS, 1); + bluetooth::shim::CountCounterMetrics(android::bluetooth::CodePathCounterKeyEnum::SDP_SUCCESS, 1); } /******************************************************************************* @@ -691,16 +659,13 @@ void bta_sdp_search(const RawAddress bd_addr, const bluetooth::Uuid uuid) { /* initialize the search for the uuid */ log::verbose("init discovery with UUID: {}", uuid.ToString()); if (!get_legacy_stack_sdp_api()->service.SDP_InitDiscoveryDb( - p_bta_sdp_cfg->p_sdp_db, p_bta_sdp_cfg->sdp_db_size, 1, &uuid, 0, - NULL)) { + p_bta_sdp_cfg->p_sdp_db, p_bta_sdp_cfg->sdp_db_size, 1, &uuid, 0, NULL)) { log::warn("Unable to initialize SDP service search db peer:{}", bd_addr); } if (!get_legacy_stack_sdp_api()->service.SDP_ServiceSearchAttributeRequest2( - bd_addr, p_bta_sdp_cfg->p_sdp_db, - base::BindRepeating(bta_sdp_search_cback, uuid))) { - log::warn("Unable to start SDP service search attribute request peer:{}", - bd_addr); + bd_addr, p_bta_sdp_cfg->p_sdp_db, base::BindRepeating(bta_sdp_search_cback, uuid))) { + log::warn("Unable to start SDP service search attribute request peer:{}", bd_addr); bta_sdp_cb.sdp_active = false; /* failed to start SDP. report the failure right away */ @@ -713,8 +678,8 @@ void bta_sdp_search(const RawAddress bd_addr, const bluetooth::Uuid uuid) { tBTA_SDP bta_sdp; bta_sdp.sdp_search_comp = result; bta_sdp_cb.p_dm_cback(BTA_SDP_SEARCH_COMP_EVT, &bta_sdp, NULL); - bluetooth::shim::CountCounterMetrics( - android::bluetooth::CodePathCounterKeyEnum::SDP_FAILURE, 1); + bluetooth::shim::CountCounterMetrics(android::bluetooth::CodePathCounterKeyEnum::SDP_FAILURE, + 1); } } /* @@ -732,8 +697,9 @@ void bta_sdp_search(const RawAddress bd_addr, const bluetooth::Uuid uuid) { * ******************************************************************************/ void bta_sdp_create_record(void* user_data) { - if (bta_sdp_cb.p_dm_cback) + if (bta_sdp_cb.p_dm_cback) { bta_sdp_cb.p_dm_cback(BTA_SDP_CREATE_RECORD_USER_EVT, NULL, user_data); + } } /******************************************************************************* @@ -746,20 +712,19 @@ void bta_sdp_create_record(void* user_data) { * ******************************************************************************/ void bta_sdp_remove_record(void* user_data) { - if (bta_sdp_cb.p_dm_cback) + if (bta_sdp_cb.p_dm_cback) { bta_sdp_cb.p_dm_cback(BTA_SDP_REMOVE_RECORD_USER_EVT, NULL, user_data); + } } namespace bluetooth { namespace testing { -void bta_create_dip_sdp_record(bluetooth_sdp_record* record, - tSDP_DISC_REC* p_rec) { +void bta_create_dip_sdp_record(bluetooth_sdp_record* record, tSDP_DISC_REC* p_rec) { ::bta_create_dip_sdp_record(record, p_rec); } -void bta_sdp_search_cback(Uuid uuid, const RawAddress& bd_addr, - tSDP_RESULT result) { +void bta_sdp_search_cback(Uuid uuid, const RawAddress& bd_addr, tSDP_RESULT result) { ::bta_sdp_search_cback(uuid, bd_addr, result); } diff --git a/system/bta/sdp/bta_sdp_api.cc b/system/bta/sdp/bta_sdp_api.cc index d68c42d03d4..cec89c358af 100644 --- a/system/bta/sdp/bta_sdp_api.cc +++ b/system/bta/sdp/bta_sdp_api.cc @@ -74,8 +74,7 @@ tBTA_SDP_STATUS BTA_SdpEnable(tBTA_SDP_DM_CBACK* p_cback) { * BTA_SDP_FAILURE, otherwise. * ******************************************************************************/ -tBTA_SDP_STATUS BTA_SdpSearch(const RawAddress& bd_addr, - const bluetooth::Uuid& uuid) { +tBTA_SDP_STATUS BTA_SdpSearch(const RawAddress& bd_addr, const bluetooth::Uuid& uuid) { do_in_main_thread(FROM_HERE, base::BindOnce(bta_sdp_search, bd_addr, uuid)); return BTA_SDP_SUCCESS; } @@ -93,8 +92,7 @@ tBTA_SDP_STATUS BTA_SdpSearch(const RawAddress& bd_addr, * ******************************************************************************/ tBTA_SDP_STATUS BTA_SdpCreateRecordByUser(void* user_data) { - do_in_main_thread(FROM_HERE, - base::BindOnce(bta_sdp_create_record, user_data)); + do_in_main_thread(FROM_HERE, base::BindOnce(bta_sdp_create_record, user_data)); return BTA_SDP_SUCCESS; } @@ -111,7 +109,6 @@ tBTA_SDP_STATUS BTA_SdpCreateRecordByUser(void* user_data) { * ******************************************************************************/ tBTA_SDP_STATUS BTA_SdpRemoveRecordByUser(void* user_data) { - do_in_main_thread(FROM_HERE, - base::BindOnce(bta_sdp_remove_record, user_data)); + do_in_main_thread(FROM_HERE, base::BindOnce(bta_sdp_remove_record, user_data)); return BTA_SDP_SUCCESS; } diff --git a/system/bta/sdp/bta_sdp_cfg.cc b/system/bta/sdp/bta_sdp_cfg.cc index 1f8eff67ba1..7ded154bb0e 100644 --- a/system/bta/sdp/bta_sdp_cfg.cc +++ b/system/bta/sdp/bta_sdp_cfg.cc @@ -28,13 +28,12 @@ #define BTA_SDP_DB_SIZE 4500 #endif -static tSDP_DISCOVERY_DB - bta_sdp_db_data[BTA_SDP_DB_SIZE / sizeof(tSDP_DISCOVERY_DB)]; +static tSDP_DISCOVERY_DB bta_sdp_db_data[BTA_SDP_DB_SIZE / sizeof(tSDP_DISCOVERY_DB)]; /* SDP configuration structure */ const tBTA_SDP_CFG bta_sdp_cfg = { - (BTA_SDP_DB_SIZE / sizeof(tSDP_DISCOVERY_DB)) * sizeof(tSDP_DISCOVERY_DB), - bta_sdp_db_data /* The data buffer to keep SDP database */ + (BTA_SDP_DB_SIZE / sizeof(tSDP_DISCOVERY_DB)) * sizeof(tSDP_DISCOVERY_DB), + bta_sdp_db_data /* The data buffer to keep SDP database */ }; const tBTA_SDP_CFG* p_bta_sdp_cfg = &bta_sdp_cfg; diff --git a/system/bta/sys/bta_sys.h b/system/bta/sys/bta_sys.h index a90607f2658..e1bca2fdbe3 100644 --- a/system/bta/sys/bta_sys.h +++ b/system/bta/sys/bta_sys.h @@ -49,9 +49,8 @@ typedef bool(tBTA_SYS_VS_EVT_HDLR)(uint16_t evt, void* p); /* event handler function type */ typedef bool(tBTA_SYS_EVT_HDLR)(const BT_HDR_RIGID* p_msg); -static_assert( - sizeof(BT_HDR) == sizeof(BT_HDR_RIGID), - "Rigid replacement should be same size struct with flexible member"); +static_assert(sizeof(BT_HDR) == sizeof(BT_HDR_RIGID), + "Rigid replacement should be same size struct with flexible member"); /* disable function type */ typedef void(tBTA_SYS_DISABLE)(void); @@ -67,39 +66,39 @@ inline const T* Specialize(U* u) { typedef enum : uint8_t { /* SW sub-systems */ - BTA_ID_SYS = 0, /* system manager */ - /* BLUETOOTH PART - from = 0, to BTA_ID_BLUETOOTH_MAX */ - BTA_ID_DM_SEC = 3, /* device manager security */ - BTA_ID_DG = 4, /* data gateway */ - BTA_ID_AG = 5, /* audio gateway */ - BTA_ID_OPC = 6, /* object push client */ - BTA_ID_OPS = 7, /* object push server */ - BTA_ID_FTS = 8, /* file transfer server */ - BTA_ID_CT = 9, /* cordless telephony terminal */ - BTA_ID_FTC = 10, /* file transfer client */ - BTA_ID_SS = 11, /* synchronization server */ - BTA_ID_PR = 12, /* Printer client */ - BTA_ID_BIC = 13, /* Basic Imaging Client */ - BTA_ID_PAN = 14, /* Personal Area Networking */ - BTA_ID_BIS = 15, /* Basic Imaging Server */ - BTA_ID_ACC = 16, /* Advanced Camera Client */ - BTA_ID_SC = 17, /* SIM Card Access server */ - BTA_ID_AV = 18, /* Advanced audio/video */ - BTA_ID_AVK = 19, /* Audio/video sink */ - BTA_ID_HD = 20, /* HID Device */ - BTA_ID_CG = 21, /* Cordless Gateway */ - BTA_ID_BP = 22, /* Basic Printing Client */ - BTA_ID_HH = 23, /* Human Interface Device Host */ - BTA_ID_PBS = 24, /* Phone Book Access Server */ - BTA_ID_PBC = 25, /* Phone Book Access Client */ - BTA_ID_JV = 26, /* Java */ - BTA_ID_HS = 27, /* Headset */ - BTA_ID_MSE = 28, /* Message Server Equipment */ - BTA_ID_MCE = 29, /* Message Client Equipment */ - BTA_ID_HL = 30, /* Health Device Profile*/ - BTA_ID_GATTC = 31, /* GATT Client */ - BTA_ID_GATTS = 32, /* GATT Client */ - BTA_ID_SDP = 33, /* SDP Client */ + BTA_ID_SYS = 0, /* system manager */ + /* BLUETOOTH PART - from = 0, to BTA_ID_BLUETOOTH_MAX */ + BTA_ID_DM_SEC = 3, /* device manager security */ + BTA_ID_DG = 4, /* data gateway */ + BTA_ID_AG = 5, /* audio gateway */ + BTA_ID_OPC = 6, /* object push client */ + BTA_ID_OPS = 7, /* object push server */ + BTA_ID_FTS = 8, /* file transfer server */ + BTA_ID_CT = 9, /* cordless telephony terminal */ + BTA_ID_FTC = 10, /* file transfer client */ + BTA_ID_SS = 11, /* synchronization server */ + BTA_ID_PR = 12, /* Printer client */ + BTA_ID_BIC = 13, /* Basic Imaging Client */ + BTA_ID_PAN = 14, /* Personal Area Networking */ + BTA_ID_BIS = 15, /* Basic Imaging Server */ + BTA_ID_ACC = 16, /* Advanced Camera Client */ + BTA_ID_SC = 17, /* SIM Card Access server */ + BTA_ID_AV = 18, /* Advanced audio/video */ + BTA_ID_AVK = 19, /* Audio/video sink */ + BTA_ID_HD = 20, /* HID Device */ + BTA_ID_CG = 21, /* Cordless Gateway */ + BTA_ID_BP = 22, /* Basic Printing Client */ + BTA_ID_HH = 23, /* Human Interface Device Host */ + BTA_ID_PBS = 24, /* Phone Book Access Server */ + BTA_ID_PBC = 25, /* Phone Book Access Client */ + BTA_ID_JV = 26, /* Java */ + BTA_ID_HS = 27, /* Headset */ + BTA_ID_MSE = 28, /* Message Server Equipment */ + BTA_ID_MCE = 29, /* Message Client Equipment */ + BTA_ID_HL = 30, /* Health Device Profile*/ + BTA_ID_GATTC = 31, /* GATT Client */ + BTA_ID_GATTS = 32, /* GATT Client */ + BTA_ID_SDP = 33, /* SDP Client */ BTA_ID_BLUETOOTH_MAX = 34, /* last BT profile */ BTA_ID_MAX = (44 + BTA_DM_NUM_JV_ID), @@ -183,24 +182,18 @@ inline std::string bta_sys_conn_status_text(tBTA_SYS_CONN_STATUS status) { } /* conn callback for power mode manager */ -typedef void(tBTA_SYS_CONN_CBACK)(tBTA_SYS_CONN_STATUS status, - const tBTA_SYS_ID id, uint8_t app_id, +typedef void(tBTA_SYS_CONN_CBACK)(tBTA_SYS_CONN_STATUS status, const tBTA_SYS_ID id, uint8_t app_id, const RawAddress& peer_addr); /* conn callback for sco change */ -typedef void(tBTA_SYS_CONN_SCO_CBACK)(tBTA_SYS_CONN_STATUS status, - uint8_t num_sco_links, uint8_t app_id, - const RawAddress& peer_addr); +typedef void(tBTA_SYS_CONN_SCO_CBACK)(tBTA_SYS_CONN_STATUS status, uint8_t num_sco_links, + uint8_t app_id, const RawAddress& peer_addr); /* callback for role switch */ -typedef void(tBTA_SYS_ROLE_SWITCH_CBACK)(tBTA_SYS_CONN_STATUS status, - tHCI_ROLE new_role, - tHCI_STATUS hci_status, - const RawAddress& peer_addr); +typedef void(tBTA_SYS_ROLE_SWITCH_CBACK)(tBTA_SYS_CONN_STATUS status, tHCI_ROLE new_role, + tHCI_STATUS hci_status, const RawAddress& peer_addr); /* callback for sniff subrating updates */ -typedef void(tBTA_SYS_SSR_CFG_CBACK)(uint8_t id, uint8_t app_id, - uint16_t latency, uint16_t tout); +typedef void(tBTA_SYS_SSR_CFG_CBACK)(uint8_t id, uint8_t app_id, uint16_t latency, uint16_t tout); -typedef void(tBTA_SYS_SNIFF_CBACK)(uint8_t id, uint8_t app_id, - const RawAddress& peer_addr); +typedef void(tBTA_SYS_SNIFF_CBACK)(uint8_t id, uint8_t app_id, const RawAddress& peer_addr); typedef struct { bluetooth::Uuid custom_uuid; @@ -209,8 +202,7 @@ typedef struct { /* eir callback for adding/removeing UUID */ typedef void(tBTA_SYS_EIR_CBACK)(uint16_t uuid16, bool adding); -typedef void(tBTA_SYS_CUST_EIR_CBACK)(const tBTA_CUSTOM_UUID& curr, - bool adding); +typedef void(tBTA_SYS_CUST_EIR_CBACK)(const tBTA_CUSTOM_UUID& curr, bool adding); /* registration structure */ typedef struct { @@ -242,32 +234,22 @@ void bta_sys_pm_register(tBTA_SYS_CONN_CBACK* p_cback); void bta_sys_sniff_register(tBTA_SYS_SNIFF_CBACK* p_cback); void bta_sys_sco_register(tBTA_SYS_CONN_SCO_CBACK* p_cback); -void bta_sys_conn_open(tBTA_SYS_ID id, uint8_t app_id, - const RawAddress& peer_addr); -void bta_sys_conn_close(tBTA_SYS_ID id, uint8_t app_id, - const RawAddress& peer_addr); -void bta_sys_app_open(tBTA_SYS_ID id, uint8_t app_id, - const RawAddress& peer_addr); -void bta_sys_app_close(tBTA_SYS_ID id, uint8_t app_id, - const RawAddress& peer_addr); -void bta_sys_sco_open(tBTA_SYS_ID id, uint8_t app_id, - const RawAddress& peer_addr); -void bta_sys_sco_close(tBTA_SYS_ID id, uint8_t app_id, - const RawAddress& peer_addr); -void bta_sys_sco_use(tBTA_SYS_ID id, uint8_t app_id, - const RawAddress& peer_addr); -void bta_sys_sco_unuse(tBTA_SYS_ID id, uint8_t app_id, - const RawAddress& peer_addr); +void bta_sys_conn_open(tBTA_SYS_ID id, uint8_t app_id, const RawAddress& peer_addr); +void bta_sys_conn_close(tBTA_SYS_ID id, uint8_t app_id, const RawAddress& peer_addr); +void bta_sys_app_open(tBTA_SYS_ID id, uint8_t app_id, const RawAddress& peer_addr); +void bta_sys_app_close(tBTA_SYS_ID id, uint8_t app_id, const RawAddress& peer_addr); +void bta_sys_sco_open(tBTA_SYS_ID id, uint8_t app_id, const RawAddress& peer_addr); +void bta_sys_sco_close(tBTA_SYS_ID id, uint8_t app_id, const RawAddress& peer_addr); +void bta_sys_sco_use(tBTA_SYS_ID id, uint8_t app_id, const RawAddress& peer_addr); +void bta_sys_sco_unuse(tBTA_SYS_ID id, uint8_t app_id, const RawAddress& peer_addr); void bta_sys_idle(tBTA_SYS_ID id, uint8_t app_id, const RawAddress& peer_addr); void bta_sys_busy(tBTA_SYS_ID id, uint8_t app_id, const RawAddress& peer_addr); -void bta_sys_reset_sniff(uint8_t id, uint8_t app_id, - const RawAddress& peer_addr); +void bta_sys_reset_sniff(uint8_t id, uint8_t app_id, const RawAddress& peer_addr); void bta_sys_role_chg_register(tBTA_SYS_ROLE_SWITCH_CBACK* p_cback); void bta_sys_notify_role_chg(const RawAddress& peer_addr, tHCI_ROLE new_role, tHCI_STATUS hci_status); -void bta_sys_collision_register(tBTA_SYS_ID bta_id, - tBTA_SYS_CONN_CBACK* p_cback); +void bta_sys_collision_register(tBTA_SYS_ID bta_id, tBTA_SYS_CONN_CBACK* p_cback); void bta_sys_notify_collision(const RawAddress& peer_addr); void bta_sys_eir_register(tBTA_SYS_EIR_CBACK* p_cback); @@ -282,8 +264,7 @@ namespace fmt { template <> struct formatter : enum_formatter {}; template <> -struct formatter : enum_formatter { -}; +struct formatter : enum_formatter {}; } // namespace fmt #endif /* BTA_SYS_H */ diff --git a/system/bta/sys/bta_sys_conn.cc b/system/bta/sys/bta_sys_conn.cc index fc18ebe3667..a4662fc0889 100644 --- a/system/bta/sys/bta_sys_conn.cc +++ b/system/bta/sys/bta_sys_conn.cc @@ -43,9 +43,7 @@ using namespace bluetooth; * Returns void * ******************************************************************************/ -void bta_sys_rm_register(tBTA_SYS_CONN_CBACK* p_cback) { - bta_sys_cb.prm_cb = p_cback; -} +void bta_sys_rm_register(tBTA_SYS_CONN_CBACK* p_cback) { bta_sys_cb.prm_cb = p_cback; } /******************************************************************************* * @@ -73,8 +71,8 @@ void bta_sys_role_chg_register(tBTA_SYS_ROLE_SWITCH_CBACK* p_cback) { ******************************************************************************/ void bta_sys_notify_role_chg(const RawAddress& peer_addr, tHCI_ROLE new_role, tHCI_STATUS hci_status) { - log::debug("Role changed peer:{} new_role:{} hci_status:{}", peer_addr, - RoleText(new_role), hci_error_code_text(hci_status)); + log::debug("Role changed peer:{} new_role:{} hci_status:{}", peer_addr, RoleText(new_role), + hci_error_code_text(hci_status)); if (bta_sys_cb.p_role_cb) { bta_sys_cb.p_role_cb(BTA_SYS_ROLE_CHANGE, new_role, hci_status, peer_addr); } @@ -90,13 +88,11 @@ void bta_sys_notify_role_chg(const RawAddress& peer_addr, tHCI_ROLE new_role, * Returns void * ******************************************************************************/ -void bta_sys_collision_register(tBTA_SYS_ID bta_id, - tBTA_SYS_CONN_CBACK* p_cback) { +void bta_sys_collision_register(tBTA_SYS_ID bta_id, tBTA_SYS_CONN_CBACK* p_cback) { uint8_t index; for (index = 0; index < MAX_COLLISION_REG; index++) { - if ((bta_sys_cb.colli_reg.id[index] == bta_id) || - (bta_sys_cb.colli_reg.id[index] == 0)) { + if ((bta_sys_cb.colli_reg.id[index] == bta_id) || (bta_sys_cb.colli_reg.id[index] == 0)) { bta_sys_cb.colli_reg.id[index] = bta_id; bta_sys_cb.colli_reg.p_coll_cback[index] = p_cback; return; @@ -120,8 +116,7 @@ void bta_sys_notify_collision(const RawAddress& peer_addr) { for (index = 0; index < MAX_COLLISION_REG; index++) { if ((bta_sys_cb.colli_reg.id[index] != 0) && (bta_sys_cb.colli_reg.p_coll_cback[index] != NULL)) { - bta_sys_cb.colli_reg.p_coll_cback[index](BTA_SYS_CONN_OPEN, BTA_ID_SYS, 0, - peer_addr); + bta_sys_cb.colli_reg.p_coll_cback[index](BTA_SYS_CONN_OPEN, BTA_ID_SYS, 0, peer_addr); } } } @@ -136,9 +131,7 @@ void bta_sys_notify_collision(const RawAddress& peer_addr) { * Returns void * ******************************************************************************/ -void bta_sys_sco_register(tBTA_SYS_CONN_SCO_CBACK* p_cback) { - bta_sys_cb.p_sco_cb = p_cback; -} +void bta_sys_sco_register(tBTA_SYS_CONN_SCO_CBACK* p_cback) { bta_sys_cb.p_sco_cb = p_cback; } /******************************************************************************* * @@ -150,9 +143,7 @@ void bta_sys_sco_register(tBTA_SYS_CONN_SCO_CBACK* p_cback) { * Returns void * ******************************************************************************/ -void bta_sys_pm_register(tBTA_SYS_CONN_CBACK* p_cback) { - bta_sys_cb.ppm_cb = p_cback; -} +void bta_sys_pm_register(tBTA_SYS_CONN_CBACK* p_cback) { bta_sys_cb.ppm_cb = p_cback; } /******************************************************************************* * @@ -164,9 +155,7 @@ void bta_sys_pm_register(tBTA_SYS_CONN_CBACK* p_cback) { * Returns void * ******************************************************************************/ -void bta_sys_sniff_register(tBTA_SYS_SNIFF_CBACK* p_cback) { - bta_sys_cb.sniff_cb = p_cback; -} +void bta_sys_sniff_register(tBTA_SYS_SNIFF_CBACK* p_cback) { bta_sys_cb.sniff_cb = p_cback; } /******************************************************************************* * @@ -178,8 +167,7 @@ void bta_sys_sniff_register(tBTA_SYS_SNIFF_CBACK* p_cback) { * Returns void * ******************************************************************************/ -void bta_sys_reset_sniff(uint8_t id, uint8_t app_id, - const RawAddress& peer_addr) { +void bta_sys_reset_sniff(uint8_t id, uint8_t app_id, const RawAddress& peer_addr) { if (bta_sys_cb.sniff_cb) { bta_sys_cb.sniff_cb(id, app_id, peer_addr); } @@ -196,8 +184,7 @@ void bta_sys_reset_sniff(uint8_t id, uint8_t app_id, * Returns void * ******************************************************************************/ -void bta_sys_conn_open(tBTA_SYS_ID id, uint8_t app_id, - const RawAddress& peer_addr) { +void bta_sys_conn_open(tBTA_SYS_ID id, uint8_t app_id, const RawAddress& peer_addr) { if (bta_sys_cb.prm_cb) { bta_sys_cb.prm_cb(BTA_SYS_CONN_OPEN, id, app_id, peer_addr); } @@ -218,8 +205,7 @@ void bta_sys_conn_open(tBTA_SYS_ID id, uint8_t app_id, * Returns void * ******************************************************************************/ -void bta_sys_conn_close(tBTA_SYS_ID id, uint8_t app_id, - const RawAddress& peer_addr) { +void bta_sys_conn_close(tBTA_SYS_ID id, uint8_t app_id, const RawAddress& peer_addr) { if (bta_sys_cb.prm_cb) { bta_sys_cb.prm_cb(BTA_SYS_CONN_CLOSE, id, app_id, peer_addr); } @@ -240,8 +226,7 @@ void bta_sys_conn_close(tBTA_SYS_ID id, uint8_t app_id, * Returns void * ******************************************************************************/ -void bta_sys_app_open(tBTA_SYS_ID id, uint8_t app_id, - const RawAddress& peer_addr) { +void bta_sys_app_open(tBTA_SYS_ID id, uint8_t app_id, const RawAddress& peer_addr) { if (bta_sys_cb.ppm_cb) { bta_sys_cb.ppm_cb(BTA_SYS_APP_OPEN, id, app_id, peer_addr); } @@ -257,8 +242,7 @@ void bta_sys_app_open(tBTA_SYS_ID id, uint8_t app_id, * Returns void * ******************************************************************************/ -void bta_sys_app_close(tBTA_SYS_ID id, uint8_t app_id, - const RawAddress& peer_addr) { +void bta_sys_app_close(tBTA_SYS_ID id, uint8_t app_id, const RawAddress& peer_addr) { if (bta_sys_cb.ppm_cb) { bta_sys_cb.ppm_cb(BTA_SYS_APP_CLOSE, id, app_id, peer_addr); } @@ -274,8 +258,7 @@ void bta_sys_app_close(tBTA_SYS_ID id, uint8_t app_id, * Returns void * ******************************************************************************/ -void bta_sys_sco_open(tBTA_SYS_ID id, uint8_t app_id, - const RawAddress& peer_addr) { +void bta_sys_sco_open(tBTA_SYS_ID id, uint8_t app_id, const RawAddress& peer_addr) { /* AG triggers p_sco_cb by bta_sys_sco_use. */ if ((id != BTA_ID_AG) && (bta_sys_cb.p_sco_cb)) { /* without querying BTM_GetNumScoLinks() */ @@ -297,8 +280,7 @@ void bta_sys_sco_open(tBTA_SYS_ID id, uint8_t app_id, * Returns void * ******************************************************************************/ -void bta_sys_sco_close(tBTA_SYS_ID id, uint8_t app_id, - const RawAddress& peer_addr) { +void bta_sys_sco_close(tBTA_SYS_ID id, uint8_t app_id, const RawAddress& peer_addr) { uint8_t num_sco_links; if ((id != BTA_ID_AG) && (bta_sys_cb.p_sco_cb)) { @@ -321,8 +303,7 @@ void bta_sys_sco_close(tBTA_SYS_ID id, uint8_t app_id, * Returns void * ******************************************************************************/ -void bta_sys_sco_use(tBTA_SYS_ID /* id */, uint8_t app_id, - const RawAddress& peer_addr) { +void bta_sys_sco_use(tBTA_SYS_ID /* id */, uint8_t app_id, const RawAddress& peer_addr) { /* AV streaming need to be suspended before SCO is connected. */ if (bta_sys_cb.p_sco_cb) { /* without querying BTM_GetNumScoLinks() */ @@ -340,9 +321,8 @@ void bta_sys_sco_use(tBTA_SYS_ID /* id */, uint8_t app_id, * Returns void * ******************************************************************************/ -void bta_sys_sco_unuse(tBTA_SYS_ID /* id */, uint8_t app_id, - const RawAddress& peer_addr) { - if ((bta_sys_cb.p_sco_cb)) { +void bta_sys_sco_unuse(tBTA_SYS_ID /* id */, uint8_t app_id, const RawAddress& peer_addr) { + if (bta_sys_cb.p_sco_cb) { uint8_t num_sco_links = get_btm_client_interface().sco.BTM_GetNumScoLinks(); bta_sys_cb.p_sco_cb(BTA_SYS_SCO_CLOSE, num_sco_links, app_id, peer_addr); } diff --git a/system/bta/sys/bta_sys_int.h b/system/bta/sys/bta_sys_int.h index 753b046c77e..7f37764fc57 100644 --- a/system/bta/sys/bta_sys_int.h +++ b/system/bta/sys/bta_sys_int.h @@ -50,18 +50,14 @@ typedef struct { bool is_reg[BTA_ID_MAX]; /* registration structures */ uint16_t sys_features; /* Bitmask of sys features */ - tBTA_SYS_CONN_CBACK* prm_cb; /* role management callback registered by DM */ - tBTA_SYS_CONN_CBACK* - ppm_cb; /* low power management callback registered by DM */ - tBTA_SYS_SNIFF_CBACK* - sniff_cb; /* low power management sniff callback registered by DM */ - tBTA_SYS_CONN_SCO_CBACK* - p_sco_cb; /* SCO connection change callback registered by AV */ - tBTA_SYS_ROLE_SWITCH_CBACK* - p_role_cb; /* role change callback registered by AV */ - tBTA_SYS_COLLISION colli_reg; /* collision handling module */ - tBTA_SYS_EIR_CBACK* eir_cb; /* add/remove UUID into EIR */ - tBTA_SYS_CUST_EIR_CBACK* cust_eir_cb; /* add/remove customer UUID into EIR */ + tBTA_SYS_CONN_CBACK* prm_cb; /* role management callback registered by DM */ + tBTA_SYS_CONN_CBACK* ppm_cb; /* low power management callback registered by DM */ + tBTA_SYS_SNIFF_CBACK* sniff_cb; /* low power management sniff callback registered by DM */ + tBTA_SYS_CONN_SCO_CBACK* p_sco_cb; /* SCO connection change callback registered by AV */ + tBTA_SYS_ROLE_SWITCH_CBACK* p_role_cb; /* role change callback registered by AV */ + tBTA_SYS_COLLISION colli_reg; /* collision handling module */ + tBTA_SYS_EIR_CBACK* eir_cb; /* add/remove UUID into EIR */ + tBTA_SYS_CUST_EIR_CBACK* cust_eir_cb; /* add/remove customer UUID into EIR */ tBTA_SYS_SSR_CFG_CBACK* p_ssr_cb; /* VS event handler */ tBTA_SYS_VS_EVT_HDLR* p_vs_evt_hdlr; diff --git a/system/bta/sys/bta_sys_main.cc b/system/bta/sys/bta_sys_main.cc index ae0279d176b..5229f3d365c 100644 --- a/system/bta/sys/bta_sys_main.cc +++ b/system/bta/sys/bta_sys_main.cc @@ -54,9 +54,7 @@ tBTA_SYS_CB bta_sys_cb; * Returns void * ******************************************************************************/ -void bta_sys_init(void) { - memset(&bta_sys_cb, 0, sizeof(tBTA_SYS_CB)); -} +void bta_sys_init(void) { memset(&bta_sys_cb, 0, sizeof(tBTA_SYS_CB)); } /******************************************************************************* * @@ -147,19 +145,17 @@ bool bta_sys_is_register(uint8_t id) { return bta_sys_cb.is_reg[id]; } * ******************************************************************************/ void bta_sys_sendmsg(void* p_msg) { - if (do_in_main_thread( - FROM_HERE, - base::BindOnce(&bta_sys_event, static_cast(p_msg))) != + if (do_in_main_thread(FROM_HERE, + base::BindOnce(&bta_sys_event, static_cast(p_msg))) != BT_STATUS_SUCCESS) { log::error("do_in_main_thread failed"); } } void bta_sys_sendmsg_delayed(void* p_msg, std::chrono::microseconds delay) { - if (do_in_main_thread_delayed( - FROM_HERE, - base::Bind(&bta_sys_event, static_cast(p_msg)), - delay) != BT_STATUS_SUCCESS) { + if (do_in_main_thread_delayed(FROM_HERE, + base::Bind(&bta_sys_event, static_cast(p_msg)), + delay) != BT_STATUS_SUCCESS) { log::error("do_in_main_thread_delayed failed"); } } @@ -199,8 +195,7 @@ void bta_sys_disable() { for (; bta_id <= bta_id_max; bta_id++) { if (bta_sys_cb.reg[bta_id] != NULL) { - if (bta_sys_cb.is_reg[bta_id] && - bta_sys_cb.reg[bta_id]->disable != NULL) { + if (bta_sys_cb.is_reg[bta_id] && bta_sys_cb.reg[bta_id]->disable != NULL) { (*bta_sys_cb.reg[bta_id]->disable)(); } } diff --git a/system/bta/sys/utl.cc b/system/bta/sys/utl.cc index b7edaefe92a..a9c1a6f5d0c 100644 --- a/system/bta/sys/utl.cc +++ b/system/bta/sys/utl.cc @@ -48,14 +48,20 @@ int16_t utl_str2int(const char* p_s) { for (; *p_s == ' ' && *p_s != 0; p_s++) ; - if (*p_s == 0) return -1; + if (*p_s == 0) { + return -1; + } for (;;) { - if ((*p_s < '0') || (*p_s > '9')) return -1; + if ((*p_s < '0') || (*p_s > '9')) { + return -1; + } val += (int32_t)(*p_s++ - '0'); - if (val > 32767) return -1; + if (val > 32767) { + return -1; + } if (*p_s == 0) { return (int16_t)val; @@ -206,7 +212,9 @@ bool utl_set_device_class(tBTA_UTL_COD* p_cod, uint8_t cmd) { DEV_CLASS dev_class; FIELDS_TO_COD(dev_class, minor, major, service); - if (BTM_SetDeviceClass(dev_class) == BTM_SUCCESS) return true; + if (BTM_SetDeviceClass(dev_class) == BTM_SUCCESS) { + return true; + } return false; } @@ -226,7 +234,9 @@ bool utl_isintstr(const char* p_s) { uint16_t i = 0; for (i = 0; p_s[i] != 0; i++) { - if (((p_s[i] < '0') || (p_s[i] > '9')) && (p_s[i] != ';')) return false; + if (((p_s[i] < '0') || (p_s[i] > '9')) && (p_s[i] != ';')) { + return false; + } } return true; @@ -243,10 +253,9 @@ bool utl_isintstr(const char* p_s) { * ******************************************************************************/ bool utl_isdialchar(const char d) { - return (((d >= '0') && (d <= '9')) || (d == '*') || (d == '+') || - (d == '#') || (d == ';') || (d == ',') || - ((d >= 'A') && (d <= 'C')) || - ((d == 'p') || (d == 'P') || (d == 'w') || (d == 'W'))); + return ((d >= '0') && (d <= '9')) || (d == '*') || (d == '+') || (d == '#') || (d == ';') || + (d == ',') || ((d >= 'A') && (d <= 'C')) || + ((d == 'p') || (d == 'P') || (d == 'w') || (d == 'W')); } /******************************************************************************* @@ -263,7 +272,9 @@ bool utl_isdialchar(const char d) { bool utl_isdialstr(const char* p_s) { for (uint16_t i = 0; p_s[i] != 0; i++) { // include chars not in spec that work sent by some headsets. - if (!(utl_isdialchar(p_s[i]) || (p_s[i] == '-'))) return false; + if (!(utl_isdialchar(p_s[i]) || (p_s[i] == '-'))) { + return false; + } } return true; } diff --git a/system/bta/test/bta_ag_sco_test.cc b/system/bta/test/bta_ag_sco_test.cc index 2fb9eb126b1..78c7902966f 100644 --- a/system/bta/test/bta_ag_sco_test.cc +++ b/system/bta/test/bta_ag_sco_test.cc @@ -35,15 +35,14 @@ bool LeAudioClient::IsLeAudioClientInStreaming() { return false; } const RawAddress kRawAddress({0x11, 0x22, 0x33, 0x44, 0x55, 0x66}); class BtaAgScoParameterSelectionTest - : public ::testing::TestWithParam< - std::tuple> { - protected: + : public ::testing::TestWithParam> { +protected: void SetUp() override { test::mock::device_esco_parameters::esco_parameters_for_codec.body = - [this](esco_codec_t codec) { - this->codec = codec; - return enh_esco_params_t{}; - }; + [this](esco_codec_t codec) { + this->codec = codec; + return enh_esco_params_t{}; + }; bluetooth::hci::testing::mock_controller_ = &controller_; } void TearDown() override { @@ -59,17 +58,16 @@ TEST_P(BtaAgScoParameterSelectionTest, create_sco_cvsd) { const auto [feature, peer_feature, is_local] = GetParam(); tBTA_AG_SCB scb{ - .peer_addr = kRawAddress, - .features = feature, - .peer_features = peer_feature, - .sco_idx = BTM_INVALID_SCO_INDEX, - .inuse_codec = tBTA_AG_UUID_CODEC::UUID_CODEC_CVSD, + .peer_addr = kRawAddress, + .features = feature, + .peer_features = peer_feature, + .sco_idx = BTM_INVALID_SCO_INDEX, + .inuse_codec = tBTA_AG_UUID_CODEC::UUID_CODEC_CVSD, }; this->codec = ESCO_CODEC_UNKNOWN; bta_ag_create_sco(&scb, is_local); - if ((scb.features & BTA_AG_FEAT_ESCO_S4) && - (scb.peer_features & BTA_AG_PEER_FEAT_ESCO_S4)) { + if ((scb.features & BTA_AG_FEAT_ESCO_S4) && (scb.peer_features & BTA_AG_PEER_FEAT_ESCO_S4)) { ASSERT_EQ(this->codec, ESCO_CODEC_CVSD_S4); } else { ASSERT_EQ(this->codec, ESCO_CODEC_CVSD_S3); @@ -81,11 +79,11 @@ TEST_P(BtaAgScoParameterSelectionTest, create_pending_sco_cvsd) { const auto [feature, peer_feature, is_local] = GetParam(); tBTA_AG_SCB scb{ - .peer_addr = kRawAddress, - .features = feature, - .peer_features = peer_feature, - .sco_idx = BTM_INVALID_SCO_INDEX, - .inuse_codec = tBTA_AG_UUID_CODEC::UUID_CODEC_CVSD, + .peer_addr = kRawAddress, + .features = feature, + .peer_features = peer_feature, + .sco_idx = BTM_INVALID_SCO_INDEX, + .inuse_codec = tBTA_AG_UUID_CODEC::UUID_CODEC_CVSD, }; this->codec = ESCO_CODEC_UNKNOWN; @@ -96,8 +94,7 @@ TEST_P(BtaAgScoParameterSelectionTest, create_pending_sco_cvsd) { tBTM_ESCO_CONN_REQ_EVT_DATA data; bta_ag_sco_conn_rsp(&scb, &data); } - if ((scb.features & BTA_AG_FEAT_ESCO_S4) && - (scb.peer_features & BTA_AG_PEER_FEAT_ESCO_S4)) { + if ((scb.features & BTA_AG_FEAT_ESCO_S4) && (scb.peer_features & BTA_AG_PEER_FEAT_ESCO_S4)) { ASSERT_EQ(this->codec, ESCO_CODEC_CVSD_S4); } else { ASSERT_EQ(this->codec, ESCO_CODEC_CVSD_S3); @@ -121,6 +118,5 @@ BtaAgScoParameterSelectionTestParameters() { return params; } -INSTANTIATE_TEST_SUITE_P( - BtaAgScoParameterSelectionTests, BtaAgScoParameterSelectionTest, - ::testing::ValuesIn(BtaAgScoParameterSelectionTestParameters())); +INSTANTIATE_TEST_SUITE_P(BtaAgScoParameterSelectionTests, BtaAgScoParameterSelectionTest, + ::testing::ValuesIn(BtaAgScoParameterSelectionTestParameters())); diff --git a/system/bta/test/bta_ag_test.cc b/system/bta/test/bta_ag_test.cc index a40bf2542a9..6ddc9f806fb 100644 --- a/system/bta/test/bta_ag_test.cc +++ b/system/bta/test/bta_ag_test.cc @@ -45,15 +45,14 @@ using namespace bluetooth; namespace { -bool bta_ag_hdl_event(const BT_HDR_RIGID* p_msg) { return true; }; +bool bta_ag_hdl_event(const BT_HDR_RIGID* p_msg) { return true; } void BTA_AgDisable() { bta_sys_deregister(BTA_ID_AG); } const tBTA_SYS_REG bta_ag_reg = {bta_ag_hdl_event, BTA_AgDisable}; } // namespace -const std::string kBtCodecAptxVoiceEnabled = - "bluetooth.hfp.codec_aptx_voice.enabled"; +const std::string kBtCodecAptxVoiceEnabled = "bluetooth.hfp.codec_aptx_voice.enabled"; static bool enable_aptx_voice_property(bool enable) { const std::string value = enable ? "true" : "false"; @@ -61,7 +60,7 @@ static bool enable_aptx_voice_property(bool enable) { } class BtaAgTest : public testing::Test { - protected: +protected: void SetUp() override { reset_mock_function_count_map(); fake_osi_ = std::make_unique(); @@ -75,10 +74,10 @@ class BtaAgTest : public testing::Test { bta_ag_cb.p_cback = [](tBTA_AG_EVT event, tBTA_AG* p_data) {}; RawAddress::FromString("00:11:22:33:44:55", addr); test::mock::device_esco_parameters::esco_parameters_for_codec.body = - [this](esco_codec_t codec) { - this->codec = codec; - return enh_esco_params_t{}; - }; + [this](esco_codec_t codec) { + this->codec = codec; + return enh_esco_params_t{}; + }; } void TearDown() override { test::mock::device_esco_parameters::esco_parameters_for_codec = {}; @@ -89,8 +88,7 @@ class BtaAgTest : public testing::Test { } std::unique_ptr fake_osi_; - const char test_strings[5][13] = {"0,4,6,7", "4,6,7", "test,0,4", "9,8,7", - "4,6,7,test"}; + const char test_strings[5][13] = {"0,4,6,7", "4,6,7", "test,0,4", "9,8,7", "4,6,7,test"}; uint32_t tmp_num = 0xFFFF; RawAddress addr; esco_codec_t codec; @@ -98,21 +96,19 @@ class BtaAgTest : public testing::Test { }; TEST_F_WITH_FLAGS(BtaAgTest, nop, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, - hfp_codec_aptx_voice))) { + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, hfp_codec_aptx_voice))) { bool status = true; ASSERT_EQ(true, status); } class BtaAgSwbTest : public BtaAgTest { - protected: +protected: void SetUp() override { BtaAgTest::SetUp(); } void TearDown() override { BtaAgTest::TearDown(); } }; TEST_F_WITH_FLAGS(BtaAgSwbTest, parse_qac_at_command, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, - hfp_codec_aptx_voice))) { + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, hfp_codec_aptx_voice))) { tBTA_AG_PEER_CODEC codec = bta_ag_parse_qac((char*)test_strings[0]); codec = bta_ag_parse_qac((char*)test_strings[0]); ASSERT_TRUE(codec & BTA_AG_SCO_APTX_SWB_SETTINGS_Q0_MASK); @@ -139,36 +135,30 @@ TEST_F_WITH_FLAGS(BtaAgSwbTest, parse_qac_at_command, } TEST_F_WITH_FLAGS(BtaAgSwbTest, enable_swb_codec_fail, - REQUIRES_FLAGS_DISABLED(ACONFIG_FLAG(TEST_BT, - hfp_codec_aptx_voice))) { + REQUIRES_FLAGS_DISABLED(ACONFIG_FLAG(TEST_BT, hfp_codec_aptx_voice))) { ASSERT_TRUE(enable_aptx_voice_property(false)); ASSERT_EQ(BT_STATUS_FAIL, enable_aptx_swb_codec(true, &addr)); - ASSERT_FALSE(get_swb_codec_status( - bluetooth::headset::BTHF_SWB_CODEC_VENDOR_APTX, &addr)); + ASSERT_FALSE(get_swb_codec_status(bluetooth::headset::BTHF_SWB_CODEC_VENDOR_APTX, &addr)); } TEST_F_WITH_FLAGS(BtaAgSwbTest, enable_swb_codec_success, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, - hfp_codec_aptx_voice))) { + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, hfp_codec_aptx_voice))) { ASSERT_TRUE(enable_aptx_voice_property(true)); ASSERT_EQ(BT_STATUS_SUCCESS, enable_aptx_swb_codec(true, &addr)); - ASSERT_TRUE(get_swb_codec_status( - bluetooth::headset::BTHF_SWB_CODEC_VENDOR_APTX, &addr)); + ASSERT_TRUE(get_swb_codec_status(bluetooth::headset::BTHF_SWB_CODEC_VENDOR_APTX, &addr)); ASSERT_TRUE(enable_aptx_voice_property(false)); } class BtaAgActTest : public BtaAgTest { - protected: +protected: void SetUp() override { BtaAgTest::SetUp(); } void TearDown() override { BtaAgTest::TearDown(); } }; TEST_F_WITH_FLAGS(BtaAgActTest, set_codec_q0_success, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, - hfp_codec_aptx_voice))) { + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, hfp_codec_aptx_voice))) { tBTA_AG_SCB* p_scb = &bta_ag_cb.scb[0]; - const tBTA_AG_DATA data = {.api_setcodec.codec = - BTA_AG_SCO_APTX_SWB_SETTINGS_Q0}; + const tBTA_AG_DATA data = {.api_setcodec.codec = BTA_AG_SCO_APTX_SWB_SETTINGS_Q0}; bta_ag_cb.p_cback = [](tBTA_AG_EVT event, tBTA_AG* p_data) { tBTA_AG_VAL* val = (tBTA_AG_VAL*)p_data; @@ -185,11 +175,9 @@ TEST_F_WITH_FLAGS(BtaAgActTest, set_codec_q0_success, } TEST_F_WITH_FLAGS(BtaAgActTest, set_codec_q1_fail_unsupported, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, - hfp_codec_aptx_voice))) { + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, hfp_codec_aptx_voice))) { tBTA_AG_SCB* p_scb = &bta_ag_cb.scb[0]; - const tBTA_AG_DATA data = {.api_setcodec.codec = - BTA_AG_SCO_APTX_SWB_SETTINGS_Q1}; + const tBTA_AG_DATA data = {.api_setcodec.codec = BTA_AG_SCO_APTX_SWB_SETTINGS_Q1}; ASSERT_TRUE(enable_aptx_voice_property(true)); @@ -208,14 +196,13 @@ TEST_F_WITH_FLAGS(BtaAgActTest, set_codec_q1_fail_unsupported, } class BtaAgCmdTest : public BtaAgTest { - protected: +protected: void SetUp() override { BtaAgTest::SetUp(); } void TearDown() override { BtaAgTest::TearDown(); } }; TEST_F_WITH_FLAGS(BtaAgCmdTest, check_flag_disabling_guarding_with_prop, - REQUIRES_FLAGS_DISABLED(ACONFIG_FLAG(TEST_BT, - hfp_codec_aptx_voice))) { + REQUIRES_FLAGS_DISABLED(ACONFIG_FLAG(TEST_BT, hfp_codec_aptx_voice))) { ASSERT_FALSE(com::android::bluetooth::flags::hfp_codec_aptx_voice()); ASSERT_TRUE(enable_aptx_voice_property(false)); ASSERT_FALSE(is_hfp_aptx_voice_enabled()); @@ -225,8 +212,7 @@ TEST_F_WITH_FLAGS(BtaAgCmdTest, check_flag_disabling_guarding_with_prop, } TEST_F_WITH_FLAGS(BtaAgCmdTest, check_flag_guarding_with_prop, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, - hfp_codec_aptx_voice))) { + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, hfp_codec_aptx_voice))) { ASSERT_TRUE(com::android::bluetooth::flags::hfp_codec_aptx_voice()); ASSERT_TRUE(enable_aptx_voice_property(false)); ASSERT_FALSE(is_hfp_aptx_voice_enabled()); @@ -236,35 +222,30 @@ TEST_F_WITH_FLAGS(BtaAgCmdTest, check_flag_guarding_with_prop, } TEST_F_WITH_FLAGS(BtaAgCmdTest, at_hfp_cback__qac_ev_codec_disabled, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, - hfp_codec_aptx_voice))) { + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, hfp_codec_aptx_voice))) { tBTA_AG_SCB p_scb = { - .peer_addr = addr, - .app_id = 0, + .peer_addr = addr, + .app_id = 0, }; ASSERT_TRUE(enable_aptx_voice_property(false)); bta_ag_at_hfp_cback(&p_scb, BTA_AG_AT_QAC_EVT, 0, (char*)&test_strings[0][0], - (char*)&test_strings[0][12], - BTA_AG_SCO_APTX_SWB_SETTINGS_Q0); + (char*)&test_strings[0][12], BTA_AG_SCO_APTX_SWB_SETTINGS_Q0); ASSERT_FALSE(p_scb.codec_updated); ASSERT_FALSE(p_scb.is_aptx_swb_codec); ASSERT_EQ(1, get_func_call_count("PORT_WriteData")); } TEST_F_WITH_FLAGS(BtaAgCmdTest, at_hfp_cback__qac_ev_codec_enabled, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, - hfp_codec_aptx_voice))) { - tBTA_AG_SCB p_scb = {.peer_addr = addr, - .app_id = 0, - .peer_codecs = BTA_AG_SCO_APTX_SWB_SETTINGS_Q0_MASK}; + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, hfp_codec_aptx_voice))) { + tBTA_AG_SCB p_scb = { + .peer_addr = addr, .app_id = 0, .peer_codecs = BTA_AG_SCO_APTX_SWB_SETTINGS_Q0_MASK}; ASSERT_TRUE(enable_aptx_voice_property(true)); ASSERT_EQ(BT_STATUS_SUCCESS, enable_aptx_swb_codec(true, &addr)); bta_ag_at_hfp_cback(&p_scb, BTA_AG_AT_QAC_EVT, 0, (char*)&test_strings[0][0], - (char*)&test_strings[0][12], - BTA_AG_SCO_APTX_SWB_SETTINGS_Q0); + (char*)&test_strings[0][12], BTA_AG_SCO_APTX_SWB_SETTINGS_Q0); ASSERT_TRUE(p_scb.codec_updated); ASSERT_TRUE(p_scb.is_aptx_swb_codec); ASSERT_EQ(2, get_func_call_count("PORT_WriteData")); @@ -273,29 +254,25 @@ TEST_F_WITH_FLAGS(BtaAgCmdTest, at_hfp_cback__qac_ev_codec_enabled, } TEST_F_WITH_FLAGS(BtaAgCmdTest, at_hfp_cback__qcs_ev_codec_disabled, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, - hfp_codec_aptx_voice))) { + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, hfp_codec_aptx_voice))) { tBTA_AG_SCB p_scb = { - .peer_addr = addr, - .app_id = 0, + .peer_addr = addr, + .app_id = 0, }; ASSERT_TRUE(enable_aptx_voice_property(false)); bta_ag_at_hfp_cback(&p_scb, BTA_AG_AT_QCS_EVT, 0, (char*)&test_strings[0][0], - (char*)&test_strings[0][12], - BTA_AG_SCO_APTX_SWB_SETTINGS_Q0); + (char*)&test_strings[0][12], BTA_AG_SCO_APTX_SWB_SETTINGS_Q0); ASSERT_FALSE(p_scb.codec_updated); ASSERT_FALSE(p_scb.is_aptx_swb_codec); ASSERT_EQ(1, get_func_call_count("PORT_WriteData")); } TEST_F_WITH_FLAGS(BtaAgCmdTest, at_hfp_cback__qcs_ev_codec_q0_enabled, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, - hfp_codec_aptx_voice))) { + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, hfp_codec_aptx_voice))) { reset_mock_btm_client_interface(); - mock_btm_client_interface.sco.BTM_SetEScoMode = - [](enh_esco_params_t* p_parms) -> tBTM_STATUS { + mock_btm_client_interface.sco.BTM_SetEScoMode = [](enh_esco_params_t* p_parms) -> tBTM_STATUS { inc_func_call_count("BTM_SetEScoMode"); return BTM_SUCCESS; }; @@ -314,8 +291,7 @@ TEST_F_WITH_FLAGS(BtaAgCmdTest, at_hfp_cback__qcs_ev_codec_q0_enabled, ASSERT_EQ(BT_STATUS_SUCCESS, enable_aptx_swb_codec(true, &addr)); bta_ag_at_hfp_cback(&p_scb, BTA_AG_AT_QCS_EVT, 0, (char*)&test_strings[0][0], - (char*)&test_strings[0][12], - BTA_AG_SCO_APTX_SWB_SETTINGS_Q0); + (char*)&test_strings[0][12], BTA_AG_SCO_APTX_SWB_SETTINGS_Q0); ASSERT_EQ(1, get_func_call_count("alarm_cancel")); ASSERT_EQ(1, get_func_call_count("esco_parameters_for_codec")); @@ -326,13 +302,10 @@ TEST_F_WITH_FLAGS(BtaAgCmdTest, at_hfp_cback__qcs_ev_codec_q0_enabled, ASSERT_TRUE(enable_aptx_voice_property(false)); } -TEST_F_WITH_FLAGS(BtaAgCmdTest, - handle_swb_at_event__qcs_ev_codec_q1_fallback_to_q0, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, - hfp_codec_aptx_voice))) { +TEST_F_WITH_FLAGS(BtaAgCmdTest, handle_swb_at_event__qcs_ev_codec_q1_fallback_to_q0, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, hfp_codec_aptx_voice))) { reset_mock_btm_client_interface(); - mock_btm_client_interface.sco.BTM_SetEScoMode = - [](enh_esco_params_t* p_parms) -> tBTM_STATUS { + mock_btm_client_interface.sco.BTM_SetEScoMode = [](enh_esco_params_t* p_parms) -> tBTM_STATUS { inc_func_call_count("BTM_SetEScoMode"); return BTM_SUCCESS; }; @@ -352,8 +325,7 @@ TEST_F_WITH_FLAGS(BtaAgCmdTest, ASSERT_EQ(BT_STATUS_SUCCESS, enable_aptx_swb_codec(true, &addr)); bta_ag_at_hfp_cback(&p_scb, BTA_AG_AT_QCS_EVT, 0, (char*)&test_strings[0][0], - (char*)&test_strings[0][12], - BTA_AG_SCO_APTX_SWB_SETTINGS_Q1); + (char*)&test_strings[0][12], BTA_AG_SCO_APTX_SWB_SETTINGS_Q1); ASSERT_EQ(1, get_func_call_count("alarm_cancel")); ASSERT_EQ(1, get_func_call_count("esco_parameters_for_codec")); @@ -365,11 +337,12 @@ TEST_F_WITH_FLAGS(BtaAgCmdTest, } class BtaAgScoTest : public BtaAgTest { - protected: +protected: void SetUp() override { BtaAgTest::SetUp(); - test::mock::stack_acl::BTM_ReadRemoteFeatures.body = - [this](const RawAddress& addr) { return this->data; }; + test::mock::stack_acl::BTM_ReadRemoteFeatures.body = [this](const RawAddress& addr) { + return this->data; + }; } void TearDown() override { BtaAgTest::TearDown(); } @@ -377,13 +350,11 @@ class BtaAgScoTest : public BtaAgTest { }; TEST_F_WITH_FLAGS(BtaAgScoTest, codec_negotiate__aptx_state_on, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, - hfp_codec_aptx_voice))) { + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, hfp_codec_aptx_voice))) { tBTA_AG_SCB* p_scb = &bta_ag_cb.scb[0]; p_scb->app_id = 0; p_scb->peer_addr = addr; - p_scb->codec_negotiation_timer = - alarm_new("bta_ag.scb_codec_negotiation_timer"); + p_scb->codec_negotiation_timer = alarm_new("bta_ag.scb_codec_negotiation_timer"); p_scb->peer_codecs = BTA_AG_SCO_APTX_SWB_SETTINGS_Q0_MASK; p_scb->is_aptx_swb_codec = false; @@ -399,13 +370,11 @@ TEST_F_WITH_FLAGS(BtaAgScoTest, codec_negotiate__aptx_state_on, } TEST_F_WITH_FLAGS(BtaAgScoTest, codec_negotiate__aptx_state_off, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, - hfp_codec_aptx_voice))) { + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, hfp_codec_aptx_voice))) { tBTA_AG_SCB* p_scb = &bta_ag_cb.scb[0]; p_scb->app_id = 0; p_scb->peer_addr = addr; - p_scb->codec_negotiation_timer = - alarm_new("bta_ag.scb_codec_negotiation_timer"); + p_scb->codec_negotiation_timer = alarm_new("bta_ag.scb_codec_negotiation_timer"); p_scb->peer_codecs = BTA_AG_SCO_APTX_SWB_SETTINGS_Q0_MASK; p_scb->is_aptx_swb_codec = true; @@ -421,14 +390,12 @@ TEST_F_WITH_FLAGS(BtaAgScoTest, codec_negotiate__aptx_state_off, } TEST_F_WITH_FLAGS(BtaAgScoTest, codec_negotiate__aptx_disabled, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, - hfp_codec_aptx_voice))) { + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, hfp_codec_aptx_voice))) { // const char* test_flag[] = {"INIT_aptx_voice=false", nullptr}; tBTA_AG_SCB* p_scb = &bta_ag_cb.scb[0]; p_scb->app_id = 0; p_scb->peer_addr = addr; - p_scb->codec_negotiation_timer = - alarm_new("bta_ag.scb_codec_negotiation_timer"); + p_scb->codec_negotiation_timer = alarm_new("bta_ag.scb_codec_negotiation_timer"); p_scb->peer_codecs = BTA_AG_SCO_APTX_SWB_SETTINGS_Q0_MASK; p_scb->is_aptx_swb_codec = true; p_scb->codec_updated = true; diff --git a/system/bta/test/bta_api_test.cc b/system/bta/test/bta_api_test.cc index 65c91d12c70..658dffe4120 100644 --- a/system/bta/test/bta_api_test.cc +++ b/system/bta/test/bta_api_test.cc @@ -30,27 +30,25 @@ using namespace std::chrono_literals; class BtaApiTest : public testing::Test { - protected: +protected: void SetUp() override { reset_mock_function_count_map(); } void TearDown() override {} }; TEST_F(BtaApiTest, bta_status_text) { std::vector> statuses = { - std::make_pair(BTA_SUCCESS, "BTA_SUCCESS"), - std::make_pair(BTA_FAILURE, "BTA_FAILURE"), - std::make_pair(BTA_PENDING, "BTA_PENDING"), - std::make_pair(BTA_BUSY, "BTA_BUSY"), - std::make_pair(BTA_NO_RESOURCES, "BTA_NO_RESOURCES"), - std::make_pair(BTA_WRONG_MODE, "BTA_WRONG_MODE"), + std::make_pair(BTA_SUCCESS, "BTA_SUCCESS"), + std::make_pair(BTA_FAILURE, "BTA_FAILURE"), + std::make_pair(BTA_PENDING, "BTA_PENDING"), + std::make_pair(BTA_BUSY, "BTA_BUSY"), + std::make_pair(BTA_NO_RESOURCES, "BTA_NO_RESOURCES"), + std::make_pair(BTA_WRONG_MODE, "BTA_WRONG_MODE"), }; for (const auto& status : statuses) { ASSERT_STREQ(status.second.c_str(), bta_status_text(status.first).c_str()); } - auto unknown = - base::StringPrintf("UNKNOWN[%d]", std::numeric_limits::max()); - ASSERT_STREQ(unknown.c_str(), - bta_status_text(static_cast( - std::numeric_limits::max())) - .c_str()); + auto unknown = base::StringPrintf("UNKNOWN[%d]", std::numeric_limits::max()); + ASSERT_STREQ( + unknown.c_str(), + bta_status_text(static_cast(std::numeric_limits::max())).c_str()); } diff --git a/system/bta/test/bta_av_test.cc b/system/bta/test/bta_av_test.cc index 7bbf6c5881b..2612c3d059d 100644 --- a/system/bta/test/bta_av_test.cc +++ b/system/bta/test/bta_av_test.cc @@ -34,18 +34,17 @@ const RawAddress kRawAddress({0x11, 0x22, 0x33, 0x44, 0x55, 0x66}); } // namespace struct alarm_t { - alarm_t(const char* name){}; + alarm_t(const char* name) {} int any_value; }; class BtaAvTest : public testing::Test { - protected: +protected: void SetUp() override { reset_mock_function_count_map(); bluetooth::common::InitFlags::SetAllForTesting(); } - void TearDown() override { - } + void TearDown() override {} }; TEST_F(BtaAvTest, nop) { @@ -55,20 +54,20 @@ TEST_F(BtaAvTest, nop) { TEST_F(BtaAvTest, bta_av_rc_opened) { tBTA_AV_CB cb = { - .p_cback = - [](tBTA_AV_EVT event, tBTA_AV* p_data) { - const tBTA_AV_RC_OPEN* rc_open = &p_data->rc_open; - ASSERT_EQ(BTA_AV_RC_OPEN_EVT, event); - ASSERT_EQ(kRawAddress, rc_open->peer_addr); - }, + .p_cback = + [](tBTA_AV_EVT event, tBTA_AV* p_data) { + const tBTA_AV_RC_OPEN* rc_open = &p_data->rc_open; + ASSERT_EQ(BTA_AV_RC_OPEN_EVT, event); + ASSERT_EQ(kRawAddress, rc_open->peer_addr); + }, }; tBTA_AV_DATA data = { - .rc_conn_chg = - { - .hdr = {}, - .peer_addr = kRawAddress, - .handle = 0, - }, + .rc_conn_chg = + { + .hdr = {}, + .peer_addr = kRawAddress, + .handle = 0, + }, }; bta_av_rc_opened(&cb, &data); } diff --git a/system/bta/test/bta_dip_test.cc b/system/bta/test/bta_dip_test.cc index 1a454fb810f..5cd1d9f0d39 100644 --- a/system/bta/test/bta_dip_test.cc +++ b/system/bta/test/bta_dip_test.cc @@ -42,50 +42,47 @@ static tSDP_DISC_ATTR g_attr_vendor_product_version; static tSDP_DISC_ATTR g_attr_vendor_product_primary_record; static tSDP_DISC_REC g_rec; -static void sdp_dm_cback(tBTA_SDP_EVT event, tBTA_SDP* p_data, - void* user_data) { - return; -} +static void sdp_dm_cback(tBTA_SDP_EVT event, tBTA_SDP* p_data, void* user_data) { return; } class BtaDipTest : public ::testing::Test { - protected: +protected: void SetUp() override { g_attr_service_class_id_list.p_next_attr = &g_attr_spec_id; g_attr_service_class_id_list.attr_id = ATTR_ID_SERVICE_CLASS_ID_LIST; - g_attr_service_class_id_list.attr_len_type = (DATA_ELE_SEQ_DESC_TYPE<<12)|2; + g_attr_service_class_id_list.attr_len_type = (DATA_ELE_SEQ_DESC_TYPE << 12) | 2; g_attr_service_class_id_list.attr_value.v.p_sub_attr = &g_sub_attr; - g_sub_attr.attr_len_type = (UUID_DESC_TYPE<<12)|2; + g_sub_attr.attr_len_type = (UUID_DESC_TYPE << 12) | 2; g_sub_attr.attr_value.v.u16 = 0x1200; g_attr_spec_id.p_next_attr = &g_attr_vendor_id; g_attr_spec_id.attr_id = ATTR_ID_SPECIFICATION_ID; - g_attr_spec_id.attr_len_type = (UINT_DESC_TYPE<<12)|2; + g_attr_spec_id.attr_len_type = (UINT_DESC_TYPE << 12) | 2; g_attr_spec_id.attr_value.v.u16 = 0x0103; g_attr_vendor_id.p_next_attr = &g_attr_vendor_id_src; g_attr_vendor_id.attr_id = ATTR_ID_VENDOR_ID; - g_attr_vendor_id.attr_len_type = (UINT_DESC_TYPE<<12)|2; + g_attr_vendor_id.attr_len_type = (UINT_DESC_TYPE << 12) | 2; g_attr_vendor_id.attr_value.v.u16 = 0x18d1; // Allocation should succeed g_attr_vendor_id_src.p_next_attr = &g_attr_vendor_product_id; g_attr_vendor_id_src.attr_id = ATTR_ID_VENDOR_ID_SOURCE; - g_attr_vendor_id_src.attr_len_type = (UINT_DESC_TYPE<<12)|2; + g_attr_vendor_id_src.attr_len_type = (UINT_DESC_TYPE << 12) | 2; g_attr_vendor_id_src.attr_value.v.u16 = 1; g_attr_vendor_product_id.p_next_attr = &g_attr_vendor_product_version; g_attr_vendor_product_id.attr_id = ATTR_ID_PRODUCT_ID; - g_attr_vendor_product_id.attr_len_type = (UINT_DESC_TYPE<<12)|2; + g_attr_vendor_product_id.attr_len_type = (UINT_DESC_TYPE << 12) | 2; g_attr_vendor_product_id.attr_value.v.u16 = 0x1234; g_attr_vendor_product_version.p_next_attr = &g_attr_vendor_product_primary_record; g_attr_vendor_product_version.attr_id = ATTR_ID_PRODUCT_VERSION; - g_attr_vendor_product_version.attr_len_type = (UINT_DESC_TYPE<<12)|2; + g_attr_vendor_product_version.attr_len_type = (UINT_DESC_TYPE << 12) | 2; g_attr_vendor_product_version.attr_value.v.u16 = 0x0100; g_attr_vendor_product_primary_record.p_next_attr = &g_attr_vendor_product_primary_record; g_attr_vendor_product_primary_record.attr_id = ATTR_ID_PRIMARY_RECORD; - g_attr_vendor_product_primary_record.attr_len_type = (BOOLEAN_DESC_TYPE<<12)|1; + g_attr_vendor_product_primary_record.attr_len_type = (BOOLEAN_DESC_TYPE << 12) | 1; g_attr_vendor_product_primary_record.attr_value.v.u8 = 1; g_rec.p_first_attr = &g_attr_service_class_id_list; @@ -105,10 +102,8 @@ class BtaDipTest : public ::testing::Test { namespace bluetooth { namespace testing { -void bta_create_dip_sdp_record(bluetooth_sdp_record* record, - tSDP_DISC_REC* p_rec); -void bta_sdp_search_cback(Uuid uuid, const RawAddress& bd_addr, - tSDP_RESULT result); +void bta_create_dip_sdp_record(bluetooth_sdp_record* record, tSDP_DISC_REC* p_rec); +void bta_sdp_search_cback(Uuid uuid, const RawAddress& bd_addr, tSDP_RESULT result); } // namespace testing } // namespace bluetooth @@ -133,22 +128,22 @@ TEST_F(BtaDipTest, test_invalid_type_checks) { // here we provide the wrong types of records // and verify that the provided values are not accepted - g_attr_spec_id.attr_len_type = (BOOLEAN_DESC_TYPE<<12)|1; + g_attr_spec_id.attr_len_type = (BOOLEAN_DESC_TYPE << 12) | 1; g_attr_spec_id.attr_value.v.u16 = 0x0103; - g_attr_vendor_id.attr_len_type = (BOOLEAN_DESC_TYPE<<12)|2; + g_attr_vendor_id.attr_len_type = (BOOLEAN_DESC_TYPE << 12) | 2; g_attr_vendor_id.attr_value.v.u16 = 0x18d1; - g_attr_vendor_id_src.attr_len_type = (BOOLEAN_DESC_TYPE<<12)|2; + g_attr_vendor_id_src.attr_len_type = (BOOLEAN_DESC_TYPE << 12) | 2; g_attr_vendor_id_src.attr_value.v.u16 = 1; - g_attr_vendor_product_id.attr_len_type = (BOOLEAN_DESC_TYPE<<12)|2; + g_attr_vendor_product_id.attr_len_type = (BOOLEAN_DESC_TYPE << 12) | 2; g_attr_vendor_product_id.attr_value.v.u16 = 0x1234; - g_attr_vendor_product_version.attr_len_type = (BOOLEAN_DESC_TYPE<<12)|2; + g_attr_vendor_product_version.attr_len_type = (BOOLEAN_DESC_TYPE << 12) | 2; g_attr_vendor_product_version.attr_value.v.u16 = 0x0100; - g_attr_vendor_product_primary_record.attr_len_type = (UINT_DESC_TYPE<<12)|1; + g_attr_vendor_product_primary_record.attr_len_type = (UINT_DESC_TYPE << 12) | 1; g_attr_vendor_product_primary_record.attr_value.v.u8 = 1; bluetooth::testing::bta_create_dip_sdp_record(&record, &g_rec); @@ -167,23 +162,23 @@ TEST_F(BtaDipTest, test_invalid_size_checks) { // here we provide the wrong sizes of records // and verify that the provided values are not accepted - g_attr_spec_id.attr_len_type = (UINT_DESC_TYPE<<12)|1; + g_attr_spec_id.attr_len_type = (UINT_DESC_TYPE << 12) | 1; g_attr_spec_id.attr_value.v.u16 = 0x0103; - g_attr_vendor_id.attr_len_type = (UINT_DESC_TYPE<<12)|1; + g_attr_vendor_id.attr_len_type = (UINT_DESC_TYPE << 12) | 1; g_attr_vendor_id.attr_value.v.u16 = 0x18d1; - g_attr_vendor_id_src.attr_len_type = (UINT_DESC_TYPE<<12)|1; + g_attr_vendor_id_src.attr_len_type = (UINT_DESC_TYPE << 12) | 1; g_attr_vendor_id_src.attr_value.v.u16 = 1; - g_attr_vendor_product_id.attr_len_type = (UINT_DESC_TYPE<<12)|1; + g_attr_vendor_product_id.attr_len_type = (UINT_DESC_TYPE << 12) | 1; g_attr_vendor_product_id.attr_value.v.u16 = 0x1234; - g_attr_vendor_product_version.attr_len_type = (UINT_DESC_TYPE<<12)|1; + g_attr_vendor_product_version.attr_len_type = (UINT_DESC_TYPE << 12) | 1; g_attr_vendor_product_version.attr_value.v.u16 = 0x0100; // size greater than 1 is accepted - g_attr_vendor_product_primary_record.attr_len_type = (BOOLEAN_DESC_TYPE<<12)|2; + g_attr_vendor_product_primary_record.attr_len_type = (BOOLEAN_DESC_TYPE << 12) | 2; g_attr_vendor_product_primary_record.attr_value.v.u8 = 1; bluetooth::testing::bta_create_dip_sdp_record(&record, &g_rec); @@ -196,8 +191,7 @@ TEST_F(BtaDipTest, test_invalid_size_checks) { ASSERT_EQ(record.dip.primary_record, true); // a size zero for boolean won't be accepted - g_attr_vendor_product_primary_record.attr_len_type = - (BOOLEAN_DESC_TYPE << 12) | 0; + g_attr_vendor_product_primary_record.attr_len_type = (BOOLEAN_DESC_TYPE << 12) | 0; record = {}; @@ -206,8 +200,6 @@ TEST_F(BtaDipTest, test_invalid_size_checks) { ASSERT_EQ(record.dip.primary_record, false); } - TEST_F(BtaDipTest, test_bta_sdp_search_cback) { - bluetooth::testing::bta_sdp_search_cback(UUID_DIP, RawAddress::kEmpty, - SDP_SUCCESS); + bluetooth::testing::bta_sdp_search_cback(UUID_DIP, RawAddress::kEmpty, SDP_SUCCESS); } diff --git a/system/bta/test/bta_disc_test.cc b/system/bta/test/bta_disc_test.cc index f1de64a2a4f..4c1a4c5ff62 100644 --- a/system/bta/test/bta_disc_test.cc +++ b/system/bta/test/bta_disc_test.cc @@ -50,18 +50,15 @@ namespace legacy { namespace testing { void bta_dm_disc_init_search_cb(tBTA_DM_SEARCH_CB& bta_dm_search_cb); -bool bta_dm_read_remote_device_name(const RawAddress& bd_addr, - tBT_TRANSPORT transport); +bool bta_dm_read_remote_device_name(const RawAddress& bd_addr, tBT_TRANSPORT transport); tBTA_DM_SEARCH_CB& bta_dm_disc_search_cb(); void bta_dm_discover_next_device(); void bta_dm_sdp_find_services(tBTA_DM_SDP_STATE* state); void bta_dm_inq_cmpl(); void bta_dm_inq_cmpl_cb(void* p_result); void bta_dm_observe_cmpl_cb(void* p_result); -void bta_dm_observe_results_cb(tBTM_INQ_RESULTS* p_inq, const uint8_t* p_eir, - uint16_t eir_len); -void bta_dm_opportunistic_observe_results_cb(tBTM_INQ_RESULTS* p_inq, - const uint8_t* p_eir, +void bta_dm_observe_results_cb(tBTM_INQ_RESULTS* p_inq, const uint8_t* p_eir, uint16_t eir_len); +void bta_dm_opportunistic_observe_results_cb(tBTM_INQ_RESULTS* p_inq, const uint8_t* p_eir, uint16_t eir_len); void bta_dm_queue_search(tBTA_DM_API_SEARCH& search); void bta_dm_start_scan(uint8_t duration_sec, bool low_latency_scan = false); @@ -70,7 +67,7 @@ void bta_dm_start_scan(uint8_t duration_sec, bool low_latency_scan = false); } // namespace bluetooth class BtaInitializedTest : public BtaWithContextTest { - protected: +protected: void SetUp() override { BtaWithContextTest::SetUp(); BTA_dm_init(); @@ -88,11 +85,11 @@ TEST_F(BtaInitializedTest, DumpsysBtaDmDisc) { TEST_F(BtaInitializedTest, bta_dm_ble_csis_observe) { bta_dm_ble_csis_observe(true, [](tBTA_DM_SEARCH_EVT, tBTA_DM_SEARCH*) {}); -}; +} TEST_F(BtaInitializedTest, bta_dm_ble_csis_observe__false) { bta_dm_ble_csis_observe(false, [](tBTA_DM_SEARCH_EVT, tBTA_DM_SEARCH*) {}); -}; +} TEST_F(BtaInitializedTest, bta_dm_ble_scan) { // bool start, uint8_t duration_sec, bool low_latency_scan @@ -109,32 +106,25 @@ TEST_F(BtaInitializedTest, bta_dm_ble_scan) { bta_dm_ble_scan(kStopLeScan, duration_in_seconds, kHighLatencyScan); } -TEST_F(BtaInitializedTest, bta_dm_disc_discover_next_device) { - bta_dm_disc_discover_next_device(); -} +TEST_F(BtaInitializedTest, bta_dm_disc_discover_next_device) { bta_dm_disc_discover_next_device(); } -TEST_F(BtaInitializedTest, bta_dm_disc_remove_device) { - bta_dm_disc_remove_device(kRawAddress); -} +TEST_F(BtaInitializedTest, bta_dm_disc_remove_device) { bta_dm_disc_remove_device(kRawAddress); } TEST_F(BtaInitializedTest, bta_dm_discover_next_device) { bluetooth::legacy::testing::bta_dm_discover_next_device(); } TEST_F(BtaInitializedTest, bta_dm_sdp_find_services) { - std::unique_ptr state = - std::make_unique(tBTA_DM_SDP_STATE{ + std::unique_ptr state = std::make_unique(tBTA_DM_SDP_STATE{ .bd_addr = kRawAddress, .services_to_search = BTA_ALL_SERVICE_MASK, .services_found = 0, .service_index = 0, - }); + }); bluetooth::legacy::testing::bta_dm_sdp_find_services(state.get()); } -TEST_F(BtaInitializedTest, bta_dm_inq_cmpl) { - bluetooth::legacy::testing::bta_dm_inq_cmpl(); -} +TEST_F(BtaInitializedTest, bta_dm_inq_cmpl) { bluetooth::legacy::testing::bta_dm_inq_cmpl(); } TEST_F(BtaInitializedTest, bta_dm_inq_cmpl_cb) { tBTM_INQUIRY_CMPL complete; @@ -149,16 +139,14 @@ TEST_F(BtaInitializedTest, bta_dm_observe_results_cb) { tBTM_INQ_RESULTS result; const uint8_t p_eir[] = {0x0, 0x1, 0x2, 0x3}; uint16_t eir_len = sizeof(p_eir); - bluetooth::legacy::testing::bta_dm_observe_results_cb(&result, p_eir, - eir_len); + bluetooth::legacy::testing::bta_dm_observe_results_cb(&result, p_eir, eir_len); } TEST_F(BtaInitializedTest, bta_dm_opportunistic_observe_results_cb) { tBTM_INQ_RESULTS result; const uint8_t p_eir[] = {0x0, 0x1, 0x2, 0x3}; uint16_t eir_len = sizeof(p_eir); - bluetooth::legacy::testing::bta_dm_opportunistic_observe_results_cb( - &result, p_eir, eir_len); + bluetooth::legacy::testing::bta_dm_opportunistic_observe_results_cb(&result, p_eir, eir_len); } TEST_F(BtaInitializedTest, bta_dm_queue_search) { @@ -170,8 +158,7 @@ TEST_F(BtaInitializedTest, bta_dm_queue_search) { } TEST_F(BtaInitializedTest, bta_dm_read_remote_device_name) { - bluetooth::legacy::testing::bta_dm_read_remote_device_name( - kRawAddress, BT_TRANSPORT_BR_EDR); + bluetooth::legacy::testing::bta_dm_read_remote_device_name(kRawAddress, BT_TRANSPORT_BR_EDR); } TEST_F(BtaInitializedTest, bta_dm_start_scan) { @@ -183,46 +170,41 @@ TEST_F(BtaInitializedTest, bta_dm_start_scan) { } TEST_F(BtaInitializedTest, bta_dm_disc_start_device_discovery) { - bta_dm_disc_start_device_discovery( - [](tBTA_DM_SEARCH_EVT event, tBTA_DM_SEARCH* p_data) {}); + bta_dm_disc_start_device_discovery([](tBTA_DM_SEARCH_EVT event, tBTA_DM_SEARCH* p_data) {}); } TEST_F(BtaInitializedTest, bta_dm_disc_stop_device_discovery) { bta_dm_disc_stop_device_discovery(); } -TEST_F(BtaInitializedTest, - bta_dm_disc_start_service_discovery__BT_TRANSPORT_AUTO) { +TEST_F(BtaInitializedTest, bta_dm_disc_start_service_discovery__BT_TRANSPORT_AUTO) { bta_dm_disc_start_service_discovery( - {nullptr, nullptr, nullptr, - [](RawAddress, const std::vector&, tBTA_STATUS) {}}, - kRawAddress, BT_TRANSPORT_AUTO); + {nullptr, nullptr, nullptr, + [](RawAddress, const std::vector&, tBTA_STATUS) {}}, + kRawAddress, BT_TRANSPORT_AUTO); } // must be global, as capturing lambda can't be treated as function int service_cb_call_cnt = 0; -TEST_F_WITH_FLAGS(BtaInitializedTest, - bta_dm_disc_start_service_discovery__BT_TRANSPORT_BR_EDR, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG( - TEST_BT, separate_service_and_device_discovery))) { +TEST_F_WITH_FLAGS(BtaInitializedTest, bta_dm_disc_start_service_discovery__BT_TRANSPORT_BR_EDR, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, + separate_service_and_device_discovery))) { bta_dm_disc_start(true); int sdp_call_cnt = 0; base::RepeatingCallback sdp_performer = - base::BindLambdaForTesting([&](tBTA_DM_SDP_STATE* sdp_state) { - sdp_call_cnt++; - bta_dm_sdp_finished(sdp_state->bd_addr, BTA_SUCCESS, {}, {}); - }); + base::BindLambdaForTesting([&](tBTA_DM_SDP_STATE* sdp_state) { + sdp_call_cnt++; + bta_dm_sdp_finished(sdp_state->bd_addr, BTA_SUCCESS, {}, {}); + }); bta_dm_disc_override_sdp_performer_for_testing(sdp_performer); service_cb_call_cnt = 0; - bta_dm_disc_start_service_discovery( - {nullptr, nullptr, nullptr, - [](RawAddress addr, const std::vector&, tBTA_STATUS) { - service_cb_call_cnt++; - }}, - kRawAddress, BT_TRANSPORT_BR_EDR); + bta_dm_disc_start_service_discovery({nullptr, nullptr, nullptr, + [](RawAddress addr, const std::vector&, + tBTA_STATUS) { service_cb_call_cnt++; }}, + kRawAddress, BT_TRANSPORT_BR_EDR); EXPECT_EQ(sdp_call_cnt, 1); EXPECT_EQ(service_cb_call_cnt, 1); @@ -233,26 +215,23 @@ TEST_F_WITH_FLAGS(BtaInitializedTest, // must be global, as capturing lambda can't be treated as function int gatt_service_cb_call_cnt = 0; -TEST_F_WITH_FLAGS(BtaInitializedTest, - bta_dm_disc_start_service_discovery__BT_TRANSPORT_LE, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG( - TEST_BT, separate_service_and_device_discovery))) { +TEST_F_WITH_FLAGS(BtaInitializedTest, bta_dm_disc_start_service_discovery__BT_TRANSPORT_LE, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, + separate_service_and_device_discovery))) { bta_dm_disc_start(true); int gatt_call_cnt = 0; base::RepeatingCallback gatt_performer = - base::BindLambdaForTesting([&](const RawAddress& bd_addr) { - gatt_call_cnt++; - bta_dm_gatt_finished(bd_addr, BTA_SUCCESS); - }); + base::BindLambdaForTesting([&](const RawAddress& bd_addr) { + gatt_call_cnt++; + bta_dm_gatt_finished(bd_addr, BTA_SUCCESS); + }); bta_dm_disc_override_gatt_performer_for_testing(gatt_performer); gatt_service_cb_call_cnt = 0; - bta_dm_disc_start_service_discovery( - {[](RawAddress, BD_NAME, std::vector&, bool) { - gatt_service_cb_call_cnt++; - }, - nullptr, nullptr, nullptr}, - kRawAddress, BT_TRANSPORT_LE); + bta_dm_disc_start_service_discovery({[](RawAddress, BD_NAME, std::vector&, + bool) { gatt_service_cb_call_cnt++; }, + nullptr, nullptr, nullptr}, + kRawAddress, BT_TRANSPORT_LE); EXPECT_EQ(gatt_call_cnt, 1); EXPECT_EQ(gatt_service_cb_call_cnt, 1); @@ -267,48 +246,44 @@ int gatt_service_cb_both_call_cnt = 0; /* This test exercises the usual service discovery flow when bonding to * dual-mode, CTKD capable device on LE transport. */ -TEST_F_WITH_FLAGS( - BtaInitializedTest, bta_dm_disc_both_transports_flag_disabled, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, - separate_service_and_device_discovery)), - REQUIRES_FLAGS_DISABLED(ACONFIG_FLAG(TEST_BT, bta_dm_discover_both))) { +TEST_F_WITH_FLAGS(BtaInitializedTest, bta_dm_disc_both_transports_flag_disabled, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, + separate_service_and_device_discovery)), + REQUIRES_FLAGS_DISABLED(ACONFIG_FLAG(TEST_BT, bta_dm_discover_both))) { bta_dm_disc_start(true); std::promise gatt_triggered; int gatt_call_cnt = 0; base::RepeatingCallback gatt_performer = - base::BindLambdaForTesting([&](const RawAddress& bd_addr) { - gatt_call_cnt++; - gatt_triggered.set_value(); - }); + base::BindLambdaForTesting([&](const RawAddress& bd_addr) { + gatt_call_cnt++; + gatt_triggered.set_value(); + }); bta_dm_disc_override_gatt_performer_for_testing(gatt_performer); int sdp_call_cnt = 0; base::RepeatingCallback sdp_performer = - base::BindLambdaForTesting( - [&](tBTA_DM_SDP_STATE* sdp_state) { sdp_call_cnt++; }); + base::BindLambdaForTesting([&](tBTA_DM_SDP_STATE* sdp_state) { sdp_call_cnt++; }); bta_dm_disc_override_sdp_performer_for_testing(sdp_performer); gatt_service_cb_both_call_cnt = 0; service_cb_both_call_cnt = 0; bta_dm_disc_start_service_discovery( - {[](RawAddress, BD_NAME, std::vector&, bool) {}, nullptr, - nullptr, - [](RawAddress addr, const std::vector&, tBTA_STATUS) { - service_cb_both_call_cnt++; - }}, - kRawAddress, BT_TRANSPORT_BR_EDR); + {[](RawAddress, BD_NAME, std::vector&, bool) {}, nullptr, nullptr, + [](RawAddress addr, const std::vector&, tBTA_STATUS) { + service_cb_both_call_cnt++; + }}, + kRawAddress, BT_TRANSPORT_BR_EDR); EXPECT_EQ(sdp_call_cnt, 1); bta_dm_disc_start_service_discovery( - {[](RawAddress, BD_NAME, std::vector&, bool) { - gatt_service_cb_both_call_cnt++; - }, - nullptr, nullptr, - [](RawAddress addr, const std::vector&, tBTA_STATUS) { - }}, - kRawAddress, BT_TRANSPORT_LE); + {[](RawAddress, BD_NAME, std::vector&, bool) { + gatt_service_cb_both_call_cnt++; + }, + nullptr, nullptr, + [](RawAddress addr, const std::vector&, tBTA_STATUS) {}}, + kRawAddress, BT_TRANSPORT_LE); // GATT discovery is queued, until SDP finishes EXPECT_EQ(gatt_call_cnt, 0); @@ -330,45 +305,36 @@ TEST_F_WITH_FLAGS( * dual-mode, CTKD capable device on LE transport. */ TEST_F_WITH_FLAGS(BtaInitializedTest, bta_dm_disc_both_transports_flag_enabled, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, - bta_dm_discover_both))) { + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, bta_dm_discover_both))) { bta_dm_disc_start(true); int gatt_call_cnt = 0; base::RepeatingCallback gatt_performer = - base::BindLambdaForTesting( - [&](const RawAddress& bd_addr) { gatt_call_cnt++; }); + base::BindLambdaForTesting([&](const RawAddress& bd_addr) { gatt_call_cnt++; }); bta_dm_disc_override_gatt_performer_for_testing(gatt_performer); int sdp_call_cnt = 0; base::RepeatingCallback sdp_performer = - base::BindLambdaForTesting( - [&](tBTA_DM_SDP_STATE* sdp_state) { sdp_call_cnt++; }); + base::BindLambdaForTesting([&](tBTA_DM_SDP_STATE* sdp_state) { sdp_call_cnt++; }); bta_dm_disc_override_sdp_performer_for_testing(sdp_performer); gatt_service_cb_both_call_cnt = 0; service_cb_both_call_cnt = 0; - bta_dm_disc_start_service_discovery( - {[](RawAddress, BD_NAME, std::vector&, bool) { - gatt_service_cb_both_call_cnt++; - }, - nullptr, nullptr, - [](RawAddress addr, const std::vector&, tBTA_STATUS) { - service_cb_both_call_cnt++; - }}, - kRawAddress, BT_TRANSPORT_BR_EDR); + bta_dm_disc_start_service_discovery({[](RawAddress, BD_NAME, std::vector&, + bool) { gatt_service_cb_both_call_cnt++; }, + nullptr, nullptr, + [](RawAddress addr, const std::vector&, + tBTA_STATUS) { service_cb_both_call_cnt++; }}, + kRawAddress, BT_TRANSPORT_BR_EDR); EXPECT_EQ(sdp_call_cnt, 1); - bta_dm_disc_start_service_discovery( - {[](RawAddress, BD_NAME, std::vector&, bool) { - gatt_service_cb_both_call_cnt++; - }, - nullptr, nullptr, - [](RawAddress addr, const std::vector&, tBTA_STATUS) { - service_cb_both_call_cnt++; - }}, - kRawAddress, BT_TRANSPORT_LE); + bta_dm_disc_start_service_discovery({[](RawAddress, BD_NAME, std::vector&, + bool) { gatt_service_cb_both_call_cnt++; }, + nullptr, nullptr, + [](RawAddress addr, const std::vector&, + tBTA_STATUS) { service_cb_both_call_cnt++; }}, + kRawAddress, BT_TRANSPORT_LE); // GATT discovery on same device is immediately started EXPECT_EQ(gatt_call_cnt, 1); @@ -387,8 +353,7 @@ TEST_F_WITH_FLAGS(BtaInitializedTest, bta_dm_disc_both_transports_flag_enabled, TEST_F(BtaInitializedTest, init_bta_dm_search_cb__conn_id) { // Set the global search block target field to some non-reset value - tBTA_DM_SEARCH_CB& search_cb = - bluetooth::legacy::testing::bta_dm_disc_search_cb(); + tBTA_DM_SEARCH_CB& search_cb = bluetooth::legacy::testing::bta_dm_disc_search_cb(); search_cb.name_discover_done = true; bluetooth::legacy::testing::bta_dm_disc_init_search_cb(search_cb); diff --git a/system/bta/test/bta_dm_cust_uuid_test.cc b/system/bta/test/bta_dm_cust_uuid_test.cc index 08e6b5790f6..5c548424fde 100644 --- a/system/bta/test/bta_dm_cust_uuid_test.cc +++ b/system/bta/test/bta_dm_cust_uuid_test.cc @@ -25,15 +25,15 @@ using bluetooth::Uuid; namespace { - uint32_t handle1 = 1; - uint32_t handle2 = 2; - static const Uuid uuid1 = Uuid::From128BitBE( - Uuid::UUID128Bit{{0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, - 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff}}); - static const Uuid uuid2 = Uuid::From128BitBE( - Uuid::UUID128Bit{{0x00, 0x00, 0x00, 0x00, 0x22, 0x22, 0x22, 0x22, 0x33, - 0x33, 0x55, 0x55, 0x55, 0x55, 0x55, 0x59}}); -} +uint32_t handle1 = 1; +uint32_t handle2 = 2; +static const Uuid uuid1 = + Uuid::From128BitBE(Uuid::UUID128Bit{{0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, + 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff}}); +static const Uuid uuid2 = + Uuid::From128BitBE(Uuid::UUID128Bit{{0x00, 0x00, 0x00, 0x00, 0x22, 0x22, 0x22, 0x22, 0x33, + 0x33, 0x55, 0x55, 0x55, 0x55, 0x55, 0x59}}); +} // namespace // Test we can remove/add 128 bit custom UUID from/to bta_dm_cb.bta_custom_uuid TEST_F(BtaWithMocksTest, test_add_remove_cust_uuid) { diff --git a/system/bta/test/bta_dm_test.cc b/system/bta/test/bta_dm_test.cc index de0173325b1..6a0a07893d8 100644 --- a/system/bta/test/bta_dm_test.cc +++ b/system/bta/test/bta_dm_test.cc @@ -65,7 +65,7 @@ void bta_dm_remote_name_cmpl(const tBTA_DM_REMOTE_NAME& remote_name_msg); } // namespace bluetooth::legacy::testing class BtaDmTest : public BtaWithContextTest { - protected: +protected: void SetUp() override { BtaWithContextTest::SetUp(); @@ -85,16 +85,15 @@ class BtaDmTest : public BtaWithContextTest { }; class BtaDmCustomAlarmTest : public BtaDmTest { - protected: +protected: void SetUp() override { BtaDmTest::SetUp(); - test::mock::osi_alarm::alarm_set_on_mloop.body = - [this](alarm_t* alarm, uint64_t interval_ms, alarm_callback_t cb, - void* data) { - ASSERT_TRUE(alarm != nullptr); - this->alarm_callback = cb; - this->alarm_data = data; - }; + test::mock::osi_alarm::alarm_set_on_mloop.body = [this](alarm_t* alarm, uint64_t interval_ms, + alarm_callback_t cb, void* data) { + ASSERT_TRUE(alarm != nullptr); + this->alarm_callback = cb; + this->alarm_data = data; + }; } void TearDown() override { test::mock::osi_alarm::alarm_set_on_mloop = {}; @@ -130,7 +129,7 @@ TEST_F(BtaDmCustomAlarmTest, disable_first_pass_with_acl_links) { // ACL link is open bta_dm_cb.device_list.count = 1; - bta_dm_disable(); // Waiting for all ACL connections to drain + bta_dm_disable(); // Waiting for all ACL connections to drain ASSERT_EQ(1, get_func_call_count("alarm_set_on_mloop")); ASSERT_EQ(0, get_func_call_count("BTIF_dm_disable")); @@ -178,8 +177,7 @@ struct BTA_DM_ENCRYPT_CBACK_parms { std::queue BTA_DM_ENCRYPT_CBACK_queue; -void BTA_DM_ENCRYPT_CBACK(const RawAddress& bd_addr, tBT_TRANSPORT transport, - tBTA_STATUS result) { +void BTA_DM_ENCRYPT_CBACK(const RawAddress& bd_addr, tBT_TRANSPORT transport, tBTA_STATUS result) { BTA_DM_ENCRYPT_CBACK_queue.push({bd_addr, transport, result}); } @@ -188,13 +186,11 @@ void BTA_DM_ENCRYPT_CBACK(const RawAddress& bd_addr, tBT_TRANSPORT transport, namespace bluetooth { namespace legacy { namespace testing { -tBTA_DM_PEER_DEVICE* allocate_device_for(const RawAddress& bd_addr, - tBT_TRANSPORT transport); +tBTA_DM_PEER_DEVICE* allocate_device_for(const RawAddress& bd_addr, tBT_TRANSPORT transport); void bta_dm_remname_cback(const tBTM_REMOTE_DEV_NAME* p); -tBT_TRANSPORT bta_dm_determine_discovery_transport( - const RawAddress& remote_bd_addr); +tBT_TRANSPORT bta_dm_determine_discovery_transport(const RawAddress& remote_bd_addr); tBTM_STATUS bta_dm_sp_cback(tBTM_SP_EVT event, tBTM_SP_EVT_DATA* p_data); @@ -216,7 +212,7 @@ TEST_F(BtaDmTest, bta_dm_set_encryption) { // Setup a connected device tBTA_DM_PEER_DEVICE* device = - bluetooth::legacy::testing::allocate_device_for(kRawAddress, transport); + bluetooth::legacy::testing::allocate_device_for(kRawAddress, transport); ASSERT_TRUE(device != nullptr); device->conn_state = tBTA_DM_CONN_STATE::BTA_DM_CONNECTED; device->p_encrypt_cback = nullptr; @@ -234,9 +230,8 @@ TEST_F(BtaDmTest, bta_dm_set_encryption) { // Setup a device that fails encryption mock_btm_client_interface.security.BTM_SetEncryption = - [](const RawAddress& bd_addr, tBT_TRANSPORT transport, - tBTM_SEC_CALLBACK* p_callback, void* p_ref_data, - tBTM_BLE_SEC_ACT sec_act) -> tBTM_STATUS { + [](const RawAddress& bd_addr, tBT_TRANSPORT transport, tBTM_SEC_CALLBACK* p_callback, + void* p_ref_data, tBTM_BLE_SEC_ACT sec_act) -> tBTM_STATUS { inc_func_call_count("BTM_SetEncryption"); return BTM_MODE_UNSUPPORTED; }; @@ -248,9 +243,8 @@ TEST_F(BtaDmTest, bta_dm_set_encryption) { // Setup a device that successfully starts encryption mock_btm_client_interface.security.BTM_SetEncryption = - [](const RawAddress& bd_addr, tBT_TRANSPORT transport, - tBTM_SEC_CALLBACK* p_callback, void* p_ref_data, - tBTM_BLE_SEC_ACT sec_act) -> tBTM_STATUS { + [](const RawAddress& bd_addr, tBT_TRANSPORT transport, tBTM_SEC_CALLBACK* p_callback, + void* p_ref_data, tBTM_BLE_SEC_ACT sec_act) -> tBTM_STATUS { inc_func_call_count("BTM_SetEncryption"); return BTM_CMD_STARTED; }; @@ -263,15 +257,15 @@ TEST_F(BtaDmTest, bta_dm_set_encryption) { BTA_DM_ENCRYPT_CBACK_queue = {}; } -void bta_dm_encrypt_cback(RawAddress bd_addr, tBT_TRANSPORT transport, - void* /* p_ref_data */, tBTM_STATUS result); +void bta_dm_encrypt_cback(RawAddress bd_addr, tBT_TRANSPORT transport, void* /* p_ref_data */, + tBTM_STATUS result); TEST_F(BtaDmTest, bta_dm_encrypt_cback) { const tBT_TRANSPORT transport{BT_TRANSPORT_LE}; // Setup a connected device tBTA_DM_PEER_DEVICE* device = - bluetooth::legacy::testing::allocate_device_for(kRawAddress, transport); + bluetooth::legacy::testing::allocate_device_for(kRawAddress, transport); ASSERT_TRUE(device != nullptr); device->conn_state = tBTA_DM_CONN_STATE::BTA_DM_CONNECTED; @@ -312,16 +306,15 @@ TEST_F(BtaDmTest, bta_dm_encrypt_cback) { } TEST_F(BtaDmTest, bta_dm_remname_cback__typical) { - tBTA_DM_SEARCH_CB& search_cb = - bluetooth::legacy::testing::bta_dm_disc_search_cb(); + tBTA_DM_SEARCH_CB& search_cb = bluetooth::legacy::testing::bta_dm_disc_search_cb(); search_cb.peer_bdaddr = kRawAddress; search_cb.name_discover_done = false; tBTM_REMOTE_DEV_NAME name = { - .status = BTM_SUCCESS, - .bd_addr = kRawAddress, - .remote_bd_name = {}, - .hci_status = HCI_SUCCESS, + .status = BTM_SUCCESS, + .bd_addr = kRawAddress, + .remote_bd_name = {}, + .hci_status = HCI_SUCCESS, }; bd_name_from_char_pointer(name.remote_bd_name, kRemoteName); @@ -329,22 +322,20 @@ TEST_F(BtaDmTest, bta_dm_remname_cback__typical) { sync_main_handler(); - ASSERT_TRUE( - bluetooth::legacy::testing::bta_dm_disc_search_cb().name_discover_done); + ASSERT_TRUE(bluetooth::legacy::testing::bta_dm_disc_search_cb().name_discover_done); } TEST_F(BtaDmTest, bta_dm_remname_cback__wrong_address) { - tBTA_DM_SEARCH_CB& search_cb = - bluetooth::legacy::testing::bta_dm_disc_search_cb(); + tBTA_DM_SEARCH_CB& search_cb = bluetooth::legacy::testing::bta_dm_disc_search_cb(); search_cb.p_device_search_cback = nullptr; search_cb.peer_bdaddr = kRawAddress; search_cb.name_discover_done = false; tBTM_REMOTE_DEV_NAME name = { - .status = BTM_SUCCESS, - .bd_addr = kRawAddress2, - .remote_bd_name = {}, - .hci_status = HCI_SUCCESS, + .status = BTM_SUCCESS, + .bd_addr = kRawAddress2, + .remote_bd_name = {}, + .hci_status = HCI_SUCCESS, }; bd_name_from_char_pointer(name.remote_bd_name, kRemoteName); @@ -354,16 +345,15 @@ TEST_F(BtaDmTest, bta_dm_remname_cback__wrong_address) { } TEST_F(BtaDmTest, bta_dm_remname_cback__HCI_ERR_CONNECTION_EXISTS) { - tBTA_DM_SEARCH_CB& search_cb = - bluetooth::legacy::testing::bta_dm_disc_search_cb(); + tBTA_DM_SEARCH_CB& search_cb = bluetooth::legacy::testing::bta_dm_disc_search_cb(); search_cb.peer_bdaddr = kRawAddress; search_cb.name_discover_done = false; tBTM_REMOTE_DEV_NAME name = { - .status = BTM_SUCCESS, - .bd_addr = RawAddress::kEmpty, - .remote_bd_name = {}, - .hci_status = HCI_ERR_CONNECTION_EXISTS, + .status = BTM_SUCCESS, + .bd_addr = RawAddress::kEmpty, + .remote_bd_name = {}, + .hci_status = HCI_ERR_CONNECTION_EXISTS, }; bd_name_from_char_pointer(name.remote_bd_name, kRemoteName); @@ -371,91 +361,79 @@ TEST_F(BtaDmTest, bta_dm_remname_cback__HCI_ERR_CONNECTION_EXISTS) { sync_main_handler(); - ASSERT_TRUE( - bluetooth::legacy::testing::bta_dm_disc_search_cb().name_discover_done); + ASSERT_TRUE(bluetooth::legacy::testing::bta_dm_disc_search_cb().name_discover_done); } TEST_F(BtaDmTest, bta_dm_determine_discovery_transport__BR_EDR) { - tBTA_DM_SEARCH_CB& search_cb = - bluetooth::legacy::testing::bta_dm_disc_search_cb(); + tBTA_DM_SEARCH_CB& search_cb = bluetooth::legacy::testing::bta_dm_disc_search_cb(); - mock_btm_client_interface.peer.BTM_ReadDevInfo = - [](const RawAddress& remote_bda, tBT_DEVICE_TYPE* p_dev_type, - tBLE_ADDR_TYPE* p_addr_type) { - *p_dev_type = BT_DEVICE_TYPE_BREDR; - *p_addr_type = BLE_ADDR_PUBLIC; - }; + mock_btm_client_interface.peer.BTM_ReadDevInfo = [](const RawAddress& remote_bda, + tBT_DEVICE_TYPE* p_dev_type, + tBLE_ADDR_TYPE* p_addr_type) { + *p_dev_type = BT_DEVICE_TYPE_BREDR; + *p_addr_type = BLE_ADDR_PUBLIC; + }; ASSERT_EQ(BT_TRANSPORT_BR_EDR, - bluetooth::legacy::testing::bta_dm_determine_discovery_transport( - kRawAddress)); + bluetooth::legacy::testing::bta_dm_determine_discovery_transport(kRawAddress)); } TEST_F(BtaDmTest, bta_dm_determine_discovery_transport__BLE__PUBLIC) { - tBTA_DM_SEARCH_CB& search_cb = - bluetooth::legacy::testing::bta_dm_disc_search_cb(); + tBTA_DM_SEARCH_CB& search_cb = bluetooth::legacy::testing::bta_dm_disc_search_cb(); - mock_btm_client_interface.peer.BTM_ReadDevInfo = - [](const RawAddress& remote_bda, tBT_DEVICE_TYPE* p_dev_type, - tBLE_ADDR_TYPE* p_addr_type) { - *p_dev_type = BT_DEVICE_TYPE_BLE; - *p_addr_type = BLE_ADDR_PUBLIC; - }; + mock_btm_client_interface.peer.BTM_ReadDevInfo = [](const RawAddress& remote_bda, + tBT_DEVICE_TYPE* p_dev_type, + tBLE_ADDR_TYPE* p_addr_type) { + *p_dev_type = BT_DEVICE_TYPE_BLE; + *p_addr_type = BLE_ADDR_PUBLIC; + }; ASSERT_EQ(BT_TRANSPORT_LE, - bluetooth::legacy::testing::bta_dm_determine_discovery_transport( - kRawAddress)); + bluetooth::legacy::testing::bta_dm_determine_discovery_transport(kRawAddress)); } TEST_F(BtaDmTest, bta_dm_determine_discovery_transport__DUMO) { - tBTA_DM_SEARCH_CB& search_cb = - bluetooth::legacy::testing::bta_dm_disc_search_cb(); + tBTA_DM_SEARCH_CB& search_cb = bluetooth::legacy::testing::bta_dm_disc_search_cb(); - mock_btm_client_interface.peer.BTM_ReadDevInfo = - [](const RawAddress& remote_bda, tBT_DEVICE_TYPE* p_dev_type, - tBLE_ADDR_TYPE* p_addr_type) { - *p_dev_type = BT_DEVICE_TYPE_DUMO; - *p_addr_type = BLE_ADDR_PUBLIC; - }; + mock_btm_client_interface.peer.BTM_ReadDevInfo = [](const RawAddress& remote_bda, + tBT_DEVICE_TYPE* p_dev_type, + tBLE_ADDR_TYPE* p_addr_type) { + *p_dev_type = BT_DEVICE_TYPE_DUMO; + *p_addr_type = BLE_ADDR_PUBLIC; + }; ASSERT_EQ(BT_TRANSPORT_BR_EDR, - bluetooth::legacy::testing::bta_dm_determine_discovery_transport( - kRawAddress)); + bluetooth::legacy::testing::bta_dm_determine_discovery_transport(kRawAddress)); } TEST_F(BtaDmTest, bta_dm_search_evt_text) { std::vector> events = { - std::make_pair(BTA_DM_INQ_RES_EVT, "BTA_DM_INQ_RES_EVT"), - std::make_pair(BTA_DM_INQ_CMPL_EVT, "BTA_DM_INQ_CMPL_EVT"), - std::make_pair(BTA_DM_DISC_CMPL_EVT, "BTA_DM_DISC_CMPL_EVT"), - std::make_pair(BTA_DM_SEARCH_CANCEL_CMPL_EVT, - "BTA_DM_SEARCH_CANCEL_CMPL_EVT"), - std::make_pair(BTA_DM_NAME_READ_EVT, "BTA_DM_NAME_READ_EVT"), + std::make_pair(BTA_DM_INQ_RES_EVT, "BTA_DM_INQ_RES_EVT"), + std::make_pair(BTA_DM_INQ_CMPL_EVT, "BTA_DM_INQ_CMPL_EVT"), + std::make_pair(BTA_DM_DISC_CMPL_EVT, "BTA_DM_DISC_CMPL_EVT"), + std::make_pair(BTA_DM_SEARCH_CANCEL_CMPL_EVT, "BTA_DM_SEARCH_CANCEL_CMPL_EVT"), + std::make_pair(BTA_DM_NAME_READ_EVT, "BTA_DM_NAME_READ_EVT"), }; for (const auto& event : events) { - ASSERT_STREQ(event.second.c_str(), - bta_dm_search_evt_text(event.first).c_str()); + ASSERT_STREQ(event.second.c_str(), bta_dm_search_evt_text(event.first).c_str()); } - ASSERT_STREQ( - base::StringPrintf("UNKNOWN[%hhu]", std::numeric_limits::max()) - .c_str(), - bta_dm_search_evt_text( - static_cast(std::numeric_limits::max())) - .c_str()); + ASSERT_STREQ(base::StringPrintf("UNKNOWN[%hhu]", std::numeric_limits::max()).c_str(), + bta_dm_search_evt_text( + static_cast(std::numeric_limits::max())) + .c_str()); } TEST_F(BtaDmTest, bta_dm_remote_name_cmpl) { reset_mock_btm_client_interface(); - mock_btm_client_interface.db.BTM_InqDbRead = - [](const RawAddress& bd_addr) -> tBTM_INQ_INFO* { + mock_btm_client_interface.db.BTM_InqDbRead = [](const RawAddress& bd_addr) -> tBTM_INQ_INFO* { inc_func_call_count("BTM_InqDbRead"); return nullptr; }; tBTA_DM_REMOTE_NAME remote_name_msg{ - // tBTA_DM_REMOTE_NAME - .bd_addr = kRawAddress, - .bd_name = {0}, - .hci_status = HCI_SUCCESS, + // tBTA_DM_REMOTE_NAME + .bd_addr = kRawAddress, + .bd_name = {0}, + .hci_status = HCI_SUCCESS, }; bluetooth::legacy::testing::bta_dm_remote_name_cmpl(remote_name_msg); ASSERT_EQ(1, get_func_call_count("BTM_InqDbRead")); @@ -470,12 +448,11 @@ TEST_F(BtaDmCustomAlarmTest, bta_dm_sniff_cback) { // Setup a connected device const tBT_TRANSPORT transport{BT_TRANSPORT_BR_EDR}; tBTA_DM_PEER_DEVICE* device = - bluetooth::legacy::testing::allocate_device_for(kRawAddress, transport); + bluetooth::legacy::testing::allocate_device_for(kRawAddress, transport); ASSERT_TRUE(device != nullptr); // Trigger a sniff timer - bta_dm_pm_start_timer(&bta_dm_cb.pm_timer[0], - bta_pm_action_to_timer_idx(BTA_DM_PM_SNIFF), 10, 1, + bta_dm_pm_start_timer(&bta_dm_cb.pm_timer[0], bta_pm_action_to_timer_idx(BTA_DM_PM_SNIFF), 10, 1, BTA_DM_PM_SNIFF); bta_dm_cb.pm_timer[0].peer_bdaddr = kRawAddress; ASSERT_EQ(1, get_func_call_count("alarm_set_on_mloop")); @@ -487,13 +464,10 @@ TEST_F(BtaDmCustomAlarmTest, bta_dm_sniff_cback) { } TEST_F_WITH_FLAGS(BtaDmCustomAlarmTest, sniff_offload_feature__enable_flag, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, - enable_sniff_offload))) { + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, enable_sniff_offload))) { bool is_property_enabled = true; test::mock::osi_properties::osi_property_get_bool.body = - [&](const char* key, bool default_value) -> int { - return is_property_enabled; - }; + [&](const char* key, bool default_value) -> int { return is_property_enabled; }; // Expect not to trigger bta_dm_init_pm due to both flag and prop are enabled // and reset the value of .srvc_id. @@ -509,13 +483,10 @@ TEST_F_WITH_FLAGS(BtaDmCustomAlarmTest, sniff_offload_feature__enable_flag, } TEST_F_WITH_FLAGS(BtaDmCustomAlarmTest, sniff_offload_feature__disable_flag, - REQUIRES_FLAGS_DISABLED(ACONFIG_FLAG(TEST_BT, - enable_sniff_offload))) { + REQUIRES_FLAGS_DISABLED(ACONFIG_FLAG(TEST_BT, enable_sniff_offload))) { bool is_property_enabled = true; test::mock::osi_properties::osi_property_get_bool.body = - [&](const char* key, bool default_value) -> int { - return is_property_enabled; - }; + [&](const char* key, bool default_value) -> int { return is_property_enabled; }; // Expect to trigger bta_dm_init_pm and init the value of .srvc_id to // BTA_ID_MAX. diff --git a/system/bta/test/bta_gatt_client_test.cc b/system/bta/test/bta_gatt_client_test.cc index 5e629cce787..60a7fd943e3 100644 --- a/system/bta/test/bta_gatt_client_test.cc +++ b/system/bta/test/bta_gatt_client_test.cc @@ -38,7 +38,7 @@ std::vector> PullCopyOfGattHistory(); } // namespace bluetooth class BtaDiscTest : public testing::Test { - protected: +protected: void SetUp() override {} void TearDown() override {} @@ -48,9 +48,9 @@ TEST_F(BtaDiscTest, nop) {} TEST_F(BtaDiscTest, gatt_history_callback) { std::array a = { - "ThisIsATest 0", - "ThisIsATest 1", - "ThisIsATest 2", + "ThisIsATest 0", + "ThisIsATest 1", + "ThisIsATest 2", }; // C string @@ -61,7 +61,7 @@ TEST_F(BtaDiscTest, gatt_history_callback) { gatt_history_callback(base::StringPrintf("%s", a[2].c_str())); std::vector> history = - bluetooth::legacy::testing::PullCopyOfGattHistory(); + bluetooth::legacy::testing::PullCopyOfGattHistory(); ASSERT_EQ(3UL, history.size()); ASSERT_STREQ(a[0].c_str(), history[0].entry.c_str()); ASSERT_STREQ(a[1].c_str(), history[1].entry.c_str()); diff --git a/system/bta/test/bta_gatt_test.cc b/system/bta/test/bta_gatt_test.cc index 97181b20223..b867948a34d 100644 --- a/system/bta/test/bta_gatt_test.cc +++ b/system/bta/test/bta_gatt_test.cc @@ -38,9 +38,8 @@ struct { void* data; } bta_gatt_read_complete_callback; } // namespace param -void bta_gatt_read_complete_callback(uint16_t conn_id, tGATT_STATUS status, - uint16_t handle, uint16_t len, - uint8_t* value, void* data) { +void bta_gatt_read_complete_callback(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, + uint16_t len, uint8_t* value, void* data) { param::bta_gatt_read_complete_callback.conn_id = conn_id; param::bta_gatt_read_complete_callback.status = status; param::bta_gatt_read_complete_callback.handle = handle; @@ -60,9 +59,8 @@ struct { } bta_gatt_write_complete_callback; } // namespace param -void bta_gatt_write_complete_callback(uint16_t conn_id, tGATT_STATUS status, - uint16_t handle, uint16_t len, - const uint8_t* value, void* data) { +void bta_gatt_write_complete_callback(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, + uint16_t len, const uint8_t* value, void* data) { param::bta_gatt_write_complete_callback.conn_id = conn_id; param::bta_gatt_write_complete_callback.status = status; param::bta_gatt_write_complete_callback.handle = handle; @@ -79,8 +77,7 @@ struct { } bta_gatt_configure_mtu_complete_callback; } // namespace param -void bta_gatt_configure_mtu_complete_callback(uint16_t conn_id, - tGATT_STATUS status, void* data) { +void bta_gatt_configure_mtu_complete_callback(uint16_t conn_id, tGATT_STATUS status, void* data) { param::bta_gatt_configure_mtu_complete_callback.conn_id = conn_id; param::bta_gatt_configure_mtu_complete_callback.status = status; param::bta_gatt_configure_mtu_complete_callback.data = data; @@ -93,14 +90,13 @@ struct { } bta_gattc_event_complete_callback; } // namespace param -void bta_gattc_event_complete_callback(tBTA_GATTC_EVT event, - tBTA_GATTC* p_data) { +void bta_gattc_event_complete_callback(tBTA_GATTC_EVT event, tBTA_GATTC* p_data) { param::bta_gattc_event_complete_callback.event = event; param::bta_gattc_event_complete_callback.p_data = p_data; } class BtaGattTest : public ::testing::Test { - protected: +protected: void SetUp() override { reset_mock_function_count_map(); param::bta_gatt_read_complete_callback = {}; @@ -112,57 +108,57 @@ class BtaGattTest : public ::testing::Test { void TearDown() override {} tBTA_GATTC_RCB app_control_block = { - .p_cback = bta_gattc_event_complete_callback, + .p_cback = bta_gattc_event_complete_callback, }; tGATT_CL_COMPLETE gatt_cl_complete = { - .att_value = - { - .conn_id = 1, - .handle = 2, - .offset = 3, - .len = 4, // length of value below - .auth_req = GATT_AUTH_REQ_NONE, - .value = {10, 11, 12, 13}, - }, + .att_value = + { + .conn_id = 1, + .handle = 2, + .offset = 3, + .len = 4, // length of value below + .auth_req = GATT_AUTH_REQ_NONE, + .value = {10, 11, 12, 13}, + }, }; tBTA_GATTC_SERV service_control_block = { - .mtu = 456, + .mtu = 456, }; tBTA_GATTC_DATA command_queue; tBTA_GATTC_CLCB client_channel_control_block = { - .bta_conn_id = 456, - .p_rcb = &app_control_block, - .p_srcb = &service_control_block, - .p_q_cmd = &command_queue, + .bta_conn_id = 456, + .p_rcb = &app_control_block, + .p_srcb = &service_control_block, + .p_q_cmd = &command_queue, }; }; TEST_F(BtaGattTest, bta_gattc_op_cmpl_read) { command_queue = { - .api_read = // tBTA_GATTC_API_READ - { - .hdr = - { - .event = BTA_GATTC_API_READ_EVT, - }, - .handle = 123, - .read_cb = bta_gatt_read_complete_callback, - .read_cb_data = static_cast(this), - }, + .api_read = // tBTA_GATTC_API_READ + { + .hdr = + { + .event = BTA_GATTC_API_READ_EVT, + }, + .handle = 123, + .read_cb = bta_gatt_read_complete_callback, + .read_cb_data = static_cast(this), + }, }; client_channel_control_block.p_q_cmd = &command_queue; tBTA_GATTC_DATA data = { - .op_cmpl = - { - .op_code = GATTC_OPTYPE_READ, - .status = GATT_OUT_OF_RANGE, - .p_cmpl = &gatt_cl_complete, - }, + .op_cmpl = + { + .op_code = GATTC_OPTYPE_READ, + .status = GATT_OUT_OF_RANGE, + .p_cmpl = &gatt_cl_complete, + }, }; bta_gattc_op_cmpl(&client_channel_control_block, &data); @@ -177,27 +173,27 @@ TEST_F(BtaGattTest, bta_gattc_op_cmpl_read) { TEST_F(BtaGattTest, bta_gattc_op_cmpl_write) { command_queue = { - .api_write = // tBTA_GATTC_API_WRITE - { - .hdr = - { - .event = BTA_GATTC_API_WRITE_EVT, - }, - .handle = 123, - .write_cb = bta_gatt_write_complete_callback, - .write_cb_data = static_cast(this), - }, + .api_write = // tBTA_GATTC_API_WRITE + { + .hdr = + { + .event = BTA_GATTC_API_WRITE_EVT, + }, + .handle = 123, + .write_cb = bta_gatt_write_complete_callback, + .write_cb_data = static_cast(this), + }, }; client_channel_control_block.p_q_cmd = &command_queue; tBTA_GATTC_DATA data = { - .op_cmpl = - { - .op_code = GATTC_OPTYPE_WRITE, - .status = GATT_OUT_OF_RANGE, - .p_cmpl = &gatt_cl_complete, - }, + .op_cmpl = + { + .op_code = GATTC_OPTYPE_WRITE, + .status = GATT_OUT_OF_RANGE, + .p_cmpl = &gatt_cl_complete, + }, }; bta_gattc_op_cmpl(&client_channel_control_block, &data); @@ -210,54 +206,53 @@ TEST_F(BtaGattTest, bta_gattc_op_cmpl_write) { TEST_F(BtaGattTest, bta_gattc_op_cmpl_config) { command_queue = { - .api_mtu = // tBTA_GATTC_API_CFG_MTU - { - .hdr = - { - .event = BTA_GATTC_API_CFG_MTU_EVT, - }, - .mtu_cb = bta_gatt_configure_mtu_complete_callback, - .mtu_cb_data = static_cast(this), - }, + .api_mtu = // tBTA_GATTC_API_CFG_MTU + { + .hdr = + { + .event = BTA_GATTC_API_CFG_MTU_EVT, + }, + .mtu_cb = bta_gatt_configure_mtu_complete_callback, + .mtu_cb_data = static_cast(this), + }, }; client_channel_control_block.p_q_cmd = &command_queue; tBTA_GATTC_DATA data = { - .op_cmpl = - { - .op_code = GATTC_OPTYPE_CONFIG, - .status = GATT_PRC_IN_PROGRESS, - }, + .op_cmpl = + { + .op_code = GATTC_OPTYPE_CONFIG, + .status = GATT_PRC_IN_PROGRESS, + }, }; bta_gattc_op_cmpl(&client_channel_control_block, &data); ASSERT_EQ(1, get_func_call_count("osi_free_and_reset")); ASSERT_EQ(456, param::bta_gatt_configure_mtu_complete_callback.conn_id); - ASSERT_EQ(GATT_PRC_IN_PROGRESS, - param::bta_gatt_configure_mtu_complete_callback.status); + ASSERT_EQ(GATT_PRC_IN_PROGRESS, param::bta_gatt_configure_mtu_complete_callback.status); ASSERT_EQ(this, param::bta_gatt_configure_mtu_complete_callback.data); } TEST_F(BtaGattTest, bta_gattc_op_cmpl_execute) { command_queue = { - .api_exec = // tBTA_GATTC_API_EXEC - { - .hdr = - { - .event = BTA_GATTC_API_EXEC_EVT, - }, - }, + .api_exec = // tBTA_GATTC_API_EXEC + { + .hdr = + { + .event = BTA_GATTC_API_EXEC_EVT, + }, + }, }; client_channel_control_block.p_q_cmd = &command_queue; tBTA_GATTC_DATA data = { - .op_cmpl = - { - .op_code = GATTC_OPTYPE_EXE_WRITE, - }, + .op_cmpl = + { + .op_code = GATTC_OPTYPE_EXE_WRITE, + }, }; bta_gattc_op_cmpl(&client_channel_control_block, &data); @@ -267,16 +262,16 @@ TEST_F(BtaGattTest, bta_gattc_op_cmpl_execute) { TEST_F(BtaGattTest, bta_gattc_op_cmpl_read_interrupted) { command_queue = { - .api_read = // tBTA_GATTC_API_READ - { - .hdr = - { - .event = BTA_GATTC_API_READ_EVT, - }, - .handle = 123, - .read_cb = bta_gatt_read_complete_callback, - .read_cb_data = static_cast(this), - }, + .api_read = // tBTA_GATTC_API_READ + { + .hdr = + { + .event = BTA_GATTC_API_READ_EVT, + }, + .handle = 123, + .read_cb = bta_gatt_read_complete_callback, + .read_cb_data = static_cast(this), + }, }; client_channel_control_block.p_q_cmd = &command_queue; @@ -286,12 +281,12 @@ TEST_F(BtaGattTest, bta_gattc_op_cmpl_read_interrupted) { client_channel_control_block.p_srcb->srvc_hdl_chg = 1; tBTA_GATTC_DATA data = { - .op_cmpl = - { - .op_code = GATTC_OPTYPE_READ, - .status = GATT_OUT_OF_RANGE, - .p_cmpl = &gatt_cl_complete, - }, + .op_cmpl = + { + .op_code = GATTC_OPTYPE_READ, + .status = GATT_OUT_OF_RANGE, + .p_cmpl = &gatt_cl_complete, + }, }; bta_gattc_op_cmpl(&client_channel_control_block, &data); diff --git a/system/bta/test/bta_hf_client_add_record_test.cc b/system/bta/test/bta_hf_client_add_record_test.cc index 0e3f75b6d14..0a41dde142f 100644 --- a/system/bta/test/bta_hf_client_add_record_test.cc +++ b/system/bta/test/bta_hf_client_add_record_test.cc @@ -25,7 +25,7 @@ #include "test/fake/fake_osi.h" class BtaHfClientAddRecordTest : public ::testing::Test { - protected: +protected: void SetUp() override { fake_osi_ = std::make_unique(); } void TearDown() override {} @@ -40,4 +40,3 @@ TEST_F(BtaHfClientAddRecordTest, test_hf_client_add_record) { bta_hf_client_add_record("Handsfree", scn, features, sdp_handle); ASSERT_EQ(HFP_VERSION_1_7, get_default_hfp_version()); } - diff --git a/system/bta/test/bta_hf_client_security_test.cc b/system/bta/test/bta_hf_client_security_test.cc index 0d2c38f1859..6023e617776 100644 --- a/system/bta/test/bta_hf_client_security_test.cc +++ b/system/bta/test/bta_hf_client_security_test.cc @@ -33,7 +33,7 @@ const RawAddress bdaddr1({0x11, 0x22, 0x33, 0x44, 0x55, 0x66}); } // namespace class BtaHfClientSecurityTest : public testing::Test { - protected: +protected: void SetUp() override { // Reset the memory block, this is the state on which the allocate handle // would start operating diff --git a/system/bta/test/bta_hf_client_test.cc b/system/bta/test/bta_hf_client_test.cc index 0c795c0008c..4559b0bfac3 100644 --- a/system/bta/test/bta_hf_client_test.cc +++ b/system/bta/test/bta_hf_client_test.cc @@ -30,7 +30,7 @@ const RawAddress bdaddr2({0x66, 0x55, 0x44, 0x33, 0x22, 0x11}); } // namespace class BtaHfClientTest : public testing::Test { - protected: +protected: void SetUp() override { fake_osi_ = std::make_unique(); // Reset the memory block, this is the state on which the allocate handle diff --git a/system/bta/test/bta_hh_test.cc b/system/bta/test/bta_hh_test.cc index e0b35eefe87..c86800d7db9 100644 --- a/system/bta/test/bta_hh_test.cc +++ b/system/bta/test/bta_hh_test.cc @@ -28,22 +28,18 @@ namespace { std::array data32 = { - 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, - 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, - 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, + 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, + 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, + 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, }; } class BtaHhTest : public ::testing::Test { - protected: +protected: void SetUp() override { reset_mock_function_count_map(); - test::mock::osi_allocator::osi_malloc.body = [](size_t size) { - return malloc(size); - }; - test::mock::osi_allocator::osi_calloc.body = [](size_t size) { - return calloc(1UL, size); - }; + test::mock::osi_allocator::osi_malloc.body = [](size_t size) { return malloc(size); }; + test::mock::osi_allocator::osi_calloc.body = [](size_t size) { return calloc(1UL, size); }; test::mock::osi_allocator::osi_free.body = [](void* ptr) { free(ptr); }; test::mock::osi_allocator::osi_free_and_reset.body = [](void** ptr) { free(*ptr); @@ -65,25 +61,25 @@ TEST_F(BtaHhTest, simple) {} TEST_F(BtaHhTest, bta_hh_ctrl_dat_act__BTA_HH_GET_RPT_EVT) { tBTA_HH_DEV_CB cb = { - .w4_evt = BTA_HH_GET_RPT_EVT, + .w4_evt = BTA_HH_GET_RPT_EVT, }; tBTA_HH_DATA data = { - .hid_cback = - { - .hdr = + .hid_cback = { - .event = 0, - .len = 0, - .offset = 0, - .layer_specific = 0, + .hdr = + { + .event = 0, + .len = 0, + .offset = 0, + .layer_specific = 0, + }, + .link_spec.addrt.bda = RawAddress::kEmpty, + .link_spec.addrt.type = BLE_ADDR_PUBLIC, + .link_spec.transport = BT_TRANSPORT_AUTO, + .data = 32, + .p_data = static_cast(osi_calloc(32 + sizeof(BT_HDR))), }, - .link_spec.addrt.bda = RawAddress::kEmpty, - .link_spec.addrt.type = BLE_ADDR_PUBLIC, - .link_spec.transport = BT_TRANSPORT_AUTO, - .data = 32, - .p_data = static_cast(osi_calloc(32 + sizeof(BT_HDR))), - }, }; data.hid_cback.p_data->len = static_cast(data32.size()); diff --git a/system/bta/test/bta_jv_test.cc b/system/bta/test/bta_jv_test.cc index aa06835235c..d541cf1562b 100644 --- a/system/bta/test/bta_jv_test.cc +++ b/system/bta/test/bta_jv_test.cc @@ -30,8 +30,7 @@ namespace { const RawAddress kRawAddress = RawAddress({0x11, 0x22, 0x33, 0x44, 0x55, 0x66}); -const RawAddress kRawAddress2 = - RawAddress({0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc}); +const RawAddress kRawAddress2 = RawAddress({0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc}); const bluetooth::Uuid kUuid = bluetooth::Uuid::From16Bit(0x1234); const bluetooth::Uuid kUuid2 = bluetooth::Uuid::From16Bit(0x789a); @@ -42,75 +41,67 @@ constexpr uint8_t kScn = 123; namespace bluetooth::legacy::testing { -void bta_jv_start_discovery_cback(uint32_t rfcomm_slot_id, - const RawAddress& bd_addr, +void bta_jv_start_discovery_cback(uint32_t rfcomm_slot_id, const RawAddress& bd_addr, tSDP_RESULT result); } // namespace bluetooth::legacy::testing class FakeSdp { - public: +public: FakeSdp() { test::mock::stack_sdp_legacy::api_ = { - .service = { - .SDP_InitDiscoveryDb = [](tSDP_DISCOVERY_DB*, uint32_t, uint16_t, - const bluetooth::Uuid*, uint16_t, - const uint16_t*) -> bool { return true; }, - .SDP_CancelServiceSearch = nullptr, - .SDP_ServiceSearchRequest = nullptr, - .SDP_ServiceSearchAttributeRequest = nullptr, - .SDP_ServiceSearchAttributeRequest2 = - [](const RawAddress& /* p_bd_addr */, - tSDP_DISCOVERY_DB* /* p_db */, - base::RepeatingCallback< - tSDP_DISC_CMPL_CB> /* complete_callback */) { - return true; - }, - }, - .db = - { - .SDP_FindServiceInDb = nullptr, - .SDP_FindServiceUUIDInDb = - [](const tSDP_DISCOVERY_DB* /* p_db */, - const bluetooth::Uuid& /* uuid */, - tSDP_DISC_REC* /* p_start_rec */) -> tSDP_DISC_REC* { - return nullptr; - }, - .SDP_FindServiceInDb_128bit = nullptr, - }, - .record = - { - .SDP_FindAttributeInRec = nullptr, - .SDP_FindServiceUUIDInRec_128bit = nullptr, - .SDP_FindProtocolListElemInRec = - [](const tSDP_DISC_REC* /* p_rec */, - uint16_t /* layer_uuid */, - tSDP_PROTOCOL_ELEM* /* p_elem */) -> bool { - return false; - }, - .SDP_FindProfileVersionInRec = nullptr, - .SDP_FindServiceUUIDInRec = nullptr, - }, - .handle = - { - .SDP_CreateRecord = nullptr, - .SDP_DeleteRecord = nullptr, - .SDP_AddAttribute = nullptr, - .SDP_AddSequence = nullptr, - .SDP_AddUuidSequence = nullptr, - .SDP_AddProtocolList = nullptr, - .SDP_AddAdditionProtoLists = nullptr, - .SDP_AddProfileDescriptorList = nullptr, - .SDP_AddLanguageBaseAttrIDList = nullptr, - .SDP_AddServiceClassIdList = nullptr, - }, - .device_id = - { - .SDP_SetLocalDiRecord = nullptr, - .SDP_DiDiscover = nullptr, - .SDP_GetNumDiRecords = nullptr, - .SDP_GetDiRecord = nullptr, + .service = { + .SDP_InitDiscoveryDb = [](tSDP_DISCOVERY_DB*, uint32_t, uint16_t, + const bluetooth::Uuid*, uint16_t, + const uint16_t*) -> bool { return true; }, + .SDP_CancelServiceSearch = nullptr, + .SDP_ServiceSearchRequest = nullptr, + .SDP_ServiceSearchAttributeRequest = nullptr, + .SDP_ServiceSearchAttributeRequest2 = + [](const RawAddress& /* p_bd_addr */, tSDP_DISCOVERY_DB* /* p_db */, + base::RepeatingCallback /* complete_callback */) { + return true; + }, }, + .db = + { + .SDP_FindServiceInDb = nullptr, + .SDP_FindServiceUUIDInDb = [](const tSDP_DISCOVERY_DB* /* p_db */, + const bluetooth::Uuid& /* uuid */, + tSDP_DISC_REC* /* p_start_rec */) + -> tSDP_DISC_REC* { return nullptr; }, + .SDP_FindServiceInDb_128bit = nullptr, + }, + .record = + { + .SDP_FindAttributeInRec = nullptr, + .SDP_FindServiceUUIDInRec_128bit = nullptr, + .SDP_FindProtocolListElemInRec = + [](const tSDP_DISC_REC* /* p_rec */, uint16_t /* layer_uuid */, + tSDP_PROTOCOL_ELEM* /* p_elem */) -> bool { return false; }, + .SDP_FindProfileVersionInRec = nullptr, + .SDP_FindServiceUUIDInRec = nullptr, + }, + .handle = + { + .SDP_CreateRecord = nullptr, + .SDP_DeleteRecord = nullptr, + .SDP_AddAttribute = nullptr, + .SDP_AddSequence = nullptr, + .SDP_AddUuidSequence = nullptr, + .SDP_AddProtocolList = nullptr, + .SDP_AddAdditionProtoLists = nullptr, + .SDP_AddProfileDescriptorList = nullptr, + .SDP_AddLanguageBaseAttrIDList = nullptr, + .SDP_AddServiceClassIdList = nullptr, + }, + .device_id = + { + .SDP_SetLocalDiRecord = nullptr, + .SDP_DiDiscover = nullptr, + .SDP_GetNumDiRecords = nullptr, + .SDP_GetDiRecord = nullptr, + }, }; } @@ -118,7 +109,7 @@ class FakeSdp { }; class BtaJvMockAndFakeTest : public ::testing::Test { - protected: +protected: void SetUp() override { reset_mock_function_count_map(); fake_osi_ = std::make_unique(); @@ -132,7 +123,7 @@ class BtaJvMockAndFakeTest : public ::testing::Test { }; class BtaJvTest : public BtaJvMockAndFakeTest { - protected: +protected: void SetUp() override { BtaJvMockAndFakeTest::SetUp(); bta_jv_cb.sdp_cb = {}; @@ -146,17 +137,15 @@ class BtaJvTest : public BtaJvMockAndFakeTest { TEST_F(BtaJvTest, bta_jv_start_discovery_cback__no_callback) { bta_jv_enable(nullptr); - bluetooth::legacy::testing::bta_jv_start_discovery_cback( - 0x12345678, kRawAddress, SDP_SUCCESS); + bluetooth::legacy::testing::bta_jv_start_discovery_cback(0x12345678, kRawAddress, SDP_SUCCESS); } -TEST_F(BtaJvTest, - bta_jv_start_discovery_cback__with_callback_success_no_record) { +TEST_F(BtaJvTest, bta_jv_start_discovery_cback__with_callback_success_no_record) { // Ensure that there was an sdp active bta_jv_cb.sdp_cb = { - .sdp_active = true, - .bd_addr = kRawAddress, - .uuid = kUuid, + .sdp_active = true, + .bd_addr = kRawAddress, + .uuid = kUuid, }; bta_jv_enable([](tBTA_JV_EVT event, tBTA_JV* p_data, uint32_t id) { switch (event) { @@ -174,37 +163,33 @@ TEST_F(BtaJvTest, FAIL(); } }); - bluetooth::legacy::testing::bta_jv_start_discovery_cback(kSlotId, kRawAddress, - SDP_SUCCESS); + bluetooth::legacy::testing::bta_jv_start_discovery_cback(kSlotId, kRawAddress, SDP_SUCCESS); } -TEST_F(BtaJvTest, - bta_jv_start_discovery_cback__with_callback_success_with_record) { +TEST_F(BtaJvTest, bta_jv_start_discovery_cback__with_callback_success_with_record) { static tSDP_DISC_REC sdp_disc_rec = { - .p_first_attr = nullptr, - .p_next_rec = nullptr, - .time_read = 1, - .remote_bd_addr = RawAddress::kAny, + .p_first_attr = nullptr, + .p_next_rec = nullptr, + .time_read = 1, + .remote_bd_addr = RawAddress::kAny, }; test::mock::stack_sdp_legacy::api_.db.SDP_FindServiceUUIDInDb = - [](const tSDP_DISCOVERY_DB* /* p_db */, const bluetooth::Uuid& /* uuid */, - tSDP_DISC_REC* /* p_start_rec */) -> tSDP_DISC_REC* { - return &sdp_disc_rec; - }; + [](const tSDP_DISCOVERY_DB* /* p_db */, const bluetooth::Uuid& /* uuid */, + tSDP_DISC_REC* /* p_start_rec */) -> tSDP_DISC_REC* { return &sdp_disc_rec; }; test::mock::stack_sdp_legacy::api_.record.SDP_FindProtocolListElemInRec = - [](const tSDP_DISC_REC* /* p_rec */, uint16_t /* layer_uuid */, - tSDP_PROTOCOL_ELEM* p_elem) -> bool { + [](const tSDP_DISC_REC* /* p_rec */, uint16_t /* layer_uuid */, + tSDP_PROTOCOL_ELEM* p_elem) -> bool { p_elem->params[0] = (uint16_t)kScn; return true; }; // Ensure that there was an sdp active bta_jv_cb.sdp_cb = { - .sdp_active = true, - .bd_addr = kRawAddress, - .uuid = kUuid, + .sdp_active = true, + .bd_addr = kRawAddress, + .uuid = kUuid, }; bta_jv_enable([](tBTA_JV_EVT event, tBTA_JV* p_data, uint32_t id) { switch (event) { @@ -223,8 +208,7 @@ TEST_F(BtaJvTest, FAIL(); } }); - bluetooth::legacy::testing::bta_jv_start_discovery_cback(kSlotId, kRawAddress, - SDP_SUCCESS); + bluetooth::legacy::testing::bta_jv_start_discovery_cback(kSlotId, kRawAddress, SDP_SUCCESS); } TEST_F(BtaJvTest, bta_jv_start_discovery_cback__with_callback_failure) { @@ -232,9 +216,9 @@ TEST_F(BtaJvTest, bta_jv_start_discovery_cback__with_callback_failure) { // Ensure that there was an sdp active bta_jv_cb.sdp_cb = { - .sdp_active = true, - .bd_addr = kRawAddress, - .uuid = kUuid, + .sdp_active = true, + .bd_addr = kRawAddress, + .uuid = kUuid, }; bta_jv_enable([](tBTA_JV_EVT event, tBTA_JV* p_data, uint32_t id) { switch (event) { @@ -252,13 +236,12 @@ TEST_F(BtaJvTest, bta_jv_start_discovery_cback__with_callback_failure) { FAIL(); } }); - bluetooth::legacy::testing::bta_jv_start_discovery_cback(kSlotId, kRawAddress, - result); + bluetooth::legacy::testing::bta_jv_start_discovery_cback(kSlotId, kRawAddress, result); } TEST_F(BtaJvTest, bta_jv_start_discovery__idle) { bluetooth::Uuid uuid_list[1] = { - kUuid, + kUuid, }; uint16_t num_uuid = (uint16_t)(sizeof(uuid_list) / sizeof(uuid_list[0])); @@ -271,16 +254,13 @@ TEST_F(BtaJvTest, bta_jv_start_discovery__idle) { TEST_F(BtaJvTest, bta_jv_start_discovery__idle_failed_to_start) { bluetooth::Uuid uuid_list[1] = { - kUuid, + kUuid, }; uint16_t num_uuid = (uint16_t)(sizeof(uuid_list) / sizeof(uuid_list[0])); - test::mock::stack_sdp_legacy::api_.service - .SDP_ServiceSearchAttributeRequest2 = - [](const RawAddress& /* p_bd_addr */, tSDP_DISCOVERY_DB* /* p_db */, - base::RepeatingCallback /* complete_callback */) { - return false; - }; + test::mock::stack_sdp_legacy::api_.service.SDP_ServiceSearchAttributeRequest2 = + [](const RawAddress& /* p_bd_addr */, tSDP_DISCOVERY_DB* /* p_db */, + base::RepeatingCallback /* complete_callback */) { return false; }; bta_jv_enable([](tBTA_JV_EVT event, tBTA_JV* p_data, uint32_t id) { switch (event) { @@ -307,13 +287,13 @@ TEST_F(BtaJvTest, bta_jv_start_discovery__idle_failed_to_start) { TEST_F(BtaJvTest, bta_jv_start_discovery__already_active) { bta_jv_cb.sdp_cb = { - .sdp_active = true, - .bd_addr = kRawAddress, - .uuid = kUuid, + .sdp_active = true, + .bd_addr = kRawAddress, + .uuid = kUuid, }; bluetooth::Uuid uuid_list[1] = { - kUuid2, + kUuid2, }; uint16_t num_uuid = (uint16_t)(sizeof(uuid_list) / sizeof(uuid_list[0])); diff --git a/system/bta/test/bta_pan_test.cc b/system/bta/test/bta_pan_test.cc index 146f2dd12fe..0e5a8cc4cc9 100644 --- a/system/bta/test/bta_pan_test.cc +++ b/system/bta/test/bta_pan_test.cc @@ -43,40 +43,36 @@ struct EventPiece { }; std::function bta_pan_event_closure; -void BTA_PAN_CBACK(tBTA_PAN_EVT event, tBTA_PAN* p_data) { - bta_pan_event_closure(event, p_data); -} +void BTA_PAN_CBACK(tBTA_PAN_EVT event, tBTA_PAN* p_data) { bta_pan_event_closure(event, p_data); } std::function bta_sys_eir_closure; -void BTA_SYS_EIR_CBACK(uint16_t uuid16, bool adding) { - bta_sys_eir_closure(uuid16, adding); -} +void BTA_SYS_EIR_CBACK(uint16_t uuid16, bool adding) { bta_sys_eir_closure(uuid16, adding); } constexpr tBTA_PAN kNoData = {}; } // namespace class BtaPanTest : public ::testing::Test { - protected: +protected: void SetUp() override { uuids.clear(); main_thread_start_up(); bta_pan_event_closure = [this](tBTA_PAN_EVT event, tBTA_PAN* data) { events.push_back({ - .event = event, - .data = (data == nullptr) ? kNoData : *data, + .event = event, + .data = (data == nullptr) ? kNoData : *data, }); }; tBTA_PAN_DATA data = { - .api_enable = - { - .p_cback = BTA_PAN_CBACK, - }, + .api_enable = + { + .p_cback = BTA_PAN_CBACK, + }, }; bta_sys_eir_closure = [this](uint16_t uuid16, bool adding) { uuids.push_back({ - .uuid16 = uuid16, - .adding = adding, + .uuid16 = uuid16, + .adding = adding, }); }; bta_pan_enable(&data); @@ -97,7 +93,7 @@ class BtaPanTest : public ::testing::Test { }; class BtaPanRegisteredTest : public BtaPanTest { - protected: +protected: void SetUp() { BtaPanTest::SetUp(); bta_sys_eir_register(BTA_SYS_EIR_CBACK); @@ -114,13 +110,13 @@ TEST_F(BtaPanTest, nop) {} TEST_F(BtaPanRegisteredTest, BTA_PanSetRole_Null) { tBTA_PAN_ROLE role = BTA_PAN_ROLE_PANU | BTA_PAN_ROLE_NAP; tBTA_PAN_ROLE_INFO user_info = { - .p_srv_name = std::string(), - .app_id = 12, + .p_srv_name = std::string(), + .app_id = 12, }; tBTA_PAN_ROLE_INFO nap_info = { - .p_srv_name = std::string(), - .app_id = 34, + .p_srv_name = std::string(), + .app_id = 34, }; BTA_PanSetRole(role, user_info, nap_info); @@ -142,12 +138,12 @@ TEST_F(BtaPanRegisteredTest, BTA_PanSetRole_Null) { TEST_F(BtaPanRegisteredTest, BTA_PanSetRole_WithNames) { tBTA_PAN_ROLE role = BTA_PAN_ROLE_PANU | BTA_PAN_ROLE_NAP; tBTA_PAN_ROLE_INFO user_info = { - .p_srv_name = "TestPanUser", - .app_id = 12, + .p_srv_name = "TestPanUser", + .app_id = 12, }; tBTA_PAN_ROLE_INFO nap_info = { - .p_srv_name = "TestPanNap", - .app_id = 34, + .p_srv_name = "TestPanNap", + .app_id = 34, }; uint8_t stack_pan_role; @@ -155,9 +151,8 @@ TEST_F(BtaPanRegisteredTest, BTA_PanSetRole_WithNames) { std::string stack_pan_nap_name; test::mock::stack_pan_api::PAN_SetRole.body = - [&stack_pan_role, &stack_pan_user_name, &stack_pan_nap_name]( - uint8_t role, std::string user_name, - std::string nap_name) -> tPAN_RESULT { + [&stack_pan_role, &stack_pan_user_name, &stack_pan_nap_name]( + uint8_t role, std::string user_name, std::string nap_name) -> tPAN_RESULT { stack_pan_role = role; stack_pan_user_name = user_name; stack_pan_nap_name = nap_name; @@ -189,14 +184,14 @@ constexpr size_t kBtaServiceNameLen = static_cast(BTA_SERVICE_NAME_LEN); TEST_F(BtaPanRegisteredTest, BTA_PanSetRole_WithLongNames) { tBTA_PAN_ROLE role = BTA_PAN_ROLE_PANU | BTA_PAN_ROLE_NAP; tBTA_PAN_ROLE_INFO user_info = { - .p_srv_name = std::string(200, 'A'), - .app_id = 12, + .p_srv_name = std::string(200, 'A'), + .app_id = 12, }; ASSERT_EQ(200UL, user_info.p_srv_name.size()); tBTA_PAN_ROLE_INFO nap_info = { - .p_srv_name = std::string(201, 'A'), - .app_id = 34, + .p_srv_name = std::string(201, 'A'), + .app_id = 34, }; ASSERT_EQ(201UL, nap_info.p_srv_name.size()); @@ -205,9 +200,8 @@ TEST_F(BtaPanRegisteredTest, BTA_PanSetRole_WithLongNames) { std::string stack_pan_nap_name; test::mock::stack_pan_api::PAN_SetRole.body = - [&stack_pan_role, &stack_pan_user_name, &stack_pan_nap_name]( - uint8_t role, std::string user_name, - std::string nap_name) -> tPAN_RESULT { + [&stack_pan_role, &stack_pan_user_name, &stack_pan_nap_name]( + uint8_t role, std::string user_name, std::string nap_name) -> tPAN_RESULT { stack_pan_role = role; stack_pan_user_name = user_name; stack_pan_nap_name = nap_name; @@ -233,8 +227,7 @@ TEST_F(BtaPanRegisteredTest, BTA_PanSetRole_WithLongNames) { ASSERT_EQ(kBtaServiceNameLen, stack_pan_nap_name.size()); ASSERT_THAT(stack_pan_user_name, StrEq(std::string(kBtaServiceNameLen, 'A'))); - ASSERT_THAT(stack_pan_user_name, - StrEq("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")); + ASSERT_THAT(stack_pan_user_name, StrEq("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")); ASSERT_THAT(stack_pan_nap_name, StrEq(std::string(kBtaServiceNameLen, 'A'))); ASSERT_THAT(stack_pan_nap_name, StrEq("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")); diff --git a/system/bta/test/bta_rfcomm_scn_test.cc b/system/bta/test/bta_rfcomm_scn_test.cc index 26e85ce9a60..c2b96a749c1 100644 --- a/system/bta/test/bta_rfcomm_scn_test.cc +++ b/system/bta/test/bta_rfcomm_scn_test.cc @@ -26,8 +26,8 @@ using testing::Test; class BtaRfcommScnTest : public Test { - public: - protected: +public: +protected: void SetUp() override { tBTA_JV_DM_CBACK* p_cback = [](tBTA_JV_EVT, tBTA_JV*, uint32_t) {}; bta_jv_enable(p_cback); diff --git a/system/bta/test/bta_sdp_test.cc b/system/bta/test/bta_sdp_test.cc index 28ca95a4a2f..32f1eca311e 100644 --- a/system/bta/test/bta_sdp_test.cc +++ b/system/bta/test/bta_sdp_test.cc @@ -39,14 +39,14 @@ void bta_dm_sdp_result(tSDP_STATUS sdp_status, tBTA_DM_SDP_STATE* state); } // namespace bluetooth class BtaSdpTest : public BtaWithHwOnTest { - protected: +protected: void SetUp() override { BtaWithHwOnTest::SetUp(); } void TearDown() override { BtaWithHwOnTest::TearDown(); } }; class BtaSdpRegisteredTest : public BtaSdpTest { - protected: +protected: void SetUp() override { BtaSdpTest::SetUp(); } void TearDown() override { BtaSdpTest::TearDown(); } @@ -55,8 +55,7 @@ class BtaSdpRegisteredTest : public BtaSdpTest { TEST_F(BtaSdpTest, nop) {} TEST_F(BtaSdpRegisteredTest, bta_dm_sdp_result_SDP_SUCCESS) { - std::unique_ptr state = - std::make_unique( + std::unique_ptr state = std::make_unique( tBTA_DM_SDP_STATE{.service_index = BTA_MAX_SERVICE_ID}); bluetooth::legacy::testing::bta_dm_sdp_result(SDP_SUCCESS, state.get()); } diff --git a/system/bta/test/bta_sec_test.cc b/system/bta/test/bta_sec_test.cc index d585e9e0891..579347918aa 100644 --- a/system/bta/test/bta_sec_test.cc +++ b/system/bta/test/bta_sec_test.cc @@ -49,7 +49,7 @@ tBTM_STATUS bta_dm_sp_cback(tBTM_SP_EVT event, tBTM_SP_EVT_DATA* p_data); } // namespace bluetooth class BtaSecTest : public BtaWithHwOnTest { - protected: +protected: void SetUp() override { BtaWithHwOnTest::SetUp(); } void TearDown() override { BtaWithHwOnTest::TearDown(); } @@ -59,8 +59,8 @@ TEST_F(BtaSecTest, bta_dm_sp_cback__BTM_SP_CFM_REQ_EVT_WithName) { constexpr uint32_t kNumVal = 1234; static bool callback_sent = false; mock_btm_client_interface.peer.BTM_ReadRemoteDeviceName = - [](const RawAddress& remote_bda, tBTM_NAME_CMPL_CB* p_cb, - tBT_TRANSPORT transport) -> tBTM_STATUS { return BTM_CMD_STARTED; }; + [](const RawAddress& remote_bda, tBTM_NAME_CMPL_CB* p_cb, + tBT_TRANSPORT transport) -> tBTM_STATUS { return BTM_CMD_STARTED; }; static tBTA_DM_SP_CFM_REQ cfm_req{}; bta_dm_sec_enable([](tBTA_DM_SEC_EVT event, tBTA_DM_SEC* p_data) { @@ -69,32 +69,31 @@ TEST_F(BtaSecTest, bta_dm_sp_cback__BTM_SP_CFM_REQ_EVT_WithName) { }); tBTM_SP_EVT_DATA data = { - .cfm_req = - { - // tBTM_SP_CFM_REQ - .bd_addr = kRawAddress, - .dev_class = {}, - .bd_name = {}, - .num_val = kNumVal, - .just_works = false, - .loc_auth_req = BTM_AUTH_SP_YES, - .rmt_auth_req = BTM_AUTH_SP_YES, - .loc_io_caps = BTM_IO_CAP_NONE, - .rmt_io_caps = BTM_IO_CAP_NONE, - }, + .cfm_req = + { + // tBTM_SP_CFM_REQ + .bd_addr = kRawAddress, + .dev_class = {}, + .bd_name = {}, + .num_val = kNumVal, + .just_works = false, + .loc_auth_req = BTM_AUTH_SP_YES, + .rmt_auth_req = BTM_AUTH_SP_YES, + .loc_io_caps = BTM_IO_CAP_NONE, + .rmt_io_caps = BTM_IO_CAP_NONE, + }, }; data.cfm_req.dev_class = kDeviceClass; bd_name_from_char_pointer(data.cfm_req.bd_name, kRemoteName); - ASSERT_EQ(btm_status_text(BTM_CMD_STARTED), - btm_status_text(bluetooth::legacy::testing::bta_dm_sp_cback( - BTM_SP_CFM_REQ_EVT, &data))); + ASSERT_EQ( + btm_status_text(BTM_CMD_STARTED), + btm_status_text(bluetooth::legacy::testing::bta_dm_sp_cback(BTM_SP_CFM_REQ_EVT, &data))); ASSERT_EQ(kNumVal, bta_dm_sec_cb.num_val); ASSERT_TRUE(callback_sent); ASSERT_EQ(kRawAddress, cfm_req.bd_addr); - ASSERT_THAT(cfm_req.dev_class, - ElementsAre(kDeviceClass[0], kDeviceClass[1], kDeviceClass[2])); + ASSERT_THAT(cfm_req.dev_class, ElementsAre(kDeviceClass[0], kDeviceClass[1], kDeviceClass[2])); ASSERT_STREQ(kRemoteName, reinterpret_cast(cfm_req.bd_name)); ASSERT_EQ(kNumVal, cfm_req.num_val); ASSERT_EQ(false, cfm_req.just_works); @@ -109,8 +108,8 @@ TEST_F(BtaSecTest, bta_dm_sp_cback__BTM_SP_CFM_REQ_EVT_WithoutName_RNRSuccess) { static bool callback_sent = false; reset_mock_btm_client_interface(); mock_btm_client_interface.peer.BTM_ReadRemoteDeviceName = - [](const RawAddress& remote_bda, tBTM_NAME_CMPL_CB* p_cb, - tBT_TRANSPORT transport) -> tBTM_STATUS { return BTM_CMD_STARTED; }; + [](const RawAddress& remote_bda, tBTM_NAME_CMPL_CB* p_cb, + tBT_TRANSPORT transport) -> tBTM_STATUS { return BTM_CMD_STARTED; }; static tBTA_DM_SP_CFM_REQ cfm_req{}; bta_dm_sec_enable([](tBTA_DM_SEC_EVT event, tBTA_DM_SEC* p_data) { @@ -119,25 +118,25 @@ TEST_F(BtaSecTest, bta_dm_sp_cback__BTM_SP_CFM_REQ_EVT_WithoutName_RNRSuccess) { }); tBTM_SP_EVT_DATA data = { - .cfm_req = - { - // tBTM_SP_CFM_REQ - .bd_addr = kRawAddress, - .dev_class = {}, - .bd_name = {0}, // No name available - .num_val = kNumVal, - .just_works = false, - .loc_auth_req = BTM_AUTH_SP_YES, - .rmt_auth_req = BTM_AUTH_SP_YES, - .loc_io_caps = BTM_IO_CAP_NONE, - .rmt_io_caps = BTM_IO_CAP_NONE, - }, + .cfm_req = + { + // tBTM_SP_CFM_REQ + .bd_addr = kRawAddress, + .dev_class = {}, + .bd_name = {0}, // No name available + .num_val = kNumVal, + .just_works = false, + .loc_auth_req = BTM_AUTH_SP_YES, + .rmt_auth_req = BTM_AUTH_SP_YES, + .loc_io_caps = BTM_IO_CAP_NONE, + .rmt_io_caps = BTM_IO_CAP_NONE, + }, }; data.cfm_req.dev_class = kDeviceClass; - ASSERT_EQ(btm_status_text(BTM_CMD_STARTED), - btm_status_text(bluetooth::legacy::testing::bta_dm_sp_cback( - BTM_SP_CFM_REQ_EVT, &data))); + ASSERT_EQ( + btm_status_text(BTM_CMD_STARTED), + btm_status_text(bluetooth::legacy::testing::bta_dm_sp_cback(BTM_SP_CFM_REQ_EVT, &data))); ASSERT_EQ(kNumVal, bta_dm_sec_cb.num_val); ASSERT_FALSE(callback_sent); @@ -148,8 +147,8 @@ TEST_F(BtaSecTest, bta_dm_sp_cback__BTM_SP_CFM_REQ_EVT_WithoutName_RNRFail) { constexpr uint32_t kNumVal = 1234; static bool callback_sent = false; mock_btm_client_interface.peer.BTM_ReadRemoteDeviceName = - [](const RawAddress& remote_bda, tBTM_NAME_CMPL_CB* p_cb, - tBT_TRANSPORT transport) -> tBTM_STATUS { return BTM_SUCCESS; }; + [](const RawAddress& remote_bda, tBTM_NAME_CMPL_CB* p_cb, + tBT_TRANSPORT transport) -> tBTM_STATUS { return BTM_SUCCESS; }; static tBTA_DM_SP_CFM_REQ cfm_req{}; bta_dm_sec_enable([](tBTA_DM_SEC_EVT event, tBTA_DM_SEC* p_data) { @@ -158,31 +157,30 @@ TEST_F(BtaSecTest, bta_dm_sp_cback__BTM_SP_CFM_REQ_EVT_WithoutName_RNRFail) { }); tBTM_SP_EVT_DATA data = { - .cfm_req = - { - // tBTM_SP_CFM_REQ - .bd_addr = kRawAddress, - .dev_class = {}, - .bd_name = {0}, - .num_val = kNumVal, - .just_works = false, - .loc_auth_req = BTM_AUTH_SP_YES, - .rmt_auth_req = BTM_AUTH_SP_YES, - .loc_io_caps = BTM_IO_CAP_NONE, - .rmt_io_caps = BTM_IO_CAP_NONE, - }, + .cfm_req = + { + // tBTM_SP_CFM_REQ + .bd_addr = kRawAddress, + .dev_class = {}, + .bd_name = {0}, + .num_val = kNumVal, + .just_works = false, + .loc_auth_req = BTM_AUTH_SP_YES, + .rmt_auth_req = BTM_AUTH_SP_YES, + .loc_io_caps = BTM_IO_CAP_NONE, + .rmt_io_caps = BTM_IO_CAP_NONE, + }, }; data.cfm_req.dev_class = kDeviceClass; - ASSERT_EQ(btm_status_text(BTM_CMD_STARTED), - btm_status_text(bluetooth::legacy::testing::bta_dm_sp_cback( - BTM_SP_CFM_REQ_EVT, &data))); + ASSERT_EQ( + btm_status_text(BTM_CMD_STARTED), + btm_status_text(bluetooth::legacy::testing::bta_dm_sp_cback(BTM_SP_CFM_REQ_EVT, &data))); ASSERT_EQ(kNumVal, bta_dm_sec_cb.num_val); ASSERT_TRUE(callback_sent); ASSERT_EQ(kRawAddress, cfm_req.bd_addr); - ASSERT_THAT(cfm_req.dev_class, - ElementsAre(kDeviceClass[0], kDeviceClass[1], kDeviceClass[2])); + ASSERT_THAT(cfm_req.dev_class, ElementsAre(kDeviceClass[0], kDeviceClass[1], kDeviceClass[2])); ASSERT_EQ(kNumVal, cfm_req.num_val); ASSERT_EQ(false, cfm_req.just_works); ASSERT_EQ(BTM_AUTH_SP_YES, cfm_req.loc_auth_req); @@ -195,8 +193,8 @@ TEST_F(BtaSecTest, bta_dm_sp_cback__BTM_SP_KEY_NOTIF_EVT) { constexpr uint32_t kPassKey = 1234; static bool callback_sent = false; mock_btm_client_interface.peer.BTM_ReadRemoteDeviceName = - [](const RawAddress& remote_bda, tBTM_NAME_CMPL_CB* p_cb, - tBT_TRANSPORT transport) -> tBTM_STATUS { return BTM_CMD_STARTED; }; + [](const RawAddress& remote_bda, tBTM_NAME_CMPL_CB* p_cb, + tBT_TRANSPORT transport) -> tBTM_STATUS { return BTM_CMD_STARTED; }; static tBTA_DM_SP_KEY_NOTIF key_notif{}; bta_dm_sec_enable([](tBTA_DM_SEC_EVT event, tBTA_DM_SEC* p_data) { @@ -205,27 +203,26 @@ TEST_F(BtaSecTest, bta_dm_sp_cback__BTM_SP_KEY_NOTIF_EVT) { }); tBTM_SP_EVT_DATA data = { - .key_notif = - { - // tBTM_SP_KEY_NOTIF - .bd_addr = kRawAddress, - .dev_class = {}, - .bd_name = {}, - .passkey = kPassKey, - }, + .key_notif = + { + // tBTM_SP_KEY_NOTIF + .bd_addr = kRawAddress, + .dev_class = {}, + .bd_name = {}, + .passkey = kPassKey, + }, }; data.key_notif.dev_class = kDeviceClass; bd_name_from_char_pointer(data.key_notif.bd_name, kRemoteName); ASSERT_EQ(btm_status_text(BTM_CMD_STARTED), - btm_status_text(bluetooth::legacy::testing::bta_dm_sp_cback( - BTM_SP_KEY_NOTIF_EVT, &data))); + btm_status_text( + bluetooth::legacy::testing::bta_dm_sp_cback(BTM_SP_KEY_NOTIF_EVT, &data))); ASSERT_EQ(kPassKey, bta_dm_sec_cb.num_val); ASSERT_TRUE(callback_sent); ASSERT_EQ(kRawAddress, key_notif.bd_addr); - ASSERT_THAT(key_notif.dev_class, - ElementsAre(kDeviceClass[0], kDeviceClass[1], kDeviceClass[2])); + ASSERT_THAT(key_notif.dev_class, ElementsAre(kDeviceClass[0], kDeviceClass[1], kDeviceClass[2])); ASSERT_STREQ(kRemoteName, reinterpret_cast(key_notif.bd_name)); ASSERT_EQ(kPassKey, key_notif.passkey); } diff --git a/system/bta/test/bta_test_fixtures.h b/system/bta/test/bta_test_fixtures.h index c09f9ca3ed1..d38f40ac240 100644 --- a/system/bta/test/bta_test_fixtures.h +++ b/system/bta/test/bta_test_fixtures.h @@ -41,7 +41,7 @@ extern tBTA_DM_CB bta_dm_cb; // Set up base mocks and fakes class BtaWithFakesTest : public testing::Test { - protected: +protected: void SetUp() override { bta_dm_cb = {}; fake_osi_ = std::make_unique(); @@ -53,7 +53,7 @@ class BtaWithFakesTest : public testing::Test { // Setup any default or optional mocks class BtaWithMocksTest : public BtaWithFakesTest { - protected: +protected: void SetUp() override { BtaWithFakesTest::SetUp(); reset_mock_function_count_map(); @@ -63,21 +63,19 @@ class BtaWithMocksTest : public BtaWithFakesTest { bluetooth::hci::testing::mock_controller_ = &mock_controller_; test::mock::stack_gatt_api::GATT_Register.body = - [](const bluetooth::Uuid& p_app_uuid128, const std::string name, - tGATT_CBACK* p_cb_info, - bool eatt_support) -> tGATT_IF { return kGattRegisteredIf; }; + [](const bluetooth::Uuid& p_app_uuid128, const std::string name, tGATT_CBACK* p_cb_info, + bool eatt_support) -> tGATT_IF { return kGattRegisteredIf; }; mock_btm_client_interface.eir.BTM_GetEirSupportedServices = - [](uint32_t* p_eir_uuid, uint8_t** p, uint8_t max_num_uuid16, - uint8_t* p_num_uuid16) -> uint8_t { return 0; }; - mock_btm_client_interface.eir.BTM_WriteEIR = - [](BT_HDR* p_buf) -> tBTM_STATUS { + [](uint32_t* p_eir_uuid, uint8_t** p, uint8_t max_num_uuid16, + uint8_t* p_num_uuid16) -> uint8_t { return 0; }; + mock_btm_client_interface.eir.BTM_WriteEIR = [](BT_HDR* p_buf) -> tBTM_STATUS { osi_free(p_buf); return BTM_SUCCESS; }; mock_btm_client_interface.local.BTM_ReadLocalDeviceNameFromController = - [](tBTM_CMPL_CB* cb) -> tBTM_STATUS { return BTM_CMD_STARTED; }; + [](tBTM_CMPL_CB* cb) -> tBTM_STATUS { return BTM_CMD_STARTED; }; mock_btm_client_interface.security.BTM_SecRegister = - [](const tBTM_APPL_INFO* p_cb_info) -> bool { return true; }; + [](const tBTM_APPL_INFO* p_cb_info) -> bool { return true; }; } void TearDown() override { @@ -96,22 +94,21 @@ class BtaWithMocksTest : public BtaWithFakesTest { }; class BtaWithContextTest : public BtaWithMocksTest { - protected: +protected: void SetUp() override { BtaWithMocksTest::SetUp(); main_thread_start_up(); post_on_bt_main([]() { bluetooth::log::info("Main thread started up"); }); } void TearDown() override { - post_on_bt_main( - []() { bluetooth::log::info("Main thread shutting down"); }); + post_on_bt_main([]() { bluetooth::log::info("Main thread shutting down"); }); main_thread_shut_down(); BtaWithMocksTest::TearDown(); } }; class BtaWithHwOnTest : public BtaWithContextTest { - protected: +protected: void SetUp() override { BtaWithContextTest::SetUp(); BTA_dm_on_hw_on(); diff --git a/system/bta/test/common/bta_dm_api_mock.h b/system/bta/test/common/bta_dm_api_mock.h index 005a24ab7c5..b724267eb65 100644 --- a/system/bta/test/common/bta_dm_api_mock.h +++ b/system/bta/test/common/bta_dm_api_mock.h @@ -20,32 +20,26 @@ #include #include "bta_api.h" -#include "bta_sec_api.h" #include "bta_dm_api.h" +#include "bta_sec_api.h" namespace dm { class BtaDmInterface { - public: - virtual void BTA_DmBleScan(bool start, uint8_t duration, - bool low_latency_scan) = 0; - virtual void BTA_DmBleCsisObserve(bool observe, - tBTA_DM_SEARCH_CBACK* p_results_cb) = 0; +public: + virtual void BTA_DmBleScan(bool start, uint8_t duration, bool low_latency_scan) = 0; + virtual void BTA_DmBleCsisObserve(bool observe, tBTA_DM_SEARCH_CBACK* p_results_cb) = 0; virtual void BTA_DmSirkSecCbRegister(tBTA_DM_SEC_CBACK* p_cback) = 0; - virtual void BTA_DmSirkConfirmDeviceReply(const RawAddress& bd_addr, - bool accept) = 0; + virtual void BTA_DmSirkConfirmDeviceReply(const RawAddress& bd_addr, bool accept) = 0; virtual ~BtaDmInterface() = default; }; class MockBtaDmInterface : public BtaDmInterface { - public: - MOCK_METHOD((void), BTA_DmBleScan, - (bool start, uint8_t duration, bool low_latency_scan)); - MOCK_METHOD((void), BTA_DmBleCsisObserve, - (bool observe, tBTA_DM_SEARCH_CBACK* p_results_cb)); +public: + MOCK_METHOD((void), BTA_DmBleScan, (bool start, uint8_t duration, bool low_latency_scan)); + MOCK_METHOD((void), BTA_DmBleCsisObserve, (bool observe, tBTA_DM_SEARCH_CBACK* p_results_cb)); MOCK_METHOD((void), BTA_DmSirkSecCbRegister, (tBTA_DM_SEC_CBACK * p_cback)); - MOCK_METHOD((void), BTA_DmSirkConfirmDeviceReply, - (const RawAddress& bd_addr, bool accept)); + MOCK_METHOD((void), BTA_DmSirkConfirmDeviceReply, (const RawAddress& bd_addr, bool accept)); }; /** diff --git a/system/bta/test/common/bta_gatt_api_mock.cc b/system/bta/test/common/bta_gatt_api_mock.cc index 164241164f7..d84d365d3fb 100644 --- a/system/bta/test/common/bta_gatt_api_mock.cc +++ b/system/bta/test/common/bta_gatt_api_mock.cc @@ -26,13 +26,12 @@ using namespace bluetooth; static gatt::MockBtaGattInterface* gatt_interface = nullptr; -void gatt::SetMockBtaGattInterface( - MockBtaGattInterface* mock_bta_gatt_interface) { +void gatt::SetMockBtaGattInterface(MockBtaGattInterface* mock_bta_gatt_interface) { gatt_interface = mock_bta_gatt_interface; } -void BTA_GATTC_AppRegister(tBTA_GATTC_CBACK* p_client_cb, - BtaAppRegisterCallback cb, bool eatt_support) { +void BTA_GATTC_AppRegister(tBTA_GATTC_CBACK* p_client_cb, BtaAppRegisterCallback cb, + bool eatt_support) { log::assert_that(gatt_interface != nullptr, "Mock GATT interface not set!"); gatt_interface->AppRegister(p_client_cb, cb, eatt_support); } @@ -43,11 +42,11 @@ void BTA_GATTC_AppDeregister(tGATT_IF client_if) { } void BTA_GATTC_Open(tGATT_IF client_if, const RawAddress& remote_bda, - tBTM_BLE_CONN_TYPE connection_type, tBT_TRANSPORT transport, - bool opportunistic, uint8_t initiating_phys) { + tBTM_BLE_CONN_TYPE connection_type, tBT_TRANSPORT transport, bool opportunistic, + uint8_t initiating_phys) { log::assert_that(gatt_interface != nullptr, "Mock GATT interface not set!"); - gatt_interface->Open(client_if, remote_bda, connection_type, transport, - opportunistic, initiating_phys); + gatt_interface->Open(client_if, remote_bda, connection_type, transport, opportunistic, + initiating_phys); } void BTA_GATTC_Open(tGATT_IF client_if, const RawAddress& remote_bda, @@ -56,8 +55,7 @@ void BTA_GATTC_Open(tGATT_IF client_if, const RawAddress& remote_bda, gatt_interface->Open(client_if, remote_bda, connection_type, opportunistic); } -void BTA_GATTC_CancelOpen(tGATT_IF client_if, const RawAddress& remote_bda, - bool is_direct) { +void BTA_GATTC_CancelOpen(tGATT_IF client_if, const RawAddress& remote_bda, bool is_direct) { log::assert_that(gatt_interface != nullptr, "Mock GATT interface not set!"); gatt_interface->CancelOpen(client_if, remote_bda, is_direct); } @@ -67,8 +65,7 @@ void BTA_GATTC_Close(uint16_t conn_id) { gatt_interface->Close(conn_id); } -void BTA_GATTC_ServiceSearchRequest(uint16_t conn_id, - bluetooth::Uuid p_srvc_uuid) { +void BTA_GATTC_ServiceSearchRequest(uint16_t conn_id, bluetooth::Uuid p_srvc_uuid) { log::assert_that(gatt_interface != nullptr, "Mock GATT interface not set!"); gatt_interface->ServiceSearchRequest(conn_id, &p_srvc_uuid); } @@ -88,30 +85,24 @@ const std::list* BTA_GATTC_GetServices(uint16_t conn_id) { return gatt_interface->GetServices(conn_id); } -const gatt::Characteristic* BTA_GATTC_GetCharacteristic(uint16_t conn_id, - uint16_t handle) { +const gatt::Characteristic* BTA_GATTC_GetCharacteristic(uint16_t conn_id, uint16_t handle) { log::assert_that(gatt_interface != nullptr, "Mock GATT interface not set!"); return gatt_interface->GetCharacteristic(conn_id, handle); } -const gatt::Service* BTA_GATTC_GetOwningService(uint16_t conn_id, - uint16_t handle) { +const gatt::Service* BTA_GATTC_GetOwningService(uint16_t conn_id, uint16_t handle) { log::assert_that(gatt_interface != nullptr, "Mock GATT interface not set!"); return gatt_interface->GetOwningService(conn_id, handle); } -tGATT_STATUS BTA_GATTC_RegisterForNotifications(tGATT_IF client_if, - const RawAddress& remote_bda, +tGATT_STATUS BTA_GATTC_RegisterForNotifications(tGATT_IF client_if, const RawAddress& remote_bda, uint16_t handle) { log::assert_that(gatt_interface != nullptr, "Mock GATT interface not set!"); - return gatt_interface->RegisterForNotifications(client_if, remote_bda, - handle); + return gatt_interface->RegisterForNotifications(client_if, remote_bda, handle); } -tGATT_STATUS BTA_GATTC_DeregisterForNotifications(tGATT_IF client_if, - const RawAddress& remote_bda, +tGATT_STATUS BTA_GATTC_DeregisterForNotifications(tGATT_IF client_if, const RawAddress& remote_bda, uint16_t handle) { log::assert_that(gatt_interface != nullptr, "Mock GATT interface not set!"); - return gatt_interface->DeregisterForNotifications(client_if, remote_bda, - handle); + return gatt_interface->DeregisterForNotifications(client_if, remote_bda, handle); } diff --git a/system/bta/test/common/bta_gatt_api_mock.h b/system/bta/test/common/bta_gatt_api_mock.h index f097236f9a1..2a1f2d96692 100644 --- a/system/bta/test/common/bta_gatt_api_mock.h +++ b/system/bta/test/common/bta_gatt_api_mock.h @@ -26,69 +26,54 @@ namespace gatt { class BtaGattInterface { - public: - virtual void AppRegister(tBTA_GATTC_CBACK* p_client_cb, - BtaAppRegisterCallback cb, bool eatt_support) = 0; +public: + virtual void AppRegister(tBTA_GATTC_CBACK* p_client_cb, BtaAppRegisterCallback cb, + bool eatt_support) = 0; virtual void AppDeregister(tGATT_IF client_if) = 0; virtual void Open(tGATT_IF client_if, const RawAddress& remote_bda, - tBTM_BLE_CONN_TYPE connection_type, tBT_TRANSPORT transport, - bool opportunistic, uint8_t initiating_phys) = 0; + tBTM_BLE_CONN_TYPE connection_type, tBT_TRANSPORT transport, bool opportunistic, + uint8_t initiating_phys) = 0; virtual void Open(tGATT_IF client_if, const RawAddress& remote_bda, tBTM_BLE_CONN_TYPE connection_type, bool opportunistic) = 0; - virtual void CancelOpen(tGATT_IF client_if, const RawAddress& remote_bda, - bool is_direct) = 0; + virtual void CancelOpen(tGATT_IF client_if, const RawAddress& remote_bda, bool is_direct) = 0; virtual void Close(uint16_t conn_id) = 0; - virtual void ServiceSearchRequest(uint16_t conn_id, - const bluetooth::Uuid* p_srvc_uuid) = 0; + virtual void ServiceSearchRequest(uint16_t conn_id, const bluetooth::Uuid* p_srvc_uuid) = 0; virtual void SendIndConfirm(uint16_t conn_id, uint16_t cid) = 0; virtual const std::list* GetServices(uint16_t conn_id) = 0; - virtual const Characteristic* GetCharacteristic(uint16_t conn_id, - uint16_t handle) = 0; - virtual const Service* GetOwningService(uint16_t conn_id, - uint16_t handle) = 0; - virtual tGATT_STATUS RegisterForNotifications(tGATT_IF client_if, - const RawAddress& remote_bda, + virtual const Characteristic* GetCharacteristic(uint16_t conn_id, uint16_t handle) = 0; + virtual const Service* GetOwningService(uint16_t conn_id, uint16_t handle) = 0; + virtual tGATT_STATUS RegisterForNotifications(tGATT_IF client_if, const RawAddress& remote_bda, uint16_t handle) = 0; - virtual tGATT_STATUS DeregisterForNotifications(tGATT_IF client_if, - const RawAddress& remote_bda, + virtual tGATT_STATUS DeregisterForNotifications(tGATT_IF client_if, const RawAddress& remote_bda, uint16_t handle) = 0; virtual ~BtaGattInterface() = default; }; class MockBtaGattInterface : public BtaGattInterface { - public: +public: MOCK_METHOD((void), AppRegister, - (tBTA_GATTC_CBACK * p_client_cb, BtaAppRegisterCallback cb, - bool eatt_support), + (tBTA_GATTC_CBACK * p_client_cb, BtaAppRegisterCallback cb, bool eatt_support), (override)); MOCK_METHOD((void), AppDeregister, (tGATT_IF client_if), (override)); MOCK_METHOD((void), Open, - (tGATT_IF client_if, const RawAddress& remote_bda, - tBTM_BLE_CONN_TYPE connection_type, tBT_TRANSPORT transport, - bool opportunistic, uint8_t initiating_phys), + (tGATT_IF client_if, const RawAddress& remote_bda, tBTM_BLE_CONN_TYPE connection_type, + tBT_TRANSPORT transport, bool opportunistic, uint8_t initiating_phys), (override)); MOCK_METHOD((void), Open, - (tGATT_IF client_if, const RawAddress& remote_bda, - tBTM_BLE_CONN_TYPE connection_type, bool opportunistic)); + (tGATT_IF client_if, const RawAddress& remote_bda, tBTM_BLE_CONN_TYPE connection_type, + bool opportunistic)); MOCK_METHOD((void), CancelOpen, - (tGATT_IF client_if, const RawAddress& remote_bda, - bool is_direct)); + (tGATT_IF client_if, const RawAddress& remote_bda, bool is_direct)); MOCK_METHOD((void), Close, (uint16_t conn_id)); - MOCK_METHOD((void), ServiceSearchRequest, - (uint16_t conn_id, const bluetooth::Uuid* p_srvc_uuid)); - MOCK_METHOD((void), SendIndConfirm, (uint16_t conn_id, uint16_t cid), - (override)); + MOCK_METHOD((void), ServiceSearchRequest, (uint16_t conn_id, const bluetooth::Uuid* p_srvc_uuid)); + MOCK_METHOD((void), SendIndConfirm, (uint16_t conn_id, uint16_t cid), (override)); MOCK_METHOD((std::list*), GetServices, (uint16_t conn_id)); - MOCK_METHOD((const Characteristic*), GetCharacteristic, - (uint16_t conn_id, uint16_t handle)); - MOCK_METHOD((const Service*), GetOwningService, - (uint16_t conn_id, uint16_t handle)); + MOCK_METHOD((const Characteristic*), GetCharacteristic, (uint16_t conn_id, uint16_t handle)); + MOCK_METHOD((const Service*), GetOwningService, (uint16_t conn_id, uint16_t handle)); MOCK_METHOD((tGATT_STATUS), RegisterForNotifications, - (tGATT_IF client_if, const RawAddress& remote_bda, - uint16_t handle)); + (tGATT_IF client_if, const RawAddress& remote_bda, uint16_t handle)); MOCK_METHOD((tGATT_STATUS), DeregisterForNotifications, - (tGATT_IF client_if, const RawAddress& remote_bda, - uint16_t handle)); + (tGATT_IF client_if, const RawAddress& remote_bda, uint16_t handle)); }; /** diff --git a/system/bta/test/common/bta_gatt_queue_mock.cc b/system/bta/test/common/bta_gatt_queue_mock.cc index 5dffe0ce869..9704ddffff6 100644 --- a/system/bta/test/common/bta_gatt_queue_mock.cc +++ b/system/bta/test/common/bta_gatt_queue_mock.cc @@ -27,23 +27,20 @@ void gatt::SetMockBtaGattQueue(MockBtaGattQueue* mock_bta_gatt_queue) { void BtaGattQueue::Clean(uint16_t conn_id) { gatt_queue->Clean(conn_id); } -void BtaGattQueue::ReadCharacteristic(uint16_t conn_id, uint16_t handle, - GATT_READ_OP_CB cb, void* cb_data) { +void BtaGattQueue::ReadCharacteristic(uint16_t conn_id, uint16_t handle, GATT_READ_OP_CB cb, + void* cb_data) { gatt_queue->ReadCharacteristic(conn_id, handle, cb, cb_data); } void BtaGattQueue::WriteCharacteristic(uint16_t conn_id, uint16_t handle, - std::vector value, - tGATT_WRITE_TYPE write_type, + std::vector value, tGATT_WRITE_TYPE write_type, GATT_WRITE_OP_CB cb, void* cb_data) { - gatt_queue->WriteCharacteristic(conn_id, handle, value, write_type, cb, - cb_data); + gatt_queue->WriteCharacteristic(conn_id, handle, value, write_type, cb, cb_data); } -void BtaGattQueue::WriteDescriptor(uint16_t conn_id, uint16_t handle, - std::vector value, - tGATT_WRITE_TYPE write_type, - GATT_WRITE_OP_CB cb, void* cb_data) { +void BtaGattQueue::WriteDescriptor(uint16_t conn_id, uint16_t handle, std::vector value, + tGATT_WRITE_TYPE write_type, GATT_WRITE_OP_CB cb, + void* cb_data) { gatt_queue->WriteDescriptor(conn_id, handle, value, write_type, cb, cb_data); } @@ -52,12 +49,9 @@ void BtaGattQueue::ConfigureMtu(uint16_t conn_id, uint16_t mtu) { gatt_queue->ConfigureMtu(conn_id, mtu); } -void BtaGattQueue::ReadMultiCharacteristic(uint16_t conn_id, - tBTA_GATTC_MULTI& p_read_multi, - bool variable_len, - GATT_READ_MULTI_OP_CB cb, +void BtaGattQueue::ReadMultiCharacteristic(uint16_t conn_id, tBTA_GATTC_MULTI& p_read_multi, + bool variable_len, GATT_READ_MULTI_OP_CB cb, void* cb_data) { bluetooth::log::assert_that(gatt_queue, "Mock GATT queue not set!"); - gatt_queue->ReadMultiCharacteristic(conn_id, p_read_multi, variable_len, cb, - cb_data); + gatt_queue->ReadMultiCharacteristic(conn_id, p_read_multi, variable_len, cb, cb_data); } diff --git a/system/bta/test/common/bta_gatt_queue_mock.h b/system/bta/test/common/bta_gatt_queue_mock.h index 8c3d3bd3c1d..5161e3401d2 100644 --- a/system/bta/test/common/bta_gatt_queue_mock.h +++ b/system/bta/test/common/bta_gatt_queue_mock.h @@ -24,23 +24,20 @@ namespace gatt { class MockBtaGattQueue { - public: +public: MOCK_METHOD((void), Clean, (uint16_t conn_id)); MOCK_METHOD((void), ReadCharacteristic, - (uint16_t conn_id, uint16_t handle, GATT_READ_OP_CB cb, - void* cb_data)); + (uint16_t conn_id, uint16_t handle, GATT_READ_OP_CB cb, void* cb_data)); MOCK_METHOD((void), WriteCharacteristic, (uint16_t conn_id, uint16_t handle, std::vector value, - tGATT_WRITE_TYPE write_type, GATT_WRITE_OP_CB cb, - void* cb_data)); + tGATT_WRITE_TYPE write_type, GATT_WRITE_OP_CB cb, void* cb_data)); MOCK_METHOD((void), WriteDescriptor, (uint16_t conn_id, uint16_t handle, std::vector value, - tGATT_WRITE_TYPE write_type, GATT_WRITE_OP_CB cb, - void* cb_data)); + tGATT_WRITE_TYPE write_type, GATT_WRITE_OP_CB cb, void* cb_data)); MOCK_METHOD((void), ConfigureMtu, (uint16_t conn_id, uint16_t mtu)); MOCK_METHOD((void), ReadMultiCharacteristic, - (uint16_t conn_id, tBTA_GATTC_MULTI& p_read_multi, - bool variable_len, GATT_READ_MULTI_OP_CB cb, void* cb_data)); + (uint16_t conn_id, tBTA_GATTC_MULTI& p_read_multi, bool variable_len, + GATT_READ_MULTI_OP_CB cb, void* cb_data)); }; /** diff --git a/system/bta/test/common/btif_storage_mock.cc b/system/bta/test/common/btif_storage_mock.cc index 0045550eb3c..d52b8e6369b 100644 --- a/system/bta/test/common/btif_storage_mock.cc +++ b/system/bta/test/common/btif_storage_mock.cc @@ -21,126 +21,102 @@ using namespace bluetooth; -static bluetooth::storage::MockBtifStorageInterface* btif_storage_interface = - nullptr; +static bluetooth::storage::MockBtifStorageInterface* btif_storage_interface = nullptr; void bluetooth::storage::SetMockBtifStorageInterface( - MockBtifStorageInterface* mock_btif_storage_interface) { + MockBtifStorageInterface* mock_btif_storage_interface) { btif_storage_interface = mock_btif_storage_interface; } -void btif_storage_set_leaudio_autoconnect(RawAddress const& addr, - bool autoconnect) { - log::assert_that(btif_storage_interface != nullptr, - "Mock storage module not set!"); +void btif_storage_set_leaudio_autoconnect(RawAddress const& addr, bool autoconnect) { + log::assert_that(btif_storage_interface != nullptr, "Mock storage module not set!"); btif_storage_interface->AddLeaudioAutoconnect(addr, autoconnect); } void btif_storage_leaudio_update_pacs_bin(const RawAddress& addr) { - log::assert_that(btif_storage_interface != nullptr, - "Mock storage module not set!"); + log::assert_that(btif_storage_interface != nullptr, "Mock storage module not set!"); btif_storage_interface->LeAudioUpdatePacs(addr); } void btif_storage_leaudio_update_ase_bin(const RawAddress& addr) { - log::assert_that(btif_storage_interface != nullptr, - "Mock storage module not set!"); + log::assert_that(btif_storage_interface != nullptr, "Mock storage module not set!"); btif_storage_interface->LeAudioUpdateAses(addr); } void btif_storage_leaudio_update_handles_bin(const RawAddress& addr) { - log::assert_that(btif_storage_interface != nullptr, - "Mock storage module not set!"); + log::assert_that(btif_storage_interface != nullptr, "Mock storage module not set!"); btif_storage_interface->LeAudioUpdateHandles(addr); } -void btif_storage_set_leaudio_audio_location(const RawAddress& addr, - uint32_t sink_location, +void btif_storage_set_leaudio_audio_location(const RawAddress& addr, uint32_t sink_location, uint32_t source_location) { - log::assert_that(btif_storage_interface != nullptr, - "Mock storage module not set!"); - btif_storage_interface->SetLeAudioLocations(addr, sink_location, - source_location); + log::assert_that(btif_storage_interface != nullptr, "Mock storage module not set!"); + btif_storage_interface->SetLeAudioLocations(addr, sink_location, source_location); } -void btif_storage_set_leaudio_supported_context_types( - const RawAddress& addr, uint16_t sink_supported_context_type, - uint16_t source_supported_context_type) { - log::assert_that(btif_storage_interface != nullptr, - "Mock storage module not set!"); +void btif_storage_set_leaudio_supported_context_types(const RawAddress& addr, + uint16_t sink_supported_context_type, + uint16_t source_supported_context_type) { + log::assert_that(btif_storage_interface != nullptr, "Mock storage module not set!"); btif_storage_interface->SetLeAudioContexts(addr, sink_supported_context_type, source_supported_context_type); } void btif_storage_leaudio_clear_service_data(RawAddress const& addr) { - log::assert_that(btif_storage_interface != nullptr, - "Mock storage module not set!"); + log::assert_that(btif_storage_interface != nullptr, "Mock storage module not set!"); btif_storage_interface->ClearLeAudioServiceData(addr); } void btif_storage_remove_leaudio(RawAddress const& addr) { - log::assert_that(btif_storage_interface != nullptr, - "Mock storage module not set!"); + log::assert_that(btif_storage_interface != nullptr, "Mock storage module not set!"); btif_storage_interface->RemoveLeaudio(addr); } void btif_storage_add_leaudio_has_device(const RawAddress& address, - std::vector presets_bin, - uint8_t features, + std::vector presets_bin, uint8_t features, uint8_t active_preset) { - log::assert_that(btif_storage_interface != nullptr, - "Mock storage module not set!"); - btif_storage_interface->AddLeaudioHasDevice(address, presets_bin, features, - active_preset); -}; + log::assert_that(btif_storage_interface != nullptr, "Mock storage module not set!"); + btif_storage_interface->AddLeaudioHasDevice(address, presets_bin, features, active_preset); +} bool btif_storage_get_leaudio_has_presets(const RawAddress& address, std::vector& presets_bin, uint8_t& active_preset) { - if (btif_storage_interface) - return btif_storage_interface->GetLeaudioHasPresets(address, presets_bin, - active_preset); + if (btif_storage_interface) { + return btif_storage_interface->GetLeaudioHasPresets(address, presets_bin, active_preset); + } return false; -}; +} void btif_storage_set_leaudio_has_presets(const RawAddress& address, std::vector presets_bin) { - log::assert_that(btif_storage_interface != nullptr, - "Mock storage module not set!"); + log::assert_that(btif_storage_interface != nullptr, "Mock storage module not set!"); btif_storage_interface->SetLeaudioHasPresets(address, presets_bin); } -bool btif_storage_get_leaudio_has_features(const RawAddress& address, - uint8_t& features) { - log::assert_that(btif_storage_interface != nullptr, - "Mock storage module not set!"); +bool btif_storage_get_leaudio_has_features(const RawAddress& address, uint8_t& features) { + log::assert_that(btif_storage_interface != nullptr, "Mock storage module not set!"); return btif_storage_interface->GetLeaudioHasFeatures(address, features); } -void btif_storage_set_leaudio_has_features(const RawAddress& address, - uint8_t features) { - log::assert_that(btif_storage_interface != nullptr, - "Mock storage module not set!"); +void btif_storage_set_leaudio_has_features(const RawAddress& address, uint8_t features) { + log::assert_that(btif_storage_interface != nullptr, "Mock storage module not set!"); btif_storage_interface->SetLeaudioHasFeatures(address, features); } -void btif_storage_set_leaudio_has_active_preset(const RawAddress& address, - uint8_t active_preset) { - log::assert_that(btif_storage_interface != nullptr, - "Mock storage module not set!"); +void btif_storage_set_leaudio_has_active_preset(const RawAddress& address, uint8_t active_preset) { + log::assert_that(btif_storage_interface != nullptr, "Mock storage module not set!"); btif_storage_interface->SetLeaudioHasActivePreset(address, active_preset); } void btif_storage_remove_leaudio_has(const RawAddress& address) { - log::assert_that(btif_storage_interface != nullptr, - "Mock storage module not set!"); + log::assert_that(btif_storage_interface != nullptr, "Mock storage module not set!"); btif_storage_interface->RemoveLeaudioHas(address); } bt_status_t btif_storage_get_remote_device_property(const RawAddress* address, bt_property_t* property) { - log::assert_that(btif_storage_interface != nullptr, - "Mock storage module not set!"); + log::assert_that(btif_storage_interface != nullptr, "Mock storage module not set!"); return btif_storage_interface->GetRemoteDeviceProperty(address, property); } diff --git a/system/bta/test/common/btif_storage_mock.h b/system/bta/test/common/btif_storage_mock.h index 6b2a020b85b..a715b43b707 100644 --- a/system/bta/test/common/btif_storage_mock.h +++ b/system/bta/test/common/btif_storage_mock.h @@ -25,32 +25,25 @@ namespace bluetooth { namespace storage { class BtifStorageInterface { - public: - virtual void AddLeaudioAutoconnect(RawAddress const& addr, - bool autoconnect) = 0; +public: + virtual void AddLeaudioAutoconnect(RawAddress const& addr, bool autoconnect) = 0; virtual void LeAudioUpdatePacs(RawAddress const& addr) = 0; virtual void LeAudioUpdateAses(RawAddress const& addr) = 0; virtual void LeAudioUpdateHandles(RawAddress const& addr) = 0; - virtual void SetLeAudioLocations(RawAddress const& addr, - uint32_t sink_location, + virtual void SetLeAudioLocations(RawAddress const& addr, uint32_t sink_location, uint32_t source_location) = 0; virtual void SetLeAudioContexts(RawAddress const& addr, uint16_t sink_context, uint16_t source_context) = 0; virtual void ClearLeAudioServiceData(RawAddress const& addr) = 0; virtual void RemoveLeaudio(RawAddress const& addr) = 0; - virtual void AddLeaudioHasDevice(const RawAddress& address, - std::vector presets_bin, + virtual void AddLeaudioHasDevice(const RawAddress& address, std::vector presets_bin, uint8_t features, uint8_t active_preset) = 0; virtual void SetLeaudioHasPresets(const RawAddress& address, std::vector presets_bin) = 0; - virtual bool GetLeaudioHasFeatures(const RawAddress& address, - uint8_t& features) = 0; - virtual void SetLeaudioHasFeatures(const RawAddress& address, - uint8_t features) = 0; - virtual void SetLeaudioHasActivePreset(const RawAddress& address, - uint8_t active_preset) = 0; - virtual bool GetLeaudioHasPresets(const RawAddress& address, - std::vector& presets_bin, + virtual bool GetLeaudioHasFeatures(const RawAddress& address, uint8_t& features) = 0; + virtual void SetLeaudioHasFeatures(const RawAddress& address, uint8_t features) = 0; + virtual void SetLeaudioHasActivePreset(const RawAddress& address, uint8_t active_preset) = 0; + virtual bool GetLeaudioHasPresets(const RawAddress& address, std::vector& presets_bin, uint8_t& active_preset) = 0; virtual void RemoveLeaudioHas(const RawAddress& address) = 0; virtual bt_status_t GetRemoteDeviceProperty(const RawAddress* address, @@ -60,43 +53,36 @@ class BtifStorageInterface { }; class MockBtifStorageInterface : public BtifStorageInterface { - public: - MOCK_METHOD((void), AddLeaudioAutoconnect, - (RawAddress const& addr, bool autoconnect), (override)); +public: + MOCK_METHOD((void), AddLeaudioAutoconnect, (RawAddress const& addr, bool autoconnect), + (override)); MOCK_METHOD((void), LeAudioUpdatePacs, (RawAddress const& addr), (override)); MOCK_METHOD((void), LeAudioUpdateAses, (RawAddress const& addr), (override)); - MOCK_METHOD((void), LeAudioUpdateHandles, (RawAddress const& addr), - (override)); + MOCK_METHOD((void), LeAudioUpdateHandles, (RawAddress const& addr), (override)); MOCK_METHOD((void), SetLeAudioLocations, - (RawAddress const& addr, uint32_t sink_location, - uint32_t source_location), + (RawAddress const& addr, uint32_t sink_location, uint32_t source_location), (override)); MOCK_METHOD((void), SetLeAudioContexts, - (RawAddress const& addr, uint16_t sink_context, - uint16_t source_context), - (override)); - MOCK_METHOD((void), ClearLeAudioServiceData, (RawAddress const& addr), - (override)); + (RawAddress const& addr, uint16_t sink_context, uint16_t source_context), (override)); + MOCK_METHOD((void), ClearLeAudioServiceData, (RawAddress const& addr), (override)); MOCK_METHOD((void), RemoveLeaudio, (RawAddress const& addr), (override)); MOCK_METHOD((void), AddLeaudioHasDevice, - (const RawAddress& address, std::vector presets_bin, - uint8_t features, uint8_t active_preset), + (const RawAddress& address, std::vector presets_bin, uint8_t features, + uint8_t active_preset), (override)); MOCK_METHOD((bool), GetLeaudioHasPresets, (const RawAddress& address, std::vector& presets_bin, uint8_t& active_preset), (override)); MOCK_METHOD((void), SetLeaudioHasPresets, - (const RawAddress& address, std::vector presets_bin), + (const RawAddress& address, std::vector presets_bin), (override)); + MOCK_METHOD((bool), GetLeaudioHasFeatures, (const RawAddress& address, uint8_t& features), + (override)); + MOCK_METHOD((void), SetLeaudioHasFeatures, (const RawAddress& address, uint8_t features), (override)); - MOCK_METHOD((bool), GetLeaudioHasFeatures, - (const RawAddress& address, uint8_t& features), (override)); - MOCK_METHOD((void), SetLeaudioHasFeatures, - (const RawAddress& address, uint8_t features), (override)); - MOCK_METHOD((void), SetLeaudioHasActivePreset, - (const RawAddress& address, uint8_t active_preset), (override)); - MOCK_METHOD((void), RemoveLeaudioHas, (const RawAddress& address), + MOCK_METHOD((void), SetLeaudioHasActivePreset, (const RawAddress& address, uint8_t active_preset), (override)); + MOCK_METHOD((void), RemoveLeaudioHas, (const RawAddress& address), (override)); MOCK_METHOD((bt_status_t), GetRemoteDeviceProperty, (const RawAddress* address, bt_property_t* property), (override)); }; @@ -107,8 +93,7 @@ class MockBtifStorageInterface : public BtifStorageInterface { * @param mock_btif_storage_interface pointer to mock btm security * internal interface, could be null */ -void SetMockBtifStorageInterface( - MockBtifStorageInterface* mock_btif_storage_interface); +void SetMockBtifStorageInterface(MockBtifStorageInterface* mock_btif_storage_interface); } // namespace storage } // namespace bluetooth diff --git a/system/bta/test/common/btm_api_mock.cc b/system/bta/test/common/btm_api_mock.cc index 6b7cd5626f5..dfaa94df0bf 100644 --- a/system/bta/test/common/btm_api_mock.cc +++ b/system/bta/test/common/btm_api_mock.cc @@ -31,8 +31,7 @@ using namespace bluetooth; static bluetooth::manager::MockBtmInterface* btm_interface = nullptr; -void bluetooth::manager::SetMockBtmInterface( - MockBtmInterface* mock_btm_interface) { +void bluetooth::manager::SetMockBtmInterface(MockBtmInterface* mock_btm_interface) { btm_interface = mock_btm_interface; mock_btm_client_interface.peer.BTM_IsPhy2mSupported = [](const RawAddress& remote_bda, tBT_TRANSPORT transport) { @@ -61,12 +60,10 @@ bool BTM_IsEncrypted(const RawAddress& bd_addr, tBT_TRANSPORT transport) { return btm_interface->BTM_IsEncrypted(bd_addr, transport); } -tBTM_STATUS BTM_SetEncryption(const RawAddress& bd_addr, - tBT_TRANSPORT transport, +tBTM_STATUS BTM_SetEncryption(const RawAddress& bd_addr, tBT_TRANSPORT transport, tBTM_SEC_CALLBACK* p_callback, void* p_ref_data, tBTM_BLE_SEC_ACT sec_act) { - return btm_interface->SetEncryption(bd_addr, transport, p_callback, - p_ref_data, sec_act); + return btm_interface->SetEncryption(bd_addr, transport, p_callback, p_ref_data, sec_act); } void BTM_BleSetPhy(const RawAddress& bd_addr, uint8_t tx_phys, uint8_t rx_phys, @@ -85,8 +82,7 @@ tBTM_SEC_DEV_REC* btm_find_dev(const RawAddress& bd_addr) { return btm_interface->FindDevice(bd_addr); } -void acl_disconnect_from_handle(uint16_t handle, tHCI_STATUS reason, - std::string comment) { +void acl_disconnect_from_handle(uint16_t handle, tHCI_STATUS reason, std::string comment) { log::assert_that(btm_interface != nullptr, "Mock btm interface not set!"); return btm_interface->AclDisconnectFromHandle(handle, reason); } @@ -115,14 +111,12 @@ bool BTM_BleIsLinkKeyKnown(const RawAddress address) { return btm_interface->BTM_BleIsLinkKeyKnown(address); } -bool BTM_IsAclConnectionUp(const RawAddress& remote_bda, - tBT_TRANSPORT transport) { +bool BTM_IsAclConnectionUp(const RawAddress& remote_bda, tBT_TRANSPORT transport) { log::assert_that(btm_interface != nullptr, "Mock btm interface not set!"); return btm_interface->BTM_IsAclConnectionUp(remote_bda, transport); } -std::optional BTM_BleGetIdentityAddress( - const RawAddress address) { +std::optional BTM_BleGetIdentityAddress(const RawAddress address) { log::assert_that(btm_interface != nullptr, "Mock btm interface not set!"); return btm_interface->BTM_BleGetIdentityAddress(address); } diff --git a/system/bta/test/common/btm_api_mock.h b/system/bta/test/common/btm_api_mock.h index f1e702a8ae2..2d926473630 100644 --- a/system/bta/test/common/btm_api_mock.h +++ b/system/bta/test/common/btm_api_mock.h @@ -30,98 +30,72 @@ namespace bluetooth { namespace manager { class BtmInterface { - public: - virtual bool GetSecurityFlagsByTransport(const RawAddress& bd_addr, - uint8_t* p_sec_flags, +public: + virtual bool GetSecurityFlagsByTransport(const RawAddress& bd_addr, uint8_t* p_sec_flags, tBT_TRANSPORT transport) = 0; - virtual bool IsLinkKeyKnown(const RawAddress& bd_addr, - tBT_TRANSPORT transport) = 0; - virtual bool BTM_IsEncrypted(const RawAddress& bd_addr, - tBT_TRANSPORT transport) = 0; - virtual tBTM_STATUS SetEncryption(const RawAddress& bd_addr, - tBT_TRANSPORT transport, - tBTM_SEC_CALLBACK* p_callback, - void* p_ref_data, + virtual bool IsLinkKeyKnown(const RawAddress& bd_addr, tBT_TRANSPORT transport) = 0; + virtual bool BTM_IsEncrypted(const RawAddress& bd_addr, tBT_TRANSPORT transport) = 0; + virtual tBTM_STATUS SetEncryption(const RawAddress& bd_addr, tBT_TRANSPORT transport, + tBTM_SEC_CALLBACK* p_callback, void* p_ref_data, tBTM_BLE_SEC_ACT sec_act) = 0; virtual tBTM_SEC_DEV_REC* FindDevice(const RawAddress& bd_addr) = 0; - virtual bool IsPhy2mSupported(const RawAddress& remote_bda, - tBT_TRANSPORT transport) = 0; - virtual uint8_t GetPeerSCA(const RawAddress& remote_bda, - tBT_TRANSPORT transport) = 0; - virtual void BleSetPhy(const RawAddress& bd_addr, uint8_t tx_phys, - uint8_t rx_phys, uint16_t phy_options) = 0; + virtual bool IsPhy2mSupported(const RawAddress& remote_bda, tBT_TRANSPORT transport) = 0; + virtual uint8_t GetPeerSCA(const RawAddress& remote_bda, tBT_TRANSPORT transport) = 0; + virtual void BleSetPhy(const RawAddress& bd_addr, uint8_t tx_phys, uint8_t rx_phys, + uint16_t phy_options) = 0; virtual bool SecIsSecurityPending(const RawAddress& bd_addr) = 0; - virtual void RequestPeerSCA(RawAddress const& bd_addr, - tBT_TRANSPORT transport) = 0; - virtual uint16_t GetHCIConnHandle(RawAddress const& bd_addr, - tBT_TRANSPORT transport) = 0; + virtual void RequestPeerSCA(RawAddress const& bd_addr, tBT_TRANSPORT transport) = 0; + virtual uint16_t GetHCIConnHandle(RawAddress const& bd_addr, tBT_TRANSPORT transport) = 0; virtual void AclDisconnectFromHandle(uint16_t handle, tHCI_STATUS reason) = 0; virtual tBTM_INQ_INFO* BTM_InqDbFirst() = 0; virtual tBTM_INQ_INFO* BTM_InqDbNext(tBTM_INQ_INFO* p_cur) = 0; - virtual std::optional BTM_BleGetPeerLTK( - const RawAddress address) = 0; - virtual std::optional BTM_BleGetPeerIRK( - const RawAddress address) = 0; + virtual std::optional BTM_BleGetPeerLTK(const RawAddress address) = 0; + virtual std::optional BTM_BleGetPeerIRK(const RawAddress address) = 0; virtual bool BTM_BleIsLinkKeyKnown(const RawAddress address) = 0; - virtual std::optional BTM_BleGetIdentityAddress( - const RawAddress address) = 0; - virtual bool BTM_IsAclConnectionUp(const RawAddress& remote_bda, - tBT_TRANSPORT transport) = 0; + virtual std::optional BTM_BleGetIdentityAddress(const RawAddress address) = 0; + virtual bool BTM_IsAclConnectionUp(const RawAddress& remote_bda, tBT_TRANSPORT transport) = 0; virtual ~BtmInterface() = default; }; class MockBtmInterface : public BtmInterface { - public: +public: MOCK_METHOD((bool), GetSecurityFlagsByTransport, - (const RawAddress& bd_addr, uint8_t* p_sec_flags, - tBT_TRANSPORT transport), + (const RawAddress& bd_addr, uint8_t* p_sec_flags, tBT_TRANSPORT transport), (override)); - MOCK_METHOD((bool), IsLinkKeyKnown, - (const RawAddress& bd_addr, tBT_TRANSPORT transport), (override)); - MOCK_METHOD((bool), BTM_IsEncrypted, - (const RawAddress& bd_addr, tBT_TRANSPORT transport), (override)); - MOCK_METHOD((tBTM_STATUS), SetEncryption, - (const RawAddress& bd_addr, tBT_TRANSPORT transport, - tBTM_SEC_CALLBACK* p_callback, void* p_ref_data, - tBTM_BLE_SEC_ACT sec_act), + MOCK_METHOD((bool), IsLinkKeyKnown, (const RawAddress& bd_addr, tBT_TRANSPORT transport), + (override)); + MOCK_METHOD((bool), BTM_IsEncrypted, (const RawAddress& bd_addr, tBT_TRANSPORT transport), (override)); - MOCK_METHOD((tBTM_SEC_DEV_REC*), FindDevice, (const RawAddress& bd_addr), + MOCK_METHOD((tBTM_STATUS), SetEncryption, + (const RawAddress& bd_addr, tBT_TRANSPORT transport, tBTM_SEC_CALLBACK* p_callback, + void* p_ref_data, tBTM_BLE_SEC_ACT sec_act), (override)); - MOCK_METHOD((bool), IsPhy2mSupported, - (const RawAddress& remote_bda, tBT_TRANSPORT transport), + MOCK_METHOD((tBTM_SEC_DEV_REC*), FindDevice, (const RawAddress& bd_addr), (override)); + MOCK_METHOD((bool), IsPhy2mSupported, (const RawAddress& remote_bda, tBT_TRANSPORT transport), (override)); - MOCK_METHOD((uint8_t), GetPeerSCA, - (const RawAddress& remote_bda, tBT_TRANSPORT transport), + MOCK_METHOD((uint8_t), GetPeerSCA, (const RawAddress& remote_bda, tBT_TRANSPORT transport), (override)); MOCK_METHOD((void), BleSetPhy, - (const RawAddress& bd_addr, uint8_t tx_phys, uint8_t rx_phys, - uint16_t phy_options), + (const RawAddress& bd_addr, uint8_t tx_phys, uint8_t rx_phys, uint16_t phy_options), (override)); - MOCK_METHOD((bool), SecIsSecurityPending, (const RawAddress& bd_addr), + MOCK_METHOD((bool), SecIsSecurityPending, (const RawAddress& bd_addr), (override)); + MOCK_METHOD((void), RequestPeerSCA, (RawAddress const& bd_addr, tBT_TRANSPORT transport), (override)); - MOCK_METHOD((void), RequestPeerSCA, - (RawAddress const& bd_addr, tBT_TRANSPORT transport), (override)); - MOCK_METHOD((uint16_t), GetHCIConnHandle, - (RawAddress const& bd_addr, tBT_TRANSPORT transport), (override)); - MOCK_METHOD((void), AclDisconnectFromHandle, - (uint16_t handle, tHCI_STATUS reason), (override)); - MOCK_METHOD((tBTM_INQ_INFO*), BTM_InqDbFirst, (), (override)); - MOCK_METHOD((tBTM_INQ_INFO*), BTM_InqDbNext, (tBTM_INQ_INFO * p_cur), + MOCK_METHOD((uint16_t), GetHCIConnHandle, (RawAddress const& bd_addr, tBT_TRANSPORT transport), (override)); - MOCK_METHOD((std::optional), BTM_BleGetPeerLTK, - (const RawAddress address), (override)); - MOCK_METHOD((std::optional), BTM_BleGetPeerIRK, - (const RawAddress address), (override)); + MOCK_METHOD((void), AclDisconnectFromHandle, (uint16_t handle, tHCI_STATUS reason), (override)); + MOCK_METHOD((tBTM_INQ_INFO*), BTM_InqDbFirst, (), (override)); + MOCK_METHOD((tBTM_INQ_INFO*), BTM_InqDbNext, (tBTM_INQ_INFO * p_cur), (override)); + MOCK_METHOD((std::optional), BTM_BleGetPeerLTK, (const RawAddress address), (override)); + MOCK_METHOD((std::optional), BTM_BleGetPeerIRK, (const RawAddress address), (override)); - MOCK_METHOD((bool), BTM_BleIsLinkKeyKnown, (const RawAddress address), + MOCK_METHOD((bool), BTM_BleIsLinkKeyKnown, (const RawAddress address), (override)); + MOCK_METHOD((std::optional), BTM_BleGetIdentityAddress, (const RawAddress address), (override)); - MOCK_METHOD((std::optional), BTM_BleGetIdentityAddress, - (const RawAddress address), (override)); MOCK_METHOD((bool), BTM_IsAclConnectionUp, - (const RawAddress& remote_bda, tBT_TRANSPORT transport), - (override)); + (const RawAddress& remote_bda, tBT_TRANSPORT transport), (override)); }; /** diff --git a/system/bta/test/common/fake_osi.h b/system/bta/test/common/fake_osi.h index 9056d583e8f..9eceafaa917 100644 --- a/system/bta/test/common/fake_osi.h +++ b/system/bta/test/common/fake_osi.h @@ -17,6 +17,7 @@ #pragma once #include + #include "osi/include/alarm.h" struct fake_osi_alarm_set_on_mloop { diff --git a/system/bta/test/common/mock_csis_client.cc b/system/bta/test/common/mock_csis_client.cc index 3ba83c8aae5..132d29f8e8e 100644 --- a/system/bta/test/common/mock_csis_client.cc +++ b/system/bta/test/common/mock_csis_client.cc @@ -19,12 +19,10 @@ static MockCsisClient* mock_csis_client; -void MockCsisClient::SetMockInstanceForTesting(MockCsisClient* mock) { - mock_csis_client = mock; -} +void MockCsisClient::SetMockInstanceForTesting(MockCsisClient* mock) { mock_csis_client = mock; } -void bluetooth::csis::CsisClient::Initialize( - bluetooth::csis::CsisClientCallbacks* callbacks, base::Closure initCb) { +void bluetooth::csis::CsisClient::Initialize(bluetooth::csis::CsisClientCallbacks* callbacks, + base::Closure initCb) { log::assert_that(mock_csis_client, "Mock CsisClient interface not set!"); mock_csis_client->Initialize(callbacks, initCb); } diff --git a/system/bta/test/common/mock_csis_client.h b/system/bta/test/common/mock_csis_client.h index ec9419211b4..682034ddf14 100644 --- a/system/bta/test/common/mock_csis_client.h +++ b/system/bta/test/common/mock_csis_client.h @@ -21,24 +21,20 @@ #include "bta_csis_api.h" class MockCsisClient : public bluetooth::csis::CsisClient { - public: +public: /* Overrides */ MOCK_METHOD((void), Connect, (const RawAddress& addr), (override)); MOCK_METHOD((void), Disconnect, (const RawAddress& addr), (override)); MOCK_METHOD((void), RemoveDevice, (const RawAddress& address), (override)); - MOCK_METHOD((int), GetGroupId, (const RawAddress& addr, bluetooth::Uuid uuid), - (override)); - MOCK_METHOD((void), LockGroup, - (const int group_id, bool lock, bluetooth::csis::CsisLockCb cb), - (override)); - MOCK_METHOD((std::vector), GetDeviceList, (int group_id), + MOCK_METHOD((int), GetGroupId, (const RawAddress& addr, bluetooth::Uuid uuid), (override)); + MOCK_METHOD((void), LockGroup, (const int group_id, bool lock, bluetooth::csis::CsisLockCb cb), (override)); + MOCK_METHOD((std::vector), GetDeviceList, (int group_id), (override)); MOCK_METHOD((int), GetDesiredSize, (int group_id), (const override)); /* Called from static methods */ MOCK_METHOD((void), Initialize, - (bluetooth::csis::CsisClientCallbacks * callbacks, - base::Closure initCb)); + (bluetooth::csis::CsisClientCallbacks * callbacks, base::Closure initCb)); MOCK_METHOD((void), CleanUp, ()); MOCK_METHOD((void), DebugDump, (int fd)); MOCK_METHOD((bool), IsCsisClientRunning, ()); diff --git a/system/bta/test/common/mock_device_groups.cc b/system/bta/test/common/mock_device_groups.cc index b4357086995..d4dadb7324d 100644 --- a/system/bta/test/common/mock_device_groups.cc +++ b/system/bta/test/common/mock_device_groups.cc @@ -19,24 +19,19 @@ static MockDeviceGroups* mock_groups = nullptr; -void MockDeviceGroups::SetMockInstanceForTesting(MockDeviceGroups* groups) { - mock_groups = groups; -} +void MockDeviceGroups::SetMockInstanceForTesting(MockDeviceGroups* groups) { mock_groups = groups; } -bluetooth::groups::DeviceGroups* bluetooth::groups::DeviceGroups::Get() { - return mock_groups; -} +bluetooth::groups::DeviceGroups* bluetooth::groups::DeviceGroups::Get() { return mock_groups; } void bluetooth::groups::DeviceGroups::Initialize( - bluetooth::groups::DeviceGroupsCallbacks* callbacks) { + bluetooth::groups::DeviceGroupsCallbacks* callbacks) { log::assert_that(mock_groups, "Mock Device Groups not set!"); mock_groups->Initialize(callbacks); -}; +} void bluetooth::groups::DeviceGroups::DebugDump(int) {} -void bluetooth::groups::DeviceGroups::CleanUp( - bluetooth::groups::DeviceGroupsCallbacks* callbacks) { +void bluetooth::groups::DeviceGroups::CleanUp(bluetooth::groups::DeviceGroupsCallbacks* callbacks) { log::assert_that(mock_groups, "Mock Device Groups not set!"); mock_groups->CleanUp(callbacks); } diff --git a/system/bta/test/common/mock_device_groups.h b/system/bta/test/common/mock_device_groups.h index afd2f405b6d..da57d374327 100644 --- a/system/bta/test/common/mock_device_groups.h +++ b/system/bta/test/common/mock_device_groups.h @@ -21,26 +21,19 @@ #include "bta_groups.h" class MockDeviceGroups : public bluetooth::groups::DeviceGroups { - public: +public: /* Overrides */ - MOCK_METHOD((int), AddDevice, - (const RawAddress& addr, bluetooth::Uuid uuid, int group_id), + MOCK_METHOD((int), AddDevice, (const RawAddress& addr, bluetooth::Uuid uuid, int group_id), (override)); - MOCK_METHOD((int), GetGroupId, (const RawAddress& addr, bluetooth::Uuid uuid), - (const override)); - MOCK_METHOD((void), RemoveDevice, (const RawAddress& addr, int group_id), - (override)); - MOCK_METHOD((size_t), GetSerializedSize, (const RawAddress& addr), - (const override)); + MOCK_METHOD((int), GetGroupId, (const RawAddress& addr, bluetooth::Uuid uuid), (const override)); + MOCK_METHOD((void), RemoveDevice, (const RawAddress& addr, int group_id), (override)); + MOCK_METHOD((size_t), GetSerializedSize, (const RawAddress& addr), (const override)); MOCK_METHOD((bool), SerializeDeviceGroups, - (const RawAddress& addr, uint8_t* p_out, size_t buffer_size), - (const override)); + (const RawAddress& addr, uint8_t* p_out, size_t buffer_size), (const override)); /* Called from static methods */ - MOCK_METHOD((void), Initialize, - (bluetooth::groups::DeviceGroupsCallbacks * callbacks)); - MOCK_METHOD((void), CleanUp, - (bluetooth::groups::DeviceGroupsCallbacks * callbacks)); + MOCK_METHOD((void), Initialize, (bluetooth::groups::DeviceGroupsCallbacks * callbacks)); + MOCK_METHOD((void), CleanUp, (bluetooth::groups::DeviceGroupsCallbacks * callbacks)); static void SetMockInstanceForTesting(MockDeviceGroups* machine); }; diff --git a/system/bta/test/gatt/database_builder_sample_device_test.cc b/system/bta/test/gatt/database_builder_sample_device_test.cc index 8c9bf83f81c..9283646feda 100644 --- a/system/bta/test/gatt/database_builder_sample_device_test.cc +++ b/system/bta/test/gatt/database_builder_sample_device_test.cc @@ -31,12 +31,10 @@ namespace gatt { namespace { /* EXPECT_EQ doesn't work well with static constexpr fields, need a variable * with address */ -constexpr std::pair EXPLORE_END = - DatabaseBuilder::EXPLORE_END; +constexpr std::pair EXPLORE_END = DatabaseBuilder::EXPLORE_END; /* make_pair doesn't work well with EXPECT_EQ, have own helper instead */ -inline std::pair make_pair_u16(uint16_t first, - uint16_t second) { +inline std::pair make_pair_u16(uint16_t first, uint16_t second) { return std::make_pair(first, second); } @@ -160,8 +158,7 @@ TEST(DatabaseBuilderSampleDeviceTest, DoDiscovery) { builder.AddCharacteristic(0x000a, 0x000b, SERVICE_3_CHAR_1_UUID, 0x12); - EXPECT_EQ(builder.NextDescriptorRangeToExplore(), - make_pair_u16(0x000c, 0x000c)); + EXPECT_EQ(builder.NextDescriptorRangeToExplore(), make_pair_u16(0x000c, 0x000c)); builder.AddDescriptor(0x000c, SERVICE_3_CHAR_1_DESC_1_UUID); @@ -179,8 +176,7 @@ TEST(DatabaseBuilderSampleDeviceTest, DoDiscovery) { builder.AddCharacteristic(0x0018, 0x0019, SERVICE_4_CHAR_6_UUID, 0x12); // Just last Characteristic have space for descriptor - EXPECT_EQ(builder.NextDescriptorRangeToExplore(), - make_pair_u16(0x001a, 0x001a)); + EXPECT_EQ(builder.NextDescriptorRangeToExplore(), make_pair_u16(0x001a, 0x001a)); builder.AddDescriptor(0x001a, SERVICE_4_CHAR_6_DESC_1_UUID); @@ -209,8 +205,7 @@ TEST(DatabaseBuilderSampleDeviceTest, DoDiscovery) { builder.AddCharacteristic(0x0030, 0x0031, SERVICE_6_CHAR_3_UUID, 0x02); // Just one Characteristic have space for descriptor - EXPECT_EQ(builder.NextDescriptorRangeToExplore(), - make_pair_u16(0x002d, 0x002d)); + EXPECT_EQ(builder.NextDescriptorRangeToExplore(), make_pair_u16(0x002d, 0x002d)); builder.AddDescriptor(0x002d, SERVICE_6_CHAR_1_DESC_1_UUID); @@ -238,8 +233,7 @@ TEST(DatabaseBuilderSampleDeviceTest, DoDiscovery) { service++; EXPECT_EQ(service->uuid, SERVICE_3_UUID); EXPECT_EQ(service->characteristics[0].uuid, SERVICE_3_CHAR_1_UUID); - EXPECT_EQ(service->characteristics[0].descriptors[0].uuid, - SERVICE_3_CHAR_1_DESC_1_UUID); + EXPECT_EQ(service->characteristics[0].descriptors[0].uuid, SERVICE_3_CHAR_1_DESC_1_UUID); service++; EXPECT_EQ(service->uuid, SERVICE_4_UUID); @@ -249,8 +243,7 @@ TEST(DatabaseBuilderSampleDeviceTest, DoDiscovery) { EXPECT_EQ(service->characteristics[3].uuid, SERVICE_4_CHAR_4_UUID); EXPECT_EQ(service->characteristics[4].uuid, SERVICE_4_CHAR_5_UUID); EXPECT_EQ(service->characteristics[5].uuid, SERVICE_4_CHAR_6_UUID); - EXPECT_EQ(service->characteristics[5].descriptors[0].uuid, - SERVICE_4_CHAR_6_DESC_1_UUID); + EXPECT_EQ(service->characteristics[5].descriptors[0].uuid, SERVICE_4_CHAR_6_DESC_1_UUID); service++; EXPECT_EQ(service->uuid, SERVICE_5_UUID); @@ -265,8 +258,7 @@ TEST(DatabaseBuilderSampleDeviceTest, DoDiscovery) { service++; EXPECT_EQ(service->uuid, SERVICE_6_UUID); EXPECT_EQ(service->characteristics[0].uuid, SERVICE_6_CHAR_1_UUID); - EXPECT_EQ(service->characteristics[0].descriptors[0].uuid, - SERVICE_6_CHAR_1_DESC_1_UUID); + EXPECT_EQ(service->characteristics[0].descriptors[0].uuid, SERVICE_6_CHAR_1_DESC_1_UUID); EXPECT_EQ(service->characteristics[1].uuid, SERVICE_6_CHAR_2_UUID); EXPECT_EQ(service->characteristics[2].uuid, SERVICE_6_CHAR_3_UUID); } diff --git a/system/bta/test/gatt/database_builder_test.cc b/system/bta/test/gatt/database_builder_test.cc index 660ebda2714..94247a74f5d 100644 --- a/system/bta/test/gatt/database_builder_test.cc +++ b/system/bta/test/gatt/database_builder_test.cc @@ -31,8 +31,7 @@ namespace gatt { namespace { /* make_pair doesn't work well with ASSERT_EQ, have own helper instead */ -inline std::pair make_pair_u16(uint16_t first, - uint16_t second) { +inline std::pair make_pair_u16(uint16_t first, uint16_t second) { return std::make_pair(first, second); } @@ -41,10 +40,8 @@ Uuid SERVICE_2_UUID = Uuid::FromString("00001801-0000-1000-8000-00805f9b34fb"); Uuid SERVICE_3_UUID = Uuid::FromString("0000180f-0000-1000-8000-00805f9b34fb"); Uuid SERVICE_4_UUID = Uuid::FromString("0000fef5-0000-1000-8000-00805f9b34fb"); Uuid SERVICE_5_UUID = Uuid::FromString("0000180a-0000-1000-8000-00805f9b34fb"); -Uuid SERVICE_1_CHAR_1_UUID = - Uuid::FromString("00002a00-0000-1000-8000-00805f9b34fb"); -Uuid SERVICE_1_CHAR_1_DESC_1_UUID = - Uuid::FromString("00002902-0000-1000-8000-00805f9b34fb"); +Uuid SERVICE_1_CHAR_1_UUID = Uuid::FromString("00002a00-0000-1000-8000-00805f9b34fb"); +Uuid SERVICE_1_CHAR_1_DESC_1_UUID = Uuid::FromString("00002902-0000-1000-8000-00805f9b34fb"); } // namespace @@ -93,8 +90,7 @@ TEST(DatabaseBuilderTest, DescriptorAddTest) { ASSERT_EQ(service->characteristics[0].value_handle, 0x0003); ASSERT_EQ(service->characteristics[0].properties, 0x02); - ASSERT_EQ(service->characteristics[0].descriptors[0].uuid, - SERVICE_1_CHAR_1_DESC_1_UUID); + ASSERT_EQ(service->characteristics[0].descriptors[0].uuid, SERVICE_1_CHAR_1_DESC_1_UUID); ASSERT_EQ(service->characteristics[0].descriptors[0].handle, 0x0004); } diff --git a/system/bta/test/gatt/database_test.cc b/system/bta/test/gatt/database_test.cc index 09d7d9b9aaf..e6f6075d10b 100644 --- a/system/bta/test/gatt/database_test.cc +++ b/system/bta/test/gatt/database_test.cc @@ -36,8 +36,7 @@ const Uuid PRIMARY_SERVICE = Uuid::From16Bit(GATT_UUID_PRI_SERVICE); const Uuid SECONDARY_SERVICE = Uuid::From16Bit(GATT_UUID_SEC_SERVICE); const Uuid INCLUDE = Uuid::From16Bit(GATT_UUID_INCLUDE_SERVICE); const Uuid CHARACTERISTIC = Uuid::From16Bit(GATT_UUID_CHAR_DECLARE); -const Uuid CHARACTERISTIC_EXTENDED_PROPERTIES = - Uuid::From16Bit(GATT_UUID_CHAR_EXT_PROP); +const Uuid CHARACTERISTIC_EXTENDED_PROPERTIES = Uuid::From16Bit(GATT_UUID_CHAR_EXT_PROP); Uuid SERVICE_1_UUID = Uuid::FromString("1800"); Uuid SERVICE_2_UUID = Uuid::FromString("1801"); @@ -107,10 +106,9 @@ TEST(GattCacheTest, stored_attribute_to_binary_service_test) { memset(&attr, 0, sizeof(attr)); attr = { - .handle = 0x0001, - .type = PRIMARY_SERVICE, - .value = {.service = {.uuid = Uuid::FromString("1800"), - .end_handle = 0x001c}}, + .handle = 0x0001, + .type = PRIMARY_SERVICE, + .value = {.service = {.uuid = Uuid::FromString("1800"), .end_handle = 0x001c}}, }; constexpr size_t len = sizeof(StoredAttribute); @@ -140,14 +138,14 @@ TEST(GattCacheTest, stored_attribute_to_binary_included_service_test) { memset(&attr, 0, sizeof(attr)); attr = { - .handle = 0x0001, - .type = INCLUDE, - .value = {.included_service = - { - .handle = 0x0010, - .end_handle = 0x001f, - .uuid = Uuid::FromString("1801"), - }}, + .handle = 0x0001, + .type = INCLUDE, + .value = {.included_service = + { + .handle = 0x0010, + .end_handle = 0x001f, + .uuid = Uuid::FromString("1801"), + }}, }; constexpr size_t len = sizeof(StoredAttribute); @@ -174,11 +172,11 @@ TEST(GattCacheTest, stored_attribute_to_binary_characteristic_test) { memset(&attr, 0, sizeof(attr)); attr = { - .handle = 0x0002, - .type = CHARACTERISTIC, - .value = {.characteristic = {.properties = 0x02, - .value_handle = 0x0003, - .uuid = Uuid::FromString("2a00")}}, + .handle = 0x0002, + .type = CHARACTERISTIC, + .value = {.characteristic = {.properties = 0x02, + .value_handle = 0x0003, + .uuid = Uuid::FromString("2a00")}}, }; constexpr size_t len = sizeof(StoredAttribute); @@ -266,8 +264,7 @@ TEST(GattDatabaseTest, hash_test) { /* This test makes sure that Descriptor represented in StoredAttribute have * proper binary format. */ -TEST(GattCacheTest, - stored_attribute_to_binary_characteristic_extended_properties_test) { +TEST(GattCacheTest, stored_attribute_to_binary_characteristic_extended_properties_test) { StoredAttribute attr; /* make sure padding at end of union is cleared */ @@ -300,9 +297,7 @@ TEST(GattCacheTest, /* This test makes sure that Descriptor represented in StoredAttribute have * proper binary format. */ -TEST( - GattCacheTest, - stored_attribute_serialized_to_binary_characteristic_extended_properties_test) { +TEST(GattCacheTest, stored_attribute_serialized_to_binary_characteristic_extended_properties_test) { StoredAttribute attr; attr = {.handle = 0x0003, @@ -343,14 +338,13 @@ TEST(GattCacheTest, stored_attributes_serialized_to_binary_test) { log::error("{}", base::HexEncode(&attr, StoredAttribute::kSizeOnDisk)); */ - memcpy( - attr_bytes, - "\x03\x00" // handle - "\x00\x00\x29\x00\x00\x00\x10\x00\x80\x00\x00\x80\x5F\x9B\x34\xFB" // Uuid - "\x34\x12" /* extended property */ - "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" - "\x00", - StoredAttribute::kSizeOnDisk); + memcpy(attr_bytes, + "\x03\x00" // handle + "\x00\x00\x29\x00\x00\x00\x10\x00\x80\x00\x00\x80\x5F\x9B\x34\xFB" // Uuid + "\x34\x12" // extended property + "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" + "\x00", + StoredAttribute::kSizeOnDisk); attr = *(StoredAttribute*)attr_bytes; std::vector serialized; @@ -374,14 +368,13 @@ TEST(GattCacheTest, stored_attributes_serialized_to_binary_test) { }; log::error("{}", base::HexEncode(&attr, StoredAttribute::kSizeOnDisk)); */ - memcpy( - attr_bytes, - "\x03\x02" // handle - "\x00\x00\x28\x00\x00\x00\x10\x00\x80\x00\x00\x80\x5F\x9B\x34\xFB" // Type - "\x00\x00\x42\x03\x00\x00\x10\x00\x80\x00\x00\x80\x5F\x9B\x34\xFB" // Uuid - "\x03\x12" // end_handle - "\x00\x00", - StoredAttribute::kSizeOnDisk); + memcpy(attr_bytes, + "\x03\x02" // handle + "\x00\x00\x28\x00\x00\x00\x10\x00\x80\x00\x00\x80\x5F\x9B\x34\xFB" // Type + "\x00\x00\x42\x03\x00\x00\x10\x00\x80\x00\x00\x80\x5F\x9B\x34\xFB" // Uuid + "\x03\x12" // end_handle + "\x00\x00", + StoredAttribute::kSizeOnDisk); attr = *(StoredAttribute*)attr_bytes; StoredAttribute::SerializeStoredAttribute(attr, serialized); @@ -404,14 +397,13 @@ TEST(GattCacheTest, stored_attributes_serialized_to_binary_test) { log::error("{}", base::HexEncode(&attr, StoredAttribute::kSizeOnDisk)); */ - memcpy( - attr_bytes, - "\x04\x03" // handle - "\x00\x00\x28\x01\x00\x00\x10\x00\x80\x00\x00\x80\x5F\x9B\x34\xFB" // type - "\x00\x00\x43\x03\x00\x00\x10\x00\x80\x00\x00\x80\x5F\x9B\x34\xFB" // UUID - "\x03\x12" // end_handle - "\x00\x000", - StoredAttribute::kSizeOnDisk); + memcpy(attr_bytes, + "\x04\x03" // handle + "\x00\x00\x28\x01\x00\x00\x10\x00\x80\x00\x00\x80\x5F\x9B\x34\xFB" // type + "\x00\x00\x43\x03\x00\x00\x10\x00\x80\x00\x00\x80\x5F\x9B\x34\xFB" // UUID + "\x03\x12" // end_handle + "\x00\x000", + StoredAttribute::kSizeOnDisk); attr = *(StoredAttribute*)attr_bytes; StoredAttribute::SerializeStoredAttribute(attr, serialized); @@ -435,14 +427,13 @@ TEST(GattCacheTest, stored_attributes_serialized_to_binary_test) { log::error("{}", base::HexEncode(&attr, StoredAttribute::kSizeOnDisk)); */ - memcpy( - attr_bytes, - "\x03\x01" // handle - "\x00\x00\x28\x02\x00\x00\x10\x00\x80\x00\x00\x80\x5F\x9B\x34\xFB" // type - "\x34\x01" // handle - "\x38\x01" // end_handle - "\x00\x00\x34\x56\x00\x00\x10\x00\x80\x00\x00\x80\x5F\x9B\x34\xFB", // Uuid - StoredAttribute::kSizeOnDisk); + memcpy(attr_bytes, + "\x03\x01" // handle + "\x00\x00\x28\x02\x00\x00\x10\x00\x80\x00\x00\x80\x5F\x9B\x34\xFB" // type + "\x34\x01" // handle + "\x38\x01" // end_handle + "\x00\x00\x34\x56\x00\x00\x10\x00\x80\x00\x00\x80\x5F\x9B\x34\xFB", // Uuid + StoredAttribute::kSizeOnDisk); attr = *(StoredAttribute*)attr_bytes; StoredAttribute::SerializeStoredAttribute(attr, serialized); @@ -462,15 +453,14 @@ TEST(GattCacheTest, stored_attributes_serialized_to_binary_test) { }; log::error("{}", base::HexEncode(&attr, StoredAttribute::kSizeOnDisk)); */ - memcpy( - attr_bytes, - "\x03\x01" // handle - "\x00\x00\x28\x03\x00\x00\x10\x00\x80\x00\x00\x80\x5F\x9B\x34\xFB" // type - "\x04" // properties - "\x00" // padding - "\x02\x03" // value_handle - "\x00\x00\x34\x56\x00\x00\x10\x00\x80\x00\x00\x80\x5F\x9B\x34\xFB", // uuid - StoredAttribute::kSizeOnDisk); + memcpy(attr_bytes, + "\x03\x01" // handle + "\x00\x00\x28\x03\x00\x00\x10\x00\x80\x00\x00\x80\x5F\x9B\x34\xFB" // type + "\x04" // properties + "\x00" // padding + "\x02\x03" // value_handle + "\x00\x00\x34\x56\x00\x00\x10\x00\x80\x00\x00\x80\x5F\x9B\x34\xFB", // uuid + StoredAttribute::kSizeOnDisk); attr = *(StoredAttribute*)attr_bytes; StoredAttribute::SerializeStoredAttribute(attr, serialized); @@ -488,13 +478,12 @@ TEST(GattCacheTest, stored_attributes_serialized_to_binary_test) { }; log::error("{}", base::HexEncode(&attr, StoredAttribute::kSizeOnDisk)); */ - memcpy( - attr_bytes, - "\x03\x01" // handle - "\x00\x00\x44\x44\x00\x00\x10\x00\x80\x00\x00\x80\x5F\x9B\x34\xFB" // type - "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" - "\x00\x00", - StoredAttribute::kSizeOnDisk); + memcpy(attr_bytes, + "\x03\x01" // handle + "\x00\x00\x44\x44\x00\x00\x10\x00\x80\x00\x00\x80\x5F\x9B\x34\xFB" // type + "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" + "\x00\x00", + StoredAttribute::kSizeOnDisk); attr = *(StoredAttribute*)attr_bytes; StoredAttribute::SerializeStoredAttribute(attr, serialized); @@ -542,12 +531,10 @@ TEST(GattDatabaseTest, serialized_hash_test) { std::vector attr_from_disk(serialized.size()); std::copy(bytes.cbegin(), bytes.cend(), (uint8_t*)attr_from_disk.data()); bool is_successful = false; - Database db_from_disk = - gatt::Database::Deserialize(attr_from_disk, &is_successful); + Database db_from_disk = gatt::Database::Deserialize(attr_from_disk, &is_successful); ASSERT_TRUE(is_successful); is_successful = false; - Database db_from_serialized = - gatt::Database::Deserialize(serialized, &is_successful); + Database db_from_serialized = gatt::Database::Deserialize(serialized, &is_successful); ASSERT_TRUE(is_successful); EXPECT_EQ(db_from_disk.Hash(), db_from_serialized.Hash()); diff --git a/system/bta/vc/device.cc b/system/bta/vc/device.cc index 8294dfc8f31..87d3efa4885 100644 --- a/system/bta/vc/device.cc +++ b/system/bta/vc/device.cc @@ -34,17 +34,17 @@ using namespace bluetooth::vc::internal; void VolumeControlDevice::DeregisterNotifications(tGATT_IF gatt_if) { - if (volume_state_handle != 0) + if (volume_state_handle != 0) { BTA_GATTC_DeregisterForNotifications(gatt_if, address, volume_state_handle); + } - if (volume_flags_handle != 0) + if (volume_flags_handle != 0) { BTA_GATTC_DeregisterForNotifications(gatt_if, address, volume_flags_handle); + } for (const VolumeOffset& of : audio_offsets.volume_offsets) { - BTA_GATTC_DeregisterForNotifications(gatt_if, address, - of.audio_descr_handle); - BTA_GATTC_DeregisterForNotifications(gatt_if, address, - of.audio_location_handle); + BTA_GATTC_DeregisterForNotifications(gatt_if, address, of.audio_descr_handle); + BTA_GATTC_DeregisterForNotifications(gatt_if, address, of.audio_location_handle); BTA_GATTC_DeregisterForNotifications(gatt_if, address, of.state_handle); } } @@ -68,25 +68,24 @@ void VolumeControlDevice::Disconnect(tGATT_IF gatt_if) { * characteristics */ uint16_t VolumeControlDevice::find_ccc_handle(uint16_t chrc_handle) { - const gatt::Characteristic* p_char = - BTA_GATTC_GetCharacteristic(connection_id, chrc_handle); + const gatt::Characteristic* p_char = BTA_GATTC_GetCharacteristic(connection_id, chrc_handle); if (!p_char) { log::warn("no such handle=0x{:x}", chrc_handle); return 0; } for (const gatt::Descriptor& desc : p_char->descriptors) { - if (desc.uuid == Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)) + if (desc.uuid == Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)) { return desc.handle; + } } return 0; } -bool VolumeControlDevice::set_volume_control_service_handles( - const gatt::Service& service) { - uint16_t state_handle = 0, state_ccc_handle = 0, control_point_handle = 0, - flags_handle = 0, flags_ccc_handle = 0; +bool VolumeControlDevice::set_volume_control_service_handles(const gatt::Service& service) { + uint16_t state_handle = 0, state_ccc_handle = 0, control_point_handle = 0, flags_handle = 0, + flags_ccc_handle = 0; for (const gatt::Characteristic& chrc : service.characteristics) { if (chrc.uuid == kVolumeControlStateUuid) { @@ -103,10 +102,8 @@ bool VolumeControlDevice::set_volume_control_service_handles( } // Validate service handles - if (GATT_HANDLE_IS_VALID(state_handle) && - GATT_HANDLE_IS_VALID(state_ccc_handle) && - GATT_HANDLE_IS_VALID(control_point_handle) && - GATT_HANDLE_IS_VALID(flags_handle) + if (GATT_HANDLE_IS_VALID(state_handle) && GATT_HANDLE_IS_VALID(state_ccc_handle) && + GATT_HANDLE_IS_VALID(control_point_handle) && GATT_HANDLE_IS_VALID(flags_handle) /* volume_flags_ccc_handle is optional */) { volume_state_handle = state_handle; volume_state_ccc_handle = state_ccc_handle; @@ -119,8 +116,7 @@ bool VolumeControlDevice::set_volume_control_service_handles( return false; } -void VolumeControlDevice::set_volume_offset_control_service_handles( - const gatt::Service& service) { +void VolumeControlDevice::set_volume_offset_control_service_handles(const gatt::Service& service) { VolumeOffset offset = VolumeOffset(service.handle); for (const gatt::Characteristic& chrc : service.characteristics) { @@ -131,8 +127,7 @@ void VolumeControlDevice::set_volume_offset_control_service_handles( } else if (chrc.uuid == kVolumeOffsetLocationUuid) { offset.audio_location_handle = chrc.value_handle; offset.audio_location_ccc_handle = find_ccc_handle(chrc.value_handle); - offset.audio_location_writable = - chrc.properties & GATT_CHAR_PROP_BIT_WRITE_NR; + offset.audio_location_writable = chrc.properties & GATT_CHAR_PROP_BIT_WRITE_NR; } else if (chrc.uuid == kVolumeOffsetControlPointUuid) { offset.control_point_handle = chrc.value_handle; @@ -140,8 +135,7 @@ void VolumeControlDevice::set_volume_offset_control_service_handles( } else if (chrc.uuid == kVolumeOffsetOutputDescriptionUuid) { offset.audio_descr_handle = chrc.value_handle; offset.audio_descr_ccc_handle = find_ccc_handle(chrc.value_handle); - offset.audio_descr_writable = - chrc.properties & GATT_CHAR_PROP_BIT_WRITE_NR; + offset.audio_descr_writable = chrc.properties & GATT_CHAR_PROP_BIT_WRITE_NR; } else { log::warn("unknown characteristic={}", chrc.uuid); @@ -149,8 +143,7 @@ void VolumeControlDevice::set_volume_offset_control_service_handles( } // Check if all mandatory attributes are present - if (GATT_HANDLE_IS_VALID(offset.state_handle) && - GATT_HANDLE_IS_VALID(offset.state_ccc_handle) && + if (GATT_HANDLE_IS_VALID(offset.state_handle) && GATT_HANDLE_IS_VALID(offset.state_ccc_handle) && GATT_HANDLE_IS_VALID(offset.audio_location_handle) && /* audio_location_ccc_handle is optional */ GATT_HANDLE_IS_VALID(offset.control_point_handle) && @@ -167,8 +160,7 @@ bool VolumeControlDevice::UpdateHandles(void) { ResetHandles(); bool vcs_found = false; - const std::list* services = - BTA_GATTC_GetServices(connection_id); + const std::list* services = BTA_GATTC_GetServices(connection_id); if (services == nullptr) { log::error("No services found"); return false; @@ -178,13 +170,17 @@ bool VolumeControlDevice::UpdateHandles(void) { if (service.uuid == kVolumeControlUuid) { log::info("Found VCS, handle=0x{:x}", service.handle); vcs_found = set_volume_control_service_handles(service); - if (!vcs_found) break; + if (!vcs_found) { + break; + } known_service_handles_ = true; for (auto const& included : service.included_services) { const gatt::Service* service = - BTA_GATTC_GetOwningService(connection_id, included.start_handle); - if (service == nullptr) continue; + BTA_GATTC_GetOwningService(connection_id, included.start_handle); + if (service == nullptr) { + continue; + } if (included.uuid == kVolumeOffsetUuid) { log::info("Found VOCS, handle=0x{:x}", service->handle); @@ -213,27 +209,25 @@ void VolumeControlDevice::ResetHandles(void) { volume_flags_handle = 0; volume_flags_ccc_handle = 0; - if (audio_offsets.Size() != 0) audio_offsets.Clear(); + if (audio_offsets.Size() != 0) { + audio_offsets.Clear(); + } } -void VolumeControlDevice::ControlPointOperation(uint8_t opcode, - const std::vector* arg, - GATT_WRITE_OP_CB cb, - void* cb_data) { +void VolumeControlDevice::ControlPointOperation(uint8_t opcode, const std::vector* arg, + GATT_WRITE_OP_CB cb, void* cb_data) { std::vector set_value({opcode, change_counter}); - if (arg != nullptr) + if (arg != nullptr) { set_value.insert(set_value.end(), (*arg).begin(), (*arg).end()); + } - BtaGattQueue::WriteCharacteristic(connection_id, volume_control_point_handle, - set_value, GATT_WRITE, cb, cb_data); + BtaGattQueue::WriteCharacteristic(connection_id, volume_control_point_handle, set_value, + GATT_WRITE, cb, cb_data); } -bool VolumeControlDevice::subscribe_for_notifications(tGATT_IF gatt_if, - uint16_t handle, - uint16_t ccc_handle, - GATT_WRITE_OP_CB cb) { - tGATT_STATUS status = - BTA_GATTC_RegisterForNotifications(gatt_if, address, handle); +bool VolumeControlDevice::subscribe_for_notifications(tGATT_IF gatt_if, uint16_t handle, + uint16_t ccc_handle, GATT_WRITE_OP_CB cb) { + tGATT_STATUS status = BTA_GATTC_RegisterForNotifications(gatt_if, address, handle); if (status != GATT_SUCCESS) { log::error("failed, status=0x{:x}", status); return false; @@ -242,8 +236,8 @@ bool VolumeControlDevice::subscribe_for_notifications(tGATT_IF gatt_if, std::vector value(2); uint8_t* ptr = value.data(); UINT16_TO_STREAM(ptr, GATT_CHAR_CLIENT_CONFIG_NOTIFICATION); - BtaGattQueue::WriteDescriptor(connection_id, ccc_handle, std::move(value), - GATT_WRITE, cb, nullptr); + BtaGattQueue::WriteDescriptor(connection_id, ccc_handle, std::move(value), GATT_WRITE, cb, + nullptr); return true; } @@ -256,31 +250,28 @@ bool VolumeControlDevice::subscribe_for_notifications(tGATT_IF gatt_if, * and reported as connected. In each case we subscribe first to be sure we do * not miss any value change. */ -bool VolumeControlDevice::EnqueueInitialRequests( - tGATT_IF gatt_if, GATT_READ_OP_CB chrc_read_cb, - GATT_WRITE_OP_CB cccd_write_cb) { +bool VolumeControlDevice::EnqueueInitialRequests(tGATT_IF gatt_if, GATT_READ_OP_CB chrc_read_cb, + GATT_WRITE_OP_CB cccd_write_cb) { handles_pending.clear(); handles_pending.insert(volume_state_handle); handles_pending.insert(volume_state_ccc_handle); - if (!subscribe_for_notifications(gatt_if, volume_state_handle, - volume_state_ccc_handle, cccd_write_cb)) { + if (!subscribe_for_notifications(gatt_if, volume_state_handle, volume_state_ccc_handle, + cccd_write_cb)) { return false; } for (auto const& offset : audio_offsets.volume_offsets) { handles_pending.insert(offset.state_handle); handles_pending.insert(offset.state_ccc_handle); - if (!subscribe_for_notifications(gatt_if, offset.state_handle, - offset.state_ccc_handle, cccd_write_cb)) { + if (!subscribe_for_notifications(gatt_if, offset.state_handle, offset.state_ccc_handle, + cccd_write_cb)) { return false; } - BtaGattQueue::ReadCharacteristic(connection_id, offset.state_handle, - chrc_read_cb, nullptr); + BtaGattQueue::ReadCharacteristic(connection_id, offset.state_handle, chrc_read_cb, nullptr); } - BtaGattQueue::ReadCharacteristic(connection_id, volume_state_handle, - chrc_read_cb, nullptr); + BtaGattQueue::ReadCharacteristic(connection_id, volume_state_handle, chrc_read_cb, nullptr); return true; } @@ -291,27 +282,23 @@ bool VolumeControlDevice::EnqueueInitialRequests( * This includes characteristics read and subscription. * In each case we subscribe first to be sure we do not miss any value change. */ -void VolumeControlDevice::EnqueueRemainingRequests( - tGATT_IF gatt_if, GATT_READ_OP_CB chrc_read_cb, - GATT_WRITE_OP_CB cccd_write_cb) { +void VolumeControlDevice::EnqueueRemainingRequests(tGATT_IF gatt_if, GATT_READ_OP_CB chrc_read_cb, + GATT_WRITE_OP_CB cccd_write_cb) { std::map handle_pairs{ - {volume_flags_handle, volume_flags_ccc_handle}, + {volume_flags_handle, volume_flags_ccc_handle}, }; for (auto const& offset : audio_offsets.volume_offsets) { - handle_pairs[offset.audio_location_handle] = - offset.audio_location_ccc_handle; + handle_pairs[offset.audio_location_handle] = offset.audio_location_ccc_handle; handle_pairs[offset.audio_descr_handle] = offset.audio_descr_ccc_handle; } for (auto const& handles : handle_pairs) { if (GATT_HANDLE_IS_VALID(handles.second)) { - subscribe_for_notifications(gatt_if, handles.first, handles.second, - cccd_write_cb); + subscribe_for_notifications(gatt_if, handles.first, handles.second, cccd_write_cb); } - BtaGattQueue::ReadCharacteristic(connection_id, handles.first, chrc_read_cb, - nullptr); + BtaGattQueue::ReadCharacteristic(connection_id, handles.first, chrc_read_cb, nullptr); } } @@ -321,8 +308,7 @@ bool VolumeControlDevice::VerifyReady(uint16_t handle) { return device_ready; } -void VolumeControlDevice::GetExtAudioOutVolumeOffset(uint8_t ext_output_id, - GATT_READ_OP_CB cb, +void VolumeControlDevice::GetExtAudioOutVolumeOffset(uint8_t ext_output_id, GATT_READ_OP_CB cb, void* cb_data) { VolumeOffset* offset = audio_offsets.FindById(ext_output_id); if (!offset) { @@ -330,12 +316,10 @@ void VolumeControlDevice::GetExtAudioOutVolumeOffset(uint8_t ext_output_id, return; } - BtaGattQueue::ReadCharacteristic(connection_id, offset->state_handle, cb, - cb_data); + BtaGattQueue::ReadCharacteristic(connection_id, offset->state_handle, cb, cb_data); } -void VolumeControlDevice::GetExtAudioOutLocation(uint8_t ext_output_id, - GATT_READ_OP_CB cb, +void VolumeControlDevice::GetExtAudioOutLocation(uint8_t ext_output_id, GATT_READ_OP_CB cb, void* cb_data) { VolumeOffset* offset = audio_offsets.FindById(ext_output_id); if (!offset) { @@ -343,12 +327,10 @@ void VolumeControlDevice::GetExtAudioOutLocation(uint8_t ext_output_id, return; } - BtaGattQueue::ReadCharacteristic(connection_id, offset->audio_location_handle, - cb, cb_data); + BtaGattQueue::ReadCharacteristic(connection_id, offset->audio_location_handle, cb, cb_data); } -void VolumeControlDevice::SetExtAudioOutLocation(uint8_t ext_output_id, - uint32_t location) { +void VolumeControlDevice::SetExtAudioOutLocation(uint8_t ext_output_id, uint32_t location) { VolumeOffset* offset = audio_offsets.FindById(ext_output_id); if (!offset) { log::error("no such offset!"); @@ -363,13 +345,11 @@ void VolumeControlDevice::SetExtAudioOutLocation(uint8_t ext_output_id, std::vector value(4); uint8_t* ptr = value.data(); UINT32_TO_STREAM(ptr, location); - BtaGattQueue::WriteCharacteristic(connection_id, - offset->audio_location_handle, value, + BtaGattQueue::WriteCharacteristic(connection_id, offset->audio_location_handle, value, GATT_WRITE_NO_RSP, nullptr, nullptr); } -void VolumeControlDevice::GetExtAudioOutDescription(uint8_t ext_output_id, - GATT_READ_OP_CB cb, +void VolumeControlDevice::GetExtAudioOutDescription(uint8_t ext_output_id, GATT_READ_OP_CB cb, void* cb_data) { VolumeOffset* offset = audio_offsets.FindById(ext_output_id); if (!offset) { @@ -377,12 +357,10 @@ void VolumeControlDevice::GetExtAudioOutDescription(uint8_t ext_output_id, return; } - BtaGattQueue::ReadCharacteristic(connection_id, offset->audio_descr_handle, - cb, cb_data); + BtaGattQueue::ReadCharacteristic(connection_id, offset->audio_descr_handle, cb, cb_data); } -void VolumeControlDevice::SetExtAudioOutDescription(uint8_t ext_output_id, - std::string& descr) { +void VolumeControlDevice::SetExtAudioOutDescription(uint8_t ext_output_id, std::string& descr) { VolumeOffset* offset = audio_offsets.FindById(ext_output_id); if (!offset) { log::error("no such offset!"); @@ -395,13 +373,13 @@ void VolumeControlDevice::SetExtAudioOutDescription(uint8_t ext_output_id, } std::vector value(descr.begin(), descr.end()); - BtaGattQueue::WriteCharacteristic(connection_id, offset->audio_descr_handle, - value, GATT_WRITE_NO_RSP, nullptr, nullptr); + BtaGattQueue::WriteCharacteristic(connection_id, offset->audio_descr_handle, value, + GATT_WRITE_NO_RSP, nullptr, nullptr); } -void VolumeControlDevice::ExtAudioOutControlPointOperation( - uint8_t ext_output_id, uint8_t opcode, const std::vector* arg, - GATT_WRITE_OP_CB cb, void* cb_data) { +void VolumeControlDevice::ExtAudioOutControlPointOperation(uint8_t ext_output_id, uint8_t opcode, + const std::vector* arg, + GATT_WRITE_OP_CB cb, void* cb_data) { VolumeOffset* offset = audio_offsets.FindById(ext_output_id); if (!offset) { log::error("no such offset!"); @@ -409,11 +387,12 @@ void VolumeControlDevice::ExtAudioOutControlPointOperation( } std::vector set_value({opcode, offset->change_counter}); - if (arg != nullptr) + if (arg != nullptr) { set_value.insert(set_value.end(), (*arg).begin(), (*arg).end()); + } - BtaGattQueue::WriteCharacteristic(connection_id, offset->control_point_handle, - set_value, GATT_WRITE, cb, cb_data); + BtaGattQueue::WriteCharacteristic(connection_id, offset->control_point_handle, set_value, + GATT_WRITE, cb, cb_data); } bool VolumeControlDevice::IsEncryptionEnabled() { @@ -421,8 +400,7 @@ bool VolumeControlDevice::IsEncryptionEnabled() { } bool VolumeControlDevice::EnableEncryption() { - int result = BTM_SetEncryption(address, BT_TRANSPORT_LE, nullptr, nullptr, - BTM_BLE_SEC_ENCRYPT); + int result = BTM_SetEncryption(address, BT_TRANSPORT_LE, nullptr, nullptr, BTM_BLE_SEC_ENCRYPT); log::info("{}: result=0x{:02x}", address, result); return result != BTM_ERR_KEY_MISSING; diff --git a/system/bta/vc/devices.h b/system/bta/vc/devices.h index ddccd0ec661..d1356d3bc03 100644 --- a/system/bta/vc/devices.h +++ b/system/bta/vc/devices.h @@ -33,7 +33,7 @@ namespace vc { namespace internal { class VolumeControlDevice : public bluetooth::common::IRedactableLoggable { - public: +public: RawAddress address; /* We are making active attempt to connect to this device */ @@ -82,9 +82,7 @@ class VolumeControlDevice : public bluetooth::common::IRedactableLoggable { // TODO: remove inline std::string ToString() { return address.ToString(); } - std::string ToStringForLogging() const override { - return address.ToStringForLogging(); - } + std::string ToStringForLogging() const override { return address.ToStringForLogging(); } std::string ToRedactedStringForLogging() const override { return address.ToRedactedStringForLogging(); @@ -92,13 +90,13 @@ class VolumeControlDevice : public bluetooth::common::IRedactableLoggable { void DebugDump(int fd) { std::stringstream stream; - stream << " == device address: " << ADDRESS_TO_LOGGABLE_STR(address) - << " == \n"; + stream << " == device address: " << ADDRESS_TO_LOGGABLE_STR(address) << " == \n"; - if (connection_id == GATT_INVALID_CONN_ID) + if (connection_id == GATT_INVALID_CONN_ID) { stream << " Not connected\n"; - else + } else { stream << " Connected. Conn_id = " << connection_id << "\n"; + } stream << " volume: " << +volume << "\n" << " mute: " << +mute << "\n" @@ -123,19 +121,16 @@ class VolumeControlDevice : public bluetooth::common::IRedactableLoggable { bool HasHandles(void) { return GATT_HANDLE_IS_VALID(volume_state_handle); } - void ControlPointOperation(uint8_t opcode, const std::vector* arg, - GATT_WRITE_OP_CB cb, void* cb_data); - void GetExtAudioOutVolumeOffset(uint8_t ext_output_id, GATT_READ_OP_CB cb, - void* cb_data); + void ControlPointOperation(uint8_t opcode, const std::vector* arg, GATT_WRITE_OP_CB cb, + void* cb_data); + void GetExtAudioOutVolumeOffset(uint8_t ext_output_id, GATT_READ_OP_CB cb, void* cb_data); void SetExtAudioOutLocation(uint8_t ext_output_id, uint32_t location); - void GetExtAudioOutLocation(uint8_t ext_output_id, GATT_READ_OP_CB cb, - void* cb_data); - void GetExtAudioOutDescription(uint8_t ext_output_id, GATT_READ_OP_CB cb, - void* cb_data); + void GetExtAudioOutLocation(uint8_t ext_output_id, GATT_READ_OP_CB cb, void* cb_data); + void GetExtAudioOutDescription(uint8_t ext_output_id, GATT_READ_OP_CB cb, void* cb_data); void SetExtAudioOutDescription(uint8_t ext_output_id, std::string& descr); void ExtAudioOutControlPointOperation(uint8_t ext_output_id, uint8_t opcode, - const std::vector* arg, - GATT_WRITE_OP_CB cb, void* cb_data); + const std::vector* arg, GATT_WRITE_OP_CB cb, + void* cb_data); bool IsEncryptionEnabled(); bool EnableEncryption(); @@ -147,7 +142,7 @@ class VolumeControlDevice : public bluetooth::common::IRedactableLoggable { bool VerifyReady(uint16_t handle); bool IsReady() { return device_ready; } - private: +private: /* * This is used to track the pending GATT operation handles. Once the list is * empty the device is assumed ready and connected. We are doing it because we @@ -159,14 +154,16 @@ class VolumeControlDevice : public bluetooth::common::IRedactableLoggable { uint16_t find_ccc_handle(uint16_t chrc_handle); bool set_volume_control_service_handles(const gatt::Service& service); void set_volume_offset_control_service_handles(const gatt::Service& service); - bool subscribe_for_notifications(tGATT_IF gatt_if, uint16_t handle, - uint16_t ccc_handle, GATT_WRITE_OP_CB cb); + bool subscribe_for_notifications(tGATT_IF gatt_if, uint16_t handle, uint16_t ccc_handle, + GATT_WRITE_OP_CB cb); }; class VolumeControlDevices { - public: +public: void Add(const RawAddress& address, bool connecting_actively) { - if (FindByAddress(address) != nullptr) return; + if (FindByAddress(address) != nullptr) { + return; + } devices_.emplace_back(address, connecting_actively); } @@ -181,25 +178,23 @@ class VolumeControlDevices { } VolumeControlDevice* FindByAddress(const RawAddress& address) { - auto iter = std::find_if(devices_.begin(), devices_.end(), - [&address](const VolumeControlDevice& device) { - return device.address == address; - }); + auto iter = std::find_if( + devices_.begin(), devices_.end(), + [&address](const VolumeControlDevice& device) { return device.address == address; }); return (iter == devices_.end()) ? nullptr : &(*iter); } VolumeControlDevice* FindByConnId(uint16_t connection_id) { - auto iter = - std::find_if(devices_.begin(), devices_.end(), - [&connection_id](const VolumeControlDevice& device) { - return device.connection_id == connection_id; - }); + auto iter = std::find_if(devices_.begin(), devices_.end(), + [&connection_id](const VolumeControlDevice& device) { + return device.connection_id == connection_id; + }); return (iter == devices_.end()) ? nullptr : &(*iter); } - size_t Size() { return (devices_.size()); } + size_t Size() { return devices_.size(); } void Clear() { devices_.clear(); } @@ -221,16 +216,16 @@ class VolumeControlDevices { } void ControlPointOperation(std::vector& devices, uint8_t opcode, - const std::vector* arg, - GATT_WRITE_OP_CB cb, void* cb_data) { + const std::vector* arg, GATT_WRITE_OP_CB cb, void* cb_data) { for (auto& addr : devices) { VolumeControlDevice* device = FindByAddress(addr); - if (device && device->IsConnected()) + if (device && device->IsConnected()) { device->ControlPointOperation(opcode, arg, cb, cb_data); + } } } - private: +private: std::vector devices_; }; diff --git a/system/bta/vc/devices_test.cc b/system/bta/vc/devices_test.cc index 287b83bb42e..09a3f2b5671 100644 --- a/system/bta/vc/devices_test.cc +++ b/system/bta/vc/devices_test.cc @@ -44,13 +44,12 @@ using ::testing::Test; RawAddress GetTestAddress(int index) { EXPECT_LT(index, UINT8_MAX); - RawAddress result = { - {0xC0, 0xDE, 0xC0, 0xDE, 0x00, static_cast(index)}}; + RawAddress result = {{0xC0, 0xDE, 0xC0, 0xDE, 0x00, static_cast(index)}}; return result; } class VolumeControlDevicesTest : public ::testing::Test { - protected: +protected: void SetUp() override { devices_ = new VolumeControlDevices(); gatt::SetMockBtaGattInterface(&gatt_interface); @@ -151,9 +150,8 @@ TEST_F(VolumeControlDevicesTest, test_control_point_operation) { device->volume_control_point_handle = control_point_handle; std::vector data_expected({opcode, change_counter}); - EXPECT_CALL(gatt_queue, - WriteCharacteristic(connection_id, control_point_handle, - data_expected, GATT_WRITE, _, _)); + EXPECT_CALL(gatt_queue, WriteCharacteristic(connection_id, control_point_handle, data_expected, + GATT_WRITE, _, _)); } const std::vector* arg = nullptr; @@ -181,9 +179,8 @@ TEST_F(VolumeControlDevicesTest, test_control_point_operation_args) { device->volume_control_point_handle = control_point_handle; std::vector data_expected({opcode, change_counter, arg_1, arg_2}); - EXPECT_CALL(gatt_queue, - WriteCharacteristic(connection_id, control_point_handle, - data_expected, GATT_WRITE, _, _)); + EXPECT_CALL(gatt_queue, WriteCharacteristic(connection_id, control_point_handle, data_expected, + GATT_WRITE, _, _)); } std::vector arg({arg_1, arg_2}); @@ -200,9 +197,7 @@ TEST_F(VolumeControlDevicesTest, test_control_point_skip_not_connected) { uint16_t control_point_handle = 0x0020; device->volume_control_point_handle = control_point_handle; - EXPECT_CALL(gatt_queue, - WriteCharacteristic(_, control_point_handle, _, _, _, _)) - .Times(0); + EXPECT_CALL(gatt_queue, WriteCharacteristic(_, control_point_handle, _, _, _, _)).Times(0); uint8_t opcode = 5; std::vector devices = {test_address}; @@ -213,7 +208,7 @@ TEST_F(VolumeControlDevicesTest, test_control_point_skip_not_connected) { } class VolumeControlDeviceTest : public ::testing::Test { - protected: +protected: void SetUp() override { device = new VolumeControlDevice(GetTestAddress(1), true); gatt::SetMockBtaGattInterface(&gatt_interface); @@ -221,23 +216,21 @@ class VolumeControlDeviceTest : public ::testing::Test { bluetooth::manager::SetMockBtmInterface(&btm_interface); ON_CALL(gatt_interface, GetCharacteristic(_, _)) - .WillByDefault( - Invoke([&](uint16_t conn_id, - uint16_t handle) -> const gatt::Characteristic* { - for (auto const& service : services) { - for (auto const& characteristic : service.characteristics) { - if (characteristic.value_handle == handle) { - return &characteristic; - } - } - } - - return nullptr; - })); + .WillByDefault( + Invoke([&](uint16_t conn_id, uint16_t handle) -> const gatt::Characteristic* { + for (auto const& service : services) { + for (auto const& characteristic : service.characteristics) { + if (characteristic.value_handle == handle) { + return &characteristic; + } + } + } + + return nullptr; + })); ON_CALL(gatt_interface, GetOwningService(_, _)) - .WillByDefault(Invoke( - [&](uint16_t conn_id, uint16_t handle) -> const gatt::Service* { + .WillByDefault(Invoke([&](uint16_t conn_id, uint16_t handle) -> const gatt::Service* { for (auto const& service : services) { if (service.handle <= handle && service.end_handle >= handle) { return &service; @@ -263,55 +256,38 @@ class VolumeControlDeviceTest : public ::testing::Test { builder.AddService(0x0001, 0x0016, kVolumeControlUuid, true); builder.AddIncludedService(0x0004, kVolumeOffsetUuid, 0x0060, 0x0069); builder.AddIncludedService(0x0005, kVolumeOffsetUuid, 0x0080, 0x008b); - builder.AddCharacteristic( - 0x0010, 0x0011, kVolumeControlStateUuid, - GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY); - builder.AddDescriptor(0x0012, - Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); - builder.AddCharacteristic(0x0013, 0x0014, kVolumeControlPointUuid, - GATT_CHAR_PROP_BIT_WRITE); - builder.AddCharacteristic(0x0015, 0x0016, kVolumeFlagsUuid, - GATT_CHAR_PROP_BIT_READ); + builder.AddCharacteristic(0x0010, 0x0011, kVolumeControlStateUuid, + GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY); + builder.AddDescriptor(0x0012, Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); + builder.AddCharacteristic(0x0013, 0x0014, kVolumeControlPointUuid, GATT_CHAR_PROP_BIT_WRITE); + builder.AddCharacteristic(0x0015, 0x0016, kVolumeFlagsUuid, GATT_CHAR_PROP_BIT_READ); builder.AddService(0x0060, 0x0069, kVolumeOffsetUuid, false); - builder.AddCharacteristic( - 0x0061, 0x0062, kVolumeOffsetStateUuid, - GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY); - builder.AddDescriptor(0x0063, - Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); - builder.AddCharacteristic(0x0064, 0x0065, kVolumeOffsetLocationUuid, - GATT_CHAR_PROP_BIT_READ); + builder.AddCharacteristic(0x0061, 0x0062, kVolumeOffsetStateUuid, + GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY); + builder.AddDescriptor(0x0063, Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); + builder.AddCharacteristic(0x0064, 0x0065, kVolumeOffsetLocationUuid, GATT_CHAR_PROP_BIT_READ); builder.AddCharacteristic(0x0066, 0x0067, kVolumeOffsetControlPointUuid, GATT_CHAR_PROP_BIT_WRITE); - builder.AddCharacteristic(0x0068, 0x0069, - kVolumeOffsetOutputDescriptionUuid, + builder.AddCharacteristic(0x0068, 0x0069, kVolumeOffsetOutputDescriptionUuid, GATT_CHAR_PROP_BIT_READ); builder.AddService(0x0080, 0x008b, kVolumeOffsetUuid, false); + builder.AddCharacteristic(0x0081, 0x0082, kVolumeOffsetStateUuid, + GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY); + builder.AddDescriptor(0x0083, Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); builder.AddCharacteristic( - 0x0081, 0x0082, kVolumeOffsetStateUuid, - GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY); - builder.AddDescriptor(0x0083, - Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); - builder.AddCharacteristic(0x0084, 0x0085, kVolumeOffsetLocationUuid, - GATT_CHAR_PROP_BIT_READ | - GATT_CHAR_PROP_BIT_WRITE_NR | - GATT_CHAR_PROP_BIT_NOTIFY); - builder.AddDescriptor(0x0086, - Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); + 0x0084, 0x0085, kVolumeOffsetLocationUuid, + GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_WRITE_NR | GATT_CHAR_PROP_BIT_NOTIFY); + builder.AddDescriptor(0x0086, Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); builder.AddCharacteristic(0x0087, 0x0088, kVolumeOffsetControlPointUuid, GATT_CHAR_PROP_BIT_WRITE); builder.AddCharacteristic( - 0x0089, 0x008a, kVolumeOffsetOutputDescriptionUuid, - GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_WRITE_NR | - GATT_CHAR_PROP_BIT_NOTIFY); - builder.AddDescriptor(0x008b, - Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); - builder.AddService(0x00a0, 0x00a3, - Uuid::From16Bit(UUID_SERVCLASS_GATT_SERVER), true); - builder.AddCharacteristic(0x00a1, 0x00a2, - Uuid::From16Bit(GATT_UUID_GATT_SRV_CHGD), + 0x0089, 0x008a, kVolumeOffsetOutputDescriptionUuid, + GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_WRITE_NR | GATT_CHAR_PROP_BIT_NOTIFY); + builder.AddDescriptor(0x008b, Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); + builder.AddService(0x00a0, 0x00a3, Uuid::From16Bit(UUID_SERVCLASS_GATT_SERVER), true); + builder.AddCharacteristic(0x00a1, 0x00a2, Uuid::From16Bit(GATT_UUID_GATT_SRV_CHGD), GATT_CHAR_PROP_BIT_NOTIFY); - builder.AddDescriptor(0x00a3, - Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); + builder.AddDescriptor(0x00a3, Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); services = builder.Build().Services(); ASSERT_EQ(true, device->UpdateHandles()); } @@ -320,8 +296,7 @@ class VolumeControlDeviceTest : public ::testing::Test { void SetSampleDatabase2(void) { gatt::DatabaseBuilder builder; builder.AddService(0x0001, 0x0003, Uuid::From16Bit(0x1800), true); - builder.AddCharacteristic(0x0002, 0x0003, Uuid::From16Bit(0x2a00), - GATT_CHAR_PROP_BIT_READ); + builder.AddCharacteristic(0x0002, 0x0003, Uuid::From16Bit(0x2a00), GATT_CHAR_PROP_BIT_READ); services = builder.Build().Services(); ASSERT_EQ(false, device->UpdateHandles()); } @@ -341,12 +316,10 @@ TEST_F(VolumeControlDeviceTest, test_service_volume_control_not_found) { TEST_F(VolumeControlDeviceTest, test_service_volume_control_incomplete) { gatt::DatabaseBuilder builder; builder.AddService(0x0001, 0x0006, kVolumeControlUuid, true); - builder.AddCharacteristic( - 0x0002, 0x0003, kVolumeControlStateUuid, - GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY); + builder.AddCharacteristic(0x0002, 0x0003, kVolumeControlStateUuid, + GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY); builder.AddDescriptor(0x0004, Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); - builder.AddCharacteristic(0x0005, 0x0006, kVolumeControlPointUuid, - GATT_CHAR_PROP_BIT_WRITE); + builder.AddCharacteristic(0x0005, 0x0006, kVolumeControlPointUuid, GATT_CHAR_PROP_BIT_WRITE); /* no Volume Control Flags characteristic */ services = builder.Build().Services(); ASSERT_EQ(false, device->UpdateHandles()); @@ -362,24 +335,19 @@ TEST_F(VolumeControlDeviceTest, test_service_vocs_incomplete) { gatt::DatabaseBuilder builder; builder.AddService(0x0001, 0x000a, kVolumeControlUuid, true); builder.AddIncludedService(0x0002, kVolumeOffsetUuid, 0x000b, 0x0013); - builder.AddCharacteristic( - 0x0003, 0x0004, kVolumeControlStateUuid, - GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY); + builder.AddCharacteristic(0x0003, 0x0004, kVolumeControlStateUuid, + GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY); builder.AddDescriptor(0x0005, Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); - builder.AddCharacteristic(0x0006, 0x0007, kVolumeControlPointUuid, - GATT_CHAR_PROP_BIT_WRITE); - builder.AddCharacteristic( - 0x0008, 0x0009, kVolumeFlagsUuid, - GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY); + builder.AddCharacteristic(0x0006, 0x0007, kVolumeControlPointUuid, GATT_CHAR_PROP_BIT_WRITE); + builder.AddCharacteristic(0x0008, 0x0009, kVolumeFlagsUuid, + GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY); builder.AddDescriptor(0x000a, Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); builder.AddService(0x000b, 0x0013, kVolumeOffsetUuid, false); - builder.AddCharacteristic( - 0x000c, 0x000d, kVolumeOffsetStateUuid, - GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY); + builder.AddCharacteristic(0x000c, 0x000d, kVolumeOffsetStateUuid, + GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY); builder.AddDescriptor(0x000e, Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); - builder.AddCharacteristic( - 0x000f, 0x0010, kVolumeOffsetLocationUuid, - GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY); + builder.AddCharacteristic(0x000f, 0x0010, kVolumeOffsetLocationUuid, + GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY); builder.AddDescriptor(0x0011, Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); builder.AddCharacteristic(0x0012, 0x0013, kVolumeOffsetControlPointUuid, GATT_CHAR_PROP_BIT_WRITE); @@ -399,24 +367,19 @@ TEST_F(VolumeControlDeviceTest, test_service_vocs_found) { gatt::DatabaseBuilder builder; builder.AddService(0x0001, 0x000a, kVolumeControlUuid, true); builder.AddIncludedService(0x0002, kVolumeOffsetUuid, 0x000b, 0x0015); - builder.AddCharacteristic( - 0x0003, 0x0004, kVolumeControlStateUuid, - GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY); + builder.AddCharacteristic(0x0003, 0x0004, kVolumeControlStateUuid, + GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY); builder.AddDescriptor(0x0005, Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); - builder.AddCharacteristic(0x0006, 0x0007, kVolumeControlPointUuid, - GATT_CHAR_PROP_BIT_WRITE); - builder.AddCharacteristic( - 0x0008, 0x0009, kVolumeFlagsUuid, - GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY); + builder.AddCharacteristic(0x0006, 0x0007, kVolumeControlPointUuid, GATT_CHAR_PROP_BIT_WRITE); + builder.AddCharacteristic(0x0008, 0x0009, kVolumeFlagsUuid, + GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY); builder.AddDescriptor(0x000a, Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); builder.AddService(0x000b, 0x0015, kVolumeOffsetUuid, false); - builder.AddCharacteristic( - 0x000c, 0x000d, kVolumeOffsetStateUuid, - GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY); + builder.AddCharacteristic(0x000c, 0x000d, kVolumeOffsetStateUuid, + GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY); builder.AddDescriptor(0x000e, Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); - builder.AddCharacteristic( - 0x000f, 0x0010, kVolumeOffsetLocationUuid, - GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY); + builder.AddCharacteristic(0x000f, 0x0010, kVolumeOffsetLocationUuid, + GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY); builder.AddDescriptor(0x0011, Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); builder.AddCharacteristic(0x0012, 0x0013, kVolumeOffsetControlPointUuid, GATT_CHAR_PROP_BIT_WRITE); @@ -468,28 +431,23 @@ TEST_F(VolumeControlDeviceTest, test_enqueue_initial_requests) { tGATT_IF gatt_if = 0x0001; std::vector register_for_notification_data({0x01, 0x00}); - std::map expected_to_read_write{ - {0x0011, 0x0012} /* volume control state */, - {0x0062, 0x0063} /* volume offset state 1 */, - {0x0082, 0x0083} /* volume offset state 2 */}; + std::map expected_to_read_write{{0x0011, 0x0012} /* volume control state */, + {0x0062, 0x0063} /* volume offset state 1 */, + {0x0082, 0x0083} /* volume offset state 2 */}; for (auto const& handle_pair : expected_to_read_write) { EXPECT_CALL(gatt_queue, ReadCharacteristic(_, handle_pair.first, _, _)); - EXPECT_CALL(gatt_queue, WriteDescriptor(_, handle_pair.second, - register_for_notification_data, + EXPECT_CALL(gatt_queue, WriteDescriptor(_, handle_pair.second, register_for_notification_data, GATT_WRITE, _, _)); - EXPECT_CALL(gatt_interface, - RegisterForNotifications(gatt_if, _, handle_pair.first)); + EXPECT_CALL(gatt_interface, RegisterForNotifications(gatt_if, _, handle_pair.first)); } - auto chrc_read_cb = [](uint16_t conn_id, tGATT_STATUS status, uint16_t handle, - uint16_t len, uint8_t* value, void* data) {}; - auto cccd_write_cb = [](uint16_t conn_id, tGATT_STATUS status, - uint16_t handle, uint16_t len, const uint8_t* value, - void* data) {}; - ASSERT_EQ(true, device->EnqueueInitialRequests(gatt_if, chrc_read_cb, - cccd_write_cb)); -}; + auto chrc_read_cb = [](uint16_t conn_id, tGATT_STATUS status, uint16_t handle, uint16_t len, + uint8_t* value, void* data) {}; + auto cccd_write_cb = [](uint16_t conn_id, tGATT_STATUS status, uint16_t handle, uint16_t len, + const uint8_t* value, void* data) {}; + ASSERT_EQ(true, device->EnqueueInitialRequests(gatt_if, chrc_read_cb, cccd_write_cb)); +} TEST_F(VolumeControlDeviceTest, test_device_ready) { SetSampleDatabase1(); @@ -497,25 +455,22 @@ TEST_F(VolumeControlDeviceTest, test_device_ready) { // grab all the handles requested std::vector requested_handles; ON_CALL(gatt_queue, WriteDescriptor(_, _, _, _, _, _)) - .WillByDefault(Invoke( - [&requested_handles]( - uint16_t conn_id, uint16_t handle, std::vector value, - tGATT_WRITE_TYPE write_type, GATT_WRITE_OP_CB cb, - void* cb_data) -> void { requested_handles.push_back(handle); })); + .WillByDefault( + Invoke([&requested_handles]( + uint16_t conn_id, uint16_t handle, std::vector value, + tGATT_WRITE_TYPE write_type, GATT_WRITE_OP_CB cb, + void* cb_data) -> void { requested_handles.push_back(handle); })); ON_CALL(gatt_queue, ReadCharacteristic(_, _, _, _)) - .WillByDefault(Invoke( - [&requested_handles](uint16_t conn_id, uint16_t handle, - GATT_READ_OP_CB cb, void* cb_data) -> void { + .WillByDefault(Invoke([&requested_handles](uint16_t conn_id, uint16_t handle, + GATT_READ_OP_CB cb, void* cb_data) -> void { requested_handles.push_back(handle); })); - auto chrc_read_cb = [](uint16_t conn_id, tGATT_STATUS status, uint16_t handle, - uint16_t len, uint8_t* value, void* data) {}; - auto cccd_write_cb = [](uint16_t conn_id, tGATT_STATUS status, - uint16_t handle, uint16_t len, const uint8_t* value, - void* data) {}; - ASSERT_EQ(true, device->EnqueueInitialRequests(0x0001, chrc_read_cb, - cccd_write_cb)); + auto chrc_read_cb = [](uint16_t conn_id, tGATT_STATUS status, uint16_t handle, uint16_t len, + uint8_t* value, void* data) {}; + auto cccd_write_cb = [](uint16_t conn_id, tGATT_STATUS status, uint16_t handle, uint16_t len, + const uint8_t* value, void* data) {}; + ASSERT_EQ(true, device->EnqueueInitialRequests(0x0001, chrc_read_cb, cccd_write_cb)); ASSERT_NE((size_t)0, requested_handles.size()); // indicate non-pending requests @@ -536,14 +491,14 @@ TEST_F(VolumeControlDeviceTest, test_enqueue_remaining_requests) { tGATT_IF gatt_if = 0x0001; std::vector register_for_notification_data({0x01, 0x00}); - std::vector expected_to_read{ - 0x0016 /* volume flags */, 0x0065 /* audio location 1 */, - 0x0069 /* audio output description 1 */, 0x0085 /* audio location 1 */, - 0x008a /* audio output description 1 */}; + std::vector expected_to_read{0x0016 /* volume flags */, 0x0065 /* audio location 1 */, + 0x0069 /* audio output description 1 */, + 0x0085 /* audio location 1 */, + 0x008a /* audio output description 1 */}; std::map expected_to_write_value_ccc_handle_map{ - {0x0085, 0x0086} /* audio location ccc 2 */, - {0x008a, 0x008b} /* audio output description ccc */ + {0x0085, 0x0086} /* audio location ccc 2 */, + {0x008a, 0x008b} /* audio output description ccc */ }; for (uint16_t handle : expected_to_read) { @@ -551,69 +506,60 @@ TEST_F(VolumeControlDeviceTest, test_enqueue_remaining_requests) { } for (auto const& handle_pair : expected_to_write_value_ccc_handle_map) { - EXPECT_CALL(gatt_queue, WriteDescriptor(_, handle_pair.second, - register_for_notification_data, + EXPECT_CALL(gatt_queue, WriteDescriptor(_, handle_pair.second, register_for_notification_data, GATT_WRITE, _, _)); - EXPECT_CALL(gatt_interface, - RegisterForNotifications(gatt_if, _, handle_pair.first)); + EXPECT_CALL(gatt_interface, RegisterForNotifications(gatt_if, _, handle_pair.first)); } - auto chrc_read_cb = [](uint16_t conn_id, tGATT_STATUS status, uint16_t handle, - uint16_t len, uint8_t* value, void* data) {}; - auto cccd_write_cb = [](uint16_t conn_id, tGATT_STATUS status, - uint16_t handle, uint16_t len, const uint8_t* value, - void* data) {}; + auto chrc_read_cb = [](uint16_t conn_id, tGATT_STATUS status, uint16_t handle, uint16_t len, + uint8_t* value, void* data) {}; + auto cccd_write_cb = [](uint16_t conn_id, tGATT_STATUS status, uint16_t handle, uint16_t len, + const uint8_t* value, void* data) {}; device->EnqueueRemainingRequests(gatt_if, chrc_read_cb, cccd_write_cb); } TEST_F(VolumeControlDeviceTest, test_check_link_encrypted) { - ON_CALL(btm_interface, BTM_IsEncrypted(_, _)) - .WillByDefault(DoAll(Return(true))); + ON_CALL(btm_interface, BTM_IsEncrypted(_, _)).WillByDefault(DoAll(Return(true))); ASSERT_EQ(true, device->IsEncryptionEnabled()); - ON_CALL(btm_interface, BTM_IsEncrypted(_, _)) - .WillByDefault(DoAll(Return(false))); + ON_CALL(btm_interface, BTM_IsEncrypted(_, _)).WillByDefault(DoAll(Return(false))); ASSERT_NE(true, device->IsEncryptionEnabled()); } TEST_F(VolumeControlDeviceTest, test_control_point_operation) { - GATT_WRITE_OP_CB write_cb = [](uint16_t conn_id, tGATT_STATUS status, - uint16_t handle, uint16_t len, - const uint8_t* value, void* data) {}; + GATT_WRITE_OP_CB write_cb = [](uint16_t conn_id, tGATT_STATUS status, uint16_t handle, + uint16_t len, const uint8_t* value, void* data) {}; SetSampleDatabase1(); device->change_counter = 0x01; std::vector expected_data({0x03, 0x01}); - EXPECT_CALL(gatt_queue, WriteCharacteristic(_, 0x0014, expected_data, - GATT_WRITE, write_cb, nullptr)); + EXPECT_CALL(gatt_queue, + WriteCharacteristic(_, 0x0014, expected_data, GATT_WRITE, write_cb, nullptr)); device->ControlPointOperation(0x03, nullptr, write_cb, nullptr); } TEST_F(VolumeControlDeviceTest, test_control_point_operation_arg) { - GATT_WRITE_OP_CB write_cb = [](uint16_t conn_id, tGATT_STATUS status, - uint16_t handle, uint16_t len, - const uint8_t* value, void* data) {}; + GATT_WRITE_OP_CB write_cb = [](uint16_t conn_id, tGATT_STATUS status, uint16_t handle, + uint16_t len, const uint8_t* value, void* data) {}; SetSampleDatabase1(); device->change_counter = 0x55; std::vector expected_data({0x01, 0x55, 0x02, 0x03}); - EXPECT_CALL(gatt_queue, WriteCharacteristic(_, 0x0014, expected_data, - GATT_WRITE, write_cb, nullptr)); + EXPECT_CALL(gatt_queue, + WriteCharacteristic(_, 0x0014, expected_data, GATT_WRITE, write_cb, nullptr)); std::vector arg({0x02, 0x03}); device->ControlPointOperation(0x01, &arg, write_cb, nullptr); } TEST_F(VolumeControlDeviceTest, test_get_ext_audio_out_volume_offset) { - GATT_READ_OP_CB read_cb = [](uint16_t conn_id, tGATT_STATUS status, - uint16_t handle, uint16_t len, uint8_t* value, - void* data) {}; + GATT_READ_OP_CB read_cb = [](uint16_t conn_id, tGATT_STATUS status, uint16_t handle, uint16_t len, + uint8_t* value, void* data) {}; SetSampleDatabase1(); EXPECT_CALL(gatt_queue, ReadCharacteristic(_, 0x0062, read_cb, nullptr)); device->GetExtAudioOutVolumeOffset(1, read_cb, nullptr); } TEST_F(VolumeControlDeviceTest, test_get_ext_audio_out_location) { - GATT_READ_OP_CB read_cb = [](uint16_t conn_id, tGATT_STATUS status, - uint16_t handle, uint16_t len, uint8_t* value, - void* data) {}; + GATT_READ_OP_CB read_cb = [](uint16_t conn_id, tGATT_STATUS status, uint16_t handle, uint16_t len, + uint8_t* value, void* data) {}; SetSampleDatabase1(); EXPECT_CALL(gatt_queue, ReadCharacteristic(_, 0x0085, read_cb, nullptr)); device->GetExtAudioOutLocation(2, read_cb, nullptr); @@ -623,8 +569,7 @@ TEST_F(VolumeControlDeviceTest, test_set_ext_audio_out_location) { SetSampleDatabase1(); std::vector expected_data({0x44, 0x33, 0x22, 0x11}); EXPECT_CALL(gatt_queue, - WriteCharacteristic(_, 0x0085, expected_data, GATT_WRITE_NO_RSP, - nullptr, nullptr)); + WriteCharacteristic(_, 0x0085, expected_data, GATT_WRITE_NO_RSP, nullptr, nullptr)); device->SetExtAudioOutLocation(2, 0x11223344); } @@ -635,9 +580,8 @@ TEST_F(VolumeControlDeviceTest, test_set_ext_audio_out_location_non_writable) { } TEST_F(VolumeControlDeviceTest, test_get_ext_audio_out_description) { - GATT_READ_OP_CB read_cb = [](uint16_t conn_id, tGATT_STATUS status, - uint16_t handle, uint16_t len, uint8_t* value, - void* data) {}; + GATT_READ_OP_CB read_cb = [](uint16_t conn_id, tGATT_STATUS status, uint16_t handle, uint16_t len, + uint8_t* value, void* data) {}; SetSampleDatabase1(); EXPECT_CALL(gatt_queue, ReadCharacteristic(_, 0x008a, read_cb, nullptr)); device->GetExtAudioOutDescription(2, read_cb, nullptr); @@ -648,13 +592,11 @@ TEST_F(VolumeControlDeviceTest, test_set_ext_audio_out_description) { std::string descr = "right front"; std::vector expected_data(descr.begin(), descr.end()); EXPECT_CALL(gatt_queue, - WriteCharacteristic(_, 0x008a, expected_data, GATT_WRITE_NO_RSP, - nullptr, nullptr)); + WriteCharacteristic(_, 0x008a, expected_data, GATT_WRITE_NO_RSP, nullptr, nullptr)); device->SetExtAudioOutDescription(2, descr); } -TEST_F(VolumeControlDeviceTest, - test_set_ext_audio_out_description_non_writable) { +TEST_F(VolumeControlDeviceTest, test_set_ext_audio_out_description_non_writable) { SetSampleDatabase1(); std::string descr = "left front"; EXPECT_CALL(gatt_queue, WriteCharacteristic(_, _, _, _, _, _)).Times(0); @@ -662,32 +604,29 @@ TEST_F(VolumeControlDeviceTest, } TEST_F(VolumeControlDeviceTest, test_ext_audio_out_control_point_operation) { - GATT_WRITE_OP_CB write_cb = [](uint16_t conn_id, tGATT_STATUS status, - uint16_t handle, uint16_t len, - const uint8_t* value, void* data) {}; + GATT_WRITE_OP_CB write_cb = [](uint16_t conn_id, tGATT_STATUS status, uint16_t handle, + uint16_t len, const uint8_t* value, void* data) {}; SetSampleDatabase1(); VolumeOffset* offset = device->audio_offsets.FindById(1); ASSERT_NE(nullptr, offset); offset->change_counter = 0x09; std::vector expected_data({0x0b, 0x09}); - EXPECT_CALL(gatt_queue, WriteCharacteristic(_, 0x0067, expected_data, - GATT_WRITE, write_cb, nullptr)); + EXPECT_CALL(gatt_queue, + WriteCharacteristic(_, 0x0067, expected_data, GATT_WRITE, write_cb, nullptr)); device->ExtAudioOutControlPointOperation(1, 0x0b, nullptr, write_cb, nullptr); } -TEST_F(VolumeControlDeviceTest, - test_ext_audio_out_control_point_operation_arg) { - GATT_WRITE_OP_CB write_cb = [](uint16_t conn_id, tGATT_STATUS status, - uint16_t handle, uint16_t len, - const uint8_t* value, void* data) {}; +TEST_F(VolumeControlDeviceTest, test_ext_audio_out_control_point_operation_arg) { + GATT_WRITE_OP_CB write_cb = [](uint16_t conn_id, tGATT_STATUS status, uint16_t handle, + uint16_t len, const uint8_t* value, void* data) {}; SetSampleDatabase1(); VolumeOffset* offset = device->audio_offsets.FindById(1); ASSERT_NE(nullptr, offset); offset->change_counter = 0x09; std::vector expected_data({0x0b, 0x09, 0x01, 0x02, 0x03, 0x04}); std::vector arg({0x01, 0x02, 0x03, 0x04}); - EXPECT_CALL(gatt_queue, WriteCharacteristic(_, 0x0067, expected_data, - GATT_WRITE, write_cb, nullptr)); + EXPECT_CALL(gatt_queue, + WriteCharacteristic(_, 0x0067, expected_data, GATT_WRITE, write_cb, nullptr)); device->ExtAudioOutControlPointOperation(1, 0x0b, &arg, write_cb, nullptr); } diff --git a/system/bta/vc/types.h b/system/bta/vc/types.h index 2096b45e1dd..3b39401b0ed 100644 --- a/system/bta/vc/types.h +++ b/system/bta/vc/types.h @@ -75,8 +75,7 @@ struct VolumeOperation { alarm_t* operation_timeout_; VolumeOperation(int operation_id, int group_id, bool is_autonomous, uint8_t opcode, - std::vector arguments, - std::vector devices) + std::vector arguments, std::vector devices) : operation_id_(operation_id), group_id_(group_id), is_autonomous_(is_autonomous), @@ -86,27 +85,26 @@ struct VolumeOperation { auto name = "operation_timeout_" + std::to_string(operation_id); operation_timeout_ = alarm_new(name.c_str()); started_ = false; - }; + } ~VolumeOperation() { if (operation_timeout_ == nullptr) { - log::warn("operation_timeout_ should not be null, id {}, device cnt {}", - operation_id_, devices_.size()); + log::warn("operation_timeout_ should not be null, id {}, device cnt {}", operation_id_, + devices_.size()); return; } - if (alarm_is_scheduled(operation_timeout_)) + if (alarm_is_scheduled(operation_timeout_)) { alarm_cancel(operation_timeout_); + } alarm_free(operation_timeout_); operation_timeout_ = nullptr; } - bool IsGroupOperation(void) { - return (group_id_ != bluetooth::groups::kGroupUnknown); - } + bool IsGroupOperation(void) { return group_id_ != bluetooth::groups::kGroupUnknown; } - bool IsStarted(void) { return started_; }; + bool IsStarted(void) { return started_; } void Start(void) { started_ = true; } }; @@ -144,17 +142,16 @@ struct VolumeOffset { }; class VolumeOffsets { - public: +public: void Add(VolumeOffset& offset) { offset.id = (uint8_t)Size() + 1; volume_offsets.push_back(offset); } VolumeOffset* FindByLocation(uint8_t location) { - auto iter = std::find_if(volume_offsets.begin(), volume_offsets.end(), - [&location](const VolumeOffset& item) { - return item.location == location; - }); + auto iter = std::find_if( + volume_offsets.begin(), volume_offsets.end(), + [&location](const VolumeOffset& item) { return item.location == location; }); return (iter == volume_offsets.end()) ? nullptr : &(*iter); } @@ -169,9 +166,8 @@ class VolumeOffsets { } VolumeOffset* FindById(uint16_t id) { - auto iter = - std::find_if(volume_offsets.begin(), volume_offsets.end(), - [&id](const VolumeOffset& item) { return item.id == id; }); + auto iter = std::find_if(volume_offsets.begin(), volume_offsets.end(), + [&id](const VolumeOffset& item) { return item.id == id; }); return (iter == volume_offsets.end()) ? nullptr : &(*iter); } @@ -192,8 +188,7 @@ class VolumeOffsets { << " changeCnt: " << +v.change_counter << "\n" << " location: " << +v.location << "\n" << " service_handle: " << +v.service_handle << "\n" - << " audio_location_writable " << v.audio_location_writable - << "\n" + << " audio_location_writable " << v.audio_location_writable << "\n" << " audio_descr_writable: " << v.audio_descr_writable << "\n"; } dprintf(fd, "%s", stream.str().c_str()); diff --git a/system/bta/vc/vc.cc b/system/bta/vc/vc.cc index 3775834dce8..8db78160453 100644 --- a/system/bta/vc/vc.cc +++ b/system/bta/vc/vc.cc @@ -75,31 +75,30 @@ std::mutex instance_mutex; * Also each of the External Device has description * characteristic and Type which gives the application hint what it is a device. * Examples of such devices: - * External Output: 1 instance to controller ballance between set of devices + * External Output: 1 instance to controller balance between set of devices * External Output: each of 5.1 speaker set etc. */ class VolumeControlImpl : public VolumeControl { - public: +public: ~VolumeControlImpl() override = default; - VolumeControlImpl(bluetooth::vc::VolumeControlCallbacks* callbacks, - const base::Closure& initCb) + VolumeControlImpl(bluetooth::vc::VolumeControlCallbacks* callbacks, const base::Closure& initCb) : gatt_if_(0), callbacks_(callbacks), latest_operation_id_(0) { BTA_GATTC_AppRegister( - gattc_callback_static, - base::Bind( - [](const base::Closure& initCb, uint8_t client_id, uint8_t status) { - if (status != GATT_SUCCESS) { - log::error( - "Can't start Volume Control profile - no gatt clients " - "left!"); - return; - } - instance->gatt_if_ = client_id; - initCb.Run(); - }, - initCb), - true); + gattc_callback_static, + base::Bind( + [](const base::Closure& initCb, uint8_t client_id, uint8_t status) { + if (status != GATT_SUCCESS) { + log::error( + "Can't start Volume Control profile - no gatt clients " + "left!"); + return; + } + instance->gatt_if_ = client_id; + initCb.Run(); + }, + initCb), + true); } void StartOpportunisticConnect(const RawAddress& address) { @@ -129,11 +128,10 @@ class VolumeControlImpl : public VolumeControl { device->connection_id); if (device->IsReady()) { - callbacks_->OnConnectionState(ConnectionState::CONNECTED, - device->address); + callbacks_->OnConnectionState(ConnectionState::CONNECTED, device->address); } else { - OnGattConnected(GATT_SUCCESS, device->connection_id, gatt_if_, - device->address, BT_TRANSPORT_LE, GATT_MAX_MTU_SIZE); + OnGattConnected(GATT_SUCCESS, device->connection_id, gatt_if_, device->address, + BT_TRANSPORT_LE, GATT_MAX_MTU_SIZE); } return; } @@ -148,22 +146,18 @@ class VolumeControlImpl : public VolumeControl { StartOpportunisticConnect(address); } - void OnGattConnected(tGATT_STATUS status, uint16_t connection_id, - tGATT_IF /*client_if*/, RawAddress address, - tBT_TRANSPORT transport, uint16_t /*mtu*/) { - log::info("{}, conn_id=0x{:04x}, transport={}, status={}(0x{:02x})", - address, connection_id, bt_transport_text(transport), - gatt_status_text(status), status); + void OnGattConnected(tGATT_STATUS status, uint16_t connection_id, tGATT_IF /*client_if*/, + RawAddress address, tBT_TRANSPORT transport, uint16_t /*mtu*/) { + log::info("{}, conn_id=0x{:04x}, transport={}, status={}(0x{:02x})", address, connection_id, + bt_transport_text(transport), gatt_status_text(status), status); if (transport != BT_TRANSPORT_LE) { - log::warn("Only LE connection is allowed (transport {})", - bt_transport_text(transport)); + log::warn("Only LE connection is allowed (transport {})", bt_transport_text(transport)); BTA_GATTC_Close(connection_id); return; } - VolumeControlDevice* device = - volume_control_devices_.FindByAddress(address); + VolumeControlDevice* device = volume_control_devices_.FindByAddress(address); if (!device) { log::error("Skipping unknown device, address={}", address); return; @@ -195,8 +189,7 @@ class VolumeControlImpl : public VolumeControl { } void OnEncryptionComplete(const RawAddress& address, uint8_t success) { - VolumeControlDevice* device = - volume_control_devices_.FindByAddress(address); + VolumeControlDevice* device = volume_control_devices_.FindByAddress(address); if (!device) { log::error("Skipping unknown device {}", address); return; @@ -214,8 +207,7 @@ class VolumeControlImpl : public VolumeControl { log::info("{} status: {}", address, success); if (device->HasHandles()) { - device->EnqueueInitialRequests(gatt_if_, chrc_read_callback_static, - OnGattWriteCccStatic); + device->EnqueueInitialRequests(gatt_if_, chrc_read_callback_static, OnGattWriteCccStatic); } else { BTA_GATTC_ServiceSearchRequest(device->connection_id, kVolumeControlUuid); @@ -237,15 +229,13 @@ class VolumeControlImpl : public VolumeControl { std::vector devices = {device->address}; device->DeregisterNotifications(gatt_if_); - RemovePendingVolumeControlOperations(devices, - bluetooth::groups::kGroupUnknown); + RemovePendingVolumeControlOperations(devices, bluetooth::groups::kGroupUnknown); device->ResetHandles(); BTA_GATTC_ServiceSearchRequest(device->connection_id, kVolumeControlUuid); } void OnServiceChangeEvent(const RawAddress& address) { - VolumeControlDevice* device = - volume_control_devices_.FindByAddress(address); + VolumeControlDevice* device = volume_control_devices_.FindByAddress(address); if (!device) { log::error("Skipping unknown device {}", address); return; @@ -255,8 +245,7 @@ class VolumeControlImpl : public VolumeControl { } void OnServiceDiscDoneEvent(const RawAddress& address) { - VolumeControlDevice* device = - volume_control_devices_.FindByAddress(address); + VolumeControlDevice* device = volume_control_devices_.FindByAddress(address); if (!device) { log::error("Skipping unknown device {}", address); return; @@ -268,16 +257,16 @@ class VolumeControlImpl : public VolumeControl { } void OnServiceSearchComplete(uint16_t connection_id, tGATT_STATUS status) { - VolumeControlDevice* device = - volume_control_devices_.FindByConnId(connection_id); + VolumeControlDevice* device = volume_control_devices_.FindByConnId(connection_id); if (!device) { - log::error("Skipping unknown device, connection_id=0x{:x}", - connection_id); + log::error("Skipping unknown device, connection_id=0x{:x}", connection_id); return; } /* Known device, nothing to do */ - if (device->IsReady()) return; + if (device->IsReady()) { + return; + } if (status != GATT_SUCCESS) { /* close connection and report service discovery complete with error */ @@ -298,13 +287,11 @@ class VolumeControlImpl : public VolumeControl { return; } - device->EnqueueInitialRequests(gatt_if_, chrc_read_callback_static, - OnGattWriteCccStatic); + device->EnqueueInitialRequests(gatt_if_, chrc_read_callback_static, OnGattWriteCccStatic); } - void OnCharacteristicValueChanged(uint16_t conn_id, tGATT_STATUS status, - uint16_t handle, uint16_t len, - uint8_t* value, void* data, + void OnCharacteristicValueChanged(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, + uint16_t len, uint8_t* value, void* data, bool is_notification) { VolumeControlDevice* device = volume_control_devices_.FindByConnId(conn_id); if (!device) { @@ -333,10 +320,11 @@ class VolumeControlImpl : public VolumeControl { } const gatt::Service* service = BTA_GATTC_GetOwningService(conn_id, handle); - if (service == nullptr) return; + if (service == nullptr) { + return; + } - VolumeOffset* offset = - device->audio_offsets.FindByServiceHandle(service->handle); + VolumeOffset* offset = device->audio_offsets.FindByServiceHandle(service->handle); if (offset != nullptr) { if (handle == offset->state_handle) { OnExtAudioOutStateChanged(device, offset, len, value); @@ -356,22 +344,19 @@ class VolumeControlImpl : public VolumeControl { log::error("unknown handle=0x{:x}", handle); } - void OnNotificationEvent(uint16_t conn_id, uint16_t handle, uint16_t len, - uint8_t* value) { + void OnNotificationEvent(uint16_t conn_id, uint16_t handle, uint16_t len, uint8_t* value) { log::info("handle=0x{:x}", handle); - OnCharacteristicValueChanged(conn_id, GATT_SUCCESS, handle, len, value, - nullptr, true); + OnCharacteristicValueChanged(conn_id, GATT_SUCCESS, handle, len, value, nullptr, true); } void VolumeControlReadCommon(uint16_t conn_id, uint16_t handle) { - BtaGattQueue::ReadCharacteristic(conn_id, handle, chrc_read_callback_static, - nullptr); + BtaGattQueue::ReadCharacteristic(conn_id, handle, chrc_read_callback_static, nullptr); } - void HandleAutonomusVolumeChange(VolumeControlDevice* device, - bool is_volume_change, bool is_mute_change) { - log::debug("{}, is volume change: {}, is mute change: {}", device->address, - is_volume_change, is_mute_change); + void HandleAutonomusVolumeChange(VolumeControlDevice* device, bool is_volume_change, + bool is_mute_change) { + log::debug("{}, is volume change: {}, is mute change: {}", device->address, is_volume_change, + is_mute_change); if (!is_volume_change && !is_mute_change) { log::error("Autonomous change but volume and mute did not changed."); @@ -381,17 +366,14 @@ class VolumeControlImpl : public VolumeControl { auto csis_api = CsisClient::Get(); if (!csis_api) { log::warn("Csis module is not available"); - callbacks_->OnVolumeStateChanged(device->address, device->volume, - device->mute, true); + callbacks_->OnVolumeStateChanged(device->address, device->volume, device->mute, true); return; } - auto group_id = - csis_api->GetGroupId(device->address, le_audio::uuid::kCapServiceUuid); + auto group_id = csis_api->GetGroupId(device->address, le_audio::uuid::kCapServiceUuid); if (group_id == bluetooth::groups::kGroupUnknown) { log::warn("No group for device {}", device->address); - callbacks_->OnVolumeStateChanged(device->address, device->volume, - device->mute, true); + callbacks_->OnVolumeStateChanged(device->address, device->volume, device->mute, true); return; } @@ -407,29 +389,26 @@ class VolumeControlImpl : public VolumeControl { if (devices.empty() && (is_volume_change || is_mute_change)) { log::info("No more devices in the group right now"); - callbacks_->OnGroupVolumeStateChanged(group_id, device->volume, - device->mute, true); + callbacks_->OnGroupVolumeStateChanged(group_id, device->volume, device->mute, true); return; } if (is_volume_change) { std::vector arg({device->volume}); - PrepareVolumeControlOperation(devices, group_id, true, - kControlPointOpcodeSetAbsoluteVolume, arg); + PrepareVolumeControlOperation(devices, group_id, true, kControlPointOpcodeSetAbsoluteVolume, + arg); } if (is_mute_change) { std::vector arg; - uint8_t opcode = - device->mute ? kControlPointOpcodeMute : kControlPointOpcodeUnmute; + uint8_t opcode = device->mute ? kControlPointOpcodeMute : kControlPointOpcodeUnmute; PrepareVolumeControlOperation(devices, group_id, true, opcode, arg); } StartQueueOperation(); } - void OnVolumeControlStateReadOrNotified(VolumeControlDevice* device, - uint16_t len, uint8_t* value, + void OnVolumeControlStateReadOrNotified(VolumeControlDevice* device, uint16_t len, uint8_t* value, bool is_notification) { if (len != 3) { log::info("malformed len=0x{:x}", len); @@ -449,8 +428,8 @@ class VolumeControlImpl : public VolumeControl { bool is_mute_change = (device->mute != mute); device->mute = mute; - log::info("volume 0x{:x} mute 0x{:x} change_counter 0x{:x}", device->volume, - device->mute, device->change_counter); + log::info("volume 0x{:x} mute 0x{:x} change_counter 0x{:x}", device->volume, device->mute, + device->change_counter); if (!device->IsReady()) { log::info("Device: {} is not ready yet.", device->address); @@ -459,21 +438,18 @@ class VolumeControlImpl : public VolumeControl { /* This is just a read, send single notification */ if (!is_notification) { - callbacks_->OnVolumeStateChanged(device->address, device->volume, - device->mute, false); + callbacks_->OnVolumeStateChanged(device->address, device->volume, device->mute, false); return; } auto addr = device->address; auto op = find_if(ongoing_operations_.begin(), ongoing_operations_.end(), [addr](auto& operation) { - auto it = find(operation.devices_.begin(), - operation.devices_.end(), addr); + auto it = find(operation.devices_.begin(), operation.devices_.end(), addr); return it != operation.devices_.end(); }); if (op == ongoing_operations_.end()) { - log::debug("Could not find operation id for device: {}. Autonomus change", - device->address); + log::debug("Could not find operation id for device: {}. Autonomus change", device->address); HandleAutonomusVolumeChange(device, is_volume_change, is_mute_change); return; } @@ -482,34 +458,30 @@ class VolumeControlImpl : public VolumeControl { auto it = find(op->devices_.begin(), op->devices_.end(), device->address); op->devices_.erase(it); if (!op->devices_.empty()) { - log::debug("wait for more responses for operation_id: {}", - op->operation_id_); + log::debug("wait for more responses for operation_id: {}", op->operation_id_); return; } if (op->IsGroupOperation()) { - callbacks_->OnGroupVolumeStateChanged(op->group_id_, device->volume, - device->mute, op->is_autonomous_); + callbacks_->OnGroupVolumeStateChanged(op->group_id_, device->volume, device->mute, + op->is_autonomous_); } else { /* op->is_autonomous_ will always be false, since we only make it true for group operations */ - callbacks_->OnVolumeStateChanged(device->address, device->volume, - device->mute, false); + callbacks_->OnVolumeStateChanged(device->address, device->volume, device->mute, false); } ongoing_operations_.erase(op); StartQueueOperation(); } - void OnVolumeControlFlagsChanged(VolumeControlDevice* device, uint16_t len, - uint8_t* value) { + void OnVolumeControlFlagsChanged(VolumeControlDevice* device, uint16_t len, uint8_t* value) { device->flags = *value; log::info("flags 0x{:x}", device->flags); } - void OnExtAudioOutStateChanged(VolumeControlDevice* device, - VolumeOffset* offset, uint16_t len, + void OnExtAudioOutStateChanged(VolumeControlDevice* device, VolumeOffset* offset, uint16_t len, uint8_t* value) { if (len != 3) { log::info("malformed len=0x{:x}", len); @@ -521,20 +493,18 @@ class VolumeControlImpl : public VolumeControl { STREAM_TO_UINT8(offset->change_counter, pp); log::info("{}", base::HexEncode(value, len)); - log::info("id: 0x{:x} offset: 0x{:x} counter: 0x{:x}", offset->id, - offset->offset, offset->change_counter); + log::info("id: 0x{:x} offset: 0x{:x} counter: 0x{:x}", offset->id, offset->offset, + offset->change_counter); if (!device->IsReady()) { log::info("Device: {} is not ready yet.", device->address); return; } - callbacks_->OnExtAudioOutVolumeOffsetChanged(device->address, offset->id, - offset->offset); + callbacks_->OnExtAudioOutVolumeOffsetChanged(device->address, offset->id, offset->offset); } - void OnExtAudioOutLocationChanged(VolumeControlDevice* device, - VolumeOffset* offset, uint16_t len, + void OnExtAudioOutLocationChanged(VolumeControlDevice* device, VolumeOffset* offset, uint16_t len, uint8_t* value) { if (len != 4) { log::info("malformed len=0x{:x}", len); @@ -552,31 +522,29 @@ class VolumeControlImpl : public VolumeControl { return; } - callbacks_->OnExtAudioOutLocationChanged(device->address, offset->id, - offset->location); + callbacks_->OnExtAudioOutLocationChanged(device->address, offset->id, offset->location); } - void OnExtAudioOutCPWrite(uint16_t connection_id, tGATT_STATUS status, - uint16_t handle, void* /*data*/) { - VolumeControlDevice* device = - volume_control_devices_.FindByConnId(connection_id); + void OnExtAudioOutCPWrite(uint16_t connection_id, tGATT_STATUS status, uint16_t handle, + void* /*data*/) { + VolumeControlDevice* device = volume_control_devices_.FindByConnId(connection_id); if (!device) { - log::error("Skipping unknown device disconnect, connection_id=0x{:x}", - connection_id); + log::error("Skipping unknown device disconnect, connection_id=0x{:x}", connection_id); return; } - log::info("Offset Control Point write response handle0x{:x} status: 0x{:x}", - handle, (int)(status)); + log::info("Offset Control Point write response handle0x{:x} status: 0x{:x}", handle, + (int)(status)); /* TODO Design callback API to notify about changes */ } - void OnOffsetOutputDescChanged(VolumeControlDevice* device, - VolumeOffset* offset, uint16_t len, + void OnOffsetOutputDescChanged(VolumeControlDevice* device, VolumeOffset* offset, uint16_t len, uint8_t* value) { std::string description = std::string(value, value + len); - if (!base::IsStringUTF8(description)) description = ""; + if (!base::IsStringUTF8(description)) { + description = ""; + } log::info("{}", description); @@ -589,11 +557,9 @@ class VolumeControlImpl : public VolumeControl { std::move(description)); } - void OnGattWriteCcc(uint16_t connection_id, tGATT_STATUS status, - uint16_t handle, uint16_t len, const uint8_t* value, - void* /*data*/) { - VolumeControlDevice* device = - volume_control_devices_.FindByConnId(connection_id); + void OnGattWriteCcc(uint16_t connection_id, tGATT_STATUS status, uint16_t handle, uint16_t len, + const uint8_t* value, void* /*data*/) { + VolumeControlDevice* device = volume_control_devices_.FindByConnId(connection_id); if (!device) { log::info("unknown connection_id=0x{:x}", connection_id); BtaGattQueue::Clean(connection_id); @@ -602,27 +568,23 @@ class VolumeControlImpl : public VolumeControl { if (status != GATT_SUCCESS) { if (status == GATT_DATABASE_OUT_OF_SYNC) { - log::info("Database out of sync for {}, conn_id: 0x{:04x}", - device->address, connection_id); + log::info("Database out of sync for {}, conn_id: 0x{:04x}", device->address, connection_id); ClearDeviceInformationAndStartSearch(device); } else { - log::error( - "Failed to register for notification: 0x{:04x}, status 0x{:02x}", - handle, status); + log::error("Failed to register for notification: 0x{:04x}, status 0x{:02x}", handle, + status); device_cleanup_helper(device, true); } return; } - log::info("Successfully registered on ccc: 0x{:04x}, device: {}", handle, - device->address); + log::info("Successfully registered on ccc: 0x{:04x}, device: {}", handle, device->address); verify_device_ready(device, handle); } - static void OnGattWriteCccStatic(uint16_t connection_id, tGATT_STATUS status, - uint16_t handle, uint16_t len, - const uint8_t* value, void* data) { + static void OnGattWriteCccStatic(uint16_t connection_id, tGATT_STATUS status, uint16_t handle, + uint16_t len, const uint8_t* value, void* data) { if (!instance) { log::error("No instance={}", handle); return; @@ -639,8 +601,7 @@ class VolumeControlImpl : public VolumeControl { void Disconnect(const RawAddress& address) override { log::info("{}", address); - VolumeControlDevice* device = - volume_control_devices_.FindByAddress(address); + VolumeControlDevice* device = volume_control_devices_.FindByAddress(address); if (!device) { log::warn("Device not connected to profile {}", address); callbacks_->OnConnectionState(ConnectionState::DISCONNECTED, address); @@ -662,21 +623,19 @@ class VolumeControlImpl : public VolumeControl { volume_control_devices_.Remove(address); } - void OnGattDisconnected(uint16_t connection_id, tGATT_IF /*client_if*/, - RawAddress remote_bda, tGATT_DISCONN_REASON reason) { - VolumeControlDevice* device = - volume_control_devices_.FindByConnId(connection_id); + void OnGattDisconnected(uint16_t connection_id, tGATT_IF /*client_if*/, RawAddress remote_bda, + tGATT_DISCONN_REASON reason) { + VolumeControlDevice* device = volume_control_devices_.FindByConnId(connection_id); if (!device) { - log::error("Skipping unknown device disconnect, connection_id=0x{:x}", - connection_id); + log::error("Skipping unknown device disconnect, connection_id=0x{:x}", connection_id); return; } if (!device->IsConnected()) { log::error( - "Skipping disconnect of the already disconnected device, " - "connection_id=0x{:x}", - connection_id); + "Skipping disconnect of the already disconnected device, " + "connection_id=0x{:x}", + connection_id); return; } @@ -685,8 +644,7 @@ class VolumeControlImpl : public VolumeControl { bool notify = device->IsReady() || device->connecting_actively; device_cleanup_helper(device, notify); - if (reason != GATT_CONN_TERMINATE_LOCAL_HOST && - device->connecting_actively) { + if (reason != GATT_CONN_TERMINATE_LOCAL_HOST && device->connecting_actively) { StartOpportunisticConnect(remote_bda); } } @@ -705,17 +663,15 @@ class VolumeControlImpl : public VolumeControl { } // Remove operations with no devices - ongoing_operations_.erase( - std::remove_if(ongoing_operations_.begin(), ongoing_operations_.end(), - [](auto& op) { return op.devices_.empty(); }), - ongoing_operations_.end()); + ongoing_operations_.erase(std::remove_if(ongoing_operations_.begin(), ongoing_operations_.end(), + [](auto& op) { return op.devices_.empty(); }), + ongoing_operations_.end()); } void RemoveDeviceFromOperationList(const RawAddress& addr, int operation_id) { - auto op = find_if(ongoing_operations_.begin(), ongoing_operations_.end(), - [operation_id](auto& operation) { - return operation.operation_id_ == operation_id; - }); + auto op = find_if( + ongoing_operations_.begin(), ongoing_operations_.end(), + [operation_id](auto& operation) { return operation.operation_id_ == operation_id; }); if (op == ongoing_operations_.end()) { log::error("Could not find operation id: {}", operation_id); @@ -733,21 +689,17 @@ class VolumeControlImpl : public VolumeControl { } } - void RemovePendingVolumeControlOperations(std::vector& devices, - int group_id) { + void RemovePendingVolumeControlOperations(std::vector& devices, int group_id) { log::debug(""); - for (auto op = ongoing_operations_.begin(); - op != ongoing_operations_.end();) { + for (auto op = ongoing_operations_.begin(); op != ongoing_operations_.end();) { // We only remove operations that don't affect the mute field. - if (op->IsStarted() || - (op->opcode_ != kControlPointOpcodeSetAbsoluteVolume && - op->opcode_ != kControlPointOpcodeVolumeUp && - op->opcode_ != kControlPointOpcodeVolumeDown)) { + if (op->IsStarted() || (op->opcode_ != kControlPointOpcodeSetAbsoluteVolume && + op->opcode_ != kControlPointOpcodeVolumeUp && + op->opcode_ != kControlPointOpcodeVolumeDown)) { op++; continue; } - if (group_id != bluetooth::groups::kGroupUnknown && - op->group_id_ == group_id) { + if (group_id != bluetooth::groups::kGroupUnknown && op->group_id_ == group_id) { log::debug("Removing operation {}", op->operation_id_); op = ongoing_operations_.erase(op); continue; @@ -768,20 +720,19 @@ class VolumeControlImpl : public VolumeControl { } } - void OnWriteControlResponse(uint16_t connection_id, tGATT_STATUS status, - uint16_t handle, void* data) { - VolumeControlDevice* device = - volume_control_devices_.FindByConnId(connection_id); + void OnWriteControlResponse(uint16_t connection_id, tGATT_STATUS status, uint16_t handle, + void* data) { + VolumeControlDevice* device = volume_control_devices_.FindByConnId(connection_id); if (!device) { - log::error("Skipping unknown device disconnect, connection_id=0x{:x}", - connection_id); + log::error("Skipping unknown device disconnect, connection_id=0x{:x}", connection_id); return; } - log::info("Write response handle: 0x{:x} status: 0x{:x}", handle, - (int)(status)); + log::info("Write response handle: 0x{:x} status: 0x{:x}", handle, (int)(status)); - if (status == GATT_SUCCESS) return; + if (status == GATT_SUCCESS) { + return; + } /* In case of error, remove device from the tracking operation list */ RemoveDeviceFromOperationList(device->address, PTR_TO_INT(data)); @@ -801,9 +752,8 @@ class VolumeControlImpl : public VolumeControl { } void OperationMonitorTimeoutFired(int operation_id) { - auto op = find_if( - ongoing_operations_.begin(), ongoing_operations_.end(), - [operation_id](auto& it) { return it.operation_id_ == operation_id; }); + auto op = find_if(ongoing_operations_.begin(), ongoing_operations_.end(), + [operation_id](auto& it) { return it.operation_id_ == operation_id; }); if (op == ongoing_operations_.end()) { log::error("Could not find operation_id: {}", operation_id); @@ -829,52 +779,48 @@ class VolumeControlImpl : public VolumeControl { log::info("Current operation_id: {}", op->operation_id_); if (op->IsStarted()) { - log::info("Operation {} is started, wait until it is complete", - op->operation_id_); + log::info("Operation {} is started, wait until it is complete", op->operation_id_); return; } op->Start(); alarm_set_on_mloop(op->operation_timeout_, kOperationMonitorTimeoutMs, - operation_timeout_callback, - INT_TO_PTR(op->operation_id_)); - devices_control_point_helper( - op->devices_, op->opcode_, - op->arguments_.size() == 0 ? nullptr : &(op->arguments_), - op->operation_id_); + operation_timeout_callback, INT_TO_PTR(op->operation_id_)); + devices_control_point_helper(op->devices_, op->opcode_, + op->arguments_.size() == 0 ? nullptr : &(op->arguments_), + op->operation_id_); } - void PrepareVolumeControlOperation(std::vector devices, - int group_id, bool is_autonomous, - uint8_t opcode, + void PrepareVolumeControlOperation(std::vector devices, int group_id, + bool is_autonomous, uint8_t opcode, std::vector& arguments) { log::debug( - "num of devices: {}, group_id: {}, is_autonomous: {} opcode: {}, arg " - "size: {}", - devices.size(), group_id, is_autonomous, opcode, arguments.size()); - - if (std::find_if(ongoing_operations_.begin(), ongoing_operations_.end(), - [opcode, &devices, &arguments](const VolumeOperation& op) { - if (op.opcode_ != opcode) return false; - if (!std::equal(op.arguments_.begin(), - op.arguments_.end(), arguments.begin())) - return false; - // Filter out all devices which have the exact operation - // already scheduled - devices.erase( - std::remove_if(devices.begin(), devices.end(), - [&op](auto d) { - return find(op.devices_.begin(), - op.devices_.end(), - d) != op.devices_.end(); - }), - devices.end()); - return devices.empty(); - }) == ongoing_operations_.end()) { - ongoing_operations_.emplace_back(latest_operation_id_++, group_id, - is_autonomous, opcode, arguments, - devices); + "num of devices: {}, group_id: {}, is_autonomous: {} opcode: {}, arg " + "size: {}", + devices.size(), group_id, is_autonomous, opcode, arguments.size()); + + if (std::find_if( + ongoing_operations_.begin(), ongoing_operations_.end(), + [opcode, &devices, &arguments](const VolumeOperation& op) { + if (op.opcode_ != opcode) { + return false; + } + if (!std::equal(op.arguments_.begin(), op.arguments_.end(), arguments.begin())) { + return false; + } + // Filter out all devices which have the exact operation + // already scheduled + devices.erase(std::remove_if(devices.begin(), devices.end(), + [&op](auto d) { + return find(op.devices_.begin(), op.devices_.end(), + d) != op.devices_.end(); + }), + devices.end()); + return devices.empty(); + }) == ongoing_operations_.end()) { + ongoing_operations_.emplace_back(latest_operation_id_++, group_id, is_autonomous, opcode, + arguments, devices); } } @@ -884,14 +830,14 @@ class VolumeControlImpl : public VolumeControl { uint8_t opcode = mute ? kControlPointOpcodeMute : kControlPointOpcodeUnmute; if (std::holds_alternative(addr_or_group_id)) { - VolumeControlDevice* dev = volume_control_devices_.FindByAddress( - std::get(addr_or_group_id)); + VolumeControlDevice* dev = + volume_control_devices_.FindByAddress(std::get(addr_or_group_id)); if (dev != nullptr) { log::debug("Address: {}: isReady: {}", dev->address, dev->IsReady()); if (dev->IsReady() && (dev->mute != mute)) { std::vector devices = {dev->address}; - PrepareVolumeControlOperation( - devices, bluetooth::groups::kGroupUnknown, false, opcode, arg); + PrepareVolumeControlOperation(devices, bluetooth::groups::kGroupUnknown, false, opcode, + arg); } } } else { @@ -922,8 +868,7 @@ class VolumeControlImpl : public VolumeControl { if (!dev->IsReady() || (dev->mute == mute)) { it = devices.erase(it); - muteNotChanged = - muteNotChanged ? muteNotChanged : (dev->mute == mute); + muteNotChanged = muteNotChanged ? muteNotChanged : (dev->mute == mute); deviceNotReady = deviceNotReady ? deviceNotReady : !dev->IsReady(); continue; } @@ -932,9 +877,9 @@ class VolumeControlImpl : public VolumeControl { if (devices.empty()) { log::debug( - "No need to update mute for group id: {} . muteNotChanged: {}, " - "deviceNotReady: {}", - group_id, muteNotChanged, deviceNotReady); + "No need to update mute for group id: {} . muteNotChanged: {}, " + "deviceNotReady: {}", + group_id, muteNotChanged, deviceNotReady); return; } @@ -954,23 +899,21 @@ class VolumeControlImpl : public VolumeControl { MuteUnmute(addr_or_group_id, false /* mute */); } - void SetVolume(std::variant addr_or_group_id, - uint8_t volume) override { + void SetVolume(std::variant addr_or_group_id, uint8_t volume) override { std::vector arg({volume}); uint8_t opcode = kControlPointOpcodeSetAbsoluteVolume; if (std::holds_alternative(addr_or_group_id)) { log::debug("Address: {}:", std::get(addr_or_group_id)); - VolumeControlDevice* dev = volume_control_devices_.FindByAddress( - std::get(addr_or_group_id)); + VolumeControlDevice* dev = + volume_control_devices_.FindByAddress(std::get(addr_or_group_id)); if (dev != nullptr) { log::debug("Address: {}: isReady: {}", dev->address, dev->IsReady()); if (dev->IsReady() && (dev->volume != volume)) { std::vector devices = {dev->address}; - RemovePendingVolumeControlOperations( - devices, bluetooth::groups::kGroupUnknown); - PrepareVolumeControlOperation( - devices, bluetooth::groups::kGroupUnknown, false, opcode, arg); + RemovePendingVolumeControlOperations(devices, bluetooth::groups::kGroupUnknown); + PrepareVolumeControlOperation(devices, bluetooth::groups::kGroupUnknown, false, opcode, + arg); } } } else { @@ -1001,8 +944,7 @@ class VolumeControlImpl : public VolumeControl { if (!dev->IsReady() || (dev->volume == volume)) { it = devices.erase(it); - volumeNotChanged = - volumeNotChanged ? volumeNotChanged : (dev->volume == volume); + volumeNotChanged = volumeNotChanged ? volumeNotChanged : (dev->volume == volume); deviceNotReady = deviceNotReady ? deviceNotReady : !dev->IsReady(); continue; } @@ -1012,9 +954,9 @@ class VolumeControlImpl : public VolumeControl { if (devices.empty()) { log::debug( - "No need to update volume for group id: {} . volumeNotChanged: {}, " - "deviceNotReady: {}", - group_id, volumeNotChanged, deviceNotReady); + "No need to update volume for group id: {} . volumeNotChanged: {}, " + "deviceNotReady: {}", + group_id, volumeNotChanged, deviceNotReady); return; } @@ -1026,46 +968,38 @@ class VolumeControlImpl : public VolumeControl { } /* Methods to operate on Volume Control Offset Service (VOCS) */ - void GetExtAudioOutVolumeOffset(const RawAddress& address, - uint8_t ext_output_id) override { - VolumeControlDevice* device = - volume_control_devices_.FindByAddress(address); + void GetExtAudioOutVolumeOffset(const RawAddress& address, uint8_t ext_output_id) override { + VolumeControlDevice* device = volume_control_devices_.FindByAddress(address); if (!device) { log::error("no such device!"); return; } - device->GetExtAudioOutVolumeOffset(ext_output_id, chrc_read_callback_static, - nullptr); + device->GetExtAudioOutVolumeOffset(ext_output_id, chrc_read_callback_static, nullptr); } - void SetExtAudioOutVolumeOffset(const RawAddress& address, - uint8_t ext_output_id, + void SetExtAudioOutVolumeOffset(const RawAddress& address, uint8_t ext_output_id, int16_t offset_val) override { std::vector arg(2); uint8_t* ptr = arg.data(); UINT16_TO_STREAM(ptr, offset_val); - ext_audio_out_control_point_helper( - address, ext_output_id, kVolumeOffsetControlPointOpcodeSet, &arg); + ext_audio_out_control_point_helper(address, ext_output_id, kVolumeOffsetControlPointOpcodeSet, + &arg); } - void GetExtAudioOutLocation(const RawAddress& address, - uint8_t ext_output_id) override { - VolumeControlDevice* device = - volume_control_devices_.FindByAddress(address); + void GetExtAudioOutLocation(const RawAddress& address, uint8_t ext_output_id) override { + VolumeControlDevice* device = volume_control_devices_.FindByAddress(address); if (!device) { log::error("no such device!"); return; } - device->GetExtAudioOutLocation(ext_output_id, chrc_read_callback_static, - nullptr); + device->GetExtAudioOutLocation(ext_output_id, chrc_read_callback_static, nullptr); } void SetExtAudioOutLocation(const RawAddress& address, uint8_t ext_output_id, uint32_t location) override { - VolumeControlDevice* device = - volume_control_devices_.FindByAddress(address); + VolumeControlDevice* device = volume_control_devices_.FindByAddress(address); if (!device) { log::error("no such device!"); return; @@ -1074,24 +1008,19 @@ class VolumeControlImpl : public VolumeControl { device->SetExtAudioOutLocation(ext_output_id, location); } - void GetExtAudioOutDescription(const RawAddress& address, - uint8_t ext_output_id) override { - VolumeControlDevice* device = - volume_control_devices_.FindByAddress(address); + void GetExtAudioOutDescription(const RawAddress& address, uint8_t ext_output_id) override { + VolumeControlDevice* device = volume_control_devices_.FindByAddress(address); if (!device) { log::error("no such device!"); return; } - device->GetExtAudioOutDescription(ext_output_id, chrc_read_callback_static, - nullptr); + device->GetExtAudioOutDescription(ext_output_id, chrc_read_callback_static, nullptr); } - void SetExtAudioOutDescription(const RawAddress& address, - uint8_t ext_output_id, + void SetExtAudioOutDescription(const RawAddress& address, uint8_t ext_output_id, std::string descr) override { - VolumeControlDevice* device = - volume_control_devices_.FindByAddress(address); + VolumeControlDevice* device = volume_control_devices_.FindByAddress(address); if (!device) { log::error("no such device!"); return; @@ -1108,7 +1037,7 @@ class VolumeControlImpl : public VolumeControl { BTA_GATTC_AppDeregister(gatt_if_); } - private: +private: tGATT_IF gatt_if_; bluetooth::vc::VolumeControlCallbacks* callbacks_; VolumeControlDevices volume_control_devices_; @@ -1120,29 +1049,26 @@ class VolumeControlImpl : public VolumeControl { static constexpr uint64_t kOperationMonitorTimeoutMs = 3000; void verify_device_ready(VolumeControlDevice* device, uint16_t handle) { - if (device->IsReady()) return; + if (device->IsReady()) { + return; + } // VerifyReady sets the device_ready flag if all remaining GATT operations // are completed if (device->VerifyReady(handle)) { log::info("Outstanding reads completed."); - callbacks_->OnDeviceAvailable(device->address, - device->audio_offsets.Size()); - callbacks_->OnConnectionState(ConnectionState::CONNECTED, - device->address); + callbacks_->OnDeviceAvailable(device->address, device->audio_offsets.Size()); + callbacks_->OnConnectionState(ConnectionState::CONNECTED, device->address); // once profile connected we can notify current states - callbacks_->OnVolumeStateChanged(device->address, device->volume, - device->mute, false); + callbacks_->OnVolumeStateChanged(device->address, device->volume, device->mute, false); for (auto const& offset : device->audio_offsets.volume_offsets) { - callbacks_->OnExtAudioOutVolumeOffsetChanged(device->address, offset.id, - offset.offset); + callbacks_->OnExtAudioOutVolumeOffsetChanged(device->address, offset.id, offset.offset); } - device->EnqueueRemainingRequests(gatt_if_, chrc_read_callback_static, - OnGattWriteCccStatic); + device->EnqueueRemainingRequests(gatt_if_, chrc_read_callback_static, OnGattWriteCccStatic); } } @@ -1151,56 +1077,54 @@ class VolumeControlImpl : public VolumeControl { RemoveDeviceFromOperationList(device->address); - if (notify) - callbacks_->OnConnectionState(ConnectionState::DISCONNECTED, - device->address); + if (notify) { + callbacks_->OnConnectionState(ConnectionState::DISCONNECTED, device->address); + } } - void devices_control_point_helper(std::vector& devices, - uint8_t opcode, - const std::vector* arg, - int operation_id = -1) { + void devices_control_point_helper(std::vector& devices, uint8_t opcode, + const std::vector* arg, int operation_id = -1) { volume_control_devices_.ControlPointOperation( - devices, opcode, arg, - [](uint16_t connection_id, tGATT_STATUS status, uint16_t handle, - uint16_t len, const uint8_t* value, void* data) { - if (instance) - instance->OnWriteControlResponse(connection_id, status, handle, - data); - }, - INT_TO_PTR(operation_id)); + devices, opcode, arg, + [](uint16_t connection_id, tGATT_STATUS status, uint16_t handle, uint16_t len, + const uint8_t* value, void* data) { + if (instance) { + instance->OnWriteControlResponse(connection_id, status, handle, data); + } + }, + INT_TO_PTR(operation_id)); } - void ext_audio_out_control_point_helper(const RawAddress& address, - uint8_t ext_output_id, uint8_t opcode, - const std::vector* arg) { + void ext_audio_out_control_point_helper(const RawAddress& address, uint8_t ext_output_id, + uint8_t opcode, const std::vector* arg) { log::info("{} id=0x{:x} op=0x{:x}", address, ext_output_id, opcode); - VolumeControlDevice* device = - volume_control_devices_.FindByAddress(address); + VolumeControlDevice* device = volume_control_devices_.FindByAddress(address); if (!device) { log::error("no such device!"); return; } device->ExtAudioOutControlPointOperation( - ext_output_id, opcode, arg, - [](uint16_t connection_id, tGATT_STATUS status, uint16_t handle, - uint16_t len, const uint8_t* value, void* data) { - if (instance) - instance->OnExtAudioOutCPWrite(connection_id, status, handle, data); - }, - nullptr); + ext_output_id, opcode, arg, + [](uint16_t connection_id, tGATT_STATUS status, uint16_t handle, uint16_t len, + const uint8_t* value, void* data) { + if (instance) { + instance->OnExtAudioOutCPWrite(connection_id, status, handle, data); + } + }, + nullptr); } void gattc_callback(tBTA_GATTC_EVT event, tBTA_GATTC* p_data) { log::info("event = {}", static_cast(event)); - if (p_data == nullptr) return; + if (p_data == nullptr) { + return; + } switch (event) { case BTA_GATTC_OPEN_EVT: { tBTA_GATTC_OPEN& o = p_data->open; - OnGattConnected(o.status, o.conn_id, o.client_if, o.remote_bda, - o.transport, o.mtu); + OnGattConnected(o.status, o.conn_id, o.client_if, o.remote_bda, o.transport, o.mtu); } break; @@ -1210,15 +1134,14 @@ class VolumeControlImpl : public VolumeControl { } break; case BTA_GATTC_SEARCH_CMPL_EVT: - OnServiceSearchComplete(p_data->search_cmpl.conn_id, - p_data->search_cmpl.status); + OnServiceSearchComplete(p_data->search_cmpl.conn_id, p_data->search_cmpl.status); break; case BTA_GATTC_NOTIF_EVT: { tBTA_GATTC_NOTIFY& n = p_data->notify; if (!n.is_notify || n.len > GATT_MAX_ATTR_LEN) { - log::error("rejected BTA_GATTC_NOTIF_EVT. is_notify={}, len={}", - n.is_notify, static_cast(n.len)); + log::error("rejected BTA_GATTC_NOTIF_EVT. is_notify={}, len={}", n.is_notify, + static_cast(n.len)); break; } OnNotificationEvent(n.conn_id, n.handle, n.len, n.value); @@ -1248,15 +1171,16 @@ class VolumeControlImpl : public VolumeControl { } static void gattc_callback_static(tBTA_GATTC_EVT event, tBTA_GATTC* p_data) { - if (instance) instance->gattc_callback(event, p_data); + if (instance) { + instance->gattc_callback(event, p_data); + } } - static void chrc_read_callback_static(uint16_t conn_id, tGATT_STATUS status, - uint16_t handle, uint16_t len, - uint8_t* value, void* data) { - if (instance) - instance->OnCharacteristicValueChanged(conn_id, status, handle, len, - value, data, false); + static void chrc_read_callback_static(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, + uint16_t len, uint8_t* value, void* data) { + if (instance) { + instance->OnCharacteristicValueChanged(conn_id, status, handle, len, value, data, false); + } } }; } // namespace @@ -1277,7 +1201,7 @@ bool VolumeControl::IsVolumeControlRunning() { return instance; } VolumeControl* VolumeControl::Get(void) { log::assert_that(instance != nullptr, "assert failed: instance != nullptr"); return instance; -}; +} void VolumeControl::AddFromStorage(const RawAddress& address) { if (!instance) { @@ -1286,7 +1210,7 @@ void VolumeControl::AddFromStorage(const RawAddress& address) { } instance->AddFromStorage(address); -}; +} void VolumeControl::CleanUp() { std::scoped_lock lock(instance_mutex); @@ -1301,11 +1225,13 @@ void VolumeControl::CleanUp() { ptr->CleanUp(); delete ptr; -}; +} void VolumeControl::DebugDump(int fd) { std::scoped_lock lock(instance_mutex); dprintf(fd, "Volume Control Manager:\n"); - if (instance) instance->Dump(fd); + if (instance) { + instance->Dump(fd); + } dprintf(fd, "\n"); } diff --git a/system/bta/vc/vc_test.cc b/system/bta/vc/vc_test.cc index eb6f0423fa6..df9dd520919 100644 --- a/system/bta/vc/vc_test.cc +++ b/system/bta/vc/vc_test.cc @@ -58,54 +58,42 @@ using testing::WithArg; RawAddress GetTestAddress(int index) { EXPECT_LT(index, UINT8_MAX); - RawAddress result = { - {0xC0, 0xDE, 0xC0, 0xDE, 0x00, static_cast(index)}}; + RawAddress result = {{0xC0, 0xDE, 0xC0, 0xDE, 0x00, static_cast(index)}}; return result; } class MockVolumeControlCallbacks : public VolumeControlCallbacks { - public: +public: MockVolumeControlCallbacks() = default; MockVolumeControlCallbacks(const MockVolumeControlCallbacks&) = delete; - MockVolumeControlCallbacks& operator=(const MockVolumeControlCallbacks&) = - delete; + MockVolumeControlCallbacks& operator=(const MockVolumeControlCallbacks&) = delete; ~MockVolumeControlCallbacks() override = default; - MOCK_METHOD((void), OnConnectionState, - (ConnectionState state, const RawAddress& address), (override)); - MOCK_METHOD((void), OnDeviceAvailable, - (const RawAddress& address, uint8_t num_offset), (override)); + MOCK_METHOD((void), OnConnectionState, (ConnectionState state, const RawAddress& address), + (override)); + MOCK_METHOD((void), OnDeviceAvailable, (const RawAddress& address, uint8_t num_offset), + (override)); MOCK_METHOD((void), OnVolumeStateChanged, - (const RawAddress& address, uint8_t volume, bool mute, - bool isAutonomous), + (const RawAddress& address, uint8_t volume, bool mute, bool isAutonomous), (override)); MOCK_METHOD((void), OnGroupVolumeStateChanged, - (int group_id, uint8_t volume, bool mute, bool isAutonomous), - (override)); + (int group_id, uint8_t volume, bool mute, bool isAutonomous), (override)); MOCK_METHOD((void), OnExtAudioOutVolumeOffsetChanged, - (const RawAddress& address, uint8_t ext_output_id, - int16_t offset), - (override)); + (const RawAddress& address, uint8_t ext_output_id, int16_t offset), (override)); MOCK_METHOD((void), OnExtAudioOutLocationChanged, - (const RawAddress& address, uint8_t ext_output_id, - uint32_t location), - (override)); + (const RawAddress& address, uint8_t ext_output_id, uint32_t location), (override)); MOCK_METHOD((void), OnExtAudioOutDescriptionChanged, - (const RawAddress& address, uint8_t ext_output_id, - std::string descr), - (override)); + (const RawAddress& address, uint8_t ext_output_id, std::string descr), (override)); }; class VolumeControlTest : public ::testing::Test { - private: - void set_sample_database(uint16_t conn_id, bool vcs, bool vcs_broken, - bool aics, bool aics_broken, bool vocs, - bool vocs_broken) { +private: + void set_sample_database(uint16_t conn_id, bool vcs, bool vcs_broken, bool aics, bool aics_broken, + bool vocs, bool vocs_broken) { gatt::DatabaseBuilder builder; builder.AddService(0x0001, 0x0003, Uuid::From16Bit(0x1800), true); - builder.AddCharacteristic(0x0002, 0x0003, Uuid::From16Bit(0x2a00), - GATT_CHAR_PROP_BIT_READ); + builder.AddCharacteristic(0x0002, 0x0003, Uuid::From16Bit(0x2a00), GATT_CHAR_PROP_BIT_READ); /* 0x0004-0x000f RFU */ if (vcs) { /* VCS */ @@ -118,17 +106,14 @@ class VolumeControlTest : public ::testing::Test { builder.AddIncludedService(0x0014, kVolumeOffsetUuid, 0x0080, 0x008b); } /* 0x0015-0x001f RFU */ - builder.AddCharacteristic( - 0x0020, 0x0021, kVolumeControlStateUuid, - GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY); - builder.AddDescriptor(0x0022, - Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); + builder.AddCharacteristic(0x0020, 0x0021, kVolumeControlStateUuid, + GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY); + builder.AddDescriptor(0x0022, Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); if (!vcs_broken) { builder.AddCharacteristic(0x0023, 0x0024, kVolumeControlPointUuid, GATT_CHAR_PROP_BIT_WRITE); } - builder.AddCharacteristic(0x0025, 0x0026, kVolumeFlagsUuid, - GATT_CHAR_PROP_BIT_READ); + builder.AddCharacteristic(0x0025, 0x0026, kVolumeFlagsUuid, GATT_CHAR_PROP_BIT_READ); /* 0x0027-0x002f RFU */ if (aics) { /* TODO Place holder for AICS */ @@ -136,108 +121,97 @@ class VolumeControlTest : public ::testing::Test { if (vocs) { /* VOCS 1st instance */ builder.AddService(0x0070, 0x0079, kVolumeOffsetUuid, false); - builder.AddCharacteristic( - 0x0071, 0x0072, kVolumeOffsetStateUuid, - GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY); - builder.AddDescriptor(0x0073, - Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); + builder.AddCharacteristic(0x0071, 0x0072, kVolumeOffsetStateUuid, + GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY); + builder.AddDescriptor(0x0073, Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); builder.AddCharacteristic(0x0074, 0x0075, kVolumeOffsetLocationUuid, GATT_CHAR_PROP_BIT_READ); builder.AddCharacteristic(0x0076, 0x0077, kVolumeOffsetControlPointUuid, GATT_CHAR_PROP_BIT_WRITE); - builder.AddCharacteristic(0x0078, 0x0079, - kVolumeOffsetOutputDescriptionUuid, + builder.AddCharacteristic(0x0078, 0x0079, kVolumeOffsetOutputDescriptionUuid, GATT_CHAR_PROP_BIT_READ); /* 0x007a-0x007f RFU */ /* VOCS 2nd instance */ builder.AddService(0x0080, 0x008b, kVolumeOffsetUuid, false); - builder.AddCharacteristic( - 0x0081, 0x0082, kVolumeOffsetStateUuid, - GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY); - builder.AddDescriptor(0x0083, - Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); + builder.AddCharacteristic(0x0081, 0x0082, kVolumeOffsetStateUuid, + GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_NOTIFY); + builder.AddDescriptor(0x0083, Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); if (!vocs_broken) { builder.AddCharacteristic(0x0084, 0x0085, kVolumeOffsetLocationUuid, - GATT_CHAR_PROP_BIT_READ | - GATT_CHAR_PROP_BIT_WRITE_NR | - GATT_CHAR_PROP_BIT_NOTIFY); - builder.AddDescriptor(0x0086, - Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); + GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_WRITE_NR | + GATT_CHAR_PROP_BIT_NOTIFY); + builder.AddDescriptor(0x0086, Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); } builder.AddCharacteristic(0x0087, 0x0088, kVolumeOffsetControlPointUuid, GATT_CHAR_PROP_BIT_WRITE); builder.AddCharacteristic( - 0x0089, 0x008a, kVolumeOffsetOutputDescriptionUuid, - GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_WRITE_NR | - GATT_CHAR_PROP_BIT_NOTIFY); - builder.AddDescriptor(0x008b, - Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); + 0x0089, 0x008a, kVolumeOffsetOutputDescriptionUuid, + GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_WRITE_NR | GATT_CHAR_PROP_BIT_NOTIFY); + builder.AddDescriptor(0x008b, Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); } } /* 0x008c-0x008f RFU */ /* GATTS */ - builder.AddService(0x0090, 0x0093, - Uuid::From16Bit(UUID_SERVCLASS_GATT_SERVER), true); - builder.AddCharacteristic(0x0091, 0x0092, - Uuid::From16Bit(GATT_UUID_GATT_SRV_CHGD), + builder.AddService(0x0090, 0x0093, Uuid::From16Bit(UUID_SERVCLASS_GATT_SERVER), true); + builder.AddCharacteristic(0x0091, 0x0092, Uuid::From16Bit(GATT_UUID_GATT_SRV_CHGD), GATT_CHAR_PROP_BIT_NOTIFY); - builder.AddDescriptor(0x0093, - Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); + builder.AddDescriptor(0x0093, Uuid::From16Bit(GATT_UUID_CHAR_CLIENT_CONFIG)); services_map[conn_id] = builder.Build().Services(); ON_CALL(gatt_queue, ReadCharacteristic(conn_id, _, _, _)) - .WillByDefault(Invoke([&](uint16_t conn_id, uint16_t handle, - GATT_READ_OP_CB cb, void* cb_data) -> void { - std::vector value; - - switch (handle) { - case 0x0003: - /* device name */ - value.resize(20); - break; - - case 0x0021: - /* volume state */ - value.resize(3); - break; - - case 0x0026: - /* volume flags */ - value.resize(1); - break; - - case 0x0072: // 1st VOCS instance - case 0x0082: // 2nd VOCS instance - /* offset state */ - value.resize(3); - break; - - case 0x0075: // 1st VOCS instance - case 0x0085: // 2nd VOCS instance - /* offset location */ - value.resize(4); - break; - - case 0x0079: // 1st VOCS instance - case 0x008a: // 2nd VOCS instance - /* offset output description */ - value.resize(10); - break; - - default: - ASSERT_TRUE(false); - return; - } - - if (do_not_respond_to_reads) return; - cb(conn_id, GATT_SUCCESS, handle, value.size(), value.data(), - cb_data); - })); + .WillByDefault(Invoke([&](uint16_t conn_id, uint16_t handle, GATT_READ_OP_CB cb, + void* cb_data) -> void { + std::vector value; + + switch (handle) { + case 0x0003: + /* device name */ + value.resize(20); + break; + + case 0x0021: + /* volume state */ + value.resize(3); + break; + + case 0x0026: + /* volume flags */ + value.resize(1); + break; + + case 0x0072: // 1st VOCS instance + case 0x0082: // 2nd VOCS instance + /* offset state */ + value.resize(3); + break; + + case 0x0075: // 1st VOCS instance + case 0x0085: // 2nd VOCS instance + /* offset location */ + value.resize(4); + break; + + case 0x0079: // 1st VOCS instance + case 0x008a: // 2nd VOCS instance + /* offset output description */ + value.resize(10); + break; + + default: + FAIL(); + return; + } + + if (do_not_respond_to_reads) { + return; + } + cb(conn_id, GATT_SUCCESS, handle, value.size(), value.data(), cb_data); + })); } - protected: +protected: bool do_not_respond_to_reads = false; void SetUp(void) override { @@ -248,30 +222,27 @@ class VolumeControlTest : public ::testing::Test { callbacks.reset(new MockVolumeControlCallbacks()); reset_mock_function_count_map(); - ON_CALL(btm_interface, IsLinkKeyKnown(_, _)) - .WillByDefault(DoAll(Return(true))); + ON_CALL(btm_interface, IsLinkKeyKnown(_, _)).WillByDefault(DoAll(Return(true))); // default action for GetCharacteristic function call ON_CALL(gatt_interface, GetCharacteristic(_, _)) - .WillByDefault( - Invoke([&](uint16_t conn_id, - uint16_t handle) -> const gatt::Characteristic* { - std::list& services = services_map[conn_id]; - for (auto const& service : services) { - for (auto const& characteristic : service.characteristics) { - if (characteristic.value_handle == handle) { - return &characteristic; - } - } - } - - return nullptr; - })); + .WillByDefault( + Invoke([&](uint16_t conn_id, uint16_t handle) -> const gatt::Characteristic* { + std::list& services = services_map[conn_id]; + for (auto const& service : services) { + for (auto const& characteristic : service.characteristics) { + if (characteristic.value_handle == handle) { + return &characteristic; + } + } + } + + return nullptr; + })); // default action for GetOwningService function call ON_CALL(gatt_interface, GetOwningService(_, _)) - .WillByDefault(Invoke( - [&](uint16_t conn_id, uint16_t handle) -> const gatt::Service* { + .WillByDefault(Invoke([&](uint16_t conn_id, uint16_t handle) -> const gatt::Service* { std::list& services = services_map[conn_id]; for (auto const& service : services) { if (service.handle <= handle && service.end_handle >= handle) { @@ -284,28 +255,26 @@ class VolumeControlTest : public ::testing::Test { // default action for GetServices function call ON_CALL(gatt_interface, GetServices(_)) - .WillByDefault(WithArg<0>( - Invoke([&](uint16_t conn_id) -> std::list* { + .WillByDefault(WithArg<0>(Invoke([&](uint16_t conn_id) -> std::list* { return &services_map[conn_id]; }))); // default action for RegisterForNotifications function call ON_CALL(gatt_interface, RegisterForNotifications(gatt_if, _, _)) - .WillByDefault(Return(GATT_SUCCESS)); + .WillByDefault(Return(GATT_SUCCESS)); // default action for DeregisterForNotifications function call ON_CALL(gatt_interface, DeregisterForNotifications(gatt_if, _, _)) - .WillByDefault(Return(GATT_SUCCESS)); + .WillByDefault(Return(GATT_SUCCESS)); // default action for WriteDescriptor function call ON_CALL(gatt_queue, WriteDescriptor(_, _, _, _, _, _)) - .WillByDefault( - Invoke([](uint16_t conn_id, uint16_t handle, - std::vector value, tGATT_WRITE_TYPE write_type, - GATT_WRITE_OP_CB cb, void* cb_data) -> void { - if (cb) - cb(conn_id, GATT_SUCCESS, handle, value.size(), value.data(), - cb_data); + .WillByDefault(Invoke([](uint16_t conn_id, uint16_t handle, std::vector value, + tGATT_WRITE_TYPE write_type, GATT_WRITE_OP_CB cb, + void* cb_data) -> void { + if (cb) { + cb(conn_id, GATT_SUCCESS, handle, value.size(), value.data(), cb_data); + } })); } @@ -320,8 +289,7 @@ class VolumeControlTest : public ::testing::Test { void TestAppRegister(void) { BtaAppRegisterCallback app_register_callback; EXPECT_CALL(gatt_interface, AppRegister(_, _, _)) - .WillOnce(DoAll(SaveArg<0>(&gatt_callback), - SaveArg<1>(&app_register_callback))); + .WillOnce(DoAll(SaveArg<0>(&gatt_callback), SaveArg<1>(&app_register_callback))); VolumeControl::Initialize(callbacks.get(), base::DoNothing()); ASSERT_TRUE(gatt_callback); ASSERT_TRUE(app_register_callback); @@ -338,11 +306,9 @@ class VolumeControlTest : public ::testing::Test { void TestConnect(const RawAddress& address) { // by default indicate link as encrypted - ON_CALL(btm_interface, BTM_IsEncrypted(address, _)) - .WillByDefault(DoAll(Return(true))); + ON_CALL(btm_interface, BTM_IsEncrypted(address, _)).WillByDefault(DoAll(Return(true))); - EXPECT_CALL(gatt_interface, - Open(gatt_if, address, BTM_BLE_DIRECT_CONNECTION, true)); + EXPECT_CALL(gatt_interface, Open(gatt_if, address, BTM_BLE_DIRECT_CONNECTION, true)); VolumeControl::Get()->Connect(address); Mock::VerifyAndClearExpectations(&gatt_interface); } @@ -370,11 +336,9 @@ class VolumeControlTest : public ::testing::Test { void TestAddFromStorage(const RawAddress& address) { // by default indicate link as encrypted - ON_CALL(btm_interface, BTM_IsEncrypted(address, _)) - .WillByDefault(DoAll(Return(true))); + ON_CALL(btm_interface, BTM_IsEncrypted(address, _)).WillByDefault(DoAll(Return(true))); - EXPECT_CALL(gatt_interface, - Open(gatt_if, address, BTM_BLE_DIRECT_CONNECTION, true)); + EXPECT_CALL(gatt_interface, Open(gatt_if, address, BTM_BLE_DIRECT_CONNECTION, true)); VolumeControl::Get()->AddFromStorage(address); } @@ -385,19 +349,16 @@ class VolumeControlTest : public ::testing::Test { TestConnect(address); GetConnectedEvent(address, conn_id); - EXPECT_CALL(gatt_queue, WriteDescriptor(_, _, _, _, _, _)) - .WillRepeatedly(DoDefault()); - EXPECT_CALL(gatt_interface, RegisterForNotifications(_, _, _)) - .WillRepeatedly(DoDefault()); + EXPECT_CALL(gatt_queue, WriteDescriptor(_, _, _, _, _, _)).WillRepeatedly(DoDefault()); + EXPECT_CALL(gatt_interface, RegisterForNotifications(_, _, _)).WillRepeatedly(DoDefault()); std::vector notify_value({0x01, 0x00}); for (auto const& handles : handle_pairs) { - EXPECT_CALL(gatt_queue, WriteDescriptor(conn_id, handles.second, - notify_value, GATT_WRITE, _, _)) - .WillOnce(DoDefault()); - EXPECT_CALL(gatt_interface, - RegisterForNotifications(gatt_if, address, handles.first)) - .WillOnce(DoDefault()); + EXPECT_CALL(gatt_queue, + WriteDescriptor(conn_id, handles.second, notify_value, GATT_WRITE, _, _)) + .WillOnce(DoDefault()); + EXPECT_CALL(gatt_interface, RegisterForNotifications(gatt_if, address, handles.first)) + .WillOnce(DoDefault()); } GetSearchCompleteEvent(conn_id); @@ -411,11 +372,9 @@ class VolumeControlTest : public ::testing::Test { TestConnect(address); GetConnectedEvent(address, conn_id); - EXPECT_CALL(gatt_queue, ReadCharacteristic(conn_id, _, _, _)) - .WillRepeatedly(DoDefault()); + EXPECT_CALL(gatt_queue, ReadCharacteristic(conn_id, _, _, _)).WillRepeatedly(DoDefault()); for (auto const& handle : handles) { - EXPECT_CALL(gatt_queue, ReadCharacteristic(conn_id, handle, _, _)) - .WillOnce(DoDefault()); + EXPECT_CALL(gatt_queue, ReadCharacteristic(conn_id, handle, _, _)).WillOnce(DoDefault()); } GetSearchCompleteEvent(conn_id); @@ -438,11 +397,11 @@ class VolumeControlTest : public ::testing::Test { void GetDisconnectedEvent(const RawAddress& address, uint16_t conn_id) { tBTA_GATTC_CLOSE event_data = { - .conn_id = conn_id, - .status = GATT_SUCCESS, - .client_if = gatt_if, - .remote_bda = address, - .reason = GATT_CONN_TERMINATE_PEER_USER, + .conn_id = conn_id, + .status = GATT_SUCCESS, + .client_if = gatt_if, + .remote_bda = address, + .reason = GATT_CONN_TERMINATE_PEER_USER, }; gatt_callback(BTA_GATTC_CLOSE_EVT, (tBTA_GATTC*)&event_data); @@ -450,8 +409,8 @@ class VolumeControlTest : public ::testing::Test { void GetSearchCompleteEvent(uint16_t conn_id) { tBTA_GATTC_SEARCH_CMPL event_data = { - .conn_id = conn_id, - .status = GATT_SUCCESS, + .conn_id = conn_id, + .status = GATT_SUCCESS, }; gatt_callback(BTA_GATTC_SEARCH_CMPL_EVT, (tBTA_GATTC*)&event_data); @@ -466,25 +425,21 @@ class VolumeControlTest : public ::testing::Test { } void SetEncryptionResult(const RawAddress& address, bool success) { - ON_CALL(btm_interface, BTM_IsEncrypted(address, _)) - .WillByDefault(DoAll(Return(false))); - ON_CALL(btm_interface, IsLinkKeyKnown(address, _)) - .WillByDefault(DoAll(Return(true))); + ON_CALL(btm_interface, BTM_IsEncrypted(address, _)).WillByDefault(DoAll(Return(false))); + ON_CALL(btm_interface, IsLinkKeyKnown(address, _)).WillByDefault(DoAll(Return(true))); ON_CALL(btm_interface, SetEncryption(address, _, _, _, BTM_BLE_SEC_ENCRYPT)) - .WillByDefault(Invoke( - [&success, this](const RawAddress& bd_addr, tBT_TRANSPORT transport, - tBTM_SEC_CALLBACK* p_callback, void* p_ref_data, - tBTM_BLE_SEC_ACT sec_act) -> tBTM_STATUS { - if (p_callback) { - p_callback(bd_addr, transport, p_ref_data, - success ? BTM_SUCCESS : BTM_FAILED_ON_SECURITY); - } - GetEncryptionCompleteEvt(bd_addr); - return BTM_SUCCESS; - })); - EXPECT_CALL(btm_interface, - SetEncryption(address, _, _, _, BTM_BLE_SEC_ENCRYPT)) - .Times(1); + .WillByDefault( + Invoke([&success, this](const RawAddress& bd_addr, tBT_TRANSPORT transport, + tBTM_SEC_CALLBACK* p_callback, void* p_ref_data, + tBTM_BLE_SEC_ACT sec_act) -> tBTM_STATUS { + if (p_callback) { + p_callback(bd_addr, transport, p_ref_data, + success ? BTM_SUCCESS : BTM_FAILED_ON_SECURITY); + } + GetEncryptionCompleteEvt(bd_addr); + return BTM_SUCCESS; + })); + EXPECT_CALL(btm_interface, SetEncryption(address, _, _, _, BTM_BLE_SEC_ENCRYPT)).Times(1); } void SetSampleDatabaseVCS(uint16_t conn_id) { @@ -521,20 +476,16 @@ class VolumeControlTest : public ::testing::Test { std::map> services_map; }; -TEST_F(VolumeControlTest, test_get_uninitialized) { - ASSERT_DEATH(VolumeControl::Get(), ""); -} +TEST_F(VolumeControlTest, test_get_uninitialized) { ASSERT_DEATH(VolumeControl::Get(), ""); } TEST_F(VolumeControlTest, test_initialize) { bool init_cb_called = false; BtaAppRegisterCallback app_register_callback; EXPECT_CALL(gatt_interface, AppRegister(_, _, _)) - .WillOnce(DoAll(SaveArg<0>(&gatt_callback), - SaveArg<1>(&app_register_callback))); + .WillOnce(DoAll(SaveArg<0>(&gatt_callback), SaveArg<1>(&app_register_callback))); VolumeControl::Initialize( - callbacks.get(), - base::Bind([](bool* init_cb_called) { *init_cb_called = true; }, - &init_cb_called)); + callbacks.get(), + base::Bind([](bool* init_cb_called) { *init_cb_called = true; }, &init_cb_called)); ASSERT_TRUE(gatt_callback); ASSERT_TRUE(app_register_callback); app_register_callback.Run(gatt_if, GATT_SUCCESS); @@ -584,18 +535,13 @@ TEST_F(VolumeControlTest, test_connect_after_remove) { GetConnectedEvent(test_address, conn_id); Mock::VerifyAndClearExpectations(callbacks.get()); - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::DISCONNECTED, test_address)) - .Times(1); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::DISCONNECTED, test_address)).Times(1); TestRemove(test_address, conn_id); Mock::VerifyAndClearExpectations(callbacks.get()); - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::DISCONNECTED, test_address)) - .Times(1); - ON_CALL(btm_interface, IsLinkKeyKnown(_, _)) - .WillByDefault(DoAll(Return(false))); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::DISCONNECTED, test_address)).Times(1); + ON_CALL(btm_interface, IsLinkKeyKnown(_, _)).WillByDefault(DoAll(Return(false))); VolumeControl::Get()->Connect(test_address); Mock::VerifyAndClearExpectations(callbacks.get()); @@ -610,38 +556,33 @@ TEST_F(VolumeControlTest, test_reconnect_after_interrupted_discovery) { SetSampleDatabaseVOCS(1); TestAppRegister(); TestConnect(test_address); - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::CONNECTED, test_address)) - .Times(0); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::CONNECTED, test_address)).Times(0); EXPECT_CALL(*callbacks, OnDeviceAvailable(test_address, 2)).Times(0); GetConnectedEvent(test_address, 1); Mock::VerifyAndClearExpectations(callbacks.get()); // Remote disconnects in the middle of the service discovery - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::DISCONNECTED, test_address)); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::DISCONNECTED, test_address)); GetDisconnectedEvent(test_address, 1); Mock::VerifyAndClearExpectations(callbacks.get()); // This time let the service discovery pass ON_CALL(gatt_interface, ServiceSearchRequest(_, _)) - .WillByDefault(Invoke( - [&](uint16_t conn_id, const bluetooth::Uuid* p_srvc_uuid) -> void { - if (*p_srvc_uuid == kVolumeControlUuid) + .WillByDefault(Invoke([&](uint16_t conn_id, const bluetooth::Uuid* p_srvc_uuid) -> void { + if (*p_srvc_uuid == kVolumeControlUuid) { GetSearchCompleteEvent(conn_id); + } })); // Remote is being connected by another GATT client - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::CONNECTED, test_address)); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::CONNECTED, test_address)); EXPECT_CALL(*callbacks, OnDeviceAvailable(test_address, 2)); GetConnectedEvent(test_address, 1); Mock::VerifyAndClearExpectations(callbacks.get()); // Request connect when the remote was already connected by another service EXPECT_CALL(*callbacks, OnDeviceAvailable(test_address, 2)).Times(0); - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::CONNECTED, test_address)); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::CONNECTED, test_address)); VolumeControl::Get()->Connect(test_address); // The GetConnectedEvent(test_address, 1); should not be triggered here, since // GATT implementation will not send this event for the already connected @@ -677,15 +618,12 @@ TEST_F(VolumeControlTest, test_reconnect_after_timeout) { SetSampleDatabaseVOCS(1); TestAppRegister(); - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::CONNECTED, address)) - .Times(0); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::CONNECTED, address)).Times(0); TestConnect(address); // Disconnect not connected device - upper layer times out and needs a // disconnection event to leave the transient Connecting state - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::DISCONNECTED, address)); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::DISCONNECTED, address)); EXPECT_CALL(gatt_interface, CancelOpen(gatt_if, address, false)).Times(0); TestDisconnect(address, 0); @@ -694,21 +632,19 @@ TEST_F(VolumeControlTest, test_reconnect_after_timeout) { // native is still doing background or opportunistic connect. Let the remote // device reconnect now. ON_CALL(gatt_interface, ServiceSearchRequest(_, _)) - .WillByDefault(Invoke( - [&](uint16_t conn_id, const bluetooth::Uuid* p_srvc_uuid) -> void { - if (*p_srvc_uuid == kVolumeControlUuid) + .WillByDefault(Invoke([&](uint16_t conn_id, const bluetooth::Uuid* p_srvc_uuid) -> void { + if (*p_srvc_uuid == kVolumeControlUuid) { GetSearchCompleteEvent(conn_id); + } })); - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::CONNECTED, address)); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::CONNECTED, address)); EXPECT_CALL(*callbacks, OnDeviceAvailable(address, 2)); GetConnectedEvent(address, 1); Mock::VerifyAndClearExpectations(callbacks.get()); // Make sure that the upper layer gets the disconnection event even if not // connecting actively anymore due to the mentioned time-out mechanism. - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::DISCONNECTED, address)); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::DISCONNECTED, address)); GetDisconnectedEvent(address, 1); Mock::VerifyAndClearExpectations(callbacks.get()); TestAppUnregister(); @@ -724,8 +660,7 @@ TEST_F(VolumeControlTest, test_remove_non_connected) { const RawAddress test_address = GetTestAddress(0); TestAppRegister(); TestConnect(test_address); - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::DISCONNECTED, test_address)); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::DISCONNECTED, test_address)); TestRemove(test_address, 0); TestAppUnregister(); } @@ -735,8 +670,7 @@ TEST_F(VolumeControlTest, test_remove_connected) { TestAppRegister(); TestConnect(test_address); GetConnectedEvent(test_address, 1); - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::DISCONNECTED, test_address)); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::DISCONNECTED, test_address)); TestDisconnect(test_address, 1); TestAppUnregister(); } @@ -745,8 +679,7 @@ TEST_F(VolumeControlTest, test_disconnect_non_connected) { const RawAddress test_address = GetTestAddress(0); TestAppRegister(); TestConnect(test_address); - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::DISCONNECTED, test_address)); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::DISCONNECTED, test_address)); TestDisconnect(test_address, 0); TestAppUnregister(); } @@ -756,8 +689,7 @@ TEST_F(VolumeControlTest, test_disconnect_connected) { TestAppRegister(); TestConnect(test_address); GetConnectedEvent(test_address, 1); - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::DISCONNECTED, test_address)); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::DISCONNECTED, test_address)); TestDisconnect(test_address, 1); TestAppUnregister(); } @@ -767,8 +699,7 @@ TEST_F(VolumeControlTest, test_disconnected) { TestAppRegister(); TestConnect(test_address); GetConnectedEvent(test_address, 1); - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::DISCONNECTED, test_address)); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::DISCONNECTED, test_address)); GetDisconnectedEvent(test_address, 1); TestAppUnregister(); } @@ -779,9 +710,7 @@ TEST_F(VolumeControlTest, test_disconnected_while_autoconnect) { TestAddFromStorage(test_address); GetConnectedEvent(test_address, 1); // autoconnect - don't indicate disconnection - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::DISCONNECTED, test_address)) - .Times(0); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::DISCONNECTED, test_address)).Times(0); GetDisconnectedEvent(test_address, 1); TestAppUnregister(); } @@ -791,16 +720,12 @@ TEST_F(VolumeControlTest, test_disconnect_when_link_key_gone) { TestAppRegister(); TestAddFromStorage(test_address); - ON_CALL(btm_interface, BTM_IsEncrypted(test_address, _)) - .WillByDefault(DoAll(Return(false))); - ON_CALL(btm_interface, - SetEncryption(test_address, _, _, _, BTM_BLE_SEC_ENCRYPT)) - .WillByDefault(Return(BTM_ERR_KEY_MISSING)); + ON_CALL(btm_interface, BTM_IsEncrypted(test_address, _)).WillByDefault(DoAll(Return(false))); + ON_CALL(btm_interface, SetEncryption(test_address, _, _, _, BTM_BLE_SEC_ENCRYPT)) + .WillByDefault(Return(BTM_ERR_KEY_MISSING)); // autoconnect - don't indicate disconnection - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::DISCONNECTED, test_address)) - .Times(0); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::DISCONNECTED, test_address)).Times(0); EXPECT_CALL(gatt_interface, Close(1)); GetConnectedEvent(test_address, 1); Mock::VerifyAndClearExpectations(&btm_interface); @@ -813,9 +738,7 @@ TEST_F(VolumeControlTest, test_reconnect_after_encryption_failed) { TestAddFromStorage(test_address); SetEncryptionResult(test_address, false); // autoconnect - don't indicate disconnection - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::DISCONNECTED, test_address)) - .Times(0); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::DISCONNECTED, test_address)).Times(0); GetConnectedEvent(test_address, 1); Mock::VerifyAndClearExpectations(&btm_interface); SetEncryptionResult(test_address, true); @@ -829,28 +752,21 @@ TEST_F(VolumeControlTest, test_service_discovery_completed_before_encryption) { TestAppRegister(); TestConnect(test_address); - ON_CALL(btm_interface, BTM_IsEncrypted(test_address, _)) - .WillByDefault(DoAll(Return(false))); - ON_CALL(btm_interface, IsLinkKeyKnown(test_address, _)) - .WillByDefault(DoAll(Return(true))); + ON_CALL(btm_interface, BTM_IsEncrypted(test_address, _)).WillByDefault(DoAll(Return(false))); + ON_CALL(btm_interface, IsLinkKeyKnown(test_address, _)).WillByDefault(DoAll(Return(true))); ON_CALL(btm_interface, SetEncryption(test_address, _, _, _, _)) - .WillByDefault(Return(BTM_SUCCESS)); + .WillByDefault(Return(BTM_SUCCESS)); - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::CONNECTED, test_address)) - .Times(0); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::CONNECTED, test_address)).Times(0); uint16_t conn_id = 1; GetConnectedEvent(test_address, conn_id); GetSearchCompleteEvent(conn_id); Mock::VerifyAndClearExpectations(&btm_interface); Mock::VerifyAndClearExpectations(callbacks.get()); - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::CONNECTED, test_address)) - .Times(1); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::CONNECTED, test_address)).Times(1); - ON_CALL(btm_interface, BTM_IsEncrypted(test_address, _)) - .WillByDefault(DoAll(Return(true))); + ON_CALL(btm_interface, BTM_IsEncrypted(test_address, _)).WillByDefault(DoAll(Return(true))); EXPECT_CALL(gatt_interface, ServiceSearchRequest(_, _)); GetEncryptionCompleteEvt(test_address); @@ -868,8 +784,7 @@ TEST_F(VolumeControlTest, test_discovery_vcs_found) { TestAppRegister(); TestConnect(test_address); EXPECT_CALL(*callbacks, OnDeviceAvailable(test_address, _)); - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::CONNECTED, test_address)); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::CONNECTED, test_address)); GetConnectedEvent(test_address, 1); GetSearchCompleteEvent(1); Mock::VerifyAndClearExpectations(callbacks.get()); @@ -881,8 +796,7 @@ TEST_F(VolumeControlTest, test_discovery_vcs_not_found) { SetSampleDatabaseNoVCS(1); TestAppRegister(); TestConnect(test_address); - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::DISCONNECTED, test_address)); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::DISCONNECTED, test_address)); GetConnectedEvent(test_address, 1); GetSearchCompleteEvent(1); @@ -895,8 +809,7 @@ TEST_F(VolumeControlTest, test_discovery_vcs_broken) { SetSampleDatabaseVCSBroken(1); TestAppRegister(); TestConnect(test_address); - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::DISCONNECTED, test_address)); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::DISCONNECTED, test_address)); GetConnectedEvent(test_address, 1); GetSearchCompleteEvent(1); Mock::VerifyAndClearExpectations(callbacks.get()); @@ -964,8 +877,7 @@ TEST_F(VolumeControlTest, test_discovery_vocs_found) { SetSampleDatabaseVOCS(1); TestAppRegister(); TestConnect(test_address); - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::CONNECTED, test_address)); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::CONNECTED, test_address)); EXPECT_CALL(*callbacks, OnDeviceAvailable(test_address, 2)); GetConnectedEvent(test_address, 1); GetSearchCompleteEvent(1); @@ -978,8 +890,7 @@ TEST_F(VolumeControlTest, test_discovery_vocs_not_found) { SetSampleDatabaseVCS(1); TestAppRegister(); TestConnect(test_address); - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::CONNECTED, test_address)); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::CONNECTED, test_address)); EXPECT_CALL(*callbacks, OnDeviceAvailable(test_address, 0)); GetConnectedEvent(test_address, 1); GetSearchCompleteEvent(1); @@ -992,8 +903,7 @@ TEST_F(VolumeControlTest, test_discovery_vocs_broken) { SetSampleDatabaseVOCSBroken(1); TestAppRegister(); TestConnect(test_address); - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::CONNECTED, test_address)); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::CONNECTED, test_address)); EXPECT_CALL(*callbacks, OnDeviceAvailable(test_address, 1)); GetConnectedEvent(test_address, 1); GetSearchCompleteEvent(1); @@ -1012,27 +922,27 @@ TEST_F(VolumeControlTest, test_read_vcs_database_out_of_sync) { TestConnect(test_address); GetConnectedEvent(test_address, conn_id); - EXPECT_CALL(gatt_queue, ReadCharacteristic(conn_id, _, _, _)) - .WillRepeatedly(DoDefault()); + EXPECT_CALL(gatt_queue, ReadCharacteristic(conn_id, _, _, _)).WillRepeatedly(DoDefault()); for (auto const& handle : handles) { - EXPECT_CALL(gatt_queue, ReadCharacteristic(conn_id, handle, _, _)) - .WillOnce(DoDefault()); + EXPECT_CALL(gatt_queue, ReadCharacteristic(conn_id, handle, _, _)).WillOnce(DoDefault()); } GetSearchCompleteEvent(conn_id); /* Simulate database change on the remote side. */ ON_CALL(gatt_queue, WriteCharacteristic(_, _, _, _, _, _)) - .WillByDefault( - Invoke([this](uint16_t conn_id, uint16_t handle, - std::vector value, tGATT_WRITE_TYPE write_type, - GATT_WRITE_OP_CB cb, void* cb_data) { - auto* svc = gatt::FindService(services_map[conn_id], handle); - if (svc == nullptr) return; - - tGATT_STATUS status = GATT_DATABASE_OUT_OF_SYNC; - if (cb) - cb(conn_id, status, handle, value.size(), value.data(), cb_data); - })); + .WillByDefault( + Invoke([this](uint16_t conn_id, uint16_t handle, std::vector value, + tGATT_WRITE_TYPE write_type, GATT_WRITE_OP_CB cb, void* cb_data) { + auto* svc = gatt::FindService(services_map[conn_id], handle); + if (svc == nullptr) { + return; + } + + tGATT_STATUS status = GATT_DATABASE_OUT_OF_SYNC; + if (cb) { + cb(conn_id, status, handle, value.size(), value.data(), cb_data); + } + })); ON_CALL(gatt_interface, ServiceSearchRequest(_, _)).WillByDefault(Return()); EXPECT_CALL(gatt_interface, ServiceSearchRequest(_, _)); @@ -1042,7 +952,7 @@ TEST_F(VolumeControlTest, test_read_vcs_database_out_of_sync) { } class VolumeControlCallbackTest : public VolumeControlTest { - protected: +protected: const RawAddress test_address = GetTestAddress(0); uint16_t conn_id = 22; @@ -1062,11 +972,11 @@ class VolumeControlCallbackTest : public VolumeControlTest { void GetNotificationEvent(uint16_t handle, std::vector& value) { tBTA_GATTC_NOTIFY event_data = { - .conn_id = conn_id, - .bda = test_address, - .handle = handle, - .len = (uint8_t)value.size(), - .is_notify = true, + .conn_id = conn_id, + .bda = test_address, + .handle = handle, + .len = (uint8_t)value.size(), + .is_notify = true, }; std::copy(value.begin(), value.end(), event_data.value); @@ -1090,14 +1000,12 @@ TEST_F(VolumeControlCallbackTest, test_volume_state_changed_malformed) { TEST_F(VolumeControlCallbackTest, test_volume_offset_changed) { std::vector value({0x04, 0x05, 0x06}); - EXPECT_CALL(*callbacks, - OnExtAudioOutVolumeOffsetChanged(test_address, 2, 0x0504)); + EXPECT_CALL(*callbacks, OnExtAudioOutVolumeOffsetChanged(test_address, 2, 0x0504)); GetNotificationEvent(0x0082, value); } TEST_F(VolumeControlCallbackTest, test_volume_offset_changed_malformed) { - EXPECT_CALL(*callbacks, OnExtAudioOutVolumeOffsetChanged(test_address, 2, _)) - .Times(0); + EXPECT_CALL(*callbacks, OnExtAudioOutVolumeOffsetChanged(test_address, 2, _)).Times(0); std::vector too_short({0x04}); GetNotificationEvent(0x0082, too_short); std::vector too_long({0x04, 0x05, 0x06, 0x07}); @@ -1106,14 +1014,12 @@ TEST_F(VolumeControlCallbackTest, test_volume_offset_changed_malformed) { TEST_F(VolumeControlCallbackTest, test_offset_location_changed) { std::vector value({0x01, 0x02, 0x03, 0x04}); - EXPECT_CALL(*callbacks, - OnExtAudioOutLocationChanged(test_address, 2, 0x04030201)); + EXPECT_CALL(*callbacks, OnExtAudioOutLocationChanged(test_address, 2, 0x04030201)); GetNotificationEvent(0x0085, value); } TEST_F(VolumeControlCallbackTest, test_offset_location_changed_malformed) { - EXPECT_CALL(*callbacks, OnExtAudioOutLocationChanged(test_address, 2, _)) - .Times(0); + EXPECT_CALL(*callbacks, OnExtAudioOutLocationChanged(test_address, 2, _)).Times(0); std::vector too_short({0x04}); GetNotificationEvent(0x0085, too_short); std::vector too_long({0x04, 0x05, 0x06}); @@ -1123,13 +1029,12 @@ TEST_F(VolumeControlCallbackTest, test_offset_location_changed_malformed) { TEST_F(VolumeControlCallbackTest, test_audio_output_description_changed) { std::string descr = "left"; std::vector value(descr.begin(), descr.end()); - EXPECT_CALL(*callbacks, - OnExtAudioOutDescriptionChanged(test_address, 2, descr)); + EXPECT_CALL(*callbacks, OnExtAudioOutDescriptionChanged(test_address, 2, descr)); GetNotificationEvent(0x008a, value); } class VolumeControlValueGetTest : public VolumeControlTest { - protected: +protected: const RawAddress test_address = GetTestAddress(0); uint16_t conn_id = 22; GATT_READ_OP_CB cb; @@ -1144,8 +1049,7 @@ class VolumeControlValueGetTest : public VolumeControlTest { GetConnectedEvent(test_address, conn_id); GetSearchCompleteEvent(conn_id); EXPECT_CALL(gatt_queue, ReadCharacteristic(conn_id, _, _, _)) - .WillOnce( - DoAll(SaveArg<1>(&handle), SaveArg<2>(&cb), SaveArg<3>(&cb_data))); + .WillOnce(DoAll(SaveArg<1>(&handle), SaveArg<2>(&cb), SaveArg<3>(&cb_data))); } void TearDown(void) override { @@ -1161,20 +1065,16 @@ TEST_F(VolumeControlValueGetTest, test_get_ext_audio_out_volume_offset) { VolumeControl::Get()->GetExtAudioOutVolumeOffset(test_address, 1); EXPECT_TRUE(cb); std::vector value({0x01, 0x02, 0x03}); - EXPECT_CALL(*callbacks, - OnExtAudioOutVolumeOffsetChanged(test_address, 1, 0x0201)); - cb(conn_id, GATT_SUCCESS, handle, (uint16_t)value.size(), value.data(), - cb_data); + EXPECT_CALL(*callbacks, OnExtAudioOutVolumeOffsetChanged(test_address, 1, 0x0201)); + cb(conn_id, GATT_SUCCESS, handle, (uint16_t)value.size(), value.data(), cb_data); } TEST_F(VolumeControlValueGetTest, test_get_ext_audio_out_location) { VolumeControl::Get()->GetExtAudioOutLocation(test_address, 2); EXPECT_TRUE(cb); std::vector value({0x01, 0x02, 0x03, 0x04}); - EXPECT_CALL(*callbacks, - OnExtAudioOutLocationChanged(test_address, 2, 0x04030201)); - cb(conn_id, GATT_SUCCESS, handle, (uint16_t)value.size(), value.data(), - cb_data); + EXPECT_CALL(*callbacks, OnExtAudioOutLocationChanged(test_address, 2, 0x04030201)); + cb(conn_id, GATT_SUCCESS, handle, (uint16_t)value.size(), value.data(), cb_data); } TEST_F(VolumeControlValueGetTest, test_get_ext_audio_out_description) { @@ -1182,14 +1082,12 @@ TEST_F(VolumeControlValueGetTest, test_get_ext_audio_out_description) { EXPECT_TRUE(cb); std::string descr = "right"; std::vector value(descr.begin(), descr.end()); - EXPECT_CALL(*callbacks, - OnExtAudioOutDescriptionChanged(test_address, 2, descr)); - cb(conn_id, GATT_SUCCESS, handle, (uint16_t)value.size(), value.data(), - cb_data); + EXPECT_CALL(*callbacks, OnExtAudioOutDescriptionChanged(test_address, 2, descr)); + cb(conn_id, GATT_SUCCESS, handle, (uint16_t)value.size(), value.data(), cb_data); } class VolumeControlValueSetTest : public VolumeControlTest { - protected: +protected: const RawAddress test_address = GetTestAddress(0); uint16_t conn_id = 22; @@ -1201,49 +1099,45 @@ class VolumeControlValueSetTest : public VolumeControlTest { GetConnectedEvent(test_address, conn_id); GetSearchCompleteEvent(conn_id); - ON_CALL(gatt_queue, - WriteCharacteristic(conn_id, 0x0024, _, GATT_WRITE, _, _)) - .WillByDefault([this](uint16_t conn_id, uint16_t handle, - std::vector value, - tGATT_WRITE_TYPE write_type, GATT_WRITE_OP_CB cb, - void* cb_data) { - uint8_t write_rsp; - - std::vector ntf_value( - {value[0], 0, static_cast(value[1] + 1)}); - switch (value[0]) { - case 0x06: // mute - ntf_value[1] = 1; - break; - case 0x05: // unmute - break; - case 0x04: // set abs. volume - ntf_value[0] = value[2]; - ntf_value[1] = (value[2] ? 0 : 1); - break; - case 0x03: // unmute rel. up - break; - case 0x02: // unmute rel. down - break; - case 0x01: // rel. up - break; - case 0x00: // rel. down - break; - default: - break; - } - GetNotificationEvent(0x0021, ntf_value); - cb(conn_id, GATT_SUCCESS, 0x0024, 0, &write_rsp, cb_data); - }); + ON_CALL(gatt_queue, WriteCharacteristic(conn_id, 0x0024, _, GATT_WRITE, _, _)) + .WillByDefault([this](uint16_t conn_id, uint16_t handle, std::vector value, + tGATT_WRITE_TYPE write_type, GATT_WRITE_OP_CB cb, void* cb_data) { + uint8_t write_rsp; + + std::vector ntf_value({value[0], 0, static_cast(value[1] + 1)}); + switch (value[0]) { + case 0x06: // mute + ntf_value[1] = 1; + break; + case 0x05: // unmute + break; + case 0x04: // set abs. volume + ntf_value[0] = value[2]; + ntf_value[1] = (value[2] ? 0 : 1); + break; + case 0x03: // unmute rel. up + break; + case 0x02: // unmute rel. down + break; + case 0x01: // rel. up + break; + case 0x00: // rel. down + break; + default: + break; + } + GetNotificationEvent(0x0021, ntf_value); + cb(conn_id, GATT_SUCCESS, 0x0024, 0, &write_rsp, cb_data); + }); } void GetNotificationEvent(uint16_t handle, std::vector& value) { tBTA_GATTC_NOTIFY event_data = { - .conn_id = conn_id, - .bda = test_address, - .handle = handle, - .len = (uint8_t)value.size(), - .is_notify = true, + .conn_id = conn_id, + .bda = test_address, + .handle = handle, + .len = (uint8_t)value.size(), + .is_notify = true, }; std::copy(value.begin(), value.end(), event_data.value); @@ -1258,21 +1152,21 @@ class VolumeControlValueSetTest : public VolumeControlTest { TEST_F(VolumeControlValueSetTest, test_volume_operation_failed) { const std::vector vol_x10({0x04, 0x00, 0x10}); - EXPECT_CALL(gatt_queue, - WriteCharacteristic(conn_id, 0x0024, vol_x10, GATT_WRITE, _, _)) - .Times(1); + EXPECT_CALL(gatt_queue, WriteCharacteristic(conn_id, 0x0024, vol_x10, GATT_WRITE, _, _)).Times(1); ON_CALL(gatt_queue, WriteCharacteristic(_, _, _, _, _, _)) - .WillByDefault( - Invoke([this](uint16_t conn_id, uint16_t handle, - std::vector value, tGATT_WRITE_TYPE write_type, - GATT_WRITE_OP_CB cb, void* cb_data) { - auto* svc = gatt::FindService(services_map[conn_id], handle); - if (svc == nullptr) return; - - tGATT_STATUS status = GATT_ERROR; - if (cb) - cb(conn_id, status, handle, value.size(), value.data(), cb_data); - })); + .WillByDefault( + Invoke([this](uint16_t conn_id, uint16_t handle, std::vector value, + tGATT_WRITE_TYPE write_type, GATT_WRITE_OP_CB cb, void* cb_data) { + auto* svc = gatt::FindService(services_map[conn_id], handle); + if (svc == nullptr) { + return; + } + + tGATT_STATUS status = GATT_ERROR; + if (cb) { + cb(conn_id, status, handle, value.size(), value.data(), cb_data); + } + })); ASSERT_EQ(0, get_func_call_count("alarm_set_on_mloop")); ASSERT_EQ(0, get_func_call_count("alarm_cancel")); @@ -1283,18 +1177,15 @@ TEST_F(VolumeControlValueSetTest, test_volume_operation_failed) { ASSERT_EQ(1, get_func_call_count("alarm_cancel")); } -TEST_F(VolumeControlValueSetTest, - test_volume_operation_failed_due_to_device_disconnection) { +TEST_F(VolumeControlValueSetTest, test_volume_operation_failed_due_to_device_disconnection) { const std::vector vol_x10({0x04, 0x00, 0x10}); - EXPECT_CALL(gatt_queue, - WriteCharacteristic(conn_id, 0x0024, vol_x10, GATT_WRITE, _, _)) - .Times(1); + EXPECT_CALL(gatt_queue, WriteCharacteristic(conn_id, 0x0024, vol_x10, GATT_WRITE, _, _)).Times(1); ON_CALL(gatt_queue, WriteCharacteristic(_, _, _, _, _, _)) - .WillByDefault(Invoke( - [](uint16_t conn_id, uint16_t handle, std::vector value, - tGATT_WRITE_TYPE write_type, GATT_WRITE_OP_CB cb, void* cb_data) { - /* Do nothing */ - })); + .WillByDefault( + Invoke([](uint16_t conn_id, uint16_t handle, std::vector value, + tGATT_WRITE_TYPE write_type, GATT_WRITE_OP_CB cb, void* cb_data) { + /* Do nothing */ + })); ASSERT_EQ(0, get_func_call_count("alarm_set_on_mloop")); ASSERT_EQ(0, get_func_call_count("alarm_cancel")); @@ -1302,8 +1193,7 @@ TEST_F(VolumeControlValueSetTest, VolumeControl::Get()->SetVolume(test_address, 0x10); Mock::VerifyAndClearExpectations(&gatt_queue); - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::DISCONNECTED, test_address)); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::DISCONNECTED, test_address)); GetDisconnectedEvent(test_address, conn_id); Mock::VerifyAndClearExpectations(callbacks.get()); @@ -1313,22 +1203,17 @@ TEST_F(VolumeControlValueSetTest, TEST_F(VolumeControlValueSetTest, test_set_volume) { const std::vector vol_x10({0x04, 0x00, 0x10}); - EXPECT_CALL(gatt_queue, - WriteCharacteristic(conn_id, 0x0024, vol_x10, GATT_WRITE, _, _)) - .Times(1); + EXPECT_CALL(gatt_queue, WriteCharacteristic(conn_id, 0x0024, vol_x10, GATT_WRITE, _, _)).Times(1); VolumeControl::Get()->SetVolume(test_address, 0x10); // Same volume level should not be applied twice const std::vector vol_x10_2({0x04, 0x01, 0x10}); - EXPECT_CALL(gatt_queue, - WriteCharacteristic(conn_id, 0x0024, vol_x10_2, GATT_WRITE, _, _)) - .Times(0); + EXPECT_CALL(gatt_queue, WriteCharacteristic(conn_id, 0x0024, vol_x10_2, GATT_WRITE, _, _)) + .Times(0); VolumeControl::Get()->SetVolume(test_address, 0x10); const std::vector vol_x20({0x04, 0x01, 0x20}); - EXPECT_CALL(gatt_queue, - WriteCharacteristic(conn_id, 0x0024, vol_x20, GATT_WRITE, _, _)) - .Times(1); + EXPECT_CALL(gatt_queue, WriteCharacteristic(conn_id, 0x0024, vol_x20, GATT_WRITE, _, _)).Times(1); VolumeControl::Get()->SetVolume(test_address, 0x20); } @@ -1339,9 +1224,8 @@ TEST_F(VolumeControlValueSetTest, test_set_volume_stress) { for (uint8_t i = 1; i < n; i++) { const std::vector vol_x10({0x04, change_cnt, vol}); - EXPECT_CALL(gatt_queue, - WriteCharacteristic(conn_id, 0x0024, vol_x10, GATT_WRITE, _, _)) - .Times(1); + EXPECT_CALL(gatt_queue, WriteCharacteristic(conn_id, 0x0024, vol_x10, GATT_WRITE, _, _)) + .Times(1); VolumeControl::Get()->SetVolume(test_address, vol); Mock::VerifyAndClearExpectations(&gatt_queue); change_cnt++; @@ -1356,19 +1240,18 @@ TEST_F(VolumeControlValueSetTest, test_set_volume_stress_2) { // In this test we simulate notification coming later and operations will be // queued ON_CALL(gatt_queue, WriteCharacteristic(conn_id, 0x0024, _, GATT_WRITE, _, _)) - .WillByDefault([](uint16_t conn_id, uint16_t handle, - std::vector value, tGATT_WRITE_TYPE write_type, - GATT_WRITE_OP_CB cb, void* cb_data) { - uint8_t write_rsp; - - switch (value[0]) { - case 0x04: // set abs. volume - break; - default: - break; - } - cb(conn_id, GATT_SUCCESS, handle, 0, &write_rsp, cb_data); - }); + .WillByDefault([](uint16_t conn_id, uint16_t handle, std::vector value, + tGATT_WRITE_TYPE write_type, GATT_WRITE_OP_CB cb, void* cb_data) { + uint8_t write_rsp; + + switch (value[0]) { + case 0x04: // set abs. volume + break; + default: + break; + } + cb(conn_id, GATT_SUCCESS, handle, 0, &write_rsp, cb_data); + }); const std::vector vol_x10({0x04, /*change_cnt*/ 0, 0x10}); std::vector ntf_value_x10({0x10, 0, 1}); @@ -1379,18 +1262,10 @@ TEST_F(VolumeControlValueSetTest, test_set_volume_stress_2) { const std::vector vol_x13({0x04, /*change_cnt*/ 3, 0x13}); std::vector ntf_value_x13({0x13, 0, 4}); - EXPECT_CALL(gatt_queue, - WriteCharacteristic(conn_id, 0x0024, vol_x10, GATT_WRITE, _, _)) - .Times(1); - EXPECT_CALL(gatt_queue, - WriteCharacteristic(conn_id, 0x0024, vol_x11, GATT_WRITE, _, _)) - .Times(1); - EXPECT_CALL(gatt_queue, - WriteCharacteristic(conn_id, 0x0024, vol_x12, GATT_WRITE, _, _)) - .Times(1); - EXPECT_CALL(gatt_queue, - WriteCharacteristic(conn_id, 0x0024, vol_x13, GATT_WRITE, _, _)) - .Times(1); + EXPECT_CALL(gatt_queue, WriteCharacteristic(conn_id, 0x0024, vol_x10, GATT_WRITE, _, _)).Times(1); + EXPECT_CALL(gatt_queue, WriteCharacteristic(conn_id, 0x0024, vol_x11, GATT_WRITE, _, _)).Times(1); + EXPECT_CALL(gatt_queue, WriteCharacteristic(conn_id, 0x0024, vol_x12, GATT_WRITE, _, _)).Times(1); + EXPECT_CALL(gatt_queue, WriteCharacteristic(conn_id, 0x0024, vol_x13, GATT_WRITE, _, _)).Times(1); VolumeControl::Get()->SetVolume(test_address, 0x10); VolumeControl::Get()->SetVolume(test_address, 0x11); @@ -1412,19 +1287,18 @@ TEST_F(VolumeControlValueSetTest, test_set_volume_stress_3) { * queued but some will be removed from the queue */ ON_CALL(gatt_queue, WriteCharacteristic(conn_id, 0x0024, _, GATT_WRITE, _, _)) - .WillByDefault([](uint16_t conn_id, uint16_t handle, - std::vector value, tGATT_WRITE_TYPE write_type, - GATT_WRITE_OP_CB cb, void* cb_data) { - uint8_t write_rsp; - - switch (value[0]) { - case 0x04: // set abs. volume - break; - default: - break; - } - cb(conn_id, GATT_SUCCESS, handle, 0, &write_rsp, cb_data); - }); + .WillByDefault([](uint16_t conn_id, uint16_t handle, std::vector value, + tGATT_WRITE_TYPE write_type, GATT_WRITE_OP_CB cb, void* cb_data) { + uint8_t write_rsp; + + switch (value[0]) { + case 0x04: // set abs. volume + break; + default: + break; + } + cb(conn_id, GATT_SUCCESS, handle, 0, &write_rsp, cb_data); + }); const std::vector vol_x10({0x04, /*change_cnt*/ 0, 0x10}); std::vector ntf_value_x10({0x10, 0, 1}); @@ -1435,22 +1309,14 @@ TEST_F(VolumeControlValueSetTest, test_set_volume_stress_3) { const std::vector vol_x13({0x04, /*change_cnt*/ 1, 0x13}); std::vector ntf_value_x13({0x13, 0, 4}); - EXPECT_CALL(gatt_queue, - WriteCharacteristic(conn_id, 0x0024, vol_x10, GATT_WRITE, _, _)) - .Times(1); + EXPECT_CALL(gatt_queue, WriteCharacteristic(conn_id, 0x0024, vol_x10, GATT_WRITE, _, _)).Times(1); // Those two belowe will be removed from the queue - EXPECT_CALL(gatt_queue, - WriteCharacteristic(conn_id, 0x0024, vol_x11, GATT_WRITE, _, _)) - .Times(0); - EXPECT_CALL(gatt_queue, - WriteCharacteristic(conn_id, 0x0024, vol_x12, GATT_WRITE, _, _)) - .Times(0); + EXPECT_CALL(gatt_queue, WriteCharacteristic(conn_id, 0x0024, vol_x11, GATT_WRITE, _, _)).Times(0); + EXPECT_CALL(gatt_queue, WriteCharacteristic(conn_id, 0x0024, vol_x12, GATT_WRITE, _, _)).Times(0); // This one shall be sent with a change count 1. - EXPECT_CALL(gatt_queue, - WriteCharacteristic(conn_id, 0x0024, vol_x13, GATT_WRITE, _, _)) - .Times(1); + EXPECT_CALL(gatt_queue, WriteCharacteristic(conn_id, 0x0024, vol_x13, GATT_WRITE, _, _)).Times(1); VolumeControl::Get()->SetVolume(test_address, 0x10); VolumeControl::Get()->SetVolume(test_address, 0x11); @@ -1466,47 +1332,39 @@ TEST_F(VolumeControlValueSetTest, test_set_volume_stress_3) { TEST_F(VolumeControlValueSetTest, test_mute_unmute) { std::vector mute_x0({0x06, 0x00}); - EXPECT_CALL(gatt_queue, - WriteCharacteristic(conn_id, 0x0024, mute_x0, GATT_WRITE, _, _)) - .Times(1); + EXPECT_CALL(gatt_queue, WriteCharacteristic(conn_id, 0x0024, mute_x0, GATT_WRITE, _, _)).Times(1); // Don't mute when already muted std::vector mute_x1({0x06, 0x01}); - EXPECT_CALL(gatt_queue, - WriteCharacteristic(conn_id, 0x0024, mute_x1, GATT_WRITE, _, _)) - .Times(0); + EXPECT_CALL(gatt_queue, WriteCharacteristic(conn_id, 0x0024, mute_x1, GATT_WRITE, _, _)).Times(0); VolumeControl::Get()->Mute(test_address); VolumeControl::Get()->Mute(test_address); // Needs to be muted to unmute std::vector unmute_x1({0x05, 0x01}); - EXPECT_CALL(gatt_queue, - WriteCharacteristic(conn_id, 0x0024, unmute_x1, GATT_WRITE, _, _)) - .Times(1); + EXPECT_CALL(gatt_queue, WriteCharacteristic(conn_id, 0x0024, unmute_x1, GATT_WRITE, _, _)) + .Times(1); // Don't unmute when already unmuted std::vector unmute_x2({0x05, 0x02}); - EXPECT_CALL(gatt_queue, - WriteCharacteristic(conn_id, 0x0024, unmute_x2, GATT_WRITE, _, _)) - .Times(0); + EXPECT_CALL(gatt_queue, WriteCharacteristic(conn_id, 0x0024, unmute_x2, GATT_WRITE, _, _)) + .Times(0); VolumeControl::Get()->UnMute(test_address); VolumeControl::Get()->UnMute(test_address); } TEST_F(VolumeControlValueSetTest, test_set_ext_audio_out_volume_offset) { std::vector expected_data({0x01, 0x00, 0x34, 0x12}); - EXPECT_CALL(gatt_queue, WriteCharacteristic(conn_id, 0x0088, expected_data, - GATT_WRITE, _, _)); + EXPECT_CALL(gatt_queue, WriteCharacteristic(conn_id, 0x0088, expected_data, GATT_WRITE, _, _)); VolumeControl::Get()->SetExtAudioOutVolumeOffset(test_address, 2, 0x1234); } TEST_F(VolumeControlValueSetTest, test_set_ext_audio_out_location) { std::vector expected_data({0x44, 0x33, 0x22, 0x11}); - EXPECT_CALL(gatt_queue, WriteCharacteristic(conn_id, 0x0085, expected_data, - GATT_WRITE_NO_RSP, _, _)); + EXPECT_CALL(gatt_queue, + WriteCharacteristic(conn_id, 0x0085, expected_data, GATT_WRITE_NO_RSP, _, _)); VolumeControl::Get()->SetExtAudioOutLocation(test_address, 2, 0x11223344); } -TEST_F(VolumeControlValueSetTest, - test_set_ext_audio_out_location_non_writable) { +TEST_F(VolumeControlValueSetTest, test_set_ext_audio_out_location_non_writable) { EXPECT_CALL(gatt_queue, WriteCharacteristic(_, _, _, _, _, _)).Times(0); VolumeControl::Get()->SetExtAudioOutLocation(test_address, 1, 0x11223344); } @@ -1514,20 +1372,19 @@ TEST_F(VolumeControlValueSetTest, TEST_F(VolumeControlValueSetTest, test_set_ext_audio_out_description) { std::string descr = "right front"; std::vector expected_data(descr.begin(), descr.end()); - EXPECT_CALL(gatt_queue, WriteCharacteristic(conn_id, 0x008a, expected_data, - GATT_WRITE_NO_RSP, _, _)); + EXPECT_CALL(gatt_queue, + WriteCharacteristic(conn_id, 0x008a, expected_data, GATT_WRITE_NO_RSP, _, _)); VolumeControl::Get()->SetExtAudioOutDescription(test_address, 2, descr); } -TEST_F(VolumeControlValueSetTest, - test_set_ext_audio_out_description_non_writable) { +TEST_F(VolumeControlValueSetTest, test_set_ext_audio_out_description_non_writable) { std::string descr = "left front"; EXPECT_CALL(gatt_queue, WriteCharacteristic(_, _, _, _, _, _)).Times(0); VolumeControl::Get()->SetExtAudioOutDescription(test_address, 1, descr); } class VolumeControlCsis : public VolumeControlTest { - protected: +protected: const RawAddress test_address_1 = GetTestAddress(0); const RawAddress test_address_2 = GetTestAddress(1); std::vector csis_group = {test_address_1, test_address_2}; @@ -1539,18 +1396,14 @@ class VolumeControlCsis : public VolumeControlTest { void SetUp(void) override { VolumeControlTest::SetUp(); - ON_CALL(mock_csis_client_module_, Get()) - .WillByDefault(Return(&mock_csis_client_module_)); + ON_CALL(mock_csis_client_module_, Get()).WillByDefault(Return(&mock_csis_client_module_)); // Report working CSIS - ON_CALL(mock_csis_client_module_, IsCsisClientRunning()) - .WillByDefault(Return(true)); + ON_CALL(mock_csis_client_module_, IsCsisClientRunning()).WillByDefault(Return(true)); - ON_CALL(mock_csis_client_module_, GetDeviceList(_)) - .WillByDefault(Return(csis_group)); + ON_CALL(mock_csis_client_module_, GetDeviceList(_)).WillByDefault(Return(csis_group)); - ON_CALL(mock_csis_client_module_, GetGroupId(_, _)) - .WillByDefault(Return(group_id)); + ON_CALL(mock_csis_client_module_, GetGroupId(_, _)).WillByDefault(Return(group_id)); SetSampleDatabase(conn_id_1); SetSampleDatabase(conn_id_2); @@ -1563,14 +1416,14 @@ class VolumeControlCsis : public VolumeControlTest { VolumeControlTest::TearDown(); } - void GetNotificationEvent(uint16_t conn_id, const RawAddress& test_address, - uint16_t handle, std::vector& value) { + void GetNotificationEvent(uint16_t conn_id, const RawAddress& test_address, uint16_t handle, + std::vector& value) { tBTA_GATTC_NOTIFY event_data = { - .conn_id = conn_id, - .bda = test_address, - .handle = handle, - .len = (uint8_t)value.size(), - .is_notify = true, + .conn_id = conn_id, + .bda = test_address, + .handle = handle, + .len = (uint8_t)value.size(), + .is_notify = true, }; std::copy(value.begin(), value.end(), event_data.value); @@ -1587,16 +1440,13 @@ TEST_F(VolumeControlCsis, test_set_volume) { GetSearchCompleteEvent(conn_id_2); /* Set value for the group */ - EXPECT_CALL(gatt_queue, - WriteCharacteristic(conn_id_1, 0x0024, _, GATT_WRITE, _, _)); - EXPECT_CALL(gatt_queue, - WriteCharacteristic(conn_id_2, 0x0024, _, GATT_WRITE, _, _)); + EXPECT_CALL(gatt_queue, WriteCharacteristic(conn_id_1, 0x0024, _, GATT_WRITE, _, _)); + EXPECT_CALL(gatt_queue, WriteCharacteristic(conn_id_2, 0x0024, _, GATT_WRITE, _, _)); VolumeControl::Get()->SetVolume(group_id, 10); /* Now inject notification and make sure callback is sent up to Java layer */ - EXPECT_CALL(*callbacks, - OnGroupVolumeStateChanged(group_id, 0x03, true, false)); + EXPECT_CALL(*callbacks, OnGroupVolumeStateChanged(group_id, 0x03, true, false)); std::vector value({0x03, 0x01, 0x02}); GetNotificationEvent(conn_id_1, test_address_1, 0x0021, value); @@ -1604,12 +1454,8 @@ TEST_F(VolumeControlCsis, test_set_volume) { /* Verify exactly one operation with this exact value is queued for each * device */ - EXPECT_CALL(gatt_queue, - WriteCharacteristic(conn_id_1, 0x0024, _, GATT_WRITE, _, _)) - .Times(1); - EXPECT_CALL(gatt_queue, - WriteCharacteristic(conn_id_2, 0x0024, _, GATT_WRITE, _, _)) - .Times(1); + EXPECT_CALL(gatt_queue, WriteCharacteristic(conn_id_1, 0x0024, _, GATT_WRITE, _, _)).Times(1); + EXPECT_CALL(gatt_queue, WriteCharacteristic(conn_id_2, 0x0024, _, GATT_WRITE, _, _)).Times(1); VolumeControl::Get()->SetVolume(test_address_1, 20); VolumeControl::Get()->SetVolume(test_address_2, 20); VolumeControl::Get()->SetVolume(test_address_1, 20); @@ -1634,12 +1480,8 @@ TEST_F(VolumeControlCsis, test_set_volume_device_not_ready) { GetSearchCompleteEvent(conn_id_2); /* Set value for the group */ - EXPECT_CALL(gatt_queue, - WriteCharacteristic(conn_id_1, 0x0024, _, GATT_WRITE, _, _)) - .Times(0); - EXPECT_CALL(gatt_queue, - WriteCharacteristic(conn_id_2, 0x0024, _, GATT_WRITE, _, _)) - .Times(0); + EXPECT_CALL(gatt_queue, WriteCharacteristic(conn_id_1, 0x0024, _, GATT_WRITE, _, _)).Times(0); + EXPECT_CALL(gatt_queue, WriteCharacteristic(conn_id_2, 0x0024, _, GATT_WRITE, _, _)).Times(0); VolumeControl::Get()->SetVolume(group_id, 10); } @@ -1653,8 +1495,7 @@ TEST_F(VolumeControlCsis, autonomus_test_set_volume) { GetSearchCompleteEvent(conn_id_2); /* Now inject notification and make sure callback is sent up to Java layer */ - EXPECT_CALL(*callbacks, - OnGroupVolumeStateChanged(group_id, 0x03, false, true)); + EXPECT_CALL(*callbacks, OnGroupVolumeStateChanged(group_id, 0x03, false, true)); std::vector value({0x03, 0x00, 0x02}); GetNotificationEvent(conn_id_1, test_address_1, 0x0021, value); @@ -1670,13 +1511,11 @@ TEST_F(VolumeControlCsis, autonomus_single_device_test_set_volume) { GetSearchCompleteEvent(conn_id_2); /* Disconnect one device. */ - EXPECT_CALL(*callbacks, - OnConnectionState(ConnectionState::DISCONNECTED, test_address_1)); + EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::DISCONNECTED, test_address_1)); GetDisconnectedEvent(test_address_1, conn_id_1); /* Now inject notification and make sure callback is sent up to Java layer */ - EXPECT_CALL(*callbacks, - OnGroupVolumeStateChanged(group_id, 0x03, false, true)); + EXPECT_CALL(*callbacks, OnGroupVolumeStateChanged(group_id, 0x03, false, true)); std::vector value({0x03, 0x00, 0x02}); GetNotificationEvent(conn_id_2, test_address_2, 0x0021, value); diff --git a/system/btcore/fuzzer/btcore_device_class_fuzzer.cpp b/system/btcore/fuzzer/btcore_device_class_fuzzer.cpp index dd763b2fc37..fef1e33370b 100644 --- a/system/btcore/fuzzer/btcore_device_class_fuzzer.cpp +++ b/system/btcore/fuzzer/btcore_device_class_fuzzer.cpp @@ -16,13 +16,14 @@ */ #include + #include "btcore/include/device_class.h" class BTCoreDeviceClassFuzzer { - public: +public: void process(const uint8_t* data, size_t size); - private: +private: std::unique_ptr mFdp = nullptr; }; diff --git a/system/btcore/fuzzer/btcore_module_fuzzer.cpp b/system/btcore/fuzzer/btcore_module_fuzzer.cpp index 71557473959..adb21b724dc 100644 --- a/system/btcore/fuzzer/btcore_module_fuzzer.cpp +++ b/system/btcore/fuzzer/btcore_module_fuzzer.cpp @@ -21,13 +21,11 @@ extern const module_t osi_module; extern "C" { -struct android_namespace_t* android_get_exported_namespace(const char*) { - return nullptr; -} +struct android_namespace_t* android_get_exported_namespace(const char*) { return nullptr; } } class BTCoreModuleFuzzer { - public: +public: void process(); }; diff --git a/system/btcore/fuzzer/btcore_property_fuzzer.cpp b/system/btcore/fuzzer/btcore_property_fuzzer.cpp index d6f8135e27d..eabcf505c3c 100644 --- a/system/btcore/fuzzer/btcore_property_fuzzer.cpp +++ b/system/btcore/fuzzer/btcore_property_fuzzer.cpp @@ -26,10 +26,10 @@ using bluetooth::Uuid; constexpr int32_t kRandomStringLength = 256; class BTCorePropertyFuzzer { - public: +public: void process(const uint8_t* data, size_t size); - private: +private: std::unique_ptr mFdp = nullptr; }; @@ -51,8 +51,7 @@ void BTCorePropertyFuzzer::process(const uint8_t* data, size_t size) { (void)device_class_to_int(pDeviceClass); property_free(property); - bt_device_type_t deviceType = - (bt_device_type_t)(mFdp->ConsumeIntegral()); + bt_device_type_t deviceType = (bt_device_type_t)(mFdp->ConsumeIntegral()); property = property_new_device_type(deviceType); (void)property_as_device_type(property); property_free(property); diff --git a/system/btcore/include/device_class.h b/system/btcore/include/device_class.h index 0b65cc8d990..6f56b119b05 100644 --- a/system/btcore/include/device_class.h +++ b/system/btcore/include/device_class.h @@ -39,8 +39,7 @@ void device_class_from_stream(bt_device_class_t* dc, const uint8_t* data); // Serializes the device class |dc| to pointer argument |data| in big endian // format. |len| must contain the buffer size of |data|. Returns the actual // number of bytes copied into |data|. |dc| and |data| must not be NULL. -int device_class_to_stream(const bt_device_class_t* dc, uint8_t* data, - size_t len); +int device_class_to_stream(const bt_device_class_t* dc, uint8_t* data, size_t len); // Copies the |data| class of device integer into device class |dc|. |dc| // must not be NULL. @@ -51,8 +50,7 @@ int device_class_to_int(const bt_device_class_t* dc); // Compares and returns |true| if two device classes |p1| and |p2| are equal. // False otherwise. -bool device_class_equals(const bt_device_class_t* p1, - const bt_device_class_t* p2); +bool device_class_equals(const bt_device_class_t* p1, const bt_device_class_t* p2); // Copies and returns |true| if the device class was successfully copied from // |p2| into |p1|. False otherwise. diff --git a/system/btcore/include/device_features.h b/system/btcore/include/device_features.h index 6cb2df6c8d0..13f8653635c 100644 --- a/system/btcore/include/device_features.h +++ b/system/btcore/include/device_features.h @@ -22,4 +22,6 @@ // Represents a page of device feature enabled/disabled bits returned // by the local controller. See the bluetooth spec for bit indexes. -typedef struct { uint8_t as_array[8]; } bt_device_features_t; +typedef struct { + uint8_t as_array[8]; +} bt_device_features_t; diff --git a/system/btcore/include/event_mask.h b/system/btcore/include/event_mask.h index c3efe644356..f811c78c8ef 100644 --- a/system/btcore/include/event_mask.h +++ b/system/btcore/include/event_mask.h @@ -23,4 +23,6 @@ // Represents a mask which can be used to tell the controller which // HCI events the stack wishes to be informed about. See the bluetooth // spec for more information on what each bit means. -typedef struct { const uint8_t as_array[8]; } bt_event_mask_t; +typedef struct { + const uint8_t as_array[8]; +} bt_event_mask_t; diff --git a/system/btcore/include/property.h b/system/btcore/include/property.h index 582392fcc4d..17d2973b530 100644 --- a/system/btcore/include/property.h +++ b/system/btcore/include/property.h @@ -28,8 +28,7 @@ // Copies an array of consecutive properties of |count| to a newly // allocated array. |properties| must not be NULL. -bt_property_t* property_copy_array(const bt_property_t* properties, - size_t count); +bt_property_t* property_copy_array(const bt_property_t* properties, size_t count); // Copies |src| to |dest|. Returns the value of |dest|. // |src| and |dest| must not be NULL. @@ -69,11 +68,9 @@ bool property_is_uuids(const bt_property_t* property); // Value conversion convenience methods. The contents of the property are // properly typed and returned to the caller. |property| must not be NULL. const RawAddress* property_as_addr(const bt_property_t* property); -const bt_device_class_t* property_as_device_class( - const bt_property_t* property); +const bt_device_class_t* property_as_device_class(const bt_property_t* property); bt_device_type_t property_as_device_type(const bt_property_t* property); uint32_t property_as_discoverable_timeout(const bt_property_t* property); const bt_bdname_t* property_as_name(const bt_property_t* property); int8_t property_as_rssi(const bt_property_t* property); -const bluetooth::Uuid* property_as_uuids(const bt_property_t* property, - size_t* count); +const bluetooth::Uuid* property_as_uuids(const bt_property_t* property, size_t* count); diff --git a/system/btcore/src/device_class.cc b/system/btcore/src/device_class.cc index ac063e4b4d3..08d2ae191aa 100644 --- a/system/btcore/src/device_class.cc +++ b/system/btcore/src/device_class.cc @@ -38,8 +38,7 @@ typedef struct _bt_device_class_t { // Ensure the internal device class implementation and public one // have equal size. static_assert(sizeof(_bt_device_class_t) == sizeof(bt_device_class_t), - "Internal and external device class implementation should have " - "the same size"); + "Internal and external device class implementation should have the same size"); // [Major Service Classes] // (https://www.bluetooth.org/en-us/specification/assigned-numbers/baseband) @@ -57,8 +56,7 @@ enum { DC_INFORMATION = 0x0400, }; -static bool device_class_get_major_service_(const bt_device_class_t* dc, - int bitmask); +static bool device_class_get_major_service_(const bt_device_class_t* dc, int bitmask); static void device_class_clr_major_service_(bt_device_class_t* dc, int bitmask); static void device_class_set_major_service_(bt_device_class_t* dc, int bitmask); @@ -68,8 +66,7 @@ void device_class_from_stream(bt_device_class_t* dc, const uint8_t* data) { *dc = *(bt_device_class_t*)data; } -int device_class_to_stream(const bt_device_class_t* dc, uint8_t* data, - size_t len) { +int device_class_to_stream(const bt_device_class_t* dc, uint8_t* data, size_t len) { log::assert_that(dc != NULL, "assert failed: dc != NULL"); log::assert_that(data != NULL, "assert failed: data != NULL"); log::assert_that(len >= sizeof(bt_device_class_t), @@ -97,17 +94,16 @@ int device_class_to_int(const bt_device_class_t* dc) { return static_cast(le32toh(val) & 0xffffff); } -bool device_class_equals(const bt_device_class_t* p1, - const bt_device_class_t* p2) { +bool device_class_equals(const bt_device_class_t* p1, const bt_device_class_t* p2) { log::assert_that(p1 != NULL, "assert failed: p1 != NULL"); log::assert_that(p2 != NULL, "assert failed: p2 != NULL"); - return (memcmp(p1, p2, sizeof(bt_device_class_t)) == 0); + return memcmp(p1, p2, sizeof(bt_device_class_t)) == 0; } bool device_class_copy(bt_device_class_t* dest, const bt_device_class_t* src) { log::assert_that(dest != NULL, "assert failed: dest != NULL"); log::assert_that(src != NULL, "assert failed: src != NULL"); - return (memcpy(dest, src, sizeof(bt_device_class_t)) == dest); + return memcpy(dest, src, sizeof(bt_device_class_t)) == dest; } int device_class_get_major_device(const bt_device_class_t* dc) { @@ -137,10 +133,11 @@ bool device_class_get_information(const bt_device_class_t* dc) { void device_class_set_information(bt_device_class_t* dc, bool set) { log::assert_that(dc != NULL, "assert failed: dc != NULL"); - if (set) + if (set) { device_class_set_major_service_(dc, DC_INFORMATION); - else + } else { device_class_clr_major_service_(dc, DC_INFORMATION); + } } bool device_class_get_limited(const bt_device_class_t* dc) { @@ -150,23 +147,21 @@ bool device_class_get_limited(const bt_device_class_t* dc) { void device_class_set_limited(bt_device_class_t* dc, bool set) { log::assert_that(dc != NULL, "assert failed: dc != NULL"); - if (set) + if (set) { device_class_set_major_service_(dc, DC_LIMITED_DISCOVERABLE_MODE); - else + } else { device_class_clr_major_service_(dc, DC_LIMITED_DISCOVERABLE_MODE); + } } -static bool device_class_get_major_service_(const bt_device_class_t* dc, - int bitmask) { - return (DC(dc)->major_service & bitmask); +static bool device_class_get_major_service_(const bt_device_class_t* dc, int bitmask) { + return DC(dc)->major_service & bitmask; } -static void device_class_clr_major_service_(bt_device_class_t* dc, - int bitmask) { +static void device_class_clr_major_service_(bt_device_class_t* dc, int bitmask) { DC(dc)->major_service &= ~bitmask; } -static void device_class_set_major_service_(bt_device_class_t* dc, - int bitmask) { +static void device_class_set_major_service_(bt_device_class_t* dc, int bitmask) { DC(dc)->major_service |= bitmask; } diff --git a/system/btcore/src/module.cc b/system/btcore/src/module.cc index b1cf72ccdad..3f809d4d5d3 100644 --- a/system/btcore/src/module.cc +++ b/system/btcore/src/module.cc @@ -60,9 +60,8 @@ const module_t* get_module(const char* name) { bool module_init(const module_t* module) { log::assert_that(module != NULL, "assert failed: module != NULL"); - log::assert_that( - get_module_state(module) == MODULE_STATE_NONE, - "assert failed: get_module_state(module) == MODULE_STATE_NONE"); + log::assert_that(get_module_state(module) == MODULE_STATE_NONE, + "assert failed: get_module_state(module) == MODULE_STATE_NONE"); if (!call_lifecycle_function(module->init)) { log::error("Failed to initialize module \"{}\"", module->name); @@ -80,8 +79,7 @@ bool module_start_up(const module_t* module) { // This hack is here so modules which don't require init don't have to have // useless calls // as we're converting the startup sequence. - log::assert_that(get_module_state(module) == MODULE_STATE_INITIALIZED || - module->init == NULL, + log::assert_that(get_module_state(module) == MODULE_STATE_INITIALIZED || module->init == NULL, "assert failed: get_module_state(module) == " "MODULE_STATE_INITIALIZED || module->init == NULL"); @@ -99,16 +97,16 @@ bool module_start_up(const module_t* module) { void module_shut_down(const module_t* module) { log::assert_that(module != NULL, "assert failed: module != NULL"); module_state_t state = get_module_state(module); - log::assert_that(state <= MODULE_STATE_STARTED, - "assert failed: state <= MODULE_STATE_STARTED"); + log::assert_that(state <= MODULE_STATE_STARTED, "assert failed: state <= MODULE_STATE_STARTED"); // Only something to do if the module was actually started - if (state < MODULE_STATE_STARTED) return; + if (state < MODULE_STATE_STARTED) { + return; + } log::info("Shutting down module \"{}\"", module->name); if (!call_lifecycle_function(module->shut_down)) { - log::error("Failed to shutdown module \"{}\". Continuing anyway.", - module->name); + log::error("Failed to shutdown module \"{}\". Continuing anyway.", module->name); } log::info("Shutdown of module \"{}\" completed", module->name); @@ -122,12 +120,13 @@ void module_clean_up(const module_t* module) { "assert failed: state <= MODULE_STATE_INITIALIZED"); // Only something to do if the module was actually initialized - if (state < MODULE_STATE_INITIALIZED) return; + if (state < MODULE_STATE_INITIALIZED) { + return; + } log::info("Cleaning up module \"{}\"", module->name); if (!call_lifecycle_function(module->clean_up)) { - log::error("Failed to cleanup module \"{}\". Continuing anyway.", - module->name); + log::error("Failed to cleanup module \"{}\". Continuing anyway.", module->name); } log::info("Cleanup of module \"{}\" completed", module->name); @@ -136,12 +135,16 @@ void module_clean_up(const module_t* module) { static bool call_lifecycle_function(module_lifecycle_fn function) { // A NULL lifecycle function means it isn't needed, so assume success - if (!function) return true; + if (!function) { + return true; + } future_t* future = function(); // A NULL future means synchronous success - if (!future) return true; + if (!future) { + return true; + } // Otherwise fall back to the future return future_await(future); diff --git a/system/btcore/src/osi_module.cc b/system/btcore/src/osi_module.cc index 6a9f939f18b..77c75fa795a 100644 --- a/system/btcore/src/osi_module.cc +++ b/system/btcore/src/osi_module.cc @@ -27,9 +27,7 @@ #include "osi/include/osi.h" #include "osi/include/wakelock.h" -future_t* osi_init(void) { - return future_new_immediate(FUTURE_SUCCESS); -} +future_t* osi_init(void) { return future_new_immediate(FUTURE_SUCCESS); } future_t* osi_clean_up(void) { alarm_cleanup(); diff --git a/system/btcore/src/property.cc b/system/btcore/src/property.cc index 26d8edb4fd1..5592b1405b2 100644 --- a/system/btcore/src/property.cc +++ b/system/btcore/src/property.cc @@ -30,14 +30,11 @@ using bluetooth::Uuid; using namespace bluetooth; -static bt_property_t* property_new_(void* val, size_t len, - bt_property_type_t type); +static bt_property_t* property_new_(void* val, size_t len, bt_property_type_t type); -bt_property_t* property_copy_array(const bt_property_t* properties, - size_t count) { +bt_property_t* property_copy_array(const bt_property_t* properties, size_t count) { log::assert_that(properties != NULL, "assert failed: properties != NULL"); - bt_property_t* clone = - static_cast(osi_calloc(sizeof(bt_property_t) * count)); + bt_property_t* clone = static_cast(osi_calloc(sizeof(bt_property_t) * count)); memcpy(&clone[0], &properties[0], sizeof(bt_property_t) * count); for (size_t i = 0; i < count; ++i) { @@ -89,18 +86,15 @@ bt_property_t* property_new_addr(const RawAddress* addr) { bt_property_t* property_new_device_class(const bt_device_class_t* dc) { log::assert_that(dc != NULL, "assert failed: dc != NULL"); - return property_new_((void*)dc, sizeof(bt_device_class_t), - BT_PROPERTY_CLASS_OF_DEVICE); + return property_new_((void*)dc, sizeof(bt_device_class_t), BT_PROPERTY_CLASS_OF_DEVICE); } bt_property_t* property_new_device_type(bt_device_type_t type) { - return property_new_((void*)&type, sizeof(bt_device_type_t), - BT_PROPERTY_TYPE_OF_DEVICE); + return property_new_((void*)&type, sizeof(bt_device_type_t), BT_PROPERTY_TYPE_OF_DEVICE); } bt_property_t* property_new_discoverable_timeout(const uint32_t timeout) { - return property_new_((void*)&timeout, sizeof(uint32_t), - BT_PROPERTY_ADAPTER_DISCOVERABLE_TIMEOUT); + return property_new_((void*)&timeout, sizeof(uint32_t), BT_PROPERTY_ADAPTER_DISCOVERABLE_TIMEOUT); } bt_property_t* property_new_name(const char* name) { @@ -117,12 +111,12 @@ bt_property_t* property_new_uuids(const Uuid* uuid, size_t count) { return property_new_((void*)uuid, sizeof(Uuid) * count, BT_PROPERTY_UUIDS); } -void property_free(bt_property_t* property) { - property_free_array(property, 1); -} +void property_free(bt_property_t* property) { property_free_array(property, 1); } void property_free_array(bt_property_t* properties, size_t count) { - if (properties == NULL) return; + if (properties == NULL) { + return; + } for (size_t i = 0; i < count; ++i) { osi_free(properties[i].val); @@ -168,13 +162,11 @@ bool property_is_uuids(const bt_property_t* property) { // Convenience conversion methods to property values const RawAddress* property_as_addr(const bt_property_t* property) { - log::assert_that(property_is_addr(property), - "assert failed: property_is_addr(property)"); + log::assert_that(property_is_addr(property), "assert failed: property_is_addr(property)"); return (const RawAddress*)property->val; } -const bt_device_class_t* property_as_device_class( - const bt_property_t* property) { +const bt_device_class_t* property_as_device_class(const bt_property_t* property) { log::assert_that(property_is_device_class(property), "assert failed: property_is_device_class(property)"); return (const bt_device_class_t*)property->val; @@ -193,28 +185,23 @@ uint32_t property_as_discoverable_timeout(const bt_property_t* property) { } const bt_bdname_t* property_as_name(const bt_property_t* property) { - log::assert_that(property_is_name(property), - "assert failed: property_is_name(property)"); + log::assert_that(property_is_name(property), "assert failed: property_is_name(property)"); return (const bt_bdname_t*)property->val; } int8_t property_as_rssi(const bt_property_t* property) { - log::assert_that(property_is_rssi(property), - "assert failed: property_is_rssi(property)"); + log::assert_that(property_is_rssi(property), "assert failed: property_is_rssi(property)"); return *(const int8_t*)property->val; } const Uuid* property_as_uuids(const bt_property_t* property, size_t* count) { - log::assert_that(property_is_uuids(property), - "assert failed: property_is_uuids(property)"); + log::assert_that(property_is_uuids(property), "assert failed: property_is_uuids(property)"); *count = sizeof(Uuid) / property->len; return (const Uuid*)property->val; } -static bt_property_t* property_new_(void* val, size_t len, - bt_property_type_t type) { - bt_property_t* property = - static_cast(osi_calloc(sizeof(bt_property_t))); +static bt_property_t* property_new_(void* val, size_t len, bt_property_type_t type) { + bt_property_t* property = static_cast(osi_calloc(sizeof(bt_property_t))); property->val = osi_calloc(len + 1); if (type == BT_PROPERTY_BDNAME) { diff --git a/system/btcore/test/device_class_test.cc b/system/btcore/test/device_class_test.cc index 64d93e65150..bdd6c69ce2b 100644 --- a/system/btcore/test/device_class_test.cc +++ b/system/btcore/test/device_class_test.cc @@ -21,9 +21,10 @@ #include #include -::testing::AssertionResult check_bitfield(const char* m_expr, - const char* n_expr, int m, int n) { - if (m == n) return ::testing::AssertionSuccess(); +::testing::AssertionResult check_bitfield(const char* m_expr, const char* n_expr, int m, int n) { + if (m == n) { + return ::testing::AssertionSuccess(); + } std::stringstream ss; @@ -35,9 +36,8 @@ ss << std::showbase << std::hex << std::setw(8) << std::setfill('0') << n; std::string actual_str = ss.str(); - return ::testing::AssertionFailure() << m_expr << " and " << n_expr << " ( " - << expected_str << " vs " << actual_str - << " )"; + return ::testing::AssertionFailure() + << m_expr << " and " << n_expr << " ( " << expected_str << " vs " << actual_str << " )"; } class DeviceClassTest : public ::testing::Test {}; @@ -51,8 +51,8 @@ TEST_F(DeviceClassTest, cod_sizeof) { TEST_F(DeviceClassTest, simple) { uint8_t dc_stream[][sizeof(bt_device_class_t)] = { - {0x00, 0x00, 0x00}, {0xff, 0xff, 0xff}, {0xaa, 0x55, 0xaa}, - {0x01, 0x23, 0x45}, {0x20, 0x07, 0x14}, + {0x00, 0x00, 0x00}, {0xff, 0xff, 0xff}, {0xaa, 0x55, 0xaa}, + {0x01, 0x23, 0x45}, {0x20, 0x07, 0x14}, }; for (size_t i = 0; i < sizeof(dc_stream) / sizeof(bt_device_class_t); i++) { @@ -60,12 +60,9 @@ TEST_F(DeviceClassTest, simple) { device_class_from_stream(&dc, (uint8_t*)&dc_stream[i]); uint8_t* to_stream = (uint8_t*)&dc; - EXPECT_PRED_FORMAT2(check_bitfield, (unsigned)dc_stream[i][0], - to_stream[0]); - EXPECT_PRED_FORMAT2(check_bitfield, (unsigned)dc_stream[i][1], - to_stream[1]); - EXPECT_PRED_FORMAT2(check_bitfield, (unsigned)dc_stream[i][2], - to_stream[2]); + EXPECT_PRED_FORMAT2(check_bitfield, (unsigned)dc_stream[i][0], to_stream[0]); + EXPECT_PRED_FORMAT2(check_bitfield, (unsigned)dc_stream[i][1], to_stream[1]); + EXPECT_PRED_FORMAT2(check_bitfield, (unsigned)dc_stream[i][2], to_stream[2]); } } diff --git a/system/btcore/test/property_test.cc b/system/btcore/test/property_test.cc index ce37cd70679..7477bca1a9c 100644 --- a/system/btcore/test/property_test.cc +++ b/system/btcore/test/property_test.cc @@ -122,8 +122,22 @@ TEST_F(PropertyTest, rssi) { TEST_F(PropertyTest, uuids) { Uuid uuid0 = Uuid::From128BitBE({{ - 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, - 0xcc, 0xdd, 0xee, 0xff, + 0x00, + 0x11, + 0x22, + 0x33, + 0x44, + 0x55, + 0x66, + 0x77, + 0x88, + 0x99, + 0xaa, + 0xbb, + 0xcc, + 0xdd, + 0xee, + 0xff, }}); bt_property_t* property = property_new_uuids(&uuid0, 1); @@ -141,18 +155,45 @@ TEST_F(PropertyTest, uuids) { TEST_F(PropertyTest, copy) { { Uuid uuids[] = { - Uuid::From128BitBE({{ - 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, - 0xbb, 0xcc, 0xdd, 0xee, 0xff, - }}), - Uuid::From128BitBE({{ - 0xf0, 0xe1, 0xd2, 0xc3, 0xf4, 0xe5, 0xd6, 0xc7, 0xf8, 0xe9, 0xda, - 0xcb, 0xfc, 0xed, 0xde, 0xcf, - }}), + Uuid::From128BitBE({{ + 0x00, + 0x11, + 0x22, + 0x33, + 0x44, + 0x55, + 0x66, + 0x77, + 0x88, + 0x99, + 0xaa, + 0xbb, + 0xcc, + 0xdd, + 0xee, + 0xff, + }}), + Uuid::From128BitBE({{ + 0xf0, + 0xe1, + 0xd2, + 0xc3, + 0xf4, + 0xe5, + 0xd6, + 0xc7, + 0xf8, + 0xe9, + 0xda, + 0xcb, + 0xfc, + 0xed, + 0xde, + 0xcf, + }}), }; - bt_property_t* property0 = - property_new_uuids(uuids, sizeof(uuids) / sizeof(Uuid)); + bt_property_t* property0 = property_new_uuids(uuids, sizeof(uuids) / sizeof(Uuid)); bt_property_t property1; property_copy(&property1, property0); diff --git a/system/btif/avrcp/avrcp_service.cc b/system/btif/avrcp/avrcp_service.cc index 71ece09535d..b968b6f930c 100644 --- a/system/btif/avrcp/avrcp_service.cc +++ b/system/btif/avrcp/avrcp_service.cc @@ -52,59 +52,47 @@ class A2dpInterfaceImpl : public A2dpInterface { return btif_av_is_peer_silenced(peer_address); } - void connect_audio_sink_delayed(uint8_t handle, - const RawAddress& peer_address) override { + void connect_audio_sink_delayed(uint8_t handle, const RawAddress& peer_address) override { btif_av_connect_sink_delayed(handle, peer_address); } uint16_t find_audio_sink_service(const RawAddress& peer_address, tA2DP_FIND_CBACK p_cback) override { - uint16_t attr_list[] = {ATTR_ID_SERVICE_CLASS_ID_LIST, - ATTR_ID_BT_PROFILE_DESC_LIST, + uint16_t attr_list[] = {ATTR_ID_SERVICE_CLASS_ID_LIST, ATTR_ID_BT_PROFILE_DESC_LIST, ATTR_ID_SUPPORTED_FEATURES}; tA2DP_SDP_DB_PARAMS db_params = { - .db_len = BT_DEFAULT_BUFFER_SIZE, - .num_attr = ARRAY_SIZE(attr_list), - .p_attrs = attr_list, + .db_len = BT_DEFAULT_BUFFER_SIZE, + .num_attr = ARRAY_SIZE(attr_list), + .p_attrs = attr_list, }; - return A2DP_FindService(UUID_SERVCLASS_AUDIO_SINK, peer_address, &db_params, - p_cback); + return A2DP_FindService(UUID_SERVCLASS_AUDIO_SINK, peer_address, &db_params, p_cback); } } a2dp_interface_; class AvrcpInterfaceImpl : public AvrcpInterface { - public: +public: uint16_t GetAvrcpControlVersion() { return AVRC_GetControlProfileVersion(); } - uint16_t GetAvrcpVersion() { - return AVRC_GetProfileVersion(); - } + uint16_t GetAvrcpVersion() { return AVRC_GetProfileVersion(); } - uint16_t AddRecord(uint16_t service_uuid, const char* p_service_name, - const char* p_provider_name, uint16_t categories, - uint32_t sdp_handle, bool browse_supported, - uint16_t profile_version, - uint16_t cover_art_psm) override { - return AVRC_AddRecord(service_uuid, p_service_name, p_provider_name, - categories, sdp_handle, browse_supported, - profile_version, cover_art_psm); + uint16_t AddRecord(uint16_t service_uuid, const char* p_service_name, const char* p_provider_name, + uint16_t categories, uint32_t sdp_handle, bool browse_supported, + uint16_t profile_version, uint16_t cover_art_psm) override { + return AVRC_AddRecord(service_uuid, p_service_name, p_provider_name, categories, sdp_handle, + browse_supported, profile_version, cover_art_psm); } - uint16_t RemoveRecord(uint32_t sdp_handle) { - return AVRC_RemoveRecord(sdp_handle); - } + uint16_t RemoveRecord(uint32_t sdp_handle) { return AVRC_RemoveRecord(sdp_handle); } - uint16_t FindService(uint16_t service_uuid, const RawAddress& bd_addr, - tAVRC_SDP_DB_PARAMS* p_db, + uint16_t FindService(uint16_t service_uuid, const RawAddress& bd_addr, tAVRC_SDP_DB_PARAMS* p_db, tAVRC_FIND_CBACK p_cback) override { return AVRC_FindService(service_uuid, bd_addr, p_db, p_cback); } - uint16_t Open(uint8_t* p_handle, tAVRC_CONN_CB* p_ccb, - const RawAddress& bd_addr) override { + uint16_t Open(uint8_t* p_handle, tAVRC_CONN_CB* p_ccb, const RawAddress& bd_addr) override { return AVRC_Open(p_handle, p_ccb, bd_addr); } @@ -112,49 +100,37 @@ class AvrcpInterfaceImpl : public AvrcpInterface { return AVRC_OpenBrowse(handle, conn_role); } - uint16_t GetPeerMtu(uint8_t handle) override { - return AVCT_GetPeerMtu(handle); - } + uint16_t GetPeerMtu(uint8_t handle) override { return AVCT_GetPeerMtu(handle); } - uint16_t GetBrowseMtu(uint8_t handle) override { - return AVCT_GetBrowseMtu(handle); - } + uint16_t GetBrowseMtu(uint8_t handle) override { return AVCT_GetBrowseMtu(handle); } uint16_t Close(uint8_t handle) override { return AVRC_Close(handle); } - uint16_t CloseBrowse(uint8_t handle) override { - return AVRC_CloseBrowse(handle); - } + uint16_t CloseBrowse(uint8_t handle) override { return AVRC_CloseBrowse(handle); } - uint16_t MsgReq(uint8_t handle, uint8_t label, uint8_t ctype, - BT_HDR* p_pkt) override { + uint16_t MsgReq(uint8_t handle, uint8_t label, uint8_t ctype, BT_HDR* p_pkt) override { return AVRC_MsgReq(handle, label, ctype, p_pkt, true); } - void SaveControllerVersion(const RawAddress& bdaddr, - uint16_t version) override { + void SaveControllerVersion(const RawAddress& bdaddr, uint16_t version) override { AVRC_SaveControllerVersion(bdaddr, version); } } avrcp_interface_; class SdpInterfaceImpl : public SdpInterface { - public: - bool InitDiscoveryDb(tSDP_DISCOVERY_DB* a, uint32_t b, uint16_t c, - const bluetooth::Uuid* d, uint16_t e, - uint16_t* f) override { - return get_legacy_stack_sdp_api()->service.SDP_InitDiscoveryDb(a, b, c, d, - e, f); +public: + bool InitDiscoveryDb(tSDP_DISCOVERY_DB* a, uint32_t b, uint16_t c, const bluetooth::Uuid* d, + uint16_t e, uint16_t* f) override { + return get_legacy_stack_sdp_api()->service.SDP_InitDiscoveryDb(a, b, c, d, e, f); } bool ServiceSearchAttributeRequest(const RawAddress& a, tSDP_DISCOVERY_DB* b, tSDP_DISC_CMPL_CB* c) override { - return get_legacy_stack_sdp_api() - ->service.SDP_ServiceSearchAttributeRequest(a, b, c); + return get_legacy_stack_sdp_api()->service.SDP_ServiceSearchAttributeRequest(a, b, c); } - tSDP_DISC_REC* FindServiceInDb(tSDP_DISCOVERY_DB* a, uint16_t b, - t_sdp_disc_rec* c) override { + tSDP_DISC_REC* FindServiceInDb(tSDP_DISCOVERY_DB* a, uint16_t b, t_sdp_disc_rec* c) override { return get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb(a, b, c); } @@ -162,22 +138,20 @@ class SdpInterfaceImpl : public SdpInterface { return get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec(a, b); } - bool FindProfileVersionInRec(t_sdp_disc_rec* a, uint16_t b, - uint16_t* c) override { - return get_legacy_stack_sdp_api()->record.SDP_FindProfileVersionInRec(a, b, - c); + bool FindProfileVersionInRec(t_sdp_disc_rec* a, uint16_t b, uint16_t* c) override { + return get_legacy_stack_sdp_api()->record.SDP_FindProfileVersionInRec(a, b, c); } } sdp_interface_; // A wrapper class for the media callbacks that handles thread // switching/synchronization so the devices don't have to worry about it. class MediaInterfaceWrapper : public MediaInterface { - public: - MediaInterfaceWrapper(MediaInterface* cb) : wrapped_(cb){}; +public: + MediaInterfaceWrapper(MediaInterface* cb) : wrapped_(cb) {} void SendKeyEvent(uint8_t key, KeyState state) override { - do_in_jni_thread(base::Bind(&MediaInterface::SendKeyEvent, - base::Unretained(wrapped_), key, state)); + do_in_jni_thread( + base::Bind(&MediaInterface::SendKeyEvent, base::Unretained(wrapped_), key, state)); } void GetSongInfo(SongInfoCallback info_cb) override { @@ -187,8 +161,8 @@ class MediaInterfaceWrapper : public MediaInterface { auto bound_cb = base::Bind(cb_lambda, info_cb); - do_in_jni_thread(base::Bind(&MediaInterface::GetSongInfo, - base::Unretained(wrapped_), bound_cb)); + do_in_jni_thread( + base::Bind(&MediaInterface::GetSongInfo, base::Unretained(wrapped_), bound_cb)); } void GetPlayStatus(PlayStatusCallback status_cb) override { @@ -198,75 +172,66 @@ class MediaInterfaceWrapper : public MediaInterface { auto bound_cb = base::Bind(cb_lambda, status_cb); - do_in_jni_thread(base::Bind(&MediaInterface::GetPlayStatus, - base::Unretained(wrapped_), bound_cb)); + do_in_jni_thread( + base::Bind(&MediaInterface::GetPlayStatus, base::Unretained(wrapped_), bound_cb)); } void GetNowPlayingList(NowPlayingCallback now_playing_cb) override { auto cb_lambda = [](NowPlayingCallback cb, std::string curr_media_id, std::vector song_list) { - do_in_main_thread( - FROM_HERE, base::BindOnce(cb, curr_media_id, std::move(song_list))); + do_in_main_thread(FROM_HERE, base::BindOnce(cb, curr_media_id, std::move(song_list))); }; auto bound_cb = base::Bind(cb_lambda, now_playing_cb); - do_in_jni_thread(base::Bind(&MediaInterface::GetNowPlayingList, - base::Unretained(wrapped_), bound_cb)); + do_in_jni_thread( + base::Bind(&MediaInterface::GetNowPlayingList, base::Unretained(wrapped_), bound_cb)); } void GetMediaPlayerList(MediaListCallback list_cb) override { auto cb_lambda = [](MediaListCallback cb, uint16_t curr_player, std::vector player_list) { - do_in_main_thread( - FROM_HERE, base::BindOnce(cb, curr_player, std::move(player_list))); + do_in_main_thread(FROM_HERE, base::BindOnce(cb, curr_player, std::move(player_list))); }; auto bound_cb = base::Bind(cb_lambda, list_cb); - do_in_jni_thread(base::Bind(&MediaInterface::GetMediaPlayerList, - base::Unretained(wrapped_), bound_cb)); + do_in_jni_thread( + base::Bind(&MediaInterface::GetMediaPlayerList, base::Unretained(wrapped_), bound_cb)); } void GetFolderItems(uint16_t player_id, std::string media_id, FolderItemsCallback folder_cb) override { - auto cb_lambda = [](FolderItemsCallback cb, - std::vector item_list) { + auto cb_lambda = [](FolderItemsCallback cb, std::vector item_list) { do_in_main_thread(FROM_HERE, base::BindOnce(cb, std::move(item_list))); }; auto bound_cb = base::Bind(cb_lambda, folder_cb); - do_in_jni_thread(base::Bind(&MediaInterface::GetFolderItems, - base::Unretained(wrapped_), player_id, media_id, - bound_cb)); + do_in_jni_thread(base::Bind(&MediaInterface::GetFolderItems, base::Unretained(wrapped_), + player_id, media_id, bound_cb)); } - void SetBrowsedPlayer(uint16_t player_id, - SetBrowsedPlayerCallback browse_cb) override { - auto cb_lambda = [](SetBrowsedPlayerCallback cb, bool success, - std::string root_id, uint32_t num_items) { - do_in_main_thread(FROM_HERE, - base::BindOnce(cb, success, root_id, num_items)); + void SetBrowsedPlayer(uint16_t player_id, SetBrowsedPlayerCallback browse_cb) override { + auto cb_lambda = [](SetBrowsedPlayerCallback cb, bool success, std::string root_id, + uint32_t num_items) { + do_in_main_thread(FROM_HERE, base::BindOnce(cb, success, root_id, num_items)); }; auto bound_cb = base::Bind(cb_lambda, browse_cb); - do_in_jni_thread(base::Bind(&MediaInterface::SetBrowsedPlayer, - base::Unretained(wrapped_), player_id, - bound_cb)); + do_in_jni_thread(base::Bind(&MediaInterface::SetBrowsedPlayer, base::Unretained(wrapped_), + player_id, bound_cb)); } - void PlayItem(uint16_t player_id, bool now_playing, - std::string media_id) override { - do_in_jni_thread(base::Bind(&MediaInterface::PlayItem, - base::Unretained(wrapped_), player_id, + void PlayItem(uint16_t player_id, bool now_playing, std::string media_id) override { + do_in_jni_thread(base::Bind(&MediaInterface::PlayItem, base::Unretained(wrapped_), player_id, now_playing, media_id)); } void SetActiveDevice(const RawAddress& address) override { - do_in_jni_thread(base::Bind(&MediaInterface::SetActiveDevice, - base::Unretained(wrapped_), address)); + do_in_jni_thread( + base::Bind(&MediaInterface::SetActiveDevice, base::Unretained(wrapped_), address)); } void RegisterUpdateCallback(MediaCallbacks* callback) override { @@ -277,21 +242,20 @@ class MediaInterfaceWrapper : public MediaInterface { wrapped_->UnregisterUpdateCallback(callback); } - private: +private: MediaInterface* wrapped_; }; // A wrapper class for the media callbacks that handles thread // switching/synchronization so the devices don't have to worry about it. class VolumeInterfaceWrapper : public VolumeInterface { - public: - VolumeInterfaceWrapper(VolumeInterface* interface) : wrapped_(interface){}; +public: + VolumeInterfaceWrapper(VolumeInterface* interface) : wrapped_(interface) {} void DeviceConnected(const RawAddress& bdaddr) override { - do_in_jni_thread( - base::Bind(static_cast( - &VolumeInterface::DeviceConnected), - base::Unretained(wrapped_), bdaddr)); + do_in_jni_thread(base::Bind(static_cast( + &VolumeInterface::DeviceConnected), + base::Unretained(wrapped_), bdaddr)); } void DeviceConnected(const RawAddress& bdaddr, VolumeChangedCb cb) override { @@ -301,32 +265,30 @@ class VolumeInterfaceWrapper : public VolumeInterface { auto bound_cb = base::Bind(cb_lambda, cb); - do_in_jni_thread(base::Bind(static_cast( - &VolumeInterface::DeviceConnected), - base::Unretained(wrapped_), bdaddr, bound_cb)); + do_in_jni_thread( + base::Bind(static_cast( + &VolumeInterface::DeviceConnected), + base::Unretained(wrapped_), bdaddr, bound_cb)); } void DeviceDisconnected(const RawAddress& bdaddr) override { - do_in_jni_thread(base::Bind(&VolumeInterface::DeviceDisconnected, - base::Unretained(wrapped_), bdaddr)); + do_in_jni_thread( + base::Bind(&VolumeInterface::DeviceDisconnected, base::Unretained(wrapped_), bdaddr)); } void SetVolume(int8_t volume) override { - do_in_jni_thread(base::Bind(&VolumeInterface::SetVolume, - base::Unretained(wrapped_), volume)); + do_in_jni_thread(base::Bind(&VolumeInterface::SetVolume, base::Unretained(wrapped_), volume)); } - private: +private: VolumeInterface* wrapped_; }; // A wrapper class for the media callbacks that handles thread // switching/synchronization so the devices don't have to worry about it. class PlayerSettingsInterfaceWrapper : public PlayerSettingsInterface { - public: - PlayerSettingsInterfaceWrapper(PlayerSettingsInterface* interface) - : wrapped_(interface){}; +public: + PlayerSettingsInterfaceWrapper(PlayerSettingsInterface* interface) : wrapped_(interface) {} void ListPlayerSettings(ListPlayerSettingsCallback cb) override { auto cb_lambda = [](const ListPlayerSettingsCallback& cb, @@ -342,38 +304,31 @@ class PlayerSettingsInterfaceWrapper : public PlayerSettingsInterface { void ListPlayerSettingValues(PlayerAttribute setting, ListPlayerSettingValuesCallback cb) override { - auto cb_lambda = [](const ListPlayerSettingValuesCallback& cb, - PlayerAttribute setting, std::vector values) { - do_in_main_thread(FROM_HERE, - base::BindOnce(cb, setting, std::move(values))); + auto cb_lambda = [](const ListPlayerSettingValuesCallback& cb, PlayerAttribute setting, + std::vector values) { + do_in_main_thread(FROM_HERE, base::BindOnce(cb, setting, std::move(values))); }; auto bound_cb = base::Bind(cb_lambda, cb); - do_in_jni_thread( - base::Bind(&PlayerSettingsInterface::ListPlayerSettingValues, - base::Unretained(wrapped_), setting, bound_cb)); + do_in_jni_thread(base::Bind(&PlayerSettingsInterface::ListPlayerSettingValues, + base::Unretained(wrapped_), setting, bound_cb)); } - void GetCurrentPlayerSettingValue( - std::vector attributes, - GetCurrentPlayerSettingValueCallback cb) override { + void GetCurrentPlayerSettingValue(std::vector attributes, + GetCurrentPlayerSettingValueCallback cb) override { auto cb_lambda = [](const GetCurrentPlayerSettingValueCallback& cb, - std::vector attributes, - std::vector values) { - do_in_main_thread(FROM_HERE, base::BindOnce(cb, std::move(attributes), - std::move(values))); + std::vector attributes, std::vector values) { + do_in_main_thread(FROM_HERE, base::BindOnce(cb, std::move(attributes), std::move(values))); }; auto bound_cb = base::Bind(cb_lambda, cb); - do_in_jni_thread(base::Bind( - &PlayerSettingsInterface::GetCurrentPlayerSettingValue, - base::Unretained(wrapped_), std::move(attributes), bound_cb)); + do_in_jni_thread(base::Bind(&PlayerSettingsInterface::GetCurrentPlayerSettingValue, + base::Unretained(wrapped_), std::move(attributes), bound_cb)); } - void SetPlayerSettings(std::vector attributes, - std::vector values, + void SetPlayerSettings(std::vector attributes, std::vector values, SetPlayerSettingValueCallback cb) override { auto cb_lambda = [](const SetPlayerSettingValueCallback& cb, bool success) { do_in_main_thread(FROM_HERE, base::BindOnce(cb, success)); @@ -381,17 +336,16 @@ class PlayerSettingsInterfaceWrapper : public PlayerSettingsInterface { auto bound_cb = base::Bind(cb_lambda, cb); - do_in_jni_thread(base::Bind( - &PlayerSettingsInterface::SetPlayerSettings, base::Unretained(wrapped_), - std::move(attributes), std::move(values), bound_cb)); + do_in_jni_thread(base::Bind(&PlayerSettingsInterface::SetPlayerSettings, + base::Unretained(wrapped_), std::move(attributes), + std::move(values), bound_cb)); } - private: +private: PlayerSettingsInterface* wrapped_; }; -void AvrcpService::Init(MediaInterface* media_interface, - VolumeInterface* volume_interface, +void AvrcpService::Init(MediaInterface* media_interface, VolumeInterface* volume_interface, PlayerSettingsInterface* player_settings_interface) { log::info("AVRCP Target Service started"); @@ -400,17 +354,14 @@ void AvrcpService::Init(MediaInterface* media_interface, uint16_t supported_features = GetSupportedFeatures(profile_version); sdp_record_handle = get_legacy_stack_sdp_api()->handle.SDP_CreateRecord(); - avrcp_interface_.AddRecord(UUID_SERVCLASS_AV_REM_CTRL_TARGET, - "AV Remote Control Target", NULL, - supported_features, sdp_record_handle, true, - profile_version, 0); + avrcp_interface_.AddRecord(UUID_SERVCLASS_AV_REM_CTRL_TARGET, "AV Remote Control Target", NULL, + supported_features, sdp_record_handle, true, profile_version, 0); bta_sys_add_uuid(UUID_SERVCLASS_AV_REM_CTRL_TARGET); ct_sdp_record_handle = get_legacy_stack_sdp_api()->handle.SDP_CreateRecord(); - avrcp_interface_.AddRecord(UUID_SERVCLASS_AV_REMOTE_CONTROL, - "AV Remote Control", NULL, AVRCP_SUPF_TG_CT, - ct_sdp_record_handle, false, + avrcp_interface_.AddRecord(UUID_SERVCLASS_AV_REMOTE_CONTROL, "AV Remote Control", NULL, + AVRCP_SUPF_TG_CT, ct_sdp_record_handle, false, avrcp_interface_.GetAvrcpControlVersion(), 0); bta_sys_add_uuid(UUID_SERVCLASS_AV_REMOTE_CONTROL); @@ -427,15 +378,14 @@ void AvrcpService::Init(MediaInterface* media_interface, PlayerSettingsInterfaceWrapper* wrapped_player_settings_interface = nullptr; if (player_settings_interface != nullptr) { wrapped_player_settings_interface = - new PlayerSettingsInterfaceWrapper(player_settings_interface); + new PlayerSettingsInterfaceWrapper(player_settings_interface); } player_settings_interface_ = wrapped_player_settings_interface; ConnectionHandler::Initialize( - base::BindRepeating(&AvrcpService::DeviceCallback, - base::Unretained(instance_)), - &avrcp_interface_, &sdp_interface_, wrapped_volume_interface); + base::BindRepeating(&AvrcpService::DeviceCallback, base::Unretained(instance_)), + &avrcp_interface_, &sdp_interface_, wrapped_volume_interface); connection_handler_ = ConnectionHandler::Get(); } @@ -475,16 +425,13 @@ void AvrcpService::Cleanup() { } void AvrcpService::RegisterBipServer(int psm) { - log::info("AVRCP Target Service has registered a BIP OBEX server, psm={}", - psm); + log::info("AVRCP Target Service has registered a BIP OBEX server, psm={}", psm); avrcp_interface_.RemoveRecord(sdp_record_handle); - uint16_t supported_features - = GetSupportedFeatures(profile_version) | AVRC_SUPF_TG_PLAYER_COVER_ART; + uint16_t supported_features = + GetSupportedFeatures(profile_version) | AVRC_SUPF_TG_PLAYER_COVER_ART; sdp_record_handle = get_legacy_stack_sdp_api()->handle.SDP_CreateRecord(); - avrcp_interface_.AddRecord(UUID_SERVCLASS_AV_REM_CTRL_TARGET, - "AV Remote Control Target", NULL, - supported_features, sdp_record_handle, true, - profile_version, psm); + avrcp_interface_.AddRecord(UUID_SERVCLASS_AV_REM_CTRL_TARGET, "AV Remote Control Target", NULL, + supported_features, sdp_record_handle, true, profile_version, psm); } void AvrcpService::UnregisterBipServer() { @@ -492,10 +439,8 @@ void AvrcpService::UnregisterBipServer() { avrcp_interface_.RemoveRecord(sdp_record_handle); uint16_t supported_features = GetSupportedFeatures(profile_version); sdp_record_handle = get_legacy_stack_sdp_api()->handle.SDP_CreateRecord(); - avrcp_interface_.AddRecord(UUID_SERVCLASS_AV_REM_CTRL_TARGET, - "AV Remote Control Target", NULL, - supported_features, sdp_record_handle, true, - profile_version, 0); + avrcp_interface_.AddRecord(UUID_SERVCLASS_AV_REM_CTRL_TARGET, "AV Remote Control Target", NULL, + supported_features, sdp_record_handle, true, profile_version, 0); } AvrcpService* AvrcpService::Get() { @@ -522,39 +467,30 @@ void AvrcpService::DisconnectDevice(const RawAddress& bdaddr) { connection_handler_->DisconnectDevice(bdaddr); } -void AvrcpService::SetBipClientStatus(const RawAddress& bdaddr, - bool connected) { +void AvrcpService::SetBipClientStatus(const RawAddress& bdaddr, bool connected) { log::info("address={}, connected={}", bdaddr, connected); connection_handler_->SetBipClientStatus(bdaddr, connected); } -void AvrcpService::SendMediaUpdate(bool track_changed, bool play_state, - bool queue) { - log::info("track_changed={} : play_state={} : queue={}", track_changed, - play_state, queue); +void AvrcpService::SendMediaUpdate(bool track_changed, bool play_state, bool queue) { + log::info("track_changed={} : play_state={} : queue={}", track_changed, play_state, queue); // This function may be called on any thread, we need to make sure that the // device update happens on the main thread. - for (const auto& device : - instance_->connection_handler_->GetListOfDevices()) { - do_in_main_thread( - FROM_HERE, base::BindOnce(&Device::SendMediaUpdate, device.get()->Get(), - track_changed, play_state, queue)); + for (const auto& device : instance_->connection_handler_->GetListOfDevices()) { + do_in_main_thread(FROM_HERE, base::BindOnce(&Device::SendMediaUpdate, device.get()->Get(), + track_changed, play_state, queue)); } } -void AvrcpService::SendFolderUpdate(bool available_players, - bool addressed_players, bool uids) { - log::info("available_players={} : addressed_players={} : uids={}", - available_players, addressed_players, uids); +void AvrcpService::SendFolderUpdate(bool available_players, bool addressed_players, bool uids) { + log::info("available_players={} : addressed_players={} : uids={}", available_players, + addressed_players, uids); // Ensure that the update is posted to the correct thread - for (const auto& device : - instance_->connection_handler_->GetListOfDevices()) { - do_in_main_thread( - FROM_HERE, - base::BindOnce(&Device::SendFolderUpdate, device.get()->Get(), - available_players, addressed_players, uids)); + for (const auto& device : instance_->connection_handler_->GetListOfDevices()) { + do_in_main_thread(FROM_HERE, base::BindOnce(&Device::SendFolderUpdate, device.get()->Get(), + available_players, addressed_players, uids)); } } @@ -563,11 +499,10 @@ void AvrcpService::SendActiveDeviceChanged(const RawAddress& address) { SendMediaUpdate(false, true, false); } -void AvrcpService::SendPlayerSettingsChanged( - std::vector attributes, std::vector values) { +void AvrcpService::SendPlayerSettingsChanged(std::vector attributes, + std::vector values) { if (attributes.size() != values.size()) { - log::error("Attributes size {} doesn't match values size {}", - attributes.size(), values.size()); + log::error("Attributes size {} doesn't match values size {}", attributes.size(), values.size()); return; } std::stringstream ss; @@ -586,27 +521,27 @@ void AvrcpService::SendPlayerSettingsChanged( log::info("{}", ss.str()); // Ensure that the update is posted to the correct thread - for (const auto& device : - instance_->connection_handler_->GetListOfDevices()) { - do_in_main_thread(FROM_HERE, - base::BindOnce(&Device::HandlePlayerSettingChanged, - device.get()->Get(), attributes, values)); + for (const auto& device : instance_->connection_handler_->GetListOfDevices()) { + do_in_main_thread(FROM_HERE, base::BindOnce(&Device::HandlePlayerSettingChanged, + device.get()->Get(), attributes, values)); } } void AvrcpService::DeviceCallback(std::shared_ptr new_device) { - if (new_device == nullptr) return; + if (new_device == nullptr) { + return; + } // TODO (apanicke): Pass the interfaces into the connection handler // so that the devices can be created with any interfaces they need. - new_device->RegisterInterfaces(media_interface_, &a2dp_interface_, - volume_interface_, player_settings_interface_); + new_device->RegisterInterfaces(media_interface_, &a2dp_interface_, volume_interface_, + player_settings_interface_); } // Service Interface -void AvrcpService::ServiceInterfaceImpl::Init( - MediaInterface* media_interface, VolumeInterface* volume_interface, - PlayerSettingsInterface* player_settings_interface) { +void AvrcpService::ServiceInterfaceImpl::Init(MediaInterface* media_interface, + VolumeInterface* volume_interface, + PlayerSettingsInterface* player_settings_interface) { std::lock_guard lock(service_interface_lock_); // TODO: This function should block until the service is completely up so @@ -616,45 +551,38 @@ void AvrcpService::ServiceInterfaceImpl::Init( log::assert_that(instance_ == nullptr, "assert failed: instance_ == nullptr"); instance_ = new AvrcpService(); - do_in_main_thread( - FROM_HERE, base::BindOnce(&AvrcpService::Init, - base::Unretained(instance_), media_interface, - volume_interface, player_settings_interface)); + do_in_main_thread(FROM_HERE, + base::BindOnce(&AvrcpService::Init, base::Unretained(instance_), + media_interface, volume_interface, player_settings_interface)); } void AvrcpService::ServiceInterfaceImpl::RegisterBipServer(int psm) { std::lock_guard lock(service_interface_lock_); log::assert_that(instance_ != nullptr, "assert failed: instance_ != nullptr"); - do_in_main_thread(FROM_HERE, - base::BindOnce(&AvrcpService::RegisterBipServer, - base::Unretained(instance_), psm)); + do_in_main_thread(FROM_HERE, base::BindOnce(&AvrcpService::RegisterBipServer, + base::Unretained(instance_), psm)); } void AvrcpService::ServiceInterfaceImpl::UnregisterBipServer() { std::lock_guard lock(service_interface_lock_); log::assert_that(instance_ != nullptr, "assert failed: instance_ != nullptr"); - do_in_main_thread(FROM_HERE, - base::BindOnce(&AvrcpService::UnregisterBipServer, - base::Unretained(instance_))); + do_in_main_thread(FROM_HERE, base::BindOnce(&AvrcpService::UnregisterBipServer, + base::Unretained(instance_))); } -bool AvrcpService::ServiceInterfaceImpl::ConnectDevice( - const RawAddress& bdaddr) { +bool AvrcpService::ServiceInterfaceImpl::ConnectDevice(const RawAddress& bdaddr) { std::lock_guard lock(service_interface_lock_); log::assert_that(instance_ != nullptr, "assert failed: instance_ != nullptr"); - do_in_main_thread(FROM_HERE, - base::BindOnce(&AvrcpService::ConnectDevice, - base::Unretained(instance_), bdaddr)); + do_in_main_thread(FROM_HERE, base::BindOnce(&AvrcpService::ConnectDevice, + base::Unretained(instance_), bdaddr)); return true; } -bool AvrcpService::ServiceInterfaceImpl::DisconnectDevice( - const RawAddress& bdaddr) { +bool AvrcpService::ServiceInterfaceImpl::DisconnectDevice(const RawAddress& bdaddr) { std::lock_guard lock(service_interface_lock_); log::assert_that(instance_ != nullptr, "assert failed: instance_ != nullptr"); - do_in_main_thread(FROM_HERE, - base::BindOnce(&AvrcpService::DisconnectDevice, - base::Unretained(instance_), bdaddr)); + do_in_main_thread(FROM_HERE, base::BindOnce(&AvrcpService::DisconnectDevice, + base::Unretained(instance_), bdaddr)); return true; } @@ -679,22 +607,22 @@ bool AvrcpService::IsDeviceConnected(const RawAddress& bdaddr) { return false; } -void AvrcpService::ServiceInterfaceImpl::SetBipClientStatus( - const RawAddress& bdaddr, bool connected) { +void AvrcpService::ServiceInterfaceImpl::SetBipClientStatus(const RawAddress& bdaddr, + bool connected) { std::lock_guard lock(service_interface_lock_); log::assert_that(instance_ != nullptr, "assert failed: instance_ != nullptr"); do_in_main_thread(FROM_HERE, base::BindOnce(&AvrcpService::SetBipClientStatus, - base::Unretained(instance_), - bdaddr, connected)); + base::Unretained(instance_), bdaddr, connected)); } bool AvrcpService::ServiceInterfaceImpl::Cleanup() { std::lock_guard lock(service_interface_lock_); - if (instance_ == nullptr) return false; + if (instance_ == nullptr) { + return false; + } - do_in_main_thread(FROM_HERE, base::BindOnce(&AvrcpService::Cleanup, - base::Owned(instance_))); + do_in_main_thread(FROM_HERE, base::BindOnce(&AvrcpService::Cleanup, base::Owned(instance_))); // Setting instance to nullptr here is fine since it will be deleted on the // other thread. @@ -716,8 +644,7 @@ void AvrcpService::DebugDump(int fd) { } auto device_list = handler->GetListOfDevices(); - dprintf(fd, "\nAVRCP Target Native Service: %zu devices\n", - device_list.size()); + dprintf(fd, "\nAVRCP Target Native Service: %zu devices\n", device_list.size()); std::stringstream stream; for (const auto& device : device_list) { diff --git a/system/btif/avrcp/avrcp_service.h b/system/btif/avrcp/avrcp_service.h index bb8fcd5f5b8..dc5513bdede 100644 --- a/system/btif/avrcp/avrcp_service.h +++ b/system/btif/avrcp/avrcp_service.h @@ -37,7 +37,7 @@ namespace avrcp { * it indirectly. */ class AvrcpService : public MediaCallbacks { - public: +public: /** * Gets a handle to the AvrcpService * @@ -67,10 +67,8 @@ class AvrcpService : public MediaCallbacks { void SetBipClientStatus(const RawAddress& bdaddr, bool connected); // Functions inherited from MediaCallbacks in order to receive updates - void SendMediaUpdate(bool track_changed, bool play_state, - bool queue) override; - void SendFolderUpdate(bool available_players, bool addressed_player, - bool queue) override; + void SendMediaUpdate(bool track_changed, bool play_state, bool queue) override; + void SendFolderUpdate(bool available_players, bool addressed_player, bool queue) override; void SendActiveDeviceChanged(const RawAddress& address) override; void SendPlayerSettingsChanged(std::vector attributes, @@ -83,9 +81,8 @@ class AvrcpService : public MediaCallbacks { void RegisterVolChanged(const RawAddress& bdaddr); class ServiceInterfaceImpl : public ServiceInterface { - public: - void Init(MediaInterface* media_interface, - VolumeInterface* volume_interface, + public: + void Init(MediaInterface* media_interface, VolumeInterface* volume_interface, PlayerSettingsInterface* player_settings_interface) override; void RegisterBipServer(int psm) override; void UnregisterBipServer() override; @@ -94,17 +91,17 @@ class AvrcpService : public MediaCallbacks { void SetBipClientStatus(const RawAddress& bdaddr, bool connected) override; bool Cleanup() override; - private: + private: std::mutex service_interface_lock_; }; static void DebugDump(int fd); - protected: +protected: void DeviceCallback(std::shared_ptr device); uint16_t GetSupportedFeatures(uint16_t profile_version); - private: +private: static AvrcpService* instance_; static ServiceInterfaceImpl* service_interface_; diff --git a/system/btif/co/bta_av_co.cc b/system/btif/co/bta_av_co.cc index 2a906a87e10..3fc6a046038 100644 --- a/system/btif/co/bta_av_co.cc +++ b/system/btif/co/bta_av_co.cc @@ -72,18 +72,15 @@ void BtaAvCoState::setCodecConfig(const uint8_t* codec_config) { memcpy(codec_config_, codec_config, AVDT_CODEC_SIZE); } -void BtaAvCoState::clearCodecConfig() { - memset(codec_config_, 0, AVDT_CODEC_SIZE); -} +void BtaAvCoState::clearCodecConfig() { memset(codec_config_, 0, AVDT_CODEC_SIZE); } void BtaAvCoState::Reset() { active_peer_ = nullptr; clearCodecConfig(); } -void BtaAvCo::Init( - const std::vector& codec_priorities, - std::vector* supported_codecs) { +void BtaAvCo::Init(const std::vector& codec_priorities, + std::vector* supported_codecs) { log::verbose(""); std::lock_guard lock(peer_cache_->codec_lock_); @@ -95,8 +92,7 @@ void BtaAvCo::Init( // Gather the supported codecs from the first peer context; // all contexes should be identical. supported_codecs->clear(); - for (auto* codec_config : - peer_cache_->peers_[0].GetCodecs()->orderedSourceCodecs()) { + for (auto* codec_config : peer_cache_->peers_[0].GetCodecs()->orderedSourceCodecs()) { auto& codec_info = supported_codecs->emplace_back(); codec_info.codec_type = codec_config->codecIndex(); codec_info.codec_id = codec_config->codecId(); @@ -156,20 +152,17 @@ A2dpCodecConfig* BtaAvCo::GetPeerCurrentCodec(const RawAddress& peer_address) { return peer->GetCodecs()->getCurrentCodecConfig(); } -void BtaAvCo::ProcessDiscoveryResult(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_address, - uint8_t num_seps, uint8_t num_sinks, - uint8_t num_sources, uint16_t uuid_local) { - log::verbose( - "peer {} bta_av_handle:0x{:x} num_seps:{} num_sinks:{} num_sources:{}", - peer_address, bta_av_handle, num_seps, num_sinks, num_sources); +void BtaAvCo::ProcessDiscoveryResult(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, + uint8_t num_seps, uint8_t num_sinks, uint8_t num_sources, + uint16_t uuid_local) { + log::verbose("peer {} bta_av_handle:0x{:x} num_seps:{} num_sinks:{} num_sources:{}", peer_address, + bta_av_handle, num_seps, num_sinks, num_sources); // Find the peer - BtaAvCoPeer* p_peer = - peer_cache_->FindPeerAndUpdate(bta_av_handle, peer_address); + BtaAvCoPeer* p_peer = peer_cache_->FindPeerAndUpdate(bta_av_handle, peer_address); if (p_peer == nullptr) { - log::error("could not find peer entry for bta_av_handle 0x{:x} peer {}", - bta_av_handle, peer_address); + log::error("could not find peer entry for bta_av_handle 0x{:x} peer {}", bta_av_handle, + peer_address); return; } @@ -196,32 +189,28 @@ void BtaAvCo::ProcessDiscoveryResult(tBTA_AV_HNDL bta_av_handle, static void bta_av_co_store_peer_codectype(const BtaAvCoPeer* p_peer); static bool bta_av_co_should_select_hardware_codec( - const A2dpCodecConfig& software_config, - const ::bluetooth::audio::a2dp::provider::a2dp_configuration& - hardware_config); - -tA2DP_STATUS BtaAvCo::ProcessSourceGetConfig( - tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, - uint8_t* p_codec_info, uint8_t* p_sep_info_idx, uint8_t seid, - uint8_t* p_num_protect, uint8_t* p_protect_info) { - log::verbose("peer {} bta_av_handle:0x{:x} codec:{} seid:{}", peer_address, - bta_av_handle, A2DP_CodecName(p_codec_info), seid); - log::verbose("num_protect:0x{:02x} protect_info:0x{:02x}{:02x}{:02x}", - *p_num_protect, p_protect_info[0], p_protect_info[1], - p_protect_info[2]); + const A2dpCodecConfig& software_config, + const ::bluetooth::audio::a2dp::provider::a2dp_configuration& hardware_config); + +tA2DP_STATUS BtaAvCo::ProcessSourceGetConfig(tBTA_AV_HNDL bta_av_handle, + const RawAddress& peer_address, uint8_t* p_codec_info, + uint8_t* p_sep_info_idx, uint8_t seid, + uint8_t* p_num_protect, uint8_t* p_protect_info) { + log::verbose("peer {} bta_av_handle:0x{:x} codec:{} seid:{}", peer_address, bta_av_handle, + A2DP_CodecName(p_codec_info), seid); + log::verbose("num_protect:0x{:02x} protect_info:0x{:02x}{:02x}{:02x}", *p_num_protect, + p_protect_info[0], p_protect_info[1], p_protect_info[2]); log::verbose("codec: {}", A2DP_CodecInfoString(p_codec_info)); // Find the peer - BtaAvCoPeer* p_peer = - peer_cache_->FindPeerAndUpdate(bta_av_handle, peer_address); + BtaAvCoPeer* p_peer = peer_cache_->FindPeerAndUpdate(bta_av_handle, peer_address); if (p_peer == nullptr) { - log::error("could not find peer entry for bta_av_handle 0x{:x} peer {}", - bta_av_handle, peer_address); + log::error("could not find peer entry for bta_av_handle 0x{:x} peer {}", bta_av_handle, + peer_address); return A2DP_FAIL; } - log::verbose("peer(o={}, n_sinks={}, n_rx_sinks={}, n_sup_sinks={})", - p_peer->opened, p_peer->num_sinks, p_peer->num_rx_sinks, - p_peer->num_sup_sinks); + log::verbose("peer(o={}, n_sinks={}, n_rx_sinks={}, n_sup_sinks={})", p_peer->opened, + p_peer->num_sinks, p_peer->num_rx_sinks, p_peer->num_sup_sinks); p_peer->num_rx_sinks++; @@ -230,8 +219,7 @@ tA2DP_STATUS BtaAvCo::ProcessSourceGetConfig( // since the validation and selection will be performed by the // bluetooth audio HAL for offloaded codecs. auto codec_index = A2DP_SourceCodecIndex(p_codec_info); - bool is_offloaded_codec = - ::bluetooth::audio::a2dp::provider::supports_codec(codec_index); + bool is_offloaded_codec = ::bluetooth::audio::a2dp::provider::supports_codec(codec_index); // Check the peer's Sink codec if (is_offloaded_codec || A2DP_IsPeerSinkCodecValid(p_codec_info)) { @@ -239,9 +227,8 @@ tA2DP_STATUS BtaAvCo::ProcessSourceGetConfig( if (p_peer->num_sup_sinks < BTA_AV_CO_NUM_ELEMENTS(p_peer->sinks)) { BtaAvCoSep* p_sink = &p_peer->sinks[p_peer->num_sup_sinks++]; - log::verbose("saved caps[{:x}:{:x}:{:x}:{:x}:{:x}:{:x}]", p_codec_info[1], - p_codec_info[2], p_codec_info[3], p_codec_info[4], - p_codec_info[5], p_codec_info[6]); + log::verbose("saved caps[{:x}:{:x}:{:x}:{:x}:{:x}:{:x}]", p_codec_info[1], p_codec_info[2], + p_codec_info[3], p_codec_info[4], p_codec_info[5], p_codec_info[6]); memcpy(p_sink->codec_caps, p_codec_info, AVDT_CODEC_SIZE); p_sink->sep_info_idx = *p_sep_info_idx; @@ -271,8 +258,7 @@ tA2DP_STATUS BtaAvCo::ProcessSourceGetConfig( if (p_peer->p_sink == nullptr) { // Update the selected codec p_peer->p_sink = peer_cache_->FindPeerSink( - p_peer, A2DP_SourceCodecIndex(p_peer->codec_config), - ContentProtectFlag()); + p_peer, A2DP_SourceCodecIndex(p_peer->codec_config), ContentProtectFlag()); } p_sink = p_peer->p_sink; if (p_sink == nullptr) { @@ -282,14 +268,14 @@ tA2DP_STATUS BtaAvCo::ProcessSourceGetConfig( } else { if (btif_av_peer_prefers_mandatory_codec(p_peer->addr, A2dpType::kSource)) { // Apply user preferred codec directly before first codec selected. - p_sink = peer_cache_->FindPeerSink( - p_peer, BTAV_A2DP_CODEC_INDEX_SOURCE_SBC, ContentProtectFlag()); + p_sink = peer_cache_->FindPeerSink(p_peer, BTAV_A2DP_CODEC_INDEX_SOURCE_SBC, + ContentProtectFlag()); if (p_sink != nullptr) { log::verbose("mandatory codec preferred for peer {}", p_peer->addr); btav_a2dp_codec_config_t high_priority_mandatory{ - .codec_type = BTAV_A2DP_CODEC_INDEX_SOURCE_SBC, - .codec_priority = BTAV_A2DP_CODEC_PRIORITY_HIGHEST, - // Using default settings for those untouched fields + .codec_type = BTAV_A2DP_CODEC_INDEX_SOURCE_SBC, + .codec_priority = BTAV_A2DP_CODEC_PRIORITY_HIGHEST, + // Using default settings for those untouched fields }; uint8_t result_codec_config[AVDT_CODEC_SIZE]; bool restart_input = false; @@ -297,10 +283,9 @@ tA2DP_STATUS BtaAvCo::ProcessSourceGetConfig( bool config_updated = false; tA2DP_ENCODER_INIT_PEER_PARAMS peer_params; GetPeerEncoderParameters(p_peer->addr, &peer_params); - p_peer->GetCodecs()->setCodecUserConfig( - high_priority_mandatory, &peer_params, p_sink->codec_caps, - result_codec_config, &restart_input, &restart_output, - &config_updated); + p_peer->GetCodecs()->setCodecUserConfig(high_priority_mandatory, &peer_params, + p_sink->codec_caps, result_codec_config, + &restart_input, &restart_output, &config_updated); } else { log::warn("mandatory codec not found for peer {}", p_peer->addr); } @@ -321,54 +306,47 @@ tA2DP_STATUS BtaAvCo::ProcessSourceGetConfig( // If acceptor -> reconfig otherwise reply for configuration *p_sep_info_idx = p_sink->sep_info_idx; - log::verbose("peer {} acceptor:{} reconfig_needed:{}", p_peer->addr, - p_peer->acceptor, p_peer->reconfig_needed); + log::verbose("peer {} acceptor:{} reconfig_needed:{}", p_peer->addr, p_peer->acceptor, + p_peer->reconfig_needed); if (p_peer->acceptor) { if (p_peer->reconfig_needed) { - log::verbose("call BTA_AvReconfig(0x{:x}) for peer {}", bta_av_handle, - p_peer->addr); - BTA_AvReconfig(bta_av_handle, true, p_sink->sep_info_idx, - p_peer->codec_config, *p_num_protect, bta_av_co_cp_scmst); + log::verbose("call BTA_AvReconfig(0x{:x}) for peer {}", bta_av_handle, p_peer->addr); + BTA_AvReconfig(bta_av_handle, true, p_sink->sep_info_idx, p_peer->codec_config, + *p_num_protect, bta_av_co_cp_scmst); } } else { memcpy(p_codec_info, p_peer->codec_config, AVDT_CODEC_SIZE); } // report this peer selectable codecs after retrieved all its capabilities. - log::info("retrieved {} capabilities from peer {}", p_peer->num_rx_sinks, - p_peer->addr); + log::info("retrieved {} capabilities from peer {}", p_peer->num_rx_sinks, p_peer->addr); ReportSourceCodecState(p_peer); return A2DP_SUCCESS; } tA2DP_STATUS BtaAvCo::ProcessSinkGetConfig(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_address, - uint8_t* p_codec_info, - uint8_t* p_sep_info_idx, - uint8_t seid, uint8_t* p_num_protect, - uint8_t* p_protect_info) { + const RawAddress& peer_address, uint8_t* p_codec_info, + uint8_t* p_sep_info_idx, uint8_t seid, + uint8_t* p_num_protect, uint8_t* p_protect_info) { std::lock_guard lock(peer_cache_->codec_lock_); - log::verbose("peer {} bta_av_handle:0x{:x} codec:{} seid:{}", peer_address, - bta_av_handle, A2DP_CodecName(p_codec_info), seid); - log::verbose("num_protect:0x{:02x} protect_info:0x{:02x}{:02x}{:02x}", - *p_num_protect, p_protect_info[0], p_protect_info[1], - p_protect_info[2]); + log::verbose("peer {} bta_av_handle:0x{:x} codec:{} seid:{}", peer_address, bta_av_handle, + A2DP_CodecName(p_codec_info), seid); + log::verbose("num_protect:0x{:02x} protect_info:0x{:02x}{:02x}{:02x}", *p_num_protect, + p_protect_info[0], p_protect_info[1], p_protect_info[2]); log::verbose("codec: {}", A2DP_CodecInfoString(p_codec_info)); // Find the peer - BtaAvCoPeer* p_peer = - peer_cache_->FindPeerAndUpdate(bta_av_handle, peer_address); + BtaAvCoPeer* p_peer = peer_cache_->FindPeerAndUpdate(bta_av_handle, peer_address); if (p_peer == nullptr) { - log::error("could not find peer entry for bta_av_handle 0x{:x} peer {}", - bta_av_handle, peer_address); + log::error("could not find peer entry for bta_av_handle 0x{:x} peer {}", bta_av_handle, + peer_address); return A2DP_FAIL; } - log::verbose( - "peer {} found (o={}, n_sources={}, n_rx_sources={}, n_sup_sources={})", - p_peer->addr, p_peer->opened, p_peer->num_sources, p_peer->num_rx_sources, - p_peer->num_sup_sources); + log::verbose("peer {} found (o={}, n_sources={}, n_rx_sources={}, n_sup_sources={})", + p_peer->addr, p_peer->opened, p_peer->num_sources, p_peer->num_rx_sources, + p_peer->num_sup_sources); p_peer->num_rx_sources++; @@ -378,9 +356,8 @@ tA2DP_STATUS BtaAvCo::ProcessSinkGetConfig(tBTA_AV_HNDL bta_av_handle, if (p_peer->num_sup_sources < BTA_AV_CO_NUM_ELEMENTS(p_peer->sources)) { BtaAvCoSep* p_source = &p_peer->sources[p_peer->num_sup_sources++]; - log::verbose("saved caps[{:x}:{:x}:{:x}:{:x}:{:x}:{:x}]", p_codec_info[1], - p_codec_info[2], p_codec_info[3], p_codec_info[4], - p_codec_info[5], p_codec_info[6]); + log::verbose("saved caps[{:x}:{:x}:{:x}:{:x}:{:x}:{:x}]", p_codec_info[1], p_codec_info[2], + p_codec_info[3], p_codec_info[4], p_codec_info[5], p_codec_info[6]); memcpy(p_source->codec_caps, p_codec_info, AVDT_CODEC_SIZE); p_source->sep_info_idx = *p_sep_info_idx; @@ -407,8 +384,7 @@ tA2DP_STATUS BtaAvCo::ProcessSinkGetConfig(tBTA_AV_HNDL bta_av_handle, if (p_peer->p_source == nullptr) { // Update the selected codec p_peer->p_source = peer_cache_->FindPeerSource( - p_peer, A2DP_SinkCodecIndex(p_peer->codec_config), - ContentProtectFlag()); + p_peer, A2DP_SinkCodecIndex(p_peer->codec_config), ContentProtectFlag()); } p_source = p_peer->p_source; if (p_source == nullptr) { @@ -432,14 +408,13 @@ tA2DP_STATUS BtaAvCo::ProcessSinkGetConfig(tBTA_AV_HNDL bta_av_handle, // If acceptor -> reconfig otherwise reply for configuration *p_sep_info_idx = p_source->sep_info_idx; - log::verbose("peer {} acceptor:{} reconfig_needed:{}", p_peer->addr, - p_peer->acceptor, p_peer->reconfig_needed); + log::verbose("peer {} acceptor:{} reconfig_needed:{}", p_peer->addr, p_peer->acceptor, + p_peer->reconfig_needed); if (p_peer->acceptor) { if (p_peer->reconfig_needed) { - log::verbose("call BTA_AvReconfig(0x{:x}) for peer {}", bta_av_handle, - p_peer->addr); - BTA_AvReconfig(bta_av_handle, true, p_source->sep_info_idx, - p_peer->codec_config, *p_num_protect, bta_av_co_cp_scmst); + log::verbose("call BTA_AvReconfig(0x{:x}) for peer {}", bta_av_handle, p_peer->addr); + BTA_AvReconfig(bta_av_handle, true, p_source->sep_info_idx, p_peer->codec_config, + *p_num_protect, bta_av_co_cp_scmst); } } else { memcpy(p_codec_info, p_peer->codec_config, AVDT_CODEC_SIZE); @@ -448,44 +423,36 @@ tA2DP_STATUS BtaAvCo::ProcessSinkGetConfig(tBTA_AV_HNDL bta_av_handle, return A2DP_SUCCESS; } -void BtaAvCo::ProcessSetConfig(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_address, - const uint8_t* p_codec_info, uint8_t seid, - uint8_t num_protect, - const uint8_t* p_protect_info, - uint8_t t_local_sep, uint8_t avdt_handle) { +void BtaAvCo::ProcessSetConfig(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, + const uint8_t* p_codec_info, uint8_t seid, uint8_t num_protect, + const uint8_t* p_protect_info, uint8_t t_local_sep, + uint8_t avdt_handle) { tA2DP_STATUS status = A2DP_SUCCESS; uint8_t category = A2DP_SUCCESS; bool reconfig_needed = false; log::verbose( - "bta_av_handle=0x{:x} peer_address={} seid={} num_protect={} " - "t_local_sep={} avdt_handle={}", - bta_av_handle, peer_address, seid, num_protect, t_local_sep, avdt_handle); - log::verbose("p_codec_info[{:x}:{:x}:{:x}:{:x}:{:x}:{:x}]", p_codec_info[1], - p_codec_info[2], p_codec_info[3], p_codec_info[4], - p_codec_info[5], p_codec_info[6]); - log::verbose("num_protect:0x{:02x} protect_info:0x{:02x}{:02x}{:02x}", - num_protect, p_protect_info[0], p_protect_info[1], - p_protect_info[2]); + "bta_av_handle=0x{:x} peer_address={} seid={} num_protect={} " + "t_local_sep={} avdt_handle={}", + bta_av_handle, peer_address, seid, num_protect, t_local_sep, avdt_handle); + log::verbose("p_codec_info[{:x}:{:x}:{:x}:{:x}:{:x}:{:x}]", p_codec_info[1], p_codec_info[2], + p_codec_info[3], p_codec_info[4], p_codec_info[5], p_codec_info[6]); + log::verbose("num_protect:0x{:02x} protect_info:0x{:02x}{:02x}{:02x}", num_protect, + p_protect_info[0], p_protect_info[1], p_protect_info[2]); log::verbose("codec: {}", A2DP_CodecInfoString(p_codec_info)); // Find the peer - BtaAvCoPeer* p_peer = - peer_cache_->FindPeerAndUpdate(bta_av_handle, peer_address); + BtaAvCoPeer* p_peer = peer_cache_->FindPeerAndUpdate(bta_av_handle, peer_address); if (p_peer == nullptr) { - log::error("could not find peer entry for bta_av_handle 0x{:x} peer {}", - bta_av_handle, peer_address); + log::error("could not find peer entry for bta_av_handle 0x{:x} peer {}", bta_av_handle, + peer_address); // Call call-in rejecting the configuration - bta_av_ci_setconfig(bta_av_handle, A2DP_BUSY, AVDT_ASC_CODEC, 0, nullptr, - false, avdt_handle); + bta_av_ci_setconfig(bta_av_handle, A2DP_BUSY, AVDT_ASC_CODEC, 0, nullptr, false, avdt_handle); return; } - log::verbose( - "peer {} found (o={}, n_sinks={}, n_rx_sinks={}, n_sup_sinks={})", - p_peer->addr, p_peer->opened, p_peer->num_sinks, p_peer->num_rx_sinks, - p_peer->num_sup_sinks); + log::verbose("peer {} found (o={}, n_sinks={}, n_rx_sinks={}, n_sup_sinks={})", p_peer->addr, + p_peer->opened, p_peer->num_sinks, p_peer->num_rx_sinks, p_peer->num_sup_sinks); // Sanity check: should not be opened at this point if (p_peer->opened) { @@ -516,8 +483,7 @@ void BtaAvCo::ProcessSetConfig(tBTA_AV_HNDL bta_av_handle, if (codec_config_supported) { // If Peer is Source, and our config subset matches with what is // requested by peer, then just accept what peer wants. - SaveNewCodecConfig(p_peer, p_codec_info, num_protect, p_protect_info, - t_local_sep); + SaveNewCodecConfig(p_peer, p_codec_info, num_protect, p_protect_info, t_local_sep); } } if (t_local_sep == AVDT_TSEP_SRC) { @@ -528,12 +494,12 @@ void BtaAvCo::ProcessSetConfig(tBTA_AV_HNDL bta_av_handle, if ((p_peer->GetCodecs() == nullptr) || !SetCodecOtaConfig(p_peer, p_codec_info, num_protect, p_protect_info, &dummy_restart_output, t_local_sep)) { - log::error("cannot set source codec {} for peer {}", - A2DP_CodecName(p_codec_info), p_peer->addr); + log::error("cannot set source codec {} for peer {}", A2DP_CodecName(p_codec_info), + p_peer->addr); } else { codec_config_supported = true; // Check if reconfiguration is needed - if (((num_protect == 1) && !p_peer->ContentProtectActive())) { + if ((num_protect == 1) && !p_peer->ContentProtectActive()) { reconfig_needed = true; } } @@ -549,8 +515,7 @@ void BtaAvCo::ProcessSetConfig(tBTA_AV_HNDL bta_av_handle, if (status != A2DP_SUCCESS) { log::verbose("peer {} reject s={} c={}", p_peer->addr, status, category); // Call call-in rejecting the configuration - bta_av_ci_setconfig(bta_av_handle, status, category, 0, nullptr, false, - avdt_handle); + bta_av_ci_setconfig(bta_av_handle, status, category, 0, nullptr, false, avdt_handle); return; } @@ -559,21 +524,19 @@ void BtaAvCo::ProcessSetConfig(tBTA_AV_HNDL bta_av_handle, p_peer->reconfig_needed = reconfig_needed; log::verbose("peer {} accept reconf={}", p_peer->addr, reconfig_needed); // Call call-in accepting the configuration - bta_av_ci_setconfig(bta_av_handle, A2DP_SUCCESS, A2DP_SUCCESS, 0, nullptr, - reconfig_needed, avdt_handle); + bta_av_ci_setconfig(bta_av_handle, A2DP_SUCCESS, A2DP_SUCCESS, 0, nullptr, reconfig_needed, + avdt_handle); } -void BtaAvCo::ProcessOpen(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_address, uint16_t mtu) { - log::verbose("peer {} bta_av_handle: 0x{:x} mtu:{}", peer_address, - bta_av_handle, mtu); +void BtaAvCo::ProcessOpen(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, + uint16_t mtu) { + log::verbose("peer {} bta_av_handle: 0x{:x} mtu:{}", peer_address, bta_av_handle, mtu); // Find the peer - BtaAvCoPeer* p_peer = - peer_cache_->FindPeerAndUpdate(bta_av_handle, peer_address); + BtaAvCoPeer* p_peer = peer_cache_->FindPeerAndUpdate(bta_av_handle, peer_address); if (p_peer == nullptr) { - log::error("could not find peer entry for bta_av_handle 0x{:x} peer {}", - bta_av_handle, peer_address); + log::error("could not find peer entry for bta_av_handle 0x{:x} peer {}", bta_av_handle, + peer_address); return; } p_peer->opened = true; @@ -590,16 +553,14 @@ void BtaAvCo::ProcessOpen(tBTA_AV_HNDL bta_av_handle, } } -void BtaAvCo::ProcessClose(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_address) { +void BtaAvCo::ProcessClose(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address) { log::verbose("peer {} bta_av_handle: 0x{:x}", peer_address, bta_av_handle); // Find the peer - BtaAvCoPeer* p_peer = - peer_cache_->FindPeerAndUpdate(bta_av_handle, peer_address); + BtaAvCoPeer* p_peer = peer_cache_->FindPeerAndUpdate(bta_av_handle, peer_address); if (p_peer == nullptr) { - log::error("could not find peer entry for bta_av_handle 0x{:x} peer {}", - bta_av_handle, peer_address); + log::error("could not find peer entry for bta_av_handle 0x{:x} peer {}", bta_av_handle, + peer_address); return; } // Reset the active peer @@ -618,42 +579,38 @@ void BtaAvCo::ProcessClose(tBTA_AV_HNDL bta_av_handle, p_peer->Init(peer_cache_->codec_priorities_); } -void BtaAvCo::ProcessStart(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_address, +void BtaAvCo::ProcessStart(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, const uint8_t* p_codec_info, bool* p_no_rtp_header) { log::verbose("peer {} bta_av_handle: 0x{:x}", peer_address, bta_av_handle); // Find the peer - BtaAvCoPeer* p_peer = - peer_cache_->FindPeerAndUpdate(bta_av_handle, peer_address); + BtaAvCoPeer* p_peer = peer_cache_->FindPeerAndUpdate(bta_av_handle, peer_address); if (p_peer == nullptr) { - log::error("could not find peer entry for bta_av_handle 0x{:x} peer {}", - bta_av_handle, peer_address); + log::error("could not find peer entry for bta_av_handle 0x{:x} peer {}", bta_av_handle, + peer_address); return; } - bool add_rtp_header = - A2DP_UsesRtpHeader(p_peer->ContentProtectActive(), p_codec_info); + bool add_rtp_header = A2DP_UsesRtpHeader(p_peer->ContentProtectActive(), p_codec_info); - log::verbose("bta_av_handle: 0x{:x} add_rtp_header: {}", bta_av_handle, - add_rtp_header); + log::verbose("bta_av_handle: 0x{:x} add_rtp_header: {}", bta_av_handle, add_rtp_header); *p_no_rtp_header = !add_rtp_header; } -void BtaAvCo::ProcessStop(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_address) { +void BtaAvCo::ProcessStop(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address) { log::verbose("peer {} bta_av_handle: 0x{:x}", peer_address, bta_av_handle); // Nothing to do } -BT_HDR* BtaAvCo::GetNextSourceDataPacket(const uint8_t* p_codec_info, - uint32_t* p_timestamp) { +BT_HDR* BtaAvCo::GetNextSourceDataPacket(const uint8_t* p_codec_info, uint32_t* p_timestamp) { BT_HDR* p_buf; log::verbose("codec: {}", A2DP_CodecName(p_codec_info)); p_buf = btif_a2dp_source_audio_readbuf(); - if (p_buf == nullptr) return nullptr; + if (p_buf == nullptr) { + return nullptr; + } if (p_buf->offset < 4) { osi_free(p_buf); @@ -668,8 +625,7 @@ BT_HDR* BtaAvCo::GetNextSourceDataPacket(const uint8_t* p_codec_info, * p_buf->layer_specific : number of audio frames in the packet * p_buf->word[0] : timestamp */ - if (!A2DP_GetPacketTimestamp(p_codec_info, (const uint8_t*)(p_buf + 1), - p_timestamp) || + if (!A2DP_GetPacketTimestamp(p_codec_info, (const uint8_t*)(p_buf + 1), p_timestamp) || !A2DP_BuildCodecHeader(p_codec_info, p_buf, p_buf->layer_specific)) { log::error("unsupported codec type ({})", A2DP_GetCodecType(p_codec_info)); osi_free(p_buf); @@ -685,8 +641,8 @@ BT_HDR* BtaAvCo::GetNextSourceDataPacket(const uint8_t* p_codec_info, BtaAvCoPeer* active_peer = reference_state->getActivePeer(); // if offset is 0, the decremental operation may result in // underflow and OOB access - if (ContentProtectEnabled() && (active_peer != nullptr) && - active_peer->ContentProtectActive() && p_buf->offset > 0) { + if (ContentProtectEnabled() && (active_peer != nullptr) && active_peer->ContentProtectActive() && + p_buf->offset > 0) { p_buf->len++; p_buf->offset--; uint8_t* p = (uint8_t*)(p_buf + 1) + p_buf->offset; @@ -696,48 +652,39 @@ BT_HDR* BtaAvCo::GetNextSourceDataPacket(const uint8_t* p_codec_info, return p_buf; } -void BtaAvCo::DataPacketWasDropped(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_address) { - log::error("peer {} dropped audio packet on handle 0x{:x}", peer_address, - bta_av_handle); +void BtaAvCo::DataPacketWasDropped(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address) { + log::error("peer {} dropped audio packet on handle 0x{:x}", peer_address, bta_av_handle); } -void BtaAvCo::ProcessAudioDelay(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_address, +void BtaAvCo::ProcessAudioDelay(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, uint16_t delay) { - log::verbose("peer {} bta_av_handle: 0x{:x} delay:0x{:x}", peer_address, - bta_av_handle, delay); + log::verbose("peer {} bta_av_handle: 0x{:x} delay:0x{:x}", peer_address, bta_av_handle, delay); btif_av_set_audio_delay(peer_address, delay, A2dpType::kSource); } -void BtaAvCo::UpdateMtu(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_address, uint16_t mtu) { - log::info("peer {} bta_av_handle: 0x{:x} mtu: {}", peer_address, - bta_av_handle, mtu); +void BtaAvCo::UpdateMtu(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, uint16_t mtu) { + log::info("peer {} bta_av_handle: 0x{:x} mtu: {}", peer_address, bta_av_handle, mtu); // Find the peer - BtaAvCoPeer* p_peer = - peer_cache_->FindPeerAndUpdate(bta_av_handle, peer_address); + BtaAvCoPeer* p_peer = peer_cache_->FindPeerAndUpdate(bta_av_handle, peer_address); if (p_peer == nullptr) { - log::error("could not find peer entry for bta_av_handle 0x{:x} peer {}", - bta_av_handle, peer_address); + log::error("could not find peer entry for bta_av_handle 0x{:x} peer {}", bta_av_handle, + peer_address); return; } p_peer->mtu = mtu; } -bool BtaAvCo::SetActivePeer(const RawAddress& peer_address, - const uint8_t t_local_sep) { +bool BtaAvCo::SetActivePeer(const RawAddress& peer_address, const uint8_t t_local_sep) { log::info("peer_address={}", peer_address); std::lock_guard lock(peer_cache_->codec_lock_); BtaAvCoState* reference_state = getStateFromLocalProfile(t_local_sep); if (reference_state == nullptr) { - log::warn( - "Invalid bta av state for peer_address : {} with local sep as :{}", - peer_address, t_local_sep); + log::warn("Invalid bta av state for peer_address : {} with local sep as :{}", peer_address, + t_local_sep); return false; } if (peer_address.IsEmpty()) { @@ -755,8 +702,7 @@ bool BtaAvCo::SetActivePeer(const RawAddress& peer_address, reference_state->setActivePeer(p_peer); reference_state->setCodecConfig(p_peer->codec_config); - log::info("codec = {}", - A2DP_CodecInfoString(reference_state->getCodecConfig())); + log::info("codec = {}", A2DP_CodecInfoString(reference_state->getCodecConfig())); // report the selected codec configuration of this new active peer. ReportSourceCodecState(p_peer); return true; @@ -785,9 +731,8 @@ void BtaAvCo::SaveCodec(const uint8_t* new_codec_config) { } } -void BtaAvCo::GetPeerEncoderParameters( - const RawAddress& peer_address, - tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params) { +void BtaAvCo::GetPeerEncoderParameters(const RawAddress& peer_address, + tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params) { uint16_t min_mtu = 0xFFFF; log::assert_that(p_peer_params != nullptr, "Peer address {}", ADDRESS_TO_LOGGABLE_STR(peer_address)); @@ -797,19 +742,22 @@ void BtaAvCo::GetPeerEncoderParameters( // Compute the MTU for (size_t i = 0; i < BTA_AV_CO_NUM_ELEMENTS(peer_cache_->peers_); i++) { const BtaAvCoPeer* p_peer = &peer_cache_->peers_[i]; - if (!p_peer->opened) continue; - if (p_peer->addr != peer_address) continue; - if (p_peer->mtu < min_mtu) min_mtu = p_peer->mtu; + if (!p_peer->opened) { + continue; + } + if (p_peer->addr != peer_address) { + continue; + } + if (p_peer->mtu < min_mtu) { + min_mtu = p_peer->mtu; + } } p_peer_params->peer_mtu = min_mtu; - p_peer_params->is_peer_edr = - btif_av_is_peer_edr(peer_address, A2dpType::kSource); - p_peer_params->peer_supports_3mbps = - btif_av_peer_supports_3mbps(peer_address, A2dpType::kSource); - log::verbose( - "peer_address={} peer_mtu={} is_peer_edr={} peer_supports_3mbps={}", - peer_address, p_peer_params->peer_mtu, p_peer_params->is_peer_edr, - p_peer_params->peer_supports_3mbps); + p_peer_params->is_peer_edr = btif_av_is_peer_edr(peer_address, A2dpType::kSource); + p_peer_params->peer_supports_3mbps = btif_av_peer_supports_3mbps(peer_address, A2dpType::kSource); + log::verbose("peer_address={} peer_mtu={} is_peer_edr={} peer_supports_3mbps={}", peer_address, + p_peer_params->peer_mtu, p_peer_params->is_peer_edr, + p_peer_params->peer_supports_3mbps); } const tA2DP_ENCODER_INTERFACE* BtaAvCo::GetSourceEncoderInterface() { @@ -820,9 +768,9 @@ const tA2DP_ENCODER_INTERFACE* BtaAvCo::GetSourceEncoderInterface() { return A2DP_GetEncoderInterface(bta_av_legacy_state_.getCodecConfig()); } -bool BtaAvCo::SetCodecUserConfig( - const RawAddress& peer_address, - const btav_a2dp_codec_config_t& codec_user_config, bool* p_restart_output) { +bool BtaAvCo::SetCodecUserConfig(const RawAddress& peer_address, + const btav_a2dp_codec_config_t& codec_user_config, + bool* p_restart_output) { uint8_t result_codec_config[AVDT_CODEC_SIZE]; const BtaAvCoSep* p_sink = nullptr; bool restart_input = false; @@ -845,33 +793,30 @@ bool BtaAvCo::SetCodecUserConfig( // Don't call BTA_AvReconfig() prior to retrieving all peer's capabilities if ((p_peer->num_rx_sinks != p_peer->num_sinks) && (p_peer->num_sup_sinks != BTA_AV_CO_NUM_ELEMENTS(p_peer->sinks))) { - log::warn("peer {} : not all peer's capabilities have been retrieved", - p_peer->addr); + log::warn("peer {} : not all peer's capabilities have been retrieved", p_peer->addr); success = false; goto done; } // Find the peer SEP codec to use if (codec_user_config.codec_type < BTAV_A2DP_CODEC_INDEX_MAX) { - p_sink = peer_cache_->FindPeerSink(p_peer, codec_user_config.codec_type, - ContentProtectFlag()); + p_sink = peer_cache_->FindPeerSink(p_peer, codec_user_config.codec_type, ContentProtectFlag()); } else { // Use the current sink codec p_sink = p_peer->p_sink; } if (p_sink == nullptr) { - log::error("peer {} : cannot find peer SEP to configure for codec type {}", - p_peer->addr, codec_user_config.codec_type); + log::error("peer {} : cannot find peer SEP to configure for codec type {}", p_peer->addr, + codec_user_config.codec_type); success = false; goto done; } tA2DP_ENCODER_INIT_PEER_PARAMS peer_params; GetPeerEncoderParameters(p_peer->addr, &peer_params); - if (!p_peer->GetCodecs()->setCodecUserConfig( - codec_user_config, &peer_params, p_sink->codec_caps, - result_codec_config, &restart_input, &restart_output, - &config_updated)) { + if (!p_peer->GetCodecs()->setCodecUserConfig(codec_user_config, &peer_params, p_sink->codec_caps, + result_codec_config, &restart_input, &restart_output, + &config_updated)) { success = false; goto done; } @@ -884,16 +829,15 @@ bool BtaAvCo::SetCodecUserConfig( p_sink = SelectSourceCodec(p_peer); if (p_sink == nullptr) { - log::error("peer {} : cannot set up codec for the peer SINK", - p_peer->addr); + log::error("peer {} : cannot set up codec for the peer SINK", p_peer->addr); success = false; goto done; } p_peer->acceptor = false; log::verbose("call BTA_AvReconfig(0x{:x})", p_peer->BtaAvHandle()); - BTA_AvReconfig(p_peer->BtaAvHandle(), true, p_sink->sep_info_idx, - p_peer->codec_config, num_protect, bta_av_co_cp_scmst); + BTA_AvReconfig(p_peer->BtaAvHandle(), true, p_sink->sep_info_idx, p_peer->codec_config, + num_protect, bta_av_co_cp_scmst); *p_restart_output = true; } @@ -914,16 +858,14 @@ done: } else { active_peer = bta_av_legacy_state_.getActivePeer(); } - if (p_peer != nullptr && - (!restart_output || !success || p_peer != active_peer)) { + if (p_peer != nullptr && (!restart_output || !success || p_peer != active_peer)) { return ReportSourceCodecState(p_peer); } return success; } -bool BtaAvCo::SetCodecAudioConfig( - const btav_a2dp_codec_config_t& codec_audio_config) { +bool BtaAvCo::SetCodecAudioConfig(const btav_a2dp_codec_config_t& codec_audio_config) { uint8_t result_codec_config[AVDT_CODEC_SIZE]; bool restart_output = false; bool config_updated = false; @@ -945,8 +887,7 @@ bool BtaAvCo::SetCodecAudioConfig( // Don't call BTA_AvReconfig() prior to retrieving all peer's capabilities if ((p_peer->num_rx_sinks != p_peer->num_sinks) && (p_peer->num_sup_sinks != BTA_AV_CO_NUM_ELEMENTS(p_peer->sinks))) { - log::warn("peer {} : not all peer's capabilities have been retrieved", - p_peer->addr); + log::warn("peer {} : not all peer's capabilities have been retrieved", p_peer->addr); return false; } @@ -959,9 +900,9 @@ bool BtaAvCo::SetCodecAudioConfig( tA2DP_ENCODER_INIT_PEER_PARAMS peer_params; GetPeerEncoderParameters(p_peer->addr, &peer_params); - if (!p_peer->GetCodecs()->setCodecAudioConfig( - codec_audio_config, &peer_params, p_sink->codec_caps, - result_codec_config, &restart_output, &config_updated)) { + if (!p_peer->GetCodecs()->setCodecAudioConfig(codec_audio_config, &peer_params, + p_sink->codec_caps, result_codec_config, + &restart_output, &config_updated)) { return false; } @@ -971,13 +912,13 @@ bool BtaAvCo::SetCodecAudioConfig( num_protect = AVDT_CP_INFO_LEN; } - SaveNewCodecConfig(p_peer, result_codec_config, p_sink->num_protect, - p_sink->protect_info, AVDT_TSEP_SRC); + SaveNewCodecConfig(p_peer, result_codec_config, p_sink->num_protect, p_sink->protect_info, + AVDT_TSEP_SRC); p_peer->acceptor = false; log::verbose("call BTA_AvReconfig(0x{:x})", p_peer->BtaAvHandle()); - BTA_AvReconfig(p_peer->BtaAvHandle(), true, p_sink->sep_info_idx, - p_peer->codec_config, num_protect, bta_av_co_cp_scmst); + BTA_AvReconfig(p_peer->BtaAvHandle(), true, p_sink->sep_info_idx, p_peer->codec_config, + num_protect, bta_av_co_cp_scmst); } if (config_updated) { @@ -993,11 +934,9 @@ int BtaAvCo::GetSourceEncoderEffectiveFrameSize() { std::lock_guard lock(peer_cache_->codec_lock_); if (com::android::bluetooth::flags::a2dp_concurrent_source_sink()) { - return A2DP_GetEecoderEffectiveFrameSize( - bta_av_source_state_.getCodecConfig()); + return A2DP_GetEecoderEffectiveFrameSize(bta_av_source_state_.getCodecConfig()); } - return A2DP_GetEecoderEffectiveFrameSize( - bta_av_legacy_state_.getCodecConfig()); + return A2DP_GetEecoderEffectiveFrameSize(bta_av_legacy_state_.getCodecConfig()); } int BtaAvCo::GetSourceEncoderPreferredIntervalUs() { @@ -1007,15 +946,15 @@ int BtaAvCo::GetSourceEncoderPreferredIntervalUs() { bool BtaAvCo::ReportSourceCodecState(BtaAvCoPeer* p_peer) { btav_a2dp_codec_config_t codec_config = { - .codec_type = BTAV_A2DP_CODEC_INDEX_SINK_MAX, - .codec_priority = BTAV_A2DP_CODEC_PRIORITY_DISABLED, - .sample_rate = BTAV_A2DP_CODEC_SAMPLE_RATE_NONE, - .bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE, - .channel_mode = BTAV_A2DP_CODEC_CHANNEL_MODE_NONE, - .codec_specific_1 = 0, - .codec_specific_2 = 0, - .codec_specific_3 = 0, - .codec_specific_4 = 0, + .codec_type = BTAV_A2DP_CODEC_INDEX_SINK_MAX, + .codec_priority = BTAV_A2DP_CODEC_PRIORITY_DISABLED, + .sample_rate = BTAV_A2DP_CODEC_SAMPLE_RATE_NONE, + .bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE, + .channel_mode = BTAV_A2DP_CODEC_CHANNEL_MODE_NONE, + .codec_specific_1 = 0, + .codec_specific_2 = 0, + .codec_specific_3 = 0, + .codec_specific_4 = 0, }; std::vector codecs_local_capabilities; std::vector codecs_selectable_capabilities; @@ -1026,18 +965,16 @@ bool BtaAvCo::ReportSourceCodecState(BtaAvCoPeer* p_peer) { log::error("Peer codecs is set to null"); return false; } - if (!codecs->getCodecConfigAndCapabilities(&codec_config, - &codecs_local_capabilities, + if (!codecs->getCodecConfigAndCapabilities(&codec_config, &codecs_local_capabilities, &codecs_selectable_capabilities)) { log::warn( - "Peer {} : error reporting audio source codec state: cannot get codec " - "config and capabilities", - p_peer->addr); + "Peer {} : error reporting audio source codec state: cannot get codec " + "config and capabilities", + p_peer->addr); return false; } log::info("peer {} codec_config={{}}", p_peer->addr, codec_config.ToString()); - btif_av_report_source_codec_state(p_peer->addr, codec_config, - codecs_local_capabilities, + btif_av_report_source_codec_state(p_peer->addr, codec_config, codecs_local_capabilities, codecs_selectable_capabilities); return true; } @@ -1074,21 +1011,18 @@ void BtaAvCo::DebugDump(int fd) { } dprintf(fd, "\nA2DP Peers State:\n"); - dprintf( - fd, " Active peer: %s\n", - (bta_av_legacy_state_.getActivePeer() != nullptr) - ? ADDRESS_TO_LOGGABLE_CSTR(bta_av_legacy_state_.getActivePeer()->addr) - : "null"); - dprintf( - fd, " Source: active peer: %s\n", - (bta_av_source_state_.getActivePeer() != nullptr) - ? ADDRESS_TO_LOGGABLE_CSTR(bta_av_source_state_.getActivePeer()->addr) - : "null"); - dprintf( - fd, " Sink: active peer: %s\n", - (bta_av_sink_state_.getActivePeer() != nullptr) - ? ADDRESS_TO_LOGGABLE_CSTR(bta_av_sink_state_.getActivePeer()->addr) - : "null"); + dprintf(fd, " Active peer: %s\n", + (bta_av_legacy_state_.getActivePeer() != nullptr) + ? ADDRESS_TO_LOGGABLE_CSTR(bta_av_legacy_state_.getActivePeer()->addr) + : "null"); + dprintf(fd, " Source: active peer: %s\n", + (bta_av_source_state_.getActivePeer() != nullptr) + ? ADDRESS_TO_LOGGABLE_CSTR(bta_av_source_state_.getActivePeer()->addr) + : "null"); + dprintf(fd, " Sink: active peer: %s\n", + (bta_av_sink_state_.getActivePeer() != nullptr) + ? ADDRESS_TO_LOGGABLE_CSTR(bta_av_sink_state_.getActivePeer()->addr) + : "null"); for (size_t i = 0; i < BTA_AV_CO_NUM_ELEMENTS(peer_cache_->peers_); i++) { const BtaAvCoPeer& peer = peer_cache_->peers_[i]; @@ -1104,8 +1038,7 @@ void BtaAvCo::DebugDump(int fd) { dprintf(fd, " Number of supported sinks: %u\n", peer.num_sup_sinks); dprintf(fd, " Number of supported sources: %u\n", peer.num_sup_sources); dprintf(fd, " Acceptor: %s\n", (peer.acceptor) ? "true" : "false"); - dprintf(fd, " Reconfig needed: %s\n", - (peer.reconfig_needed) ? "true" : "false"); + dprintf(fd, " Reconfig needed: %s\n", (peer.reconfig_needed) ? "true" : "false"); dprintf(fd, " Opened: %s\n", (peer.opened) ? "true" : "false"); dprintf(fd, " MTU: %u\n", peer.mtu); dprintf(fd, " UUID to connect: 0x%x\n", peer.uuid_to_connect); @@ -1116,8 +1049,7 @@ void BtaAvCo::DebugDump(int fd) { std::optional<::bluetooth::audio::a2dp::provider::a2dp_configuration> BtaAvCo::GetProviderCodecConfiguration(BtaAvCoPeer* p_peer) { // Gather peer codec capabilities. - std::vector<::bluetooth::audio::a2dp::provider::a2dp_remote_capabilities> - a2dp_remote_caps; + std::vector<::bluetooth::audio::a2dp::provider::a2dp_remote_capabilities> a2dp_remote_caps; for (size_t index = 0; index < p_peer->num_sup_sinks; index++) { const BtaAvCoSep* p_sink = &p_peer->sinks[index]; auto& capabilities = a2dp_remote_caps.emplace_back(); @@ -1127,17 +1059,16 @@ BtaAvCo::GetProviderCodecConfiguration(BtaAvCoPeer* p_peer) { // Get the configuration of the preferred codec as codec hint. btav_a2dp_codec_config_t codec_config = - p_peer->GetCodecs()->orderedSourceCodecs().front()->getCodecUserConfig(); + p_peer->GetCodecs()->orderedSourceCodecs().front()->getCodecUserConfig(); // Pass all gathered codec capabilities to the provider - return ::bluetooth::audio::a2dp::provider::get_a2dp_configuration( - p_peer->addr, a2dp_remote_caps, codec_config); + return ::bluetooth::audio::a2dp::provider::get_a2dp_configuration(p_peer->addr, a2dp_remote_caps, + codec_config); } BtaAvCoSep* BtaAvCo::SelectProviderCodecConfiguration( - BtaAvCoPeer* p_peer, - const ::bluetooth::audio::a2dp::provider::a2dp_configuration& - provider_codec_config) { + BtaAvCoPeer* p_peer, + const ::bluetooth::audio::a2dp::provider::a2dp_configuration& provider_codec_config) { // Configure the selected offload codec for the active peer. // This function _must_ have the same external behaviour as // AttemptSourceCodecSelection, except the configuration @@ -1147,29 +1078,25 @@ BtaAvCoSep* BtaAvCo::SelectProviderCodecConfiguration( // Identify the selected sink. auto* p_sink = peer_cache_->FindPeerSink( - p_peer, provider_codec_config.codec_parameters.codec_type, - ContentProtectFlag()); - log::assert_that(p_sink != nullptr, - "Unable to find the selected codec config"); + p_peer, provider_codec_config.codec_parameters.codec_type, ContentProtectFlag()); + log::assert_that(p_sink != nullptr, "Unable to find the selected codec config"); // Identify the selected codec. - auto* codec_config = reinterpret_cast( - p_peer->GetCodecs()->findSourceCodecConfig( - provider_codec_config.codec_parameters.codec_type)); - log::assert_that(codec_config != nullptr, - "Unable to find the selected codec config"); + auto* codec_config = + reinterpret_cast(p_peer->GetCodecs()->findSourceCodecConfig( + provider_codec_config.codec_parameters.codec_type)); + log::assert_that(codec_config != nullptr, "Unable to find the selected codec config"); // Update the vendor codec parameters and codec configuration. - codec_config->setCodecConfig( - provider_codec_config.codec_parameters, - provider_codec_config.codec_config, - provider_codec_config.vendor_specific_parameters); + codec_config->setCodecConfig(provider_codec_config.codec_parameters, + provider_codec_config.codec_config, + provider_codec_config.vendor_specific_parameters); // Select the codec config. p_peer->GetCodecs()->setCurrentCodecConfig(codec_config); p_peer->p_sink = p_sink; - SaveNewCodecConfig(p_peer, provider_codec_config.codec_config, - p_sink->num_protect, p_sink->protect_info, AVDT_TSEP_SRC); + SaveNewCodecConfig(p_peer, provider_codec_config.codec_config, p_sink->num_protect, + p_sink->protect_info, AVDT_TSEP_SRC); return p_sink; } @@ -1186,24 +1113,22 @@ const BtaAvCoSep* BtaAvCo::SelectSourceCodec(BtaAvCoPeer* p_peer) { // Query the preferred codec configuration for software codecs. A2dpCodecConfig* software_codec_config = nullptr; for (const auto& iter : p_peer->GetCodecs()->orderedSourceCodecs()) { - if (::bluetooth::audio::a2dp::provider::supports_codec( - iter->codecIndex())) { + if (::bluetooth::audio::a2dp::provider::supports_codec(iter->codecIndex())) { continue; } // Find the peer Sink for the codec uint8_t new_codec_config[AVDT_CODEC_SIZE]; - const BtaAvCoSep* p_sink = peer_cache_->FindPeerSink( - p_peer, iter->codecIndex(), ContentProtectFlag()); + const BtaAvCoSep* p_sink = + peer_cache_->FindPeerSink(p_peer, iter->codecIndex(), ContentProtectFlag()); if (p_sink == nullptr) { log::verbose("peer Sink for codec {} not found", iter->name()); continue; } - if (!p_peer->GetCodecs()->setCodecConfig( - p_sink->codec_caps, true /* is_capability */, new_codec_config, - false /* select_current_codec */)) { + if (!p_peer->GetCodecs()->setCodecConfig(p_sink->codec_caps, true /* is_capability */, + new_codec_config, false /* select_current_codec */)) { log::verbose("cannot set source codec {}", iter->name()); } else { log::verbose("feasible to set source codec {}", iter->name()); @@ -1217,8 +1142,7 @@ const BtaAvCoSep* BtaAvCo::SelectSourceCodec(BtaAvCoPeer* p_peer) { bta_av_co_should_select_hardware_codec(*software_codec_config, provider_codec_config.value()))) { // Select hardware offload codec configuration - return SelectProviderCodecConfiguration(p_peer, - provider_codec_config.value()); + return SelectProviderCodecConfiguration(p_peer, provider_codec_config.value()); } if (software_codec_config != nullptr) { @@ -1255,56 +1179,54 @@ const BtaAvCoSep* BtaAvCo::SelectSinkCodec(BtaAvCoPeer* p_peer) { return p_source; } -const BtaAvCoSep* BtaAvCo::AttemptSourceCodecSelection( - const A2dpCodecConfig& codec_config, BtaAvCoPeer* p_peer) { +const BtaAvCoSep* BtaAvCo::AttemptSourceCodecSelection(const A2dpCodecConfig& codec_config, + BtaAvCoPeer* p_peer) { uint8_t new_codec_config[AVDT_CODEC_SIZE]; log::verbose(""); // Find the peer Sink for the codec - BtaAvCoSep* p_sink = peer_cache_->FindPeerSink( - p_peer, codec_config.codecIndex(), ContentProtectFlag()); + BtaAvCoSep* p_sink = + peer_cache_->FindPeerSink(p_peer, codec_config.codecIndex(), ContentProtectFlag()); if (p_sink == nullptr) { log::verbose("peer Sink for codec {} not found", codec_config.name()); return nullptr; } - if (!p_peer->GetCodecs()->setCodecConfig( - p_sink->codec_caps, true /* is_capability */, new_codec_config, - true /* select_current_codec */)) { + if (!p_peer->GetCodecs()->setCodecConfig(p_sink->codec_caps, true /* is_capability */, + new_codec_config, true /* select_current_codec */)) { log::verbose("cannot set source codec {}", codec_config.name()); return nullptr; } p_peer->p_sink = p_sink; - SaveNewCodecConfig(p_peer, new_codec_config, p_sink->num_protect, - p_sink->protect_info, AVDT_TSEP_SRC); + SaveNewCodecConfig(p_peer, new_codec_config, p_sink->num_protect, p_sink->protect_info, + AVDT_TSEP_SRC); return p_sink; } -const BtaAvCoSep* BtaAvCo::AttemptSinkCodecSelection( - const A2dpCodecConfig& codec_config, BtaAvCoPeer* p_peer) { +const BtaAvCoSep* BtaAvCo::AttemptSinkCodecSelection(const A2dpCodecConfig& codec_config, + BtaAvCoPeer* p_peer) { uint8_t new_codec_config[AVDT_CODEC_SIZE]; log::verbose(""); // Find the peer Source for the codec - BtaAvCoSep* p_source = peer_cache_->FindPeerSource( - p_peer, codec_config.codecIndex(), ContentProtectFlag()); + BtaAvCoSep* p_source = + peer_cache_->FindPeerSource(p_peer, codec_config.codecIndex(), ContentProtectFlag()); if (p_source == nullptr) { log::verbose("peer Source for codec {} not found", codec_config.name()); return nullptr; } - if (!p_peer->GetCodecs()->setSinkCodecConfig( - p_source->codec_caps, true /* is_capability */, new_codec_config, - true /* select_current_codec */)) { + if (!p_peer->GetCodecs()->setSinkCodecConfig(p_source->codec_caps, true /* is_capability */, + new_codec_config, true /* select_current_codec */)) { log::verbose("cannot set sink codec {}", codec_config.name()); return nullptr; } p_peer->p_source = p_source; - SaveNewCodecConfig(p_peer, new_codec_config, p_source->num_protect, - p_source->protect_info, AVDT_TSEP_SNK); + SaveNewCodecConfig(p_peer, new_codec_config, p_source->num_protect, p_source->protect_info, + AVDT_TSEP_SNK); return p_source; } @@ -1327,8 +1249,8 @@ bool BtaAvCo::UpdateSelectableSourceCodec(const A2dpCodecConfig& codec_config, log::verbose("peer {}", p_peer->addr); // Find the peer Sink for the codec - const BtaAvCoSep* p_sink = peer_cache_->FindPeerSink( - p_peer, codec_config.codecIndex(), ContentProtectFlag()); + const BtaAvCoSep* p_sink = + peer_cache_->FindPeerSink(p_peer, codec_config.codecIndex(), ContentProtectFlag()); if (p_sink == nullptr) { // The peer Sink device does not support this codec return false; @@ -1354,19 +1276,17 @@ size_t BtaAvCo::UpdateAllSelectableSinkCodecs(BtaAvCoPeer* p_peer) { return updated_codecs; } -bool BtaAvCo::UpdateSelectableSinkCodec(const A2dpCodecConfig& codec_config, - BtaAvCoPeer* p_peer) { +bool BtaAvCo::UpdateSelectableSinkCodec(const A2dpCodecConfig& codec_config, BtaAvCoPeer* p_peer) { log::verbose("peer {}", p_peer->addr); // Find the peer Source for the codec - const BtaAvCoSep* p_source = peer_cache_->FindPeerSource( - p_peer, codec_config.codecIndex(), ContentProtectFlag()); + const BtaAvCoSep* p_source = + peer_cache_->FindPeerSource(p_peer, codec_config.codecIndex(), ContentProtectFlag()); if (p_source == nullptr) { // The peer Source device does not support this codec return false; } - if (!p_peer->GetCodecs()->setPeerSourceCodecCapabilities( - p_source->codec_caps)) { + if (!p_peer->GetCodecs()->setPeerSourceCodecCapabilities(p_source->codec_caps)) { log::warn("cannot update peer {} codec capabilities for {}", p_peer->addr, A2DP_CodecName(p_source->codec_caps)); return false; @@ -1374,10 +1294,8 @@ bool BtaAvCo::UpdateSelectableSinkCodec(const A2dpCodecConfig& codec_config, return true; } -void BtaAvCo::SaveNewCodecConfig(BtaAvCoPeer* p_peer, - const uint8_t* new_codec_config, - uint8_t num_protect, - const uint8_t* p_protect_info, +void BtaAvCo::SaveNewCodecConfig(BtaAvCoPeer* p_peer, const uint8_t* new_codec_config, + uint8_t num_protect, const uint8_t* p_protect_info, const uint8_t t_local_sep) { log::verbose("peer {}", p_peer->addr); log::verbose("codec: {}", A2DP_CodecInfoString(new_codec_config)); @@ -1385,9 +1303,8 @@ void BtaAvCo::SaveNewCodecConfig(BtaAvCoPeer* p_peer, std::lock_guard lock(peer_cache_->codec_lock_); BtaAvCoState* reference_state = getStateFromLocalProfile(t_local_sep); if (reference_state == nullptr) { - log::warn( - "Invalid bta av state for peer_address : {} with local sep as :{}", - p_peer->addr, t_local_sep); + log::warn("Invalid bta av state for peer_address : {} with local sep as :{}", p_peer->addr, + t_local_sep); return; } reference_state->setCodecConfig(new_codec_config); @@ -1407,8 +1324,8 @@ BtaAvCoState* BtaAvCo::getStateFromPeer(const BtaAvCoPeer* p_peer) { } else if (p_peer->uuid_to_connect == UUID_SERVCLASS_AUDIO_SOURCE) { return &bta_av_sink_state_; } else { - log::warn("Invalid bta av state for peer_address : {} with uuid as :{}", - p_peer->addr, p_peer->uuid_to_connect); + log::warn("Invalid bta av state for peer_address : {} with uuid as :{}", p_peer->addr, + p_peer->uuid_to_connect); return nullptr; } } else { @@ -1416,25 +1333,21 @@ BtaAvCoState* BtaAvCo::getStateFromPeer(const BtaAvCoPeer* p_peer) { } } -bool BtaAvCo::SetCodecOtaConfig(BtaAvCoPeer* p_peer, - const uint8_t* p_ota_codec_config, - uint8_t num_protect, - const uint8_t* p_protect_info, - bool* p_restart_output, - const uint8_t t_local_sep) { +bool BtaAvCo::SetCodecOtaConfig(BtaAvCoPeer* p_peer, const uint8_t* p_ota_codec_config, + uint8_t num_protect, const uint8_t* p_protect_info, + bool* p_restart_output, const uint8_t t_local_sep) { uint8_t result_codec_config[AVDT_CODEC_SIZE]; bool restart_input = false; bool restart_output = false; bool config_updated = false; - log::info("peer_address={}, codec: {}", p_peer->addr, - A2DP_CodecInfoString(p_ota_codec_config)); + log::info("peer_address={}, codec: {}", p_peer->addr, A2DP_CodecInfoString(p_ota_codec_config)); *p_restart_output = false; // Find the peer SEP codec to use const BtaAvCoSep* p_sink = peer_cache_->FindPeerSink( - p_peer, A2DP_SourceCodecIndex(p_ota_codec_config), ContentProtectFlag()); + p_peer, A2DP_SourceCodecIndex(p_ota_codec_config), ContentProtectFlag()); if ((p_peer->num_sup_sinks > 0) && (p_sink == nullptr)) { // There are no peer SEPs if we didn't do the discovery procedure yet. // We have all the information we need from the peer, so we can @@ -1445,21 +1358,18 @@ bool BtaAvCo::SetCodecOtaConfig(BtaAvCoPeer* p_peer, tA2DP_ENCODER_INIT_PEER_PARAMS peer_params; GetPeerEncoderParameters(p_peer->addr, &peer_params); - if (!p_peer->GetCodecs()->setCodecOtaConfig( - p_ota_codec_config, &peer_params, result_codec_config, &restart_input, - &restart_output, &config_updated)) { + if (!p_peer->GetCodecs()->setCodecOtaConfig(p_ota_codec_config, &peer_params, result_codec_config, + &restart_input, &restart_output, &config_updated)) { log::error("peer {} : cannot set OTA config", p_peer->addr); return false; } if (restart_output) { - log::verbose("restart output for codec: {}", - A2DP_CodecInfoString(result_codec_config)); + log::verbose("restart output for codec: {}", A2DP_CodecInfoString(result_codec_config)); *p_restart_output = true; p_peer->p_sink = p_sink; - SaveNewCodecConfig(p_peer, result_codec_config, num_protect, p_protect_info, - t_local_sep); + SaveNewCodecConfig(p_peer, result_codec_config, num_protect, p_protect_info, t_local_sep); } if (restart_input || config_updated) { @@ -1471,9 +1381,8 @@ bool BtaAvCo::SetCodecOtaConfig(BtaAvCoPeer* p_peer, return true; } -void bta_av_co_init( - const std::vector& codec_priorities, - std::vector* supported_codecs) { +void bta_av_co_init(const std::vector& codec_priorities, + std::vector* supported_codecs) { bta_av_co_cb.Init(codec_priorities, supported_codecs); } @@ -1485,22 +1394,19 @@ A2dpCodecConfig* bta_av_get_a2dp_current_codec(void) { return bta_av_co_cb.GetActivePeerCurrentCodec(); } -A2dpCodecConfig* bta_av_get_a2dp_peer_current_codec( - const RawAddress& peer_address) { +A2dpCodecConfig* bta_av_get_a2dp_peer_current_codec(const RawAddress& peer_address) { return bta_av_co_cb.GetPeerCurrentCodec(peer_address); } -bool bta_av_co_audio_init(btav_a2dp_codec_index_t codec_index, - AvdtpSepConfig* p_cfg) { +bool bta_av_co_audio_init(btav_a2dp_codec_index_t codec_index, AvdtpSepConfig* p_cfg) { return A2DP_InitCodecConfig(codec_index, p_cfg); } -void bta_av_co_audio_disc_res(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_address, uint8_t num_seps, - uint8_t num_sinks, uint8_t num_sources, +void bta_av_co_audio_disc_res(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, + uint8_t num_seps, uint8_t num_sinks, uint8_t num_sources, uint16_t uuid_local) { - bta_av_co_cb.ProcessDiscoveryResult(bta_av_handle, peer_address, num_seps, - num_sinks, num_sources, uuid_local); + bta_av_co_cb.ProcessDiscoveryResult(bta_av_handle, peer_address, num_seps, num_sinks, num_sources, + uuid_local); } static void bta_av_co_store_peer_codectype(const BtaAvCoPeer* p_peer) { @@ -1512,140 +1418,117 @@ static void bta_av_co_store_peer_codectype(const BtaAvCoPeer* p_peer) { peer_codec_type |= A2DP_IotGetPeerSinkCodecType(p_sink->codec_caps); } - DEVICE_IOT_CONFIG_ADDR_SET_HEX(p_peer->addr, IOT_CONF_KEY_A2DP_CODECTYPE, - peer_codec_type, IOT_CONF_BYTE_NUM_1); + DEVICE_IOT_CONFIG_ADDR_SET_HEX(p_peer->addr, IOT_CONF_KEY_A2DP_CODECTYPE, peer_codec_type, + IOT_CONF_BYTE_NUM_1); } static bool bta_av_co_should_select_hardware_codec( - const A2dpCodecConfig& software_config, - const ::bluetooth::audio::a2dp::provider::a2dp_configuration& - hardware_config) { + const A2dpCodecConfig& software_config, + const ::bluetooth::audio::a2dp::provider::a2dp_configuration& hardware_config) { btav_a2dp_codec_index_t software_codec_index = software_config.codecIndex(); - btav_a2dp_codec_index_t hardware_offload_index = - hardware_config.codec_parameters.codec_type; + btav_a2dp_codec_index_t hardware_offload_index = hardware_config.codec_parameters.codec_type; // Prioritize any offload codec except SBC and AAC - if (A2DP_GetCodecType(hardware_config.codec_config) == - A2DP_MEDIA_CT_NON_A2DP) { - log::verbose("select hardware codec: {}", - A2DP_CodecIndexStr(hardware_offload_index)); + if (A2DP_GetCodecType(hardware_config.codec_config) == A2DP_MEDIA_CT_NON_A2DP) { + log::verbose("select hardware codec: {}", A2DP_CodecIndexStr(hardware_offload_index)); return true; } // Prioritize LDAC, AptX HD and AptX over AAC and SBC offload codecs if (software_codec_index == BTAV_A2DP_CODEC_INDEX_SOURCE_LDAC || software_codec_index == BTAV_A2DP_CODEC_INDEX_SOURCE_APTX_HD || software_codec_index == BTAV_A2DP_CODEC_INDEX_SOURCE_APTX) { - log::verbose("select software codec: {}", - A2DP_CodecIndexStr(software_codec_index)); + log::verbose("select software codec: {}", A2DP_CodecIndexStr(software_codec_index)); return false; } // Prioritize AAC offload if (hardware_offload_index == BTAV_A2DP_CODEC_INDEX_SOURCE_AAC) { - log::verbose("select hardware codec: {}", - A2DP_CodecIndexStr(hardware_offload_index)); + log::verbose("select hardware codec: {}", A2DP_CodecIndexStr(hardware_offload_index)); return true; } // Prioritize AAC software if (software_codec_index == BTAV_A2DP_CODEC_INDEX_SOURCE_AAC) { - log::verbose("select software codec: {}", - A2DP_CodecIndexStr(software_codec_index)); + log::verbose("select software codec: {}", A2DP_CodecIndexStr(software_codec_index)); return false; } // Prioritize SBC offload if (hardware_offload_index == BTAV_A2DP_CODEC_INDEX_SOURCE_SBC) { - log::verbose("select hardware codec: {}", - A2DP_CodecIndexStr(hardware_offload_index)); + log::verbose("select hardware codec: {}", A2DP_CodecIndexStr(hardware_offload_index)); return true; } // Prioritize SBC software if (software_codec_index == BTAV_A2DP_CODEC_INDEX_SOURCE_SBC) { - log::verbose("select software codec: {}", - A2DP_CodecIndexStr(software_codec_index)); + log::verbose("select software codec: {}", A2DP_CodecIndexStr(software_codec_index)); return false; } - log::error("select unknown software codec: {}", - A2DP_CodecIndexStr(software_codec_index)); + log::error("select unknown software codec: {}", A2DP_CodecIndexStr(software_codec_index)); return false; } -tA2DP_STATUS bta_av_co_audio_getconfig(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_address, - uint8_t* p_codec_info, - uint8_t* p_sep_info_idx, uint8_t seid, - uint8_t* p_num_protect, - uint8_t* p_protect_info) { +tA2DP_STATUS bta_av_co_audio_getconfig(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, + uint8_t* p_codec_info, uint8_t* p_sep_info_idx, uint8_t seid, + uint8_t* p_num_protect, uint8_t* p_protect_info) { uint16_t peer_uuid = bta_av_co_cb.peer_cache_->FindPeerUuid(bta_av_handle); - log::verbose("peer {} bta_av_handle=0x{:x} peer_uuid=0x{:x}", peer_address, - bta_av_handle, peer_uuid); + log::verbose("peer {} bta_av_handle=0x{:x} peer_uuid=0x{:x}", peer_address, bta_av_handle, + peer_uuid); switch (peer_uuid) { case UUID_SERVCLASS_AUDIO_SOURCE: - return bta_av_co_cb.ProcessSinkGetConfig( - bta_av_handle, peer_address, p_codec_info, p_sep_info_idx, seid, - p_num_protect, p_protect_info); + return bta_av_co_cb.ProcessSinkGetConfig(bta_av_handle, peer_address, p_codec_info, + p_sep_info_idx, seid, p_num_protect, p_protect_info); case UUID_SERVCLASS_AUDIO_SINK: - return bta_av_co_cb.ProcessSourceGetConfig( - bta_av_handle, peer_address, p_codec_info, p_sep_info_idx, seid, - p_num_protect, p_protect_info); + return bta_av_co_cb.ProcessSourceGetConfig(bta_av_handle, peer_address, p_codec_info, + p_sep_info_idx, seid, p_num_protect, + p_protect_info); default: break; } - log::error("peer {} : Invalid peer UUID: 0x{:x} for bta_av_handle 0x{:x}", - peer_address, peer_uuid, bta_av_handle); + log::error("peer {} : Invalid peer UUID: 0x{:x} for bta_av_handle 0x{:x}", peer_address, + peer_uuid, bta_av_handle); return A2DP_FAIL; } -void bta_av_co_audio_setconfig(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_address, - const uint8_t* p_codec_info, uint8_t seid, - uint8_t num_protect, - const uint8_t* p_protect_info, - uint8_t t_local_sep, uint8_t avdt_handle) { - bta_av_co_cb.ProcessSetConfig(bta_av_handle, peer_address, p_codec_info, seid, - num_protect, p_protect_info, t_local_sep, - avdt_handle); +void bta_av_co_audio_setconfig(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, + const uint8_t* p_codec_info, uint8_t seid, uint8_t num_protect, + const uint8_t* p_protect_info, uint8_t t_local_sep, + uint8_t avdt_handle) { + bta_av_co_cb.ProcessSetConfig(bta_av_handle, peer_address, p_codec_info, seid, num_protect, + p_protect_info, t_local_sep, avdt_handle); } -void bta_av_co_audio_open(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_address, uint16_t mtu) { +void bta_av_co_audio_open(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, + uint16_t mtu) { bta_av_co_cb.ProcessOpen(bta_av_handle, peer_address, mtu); } -void bta_av_co_audio_close(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_address) { +void bta_av_co_audio_close(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address) { bta_av_co_cb.ProcessClose(bta_av_handle, peer_address); } -void bta_av_co_audio_start(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_address, +void bta_av_co_audio_start(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, const uint8_t* p_codec_info, bool* p_no_rtp_header) { - bta_av_co_cb.ProcessStart(bta_av_handle, peer_address, p_codec_info, - p_no_rtp_header); + bta_av_co_cb.ProcessStart(bta_av_handle, peer_address, p_codec_info, p_no_rtp_header); } -void bta_av_co_audio_stop(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_address) { +void bta_av_co_audio_stop(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address) { bta_av_co_cb.ProcessStop(bta_av_handle, peer_address); } -BT_HDR* bta_av_co_audio_source_data_path(const uint8_t* p_codec_info, - uint32_t* p_timestamp) { +BT_HDR* bta_av_co_audio_source_data_path(const uint8_t* p_codec_info, uint32_t* p_timestamp) { return bta_av_co_cb.GetNextSourceDataPacket(p_codec_info, p_timestamp); } -void bta_av_co_audio_drop(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_address) { +void bta_av_co_audio_drop(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address) { bta_av_co_cb.DataPacketWasDropped(bta_av_handle, peer_address); } -void bta_av_co_audio_delay(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_address, uint16_t delay) { +void bta_av_co_audio_delay(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, + uint16_t delay) { bta_av_co_cb.ProcessAudioDelay(bta_av_handle, peer_address, delay); } -void bta_av_co_audio_update_mtu(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_address, uint16_t mtu) { +void bta_av_co_audio_update_mtu(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, + uint16_t mtu) { bta_av_co_cb.UpdateMtu(bta_av_handle, peer_address, mtu); } @@ -1674,15 +1557,13 @@ const tA2DP_ENCODER_INTERFACE* bta_av_co_get_encoder_interface(void) { return bta_av_co_cb.GetSourceEncoderInterface(); } -bool bta_av_co_set_codec_user_config( - const RawAddress& peer_address, - const btav_a2dp_codec_config_t& codec_user_config, bool* p_restart_output) { - return bta_av_co_cb.SetCodecUserConfig(peer_address, codec_user_config, - p_restart_output); +bool bta_av_co_set_codec_user_config(const RawAddress& peer_address, + const btav_a2dp_codec_config_t& codec_user_config, + bool* p_restart_output) { + return bta_av_co_cb.SetCodecUserConfig(peer_address, codec_user_config, p_restart_output); } -bool bta_av_co_set_codec_audio_config( - const btav_a2dp_codec_config_t& codec_audio_config) { +bool bta_av_co_set_codec_audio_config(const btav_a2dp_codec_config_t& codec_audio_config) { return bta_av_co_cb.SetCodecAudioConfig(codec_audio_config); } @@ -1694,8 +1575,7 @@ int bta_av_co_get_encoder_preferred_interval_us() { return bta_av_co_cb.GetSourceEncoderPreferredIntervalUs(); } -btav_a2dp_scmst_info_t bta_av_co_get_scmst_info( - const RawAddress& peer_address) { +btav_a2dp_scmst_info_t bta_av_co_get_scmst_info(const RawAddress& peer_address) { BtaAvCoPeer* p_peer = bta_av_co_cb.peer_cache_->FindPeer(peer_address); log::assert_that(p_peer != nullptr, "assert failed: p_peer != nullptr"); btav_a2dp_scmst_info_t scmst_info{}; diff --git a/system/btif/co/bta_av_co_peer.cc b/system/btif/co/bta_av_co_peer.cc index 81e37abbd2a..a6529260919 100644 --- a/system/btif/co/bta_av_co_peer.cc +++ b/system/btif/co/bta_av_co_peer.cc @@ -25,10 +25,8 @@ using namespace bluetooth; // Macro to convert BTA AV audio handle to index and vice versa -#define BTA_AV_CO_AUDIO_HANDLE_TO_INDEX(bta_av_handle) \ - (((bta_av_handle) & (~BTA_AV_CHNL_MSK)) - 1) -#define BTA_AV_CO_AUDIO_INDEX_TO_HANDLE(index) \ - (((index) + 1) | BTA_AV_CHNL_AUDIO) +#define BTA_AV_CO_AUDIO_HANDLE_TO_INDEX(bta_av_handle) (((bta_av_handle) & (~BTA_AV_CHNL_MSK)) - 1) +#define BTA_AV_CO_AUDIO_INDEX_TO_HANDLE(index) (((index) + 1) | BTA_AV_CHNL_AUDIO) BtaAvCoPeer::BtaAvCoPeer() : addr(RawAddress::kEmpty), @@ -53,8 +51,7 @@ BtaAvCoPeer::BtaAvCoPeer() Reset(0); } -void BtaAvCoPeer::Init( - const std::vector& codec_priorities) { +void BtaAvCoPeer::Init(const std::vector& codec_priorities) { Reset(bta_av_handle_); // Reset the current config codecs_ = new A2dpCodecs(codec_priorities); @@ -94,9 +91,8 @@ void BtaAvCoPeer::Reset(tBTA_AV_HNDL bta_av_handle) { content_protect_active_ = false; } -void BtaAvCoPeerCache::Init( - const std::vector& codec_priorities, - std::vector* supported_codecs) { +void BtaAvCoPeerCache::Init(const std::vector& codec_priorities, + std::vector* supported_codecs) { std::lock_guard lock(codec_lock_); codec_priorities_ = codec_priorities; @@ -127,9 +123,9 @@ BtaAvCoPeer* BtaAvCoPeerCache::FindPeer(const RawAddress& peer_address) { return nullptr; } -BtaAvCoSep* BtaAvCoPeerCache::FindPeerSource( - BtaAvCoPeer* p_peer, btav_a2dp_codec_index_t codec_index, - const uint8_t content_protect_flag) { +BtaAvCoSep* BtaAvCoPeerCache::FindPeerSource(BtaAvCoPeer* p_peer, + btav_a2dp_codec_index_t codec_index, + const uint8_t content_protect_flag) { if (codec_index == BTAV_A2DP_CODEC_INDEX_MAX) { log::warn("invalid codec index for peer {}", p_peer->addr); return nullptr; @@ -138,15 +134,13 @@ BtaAvCoSep* BtaAvCoPeerCache::FindPeerSource( // Find the peer Source for the codec for (size_t index = 0; index < p_peer->num_sup_sources; index++) { BtaAvCoSep* p_source = &p_peer->sources[index]; - btav_a2dp_codec_index_t peer_codec_index = - A2DP_SinkCodecIndex(p_source->codec_caps); + btav_a2dp_codec_index_t peer_codec_index = A2DP_SinkCodecIndex(p_source->codec_caps); if (peer_codec_index != codec_index) { continue; } if (!AudioSepHasContentProtection(p_source, content_protect_flag)) { - log::verbose( - "peer Source for codec {} does not support Content Protection", - A2DP_CodecIndexStr(codec_index)); + log::verbose("peer Source for codec {} does not support Content Protection", + A2DP_CodecIndexStr(codec_index)); continue; } return p_source; @@ -154,8 +148,7 @@ BtaAvCoSep* BtaAvCoPeerCache::FindPeerSource( return nullptr; } -BtaAvCoSep* BtaAvCoPeerCache::FindPeerSink(BtaAvCoPeer* p_peer, - btav_a2dp_codec_index_t codec_index, +BtaAvCoSep* BtaAvCoPeerCache::FindPeerSink(BtaAvCoPeer* p_peer, btav_a2dp_codec_index_t codec_index, const uint8_t content_protect_flag) { if (codec_index == BTAV_A2DP_CODEC_INDEX_MAX) { log::warn("invalid codec index for peer {}", p_peer->addr); @@ -165,8 +158,7 @@ BtaAvCoSep* BtaAvCoPeerCache::FindPeerSink(BtaAvCoPeer* p_peer, // Find the peer Sink for the codec for (size_t index = 0; index < p_peer->num_sup_sinks; index++) { BtaAvCoSep* p_sink = &p_peer->sinks[index]; - btav_a2dp_codec_index_t peer_codec_index = - A2DP_SourceCodecIndex(p_sink->codec_caps); + btav_a2dp_codec_index_t peer_codec_index = A2DP_SourceCodecIndex(p_sink->codec_caps); if (peer_codec_index != codec_index) { continue; } @@ -188,27 +180,26 @@ BtaAvCoPeer* BtaAvCoPeerCache::FindPeer(tBTA_AV_HNDL bta_av_handle) { // Sanity check if (index >= BTA_AV_CO_NUM_ELEMENTS(peers_)) { - log::error("peer index {} for BTA AV handle 0x{:x} is out of bounds", index, - bta_av_handle); + log::error("peer index {} for BTA AV handle 0x{:x} is out of bounds", index, bta_av_handle); return nullptr; } return &peers_[index]; } -BtaAvCoPeer* BtaAvCoPeerCache::FindPeerAndUpdate( - tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address) { +BtaAvCoPeer* BtaAvCoPeerCache::FindPeerAndUpdate(tBTA_AV_HNDL bta_av_handle, + const RawAddress& peer_address) { log::verbose("peer {} bta_av_handle = 0x{:x}", peer_address, bta_av_handle); BtaAvCoPeer* p_peer = FindPeer(bta_av_handle); if (p_peer == nullptr) { - log::error("peer entry for BTA AV handle 0x{:x} peer {} not found", - bta_av_handle, peer_address); + log::error("peer entry for BTA AV handle 0x{:x} peer {} not found", bta_av_handle, + peer_address); return nullptr; } - log::verbose("peer {} bta_av_handle = 0x{:x} previous address {}", - peer_address, bta_av_handle, p_peer->addr); + log::verbose("peer {} bta_av_handle = 0x{:x} previous address {}", peer_address, bta_av_handle, + p_peer->addr); p_peer->addr = peer_address; return p_peer; } @@ -239,7 +230,9 @@ bool ContentProtectIsScmst(const uint8_t* p_protect_info) { bool AudioProtectHasScmst(uint8_t num_protect, const uint8_t* p_protect_info) { log::verbose(""); while (num_protect--) { - if (ContentProtectIsScmst(p_protect_info)) return true; + if (ContentProtectIsScmst(p_protect_info)) { + return true; + } // Move to the next Content Protect schema p_protect_info += *p_protect_info + 1; } @@ -247,8 +240,7 @@ bool AudioProtectHasScmst(uint8_t num_protect, const uint8_t* p_protect_info) { return false; } -bool AudioSepHasContentProtection(const BtaAvCoSep* p_sep, - const uint8_t content_protect_flag) { +bool AudioSepHasContentProtection(const BtaAvCoSep* p_sep, const uint8_t content_protect_flag) { log::verbose(""); // Check if content protection is enabled for this stream diff --git a/system/btif/co/bta_dm_co.cc b/system/btif/co/bta_dm_co.cc index 4f60e2bce96..80dc070b917 100644 --- a/system/btif/co/bta_dm_co.cc +++ b/system/btif/co/bta_dm_co.cc @@ -20,7 +20,6 @@ #include "internal_include/bte_appl.h" #include "stack/include/btm_api_types.h" -tBTE_APPL_CFG bte_appl_cfg = { - BTA_LE_AUTH_REQ_SC_MITM_BOND, // Authentication requirements - BTM_IO_CAP_KBDISP, BTM_BLE_INITIATOR_KEY_SIZE, BTM_BLE_RESPONDER_KEY_SIZE, - BTM_BLE_MAX_KEY_SIZE}; +tBTE_APPL_CFG bte_appl_cfg = {BTA_LE_AUTH_REQ_SC_MITM_BOND, // Authentication requirements + BTM_IO_CAP_KBDISP, BTM_BLE_INITIATOR_KEY_SIZE, + BTM_BLE_RESPONDER_KEY_SIZE, BTM_BLE_MAX_KEY_SIZE}; diff --git a/system/btif/co/bta_hh_co.cc b/system/btif/co/bta_hh_co.cc index 6c5e13dbae5..5ef59577233 100644 --- a/system/btif/co/bta_hh_co.cc +++ b/system/btif/co/bta_hh_co.cc @@ -53,23 +53,25 @@ static tBTA_HH_RPT_CACHE_ENTRY sReportCache[BTA_HH_NV_LOAD_MAX]; using namespace bluetooth; -static const bthh_report_type_t map_rtype_uhid_hh[] = { - BTHH_FEATURE_REPORT, BTHH_OUTPUT_REPORT, BTHH_INPUT_REPORT}; +static const bthh_report_type_t map_rtype_uhid_hh[] = {BTHH_FEATURE_REPORT, BTHH_OUTPUT_REPORT, + BTHH_INPUT_REPORT}; static void* btif_hh_poll_event_thread(void* arg); void uhid_set_non_blocking(int fd) { int opts = fcntl(fd, F_GETFL); - if (opts < 0) log::error("Getting flags failed ({})", strerror(errno)); + if (opts < 0) { + log::error("Getting flags failed ({})", strerror(errno)); + } opts |= O_NONBLOCK; - if (fcntl(fd, F_SETFL, opts) < 0) + if (fcntl(fd, F_SETFL, opts) < 0) { log::verbose("Setting non-blocking flag failed ({})", strerror(errno)); + } } -static bool uhid_feature_req_handler(btif_hh_uhid_t* p_uhid, - struct uhid_feature_req& req) { +static bool uhid_feature_req_handler(btif_hh_uhid_t* p_uhid, struct uhid_feature_req& req) { log::debug("Report type = {}, id = {}", req.rtype, req.rnum); if (req.rtype > UHID_INPUT_REPORT) { @@ -96,8 +98,7 @@ static bool uhid_feature_req_handler(btif_hh_uhid_t* p_uhid, } #if ENABLE_UHID_SET_REPORT -static bool uhid_set_report_req_handler(btif_hh_uhid_t* p_uhid, - struct uhid_set_report_req& req) { +static bool uhid_set_report_req_handler(btif_hh_uhid_t* p_uhid, struct uhid_set_report_req& req) { log::debug("Report type = {}, id = {}", req.rtype, req.rnum); if (req.rtype > UHID_INPUT_REPORT) { @@ -183,17 +184,17 @@ static int uhid_read_event(btif_hh_uhid_t* p_uhid) { return -EFAULT; } - log::verbose("UHID_OUTPUT: Report type = {}, report_size = {}", - ev.u.output.rtype, ev.u.output.size); + log::verbose("UHID_OUTPUT: Report type = {}, report_size = {}", ev.u.output.rtype, + ev.u.output.size); // Send SET_REPORT with feature report if the report type in output event // is FEATURE - if (ev.u.output.rtype == UHID_FEATURE_REPORT) - btif_hh_setreport(p_uhid, BTHH_FEATURE_REPORT, ev.u.output.size, - ev.u.output.data); - else if (ev.u.output.rtype == UHID_OUTPUT_REPORT) + if (ev.u.output.rtype == UHID_FEATURE_REPORT) { + btif_hh_setreport(p_uhid, BTHH_FEATURE_REPORT, ev.u.output.size, ev.u.output.data); + } else if (ev.u.output.rtype == UHID_OUTPUT_REPORT) { btif_hh_senddata(p_uhid, ev.u.output.size, ev.u.output.data); - else + } else { log::error("UHID_OUTPUT: Invalid report type = {}", ev.u.output.rtype); + } break; case UHID_OUTPUT_EV: if (ret < (ssize_t)(sizeof(ev.type) + sizeof(ev.u.output_ev))) { @@ -206,8 +207,8 @@ static int uhid_read_event(btif_hh_uhid_t* p_uhid) { case UHID_FEATURE: // UHID_GET_REPORT if (ret < (ssize_t)(sizeof(ev.type) + sizeof(ev.u.feature))) { - log::error("UHID_GET_REPORT: Invalid size read from uhid-dev: {} < {}", - ret, sizeof(ev.type) + sizeof(ev.u.feature)); + log::error("UHID_GET_REPORT: Invalid size read from uhid-dev: {} < {}", ret, + sizeof(ev.type) + sizeof(ev.u.feature)); return -EFAULT; } @@ -220,8 +221,8 @@ static int uhid_read_event(btif_hh_uhid_t* p_uhid) { #if ENABLE_UHID_SET_REPORT case UHID_SET_REPORT: { if (ret < (ssize_t)(sizeof(ev.type) + sizeof(ev.u.set_report))) { - log::error("UHID_SET_REPORT: Invalid size read from uhid-dev: {} < {}", - ret, sizeof(ev.type) + sizeof(ev.u.set_report)); + log::error("UHID_SET_REPORT: Invalid size read from uhid-dev: {} < {}", ret, + sizeof(ev.type) + sizeof(ev.u.set_report)); return -EFAULT; } @@ -248,8 +249,7 @@ static int uhid_read_event(btif_hh_uhid_t* p_uhid) { * Returns pthread_t * ******************************************************************************/ -static inline pthread_t create_thread(void* (*start_routine)(void*), - void* arg) { +static inline pthread_t create_thread(void* (*start_routine)(void*), void* arg) { log::verbose("create_thread: entered"); pthread_attr_t thread_attr; @@ -288,27 +288,23 @@ static bool uhid_fd_open(btif_hh_device_t* p_dev) { if (p_dev->uhid.hh_keep_polling == 0) { p_dev->uhid.hh_keep_polling = 1; - p_dev->hh_poll_thread_id = - create_thread(btif_hh_poll_event_thread, &p_dev->uhid); + p_dev->hh_poll_thread_id = create_thread(btif_hh_poll_event_thread, &p_dev->uhid); } return true; } -static int uhid_fd_poll(btif_hh_uhid_t* p_uhid, - std::array& pfds) { +static int uhid_fd_poll(btif_hh_uhid_t* p_uhid, std::array& pfds) { int ret = 0; int counter = 0; do { - if (com::android::bluetooth::flags::break_uhid_polling_early() && - !p_uhid->hh_keep_polling) { + if (com::android::bluetooth::flags::break_uhid_polling_early() && !p_uhid->hh_keep_polling) { log::debug("Polling stopped"); return -1; } if (counter++ > BTA_HH_UHID_INTERRUPT_COUNT_MAX) { - log::error("Polling interrupted consecutively {} times", - BTA_HH_UHID_INTERRUPT_COUNT_MAX); + log::error("Polling interrupted consecutively {} times", BTA_HH_UHID_INTERRUPT_COUNT_MAX); return -1; } @@ -366,12 +362,10 @@ static bool uhid_configure_thread(btif_hh_uhid_t* p_uhid) { // Change the name of thread char thread_name[16] = {}; - sprintf(thread_name, BT_HH_THREAD_PREFIX "%02x:%02x", - p_uhid->link_spec.addrt.bda.address[4], + sprintf(thread_name, BT_HH_THREAD_PREFIX "%02x:%02x", p_uhid->link_spec.addrt.bda.address[4], p_uhid->link_spec.addrt.bda.address[5]); pthread_setname_np(pthread_self(), thread_name); - log::debug("Host hid polling thread created name:{} pid:{} fd:{}", - thread_name, pid, p_uhid->fd); + log::debug("Host hid polling thread created name:{} pid:{} fd:{}", thread_name, pid, p_uhid->fd); // Set the uhid fd as non-blocking to ensure we never block the BTU thread uhid_set_non_blocking(p_uhid->fd); @@ -427,9 +421,8 @@ int bta_hh_co_write(int fd, uint8_t* rpt, uint16_t len) { * * Returns True if platform specific initialization is successful ******************************************************************************/ -bool bta_hh_co_open(uint8_t dev_handle, uint8_t sub_class, - tBTA_HH_ATTR_MASK attr_mask, uint8_t app_id, - tAclLinkSpec& link_spec) { +bool bta_hh_co_open(uint8_t dev_handle, uint8_t sub_class, tBTA_HH_ATTR_MASK attr_mask, + uint8_t app_id, tAclLinkSpec& link_spec) { bool new_device = false; if (dev_handle == BTA_HH_INVALID_HANDLE) { @@ -441,11 +434,11 @@ bool bta_hh_co_open(uint8_t dev_handle, uint8_t sub_class, btif_hh_device_t* p_dev = btif_hh_find_dev_by_handle(dev_handle); if (p_dev != nullptr) { log::info( - "Found an existing device with the same handle dev_status={}, " - "device={}, attr_mask=0x{:04x}, sub_class=0x{:02x}, app_id={}, " - "dev_handle={}", - p_dev->dev_status, p_dev->link_spec, p_dev->attr_mask, p_dev->sub_class, - p_dev->app_id, dev_handle); + "Found an existing device with the same handle dev_status={}, " + "device={}, attr_mask=0x{:04x}, sub_class=0x{:02x}, app_id={}, " + "dev_handle={}", + p_dev->dev_status, p_dev->link_spec, p_dev->attr_mask, p_dev->sub_class, p_dev->app_id, + dev_handle); } else { // Use an empty slot p_dev = btif_hh_find_empty_dev(); if (p_dev == nullptr) { @@ -477,12 +470,10 @@ bool bta_hh_co_open(uint8_t dev_handle, uint8_t sub_class, p_dev->dev_status = BTHH_CONN_STATE_CONNECTED; p_dev->dev_handle = dev_handle; p_dev->uhid.get_rpt_id_queue = fixed_queue_new(SIZE_MAX); - log::assert_that(p_dev->uhid.get_rpt_id_queue, - "assert failed: p_dev->uhid.get_rpt_id_queue"); + log::assert_that(p_dev->uhid.get_rpt_id_queue, "assert failed: p_dev->uhid.get_rpt_id_queue"); #if ENABLE_UHID_SET_REPORT p_dev->uhid.set_rpt_id_queue = fixed_queue_new(SIZE_MAX); - log::assert_that(p_dev->uhid.set_rpt_id_queue, - "assert failed: p_dev->uhid.set_rpt_id_queue"); + log::assert_that(p_dev->uhid.set_rpt_id_queue, "assert failed: p_dev->uhid.set_rpt_id_queue"); #endif // ENABLE_UHID_SET_REPORT log::debug("Return device status {}", p_dev->dev_status); @@ -501,8 +492,8 @@ bool bta_hh_co_open(uint8_t dev_handle, uint8_t sub_class, * Returns void. ******************************************************************************/ void bta_hh_co_close(btif_hh_device_t* p_dev) { - log::info("Closing device handle={}, status={}, address={}", - p_dev->dev_handle, p_dev->dev_status, p_dev->link_spec); + log::info("Closing device handle={}, status={}, address={}", p_dev->dev_handle, p_dev->dev_status, + p_dev->link_spec); /* Clear the queues */ fixed_queue_flush(p_dev->uhid.get_rpt_id_queue, osi_free); @@ -551,8 +542,7 @@ void bta_hh_co_data(uint8_t dev_handle, uint8_t* p_rpt, uint16_t len) { // device creation is pending. if (p_dev->uhid.fd >= 0) { uint32_t polling_attempts = 0; - while (!p_dev->uhid.ready_for_data && - polling_attempts++ < BTIF_HH_MAX_POLLING_ATTEMPTS) { + while (!p_dev->uhid.ready_for_data && polling_attempts++ < BTIF_HH_MAX_POLLING_ATTEMPTS) { usleep(BTIF_HH_POLLING_SLEEP_DURATION_US); } } @@ -561,8 +551,8 @@ void bta_hh_co_data(uint8_t dev_handle, uint8_t* p_rpt, uint16_t len) { if ((p_dev->uhid.fd >= 0) && p_dev->uhid.ready_for_data) { bta_hh_co_write(p_dev->uhid.fd, p_rpt, len); } else { - log::warn("Error: fd = {}, ready {}, len = {}", p_dev->uhid.fd, - p_dev->uhid.ready_for_data, len); + log::warn("Error: fd = {}, ready {}, len = {}", p_dev->uhid.fd, p_dev->uhid.ready_for_data, + len); } } @@ -579,9 +569,8 @@ void bta_hh_co_data(uint8_t dev_handle, uint8_t* p_rpt, uint16_t len) { * * Returns void ******************************************************************************/ -void bta_hh_co_send_hid_info(btif_hh_device_t* p_dev, const char* dev_name, - uint16_t vendor_id, uint16_t product_id, - uint16_t version, uint8_t ctry_code, int dscp_len, +void bta_hh_co_send_hid_info(btif_hh_device_t* p_dev, const char* dev_name, uint16_t vendor_id, + uint16_t product_id, uint16_t version, uint8_t ctry_code, int dscp_len, uint8_t* p_dscp) { int result; struct uhid_event ev; @@ -591,12 +580,11 @@ void bta_hh_co_send_hid_info(btif_hh_device_t* p_dev, const char* dev_name, return; } - log::warn("fd = {}, name = [{}], dscp_len = {}", p_dev->uhid.fd, dev_name, - dscp_len); + log::warn("fd = {}, name = [{}], dscp_len = {}", p_dev->uhid.fd, dev_name, dscp_len); log::warn( - "vendor_id = 0x{:04x}, product_id = 0x{:04x}, version= " - "0x{:04x},ctry_code=0x{:02x}", - vendor_id, product_id, version, ctry_code); + "vendor_id = 0x{:04x}, product_id = 0x{:04x}, version= " + "0x{:04x},ctry_code=0x{:02x}", + vendor_id, product_id, version, ctry_code); // Create and send hid descriptor to kernel memset(&ev, 0, sizeof(ev)); @@ -622,8 +610,8 @@ void bta_hh_co_send_hid_info(btif_hh_device_t* p_dev, const char* dev_name, ev.u.create.country = ctry_code; result = uhid_write(p_dev->uhid.fd, &ev); - log::warn("wrote descriptor to fd = {}, dscp_len = {}, result = {}", - p_dev->uhid.fd, dscp_len, result); + log::warn("wrote descriptor to fd = {}, dscp_len = {}, result = {}", p_dev->uhid.fd, dscp_len, + result); if (result) { log::warn("Error: failed to send DSCP, result = {}", result); @@ -665,8 +653,7 @@ void bta_hh_co_set_rpt_rsp(uint8_t dev_handle, uint8_t status) { return; } - uint32_t* context = - (uint32_t*)fixed_queue_try_dequeue(p_dev->uhid.set_rpt_id_queue); + uint32_t* context = (uint32_t*)fixed_queue_try_dequeue(p_dev->uhid.set_rpt_id_queue); if (context == nullptr) { log::warn("No pending UHID_SET_REPORT"); @@ -674,13 +661,15 @@ void bta_hh_co_set_rpt_rsp(uint8_t dev_handle, uint8_t status) { } struct uhid_event ev = { - .type = UHID_SET_REPORT_REPLY, - .u = { - .set_report_reply = { - .id = *context, - .err = status, - }, - }, + .type = UHID_SET_REPORT_REPLY, + .u = + { + .set_report_reply = + { + .id = *context, + .err = status, + }, + }, }; uhid_write(p_dev->uhid.fd, &ev); osi_free(context); @@ -700,8 +689,7 @@ void bta_hh_co_set_rpt_rsp(uint8_t dev_handle, uint8_t status) { * Returns void. * ******************************************************************************/ -void bta_hh_co_get_rpt_rsp(uint8_t dev_handle, uint8_t status, - const uint8_t* p_rpt, uint16_t len) { +void bta_hh_co_get_rpt_rsp(uint8_t dev_handle, uint8_t status, const uint8_t* p_rpt, uint16_t len) { btif_hh_device_t* p_dev; log::verbose("dev_handle = {}, status = {}", dev_handle, status); @@ -723,8 +711,7 @@ void bta_hh_co_get_rpt_rsp(uint8_t dev_handle, uint8_t status, return; } - uint32_t* context = - (uint32_t*)fixed_queue_try_dequeue(p_dev->uhid.get_rpt_id_queue); + uint32_t* context = (uint32_t*)fixed_queue_try_dequeue(p_dev->uhid.get_rpt_id_queue); if (context == nullptr) { log::warn("No pending UHID_GET_REPORT"); @@ -737,14 +724,16 @@ void bta_hh_co_get_rpt_rsp(uint8_t dev_handle, uint8_t status, } struct uhid_event ev = { - .type = UHID_FEATURE_ANSWER, - .u = { - .feature_answer = { - .id = *context, - .err = status, - .size = len, - }, - }, + .type = UHID_FEATURE_ANSWER, + .u = + { + .feature_answer = + { + .id = *context, + .err = status, + .size = len, + }, + }, }; memcpy(ev.u.feature_answer.data, p_rpt, len); @@ -768,8 +757,7 @@ void bta_hh_co_get_rpt_rsp(uint8_t dev_handle, uint8_t status, * Returns void. * ******************************************************************************/ -void bta_hh_le_co_rpt_info(const tAclLinkSpec& link_spec, - tBTA_HH_RPT_CACHE_ENTRY* p_entry, +void bta_hh_le_co_rpt_info(const tAclLinkSpec& link_spec, tBTA_HH_RPT_CACHE_ENTRY* p_entry, uint8_t /* app_id */) { unsigned idx = 0; @@ -778,18 +766,15 @@ void bta_hh_le_co_rpt_info(const tAclLinkSpec& link_spec, size_t len = btif_config_get_bin_length(bdstr, BTIF_STORAGE_KEY_HOGP_REPORT); if (len >= sizeof(tBTA_HH_RPT_CACHE_ENTRY) && len <= sizeof(sReportCache)) { - btif_config_get_bin(bdstr, BTIF_STORAGE_KEY_HOGP_REPORT, - (uint8_t*)sReportCache, &len); + btif_config_get_bin(bdstr, BTIF_STORAGE_KEY_HOGP_REPORT, (uint8_t*)sReportCache, &len); idx = len / sizeof(tBTA_HH_RPT_CACHE_ENTRY); } if (idx < BTA_HH_NV_LOAD_MAX) { memcpy(&sReportCache[idx++], p_entry, sizeof(tBTA_HH_RPT_CACHE_ENTRY)); - btif_config_set_bin(bdstr, BTIF_STORAGE_KEY_HOGP_REPORT, - (const uint8_t*)sReportCache, + btif_config_set_bin(bdstr, BTIF_STORAGE_KEY_HOGP_REPORT, (const uint8_t*)sReportCache, idx * sizeof(tBTA_HH_RPT_CACHE_ENTRY)); - btif_config_set_int(bdstr, BTIF_STORAGE_KEY_HOGP_REPORT_VERSION, - BTA_HH_CACHE_REPORT_VERSION); + btif_config_set_int(bdstr, BTIF_STORAGE_KEY_HOGP_REPORT_VERSION, BTA_HH_CACHE_REPORT_VERSION); log::verbose("Saving report; dev={}, idx={}", link_spec, idx); } } @@ -810,22 +795,23 @@ void bta_hh_le_co_rpt_info(const tAclLinkSpec& link_spec, * Returns the cached report array * ******************************************************************************/ -tBTA_HH_RPT_CACHE_ENTRY* bta_hh_le_co_cache_load(const tAclLinkSpec& link_spec, - uint8_t* p_num_rpt, +tBTA_HH_RPT_CACHE_ENTRY* bta_hh_le_co_cache_load(const tAclLinkSpec& link_spec, uint8_t* p_num_rpt, uint8_t app_id) { std::string addrstr = link_spec.addrt.bda.ToString(); const char* bdstr = addrstr.c_str(); size_t len = btif_config_get_bin_length(bdstr, BTIF_STORAGE_KEY_HOGP_REPORT); - if (!p_num_rpt || len < sizeof(tBTA_HH_RPT_CACHE_ENTRY)) return NULL; + if (!p_num_rpt || len < sizeof(tBTA_HH_RPT_CACHE_ENTRY)) { + return NULL; + } - if (len > sizeof(sReportCache)) len = sizeof(sReportCache); - btif_config_get_bin(bdstr, BTIF_STORAGE_KEY_HOGP_REPORT, - (uint8_t*)sReportCache, &len); + if (len > sizeof(sReportCache)) { + len = sizeof(sReportCache); + } + btif_config_get_bin(bdstr, BTIF_STORAGE_KEY_HOGP_REPORT, (uint8_t*)sReportCache, &len); int cache_version = -1; - btif_config_get_int(bdstr, BTIF_STORAGE_KEY_HOGP_REPORT_VERSION, - &cache_version); + btif_config_get_int(bdstr, BTIF_STORAGE_KEY_HOGP_REPORT_VERSION, &cache_version); if (cache_version != BTA_HH_CACHE_REPORT_VERSION) { bta_hh_le_co_reset_rpt_cache(link_spec, app_id); @@ -850,8 +836,7 @@ tBTA_HH_RPT_CACHE_ENTRY* bta_hh_le_co_cache_load(const tAclLinkSpec& link_spec, * Returns none * ******************************************************************************/ -void bta_hh_le_co_reset_rpt_cache(const tAclLinkSpec& link_spec, - uint8_t /* app_id */) { +void bta_hh_le_co_reset_rpt_cache(const tAclLinkSpec& link_spec, uint8_t /* app_id */) { std::string addrstr = link_spec.addrt.bda.ToString(); const char* bdstr = addrstr.c_str(); diff --git a/system/btif/co/bta_pan_co.cc b/system/btif/co/bta_pan_co.cc index b6d85ba3ff4..bdc0ac397bb 100644 --- a/system/btif/co/bta_pan_co.cc +++ b/system/btif/co/bta_pan_co.cc @@ -61,7 +61,7 @@ uint8_t bta_pan_co_init(uint8_t* q_level) { *q_level = 30; // return (BTA_PAN_RX_PULL | BTA_PAN_TX_PULL); - return (BTA_PAN_RX_PUSH_BUF | BTA_PAN_RX_PUSH | BTA_PAN_TX_PULL); + return BTA_PAN_RX_PUSH_BUF | BTA_PAN_RX_PUSH | BTA_PAN_TX_PULL; } /******************************************************************************* @@ -126,8 +126,7 @@ void bta_pan_co_tx_path(uint16_t handle, uint8_t app_id) { log::error("cannot find pan connection"); return; } else if (conn->state != PAN_STATE_OPEN) { - log::error("conn is not opened, conn:{}, conn->state:{}", fmt::ptr(conn), - conn->state); + log::error("conn is not opened, conn:{}, conn->state:{}", fmt::ptr(conn), conn->state); return; } @@ -135,16 +134,13 @@ void bta_pan_co_tx_path(uint16_t handle, uint8_t app_id) { /* read next data buffer from pan */ p_buf = bta_pan_ci_readbuf(handle, src, dst, &protocol, &ext, &forward); if (p_buf) { - log::verbose("calling btapp_tap_send, p_buf->len:{}, offset:{}", - p_buf->len, p_buf->offset); + log::verbose("calling btapp_tap_send, p_buf->len:{}, offset:{}", p_buf->len, p_buf->offset); if (is_empty_eth_addr(conn->eth_addr) && is_valid_bt_eth_addr(src)) { - log::verbose("pan bt peer addr: {} update its ethernet addr: {}", - conn->peer, src); + log::verbose("pan bt peer addr: {} update its ethernet addr: {}", conn->peer, src); conn->eth_addr = src; } - btpan_tap_send(btpan_cb.tap_fd, src, dst, protocol, - (char*)(p_buf + 1) + p_buf->offset, p_buf->len, ext, - forward); + btpan_tap_send(btpan_cb.tap_fd, src, dst, protocol, (char*)(p_buf + 1) + p_buf->offset, + p_buf->len, ext, forward); osi_free(p_buf); } @@ -184,7 +180,9 @@ void bta_pan_co_rx_path(uint16_t /* handle */, uint8_t /* app_id */) { void bta_pan_co_rx_flow(uint16_t handle, uint8_t /* app_id */, bool enable) { log::verbose("bta_pan_co_rx_flow, enabled:{}, not used", enable); btpan_conn_t* conn = btpan_find_conn_handle(handle); - if (!conn || conn->state != PAN_STATE_OPEN) return; + if (!conn || conn->state != PAN_STATE_OPEN) { + return; + } btpan_set_flow_control(enable); } diff --git a/system/btif/include/bta_av_co.h b/system/btif/include/bta_av_co.h index fa85a180368..e36379f26ce 100644 --- a/system/btif/include/bta_av_co.h +++ b/system/btif/include/bta_av_co.h @@ -24,7 +24,7 @@ * BTA AV codec callouts state. */ class BtaAvCoState { - public: +public: BtaAvCoState() = default; /** @@ -62,7 +62,7 @@ class BtaAvCoState { void Reset(); virtual ~BtaAvCoState() = default; - private: +private: // The current active peer BtaAvCoPeer* active_peer_; // Current codec configuration @@ -70,7 +70,7 @@ class BtaAvCoState { }; class BtaAvCo { - public: +public: BtaAvCo(bool content_protect_enabled, BtaAvCoPeerCache* bta_av_co_peer_bank) : peer_cache_(bta_av_co_peer_bank), content_protect_enabled_(content_protect_enabled), @@ -123,9 +123,8 @@ class BtaAvCo { * @param num_sources number of discovered Source SEPs * @param uuid_local local UUID */ - void ProcessDiscoveryResult(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_address, uint8_t num_seps, - uint8_t num_sinks, uint8_t num_sources, + void ProcessDiscoveryResult(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, + uint8_t num_seps, uint8_t num_sinks, uint8_t num_sources, uint16_t uuid_local); /** @@ -149,12 +148,9 @@ class BtaAvCo { * for the current codec configuration for the peer. * @return A2DP_SUCCESS on success, otherwise A2DP_FAIL */ - tA2DP_STATUS ProcessSourceGetConfig(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_address, - uint8_t* p_codec_info, - uint8_t* p_sep_info_idx, uint8_t seid, - uint8_t* p_num_protect, - uint8_t* p_protect_info); + tA2DP_STATUS ProcessSourceGetConfig(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, + uint8_t* p_codec_info, uint8_t* p_sep_info_idx, uint8_t seid, + uint8_t* p_num_protect, uint8_t* p_protect_info); /** * Process retrieved codec configuration and content protection from @@ -177,12 +173,9 @@ class BtaAvCo { * for the current codec configuration for the peer. * @return A2DP_SUCCESS on success, otherwise A2DP_FAIL */ - tA2DP_STATUS ProcessSinkGetConfig(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_address, - uint8_t* p_codec_info, - uint8_t* p_sep_info_idx, uint8_t seid, - uint8_t* p_num_protect, - uint8_t* p_protect_info); + tA2DP_STATUS ProcessSinkGetConfig(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, + uint8_t* p_codec_info, uint8_t* p_sep_info_idx, uint8_t seid, + uint8_t* p_num_protect, uint8_t* p_protect_info); /** * Process AVDTP Set Config to set the codec and content protection @@ -198,11 +191,9 @@ class BtaAvCo { * @param t_local_sep the local SEP: AVDT_TSEP_SRC or AVDT_TSEP_SNK * @param avdt_handle the AVDTP handle */ - void ProcessSetConfig(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_address, - const uint8_t* p_codec_info, uint8_t seid, - uint8_t num_protect, const uint8_t* p_protect_info, - uint8_t t_local_sep, uint8_t avdt_handle); + void ProcessSetConfig(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, + const uint8_t* p_codec_info, uint8_t seid, uint8_t num_protect, + const uint8_t* p_protect_info, uint8_t t_local_sep, uint8_t avdt_handle); /** * Process AVDTP Open when the stream connection is opened. @@ -211,8 +202,7 @@ class BtaAvCo { * @param peer_address the peer address * @param mtu the MTU of the connection */ - void ProcessOpen(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, - uint16_t mtu); + void ProcessOpen(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, uint16_t mtu); /** * Process AVDTP Close when the stream connection is closed. @@ -249,8 +239,7 @@ class BtaAvCo { * @param p_timestamp on return, set to the timestamp of the data packet * @return the next encoded data packet or nullptr if no encoded data to send */ - BT_HDR* GetNextSourceDataPacket(const uint8_t* p_codec_info, - uint32_t* p_timestamp); + BT_HDR* GetNextSourceDataPacket(const uint8_t* p_codec_info, uint32_t* p_timestamp); /** * An audio packet has been dropped. @@ -260,8 +249,7 @@ class BtaAvCo { * @param bta_av_handle the BTA AV handle to identify the peer * @param peer_address the peer address */ - void DataPacketWasDropped(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_address); + void DataPacketWasDropped(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address); /** * Process AVDTP Audio Delay when the initial delay report is received by @@ -271,8 +259,8 @@ class BtaAvCo { * @param peer_address the peer address * @param delay the reported delay in 1/10th of a millisecond */ - void ProcessAudioDelay(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_address, uint16_t delay); + void ProcessAudioDelay(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, + uint16_t delay); /** * Update the MTU of the audio data connection. @@ -281,8 +269,7 @@ class BtaAvCo { * @param peer_address the peer address * @param mtu the new MTU of the audio data connection */ - void UpdateMtu(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, - uint16_t mtu); + void UpdateMtu(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, uint16_t mtu); /** * Set the active peer. @@ -405,7 +392,7 @@ class BtaAvCo { */ BtaAvCoPeerCache* peer_cache_; - private: +private: /** * Reset the state. */ @@ -445,9 +432,8 @@ class BtaAvCo { * @param t_local_sep the profile for which the codec config needs to be * saved. */ - void SaveNewCodecConfig(BtaAvCoPeer* p_peer, const uint8_t* new_codec_config, - uint8_t num_protect, const uint8_t* p_protect_info, - const uint8_t t_local_sep); + void SaveNewCodecConfig(BtaAvCoPeer* p_peer, const uint8_t* new_codec_config, uint8_t num_protect, + const uint8_t* p_protect_info, const uint8_t t_local_sep); /** * Set the Over-The-Air preferred codec configuration. @@ -470,8 +456,8 @@ class BtaAvCo { * @return true on success, otherwise false */ bool SetCodecOtaConfig(BtaAvCoPeer* p_peer, const uint8_t* p_ota_codec_config, - uint8_t num_protect, const uint8_t* p_protect_info, - bool* p_restart_output, const uint8_t t_local_sep); + uint8_t num_protect, const uint8_t* p_protect_info, bool* p_restart_output, + const uint8_t t_local_sep); /** * Update all selectable Source codecs with the corresponding codec @@ -490,8 +476,7 @@ class BtaAvCo { * @param p_peer the peer Sink SEP to use * @return true if the codec is updated, otherwise false */ - bool UpdateSelectableSourceCodec(const A2dpCodecConfig& codec_config, - BtaAvCoPeer* p_peer); + bool UpdateSelectableSourceCodec(const A2dpCodecConfig& codec_config, BtaAvCoPeer* p_peer); /** * Update all selectable Sink codecs with the corresponding codec @@ -510,8 +495,7 @@ class BtaAvCo { * @param p_peer the peer Source SEP to use * @return true if the codec is updated, otherwise false */ - bool UpdateSelectableSinkCodec(const A2dpCodecConfig& codec_config, - BtaAvCoPeer* p_peer); + bool UpdateSelectableSinkCodec(const A2dpCodecConfig& codec_config, BtaAvCoPeer* p_peer); /** * Attempt to select Source codec configuration for a Sink peer. @@ -521,8 +505,8 @@ class BtaAvCo { * @return a pointer to the corresponding SEP Sink entry on success, * otnerwise nullptr */ - const BtaAvCoSep* AttemptSourceCodecSelection( - const A2dpCodecConfig& codec_config, BtaAvCoPeer* p_peer); + const BtaAvCoSep* AttemptSourceCodecSelection(const A2dpCodecConfig& codec_config, + BtaAvCoPeer* p_peer); /** * Attempt to select Sink codec configuration for a Source peer. @@ -532,8 +516,8 @@ class BtaAvCo { * @return a pointer to the corresponding SEP Source entry on success, * otnerwise nullptr */ - const BtaAvCoSep* AttemptSinkCodecSelection( - const A2dpCodecConfig& codec_config, BtaAvCoPeer* p_peer); + const BtaAvCoSep* AttemptSinkCodecSelection(const A2dpCodecConfig& codec_config, + BtaAvCoPeer* p_peer); /** * Let the HAL offload provider select codec configuration. @@ -548,9 +532,8 @@ class BtaAvCo { * Select the HAL proposed configuration. */ BtaAvCoSep* SelectProviderCodecConfiguration( - BtaAvCoPeer* p_peer, - const ::bluetooth::audio::a2dp::provider::a2dp_configuration& - provider_codec_config); + BtaAvCoPeer* p_peer, + const ::bluetooth::audio::a2dp::provider::a2dp_configuration& provider_codec_config); /** * Returns the state that needs to be accessed. diff --git a/system/btif/include/bta_av_co_peer.h b/system/btif/include/bta_av_co_peer.h index 7703c3033b4..9e0bcd1a3c3 100644 --- a/system/btif/include/bta_av_co_peer.h +++ b/system/btif/include/bta_av_co_peer.h @@ -24,11 +24,8 @@ #define BTA_AV_CO_NUM_ELEMENTS(__a) (sizeof(__a) / sizeof((__a)[0])) class BtaAvCoSep { - public: - BtaAvCoSep() - : sep_info_idx(0), seid(0), codec_caps{}, num_protect(0), protect_info{} { - Reset(); - } +public: + BtaAvCoSep() : sep_info_idx(0), seid(0), codec_caps{}, num_protect(0), protect_info{} { Reset(); } /** * Reset the state. @@ -49,7 +46,7 @@ class BtaAvCoSep { }; class BtaAvCoPeer { - public: +public: /** * Default constructor to initialize the state of the member variables. */ @@ -84,30 +81,28 @@ class BtaAvCoPeer { A2dpCodecs* GetCodecs() const { return codecs_; } bool ContentProtectActive() const { return content_protect_active_; } - void SetContentProtectActive(bool cp_active) { - content_protect_active_ = cp_active; - } + void SetContentProtectActive(bool cp_active) { content_protect_active_ = cp_active; } RawAddress addr; // Peer address BtaAvCoSep sinks[BTAV_A2DP_CODEC_INDEX_MAX]; // Supported sinks BtaAvCoSep sources[BTAV_A2DP_CODEC_INDEX_MAX]; // Supported sources - uint8_t num_sinks; // Total number of sinks at peer - uint8_t num_sources; // Total number of sources at peer - uint8_t num_seps; // Total number of SEPs at peer - uint8_t num_rx_sinks; // Number of received sinks - uint8_t num_rx_sources; // Number of received sources - uint8_t num_sup_sinks; // Number of supported sinks - uint8_t num_sup_sources; // Number of supported sources - const BtaAvCoSep* p_sink; // Currently selected sink - const BtaAvCoSep* p_source; // Currently selected source - uint8_t codec_config[AVDT_CODEC_SIZE]; // Current codec configuration - bool acceptor; // True if acceptor - bool reconfig_needed; // True if reconfiguration is needed - bool opened; // True if opened - uint16_t mtu; // Maximum Transmit Unit size - uint16_t uuid_to_connect; // UUID of peer device - - private: + uint8_t num_sinks; // Total number of sinks at peer + uint8_t num_sources; // Total number of sources at peer + uint8_t num_seps; // Total number of SEPs at peer + uint8_t num_rx_sinks; // Number of received sinks + uint8_t num_rx_sources; // Number of received sources + uint8_t num_sup_sinks; // Number of supported sinks + uint8_t num_sup_sources; // Number of supported sources + const BtaAvCoSep* p_sink; // Currently selected sink + const BtaAvCoSep* p_source; // Currently selected source + uint8_t codec_config[AVDT_CODEC_SIZE]; // Current codec configuration + bool acceptor; // True if acceptor + bool reconfig_needed; // True if reconfiguration is needed + bool opened; // True if opened + uint16_t mtu; // Maximum Transmit Unit size + uint16_t uuid_to_connect; // UUID of peer device + +private: tBTA_AV_HNDL bta_av_handle_; // BTA AV handle to use A2dpCodecs* codecs_; // Locally supported codecs bool content_protect_active_; // True if Content Protect is active @@ -118,11 +113,11 @@ class BtaAvCoPeer { * It provides different APIs to retrieve the peer and update the peer data. */ class BtaAvCoPeerCache { - public: +public: BtaAvCoPeerCache() = default; - std::recursive_mutex codec_lock_; // Protect access to the codec state + std::recursive_mutex codec_lock_; // Protect access to the codec state std::vector codec_priorities_; // Configured - BtaAvCoPeer peers_[BTA_AV_NUM_STRS]; // Connected peer information + BtaAvCoPeer peers_[BTA_AV_NUM_STRS]; // Connected peer information /** * Inits the cache with the appropriate data. @@ -152,8 +147,7 @@ class BtaAvCoPeerCache { * @param codec_config the codec index to use * @return the peer Source SEP for the codec index if found, otherwise nullptr */ - BtaAvCoSep* FindPeerSource(BtaAvCoPeer* p_peer, - btav_a2dp_codec_index_t codec_index, + BtaAvCoSep* FindPeerSource(BtaAvCoPeer* p_peer, btav_a2dp_codec_index_t codec_index, const uint8_t content_protect_flag); /** @@ -163,8 +157,7 @@ class BtaAvCoPeerCache { * @param codec_index the codec index to use * @return the peer Sink SEP for the codec index if found, otherwise nullptr */ - BtaAvCoSep* FindPeerSink(BtaAvCoPeer* p_peer, - btav_a2dp_codec_index_t codec_index, + BtaAvCoSep* FindPeerSink(BtaAvCoPeer* p_peer, btav_a2dp_codec_index_t codec_index, const uint8_t content_protect_flag); /** @@ -183,8 +176,7 @@ class BtaAvCoPeerCache { * @param peer_address the peer address * @return the peer entry if found, otherwise nullptr */ - BtaAvCoPeer* FindPeerAndUpdate(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_address); + BtaAvCoPeer* FindPeerAndUpdate(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address); /** * Find the peer UUID for a given BTA AV handle. @@ -222,5 +214,4 @@ bool AudioProtectHasScmst(uint8_t num_protect, const uint8_t* p_protect_info); * @return true if the peer SEP has content protection enabled, * otherwise false */ -bool AudioSepHasContentProtection(const BtaAvCoSep* p_sep, - const uint8_t content_protect_flag); +bool AudioSepHasContentProtection(const BtaAvCoSep* p_sep, const uint8_t content_protect_flag); diff --git a/system/btif/include/btif_a2dp.h b/system/btif/include/btif_a2dp.h index 24aacb8deb6..c7cd3681356 100644 --- a/system/btif/include/btif_a2dp.h +++ b/system/btif/include/btif_a2dp.h @@ -27,8 +27,7 @@ #include "types/raw_address.h" // Process 'idle' request from the BTIF state machine during initialization. -void btif_a2dp_on_idle(const RawAddress& peer_addr, - const A2dpType local_a2dp_type); +void btif_a2dp_on_idle(const RawAddress& peer_addr, const A2dpType local_a2dp_type); // Process 'start' request from the BTIF state machine to prepare for A2DP // streaming. @@ -36,24 +35,21 @@ void btif_a2dp_on_idle(const RawAddress& peer_addr, // |p_av_start| is the data associated with the request - see |tBTA_AV_START|. // |local_a2dp_type| type of local a2dp profile. // Returns true if an ACK for the local command was sent, otherwise false. -bool btif_a2dp_on_started(const RawAddress& peer_addr, - tBTA_AV_START* p_av_start, +bool btif_a2dp_on_started(const RawAddress& peer_addr, tBTA_AV_START* p_av_start, const A2dpType local_a2dp_type); // Process 'stop' request from the BTIF state machine to stop A2DP streaming. // |p_av_suspend| is the data associated with the request - see // |tBTA_AV_SUSPEND|. // |local_a2dp_type| type of local a2dp profile. -void btif_a2dp_on_stopped(tBTA_AV_SUSPEND* p_av_suspend, - const A2dpType local_a2dp_type); +void btif_a2dp_on_stopped(tBTA_AV_SUSPEND* p_av_suspend, const A2dpType local_a2dp_type); // Process 'suspend' request from the BTIF state machine to suspend A2DP // streaming. // |p_av_suspend| is the data associated with the request - see // |tBTA_AV_SUSPEND|. // |local_a2dp_type| type of local a2dp profile. -void btif_a2dp_on_suspended(tBTA_AV_SUSPEND* p_av_suspend, - const A2dpType local_a2dp_type); +void btif_a2dp_on_suspended(tBTA_AV_SUSPEND* p_av_suspend, const A2dpType local_a2dp_type); // Process 'offload start' request from the BTIF state machine to start // offloading of the A2DP streaming. @@ -61,8 +57,7 @@ void btif_a2dp_on_suspended(tBTA_AV_SUSPEND* p_av_suspend, // |status| is the processing status of the request prior to this call. // The value can be |BTA_AV_SUCCESS| if the processing has been successful // so far, or |BTA_AV_FAIL*| if the request has already failed. -void btif_a2dp_on_offload_started(const RawAddress& peer_addr, - tBTA_AV_STATUS status); +void btif_a2dp_on_offload_started(const RawAddress& peer_addr, tBTA_AV_STATUS status); // Dump debug-related information for the A2DP module. // |fd| is the file descriptor to use for writing the ASCII formatted diff --git a/system/btif/include/btif_a2dp_sink.h b/system/btif/include/btif_a2dp_sink.h index e977d406b25..ef340a5b53e 100644 --- a/system/btif/include/btif_a2dp_sink.h +++ b/system/btif/include/btif_a2dp_sink.h @@ -131,12 +131,11 @@ void btif_a2dp_sink_set_focus_state_req(btif_a2dp_sink_focus_state_t state); void btif_a2dp_sink_set_audio_track_gain(float gain); // Get audio track handle -void * btif_a2dp_sink_get_audio_track(void); +void* btif_a2dp_sink_get_audio_track(void); namespace fmt { template <> -struct formatter - : enum_formatter {}; +struct formatter : enum_formatter {}; } // namespace fmt #endif /* BTIF_A2DP_SINK_H */ diff --git a/system/btif/include/btif_a2dp_source.h b/system/btif/include/btif_a2dp_source.h index df20319ebe9..0e32a3bde69 100644 --- a/system/btif/include/btif_a2dp_source.h +++ b/system/btif/include/btif_a2dp_source.h @@ -92,16 +92,15 @@ void btif_a2dp_source_stop_audio_req(void); // The peer address is |peer_addr|. // |codec_user_config| contains the preferred codec user configuration. void btif_a2dp_source_encoder_user_config_update_req( - const RawAddress& peer_addr, - const std::vector& codec_user_preferences, - std::promise peer_ready_promise); + const RawAddress& peer_addr, + const std::vector& codec_user_preferences, + std::promise peer_ready_promise); // Process a request to update the A2DP audio encoding with new audio // configuration feeding parameters stored in |codec_audio_config|. // The fields that are used are: |codec_audio_config.sample_rate|, // |codec_audio_config.bits_per_sample| and |codec_audio_config.channel_mode|. -void btif_a2dp_source_feeding_update_req( - const btav_a2dp_codec_config_t& codec_audio_config); +void btif_a2dp_source_feeding_update_req(const btav_a2dp_codec_config_t& codec_audio_config); // Process 'idle' request from the BTIF state machine during initialization. void btif_a2dp_source_on_idle(void); @@ -131,7 +130,6 @@ BT_HDR* btif_a2dp_source_audio_readbuf(void); void btif_a2dp_source_debug_dump(int fd); // Set the dynamic audio buffer size -void btif_a2dp_source_set_dynamic_audio_buffer_size( - uint8_t dynamic_audio_buffer_size); +void btif_a2dp_source_set_dynamic_audio_buffer_size(uint8_t dynamic_audio_buffer_size); #endif /* BTIF_A2DP_SOURCE_H */ diff --git a/system/btif/include/btif_api.h b/system/btif/include/btif_api.h index b01d4643f30..1c05c99ec25 100644 --- a/system/btif/include/btif_api.h +++ b/system/btif/include/btif_api.h @@ -177,8 +177,7 @@ void btif_set_adapter_property(bt_property_t* property); * Description Fetches the remote device property from the NVRAM * ******************************************************************************/ -void btif_get_remote_device_property(RawAddress remote_addr, - bt_property_type_t type); +void btif_get_remote_device_property(RawAddress remote_addr, bt_property_type_t type); /******************************************************************************* * @@ -198,8 +197,7 @@ void btif_get_remote_device_properties(RawAddress remote_addr); * remote device property that can be set * ******************************************************************************/ -void btif_set_remote_device_property(RawAddress* remote_addr, - bt_property_t* property); +void btif_set_remote_device_property(RawAddress* remote_addr, bt_property_t* property); /******************************************************************************* * BTIF DM API @@ -249,10 +247,8 @@ void btif_dm_create_bond_le(const RawAddress bd_addr, uint8_t addr_type); * Description Initiate bonding with the specified device using OOB data. * ******************************************************************************/ -void btif_dm_create_bond_out_of_band(const RawAddress bd_addr, - tBT_TRANSPORT transport, - const bt_oob_data_t p192_data, - const bt_oob_data_t p256_data); +void btif_dm_create_bond_out_of_band(const RawAddress bd_addr, tBT_TRANSPORT transport, + const bt_oob_data_t p192_data, const bt_oob_data_t p256_data); /******************************************************************************* * @@ -305,8 +301,8 @@ uint16_t btif_dm_get_connection_state_sync(const RawAddress& bd_addr); * Description BT legacy pairing - PIN code reply * ******************************************************************************/ -void btif_dm_pin_reply(const RawAddress bd_addr, uint8_t accept, - uint8_t pin_len, bt_pin_code_t pin_code); +void btif_dm_pin_reply(const RawAddress bd_addr, uint8_t accept, uint8_t pin_len, + bt_pin_code_t pin_code); /******************************************************************************* * @@ -317,8 +313,7 @@ void btif_dm_pin_reply(const RawAddress bd_addr, uint8_t accept, * Returns bt_status_t * ******************************************************************************/ -bt_status_t btif_dm_passkey_reply(const RawAddress* bd_addr, uint8_t accept, - uint32_t passkey); +bt_status_t btif_dm_passkey_reply(const RawAddress* bd_addr, uint8_t accept, uint32_t passkey); /******************************************************************************* * @@ -328,8 +323,7 @@ bt_status_t btif_dm_passkey_reply(const RawAddress* bd_addr, uint8_t accept, * Entry * ******************************************************************************/ -void btif_dm_ssp_reply(const RawAddress bd_addr, bt_ssp_variant_t variant, - uint8_t accept); +void btif_dm_ssp_reply(const RawAddress bd_addr, bt_ssp_variant_t variant, uint8_t accept); /******************************************************************************* * @@ -374,8 +368,7 @@ bool btif_is_dut_mode(); ******************************************************************************/ void btif_dut_mode_send(uint16_t opcode, uint8_t* buf, uint8_t len); -void btif_ble_transmitter_test(uint8_t tx_freq, uint8_t test_data_len, - uint8_t packet_payload); +void btif_ble_transmitter_test(uint8_t tx_freq, uint8_t test_data_len, uint8_t packet_payload); void btif_ble_receiver_test(uint8_t rx_freq); void btif_ble_test_end(); diff --git a/system/btif/include/btif_av.h b/system/btif/include/btif_av.h index c6366eb1a85..b8f4d4e7f71 100644 --- a/system/btif/include/btif_av.h +++ b/system/btif/include/btif_av.h @@ -31,25 +31,21 @@ /* Interface methods for the A2DP source stack. */ -bt_status_t btif_av_source_init( - btav_source_callbacks_t* callbacks, int max_connected_audio_devices, - const std::vector& codec_priorities, - const std::vector& offloading_preference, - std::vector* supported_codecs); +bt_status_t btif_av_source_init(btav_source_callbacks_t* callbacks, int max_connected_audio_devices, + const std::vector& codec_priorities, + const std::vector& offloading_preference, + std::vector* supported_codecs); bt_status_t btif_av_source_connect(const RawAddress& peer_address); bt_status_t btif_av_source_disconnect(const RawAddress& peer_address); -bt_status_t btif_av_source_set_silence_device(const RawAddress& peer_address, - bool silence); +bt_status_t btif_av_source_set_silence_device(const RawAddress& peer_address, bool silence); bt_status_t btif_av_source_set_active_device(const RawAddress& peer_address); bt_status_t btif_av_source_set_codec_config_preference( - const RawAddress& peer_address, - std::vector codec_preferences); + const RawAddress& peer_address, std::vector codec_preferences); void btif_av_source_cleanup(); /* Interface methods for the A2DP sink stack. */ -bt_status_t btif_av_sink_init(btav_sink_callbacks_t* callbacks, - int max_connected_audio_devices); +bt_status_t btif_av_sink_init(btav_sink_callbacks_t* callbacks, int max_connected_audio_devices); bt_status_t btif_av_sink_connect(const RawAddress& peer_address); bt_status_t btif_av_sink_disconnect(const RawAddress& peer_address); void btif_av_sink_cleanup(); @@ -153,8 +149,7 @@ void btif_av_clear_remote_suspend_flag(const A2dpType local_a2dp_type); * @param local_a2dp_type type of local a2dp profile. * @return true if the remote peer is capable of EDR */ -bool btif_av_is_peer_edr(const RawAddress& peer_address, - const A2dpType local_a2dp_type); +bool btif_av_is_peer_edr(const RawAddress& peer_address, const A2dpType local_a2dp_type); /** * Check whether the connected A2DP peer supports 3 Mbps EDR. @@ -166,8 +161,7 @@ bool btif_av_is_peer_edr(const RawAddress& peer_address, * @param local_a2dp_type type of local a2dp profile. * @return true if the remote peer is capable of EDR and supports 3 Mbps */ -bool btif_av_peer_supports_3mbps(const RawAddress& peer_address, - const A2dpType local_a2dp_type); +bool btif_av_peer_supports_3mbps(const RawAddress& peer_address, const A2dpType local_a2dp_type); /** * Check whether the mandatory codec is more preferred for this peer. @@ -189,11 +183,9 @@ bool btif_av_peer_prefers_mandatory_codec(const RawAddress& peer_address, * to report */ void btif_av_report_source_codec_state( - const RawAddress& peer_address, - const btav_a2dp_codec_config_t& codec_config, - const std::vector& codecs_local_capabilities, - const std::vector& - codecs_selectable_capabilities); + const RawAddress& peer_address, const btav_a2dp_codec_config_t& codec_config, + const std::vector& codecs_local_capabilities, + const std::vector& codecs_selectable_capabilities); /** * Initialize / shut down the A2DP Source service. @@ -217,8 +209,7 @@ bt_status_t btif_av_sink_execute_service(bool enable); * @param peer_address the disconnected peer address * @param local_a2dp_type type of local a2dp profile. */ -void btif_av_acl_disconnected(const RawAddress& peer_address, - const A2dpType local_a2dp_type); +void btif_av_acl_disconnected(const RawAddress& peer_address, const A2dpType local_a2dp_type); /** * Dump debug-related information for the BTIF AV module. @@ -271,8 +262,7 @@ bool btif_av_is_peer_silenced(const RawAddress& peer_address); * @param local_a2dp_type type of local a2dp profile. * */ -bool btif_av_is_connected_addr(const RawAddress& peer_address, - const A2dpType local_a2dp_type); +bool btif_av_is_connected_addr(const RawAddress& peer_address, const A2dpType local_a2dp_type); /** * Set the dynamic audio buffer size @@ -293,8 +283,7 @@ void btif_av_set_low_latency(bool is_low_latency); * @param handle bta handle * @param peer_addr peer address */ -void btif_av_connect_sink_delayed(uint8_t handle, - const RawAddress& peer_address); +void btif_av_connect_sink_delayed(uint8_t handle, const RawAddress& peer_address); /** * Check whether A2DP Source is enabled. diff --git a/system/btif/include/btif_av_co.h b/system/btif/include/btif_av_co.h index df8d371419e..c0c49bfb278 100644 --- a/system/btif/include/btif_av_co.h +++ b/system/btif/include/btif_av_co.h @@ -61,23 +61,21 @@ const tA2DP_ENCODER_INTERFACE* bta_av_co_get_encoder_interface(void); // |codec_user_config| contains the preferred codec configuration. // |restart_output| is used to know whether AV is reconfiguring with remote. // Returns true on success, otherwise false. -bool bta_av_co_set_codec_user_config( - const RawAddress& peer_addr, - const btav_a2dp_codec_config_t& codec_user_config, bool* p_restart_output); +bool bta_av_co_set_codec_user_config(const RawAddress& peer_addr, + const btav_a2dp_codec_config_t& codec_user_config, + bool* p_restart_output); // Sets the Audio HAL selected audio feeding parameters. // Those parameters are applied only to the currently selected codec. // |codec_audio_config| contains the selected audio feeding configuration. // Returns true on success, otherwise false. -bool bta_av_co_set_codec_audio_config( - const btav_a2dp_codec_config_t& codec_audio_config); +bool bta_av_co_set_codec_audio_config(const btav_a2dp_codec_config_t& codec_audio_config); // Initializes the control block. // |codec_priorities| contains the A2DP Source codec priorities to use. // |supported_codecs| returns the list of supported A2DP Source codecs. -void bta_av_co_init( - const std::vector& codec_priorities, - std::vector* supported_codecs); +void bta_av_co_init(const std::vector& codec_priorities, + std::vector* supported_codecs); // Checks whether the codec for |codec_index| is supported. // Returns true if the codec is supported, otherwise false. @@ -91,8 +89,7 @@ A2dpCodecConfig* bta_av_get_a2dp_current_codec(void); // Gets the current A2DP codec for a peer identified by |peer_address|. // Returns a pointer to the current |A2dpCodecConfig| if valid, otherwise // nullptr. -A2dpCodecConfig* bta_av_get_a2dp_peer_current_codec( - const RawAddress& peer_address); +A2dpCodecConfig* bta_av_get_a2dp_peer_current_codec(const RawAddress& peer_address); // Gets the A2DP effective frame size from the current encoder. // Returns the effective frame size if the encoder is configured, otherwise 0. diff --git a/system/btif/include/btif_avrcp_audio_track.h b/system/btif/include/btif_avrcp_audio_track.h index eeca1c8b8f2..5ea8d5e6822 100644 --- a/system/btif/include/btif_avrcp_audio_track.h +++ b/system/btif/include/btif_avrcp_audio_track.h @@ -35,8 +35,7 @@ * should eventually be * deleted using BtifAvrcpAudioTrackDelete (see below). */ -void* BtifAvrcpAudioTrackCreate(int trackFreq, int bitsPerSample, - int channelCount); +void* BtifAvrcpAudioTrackCreate(int trackFreq, int bitsPerSample, int channelCount); /** * Starts the audio track. @@ -65,5 +64,4 @@ void BtifAvrcpAudioTrackDelete(void* handle); * * Used only for debugging. */ -int BtifAvrcpAudioTrackWriteData(void* handle, void* audioBuffer, - int bufferLength); +int BtifAvrcpAudioTrackWriteData(void* handle, void* audioBuffer, int bufferLength); diff --git a/system/btif/include/btif_bqr.h b/system/btif/include/btif_bqr.h index bafce34b0db..716ab681f73 100644 --- a/system/btif/include/btif_bqr.h +++ b/system/btif/include/btif_bqr.h @@ -96,14 +96,14 @@ static constexpr uint32_t kQualityEventMaskBtSchedulingTrace = 0x1 << 17; static constexpr uint32_t kQualityEventMaskControllerDbgInfo = 0x1 << 18; static constexpr uint32_t kQualityEventMaskVendorSpecificTrace = 0x1 << 31; static constexpr uint32_t kQualityEventMaskAll = - kQualityEventMaskMonitorMode | kQualityEventMaskApproachLsto | - kQualityEventMaskA2dpAudioChoppy | kQualityEventMaskScoVoiceChoppy | - kQualityEventMaskRootInflammation | kQualityEventMaskEnergyMonitoring | - kQualityEventMaskLeAudioChoppy | kQualityEventMaskConnectFail | - kQualityEventMaskAdvRFStatsEvent | kQualityEventMaskAdvRFStatsMonitor | - kQualityEventMaskVendorSpecificQuality | kQualityEventMaskLmpMessageTrace | - kQualityEventMaskBtSchedulingTrace | kQualityEventMaskControllerDbgInfo | - kQualityEventMaskVendorSpecificTrace; + kQualityEventMaskMonitorMode | kQualityEventMaskApproachLsto | + kQualityEventMaskA2dpAudioChoppy | kQualityEventMaskScoVoiceChoppy | + kQualityEventMaskRootInflammation | kQualityEventMaskEnergyMonitoring | + kQualityEventMaskLeAudioChoppy | kQualityEventMaskConnectFail | + kQualityEventMaskAdvRFStatsEvent | kQualityEventMaskAdvRFStatsMonitor | + kQualityEventMaskVendorSpecificQuality | kQualityEventMaskLmpMessageTrace | + kQualityEventMaskBtSchedulingTrace | kQualityEventMaskControllerDbgInfo | + kQualityEventMaskVendorSpecificTrace; // Define the minimum time interval (in ms) of quality event reporting for the // selected quality event(s). Controller Firmware should not report the next // event within the defined Minimum Report Interval * Report Interval @@ -141,38 +141,33 @@ static constexpr uint8_t kCriWarnUnusedCh = 55; // The queue size of recording the BQR events. static constexpr uint8_t kBqrEventQueueSize = 25; // The Property of BQR event mask configuration. -static constexpr const char* kpPropertyEventMask = - "persist.bluetooth.bqr.event_mask"; +static constexpr const char* kpPropertyEventMask = "persist.bluetooth.bqr.event_mask"; // The Property of BQR Vendor Quality configuration. -static constexpr const char* kpPropertyVndQualityMask = - "persist.bluetooth.bqr.vnd_quality_mask"; +static constexpr const char* kpPropertyVndQualityMask = "persist.bluetooth.bqr.vnd_quality_mask"; // The Property of BQR Vendor Trace configuration. -static constexpr const char* kpPropertyVndTraceMask = - "persist.bluetooth.bqr.vnd_trace_mask"; +static constexpr const char* kpPropertyVndTraceMask = "persist.bluetooth.bqr.vnd_trace_mask"; // The Property of BQR minimum report interval configuration. static constexpr const char* kpPropertyMinReportIntervalMs = - "persist.bluetooth.bqr.min_interval_ms"; + "persist.bluetooth.bqr.min_interval_ms"; // The Property of BQR minimum report interval multiple. -static constexpr const char* kpPropertyIntervalMultiple = - "persist.bluetooth.bqr.interval_multiple"; +static constexpr const char* kpPropertyIntervalMultiple = "persist.bluetooth.bqr.interval_multiple"; // Path of the LMP/LL message trace log file. static constexpr const char* kpLmpLlMessageTraceLogPath = - "/data/misc/bluetooth/logs/lmp_ll_message_trace.log"; + "/data/misc/bluetooth/logs/lmp_ll_message_trace.log"; // Path of the last LMP/LL message trace log file. static constexpr const char* kpLmpLlMessageTraceLastLogPath = - "/data/misc/bluetooth/logs/lmp_ll_message_trace.log.last"; + "/data/misc/bluetooth/logs/lmp_ll_message_trace.log.last"; // Path of the Bluetooth Multi-profile/Coex scheduling trace log file. static constexpr const char* kpBtSchedulingTraceLogPath = - "/data/misc/bluetooth/logs/bt_scheduling_trace.log"; + "/data/misc/bluetooth/logs/bt_scheduling_trace.log"; // Path of the last Bluetooth Multi-profile/Coex scheduling trace log file. static constexpr const char* kpBtSchedulingTraceLastLogPath = - "/data/misc/bluetooth/logs/bt_scheduling_trace.log.last"; + "/data/misc/bluetooth/logs/bt_scheduling_trace.log.last"; // The Property of BQR a2dp choppy report and sco choppy report thresholds. // A2dp choppy will be reported only when a2dp choppy times is >= // a2dp_choppy_threshold. The default value in firmware side is 1. It is same // for sco choppy. Value format is a2dp_choppy_threshold,sco_choppy_threshold -static constexpr const char* kpPropertyChoppyThreshold = - "persist.bluetooth.bqr.choppy_threshold"; +static constexpr const char* kpPropertyChoppyThreshold = "persist.bluetooth.bqr.choppy_threshold"; // File Descriptor of LMP/LL message trace log static int LmpLlMessageTraceLogFd = INVALID_FD; @@ -353,7 +348,7 @@ typedef struct { // BQR sub-event of Vendor Specific Event class BqrVseSubEvt { - public: +public: // Parse the Link Quality related BQR event. // // @param length Total length of all parameters contained in the sub-event. @@ -364,15 +359,13 @@ class BqrVseSubEvt { // @param fd The File Descriptor of the log file. // @param length Total length of all parameters contained in the sub-event. // @param p_param_buf A pointer to the parameters contained in the sub-event. - void WriteLmpLlTraceLogFile(int fd, uint8_t length, - const uint8_t* p_param_buf); + void WriteLmpLlTraceLogFile(int fd, uint8_t length, const uint8_t* p_param_buf); // Write the Bluetooth Multi-profile/Coex scheduling trace to the log file. // // @param fd The File Descriptor of the log file. // @param length Total length of all parameters contained in the sub-event. // @param p_param_buf A pointer to the parameters contained in the sub-event. - void WriteBtSchedulingTraceLogFile(int fd, uint8_t length, - const uint8_t* p_param_buf); + void WriteBtSchedulingTraceLogFile(int fd, uint8_t length, const uint8_t* p_param_buf); // Get a string representation of the Bluetooth Quality event. // // @return a string representation of the Bluetooth Quality event. diff --git a/system/btif/include/btif_common.h b/system/btif/include/btif_common.h index 2c8d2adf5a1..f0c838a401c 100644 --- a/system/btif/include/btif_common.h +++ b/system/btif/include/btif_common.h @@ -60,8 +60,7 @@ * problematic "char *" to struct pointer casting, and this macro itself should * be removed. */ -#define maybe_non_aligned_memcpy(_a, _b, _c) \ - memcpy((void*)(_a), (void*)(_b), (_c)) +#define maybe_non_aligned_memcpy(_a, _b, _c) memcpy((void*)(_a), (void*)(_b), (_c)) #define HAL_CBACK(P_CB, P_CBACK, ...) \ do { \ @@ -111,10 +110,10 @@ void post_on_bt_jni(BtJniClosure closure); template base::Callback jni_thread_wrapper(base::Callback cb) { return base::Bind( - [](base::Callback cb, Args... args) { - do_in_jni_thread(base::BindOnce(cb, std::forward(args)...)); - }, - std::move(cb)); + [](base::Callback cb, Args... args) { + do_in_jni_thread(base::BindOnce(cb, std::forward(args)...)); + }, + std::move(cb)); } tBTA_SERVICE_MASK btif_get_enabled_services_mask(void); @@ -126,53 +125,42 @@ int btif_is_enabled(void); * BTIF_Events */ void btif_enable_bluetooth_evt(); -void btif_adapter_properties_evt(bt_status_t status, uint32_t num_props, - bt_property_t* p_props); -void btif_remote_properties_evt(bt_status_t status, RawAddress* remote_addr, - uint32_t num_props, bt_property_t* p_props); +void btif_adapter_properties_evt(bt_status_t status, uint32_t num_props, bt_property_t* p_props); +void btif_remote_properties_evt(bt_status_t status, RawAddress* remote_addr, uint32_t num_props, + bt_property_t* p_props); void bte_load_did_conf(const char* p_path); -bt_status_t btif_transfer_context(tBTIF_CBACK* p_cback, uint16_t event, - char* p_params, int param_len, - tBTIF_COPY_CBACK* p_copy_cback); +bt_status_t btif_transfer_context(tBTIF_CBACK* p_cback, uint16_t event, char* p_params, + int param_len, tBTIF_COPY_CBACK* p_copy_cback); void btif_init_ok(); void invoke_adapter_state_changed_cb(bt_state_t state); void invoke_adapter_properties_cb(bt_status_t status, int num_properties, bt_property_t* properties); -void invoke_remote_device_properties_cb(bt_status_t status, RawAddress bd_addr, - int num_properties, +void invoke_remote_device_properties_cb(bt_status_t status, RawAddress bd_addr, int num_properties, bt_property_t* properties); void invoke_device_found_cb(int num_properties, bt_property_t* properties); void invoke_discovery_state_changed_cb(bt_discovery_state_t state); -void invoke_pin_request_cb(RawAddress bd_addr, bt_bdname_t bd_name, - uint32_t cod, bool min_16_digit); -void invoke_ssp_request_cb(RawAddress bd_addr, bt_ssp_variant_t pairing_variant, - uint32_t pass_key); -void invoke_oob_data_request_cb(tBT_TRANSPORT t, bool valid, Octet16 c, - Octet16 r, RawAddress raw_address, - uint8_t address_type); -void invoke_bond_state_changed_cb(bt_status_t status, RawAddress bd_addr, - bt_bond_state_t state, int fail_reason); -void invoke_address_consolidate_cb(RawAddress main_bd_addr, - RawAddress secondary_bd_addr); -void invoke_le_address_associate_cb(RawAddress main_bd_addr, - RawAddress secondary_bd_addr); -void invoke_acl_state_changed_cb(bt_status_t status, RawAddress bd_addr, - bt_acl_state_t state, int transport_link_type, - bt_hci_error_code_t hci_reason, - bt_conn_direction_t direction, - uint16_t acl_handle); +void invoke_pin_request_cb(RawAddress bd_addr, bt_bdname_t bd_name, uint32_t cod, + bool min_16_digit); +void invoke_ssp_request_cb(RawAddress bd_addr, bt_ssp_variant_t pairing_variant, uint32_t pass_key); +void invoke_oob_data_request_cb(tBT_TRANSPORT t, bool valid, Octet16 c, Octet16 r, + RawAddress raw_address, uint8_t address_type); +void invoke_bond_state_changed_cb(bt_status_t status, RawAddress bd_addr, bt_bond_state_t state, + int fail_reason); +void invoke_address_consolidate_cb(RawAddress main_bd_addr, RawAddress secondary_bd_addr); +void invoke_le_address_associate_cb(RawAddress main_bd_addr, RawAddress secondary_bd_addr); +void invoke_acl_state_changed_cb(bt_status_t status, RawAddress bd_addr, bt_acl_state_t state, + int transport_link_type, bt_hci_error_code_t hci_reason, + bt_conn_direction_t direction, uint16_t acl_handle); void invoke_thread_evt_cb(bt_cb_thread_evt event); void invoke_le_test_mode_cb(bt_status_t status, uint16_t count); -void invoke_energy_info_cb(bt_activity_energy_info energy_info, - bt_uid_traffic_t* uid_data); -void invoke_link_quality_report_cb( - uint64_t timestamp, int report_id, int rssi, int snr, - int retransmission_count, int packets_not_receive_count, - int negative_acknowledgement_count); +void invoke_energy_info_cb(bt_activity_energy_info energy_info, bt_uid_traffic_t* uid_data); +void invoke_link_quality_report_cb(uint64_t timestamp, int report_id, int rssi, int snr, + int retransmission_count, int packets_not_receive_count, + int negative_acknowledgement_count); void invoke_switch_buffer_size_cb(bool is_low_latency_buffer_size); void invoke_switch_codec_cb(bool is_low_latency_buffer_size); diff --git a/system/btif/include/btif_config.h b/system/btif/include/btif_config.h index 133f8539cc6..da98582f673 100644 --- a/system/btif/include/btif_config.h +++ b/system/btif/include/btif_config.h @@ -32,28 +32,23 @@ static const char BTIF_CONFIG_MODULE[] = "btif_config_module"; bool btif_config_exist(const std::string& section, const std::string& key); -bool btif_config_get_int(const std::string& section, const std::string& key, - int* value); -bool btif_config_set_int(const std::string& section, const std::string& key, - int value); -bool btif_config_get_uint64(const std::string& section, const std::string& key, - uint64_t* value); -bool btif_config_set_uint64(const std::string& section, const std::string& key, - uint64_t value); -bool btif_config_get_str(const std::string& section, const std::string& key, - char* value, int* size_bytes); +bool btif_config_get_int(const std::string& section, const std::string& key, int* value); +bool btif_config_set_int(const std::string& section, const std::string& key, int value); +bool btif_config_get_uint64(const std::string& section, const std::string& key, uint64_t* value); +bool btif_config_set_uint64(const std::string& section, const std::string& key, uint64_t value); +bool btif_config_get_str(const std::string& section, const std::string& key, char* value, + int* size_bytes); bool btif_config_set_str(const std::string& section, const std::string& key, const std::string& value); -bool btif_config_get_bin(const std::string& section, const std::string& key, - uint8_t* value, size_t* length); -bool btif_config_set_bin(const std::string& section, const std::string& key, - const uint8_t* value, size_t length); +bool btif_config_get_bin(const std::string& section, const std::string& key, uint8_t* value, + size_t* length); +bool btif_config_set_bin(const std::string& section, const std::string& key, const uint8_t* value, + size_t length); bool btif_config_remove(const std::string& section, const std::string& key); void btif_config_remove_device(const std::string& section); -size_t btif_config_get_bin_length(const std::string& section, - const std::string& key); +size_t btif_config_get_bin_length(const std::string& section, const std::string& key); std::vector btif_config_get_paired_devices(); diff --git a/system/btif/include/btif_debug_btsnoop.h b/system/btif/include/btif_debug_btsnoop.h index 4f6ad8fc731..ccb9e653208 100644 --- a/system/btif/include/btif_debug_btsnoop.h +++ b/system/btif/include/btif_debug_btsnoop.h @@ -36,4 +36,3 @@ typedef struct btsnooz_header_t { uint32_t delta_time_ms; uint8_t type; } __attribute__((__packed__)) btsnooz_header_t; - diff --git a/system/btif/include/btif_debug_conn.h b/system/btif/include/btif_debug_conn.h index 29b33357266..f436017c650 100644 --- a/system/btif/include/btif_debug_conn.h +++ b/system/btif/include/btif_debug_conn.h @@ -23,14 +23,10 @@ #include "gatt_api.h" #include "types/raw_address.h" -typedef enum { - BTIF_DEBUG_CONNECTED = 1, - BTIF_DEBUG_DISCONNECTED -} btif_debug_conn_state_t; +typedef enum { BTIF_DEBUG_CONNECTED = 1, BTIF_DEBUG_DISCONNECTED } btif_debug_conn_state_t; // Report a connection state change -void btif_debug_conn_state(const RawAddress& bda, - const btif_debug_conn_state_t state, +void btif_debug_conn_state(const RawAddress& bda, const btif_debug_conn_state_t state, const tGATT_DISCONN_REASON disconnect_reason); void btif_debug_conn_dump(int fd); diff --git a/system/btif/include/btif_dm.h b/system/btif/include/btif_dm.h index 05bae2ba2ac..32cb7cd24df 100644 --- a/system/btif/include/btif_dm.h +++ b/system/btif/include/btif_dm.h @@ -76,8 +76,8 @@ void btif_dm_proc_io_req(tBTM_AUTH_REQ* p_auth_req, bool is_orig); /** * Callout for handling io_capabilities response */ -void btif_dm_proc_io_rsp(const RawAddress& bd_addr, tBTM_IO_CAP io_cap, - tBTM_OOB_DATA oob_data, tBTM_AUTH_REQ auth_req); +void btif_dm_proc_io_rsp(const RawAddress& bd_addr, tBTM_IO_CAP io_cap, tBTM_OOB_DATA oob_data, + tBTM_AUTH_REQ auth_req); /** * Device Configuration Queries @@ -88,14 +88,12 @@ DEV_CLASS btif_dm_get_local_class_of_device(); * Out-of-band functions */ void btif_dm_set_oob_for_io_req(tBTM_OOB_DATA* p_oob_data); -void btif_dm_set_oob_for_le_io_req(const RawAddress& bd_addr, - tBTM_OOB_DATA* p_oob_data, +void btif_dm_set_oob_for_le_io_req(const RawAddress& bd_addr, tBTM_OOB_DATA* p_oob_data, tBTM_LE_AUTH_REQ* p_auth_req); void btif_dm_load_local_oob(void); -void btif_dm_proc_loc_oob(tBT_TRANSPORT transport, bool is_valid, - const Octet16& c, const Octet16& r); -bool btif_dm_proc_rmt_oob(const RawAddress& bd_addr, Octet16* p_c, - Octet16* p_r); +void btif_dm_proc_loc_oob(tBT_TRANSPORT transport, bool is_valid, const Octet16& c, + const Octet16& r); +bool btif_dm_proc_rmt_oob(const RawAddress& bd_addr, Octet16* p_c, Octet16* p_r); void btif_dm_generate_local_oob_data(tBT_TRANSPORT transport); void btif_check_device_in_inquiry_db(const RawAddress& address); @@ -110,11 +108,9 @@ void btif_dm_disconnect_all_acls(); void btif_dm_le_rand(bluetooth::hci::LeRandCallback callback); void btif_dm_set_event_filter_connection_setup_all_devices(); -void btif_dm_allow_wake_by_hid( - std::vector classic_addrs, - std::vector> le_addrs); -void btif_dm_restore_filter_accept_list( - std::vector> le_devices); +void btif_dm_allow_wake_by_hid(std::vector classic_addrs, + std::vector> le_addrs); +void btif_dm_restore_filter_accept_list(std::vector> le_devices); void btif_dm_set_default_event_mask_except(uint64_t mask, uint64_t le_mask); void btif_dm_set_event_filter_inquiry_result_all_devices(); void btif_dm_metadata_changed(const RawAddress& remote_bd_addr, int key, @@ -131,8 +127,7 @@ typedef struct { bool is_pid_key_rcvd; tBTM_LE_PID_KEYS pid_key; /* peer device ID key */ bool is_lenc_key_rcvd; - tBTM_LE_LENC_KEYS - lenc_key; /* local encryption reproduction keys LTK = = d1(ER,DIV,0)*/ + tBTM_LE_LENC_KEYS lenc_key; /* local encryption reproduction keys LTK = = d1(ER,DIV,0)*/ bool is_lcsrk_key_rcvd; tBTM_LE_LCSRK_KEYS lcsrk_key; /* local device CSRK = d1(ER,DIV,1)*/ bool is_lidk_key_rcvd; /* local identity key received */ @@ -144,12 +139,10 @@ typedef struct { #define BTIF_DM_LE_LOCAL_KEY_ER (1 << 3) void btif_dm_load_ble_local_keys(void); -void btif_dm_get_ble_local_keys(tBTA_DM_BLE_LOCAL_KEY_MASK* p_key_mask, - Octet16* p_er, +void btif_dm_get_ble_local_keys(tBTA_DM_BLE_LOCAL_KEY_MASK* p_key_mask, Octet16* p_er, tBTA_BLE_LOCAL_ID_KEYS* p_id_keys); -void btif_dm_update_ble_remote_properties(const RawAddress& bd_addr, - BD_NAME bd_name, DEV_CLASS dev_class, - tBT_DEVICE_TYPE dev_type); +void btif_dm_update_ble_remote_properties(const RawAddress& bd_addr, BD_NAME bd_name, + DEV_CLASS dev_class, tBT_DEVICE_TYPE dev_type); bool check_cod_hid(const RawAddress& bd_addr); bool check_cod_hid_major(const RawAddress& bd_addr, uint32_t cod); diff --git a/system/btif/include/btif_gatt_util.h b/system/btif/include/btif_gatt_util.h index 599d8ea795e..c2c378f422c 100644 --- a/system/btif/include/btif_gatt_util.h +++ b/system/btif/include/btif_gatt_util.h @@ -28,7 +28,6 @@ void btif_to_bta_response(tGATTS_RSP* p_dest, btgatt_response_t* p_src); -void btif_gatt_check_encrypted_link(RawAddress bd_addr, - tBT_TRANSPORT transport); +void btif_gatt_check_encrypted_link(RawAddress bd_addr, tBT_TRANSPORT transport); #endif diff --git a/system/btif/include/btif_hd.h b/system/btif/include/btif_hd.h index ac29552cfb1..3eccd849bac 100644 --- a/system/btif/include/btif_hd.h +++ b/system/btif/include/btif_hd.h @@ -28,11 +28,7 @@ #include "bta/include/bta_hd_api.h" #include "types/raw_address.h" -typedef enum { - BTIF_HD_DISABLED = 0, - BTIF_HD_ENABLED, - BTIF_HD_DISABLING -} BTIF_HD_STATUS; +typedef enum { BTIF_HD_DISABLED = 0, BTIF_HD_ENABLED, BTIF_HD_DISABLING } BTIF_HD_STATUS; /* BTIF-HD control block */ typedef struct { diff --git a/system/btif/include/btif_hh.h b/system/btif/include/btif_hh.h index 1f11edc65e5..05700d14f2d 100644 --- a/system/btif/include/btif_hh.h +++ b/system/btif/include/btif_hh.h @@ -145,16 +145,15 @@ btif_hh_device_t* btif_hh_find_empty_dev(void); bt_status_t btif_hh_connect(const tAclLinkSpec& link_spec); bt_status_t btif_hh_virtual_unplug(const tAclLinkSpec& link_spec); void btif_hh_remove_device(const tAclLinkSpec& link_spec); -void btif_hh_setreport(btif_hh_uhid_t* p_uhid, bthh_report_type_t r_type, - uint16_t size, uint8_t* report); +void btif_hh_setreport(btif_hh_uhid_t* p_uhid, bthh_report_type_t r_type, uint16_t size, + uint8_t* report); void btif_hh_senddata(btif_hh_uhid_t* p_uhid, uint16_t size, uint8_t* report); -void btif_hh_getreport(btif_hh_uhid_t* p_uhid, bthh_report_type_t r_type, - uint8_t reportId, uint16_t bufferSize); +void btif_hh_getreport(btif_hh_uhid_t* p_uhid, bthh_report_type_t r_type, uint8_t reportId, + uint16_t bufferSize); void btif_hh_service_registration(bool enable); -void btif_hh_load_bonded_dev(const tAclLinkSpec& link_spec, - tBTA_HH_ATTR_MASK attr_mask, uint8_t sub_class, - uint8_t app_id, tBTA_HH_DEV_DSCP_INFO dscp_info, +void btif_hh_load_bonded_dev(const tAclLinkSpec& link_spec, tBTA_HH_ATTR_MASK attr_mask, + uint8_t sub_class, uint8_t app_id, tBTA_HH_DEV_DSCP_INFO dscp_info, bool reconnect_allowed); void DumpsysHid(int fd); diff --git a/system/btif/include/btif_jni_task.h b/system/btif/include/btif_jni_task.h index f8fa01bef1a..c94d7d8c726 100644 --- a/system/btif/include/btif_jni_task.h +++ b/system/btif/include/btif_jni_task.h @@ -40,9 +40,8 @@ void jni_thread_shutdown(); * ******************************************************************************/ -bt_status_t btif_transfer_context(tBTIF_CBACK* p_cback, uint16_t event, - char* p_params, int param_len, - tBTIF_COPY_CBACK* p_copy_cback); +bt_status_t btif_transfer_context(tBTIF_CBACK* p_cback, uint16_t event, char* p_params, + int param_len, tBTIF_COPY_CBACK* p_copy_cback); /** * This function posts a task into the btif message loop, that executes it in diff --git a/system/btif/include/btif_metrics_logging.h b/system/btif/include/btif_metrics_logging.h index 6226060423e..00e3a337721 100644 --- a/system/btif/include/btif_metrics_logging.h +++ b/system/btif/include/btif_metrics_logging.h @@ -22,51 +22,41 @@ #include "main/shim/metric_id_api.h" #include "types/raw_address.h" -void log_a2dp_audio_underrun_event(const RawAddress& address, - uint64_t encoding_interval_millis, +void log_a2dp_audio_underrun_event(const RawAddress& address, uint64_t encoding_interval_millis, int num_missing_pcm_bytes); -void log_a2dp_audio_overrun_event(const RawAddress& address, - uint64_t encoding_interval_millis, - int num_dropped_buffers, - int num_dropped_encoded_frames, +void log_a2dp_audio_overrun_event(const RawAddress& address, uint64_t encoding_interval_millis, + int num_dropped_buffers, int num_dropped_encoded_frames, int num_dropped_encoded_bytes); -void log_a2dp_playback_event(const RawAddress& address, int playback_state, - int audio_coding_mode); +void log_a2dp_playback_event(const RawAddress& address, int playback_state, int audio_coding_mode); -void log_a2dp_session_metrics_event( - const RawAddress& address, int64_t audio_duration_ms, - int media_timer_min_ms, int media_timer_max_ms, int media_timer_avg_ms, - int total_scheduling_count, int buffer_overruns_max_count, - int buffer_overruns_total, float buffer_underruns_average, - int buffer_underruns_count, int64_t codec_index, bool is_a2dp_offload); +void log_a2dp_session_metrics_event(const RawAddress& address, int64_t audio_duration_ms, + int media_timer_min_ms, int media_timer_max_ms, + int media_timer_avg_ms, int total_scheduling_count, + int buffer_overruns_max_count, int buffer_overruns_total, + float buffer_underruns_average, int buffer_underruns_count, + int64_t codec_index, bool is_a2dp_offload); -void log_read_rssi_result(const RawAddress& address, uint16_t handle, - uint32_t cmd_status, int8_t rssi); +void log_read_rssi_result(const RawAddress& address, uint16_t handle, uint32_t cmd_status, + int8_t rssi); -void log_read_failed_contact_counter_result(const RawAddress& address, - uint16_t handle, - uint32_t cmd_status, - int32_t failed_contact_counter); +void log_read_failed_contact_counter_result(const RawAddress& address, uint16_t handle, + uint32_t cmd_status, int32_t failed_contact_counter); -void log_read_tx_power_level_result(const RawAddress& address, uint16_t handle, - uint32_t cmd_status, +void log_read_tx_power_level_result(const RawAddress& address, uint16_t handle, uint32_t cmd_status, int32_t transmit_power_level); -void log_counter_metrics_btif(android::bluetooth::CodePathCounterKeyEnum key, - int64_t value); +void log_counter_metrics_btif(android::bluetooth::CodePathCounterKeyEnum key, int64_t value); -void log_socket_connection_state( - const RawAddress& address, int port, int type, - android::bluetooth::SocketConnectionstateEnum connection_state, - int64_t tx_bytes, int64_t rx_bytes, int uid, int server_port, - android::bluetooth::SocketRoleEnum socket_role); +void log_socket_connection_state(const RawAddress& address, int port, int type, + android::bluetooth::SocketConnectionstateEnum connection_state, + int64_t tx_bytes, int64_t rx_bytes, int uid, int server_port, + android::bluetooth::SocketRoleEnum socket_role); -bool init_metric_id_allocator( - const std::unordered_map& paired_device_map, - bluetooth::shim::CallbackLegacy save_id_callback, - bluetooth::shim::CallbackLegacy forget_device_callback); +bool init_metric_id_allocator(const std::unordered_map& paired_device_map, + bluetooth::shim::CallbackLegacy save_id_callback, + bluetooth::shim::CallbackLegacy forget_device_callback); bool close_metric_id_allocator(); diff --git a/system/btif/include/btif_pan_internal.h b/system/btif/include/btif_pan_internal.h index 0491041078d..a9aa42795dc 100644 --- a/system/btif/include/btif_pan_internal.h +++ b/system/btif/include/btif_pan_internal.h @@ -82,8 +82,8 @@ typedef struct { ******************************************************************************/ extern btpan_cb_t btpan_cb; -btpan_conn_t* btpan_new_conn(int handle, const RawAddress& addr, - tBTA_PAN_ROLE local_role, tBTA_PAN_ROLE peer_role); +btpan_conn_t* btpan_new_conn(int handle, const RawAddress& addr, tBTA_PAN_ROLE local_role, + tBTA_PAN_ROLE peer_role); btpan_conn_t* btpan_find_conn_addr(const RawAddress& addr); btpan_conn_t* btpan_find_conn_handle(uint16_t handle); void btpan_set_flow_control(bool enable); @@ -92,16 +92,15 @@ int btpan_tap_open(void); void create_tap_read_thread(int tap_fd); void destroy_tap_read_thread(void); int btpan_tap_close(int tap_fd); -int btpan_tap_send(int tap_fd, const RawAddress& src, const RawAddress& dst, - uint16_t protocol, const char* buff, uint16_t size, bool ext, - bool forward); +int btpan_tap_send(int tap_fd, const RawAddress& src, const RawAddress& dst, uint16_t protocol, + const char* buff, uint16_t size, bool ext, bool forward); -static inline int is_empty_eth_addr(const RawAddress& addr) { - return addr == RawAddress::kEmpty; -} +static inline int is_empty_eth_addr(const RawAddress& addr) { return addr == RawAddress::kEmpty; } static inline int is_valid_bt_eth_addr(const RawAddress& addr) { - if (is_empty_eth_addr(addr)) return 0; + if (is_empty_eth_addr(addr)) { + return 0; + } return addr.address[0] & 1 ? 0 : 1; /* Cannot be multicasting address */ } diff --git a/system/btif/include/btif_profile_queue.h b/system/btif/include/btif_profile_queue.h index 73c19787435..472aad548c2 100644 --- a/system/btif/include/btif_profile_queue.h +++ b/system/btif/include/btif_profile_queue.h @@ -33,8 +33,7 @@ typedef bt_status_t (*btif_connect_cb_t)(RawAddress* bda, uint16_t uuid); -bt_status_t btif_queue_connect(uint16_t uuid, const RawAddress* bda, - btif_connect_cb_t connect_cb); +bt_status_t btif_queue_connect(uint16_t uuid, const RawAddress* bda, btif_connect_cb_t connect_cb); void btif_queue_cleanup(uint16_t uuid); void btif_queue_advance(); diff --git a/system/btif/include/btif_profile_storage.h b/system/btif/include/btif_profile_storage.h index 1f1da31cf3e..1aaddd2c243 100644 --- a/system/btif/include/btif_profile_storage.h +++ b/system/btif/include/btif_profile_storage.h @@ -42,11 +42,12 @@ * ******************************************************************************/ -bt_status_t btif_storage_add_hid_device_info( - const tAclLinkSpec& link_spec, uint16_t attr_mask, uint8_t sub_class, - uint8_t app_id, uint16_t vendor_id, uint16_t product_id, uint16_t version, - uint8_t ctry_code, uint16_t ssr_max_latency, uint16_t ssr_min_tout, - uint16_t dl_len, uint8_t* dsc_list); +bt_status_t btif_storage_add_hid_device_info(const tAclLinkSpec& link_spec, uint16_t attr_mask, + uint8_t sub_class, uint8_t app_id, uint16_t vendor_id, + uint16_t product_id, uint16_t version, + uint8_t ctry_code, uint16_t ssr_max_latency, + uint16_t ssr_min_tout, uint16_t dl_len, + uint8_t* dsc_list); /******************************************************************************* * @@ -74,8 +75,7 @@ bt_status_t btif_storage_load_bonded_hid_info(void); bt_status_t btif_storage_remove_hid_info(const tAclLinkSpec& link_spec); /** Returns all bonded LE hid devices + their address types. */ -std::vector> btif_storage_get_le_hid_devices( - void); +std::vector> btif_storage_get_le_hid_devices(void); /** Returns all bonded Classic HID devices capable of waking the system from * system suspend (i.e. Keyboards and Pointing devices). @@ -89,17 +89,15 @@ void btif_storage_load_bonded_hearing_aids(); void btif_storage_remove_hearing_aid(const RawAddress& address); /** Set/Unset the hearing aid device HEARING_AID_IS_ACCEPTLISTED flag. */ -void btif_storage_set_hearing_aid_acceptlist(const RawAddress& address, - bool add_to_acceptlist); +void btif_storage_set_hearing_aid_acceptlist(const RawAddress& address, bool add_to_acceptlist); /** Get the hearing aid device properties. */ -bool btif_storage_get_hearing_aid_prop( - const RawAddress& address, uint8_t* capabilities, uint64_t* hi_sync_id, - uint16_t* render_delay, uint16_t* preparation_delay, uint16_t* codecs); +bool btif_storage_get_hearing_aid_prop(const RawAddress& address, uint8_t* capabilities, + uint64_t* hi_sync_id, uint16_t* render_delay, + uint16_t* preparation_delay, uint16_t* codecs); /** Store Le Audio device autoconnect flag */ -void btif_storage_set_leaudio_autoconnect(const RawAddress& addr, - bool autoconnect); +void btif_storage_set_leaudio_autoconnect(const RawAddress& addr, bool autoconnect); /** Store PACs information */ void btif_storage_leaudio_update_pacs_bin(const RawAddress& addr); @@ -111,14 +109,13 @@ void btif_storage_leaudio_update_ase_bin(const RawAddress& addr); void btif_storage_leaudio_update_handles_bin(const RawAddress& addr); /** Store Le Audio device audio locations */ -void btif_storage_set_leaudio_audio_location(const RawAddress& addr, - uint32_t sink_location, +void btif_storage_set_leaudio_audio_location(const RawAddress& addr, uint32_t sink_location, uint32_t source_location); /** Store Le Audio device context types */ -void btif_storage_set_leaudio_supported_context_types( - const RawAddress& addr, uint16_t sink_supported_context_type, - uint16_t source_supported_context_type); +void btif_storage_set_leaudio_supported_context_types(const RawAddress& addr, + uint16_t sink_supported_context_type, + uint16_t source_supported_context_type); /** Remove Le Audio device service data */ void btif_storage_leaudio_clear_service_data(const RawAddress& address); @@ -136,15 +133,13 @@ void btif_storage_load_bonded_leaudio_has_devices(void); void btif_storage_remove_leaudio_has(const RawAddress& address); /** Set/Unset the HAS device acceptlist flag. */ -void btif_storage_set_leaudio_has_acceptlist(const RawAddress& address, - bool add_to_acceptlist); +void btif_storage_set_leaudio_has_acceptlist(const RawAddress& address, bool add_to_acceptlist); void btif_storage_add_groups(const RawAddress& addr); void btif_storage_load_bonded_groups(void); void btif_storage_remove_groups(const RawAddress& address); -void btif_storage_set_csis_autoconnect(const RawAddress& addr, - bool autoconnect); +void btif_storage_set_csis_autoconnect(const RawAddress& addr, bool autoconnect); void btif_storage_update_csis_info(const RawAddress& addr); void btif_storage_load_bonded_csis_devices(); void btif_storage_remove_csis_device(const RawAddress& address); diff --git a/system/btif/include/btif_rc.h b/system/btif/include/btif_rc.h index ea2e9f9da10..94d365cc4dc 100644 --- a/system/btif/include/btif_rc.h +++ b/system/btif/include/btif_rc.h @@ -24,8 +24,7 @@ class RawAddress; void btif_rc_handler(tBTA_AV_EVT event, tBTA_AV* p_data); uint8_t btif_rc_get_connected_peer_handle(const RawAddress& peer_addr); -void btif_rc_check_handle_pending_play(const RawAddress& peer_addr, - bool bSendToApp); +void btif_rc_check_handle_pending_play(const RawAddress& peer_addr, bool bSendToApp); bool btif_rc_is_connected_peer(const RawAddress& peer_addr); void btif_rc_check_pending_cmd(const RawAddress& peer_addr); void btif_rc_get_addr_by_handle(uint8_t handle, RawAddress& rc_addr); diff --git a/system/btif/include/btif_sock_l2cap.h b/system/btif/include/btif_sock_l2cap.h index 6b0ce983e42..d527ed8347a 100644 --- a/system/btif/include/btif_sock_l2cap.h +++ b/system/btif/include/btif_sock_l2cap.h @@ -12,16 +12,14 @@ bt_status_t btsock_l2cap_init(int handle, uid_set_t* set); bt_status_t btsock_l2cap_cleanup(); -bt_status_t btsock_l2cap_listen(const char* name, int channel, int* sock_fd, - int flags, int app_uid); -bt_status_t btsock_l2cap_connect(const RawAddress* bd_addr, int channel, - int* sock_fd, int flags, int app_uid); +bt_status_t btsock_l2cap_listen(const char* name, int channel, int* sock_fd, int flags, + int app_uid); +bt_status_t btsock_l2cap_connect(const RawAddress* bd_addr, int channel, int* sock_fd, int flags, + int app_uid); void btsock_l2cap_signaled(int fd, int flags, uint32_t user_id); void on_l2cap_psm_assigned(int id, int psm); bt_status_t btsock_l2cap_disconnect(const RawAddress* bd_addr); -bt_status_t btsock_l2cap_get_l2cap_local_cid(bluetooth::Uuid& conn_uuid, - uint16_t* cid); -bt_status_t btsock_l2cap_get_l2cap_remote_cid(bluetooth::Uuid& conn_uuid, - uint16_t* cid); +bt_status_t btsock_l2cap_get_l2cap_local_cid(bluetooth::Uuid& conn_uuid, uint16_t* cid); +bt_status_t btsock_l2cap_get_l2cap_remote_cid(bluetooth::Uuid& conn_uuid, uint16_t* cid); #endif diff --git a/system/btif/include/btif_sock_logging.h b/system/btif/include/btif_sock_logging.h index 4a963314e51..7cd30f6396a 100644 --- a/system/btif/include/btif_sock_logging.h +++ b/system/btif/include/btif_sock_logging.h @@ -18,8 +18,7 @@ #include "types/raw_address.h" -void btif_sock_connection_logger(const RawAddress& address, int port, int type, - int state, int role, int uid, int server_port, - int64_t tx_bytes, int64_t rx_bytes, +void btif_sock_connection_logger(const RawAddress& address, int port, int type, int state, int role, + int uid, int server_port, int64_t tx_bytes, int64_t rx_bytes, const char* server_name); void btif_sock_dump(int fd); diff --git a/system/btif/include/btif_sock_rfc.h b/system/btif/include/btif_sock_rfc.h index ae52e23d73a..a7b21aab528 100644 --- a/system/btif/include/btif_sock_rfc.h +++ b/system/btif/include/btif_sock_rfc.h @@ -32,15 +32,12 @@ #include "types/raw_address.h" bt_status_t btsock_rfc_init(int handle, uid_set_t* set); bt_status_t btsock_rfc_cleanup(); -bt_status_t btsock_rfc_control_req(uint8_t dlci, const RawAddress& bd_addr, - uint8_t modem_signal, uint8_t break_signal, - uint8_t discard_buffers, +bt_status_t btsock_rfc_control_req(uint8_t dlci, const RawAddress& bd_addr, uint8_t modem_signal, + uint8_t break_signal, uint8_t discard_buffers, uint8_t break_signal_seq, bool fc); -bt_status_t btsock_rfc_listen(const char* name, const bluetooth::Uuid* uuid, - int channel, int* sock_fd, int flags, - int app_uid); -bt_status_t btsock_rfc_connect(const RawAddress* bd_addr, - const bluetooth::Uuid* uuid, int channel, +bt_status_t btsock_rfc_listen(const char* name, const bluetooth::Uuid* uuid, int channel, + int* sock_fd, int flags, int app_uid); +bt_status_t btsock_rfc_connect(const RawAddress* bd_addr, const bluetooth::Uuid* uuid, int channel, int* sock_fd, int flags, int app_uid); void btsock_rfc_signaled(int fd, int flags, uint32_t user_id); bt_status_t btsock_rfc_disconnect(const RawAddress* bd_addr); diff --git a/system/btif/include/btif_sock_sco.h b/system/btif/include/btif_sock_sco.h index 1b72a6a57cc..82e262928be 100644 --- a/system/btif/include/btif_sock_sco.h +++ b/system/btif/include/btif_sock_sco.h @@ -27,5 +27,4 @@ typedef struct thread_t thread_t; bt_status_t btsock_sco_init(thread_t* thread); bt_status_t btsock_sco_cleanup(void); bt_status_t btsock_sco_listen(int* sock_fd, int flags); -bt_status_t btsock_sco_connect(const RawAddress* bd_addr, int* sock_fd, - int flags); +bt_status_t btsock_sco_connect(const RawAddress* bd_addr, int* sock_fd, int flags); diff --git a/system/btif/include/btif_sock_sdp.h b/system/btif/include/btif_sock_sdp.h index 50ef9aacebe..44d765e417b 100644 --- a/system/btif/include/btif_sock_sdp.h +++ b/system/btif/include/btif_sock_sdp.h @@ -24,8 +24,7 @@ #include #include -static const bluetooth::Uuid UUID_OBEX_OBJECT_PUSH = - bluetooth::Uuid::From16Bit(0x1105); +static const bluetooth::Uuid UUID_OBEX_OBJECT_PUSH = bluetooth::Uuid::From16Bit(0x1105); static const bluetooth::Uuid UUID_PBAP_PCE = bluetooth::Uuid::From16Bit(0x112E); static const bluetooth::Uuid UUID_PBAP_PSE = bluetooth::Uuid::From16Bit(0x112F); static const bluetooth::Uuid UUID_MAP_MAS = bluetooth::Uuid::From16Bit(0x1132); diff --git a/system/btif/include/btif_sock_thread.h b/system/btif/include/btif_sock_thread.h index ab2b684b7a8..34f10792096 100644 --- a/system/btif/include/btif_sock_thread.h +++ b/system/btif/include/btif_sock_thread.h @@ -19,10 +19,9 @@ #ifndef BTIF_SOCK_THREAD_H #define BTIF_SOCK_THREAD_H -#include - #include #include +#include /******************************************************************************* * Constants & Macros @@ -39,16 +38,13 @@ * Functions ******************************************************************************/ -typedef void (*btsock_signaled_cb)(int fd, int type, int flags, - uint32_t user_id); +typedef void (*btsock_signaled_cb)(int fd, int type, int flags, uint32_t user_id); typedef void (*btsock_cmd_cb)(int cmd_fd, int type, int size, uint32_t user_id); void btsock_thread_init(); -int btsock_thread_add_fd(int handle, int fd, int type, int flags, - uint32_t user_id); +int btsock_thread_add_fd(int handle, int fd, int type, int flags, uint32_t user_id); int btsock_thread_wakeup(int handle); -int btsock_thread_create(btsock_signaled_cb callback, - btsock_cmd_cb cmd_callback); +int btsock_thread_create(btsock_signaled_cb callback, btsock_cmd_cb cmd_callback); int btsock_thread_exit(int handle); #endif diff --git a/system/btif/include/btif_storage.h b/system/btif/include/btif_storage.h index e9807c82e3b..de9f8901f28 100644 --- a/system/btif/include/btif_storage.h +++ b/system/btif/include/btif_storage.h @@ -41,9 +41,8 @@ (p_prop)->val = (p_v); \ } while (0) -#define STORAGE_BDADDR_STRING_SZ (18) /* 00:11:22:33:44:55 */ -#define STORAGE_UUID_STRING_SIZE \ - (36 + 1) /* 00001200-0000-1000-8000-00805f9b34fb; */ +#define STORAGE_BDADDR_STRING_SZ (18) /* 00:11:22:33:44:55 */ +#define STORAGE_UUID_STRING_SIZE (36 + 1) /* 00001200-0000-1000-8000-00805f9b34fb; */ #define STORAGE_PINLEN_STRING_MAX_SIZE (2) /* ascii pinlen max chars */ #define STORAGE_KEYTYPE_STRING_MAX_SIZE (1) /* ascii keytype max chars */ @@ -70,9 +69,8 @@ typedef struct { RawAddress devices[BTM_SEC_MAX_DEVICE_RECORDS]; } btif_bonded_devices_t; -bt_status_t btif_in_fetch_bonded_ble_device( - const std::string& remote_bd_addr, int add, - btif_bonded_devices_t* p_bonded_devices); +bt_status_t btif_in_fetch_bonded_ble_device(const std::string& remote_bd_addr, int add, + btif_bonded_devices_t* p_bonded_devices); /******************************************************************************* * @@ -115,8 +113,8 @@ bt_status_t btif_storage_set_adapter_property(bt_property_t* property); * BT_STATUS_FAIL otherwise * ******************************************************************************/ -bt_status_t btif_storage_get_remote_device_property( - const RawAddress* remote_bd_addr, bt_property_t* property); +bt_status_t btif_storage_get_remote_device_property(const RawAddress* remote_bd_addr, + bt_property_t* property); /******************************************************************************* * @@ -129,8 +127,8 @@ bt_status_t btif_storage_get_remote_device_property( * BT_STATUS_FAIL otherwise * ******************************************************************************/ -bt_status_t btif_storage_set_remote_device_property( - const RawAddress* remote_bd_addr, bt_property_t* property); +bt_status_t btif_storage_set_remote_device_property(const RawAddress* remote_bd_addr, + bt_property_t* property); /******************************************************************************* * @@ -145,8 +143,7 @@ bt_status_t btif_storage_set_remote_device_property( * ******************************************************************************/ bt_status_t btif_storage_add_remote_device(const RawAddress* remote_bd_addr, - uint32_t num_properties, - bt_property_t* properties); + uint32_t num_properties, bt_property_t* properties); /******************************************************************************* * @@ -159,9 +156,8 @@ bt_status_t btif_storage_add_remote_device(const RawAddress* remote_bd_addr, * BT_STATUS_FAIL otherwise * ******************************************************************************/ -bt_status_t btif_storage_add_bonded_device(RawAddress* remote_bd_addr, - LinkKey link_key, uint8_t key_type, - uint8_t pin_length); +bt_status_t btif_storage_add_bonded_device(RawAddress* remote_bd_addr, LinkKey link_key, + uint8_t key_type, uint8_t pin_length); /******************************************************************************* * @@ -216,11 +212,12 @@ bt_status_t btif_storage_load_bonded_devices(void); * ******************************************************************************/ -bt_status_t btif_storage_add_hid_device_info( - const tAclLinkSpec& link_spec, uint16_t attr_mask, uint8_t sub_class, - uint8_t app_id, uint16_t vendor_id, uint16_t product_id, uint16_t version, - uint8_t ctry_code, uint16_t ssr_max_latency, uint16_t ssr_min_tout, - uint16_t dl_len, uint8_t* dsc_list); +bt_status_t btif_storage_add_hid_device_info(const tAclLinkSpec& link_spec, uint16_t attr_mask, + uint8_t sub_class, uint8_t app_id, uint16_t vendor_id, + uint16_t product_id, uint16_t version, + uint8_t ctry_code, uint16_t ssr_max_latency, + uint16_t ssr_min_tout, uint16_t dl_len, + uint8_t* dsc_list); /******************************************************************************* * @@ -254,12 +251,10 @@ void btif_storage_load_bonded_hearing_aids(); void btif_storage_remove_hearing_aid(const RawAddress& address); /** Set/Unset the hearing aid device HEARING_AID_IS_ACCEPTLISTED flag. */ -void btif_storage_set_hearing_aid_acceptlist(const RawAddress& address, - bool add_to_acceptlist); +void btif_storage_set_hearing_aid_acceptlist(const RawAddress& address, bool add_to_acceptlist); /** Stores information about GATT Client supported features support */ -void btif_storage_set_gatt_cl_supp_feat(const RawAddress& bd_addr, - uint8_t feat); +void btif_storage_set_gatt_cl_supp_feat(const RawAddress& bd_addr, uint8_t feat); /** Get client supported features */ uint8_t btif_storage_get_gatt_cl_supp_feat(const RawAddress& bd_addr); @@ -283,13 +278,12 @@ Octet16 btif_storage_get_gatt_cl_db_hash(const RawAddress& bd_addr); void btif_storage_remove_gatt_cl_db_hash(const RawAddress& bd_addr); /** Get the hearing aid device properties. */ -bool btif_storage_get_hearing_aid_prop( - const RawAddress& address, uint8_t* capabilities, uint64_t* hi_sync_id, - uint16_t* render_delay, uint16_t* preparation_delay, uint16_t* codecs); +bool btif_storage_get_hearing_aid_prop(const RawAddress& address, uint8_t* capabilities, + uint64_t* hi_sync_id, uint16_t* render_delay, + uint16_t* preparation_delay, uint16_t* codecs); /** Store Le Audio device autoconnect flag */ -void btif_storage_set_leaudio_autoconnect(const RawAddress& addr, - bool autoconnect); +void btif_storage_set_leaudio_autoconnect(const RawAddress& addr, bool autoconnect); /** Store PACs information */ void btif_storage_leaudio_update_pacs_bin(const RawAddress& addr); @@ -301,14 +295,13 @@ void btif_storage_leaudio_update_ase_bin(const RawAddress& addr); void btif_storage_leaudio_update_handles_bin(const RawAddress& addr); /** Store Le Audio device audio locations */ -void btif_storage_set_leaudio_audio_location(const RawAddress& addr, - uint32_t sink_location, +void btif_storage_set_leaudio_audio_location(const RawAddress& addr, uint32_t sink_location, uint32_t source_location); /** Store Le Audio device context types */ -void btif_storage_set_leaudio_supported_context_types( - const RawAddress& addr, uint16_t sink_supported_context_type, - uint16_t source_supported_context_type); +void btif_storage_set_leaudio_supported_context_types(const RawAddress& addr, + uint16_t sink_supported_context_type, + uint16_t source_supported_context_type); /** Remove Le Audio device service data */ void btif_storage_leaudio_clear_service_data(const RawAddress& address); @@ -326,8 +319,7 @@ void btif_storage_load_bonded_leaudio_has_devices(void); void btif_storage_remove_leaudio_has(const RawAddress& address); /** Set/Unset the HAS device acceptlist flag. */ -void btif_storage_set_leaudio_has_acceptlist(const RawAddress& address, - bool add_to_acceptlist); +void btif_storage_set_leaudio_has_acceptlist(const RawAddress& address, bool add_to_acceptlist); /******************************************************************************* * @@ -342,21 +334,14 @@ void btif_storage_set_leaudio_has_acceptlist(const RawAddress& address, ******************************************************************************/ bool btif_storage_is_restricted_device(const RawAddress* remote_bd_addr); -bt_status_t btif_storage_add_ble_bonding_key(RawAddress* remote_bd_addr, - const uint8_t* key, - uint8_t key_type, - uint8_t key_length); -bt_status_t btif_storage_get_ble_bonding_key(const RawAddress& remote_bd_addr, - uint8_t key_type, - uint8_t* key_value, - int key_length); - -bt_status_t btif_storage_add_ble_local_key(const Octet16& key, - uint8_t key_type); -bt_status_t btif_storage_remove_ble_bonding_keys( - const RawAddress* remote_bd_addr); -bt_status_t btif_storage_get_ble_local_key(uint8_t key_type, - Octet16* key_value); +bt_status_t btif_storage_add_ble_bonding_key(RawAddress* remote_bd_addr, const uint8_t* key, + uint8_t key_type, uint8_t key_length); +bt_status_t btif_storage_get_ble_bonding_key(const RawAddress& remote_bd_addr, uint8_t key_type, + uint8_t* key_value, int key_length); + +bt_status_t btif_storage_add_ble_local_key(const Octet16& key, uint8_t key_type); +bt_status_t btif_storage_remove_ble_bonding_keys(const RawAddress* remote_bd_addr); +bt_status_t btif_storage_get_ble_local_key(uint8_t key_type, Octet16* key_value); bt_status_t btif_storage_get_remote_addr_type(const RawAddress* remote_bd_addr, tBLE_ADDR_TYPE* addr_type); @@ -423,8 +408,8 @@ bool btif_storage_get_stored_remote_name(const RawAddress& bd_addr, char* name); * ******************************************************************************/ -bt_status_t btif_storage_set_hid_connection_policy( - const tAclLinkSpec& link_spec, bool reconnect_allowed); +bt_status_t btif_storage_set_hid_connection_policy(const tAclLinkSpec& link_spec, + bool reconnect_allowed); /******************************************************************************* * @@ -436,13 +421,12 @@ bt_status_t btif_storage_set_hid_connection_policy( * ******************************************************************************/ -bt_status_t btif_storage_get_hid_connection_policy( - const tAclLinkSpec& link_spec, bool* reconnect_allowed); +bt_status_t btif_storage_get_hid_connection_policy(const tAclLinkSpec& link_spec, + bool* reconnect_allowed); /****************************************************************************** * Exported for unit tests *****************************************************************************/ -size_t btif_split_uuids_string(const char* str, bluetooth::Uuid* p_uuid, - size_t max_uuids); +size_t btif_split_uuids_string(const char* str, bluetooth::Uuid* p_uuid, size_t max_uuids); #endif // SYSTEM_BTIF_INCLUDE_BTIF_STORAGE_H_ diff --git a/system/btif/include/core_callbacks.h b/system/btif/include/core_callbacks.h index 7d9f0e1cb7b..3a5c08c54af 100644 --- a/system/btif/include/core_callbacks.h +++ b/system/btif/include/core_callbacks.h @@ -31,40 +31,28 @@ struct EventCallbacks { void (*invoke_adapter_state_changed_cb)(bt_state_t state); void (*invoke_adapter_properties_cb)(bt_status_t status, int num_properties, bt_property_t* properties); - void (*invoke_remote_device_properties_cb)(bt_status_t status, - RawAddress bd_addr, - int num_properties, - bt_property_t* properties); + void (*invoke_remote_device_properties_cb)(bt_status_t status, RawAddress bd_addr, + int num_properties, bt_property_t* properties); void (*invoke_device_found_cb)(int num_properties, bt_property_t* properties); void (*invoke_discovery_state_changed_cb)(bt_discovery_state_t state); - void (*invoke_pin_request_cb)(RawAddress bd_addr, bt_bdname_t bd_name, - uint32_t cod, bool min_16_digit); - void (*invoke_ssp_request_cb)(RawAddress bd_addr, - bt_ssp_variant_t pairing_variant, + void (*invoke_pin_request_cb)(RawAddress bd_addr, bt_bdname_t bd_name, uint32_t cod, + bool min_16_digit); + void (*invoke_ssp_request_cb)(RawAddress bd_addr, bt_ssp_variant_t pairing_variant, uint32_t pass_key); - void (*invoke_oob_data_request_cb)(tBT_TRANSPORT t, bool valid, Octet16 c, - Octet16 r, RawAddress raw_address, - uint8_t address_type); + void (*invoke_oob_data_request_cb)(tBT_TRANSPORT t, bool valid, Octet16 c, Octet16 r, + RawAddress raw_address, uint8_t address_type); void (*invoke_bond_state_changed_cb)(bt_status_t status, RawAddress bd_addr, bt_bond_state_t state, int fail_reason); - void (*invoke_address_consolidate_cb)(RawAddress main_bd_addr, - RawAddress secondary_bd_addr); - void (*invoke_le_address_associate_cb)(RawAddress main_bd_addr, - RawAddress secondary_bd_addr); - void (*invoke_acl_state_changed_cb)(bt_status_t status, RawAddress bd_addr, - bt_acl_state_t state, - int transport_link_type, - bt_hci_error_code_t hci_reason, - bt_conn_direction_t direction, - uint16_t acl_handle); + void (*invoke_address_consolidate_cb)(RawAddress main_bd_addr, RawAddress secondary_bd_addr); + void (*invoke_le_address_associate_cb)(RawAddress main_bd_addr, RawAddress secondary_bd_addr); + void (*invoke_acl_state_changed_cb)(bt_status_t status, RawAddress bd_addr, bt_acl_state_t state, + int transport_link_type, bt_hci_error_code_t hci_reason, + bt_conn_direction_t direction, uint16_t acl_handle); void (*invoke_thread_evt_cb)(bt_cb_thread_evt event); void (*invoke_le_test_mode_cb)(bt_status_t status, uint16_t count); - void (*invoke_energy_info_cb)(bt_activity_energy_info energy_info, - bt_uid_traffic_t* uid_data); - void (*invoke_link_quality_report_cb)(uint64_t timestamp, int report_id, - int rssi, int snr, - int retransmission_count, - int packets_not_receive_count, + void (*invoke_energy_info_cb)(bt_activity_energy_info energy_info, bt_uid_traffic_t* uid_data); + void (*invoke_link_quality_report_cb)(uint64_t timestamp, int report_id, int rssi, int snr, + int retransmission_count, int packets_not_receive_count, int negative_acknowledgement_count); void (*invoke_key_missing_cb)(RawAddress bd_addr); @@ -90,8 +78,7 @@ struct CodecInterface { virtual void cleanup() = 0; virtual uint32_t encodePacket(int16_t* input, uint8_t* output) = 0; - virtual bool decodePacket(const uint8_t* i_buf, int16_t* o_buf, - size_t out_len) = 0; + virtual bool decodePacket(const uint8_t* i_buf, int16_t* o_buf, size_t out_len) = 0; explicit CodecInterface() = default; CodecInterface(const CodecInterface&) = delete; @@ -109,13 +96,11 @@ struct HACK_ProfileInterface { // HID hacks bt_status_t (*btif_hh_connect)(const tAclLinkSpec& link_spec); bt_status_t (*btif_hh_virtual_unplug)(const tAclLinkSpec& link_spec); - tBTA_HH_STATUS (*bta_hh_read_ssr_param)(const tAclLinkSpec& link_spec, - uint16_t* p_max_ssr_lat, + tBTA_HH_STATUS (*bta_hh_read_ssr_param)(const tAclLinkSpec& link_spec, uint16_t* p_max_ssr_lat, uint16_t* p_min_ssr_tout); // AVDTP hacks - void (*btif_av_set_dynamic_audio_buffer_size)( - uint8_t dynamic_audio_buffer_size); + void (*btif_av_set_dynamic_audio_buffer_size)(uint8_t dynamic_audio_buffer_size); // ASHA hacks int (*GetHearingAidDeviceCount)(); @@ -143,21 +128,18 @@ struct CoreInterface { HACK_ProfileInterface* profileSpecific_HACK; virtual void onBluetoothEnabled() = 0; - virtual bt_status_t toggleProfile(tBTA_SERVICE_ID service_id, - bool enable) = 0; + virtual bt_status_t toggleProfile(tBTA_SERVICE_ID service_id, bool enable) = 0; virtual void removeDeviceFromProfiles(const RawAddress& bd_addr) = 0; - virtual void onLinkDown(const RawAddress& bd_addr, - tBT_TRANSPORT transport) = 0; + virtual void onLinkDown(const RawAddress& bd_addr, tBT_TRANSPORT transport) = 0; - CoreInterface(EventCallbacks* eventCallbacks, - ConfigInterface* configInterface, CodecInterface* msbcCodec, - CodecInterface* lc3Codec, + CoreInterface(EventCallbacks* eventCallbacks, ConfigInterface* configInterface, + CodecInterface* msbcCodec, CodecInterface* lc3Codec, HACK_ProfileInterface* profileSpecific_HACK) : events{eventCallbacks}, config{configInterface}, msbcCodec{msbcCodec}, lc3Codec{lc3Codec}, - profileSpecific_HACK{profileSpecific_HACK} {}; + profileSpecific_HACK{profileSpecific_HACK} {} CoreInterface(const CoreInterface&) = delete; CoreInterface& operator=(const CoreInterface&) = delete; diff --git a/system/btif/include/mock_core_callbacks.h b/system/btif/include/mock_core_callbacks.h index c5ea2365b1a..8f4202f6a94 100644 --- a/system/btif/include/mock_core_callbacks.h +++ b/system/btif/include/mock_core_callbacks.h @@ -29,50 +29,41 @@ namespace testing { // These callbacks are not profile specific (e.g. connection complete, bond // complete, etc) and are what go to the Java layer. EventCallbacks mock_event_callbacks = { - .invoke_adapter_state_changed_cb = [](bt_state_t /* state */) {}, - .invoke_adapter_properties_cb = [](bt_status_t /* status */, - int /* num_properties */, - bt_property_t* /* properties */) {}, - .invoke_remote_device_properties_cb = - [](bt_status_t /* status */, RawAddress /* bd_addr */, - int /* num_properties */, bt_property_t* /* properties */) {}, - .invoke_device_found_cb = [](int /* num_properties */, - bt_property_t* /* properties */) {}, - .invoke_discovery_state_changed_cb = - [](bt_discovery_state_t /* state */) {}, - .invoke_pin_request_cb = [](RawAddress /* bd_addr */, - bt_bdname_t /* bd_name */, uint32_t /* cod */, - bool /* min_16_digit */) {}, - .invoke_ssp_request_cb = [](RawAddress /* bd_addr */, - bt_ssp_variant_t /* pairing_variant */, - uint32_t /* pass_key */) {}, - .invoke_oob_data_request_cb = [](tBT_TRANSPORT /* t */, bool /* valid */, - Octet16 /* c */, Octet16 /* r */, - RawAddress /* raw_address */, - uint8_t /* address_type */) {}, - .invoke_bond_state_changed_cb = - [](bt_status_t /* status */, RawAddress /* bd_addr */, - bt_bond_state_t /* state */, int /* fail_reason */) {}, - .invoke_address_consolidate_cb = [](RawAddress /* main_bd_addr */, - RawAddress /* secondary_bd_addr */) {}, - .invoke_le_address_associate_cb = [](RawAddress /* main_bd_addr */, - RawAddress /* secondary_bd_addr */) {}, - .invoke_acl_state_changed_cb = - [](bt_status_t /* status */, RawAddress /* bd_addr */, - bt_acl_state_t /* state */, int /* transport_link_type */, - bt_hci_error_code_t /* hci_reason */, - bt_conn_direction_t /* direction */, uint16_t /* acl_handle */) {}, - .invoke_thread_evt_cb = [](bt_cb_thread_evt /* event */) {}, - .invoke_le_test_mode_cb = [](bt_status_t /* status */, - uint16_t /* count */) {}, - .invoke_energy_info_cb = [](bt_activity_energy_info /* energy_info */, - bt_uid_traffic_t* /* uid_data */) {}, - .invoke_link_quality_report_cb = - [](uint64_t /* timestamp */, int /* report_id */, int /* rssi */, - int /* snr */, int /* retransmission_count */, - int /* packets_not_receive_count */, - int /* negative_acknowledgement_count */) {}, - .invoke_key_missing_cb = [](RawAddress /* bd_addr */) {}, + .invoke_adapter_state_changed_cb = [](bt_state_t /* state */) {}, + .invoke_adapter_properties_cb = [](bt_status_t /* status */, int /* num_properties */, + bt_property_t* /* properties */) {}, + .invoke_remote_device_properties_cb = [](bt_status_t /* status */, RawAddress /* bd_addr */, + int /* num_properties */, + bt_property_t* /* properties */) {}, + .invoke_device_found_cb = [](int /* num_properties */, bt_property_t* /* properties */) {}, + .invoke_discovery_state_changed_cb = [](bt_discovery_state_t /* state */) {}, + .invoke_pin_request_cb = [](RawAddress /* bd_addr */, bt_bdname_t /* bd_name */, + uint32_t /* cod */, bool /* min_16_digit */) {}, + .invoke_ssp_request_cb = [](RawAddress /* bd_addr */, + bt_ssp_variant_t /* pairing_variant */, + uint32_t /* pass_key */) {}, + .invoke_oob_data_request_cb = [](tBT_TRANSPORT /* t */, bool /* valid */, Octet16 /* c */, + Octet16 /* r */, RawAddress /* raw_address */, + uint8_t /* address_type */) {}, + .invoke_bond_state_changed_cb = [](bt_status_t /* status */, RawAddress /* bd_addr */, + bt_bond_state_t /* state */, int /* fail_reason */) {}, + .invoke_address_consolidate_cb = [](RawAddress /* main_bd_addr */, + RawAddress /* secondary_bd_addr */) {}, + .invoke_le_address_associate_cb = [](RawAddress /* main_bd_addr */, + RawAddress /* secondary_bd_addr */) {}, + .invoke_acl_state_changed_cb = + [](bt_status_t /* status */, RawAddress /* bd_addr */, bt_acl_state_t /* state */, + int /* transport_link_type */, bt_hci_error_code_t /* hci_reason */, + bt_conn_direction_t /* direction */, uint16_t /* acl_handle */) {}, + .invoke_thread_evt_cb = [](bt_cb_thread_evt /* event */) {}, + .invoke_le_test_mode_cb = [](bt_status_t /* status */, uint16_t /* count */) {}, + .invoke_energy_info_cb = [](bt_activity_energy_info /* energy_info */, + bt_uid_traffic_t* /* uid_data */) {}, + .invoke_link_quality_report_cb = + [](uint64_t /* timestamp */, int /* report_id */, int /* rssi */, int /* snr */, + int /* retransmission_count */, int /* packets_not_receive_count */, + int /* negative_acknowledgement_count */) {}, + .invoke_key_missing_cb = [](RawAddress /* bd_addr */) {}, }; // This interface lets us query for configuration properties of the stack that @@ -88,46 +79,39 @@ MockConfigInterface mock_config_interface; struct MockCodecInterface : public CodecInterface { MOCK_METHOD((void), initialize, (), ()); MOCK_METHOD((void), cleanup, (), ()); - MOCK_METHOD((uint32_t), encodePacket, (int16_t * input, uint8_t* output), ()); - MOCK_METHOD((bool), decodePacket, - (const uint8_t* i_buf, int16_t* o_buf, size_t out_len), ()); + MOCK_METHOD((uint32_t), encodePacket, (int16_t* input, uint8_t* output), ()); + MOCK_METHOD((bool), decodePacket, (const uint8_t* i_buf, int16_t* o_buf, size_t out_len), ()); }; MockCodecInterface mock_codec_msbcCodec; MockCodecInterface mock_codec_lc3Codec; HACK_ProfileInterface mock_HACK_profile_interface = { - .btif_hh_connect = [](const tAclLinkSpec& /* link_spec */) -> bt_status_t { - return BT_STATUS_SUCCESS; - }, - .btif_hh_virtual_unplug = [](const tAclLinkSpec& /* link_spec */) - -> bt_status_t { return BT_STATUS_SUCCESS; }, - .bta_hh_read_ssr_param = - [](const tAclLinkSpec& /* link_spec */, uint16_t* /* p_max_ssr_lat */, - uint16_t* /* p_min_ssr_tout */) -> tBTA_HH_STATUS { - return BTA_HH_OK; - }, + .btif_hh_connect = [](const tAclLinkSpec& /* link_spec */) -> bt_status_t { + return BT_STATUS_SUCCESS; + }, + .btif_hh_virtual_unplug = [](const tAclLinkSpec& /* link_spec */) -> bt_status_t { + return BT_STATUS_SUCCESS; + }, + .bta_hh_read_ssr_param = + [](const tAclLinkSpec& /* link_spec */, uint16_t* /* p_max_ssr_lat */, + uint16_t* /* p_min_ssr_tout */) -> tBTA_HH_STATUS { return BTA_HH_OK; }, - .btif_av_set_dynamic_audio_buffer_size = - [](uint8_t /* dynamic_audio_buffer_size */) {}, - .GetHearingAidDeviceCount = []() -> int { return 0; }, - .IsLeAudioClientRunning = []() -> bool { return false; }, - .AVRC_GetProfileVersion = []() -> uint16_t { return 0; }, + .btif_av_set_dynamic_audio_buffer_size = [](uint8_t /* dynamic_audio_buffer_size */) {}, + .GetHearingAidDeviceCount = []() -> int { return 0; }, + .IsLeAudioClientRunning = []() -> bool { return false; }, + .AVRC_GetProfileVersion = []() -> uint16_t { return 0; }, }; // This class defines the overall interface expected by bluetooth::core. struct MockCoreInterface : public CoreInterface { MockCoreInterface() - : CoreInterface(&mock_event_callbacks, &mock_config_interface, - &mock_codec_msbcCodec, &mock_codec_lc3Codec, - &mock_HACK_profile_interface) {} + : CoreInterface(&mock_event_callbacks, &mock_config_interface, &mock_codec_msbcCodec, + &mock_codec_lc3Codec, &mock_HACK_profile_interface) {} MOCK_METHOD((void), onBluetoothEnabled, (), ()); - MOCK_METHOD((bt_status_t), toggleProfile, - (tBTA_SERVICE_ID service_id, bool enable), ()); - MOCK_METHOD((void), removeDeviceFromProfiles, (const RawAddress& bd_addr), - ()); - MOCK_METHOD((void), onLinkDown, - (const RawAddress& bd_addr, tBT_TRANSPORT transport), ()); + MOCK_METHOD((bt_status_t), toggleProfile, (tBTA_SERVICE_ID service_id, bool enable), ()); + MOCK_METHOD((void), removeDeviceFromProfiles, (const RawAddress& bd_addr), ()); + MOCK_METHOD((void), onLinkDown, (const RawAddress& bd_addr, tBT_TRANSPORT transport), ()); }; } // namespace testing diff --git a/system/btif/include/stack_manager_t.h b/system/btif/include/stack_manager_t.h index 6bdf1c02dd7..0e7f00dfe2e 100644 --- a/system/btif/include/stack_manager_t.h +++ b/system/btif/include/stack_manager_t.h @@ -28,8 +28,8 @@ using ProfileStopCallback = void(); typedef struct { void (*init_stack)(bluetooth::core::CoreInterface*); - void (*start_up_stack_async)(bluetooth::core::CoreInterface*, - ProfileStartCallback, ProfileStopCallback); + void (*start_up_stack_async)(bluetooth::core::CoreInterface*, ProfileStartCallback, + ProfileStopCallback); void (*shut_down_stack_async)(ProfileStopCallback); void (*clean_up_stack)(ProfileStopCallback); void (*start_up_rust_module_async)(); diff --git a/system/btif/src/bluetooth.cc b/system/btif/src/bluetooth.cc index 5c377435f98..6bf35f5b4df 100644 --- a/system/btif/src/bluetooth.cc +++ b/system/btif/src/bluetooth.cc @@ -184,7 +184,7 @@ extern void bta_gatt_client_dump(int fd); ******************************************************************************/ struct ConfigInterfaceImpl : bluetooth::core::ConfigInterface { - ConfigInterfaceImpl() : bluetooth::core::ConfigInterface(){}; + ConfigInterfaceImpl() : bluetooth::core::ConfigInterface() {} bool isRestrictedMode() override { return is_restricted_mode(); } @@ -193,10 +193,9 @@ struct ConfigInterfaceImpl : bluetooth::core::ConfigInterface { char value_dis[PROPERTY_VALUE_MAX] = {'\0'}; osi_property_get("ro.bluetooth.a2dp_offload.supported", value_sup, "false"); - osi_property_get("persist.bluetooth.a2dp_offload.disabled", value_dis, - "false"); + osi_property_get("persist.bluetooth.a2dp_offload.disabled", value_dis, "false"); auto a2dp_offload_enabled = - (strcmp(value_sup, "true") == 0) && (strcmp(value_dis, "false") == 0); + (strcmp(value_sup, "true") == 0) && (strcmp(value_dis, "false") == 0); log::verbose("a2dp_offload.enable = {}", a2dp_offload_enabled); return a2dp_offload_enabled; @@ -207,7 +206,7 @@ struct ConfigInterfaceImpl : bluetooth::core::ConfigInterface { // TODO(aryarahul): remove unnecessary indirection through hfp_msbc_*.cc struct MSBCCodec : bluetooth::core::CodecInterface { - MSBCCodec() : bluetooth::core::CodecInterface(){}; + MSBCCodec() : bluetooth::core::CodecInterface() {} void initialize() override { hfp_msbc_decoder_init(); @@ -229,7 +228,7 @@ struct MSBCCodec : bluetooth::core::CodecInterface { }; struct LC3Codec : bluetooth::core::CodecInterface { - LC3Codec() : bluetooth::core::CodecInterface(){}; + LC3Codec() : bluetooth::core::CodecInterface() {} void initialize() override { hfp_lc3_decoder_init(); @@ -295,8 +294,7 @@ struct CoreInterfaceImpl : bluetooth::core::CoreInterface { */ } break; default: - log::error("Unknown service {} being {}", service_id, - (enable) ? "enabled" : "disabled"); + log::error("Unknown service {} being {}", service_id, (enable) ? "enabled" : "disabled"); return BT_STATUS_FAIL; } return BT_STATUS_SUCCESS; @@ -317,11 +315,13 @@ struct CoreInterfaceImpl : bluetooth::core::CoreInterface { #endif btif_hearing_aid_get_interface()->RemoveDevice(bd_addr); - if (bluetooth::csis::CsisClient::IsCsisClientRunning()) + if (bluetooth::csis::CsisClient::IsCsisClientRunning()) { btif_csis_client_get_interface()->RemoveDevice(bd_addr); + } - if (LeAudioClient::IsLeAudioClientRunning()) + if (LeAudioClient::IsLeAudioClientRunning()) { btif_le_audio_get_interface()->RemoveDevice(bd_addr); + } if (VolumeControl::IsVolumeControlRunning()) { btif_volume_control_get_interface()->RemoveDevice(bd_addr); @@ -329,7 +329,9 @@ struct CoreInterfaceImpl : bluetooth::core::CoreInterface { } void onLinkDown(const RawAddress& bd_addr, tBT_TRANSPORT transport) override { - if (transport != BT_TRANSPORT_BR_EDR) return; + if (transport != BT_TRANSPORT_BR_EDR) { + return; + } if (com::android::bluetooth::flags::a2dp_concurrent_source_sink()) { btif_av_acl_disconnected(bd_addr, A2dpType::kSource); @@ -342,42 +344,41 @@ struct CoreInterfaceImpl : bluetooth::core::CoreInterface { static bluetooth::core::CoreInterface* CreateInterfaceToProfiles() { static bluetooth::core::EventCallbacks eventCallbacks{ - .invoke_adapter_state_changed_cb = invoke_adapter_state_changed_cb, - .invoke_adapter_properties_cb = invoke_adapter_properties_cb, - .invoke_remote_device_properties_cb = invoke_remote_device_properties_cb, - .invoke_device_found_cb = invoke_device_found_cb, - .invoke_discovery_state_changed_cb = invoke_discovery_state_changed_cb, - .invoke_pin_request_cb = invoke_pin_request_cb, - .invoke_ssp_request_cb = invoke_ssp_request_cb, - .invoke_oob_data_request_cb = invoke_oob_data_request_cb, - .invoke_bond_state_changed_cb = invoke_bond_state_changed_cb, - .invoke_address_consolidate_cb = invoke_address_consolidate_cb, - .invoke_le_address_associate_cb = invoke_le_address_associate_cb, - .invoke_acl_state_changed_cb = invoke_acl_state_changed_cb, - .invoke_thread_evt_cb = invoke_thread_evt_cb, - .invoke_le_test_mode_cb = invoke_le_test_mode_cb, - .invoke_energy_info_cb = invoke_energy_info_cb, - .invoke_link_quality_report_cb = invoke_link_quality_report_cb, - .invoke_key_missing_cb = invoke_key_missing_cb, + .invoke_adapter_state_changed_cb = invoke_adapter_state_changed_cb, + .invoke_adapter_properties_cb = invoke_adapter_properties_cb, + .invoke_remote_device_properties_cb = invoke_remote_device_properties_cb, + .invoke_device_found_cb = invoke_device_found_cb, + .invoke_discovery_state_changed_cb = invoke_discovery_state_changed_cb, + .invoke_pin_request_cb = invoke_pin_request_cb, + .invoke_ssp_request_cb = invoke_ssp_request_cb, + .invoke_oob_data_request_cb = invoke_oob_data_request_cb, + .invoke_bond_state_changed_cb = invoke_bond_state_changed_cb, + .invoke_address_consolidate_cb = invoke_address_consolidate_cb, + .invoke_le_address_associate_cb = invoke_le_address_associate_cb, + .invoke_acl_state_changed_cb = invoke_acl_state_changed_cb, + .invoke_thread_evt_cb = invoke_thread_evt_cb, + .invoke_le_test_mode_cb = invoke_le_test_mode_cb, + .invoke_energy_info_cb = invoke_energy_info_cb, + .invoke_link_quality_report_cb = invoke_link_quality_report_cb, + .invoke_key_missing_cb = invoke_key_missing_cb, }; static bluetooth::core::HACK_ProfileInterface profileInterface{ - // HID - .btif_hh_connect = btif_hh_connect, - .btif_hh_virtual_unplug = btif_hh_virtual_unplug, - .bta_hh_read_ssr_param = bta_hh_read_ssr_param, + // HID + .btif_hh_connect = btif_hh_connect, + .btif_hh_virtual_unplug = btif_hh_virtual_unplug, + .bta_hh_read_ssr_param = bta_hh_read_ssr_param, - // AVDTP - .btif_av_set_dynamic_audio_buffer_size = - btif_av_set_dynamic_audio_buffer_size, + // AVDTP + .btif_av_set_dynamic_audio_buffer_size = btif_av_set_dynamic_audio_buffer_size, - // ASHA - .GetHearingAidDeviceCount = HearingAid::GetDeviceCount, + // ASHA + .GetHearingAidDeviceCount = HearingAid::GetDeviceCount, - // LE Audio - .IsLeAudioClientRunning = LeAudioClient::IsLeAudioClientRunning, + // LE Audio + .IsLeAudioClientRunning = LeAudioClient::IsLeAudioClientRunning, - // AVRCP - .AVRC_GetProfileVersion = AVRC_GetProfileVersion, + // AVRCP + .AVRC_GetProfileVersion = AVRC_GetProfileVersion, }; static auto configInterface = ConfigInterfaceImpl(); @@ -385,8 +386,8 @@ static bluetooth::core::CoreInterface* CreateInterfaceToProfiles() { static auto lc3CodecInterface = LC3Codec(); static auto interfaceForCore = - CoreInterfaceImpl(&eventCallbacks, &configInterface, &msbcCodecInterface, - &lc3CodecInterface, &profileInterface); + CoreInterfaceImpl(&eventCallbacks, &configInterface, &msbcCodecInterface, + &lc3CodecInterface, &profileInterface); return &interfaceForCore; } @@ -395,9 +396,7 @@ static bluetooth::core::CoreInterface* CreateInterfaceToProfiles() { ******************************************************************************/ static bool interface_ready(void) { return bt_hal_cbacks != NULL; } -static void set_hal_cbacks(bt_callbacks_t* callbacks) { - bt_hal_cbacks = callbacks; -} +static void set_hal_cbacks(bt_callbacks_t* callbacks) { bt_hal_cbacks = callbacks; } static bool is_profile(const char* p1, const char* p2) { log::assert_that(p1 != nullptr, "assert failed: p1 != nullptr"); @@ -411,34 +410,32 @@ static bool is_profile(const char* p1, const char* p2) { * ****************************************************************************/ -static int init(bt_callbacks_t* callbacks, bool start_restricted, - bool is_common_criteria_mode, int config_compare_result, - const char** init_flags, bool is_atv, +static int init(bt_callbacks_t* callbacks, bool start_restricted, bool is_common_criteria_mode, + int config_compare_result, const char** init_flags, bool is_atv, const char* user_data_directory) { (void)user_data_directory; log::info( - "start restricted = {} ; common criteria mode = {}, config compare " - "result = {}", - start_restricted, is_common_criteria_mode, config_compare_result); + "start restricted = {} ; common criteria mode = {}, config compare " + "result = {}", + start_restricted, is_common_criteria_mode, config_compare_result); bluetooth::common::InitFlags::Load(init_flags); - if (interface_ready()) return BT_STATUS_DONE; + if (interface_ready()) { + return BT_STATUS_DONE; + } set_hal_cbacks(callbacks); restricted_mode = start_restricted; bluetooth::os::ParameterProvider::SetBtKeystoreInterface( - bluetooth::bluetooth_keystore::getBluetoothKeystoreInterface()); - bluetooth::os::ParameterProvider::SetCommonCriteriaMode( - is_common_criteria_mode); + bluetooth::bluetooth_keystore::getBluetoothKeystoreInterface()); + bluetooth::os::ParameterProvider::SetCommonCriteriaMode(is_common_criteria_mode); if (is_bluetooth_uid() && is_common_criteria_mode) { - bluetooth::os::ParameterProvider::SetCommonCriteriaConfigCompareResult( - config_compare_result); + bluetooth::os::ParameterProvider::SetCommonCriteriaConfigCompareResult(config_compare_result); } else { - bluetooth::os::ParameterProvider::SetCommonCriteriaConfigCompareResult( - CONFIG_COMPARE_ALL_PASS); + bluetooth::os::ParameterProvider::SetCommonCriteriaConfigCompareResult(CONFIG_COMPARE_ALL_PASS); } is_local_device_atv = is_atv; @@ -468,49 +465,41 @@ static void stop_profiles() { } static int enable() { - if (!interface_ready()) return BT_STATUS_NOT_READY; + if (!interface_ready()) { + return BT_STATUS_NOT_READY; + } - stack_manager_get_interface()->start_up_stack_async( - CreateInterfaceToProfiles(), &start_profiles, &stop_profiles); + stack_manager_get_interface()->start_up_stack_async(CreateInterfaceToProfiles(), &start_profiles, + &stop_profiles); return BT_STATUS_SUCCESS; } static int disable(void) { - if (!interface_ready()) return BT_STATUS_NOT_READY; + if (!interface_ready()) { + return BT_STATUS_NOT_READY; + } stack_manager_get_interface()->shut_down_stack_async(&stop_profiles); return BT_STATUS_SUCCESS; } -static void cleanup(void) { - stack_manager_get_interface()->clean_up_stack(&stop_profiles); -} +static void cleanup(void) { stack_manager_get_interface()->clean_up_stack(&stop_profiles); } -static void start_rust_module(void) { - stack_manager_get_interface()->start_up_rust_module_async(); -} +static void start_rust_module(void) { stack_manager_get_interface()->start_up_rust_module_async(); } -static void stop_rust_module(void) { - stack_manager_get_interface()->shut_down_rust_module_async(); -} +static void stop_rust_module(void) { stack_manager_get_interface()->shut_down_rust_module_async(); } bool is_restricted_mode() { return restricted_mode; } -static bool get_wbs_supported() { - return hfp_hal_interface::get_wbs_supported(); -} +static bool get_wbs_supported() { return hfp_hal_interface::get_wbs_supported(); } -static bool get_swb_supported() { - return hfp_hal_interface::get_swb_supported(); -} +static bool get_swb_supported() { return hfp_hal_interface::get_swb_supported(); } static bool is_coding_format_supported(esco_coding_format_t coding_format) { return hfp_hal_interface::is_coding_format_supported(coding_format); } -bool is_common_criteria_mode() { - return is_bluetooth_uid() && common_criteria_mode; -} +bool is_common_criteria_mode() { return is_bluetooth_uid() && common_criteria_mode; } // if common criteria mode disable, will always return // CONFIG_COMPARE_ALL_PASS(0b11) indicate don't check config checksum. int get_common_criteria_config_compare_result() { @@ -521,7 +510,9 @@ int get_common_criteria_config_compare_result() { bool is_atv_device() { return is_local_device_atv; } static int get_adapter_properties(void) { - if (!btif_is_enabled()) return BT_STATUS_NOT_READY; + if (!btif_is_enabled()) { + return BT_STATUS_NOT_READY; + } do_in_main_thread(FROM_HERE, base::BindOnce(btif_get_adapter_properties)); return BT_STATUS_SUCCESS; @@ -529,9 +520,9 @@ static int get_adapter_properties(void) { static int get_adapter_property(bt_property_type_t type) { /* Allow get_adapter_property only for BDADDR and BDNAME if BT is disabled */ - if (!btif_is_enabled() && (type != BT_PROPERTY_BDADDR) && - (type != BT_PROPERTY_BDNAME)) + if (!btif_is_enabled() && (type != BT_PROPERTY_BDADDR) && (type != BT_PROPERTY_BDNAME)) { return BT_STATUS_NOT_READY; + } do_in_main_thread(FROM_HERE, base::BindOnce(btif_get_adapter_property, type)); return BT_STATUS_SUCCESS; @@ -542,7 +533,9 @@ static void set_scan_mode(bt_scan_mode_t mode) { } static int set_adapter_property(const bt_property_t* property) { - if (!btif_is_enabled()) return BT_STATUS_NOT_READY; + if (!btif_is_enabled()) { + return BT_STATUS_NOT_READY; + } switch (property->type) { case BT_PROPERTY_BDNAME: @@ -554,107 +547,125 @@ static int set_adapter_property(const bt_property_t* property) { } do_in_main_thread(FROM_HERE, base::BindOnce( - [](bt_property_t* property) { - btif_set_adapter_property(property); - osi_free(property); - }, - property_deep_copy(property))); + [](bt_property_t* property) { + btif_set_adapter_property(property); + osi_free(property); + }, + property_deep_copy(property))); return BT_STATUS_SUCCESS; } int get_remote_device_properties(RawAddress* remote_addr) { - if (!btif_is_enabled()) return BT_STATUS_NOT_READY; + if (!btif_is_enabled()) { + return BT_STATUS_NOT_READY; + } - do_in_main_thread(FROM_HERE, base::BindOnce(btif_get_remote_device_properties, - *remote_addr)); + do_in_main_thread(FROM_HERE, base::BindOnce(btif_get_remote_device_properties, *remote_addr)); return BT_STATUS_SUCCESS; } -int get_remote_device_property(RawAddress* remote_addr, - bt_property_type_t type) { - if (!btif_is_enabled()) return BT_STATUS_NOT_READY; +int get_remote_device_property(RawAddress* remote_addr, bt_property_type_t type) { + if (!btif_is_enabled()) { + return BT_STATUS_NOT_READY; + } - do_in_main_thread(FROM_HERE, base::BindOnce(btif_get_remote_device_property, - *remote_addr, type)); + do_in_main_thread(FROM_HERE, base::BindOnce(btif_get_remote_device_property, *remote_addr, type)); return BT_STATUS_SUCCESS; } -int set_remote_device_property(RawAddress* remote_addr, - const bt_property_t* property) { - if (!btif_is_enabled()) return BT_STATUS_NOT_READY; +int set_remote_device_property(RawAddress* remote_addr, const bt_property_t* property) { + if (!btif_is_enabled()) { + return BT_STATUS_NOT_READY; + } - do_in_main_thread( - FROM_HERE, base::BindOnce( - [](RawAddress remote_addr, bt_property_t* property) { - btif_set_remote_device_property(&remote_addr, property); - osi_free(property); - }, - *remote_addr, property_deep_copy(property))); + do_in_main_thread(FROM_HERE, base::BindOnce( + [](RawAddress remote_addr, bt_property_t* property) { + btif_set_remote_device_property(&remote_addr, property); + osi_free(property); + }, + *remote_addr, property_deep_copy(property))); return BT_STATUS_SUCCESS; } int get_remote_services(RawAddress* remote_addr, int transport) { - if (!interface_ready()) return BT_STATUS_NOT_READY; + if (!interface_ready()) { + return BT_STATUS_NOT_READY; + } - do_in_main_thread(FROM_HERE, base::BindOnce(btif_dm_get_remote_services, - *remote_addr, transport)); + do_in_main_thread(FROM_HERE, + base::BindOnce(btif_dm_get_remote_services, *remote_addr, transport)); return BT_STATUS_SUCCESS; } static int start_discovery(void) { - if (!interface_ready()) return BT_STATUS_NOT_READY; + if (!interface_ready()) { + return BT_STATUS_NOT_READY; + } do_in_main_thread(FROM_HERE, base::BindOnce(btif_dm_start_discovery)); return BT_STATUS_SUCCESS; } static int cancel_discovery(void) { - if (!interface_ready()) return BT_STATUS_NOT_READY; + if (!interface_ready()) { + return BT_STATUS_NOT_READY; + } do_in_main_thread(FROM_HERE, base::BindOnce(btif_dm_cancel_discovery)); return BT_STATUS_SUCCESS; } static int create_bond(const RawAddress* bd_addr, int transport) { - if (!interface_ready()) return BT_STATUS_NOT_READY; - if (btif_dm_pairing_is_busy()) return BT_STATUS_BUSY; + if (!interface_ready()) { + return BT_STATUS_NOT_READY; + } + if (btif_dm_pairing_is_busy()) { + return BT_STATUS_BUSY; + } - do_in_main_thread(FROM_HERE, - base::BindOnce(btif_dm_create_bond, *bd_addr, transport)); + do_in_main_thread(FROM_HERE, base::BindOnce(btif_dm_create_bond, *bd_addr, transport)); return BT_STATUS_SUCCESS; } static int create_bond_le(const RawAddress* bd_addr, uint8_t addr_type) { - if (!interface_ready()) return BT_STATUS_NOT_READY; - if (btif_dm_pairing_is_busy()) return BT_STATUS_BUSY; + if (!interface_ready()) { + return BT_STATUS_NOT_READY; + } + if (btif_dm_pairing_is_busy()) { + return BT_STATUS_BUSY; + } - do_in_main_thread( - FROM_HERE, base::BindOnce(btif_dm_create_bond_le, *bd_addr, addr_type)); + do_in_main_thread(FROM_HERE, base::BindOnce(btif_dm_create_bond_le, *bd_addr, addr_type)); return BT_STATUS_SUCCESS; } static int create_bond_out_of_band(const RawAddress* bd_addr, int transport, - const bt_oob_data_t* p192_data, - const bt_oob_data_t* p256_data) { - if (!interface_ready()) return BT_STATUS_NOT_READY; - if (btif_dm_pairing_is_busy()) return BT_STATUS_BUSY; + const bt_oob_data_t* p192_data, const bt_oob_data_t* p256_data) { + if (!interface_ready()) { + return BT_STATUS_NOT_READY; + } + if (btif_dm_pairing_is_busy()) { + return BT_STATUS_BUSY; + } - do_in_main_thread(FROM_HERE, - base::BindOnce(btif_dm_create_bond_out_of_band, *bd_addr, - transport, *p192_data, *p256_data)); + do_in_main_thread(FROM_HERE, base::BindOnce(btif_dm_create_bond_out_of_band, *bd_addr, transport, + *p192_data, *p256_data)); return BT_STATUS_SUCCESS; } static int generate_local_oob_data(tBT_TRANSPORT transport) { log::info(""); - if (!interface_ready()) return BT_STATUS_NOT_READY; + if (!interface_ready()) { + return BT_STATUS_NOT_READY; + } - return do_in_main_thread( - FROM_HERE, base::BindOnce(btif_dm_generate_local_oob_data, transport)); + return do_in_main_thread(FROM_HERE, base::BindOnce(btif_dm_generate_local_oob_data, transport)); } static int cancel_bond(const RawAddress* bd_addr) { - if (!interface_ready()) return BT_STATUS_NOT_READY; + if (!interface_ready()) { + return BT_STATUS_NOT_READY; + } do_in_main_thread(FROM_HERE, base::BindOnce(btif_dm_cancel_bond, *bd_addr)); return BT_STATUS_SUCCESS; @@ -666,22 +677,30 @@ static int remove_bond(const RawAddress* bd_addr) { return BT_STATUS_SUCCESS; } - if (!interface_ready()) return BT_STATUS_NOT_READY; + if (!interface_ready()) { + return BT_STATUS_NOT_READY; + } do_in_main_thread(FROM_HERE, base::BindOnce(btif_dm_remove_bond, *bd_addr)); return BT_STATUS_SUCCESS; } static bool pairing_is_busy() { - if (btif_dm_pairing_is_busy()) return true; + if (btif_dm_pairing_is_busy()) { + return true; + } return false; } static int get_connection_state(const RawAddress* bd_addr) { - if (!interface_ready()) return 0; + if (!interface_ready()) { + return 0; + } - if (bd_addr == nullptr) return 0; + if (bd_addr == nullptr) { + return 0; + } return btif_dm_get_connection_state(*bd_addr); } @@ -689,30 +708,37 @@ static int get_connection_state(const RawAddress* bd_addr) { static int pin_reply(const RawAddress* bd_addr, uint8_t accept, uint8_t pin_len, bt_pin_code_t* pin_code) { bt_pin_code_t tmp_pin_code; - if (!interface_ready()) return BT_STATUS_NOT_READY; + if (!interface_ready()) { + return BT_STATUS_NOT_READY; + } if (pin_code == nullptr || pin_len > PIN_CODE_LEN) { return BT_STATUS_PARM_INVALID; } memcpy(&tmp_pin_code, pin_code, pin_len); - do_in_main_thread(FROM_HERE, base::BindOnce(btif_dm_pin_reply, *bd_addr, - accept, pin_len, tmp_pin_code)); + do_in_main_thread(FROM_HERE, + base::BindOnce(btif_dm_pin_reply, *bd_addr, accept, pin_len, tmp_pin_code)); return BT_STATUS_SUCCESS; } -static int ssp_reply(const RawAddress* bd_addr, bt_ssp_variant_t variant, - uint8_t accept, uint32_t /* passkey */) { - if (!interface_ready()) return BT_STATUS_NOT_READY; - if (variant == BT_SSP_VARIANT_PASSKEY_ENTRY) return BT_STATUS_PARM_INVALID; +static int ssp_reply(const RawAddress* bd_addr, bt_ssp_variant_t variant, uint8_t accept, + uint32_t /* passkey */) { + if (!interface_ready()) { + return BT_STATUS_NOT_READY; + } + if (variant == BT_SSP_VARIANT_PASSKEY_ENTRY) { + return BT_STATUS_PARM_INVALID; + } - do_in_main_thread( - FROM_HERE, base::BindOnce(btif_dm_ssp_reply, *bd_addr, variant, accept)); + do_in_main_thread(FROM_HERE, base::BindOnce(btif_dm_ssp_reply, *bd_addr, variant, accept)); return BT_STATUS_SUCCESS; } static int read_energy_info() { - if (!interface_ready()) return BT_STATUS_NOT_READY; + if (!interface_ready()) { + return BT_STATUS_NOT_READY; + } do_in_main_thread(FROM_HERE, base::BindOnce(btif_dm_read_energy_info)); return BT_STATUS_SUCCESS; @@ -720,7 +746,9 @@ static int read_energy_info() { static int clear_event_filter() { log::verbose(""); - if (!interface_ready()) return BT_STATUS_NOT_READY; + if (!interface_ready()) { + return BT_STATUS_NOT_READY; + } do_in_main_thread(FROM_HERE, base::BindOnce(btif_dm_clear_event_filter)); return BT_STATUS_SUCCESS; @@ -728,7 +756,9 @@ static int clear_event_filter() { static int clear_event_mask() { log::verbose(""); - if (!interface_ready()) return BT_STATUS_NOT_READY; + if (!interface_ready()) { + return BT_STATUS_NOT_READY; + } do_in_main_thread(FROM_HERE, base::BindOnce(btif_dm_clear_event_mask)); return BT_STATUS_SUCCESS; @@ -736,16 +766,19 @@ static int clear_event_mask() { static int clear_filter_accept_list() { log::verbose(""); - if (!interface_ready()) return BT_STATUS_NOT_READY; + if (!interface_ready()) { + return BT_STATUS_NOT_READY; + } - do_in_main_thread(FROM_HERE, - base::BindOnce(btif_dm_clear_filter_accept_list)); + do_in_main_thread(FROM_HERE, base::BindOnce(btif_dm_clear_filter_accept_list)); return BT_STATUS_SUCCESS; } static int disconnect_all_acls() { log::verbose(""); - if (!interface_ready()) return BT_STATUS_NOT_READY; + if (!interface_ready()) { + return BT_STATUS_NOT_READY; + } do_in_main_thread(FROM_HERE, base::BindOnce(btif_dm_disconnect_all_acls)); return BT_STATUS_SUCCESS; @@ -754,38 +787,41 @@ static int disconnect_all_acls() { static void le_rand_btif_cb(uint64_t random_number) { log::verbose(""); do_in_jni_thread(base::BindOnce( - [](uint64_t random) { HAL_CBACK(bt_hal_cbacks, le_rand_cb, random); }, - random_number)); + [](uint64_t random) { HAL_CBACK(bt_hal_cbacks, le_rand_cb, random); }, random_number)); } static int le_rand() { log::verbose(""); - if (!interface_ready()) return BT_STATUS_NOT_READY; + if (!interface_ready()) { + return BT_STATUS_NOT_READY; + } - do_in_main_thread( - FROM_HERE, base::BindOnce(btif_dm_le_rand, - get_main_thread()->BindOnce(&le_rand_btif_cb))); + do_in_main_thread(FROM_HERE, + base::BindOnce(btif_dm_le_rand, get_main_thread()->BindOnce(&le_rand_btif_cb))); return BT_STATUS_SUCCESS; } static int set_event_filter_inquiry_result_all_devices() { - if (!interface_ready()) return BT_STATUS_NOT_READY; - do_in_main_thread( - FROM_HERE, - base::BindOnce(btif_dm_set_event_filter_inquiry_result_all_devices)); + if (!interface_ready()) { + return BT_STATUS_NOT_READY; + } + do_in_main_thread(FROM_HERE, base::BindOnce(btif_dm_set_event_filter_inquiry_result_all_devices)); return BT_STATUS_SUCCESS; } static int set_default_event_mask_except(uint64_t mask, uint64_t le_mask) { - if (!interface_ready()) return BT_STATUS_NOT_READY; - do_in_main_thread( - FROM_HERE, - base::BindOnce(btif_dm_set_default_event_mask_except, mask, le_mask)); + if (!interface_ready()) { + return BT_STATUS_NOT_READY; + } + do_in_main_thread(FROM_HERE, + base::BindOnce(btif_dm_set_default_event_mask_except, mask, le_mask)); return BT_STATUS_SUCCESS; } static int restore_filter_accept_list() { - if (!interface_ready()) return BT_STATUS_NOT_READY; + if (!interface_ready()) { + return BT_STATUS_NOT_READY; + } // TODO(b/260922031) - When restoring the filter accept list after a system // suspend, we need to re-arm the LE connections that had `is_direct=False`. // This should be the list of bonded devices and potentially any GATT @@ -793,26 +829,28 @@ static int restore_filter_accept_list() { // devices. auto le_hid_addrs = btif_storage_get_le_hid_devices(); do_in_main_thread(FROM_HERE, - base::BindOnce(btif_dm_restore_filter_accept_list, - std::move(le_hid_addrs))); + base::BindOnce(btif_dm_restore_filter_accept_list, std::move(le_hid_addrs))); return BT_STATUS_SUCCESS; } static int allow_wake_by_hid() { - if (!interface_ready()) return BT_STATUS_NOT_READY; + if (!interface_ready()) { + return BT_STATUS_NOT_READY; + } auto le_hid_addrs = btif_storage_get_le_hid_devices(); auto classic_hid_addrs = btif_storage_get_wake_capable_classic_hid_devices(); - do_in_main_thread(FROM_HERE, base::BindOnce(btif_dm_allow_wake_by_hid, - std::move(classic_hid_addrs), - std::move(le_hid_addrs))); + do_in_main_thread(FROM_HERE, + base::BindOnce(btif_dm_allow_wake_by_hid, std::move(classic_hid_addrs), + std::move(le_hid_addrs))); return BT_STATUS_SUCCESS; } static int set_event_filter_connection_setup_all_devices() { - if (!interface_ready()) return BT_STATUS_NOT_READY; - do_in_main_thread( - FROM_HERE, - base::BindOnce(btif_dm_set_event_filter_connection_setup_all_devices)); + if (!interface_ready()) { + return BT_STATUS_NOT_READY; + } + do_in_main_thread(FROM_HERE, + base::BindOnce(btif_dm_set_event_filter_connection_setup_all_devices)); return BT_STATUS_SUCCESS; } @@ -858,8 +896,7 @@ static int get_remote_pbap_pce_version(const RawAddress* bd_addr) { // Read and restore the PCE version from local storage uint16_t pce_version = 0; size_t version_value_size = sizeof(pce_version); - if (!btif_config_get_bin(bd_addr->ToString(), - BTIF_STORAGE_KEY_PBAP_PCE_VERSION, + if (!btif_config_get_bin(bd_addr->ToString(), BTIF_STORAGE_KEY_PBAP_PCE_VERSION, (uint8_t*)&pce_version, &version_value_size)) { log::warn("Failed to read cached peer PCE version for {}", *bd_addr); } @@ -867,8 +904,7 @@ static int get_remote_pbap_pce_version(const RawAddress* bd_addr) { } static bool pbap_pse_dynamic_version_upgrade_is_enabled() { - if (bluetooth::common::init_flags:: - pbap_pse_dynamic_version_upgrade_is_enabled()) { + if (bluetooth::common::init_flags::pbap_pse_dynamic_version_upgrade_is_enabled()) { return true; } log::warn("PBAP PSE dynamic version upgrade is not enabled"); @@ -879,105 +915,136 @@ static const void* get_profile_interface(const char* profile_id) { log::info("id = {}", profile_id); /* sanity check */ - if (!interface_ready()) return NULL; + if (!interface_ready()) { + return NULL; + } /* check for supported profile interfaces */ - if (is_profile(profile_id, BT_PROFILE_HANDSFREE_ID)) + if (is_profile(profile_id, BT_PROFILE_HANDSFREE_ID)) { return bluetooth::headset::GetInterface(); + } - if (is_profile(profile_id, BT_PROFILE_HANDSFREE_CLIENT_ID)) + if (is_profile(profile_id, BT_PROFILE_HANDSFREE_CLIENT_ID)) { return btif_hf_client_get_interface(); + } - if (is_profile(profile_id, BT_PROFILE_SOCKETS_ID)) + if (is_profile(profile_id, BT_PROFILE_SOCKETS_ID)) { return btif_sock_get_interface(); + } - if (is_profile(profile_id, BT_PROFILE_PAN_ID)) + if (is_profile(profile_id, BT_PROFILE_PAN_ID)) { return btif_pan_get_interface(); + } - if (is_profile(profile_id, BT_PROFILE_HIDHOST_ID)) + if (is_profile(profile_id, BT_PROFILE_HIDHOST_ID)) { return btif_hh_get_interface(); + } - if (is_profile(profile_id, BT_PROFILE_HIDDEV_ID)) + if (is_profile(profile_id, BT_PROFILE_HIDDEV_ID)) { return btif_hd_get_interface(); + } - if (is_profile(profile_id, BT_PROFILE_SDP_CLIENT_ID)) + if (is_profile(profile_id, BT_PROFILE_SDP_CLIENT_ID)) { return btif_sdp_get_interface(); + } - if (is_profile(profile_id, BT_PROFILE_GATT_ID)) + if (is_profile(profile_id, BT_PROFILE_GATT_ID)) { return btif_gatt_get_interface(); + } - if (is_profile(profile_id, BT_PROFILE_AV_RC_ID)) + if (is_profile(profile_id, BT_PROFILE_AV_RC_ID)) { return btif_rc_get_interface(); + } - if (is_profile(profile_id, BT_PROFILE_AV_RC_CTRL_ID)) + if (is_profile(profile_id, BT_PROFILE_AV_RC_CTRL_ID)) { return btif_rc_ctrl_get_interface(); + } - if (is_profile(profile_id, BT_PROFILE_HEARING_AID_ID)) + if (is_profile(profile_id, BT_PROFILE_HEARING_AID_ID)) { return btif_hearing_aid_get_interface(); + } - if (is_profile(profile_id, BT_PROFILE_HAP_CLIENT_ID)) + if (is_profile(profile_id, BT_PROFILE_HAP_CLIENT_ID)) { return btif_has_client_get_interface(); + } - if (is_profile(profile_id, BT_KEYSTORE_ID)) + if (is_profile(profile_id, BT_KEYSTORE_ID)) { return bluetooth::bluetooth_keystore::getBluetoothKeystoreInterface(); + } - if (is_profile(profile_id, BT_PROFILE_LE_AUDIO_ID)) + if (is_profile(profile_id, BT_PROFILE_LE_AUDIO_ID)) { return btif_le_audio_get_interface(); + } - if (is_profile(profile_id, BT_PROFILE_LE_AUDIO_BROADCASTER_ID)) + if (is_profile(profile_id, BT_PROFILE_LE_AUDIO_BROADCASTER_ID)) { return btif_le_audio_broadcaster_get_interface(); + } - if (is_profile(profile_id, BT_PROFILE_VC_ID)) + if (is_profile(profile_id, BT_PROFILE_VC_ID)) { return btif_volume_control_get_interface(); + } - if (is_profile(profile_id, BT_PROFILE_CSIS_CLIENT_ID)) + if (is_profile(profile_id, BT_PROFILE_CSIS_CLIENT_ID)) { return btif_csis_client_get_interface(); + } - if (is_profile(profile_id, BT_BQR_ID)) + if (is_profile(profile_id, BT_BQR_ID)) { return bluetooth::bqr::getBluetoothQualityReportInterface(); + } return NULL; } int dut_mode_configure(uint8_t enable) { - if (!interface_ready()) return BT_STATUS_NOT_READY; - if (!stack_manager_get_interface()->get_stack_is_running()) + if (!interface_ready()) { return BT_STATUS_NOT_READY; + } + if (!stack_manager_get_interface()->get_stack_is_running()) { + return BT_STATUS_NOT_READY; + } do_in_main_thread(FROM_HERE, base::BindOnce(btif_dut_mode_configure, enable)); return BT_STATUS_SUCCESS; } int dut_mode_send(uint16_t opcode, uint8_t* buf, uint8_t len) { - if (!interface_ready()) return BT_STATUS_NOT_READY; - if (!btif_is_dut_mode()) return BT_STATUS_UNEXPECTED_STATE; + if (!interface_ready()) { + return BT_STATUS_NOT_READY; + } + if (!btif_is_dut_mode()) { + return BT_STATUS_UNEXPECTED_STATE; + } uint8_t* copy = (uint8_t*)osi_calloc(len); memcpy(copy, buf, len); - do_in_main_thread(FROM_HERE, - base::BindOnce( - [](uint16_t opcode, uint8_t* buf, uint8_t len) { - btif_dut_mode_send(opcode, buf, len); - osi_free(buf); - }, - opcode, copy, len)); + do_in_main_thread(FROM_HERE, base::BindOnce( + [](uint16_t opcode, uint8_t* buf, uint8_t len) { + btif_dut_mode_send(opcode, buf, len); + osi_free(buf); + }, + opcode, copy, len)); return BT_STATUS_SUCCESS; } int le_test_mode(uint16_t opcode, uint8_t* buf, uint8_t len) { - if (!interface_ready()) return BT_STATUS_NOT_READY; + if (!interface_ready()) { + return BT_STATUS_NOT_READY; + } switch (opcode) { case HCI_BLE_TRANSMITTER_TEST: - if (len != 3) return BT_STATUS_PARM_INVALID; - do_in_main_thread(FROM_HERE, base::BindOnce(btif_ble_transmitter_test, - buf[0], buf[1], buf[2])); + if (len != 3) { + return BT_STATUS_PARM_INVALID; + } + do_in_main_thread(FROM_HERE, + base::BindOnce(btif_ble_transmitter_test, buf[0], buf[1], buf[2])); break; case HCI_BLE_RECEIVER_TEST: - if (len != 1) return BT_STATUS_PARM_INVALID; - do_in_main_thread(FROM_HERE, - base::BindOnce(btif_ble_receiver_test, buf[0])); + if (len != 1) { + return BT_STATUS_PARM_INVALID; + } + do_in_main_thread(FROM_HERE, base::BindOnce(btif_ble_receiver_test, buf[0])); break; case HCI_BLE_TEST_END: do_in_main_thread(FROM_HERE, base::BindOnce(btif_ble_test_end)); @@ -992,20 +1059,18 @@ static bt_os_callouts_t* wakelock_os_callouts_saved = nullptr; static int acquire_wake_lock_cb(const char* lock_name) { return do_in_jni_thread(base::BindOnce( - base::IgnoreResult(wakelock_os_callouts_saved->acquire_wake_lock), - lock_name)); + base::IgnoreResult(wakelock_os_callouts_saved->acquire_wake_lock), lock_name)); } static int release_wake_lock_cb(const char* lock_name) { return do_in_jni_thread(base::BindOnce( - base::IgnoreResult(wakelock_os_callouts_saved->release_wake_lock), - lock_name)); + base::IgnoreResult(wakelock_os_callouts_saved->release_wake_lock), lock_name)); } static bt_os_callouts_t wakelock_os_callouts_jni = { - sizeof(wakelock_os_callouts_jni), - acquire_wake_lock_cb, - release_wake_lock_cb, + sizeof(wakelock_os_callouts_jni), + acquire_wake_lock_cb, + release_wake_lock_cb, }; static int set_os_callouts(bt_os_callouts_t* callouts) { @@ -1035,8 +1100,7 @@ static bluetooth::avrcp::ServiceInterface* get_avrcp_service(void) { } static std::string obfuscate_address(const RawAddress& address) { - return bluetooth::common::AddressObfuscator::GetInstance()->Obfuscate( - address); + return bluetooth::common::AddressObfuscator::GetInstance()->Obfuscate(address); } static int get_metric_id(const RawAddress& address) { @@ -1047,15 +1111,12 @@ static int set_dynamic_audio_buffer_size(int codec, int size) { return btif_set_dynamic_audio_buffer_size(codec, size); } -static bool allow_low_latency_audio(bool allowed, - const RawAddress& /* address */) { +static bool allow_low_latency_audio(bool allowed, const RawAddress& /* address */) { log::info("{}", allowed); if (com::android::bluetooth::flags::a2dp_async_allow_low_latency()) { do_in_main_thread( - FROM_HERE, - base::BindOnce( - bluetooth::audio::a2dp::set_audio_low_latency_mode_allowed, - allowed)); + FROM_HERE, + base::BindOnce(bluetooth::audio::a2dp::set_audio_low_latency_mode_allowed, allowed)); } else { bluetooth::audio::a2dp::set_audio_low_latency_mode_allowed(allowed); } @@ -1069,13 +1130,11 @@ static void metadata_changed(const RawAddress& remote_bd_addr, int key, return; } - do_in_main_thread( - FROM_HERE, base::BindOnce(btif_dm_metadata_changed, remote_bd_addr, key, - std::move(value))); + do_in_main_thread(FROM_HERE, base::BindOnce(btif_dm_metadata_changed, remote_bd_addr, key, + std::move(value))); } -static bool interop_match_addr(const char* feature_name, - const RawAddress* addr) { +static bool interop_match_addr(const char* feature_name, const RawAddress* addr) { if (feature_name == NULL || addr == NULL) { return false; } @@ -1103,8 +1162,7 @@ static bool interop_match_name(const char* feature_name, const char* name) { return interop_match_name((interop_feature_t)feature, name); } -static bool interop_match_addr_or_name(const char* feature_name, - const RawAddress* addr) { +static bool interop_match_addr_or_name(const char* feature_name, const RawAddress* addr) { if (feature_name == NULL || addr == NULL) { return false; } @@ -1119,10 +1177,8 @@ static bool interop_match_addr_or_name(const char* feature_name, &btif_storage_get_remote_device_property); } -static void interop_database_add_remove_addr(bool do_add, - const char* feature_name, - const RawAddress* addr, - int length) { +static void interop_database_add_remove_addr(bool do_add, const char* feature_name, + const RawAddress* addr, int length) { if (feature_name == NULL || addr == NULL) { return; } @@ -1140,8 +1196,7 @@ static void interop_database_add_remove_addr(bool do_add, } } -static void interop_database_add_remove_name(bool do_add, - const char* feature_name, +static void interop_database_add_remove_name(bool do_add, const char* feature_name, const char* name) { if (feature_name == NULL || name == NULL) { return; @@ -1161,80 +1216,77 @@ static void interop_database_add_remove_name(bool do_add, } EXPORT_SYMBOL bt_interface_t bluetoothInterface = { - sizeof(bluetoothInterface), - .init = init, - .enable = enable, - .disable = disable, - .cleanup = cleanup, - .start_rust_module = start_rust_module, - .stop_rust_module = stop_rust_module, - .get_adapter_properties = get_adapter_properties, - .get_adapter_property = get_adapter_property, - .set_scan_mode = set_scan_mode, - .set_adapter_property = set_adapter_property, - .get_remote_device_properties = get_remote_device_properties, - .get_remote_device_property = get_remote_device_property, - .set_remote_device_property = set_remote_device_property, - .get_remote_service_record = nullptr, - .get_remote_services = get_remote_services, - .start_discovery = start_discovery, - .cancel_discovery = cancel_discovery, - .create_bond = create_bond, - .create_bond_le = create_bond_le, - .create_bond_out_of_band = create_bond_out_of_band, - .remove_bond = remove_bond, - .cancel_bond = cancel_bond, - .pairing_is_busy = pairing_is_busy, - .get_connection_state = get_connection_state, - .pin_reply = pin_reply, - .ssp_reply = ssp_reply, - .get_profile_interface = get_profile_interface, - .dut_mode_configure = dut_mode_configure, - .dut_mode_send = dut_mode_send, - .le_test_mode = le_test_mode, - .set_os_callouts = set_os_callouts, - .read_energy_info = read_energy_info, - .dump = dump, - .dumpMetrics = dumpMetrics, - .config_clear = config_clear, - .interop_database_clear = interop_database_clear, - .interop_database_add = interop_database_add, - .get_avrcp_service = get_avrcp_service, - .obfuscate_address = obfuscate_address, - .get_metric_id = get_metric_id, - .set_dynamic_audio_buffer_size = set_dynamic_audio_buffer_size, - .generate_local_oob_data = generate_local_oob_data, - .allow_low_latency_audio = allow_low_latency_audio, - .clear_event_filter = clear_event_filter, - .clear_event_mask = clear_event_mask, - .clear_filter_accept_list = clear_filter_accept_list, - .disconnect_all_acls = disconnect_all_acls, - .le_rand = le_rand, - .set_event_filter_inquiry_result_all_devices = - set_event_filter_inquiry_result_all_devices, - .set_default_event_mask_except = set_default_event_mask_except, - .restore_filter_accept_list = restore_filter_accept_list, - .allow_wake_by_hid = allow_wake_by_hid, - .set_event_filter_connection_setup_all_devices = - set_event_filter_connection_setup_all_devices, - .get_wbs_supported = get_wbs_supported, - .get_swb_supported = get_swb_supported, - .is_coding_format_supported = is_coding_format_supported, - .metadata_changed = metadata_changed, - .interop_match_addr = interop_match_addr, - .interop_match_name = interop_match_name, - .interop_match_addr_or_name = interop_match_addr_or_name, - .interop_database_add_remove_addr = interop_database_add_remove_addr, - .interop_database_add_remove_name = interop_database_add_remove_name, - .get_remote_pbap_pce_version = get_remote_pbap_pce_version, - .pbap_pse_dynamic_version_upgrade_is_enabled = - pbap_pse_dynamic_version_upgrade_is_enabled, + sizeof(bluetoothInterface), + .init = init, + .enable = enable, + .disable = disable, + .cleanup = cleanup, + .start_rust_module = start_rust_module, + .stop_rust_module = stop_rust_module, + .get_adapter_properties = get_adapter_properties, + .get_adapter_property = get_adapter_property, + .set_scan_mode = set_scan_mode, + .set_adapter_property = set_adapter_property, + .get_remote_device_properties = get_remote_device_properties, + .get_remote_device_property = get_remote_device_property, + .set_remote_device_property = set_remote_device_property, + .get_remote_service_record = nullptr, + .get_remote_services = get_remote_services, + .start_discovery = start_discovery, + .cancel_discovery = cancel_discovery, + .create_bond = create_bond, + .create_bond_le = create_bond_le, + .create_bond_out_of_band = create_bond_out_of_band, + .remove_bond = remove_bond, + .cancel_bond = cancel_bond, + .pairing_is_busy = pairing_is_busy, + .get_connection_state = get_connection_state, + .pin_reply = pin_reply, + .ssp_reply = ssp_reply, + .get_profile_interface = get_profile_interface, + .dut_mode_configure = dut_mode_configure, + .dut_mode_send = dut_mode_send, + .le_test_mode = le_test_mode, + .set_os_callouts = set_os_callouts, + .read_energy_info = read_energy_info, + .dump = dump, + .dumpMetrics = dumpMetrics, + .config_clear = config_clear, + .interop_database_clear = interop_database_clear, + .interop_database_add = interop_database_add, + .get_avrcp_service = get_avrcp_service, + .obfuscate_address = obfuscate_address, + .get_metric_id = get_metric_id, + .set_dynamic_audio_buffer_size = set_dynamic_audio_buffer_size, + .generate_local_oob_data = generate_local_oob_data, + .allow_low_latency_audio = allow_low_latency_audio, + .clear_event_filter = clear_event_filter, + .clear_event_mask = clear_event_mask, + .clear_filter_accept_list = clear_filter_accept_list, + .disconnect_all_acls = disconnect_all_acls, + .le_rand = le_rand, + .set_event_filter_inquiry_result_all_devices = set_event_filter_inquiry_result_all_devices, + .set_default_event_mask_except = set_default_event_mask_except, + .restore_filter_accept_list = restore_filter_accept_list, + .allow_wake_by_hid = allow_wake_by_hid, + .set_event_filter_connection_setup_all_devices = + set_event_filter_connection_setup_all_devices, + .get_wbs_supported = get_wbs_supported, + .get_swb_supported = get_swb_supported, + .is_coding_format_supported = is_coding_format_supported, + .metadata_changed = metadata_changed, + .interop_match_addr = interop_match_addr, + .interop_match_name = interop_match_name, + .interop_match_addr_or_name = interop_match_addr_or_name, + .interop_database_add_remove_addr = interop_database_add_remove_addr, + .interop_database_add_remove_name = interop_database_add_remove_name, + .get_remote_pbap_pce_version = get_remote_pbap_pce_version, + .pbap_pse_dynamic_version_upgrade_is_enabled = pbap_pse_dynamic_version_upgrade_is_enabled, }; // callback reporting helpers -bt_property_t* property_deep_copy_array(int num_properties, - bt_property_t* properties) { +bt_property_t* property_deep_copy_array(int num_properties, bt_property_t* properties) { bt_property_t* copy = nullptr; if (num_properties > 0) { size_t content_len = 0; @@ -1245,8 +1297,7 @@ bt_property_t* property_deep_copy_array(int num_properties, } } - copy = (bt_property_t*)osi_calloc((sizeof(bt_property_t) * num_properties) + - content_len); + copy = (bt_property_t*)osi_calloc((sizeof(bt_property_t) * num_properties) + content_len); log::assert_that(copy != nullptr, "assert failed: copy != nullptr"); uint8_t* content = (uint8_t*)(copy + num_properties); @@ -1267,91 +1318,79 @@ bt_property_t* property_deep_copy_array(int num_properties, void invoke_adapter_state_changed_cb(bt_state_t state) { do_in_jni_thread(base::BindOnce( - [](bt_state_t state) { - HAL_CBACK(bt_hal_cbacks, adapter_state_changed_cb, state); - }, - state)); + [](bt_state_t state) { HAL_CBACK(bt_hal_cbacks, adapter_state_changed_cb, state); }, + state)); } void invoke_adapter_properties_cb(bt_status_t status, int num_properties, bt_property_t* properties) { do_in_jni_thread(base::BindOnce( - [](bt_status_t status, int num_properties, bt_property_t* properties) { - HAL_CBACK(bt_hal_cbacks, adapter_properties_cb, status, num_properties, - properties); - if (properties) { - osi_free(properties); - } - }, - status, num_properties, - property_deep_copy_array(num_properties, properties))); -} - -void invoke_remote_device_properties_cb(bt_status_t status, RawAddress bd_addr, - int num_properties, + [](bt_status_t status, int num_properties, bt_property_t* properties) { + HAL_CBACK(bt_hal_cbacks, adapter_properties_cb, status, num_properties, properties); + if (properties) { + osi_free(properties); + } + }, + status, num_properties, property_deep_copy_array(num_properties, properties))); +} + +void invoke_remote_device_properties_cb(bt_status_t status, RawAddress bd_addr, int num_properties, bt_property_t* properties) { do_in_jni_thread(base::BindOnce( - [](bt_status_t status, RawAddress bd_addr, int num_properties, - bt_property_t* properties) { - HAL_CBACK(bt_hal_cbacks, remote_device_properties_cb, status, &bd_addr, - num_properties, properties); - if (properties) { - osi_free(properties); - } - }, - status, bd_addr, num_properties, - property_deep_copy_array(num_properties, properties))); + [](bt_status_t status, RawAddress bd_addr, int num_properties, + bt_property_t* properties) { + HAL_CBACK(bt_hal_cbacks, remote_device_properties_cb, status, &bd_addr, num_properties, + properties); + if (properties) { + osi_free(properties); + } + }, + status, bd_addr, num_properties, property_deep_copy_array(num_properties, properties))); } void invoke_device_found_cb(int num_properties, bt_property_t* properties) { do_in_jni_thread(base::BindOnce( - [](int num_properties, bt_property_t* properties) { - HAL_CBACK(bt_hal_cbacks, device_found_cb, num_properties, properties); - if (properties) { - osi_free(properties); - } - }, - num_properties, property_deep_copy_array(num_properties, properties))); + [](int num_properties, bt_property_t* properties) { + HAL_CBACK(bt_hal_cbacks, device_found_cb, num_properties, properties); + if (properties) { + osi_free(properties); + } + }, + num_properties, property_deep_copy_array(num_properties, properties))); } void invoke_discovery_state_changed_cb(bt_discovery_state_t state) { do_in_jni_thread(base::BindOnce( - [](bt_discovery_state_t state) { - HAL_CBACK(bt_hal_cbacks, discovery_state_changed_cb, state); - }, - state)); + [](bt_discovery_state_t state) { + HAL_CBACK(bt_hal_cbacks, discovery_state_changed_cb, state); + }, + state)); } -void invoke_pin_request_cb(RawAddress bd_addr, bt_bdname_t bd_name, - uint32_t cod, bool min_16_digit) { +void invoke_pin_request_cb(RawAddress bd_addr, bt_bdname_t bd_name, uint32_t cod, + bool min_16_digit) { do_in_jni_thread(base::BindOnce( - [](RawAddress bd_addr, bt_bdname_t bd_name, uint32_t cod, - bool min_16_digit) { - HAL_CBACK(bt_hal_cbacks, pin_request_cb, &bd_addr, &bd_name, cod, - min_16_digit); - }, - bd_addr, bd_name, cod, min_16_digit)); + [](RawAddress bd_addr, bt_bdname_t bd_name, uint32_t cod, bool min_16_digit) { + HAL_CBACK(bt_hal_cbacks, pin_request_cb, &bd_addr, &bd_name, cod, min_16_digit); + }, + bd_addr, bd_name, cod, min_16_digit)); } void invoke_ssp_request_cb(RawAddress bd_addr, bt_ssp_variant_t pairing_variant, uint32_t pass_key) { do_in_jni_thread(base::BindOnce( - [](RawAddress bd_addr, bt_ssp_variant_t pairing_variant, - uint32_t pass_key) { - HAL_CBACK(bt_hal_cbacks, ssp_request_cb, &bd_addr, pairing_variant, - pass_key); - }, - bd_addr, pairing_variant, pass_key)); + [](RawAddress bd_addr, bt_ssp_variant_t pairing_variant, uint32_t pass_key) { + HAL_CBACK(bt_hal_cbacks, ssp_request_cb, &bd_addr, pairing_variant, pass_key); + }, + bd_addr, pairing_variant, pass_key)); } -void invoke_oob_data_request_cb(tBT_TRANSPORT t, bool valid, Octet16 c, - Octet16 r, RawAddress raw_address, - uint8_t address_type) { +void invoke_oob_data_request_cb(tBT_TRANSPORT t, bool valid, Octet16 c, Octet16 r, + RawAddress raw_address, uint8_t address_type) { log::info(""); bt_oob_data_t oob_data = {}; const char* local_name; - if (get_btm_client_interface().local.BTM_ReadLocalDeviceName(&local_name) != - BTM_SUCCESS) { + if (get_btm_client_interface().local.BTM_ReadLocalDeviceName(&local_name) != BTM_SUCCESS) { log::warn("Unable to read local device name"); } for (int i = 0; i < BD_NAME_LEN; i++) { @@ -1370,143 +1409,126 @@ void invoke_oob_data_request_cb(tBT_TRANSPORT t, bool valid, Octet16 c, bool c_empty = true; for (int i = 0; i < 16; i++) { // C cannot be all 0s, if so then we want to fail - if (c[i] != 0) c_empty = false; + if (c[i] != 0) { + c_empty = false; + } oob_data.c[i] = c[i]; // R is optional and may be empty oob_data.r[i] = r[i]; } oob_data.is_valid = valid && !c_empty; - // The oob_data_length is 2 octects in length. The value includes the length + // The oob_data_length is 2 octets in length. The value includes the length // of itself. 16 + 16 + 2 = 34 Data 0x0022 Little Endian order 0x2200 oob_data.oob_data_length[0] = 0; oob_data.oob_data_length[1] = 34; bt_status_t status = do_in_jni_thread(base::BindOnce( - [](tBT_TRANSPORT t, bt_oob_data_t oob_data) { - HAL_CBACK(bt_hal_cbacks, generate_local_oob_data_cb, t, oob_data); - }, - t, oob_data)); + [](tBT_TRANSPORT t, bt_oob_data_t oob_data) { + HAL_CBACK(bt_hal_cbacks, generate_local_oob_data_cb, t, oob_data); + }, + t, oob_data)); if (status != BT_STATUS_SUCCESS) { log::error("Failed to call callback!"); } } -void invoke_bond_state_changed_cb(bt_status_t status, RawAddress bd_addr, - bt_bond_state_t state, int fail_reason) { +void invoke_bond_state_changed_cb(bt_status_t status, RawAddress bd_addr, bt_bond_state_t state, + int fail_reason) { do_in_jni_thread(base::BindOnce( - [](bt_status_t status, RawAddress bd_addr, bt_bond_state_t state, - int fail_reason) { - HAL_CBACK(bt_hal_cbacks, bond_state_changed_cb, status, &bd_addr, state, - fail_reason); - }, - status, bd_addr, state, fail_reason)); + [](bt_status_t status, RawAddress bd_addr, bt_bond_state_t state, int fail_reason) { + HAL_CBACK(bt_hal_cbacks, bond_state_changed_cb, status, &bd_addr, state, fail_reason); + }, + status, bd_addr, state, fail_reason)); } -void invoke_address_consolidate_cb(RawAddress main_bd_addr, - RawAddress secondary_bd_addr) { +void invoke_address_consolidate_cb(RawAddress main_bd_addr, RawAddress secondary_bd_addr) { do_in_jni_thread(base::BindOnce( - [](RawAddress main_bd_addr, RawAddress secondary_bd_addr) { - HAL_CBACK(bt_hal_cbacks, address_consolidate_cb, &main_bd_addr, - &secondary_bd_addr); - }, - main_bd_addr, secondary_bd_addr)); + [](RawAddress main_bd_addr, RawAddress secondary_bd_addr) { + HAL_CBACK(bt_hal_cbacks, address_consolidate_cb, &main_bd_addr, &secondary_bd_addr); + }, + main_bd_addr, secondary_bd_addr)); } -void invoke_le_address_associate_cb(RawAddress main_bd_addr, - RawAddress secondary_bd_addr) { +void invoke_le_address_associate_cb(RawAddress main_bd_addr, RawAddress secondary_bd_addr) { do_in_jni_thread(base::BindOnce( - [](RawAddress main_bd_addr, RawAddress secondary_bd_addr) { - HAL_CBACK(bt_hal_cbacks, le_address_associate_cb, &main_bd_addr, - &secondary_bd_addr); - }, - main_bd_addr, secondary_bd_addr)); -} -void invoke_acl_state_changed_cb(bt_status_t status, RawAddress bd_addr, - bt_acl_state_t state, int transport_link_type, - bt_hci_error_code_t hci_reason, - bt_conn_direction_t direction, - uint16_t acl_handle) { + [](RawAddress main_bd_addr, RawAddress secondary_bd_addr) { + HAL_CBACK(bt_hal_cbacks, le_address_associate_cb, &main_bd_addr, &secondary_bd_addr); + }, + main_bd_addr, secondary_bd_addr)); +} +void invoke_acl_state_changed_cb(bt_status_t status, RawAddress bd_addr, bt_acl_state_t state, + int transport_link_type, bt_hci_error_code_t hci_reason, + bt_conn_direction_t direction, uint16_t acl_handle) { do_in_jni_thread(base::BindOnce( - [](bt_status_t status, RawAddress bd_addr, bt_acl_state_t state, - int transport_link_type, bt_hci_error_code_t hci_reason, - bt_conn_direction_t direction, uint16_t acl_handle) { - HAL_CBACK(bt_hal_cbacks, acl_state_changed_cb, status, &bd_addr, state, - transport_link_type, hci_reason, direction, acl_handle); - }, - status, bd_addr, state, transport_link_type, hci_reason, direction, - acl_handle)); + [](bt_status_t status, RawAddress bd_addr, bt_acl_state_t state, int transport_link_type, + bt_hci_error_code_t hci_reason, bt_conn_direction_t direction, uint16_t acl_handle) { + HAL_CBACK(bt_hal_cbacks, acl_state_changed_cb, status, &bd_addr, state, + transport_link_type, hci_reason, direction, acl_handle); + }, + status, bd_addr, state, transport_link_type, hci_reason, direction, acl_handle)); } void invoke_thread_evt_cb(bt_cb_thread_evt event) { do_in_jni_thread(base::BindOnce( - [](bt_cb_thread_evt event) { - HAL_CBACK(bt_hal_cbacks, thread_evt_cb, event); - if (event == DISASSOCIATE_JVM) { - bt_hal_cbacks = NULL; - } - }, - event)); + [](bt_cb_thread_evt event) { + HAL_CBACK(bt_hal_cbacks, thread_evt_cb, event); + if (event == DISASSOCIATE_JVM) { + bt_hal_cbacks = NULL; + } + }, + event)); } void invoke_le_test_mode_cb(bt_status_t status, uint16_t count) { do_in_jni_thread(base::BindOnce( - [](bt_status_t status, uint16_t count) { - HAL_CBACK(bt_hal_cbacks, le_test_mode_cb, status, count); - }, - status, count)); + [](bt_status_t status, uint16_t count) { + HAL_CBACK(bt_hal_cbacks, le_test_mode_cb, status, count); + }, + status, count)); } // takes ownership of |uid_data| -void invoke_energy_info_cb(bt_activity_energy_info energy_info, - bt_uid_traffic_t* uid_data) { +void invoke_energy_info_cb(bt_activity_energy_info energy_info, bt_uid_traffic_t* uid_data) { do_in_jni_thread(base::BindOnce( - [](bt_activity_energy_info energy_info, bt_uid_traffic_t* uid_data) { - HAL_CBACK(bt_hal_cbacks, energy_info_cb, &energy_info, uid_data); - osi_free(uid_data); - }, - energy_info, uid_data)); + [](bt_activity_energy_info energy_info, bt_uid_traffic_t* uid_data) { + HAL_CBACK(bt_hal_cbacks, energy_info_cb, &energy_info, uid_data); + osi_free(uid_data); + }, + energy_info, uid_data)); } -void invoke_link_quality_report_cb(uint64_t timestamp, int report_id, int rssi, - int snr, int retransmission_count, - int packets_not_receive_count, +void invoke_link_quality_report_cb(uint64_t timestamp, int report_id, int rssi, int snr, + int retransmission_count, int packets_not_receive_count, int negative_acknowledgement_count) { - do_in_jni_thread( - base::BindOnce( - [](uint64_t timestamp, int report_id, int rssi, int snr, - int retransmission_count, int packets_not_receive_count, - int negative_acknowledgement_count) { - HAL_CBACK(bt_hal_cbacks, link_quality_report_cb, timestamp, - report_id, rssi, snr, retransmission_count, - packets_not_receive_count, + do_in_jni_thread(base::BindOnce( + [](uint64_t timestamp, int report_id, int rssi, int snr, int retransmission_count, + int packets_not_receive_count, int negative_acknowledgement_count) { + HAL_CBACK(bt_hal_cbacks, link_quality_report_cb, timestamp, report_id, rssi, snr, + retransmission_count, packets_not_receive_count, negative_acknowledgement_count); }, - timestamp, report_id, rssi, snr, retransmission_count, - packets_not_receive_count, negative_acknowledgement_count)); + timestamp, report_id, rssi, snr, retransmission_count, packets_not_receive_count, + negative_acknowledgement_count)); } void invoke_switch_buffer_size_cb(bool is_low_latency_buffer_size) { do_in_jni_thread(base::BindOnce( - [](bool is_low_latency_buffer_size) { - HAL_CBACK(bt_hal_cbacks, switch_buffer_size_cb, - is_low_latency_buffer_size); - }, - is_low_latency_buffer_size)); + [](bool is_low_latency_buffer_size) { + HAL_CBACK(bt_hal_cbacks, switch_buffer_size_cb, is_low_latency_buffer_size); + }, + is_low_latency_buffer_size)); } void invoke_switch_codec_cb(bool is_low_latency_buffer_size) { do_in_jni_thread(base::BindOnce( - [](bool is_low_latency_buffer_size) { - HAL_CBACK(bt_hal_cbacks, switch_codec_cb, is_low_latency_buffer_size); - }, - is_low_latency_buffer_size)); + [](bool is_low_latency_buffer_size) { + HAL_CBACK(bt_hal_cbacks, switch_codec_cb, is_low_latency_buffer_size); + }, + is_low_latency_buffer_size)); } void invoke_key_missing_cb(RawAddress bd_addr) { do_in_jni_thread(base::BindOnce( - [](RawAddress bd_addr) { - HAL_CBACK(bt_hal_cbacks, key_missing_cb, bd_addr); - }, - bd_addr)); + [](RawAddress bd_addr) { HAL_CBACK(bt_hal_cbacks, key_missing_cb, bd_addr); }, bd_addr)); } namespace bluetooth::testing { diff --git a/system/btif/src/btif_a2dp.cc b/system/btif/src/btif_a2dp.cc index d01f15cb52b..1133ef54d18 100644 --- a/system/btif/src/btif_a2dp.cc +++ b/system/btif/src/btif_a2dp.cc @@ -40,11 +40,9 @@ using namespace bluetooth; using bluetooth::audio::a2dp::BluetoothAudioStatus; -void btif_a2dp_on_idle(const RawAddress& peer_addr, - const A2dpType local_a2dp_type) { - log::verbose( - "Peer stream endpoint type:{}", - peer_stream_endpoint_text(btif_av_get_peer_sep(local_a2dp_type))); +void btif_a2dp_on_idle(const RawAddress& peer_addr, const A2dpType local_a2dp_type) { + log::verbose("Peer stream endpoint type:{}", + peer_stream_endpoint_text(btif_av_get_peer_sep(local_a2dp_type))); if (!com::android::bluetooth::flags::a2dp_concurrent_source_sink() && btif_av_src_sink_coexist_enabled()) { bool is_sink = btif_av_peer_is_sink(peer_addr); @@ -64,17 +62,14 @@ void btif_a2dp_on_idle(const RawAddress& peer_addr, } } -bool btif_a2dp_on_started(const RawAddress& peer_addr, - tBTA_AV_START* p_av_start, +bool btif_a2dp_on_started(const RawAddress& peer_addr, tBTA_AV_START* p_av_start, const A2dpType local_a2dp_type) { - log::info("## ON A2DP STARTED ## peer {} p_av_start:{}", peer_addr, - fmt::ptr(p_av_start)); + log::info("## ON A2DP STARTED ## peer {} p_av_start:{}", peer_addr, fmt::ptr(p_av_start)); if (p_av_start == NULL) { auto status = BluetoothAudioStatus::SUCCESS; if (!bluetooth::headset::IsCallIdle()) { - log::error("peer {} call in progress, do not start A2DP stream", - peer_addr); + log::error("peer {} call in progress, do not start A2DP stream", peer_addr); status = BluetoothAudioStatus::FAILURE; } /* just ack back a local start request, do not start the media encoder since @@ -83,13 +78,12 @@ bool btif_a2dp_on_started(const RawAddress& peer_addr, return true; } - log::info("peer {} status:{} suspending:{} initiator:{}", peer_addr, - p_av_start->status, p_av_start->suspending, p_av_start->initiator); + log::info("peer {} status:{} suspending:{} initiator:{}", peer_addr, p_av_start->status, + p_av_start->suspending, p_av_start->initiator); if (p_av_start->status == BTA_AV_SUCCESS) { if (p_av_start->suspending) { - log::warn("peer {} A2DP is suspending and ignores the started event", - peer_addr); + log::warn("peer {} A2DP is suspending and ignores the started event", peer_addr); return false; } if (btif_av_is_a2dp_offload_running()) { @@ -105,16 +99,14 @@ bool btif_a2dp_on_started(const RawAddress& peer_addr, } } } else if (p_av_start->initiator) { - log::error("peer {} A2DP start request failed: status = {}", peer_addr, - p_av_start->status); + log::error("peer {} A2DP start request failed: status = {}", peer_addr, p_av_start->status); bluetooth::audio::a2dp::ack_stream_started(BluetoothAudioStatus::FAILURE); return true; } return false; } -void btif_a2dp_on_stopped(tBTA_AV_SUSPEND* p_av_suspend, - const A2dpType local_a2dp_type) { +void btif_a2dp_on_stopped(tBTA_AV_SUSPEND* p_av_suspend, const A2dpType local_a2dp_type) { log::info("## ON A2DP STOPPED ## p_av_suspend={}", fmt::ptr(p_av_suspend)); const uint8_t peer_type_sep = btif_av_get_peer_sep(local_a2dp_type); @@ -123,22 +115,19 @@ void btif_a2dp_on_stopped(tBTA_AV_SUSPEND* p_av_suspend, return; } if (!com::android::bluetooth::flags::a2dp_concurrent_source_sink()) { - if (bluetooth::audio::a2dp::is_hal_enabled() || - !btif_av_is_a2dp_offload_running()) { + if (bluetooth::audio::a2dp::is_hal_enabled() || !btif_av_is_a2dp_offload_running()) { btif_a2dp_source_on_stopped(p_av_suspend); return; } } else if (peer_type_sep == AVDT_TSEP_SNK) { - if (bluetooth::audio::a2dp::is_hal_enabled() || - !btif_av_is_a2dp_offload_running()) { + if (bluetooth::audio::a2dp::is_hal_enabled() || !btif_av_is_a2dp_offload_running()) { btif_a2dp_source_on_stopped(p_av_suspend); return; } } } -void btif_a2dp_on_suspended(tBTA_AV_SUSPEND* p_av_suspend, - const A2dpType local_a2dp_type) { +void btif_a2dp_on_suspended(tBTA_AV_SUSPEND* p_av_suspend, const A2dpType local_a2dp_type) { log::info("## ON A2DP SUSPENDED ## p_av_suspend={}", fmt::ptr(p_av_suspend)); const uint8_t peer_type_sep = btif_av_get_peer_sep(local_a2dp_type); if (peer_type_sep == AVDT_TSEP_SRC) { @@ -146,22 +135,19 @@ void btif_a2dp_on_suspended(tBTA_AV_SUSPEND* p_av_suspend, return; } if (!com::android::bluetooth::flags::a2dp_concurrent_source_sink()) { - if (bluetooth::audio::a2dp::is_hal_enabled() || - !btif_av_is_a2dp_offload_running()) { + if (bluetooth::audio::a2dp::is_hal_enabled() || !btif_av_is_a2dp_offload_running()) { btif_a2dp_source_on_suspended(p_av_suspend); return; } } else if (peer_type_sep == AVDT_TSEP_SNK) { - if (bluetooth::audio::a2dp::is_hal_enabled() || - !btif_av_is_a2dp_offload_running()) { + if (bluetooth::audio::a2dp::is_hal_enabled() || !btif_av_is_a2dp_offload_running()) { btif_a2dp_source_on_suspended(p_av_suspend); return; } } } -void btif_a2dp_on_offload_started(const RawAddress& peer_addr, - tBTA_AV_STATUS status) { +void btif_a2dp_on_offload_started(const RawAddress& peer_addr, tBTA_AV_STATUS status) { BluetoothAudioStatus ack; log::info("peer {} status {}", peer_addr, status); diff --git a/system/btif/src/btif_a2dp_sink.cc b/system/btif/src/btif_a2dp_sink.cc index 7dec255dba6..e2e6265355f 100644 --- a/system/btif/src/btif_a2dp_sink.cc +++ b/system/btif/src/btif_a2dp_sink.cc @@ -32,7 +32,7 @@ #include "btif/include/btif_av.h" #include "btif/include/btif_av_co.h" #include "btif/include/btif_avrcp_audio_track.h" -#include "btif/include/btif_util.h" // CASE_RETURN_STR +#include "btif/include/btif_util.h" // CASE_RETURN_STR #include "common/message_loop_thread.h" #include "hardware/bt_av.h" #include "os/log.h" @@ -85,7 +85,7 @@ typedef struct { /* BTIF A2DP Sink control block */ class BtifA2dpSinkControlBlock { - public: +public: explicit BtifA2dpSinkControlBlock(const std::string& thread_name) : worker_thread(thread_name), rx_audio_queue(nullptr), @@ -135,8 +135,7 @@ static std::atomic btif_a2dp_sink_state{BTIF_A2DP_SINK_STATE_OFF}; static void btif_a2dp_sink_init_delayed(); static void btif_a2dp_sink_startup_delayed(); -static void btif_a2dp_sink_start_session_delayed( - std::promise peer_ready_promise); +static void btif_a2dp_sink_start_session_delayed(std::promise peer_ready_promise); static void btif_a2dp_sink_end_session_delayed(); static void btif_a2dp_sink_shutdown_delayed(); static void btif_a2dp_sink_cleanup_delayed(); @@ -148,11 +147,9 @@ static void btif_a2dp_sink_avk_handle_timer(); static void btif_a2dp_sink_audio_rx_flush_req(); /* Handle incoming media packets A2DP SINK streaming */ static void btif_a2dp_sink_handle_inc_media(BT_HDR* p_msg); -static void btif_a2dp_sink_decoder_update_event( - tBTIF_MEDIA_SINK_DECODER_UPDATE* p_buf); +static void btif_a2dp_sink_decoder_update_event(tBTIF_MEDIA_SINK_DECODER_UPDATE* p_buf); static void btif_a2dp_sink_clear_track_event(); -static void btif_a2dp_sink_set_focus_state_event( - btif_a2dp_sink_focus_state_t state); +static void btif_a2dp_sink_set_focus_state_event(btif_a2dp_sink_focus_state_t state); static void btif_a2dp_sink_audio_rx_flush_event(); static void btif_a2dp_sink_clear_track_event_req(); static void btif_a2dp_sink_on_start_event(); @@ -200,8 +197,8 @@ bool btif_a2dp_sink_init() { log::fatal("Failed to increase A2DP decoder thread priority"); #endif } - btif_a2dp_sink_cb.worker_thread.DoInThread( - FROM_HERE, base::BindOnce(btif_a2dp_sink_init_delayed)); + btif_a2dp_sink_cb.worker_thread.DoInThread(FROM_HERE, + base::BindOnce(btif_a2dp_sink_init_delayed)); return true; } @@ -212,8 +209,8 @@ static void btif_a2dp_sink_init_delayed() { bool btif_a2dp_sink_startup() { log::info(""); - btif_a2dp_sink_cb.worker_thread.DoInThread( - FROM_HERE, base::BindOnce(btif_a2dp_sink_startup_delayed)); + btif_a2dp_sink_cb.worker_thread.DoInThread(FROM_HERE, + base::BindOnce(btif_a2dp_sink_startup_delayed)); return true; } @@ -227,8 +224,8 @@ bool btif_a2dp_sink_start_session(const RawAddress& peer_address, std::promise peer_ready_promise) { log::info("peer_address={}", peer_address); if (btif_a2dp_sink_cb.worker_thread.DoInThread( - FROM_HERE, base::BindOnce(btif_a2dp_sink_start_session_delayed, - std::move(peer_ready_promise)))) { + FROM_HERE, base::BindOnce(btif_a2dp_sink_start_session_delayed, + std::move(peer_ready_promise)))) { return true; } else { // cannot set promise but triggers crash @@ -237,8 +234,7 @@ bool btif_a2dp_sink_start_session(const RawAddress& peer_address, } } -static void btif_a2dp_sink_start_session_delayed( - std::promise peer_ready_promise) { +static void btif_a2dp_sink_start_session_delayed(std::promise peer_ready_promise) { log::info(""); LockGuard lock(g_mutex); peer_ready_promise.set_value(); @@ -248,26 +244,22 @@ static void btif_a2dp_sink_start_session_delayed( bool btif_a2dp_sink_restart_session(const RawAddress& old_peer_address, const RawAddress& new_peer_address, std::promise peer_ready_promise) { - log::info("old_peer_address={} new_peer_address={}", old_peer_address, - new_peer_address); + log::info("old_peer_address={} new_peer_address={}", old_peer_address, new_peer_address); - log::assert_that(!new_peer_address.IsEmpty(), - "assert failed: !new_peer_address.IsEmpty()"); + log::assert_that(!new_peer_address.IsEmpty(), "assert failed: !new_peer_address.IsEmpty()"); if (!old_peer_address.IsEmpty()) { btif_a2dp_sink_end_session(old_peer_address); } if (com::android::bluetooth::flags::a2dp_concurrent_source_sink()) { if (!bta_av_co_set_active_sink_peer(new_peer_address)) { - log::error("Cannot stream audio: cannot set active peer to {}", - new_peer_address); + log::error("Cannot stream audio: cannot set active peer to {}", new_peer_address); peer_ready_promise.set_value(); return false; } } else { if (!bta_av_co_set_active_peer(new_peer_address)) { - log::error("Cannot stream audio: cannot set active peer to {}", - new_peer_address); + log::error("Cannot stream audio: cannot set active peer to {}", new_peer_address); peer_ready_promise.set_value(); return false; } @@ -283,8 +275,8 @@ bool btif_a2dp_sink_restart_session(const RawAddress& old_peer_address, bool btif_a2dp_sink_end_session(const RawAddress& peer_address) { log::info("peer_address={}", peer_address); - btif_a2dp_sink_cb.worker_thread.DoInThread( - FROM_HERE, base::BindOnce(btif_a2dp_sink_end_session_delayed)); + btif_a2dp_sink_cb.worker_thread.DoInThread(FROM_HERE, + base::BindOnce(btif_a2dp_sink_end_session_delayed)); return true; } @@ -296,8 +288,8 @@ static void btif_a2dp_sink_end_session_delayed() { void btif_a2dp_sink_shutdown() { log::info(""); - btif_a2dp_sink_cb.worker_thread.DoInThread( - FROM_HERE, base::BindOnce(btif_a2dp_sink_shutdown_delayed)); + btif_a2dp_sink_cb.worker_thread.DoInThread(FROM_HERE, + base::BindOnce(btif_a2dp_sink_shutdown_delayed)); } static void btif_a2dp_sink_shutdown_delayed() { @@ -331,8 +323,8 @@ void btif_a2dp_sink_cleanup() { alarm_free(decode_alarm); // Exit the thread - btif_a2dp_sink_cb.worker_thread.DoInThread( - FROM_HERE, base::BindOnce(btif_a2dp_sink_cleanup_delayed)); + btif_a2dp_sink_cb.worker_thread.DoInThread(FROM_HERE, + base::BindOnce(btif_a2dp_sink_cleanup_delayed)); btif_a2dp_sink_cb.worker_thread.ShutDown(); } @@ -350,15 +342,13 @@ static void btif_a2dp_sink_command_ready(BT_HDR_RIGID* p_msg) { switch (p_msg->event) { case BTIF_MEDIA_SINK_DECODER_UPDATE: - btif_a2dp_sink_decoder_update_event( - (tBTIF_MEDIA_SINK_DECODER_UPDATE*)p_msg); + btif_a2dp_sink_decoder_update_event((tBTIF_MEDIA_SINK_DECODER_UPDATE*)p_msg); break; case BTIF_MEDIA_SINK_CLEAR_TRACK: btif_a2dp_sink_clear_track_event(); break; case BTIF_MEDIA_SINK_SET_FOCUS_STATE: { - btif_a2dp_sink_focus_state_t state = - ((tBTIF_MEDIA_SINK_FOCUS_UPDATE*)p_msg)->focus_state; + btif_a2dp_sink_focus_state_t state = ((tBTIF_MEDIA_SINK_FOCUS_UPDATE*)p_msg)->focus_state; btif_a2dp_sink_set_focus_state_event(state); break; } @@ -382,67 +372,66 @@ static void btif_a2dp_sink_command_ready(BT_HDR_RIGID* p_msg) { void btif_a2dp_sink_update_decoder(const uint8_t* p_codec_info) { log::info(""); - tBTIF_MEDIA_SINK_DECODER_UPDATE* p_buf = - reinterpret_cast( + tBTIF_MEDIA_SINK_DECODER_UPDATE* p_buf = reinterpret_cast( osi_malloc(sizeof(tBTIF_MEDIA_SINK_DECODER_UPDATE))); - log::verbose("p_codec_info[{:x}:{:x}:{:x}:{:x}:{:x}:{:x}]", p_codec_info[1], - p_codec_info[2], p_codec_info[3], p_codec_info[4], - p_codec_info[5], p_codec_info[6]); + log::verbose("p_codec_info[{:x}:{:x}:{:x}:{:x}:{:x}:{:x}]", p_codec_info[1], p_codec_info[2], + p_codec_info[3], p_codec_info[4], p_codec_info[5], p_codec_info[6]); memcpy(p_buf->codec_info, p_codec_info, AVDT_CODEC_SIZE); p_buf->hdr.event = BTIF_MEDIA_SINK_DECODER_UPDATE; btif_a2dp_sink_cb.worker_thread.DoInThread( - FROM_HERE, - base::BindOnce(btif_a2dp_sink_command_ready, (BT_HDR_RIGID*)p_buf)); + FROM_HERE, base::BindOnce(btif_a2dp_sink_command_ready, (BT_HDR_RIGID*)p_buf)); } void btif_a2dp_sink_on_idle() { log::info(""); - BT_HDR_RIGID* p_buf = - reinterpret_cast(osi_malloc(sizeof(BT_HDR_RIGID))); + BT_HDR_RIGID* p_buf = reinterpret_cast(osi_malloc(sizeof(BT_HDR_RIGID))); p_buf->event = BTIF_MEDIA_SINK_SUSPEND; - btif_a2dp_sink_cb.worker_thread.DoInThread( - FROM_HERE, base::BindOnce(btif_a2dp_sink_command_ready, p_buf)); + btif_a2dp_sink_cb.worker_thread.DoInThread(FROM_HERE, + base::BindOnce(btif_a2dp_sink_command_ready, p_buf)); - if (btif_a2dp_sink_state == BTIF_A2DP_SINK_STATE_OFF) return; + if (btif_a2dp_sink_state == BTIF_A2DP_SINK_STATE_OFF) { + return; + } btif_a2dp_sink_audio_handle_stop_decoding(); btif_a2dp_sink_clear_track_event_req(); } void btif_a2dp_sink_on_stopped(tBTA_AV_SUSPEND* /* p_av_suspend */) { log::info(""); - BT_HDR_RIGID* p_buf = - reinterpret_cast(osi_malloc(sizeof(BT_HDR_RIGID))); + BT_HDR_RIGID* p_buf = reinterpret_cast(osi_malloc(sizeof(BT_HDR_RIGID))); p_buf->event = BTIF_MEDIA_SINK_SUSPEND; - btif_a2dp_sink_cb.worker_thread.DoInThread( - FROM_HERE, base::BindOnce(btif_a2dp_sink_command_ready, p_buf)); + btif_a2dp_sink_cb.worker_thread.DoInThread(FROM_HERE, + base::BindOnce(btif_a2dp_sink_command_ready, p_buf)); - if (btif_a2dp_sink_state == BTIF_A2DP_SINK_STATE_OFF) return; + if (btif_a2dp_sink_state == BTIF_A2DP_SINK_STATE_OFF) { + return; + } btif_a2dp_sink_audio_handle_stop_decoding(); } void btif_a2dp_sink_on_suspended(tBTA_AV_SUSPEND* /* p_av_suspend */) { log::info(""); - BT_HDR_RIGID* p_buf = - reinterpret_cast(osi_malloc(sizeof(BT_HDR_RIGID))); + BT_HDR_RIGID* p_buf = reinterpret_cast(osi_malloc(sizeof(BT_HDR_RIGID))); p_buf->event = BTIF_MEDIA_SINK_SUSPEND; - btif_a2dp_sink_cb.worker_thread.DoInThread( - FROM_HERE, base::BindOnce(btif_a2dp_sink_command_ready, p_buf)); + btif_a2dp_sink_cb.worker_thread.DoInThread(FROM_HERE, + base::BindOnce(btif_a2dp_sink_command_ready, p_buf)); - if (btif_a2dp_sink_state == BTIF_A2DP_SINK_STATE_OFF) return; + if (btif_a2dp_sink_state == BTIF_A2DP_SINK_STATE_OFF) { + return; + } btif_a2dp_sink_audio_handle_stop_decoding(); } bool btif_a2dp_sink_on_start() { log::info(""); - BT_HDR_RIGID* p_buf = - reinterpret_cast(osi_malloc(sizeof(BT_HDR_RIGID))); + BT_HDR_RIGID* p_buf = reinterpret_cast(osi_malloc(sizeof(BT_HDR_RIGID))); p_buf->event = BTIF_MEDIA_SINK_START; - btif_a2dp_sink_cb.worker_thread.DoInThread( - FROM_HERE, base::BindOnce(btif_a2dp_sink_command_ready, p_buf)); + btif_a2dp_sink_cb.worker_thread.DoInThread(FROM_HERE, + base::BindOnce(btif_a2dp_sink_command_ready, p_buf)); return true; } @@ -474,8 +463,8 @@ static void btif_a2dp_sink_audio_handle_stop_decoding() { static void btif_decode_alarm_cb(void* /* context */) { LockGuard lock(g_mutex); - btif_a2dp_sink_cb.worker_thread.DoInThread( - FROM_HERE, base::BindOnce(btif_a2dp_sink_avk_handle_timer)); + btif_a2dp_sink_cb.worker_thread.DoInThread(FROM_HERE, + base::BindOnce(btif_a2dp_sink_avk_handle_timer)); } static void btif_a2dp_sink_clear_track_event() { @@ -492,8 +481,9 @@ static void btif_a2dp_sink_clear_track_event() { // Must be called while locked. static void btif_a2dp_sink_audio_handle_start_decoding() { log::info(""); - if (btif_a2dp_sink_cb.decode_alarm != nullptr) + if (btif_a2dp_sink_cb.decode_alarm != nullptr) { return; // Already started decoding + } #ifdef __ANDROID__ BtifAvrcpAudioTrackStart(btif_a2dp_sink_cb.audio_track); @@ -504,28 +494,25 @@ static void btif_a2dp_sink_audio_handle_start_decoding() { log::error("unable to allocate decode alarm"); return; } - alarm_set(btif_a2dp_sink_cb.decode_alarm, BTIF_SINK_MEDIA_TIME_TICK_MS, - btif_decode_alarm_cb, nullptr); + alarm_set(btif_a2dp_sink_cb.decode_alarm, BTIF_SINK_MEDIA_TIME_TICK_MS, btif_decode_alarm_cb, + nullptr); } static void btif_a2dp_sink_on_decode_complete(uint8_t* data, uint32_t len) { #ifdef __ANDROID__ - BtifAvrcpAudioTrackWriteData(btif_a2dp_sink_cb.audio_track, - reinterpret_cast(data), len); + BtifAvrcpAudioTrackWriteData(btif_a2dp_sink_cb.audio_track, reinterpret_cast(data), len); #endif } // Must be called while locked. static void btif_a2dp_sink_handle_inc_media(BT_HDR* p_msg) { - if ((btif_av_get_peer_sep(A2dpType::kSink) == AVDT_TSEP_SNK) || - (btif_a2dp_sink_cb.rx_flush)) { + if ((btif_av_get_peer_sep(A2dpType::kSink) == AVDT_TSEP_SNK) || (btif_a2dp_sink_cb.rx_flush)) { log::verbose("state changed happened in this tick"); return; } - log::assert_that( - btif_a2dp_sink_cb.decoder_interface != nullptr, - "assert failed: btif_a2dp_sink_cb.decoder_interface != nullptr"); + log::assert_that(btif_a2dp_sink_cb.decoder_interface != nullptr, + "assert failed: btif_a2dp_sink_cb.decoder_interface != nullptr"); if (!btif_a2dp_sink_cb.decoder_interface->decode_packet(p_msg)) { log::error("decoding failed"); } @@ -582,14 +569,12 @@ static void btif_a2dp_sink_audio_rx_flush_event() { fixed_queue_flush(btif_a2dp_sink_cb.rx_audio_queue, osi_free); } -static void btif_a2dp_sink_decoder_update_event( - tBTIF_MEDIA_SINK_DECODER_UPDATE* p_buf) { +static void btif_a2dp_sink_decoder_update_event(tBTIF_MEDIA_SINK_DECODER_UPDATE* p_buf) { log::info(""); LockGuard lock(g_mutex); - log::verbose("p_codec_info[{:x}:{:x}:{:x}:{:x}:{:x}:{:x}]", - p_buf->codec_info[1], p_buf->codec_info[2], p_buf->codec_info[3], - p_buf->codec_info[4], p_buf->codec_info[5], - p_buf->codec_info[6]); + log::verbose("p_codec_info[{:x}:{:x}:{:x}:{:x}:{:x}:{:x}]", p_buf->codec_info[1], + p_buf->codec_info[2], p_buf->codec_info[3], p_buf->codec_info[4], + p_buf->codec_info[5], p_buf->codec_info[6]); int sample_rate = A2DP_GetTrackSampleRate(p_buf->codec_info); if (sample_rate == -1) { @@ -620,16 +605,14 @@ static void btif_a2dp_sink_decoder_update_event( bta_av_co_save_codec(p_buf->codec_info); - btif_a2dp_sink_cb.decoder_interface = - A2DP_GetDecoderInterface(p_buf->codec_info); + btif_a2dp_sink_cb.decoder_interface = A2DP_GetDecoderInterface(p_buf->codec_info); if (btif_a2dp_sink_cb.decoder_interface == nullptr) { log::error("cannot stream audio: no source decoder interface"); return; } - if (!btif_a2dp_sink_cb.decoder_interface->decoder_init( - btif_a2dp_sink_on_decode_complete)) { + if (!btif_a2dp_sink_cb.decoder_interface->decoder_init(btif_a2dp_sink_on_decode_complete)) { log::error("failed to initialize decoder"); return; } @@ -641,9 +624,9 @@ static void btif_a2dp_sink_decoder_update_event( log::verbose("create audio track"); btif_a2dp_sink_cb.audio_track = #ifdef __ANDROID__ - BtifAvrcpAudioTrackCreate(sample_rate, bits_per_sample, channel_count); + BtifAvrcpAudioTrackCreate(sample_rate, bits_per_sample, channel_count); #else - NULL; + NULL; #endif if (btif_a2dp_sink_cb.audio_track == nullptr) { log::error("track creation failed"); @@ -653,20 +636,19 @@ static void btif_a2dp_sink_decoder_update_event( uint8_t btif_a2dp_sink_enqueue_buf(BT_HDR* p_pkt) { LockGuard lock(g_mutex); - if (btif_a2dp_sink_cb.rx_flush) /* Flush enabled, do not enqueue */ + if (btif_a2dp_sink_cb.rx_flush) { /* Flush enabled, do not enqueue */ return fixed_queue_length(btif_a2dp_sink_cb.rx_audio_queue); + } log::verbose("+"); /* Allocate and queue this buffer */ - BT_HDR* p_msg = - reinterpret_cast(osi_malloc(sizeof(*p_msg) + p_pkt->len)); + BT_HDR* p_msg = reinterpret_cast(osi_malloc(sizeof(*p_msg) + p_pkt->len)); memcpy(p_msg, p_pkt, sizeof(*p_msg)); p_msg->offset = 0; memcpy(p_msg->data, p_pkt->data + p_pkt->offset, p_pkt->len); fixed_queue_enqueue(btif_a2dp_sink_cb.rx_audio_queue, p_msg); - if (fixed_queue_length(btif_a2dp_sink_cb.rx_audio_queue) == - MAX_INPUT_A2DP_FRAME_QUEUE_SZ) { + if (fixed_queue_length(btif_a2dp_sink_cb.rx_audio_queue) == MAX_INPUT_A2DP_FRAME_QUEUE_SZ) { osi_free(fixed_queue_try_dequeue(btif_a2dp_sink_cb.rx_audio_queue)); uint8_t ret = fixed_queue_length(btif_a2dp_sink_cb.rx_audio_queue); return ret; @@ -674,10 +656,8 @@ uint8_t btif_a2dp_sink_enqueue_buf(BT_HDR* p_pkt) { // Avoid other checks if alarm has already been initialized. if (btif_a2dp_sink_cb.decode_alarm == nullptr && - fixed_queue_length(btif_a2dp_sink_cb.rx_audio_queue) >= - MAX_A2DP_DELAYED_START_FRAME_COUNT) { - log::verbose("Initiate decoding. Current focus state:{}", - btif_a2dp_sink_cb.rx_focus_state); + fixed_queue_length(btif_a2dp_sink_cb.rx_audio_queue) >= MAX_A2DP_DELAYED_START_FRAME_COUNT) { + log::verbose("Initiate decoding. Current focus state:{}", btif_a2dp_sink_cb.rx_focus_state); if (btif_a2dp_sink_cb.rx_focus_state == BTIF_A2DP_SINK_FOCUS_GRANTED) { btif_a2dp_sink_audio_handle_start_decoding(); } @@ -693,11 +673,10 @@ void btif_a2dp_sink_audio_rx_flush_req() { return; } - BT_HDR_RIGID* p_buf = - reinterpret_cast(osi_malloc(sizeof(BT_HDR_RIGID))); + BT_HDR_RIGID* p_buf = reinterpret_cast(osi_malloc(sizeof(BT_HDR_RIGID))); p_buf->event = BTIF_MEDIA_SINK_AUDIO_RX_FLUSH; - btif_a2dp_sink_cb.worker_thread.DoInThread( - FROM_HERE, base::BindOnce(btif_a2dp_sink_command_ready, p_buf)); + btif_a2dp_sink_cb.worker_thread.DoInThread(FROM_HERE, + base::BindOnce(btif_a2dp_sink_command_ready, p_buf)); } void btif_a2dp_sink_debug_dump(int /* fd */) { @@ -706,18 +685,15 @@ void btif_a2dp_sink_debug_dump(int /* fd */) { void btif_a2dp_sink_set_focus_state_req(btif_a2dp_sink_focus_state_t state) { log::info(""); - tBTIF_MEDIA_SINK_FOCUS_UPDATE* p_buf = - reinterpret_cast( + tBTIF_MEDIA_SINK_FOCUS_UPDATE* p_buf = reinterpret_cast( osi_malloc(sizeof(tBTIF_MEDIA_SINK_FOCUS_UPDATE))); p_buf->focus_state = state; p_buf->hdr.event = BTIF_MEDIA_SINK_SET_FOCUS_STATE; btif_a2dp_sink_cb.worker_thread.DoInThread( - FROM_HERE, - base::BindOnce(btif_a2dp_sink_command_ready, (BT_HDR_RIGID*)p_buf)); + FROM_HERE, base::BindOnce(btif_a2dp_sink_command_ready, (BT_HDR_RIGID*)p_buf)); } -static void btif_a2dp_sink_set_focus_state_event( - btif_a2dp_sink_focus_state_t state) { +static void btif_a2dp_sink_set_focus_state_event(btif_a2dp_sink_focus_state_t state) { log::info("state={}", state); LockGuard lock(g_mutex); @@ -740,19 +716,15 @@ void btif_a2dp_sink_set_audio_track_gain(float gain) { #endif } -void * btif_a2dp_sink_get_audio_track(void) -{ - return btif_a2dp_sink_cb.audio_track; -} +void* btif_a2dp_sink_get_audio_track(void) { return btif_a2dp_sink_cb.audio_track; } static void btif_a2dp_sink_clear_track_event_req() { log::info(""); - BT_HDR_RIGID* p_buf = - reinterpret_cast(osi_malloc(sizeof(BT_HDR_RIGID))); + BT_HDR_RIGID* p_buf = reinterpret_cast(osi_malloc(sizeof(BT_HDR_RIGID))); p_buf->event = BTIF_MEDIA_SINK_CLEAR_TRACK; - btif_a2dp_sink_cb.worker_thread.DoInThread( - FROM_HERE, base::BindOnce(btif_a2dp_sink_command_ready, p_buf)); + btif_a2dp_sink_cb.worker_thread.DoInThread(FROM_HERE, + base::BindOnce(btif_a2dp_sink_command_ready, p_buf)); } static void btif_a2dp_sink_on_start_event() { diff --git a/system/btif/src/btif_a2dp_source.cc b/system/btif/src/btif_a2dp_source.cc index 0885634b075..9da576698dd 100644 --- a/system/btif/src/btif_a2dp_source.cc +++ b/system/btif/src/btif_a2dp_source.cc @@ -66,7 +66,7 @@ using namespace bluetooth; #define MAX_OUTPUT_A2DP_FRAME_QUEUE_SZ (MAX_PCM_FRAME_NUM_PER_TICK * 2) class SchedulingStats { - public: +public: SchedulingStats() { Reset(); } void Reset() { total_updates = 0; @@ -113,7 +113,7 @@ class SchedulingStats { }; class BtifMediaStats { - public: +public: BtifMediaStats() { Reset(); } void Reset() { session_start_us = 0; @@ -169,13 +169,8 @@ class BtifMediaStats { }; class BtifA2dpSource { - public: - enum RunState { - kStateOff, - kStateStartingUp, - kStateRunning, - kStateShuttingDown - }; +public: + enum RunState { kStateOff, kStateStartingUp, kStateRunning, kStateShuttingDown }; BtifA2dpSource() : tx_audio_queue(nullptr), @@ -223,23 +218,20 @@ class BtifA2dpSource { BtifMediaStats stats; BtifMediaStats accumulated_stats; - private: +private: BtifA2dpSource::RunState state_; }; -static bluetooth::common::MessageLoopThread btif_a2dp_source_thread( - "bt_a2dp_source_worker_thread"); +static bluetooth::common::MessageLoopThread btif_a2dp_source_thread("bt_a2dp_source_worker_thread"); static BtifA2dpSource btif_a2dp_source_cb; -static uint8_t btif_a2dp_source_dynamic_audio_buffer_size = - MAX_OUTPUT_A2DP_FRAME_QUEUE_SZ; +static uint8_t btif_a2dp_source_dynamic_audio_buffer_size = MAX_OUTPUT_A2DP_FRAME_QUEUE_SZ; static void btif_a2dp_source_init_delayed(void); static void btif_a2dp_source_startup_delayed(void); -static void btif_a2dp_source_start_session_delayed( - const RawAddress& peer_address, std::promise start_session_promise); -static void btif_a2dp_source_end_session_delayed( - const RawAddress& peer_address); +static void btif_a2dp_source_start_session_delayed(const RawAddress& peer_address, + std::promise start_session_promise); +static void btif_a2dp_source_end_session_delayed(const RawAddress& peer_address); static void btif_a2dp_source_shutdown_delayed(std::promise); static void btif_a2dp_source_cleanup_delayed(void); static void btif_a2dp_source_audio_tx_start_event(void); @@ -249,21 +241,19 @@ static void btif_a2dp_source_audio_tx_flush_event(void); // The peer address is |peer_addr|. // This function should be called prior to starting A2DP streaming. static void btif_a2dp_source_setup_codec(const RawAddress& peer_addr); -static void btif_a2dp_source_setup_codec_delayed( - const RawAddress& peer_address); +static void btif_a2dp_source_setup_codec_delayed(const RawAddress& peer_address); static void btif_a2dp_source_cleanup_codec(); static void btif_a2dp_source_cleanup_codec_delayed(); static void btif_a2dp_source_encoder_user_config_update_event( - const RawAddress& peer_address, - const std::vector& codec_user_preferences, - std::promise peer_ready_promise); + const RawAddress& peer_address, + const std::vector& codec_user_preferences, + std::promise peer_ready_promise); static void btif_a2dp_source_audio_feeding_update_event( - const btav_a2dp_codec_config_t& codec_audio_config); + const btav_a2dp_codec_config_t& codec_audio_config); static bool btif_a2dp_source_audio_tx_flush_req(void); static void btif_a2dp_source_audio_handle_timer(void); static uint32_t btif_a2dp_source_read_callback(uint8_t* p_buf, uint32_t len); -static bool btif_a2dp_source_enqueue_callback(BT_HDR* p_buf, size_t frames_n, - uint32_t bytes_read); +static bool btif_a2dp_source_enqueue_callback(BT_HDR* p_buf, size_t frames_n, uint32_t bytes_read); static void log_tstamps_us(const char* comment, uint64_t timestamp_us); static void update_scheduling_stats(SchedulingStats* stats, uint64_t now_us, uint64_t expected_delta); @@ -274,49 +264,43 @@ static void btm_read_rssi_cb(void* data); static void btm_read_failed_contact_counter_cb(void* data); static void btm_read_tx_power_cb(void* data); -void btif_a2dp_source_accumulate_scheduling_stats(SchedulingStats* src, - SchedulingStats* dst) { +void btif_a2dp_source_accumulate_scheduling_stats(SchedulingStats* src, SchedulingStats* dst) { dst->total_updates += src->total_updates; dst->last_update_us = src->last_update_us; dst->overdue_scheduling_count += src->overdue_scheduling_count; - dst->total_overdue_scheduling_delta_us += - src->total_overdue_scheduling_delta_us; + dst->total_overdue_scheduling_delta_us += src->total_overdue_scheduling_delta_us; dst->max_overdue_scheduling_delta_us = - std::max(dst->max_overdue_scheduling_delta_us, - src->max_overdue_scheduling_delta_us); + std::max(dst->max_overdue_scheduling_delta_us, src->max_overdue_scheduling_delta_us); dst->premature_scheduling_count += src->premature_scheduling_count; - dst->total_premature_scheduling_delta_us += - src->total_premature_scheduling_delta_us; + dst->total_premature_scheduling_delta_us += src->total_premature_scheduling_delta_us; dst->max_premature_scheduling_delta_us = - std::max(dst->max_premature_scheduling_delta_us, - src->max_premature_scheduling_delta_us); + std::max(dst->max_premature_scheduling_delta_us, src->max_premature_scheduling_delta_us); dst->exact_scheduling_count += src->exact_scheduling_count; dst->total_scheduling_time_us += src->total_scheduling_time_us; } -void btif_a2dp_source_accumulate_stats(BtifMediaStats* src, - BtifMediaStats* dst) { +void btif_a2dp_source_accumulate_stats(BtifMediaStats* src, BtifMediaStats* dst) { dst->tx_queue_total_frames += src->tx_queue_total_frames; - dst->tx_queue_max_frames_per_packet = std::max( - dst->tx_queue_max_frames_per_packet, src->tx_queue_max_frames_per_packet); + dst->tx_queue_max_frames_per_packet = + std::max(dst->tx_queue_max_frames_per_packet, src->tx_queue_max_frames_per_packet); dst->tx_queue_total_queueing_time_us += src->tx_queue_total_queueing_time_us; - dst->tx_queue_max_queueing_time_us = std::max( - dst->tx_queue_max_queueing_time_us, src->tx_queue_max_queueing_time_us); + dst->tx_queue_max_queueing_time_us = + std::max(dst->tx_queue_max_queueing_time_us, src->tx_queue_max_queueing_time_us); dst->tx_queue_total_readbuf_calls += src->tx_queue_total_readbuf_calls; dst->tx_queue_last_readbuf_us = src->tx_queue_last_readbuf_us; dst->tx_queue_total_flushed_messages += src->tx_queue_total_flushed_messages; dst->tx_queue_last_flushed_us = src->tx_queue_last_flushed_us; dst->tx_queue_total_dropped_messages += src->tx_queue_total_dropped_messages; - dst->tx_queue_max_dropped_messages = std::max( - dst->tx_queue_max_dropped_messages, src->tx_queue_max_dropped_messages); + dst->tx_queue_max_dropped_messages = + std::max(dst->tx_queue_max_dropped_messages, src->tx_queue_max_dropped_messages); dst->tx_queue_dropouts += src->tx_queue_dropouts; dst->tx_queue_last_dropouts_us = src->tx_queue_last_dropouts_us; - dst->media_read_total_underflow_bytes += - src->media_read_total_underflow_bytes; - dst->media_read_total_underflow_count += - src->media_read_total_underflow_count; + dst->media_read_total_underflow_bytes += src->media_read_total_underflow_bytes; + dst->media_read_total_underflow_count += src->media_read_total_underflow_count; dst->media_read_last_underflow_us = src->media_read_last_underflow_us; - if (dst->codec_index < 0) dst->codec_index = src->codec_index; + if (dst->codec_index < 0) { + dst->codec_index = src->codec_index; + } btif_a2dp_source_accumulate_scheduling_stats(&src->tx_queue_enqueue_stats, &dst->tx_queue_enqueue_stats); btif_a2dp_source_accumulate_scheduling_stats(&src->tx_queue_dequeue_stats, @@ -329,8 +313,7 @@ bool btif_a2dp_source_init(void) { // Start A2DP Source media task btif_a2dp_source_thread.StartUp(); - btif_a2dp_source_thread.DoInThread( - FROM_HERE, base::BindOnce(&btif_a2dp_source_init_delayed)); + btif_a2dp_source_thread.DoInThread(FROM_HERE, base::BindOnce(&btif_a2dp_source_init_delayed)); return true; } @@ -358,8 +341,7 @@ bool btif_a2dp_source_startup(void) { btif_a2dp_source_cb.tx_audio_queue = fixed_queue_new(SIZE_MAX); // Schedule the rest of the operations - btif_a2dp_source_thread.DoInThread( - FROM_HERE, base::BindOnce(&btif_a2dp_source_startup_delayed)); + btif_a2dp_source_thread.DoInThread(FROM_HERE, base::BindOnce(&btif_a2dp_source_startup_delayed)); return true; } @@ -379,13 +361,11 @@ static void btif_a2dp_source_startup_delayed() { bool btif_a2dp_source_start_session(const RawAddress& peer_address, std::promise peer_ready_promise) { - log::info("peer_address={} state={}", peer_address, - btif_a2dp_source_cb.StateStr()); + log::info("peer_address={} state={}", peer_address, btif_a2dp_source_cb.StateStr()); btif_a2dp_source_setup_codec(peer_address); if (btif_a2dp_source_thread.DoInThread( - FROM_HERE, - base::BindOnce(&btif_a2dp_source_start_session_delayed, peer_address, - std::move(peer_ready_promise)))) { + FROM_HERE, base::BindOnce(&btif_a2dp_source_start_session_delayed, peer_address, + std::move(peer_ready_promise)))) { return true; } else { // cannot set promise but triggers crash @@ -395,10 +375,9 @@ bool btif_a2dp_source_start_session(const RawAddress& peer_address, } } -static void btif_a2dp_source_start_session_delayed( - const RawAddress& peer_address, std::promise peer_ready_promise) { - log::info("peer_address={} state={}", peer_address, - btif_a2dp_source_cb.StateStr()); +static void btif_a2dp_source_start_session_delayed(const RawAddress& peer_address, + std::promise peer_ready_promise) { + log::info("peer_address={} state={}", peer_address, btif_a2dp_source_cb.StateStr()); if (btif_a2dp_source_cb.State() != BtifA2dpSource::kStateRunning) { log::error("A2DP Source media task is not running"); peer_ready_promise.set_value(); @@ -406,13 +385,12 @@ static void btif_a2dp_source_start_session_delayed( } if (bluetooth::audio::a2dp::is_hal_enabled()) { bluetooth::audio::a2dp::start_session(); - bluetooth::audio::a2dp::set_remote_delay( - btif_av_get_audio_delay(A2dpType::kSource)); + bluetooth::audio::a2dp::set_remote_delay(btif_av_get_audio_delay(A2dpType::kSource)); BluetoothMetricsLogger::GetInstance()->LogBluetoothSessionStart( - bluetooth::common::CONNECTION_TECHNOLOGY_TYPE_BREDR, 0); + bluetooth::common::CONNECTION_TECHNOLOGY_TYPE_BREDR, 0); } else { BluetoothMetricsLogger::GetInstance()->LogBluetoothSessionStart( - bluetooth::common::CONNECTION_TECHNOLOGY_TYPE_BREDR, 0); + bluetooth::common::CONNECTION_TECHNOLOGY_TYPE_BREDR, 0); } peer_ready_promise.set_value(); } @@ -420,11 +398,10 @@ static void btif_a2dp_source_start_session_delayed( bool btif_a2dp_source_restart_session(const RawAddress& old_peer_address, const RawAddress& new_peer_address, std::promise peer_ready_promise) { - log::info("old_peer_address={} new_peer_address={} state={}", - old_peer_address, new_peer_address, btif_a2dp_source_cb.StateStr()); + log::info("old_peer_address={} new_peer_address={} state={}", old_peer_address, new_peer_address, + btif_a2dp_source_cb.StateStr()); - log::assert_that(!new_peer_address.IsEmpty(), - "assert failed: !new_peer_address.IsEmpty()"); + log::assert_that(!new_peer_address.IsEmpty(), "assert failed: !new_peer_address.IsEmpty()"); // Must stop first the audio streaming btif_a2dp_source_stop_audio_req(); @@ -438,27 +415,22 @@ bool btif_a2dp_source_restart_session(const RawAddress& old_peer_address, } // Start the session. - btif_a2dp_source_start_session(new_peer_address, - std::move(peer_ready_promise)); + btif_a2dp_source_start_session(new_peer_address, std::move(peer_ready_promise)); // If audio was streaming before, DON'T start audio streaming, but leave the // control to the audio HAL. return true; } bool btif_a2dp_source_end_session(const RawAddress& peer_address) { - log::info("peer_address={} state={}", peer_address, - btif_a2dp_source_cb.StateStr()); + log::info("peer_address={} state={}", peer_address, btif_a2dp_source_cb.StateStr()); btif_a2dp_source_thread.DoInThread( - FROM_HERE, - base::BindOnce(&btif_a2dp_source_end_session_delayed, peer_address)); + FROM_HERE, base::BindOnce(&btif_a2dp_source_end_session_delayed, peer_address)); btif_a2dp_source_cleanup_codec(); return true; } -static void btif_a2dp_source_end_session_delayed( - const RawAddress& peer_address) { - log::info("peer_address={} state={}", peer_address, - btif_a2dp_source_cb.StateStr()); +static void btif_a2dp_source_end_session_delayed(const RawAddress& peer_address) { + log::info("peer_address={} state={}", peer_address, btif_a2dp_source_cb.StateStr()); if ((btif_a2dp_source_cb.State() == BtifA2dpSource::kStateRunning) || (btif_a2dp_source_cb.State() == BtifA2dpSource::kStateShuttingDown)) { btif_av_stream_stop(peer_address); @@ -468,10 +440,10 @@ static void btif_a2dp_source_end_session_delayed( if (bluetooth::audio::a2dp::is_hal_enabled()) { bluetooth::audio::a2dp::end_session(); BluetoothMetricsLogger::GetInstance()->LogBluetoothSessionEnd( - bluetooth::common::DISCONNECT_REASON_UNKNOWN, 0); + bluetooth::common::DISCONNECT_REASON_UNKNOWN, 0); } else { BluetoothMetricsLogger::GetInstance()->LogBluetoothSessionEnd( - bluetooth::common::DISCONNECT_REASON_UNKNOWN, 0); + bluetooth::common::DISCONNECT_REASON_UNKNOWN, 0); } } @@ -487,12 +459,11 @@ void btif_a2dp_source_shutdown(std::promise shutdown_complete_promise) { btif_a2dp_source_cb.SetState(BtifA2dpSource::kStateShuttingDown); btif_a2dp_source_thread.DoInThread( - FROM_HERE, base::BindOnce(&btif_a2dp_source_shutdown_delayed, - std::move(shutdown_complete_promise))); + FROM_HERE, + base::BindOnce(&btif_a2dp_source_shutdown_delayed, std::move(shutdown_complete_promise))); } -static void btif_a2dp_source_shutdown_delayed( - std::promise shutdown_complete_promise) { +static void btif_a2dp_source_shutdown_delayed(std::promise shutdown_complete_promise) { log::info("state={}", btif_a2dp_source_cb.StateStr()); // Stop the timer @@ -516,8 +487,7 @@ void btif_a2dp_source_cleanup(void) { std::promise shutdown_complete_promise; btif_a2dp_source_shutdown(std::move(shutdown_complete_promise)); - btif_a2dp_source_thread.DoInThread( - FROM_HERE, base::BindOnce(&btif_a2dp_source_cleanup_delayed)); + btif_a2dp_source_thread.DoInThread(FROM_HERE, base::BindOnce(&btif_a2dp_source_cleanup_delayed)); // Exit the thread btif_a2dp_source_thread.ShutDown(); @@ -529,21 +499,18 @@ static void btif_a2dp_source_cleanup_delayed(void) { } bool btif_a2dp_source_media_task_is_running(void) { - return (btif_a2dp_source_cb.State() == BtifA2dpSource::kStateRunning); + return btif_a2dp_source_cb.State() == BtifA2dpSource::kStateRunning; } bool btif_a2dp_source_media_task_is_shutting_down(void) { - return (btif_a2dp_source_cb.State() == BtifA2dpSource::kStateShuttingDown); + return btif_a2dp_source_cb.State() == BtifA2dpSource::kStateShuttingDown; } // This runs on worker thread -bool btif_a2dp_source_is_streaming(void) { - return btif_a2dp_source_cb.media_alarm.IsScheduled(); -} +bool btif_a2dp_source_is_streaming(void) { return btif_a2dp_source_cb.media_alarm.IsScheduled(); } static void btif_a2dp_source_setup_codec(const RawAddress& peer_address) { - log::info("peer_address={} state={}", peer_address, - btif_a2dp_source_cb.StateStr()); + log::info("peer_address={} state={}", peer_address, btif_a2dp_source_cb.StateStr()); // Check to make sure the platform has 8 bits/byte since // we're using that in frame size calculations now. @@ -551,27 +518,22 @@ static void btif_a2dp_source_setup_codec(const RawAddress& peer_address) { btif_a2dp_source_audio_tx_flush_req(); btif_a2dp_source_thread.DoInThread( - FROM_HERE, - base::BindOnce(&btif_a2dp_source_setup_codec_delayed, peer_address)); + FROM_HERE, base::BindOnce(&btif_a2dp_source_setup_codec_delayed, peer_address)); } -static void btif_a2dp_source_setup_codec_delayed( - const RawAddress& peer_address) { - log::info("peer_address={} state={}", peer_address, - btif_a2dp_source_cb.StateStr()); +static void btif_a2dp_source_setup_codec_delayed(const RawAddress& peer_address) { + log::info("peer_address={} state={}", peer_address, btif_a2dp_source_cb.StateStr()); tA2DP_ENCODER_INIT_PEER_PARAMS peer_params; bta_av_co_get_peer_params(peer_address, &peer_params); if (com::android::bluetooth::flags::a2dp_concurrent_source_sink()) { if (!bta_av_co_set_active_source_peer(peer_address)) { - log::error("Cannot stream audio: cannot set active peer to {}", - peer_address); + log::error("Cannot stream audio: cannot set active peer to {}", peer_address); return; } } else { if (!bta_av_co_set_active_peer(peer_address)) { - log::error("Cannot stream audio: cannot set active peer to {}", - peer_address); + log::error("Cannot stream audio: cannot set active peer to {}", peer_address); return; } } @@ -587,13 +549,13 @@ static void btif_a2dp_source_setup_codec_delayed( return; } - btif_a2dp_source_cb.encoder_interface->encoder_init( - &peer_params, a2dp_codec_config, btif_a2dp_source_read_callback, - btif_a2dp_source_enqueue_callback); + btif_a2dp_source_cb.encoder_interface->encoder_init(&peer_params, a2dp_codec_config, + btif_a2dp_source_read_callback, + btif_a2dp_source_enqueue_callback); // Save a local copy of the encoder_interval_ms btif_a2dp_source_cb.encoder_interval_ms = - btif_a2dp_source_cb.encoder_interface->get_encoder_interval_ms(); + btif_a2dp_source_cb.encoder_interface->get_encoder_interval_ms(); if (bluetooth::audio::a2dp::is_hal_enabled()) { bluetooth::audio::a2dp::setup_codec(); @@ -604,8 +566,8 @@ static void btif_a2dp_source_cleanup_codec() { log::info("state={}", btif_a2dp_source_cb.StateStr()); // Must stop media task first before cleaning up the encoder btif_a2dp_source_stop_audio_req(); - btif_a2dp_source_thread.DoInThread( - FROM_HERE, base::BindOnce(&btif_a2dp_source_cleanup_codec_delayed)); + btif_a2dp_source_thread.DoInThread(FROM_HERE, + base::BindOnce(&btif_a2dp_source_cleanup_codec_delayed)); } static void btif_a2dp_source_cleanup_codec_delayed() { @@ -619,28 +581,27 @@ static void btif_a2dp_source_cleanup_codec_delayed() { void btif_a2dp_source_start_audio_req(void) { log::info("state={}", btif_a2dp_source_cb.StateStr()); - btif_a2dp_source_thread.DoInThread( - FROM_HERE, base::BindOnce(&btif_a2dp_source_audio_tx_start_event)); + btif_a2dp_source_thread.DoInThread(FROM_HERE, + base::BindOnce(&btif_a2dp_source_audio_tx_start_event)); } void btif_a2dp_source_stop_audio_req(void) { log::info("state={}", btif_a2dp_source_cb.StateStr()); - btif_a2dp_source_thread.DoInThread( - FROM_HERE, base::BindOnce(&btif_a2dp_source_audio_tx_stop_event)); + btif_a2dp_source_thread.DoInThread(FROM_HERE, + base::BindOnce(&btif_a2dp_source_audio_tx_stop_event)); } void btif_a2dp_source_encoder_user_config_update_req( - const RawAddress& peer_address, - const std::vector& codec_user_preferences, - std::promise peer_ready_promise) { + const RawAddress& peer_address, + const std::vector& codec_user_preferences, + std::promise peer_ready_promise) { log::info("peer_address={} state={} {} codec_preference(s)", peer_address, btif_a2dp_source_cb.StateStr(), codec_user_preferences.size()); if (!btif_a2dp_source_thread.DoInThread( - FROM_HERE, - base::BindOnce(&btif_a2dp_source_encoder_user_config_update_event, - peer_address, codec_user_preferences, - std::move(peer_ready_promise)))) { + FROM_HERE, + base::BindOnce(&btif_a2dp_source_encoder_user_config_update_event, peer_address, + codec_user_preferences, std::move(peer_ready_promise)))) { // cannot set promise but triggers crash log::fatal("peer_address={} state={} fails to context switch", peer_address, btif_a2dp_source_cb.StateStr()); @@ -648,19 +609,16 @@ void btif_a2dp_source_encoder_user_config_update_req( } static void btif_a2dp_source_encoder_user_config_update_event( - const RawAddress& peer_address, - const std::vector& codec_user_preferences, - std::promise peer_ready_promise) { + const RawAddress& peer_address, + const std::vector& codec_user_preferences, + std::promise peer_ready_promise) { bool restart_output = false; bool success = false; for (auto codec_user_config : codec_user_preferences) { - success = bta_av_co_set_codec_user_config(peer_address, codec_user_config, - &restart_output); + success = bta_av_co_set_codec_user_config(peer_address, codec_user_config, &restart_output); if (success) { - log::info( - "peer_address={} state={} codec_preference=[{}] restart_output={}", - peer_address, btif_a2dp_source_cb.StateStr(), - codec_user_config.ToString(), restart_output); + log::info("peer_address={} state={} codec_preference=[{}] restart_output={}", peer_address, + btif_a2dp_source_cb.StateStr(), codec_user_config.ToString(), restart_output); break; } } @@ -684,16 +642,15 @@ static void btif_a2dp_source_encoder_user_config_update_event( } } -void btif_a2dp_source_feeding_update_req( - const btav_a2dp_codec_config_t& codec_audio_config) { +void btif_a2dp_source_feeding_update_req(const btav_a2dp_codec_config_t& codec_audio_config) { log::info("state={}", btif_a2dp_source_cb.StateStr()); btif_a2dp_source_thread.DoInThread( - FROM_HERE, base::BindOnce(&btif_a2dp_source_audio_feeding_update_event, - codec_audio_config)); + FROM_HERE, + base::BindOnce(&btif_a2dp_source_audio_feeding_update_event, codec_audio_config)); } static void btif_a2dp_source_audio_feeding_update_event( - const btav_a2dp_codec_config_t& codec_audio_config) { + const btav_a2dp_codec_config_t& codec_audio_config) { log::info("state={}", btif_a2dp_source_cb.StateStr()); if (!bta_av_co_set_codec_audio_config(codec_audio_config)) { log::error("cannot update codec audio feeding parameters"); @@ -702,7 +659,9 @@ static void btif_a2dp_source_audio_feeding_update_event( void btif_a2dp_source_on_idle(void) { log::info("state={}", btif_a2dp_source_cb.StateStr()); - if (btif_a2dp_source_cb.State() == BtifA2dpSource::kStateOff) return; + if (btif_a2dp_source_cb.State() == BtifA2dpSource::kStateOff) { + return; + } /* Make sure media task is stopped */ btif_a2dp_source_stop_audio_req(); @@ -716,8 +675,8 @@ void btif_a2dp_source_on_stopped(tBTA_AV_SUSPEND* p_av_suspend) { // allow using this API for other (acknowledgement and stopping media task) // than suspend if (p_av_suspend != nullptr && p_av_suspend->status != BTA_AV_SUCCESS) { - log::error("A2DP stop failed: status={}, initiator={}", - p_av_suspend->status, p_av_suspend->initiator); + log::error("A2DP stop failed: status={}, initiator={}", p_av_suspend->status, + p_av_suspend->initiator); if (p_av_suspend->initiator) { bluetooth::audio::a2dp::ack_stream_suspended(BluetoothAudioStatus::FAILURE); } @@ -726,7 +685,9 @@ void btif_a2dp_source_on_stopped(tBTA_AV_SUSPEND* p_av_suspend) { return; } - if (btif_a2dp_source_cb.State() == BtifA2dpSource::kStateOff) return; + if (btif_a2dp_source_cb.State() == BtifA2dpSource::kStateOff) { + return; + } // ensure tx frames are immediately suspended btif_a2dp_source_cb.tx_flush = true; @@ -742,15 +703,16 @@ void btif_a2dp_source_on_stopped(tBTA_AV_SUSPEND* p_av_suspend) { void btif_a2dp_source_on_suspended(tBTA_AV_SUSPEND* p_av_suspend) { log::info("state={}", btif_a2dp_source_cb.StateStr()); - if (btif_a2dp_source_cb.State() == BtifA2dpSource::kStateOff) return; + if (btif_a2dp_source_cb.State() == BtifA2dpSource::kStateOff) { + return; + } - log::assert_that(p_av_suspend != nullptr, - "Suspend result could not be nullptr"); + log::assert_that(p_av_suspend != nullptr, "Suspend result could not be nullptr"); // check for status failures if (p_av_suspend->status != BTA_AV_SUCCESS) { - log::warn("A2DP suspend failed: status={}, initiator={}", - p_av_suspend->status, p_av_suspend->initiator); + log::warn("A2DP suspend failed: status={}, initiator={}", p_av_suspend->status, + p_av_suspend->initiator); if (p_av_suspend->initiator) { bluetooth::audio::a2dp::ack_stream_suspended(BluetoothAudioStatus::FAILURE); } @@ -778,35 +740,34 @@ static void btif_a2dp_source_audio_tx_start_event(void) { log::info("streaming {} state={}", btif_a2dp_source_is_streaming(), btif_a2dp_source_cb.StateStr()); - if (btif_av_is_a2dp_offload_running()) return; + if (btif_av_is_a2dp_offload_running()) { + return; + } /* Reset the media feeding state */ - log::assert_that( - btif_a2dp_source_cb.encoder_interface != nullptr, - "assert failed: btif_a2dp_source_cb.encoder_interface != nullptr"); + log::assert_that(btif_a2dp_source_cb.encoder_interface != nullptr, + "assert failed: btif_a2dp_source_cb.encoder_interface != nullptr"); btif_a2dp_source_cb.encoder_interface->feeding_reset(); - log::verbose( - "starting timer {} ms", - btif_a2dp_source_cb.encoder_interface->get_encoder_interval_ms()); + log::verbose("starting timer {} ms", + btif_a2dp_source_cb.encoder_interface->get_encoder_interval_ms()); /* audio engine starting, reset tx suspended flag */ btif_a2dp_source_cb.tx_flush = false; wakelock_acquire(); btif_a2dp_source_cb.media_alarm.SchedulePeriodic( - btif_a2dp_source_thread.GetWeakPtr(), FROM_HERE, - base::BindRepeating(&btif_a2dp_source_audio_handle_timer), - std::chrono::milliseconds( - btif_a2dp_source_cb.encoder_interface->get_encoder_interval_ms())); + btif_a2dp_source_thread.GetWeakPtr(), FROM_HERE, + base::BindRepeating(&btif_a2dp_source_audio_handle_timer), + std::chrono::milliseconds( + btif_a2dp_source_cb.encoder_interface->get_encoder_interval_ms())); btif_a2dp_source_cb.sw_audio_is_encoding = true; btif_a2dp_source_cb.stats.Reset(); // Assign session_start_us to 1 when // bluetooth::common::time_get_os_boottime_us() is 0 to indicate // btif_a2dp_source_start_audio_req() has been called - btif_a2dp_source_cb.stats.session_start_us = - bluetooth::common::time_get_os_boottime_us(); + btif_a2dp_source_cb.stats.session_start_us = bluetooth::common::time_get_os_boottime_us(); if (btif_a2dp_source_cb.stats.session_start_us == 0) { btif_a2dp_source_cb.stats.session_start_us = 1; } @@ -821,11 +782,14 @@ static void btif_a2dp_source_audio_tx_stop_event(void) { log::info("streaming {} state={}", btif_a2dp_source_is_streaming(), btif_a2dp_source_cb.StateStr()); - if (btif_av_is_a2dp_offload_running()) return; - if (!btif_a2dp_source_is_streaming()) return; + if (btif_av_is_a2dp_offload_running()) { + return; + } + if (!btif_a2dp_source_is_streaming()) { + return; + } - btif_a2dp_source_cb.stats.session_end_us = - bluetooth::common::time_get_os_boottime_us(); + btif_a2dp_source_cb.stats.session_end_us = bluetooth::common::time_get_os_boottime_us(); btif_a2dp_source_update_metrics(); btif_a2dp_source_accumulate_stats(&btif_a2dp_source_cb.stats, &btif_a2dp_source_cb.accumulated_stats); @@ -845,12 +809,15 @@ static void btif_a2dp_source_audio_tx_stop_event(void) { btif_a2dp_source_cb.tx_flush = false; /* Reset the media feeding state */ - if (btif_a2dp_source_cb.encoder_interface != nullptr) + if (btif_a2dp_source_cb.encoder_interface != nullptr) { btif_a2dp_source_cb.encoder_interface->feeding_reset(); + } } static void btif_a2dp_source_audio_handle_timer(void) { - if (btif_av_is_a2dp_offload_running()) return; + if (btif_av_is_a2dp_offload_running()) { + return; + } uint64_t timestamp_us = bluetooth::common::time_get_audio_server_tick_us(); uint64_t stats_timestamp_us = bluetooth::common::time_get_os_boottime_us(); @@ -861,23 +828,18 @@ static void btif_a2dp_source_audio_handle_timer(void) { log::error("ERROR Media task Scheduled after Suspend"); return; } - log::assert_that( - btif_a2dp_source_cb.encoder_interface != nullptr, - "assert failed: btif_a2dp_source_cb.encoder_interface != nullptr"); - size_t transmit_queue_length = - fixed_queue_length(btif_a2dp_source_cb.tx_audio_queue); + log::assert_that(btif_a2dp_source_cb.encoder_interface != nullptr, + "assert failed: btif_a2dp_source_cb.encoder_interface != nullptr"); + size_t transmit_queue_length = fixed_queue_length(btif_a2dp_source_cb.tx_audio_queue); #ifdef __ANDROID__ ATRACE_INT("btif TX queue", transmit_queue_length); #endif - if (btif_a2dp_source_cb.encoder_interface->set_transmit_queue_length != - nullptr) { - btif_a2dp_source_cb.encoder_interface->set_transmit_queue_length( - transmit_queue_length); + if (btif_a2dp_source_cb.encoder_interface->set_transmit_queue_length != nullptr) { + btif_a2dp_source_cb.encoder_interface->set_transmit_queue_length(transmit_queue_length); } btif_a2dp_source_cb.encoder_interface->send_frames(timestamp_us); bta_av_ci_src_data_ready(BTA_AV_CHNL_AUDIO); - update_scheduling_stats(&btif_a2dp_source_cb.stats.tx_queue_enqueue_stats, - stats_timestamp_us, + update_scheduling_stats(&btif_a2dp_source_cb.stats.tx_queue_enqueue_stats, stats_timestamp_us, btif_a2dp_source_cb.encoder_interval_ms * 1000); } @@ -886,14 +848,12 @@ static uint32_t btif_a2dp_source_read_callback(uint8_t* p_buf, uint32_t len) { if (btif_a2dp_source_cb.sw_audio_is_encoding && bytes_read < len) { log::warn("UNDERFLOW: ONLY READ {} BYTES OUT OF {}", bytes_read, len); - btif_a2dp_source_cb.stats.media_read_total_underflow_bytes += - (len - bytes_read); + btif_a2dp_source_cb.stats.media_read_total_underflow_bytes += (len - bytes_read); btif_a2dp_source_cb.stats.media_read_total_underflow_count++; btif_a2dp_source_cb.stats.media_read_last_underflow_us = - bluetooth::common::time_get_os_boottime_us(); + bluetooth::common::time_get_os_boottime_us(); log_a2dp_audio_underrun_event(btif_av_source_active_peer(), - btif_a2dp_source_cb.encoder_interval_ms, - len - bytes_read); + btif_a2dp_source_cb.encoder_interval_ms, len - bytes_read); } return bytes_read; @@ -914,7 +874,7 @@ static bool btif_a2dp_source_enqueue_callback(BT_HDR* p_buf, size_t frames_n, log::verbose("tx suspended, discarded frame"); btif_a2dp_source_cb.stats.tx_queue_total_flushed_messages += - fixed_queue_length(btif_a2dp_source_cb.tx_audio_queue); + fixed_queue_length(btif_a2dp_source_cb.tx_audio_queue); btif_a2dp_source_cb.stats.tx_queue_last_flushed_us = now_us; fixed_queue_flush(btif_a2dp_source_cb.tx_audio_queue, osi_free); @@ -927,22 +887,21 @@ static bool btif_a2dp_source_enqueue_callback(BT_HDR* p_buf, size_t frames_n, if (fixed_queue_length(btif_a2dp_source_cb.tx_audio_queue) + frames_n > btif_a2dp_source_dynamic_audio_buffer_size) { log::warn("TX queue buffer size now={} adding={} max={}", - (uint32_t)fixed_queue_length(btif_a2dp_source_cb.tx_audio_queue), - (uint32_t)frames_n, btif_a2dp_source_dynamic_audio_buffer_size); + (uint32_t)fixed_queue_length(btif_a2dp_source_cb.tx_audio_queue), (uint32_t)frames_n, + btif_a2dp_source_dynamic_audio_buffer_size); // Keep track of drop-outs btif_a2dp_source_cb.stats.tx_queue_dropouts++; btif_a2dp_source_cb.stats.tx_queue_last_dropouts_us = now_us; // Flush all queued buffers size_t drop_n = fixed_queue_length(btif_a2dp_source_cb.tx_audio_queue); - btif_a2dp_source_cb.stats.tx_queue_max_dropped_messages = std::max( - drop_n, btif_a2dp_source_cb.stats.tx_queue_max_dropped_messages); + btif_a2dp_source_cb.stats.tx_queue_max_dropped_messages = + std::max(drop_n, btif_a2dp_source_cb.stats.tx_queue_max_dropped_messages); int num_dropped_encoded_bytes = 0; int num_dropped_encoded_frames = 0; while (fixed_queue_length(btif_a2dp_source_cb.tx_audio_queue)) { btif_a2dp_source_cb.stats.tx_queue_total_dropped_messages++; - void* p_data = - fixed_queue_try_dequeue(btif_a2dp_source_cb.tx_audio_queue); + void* p_data = fixed_queue_try_dequeue(btif_a2dp_source_cb.tx_audio_queue); if (p_data != nullptr) { auto p_dropped_buf = static_cast(p_data); num_dropped_encoded_bytes += p_dropped_buf->len; @@ -950,9 +909,9 @@ static bool btif_a2dp_source_enqueue_callback(BT_HDR* p_buf, size_t frames_n, osi_free(p_data); } } - log_a2dp_audio_overrun_event( - btif_av_source_active_peer(), btif_a2dp_source_cb.encoder_interval_ms, - drop_n, num_dropped_encoded_frames, num_dropped_encoded_bytes); + log_a2dp_audio_overrun_event(btif_av_source_active_peer(), + btif_a2dp_source_cb.encoder_interval_ms, drop_n, + num_dropped_encoded_frames, num_dropped_encoded_bytes); // Request additional debug info if we had to flush buffers RawAddress peer_bda = btif_av_source_active_peer(); @@ -968,15 +927,13 @@ static bool btif_a2dp_source_enqueue_callback(BT_HDR* p_buf, size_t frames_n, // And if the need for disabling metrics-related HCI call grows, consider // creating a framework to avoid ifdefs. #ifndef TARGET_FLOSS - status = BTM_ReadFailedContactCounter(peer_bda, - btm_read_failed_contact_counter_cb); + status = BTM_ReadFailedContactCounter(peer_bda, btm_read_failed_contact_counter_cb); if (status != BTM_CMD_STARTED) { log::warn("Cannot read Failed Contact Counter: status {}", status); } #endif - status = - BTM_ReadTxPower(peer_bda, BT_TRANSPORT_BR_EDR, btm_read_tx_power_cb); + status = BTM_ReadTxPower(peer_bda, BT_TRANSPORT_BR_EDR, btm_read_tx_power_cb); if (status != BTM_CMD_STARTED) { log::warn("Cannot read Tx Power: status {}", status); } @@ -984,11 +941,10 @@ static bool btif_a2dp_source_enqueue_callback(BT_HDR* p_buf, size_t frames_n, /* Update the statistics */ btif_a2dp_source_cb.stats.tx_queue_total_frames += frames_n; - btif_a2dp_source_cb.stats.tx_queue_max_frames_per_packet = std::max( - frames_n, btif_a2dp_source_cb.stats.tx_queue_max_frames_per_packet); - log::assert_that( - btif_a2dp_source_cb.encoder_interface != nullptr, - "assert failed: btif_a2dp_source_cb.encoder_interface != nullptr"); + btif_a2dp_source_cb.stats.tx_queue_max_frames_per_packet = + std::max(frames_n, btif_a2dp_source_cb.stats.tx_queue_max_frames_per_packet); + log::assert_that(btif_a2dp_source_cb.encoder_interface != nullptr, + "assert failed: btif_a2dp_source_cb.encoder_interface != nullptr"); fixed_queue_enqueue(btif_a2dp_source_cb.tx_audio_queue, p_buf); @@ -998,37 +954,37 @@ static bool btif_a2dp_source_enqueue_callback(BT_HDR* p_buf, size_t frames_n, static void btif_a2dp_source_audio_tx_flush_event(void) { /* Flush all enqueued audio buffers (encoded) */ log::info("state={}", btif_a2dp_source_cb.StateStr()); - if (btif_av_is_a2dp_offload_running()) return; + if (btif_av_is_a2dp_offload_running()) { + return; + } - if (btif_a2dp_source_cb.encoder_interface != nullptr) + if (btif_a2dp_source_cb.encoder_interface != nullptr) { btif_a2dp_source_cb.encoder_interface->feeding_flush(); + } btif_a2dp_source_cb.stats.tx_queue_total_flushed_messages += - fixed_queue_length(btif_a2dp_source_cb.tx_audio_queue); - btif_a2dp_source_cb.stats.tx_queue_last_flushed_us = - bluetooth::common::time_get_os_boottime_us(); + fixed_queue_length(btif_a2dp_source_cb.tx_audio_queue); + btif_a2dp_source_cb.stats.tx_queue_last_flushed_us = bluetooth::common::time_get_os_boottime_us(); fixed_queue_flush(btif_a2dp_source_cb.tx_audio_queue, osi_free); } static bool btif_a2dp_source_audio_tx_flush_req(void) { log::info("state={}", btif_a2dp_source_cb.StateStr()); - btif_a2dp_source_thread.DoInThread( - FROM_HERE, base::BindOnce(&btif_a2dp_source_audio_tx_flush_event)); + btif_a2dp_source_thread.DoInThread(FROM_HERE, + base::BindOnce(&btif_a2dp_source_audio_tx_flush_event)); return true; } BT_HDR* btif_a2dp_source_audio_readbuf(void) { uint64_t now_us = bluetooth::common::time_get_os_boottime_us(); - BT_HDR* p_buf = - (BT_HDR*)fixed_queue_try_dequeue(btif_a2dp_source_cb.tx_audio_queue); + BT_HDR* p_buf = (BT_HDR*)fixed_queue_try_dequeue(btif_a2dp_source_cb.tx_audio_queue); btif_a2dp_source_cb.stats.tx_queue_total_readbuf_calls++; btif_a2dp_source_cb.stats.tx_queue_last_readbuf_us = now_us; if (p_buf != nullptr) { // Update the statistics - update_scheduling_stats(&btif_a2dp_source_cb.stats.tx_queue_dequeue_stats, - now_us, + update_scheduling_stats(&btif_a2dp_source_cb.stats.tx_queue_dequeue_stats, now_us, btif_a2dp_source_cb.encoder_interval_ms * 1000); } @@ -1037,9 +993,8 @@ BT_HDR* btif_a2dp_source_audio_readbuf(void) { static void log_tstamps_us(const char* comment, uint64_t timestamp_us) { static uint64_t prev_us = 0; - log::verbose("[{}] ts {:08}, diff : {:08}, queue sz {}", comment, - timestamp_us, timestamp_us - prev_us, - fixed_queue_length(btif_a2dp_source_cb.tx_audio_queue)); + log::verbose("[{}] ts {:08}, diff : {:08}, queue sz {}", comment, timestamp_us, + timestamp_us - prev_us, fixed_queue_length(btif_a2dp_source_cb.tx_audio_queue)); prev_us = timestamp_us; } @@ -1050,7 +1005,9 @@ static void update_scheduling_stats(SchedulingStats* stats, uint64_t now_us, stats->total_updates++; stats->last_update_us = now_us; - if (last_us == 0) return; // First update: expected delta doesn't apply + if (last_us == 0) { + return; // First update: expected delta doesn't apply + } uint64_t deadline_us = last_us + expected_delta; if (deadline_us < now_us) { @@ -1059,7 +1016,7 @@ static void update_scheduling_stats(SchedulingStats* stats, uint64_t now_us, // Ignore extreme outliers if (delta_us < 10 * expected_delta) { stats->max_overdue_scheduling_delta_us = - std::max(delta_us, stats->max_overdue_scheduling_delta_us); + std::max(delta_us, stats->max_overdue_scheduling_delta_us); stats->total_overdue_scheduling_delta_us += delta_us; stats->overdue_scheduling_count++; stats->total_scheduling_time_us += now_us - last_us; @@ -1070,7 +1027,7 @@ static void update_scheduling_stats(SchedulingStats* stats, uint64_t now_us, // Ignore extreme outliers if (delta_us < 10 * expected_delta) { stats->max_premature_scheduling_delta_us = - std::max(delta_us, stats->max_premature_scheduling_delta_us); + std::max(delta_us, stats->max_premature_scheduling_delta_us); stats->total_premature_scheduling_delta_us += delta_us; stats->premature_scheduling_count++; stats->total_scheduling_time_us += now_us - last_us; @@ -1101,26 +1058,24 @@ void btif_a2dp_source_debug_dump(int fd) { enqueue_stats->total_updates, dequeue_stats->total_updates, accumulated_stats->tx_queue_total_readbuf_calls); - dprintf( - fd, - " Last update time ago in ms (enqueue/dequeue/readbuf) : %llu / %llu " - "/ %llu\n", - (enqueue_stats->last_update_us > 0) - ? (unsigned long long)(now_us - enqueue_stats->last_update_us) / 1000 - : 0, - (dequeue_stats->last_update_us > 0) - ? (unsigned long long)(now_us - dequeue_stats->last_update_us) / 1000 - : 0, - (accumulated_stats->tx_queue_last_readbuf_us > 0) - ? (unsigned long long)(now_us - - accumulated_stats->tx_queue_last_readbuf_us) / - 1000 - : 0); + dprintf(fd, + " Last update time ago in ms (enqueue/dequeue/readbuf) : %llu / %llu " + "/ %llu\n", + (enqueue_stats->last_update_us > 0) + ? (unsigned long long)(now_us - enqueue_stats->last_update_us) / 1000 + : 0, + (dequeue_stats->last_update_us > 0) + ? (unsigned long long)(now_us - dequeue_stats->last_update_us) / 1000 + : 0, + (accumulated_stats->tx_queue_last_readbuf_us > 0) + ? (unsigned long long)(now_us - accumulated_stats->tx_queue_last_readbuf_us) / + 1000 + : 0); ave_size = 0; - if (enqueue_stats->total_updates != 0) - ave_size = - accumulated_stats->tx_queue_total_frames / enqueue_stats->total_updates; + if (enqueue_stats->total_updates != 0) { + ave_size = accumulated_stats->tx_queue_total_frames / enqueue_stats->total_updates; + } dprintf(fd, " Frames per packet (total/max/ave) : %zu / " "%zu / %zu\n", @@ -1131,120 +1086,94 @@ void btif_a2dp_source_debug_dump(int fd) { " Counts (flushed/dropped/dropouts) : %zu / " "%zu / %zu\n", accumulated_stats->tx_queue_total_flushed_messages, - accumulated_stats->tx_queue_total_dropped_messages, - accumulated_stats->tx_queue_dropouts); + accumulated_stats->tx_queue_total_dropped_messages, accumulated_stats->tx_queue_dropouts); - dprintf(fd, - " Counts (max dropped) : %zu\n", + dprintf(fd, " Counts (max dropped) : %zu\n", accumulated_stats->tx_queue_max_dropped_messages); - dprintf( - fd, - " Last update time ago in ms (flushed/dropped) : %llu / " - "%llu\n", - (accumulated_stats->tx_queue_last_flushed_us > 0) - ? (unsigned long long)(now_us - - accumulated_stats->tx_queue_last_flushed_us) / - 1000 - : 0, - (accumulated_stats->tx_queue_last_dropouts_us > 0) - ? (unsigned long long)(now_us - - accumulated_stats->tx_queue_last_dropouts_us) / - 1000 - : 0); - dprintf(fd, - " Counts (underflow) : %zu\n", + " Last update time ago in ms (flushed/dropped) : %llu / " + "%llu\n", + (accumulated_stats->tx_queue_last_flushed_us > 0) + ? (unsigned long long)(now_us - accumulated_stats->tx_queue_last_flushed_us) / + 1000 + : 0, + (accumulated_stats->tx_queue_last_dropouts_us > 0) + ? (unsigned long long)(now_us - accumulated_stats->tx_queue_last_dropouts_us) / + 1000 + : 0); + + dprintf(fd, " Counts (underflow) : %zu\n", accumulated_stats->media_read_total_underflow_count); - dprintf(fd, - " Bytes (underflow) : %zu\n", + dprintf(fd, " Bytes (underflow) : %zu\n", accumulated_stats->media_read_total_underflow_bytes); - dprintf(fd, - " Last update time ago in ms (underflow) : %llu\n", + dprintf(fd, " Last update time ago in ms (underflow) : %llu\n", (accumulated_stats->media_read_last_underflow_us > 0) - ? (unsigned long long)(now_us - - accumulated_stats - ->media_read_last_underflow_us) / - 1000 - : 0); + ? (unsigned long long)(now_us - accumulated_stats->media_read_last_underflow_us) / + 1000 + : 0); // // TxQueue enqueue stats // - dprintf( - fd, - " Enqueue deviation counts (overdue/premature) : %zu / %zu\n", - enqueue_stats->overdue_scheduling_count, - enqueue_stats->premature_scheduling_count); + dprintf(fd, " Enqueue deviation counts (overdue/premature) : %zu / %zu\n", + enqueue_stats->overdue_scheduling_count, enqueue_stats->premature_scheduling_count); ave_time_us = 0; if (enqueue_stats->overdue_scheduling_count != 0) { ave_time_us = enqueue_stats->total_overdue_scheduling_delta_us / enqueue_stats->overdue_scheduling_count; } - dprintf( - fd, - " Enqueue overdue scheduling time in ms (total/max/ave) : %llu / %llu " - "/ %llu\n", - (unsigned long long)enqueue_stats->total_overdue_scheduling_delta_us / - 1000, - (unsigned long long)enqueue_stats->max_overdue_scheduling_delta_us / 1000, - (unsigned long long)ave_time_us / 1000); + dprintf(fd, + " Enqueue overdue scheduling time in ms (total/max/ave) : %llu / %llu " + "/ %llu\n", + (unsigned long long)enqueue_stats->total_overdue_scheduling_delta_us / 1000, + (unsigned long long)enqueue_stats->max_overdue_scheduling_delta_us / 1000, + (unsigned long long)ave_time_us / 1000); ave_time_us = 0; if (enqueue_stats->premature_scheduling_count != 0) { ave_time_us = enqueue_stats->total_premature_scheduling_delta_us / enqueue_stats->premature_scheduling_count; } - dprintf( - fd, - " Enqueue premature scheduling time in ms (total/max/ave) : %llu / %llu " - "/ %llu\n", - (unsigned long long)enqueue_stats->total_premature_scheduling_delta_us / - 1000, - (unsigned long long)enqueue_stats->max_premature_scheduling_delta_us / - 1000, - (unsigned long long)ave_time_us / 1000); + dprintf(fd, + " Enqueue premature scheduling time in ms (total/max/ave) : %llu / %llu " + "/ %llu\n", + (unsigned long long)enqueue_stats->total_premature_scheduling_delta_us / 1000, + (unsigned long long)enqueue_stats->max_premature_scheduling_delta_us / 1000, + (unsigned long long)ave_time_us / 1000); // // TxQueue dequeue stats // - dprintf( - fd, - " Dequeue deviation counts (overdue/premature) : %zu / %zu\n", - dequeue_stats->overdue_scheduling_count, - dequeue_stats->premature_scheduling_count); + dprintf(fd, " Dequeue deviation counts (overdue/premature) : %zu / %zu\n", + dequeue_stats->overdue_scheduling_count, dequeue_stats->premature_scheduling_count); ave_time_us = 0; if (dequeue_stats->overdue_scheduling_count != 0) { ave_time_us = dequeue_stats->total_overdue_scheduling_delta_us / dequeue_stats->overdue_scheduling_count; } - dprintf( - fd, - " Dequeue overdue scheduling time in ms (total/max/ave) : %llu / %llu " - "/ %llu\n", - (unsigned long long)dequeue_stats->total_overdue_scheduling_delta_us / - 1000, - (unsigned long long)dequeue_stats->max_overdue_scheduling_delta_us / 1000, - (unsigned long long)ave_time_us / 1000); + dprintf(fd, + " Dequeue overdue scheduling time in ms (total/max/ave) : %llu / %llu " + "/ %llu\n", + (unsigned long long)dequeue_stats->total_overdue_scheduling_delta_us / 1000, + (unsigned long long)dequeue_stats->max_overdue_scheduling_delta_us / 1000, + (unsigned long long)ave_time_us / 1000); ave_time_us = 0; if (dequeue_stats->premature_scheduling_count != 0) { ave_time_us = dequeue_stats->total_premature_scheduling_delta_us / dequeue_stats->premature_scheduling_count; } - dprintf( - fd, - " Dequeue premature scheduling time in ms (total/max/ave) : %llu / %llu " - "/ %llu\n", - (unsigned long long)dequeue_stats->total_premature_scheduling_delta_us / - 1000, - (unsigned long long)dequeue_stats->max_premature_scheduling_delta_us / - 1000, - (unsigned long long)ave_time_us / 1000); + dprintf(fd, + " Dequeue premature scheduling time in ms (total/max/ave) : %llu / %llu " + "/ %llu\n", + (unsigned long long)dequeue_stats->total_premature_scheduling_delta_us / 1000, + (unsigned long long)dequeue_stats->max_premature_scheduling_delta_us / 1000, + (unsigned long long)ave_time_us / 1000); } static void btif_a2dp_source_update_metrics(void) { @@ -1257,28 +1186,25 @@ static void btif_a2dp_source_update_metrics(void) { // mark the metric duration as invalid (-1) in this case if (stats.session_start_us != 0) { int64_t session_end_us = stats.session_end_us == 0 - ? bluetooth::common::time_get_os_boottime_us() - : stats.session_end_us; + ? bluetooth::common::time_get_os_boottime_us() + : stats.session_end_us; if (static_cast(session_end_us) > stats.session_start_us) { - metrics.audio_duration_ms = - (session_end_us - stats.session_start_us) / 1000; + metrics.audio_duration_ms = (session_end_us - stats.session_start_us) / 1000; } } if (enqueue_stats.total_updates > 1) { - metrics.media_timer_min_ms = - btif_a2dp_source_cb.encoder_interval_ms - - (enqueue_stats.max_premature_scheduling_delta_us / 1000); - metrics.media_timer_max_ms = - btif_a2dp_source_cb.encoder_interval_ms + - (enqueue_stats.max_overdue_scheduling_delta_us / 1000); + metrics.media_timer_min_ms = btif_a2dp_source_cb.encoder_interval_ms - + (enqueue_stats.max_premature_scheduling_delta_us / 1000); + metrics.media_timer_max_ms = btif_a2dp_source_cb.encoder_interval_ms + + (enqueue_stats.max_overdue_scheduling_delta_us / 1000); metrics.total_scheduling_count = enqueue_stats.overdue_scheduling_count + enqueue_stats.premature_scheduling_count + enqueue_stats.exact_scheduling_count; if (metrics.total_scheduling_count > 0) { - metrics.media_timer_avg_ms = enqueue_stats.total_scheduling_time_us / - (1000 * metrics.total_scheduling_count); + metrics.media_timer_avg_ms = + enqueue_stats.total_scheduling_time_us / (1000 * metrics.total_scheduling_count); } metrics.buffer_overruns_max_count = stats.tx_queue_max_dropped_messages; @@ -1287,25 +1213,22 @@ static void btif_a2dp_source_update_metrics(void) { metrics.buffer_underruns_average = 0; if (metrics.buffer_underruns_count > 0) { metrics.buffer_underruns_average = - (float)stats.media_read_total_underflow_bytes / - metrics.buffer_underruns_count; + (float)stats.media_read_total_underflow_bytes / metrics.buffer_underruns_count; } } BluetoothMetricsLogger::GetInstance()->LogA2dpSession(metrics); if (metrics.audio_duration_ms != -1) { - log_a2dp_session_metrics_event( - btif_av_source_active_peer(), metrics.audio_duration_ms, - metrics.media_timer_min_ms, metrics.media_timer_max_ms, - metrics.media_timer_avg_ms, metrics.total_scheduling_count, - metrics.buffer_overruns_max_count, metrics.buffer_overruns_total, - metrics.buffer_underruns_average, metrics.buffer_underruns_count, - metrics.codec_index, metrics.is_a2dp_offload); + log_a2dp_session_metrics_event(btif_av_source_active_peer(), metrics.audio_duration_ms, + metrics.media_timer_min_ms, metrics.media_timer_max_ms, + metrics.media_timer_avg_ms, metrics.total_scheduling_count, + metrics.buffer_overruns_max_count, metrics.buffer_overruns_total, + metrics.buffer_underruns_average, metrics.buffer_underruns_count, + metrics.codec_index, metrics.is_a2dp_offload); } } -void btif_a2dp_source_set_dynamic_audio_buffer_size( - uint8_t dynamic_audio_buffer_size) { +void btif_a2dp_source_set_dynamic_audio_buffer_size(uint8_t dynamic_audio_buffer_size) { btif_a2dp_source_dynamic_audio_buffer_size = dynamic_audio_buffer_size; } @@ -1321,8 +1244,7 @@ static void btm_read_rssi_cb(void* data) { return; } - log_read_rssi_result(result->rem_bda, - bluetooth::common::kUnknownConnectionHandle, + log_read_rssi_result(result->rem_bda, bluetooth::common::kUnknownConnectionHandle, result->hci_status, result->rssi); log::warn("device: {}, rssi: {}", result->rem_bda, result->rssi); @@ -1334,16 +1256,14 @@ static void btm_read_failed_contact_counter_cb(void* data) { return; } - tBTM_FAILED_CONTACT_COUNTER_RESULT* result = - (tBTM_FAILED_CONTACT_COUNTER_RESULT*)data; + tBTM_FAILED_CONTACT_COUNTER_RESULT* result = (tBTM_FAILED_CONTACT_COUNTER_RESULT*)data; if (result->status != BTM_SUCCESS) { - log::error("unable to read Failed Contact Counter (status {})", - result->status); + log::error("unable to read Failed Contact Counter (status {})", result->status); return; } - log_read_failed_contact_counter_result( - result->rem_bda, bluetooth::common::kUnknownConnectionHandle, - result->hci_status, result->failed_contact_counter); + log_read_failed_contact_counter_result(result->rem_bda, + bluetooth::common::kUnknownConnectionHandle, + result->hci_status, result->failed_contact_counter); log::warn("device: {}, Failed Contact Counter: {}", result->rem_bda, result->failed_contact_counter); @@ -1360,8 +1280,7 @@ static void btm_read_tx_power_cb(void* data) { log::error("unable to read Tx Power (status {})", result->status); return; } - log_read_tx_power_level_result(result->rem_bda, - bluetooth::common::kUnknownConnectionHandle, + log_read_tx_power_level_result(result->rem_bda, bluetooth::common::kUnknownConnectionHandle, result->hci_status, result->tx_power); log::warn("device: {}, Tx Power: {}", result->rem_bda, result->tx_power); diff --git a/system/btif/src/btif_av.cc b/system/btif/src/btif_av.cc index 33437a4d939..063c3ce5e6d 100644 --- a/system/btif/src/btif_av.cc +++ b/system/btif/src/btif_av.cc @@ -122,7 +122,7 @@ typedef enum { } btif_av_sm_event_t; class BtifAvEvent { - public: +public: BtifAvEvent(uint32_t event, const void* p_data, size_t data_length); BtifAvEvent(const BtifAvEvent& other); BtifAvEvent() = delete; @@ -135,7 +135,7 @@ class BtifAvEvent { std::string ToString() const; static std::string EventName(uint32_t event); - private: +private: void DeepCopy(uint32_t event, const void* p_data, size_t data_length); void DeepFree(); @@ -154,7 +154,7 @@ static void btif_av_source_delete_active_peer(void); // media task from trying to restart stream during remote Suspend or while // we are in the process of a local Suspend. class BtifAvStateMachine : public bluetooth::common::StateMachine { - public: +public: enum { kStateIdle, // AVDTP disconnected kStateOpening, // Opening AVDTP connection @@ -164,62 +164,57 @@ class BtifAvStateMachine : public bluetooth::common::StateMachine { }; class StateIdle : public State { - public: - explicit StateIdle(BtifAvStateMachine& sm) - : State(sm, kStateIdle), peer_(sm.Peer()) {} + public: + explicit StateIdle(BtifAvStateMachine& sm) : State(sm, kStateIdle), peer_(sm.Peer()) {} void OnEnter() override; void OnExit() override; bool ProcessEvent(uint32_t event, void* p_data) override; - private: + private: BtifAvPeer& peer_; }; class StateOpening : public State { - public: - explicit StateOpening(BtifAvStateMachine& sm) - : State(sm, kStateOpening), peer_(sm.Peer()) {} + public: + explicit StateOpening(BtifAvStateMachine& sm) : State(sm, kStateOpening), peer_(sm.Peer()) {} void OnEnter() override; void OnExit() override; bool ProcessEvent(uint32_t event, void* p_data) override; - private: + private: BtifAvPeer& peer_; }; class StateOpened : public State { - public: - explicit StateOpened(BtifAvStateMachine& sm) - : State(sm, kStateOpened), peer_(sm.Peer()) {} + public: + explicit StateOpened(BtifAvStateMachine& sm) : State(sm, kStateOpened), peer_(sm.Peer()) {} void OnEnter() override; void OnExit() override; bool ProcessEvent(uint32_t event, void* p_data) override; - private: + private: BtifAvPeer& peer_; }; class StateStarted : public State { - public: - explicit StateStarted(BtifAvStateMachine& sm) - : State(sm, kStateStarted), peer_(sm.Peer()) {} + public: + explicit StateStarted(BtifAvStateMachine& sm) : State(sm, kStateStarted), peer_(sm.Peer()) {} void OnEnter() override; void OnExit() override; bool ProcessEvent(uint32_t event, void* p_data) override; - private: + private: BtifAvPeer& peer_; }; class StateClosing : public State { - public: - explicit StateClosing(BtifAvStateMachine& sm) - : State(sm, kStateClosing), peer_(sm.Peer()) {} + public: + explicit StateClosing(BtifAvStateMachine& sm) : State(sm, kStateClosing), peer_(sm.Peer()) {} void OnEnter() override; void OnExit() override; bool ProcessEvent(uint32_t event, void* p_data) override; - private: + private: BtifAvPeer& peer_; }; @@ -240,7 +235,7 @@ class BtifAvStateMachine : public bluetooth::common::StateMachine { BtifAvPeer& Peer() { return peer_; } - private: +private: BtifAvPeer& peer_; StateIdle* state_idle_; StateOpening* state_opening_; @@ -250,7 +245,7 @@ class BtifAvStateMachine : public bluetooth::common::StateMachine { }; class BtifAvPeer { - public: +public: enum { kFlagLocalSuspendPending = 0x1, kFlagRemoteSuspend = 0x2, @@ -259,8 +254,8 @@ class BtifAvPeer { }; static constexpr uint64_t kTimeoutAvOpenOnRcMs = 2 * 1000; // 2s - BtifAvPeer(const RawAddress& peer_address, uint8_t peer_sep, - tBTA_AV_HNDL bta_handle, uint8_t peer_id); + BtifAvPeer(const RawAddress& peer_address, uint8_t peer_sep, tBTA_AV_HNDL bta_handle, + uint8_t peer_id); ~BtifAvPeer(); bt_status_t Init(); @@ -278,7 +273,7 @@ class BtifAvPeer { * * @return true if this peer is the active one */ - bool IsActivePeer() const { return (PeerAddress() == ActivePeerAddress()); } + bool IsActivePeer() const { return PeerAddress() == ActivePeerAddress(); } /** * Get the address of the active peer. @@ -288,8 +283,8 @@ class BtifAvPeer { const RawAddress& ActivePeerAddress() const; const RawAddress& PeerAddress() const { return peer_address_; } - bool IsSource() const { return (peer_sep_ == AVDT_TSEP_SRC); } - bool IsSink() const { return (peer_sep_ == AVDT_TSEP_SNK); } + bool IsSource() const { return peer_sep_ == AVDT_TSEP_SRC; } + bool IsSink() const { return peer_sep_ == AVDT_TSEP_SNK; } uint8_t PeerSep() const { return peer_sep_; } void SetSep(uint8_t sep_type) { peer_sep_ = sep_type; } /** @@ -299,7 +294,7 @@ class BtifAvPeer { * or UUID_SERVCLASS_AUDIO_SINK */ uint16_t LocalUuidServiceClass() const { - return (IsSink() ? UUID_SERVCLASS_AUDIO_SOURCE : UUID_SERVCLASS_AUDIO_SINK); + return IsSink() ? UUID_SERVCLASS_AUDIO_SOURCE : UUID_SERVCLASS_AUDIO_SINK; } tBTA_AV_HNDL BtaHandle() const { return bta_handle_; } void SetBtaHandle(tBTA_AV_HNDL bta_handle) { bta_handle_ = bta_handle; } @@ -311,8 +306,8 @@ class BtifAvPeer { const alarm_t* AvOpenOnRcTimer() const { return av_open_on_rc_timer_; } void SetEdr(tBTA_AV_EDR edr) { edr_ = edr; } - bool IsEdr() const { return (edr_ != 0); } - bool Is3Mbps() const { return ((edr_ & BTA_AV_EDR_3MBPS) != 0); } + bool IsEdr() const { return edr_ != 0; } + bool Is3Mbps() const { return (edr_ & BTA_AV_EDR_3MBPS) != 0; } bool IsConnected() const; bool IsStreaming() const; @@ -324,9 +319,7 @@ class BtifAvPeer { void SetDelayReport(uint16_t delay) { delay_report_ = delay; } uint16_t GetDelayReport() const { return delay_report_; } - void SetMandatoryCodecPreferred(bool preferred) { - mandatory_codec_preferred_ = preferred; - } + void SetMandatoryCodecPreferred(bool preferred) { mandatory_codec_preferred_ = preferred; } bool IsMandatoryCodecPreferred() const { return mandatory_codec_preferred_; } /** @@ -335,9 +328,7 @@ class BtifAvPeer { * @param bitflags_mask the bitflags to check * @return true if any of the flags to check is set, otherwise false. */ - bool CheckFlags(uint8_t bitflags_mask) const { - return ((flags_ & bitflags_mask) != 0); - } + bool CheckFlags(uint8_t bitflags_mask) const { return (flags_ & bitflags_mask) != 0; } /** * Set only the flags as specified by the bitflags mask. @@ -367,11 +358,9 @@ class BtifAvPeer { void SetSelfInitiatedConnection(bool v) { self_initiated_connection_ = v; } bool UseLatencyMode() const { return use_latency_mode_; } - void SetUseLatencyMode(bool use_latency_mode) { - use_latency_mode_ = use_latency_mode; - } + void SetUseLatencyMode(bool use_latency_mode) { use_latency_mode_ = use_latency_mode; } - private: +private: const RawAddress peer_address_; uint8_t peer_sep_; // SEP type of peer device tBTA_AV_HNDL bta_handle_; @@ -388,7 +377,7 @@ class BtifAvPeer { }; class BtifAvSource { - public: +public: // The PeerId is used as AppId for BTA_AvRegister() purpose static constexpr uint8_t kPeerIdMin = 0; static constexpr uint8_t kPeerIdMax = BTA_AV_NUM_STRS; @@ -401,25 +390,21 @@ class BtifAvSource { max_connected_peers_(kDefaultMaxConnectedAudioDevices) {} ~BtifAvSource(); - bt_status_t Init( - btav_source_callbacks_t* callbacks, int max_connected_audio_devices, - const std::vector& codec_priorities, - const std::vector& offloading_preference, - std::vector* supported_codecs); + bt_status_t Init(btav_source_callbacks_t* callbacks, int max_connected_audio_devices, + const std::vector& codec_priorities, + const std::vector& offloading_preference, + std::vector* supported_codecs); void Cleanup(); btav_source_callbacks_t* Callbacks() { return callbacks_; } bool Enabled() const { return enabled_; } bool A2dpOffloadEnabled() const { return a2dp_offload_enabled_; } // TODO(b/321806163): Remove this method as part of flag cleanup - void SetInvalidPeerCheck(bool invalid_peer_check) { - invalid_peer_check_ = invalid_peer_check; - } + void SetInvalidPeerCheck(bool invalid_peer_check) { invalid_peer_check_ = invalid_peer_check; } BtifAvPeer* FindPeer(const RawAddress& peer_address); BtifAvPeer* FindPeerByHandle(tBTA_AV_HNDL bta_handle); BtifAvPeer* FindPeerByPeerId(uint8_t peer_id); - BtifAvPeer* FindOrCreatePeer(const RawAddress& peer_address, - tBTA_AV_HNDL bta_handle); + BtifAvPeer* FindOrCreatePeer(const RawAddress& peer_address, tBTA_AV_HNDL bta_handle); /** * Check whether a connection to a peer is allowed. @@ -497,8 +482,7 @@ class BtifAvSource { * reset the active peer * @return true on success, otherwise false */ - bool SetActivePeer(const RawAddress& peer_address, - std::promise peer_ready_promise) { + bool SetActivePeer(const RawAddress& peer_address, std::promise peer_ready_promise) { log::info("peer={} active_peer={}", peer_address, active_peer_); if (active_peer_ == peer_address) { @@ -513,8 +497,7 @@ class BtifAvSource { } } else { if (!btif_av_src_sink_coexist_enabled() || - (btif_av_src_sink_coexist_enabled() && - btif_av_sink_active_peer().IsEmpty())) { + (btif_av_src_sink_coexist_enabled() && btif_av_sink_active_peer().IsEmpty())) { if (!bta_av_co_set_active_peer(peer_address)) { log::warn("unable to set active peer to empty in BtaAvCo"); } @@ -523,12 +506,10 @@ class BtifAvSource { btif_a2dp_source_end_session(active_peer_); std::promise shutdown_complete_promise; - std::future shutdown_complete_future = - shutdown_complete_promise.get_future(); + std::future shutdown_complete_future = shutdown_complete_promise.get_future(); btif_a2dp_source_shutdown(std::move(shutdown_complete_promise)); using namespace std::chrono_literals; - if (shutdown_complete_future.wait_for(1s) == - std::future_status::timeout) { + if (shutdown_complete_future.wait_for(1s) == std::future_status::timeout) { log::error("Timed out waiting for A2DP source shutdown to complete."); } active_peer_ = peer_address; @@ -584,17 +565,16 @@ class BtifAvSource { * @param peer_address the address of the peer to update * @param codec_preferences the updated codec preferences */ - void UpdateCodecConfig( - const RawAddress& peer_address, - const std::vector& codec_preferences, - std::promise peer_ready_promise) { + void UpdateCodecConfig(const RawAddress& peer_address, + const std::vector& codec_preferences, + std::promise peer_ready_promise) { // Restart the session if the codec for the active peer is updated if (!peer_address.IsEmpty() && active_peer_ == peer_address) { btif_a2dp_source_end_session(active_peer_); } - btif_a2dp_source_encoder_user_config_update_req( - peer_address, codec_preferences, std::move(peer_ready_promise)); + btif_a2dp_source_encoder_user_config_update_req(peer_address, codec_preferences, + std::move(peer_ready_promise)); } /** @@ -619,7 +599,7 @@ class BtifAvSource { BtifAvPeer* popPeer(const RawAddress& peer_address); void AddPeer(BtifAvPeer* peer); - private: +private: void CleanupAllPeers(); btav_source_callbacks_t* callbacks_; @@ -636,7 +616,7 @@ class BtifAvSource { }; class BtifAvSink { - public: +public: // The PeerId is used as AppId for BTA_AvRegister() purpose static constexpr uint8_t kPeerIdMin = 0; static constexpr uint8_t kPeerIdMax = BTA_AV_NUM_STRS; @@ -648,22 +628,18 @@ class BtifAvSink { max_connected_peers_(kDefaultMaxConnectedAudioDevices) {} ~BtifAvSink(); - bt_status_t Init(btav_sink_callbacks_t* callbacks, - int max_connected_audio_devices); + bt_status_t Init(btav_sink_callbacks_t* callbacks, int max_connected_audio_devices); void Cleanup(); btav_sink_callbacks_t* Callbacks() { return callbacks_; } bool Enabled() const { return enabled_; } // TODO(b/321806163): Remove this method as part of flag cleanup - void SetInvalidPeerCheck(bool invalid_peer_check) { - invalid_peer_check_ = invalid_peer_check; - } + void SetInvalidPeerCheck(bool invalid_peer_check) { invalid_peer_check_ = invalid_peer_check; } BtifAvPeer* FindPeer(const RawAddress& peer_address); BtifAvPeer* FindPeerByHandle(tBTA_AV_HNDL bta_handle); BtifAvPeer* FindPeerByPeerId(uint8_t peer_id); - BtifAvPeer* FindOrCreatePeer(const RawAddress& peer_address, - tBTA_AV_HNDL bta_handle); + BtifAvPeer* FindOrCreatePeer(const RawAddress& peer_address, tBTA_AV_HNDL bta_handle); /** * Check whether a connection to a peer is allowed. @@ -694,8 +670,7 @@ class BtifAvSink { * reset the active peer * @return true on success, otherwise false */ - bool SetActivePeer(const RawAddress& peer_address, - std::promise peer_ready_promise) { + bool SetActivePeer(const RawAddress& peer_address, std::promise peer_ready_promise) { log::info("peer={} active_peer={}", peer_address, active_peer_); if (active_peer_ == peer_address) { @@ -710,8 +685,7 @@ class BtifAvSink { } } else { if (!btif_av_src_sink_coexist_enabled() || - (btif_av_src_sink_coexist_enabled() && - btif_av_source_active_peer().IsEmpty())) { + (btif_av_src_sink_coexist_enabled() && btif_av_source_active_peer().IsEmpty())) { if (!bta_av_co_set_active_peer(peer_address)) { log::warn("unable to set active peer to empty in BtaAvCo"); } @@ -782,7 +756,7 @@ class BtifAvSink { BtifAvPeer* popPeer(const RawAddress& peer_address); void AddPeer(BtifAvPeer* peer); - private: +private: void CleanupAllPeers(); btav_sink_callbacks_t* callbacks_; @@ -821,27 +795,20 @@ static void btif_av_source_dispatch_sm_event(const RawAddress& peer_address, btif_av_sm_event_t event); static void btif_av_sink_dispatch_sm_event(const RawAddress& peer_address, btif_av_sm_event_t event); -static void btif_av_handle_event(uint8_t peer_sep, - const RawAddress& peer_address, - tBTA_AV_HNDL bta_handle, - const BtifAvEvent& btif_av_event); +static void btif_av_handle_event(uint8_t peer_sep, const RawAddress& peer_address, + tBTA_AV_HNDL bta_handle, const BtifAvEvent& btif_av_event); static void btif_debug_av_peer_dump(int fd, const BtifAvPeer& peer); static void btif_report_connection_state(const RawAddress& peer_address, - btav_connection_state_t state, - const bt_status_t status, - uint8_t error_code, - const A2dpType local_a2dp_type); -static void btif_report_audio_state(const RawAddress& peer_address, - btav_audio_state_t state, + btav_connection_state_t state, const bt_status_t status, + uint8_t error_code, const A2dpType local_a2dp_type); +static void btif_report_audio_state(const RawAddress& peer_address, btav_audio_state_t state, const A2dpType local_a2dp_type); -static void btif_av_report_sink_audio_config_state( - const RawAddress& peer_address, int sample_rate, int channel_count); -static void btif_av_query_mandatory_codec_priority( - const RawAddress& peer_address); +static void btif_av_report_sink_audio_config_state(const RawAddress& peer_address, int sample_rate, + int channel_count); +static void btif_av_query_mandatory_codec_priority(const RawAddress& peer_address); static void btif_av_source_initiate_av_open_timer_timeout(void* data); static void btif_av_sink_initiate_av_open_timer_timeout(void* data); -static void bta_av_sink_media_callback(const RawAddress& peer_address, - tBTA_AV_EVT event, +static void bta_av_sink_media_callback(const RawAddress& peer_address, tBTA_AV_EVT event, tBTA_AV_MEDIA* p_data); static BtifAvPeer* btif_av_source_find_peer(const RawAddress& peer_address) { @@ -890,17 +857,23 @@ static BtifAvPeer* btif_av_find_peer(const RawAddress& peer_address, } return peer; } - if (btif_av_source.Enabled()) return btif_av_source_find_peer(peer_address); - if (btif_av_sink.Enabled()) return btif_av_sink_find_peer(peer_address); + if (btif_av_source.Enabled()) { + return btif_av_source_find_peer(peer_address); + } + if (btif_av_sink.Enabled()) { + return btif_av_sink_find_peer(peer_address); + } return nullptr; } static BtifAvPeer* btif_av_find_active_peer(const A2dpType local_a2dp_type) { if (com::android::bluetooth::flags::a2dp_concurrent_source_sink()) { - if (btif_av_source.Enabled() && local_a2dp_type == A2dpType::kSource) + if (btif_av_source.Enabled() && local_a2dp_type == A2dpType::kSource) { return btif_av_source_find_peer(btif_av_source.ActivePeer()); - if (btif_av_sink.Enabled() && local_a2dp_type == A2dpType::kSink) + } + if (btif_av_sink.Enabled() && local_a2dp_type == A2dpType::kSink) { return btif_av_sink_find_peer(btif_av_sink.ActivePeer()); + } return nullptr; } @@ -912,10 +885,12 @@ static BtifAvPeer* btif_av_find_active_peer(const A2dpType local_a2dp_type) { } return peer; } - if (btif_av_source.Enabled()) + if (btif_av_source.Enabled()) { return btif_av_source_find_peer(btif_av_source.ActivePeer()); - if (btif_av_sink.Enabled()) + } + if (btif_av_sink.Enabled()) { return btif_av_sink_find_peer(btif_av_sink.ActivePeer()); + } return nullptr; } @@ -926,15 +901,22 @@ const RawAddress& btif_av_find_by_handle(tBTA_AV_HNDL bta_handle) { if (peer == nullptr) { peer = btif_av_sink.FindPeerByHandle(bta_handle); } - if (peer == nullptr) return RawAddress::kEmpty; + if (peer == nullptr) { + return RawAddress::kEmpty; + } return peer->PeerAddress(); } - if (btif_av_source.Enabled()) + if (btif_av_source.Enabled()) { peer = btif_av_source.FindPeerByHandle(bta_handle); - if (btif_av_sink.Enabled()) peer = btif_av_sink.FindPeerByHandle(bta_handle); + } + if (btif_av_sink.Enabled()) { + peer = btif_av_sink.FindPeerByHandle(bta_handle); + } - if (peer == nullptr) return RawAddress::kEmpty; + if (peer == nullptr) { + return RawAddress::kEmpty; + } return peer->PeerAddress(); } @@ -995,8 +977,7 @@ BtifAvEvent::BtifAvEvent(uint32_t event, const void* p_data, size_t data_length) DeepCopy(event, p_data, data_length); } -BtifAvEvent::BtifAvEvent(const BtifAvEvent& other) - : event_(0), data_(nullptr), data_length_(0) { +BtifAvEvent::BtifAvEvent(const BtifAvEvent& other) : event_(0), data_(nullptr), data_length_(0) { *this = other; } @@ -1008,9 +989,7 @@ BtifAvEvent& BtifAvEvent::operator=(const BtifAvEvent& other) { BtifAvEvent::~BtifAvEvent() { DeepFree(); } -std::string BtifAvEvent::ToString() const { - return BtifAvEvent::EventName(event_); -} +std::string BtifAvEvent::ToString() const { return BtifAvEvent::EventName(event_); } std::string BtifAvEvent::EventName(uint32_t event) { std::string name = dump_av_sm_event_name((btif_av_sm_event_t)event); @@ -1019,8 +998,7 @@ std::string BtifAvEvent::EventName(uint32_t event) { return name + ss_value.str(); } -void BtifAvEvent::DeepCopy(uint32_t event, const void* p_data, - size_t data_length) { +void BtifAvEvent::DeepCopy(uint32_t event, const void* p_data, size_t data_length) { event_ = event; data_length_ = data_length; if (data_length == 0) { @@ -1037,34 +1015,30 @@ void BtifAvEvent::DeepCopy(uint32_t event, const void* p_data, const tBTA_AV* av_src = (const tBTA_AV*)p_data; tBTA_AV* av_dest = reinterpret_cast(data_); if (av_src->meta_msg.p_data && av_src->meta_msg.len) { - av_dest->meta_msg.p_data = - reinterpret_cast(osi_calloc(av_src->meta_msg.len)); - memcpy(av_dest->meta_msg.p_data, av_src->meta_msg.p_data, - av_src->meta_msg.len); + av_dest->meta_msg.p_data = reinterpret_cast(osi_calloc(av_src->meta_msg.len)); + memcpy(av_dest->meta_msg.p_data, av_src->meta_msg.p_data, av_src->meta_msg.len); } if (av_src->meta_msg.p_msg) { - av_dest->meta_msg.p_msg = - reinterpret_cast(osi_calloc(sizeof(tAVRC_MSG))); - memcpy(av_dest->meta_msg.p_msg, av_src->meta_msg.p_msg, - sizeof(tAVRC_MSG)); + av_dest->meta_msg.p_msg = reinterpret_cast(osi_calloc(sizeof(tAVRC_MSG))); + memcpy(av_dest->meta_msg.p_msg, av_src->meta_msg.p_msg, sizeof(tAVRC_MSG)); tAVRC_MSG* p_msg_src = av_src->meta_msg.p_msg; tAVRC_MSG* p_msg_dest = av_dest->meta_msg.p_msg; if ((p_msg_src->hdr.opcode == AVRC_OP_VENDOR) && (p_msg_src->vendor.p_vendor_data && p_msg_src->vendor.vendor_len)) { - p_msg_dest->vendor.p_vendor_data = reinterpret_cast( - osi_calloc(p_msg_src->vendor.vendor_len)); - memcpy(p_msg_dest->vendor.p_vendor_data, - p_msg_src->vendor.p_vendor_data, p_msg_src->vendor.vendor_len); + p_msg_dest->vendor.p_vendor_data = + reinterpret_cast(osi_calloc(p_msg_src->vendor.vendor_len)); + memcpy(p_msg_dest->vendor.p_vendor_data, p_msg_src->vendor.p_vendor_data, + p_msg_src->vendor.vendor_len); } - if ((p_msg_src->hdr.opcode == AVRC_OP_BROWSE) && - p_msg_src->browse.p_browse_data && p_msg_src->browse.browse_len) { - p_msg_dest->browse.p_browse_data = reinterpret_cast( - osi_calloc(p_msg_src->browse.browse_len)); - memcpy(p_msg_dest->browse.p_browse_data, - p_msg_src->browse.p_browse_data, p_msg_src->browse.browse_len); + if ((p_msg_src->hdr.opcode == AVRC_OP_BROWSE) && p_msg_src->browse.p_browse_data && + p_msg_src->browse.browse_len) { + p_msg_dest->browse.p_browse_data = + reinterpret_cast(osi_calloc(p_msg_src->browse.browse_len)); + memcpy(p_msg_dest->browse.p_browse_data, p_msg_src->browse.p_browse_data, + p_msg_src->browse.browse_len); } } } break; @@ -1102,8 +1076,8 @@ void BtifAvEvent::DeepFree() { data_length_ = 0; } -BtifAvPeer::BtifAvPeer(const RawAddress& peer_address, uint8_t peer_sep, - tBTA_AV_HNDL bta_handle, uint8_t peer_id) +BtifAvPeer::BtifAvPeer(const RawAddress& peer_address, uint8_t peer_sep, tBTA_AV_HNDL bta_handle, + uint8_t peer_id) : peer_address_(peer_address), peer_sep_(peer_sep), bta_handle_(bta_handle), @@ -1121,22 +1095,32 @@ std::string BtifAvPeer::FlagsToString() const { std::string result; if (flags_ & BtifAvPeer::kFlagLocalSuspendPending) { - if (!result.empty()) result += "|"; + if (!result.empty()) { + result += "|"; + } result += "LOCAL_SUSPEND_PENDING"; } if (flags_ & BtifAvPeer::kFlagRemoteSuspend) { - if (!result.empty()) result += "|"; + if (!result.empty()) { + result += "|"; + } result += "REMOTE_SUSPEND"; } if (flags_ & BtifAvPeer::kFlagPendingStart) { - if (!result.empty()) result += "|"; + if (!result.empty()) { + result += "|"; + } result += "PENDING_START"; } if (flags_ & BtifAvPeer::kFlagPendingStop) { - if (!result.empty()) result += "|"; + if (!result.empty()) { + result += "|"; + } result += "PENDING_STOP"; } - if (result.empty()) result = "None"; + if (result.empty()) { + result = "None"; + } return base::StringPrintf("0x%x(%s)", flags_, result.c_str()); } @@ -1157,9 +1141,8 @@ void BtifAvPeer::Cleanup() { } bool BtifAvPeer::CanBeDeleted() const { - return ( - (state_machine_.StateId() == BtifAvStateMachine::kStateIdle) && - (state_machine_.PreviousStateId() != BtifAvStateMachine::kStateInvalid)); + return (state_machine_.StateId() == BtifAvStateMachine::kStateIdle) && + (state_machine_.PreviousStateId() != BtifAvStateMachine::kStateInvalid); } const RawAddress& BtifAvPeer::ActivePeerAddress() const { @@ -1187,30 +1170,30 @@ const RawAddress& BtifAvPeer::ActivePeerAddress() const { bool BtifAvPeer::IsConnected() const { int state = state_machine_.StateId(); - return ((state == BtifAvStateMachine::kStateOpened) || - (state == BtifAvStateMachine::kStateStarted)); + return (state == BtifAvStateMachine::kStateOpened) || + (state == BtifAvStateMachine::kStateStarted); } bool BtifAvPeer::IsStreaming() const { int state = state_machine_.StateId(); - return (state == BtifAvStateMachine::kStateStarted); + return state == BtifAvStateMachine::kStateStarted; } BtifAvSource::~BtifAvSource() { CleanupAllPeers(); } -bt_status_t BtifAvSource::Init( - btav_source_callbacks_t* callbacks, int max_connected_audio_devices, - const std::vector& codec_priorities, - const std::vector& offloading_preference, - std::vector* supported_codecs) { +bt_status_t BtifAvSource::Init(btav_source_callbacks_t* callbacks, int max_connected_audio_devices, + const std::vector& codec_priorities, + const std::vector& offloading_preference, + std::vector* supported_codecs) { log::info("max_connected_audio_devices={}", max_connected_audio_devices); - if (enabled_) return BT_STATUS_SUCCESS; + if (enabled_) { + return BT_STATUS_SUCCESS; + } CleanupAllPeers(); max_connected_peers_ = max_connected_audio_devices; /* A2DP OFFLOAD */ - a2dp_offload_enabled_ = - GetInterfaceToProfiles()->config->isA2DPOffloadEnabled(); + a2dp_offload_enabled_ = GetInterfaceToProfiles()->config->isA2DPOffloadEnabled(); log::verbose("a2dp_offload.enable = {}", a2dp_offload_enabled_); callbacks_ = callbacks; @@ -1218,9 +1201,9 @@ bt_status_t BtifAvSource::Init( tBTM_BLE_VSC_CB vsc_cb = {}; BTM_BleGetVendorCapabilities(&vsc_cb); bool supports_a2dp_hw_offload_v2 = - vsc_cb.version_supported >= 0x0104 && vsc_cb.a2dp_offload_v2_support; - bluetooth::audio::a2dp::update_codec_offloading_capabilities( - offloading_preference, supports_a2dp_hw_offload_v2); + vsc_cb.version_supported >= 0x0104 && vsc_cb.a2dp_offload_v2_support; + bluetooth::audio::a2dp::update_codec_offloading_capabilities(offloading_preference, + supports_a2dp_hw_offload_v2); } bta_av_co_init(codec_priorities, supported_codecs); @@ -1234,17 +1217,17 @@ bt_status_t BtifAvSource::Init( void BtifAvSource::Cleanup() { log::info(""); - if (!enabled_) return; + if (!enabled_) { + return; + } enabled_ = false; btif_queue_cleanup(UUID_SERVCLASS_AUDIO_SOURCE); std::promise peer_ready_promise; - do_in_main_thread( - FROM_HERE, - base::BindOnce(base::IgnoreResult(&BtifAvSource::SetActivePeer), - base::Unretained(&btif_av_source), RawAddress::kEmpty, - std::move(peer_ready_promise))); + do_in_main_thread(FROM_HERE, base::BindOnce(base::IgnoreResult(&BtifAvSource::SetActivePeer), + base::Unretained(&btif_av_source), RawAddress::kEmpty, + std::move(peer_ready_promise))); do_in_main_thread(FROM_HERE, base::BindOnce(&btif_a2dp_source_cleanup)); btif_disable_service(BTA_A2DP_SOURCE_SERVICE_ID); @@ -1255,7 +1238,9 @@ void BtifAvSource::Cleanup() { BtifAvPeer* BtifAvSource::FindPeer(const RawAddress& peer_address) { auto it = peers_.find(peer_address); - if (it != peers_.end()) return it->second; + if (it != peers_.end()) { + return it->second; + } return nullptr; } @@ -1287,7 +1272,9 @@ BtifAvPeer* BtifAvSource::FindOrCreatePeer(const RawAddress& peer_address, log::verbose("peer={} bta_handle=0x{:x}", peer_address, bta_handle); BtifAvPeer* peer = FindPeer(peer_address); - if (peer != nullptr) return peer; + if (peer != nullptr) { + return peer; + } // Find next availabie Peer ID to use uint8_t peer_id; @@ -1295,17 +1282,20 @@ BtifAvPeer* BtifAvSource::FindOrCreatePeer(const RawAddress& peer_address, /* because the peer id may be in source cb and we cannot use it */ if (btif_av_src_sink_coexist_enabled() && btif_av_both_enable()) { if (FindPeerByPeerId(peer_id) == nullptr && - btif_av_sink.FindPeerByPeerId(peer_id) == nullptr) + btif_av_sink.FindPeerByPeerId(peer_id) == nullptr) { break; + } } else { - if (FindPeerByPeerId(peer_id) == nullptr) break; + if (FindPeerByPeerId(peer_id) == nullptr) { + break; + } } } if (peer_id == kPeerIdMax) { log::error( - "Cannot create peer for peer={} : cannot allocate unique Peer " - "ID", - peer_address); + "Cannot create peer for peer={} : cannot allocate unique Peer " + "ID", + peer_address); return nullptr; } @@ -1314,16 +1304,15 @@ BtifAvPeer* BtifAvSource::FindOrCreatePeer(const RawAddress& peer_address, auto it = peer_id2bta_handle_.find(peer_id); if (it == peer_id2bta_handle_.end() || it->second == kBtaHandleUnknown) { log::error( - "Cannot create peer for peer={} : cannot convert Peer ID={} " - "to unique BTA Handle", - peer_address, peer_id); + "Cannot create peer for peer={} : cannot convert Peer ID={} " + "to unique BTA Handle", + peer_address, peer_id); return nullptr; } bta_handle = it->second; } - log::info("Create peer: peer={} bta_handle=0x{:x} peer_id={}", - peer_address, bta_handle, peer_id); + log::info("Create peer: peer={} bta_handle=0x{:x} peer_id={}", peer_address, bta_handle, peer_id); peer = new BtifAvPeer(peer_address, AVDT_TSEP_SNK, bta_handle, peer_id); peers_.insert(std::make_pair(peer_address, peer)); peer->Init(); @@ -1337,8 +1326,8 @@ bool BtifAvSource::AllowedToConnect(const RawAddress& peer_address) const { if (!com::android::bluetooth::flags::a2dp_concurrent_source_sink() && btif_av_src_sink_coexist_enabled() && invalid_peer_check_) { log::info( - "invalid_peer_check_ so allow to connect here, when BTA_AV_OPEN_EVT " - "coming, would check again!"); + "invalid_peer_check_ so allow to connect here, when BTA_AV_OPEN_EVT " + "coming, would check again!"); return true; } @@ -1370,8 +1359,7 @@ bool BtifAvSource::AllowedToConnect(const RawAddress& peer_address) const { max_connected_peers_, btif_av_sink.GetPeersCount()); /* if source device connected, don't connect sink device */ - if (connected >= max_connected_peers_ || - btif_av_sink.GetPeersCount() != 0) { + if (connected >= max_connected_peers_ || btif_av_sink.GetPeersCount() != 0) { return false; } else { return true; @@ -1379,12 +1367,11 @@ bool BtifAvSource::AllowedToConnect(const RawAddress& peer_address) const { } if (com::android::bluetooth::flags::a2dp_concurrent_source_sink()) { const int sink_connected_peers_size = btif_av_sink.GetPeersCount(); - log::info( - "connected={}, max_connected_peers_={}, sink_connected_peers_size={}", - connected, max_connected_peers_, btif_av_sink.GetPeersCount()); - return ((connected + sink_connected_peers_size) < max_connected_peers_); + log::info("connected={}, max_connected_peers_={}, sink_connected_peers_size={}", connected, + max_connected_peers_, btif_av_sink.GetPeersCount()); + return (connected + sink_connected_peers_size) < max_connected_peers_; } - return (connected < max_connected_peers_); + return connected < max_connected_peers_; } void BtifAvSource::DumpPeersInfo(int fd) { @@ -1399,10 +1386,8 @@ void BtifAvSource::DumpPeersInfo(int fd) { void BtifAvSource::DispatchSuspendStreamEvent(btif_av_sm_event_t event) { std::lock_guard lock(btifavsource_peers_lock_); - if (event != BTIF_AV_SUSPEND_STREAM_REQ_EVT && - event != BTIF_AV_STOP_STREAM_REQ_EVT) { - log::error("Invalid event: {} id: {}", dump_av_sm_event_name(event), - static_cast(event)); + if (event != BTIF_AV_SUSPEND_STREAM_REQ_EVT && event != BTIF_AV_STOP_STREAM_REQ_EVT) { + log::error("Invalid event: {} id: {}", dump_av_sm_event_name(event), static_cast(event)); return; } bool av_stream_idle = true; @@ -1424,9 +1409,10 @@ void BtifAvSource::DeleteIdlePeers() { for (auto it = peers_.begin(); it != peers_.end();) { BtifAvPeer* peer = it->second; auto prev_it = it++; - if (!peer->CanBeDeleted()) continue; - log::info("peer={} bta_handle=0x{:x}", peer->PeerAddress(), - peer->BtaHandle()); + if (!peer->CanBeDeleted()) { + continue; + } + log::info("peer={} bta_handle=0x{:x}", peer->PeerAddress(), peer->BtaHandle()); peer->Cleanup(); peers_.erase(prev_it); delete peer; @@ -1448,8 +1434,8 @@ void BtifAvSource::CleanupAllPeers() { void BtifAvSource::RegisterAllBtaHandles() { for (int peer_id = kPeerIdMin; peer_id < kPeerIdMax; peer_id++) { - BTA_AvRegister(BTA_AV_CHNL_AUDIO, kBtifAvSourceServiceName, peer_id, - nullptr, UUID_SERVCLASS_AUDIO_SOURCE); + BTA_AvRegister(BTA_AV_CHNL_AUDIO, kBtifAvSourceServiceName, peer_id, nullptr, + UUID_SERVCLASS_AUDIO_SOURCE); } } @@ -1461,20 +1447,18 @@ void BtifAvSource::DeregisterAllBtaHandles() { peer_id2bta_handle_.clear(); } -void BtifAvSource::BtaHandleRegistered(uint8_t peer_id, - tBTA_AV_HNDL bta_handle) { +void BtifAvSource::BtaHandleRegistered(uint8_t peer_id, tBTA_AV_HNDL bta_handle) { peer_id2bta_handle_.insert(std::make_pair(peer_id, bta_handle)); // Set the BTA Handle for the Peer (if exists) BtifAvPeer* peer = FindPeerByPeerId(peer_id); if (peer != nullptr && peer->BtaHandle() != bta_handle) { if (peer->BtaHandle() == kBtaHandleUnknown) { - log::verbose("Assign peer: peer={} bta_handle=0x{:x} peer_id={}", - peer->PeerAddress(), bta_handle, peer_id); + log::verbose("Assign peer: peer={} bta_handle=0x{:x} peer_id={}", peer->PeerAddress(), + bta_handle, peer_id); } else { - log::warn( - "Correct peer: peer={} bta_handle=0x{:x}->0x{:x} peer_id={}", - peer->PeerAddress(), peer->BtaHandle(), bta_handle, peer_id); + log::warn("Correct peer: peer={} bta_handle=0x{:x}->0x{:x} peer_id={}", peer->PeerAddress(), + peer->BtaHandle(), bta_handle, peer_id); } peer->SetBtaHandle(bta_handle); } @@ -1483,26 +1467,27 @@ void BtifAvSource::BtaHandleRegistered(uint8_t peer_id, BtifAvPeer* BtifAvSource::popPeer(const RawAddress& peer_address) { std::lock_guard lock(btifavsource_peers_lock_); auto it = peers_.find(peer_address); - if (it == peers_.end()) return nullptr; + if (it == peers_.end()) { + return nullptr; + } BtifAvPeer* peer = it->second; peers_.erase(it); - log::info("peer={}, state={}", peer->PeerAddress(), - peer->StateMachine().StateId()); + log::info("peer={}, state={}", peer->PeerAddress(), peer->StateMachine().StateId()); return peer; } void BtifAvSource::AddPeer(BtifAvPeer* peer) { std::lock_guard lock(btifavsource_peers_lock_); - log::info("peer={}, state={}", peer->PeerAddress(), - peer->StateMachine().StateId()); + log::info("peer={}, state={}", peer->PeerAddress(), peer->StateMachine().StateId()); peers_.insert(std::make_pair(peer->PeerAddress(), peer)); } BtifAvSink::~BtifAvSink() { CleanupAllPeers(); } -bt_status_t BtifAvSink::Init(btav_sink_callbacks_t* callbacks, - int max_connected_audio_devices) { +bt_status_t BtifAvSink::Init(btav_sink_callbacks_t* callbacks, int max_connected_audio_devices) { log::info("(max_connected_audio_devices={})", max_connected_audio_devices); - if (enabled_) return BT_STATUS_SUCCESS; + if (enabled_) { + return BT_STATUS_SUCCESS; + } CleanupAllPeers(); max_connected_peers_ = max_connected_audio_devices; @@ -1511,8 +1496,7 @@ bt_status_t BtifAvSink::Init(btav_sink_callbacks_t* callbacks, /** source will have this configuration, but sink don't have, so don't * overwrite it. */ if (!btif_av_source.Enabled()) { - std::vector - codec_priorities; // Default priorities + std::vector codec_priorities; // Default priorities std::vector supported_codecs; bta_av_co_init(codec_priorities, &supported_codecs); } @@ -1527,17 +1511,17 @@ bt_status_t BtifAvSink::Init(btav_sink_callbacks_t* callbacks, void BtifAvSink::Cleanup() { log::info(""); - if (!enabled_) return; + if (!enabled_) { + return; + } enabled_ = false; btif_queue_cleanup(UUID_SERVCLASS_AUDIO_SINK); std::promise peer_ready_promise; - do_in_main_thread( - FROM_HERE, - base::BindOnce(base::IgnoreResult(&BtifAvSink::SetActivePeer), - base::Unretained(&btif_av_sink), RawAddress::kEmpty, - std::move(peer_ready_promise))); + do_in_main_thread(FROM_HERE, base::BindOnce(base::IgnoreResult(&BtifAvSink::SetActivePeer), + base::Unretained(&btif_av_sink), RawAddress::kEmpty, + std::move(peer_ready_promise))); do_in_main_thread(FROM_HERE, base::BindOnce(&btif_a2dp_sink_cleanup)); btif_disable_service(BTA_A2DP_SINK_SERVICE_ID); @@ -1548,7 +1532,9 @@ void BtifAvSink::Cleanup() { BtifAvPeer* BtifAvSink::FindPeer(const RawAddress& peer_address) { auto it = peers_.find(peer_address); - if (it != peers_.end()) return it->second; + if (it != peers_.end()) { + return it->second; + } return nullptr; } @@ -1574,13 +1560,14 @@ BtifAvPeer* BtifAvSink::FindPeerByPeerId(uint8_t peer_id) { return nullptr; } -BtifAvPeer* BtifAvSink::FindOrCreatePeer(const RawAddress& peer_address, - tBTA_AV_HNDL bta_handle) { +BtifAvPeer* BtifAvSink::FindOrCreatePeer(const RawAddress& peer_address, tBTA_AV_HNDL bta_handle) { std::lock_guard lock(btifavsink_peers_lock_); log::verbose("peer={} bta_handle=0x{:x}", peer_address, bta_handle); BtifAvPeer* peer = FindPeer(peer_address); - if (peer != nullptr) return peer; + if (peer != nullptr) { + return peer; + } // Find next availabie Peer ID to use uint8_t peer_id; @@ -1588,18 +1575,21 @@ BtifAvPeer* BtifAvSink::FindOrCreatePeer(const RawAddress& peer_address, /* because the peer id may be in source cb and we cannot use it */ if (btif_av_both_enable()) { if (FindPeerByPeerId(peer_id) == nullptr && - btif_av_source.FindPeerByPeerId(peer_id) == nullptr) + btif_av_source.FindPeerByPeerId(peer_id) == nullptr) { break; + } } else { - if (FindPeerByPeerId(peer_id) == nullptr) break; + if (FindPeerByPeerId(peer_id) == nullptr) { + break; + } } } if (peer_id == kPeerIdMax) { log::error( - "Cannot create peer for peer={} : cannot allocate unique Peer " - "ID", - peer_address); + "Cannot create peer for peer={} : cannot allocate unique Peer " + "ID", + peer_address); return nullptr; } @@ -1608,16 +1598,15 @@ BtifAvPeer* BtifAvSink::FindOrCreatePeer(const RawAddress& peer_address, auto it = peer_id2bta_handle_.find(peer_id); if (it == peer_id2bta_handle_.end() || it->second == kBtaHandleUnknown) { log::error( - "Cannot create peer for peer={} : cannot convert Peer ID={} " - "to unique BTA Handle", - peer_address, peer_id); + "Cannot create peer for peer={} : cannot convert Peer ID={} " + "to unique BTA Handle", + peer_address, peer_id); return nullptr; } bta_handle = it->second; } - log::info("Create peer: peer={} bta_handle=0x{:x} peer_id={}", - peer_address, bta_handle, peer_id); + log::info("Create peer: peer={} bta_handle=0x{:x} peer_id={}", peer_address, bta_handle, peer_id); peer = new BtifAvPeer(peer_address, AVDT_TSEP_SRC, bta_handle, peer_id); peers_.insert(std::make_pair(peer_address, peer)); peer->Init(); @@ -1641,8 +1630,8 @@ bool BtifAvSink::AllowedToConnect(const RawAddress& peer_address) const { if (!com::android::bluetooth::flags::a2dp_concurrent_source_sink() && btif_av_src_sink_coexist_enabled() && invalid_peer_check_) { log::info( - "invalid_peer_check_ so allow to connect here, when BTA_AV_OPEN_EVT " - "coming, would check again!"); + "invalid_peer_check_ so allow to connect here, when BTA_AV_OPEN_EVT " + "coming, would check again!"); return true; } // Count peers that are in the process of connecting or already connected @@ -1655,7 +1644,9 @@ bool BtifAvSink::AllowedToConnect(const RawAddress& peer_address) const { if (peer->PeerAddress() == peer_address) { if (!com::android::bluetooth::flags::a2dp_concurrent_source_sink()) { /* we should check if another role is used */ - if (btif_av_both_enable()) break; + if (btif_av_both_enable()) { + break; + } } return true; // Already connected or accounted for } @@ -1664,11 +1655,9 @@ bool BtifAvSink::AllowedToConnect(const RawAddress& peer_address) const { case BtifAvStateMachine::kStateClosing: case BtifAvStateMachine::kStateIdle: if ((btif_a2dp_sink_get_audio_track() != nullptr) && - (peer->PeerAddress() != peer_address)) { - log::info( - "there is another peer with audio track({}), another={}, peer={}", - fmt::ptr(btif_a2dp_sink_get_audio_track()), peer->PeerAddress(), - peer_address); + (peer->PeerAddress() != peer_address)) { + log::info("there is another peer with audio track({}), another={}, peer={}", + fmt::ptr(btif_a2dp_sink_get_audio_track()), peer->PeerAddress(), peer_address); connected++; } break; @@ -1676,23 +1665,20 @@ bool BtifAvSink::AllowedToConnect(const RawAddress& peer_address) const { break; } } - if (!com::android::bluetooth::flags::a2dp_concurrent_source_sink() && - btif_av_both_enable()) { - log::info("connected={}, max_connected_peers_={}, source_peers={}", - connected, max_connected_peers_, btif_av_source.GetPeersCount()); + if (!com::android::bluetooth::flags::a2dp_concurrent_source_sink() && btif_av_both_enable()) { + log::info("connected={}, max_connected_peers_={}, source_peers={}", connected, + max_connected_peers_, btif_av_source.GetPeersCount()); /* if source device connected, don't connect sink device */ - return (connected < max_connected_peers_) && - (btif_av_source.GetPeersCount() == 0); + return (connected < max_connected_peers_) && (btif_av_source.GetPeersCount() == 0); } if (com::android::bluetooth::flags::a2dp_concurrent_source_sink()) { const int source_connected_peers_size = btif_av_source.GetPeersCount(); - log::info( - "connected={}, max_connected_peers_={}, source_connected_peers_size={}", - connected, max_connected_peers_, source_connected_peers_size); - return ((connected + source_connected_peers_size) < max_connected_peers_); + log::info("connected={}, max_connected_peers_={}, source_connected_peers_size={}", connected, + max_connected_peers_, source_connected_peers_size); + return (connected + source_connected_peers_size) < max_connected_peers_; } - return (connected < max_connected_peers_); + return connected < max_connected_peers_; } void BtifAvSink::DeleteIdlePeers() { @@ -1700,9 +1686,10 @@ void BtifAvSink::DeleteIdlePeers() { for (auto it = peers_.begin(); it != peers_.end();) { BtifAvPeer* peer = it->second; auto prev_it = it++; - if (!peer->CanBeDeleted()) continue; - log::info("Deleting idle peer: {} bta_handle=0x{:x}", peer->PeerAddress(), - peer->BtaHandle()); + if (!peer->CanBeDeleted()) { + continue; + } + log::info("Deleting idle peer: {} bta_handle=0x{:x}", peer->PeerAddress(), peer->BtaHandle()); peer->Cleanup(); peers_.erase(prev_it); delete peer; @@ -1724,8 +1711,8 @@ void BtifAvSink::CleanupAllPeers() { void BtifAvSink::RegisterAllBtaHandles() { for (int peer_id = kPeerIdMin; peer_id < kPeerIdMax; peer_id++) { - BTA_AvRegister(BTA_AV_CHNL_AUDIO, kBtifAvSinkServiceName, peer_id, - bta_av_sink_media_callback, UUID_SERVCLASS_AUDIO_SINK); + BTA_AvRegister(BTA_AV_CHNL_AUDIO, kBtifAvSinkServiceName, peer_id, bta_av_sink_media_callback, + UUID_SERVCLASS_AUDIO_SINK); } } @@ -1744,12 +1731,11 @@ void BtifAvSink::BtaHandleRegistered(uint8_t peer_id, tBTA_AV_HNDL bta_handle) { BtifAvPeer* peer = FindPeerByPeerId(peer_id); if (peer != nullptr && peer->BtaHandle() != bta_handle) { if (peer->BtaHandle() == kBtaHandleUnknown) { - log::verbose("Assign peer: peer={} bta_handle=0x{:x} peer_id={}", - peer->PeerAddress(), bta_handle, peer_id); + log::verbose("Assign peer: peer={} bta_handle=0x{:x} peer_id={}", peer->PeerAddress(), + bta_handle, peer_id); } else { - log::warn( - "Correct peer: peer={} bta_handle=0x{:x}->0x{:x} peer_id={}", - peer->PeerAddress(), peer->BtaHandle(), bta_handle, peer_id); + log::warn("Correct peer: peer={} bta_handle=0x{:x}->0x{:x} peer_id={}", peer->PeerAddress(), + peer->BtaHandle(), bta_handle, peer_id); } peer->SetBtaHandle(bta_handle); } @@ -1758,18 +1744,18 @@ void BtifAvSink::BtaHandleRegistered(uint8_t peer_id, tBTA_AV_HNDL bta_handle) { BtifAvPeer* BtifAvSink::popPeer(const RawAddress& peer_address) { std::lock_guard lock(btifavsink_peers_lock_); auto it = peers_.find(peer_address); - if (it == peers_.end()) return nullptr; + if (it == peers_.end()) { + return nullptr; + } BtifAvPeer* peer = it->second; peers_.erase(it); - log::info("peer={}, state={}", peer->PeerAddress(), - peer->StateMachine().StateId()); + log::info("peer={}, state={}", peer->PeerAddress(), peer->StateMachine().StateId()); return peer; } void BtifAvSink::AddPeer(BtifAvPeer* peer) { std::lock_guard lock(btifavsink_peers_lock_); - log::info("peer={}, state={}", peer->PeerAddress(), - peer->StateMachine().StateId()); + log::info("peer={}, state={}", peer->PeerAddress(), peer->StateMachine().StateId()); peers_.insert(std::make_pair(peer->PeerAddress(), peer)); } @@ -1781,8 +1767,7 @@ void BtifAvStateMachine::StateIdle::OnEnter() { // Stop A2DP if this is the active peer if (peer_.IsActivePeer() || peer_.ActivePeerAddress().IsEmpty()) { - btif_a2dp_on_idle(peer_.PeerAddress(), - peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); + btif_a2dp_on_idle(peer_.PeerAddress(), peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); } // Reset the active peer if this was the active peer and @@ -1790,23 +1775,19 @@ void BtifAvStateMachine::StateIdle::OnEnter() { if (peer_.IsActivePeer() && peer_.CanBeDeleted()) { std::promise peer_ready_promise; if (peer_.IsSink()) { - btif_av_source.SetActivePeer(RawAddress::kEmpty, - std::move(peer_ready_promise)); + btif_av_source.SetActivePeer(RawAddress::kEmpty, std::move(peer_ready_promise)); } else if (peer_.IsSource()) { - btif_av_sink.SetActivePeer(RawAddress::kEmpty, - std::move(peer_ready_promise)); + btif_av_sink.SetActivePeer(RawAddress::kEmpty, std::move(peer_ready_promise)); } } // Delete peers that are re-entering the Idle state if (peer_.IsSink()) { - do_in_main_thread(FROM_HERE, - base::BindOnce(&BtifAvSource::DeleteIdlePeers, - base::Unretained(&btif_av_source))); + do_in_main_thread(FROM_HERE, base::BindOnce(&BtifAvSource::DeleteIdlePeers, + base::Unretained(&btif_av_source))); } else if (peer_.IsSource()) { - do_in_main_thread(FROM_HERE, - base::BindOnce(&BtifAvSink::DeleteIdlePeers, - base::Unretained(&btif_av_sink))); + do_in_main_thread(FROM_HERE, base::BindOnce(&BtifAvSink::DeleteIdlePeers, + base::Unretained(&btif_av_sink))); } } @@ -1815,9 +1796,8 @@ void BtifAvStateMachine::StateIdle::OnExit() { } bool BtifAvStateMachine::StateIdle::ProcessEvent(uint32_t event, void* p_data) { - log::info("state=Idle peer={} event={} flags={} active_peer={}", - peer_.PeerAddress(), BtifAvEvent::EventName(event), - peer_.FlagsToString(), peer_.IsActivePeer()); + log::info("state=Idle peer={} event={} flags={} active_peer={}", peer_.PeerAddress(), + BtifAvEvent::EventName(event), peer_.FlagsToString(), peer_.IsActivePeer()); switch (event) { case BTA_AV_ENABLE_EVT: @@ -1848,34 +1828,34 @@ bool BtifAvStateMachine::StateIdle::ProcessEvent(uint32_t event, void* p_data) { // Check whether connection is allowed if (peer_.IsSink()) { can_connect = btif_av_source.AllowedToConnect(peer_.PeerAddress()); - if (!can_connect) btif_av_source_disconnect(peer_.PeerAddress()); + if (!can_connect) { + btif_av_source_disconnect(peer_.PeerAddress()); + } } else if (peer_.IsSource()) { can_connect = btif_av_sink.AllowedToConnect(peer_.PeerAddress()); - if (!can_connect) btif_av_sink_disconnect(peer_.PeerAddress()); + if (!can_connect) { + btif_av_sink_disconnect(peer_.PeerAddress()); + } } if (!can_connect) { - log::error("Cannot connect to peer {}: too many connected peers", - peer_.PeerAddress()); + log::error("Cannot connect to peer {}: too many connected peers", peer_.PeerAddress()); if (peer_.SelfInitiatedConnection()) { btif_queue_advance(); } break; } btif_av_query_mandatory_codec_priority(peer_.PeerAddress()); - BTA_AvOpen(peer_.PeerAddress(), peer_.BtaHandle(), true, - peer_.LocalUuidServiceClass()); + BTA_AvOpen(peer_.PeerAddress(), peer_.BtaHandle(), true, peer_.LocalUuidServiceClass()); peer_.StateMachine().TransitionTo(BtifAvStateMachine::kStateOpening); if (event == BTIF_AV_CONNECT_REQ_EVT) { DEVICE_IOT_CONFIG_ADDR_SET_INT( - peer_.PeerAddress(), IOT_CONF_KEY_A2DP_ROLE, - (peer_.LocalUuidServiceClass() == UUID_SERVCLASS_AUDIO_SOURCE) - ? IOT_CONF_VAL_A2DP_ROLE_SINK - : IOT_CONF_VAL_A2DP_ROLE_SOURCE); - DEVICE_IOT_CONFIG_ADDR_INT_ADD_ONE(peer_.PeerAddress(), - IOT_CONF_KEY_A2DP_CONN_COUNT); + peer_.PeerAddress(), IOT_CONF_KEY_A2DP_ROLE, + (peer_.LocalUuidServiceClass() == UUID_SERVCLASS_AUDIO_SOURCE) + ? IOT_CONF_VAL_A2DP_ROLE_SINK + : IOT_CONF_VAL_A2DP_ROLE_SOURCE); + DEVICE_IOT_CONFIG_ADDR_INT_ADD_ONE(peer_.PeerAddress(), IOT_CONF_KEY_A2DP_CONN_COUNT); } else if (event == BTA_AV_PENDING_EVT) { - DEVICE_IOT_CONFIG_ADDR_INT_ADD_ONE(peer_.PeerAddress(), - IOT_CONF_KEY_A2DP_CONN_COUNT); + DEVICE_IOT_CONFIG_ADDR_INT_ADD_ONE(peer_.PeerAddress(), IOT_CONF_KEY_A2DP_CONN_COUNT); } } break; case BTIF_AV_AVRCP_OPEN_EVT: @@ -1897,51 +1877,44 @@ bool BtifAvStateMachine::StateIdle::ProcessEvent(uint32_t event, void* p_data) { if (peer_.IsSink()) { can_connect = btif_av_source.AllowedToConnect(peer_.PeerAddress()); if (!can_connect) { - log::error("Source profile doesn't allow connection to peer:{}", - peer_.PeerAddress()); - if (btif_av_src_sink_coexist_enabled()) - BTA_AvCloseRc( - (reinterpret_cast(p_data))->rc_open.rc_handle); - else + log::error("Source profile doesn't allow connection to peer:{}", peer_.PeerAddress()); + if (btif_av_src_sink_coexist_enabled()) { + BTA_AvCloseRc((reinterpret_cast(p_data))->rc_open.rc_handle); + } else { btif_av_source_disconnect(peer_.PeerAddress()); + } } } else if (peer_.IsSource()) { can_connect = btif_av_sink.AllowedToConnect(peer_.PeerAddress()); if (!can_connect) { - log::error("Sink profile doesn't allow connection to peer:{}", - peer_.PeerAddress()); - if (btif_av_src_sink_coexist_enabled()) - BTA_AvCloseRc( - (reinterpret_cast(p_data))->rc_open.rc_handle); - else + log::error("Sink profile doesn't allow connection to peer:{}", peer_.PeerAddress()); + if (btif_av_src_sink_coexist_enabled()) { + BTA_AvCloseRc((reinterpret_cast(p_data))->rc_open.rc_handle); + } else { btif_av_sink_disconnect(peer_.PeerAddress()); + } } } if (!can_connect) { - log::error("Cannot connect to peer {}: too many connected peers", - peer_.PeerAddress()); + log::error("Cannot connect to peer {}: too many connected peers", peer_.PeerAddress()); break; } /* if peer is source, then start timer for sink connect to src */ if (btif_av_src_sink_coexist_enabled()) { if (peer_.IsSource()) { - alarm_set_on_mloop( - peer_.AvOpenOnRcTimer(), BtifAvPeer::kTimeoutAvOpenOnRcMs, - btif_av_sink_initiate_av_open_timer_timeout, &peer_); + alarm_set_on_mloop(peer_.AvOpenOnRcTimer(), BtifAvPeer::kTimeoutAvOpenOnRcMs, + btif_av_sink_initiate_av_open_timer_timeout, &peer_); } else { - alarm_set_on_mloop( - peer_.AvOpenOnRcTimer(), BtifAvPeer::kTimeoutAvOpenOnRcMs, - btif_av_source_initiate_av_open_timer_timeout, &peer_); + alarm_set_on_mloop(peer_.AvOpenOnRcTimer(), BtifAvPeer::kTimeoutAvOpenOnRcMs, + btif_av_source_initiate_av_open_timer_timeout, &peer_); } } else { if (btif_av_source.Enabled()) { - alarm_set_on_mloop( - peer_.AvOpenOnRcTimer(), BtifAvPeer::kTimeoutAvOpenOnRcMs, - btif_av_source_initiate_av_open_timer_timeout, &peer_); + alarm_set_on_mloop(peer_.AvOpenOnRcTimer(), BtifAvPeer::kTimeoutAvOpenOnRcMs, + btif_av_source_initiate_av_open_timer_timeout, &peer_); } else if (btif_av_sink.Enabled()) { - alarm_set_on_mloop( - peer_.AvOpenOnRcTimer(), BtifAvPeer::kTimeoutAvOpenOnRcMs, - btif_av_sink_initiate_av_open_timer_timeout, &peer_); + alarm_set_on_mloop(peer_.AvOpenOnRcTimer(), BtifAvPeer::kTimeoutAvOpenOnRcMs, + btif_av_sink_initiate_av_open_timer_timeout, &peer_); } } if (event == BTA_AV_RC_OPEN_EVT) { @@ -1958,9 +1931,8 @@ bool BtifAvStateMachine::StateIdle::ProcessEvent(uint32_t event, void* p_data) { // We hit these scenarios while running PTS test case for AVRCP Controller. case BTIF_AV_SINK_CONFIG_REQ_EVT: { const btif_av_sink_config_req_t* p_config_req = - static_cast(p_data); - btif_av_report_sink_audio_config_state(p_config_req->peer_address, - p_config_req->sample_rate, + static_cast(p_data); + btif_av_report_sink_audio_config_state(p_config_req->peer_address, p_config_req->sample_rate, p_config_req->channel_count); } break; @@ -1969,22 +1941,19 @@ bool BtifAvStateMachine::StateIdle::ProcessEvent(uint32_t event, void* p_data) { tBTA_AV_STATUS status = p_bta_data->open.status; bool can_connect = true; - log::info("Peer {} : event={} flags={} status={}({}) edr=0x{:x}", - peer_.PeerAddress(), BtifAvEvent::EventName(event), - peer_.FlagsToString(), status, - (status == BTA_AV_SUCCESS) ? "SUCCESS" : "FAILED", - p_bta_data->open.edr); + log::info("Peer {} : event={} flags={} status={}({}) edr=0x{:x}", peer_.PeerAddress(), + BtifAvEvent::EventName(event), peer_.FlagsToString(), status, + (status == BTA_AV_SUCCESS) ? "SUCCESS" : "FAILED", p_bta_data->open.edr); - btif_report_connection_state( - peer_.PeerAddress(), BTAV_CONNECTION_STATE_CONNECTING, - bt_status_t::BT_STATUS_SUCCESS, BTA_AV_SUCCESS, - peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); + btif_report_connection_state(peer_.PeerAddress(), BTAV_CONNECTION_STATE_CONNECTING, + bt_status_t::BT_STATUS_SUCCESS, BTA_AV_SUCCESS, + peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); if (p_bta_data->open.status == BTA_AV_SUCCESS) { peer_.SetEdr(p_bta_data->open.edr); if (btif_av_src_sink_coexist_enabled()) { - log::verbose("Peer {} sep={}, open_sep={}", peer_.PeerAddress(), - peer_.PeerSep(), p_bta_data->open.sep); + log::verbose("Peer {} sep={}, open_sep={}", peer_.PeerAddress(), peer_.PeerSep(), + p_bta_data->open.sep); /* if peer is wrong sep type, move it to BtifAvSxxx */ if (!com::android::bluetooth::flags::a2dp_concurrent_source_sink()) { if (peer_.PeerSep() == AVDT_TSEP_SNK) { @@ -2000,15 +1969,17 @@ bool BtifAvStateMachine::StateIdle::ProcessEvent(uint32_t event, void* p_data) { if (peer_.PeerSep() == AVDT_TSEP_SNK) { tmp_peer = btif_av_source.popPeer(peer_.PeerAddress()); - if (peer_.PeerAddress() != tmp_peer->PeerAddress()) + if (peer_.PeerAddress() != tmp_peer->PeerAddress()) { log::error("error, not same peer"); + } btif_av_sink.AddPeer(tmp_peer); } else { tmp_peer = btif_av_sink.popPeer(peer_.PeerAddress()); - if (peer_.PeerAddress() != tmp_peer->PeerAddress()) + if (peer_.PeerAddress() != tmp_peer->PeerAddress()) { log::error("error, not same peer"); + } btif_av_source.AddPeer(tmp_peer); } @@ -2020,17 +1991,14 @@ bool BtifAvStateMachine::StateIdle::ProcessEvent(uint32_t event, void* p_data) { } btif_rc_check_pending_cmd(p_bta_data->open.bd_addr); } - log::assert_that( - peer_.PeerSep() == p_bta_data->open.sep, - "assert failed: peer_.PeerSep() == p_bta_data->open.sep"); + log::assert_that(peer_.PeerSep() == p_bta_data->open.sep, + "assert failed: peer_.PeerSep() == p_bta_data->open.sep"); - can_connect = peer_.IsSink() - ? btif_av_source.AllowedToConnect(peer_.PeerAddress()) - : btif_av_sink.AllowedToConnect(peer_.PeerAddress()); + can_connect = peer_.IsSink() ? btif_av_source.AllowedToConnect(peer_.PeerAddress()) + : btif_av_sink.AllowedToConnect(peer_.PeerAddress()); if (!can_connect) { - log::error("Cannot connect to peer {}: too many connected peers", - peer_.PeerAddress()); + log::error("Cannot connect to peer {}: too many connected peers", peer_.PeerAddress()); if (peer_.IsSink()) { btif_av_source_disconnect(peer_.PeerAddress()); @@ -2038,36 +2006,30 @@ bool BtifAvStateMachine::StateIdle::ProcessEvent(uint32_t event, void* p_data) { btif_av_sink_disconnect(peer_.PeerAddress()); } - btif_report_connection_state( - peer_.PeerAddress(), BTAV_CONNECTION_STATE_DISCONNECTED, - bt_status_t::BT_STATUS_NOMEM, BTA_AV_FAIL_RESOURCES, - peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); + btif_report_connection_state(peer_.PeerAddress(), BTAV_CONNECTION_STATE_DISCONNECTED, + bt_status_t::BT_STATUS_NOMEM, BTA_AV_FAIL_RESOURCES, + peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); peer_.StateMachine().TransitionTo(BtifAvStateMachine::kStateIdle); } else { if (peer_.IsSink()) { // If queued PLAY command, send it now - btif_rc_check_handle_pending_play( - p_bta_data->open.bd_addr, - (p_bta_data->open.status == BTA_AV_SUCCESS)); - } else if (peer_.IsSource() && - (p_bta_data->open.status == BTA_AV_SUCCESS)) { + btif_rc_check_handle_pending_play(p_bta_data->open.bd_addr, + (p_bta_data->open.status == BTA_AV_SUCCESS)); + } else if (peer_.IsSource() && (p_bta_data->open.status == BTA_AV_SUCCESS)) { // Bring up AVRCP connection as well BTA_AvOpenRc(peer_.BtaHandle()); } - btif_report_connection_state( - peer_.PeerAddress(), BTAV_CONNECTION_STATE_CONNECTED, - bt_status_t::BT_STATUS_SUCCESS, BTA_AV_SUCCESS, - peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); + btif_report_connection_state(peer_.PeerAddress(), BTAV_CONNECTION_STATE_CONNECTED, + bt_status_t::BT_STATUS_SUCCESS, BTA_AV_SUCCESS, + peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); peer_.StateMachine().TransitionTo(BtifAvStateMachine::kStateOpened); } } else { - btif_report_connection_state( - peer_.PeerAddress(), BTAV_CONNECTION_STATE_DISCONNECTED, - bt_status_t::BT_STATUS_FAIL, status, - peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); + btif_report_connection_state(peer_.PeerAddress(), BTAV_CONNECTION_STATE_DISCONNECTED, + bt_status_t::BT_STATUS_FAIL, status, + peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); peer_.StateMachine().TransitionTo(BtifAvStateMachine::kStateIdle); - DEVICE_IOT_CONFIG_ADDR_INT_ADD_ONE(peer_.PeerAddress(), - IOT_CONF_KEY_A2DP_CONN_FAIL_COUNT); + DEVICE_IOT_CONFIG_ADDR_INT_ADD_ONE(peer_.PeerAddress(), IOT_CONF_KEY_A2DP_CONN_FAIL_COUNT); } btif_queue_advance(); } break; @@ -2083,8 +2045,8 @@ bool BtifAvStateMachine::StateIdle::ProcessEvent(uint32_t event, void* p_data) { case BTIF_AV_AVRCP_CLOSE_EVT: case BTA_AV_RC_CLOSE_EVT: { - log::verbose("Peer {} : event={} : Stopping AV timer", - peer_.PeerAddress(), BtifAvEvent::EventName(event)); + log::verbose("Peer {} : event={} : Stopping AV timer", peer_.PeerAddress(), + BtifAvEvent::EventName(event)); alarm_cancel(peer_.AvOpenOnRcTimer()); if (event == BTA_AV_RC_CLOSE_EVT) { @@ -2093,14 +2055,13 @@ bool BtifAvStateMachine::StateIdle::ProcessEvent(uint32_t event, void* p_data) { } break; case BTIF_AV_OFFLOAD_START_REQ_EVT: - log::error("Peer {} : event={}: stream is not Opened", - peer_.PeerAddress(), BtifAvEvent::EventName(event)); + log::error("Peer {} : event={}: stream is not Opened", peer_.PeerAddress(), + BtifAvEvent::EventName(event)); btif_a2dp_on_offload_started(peer_.PeerAddress(), BTA_AV_FAIL); break; default: - log::warn("Peer {} : Unhandled event={}", peer_.PeerAddress(), - BtifAvEvent::EventName(event)); + log::warn("Peer {} : Unhandled event={}", peer_.PeerAddress(), BtifAvEvent::EventName(event)); return false; } @@ -2113,23 +2074,22 @@ void BtifAvStateMachine::StateOpening::OnEnter() { // Inform the application that we are entering connecting state if (btif_av_both_enable()) { /* if peer connect to us, don't know which role it is */ - if (!peer_.SelfInitiatedConnection()) return; + if (!peer_.SelfInitiatedConnection()) { + return; + } } - btif_report_connection_state( - peer_.PeerAddress(), BTAV_CONNECTION_STATE_CONNECTING, - bt_status_t::BT_STATUS_SUCCESS, BTA_AV_SUCCESS, - peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); + btif_report_connection_state(peer_.PeerAddress(), BTAV_CONNECTION_STATE_CONNECTING, + bt_status_t::BT_STATUS_SUCCESS, BTA_AV_SUCCESS, + peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); } void BtifAvStateMachine::StateOpening::OnExit() { log::info("state=Opening peer={}", peer_.PeerAddress()); } -bool BtifAvStateMachine::StateOpening::ProcessEvent(uint32_t event, - void* p_data) { - log::info("state=Opening peer={} event={} flags={} active_peer={}", - peer_.PeerAddress(), BtifAvEvent::EventName(event), - peer_.FlagsToString(), peer_.IsActivePeer()); +bool BtifAvStateMachine::StateOpening::ProcessEvent(uint32_t event, void* p_data) { + log::info("state=Opening peer={} event={} flags={} active_peer={}", peer_.PeerAddress(), + BtifAvEvent::EventName(event), peer_.FlagsToString(), peer_.IsActivePeer()); switch (event) { case BTIF_AV_STOP_STREAM_REQ_EVT: @@ -2140,31 +2100,26 @@ bool BtifAvStateMachine::StateOpening::ProcessEvent(uint32_t event, // ACL Disconnected needs to be handled only in Opening state, because // it is in an intermediate state. In other states we can handle // incoming/outgoing connect/disconnect requests. - log::warn( - "Peer {} : event={}: transitioning to Idle due to ACL Disconnect", - peer_.PeerAddress(), BtifAvEvent::EventName(event)); - log_counter_metrics_btif(android::bluetooth::CodePathCounterKeyEnum:: - A2DP_CONNECTION_ACL_DISCONNECTED, - 1); - btif_report_connection_state( - peer_.PeerAddress(), BTAV_CONNECTION_STATE_DISCONNECTED, - bt_status_t::BT_STATUS_FAIL, BTA_AV_FAIL, - peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); + log::warn("Peer {} : event={}: transitioning to Idle due to ACL Disconnect", + peer_.PeerAddress(), BtifAvEvent::EventName(event)); + log_counter_metrics_btif( + android::bluetooth::CodePathCounterKeyEnum::A2DP_CONNECTION_ACL_DISCONNECTED, 1); + btif_report_connection_state(peer_.PeerAddress(), BTAV_CONNECTION_STATE_DISCONNECTED, + bt_status_t::BT_STATUS_FAIL, BTA_AV_FAIL, + peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); peer_.StateMachine().TransitionTo(BtifAvStateMachine::kStateIdle); if (peer_.SelfInitiatedConnection()) { btif_queue_advance(); } break; case BTA_AV_REJECT_EVT: - log::warn("Peer {} : event={} flags={}", peer_.PeerAddress(), - BtifAvEvent::EventName(event), peer_.FlagsToString()); - log_counter_metrics_btif(android::bluetooth::CodePathCounterKeyEnum:: - A2DP_CONNECTION_REJECT_EVT, - 1); - btif_report_connection_state( - peer_.PeerAddress(), BTAV_CONNECTION_STATE_DISCONNECTED, - bt_status_t::BT_STATUS_AUTH_REJECTED, BTA_AV_FAIL, - peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); + log::warn("Peer {} : event={} flags={}", peer_.PeerAddress(), BtifAvEvent::EventName(event), + peer_.FlagsToString()); + log_counter_metrics_btif( + android::bluetooth::CodePathCounterKeyEnum::A2DP_CONNECTION_REJECT_EVT, 1); + btif_report_connection_state(peer_.PeerAddress(), BTAV_CONNECTION_STATE_DISCONNECTED, + bt_status_t::BT_STATUS_AUTH_REJECTED, BTA_AV_FAIL, + peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); peer_.StateMachine().TransitionTo(BtifAvStateMachine::kStateIdle); if (peer_.SelfInitiatedConnection()) { btif_queue_advance(); @@ -2176,18 +2131,16 @@ bool BtifAvStateMachine::StateOpening::ProcessEvent(uint32_t event, int av_state; tBTA_AV_STATUS status = p_bta_data->open.status; - log::info("Peer {} : event={} flags={} status={}({}) edr=0x{:x}", - peer_.PeerAddress(), BtifAvEvent::EventName(event), - peer_.FlagsToString(), status, - (status == BTA_AV_SUCCESS) ? "SUCCESS" : "FAILED", - p_bta_data->open.edr); + log::info("Peer {} : event={} flags={} status={}({}) edr=0x{:x}", peer_.PeerAddress(), + BtifAvEvent::EventName(event), peer_.FlagsToString(), status, + (status == BTA_AV_SUCCESS) ? "SUCCESS" : "FAILED", p_bta_data->open.edr); if (p_bta_data->open.status == BTA_AV_SUCCESS) { av_state = BtifAvStateMachine::kStateOpened; peer_.SetEdr(p_bta_data->open.edr); if (btif_av_src_sink_coexist_enabled()) { - log::verbose("Peer {} sep={}, open_sep={}", peer_.PeerAddress(), - peer_.PeerSep(), p_bta_data->open.sep); + log::verbose("Peer {} sep={}, open_sep={}", peer_.PeerAddress(), peer_.PeerSep(), + p_bta_data->open.sep); /* if peer is wrong sep type, move it to BtifAvSxxx */ if (!com::android::bluetooth::flags::a2dp_concurrent_source_sink()) { if (peer_.PeerSep() == AVDT_TSEP_SNK) { @@ -2203,15 +2156,17 @@ bool BtifAvStateMachine::StateOpening::ProcessEvent(uint32_t event, if (peer_.PeerSep() == AVDT_TSEP_SNK) { tmp_peer = btif_av_source.popPeer(peer_.PeerAddress()); - if (peer_.PeerAddress() != tmp_peer->PeerAddress()) + if (peer_.PeerAddress() != tmp_peer->PeerAddress()) { log::error("error, not same peer"); + } btif_av_sink.AddPeer(tmp_peer); } else { tmp_peer = btif_av_sink.popPeer(peer_.PeerAddress()); - if (peer_.PeerAddress() != tmp_peer->PeerAddress()) + if (peer_.PeerAddress() != tmp_peer->PeerAddress()) { log::error("error, not same peer"); + } btif_av_source.AddPeer(tmp_peer); } @@ -2223,9 +2178,8 @@ bool BtifAvStateMachine::StateOpening::ProcessEvent(uint32_t event, } btif_rc_check_pending_cmd(p_bta_data->open.bd_addr); } - log::assert_that( - peer_.PeerSep() == p_bta_data->open.sep, - "assert failed: peer_.PeerSep() == p_bta_data->open.sep"); + log::assert_that(peer_.PeerSep() == p_bta_data->open.sep, + "assert failed: peer_.PeerSep() == p_bta_data->open.sep"); /** normally it can be checked in IDLE PENDING/CONNECT_REQ, in case: * 1 speacker connected to DUT and phone connect DUT, because * default @@ -2236,29 +2190,30 @@ bool BtifAvStateMachine::StateOpening::ProcessEvent(uint32_t event, bool can_connect = true; if (peer_.IsSink()) { can_connect = btif_av_source.AllowedToConnect(peer_.PeerAddress()); - if (!can_connect) btif_av_source_disconnect(peer_.PeerAddress()); + if (!can_connect) { + btif_av_source_disconnect(peer_.PeerAddress()); + } } else if (peer_.IsSource()) { can_connect = btif_av_sink.AllowedToConnect(peer_.PeerAddress()); - if (!can_connect) btif_av_sink_disconnect(peer_.PeerAddress()); + if (!can_connect) { + btif_av_sink_disconnect(peer_.PeerAddress()); + } } } /** @} */ // Report the connection state to the application - btif_report_connection_state( - peer_.PeerAddress(), BTAV_CONNECTION_STATE_CONNECTED, - bt_status_t::BT_STATUS_SUCCESS, BTA_AV_SUCCESS, - peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); + btif_report_connection_state(peer_.PeerAddress(), BTAV_CONNECTION_STATE_CONNECTED, + bt_status_t::BT_STATUS_SUCCESS, BTA_AV_SUCCESS, + peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); log_counter_metrics_btif( - android::bluetooth::CodePathCounterKeyEnum::A2DP_CONNECTION_SUCCESS, - 1); + android::bluetooth::CodePathCounterKeyEnum::A2DP_CONNECTION_SUCCESS, 1); } else { if (btif_rc_is_connected_peer(peer_.PeerAddress())) { // Disconnect the AVRCP connection, in case the A2DP connectiton // failed for any reason. log::warn("Peer {} : Disconnecting AVRCP", peer_.PeerAddress()); - uint8_t peer_handle = - btif_rc_get_connected_peer_handle(peer_.PeerAddress()); + uint8_t peer_handle = btif_rc_get_connected_peer_handle(peer_.PeerAddress()); if (peer_handle != BTRC_HANDLE_NONE) { BTA_AvCloseRc(peer_handle); } @@ -2267,28 +2222,25 @@ bool BtifAvStateMachine::StateOpening::ProcessEvent(uint32_t event, } av_state = BtifAvStateMachine::kStateIdle; // Report the connection state to the application - btif_report_connection_state( - peer_.PeerAddress(), BTAV_CONNECTION_STATE_DISCONNECTED, - bt_status_t::BT_STATUS_FAIL, status, - peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); + btif_report_connection_state(peer_.PeerAddress(), BTAV_CONNECTION_STATE_DISCONNECTED, + bt_status_t::BT_STATUS_FAIL, status, + peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); log_counter_metrics_btif( - android::bluetooth::CodePathCounterKeyEnum::A2DP_CONNECTION_FAILURE, - 1); + android::bluetooth::CodePathCounterKeyEnum::A2DP_CONNECTION_FAILURE, 1); } // Change state to Open/Idle based on the status peer_.StateMachine().TransitionTo(av_state); if (peer_.IsSink()) { // If queued PLAY command, send it now - btif_rc_check_handle_pending_play( - p_bta_data->open.bd_addr, - (p_bta_data->open.status == BTA_AV_SUCCESS)); - } else if (peer_.IsSource() && - (p_bta_data->open.status == BTA_AV_SUCCESS)) { + btif_rc_check_handle_pending_play(p_bta_data->open.bd_addr, + (p_bta_data->open.status == BTA_AV_SUCCESS)); + } else if (peer_.IsSource() && (p_bta_data->open.status == BTA_AV_SUCCESS)) { // Bring up AVRCP connection as well if (btif_av_src_sink_coexist_enabled() && - btif_av_sink.AllowedToConnect(peer_.PeerAddress())) + btif_av_sink.AllowedToConnect(peer_.PeerAddress())) { BTA_AvOpenRc(peer_.BtaHandle()); + } } if (peer_.SelfInitiatedConnection()) { btif_queue_advance(); @@ -2297,18 +2249,16 @@ bool BtifAvStateMachine::StateOpening::ProcessEvent(uint32_t event, case BTIF_AV_SINK_CONFIG_REQ_EVT: { const btif_av_sink_config_req_t* p_config_req = - static_cast(p_data); + static_cast(p_data); /* before this point, we don't know it's role, actually peer is source */ if (btif_av_both_enable()) { - btif_av_report_sink_audio_config_state(p_config_req->peer_address, - p_config_req->sample_rate, - p_config_req->channel_count); + btif_av_report_sink_audio_config_state( + p_config_req->peer_address, p_config_req->sample_rate, p_config_req->channel_count); break; } if (peer_.IsSource()) { - btif_av_report_sink_audio_config_state(p_config_req->peer_address, - p_config_req->sample_rate, - p_config_req->channel_count); + btif_av_report_sink_audio_config_state( + p_config_req->peer_address, p_config_req->sample_rate, p_config_req->channel_count); } } break; @@ -2316,12 +2266,11 @@ bool BtifAvStateMachine::StateOpening::ProcessEvent(uint32_t event, // The device has moved already to Opening, hence don't report the // connection state. log::warn( - "Peer {} : event={} : device is already connecting, ignore Connect " - "request", - peer_.PeerAddress(), BtifAvEvent::EventName(event)); - log_counter_metrics_btif( - android::bluetooth::CodePathCounterKeyEnum::A2DP_ALREADY_CONNECTING, - 1); + "Peer {} : event={} : device is already connecting, ignore Connect " + "request", + peer_.PeerAddress(), BtifAvEvent::EventName(event)); + log_counter_metrics_btif(android::bluetooth::CodePathCounterKeyEnum::A2DP_ALREADY_CONNECTING, + 1); btif_queue_advance(); } break; @@ -2329,35 +2278,30 @@ bool BtifAvStateMachine::StateOpening::ProcessEvent(uint32_t event, // The device has moved already to Opening, hence don't report the // connection state. log::warn( - "Peer {} : event={} : device is already connecting, ignore incoming " - "request", - peer_.PeerAddress(), BtifAvEvent::EventName(event)); - log_counter_metrics_btif( - android::bluetooth::CodePathCounterKeyEnum::A2DP_ALREADY_CONNECTING, - 1); + "Peer {} : event={} : device is already connecting, ignore incoming " + "request", + peer_.PeerAddress(), BtifAvEvent::EventName(event)); + log_counter_metrics_btif(android::bluetooth::CodePathCounterKeyEnum::A2DP_ALREADY_CONNECTING, + 1); } break; case BTIF_AV_OFFLOAD_START_REQ_EVT: - log::error("Peer {} : event={}: stream is not Opened", - peer_.PeerAddress(), BtifAvEvent::EventName(event)); + log::error("Peer {} : event={}: stream is not Opened", peer_.PeerAddress(), + BtifAvEvent::EventName(event)); btif_a2dp_on_offload_started(peer_.PeerAddress(), BTA_AV_FAIL); - log_counter_metrics_btif(android::bluetooth::CodePathCounterKeyEnum:: - A2DP_OFFLOAD_START_REQ_FAILURE, - 1); + log_counter_metrics_btif( + android::bluetooth::CodePathCounterKeyEnum::A2DP_OFFLOAD_START_REQ_FAILURE, 1); break; case BTA_AV_CLOSE_EVT: - btif_a2dp_on_stopped( - nullptr, peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); - btif_report_connection_state( - peer_.PeerAddress(), BTAV_CONNECTION_STATE_DISCONNECTED, - bt_status_t::BT_STATUS_FAIL, BTA_AV_FAIL, - peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); + btif_a2dp_on_stopped(nullptr, peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); + btif_report_connection_state(peer_.PeerAddress(), BTAV_CONNECTION_STATE_DISCONNECTED, + bt_status_t::BT_STATUS_FAIL, BTA_AV_FAIL, + peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); peer_.StateMachine().TransitionTo(BtifAvStateMachine::kStateIdle); - log_counter_metrics_btif( - android::bluetooth::CodePathCounterKeyEnum::A2DP_CONNECTION_CLOSE, 1); - DEVICE_IOT_CONFIG_ADDR_INT_ADD_ONE(peer_.PeerAddress(), - IOT_CONF_KEY_A2DP_CONN_FAIL_COUNT); + log_counter_metrics_btif(android::bluetooth::CodePathCounterKeyEnum::A2DP_CONNECTION_CLOSE, + 1); + DEVICE_IOT_CONFIG_ADDR_INT_ADD_ONE(peer_.PeerAddress(), IOT_CONF_KEY_A2DP_CONN_FAIL_COUNT); if (peer_.SelfInitiatedConnection()) { btif_queue_advance(); } @@ -2365,16 +2309,13 @@ bool BtifAvStateMachine::StateOpening::ProcessEvent(uint32_t event, case BTIF_AV_DISCONNECT_REQ_EVT: BTA_AvClose(peer_.BtaHandle()); - btif_report_connection_state( - peer_.PeerAddress(), BTAV_CONNECTION_STATE_DISCONNECTED, - bt_status_t::BT_STATUS_FAIL, BTA_AV_FAIL, - peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); + btif_report_connection_state(peer_.PeerAddress(), BTAV_CONNECTION_STATE_DISCONNECTED, + bt_status_t::BT_STATUS_FAIL, BTA_AV_FAIL, + peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); peer_.StateMachine().TransitionTo(BtifAvStateMachine::kStateIdle); - DEVICE_IOT_CONFIG_ADDR_INT_ADD_ONE(peer_.PeerAddress(), - IOT_CONF_KEY_A2DP_CONN_FAIL_COUNT); - log_counter_metrics_btif(android::bluetooth::CodePathCounterKeyEnum:: - A2DP_CONNECTION_DISCONNECTED, - 1); + DEVICE_IOT_CONFIG_ADDR_INT_ADD_ONE(peer_.PeerAddress(), IOT_CONF_KEY_A2DP_CONN_FAIL_COUNT); + log_counter_metrics_btif( + android::bluetooth::CodePathCounterKeyEnum::A2DP_CONNECTION_DISCONNECTED, 1); if (peer_.SelfInitiatedConnection()) { btif_queue_advance(); } @@ -2383,11 +2324,9 @@ bool BtifAvStateMachine::StateOpening::ProcessEvent(uint32_t event, CHECK_RC_EVENT(event, reinterpret_cast(p_data)); default: - log_counter_metrics_btif(android::bluetooth::CodePathCounterKeyEnum:: - A2DP_CONNECTION_UNKNOWN_EVENT, - 1); - log::warn("Peer {} : Unhandled event={}", peer_.PeerAddress(), - BtifAvEvent::EventName(event)); + log_counter_metrics_btif( + android::bluetooth::CodePathCounterKeyEnum::A2DP_CONNECTION_UNKNOWN_EVENT, 1); + log::warn("Peer {} : Unhandled event={}", peer_.PeerAddress(), BtifAvEvent::EventName(event)); return false; } return true; @@ -2396,8 +2335,7 @@ bool BtifAvStateMachine::StateOpening::ProcessEvent(uint32_t event, void BtifAvStateMachine::StateOpened::OnEnter() { log::info("state=Opened peer={}", peer_.PeerAddress()); - peer_.ClearFlags(BtifAvPeer::kFlagLocalSuspendPending | - BtifAvPeer::kFlagPendingStart | + peer_.ClearFlags(BtifAvPeer::kFlagLocalSuspendPending | BtifAvPeer::kFlagPendingStart | BtifAvPeer::kFlagPendingStop); // Set the active peer if the first connected device. @@ -2407,8 +2345,7 @@ void BtifAvStateMachine::StateOpened::OnEnter() { // ActiveDeviceManager in Java. if (peer_.IsSource() && btif_av_sink.ActivePeer().IsEmpty()) { std::promise peer_ready_promise; - if (!btif_av_sink.SetActivePeer(peer_.PeerAddress(), - std::move(peer_ready_promise))) { + if (!btif_av_sink.SetActivePeer(peer_.PeerAddress(), std::move(peer_ready_promise))) { log::error("Error setting {} as active Source peer", peer_.PeerAddress()); } } @@ -2420,19 +2357,15 @@ void BtifAvStateMachine::StateOpened::OnExit() { peer_.ClearFlags(BtifAvPeer::kFlagPendingStart); } -bool BtifAvStateMachine::StateOpened::ProcessEvent(uint32_t event, - void* p_data) { +bool BtifAvStateMachine::StateOpened::ProcessEvent(uint32_t event, void* p_data) { tBTA_AV* p_av = reinterpret_cast(p_data); - log::info("state=Opened peer={} event={} flags={} active_peer={}", - peer_.PeerAddress(), BtifAvEvent::EventName(event), - peer_.FlagsToString(), peer_.IsActivePeer()); + log::info("state=Opened peer={} event={} flags={} active_peer={}", peer_.PeerAddress(), + BtifAvEvent::EventName(event), peer_.FlagsToString(), peer_.IsActivePeer()); - if ((event == BTA_AV_REMOTE_CMD_EVT) && - peer_.CheckFlags(BtifAvPeer::kFlagRemoteSuspend) && + if ((event == BTA_AV_REMOTE_CMD_EVT) && peer_.CheckFlags(BtifAvPeer::kFlagRemoteSuspend) && (p_av->remote_cmd.rc_id == AVRC_ID_PLAY)) { - log::verbose("Peer {} : Resetting remote suspend flag on RC PLAY", - peer_.PeerAddress()); + log::verbose("Peer {} : Resetting remote suspend flag on RC PLAY", peer_.PeerAddress()); peer_.ClearFlags(BtifAvPeer::kFlagRemoteSuspend); } @@ -2446,13 +2379,12 @@ bool BtifAvStateMachine::StateOpened::ProcessEvent(uint32_t event, // when a stream is ready to play. The stack shall send AVDTP Start to the // remote device to start the stream. case BTIF_AV_START_STREAM_REQ_EVT: { - log::info("Peer {} : event={} flags={}", peer_.PeerAddress(), - BtifAvEvent::EventName(event), peer_.FlagsToString()); + log::info("Peer {} : event={} flags={}", peer_.PeerAddress(), BtifAvEvent::EventName(event), + peer_.FlagsToString()); if (p_data) { const btif_av_start_stream_req_t* p_start_steam_req = - static_cast(p_data); - log::info("Stream use_latency_mode={}", - p_start_steam_req->use_latency_mode); + static_cast(p_data); + log::info("Stream use_latency_mode={}", p_start_steam_req->use_latency_mode); peer_.SetUseLatencyMode(p_start_steam_req->use_latency_mode); } @@ -2465,36 +2397,31 @@ bool BtifAvStateMachine::StateOpened::ProcessEvent(uint32_t event, // event is ignored by source A2DP, and the stack shall immediately suspend // the stream. case BTA_AV_START_EVT: { - log::info( - "Peer {} : event={} status={} suspending={} initiator={} flags={}", - peer_.PeerAddress(), BtifAvEvent::EventName(event), - p_av->start.status, p_av->start.suspending, p_av->start.initiator, - peer_.FlagsToString()); + log::info("Peer {} : event={} status={} suspending={} initiator={} flags={}", + peer_.PeerAddress(), BtifAvEvent::EventName(event), p_av->start.status, + p_av->start.suspending, p_av->start.initiator, peer_.FlagsToString()); - if ((p_av->start.status == BTA_SUCCESS) && p_av->start.suspending) + if ((p_av->start.status == BTA_SUCCESS) && p_av->start.suspending) { return true; + } // If remote tries to start A2DP when DUT is A2DP Source, then Suspend. // If A2DP is Sink and call is active, then disconnect the AVDTP // channel. bool should_suspend = false; if (peer_.IsSink()) { - if (!peer_.CheckFlags(BtifAvPeer::kFlagPendingStart | - BtifAvPeer::kFlagRemoteSuspend)) { - log::warn("Peer {} : trigger Suspend as remote initiated", - peer_.PeerAddress()); + if (!peer_.CheckFlags(BtifAvPeer::kFlagPendingStart | BtifAvPeer::kFlagRemoteSuspend)) { + log::warn("Peer {} : trigger Suspend as remote initiated", peer_.PeerAddress()); should_suspend = true; } else if (!peer_.IsActivePeer()) { - log::warn("Peer {} : trigger Suspend as non-active", - peer_.PeerAddress()); + log::warn("Peer {} : trigger Suspend as non-active", peer_.PeerAddress()); should_suspend = true; } // Invoke the started handler only when initiator. if (!com::android::bluetooth::flags::a2dp_ignore_started_when_responder() || peer_.CheckFlags(BtifAvPeer::kFlagPendingStart)) { - if (btif_a2dp_on_started( - peer_.PeerAddress(), &p_av->start, A2dpType::kSource)) { + if (btif_a2dp_on_started(peer_.PeerAddress(), &p_av->start, A2dpType::kSource)) { // Only clear pending flag after acknowledgement peer_.ClearFlags(BtifAvPeer::kFlagPendingStart); } @@ -2502,7 +2429,9 @@ bool BtifAvStateMachine::StateOpened::ProcessEvent(uint32_t event, } // Remain in Open state if status failed - if (p_av->start.status != BTA_AV_SUCCESS) return false; + if (p_av->start.status != BTA_AV_SUCCESS) { + return false; + } if (peer_.IsSource() && peer_.IsActivePeer()) { // Remove flush state, ready for streaming @@ -2511,8 +2440,7 @@ bool BtifAvStateMachine::StateOpened::ProcessEvent(uint32_t event, } if (should_suspend) { - btif_av_source_dispatch_sm_event(peer_.PeerAddress(), - BTIF_AV_SUSPEND_STREAM_REQ_EVT); + btif_av_source_dispatch_sm_event(peer_.PeerAddress(), BTIF_AV_SUSPEND_STREAM_REQ_EVT); } peer_.StateMachine().TransitionTo(BtifAvStateMachine::kStateStarted); break; @@ -2525,10 +2453,9 @@ bool BtifAvStateMachine::StateOpened::ProcessEvent(uint32_t event, } // Inform the application that we are disconnecting - btif_report_connection_state( - peer_.PeerAddress(), BTAV_CONNECTION_STATE_DISCONNECTING, - bt_status_t::BT_STATUS_SUCCESS, BTA_AV_SUCCESS, - peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); + btif_report_connection_state(peer_.PeerAddress(), BTAV_CONNECTION_STATE_DISCONNECTING, + bt_status_t::BT_STATUS_SUCCESS, BTA_AV_SUCCESS, + peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); // Wait in closing state until fully closed peer_.StateMachine().TransitionTo(BtifAvStateMachine::kStateClosing); @@ -2537,33 +2464,28 @@ bool BtifAvStateMachine::StateOpened::ProcessEvent(uint32_t event, case BTA_AV_CLOSE_EVT: // AVDTP link is closed // Inform the application that we are disconnecting - btif_report_connection_state( - peer_.PeerAddress(), BTAV_CONNECTION_STATE_DISCONNECTING, - bt_status_t::BT_STATUS_SUCCESS, BTA_AV_SUCCESS, - peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); + btif_report_connection_state(peer_.PeerAddress(), BTAV_CONNECTION_STATE_DISCONNECTING, + bt_status_t::BT_STATUS_SUCCESS, BTA_AV_SUCCESS, + peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); // Change state to Idle, send acknowledgement if start is pending if (peer_.CheckFlags(BtifAvPeer::kFlagPendingStart)) { - log::warn("Peer {} : failed pending start request", - peer_.PeerAddress()); + log::warn("Peer {} : failed pending start request", peer_.PeerAddress()); tBTA_AV_START av_start = {.chnl = p_av->close.chnl, .hndl = p_av->close.hndl, .status = BTA_AV_FAIL_STREAM, .initiator = true, .suspending = true}; - btif_a2dp_on_started( - peer_.PeerAddress(), &av_start, - peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); + btif_a2dp_on_started(peer_.PeerAddress(), &av_start, + peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); // Pending start flag will be cleared when exit current state } else if (peer_.IsActivePeer()) { - btif_a2dp_on_stopped( - nullptr, peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); + btif_a2dp_on_stopped(nullptr, peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); } // Inform the application that we are disconnected - btif_report_connection_state( - peer_.PeerAddress(), BTAV_CONNECTION_STATE_DISCONNECTED, - bt_status_t::BT_STATUS_SUCCESS, BTA_AV_SUCCESS, - peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); + btif_report_connection_state(peer_.PeerAddress(), BTAV_CONNECTION_STATE_DISCONNECTED, + bt_status_t::BT_STATUS_SUCCESS, BTA_AV_SUCCESS, + peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); peer_.StateMachine().TransitionTo(BtifAvStateMachine::kStateIdle); break; @@ -2571,8 +2493,7 @@ bool BtifAvStateMachine::StateOpened::ProcessEvent(uint32_t event, if (p_av->reconfig.status != BTA_AV_SUCCESS) { log::warn("Peer {} : failed reconfiguration", peer_.PeerAddress()); if (peer_.CheckFlags(BtifAvPeer::kFlagPendingStart)) { - log::error("Peer {} : cannot proceed to do AvStart", - peer_.PeerAddress()); + log::error("Peer {} : cannot proceed to do AvStart", peer_.PeerAddress()); peer_.ClearFlags(BtifAvPeer::kFlagPendingStart); bluetooth::audio::a2dp::ack_stream_started( bluetooth::audio::a2dp::BluetoothAudioStatus::FAILURE); @@ -2586,17 +2507,15 @@ bool BtifAvStateMachine::StateOpened::ProcessEvent(uint32_t event, } if (peer_.IsActivePeer()) { - log::info( - "Peer {} : Reconfig done - calling startSession() to audio HAL", - peer_.PeerAddress()); + log::info("Peer {} : Reconfig done - calling startSession() to audio HAL", + peer_.PeerAddress()); std::promise peer_ready_promise; std::future peer_ready_future = peer_ready_promise.get_future(); - btif_a2dp_source_start_session(peer_.PeerAddress(), - std::move(peer_ready_promise)); + btif_a2dp_source_start_session(peer_.PeerAddress(), std::move(peer_ready_promise)); } if (peer_.CheckFlags(BtifAvPeer::kFlagPendingStart)) { - log::info("Peer {} : Reconfig done - calling BTA_AvStart(0x{:x})", - peer_.PeerAddress(), peer_.BtaHandle()); + log::info("Peer {} : Reconfig done - calling BTA_AvStart(0x{:x})", peer_.PeerAddress(), + peer_.BtaHandle()); BTA_AvStart(peer_.BtaHandle(), peer_.UseLatencyMode()); } break; @@ -2608,15 +2527,14 @@ bool BtifAvStateMachine::StateOpened::ProcessEvent(uint32_t event, } break; case BTIF_AV_OFFLOAD_START_REQ_EVT: - log::error("Peer {} : event={}: stream is not Started", - peer_.PeerAddress(), BtifAvEvent::EventName(event)); + log::error("Peer {} : event={}: stream is not Started", peer_.PeerAddress(), + BtifAvEvent::EventName(event)); btif_a2dp_on_offload_started(peer_.PeerAddress(), BTA_AV_FAIL); break; case BTIF_AV_AVRCP_REMOTE_PLAY_EVT: if (peer_.CheckFlags(BtifAvPeer::kFlagRemoteSuspend)) { - log::verbose("Peer {} : Resetting remote suspend flag on RC PLAY", - peer_.PeerAddress()); + log::verbose("Peer {} : Resetting remote suspend flag on RC PLAY", peer_.PeerAddress()); peer_.ClearFlags(BtifAvPeer::kFlagRemoteSuspend); } break; @@ -2625,17 +2543,16 @@ bool BtifAvStateMachine::StateOpened::ProcessEvent(uint32_t event, case BTIF_AV_SET_LATENCY_REQ_EVT: { const btif_av_set_latency_req_t* p_set_latency_req = - static_cast(p_data); - log::info("Peer {} : event={} flags={} is_low_latency={}", - peer_.PeerAddress(), BtifAvEvent::EventName(event), - peer_.FlagsToString(), p_set_latency_req->is_low_latency); + static_cast(p_data); + log::info("Peer {} : event={} flags={} is_low_latency={}", peer_.PeerAddress(), + BtifAvEvent::EventName(event), peer_.FlagsToString(), + p_set_latency_req->is_low_latency); BTA_AvSetLatency(peer_.BtaHandle(), p_set_latency_req->is_low_latency); } break; default: - log::warn("Peer {} : Unhandled event={}", peer_.PeerAddress(), - BtifAvEvent::EventName(event)); + log::warn("Peer {} : Unhandled event={}", peer_.PeerAddress(), BtifAvEvent::EventName(event)); return false; } return true; @@ -2651,42 +2568,39 @@ void BtifAvStateMachine::StateStarted::OnEnter() { // Report that we have entered the Streaming stage. Usually, this should // be followed by focus grant. See set_audio_focus_state() - btif_report_audio_state( - peer_.PeerAddress(), BTAV_AUDIO_STATE_STARTED, - peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); + btif_report_audio_state(peer_.PeerAddress(), BTAV_AUDIO_STATE_STARTED, + peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); } void BtifAvStateMachine::StateStarted::OnExit() { log::info("state=Started peer={}", peer_.PeerAddress()); } -bool BtifAvStateMachine::StateStarted::ProcessEvent(uint32_t event, - void* p_data) { +bool BtifAvStateMachine::StateStarted::ProcessEvent(uint32_t event, void* p_data) { tBTA_AV* p_av = reinterpret_cast(p_data); - log::info("state=Started peer={} event={} flags={} active_peer={}", - peer_.PeerAddress(), BtifAvEvent::EventName(event), - peer_.FlagsToString(), peer_.IsActivePeer()); + log::info("state=Started peer={} event={} flags={} active_peer={}", peer_.PeerAddress(), + BtifAvEvent::EventName(event), peer_.FlagsToString(), peer_.IsActivePeer()); switch (event) { case BTIF_AV_ACL_DISCONNECTED: break; // Ignore case BTIF_AV_START_STREAM_REQ_EVT: - log::info("Peer {} : event={} flags={}", peer_.PeerAddress(), - BtifAvEvent::EventName(event), peer_.FlagsToString()); + log::info("Peer {} : event={} flags={}", peer_.PeerAddress(), BtifAvEvent::EventName(event), + peer_.FlagsToString()); // We were started remotely, just ACK back the local request - if (peer_.IsSink()) - btif_a2dp_on_started( - peer_.PeerAddress(), nullptr, - peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); + if (peer_.IsSink()) { + btif_a2dp_on_started(peer_.PeerAddress(), nullptr, + peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); + } break; // FIXME -- use suspend = true always to work around issue with BTA AV case BTIF_AV_STOP_STREAM_REQ_EVT: case BTIF_AV_SUSPEND_STREAM_REQ_EVT: - log::info("Peer {} : event={} flags={}", peer_.PeerAddress(), - BtifAvEvent::EventName(event), peer_.FlagsToString()); + log::info("Peer {} : event={} flags={}", peer_.PeerAddress(), BtifAvEvent::EventName(event), + peer_.FlagsToString()); // There is a pending LocalSuspend already, ignore. if (peer_.CheckFlags(BtifAvPeer::kFlagLocalSuspendPending)) { @@ -2702,26 +2616,23 @@ bool BtifAvStateMachine::StateStarted::ProcessEvent(uint32_t event, peer_.ClearFlags(BtifAvPeer::kFlagRemoteSuspend); if (peer_.IsSink() && - (peer_.IsActivePeer() || - !btif_av_stream_started_ready(A2dpType::kSource))) { + (peer_.IsActivePeer() || !btif_av_stream_started_ready(A2dpType::kSource))) { // Immediately stop transmission of frames while suspend is pending if (event == BTIF_AV_STOP_STREAM_REQ_EVT) { - btif_a2dp_on_stopped( - nullptr, peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); + btif_a2dp_on_stopped(nullptr, peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); } else { // ensure tx frames are immediately suspended btif_a2dp_source_set_tx_flush(true); } } else if (peer_.IsSource()) { - btif_a2dp_on_stopped( - nullptr, peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); + btif_a2dp_on_stopped(nullptr, peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); } BTA_AvStop(peer_.BtaHandle(), true); break; case BTIF_AV_DISCONNECT_REQ_EVT: - log::info("Peer {} : event={} flags={}", peer_.PeerAddress(), - BtifAvEvent::EventName(event), peer_.FlagsToString()); + log::info("Peer {} : event={} flags={}", peer_.PeerAddress(), BtifAvEvent::EventName(event), + peer_.FlagsToString()); // Request AVDTP to close BTA_AvClose(peer_.BtaHandle()); @@ -2730,28 +2641,24 @@ bool BtifAvStateMachine::StateStarted::ProcessEvent(uint32_t event, } // Inform the application that we are disconnecting - btif_report_connection_state( - peer_.PeerAddress(), BTAV_CONNECTION_STATE_DISCONNECTING, - bt_status_t::BT_STATUS_SUCCESS, BTA_AV_SUCCESS, - peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); + btif_report_connection_state(peer_.PeerAddress(), BTAV_CONNECTION_STATE_DISCONNECTING, + bt_status_t::BT_STATUS_SUCCESS, BTA_AV_SUCCESS, + peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); // Wait in closing state until fully closed peer_.StateMachine().TransitionTo(BtifAvStateMachine::kStateClosing); break; case BTA_AV_SUSPEND_EVT: { - log::info("Peer {} : event={} status={} initiator={} flags={}", - peer_.PeerAddress(), BtifAvEvent::EventName(event), - p_av->suspend.status, p_av->suspend.initiator, + log::info("Peer {} : event={} status={} initiator={} flags={}", peer_.PeerAddress(), + BtifAvEvent::EventName(event), p_av->suspend.status, p_av->suspend.initiator, peer_.FlagsToString()); // A2DP suspended, stop A2DP encoder / decoder until resumed if (peer_.IsActivePeer() || - !btif_av_stream_started_ready(peer_.IsSource() ? A2dpType::kSink - : A2dpType::kSource)) { - btif_a2dp_on_suspended(&p_av->suspend, peer_.IsSource() - ? A2dpType::kSink - : A2dpType::kSource); + !btif_av_stream_started_ready(peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource)) { + btif_a2dp_on_suspended(&p_av->suspend, + peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); } // If not successful, remain in current state @@ -2772,22 +2679,22 @@ bool BtifAvStateMachine::StateStarted::ProcessEvent(uint32_t event, // // Set remote suspend flag to block media task from restarting // stream only if we did not already initiate a local suspend. - if (!peer_.CheckFlags(BtifAvPeer::kFlagLocalSuspendPending)) + if (!peer_.CheckFlags(BtifAvPeer::kFlagLocalSuspendPending)) { peer_.SetFlags(BtifAvPeer::kFlagRemoteSuspend); + } } else { state = BTAV_AUDIO_STATE_STOPPED; } - btif_report_audio_state( - peer_.PeerAddress(), state, - peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); + btif_report_audio_state(peer_.PeerAddress(), state, + peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); // Suspend completed, clear local pending flags while entering Opened peer_.StateMachine().TransitionTo(BtifAvStateMachine::kStateOpened); } break; case BTA_AV_STOP_EVT: - log::info("Peer {} : event={} flags={}", peer_.PeerAddress(), - BtifAvEvent::EventName(event), peer_.FlagsToString()); + log::info("Peer {} : event={} flags={}", peer_.PeerAddress(), BtifAvEvent::EventName(event), + peer_.FlagsToString()); peer_.SetFlags(BtifAvPeer::kFlagPendingStop); peer_.ClearFlags(BtifAvPeer::kFlagLocalSuspendPending); @@ -2795,56 +2702,49 @@ bool BtifAvStateMachine::StateStarted::ProcessEvent(uint32_t event, // Don't change the encoder and audio provider state by a non-active // peer since they are shared between peers if (peer_.IsActivePeer() || - !btif_av_stream_started_ready(peer_.IsSource() ? A2dpType::kSink - : A2dpType::kSource)) { - btif_a2dp_on_stopped(&p_av->suspend, peer_.IsSource() - ? A2dpType::kSink - : A2dpType::kSource); + !btif_av_stream_started_ready(peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource)) { + btif_a2dp_on_stopped(&p_av->suspend, + peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); } - btif_report_audio_state( - peer_.PeerAddress(), BTAV_AUDIO_STATE_STOPPED, - peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); + btif_report_audio_state(peer_.PeerAddress(), BTAV_AUDIO_STATE_STOPPED, + peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); // If stop was successful, change state to Open - if (p_av->suspend.status == BTA_AV_SUCCESS) + if (p_av->suspend.status == BTA_AV_SUCCESS) { peer_.StateMachine().TransitionTo(BtifAvStateMachine::kStateOpened); + } break; case BTA_AV_CLOSE_EVT: - log::info("Peer {} : event={} flags={}", peer_.PeerAddress(), - BtifAvEvent::EventName(event), peer_.FlagsToString()); + log::info("Peer {} : event={} flags={}", peer_.PeerAddress(), BtifAvEvent::EventName(event), + peer_.FlagsToString()); // Inform the application that we are disconnecting - btif_report_connection_state( - peer_.PeerAddress(), BTAV_CONNECTION_STATE_DISCONNECTING, - bt_status_t::BT_STATUS_SUCCESS, BTA_AV_SUCCESS, - peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); + btif_report_connection_state(peer_.PeerAddress(), BTAV_CONNECTION_STATE_DISCONNECTING, + bt_status_t::BT_STATUS_SUCCESS, BTA_AV_SUCCESS, + peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); peer_.SetFlags(BtifAvPeer::kFlagPendingStop); // AVDTP link is closed if (peer_.IsActivePeer()) { - btif_a2dp_on_stopped( - nullptr, peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); + btif_a2dp_on_stopped(nullptr, peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); } // Inform the application that we are disconnected - btif_report_connection_state( - peer_.PeerAddress(), BTAV_CONNECTION_STATE_DISCONNECTED, - bt_status_t::BT_STATUS_SUCCESS, BTA_AV_SUCCESS, - peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); + btif_report_connection_state(peer_.PeerAddress(), BTAV_CONNECTION_STATE_DISCONNECTED, + bt_status_t::BT_STATUS_SUCCESS, BTA_AV_SUCCESS, + peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); peer_.StateMachine().TransitionTo(BtifAvStateMachine::kStateIdle); break; case BTIF_AV_OFFLOAD_START_REQ_EVT: - if (peer_.CheckFlags(BtifAvPeer::kFlagLocalSuspendPending | - BtifAvPeer::kFlagRemoteSuspend | + if (peer_.CheckFlags(BtifAvPeer::kFlagLocalSuspendPending | BtifAvPeer::kFlagRemoteSuspend | BtifAvPeer::kFlagPendingStop)) { - log::warn("Peer {} : event={} flags={}: stream is Suspending", - peer_.PeerAddress(), BtifAvEvent::EventName(event), - peer_.FlagsToString()); + log::warn("Peer {} : event={} flags={}: stream is Suspending", peer_.PeerAddress(), + BtifAvEvent::EventName(event), peer_.FlagsToString()); btif_a2dp_on_offload_started(peer_.PeerAddress(), BTA_AV_FAIL); break; } @@ -2857,10 +2757,10 @@ bool BtifAvStateMachine::StateStarted::ProcessEvent(uint32_t event, case BTIF_AV_SET_LATENCY_REQ_EVT: { const btif_av_set_latency_req_t* p_set_latency_req = - static_cast(p_data); - log::info("Peer {} : event={} flags={} is_low_latency={}", - peer_.PeerAddress(), BtifAvEvent::EventName(event), - peer_.FlagsToString(), p_set_latency_req->is_low_latency); + static_cast(p_data); + log::info("Peer {} : event={} flags={} is_low_latency={}", peer_.PeerAddress(), + BtifAvEvent::EventName(event), peer_.FlagsToString(), + p_set_latency_req->is_low_latency); BTA_AvSetLatency(peer_.BtaHandle(), p_set_latency_req->is_low_latency); } break; @@ -2868,8 +2768,7 @@ bool BtifAvStateMachine::StateStarted::ProcessEvent(uint32_t event, CHECK_RC_EVENT(event, reinterpret_cast(p_data)); default: - log::warn("Peer {} : Unhandled event={}", peer_.PeerAddress(), - BtifAvEvent::EventName(event)); + log::warn("Peer {} : Unhandled event={}", peer_.PeerAddress(), BtifAvEvent::EventName(event)); return false; } @@ -2894,11 +2793,9 @@ void BtifAvStateMachine::StateClosing::OnExit() { log::info("state=Closing peer={}", peer_.PeerAddress()); } -bool BtifAvStateMachine::StateClosing::ProcessEvent(uint32_t event, - void* p_data) { - log::info("state=Closing peer={} event={} flags={} active_peer={}", - peer_.PeerAddress(), BtifAvEvent::EventName(event), - peer_.FlagsToString(), peer_.IsActivePeer()); +bool BtifAvStateMachine::StateClosing::ProcessEvent(uint32_t event, void* p_data) { + log::info("state=Closing peer={} event={} flags={} active_peer={}", peer_.PeerAddress(), + BtifAvEvent::EventName(event), peer_.FlagsToString(), peer_.IsActivePeer()); switch (event) { case BTIF_AV_SUSPEND_STREAM_REQ_EVT: @@ -2908,17 +2805,15 @@ bool BtifAvStateMachine::StateClosing::ProcessEvent(uint32_t event, case BTA_AV_STOP_EVT: case BTIF_AV_STOP_STREAM_REQ_EVT: if (peer_.IsActivePeer()) { - btif_a2dp_on_stopped( - nullptr, peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); + btif_a2dp_on_stopped(nullptr, peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); } break; case BTA_AV_CLOSE_EVT: // Inform the application that we are disconnecting - btif_report_connection_state( - peer_.PeerAddress(), BTAV_CONNECTION_STATE_DISCONNECTED, - bt_status_t::BT_STATUS_SUCCESS, BTA_AV_SUCCESS, - peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); + btif_report_connection_state(peer_.PeerAddress(), BTAV_CONNECTION_STATE_DISCONNECTED, + bt_status_t::BT_STATUS_SUCCESS, BTA_AV_SUCCESS, + peer_.IsSource() ? A2dpType::kSink : A2dpType::kSource); peer_.StateMachine().TransitionTo(BtifAvStateMachine::kStateIdle); break; @@ -2934,8 +2829,8 @@ bool BtifAvStateMachine::StateClosing::ProcessEvent(uint32_t event, break; case BTIF_AV_OFFLOAD_START_REQ_EVT: - log::error("Peer {} : event={}: stream is not Opened", - peer_.PeerAddress(), BtifAvEvent::EventName(event)); + log::error("Peer {} : event={}: stream is not Opened", peer_.PeerAddress(), + BtifAvEvent::EventName(event)); btif_a2dp_on_offload_started(peer_.PeerAddress(), BTA_AV_FAIL); break; @@ -2947,8 +2842,7 @@ bool BtifAvStateMachine::StateClosing::ProcessEvent(uint32_t event, break; default: - log::warn("Peer {} : Unhandled event={}", peer_.PeerAddress(), - BtifAvEvent::EventName(event)); + log::warn("Peer {} : Unhandled event={}", peer_.PeerAddress(), BtifAvEvent::EventName(event)); return false; } return true; @@ -2963,13 +2857,11 @@ static void btif_av_source_initiate_av_open_timer_timeout(void* data) { BtifAvPeer* peer = reinterpret_cast(data); bool device_connected = false; - if (com::android::bluetooth::flags::avrcp_connect_a2dp_delayed() && - is_new_avrcp_enabled()) { + if (com::android::bluetooth::flags::avrcp_connect_a2dp_delayed() && is_new_avrcp_enabled()) { // check if device is connected if (bluetooth::avrcp::AvrcpService::Get() != nullptr) { device_connected = - bluetooth::avrcp::AvrcpService::Get()->IsDeviceConnected( - peer->PeerAddress()); + bluetooth::avrcp::AvrcpService::Get()->IsDeviceConnected(peer->PeerAddress()); } } else { device_connected = btif_rc_is_connected_peer(peer->PeerAddress()); @@ -2984,11 +2876,9 @@ static void btif_av_source_initiate_av_open_timer_timeout(void* data) { } // Connect to the AVRCP peer - if (btif_av_source.Enabled() && - btif_av_source.FindPeer(peer->PeerAddress()) == peer) { + if (btif_av_source.Enabled() && btif_av_source.FindPeer(peer->PeerAddress()) == peer) { log::verbose("Connecting to AVRCP peer {}", peer->PeerAddress()); - btif_av_source_dispatch_sm_event(peer->PeerAddress(), - BTIF_AV_CONNECT_REQ_EVT); + btif_av_source_dispatch_sm_event(peer->PeerAddress(), BTIF_AV_CONNECT_REQ_EVT); } } @@ -3008,11 +2898,9 @@ static void btif_av_sink_initiate_av_open_timer_timeout(void* data) { } // Connect to the AVRCP peer - if (btif_av_sink.Enabled() && - btif_av_sink.FindPeer(peer->PeerAddress()) == peer) { + if (btif_av_sink.Enabled() && btif_av_sink.FindPeer(peer->PeerAddress()) == peer) { log::verbose("Connecting to AVRCP peer {}", peer->PeerAddress()); - btif_av_sink_dispatch_sm_event(peer->PeerAddress(), - BTIF_AV_CONNECT_REQ_EVT); + btif_av_sink_dispatch_sm_event(peer->PeerAddress(), BTIF_AV_CONNECT_REQ_EVT); } } @@ -3023,9 +2911,8 @@ static void btif_av_sink_initiate_av_open_timer_timeout(void* data) { * @param state the connection state */ static void btif_report_connection_state(const RawAddress& peer_address, - btav_connection_state_t state, - bt_status_t status, uint8_t error_code, - const A2dpType local_a2dp_type) { + btav_connection_state_t state, bt_status_t status, + uint8_t error_code, const A2dpType local_a2dp_type) { log::info("peer={} state={}", peer_address, state); if (btif_av_src_sink_coexist_enabled() && btif_av_both_enable()) { BtifAvPeer* peer = btif_av_find_peer(peer_address, local_a2dp_type); @@ -3035,25 +2922,23 @@ static void btif_report_connection_state(const RawAddress& peer_address, } if (peer->IsSink()) { - do_in_jni_thread( - base::BindOnce(btif_av_source.Callbacks()->connection_state_cb, - peer_address, state, btav_error_t{})); + do_in_jni_thread(base::BindOnce(btif_av_source.Callbacks()->connection_state_cb, peer_address, + state, btav_error_t{})); } else if (peer->IsSource()) { - do_in_jni_thread( - base::BindOnce(btif_av_sink.Callbacks()->connection_state_cb, - peer_address, state, btav_error_t{})); + do_in_jni_thread(base::BindOnce(btif_av_sink.Callbacks()->connection_state_cb, peer_address, + state, btav_error_t{})); } return; } if (btif_av_source.Enabled()) { - do_in_jni_thread(base::BindOnce( - btif_av_source.Callbacks()->connection_state_cb, peer_address, state, - btav_error_t{.status = status, .error_code = error_code})); + do_in_jni_thread(base::BindOnce(btif_av_source.Callbacks()->connection_state_cb, peer_address, + state, + btav_error_t{.status = status, .error_code = error_code})); } else if (btif_av_sink.Enabled()) { - do_in_jni_thread(base::BindOnce( - btif_av_sink.Callbacks()->connection_state_cb, peer_address, state, - btav_error_t{.status = status, .error_code = error_code})); + do_in_jni_thread(base::BindOnce(btif_av_sink.Callbacks()->connection_state_cb, peer_address, + state, + btav_error_t{.status = status, .error_code = error_code})); } } @@ -3066,28 +2951,26 @@ static void btif_report_connection_state(const RawAddress& peer_address, * @param peer_address the peer address * @param state the audio state */ -static void btif_report_audio_state(const RawAddress& peer_address, - btav_audio_state_t state, +static void btif_report_audio_state(const RawAddress& peer_address, btav_audio_state_t state, const A2dpType local_a2dp_type) { log::info("peer={} state={}", peer_address, state); if (btif_av_both_enable()) { BtifAvPeer* peer = btif_av_find_peer(peer_address, local_a2dp_type); if (peer->IsSink()) { - do_in_jni_thread(base::BindOnce( - btif_av_source.Callbacks()->audio_state_cb, peer_address, state)); + do_in_jni_thread( + base::BindOnce(btif_av_source.Callbacks()->audio_state_cb, peer_address, state)); } else if (peer->IsSource()) { - do_in_jni_thread(base::BindOnce(btif_av_sink.Callbacks()->audio_state_cb, - peer_address, state)); + do_in_jni_thread( + base::BindOnce(btif_av_sink.Callbacks()->audio_state_cb, peer_address, state)); } return; } if (btif_av_source.Enabled()) { - do_in_jni_thread(base::BindOnce(btif_av_source.Callbacks()->audio_state_cb, - peer_address, state)); + do_in_jni_thread( + base::BindOnce(btif_av_source.Callbacks()->audio_state_cb, peer_address, state)); } else if (btif_av_sink.Enabled()) { - do_in_jni_thread(base::BindOnce(btif_av_sink.Callbacks()->audio_state_cb, - peer_address, state)); + do_in_jni_thread(base::BindOnce(btif_av_sink.Callbacks()->audio_state_cb, peer_address, state)); } using android::bluetooth::a2dp::AudioCodingModeEnum; @@ -3103,25 +2986,22 @@ static void btif_report_audio_state(const RawAddress& peer_address, default: break; } - AudioCodingModeEnum audio_coding_mode = - btif_av_is_a2dp_offload_running() - ? AudioCodingModeEnum::AUDIO_CODING_MODE_HARDWARE - : AudioCodingModeEnum::AUDIO_CODING_MODE_SOFTWARE; + AudioCodingModeEnum audio_coding_mode = btif_av_is_a2dp_offload_running() + ? AudioCodingModeEnum::AUDIO_CODING_MODE_HARDWARE + : AudioCodingModeEnum::AUDIO_CODING_MODE_SOFTWARE; log_a2dp_playback_event(peer_address, playback_state, audio_coding_mode); } void btif_av_report_source_codec_state( - const RawAddress& peer_address, - const btav_a2dp_codec_config_t& codec_config, - const std::vector& codecs_local_capabilities, - const std::vector& - codecs_selectable_capabilities) { + const RawAddress& peer_address, const btav_a2dp_codec_config_t& codec_config, + const std::vector& codecs_local_capabilities, + const std::vector& codecs_selectable_capabilities) { log::verbose("peer={}", peer_address); if (btif_av_source.Enabled()) { - do_in_jni_thread(base::BindOnce( - btif_av_source.Callbacks()->audio_config_cb, peer_address, codec_config, - codecs_local_capabilities, codecs_selectable_capabilities)); + do_in_jni_thread(base::BindOnce(btif_av_source.Callbacks()->audio_config_cb, peer_address, + codec_config, codecs_local_capabilities, + codecs_selectable_capabilities)); } } @@ -3132,13 +3012,12 @@ void btif_av_report_source_codec_state( * @param sample_rate the sample rate (in samples per second) * @param channel_count the channel count (1 for Mono, 2 for Stereo) */ -static void btif_av_report_sink_audio_config_state( - const RawAddress& peer_address, int sample_rate, int channel_count) { - log::info("peer={} sample_rate={} channel_count={}", peer_address, - sample_rate, channel_count); +static void btif_av_report_sink_audio_config_state(const RawAddress& peer_address, int sample_rate, + int channel_count) { + log::info("peer={} sample_rate={} channel_count={}", peer_address, sample_rate, channel_count); if (btif_av_sink.Enabled()) { - do_in_jni_thread(base::BindOnce(btif_av_sink.Callbacks()->audio_config_cb, - peer_address, sample_rate, channel_count)); + do_in_jni_thread(base::BindOnce(btif_av_sink.Callbacks()->audio_config_cb, peer_address, + sample_rate, channel_count)); } } @@ -3148,16 +3027,14 @@ static void btif_av_report_sink_audio_config_state( * * @param peer_address the peer address */ -static void btif_av_query_mandatory_codec_priority( - const RawAddress& peer_address) { +static void btif_av_query_mandatory_codec_priority(const RawAddress& peer_address) { auto query_priority = [](const RawAddress& peer_address) { if (!btif_av_source.Enabled()) { log::warn("BTIF AV Source is not enabled"); return; } btav_source_callbacks_t* callbacks = btif_av_source.Callbacks(); - bool preferred = callbacks != nullptr && - callbacks->mandatory_codec_preferred_cb(peer_address); + bool preferred = callbacks != nullptr && callbacks->mandatory_codec_preferred_cb(peer_address); if (preferred) { auto apply_priority = [](const RawAddress& peer_address, bool preferred) { BtifAvPeer* peer = btif_av_find_peer(peer_address, A2dpType::kSource); @@ -3167,8 +3044,7 @@ static void btif_av_query_mandatory_codec_priority( } peer->SetMandatoryCodecPreferred(preferred); }; - do_in_main_thread( - FROM_HERE, base::BindOnce(apply_priority, peer_address, preferred)); + do_in_main_thread(FROM_HERE, base::BindOnce(apply_priority, peer_address, preferred)); } }; if (btif_av_source.Enabled()) { @@ -3176,8 +3052,7 @@ static void btif_av_query_mandatory_codec_priority( } } -static BtifAvPeer* btif_av_handle_both_peer(uint8_t peer_sep, - const RawAddress& peer_address, +static BtifAvPeer* btif_av_handle_both_peer(uint8_t peer_sep, const RawAddress& peer_address, tBTA_AV_HNDL bta_handle) { BtifAvPeer* peer = nullptr; @@ -3198,30 +3073,28 @@ static BtifAvPeer* btif_av_handle_both_peer(uint8_t peer_sep, } if (btif_av_source.GetPeersCount() != 0) { log::verbose( - "peer_sep invalid, and already has sink peer, so try create a " - "new sink peer"); + "peer_sep invalid, and already has sink peer, so try create a " + "new sink peer"); peer = btif_av_source.FindOrCreatePeer(peer_address, bta_handle); } else if (btif_av_sink.GetPeersCount() != 0) { log::verbose( - "peer_sep invalid, and already has source peer, so try create " - "a new source peer"); + "peer_sep invalid, and already has source peer, so try create " + "a new source peer"); peer = btif_av_sink.FindOrCreatePeer(peer_address, bta_handle); } else { log::verbose( - "peer_sep invalid, and no active peer, so try create a new " - "sink peer"); + "peer_sep invalid, and no active peer, so try create a new " + "sink peer"); peer = btif_av_source.FindOrCreatePeer(peer_address, bta_handle); } } } } else { if (peer_sep == AVDT_TSEP_SNK) { - log::verbose("peer_sep({}), only init src create a new source peer", - peer_sep); + log::verbose("peer_sep({}), only init src create a new source peer", peer_sep); peer = btif_av_source.FindOrCreatePeer(peer_address, bta_handle); } else if (peer_sep == AVDT_TSEP_SRC) { - log::verbose("peer_sep({}), only init sink create a new source peer", - peer_sep); + log::verbose("peer_sep({}), only init sink create a new source peer", peer_sep); peer = btif_av_sink.FindOrCreatePeer(peer_address, bta_handle); } } @@ -3260,12 +3133,9 @@ static BtifAvPeer* btif_av_handle_both_peer(uint8_t peer_sep, * kBtaHandleUnknown * @param btif_av_event the corresponding event */ -static void btif_av_handle_event(uint8_t peer_sep, - const RawAddress& peer_address, - tBTA_AV_HNDL bta_handle, - const BtifAvEvent& btif_av_event) { - log::info("peer={} handle=0x{:x} event={}", - peer_address, bta_handle, btif_av_event.ToString()); +static void btif_av_handle_event(uint8_t peer_sep, const RawAddress& peer_address, + tBTA_AV_HNDL bta_handle, const BtifAvEvent& btif_av_event) { + log::info("peer={} handle=0x{:x} event={}", peer_address, bta_handle, btif_av_event.ToString()); BtifAvPeer* peer = nullptr; @@ -3289,15 +3159,14 @@ static void btif_av_handle_event(uint8_t peer_sep, } if (peer == nullptr) { log::error( - "Cannot find or create {} peer for peer={} " - "bta_handle=0x{:x} : event dropped: {}", - peer_stream_endpoint_text(peer_sep), peer_address, bta_handle, - btif_av_event.ToString()); + "Cannot find or create {} peer for peer={} " + "bta_handle=0x{:x} : event dropped: {}", + peer_stream_endpoint_text(peer_sep), peer_address, bta_handle, + btif_av_event.ToString()); return; } - peer->StateMachine().ProcessEvent(btif_av_event.Event(), - btif_av_event.Data()); + peer->StateMachine().ProcessEvent(btif_av_event.Event(), btif_av_event.Data()); } /** @@ -3308,8 +3177,7 @@ static void btif_av_handle_event(uint8_t peer_sep, * is A2DP Source, or AVDT_TSEP_SNK if the peer is A2DP Sink. * @param btif_av_event the corresponding event */ -static void btif_av_handle_bta_av_event(uint8_t peer_sep, - const BtifAvEvent& btif_av_event) { +static void btif_av_handle_bta_av_event(uint8_t peer_sep, const BtifAvEvent& btif_av_event) { RawAddress peer_address = RawAddress::kEmpty; tBTA_AV_HNDL bta_handle = kBtaHandleUnknown; tBTA_AV_EVT event = btif_av_event.Event(); @@ -3329,14 +3197,14 @@ static void btif_av_handle_bta_av_event(uint8_t peer_sep, const tBTA_AV_REGISTER& reg = p_data->reg; bta_handle = reg.hndl; uint8_t peer_id = reg.app_id; // The PeerId is used as AppId - log::verbose("Register bta_handle=0x{:x} app_id={}", bta_handle, - reg.app_id); + log::verbose("Register bta_handle=0x{:x} app_id={}", bta_handle, reg.app_id); if (btif_av_src_sink_coexist_enabled()) { if (peer_sep == AVDT_TSEP_INVALID) { - if (reg.peer_sep == AVDT_TSEP_SNK) + if (reg.peer_sep == AVDT_TSEP_SNK) { peer_sep = AVDT_TSEP_SNK; - else + } else { peer_sep = AVDT_TSEP_SRC; + } } } if (peer_sep == AVDT_TSEP_SNK) { @@ -3468,20 +3336,16 @@ static void btif_av_handle_bta_av_event(uint8_t peer_sep, } if (!msg.empty()) { - BTM_LogHistory(kBtmLogHistoryTag, peer_address, msg, - btif_av_event.ToString()); + BTM_LogHistory(kBtmLogHistoryTag, peer_address, msg, btif_av_event.ToString()); } btif_av_handle_event(peer_sep, peer_address, bta_handle, btif_av_event); } -bool btif_av_both_enable(void) { - return (btif_av_sink.Enabled() && btif_av_source.Enabled()); -} +bool btif_av_both_enable(void) { return btif_av_sink.Enabled() && btif_av_source.Enabled(); } bool is_a2dp_source_property_enabled(void) { #ifdef __ANDROID__ - return android::sysprop::BluetoothProperties::isProfileA2dpSourceEnabled() - .value_or(false); + return android::sysprop::BluetoothProperties::isProfileA2dpSourceEnabled().value_or(false); #else return false; #endif @@ -3489,8 +3353,7 @@ bool is_a2dp_source_property_enabled(void) { bool is_a2dp_sink_property_enabled(void) { #ifdef __ANDROID__ - return android::sysprop::BluetoothProperties::isProfileA2dpSinkEnabled() - .value_or(false); + return android::sysprop::BluetoothProperties::isProfileA2dpSinkEnabled().value_or(false); #else return false; #endif @@ -3506,25 +3369,21 @@ static void bta_av_source_callback(tBTA_AV_EVT event, tBTA_AV* p_data) { BtifAvEvent btif_av_event(event, p_data, sizeof(tBTA_AV)); log::verbose("event={}", btif_av_event.ToString()); - do_in_main_thread( - FROM_HERE, base::BindOnce(&btif_av_handle_bta_av_event, - AVDT_TSEP_SNK /* peer_sep */, btif_av_event)); + do_in_main_thread(FROM_HERE, base::BindOnce(&btif_av_handle_bta_av_event, + AVDT_TSEP_SNK /* peer_sep */, btif_av_event)); } static void bta_av_sink_callback(tBTA_AV_EVT event, tBTA_AV* p_data) { BtifAvEvent btif_av_event(event, p_data, sizeof(tBTA_AV)); - do_in_main_thread( - FROM_HERE, base::BindOnce(&btif_av_handle_bta_av_event, - AVDT_TSEP_SRC /* peer_sep */, btif_av_event)); + do_in_main_thread(FROM_HERE, base::BindOnce(&btif_av_handle_bta_av_event, + AVDT_TSEP_SRC /* peer_sep */, btif_av_event)); } static void bta_av_event_callback(tBTA_AV_EVT event, tBTA_AV* p_data) { if (btif_av_both_enable()) { BtifAvEvent btif_av_event(event, p_data, sizeof(tBTA_AV)); - do_in_main_thread( - FROM_HERE, - base::BindOnce(&btif_av_handle_bta_av_event, - AVDT_TSEP_INVALID /* peer_sep */, btif_av_event)); + do_in_main_thread(FROM_HERE, base::BindOnce(&btif_av_handle_bta_av_event, + AVDT_TSEP_INVALID /* peer_sep */, btif_av_event)); return; } @@ -3536,8 +3395,7 @@ static void bta_av_event_callback(tBTA_AV_EVT event, tBTA_AV* p_data) { } // TODO: All processing should be done on the JNI thread -static void bta_av_sink_media_callback(const RawAddress& peer_address, - tBTA_AV_EVT event, +static void bta_av_sink_media_callback(const RawAddress& peer_address, tBTA_AV_EVT event, tBTA_AV_MEDIA* p_data) { log::verbose("event={}", event); @@ -3548,8 +3406,7 @@ static void bta_av_sink_media_callback(const RawAddress& peer_address, int state = peer->StateMachine().StateId(); if ((state == BtifAvStateMachine::kStateStarted) || (state == BtifAvStateMachine::kStateOpened)) { - uint8_t queue_len = - btif_a2dp_sink_enqueue_buf(reinterpret_cast(p_data)); + uint8_t queue_len = btif_a2dp_sink_enqueue_buf(reinterpret_cast(p_data)); log::verbose("Packets in Sink queue {}", queue_len); } } @@ -3561,29 +3418,24 @@ static void bta_av_sink_media_callback(const RawAddress& peer_address, log::verbose("address={}", p_data->avk_config.bd_addr); // Update the codec info of the A2DP Sink decoder - btif_a2dp_sink_update_decoder( - reinterpret_cast(p_data->avk_config.codec_info)); + btif_a2dp_sink_update_decoder(reinterpret_cast(p_data->avk_config.codec_info)); - config_req.sample_rate = - A2DP_GetTrackSampleRate(p_data->avk_config.codec_info); + config_req.sample_rate = A2DP_GetTrackSampleRate(p_data->avk_config.codec_info); if (config_req.sample_rate == -1) { log::error("Cannot get the track frequency"); break; } - config_req.channel_count = - A2DP_GetTrackChannelCount(p_data->avk_config.codec_info); + config_req.channel_count = A2DP_GetTrackChannelCount(p_data->avk_config.codec_info); if (config_req.channel_count == -1) { log::error("Cannot get the channel count"); break; } config_req.peer_address = p_data->avk_config.bd_addr; - BtifAvEvent btif_av_event(BTIF_AV_SINK_CONFIG_REQ_EVT, &config_req, - sizeof(config_req)); - do_in_main_thread( - FROM_HERE, base::BindOnce(&btif_av_handle_event, - AVDT_TSEP_SRC, // peer_sep - config_req.peer_address, kBtaHandleUnknown, - btif_av_event)); + BtifAvEvent btif_av_event(BTIF_AV_SINK_CONFIG_REQ_EVT, &config_req, sizeof(config_req)); + do_in_main_thread(FROM_HERE, + base::BindOnce(&btif_av_handle_event, + AVDT_TSEP_SRC, // peer_sep + config_req.peer_address, kBtaHandleUnknown, btif_av_event)); break; } default: @@ -3592,20 +3444,17 @@ static void bta_av_sink_media_callback(const RawAddress& peer_address, } // Initializes the AV interface for source mode -bt_status_t btif_av_source_init( - btav_source_callbacks_t* callbacks, int max_connected_audio_devices, - const std::vector& codec_priorities, - const std::vector& offloading_preference, - std::vector* supported_codecs) { +bt_status_t btif_av_source_init(btav_source_callbacks_t* callbacks, int max_connected_audio_devices, + const std::vector& codec_priorities, + const std::vector& offloading_preference, + std::vector* supported_codecs) { log::info(""); - return btif_av_source.Init(callbacks, max_connected_audio_devices, - codec_priorities, offloading_preference, - supported_codecs); + return btif_av_source.Init(callbacks, max_connected_audio_devices, codec_priorities, + offloading_preference, supported_codecs); } // Initializes the AV interface for sink mode -bt_status_t btif_av_sink_init(btav_sink_callbacks_t* callbacks, - int max_connected_audio_devices) { +bt_status_t btif_av_sink_init(btav_sink_callbacks_t* callbacks, int max_connected_audio_devices) { log::info(""); return btif_av_sink.Init(callbacks, max_connected_audio_devices); } @@ -3649,16 +3498,15 @@ static bt_status_t connect_int(RawAddress* peer_address, uint16_t uuid) { } peer->StateMachine().ProcessEvent(BTIF_AV_CONNECT_REQ_EVT, nullptr); }; - bt_status_t status = do_in_main_thread( - FROM_HERE, base::BindOnce(connection_task, peer_address, uuid)); + bt_status_t status = + do_in_main_thread(FROM_HERE, base::BindOnce(connection_task, peer_address, uuid)); if (status != BT_STATUS_SUCCESS) { log::error("can't post connection task to main_thread"); } return status; } -static void set_source_silence_peer_int(const RawAddress& peer_address, - bool silence) { +static void set_source_silence_peer_int(const RawAddress& peer_address, bool silence) { log::info("peer={} silence={}", peer_address, silence); if (!btif_av_source.SetSilencePeer(peer_address, silence)) { @@ -3667,28 +3515,26 @@ static void set_source_silence_peer_int(const RawAddress& peer_address, } // Set the active peer -static void set_active_peer_int(uint8_t peer_sep, - const RawAddress& peer_address, +static void set_active_peer_int(uint8_t peer_sep, const RawAddress& peer_address, std::promise peer_ready_promise) { - log::info("peer_sep={} peer={}", - peer_sep == AVDT_TSEP_SRC ? "Source" : "Sink", peer_address); + log::info("peer_sep={} peer={}", peer_sep == AVDT_TSEP_SRC ? "Source" : "Sink", peer_address); BtifAvPeer* peer = nullptr; if (peer_sep == AVDT_TSEP_SNK) { - if (!btif_av_src_sink_coexist_enabled() || (btif_av_src_sink_coexist_enabled() && - btif_av_both_enable() && (btif_av_sink.FindPeer(peer_address) == nullptr))) { - if (!btif_av_source.SetActivePeer(peer_address, - std::move(peer_ready_promise))) { + if (!btif_av_src_sink_coexist_enabled() || + (btif_av_src_sink_coexist_enabled() && btif_av_both_enable() && + (btif_av_sink.FindPeer(peer_address) == nullptr))) { + if (!btif_av_source.SetActivePeer(peer_address, std::move(peer_ready_promise))) { log::error("Error setting {} as active Sink peer", peer_address); } } return; } if (peer_sep == AVDT_TSEP_SRC) { - if (!btif_av_src_sink_coexist_enabled() || (btif_av_src_sink_coexist_enabled() && - btif_av_both_enable() && (btif_av_source.FindPeer(peer_address) == nullptr))) { - if (!btif_av_sink.SetActivePeer(peer_address, - std::move(peer_ready_promise))) { + if (!btif_av_src_sink_coexist_enabled() || + (btif_av_src_sink_coexist_enabled() && btif_av_both_enable() && + (btif_av_source.FindPeer(peer_address) == nullptr))) { + if (!btif_av_sink.SetActivePeer(peer_address, std::move(peer_ready_promise))) { log::error("Error setting {} as active Source peer", peer_address); } } @@ -3710,8 +3556,7 @@ bt_status_t btif_av_source_connect(const RawAddress& peer_address) { } RawAddress peer_address_copy(peer_address); - return btif_queue_connect(UUID_SERVCLASS_AUDIO_SOURCE, &peer_address_copy, - connect_int); + return btif_queue_connect(UUID_SERVCLASS_AUDIO_SOURCE, &peer_address_copy, connect_int); } bt_status_t btif_av_sink_connect(const RawAddress& peer_address) { @@ -3723,8 +3568,7 @@ bt_status_t btif_av_sink_connect(const RawAddress& peer_address) { } RawAddress peer_address_copy(peer_address); - return btif_queue_connect(UUID_SERVCLASS_AUDIO_SINK, &peer_address_copy, - connect_int); + return btif_queue_connect(UUID_SERVCLASS_AUDIO_SINK, &peer_address_copy, connect_int); } bt_status_t btif_av_source_disconnect(const RawAddress& peer_address) { @@ -3735,13 +3579,11 @@ bt_status_t btif_av_source_disconnect(const RawAddress& peer_address) { return BT_STATUS_NOT_READY; } - BtifAvEvent btif_av_event(BTIF_AV_DISCONNECT_REQ_EVT, &peer_address, - sizeof(peer_address)); - return do_in_main_thread( - FROM_HERE, - base::BindOnce(&btif_av_handle_event, - AVDT_TSEP_SNK, // peer_sep - peer_address, kBtaHandleUnknown, btif_av_event)); + BtifAvEvent btif_av_event(BTIF_AV_DISCONNECT_REQ_EVT, &peer_address, sizeof(peer_address)); + return do_in_main_thread(FROM_HERE, + base::BindOnce(&btif_av_handle_event, + AVDT_TSEP_SNK, // peer_sep + peer_address, kBtaHandleUnknown, btif_av_event)); } bt_status_t btif_av_sink_disconnect(const RawAddress& peer_address) { @@ -3752,13 +3594,11 @@ bt_status_t btif_av_sink_disconnect(const RawAddress& peer_address) { return BT_STATUS_NOT_READY; } - BtifAvEvent btif_av_event(BTIF_AV_DISCONNECT_REQ_EVT, &peer_address, - sizeof(peer_address)); - return do_in_main_thread( - FROM_HERE, - base::BindOnce(&btif_av_handle_event, - AVDT_TSEP_SRC, // peer_sep - peer_address, kBtaHandleUnknown, btif_av_event)); + BtifAvEvent btif_av_event(BTIF_AV_DISCONNECT_REQ_EVT, &peer_address, sizeof(peer_address)); + return do_in_main_thread(FROM_HERE, + base::BindOnce(&btif_av_handle_event, + AVDT_TSEP_SRC, // peer_sep + peer_address, kBtaHandleUnknown, btif_av_event)); } bt_status_t btif_av_sink_set_active_device(const RawAddress& peer_address) { @@ -3771,10 +3611,10 @@ bt_status_t btif_av_sink_set_active_device(const RawAddress& peer_address) { std::promise peer_ready_promise; std::future peer_ready_future = peer_ready_promise.get_future(); - bt_status_t status = do_in_main_thread( - FROM_HERE, base::BindOnce(&set_active_peer_int, - AVDT_TSEP_SRC, // peer_sep - peer_address, std::move(peer_ready_promise))); + bt_status_t status = + do_in_main_thread(FROM_HERE, base::BindOnce(&set_active_peer_int, + AVDT_TSEP_SRC, // peer_sep + peer_address, std::move(peer_ready_promise))); if (status == BT_STATUS_SUCCESS) { peer_ready_future.wait(); } else { @@ -3783,8 +3623,7 @@ bt_status_t btif_av_sink_set_active_device(const RawAddress& peer_address) { return status; } -bt_status_t btif_av_source_set_silence_device(const RawAddress& peer_address, - bool silence) { +bt_status_t btif_av_source_set_silence_device(const RawAddress& peer_address, bool silence) { log::info("peer={} silence={}", peer_address, silence); if (!btif_av_source.Enabled()) { @@ -3792,9 +3631,8 @@ bt_status_t btif_av_source_set_silence_device(const RawAddress& peer_address, return BT_STATUS_NOT_READY; } - return do_in_main_thread( - FROM_HERE, - base::BindOnce(&set_source_silence_peer_int, peer_address, silence)); + return do_in_main_thread(FROM_HERE, + base::BindOnce(&set_source_silence_peer_int, peer_address, silence)); } bt_status_t btif_av_source_set_active_device(const RawAddress& peer_address) { @@ -3807,10 +3645,10 @@ bt_status_t btif_av_source_set_active_device(const RawAddress& peer_address) { std::promise peer_ready_promise; std::future peer_ready_future = peer_ready_promise.get_future(); - bt_status_t status = do_in_main_thread( - FROM_HERE, base::BindOnce(&set_active_peer_int, - AVDT_TSEP_SNK, // peer_sep - peer_address, std::move(peer_ready_promise))); + bt_status_t status = + do_in_main_thread(FROM_HERE, base::BindOnce(&set_active_peer_int, + AVDT_TSEP_SNK, // peer_sep + peer_address, std::move(peer_ready_promise))); if (status == BT_STATUS_SUCCESS) { peer_ready_future.wait(); } else { @@ -3820,10 +3658,8 @@ bt_status_t btif_av_source_set_active_device(const RawAddress& peer_address) { } bt_status_t btif_av_source_set_codec_config_preference( - const RawAddress& peer_address, - std::vector codec_preferences) { - log::info("peer={} codec_preferences=[{}]", peer_address, - codec_preferences.size()); + const RawAddress& peer_address, std::vector codec_preferences) { + log::info("peer={} codec_preferences=[{}]", peer_address, codec_preferences.size()); if (!btif_av_source.Enabled()) { log::warn("BTIF AV Source is not enabled"); @@ -3838,10 +3674,9 @@ bt_status_t btif_av_source_set_codec_config_preference( std::promise peer_ready_promise; std::future peer_ready_future = peer_ready_promise.get_future(); bt_status_t status = do_in_main_thread( - FROM_HERE, - base::BindOnce(&BtifAvSource::UpdateCodecConfig, - base::Unretained(&btif_av_source), peer_address, - codec_preferences, std::move(peer_ready_promise))); + FROM_HERE, + base::BindOnce(&BtifAvSource::UpdateCodecConfig, base::Unretained(&btif_av_source), + peer_address, codec_preferences, std::move(peer_ready_promise))); if (status == BT_STATUS_SUCCESS) { peer_ready_future.wait(); } else { @@ -3853,19 +3688,16 @@ bt_status_t btif_av_source_set_codec_config_preference( void btif_av_source_cleanup(void) { log::info(""); do_in_main_thread(FROM_HERE, - base::BindOnce(&BtifAvSource::Cleanup, - base::Unretained(&btif_av_source))); + base::BindOnce(&BtifAvSource::Cleanup, base::Unretained(&btif_av_source))); } void btif_av_sink_cleanup(void) { log::info(""); - do_in_main_thread(FROM_HERE, base::BindOnce(&BtifAvSink::Cleanup, - base::Unretained(&btif_av_sink))); + do_in_main_thread(FROM_HERE, + base::BindOnce(&BtifAvSink::Cleanup, base::Unretained(&btif_av_sink))); } -RawAddress btif_av_source_active_peer(void) { - return btif_av_source.ActivePeer(); -} +RawAddress btif_av_source_active_peer(void) { return btif_av_source.ActivePeer(); } RawAddress btif_av_sink_active_peer(void) { return btif_av_sink.ActivePeer(); } bool btif_av_is_sink_enabled(void) { return btif_av_sink.Enabled(); } @@ -3875,24 +3707,21 @@ bool btif_av_is_source_enabled(void) { return btif_av_source.Enabled(); } void btif_av_stream_start(const A2dpType local_a2dp_type) { log::info(""); - btif_av_source_dispatch_sm_event(btif_av_source_active_peer(), - BTIF_AV_START_STREAM_REQ_EVT); + btif_av_source_dispatch_sm_event(btif_av_source_active_peer(), BTIF_AV_START_STREAM_REQ_EVT); } void btif_av_stream_start_with_latency(bool use_latency_mode) { - log::info("peer={} use_latency_mode={}", - btif_av_source_active_peer(), use_latency_mode); + log::info("peer={} use_latency_mode={}", btif_av_source_active_peer(), use_latency_mode); btif_av_start_stream_req_t start_stream_req; start_stream_req.use_latency_mode = use_latency_mode; BtifAvEvent btif_av_event(BTIF_AV_START_STREAM_REQ_EVT, &start_stream_req, sizeof(start_stream_req)); - do_in_main_thread( - FROM_HERE, base::BindOnce(&btif_av_handle_event, - AVDT_TSEP_SNK, // peer_sep - btif_av_source_active_peer(), kBtaHandleUnknown, - btif_av_event)); + do_in_main_thread(FROM_HERE, + base::BindOnce(&btif_av_handle_event, + AVDT_TSEP_SNK, // peer_sep + btif_av_source_active_peer(), kBtaHandleUnknown, btif_av_event)); } void btif_av_stream_stop(const RawAddress& peer_address) { @@ -3919,8 +3748,7 @@ void btif_av_stream_suspend(void) { void btif_av_stream_start_offload(void) { log::info(""); - btif_av_source_dispatch_sm_event(btif_av_source_active_peer(), - BTIF_AV_OFFLOAD_START_REQ_EVT); + btif_av_source_dispatch_sm_event(btif_av_source_active_peer(), BTIF_AV_OFFLOAD_START_REQ_EVT); } bool btif_av_stream_ready(const A2dpType local_a2dp_type) { @@ -3937,16 +3765,14 @@ bool btif_av_stream_ready(const A2dpType local_a2dp_type) { } int state = peer->StateMachine().StateId(); - log::info("active_peer={} state={} flags={}", peer->PeerAddress(), state, - peer->FlagsToString()); + log::info("active_peer={} state={} flags={}", peer->PeerAddress(), state, peer->FlagsToString()); // check if we are remotely suspended or stop is pending - if (peer->CheckFlags(BtifAvPeer::kFlagRemoteSuspend | - BtifAvPeer::kFlagPendingStop)) { + if (peer->CheckFlags(BtifAvPeer::kFlagRemoteSuspend | BtifAvPeer::kFlagPendingStop)) { return false; } - return (state == BtifAvStateMachine::kStateOpened); + return state == BtifAvStateMachine::kStateOpened; } bool btif_av_stream_started_ready(const A2dpType local_a2dp_type) { @@ -3958,8 +3784,7 @@ bool btif_av_stream_started_ready(const A2dpType local_a2dp_type) { int state = peer->StateMachine().StateId(); bool ready = false; - if (peer->CheckFlags(BtifAvPeer::kFlagLocalSuspendPending | - BtifAvPeer::kFlagRemoteSuspend | + if (peer->CheckFlags(BtifAvPeer::kFlagLocalSuspendPending | BtifAvPeer::kFlagRemoteSuspend | BtifAvPeer::kFlagPendingStop)) { // Disallow media task to start if we have pending actions ready = false; @@ -3967,8 +3792,8 @@ bool btif_av_stream_started_ready(const A2dpType local_a2dp_type) { ready = (state == BtifAvStateMachine::kStateStarted); } - log::info("active_peer={} state={} flags={} ready={}", peer->PeerAddress(), - state, peer->FlagsToString(), ready); + log::info("active_peer={} state={} flags={} ready={}", peer->PeerAddress(), state, + peer->FlagsToString(), ready); return ready; } @@ -3976,25 +3801,21 @@ bool btif_av_stream_started_ready(const A2dpType local_a2dp_type) { static void btif_av_source_dispatch_sm_event(const RawAddress& peer_address, btif_av_sm_event_t event) { BtifAvEvent btif_av_event(event, nullptr, 0); - log::verbose("peer={} event={}", peer_address, - btif_av_event.ToString()); + log::verbose("peer={} event={}", peer_address, btif_av_event.ToString()); do_in_main_thread(FROM_HERE, base::BindOnce(&btif_av_handle_event, AVDT_TSEP_SNK, // peer_sep - peer_address, kBtaHandleUnknown, - btif_av_event)); + peer_address, kBtaHandleUnknown, btif_av_event)); } static void btif_av_sink_dispatch_sm_event(const RawAddress& peer_address, btif_av_sm_event_t event) { BtifAvEvent btif_av_event(event, nullptr, 0); - log::verbose("peer={} event={}", peer_address, - btif_av_event.ToString()); + log::verbose("peer={} event={}", peer_address, btif_av_event.ToString()); do_in_main_thread(FROM_HERE, base::BindOnce(&btif_av_handle_event, AVDT_TSEP_SRC, // peer_sep - peer_address, kBtaHandleUnknown, - btif_av_event)); + peer_address, kBtaHandleUnknown, btif_av_event)); } bt_status_t btif_av_source_execute_service(bool enable) { @@ -4006,8 +3827,8 @@ bt_status_t btif_av_source_execute_service(bool enable) { // be initiated by the app/audioflinger layers. // Support for browsing for SDP record should work only if we enable // BROWSE while registering. - tBTA_AV_FEAT features = BTA_AV_FEAT_RCTG | BTA_AV_FEAT_METADATA | - BTA_AV_FEAT_VENDOR | BTA_AV_FEAT_NO_SCO_SSPD; + tBTA_AV_FEAT features = + BTA_AV_FEAT_RCTG | BTA_AV_FEAT_METADATA | BTA_AV_FEAT_VENDOR | BTA_AV_FEAT_NO_SCO_SSPD; if (delay_reporting_enabled()) { features |= BTA_AV_FEAT_DELAY_RPT; @@ -4040,19 +3861,19 @@ bt_status_t btif_av_sink_execute_service(bool enable) { // Added BTA_AV_FEAT_NO_SCO_SSPD - this ensures that the BTA does not // auto-suspend AV streaming on AG events (SCO or Call). The suspend shall // be initiated by the app/audioflinger layers. - tBTA_AV_FEAT features = BTA_AV_FEAT_NO_SCO_SSPD | BTA_AV_FEAT_RCCT | - BTA_AV_FEAT_METADATA | BTA_AV_FEAT_VENDOR | - BTA_AV_FEAT_ADV_CTRL | BTA_AV_FEAT_RCTG | + tBTA_AV_FEAT features = BTA_AV_FEAT_NO_SCO_SSPD | BTA_AV_FEAT_RCCT | BTA_AV_FEAT_METADATA | + BTA_AV_FEAT_VENDOR | BTA_AV_FEAT_ADV_CTRL | BTA_AV_FEAT_RCTG | BTA_AV_FEAT_BROWSE | BTA_AV_FEAT_COVER_ARTWORK; if (delay_reporting_enabled()) { features |= BTA_AV_FEAT_DELAY_RPT; } - if (btif_av_src_sink_coexist_enabled()) + if (btif_av_src_sink_coexist_enabled()) { BTA_AvEnable(features, bta_av_event_callback); - else + } else { BTA_AvEnable(features, bta_av_sink_callback); + } btif_av_sink.RegisterAllBtaHandles(); return BT_STATUS_SUCCESS; } @@ -4095,17 +3916,14 @@ void btif_av_clear_remote_suspend_flag(const A2dpType local_a2dp_type) { log::warn("No active peer found"); return; } - log::verbose("active_peer={} flags={}", peer->PeerAddress(), - peer->FlagsToString()); + log::verbose("active_peer={} flags={}", peer->PeerAddress(), peer->FlagsToString()); peer->ClearFlags(BtifAvPeer::kFlagRemoteSuspend); }; // switch to main thread to prevent a race condition of accessing peers - do_in_main_thread(FROM_HERE, - base::BindOnce(clear_remote_suspend_flag, local_a2dp_type)); + do_in_main_thread(FROM_HERE, base::BindOnce(clear_remote_suspend_flag, local_a2dp_type)); } -bool btif_av_is_peer_edr(const RawAddress& peer_address, - const A2dpType local_a2dp_type) { +bool btif_av_is_peer_edr(const RawAddress& peer_address, const A2dpType local_a2dp_type) { BtifAvPeer* peer = btif_av_find_peer(peer_address, local_a2dp_type); if (peer == nullptr) { log::warn("peer={} not found", peer_address); @@ -4121,8 +3939,7 @@ bool btif_av_is_peer_edr(const RawAddress& peer_address, return is_edr; } -bool btif_av_peer_supports_3mbps(const RawAddress& peer_address, - const A2dpType local_a2dp_type) { +bool btif_av_peer_supports_3mbps(const RawAddress& peer_address, const A2dpType local_a2dp_type) { BtifAvPeer* peer = btif_av_find_peer(peer_address, local_a2dp_type); if (peer == nullptr) { log::warn("peer={} not found", peer_address); @@ -4131,8 +3948,7 @@ bool btif_av_peer_supports_3mbps(const RawAddress& peer_address, bool is_3mbps = peer->Is3Mbps(); bool is_connected = peer->IsConnected(); - log::verbose("peer={} connected={}, edr_3mbps={}", peer_address, - is_connected, is_3mbps); + log::verbose("peer={} connected={}, edr_3mbps={}", peer_address, is_connected, is_3mbps); return is_connected && is_3mbps; } @@ -4146,20 +3962,17 @@ bool btif_av_peer_prefers_mandatory_codec(const RawAddress& peer_address, return peer->IsMandatoryCodecPreferred(); } -void btif_av_acl_disconnected(const RawAddress& peer_address, - const A2dpType local_a2dp_type) { +void btif_av_acl_disconnected(const RawAddress& peer_address, const A2dpType local_a2dp_type) { log::info("peer={}", peer_address); // Inform the application that ACL is disconnected and move to idle state - if (com::android::bluetooth::flags::a2dp_concurrent_source_sink() || - btif_av_both_enable()) { + if (com::android::bluetooth::flags::a2dp_concurrent_source_sink() || btif_av_both_enable()) { BtifAvPeer* peer = btif_av_find_peer(peer_address, local_a2dp_type); if (peer != nullptr) { if (peer->IsSource()) { btif_av_sink_dispatch_sm_event(peer_address, BTIF_AV_ACL_DISCONNECTED); } else { - btif_av_source_dispatch_sm_event(peer_address, - BTIF_AV_ACL_DISCONNECTED); + btif_av_source_dispatch_sm_event(peer_address, BTIF_AV_ACL_DISCONNECTED); } } return; @@ -4199,21 +4012,18 @@ static void btif_debug_av_peer_dump(int fd, const BtifAvPeer& peer) { dprintf(fd, " Peer: %s\n", ADDRESS_TO_LOGGABLE_CSTR(peer.PeerAddress())); dprintf(fd, " Connected: %s\n", peer.IsConnected() ? "true" : "false"); dprintf(fd, " Streaming: %s\n", peer.IsStreaming() ? "true" : "false"); - dprintf(fd, " SEP: %d(%s)\n", peer.PeerSep(), - (peer.IsSource()) ? "Source" : "Sink"); + dprintf(fd, " SEP: %d(%s)\n", peer.PeerSep(), (peer.IsSource()) ? "Source" : "Sink"); dprintf(fd, " State Machine: %s\n", state_str.c_str()); dprintf(fd, " Flags: %s\n", peer.FlagsToString().c_str()); dprintf(fd, " OpenOnRcTimer: %s\n", - alarm_is_scheduled(peer.AvOpenOnRcTimer()) ? "Scheduled" - : "Not scheduled"); + alarm_is_scheduled(peer.AvOpenOnRcTimer()) ? "Scheduled" : "Not scheduled"); dprintf(fd, " BTA Handle: 0x%x\n", peer.BtaHandle()); dprintf(fd, " Peer ID: %d\n", peer.PeerId()); dprintf(fd, " EDR: %s\n", peer.IsEdr() ? "true" : "false"); dprintf(fd, " Support 3Mbps: %s\n", peer.Is3Mbps() ? "true" : "false"); dprintf(fd, " Self Initiated Connection: %s\n", peer.SelfInitiatedConnection() ? "true" : "false"); - dprintf(fd, " Delay Reporting: %u (in 1/10 milliseconds) \n", - peer.GetDelayReport()); + dprintf(fd, " Delay Reporting: %u (in 1/10 milliseconds) \n", peer.GetDelayReport()); dprintf(fd, " Codec Preferred: %s\n", peer.IsMandatoryCodecPreferred() ? "Mandatory" : "Optional"); } @@ -4222,9 +4032,10 @@ static void btif_debug_av_source_dump(int fd) { bool enabled = btif_av_source.Enabled(); dprintf(fd, "\nA2DP Source State: %s\n", (enabled) ? "Enabled" : "Disabled"); - if (!enabled) return; - dprintf(fd, " Active peer: %s\n", - ADDRESS_TO_LOGGABLE_CSTR(btif_av_source.ActivePeer())); + if (!enabled) { + return; + } + dprintf(fd, " Active peer: %s\n", ADDRESS_TO_LOGGABLE_CSTR(btif_av_source.ActivePeer())); dprintf(fd, " Peers:\n"); btif_av_source.DumpPeersInfo(fd); } @@ -4233,9 +4044,10 @@ static void btif_debug_av_sink_dump(int fd) { bool enabled = btif_av_sink.Enabled(); dprintf(fd, "\nA2DP Sink State: %s\n", (enabled) ? "Enabled" : "Disabled"); - if (!enabled) return; - dprintf(fd, " Active peer: %s\n", - ADDRESS_TO_LOGGABLE_CSTR(btif_av_sink.ActivePeer())); + if (!enabled) { + return; + } + dprintf(fd, " Active peer: %s\n", ADDRESS_TO_LOGGABLE_CSTR(btif_av_sink.ActivePeer())); dprintf(fd, " Peers:\n"); btif_av_sink.DumpPeersInfo(fd); } @@ -4266,9 +4078,7 @@ uint16_t btif_av_get_audio_delay(const A2dpType local_a2dp_type) { return 0; } -bool btif_av_is_a2dp_offload_enabled() { - return btif_av_source.A2dpOffloadEnabled(); -} +bool btif_av_is_a2dp_offload_enabled() { return btif_av_source.A2dpOffloadEnabled(); } bool btif_av_is_a2dp_offload_running() { if (!btif_av_is_a2dp_offload_enabled()) { @@ -4289,31 +4099,23 @@ void btif_av_set_dynamic_audio_buffer_size(uint8_t dynamic_audio_buffer_size) { } void btif_av_set_low_latency(bool is_low_latency) { - log::info("active_peer={} is_low_latency={}", - btif_av_source_active_peer(), is_low_latency); + log::info("active_peer={} is_low_latency={}", btif_av_source_active_peer(), is_low_latency); btif_av_set_latency_req_t set_latency_req; set_latency_req.is_low_latency = is_low_latency; - BtifAvEvent btif_av_event(BTIF_AV_SET_LATENCY_REQ_EVT, &set_latency_req, - sizeof(set_latency_req)); + BtifAvEvent btif_av_event(BTIF_AV_SET_LATENCY_REQ_EVT, &set_latency_req, sizeof(set_latency_req)); - do_in_main_thread( - FROM_HERE, base::BindOnce(&btif_av_handle_event, - AVDT_TSEP_SNK, // peer_sep - btif_av_source_active_peer(), kBtaHandleUnknown, - btif_av_event)); + do_in_main_thread(FROM_HERE, + base::BindOnce(&btif_av_handle_event, + AVDT_TSEP_SNK, // peer_sep + btif_av_source_active_peer(), kBtaHandleUnknown, btif_av_event)); } -static void btif_av_sink_delete_active_peer(void) { - btif_av_sink.DeleteActivePeer(); -} +static void btif_av_sink_delete_active_peer(void) { btif_av_sink.DeleteActivePeer(); } -static void btif_av_source_delete_active_peer(void) { - btif_av_source.DeleteActivePeer(); -} +static void btif_av_source_delete_active_peer(void) { btif_av_source.DeleteActivePeer(); } -bool btif_av_is_connected_addr(const RawAddress& peer_address, - const A2dpType local_a2dp_type) { +bool btif_av_is_connected_addr(const RawAddress& peer_address, const A2dpType local_a2dp_type) { BtifAvPeer* peer = btif_av_find_peer(peer_address, local_a2dp_type); if (peer == nullptr) { log::warn("No active peer found"); @@ -4369,8 +4171,7 @@ bool btif_av_peer_is_source(const RawAddress& peer_address) { return true; } -void btif_av_connect_sink_delayed(uint8_t handle, - const RawAddress& peer_address) { +void btif_av_connect_sink_delayed(uint8_t handle, const RawAddress& peer_address) { log::info("peer={} handle=0x{:x}", peer_address, handle); if (btif_av_source.Enabled()) { diff --git a/system/btif/src/btif_avrcp_audio_track.cc b/system/btif/src/btif_avrcp_audio_track.cc index 5c3416f3847..77faff93cbc 100644 --- a/system/btif/src/btif_avrcp_audio_track.cc +++ b/system/btif/src/btif_avrcp_audio_track.cc @@ -14,7 +14,7 @@ * limitations under the License. */ -//#define LOG_NDEBUG 0 +// #define LOG_NDEBUG 0 #define LOG_TAG "bt_btif_avrcp_audio_track" #include "btif_avrcp_audio_track.h" @@ -53,7 +53,7 @@ constexpr float kMinTrackGain = 0.0f; struct AudioEngine { int trackFreq = 0; int channelCount = 0; - std::thread *thread = nullptr; + std::thread* thread = nullptr; void* trackHandle = nullptr; } s_AudioEngine; @@ -68,8 +68,7 @@ void BtifAvrcpAudioErrorHandle() { AAudioStreamBuilder_setFormat(builder, AAUDIO_FORMAT_PCM_FLOAT); AAudioStreamBuilder_setChannelCount(builder, s_AudioEngine.channelCount); AAudioStreamBuilder_setSessionId(builder, AAUDIO_SESSION_ID_ALLOCATE); - AAudioStreamBuilder_setPerformanceMode(builder, - AAUDIO_PERFORMANCE_MODE_LOW_LATENCY); + AAudioStreamBuilder_setPerformanceMode(builder, AAUDIO_PERFORMANCE_MODE_LOW_LATENCY); AAudioStreamBuilder_setErrorCallback(builder, ErrorCallback, nullptr); result = AAudioStreamBuilder_openStream(builder, &stream); log::assert_that(result == AAUDIO_OK, "assert failed: result == AAUDIO_OK"); @@ -86,18 +85,17 @@ void BtifAvrcpAudioErrorHandle() { s_AudioEngine.thread = nullptr; } -void ErrorCallback(AAudioStream* stream, - void* userdata, - aaudio_result_t error) { - if (error == AAUDIO_ERROR_DISCONNECTED) - if (s_AudioEngine.thread == nullptr) +void ErrorCallback(AAudioStream* stream, void* userdata, aaudio_result_t error) { + if (error == AAUDIO_ERROR_DISCONNECTED) { + if (s_AudioEngine.thread == nullptr) { s_AudioEngine.thread = new std::thread(BtifAvrcpAudioErrorHandle); + } + } } -void* BtifAvrcpAudioTrackCreate(int trackFreq, int bitsPerSample, - int channelCount) { - log::info("Track.cpp: btCreateTrack freq {} bps {} channel {}", trackFreq, - bitsPerSample, channelCount); +void* BtifAvrcpAudioTrackCreate(int trackFreq, int bitsPerSample, int channelCount) { + log::info("Track.cpp: btCreateTrack freq {} bps {} channel {}", trackFreq, bitsPerSample, + channelCount); AAudioStreamBuilder* builder; AAudioStream* stream; @@ -106,8 +104,7 @@ void* BtifAvrcpAudioTrackCreate(int trackFreq, int bitsPerSample, AAudioStreamBuilder_setFormat(builder, AAUDIO_FORMAT_PCM_FLOAT); AAudioStreamBuilder_setChannelCount(builder, channelCount); AAudioStreamBuilder_setSessionId(builder, AAUDIO_SESSION_ID_ALLOCATE); - AAudioStreamBuilder_setPerformanceMode(builder, - AAUDIO_PERFORMANCE_MODE_LOW_LATENCY); + AAudioStreamBuilder_setPerformanceMode(builder, AAUDIO_PERFORMANCE_MODE_LOW_LATENCY); AAudioStreamBuilder_setErrorCallback(builder, ErrorCallback, nullptr); result = AAudioStreamBuilder_openStream(builder, &stream); log::assert_that(result == AAUDIO_OK, "assert failed: result == AAUDIO_OK"); @@ -119,7 +116,7 @@ void* BtifAvrcpAudioTrackCreate(int trackFreq, int bitsPerSample, trackHolder->bitsPerSample = bitsPerSample; trackHolder->channelCount = channelCount; trackHolder->bufferLength = - trackHolder->channelCount * AAudioStream_getBufferSizeInFrames(stream); + trackHolder->channelCount * AAudioStream_getBufferSizeInFrames(stream); trackHolder->gain = kMaxTrackGain; trackHolder->buffer = new float[trackHolder->bufferLength](); @@ -137,8 +134,7 @@ void BtifAvrcpAudioTrackStart(void* handle) { } BtifAvrcpAudioTrack* trackHolder = static_cast(handle); log::assert_that(trackHolder != NULL, "assert failed: trackHolder != NULL"); - log::assert_that(trackHolder->stream != NULL, - "assert failed: trackHolder->stream != NULL"); + log::assert_that(trackHolder->stream != NULL, "assert failed: trackHolder->stream != NULL"); log::verbose("Track.cpp: btStartTrack"); AAudioStream_requestStart(trackHolder->stream); } @@ -191,8 +187,7 @@ void BtifAvrcpSetAudioTrackGain(void* handle, float gain) { if (trackHolder != NULL) { const float clampedGain = std::clamp(gain, kMinTrackGain, kMaxTrackGain); if (clampedGain != gain) { - log::warn("Out of bounds gain set. Clamping the gain from :{:f} to {:f}", - gain, clampedGain); + log::warn("Out of bounds gain set. Clamping the gain from :{:f} to {:f}", gain, clampedGain); } trackHolder->gain = clampedGain; log::info("Avrcp audio track gain is set to {:f}", trackHolder->gain); @@ -257,27 +252,22 @@ static size_t transcodeToPcmFloat(uint8_t* buffer, size_t length, constexpr int64_t kTimeoutNanos = 100 * 1000 * 1000; // 100 ms -int BtifAvrcpAudioTrackWriteData(void* handle, void* audioBuffer, - int bufferLength) { +int BtifAvrcpAudioTrackWriteData(void* handle, void* audioBuffer, int bufferLength) { BtifAvrcpAudioTrack* trackHolder = static_cast(handle); log::assert_that(trackHolder != NULL, "assert failed: trackHolder != NULL"); - log::assert_that(trackHolder->stream != NULL, - "assert failed: trackHolder->stream != NULL"); + log::assert_that(trackHolder->stream != NULL, "assert failed: trackHolder->stream != NULL"); aaudio_result_t retval = -1; size_t sampleSize = sampleSizeFor(trackHolder); int transcodedCount = 0; do { - transcodedCount += - transcodeToPcmFloat(((uint8_t*)audioBuffer) + transcodedCount, - bufferLength - transcodedCount, trackHolder); - - retval = AAudioStream_write( - trackHolder->stream, trackHolder->buffer, - transcodedCount / (sampleSize * trackHolder->channelCount), - kTimeoutNanos); - log::verbose("Track.cpp: btWriteData len = {} ret = {}", bufferLength, - retval); + transcodedCount += transcodeToPcmFloat(((uint8_t*)audioBuffer) + transcodedCount, + bufferLength - transcodedCount, trackHolder); + + retval = AAudioStream_write(trackHolder->stream, trackHolder->buffer, + transcodedCount / (sampleSize * trackHolder->channelCount), + kTimeoutNanos); + log::verbose("Track.cpp: btWriteData len = {} ret = {}", bufferLength, retval); } while (transcodedCount < bufferLength); return transcodedCount; diff --git a/system/btif/src/btif_avrcp_audio_track_linux.cc b/system/btif/src/btif_avrcp_audio_track_linux.cc index ea3521234e7..45dd71d5060 100644 --- a/system/btif/src/btif_avrcp_audio_track_linux.cc +++ b/system/btif/src/btif_avrcp_audio_track_linux.cc @@ -16,8 +16,7 @@ #include "btif_avrcp_audio_track.h" -void* BtifAvrcpAudioTrackCreate(int trackFreq, int bits_per_sample, - int channelType) { +void* BtifAvrcpAudioTrackCreate(int trackFreq, int bits_per_sample, int channelType) { return nullptr; } @@ -31,7 +30,4 @@ void BtifAvrcpAudioTrackPause(void* handle) {} void BtifAvrcpSetAudioTrackGain(void* handle, float gain) {} -int BtifAvrcpAudioTrackWriteData(void* handle, void* audioBuffer, - int bufferlen) { - return 0; -} +int BtifAvrcpAudioTrackWriteData(void* handle, void* audioBuffer, int bufferlen) { return 0; } diff --git a/system/btif/src/btif_bqr.cc b/system/btif/src/btif_bqr.cc index 25efd5df4ce..b46ac710886 100644 --- a/system/btif/src/btif_bqr.cc +++ b/system/btif/src/btif_bqr.cc @@ -63,13 +63,12 @@ namespace { common::PostableContext* to_bind_ = nullptr; } -void BqrVseSubEvt::ParseBqrLinkQualityEvt(uint8_t length, - const uint8_t* p_param_buf) { +void BqrVseSubEvt::ParseBqrLinkQualityEvt(uint8_t length, const uint8_t* p_param_buf) { if (length < kLinkQualityParamTotalLen) { log::fatal( - "Parameter total length: {} is abnormal. It shall be not shorter than: " - "{}", - length, kLinkQualityParamTotalLen); + "Parameter total length: {} is abnormal. It shall be not shorter than: " + "{}", + length, kLinkQualityParamTotalLen); return; } @@ -80,13 +79,10 @@ void BqrVseSubEvt::ParseBqrLinkQualityEvt(uint8_t length, STREAM_TO_INT8(bqr_link_quality_event_.tx_power_level, p_param_buf); STREAM_TO_INT8(bqr_link_quality_event_.rssi, p_param_buf); STREAM_TO_UINT8(bqr_link_quality_event_.snr, p_param_buf); - STREAM_TO_UINT8(bqr_link_quality_event_.unused_afh_channel_count, - p_param_buf); - STREAM_TO_UINT8(bqr_link_quality_event_.afh_select_unideal_channel_count, - p_param_buf); + STREAM_TO_UINT8(bqr_link_quality_event_.unused_afh_channel_count, p_param_buf); + STREAM_TO_UINT8(bqr_link_quality_event_.afh_select_unideal_channel_count, p_param_buf); STREAM_TO_UINT16(bqr_link_quality_event_.lsto, p_param_buf); - STREAM_TO_UINT32(bqr_link_quality_event_.connection_piconet_clock, - p_param_buf); + STREAM_TO_UINT32(bqr_link_quality_event_.connection_piconet_clock, p_param_buf); STREAM_TO_UINT32(bqr_link_quality_event_.retransmission_count, p_param_buf); STREAM_TO_UINT32(bqr_link_quality_event_.no_rx_count, p_param_buf); STREAM_TO_UINT32(bqr_link_quality_event_.nak_count, p_param_buf); @@ -97,55 +93,50 @@ void BqrVseSubEvt::ParseBqrLinkQualityEvt(uint8_t length, STREAM_TO_UINT32(bqr_link_quality_event_.buffer_underflow_bytes, p_param_buf); if (vendor_cap_supported_version >= kBqrVersion5_0) { - if (length < kLinkQualityParamTotalLen + kISOLinkQualityParamTotalLen + - kVersion5_0ParamsTotalLen) { + if (length < + kLinkQualityParamTotalLen + kISOLinkQualityParamTotalLen + kVersion5_0ParamsTotalLen) { log::warn( - "Parameter total length: {} is abnormal. " - "vendor_cap_supported_version: {} (>= kBqrVersion5_0={}), It should " - "not be shorter than: {}", - length, vendor_cap_supported_version, kBqrVersion5_0, - kLinkQualityParamTotalLen + kISOLinkQualityParamTotalLen + - kVersion5_0ParamsTotalLen); + "Parameter total length: {} is abnormal. " + "vendor_cap_supported_version: {} (>= kBqrVersion5_0={}), It should " + "not be shorter than: {}", + length, vendor_cap_supported_version, kBqrVersion5_0, + kLinkQualityParamTotalLen + kISOLinkQualityParamTotalLen + kVersion5_0ParamsTotalLen); } else { STREAM_TO_BDADDR(bqr_link_quality_event_.bdaddr, p_param_buf); - STREAM_TO_UINT8(bqr_link_quality_event_.cal_failed_item_count, - p_param_buf); + STREAM_TO_UINT8(bqr_link_quality_event_.cal_failed_item_count, p_param_buf); } } if (vendor_cap_supported_version >= kBqrIsoVersion) { if (length < kLinkQualityParamTotalLen + kISOLinkQualityParamTotalLen) { log::warn( - "Parameter total length: {} is abnormal. " - "vendor_cap_supported_version: {} (>= kBqrIsoVersion={}), It should " - "not be shorter than: {}", - length, vendor_cap_supported_version, kBqrIsoVersion, - kLinkQualityParamTotalLen + kISOLinkQualityParamTotalLen); + "Parameter total length: {} is abnormal. " + "vendor_cap_supported_version: {} (>= kBqrIsoVersion={}), It should " + "not be shorter than: {}", + length, vendor_cap_supported_version, kBqrIsoVersion, + kLinkQualityParamTotalLen + kISOLinkQualityParamTotalLen); } else { STREAM_TO_UINT32(bqr_link_quality_event_.tx_total_packets, p_param_buf); STREAM_TO_UINT32(bqr_link_quality_event_.tx_unacked_packets, p_param_buf); STREAM_TO_UINT32(bqr_link_quality_event_.tx_flushed_packets, p_param_buf); - STREAM_TO_UINT32(bqr_link_quality_event_.tx_last_subevent_packets, - p_param_buf); + STREAM_TO_UINT32(bqr_link_quality_event_.tx_last_subevent_packets, p_param_buf); STREAM_TO_UINT32(bqr_link_quality_event_.crc_error_packets, p_param_buf); - STREAM_TO_UINT32(bqr_link_quality_event_.rx_duplicate_packets, - p_param_buf); + STREAM_TO_UINT32(bqr_link_quality_event_.rx_duplicate_packets, p_param_buf); } } if (vendor_cap_supported_version >= kBqrVersion6_0) { if (length < kLinkQualityParamTotalLen + kISOLinkQualityParamTotalLen + - kVersion5_0ParamsTotalLen + kVersion6_0ParamsTotalLen) { + kVersion5_0ParamsTotalLen + kVersion6_0ParamsTotalLen) { log::warn( - "Parameter total length: {} is abnormal. " - "vendor_cap_supported_version: {} (>= kBqrVersion6_0={}), It should " - "not be shorter than: {}", - length, vendor_cap_supported_version, kBqrVersion6_0, - kLinkQualityParamTotalLen + kISOLinkQualityParamTotalLen + - kVersion5_0ParamsTotalLen + kVersion6_0ParamsTotalLen); + "Parameter total length: {} is abnormal. " + "vendor_cap_supported_version: {} (>= kBqrVersion6_0={}), It should " + "not be shorter than: {}", + length, vendor_cap_supported_version, kBqrVersion6_0, + kLinkQualityParamTotalLen + kISOLinkQualityParamTotalLen + kVersion5_0ParamsTotalLen + + kVersion6_0ParamsTotalLen); } else { - STREAM_TO_UINT32(bqr_link_quality_event_.rx_unreceived_packets, - p_param_buf); + STREAM_TO_UINT32(bqr_link_quality_event_.rx_unreceived_packets, p_param_buf); STREAM_TO_UINT16(bqr_link_quality_event_.coex_info_mask, p_param_buf); } } @@ -154,8 +145,7 @@ void BqrVseSubEvt::ParseBqrLinkQualityEvt(uint8_t length, localtime_r(&now, &tm_timestamp_); } -void BqrVseSubEvt::WriteLmpLlTraceLogFile(int fd, uint8_t length, - const uint8_t* p_param_buf) { +void BqrVseSubEvt::WriteLmpLlTraceLogFile(int fd, uint8_t length, const uint8_t* p_param_buf) { const auto now = system_clock::to_time_t(system_clock::now()); localtime_r(&now, &tm_timestamp_); @@ -167,12 +157,10 @@ void BqrVseSubEvt::WriteLmpLlTraceLogFile(int fd, uint8_t length, std::stringstream ss_log; ss_log << "\n" << std::put_time(&tm_timestamp_, "%m-%d %H:%M:%S ") - << "Handle: " << loghex(bqr_log_dump_event_.connection_handle) - << " VSP: "; + << "Handle: " << loghex(bqr_log_dump_event_.connection_handle) << " VSP: "; TEMP_FAILURE_RETRY(write(fd, ss_log.str().c_str(), ss_log.str().size())); - TEMP_FAILURE_RETRY( - write(fd, bqr_log_dump_event_.vendor_specific_parameter, length)); + TEMP_FAILURE_RETRY(write(fd, bqr_log_dump_event_.vendor_specific_parameter, length)); LmpLlMessageTraceCounter++; } @@ -189,12 +177,10 @@ void BqrVseSubEvt::WriteBtSchedulingTraceLogFile(int fd, uint8_t length, std::stringstream ss_log; ss_log << "\n" << std::put_time(&tm_timestamp_, "%m-%d %H:%M:%S ") - << "Handle: " << loghex(bqr_log_dump_event_.connection_handle) - << " VSP: "; + << "Handle: " << loghex(bqr_log_dump_event_.connection_handle) << " VSP: "; TEMP_FAILURE_RETRY(write(fd, ss_log.str().c_str(), ss_log.str().size())); - TEMP_FAILURE_RETRY( - write(fd, bqr_log_dump_event_.vendor_specific_parameter, length)); + TEMP_FAILURE_RETRY(write(fd, bqr_log_dump_event_.vendor_specific_parameter, length)); BtSchedulingTraceCounter++; } @@ -204,45 +190,31 @@ static std::string PacketTypeToString(uint8_t packet_type); std::string BqrVseSubEvt::ToString() const { std::stringstream ss; ss << QualityReportIdToString(bqr_link_quality_event_.quality_report_id) - << ", Handle: " << loghex(bqr_link_quality_event_.connection_handle) - << ", " << PacketTypeToString(bqr_link_quality_event_.packet_types) << ", " - << ((bqr_link_quality_event_.connection_role == 0) ? "Central" - : "Peripheral ") + << ", Handle: " << loghex(bqr_link_quality_event_.connection_handle) << ", " + << PacketTypeToString(bqr_link_quality_event_.packet_types) << ", " + << ((bqr_link_quality_event_.connection_role == 0) ? "Central" : "Peripheral ") << ", PwLv: " << std::to_string(bqr_link_quality_event_.tx_power_level) << ", RSSI: " << std::to_string(bqr_link_quality_event_.rssi) << ", SNR: " << std::to_string(bqr_link_quality_event_.snr) - << ", UnusedCh: " - << std::to_string(bqr_link_quality_event_.unused_afh_channel_count) - << ", UnidealCh: " - << std::to_string(bqr_link_quality_event_.afh_select_unideal_channel_count) - << ", ReTx: " - << std::to_string(bqr_link_quality_event_.retransmission_count) + << ", UnusedCh: " << std::to_string(bqr_link_quality_event_.unused_afh_channel_count) + << ", UnidealCh: " << std::to_string(bqr_link_quality_event_.afh_select_unideal_channel_count) + << ", ReTx: " << std::to_string(bqr_link_quality_event_.retransmission_count) << ", NoRX: " << std::to_string(bqr_link_quality_event_.no_rx_count) << ", NAK: " << std::to_string(bqr_link_quality_event_.nak_count) << ", FlowOff: " << std::to_string(bqr_link_quality_event_.flow_off_count) - << ", OverFlow: " - << std::to_string(bqr_link_quality_event_.buffer_overflow_bytes) - << ", UndFlow: " - << std::to_string(bqr_link_quality_event_.buffer_underflow_bytes); + << ", OverFlow: " << std::to_string(bqr_link_quality_event_.buffer_overflow_bytes) + << ", UndFlow: " << std::to_string(bqr_link_quality_event_.buffer_underflow_bytes); if (vendor_cap_supported_version >= kBqrVersion5_0) { - ss << ", RemoteDevAddr: " - << bqr_link_quality_event_.bdaddr.ToColonSepHexString() - << ", CalFailedItems: " - << std::to_string(bqr_link_quality_event_.cal_failed_item_count); + ss << ", RemoteDevAddr: " << bqr_link_quality_event_.bdaddr.ToColonSepHexString() + << ", CalFailedItems: " << std::to_string(bqr_link_quality_event_.cal_failed_item_count); } if (vendor_cap_supported_version >= kBqrIsoVersion) { - ss << ", TxTotal: " - << std::to_string(bqr_link_quality_event_.tx_total_packets) - << ", TxUnAcked: " - << std::to_string(bqr_link_quality_event_.tx_unacked_packets) - << ", TxFlushed: " - << std::to_string(bqr_link_quality_event_.tx_flushed_packets) - << ", TxLastSubEvent: " - << std::to_string(bqr_link_quality_event_.tx_last_subevent_packets) - << ", CRCError: " - << std::to_string(bqr_link_quality_event_.crc_error_packets) - << ", RxDuplicate: " - << std::to_string(bqr_link_quality_event_.rx_duplicate_packets); + ss << ", TxTotal: " << std::to_string(bqr_link_quality_event_.tx_total_packets) + << ", TxUnAcked: " << std::to_string(bqr_link_quality_event_.tx_unacked_packets) + << ", TxFlushed: " << std::to_string(bqr_link_quality_event_.tx_flushed_packets) + << ", TxLastSubEvent: " << std::to_string(bqr_link_quality_event_.tx_last_subevent_packets) + << ", CRCError: " << std::to_string(bqr_link_quality_event_.crc_error_packets) + << ", RxDuplicate: " << std::to_string(bqr_link_quality_event_.rx_duplicate_packets); } return ss.str(); @@ -364,9 +336,9 @@ void EnableBtQualityReport(common::PostableContext* to_bind) { if (strlen(bqr_prop_evtmask) == 0 || strlen(bqr_prop_interval_ms) == 0) { log::warn( - "Bluetooth Quality Report is disabled. bqr_prop_evtmask: {}, " - "bqr_prop_interval_ms: {}", - bqr_prop_evtmask, bqr_prop_interval_ms); + "Bluetooth Quality Report is disabled. bqr_prop_evtmask: {}, " + "bqr_prop_interval_ms: {}", + bqr_prop_evtmask, bqr_prop_interval_ms); return; } @@ -374,16 +346,11 @@ void EnableBtQualityReport(common::PostableContext* to_bind) { if (to_bind) { bqr_config.report_action = REPORT_ACTION_ADD; - bqr_config.quality_event_mask = - static_cast(atoi(bqr_prop_evtmask)); - bqr_config.minimum_report_interval_ms = - static_cast(atoi(bqr_prop_interval_ms)); - bqr_config.vnd_quality_mask = - static_cast(atoi(bqr_prop_vnd_quality_mask)); - bqr_config.vnd_trace_mask = - static_cast(atoi(bqr_prop_vnd_trace_mask)); - bqr_config.report_interval_multiple = - static_cast(atoi(bqr_prop_interval_multiple)); + bqr_config.quality_event_mask = static_cast(atoi(bqr_prop_evtmask)); + bqr_config.minimum_report_interval_ms = static_cast(atoi(bqr_prop_interval_ms)); + bqr_config.vnd_quality_mask = static_cast(atoi(bqr_prop_vnd_quality_mask)); + bqr_config.vnd_trace_mask = static_cast(atoi(bqr_prop_vnd_trace_mask)); + bqr_config.report_interval_multiple = static_cast(atoi(bqr_prop_interval_multiple)); register_vse(); kpBqrEventQueue.Clear(); } else { @@ -401,10 +368,10 @@ void EnableBtQualityReport(common::PostableContext* to_bind) { vendor_cap_supported_version = cmn_vsc_cb.version_supported; log::info( - "Event Mask: 0x{:x}, Interval: {}, Multiple: {}, " - "vendor_cap_supported_version: {}", - bqr_config.quality_event_mask, bqr_config.minimum_report_interval_ms, - bqr_config.report_interval_multiple, vendor_cap_supported_version); + "Event Mask: 0x{:x}, Interval: {}, Multiple: {}, " + "vendor_cap_supported_version: {}", + bqr_config.quality_event_mask, bqr_config.minimum_report_interval_ms, + bqr_config.report_interval_multiple, vendor_cap_supported_version); ConfigureBqr(bqr_config); } @@ -419,11 +386,10 @@ void ConfigureBqr(const BqrConfiguration& bqr_config) { bqr_config.quality_event_mask > kQualityEventMaskAll || bqr_config.minimum_report_interval_ms > kMinReportIntervalMaxMs) { log::fatal( - "Invalid Parameter, Action: {}, Mask: 0x{:x}, Interval: {} Multiple: " - "{}", - bqr_config.report_action, bqr_config.quality_event_mask, - bqr_config.minimum_report_interval_ms, - bqr_config.report_interval_multiple); + "Invalid Parameter, Action: {}, Mask: 0x{:x}, Interval: {} Multiple: " + "{}", + bqr_config.report_action, bqr_config.quality_event_mask, + bqr_config.minimum_report_interval_ms, bqr_config.report_interval_multiple); return; } else { if (bqr_config.report_action > REPORT_ACTION_CLEAR || @@ -438,10 +404,8 @@ void ConfigureBqr(const BqrConfiguration& bqr_config) { } log::info("Action: 0x{:x}, Mask: 0x{:x}, Interval: {} Multiple: {}", - static_cast(bqr_config.report_action), - bqr_config.quality_event_mask, - bqr_config.minimum_report_interval_ms, - bqr_config.report_interval_multiple); + static_cast(bqr_config.report_action), bqr_config.quality_event_mask, + bqr_config.minimum_report_interval_ms, bqr_config.report_interval_multiple); auto payload = std::make_unique(); payload->AddOctets1(bqr_config.report_action); @@ -456,9 +420,8 @@ void ConfigureBqr(const BqrConfiguration& bqr_config) { } shim::GetHciLayer()->EnqueueCommand( - hci::CommandBuilder::Create(hci::OpCode::CONTROLLER_BQR, - std::move(payload)), - to_bind_->BindOnce(BqrVscCompleteCallback)); + hci::CommandBuilder::Create(hci::OpCode::CONTROLLER_BQR, std::move(payload)), + to_bind_->BindOnce(BqrVscCompleteCallback)); } static void ConfigureBqrCmpl(uint32_t current_evt_mask); @@ -469,12 +432,10 @@ static void ConfigureBqrCmpl(uint32_t current_evt_mask); // @param p_vsc_cmpl_params A pointer to the parameters contained in the vendor // specific command complete event. static void BqrVscCompleteCallback(hci::CommandCompleteView complete) { - std::vector payload_vector{complete.GetPayload().begin(), - complete.GetPayload().end()}; - tBTM_VSC_CMPL vsc_cmpl_params = { - .opcode = static_cast(complete.GetCommandOpCode()), - .param_len = static_cast(payload_vector.size()), - .p_param_buf = payload_vector.data()}; + std::vector payload_vector{complete.GetPayload().begin(), complete.GetPayload().end()}; + tBTM_VSC_CMPL vsc_cmpl_params = {.opcode = static_cast(complete.GetCommandOpCode()), + .param_len = static_cast(payload_vector.size()), + .p_param_buf = payload_vector.data()}; tBTM_VSC_CMPL* p_vsc_cmpl_params = &vsc_cmpl_params; if (p_vsc_cmpl_params->param_len < 1) { @@ -510,8 +471,7 @@ static void BqrVscCompleteCallback(hci::CommandCompleteView complete) { } if (p_vsc_cmpl_params->param_len != command_complete_param_len) { - log::fatal("The length of returned parameters is incorrect: {}", - p_vsc_cmpl_params->param_len); + log::fatal("The length of returned parameters is incorrect: {}", p_vsc_cmpl_params->param_len); return; } @@ -528,10 +488,10 @@ static void BqrVscCompleteCallback(hci::CommandCompleteView complete) { } log::info( - "current event mask: 0x{:x}, vendor quality: 0x{:x}, vendor trace: " - "0x{:x}, report interval: 0x{:x}", - current_quality_event_mask, current_vnd_quality_mask, - current_vnd_trace_mask, bqr_report_interval); + "current event mask: 0x{:x}, vendor quality: 0x{:x}, vendor trace: " + "0x{:x}, report interval: 0x{:x}", + current_quality_event_mask, current_vnd_quality_mask, current_vnd_trace_mask, + bqr_report_interval); ConfigureBqrCmpl(current_quality_event_mask); } @@ -544,11 +504,10 @@ void ConfigBqrA2dpScoThreshold() { char bqr_prop_threshold[PROPERTY_VALUE_MAX] = {0}; osi_property_get(kpPropertyChoppyThreshold, bqr_prop_threshold, ""); - sscanf(bqr_prop_threshold, "%hu,%hu", &a2dp_choppy_threshold, - &sco_choppy_threshold); + sscanf(bqr_prop_threshold, "%hu,%hu", &a2dp_choppy_threshold, &sco_choppy_threshold); - log::info("a2dp_choppy_threshold: {}, sco_choppy_threshold: {}", - a2dp_choppy_threshold, sco_choppy_threshold); + log::info("a2dp_choppy_threshold: {}, sco_choppy_threshold: {}", a2dp_choppy_threshold, + sco_choppy_threshold); auto payload = std::make_unique(); payload->AddOctets1(sub_opcode); @@ -568,9 +527,9 @@ void ConfigBqrA2dpScoThreshold() { payload->AddOctets2(sco_choppy_threshold == 0 ? 1 : sco_choppy_threshold); shim::GetHciLayer()->EnqueueCommand( - hci::CommandBuilder::Create( - static_cast(HCI_VS_HOST_LOG_OPCODE), std::move(payload)), - to_bind_->BindOnce([](hci::CommandCompleteView) {})); + hci::CommandBuilder::Create(static_cast(HCI_VS_HOST_LOG_OPCODE), + std::move(payload)), + to_bind_->BindOnce([](hci::CommandCompleteView) {})); } // Invoked on completion of Bluetooth Quality Report configuration. Then it will @@ -599,8 +558,7 @@ static void ConfigureBqrCmpl(uint32_t current_evt_mask) { } } -static void AddLinkQualityEventToQueue(uint8_t length, - const uint8_t* p_link_quality_event); +static void AddLinkQualityEventToQueue(uint8_t length, const uint8_t* p_link_quality_event); // Categorize the incoming Bluetooth Quality Report. // // @param length Lengths of the quality report sent from the Bluetooth @@ -623,9 +581,9 @@ static void CategorizeBqrEvent(uint8_t length, const uint8_t* p_bqr_event) { case QUALITY_REPORT_ID_CONNECT_FAIL: if (length < kLinkQualityParamTotalLen) { log::fatal( - "Parameter total length: {} is abnormal. It shall be not shorter " - "than: {}", - length, kLinkQualityParamTotalLen); + "Parameter total length: {} is abnormal. It shall be not shorter " + "than: {}", + length, kLinkQualityParamTotalLen); return; } @@ -653,66 +611,60 @@ static void CategorizeBqrEvent(uint8_t length, const uint8_t* p_bqr_event) { // // @param length Lengths of the Link Quality related BQR event. // @param p_link_quality_event A pointer to the Link Quality related BQR event. -static void AddLinkQualityEventToQueue(uint8_t length, - const uint8_t* p_link_quality_event) { +static void AddLinkQualityEventToQueue(uint8_t length, const uint8_t* p_link_quality_event) { std::unique_ptr p_bqr_event = std::make_unique(); RawAddress bd_addr; p_bqr_event->ParseBqrLinkQualityEvt(length, p_link_quality_event); GetInterfaceToProfiles()->events->invoke_link_quality_report_cb( - bluetooth::common::time_get_os_boottime_ms(), - p_bqr_event->bqr_link_quality_event_.quality_report_id, - p_bqr_event->bqr_link_quality_event_.rssi, - p_bqr_event->bqr_link_quality_event_.snr, - p_bqr_event->bqr_link_quality_event_.retransmission_count, - p_bqr_event->bqr_link_quality_event_.no_rx_count, - p_bqr_event->bqr_link_quality_event_.nak_count); + bluetooth::common::time_get_os_boottime_ms(), + p_bqr_event->bqr_link_quality_event_.quality_report_id, + p_bqr_event->bqr_link_quality_event_.rssi, p_bqr_event->bqr_link_quality_event_.snr, + p_bqr_event->bqr_link_quality_event_.retransmission_count, + p_bqr_event->bqr_link_quality_event_.no_rx_count, + p_bqr_event->bqr_link_quality_event_.nak_count); #ifdef __ANDROID__ int ret = stats_write( - BLUETOOTH_QUALITY_REPORT_REPORTED, - p_bqr_event->bqr_link_quality_event_.quality_report_id, - p_bqr_event->bqr_link_quality_event_.packet_types, - p_bqr_event->bqr_link_quality_event_.connection_handle, - p_bqr_event->bqr_link_quality_event_.connection_role, - p_bqr_event->bqr_link_quality_event_.tx_power_level, - p_bqr_event->bqr_link_quality_event_.rssi, - p_bqr_event->bqr_link_quality_event_.snr, - p_bqr_event->bqr_link_quality_event_.unused_afh_channel_count, - p_bqr_event->bqr_link_quality_event_.afh_select_unideal_channel_count, - p_bqr_event->bqr_link_quality_event_.lsto, - p_bqr_event->bqr_link_quality_event_.connection_piconet_clock, - p_bqr_event->bqr_link_quality_event_.retransmission_count, - p_bqr_event->bqr_link_quality_event_.no_rx_count, - p_bqr_event->bqr_link_quality_event_.nak_count, - p_bqr_event->bqr_link_quality_event_.last_tx_ack_timestamp, - p_bqr_event->bqr_link_quality_event_.flow_off_count, - p_bqr_event->bqr_link_quality_event_.last_flow_on_timestamp, - p_bqr_event->bqr_link_quality_event_.buffer_overflow_bytes, - p_bqr_event->bqr_link_quality_event_.buffer_underflow_bytes); + BLUETOOTH_QUALITY_REPORT_REPORTED, p_bqr_event->bqr_link_quality_event_.quality_report_id, + p_bqr_event->bqr_link_quality_event_.packet_types, + p_bqr_event->bqr_link_quality_event_.connection_handle, + p_bqr_event->bqr_link_quality_event_.connection_role, + p_bqr_event->bqr_link_quality_event_.tx_power_level, + p_bqr_event->bqr_link_quality_event_.rssi, p_bqr_event->bqr_link_quality_event_.snr, + p_bqr_event->bqr_link_quality_event_.unused_afh_channel_count, + p_bqr_event->bqr_link_quality_event_.afh_select_unideal_channel_count, + p_bqr_event->bqr_link_quality_event_.lsto, + p_bqr_event->bqr_link_quality_event_.connection_piconet_clock, + p_bqr_event->bqr_link_quality_event_.retransmission_count, + p_bqr_event->bqr_link_quality_event_.no_rx_count, + p_bqr_event->bqr_link_quality_event_.nak_count, + p_bqr_event->bqr_link_quality_event_.last_tx_ack_timestamp, + p_bqr_event->bqr_link_quality_event_.flow_off_count, + p_bqr_event->bqr_link_quality_event_.last_flow_on_timestamp, + p_bqr_event->bqr_link_quality_event_.buffer_overflow_bytes, + p_bqr_event->bqr_link_quality_event_.buffer_underflow_bytes); if (ret < 0) { log::warn("failed to log BQR event to statsd, error {}", ret); } #else // TODO(abps) Metrics for non-Android build #endif - BluetoothQualityReportInterface* bqrItf = - getBluetoothQualityReportInterface(); + BluetoothQualityReportInterface* bqrItf = getBluetoothQualityReportInterface(); if (bqrItf != NULL) { bd_addr = p_bqr_event->bqr_link_quality_event_.bdaddr; if (bd_addr.IsEmpty()) { - tBTM_SEC_DEV_REC* dev = btm_find_dev_by_handle( - p_bqr_event->bqr_link_quality_event_.connection_handle); + tBTM_SEC_DEV_REC* dev = + btm_find_dev_by_handle(p_bqr_event->bqr_link_quality_event_.connection_handle); if (dev != NULL) { bd_addr = dev->RemoteAddress(); } } if (!bd_addr.IsEmpty()) { - bqrItf->bqr_delivery_event(bd_addr, (uint8_t*)p_link_quality_event, - length); + bqrItf->bqr_delivery_event(bd_addr, (uint8_t*)p_link_quality_event, length); } else { log::warn("failed to deliver BQR, bdaddr is empty"); } @@ -729,17 +681,14 @@ static int OpenLmpLlTraceLogFile(); // // @param length Lengths of the LMP/LL message trace event. // @param p_lmp_ll_message_event A pointer to the LMP/LL message trace event. -static void DumpLmpLlMessage(uint8_t length, - const uint8_t* p_lmp_ll_message_event) { +static void DumpLmpLlMessage(uint8_t length, const uint8_t* p_lmp_ll_message_event) { std::unique_ptr p_bqr_event = std::make_unique(); - if (LmpLlMessageTraceLogFd == INVALID_FD || - LmpLlMessageTraceCounter >= kLogDumpEventPerFile) { + if (LmpLlMessageTraceLogFd == INVALID_FD || LmpLlMessageTraceCounter >= kLogDumpEventPerFile) { LmpLlMessageTraceLogFd = OpenLmpLlTraceLogFile(); } if (LmpLlMessageTraceLogFd != INVALID_FD) { - p_bqr_event->WriteLmpLlTraceLogFile(LmpLlMessageTraceLogFd, length, - p_lmp_ll_message_event); + p_bqr_event->WriteLmpLlTraceLogFile(LmpLlMessageTraceLogFd, length, p_lmp_ll_message_event); } } @@ -747,20 +696,17 @@ static void DumpLmpLlMessage(uint8_t length, // // @return a file descriptor of the LMP/LL message trace log file. static int OpenLmpLlTraceLogFile() { - if (rename(kpLmpLlMessageTraceLogPath, kpLmpLlMessageTraceLastLogPath) != 0 && - errno != ENOENT) { + if (rename(kpLmpLlMessageTraceLogPath, kpLmpLlMessageTraceLastLogPath) != 0 && errno != ENOENT) { log::error("Unable to rename '{}' to '{}' : {}", kpLmpLlMessageTraceLogPath, kpLmpLlMessageTraceLastLogPath, strerror(errno)); } mode_t prevmask = umask(0); - int logfile_fd = - open(kpLmpLlMessageTraceLogPath, O_WRONLY | O_CREAT | O_TRUNC, - S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH); + int logfile_fd = open(kpLmpLlMessageTraceLogPath, O_WRONLY | O_CREAT | O_TRUNC, + S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH); umask(prevmask); if (logfile_fd == INVALID_FD) { - log::error("Unable to open '{}' : {}", kpLmpLlMessageTraceLogPath, - strerror(errno)); + log::error("Unable to open '{}' : {}", kpLmpLlMessageTraceLogPath, strerror(errno)); } else { LmpLlMessageTraceCounter = 0; } @@ -775,12 +721,10 @@ static int OpenBtSchedulingTraceLogFile(); // event. // @param p_bt_scheduling_event A pointer to the Bluetooth Multi-profile/Coex // scheduling trace event. -static void DumpBtScheduling(uint8_t length, - const uint8_t* p_bt_scheduling_event) { +static void DumpBtScheduling(uint8_t length, const uint8_t* p_bt_scheduling_event) { std::unique_ptr p_bqr_event = std::make_unique(); - if (BtSchedulingTraceLogFd == INVALID_FD || - BtSchedulingTraceCounter == kLogDumpEventPerFile) { + if (BtSchedulingTraceLogFd == INVALID_FD || BtSchedulingTraceCounter == kLogDumpEventPerFile) { BtSchedulingTraceLogFd = OpenBtSchedulingTraceLogFile(); } if (BtSchedulingTraceLogFd != INVALID_FD) { @@ -794,20 +738,17 @@ static void DumpBtScheduling(uint8_t length, // @return a file descriptor of the Bluetooth Multi-profile/Coex scheduling // trace log file. static int OpenBtSchedulingTraceLogFile() { - if (rename(kpBtSchedulingTraceLogPath, kpBtSchedulingTraceLastLogPath) != 0 && - errno != ENOENT) { + if (rename(kpBtSchedulingTraceLogPath, kpBtSchedulingTraceLastLogPath) != 0 && errno != ENOENT) { log::error("Unable to rename '{}' to '{}' : {}", kpBtSchedulingTraceLogPath, kpBtSchedulingTraceLastLogPath, strerror(errno)); } mode_t prevmask = umask(0); - int logfile_fd = - open(kpBtSchedulingTraceLogPath, O_WRONLY | O_CREAT | O_TRUNC, - S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH); + int logfile_fd = open(kpBtSchedulingTraceLogPath, O_WRONLY | O_CREAT | O_TRUNC, + S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH); umask(prevmask); if (logfile_fd == INVALID_FD) { - log::error("Unable to open '{}' : {}", kpBtSchedulingTraceLogPath, - strerror(errno)); + log::error("Unable to open '{}' : {}", kpBtSchedulingTraceLogPath, strerror(errno)); } else { BtSchedulingTraceCounter = 0; } @@ -826,8 +767,7 @@ void DebugDump(int fd) { std::unique_ptr p_event(kpBqrEventQueue.Dequeue()); bool warning = (p_event->bqr_link_quality_event_.rssi < kCriWarnRssi || - p_event->bqr_link_quality_event_.unused_afh_channel_count > - kCriWarnUnusedCh); + p_event->bqr_link_quality_event_.unused_afh_channel_count > kCriWarnUnusedCh); std::stringstream ss_timestamp; ss_timestamp << std::put_time(&p_event->tm_timestamp_, "%m-%d %H:%M:%S"); @@ -839,10 +779,8 @@ void DebugDump(int fd) { dprintf(fd, "\n"); } -static void btif_get_remote_version(const RawAddress& bd_addr, - uint8_t& lmp_version, - uint16_t& manufacturer, - uint16_t& lmp_sub_version) { +static void btif_get_remote_version(const RawAddress& bd_addr, uint8_t& lmp_version, + uint16_t& manufacturer, uint16_t& lmp_sub_version) { bt_property_t prop; bt_remote_version_t info; uint8_t tmp_lmp_ver = 0; @@ -851,9 +789,8 @@ static void btif_get_remote_version(const RawAddress& bd_addr, tBTM_STATUS status; status = get_btm_client_interface().peer.BTM_ReadRemoteVersion( - bd_addr, &tmp_lmp_ver, &tmp_manufacturer, &tmp_lmp_subver); - if (status == BTM_SUCCESS && - (tmp_lmp_ver || tmp_manufacturer || tmp_lmp_subver)) { + bd_addr, &tmp_lmp_ver, &tmp_manufacturer, &tmp_lmp_subver); + if (status == BTM_SUCCESS && (tmp_lmp_ver || tmp_manufacturer || tmp_lmp_subver)) { lmp_version = tmp_lmp_ver; manufacturer = tmp_manufacturer; lmp_sub_version = tmp_lmp_subver; @@ -864,16 +801,14 @@ static void btif_get_remote_version(const RawAddress& bd_addr, prop.len = sizeof(bt_remote_version_t); prop.val = (void*)&info; - if (btif_storage_get_remote_device_property(&bd_addr, &prop) == - BT_STATUS_SUCCESS) { + if (btif_storage_get_remote_device_property(&bd_addr, &prop) == BT_STATUS_SUCCESS) { lmp_version = (uint8_t)info.version; manufacturer = (uint16_t)info.manufacturer; lmp_sub_version = (uint16_t)info.sub_ver; } } -class BluetoothQualityReportInterfaceImpl - : public bluetooth::bqr::BluetoothQualityReportInterface { +class BluetoothQualityReportInterfaceImpl : public bluetooth::bqr::BluetoothQualityReportInterface { ~BluetoothQualityReportInterfaceImpl() override = default; void init(BluetoothQualityReportCallbacks* callbacks) override { @@ -881,8 +816,7 @@ class BluetoothQualityReportInterfaceImpl this->callbacks = callbacks; } - void bqr_delivery_event(const RawAddress& bd_addr, - const uint8_t* bqr_raw_data, + void bqr_delivery_event(const RawAddress& bd_addr, const uint8_t* bqr_raw_data, uint32_t bqr_raw_data_len) override { if (bqr_raw_data == NULL) { log::error("bqr data is null"); @@ -890,14 +824,11 @@ class BluetoothQualityReportInterfaceImpl } std::vector raw_data; - raw_data.insert(raw_data.begin(), bqr_raw_data, - bqr_raw_data + bqr_raw_data_len); + raw_data.insert(raw_data.begin(), bqr_raw_data, bqr_raw_data + bqr_raw_data_len); if (vendor_cap_supported_version < kBqrVersion5_0 && - bqr_raw_data_len < - kLinkQualityParamTotalLen + kVersion5_0ParamsTotalLen) { - std::vector::iterator it = - raw_data.begin() + kLinkQualityParamTotalLen; + bqr_raw_data_len < kLinkQualityParamTotalLen + kVersion5_0ParamsTotalLen) { + std::vector::iterator it = raw_data.begin() + kLinkQualityParamTotalLen; /** * Insert zeros as remote address and calibration count * for BQR 5.0 incompatible devices @@ -910,36 +841,34 @@ class BluetoothQualityReportInterfaceImpl uint16_t manufacturer_id = 0; btif_get_remote_version(bd_addr, lmp_ver, manufacturer_id, lmp_subver); - log::info( - "len: {}, addr: {}, lmp_ver: {}, manufacturer_id: {}, lmp_subver: {}", - bqr_raw_data_len, bd_addr, lmp_ver, manufacturer_id, lmp_subver); + log::info("len: {}, addr: {}, lmp_ver: {}, manufacturer_id: {}, lmp_subver: {}", + bqr_raw_data_len, bd_addr, lmp_ver, manufacturer_id, lmp_subver); if (callbacks == nullptr) { log::error("callbacks is nullptr"); return; } - do_in_jni_thread(base::BindOnce( - &bluetooth::bqr::BluetoothQualityReportCallbacks::bqr_delivery_callback, - base::Unretained(callbacks), bd_addr, lmp_ver, lmp_subver, - manufacturer_id, std::move(raw_data))); + do_in_jni_thread( + base::BindOnce(&bluetooth::bqr::BluetoothQualityReportCallbacks::bqr_delivery_callback, + base::Unretained(callbacks), bd_addr, lmp_ver, lmp_subver, + manufacturer_id, std::move(raw_data))); } - private: +private: BluetoothQualityReportCallbacks* callbacks = nullptr; }; BluetoothQualityReportInterface* getBluetoothQualityReportInterface() { if (!bluetoothQualityReportInstance) { - bluetoothQualityReportInstance.reset( - new BluetoothQualityReportInterfaceImpl()); + bluetoothQualityReportInstance.reset(new BluetoothQualityReportInterfaceImpl()); } return bluetoothQualityReportInstance.get(); } static void vendor_specific_event_callback( - hci::VendorSpecificEventView vendor_specific_event_view) { + hci::VendorSpecificEventView vendor_specific_event_view) { auto bqr = hci::BqrEventView::CreateOptional(vendor_specific_event_view); if (!bqr) { return; @@ -981,13 +910,12 @@ static void vendor_specific_event_callback( void register_vse() { bluetooth::shim::GetHciLayer()->RegisterVendorSpecificEventHandler( - hci::VseSubeventCode::BQR_EVENT, - to_bind_->Bind(vendor_specific_event_callback)); + hci::VseSubeventCode::BQR_EVENT, to_bind_->Bind(vendor_specific_event_callback)); } void unregister_vse() { bluetooth::shim::GetHciLayer()->UnregisterVendorSpecificEventHandler( - hci::VseSubeventCode::BQR_EVENT); + hci::VseSubeventCode::BQR_EVENT); } namespace testing { diff --git a/system/btif/src/btif_config.cc b/system/btif/src/btif_config.cc index c57011678d9..6d6063498b7 100644 --- a/system/btif/src/btif_config.cc +++ b/system/btif/src/btif_config.cc @@ -58,9 +58,9 @@ using namespace bluetooth; static const std::string ENCRYPTED_STR = "encrypted"; static const std::string CONFIG_FILE_PREFIX = "bt_config-origin"; static const std::string CONFIG_FILE_HASH = "hash"; -static const std::string encrypt_key_name_list[] = { - "LinkKey", "LE_KEY_PENC", "LE_KEY_PID", "LE_KEY_LID", - "LE_KEY_PCSRK", "LE_KEY_LENC", "LE_KEY_LCSRK"}; +static const std::string encrypt_key_name_list[] = {"LinkKey", "LE_KEY_PENC", "LE_KEY_PID", + "LE_KEY_LID", "LE_KEY_PCSRK", "LE_KEY_LENC", + "LE_KEY_LCSRK"}; /** * Read metrics salt from config file, if salt is invalid or does not exist, @@ -69,16 +69,15 @@ static const std::string encrypt_key_name_list[] = { static void read_or_set_metrics_salt() { AddressObfuscator::Octet32 metrics_salt = {}; size_t metrics_salt_length = metrics_salt.size(); - if (!btif_config_get_bin(BTIF_STORAGE_SECTION_METRICS, - BTIF_STORAGE_KEY_METRICS_SALT_256BIT, + if (!btif_config_get_bin(BTIF_STORAGE_SECTION_METRICS, BTIF_STORAGE_KEY_METRICS_SALT_256BIT, metrics_salt.data(), &metrics_salt_length)) { log::warn("Failed to read metrics salt from config"); // Invalidate salt metrics_salt.fill(0); } if (metrics_salt_length != metrics_salt.size()) { - log::error("Metrics salt length incorrect, {} instead of {}", - metrics_salt_length, metrics_salt.size()); + log::error("Metrics salt length incorrect, {} instead of {}", metrics_salt_length, + metrics_salt.size()); // Invalidate salt metrics_salt.fill(0); } @@ -87,8 +86,7 @@ static void read_or_set_metrics_salt() { if (RAND_bytes(metrics_salt.data(), metrics_salt.size()) != 1) { log::fatal("Failed to generate salt for metrics"); } - if (!btif_config_set_bin(BTIF_STORAGE_SECTION_METRICS, - BTIF_STORAGE_KEY_METRICS_SALT_256BIT, + if (!btif_config_set_bin(BTIF_STORAGE_SECTION_METRICS, BTIF_STORAGE_KEY_METRICS_SALT_256BIT, metrics_salt.data(), metrics_salt.size())) { log::fatal("Failed to write metrics salt to config"); } @@ -127,18 +125,13 @@ static void init_metric_id_allocator() { } // Initialize MetricIdAllocator - MetricIdAllocator::Callback save_device_callback = - [](const RawAddress& address, const int id) { - return btif_config_set_int(address.ToString(), - BTIF_STORAGE_KEY_METRICS_ID_KEY, id); - }; - MetricIdAllocator::Callback forget_device_callback = - [](const RawAddress& address, const int id) { - return btif_config_remove(address.ToString(), - BTIF_STORAGE_KEY_METRICS_ID_KEY); - }; - if (!init_metric_id_allocator(paired_device_map, - std::move(save_device_callback), + MetricIdAllocator::Callback save_device_callback = [](const RawAddress& address, const int id) { + return btif_config_set_int(address.ToString(), BTIF_STORAGE_KEY_METRICS_ID_KEY, id); + }; + MetricIdAllocator::Callback forget_device_callback = [](const RawAddress& address, const int id) { + return btif_config_remove(address.ToString(), BTIF_STORAGE_KEY_METRICS_ID_KEY); + }; + if (!init_metric_id_allocator(paired_device_map, std::move(save_device_callback), std::move(forget_device_callback))) { log::fatal("Failed to initialize MetricIdAllocator"); } @@ -163,9 +156,7 @@ static future_t* init(void) { return future_new_immediate(FUTURE_SUCCESS); } -static future_t* shut_down(void) { - return future_new_immediate(FUTURE_SUCCESS); -} +static future_t* shut_down(void) { return future_new_immediate(FUTURE_SUCCESS); } static future_t* clean_up(void) { log::assert_that(bluetooth::shim::is_gd_stack_started_up(), @@ -183,27 +174,28 @@ EXPORT_SYMBOL module_t btif_config_module = {.name = BTIF_CONFIG_MODULE, .clean_up = clean_up}; bool btif_get_device_clockoffset(const RawAddress& bda, int* p_clock_offset) { - if (p_clock_offset == NULL) return false; + if (p_clock_offset == NULL) { + return false; + } std::string addrstr = bda.ToString(); const char* bd_addr_str = addrstr.c_str(); - if (!btif_config_get_int(bd_addr_str, BTIF_STORAGE_KEY_CLOCK_OFFSET, - p_clock_offset)) + if (!btif_config_get_int(bd_addr_str, BTIF_STORAGE_KEY_CLOCK_OFFSET, p_clock_offset)) { return false; + } log::debug("Device [{}] clock_offset {}", bda, *p_clock_offset); return true; } bool btif_set_device_clockoffset(const RawAddress& bda, int clock_offset) { - std::string addrstr = bda.ToString(); const char* bd_addr_str = addrstr.c_str(); - if (!btif_config_set_int(bd_addr_str, BTIF_STORAGE_KEY_CLOCK_OFFSET, - clock_offset)) + if (!btif_config_set_int(bd_addr_str, BTIF_STORAGE_KEY_CLOCK_OFFSET, clock_offset)) { return false; + } log::debug("Device [{}] clock_offset {}", bda, clock_offset); return true; @@ -215,29 +207,25 @@ bool btif_config_exist(const std::string& section, const std::string& key) { return bluetooth::shim::BtifConfigInterface::HasProperty(section, key); } -bool btif_config_get_int(const std::string& section, const std::string& key, - int* value) { +bool btif_config_get_int(const std::string& section, const std::string& key, int* value) { log::assert_that(bluetooth::shim::is_gd_stack_started_up(), "assert failed: bluetooth::shim::is_gd_stack_started_up()"); return bluetooth::shim::BtifConfigInterface::GetInt(section, key, value); } -bool btif_config_set_int(const std::string& section, const std::string& key, - int value) { +bool btif_config_set_int(const std::string& section, const std::string& key, int value) { log::assert_that(bluetooth::shim::is_gd_stack_started_up(), "assert failed: bluetooth::shim::is_gd_stack_started_up()"); return bluetooth::shim::BtifConfigInterface::SetInt(section, key, value); } -bool btif_config_get_uint64(const std::string& section, const std::string& key, - uint64_t* value) { +bool btif_config_get_uint64(const std::string& section, const std::string& key, uint64_t* value) { log::assert_that(bluetooth::shim::is_gd_stack_started_up(), "assert failed: bluetooth::shim::is_gd_stack_started_up()"); return bluetooth::shim::BtifConfigInterface::GetUint64(section, key, value); } -bool btif_config_set_uint64(const std::string& section, const std::string& key, - uint64_t value) { +bool btif_config_set_uint64(const std::string& section, const std::string& key, uint64_t value) { log::assert_that(bluetooth::shim::is_gd_stack_started_up(), "assert failed: bluetooth::shim::is_gd_stack_started_up()"); return bluetooth::shim::BtifConfigInterface::SetUint64(section, key, value); @@ -262,12 +250,11 @@ bool btif_config_set_uint64(const std::string& section, const std::string& key, * ******************************************************************************/ -bool btif_config_get_str(const std::string& section, const std::string& key, - char* value, int* size_bytes) { +bool btif_config_get_str(const std::string& section, const std::string& key, char* value, + int* size_bytes) { log::assert_that(bluetooth::shim::is_gd_stack_started_up(), "assert failed: bluetooth::shim::is_gd_stack_started_up()"); - return bluetooth::shim::BtifConfigInterface::GetStr(section, key, value, - size_bytes); + return bluetooth::shim::BtifConfigInterface::GetStr(section, key, value, size_bytes); } bool btif_config_set_str(const std::string& section, const std::string& key, @@ -277,27 +264,24 @@ bool btif_config_set_str(const std::string& section, const std::string& key, return bluetooth::shim::BtifConfigInterface::SetStr(section, key, value); } -bool btif_config_get_bin(const std::string& section, const std::string& key, - uint8_t* value, size_t* length) { +bool btif_config_get_bin(const std::string& section, const std::string& key, uint8_t* value, + size_t* length) { log::assert_that(bluetooth::shim::is_gd_stack_started_up(), "assert failed: bluetooth::shim::is_gd_stack_started_up()"); - return bluetooth::shim::BtifConfigInterface::GetBin(section, key, value, - length); + return bluetooth::shim::BtifConfigInterface::GetBin(section, key, value, length); } -size_t btif_config_get_bin_length(const std::string& section, - const std::string& key) { +size_t btif_config_get_bin_length(const std::string& section, const std::string& key) { log::assert_that(bluetooth::shim::is_gd_stack_started_up(), "assert failed: bluetooth::shim::is_gd_stack_started_up()"); return bluetooth::shim::BtifConfigInterface::GetBinLength(section, key); } -bool btif_config_set_bin(const std::string& section, const std::string& key, - const uint8_t* value, size_t length) { +bool btif_config_set_bin(const std::string& section, const std::string& key, const uint8_t* value, + size_t length) { log::assert_that(bluetooth::shim::is_gd_stack_started_up(), "assert failed: bluetooth::shim::is_gd_stack_started_up()"); - return bluetooth::shim::BtifConfigInterface::SetBin(section, key, value, - length); + return bluetooth::shim::BtifConfigInterface::SetBin(section, key, value, length); } std::vector btif_config_get_paired_devices() { diff --git a/system/btif/src/btif_core.cc b/system/btif/src/btif_core.cc index 6c3a71184f1..7575161123e 100644 --- a/system/btif/src/btif_core.cc +++ b/system/btif/src/btif_core.cc @@ -78,8 +78,7 @@ using namespace bluetooth; #if defined(TARGET_FLOSS) #define BTE_DID_CONF_FILE "/var/lib/bluetooth/bt_did.conf" #elif defined(__ANDROID__) -#define BTE_DID_CONF_FILE \ - "/apex/com.android.btservices/etc/bluetooth/bt_did.conf" +#define BTE_DID_CONF_FILE "/apex/com.android.btservices/etc/bluetooth/bt_did.conf" #else // !defined(__ANDROID__) #define BTE_DID_CONF_FILE "bt_did.conf" #endif // defined(__ANDROID__) @@ -136,13 +135,10 @@ bool btif_is_dut_mode() { return btif_dut_mode == 1; } ******************************************************************************/ int btif_is_enabled(void) { - return ((!btif_is_dut_mode()) && - (stack_manager_get_interface()->get_stack_is_running())); + return (!btif_is_dut_mode()) && (stack_manager_get_interface()->get_stack_is_running()); } -void btif_init_ok() { - btif_dm_load_ble_local_keys(); -} +void btif_init_ok() { btif_dm_load_ble_local_keys(); } /******************************************************************************* * @@ -175,33 +171,30 @@ bt_status_t btif_init_bluetooth() { void btif_enable_bluetooth_evt() { /* Fetch the local BD ADDR */ - RawAddress local_bd_addr = bluetooth::ToRawAddress( - bluetooth::shim::GetController()->GetMacAddress()); + RawAddress local_bd_addr = + bluetooth::ToRawAddress(bluetooth::shim::GetController()->GetMacAddress()); std::string bdstr = local_bd_addr.ToString(); // save bd addr to iot conf file - device_iot_config_set_str(IOT_CONF_KEY_SECTION_ADAPTER, IOT_CONF_KEY_ADDRESS, - bdstr); + device_iot_config_set_str(IOT_CONF_KEY_SECTION_ADAPTER, IOT_CONF_KEY_ADDRESS, bdstr); char val[PROPERTY_VALUE_MAX] = ""; int val_size = PROPERTY_VALUE_MAX; - if (!btif_config_get_str(BTIF_STORAGE_SECTION_ADAPTER, - BTIF_STORAGE_KEY_ADDRESS, val, &val_size) || + if (!btif_config_get_str(BTIF_STORAGE_SECTION_ADAPTER, BTIF_STORAGE_KEY_ADDRESS, val, + &val_size) || strcmp(bdstr.c_str(), val) != 0) { // We failed to get an address or the one in the config file does not match // the address given by the controller interface. Update the config cache log::info("Storing '{}' into the config file", local_bd_addr); - btif_config_set_str(BTIF_STORAGE_SECTION_ADAPTER, BTIF_STORAGE_KEY_ADDRESS, - bdstr.c_str()); + btif_config_set_str(BTIF_STORAGE_SECTION_ADAPTER, BTIF_STORAGE_KEY_ADDRESS, bdstr.c_str()); // fire HAL callback for property change bt_property_t prop; prop.type = BT_PROPERTY_BDADDR; prop.val = (void*)&local_bd_addr; prop.len = sizeof(RawAddress); - GetInterfaceToProfiles()->events->invoke_adapter_properties_cb( - BT_STATUS_SUCCESS, 1, &prop); + GetInterfaceToProfiles()->events->invoke_adapter_properties_cb(BT_STATUS_SUCCESS, 1, &prop); } /* callback to HAL */ @@ -232,8 +225,7 @@ void btif_enable_bluetooth_evt() { uint32_t record_handle; tBTA_STATUS status = BTA_DmSetLocalDiRecord(&record, &record_handle); if (status != BTA_SUCCESS) { - log::error("unable to set device ID record error {}.", - bta_status_text(status)); + log::error("unable to set device ID record error {}.", bta_status_text(status)); } } @@ -296,8 +288,8 @@ void btif_dut_mode_configure(uint8_t enable) { void btif_dut_mode_send(uint16_t opcode, uint8_t* buf, uint8_t len) { log::verbose(""); /* For now nothing to be done. */ - get_btm_client_interface().vendor.BTM_VendorSpecificCommand( - opcode, len, buf, [](tBTM_VSC_CMPL*) {}); + get_btm_client_interface().vendor.BTM_VendorSpecificCommand(opcode, len, buf, + [](tBTM_VSC_CMPL*) {}); } /***************************************************************************** @@ -320,8 +312,7 @@ static bt_status_t btif_in_get_adapter_properties(void) { bt_status_t status; /* RawAddress */ - BTIF_STORAGE_FILL_PROPERTY(&properties[num_props], BT_PROPERTY_BDADDR, - sizeof(addr), &addr); + BTIF_STORAGE_FILL_PROPERTY(&properties[num_props], BT_PROPERTY_BDADDR, sizeof(addr), &addr); status = btif_storage_get_adapter_property(&properties[num_props]); // Add BT_PROPERTY_BDADDR property into list only when successful. // Otherwise, skip this property entry. @@ -330,33 +321,30 @@ static bt_status_t btif_in_get_adapter_properties(void) { } /* BD_NAME */ - BTIF_STORAGE_FILL_PROPERTY(&properties[num_props], BT_PROPERTY_BDNAME, - sizeof(name), &name); + BTIF_STORAGE_FILL_PROPERTY(&properties[num_props], BT_PROPERTY_BDNAME, sizeof(name), &name); btif_storage_get_adapter_property(&properties[num_props]); num_props++; /* DISC_TIMEOUT */ - BTIF_STORAGE_FILL_PROPERTY(&properties[num_props], - BT_PROPERTY_ADAPTER_DISCOVERABLE_TIMEOUT, + BTIF_STORAGE_FILL_PROPERTY(&properties[num_props], BT_PROPERTY_ADAPTER_DISCOVERABLE_TIMEOUT, sizeof(disc_timeout), &disc_timeout); btif_storage_get_adapter_property(&properties[num_props]); num_props++; /* BONDED_DEVICES */ - BTIF_STORAGE_FILL_PROPERTY(&properties[num_props], - BT_PROPERTY_ADAPTER_BONDED_DEVICES, + BTIF_STORAGE_FILL_PROPERTY(&properties[num_props], BT_PROPERTY_ADAPTER_BONDED_DEVICES, sizeof(bonded_devices), bonded_devices); btif_storage_get_adapter_property(&properties[num_props]); num_props++; /* LOCAL UUIDs */ - BTIF_STORAGE_FILL_PROPERTY(&properties[num_props], BT_PROPERTY_UUIDS, - sizeof(local_uuids), local_uuids); + BTIF_STORAGE_FILL_PROPERTY(&properties[num_props], BT_PROPERTY_UUIDS, sizeof(local_uuids), + local_uuids); btif_storage_get_adapter_property(&properties[num_props]); num_props++; - GetInterfaceToProfiles()->events->invoke_adapter_properties_cb( - BT_STATUS_SUCCESS, num_props, properties); + GetInterfaceToProfiles()->events->invoke_adapter_properties_cb(BT_STATUS_SUCCESS, num_props, + properties); return BT_STATUS_SUCCESS; } @@ -369,61 +357,50 @@ static bt_status_t btif_in_get_remote_device_properties(RawAddress* bd_addr) { Uuid remote_uuids[BT_MAX_NUM_UUIDS]; memset(remote_properties, 0, sizeof(remote_properties)); - BTIF_STORAGE_FILL_PROPERTY(&remote_properties[num_props], BT_PROPERTY_BDNAME, - sizeof(name), &name); - btif_storage_get_remote_device_property(bd_addr, - &remote_properties[num_props]); + BTIF_STORAGE_FILL_PROPERTY(&remote_properties[num_props], BT_PROPERTY_BDNAME, sizeof(name), + &name); + btif_storage_get_remote_device_property(bd_addr, &remote_properties[num_props]); num_props++; - BTIF_STORAGE_FILL_PROPERTY(&remote_properties[num_props], - BT_PROPERTY_REMOTE_FRIENDLY_NAME, sizeof(alias), - &alias); - btif_storage_get_remote_device_property(bd_addr, - &remote_properties[num_props]); + BTIF_STORAGE_FILL_PROPERTY(&remote_properties[num_props], BT_PROPERTY_REMOTE_FRIENDLY_NAME, + sizeof(alias), &alias); + btif_storage_get_remote_device_property(bd_addr, &remote_properties[num_props]); num_props++; - BTIF_STORAGE_FILL_PROPERTY(&remote_properties[num_props], - BT_PROPERTY_CLASS_OF_DEVICE, sizeof(cod), &cod); - btif_storage_get_remote_device_property(bd_addr, - &remote_properties[num_props]); + BTIF_STORAGE_FILL_PROPERTY(&remote_properties[num_props], BT_PROPERTY_CLASS_OF_DEVICE, + sizeof(cod), &cod); + btif_storage_get_remote_device_property(bd_addr, &remote_properties[num_props]); num_props++; - BTIF_STORAGE_FILL_PROPERTY(&remote_properties[num_props], - BT_PROPERTY_TYPE_OF_DEVICE, sizeof(devtype), - &devtype); - btif_storage_get_remote_device_property(bd_addr, - &remote_properties[num_props]); + BTIF_STORAGE_FILL_PROPERTY(&remote_properties[num_props], BT_PROPERTY_TYPE_OF_DEVICE, + sizeof(devtype), &devtype); + btif_storage_get_remote_device_property(bd_addr, &remote_properties[num_props]); num_props++; - BTIF_STORAGE_FILL_PROPERTY(&remote_properties[num_props], BT_PROPERTY_UUIDS, - sizeof(remote_uuids), remote_uuids); - btif_storage_get_remote_device_property(bd_addr, - &remote_properties[num_props]); + BTIF_STORAGE_FILL_PROPERTY(&remote_properties[num_props], BT_PROPERTY_UUIDS, sizeof(remote_uuids), + remote_uuids); + btif_storage_get_remote_device_property(bd_addr, &remote_properties[num_props]); num_props++; GetInterfaceToProfiles()->events->invoke_remote_device_properties_cb( - BT_STATUS_SUCCESS, *bd_addr, num_props, remote_properties); + BT_STATUS_SUCCESS, *bd_addr, num_props, remote_properties); return BT_STATUS_SUCCESS; } static void btif_core_storage_adapter_write(bt_property_t* prop) { - log::verbose("type: {}, len {}, {}", prop->type, prop->len, - fmt::ptr(prop->val)); + log::verbose("type: {}, len {}, {}", prop->type, prop->len, fmt::ptr(prop->val)); bt_status_t status = btif_storage_set_adapter_property(prop); - GetInterfaceToProfiles()->events->invoke_adapter_properties_cb(status, 1, - prop); + GetInterfaceToProfiles()->events->invoke_adapter_properties_cb(status, 1, prop); } -void btif_adapter_properties_evt(bt_status_t status, uint32_t num_props, - bt_property_t* p_props) { - GetInterfaceToProfiles()->events->invoke_adapter_properties_cb( - status, num_props, p_props); +void btif_adapter_properties_evt(bt_status_t status, uint32_t num_props, bt_property_t* p_props) { + GetInterfaceToProfiles()->events->invoke_adapter_properties_cb(status, num_props, p_props); } -void btif_remote_properties_evt(bt_status_t status, RawAddress* remote_addr, - uint32_t num_props, bt_property_t* p_props) { - GetInterfaceToProfiles()->events->invoke_remote_device_properties_cb( - status, *remote_addr, num_props, p_props); +void btif_remote_properties_evt(bt_status_t status, RawAddress* remote_addr, uint32_t num_props, + bt_property_t* p_props) { + GetInterfaceToProfiles()->events->invoke_remote_device_properties_cb(status, *remote_addr, + num_props, p_props); } /******************************************************************************* @@ -467,57 +444,48 @@ void btif_get_adapter_property(bt_property_type_t type) { local_le_features.local_privacy_enabled = BTM_BleLocalPrivacyEnabled(); prop.len = sizeof(bt_local_le_features_t); - if (cmn_vsc_cb.filter_support == 1) + if (cmn_vsc_cb.filter_support == 1) { local_le_features.max_adv_filter_supported = cmn_vsc_cb.max_filter; - else + } else { local_le_features.max_adv_filter_supported = 0; + } local_le_features.max_adv_instance = cmn_vsc_cb.adv_inst_max; local_le_features.max_irk_list_size = cmn_vsc_cb.max_irk_list_sz; local_le_features.rpa_offload_supported = cmn_vsc_cb.rpa_offloading; - local_le_features.scan_result_storage_size = - cmn_vsc_cb.tot_scan_results_strg; - local_le_features.activity_energy_info_supported = - cmn_vsc_cb.energy_support; + local_le_features.scan_result_storage_size = cmn_vsc_cb.tot_scan_results_strg; + local_le_features.activity_energy_info_supported = cmn_vsc_cb.energy_support; local_le_features.version_supported = cmn_vsc_cb.version_supported; - local_le_features.total_trackable_advertisers = - cmn_vsc_cb.total_trackable_advertisers; + local_le_features.total_trackable_advertisers = cmn_vsc_cb.total_trackable_advertisers; - local_le_features.extended_scan_support = - cmn_vsc_cb.extended_scan_support > 0; - local_le_features.debug_logging_supported = - cmn_vsc_cb.debug_logging_supported > 0; + local_le_features.extended_scan_support = cmn_vsc_cb.extended_scan_support > 0; + local_le_features.debug_logging_supported = cmn_vsc_cb.debug_logging_supported > 0; auto controller = bluetooth::shim::GetController(); if (controller->SupportsBleExtendedAdvertising()) { - local_le_features.max_adv_instance = - controller->GetLeNumberOfSupportedAdverisingSets(); + local_le_features.max_adv_instance = controller->GetLeNumberOfSupportedAdverisingSets(); } local_le_features.le_2m_phy_supported = controller->SupportsBle2mPhy(); - local_le_features.le_coded_phy_supported = - controller->SupportsBleCodedPhy(); + local_le_features.le_coded_phy_supported = controller->SupportsBleCodedPhy(); local_le_features.le_extended_advertising_supported = - controller->SupportsBleExtendedAdvertising(); + controller->SupportsBleExtendedAdvertising(); local_le_features.le_periodic_advertising_supported = - controller->SupportsBlePeriodicAdvertising(); + controller->SupportsBlePeriodicAdvertising(); local_le_features.le_maximum_advertising_data_length = - controller->GetLeMaximumAdvertisingDataLength(); + controller->GetLeMaximumAdvertisingDataLength(); - local_le_features.dynamic_audio_buffer_supported = - cmn_vsc_cb.dynamic_audio_buffer_support; + local_le_features.dynamic_audio_buffer_supported = cmn_vsc_cb.dynamic_audio_buffer_support; local_le_features.le_periodic_advertising_sync_transfer_sender_supported = - controller->SupportsBlePeriodicAdvertisingSyncTransferSender(); + controller->SupportsBlePeriodicAdvertisingSyncTransferSender(); local_le_features.le_connected_isochronous_stream_central_supported = - controller->SupportsBleConnectedIsochronousStreamCentral(); + controller->SupportsBleConnectedIsochronousStreamCentral(); local_le_features.le_isochronous_broadcast_supported = - controller->SupportsBleIsochronousBroadcaster(); - local_le_features - .le_periodic_advertising_sync_transfer_recipient_supported = - controller->SupportsBlePeriodicAdvertisingSyncTransferRecipient(); + controller->SupportsBleIsochronousBroadcaster(); + local_le_features.le_periodic_advertising_sync_transfer_recipient_supported = + controller->SupportsBlePeriodicAdvertisingSyncTransferRecipient(); local_le_features.adv_filter_extended_features_mask = - cmn_vsc_cb.adv_filter_extended_features_mask; - local_le_features.le_channel_sounding_supported = - controller->SupportsBleChannelSounding(); + cmn_vsc_cb.adv_filter_extended_features_mask; + local_le_features.le_channel_sounding_supported = controller->SupportsBleChannelSounding(); memcpy(prop.val, &local_le_features, prop.len); } else if (prop.type == BT_PROPERTY_DYNAMIC_AUDIO_BUFFER) { @@ -530,27 +498,22 @@ void btif_get_adapter_property(bt_property_type_t type) { if (GetInterfaceToProfiles()->config->isA2DPOffloadEnabled() == false) { log::verbose("Get buffer millis for A2DP software encoding"); for (int i = 0; i < CODEC_TYPE_NUMBER; i++) { - dynamic_audio_buffer_item.dab_item[i] = { - .default_buffer_time = DEFAULT_BUFFER_TIME, - .maximum_buffer_time = MAXIMUM_BUFFER_TIME, - .minimum_buffer_time = MINIMUM_BUFFER_TIME}; + dynamic_audio_buffer_item.dab_item[i] = {.default_buffer_time = DEFAULT_BUFFER_TIME, + .maximum_buffer_time = MAXIMUM_BUFFER_TIME, + .minimum_buffer_time = MINIMUM_BUFFER_TIME}; } memcpy(prop.val, &dynamic_audio_buffer_item, prop.len); } else { if (cmn_vsc_cb.dynamic_audio_buffer_support != 0) { log::verbose("Get buffer millis for A2DP Offload"); - tBTM_BT_DYNAMIC_AUDIO_BUFFER_CB - bt_dynamic_audio_buffer_cb[CODEC_TYPE_NUMBER]; + tBTM_BT_DYNAMIC_AUDIO_BUFFER_CB bt_dynamic_audio_buffer_cb[CODEC_TYPE_NUMBER]; BTM_BleGetDynamicAudioBuffer(bt_dynamic_audio_buffer_cb); for (int i = 0; i < CODEC_TYPE_NUMBER; i++) { dynamic_audio_buffer_item.dab_item[i] = { - .default_buffer_time = - bt_dynamic_audio_buffer_cb[i].default_buffer_time, - .maximum_buffer_time = - bt_dynamic_audio_buffer_cb[i].maximum_buffer_time, - .minimum_buffer_time = - bt_dynamic_audio_buffer_cb[i].minimum_buffer_time}; + .default_buffer_time = bt_dynamic_audio_buffer_cb[i].default_buffer_time, + .maximum_buffer_time = bt_dynamic_audio_buffer_cb[i].maximum_buffer_time, + .minimum_buffer_time = bt_dynamic_audio_buffer_cb[i].minimum_buffer_time}; } memcpy(prop.val, &dynamic_audio_buffer_item, prop.len); } else { @@ -560,13 +523,11 @@ void btif_get_adapter_property(bt_property_type_t type) { } else { status = btif_storage_get_adapter_property(&prop); } - GetInterfaceToProfiles()->events->invoke_adapter_properties_cb(status, 1, - &prop); + GetInterfaceToProfiles()->events->invoke_adapter_properties_cb(status, 1, &prop); } bt_property_t* property_deep_copy(const bt_property_t* prop) { - bt_property_t* copy = - (bt_property_t*)osi_calloc(sizeof(bt_property_t) + prop->len); + bt_property_t* copy = (bt_property_t*)osi_calloc(sizeof(bt_property_t) + prop->len); copy->type = prop->type; copy->len = prop->len; copy->val = (uint8_t*)(copy + 1); @@ -598,14 +559,13 @@ void btif_set_scan_mode(bt_scan_mode_t mode) { ******************************************************************************/ void btif_set_adapter_property(bt_property_t* property) { - log::verbose("btif_set_adapter_property type: {}, len {}, {}", property->type, - property->len, fmt::ptr(property->val)); + log::verbose("btif_set_adapter_property type: {}, len {}, {}", property->type, property->len, + fmt::ptr(property->val)); switch (property->type) { case BT_PROPERTY_BDNAME: { char bd_name[BD_NAME_LEN + 1]; - uint16_t name_len = - property->len > BD_NAME_LEN ? BD_NAME_LEN : property->len; + uint16_t name_len = property->len > BD_NAME_LEN ? BD_NAME_LEN : property->len; memcpy(bd_name, property->val, name_len); bd_name[name_len] = '\0'; @@ -634,18 +594,16 @@ void btif_set_adapter_property(bt_property_t* property) { * Description Fetches the remote device property from the NVRAM * ******************************************************************************/ -void btif_get_remote_device_property(RawAddress remote_addr, - bt_property_type_t type) { +void btif_get_remote_device_property(RawAddress remote_addr, bt_property_type_t type) { char buf[1024]; bt_property_t prop; prop.type = type; prop.val = (void*)buf; prop.len = sizeof(buf); - bt_status_t status = - btif_storage_get_remote_device_property(&remote_addr, &prop); - GetInterfaceToProfiles()->events->invoke_remote_device_properties_cb( - status, remote_addr, 1, &prop); + bt_status_t status = btif_storage_get_remote_device_property(&remote_addr, &prop); + GetInterfaceToProfiles()->events->invoke_remote_device_properties_cb(status, remote_addr, 1, + &prop); } /******************************************************************************* @@ -668,8 +626,7 @@ void btif_get_remote_device_properties(RawAddress remote_addr) { * remote device property that can be set * ******************************************************************************/ -void btif_set_remote_device_property(RawAddress* remote_addr, - bt_property_t* property) { +void btif_set_remote_device_property(RawAddress* remote_addr, bt_property_t* property) { btif_storage_set_remote_device_property(remote_addr, property); } @@ -683,9 +640,7 @@ void btif_set_remote_device_property(RawAddress* remote_addr, * ******************************************************************************/ -tBTA_SERVICE_MASK btif_get_enabled_services_mask(void) { - return btif_enabled_services; -} +tBTA_SERVICE_MASK btif_get_enabled_services_mask(void) { return btif_enabled_services; } /******************************************************************************* * @@ -732,18 +687,15 @@ bt_status_t btif_set_dynamic_audio_buffer_size(int codec, int size) { if (!GetInterfaceToProfiles()->config->isA2DPOffloadEnabled()) { log::verbose("Set buffer size ({}) for A2DP software encoding", size); - GetInterfaceToProfiles() - ->profileSpecific_HACK->btif_av_set_dynamic_audio_buffer_size( + GetInterfaceToProfiles()->profileSpecific_HACK->btif_av_set_dynamic_audio_buffer_size( uint8_t(size)); } else { if (cmn_vsc_cb.dynamic_audio_buffer_support != 0) { log::verbose("Set buffer size ({}) for A2DP offload", size); uint16_t firmware_tx_buffer_length_byte; firmware_tx_buffer_length_byte = static_cast(size); - log::info("firmware_tx_buffer_length_byte: {}", - firmware_tx_buffer_length_byte); - bluetooth::shim::GetController()->SetDabAudioBufferTime( - firmware_tx_buffer_length_byte); + log::info("firmware_tx_buffer_length_byte: {}", firmware_tx_buffer_length_byte); + bluetooth::shim::GetController()->SetDabAudioBufferTime(firmware_tx_buffer_length_byte); } } diff --git a/system/btif/src/btif_csis_client.cc b/system/btif/src/btif_csis_client.cc index f1fd2b492aa..6d0ced85532 100644 --- a/system/btif/src/btif_csis_client.cc +++ b/system/btif/src/btif_csis_client.cc @@ -50,10 +50,9 @@ class CsipSetCoordinatorServiceInterfaceImpl : public CsisClientInterface, void Init(CsisClientCallbacks* callbacks) override { this->callbacks_ = callbacks; - do_in_main_thread( - FROM_HERE, - Bind(&CsisClient::Initialize, this, - jni_thread_wrapper(Bind(&btif_storage_load_bonded_csis_devices)))); + do_in_main_thread(FROM_HERE, + Bind(&CsisClient::Initialize, this, + jni_thread_wrapper(Bind(&btif_storage_load_bonded_csis_devices)))); /* It might be not yet initialized, but setting this flag here is safe, * because other calls will check this and the native instance */ @@ -63,40 +62,39 @@ class CsipSetCoordinatorServiceInterfaceImpl : public CsisClientInterface, void Connect(const RawAddress& addr) override { if (!initialized || !CsisClient::IsCsisClientRunning()) { log::verbose( - "call ignored, due to already started cleanup procedure or service " - "being not read"); + "call ignored, due to already started cleanup procedure or service " + "being not read"); return; } - do_in_main_thread(FROM_HERE, Bind(&CsisClient::Connect, - Unretained(CsisClient::Get()), addr)); + do_in_main_thread(FROM_HERE, Bind(&CsisClient::Connect, Unretained(CsisClient::Get()), addr)); } void Disconnect(const RawAddress& addr) override { if (!initialized || !CsisClient::IsCsisClientRunning()) { log::verbose( - "call ignored, due to already started cleanup procedure or service " - "being not read"); + "call ignored, due to already started cleanup procedure or service " + "being not read"); return; } - do_in_main_thread(FROM_HERE, Bind(&CsisClient::Disconnect, - Unretained(CsisClient::Get()), addr)); + do_in_main_thread(FROM_HERE, + Bind(&CsisClient::Disconnect, Unretained(CsisClient::Get()), addr)); } void RemoveDevice(const RawAddress& addr) override { if (!initialized || !CsisClient::IsCsisClientRunning()) { log::verbose( - "call ignored, due to already started cleanup procedure or service " - "being not ready"); + "call ignored, due to already started cleanup procedure or service " + "being not ready"); /* Clear storage */ do_in_jni_thread(Bind(&btif_storage_remove_csis_device, addr)); return; } - do_in_main_thread(FROM_HERE, Bind(&CsisClient::RemoveDevice, - Unretained(CsisClient::Get()), addr)); + do_in_main_thread(FROM_HERE, + Bind(&CsisClient::RemoveDevice, Unretained(CsisClient::Get()), addr)); /* Clear storage */ do_in_jni_thread(Bind(&btif_storage_remove_csis_device, addr)); } @@ -104,21 +102,20 @@ class CsipSetCoordinatorServiceInterfaceImpl : public CsisClientInterface, void LockGroup(int group_id, bool lock) override { if (!initialized || !CsisClient::IsCsisClientRunning()) { log::verbose( - "call ignored, due to already started cleanup procedure or service " - "being not read"); + "call ignored, due to already started cleanup procedure or service " + "being not read"); return; } - do_in_main_thread( - FROM_HERE, Bind(&CsisClient::LockGroup, Unretained(CsisClient::Get()), - group_id, lock, base::DoNothing())); + do_in_main_thread(FROM_HERE, Bind(&CsisClient::LockGroup, Unretained(CsisClient::Get()), + group_id, lock, base::DoNothing())); } void Cleanup(void) override { if (!initialized || !CsisClient::IsCsisClientRunning()) { log::verbose( - "call ignored, due to already started cleanup procedure or service " - "being not read"); + "call ignored, due to already started cleanup procedure or service " + "being not read"); return; } @@ -126,40 +123,38 @@ class CsipSetCoordinatorServiceInterfaceImpl : public CsisClientInterface, do_in_main_thread(FROM_HERE, Bind(&CsisClient::CleanUp)); } - void OnConnectionState(const RawAddress& addr, - ConnectionState state) override { - do_in_jni_thread(Bind(&CsisClientCallbacks::OnConnectionState, - Unretained(callbacks_), addr, state)); + void OnConnectionState(const RawAddress& addr, ConnectionState state) override { + do_in_jni_thread( + Bind(&CsisClientCallbacks::OnConnectionState, Unretained(callbacks_), addr, state)); } - void OnDeviceAvailable(const RawAddress& addr, int group_id, int group_size, - int rank, const bluetooth::Uuid& uuid) override { - do_in_jni_thread(Bind(&CsisClientCallbacks::OnDeviceAvailable, - Unretained(callbacks_), addr, group_id, group_size, - rank, uuid)); + void OnDeviceAvailable(const RawAddress& addr, int group_id, int group_size, int rank, + const bluetooth::Uuid& uuid) override { + do_in_jni_thread(Bind(&CsisClientCallbacks::OnDeviceAvailable, Unretained(callbacks_), addr, + group_id, group_size, rank, uuid)); } void OnSetMemberAvailable(const RawAddress& addr, int group_id) override { - do_in_jni_thread(Bind(&CsisClientCallbacks::OnSetMemberAvailable, - Unretained(callbacks_), addr, group_id)); + do_in_jni_thread(Bind(&CsisClientCallbacks::OnSetMemberAvailable, Unretained(callbacks_), addr, + group_id)); } /* Callback for lock changed in the group */ - virtual void OnGroupLockChanged(int group_id, bool locked, - CsisGroupLockStatus status) override { - do_in_jni_thread(Bind(&CsisClientCallbacks::OnGroupLockChanged, - Unretained(callbacks_), group_id, locked, status)); + virtual void OnGroupLockChanged(int group_id, bool locked, CsisGroupLockStatus status) override { + do_in_jni_thread(Bind(&CsisClientCallbacks::OnGroupLockChanged, Unretained(callbacks_), + group_id, locked, status)); } - private: +private: CsisClientCallbacks* callbacks_; }; } /* namespace */ CsisClientInterface* btif_csis_client_get_interface(void) { - if (!csis_client_instance) + if (!csis_client_instance) { csis_client_instance.reset(new CsipSetCoordinatorServiceInterfaceImpl()); + } return csis_client_instance.get(); } diff --git a/system/btif/src/btif_debug_conn.cc b/system/btif/src/btif_debug_conn.cc index c73d7cccd85..ef2843baf31 100644 --- a/system/btif/src/btif_debug_conn.cc +++ b/system/btif/src/btif_debug_conn.cc @@ -61,11 +61,12 @@ static const char* format_state(const btif_debug_conn_state_t state) { static void next_event() { ++current_event; - if (current_event == NUM_CONNECTION_EVENTS) current_event = 0; + if (current_event == NUM_CONNECTION_EVENTS) { + current_event = 0; + } } -void btif_debug_conn_state(const RawAddress& bda, - const btif_debug_conn_state_t state, +void btif_debug_conn_state(const RawAddress& bda, const btif_debug_conn_state_t state, const tGATT_DISCONN_REASON disconnect_reason) { next_event(); @@ -77,29 +78,34 @@ void btif_debug_conn_state(const RawAddress& bda, } void btif_debug_conn_dump(int fd) { - const uint8_t current_event_local = - current_event; // Cache to avoid threading issues + const uint8_t current_event_local = current_event; // Cache to avoid threading issues uint8_t dump_event = current_event_local; char ts_buffer[TEMP_BUFFER_SIZE] = {0}; dprintf(fd, "\nConnection Events:\n"); - if (connection_events[dump_event].ts == 0) dprintf(fd, " None\n"); + if (connection_events[dump_event].ts == 0) { + dprintf(fd, " None\n"); + } while (connection_events[dump_event].ts) { conn_event_t* evt = &connection_events[dump_event]; dprintf(fd, " %s %s %s", format_ts(evt->ts, ts_buffer, sizeof(ts_buffer)), format_state(evt->state), ADDRESS_TO_LOGGABLE_CSTR(evt->bda)); - if (evt->state == BTIF_DEBUG_DISCONNECTED) + if (evt->state == BTIF_DEBUG_DISCONNECTED) { dprintf(fd, " reason=%d", evt->disconnect_reason); + } dprintf(fd, "\n"); // Go to previous event; wrap if needed - if (dump_event > 0) + if (dump_event > 0) { --dump_event; - else + } else { dump_event = NUM_CONNECTION_EVENTS - 1; + } // Check if we dumped all events - if (dump_event == current_event_local) break; + if (dump_event == current_event_local) { + break; + } } } diff --git a/system/btif/src/btif_dm.cc b/system/btif/src/btif_dm.cc index 9e4112ed33e..5a84f1ef27b 100644 --- a/system/btif/src/btif_dm.cc +++ b/system/btif/src/btif_dm.cc @@ -118,7 +118,7 @@ namespace { constexpr char kBtmLogTag[] = "API"; constexpr char kBtmLogTagCallback[] = "CBACK"; constexpr char kBtmLogTagSdp[] = "SDP"; -} +} // namespace /****************************************************************************** * Constants & Macros @@ -128,8 +128,7 @@ const Uuid UUID_HEARING_AID = Uuid::FromString("FDF0"); const Uuid UUID_VC = Uuid::FromString("1844"); const Uuid UUID_CSIS = Uuid::FromString("1846"); const Uuid UUID_LE_AUDIO = Uuid::FromString("184E"); -const Uuid UUID_LE_MIDI = - Uuid::FromString("03B80E5A-EDE8-4B33-A751-6CE34EC4C700"); +const Uuid UUID_LE_MIDI = Uuid::FromString("03B80E5A-EDE8-4B33-A751-6CE34EC4C700"); const Uuid UUID_HAS = Uuid::FromString("1854"); const Uuid UUID_BASS = Uuid::FromString("184F"); const Uuid UUID_BATTERY = Uuid::FromString("180F"); @@ -244,7 +243,7 @@ typedef struct { #define MAX_NUM_DEVICES_IN_EIR_UUID_CACHE 128 static bluetooth::common::LruCache> eir_uuids_cache( - MAX_NUM_DEVICES_IN_EIR_UUID_CACHE); + MAX_NUM_DEVICES_IN_EIR_UUID_CACHE); static skip_sdp_entry_t sdp_rejectlist[] = {{76}}; // Apple Mouse and Keyboard @@ -271,20 +270,16 @@ static size_t btif_events_end_index = 0; /****************************************************************************** * Static functions *****************************************************************************/ -static void btif_dm_ble_sec_req_evt(tBTA_DM_BLE_SEC_REQ* p_ble_req, - bool is_consent); +static void btif_dm_ble_sec_req_evt(tBTA_DM_BLE_SEC_REQ* p_ble_req, bool is_consent); static void btif_dm_remove_ble_bonding_keys(void); static void btif_dm_save_ble_bonding_keys(RawAddress& bd_addr); static btif_dm_pairing_cb_t pairing_cb; static btif_dm_oob_cb_t oob_cb; static btif_dm_metadata_cb_t metadata_cb{.le_audio_cache{40}}; -static void btif_dm_cb_create_bond(const RawAddress bd_addr, - tBT_TRANSPORT transport); -static void btif_dm_cb_create_bond_le(const RawAddress bd_addr, - tBLE_ADDR_TYPE addr_type); -static void btif_update_remote_properties(const RawAddress& bd_addr, - BD_NAME bd_name, DEV_CLASS dev_class, - tBT_DEVICE_TYPE dev_type); +static void btif_dm_cb_create_bond(const RawAddress bd_addr, tBT_TRANSPORT transport); +static void btif_dm_cb_create_bond_le(const RawAddress bd_addr, tBLE_ADDR_TYPE addr_type); +static void btif_update_remote_properties(const RawAddress& bd_addr, BD_NAME bd_name, + DEV_CLASS dev_class, tBT_DEVICE_TYPE dev_type); static btif_dm_local_key_cb_t ble_local_key_cb; static void btif_dm_ble_key_notif_evt(tBTA_DM_SP_KEY_NOTIF* p_ssp_key_notif); static void btif_dm_ble_auth_cmpl_evt(tBTA_DM_AUTH_CMPL* p_auth_cmpl); @@ -295,19 +290,17 @@ static void btif_dm_ble_sc_oob_req_evt(tBTA_DM_SP_RMT_OOB* req_oob_type); static const char* btif_get_default_local_name(); -static void btif_stats_add_bond_event(const RawAddress& bd_addr, - bt_bond_function_t function, +static void btif_stats_add_bond_event(const RawAddress& bd_addr, bt_bond_function_t function, bt_bond_state_t state); -static void btif_on_name_read(RawAddress bd_addr, tHCI_ERROR_CODE hci_status, - const BD_NAME bd_name, bool during_device_search); +static void btif_on_name_read(RawAddress bd_addr, tHCI_ERROR_CODE hci_status, const BD_NAME bd_name, + bool during_device_search); /****************************************************************************** * Externs *****************************************************************************/ bt_status_t btif_sdp_execute_service(bool b_enable); -void btif_iot_update_remote_info(tBTA_DM_AUTH_CMPL* p_auth_cmpl, bool is_ble, - bool is_ssp); +void btif_iot_update_remote_info(tBTA_DM_AUTH_CMPL* p_auth_cmpl, bool is_ble, bool is_ssp); /****************************************************************************** * Functions @@ -332,8 +325,7 @@ void btif_dm_cleanup(void) { } } -bt_status_t btif_in_execute_service_request(tBTA_SERVICE_ID service_id, - bool b_enable) { +bt_status_t btif_in_execute_service_request(tBTA_SERVICE_ID service_id, bool b_enable) { log::verbose("service_id:{}", service_id); if (service_id == BTA_SDP_SERVICE_ID) { @@ -352,8 +344,7 @@ bt_status_t btif_in_execute_service_request(tBTA_SERVICE_ID service_id, * @param asha_truncated_hi_sync_id value will be updated if found, otherwise no * change */ -static void get_asha_service_data(const tBTA_DM_INQ_RES& inq_res, - int16_t& asha_capability, +static void get_asha_service_data(const tBTA_DM_INQ_RES& inq_res, int16_t& asha_capability, uint32_t& asha_truncated_hi_sync_id) { asha_capability = -1; if (inq_res.p_eir) { @@ -363,10 +354,9 @@ static void get_asha_service_data(const tBTA_DM_INQ_RES& inq_res, const uint8_t* p_service_data = inq_res.p_eir; uint8_t service_data_len = 0; while ((p_service_data = AdvertiseDataParser::GetFieldByType( - p_service_data + service_data_len, - inq_res.eir_len - (p_service_data - inq_res.p_eir) - - service_data_len, - BTM_BLE_AD_TYPE_SERVICE_DATA_TYPE, &service_data_len))) { + p_service_data + service_data_len, + inq_res.eir_len - (p_service_data - inq_res.p_eir) - service_data_len, + BTM_BLE_AD_TYPE_SERVICE_DATA_TYPE, &service_data_len))) { if (service_data_len < 2) { continue; } @@ -404,8 +394,7 @@ static void get_asha_service_data(const tBTA_DM_INQ_RES& inq_res, * Populate p_remote_name, if provided and remote name found * ******************************************************************************/ -static bool check_eir_remote_name(tBTA_DM_SEARCH* p_search_data, - uint8_t* p_remote_name, +static bool check_eir_remote_name(tBTA_DM_SEARCH* p_search_data, uint8_t* p_remote_name, uint8_t* p_remote_name_len) { const uint8_t* p_eir_remote_name = NULL; uint8_t remote_name_len = 0; @@ -413,16 +402,18 @@ static bool check_eir_remote_name(tBTA_DM_SEARCH* p_search_data, /* Check EIR for remote name and services */ if (p_search_data->inq_res.p_eir) { p_eir_remote_name = AdvertiseDataParser::GetFieldByType( - p_search_data->inq_res.p_eir, p_search_data->inq_res.eir_len, - HCI_EIR_COMPLETE_LOCAL_NAME_TYPE, &remote_name_len); + p_search_data->inq_res.p_eir, p_search_data->inq_res.eir_len, + HCI_EIR_COMPLETE_LOCAL_NAME_TYPE, &remote_name_len); if (!p_eir_remote_name) { p_eir_remote_name = AdvertiseDataParser::GetFieldByType( - p_search_data->inq_res.p_eir, p_search_data->inq_res.eir_len, - HCI_EIR_SHORTENED_LOCAL_NAME_TYPE, &remote_name_len); + p_search_data->inq_res.p_eir, p_search_data->inq_res.eir_len, + HCI_EIR_SHORTENED_LOCAL_NAME_TYPE, &remote_name_len); } if (p_eir_remote_name) { - if (remote_name_len > BD_NAME_LEN) remote_name_len = BD_NAME_LEN; + if (remote_name_len > BD_NAME_LEN) { + remote_name_len = BD_NAME_LEN; + } if (p_remote_name && p_remote_name_len) { memcpy(p_remote_name, p_eir_remote_name, remote_name_len); @@ -447,16 +438,15 @@ static bool check_eir_remote_name(tBTA_DM_SEARCH* p_search_data, * Populate p_appearance, if provided and appearance found * ******************************************************************************/ -static bool check_eir_appearance(tBTA_DM_SEARCH* p_search_data, - uint16_t* p_appearance) { +static bool check_eir_appearance(tBTA_DM_SEARCH* p_search_data, uint16_t* p_appearance) { const uint8_t* p_eir_appearance = NULL; uint8_t appearance_len = 0; /* Check EIR for remote name and services */ if (p_search_data->inq_res.p_eir) { p_eir_appearance = AdvertiseDataParser::GetFieldByType( - p_search_data->inq_res.p_eir, p_search_data->inq_res.eir_len, - HCI_EIR_APPEARANCE_TYPE, &appearance_len); + p_search_data->inq_res.p_eir, p_search_data->inq_res.eir_len, HCI_EIR_APPEARANCE_TYPE, + &appearance_len); if (p_eir_appearance && appearance_len >= 2) { if (p_appearance) { @@ -480,18 +470,15 @@ static bool check_eir_appearance(tBTA_DM_SEARCH* p_search_data, * Populate p_remote_name, if provided and remote name found * ******************************************************************************/ -static bool get_cached_remote_name(const RawAddress& bd_addr, - uint8_t* p_remote_name, +static bool get_cached_remote_name(const RawAddress& bd_addr, uint8_t* p_remote_name, uint8_t* p_remote_name_len) { bt_bdname_t bdname; bt_property_t prop_name; /* check if we already have it in our btif_storage cache */ - BTIF_STORAGE_FILL_PROPERTY(&prop_name, BT_PROPERTY_BDNAME, - sizeof(bt_bdname_t), &bdname); - if (btif_storage_get_remote_device_property(&bd_addr, &prop_name) == - BT_STATUS_SUCCESS) { + BTIF_STORAGE_FILL_PROPERTY(&prop_name, BT_PROPERTY_BDNAME, sizeof(bt_bdname_t), &bdname); + if (btif_storage_get_remote_device_property(&bd_addr, &prop_name) == BT_STATUS_SUCCESS) { if (p_remote_name && p_remote_name_len) { strcpy((char*)p_remote_name, (char*)bdname.name); *p_remote_name_len = strlen((char*)p_remote_name); @@ -507,10 +494,10 @@ static uint32_t get_cod(const RawAddress* remote_bdaddr) { bt_property_t prop_name; /* check if we already have it in our btif_storage cache */ - BTIF_STORAGE_FILL_PROPERTY(&prop_name, BT_PROPERTY_CLASS_OF_DEVICE, - sizeof(uint32_t), &remote_cod); - if (btif_storage_get_remote_device_property( - (RawAddress*)remote_bdaddr, &prop_name) == BT_STATUS_SUCCESS) { + BTIF_STORAGE_FILL_PROPERTY(&prop_name, BT_PROPERTY_CLASS_OF_DEVICE, sizeof(uint32_t), + &remote_cod); + if (btif_storage_get_remote_device_property((RawAddress*)remote_bdaddr, &prop_name) == + BT_STATUS_SUCCESS) { return remote_cod; } @@ -553,20 +540,23 @@ static bool check_sdp_bl(const RawAddress* remote_bdaddr) { bt_property_t prop_name; bt_remote_version_t info; - if (remote_bdaddr == NULL) return false; + if (remote_bdaddr == NULL) { + return false; + } /* if not available yet, try fetching from config database */ BTIF_STORAGE_FILL_PROPERTY(&prop_name, BT_PROPERTY_REMOTE_VERSION_INFO, sizeof(bt_remote_version_t), &info); - if (btif_storage_get_remote_device_property(remote_bdaddr, &prop_name) != - BT_STATUS_SUCCESS) { + if (btif_storage_get_remote_device_property(remote_bdaddr, &prop_name) != BT_STATUS_SUCCESS) { return false; } uint16_t manufacturer = info.manufacturer; for (unsigned int i = 0; i < ARRAY_SIZE(sdp_rejectlist); i++) { - if (manufacturer == sdp_rejectlist[i].manufact_id) return true; + if (manufacturer == sdp_rejectlist[i].manufact_id) { + return true; + } } return false; } @@ -579,14 +569,13 @@ static void bond_state_changed(bt_status_t status, const RawAddress& bd_addr, // Cross key pairing so send callback for static address if (!pairing_cb.static_bdaddr.IsEmpty()) { BTM_LogHistory( - kBtmLogTagCallback, bd_addr, "Bond state changed", - base::StringPrintf( - "Crosskey bt_status:%s bond_state:%u reason:%s", - bt_status_text(status).c_str(), state, - hci_reason_code_text(to_hci_reason_code(pairing_cb.fail_reason)) - .c_str())); - GetInterfaceToProfiles()->events->invoke_bond_state_changed_cb( - status, bd_addr, state, pairing_cb.fail_reason); + kBtmLogTagCallback, bd_addr, "Bond state changed", + base::StringPrintf( + "Crosskey bt_status:%s bond_state:%u reason:%s", + bt_status_text(status).c_str(), state, + hci_reason_code_text(to_hci_reason_code(pairing_cb.fail_reason)).c_str())); + GetInterfaceToProfiles()->events->invoke_bond_state_changed_cb(status, bd_addr, state, + pairing_cb.fail_reason); } return; } @@ -596,20 +585,18 @@ static void bond_state_changed(bt_status_t status, const RawAddress& bd_addr, } log::info( - "Bond state changed to state={}[0:none, 1:bonding, " - "2:bonded],prev_state={}, sdp_attempts={}", - state, pairing_cb.state, pairing_cb.sdp_attempts); + "Bond state changed to state={}[0:none, 1:bonding, " + "2:bonded],prev_state={}, sdp_attempts={}", + state, pairing_cb.state, pairing_cb.sdp_attempts); if (state == BT_BOND_STATE_NONE) { forget_device_from_metric_id_allocator(bd_addr); - if (com::android::bluetooth::flags:: - bond_transport_after_bond_cancel_fix()) { + if (com::android::bluetooth::flags::bond_transport_after_bond_cancel_fix()) { btif_config_remove_device(bd_addr.ToString()); } - if (bluetooth::common::init_flags:: - pbap_pse_dynamic_version_upgrade_is_enabled()) { + if (bluetooth::common::init_flags::pbap_pse_dynamic_version_upgrade_is_enabled()) { if (btif_storage_is_pce_version_102(bd_addr)) { update_pce_entry_to_interop_database(bd_addr); } @@ -621,28 +608,23 @@ static void bond_state_changed(bt_status_t status, const RawAddress& bd_addr, } } BTM_LogHistory( - kBtmLogTagCallback, bd_addr, "Bond state changed", - base::StringPrintf( - "bt_status:%s bond_state:%u reason:%s", - bt_status_text(status).c_str(), state, - hci_reason_code_text(to_hci_reason_code(pairing_cb.fail_reason)) - .c_str())); - GetInterfaceToProfiles()->events->invoke_bond_state_changed_cb( - status, bd_addr, state, pairing_cb.fail_reason); - - if ((state == BT_BOND_STATE_NONE) && (pairing_cb.bd_addr != bd_addr) - && is_bonding_or_sdp()) { - log::warn( - "Ignoring bond state changed for unexpected device: {} pairing: {}", - bd_addr, pairing_cb.bd_addr); + kBtmLogTagCallback, bd_addr, "Bond state changed", + base::StringPrintf( + "bt_status:%s bond_state:%u reason:%s", bt_status_text(status).c_str(), state, + hci_reason_code_text(to_hci_reason_code(pairing_cb.fail_reason)).c_str())); + GetInterfaceToProfiles()->events->invoke_bond_state_changed_cb(status, bd_addr, state, + pairing_cb.fail_reason); + + if ((state == BT_BOND_STATE_NONE) && (pairing_cb.bd_addr != bd_addr) && is_bonding_or_sdp()) { + log::warn("Ignoring bond state changed for unexpected device: {} pairing: {}", bd_addr, + pairing_cb.bd_addr); return; } if (state == BT_BOND_STATE_BONDING || (state == BT_BOND_STATE_BONDED && (pairing_cb.sdp_attempts > 0 || - pairing_cb.gatt_over_le == - btif_dm_pairing_cb_t::ServiceDiscoveryState::SCHEDULED))) { + pairing_cb.gatt_over_le == btif_dm_pairing_cb_t::ServiceDiscoveryState::SCHEDULED))) { // Save state for the device is bonding or SDP or GATT over LE discovery pairing_cb.state = state; pairing_cb.bd_addr = bd_addr; @@ -664,12 +646,11 @@ static void btif_update_remote_version_property(RawAddress* p_bd) { log::assert_that(p_bd != nullptr, "assert failed: p_bd != nullptr"); - const bool version_info_valid = - get_btm_client_interface().peer.BTM_ReadRemoteVersion( + const bool version_info_valid = get_btm_client_interface().peer.BTM_ReadRemoteVersion( *p_bd, &lmp_ver, &mfct_set, &lmp_subver); - log::info("Remote version info valid:{} [{}]:0x{:x},0x{:x},0x{:x}", - version_info_valid, *p_bd, lmp_ver, mfct_set, lmp_subver); + log::info("Remote version info valid:{} [{}]:0x{:x},0x{:x},0x{:x}", version_info_valid, *p_bd, + lmp_ver, mfct_set, lmp_subver); if (version_info_valid) { // Always update cache to ensure we have availability whenever BTM API is @@ -680,14 +661,12 @@ static void btif_update_remote_version_property(RawAddress* p_bd) { BTIF_STORAGE_FILL_PROPERTY(&property, BT_PROPERTY_REMOTE_VERSION_INFO, sizeof(bt_remote_version_t), &info); status = btif_storage_set_remote_device_property(p_bd, &property); - ASSERTC(status == BT_STATUS_SUCCESS, "failed to save remote version", - status); + ASSERTC(status == BT_STATUS_SUCCESS, "failed to save remote version", status); } } -static void btif_update_remote_properties(const RawAddress& bdaddr, - BD_NAME bd_name, DEV_CLASS dev_class, - tBT_DEVICE_TYPE device_type) { +static void btif_update_remote_properties(const RawAddress& bdaddr, BD_NAME bd_name, + DEV_CLASS dev_class, tBT_DEVICE_TYPE device_type) { std::vector properties; bt_status_t status = BT_STATUS_UNHANDLED; uint32_t cod; @@ -695,12 +674,10 @@ static void btif_update_remote_properties(const RawAddress& bdaddr, /* remote name */ if (strlen((const char*)bd_name)) { - properties.push_back(bt_property_t{ - BT_PROPERTY_BDNAME, static_cast(strlen((char*)bd_name)), bd_name}); - status = - btif_storage_set_remote_device_property(&bdaddr, &properties.back()); - ASSERTC(status == BT_STATUS_SUCCESS, "failed to save remote device name", - status); + properties.push_back( + bt_property_t{BT_PROPERTY_BDNAME, static_cast(strlen((char*)bd_name)), bd_name}); + status = btif_storage_set_remote_device_property(&bdaddr, &properties.back()); + ASSERTC(status == BT_STATUS_SUCCESS, "failed to save remote device name", status); } uint32_t old_cod = get_cod(&bdaddr); @@ -715,41 +692,35 @@ static void btif_update_remote_properties(const RawAddress& bdaddr, log::info("{} CoD: 0x{:06x} -> 0x{:06x}", bdaddr, old_cod, cod); } - properties.push_back( - bt_property_t{BT_PROPERTY_CLASS_OF_DEVICE, sizeof(cod), &cod}); + properties.push_back(bt_property_t{BT_PROPERTY_CLASS_OF_DEVICE, sizeof(cod), &cod}); status = btif_storage_set_remote_device_property(&bdaddr, &properties.back()); - ASSERTC(status == BT_STATUS_SUCCESS, "failed to save remote device class", - status); + ASSERTC(status == BT_STATUS_SUCCESS, "failed to save remote device class", status); /* device type */ bt_property_t prop_name; uint32_t remote_dev_type; - BTIF_STORAGE_FILL_PROPERTY(&prop_name, BT_PROPERTY_TYPE_OF_DEVICE, - sizeof(uint32_t), &remote_dev_type); - if (btif_storage_get_remote_device_property(&bdaddr, &prop_name) == - BT_STATUS_SUCCESS) { + BTIF_STORAGE_FILL_PROPERTY(&prop_name, BT_PROPERTY_TYPE_OF_DEVICE, sizeof(uint32_t), + &remote_dev_type); + if (btif_storage_get_remote_device_property(&bdaddr, &prop_name) == BT_STATUS_SUCCESS) { dev_type = remote_dev_type | device_type; } else { dev_type = device_type; } - properties.push_back( - bt_property_t{BT_PROPERTY_TYPE_OF_DEVICE, sizeof(dev_type), &dev_type}); + properties.push_back(bt_property_t{BT_PROPERTY_TYPE_OF_DEVICE, sizeof(dev_type), &dev_type}); status = btif_storage_set_remote_device_property(&bdaddr, &properties.back()); - ASSERTC(status == BT_STATUS_SUCCESS, "failed to save remote device type", - status); + ASSERTC(status == BT_STATUS_SUCCESS, "failed to save remote device type", status); GetInterfaceToProfiles()->events->invoke_remote_device_properties_cb( - status, bdaddr, properties.size(), properties.data()); + status, bdaddr, properties.size(), properties.data()); } /* If device is LE Audio capable, we prefer LE connection first, this speeds * up LE profile connection, and limits all possible service discovery * ordering issues (first Classic, GATT over SDP, etc) */ bool is_device_le_audio_capable(const RawAddress bd_addr) { - if (!GetInterfaceToProfiles() - ->profileSpecific_HACK->IsLeAudioClientRunning()) { + if (!GetInterfaceToProfiles()->profileSpecific_HACK->IsLeAudioClientRunning()) { /* If LE Audio profile is not enabled, do nothing. */ return false; } @@ -762,8 +733,8 @@ bool is_device_le_audio_capable(const RawAddress bd_addr) { /* First try reading device type from BTIF - it persists over multiple * inquiry sessions */ int dev_type = 0; - if ((btif_get_device_type(bd_addr, &dev_type) && - (dev_type & BT_DEVICE_TYPE_BLE) == BT_DEVICE_TYPE_BLE)) { + if (btif_get_device_type(bd_addr, &dev_type) && + (dev_type & BT_DEVICE_TYPE_BLE) == BT_DEVICE_TYPE_BLE) { /* LE Audio capable device is discoverable over both LE and Classic using * same address. Prefer to use LE transport, as we don't know if it can do * CTKD from Classic to LE */ @@ -785,8 +756,7 @@ bool is_device_le_audio_capable(const RawAddress bd_addr) { /* use to check if device is LE Audio Capable during bonding */ bool is_le_audio_capable_during_service_discovery(const RawAddress& bd_addr) { - if (!GetInterfaceToProfiles() - ->profileSpecific_HACK->IsLeAudioClientRunning()) { + if (!GetInterfaceToProfiles()->profileSpecific_HACK->IsLeAudioClientRunning()) { /* If LE Audio profile is not enabled, do nothing. */ return false; } @@ -795,8 +765,7 @@ bool is_le_audio_capable_during_service_discovery(const RawAddress& bd_addr) { return false; } - if (check_cod_le_audio(bd_addr) || - metadata_cb.le_audio_cache.contains(bd_addr) || + if (check_cod_le_audio(bd_addr) || metadata_cb.le_audio_cache.contains(bd_addr) || metadata_cb.le_audio_cache.contains(pairing_cb.bd_addr) || BTA_DmCheckLeAudioCapable(bd_addr)) { return true; @@ -815,8 +784,7 @@ bool is_le_audio_capable_during_service_discovery(const RawAddress& bd_addr) { * Returns void * ******************************************************************************/ -static void btif_dm_cb_create_bond(const RawAddress bd_addr, - tBT_TRANSPORT transport) { +static void btif_dm_cb_create_bond(const RawAddress bd_addr, tBT_TRANSPORT transport) { bool is_hid = check_cod_hid_major(bd_addr, COD_HID_POINTING); bond_state_changed(BT_STATUS_SUCCESS, bd_addr, BT_BOND_STATE_BONDING); @@ -833,8 +801,7 @@ static void btif_dm_cb_create_bond(const RawAddress bd_addr, if (!btif_config_get_int(bdstr, BTIF_STORAGE_KEY_DEV_TYPE, &device_type)) { btif_config_set_int(bdstr, BTIF_STORAGE_KEY_DEV_TYPE, BT_DEVICE_TYPE_BLE); } - if (btif_storage_get_remote_addr_type(&bd_addr, &addr_type) != - BT_STATUS_SUCCESS) { + if (btif_storage_get_remote_addr_type(&bd_addr, &addr_type) != BT_STATUS_SUCCESS) { // Try to read address type. OOB pairing might have set it earlier, but // didn't store it, it defaults to BLE_ADDR_PUBLIC uint8_t tmp_dev_type; @@ -846,12 +813,10 @@ static void btif_dm_cb_create_bond(const RawAddress bd_addr, } } if ((btif_config_get_int(bdstr, BTIF_STORAGE_KEY_DEV_TYPE, &device_type) && - (btif_storage_get_remote_addr_type(&bd_addr, &addr_type) == - BT_STATUS_SUCCESS) && + (btif_storage_get_remote_addr_type(&bd_addr, &addr_type) == BT_STATUS_SUCCESS) && (device_type & BT_DEVICE_TYPE_BLE) == BT_DEVICE_TYPE_BLE) || (transport == BT_TRANSPORT_LE)) { - BTA_DmAddBleDevice(bd_addr, addr_type, - static_cast(device_type)); + BTA_DmAddBleDevice(bd_addr, addr_type, static_cast(device_type)); } BTA_DmBond(bd_addr, addr_type, transport, device_type); @@ -869,8 +834,7 @@ static void btif_dm_cb_create_bond(const RawAddress bd_addr, * Returns void * ******************************************************************************/ -static void btif_dm_cb_create_bond_le(const RawAddress bd_addr, - tBLE_ADDR_TYPE addr_type) { +static void btif_dm_cb_create_bond_le(const RawAddress bd_addr, tBLE_ADDR_TYPE addr_type) { bond_state_changed(BT_STATUS_SUCCESS, bd_addr, BT_BOND_STATE_BONDING); /* Handle only LE create bond with random address case */ BTA_DmAddBleDevice(bd_addr, addr_type, BT_DEVICE_TYPE_BLE); @@ -893,7 +857,7 @@ static void btif_dm_cb_create_bond_le(const RawAddress bd_addr, uint16_t btif_dm_get_connection_state(const RawAddress& bd_addr) { uint16_t rc = 0; if (BTA_DmGetConnectionState(bd_addr)) { - rc = (uint16_t) true; + rc = (uint16_t)true; if (BTM_IsEncrypted(bd_addr, BT_TRANSPORT_BR_EDR)) { rc |= ENCRYPTED_BREDR; } @@ -906,8 +870,7 @@ uint16_t btif_dm_get_connection_state(const RawAddress& bd_addr) { return rc; } -static uint16_t btif_dm_get_resolved_connection_state( - tBLE_BD_ADDR ble_bd_addr) { +static uint16_t btif_dm_get_resolved_connection_state(tBLE_BD_ADDR ble_bd_addr) { uint16_t rc = 0; if (maybe_resolve_address(&ble_bd_addr.bda, &ble_bd_addr.type)) { if (BTA_DmGetConnectionState(ble_bd_addr.bda)) { @@ -928,20 +891,18 @@ uint16_t btif_dm_get_connection_state_sync(const RawAddress& bd_addr) { std::future future = promise.get_future(); auto status = do_in_main_thread( - FROM_HERE, - base::BindOnce( - [](const RawAddress bd_addr, std::promise promise) { - // Experiment to try with maybe resolved address - uint16_t state = btif_dm_get_resolved_connection_state({ - .type = BLE_ADDR_RANDOM, - .bda = bd_addr, - }); - state |= btif_dm_get_connection_state(bd_addr); - promise.set_value(state); - }, - bd_addr, std::move(promise))); - log::assert_that(BT_STATUS_SUCCESS == status, - "assert failed: BT_STATUS_SUCCESS == status"); + FROM_HERE, base::BindOnce( + [](const RawAddress bd_addr, std::promise promise) { + // Experiment to try with maybe resolved address + uint16_t state = btif_dm_get_resolved_connection_state({ + .type = BLE_ADDR_RANDOM, + .bda = bd_addr, + }); + state |= btif_dm_get_connection_state(bd_addr); + promise.set_value(state); + }, + bd_addr, std::move(promise))); + log::assert_that(BT_STATUS_SUCCESS == status, "assert failed: BT_STATUS_SUCCESS == status"); return future.get(); } @@ -967,22 +928,20 @@ static void btif_dm_pin_req_evt(tBTA_DM_PIN_REQ* p_pin_req) { int dev_type; /* Remote properties update */ - if (get_btm_client_interface().peer.BTM_GetPeerDeviceTypeFromFeatures( - p_pin_req->bd_addr) == BT_DEVICE_TYPE_DUMO) { + if (get_btm_client_interface().peer.BTM_GetPeerDeviceTypeFromFeatures(p_pin_req->bd_addr) == + BT_DEVICE_TYPE_DUMO) { dev_type = BT_DEVICE_TYPE_DUMO; } else if (!btif_get_device_type(p_pin_req->bd_addr, &dev_type)) { // Failed to get device type, defaulting to BR/EDR. dev_type = BT_DEVICE_TYPE_BREDR; } - btif_update_remote_properties(p_pin_req->bd_addr, p_pin_req->bd_name, - p_pin_req->dev_class, + btif_update_remote_properties(p_pin_req->bd_addr, p_pin_req->bd_name, p_pin_req->dev_class, (tBT_DEVICE_TYPE)dev_type); const RawAddress& bd_addr = p_pin_req->bd_addr; bd_name_copy(bd_name.name, p_pin_req->bd_name); - if (pairing_cb.state == BT_BOND_STATE_BONDING && - bd_addr != pairing_cb.bd_addr) { + if (pairing_cb.state == BT_BOND_STATE_BONDING && bd_addr != pairing_cb.bd_addr) { log::warn("already in bonding state, reject request"); return; } @@ -999,15 +958,12 @@ static void btif_dm_pin_req_evt(tBTA_DM_PIN_REQ* p_pin_req) { /* check for auto pair possiblity only if bond was initiated by local device */ if (pairing_cb.is_local_initiated && !p_pin_req->min_16_digit) { - if (check_cod(&bd_addr, COD_AV_HEADSETS) || - check_cod(&bd_addr, COD_AV_HEADPHONES) || - check_cod(&bd_addr, COD_AV_PORTABLE_AUDIO) || - check_cod(&bd_addr, COD_AV_HIFI_AUDIO) || + if (check_cod(&bd_addr, COD_AV_HEADSETS) || check_cod(&bd_addr, COD_AV_HEADPHONES) || + check_cod(&bd_addr, COD_AV_PORTABLE_AUDIO) || check_cod(&bd_addr, COD_AV_HIFI_AUDIO) || check_cod_hid_major(bd_addr, COD_HID_POINTING)) { /* Check if this device can be auto paired */ if (!interop_match_addr(INTEROP_DISABLE_AUTO_PAIRING, &bd_addr) && - !interop_match_name(INTEROP_DISABLE_AUTO_PAIRING, - (const char*)bd_name.name) && + !interop_match_name(INTEROP_DISABLE_AUTO_PAIRING, (const char*)bd_name.name) && (pairing_cb.autopair_attempts == 0)) { log::debug("Attempting auto pair w/ IOP"); pin_code.pin[0] = 0x30; @@ -1021,8 +977,7 @@ static void btif_dm_pin_req_evt(tBTA_DM_PIN_REQ* p_pin_req) { } } else if (check_cod_hid_major(bd_addr, COD_HID_KEYBOARD) || check_cod_hid_major(bd_addr, COD_HID_COMBO)) { - if ((interop_match_addr(INTEROP_KEYBOARD_REQUIRES_FIXED_PIN, &bd_addr) == - true) && + if ((interop_match_addr(INTEROP_KEYBOARD_REQUIRES_FIXED_PIN, &bd_addr) == true) && (pairing_cb.autopair_attempts == 0)) { log::debug("Attempting auto pair w/ IOP"); pin_code.pin[0] = 0x30; @@ -1036,12 +991,11 @@ static void btif_dm_pin_req_evt(tBTA_DM_PIN_REQ* p_pin_req) { } } } - BTM_LogHistory( - kBtmLogTagCallback, bd_addr, "Pin request", - base::StringPrintf("name:\"%s\" min16:%c", PRIVATE_NAME(bd_name.name), - (p_pin_req->min_16_digit) ? 'T' : 'F')); - GetInterfaceToProfiles()->events->invoke_pin_request_cb( - bd_addr, bd_name, cod, p_pin_req->min_16_digit); + BTM_LogHistory(kBtmLogTagCallback, bd_addr, "Pin request", + base::StringPrintf("name:\"%s\" min16:%c", PRIVATE_NAME(bd_name.name), + (p_pin_req->min_16_digit) ? 'T' : 'F')); + GetInterfaceToProfiles()->events->invoke_pin_request_cb(bd_addr, bd_name, cod, + p_pin_req->min_16_digit); } /******************************************************************************* @@ -1061,21 +1015,19 @@ static void btif_dm_ssp_cfm_req_evt(tBTA_DM_SP_CFM_REQ* p_ssp_cfm_req) { p_ssp_cfm_req->bd_addr, dev_class_text(p_ssp_cfm_req->dev_class), p_ssp_cfm_req->just_works, p_ssp_cfm_req->loc_auth_req, p_ssp_cfm_req->rmt_auth_req); /* Remote properties update */ - if (get_btm_client_interface().peer.BTM_GetPeerDeviceTypeFromFeatures( - p_ssp_cfm_req->bd_addr) == BT_DEVICE_TYPE_DUMO) { + if (get_btm_client_interface().peer.BTM_GetPeerDeviceTypeFromFeatures(p_ssp_cfm_req->bd_addr) == + BT_DEVICE_TYPE_DUMO) { dev_type = BT_DEVICE_TYPE_DUMO; } else if (!btif_get_device_type(p_ssp_cfm_req->bd_addr, &dev_type)) { // Failed to get device type, defaulting to BR/EDR. dev_type = BT_DEVICE_TYPE_BREDR; } btif_update_remote_properties(p_ssp_cfm_req->bd_addr, p_ssp_cfm_req->bd_name, - p_ssp_cfm_req->dev_class, - (tBT_DEVICE_TYPE)dev_type); + p_ssp_cfm_req->dev_class, (tBT_DEVICE_TYPE)dev_type); RawAddress bd_addr = p_ssp_cfm_req->bd_addr; - if (pairing_cb.state == BT_BOND_STATE_BONDING && - bd_addr != pairing_cb.bd_addr) { + if (pairing_cb.state == BT_BOND_STATE_BONDING && bd_addr != pairing_cb.bd_addr) { log::warn("already in bonding state, reject request"); btif_dm_ssp_reply(bd_addr, BT_SSP_VARIANT_PASSKEY_CONFIRMATION, 0); return; @@ -1086,13 +1038,13 @@ static void btif_dm_ssp_cfm_req_evt(tBTA_DM_SP_CFM_REQ* p_ssp_cfm_req) { bond_state_changed(BT_STATUS_SUCCESS, bd_addr, BT_BOND_STATE_BONDING); /* if just_works and bonding bit is not set treat this as temporary */ - if (p_ssp_cfm_req->just_works && - !(p_ssp_cfm_req->loc_auth_req & BTM_AUTH_BONDS) && + if (p_ssp_cfm_req->just_works && !(p_ssp_cfm_req->loc_auth_req & BTM_AUTH_BONDS) && !(p_ssp_cfm_req->rmt_auth_req & BTM_AUTH_BONDS) && - !(check_cod_hid_major(p_ssp_cfm_req->bd_addr, COD_HID_POINTING))) + !(check_cod_hid_major(p_ssp_cfm_req->bd_addr, COD_HID_POINTING))) { pairing_cb.bond_type = BOND_TYPE_TEMPORARY; - else + } else { pairing_cb.bond_type = BOND_TYPE_PERSISTENT; + } btm_set_bond_type_dev(p_ssp_cfm_req->bd_addr, pairing_cb.bond_type); @@ -1104,8 +1056,7 @@ static void btif_dm_ssp_cfm_req_evt(tBTA_DM_SP_CFM_REQ* p_ssp_cfm_req) { * Incoming temporary pairing is detected */ if (is_incoming && pairing_cb.bond_type == BOND_TYPE_TEMPORARY) { - log::debug( - "Auto-accept JustWorks incoming pairing for temporary bonding"); + log::debug("Auto-accept JustWorks incoming pairing for temporary bonding"); btif_dm_ssp_reply(bd_addr, BT_SSP_VARIANT_CONSENT, true); return; } @@ -1113,14 +1064,13 @@ static void btif_dm_ssp_cfm_req_evt(tBTA_DM_SP_CFM_REQ* p_ssp_cfm_req) { pairing_cb.sdp_attempts = 0; BTM_LogHistory(kBtmLogTagCallback, bd_addr, "Ssp request", - base::StringPrintf("just_works:%c pin:%u", - (p_ssp_cfm_req->just_works) ? 'T' : 'F', + base::StringPrintf("just_works:%c pin:%u", (p_ssp_cfm_req->just_works) ? 'T' : 'F', p_ssp_cfm_req->num_val)); GetInterfaceToProfiles()->events->invoke_ssp_request_cb( - bd_addr, - (p_ssp_cfm_req->just_works ? BT_SSP_VARIANT_CONSENT - : BT_SSP_VARIANT_PASSKEY_CONFIRMATION), - p_ssp_cfm_req->num_val); + bd_addr, + (p_ssp_cfm_req->just_works ? BT_SSP_VARIANT_CONSENT + : BT_SSP_VARIANT_PASSKEY_CONFIRMATION), + p_ssp_cfm_req->num_val); } static void btif_dm_ssp_key_notif_evt(tBTA_DM_SP_KEY_NOTIF* p_ssp_key_notif) { @@ -1129,16 +1079,15 @@ static void btif_dm_ssp_key_notif_evt(tBTA_DM_SP_KEY_NOTIF* p_ssp_key_notif) { log::verbose("addr:{}", p_ssp_key_notif->bd_addr); /* Remote properties update */ - if (get_btm_client_interface().peer.BTM_GetPeerDeviceTypeFromFeatures( - p_ssp_key_notif->bd_addr) == BT_DEVICE_TYPE_DUMO) { + if (get_btm_client_interface().peer.BTM_GetPeerDeviceTypeFromFeatures(p_ssp_key_notif->bd_addr) == + BT_DEVICE_TYPE_DUMO) { dev_type = BT_DEVICE_TYPE_DUMO; } else if (!btif_get_device_type(p_ssp_key_notif->bd_addr, &dev_type)) { // Failed to get device type, defaulting to BR/EDR. dev_type = BT_DEVICE_TYPE_BREDR; } - btif_update_remote_properties( - p_ssp_key_notif->bd_addr, p_ssp_key_notif->bd_name, - p_ssp_key_notif->dev_class, (tBT_DEVICE_TYPE)dev_type); + btif_update_remote_properties(p_ssp_key_notif->bd_addr, p_ssp_key_notif->bd_name, + p_ssp_key_notif->dev_class, (tBT_DEVICE_TYPE)dev_type); RawAddress bd_addr = p_ssp_key_notif->bd_addr; @@ -1148,7 +1097,7 @@ static void btif_dm_ssp_key_notif_evt(tBTA_DM_SP_KEY_NOTIF* p_ssp_key_notif) { BTM_LogHistory(kBtmLogTagCallback, bd_addr, "Ssp request", base::StringPrintf("passkey:%u", p_ssp_key_notif->passkey)); GetInterfaceToProfiles()->events->invoke_ssp_request_cb( - bd_addr, BT_SSP_VARIANT_PASSKEY_NOTIFICATION, p_ssp_key_notif->passkey); + bd_addr, BT_SSP_VARIANT_PASSKEY_NOTIFICATION, p_ssp_key_notif->passkey); } /******************************************************************************* * @@ -1165,8 +1114,8 @@ static void btif_dm_auth_cmpl_evt(tBTA_DM_AUTH_CMPL* p_auth_cmpl) { bt_bond_state_t state = BT_BOND_STATE_NONE; bool skip_sdp = false; - log::info("bond state={}, success={}, key_present={}", pairing_cb.state, - p_auth_cmpl->success, p_auth_cmpl->key_present); + log::info("bond state={}, success={}, key_present={}", pairing_cb.state, p_auth_cmpl->success, + p_auth_cmpl->key_present); pairing_cb.fail_reason = p_auth_cmpl->fail_reason; @@ -1181,10 +1130,9 @@ static void btif_dm_auth_cmpl_evt(tBTA_DM_AUTH_CMPL* p_auth_cmpl) { bt_status_t ret; if (!bd_addr.IsEmpty()) { - log::debug("Storing link key. key_type=0x{:x}, bond_type={}", - p_auth_cmpl->key_type, pairing_cb.bond_type); - ret = btif_storage_add_bonded_device(&bd_addr, p_auth_cmpl->key, - p_auth_cmpl->key_type, + log::debug("Storing link key. key_type=0x{:x}, bond_type={}", p_auth_cmpl->key_type, + pairing_cb.bond_type); + ret = btif_storage_add_bonded_device(&bd_addr, p_auth_cmpl->key, p_auth_cmpl->key_type, pairing_cb.pin_code_len); } else { log::warn("bd_addr is empty"); @@ -1192,8 +1140,8 @@ static void btif_dm_auth_cmpl_evt(tBTA_DM_AUTH_CMPL* p_auth_cmpl) { } ASSERTC(ret == BT_STATUS_SUCCESS, "storing link key failed", ret); } else { - log::debug("Temporary key. Not storing. key_type=0x{:x}, bond_type={}", - p_auth_cmpl->key_type, pairing_cb.bond_type); + log::debug("Temporary key. Not storing. key_type=0x{:x}, bond_type={}", p_auth_cmpl->key_type, + pairing_cb.bond_type); if (pairing_cb.bond_type == BOND_TYPE_TEMPORARY) { log::debug("sending BT_BOND_STATE_NONE for Temp pairing"); btif_storage_remove_bonded_device(&bd_addr); @@ -1214,8 +1162,7 @@ static void btif_dm_auth_cmpl_evt(tBTA_DM_AUTH_CMPL* p_auth_cmpl) { // derivation to allow bond state change notification for the BR/EDR // transport so that the subsequent BR/EDR connections to the remote can use // the derived link key. - if (p_auth_cmpl->bd_addr != pairing_cb.bd_addr && - (!pairing_cb.ble.is_penc_key_rcvd)) { + if (p_auth_cmpl->bd_addr != pairing_cb.bd_addr && (!pairing_cb.ble.is_penc_key_rcvd)) { log::warn("skipping SDP for unknown device {}", p_auth_cmpl->bd_addr); return; } @@ -1223,8 +1170,8 @@ static void btif_dm_auth_cmpl_evt(tBTA_DM_AUTH_CMPL* p_auth_cmpl) { btif_storage_set_remote_addr_type(&bd_addr, p_auth_cmpl->addr_type); int dev_type; - if (get_btm_client_interface().peer.BTM_GetPeerDeviceTypeFromFeatures( - bd_addr) == BT_DEVICE_TYPE_DUMO) { + if (get_btm_client_interface().peer.BTM_GetPeerDeviceTypeFromFeatures(bd_addr) == + BT_DEVICE_TYPE_DUMO) { dev_type = BT_DEVICE_TYPE_DUMO; } else { dev_type = p_auth_cmpl->dev_type; @@ -1237,8 +1184,8 @@ static void btif_dm_auth_cmpl_evt(tBTA_DM_AUTH_CMPL* p_auth_cmpl) { } if (!is_crosskey) { - btif_update_remote_properties(p_auth_cmpl->bd_addr, p_auth_cmpl->bd_name, - kDevClassEmpty, dev_type); + btif_update_remote_properties(p_auth_cmpl->bd_addr, p_auth_cmpl->bd_name, kDevClassEmpty, + dev_type); } pairing_cb.timeout_retries = 0; @@ -1261,16 +1208,15 @@ static void btif_dm_auth_cmpl_evt(tBTA_DM_AUTH_CMPL* p_auth_cmpl) { prop.val = &uuid; prop.len = Uuid::kNumBytes128; - GetInterfaceToProfiles()->events->invoke_remote_device_properties_cb( - BT_STATUS_SUCCESS, bd_addr, 1, &prop); + GetInterfaceToProfiles()->events->invoke_remote_device_properties_cb(BT_STATUS_SUCCESS, + bd_addr, 1, &prop); } else { /* If bonded due to cross-key, save the static address too*/ if (is_crosskey) { log::debug("bonding initiated due to cross key, adding static address"); pairing_cb.static_bdaddr = bd_addr; } - if (!is_crosskey || - !(stack_config_get_interface()->get_pts_crosskey_sdp_disable())) { + if (!is_crosskey || !(stack_config_get_interface()->get_pts_crosskey_sdp_disable())) { // Ensure inquiry is stopped before attempting service discovery btif_dm_cancel_discovery(); @@ -1281,11 +1227,10 @@ static void btif_dm_auth_cmpl_evt(tBTA_DM_AUTH_CMPL* p_auth_cmpl) { // If bonding occurred due to cross-key pairing, send address // consolidate callback BTM_LogHistory( - kBtmLogTagCallback, bd_addr, "Consolidate", - base::StringPrintf(" <=> %s", - ADDRESS_TO_LOGGABLE_CSTR(pairing_cb.bd_addr))); - GetInterfaceToProfiles()->events->invoke_address_consolidate_cb( - pairing_cb.bd_addr, bd_addr); + kBtmLogTagCallback, bd_addr, "Consolidate", + base::StringPrintf(" <=> %s", ADDRESS_TO_LOGGABLE_CSTR(pairing_cb.bd_addr))); + GetInterfaceToProfiles()->events->invoke_address_consolidate_cb(pairing_cb.bd_addr, + bd_addr); } else { bond_state_changed(BT_STATUS_SUCCESS, bd_addr, BT_BOND_STATE_BONDED); } @@ -1293,8 +1238,7 @@ static void btif_dm_auth_cmpl_evt(tBTA_DM_AUTH_CMPL* p_auth_cmpl) { if (pairing_cb.sdp_over_classic == btif_dm_pairing_cb_t::ServiceDiscoveryState::NOT_STARTED) { log::info("scheduling SDP for {}", bd_addr); - pairing_cb.sdp_over_classic = - btif_dm_pairing_cb_t::ServiceDiscoveryState::SCHEDULED; + pairing_cb.sdp_over_classic = btif_dm_pairing_cb_t::ServiceDiscoveryState::SCHEDULED; btif_dm_get_remote_services(bd_addr, BT_TRANSPORT_BR_EDR); } } @@ -1311,8 +1255,7 @@ static void btif_dm_auth_cmpl_evt(tBTA_DM_AUTH_CMPL* p_auth_cmpl) { case HCI_ERR_LMP_RESPONSE_TIMEOUT: if (interop_match_addr(INTEROP_AUTO_RETRY_PAIRING, &bd_addr) && pairing_cb.timeout_retries) { - log::warn("Pairing timeout; retrying ({}) ...", - pairing_cb.timeout_retries); + log::warn("Pairing timeout; retrying ({}) ...", pairing_cb.timeout_retries); --pairing_cb.timeout_retries; if (addr_type == BLE_ADDR_RANDOM) { btif_dm_cb_create_bond_le(bd_addr, addr_type); @@ -1343,8 +1286,7 @@ static void btif_dm_auth_cmpl_evt(tBTA_DM_AUTH_CMPL* p_auth_cmpl) { case HCI_ERR_INSUFFCIENT_SECURITY: case HCI_ERR_PEER_USER: case HCI_ERR_UNSPECIFIED: - log::warn("Authentication fail:{}", - hci_reason_code_text(p_auth_cmpl->fail_reason)); + log::warn("Authentication fail:{}", hci_reason_code_text(p_auth_cmpl->fail_reason)); if (pairing_cb.autopair_attempts == 1) { /* Create the Bond once again */ log::warn("auto pair failed. Reinitiate Bond"); @@ -1386,15 +1328,13 @@ static void btif_dm_auth_cmpl_evt(tBTA_DM_AUTH_CMPL* p_auth_cmpl) { * Returns void * *****************************************************************************/ -static void btif_dm_search_devices_evt(tBTA_DM_SEARCH_EVT event, - tBTA_DM_SEARCH* p_search_data) { +static void btif_dm_search_devices_evt(tBTA_DM_SEARCH_EVT event, tBTA_DM_SEARCH* p_search_data) { log::verbose("event={}", dump_dm_search_event(event)); switch (event) { case BTA_DM_NAME_READ_EVT: { btif_on_name_read(p_search_data->name_res.bd_addr, HCI_SUCCESS, - p_search_data->name_res.bd_name, - true /* duirng_device_search */); + p_search_data->name_res.bd_name, true /* during_device_search */); } break; case BTA_DM_INQ_RES_EVT: { @@ -1406,23 +1346,22 @@ static void btif_dm_search_devices_evt(tBTA_DM_SEARCH_EVT event, if (p_search_data->inq_res.inq_result_type != BT_DEVICE_TYPE_BLE) { p_search_data->inq_res.remt_name_not_required = - check_eir_remote_name(p_search_data, NULL, NULL); + check_eir_remote_name(p_search_data, NULL, NULL); } RawAddress& bdaddr = p_search_data->inq_res.bd_addr; - log::verbose("addr:{} device_type=0x{:x}", bdaddr, - p_search_data->inq_res.device_type); + log::verbose("addr:{} device_type=0x{:x}", bdaddr, p_search_data->inq_res.device_type); bdname.name[0] = 0; - if (!check_eir_remote_name(p_search_data, bdname.name, &remote_name_len)) - get_cached_remote_name(p_search_data->inq_res.bd_addr, bdname.name, - &remote_name_len); + if (!check_eir_remote_name(p_search_data, bdname.name, &remote_name_len)) { + get_cached_remote_name(p_search_data->inq_res.bd_addr, bdname.name, &remote_name_len); + } /* Check EIR for services */ if (p_search_data->inq_res.p_eir) { if (!get_btm_client_interface().eir.BTM_GetEirUuidList( - p_search_data->inq_res.p_eir, p_search_data->inq_res.eir_len, - Uuid::kNumBytes16, &num_uuids, uuid_list, max_num_uuid)) { + p_search_data->inq_res.p_eir, p_search_data->inq_res.eir_len, Uuid::kNumBytes16, + &num_uuids, uuid_list, max_num_uuid)) { log::debug("Unable to find service uuids in EIR peer:{}", bdaddr); } } @@ -1435,15 +1374,13 @@ static void btif_dm_search_devices_evt(tBTA_DM_SEARCH_EVT event, tBLE_ADDR_TYPE addr_type = BLE_ADDR_PUBLIC; /* RawAddress */ - bt_properties.push_back( - bt_property_t{BT_PROPERTY_BDADDR, sizeof(bdaddr), &bdaddr}); + bt_properties.push_back(bt_property_t{BT_PROPERTY_BDADDR, sizeof(bdaddr), &bdaddr}); /* BD_NAME */ /* Don't send BDNAME if it is empty */ if (bdname.name[0]) { bt_properties.push_back(bt_property_t{ - BT_PROPERTY_BDNAME, static_cast(strlen((char*)bdname.name)), - &bdname}); + BT_PROPERTY_BDNAME, static_cast(strlen((char*)bdname.name)), &bdname}); } /* DEV_CLASS */ @@ -1457,7 +1394,7 @@ static void btif_dm_search_devices_evt(tBTA_DM_SEARCH_EVT event, btif_storage_add_remote_device */ uint32_t old_cod = get_cod(&bdaddr); if (com::android::bluetooth::flags:: - do_not_replace_existing_cod_with_uncategorized_cod()) { + do_not_replace_existing_cod_with_uncategorized_cod()) { if (cod == COD_UNCLASSIFIED && old_cod != 0) { cod = old_cod; } @@ -1466,12 +1403,10 @@ static void btif_dm_search_devices_evt(tBTA_DM_SEARCH_EVT event, if (old_cod != cod) { log::info("{} CoD: 0x{:06x} -> 0x{:06x}", bdaddr, old_cod, cod); } - bt_properties.push_back( - bt_property_t{BT_PROPERTY_CLASS_OF_DEVICE, sizeof(cod), &cod}); + bt_properties.push_back(bt_property_t{BT_PROPERTY_CLASS_OF_DEVICE, sizeof(cod), &cod}); } - log::verbose("clock_offset is 0x{:x}", - p_search_data->inq_res.clock_offset); + log::verbose("clock_offset is 0x{:x}", p_search_data->inq_res.clock_offset); if (p_search_data->inq_res.clock_offset & BTM_CLOCK_OFFSET_VALID) { btif_set_device_clockoffset(bdaddr, (int)p_search_data->inq_res.clock_offset); } @@ -1494,17 +1429,15 @@ static void btif_dm_search_devices_evt(tBTA_DM_SEARCH_EVT event, if (p_search_data->inq_res.device_type == BT_DEVICE_TYPE_BLE) { addr_type = p_search_data->inq_res.ble_addr_type; } - bt_properties.push_back(bt_property_t{BT_PROPERTY_TYPE_OF_DEVICE, - sizeof(dev_type), &dev_type}); + bt_properties.push_back( + bt_property_t{BT_PROPERTY_TYPE_OF_DEVICE, sizeof(dev_type), &dev_type}); /* RSSI */ - bt_properties.push_back(bt_property_t{BT_PROPERTY_REMOTE_RSSI, - sizeof(int8_t), + bt_properties.push_back(bt_property_t{BT_PROPERTY_REMOTE_RSSI, sizeof(int8_t), &(p_search_data->inq_res.rssi)}); /* CSIP supported device */ - bt_properties.push_back( - bt_property_t{BT_PROPERTY_REMOTE_IS_COORDINATED_SET_MEMBER, - sizeof(bool), &(p_search_data->inq_res.include_rsi)}); + bt_properties.push_back(bt_property_t{BT_PROPERTY_REMOTE_IS_COORDINATED_SET_MEMBER, + sizeof(bool), &(p_search_data->inq_res.include_rsi)}); // The default negative value means ASHA capability not found. // A non-negative value represents ASHA capability information is valid. @@ -1514,16 +1447,13 @@ static void btif_dm_search_devices_evt(tBTA_DM_SEARCH_EVT event, // contains ASHA truncated HiSyncId if asha_capability is non-negative uint32_t asha_truncated_hi_sync_id = 0; - get_asha_service_data(p_search_data->inq_res, asha_capability, - asha_truncated_hi_sync_id); + get_asha_service_data(p_search_data->inq_res, asha_capability, asha_truncated_hi_sync_id); - bt_properties.push_back( - bt_property_t{BT_PROPERTY_REMOTE_ASHA_CAPABILITY, sizeof(int16_t), - &asha_capability}); + bt_properties.push_back(bt_property_t{BT_PROPERTY_REMOTE_ASHA_CAPABILITY, sizeof(int16_t), + &asha_capability}); - bt_properties.push_back( - bt_property_t{BT_PROPERTY_REMOTE_ASHA_TRUNCATED_HISYNCID, - sizeof(uint32_t), &asha_truncated_hi_sync_id}); + bt_properties.push_back(bt_property_t{BT_PROPERTY_REMOTE_ASHA_TRUNCATED_HISYNCID, + sizeof(uint32_t), &asha_truncated_hi_sync_id}); // Floss expects that EIR uuids are immediately reported when the // device is found and doesn't wait for the pairing intent. @@ -1555,50 +1485,45 @@ static void btif_dm_search_devices_evt(tBTA_DM_SEARCH_EVT event, if (report_eir_uuids) { for (auto uuid : uuid_iter->second) { auto uuid_128bit = uuid.To128BitBE(); - property_value.insert(property_value.end(), uuid_128bit.begin(), - uuid_128bit.end()); + property_value.insert(property_value.end(), uuid_128bit.begin(), uuid_128bit.end()); } - bt_properties.push_back(bt_property_t{ - BT_PROPERTY_UUIDS, - static_cast(uuid_iter->second.size() * Uuid::kNumBytes128), - (void*)property_value.data()}); + bt_properties.push_back( + bt_property_t{BT_PROPERTY_UUIDS, + static_cast(uuid_iter->second.size() * Uuid::kNumBytes128), + (void*)property_value.data()}); } } // Floss needs appearance for metrics purposes uint16_t appearance = 0; if (check_eir_appearance(p_search_data, &appearance)) { - bt_properties.push_back(bt_property_t{ - BT_PROPERTY_APPEARANCE, sizeof(appearance), &appearance}); + bt_properties.push_back( + bt_property_t{BT_PROPERTY_APPEARANCE, sizeof(appearance), &appearance}); } - status = btif_storage_add_remote_device(&bdaddr, bt_properties.size(), - bt_properties.data()); - ASSERTC(status == BT_STATUS_SUCCESS, - "failed to save remote device (inquiry)", status); + status = + btif_storage_add_remote_device(&bdaddr, bt_properties.size(), bt_properties.data()); + ASSERTC(status == BT_STATUS_SUCCESS, "failed to save remote device (inquiry)", status); status = btif_storage_set_remote_addr_type(&bdaddr, addr_type); - ASSERTC(status == BT_STATUS_SUCCESS, - "failed to save remote addr type (inquiry)", status); + ASSERTC(status == BT_STATUS_SUCCESS, "failed to save remote addr type (inquiry)", status); - bool restrict_report = osi_property_get_bool( - "bluetooth.restrict_discovered_device.enabled", false); - if (restrict_report && - p_search_data->inq_res.device_type == BT_DEVICE_TYPE_BLE && + bool restrict_report = + osi_property_get_bool("bluetooth.restrict_discovered_device.enabled", false); + if (restrict_report && p_search_data->inq_res.device_type == BT_DEVICE_TYPE_BLE && !(p_search_data->inq_res.ble_evt_type & BTM_BLE_CONNECTABLE_MASK)) { log::debug("Ble device {} is not connectable", bdaddr); break; } /* Callback to notify upper layer of device */ - GetInterfaceToProfiles()->events->invoke_device_found_cb( - bt_properties.size(), bt_properties.data()); + GetInterfaceToProfiles()->events->invoke_device_found_cb(bt_properties.size(), + bt_properties.data()); } } break; case BTA_DM_DISC_CMPL_EVT: { - GetInterfaceToProfiles()->events->invoke_discovery_state_changed_cb( - BT_DISCOVERY_STOPPED); + GetInterfaceToProfiles()->events->invoke_discovery_state_changed_cb(BT_DISCOVERY_STOPPED); } break; case BTA_DM_SEARCH_CANCEL_CMPL_EVT: { /* if inquiry is not in progress and we get a cancel event, then @@ -1611,8 +1536,7 @@ static void btif_dm_search_devices_evt(tBTA_DM_SEARCH_EVT event, * */ if (!btif_dm_inquiry_in_progress) { - GetInterfaceToProfiles()->events->invoke_discovery_state_changed_cb( - BT_DISCOVERY_STOPPED); + GetInterfaceToProfiles()->events->invoke_discovery_state_changed_cb(BT_DISCOVERY_STOPPED); } } break; default: @@ -1623,26 +1547,21 @@ static void btif_dm_search_devices_evt(tBTA_DM_SEARCH_EVT event, /* Returns true if |uuid| should be passed as device property */ static bool btif_is_interesting_le_service(bluetooth::Uuid uuid) { - return (uuid.As16Bit() == UUID_SERVCLASS_LE_HID || uuid == UUID_HEARING_AID || - uuid == UUID_VC || uuid == UUID_CSIS || uuid == UUID_LE_AUDIO || - uuid == UUID_LE_MIDI || uuid == UUID_HAS || uuid == UUID_BASS || - uuid == UUID_BATTERY || - (com::android::bluetooth::flags::android_headtracker_service() && - uuid == ANDROID_HEADTRACKER_SERVICE_UUID)); + return uuid.As16Bit() == UUID_SERVCLASS_LE_HID || uuid == UUID_HEARING_AID || uuid == UUID_VC || + uuid == UUID_CSIS || uuid == UUID_LE_AUDIO || uuid == UUID_LE_MIDI || uuid == UUID_HAS || + uuid == UUID_BASS || uuid == UUID_BATTERY || + (com::android::bluetooth::flags::android_headtracker_service() && + uuid == ANDROID_HEADTRACKER_SERVICE_UUID); } -static bt_status_t btif_get_existing_uuids(RawAddress* bd_addr, - Uuid* existing_uuids) { +static bt_status_t btif_get_existing_uuids(RawAddress* bd_addr, Uuid* existing_uuids) { bt_property_t tmp_prop; - BTIF_STORAGE_FILL_PROPERTY(&tmp_prop, BT_PROPERTY_UUIDS, - sizeof(existing_uuids), existing_uuids); + BTIF_STORAGE_FILL_PROPERTY(&tmp_prop, BT_PROPERTY_UUIDS, sizeof(existing_uuids), existing_uuids); return btif_storage_get_remote_device_property(bd_addr, &tmp_prop); } -static bool btif_should_ignore_uuid(const Uuid& uuid) { - return uuid.IsEmpty() || uuid.IsBase(); -} +static bool btif_should_ignore_uuid(const Uuid& uuid) { return uuid.IsEmpty() || uuid.IsBase(); } static bool btif_is_gatt_service_discovery_post_pairing(const RawAddress bd_addr) { return (bd_addr == pairing_cb.bd_addr || bd_addr == pairing_cb.static_bdaddr) && @@ -1653,7 +1572,9 @@ static void btif_merge_existing_uuids(RawAddress& addr, std::set* uuids) { Uuid existing_uuids[BT_MAX_NUM_UUIDS] = {}; bt_status_t lookup_result = btif_get_existing_uuids(&addr, existing_uuids); - if (lookup_result == BT_STATUS_FAIL) return; + if (lookup_result == BT_STATUS_FAIL) { + return; + } for (int i = 0; i < BT_MAX_NUM_UUIDS; i++) { Uuid uuid = existing_uuids[i]; @@ -1667,16 +1588,16 @@ static void btif_merge_existing_uuids(RawAddress& addr, std::set* uuids) { } } -static void btif_on_service_discovery_results( - RawAddress bd_addr, const std::vector& uuids_param, - tBTA_STATUS result) { +static void btif_on_service_discovery_results(RawAddress bd_addr, + const std::vector& uuids_param, + tBTA_STATUS result) { bt_property_t prop; std::vector property_value; std::set uuids; bool a2dp_sink_capable = false; bool results_for_bonding_device = - (bd_addr == pairing_cb.bd_addr || bd_addr == pairing_cb.static_bdaddr); + (bd_addr == pairing_cb.bd_addr || bd_addr == pairing_cb.static_bdaddr); if (results_for_bonding_device && result != BTA_SUCCESS && pairing_cb.state == BT_BOND_STATE_BONDED && @@ -1693,8 +1614,7 @@ static void btif_on_service_discovery_results( if (results_for_bonding_device) { log::info("SDP finished for {}:", bd_addr); - pairing_cb.sdp_over_classic = - btif_dm_pairing_cb_t::ServiceDiscoveryState::FINISHED; + pairing_cb.sdp_over_classic = btif_dm_pairing_cb_t::ServiceDiscoveryState::FINISHED; } prop.type = BT_PROPERTY_UUIDS; @@ -1718,8 +1638,7 @@ static void btif_on_service_discovery_results( for (auto& uuid : uuids) { auto uuid_128bit = uuid.To128BitBE(); - property_value.insert(property_value.end(), uuid_128bit.begin(), - uuid_128bit.end()); + property_value.insert(property_value.end(), uuid_128bit.begin(), uuid_128bit.end()); if (uuid == UUID_A2DP_SINK) { a2dp_sink_capable = true; } @@ -1734,8 +1653,7 @@ static void btif_on_service_discovery_results( * finished GATT over LE yet, then wait for LE service discovery to finish * before before passing services to upper layers. */ if (results_for_bonding_device && a2dp_sink_capable && - pairing_cb.gatt_over_le != - btif_dm_pairing_cb_t::ServiceDiscoveryState::FINISHED && + pairing_cb.gatt_over_le != btif_dm_pairing_cb_t::ServiceDiscoveryState::FINISHED && is_le_audio_capable_during_service_discovery(bd_addr)) { skip_reporting_wait_for_le = true; } @@ -1756,12 +1674,10 @@ static void btif_on_service_discovery_results( auto uuids_iter = eir_uuids_cache.find(bd_addr); if (uuids_iter != eir_uuids_cache.end()) { num_eir_uuids = uuids_iter->second.size(); - log::info("SDP failed, send {} EIR UUIDs to unblock bonding {}", - num_eir_uuids, bd_addr); + log::info("SDP failed, send {} EIR UUIDs to unblock bonding {}", num_eir_uuids, bd_addr); for (auto eir_uuid : uuids_iter->second) { auto uuid_128bit = eir_uuid.To128BitBE(); - property_value.insert(property_value.end(), uuid_128bit.begin(), - uuid_128bit.end()); + property_value.insert(property_value.end(), uuid_128bit.begin(), uuid_128bit.end()); } eir_uuids_cache.erase(uuids_iter); } @@ -1786,20 +1702,19 @@ static void btif_on_service_discovery_results( const tBTA_STATUS bta_status = result; BTM_LogHistory(kBtmLogTagSdp, bd_addr, "Discovered services", base::StringPrintf("bta_status:%s sdp_uuids:%zu eir_uuids:%zu", - bta_status_text(bta_status).c_str(), - uuids_param.size(), num_eir_uuids)); + bta_status_text(bta_status).c_str(), uuids_param.size(), + num_eir_uuids)); if (!uuids_param.empty() || num_eir_uuids != 0) { /* Also write this to the NVRAM */ - const bt_status_t ret = - btif_storage_set_remote_device_property(&bd_addr, &prop); + const bt_status_t ret = btif_storage_set_remote_device_property(&bd_addr, &prop); ASSERTC(ret == BT_STATUS_SUCCESS, "storing remote services failed", ret); if (skip_reporting_wait_for_le) { log::info( - "Bonding LE Audio sink - must wait for le services discovery to pass " - "all services to java {}", - bd_addr); + "Bonding LE Audio sink - must wait for le services discovery to pass " + "all services to java {}", + bd_addr); /* For LE Audio capable devices, we care more about passing GATT LE * services than about just finishing pairing. Service discovery * should be scheduled when LE pairing finishes, by call to @@ -1808,14 +1723,13 @@ static void btif_on_service_discovery_results( } /* Send the event to the BTIF */ - GetInterfaceToProfiles()->events->invoke_remote_device_properties_cb( - BT_STATUS_SUCCESS, bd_addr, 1, &prop); + GetInterfaceToProfiles()->events->invoke_remote_device_properties_cb(BT_STATUS_SUCCESS, bd_addr, + 1, &prop); } } void btif_on_gatt_results(RawAddress bd_addr, BD_NAME bd_name, - std::vector& services, - bool transport_le) { + std::vector& services, bool transport_le) { std::vector prop; std::vector property_value; std::set uuids; @@ -1824,14 +1738,11 @@ void btif_on_gatt_results(RawAddress bd_addr, BD_NAME bd_name, if (transport_le) { log::info("New GATT over LE UUIDs for {}:", bd_addr); - BTM_LogHistory(kBtmLogTag, bd_addr, - "Discovered GATT services using LE transport"); + BTM_LogHistory(kBtmLogTag, bd_addr, "Discovered GATT services using LE transport"); if (btif_is_gatt_service_discovery_post_pairing(bd_addr)) { - pairing_cb.gatt_over_le = - btif_dm_pairing_cb_t::ServiceDiscoveryState::FINISHED; + pairing_cb.gatt_over_le = btif_dm_pairing_cb_t::ServiceDiscoveryState::FINISHED; - if (pairing_cb.sdp_over_classic != - btif_dm_pairing_cb_t::ServiceDiscoveryState::SCHEDULED) { + if (pairing_cb.sdp_over_classic != btif_dm_pairing_cb_t::ServiceDiscoveryState::SCHEDULED) { // Both SDP and bonding are either done, or not scheduled, // we are safe to clear the service discovery part of CB. log::debug("clearing pairing_cb"); @@ -1842,20 +1753,19 @@ void btif_on_gatt_results(RawAddress bd_addr, BD_NAME bd_name, /* LE Audio profile should relax parameters when it connects. If * profile is not enabled, relax parameters after timeout. */ log::debug("Scheduling conn params unlock for {}", bd_addr); - do_in_main_thread_delayed( - FROM_HERE, - base::BindOnce( - [](RawAddress bd_addr) { - L2CA_LockBleConnParamsForProfileConnection(bd_addr, false); - }, - bd_addr), - std::chrono::seconds(15)); + do_in_main_thread_delayed(FROM_HERE, + base::BindOnce( + [](RawAddress bd_addr) { + L2CA_LockBleConnParamsForProfileConnection(bd_addr, + false); + }, + bd_addr), + std::chrono::seconds(15)); } } } else { log::debug("New GATT over SDP UUIDs for {}:", bd_addr); - BTM_LogHistory(kBtmLogTag, bd_addr, - "Discovered GATT services using SDP transport"); + BTM_LogHistory(kBtmLogTag, bd_addr, "Discovered GATT services using SDP transport"); } for (Uuid uuid : services) { @@ -1863,8 +1773,7 @@ void btif_on_gatt_results(RawAddress bd_addr, BD_NAME bd_name, if (btif_should_ignore_uuid(uuid)) { continue; } - log::info("index:{} uuid:{}", static_cast(uuids.size()), - uuid.ToString()); + log::info("index:{} uuid:{}", static_cast(uuids.size()), uuid.ToString()); uuids.insert(uuid); } } @@ -1882,9 +1791,8 @@ void btif_on_gatt_results(RawAddress bd_addr, BD_NAME bd_name, if (lea_supported) { if (bluetooth::common::init_flags:: - sdp_return_classic_services_when_le_discovery_fails_is_enabled()) { - log::info( - "Will return Classic SDP results, if done, to unblock bonding"); + sdp_return_classic_services_when_le_discovery_fails_is_enabled()) { + log::info("Will return Classic SDP results, if done, to unblock bonding"); } else { // LEA device w/o this flag // TODO: we might want to remove bond or do some action on @@ -1901,8 +1809,7 @@ void btif_on_gatt_results(RawAddress bd_addr, BD_NAME bd_name, Uuid existing_uuids[BT_MAX_NUM_UUIDS] = {}; // Look up UUIDs using pseudo address (either RPA or static address) - bt_status_t existing_lookup_result = - btif_get_existing_uuids(&bd_addr, existing_uuids); + bt_status_t existing_lookup_result = btif_get_existing_uuids(&bd_addr, existing_uuids); if (existing_lookup_result != BT_STATUS_FAIL) { log::info("Got some existing UUIDs by address {}", bd_addr); @@ -1918,11 +1825,9 @@ void btif_on_gatt_results(RawAddress bd_addr, BD_NAME bd_name, if (bd_addr != static_addr_copy) { // Look up UUID using static address, if different than sudo address - existing_lookup_result = - btif_get_existing_uuids(&static_addr_copy, existing_uuids); + existing_lookup_result = btif_get_existing_uuids(&static_addr_copy, existing_uuids); if (existing_lookup_result != BT_STATUS_FAIL) { - log::info("Got some existing UUIDs by static address {}", - static_addr_copy); + log::info("Got some existing UUIDs by static address {}", static_addr_copy); for (int i = 0; i < BT_MAX_NUM_UUIDS; i++) { Uuid uuid = existing_uuids[i]; if (uuid.IsEmpty()) { @@ -1935,29 +1840,25 @@ void btif_on_gatt_results(RawAddress bd_addr, BD_NAME bd_name, for (auto& uuid : uuids) { auto uuid_128bit = uuid.To128BitBE(); - property_value.insert(property_value.end(), uuid_128bit.begin(), - uuid_128bit.end()); + property_value.insert(property_value.end(), uuid_128bit.begin(), uuid_128bit.end()); } - prop.push_back(bt_property_t{ - BT_PROPERTY_UUIDS, static_cast(Uuid::kNumBytes128 * uuids.size()), - (void*)property_value.data()}); + prop.push_back(bt_property_t{BT_PROPERTY_UUIDS, + static_cast(Uuid::kNumBytes128 * uuids.size()), + (void*)property_value.data()}); /* Also write this to the NVRAM */ bt_status_t ret = btif_storage_set_remote_device_property(&bd_addr, &prop[0]); ASSERTC(ret == BT_STATUS_SUCCESS, "storing remote services failed", ret); /* Remote name update */ - if (!com::android::bluetooth::flags:: - separate_service_and_device_discovery() && + if (!com::android::bluetooth::flags::separate_service_and_device_discovery() && strnlen((const char*)bd_name, BD_NAME_LEN)) { - prop.push_back(bt_property_t{ - BT_PROPERTY_BDNAME, - static_cast(strnlen((char*)bd_name, BD_NAME_LEN)), bd_name}); + prop.push_back(bt_property_t{BT_PROPERTY_BDNAME, + static_cast(strnlen((char*)bd_name, BD_NAME_LEN)), bd_name}); ret = btif_storage_set_remote_device_property(&bd_addr, &prop[1]); - ASSERTC(ret == BT_STATUS_SUCCESS, "failed to save remote device property", - ret); + ASSERTC(ret == BT_STATUS_SUCCESS, "failed to save remote device property", ret); } if (!transport_le) { @@ -1965,8 +1866,7 @@ void btif_on_gatt_results(RawAddress bd_addr, BD_NAME bd_name, * send them with rest of SDP results in on_service_discovery_results */ return; } else { - if (pairing_cb.sdp_over_classic == - btif_dm_pairing_cb_t::ServiceDiscoveryState::SCHEDULED && + if (pairing_cb.sdp_over_classic == btif_dm_pairing_cb_t::ServiceDiscoveryState::SCHEDULED && com::android::bluetooth::flags::bta_dm_discover_both()) { /* Don't report services yet, they will be reported together once SDP * finishes. */ @@ -1976,25 +1876,23 @@ void btif_on_gatt_results(RawAddress bd_addr, BD_NAME bd_name, } /* Send the event to the BTIF */ - GetInterfaceToProfiles()->events->invoke_remote_device_properties_cb( - BT_STATUS_SUCCESS, bd_addr, prop.size(), prop.data()); + GetInterfaceToProfiles()->events->invoke_remote_device_properties_cb(BT_STATUS_SUCCESS, bd_addr, + prop.size(), prop.data()); } -static void btif_on_name_read(RawAddress bd_addr, tHCI_ERROR_CODE hci_status, - const BD_NAME bd_name, +static void btif_on_name_read(RawAddress bd_addr, tHCI_ERROR_CODE hci_status, const BD_NAME bd_name, bool during_device_search) { // Differentiate between merged callbacks if (!during_device_search // New fix after refactor, this callback is needed for the fix to work - && !com::android::bluetooth::flags:: - separate_service_and_device_discovery()) { + && !com::android::bluetooth::flags::separate_service_and_device_discovery()) { log::info("Skipping name read event - called on bad callback."); return; } if (hci_status != HCI_SUCCESS) { - log::warn("Received RNR event with bad status addr:{} hci_status:{}", - bd_addr, hci_error_code_text(hci_status)); + log::warn("Received RNR event with bad status addr:{} hci_status:{}", bd_addr, + hci_error_code_text(hci_status)); return; } if (bd_name[0] == '\0') { @@ -2005,18 +1903,15 @@ static void btif_on_name_read(RawAddress bd_addr, tHCI_ERROR_CODE hci_status, // Needs 3 properties if during_device_search is true std::vector properties; - properties.push_back( - bt_property_t{BT_PROPERTY_BDNAME, - static_cast(strnlen((char*)bd_name, BD_NAME_LEN)), - (void*)(bd_name)}); + properties.push_back(bt_property_t{BT_PROPERTY_BDNAME, + static_cast(strnlen((char*)bd_name, BD_NAME_LEN)), + (void*)(bd_name)}); - const bt_status_t status = - btif_storage_set_remote_device_property(&bd_addr, properties.data()); - log::assert_that(status == BT_STATUS_SUCCESS, - "Failed to save remote device property status:{}", + const bt_status_t status = btif_storage_set_remote_device_property(&bd_addr, properties.data()); + log::assert_that(status == BT_STATUS_SUCCESS, "Failed to save remote device property status:{}", bt_status_text(status)); GetInterfaceToProfiles()->events->invoke_remote_device_properties_cb( - status, bd_addr, properties.size(), properties.data()); + status, bd_addr, properties.size(), properties.data()); log::info("Callback for read name event addr:{} name:{}", bd_addr, PRIVATE_NAME(reinterpret_cast(bd_name))); @@ -2026,62 +1921,51 @@ static void btif_on_name_read(RawAddress bd_addr, tHCI_ERROR_CODE hci_status, uint32_t cod = get_cod(&bd_addr); if (cod != 0) { - properties.push_back( - bt_property_t{BT_PROPERTY_BDADDR, sizeof(bd_addr), &bd_addr}); - properties.push_back( - bt_property_t{BT_PROPERTY_CLASS_OF_DEVICE, sizeof(uint32_t), &cod}); + properties.push_back(bt_property_t{BT_PROPERTY_BDADDR, sizeof(bd_addr), &bd_addr}); + properties.push_back(bt_property_t{BT_PROPERTY_CLASS_OF_DEVICE, sizeof(uint32_t), &cod}); log::debug("report new device to JNI"); - GetInterfaceToProfiles()->events->invoke_device_found_cb(properties.size(), - properties.data()); + GetInterfaceToProfiles()->events->invoke_device_found_cb(properties.size(), properties.data()); } else { - log::info( - "Skipping device found callback because cod is zero addr:{} name:{}", - bd_addr, PRIVATE_NAME(reinterpret_cast(bd_name))); + log::info("Skipping device found callback because cod is zero addr:{} name:{}", bd_addr, + PRIVATE_NAME(reinterpret_cast(bd_name))); } } -void btif_on_name_read_from_btm(const RawAddress& bd_addr, DEV_CLASS /* dc */, - BD_NAME bd_name) { +void btif_on_name_read_from_btm(const RawAddress& bd_addr, DEV_CLASS /* dc */, BD_NAME bd_name) { log::info("{} {}", bd_addr, reinterpret_cast(bd_name)); - btif_on_name_read(bd_addr, HCI_SUCCESS, bd_name, - false /* duirng_device_search */); + btif_on_name_read(bd_addr, HCI_SUCCESS, bd_name, false /* during_device_search */); } -void btif_on_did_received(RawAddress bd_addr, uint8_t vendor_id_src, - uint16_t vendor_id, uint16_t product_id, - uint16_t version) { +void btif_on_did_received(RawAddress bd_addr, uint8_t vendor_id_src, uint16_t vendor_id, + uint16_t product_id, uint16_t version) { bt_vendor_product_info_t vp_info{ - .vendor_id_src = vendor_id_src, - .vendor_id = vendor_id, - .product_id = product_id, - .version = version, + .vendor_id_src = vendor_id_src, + .vendor_id = vendor_id, + .product_id = product_id, + .version = version, }; bt_property_t prop_did{ - .type = BT_PROPERTY_VENDOR_PRODUCT_INFO, - .len = sizeof(vp_info), - .val = &vp_info, + .type = BT_PROPERTY_VENDOR_PRODUCT_INFO, + .len = sizeof(vp_info), + .val = &vp_info, }; - bt_status_t ret = - btif_storage_set_remote_device_property(&bd_addr, &prop_did); + bt_status_t ret = btif_storage_set_remote_device_property(&bd_addr, &prop_did); ASSERTC(ret == BT_STATUS_SUCCESS, "storing remote services failed", ret); /* Send the event to the BTIF */ - GetInterfaceToProfiles()->events->invoke_remote_device_properties_cb( - BT_STATUS_SUCCESS, bd_addr, 1, &prop_did); + GetInterfaceToProfiles()->events->invoke_remote_device_properties_cb(BT_STATUS_SUCCESS, bd_addr, + 1, &prop_did); } void BTIF_dm_report_inquiry_status_change(tBTM_INQUIRY_STATE status) { - btif_dm_inquiry_in_progress = - (status == tBTM_INQUIRY_STATE::BTM_INQUIRY_STARTED); + btif_dm_inquiry_in_progress = (status == tBTM_INQUIRY_STATE::BTM_INQUIRY_STARTED); if (status == tBTM_INQUIRY_STATE::BTM_INQUIRY_STARTED) { - GetInterfaceToProfiles()->events->invoke_discovery_state_changed_cb( - BT_DISCOVERY_STARTED); + GetInterfaceToProfiles()->events->invoke_discovery_state_changed_cb(BT_DISCOVERY_STARTED); } else if (status == tBTM_INQUIRY_STATE::BTM_INQUIRY_CANCELLED) { - GetInterfaceToProfiles()->events->invoke_discovery_state_changed_cb( - BT_DISCOVERY_STOPPED); + GetInterfaceToProfiles()->events->invoke_discovery_state_changed_cb(BT_DISCOVERY_STOPPED); } } @@ -2105,8 +1989,7 @@ void BTIF_dm_enable() { } /* Enable or disable local privacy */ - bool ble_privacy_enabled = - osi_property_get_bool(PROPERTY_BLE_PRIVACY_ENABLED, /*default=*/true); + bool ble_privacy_enabled = osi_property_get_bool(PROPERTY_BLE_PRIVACY_ENABLED, /*default=*/true); log::info("Local BLE Privacy enabled:{}", ble_privacy_enabled); BTA_DmBleConfigLocalPrivacy(ble_privacy_enabled); @@ -2183,8 +2066,8 @@ void btif_dm_sec_evt(tBTA_DM_SEC_EVT event, tBTA_DM_SEC* p_data) { if (is_bonding_or_sdp()) { bd_addr = pairing_cb.bd_addr; btm_set_bond_type_dev(pairing_cb.bd_addr, BOND_TYPE_UNKNOWN); - bond_state_changed((bt_status_t)p_data->bond_cancel_cmpl.result, - bd_addr, BT_BOND_STATE_NONE); + bond_state_changed((bt_status_t)p_data->bond_cancel_cmpl.result, bd_addr, + BT_BOND_STATE_NONE); } break; @@ -2205,8 +2088,7 @@ void btif_dm_sec_evt(tBTA_DM_SEC_EVT event, tBTA_DM_SEC* p_data) { break; case BTA_DM_BLE_KEY_EVT: - log::verbose("BTA_DM_BLE_KEY_EVT key_type=0x{:02x}", - p_data->ble_key.key_type); + log::verbose("BTA_DM_BLE_KEY_EVT key_type=0x{:02x}", p_data->ble_key.key_type); /* If this pairing is by-product of local initiated GATT client Read or Write, @@ -2216,11 +2098,9 @@ void btif_dm_sec_evt(tBTA_DM_SEC_EVT event, tBTA_DM_SEC* p_data) { now*/ if (pairing_cb.state != BT_BOND_STATE_BONDING) { log::verbose("Bond state not sent to App so far.Notify the app now"); - bond_state_changed(BT_STATUS_SUCCESS, p_data->ble_key.bd_addr, - BT_BOND_STATE_BONDING); + bond_state_changed(BT_STATUS_SUCCESS, p_data->ble_key.bd_addr, BT_BOND_STATE_BONDING); } else if (pairing_cb.bd_addr != p_data->ble_key.bd_addr) { - log::error("BD mismatch discard BLE key_type={}", - p_data->ble_key.key_type); + log::error("BD mismatch discard BLE key_type={}", p_data->ble_key.key_type); break; } @@ -2261,8 +2141,7 @@ void btif_dm_sec_evt(tBTA_DM_SEC_EVT event, tBTA_DM_SEC* p_data) { break; default: - log::error("unknown BLE key type (0x{:02x})", - p_data->ble_key.key_type); + log::error("unknown BLE key type (0x{:02x})", p_data->ble_key.key_type); break; } break; @@ -2296,8 +2175,7 @@ void btif_dm_sec_evt(tBTA_DM_SEC_EVT event, tBTA_DM_SEC* p_data) { break; case BTA_DM_BLE_SC_CR_LOC_OOB_EVT: log::verbose("BTA_DM_BLE_SC_CR_LOC_OOB_EVT"); - btif_dm_proc_loc_oob(BT_TRANSPORT_LE, true, - p_data->local_oob_data.local_oob_c, + btif_dm_proc_loc_oob(BT_TRANSPORT_LE, true, p_data->local_oob_data.local_oob_c, p_data->local_oob_data.local_oob_r); break; @@ -2307,19 +2185,15 @@ void btif_dm_sec_evt(tBTA_DM_SEC_EVT event, tBTA_DM_SEC* p_data) { ble_local_key_cb.id_keys.irk = p_data->ble_id_keys.irk; ble_local_key_cb.id_keys.ir = p_data->ble_id_keys.ir; ble_local_key_cb.id_keys.dhk = p_data->ble_id_keys.dhk; - btif_storage_add_ble_local_key(ble_local_key_cb.id_keys.irk, - BTIF_DM_LE_LOCAL_KEY_IRK); - btif_storage_add_ble_local_key(ble_local_key_cb.id_keys.ir, - BTIF_DM_LE_LOCAL_KEY_IR); - btif_storage_add_ble_local_key(ble_local_key_cb.id_keys.dhk, - BTIF_DM_LE_LOCAL_KEY_DHK); + btif_storage_add_ble_local_key(ble_local_key_cb.id_keys.irk, BTIF_DM_LE_LOCAL_KEY_IRK); + btif_storage_add_ble_local_key(ble_local_key_cb.id_keys.ir, BTIF_DM_LE_LOCAL_KEY_IR); + btif_storage_add_ble_local_key(ble_local_key_cb.id_keys.dhk, BTIF_DM_LE_LOCAL_KEY_DHK); break; case BTA_DM_BLE_LOCAL_ER_EVT: log::verbose("BTA_DM_BLE_LOCAL_ER_EVT"); ble_local_key_cb.is_er_rcvd = true; ble_local_key_cb.er = p_data->ble_er; - btif_storage_add_ble_local_key(ble_local_key_cb.er, - BTIF_DM_LE_LOCAL_KEY_ER); + btif_storage_add_ble_local_key(ble_local_key_cb.er, BTIF_DM_LE_LOCAL_KEY_ER); break; case BTA_DM_BLE_AUTH_CMPL_EVT: @@ -2329,17 +2203,16 @@ void btif_dm_sec_evt(tBTA_DM_SEC_EVT event, tBTA_DM_SEC* p_data) { case BTA_DM_LE_ADDR_ASSOC_EVT: GetInterfaceToProfiles()->events->invoke_le_address_associate_cb( - p_data->proc_id_addr.pairing_bda, p_data->proc_id_addr.id_addr); + p_data->proc_id_addr.pairing_bda, p_data->proc_id_addr.id_addr); break; case BTA_DM_SIRK_VERIFICATION_REQ_EVT: GetInterfaceToProfiles()->events->invoke_le_address_associate_cb( - p_data->proc_id_addr.pairing_bda, p_data->proc_id_addr.id_addr); + p_data->proc_id_addr.pairing_bda, p_data->proc_id_addr.id_addr); break; case BTA_DM_KEY_MISSING_EVT: - GetInterfaceToProfiles()->events->invoke_key_missing_cb( - p_data->key_missing.bd_addr); + GetInterfaceToProfiles()->events->invoke_key_missing_cb(p_data->key_missing.bd_addr); break; default: @@ -2368,15 +2241,13 @@ void btif_dm_acl_evt(tBTA_DM_ACL_EVT event, tBTA_DM_ACL* p_data) { btif_update_remote_version_property(&bd_addr); GetInterfaceToProfiles()->events->invoke_acl_state_changed_cb( - BT_STATUS_SUCCESS, bd_addr, BT_ACL_STATE_CONNECTED, - (int)p_data->link_up.transport_link_type, HCI_SUCCESS, - btm_is_acl_locally_initiated() - ? bt_conn_direction_t::BT_CONN_DIRECTION_OUTGOING - : bt_conn_direction_t::BT_CONN_DIRECTION_INCOMING, - p_data->link_up.acl_handle); - - if (p_data->link_up.transport_link_type == BT_TRANSPORT_LE && - pairing_cb.bd_addr == bd_addr && + BT_STATUS_SUCCESS, bd_addr, BT_ACL_STATE_CONNECTED, + (int)p_data->link_up.transport_link_type, HCI_SUCCESS, + btm_is_acl_locally_initiated() ? bt_conn_direction_t::BT_CONN_DIRECTION_OUTGOING + : bt_conn_direction_t::BT_CONN_DIRECTION_INCOMING, + p_data->link_up.acl_handle); + + if (p_data->link_up.transport_link_type == BT_TRANSPORT_LE && pairing_cb.bd_addr == bd_addr && is_device_le_audio_capable(bd_addr)) { L2CA_LockBleConnParamsForProfileConnection(bd_addr, true); } @@ -2384,20 +2255,17 @@ void btif_dm_acl_evt(tBTA_DM_ACL_EVT event, tBTA_DM_ACL* p_data) { case BTA_DM_LINK_UP_FAILED_EVT: GetInterfaceToProfiles()->events->invoke_acl_state_changed_cb( - BT_STATUS_FAIL, p_data->link_up_failed.bd_addr, - BT_ACL_STATE_DISCONNECTED, p_data->link_up_failed.transport_link_type, - p_data->link_up_failed.status, - btm_is_acl_locally_initiated() - ? bt_conn_direction_t::BT_CONN_DIRECTION_OUTGOING - : bt_conn_direction_t::BT_CONN_DIRECTION_INCOMING, - INVALID_ACL_HANDLE); + BT_STATUS_FAIL, p_data->link_up_failed.bd_addr, BT_ACL_STATE_DISCONNECTED, + p_data->link_up_failed.transport_link_type, p_data->link_up_failed.status, + btm_is_acl_locally_initiated() ? bt_conn_direction_t::BT_CONN_DIRECTION_OUTGOING + : bt_conn_direction_t::BT_CONN_DIRECTION_INCOMING, + INVALID_ACL_HANDLE); break; case BTA_DM_LINK_DOWN_EVT: { bd_addr = p_data->link_down.bd_addr; btm_set_bond_type_dev(p_data->link_down.bd_addr, BOND_TYPE_UNKNOWN); - GetInterfaceToProfiles()->onLinkDown( - bd_addr, p_data->link_down.transport_link_type); + GetInterfaceToProfiles()->onLinkDown(bd_addr, p_data->link_down.transport_link_type); bt_conn_direction_t direction; switch (btm_get_acl_disc_reason_code()) { @@ -2414,26 +2282,23 @@ void btif_dm_acl_evt(tBTA_DM_ACL_EVT event, tBTA_DM_ACL* p_data) { direction = bt_conn_direction_t::BT_CONN_DIRECTION_UNKNOWN; } GetInterfaceToProfiles()->events->invoke_acl_state_changed_cb( - BT_STATUS_SUCCESS, bd_addr, BT_ACL_STATE_DISCONNECTED, - (int)p_data->link_down.transport_link_type, - static_cast(btm_get_acl_disc_reason_code()), - direction, INVALID_ACL_HANDLE); + BT_STATUS_SUCCESS, bd_addr, BT_ACL_STATE_DISCONNECTED, + (int)p_data->link_down.transport_link_type, + static_cast(btm_get_acl_disc_reason_code()), direction, + INVALID_ACL_HANDLE); log::debug( - "Sent BT_ACL_STATE_DISCONNECTED upward as ACL link down event " - "device:{} reason:{}", - bd_addr, - hci_reason_code_text( - static_cast(btm_get_acl_disc_reason_code()))); + "Sent BT_ACL_STATE_DISCONNECTED upward as ACL link down event " + "device:{} reason:{}", + bd_addr, + hci_reason_code_text(static_cast(btm_get_acl_disc_reason_code()))); } break; case BTA_DM_LE_FEATURES_READ: btif_get_adapter_property(BT_PROPERTY_LOCAL_LE_FEATURES); break; - - default: { - log::error("Unexpected tBTA_DM_ACL_EVT:{}", event); + default: { + log::error("Unexpected tBTA_DM_ACL_EVT:{}", event); } break; - } } @@ -2446,16 +2311,13 @@ void btif_dm_acl_evt(tBTA_DM_ACL_EVT event, tBTA_DM_ACL* p_data) { * Returns void * ******************************************************************************/ -static void bta_energy_info_cb(tBTM_BLE_TX_TIME_MS tx_time, - tBTM_BLE_RX_TIME_MS rx_time, - tBTM_BLE_IDLE_TIME_MS idle_time, - tBTM_BLE_ENERGY_USED energy_used, - tBTM_CONTRL_STATE ctrl_state, - tBTA_STATUS status) { +static void bta_energy_info_cb(tBTM_BLE_TX_TIME_MS tx_time, tBTM_BLE_RX_TIME_MS rx_time, + tBTM_BLE_IDLE_TIME_MS idle_time, tBTM_BLE_ENERGY_USED energy_used, + tBTM_CONTRL_STATE ctrl_state, tBTA_STATUS status) { log::verbose( - "energy_info_cb-Status:{},state={},tx_t={}, rx_t={}, " - "idle_time={},used={}", - status, ctrl_state, tx_time, rx_time, idle_time, energy_used); + "energy_info_cb-Status:{},state={},tx_t={}, rx_t={}, " + "idle_time={},used={}", + status, ctrl_state, tx_time, rx_time, idle_time, energy_used); if (uid_set != nullptr) { bt_activity_energy_info energy_info; @@ -2489,10 +2351,9 @@ static void bta_energy_info_cb(tBTM_BLE_TX_TIME_MS tx_time, void btif_dm_start_discovery(void) { log::verbose("start device discover/inquiry"); - BTM_LogHistory( - kBtmLogTag, RawAddress::kEmpty, "Device discovery", - base::StringPrintf("is_request_queued:%c", - bta_dm_is_search_request_queued() ? 'T' : 'F')); + BTM_LogHistory(kBtmLogTag, RawAddress::kEmpty, "Device discovery", + base::StringPrintf("is_request_queued:%c", + bta_dm_is_search_request_queued() ? 'T' : 'F')); /* no race here because we're guaranteed to be in the main thread */ if (bta_dm_is_search_request_queued()) { @@ -2521,9 +2382,7 @@ void btif_dm_cancel_discovery(void) { BTA_DmSearchCancel(); } -bool btif_dm_pairing_is_busy() { - return pairing_cb.state != BT_BOND_STATE_NONE; -} +bool btif_dm_pairing_is_busy() { return pairing_cb.state != BT_BOND_STATE_NONE; } /******************************************************************************* * @@ -2535,12 +2394,10 @@ bool btif_dm_pairing_is_busy() { void btif_dm_create_bond(const RawAddress bd_addr, int transport) { log::verbose("bd_addr={}, transport={}", bd_addr, transport); - BTM_LogHistory( - kBtmLogTag, bd_addr, "Create bond", - base::StringPrintf("transport:%s", bt_transport_text(transport).c_str())); + BTM_LogHistory(kBtmLogTag, bd_addr, "Create bond", + base::StringPrintf("transport:%s", bt_transport_text(transport).c_str())); - btif_stats_add_bond_event(bd_addr, BTIF_DM_FUNC_CREATE_BOND, - pairing_cb.state); + btif_stats_add_bond_event(bd_addr, BTIF_DM_FUNC_CREATE_BOND, pairing_cb.state); pairing_cb.timeout_retries = NUM_TIMEOUT_RETRIES; btif_dm_cb_create_bond(bd_addr, transport); @@ -2553,20 +2410,16 @@ void btif_dm_create_bond(const RawAddress bd_addr, int transport) { * Description Initiate bonding with the specified device over le transport * ******************************************************************************/ -void btif_dm_create_bond_le(const RawAddress bd_addr, - tBLE_ADDR_TYPE addr_type) { +void btif_dm_create_bond_le(const RawAddress bd_addr, tBLE_ADDR_TYPE addr_type) { log::verbose("bd_addr={}, addr_type={}", bd_addr, addr_type); const tBLE_BD_ADDR ble_bd_addr{ - .type = addr_type, - .bda = bd_addr, + .type = addr_type, + .bda = bd_addr, }; - BTM_LogHistory( - kBtmLogTag, ble_bd_addr, "Create bond", - base::StringPrintf("transport:%s", - bt_transport_text(BT_TRANSPORT_LE).c_str())); + BTM_LogHistory(kBtmLogTag, ble_bd_addr, "Create bond", + base::StringPrintf("transport:%s", bt_transport_text(BT_TRANSPORT_LE).c_str())); - btif_stats_add_bond_event(bd_addr, BTIF_DM_FUNC_CREATE_BOND, - pairing_cb.state); + btif_stats_add_bond_event(bd_addr, BTIF_DM_FUNC_CREATE_BOND, pairing_cb.state); pairing_cb.timeout_retries = NUM_TIMEOUT_RETRIES; btif_dm_cb_create_bond_le(bd_addr, addr_type); @@ -2580,10 +2433,8 @@ void btif_dm_create_bond_le(const RawAddress bd_addr, * data * ******************************************************************************/ -void btif_dm_create_bond_out_of_band(const RawAddress bd_addr, - tBT_TRANSPORT transport, - const bt_oob_data_t p192_data, - const bt_oob_data_t p256_data) { +void btif_dm_create_bond_out_of_band(const RawAddress bd_addr, tBT_TRANSPORT transport, + const bt_oob_data_t p192_data, const bt_oob_data_t p256_data) { bt_oob_data_t empty_data; memset(&empty_data, 0, sizeof(empty_data)); @@ -2604,11 +2455,9 @@ void btif_dm_create_bond_out_of_band(const RawAddress bd_addr, } } - BTM_LogHistory( - kBtmLogTag, bd_addr, "Create bond", - base::StringPrintf("transport:%s oob:%s", - bt_transport_text(transport).c_str(), - btm_oob_data_text(oob_cb.data_present).c_str())); + BTM_LogHistory(kBtmLogTag, bd_addr, "Create bond", + base::StringPrintf("transport:%s oob:%s", bt_transport_text(transport).c_str(), + btm_oob_data_text(oob_cb.data_present).c_str())); uint8_t empty[] = {0, 0, 0, 0, 0, 0, 0}; switch (transport) { @@ -2629,14 +2478,11 @@ void btif_dm_create_bond_out_of_band(const RawAddress bd_addr, // TODO(181889116): // Upgrade to support p256 (for now we just ignore P256) // because the controllers do not yet support it. - bond_state_changed(BT_STATUS_UNSUPPORTED, bd_addr, - BT_BOND_STATE_NONE); + bond_state_changed(BT_STATUS_UNSUPPORTED, bd_addr, BT_BOND_STATE_NONE); return; default: - log::error("Invalid data present for controller:{}", - oob_cb.data_present); - bond_state_changed(BT_STATUS_PARM_INVALID, bd_addr, - BT_BOND_STATE_NONE); + log::error("Invalid data present for controller:{}", oob_cb.data_present); + bond_state_changed(BT_STATUS_PARM_INVALID, bd_addr, BT_BOND_STATE_NONE); return; } pairing_cb.is_local_initiated = true; @@ -2670,8 +2516,8 @@ void btif_dm_create_bond_out_of_band(const RawAddress bd_addr, break; } pairing_cb.is_local_initiated = true; - get_btm_client_interface().security.BTM_SecAddBleDevice( - bd_addr, BT_DEVICE_TYPE_BLE, address_type); + get_btm_client_interface().security.BTM_SecAddBleDevice(bd_addr, BT_DEVICE_TYPE_BLE, + address_type); BTA_DmBond(bd_addr, address_type, transport, BT_DEVICE_TYPE_BLE); break; } @@ -2694,8 +2540,7 @@ void btif_dm_cancel_bond(const RawAddress bd_addr) { BTM_LogHistory(kBtmLogTag, bd_addr, "Cancel bond"); - btif_stats_add_bond_event(bd_addr, BTIF_DM_FUNC_CANCEL_BOND, - pairing_cb.state); + btif_stats_add_bond_event(bd_addr, BTIF_DM_FUNC_CANCEL_BOND, pairing_cb.state); /* TODO: ** 1. Restore scan modes @@ -2734,8 +2579,7 @@ void btif_dm_cancel_bond(const RawAddress bd_addr) { ******************************************************************************/ void btif_dm_hh_open_failed(RawAddress* bdaddr) { - if (pairing_cb.state == BT_BOND_STATE_BONDING && - *bdaddr == pairing_cb.bd_addr) { + if (pairing_cb.state == BT_BOND_STATE_BONDING && *bdaddr == pairing_cb.bd_addr) { bond_state_changed(BT_STATUS_RMT_DEV_DOWN, *bdaddr, BT_BOND_STATE_NONE); } } @@ -2753,8 +2597,7 @@ void btif_dm_remove_bond(const RawAddress bd_addr) { BTM_LogHistory(kBtmLogTag, bd_addr, "Remove bond"); - btif_stats_add_bond_event(bd_addr, BTIF_DM_FUNC_REMOVE_BOND, - pairing_cb.state); + btif_stats_add_bond_event(bd_addr, BTIF_DM_FUNC_REMOVE_BOND, pairing_cb.state); // special handling for HID devices // VUP needs to be sent if its a HID Device. The HID HOST module will check if @@ -2766,8 +2609,8 @@ void btif_dm_remove_bond(const RawAddress bd_addr) { link_spec.transport = BT_TRANSPORT_AUTO; link_spec.addrt.type = BLE_ADDR_PUBLIC; - if (GetInterfaceToProfiles()->profileSpecific_HACK->btif_hh_virtual_unplug( - link_spec) != BT_STATUS_SUCCESS) + if (GetInterfaceToProfiles()->profileSpecific_HACK->btif_hh_virtual_unplug(link_spec) != + BT_STATUS_SUCCESS) #endif { log::debug("Removing HH device"); @@ -2783,8 +2626,8 @@ void btif_dm_remove_bond(const RawAddress bd_addr) { * ******************************************************************************/ -void btif_dm_pin_reply(const RawAddress bd_addr, uint8_t accept, - uint8_t pin_len, bt_pin_code_t pin_code) { +void btif_dm_pin_reply(const RawAddress bd_addr, uint8_t accept, uint8_t pin_len, + bt_pin_code_t pin_code) { log::verbose("accept={}", accept); if (pairing_cb.is_le_only) { @@ -2801,7 +2644,9 @@ void btif_dm_pin_reply(const RawAddress bd_addr, uint8_t accept, } else { BTA_DmPinReply(bd_addr, accept, pin_len, pin_code.pin); - if (accept) pairing_cb.pin_code_len = pin_len; + if (accept) { + pairing_cb.pin_code_len = pin_len; + } } } @@ -2813,24 +2658,23 @@ void btif_dm_pin_reply(const RawAddress bd_addr, uint8_t accept, * Entry * ******************************************************************************/ -void btif_dm_ssp_reply(const RawAddress bd_addr, bt_ssp_variant_t variant, - uint8_t accept) { +void btif_dm_ssp_reply(const RawAddress bd_addr, bt_ssp_variant_t variant, uint8_t accept) { log::verbose("accept={}", accept); BTM_LogHistory( - kBtmLogTag, bd_addr, "Ssp reply", - base::StringPrintf( - "originator:%s variant:%d accept:%c le:%c numeric_comparison:%c", - (pairing_cb.is_local_initiated) ? "local" : "remote", variant, - (accept) ? 'Y' : 'N', (pairing_cb.is_le_only) ? 'T' : 'F', - (pairing_cb.is_le_nc) ? 'T' : 'F')); + kBtmLogTag, bd_addr, "Ssp reply", + base::StringPrintf("originator:%s variant:%d accept:%c le:%c numeric_comparison:%c", + (pairing_cb.is_local_initiated) ? "local" : "remote", variant, + (accept) ? 'Y' : 'N', (pairing_cb.is_le_only) ? 'T' : 'F', + (pairing_cb.is_le_nc) ? 'T' : 'F')); if (pairing_cb.is_le_only) { if (pairing_cb.is_le_nc) { BTA_DmBleConfirmReply(bd_addr, accept); } else { - if (accept) + if (accept) { BTA_DmBleSecurityGrant(bd_addr, BTA_DM_SEC_GRANTED); - else + } else { BTA_DmBleSecurityGrant(bd_addr, BTA_DM_SEC_PAIR_NOT_SPT); + } } } else { BTA_DmConfirm(bd_addr, accept); @@ -2876,8 +2720,7 @@ DEV_CLASS btif_dm_get_local_class_of_device() { // Build a string of all the chars until the next comma, null, or end of the // buffer is reached. If any char is not a digit, then return the default. std::string value; - while (i < PROPERTY_VALUE_MAX && prop_cod[i] != ',' && - prop_cod[i] != '\0') { + while (i < PROPERTY_VALUE_MAX && prop_cod[i] != ',' && prop_cod[i] != '\0') { char c = prop_cod[i++]; if (!std::isdigit(c)) { log::error("COD malformed, '{:c}' is a non-digit", c); @@ -2936,31 +2779,25 @@ DEV_CLASS btif_dm_get_local_class_of_device() { log::error("COD malformed, fewer than three numbers"); } - log::debug( - "Using class of device '0x{:x}, 0x{:x}, 0x{:x}' from CoD system property", - device_class[0], device_class[1], device_class[2]); + log::debug("Using class of device '0x{:x}, 0x{:x}, 0x{:x}' from CoD system property", + device_class[0], device_class[1], device_class[2]); #ifdef __ANDROID__ // Per BAP 1.0.1, 8.2.3. Device discovery, the stack needs to set Class of // Device (CoD) field Major Service Class bit 14 to 0b1 when Unicast Server, // Unicast Client, Broadcast Source, Broadcast Sink, Scan Delegator, or // Broadcast Assistant is supported on this device - if (android::sysprop::BluetoothProperties::isProfileBapUnicastClientEnabled() - .value_or(false) || - android::sysprop::BluetoothProperties:: - isProfileBapBroadcastAssistEnabled() - .value_or(false) || - android::sysprop::BluetoothProperties:: - isProfileBapBroadcastSourceEnabled() - .value_or(false)) { + if (android::sysprop::BluetoothProperties::isProfileBapUnicastClientEnabled().value_or(false) || + android::sysprop::BluetoothProperties::isProfileBapBroadcastAssistEnabled().value_or(false) || + android::sysprop::BluetoothProperties::isProfileBapBroadcastSourceEnabled().value_or(false)) { device_class[1] |= 0x01 << 6; } else { device_class[1] &= ~(0x01 << 6); } log::debug( - "Check LE audio enabled status, update class of device to '0x{:x}, " - "0x{:x}, 0x{:x}'", - device_class[0], device_class[1], device_class[2]); + "Check LE audio enabled status, update class of device to '0x{:x}, " + "0x{:x}, 0x{:x}'", + device_class[0], device_class[1], device_class[2]); #endif return device_class; } @@ -2998,12 +2835,10 @@ bt_status_t btif_dm_get_adapter_property(bt_property_t* prop) { return BT_STATUS_SUCCESS; } -static void btif_on_name_read_legacy(RawAddress bd_addr, - tHCI_ERROR_CODE hci_status, +static void btif_on_name_read_legacy(RawAddress bd_addr, tHCI_ERROR_CODE hci_status, const BD_NAME bd_name) { - btif_on_name_read(bd_addr, hci_status, bd_name, - false /* during_device_search */); -}; + btif_on_name_read(bd_addr, hci_status, bd_name, false /* during_device_search */); +} /******************************************************************************* * @@ -3015,21 +2850,18 @@ static void btif_on_name_read_legacy(RawAddress bd_addr, * ******************************************************************************/ void btif_dm_get_remote_services(RawAddress remote_addr, const int transport) { - log::verbose("transport={}, remote_addr={}", bt_transport_text(transport), - remote_addr); + log::verbose("transport={}, remote_addr={}", bt_transport_text(transport), remote_addr); - BTM_LogHistory( - kBtmLogTag, remote_addr, "Service discovery", - base::StringPrintf("transport:%s", bt_transport_text(transport).c_str())); - - BTA_DmDiscover( - remote_addr, - service_discovery_callbacks{ - .on_gatt_results = btif_on_gatt_results, - .on_did_received = btif_on_did_received, - .on_name_read = btif_on_name_read_legacy, - .on_service_discovery_results = btif_on_service_discovery_results}, - transport); + BTM_LogHistory(kBtmLogTag, remote_addr, "Service discovery", + base::StringPrintf("transport:%s", bt_transport_text(transport).c_str())); + + BTA_DmDiscover(remote_addr, + service_discovery_callbacks{ + .on_gatt_results = btif_on_gatt_results, + .on_did_received = btif_on_did_received, + .on_name_read = btif_on_name_read_legacy, + .on_service_discovery_results = btif_on_service_discovery_results}, + transport); } void btif_dm_enable_service(tBTA_SERVICE_ID service_id, bool enable) { @@ -3039,11 +2871,9 @@ void btif_dm_enable_service(tBTA_SERVICE_ID service_id, bool enable) { Uuid local_uuids[BT_MAX_NUM_UUIDS]; /* Now send the UUID_PROPERTY_CHANGED event to the upper layer */ - BTIF_STORAGE_FILL_PROPERTY(&property, BT_PROPERTY_UUIDS, - sizeof(local_uuids), local_uuids); + BTIF_STORAGE_FILL_PROPERTY(&property, BT_PROPERTY_UUIDS, sizeof(local_uuids), local_uuids); btif_storage_get_adapter_property(&property); - GetInterfaceToProfiles()->events->invoke_adapter_properties_cb( - BT_STATUS_SUCCESS, 1, &property); + GetInterfaceToProfiles()->events->invoke_adapter_properties_cb(BT_STATUS_SUCCESS, 1, &property); } return; } @@ -3067,14 +2897,14 @@ void btif_dm_proc_io_req(tBTM_AUTH_REQ* p_auth_req, bool is_orig) { /* peer initiated paring. They probably know what they want. ** Copy the mitm from peer device. */ - log::debug("peer initiated, setting p_auth_req to peer's: {}", - pairing_cb.auth_req); + log::debug("peer initiated, setting p_auth_req to peer's: {}", pairing_cb.auth_req); *p_auth_req = (pairing_cb.auth_req & BTA_AUTH_BONDS); /* copy over the MITM bit as well. In addition if the peer has DisplayYesNo, * force MITM */ - if ((yes_no_bit) || (pairing_cb.io_cap & BTM_IO_CAP_IO)) + if ((yes_no_bit) || (pairing_cb.io_cap & BTM_IO_CAP_IO)) { *p_auth_req |= BTA_AUTH_SP_YES; + } } else if (yes_no_bit) { /* set the general bonding bit for stored device */ *p_auth_req = BTA_AUTH_GEN_BOND | yes_no_bit; @@ -3100,8 +2930,7 @@ void btif_dm_set_oob_for_io_req(tBTM_OOB_DATA* p_has_oob_data) { log::verbose("*p_has_oob_data={}", *p_has_oob_data); } -void btif_dm_set_oob_for_le_io_req(const RawAddress& bd_addr, - tBTM_OOB_DATA* p_has_oob_data, +void btif_dm_set_oob_for_le_io_req(const RawAddress& bd_addr, tBTM_OOB_DATA* p_has_oob_data, tBTM_LE_AUTH_REQ* p_auth_req) { switch (oob_cb.data_present) { case BTM_OOB_PRESENT_192_AND_256: @@ -3110,8 +2939,7 @@ void btif_dm_set_oob_for_le_io_req(const RawAddress& bd_addr, // Always prefer 256 for LE case BTM_OOB_PRESENT_256: log::info("Using P256"); - if (!is_empty_128bit(oob_cb.p256_data.c) && - !is_empty_128bit(oob_cb.p256_data.r)) { + if (!is_empty_128bit(oob_cb.p256_data.c) && !is_empty_128bit(oob_cb.p256_data.r)) { /* make sure OOB data is for this particular device */ if (bd_addr == oob_cb.bdaddr) { *p_auth_req = ((*p_auth_req) | BTM_LE_AUTH_REQ_SC_ONLY); @@ -3139,8 +2967,7 @@ void btif_dm_set_oob_for_le_io_req(const RawAddress& bd_addr, break; case BTM_OOB_PRESENT_192: log::info("Using P192"); - if (!is_empty_128bit(oob_cb.p192_data.c) && - !is_empty_128bit(oob_cb.p192_data.r)) { + if (!is_empty_128bit(oob_cb.p192_data.c) && !is_empty_128bit(oob_cb.p192_data.r)) { /* make sure OOB data is for this particular device */ if (bd_addr == oob_cb.bdaddr) { *p_auth_req = ((*p_auth_req) | BTM_LE_AUTH_REQ_SC_ONLY); @@ -3218,33 +3045,31 @@ void btif_dm_generate_local_oob_data(tBT_TRANSPORT transport) { waiting_on_oob_advertiser_start = true; if (!SMP_CrLocScOobData()) { waiting_on_oob_advertiser_start = false; - GetInterfaceToProfiles()->events->invoke_oob_data_request_cb( - transport, false, Octet16{}, Octet16{}, RawAddress{}, 0x00); + GetInterfaceToProfiles()->events->invoke_oob_data_request_cb(transport, false, Octet16{}, + Octet16{}, RawAddress{}, 0x00); } } else { - GetInterfaceToProfiles()->events->invoke_oob_data_request_cb( - transport, false, Octet16{}, Octet16{}, RawAddress{}, 0x00); + GetInterfaceToProfiles()->events->invoke_oob_data_request_cb(transport, false, Octet16{}, + Octet16{}, RawAddress{}, 0x00); } } } // Step Four: CallBack from Step Three -static void get_address_callback(tBT_TRANSPORT transport, bool is_valid, - const Octet16& c, const Octet16& r, - uint8_t address_type, RawAddress address) { - GetInterfaceToProfiles()->events->invoke_oob_data_request_cb( - transport, is_valid, c, r, address, address_type); +static void get_address_callback(tBT_TRANSPORT transport, bool is_valid, const Octet16& c, + const Octet16& r, uint8_t address_type, RawAddress address) { + GetInterfaceToProfiles()->events->invoke_oob_data_request_cb(transport, is_valid, c, r, address, + address_type); waiting_on_oob_advertiser_start = false; } // Step Three: CallBack from Step Two, advertise and get address -static void start_advertising_callback(uint8_t id, tBT_TRANSPORT transport, - bool is_valid, const Octet16& c, - const Octet16& r, tBTM_STATUS status) { +static void start_advertising_callback(uint8_t id, tBT_TRANSPORT transport, bool is_valid, + const Octet16& c, const Octet16& r, tBTM_STATUS status) { if (status != 0) { log::info("OOB get advertiser ID failed with status {}", status); - GetInterfaceToProfiles()->events->invoke_oob_data_request_cb( - transport, false, c, r, RawAddress{}, 0x00); + GetInterfaceToProfiles()->events->invoke_oob_data_request_cb(transport, false, c, r, + RawAddress{}, 0x00); SMP_ClearLocScOobData(); waiting_on_oob_advertiser_start = false; oob_advertiser_id_ = {}; @@ -3252,8 +3077,7 @@ static void start_advertising_callback(uint8_t id, tBT_TRANSPORT transport, } log::debug("OOB advertiser with id {}", id); auto advertiser = bluetooth::shim::get_ble_advertiser_instance(); - advertiser->GetOwnAddress( - id, base::Bind(&get_address_callback, transport, is_valid, c, r)); + advertiser->GetOwnAddress(id, base::Bind(&get_address_callback, transport, is_valid, c, r)); } static void timeout_cb(uint8_t id, tBTM_STATUS status) { @@ -3266,13 +3090,12 @@ static void timeout_cb(uint8_t id, tBTM_STATUS status) { } // Step Two: CallBack from Step One, advertise and get address -static void id_status_callback(tBT_TRANSPORT transport, bool is_valid, - const Octet16& c, const Octet16& r, uint8_t id, - tBTM_STATUS status) { +static void id_status_callback(tBT_TRANSPORT transport, bool is_valid, const Octet16& c, + const Octet16& r, uint8_t id, tBTM_STATUS status) { if (status != 0) { log::info("OOB get advertiser ID failed with status {}", status); - GetInterfaceToProfiles()->events->invoke_oob_data_request_cb( - transport, false, c, r, RawAddress{}, 0x00); + GetInterfaceToProfiles()->events->invoke_oob_data_request_cb(transport, false, c, r, + RawAddress{}, 0x00); SMP_ClearLocScOobData(); waiting_on_oob_advertiser_start = false; oob_advertiser_id_ = {}; @@ -3284,8 +3107,7 @@ static void id_status_callback(tBT_TRANSPORT transport, bool is_valid, auto advertiser = bluetooth::shim::get_ble_advertiser_instance(); AdvertiseParameters parameters{}; - parameters.advertising_event_properties = - 0x0045 /* connectable, discoverable, tx power */; + parameters.advertising_event_properties = 0x0045 /* connectable, discoverable, tx power */; parameters.min_interval = 0xa0; // 100 ms parameters.max_interval = 0x500; // 800 ms parameters.channel_map = 0x7; // Use all the channels @@ -3295,31 +3117,27 @@ static void id_status_callback(tBT_TRANSPORT transport, bool is_valid, parameters.scan_request_notification_enable = 0; parameters.own_address_type = BLE_ADDR_RANDOM; - std::vector advertisement{0x02, 0x01 /* Flags */, - 0x02 /* Connectable */}; + std::vector advertisement{0x02, 0x01 /* Flags */, 0x02 /* Connectable */}; std::vector scan_data{}; advertiser->StartAdvertising( - id, - base::Bind(&start_advertising_callback, id, transport, is_valid, c, r), - parameters, advertisement, scan_data, 120 /* timeout_s */, - base::Bind(&timeout_cb, id)); + id, base::Bind(&start_advertising_callback, id, transport, is_valid, c, r), parameters, + advertisement, scan_data, 120 /* timeout_s */, base::Bind(&timeout_cb, id)); } // Step One: Start the advertiser -static void start_oob_advertiser(tBT_TRANSPORT transport, bool is_valid, - const Octet16& c, const Octet16& r) { +static void start_oob_advertiser(tBT_TRANSPORT transport, bool is_valid, const Octet16& c, + const Octet16& r) { auto advertiser = bluetooth::shim::get_ble_advertiser_instance(); - advertiser->RegisterAdvertiser( - base::Bind(&id_status_callback, transport, is_valid, c, r)); + advertiser->RegisterAdvertiser(base::Bind(&id_status_callback, transport, is_valid, c, r)); } -void btif_dm_proc_loc_oob(tBT_TRANSPORT transport, bool is_valid, - const Octet16& c, const Octet16& r) { +void btif_dm_proc_loc_oob(tBT_TRANSPORT transport, bool is_valid, const Octet16& c, + const Octet16& r) { // is_valid is important for deciding which OobDataCallback function to use if (!is_valid) { - GetInterfaceToProfiles()->events->invoke_oob_data_request_cb( - transport, false, c, r, RawAddress{}, 0x00); + GetInterfaceToProfiles()->events->invoke_oob_data_request_cb(transport, false, c, r, + RawAddress{}, 0x00); waiting_on_oob_advertiser_start = false; return; } @@ -3328,10 +3146,8 @@ void btif_dm_proc_loc_oob(tBT_TRANSPORT transport, bool is_valid, start_oob_advertiser(transport, is_valid, c, r); } else { GetInterfaceToProfiles()->events->invoke_oob_data_request_cb( - transport, is_valid, c, r, - bluetooth::ToRawAddress( - bluetooth::shim::GetController()->GetMacAddress()), - 0x00); + transport, is_valid, c, r, + bluetooth::ToRawAddress(bluetooth::shim::GetController()->GetMacAddress()), 0x00); } } @@ -3366,50 +3182,55 @@ bool btif_dm_get_smp_config(tBTE_APPL_CFG* p_cfg) { conf[63] = 0; // null terminate pch = strtok(conf, ","); - if (pch != NULL) + if (pch != NULL) { p_cfg->ble_auth_req = (uint8_t)strtoul(pch, &endptr, 16); - else + } else { return false; + } pch = strtok(NULL, ","); - if (pch != NULL) + if (pch != NULL) { p_cfg->ble_io_cap = (uint8_t)strtoul(pch, &endptr, 16); - else + } else { return false; + } pch = strtok(NULL, ","); - if (pch != NULL) + if (pch != NULL) { p_cfg->ble_init_key = (uint8_t)strtoul(pch, &endptr, 16); - else + } else { return false; + } pch = strtok(NULL, ","); - if (pch != NULL) + if (pch != NULL) { p_cfg->ble_resp_key = (uint8_t)strtoul(pch, &endptr, 16); - else + } else { return false; + } pch = strtok(NULL, ","); - if (pch != NULL) + if (pch != NULL) { p_cfg->ble_max_key_size = (uint8_t)strtoul(pch, &endptr, 16); - else + } else { return false; + } return true; } -bool btif_dm_proc_rmt_oob(const RawAddress& bd_addr, Octet16* p_c, - Octet16* p_r) { +bool btif_dm_proc_rmt_oob(const RawAddress& bd_addr, Octet16* p_c, Octet16* p_r) { const char* path_a = "/data/misc/bluedroid/LOCAL/a.key"; const char* path_b = "/data/misc/bluedroid/LOCAL/b.key"; const char* path = NULL; char prop_oob[PROPERTY_VALUE_MAX]; osi_property_get("service.brcm.bt.oob", prop_oob, "3"); log::debug("prop_oob = {}", prop_oob); - if (prop_oob[0] == '1') + if (prop_oob[0] == '1') { path = path_b; - else if (prop_oob[0] == '2') + } else if (prop_oob[0] == '2') { path = path_a; + } if (!path) { log::debug("can't open path!"); return false; @@ -3440,9 +3261,8 @@ static void btif_dm_ble_key_notif_evt(tBTA_DM_SP_KEY_NOTIF* p_ssp_key_notif) { if (!btif_get_device_type(p_ssp_key_notif->bd_addr, &dev_type)) { dev_type = BT_DEVICE_TYPE_BLE; } - btif_dm_update_ble_remote_properties(p_ssp_key_notif->bd_addr, - p_ssp_key_notif->bd_name, kDevClassEmpty, - (tBT_DEVICE_TYPE)dev_type); + btif_dm_update_ble_remote_properties(p_ssp_key_notif->bd_addr, p_ssp_key_notif->bd_name, + kDevClassEmpty, (tBT_DEVICE_TYPE)dev_type); bd_addr = p_ssp_key_notif->bd_addr; bond_state_changed(BT_STATUS_SUCCESS, bd_addr, BT_BOND_STATE_BONDING); @@ -3452,7 +3272,7 @@ static void btif_dm_ble_key_notif_evt(tBTA_DM_SP_KEY_NOTIF* p_ssp_key_notif) { base::StringPrintf("passkey:%u", p_ssp_key_notif->passkey)); GetInterfaceToProfiles()->events->invoke_ssp_request_cb( - bd_addr, BT_SSP_VARIANT_PASSKEY_NOTIFICATION, p_ssp_key_notif->passkey); + bd_addr, BT_SSP_VARIANT_PASSKEY_NOTIFICATION, p_ssp_key_notif->passkey); } static bool btif_dm_ble_is_temp_pairing(RawAddress& bd_addr, bool ctkd) { @@ -3466,11 +3286,9 @@ static bool btif_dm_ble_is_temp_pairing(RawAddress& bd_addr, bool ctkd) { static bool btif_model_name_known(const RawAddress& bd_addr) { bt_property_t prop; bt_bdname_t model_name; - BTIF_STORAGE_FILL_PROPERTY(&prop, BT_PROPERTY_REMOTE_MODEL_NUM, - sizeof(model_name), &model_name); + BTIF_STORAGE_FILL_PROPERTY(&prop, BT_PROPERTY_REMOTE_MODEL_NUM, sizeof(model_name), &model_name); - if (btif_storage_get_remote_device_property(&bd_addr, &prop) != - BT_STATUS_SUCCESS || + if (btif_storage_get_remote_device_property(&bd_addr, &prop) != BT_STATUS_SUCCESS || prop.len == 0) { log::info("Device {} no cached model name", bd_addr); return false; @@ -3491,7 +3309,9 @@ static void read_dis_cback(const RawAddress& bd_addr, tDIS_VALUE* p_dis_value) { } for (int i = 0; i < DIS_MAX_STRING_DATA; i++) { - if (p_dis_value->data_string[i] == nullptr) continue; + if (p_dis_value->data_string[i] == nullptr) { + continue; + } bt_property_t prop; prop.type = BT_PROPERTY_REMOTE_MODEL_NUM; @@ -3501,8 +3321,8 @@ static void read_dis_cback(const RawAddress& bd_addr, tDIS_VALUE* p_dis_value) { log::info("Device {}, model name: {}", bd_addr, (char*)prop.val); btif_storage_set_remote_device_property(&bd_addr, &prop); - GetInterfaceToProfiles()->events->invoke_remote_device_properties_cb( - BT_STATUS_SUCCESS, bd_addr, 1, &prop); + GetInterfaceToProfiles()->events->invoke_remote_device_properties_cb(BT_STATUS_SUCCESS, bd_addr, + 1, &prop); } } @@ -3533,9 +3353,9 @@ static void btif_dm_ble_auth_cmpl_evt(tBTA_DM_AUTH_CMPL* p_auth_cmpl) { state = BT_BOND_STATE_BONDED; tBLE_ADDR_TYPE addr_type; - if (btif_storage_get_remote_addr_type(&bd_addr, &addr_type) != - BT_STATUS_SUCCESS) + if (btif_storage_get_remote_addr_type(&bd_addr, &addr_type) != BT_STATUS_SUCCESS) { btif_storage_set_remote_addr_type(&bd_addr, p_auth_cmpl->addr_type); + } /* Test for temporary bonding */ if (btif_dm_ble_is_temp_pairing(bd_addr, p_auth_cmpl->is_ctkd)) { @@ -3547,33 +3367,29 @@ static void btif_dm_ble_auth_cmpl_evt(tBTA_DM_AUTH_CMPL* p_auth_cmpl) { if (com::android::bluetooth::flags::read_model_num_fix() && is_le_audio_capable_during_service_discovery(bd_addr) && - !btif_model_name_known(bd_addr) && - BTM_IsAclConnectionUp(bd_addr, BT_TRANSPORT_LE)) { + !btif_model_name_known(bd_addr) && BTM_IsAclConnectionUp(bd_addr, BT_TRANSPORT_LE)) { log::info("Read model name for le audio capable device"); if (!DIS_ReadDISInfo(bd_addr, read_dis_cback, DIS_ATTR_MODEL_NUM_BIT)) { log::warn("Read DIS failed"); } } - if (pairing_cb.gatt_over_le == - btif_dm_pairing_cb_t::ServiceDiscoveryState::NOT_STARTED) { + if (pairing_cb.gatt_over_le == btif_dm_pairing_cb_t::ServiceDiscoveryState::NOT_STARTED) { log::info("scheduling GATT discovery over LE for {}", bd_addr); - pairing_cb.gatt_over_le = - btif_dm_pairing_cb_t::ServiceDiscoveryState::SCHEDULED; + pairing_cb.gatt_over_le = btif_dm_pairing_cb_t::ServiceDiscoveryState::SCHEDULED; btif_dm_get_remote_services(bd_addr, BT_TRANSPORT_LE); } else { log::info( - "skipping GATT discovery over LE - was already scheduled or " - "finished for {}, state: {}", - bd_addr, pairing_cb.gatt_over_le); + "skipping GATT discovery over LE - was already scheduled or " + "finished for {}, state: {}", + bd_addr, pairing_cb.gatt_over_le); } } } else { /* Map the HCI fail reason to bt status */ // TODO This is not a proper use of the type uint8_t fail_reason = static_cast(p_auth_cmpl->fail_reason); - log::error("LE authentication for {} failed with reason {}", bd_addr, - p_auth_cmpl->fail_reason); + log::error("LE authentication for {} failed with reason {}", bd_addr, p_auth_cmpl->fail_reason); switch (fail_reason) { case BTA_DM_AUTH_SMP_PAIR_AUTH_FAIL: case BTA_DM_AUTH_SMP_CONFIRM_VALUE_FAIL: @@ -3584,16 +3400,13 @@ static void btif_dm_ble_auth_cmpl_evt(tBTA_DM_AUTH_CMPL* p_auth_cmpl) { case BTA_DM_AUTH_SMP_CONN_TOUT: { if (!p_auth_cmpl->is_ctkd && btm_sec_is_a_bonded_dev(bd_addr)) { - log::warn( - "Bonded device addr={}, timed out - will not remove the keys", - bd_addr); + log::warn("Bonded device addr={}, timed out - will not remove the keys", bd_addr); // Don't send state change to upper layers - otherwise Java think we // unbonded, and will disconnect HID profile. return; } - log::info( - "Removing ble bonding keys on SMP_CONN_TOUT during crosskey: {}", - p_auth_cmpl->is_ctkd); + log::info("Removing ble bonding keys on SMP_CONN_TOUT during crosskey: {}", + p_auth_cmpl->is_ctkd); btif_dm_remove_ble_bonding_keys(); status = BT_STATUS_AUTH_FAILURE; break; @@ -3620,30 +3433,25 @@ static void btif_dm_ble_auth_cmpl_evt(tBTA_DM_AUTH_CMPL* p_auth_cmpl) { void btif_dm_load_ble_local_keys(void) { memset(&ble_local_key_cb, 0, sizeof(btif_dm_local_key_cb_t)); - if (btif_storage_get_ble_local_key( - BTIF_DM_LE_LOCAL_KEY_ER, &ble_local_key_cb.er) == BT_STATUS_SUCCESS) { + if (btif_storage_get_ble_local_key(BTIF_DM_LE_LOCAL_KEY_ER, &ble_local_key_cb.er) == + BT_STATUS_SUCCESS) { ble_local_key_cb.is_er_rcvd = true; log::verbose("BLE ER key loaded"); } - if ((btif_storage_get_ble_local_key(BTIF_DM_LE_LOCAL_KEY_IR, - &ble_local_key_cb.id_keys.ir) == + if ((btif_storage_get_ble_local_key(BTIF_DM_LE_LOCAL_KEY_IR, &ble_local_key_cb.id_keys.ir) == BT_STATUS_SUCCESS) && - (btif_storage_get_ble_local_key(BTIF_DM_LE_LOCAL_KEY_IRK, - &ble_local_key_cb.id_keys.irk) == + (btif_storage_get_ble_local_key(BTIF_DM_LE_LOCAL_KEY_IRK, &ble_local_key_cb.id_keys.irk) == BT_STATUS_SUCCESS) && - (btif_storage_get_ble_local_key(BTIF_DM_LE_LOCAL_KEY_DHK, - &ble_local_key_cb.id_keys.dhk) == + (btif_storage_get_ble_local_key(BTIF_DM_LE_LOCAL_KEY_DHK, &ble_local_key_cb.id_keys.dhk) == BT_STATUS_SUCCESS)) { ble_local_key_cb.is_id_keys_rcvd = true; log::verbose("BLE ID keys loaded"); } } -void btif_dm_get_ble_local_keys(tBTA_DM_BLE_LOCAL_KEY_MASK* p_key_mask, - Octet16* p_er, +void btif_dm_get_ble_local_keys(tBTA_DM_BLE_LOCAL_KEY_MASK* p_key_mask, Octet16* p_er, tBTA_BLE_LOCAL_ID_KEYS* p_id_keys) { - log::assert_that(p_key_mask != nullptr, - "assert failed: p_key_mask != nullptr"); + log::assert_that(p_key_mask != nullptr, "assert failed: p_key_mask != nullptr"); if (ble_local_key_cb.is_er_rcvd) { log::assert_that(p_er != nullptr, "assert failed: p_er != nullptr"); *p_er = ble_local_key_cb.er; @@ -3651,8 +3459,7 @@ void btif_dm_get_ble_local_keys(tBTA_DM_BLE_LOCAL_KEY_MASK* p_key_mask, } if (ble_local_key_cb.is_id_keys_rcvd) { - log::assert_that(p_id_keys != nullptr, - "assert failed: p_id_keys != nullptr"); + log::assert_that(p_id_keys != nullptr, "assert failed: p_id_keys != nullptr"); p_id_keys->ir = ble_local_key_cb.id_keys.ir; p_id_keys->irk = ble_local_key_cb.id_keys.irk; p_id_keys->dhk = ble_local_key_cb.id_keys.dhk; @@ -3670,33 +3477,28 @@ static void btif_dm_save_ble_bonding_keys(RawAddress& bd_addr) { } if (pairing_cb.ble.is_penc_key_rcvd) { - btif_storage_add_ble_bonding_key( - &bd_addr, (uint8_t*)&pairing_cb.ble.penc_key, BTM_LE_KEY_PENC, - sizeof(tBTM_LE_PENC_KEYS)); + btif_storage_add_ble_bonding_key(&bd_addr, (uint8_t*)&pairing_cb.ble.penc_key, BTM_LE_KEY_PENC, + sizeof(tBTM_LE_PENC_KEYS)); } if (pairing_cb.ble.is_pid_key_rcvd) { - btif_storage_add_ble_bonding_key(&bd_addr, - (uint8_t*)&pairing_cb.ble.pid_key, - BTM_LE_KEY_PID, sizeof(tBTM_LE_PID_KEYS)); + btif_storage_add_ble_bonding_key(&bd_addr, (uint8_t*)&pairing_cb.ble.pid_key, BTM_LE_KEY_PID, + sizeof(tBTM_LE_PID_KEYS)); } if (pairing_cb.ble.is_pcsrk_key_rcvd) { - btif_storage_add_ble_bonding_key( - &bd_addr, (uint8_t*)&pairing_cb.ble.pcsrk_key, BTM_LE_KEY_PCSRK, - sizeof(tBTM_LE_PCSRK_KEYS)); + btif_storage_add_ble_bonding_key(&bd_addr, (uint8_t*)&pairing_cb.ble.pcsrk_key, + BTM_LE_KEY_PCSRK, sizeof(tBTM_LE_PCSRK_KEYS)); } if (pairing_cb.ble.is_lenc_key_rcvd) { - btif_storage_add_ble_bonding_key( - &bd_addr, (uint8_t*)&pairing_cb.ble.lenc_key, BTM_LE_KEY_LENC, - sizeof(tBTM_LE_LENC_KEYS)); + btif_storage_add_ble_bonding_key(&bd_addr, (uint8_t*)&pairing_cb.ble.lenc_key, BTM_LE_KEY_LENC, + sizeof(tBTM_LE_LENC_KEYS)); } if (pairing_cb.ble.is_lcsrk_key_rcvd) { - btif_storage_add_ble_bonding_key( - &bd_addr, (uint8_t*)&pairing_cb.ble.lcsrk_key, BTM_LE_KEY_LCSRK, - sizeof(tBTM_LE_LCSRK_KEYS)); + btif_storage_add_ble_bonding_key(&bd_addr, (uint8_t*)&pairing_cb.ble.lcsrk_key, + BTM_LE_KEY_LCSRK, sizeof(tBTM_LE_LCSRK_KEYS)); } if (pairing_cb.ble.is_lidk_key_rcvd) { @@ -3721,8 +3523,7 @@ static void btif_dm_remove_ble_bonding_keys(void) { * Returns void * ******************************************************************************/ -static void btif_dm_ble_sec_req_evt(tBTA_DM_BLE_SEC_REQ* p_ble_req, - bool is_consent) { +static void btif_dm_ble_sec_req_evt(tBTA_DM_BLE_SEC_REQ* p_ble_req, bool is_consent) { int dev_type; log::verbose("addr:{}", p_ble_req->bd_addr); @@ -3736,8 +3537,7 @@ static void btif_dm_ble_sec_req_evt(tBTA_DM_BLE_SEC_REQ* p_ble_req, if (!btif_get_device_type(p_ble_req->bd_addr, &dev_type)) { dev_type = BT_DEVICE_TYPE_BLE; } - btif_dm_update_ble_remote_properties(p_ble_req->bd_addr, p_ble_req->bd_name, - kDevClassEmpty, + btif_dm_update_ble_remote_properties(p_ble_req->bd_addr, p_ble_req->bd_name, kDevClassEmpty, (tBT_DEVICE_TYPE)dev_type); RawAddress bd_addr = p_ble_req->bd_addr; @@ -3750,11 +3550,9 @@ static void btif_dm_ble_sec_req_evt(tBTA_DM_BLE_SEC_REQ* p_ble_req, pairing_cb.is_ssp = true; btm_set_bond_type_dev(p_ble_req->bd_addr, pairing_cb.bond_type); - BTM_LogHistory(kBtmLogTagCallback, bd_addr, "SSP ble request", - "BT_SSP_VARIANT_CONSENT"); + BTM_LogHistory(kBtmLogTagCallback, bd_addr, "SSP ble request", "BT_SSP_VARIANT_CONSENT"); - GetInterfaceToProfiles()->events->invoke_ssp_request_cb( - bd_addr, BT_SSP_VARIANT_CONSENT, 0); + GetInterfaceToProfiles()->events->invoke_ssp_request_cb(bd_addr, BT_SSP_VARIANT_CONSENT, 0); } /******************************************************************************* @@ -3775,8 +3573,7 @@ static void btif_dm_ble_passkey_req_evt(tBTA_DM_PIN_REQ* p_pin_req) { if (!btif_get_device_type(p_pin_req->bd_addr, &dev_type)) { dev_type = BT_DEVICE_TYPE_BLE; } - btif_dm_update_ble_remote_properties(p_pin_req->bd_addr, p_pin_req->bd_name, - kDevClassEmpty, + btif_dm_update_ble_remote_properties(p_pin_req->bd_addr, p_pin_req->bd_name, kDevClassEmpty, (tBT_DEVICE_TYPE)dev_type); RawAddress bd_addr = p_pin_req->bd_addr; @@ -3790,8 +3587,7 @@ static void btif_dm_ble_passkey_req_evt(tBTA_DM_PIN_REQ* p_pin_req) { BTM_LogHistory(kBtmLogTagCallback, bd_addr, "PIN request", base::StringPrintf("name:'%s'", PRIVATE_NAME(bd_name.name))); - GetInterfaceToProfiles()->events->invoke_pin_request_cb(bd_addr, bd_name, cod, - false); + GetInterfaceToProfiles()->events->invoke_pin_request_cb(bd_addr, bd_name, cod, false); } static void btif_dm_ble_key_nc_req_evt(tBTA_DM_SP_KEY_NOTIF* p_notif_req) { /* TODO implement key notification for numeric comparison */ @@ -3800,8 +3596,8 @@ static void btif_dm_ble_key_nc_req_evt(tBTA_DM_SP_KEY_NOTIF* p_notif_req) { log::verbose("addr:{}", bd_addr); /* Remote name update */ - btif_update_remote_properties(p_notif_req->bd_addr, p_notif_req->bd_name, - kDevClassEmpty, BT_DEVICE_TYPE_BLE); + btif_update_remote_properties(p_notif_req->bd_addr, p_notif_req->bd_name, kDevClassEmpty, + BT_DEVICE_TYPE_BLE); bond_state_changed(BT_STATUS_SUCCESS, bd_addr, BT_BOND_STATE_BONDING); pairing_cb.is_ssp = false; @@ -3812,7 +3608,7 @@ static void btif_dm_ble_key_nc_req_evt(tBTA_DM_SP_KEY_NOTIF* p_notif_req) { base::StringPrintf("passkey:%u", p_notif_req->passkey)); GetInterfaceToProfiles()->events->invoke_ssp_request_cb( - bd_addr, BT_SSP_VARIANT_PASSKEY_CONFIRMATION, p_notif_req->passkey); + bd_addr, BT_SSP_VARIANT_PASSKEY_CONFIRMATION, p_notif_req->passkey); } static void btif_dm_ble_oob_req_evt(tBTA_DM_SP_RMT_OOB* req_oob_type) { @@ -3834,8 +3630,8 @@ static void btif_dm_ble_oob_req_evt(tBTA_DM_SP_RMT_OOB* req_oob_type) { } /* Remote name update */ - btif_update_remote_properties(req_oob_type->bd_addr, req_oob_type->bd_name, - kDevClassEmpty, BT_DEVICE_TYPE_BLE); + btif_update_remote_properties(req_oob_type->bd_addr, req_oob_type->bd_name, kDevClassEmpty, + BT_DEVICE_TYPE_BLE); bond_state_changed(BT_STATUS_SUCCESS, bd_addr, BT_BOND_STATE_BONDING); pairing_cb.is_ssp = false; @@ -3868,8 +3664,7 @@ static void btif_dm_ble_sc_oob_req_evt(tBTA_DM_SP_RMT_OOB* req_oob_type) { // Always prefer 256 for LE case BTM_OOB_PRESENT_256: log::info("Using P256"); - if (is_empty_128bit(oob_cb.p256_data.c) && - is_empty_128bit(oob_cb.p256_data.r)) { + if (is_empty_128bit(oob_cb.p256_data.c) && is_empty_128bit(oob_cb.p256_data.r)) { log::warn("P256 LE SC OOB data is empty"); return; } @@ -3877,8 +3672,7 @@ static void btif_dm_ble_sc_oob_req_evt(tBTA_DM_SP_RMT_OOB* req_oob_type) { break; case BTM_OOB_PRESENT_192: log::info("Using P192"); - if (is_empty_128bit(oob_cb.p192_data.c) && - is_empty_128bit(oob_cb.p192_data.r)) { + if (is_empty_128bit(oob_cb.p192_data.c) && is_empty_128bit(oob_cb.p192_data.r)) { log::warn("P192 LE SC OOB data is empty"); return; } @@ -3887,8 +3681,7 @@ static void btif_dm_ble_sc_oob_req_evt(tBTA_DM_SP_RMT_OOB* req_oob_type) { } /* Remote name update */ - btif_update_remote_properties(req_oob_type->bd_addr, - oob_data_to_use.device_name, kDevClassEmpty, + btif_update_remote_properties(req_oob_type->bd_addr, oob_data_to_use.device_name, kDevClassEmpty, BT_DEVICE_TYPE_BLE); bond_state_changed(BT_STATUS_SUCCESS, bd_addr, BT_BOND_STATE_BONDING); @@ -3896,13 +3689,11 @@ static void btif_dm_ble_sc_oob_req_evt(tBTA_DM_SP_RMT_OOB* req_oob_type) { // TODO: we can derive classic pairing from this one pairing_cb.is_le_only = true; pairing_cb.is_le_nc = false; - BTM_BleSecureConnectionOobDataReply(req_oob_type->bd_addr, oob_data_to_use.c, - oob_data_to_use.r); + BTM_BleSecureConnectionOobDataReply(req_oob_type->bd_addr, oob_data_to_use.c, oob_data_to_use.r); } -void btif_dm_update_ble_remote_properties(const RawAddress& bd_addr, - BD_NAME bd_name, DEV_CLASS dev_class, - tBT_DEVICE_TYPE dev_type) { +void btif_dm_update_ble_remote_properties(const RawAddress& bd_addr, BD_NAME bd_name, + DEV_CLASS dev_class, tBT_DEVICE_TYPE dev_type) { btif_update_remote_properties(bd_addr, bd_name, dev_class, dev_type); } @@ -3911,7 +3702,7 @@ static void btif_dm_ble_tx_test_cback(void* p) { uint8_t status; STREAM_TO_UINT8(status, p_param); GetInterfaceToProfiles()->events->invoke_le_test_mode_cb( - (status == 0) ? BT_STATUS_SUCCESS : BT_STATUS_FAIL, 0); + (status == 0) ? BT_STATUS_SUCCESS : BT_STATUS_FAIL, 0); } static void btif_dm_ble_rx_test_cback(void* p) { @@ -3919,7 +3710,7 @@ static void btif_dm_ble_rx_test_cback(void* p) { uint8_t status; STREAM_TO_UINT8(status, p_param); GetInterfaceToProfiles()->events->invoke_le_test_mode_cb( - (status == 0) ? BT_STATUS_SUCCESS : BT_STATUS_FAIL, 0); + (status == 0) ? BT_STATUS_SUCCESS : BT_STATUS_FAIL, 0); } static void btif_dm_ble_test_end_cback(void* p) { @@ -3927,15 +3718,15 @@ static void btif_dm_ble_test_end_cback(void* p) { uint8_t status; uint16_t count = 0; STREAM_TO_UINT8(status, p_param); - if (status == 0) STREAM_TO_UINT16(count, p_param); + if (status == 0) { + STREAM_TO_UINT16(count, p_param); + } GetInterfaceToProfiles()->events->invoke_le_test_mode_cb( - (status == 0) ? BT_STATUS_SUCCESS : BT_STATUS_FAIL, count); + (status == 0) ? BT_STATUS_SUCCESS : BT_STATUS_FAIL, count); } -void btif_ble_transmitter_test(uint8_t tx_freq, uint8_t test_data_len, - uint8_t packet_payload) { - BTM_BleTransmitterTest(tx_freq, test_data_len, packet_payload, - btif_dm_ble_tx_test_cback); +void btif_ble_transmitter_test(uint8_t tx_freq, uint8_t test_data_len, uint8_t packet_payload) { + BTM_BleTransmitterTest(tx_freq, test_data_len, packet_payload, btif_dm_ble_tx_test_cback); } void btif_ble_receiver_test(uint8_t rx_freq) { @@ -3982,8 +3773,7 @@ static const char* btif_get_default_local_name() { return btif_default_local_name; } -static void btif_stats_add_bond_event(const RawAddress& bd_addr, - bt_bond_function_t function, +static void btif_stats_add_bond_event(const RawAddress& bd_addr, bt_bond_function_t function, bt_bond_state_t state) { std::unique_lock lock(bond_event_lock); @@ -3994,11 +3784,9 @@ static void btif_stats_add_bond_event(const RawAddress& bd_addr, clock_gettime(CLOCK_REALTIME, &event->timestamp); btif_num_bond_events++; - btif_events_end_index = - (btif_events_end_index + 1) % (MAX_BTIF_BOND_EVENT_ENTRIES + 1); + btif_events_end_index = (btif_events_end_index + 1) % (MAX_BTIF_BOND_EVENT_ENTRIES + 1); if (btif_events_end_index == btif_events_start_index) { - btif_events_start_index = - (btif_events_start_index + 1) % (MAX_BTIF_BOND_EVENT_ENTRIES + 1); + btif_events_start_index = (btif_events_start_index + 1) % (MAX_BTIF_BOND_EVENT_ENTRIES + 1); } int type; @@ -4021,19 +3809,17 @@ static void btif_stats_add_bond_event(const RawAddress& bd_addr, } uint32_t cod = get_cod(&bd_addr); - uint64_t ts = - event->timestamp.tv_sec * 1000 + event->timestamp.tv_nsec / 1000000; - bluetooth::common::BluetoothMetricsLogger::GetInstance()->LogPairEvent( - 0, ts, cod, device_type); + uint64_t ts = event->timestamp.tv_sec * 1000 + event->timestamp.tv_nsec / 1000000; + bluetooth::common::BluetoothMetricsLogger::GetInstance()->LogPairEvent(0, ts, cod, device_type); } void btif_debug_bond_event_dump(int fd) { std::unique_lock lock(bond_event_lock); dprintf(fd, "\nBond Events: \n"); dprintf(fd, " Total Number of events: %zu\n", btif_num_bond_events); - if (btif_num_bond_events > 0) - dprintf(fd, - " Time address Function State\n"); + if (btif_num_bond_events > 0) { + dprintf(fd, " Time address Function State\n"); + } for (size_t i = btif_events_start_index; i != btif_events_end_index; i = (i + 1) % (MAX_BTIF_BOND_EVENT_ENTRIES + 1)) { @@ -4081,20 +3867,22 @@ void btif_debug_bond_event_dump(int fd) { break; } - dprintf(fd, " %s %s %s %s\n", eventtime, - ADDRESS_TO_LOGGABLE_CSTR(event->bd_addr), func_name, bond_state); + dprintf(fd, " %s %s %s %s\n", eventtime, ADDRESS_TO_LOGGABLE_CSTR(event->bd_addr), + func_name, bond_state); } } bool btif_get_device_type(const RawAddress& bda, int* p_device_type) { - if (p_device_type == NULL) return false; + if (p_device_type == NULL) { + return false; + } std::string addrstr = bda.ToString(); const char* bd_addr_str = addrstr.c_str(); - if (!btif_config_get_int(bd_addr_str, BTIF_STORAGE_KEY_DEV_TYPE, - p_device_type)) + if (!btif_config_get_int(bd_addr_str, BTIF_STORAGE_KEY_DEV_TYPE, p_device_type)) { return false; + } tBT_DEVICE_TYPE device_type = static_cast(*p_device_type); log::debug("bd_addr:{} device_type:{}", bda, DeviceTypeText(device_type)); @@ -4102,14 +3890,17 @@ bool btif_get_device_type(const RawAddress& bda, int* p_device_type) { } bool btif_get_address_type(const RawAddress& bda, tBLE_ADDR_TYPE* p_addr_type) { - if (p_addr_type == NULL) return false; + if (p_addr_type == NULL) { + return false; + } std::string addrstr = bda.ToString(); const char* bd_addr_str = addrstr.c_str(); int val = 0; - if (!btif_config_get_int(bd_addr_str, BTIF_STORAGE_KEY_ADDR_TYPE, &val)) + if (!btif_config_get_int(bd_addr_str, BTIF_STORAGE_KEY_ADDR_TYPE, &val)) { return false; + } *p_addr_type = static_cast(val); log::debug("bd_addr:{}[{}]", bda, AddressTypeText(*p_addr_type)); return true; @@ -4119,8 +3910,7 @@ void btif_check_device_in_inquiry_db(const RawAddress& address) { tBLE_ADDR_TYPE addr_type = BLE_ADDR_PUBLIC; int device_type = 0; - if (btif_get_address_type(address, &addr_type) && - btif_get_device_type(address, &device_type) && + if (btif_get_address_type(address, &addr_type) && btif_get_device_type(address, &device_type) && device_type != BT_DEVICE_TYPE_BREDR) { BTA_DmAddBleDevice(address, addr_type, device_type); } @@ -4134,23 +3924,19 @@ void btif_dm_clear_filter_accept_list() { BTA_DmClearFilterAcceptList(); } void btif_dm_disconnect_all_acls() { BTA_DmDisconnectAllAcls(); } -void btif_dm_le_rand(bluetooth::hci::LeRandCallback callback) { - BTA_DmLeRand(std::move(callback)); -} +void btif_dm_le_rand(bluetooth::hci::LeRandCallback callback) { BTA_DmLeRand(std::move(callback)); } void btif_dm_set_event_filter_connection_setup_all_devices() { // Autoplumbed BTA_DmSetEventFilterConnectionSetupAllDevices(); } -void btif_dm_allow_wake_by_hid( - std::vector classic_addrs, - std::vector> le_addrs) { +void btif_dm_allow_wake_by_hid(std::vector classic_addrs, + std::vector> le_addrs) { BTA_DmAllowWakeByHid(std::move(classic_addrs), std::move(le_addrs)); } -void btif_dm_restore_filter_accept_list( - std::vector> le_devices) { +void btif_dm_restore_filter_accept_list(std::vector> le_devices) { // Autoplumbed BTA_DmRestoreFilterAcceptList(std::move(le_devices)); } @@ -4178,8 +3964,7 @@ void btif_dm_metadata_changed(const RawAddress& remote_bd_addr, int key, !btif_model_name_known(remote_bd_addr) && BTM_IsAclConnectionUp(remote_bd_addr, BT_TRANSPORT_LE)) { log::info("Read model name for le audio capable device"); - if (!DIS_ReadDISInfo(remote_bd_addr, read_dis_cback, - DIS_ATTR_MODEL_NUM_BIT)) { + if (!DIS_ReadDISInfo(remote_bd_addr, read_dis_cback, DIS_ATTR_MODEL_NUM_BIT)) { log::warn("Read DIS failed"); } } @@ -4190,17 +3975,14 @@ namespace bluetooth { namespace legacy { namespace testing { -void bta_energy_info_cb(tBTM_BLE_TX_TIME_MS tx_time, - tBTM_BLE_RX_TIME_MS rx_time, - tBTM_BLE_IDLE_TIME_MS idle_time, - tBTM_BLE_ENERGY_USED energy_used, +void bta_energy_info_cb(tBTM_BLE_TX_TIME_MS tx_time, tBTM_BLE_RX_TIME_MS rx_time, + tBTM_BLE_IDLE_TIME_MS idle_time, tBTM_BLE_ENERGY_USED energy_used, tBTM_CONTRL_STATE ctrl_state, tBTA_STATUS status) { - ::bta_energy_info_cb(tx_time, rx_time, idle_time, energy_used, ctrl_state, - status); + ::bta_energy_info_cb(tx_time, rx_time, idle_time, energy_used, ctrl_state, status); } -void btif_on_name_read(RawAddress bd_addr, tHCI_ERROR_CODE hci_status, - const BD_NAME bd_name, bool during_device_search) { +void btif_on_name_read(RawAddress bd_addr, tHCI_ERROR_CODE hci_status, const BD_NAME bd_name, + bool during_device_search) { ::btif_on_name_read(bd_addr, hci_status, bd_name, during_device_search); } diff --git a/system/btif/src/btif_gatt.cc b/system/btif/src/btif_gatt.cc index 3e77e987372..3292ddbe7a5 100644 --- a/system/btif/src/btif_gatt.cc +++ b/system/btif/src/btif_gatt.cc @@ -64,22 +64,24 @@ static bt_status_t btif_gatt_init(const btgatt_callbacks_t* callbacks) { * ******************************************************************************/ static void btif_gatt_cleanup(void) { - if (bt_gatt_callbacks) bt_gatt_callbacks = NULL; + if (bt_gatt_callbacks) { + bt_gatt_callbacks = NULL; + } BTA_GATTC_Disable(); BTA_GATTS_Disable(); } static btgatt_interface_t btgattInterface = { - .size = sizeof(btgattInterface), + .size = sizeof(btgattInterface), - .init = btif_gatt_init, - .cleanup = btif_gatt_cleanup, + .init = btif_gatt_init, + .cleanup = btif_gatt_cleanup, - .client = &btgattClientInterface, - .server = &btgattServerInterface, - .scanner = nullptr, // filled in btif_gatt_get_interface - .advertiser = nullptr // filled in btif_gatt_get_interface + .client = &btgattClientInterface, + .server = &btgattServerInterface, + .scanner = nullptr, // filled in btif_gatt_get_interface + .advertiser = nullptr // filled in btif_gatt_get_interface }; /******************************************************************************* @@ -98,6 +100,6 @@ const btgatt_interface_t* btif_gatt_get_interface() { btgattInterface.scanner = get_ble_scanner_instance(); btgattInterface.advertiser = bluetooth::shim::get_ble_advertiser_instance(); btgattInterface.distance_measurement_manager = - bluetooth::shim::get_distance_measurement_instance(); + bluetooth::shim::get_distance_measurement_instance(); return &btgattInterface; } diff --git a/system/btif/src/btif_gatt_client.cc b/system/btif/src/btif_gatt_client.cc index 954265482f8..41dae810598 100644 --- a/system/btif/src/btif_gatt_client.cc +++ b/system/btif/src/btif_gatt_client.cc @@ -69,8 +69,7 @@ using std::vector; bool btif_get_address_type(const RawAddress& bda, tBLE_ADDR_TYPE* p_addr_type); bool btif_get_device_type(const RawAddress& bda, int* p_device_type); -static bt_status_t btif_gattc_test_command_impl( - int command, const btgatt_test_params_t* params); +static bt_status_t btif_gattc_test_command_impl(int command, const btgatt_test_params_t* params); extern const btgatt_callbacks_t* bt_gatt_callbacks; typedef struct { @@ -78,12 +77,9 @@ typedef struct { uint16_t conn_id; } btif_test_cb_t; -static const char* disc_name[GATT_DISC_MAX] = {"Unknown", - "GATT_DISC_SRVC_ALL", - "GATT_DISC_SRVC_BY_UUID", - "GATT_DISC_INC_SRVC", - "GATT_DISC_CHAR", - "GATT_DISC_CHAR_DSCPT"}; +static const char* disc_name[GATT_DISC_MAX] = { + "Unknown", "GATT_DISC_SRVC_ALL", "GATT_DISC_SRVC_BY_UUID", "GATT_DISC_INC_SRVC", + "GATT_DISC_CHAR", "GATT_DISC_CHAR_DSCPT"}; static btif_test_cb_t test_cb; @@ -125,20 +121,19 @@ namespace { uint8_t rssi_request_client_if; static void btif_gattc_upstreams_evt(uint16_t event, char* p_param) { - log::debug("Event {} [{}]", - gatt_client_event_text(static_cast(event)), event); + log::debug("Event {} [{}]", gatt_client_event_text(static_cast(event)), event); tBTA_GATTC* p_data = (tBTA_GATTC*)p_param; switch (event) { case BTA_GATTC_EXEC_EVT: { - HAL_CBACK(bt_gatt_callbacks, client->execute_write_cb, - p_data->exec_cmpl.conn_id, p_data->exec_cmpl.status); + HAL_CBACK(bt_gatt_callbacks, client->execute_write_cb, p_data->exec_cmpl.conn_id, + p_data->exec_cmpl.status); break; } case BTA_GATTC_SEARCH_CMPL_EVT: { - HAL_CBACK(bt_gatt_callbacks, client->search_complete_cb, - p_data->search_cmpl.conn_id, p_data->search_cmpl.status); + HAL_CBACK(bt_gatt_callbacks, client->search_complete_cb, p_data->search_cmpl.conn_id, + p_data->search_cmpl.status); break; } @@ -152,37 +147,35 @@ static void btif_gattc_upstreams_evt(uint16_t event, char* p_param) { data.is_notify = p_data->notify.is_notify; data.len = p_data->notify.len; - HAL_CBACK(bt_gatt_callbacks, client->notify_cb, p_data->notify.conn_id, - data); + HAL_CBACK(bt_gatt_callbacks, client->notify_cb, p_data->notify.conn_id, data); - if (!p_data->notify.is_notify) + if (!p_data->notify.is_notify) { BTA_GATTC_SendIndConfirm(p_data->notify.conn_id, p_data->notify.cid); + } break; } case BTA_GATTC_OPEN_EVT: { log::debug("BTA_GATTC_OPEN_EVT {}", p_data->open.remote_bda); - HAL_CBACK(bt_gatt_callbacks, client->open_cb, p_data->open.conn_id, - p_data->open.status, p_data->open.client_if, - p_data->open.remote_bda); + HAL_CBACK(bt_gatt_callbacks, client->open_cb, p_data->open.conn_id, p_data->open.status, + p_data->open.client_if, p_data->open.remote_bda); if (GATT_DEF_BLE_MTU_SIZE != p_data->open.mtu && p_data->open.mtu) { - HAL_CBACK(bt_gatt_callbacks, client->configure_mtu_cb, - p_data->open.conn_id, p_data->open.status, p_data->open.mtu); + HAL_CBACK(bt_gatt_callbacks, client->configure_mtu_cb, p_data->open.conn_id, + p_data->open.status, p_data->open.mtu); } - if (p_data->open.status == GATT_SUCCESS) - btif_gatt_check_encrypted_link(p_data->open.remote_bda, - p_data->open.transport); + if (p_data->open.status == GATT_SUCCESS) { + btif_gatt_check_encrypted_link(p_data->open.remote_bda, p_data->open.transport); + } break; } case BTA_GATTC_CLOSE_EVT: { log::debug("BTA_GATTC_CLOSE_EVT {}", p_data->close.remote_bda); - HAL_CBACK(bt_gatt_callbacks, client->close_cb, p_data->close.conn_id, - p_data->close.status, p_data->close.client_if, - p_data->close.remote_bda); + HAL_CBACK(bt_gatt_callbacks, client->close_cb, p_data->close.conn_id, p_data->close.status, + p_data->close.client_if, p_data->close.remote_bda); break; } @@ -194,40 +187,36 @@ static void btif_gattc_upstreams_evt(uint16_t event, char* p_param) { break; case BTA_GATTC_CFG_MTU_EVT: { - HAL_CBACK(bt_gatt_callbacks, client->configure_mtu_cb, - p_data->cfg_mtu.conn_id, p_data->cfg_mtu.status, - p_data->cfg_mtu.mtu); + HAL_CBACK(bt_gatt_callbacks, client->configure_mtu_cb, p_data->cfg_mtu.conn_id, + p_data->cfg_mtu.status, p_data->cfg_mtu.mtu); break; } case BTA_GATTC_CONGEST_EVT: - HAL_CBACK(bt_gatt_callbacks, client->congestion_cb, - p_data->congest.conn_id, p_data->congest.congested); + HAL_CBACK(bt_gatt_callbacks, client->congestion_cb, p_data->congest.conn_id, + p_data->congest.congested); break; case BTA_GATTC_PHY_UPDATE_EVT: - HAL_CBACK(bt_gatt_callbacks, client->phy_updated_cb, - p_data->phy_update.conn_id, p_data->phy_update.tx_phy, - p_data->phy_update.rx_phy, p_data->phy_update.status); + HAL_CBACK(bt_gatt_callbacks, client->phy_updated_cb, p_data->phy_update.conn_id, + p_data->phy_update.tx_phy, p_data->phy_update.rx_phy, p_data->phy_update.status); break; case BTA_GATTC_CONN_UPDATE_EVT: - HAL_CBACK(bt_gatt_callbacks, client->conn_updated_cb, - p_data->conn_update.conn_id, p_data->conn_update.interval, - p_data->conn_update.latency, p_data->conn_update.timeout, - p_data->conn_update.status); + HAL_CBACK(bt_gatt_callbacks, client->conn_updated_cb, p_data->conn_update.conn_id, + p_data->conn_update.interval, p_data->conn_update.latency, + p_data->conn_update.timeout, p_data->conn_update.status); break; case BTA_GATTC_SRVC_CHG_EVT: - HAL_CBACK(bt_gatt_callbacks, client->service_changed_cb, - p_data->service_changed.conn_id); + HAL_CBACK(bt_gatt_callbacks, client->service_changed_cb, p_data->service_changed.conn_id); break; case BTA_GATTC_SUBRATE_CHG_EVT: - HAL_CBACK(bt_gatt_callbacks, client->subrate_chg_cb, - p_data->subrate_chg.conn_id, p_data->subrate_chg.subrate_factor, - p_data->subrate_chg.latency, p_data->subrate_chg.cont_num, - p_data->subrate_chg.timeout, p_data->subrate_chg.status); + HAL_CBACK(bt_gatt_callbacks, client->subrate_chg_cb, p_data->subrate_chg.conn_id, + p_data->subrate_chg.subrate_factor, p_data->subrate_chg.latency, + p_data->subrate_chg.cont_num, p_data->subrate_chg.timeout, + p_data->subrate_chg.status); break; default: @@ -237,62 +226,58 @@ static void btif_gattc_upstreams_evt(uint16_t event, char* p_param) { } static void bta_gattc_cback(tBTA_GATTC_EVT event, tBTA_GATTC* p_data) { - log::debug("gatt client callback event:{} [{}]", - gatt_client_event_text(event), event); - bt_status_t status = - btif_transfer_context(btif_gattc_upstreams_evt, (uint16_t)event, - (char*)p_data, sizeof(tBTA_GATTC), NULL); + log::debug("gatt client callback event:{} [{}]", gatt_client_event_text(event), event); + bt_status_t status = btif_transfer_context(btif_gattc_upstreams_evt, (uint16_t)event, + (char*)p_data, sizeof(tBTA_GATTC), NULL); ASSERTC(status == BT_STATUS_SUCCESS, "Context transfer failed!", status); } void btm_read_rssi_cb(void* p_void) { tBTM_RSSI_RESULT* p_result = (tBTM_RSSI_RESULT*)p_void; - if (!p_result) return; + if (!p_result) { + return; + } - CLI_CBACK_IN_JNI(read_remote_rssi_cb, rssi_request_client_if, - p_result->rem_bda, p_result->rssi, p_result->status); + CLI_CBACK_IN_JNI(read_remote_rssi_cb, rssi_request_client_if, p_result->rem_bda, p_result->rssi, + p_result->status); } /******************************************************************************* * Client API Functions ******************************************************************************/ -static bt_status_t btif_gattc_register_app(const Uuid& uuid, - bool eatt_support) { +static bt_status_t btif_gattc_register_app(const Uuid& uuid, bool eatt_support) { CHECK_BTGATT_INIT(); return do_in_jni_thread(Bind( - [](const Uuid& uuid, bool eatt_support) { - BTA_GATTC_AppRegister( - bta_gattc_cback, - base::Bind( - [](const Uuid& uuid, uint8_t client_id, uint8_t status) { - do_in_jni_thread(Bind( - [](const Uuid& uuid, uint8_t client_id, uint8_t status) { - HAL_CBACK(bt_gatt_callbacks, client->register_client_cb, - status, client_id, uuid); - }, - uuid, client_id, status)); - }, - uuid), - eatt_support); - }, - uuid, eatt_support)); -} - -static void btif_gattc_unregister_app_impl(int client_if) { - BTA_GATTC_AppDeregister(client_if); + [](const Uuid& uuid, bool eatt_support) { + BTA_GATTC_AppRegister( + bta_gattc_cback, + base::Bind( + [](const Uuid& uuid, uint8_t client_id, uint8_t status) { + do_in_jni_thread(Bind( + [](const Uuid& uuid, uint8_t client_id, uint8_t status) { + HAL_CBACK(bt_gatt_callbacks, client->register_client_cb, + status, client_id, uuid); + }, + uuid, client_id, status)); + }, + uuid), + eatt_support); + }, + uuid, eatt_support)); } +static void btif_gattc_unregister_app_impl(int client_if) { BTA_GATTC_AppDeregister(client_if); } + static bt_status_t btif_gattc_unregister_app(int client_if) { CHECK_BTGATT_INIT(); return do_in_jni_thread(Bind(&btif_gattc_unregister_app_impl, client_if)); } -void btif_gattc_open_impl(int client_if, RawAddress address, - tBLE_ADDR_TYPE addr_type, bool is_direct, - int transport_p, bool opportunistic, +void btif_gattc_open_impl(int client_if, RawAddress address, tBLE_ADDR_TYPE addr_type, + bool is_direct, int transport_p, bool opportunistic, int initiating_phys) { int device_type = BT_DEVICE_TYPE_UNKNOWN; tBT_TRANSPORT transport = (tBT_TRANSPORT)BT_TRANSPORT_LE; @@ -303,8 +288,7 @@ void btif_gattc_open_impl(int client_if, RawAddress address, } else { // Ensure device is in inquiry database addr_type = BLE_ADDR_PUBLIC; - if (btif_get_address_type(address, &addr_type) && - btif_get_device_type(address, &device_type) && + if (btif_get_address_type(address, &addr_type) && btif_get_device_type(address, &device_type) && device_type != BT_DEVICE_TYPE_BREDR) { BTA_DmAddBleDevice(address, addr_type, device_type); } @@ -315,13 +299,12 @@ void btif_gattc_open_impl(int client_if, RawAddress address, // Check for privacy 1.0 and 1.1 controller and do not start background // connection if RPA offloading is not supported, since it will not // connect after change of random address - if (!bluetooth::shim::GetController()->SupportsBlePrivacy() && - (addr_type == BLE_ADDR_RANDOM) && BTM_BLE_IS_RESOLVE_BDA(address)) { + if (!bluetooth::shim::GetController()->SupportsBlePrivacy() && (addr_type == BLE_ADDR_RANDOM) && + BTM_BLE_IS_RESOLVE_BDA(address)) { tBTM_BLE_VSC_CB vnd_capabilities; BTM_BleGetVendorCapabilities(&vnd_capabilities); if (!vnd_capabilities.rpa_offloading) { - HAL_CBACK(bt_gatt_callbacks, client->open_cb, 0, BT_STATUS_UNSUPPORTED, - client_if, address); + HAL_CBACK(bt_gatt_callbacks, client->open_cb, 0, BT_STATUS_UNSUPPORTED, client_if, address); return; } } @@ -341,10 +324,11 @@ void btif_gattc_open_impl(int client_if, RawAddress address, break; case BT_DEVICE_TYPE_DUMO: - if (addr_type == BLE_ADDR_RANDOM) + if (addr_type == BLE_ADDR_RANDOM) { transport = BT_TRANSPORT_LE; - else + } else { transport = BT_TRANSPORT_BR_EDR; + } break; default: log::error("Unknown device type {}", device_type); @@ -353,28 +337,23 @@ void btif_gattc_open_impl(int client_if, RawAddress address, } // Connect! - log::info("Transport={}, device type={}, address type ={}, phy={}", transport, - device_type, addr_type, initiating_phys); - tBTM_BLE_CONN_TYPE type = - is_direct ? BTM_BLE_DIRECT_CONNECTION : BTM_BLE_BKG_CONNECT_ALLOW_LIST; - BTA_GATTC_Open(client_if, address, addr_type, type, transport, opportunistic, - initiating_phys); + log::info("Transport={}, device type={}, address type ={}, phy={}", transport, device_type, + addr_type, initiating_phys); + tBTM_BLE_CONN_TYPE type = is_direct ? BTM_BLE_DIRECT_CONNECTION : BTM_BLE_BKG_CONNECT_ALLOW_LIST; + BTA_GATTC_Open(client_if, address, addr_type, type, transport, opportunistic, initiating_phys); } -static bt_status_t btif_gattc_open(int client_if, const RawAddress& bd_addr, - uint8_t addr_type, bool is_direct, - int transport, bool opportunistic, +static bt_status_t btif_gattc_open(int client_if, const RawAddress& bd_addr, uint8_t addr_type, + bool is_direct, int transport, bool opportunistic, int initiating_phys) { CHECK_BTGATT_INIT(); // Closure will own this value and free it. - return do_in_jni_thread(Bind(&btif_gattc_open_impl, client_if, bd_addr, - addr_type, is_direct, transport, opportunistic, - initiating_phys)); + return do_in_jni_thread(Bind(&btif_gattc_open_impl, client_if, bd_addr, addr_type, is_direct, + transport, opportunistic, initiating_phys)); } void btif_gattc_close_impl(int client_if, RawAddress address, int conn_id) { - log::info("client_if={}, conn_id={}, address={}", client_if, conn_id, - address); + log::info("client_if={}, conn_id={}, address={}", client_if, conn_id, address); // Disconnect established connections if (conn_id != 0) { BTA_GATTC_Close(conn_id); @@ -386,26 +365,21 @@ void btif_gattc_close_impl(int client_if, RawAddress address, int conn_id) { BTA_GATTC_CancelOpen(client_if, address, false); } -static bt_status_t btif_gattc_close(int client_if, const RawAddress& bd_addr, - int conn_id) { +static bt_status_t btif_gattc_close(int client_if, const RawAddress& bd_addr, int conn_id) { CHECK_BTGATT_INIT(); - return do_in_jni_thread( - Bind(&btif_gattc_close_impl, client_if, bd_addr, conn_id)); + return do_in_jni_thread(Bind(&btif_gattc_close_impl, client_if, bd_addr, conn_id)); } -static bt_status_t btif_gattc_refresh(int client_if, - const RawAddress& bd_addr) { +static bt_status_t btif_gattc_refresh(int client_if, const RawAddress& bd_addr) { CHECK_BTGATT_INIT(); return do_in_jni_thread(Bind(&BTA_GATTC_Refresh, bd_addr)); } -static bt_status_t btif_gattc_search_service(int conn_id, - const Uuid* filter_uuid) { +static bt_status_t btif_gattc_search_service(int conn_id, const Uuid* filter_uuid) { CHECK_BTGATT_INIT(); if (filter_uuid) { - return do_in_jni_thread( - Bind(&BTA_GATTC_ServiceSearchRequest, conn_id, *filter_uuid)); + return do_in_jni_thread(Bind(&BTA_GATTC_ServiceSearchRequest, conn_id, *filter_uuid)); } else { return do_in_jni_thread(Bind(&BTA_GATTC_ServiceSearchAllRequest, conn_id)); } @@ -429,285 +403,254 @@ static bt_status_t btif_gattc_get_gatt_db(int conn_id) { return do_in_jni_thread(Bind(&btif_gattc_get_gatt_db_impl, conn_id)); } -void read_char_cb(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, - uint16_t len, uint8_t* value, void* data) { +void read_char_cb(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, uint16_t len, + uint8_t* value, void* data) { btgatt_read_params_t params = { - .handle = handle, - .value.len = len, - .value_type = 0x00, /* GATTC_READ_VALUE_TYPE_VALUE */ - .status = status, + .handle = handle, + .value.len = len, + .value_type = 0x00, /* GATTC_READ_VALUE_TYPE_VALUE */ + .status = status, }; - log::assert_that(len <= GATT_MAX_ATTR_LEN, - "assert failed: len <= GATT_MAX_ATTR_LEN"); - if (len > 0) memcpy(params.value.value, value, len); + log::assert_that(len <= GATT_MAX_ATTR_LEN, "assert failed: len <= GATT_MAX_ATTR_LEN"); + if (len > 0) { + memcpy(params.value.value, value, len); + } CLI_CBACK_IN_JNI(read_characteristic_cb, conn_id, status, params); } -static bt_status_t btif_gattc_read_char(int conn_id, uint16_t handle, - int auth_req) { +static bt_status_t btif_gattc_read_char(int conn_id, uint16_t handle, int auth_req) { CHECK_BTGATT_INIT(); - return do_in_jni_thread(Bind(&BTA_GATTC_ReadCharacteristic, conn_id, handle, - auth_req, read_char_cb, nullptr)); + return do_in_jni_thread( + Bind(&BTA_GATTC_ReadCharacteristic, conn_id, handle, auth_req, read_char_cb, nullptr)); } -void read_using_char_uuid_cb(uint16_t conn_id, tGATT_STATUS status, - uint16_t handle, uint16_t len, uint8_t* value, - void* data) { +void read_using_char_uuid_cb(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, uint16_t len, + uint8_t* value, void* data) { btgatt_read_params_t params = { - .handle = handle, - .value.len = len, - .value_type = 0x00, /* GATTC_READ_VALUE_TYPE_VALUE */ - .status = status, + .handle = handle, + .value.len = len, + .value_type = 0x00, /* GATTC_READ_VALUE_TYPE_VALUE */ + .status = status, }; - log::assert_that(len <= GATT_MAX_ATTR_LEN, - "assert failed: len <= GATT_MAX_ATTR_LEN"); - if (len > 0) memcpy(params.value.value, value, len); + log::assert_that(len <= GATT_MAX_ATTR_LEN, "assert failed: len <= GATT_MAX_ATTR_LEN"); + if (len > 0) { + memcpy(params.value.value, value, len); + } CLI_CBACK_IN_JNI(read_characteristic_cb, conn_id, status, params); } -static bt_status_t btif_gattc_read_using_char_uuid(int conn_id, - const Uuid& uuid, - uint16_t s_handle, - uint16_t e_handle, - int auth_req) { +static bt_status_t btif_gattc_read_using_char_uuid(int conn_id, const Uuid& uuid, uint16_t s_handle, + uint16_t e_handle, int auth_req) { CHECK_BTGATT_INIT(); - return do_in_jni_thread(Bind(&BTA_GATTC_ReadUsingCharUuid, conn_id, uuid, - s_handle, e_handle, auth_req, - read_using_char_uuid_cb, nullptr)); + return do_in_jni_thread(Bind(&BTA_GATTC_ReadUsingCharUuid, conn_id, uuid, s_handle, e_handle, + auth_req, read_using_char_uuid_cb, nullptr)); } -void read_desc_cb(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, - uint16_t len, uint8_t* value, void* data) { +void read_desc_cb(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, uint16_t len, + uint8_t* value, void* data) { btgatt_read_params_t params; params.value_type = 0x00 /* GATTC_READ_VALUE_TYPE_VALUE */; params.status = status; params.handle = handle; params.value.len = len; - log::assert_that(len <= GATT_MAX_ATTR_LEN, - "assert failed: len <= GATT_MAX_ATTR_LEN"); - if (len > 0) memcpy(params.value.value, value, len); + log::assert_that(len <= GATT_MAX_ATTR_LEN, "assert failed: len <= GATT_MAX_ATTR_LEN"); + if (len > 0) { + memcpy(params.value.value, value, len); + } CLI_CBACK_IN_JNI(read_descriptor_cb, conn_id, status, params); } -static bt_status_t btif_gattc_read_char_descr(int conn_id, uint16_t handle, - int auth_req) { +static bt_status_t btif_gattc_read_char_descr(int conn_id, uint16_t handle, int auth_req) { CHECK_BTGATT_INIT(); - return do_in_jni_thread(Bind(&BTA_GATTC_ReadCharDescr, conn_id, handle, - auth_req, read_desc_cb, nullptr)); + return do_in_jni_thread( + Bind(&BTA_GATTC_ReadCharDescr, conn_id, handle, auth_req, read_desc_cb, nullptr)); } -void write_char_cb(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, - uint16_t len, const uint8_t* value, void* data) { +void write_char_cb(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, uint16_t len, + const uint8_t* value, void* data) { std::vector val(value, value + len); CLI_CBACK_WRAP_IN_JNI( - write_characteristic_cb, - base::BindOnce( - [](write_characteristic_callback cb, uint16_t conn_id, - tGATT_STATUS status, uint16_t handle, - std::vector moved_value) { - cb(conn_id, status, handle, moved_value.size(), moved_value.data()); - }, - bt_gatt_callbacks->client->write_characteristic_cb, conn_id, status, - handle, std::move(val))); + write_characteristic_cb, + base::BindOnce( + [](write_characteristic_callback cb, uint16_t conn_id, tGATT_STATUS status, + uint16_t handle, std::vector moved_value) { + cb(conn_id, status, handle, moved_value.size(), moved_value.data()); + }, + bt_gatt_callbacks->client->write_characteristic_cb, conn_id, status, handle, + std::move(val))); } -static bt_status_t btif_gattc_write_char(int conn_id, uint16_t handle, - int write_type, int auth_req, +static bt_status_t btif_gattc_write_char(int conn_id, uint16_t handle, int write_type, int auth_req, const uint8_t* val, size_t len) { CHECK_BTGATT_INIT(); std::vector value(val, val + len); - if (value.size() > GATT_MAX_ATTR_LEN) value.resize(GATT_MAX_ATTR_LEN); + if (value.size() > GATT_MAX_ATTR_LEN) { + value.resize(GATT_MAX_ATTR_LEN); + } - return do_in_jni_thread(Bind(&BTA_GATTC_WriteCharValue, conn_id, handle, - write_type, std::move(value), auth_req, - write_char_cb, nullptr)); + return do_in_jni_thread(Bind(&BTA_GATTC_WriteCharValue, conn_id, handle, write_type, + std::move(value), auth_req, write_char_cb, nullptr)); } -void write_descr_cb(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, - uint16_t len, const uint8_t* value, void* data) { +void write_descr_cb(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, uint16_t len, + const uint8_t* value, void* data) { std::vector val(value, value + len); CLI_CBACK_WRAP_IN_JNI( - write_descriptor_cb, - base::BindOnce( - [](write_descriptor_callback cb, uint16_t conn_id, - tGATT_STATUS status, uint16_t handle, - std::vector moved_value) { - cb(conn_id, status, handle, moved_value.size(), moved_value.data()); - }, - bt_gatt_callbacks->client->write_descriptor_cb, conn_id, status, - handle, std::move(val))); -} - -static bt_status_t btif_gattc_write_char_descr(int conn_id, uint16_t handle, - int auth_req, const uint8_t* val, - size_t len) { + write_descriptor_cb, + base::BindOnce( + [](write_descriptor_callback cb, uint16_t conn_id, tGATT_STATUS status, + uint16_t handle, std::vector moved_value) { + cb(conn_id, status, handle, moved_value.size(), moved_value.data()); + }, + bt_gatt_callbacks->client->write_descriptor_cb, conn_id, status, handle, + std::move(val))); +} + +static bt_status_t btif_gattc_write_char_descr(int conn_id, uint16_t handle, int auth_req, + const uint8_t* val, size_t len) { CHECK_BTGATT_INIT(); std::vector value(val, val + len); - if (value.size() > GATT_MAX_ATTR_LEN) value.resize(GATT_MAX_ATTR_LEN); + if (value.size() > GATT_MAX_ATTR_LEN) { + value.resize(GATT_MAX_ATTR_LEN); + } - return do_in_jni_thread(Bind(&BTA_GATTC_WriteCharDescr, conn_id, handle, - std::move(value), auth_req, write_descr_cb, - nullptr)); + return do_in_jni_thread(Bind(&BTA_GATTC_WriteCharDescr, conn_id, handle, std::move(value), + auth_req, write_descr_cb, nullptr)); } static bt_status_t btif_gattc_execute_write(int conn_id, int execute) { CHECK_BTGATT_INIT(); - return do_in_jni_thread( - Bind(&BTA_GATTC_ExecuteWrite, conn_id, (uint8_t)execute)); + return do_in_jni_thread(Bind(&BTA_GATTC_ExecuteWrite, conn_id, (uint8_t)execute)); } -static void btif_gattc_reg_for_notification_impl(tGATT_IF client_if, - const RawAddress& bda, +static void btif_gattc_reg_for_notification_impl(tGATT_IF client_if, const RawAddress& bda, uint16_t handle) { - tGATT_STATUS status = - BTA_GATTC_RegisterForNotifications(client_if, bda, handle); + tGATT_STATUS status = BTA_GATTC_RegisterForNotifications(client_if, bda, handle); // TODO(jpawlowski): conn_id is currently unused HAL_CBACK(bt_gatt_callbacks, client->register_for_notification_cb, /* conn_id */ 0, 1, status, handle); } -bt_status_t btif_gattc_reg_for_notification(int client_if, - const RawAddress& bd_addr, +bt_status_t btif_gattc_reg_for_notification(int client_if, const RawAddress& bd_addr, uint16_t handle) { CHECK_BTGATT_INIT(); - return do_in_jni_thread( - Bind(base::IgnoreResult(&btif_gattc_reg_for_notification_impl), client_if, - bd_addr, handle)); + return do_in_jni_thread(Bind(base::IgnoreResult(&btif_gattc_reg_for_notification_impl), client_if, + bd_addr, handle)); } -static void btif_gattc_dereg_for_notification_impl(tGATT_IF client_if, - const RawAddress& bda, +static void btif_gattc_dereg_for_notification_impl(tGATT_IF client_if, const RawAddress& bda, uint16_t handle) { - tGATT_STATUS status = - BTA_GATTC_DeregisterForNotifications(client_if, bda, handle); + tGATT_STATUS status = BTA_GATTC_DeregisterForNotifications(client_if, bda, handle); // TODO(jpawlowski): conn_id is currently unused HAL_CBACK(bt_gatt_callbacks, client->register_for_notification_cb, /* conn_id */ 0, 0, status, handle); } -bt_status_t btif_gattc_dereg_for_notification(int client_if, - const RawAddress& bd_addr, +bt_status_t btif_gattc_dereg_for_notification(int client_if, const RawAddress& bd_addr, uint16_t handle) { CHECK_BTGATT_INIT(); - return do_in_jni_thread( - Bind(base::IgnoreResult(&btif_gattc_dereg_for_notification_impl), - client_if, bd_addr, handle)); + return do_in_jni_thread(Bind(base::IgnoreResult(&btif_gattc_dereg_for_notification_impl), + client_if, bd_addr, handle)); } -static bt_status_t btif_gattc_read_remote_rssi(int client_if, - const RawAddress& bd_addr) { +static bt_status_t btif_gattc_read_remote_rssi(int client_if, const RawAddress& bd_addr) { CHECK_BTGATT_INIT(); rssi_request_client_if = client_if; - return do_in_jni_thread( - Bind(base::IgnoreResult(&BTM_ReadRSSI), bd_addr, btm_read_rssi_cb)); + return do_in_jni_thread(Bind(base::IgnoreResult(&BTM_ReadRSSI), bd_addr, btm_read_rssi_cb)); } static bt_status_t btif_gattc_configure_mtu(int conn_id, int mtu) { CHECK_BTGATT_INIT(); - return do_in_jni_thread( - Bind(base::IgnoreResult( - static_cast(&BTA_GATTC_ConfigureMTU)), - conn_id, mtu)); -} - -static void btif_gattc_conn_parameter_update_impl( - RawAddress addr, int min_interval, int max_interval, int latency, - int timeout, uint16_t min_ce_len, uint16_t max_ce_len) { - if (BTA_DmGetConnectionState(addr)) - BTA_DmBleUpdateConnectionParams(addr, min_interval, max_interval, latency, - timeout, min_ce_len, max_ce_len); - else - BTA_DmSetBlePrefConnParams(addr, min_interval, max_interval, latency, - timeout); -} - -bt_status_t btif_gattc_conn_parameter_update(const RawAddress& bd_addr, - int min_interval, int max_interval, - int latency, int timeout, - uint16_t min_ce_len, - uint16_t max_ce_len) { - CHECK_BTGATT_INIT(); return do_in_jni_thread(Bind( - base::IgnoreResult(&btif_gattc_conn_parameter_update_impl), bd_addr, - min_interval, max_interval, latency, timeout, min_ce_len, max_ce_len)); + base::IgnoreResult(static_cast(&BTA_GATTC_ConfigureMTU)), + conn_id, mtu)); +} + +static void btif_gattc_conn_parameter_update_impl(RawAddress addr, int min_interval, + int max_interval, int latency, int timeout, + uint16_t min_ce_len, uint16_t max_ce_len) { + if (BTA_DmGetConnectionState(addr)) { + BTA_DmBleUpdateConnectionParams(addr, min_interval, max_interval, latency, timeout, min_ce_len, + max_ce_len); + } else { + BTA_DmSetBlePrefConnParams(addr, min_interval, max_interval, latency, timeout); + } } -static bt_status_t btif_gattc_set_preferred_phy(const RawAddress& bd_addr, - uint8_t tx_phy, uint8_t rx_phy, - uint16_t phy_options) { +bt_status_t btif_gattc_conn_parameter_update(const RawAddress& bd_addr, int min_interval, + int max_interval, int latency, int timeout, + uint16_t min_ce_len, uint16_t max_ce_len) { CHECK_BTGATT_INIT(); - do_in_main_thread(FROM_HERE, - Bind(&BTM_BleSetPhy, bd_addr, tx_phy, rx_phy, phy_options)); + return do_in_jni_thread(Bind(base::IgnoreResult(&btif_gattc_conn_parameter_update_impl), bd_addr, + min_interval, max_interval, latency, timeout, min_ce_len, + max_ce_len)); +} + +static bt_status_t btif_gattc_set_preferred_phy(const RawAddress& bd_addr, uint8_t tx_phy, + uint8_t rx_phy, uint16_t phy_options) { + CHECK_BTGATT_INIT(); + do_in_main_thread(FROM_HERE, Bind(&BTM_BleSetPhy, bd_addr, tx_phy, rx_phy, phy_options)); return BT_STATUS_SUCCESS; } static bt_status_t btif_gattc_read_phy( - const RawAddress& bd_addr, - base::Callback cb) { + const RawAddress& bd_addr, + base::Callback cb) { CHECK_BTGATT_INIT(); - do_in_main_thread(FROM_HERE, - Bind(&BTM_BleReadPhy, bd_addr, jni_thread_wrapper(cb))); + do_in_main_thread(FROM_HERE, Bind(&BTM_BleReadPhy, bd_addr, jni_thread_wrapper(cb))); return BT_STATUS_SUCCESS; } static int btif_gattc_get_device_type(const RawAddress& bd_addr) { int device_type = 0; - if (btif_config_get_int(bd_addr.ToString().c_str(), BTIF_STORAGE_KEY_DEV_TYPE, - &device_type)) + if (btif_config_get_int(bd_addr.ToString().c_str(), BTIF_STORAGE_KEY_DEV_TYPE, &device_type)) { return device_type; + } return 0; } -static bt_status_t btif_gattc_test_command(int command, - const btgatt_test_params_t& params) { +static bt_status_t btif_gattc_test_command(int command, const btgatt_test_params_t& params) { return btif_gattc_test_command_impl(command, ¶ms); } -static void btif_gattc_subrate_request_impl(RawAddress addr, int subrate_min, - int subrate_max, int max_latency, - int cont_num, int sup_timeout) { +static void btif_gattc_subrate_request_impl(RawAddress addr, int subrate_min, int subrate_max, + int max_latency, int cont_num, int sup_timeout) { if (BTA_DmGetConnectionState(addr)) { - BTA_DmBleSubrateRequest(addr, subrate_min, subrate_max, max_latency, - cont_num, sup_timeout); + BTA_DmBleSubrateRequest(addr, subrate_min, subrate_max, max_latency, cont_num, sup_timeout); } } -static bt_status_t btif_gattc_subrate_request(const RawAddress& bd_addr, - int subrate_min, int subrate_max, - int max_latency, int cont_num, +static bt_status_t btif_gattc_subrate_request(const RawAddress& bd_addr, int subrate_min, + int subrate_max, int max_latency, int cont_num, int sup_timeout) { CHECK_BTGATT_INIT(); - return do_in_jni_thread( - Bind(base::IgnoreResult(&btif_gattc_subrate_request_impl), bd_addr, - subrate_min, subrate_max, max_latency, cont_num, sup_timeout)); + return do_in_jni_thread(Bind(base::IgnoreResult(&btif_gattc_subrate_request_impl), bd_addr, + subrate_min, subrate_max, max_latency, cont_num, sup_timeout)); } -static void btif_test_connect_cback(tGATT_IF, const RawAddress&, - uint16_t conn_id, bool connected, +static void btif_test_connect_cback(tGATT_IF, const RawAddress&, uint16_t conn_id, bool connected, tGATT_DISCONN_REASON, tBT_TRANSPORT) { log::info("conn_id={}, connected={}", conn_id, connected); test_cb.conn_id = connected ? conn_id : 0; } static void btif_test_command_complete_cback(uint16_t conn_id, tGATTC_OPTYPE op, - tGATT_STATUS status, - tGATT_CL_COMPLETE* p_data) { - log::info("op_code=0x{:02x}, conn_id=0x{:x}. status=0x{:x}", op, conn_id, - status); + tGATT_STATUS status, tGATT_CL_COMPLETE* p_data) { + log::info("op_code=0x{:02x}, conn_id=0x{:x}. status=0x{:x}", op, conn_id, status); switch (op) { case GATTC_OPTYPE_READ: @@ -718,11 +661,12 @@ static void btif_test_command_complete_cback(uint16_t conn_id, tGATTC_OPTYPE op, break; case GATTC_OPTYPE_INDICATION: - if (GATTC_SendHandleValueConfirm(conn_id, p_data->cid) != GATT_SUCCESS) + if (GATTC_SendHandleValueConfirm(conn_id, p_data->cid) != GATT_SUCCESS) { log::error( - "Unable to send handle value confirmation conn_id:0x{:x} " - "cid:0x{:04x}", - conn_id, p_data->cid); + "Unable to send handle value confirmation conn_id:0x{:x} " + "cid:0x{:04x}", + conn_id, p_data->cid); + } break; default: @@ -731,11 +675,9 @@ static void btif_test_command_complete_cback(uint16_t conn_id, tGATTC_OPTYPE op, } } -static void btif_test_discovery_result_cback(uint16_t /* conn_id */, - tGATT_DISC_TYPE disc_type, +static void btif_test_discovery_result_cback(uint16_t /* conn_id */, tGATT_DISC_TYPE disc_type, tGATT_DISC_RES* p_data) { - log::info("------ GATT Discovery result {:<22s} -------", - disc_name[disc_type]); + log::info("------ GATT Discovery result {:<22s} -------", disc_name[disc_type]); log::info("Attribute handle: 0x{:04x} ({})", p_data->handle, p_data->handle); if (disc_type != GATT_DISC_CHAR_DSCPT) { @@ -747,29 +689,24 @@ static void btif_test_discovery_result_cback(uint16_t /* conn_id */, log::info("Handle range: 0x{:04x} ~ 0x{:04x} ({} ~ {})", p_data->handle, p_data->value.group_value.e_handle, p_data->handle, p_data->value.group_value.e_handle); - log::info("Service UUID: {}", - p_data->value.group_value.service_type.ToString()); + log::info("Service UUID: {}", p_data->value.group_value.service_type.ToString()); break; case GATT_DISC_SRVC_BY_UUID: - log::info("Handle range: 0x{:04x} ~ 0x{:04x} ({} ~ {})", p_data->handle, - p_data->value.handle, p_data->handle, p_data->value.handle); + log::info("Handle range: 0x{:04x} ~ 0x{:04x} ({} ~ {})", p_data->handle, p_data->value.handle, + p_data->handle, p_data->value.handle); break; case GATT_DISC_INC_SRVC: - log::info("Handle range: 0x{:04x} ~ 0x{:04x} ({} ~ {})", - p_data->value.incl_service.s_handle, - p_data->value.incl_service.e_handle, - p_data->value.incl_service.s_handle, + log::info("Handle range: 0x{:04x} ~ 0x{:04x} ({} ~ {})", p_data->value.incl_service.s_handle, + p_data->value.incl_service.e_handle, p_data->value.incl_service.s_handle, p_data->value.incl_service.e_handle); - log::info("Service UUID: {}", - p_data->value.incl_service.service_type.ToString()); + log::info("Service UUID: {}", p_data->value.incl_service.service_type.ToString()); break; case GATT_DISC_CHAR: log::info("Properties: 0x{:02x}", p_data->value.dclr_value.char_prop); - log::info("Characteristic UUID: {}", - p_data->value.dclr_value.char_uuid.ToString()); + log::info("Characteristic UUID: {}", p_data->value.dclr_value.char_uuid.ToString()); break; case GATT_DISC_CHAR_DSCPT: @@ -790,22 +727,21 @@ static void btif_test_discovery_complete_cback(uint16_t /* conn_id */, } static tGATT_CBACK btif_test_callbacks = { - btif_test_connect_cback, - btif_test_command_complete_cback, - btif_test_discovery_result_cback, - btif_test_discovery_complete_cback, - NULL, - NULL, - NULL, - NULL, - NULL, - NULL, + btif_test_connect_cback, + btif_test_command_complete_cback, + btif_test_discovery_result_cback, + btif_test_discovery_complete_cback, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, }; } // namespace -static bt_status_t btif_gattc_test_command_impl( - int command, const btgatt_test_params_t* params) { +static bt_status_t btif_gattc_test_command_impl(int command, const btgatt_test_params_t* params) { switch (command) { case 0x01: /* Enable */ { @@ -813,9 +749,8 @@ static bt_status_t btif_gattc_test_command_impl( if (params->u1) { std::array tmp; tmp.fill(0xAE); - test_cb.gatt_if = - GATT_Register(bluetooth::Uuid::From128BitBE(tmp), - std::string("GattTest"), &btif_test_callbacks, false); + test_cb.gatt_if = GATT_Register(bluetooth::Uuid::From128BitBE(tmp), std::string("GattTest"), + &btif_test_callbacks, false); GATT_StartIf(test_cb.gatt_if); } else { GATT_Deregister(test_cb.gatt_if); @@ -826,15 +761,16 @@ static bt_status_t btif_gattc_test_command_impl( case 0x02: /* Connect */ { - log::info("CONNECT - device={} (dev_type={}, addr_type={})", - *params->bda1, params->u1, params->u2); + log::info("CONNECT - device={} (dev_type={}, addr_type={})", *params->bda1, params->u1, + params->u2); - if (params->u1 == BT_DEVICE_TYPE_BLE) + if (params->u1 == BT_DEVICE_TYPE_BLE) { BTM_SecAddBleDevice(*params->bda1, BT_DEVICE_TYPE_BLE, static_cast(params->u2)); + } - if (!GATT_Connect(test_cb.gatt_if, *params->bda1, - BTM_BLE_DIRECT_CONNECTION, BT_TRANSPORT_LE, false)) { + if (!GATT_Connect(test_cb.gatt_if, *params->bda1, BTM_BLE_DIRECT_CONNECTION, BT_TRANSPORT_LE, + false)) { log::error("GATT_Connect failed!"); } break; @@ -843,8 +779,9 @@ static bt_status_t btif_gattc_test_command_impl( case 0x03: /* Disconnect */ { log::info("DISCONNECT - conn_id={}", test_cb.conn_id); - if (GATT_Disconnect(test_cb.conn_id) != GATT_SUCCESS) + if (GATT_Disconnect(test_cb.conn_id) != GATT_SUCCESS) { log::error("Unable to disconnect"); + } break; } @@ -856,18 +793,18 @@ static bt_status_t btif_gattc_test_command_impl( } log::info("DISCOVER ({}), conn_id={}, uuid={}, handles=0x{:04x}-0x{:04x}", - disc_name[params->u1], test_cb.conn_id, - params->uuid1->ToString(), params->u2, params->u3); - if (GATTC_Discover(test_cb.conn_id, - static_cast(params->u1), params->u2, - params->u3, *params->uuid1) != GATT_SUCCESS) + disc_name[params->u1], test_cb.conn_id, params->uuid1->ToString(), params->u2, + params->u3); + if (GATTC_Discover(test_cb.conn_id, static_cast(params->u1), params->u2, + params->u3, *params->uuid1) != GATT_SUCCESS) { log::error("Unable to discover"); + } break; } case 0xF0: /* Pairing configuration */ - log::info("Setting pairing config auth={}, iocaps={}, keys={}/{}/{}", - params->u1, params->u2, params->u3, params->u4, params->u5); + log::info("Setting pairing config auth={}, iocaps={}, keys={}/{}/{}", params->u1, params->u2, + params->u3, params->u4, params->u5); bte_appl_cfg.ble_auth_req = params->u1; bte_appl_cfg.ble_io_cap = params->u2; @@ -884,28 +821,28 @@ static bt_status_t btif_gattc_test_command_impl( } const btgatt_client_interface_t btgattClientInterface = { - btif_gattc_register_app, - btif_gattc_unregister_app, - btif_gattc_open, - btif_gattc_close, - btif_gattc_refresh, - btif_gattc_search_service, - btif_gattc_discover_service_by_uuid, - btif_gattc_read_char, - btif_gattc_read_using_char_uuid, - btif_gattc_write_char, - btif_gattc_read_char_descr, - btif_gattc_write_char_descr, - btif_gattc_execute_write, - btif_gattc_reg_for_notification, - btif_gattc_dereg_for_notification, - btif_gattc_read_remote_rssi, - btif_gattc_get_device_type, - btif_gattc_configure_mtu, - btif_gattc_conn_parameter_update, - btif_gattc_set_preferred_phy, - btif_gattc_read_phy, - btif_gattc_test_command, - btif_gattc_get_gatt_db, - btif_gattc_subrate_request, + btif_gattc_register_app, + btif_gattc_unregister_app, + btif_gattc_open, + btif_gattc_close, + btif_gattc_refresh, + btif_gattc_search_service, + btif_gattc_discover_service_by_uuid, + btif_gattc_read_char, + btif_gattc_read_using_char_uuid, + btif_gattc_write_char, + btif_gattc_read_char_descr, + btif_gattc_write_char_descr, + btif_gattc_execute_write, + btif_gattc_reg_for_notification, + btif_gattc_dereg_for_notification, + btif_gattc_read_remote_rssi, + btif_gattc_get_device_type, + btif_gattc_configure_mtu, + btif_gattc_conn_parameter_update, + btif_gattc_set_preferred_phy, + btif_gattc_read_phy, + btif_gattc_test_command, + btif_gattc_get_gatt_db, + btif_gattc_subrate_request, }; diff --git a/system/btif/src/btif_gatt_server.cc b/system/btif/src/btif_gatt_server.cc index 092dac90ae0..e5c4394b561 100644 --- a/system/btif/src/btif_gatt_server.cc +++ b/system/btif/src/btif_gatt_server.cc @@ -80,12 +80,13 @@ extern const btgatt_callbacks_t* bt_gatt_callbacks; * Static functions ******************************************************************************/ -static void btapp_gatts_copy_req_data(uint16_t event, char* p_dest, - const char* p_src) { +static void btapp_gatts_copy_req_data(uint16_t event, char* p_dest, const char* p_src) { tBTA_GATTS* p_dest_data = (tBTA_GATTS*)p_dest; const tBTA_GATTS* p_src_data = (const tBTA_GATTS*)p_src; - if (!p_src_data || !p_dest_data) return; + if (!p_src_data || !p_dest_data) { + return; + } // Copy basic structure first maybe_non_aligned_memcpy(p_dest_data, p_src_data, sizeof(*p_src_data)); @@ -98,10 +99,8 @@ static void btapp_gatts_copy_req_data(uint16_t event, char* p_dest, case BTA_GATTS_WRITE_DESCRIPTOR_EVT: case BTA_GATTS_EXEC_WRITE_EVT: case BTA_GATTS_MTU_EVT: - p_dest_data->req_data.p_data = - (tGATTS_DATA*)osi_malloc(sizeof(tGATTS_DATA)); - memcpy(p_dest_data->req_data.p_data, p_src_data->req_data.p_data, - sizeof(tGATTS_DATA)); + p_dest_data->req_data.p_data = (tGATTS_DATA*)osi_malloc(sizeof(tGATTS_DATA)); + memcpy(p_dest_data->req_data.p_data, p_src_data->req_data.p_data, sizeof(tGATTS_DATA)); break; default: @@ -117,7 +116,9 @@ static void btapp_gatts_free_req_data(uint16_t event, tBTA_GATTS* p_data) { case BTA_GATTS_WRITE_DESCRIPTOR_EVT: case BTA_GATTS_EXEC_WRITE_EVT: case BTA_GATTS_MTU_EVT: - if (p_data != NULL) osi_free_and_reset((void**)&p_data->req_data.p_data); + if (p_data != NULL) { + osi_free_and_reset((void**)&p_data->req_data.p_data); + } break; default: @@ -131,9 +132,8 @@ static void btapp_gatts_handle_cback(uint16_t event, char* p_param) { tBTA_GATTS* p_data = (tBTA_GATTS*)p_param; switch (event) { case BTA_GATTS_REG_EVT: { - HAL_CBACK(bt_gatt_callbacks, server->register_server_cb, - p_data->reg_oper.status, p_data->reg_oper.server_if, - p_data->reg_oper.uuid); + HAL_CBACK(bt_gatt_callbacks, server->register_server_cb, p_data->reg_oper.status, + p_data->reg_oper.server_if, p_data->reg_oper.uuid); break; } @@ -141,8 +141,7 @@ static void btapp_gatts_handle_cback(uint16_t event, char* p_param) { break; case BTA_GATTS_CONNECT_EVT: { - btif_gatt_check_encrypted_link(p_data->conn.remote_bda, - p_data->conn.transport); + btif_gatt_check_encrypted_link(p_data->conn.remote_bda, p_data->conn.transport); HAL_CBACK(bt_gatt_callbacks, server->connection_cb, p_data->conn.conn_id, p_data->conn.server_if, true, p_data->conn.remote_bda); @@ -156,33 +155,27 @@ static void btapp_gatts_handle_cback(uint16_t event, char* p_param) { } case BTA_GATTS_STOP_EVT: - HAL_CBACK(bt_gatt_callbacks, server->service_stopped_cb, - p_data->srvc_oper.status, p_data->srvc_oper.server_if, - p_data->srvc_oper.service_id); + HAL_CBACK(bt_gatt_callbacks, server->service_stopped_cb, p_data->srvc_oper.status, + p_data->srvc_oper.server_if, p_data->srvc_oper.service_id); break; case BTA_GATTS_DELETE_EVT: - HAL_CBACK(bt_gatt_callbacks, server->service_deleted_cb, - p_data->srvc_oper.status, p_data->srvc_oper.server_if, - p_data->srvc_oper.service_id); + HAL_CBACK(bt_gatt_callbacks, server->service_deleted_cb, p_data->srvc_oper.status, + p_data->srvc_oper.server_if, p_data->srvc_oper.service_id); break; case BTA_GATTS_READ_CHARACTERISTIC_EVT: { - HAL_CBACK(bt_gatt_callbacks, server->request_read_characteristic_cb, - p_data->req_data.conn_id, p_data->req_data.trans_id, - p_data->req_data.remote_bda, - p_data->req_data.p_data->read_req.handle, - p_data->req_data.p_data->read_req.offset, + HAL_CBACK(bt_gatt_callbacks, server->request_read_characteristic_cb, p_data->req_data.conn_id, + p_data->req_data.trans_id, p_data->req_data.remote_bda, + p_data->req_data.p_data->read_req.handle, p_data->req_data.p_data->read_req.offset, p_data->req_data.p_data->read_req.is_long); break; } case BTA_GATTS_READ_DESCRIPTOR_EVT: { - HAL_CBACK(bt_gatt_callbacks, server->request_read_descriptor_cb, - p_data->req_data.conn_id, p_data->req_data.trans_id, - p_data->req_data.remote_bda, - p_data->req_data.p_data->read_req.handle, - p_data->req_data.p_data->read_req.offset, + HAL_CBACK(bt_gatt_callbacks, server->request_read_descriptor_cb, p_data->req_data.conn_id, + p_data->req_data.trans_id, p_data->req_data.remote_bda, + p_data->req_data.p_data->read_req.handle, p_data->req_data.p_data->read_req.offset, p_data->req_data.p_data->read_req.is_long); break; } @@ -190,42 +183,39 @@ static void btapp_gatts_handle_cback(uint16_t event, char* p_param) { case BTA_GATTS_WRITE_CHARACTERISTIC_EVT: { const auto& req = p_data->req_data.p_data->write_req; HAL_CBACK(bt_gatt_callbacks, server->request_write_characteristic_cb, - p_data->req_data.conn_id, p_data->req_data.trans_id, - p_data->req_data.remote_bda, req.handle, req.offset, - req.need_rsp, req.is_prep, req.value, req.len); + p_data->req_data.conn_id, p_data->req_data.trans_id, p_data->req_data.remote_bda, + req.handle, req.offset, req.need_rsp, req.is_prep, req.value, req.len); break; } case BTA_GATTS_WRITE_DESCRIPTOR_EVT: { const auto& req = p_data->req_data.p_data->write_req; - HAL_CBACK(bt_gatt_callbacks, server->request_write_descriptor_cb, - p_data->req_data.conn_id, p_data->req_data.trans_id, - p_data->req_data.remote_bda, req.handle, req.offset, + HAL_CBACK(bt_gatt_callbacks, server->request_write_descriptor_cb, p_data->req_data.conn_id, + p_data->req_data.trans_id, p_data->req_data.remote_bda, req.handle, req.offset, req.need_rsp, req.is_prep, req.value, req.len); break; } case BTA_GATTS_EXEC_WRITE_EVT: { - HAL_CBACK(bt_gatt_callbacks, server->request_exec_write_cb, - p_data->req_data.conn_id, p_data->req_data.trans_id, - p_data->req_data.remote_bda, + HAL_CBACK(bt_gatt_callbacks, server->request_exec_write_cb, p_data->req_data.conn_id, + p_data->req_data.trans_id, p_data->req_data.remote_bda, p_data->req_data.p_data->exec_write); break; } case BTA_GATTS_CONF_EVT: - HAL_CBACK(bt_gatt_callbacks, server->indication_sent_cb, - p_data->req_data.conn_id, p_data->req_data.status); + HAL_CBACK(bt_gatt_callbacks, server->indication_sent_cb, p_data->req_data.conn_id, + p_data->req_data.status); break; case BTA_GATTS_CONGEST_EVT: - HAL_CBACK(bt_gatt_callbacks, server->congestion_cb, - p_data->congest.conn_id, p_data->congest.congested); + HAL_CBACK(bt_gatt_callbacks, server->congestion_cb, p_data->congest.conn_id, + p_data->congest.congested); break; case BTA_GATTS_MTU_EVT: - HAL_CBACK(bt_gatt_callbacks, server->mtu_changed_cb, - p_data->req_data.conn_id, p_data->req_data.p_data->mtu); + HAL_CBACK(bt_gatt_callbacks, server->mtu_changed_cb, p_data->req_data.conn_id, + p_data->req_data.p_data->mtu); break; case BTA_GATTS_OPEN_EVT: @@ -235,23 +225,21 @@ static void btapp_gatts_handle_cback(uint16_t event, char* p_param) { break; case BTA_GATTS_PHY_UPDATE_EVT: - HAL_CBACK(bt_gatt_callbacks, server->phy_updated_cb, - p_data->phy_update.conn_id, p_data->phy_update.tx_phy, - p_data->phy_update.rx_phy, p_data->phy_update.status); + HAL_CBACK(bt_gatt_callbacks, server->phy_updated_cb, p_data->phy_update.conn_id, + p_data->phy_update.tx_phy, p_data->phy_update.rx_phy, p_data->phy_update.status); break; case BTA_GATTS_CONN_UPDATE_EVT: - HAL_CBACK(bt_gatt_callbacks, server->conn_updated_cb, - p_data->conn_update.conn_id, p_data->conn_update.interval, - p_data->conn_update.latency, p_data->conn_update.timeout, - p_data->conn_update.status); + HAL_CBACK(bt_gatt_callbacks, server->conn_updated_cb, p_data->conn_update.conn_id, + p_data->conn_update.interval, p_data->conn_update.latency, + p_data->conn_update.timeout, p_data->conn_update.status); break; case BTA_GATTS_SUBRATE_CHG_EVT: - HAL_CBACK(bt_gatt_callbacks, server->subrate_chg_cb, - p_data->subrate_chg.conn_id, p_data->subrate_chg.subrate_factor, - p_data->subrate_chg.latency, p_data->subrate_chg.cont_num, - p_data->subrate_chg.timeout, p_data->subrate_chg.status); + HAL_CBACK(bt_gatt_callbacks, server->subrate_chg_cb, p_data->subrate_chg.conn_id, + p_data->subrate_chg.subrate_factor, p_data->subrate_chg.latency, + p_data->subrate_chg.cont_num, p_data->subrate_chg.timeout, + p_data->subrate_chg.status); break; default: @@ -264,21 +252,18 @@ static void btapp_gatts_handle_cback(uint16_t event, char* p_param) { static void btapp_gatts_cback(tBTA_GATTS_EVT event, tBTA_GATTS* p_data) { bt_status_t status; - status = btif_transfer_context(btapp_gatts_handle_cback, (uint16_t)event, - (char*)p_data, sizeof(tBTA_GATTS), - btapp_gatts_copy_req_data); + status = btif_transfer_context(btapp_gatts_handle_cback, (uint16_t)event, (char*)p_data, + sizeof(tBTA_GATTS), btapp_gatts_copy_req_data); ASSERTC(status == BT_STATUS_SUCCESS, "Context transfer failed!", status); } /******************************************************************************* * Server API Functions ******************************************************************************/ -static bt_status_t btif_gatts_register_app(const Uuid& bt_uuid, - bool eatt_support) { +static bt_status_t btif_gatts_register_app(const Uuid& bt_uuid, bool eatt_support) { CHECK_BTGATT_INIT(); - return do_in_jni_thread( - Bind(&BTA_GATTS_AppRegister, bt_uuid, &btapp_gatts_cback, eatt_support)); + return do_in_jni_thread(Bind(&BTA_GATTS_AppRegister, bt_uuid, &btapp_gatts_cback, eatt_support)); } static bt_status_t btif_gatts_unregister_app(int server_if) { @@ -286,15 +271,14 @@ static bt_status_t btif_gatts_unregister_app(int server_if) { return do_in_jni_thread(Bind(&BTA_GATTS_AppDeregister, server_if)); } -static void btif_gatts_open_impl(int server_if, const RawAddress& address, - bool is_direct, int transport_param) { +static void btif_gatts_open_impl(int server_if, const RawAddress& address, bool is_direct, + int transport_param) { // Ensure device is in inquiry database tBLE_ADDR_TYPE addr_type = BLE_ADDR_PUBLIC; int device_type = 0; tBT_TRANSPORT transport = BT_TRANSPORT_LE; - if (btif_get_address_type(address, &addr_type) && - btif_get_device_type(address, &device_type) && + if (btif_get_address_type(address, &addr_type) && btif_get_device_type(address, &device_type) && device_type != BT_DEVICE_TYPE_BREDR) { BTA_DmAddBleDevice(address, addr_type, device_type); } @@ -324,14 +308,11 @@ static void btif_gatts_open_impl(int server_if, const RawAddress& address, // Used instead of btif_gatts_open_impl if the flag // ble_gatt_server_use_address_type_in_connection is enabled. -static void btif_gatts_open_impl_use_address_type(int server_if, - const RawAddress& address, - tBLE_ADDR_TYPE addr_type, - bool is_direct, +static void btif_gatts_open_impl_use_address_type(int server_if, const RawAddress& address, + tBLE_ADDR_TYPE addr_type, bool is_direct, int transport_param) { int device_type = BT_DEVICE_TYPE_UNKNOWN; - if (btif_get_address_type(address, &addr_type) && - btif_get_device_type(address, &device_type) && + if (btif_get_address_type(address, &addr_type) && btif_get_device_type(address, &device_type) && device_type != BT_DEVICE_TYPE_BREDR) { BTA_DmAddBleDevice(address, addr_type, device_type); } @@ -342,78 +323,67 @@ static void btif_gatts_open_impl_use_address_type(int server_if, return; } - tBT_TRANSPORT transport = (device_type == BT_DEVICE_TYPE_BREDR) - ? BT_TRANSPORT_BR_EDR - : BT_TRANSPORT_LE; + tBT_TRANSPORT transport = + (device_type == BT_DEVICE_TYPE_BREDR) ? BT_TRANSPORT_BR_EDR : BT_TRANSPORT_LE; log::info("addr_type:{}, transport:{}", addr_type, transport); BTA_GATTS_Open(server_if, address, addr_type, is_direct, transport); } -static bt_status_t btif_gatts_open(int server_if, const RawAddress& bd_addr, - uint8_t addr_type, bool is_direct, - int transport) { +static bt_status_t btif_gatts_open(int server_if, const RawAddress& bd_addr, uint8_t addr_type, + bool is_direct, int transport) { CHECK_BTGATT_INIT(); - if (com::android::bluetooth::flags:: - ble_gatt_server_use_address_type_in_connection()) { - return do_in_jni_thread(Bind(&btif_gatts_open_impl_use_address_type, - server_if, bd_addr, addr_type, is_direct, - transport)); + if (com::android::bluetooth::flags::ble_gatt_server_use_address_type_in_connection()) { + return do_in_jni_thread(Bind(&btif_gatts_open_impl_use_address_type, server_if, bd_addr, + addr_type, is_direct, transport)); } else { - return do_in_jni_thread( - Bind(&btif_gatts_open_impl, server_if, bd_addr, is_direct, transport)); + return do_in_jni_thread(Bind(&btif_gatts_open_impl, server_if, bd_addr, is_direct, transport)); } } -static void btif_gatts_close_impl(int server_if, const RawAddress& address, - int conn_id) { +static void btif_gatts_close_impl(int server_if, const RawAddress& address, int conn_id) { // Close active connection - if (conn_id != 0) + if (conn_id != 0) { BTA_GATTS_Close(conn_id); - else + } else { BTA_GATTS_CancelOpen(server_if, address, true); + } // Cancel pending background connections BTA_GATTS_CancelOpen(server_if, address, false); } -static bt_status_t btif_gatts_close(int server_if, const RawAddress& bd_addr, - int conn_id) { +static bt_status_t btif_gatts_close(int server_if, const RawAddress& bd_addr, int conn_id) { CHECK_BTGATT_INIT(); - return do_in_jni_thread( - Bind(&btif_gatts_close_impl, server_if, bd_addr, conn_id)); + return do_in_jni_thread(Bind(&btif_gatts_close_impl, server_if, bd_addr, conn_id)); } static void on_service_added_cb(tGATT_STATUS status, int server_if, vector service) { - HAL_CBACK(bt_gatt_callbacks, server->service_added_cb, status, server_if, - service.data(), service.size()); + HAL_CBACK(bt_gatt_callbacks, server->service_added_cb, status, server_if, service.data(), + service.size()); } -static void add_service_impl(int server_if, - vector service) { +static void add_service_impl(int server_if, vector service) { // TODO(jpawlowski): btif should be a pass through layer, and no checks should // be made here. This exception is added only until GATT server code is // refactored, and one can distinguish stack-internal aps from external apps if (service[0].uuid == Uuid::From16Bit(UUID_SERVCLASS_GATT_SERVER) || service[0].uuid == Uuid::From16Bit(UUID_SERVCLASS_GAP_SERVER)) { log::error("Attept to register restricted service"); - HAL_CBACK(bt_gatt_callbacks, server->service_added_cb, - BT_STATUS_AUTH_REJECTED, server_if, service.data(), - service.size()); + HAL_CBACK(bt_gatt_callbacks, server->service_added_cb, BT_STATUS_AUTH_REJECTED, server_if, + service.data(), service.size()); return; } - BTA_GATTS_AddService(server_if, service, - jni_thread_wrapper(base::Bind(&on_service_added_cb))); + BTA_GATTS_AddService(server_if, service, jni_thread_wrapper(base::Bind(&on_service_added_cb))); } -static bt_status_t btif_gatts_add_service(int server_if, - const btgatt_db_element_t* service, +static bt_status_t btif_gatts_add_service(int server_if, const btgatt_db_element_t* service, size_t service_count) { CHECK_BTGATT_INIT(); - return do_in_jni_thread(Bind(&add_service_impl, server_if, - std::vector(service, service + service_count))); + return do_in_jni_thread( + Bind(&add_service_impl, server_if, std::vector(service, service + service_count))); } static bt_status_t btif_gatts_stop_service(int server_if, int service_handle) { @@ -421,22 +391,20 @@ static bt_status_t btif_gatts_stop_service(int server_if, int service_handle) { return do_in_jni_thread(Bind(&BTA_GATTS_StopService, service_handle)); } -static bt_status_t btif_gatts_delete_service(int server_if, - int service_handle) { +static bt_status_t btif_gatts_delete_service(int server_if, int service_handle) { CHECK_BTGATT_INIT(); return do_in_jni_thread(Bind(&BTA_GATTS_DeleteService, service_handle)); } -static bt_status_t btif_gatts_send_indication(int server_if, - int attribute_handle, int conn_id, - int confirm, const uint8_t* value, - size_t length) { +static bt_status_t btif_gatts_send_indication(int server_if, int attribute_handle, int conn_id, + int confirm, const uint8_t* value, size_t length) { CHECK_BTGATT_INIT(); - if (length > GATT_MAX_ATTR_LEN) length = GATT_MAX_ATTR_LEN; + if (length > GATT_MAX_ATTR_LEN) { + length = GATT_MAX_ATTR_LEN; + } - return do_in_jni_thread(Bind(&BTA_GATTS_HandleValueIndication, conn_id, - attribute_handle, + return do_in_jni_thread(Bind(&BTA_GATTS_HandleValueIndication, conn_id, attribute_handle, std::vector(value, value + length), confirm)); // TODO: Might need to send an ACK if handle value indication is // invoked without need for confirmation. @@ -447,43 +415,37 @@ static void btif_gatts_send_response_impl(int conn_id, int trans_id, int status, tGATTS_RSP rsp_struct; btif_to_bta_response(&rsp_struct, &response); - BTA_GATTS_SendRsp(conn_id, trans_id, static_cast(status), - &rsp_struct); + BTA_GATTS_SendRsp(conn_id, trans_id, static_cast(status), &rsp_struct); - HAL_CBACK(bt_gatt_callbacks, server->response_confirmation_cb, 0, - rsp_struct.attr_value.handle); + HAL_CBACK(bt_gatt_callbacks, server->response_confirmation_cb, 0, rsp_struct.attr_value.handle); } -static bt_status_t btif_gatts_send_response(int conn_id, int trans_id, - int status, +static bt_status_t btif_gatts_send_response(int conn_id, int trans_id, int status, const btgatt_response_t& response) { CHECK_BTGATT_INIT(); - return do_in_jni_thread(Bind(&btif_gatts_send_response_impl, conn_id, - trans_id, status, response)); + return do_in_jni_thread( + Bind(&btif_gatts_send_response_impl, conn_id, trans_id, status, response)); } -static bt_status_t btif_gatts_set_preferred_phy(const RawAddress& bd_addr, - uint8_t tx_phy, uint8_t rx_phy, - uint16_t phy_options) { +static bt_status_t btif_gatts_set_preferred_phy(const RawAddress& bd_addr, uint8_t tx_phy, + uint8_t rx_phy, uint16_t phy_options) { CHECK_BTGATT_INIT(); - do_in_main_thread(FROM_HERE, - Bind(&BTM_BleSetPhy, bd_addr, tx_phy, rx_phy, phy_options)); + do_in_main_thread(FROM_HERE, Bind(&BTM_BleSetPhy, bd_addr, tx_phy, rx_phy, phy_options)); return BT_STATUS_SUCCESS; } static bt_status_t btif_gatts_read_phy( - const RawAddress& bd_addr, - base::Callback cb) { + const RawAddress& bd_addr, + base::Callback cb) { CHECK_BTGATT_INIT(); - do_in_main_thread(FROM_HERE, - Bind(&BTM_BleReadPhy, bd_addr, jni_thread_wrapper(cb))); + do_in_main_thread(FROM_HERE, Bind(&BTM_BleReadPhy, bd_addr, jni_thread_wrapper(cb))); return BT_STATUS_SUCCESS; } const btgatt_server_interface_t btgattServerInterface = { - btif_gatts_register_app, btif_gatts_unregister_app, - btif_gatts_open, btif_gatts_close, - btif_gatts_add_service, btif_gatts_stop_service, - btif_gatts_delete_service, btif_gatts_send_indication, - btif_gatts_send_response, btif_gatts_set_preferred_phy, - btif_gatts_read_phy}; + btif_gatts_register_app, btif_gatts_unregister_app, + btif_gatts_open, btif_gatts_close, + btif_gatts_add_service, btif_gatts_stop_service, + btif_gatts_delete_service, btif_gatts_send_indication, + btif_gatts_send_response, btif_gatts_set_preferred_phy, + btif_gatts_read_phy}; diff --git a/system/btif/src/btif_gatt_util.cc b/system/btif/src/btif_gatt_util.cc index e3a33e06f08..cca3d36fb2c 100644 --- a/system/btif/src/btif_gatt_util.cc +++ b/system/btif/src/btif_gatt_util.cc @@ -61,20 +61,17 @@ void btif_to_bta_response(tGATTS_RSP* p_dest, btgatt_response_t* p_src) { ******************************************************************************/ static bool btif_gatt_is_link_encrypted(const RawAddress& bd_addr) { - return BTM_IsEncrypted(bd_addr, BT_TRANSPORT_BR_EDR) || - BTM_IsEncrypted(bd_addr, BT_TRANSPORT_LE); + return BTM_IsEncrypted(bd_addr, BT_TRANSPORT_BR_EDR) || BTM_IsEncrypted(bd_addr, BT_TRANSPORT_LE); } static void btif_gatt_set_encryption_cb(const RawAddress& /* bd_addr */, - tBT_TRANSPORT /* transport */, - tBTA_STATUS result) { + tBT_TRANSPORT /* transport */, tBTA_STATUS result) { if (result != BTA_SUCCESS && result != BTA_BUSY) { log::warn("Encryption failed ({})", result); } } -void btif_gatt_check_encrypted_link(RawAddress bd_addr, - tBT_TRANSPORT transport_link) { +void btif_gatt_check_encrypted_link(RawAddress bd_addr, tBT_TRANSPORT transport_link) { RawAddress raw_local_addr; tBLE_ADDR_TYPE local_addr_type; BTM_ReadConnectionAddr(bd_addr, raw_local_addr, &local_addr_type); @@ -84,20 +81,18 @@ void btif_gatt_check_encrypted_link(RawAddress bd_addr, return; } - static const bool check_encrypted = bluetooth::os::GetSystemPropertyBool( - "bluetooth.gatt.check_encrypted_link.enabled", true); + static const bool check_encrypted = + bluetooth::os::GetSystemPropertyBool("bluetooth.gatt.check_encrypted_link.enabled", true); if (!check_encrypted) { log::debug("Check skipped due to system config"); return; } tBTM_LE_PENC_KEYS key; - if ((btif_storage_get_ble_bonding_key( - bd_addr, BTM_LE_KEY_PENC, (uint8_t*)&key, - sizeof(tBTM_LE_PENC_KEYS)) == BT_STATUS_SUCCESS) && + if ((btif_storage_get_ble_bonding_key(bd_addr, BTM_LE_KEY_PENC, (uint8_t*)&key, + sizeof(tBTM_LE_PENC_KEYS)) == BT_STATUS_SUCCESS) && !btif_gatt_is_link_encrypted(bd_addr)) { log::debug("Checking gatt link peer:{} transport:{}", bd_addr, bt_transport_text(transport_link)); - BTA_DmSetEncryption(bd_addr, transport_link, &btif_gatt_set_encryption_cb, - BTM_BLE_SEC_ENCRYPT); + BTA_DmSetEncryption(bd_addr, transport_link, &btif_gatt_set_encryption_cb, BTM_BLE_SEC_ENCRYPT); } } diff --git a/system/btif/src/btif_has_client.cc b/system/btif/src/btif_has_client.cc index f443e5dd911..9c2570fc72c 100644 --- a/system/btif/src/btif_has_client.cc +++ b/system/btif/src/btif_has_client.cc @@ -53,139 +53,118 @@ class HearingAaccessClientServiceInterfaceImpl : public HasClientInterface, this->callbacks_ = callbacks; do_in_main_thread( - FROM_HERE, Bind(&HasClient::Initialize, this, - jni_thread_wrapper(Bind( - &btif_storage_load_bonded_leaudio_has_devices)))); + FROM_HERE, + Bind(&HasClient::Initialize, this, + jni_thread_wrapper(Bind(&btif_storage_load_bonded_leaudio_has_devices)))); } void Connect(const RawAddress& addr) override { - do_in_main_thread(FROM_HERE, Bind(&HasClient::Connect, - Unretained(HasClient::Get()), addr)); + do_in_main_thread(FROM_HERE, Bind(&HasClient::Connect, Unretained(HasClient::Get()), addr)); - do_in_jni_thread( - Bind(&btif_storage_set_leaudio_has_acceptlist, addr, true)); + do_in_jni_thread(Bind(&btif_storage_set_leaudio_has_acceptlist, addr, true)); } void Disconnect(const RawAddress& addr) override { - do_in_main_thread(FROM_HERE, Bind(&HasClient::Disconnect, - Unretained(HasClient::Get()), addr)); + do_in_main_thread(FROM_HERE, Bind(&HasClient::Disconnect, Unretained(HasClient::Get()), addr)); - do_in_jni_thread( - Bind(&btif_storage_set_leaudio_has_acceptlist, addr, false)); + do_in_jni_thread(Bind(&btif_storage_set_leaudio_has_acceptlist, addr, false)); } void SelectActivePreset(std::variant addr_or_group_id, uint8_t preset_index) override { - do_in_main_thread( - FROM_HERE, - Bind(&HasClient::SelectActivePreset, Unretained(HasClient::Get()), - std::move(addr_or_group_id), preset_index)); + do_in_main_thread(FROM_HERE, Bind(&HasClient::SelectActivePreset, Unretained(HasClient::Get()), + std::move(addr_or_group_id), preset_index)); } - void NextActivePreset( - std::variant addr_or_group_id) override { - do_in_main_thread(FROM_HERE, Bind(&HasClient::NextActivePreset, - Unretained(HasClient::Get()), + void NextActivePreset(std::variant addr_or_group_id) override { + do_in_main_thread(FROM_HERE, Bind(&HasClient::NextActivePreset, Unretained(HasClient::Get()), std::move(addr_or_group_id))); } - void PreviousActivePreset( - std::variant addr_or_group_id) override { + void PreviousActivePreset(std::variant addr_or_group_id) override { do_in_main_thread(FROM_HERE, Bind(&HasClient::PreviousActivePreset, - Unretained(HasClient::Get()), - std::move(addr_or_group_id))); + Unretained(HasClient::Get()), std::move(addr_or_group_id))); } void GetPresetInfo(const RawAddress& addr, uint8_t preset_index) override { - do_in_main_thread( - FROM_HERE, Bind(&HasClient::GetPresetInfo, Unretained(HasClient::Get()), - addr, preset_index)); + do_in_main_thread(FROM_HERE, Bind(&HasClient::GetPresetInfo, Unretained(HasClient::Get()), addr, + preset_index)); } - void SetPresetName(std::variant addr_or_group_id, - uint8_t preset_index, std::string preset_name) override { - do_in_main_thread( - FROM_HERE, Bind(&HasClient::SetPresetName, Unretained(HasClient::Get()), - std::move(addr_or_group_id), preset_index, - std::move(preset_name))); + void SetPresetName(std::variant addr_or_group_id, uint8_t preset_index, + std::string preset_name) override { + do_in_main_thread(FROM_HERE, + Bind(&HasClient::SetPresetName, Unretained(HasClient::Get()), + std::move(addr_or_group_id), preset_index, std::move(preset_name))); } void RemoveDevice(const RawAddress& addr) override { /* RemoveDevice can be called on devices that don't have BAS enabled */ if (HasClient::IsHasClientRunning()) { - do_in_main_thread(FROM_HERE, Bind(&HasClient::Disconnect, - Unretained(HasClient::Get()), addr)); + do_in_main_thread(FROM_HERE, + Bind(&HasClient::Disconnect, Unretained(HasClient::Get()), addr)); } do_in_jni_thread(Bind(&btif_storage_remove_leaudio_has, addr)); } - void Cleanup(void) override { - do_in_main_thread(FROM_HERE, Bind(&HasClient::CleanUp)); - } + void Cleanup(void) override { do_in_main_thread(FROM_HERE, Bind(&HasClient::CleanUp)); } - void OnConnectionState(ConnectionState state, - const RawAddress& addr) override { - do_in_jni_thread(Bind(&HasClientCallbacks::OnConnectionState, - Unretained(callbacks_), state, addr)); + void OnConnectionState(ConnectionState state, const RawAddress& addr) override { + do_in_jni_thread( + Bind(&HasClientCallbacks::OnConnectionState, Unretained(callbacks_), state, addr)); } void OnDeviceAvailable(const RawAddress& addr, uint8_t features) override { - do_in_jni_thread(Bind(&HasClientCallbacks::OnDeviceAvailable, - Unretained(callbacks_), addr, features)); + do_in_jni_thread( + Bind(&HasClientCallbacks::OnDeviceAvailable, Unretained(callbacks_), addr, features)); } void OnFeaturesUpdate(const RawAddress& addr, uint8_t features) override { - do_in_jni_thread(Bind(&HasClientCallbacks::OnFeaturesUpdate, - Unretained(callbacks_), addr, features)); + do_in_jni_thread( + Bind(&HasClientCallbacks::OnFeaturesUpdate, Unretained(callbacks_), addr, features)); } void OnActivePresetSelected(std::variant addr_or_group_id, uint8_t preset_index) override { - do_in_jni_thread(Bind(&HasClientCallbacks::OnActivePresetSelected, - Unretained(callbacks_), std::move(addr_or_group_id), - preset_index)); + do_in_jni_thread(Bind(&HasClientCallbacks::OnActivePresetSelected, Unretained(callbacks_), + std::move(addr_or_group_id), preset_index)); } void OnActivePresetSelectError(std::variant addr_or_group_id, ErrorCode result_code) override { - do_in_jni_thread(Bind(&HasClientCallbacks::OnActivePresetSelectError, - Unretained(callbacks_), std::move(addr_or_group_id), - result_code)); + do_in_jni_thread(Bind(&HasClientCallbacks::OnActivePresetSelectError, Unretained(callbacks_), + std::move(addr_or_group_id), result_code)); } - void OnPresetInfo(std::variant addr_or_group_id, - PresetInfoReason change_id, + void OnPresetInfo(std::variant addr_or_group_id, PresetInfoReason change_id, std::vector detail_records) override { - do_in_jni_thread(Bind(&HasClientCallbacks::OnPresetInfo, - Unretained(callbacks_), std::move(addr_or_group_id), - change_id, std::move(detail_records))); + do_in_jni_thread(Bind(&HasClientCallbacks::OnPresetInfo, Unretained(callbacks_), + std::move(addr_or_group_id), change_id, std::move(detail_records))); } - void OnPresetInfoError(std::variant addr_or_group_id, - uint8_t preset_index, ErrorCode result_code) override { - do_in_jni_thread(Bind(&HasClientCallbacks::OnPresetInfoError, - Unretained(callbacks_), std::move(addr_or_group_id), - preset_index, result_code)); + void OnPresetInfoError(std::variant addr_or_group_id, uint8_t preset_index, + ErrorCode result_code) override { + do_in_jni_thread(Bind(&HasClientCallbacks::OnPresetInfoError, Unretained(callbacks_), + std::move(addr_or_group_id), preset_index, result_code)); } - void OnSetPresetNameError(std::variant addr_or_group_id, - uint8_t preset_index, + void OnSetPresetNameError(std::variant addr_or_group_id, uint8_t preset_index, ErrorCode result_code) override { - do_in_jni_thread(Bind(&HasClientCallbacks::OnSetPresetNameError, - Unretained(callbacks_), std::move(addr_or_group_id), - preset_index, result_code)); + do_in_jni_thread(Bind(&HasClientCallbacks::OnSetPresetNameError, Unretained(callbacks_), + std::move(addr_or_group_id), preset_index, result_code)); } - private: +private: HasClientCallbacks* callbacks_; }; } /* namespace */ HasClientInterface* btif_has_client_get_interface(void) { - if (!has_client_instance) + if (!has_client_instance) { has_client_instance.reset(new HearingAaccessClientServiceInterfaceImpl()); + } return has_client_instance.get(); } diff --git a/system/btif/src/btif_hd.cc b/system/btif/src/btif_hd.cc index 1586835c55c..fa353f87df2 100644 --- a/system/btif/src/btif_hd.cc +++ b/system/btif/src/btif_hd.cc @@ -77,9 +77,13 @@ static void intr_data_copy_cb(uint16_t event, char* p_dst, const char* p_src) { tBTA_HD_INTR_DATA* p_src_data = (tBTA_HD_INTR_DATA*)p_src; uint8_t* p_data; - if (!p_src) return; + if (!p_src) { + return; + } - if (event != BTA_HD_INTR_DATA_EVT) return; + if (event != BTA_HD_INTR_DATA_EVT) { + return; + } memcpy(p_dst, p_src, sizeof(tBTA_HD_INTR_DATA)); @@ -95,9 +99,13 @@ static void set_report_copy_cb(uint16_t event, char* p_dst, const char* p_src) { tBTA_HD_SET_REPORT* p_src_data = (tBTA_HD_SET_REPORT*)p_src; uint8_t* p_data; - if (!p_src) return; + if (!p_src) { + return; + } - if (event != BTA_HD_SET_REPORT_EVT) return; + if (event != BTA_HD_SET_REPORT_EVT) { + return; + } memcpy(p_dst, p_src, sizeof(tBTA_HD_SET_REPORT)); @@ -109,10 +117,18 @@ static void set_report_copy_cb(uint16_t event, char* p_dst, const char* p_src) { } static void btif_hd_free_buf() { - if (app_info.descriptor.dsc_list) osi_free(app_info.descriptor.dsc_list); - if (app_info.p_description) osi_free(app_info.p_description); - if (app_info.p_name) osi_free(app_info.p_name); - if (app_info.p_provider) osi_free(app_info.p_provider); + if (app_info.descriptor.dsc_list) { + osi_free(app_info.descriptor.dsc_list); + } + if (app_info.p_description) { + osi_free(app_info.p_description); + } + if (app_info.p_name) { + osi_free(app_info.p_name); + } + if (app_info.p_provider) { + osi_free(app_info.p_provider); + } app_info.descriptor.dsc_list = NULL; app_info.p_description = NULL; app_info.p_name = NULL; @@ -174,10 +190,11 @@ static void btif_hd_upstreams_evt(uint16_t event, char* p_param) { btif_hd_cb.service_dereg_active = FALSE; } btif_hd_free_buf(); - if (p_data->status == BTA_HD_OK) + if (p_data->status == BTA_HD_OK) { memset(&btif_hd_cb, 0, sizeof(btif_hd_cb)); - else + } else { log::warn("Failed to disable BT-HD, status={}", p_data->status); + } break; case BTA_HD_REGISTER_APP_EVT: { @@ -189,14 +206,12 @@ static void btif_hd_upstreams_evt(uint16_t event, char* p_param) { log::info("Registering HID device app"); btif_hd_cb.app_registered = TRUE; - HAL_CBACK(bt_hd_callbacks, application_state_cb, addr, - BTHD_APP_STATE_REGISTERED); + HAL_CBACK(bt_hd_callbacks, application_state_cb, addr, BTHD_APP_STATE_REGISTERED); } break; case BTA_HD_UNREGISTER_APP_EVT: btif_hd_cb.app_registered = FALSE; - HAL_CBACK(bt_hd_callbacks, application_state_cb, NULL, - BTHD_APP_STATE_NOT_REGISTERED); + HAL_CBACK(bt_hd_callbacks, application_state_cb, NULL, BTHD_APP_STATE_NOT_REGISTERED); if (btif_hd_cb.service_dereg_active) { log::warn("disabling hid device service now"); BTA_HdDisable(); @@ -216,8 +231,8 @@ static void btif_hd_upstreams_evt(uint16_t event, char* p_param) { } btif_storage_set_hidd(p_data->conn.bda); - HAL_CBACK(bt_hd_callbacks, connection_state_cb, - (RawAddress*)&p_data->conn.bda, BTHD_CONN_STATE_CONNECTED); + HAL_CBACK(bt_hd_callbacks, connection_state_cb, (RawAddress*)&p_data->conn.bda, + BTHD_CONN_STATE_CONNECTED); } break; case BTA_HD_CLOSE_EVT: @@ -228,8 +243,8 @@ static void btif_hd_upstreams_evt(uint16_t event, char* p_param) { btif_hd_cb.forced_disc = FALSE; break; } - HAL_CBACK(bt_hd_callbacks, connection_state_cb, - (RawAddress*)&p_data->conn.bda, BTHD_CONN_STATE_DISCONNECTED); + HAL_CBACK(bt_hd_callbacks, connection_state_cb, (RawAddress*)&p_data->conn.bda, + BTHD_CONN_STATE_DISCONNECTED); break; case BTA_HD_GET_REPORT_EVT: @@ -239,8 +254,7 @@ static void btif_hd_upstreams_evt(uint16_t event, char* p_param) { case BTA_HD_SET_REPORT_EVT: HAL_CBACK(bt_hd_callbacks, set_report_cb, p_data->set_report.report_type, - p_data->set_report.report_id, p_data->set_report.len, - p_data->set_report.p_data); + p_data->set_report.report_id, p_data->set_report.len, p_data->set_report.p_data); break; case BTA_HD_SET_PROTOCOL_EVT: @@ -248,13 +262,13 @@ static void btif_hd_upstreams_evt(uint16_t event, char* p_param) { break; case BTA_HD_INTR_DATA_EVT: - HAL_CBACK(bt_hd_callbacks, intr_data_cb, p_data->intr_data.report_id, - p_data->intr_data.len, p_data->intr_data.p_data); + HAL_CBACK(bt_hd_callbacks, intr_data_cb, p_data->intr_data.report_id, p_data->intr_data.len, + p_data->intr_data.p_data); break; case BTA_HD_VC_UNPLUG_EVT: - HAL_CBACK(bt_hd_callbacks, connection_state_cb, - (RawAddress*)&p_data->conn.bda, BTHD_CONN_STATE_DISCONNECTED); + HAL_CBACK(bt_hd_callbacks, connection_state_cb, (RawAddress*)&p_data->conn.bda, + BTHD_CONN_STATE_DISCONNECTED); if (bta_dm_check_if_only_hd_connected(p_data->conn.bda)) { log::verbose("Removing bonding as only HID profile connected"); BTA_DmRemoveDevice(p_data->conn.bda); @@ -267,8 +281,7 @@ static void btif_hd_upstreams_evt(uint16_t event, char* p_param) { break; case BTA_HD_CONN_STATE_EVT: - HAL_CBACK(bt_hd_callbacks, connection_state_cb, - (RawAddress*)&p_data->conn.bda, + HAL_CBACK(bt_hd_callbacks, connection_state_cb, (RawAddress*)&p_data->conn.bda, (bthd_connection_state_t)p_data->conn.status); break; @@ -332,8 +345,8 @@ static void bte_hd_evt(tBTA_HD_EVT event, tBTA_HD* p_data) { break; } - status = btif_transfer_context(btif_hd_upstreams_evt, (uint16_t)event, - (char*)p_data, param_len, p_copy_cback); + status = btif_transfer_context(btif_hd_upstreams_evt, (uint16_t)event, (char*)p_data, param_len, + p_copy_cback); ASSERTC(status == BT_STATUS_SUCCESS, "context transfer failed", status); } @@ -387,8 +400,7 @@ static void cleanup(void) { * Returns bt_status_t * ******************************************************************************/ -static bt_status_t register_app(bthd_app_param_t* p_app_param, - bthd_qos_param_t* p_in_qos, +static bt_status_t register_app(bthd_app_param_t* p_app_param, bthd_qos_param_t* p_in_qos, bthd_qos_param_t* p_out_qos) { log::verbose(""); @@ -400,16 +412,13 @@ static bt_status_t register_app(bthd_app_param_t* p_app_param, app_info.p_name = (char*)osi_calloc(BTIF_HD_APP_NAME_LEN); strlcpy(app_info.p_name, p_app_param->name, BTIF_HD_APP_NAME_LEN); app_info.p_description = (char*)osi_calloc(BTIF_HD_APP_DESCRIPTION_LEN); - strlcpy(app_info.p_description, p_app_param->description, - BTIF_HD_APP_DESCRIPTION_LEN); + strlcpy(app_info.p_description, p_app_param->description, BTIF_HD_APP_DESCRIPTION_LEN); app_info.p_provider = (char*)osi_calloc(BTIF_HD_APP_PROVIDER_LEN); strlcpy(app_info.p_provider, p_app_param->provider, BTIF_HD_APP_PROVIDER_LEN); app_info.subclass = p_app_param->subclass; app_info.descriptor.dl_len = p_app_param->desc_list_len; - app_info.descriptor.dsc_list = - (uint8_t*)osi_malloc(app_info.descriptor.dl_len); - memcpy(app_info.descriptor.dsc_list, p_app_param->desc_list, - p_app_param->desc_list_len); + app_info.descriptor.dsc_list = (uint8_t*)osi_malloc(app_info.descriptor.dl_len); + memcpy(app_info.descriptor.dsc_list, p_app_param->desc_list, p_app_param->desc_list_len); in_qos.service_type = p_in_qos->service_type; in_qos.token_rate = p_in_qos->token_rate; @@ -528,8 +537,7 @@ static bt_status_t disconnect(void) { * Returns bt_status_t * ******************************************************************************/ -static bt_status_t send_report(bthd_report_type_t type, uint8_t id, - uint16_t len, uint8_t* p_data) { +static bt_status_t send_report(bthd_report_type_t type, uint8_t id, uint16_t len, uint8_t* p_data) { tBTA_HD_REPORT report; log::verbose("type={} id={} len={}", type, id, len); @@ -616,16 +624,16 @@ static bt_status_t virtual_cable_unplug(void) { } static const bthd_interface_t bthdInterface = { - sizeof(bthdInterface), - init, - cleanup, - register_app, - unregister_app, - connect, - disconnect, - send_report, - report_error, - virtual_cable_unplug, + sizeof(bthdInterface), + init, + cleanup, + register_app, + unregister_app, + connect, + disconnect, + send_report, + report_error, + virtual_cable_unplug, }; /******************************************************************************* @@ -640,7 +648,9 @@ static const bthd_interface_t bthdInterface = { bt_status_t btif_hd_execute_service(bool b_enable) { log::verbose("b_enable={}", b_enable); - if (!b_enable) BTA_HdDisable(); + if (!b_enable) { + BTA_HdDisable(); + } return BT_STATUS_SUCCESS; } diff --git a/system/btif/src/btif_hearing_aid.cc b/system/btif/src/btif_hearing_aid.cc index 3ab2e4a91a3..72b5aaed375 100644 --- a/system/btif/src/btif_hearing_aid.cc +++ b/system/btif/src/btif_hearing_aid.cc @@ -38,38 +38,33 @@ using bluetooth::hearing_aid::HearingAidInterface; // template specialization template <> base::Callback jni_thread_wrapper(base::Callback cb) { - return base::Bind([](base::Callback cb) { do_in_jni_thread(cb); }, - std::move(cb)); + return base::Bind([](base::Callback cb) { do_in_jni_thread(cb); }, std::move(cb)); } namespace { class HearingAidInterfaceImpl; std::unique_ptr hearingAidInstance; -class HearingAidInterfaceImpl - : public bluetooth::hearing_aid::HearingAidInterface, - public HearingAidCallbacks { +class HearingAidInterfaceImpl : public bluetooth::hearing_aid::HearingAidInterface, + public HearingAidCallbacks { ~HearingAidInterfaceImpl() override = default; void Init(HearingAidCallbacks* callbacks) override { this->callbacks = callbacks; - do_in_main_thread( - FROM_HERE, - Bind(&HearingAid::Initialize, this, - jni_thread_wrapper(Bind(&btif_storage_load_bonded_hearing_aids)))); + do_in_main_thread(FROM_HERE, + Bind(&HearingAid::Initialize, this, + jni_thread_wrapper(Bind(&btif_storage_load_bonded_hearing_aids)))); } - void OnConnectionState(ConnectionState state, - const RawAddress& address) override { - do_in_jni_thread(Bind(&HearingAidCallbacks::OnConnectionState, - Unretained(callbacks), state, address)); + void OnConnectionState(ConnectionState state, const RawAddress& address) override { + do_in_jni_thread( + Bind(&HearingAidCallbacks::OnConnectionState, Unretained(callbacks), state, address)); } void OnDeviceAvailable(uint8_t capabilities, uint64_t hiSyncId, const RawAddress& address) override { - do_in_jni_thread(Bind(&HearingAidCallbacks::OnDeviceAvailable, - Unretained(callbacks), capabilities, hiSyncId, - address)); + do_in_jni_thread(Bind(&HearingAidCallbacks::OnDeviceAvailable, Unretained(callbacks), + capabilities, hiSyncId, address)); } void Connect(const RawAddress& address) override { @@ -78,14 +73,12 @@ class HearingAidInterfaceImpl void Disconnect(const RawAddress& address) override { do_in_main_thread(FROM_HERE, Bind(&HearingAid::Disconnect, address)); - do_in_jni_thread( - Bind(&btif_storage_set_hearing_aid_acceptlist, address, false)); + do_in_jni_thread(Bind(&btif_storage_set_hearing_aid_acceptlist, address, false)); } void AddToAcceptlist(const RawAddress& address) override { do_in_main_thread(FROM_HERE, Bind(&HearingAid::AddToAcceptlist, address)); - do_in_jni_thread( - Bind(&btif_storage_set_hearing_aid_acceptlist, address, true)); + do_in_jni_thread(Bind(&btif_storage_set_hearing_aid_acceptlist, address, true)); } void SetVolume(int8_t volume) override { @@ -101,19 +94,18 @@ class HearingAidInterfaceImpl do_in_jni_thread(Bind(&btif_storage_remove_hearing_aid, address)); } - void Cleanup(void) override { - do_in_main_thread(FROM_HERE, Bind(&HearingAid::CleanUp)); - } + void Cleanup(void) override { do_in_main_thread(FROM_HERE, Bind(&HearingAid::CleanUp)); } - private: +private: HearingAidCallbacks* callbacks; }; } // namespace HearingAidInterface* btif_hearing_aid_get_interface() { - if (!hearingAidInstance) + if (!hearingAidInstance) { hearingAidInstance.reset(new HearingAidInterfaceImpl()); + } return hearingAidInstance.get(); } diff --git a/system/btif/src/btif_hf.cc b/system/btif/src/btif_hf.cc index d3981255d39..35408361844 100644 --- a/system/btif/src/btif_hf.cc +++ b/system/btif/src/btif_hf.cc @@ -151,15 +151,14 @@ static tBTA_SERVICE_MASK get_BTIF_HF_SERVICES() { /* HF features supported at runtime */ static uint32_t get_hf_features() { #if TARGET_FLOSS -#define DEFAULT_BTIF_HF_FEATURES \ - (BTA_AG_FEAT_ECS | BTA_AG_FEAT_CODEC | BTA_AG_FEAT_UNAT | \ - BTA_AG_FEAT_HF_IND | BTA_AG_FEAT_ESCO_S4 | BTA_AG_FEAT_NOSCO) +#define DEFAULT_BTIF_HF_FEATURES \ + (BTA_AG_FEAT_ECS | BTA_AG_FEAT_CODEC | BTA_AG_FEAT_UNAT | BTA_AG_FEAT_HF_IND | \ + BTA_AG_FEAT_ESCO_S4 | BTA_AG_FEAT_NOSCO) #else -#define DEFAULT_BTIF_HF_FEATURES \ - (BTA_AG_FEAT_3WAY | BTA_AG_FEAT_ECNR | BTA_AG_FEAT_REJECT | \ - BTA_AG_FEAT_ECS | BTA_AG_FEAT_EXTERR | BTA_AG_FEAT_VREC | \ - BTA_AG_FEAT_CODEC | BTA_AG_FEAT_HF_IND | BTA_AG_FEAT_ESCO_S4 | \ - BTA_AG_FEAT_UNAT) +#define DEFAULT_BTIF_HF_FEATURES \ + (BTA_AG_FEAT_3WAY | BTA_AG_FEAT_ECNR | BTA_AG_FEAT_REJECT | BTA_AG_FEAT_ECS | \ + BTA_AG_FEAT_EXTERR | BTA_AG_FEAT_VREC | BTA_AG_FEAT_CODEC | BTA_AG_FEAT_HF_IND | \ + BTA_AG_FEAT_ESCO_S4 | BTA_AG_FEAT_UNAT) #endif return android::sysprop::bluetooth::Hfp::hf_features().value_or(DEFAULT_BTIF_HF_FEATURES); @@ -180,8 +179,9 @@ static bool is_connected(RawAddress* bd_addr) { for (int i = 0; i < btif_max_hf_clients; ++i) { if (((btif_hf_cb[i].state == BTHF_CONNECTION_STATE_CONNECTED) || (btif_hf_cb[i].state == BTHF_CONNECTION_STATE_SLC_CONNECTED)) && - (!bd_addr || *bd_addr == btif_hf_cb[i].connected_bda)) + (!bd_addr || *bd_addr == btif_hf_cb[i].connected_bda)) { return true; + } } return false; } @@ -197,7 +197,9 @@ static bool is_connected(RawAddress* bd_addr) { ******************************************************************************/ static int btif_hf_idx_by_bdaddr(RawAddress* bd_addr) { for (int i = 0; i < btif_max_hf_clients; ++i) { - if (*bd_addr == btif_hf_cb[i].connected_bda) return i; + if (*bd_addr == btif_hf_cb[i].connected_bda) { + return i; + } } return BTIF_HF_INVALID_IDX; } @@ -251,8 +253,8 @@ static void send_at_result(uint8_t ok_flag, uint16_t errcode, int idx) { * Returns void * ******************************************************************************/ -static void send_indicator_update(const btif_hf_cb_t& control_block, - uint16_t indicator, uint16_t value) { +static void send_indicator_update(const btif_hf_cb_t& control_block, uint16_t indicator, + uint16_t value) { tBTA_AG_RES_DATA ag_res = {}; ag_res.ind.id = indicator; ag_res.ind.value = value; @@ -349,50 +351,43 @@ static void btif_hf_upstreams_evt(uint16_t event, char* p_param) { // for the same device. if (p_data->open.bd_addr == btif_hf_cb[idx].connected_bda) { log::warn( - "btif_hf_cb state[{}] is not expected, possible connection " - "collision, ignoring AG open failure event for the same device " - "{}", - p_data->open.status, p_data->open.bd_addr); + "btif_hf_cb state[{}] is not expected, possible connection " + "collision, ignoring AG open failure event for the same device " + "{}", + p_data->open.status, p_data->open.bd_addr); } else { log::warn( - "btif_hf_cb state[{}] is not expected, possible connection " - "collision, ignoring AG open failure event for the different " - "devices btif_hf_cb bda: {}, p_data bda: {}, report disconnect " - "state for p_data bda.", - p_data->open.status, btif_hf_cb[idx].connected_bda, - p_data->open.bd_addr); - bt_hf_callbacks->ConnectionStateCallback( - BTHF_CONNECTION_STATE_DISCONNECTED, &(p_data->open.bd_addr)); + "btif_hf_cb state[{}] is not expected, possible connection " + "collision, ignoring AG open failure event for the different " + "devices btif_hf_cb bda: {}, p_data bda: {}, report disconnect " + "state for p_data bda.", + p_data->open.status, btif_hf_cb[idx].connected_bda, p_data->open.bd_addr); + bt_hf_callbacks->ConnectionStateCallback(BTHF_CONNECTION_STATE_DISCONNECTED, + &(p_data->open.bd_addr)); log_counter_metrics_btif( - android::bluetooth::CodePathCounterKeyEnum:: - HFP_COLLISON_AT_AG_OPEN, - 1); + android::bluetooth::CodePathCounterKeyEnum::HFP_COLLISON_AT_AG_OPEN, 1); } break; } // There is an outgoing connection. // Check the outgoing connection state and address. - log::assert_that( - btif_hf_cb[idx].state == BTHF_CONNECTION_STATE_CONNECTING, - "Control block must be in connecting state when initiating"); - log::assert_that( - !btif_hf_cb[idx].connected_bda.IsEmpty(), - "Remote device address must not be empty when initiating"); + log::assert_that(btif_hf_cb[idx].state == BTHF_CONNECTION_STATE_CONNECTING, + "Control block must be in connecting state when initiating"); + log::assert_that(!btif_hf_cb[idx].connected_bda.IsEmpty(), + "Remote device address must not be empty when initiating"); // Check if the incoming open event and the outgoing connection are // for the same device. if (btif_hf_cb[idx].connected_bda != p_data->open.bd_addr) { log::warn( - "possible connection collision, ignore the outgoing connection " - "for the different devices btif_hf_cb bda: {}, p_data bda: {}, " - "report disconnect state for btif_hf_cb bda.", - btif_hf_cb[idx].connected_bda, p_data->open.bd_addr); - bt_hf_callbacks->ConnectionStateCallback( - BTHF_CONNECTION_STATE_DISCONNECTED, - &(btif_hf_cb[idx].connected_bda)); - log_counter_metrics_btif(android::bluetooth::CodePathCounterKeyEnum:: - HFP_COLLISON_AT_CONNECTING, - 1); + "possible connection collision, ignore the outgoing connection " + "for the different devices btif_hf_cb bda: {}, p_data bda: {}, " + "report disconnect state for btif_hf_cb bda.", + btif_hf_cb[idx].connected_bda, p_data->open.bd_addr); + bt_hf_callbacks->ConnectionStateCallback(BTHF_CONNECTION_STATE_DISCONNECTED, + &(btif_hf_cb[idx].connected_bda)); + log_counter_metrics_btif( + android::bluetooth::CodePathCounterKeyEnum::HFP_COLLISON_AT_CONNECTING, 1); reset_control_block(&btif_hf_cb[idx]); btif_queue_advance(); } @@ -403,8 +398,7 @@ static void btif_hf_upstreams_evt(uint16_t event, char* p_param) { // In case this is an incoming connection btif_hf_cb[idx].connected_bda = p_data->open.bd_addr; if (btif_hf_cb[idx].state != BTHF_CONNECTION_STATE_CONNECTING) { - DEVICE_IOT_CONFIG_ADDR_SET_INT(btif_hf_cb[idx].connected_bda, - IOT_CONF_KEY_HFP_ROLE, + DEVICE_IOT_CONFIG_ADDR_SET_INT(btif_hf_cb[idx].connected_bda, IOT_CONF_KEY_HFP_ROLE, IOT_CONF_VAL_HFP_ROLE_CLIENT); DEVICE_IOT_CONFIG_ADDR_INT_ADD_ONE(btif_hf_cb[idx].connected_bda, IOT_CONF_KEY_HFP_SLC_CONN_COUNT); @@ -413,94 +407,84 @@ static void btif_hf_upstreams_evt(uint16_t event, char* p_param) { btif_hf_cb[idx].state = BTHF_CONNECTION_STATE_CONNECTED; btif_hf_cb[idx].peer_feat = 0; clear_phone_state_multihf(&btif_hf_cb[idx]); - bluetooth::common::BluetoothMetricsLogger::GetInstance() - ->LogHeadsetProfileRfcConnection(p_data->open.service_id); - bt_hf_callbacks->ConnectionStateCallback( - btif_hf_cb[idx].state, &btif_hf_cb[idx].connected_bda); + bluetooth::common::BluetoothMetricsLogger::GetInstance()->LogHeadsetProfileRfcConnection( + p_data->open.service_id); + bt_hf_callbacks->ConnectionStateCallback(btif_hf_cb[idx].state, + &btif_hf_cb[idx].connected_bda); } else { if (!btif_hf_cb[idx].is_initiator) { // Ignore remote initiated open failures - log::warn("Unexpected AG open failure {} for {} is ignored", - p_data->open.status, p_data->open.bd_addr); + log::warn("Unexpected AG open failure {} for {} is ignored", p_data->open.status, + p_data->open.bd_addr); break; } - log::error("self initiated AG open failed for {}, status {}", - btif_hf_cb[idx].connected_bda, p_data->open.status); + log::error("self initiated AG open failed for {}, status {}", btif_hf_cb[idx].connected_bda, + p_data->open.status); RawAddress connected_bda = btif_hf_cb[idx].connected_bda; reset_control_block(&btif_hf_cb[idx]); - if (com::android::bluetooth::flags:: - ignore_notify_when_already_connected()) { + if (com::android::bluetooth::flags::ignore_notify_when_already_connected()) { bool notify_required = true; for (int i = 0; i < BTA_AG_MAX_NUM_CLIENTS; i++) { - if ((i != idx) && - (BTHF_CONNECTION_STATE_CONNECTED == btif_hf_cb[i].state) && + if ((i != idx) && (BTHF_CONNECTION_STATE_CONNECTED == btif_hf_cb[i].state) && (connected_bda == btif_hf_cb[i].connected_bda)) { // There is already an active cnnection on this device // skip upper layer notification notify_required = false; - log::info("AG open failure for {} is ignored because there's an " - "active connection on the same device", connected_bda); + log::info( + "AG open failure for {} is ignored because there's an " + "active connection on the same device", + connected_bda); break; } } if (notify_required) { - bt_hf_callbacks->ConnectionStateCallback(btif_hf_cb[idx].state, - &connected_bda); + bt_hf_callbacks->ConnectionStateCallback(btif_hf_cb[idx].state, &connected_bda); } } else { - bt_hf_callbacks->ConnectionStateCallback(btif_hf_cb[idx].state, - &connected_bda); + bt_hf_callbacks->ConnectionStateCallback(btif_hf_cb[idx].state, &connected_bda); } - log_counter_metrics_btif(android::bluetooth::CodePathCounterKeyEnum:: - HFP_SELF_INITIATED_AG_FAILED, - 1); + log_counter_metrics_btif( + android::bluetooth::CodePathCounterKeyEnum::HFP_SELF_INITIATED_AG_FAILED, 1); btif_queue_advance(); - DEVICE_IOT_CONFIG_ADDR_INT_ADD_ONE( - connected_bda, IOT_CONF_KEY_HFP_SLC_CONN_FAIL_COUNT); + DEVICE_IOT_CONFIG_ADDR_INT_ADD_ONE(connected_bda, IOT_CONF_KEY_HFP_SLC_CONN_FAIL_COUNT); } break; case BTA_AG_CLOSE_EVT: { log::debug( - "SLC and RFCOMM both disconnected event:{} idx:{} " - "btif_hf_cb.handle:{}", - dump_hf_event(event), idx, btif_hf_cb[idx].handle); + "SLC and RFCOMM both disconnected event:{} idx:{} " + "btif_hf_cb.handle:{}", + dump_hf_event(event), idx, btif_hf_cb[idx].handle); RawAddress connected_bda = btif_hf_cb[idx].connected_bda; - bt_hf_callbacks->ConnectionStateCallback( - BTHF_CONNECTION_STATE_DISCONNECTING, &connected_bda); + bt_hf_callbacks->ConnectionStateCallback(BTHF_CONNECTION_STATE_DISCONNECTING, &connected_bda); // If AG_OPEN was received but SLC was not connected in time, then // AG_CLOSE may be received. We need to advance the queue here. - bool failed_to_setup_slc = - (btif_hf_cb[idx].state != BTHF_CONNECTION_STATE_SLC_CONNECTED) && - btif_hf_cb[idx].is_initiator; + bool failed_to_setup_slc = (btif_hf_cb[idx].state != BTHF_CONNECTION_STATE_SLC_CONNECTED) && + btif_hf_cb[idx].is_initiator; reset_control_block(&btif_hf_cb[idx]); - bt_hf_callbacks->ConnectionStateCallback(btif_hf_cb[idx].state, - &connected_bda); + bt_hf_callbacks->ConnectionStateCallback(btif_hf_cb[idx].state, &connected_bda); if (failed_to_setup_slc) { log::error("failed to setup SLC for {}", connected_bda); - log_counter_metrics_btif( - android::bluetooth::CodePathCounterKeyEnum::HFP_SLC_SETUP_FAILED, - 1); + log_counter_metrics_btif(android::bluetooth::CodePathCounterKeyEnum::HFP_SLC_SETUP_FAILED, + 1); btif_queue_advance(); - DEVICE_IOT_CONFIG_ADDR_INT_ADD_ONE( - btif_hf_cb[idx].connected_bda, - IOT_CONF_KEY_HFP_SLC_CONN_FAIL_COUNT); + DEVICE_IOT_CONFIG_ADDR_INT_ADD_ONE(btif_hf_cb[idx].connected_bda, + IOT_CONF_KEY_HFP_SLC_CONN_FAIL_COUNT); } break; } case BTA_AG_CONN_EVT: - DEVICE_IOT_CONFIG_ADDR_SET_HEX( - btif_hf_cb[idx].connected_bda, IOT_CONF_KEY_HFP_CODECTYPE, - p_data->conn.peer_codec == 0x03 ? IOT_CONF_VAL_HFP_CODECTYPE_CVSDMSBC - : IOT_CONF_VAL_HFP_CODECTYPE_CVSD, - IOT_CONF_BYTE_NUM_1); - DEVICE_IOT_CONFIG_ADDR_SET_HEX( - btif_hf_cb[idx].connected_bda, IOT_CONF_KEY_HFP_FEATURES, - p_data->conn.peer_feat, IOT_CONF_BYTE_NUM_2); + DEVICE_IOT_CONFIG_ADDR_SET_HEX(btif_hf_cb[idx].connected_bda, IOT_CONF_KEY_HFP_CODECTYPE, + p_data->conn.peer_codec == 0x03 + ? IOT_CONF_VAL_HFP_CODECTYPE_CVSDMSBC + : IOT_CONF_VAL_HFP_CODECTYPE_CVSD, + IOT_CONF_BYTE_NUM_1); + DEVICE_IOT_CONFIG_ADDR_SET_HEX(btif_hf_cb[idx].connected_bda, IOT_CONF_KEY_HFP_FEATURES, + p_data->conn.peer_feat, IOT_CONF_BYTE_NUM_2); log::debug("SLC connected event:{} idx:{}", dump_hf_event(event), idx); btif_hf_cb[idx].peer_feat = p_data->conn.peer_feat; @@ -530,12 +514,10 @@ static void btif_hf_upstreams_evt(uint16_t event, char* p_param) { case BTA_AG_SPK_EVT: case BTA_AG_MIC_EVT: - log::debug("BTA auto-responds, silently discard event:{}", - dump_hf_event(event)); + log::debug("BTA auto-responds, silently discard event:{}", dump_hf_event(event)); bt_hf_callbacks->VolumeControlCallback( - (event == BTA_AG_SPK_EVT) ? BTHF_VOLUME_TYPE_SPK - : BTHF_VOLUME_TYPE_MIC, - p_data->val.num, &btif_hf_cb[idx].connected_bda); + (event == BTA_AG_SPK_EVT) ? BTHF_VOLUME_TYPE_SPK : BTHF_VOLUME_TYPE_MIC, + p_data->val.num, &btif_hf_cb[idx].connected_bda); break; case BTA_AG_AT_A_EVT: @@ -545,9 +527,8 @@ static void btif_hf_upstreams_evt(uint16_t event, char* p_param) { /* Java needs to send OK/ERROR for these commands */ case BTA_AG_AT_BLDN_EVT: case BTA_AG_AT_D_EVT: - bt_hf_callbacks->DialCallCallback( - (event == BTA_AG_AT_D_EVT) ? p_data->val.str : (char*)"", - &btif_hf_cb[idx].connected_bda); + bt_hf_callbacks->DialCallCallback((event == BTA_AG_AT_D_EVT) ? p_data->val.str : (char*)"", + &btif_hf_cb[idx].connected_bda); break; case BTA_AG_AT_CHUP_EVT: @@ -559,21 +540,19 @@ static void btif_hf_upstreams_evt(uint16_t event, char* p_param) { break; case BTA_AG_AT_VTS_EVT: - bt_hf_callbacks->DtmfCmdCallback(p_data->val.str[0], - &btif_hf_cb[idx].connected_bda); + bt_hf_callbacks->DtmfCmdCallback(p_data->val.str[0], &btif_hf_cb[idx].connected_bda); break; case BTA_AG_AT_BVRA_EVT: - bt_hf_callbacks->VoiceRecognitionCallback((p_data->val.num == 1) - ? BTHF_VR_STATE_STARTED - : BTHF_VR_STATE_STOPPED, - &btif_hf_cb[idx].connected_bda); + bt_hf_callbacks->VoiceRecognitionCallback( + (p_data->val.num == 1) ? BTHF_VR_STATE_STARTED : BTHF_VR_STATE_STOPPED, + &btif_hf_cb[idx].connected_bda); break; case BTA_AG_AT_NREC_EVT: bt_hf_callbacks->NoiseReductionCallback( - (p_data->val.num == 1) ? BTHF_NREC_START : BTHF_NREC_STOP, - &btif_hf_cb[idx].connected_bda); + (p_data->val.num == 1) ? BTHF_NREC_START : BTHF_NREC_STOP, + &btif_hf_cb[idx].connected_bda); break; /* TODO: Add a callback for CBC */ @@ -585,27 +564,22 @@ static void btif_hf_upstreams_evt(uint16_t event, char* p_param) { break; case BTA_AG_CODEC_EVT: - log::verbose( - "BTA_AG_CODEC_EVT Set codec status {} codec {} 1=CVSD 2=MSBC 4=LC3", - p_data->val.hdr.status, p_data->val.num); + log::verbose("BTA_AG_CODEC_EVT Set codec status {} codec {} 1=CVSD 2=MSBC 4=LC3", + p_data->val.hdr.status, p_data->val.num); if (p_data->val.num == BTM_SCO_CODEC_CVSD) { - bt_hf_callbacks->WbsCallback(BTHF_WBS_NO, - &btif_hf_cb[idx].connected_bda); + bt_hf_callbacks->WbsCallback(BTHF_WBS_NO, &btif_hf_cb[idx].connected_bda); bt_hf_callbacks->SwbCallback(BTHF_SWB_CODEC_LC3, BTHF_SWB_NO, &btif_hf_cb[idx].connected_bda); } else if (p_data->val.num == BTM_SCO_CODEC_MSBC) { - bt_hf_callbacks->WbsCallback(BTHF_WBS_YES, - &btif_hf_cb[idx].connected_bda); + bt_hf_callbacks->WbsCallback(BTHF_WBS_YES, &btif_hf_cb[idx].connected_bda); bt_hf_callbacks->SwbCallback(BTHF_SWB_CODEC_LC3, BTHF_SWB_NO, &btif_hf_cb[idx].connected_bda); } else if (p_data->val.num == BTM_SCO_CODEC_LC3) { - bt_hf_callbacks->WbsCallback(BTHF_WBS_NO, - &btif_hf_cb[idx].connected_bda); + bt_hf_callbacks->WbsCallback(BTHF_WBS_NO, &btif_hf_cb[idx].connected_bda); bt_hf_callbacks->SwbCallback(BTHF_SWB_CODEC_LC3, BTHF_SWB_YES, &btif_hf_cb[idx].connected_bda); } else { - bt_hf_callbacks->WbsCallback(BTHF_WBS_NONE, - &btif_hf_cb[idx].connected_bda); + bt_hf_callbacks->WbsCallback(BTHF_WBS_NONE, &btif_hf_cb[idx].connected_bda); bthf_swb_codec_t codec = BTHF_SWB_CODEC_LC3; bthf_swb_config_t config = BTHF_SWB_NONE; @@ -613,9 +587,8 @@ static void btif_hf_upstreams_evt(uint16_t event, char* p_param) { if (is_hfp_aptx_voice_enabled()) { codec = BTHF_SWB_CODEC_VENDOR_APTX; - log::verbose( - "AG final selected SWB codec is 0x{:02x} 0=Q0 4=Q1 6=Q2 7=Q3", - p_data->val.num); + log::verbose("AG final selected SWB codec is 0x{:02x} 0=Q0 4=Q1 6=Q2 7=Q3", + p_data->val.num); if (p_data->val.num == BTA_AG_SCO_APTX_SWB_SETTINGS_Q0 || p_data->val.num == BTA_AG_SCO_APTX_SWB_SETTINGS_Q1 || p_data->val.num == BTA_AG_SCO_APTX_SWB_SETTINGS_Q2 || @@ -625,8 +598,7 @@ static void btif_hf_upstreams_evt(uint16_t event, char* p_param) { config = BTHF_SWB_NO; } } - bt_hf_callbacks->SwbCallback(codec, config, - &btif_hf_cb[idx].connected_bda); + bt_hf_callbacks->SwbCallback(codec, config, &btif_hf_cb[idx].connected_bda); } break; @@ -645,8 +617,7 @@ static void btif_hf_upstreams_evt(uint16_t event, char* p_param) { break; case BTA_AG_AT_UNAT_EVT: - bt_hf_callbacks->UnknownAtCallback(p_data->val.str, - &btif_hf_cb[idx].connected_bda); + bt_hf_callbacks->UnknownAtCallback(p_data->val.str, &btif_hf_cb[idx].connected_bda); break; case BTA_AG_AT_CNUM_EVT: @@ -664,12 +635,10 @@ static void btif_hf_upstreams_evt(uint16_t event, char* p_param) { /* If the peer supports mSBC and the BTIF preferred codec is also mSBC, * then we should set the BTA AG Codec to mSBC. This would trigger a +BCS * to mSBC at the time of SCO connection establishment */ - if (hfp_hal_interface::get_swb_supported() && - (p_data->val.num & BTM_SCO_CODEC_LC3)) { + if (hfp_hal_interface::get_swb_supported() && (p_data->val.num & BTM_SCO_CODEC_LC3)) { log::verbose("btif_hf override-Preferred Codec to LC3"); BTA_AgSetCodec(btif_hf_cb[idx].handle, BTM_SCO_CODEC_LC3); - } else if (hfp_hal_interface::get_wbs_supported() && - (p_data->val.num & BTM_SCO_CODEC_MSBC)) { + } else if (hfp_hal_interface::get_wbs_supported() && (p_data->val.num & BTM_SCO_CODEC_MSBC)) { log::verbose("btif_hf override-Preferred Codec to mSBC"); BTA_AgSetCodec(btif_hf_cb[idx].handle, BTM_SCO_CODEC_MSBC); } else { @@ -679,30 +648,27 @@ static void btif_hf_upstreams_evt(uint16_t event, char* p_param) { break; case BTA_AG_AT_BCS_EVT: - log::verbose("AG final selected codec is 0x{:02x} 1=CVSD 2=MSBC", - p_data->val.num); + log::verbose("AG final selected codec is 0x{:02x} 1=CVSD 2=MSBC", p_data->val.num); /* No BTHF_WBS_NONE case, because HF1.6 supported device can send BCS */ /* Only CVSD is considered narrow band speech */ bt_hf_callbacks->WbsCallback( - (p_data->val.num == BTM_SCO_CODEC_MSBC) ? BTHF_WBS_YES : BTHF_WBS_NO, - &btif_hf_cb[idx].connected_bda); + (p_data->val.num == BTM_SCO_CODEC_MSBC) ? BTHF_WBS_YES : BTHF_WBS_NO, + &btif_hf_cb[idx].connected_bda); bt_hf_callbacks->SwbCallback( - BTHF_SWB_CODEC_LC3, - (p_data->val.num == BTM_SCO_CODEC_LC3) ? BTHF_SWB_YES : BTHF_SWB_NO, - &btif_hf_cb[idx].connected_bda); + BTHF_SWB_CODEC_LC3, + (p_data->val.num == BTM_SCO_CODEC_LC3) ? BTHF_SWB_YES : BTHF_SWB_NO, + &btif_hf_cb[idx].connected_bda); break; case BTA_AG_AT_BIND_EVT: if (p_data->val.hdr.status == BTA_AG_SUCCESS) { - bt_hf_callbacks->AtBindCallback(p_data->val.str, - &btif_hf_cb[idx].connected_bda); + bt_hf_callbacks->AtBindCallback(p_data->val.str, &btif_hf_cb[idx].connected_bda); } break; case BTA_AG_AT_BIEV_EVT: if (p_data->val.hdr.status == BTA_AG_SUCCESS) { - bt_hf_callbacks->AtBievCallback((bthf_hf_ind_type_t)p_data->val.lidx, - (int)p_data->val.num, + bt_hf_callbacks->AtBievCallback((bthf_hf_ind_type_t)p_data->val.lidx, (int)p_data->val.num, &btif_hf_cb[idx].connected_bda); } break; @@ -724,13 +690,11 @@ static void btif_hf_upstreams_evt(uint16_t event, char* p_param) { break; } - log::info("AG final selected SWB codec is {:#02x} 0=Q0 4=Q1 6=Q2 7=Q3", - p_data->val.num); + log::info("AG final selected SWB codec is {:#02x} 0=Q0 4=Q1 6=Q2 7=Q3", p_data->val.num); bt_hf_callbacks->SwbCallback( - BTHF_SWB_CODEC_VENDOR_APTX, - p_data->val.num <= BTA_AG_SCO_APTX_SWB_SETTINGS_Q3 ? BTHF_SWB_YES - : BTHF_SWB_NO, - &btif_hf_cb[idx].connected_bda); + BTHF_SWB_CODEC_VENDOR_APTX, + p_data->val.num <= BTA_AG_SCO_APTX_SWB_SETTINGS_Q3 ? BTHF_SWB_YES : BTHF_SWB_NO, + &btif_hf_cb[idx].connected_bda); break; default: @@ -755,22 +719,23 @@ static void bte_hf_evt(tBTA_AG_EVT event, tBTA_AG* p_data) { /* TODO: BTA sends the union members and not tBTA_AG. If using * param_len=sizeof(tBTA_AG), we get a crash on memcpy */ - if (BTA_AG_REGISTER_EVT == event) + if (BTA_AG_REGISTER_EVT == event) { param_len = sizeof(tBTA_AG_REGISTER); - else if (BTA_AG_OPEN_EVT == event) + } else if (BTA_AG_OPEN_EVT == event) { param_len = sizeof(tBTA_AG_OPEN); - else if (BTA_AG_CONN_EVT == event) + } else if (BTA_AG_CONN_EVT == event) { param_len = sizeof(tBTA_AG_CONN); - else if ((BTA_AG_CLOSE_EVT == event) || (BTA_AG_AUDIO_OPEN_EVT == event) || - (BTA_AG_AUDIO_CLOSE_EVT == event)) + } else if ((BTA_AG_CLOSE_EVT == event) || (BTA_AG_AUDIO_OPEN_EVT == event) || + (BTA_AG_AUDIO_CLOSE_EVT == event)) { param_len = sizeof(tBTA_AG_HDR); - else if (p_data) + } else if (p_data) { param_len = sizeof(tBTA_AG_VAL); + } /* switch context to btif task context (copy full union size for convenience) */ - status = btif_transfer_context(btif_hf_upstreams_evt, (uint16_t)event, - (char*)p_data, param_len, nullptr); + status = btif_transfer_context(btif_hf_upstreams_evt, (uint16_t)event, (char*)p_data, param_len, + nullptr); /* catch any failed context transfers */ ASSERTC(status == BT_STATUS_SUCCESS, "context transfer failed", status); @@ -801,14 +766,13 @@ static bt_status_t connect_int(RawAddress* bd_addr, uint16_t uuid) { // control block should be in connecting state // Crash here to prevent future code changes from breaking this mechanism if (btif_hf_cb[i].state == BTHF_CONNECTION_STATE_CONNECTING) { - log::fatal("{}, handle {}, is still in connecting state {}", - btif_hf_cb[i].connected_bda, btif_hf_cb[i].handle, - btif_hf_cb[i].state); + log::fatal("{}, handle {}, is still in connecting state {}", btif_hf_cb[i].connected_bda, + btif_hf_cb[i].handle, btif_hf_cb[i].state); } } if (hf_cb == nullptr) { - log::warn("Cannot connect {}: maximum {} clients already connected", - *bd_addr, btif_max_hf_clients); + log::warn("Cannot connect {}: maximum {} clients already connected", *bd_addr, + btif_max_hf_clients); return BT_STATUS_BUSY; } hf_cb->state = BTHF_CONNECTION_STATE_CONNECTING; @@ -819,13 +783,12 @@ static bt_status_t connect_int(RawAddress* bd_addr, uint16_t uuid) { DEVICE_IOT_CONFIG_ADDR_SET_INT(hf_cb->connected_bda, IOT_CONF_KEY_HFP_ROLE, IOT_CONF_VAL_HFP_ROLE_CLIENT); - DEVICE_IOT_CONFIG_ADDR_INT_ADD_ONE(hf_cb->connected_bda, - IOT_CONF_KEY_HFP_SLC_CONN_COUNT); + DEVICE_IOT_CONFIG_ADDR_INT_ADD_ONE(hf_cb->connected_bda, IOT_CONF_KEY_HFP_SLC_CONN_COUNT); return BT_STATUS_SUCCESS; } -static void UpdateCallStates(btif_hf_cb_t* control_block, int num_active, - int num_held, bthf_call_state_t call_setup_state) { +static void UpdateCallStates(btif_hf_cb_t* control_block, int num_active, int num_held, + bthf_call_state_t call_setup_state) { control_block->num_active = num_active; control_block->num_held = num_held; control_block->call_setup_state = call_setup_state; @@ -841,25 +804,27 @@ static void UpdateCallStates(btif_hf_cb_t* control_block, int num_active, * ******************************************************************************/ bool IsCallIdle() { - if (!bt_hf_callbacks) return true; + if (!bt_hf_callbacks) { + return true; + } for (int i = 0; i < btif_max_hf_clients; ++i) { if ((btif_hf_cb[i].call_setup_state != BTHF_CALL_STATE_IDLE) || - ((btif_hf_cb[i].num_held + btif_hf_cb[i].num_active) > 0)) + ((btif_hf_cb[i].num_held + btif_hf_cb[i].num_active) > 0)) { return false; + } } return true; } class HeadsetInterface : Interface { - public: +public: static Interface* GetInstance() { static Interface* instance = new HeadsetInterface(); return instance; } - bt_status_t Init(Callbacks* callbacks, int max_hf_clients, - bool inband_ringing_enabled) override; + bt_status_t Init(Callbacks* callbacks, int max_hf_clients, bool inband_ringing_enabled) override; bt_status_t Connect(RawAddress* bd_addr) override; bt_status_t Disconnect(RawAddress* bd_addr) override; bt_status_t ConnectAudio(RawAddress* bd_addr, int disabled_codecs) override; @@ -868,33 +833,24 @@ class HeadsetInterface : Interface { bt_status_t isVoiceRecognitionSupported(RawAddress* bd_addr) override; bt_status_t StartVoiceRecognition(RawAddress* bd_addr) override; bt_status_t StopVoiceRecognition(RawAddress* bd_addr) override; - bt_status_t VolumeControl(bthf_volume_type_t type, int volume, - RawAddress* bd_addr) override; - bt_status_t DeviceStatusNotification(bthf_network_state_t ntk_state, - bthf_service_type_t svc_type, int signal, - int batt_chg, - RawAddress* bd_addr) override; + bt_status_t VolumeControl(bthf_volume_type_t type, int volume, RawAddress* bd_addr) override; + bt_status_t DeviceStatusNotification(bthf_network_state_t ntk_state, bthf_service_type_t svc_type, + int signal, int batt_chg, RawAddress* bd_addr) override; bt_status_t CopsResponse(const char* cops, RawAddress* bd_addr) override; bt_status_t CindResponse(int svc, int num_active, int num_held, - bthf_call_state_t call_setup_state, int signal, - int roam, int batt_chg, + bthf_call_state_t call_setup_state, int signal, int roam, int batt_chg, RawAddress* bd_addr) override; - bt_status_t FormattedAtResponse(const char* rsp, - RawAddress* bd_addr) override; + bt_status_t FormattedAtResponse(const char* rsp, RawAddress* bd_addr) override; bt_status_t AtResponse(bthf_at_response_t response_code, int error_code, RawAddress* bd_addr) override; - bt_status_t ClccResponse(int index, bthf_call_direction_t dir, - bthf_call_state_t state, bthf_call_mode_t mode, - bthf_call_mpty_type_t mpty, const char* number, - bthf_call_addrtype_t type, - RawAddress* bd_addr) override; - bt_status_t PhoneStateChange(int num_active, int num_held, - bthf_call_state_t call_setup_state, - const char* number, bthf_call_addrtype_t type, - const char* name, RawAddress* bd_addr) override; + bt_status_t ClccResponse(int index, bthf_call_direction_t dir, bthf_call_state_t state, + bthf_call_mode_t mode, bthf_call_mpty_type_t mpty, const char* number, + bthf_call_addrtype_t type, RawAddress* bd_addr) override; + bt_status_t PhoneStateChange(int num_active, int num_held, bthf_call_state_t call_setup_state, + const char* number, bthf_call_addrtype_t type, const char* name, + RawAddress* bd_addr) override; - bt_status_t EnableSwb(bthf_swb_codec_t swbCodec, bool enable, - RawAddress* bd_addr) override; + bt_status_t EnableSwb(bthf_swb_codec_t swbCodec, bool enable, RawAddress* bd_addr) override; void Cleanup() override; bt_status_t SetScoOffloadEnabled(bool value) override; @@ -912,20 +868,19 @@ bt_status_t HeadsetInterface::Init(Callbacks* callbacks, int max_hf_clients, btif_hf_features &= ~BTA_AG_FEAT_INBAND; } log::assert_that(max_hf_clients <= BTA_AG_MAX_NUM_CLIENTS, - "Too many HF clients, maximum is {}, was given {}", - BTA_AG_MAX_NUM_CLIENTS, max_hf_clients); + "Too many HF clients, maximum is {}, was given {}", BTA_AG_MAX_NUM_CLIENTS, + max_hf_clients); btif_max_hf_clients = max_hf_clients; - log::verbose( - "btif_hf_features={}, max_hf_clients={}, inband_ringing_enabled={}", - btif_hf_features, btif_max_hf_clients, inband_ringing_enabled); + log::verbose("btif_hf_features={}, max_hf_clients={}, inband_ringing_enabled={}", + btif_hf_features, btif_max_hf_clients, inband_ringing_enabled); bt_hf_callbacks = callbacks; for (btif_hf_cb_t& hf_cb : btif_hf_cb) { reset_control_block(&hf_cb); } -// Invoke the enable service API to the core to set the appropriate service_id -// Internally, the HSP_SERVICE_ID shall also be enabled if HFP is enabled -// (phone) otherwise only HSP is enabled (tablet) + // Invoke the enable service API to the core to set the appropriate service_id + // Internally, the HSP_SERVICE_ID shall also be enabled if HFP is enabled + // (phone) otherwise only HSP is enabled (tablet) if (get_BTIF_HF_SERVICES() & BTA_HFP_SERVICE_MASK) { btif_enable_service(BTA_HFP_SERVICE_ID); } else { @@ -955,8 +910,7 @@ bt_status_t HeadsetInterface::Disconnect(RawAddress* bd_addr) { return BT_STATUS_SUCCESS; } -bt_status_t HeadsetInterface::ConnectAudio(RawAddress* bd_addr, - int disabled_codecs) { +bt_status_t HeadsetInterface::ConnectAudio(RawAddress* bd_addr, int disabled_codecs) { CHECK_BTHF_INIT(); int idx = btif_hf_idx_by_bdaddr(bd_addr); if ((idx < 0) || (idx >= BTA_AG_MAX_NUM_CLIENTS)) { @@ -970,8 +924,7 @@ bt_status_t HeadsetInterface::ConnectAudio(RawAddress* bd_addr, } do_in_jni_thread(base::BindOnce(&Callbacks::AudioStateCallback, // Manual pointer management for now - base::Unretained(bt_hf_callbacks), - BTHF_AUDIO_STATE_CONNECTING, + base::Unretained(bt_hf_callbacks), BTHF_AUDIO_STATE_CONNECTING, &btif_hf_cb[idx].connected_bda)); BTA_AgAudioOpen(btif_hf_cb[idx].handle, disabled_codecs); @@ -1033,8 +986,7 @@ bt_status_t HeadsetInterface::StartVoiceRecognition(RawAddress* bd_addr) { return BT_STATUS_NOT_READY; } if (!(btif_hf_cb[idx].peer_feat & BTA_AG_PEER_FEAT_VREC)) { - log::error("voice recognition not supported, features=0x{:x}", - btif_hf_cb[idx].peer_feat); + log::error("voice recognition not supported, features=0x{:x}", btif_hf_cb[idx].peer_feat); return BT_STATUS_UNSUPPORTED; } tBTA_AG_RES_DATA ag_res = {}; @@ -1056,8 +1008,7 @@ bt_status_t HeadsetInterface::StopVoiceRecognition(RawAddress* bd_addr) { return BT_STATUS_NOT_READY; } if (!(btif_hf_cb[idx].peer_feat & BTA_AG_PEER_FEAT_VREC)) { - log::error("voice recognition not supported, features=0x{:x}", - btif_hf_cb[idx].peer_feat); + log::error("voice recognition not supported, features=0x{:x}", btif_hf_cb[idx].peer_feat); return BT_STATUS_UNSUPPORTED; } tBTA_AG_RES_DATA ag_res = {}; @@ -1081,14 +1032,13 @@ bt_status_t HeadsetInterface::VolumeControl(bthf_volume_type_t type, int volume, tBTA_AG_RES_DATA ag_res = {}; ag_res.num = static_cast(volume); BTA_AgResult(btif_hf_cb[idx].handle, - (type == BTHF_VOLUME_TYPE_SPK) ? BTA_AG_SPK_RES : BTA_AG_MIC_RES, - ag_res); + (type == BTHF_VOLUME_TYPE_SPK) ? BTA_AG_SPK_RES : BTA_AG_MIC_RES, ag_res); return BT_STATUS_SUCCESS; } -bt_status_t HeadsetInterface::DeviceStatusNotification( - bthf_network_state_t ntk_state, bthf_service_type_t svc_type, int signal, - int batt_chg, RawAddress* bd_addr) { +bt_status_t HeadsetInterface::DeviceStatusNotification(bthf_network_state_t ntk_state, + bthf_service_type_t svc_type, int signal, + int batt_chg, RawAddress* bd_addr) { CHECK_BTHF_INIT(); if (!bd_addr) { log::warn("bd_addr is null"); @@ -1114,8 +1064,7 @@ bt_status_t HeadsetInterface::DeviceStatusNotification( return BT_STATUS_SUCCESS; } -bt_status_t HeadsetInterface::CopsResponse(const char* cops, - RawAddress* bd_addr) { +bt_status_t HeadsetInterface::CopsResponse(const char* cops, RawAddress* bd_addr) { CHECK_BTHF_INIT(); int idx = btif_hf_idx_by_bdaddr(bd_addr); if ((idx < 0) || (idx >= BTA_AG_MAX_NUM_CLIENTS)) { @@ -1134,11 +1083,9 @@ bt_status_t HeadsetInterface::CopsResponse(const char* cops, return BT_STATUS_SUCCESS; } -bt_status_t HeadsetInterface::CindResponse(int svc, int num_active, - int num_held, - bthf_call_state_t call_setup_state, - int signal, int roam, int batt_chg, - RawAddress* bd_addr) { +bt_status_t HeadsetInterface::CindResponse(int svc, int num_active, int num_held, + bthf_call_state_t call_setup_state, int signal, int roam, + int batt_chg, RawAddress* bd_addr) { CHECK_BTHF_INIT(); int idx = btif_hf_idx_by_bdaddr(bd_addr); if ((idx < 0) || (idx >= BTA_AG_MAX_NUM_CLIENTS)) { @@ -1154,19 +1101,18 @@ bt_status_t HeadsetInterface::CindResponse(int svc, int num_active, // (active/held), see: // https://www.bluetooth.org/errata/errata_view.cfm?errata_id=2043 snprintf(ag_res.str, sizeof(ag_res.str), "%d,%d,%d,%d,%d,%d,%d", - (num_active + num_held) ? 1 : 0, /* Call state */ - callstate_to_callsetup(call_setup_state), /* Callsetup state */ - svc, /* network service */ - signal, /* Signal strength */ - roam, /* Roaming indicator */ - batt_chg, /* Battery level */ + (num_active + num_held) ? 1 : 0, /* Call state */ + callstate_to_callsetup(call_setup_state), /* Callsetup state */ + svc, /* network service */ + signal, /* Signal strength */ + roam, /* Roaming indicator */ + batt_chg, /* Battery level */ ((num_held == 0) ? 0 : ((num_active == 0) ? 2 : 1))); /* Call held */ BTA_AgResult(btif_hf_cb[idx].handle, BTA_AG_CIND_RES, ag_res); return BT_STATUS_SUCCESS; } -bt_status_t HeadsetInterface::FormattedAtResponse(const char* rsp, - RawAddress* bd_addr) { +bt_status_t HeadsetInterface::FormattedAtResponse(const char* rsp, RawAddress* bd_addr) { CHECK_BTHF_INIT(); tBTA_AG_RES_DATA ag_res = {}; int idx = btif_hf_idx_by_bdaddr(bd_addr); @@ -1184,8 +1130,8 @@ bt_status_t HeadsetInterface::FormattedAtResponse(const char* rsp, return BT_STATUS_SUCCESS; } -bt_status_t HeadsetInterface::AtResponse(bthf_at_response_t response_code, - int error_code, RawAddress* bd_addr) { +bt_status_t HeadsetInterface::AtResponse(bthf_at_response_t response_code, int error_code, + RawAddress* bd_addr) { CHECK_BTHF_INIT(); int idx = btif_hf_idx_by_bdaddr(bd_addr); if ((idx < 0) || (idx >= BTA_AG_MAX_NUM_CLIENTS)) { @@ -1196,16 +1142,15 @@ bt_status_t HeadsetInterface::AtResponse(bthf_at_response_t response_code, log::error("{} is not connected", *bd_addr); return BT_STATUS_DEVICE_NOT_FOUND; } - send_at_result( - (response_code == BTHF_AT_RESPONSE_OK) ? BTA_AG_OK_DONE : BTA_AG_OK_ERROR, - static_cast(error_code), idx); + send_at_result((response_code == BTHF_AT_RESPONSE_OK) ? BTA_AG_OK_DONE : BTA_AG_OK_ERROR, + static_cast(error_code), idx); return BT_STATUS_SUCCESS; } -bt_status_t HeadsetInterface::ClccResponse( - int index, bthf_call_direction_t dir, bthf_call_state_t state, - bthf_call_mode_t mode, bthf_call_mpty_type_t mpty, const char* number, - bthf_call_addrtype_t type, RawAddress* bd_addr) { +bt_status_t HeadsetInterface::ClccResponse(int index, bthf_call_direction_t dir, + bthf_call_state_t state, bthf_call_mode_t mode, + bthf_call_mpty_type_t mpty, const char* number, + bthf_call_addrtype_t type, RawAddress* bd_addr) { CHECK_BTHF_INIT(); int idx = btif_hf_idx_by_bdaddr(bd_addr); if ((idx < 0) || (idx >= BTA_AG_MAX_NUM_CLIENTS)) { @@ -1222,11 +1167,10 @@ bt_status_t HeadsetInterface::ClccResponse( ag_res.ok_flag = BTA_AG_OK_DONE; } else { std::string cell_number(number ? number : ""); - log::verbose( - "clcc_response: [{}] dir {} state {} mode {} number = {} type = {}", - index, dir, state, mode, PRIVATE_CELL(cell_number), type); - int res_strlen = snprintf(ag_res.str, sizeof(ag_res.str), "%d,%d,%d,%d,%d", - index, dir, state, mode, mpty); + log::verbose("clcc_response: [{}] dir {} state {} mode {} number = {} type = {}", index, dir, + state, mode, PRIVATE_CELL(cell_number), type); + int res_strlen = snprintf(ag_res.str, sizeof(ag_res.str), "%d,%d,%d,%d,%d", index, dir, state, + mode, mpty); if (number) { size_t rem_bytes = sizeof(ag_res.str) - res_strlen; char dialnum[sizeof(ag_res.str)]; @@ -1254,10 +1198,10 @@ bt_status_t HeadsetInterface::ClccResponse( return BT_STATUS_SUCCESS; } -bt_status_t HeadsetInterface::PhoneStateChange( - int num_active, int num_held, bthf_call_state_t call_setup_state, - const char* number, bthf_call_addrtype_t type, const char* name, - RawAddress* bd_addr) { +bt_status_t HeadsetInterface::PhoneStateChange(int num_active, int num_held, + bthf_call_state_t call_setup_state, + const char* number, bthf_call_addrtype_t type, + const char* name, RawAddress* bd_addr) { CHECK_BTHF_INIT(); if (bd_addr == nullptr) { log::warn("bd_addr is null"); @@ -1280,29 +1224,27 @@ bt_status_t HeadsetInterface::PhoneStateChange( // HFP spec does not handle cases when a call is being disconnected. // Since DISCONNECTED state must lead to IDLE state, ignoring it here.s log::info( - "Ignore call state change to DISCONNECTED, idx={}, addr={}, " - "num_active={}, num_held={}", - idx, *bd_addr, num_active, num_held); + "Ignore call state change to DISCONNECTED, idx={}, addr={}, " + "num_active={}, num_held={}", + idx, *bd_addr, num_active, num_held); return BT_STATUS_SUCCESS; } log::debug( - "bd_addr:{} active_bda:{} num_active:{} prev_num_active:{} num_held:{} " - "prev_num_held:{} call_state:{} prev_call_state:{}", - *bd_addr, active_bda, num_active, control_block.num_active, num_held, - control_block.num_held, dump_hf_call_state(call_setup_state), - dump_hf_call_state(control_block.call_setup_state)); + "bd_addr:{} active_bda:{} num_active:{} prev_num_active:{} num_held:{} " + "prev_num_held:{} call_state:{} prev_call_state:{}", + *bd_addr, active_bda, num_active, control_block.num_active, num_held, + control_block.num_held, dump_hf_call_state(call_setup_state), + dump_hf_call_state(control_block.call_setup_state)); tBTA_AG_RES res = BTA_AG_UNKNOWN; bt_status_t status = BT_STATUS_SUCCESS; bool active_call_updated = false; /* if all indicators are 0, send end call and return */ - if (num_active == 0 && num_held == 0 && - call_setup_state == BTHF_CALL_STATE_IDLE) { + if (num_active == 0 && num_held == 0 && call_setup_state == BTHF_CALL_STATE_IDLE) { if (control_block.num_active > 0) { BTM_LogHistory(kBtmLogTag, raw_address, "Call Ended"); } - BTA_AgResult(control_block.handle, BTA_AG_END_CALL_RES, - tBTA_AG_RES_DATA::kEmpty); + BTA_AgResult(control_block.handle, BTA_AG_END_CALL_RES, tBTA_AG_RES_DATA::kEmpty); /* if held call was present, reset that as well */ if (control_block.num_held) { send_indicator_update(control_block, BTA_AG_IND_CALLHELD, 0); @@ -1323,11 +1265,9 @@ bt_status_t HeadsetInterface::PhoneStateChange( ** call setup handling */ if (((num_active + num_held) > 0) && (control_block.num_active == 0) && - (control_block.num_held == 0) && - (control_block.call_setup_state == BTHF_CALL_STATE_IDLE)) { + (control_block.num_held == 0) && (control_block.call_setup_state == BTHF_CALL_STATE_IDLE)) { tBTA_AG_RES_DATA ag_res = {}; - log::verbose( - "Active/Held call notification received without call setup update"); + log::verbose("Active/Held call notification received without call setup update"); ag_res.audio_handle = BTA_AG_HANDLE_SCO_NO_CHANGE; // Addition call setup with the Active call @@ -1358,21 +1298,23 @@ bt_status_t HeadsetInterface::PhoneStateChange( if (is_active_device(*bd_addr)) { ag_res.audio_handle = control_block.handle; } - } else if (num_held > control_block.num_held) + } else if (num_held > control_block.num_held) { res = BTA_AG_IN_CALL_HELD_RES; - else + } else { res = BTA_AG_CALL_CANCEL_RES; + } break; case BTHF_CALL_STATE_DIALING: case BTHF_CALL_STATE_ALERTING: if (num_active > control_block.num_active) { res = BTA_AG_OUT_CALL_CONN_RES; - } else + } else { res = BTA_AG_CALL_CANCEL_RES; + } break; default: - log::error("Incorrect call state prev={}, now={}", - control_block.call_setup_state, call_setup_state); + log::error("Incorrect call state prev={}, now={}", control_block.call_setup_state, + call_setup_state); status = BT_STATUS_PARM_INVALID; break; } @@ -1401,12 +1343,10 @@ bt_status_t HeadsetInterface::PhoneStateChange( } std::string number_str(number); // 13 = ["][+]["][,][3_digit_type][,,,]["]["][null_terminator] - int overflow_size = - 13 + static_cast(number_str.length() + name_str.length()) - - static_cast(sizeof(ag_res.str)); + int overflow_size = 13 + static_cast(number_str.length() + name_str.length()) - + static_cast(sizeof(ag_res.str)); if (overflow_size > 0) { - int extra_overflow_size = - overflow_size - static_cast(name_str.length()); + int extra_overflow_size = overflow_size - static_cast(name_str.length()); if (extra_overflow_size > 0) { number_str.resize(number_str.length() - extra_overflow_size); name_str.clear(); @@ -1419,8 +1359,7 @@ bt_status_t HeadsetInterface::PhoneStateChange( // Store caller id string and append type info. // Make sure type info is valid, otherwise add 129 as default type ag_res.num = static_cast(type); - if ((ag_res.num < BTA_AG_CLIP_TYPE_MIN) || - (ag_res.num > BTA_AG_CLIP_TYPE_MAX)) { + if ((ag_res.num < BTA_AG_CLIP_TYPE_MIN) || (ag_res.num > BTA_AG_CLIP_TYPE_MAX)) { if (ag_res.num != BTA_AG_CLIP_TYPE_VOIP) { ag_res.num = BTA_AG_CLIP_TYPE_DEFAULT; } @@ -1429,17 +1368,14 @@ bt_status_t HeadsetInterface::PhoneStateChange( if (res == BTA_AG_CALL_WAIT_RES || name_str.empty()) { call_number_stream << "," << std::to_string(ag_res.num); } else { - call_number_stream << "," << std::to_string(ag_res.num) << ",,,\"" - << name_str << "\""; + call_number_stream << "," << std::to_string(ag_res.num) << ",,,\"" << name_str << "\""; } - snprintf(ag_res.str, sizeof(ag_res.str), "%s", - call_number_stream.str().c_str()); + snprintf(ag_res.str, sizeof(ag_res.str), "%s", call_number_stream.str().c_str()); } { std::string cell_number(number); - BTM_LogHistory( - kBtmLogTag, raw_address, "Call Incoming", - base::StringPrintf("number:%s", PRIVATE_CELL(cell_number))); + BTM_LogHistory(kBtmLogTag, raw_address, "Call Incoming", + base::StringPrintf("number:%s", PRIVATE_CELL(cell_number))); } // base::StringPrintf("number:%s", PRIVATE_CELL(number))); break; @@ -1452,20 +1388,19 @@ bt_status_t HeadsetInterface::PhoneStateChange( case BTHF_CALL_STATE_ALERTING: /* if we went from idle->alert, force SCO setup here. dialing usually * triggers it */ - if ((control_block.call_setup_state == BTHF_CALL_STATE_IDLE) && - !(num_active + num_held) && is_active_device(*bd_addr)) { + if ((control_block.call_setup_state == BTHF_CALL_STATE_IDLE) && !(num_active + num_held) && + is_active_device(*bd_addr)) { ag_res.audio_handle = control_block.handle; } res = BTA_AG_OUT_CALL_ALERT_RES; break; default: - log::error("Incorrect call state prev={}, now={}", - control_block.call_setup_state, call_setup_state); + log::error("Incorrect call state prev={}, now={}", control_block.call_setup_state, + call_setup_state); status = BT_STATUS_PARM_INVALID; break; } - log::verbose("Call setup state changed. res={}, audio_handle={}", res, - ag_res.audio_handle); + log::verbose("Call setup state changed. res={}, audio_handle={}", res, ag_res.audio_handle); if (res != 0xFF) { BTA_AgResult(control_block.handle, res, ag_res); @@ -1478,8 +1413,7 @@ bt_status_t HeadsetInterface::PhoneStateChange( if ((num_held > 0) && (num_active > 0)) { send_indicator_update(control_block, BTA_AG_IND_CALLHELD, 1); } - UpdateCallStates(&btif_hf_cb[idx], num_active, num_held, - call_setup_state); + UpdateCallStates(&btif_hf_cb[idx], num_active, num_held, call_setup_state); return status; } } @@ -1493,29 +1427,25 @@ bt_status_t HeadsetInterface::PhoneStateChange( * **/ if (!active_call_updated && - ((num_active + num_held) != - (control_block.num_active + control_block.num_held))) { - log::verbose( - "in progress call states changed, active=[{}->{}], held=[{}->{}]", - control_block.num_active, num_active, control_block.num_held, num_held); - send_indicator_update(control_block, BTA_AG_IND_CALL, - ((num_active + num_held) > 0) ? BTA_AG_CALL_ACTIVE - : BTA_AG_CALL_INACTIVE); + ((num_active + num_held) != (control_block.num_active + control_block.num_held))) { + log::verbose("in progress call states changed, active=[{}->{}], held=[{}->{}]", + control_block.num_active, num_active, control_block.num_held, num_held); + send_indicator_update( + control_block, BTA_AG_IND_CALL, + ((num_active + num_held) > 0) ? BTA_AG_CALL_ACTIVE : BTA_AG_CALL_INACTIVE); } /* Held Changed? */ if (num_held != control_block.num_held || ((num_active == 0) && ((num_held + control_block.num_held) > 1))) { - log::verbose("Held call states changed. old: {} new: {}", - control_block.num_held, num_held); + log::verbose("Held call states changed. old: {} new: {}", control_block.num_held, num_held); send_indicator_update(control_block, BTA_AG_IND_CALLHELD, ((num_held == 0) ? 0 : ((num_active == 0) ? 2 : 1))); } /* Calls Swapped? */ - if ((call_setup_state == control_block.call_setup_state) && - (num_active && num_held) && (num_active == control_block.num_active) && - (num_held == control_block.num_held)) { + if ((call_setup_state == control_block.call_setup_state) && (num_active && num_held) && + (num_active == control_block.num_active) && (num_held == control_block.num_held)) { log::verbose("Calls swapped"); send_indicator_update(control_block, BTA_AG_IND_CALLHELD, 1); } @@ -1604,15 +1534,12 @@ bt_status_t HeadsetInterface::SetActiveDevice(RawAddress* active_device_addr) { bt_status_t HeadsetInterface::DebugDump() { CHECK_BTHF_INIT(); - tBTM_SCO_DEBUG_DUMP debug_dump = - get_btm_client_interface().sco.BTM_GetScoDebugDump(); + tBTM_SCO_DEBUG_DUMP debug_dump = get_btm_client_interface().sco.BTM_GetScoDebugDump(); bt_hf_callbacks->DebugDumpCallback( - debug_dump.is_active, debug_dump.codec_id, - debug_dump.total_num_decoded_frames, debug_dump.pkt_loss_ratio, - debug_dump.latest_data.begin_ts_raw_us, - debug_dump.latest_data.end_ts_raw_us, - debug_dump.latest_data.status_in_hex.c_str(), - debug_dump.latest_data.status_in_binary.c_str()); + debug_dump.is_active, debug_dump.codec_id, debug_dump.total_num_decoded_frames, + debug_dump.pkt_loss_ratio, debug_dump.latest_data.begin_ts_raw_us, + debug_dump.latest_data.end_ts_raw_us, debug_dump.latest_data.status_in_hex.c_str(), + debug_dump.latest_data.status_in_binary.c_str()); return BT_STATUS_SUCCESS; } @@ -1638,8 +1565,7 @@ bt_status_t ExecuteService(bool b_enable) { /* Enable and register with BTA-AG */ BTA_AgEnable(bte_hf_evt); for (uint8_t app_id = 0; app_id < btif_max_hf_clients; app_id++) { - BTA_AgRegister(get_BTIF_HF_SERVICES(), btif_hf_features, service_names, - app_id); + BTA_AgRegister(get_BTIF_HF_SERVICES(), btif_hf_features, service_names, app_id); } } else { /* De-register AG */ diff --git a/system/btif/src/btif_hf_client.cc b/system/btif/src/btif_hf_client.cc index e00306e4122..8a0284ececa 100644 --- a/system/btif/src/btif_hf_client.cc +++ b/system/btif/src/btif_hf_client.cc @@ -182,8 +182,9 @@ static void btif_in_hf_client_generic_evt(uint16_t event, char* p_param) { ******************************************************************************/ bool is_connected(const btif_hf_client_cb_t* cb) { if ((cb->state == BTHF_CLIENT_CONNECTION_STATE_CONNECTED) || - (cb->state == BTHF_CLIENT_CONNECTION_STATE_SLC_CONNECTED)) + (cb->state == BTHF_CLIENT_CONNECTION_STATE_SLC_CONNECTED)) { return true; + } log::error("not connected!"); return false; @@ -202,8 +203,7 @@ btif_hf_client_cb_t* btif_hf_client_get_cb_by_handle(uint16_t handle) { log::verbose("cb by handle {}", handle); for (int i = 0; i < HF_CLIENT_MAX_DEVICES; i++) { // Block is valid only if it is allocated i.e. state is not DISCONNECTED - if (btif_hf_client_cb_arr.cb[i].state != - BTHF_CLIENT_CONNECTION_STATE_DISCONNECTED && + if (btif_hf_client_cb_arr.cb[i].state != BTHF_CLIENT_CONNECTION_STATE_DISCONNECTED && btif_hf_client_cb_arr.cb[i].handle == handle) { return &btif_hf_client_cb_arr.cb[i]; } @@ -226,8 +226,7 @@ btif_hf_client_cb_t* btif_hf_client_get_cb_by_bda(const RawAddress& bd_addr) { for (int i = 0; i < HF_CLIENT_MAX_DEVICES; i++) { // Block is valid only if it is allocated i.e. state is not DISCONNECTED - if (btif_hf_client_cb_arr.cb[i].state != - BTHF_CLIENT_CONNECTION_STATE_DISCONNECTED && + if (btif_hf_client_cb_arr.cb[i].state != BTHF_CLIENT_CONNECTION_STATE_DISCONNECTED && btif_hf_client_cb_arr.cb[i].peer_bda == bd_addr) { return &btif_hf_client_cb_arr.cb[i]; } @@ -300,7 +299,9 @@ static bt_status_t connect_int(RawAddress* bd_addr, uint16_t uuid) { } cb->peer_bda = *bd_addr; - if (is_connected(cb)) return BT_STATUS_BUSY; + if (is_connected(cb)) { + return BT_STATUS_BUSY; + } cb->state = BTHF_CLIENT_CONNECTION_STATE_CONNECTING; cb->peer_bda = *bd_addr; @@ -350,7 +351,9 @@ static bt_status_t disconnect(const RawAddress* bd_addr) { ******************************************************************************/ static bt_status_t connect_audio(const RawAddress* bd_addr) { btif_hf_client_cb_t* cb = btif_hf_client_get_cb_by_bda(*bd_addr); - if (cb == NULL || !is_connected(cb)) return BT_STATUS_DEVICE_NOT_FOUND; + if (cb == NULL || !is_connected(cb)) { + return BT_STATUS_DEVICE_NOT_FOUND; + } CHECK_BTHF_CLIENT_SLC_CONNECTED(cb); @@ -363,9 +366,8 @@ static bt_status_t connect_audio(const RawAddress* bd_addr) { /* Inform the application that the audio connection has been initiated * successfully */ - btif_transfer_context(btif_in_hf_client_generic_evt, - BTIF_HF_CLIENT_CB_AUDIO_CONNECTING, (char*)bd_addr, - sizeof(RawAddress), NULL); + btif_transfer_context(btif_in_hf_client_generic_evt, BTIF_HF_CLIENT_CB_AUDIO_CONNECTING, + (char*)bd_addr, sizeof(RawAddress), NULL); return BT_STATUS_SUCCESS; } @@ -380,7 +382,9 @@ static bt_status_t connect_audio(const RawAddress* bd_addr) { ******************************************************************************/ static bt_status_t disconnect_audio(const RawAddress* bd_addr) { btif_hf_client_cb_t* cb = btif_hf_client_get_cb_by_bda(*bd_addr); - if (cb == NULL || !is_connected(cb)) return BT_STATUS_DEVICE_NOT_FOUND; + if (cb == NULL || !is_connected(cb)) { + return BT_STATUS_DEVICE_NOT_FOUND; + } CHECK_BTHF_CLIENT_SLC_CONNECTED(cb); @@ -399,7 +403,9 @@ static bt_status_t disconnect_audio(const RawAddress* bd_addr) { ******************************************************************************/ static bt_status_t start_voice_recognition(const RawAddress* bd_addr) { btif_hf_client_cb_t* cb = btif_hf_client_get_cb_by_bda(*bd_addr); - if (cb == NULL || !is_connected(cb)) return BT_STATUS_DEVICE_NOT_FOUND; + if (cb == NULL || !is_connected(cb)) { + return BT_STATUS_DEVICE_NOT_FOUND; + } CHECK_BTHF_CLIENT_SLC_CONNECTED(cb); @@ -421,7 +427,9 @@ static bt_status_t start_voice_recognition(const RawAddress* bd_addr) { ******************************************************************************/ static bt_status_t stop_voice_recognition(const RawAddress* bd_addr) { btif_hf_client_cb_t* cb = btif_hf_client_get_cb_by_bda(*bd_addr); - if (cb == NULL || !is_connected(cb)) return BT_STATUS_DEVICE_NOT_FOUND; + if (cb == NULL || !is_connected(cb)) { + return BT_STATUS_DEVICE_NOT_FOUND; + } CHECK_BTHF_CLIENT_SLC_CONNECTED(cb); @@ -441,10 +449,12 @@ static bt_status_t stop_voice_recognition(const RawAddress* bd_addr) { * Returns bt_status_t * ******************************************************************************/ -static bt_status_t volume_control(const RawAddress* bd_addr, - bthf_client_volume_type_t type, int volume) { +static bt_status_t volume_control(const RawAddress* bd_addr, bthf_client_volume_type_t type, + int volume) { btif_hf_client_cb_t* cb = btif_hf_client_get_cb_by_bda(*bd_addr); - if (cb == NULL || !is_connected(cb)) return BT_STATUS_DEVICE_NOT_FOUND; + if (cb == NULL || !is_connected(cb)) { + return BT_STATUS_DEVICE_NOT_FOUND; + } CHECK_BTHF_CLIENT_SLC_CONNECTED(cb); @@ -473,7 +483,9 @@ static bt_status_t volume_control(const RawAddress* bd_addr, ******************************************************************************/ static bt_status_t dial(const RawAddress* bd_addr, const char* number) { btif_hf_client_cb_t* cb = btif_hf_client_get_cb_by_bda(*bd_addr); - if (cb == NULL || !is_connected(cb)) return BT_STATUS_DEVICE_NOT_FOUND; + if (cb == NULL || !is_connected(cb)) { + return BT_STATUS_DEVICE_NOT_FOUND; + } CHECK_BTHF_CLIENT_SLC_CONNECTED(cb); @@ -496,7 +508,9 @@ static bt_status_t dial(const RawAddress* bd_addr, const char* number) { ******************************************************************************/ static bt_status_t dial_memory(const RawAddress* bd_addr, int location) { btif_hf_client_cb_t* cb = btif_hf_client_get_cb_by_bda(*bd_addr); - if (cb == NULL || !is_connected(cb)) return BT_STATUS_DEVICE_NOT_FOUND; + if (cb == NULL || !is_connected(cb)) { + return BT_STATUS_DEVICE_NOT_FOUND; + } CHECK_BTHF_CLIENT_SLC_CONNECTED(cb); @@ -513,11 +527,12 @@ static bt_status_t dial_memory(const RawAddress* bd_addr, int location) { * Returns bt_status_t * ******************************************************************************/ -static bt_status_t handle_call_action(const RawAddress* bd_addr, - bthf_client_call_action_t action, +static bt_status_t handle_call_action(const RawAddress* bd_addr, bthf_client_call_action_t action, int idx) { btif_hf_client_cb_t* cb = btif_hf_client_get_cb_by_bda(*bd_addr); - if (cb == NULL || !is_connected(cb)) return BT_STATUS_DEVICE_NOT_FOUND; + if (cb == NULL || !is_connected(cb)) { + return BT_STATUS_DEVICE_NOT_FOUND; + } CHECK_BTHF_CLIENT_SLC_CONNECTED(cb); @@ -605,7 +620,9 @@ static bt_status_t handle_call_action(const RawAddress* bd_addr, ******************************************************************************/ static bt_status_t query_current_calls(const RawAddress* bd_addr) { btif_hf_client_cb_t* cb = btif_hf_client_get_cb_by_bda(*bd_addr); - if (cb == NULL || !is_connected(cb)) return BT_STATUS_DEVICE_NOT_FOUND; + if (cb == NULL || !is_connected(cb)) { + return BT_STATUS_DEVICE_NOT_FOUND; + } CHECK_BTHF_CLIENT_SLC_CONNECTED(cb); @@ -628,7 +645,9 @@ static bt_status_t query_current_calls(const RawAddress* bd_addr) { ******************************************************************************/ static bt_status_t query_current_operator_name(const RawAddress* bd_addr) { btif_hf_client_cb_t* cb = btif_hf_client_get_cb_by_bda(*bd_addr); - if (cb == NULL || !is_connected(cb)) return BT_STATUS_DEVICE_NOT_FOUND; + if (cb == NULL || !is_connected(cb)) { + return BT_STATUS_DEVICE_NOT_FOUND; + } CHECK_BTHF_CLIENT_SLC_CONNECTED(cb); @@ -647,7 +666,9 @@ static bt_status_t query_current_operator_name(const RawAddress* bd_addr) { ******************************************************************************/ static bt_status_t retrieve_subscriber_info(const RawAddress* bd_addr) { btif_hf_client_cb_t* cb = btif_hf_client_get_cb_by_bda(*bd_addr); - if (cb == NULL || !is_connected(cb)) return BT_STATUS_DEVICE_NOT_FOUND; + if (cb == NULL || !is_connected(cb)) { + return BT_STATUS_DEVICE_NOT_FOUND; + } CHECK_BTHF_CLIENT_SLC_CONNECTED(cb); @@ -666,7 +687,9 @@ static bt_status_t retrieve_subscriber_info(const RawAddress* bd_addr) { ******************************************************************************/ static bt_status_t send_dtmf(const RawAddress* bd_addr, char code) { btif_hf_client_cb_t* cb = btif_hf_client_get_cb_by_bda(*bd_addr); - if (cb == NULL || !is_connected(cb)) return BT_STATUS_DEVICE_NOT_FOUND; + if (cb == NULL || !is_connected(cb)) { + return BT_STATUS_DEVICE_NOT_FOUND; + } CHECK_BTHF_CLIENT_SLC_CONNECTED(cb); @@ -685,7 +708,9 @@ static bt_status_t send_dtmf(const RawAddress* bd_addr, char code) { ******************************************************************************/ static bt_status_t request_last_voice_tag_number(const RawAddress* bd_addr) { btif_hf_client_cb_t* cb = btif_hf_client_get_cb_by_bda(*bd_addr); - if (cb == NULL || !is_connected(cb)) return BT_STATUS_DEVICE_NOT_FOUND; + if (cb == NULL || !is_connected(cb)) { + return BT_STATUS_DEVICE_NOT_FOUND; + } CHECK_BTHF_CLIENT_SLC_CONNECTED(cb); @@ -724,15 +749,16 @@ static void cleanup(void) { * Returns bt_status_t * ******************************************************************************/ -static bt_status_t send_at_cmd(const RawAddress* bd_addr, int cmd, int val1, - int val2, const char* arg) { +static bt_status_t send_at_cmd(const RawAddress* bd_addr, int cmd, int val1, int val2, + const char* arg) { btif_hf_client_cb_t* cb = btif_hf_client_get_cb_by_bda(*bd_addr); - if (cb == NULL || !is_connected(cb)) return BT_STATUS_DEVICE_NOT_FOUND; + if (cb == NULL || !is_connected(cb)) { + return BT_STATUS_DEVICE_NOT_FOUND; + } CHECK_BTHF_CLIENT_SLC_CONNECTED(cb); - log::verbose("Cmd {} val1 {} val2 {} arg {}", cmd, val1, val2, - (arg != NULL) ? arg : ""); + log::verbose("Cmd {} val1 {} val2 {} arg {}", cmd, val1, val2, (arg != NULL) ? arg : ""); BTA_HfClientSendAT(cb->handle, cmd, val1, val2, arg); return BT_STATUS_SUCCESS; @@ -749,7 +775,9 @@ static bt_status_t send_at_cmd(const RawAddress* bd_addr, int cmd, int val1, ******************************************************************************/ static bt_status_t send_android_at(const RawAddress* bd_addr, const char* arg) { btif_hf_client_cb_t* cb = btif_hf_client_get_cb_by_bda(*bd_addr); - if (cb == NULL || !is_connected(cb)) return BT_STATUS_DEVICE_NOT_FOUND; + if (cb == NULL || !is_connected(cb)) { + return BT_STATUS_DEVICE_NOT_FOUND; + } CHECK_BTHF_CLIENT_SLC_CONNECTED(cb); @@ -760,38 +788,39 @@ static bt_status_t send_android_at(const RawAddress* bd_addr, const char* arg) { } static const bthf_client_interface_t bthfClientInterface = { - .size = sizeof(bthf_client_interface_t), - .init = init, - .connect = connect, - .disconnect = disconnect, - .connect_audio = connect_audio, - .disconnect_audio = disconnect_audio, - .start_voice_recognition = start_voice_recognition, - .stop_voice_recognition = stop_voice_recognition, - .volume_control = volume_control, - .dial = dial, - .dial_memory = dial_memory, - .handle_call_action = handle_call_action, - .query_current_calls = query_current_calls, - .query_current_operator_name = query_current_operator_name, - .retrieve_subscriber_info = retrieve_subscriber_info, - .send_dtmf = send_dtmf, - .request_last_voice_tag_number = request_last_voice_tag_number, - .cleanup = cleanup, - .send_at_cmd = send_at_cmd, - .send_android_at = send_android_at, + .size = sizeof(bthf_client_interface_t), + .init = init, + .connect = connect, + .disconnect = disconnect, + .connect_audio = connect_audio, + .disconnect_audio = disconnect_audio, + .start_voice_recognition = start_voice_recognition, + .stop_voice_recognition = stop_voice_recognition, + .volume_control = volume_control, + .dial = dial, + .dial_memory = dial_memory, + .handle_call_action = handle_call_action, + .query_current_calls = query_current_calls, + .query_current_operator_name = query_current_operator_name, + .retrieve_subscriber_info = retrieve_subscriber_info, + .send_dtmf = send_dtmf, + .request_last_voice_tag_number = request_last_voice_tag_number, + .cleanup = cleanup, + .send_at_cmd = send_at_cmd, + .send_android_at = send_android_at, }; static void process_ind_evt(tBTA_HF_CLIENT_IND* ind) { log::verbose(""); btif_hf_client_cb_t* cb = btif_hf_client_get_cb_by_bda(ind->bd_addr); - if (cb == NULL || !is_connected(cb)) return; + if (cb == NULL || !is_connected(cb)) { + return; + } switch (ind->type) { case BTA_HF_CLIENT_IND_CALL: - HAL_CBACK(bt_hf_client_callbacks, call_cb, &cb->peer_bda, - (bthf_client_call_t)ind->value); + HAL_CBACK(bt_hf_client_callbacks, call_cb, &cb->peer_bda, (bthf_client_call_t)ind->value); break; case BTA_HF_CLIENT_IND_CALLSETUP: @@ -809,8 +838,7 @@ static void process_ind_evt(tBTA_HF_CLIENT_IND* ind) { break; case BTA_HF_CLIENT_IND_SIGNAL: - HAL_CBACK(bt_hf_client_callbacks, network_signal_cb, &cb->peer_bda, - ind->value); + HAL_CBACK(bt_hf_client_callbacks, network_signal_cb, &cb->peer_bda, ind->value); break; case BTA_HF_CLIENT_IND_ROAM: @@ -819,8 +847,7 @@ static void process_ind_evt(tBTA_HF_CLIENT_IND* ind) { break; case BTA_HF_CLIENT_IND_BATTCH: - HAL_CBACK(bt_hf_client_callbacks, battery_level_cb, &cb->peer_bda, - ind->value); + HAL_CBACK(bt_hf_client_callbacks, battery_level_cb, &cb->peer_bda, ind->value); break; default: @@ -868,20 +895,23 @@ static void btif_hf_client_upstreams_evt(uint16_t event, char* p_param) { cb->state = BTHF_CLIENT_CONNECTION_STATE_DISCONNECTED; } else { log::warn( - "HF CLient open failed, but another device connected. status={} " - "state={} connected device={}", - p_data->open.status, cb->state, cb->peer_bda); + "HF CLient open failed, but another device connected. status={} " + "state={} connected device={}", + p_data->open.status, cb->state, cb->peer_bda); break; } - HAL_CBACK(bt_hf_client_callbacks, connection_state_cb, &cb->peer_bda, - cb->state, 0, /* peer feat */ + HAL_CBACK(bt_hf_client_callbacks, connection_state_cb, &cb->peer_bda, cb->state, + 0, /* peer feat */ 0 /* AT+CHLD feat */); - if (cb->state == BTHF_CLIENT_CONNECTION_STATE_DISCONNECTED) + if (cb->state == BTHF_CLIENT_CONNECTION_STATE_DISCONNECTED) { cb->peer_bda = RawAddress::kAny; + } - if (p_data->open.status != BTA_HF_CLIENT_SUCCESS) btif_queue_advance(); + if (p_data->open.status != BTA_HF_CLIENT_SUCCESS) { + btif_queue_advance(); + } break; case BTA_HF_CLIENT_CONN_EVT: @@ -889,8 +919,8 @@ static void btif_hf_client_upstreams_evt(uint16_t event, char* p_param) { cb->chld_feat = p_data->conn.chld_feat; cb->state = BTHF_CLIENT_CONNECTION_STATE_SLC_CONNECTED; - HAL_CBACK(bt_hf_client_callbacks, connection_state_cb, &cb->peer_bda, - cb->state, cb->peer_feat, cb->chld_feat); + HAL_CBACK(bt_hf_client_callbacks, connection_state_cb, &cb->peer_bda, cb->state, + cb->peer_feat, cb->chld_feat); /* Inform the application about in-band ringtone */ if (cb->peer_feat & BTA_HF_CLIENT_PEER_INBAND) { @@ -903,8 +933,7 @@ static void btif_hf_client_upstreams_evt(uint16_t event, char* p_param) { case BTA_HF_CLIENT_CLOSE_EVT: cb->state = BTHF_CLIENT_CONNECTION_STATE_DISCONNECTED; - HAL_CBACK(bt_hf_client_callbacks, connection_state_cb, &cb->peer_bda, - cb->state, 0, 0); + HAL_CBACK(bt_hf_client_callbacks, connection_state_cb, &cb->peer_bda, cb->state, 0, 0); cb->peer_bda = RawAddress::kAny; cb->peer_feat = 0; cb->chld_feat = 0; @@ -952,29 +981,25 @@ static void btif_hf_client_upstreams_evt(uint16_t event, char* p_param) { break; case BTA_HF_CLIENT_CLIP_EVT: - HAL_CBACK(bt_hf_client_callbacks, clip_cb, &cb->peer_bda, - p_data->number.number); + HAL_CBACK(bt_hf_client_callbacks, clip_cb, &cb->peer_bda, p_data->number.number); break; case BTA_HF_CLIENT_BINP_EVT: - HAL_CBACK(bt_hf_client_callbacks, last_voice_tag_number_callback, - &cb->peer_bda, p_data->number.number); + HAL_CBACK(bt_hf_client_callbacks, last_voice_tag_number_callback, &cb->peer_bda, + p_data->number.number); break; case BTA_HF_CLIENT_CCWA_EVT: - HAL_CBACK(bt_hf_client_callbacks, call_waiting_cb, &cb->peer_bda, - p_data->number.number); + HAL_CBACK(bt_hf_client_callbacks, call_waiting_cb, &cb->peer_bda, p_data->number.number); break; case BTA_HF_CLIENT_AT_RESULT_EVT: HAL_CBACK(bt_hf_client_callbacks, cmd_complete_cb, &cb->peer_bda, - (bthf_client_cmd_complete_t)p_data->result.type, - p_data->result.cme); + (bthf_client_cmd_complete_t)p_data->result.type, p_data->result.cme); break; case BTA_HF_CLIENT_CLCC_EVT: - HAL_CBACK(bt_hf_client_callbacks, current_calls_cb, &cb->peer_bda, - p_data->clcc.idx, + HAL_CBACK(bt_hf_client_callbacks, current_calls_cb, &cb->peer_bda, p_data->clcc.idx, p_data->clcc.inc ? BTHF_CLIENT_CALL_DIRECTION_INCOMING : BTHF_CLIENT_CALL_DIRECTION_OUTGOING, (bthf_client_call_state_t)p_data->clcc.status, @@ -985,14 +1010,14 @@ static void btif_hf_client_upstreams_evt(uint16_t event, char* p_param) { case BTA_HF_CLIENT_CNUM_EVT: if (p_data->cnum.service == 4) { - HAL_CBACK(bt_hf_client_callbacks, subscriber_info_cb, &cb->peer_bda, - p_data->cnum.number, BTHF_CLIENT_SERVICE_VOICE); + HAL_CBACK(bt_hf_client_callbacks, subscriber_info_cb, &cb->peer_bda, p_data->cnum.number, + BTHF_CLIENT_SERVICE_VOICE); } else if (p_data->cnum.service == 5) { - HAL_CBACK(bt_hf_client_callbacks, subscriber_info_cb, &cb->peer_bda, - p_data->cnum.number, BTHF_CLIENT_SERVICE_FAX); + HAL_CBACK(bt_hf_client_callbacks, subscriber_info_cb, &cb->peer_bda, p_data->cnum.number, + BTHF_CLIENT_SERVICE_FAX); } else { - HAL_CBACK(bt_hf_client_callbacks, subscriber_info_cb, &cb->peer_bda, - p_data->cnum.number, BTHF_CLIENT_SERVICE_UNKNOWN); + HAL_CBACK(bt_hf_client_callbacks, subscriber_info_cb, &cb->peer_bda, p_data->cnum.number, + BTHF_CLIENT_SERVICE_UNKNOWN); } break; @@ -1053,14 +1078,13 @@ static void btif_hf_client_upstreams_evt(uint16_t event, char* p_param) { * ******************************************************************************/ -static void bta_hf_client_evt(tBTA_HF_CLIENT_EVT event, - tBTA_HF_CLIENT* p_data) { +static void bta_hf_client_evt(tBTA_HF_CLIENT_EVT event, tBTA_HF_CLIENT* p_data) { bt_status_t status; /* switch context to btif task context (copy full union size for convenience) */ - status = btif_transfer_context(btif_hf_client_upstreams_evt, (uint16_t)event, - (char*)p_data, sizeof(*p_data), NULL); + status = btif_transfer_context(btif_hf_client_upstreams_evt, (uint16_t)event, (char*)p_data, + sizeof(*p_data), NULL); /* catch any failed context transfers */ ASSERTC(status == BT_STATUS_SUCCESS, "context transfer failed", status); @@ -1080,8 +1104,7 @@ bt_status_t btif_hf_client_execute_service(bool b_enable) { tBTA_HF_CLIENT_FEAT features = get_default_hf_client_features(); uint16_t hfp_version = get_default_hfp_version(); - if (hfp_version >= HFP_VERSION_1_9 && - hfp_hal_interface::get_swb_supported()) { + if (hfp_version >= HFP_VERSION_1_9 && hfp_hal_interface::get_swb_supported()) { features |= BTA_HF_CLIENT_FEAT_SWB; } if (hfp_version >= HFP_VERSION_1_7) { @@ -1091,8 +1114,7 @@ bt_status_t btif_hf_client_execute_service(bool b_enable) { if (b_enable) { /* Enable and register with BTA-HFClient */ log::verbose("support codec negotiation {}", features); - BTA_HfClientEnable(bta_hf_client_evt, features, - BTIF_HF_CLIENT_SERVICE_NAME); + BTA_HfClientEnable(bta_hf_client_evt, features, BTIF_HF_CLIENT_SERVICE_NAME); } else { BTA_HfClientDisable(); } diff --git a/system/btif/src/btif_hh.cc b/system/btif/src/btif_hh.cc index c62bed15882..403e28a7c61 100644 --- a/system/btif/src/btif_hh.cc +++ b/system/btif/src/btif_hh.cc @@ -100,15 +100,13 @@ typedef struct hid_kb_list { btif_hh_cb_t btif_hh_cb; static bthh_callbacks_t* bt_hh_callbacks = NULL; -static bthh_profile_enable_t bt_hh_enable_type = {.hidp_enabled = true, - .hogp_enabled = true}; +static bthh_profile_enable_t bt_hh_enable_type = {.hidp_enabled = true, .hogp_enabled = true}; /* List of HID keyboards for which the NUMLOCK state needs to be * turned ON by default. Add devices to this list to apply the * NUMLOCK state toggle on fpr first connect.*/ -static tHID_KB_LIST hid_kb_numlock_on_list[] = {{LOGITECH_KB_MX5500_PRODUCT_ID, - LOGITECH_KB_MX5500_VENDOR_ID, - "Logitech MX5500 Keyboard"}}; +static tHID_KB_LIST hid_kb_numlock_on_list[] = { + {LOGITECH_KB_MX5500_PRODUCT_ID, LOGITECH_KB_MX5500_VENDOR_ID, "Logitech MX5500 Keyboard"}}; #define CHECK_BTHH_INIT() \ do { \ @@ -131,13 +129,12 @@ static tHID_KB_LIST hid_kb_numlock_on_list[] = {{LOGITECH_KB_MX5500_PRODUCT_ID, #define BTHH_LOG_LINK(_link_spec) \ log::verbose("link spec: {}", (_link_spec).ToRedactedStringForLogging()) -#define BTHH_STATE_UPDATE(_link_spec, _state) \ - do { \ - log::verbose("link spec: {} state: {}", \ - (_link_spec).ToRedactedStringForLogging(), \ - bthh_connection_state_text(_state)); \ - HAL_CBACK(bt_hh_callbacks, connection_state_cb, &(_link_spec).addrt.bda, \ - (_link_spec).addrt.type, (_link_spec).transport, (_state)); \ +#define BTHH_STATE_UPDATE(_link_spec, _state) \ + do { \ + log::verbose("link spec: {} state: {}", (_link_spec).ToRedactedStringForLogging(), \ + bthh_connection_state_text(_state)); \ + HAL_CBACK(bt_hh_callbacks, connection_state_cb, &(_link_spec).addrt.bda, \ + (_link_spec).addrt.type, (_link_spec).transport, (_state)); \ } while (0) /******************************************************************************* @@ -152,9 +149,8 @@ bool check_cod(const RawAddress* remote_bdaddr, uint32_t cod); bool check_cod_hid(const RawAddress* remote_bdaddr); bool check_cod_hid_major(const RawAddress& bd_addr, uint32_t cod); void bta_hh_co_close(btif_hh_device_t* p_dev); -void bta_hh_co_send_hid_info(btif_hh_device_t* p_dev, const char* dev_name, - uint16_t vendor_id, uint16_t product_id, - uint16_t version, uint8_t ctry_code, int dscp_len, +void bta_hh_co_send_hid_info(btif_hh_device_t* p_dev, const char* dev_name, uint16_t vendor_id, + uint16_t product_id, uint16_t version, uint8_t ctry_code, int dscp_len, uint8_t* p_dscp); void bta_hh_co_write(int fd, uint8_t* rpt, uint16_t len); static void bte_hh_evt(tBTA_HH_EVT event, tBTA_HH* p_data); @@ -169,7 +165,9 @@ void btif_hh_timer_timeout(void* data); static int get_keylockstates() { return btif_hh_keylockstates; } static void set_keylockstate(int keymask, bool isSet) { - if (isSet) btif_hh_keylockstates |= keymask; + if (isSet) { + btif_hh_keylockstates |= keymask; + } } /******************************************************************************* @@ -258,7 +256,7 @@ static BT_HDR* create_pbuf(uint16_t len, uint8_t* data) { static void update_keyboard_lockstates(btif_hh_device_t* p_dev) { uint8_t len = 2; /* reportid + 1 byte report*/ BT_HDR* p_buf; - uint8_t data[] = {0x01, /* report id */ + uint8_t data[] = {0x01, /* report id */ static_cast(btif_hh_keylockstates)}; /* keystate */ /* Set report for other keyboards */ @@ -295,15 +293,12 @@ static void sync_lockstate_on_connect(btif_hh_device_t* p_dev) { so the lockstate is in sync */ keylockstates = get_keylockstates(); if (keylockstates) { - log::verbose( - "Sending hid report to kernel indicating lock key state 0x{:x}", - keylockstates); + log::verbose("Sending hid report to kernel indicating lock key state 0x{:x}", keylockstates); usleep(200000); toggle_os_keylockstates(p_dev->uhid.fd, keylockstates); } else { - log::verbose( - "NOT sending hid report to kernel indicating lock key state 0x{:x}", - keylockstates); + log::verbose("NOT sending hid report to kernel indicating lock key state 0x{:x}", + keylockstates); } } @@ -356,8 +351,7 @@ btif_hh_device_t* btif_hh_find_connected_dev_by_handle(uint8_t handle) { btif_hh_device_t* btif_hh_find_dev_by_handle(uint8_t handle) { for (int i = 0; i < BTIF_HH_MAX_HID; i++) { btif_hh_device_t* p_dev = &btif_hh_cb.devices[i]; - if (p_dev->dev_status != BTHH_CONN_STATE_UNKNOWN && - p_dev->dev_handle == handle) { + if (p_dev->dev_status != BTHH_CONN_STATE_UNKNOWN && p_dev->dev_handle == handle) { return p_dev; } } @@ -391,8 +385,7 @@ btif_hh_device_t* btif_hh_find_empty_dev(void) { * * Returns Device entry pointer in the device table ******************************************************************************/ -static btif_hh_device_t* btif_hh_find_dev_by_link_spec( - const tAclLinkSpec& link_spec) { +static btif_hh_device_t* btif_hh_find_dev_by_link_spec(const tAclLinkSpec& link_spec) { uint32_t i; for (i = 0; i < BTIF_HH_MAX_HID; i++) { if (btif_hh_cb.devices[i].dev_status != BTHH_CONN_STATE_UNKNOWN && @@ -412,8 +405,7 @@ static btif_hh_device_t* btif_hh_find_dev_by_link_spec( * * Returns Device entry pointer in the device table ******************************************************************************/ -static btif_hh_device_t* btif_hh_find_connected_dev_by_link_spec( - const tAclLinkSpec& link_spec) { +static btif_hh_device_t* btif_hh_find_connected_dev_by_link_spec(const tAclLinkSpec& link_spec) { uint32_t i; for (i = 0; i < BTIF_HH_MAX_HID; i++) { if (btif_hh_cb.devices[i].dev_status == BTHH_CONN_STATE_CONNECTED && @@ -428,7 +420,7 @@ static btif_hh_device_t* btif_hh_find_connected_dev_by_link_spec( * * Function btif_hh_stop_vup_timer * - * Description stop vitual unplug timer + * Description stop virtual unplug timer * * Returns void ******************************************************************************/ @@ -457,27 +449,23 @@ static void btif_hh_start_vup_timer(const tAclLinkSpec& link_spec) { alarm_free(p_dev->vup_timer); p_dev->vup_timer = alarm_new("btif_hh.vup_timer"); - alarm_set_on_mloop(p_dev->vup_timer, BTIF_TIMEOUT_VUP_MS, - btif_hh_timer_timeout, p_dev); + alarm_set_on_mloop(p_dev->vup_timer, BTIF_TIMEOUT_VUP_MS, btif_hh_timer_timeout, p_dev); } -static bthh_connection_state_t hh_get_state_on_disconnect( - tAclLinkSpec& link_spec) { +static bthh_connection_state_t hh_get_state_on_disconnect(tAclLinkSpec& link_spec) { if (!com::android::bluetooth::flags::allow_switching_hid_and_hogp()) { return BTHH_CONN_STATE_ACCEPTING; } btif_hh_added_device_t* added_dev = btif_hh_find_added_dev(link_spec); if (added_dev != nullptr) { - return added_dev->reconnect_allowed ? BTHH_CONN_STATE_ACCEPTING - : BTHH_CONN_STATE_DISCONNECTED; + return added_dev->reconnect_allowed ? BTHH_CONN_STATE_ACCEPTING : BTHH_CONN_STATE_DISCONNECTED; } else { return BTHH_CONN_STATE_DISCONNECTED; } } -static void hh_connect_complete(uint8_t handle, tAclLinkSpec& link_spec, - BTIF_HH_STATUS status) { +static void hh_connect_complete(uint8_t handle, tAclLinkSpec& link_spec, BTIF_HH_STATUS status) { bthh_connection_state_t state = BTHH_CONN_STATE_CONNECTED; btif_hh_cb.status = status; @@ -490,13 +478,11 @@ static void hh_connect_complete(uint8_t handle, tAclLinkSpec& link_spec, static void hh_open_handler(tBTA_HH_CONN& conn) { log::debug("link spec = {}, status = {}, handle = {}", - conn.link_spec.ToRedactedStringForLogging(), conn.status, - conn.handle); + conn.link_spec.ToRedactedStringForLogging(), conn.status, conn.handle); if (com::android::bluetooth::flags::allow_switching_hid_and_hogp()) { // Initialize with disconnected/accepting state based on reconnection policy - bthh_connection_state_t dev_status = - hh_get_state_on_disconnect(conn.link_spec); + bthh_connection_state_t dev_status = hh_get_state_on_disconnect(conn.link_spec); // Use current state if the device instance already exists btif_hh_device_t* p_dev = btif_hh_find_dev_by_link_spec(conn.link_spec); @@ -514,22 +500,20 @@ static void hh_open_handler(tBTA_HH_CONN& conn) { dev_status = BTHH_CONN_STATE_CONNECTING; } - if (dev_status != BTHH_CONN_STATE_ACCEPTING && - dev_status != BTHH_CONN_STATE_CONNECTING) { + if (dev_status != BTHH_CONN_STATE_ACCEPTING && dev_status != BTHH_CONN_STATE_CONNECTING) { log::warn("Reject Incoming HID Connection, device: {}, state: {}", conn.link_spec.ToRedactedStringForLogging(), bthh_connection_state_text(dev_status)); - log_counter_metrics_btif(android::bluetooth::CodePathCounterKeyEnum:: - HIDH_COUNT_INCOMING_CONNECTION_REJECTED, - 1); + log_counter_metrics_btif( + android::bluetooth::CodePathCounterKeyEnum::HIDH_COUNT_INCOMING_CONNECTION_REJECTED, + 1); if (p_dev != nullptr) { p_dev->dev_status = BTHH_CONN_STATE_DISCONNECTED; } if (!com::android::bluetooth::flags::suppress_hid_rejection_broadcast()) { - hh_connect_complete(conn.handle, conn.link_spec, - BTIF_HH_DEV_DISCONNECTED); + hh_connect_complete(conn.handle, conn.link_spec, BTIF_HH_DEV_DISCONNECTED); return; } BTA_HhClose(conn.handle); @@ -556,8 +540,7 @@ static void hh_open_handler(tBTA_HH_CONN& conn) { } /* Initialize device driver */ - if (!bta_hh_co_open(conn.handle, conn.sub_class, conn.attr_mask, conn.app_id, - conn.link_spec)) { + if (!bta_hh_co_open(conn.handle, conn.sub_class, conn.attr_mask, conn.app_id, conn.link_spec)) { log::warn("Failed to find the uhid driver"); hh_connect_complete(conn.handle, conn.link_spec, BTIF_HH_DEV_DISCONNECTED); return; @@ -593,14 +576,13 @@ static void hh_open_handler(tBTA_HH_CONN& conn) { * * Returns true if add successfully, otherwise false. ******************************************************************************/ -static bool hh_add_device(const tAclLinkSpec& link_spec, - tBTA_HH_ATTR_MASK attr_mask, bool reconnect_allowed) { +static bool hh_add_device(const tAclLinkSpec& link_spec, tBTA_HH_ATTR_MASK attr_mask, + bool reconnect_allowed) { int i; // Check if already added if (btif_hh_find_added_dev(link_spec) != nullptr) { - log::warn("Device {} already added", - link_spec.ToRedactedStringForLogging()); + log::warn("Device {} already added", link_spec.ToRedactedStringForLogging()); return false; } @@ -618,15 +600,13 @@ static bool hh_add_device(const tAclLinkSpec& link_spec, } log::error("Out of space to add device"); - log_counter_metrics_btif(android::bluetooth::CodePathCounterKeyEnum:: - HIDH_COUNT_MAX_ADDED_DEVICE_LIMIT_REACHED, - 1); + log_counter_metrics_btif( + android::bluetooth::CodePathCounterKeyEnum::HIDH_COUNT_MAX_ADDED_DEVICE_LIMIT_REACHED, 1); return false; } -void btif_hh_load_bonded_dev(const tAclLinkSpec& link_spec_ref, - tBTA_HH_ATTR_MASK attr_mask, uint8_t sub_class, - uint8_t app_id, tBTA_HH_DEV_DSCP_INFO dscp_info, +void btif_hh_load_bonded_dev(const tAclLinkSpec& link_spec_ref, tBTA_HH_ATTR_MASK attr_mask, + uint8_t sub_class, uint8_t app_id, tBTA_HH_DEV_DSCP_INFO dscp_info, bool reconnect_allowed) { btif_hh_device_t* p_dev; uint8_t i; @@ -642,16 +622,14 @@ void btif_hh_load_bonded_dev(const tAclLinkSpec& link_spec_ref, // remove and re-write the hid info btif_storage_remove_hid_info(link_spec); - btif_storage_add_hid_device_info( - link_spec, attr_mask, sub_class, app_id, dscp_info.vendor_id, - dscp_info.product_id, dscp_info.version, dscp_info.ctry_code, - dscp_info.ssr_max_latency, dscp_info.ssr_min_tout, - dscp_info.descriptor.dl_len, dscp_info.descriptor.dsc_list); + btif_storage_add_hid_device_info(link_spec, attr_mask, sub_class, app_id, dscp_info.vendor_id, + dscp_info.product_id, dscp_info.version, dscp_info.ctry_code, + dscp_info.ssr_max_latency, dscp_info.ssr_min_tout, + dscp_info.descriptor.dl_len, dscp_info.descriptor.dsc_list); } if (hh_add_device(link_spec, attr_mask, reconnect_allowed)) { - if (com::android::bluetooth::flags::allow_switching_hid_and_hogp() && - reconnect_allowed) { + if (com::android::bluetooth::flags::allow_switching_hid_and_hogp() && reconnect_allowed) { BTHH_STATE_UPDATE(link_spec, BTHH_CONN_STATE_ACCEPTING); } BTA_HhAddDev(link_spec, attr_mask, sub_class, app_id, dscp_info); @@ -695,10 +673,10 @@ void btif_hh_remove_device(const tAclLinkSpec& link_spec) { * with up-layer */ do_in_jni_thread(base::Bind( - [](tAclLinkSpec link_spec) { - BTHH_STATE_UPDATE(link_spec, BTHH_CONN_STATE_DISCONNECTED); - }, - link_spec)); + [](tAclLinkSpec link_spec) { + BTHH_STATE_UPDATE(link_spec, BTHH_CONN_STATE_DISCONNECTED); + }, + link_spec)); if (btif_hh_cb.device_num > 0) { btif_hh_cb.device_num--; @@ -712,15 +690,13 @@ void btif_hh_remove_device(const tAclLinkSpec& link_spec) { } } -bool btif_hh_copy_hid_info(tBTA_HH_DEV_DSCP_INFO* dest, - tBTA_HH_DEV_DSCP_INFO* src) { +bool btif_hh_copy_hid_info(tBTA_HH_DEV_DSCP_INFO* dest, tBTA_HH_DEV_DSCP_INFO* src) { memset(dest, 0, sizeof(tBTA_HH_DEV_DSCP_INFO)); dest->descriptor.dl_len = 0; if (src->descriptor.dl_len > 0) { dest->descriptor.dsc_list = (uint8_t*)osi_malloc(src->descriptor.dl_len); } - memcpy(dest->descriptor.dsc_list, src->descriptor.dsc_list, - src->descriptor.dl_len); + memcpy(dest->descriptor.dsc_list, src->descriptor.dsc_list, src->descriptor.dl_len); dest->descriptor.dl_len = src->descriptor.dl_len; dest->vendor_id = src->vendor_id; dest->product_id = src->product_id; @@ -755,8 +731,7 @@ bt_status_t btif_hh_virtual_unplug(const tAclLinkSpec& link_spec) { p_dev->local_vup = true; BTA_HhSendCtrl(p_dev->dev_handle, BTA_HH_CTRL_VIRTUAL_CABLE_UNPLUG); return BT_STATUS_SUCCESS; - } else if ((p_dev != NULL) && - (p_dev->dev_status == BTHH_CONN_STATE_CONNECTED)) { + } else if ((p_dev != NULL) && (p_dev->dev_status == BTHH_CONN_STATE_CONNECTED)) { log::error("Virtual unplug not supported, disconnecting device: {}", link_spec.ToRedactedStringForLogging()); /* start the timer */ @@ -765,8 +740,7 @@ bt_status_t btif_hh_virtual_unplug(const tAclLinkSpec& link_spec) { BTA_HhClose(p_dev->dev_handle); return BT_STATUS_SUCCESS; } else { - log::error("Error, device {} not opened, status = {}", - link_spec.ToRedactedStringForLogging(), + log::error("Error, device {} not opened, status = {}", link_spec.ToRedactedStringForLogging(), btif_hh_status_text(btif_hh_cb.status)); if ((btif_hh_cb.pending_link_spec.addrt.bda == link_spec.addrt.bda) && (btif_hh_cb.status == BTIF_HH_DEV_CONNECTING)) { @@ -776,10 +750,10 @@ bt_status_t btif_hh_virtual_unplug(const tAclLinkSpec& link_spec) { /* need to notify up-layer device is disconnected to avoid * state out of sync with up-layer */ do_in_jni_thread(base::Bind( - [](tAclLinkSpec link_spec) { - BTHH_STATE_UPDATE(link_spec, BTHH_CONN_STATE_DISCONNECTED); - }, - link_spec)); + [](tAclLinkSpec link_spec) { + BTHH_STATE_UPDATE(link_spec, BTHH_CONN_STATE_DISCONNECTED); + }, + link_spec)); } return BT_STATUS_DEVICE_NOT_FOUND; } @@ -801,24 +775,21 @@ bt_status_t btif_hh_connect(const tAclLinkSpec& link_spec) { btif_hh_device_t* p_dev = btif_hh_find_dev_by_link_spec(link_spec); if (!p_dev && btif_hh_cb.device_num >= BTIF_HH_MAX_HID) { // No space for more HID device now. - log::warn("Error, exceeded the maximum supported HID device number {}", - BTIF_HH_MAX_HID); - log_counter_metrics_btif( - android::bluetooth::CodePathCounterKeyEnum:: - HIDH_COUNT_CONNECT_REQ_WHEN_MAX_DEVICE_LIMIT_REACHED, - 1); + log::warn("Error, exceeded the maximum supported HID device number {}", BTIF_HH_MAX_HID); + log_counter_metrics_btif(android::bluetooth::CodePathCounterKeyEnum:: + HIDH_COUNT_CONNECT_REQ_WHEN_MAX_DEVICE_LIMIT_REACHED, + 1); return BT_STATUS_NOMEM; } btif_hh_added_device_t* added_dev = btif_hh_find_added_dev(link_spec); if (added_dev != nullptr) { - log::info("Device {} already added, attr_mask = 0x{:x}", - link_spec.ToRedactedStringForLogging(), added_dev->attr_mask); + log::info("Device {} already added, attr_mask = 0x{:x}", link_spec.ToRedactedStringForLogging(), + added_dev->attr_mask); if (added_dev->dev_handle == BTA_HH_INVALID_HANDLE) { // No space for more HID device now. - log::error("Device {} added but addition failed", - link_spec.ToRedactedStringForLogging()); + log::error("Device {} added but addition failed", link_spec.ToRedactedStringForLogging()); added_dev->link_spec = {}; added_dev->dev_handle = BTA_HH_INVALID_HANDLE; return BT_STATUS_NOMEM; @@ -832,8 +803,7 @@ bt_status_t btif_hh_connect(const tAclLinkSpec& link_spec) { } if (p_dev && p_dev->dev_status == BTHH_CONN_STATE_CONNECTED) { - log::debug("HidHost profile already connected for {}", - link_spec.ToRedactedStringForLogging()); + log::debug("HidHost profile already connected for {}", link_spec.ToRedactedStringForLogging()); return BT_STATUS_SUCCESS; } @@ -850,10 +820,8 @@ bt_status_t btif_hh_connect(const tAclLinkSpec& link_spec) { BTA_HhOpen(btif_hh_cb.pending_link_spec); do_in_jni_thread(base::Bind( - [](tAclLinkSpec link_spec) { - BTHH_STATE_UPDATE(link_spec, BTHH_CONN_STATE_CONNECTING); - }, - link_spec)); + [](tAclLinkSpec link_spec) { BTHH_STATE_UPDATE(link_spec, BTHH_CONN_STATE_CONNECTING); }, + link_spec)); return BT_STATUS_SUCCESS; } @@ -869,8 +837,7 @@ bt_status_t btif_hh_connect(const tAclLinkSpec& link_spec) { void btif_hh_disconnect(const tAclLinkSpec& link_spec) { btif_hh_device_t* p_dev = btif_hh_find_connected_dev_by_link_spec(link_spec); if (p_dev == nullptr) { - log::warn("Unable to disconnect unknown HID device:{}", - link_spec.ToRedactedStringForLogging()); + log::warn("Unable to disconnect unknown HID device:{}", link_spec.ToRedactedStringForLogging()); return; } log::debug("Disconnect and close request for HID device:{}", @@ -887,8 +854,8 @@ void btif_hh_disconnect(const tAclLinkSpec& link_spec) { * Returns void * ******************************************************************************/ -void btif_hh_setreport(btif_hh_uhid_t* p_uhid, bthh_report_type_t r_type, - uint16_t size, uint8_t* report) { +void btif_hh_setreport(btif_hh_uhid_t* p_uhid, bthh_report_type_t r_type, uint16_t size, + uint8_t* report) { BT_HDR* p_buf = create_pbuf(size, report); if (p_buf == NULL) { log::error("Error, failed to allocate RPT buffer, size = {}", size); @@ -937,8 +904,7 @@ void btif_hh_service_registration(bool enable) { btif_hd_service_registration(); } } else if (enable) { - BTA_HhEnable(bte_hh_evt, bt_hh_enable_type.hidp_enabled, - bt_hh_enable_type.hogp_enabled); + BTA_HhEnable(bte_hh_evt, bt_hh_enable_type.hidp_enabled, bt_hh_enable_type.hogp_enabled); } else { btif_hh_cb.service_dereg_active = TRUE; BTA_HhDisable(); @@ -955,8 +921,8 @@ void btif_hh_service_registration(bool enable) { * Returns void * ******************************************************************************/ -void btif_hh_getreport(btif_hh_uhid_t* p_uhid, bthh_report_type_t r_type, - uint8_t reportId, uint16_t bufferSize) { +void btif_hh_getreport(btif_hh_uhid_t* p_uhid, bthh_report_type_t r_type, uint8_t reportId, + uint16_t bufferSize) { BTA_HhGetReport(p_uhid->dev_handle, r_type, reportId, bufferSize); } @@ -983,8 +949,7 @@ static void btif_hh_upstreams_evt(uint16_t event, char* p_param) { tBTA_HH* p_data = (tBTA_HH*)p_param; btif_hh_device_t* p_dev = NULL; - log::verbose("event={} dereg = {}", bta_hh_event_text(event), - btif_hh_cb.service_dereg_active); + log::verbose("event={} dereg = {}", bta_hh_event_text(event), btif_hh_cb.service_dereg_active); switch (event) { case BTA_HH_ENABLE_EVT: @@ -996,8 +961,7 @@ static void btif_hh_upstreams_evt(uint16_t event, char* p_param) { btif_storage_load_bonded_hid_info(); } else { btif_hh_cb.status = BTIF_HH_DISABLED; - log::warn("BTA_HH_ENABLE_EVT: HH enabling failed, status = {}", - p_data->status); + log::warn("BTA_HH_ENABLE_EVT: HH enabling failed, status = {}", p_data->status); } break; @@ -1023,8 +987,7 @@ static void btif_hh_upstreams_evt(uint16_t event, char* p_param) { btif_hh_cb.devices[i].dev_status = BTHH_CONN_STATE_UNKNOWN; } } else { - log::warn("BTA_HH_DISABLE_EVT: HH disabling failed, status = {}", - p_data->status); + log::warn("BTA_HH_DISABLE_EVT: HH disabling failed, status = {}", p_data->status); } break; @@ -1033,13 +996,12 @@ static void btif_hh_upstreams_evt(uint16_t event, char* p_param) { break; case BTA_HH_CLOSE_EVT: - log::verbose("BTA_HH_CLOSE_EVT: status = {}, handle = {}", - p_data->dev_status.status, p_data->dev_status.handle); + log::verbose("BTA_HH_CLOSE_EVT: status = {}, handle = {}", p_data->dev_status.status, + p_data->dev_status.handle); p_dev = btif_hh_find_connected_dev_by_handle(p_data->dev_status.handle); if (p_dev != NULL) { BTHH_STATE_UPDATE(p_dev->link_spec, BTHH_CONN_STATE_DISCONNECTING); - log::verbose("uhid fd={} local_vup={}", p_dev->uhid.fd, - p_dev->local_vup); + log::verbose("uhid fd={} local_vup={}", p_dev->uhid.fd, p_dev->local_vup); btif_hh_stop_vup_timer(p_dev->link_spec); /* If this is a locally initiated VUP, remove the bond as ACL got * disconnected while VUP being processed. @@ -1050,9 +1012,8 @@ static void btif_hh_upstreams_evt(uint16_t event, char* p_param) { } else if (p_data->dev_status.status == BTA_HH_HS_SERVICE_CHANGED) { /* Local disconnection due to service change in the HOGP device. HID descriptor would be read again, so remove it from cache. */ - log::warn( - "Removing cached descriptor due to service change, handle = {}", - p_data->dev_status.handle); + log::warn("Removing cached descriptor due to service change, handle = {}", + p_data->dev_status.handle); btif_storage_remove_hid_info(p_dev->link_spec); } @@ -1062,14 +1023,13 @@ static void btif_hh_upstreams_evt(uint16_t event, char* p_param) { bta_hh_co_close(p_dev); BTHH_STATE_UPDATE(p_dev->link_spec, p_dev->dev_status); } else { - log::warn("Error: cannot find device with handle {}", - p_data->dev_status.handle); + log::warn("Error: cannot find device with handle {}", p_data->dev_status.handle); } break; case BTA_HH_GET_RPT_EVT: { - log::verbose("BTA_HH_GET_RPT_EVT: status = {}, handle = {}", - p_data->hs_data.status, p_data->hs_data.handle); + log::verbose("BTA_HH_GET_RPT_EVT: status = {}, handle = {}", p_data->hs_data.status, + p_data->hs_data.handle); p_dev = btif_hh_find_connected_dev_by_handle(p_data->hs_data.handle); if (p_dev) { BT_HDR* hdr = p_data->hs_data.rsp_data.p_rpt_data; @@ -1077,34 +1037,29 @@ static void btif_hh_upstreams_evt(uint16_t event, char* p_param) { if (hdr) { /* Get report response */ uint8_t* data = (uint8_t*)(hdr + 1) + hdr->offset; uint16_t len = hdr->len; - HAL_CBACK(bt_hh_callbacks, get_report_cb, - (RawAddress*)&(p_dev->link_spec.addrt.bda), + HAL_CBACK(bt_hh_callbacks, get_report_cb, (RawAddress*)&(p_dev->link_spec.addrt.bda), p_dev->link_spec.addrt.type, p_dev->link_spec.transport, (bthh_status_t)p_data->hs_data.status, data, len); - bta_hh_co_get_rpt_rsp(p_dev->dev_handle, - (tBTA_HH_STATUS)p_data->hs_data.status, data, + bta_hh_co_get_rpt_rsp(p_dev->dev_handle, (tBTA_HH_STATUS)p_data->hs_data.status, data, len); } else { /* Handshake */ - HAL_CBACK(bt_hh_callbacks, handshake_cb, - (RawAddress*)&(p_dev->link_spec.addrt.bda), + HAL_CBACK(bt_hh_callbacks, handshake_cb, (RawAddress*)&(p_dev->link_spec.addrt.bda), p_dev->link_spec.addrt.type, p_dev->link_spec.transport, (bthh_status_t)p_data->hs_data.status); } } else { - log::warn("Error: cannot find device with handle {}", - p_data->hs_data.handle); + log::warn("Error: cannot find device with handle {}", p_data->hs_data.handle); } break; } case BTA_HH_SET_RPT_EVT: - log::verbose("BTA_HH_SET_RPT_EVT: status = {}, handle = {}", - p_data->dev_status.status, p_data->dev_status.handle); + log::verbose("BTA_HH_SET_RPT_EVT: status = {}, handle = {}", p_data->dev_status.status, + p_data->dev_status.handle); p_dev = btif_hh_find_connected_dev_by_handle(p_data->dev_status.handle); if (p_dev != NULL) { - HAL_CBACK(bt_hh_callbacks, handshake_cb, - (RawAddress*)&(p_dev->link_spec.addrt.bda), + HAL_CBACK(bt_hh_callbacks, handshake_cb, (RawAddress*)&(p_dev->link_spec.addrt.bda), p_dev->link_spec.addrt.type, p_dev->link_spec.transport, (bthh_status_t)p_data->hs_data.status); @@ -1119,36 +1074,29 @@ static void btif_hh_upstreams_evt(uint16_t event, char* p_param) { p_data->hs_data.handle); return; } - log::warn( - "BTA_HH_GET_PROTO_EVT: status = {}, handle = {}, proto = [{}], {}", - p_data->hs_data.status, p_data->hs_data.handle, - p_data->hs_data.rsp_data.proto_mode, - (p_data->hs_data.rsp_data.proto_mode == BTA_HH_PROTO_RPT_MODE) - ? "Report Mode" - : (p_data->hs_data.rsp_data.proto_mode == BTA_HH_PROTO_BOOT_MODE) - ? "Boot Mode" - : "Unsupported"); + log::warn("BTA_HH_GET_PROTO_EVT: status = {}, handle = {}, proto = [{}], {}", + p_data->hs_data.status, p_data->hs_data.handle, p_data->hs_data.rsp_data.proto_mode, + (p_data->hs_data.rsp_data.proto_mode == BTA_HH_PROTO_RPT_MODE) ? "Report Mode" + : (p_data->hs_data.rsp_data.proto_mode == BTA_HH_PROTO_BOOT_MODE) ? "Boot Mode" + : "Unsupported"); if (p_data->hs_data.rsp_data.proto_mode != BTA_HH_PROTO_UNKNOWN) { - HAL_CBACK(bt_hh_callbacks, protocol_mode_cb, - (RawAddress*)&(p_dev->link_spec.addrt.bda), + HAL_CBACK(bt_hh_callbacks, protocol_mode_cb, (RawAddress*)&(p_dev->link_spec.addrt.bda), p_dev->link_spec.addrt.type, p_dev->link_spec.transport, (bthh_status_t)p_data->hs_data.status, (bthh_protocol_mode_t)p_data->hs_data.rsp_data.proto_mode); } else { - HAL_CBACK(bt_hh_callbacks, handshake_cb, - (RawAddress*)&(p_dev->link_spec.addrt.bda), + HAL_CBACK(bt_hh_callbacks, handshake_cb, (RawAddress*)&(p_dev->link_spec.addrt.bda), p_dev->link_spec.addrt.type, p_dev->link_spec.transport, (bthh_status_t)p_data->hs_data.status); } break; case BTA_HH_SET_PROTO_EVT: - log::verbose("BTA_HH_SET_PROTO_EVT: status = {}, handle = {}", - p_data->dev_status.status, p_data->dev_status.handle); + log::verbose("BTA_HH_SET_PROTO_EVT: status = {}, handle = {}", p_data->dev_status.status, + p_data->dev_status.handle); p_dev = btif_hh_find_connected_dev_by_handle(p_data->dev_status.handle); if (p_dev) { - HAL_CBACK(bt_hh_callbacks, handshake_cb, - (RawAddress*)&(p_dev->link_spec.addrt.bda), + HAL_CBACK(bt_hh_callbacks, handshake_cb, (RawAddress*)&(p_dev->link_spec.addrt.bda), p_dev->link_spec.addrt.type, p_dev->link_spec.transport, (bthh_status_t)p_data->hs_data.status); } @@ -1160,24 +1108,21 @@ static void btif_hh_upstreams_evt(uint16_t event, char* p_param) { p_data->hs_data.rsp_data.idle_rate); p_dev = btif_hh_find_connected_dev_by_handle(p_data->hs_data.handle); if (p_dev) { - HAL_CBACK(bt_hh_callbacks, idle_time_cb, - (RawAddress*)&(p_dev->link_spec.addrt.bda), + HAL_CBACK(bt_hh_callbacks, idle_time_cb, (RawAddress*)&(p_dev->link_spec.addrt.bda), p_dev->link_spec.addrt.type, p_dev->link_spec.transport, - (bthh_status_t)p_data->hs_data.status, - p_data->hs_data.rsp_data.idle_rate); + (bthh_status_t)p_data->hs_data.status, p_data->hs_data.rsp_data.idle_rate); } break; case BTA_HH_SET_IDLE_EVT: - log::verbose("BTA_HH_SET_IDLE_EVT: status = {}, handle = {}", - p_data->dev_status.status, p_data->dev_status.handle); + log::verbose("BTA_HH_SET_IDLE_EVT: status = {}, handle = {}", p_data->dev_status.status, + p_data->dev_status.handle); break; case BTA_HH_GET_DSCP_EVT: { uint8_t hid_handle = p_data->dscp_info.hid_handle; int len = p_data->dscp_info.descriptor.dl_len; - log::verbose("BTA_HH_GET_DSCP_EVT: len = {}, handle = {}", len, - hid_handle); + log::verbose("BTA_HH_GET_DSCP_EVT: len = {}, handle = {}", len, hid_handle); p_dev = btif_hh_find_connected_dev_by_handle(hid_handle); if (p_dev == NULL) { @@ -1194,10 +1139,9 @@ static void btif_hh_upstreams_evt(uint16_t event, char* p_param) { const char* cached_name = NULL; bt_bdname_t bdname; bt_property_t prop_name; - BTIF_STORAGE_FILL_PROPERTY(&prop_name, BT_PROPERTY_BDNAME, - sizeof(bt_bdname_t), &bdname); - if (btif_storage_get_remote_device_property( - &p_dev->link_spec.addrt.bda, &prop_name) == BT_STATUS_SUCCESS) { + BTIF_STORAGE_FILL_PROPERTY(&prop_name, BT_PROPERTY_BDNAME, sizeof(bt_bdname_t), &bdname); + if (btif_storage_get_remote_device_property(&p_dev->link_spec.addrt.bda, &prop_name) == + BT_STATUS_SUCCESS) { cached_name = (char*)bdname.name; } else { cached_name = "Bluetooth HID"; @@ -1205,8 +1149,7 @@ static void btif_hh_upstreams_evt(uint16_t event, char* p_param) { log::warn("name = {}", cached_name); bta_hh_co_send_hid_info(p_dev, cached_name, p_data->dscp_info.vendor_id, - p_data->dscp_info.product_id, - p_data->dscp_info.version, + p_data->dscp_info.product_id, p_data->dscp_info.version, p_data->dscp_info.ctry_code, len, p_data->dscp_info.descriptor.dsc_list); if (hh_add_device(p_dev->link_spec, p_dev->attr_mask, true)) { @@ -1215,20 +1158,19 @@ static void btif_hh_upstreams_evt(uint16_t event, char* p_param) { btif_hh_copy_hid_info(&dscp_info, &p_data->dscp_info); log::verbose("BTA_HH_GET_DSCP_EVT: link spec = {}", p_dev->link_spec.ToRedactedStringForLogging()); - BTA_HhAddDev(p_dev->link_spec, p_dev->attr_mask, p_dev->sub_class, - p_dev->app_id, dscp_info); + BTA_HhAddDev(p_dev->link_spec, p_dev->attr_mask, p_dev->sub_class, p_dev->app_id, + dscp_info); // write hid info to nvram ret = btif_storage_add_hid_device_info( - p_dev->link_spec, p_dev->attr_mask, p_dev->sub_class, p_dev->app_id, - p_data->dscp_info.vendor_id, p_data->dscp_info.product_id, - p_data->dscp_info.version, p_data->dscp_info.ctry_code, - p_data->dscp_info.ssr_max_latency, p_data->dscp_info.ssr_min_tout, - len, p_data->dscp_info.descriptor.dsc_list); + p_dev->link_spec, p_dev->attr_mask, p_dev->sub_class, p_dev->app_id, + p_data->dscp_info.vendor_id, p_data->dscp_info.product_id, + p_data->dscp_info.version, p_data->dscp_info.ctry_code, + p_data->dscp_info.ssr_max_latency, p_data->dscp_info.ssr_min_tout, len, + p_data->dscp_info.descriptor.dsc_list); // Allow incoming connections if (com::android::bluetooth::flags::allow_switching_hid_and_hogp() && - com::android::bluetooth::flags:: - save_initial_hid_connection_policy()) { + com::android::bluetooth::flags::save_initial_hid_connection_policy()) { btif_storage_set_hid_connection_policy(p_dev->link_spec, true); } @@ -1236,8 +1178,7 @@ static void btif_hh_upstreams_evt(uint16_t event, char* p_param) { log::warn("BTA_HH_GET_DSCP_EVT: Called add device"); // Free buffer created for dscp_info; - if (dscp_info.descriptor.dl_len > 0 && - dscp_info.descriptor.dsc_list != NULL) { + if (dscp_info.descriptor.dl_len > 0 && dscp_info.descriptor.dsc_list != NULL) { osi_free_and_reset((void**)&dscp_info.descriptor.dsc_list); dscp_info.descriptor.dl_len = 0; } @@ -1249,10 +1190,8 @@ static void btif_hh_upstreams_evt(uint16_t event, char* p_param) { /*Sync HID Keyboard lockstates */ int tmplen = sizeof(hid_kb_numlock_on_list) / sizeof(tHID_KB_LIST); for (int i = 0; i < tmplen; i++) { - if (p_data->dscp_info.vendor_id == - hid_kb_numlock_on_list[i].version_id && - p_data->dscp_info.product_id == - hid_kb_numlock_on_list[i].product_id) { + if (p_data->dscp_info.vendor_id == hid_kb_numlock_on_list[i].version_id && + p_data->dscp_info.product_id == hid_kb_numlock_on_list[i].product_id) { log::verbose("idx[{}] Enabling NUMLOCK for device :: {}", i, hid_kb_numlock_on_list[i].kb_name); /* Enable NUMLOCK by default so that numeric @@ -1266,10 +1205,9 @@ static void btif_hh_upstreams_evt(uint16_t event, char* p_param) { } break; case BTA_HH_ADD_DEV_EVT: { - log::info("BTA_HH_ADD_DEV_EVT: status = {}, handle = {}", - p_data->dev_info.status, p_data->dev_info.handle); - btif_hh_added_device_t* added_dev = - btif_hh_find_added_dev(p_data->dev_info.link_spec); + log::info("BTA_HH_ADD_DEV_EVT: status = {}, handle = {}", p_data->dev_info.status, + p_data->dev_info.handle); + btif_hh_added_device_t* added_dev = btif_hh_find_added_dev(p_data->dev_info.link_spec); if (added_dev != nullptr) { if (p_data->dev_info.status == BTA_HH_OK) { added_dev->dev_handle = p_data->dev_info.handle; @@ -1280,20 +1218,18 @@ static void btif_hh_upstreams_evt(uint16_t event, char* p_param) { } } break; case BTA_HH_RMV_DEV_EVT: - log::verbose( - "BTA_HH_RMV_DEV_EVT: status = {}, handle = {}, link spec = {}", - p_data->dev_info.status, p_data->dev_info.handle, - p_data->dev_info.link_spec.ToRedactedStringForLogging()); + log::verbose("BTA_HH_RMV_DEV_EVT: status = {}, handle = {}, link spec = {}", + p_data->dev_info.status, p_data->dev_info.handle, + p_data->dev_info.link_spec.ToRedactedStringForLogging()); break; case BTA_HH_VC_UNPLUG_EVT: - log::verbose("BTA_HH_VC_UNPLUG_EVT: status = {}, handle = {}", - p_data->dev_status.status, p_data->dev_status.handle); + log::verbose("BTA_HH_VC_UNPLUG_EVT: status = {}, handle = {}", p_data->dev_status.status, + p_data->dev_status.handle); p_dev = btif_hh_find_connected_dev_by_handle(p_data->dev_status.handle); if (p_dev == NULL) { - log::error("BTA_HH_VC_UNPLUG_EVT: device not found handle {}", - p_data->dev_status.handle); + log::error("BTA_HH_VC_UNPLUG_EVT: device not found handle {}", p_data->dev_status.handle); return; } @@ -1318,15 +1254,13 @@ static void btif_hh_upstreams_evt(uint16_t event, char* p_param) { p_dev->local_vup = false; BTA_DmRemoveDevice(p_dev->link_spec.addrt.bda); } else { - log_counter_metrics_btif( - android::bluetooth::CodePathCounterKeyEnum:: - HIDH_COUNT_VIRTUAL_UNPLUG_REQUESTED_BY_REMOTE_DEVICE, - 1); + log_counter_metrics_btif(android::bluetooth::CodePathCounterKeyEnum:: + HIDH_COUNT_VIRTUAL_UNPLUG_REQUESTED_BY_REMOTE_DEVICE, + 1); btif_hh_remove_device(p_dev->link_spec); } - HAL_CBACK(bt_hh_callbacks, virtual_unplug_cb, - &(p_dev->link_spec.addrt.bda), p_dev->link_spec.addrt.type, - p_dev->link_spec.transport, + HAL_CBACK(bt_hh_callbacks, virtual_unplug_cb, &(p_dev->link_spec.addrt.bda), + p_dev->link_spec.addrt.type, p_dev->link_spec.transport, (bthh_status_t)p_data->dev_status.status); break; @@ -1350,8 +1284,7 @@ static void btif_hh_upstreams_evt(uint16_t event, char* p_param) { * ******************************************************************************/ -static void btif_hh_hsdata_rpt_copy_cb(uint16_t event, char* p_dest, - const char* p_src) { +static void btif_hh_hsdata_rpt_copy_cb(uint16_t event, char* p_dest, const char* p_src) { tBTA_HH_HSDATA* p_dst_data = (tBTA_HH_HSDATA*)p_dest; tBTA_HH_HSDATA* p_src_data = (tBTA_HH_HSDATA*)p_src; BT_HDR* hdr; @@ -1387,19 +1320,19 @@ static void bte_hh_evt(tBTA_HH_EVT event, tBTA_HH* p_data) { int param_len = 0; tBTIF_COPY_CBACK* p_copy_cback = NULL; - if (BTA_HH_ENABLE_EVT == event) + if (BTA_HH_ENABLE_EVT == event) { param_len = sizeof(tBTA_HH_STATUS); - else if (BTA_HH_OPEN_EVT == event) + } else if (BTA_HH_OPEN_EVT == event) { param_len = sizeof(tBTA_HH_CONN); - else if (BTA_HH_DISABLE_EVT == event) + } else if (BTA_HH_DISABLE_EVT == event) { param_len = sizeof(tBTA_HH_STATUS); - else if (BTA_HH_CLOSE_EVT == event) + } else if (BTA_HH_CLOSE_EVT == event) { param_len = sizeof(tBTA_HH_CBDATA); - else if (BTA_HH_GET_DSCP_EVT == event) + } else if (BTA_HH_GET_DSCP_EVT == event) { param_len = sizeof(tBTA_HH_DEV_DSCP_INFO); - else if ((BTA_HH_GET_PROTO_EVT == event) || (BTA_HH_GET_IDLE_EVT == event)) + } else if ((BTA_HH_GET_PROTO_EVT == event) || (BTA_HH_GET_IDLE_EVT == event)) { param_len = sizeof(tBTA_HH_HSDATA); - else if (BTA_HH_GET_RPT_EVT == event) { + } else if (BTA_HH_GET_RPT_EVT == event) { BT_HDR* hdr = p_data->hs_data.rsp_data.p_rpt_data; param_len = sizeof(tBTA_HH_HSDATA); @@ -1408,16 +1341,17 @@ static void bte_hh_evt(tBTA_HH_EVT event, tBTA_HH* p_data) { param_len += BT_HDR_SIZE + hdr->offset + hdr->len; } } else if ((BTA_HH_SET_PROTO_EVT == event) || (BTA_HH_SET_RPT_EVT == event) || - (BTA_HH_VC_UNPLUG_EVT == event) || (BTA_HH_SET_IDLE_EVT == event)) + (BTA_HH_VC_UNPLUG_EVT == event) || (BTA_HH_SET_IDLE_EVT == event)) { param_len = sizeof(tBTA_HH_CBDATA); - else if ((BTA_HH_ADD_DEV_EVT == event) || (BTA_HH_RMV_DEV_EVT == event)) + } else if ((BTA_HH_ADD_DEV_EVT == event) || (BTA_HH_RMV_DEV_EVT == event)) { param_len = sizeof(tBTA_HH_DEV_INFO); - else if (BTA_HH_API_ERR_EVT == event) + } else if (BTA_HH_API_ERR_EVT == event) { param_len = 0; + } /* switch context to btif task context (copy full union size for convenience) */ - status = btif_transfer_context(btif_hh_upstreams_evt, (uint16_t)event, - (char*)p_data, param_len, p_copy_cback); + status = btif_transfer_context(btif_hh_upstreams_evt, (uint16_t)event, (char*)p_data, param_len, + p_copy_cback); /* catch any failed context transfers */ ASSERTC(status == BT_STATUS_SUCCESS, "context transfer failed", status); @@ -1439,8 +1373,7 @@ static void btif_hh_handle_evt(uint16_t event, char* p_param) { switch (event) { case BTIF_HH_CONNECT_REQ_EVT: { - log::debug("BTIF_HH_CONNECT_REQ_EVT: link spec:{}", - link_spec.ToRedactedStringForLogging()); + log::debug("BTIF_HH_CONNECT_REQ_EVT: link spec:{}", link_spec.ToRedactedStringForLogging()); if (btif_hh_connect(link_spec) == BT_STATUS_SUCCESS) { BTHH_STATE_UPDATE(link_spec, BTHH_CONN_STATE_CONNECTING); } else { @@ -1456,8 +1389,7 @@ static void btif_hh_handle_evt(uint16_t event, char* p_param) { } break; case BTIF_HH_VUP_REQ_EVT: { - log::debug("BTIF_HH_VUP_REQ_EVT: link spec:{}", - link_spec.ToRedactedStringForLogging()); + log::debug("BTIF_HH_VUP_REQ_EVT: link spec:{}", link_spec.ToRedactedStringForLogging()); if (btif_hh_virtual_unplug(link_spec) != BT_STATUS_SUCCESS) { log::warn("Unable to virtual unplug device remote:{}", link_spec.ToRedactedStringForLogging()); @@ -1486,15 +1418,16 @@ void btif_hh_timer_timeout(void* data) { int param_len = sizeof(tBTA_HH_CBDATA); log::verbose(""); - if (p_dev->dev_status != BTHH_CONN_STATE_CONNECTED) return; + if (p_dev->dev_status != BTHH_CONN_STATE_CONNECTED) { + return; + } memset(&p_data, 0, sizeof(tBTA_HH)); p_data.dev_status.status = BTA_HH_ERR; // tBTA_HH_STATUS p_data.dev_status.handle = p_dev->dev_handle; /* switch context to btif task context */ - btif_transfer_context(btif_hh_upstreams_evt, (uint16_t)event, (char*)&p_data, - param_len, NULL); + btif_transfer_context(btif_hh_upstreams_evt, (uint16_t)event, (char*)&p_data, param_len, NULL); } /******************************************************************************* @@ -1535,8 +1468,7 @@ static void btif_hh_transport_select(tAclLinkSpec& link_spec) { bool headtracker_available = false; bool le_preferred = false; bluetooth::Uuid remote_uuids[BT_MAX_NUM_UUIDS] = {}; - bt_property_t remote_properties = {BT_PROPERTY_UUIDS, sizeof(remote_uuids), - &remote_uuids}; + bt_property_t remote_properties = {BT_PROPERTY_UUIDS, sizeof(remote_uuids), &remote_uuids}; const RawAddress& bd_addr = link_spec.addrt.bda; // Find the device type @@ -1549,8 +1481,7 @@ static void btif_hh_transport_select(tAclLinkSpec& link_spec) { bool le_acl = BTM_IsAclConnectionUp(bd_addr, BT_TRANSPORT_LE); // Find which services known to be available - if (btif_storage_get_remote_device_property(&bd_addr, &remote_properties) == - BT_STATUS_SUCCESS) { + if (btif_storage_get_remote_device_property(&bd_addr, &remote_properties) == BT_STATUS_SUCCESS) { int count = remote_properties.len / sizeof(remote_uuids[0]); for (int i = 0; i < count; i++) { if (remote_uuids[i].Is16Bit()) { @@ -1559,8 +1490,7 @@ static void btif_hh_transport_select(tAclLinkSpec& link_spec) { } else if (remote_uuids[i].As16Bit() == UUID_SERVCLASS_LE_HID) { hogp_available = true; } - } else if (com::android::bluetooth::flags:: - android_headtracker_service() && + } else if (com::android::bluetooth::flags::android_headtracker_service() && remote_uuids[i] == ANDROID_HEADTRACKER_SERVICE_UUID) { headtracker_available = true; } @@ -1590,11 +1520,11 @@ static void btif_hh_transport_select(tAclLinkSpec& link_spec) { link_spec.transport = le_preferred ? BT_TRANSPORT_LE : BT_TRANSPORT_BR_EDR; log::info( - "link_spec:{}, bredr_acl:{}, hid_available:{}, le_acl:{}, " - "hogp_available:{}, headtracker_available:{}, " - "dev_type:{}, le_preferred:{}", - link_spec.ToRedactedStringForLogging(), bredr_acl, hid_available, le_acl, - hogp_available, headtracker_available, dev_type, le_preferred); + "link_spec:{}, bredr_acl:{}, hid_available:{}, le_acl:{}, " + "hogp_available:{}, headtracker_available:{}, " + "dev_type:{}, le_preferred:{}", + link_spec.ToRedactedStringForLogging(), bredr_acl, hid_available, le_acl, hogp_available, + headtracker_available, dev_type, le_preferred); } /******************************************************************************* * @@ -1605,8 +1535,7 @@ static void btif_hh_transport_select(tAclLinkSpec& link_spec) { * Returns bt_status_t * ******************************************************************************/ -static bt_status_t connect(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, - tBT_TRANSPORT transport) { +static bt_status_t connect(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, tBT_TRANSPORT transport) { tAclLinkSpec link_spec = {}; link_spec.addrt.bda = *bd_addr; link_spec.addrt.type = addr_type; @@ -1617,16 +1546,14 @@ static bt_status_t connect(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, if (btif_hh_cb.status == BTIF_HH_DEV_CONNECTING) { log::warn("HH status = {}", btif_hh_status_text(btif_hh_cb.status)); return BT_STATUS_BUSY; - } else if (btif_hh_cb.status == BTIF_HH_DISABLED || - btif_hh_cb.status == BTIF_HH_DISABLING) { + } else if (btif_hh_cb.status == BTIF_HH_DISABLED || btif_hh_cb.status == BTIF_HH_DISABLING) { log::warn("HH status = {}", btif_hh_status_text(btif_hh_cb.status)); return BT_STATUS_NOT_READY; } btif_hh_device_t* p_dev = btif_hh_find_connected_dev_by_link_spec(link_spec); if (p_dev != nullptr) { - log::warn("device {} already connected", - p_dev->link_spec.ToRedactedStringForLogging()); + log::warn("device {} already connected", p_dev->link_spec.ToRedactedStringForLogging()); return BT_STATUS_DONE; } @@ -1634,8 +1561,8 @@ static bt_status_t connect(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, btif_hh_transport_select(link_spec); } - return btif_transfer_context(btif_hh_handle_evt, BTIF_HH_CONNECT_REQ_EVT, - (char*)&link_spec, sizeof(tAclLinkSpec), NULL); + return btif_transfer_context(btif_hh_handle_evt, BTIF_HH_CONNECT_REQ_EVT, (char*)&link_spec, + sizeof(tAclLinkSpec), NULL); } /******************************************************************************* @@ -1657,21 +1584,18 @@ static bt_status_t disconnect(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, BTHH_LOG_LINK(link_spec); - if (btif_hh_cb.status == BTIF_HH_DISABLED || - btif_hh_cb.status == BTIF_HH_DISABLING) { + if (btif_hh_cb.status == BTIF_HH_DISABLED || btif_hh_cb.status == BTIF_HH_DISABLING) { log::error("HH status = {}", btif_hh_status_text(btif_hh_cb.status)); return BT_STATUS_UNHANDLED; } - if (com::android::bluetooth::flags::allow_switching_hid_and_hogp() && - !reconnect_allowed) { + if (com::android::bluetooth::flags::allow_switching_hid_and_hogp() && !reconnect_allowed) { log::info("Incoming reconnections disabled for device {}", link_spec.ToRedactedStringForLogging()); btif_hh_added_device_t* added_dev = btif_hh_find_added_dev(link_spec); if (added_dev != nullptr) { added_dev->reconnect_allowed = reconnect_allowed; - btif_storage_set_hid_connection_policy(added_dev->link_spec, - reconnect_allowed); + btif_storage_set_hid_connection_policy(added_dev->link_spec, reconnect_allowed); } } @@ -1680,9 +1604,8 @@ static bt_status_t disconnect(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, if (com::android::bluetooth::flags::allow_switching_hid_and_hogp()) { // Conclude the request if the device is already disconnected p_dev = btif_hh_find_dev_by_link_spec(link_spec); - if (p_dev != nullptr && - (p_dev->dev_status == BTHH_CONN_STATE_ACCEPTING || - p_dev->dev_status == BTHH_CONN_STATE_CONNECTING)) { + if (p_dev != nullptr && (p_dev->dev_status == BTHH_CONN_STATE_ACCEPTING || + p_dev->dev_status == BTHH_CONN_STATE_CONNECTING)) { log::warn("Device {} already not connected, state: {}", p_dev->link_spec.ToRedactedStringForLogging(), bthh_connection_state_text(p_dev->dev_status)); @@ -1696,8 +1619,7 @@ static bt_status_t disconnect(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, } return btif_transfer_context(btif_hh_handle_evt, BTIF_HH_DISCONNECT_REQ_EVT, - (char*)&p_dev->link_spec, sizeof(tAclLinkSpec), - NULL); + (char*)&p_dev->link_spec, sizeof(tAclLinkSpec), NULL); } /******************************************************************************* @@ -1726,8 +1648,8 @@ static bt_status_t virtual_unplug(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, BTHH_LOG_UNKNOWN_LINK(link_spec); return BT_STATUS_DEVICE_NOT_FOUND; } - btif_transfer_context(btif_hh_handle_evt, BTIF_HH_VUP_REQ_EVT, - (char*)&link_spec, sizeof(tAclLinkSpec), NULL); + btif_transfer_context(btif_hh_handle_evt, BTIF_HH_VUP_REQ_EVT, (char*)&link_spec, + sizeof(tAclLinkSpec), NULL); return BT_STATUS_SUCCESS; } @@ -1803,8 +1725,8 @@ static bt_status_t set_idle_time(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, * Returns bt_status_t * ******************************************************************************/ -static bt_status_t set_info(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, - tBT_TRANSPORT transport, bthh_hid_info_t hid_info) { +static bt_status_t set_info(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, tBT_TRANSPORT transport, + bthh_hid_info_t hid_info) { CHECK_BTHH_INIT(); tBTA_HH_DEV_DSCP_INFO dscp_info = {}; tAclLinkSpec link_spec = {}; @@ -1814,10 +1736,10 @@ static bt_status_t set_info(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, BTHH_LOG_LINK(link_spec); log::verbose( - "sub_class = 0x{:02x}, app_id = {}, vendor_id = 0x{:04x}, " - "product_id = 0x{:04x}, version= 0x{:04x}", - hid_info.sub_class, hid_info.app_id, hid_info.vendor_id, - hid_info.product_id, hid_info.version); + "sub_class = 0x{:02x}, app_id = {}, vendor_id = 0x{:04x}, " + "product_id = 0x{:04x}, version= 0x{:04x}", + hid_info.sub_class, hid_info.app_id, hid_info.vendor_id, hid_info.product_id, + hid_info.version); BTHH_CHECK_NOT_DISABLED(); @@ -1827,8 +1749,7 @@ static bt_status_t set_info(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, dscp_info.ctry_code = hid_info.ctry_code; dscp_info.descriptor.dl_len = hid_info.dl_len; - dscp_info.descriptor.dsc_list = - (uint8_t*)osi_malloc(dscp_info.descriptor.dl_len); + dscp_info.descriptor.dsc_list = (uint8_t*)osi_malloc(dscp_info.descriptor.dl_len); memcpy(dscp_info.descriptor.dsc_list, &(hid_info.dsc_list), hid_info.dl_len); if (transport == BT_TRANSPORT_AUTO) { @@ -1836,8 +1757,7 @@ static bt_status_t set_info(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, } if (hh_add_device(link_spec, hid_info.attr_mask, true)) { - BTA_HhAddDev(link_spec, hid_info.attr_mask, hid_info.sub_class, - hid_info.app_id, dscp_info); + BTA_HhAddDev(link_spec, hid_info.attr_mask, hid_info.sub_class, hid_info.app_id, dscp_info); } osi_free_and_reset((void**)&dscp_info.descriptor.dsc_list); @@ -1855,8 +1775,7 @@ static bt_status_t set_info(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, * ******************************************************************************/ static bt_status_t get_protocol(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, - tBT_TRANSPORT transport, - bthh_protocol_mode_t /* protocolMode */) { + tBT_TRANSPORT transport, bthh_protocol_mode_t /* protocolMode */) { CHECK_BTHH_INIT(); tAclLinkSpec link_spec = {}; link_spec.addrt.bda = *bd_addr; @@ -1887,8 +1806,7 @@ static bt_status_t get_protocol(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, * ******************************************************************************/ static bt_status_t set_protocol(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, - tBT_TRANSPORT transport, - bthh_protocol_mode_t protocolMode) { + tBT_TRANSPORT transport, bthh_protocol_mode_t protocolMode) { CHECK_BTHH_INIT(); btif_hh_device_t* p_dev; uint8_t proto_mode = protocolMode; @@ -1906,8 +1824,7 @@ static bt_status_t set_protocol(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, if (p_dev == NULL) { BTHH_LOG_UNKNOWN_LINK(link_spec); return BT_STATUS_DEVICE_NOT_FOUND; - } else if (protocolMode != BTA_HH_PROTO_RPT_MODE && - protocolMode != BTA_HH_PROTO_BOOT_MODE) { + } else if (protocolMode != BTA_HH_PROTO_RPT_MODE && protocolMode != BTA_HH_PROTO_BOOT_MODE) { log::warn("device proto_mode = {}", proto_mode); return BT_STATUS_PARM_INVALID; } else { @@ -1927,9 +1844,8 @@ static bt_status_t set_protocol(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, * ******************************************************************************/ static bt_status_t get_report(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, - tBT_TRANSPORT transport, - bthh_report_type_t reportType, uint8_t reportId, - int bufferSize) { + tBT_TRANSPORT transport, bthh_report_type_t reportType, + uint8_t reportId, int bufferSize) { CHECK_BTHH_INIT(); btif_hh_device_t* p_dev; tAclLinkSpec link_spec = {}; @@ -1938,8 +1854,7 @@ static bt_status_t get_report(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, link_spec.transport = transport; BTHH_LOG_LINK(link_spec); - log::verbose("r_type: {}; rpt_id: {}; buf_size: {}", reportType, reportId, - bufferSize); + log::verbose("r_type: {}; rpt_id: {}; buf_size: {}", reportType, reportId, bufferSize); BTHH_CHECK_NOT_DISABLED(); @@ -1947,12 +1862,10 @@ static bt_status_t get_report(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, if (p_dev == NULL) { BTHH_LOG_UNKNOWN_LINK(link_spec); return BT_STATUS_DEVICE_NOT_FOUND; - } else if (((int)reportType) <= BTA_HH_RPTT_RESRV || - ((int)reportType) > BTA_HH_RPTT_FEATURE) { + } else if (((int)reportType) <= BTA_HH_RPTT_RESRV || ((int)reportType) > BTA_HH_RPTT_FEATURE) { log::error("report type={} not supported", reportType); - log_counter_metrics_btif(android::bluetooth::CodePathCounterKeyEnum:: - HIDH_COUNT_WRONG_REPORT_TYPE, - 1); + log_counter_metrics_btif( + android::bluetooth::CodePathCounterKeyEnum::HIDH_COUNT_WRONG_REPORT_TYPE, 1); return BT_STATUS_UNSUPPORTED; } else { BTA_HhGetReport(p_dev->dev_handle, reportType, reportId, bufferSize); @@ -1970,10 +1883,8 @@ static bt_status_t get_report(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, * Returns bt_status_t * ******************************************************************************/ -static bt_status_t get_report_reply(RawAddress* bd_addr, - tBLE_ADDR_TYPE addr_type, - tBT_TRANSPORT transport, - bthh_status_t status, char* report, +static bt_status_t get_report_reply(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, + tBT_TRANSPORT transport, bthh_status_t status, char* report, uint16_t size) { CHECK_BTHH_INIT(); tAclLinkSpec link_spec = {}; @@ -1991,8 +1902,7 @@ static bt_status_t get_report_reply(RawAddress* bd_addr, return BT_STATUS_DEVICE_NOT_FOUND; } - bta_hh_co_get_rpt_rsp(p_dev->dev_handle, (tBTA_HH_STATUS)status, - (uint8_t*)report, size); + bta_hh_co_get_rpt_rsp(p_dev->dev_handle, (tBTA_HH_STATUS)status, (uint8_t*)report, size); return BT_STATUS_SUCCESS; } @@ -2006,8 +1916,8 @@ static bt_status_t get_report_reply(RawAddress* bd_addr, * ******************************************************************************/ static bt_status_t set_report(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, - tBT_TRANSPORT transport, - bthh_report_type_t reportType, char* report) { + tBT_TRANSPORT transport, bthh_report_type_t reportType, + char* report) { CHECK_BTHH_INIT(); btif_hh_device_t* p_dev; tAclLinkSpec link_spec = {}; @@ -2024,12 +1934,10 @@ static bt_status_t set_report(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, if (p_dev == NULL) { BTHH_LOG_UNKNOWN_LINK(link_spec); return BT_STATUS_DEVICE_NOT_FOUND; - } else if (((int)reportType) <= BTA_HH_RPTT_RESRV || - ((int)reportType) > BTA_HH_RPTT_FEATURE) { + } else if (((int)reportType) <= BTA_HH_RPTT_RESRV || ((int)reportType) > BTA_HH_RPTT_FEATURE) { log::error("report type={} not supported", reportType); - log_counter_metrics_btif(android::bluetooth::CodePathCounterKeyEnum:: - HIDH_COUNT_WRONG_REPORT_TYPE, - 1); + log_counter_metrics_btif( + android::bluetooth::CodePathCounterKeyEnum::HIDH_COUNT_WRONG_REPORT_TYPE, 1); return BT_STATUS_UNSUPPORTED; } else { int hex_bytes_filled; @@ -2065,8 +1973,8 @@ static bt_status_t set_report(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, * Returns bt_status_t * ******************************************************************************/ -static bt_status_t send_data(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, - tBT_TRANSPORT transport, char* data) { +static bt_status_t send_data(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, tBT_TRANSPORT transport, + char* data) { CHECK_BTHH_INIT(); tAclLinkSpec link_spec = {}; link_spec.addrt.bda = *bd_addr; @@ -2120,8 +2028,7 @@ static void cleanup(void) { log::verbose(""); btif_hh_device_t* p_dev; int i; - if (btif_hh_cb.status == BTIF_HH_DISABLED || - btif_hh_cb.status == BTIF_HH_DISABLING) { + if (btif_hh_cb.status == BTIF_HH_DISABLED || btif_hh_cb.status == BTIF_HH_DISABLING) { log::warn("HH disabling or disabled already, status = {}", btif_hh_status_text(btif_hh_cb.status)); return; @@ -2158,22 +2065,22 @@ static void configure_enabled_profiles(bool enable_hidp, bool enable_hogp) { } static const bthh_interface_t bthhInterface = { - sizeof(bthhInterface), - init, - connect, - disconnect, - virtual_unplug, - set_info, - get_protocol, - set_protocol, - get_idle_time, - set_idle_time, - get_report, - get_report_reply, - set_report, - send_data, - cleanup, - configure_enabled_profiles, + sizeof(bthhInterface), + init, + connect, + disconnect, + virtual_unplug, + set_info, + get_protocol, + set_protocol, + get_idle_time, + set_idle_time, + get_report, + get_report_reply, + set_report, + send_data, + cleanup, + configure_enabled_profiles, }; /******************************************************************************* @@ -2188,8 +2095,7 @@ static const bthh_interface_t bthhInterface = { bt_status_t btif_hh_execute_service(bool b_enable) { if (b_enable) { /* Enable and register with BTA-HH */ - BTA_HhEnable(bte_hh_evt, bt_hh_enable_type.hidp_enabled, - bt_hh_enable_type.hogp_enabled); + BTA_HhEnable(bte_hh_evt, bt_hh_enable_type.hidp_enabled, bt_hh_enable_type.hogp_enabled); } else { /* Disable HH */ BTA_HhDisable(); @@ -2214,19 +2120,17 @@ const bthh_interface_t* btif_hh_get_interface() { #define DUMPSYS_TAG "shim::legacy::hid" void DumpsysHid(int fd) { LOG_DUMPSYS_TITLE(fd, DUMPSYS_TAG); - LOG_DUMPSYS(fd, "status:%s num_devices:%u", - btif_hh_status_text(btif_hh_cb.status).c_str(), + LOG_DUMPSYS(fd, "status:%s num_devices:%u", btif_hh_status_text(btif_hh_cb.status).c_str(), btif_hh_cb.device_num); LOG_DUMPSYS(fd, "status:%s", btif_hh_status_text(btif_hh_cb.status).c_str()); for (unsigned i = 0; i < BTIF_HH_MAX_HID; i++) { const btif_hh_device_t* p_dev = &btif_hh_cb.devices[i]; if (p_dev->link_spec.addrt.bda != RawAddress::kEmpty) { - LOG_DUMPSYS( - fd, " %u: addr:%s fd:%d state:%s ready:%s thread_id:%d handle:%d", i, - p_dev->link_spec.ToRedactedStringForLogging().c_str(), p_dev->uhid.fd, - bthh_connection_state_text(p_dev->dev_status).c_str(), - (p_dev->uhid.ready_for_data) ? ("T") : ("F"), - static_cast(p_dev->hh_poll_thread_id), p_dev->dev_handle); + LOG_DUMPSYS(fd, " %u: addr:%s fd:%d state:%s ready:%s thread_id:%d handle:%d", i, + p_dev->link_spec.ToRedactedStringForLogging().c_str(), p_dev->uhid.fd, + bthh_connection_state_text(p_dev->dev_status).c_str(), + (p_dev->uhid.ready_for_data) ? ("T") : ("F"), + static_cast(p_dev->hh_poll_thread_id), p_dev->dev_handle); } } for (unsigned i = 0; i < BTIF_HH_MAX_ADDED_DEV; i++) { @@ -2243,9 +2147,7 @@ namespace bluetooth { namespace legacy { namespace testing { -void bte_hh_evt(tBTA_HH_EVT event, tBTA_HH* p_data) { - ::bte_hh_evt(event, p_data); -} +void bte_hh_evt(tBTA_HH_EVT event, tBTA_HH* p_data) { ::bte_hh_evt(event, p_data); } } // namespace testing } // namespace legacy diff --git a/system/btif/src/btif_iot_config.cc b/system/btif/src/btif_iot_config.cc index d96d900ebb4..6a40fba6fcf 100644 --- a/system/btif/src/btif_iot_config.cc +++ b/system/btif/src/btif_iot_config.cc @@ -40,22 +40,21 @@ using namespace bluetooth; * Returns void * *******************************************************************************/ -static void btif_iot_save_pair_type(const RawAddress& bdaddr, bool is_ble, - bool is_ssp) { +static void btif_iot_save_pair_type(const RawAddress& bdaddr, bool is_ble, bool is_ssp) { if (is_ssp) { - if (!is_ble) - DEVICE_IOT_CONFIG_ADDR_SET_INT(bdaddr, IOT_CONF_KEY_PAIRTYPE, - IOT_CONF_VAL_PAIR_TYPE_SSP); - else + if (!is_ble) { + DEVICE_IOT_CONFIG_ADDR_SET_INT(bdaddr, IOT_CONF_KEY_PAIRTYPE, IOT_CONF_VAL_PAIR_TYPE_SSP); + } else { DEVICE_IOT_CONFIG_ADDR_SET_INT(bdaddr, IOT_CONF_KEY_LE_PAIRTYPE, IOT_CONF_VAL_LE_PAIRTYPE_SECURE); + } } else { - if (!is_ble) - DEVICE_IOT_CONFIG_ADDR_SET_INT(bdaddr, IOT_CONF_KEY_PAIRTYPE, - IOT_CONF_VAL_PAIR_TYPE_LEGACY); - else + if (!is_ble) { + DEVICE_IOT_CONFIG_ADDR_SET_INT(bdaddr, IOT_CONF_KEY_PAIRTYPE, IOT_CONF_VAL_PAIR_TYPE_LEGACY); + } else { DEVICE_IOT_CONFIG_ADDR_SET_INT(bdaddr, IOT_CONF_KEY_LE_PAIRTYPE, IOT_CONF_VAL_LE_PAIRTYPE_LEGACY); + } } } @@ -68,8 +67,7 @@ static void btif_iot_save_pair_type(const RawAddress& bdaddr, bool is_ble, * Returns void * *******************************************************************************/ -void btif_iot_update_remote_info(tBTA_DM_AUTH_CMPL* p_auth_cmpl, bool is_ble, - bool is_ssp) { +void btif_iot_update_remote_info(tBTA_DM_AUTH_CMPL* p_auth_cmpl, bool is_ble, bool is_ssp) { int name_length = 0; char value[1024]; BD_NAME bd_name; @@ -84,66 +82,58 @@ void btif_iot_update_remote_info(tBTA_DM_AUTH_CMPL* p_auth_cmpl, bool is_ble, // save remote name to iot conf file if (strlen((const char*)p_auth_cmpl->bd_name)) { name_length = strlen((char*)p_auth_cmpl->bd_name) > BD_NAME_LEN - ? BD_NAME_LEN - : strlen((char*)p_auth_cmpl->bd_name) + 1; + ? BD_NAME_LEN + : strlen((char*)p_auth_cmpl->bd_name) + 1; strncpy(value, (char*)p_auth_cmpl->bd_name, name_length); - DEVICE_IOT_CONFIG_ADDR_SET_STR(p_auth_cmpl->bd_addr, - IOT_CONF_KEY_REMOTE_NAME, value); + DEVICE_IOT_CONFIG_ADDR_SET_STR(p_auth_cmpl->bd_addr, IOT_CONF_KEY_REMOTE_NAME, value); } else { if (BTM_GetRemoteDeviceName(p_auth_cmpl->bd_addr, bd_name)) { - DEVICE_IOT_CONFIG_ADDR_SET_STR(p_auth_cmpl->bd_addr, - IOT_CONF_KEY_REMOTE_NAME, (char*)bd_name); + DEVICE_IOT_CONFIG_ADDR_SET_STR(p_auth_cmpl->bd_addr, IOT_CONF_KEY_REMOTE_NAME, + (char*)bd_name); } } // save remote dev class to iot conf file // Try to retrieve cod from storage - BTIF_STORAGE_FILL_PROPERTY(&properties[num_properties], - BT_PROPERTY_CLASS_OF_DEVICE, sizeof(cod), &cod); - if (btif_storage_get_remote_device_property(&p_auth_cmpl->bd_addr, - &properties[num_properties]) == - BT_STATUS_SUCCESS) + BTIF_STORAGE_FILL_PROPERTY(&properties[num_properties], BT_PROPERTY_CLASS_OF_DEVICE, sizeof(cod), + &cod); + if (btif_storage_get_remote_device_property(&p_auth_cmpl->bd_addr, &properties[num_properties]) == + BT_STATUS_SUCCESS) { log::verbose("cod retrieved from storage is 0x{:06x}", cod); + } if (cod == 0) { log::verbose("cod is 0, set as unclassified"); cod = COD_UNCLASSIFIED; } - DEVICE_IOT_CONFIG_ADDR_SET_INT(p_auth_cmpl->bd_addr, IOT_CONF_KEY_DEVCLASS, - (int)cod); + DEVICE_IOT_CONFIG_ADDR_SET_INT(p_auth_cmpl->bd_addr, IOT_CONF_KEY_DEVCLASS, (int)cod); num_properties++; // save remote dev type to iot conf file bt_device_type_t dev_type; uint32_t remote_dev_type; - BTIF_STORAGE_FILL_PROPERTY(&properties[num_properties], - BT_PROPERTY_TYPE_OF_DEVICE, sizeof(uint32_t), - &remote_dev_type); - if (btif_storage_get_remote_device_property(&p_auth_cmpl->bd_addr, - &properties[num_properties]) == + BTIF_STORAGE_FILL_PROPERTY(&properties[num_properties], BT_PROPERTY_TYPE_OF_DEVICE, + sizeof(uint32_t), &remote_dev_type); + if (btif_storage_get_remote_device_property(&p_auth_cmpl->bd_addr, &properties[num_properties]) == BT_STATUS_SUCCESS) { log::verbose("retrieve dev type from storage"); dev_type = (bt_device_type_t)(remote_dev_type | p_auth_cmpl->dev_type); } else { dev_type = (bt_device_type_t)(p_auth_cmpl->dev_type); } - DEVICE_IOT_CONFIG_ADDR_SET_INT(p_auth_cmpl->bd_addr, IOT_CONF_KEY_DEVTYPE, - (int)dev_type); + DEVICE_IOT_CONFIG_ADDR_SET_INT(p_auth_cmpl->bd_addr, IOT_CONF_KEY_DEVTYPE, (int)dev_type); // save remote addr type to iot conf file DEVICE_IOT_CONFIG_ADDR_SET_INT(p_auth_cmpl->bd_addr, IOT_CONF_KEY_ADDRTYPE, (int)p_auth_cmpl->addr_type); // save remote versions to iot conf file - btm_status = get_btm_client_interface().peer.BTM_ReadRemoteVersion( - p_auth_cmpl->bd_addr, &lmp_ver, &mfct_set, &lmp_subver); + btm_status = get_btm_client_interface().peer.BTM_ReadRemoteVersion(p_auth_cmpl->bd_addr, &lmp_ver, + &mfct_set, &lmp_subver); if (btm_status == BTM_SUCCESS) { - DEVICE_IOT_CONFIG_ADDR_SET_INT(p_auth_cmpl->bd_addr, - IOT_CONF_KEY_MANUFACTURER, mfct_set); - DEVICE_IOT_CONFIG_ADDR_SET_INT(p_auth_cmpl->bd_addr, IOT_CONF_KEY_LMPVER, - lmp_ver); - DEVICE_IOT_CONFIG_ADDR_SET_INT(p_auth_cmpl->bd_addr, IOT_CONF_KEY_LMPSUBVER, - lmp_subver); + DEVICE_IOT_CONFIG_ADDR_SET_INT(p_auth_cmpl->bd_addr, IOT_CONF_KEY_MANUFACTURER, mfct_set); + DEVICE_IOT_CONFIG_ADDR_SET_INT(p_auth_cmpl->bd_addr, IOT_CONF_KEY_LMPVER, lmp_ver); + DEVICE_IOT_CONFIG_ADDR_SET_INT(p_auth_cmpl->bd_addr, IOT_CONF_KEY_LMPSUBVER, lmp_subver); } // save remote pair type to iot conf file diff --git a/system/btif/src/btif_jni_task.cc b/system/btif/src/btif_jni_task.cc index ee516e1b38a..3937dd15914 100644 --- a/system/btif/src/btif_jni_task.cc +++ b/system/btif/src/btif_jni_task.cc @@ -54,7 +54,9 @@ void jni_thread_shutdown() { jni_thread.ShutDown(); } ******************************************************************************/ static void bt_jni_msg_ready(void* context) { tBTIF_CONTEXT_SWITCH_CBACK* p = (tBTIF_CONTEXT_SWITCH_CBACK*)context; - if (p->p_cb) p->p_cb(p->event, p->p_param); + if (p->p_cb) { + p->p_cb(p->event, p->p_param); + } osi_free(p); } @@ -75,11 +77,10 @@ static void bt_jni_msg_ready(void* context) { * ******************************************************************************/ -bt_status_t btif_transfer_context(tBTIF_CBACK* p_cback, uint16_t event, - char* p_params, int param_len, - tBTIF_COPY_CBACK* p_copy_cback) { - tBTIF_CONTEXT_SWITCH_CBACK* p_msg = (tBTIF_CONTEXT_SWITCH_CBACK*)osi_malloc( - sizeof(tBTIF_CONTEXT_SWITCH_CBACK) + param_len); +bt_status_t btif_transfer_context(tBTIF_CBACK* p_cback, uint16_t event, char* p_params, + int param_len, tBTIF_COPY_CBACK* p_copy_cback) { + tBTIF_CONTEXT_SWITCH_CBACK* p_msg = + (tBTIF_CONTEXT_SWITCH_CBACK*)osi_malloc(sizeof(tBTIF_CONTEXT_SWITCH_CBACK) + param_len); log::verbose("btif_transfer_context event {}, len {}", event, param_len); @@ -111,19 +112,16 @@ bt_status_t do_in_jni_thread(base::OnceClosure task) { return BT_STATUS_SUCCESS; } -bool is_on_jni_thread() { - return jni_thread.GetThreadId() == PlatformThread::CurrentId(); -} +bool is_on_jni_thread() { return jni_thread.GetThreadId() == PlatformThread::CurrentId(); } static void do_post_on_bt_jni(BtJniClosure closure) { closure(); } void post_on_bt_jni(BtJniClosure closure) { - log::assert_that( - do_in_jni_thread(base::BindOnce(do_post_on_bt_jni, std::move(closure))) == - BT_STATUS_SUCCESS, - "assert failed: do_in_jni_thread(" - "base::BindOnce(do_post_on_bt_jni, std::move(closure))) == " - "BT_STATUS_SUCCESS"); + log::assert_that(do_in_jni_thread(base::BindOnce(do_post_on_bt_jni, std::move(closure))) == + BT_STATUS_SUCCESS, + "assert failed: do_in_jni_thread(" + "base::BindOnce(do_post_on_bt_jni, std::move(closure))) == " + "BT_STATUS_SUCCESS"); } bluetooth::common::PostableContext* get_jni() { return jni_thread.Postable(); } diff --git a/system/btif/src/btif_keystore.cc b/system/btif/src/btif_keystore.cc index 32c17c67ab9..8e1c80b7fb9 100644 --- a/system/btif/src/btif_keystore.cc +++ b/system/btif/src/btif_keystore.cc @@ -50,8 +50,7 @@ class BluetoothKeystoreInterfaceImpl log::verbose(""); this->callbacks = callbacks; - bluetooth::os::ParameterProvider::SetCommonCriteriaConfigCompareResult( - CONFIG_COMPARE_ALL_PASS); + bluetooth::os::ParameterProvider::SetCommonCriteriaConfigCompareResult(CONFIG_COMPARE_ALL_PASS); ConvertEncryptOrDecryptKeyIfNeeded(); } @@ -61,13 +60,11 @@ class BluetoothKeystoreInterfaceImpl log::info("callback isn't ready."); return; } - do_in_jni_thread(base::BindOnce([]() { - shim::BtifConfigInterface::ConvertEncryptOrDecryptKeyIfNeeded(); - })); + do_in_jni_thread(base::BindOnce( + []() { shim::BtifConfigInterface::ConvertEncryptOrDecryptKeyIfNeeded(); })); } - bool set_encrypt_key_or_remove_key(std::string prefix, - std::string decryptedString) override { + bool set_encrypt_key_or_remove_key(std::string prefix, std::string decryptedString) override { log::verbose("prefix: {}", prefix); if (!callbacks) { @@ -78,10 +75,9 @@ class BluetoothKeystoreInterfaceImpl // Save the value into a map. key_map[prefix] = decryptedString; - do_in_jni_thread(base::BindOnce( - &bluetooth::bluetooth_keystore::BluetoothKeystoreCallbacks:: - set_encrypt_key_or_remove_key, - base::Unretained(callbacks), prefix, decryptedString)); + do_in_jni_thread(base::BindOnce(&bluetooth::bluetooth_keystore::BluetoothKeystoreCallbacks:: + set_encrypt_key_or_remove_key, + base::Unretained(callbacks), prefix, decryptedString)); return true; } @@ -115,7 +111,7 @@ class BluetoothKeystoreInterfaceImpl key_map.clear(); } - private: +private: BluetoothKeystoreCallbacks* callbacks = nullptr; std::map key_map; }; diff --git a/system/btif/src/btif_le_audio.cc b/system/btif/src/btif_le_audio.cc index 4432b1c9b54..f33e22dd245 100644 --- a/system/btif/src/btif_le_audio.cc +++ b/system/btif/src/btif_le_audio.cc @@ -43,37 +43,33 @@ class LeAudioClientInterfaceImpl; std::unique_ptr leAudioInstance; std::atomic_bool initialized = false; -class LeAudioClientInterfaceImpl : public LeAudioClientInterface, - public LeAudioClientCallbacks { +class LeAudioClientInterfaceImpl : public LeAudioClientInterface, public LeAudioClientCallbacks { ~LeAudioClientInterfaceImpl() = default; void OnInitialized(void) { - do_in_jni_thread( - Bind(&LeAudioClientCallbacks::OnInitialized, Unretained(callbacks))); + do_in_jni_thread(Bind(&LeAudioClientCallbacks::OnInitialized, Unretained(callbacks))); } - void OnConnectionState(ConnectionState state, - const RawAddress& address) override { - do_in_jni_thread(Bind(&LeAudioClientCallbacks::OnConnectionState, - Unretained(callbacks), state, address)); + void OnConnectionState(ConnectionState state, const RawAddress& address) override { + do_in_jni_thread(Bind(&LeAudioClientCallbacks::OnConnectionState, Unretained(callbacks), state, + address)); } void OnGroupStatus(int group_id, GroupStatus group_status) override { - do_in_jni_thread(Bind(&LeAudioClientCallbacks::OnGroupStatus, - Unretained(callbacks), group_id, group_status)); + do_in_jni_thread(Bind(&LeAudioClientCallbacks::OnGroupStatus, Unretained(callbacks), group_id, + group_status)); } void OnGroupNodeStatus(const RawAddress& addr, int group_id, GroupNodeStatus node_status) override { - do_in_jni_thread(Bind(&LeAudioClientCallbacks::OnGroupNodeStatus, - Unretained(callbacks), addr, group_id, node_status)); + do_in_jni_thread(Bind(&LeAudioClientCallbacks::OnGroupNodeStatus, Unretained(callbacks), addr, + group_id, node_status)); } void OnAudioConf(uint8_t direction, int group_id, uint32_t snk_audio_location, uint32_t src_audio_location, uint16_t avail_cont) override { - do_in_jni_thread(Bind(&LeAudioClientCallbacks::OnAudioConf, - Unretained(callbacks), direction, group_id, - snk_audio_location, src_audio_location, avail_cont)); + do_in_jni_thread(Bind(&LeAudioClientCallbacks::OnAudioConf, Unretained(callbacks), direction, + group_id, snk_audio_location, src_audio_location, avail_cont)); } void OnSinkAudioLocationAvailable(const RawAddress& address, @@ -83,66 +79,52 @@ class LeAudioClientInterfaceImpl : public LeAudioClientInterface, } void OnAudioLocalCodecCapabilities( - std::vector local_input_capa_codec_conf, - std::vector local_output_capa_codec_conf) - override { - do_in_jni_thread( - Bind(&LeAudioClientCallbacks::OnAudioLocalCodecCapabilities, - Unretained(callbacks), local_input_capa_codec_conf, - local_output_capa_codec_conf)); + std::vector local_input_capa_codec_conf, + std::vector local_output_capa_codec_conf) override { + do_in_jni_thread(Bind(&LeAudioClientCallbacks::OnAudioLocalCodecCapabilities, + Unretained(callbacks), local_input_capa_codec_conf, + local_output_capa_codec_conf)); } - void OnAudioGroupCurrentCodecConf( - int group_id, btle_audio_codec_config_t input_codec_conf, - btle_audio_codec_config_t output_codec_conf) override { + void OnAudioGroupCurrentCodecConf(int group_id, btle_audio_codec_config_t input_codec_conf, + btle_audio_codec_config_t output_codec_conf) override { do_in_jni_thread(Bind(&LeAudioClientCallbacks::OnAudioGroupCurrentCodecConf, - Unretained(callbacks), group_id, input_codec_conf, - output_codec_conf)); + Unretained(callbacks), group_id, input_codec_conf, output_codec_conf)); } void OnAudioGroupSelectableCodecConf( - int group_id, - std::vector input_selectable_codec_conf, - std::vector output_selectable_codec_conf) - override { - do_in_jni_thread( - Bind(&LeAudioClientCallbacks::OnAudioGroupSelectableCodecConf, - Unretained(callbacks), group_id, input_selectable_codec_conf, - output_selectable_codec_conf)); + int group_id, std::vector input_selectable_codec_conf, + std::vector output_selectable_codec_conf) override { + do_in_jni_thread(Bind(&LeAudioClientCallbacks::OnAudioGroupSelectableCodecConf, + Unretained(callbacks), group_id, input_selectable_codec_conf, + output_selectable_codec_conf)); } void OnHealthBasedRecommendationAction( - const RawAddress& address, - bluetooth::le_audio::LeAudioHealthBasedAction action) override { - do_in_jni_thread( - Bind(&LeAudioClientCallbacks::OnHealthBasedRecommendationAction, - Unretained(callbacks), address, action)); + const RawAddress& address, + bluetooth::le_audio::LeAudioHealthBasedAction action) override { + do_in_jni_thread(Bind(&LeAudioClientCallbacks::OnHealthBasedRecommendationAction, + Unretained(callbacks), address, action)); } void OnHealthBasedGroupRecommendationAction( - int group_id, - bluetooth::le_audio::LeAudioHealthBasedAction action) override { - do_in_jni_thread( - Bind(&LeAudioClientCallbacks::OnHealthBasedGroupRecommendationAction, - Unretained(callbacks), group_id, action)); + int group_id, bluetooth::le_audio::LeAudioHealthBasedAction action) override { + do_in_jni_thread(Bind(&LeAudioClientCallbacks::OnHealthBasedGroupRecommendationAction, + Unretained(callbacks), group_id, action)); } - void OnUnicastMonitorModeStatus(uint8_t direction, - UnicastMonitorModeStatus status) override { + void OnUnicastMonitorModeStatus(uint8_t direction, UnicastMonitorModeStatus status) override { do_in_jni_thread(Bind(&LeAudioClientCallbacks::OnUnicastMonitorModeStatus, Unretained(callbacks), direction, status)); } - void OnGroupStreamStatus(int group_id, - GroupStreamStatus group_stream_status) override { - do_in_jni_thread(Bind(&LeAudioClientCallbacks::OnGroupStreamStatus, - Unretained(callbacks), group_id, - group_stream_status)); + void OnGroupStreamStatus(int group_id, GroupStreamStatus group_stream_status) override { + do_in_jni_thread(Bind(&LeAudioClientCallbacks::OnGroupStreamStatus, Unretained(callbacks), + group_id, group_stream_status)); } void Initialize(LeAudioClientCallbacks* callbacks, - const std::vector& - offloading_preference) override { + const std::vector& offloading_preference) override { this->callbacks = callbacks; for (auto codec : offloading_preference) { @@ -150,13 +132,11 @@ class LeAudioClientInterfaceImpl : public LeAudioClientInterface, } do_in_main_thread( - FROM_HERE, - Bind(&LeAudioClient::Initialize, this, - jni_thread_wrapper(Bind(&btif_storage_load_bonded_leaudio)), - base::Bind([]() -> bool { - return LeAudioHalVerifier::SupportsLeAudio(); - }), - offloading_preference)); + FROM_HERE, + Bind(&LeAudioClient::Initialize, this, + jni_thread_wrapper(Bind(&btif_storage_load_bonded_leaudio)), + base::Bind([]() -> bool { return LeAudioHalVerifier::SupportsLeAudio(); }), + offloading_preference)); /* It might be not yet initialized, but setting this flag here is safe, * because other calls will check this and the native instance @@ -167,8 +147,8 @@ class LeAudioClientInterfaceImpl : public LeAudioClientInterface, void Cleanup(void) override { if (!initialized || !LeAudioClient::IsLeAudioClientRunning()) { log::verbose( - "call ignored, due to already started cleanup procedure or service " - "being not read"); + "call ignored, due to already started cleanup procedure or service " + "being not read"); return; } @@ -180,16 +160,15 @@ class LeAudioClientInterfaceImpl : public LeAudioClientInterface, void RemoveDevice(const RawAddress& address) override { if (!initialized || !LeAudioClient::IsLeAudioClientRunning()) { log::verbose( - "call ignored, due to already started cleanup procedure or service " - "being not read"); + "call ignored, due to already started cleanup procedure or service " + "being not read"); do_in_jni_thread(Bind(&btif_storage_remove_leaudio, address)); return; } - do_in_main_thread(FROM_HERE, - Bind(&LeAudioClient::RemoveDevice, - Unretained(LeAudioClient::Get()), address)); + do_in_main_thread(FROM_HERE, Bind(&LeAudioClient::RemoveDevice, + Unretained(LeAudioClient::Get()), address)); do_in_jni_thread(Bind(&btif_storage_remove_leaudio, address)); } @@ -197,172 +176,157 @@ class LeAudioClientInterfaceImpl : public LeAudioClientInterface, void Connect(const RawAddress& address) override { if (!initialized || !LeAudioClient::IsLeAudioClientRunning()) { log::verbose( - "call ignored, due to already started cleanup procedure or service " - "being not read"); + "call ignored, due to already started cleanup procedure or service " + "being not read"); return; } do_in_main_thread(FROM_HERE, - Bind(&LeAudioClient::Connect, - Unretained(LeAudioClient::Get()), address)); + Bind(&LeAudioClient::Connect, Unretained(LeAudioClient::Get()), address)); } void Disconnect(const RawAddress& address) override { if (!initialized || !LeAudioClient::IsLeAudioClientRunning()) { log::verbose( - "call ignored, due to already started cleanup procedure or service " - "being not read"); + "call ignored, due to already started cleanup procedure or service " + "being not read"); return; } do_in_main_thread(FROM_HERE, - Bind(&LeAudioClient::Disconnect, - Unretained(LeAudioClient::Get()), address)); + Bind(&LeAudioClient::Disconnect, Unretained(LeAudioClient::Get()), address)); } void SetEnableState(const RawAddress& address, bool enabled) override { if (!initialized || !LeAudioClient::IsLeAudioClientRunning()) { log::verbose( - "call ignored, due to already started cleanup procedure or service " - "being not read"); + "call ignored, due to already started cleanup procedure or service " + "being not read"); return; } - do_in_main_thread(FROM_HERE, - Bind(&LeAudioClient::SetEnableState, - Unretained(LeAudioClient::Get()), address, enabled)); + do_in_main_thread(FROM_HERE, Bind(&LeAudioClient::SetEnableState, + Unretained(LeAudioClient::Get()), address, enabled)); } void GroupAddNode(const int group_id, const RawAddress& address) override { if (!initialized || !LeAudioClient::IsLeAudioClientRunning()) { log::verbose( - "call ignored, due to already started cleanup procedure or service " - "being not read"); + "call ignored, due to already started cleanup procedure or service " + "being not read"); return; } - do_in_main_thread( - FROM_HERE, Bind(&LeAudioClient::GroupAddNode, - Unretained(LeAudioClient::Get()), group_id, address)); + do_in_main_thread(FROM_HERE, Bind(&LeAudioClient::GroupAddNode, + Unretained(LeAudioClient::Get()), group_id, address)); } void GroupRemoveNode(const int group_id, const RawAddress& address) override { if (!initialized || !LeAudioClient::IsLeAudioClientRunning()) { log::verbose( - "call ignored, due to already started cleanup procedure or service " - "being not read"); + "call ignored, due to already started cleanup procedure or service " + "being not read"); return; } - do_in_main_thread( - FROM_HERE, Bind(&LeAudioClient::GroupRemoveNode, - Unretained(LeAudioClient::Get()), group_id, address)); + do_in_main_thread(FROM_HERE, Bind(&LeAudioClient::GroupRemoveNode, + Unretained(LeAudioClient::Get()), group_id, address)); } void GroupSetActive(const int group_id) override { if (!initialized || !LeAudioClient::IsLeAudioClientRunning()) { log::verbose( - "call ignored, due to already started cleanup procedure or service " - "being not read"); + "call ignored, due to already started cleanup procedure or service " + "being not read"); return; } - do_in_main_thread(FROM_HERE, - Bind(&LeAudioClient::GroupSetActive, - Unretained(LeAudioClient::Get()), group_id)); + do_in_main_thread(FROM_HERE, Bind(&LeAudioClient::GroupSetActive, + Unretained(LeAudioClient::Get()), group_id)); } - void SetCodecConfigPreference(int group_id, - btle_audio_codec_config_t input_codec_config, + void SetCodecConfigPreference(int group_id, btle_audio_codec_config_t input_codec_config, btle_audio_codec_config_t output_codec_config) { if (!initialized || !LeAudioClient::IsLeAudioClientRunning()) { log::verbose( - "call ignored, due to already started cleanup procedure or service " - "being not read"); + "call ignored, due to already started cleanup procedure or service " + "being not read"); return; } - do_in_main_thread(FROM_HERE, - Bind(&LeAudioClient::SetCodecConfigPreference, - Unretained(LeAudioClient::Get()), group_id, - input_codec_config, output_codec_config)); + do_in_main_thread(FROM_HERE, Bind(&LeAudioClient::SetCodecConfigPreference, + Unretained(LeAudioClient::Get()), group_id, + input_codec_config, output_codec_config)); } void SetCcidInformation(int ccid, int context_type) { if (!initialized || !LeAudioClient::IsLeAudioClientRunning()) { log::verbose( - "call ignored, due to already started cleanup procedure or service " - "being not read"); + "call ignored, due to already started cleanup procedure or service " + "being not read"); return; } - do_in_main_thread( - FROM_HERE, Bind(&LeAudioClient::SetCcidInformation, - Unretained(LeAudioClient::Get()), ccid, context_type)); + do_in_main_thread(FROM_HERE, Bind(&LeAudioClient::SetCcidInformation, + Unretained(LeAudioClient::Get()), ccid, context_type)); } void SetInCall(bool in_call) { if (!initialized || !LeAudioClient::IsLeAudioClientRunning()) { log::verbose( - "call ignored, due to already started cleanup procedure or service " - "being not read"); + "call ignored, due to already started cleanup procedure or service " + "being not read"); return; } do_in_main_thread(FROM_HERE, - Bind(&LeAudioClient::SetInCall, - Unretained(LeAudioClient::Get()), in_call)); + Bind(&LeAudioClient::SetInCall, Unretained(LeAudioClient::Get()), in_call)); } void SetUnicastMonitorMode(uint8_t direction, bool enable) { log::verbose("enable: {}", enable); if (!initialized || !LeAudioClient::IsLeAudioClientRunning()) { log::verbose( - "Unicast monitoring mode set ignored, due to already" - " started cleanup procedure or service being not read"); + "Unicast monitoring mode set ignored, due to already" + " started cleanup procedure or service being not read"); return; } - do_in_main_thread( - FROM_HERE, Bind(&LeAudioClient::SetUnicastMonitorMode, - Unretained(LeAudioClient::Get()), direction, enable)); + do_in_main_thread(FROM_HERE, Bind(&LeAudioClient::SetUnicastMonitorMode, + Unretained(LeAudioClient::Get()), direction, enable)); } - void SendAudioProfilePreferences(int group_id, - bool is_output_preference_le_audio, + void SendAudioProfilePreferences(int group_id, bool is_output_preference_le_audio, bool is_duplex_preference_le_audio) { if (!initialized || !LeAudioClient::IsLeAudioClientRunning()) { log::verbose( - "call ignored, due to already started cleanup procedure or service " - "being not read"); + "call ignored, due to already started cleanup procedure or service " + "being not read"); return; } do_in_main_thread( - FROM_HERE, - Bind(&LeAudioClient::SendAudioProfilePreferences, - Unretained(LeAudioClient::Get()), group_id, - is_output_preference_le_audio, is_duplex_preference_le_audio)); + FROM_HERE, + Bind(&LeAudioClient::SendAudioProfilePreferences, Unretained(LeAudioClient::Get()), + group_id, is_output_preference_le_audio, is_duplex_preference_le_audio)); } - void SetGroupAllowedContextMask(int group_id, int sink_context_types, - int source_context_types) { + void SetGroupAllowedContextMask(int group_id, int sink_context_types, int source_context_types) { if (!initialized || !LeAudioClient::IsLeAudioClientRunning()) { log::verbose( - "call ignored, due to already started cleanup procedure or service " - "being not read"); + "call ignored, due to already started cleanup procedure or service " + "being not read"); return; } - log::info("group_id: {}, sink context types: {}, source context types: {}", - group_id, sink_context_types, source_context_types); + log::info("group_id: {}, sink context types: {}, source context types: {}", group_id, + sink_context_types, source_context_types); - do_in_main_thread(FROM_HERE, - Bind(&LeAudioClient::SetGroupAllowedContextMask, - Unretained(LeAudioClient::Get()), group_id, - sink_context_types, source_context_types)); + do_in_main_thread(FROM_HERE, Bind(&LeAudioClient::SetGroupAllowedContextMask, + Unretained(LeAudioClient::Get()), group_id, + sink_context_types, source_context_types)); } - private: +private: LeAudioClientCallbacks* callbacks; }; diff --git a/system/btif/src/btif_le_audio_broadcaster.cc b/system/btif/src/btif_le_audio_broadcaster.cc index 39e92b71d2d..d5f3a53ce30 100644 --- a/system/btif/src/btif_le_audio_broadcaster.cc +++ b/system/btif/src/btif_le_audio_broadcaster.cc @@ -41,71 +41,59 @@ class LeAudioBroadcasterInterfaceImpl : public LeAudioBroadcasterInterface, void Initialize(LeAudioBroadcasterCallbacks* callbacks) override { this->callbacks_ = callbacks; - do_in_main_thread( - FROM_HERE, - Bind(&LeAudioBroadcaster::Initialize, this, base::Bind([]() -> bool { - return LeAudioHalVerifier::SupportsLeAudioBroadcast(); - }))); + do_in_main_thread(FROM_HERE, + Bind(&LeAudioBroadcaster::Initialize, this, base::Bind([]() -> bool { + return LeAudioHalVerifier::SupportsLeAudioBroadcast(); + }))); } - void CreateBroadcast( - bool is_public, std::string broadcast_name, - std::optional broadcast_code, - std::vector public_metadata, - std::vector subgroup_quality, - std::vector> subgroup_metadata) override { + void CreateBroadcast(bool is_public, std::string broadcast_name, + std::optional broadcast_code, + std::vector public_metadata, std::vector subgroup_quality, + std::vector> subgroup_metadata) override { do_in_main_thread(FROM_HERE, Bind(&LeAudioBroadcaster::CreateAudioBroadcast, - Unretained(LeAudioBroadcaster::Get()), - is_public, broadcast_name, broadcast_code, - std::move(public_metadata), - std::move(subgroup_quality), - std::move(subgroup_metadata))); + Unretained(LeAudioBroadcaster::Get()), is_public, + broadcast_name, broadcast_code, std::move(public_metadata), + std::move(subgroup_quality), std::move(subgroup_metadata))); } - void UpdateMetadata( - uint32_t broadcast_id, std::string broadcast_name, - std::vector public_metadata, - std::vector> subgroup_metadata) override { + void UpdateMetadata(uint32_t broadcast_id, std::string broadcast_name, + std::vector public_metadata, + std::vector> subgroup_metadata) override { do_in_main_thread(FROM_HERE, Bind(&LeAudioBroadcaster::UpdateMetadata, - Unretained(LeAudioBroadcaster::Get()), broadcast_id, - broadcast_name, std::move(public_metadata), - std::move(subgroup_metadata))); + Unretained(LeAudioBroadcaster::Get()), broadcast_id, broadcast_name, + std::move(public_metadata), std::move(subgroup_metadata))); } void StartBroadcast(uint32_t broadcast_id) override { - do_in_main_thread( - FROM_HERE, Bind(&LeAudioBroadcaster::StartAudioBroadcast, - Unretained(LeAudioBroadcaster::Get()), broadcast_id)); + do_in_main_thread(FROM_HERE, Bind(&LeAudioBroadcaster::StartAudioBroadcast, + Unretained(LeAudioBroadcaster::Get()), broadcast_id)); } void StopBroadcast(uint32_t broadcast_id) override { - do_in_main_thread( - FROM_HERE, Bind(&LeAudioBroadcaster::StopAudioBroadcast, - Unretained(LeAudioBroadcaster::Get()), broadcast_id)); + do_in_main_thread(FROM_HERE, Bind(&LeAudioBroadcaster::StopAudioBroadcast, + Unretained(LeAudioBroadcaster::Get()), broadcast_id)); } void PauseBroadcast(uint32_t broadcast_id) override { - do_in_main_thread( - FROM_HERE, Bind(&LeAudioBroadcaster::SuspendAudioBroadcast, - Unretained(LeAudioBroadcaster::Get()), broadcast_id)); + do_in_main_thread(FROM_HERE, Bind(&LeAudioBroadcaster::SuspendAudioBroadcast, + Unretained(LeAudioBroadcaster::Get()), broadcast_id)); } void DestroyBroadcast(uint32_t broadcast_id) override { - do_in_main_thread( - FROM_HERE, Bind(&LeAudioBroadcaster::DestroyAudioBroadcast, - Unretained(LeAudioBroadcaster::Get()), broadcast_id)); + do_in_main_thread(FROM_HERE, Bind(&LeAudioBroadcaster::DestroyAudioBroadcast, + Unretained(LeAudioBroadcaster::Get()), broadcast_id)); } void GetBroadcastMetadata(uint32_t broadcast_id) override { - do_in_main_thread( - FROM_HERE, Bind(&LeAudioBroadcaster::GetBroadcastMetadata, - Unretained(LeAudioBroadcaster::Get()), broadcast_id)); + do_in_main_thread(FROM_HERE, Bind(&LeAudioBroadcaster::GetBroadcastMetadata, + Unretained(LeAudioBroadcaster::Get()), broadcast_id)); } void OnBroadcastCreated(uint32_t broadcast_id, bool success) override { - do_in_jni_thread(Bind(&LeAudioBroadcasterCallbacks::OnBroadcastCreated, - Unretained(callbacks_), broadcast_id, success)); + do_in_jni_thread(Bind(&LeAudioBroadcasterCallbacks::OnBroadcastCreated, Unretained(callbacks_), + broadcast_id, success)); } void OnBroadcastDestroyed(uint32_t broadcast_id) override { @@ -113,29 +101,23 @@ class LeAudioBroadcasterInterfaceImpl : public LeAudioBroadcasterInterface, Unretained(callbacks_), broadcast_id)); } - void OnBroadcastStateChanged(uint32_t broadcast_id, - BroadcastState state) override { + void OnBroadcastStateChanged(uint32_t broadcast_id, BroadcastState state) override { do_in_jni_thread(Bind(&LeAudioBroadcasterCallbacks::OnBroadcastStateChanged, Unretained(callbacks_), broadcast_id, state)); } - void OnBroadcastMetadataChanged(uint32_t broadcast_id, - const bluetooth::le_audio::BroadcastMetadata& - broadcast_metadata) override { - do_in_jni_thread( - Bind(&LeAudioBroadcasterCallbacks::OnBroadcastMetadataChanged, - Unretained(callbacks_), broadcast_id, broadcast_metadata)); + void OnBroadcastMetadataChanged( + uint32_t broadcast_id, + const bluetooth::le_audio::BroadcastMetadata& broadcast_metadata) override { + do_in_jni_thread(Bind(&LeAudioBroadcasterCallbacks::OnBroadcastMetadataChanged, + Unretained(callbacks_), broadcast_id, broadcast_metadata)); } - void Stop(void) override { - do_in_main_thread(FROM_HERE, Bind(&LeAudioBroadcaster::Stop)); - } + void Stop(void) override { do_in_main_thread(FROM_HERE, Bind(&LeAudioBroadcaster::Stop)); } - void Cleanup(void) override { - do_in_main_thread(FROM_HERE, Bind(&LeAudioBroadcaster::Cleanup)); - } + void Cleanup(void) override { do_in_main_thread(FROM_HERE, Bind(&LeAudioBroadcaster::Cleanup)); } - private: +private: LeAudioBroadcasterCallbacks* callbacks_; }; diff --git a/system/btif/src/btif_leaudio_hal_version_host.cc b/system/btif/src/btif_leaudio_hal_version_host.cc index 673adcc1440..c0998078b1e 100644 --- a/system/btif/src/btif_leaudio_hal_version_host.cc +++ b/system/btif/src/btif_leaudio_hal_version_host.cc @@ -21,7 +21,7 @@ namespace audio { class HalVersionManager { static inline std::unique_ptr instance_ptr = - std::make_unique(); + std::make_unique(); }; } // namespace audio diff --git a/system/btif/src/btif_metrics_logging.cc b/system/btif/src/btif_metrics_logging.cc index dadd14eea1d..958e74a574c 100644 --- a/system/btif/src/btif_metrics_logging.cc +++ b/system/btif/src/btif_metrics_logging.cc @@ -14,99 +14,84 @@ * limitations under the License. */ +#include "btif/include/btif_metrics_logging.h" + #include #include -#include "btif/include/btif_metrics_logging.h" #include "common/metric_id_allocator.h" #include "common/metrics.h" #include "main/shim/metrics_api.h" #include "main/shim/shim.h" #include "types/raw_address.h" -void log_a2dp_audio_underrun_event(const RawAddress& address, - uint64_t encoding_interval_millis, +void log_a2dp_audio_underrun_event(const RawAddress& address, uint64_t encoding_interval_millis, int num_missing_pcm_bytes) { - bluetooth::shim::LogMetricA2dpAudioUnderrunEvent( - address, encoding_interval_millis, num_missing_pcm_bytes); + bluetooth::shim::LogMetricA2dpAudioUnderrunEvent(address, encoding_interval_millis, + num_missing_pcm_bytes); } -void log_a2dp_audio_overrun_event(const RawAddress& address, - uint64_t encoding_interval_millis, - int num_dropped_buffers, - int num_dropped_encoded_frames, +void log_a2dp_audio_overrun_event(const RawAddress& address, uint64_t encoding_interval_millis, + int num_dropped_buffers, int num_dropped_encoded_frames, int num_dropped_encoded_bytes) { - bluetooth::shim::LogMetricA2dpAudioOverrunEvent( - address, encoding_interval_millis, num_dropped_buffers, - num_dropped_encoded_frames, num_dropped_encoded_bytes); + bluetooth::shim::LogMetricA2dpAudioOverrunEvent(address, encoding_interval_millis, + num_dropped_buffers, num_dropped_encoded_frames, + num_dropped_encoded_bytes); } -void log_a2dp_playback_event(const RawAddress& address, int playback_state, - int audio_coding_mode) { - bluetooth::shim::LogMetricA2dpPlaybackEvent(address, playback_state, - audio_coding_mode); +void log_a2dp_playback_event(const RawAddress& address, int playback_state, int audio_coding_mode) { + bluetooth::shim::LogMetricA2dpPlaybackEvent(address, playback_state, audio_coding_mode); } -void log_a2dp_session_metrics_event( - const RawAddress& address, int64_t audio_duration_ms, - int media_timer_min_ms, int media_timer_max_ms, int media_timer_avg_ms, - int total_scheduling_count, int buffer_overruns_max_count, - int buffer_overruns_total, float buffer_underruns_average, - int buffer_underruns_count, int64_t codec_index, bool is_a2dp_offload) { - bluetooth::shim::LogMetricA2dpSessionMetricsEvent( - address, audio_duration_ms, media_timer_min_ms, media_timer_max_ms, - media_timer_avg_ms, total_scheduling_count, buffer_overruns_max_count, - buffer_overruns_total, buffer_underruns_average, buffer_underruns_count, - codec_index, is_a2dp_offload); +void log_a2dp_session_metrics_event(const RawAddress& address, int64_t audio_duration_ms, + int media_timer_min_ms, int media_timer_max_ms, + int media_timer_avg_ms, int total_scheduling_count, + int buffer_overruns_max_count, int buffer_overruns_total, + float buffer_underruns_average, int buffer_underruns_count, + int64_t codec_index, bool is_a2dp_offload) { + bluetooth::shim::LogMetricA2dpSessionMetricsEvent( + address, audio_duration_ms, media_timer_min_ms, media_timer_max_ms, media_timer_avg_ms, + total_scheduling_count, buffer_overruns_max_count, buffer_overruns_total, + buffer_underruns_average, buffer_underruns_count, codec_index, is_a2dp_offload); } -void log_read_rssi_result(const RawAddress& address, uint16_t handle, - uint32_t cmd_status, int8_t rssi) { +void log_read_rssi_result(const RawAddress& address, uint16_t handle, uint32_t cmd_status, + int8_t rssi) { bluetooth::shim::LogMetricReadRssiResult(address, handle, cmd_status, rssi); } -void log_read_failed_contact_counter_result(const RawAddress& address, - uint16_t handle, - uint32_t cmd_status, - int32_t failed_contact_counter) { - bluetooth::shim::LogMetricReadFailedContactCounterResult( - address, handle, cmd_status, failed_contact_counter); +void log_read_failed_contact_counter_result(const RawAddress& address, uint16_t handle, + uint32_t cmd_status, int32_t failed_contact_counter) { + bluetooth::shim::LogMetricReadFailedContactCounterResult(address, handle, cmd_status, + failed_contact_counter); } -void log_read_tx_power_level_result(const RawAddress& address, uint16_t handle, - uint32_t cmd_status, +void log_read_tx_power_level_result(const RawAddress& address, uint16_t handle, uint32_t cmd_status, int32_t transmit_power_level) { bluetooth::shim::LogMetricReadTxPowerLevelResult(address, handle, cmd_status, transmit_power_level); } -void log_socket_connection_state( - const RawAddress& address, int port, int type, - android::bluetooth::SocketConnectionstateEnum connection_state, - int64_t tx_bytes, int64_t rx_bytes, int uid, int server_port, - android::bluetooth::SocketRoleEnum socket_role) { - bluetooth::shim::LogMetricSocketConnectionState( - address, port, type, connection_state, tx_bytes, rx_bytes, uid, - server_port, socket_role); +void log_socket_connection_state(const RawAddress& address, int port, int type, + android::bluetooth::SocketConnectionstateEnum connection_state, + int64_t tx_bytes, int64_t rx_bytes, int uid, int server_port, + android::bluetooth::SocketRoleEnum socket_role) { + bluetooth::shim::LogMetricSocketConnectionState(address, port, type, connection_state, tx_bytes, + rx_bytes, uid, server_port, socket_role); } -void log_counter_metrics_btif(android::bluetooth::CodePathCounterKeyEnum key, - int64_t value) { +void log_counter_metrics_btif(android::bluetooth::CodePathCounterKeyEnum key, int64_t value) { bluetooth::shim::CountCounterMetrics(key, value); } -bool init_metric_id_allocator( - const std::unordered_map& paired_device_map, - bluetooth::shim::CallbackLegacy save_device_callback, - bluetooth::shim::CallbackLegacy forget_device_callback) { - return bluetooth::shim::InitMetricIdAllocator( - paired_device_map, std::move(save_device_callback), - std::move(forget_device_callback)); +bool init_metric_id_allocator(const std::unordered_map& paired_device_map, + bluetooth::shim::CallbackLegacy save_device_callback, + bluetooth::shim::CallbackLegacy forget_device_callback) { + return bluetooth::shim::InitMetricIdAllocator(paired_device_map, std::move(save_device_callback), + std::move(forget_device_callback)); } -bool close_metric_id_allocator() { - return bluetooth::shim::CloseMetricIdAllocator(); -} +bool close_metric_id_allocator() { return bluetooth::shim::CloseMetricIdAllocator(); } int allocate_metric_id_from_metric_id_allocator(const RawAddress& address) { return bluetooth::shim::AllocateIdFromMetricIdAllocator(address); diff --git a/system/btif/src/btif_pan.cc b/system/btif/src/btif_pan.cc index 3b8bbbd2b59..aef43b0d376 100644 --- a/system/btif/src/btif_pan.cc +++ b/system/btif/src/btif_pan.cc @@ -66,9 +66,10 @@ #define FORWARD_FAILURE (-1) #define FORWARD_CONGEST (-2) -#define asrt(s) \ - do { \ - if (!(s)) log::error("btif_pan: ## assert {} failed ##", #s); \ +#define asrt(s) \ + do { \ + if (!(s)) \ + log::error("btif_pan: ## assert {} failed ##", #s); \ } while (0) #define MIN(x, y) (((x) < (y)) ? (x) : (y)) @@ -82,21 +83,19 @@ static bool stack_initialized; static bt_status_t btpan_jni_init(const btpan_callbacks_t* callbacks); static void btpan_jni_cleanup(); -static bt_status_t btpan_connect(const RawAddress* bd_addr, int local_role, - int remote_role); +static bt_status_t btpan_connect(const RawAddress* bd_addr, int local_role, int remote_role); static bt_status_t btpan_disconnect(const RawAddress* bd_addr); static bt_status_t btpan_enable(int local_role); static int btpan_get_local_role(void); -static void btpan_tap_fd_signaled(int fd, int type, int flags, - uint32_t user_id); +static void btpan_tap_fd_signaled(int fd, int type, int flags, uint32_t user_id); static void btpan_cleanup_conn(btpan_conn_t* conn); static void bta_pan_callback(tBTA_PAN_EVT event, tBTA_PAN* p_data); static void btu_exec_tap_fd_read(const int fd); -static btpan_interface_t pan_if = { - sizeof(pan_if), btpan_jni_init, nullptr, btpan_get_local_role, - btpan_connect, btpan_disconnect, btpan_jni_cleanup}; +static btpan_interface_t pan_if = {sizeof(pan_if), btpan_jni_init, nullptr, + btpan_get_local_role, btpan_connect, btpan_disconnect, + btpan_jni_cleanup}; const btpan_interface_t* btif_pan_get_interface() { return &pan_if; } @@ -110,8 +109,7 @@ const btpan_interface_t* btif_pan_get_interface() { return &pan_if; } ** ******************************************************************************/ void btif_pan_init() { - log::verbose("jni_initialized = {}, btpan_cb.enabled:{}", jni_initialized, - btpan_cb.enabled); + log::verbose("jni_initialized = {}, btpan_cb.enabled:{}", jni_initialized, btpan_cb.enabled); stack_initialized = true; if (jni_initialized && !btpan_cb.enabled) { @@ -119,15 +117,15 @@ void btif_pan_init() { memset(&btpan_cb, 0, sizeof(btpan_cb)); btpan_cb.tap_fd = INVALID_FD; btpan_cb.flow = 1; - for (int i = 0; i < MAX_PAN_CONNS; i++) + for (int i = 0; i < MAX_PAN_CONNS; i++) { btpan_cleanup_conn(&btpan_cb.conns[i]); + } BTA_PanEnable(bta_pan_callback); btpan_cb.enabled = 1; int role = BTPAN_ROLE_NONE; #ifdef __ANDROID__ - if (android::sysprop::BluetoothProperties::isProfilePanNapEnabled() - .value_or(false)) { + if (android::sysprop::BluetoothProperties::isProfilePanNapEnabled().value_or(false)) { role |= BTPAN_ROLE_PANNAP; } #endif @@ -148,11 +146,14 @@ static void pan_disable() { } void btif_pan_cleanup() { - if (!stack_initialized) return; + if (!stack_initialized) { + return; + } - // Bluetooth is shuting down, invalidate all BTA PAN handles - for (int i = 0; i < MAX_PAN_CONNS; i++) + // Bluetooth is shutting down, invalidate all BTA PAN handles + for (int i = 0; i < MAX_PAN_CONNS; i++) { btpan_cleanup_conn(&btpan_cb.conns[i]); + } pan_disable(); stack_initialized = false; @@ -160,11 +161,12 @@ void btif_pan_cleanup() { static btpan_callbacks_t callback; static bt_status_t btpan_jni_init(const btpan_callbacks_t* callbacks) { - log::verbose("stack_initialized = {}, btpan_cb.enabled:{}", stack_initialized, - btpan_cb.enabled); + log::verbose("stack_initialized = {}, btpan_cb.enabled:{}", stack_initialized, btpan_cb.enabled); callback = *callbacks; jni_initialized = true; - if (stack_initialized && !btpan_cb.enabled) btif_pan_init(); + if (stack_initialized && !btpan_cb.enabled) { + btif_pan_init(); + } return BT_STATUS_SUCCESS; } @@ -175,22 +177,29 @@ static void btpan_jni_cleanup() { static inline int bta_role_to_btpan(tBTA_PAN_ROLE bta_pan_role) { int btpan_role = 0; - if (bta_pan_role & PAN_ROLE_NAP_SERVER) btpan_role |= BTPAN_ROLE_PANNAP; - if (bta_pan_role & PAN_ROLE_CLIENT) btpan_role |= BTPAN_ROLE_PANU; + if (bta_pan_role & PAN_ROLE_NAP_SERVER) { + btpan_role |= BTPAN_ROLE_PANNAP; + } + if (bta_pan_role & PAN_ROLE_CLIENT) { + btpan_role |= BTPAN_ROLE_PANU; + } return btpan_role; } static inline tBTA_PAN_ROLE btpan_role_to_bta(int btpan_role) { tBTA_PAN_ROLE bta_pan_role = PAN_ROLE_INACTIVE; - if (btpan_role & BTPAN_ROLE_PANNAP) bta_pan_role |= PAN_ROLE_NAP_SERVER; - if (btpan_role & BTPAN_ROLE_PANU) bta_pan_role |= PAN_ROLE_CLIENT; + if (btpan_role & BTPAN_ROLE_PANNAP) { + bta_pan_role |= PAN_ROLE_NAP_SERVER; + } + if (btpan_role & BTPAN_ROLE_PANU) { + bta_pan_role |= PAN_ROLE_CLIENT; + } return bta_pan_role; } static tBTA_PAN_ROLE btpan_dev_local_role; static tBTA_PAN_ROLE_INFO bta_panu_info = {std::string(PANU_SERVICE_NAME), 0}; -static tBTA_PAN_ROLE_INFO bta_pan_nap_info = {std::string(PAN_NAP_SERVICE_NAME), - 1}; +static tBTA_PAN_ROLE_INFO bta_pan_nap_info = {std::string(PAN_NAP_SERVICE_NAME), 1}; static bt_status_t btpan_enable(int local_role) { const tBTA_PAN_ROLE bta_pan_role = btpan_role_to_bta(local_role); @@ -199,12 +208,9 @@ static bt_status_t btpan_enable(int local_role) { return BT_STATUS_SUCCESS; } -static int btpan_get_local_role() { - return static_cast(btpan_dev_local_role); -} +static int btpan_get_local_role() { return static_cast(btpan_dev_local_role); } -static bt_status_t btpan_connect(const RawAddress* bd_addr, int local_role, - int remote_role) { +static bt_status_t btpan_connect(const RawAddress* bd_addr, int local_role, int remote_role) { tBTA_PAN_ROLE bta_local_role = btpan_role_to_bta(local_role); tBTA_PAN_ROLE bta_remote_role = btpan_role_to_bta(remote_role); btpan_new_conn(-1, *bd_addr, bta_local_role, bta_remote_role); @@ -225,8 +231,7 @@ static void btif_in_pan_generic_evt(uint16_t event, char* p_param) { if (conn) { btpan_conn_local_role = bta_role_to_btpan(conn->local_role); btpan_remote_role = bta_role_to_btpan(conn->remote_role); - callback.connection_state_cb(BTPAN_STATE_DISCONNECTING, - BT_STATUS_SUCCESS, &conn->peer, + callback.connection_state_cb(BTPAN_STATE_DISCONNECTING, BT_STATUS_SUCCESS, &conn->peer, btpan_conn_local_role, btpan_remote_role); } } break; @@ -241,8 +246,8 @@ static bt_status_t btpan_disconnect(const RawAddress* bd_addr) { if (conn && conn->handle >= 0) { /* Inform the application that the disconnect has been initiated * successfully */ - btif_transfer_context(btif_in_pan_generic_evt, BTIF_PAN_CB_DISCONNECTING, - (char*)bd_addr, sizeof(RawAddress), NULL); + btif_transfer_context(btif_in_pan_generic_evt, BTIF_PAN_CB_DISCONNECTING, (char*)bd_addr, + sizeof(RawAddress), NULL); BTA_PanClose(conn->handle); return BT_STATUS_SUCCESS; } @@ -251,9 +256,12 @@ static bt_status_t btpan_disconnect(const RawAddress* bd_addr) { static int pan_pth = -1; void create_tap_read_thread(int tap_fd) { - if (pan_pth < 0) pan_pth = btsock_thread_create(btpan_tap_fd_signaled, NULL); - if (pan_pth >= 0) + if (pan_pth < 0) { + pan_pth = btsock_thread_create(btpan_tap_fd_signaled, NULL); + } + if (pan_pth >= 0) { btsock_thread_add_fd(pan_pth, tap_fd, 0, SOCK_THREAD_FD_RD, 0); + } } void destroy_tap_read_thread(void) { @@ -268,15 +276,17 @@ static int tap_if_up(const char* devname, const RawAddress& addr) { int sk, err; sk = socket(AF_INET, SOCK_DGRAM, 0); - if (sk < 0) return -1; + if (sk < 0) { + return -1; + } // set mac addr memset(&ifr, 0, sizeof(ifr)); strlcpy(ifr.ifr_name, devname, IFNAMSIZ); err = ioctl(sk, SIOCGIFHWADDR, &ifr); if (err < 0) { - log::error("Could not get network hardware for interface:{}, errno:{}", - devname, strerror(errno)); + log::error("Could not get network hardware for interface:{}, errno:{}", devname, + strerror(errno)); close(sk); return -1; } @@ -300,8 +310,7 @@ static int tap_if_up(const char* devname, const RawAddress& addr) { err = ioctl(sk, SIOCSIFHWADDR, (caddr_t)&ifr); if (err < 0) { - log::error("Could not set bt address for interface:{}, errno:{}", devname, - strerror(errno)); + log::error("Could not set bt address for interface:{}, errno:{}", devname, strerror(errno)); close(sk); return -1; } @@ -316,8 +325,7 @@ static int tap_if_up(const char* devname, const RawAddress& addr) { err = ioctl(sk, SIOCSIFFLAGS, (caddr_t)&ifr); if (err < 0) { - log::error("Could not bring up network interface:{}, errno:{}", devname, - errno); + log::error("Could not bring up network interface:{}, errno:{}", devname, errno); close(sk); return -1; } @@ -331,7 +339,9 @@ static int tap_if_down(const char* devname) { int sk; sk = socket(AF_INET, SOCK_DGRAM, 0); - if (sk < 0) return -1; + if (sk < 0) { + return -1; + } memset(&ifr, 0, sizeof(ifr)); strlcpy(ifr.ifr_name, devname, IF_NAMESIZE); @@ -346,13 +356,14 @@ static int tap_if_down(const char* devname) { } void btpan_set_flow_control(bool enable) { - if (btpan_cb.tap_fd == -1) return; + if (btpan_cb.tap_fd == -1) { + return; + } btpan_cb.flow = enable; if (enable) { btsock_thread_add_fd(pan_pth, btpan_cb.tap_fd, 0, SOCK_THREAD_FD_RD, 0); - do_in_main_thread(FROM_HERE, - base::BindOnce(btu_exec_tap_fd_read, btpan_cb.tap_fd)); + do_in_main_thread(FROM_HERE, base::BindOnce(btu_exec_tap_fd_read, btpan_cb.tap_fd)); } } @@ -382,8 +393,7 @@ int btpan_tap_open() { return err; } if (tap_if_up(TAP_IF_NAME, - bluetooth::ToRawAddress( - bluetooth::shim::GetController()->GetMacAddress())) == 0) { + bluetooth::ToRawAddress(bluetooth::shim::GetController()->GetMacAddress())) == 0) { int flags = fcntl(fd, F_GETFL, 0); fcntl(fd, F_SETFL, flags | O_NONBLOCK); return fd; @@ -393,9 +403,8 @@ int btpan_tap_open() { return INVALID_FD; } -int btpan_tap_send(int tap_fd, const RawAddress& src, const RawAddress& dst, - uint16_t proto, const char* buf, uint16_t len, - bool /* ext */, bool /* forward */) { +int btpan_tap_send(int tap_fd, const RawAddress& src, const RawAddress& dst, uint16_t proto, + const char* buf, uint16_t len, bool /* ext */, bool /* forward */) { if (tap_fd != INVALID_FD) { tETH_HDR eth_hdr; eth_hdr.h_dest = dst; @@ -419,46 +428,56 @@ int btpan_tap_send(int tap_fd, const RawAddress& src, const RawAddress& dst, } int btpan_tap_close(int fd) { - if (tap_if_down(TAP_IF_NAME) == 0) close(fd); - if (pan_pth >= 0) btsock_thread_wakeup(pan_pth); + if (tap_if_down(TAP_IF_NAME) == 0) { + close(fd); + } + if (pan_pth >= 0) { + btsock_thread_wakeup(pan_pth); + } return 0; } btpan_conn_t* btpan_find_conn_handle(uint16_t handle) { for (int i = 0; i < MAX_PAN_CONNS; i++) { - if (btpan_cb.conns[i].handle == handle) return &btpan_cb.conns[i]; + if (btpan_cb.conns[i].handle == handle) { + return &btpan_cb.conns[i]; + } } return NULL; } btpan_conn_t* btpan_find_conn_addr(const RawAddress& addr) { for (int i = 0; i < MAX_PAN_CONNS; i++) { - if (btpan_cb.conns[i].peer == addr) return &btpan_cb.conns[i]; + if (btpan_cb.conns[i].peer == addr) { + return &btpan_cb.conns[i]; + } } return NULL; } static void btpan_open_conn(btpan_conn_t* conn, tBTA_PAN* p_data) { - log::verbose( - "btpan_open_conn: local_role:{}, peer_role: {}, handle:{}, conn: {}", - p_data->open.local_role, p_data->open.peer_role, p_data->open.handle, - fmt::ptr(conn)); - - if (conn == NULL) - conn = btpan_new_conn(p_data->open.handle, p_data->open.bd_addr, - p_data->open.local_role, p_data->open.peer_role); + log::verbose("btpan_open_conn: local_role:{}, peer_role: {}, handle:{}, conn: {}", + p_data->open.local_role, p_data->open.peer_role, p_data->open.handle, + fmt::ptr(conn)); + + if (conn == NULL) { + conn = btpan_new_conn(p_data->open.handle, p_data->open.bd_addr, p_data->open.local_role, + p_data->open.peer_role); + } if (conn) { log::verbose( - "btpan_open_conn:tap_fd:{}, open_count:{}, conn->handle:{} should = " - "handle:{}, local_role:{}, remote_role:{}", - btpan_cb.tap_fd, btpan_cb.open_count, conn->handle, p_data->open.handle, - conn->local_role, conn->remote_role); + "btpan_open_conn:tap_fd:{}, open_count:{}, conn->handle:{} should = " + "handle:{}, local_role:{}, remote_role:{}", + btpan_cb.tap_fd, btpan_cb.open_count, conn->handle, p_data->open.handle, + conn->local_role, conn->remote_role); btpan_cb.open_count++; conn->handle = p_data->open.handle; if (btpan_cb.tap_fd < 0) { btpan_cb.tap_fd = btpan_tap_open(); - if (btpan_cb.tap_fd >= 0) create_tap_read_thread(btpan_cb.tap_fd); + if (btpan_cb.tap_fd >= 0) { + create_tap_read_thread(btpan_cb.tap_fd); + } } if (btpan_cb.tap_fd >= 0) { @@ -497,14 +516,12 @@ static void btpan_cleanup_conn(btpan_conn_t* conn) { } } -btpan_conn_t* btpan_new_conn(int handle, const RawAddress& addr, - tBTA_PAN_ROLE local_role, +btpan_conn_t* btpan_new_conn(int handle, const RawAddress& addr, tBTA_PAN_ROLE local_role, tBTA_PAN_ROLE remote_role) { for (int i = 0; i < MAX_PAN_CONNS; i++) { if (btpan_cb.conns[i].handle == -1) { - log::debug( - "Allocated new pan connection handle:{} local_role:{} remote_role:{}", - handle, local_role, remote_role); + log::debug("Allocated new pan connection handle:{} local_role:{} remote_role:{}", handle, + local_role, remote_role); btpan_cb.conns[i].handle = handle; btpan_cb.conns[i].peer = addr; btpan_cb.conns[i].local_role = local_role; @@ -526,8 +543,9 @@ void btpan_close_handle(btpan_conn_t* p) { static inline bool should_forward(tETH_HDR* hdr) { uint16_t proto = ntohs(hdr->h_proto); - if (proto == ETH_P_IP || proto == ETH_P_ARP || proto == ETH_P_IPV6) + if (proto == ETH_P_IP || proto == ETH_P_ARP || proto == ETH_P_IPV6) { return true; + } log::verbose("unknown proto:{:x}", proto); return false; } @@ -538,11 +556,10 @@ static int forward_bnep(tETH_HDR* eth_hdr, BT_HDR* hdr) { // Find the right connection to send this frame over. for (int i = 0; i < MAX_PAN_CONNS; i++) { uint16_t handle = btpan_cb.conns[i].handle; - if (handle != (uint16_t)-1 && - (broadcast || btpan_cb.conns[i].eth_addr == eth_hdr->h_dest || - btpan_cb.conns[i].peer == eth_hdr->h_dest)) { - int result = PAN_WriteBuf(handle, eth_hdr->h_dest, eth_hdr->h_src, - ntohs(eth_hdr->h_proto), hdr, 0); + if (handle != (uint16_t)-1 && (broadcast || btpan_cb.conns[i].eth_addr == eth_hdr->h_dest || + btpan_cb.conns[i].peer == eth_hdr->h_dest)) { + int result = PAN_WriteBuf(handle, eth_hdr->h_dest, eth_hdr->h_src, ntohs(eth_hdr->h_proto), + hdr, 0); switch (result) { case PAN_Q_SIZE_EXCEEDED: return FORWARD_CONGEST; @@ -566,17 +583,15 @@ static void bta_pan_callback_transfer(uint16_t event, char* p_param) { break; case BTA_PAN_SET_ROLE_EVT: { int btpan_role = bta_role_to_btpan(p_data->set_role.role); - bt_status_t status = - (p_data->set_role.status) ? BT_STATUS_SUCCESS : BT_STATUS_FAIL; - btpan_control_state_t state = - btpan_role == 0 ? BTPAN_STATE_DISABLED : BTPAN_STATE_ENABLED; + bt_status_t status = (p_data->set_role.status) ? BT_STATUS_SUCCESS : BT_STATUS_FAIL; + btpan_control_state_t state = btpan_role == 0 ? BTPAN_STATE_DISABLED : BTPAN_STATE_ENABLED; callback.control_state_cb(state, btpan_role, status, TAP_IF_NAME); break; } case BTA_PAN_OPENING_EVT: { btpan_conn_t* conn; - log::verbose("BTA_PAN_OPENING_EVT handle {}, addr: {}", - p_data->opening.handle, p_data->opening.bd_addr); + log::verbose("BTA_PAN_OPENING_EVT handle {}, addr: {}", p_data->opening.handle, + p_data->opening.bd_addr); conn = btpan_find_conn_addr(p_data->opening.bd_addr); asrt(conn != NULL); @@ -585,10 +600,11 @@ static void bta_pan_callback_transfer(uint16_t event, char* p_param) { int btpan_conn_local_role = bta_role_to_btpan(conn->local_role); int btpan_remote_role = bta_role_to_btpan(conn->remote_role); callback.connection_state_cb(BTPAN_STATE_CONNECTING, BT_STATUS_SUCCESS, - &p_data->opening.bd_addr, - btpan_conn_local_role, btpan_remote_role); - } else + &p_data->opening.bd_addr, btpan_conn_local_role, + btpan_remote_role); + } else { log::error("connection not found"); + } break; } case BTA_PAN_OPEN_EVT: { @@ -612,8 +628,8 @@ static void bta_pan_callback_transfer(uint16_t event, char* p_param) { * conn->remote_role); */ int btpan_conn_local_role = bta_role_to_btpan(p_data->open.local_role); int btpan_remote_role = bta_role_to_btpan(p_data->open.peer_role); - callback.connection_state_cb(state, status, &p_data->open.bd_addr, - btpan_conn_local_role, btpan_remote_role); + callback.connection_state_cb(state, status, &p_data->open.bd_addr, btpan_conn_local_role, + btpan_remote_role); break; } case BTA_PAN_CLOSE_EVT: { @@ -624,12 +640,12 @@ static void bta_pan_callback_transfer(uint16_t event, char* p_param) { if (conn && conn->handle >= 0) { int btpan_conn_local_role = bta_role_to_btpan(conn->local_role); int btpan_remote_role = bta_role_to_btpan(conn->remote_role); - callback.connection_state_cb(BTPAN_STATE_DISCONNECTED, (bt_status_t)0, - &conn->peer, btpan_conn_local_role, - btpan_remote_role); + callback.connection_state_cb(BTPAN_STATE_DISCONNECTED, (bt_status_t)0, &conn->peer, + btpan_conn_local_role, btpan_remote_role); btpan_cleanup_conn(conn); - } else + } else { log::error("pan handle not found ({})", p_data->close.handle); + } break; } default: @@ -639,15 +655,16 @@ static void bta_pan_callback_transfer(uint16_t event, char* p_param) { } static void bta_pan_callback(tBTA_PAN_EVT event, tBTA_PAN* p_data) { - btif_transfer_context(bta_pan_callback_transfer, event, (char*)p_data, - sizeof(tBTA_PAN), NULL); + btif_transfer_context(bta_pan_callback_transfer, event, (char*)p_data, sizeof(tBTA_PAN), NULL); } #define IS_EXCEPTION(e) ((e) & (POLLHUP | POLLRDHUP | POLLERR | POLLNVAL)) static void btu_exec_tap_fd_read(int fd) { struct pollfd ufd; - if (fd == INVALID_FD || fd != btpan_cb.tap_fd) return; + if (fd == INVALID_FD || fd != btpan_cb.tap_fd) { + return; + } // Don't occupy BTU context too long, avoid buffer overruns and // give other profiles a chance to run by limiting the amount of memory @@ -666,8 +683,7 @@ static void btu_exec_tap_fd_read(int fd) { // attempt. if (!btpan_cb.congest_packet_size) { ssize_t ret; - OSI_NO_INTR(ret = read(fd, btpan_cb.congest_packet, - sizeof(btpan_cb.congest_packet))); + OSI_NO_INTR(ret = read(fd, btpan_cb.congest_packet, sizeof(btpan_cb.congest_packet))); switch (ret) { case -1: log::error("unable to read from driver: {}", strerror(errno)); @@ -687,8 +703,7 @@ static void btu_exec_tap_fd_read(int fd) { } } - memcpy(packet, btpan_cb.congest_packet, - MIN(btpan_cb.congest_packet_size, buffer->len)); + memcpy(packet, btpan_cb.congest_packet, MIN(btpan_cb.congest_packet_size, buffer->len)); buffer->len = MIN(btpan_cb.congest_packet_size, buffer->len); if (buffer->len > sizeof(tETH_HDR) && should_forward((tETH_HDR*)packet)) { @@ -702,8 +717,9 @@ static void btu_exec_tap_fd_read(int fd) { // Skip the ethernet header. buffer->len -= sizeof(tETH_HDR); buffer->offset += sizeof(tETH_HDR); - if (forward_bnep(&hdr, buffer) != FORWARD_CONGEST) + if (forward_bnep(&hdr, buffer) != FORWARD_CONGEST) { btpan_cb.congest_packet_size = 0; + } } else { log::warn("dropping packet of length {}", buffer->len); btpan_cb.congest_packet_size = 0; @@ -717,7 +733,9 @@ static void btu_exec_tap_fd_read(int fd) { int ret; OSI_NO_INTR(ret = poll(&ufd, 1, 0)); - if (ret <= 0 || IS_EXCEPTION(ufd.revents)) break; + if (ret <= 0 || IS_EXCEPTION(ufd.revents)) { + break; + } } if (btpan_cb.flow) { @@ -727,18 +745,20 @@ static void btu_exec_tap_fd_read(int fd) { } static void btif_pan_close_all_conns() { - if (!stack_initialized) return; + if (!stack_initialized) { + return; + } for (int i = 0; i < MAX_PAN_CONNS; ++i) { - if (btpan_cb.conns[i].handle != -1) BTA_PanClose(btpan_cb.conns[i].handle); + if (btpan_cb.conns[i].handle != -1) { + BTA_PanClose(btpan_cb.conns[i].handle); + } } } -static void btpan_tap_fd_signaled(int fd, int type, int flags, - uint32_t user_id) { - log::assert_that( - btpan_cb.tap_fd == INVALID_FD || btpan_cb.tap_fd == fd, - "assert failed: btpan_cb.tap_fd == INVALID_FD || btpan_cb.tap_fd == fd"); +static void btpan_tap_fd_signaled(int fd, int type, int flags, uint32_t user_id) { + log::assert_that(btpan_cb.tap_fd == INVALID_FD || btpan_cb.tap_fd == fd, + "assert failed: btpan_cb.tap_fd == INVALID_FD || btpan_cb.tap_fd == fd"); if (btpan_cb.tap_fd != fd) { log::warn("Signaled on mismatched fds exp:{} act:{}", btpan_cb.tap_fd, fd); diff --git a/system/btif/src/btif_profile_queue.cc b/system/btif/src/btif_profile_queue.cc index 95186a43904..b640c70d02e 100644 --- a/system/btif/src/btif_profile_queue.cc +++ b/system/btif/src/btif_profile_queue.cc @@ -48,15 +48,13 @@ using namespace bluetooth; // Class to store connect info. class ConnectNode { - public: - ConnectNode(const RawAddress& address, uint16_t uuid, - btif_connect_cb_t connect_cb) +public: + ConnectNode(const RawAddress& address, uint16_t uuid, btif_connect_cb_t connect_cb) : address_(address), uuid_(uuid), busy_(false), connect_cb_(connect_cb) {} std::string ToString() const { - return base::StringPrintf("address=%s UUID=%04X busy=%s", - ADDRESS_TO_LOGGABLE_CSTR(address_), uuid_, - (busy_) ? "true" : "false"); + return base::StringPrintf("address=%s UUID=%04X busy=%s", ADDRESS_TO_LOGGABLE_CSTR(address_), + uuid_, (busy_) ? "true" : "false"); } const RawAddress& address() const { return address_; } @@ -70,12 +68,14 @@ class ConnectNode { * return value is BT_STATUS_SUCCESS. */ bt_status_t connect() { - if (busy_) return BT_STATUS_SUCCESS; + if (busy_) { + return BT_STATUS_SUCCESS; + } busy_ = true; return connect_cb_(&address_, uuid_); } - private: +private: RawAddress address_; uint16_t uuid_; bool busy_; @@ -94,18 +94,15 @@ static const size_t MAX_REASONABLE_REQUESTS = 20; * Queue helper functions ******************************************************************************/ -static void queue_int_add(uint16_t uuid, const RawAddress& bda, - btif_connect_cb_t connect_cb) { +static void queue_int_add(uint16_t uuid, const RawAddress& bda, btif_connect_cb_t connect_cb) { // Sanity check to make sure we're not leaking connection requests - log::assert_that( - connect_queue.size() < MAX_REASONABLE_REQUESTS, - "assert failed: connect_queue.size() < MAX_REASONABLE_REQUESTS"); + log::assert_that(connect_queue.size() < MAX_REASONABLE_REQUESTS, + "assert failed: connect_queue.size() < MAX_REASONABLE_REQUESTS"); ConnectNode param(bda, uuid, connect_cb); for (const auto& node : connect_queue) { if (node.uuid() == param.uuid() && node.address() == param.address()) { - log::error("Dropping duplicate profile connection request:{}", - param.ToString()); + log::error("Dropping duplicate profile connection request:{}", param.ToString()); return; } } @@ -117,7 +114,9 @@ static void queue_int_add(uint16_t uuid, const RawAddress& bda, } static void queue_int_advance() { - if (connect_queue.empty()) return; + if (connect_queue.empty()) { + return; + } const ConnectNode& head = connect_queue.front(); log::info("removing connection request: {}", head.ToString()); @@ -151,10 +150,8 @@ static void queue_int_release() { connect_queue.clear(); } * Returns BT_STATUS_SUCCESS if successful * ******************************************************************************/ -bt_status_t btif_queue_connect(uint16_t uuid, const RawAddress* bda, - btif_connect_cb_t connect_cb) { - return do_in_jni_thread( - base::BindOnce(&queue_int_add, uuid, *bda, connect_cb)); +bt_status_t btif_queue_connect(uint16_t uuid, const RawAddress* bda, btif_connect_cb_t connect_cb) { + return do_in_jni_thread(base::BindOnce(&queue_int_add, uuid, *bda, connect_cb)); } /******************************************************************************* @@ -180,26 +177,26 @@ void btif_queue_cleanup(uint16_t uuid) { * Returns void * ******************************************************************************/ -void btif_queue_advance() { - do_in_jni_thread(base::BindOnce(&queue_int_advance)); -} +void btif_queue_advance() { do_in_jni_thread(base::BindOnce(&queue_int_advance)); } bt_status_t btif_queue_connect_next(void) { // The call must be on the JNI thread, otherwise the access to connect_queue // is not thread-safe. log::assert_that(is_on_jni_thread(), "assert failed: is_on_jni_thread()"); - if (connect_queue.empty()) return BT_STATUS_FAIL; - if (!stack_manager_get_interface()->get_stack_is_running()) + if (connect_queue.empty()) { + return BT_STATUS_FAIL; + } + if (!stack_manager_get_interface()->get_stack_is_running()) { return BT_STATUS_UNEXPECTED_STATE; + } ConnectNode& head = connect_queue.front(); log::info("Executing profile connection request:{}", head.ToString()); bt_status_t b_status = head.connect(); if (b_status != BT_STATUS_SUCCESS) { - log::info("connect {} failed, advance to next scheduled connection.", - head.ToString()); + log::info("connect {} failed, advance to next scheduled connection.", head.ToString()); btif_queue_advance(); } return b_status; @@ -216,8 +213,7 @@ bt_status_t btif_queue_connect_next(void) { ******************************************************************************/ void btif_queue_release() { log::info(""); - if (do_in_jni_thread(base::BindOnce(&queue_int_release)) != - BT_STATUS_SUCCESS) { + if (do_in_jni_thread(base::BindOnce(&queue_int_release)) != BT_STATUS_SUCCESS) { log::fatal("Failed to schedule on JNI thread"); } } diff --git a/system/btif/src/btif_profile_storage.cc b/system/btif/src/btif_profile_storage.cc index 9f4154316d0..8fdb2d3056a 100644 --- a/system/btif/src/btif_profile_storage.cc +++ b/system/btif/src/btif_profile_storage.cc @@ -73,20 +73,19 @@ using namespace bluetooth; > */ -#define BTIF_HID_INFO_ENTRY_SIZE_MAX \ - (STORAGE_BDADDR_STRING_SZ + 1 + STORAGE_HID_ATRR_MASK_SIZE + 1 + \ - STORAGE_HID_SUB_CLASS_SIZE + 1 + STORAGE_HID_APP_ID_SIZE + 1 + \ - STORAGE_HID_VENDOR_ID_SIZE + 1 + STORAGE_HID_PRODUCT_ID_SIZE + 1 + \ - STORAGE_HID_VERSION_SIZE + 1 + STORAGE_HID_CTRY_CODE_SIZE + 1 + \ - STORAGE_HID_DESC_LEN_SIZE + 1 + STORAGE_HID_DESC_MAX_SIZE + 1) +#define BTIF_HID_INFO_ENTRY_SIZE_MAX \ + (STORAGE_BDADDR_STRING_SZ + 1 + STORAGE_HID_ATRR_MASK_SIZE + 1 + STORAGE_HID_SUB_CLASS_SIZE + \ + 1 + STORAGE_HID_APP_ID_SIZE + 1 + STORAGE_HID_VENDOR_ID_SIZE + 1 + \ + STORAGE_HID_PRODUCT_ID_SIZE + 1 + STORAGE_HID_VERSION_SIZE + 1 + STORAGE_HID_CTRY_CODE_SIZE + \ + 1 + STORAGE_HID_DESC_LEN_SIZE + 1 + STORAGE_HID_DESC_MAX_SIZE + 1) #define STORAGE_HID_DB_VERSION (1) -static void btif_storage_hid_device_info( - std::string bdstr, uint16_t attr_mask, uint8_t sub_class, uint8_t app_id, - uint16_t vendor_id, uint16_t product_id, uint16_t version, - uint8_t ctry_code, uint16_t ssr_max_latency, uint16_t ssr_min_tout, - uint16_t dl_len, uint8_t* dsc_list) { +static void btif_storage_hid_device_info(std::string bdstr, uint16_t attr_mask, uint8_t sub_class, + uint8_t app_id, uint16_t vendor_id, uint16_t product_id, + uint16_t version, uint8_t ctry_code, + uint16_t ssr_max_latency, uint16_t ssr_min_tout, + uint16_t dl_len, uint8_t* dsc_list) { btif_config_set_int(bdstr, BTIF_STORAGE_KEY_HID_ATTR_MASK, attr_mask); btif_config_set_int(bdstr, BTIF_STORAGE_KEY_HID_SUB_CLASS, sub_class); btif_config_set_int(bdstr, BTIF_STORAGE_KEY_HID_APP_ID, app_id); @@ -94,19 +93,15 @@ static void btif_storage_hid_device_info( btif_config_set_int(bdstr, BTIF_STORAGE_KEY_HID_PRODUCT_ID, product_id); btif_config_set_int(bdstr, BTIF_STORAGE_KEY_HID_VERSION, version); btif_config_set_int(bdstr, BTIF_STORAGE_KEY_HID_COUNTRY_CODE, ctry_code); - btif_config_set_int(bdstr, BTIF_STORAGE_KEY_HID_SSR_MAX_LATENCY, - ssr_max_latency); - btif_config_set_int(bdstr, BTIF_STORAGE_KEY_HID_SSR_MIN_TIMEOUT, - ssr_min_tout); - if (dl_len > 0) - btif_config_set_bin(bdstr, BTIF_STORAGE_KEY_HID_DESCRIPTOR, dsc_list, - dl_len); + btif_config_set_int(bdstr, BTIF_STORAGE_KEY_HID_SSR_MAX_LATENCY, ssr_max_latency); + btif_config_set_int(bdstr, BTIF_STORAGE_KEY_HID_SSR_MIN_TIMEOUT, ssr_min_tout); + if (dl_len > 0) { + btif_config_set_bin(bdstr, BTIF_STORAGE_KEY_HID_DESCRIPTOR, dsc_list, dl_len); + } } -static void btif_storage_hogp_device_info(std::string bdstr, uint16_t attr_mask, - uint8_t sub_class, uint8_t app_id, - uint16_t vendor_id, - uint16_t product_id, uint16_t version, - uint8_t ctry_code, uint16_t dl_len, +static void btif_storage_hogp_device_info(std::string bdstr, uint16_t attr_mask, uint8_t sub_class, + uint8_t app_id, uint16_t vendor_id, uint16_t product_id, + uint16_t version, uint8_t ctry_code, uint16_t dl_len, uint8_t* dsc_list) { btif_config_set_int(bdstr, BTIF_STORAGE_KEY_HOGP_ATTR_MASK, attr_mask); btif_config_set_int(bdstr, BTIF_STORAGE_KEY_HOGP_SUB_CLASS, sub_class); @@ -115,9 +110,9 @@ static void btif_storage_hogp_device_info(std::string bdstr, uint16_t attr_mask, btif_config_set_int(bdstr, BTIF_STORAGE_KEY_HOGP_PRODUCT_ID, product_id); btif_config_set_int(bdstr, BTIF_STORAGE_KEY_HOGP_VERSION, version); btif_config_set_int(bdstr, BTIF_STORAGE_KEY_HOGP_COUNTRY_CODE, ctry_code); - if (dl_len > 0) - btif_config_set_bin(bdstr, BTIF_STORAGE_KEY_HOGP_DESCRIPTOR, dsc_list, - dl_len); + if (dl_len > 0) { + btif_config_set_bin(bdstr, BTIF_STORAGE_KEY_HOGP_DESCRIPTOR, dsc_list, dl_len); + } } /******************************************************************************* * @@ -131,18 +126,19 @@ static void btif_storage_hogp_device_info(std::string bdstr, uint16_t attr_mask, * ******************************************************************************/ -bt_status_t btif_storage_add_hid_device_info( - const tAclLinkSpec& link_spec, uint16_t attr_mask, uint8_t sub_class, - uint8_t app_id, uint16_t vendor_id, uint16_t product_id, uint16_t version, - uint8_t ctry_code, uint16_t ssr_max_latency, uint16_t ssr_min_tout, - uint16_t dl_len, uint8_t* dsc_list) { +bt_status_t btif_storage_add_hid_device_info(const tAclLinkSpec& link_spec, uint16_t attr_mask, + uint8_t sub_class, uint8_t app_id, uint16_t vendor_id, + uint16_t product_id, uint16_t version, + uint8_t ctry_code, uint16_t ssr_max_latency, + uint16_t ssr_min_tout, uint16_t dl_len, + uint8_t* dsc_list) { log::verbose("link spec: {}", link_spec.ToRedactedStringForLogging()); std::string bdstr = link_spec.addrt.bda.ToString(); if (!com::android::bluetooth::flags::allow_switching_hid_and_hogp()) { - btif_storage_hid_device_info( - bdstr, attr_mask, sub_class, app_id, vendor_id, product_id, version, - ctry_code, ssr_max_latency, ssr_min_tout, dl_len, dsc_list); + btif_storage_hid_device_info(bdstr, attr_mask, sub_class, app_id, vendor_id, product_id, + version, ctry_code, ssr_max_latency, ssr_min_tout, dl_len, + dsc_list); return BT_STATUS_SUCCESS; } @@ -150,16 +146,14 @@ bt_status_t btif_storage_add_hid_device_info( log::error("Unexpected transport!"); return BT_STATUS_UNHANDLED; } - btif_config_set_int(bdstr, BTIF_STORAGE_KEY_HID_DB_VERSION, - STORAGE_HID_DB_VERSION); + btif_config_set_int(bdstr, BTIF_STORAGE_KEY_HID_DB_VERSION, STORAGE_HID_DB_VERSION); if (link_spec.transport == BT_TRANSPORT_BR_EDR) { - btif_storage_hid_device_info( - bdstr, attr_mask, sub_class, app_id, vendor_id, product_id, version, - ctry_code, ssr_max_latency, ssr_min_tout, dl_len, dsc_list); + btif_storage_hid_device_info(bdstr, attr_mask, sub_class, app_id, vendor_id, product_id, + version, ctry_code, ssr_max_latency, ssr_min_tout, dl_len, + dsc_list); } else { - btif_storage_hogp_device_info(bdstr, attr_mask, sub_class, app_id, - vendor_id, product_id, version, ctry_code, - dl_len, dsc_list); + btif_storage_hogp_device_info(bdstr, attr_mask, sub_class, app_id, vendor_id, product_id, + version, ctry_code, dl_len, dsc_list); } return BT_STATUS_SUCCESS; @@ -170,8 +164,9 @@ static void btif_storage_load_bonded_hid_device(const tAclLinkSpec link_spec) { int value; bool reconnect_allowed = true; - if (!btif_config_get_int(name, BTIF_STORAGE_KEY_HID_ATTR_MASK, &value)) + if (!btif_config_get_int(name, BTIF_STORAGE_KEY_HID_ATTR_MASK, &value)) { return; + } uint16_t attr_mask = (uint16_t)value; if (btif_in_fetch_bonded_device(name) != BT_STATUS_SUCCESS) { @@ -207,8 +202,7 @@ static void btif_storage_load_bonded_hid_device(const tAclLinkSpec link_spec) { btif_config_get_int(name, BTIF_STORAGE_KEY_HID_SSR_MIN_TIMEOUT, &value); dscp_info.ssr_min_tout = (uint16_t)value; - size_t len = - btif_config_get_bin_length(name, BTIF_STORAGE_KEY_HID_DESCRIPTOR); + size_t len = btif_config_get_bin_length(name, BTIF_STORAGE_KEY_HID_DESCRIPTOR); if (len > 0) { dscp_info.descriptor.dl_len = (uint16_t)len; dscp_info.descriptor.dsc_list = (uint8_t*)alloca(len); @@ -218,8 +212,7 @@ static void btif_storage_load_bonded_hid_device(const tAclLinkSpec link_spec) { btif_storage_get_hid_connection_policy(link_spec, &reconnect_allowed); // add extracted information to BTA HH - btif_hh_load_bonded_dev(link_spec, attr_mask, sub_class, app_id, dscp_info, - reconnect_allowed); + btif_hh_load_bonded_dev(link_spec, attr_mask, sub_class, app_id, dscp_info, reconnect_allowed); } static void btif_storage_load_bonded_hogp_device(const tAclLinkSpec link_spec) { @@ -227,8 +220,9 @@ static void btif_storage_load_bonded_hogp_device(const tAclLinkSpec link_spec) { int value; bool reconnect_allowed = true; - if (!btif_config_get_int(name, BTIF_STORAGE_KEY_HOGP_ATTR_MASK, &value)) + if (!btif_config_get_int(name, BTIF_STORAGE_KEY_HOGP_ATTR_MASK, &value)) { return; + } uint16_t attr_mask = (uint16_t)value; if (btif_in_fetch_bonded_device(name) != BT_STATUS_SUCCESS) { @@ -256,8 +250,7 @@ static void btif_storage_load_bonded_hogp_device(const tAclLinkSpec link_spec) { btif_config_get_int(name, BTIF_STORAGE_KEY_HOGP_COUNTRY_CODE, &value); dscp_info.ctry_code = (uint8_t)value; - size_t len = - btif_config_get_bin_length(name, BTIF_STORAGE_KEY_HOGP_DESCRIPTOR); + size_t len = btif_config_get_bin_length(name, BTIF_STORAGE_KEY_HOGP_DESCRIPTOR); if (len > 0) { dscp_info.descriptor.dl_len = (uint16_t)len; dscp_info.descriptor.dsc_list = (uint8_t*)alloca(len); @@ -267,8 +260,7 @@ static void btif_storage_load_bonded_hogp_device(const tAclLinkSpec link_spec) { btif_storage_get_hid_connection_policy(link_spec, &reconnect_allowed); // add extracted information to BTA HH - btif_hh_load_bonded_dev(link_spec, attr_mask, sub_class, app_id, dscp_info, - reconnect_allowed); + btif_hh_load_bonded_dev(link_spec, attr_mask, sub_class, app_id, dscp_info, reconnect_allowed); } /******************************************************************************* * @@ -356,15 +348,12 @@ bt_status_t btif_storage_remove_hid_info(const tAclLinkSpec& link_spec) { } // Check if a given profile is supported. -static bool btif_device_supports_profile(const std::string& device, - const Uuid& profile) { +static bool btif_device_supports_profile(const std::string& device, const Uuid& profile) { int size = STORAGE_UUID_STRING_SIZE * BT_MAX_NUM_UUIDS; char uuid_str[size]; - if (btif_config_get_str(device, BTIF_STORAGE_KEY_REMOTE_SERVICE, uuid_str, - &size)) { + if (btif_config_get_str(device, BTIF_STORAGE_KEY_REMOTE_SERVICE, uuid_str, &size)) { Uuid p_uuid[BT_MAX_NUM_UUIDS]; - size_t num_uuids = - btif_split_uuids_string(uuid_str, p_uuid, BT_MAX_NUM_UUIDS); + size_t num_uuids = btif_split_uuids_string(uuid_str, p_uuid, BT_MAX_NUM_UUIDS); for (size_t i = 0; i < num_uuids; i++) { if (p_uuid[i] == profile) { return true; @@ -376,13 +365,11 @@ static bool btif_device_supports_profile(const std::string& device, } static bool btif_device_supports_hogp(const std::string& device) { - return btif_device_supports_profile(device, - Uuid::From16Bit(UUID_SERVCLASS_LE_HID)); + return btif_device_supports_profile(device, Uuid::From16Bit(UUID_SERVCLASS_LE_HID)); } static bool btif_device_supports_classic_hid(const std::string& device) { - return btif_device_supports_profile( - device, Uuid::From16Bit(UUID_SERVCLASS_HUMAN_INTERFACE)); + return btif_device_supports_profile(device, Uuid::From16Bit(UUID_SERVCLASS_HUMAN_INTERFACE)); } /******************************************************************************* @@ -397,8 +384,7 @@ static bool btif_device_supports_classic_hid(const std::string& device) { bool btif_get_address_type(const RawAddress& bda, tBLE_ADDR_TYPE* p_addr_type); -std::vector> btif_storage_get_le_hid_devices( - void) { +std::vector> btif_storage_get_le_hid_devices(void) { std::vector> hid_addresses; for (const auto& bd_addr : btif_config_get_paired_devices()) { auto name = bd_addr.ToString(); @@ -414,8 +400,7 @@ std::vector> btif_storage_get_le_hid_devices( return hid_addresses; } -std::vector btif_storage_get_wake_capable_classic_hid_devices( - void) { +std::vector btif_storage_get_wake_capable_classic_hid_devices(void) { std::vector hid_addresses; for (const auto& bd_addr : btif_config_get_paired_devices()) { auto name = bd_addr.ToString(); @@ -428,8 +413,7 @@ std::vector btif_storage_get_wake_capable_classic_hid_devices( constexpr int kKeyboardMouseMask = COD_HID_COMBO & ~COD_HID_MAJOR; int cod_value; if (!btif_config_get_int(name, BTIF_STORAGE_KEY_DEV_CLASS, &cod_value) || - (cod_value & kHidMask) != kHidMask || - (cod_value & kKeyboardMouseMask) == 0) { + (cod_value & kHidMask) != kHidMask || (cod_value & kKeyboardMouseMask) == 0) { continue; } @@ -442,44 +426,32 @@ std::vector btif_storage_get_wake_capable_classic_hid_devices( } void btif_storage_add_hearing_aid(const HearingDevice& dev_info) { - do_in_jni_thread( - Bind( + do_in_jni_thread(Bind( [](const HearingDevice& dev_info) { std::string bdstr = dev_info.address.ToString(); log::verbose("saving hearing aid device: {}", dev_info.address); - btif_config_set_int( - bdstr, BTIF_STORAGE_KEY_HEARING_AID_SERVICE_CHANGED_CCC_HANDLE, - dev_info.service_changed_ccc_handle); - btif_config_set_int(bdstr, - BTIF_STORAGE_KEY_HEARING_AID_READ_PSM_HANDLE, + btif_config_set_int(bdstr, BTIF_STORAGE_KEY_HEARING_AID_SERVICE_CHANGED_CCC_HANDLE, + dev_info.service_changed_ccc_handle); + btif_config_set_int(bdstr, BTIF_STORAGE_KEY_HEARING_AID_READ_PSM_HANDLE, dev_info.read_psm_handle); - btif_config_set_int(bdstr, - BTIF_STORAGE_KEY_HEARING_AID_CAPABILITIES, + btif_config_set_int(bdstr, BTIF_STORAGE_KEY_HEARING_AID_CAPABILITIES, dev_info.capabilities); - btif_config_set_int(bdstr, BTIF_STORAGE_KEY_HEARING_AID_CODECS, - dev_info.codecs); - btif_config_set_int( - bdstr, BTIF_STORAGE_KEY_HEARING_AID_AUDIO_CONTROL_POINT, - dev_info.audio_control_point_handle); - btif_config_set_int(bdstr, - BTIF_STORAGE_KEY_HEARING_AID_VOLUME_HANDLE, + btif_config_set_int(bdstr, BTIF_STORAGE_KEY_HEARING_AID_CODECS, dev_info.codecs); + btif_config_set_int(bdstr, BTIF_STORAGE_KEY_HEARING_AID_AUDIO_CONTROL_POINT, + dev_info.audio_control_point_handle); + btif_config_set_int(bdstr, BTIF_STORAGE_KEY_HEARING_AID_VOLUME_HANDLE, dev_info.volume_handle); - btif_config_set_int( - bdstr, BTIF_STORAGE_KEY_HEARING_AID_AUDIO_STATUS_HANDLE, - dev_info.audio_status_handle); - btif_config_set_int( - bdstr, BTIF_STORAGE_KEY_HEARING_AID_AUDIO_STATUS_CCC_HANDLE, - dev_info.audio_status_ccc_handle); + btif_config_set_int(bdstr, BTIF_STORAGE_KEY_HEARING_AID_AUDIO_STATUS_HANDLE, + dev_info.audio_status_handle); + btif_config_set_int(bdstr, BTIF_STORAGE_KEY_HEARING_AID_AUDIO_STATUS_CCC_HANDLE, + dev_info.audio_status_ccc_handle); btif_config_set_uint64(bdstr, BTIF_STORAGE_KEY_HEARING_AID_SYNC_ID, dev_info.hi_sync_id); - btif_config_set_int(bdstr, - BTIF_STORAGE_KEY_HEARING_AID_RENDER_DELAY, + btif_config_set_int(bdstr, BTIF_STORAGE_KEY_HEARING_AID_RENDER_DELAY, dev_info.render_delay); - btif_config_set_int(bdstr, - BTIF_STORAGE_KEY_HEARING_AID_PREPARATION_DELAY, + btif_config_set_int(bdstr, BTIF_STORAGE_KEY_HEARING_AID_PREPARATION_DELAY, dev_info.preparation_delay); - btif_config_set_int( - bdstr, BTIF_STORAGE_KEY_HEARING_AID_IS_ACCEPTLISTED, true); + btif_config_set_int(bdstr, BTIF_STORAGE_KEY_HEARING_AID_IS_ACCEPTLISTED, true); }, dev_info)); } @@ -492,11 +464,9 @@ void btif_storage_load_bonded_hearing_aids() { int size = STORAGE_UUID_STRING_SIZE * BT_MAX_NUM_UUIDS; char uuid_str[size]; bool isHearingaidDevice = false; - if (btif_config_get_str(name, BTIF_STORAGE_KEY_REMOTE_SERVICE, uuid_str, - &size)) { + if (btif_config_get_str(name, BTIF_STORAGE_KEY_REMOTE_SERVICE, uuid_str, &size)) { Uuid p_uuid[BT_MAX_NUM_UUIDS]; - size_t num_uuids = - btif_split_uuids_string(uuid_str, p_uuid, BT_MAX_NUM_UUIDS); + size_t num_uuids = btif_split_uuids_string(uuid_str, p_uuid, BT_MAX_NUM_UUIDS); for (size_t i = 0; i < num_uuids; i++) { if (p_uuid[i] == Uuid::FromString("FDF0")) { isHearingaidDevice = true; @@ -517,76 +487,75 @@ void btif_storage_load_bonded_hearing_aids() { int value; uint8_t capabilities = 0; - if (btif_config_get_int(name, BTIF_STORAGE_KEY_HEARING_AID_CAPABILITIES, - &value)) + if (btif_config_get_int(name, BTIF_STORAGE_KEY_HEARING_AID_CAPABILITIES, &value)) { capabilities = value; + } uint16_t codecs = 0; - if (btif_config_get_int(name, BTIF_STORAGE_KEY_HEARING_AID_CODECS, &value)) + if (btif_config_get_int(name, BTIF_STORAGE_KEY_HEARING_AID_CODECS, &value)) { codecs = value; + } uint16_t audio_control_point_handle = 0; - if (btif_config_get_int( - name, BTIF_STORAGE_KEY_HEARING_AID_AUDIO_CONTROL_POINT, &value)) + if (btif_config_get_int(name, BTIF_STORAGE_KEY_HEARING_AID_AUDIO_CONTROL_POINT, &value)) { audio_control_point_handle = value; + } uint16_t audio_status_handle = 0; - if (btif_config_get_int( - name, BTIF_STORAGE_KEY_HEARING_AID_AUDIO_STATUS_HANDLE, &value)) + if (btif_config_get_int(name, BTIF_STORAGE_KEY_HEARING_AID_AUDIO_STATUS_HANDLE, &value)) { audio_status_handle = value; + } uint16_t audio_status_ccc_handle = 0; - if (btif_config_get_int( - name, BTIF_STORAGE_KEY_HEARING_AID_AUDIO_STATUS_CCC_HANDLE, &value)) + if (btif_config_get_int(name, BTIF_STORAGE_KEY_HEARING_AID_AUDIO_STATUS_CCC_HANDLE, &value)) { audio_status_ccc_handle = value; + } uint16_t service_changed_ccc_handle = 0; - if (btif_config_get_int( - name, BTIF_STORAGE_KEY_HEARING_AID_SERVICE_CHANGED_CCC_HANDLE, - &value)) + if (btif_config_get_int(name, BTIF_STORAGE_KEY_HEARING_AID_SERVICE_CHANGED_CCC_HANDLE, + &value)) { service_changed_ccc_handle = value; + } uint16_t volume_handle = 0; - if (btif_config_get_int(name, BTIF_STORAGE_KEY_HEARING_AID_VOLUME_HANDLE, - &value)) + if (btif_config_get_int(name, BTIF_STORAGE_KEY_HEARING_AID_VOLUME_HANDLE, &value)) { volume_handle = value; + } uint16_t read_psm_handle = 0; - if (btif_config_get_int(name, BTIF_STORAGE_KEY_HEARING_AID_READ_PSM_HANDLE, - &value)) + if (btif_config_get_int(name, BTIF_STORAGE_KEY_HEARING_AID_READ_PSM_HANDLE, &value)) { read_psm_handle = value; + } uint64_t lvalue; uint64_t hi_sync_id = 0; - if (btif_config_get_uint64(name, BTIF_STORAGE_KEY_HEARING_AID_SYNC_ID, - &lvalue)) + if (btif_config_get_uint64(name, BTIF_STORAGE_KEY_HEARING_AID_SYNC_ID, &lvalue)) { hi_sync_id = lvalue; + } uint16_t render_delay = 0; - if (btif_config_get_int(name, BTIF_STORAGE_KEY_HEARING_AID_RENDER_DELAY, - &value)) + if (btif_config_get_int(name, BTIF_STORAGE_KEY_HEARING_AID_RENDER_DELAY, &value)) { render_delay = value; + } uint16_t preparation_delay = 0; - if (btif_config_get_int( - name, BTIF_STORAGE_KEY_HEARING_AID_PREPARATION_DELAY, &value)) + if (btif_config_get_int(name, BTIF_STORAGE_KEY_HEARING_AID_PREPARATION_DELAY, &value)) { preparation_delay = value; + } bool is_acceptlisted = false; - if (btif_config_get_int(name, BTIF_STORAGE_KEY_HEARING_AID_IS_ACCEPTLISTED, - &value)) + if (btif_config_get_int(name, BTIF_STORAGE_KEY_HEARING_AID_IS_ACCEPTLISTED, &value)) { is_acceptlisted = value; + } // add extracted information to BTA Hearing Aid - do_in_main_thread( - FROM_HERE, - Bind(&HearingAid::AddFromStorage, - HearingDevice(bd_addr, capabilities, codecs, - audio_control_point_handle, audio_status_handle, - audio_status_ccc_handle, service_changed_ccc_handle, - volume_handle, read_psm_handle, hi_sync_id, - render_delay, preparation_delay), - is_acceptlisted)); + do_in_main_thread(FROM_HERE, + Bind(&HearingAid::AddFromStorage, + HearingDevice(bd_addr, capabilities, codecs, audio_control_point_handle, + audio_status_handle, audio_status_ccc_handle, + service_changed_ccc_handle, volume_handle, read_psm_handle, + hi_sync_id, render_delay, preparation_delay), + is_acceptlisted)); } } @@ -599,10 +568,8 @@ void btif_storage_remove_hearing_aid(const RawAddress& address) { btif_config_remove(addrstr, BTIF_STORAGE_KEY_HEARING_AID_AUDIO_CONTROL_POINT); btif_config_remove(addrstr, BTIF_STORAGE_KEY_HEARING_AID_VOLUME_HANDLE); btif_config_remove(addrstr, BTIF_STORAGE_KEY_HEARING_AID_AUDIO_STATUS_HANDLE); - btif_config_remove(addrstr, - BTIF_STORAGE_KEY_HEARING_AID_AUDIO_STATUS_CCC_HANDLE); - btif_config_remove(addrstr, - BTIF_STORAGE_KEY_HEARING_AID_SERVICE_CHANGED_CCC_HANDLE); + btif_config_remove(addrstr, BTIF_STORAGE_KEY_HEARING_AID_AUDIO_STATUS_CCC_HANDLE); + btif_config_remove(addrstr, BTIF_STORAGE_KEY_HEARING_AID_SERVICE_CHANGED_CCC_HANDLE); btif_config_remove(addrstr, BTIF_STORAGE_KEY_HEARING_AID_SYNC_ID); btif_config_remove(addrstr, BTIF_STORAGE_KEY_HEARING_AID_RENDER_DELAY); btif_config_remove(addrstr, BTIF_STORAGE_KEY_HEARING_AID_PREPARATION_DELAY); @@ -610,52 +577,45 @@ void btif_storage_remove_hearing_aid(const RawAddress& address) { } /** Set/Unset the hearing aid device HEARING_AID_IS_ACCEPTLISTED flag. */ -void btif_storage_set_hearing_aid_acceptlist(const RawAddress& address, - bool add_to_acceptlist) { +void btif_storage_set_hearing_aid_acceptlist(const RawAddress& address, bool add_to_acceptlist) { std::string addrstr = address.ToString(); - btif_config_set_int(addrstr, BTIF_STORAGE_KEY_HEARING_AID_IS_ACCEPTLISTED, - add_to_acceptlist); + btif_config_set_int(addrstr, BTIF_STORAGE_KEY_HEARING_AID_IS_ACCEPTLISTED, add_to_acceptlist); } /** Get the hearing aid device properties. */ -bool btif_storage_get_hearing_aid_prop( - const RawAddress& address, uint8_t* capabilities, uint64_t* hi_sync_id, - uint16_t* render_delay, uint16_t* preparation_delay, uint16_t* codecs) { +bool btif_storage_get_hearing_aid_prop(const RawAddress& address, uint8_t* capabilities, + uint64_t* hi_sync_id, uint16_t* render_delay, + uint16_t* preparation_delay, uint16_t* codecs) { std::string addrstr = address.ToString(); int value; - if (btif_config_get_int(addrstr, BTIF_STORAGE_KEY_HEARING_AID_CAPABILITIES, - &value)) { + if (btif_config_get_int(addrstr, BTIF_STORAGE_KEY_HEARING_AID_CAPABILITIES, &value)) { *capabilities = value; } else { return false; } - if (btif_config_get_int(addrstr, BTIF_STORAGE_KEY_HEARING_AID_CODECS, - &value)) { + if (btif_config_get_int(addrstr, BTIF_STORAGE_KEY_HEARING_AID_CODECS, &value)) { *codecs = value; } else { return false; } - if (btif_config_get_int(addrstr, BTIF_STORAGE_KEY_HEARING_AID_RENDER_DELAY, - &value)) { + if (btif_config_get_int(addrstr, BTIF_STORAGE_KEY_HEARING_AID_RENDER_DELAY, &value)) { *render_delay = value; } else { return false; } - if (btif_config_get_int( - addrstr, BTIF_STORAGE_KEY_HEARING_AID_PREPARATION_DELAY, &value)) { + if (btif_config_get_int(addrstr, BTIF_STORAGE_KEY_HEARING_AID_PREPARATION_DELAY, &value)) { *preparation_delay = value; } else { return false; } uint64_t lvalue; - if (btif_config_get_uint64(addrstr, BTIF_STORAGE_KEY_HEARING_AID_SYNC_ID, - &lvalue)) { + if (btif_config_get_uint64(addrstr, BTIF_STORAGE_KEY_HEARING_AID_SYNC_ID, &lvalue)) { *hi_sync_id = lvalue; } else { return false; @@ -665,16 +625,14 @@ bool btif_storage_get_hearing_aid_prop( } /** Set autoconnect information for LeAudio device */ -void btif_storage_set_leaudio_autoconnect(const RawAddress& addr, - bool autoconnect) { +void btif_storage_set_leaudio_autoconnect(const RawAddress& addr, bool autoconnect) { do_in_jni_thread(Bind( - [](const RawAddress& addr, bool autoconnect) { - std::string bdstr = addr.ToString(); - log::verbose("saving le audio device: {}", addr); - btif_config_set_int(bdstr, BTIF_STORAGE_KEY_LEAUDIO_AUTOCONNECT, - autoconnect); - }, - addr, autoconnect)); + [](const RawAddress& addr, bool autoconnect) { + std::string bdstr = addr.ToString(); + log::verbose("saving le audio device: {}", addr); + btif_config_set_int(bdstr, BTIF_STORAGE_KEY_LEAUDIO_AUTOCONNECT, autoconnect); + }, + addr, autoconnect)); } /** Store ASEs information */ @@ -683,12 +641,12 @@ void btif_storage_leaudio_update_handles_bin(const RawAddress& addr) { if (LeAudioClient::GetHandlesForStorage(addr, handles)) { do_in_jni_thread(Bind( - [](const RawAddress& bd_addr, std::vector handles) { - auto bdstr = bd_addr.ToString(); - btif_config_set_bin(bdstr, BTIF_STORAGE_KEY_LEAUDIO_HANDLES_BIN, - handles.data(), handles.size()); - }, - addr, std::move(handles))); + [](const RawAddress& bd_addr, std::vector handles) { + auto bdstr = bd_addr.ToString(); + btif_config_set_bin(bdstr, BTIF_STORAGE_KEY_LEAUDIO_HANDLES_BIN, handles.data(), + handles.size()); + }, + addr, std::move(handles))); } } @@ -698,23 +656,23 @@ void btif_storage_leaudio_update_pacs_bin(const RawAddress& addr) { if (LeAudioClient::GetSinkPacsForStorage(addr, sink_pacs)) { do_in_jni_thread(Bind( - [](const RawAddress& bd_addr, std::vector sink_pacs) { - auto bdstr = bd_addr.ToString(); - btif_config_set_bin(bdstr, BTIF_STORAGE_KEY_LEAUDIO_SINK_PACS_BIN, - sink_pacs.data(), sink_pacs.size()); - }, - addr, std::move(sink_pacs))); + [](const RawAddress& bd_addr, std::vector sink_pacs) { + auto bdstr = bd_addr.ToString(); + btif_config_set_bin(bdstr, BTIF_STORAGE_KEY_LEAUDIO_SINK_PACS_BIN, sink_pacs.data(), + sink_pacs.size()); + }, + addr, std::move(sink_pacs))); } std::vector source_pacs; if (LeAudioClient::GetSourcePacsForStorage(addr, source_pacs)) { do_in_jni_thread(Bind( - [](const RawAddress& bd_addr, std::vector source_pacs) { - auto bdstr = bd_addr.ToString(); - btif_config_set_bin(bdstr, BTIF_STORAGE_KEY_LEAUDIO_SOURCE_PACS_BIN, - source_pacs.data(), source_pacs.size()); - }, - addr, std::move(source_pacs))); + [](const RawAddress& bd_addr, std::vector source_pacs) { + auto bdstr = bd_addr.ToString(); + btif_config_set_bin(bdstr, BTIF_STORAGE_KEY_LEAUDIO_SOURCE_PACS_BIN, + source_pacs.data(), source_pacs.size()); + }, + addr, std::move(source_pacs))); } } @@ -724,50 +682,42 @@ void btif_storage_leaudio_update_ase_bin(const RawAddress& addr) { if (LeAudioClient::GetAsesForStorage(addr, ases)) { do_in_jni_thread(Bind( - [](const RawAddress& bd_addr, std::vector ases) { - auto bdstr = bd_addr.ToString(); - btif_config_set_bin(bdstr, BTIF_STORAGE_KEY_LEAUDIO_ASES_BIN, - ases.data(), ases.size()); - }, - addr, std::move(ases))); + [](const RawAddress& bd_addr, std::vector ases) { + auto bdstr = bd_addr.ToString(); + btif_config_set_bin(bdstr, BTIF_STORAGE_KEY_LEAUDIO_ASES_BIN, ases.data(), + ases.size()); + }, + addr, std::move(ases))); } } /** Store Le Audio device audio locations */ -void btif_storage_set_leaudio_audio_location(const RawAddress& addr, - uint32_t sink_location, +void btif_storage_set_leaudio_audio_location(const RawAddress& addr, uint32_t sink_location, uint32_t source_location) { - do_in_jni_thread( - Bind( + do_in_jni_thread(Bind( [](const RawAddress& addr, int sink_location, int source_location) { std::string bdstr = addr.ToString(); log::debug("saving le audio device: {}", addr); - btif_config_set_int(bdstr, - BTIF_STORAGE_KEY_LEAUDIO_SINK_AUDIOLOCATION, - sink_location); - btif_config_set_int(bdstr, - BTIF_STORAGE_KEY_LEAUDIO_SOURCE_AUDIOLOCATION, + btif_config_set_int(bdstr, BTIF_STORAGE_KEY_LEAUDIO_SINK_AUDIOLOCATION, sink_location); + btif_config_set_int(bdstr, BTIF_STORAGE_KEY_LEAUDIO_SOURCE_AUDIOLOCATION, source_location); }, addr, sink_location, source_location)); } /** Store Le Audio device context types */ -void btif_storage_set_leaudio_supported_context_types( - const RawAddress& addr, uint16_t sink_supported_context_type, - uint16_t source_supported_context_type) { - do_in_jni_thread( - Bind( +void btif_storage_set_leaudio_supported_context_types(const RawAddress& addr, + uint16_t sink_supported_context_type, + uint16_t source_supported_context_type) { + do_in_jni_thread(Bind( [](const RawAddress& addr, int sink_supported_context_type, int source_supported_context_type) { std::string bdstr = addr.ToString(); log::debug("saving le audio device: {}", addr); - btif_config_set_int( - bdstr, BTIF_STORAGE_KEY_LEAUDIO_SINK_SUPPORTED_CONTEXT_TYPE, - sink_supported_context_type); - btif_config_set_int( - bdstr, BTIF_STORAGE_KEY_LEAUDIO_SOURCE_SUPPORTED_CONTEXT_TYPE, - source_supported_context_type); + btif_config_set_int(bdstr, BTIF_STORAGE_KEY_LEAUDIO_SINK_SUPPORTED_CONTEXT_TYPE, + sink_supported_context_type); + btif_config_set_int(bdstr, BTIF_STORAGE_KEY_LEAUDIO_SOURCE_SUPPORTED_CONTEXT_TYPE, + source_supported_context_type); }, addr, sink_supported_context_type, source_supported_context_type)); } @@ -780,11 +730,9 @@ void btif_storage_load_bonded_leaudio() { int size = STORAGE_UUID_STRING_SIZE * BT_MAX_NUM_UUIDS; char uuid_str[size]; bool isLeAudioDevice = false; - if (btif_config_get_str(name, BTIF_STORAGE_KEY_REMOTE_SERVICE, uuid_str, - &size)) { + if (btif_config_get_str(name, BTIF_STORAGE_KEY_REMOTE_SERVICE, uuid_str, &size)) { Uuid p_uuid[BT_MAX_NUM_UUIDS]; - size_t num_uuids = - btif_split_uuids_string(uuid_str, p_uuid, BT_MAX_NUM_UUIDS); + size_t num_uuids = btif_split_uuids_string(uuid_str, p_uuid, BT_MAX_NUM_UUIDS); for (size_t i = 0; i < num_uuids; i++) { if (p_uuid[i] == Uuid::FromString("184E")) { isLeAudioDevice = true; @@ -800,69 +748,61 @@ void btif_storage_load_bonded_leaudio() { int value; bool autoconnect = false; - if (btif_config_get_int(name, BTIF_STORAGE_KEY_LEAUDIO_AUTOCONNECT, &value)) + if (btif_config_get_int(name, BTIF_STORAGE_KEY_LEAUDIO_AUTOCONNECT, &value)) { autoconnect = !!value; + } int sink_audio_location = 0; - if (btif_config_get_int(name, BTIF_STORAGE_KEY_LEAUDIO_SINK_AUDIOLOCATION, - &value)) + if (btif_config_get_int(name, BTIF_STORAGE_KEY_LEAUDIO_SINK_AUDIOLOCATION, &value)) { sink_audio_location = value; + } int source_audio_location = 0; - if (btif_config_get_int(name, BTIF_STORAGE_KEY_LEAUDIO_SOURCE_AUDIOLOCATION, - &value)) + if (btif_config_get_int(name, BTIF_STORAGE_KEY_LEAUDIO_SOURCE_AUDIOLOCATION, &value)) { source_audio_location = value; + } int sink_supported_context_type = 0; - if (btif_config_get_int( - name, BTIF_STORAGE_KEY_LEAUDIO_SINK_SUPPORTED_CONTEXT_TYPE, &value)) + if (btif_config_get_int(name, BTIF_STORAGE_KEY_LEAUDIO_SINK_SUPPORTED_CONTEXT_TYPE, &value)) { sink_supported_context_type = value; + } int source_supported_context_type = 0; - if (btif_config_get_int( - name, BTIF_STORAGE_KEY_LEAUDIO_SOURCE_SUPPORTED_CONTEXT_TYPE, - &value)) + if (btif_config_get_int(name, BTIF_STORAGE_KEY_LEAUDIO_SOURCE_SUPPORTED_CONTEXT_TYPE, &value)) { source_supported_context_type = value; + } - size_t buffer_size = - btif_config_get_bin_length(name, BTIF_STORAGE_KEY_LEAUDIO_HANDLES_BIN); + size_t buffer_size = btif_config_get_bin_length(name, BTIF_STORAGE_KEY_LEAUDIO_HANDLES_BIN); std::vector handles(buffer_size); if (buffer_size > 0) { - btif_config_get_bin(name, BTIF_STORAGE_KEY_LEAUDIO_HANDLES_BIN, - handles.data(), &buffer_size); + btif_config_get_bin(name, BTIF_STORAGE_KEY_LEAUDIO_HANDLES_BIN, handles.data(), &buffer_size); } - buffer_size = btif_config_get_bin_length( - name, BTIF_STORAGE_KEY_LEAUDIO_SINK_PACS_BIN); + buffer_size = btif_config_get_bin_length(name, BTIF_STORAGE_KEY_LEAUDIO_SINK_PACS_BIN); std::vector sink_pacs(buffer_size); if (buffer_size > 0) { - btif_config_get_bin(name, BTIF_STORAGE_KEY_LEAUDIO_SINK_PACS_BIN, - sink_pacs.data(), &buffer_size); + btif_config_get_bin(name, BTIF_STORAGE_KEY_LEAUDIO_SINK_PACS_BIN, sink_pacs.data(), + &buffer_size); } - buffer_size = btif_config_get_bin_length( - name, BTIF_STORAGE_KEY_LEAUDIO_SOURCE_PACS_BIN); + buffer_size = btif_config_get_bin_length(name, BTIF_STORAGE_KEY_LEAUDIO_SOURCE_PACS_BIN); std::vector source_pacs(buffer_size); if (buffer_size > 0) { - btif_config_get_bin(name, BTIF_STORAGE_KEY_LEAUDIO_SOURCE_PACS_BIN, - source_pacs.data(), &buffer_size); + btif_config_get_bin(name, BTIF_STORAGE_KEY_LEAUDIO_SOURCE_PACS_BIN, source_pacs.data(), + &buffer_size); } - buffer_size = - btif_config_get_bin_length(name, BTIF_STORAGE_KEY_LEAUDIO_ASES_BIN); + buffer_size = btif_config_get_bin_length(name, BTIF_STORAGE_KEY_LEAUDIO_ASES_BIN); std::vector ases(buffer_size); if (buffer_size > 0) { - btif_config_get_bin(name, BTIF_STORAGE_KEY_LEAUDIO_ASES_BIN, ases.data(), - &buffer_size); + btif_config_get_bin(name, BTIF_STORAGE_KEY_LEAUDIO_ASES_BIN, ases.data(), &buffer_size); } - do_in_main_thread( - FROM_HERE, - Bind(&LeAudioClient::AddFromStorage, bd_addr, autoconnect, - sink_audio_location, source_audio_location, - sink_supported_context_type, source_supported_context_type, - std::move(handles), std::move(sink_pacs), std::move(source_pacs), - std::move(ases))); + do_in_main_thread(FROM_HERE, + Bind(&LeAudioClient::AddFromStorage, bd_addr, autoconnect, + sink_audio_location, source_audio_location, sink_supported_context_type, + source_supported_context_type, std::move(handles), std::move(sink_pacs), + std::move(source_pacs), std::move(ases))); } } @@ -880,88 +820,78 @@ void btif_storage_remove_leaudio(const RawAddress& address) { } void btif_storage_add_leaudio_has_device(const RawAddress& address, - std::vector presets_bin, - uint8_t features, + std::vector presets_bin, uint8_t features, uint8_t active_preset) { - do_in_jni_thread( - Bind( - [](const RawAddress& address, std::vector presets_bin, - uint8_t features, uint8_t active_preset) { + do_in_jni_thread(Bind( + [](const RawAddress& address, std::vector presets_bin, uint8_t features, + uint8_t active_preset) { const std::string& name = address.ToString(); - btif_config_set_int(name, BTIF_STORAGE_KEY_LEAUDIO_HAS_FLAGS, - features); - btif_config_set_int(name, - BTIF_STORAGE_KEY_LEAUDIO_HAS_ACTIVE_PRESET, - active_preset); - btif_config_set_bin(name, - BTIF_STORAGE_KEY_LEAUDIO_HAS_SERIALIZED_PRESETS, + btif_config_set_int(name, BTIF_STORAGE_KEY_LEAUDIO_HAS_FLAGS, features); + btif_config_set_int(name, BTIF_STORAGE_KEY_LEAUDIO_HAS_ACTIVE_PRESET, active_preset); + btif_config_set_bin(name, BTIF_STORAGE_KEY_LEAUDIO_HAS_SERIALIZED_PRESETS, presets_bin.data(), presets_bin.size()); - btif_config_set_int( - name, BTIF_STORAGE_KEY_LEAUDIO_HAS_IS_ACCEPTLISTED, true); + btif_config_set_int(name, BTIF_STORAGE_KEY_LEAUDIO_HAS_IS_ACCEPTLISTED, true); }, address, std::move(presets_bin), features, active_preset)); } -void btif_storage_set_leaudio_has_active_preset(const RawAddress& address, - uint8_t active_preset) { +void btif_storage_set_leaudio_has_active_preset(const RawAddress& address, uint8_t active_preset) { do_in_jni_thread(Bind( - [](const RawAddress& address, uint8_t active_preset) { - const std::string& name = address.ToString(); + [](const RawAddress& address, uint8_t active_preset) { + const std::string& name = address.ToString(); - btif_config_set_int(name, BTIF_STORAGE_KEY_LEAUDIO_HAS_ACTIVE_PRESET, - active_preset); - }, - address, active_preset)); + btif_config_set_int(name, BTIF_STORAGE_KEY_LEAUDIO_HAS_ACTIVE_PRESET, active_preset); + }, + address, active_preset)); } -bool btif_storage_get_leaudio_has_features(const RawAddress& address, - uint8_t& features) { +bool btif_storage_get_leaudio_has_features(const RawAddress& address, uint8_t& features) { std::string name = address.ToString(); int value; - if (!btif_config_get_int(name, BTIF_STORAGE_KEY_LEAUDIO_HAS_FLAGS, &value)) + if (!btif_config_get_int(name, BTIF_STORAGE_KEY_LEAUDIO_HAS_FLAGS, &value)) { return false; + } features = value; return true; } -void btif_storage_set_leaudio_has_features(const RawAddress& address, - uint8_t features) { +void btif_storage_set_leaudio_has_features(const RawAddress& address, uint8_t features) { do_in_jni_thread(Bind( - [](const RawAddress& address, uint8_t features) { - const std::string& name = address.ToString(); + [](const RawAddress& address, uint8_t features) { + const std::string& name = address.ToString(); - btif_config_set_int(name, BTIF_STORAGE_KEY_LEAUDIO_HAS_FLAGS, features); - }, - address, features)); + btif_config_set_int(name, BTIF_STORAGE_KEY_LEAUDIO_HAS_FLAGS, features); + }, + address, features)); } void btif_storage_load_bonded_leaudio_has_devices() { for (const auto& bd_addr : btif_config_get_paired_devices()) { const std::string& name = bd_addr.ToString(); - if (!btif_config_exist(name, - BTIF_STORAGE_KEY_LEAUDIO_HAS_IS_ACCEPTLISTED) && - !btif_config_exist(name, BTIF_STORAGE_KEY_LEAUDIO_HAS_FLAGS)) + if (!btif_config_exist(name, BTIF_STORAGE_KEY_LEAUDIO_HAS_IS_ACCEPTLISTED) && + !btif_config_exist(name, BTIF_STORAGE_KEY_LEAUDIO_HAS_FLAGS)) { continue; + } #ifndef TARGET_FLOSS int value; uint16_t is_acceptlisted = 0; - if (btif_config_get_int(name, BTIF_STORAGE_KEY_LEAUDIO_HAS_IS_ACCEPTLISTED, - &value)) + if (btif_config_get_int(name, BTIF_STORAGE_KEY_LEAUDIO_HAS_IS_ACCEPTLISTED, &value)) { is_acceptlisted = value; + } uint8_t features = 0; - if (btif_config_get_int(name, BTIF_STORAGE_KEY_LEAUDIO_HAS_FLAGS, &value)) + if (btif_config_get_int(name, BTIF_STORAGE_KEY_LEAUDIO_HAS_FLAGS, &value)) { features = value; + } - do_in_main_thread(FROM_HERE, - Bind(&bluetooth::le_audio::has::HasClient::AddFromStorage, - bd_addr, features, is_acceptlisted)); + do_in_main_thread(FROM_HERE, Bind(&bluetooth::le_audio::has::HasClient::AddFromStorage, bd_addr, + features, is_acceptlisted)); #else log::fatal("TODO - Fix LE audio build."); #endif @@ -976,23 +906,19 @@ void btif_storage_remove_leaudio_has(const RawAddress& address) { btif_config_remove(addrstr, BTIF_STORAGE_KEY_LEAUDIO_HAS_SERIALIZED_PRESETS); } -void btif_storage_set_leaudio_has_acceptlist(const RawAddress& address, - bool add_to_acceptlist) { +void btif_storage_set_leaudio_has_acceptlist(const RawAddress& address, bool add_to_acceptlist) { std::string addrstr = address.ToString(); - btif_config_set_int(addrstr, BTIF_STORAGE_KEY_LEAUDIO_HAS_IS_ACCEPTLISTED, - add_to_acceptlist); + btif_config_set_int(addrstr, BTIF_STORAGE_KEY_LEAUDIO_HAS_IS_ACCEPTLISTED, add_to_acceptlist); } void btif_storage_set_leaudio_has_presets(const RawAddress& address, std::vector presets_bin) { - do_in_jni_thread( - Bind( + do_in_jni_thread(Bind( [](const RawAddress& address, std::vector presets_bin) { const std::string& name = address.ToString(); - btif_config_set_bin(name, - BTIF_STORAGE_KEY_LEAUDIO_HAS_SERIALIZED_PRESETS, + btif_config_set_bin(name, BTIF_STORAGE_KEY_LEAUDIO_HAS_SERIALIZED_PRESETS, presets_bin.data(), presets_bin.size()); }, address, std::move(presets_bin))); @@ -1004,18 +930,17 @@ bool btif_storage_get_leaudio_has_presets(const RawAddress& address, std::string name = address.ToString(); int value; - if (!btif_config_get_int(name, BTIF_STORAGE_KEY_LEAUDIO_HAS_ACTIVE_PRESET, - &value)) + if (!btif_config_get_int(name, BTIF_STORAGE_KEY_LEAUDIO_HAS_ACTIVE_PRESET, &value)) { return false; + } active_preset = value; - auto bin_sz = btif_config_get_bin_length( - name, BTIF_STORAGE_KEY_LEAUDIO_HAS_SERIALIZED_PRESETS); + auto bin_sz = btif_config_get_bin_length(name, BTIF_STORAGE_KEY_LEAUDIO_HAS_SERIALIZED_PRESETS); presets_bin.resize(bin_sz); - if (!btif_config_get_bin(name, - BTIF_STORAGE_KEY_LEAUDIO_HAS_SERIALIZED_PRESETS, - presets_bin.data(), &bin_sz)) + if (!btif_config_get_bin(name, BTIF_STORAGE_KEY_LEAUDIO_HAS_SERIALIZED_PRESETS, + presets_bin.data(), &bin_sz)) { return false; + } return true; } @@ -1025,14 +950,15 @@ void btif_storage_add_groups(const RawAddress& addr) { std::vector group_info; auto not_empty = DeviceGroups::GetForStorage(addr, group_info); - if (not_empty) + if (not_empty) { do_in_jni_thread(Bind( - [](const RawAddress& bd_addr, std::vector group_info) { - auto bdstr = bd_addr.ToString(); - btif_config_set_bin(bdstr, BTIF_STORAGE_KEY_DEVICE_GROUP_BIN, - group_info.data(), group_info.size()); - }, - addr, std::move(group_info))); + [](const RawAddress& bd_addr, std::vector group_info) { + auto bdstr = bd_addr.ToString(); + btif_config_set_bin(bdstr, BTIF_STORAGE_KEY_DEVICE_GROUP_BIN, group_info.data(), + group_info.size()); + }, + addr, std::move(group_info))); + } } /** Deletes the bonded Le Audio device grouping info from the NVRAM */ @@ -1045,17 +971,16 @@ void btif_storage_remove_groups(const RawAddress& address) { void btif_storage_load_bonded_groups(void) { for (const auto& bd_addr : btif_config_get_paired_devices()) { auto name = bd_addr.ToString(); - size_t buffer_size = - btif_config_get_bin_length(name, BTIF_STORAGE_KEY_DEVICE_GROUP_BIN); - if (buffer_size == 0) continue; + size_t buffer_size = btif_config_get_bin_length(name, BTIF_STORAGE_KEY_DEVICE_GROUP_BIN); + if (buffer_size == 0) { + continue; + } log::verbose("Grouped device:{}", bd_addr); std::vector in(buffer_size); - if (btif_config_get_bin(name, BTIF_STORAGE_KEY_DEVICE_GROUP_BIN, in.data(), - &buffer_size)) { - do_in_main_thread(FROM_HERE, Bind(&DeviceGroups::AddFromStorage, bd_addr, - std::move(in))); + if (btif_config_get_bin(name, BTIF_STORAGE_KEY_DEVICE_GROUP_BIN, in.data(), &buffer_size)) { + do_in_main_thread(FROM_HERE, Bind(&DeviceGroups::AddFromStorage, bd_addr, std::move(in))); } } } @@ -1064,10 +989,9 @@ void btif_storage_load_bonded_groups(void) { void btif_storage_load_bonded_volume_control_devices(void) { for (const auto& bd_addr : btif_config_get_paired_devices()) { auto device = bd_addr.ToString(); - if (btif_device_supports_profile( - device, Uuid::From16Bit(UUID_SERVCLASS_VOLUME_CONTROL_SERVER))) { - do_in_main_thread(FROM_HERE, - Bind(&VolumeControl::AddFromStorage, bd_addr)); + if (btif_device_supports_profile(device, + Uuid::From16Bit(UUID_SERVCLASS_VOLUME_CONTROL_SERVER))) { + do_in_main_thread(FROM_HERE, Bind(&VolumeControl::AddFromStorage, bd_addr)); } } } @@ -1077,14 +1001,15 @@ void btif_storage_update_csis_info(const RawAddress& addr) { std::vector set_info; auto not_empty = CsisClient::GetForStorage(addr, set_info); - if (not_empty) + if (not_empty) { do_in_jni_thread(Bind( - [](const RawAddress& bd_addr, std::vector set_info) { - auto bdstr = bd_addr.ToString(); - btif_config_set_bin(bdstr, BTIF_STORAGE_KEY_CSIS_SET_INFO_BIN, - set_info.data(), set_info.size()); - }, - addr, std::move(set_info))); + [](const RawAddress& bd_addr, std::vector set_info) { + auto bdstr = bd_addr.ToString(); + btif_config_set_bin(bdstr, BTIF_STORAGE_KEY_CSIS_SET_INFO_BIN, set_info.data(), + set_info.size()); + }, + addr, std::move(set_info))); + } } /** Loads information about the bonded CSIS device */ @@ -1094,16 +1019,15 @@ void btif_storage_load_bonded_csis_devices(void) { log::verbose("Loading CSIS device:{}", bd_addr); - size_t buffer_size = - btif_config_get_bin_length(name, BTIF_STORAGE_KEY_CSIS_SET_INFO_BIN); + size_t buffer_size = btif_config_get_bin_length(name, BTIF_STORAGE_KEY_CSIS_SET_INFO_BIN); std::vector in(buffer_size); - if (buffer_size != 0) - btif_config_get_bin(name, BTIF_STORAGE_KEY_CSIS_SET_INFO_BIN, in.data(), - &buffer_size); + if (buffer_size != 0) { + btif_config_get_bin(name, BTIF_STORAGE_KEY_CSIS_SET_INFO_BIN, in.data(), &buffer_size); + } - if (buffer_size != 0) - do_in_main_thread( - FROM_HERE, Bind(&CsisClient::AddFromStorage, bd_addr, std::move(in))); + if (buffer_size != 0) { + do_in_main_thread(FROM_HERE, Bind(&CsisClient::AddFromStorage, bd_addr, std::move(in))); + } } } @@ -1129,8 +1053,7 @@ bt_status_t btif_storage_load_hidd(void) { log::verbose("Remote device:{}", bd_addr); int value; if (btif_in_fetch_bonded_device(name) == BT_STATUS_SUCCESS) { - if (btif_config_get_int(name, BTIF_STORAGE_KEY_HID_DEVICE_CABLED, - &value)) { + if (btif_config_get_int(name, BTIF_STORAGE_KEY_HID_DEVICE_CABLED, &value)) { BTA_HdAddDevice(bd_addr); break; } @@ -1154,14 +1077,15 @@ bt_status_t btif_storage_set_hidd(const RawAddress& remote_bd_addr) { std::string remote_device_address_string = remote_bd_addr.ToString(); for (const auto& bd_addr : btif_config_get_paired_devices()) { auto name = bd_addr.ToString(); - if (bd_addr == remote_bd_addr) continue; + if (bd_addr == remote_bd_addr) { + continue; + } if (btif_in_fetch_bonded_device(name) == BT_STATUS_SUCCESS) { btif_config_remove(name, BTIF_STORAGE_KEY_HID_DEVICE_CABLED); } } - btif_config_set_int(remote_device_address_string, - BTIF_STORAGE_KEY_HID_DEVICE_CABLED, 1); + btif_config_set_int(remote_device_address_string, BTIF_STORAGE_KEY_HID_DEVICE_CABLED, 1); return BT_STATUS_SUCCESS; } @@ -1175,8 +1099,7 @@ bt_status_t btif_storage_set_hidd(const RawAddress& remote_bd_addr) { * ******************************************************************************/ bt_status_t btif_storage_remove_hidd(RawAddress* remote_bd_addr) { - btif_config_remove(remote_bd_addr->ToString(), - BTIF_STORAGE_KEY_HID_DEVICE_CABLED); + btif_config_remove(remote_bd_addr->ToString(), BTIF_STORAGE_KEY_HID_DEVICE_CABLED); return BT_STATUS_SUCCESS; } @@ -1190,16 +1113,14 @@ bt_status_t btif_storage_remove_hidd(RawAddress* remote_bd_addr) { * Returns BT_STATUS_SUCCESS * ******************************************************************************/ -bt_status_t btif_storage_set_hid_connection_policy( - const tAclLinkSpec& link_spec, bool reconnect_allowed) { +bt_status_t btif_storage_set_hid_connection_policy(const tAclLinkSpec& link_spec, + bool reconnect_allowed) { std::string bdstr = link_spec.addrt.bda.ToString(); if (link_spec.transport == BT_TRANSPORT_LE) { - btif_config_set_int(bdstr, BTIF_STORAGE_KEY_HOGP_RECONNECT_ALLOWED, - reconnect_allowed); + btif_config_set_int(bdstr, BTIF_STORAGE_KEY_HOGP_RECONNECT_ALLOWED, reconnect_allowed); } else if (link_spec.transport == BT_TRANSPORT_BR_EDR) { - btif_config_set_int(bdstr, BTIF_STORAGE_KEY_HID_RECONNECT_ALLOWED, - reconnect_allowed); + btif_config_set_int(bdstr, BTIF_STORAGE_KEY_HID_RECONNECT_ALLOWED, reconnect_allowed); } else { log::error("Unexpected!"); } @@ -1216,8 +1137,8 @@ bt_status_t btif_storage_set_hid_connection_policy( * Returns BT_STATUS_SUCCESS * ******************************************************************************/ -bt_status_t btif_storage_get_hid_connection_policy( - const tAclLinkSpec& link_spec, bool* reconnect_allowed) { +bt_status_t btif_storage_get_hid_connection_policy(const tAclLinkSpec& link_spec, + bool* reconnect_allowed) { std::string bdstr = link_spec.addrt.bda.ToString(); int value = 0; @@ -1245,9 +1166,8 @@ void btif_storage_set_pce_profile_version(const RawAddress& remote_bd_addr, uint16_t peer_pce_version) { log::verbose("peer_pce_version : 0x{:x}", peer_pce_version); - if (btif_config_set_bin( - remote_bd_addr.ToString(), BTIF_STORAGE_KEY_PBAP_PCE_VERSION, - (const uint8_t*)&peer_pce_version, sizeof(peer_pce_version))) { + if (btif_config_set_bin(remote_bd_addr.ToString(), BTIF_STORAGE_KEY_PBAP_PCE_VERSION, + (const uint8_t*)&peer_pce_version, sizeof(peer_pce_version))) { } else { log::warn("Failed to store peer_pce_version for {}", remote_bd_addr); } @@ -1268,11 +1188,9 @@ bool btif_storage_is_pce_version_102(const RawAddress& remote_bd_addr) { // Read and restore the PBAP PCE version from local storage uint16_t pce_version = 0; size_t version_value_size = sizeof(pce_version); - if (!btif_config_get_bin(remote_bd_addr.ToString(), - BTIF_STORAGE_KEY_PBAP_PCE_VERSION, + if (!btif_config_get_bin(remote_bd_addr.ToString(), BTIF_STORAGE_KEY_PBAP_PCE_VERSION, (uint8_t*)&pce_version, &version_value_size)) { - log::verbose("Failed to read cached peer PCE version for {}", - remote_bd_addr); + log::verbose("Failed to read cached peer PCE version for {}", remote_bd_addr); return entry_found; } @@ -1280,8 +1198,7 @@ bool btif_storage_is_pce_version_102(const RawAddress& remote_bd_addr) { entry_found = true; } - log::verbose("read cached peer PCE version 0x{:04x} for {}", pce_version, - remote_bd_addr); + log::verbose("read cached peer PCE version 0x{:04x} for {}", pce_version, remote_bd_addr); return entry_found; } diff --git a/system/btif/src/btif_rc.cc b/system/btif/src/btif_rc.cc index 8f9a2b6e375..b10b30aa766 100644 --- a/system/btif/src/btif_rc.cc +++ b/system/btif/src/btif_rc.cc @@ -129,11 +129,7 @@ typedef struct { /* 2 second timeout to get command response, then we free label */ #define BTIF_RC_TIMEOUT_MS (2 * 1000) -typedef enum { - eNOT_REGISTERED, - eREGISTERED, - eINTERIM -} btif_rc_nfn_reg_status_t; +typedef enum { eNOT_REGISTERED, eREGISTERED, eINTERIM } btif_rc_nfn_reg_status_t; typedef struct { uint8_t event_id; @@ -236,7 +232,9 @@ typedef struct { btif_rc_device_cb_t rc_multi_cb[BTIF_RC_NUM_CONN]; } rc_cb_t; -typedef struct { uint8_t handle; } btif_rc_handle_t; +typedef struct { + uint8_t handle; +} btif_rc_handle_t; static void sleep_ms(uint64_t timeout_ms); @@ -246,132 +244,102 @@ static void sleep_ms(uint64_t timeout_ms); /* Utility table to map hal status codes to bta status codes for the response * status */ static const uint8_t status_code_map[] = { - /* BTA_Status codes HAL_Status codes */ - AVRC_STS_BAD_CMD, /* BTRC_STS_BAD_CMD */ - AVRC_STS_BAD_PARAM, /* BTRC_STS_BAD_PARAM */ - AVRC_STS_NOT_FOUND, /* BTRC_STS_NOT_FOUND */ - AVRC_STS_INTERNAL_ERR, /* BTRC_STS_INTERNAL_ERR */ - AVRC_STS_NO_ERROR, /* BTRC_STS_NO_ERROR */ - AVRC_STS_UID_CHANGED, /* BTRC_STS_UID_CHANGED */ - BTIF_STS_GEN_ERROR, /* BTRC_STS_RESERVED */ - AVRC_STS_BAD_DIR, /* BTRC_STS_INV_DIRN */ - AVRC_STS_NOT_DIR, /* BTRC_STS_INV_DIRECTORY */ - AVRC_STS_NOT_EXIST, /* BTRC_STS_INV_ITEM */ - AVRC_STS_BAD_SCOPE, /* BTRC_STS_INV_SCOPE */ - AVRC_STS_BAD_RANGE, /* BTRC_STS_INV_RANGE */ - AVRC_STS_UID_IS_DIR, /* BTRC_STS_DIRECTORY */ - AVRC_STS_IN_USE, /* BTRC_STS_MEDIA_IN_USE */ - AVRC_STS_NOW_LIST_FULL, /* BTRC_STS_PLAY_LIST_FULL */ - AVRC_STS_SEARCH_NOT_SUP, /* BTRC_STS_SRCH_NOT_SPRTD */ - AVRC_STS_SEARCH_BUSY, /* BTRC_STS_SRCH_IN_PROG */ - AVRC_STS_BAD_PLAYER_ID, /* BTRC_STS_INV_PLAYER */ - AVRC_STS_PLAYER_N_BR, /* BTRC_STS_PLAY_NOT_BROW */ - AVRC_STS_PLAYER_N_ADDR, /* BTRC_STS_PLAY_NOT_ADDR */ - AVRC_STS_BAD_SEARCH_RES, /* BTRC_STS_INV_RESULTS */ - AVRC_STS_NO_AVAL_PLAYER, /* BTRC_STS_NO_AVBL_PLAY */ - AVRC_STS_ADDR_PLAYER_CHG, /* BTRC_STS_ADDR_PLAY_CHGD */ + /* BTA_Status codes HAL_Status codes */ + AVRC_STS_BAD_CMD, /* BTRC_STS_BAD_CMD */ + AVRC_STS_BAD_PARAM, /* BTRC_STS_BAD_PARAM */ + AVRC_STS_NOT_FOUND, /* BTRC_STS_NOT_FOUND */ + AVRC_STS_INTERNAL_ERR, /* BTRC_STS_INTERNAL_ERR */ + AVRC_STS_NO_ERROR, /* BTRC_STS_NO_ERROR */ + AVRC_STS_UID_CHANGED, /* BTRC_STS_UID_CHANGED */ + BTIF_STS_GEN_ERROR, /* BTRC_STS_RESERVED */ + AVRC_STS_BAD_DIR, /* BTRC_STS_INV_DIRN */ + AVRC_STS_NOT_DIR, /* BTRC_STS_INV_DIRECTORY */ + AVRC_STS_NOT_EXIST, /* BTRC_STS_INV_ITEM */ + AVRC_STS_BAD_SCOPE, /* BTRC_STS_INV_SCOPE */ + AVRC_STS_BAD_RANGE, /* BTRC_STS_INV_RANGE */ + AVRC_STS_UID_IS_DIR, /* BTRC_STS_DIRECTORY */ + AVRC_STS_IN_USE, /* BTRC_STS_MEDIA_IN_USE */ + AVRC_STS_NOW_LIST_FULL, /* BTRC_STS_PLAY_LIST_FULL */ + AVRC_STS_SEARCH_NOT_SUP, /* BTRC_STS_SRCH_NOT_SPRTD */ + AVRC_STS_SEARCH_BUSY, /* BTRC_STS_SRCH_IN_PROG */ + AVRC_STS_BAD_PLAYER_ID, /* BTRC_STS_INV_PLAYER */ + AVRC_STS_PLAYER_N_BR, /* BTRC_STS_PLAY_NOT_BROW */ + AVRC_STS_PLAYER_N_ADDR, /* BTRC_STS_PLAY_NOT_ADDR */ + AVRC_STS_BAD_SEARCH_RES, /* BTRC_STS_INV_RESULTS */ + AVRC_STS_NO_AVAL_PLAYER, /* BTRC_STS_NO_AVBL_PLAY */ + AVRC_STS_ADDR_PLAYER_CHG, /* BTRC_STS_ADDR_PLAY_CHGD */ }; void initialize_device(btif_rc_device_cb_t* p_dev); -static void send_reject_response(uint8_t rc_handle, uint8_t label, uint8_t pdu, - uint8_t status, uint8_t opcode); +static void send_reject_response(uint8_t rc_handle, uint8_t label, uint8_t pdu, uint8_t status, + uint8_t opcode); static uint8_t opcode_from_pdu(uint8_t pdu); -static void send_metamsg_rsp(btif_rc_device_cb_t* p_dev, int index, - uint8_t label, tBTA_AV_CODE code, - tAVRC_RESPONSE* pmetamsg_resp); +static void send_metamsg_rsp(btif_rc_device_cb_t* p_dev, int index, uint8_t label, + tBTA_AV_CODE code, tAVRC_RESPONSE* pmetamsg_resp); static void register_volumechange(btif_rc_device_cb_t* p_dev); static void init_all_transactions(btif_rc_device_cb_t* p_dev); -static bt_status_t get_transaction(btif_rc_device_cb_t* p_dev, - rc_transaction_context_t& context, +static bt_status_t get_transaction(btif_rc_device_cb_t* p_dev, rc_transaction_context_t& context, rc_transaction_t** ptransaction); -static void start_transaction_timer(btif_rc_device_cb_t* p_dev, uint8_t label, - uint64_t timeout_ms); +static void start_transaction_timer(btif_rc_device_cb_t* p_dev, uint8_t label, uint64_t timeout_ms); static void btif_rc_transaction_timer_timeout(void* data); static void release_transaction(btif_rc_device_cb_t* p_dev, uint8_t label); static std::string dump_transaction(const rc_transaction_t* const transaction); -static rc_transaction_t* get_transaction_by_lbl(btif_rc_device_cb_t* p_dev, - uint8_t label); -static void handle_rc_metamsg_rsp(tBTA_AV_META_MSG* pmeta_msg, - btif_rc_device_cb_t* p_dev); +static rc_transaction_t* get_transaction_by_lbl(btif_rc_device_cb_t* p_dev, uint8_t label); +static void handle_rc_metamsg_rsp(tBTA_AV_META_MSG* pmeta_msg, btif_rc_device_cb_t* p_dev); static void handle_avk_rc_metamsg_cmd(tBTA_AV_META_MSG* pmeta_msg); static void handle_avk_rc_metamsg_rsp(tBTA_AV_META_MSG* pmeta_msg); -static void btif_rc_ctrl_upstreams_rsp_cmd(uint8_t event, - tAVRC_COMMAND* pavrc_cmd, - uint8_t label, +static void btif_rc_ctrl_upstreams_rsp_cmd(uint8_t event, tAVRC_COMMAND* pavrc_cmd, uint8_t label, btif_rc_device_cb_t* p_dev); static void rc_ctrl_procedure_complete(btif_rc_device_cb_t* p_dev); static void register_for_event_notification(btif_rc_supported_event_t* p_event, btif_rc_device_cb_t* p_dev); -static void handle_get_capability_response(tBTA_AV_META_MSG* pmeta_msg, - tAVRC_GET_CAPS_RSP* p_rsp); -static void handle_app_attr_response(tBTA_AV_META_MSG* pmeta_msg, - tAVRC_LIST_APP_ATTR_RSP* p_rsp); -static void handle_app_val_response(tBTA_AV_META_MSG* pmeta_msg, - tAVRC_LIST_APP_VALUES_RSP* p_rsp); +static void handle_get_capability_response(tBTA_AV_META_MSG* pmeta_msg, tAVRC_GET_CAPS_RSP* p_rsp); +static void handle_app_attr_response(tBTA_AV_META_MSG* pmeta_msg, tAVRC_LIST_APP_ATTR_RSP* p_rsp); +static void handle_app_val_response(tBTA_AV_META_MSG* pmeta_msg, tAVRC_LIST_APP_VALUES_RSP* p_rsp); static void handle_app_cur_val_response(tBTA_AV_META_MSG* pmeta_msg, tAVRC_GET_CUR_APP_VALUE_RSP* p_rsp); static void handle_app_attr_txt_response(tBTA_AV_META_MSG* pmeta_msg, tAVRC_GET_APP_ATTR_TXT_RSP* p_rsp); static void handle_app_attr_val_txt_response(tBTA_AV_META_MSG* pmeta_msg, tAVRC_GET_APP_ATTR_TXT_RSP* p_rsp); -static void cleanup_app_attr_val_txt_response( - btif_rc_player_app_settings_t* p_app_settings); +static void cleanup_app_attr_val_txt_response(btif_rc_player_app_settings_t* p_app_settings); static void handle_get_playstatus_response(tBTA_AV_META_MSG* pmeta_msg, tAVRC_GET_PLAY_STATUS_RSP* p_rsp); -static void handle_set_addressed_player_response(tBTA_AV_META_MSG* pmeta_msg, - tAVRC_RSP* p_rsp); -static void cleanup_btrc_folder_items(btrc_folder_items_t* btrc_items, - uint8_t item_count); +static void handle_set_addressed_player_response(tBTA_AV_META_MSG* pmeta_msg, tAVRC_RSP* p_rsp); +static void cleanup_btrc_folder_items(btrc_folder_items_t* btrc_items, uint8_t item_count); static void handle_get_metadata_attr_response(tBTA_AV_META_MSG* pmeta_msg, - tAVRC_GET_ATTRS_RSP* p_rsp); -static void handle_set_app_attr_val_response(tBTA_AV_META_MSG* pmeta_msg, - tAVRC_RSP* p_rsp); + tAVRC_GET_ATTRS_RSP* p_rsp); +static void handle_set_app_attr_val_response(tBTA_AV_META_MSG* pmeta_msg, tAVRC_RSP* p_rsp); static bt_status_t get_play_status_cmd(btif_rc_device_cb_t* p_dev); -static bt_status_t get_player_app_setting_attr_text_cmd( - uint8_t* attrs, uint8_t num_attrs, btif_rc_device_cb_t* p_dev); -static bt_status_t get_player_app_setting_value_text_cmd( - uint8_t* vals, uint8_t num_vals, btif_rc_device_cb_t* p_dev); -static bt_status_t register_notification_cmd(uint8_t event_id, - uint32_t event_value, +static bt_status_t get_player_app_setting_attr_text_cmd(uint8_t* attrs, uint8_t num_attrs, + btif_rc_device_cb_t* p_dev); +static bt_status_t get_player_app_setting_value_text_cmd(uint8_t* vals, uint8_t num_vals, + btif_rc_device_cb_t* p_dev); +static bt_status_t register_notification_cmd(uint8_t event_id, uint32_t event_value, btif_rc_device_cb_t* p_dev); -static bt_status_t get_metadata_attribute_cmd(uint8_t num_attribute, - const uint32_t* p_attr_ids, +static bt_status_t get_metadata_attribute_cmd(uint8_t num_attribute, const uint32_t* p_attr_ids, btif_rc_device_cb_t* p_dev); -static bt_status_t get_element_attribute_cmd(uint8_t num_attribute, - const uint32_t* p_attr_ids, +static bt_status_t get_element_attribute_cmd(uint8_t num_attribute, const uint32_t* p_attr_ids, btif_rc_device_cb_t* p_dev); -static bt_status_t get_item_attribute_cmd(uint64_t uid, int scope, - uint8_t num_attribute, - const uint32_t* p_attr_ids, - btif_rc_device_cb_t* p_dev); -static bt_status_t getcapabilities_cmd(uint8_t cap_id, - btif_rc_device_cb_t* p_dev); -static bt_status_t list_player_app_setting_attrib_cmd( - btif_rc_device_cb_t* p_dev); -static bt_status_t list_player_app_setting_value_cmd( - uint8_t attrib_id, btif_rc_device_cb_t* p_dev); -static bt_status_t get_player_app_setting_cmd(uint8_t num_attrib, - uint8_t* attrib_ids, +static bt_status_t get_item_attribute_cmd(uint64_t uid, int scope, uint8_t num_attribute, + const uint32_t* p_attr_ids, btif_rc_device_cb_t* p_dev); +static bt_status_t getcapabilities_cmd(uint8_t cap_id, btif_rc_device_cb_t* p_dev); +static bt_status_t list_player_app_setting_attrib_cmd(btif_rc_device_cb_t* p_dev); +static bt_status_t list_player_app_setting_value_cmd(uint8_t attrib_id, btif_rc_device_cb_t* p_dev); +static bt_status_t get_player_app_setting_cmd(uint8_t num_attrib, uint8_t* attrib_ids, btif_rc_device_cb_t* p_dev); -void get_folder_item_type_media(const tAVRC_ITEM* avrc_item, - btrc_folder_items_t* btrc_item); -void get_folder_item_type_folder(const tAVRC_ITEM* avrc_item, - btrc_folder_items_t* btrc_item); -void get_folder_item_type_player(const tAVRC_ITEM* avrc_item, - btrc_folder_items_t* btrc_item); -static bt_status_t get_folder_items_cmd(const RawAddress& bd_addr, - uint8_t scope, uint32_t start_item, - uint32_t end_item); - -static void btif_rc_upstreams_evt(uint16_t event, tAVRC_COMMAND* p_param, - uint8_t ctype, uint8_t label, - btif_rc_device_cb_t* p_dev); - -static void btif_rc_upstreams_rsp_evt(uint16_t event, - tAVRC_RESPONSE* pavrc_resp, uint8_t ctype, - uint8_t label, - btif_rc_device_cb_t* p_dev); +void get_folder_item_type_media(const tAVRC_ITEM* avrc_item, btrc_folder_items_t* btrc_item); +void get_folder_item_type_folder(const tAVRC_ITEM* avrc_item, btrc_folder_items_t* btrc_item); +void get_folder_item_type_player(const tAVRC_ITEM* avrc_item, btrc_folder_items_t* btrc_item); +static bt_status_t get_folder_items_cmd(const RawAddress& bd_addr, uint8_t scope, + uint32_t start_item, uint32_t end_item); + +static void btif_rc_upstreams_evt(uint16_t event, tAVRC_COMMAND* p_param, uint8_t ctype, + uint8_t label, btif_rc_device_cb_t* p_dev); + +static void btif_rc_upstreams_rsp_evt(uint16_t event, tAVRC_RESPONSE* pavrc_resp, uint8_t ctype, + uint8_t label, btif_rc_device_cb_t* p_dev); static bool absolute_volume_disabled(void); @@ -384,23 +352,20 @@ static btrc_ctrl_callbacks_t* bt_rc_ctrl_callbacks = NULL; // List of desired media attribute keys to request by default static const uint32_t media_attr_list[] = { - AVRC_MEDIA_ATTR_ID_TITLE, AVRC_MEDIA_ATTR_ID_ARTIST, - AVRC_MEDIA_ATTR_ID_ALBUM, AVRC_MEDIA_ATTR_ID_TRACK_NUM, - AVRC_MEDIA_ATTR_ID_NUM_TRACKS, AVRC_MEDIA_ATTR_ID_GENRE, - AVRC_MEDIA_ATTR_ID_PLAYING_TIME, - AVRC_MEDIA_ATTR_ID_COVER_ARTWORK_HANDLE}; -static const uint8_t media_attr_list_size = - sizeof(media_attr_list)/sizeof(uint32_t); + AVRC_MEDIA_ATTR_ID_TITLE, AVRC_MEDIA_ATTR_ID_ARTIST, + AVRC_MEDIA_ATTR_ID_ALBUM, AVRC_MEDIA_ATTR_ID_TRACK_NUM, + AVRC_MEDIA_ATTR_ID_NUM_TRACKS, AVRC_MEDIA_ATTR_ID_GENRE, + AVRC_MEDIA_ATTR_ID_PLAYING_TIME, AVRC_MEDIA_ATTR_ID_COVER_ARTWORK_HANDLE}; +static const uint8_t media_attr_list_size = sizeof(media_attr_list) / sizeof(uint32_t); // List of desired media attribute keys to request if cover artwork is not a // supported feature static const uint32_t media_attr_list_no_cover_art[] = { - AVRC_MEDIA_ATTR_ID_TITLE, AVRC_MEDIA_ATTR_ID_ARTIST, - AVRC_MEDIA_ATTR_ID_ALBUM, AVRC_MEDIA_ATTR_ID_TRACK_NUM, - AVRC_MEDIA_ATTR_ID_NUM_TRACKS, AVRC_MEDIA_ATTR_ID_GENRE, - AVRC_MEDIA_ATTR_ID_PLAYING_TIME}; + AVRC_MEDIA_ATTR_ID_TITLE, AVRC_MEDIA_ATTR_ID_ARTIST, AVRC_MEDIA_ATTR_ID_ALBUM, + AVRC_MEDIA_ATTR_ID_TRACK_NUM, AVRC_MEDIA_ATTR_ID_NUM_TRACKS, AVRC_MEDIA_ATTR_ID_GENRE, + AVRC_MEDIA_ATTR_ID_PLAYING_TIME}; static const uint8_t media_attr_list_no_cover_art_size = - sizeof(media_attr_list_no_cover_art)/sizeof(uint32_t); + sizeof(media_attr_list_no_cover_art) / sizeof(uint32_t); /***************************************************************************** * Static functions @@ -414,8 +379,7 @@ bool check_cod(const RawAddress& remote_bdaddr, uint32_t cod); void btif_rc_get_addr_by_handle(uint8_t handle, RawAddress& rc_addr) { log::verbose("handle: 0x{:x}", handle); for (int idx = 0; idx < BTIF_RC_NUM_CONN; idx++) { - if ((btif_rc_cb.rc_multi_cb[idx].rc_state != - BTRC_CONNECTION_STATE_DISCONNECTED) && + if ((btif_rc_cb.rc_multi_cb[idx].rc_state != BTRC_CONNECTION_STATE_DISCONNECTED) && (btif_rc_cb.rc_multi_cb[idx].rc_handle == handle)) { log::verbose("btif_rc_cb.rc_multi_cb[idx].rc_handle: 0x{:x}", btif_rc_cb.rc_multi_cb[idx].rc_handle); @@ -433,16 +397,17 @@ void btif_rc_get_addr_by_handle(uint8_t handle, RawAddress& rc_addr) { *****************************************************************************/ static btif_rc_device_cb_t* alloc_device() { for (int idx = 0; idx < BTIF_RC_NUM_CONN; idx++) { - if (btif_rc_cb.rc_multi_cb[idx].rc_state == - BTRC_CONNECTION_STATE_DISCONNECTED) { - return (&btif_rc_cb.rc_multi_cb[idx]); + if (btif_rc_cb.rc_multi_cb[idx].rc_state == BTRC_CONNECTION_STATE_DISCONNECTED) { + return &btif_rc_cb.rc_multi_cb[idx]; } } return NULL; } void initialize_device(btif_rc_device_cb_t* p_dev) { - if (p_dev == nullptr) return; + if (p_dev == nullptr) { + return; + } p_dev->rc_connected = false; p_dev->br_connected = false; @@ -483,22 +448,20 @@ static btif_rc_device_cb_t* get_connected_device(int index) { log::error("can't support more than {} connections", BTIF_RC_NUM_CONN); return NULL; } - if (btif_rc_cb.rc_multi_cb[index].rc_state != - BTRC_CONNECTION_STATE_CONNECTED) { + if (btif_rc_cb.rc_multi_cb[index].rc_state != BTRC_CONNECTION_STATE_CONNECTED) { log::error("returning NULL"); return NULL; } - return (&btif_rc_cb.rc_multi_cb[index]); + return &btif_rc_cb.rc_multi_cb[index]; } btif_rc_device_cb_t* btif_rc_get_device_by_bda(const RawAddress& bd_addr) { log::verbose("bd_addr: {}", bd_addr); for (int idx = 0; idx < BTIF_RC_NUM_CONN; idx++) { - if ((btif_rc_cb.rc_multi_cb[idx].rc_state != - BTRC_CONNECTION_STATE_DISCONNECTED) && + if ((btif_rc_cb.rc_multi_cb[idx].rc_state != BTRC_CONNECTION_STATE_DISCONNECTED) && btif_rc_cb.rc_multi_cb[idx].rc_addr == bd_addr) { - return (&btif_rc_cb.rc_multi_cb[idx]); + return &btif_rc_cb.rc_multi_cb[idx]; } } log::error("device not found, returning NULL!"); @@ -508,12 +471,11 @@ btif_rc_device_cb_t* btif_rc_get_device_by_bda(const RawAddress& bd_addr) { btif_rc_device_cb_t* btif_rc_get_device_by_handle(uint8_t handle) { log::verbose("handle: 0x{:x}", handle); for (int idx = 0; idx < BTIF_RC_NUM_CONN; idx++) { - if ((btif_rc_cb.rc_multi_cb[idx].rc_state != - BTRC_CONNECTION_STATE_DISCONNECTED) && + if ((btif_rc_cb.rc_multi_cb[idx].rc_state != BTRC_CONNECTION_STATE_DISCONNECTED) && (btif_rc_cb.rc_multi_cb[idx].rc_handle == handle)) { log::verbose("btif_rc_cb.rc_multi_cb[idx].rc_handle: 0x{:x}", btif_rc_cb.rc_multi_cb[idx].rc_handle); - return (&btif_rc_cb.rc_multi_cb[idx]); + return &btif_rc_cb.rc_multi_cb[idx]; } } log::error("returning NULL"); @@ -521,15 +483,13 @@ btif_rc_device_cb_t* btif_rc_get_device_by_handle(uint8_t handle) { } const uint32_t* get_requested_attributes_list(btif_rc_device_cb_t* p_dev) { - return (p_dev->rc_features & BTA_AV_FEAT_COVER_ARTWORK - ? media_attr_list - : media_attr_list_no_cover_art); + return p_dev->rc_features & BTA_AV_FEAT_COVER_ARTWORK ? media_attr_list + : media_attr_list_no_cover_art; } uint8_t get_requested_attributes_list_size(btif_rc_device_cb_t* p_dev) { - return (p_dev->rc_features & BTA_AV_FEAT_COVER_ARTWORK - ? media_attr_list_size - : media_attr_list_no_cover_art_size); + return p_dev->rc_features & BTA_AV_FEAT_COVER_ARTWORK ? media_attr_list_size + : media_attr_list_no_cover_art_size; } void fill_pdu_queue(int index, uint8_t ctype, uint8_t label, bool pending, @@ -544,12 +504,10 @@ void fill_avrc_attr_entry(tAVRC_ATTR_ENTRY* attr_vals, int num_attrs, for (int attr_cnt = 0; attr_cnt < num_attrs; attr_cnt++) { attr_vals[attr_cnt].attr_id = p_attrs[attr_cnt].attr_id; attr_vals[attr_cnt].name.charset_id = AVRC_CHARSET_ID_UTF8; - attr_vals[attr_cnt].name.str_len = - (uint16_t)strlen((char*)p_attrs[attr_cnt].text); + attr_vals[attr_cnt].name.str_len = (uint16_t)strlen((char*)p_attrs[attr_cnt].text); attr_vals[attr_cnt].name.p_str = p_attrs[attr_cnt].text; log::verbose("attr_id: 0x{:x}, charset_id: 0x{:x}, str_len: {}, str: {}", - (unsigned int)attr_vals[attr_cnt].attr_id, - attr_vals[attr_cnt].name.charset_id, + (unsigned int)attr_vals[attr_cnt].attr_id, attr_vals[attr_cnt].name.charset_id, attr_vals[attr_cnt].name.str_len, reinterpret_cast(attr_vals[attr_cnt].name.p_str)); } @@ -567,11 +525,11 @@ void handle_rc_ctrl_features_all(btif_rc_device_cb_t* p_dev) { int rc_features = 0; log::verbose( - "peer_tg_features: 0x{:x}, rc_features_processed={}, connected={}, " - "peer_is_src:{}", - p_dev->peer_tg_features, p_dev->rc_features_processed, - btif_av_is_connected_addr(p_dev->rc_addr, A2dpType::kSink), - btif_av_peer_is_source(p_dev->rc_addr)); + "peer_tg_features: 0x{:x}, rc_features_processed={}, connected={}, " + "peer_is_src:{}", + p_dev->peer_tg_features, p_dev->rc_features_processed, + btif_av_is_connected_addr(p_dev->rc_addr, A2dpType::kSink), + btif_av_peer_is_source(p_dev->rc_addr)); if ((p_dev->peer_tg_features & BTA_AV_FEAT_ADV_CTRL) && (p_dev->peer_tg_features & BTA_AV_FEAT_RCCT)) { @@ -579,8 +537,7 @@ void handle_rc_ctrl_features_all(btif_rc_device_cb_t* p_dev) { } if ((p_dev->peer_tg_features & BTA_AV_FEAT_METADATA) && - (p_dev->peer_tg_features & BTA_AV_FEAT_VENDOR) && - (p_dev->rc_features_processed != true)) { + (p_dev->peer_tg_features & BTA_AV_FEAT_VENDOR) && (p_dev->rc_features_processed != true)) { rc_features |= BTRC_FEAT_METADATA; /* Mark rc features processed to avoid repeating @@ -600,8 +557,7 @@ void handle_rc_ctrl_features_all(btif_rc_device_cb_t* p_dev) { } } else { log::verbose("{} is not connected, pending", p_dev->rc_addr); - p_dev->launch_cmd_pending |= - (RC_PENDING_ACT_GET_CAP | RC_PENDING_ACT_REG_VOL); + p_dev->launch_cmd_pending |= (RC_PENDING_ACT_GET_CAP | RC_PENDING_ACT_REG_VOL); } /* Add browsing feature capability */ @@ -616,8 +572,8 @@ void handle_rc_ctrl_features_all(btif_rc_device_cb_t* p_dev) { if (bt_rc_ctrl_callbacks != NULL) { log::verbose("Update rc features to CTRL: {}", rc_features); - do_in_jni_thread(base::BindOnce(bt_rc_ctrl_callbacks->getrcfeatures_cb, - p_dev->rc_addr, rc_features)); + do_in_jni_thread( + base::BindOnce(bt_rc_ctrl_callbacks->getrcfeatures_cb, p_dev->rc_addr, rc_features)); } } @@ -628,15 +584,13 @@ void handle_rc_ctrl_features(btif_rc_device_cb_t* p_dev) { } if (!(p_dev->rc_features & BTA_AV_FEAT_RCTG) && - (!(p_dev->rc_features & BTA_AV_FEAT_RCCT) || - !(p_dev->rc_features & BTA_AV_FEAT_ADV_CTRL))) { + (!(p_dev->rc_features & BTA_AV_FEAT_RCCT) || !(p_dev->rc_features & BTA_AV_FEAT_ADV_CTRL))) { return; } int rc_features = 0; - if ((p_dev->rc_features & BTA_AV_FEAT_ADV_CTRL) && - (p_dev->rc_features & BTA_AV_FEAT_RCCT)) { + if ((p_dev->rc_features & BTA_AV_FEAT_ADV_CTRL) && (p_dev->rc_features & BTA_AV_FEAT_RCCT)) { rc_features |= BTRC_FEAT_ABSOLUTE_VOLUME; } @@ -644,8 +598,7 @@ void handle_rc_ctrl_features(btif_rc_device_cb_t* p_dev) { rc_features |= BTRC_FEAT_METADATA; } - if ((p_dev->rc_features & BTA_AV_FEAT_VENDOR) && - (p_dev->rc_features_processed != true)) { + if ((p_dev->rc_features & BTA_AV_FEAT_VENDOR) && (p_dev->rc_features_processed != true)) { /* Mark rc features processed to avoid repeating * the AVRCP procedure every time on receiving this * update. @@ -667,8 +620,8 @@ void handle_rc_ctrl_features(btif_rc_device_cb_t* p_dev) { } log::verbose("Update rc features to CTRL: {}", rc_features); - do_in_jni_thread(base::BindOnce(bt_rc_ctrl_callbacks->getrcfeatures_cb, - p_dev->rc_addr, rc_features)); + do_in_jni_thread( + base::BindOnce(bt_rc_ctrl_callbacks->getrcfeatures_cb, p_dev->rc_addr, rc_features)); } void btif_rc_check_pending_cmd(const RawAddress& peer_address) { btif_rc_device_cb_t* p_dev = NULL; @@ -679,10 +632,10 @@ void btif_rc_check_pending_cmd(const RawAddress& peer_address) { } log::verbose( - "launch_cmd_pending={}, rc_connected={}, peer_ct_features=0x{:x}, " - "peer_tg_features=0x{:x}", - p_dev->launch_cmd_pending, p_dev->rc_connected, p_dev->peer_ct_features, - p_dev->peer_tg_features); + "launch_cmd_pending={}, rc_connected={}, peer_ct_features=0x{:x}, " + "peer_tg_features=0x{:x}", + p_dev->launch_cmd_pending, p_dev->rc_connected, p_dev->peer_ct_features, + p_dev->peer_tg_features); if (p_dev->launch_cmd_pending && p_dev->rc_connected) { if ((p_dev->launch_cmd_pending & RC_PENDING_ACT_REG_VOL) && btif_av_peer_is_sink(p_dev->rc_addr)) { @@ -698,9 +651,8 @@ void btif_rc_check_pending_cmd(const RawAddress& peer_address) { if ((p_dev->launch_cmd_pending & RC_PENDING_ACT_REPORT_CONN) && btif_av_peer_is_source(p_dev->rc_addr)) { if (bt_rc_ctrl_callbacks != NULL) { - do_in_jni_thread( - base::BindOnce(bt_rc_ctrl_callbacks->connection_state_cb, true, - false, p_dev->rc_addr)); + do_in_jni_thread(base::BindOnce(bt_rc_ctrl_callbacks->connection_state_cb, true, false, + p_dev->rc_addr)); } } } @@ -711,24 +663,22 @@ void handle_rc_ctrl_psm(btif_rc_device_cb_t* p_dev) { uint16_t cover_art_psm = p_dev->rc_cover_art_psm; log::verbose("Update rc cover art psm to CTRL: {}", cover_art_psm); if (bt_rc_ctrl_callbacks != NULL) { - do_in_jni_thread(base::BindOnce(bt_rc_ctrl_callbacks->get_cover_art_psm_cb, - p_dev->rc_addr, cover_art_psm)); + do_in_jni_thread(base::BindOnce(bt_rc_ctrl_callbacks->get_cover_art_psm_cb, p_dev->rc_addr, + cover_art_psm)); } } void handle_rc_features(btif_rc_device_cb_t* p_dev) { - log::assert_that(bt_rc_callbacks != nullptr, - "assert failed: bt_rc_callbacks != nullptr"); + log::assert_that(bt_rc_callbacks != nullptr, "assert failed: bt_rc_callbacks != nullptr"); btrc_remote_features_t rc_features = BTRC_FEAT_NONE; RawAddress avdtp_source_active_peer_addr = btif_av_source_active_peer(); RawAddress avdtp_sink_active_peer_addr = btif_av_sink_active_peer(); log::verbose( - "AVDTP Source Active Peer Address: {} AVDTP Sink Active Peer Address: {} " - "AVCTP address: {}", - avdtp_source_active_peer_addr, avdtp_sink_active_peer_addr, - p_dev->rc_addr); + "AVDTP Source Active Peer Address: {} AVDTP Sink Active Peer Address: {} " + "AVCTP address: {}", + avdtp_source_active_peer_addr, avdtp_sink_active_peer_addr, p_dev->rc_addr); if (interop_match_addr(INTEROP_DISABLE_ABSOLUTE_VOLUME, &p_dev->rc_addr) || absolute_volume_disabled() || @@ -749,20 +699,16 @@ void handle_rc_features(btif_rc_device_cb_t* p_dev) { return; } - if ((p_dev->rc_features & BTA_AV_FEAT_ADV_CTRL) && - (p_dev->rc_features & BTA_AV_FEAT_RCTG)) { - rc_features = - (btrc_remote_features_t)(rc_features | BTRC_FEAT_ABSOLUTE_VOLUME); + if ((p_dev->rc_features & BTA_AV_FEAT_ADV_CTRL) && (p_dev->rc_features & BTA_AV_FEAT_RCTG)) { + rc_features = (btrc_remote_features_t)(rc_features | BTRC_FEAT_ABSOLUTE_VOLUME); } log::verbose("rc_features: 0x{:x}", rc_features); HAL_CBACK(bt_rc_callbacks, remote_features_cb, p_dev->rc_addr, rc_features); - log::verbose("Checking for feature flags in btif_rc_handler with label: {}", - p_dev->rc_vol_label); + log::verbose("Checking for feature flags in btif_rc_handler with label: {}", p_dev->rc_vol_label); // Register for volume change on connect - if (p_dev->rc_features & BTA_AV_FEAT_ADV_CTRL && - p_dev->rc_features & BTA_AV_FEAT_RCTG) { + if (p_dev->rc_features & BTA_AV_FEAT_ADV_CTRL && p_dev->rc_features & BTA_AV_FEAT_RCTG) { register_volumechange(p_dev); } } @@ -776,10 +722,8 @@ void handle_rc_features(btif_rc_device_cb_t* p_dev) { * ***************************************************************************/ void handle_rc_browse_connect(tBTA_AV_RC_BROWSE_OPEN* p_rc_br_open) { - log::verbose("rc_handle {} status {}", p_rc_br_open->rc_handle, - p_rc_br_open->status); - btif_rc_device_cb_t* p_dev = - btif_rc_get_device_by_handle(p_rc_br_open->rc_handle); + log::verbose("rc_handle {} status {}", p_rc_br_open->rc_handle, p_rc_br_open->status); + btif_rc_device_cb_t* p_dev = btif_rc_get_device_by_handle(p_rc_br_open->rc_handle); if (!p_dev) { log::error("p_dev is null"); @@ -794,22 +738,20 @@ void handle_rc_browse_connect(tBTA_AV_RC_BROWSE_OPEN* p_rc_br_open) { if (btif_av_src_sink_coexist_enabled()) { if (btif_av_peer_is_connected_source(p_dev->rc_addr)) { if (bt_rc_ctrl_callbacks != NULL) { - do_in_jni_thread( - base::BindOnce(bt_rc_ctrl_callbacks->connection_state_cb, true, - true, p_dev->rc_addr)); + do_in_jni_thread(base::BindOnce(bt_rc_ctrl_callbacks->connection_state_cb, true, true, + p_dev->rc_addr)); } } else { p_dev->launch_cmd_pending |= RC_PENDING_ACT_REPORT_CONN; log::verbose("pending rc browse connection event"); } } else { - if (bt_rc_ctrl_callbacks != NULL) { - do_in_jni_thread( - base::BindOnce(bt_rc_ctrl_callbacks->connection_state_cb, true, - true, p_dev->rc_addr)); - } else { - log::warn("bt_rc_ctrl_callbacks is null."); - } + if (bt_rc_ctrl_callbacks != NULL) { + do_in_jni_thread(base::BindOnce(bt_rc_ctrl_callbacks->connection_state_cb, true, true, + p_dev->rc_addr)); + } else { + log::warn("bt_rc_ctrl_callbacks is null."); + } } } } @@ -849,11 +791,9 @@ void handle_rc_connect(tBTA_AV_RC_OPEN* p_rc_open) { // check if already some RC is connected if (p_dev->rc_connected) { - log::error( - "Got RC OPEN in connected state, Connected RC: {} and Current RC: {}", - p_dev->rc_handle, p_rc_open->rc_handle); - if (p_dev->rc_handle != p_rc_open->rc_handle && - p_dev->rc_addr != p_rc_open->peer_addr) { + log::error("Got RC OPEN in connected state, Connected RC: {} and Current RC: {}", + p_dev->rc_handle, p_rc_open->rc_handle); + if (p_dev->rc_handle != p_rc_open->rc_handle && p_dev->rc_addr != p_rc_open->peer_addr) { log::verbose("Got RC connected for some other handle"); BTA_AvCloseRc(p_rc_open->rc_handle); return; @@ -868,10 +808,10 @@ void handle_rc_connect(tBTA_AV_RC_OPEN* p_rc_open) { p_dev->rc_volume = MAX_VOLUME; log::verbose( - "handle_rc_connect in features={:#x}, out features={:#x}, " - "ct_feature={:#x}, tg_feature={:#x}, cover art psm={:#x}", - p_rc_open->peer_features, p_dev->rc_features, p_dev->peer_ct_features, - p_dev->peer_tg_features, p_dev->rc_cover_art_psm); + "handle_rc_connect in features={:#x}, out features={:#x}, " + "ct_feature={:#x}, tg_feature={:#x}, cover art psm={:#x}", + p_rc_open->peer_features, p_dev->rc_features, p_dev->peer_ct_features, + p_dev->peer_tg_features, p_dev->rc_cover_art_psm); p_dev->rc_connected = true; p_dev->rc_handle = p_rc_open->rc_handle; @@ -879,15 +819,14 @@ void handle_rc_connect(tBTA_AV_RC_OPEN* p_rc_open) { p_dev->rc_playing_uid = RC_INVALID_TRACK_ID; - if (btif_av_src_sink_coexist_enabled() && - !btif_av_peer_is_connected_source(p_dev->rc_addr)) { + if (btif_av_src_sink_coexist_enabled() && !btif_av_peer_is_connected_source(p_dev->rc_addr)) { p_dev->launch_cmd_pending |= RC_PENDING_ACT_REPORT_CONN; log::verbose("pending rc connection event"); return; } if (bt_rc_ctrl_callbacks != NULL) { - do_in_jni_thread(base::BindOnce(bt_rc_ctrl_callbacks->connection_state_cb, - true, false, p_dev->rc_addr)); + do_in_jni_thread( + base::BindOnce(bt_rc_ctrl_callbacks->connection_state_cb, true, false, p_dev->rc_addr)); /* report connection state if remote device is AVRCP target */ handle_rc_ctrl_features(p_dev); @@ -914,16 +853,15 @@ void handle_rc_disconnect(tBTA_AV_RC_CLOSE* p_rc_close) { return; } - if (p_rc_close->rc_handle != p_dev->rc_handle && - p_dev->rc_addr != p_rc_close->peer_addr) { + if (p_rc_close->rc_handle != p_dev->rc_handle && p_dev->rc_addr != p_rc_close->peer_addr) { log::error("Got disconnect of unknown device"); return; } /* Report connection state if device is AVRCP target */ if (bt_rc_ctrl_callbacks != NULL) { - do_in_jni_thread(base::BindOnce(bt_rc_ctrl_callbacks->connection_state_cb, - false, false, p_dev->rc_addr)); + do_in_jni_thread(base::BindOnce(bt_rc_ctrl_callbacks->connection_state_cb, false, false, + p_dev->rc_addr)); } // We'll re-initialize the device state back to what it looked like before @@ -947,8 +885,7 @@ void handle_rc_passthrough_cmd(tBTA_AV_REMOTE_CMD* p_remote_cmd) { return; } - btif_rc_device_cb_t* p_dev = - btif_rc_get_device_by_handle(p_remote_cmd->rc_handle); + btif_rc_device_cb_t* p_dev = btif_rc_get_device_by_handle(p_remote_cmd->rc_handle); if (p_dev == NULL) { log::error("Got passthrough command from invalid rc handle"); return; @@ -958,8 +895,7 @@ void handle_rc_passthrough_cmd(tBTA_AV_REMOTE_CMD* p_remote_cmd) { /* If AVRC is open and peer sends PLAY but there is no AVDT, then we queue-up * this PLAY */ - if ((p_remote_cmd->rc_id == AVRC_ID_PLAY) && - (!btif_av_is_connected(A2dpType::kSink))) { + if ((p_remote_cmd->rc_id == AVRC_ID_PLAY) && (!btif_av_is_connected(A2dpType::kSink))) { if (p_remote_cmd->key_state == AVRC_STATE_PRESS) { log::warn("AVDT not open, queuing the PLAY command"); p_dev->rc_pending_play = true; @@ -974,8 +910,7 @@ void handle_rc_passthrough_cmd(tBTA_AV_REMOTE_CMD* p_remote_cmd) { return; } - if ((p_remote_cmd->rc_id == AVRC_ID_STOP) && - (!btif_av_stream_started_ready(A2dpType::kSink))) { + if ((p_remote_cmd->rc_id == AVRC_ID_STOP) && (!btif_av_stream_started_ready(A2dpType::kSink))) { log::warn("Stream suspended, ignore STOP cmd"); return; } @@ -983,10 +918,9 @@ void handle_rc_passthrough_cmd(tBTA_AV_REMOTE_CMD* p_remote_cmd) { int pressed = (p_remote_cmd->key_state == AVRC_STATE_PRESS) ? 1 : 0; /* pass all commands up */ - log::verbose("rc_features: {}, cmd->rc_id: {}, pressed: {}", - p_dev->rc_features, p_remote_cmd->rc_id, pressed); - HAL_CBACK(bt_rc_callbacks, passthrough_cmd_cb, p_remote_cmd->rc_id, pressed, - p_dev->rc_addr); + log::verbose("rc_features: {}, cmd->rc_id: {}, pressed: {}", p_dev->rc_features, + p_remote_cmd->rc_id, pressed); + HAL_CBACK(bt_rc_callbacks, passthrough_cmd_cb, p_remote_cmd->rc_id, pressed, p_dev->rc_addr); } /*************************************************************************** @@ -1006,7 +940,6 @@ void handle_rc_passthrough_rsp(tBTA_AV_REMOTE_RSP* p_remote_rsp) { return; } - if (!(p_dev->rc_features & BTA_AV_FEAT_RCTG)) { log::error("DUT does not support AVRCP controller role"); return; @@ -1017,9 +950,8 @@ void handle_rc_passthrough_rsp(tBTA_AV_REMOTE_RSP* p_remote_rsp) { release_transaction(p_dev, p_remote_rsp->label); if (bt_rc_ctrl_callbacks != NULL) { - do_in_jni_thread(base::BindOnce(bt_rc_ctrl_callbacks->passthrough_rsp_cb, - p_dev->rc_addr, p_remote_rsp->rc_id, - p_remote_rsp->key_state)); + do_in_jni_thread(base::BindOnce(bt_rc_ctrl_callbacks->passthrough_rsp_cb, p_dev->rc_addr, + p_remote_rsp->rc_id, p_remote_rsp->key_state)); } } @@ -1053,15 +985,16 @@ void handle_rc_vendorunique_rsp(tBTA_AV_REMOTE_RSP* p_remote_rsp) { } if (p_remote_rsp->len > 0 && p_remote_rsp->p_data != NULL) { - if (p_remote_rsp->len >= AVRC_PASS_THRU_GROUP_LEN) + if (p_remote_rsp->len >= AVRC_PASS_THRU_GROUP_LEN) { vendor_id = p_remote_rsp->p_data[AVRC_PASS_THRU_GROUP_LEN - 1]; + } osi_free_and_reset((void**)&p_remote_rsp->p_data); } log::verbose("vendor_id: {} status: {}", vendor_id, status); release_transaction(p_dev, p_remote_rsp->label); - do_in_jni_thread(base::BindOnce( - bt_rc_ctrl_callbacks->groupnavigation_rsp_cb, vendor_id, key_state)); + do_in_jni_thread( + base::BindOnce(bt_rc_ctrl_callbacks->groupnavigation_rsp_cb, vendor_id, key_state)); } else { log::error("Remote does not support AVRCP TG role"); } @@ -1093,8 +1026,8 @@ void handle_rc_metamsg_cmd(tBTA_AV_META_MSG* pmeta_msg) { return; } - log::verbose("pmeta_msg: opcode: {:x}, code: {:x}", - pmeta_msg->p_msg->hdr.opcode, pmeta_msg->code); + log::verbose("pmeta_msg: opcode: {:x}, code: {:x}", pmeta_msg->p_msg->hdr.opcode, + pmeta_msg->code); p_dev = btif_rc_get_device_by_handle(pmeta_msg->rc_handle); if (p_dev == NULL) { @@ -1109,8 +1042,8 @@ void handle_rc_metamsg_cmd(tBTA_AV_META_MSG* pmeta_msg) { } if (pmeta_msg->len < 3) { - log::warn("Invalid length. opcode: 0x{:x}, len: 0x{:x}", - pmeta_msg->p_msg->hdr.opcode, pmeta_msg->len); + log::warn("Invalid length. opcode: 0x{:x}, len: 0x{:x}", pmeta_msg->p_msg->hdr.opcode, + pmeta_msg->len); return; } @@ -1121,24 +1054,21 @@ void handle_rc_metamsg_cmd(tBTA_AV_META_MSG* pmeta_msg) { if (transaction != NULL) { handle_rc_metamsg_rsp(pmeta_msg, p_dev); } else { - log::verbose("Discard vendor dependent rsp. code: {} label: {}.", - pmeta_msg->code, pmeta_msg->label); + log::verbose("Discard vendor dependent rsp. code: {} label: {}.", pmeta_msg->code, + pmeta_msg->label); } return; } } - status = AVRC_ParsCommand(pmeta_msg->p_msg, &avrc_command, scratch_buf, - sizeof(scratch_buf)); - log::verbose("Received vendor command.code,PDU and label: {}, {}, {}", - pmeta_msg->code, avrc_command.cmd.pdu, pmeta_msg->label); + status = AVRC_ParsCommand(pmeta_msg->p_msg, &avrc_command, scratch_buf, sizeof(scratch_buf)); + log::verbose("Received vendor command.code,PDU and label: {}, {}, {}", pmeta_msg->code, + avrc_command.cmd.pdu, pmeta_msg->label); if (status != AVRC_STS_NO_ERROR) { /* return error */ - log::warn("Error in parsing received metamsg command. status: 0x{:02x}", - status); - send_reject_response(pmeta_msg->rc_handle, pmeta_msg->label, - avrc_command.pdu, status, + log::warn("Error in parsing received metamsg command. status: 0x{:02x}", status); + send_reject_response(pmeta_msg->rc_handle, pmeta_msg->label, avrc_command.pdu, status, pmeta_msg->p_msg->hdr.opcode); } else { /* if RegisterNotification, add it to our registered queue */ @@ -1147,10 +1077,9 @@ void handle_rc_metamsg_cmd(tBTA_AV_META_MSG* pmeta_msg) { uint8_t event_id = avrc_command.reg_notif.event_id; log::verbose( - "New register notification received.event_id: {}, label: 0x{:x}, " - "code: {:x}", - dump_rc_notification_event_id(event_id), pmeta_msg->label, - pmeta_msg->code); + "New register notification received.event_id: {}, label: 0x{:x}, " + "code: {:x}", + dump_rc_notification_event_id(event_id), pmeta_msg->label, pmeta_msg->code); p_dev->rc_notif[event_id - 1].bNotify = true; p_dev->rc_notif[event_id - 1].label = pmeta_msg->label; /* this is sink(tg) feature, so it should not handle here */ @@ -1160,18 +1089,17 @@ void handle_rc_metamsg_cmd(tBTA_AV_META_MSG* pmeta_msg) { } /* this is sink(tg) feature, so it should not handle here */ - if (btif_av_both_enable() && - avrc_command.cmd.pdu == AVRC_PDU_SET_ABSOLUTE_VOLUME) { + if (btif_av_both_enable() && avrc_command.cmd.pdu == AVRC_PDU_SET_ABSOLUTE_VOLUME) { return; } log::verbose("Passing received metamsg command to app. pdu: {}", dump_rc_pdu(avrc_command.cmd.pdu)); /* Since handle_rc_metamsg_cmd() itself is called from - *btif context, no context switching is required. Invoke - * btif_rc_upstreams_evt directly from here. */ - btif_rc_upstreams_evt((uint16_t)avrc_command.cmd.pdu, &avrc_command, - pmeta_msg->code, pmeta_msg->label, p_dev); + *btif context, no context switching is required. Invoke + * btif_rc_upstreams_evt directly from here. */ + btif_rc_upstreams_evt((uint16_t)avrc_command.cmd.pdu, &avrc_command, pmeta_msg->code, + pmeta_msg->label, p_dev); } } @@ -1187,8 +1115,7 @@ void btif_rc_handler(tBTA_AV_EVT event, tBTA_AV* p_data) { btif_rc_device_cb_t* p_dev = NULL; switch (event) { case BTA_AV_RC_OPEN_EVT: { - log::verbose("Peer_features: 0x{:x} Cover Art PSM: 0x{:x}", - p_data->rc_open.peer_features, + log::verbose("Peer_features: 0x{:x} Cover Art PSM: 0x{:x}", p_data->rc_open.peer_features, p_data->rc_open.cover_art_psm); handle_rc_connect(&(p_data->rc_open)); } break; @@ -1211,7 +1138,7 @@ void btif_rc_handler(tBTA_AV_EVT event, tBTA_AV* p_data) { if (bt_rc_callbacks != NULL) { log::verbose("rc_id: 0x{:x} key_state: {}", p_data->remote_cmd.rc_id, p_data->remote_cmd.key_state); - handle_rc_passthrough_cmd((&p_data->remote_cmd)); + handle_rc_passthrough_cmd(&p_data->remote_cmd); } else { log::error("AVRCP TG role not up, drop passthrough commands"); } @@ -1222,9 +1149,9 @@ void btif_rc_handler(tBTA_AV_EVT event, tBTA_AV* p_data) { p_data->remote_rsp.key_state); if (p_data->remote_rsp.rc_id == AVRC_ID_VENDOR) { - handle_rc_vendorunique_rsp((&p_data->remote_rsp)); + handle_rc_vendorunique_rsp(&p_data->remote_rsp); } else { - handle_rc_passthrough_rsp((&p_data->remote_rsp)); + handle_rc_passthrough_rsp(&p_data->remote_rsp); } } break; @@ -1236,13 +1163,11 @@ void btif_rc_handler(tBTA_AV_EVT event, tBTA_AV* p_data) { break; } log::verbose("peer_ct_features:0x{:x}, peer_tg_features=0x{:x}", - p_data->rc_feat.peer_ct_features, - p_data->rc_feat.peer_tg_features); + p_data->rc_feat.peer_ct_features, p_data->rc_feat.peer_tg_features); if (btif_av_src_sink_coexist_enabled() && (p_dev->peer_ct_features == p_data->rc_feat.peer_ct_features) && (p_dev->peer_tg_features == p_data->rc_feat.peer_tg_features)) { - log::error( - "do SDP twice, no need callback rc_feature to framework again"); + log::error("do SDP twice, no need callback rc_feature to framework again"); break; } @@ -1259,8 +1184,7 @@ void btif_rc_handler(tBTA_AV_EVT event, tBTA_AV* p_data) { } break; case BTA_AV_RC_PSM_EVT: { - log::verbose("Peer cover art PSM: {:x}", - p_data->rc_cover_art_psm.cover_art_psm); + log::verbose("Peer cover art PSM: {:x}", p_data->rc_cover_art_psm.cover_art_psm); p_dev = btif_rc_get_device_by_handle(p_data->rc_cover_art_psm.rc_handle); if (p_dev == NULL) { log::error("RC PSM event for Invalid rc handle"); @@ -1275,11 +1199,10 @@ void btif_rc_handler(tBTA_AV_EVT event, tBTA_AV* p_data) { case BTA_AV_META_MSG_EVT: { if (bt_rc_callbacks != NULL) { - log::verbose("BTA_AV_META_MSG_EVT code: {} label: {}", - p_data->meta_msg.code, p_data->meta_msg.label); - log::verbose("company_id: 0x{:x} len: {} handle: {}", - p_data->meta_msg.company_id, p_data->meta_msg.len, - p_data->meta_msg.rc_handle); + log::verbose("BTA_AV_META_MSG_EVT code: {} label: {}", p_data->meta_msg.code, + p_data->meta_msg.label); + log::verbose("company_id: 0x{:x} len: {} handle: {}", p_data->meta_msg.company_id, + p_data->meta_msg.len, p_data->meta_msg.rc_handle); /* handle the metamsg command */ handle_rc_metamsg_cmd(&(p_data->meta_msg)); @@ -1289,11 +1212,9 @@ void btif_rc_handler(tBTA_AV_EVT event, tBTA_AV* p_data) { /* This is case of Sink + CT + TG(for abs vol)) */ log::verbose("BTA_AV_META_MSG_EVT code:{} label:{} opcode {} ctype {}", p_data->meta_msg.code, p_data->meta_msg.label, - p_data->meta_msg.p_msg->hdr.opcode, - p_data->meta_msg.p_msg->hdr.ctype); - log::verbose("company_id:0x{:x} len:{} handle:{}", - p_data->meta_msg.company_id, p_data->meta_msg.len, - p_data->meta_msg.rc_handle); + p_data->meta_msg.p_msg->hdr.opcode, p_data->meta_msg.p_msg->hdr.ctype); + log::verbose("company_id:0x{:x} len:{} handle:{}", p_data->meta_msg.company_id, + p_data->meta_msg.len, p_data->meta_msg.rc_handle); switch (p_data->meta_msg.p_msg->hdr.opcode) { case AVRC_OP_VENDOR: if ((p_data->meta_msg.code >= AVRC_RSP_NOT_IMPL) && @@ -1327,8 +1248,7 @@ void btif_rc_handler(tBTA_AV_EVT event, tBTA_AV* p_data) { bool btif_rc_is_connected_peer(const RawAddress& peer_addr) { for (int idx = 0; idx < BTIF_RC_NUM_CONN; idx++) { btif_rc_device_cb_t* p_dev = get_connected_device(idx); - if (p_dev != NULL && (p_dev->rc_connected == TRUE) && - peer_addr == p_dev->rc_addr) { + if (p_dev != NULL && (p_dev->rc_connected == TRUE) && peer_addr == p_dev->rc_addr) { return true; } } @@ -1363,8 +1283,7 @@ uint8_t btif_rc_get_connected_peer_handle(const RawAddress& peer_addr) { ***************************************************************************/ /* clear the queued PLAY command. if |bSendToApp| is true, forward to app */ -void btif_rc_check_handle_pending_play(const RawAddress& peer_addr, - bool bSendToApp) { +void btif_rc_check_handle_pending_play(const RawAddress& peer_addr, bool bSendToApp) { btif_rc_device_cb_t* p_dev = NULL; p_dev = btif_rc_get_device_by_bda(peer_addr); @@ -1388,7 +1307,7 @@ void btif_rc_check_handle_pending_play(const RawAddress& peer_addr, /* delay sending to app, else there is a timing issue in the framework, ** which causes the audio to be on th device's speaker. Delay between ** OPEN & RC_PLAYs - */ + */ sleep_ms(200); /* send to app - both PRESSED & RELEASED */ remote_cmd.key_state = AVRC_STATE_PRESS; @@ -1404,8 +1323,8 @@ void btif_rc_check_handle_pending_play(const RawAddress& peer_addr, } /* Generic reject response */ -static void send_reject_response(uint8_t rc_handle, uint8_t label, uint8_t pdu, - uint8_t status, uint8_t opcode) { +static void send_reject_response(uint8_t rc_handle, uint8_t label, uint8_t pdu, uint8_t status, + uint8_t opcode) { uint8_t ctype = AVRC_RSP_REJ; tAVRC_RESPONSE avrc_rsp; BT_HDR* p_msg = NULL; @@ -1422,9 +1341,8 @@ static void send_reject_response(uint8_t rc_handle, uint8_t label, uint8_t pdu, return; } - log::verbose( - "Sending error notification to handle: {}. pdu: {},status: 0x{:02x}", - rc_handle, dump_rc_pdu(pdu), status); + log::verbose("Sending error notification to handle: {}. pdu: {},status: 0x{:02x}", rc_handle, + dump_rc_pdu(pdu), status); BTA_AvMetaRsp(rc_handle, label, ctype, p_msg); } @@ -1442,9 +1360,13 @@ static tBTA_AV_CODE get_rsp_type_code(tAVRC_STS status, tBTA_AV_CODE code) { } if (code < AVRC_RSP_NOT_IMPL) { - if (code == AVRC_CMD_NOTIF) return AVRC_RSP_INTERIM; + if (code == AVRC_CMD_NOTIF) { + return AVRC_RSP_INTERIM; + } - if (code == AVRC_CMD_STATUS) return AVRC_RSP_IMPL_STBL; + if (code == AVRC_CMD_STATUS) { + return AVRC_RSP_IMPL_STBL; + } return AVRC_RSP_ACCEPT; } @@ -1465,9 +1387,8 @@ static tBTA_AV_CODE get_rsp_type_code(tAVRC_STS status, tBTA_AV_CODE code) { * - Description: Remote control metamsg response handler * ***************************************************************************/ -static void send_metamsg_rsp(btif_rc_device_cb_t* p_dev, int index, - uint8_t label, tBTA_AV_CODE code, - tAVRC_RESPONSE* pmetamsg_resp) { +static void send_metamsg_rsp(btif_rc_device_cb_t* p_dev, int index, uint8_t label, + tBTA_AV_CODE code, tAVRC_RESPONSE* pmetamsg_resp) { uint8_t ctype; if (p_dev == NULL) { @@ -1480,9 +1401,8 @@ static void send_metamsg_rsp(btif_rc_device_cb_t* p_dev, int index, return; } - log::verbose("rc_handle: {}, index: {}, label: {}, code: 0x{:02x}, pdu: {}", - p_dev->rc_handle, index, label, code, - dump_rc_pdu(pmetamsg_resp->rsp.pdu)); + log::verbose("rc_handle: {}, index: {}, label: {}, code: 0x{:02x}, pdu: {}", p_dev->rc_handle, + index, label, code, dump_rc_pdu(pmetamsg_resp->rsp.pdu)); if (index >= 0 && !p_dev->rc_pdu_info[index].is_rsp_pending) { log::error("is_rsp_pending false, returning"); @@ -1497,24 +1417,22 @@ static void send_metamsg_rsp(btif_rc_device_cb_t* p_dev, int index, ((code == AVRC_RSP_CHANGED) || (code == AVRC_RSP_INTERIM))) { bool bSent = false; uint8_t event_id = pmetamsg_resp->reg_notif.event_id; - bool bNotify = - (p_dev->rc_connected) && (p_dev->rc_notif[event_id - 1].bNotify); + bool bNotify = (p_dev->rc_connected) && (p_dev->rc_notif[event_id - 1].bNotify); /* de-register this notification for a CHANGED response */ p_dev->rc_notif[event_id - 1].bNotify = false; - log::verbose("rc_handle: {}. event_id: 0x{:02} bNotify: {}", - p_dev->rc_handle, event_id, bNotify); + log::verbose("rc_handle: {}. event_id: 0x{:02} bNotify: {}", p_dev->rc_handle, event_id, + bNotify); if (bNotify) { BT_HDR* p_msg = NULL; tAVRC_STS status; - if (AVRC_STS_NO_ERROR == (status = AVRC_BldResponse( - p_dev->rc_handle, pmetamsg_resp, &p_msg))) { - log::verbose("Sending notification to rc_handle: {}. event_id: 0x{:02}", - p_dev->rc_handle, event_id); + if (AVRC_STS_NO_ERROR == + (status = AVRC_BldResponse(p_dev->rc_handle, pmetamsg_resp, &p_msg))) { + log::verbose("Sending notification to rc_handle: {}. event_id: 0x{:02}", p_dev->rc_handle, + event_id); bSent = true; - BTA_AvMetaRsp(p_dev->rc_handle, p_dev->rc_notif[event_id - 1].label, - ctype, p_msg); + BTA_AvMetaRsp(p_dev->rc_handle, p_dev->rc_notif[event_id - 1].label, ctype, p_msg); } else { log::warn("failed to build metamsg response. status: 0x{:02x}", status); } @@ -1522,9 +1440,9 @@ static void send_metamsg_rsp(btif_rc_device_cb_t* p_dev, int index, if (!bSent) { log::verbose( - "Notification not sent, as there are no RC connections or the CT has " - "not subscribed for event_id: {}", - dump_rc_notification_event_id(event_id)); + "Notification not sent, as there are no RC connections or the CT has " + "not subscribed for event_id: {}", + dump_rc_notification_event_id(event_id)); } } else { /* All other commands go here */ @@ -1592,16 +1510,16 @@ static uint8_t opcode_from_pdu(uint8_t pdu) { * The number of attributes filled in * ***************************************************************************/ -static uint8_t fill_attribute_id_array( - uint8_t cmd_attribute_number, const uint32_t* cmd_attribute_id_array, - size_t out_array_size, btrc_media_attr_t* out_attribute_id_array) { +static uint8_t fill_attribute_id_array(uint8_t cmd_attribute_number, + const uint32_t* cmd_attribute_id_array, + size_t out_array_size, + btrc_media_attr_t* out_attribute_id_array) { /* Default case for cmd_attribute_number == 0xFF, No attribute */ uint8_t out_attribute_number = 0; if (cmd_attribute_number == 0) { /* All attributes */ - out_attribute_number = out_array_size < AVRC_MAX_NUM_MEDIA_ATTR_ID - ? out_array_size - : AVRC_MAX_NUM_MEDIA_ATTR_ID; + out_attribute_number = out_array_size < AVRC_MAX_NUM_MEDIA_ATTR_ID ? out_array_size + : AVRC_MAX_NUM_MEDIA_ATTR_ID; for (int i = 0; i < out_attribute_number; i++) { out_attribute_id_array[i] = (btrc_media_attr_t)(i + 1); } @@ -1609,23 +1527,21 @@ static uint8_t fill_attribute_id_array( /* Attribute List */ out_attribute_number = 0; int filled_id_count = 0; - for (int i = 0; (i < cmd_attribute_number) && - (out_attribute_number < out_array_size) && + for (int i = 0; (i < cmd_attribute_number) && (out_attribute_number < out_array_size) && (out_attribute_number < AVRC_MAX_NUM_MEDIA_ATTR_ID); i++) { /* Fill only valid entries */ if (AVRC_IS_VALID_MEDIA_ATTRIBUTE(cmd_attribute_id_array[i])) { /* Skip the duplicate entries */ - for (filled_id_count = 0; filled_id_count < out_attribute_number; - filled_id_count++) { - if (out_attribute_id_array[filled_id_count] == - cmd_attribute_id_array[i]) + for (filled_id_count = 0; filled_id_count < out_attribute_number; filled_id_count++) { + if (out_attribute_id_array[filled_id_count] == cmd_attribute_id_array[i]) { break; + } } /* New ID */ if (filled_id_count == out_attribute_number) { out_attribute_id_array[out_attribute_number] = - (btrc_media_attr_t)cmd_attribute_id_array[i]; + (btrc_media_attr_t)cmd_attribute_id_array[i]; out_attribute_number++; } } @@ -1643,9 +1559,8 @@ static uint8_t fill_attribute_id_array( * Returns void * ******************************************************************************/ -static void btif_rc_upstreams_evt(uint16_t event, tAVRC_COMMAND* pavrc_cmd, - uint8_t ctype, uint8_t label, - btif_rc_device_cb_t* p_dev) { +static void btif_rc_upstreams_evt(uint16_t event, tAVRC_COMMAND* pavrc_cmd, uint8_t ctype, + uint8_t label, btif_rc_device_cb_t* p_dev) { log::verbose("pdu: {} handle: 0x{:x} ctype: {:x} label: {:x} event ID: {:x}", dump_rc_pdu(pavrc_cmd->pdu), p_dev->rc_handle, ctype, label, pavrc_cmd->reg_notif.event_id); @@ -1662,45 +1577,43 @@ static void btif_rc_upstreams_evt(uint16_t event, tAVRC_COMMAND* pavrc_cmd, case AVRC_PDU_GET_PLAYER_APP_ATTR_TEXT: case AVRC_PDU_GET_PLAYER_APP_VALUE_TEXT: { /* TODO: Add support for Application Settings */ - send_reject_response(p_dev->rc_handle, label, pavrc_cmd->pdu, - AVRC_STS_BAD_CMD, pavrc_cmd->cmd.opcode); + send_reject_response(p_dev->rc_handle, label, pavrc_cmd->pdu, AVRC_STS_BAD_CMD, + pavrc_cmd->cmd.opcode); } break; case AVRC_PDU_GET_ELEMENT_ATTR: { btrc_media_attr_t element_attrs[BTRC_MAX_ELEM_ATTR_SIZE] = {}; - uint8_t num_attr = fill_attribute_id_array( - pavrc_cmd->get_elem_attrs.num_attr, pavrc_cmd->get_elem_attrs.attrs, - BTRC_MAX_ELEM_ATTR_SIZE, element_attrs); + uint8_t num_attr = fill_attribute_id_array(pavrc_cmd->get_elem_attrs.num_attr, + pavrc_cmd->get_elem_attrs.attrs, + BTRC_MAX_ELEM_ATTR_SIZE, element_attrs); if (num_attr == 0) { log::error("No valid attributes requested in GET_ELEMENT_ATTRIBUTES"); - send_reject_response(p_dev->rc_handle, label, pavrc_cmd->pdu, - AVRC_STS_BAD_PARAM, pavrc_cmd->cmd.opcode); + send_reject_response(p_dev->rc_handle, label, pavrc_cmd->pdu, AVRC_STS_BAD_PARAM, + pavrc_cmd->cmd.opcode); return; } fill_pdu_queue(IDX_GET_ELEMENT_ATTR_RSP, ctype, label, true, p_dev); - HAL_CBACK(bt_rc_callbacks, get_element_attr_cb, num_attr, element_attrs, - p_dev->rc_addr); + HAL_CBACK(bt_rc_callbacks, get_element_attr_cb, num_attr, element_attrs, p_dev->rc_addr); } break; case AVRC_PDU_REGISTER_NOTIFICATION: { if (pavrc_cmd->reg_notif.event_id == BTRC_EVT_PLAY_POS_CHANGED && pavrc_cmd->reg_notif.param == 0) { log::warn("Device registering position changed with illegal param 0."); - send_reject_response(p_dev->rc_handle, label, pavrc_cmd->pdu, - AVRC_STS_BAD_PARAM, pavrc_cmd->cmd.opcode); + send_reject_response(p_dev->rc_handle, label, pavrc_cmd->pdu, AVRC_STS_BAD_PARAM, + pavrc_cmd->cmd.opcode); /* de-register this notification for a rejected response */ p_dev->rc_notif[BTRC_EVT_PLAY_POS_CHANGED - 1].bNotify = false; return; } HAL_CBACK(bt_rc_callbacks, register_notification_cb, - (btrc_event_id_t)pavrc_cmd->reg_notif.event_id, - pavrc_cmd->reg_notif.param, p_dev->rc_addr); + (btrc_event_id_t)pavrc_cmd->reg_notif.event_id, pavrc_cmd->reg_notif.param, + p_dev->rc_addr); } break; case AVRC_PDU_INFORM_DISPLAY_CHARSET: { tAVRC_RESPONSE avrc_rsp; log::verbose("AVRC_PDU_INFORM_DISPLAY_CHARSET"); if (p_dev->rc_connected) { memset(&(avrc_rsp.inform_charset), 0, sizeof(tAVRC_RSP)); - avrc_rsp.inform_charset.opcode = - opcode_from_pdu(AVRC_PDU_INFORM_DISPLAY_CHARSET); + avrc_rsp.inform_charset.opcode = opcode_from_pdu(AVRC_PDU_INFORM_DISPLAY_CHARSET); avrc_rsp.inform_charset.pdu = AVRC_PDU_INFORM_DISPLAY_CHARSET; avrc_rsp.inform_charset.status = AVRC_STS_NO_ERROR; send_metamsg_rsp(p_dev, -1, label, ctype, &avrc_rsp); @@ -1713,56 +1626,51 @@ static void btif_rc_upstreams_evt(uint16_t event, tAVRC_COMMAND* pavrc_cmd, num_attr = pavrc_cmd->get_items.attr_count; log::verbose( - "AVRC_PDU_GET_FOLDER_ITEMS num_attr: {}, start_item [{}] end_item " - "[{}]", - num_attr, pavrc_cmd->get_items.start_item, - pavrc_cmd->get_items.end_item); + "AVRC_PDU_GET_FOLDER_ITEMS num_attr: {}, start_item [{}] end_item " + "[{}]", + num_attr, pavrc_cmd->get_items.start_item, pavrc_cmd->get_items.end_item); /* num_attr requested: * 0x00: All attributes requested * 0xFF: No Attributes requested * 0x01 to 0x07: Specified number of attributes */ - if ((num_attr != 0xFF && num_attr > BTRC_MAX_ELEM_ATTR_SIZE)) { - send_reject_response(p_dev->rc_handle, label, pavrc_cmd->pdu, - AVRC_STS_BAD_PARAM, pavrc_cmd->cmd.opcode); + if (num_attr != 0xFF && num_attr > BTRC_MAX_ELEM_ATTR_SIZE) { + send_reject_response(p_dev->rc_handle, label, pavrc_cmd->pdu, AVRC_STS_BAD_PARAM, + pavrc_cmd->cmd.opcode); return; } /* Except num_attr is None(0xff) / All(0x00), request follows with an * Attribute List */ if ((num_attr != 0xFF) && (num_attr != 0x00)) { - memcpy(attr_ids, pavrc_cmd->get_items.p_attr_list, - sizeof(uint32_t) * num_attr); + memcpy(attr_ids, pavrc_cmd->get_items.p_attr_list, sizeof(uint32_t) * num_attr); } fill_pdu_queue(IDX_GET_FOLDER_ITEMS_RSP, ctype, label, true, p_dev); - HAL_CBACK(bt_rc_callbacks, get_folder_items_cb, - pavrc_cmd->get_items.scope, pavrc_cmd->get_items.start_item, - pavrc_cmd->get_items.end_item, num_attr, attr_ids, + HAL_CBACK(bt_rc_callbacks, get_folder_items_cb, pavrc_cmd->get_items.scope, + pavrc_cmd->get_items.start_item, pavrc_cmd->get_items.end_item, num_attr, attr_ids, p_dev->rc_addr); } break; case AVRC_PDU_SET_ADDRESSED_PLAYER: { fill_pdu_queue(IDX_SET_ADDR_PLAYER_RSP, ctype, label, true, p_dev); - HAL_CBACK(bt_rc_callbacks, set_addressed_player_cb, - pavrc_cmd->addr_player.player_id, p_dev->rc_addr); + HAL_CBACK(bt_rc_callbacks, set_addressed_player_cb, pavrc_cmd->addr_player.player_id, + p_dev->rc_addr); } break; case AVRC_PDU_SET_BROWSED_PLAYER: { fill_pdu_queue(IDX_SET_BROWSED_PLAYER_RSP, ctype, label, true, p_dev); - HAL_CBACK(bt_rc_callbacks, set_browsed_player_cb, - pavrc_cmd->br_player.player_id, p_dev->rc_addr); + HAL_CBACK(bt_rc_callbacks, set_browsed_player_cb, pavrc_cmd->br_player.player_id, + p_dev->rc_addr); } break; case AVRC_PDU_REQUEST_CONTINUATION_RSP: { - log::verbose("REQUEST CONTINUATION: target_pdu: 0x{:02d}", - pavrc_cmd->continu.target_pdu); + log::verbose("REQUEST CONTINUATION: target_pdu: 0x{:02d}", pavrc_cmd->continu.target_pdu); tAVRC_RESPONSE avrc_rsp; if (p_dev->rc_connected == TRUE) { memset(&(avrc_rsp.continu), 0, sizeof(tAVRC_NEXT_RSP)); - avrc_rsp.continu.opcode = - opcode_from_pdu(AVRC_PDU_REQUEST_CONTINUATION_RSP); + avrc_rsp.continu.opcode = opcode_from_pdu(AVRC_PDU_REQUEST_CONTINUATION_RSP); avrc_rsp.continu.pdu = AVRC_PDU_REQUEST_CONTINUATION_RSP; avrc_rsp.continu.status = AVRC_STS_NO_ERROR; avrc_rsp.continu.target_pdu = pavrc_cmd->continu.target_pdu; @@ -1771,13 +1679,11 @@ static void btif_rc_upstreams_evt(uint16_t event, tAVRC_COMMAND* pavrc_cmd, } break; case AVRC_PDU_ABORT_CONTINUATION_RSP: { - log::verbose("ABORT CONTINUATION: target_pdu: 0x{:02d}", - pavrc_cmd->abort.target_pdu); + log::verbose("ABORT CONTINUATION: target_pdu: 0x{:02d}", pavrc_cmd->abort.target_pdu); tAVRC_RESPONSE avrc_rsp; if (p_dev->rc_connected == TRUE) { memset(&(avrc_rsp.abort), 0, sizeof(tAVRC_NEXT_RSP)); - avrc_rsp.abort.opcode = - opcode_from_pdu(AVRC_PDU_ABORT_CONTINUATION_RSP); + avrc_rsp.abort.opcode = opcode_from_pdu(AVRC_PDU_ABORT_CONTINUATION_RSP); avrc_rsp.abort.pdu = AVRC_PDU_ABORT_CONTINUATION_RSP; avrc_rsp.abort.status = AVRC_STS_NO_ERROR; avrc_rsp.abort.target_pdu = pavrc_cmd->continu.target_pdu; @@ -1794,51 +1700,48 @@ static void btif_rc_upstreams_evt(uint16_t event, tAVRC_COMMAND* pavrc_cmd, case AVRC_PDU_SEARCH: { fill_pdu_queue(IDX_SEARCH_RSP, ctype, label, true, p_dev); HAL_CBACK(bt_rc_callbacks, search_cb, pavrc_cmd->search.string.charset_id, - pavrc_cmd->search.string.str_len, - pavrc_cmd->search.string.p_str, p_dev->rc_addr); + pavrc_cmd->search.string.str_len, pavrc_cmd->search.string.p_str, p_dev->rc_addr); } break; case AVRC_PDU_GET_ITEM_ATTRIBUTES: { btrc_media_attr_t item_attrs[BTRC_MAX_ELEM_ATTR_SIZE] = {}; - uint8_t num_attr = fill_attribute_id_array( - pavrc_cmd->get_attrs.attr_count, pavrc_cmd->get_attrs.p_attr_list, - BTRC_MAX_ELEM_ATTR_SIZE, item_attrs); + uint8_t num_attr = fill_attribute_id_array(pavrc_cmd->get_attrs.attr_count, + pavrc_cmd->get_attrs.p_attr_list, + BTRC_MAX_ELEM_ATTR_SIZE, item_attrs); if (num_attr == 0) { log::error("No valid attributes requested in GET_ITEM_ATTRIBUTES"); - send_reject_response(p_dev->rc_handle, label, pavrc_cmd->pdu, - AVRC_STS_BAD_PARAM, pavrc_cmd->cmd.opcode); + send_reject_response(p_dev->rc_handle, label, pavrc_cmd->pdu, AVRC_STS_BAD_PARAM, + pavrc_cmd->cmd.opcode); return; } fill_pdu_queue(IDX_GET_ITEM_ATTR_RSP, ctype, label, true, p_dev); log::verbose("GET_ITEM_ATTRIBUTES: num_attr: {}", num_attr); HAL_CBACK(bt_rc_callbacks, get_item_attr_cb, pavrc_cmd->get_attrs.scope, - pavrc_cmd->get_attrs.uid, pavrc_cmd->get_attrs.uid_counter, - num_attr, item_attrs, p_dev->rc_addr); + pavrc_cmd->get_attrs.uid, pavrc_cmd->get_attrs.uid_counter, num_attr, item_attrs, + p_dev->rc_addr); } break; case AVRC_PDU_GET_TOTAL_NUM_OF_ITEMS: { fill_pdu_queue(IDX_GET_TOTAL_NUM_OF_ITEMS_RSP, ctype, label, true, p_dev); - HAL_CBACK(bt_rc_callbacks, get_total_num_of_items_cb, - pavrc_cmd->get_num_of_items.scope, p_dev->rc_addr); + HAL_CBACK(bt_rc_callbacks, get_total_num_of_items_cb, pavrc_cmd->get_num_of_items.scope, + p_dev->rc_addr); } break; case AVRC_PDU_ADD_TO_NOW_PLAYING: { fill_pdu_queue(IDX_ADD_TO_NOW_PLAYING_RSP, ctype, label, true, p_dev); - HAL_CBACK(bt_rc_callbacks, add_to_now_playing_cb, - pavrc_cmd->add_to_play.scope, pavrc_cmd->add_to_play.uid, - pavrc_cmd->add_to_play.uid_counter, p_dev->rc_addr); + HAL_CBACK(bt_rc_callbacks, add_to_now_playing_cb, pavrc_cmd->add_to_play.scope, + pavrc_cmd->add_to_play.uid, pavrc_cmd->add_to_play.uid_counter, p_dev->rc_addr); } break; case AVRC_PDU_PLAY_ITEM: { fill_pdu_queue(IDX_PLAY_ITEM_RSP, ctype, label, true, p_dev); HAL_CBACK(bt_rc_callbacks, play_item_cb, pavrc_cmd->play_item.scope, - pavrc_cmd->play_item.uid_counter, pavrc_cmd->play_item.uid, - p_dev->rc_addr); + pavrc_cmd->play_item.uid_counter, pavrc_cmd->play_item.uid, p_dev->rc_addr); } break; default: { - send_reject_response(p_dev->rc_handle, label, pavrc_cmd->pdu, - AVRC_STS_BAD_CMD, pavrc_cmd->cmd.opcode); + send_reject_response(p_dev->rc_handle, label, pavrc_cmd->pdu, AVRC_STS_BAD_CMD, + pavrc_cmd->cmd.opcode); return; } break; } @@ -1853,23 +1756,18 @@ static void btif_rc_upstreams_evt(uint16_t event, tAVRC_COMMAND* pavrc_cmd, * Returns void * ******************************************************************************/ -static void btif_rc_ctrl_upstreams_rsp_cmd(uint8_t event, - tAVRC_COMMAND* pavrc_cmd, - uint8_t label, +static void btif_rc_ctrl_upstreams_rsp_cmd(uint8_t event, tAVRC_COMMAND* pavrc_cmd, uint8_t label, btif_rc_device_cb_t* p_dev) { - log::verbose("pdu: {}: handle: 0x{:x}", dump_rc_pdu(pavrc_cmd->pdu), - p_dev->rc_handle); + log::verbose("pdu: {}: handle: 0x{:x}", dump_rc_pdu(pavrc_cmd->pdu), p_dev->rc_handle); switch (event) { case AVRC_PDU_SET_ABSOLUTE_VOLUME: - do_in_jni_thread(base::BindOnce(bt_rc_ctrl_callbacks->setabsvol_cmd_cb, - p_dev->rc_addr, pavrc_cmd->volume.volume, - label)); + do_in_jni_thread(base::BindOnce(bt_rc_ctrl_callbacks->setabsvol_cmd_cb, p_dev->rc_addr, + pavrc_cmd->volume.volume, label)); break; case AVRC_PDU_REGISTER_NOTIFICATION: if (pavrc_cmd->reg_notif.event_id == AVRC_EVT_VOLUME_CHANGE) { - do_in_jni_thread( - base::BindOnce(bt_rc_ctrl_callbacks->registernotification_absvol_cb, - p_dev->rc_addr, label)); + do_in_jni_thread(base::BindOnce(bt_rc_ctrl_callbacks->registernotification_absvol_cb, + p_dev->rc_addr, label)); } break; } @@ -1884,29 +1782,28 @@ static void btif_rc_ctrl_upstreams_rsp_cmd(uint8_t event, * Returns void * ******************************************************************************/ -static void btif_rc_upstreams_rsp_evt(uint16_t event, - tAVRC_RESPONSE* pavrc_resp, uint8_t ctype, - uint8_t label, - btif_rc_device_cb_t* p_dev) { - log::verbose("pdu: {}: handle: 0x{:x} ctype: {:x} label: {:x}", - dump_rc_pdu(pavrc_resp->pdu), p_dev->rc_handle, ctype, label); +static void btif_rc_upstreams_rsp_evt(uint16_t event, tAVRC_RESPONSE* pavrc_resp, uint8_t ctype, + uint8_t label, btif_rc_device_cb_t* p_dev) { + log::verbose("pdu: {}: handle: 0x{:x} ctype: {:x} label: {:x}", dump_rc_pdu(pavrc_resp->pdu), + p_dev->rc_handle, ctype, label); switch (event) { case AVRC_PDU_REGISTER_NOTIFICATION: { - if (AVRC_RSP_CHANGED == ctype) + if (AVRC_RSP_CHANGED == ctype) { p_dev->rc_volume = pavrc_resp->reg_notif.param.volume; - HAL_CBACK(bt_rc_callbacks, volume_change_cb, - pavrc_resp->reg_notif.param.volume, ctype, p_dev->rc_addr); + } + HAL_CBACK(bt_rc_callbacks, volume_change_cb, pavrc_resp->reg_notif.param.volume, ctype, + p_dev->rc_addr); } break; case AVRC_PDU_SET_ABSOLUTE_VOLUME: { - log::verbose( - "Set absolute volume change event received: volume: {}, ctype: {}", - pavrc_resp->volume.volume, ctype); - if (AVRC_RSP_ACCEPT == ctype) + log::verbose("Set absolute volume change event received: volume: {}, ctype: {}", + pavrc_resp->volume.volume, ctype); + if (AVRC_RSP_ACCEPT == ctype) { p_dev->rc_volume = pavrc_resp->volume.volume; - HAL_CBACK(bt_rc_callbacks, volume_change_cb, pavrc_resp->volume.volume, - ctype, p_dev->rc_addr); + } + HAL_CBACK(bt_rc_callbacks, volume_change_cb, pavrc_resp->volume.volume, ctype, + p_dev->rc_addr); } break; default: @@ -1931,10 +1828,14 @@ static bt_status_t init(btrc_callbacks_t* callbacks) { log::verbose(""); bt_status_t result = BT_STATUS_SUCCESS; - if (bt_rc_callbacks) return BT_STATUS_DONE; + if (bt_rc_callbacks) { + return BT_STATUS_DONE; + } bt_rc_callbacks = callbacks; - if (bt_rc_ctrl_callbacks) return BT_STATUS_SUCCESS; + if (bt_rc_ctrl_callbacks) { + return BT_STATUS_SUCCESS; + } for (int idx = 0; idx < BTIF_RC_NUM_CONN; idx++) { initialize_device(&btif_rc_cb.rc_multi_cb[idx]); @@ -1956,10 +1857,14 @@ static bt_status_t init_ctrl(btrc_ctrl_callbacks_t* callbacks) { log::verbose(""); bt_status_t result = BT_STATUS_SUCCESS; - if (bt_rc_ctrl_callbacks) return BT_STATUS_DONE; + if (bt_rc_ctrl_callbacks) { + return BT_STATUS_DONE; + } bt_rc_ctrl_callbacks = callbacks; - if (bt_rc_callbacks) return BT_STATUS_SUCCESS; + if (bt_rc_callbacks) { + return BT_STATUS_SUCCESS; + } for (int idx = 0; idx < BTIF_RC_NUM_CONN; idx++) { initialize_device(&btif_rc_cb.rc_multi_cb[idx]); @@ -1994,8 +1899,7 @@ static void rc_ctrl_procedure_complete(btif_rc_device_cb_t* p_dev) { * Returns bt_status_t * **************************************************************************/ -static bt_status_t get_play_status_rsp(const RawAddress& bd_addr, - btrc_play_status_t play_status, +static bt_status_t get_play_status_rsp(const RawAddress& bd_addr, btrc_play_status_t play_status, uint32_t song_len, uint32_t song_pos) { tAVRC_RESPONSE avrc_rsp; btif_rc_device_cb_t* p_dev = btif_rc_get_device_by_bda(bd_addr); @@ -2012,14 +1916,12 @@ static bt_status_t get_play_status_rsp(const RawAddress& bd_addr, avrc_rsp.get_play_status.pdu = AVRC_PDU_GET_PLAY_STATUS; avrc_rsp.get_play_status.opcode = opcode_from_pdu(AVRC_PDU_GET_PLAY_STATUS); avrc_rsp.get_play_status.status = - ((play_status != BTRC_PLAYSTATE_ERROR) ? AVRC_STS_NO_ERROR - : AVRC_STS_BAD_PARAM); + ((play_status != BTRC_PLAYSTATE_ERROR) ? AVRC_STS_NO_ERROR : AVRC_STS_BAD_PARAM); /* Send the response */ send_metamsg_rsp(p_dev, IDX_GET_PLAY_STATUS_RSP, p_dev->rc_pdu_info[IDX_GET_PLAY_STATUS_RSP].label, - p_dev->rc_pdu_info[IDX_GET_PLAY_STATUS_RSP].ctype, - &avrc_rsp); + p_dev->rc_pdu_info[IDX_GET_PLAY_STATUS_RSP].ctype, &avrc_rsp); return BT_STATUS_SUCCESS; } @@ -2034,8 +1936,7 @@ static bt_status_t get_play_status_rsp(const RawAddress& bd_addr, * Returns bt_status_t * **************************************************************************/ -static bt_status_t get_element_attr_rsp(const RawAddress& bd_addr, - uint8_t num_attr, +static bt_status_t get_element_attr_rsp(const RawAddress& bd_addr, uint8_t num_attr, btrc_element_attr_val_t* p_attrs) { tAVRC_RESPONSE avrc_rsp; uint32_t i; @@ -2046,8 +1947,8 @@ static bt_status_t get_element_attr_rsp(const RawAddress& bd_addr, CHECK_RC_CONNECTED(p_dev); if (num_attr > BTRC_MAX_ELEM_ATTR_SIZE) { - log::warn("Exceeded number attributes:{} max:{}", - static_cast(num_attr), BTRC_MAX_ELEM_ATTR_SIZE); + log::warn("Exceeded number attributes:{} max:{}", static_cast(num_attr), + BTRC_MAX_ELEM_ATTR_SIZE); num_attr = BTRC_MAX_ELEM_ATTR_SIZE; } memset(element_attrs, 0, sizeof(tAVRC_ATTR_ENTRY) * num_attr); @@ -2059,11 +1960,10 @@ static bt_status_t get_element_attr_rsp(const RawAddress& bd_addr, element_attrs[i].attr_id = p_attrs[i].attr_id; element_attrs[i].name.charset_id = AVRC_CHARSET_ID_UTF8; element_attrs[i].name.str_len = - (uint16_t)strnlen((char*)p_attrs[i].text, BTRC_MAX_ATTR_STR_LEN); + (uint16_t)strnlen((char*)p_attrs[i].text, BTRC_MAX_ATTR_STR_LEN); element_attrs[i].name.p_str = p_attrs[i].text; log::verbose("attr_id: 0x{:x}, charset_id: 0x{:x}, str_len: {}, str: {}", - (unsigned int)element_attrs[i].attr_id, - element_attrs[i].name.charset_id, + (unsigned int)element_attrs[i].attr_id, element_attrs[i].name.charset_id, element_attrs[i].name.str_len, reinterpret_cast(element_attrs[i].name.p_str)); } @@ -2077,8 +1977,7 @@ static bt_status_t get_element_attr_rsp(const RawAddress& bd_addr, /* Send the response */ send_metamsg_rsp(p_dev, IDX_GET_ELEMENT_ATTR_RSP, p_dev->rc_pdu_info[IDX_GET_ELEMENT_ATTR_RSP].label, - p_dev->rc_pdu_info[IDX_GET_ELEMENT_ATTR_RSP].ctype, - &avrc_rsp); + p_dev->rc_pdu_info[IDX_GET_ELEMENT_ATTR_RSP].ctype, &avrc_rsp); return BT_STATUS_SUCCESS; } @@ -2092,9 +1991,9 @@ static bt_status_t get_element_attr_rsp(const RawAddress& bd_addr, * Returns bt_status_t * **************************************************************************/ -static bt_status_t register_notification_rsp( - btrc_event_id_t event_id, btrc_notification_type_t type, - btrc_register_notification_t* p_param) { +static bt_status_t register_notification_rsp(btrc_event_id_t event_id, + btrc_notification_type_t type, + btrc_register_notification_t* p_param) { tAVRC_RESPONSE avrc_rsp; log::verbose("event_id: {}", dump_rc_notification_event_id(event_id)); std::unique_lock lock(btif_rc_cb.lock); @@ -2121,24 +2020,23 @@ static bt_status_t register_notification_rsp( } if (!btif_rc_cb.rc_multi_cb[idx].rc_notif[event_id - 1].bNotify) { - log::warn( - "Avrcp Event id is not registered: event_id: {:x}, handle: 0x{:x}", - event_id, btif_rc_cb.rc_multi_cb[idx].rc_handle); + log::warn("Avrcp Event id is not registered: event_id: {:x}, handle: 0x{:x}", event_id, + btif_rc_cb.rc_multi_cb[idx].rc_handle); continue; } - log::verbose("Avrcp Event id is registered: event_id: {:x} handle: 0x{:x}", - event_id, btif_rc_cb.rc_multi_cb[idx].rc_handle); + log::verbose("Avrcp Event id is registered: event_id: {:x} handle: 0x{:x}", event_id, + btif_rc_cb.rc_multi_cb[idx].rc_handle); switch (event_id) { case BTRC_EVT_PLAY_STATUS_CHANGED: avrc_rsp.reg_notif.param.play_status = p_param->play_status; - if (avrc_rsp.reg_notif.param.play_status == PLAY_STATUS_PLAYING) + if (avrc_rsp.reg_notif.param.play_status == PLAY_STATUS_PLAYING) { btif_av_clear_remote_suspend_flag(A2dpType::kSink); + } break; case BTRC_EVT_TRACK_CHANGE: - memcpy(&(avrc_rsp.reg_notif.param.track), &(p_param->track), - sizeof(btrc_uid_t)); + memcpy(&(avrc_rsp.reg_notif.param.track), &(p_param->track), sizeof(btrc_uid_t)); break; case BTRC_EVT_PLAY_POS_CHANGED: avrc_rsp.reg_notif.param.play_pos = p_param->song_pos; @@ -2146,14 +2044,11 @@ static bt_status_t register_notification_rsp( case BTRC_EVT_AVAL_PLAYER_CHANGE: break; case BTRC_EVT_ADDR_PLAYER_CHANGE: - avrc_rsp.reg_notif.param.addr_player.player_id = - p_param->addr_player_changed.player_id; - avrc_rsp.reg_notif.param.addr_player.uid_counter = - p_param->addr_player_changed.uid_counter; + avrc_rsp.reg_notif.param.addr_player.player_id = p_param->addr_player_changed.player_id; + avrc_rsp.reg_notif.param.addr_player.uid_counter = p_param->addr_player_changed.uid_counter; break; case BTRC_EVT_UIDS_CHANGED: - avrc_rsp.reg_notif.param.uid_counter = - p_param->uids_changed.uid_counter; + avrc_rsp.reg_notif.param.uid_counter = p_param->uids_changed.uid_counter; break; case BTRC_EVT_NOW_PLAYING_CONTENT_CHANGED: break; @@ -2164,12 +2059,10 @@ static bt_status_t register_notification_rsp( } /* Send the response. */ - send_metamsg_rsp( - &btif_rc_cb.rc_multi_cb[idx], -1, - btif_rc_cb.rc_multi_cb[idx].rc_notif[event_id - 1].label, - ((type == BTRC_NOTIFICATION_TYPE_INTERIM) ? AVRC_CMD_NOTIF - : AVRC_RSP_CHANGED), - &avrc_rsp); + send_metamsg_rsp(&btif_rc_cb.rc_multi_cb[idx], -1, + btif_rc_cb.rc_multi_cb[idx].rc_notif[event_id - 1].label, + ((type == BTRC_NOTIFICATION_TYPE_INTERIM) ? AVRC_CMD_NOTIF : AVRC_RSP_CHANGED), + &avrc_rsp); } return BT_STATUS_SUCCESS; } @@ -2189,10 +2082,8 @@ static bt_status_t register_notification_rsp( * get_folder_items_list PDU * **************************************************************************/ -static bt_status_t get_folder_items_list_rsp(const RawAddress& bd_addr, - btrc_status_t rsp_status, - uint16_t uid_counter, - uint8_t num_items, +static bt_status_t get_folder_items_list_rsp(const RawAddress& bd_addr, btrc_status_t rsp_status, + uint16_t uid_counter, uint8_t num_items, btrc_folder_items_t* p_items) { tAVRC_RESPONSE avrc_rsp; tAVRC_ITEM item; @@ -2220,9 +2111,8 @@ static bt_status_t get_folder_items_list_rsp(const RawAddress& bd_addr, avrc_rsp.get_items.status = status_code_map[rsp_status]; if (avrc_rsp.get_items.status != AVRC_STS_NO_ERROR) { - log::warn( - "Error in parsing the received getfolderitems cmd. status: 0x{:02x}", - avrc_rsp.get_items.status); + log::warn("Error in parsing the received getfolderitems cmd. status: 0x{:02x}", + avrc_rsp.get_items.status); status = avrc_rsp.get_items.status; } else { avrc_rsp.get_items.uid_counter = uid_counter; @@ -2245,8 +2135,7 @@ static bt_status_t get_folder_items_list_rsp(const RawAddress& bd_addr, item.u.player.play_status = cur_item->player.play_status; item.u.player.player_id = cur_item->player.player_id; item.u.player.name.p_str = cur_item->player.name; - item.u.player.name.str_len = - (uint16_t)strlen((char*)(cur_item->player.name)); + item.u.player.name.str_len = (uint16_t)strlen((char*)(cur_item->player.name)); } break; case AVRC_ITEM_FOLDER: { @@ -2272,17 +2161,14 @@ static bt_status_t get_folder_items_list_rsp(const RawAddress& bd_addr, if (item.u.media.attr_count == 0) { item.u.media.p_attr_list = NULL; } else { - memset(&attr_vals, 0, - sizeof(tAVRC_ATTR_ENTRY) * BTRC_MAX_ELEM_ATTR_SIZE); - fill_avrc_attr_entry(attr_vals, item.u.media.attr_count, - cur_item->media.p_attrs); + memset(&attr_vals, 0, sizeof(tAVRC_ATTR_ENTRY) * BTRC_MAX_ELEM_ATTR_SIZE); + fill_avrc_attr_entry(attr_vals, item.u.media.attr_count, cur_item->media.p_attrs); item.u.media.p_attr_list = attr_vals; } } break; default: { - log::error("Unknown item_type: {}. Internal Error", - p_items->item_type); + log::error("Unknown item_type: {}. Internal Error", p_items->item_type); status = AVRC_STS_INTERNAL_ERR; } break; } @@ -2292,7 +2178,7 @@ static bt_status_t get_folder_items_list_rsp(const RawAddress& bd_addr, /* Add current item to buffer and build response if no error in item type */ if (status != AVRC_STS_NO_ERROR) { - /* Reject response due to error occured for unknown item_type, break the + /* Reject response due to error occurred for unknown item_type, break the * loop */ break; } @@ -2300,11 +2186,10 @@ static bt_status_t get_folder_items_list_rsp(const RawAddress& bd_addr, int len_before = p_msg ? p_msg->len : 0; log::verbose("item_cnt: {} len: {}", item_cnt, len_before); status = AVRC_BldResponse(p_dev->rc_handle, &avrc_rsp, &p_msg); - log::verbose("Build rsp status: {} len: {}", status, - p_msg ? p_msg->len : 0); + log::verbose("Build rsp status: {} len: {}", status, p_msg ? p_msg->len : 0); int len_after = p_msg ? p_msg->len : 0; if (status != AVRC_STS_NO_ERROR || len_before == len_after) { - /* Error occured in build response or we ran out of buffer so break the + /* Error occurred in build response or we ran out of buffer so break the * loop */ break; } @@ -2318,16 +2203,13 @@ static bt_status_t get_folder_items_list_rsp(const RawAddress& bd_addr, if (status == AVRC_STS_NO_ERROR) { code = p_dev->rc_pdu_info[IDX_GET_FOLDER_ITEMS_RSP].ctype; ctype = get_rsp_type_code(avrc_rsp.get_items.status, code); - BTA_AvMetaRsp(p_dev->rc_handle, - p_dev->rc_pdu_info[IDX_GET_FOLDER_ITEMS_RSP].label, ctype, + BTA_AvMetaRsp(p_dev->rc_handle, p_dev->rc_pdu_info[IDX_GET_FOLDER_ITEMS_RSP].label, ctype, p_msg); - } else /* Error occured, send reject response */ - { - log::error("Error status: 0x{:02X}. Sending reject rsp", - avrc_rsp.rsp.status); - send_reject_response( - p_dev->rc_handle, p_dev->rc_pdu_info[IDX_GET_FOLDER_ITEMS_RSP].label, - avrc_rsp.pdu, avrc_rsp.get_items.status, avrc_rsp.get_items.opcode); + } else { + /* Error occurred, send reject response */ + log::error("Error status: 0x{:02X}. Sending reject rsp", avrc_rsp.rsp.status); + send_reject_response(p_dev->rc_handle, p_dev->rc_pdu_info[IDX_GET_FOLDER_ITEMS_RSP].label, + avrc_rsp.pdu, avrc_rsp.get_items.status, avrc_rsp.get_items.opcode); } /* Reset values for current pdu. */ @@ -2350,8 +2232,7 @@ static bt_status_t get_folder_items_list_rsp(const RawAddress& bd_addr, * BT_STATUS_SUCCESS - always if RC is connected * **************************************************************************/ -static bt_status_t set_addressed_player_rsp(const RawAddress& bd_addr, - btrc_status_t rsp_status) { +static bt_status_t set_addressed_player_rsp(const RawAddress& bd_addr, btrc_status_t rsp_status) { tAVRC_RESPONSE avrc_rsp; btif_rc_device_cb_t* p_dev = btif_rc_get_device_by_bda(bd_addr); @@ -2365,8 +2246,7 @@ static bt_status_t set_addressed_player_rsp(const RawAddress& bd_addr, /* Send the response. */ send_metamsg_rsp(p_dev, IDX_SET_ADDR_PLAYER_RSP, p_dev->rc_pdu_info[IDX_SET_ADDR_PLAYER_RSP].label, - p_dev->rc_pdu_info[IDX_SET_ADDR_PLAYER_RSP].ctype, - &avrc_rsp); + p_dev->rc_pdu_info[IDX_SET_ADDR_PLAYER_RSP].ctype, &avrc_rsp); return BT_STATUS_SUCCESS; } @@ -2382,18 +2262,15 @@ static bt_status_t set_addressed_player_rsp(const RawAddress& bd_addr, * * Returns bt_status_t * BT_STATUS_NOT_READY - when RC is not connected. - * BT_STATUS_SUCCESS - if RC is connected and reponse + * BT_STATUS_SUCCESS - if RC is connected and response * sent successfully * BT_STATUS_UNHANDLED - when rsp is not pending for * set_browsed_player PDU * **************************************************************************/ -static bt_status_t set_browsed_player_rsp(const RawAddress& bd_addr, - btrc_status_t rsp_status, - uint32_t num_items, - uint16_t charset_id, - uint8_t folder_depth, - btrc_br_folder_name_t* p_folders) { +static bt_status_t set_browsed_player_rsp(const RawAddress& bd_addr, btrc_status_t rsp_status, + uint32_t num_items, uint16_t charset_id, + uint8_t folder_depth, btrc_br_folder_name_t* p_folders) { tAVRC_RESPONSE avrc_rsp; tAVRC_NAME item; BT_HDR* p_msg = NULL; @@ -2412,8 +2289,8 @@ static bt_status_t set_browsed_player_rsp(const RawAddress& bd_addr, avrc_rsp.br_player.pdu = AVRC_PDU_SET_BROWSED_PLAYER; avrc_rsp.br_player.opcode = opcode_from_pdu(AVRC_PDU_SET_BROWSED_PLAYER); - log::verbose("rsp_status: 0x{:02X} avrc_rsp.br_player.status: 0x{:02X}", - rsp_status, avrc_rsp.br_player.status); + log::verbose("rsp_status: 0x{:02X} avrc_rsp.br_player.status: 0x{:02X}", rsp_status, + avrc_rsp.br_player.status); /* check if rsp to previous cmd was completed */ if (!p_dev->rc_pdu_info[IDX_SET_BROWSED_PLAYER_RSP].is_rsp_pending) { @@ -2427,8 +2304,7 @@ static bt_status_t set_browsed_player_rsp(const RawAddress& bd_addr, avrc_rsp.br_player.folder_depth = folder_depth; avrc_rsp.br_player.p_folders = (tAVRC_NAME*)p_folders; - log::verbose("folder_depth: 0x{:02X} num_items: {}", folder_depth, - num_items); + log::verbose("folder_depth: 0x{:02X} num_items: {}", folder_depth, num_items); if (folder_depth > 0) { /* Iteratively build response for all folders across folder depth upto @@ -2445,12 +2321,14 @@ static bt_status_t set_browsed_player_rsp(const RawAddress& bd_addr, if (AVRC_STS_NO_ERROR != status) { log::warn("Build rsp status: {}", status); /* if the build fails, it is likely that we ran out of buffer. so if - * we have - * some items to send, reset this error to no error for sending what we - * have */ - if (item_cnt > 0) status = AVRC_STS_NO_ERROR; + * we have + * some items to send, reset this error to no error for sending what we + * have */ + if (item_cnt > 0) { + status = AVRC_STS_NO_ERROR; + } - /* Error occured in build response so break the loop */ + /* Error occurred in build response so break the loop */ break; } } @@ -2463,9 +2341,8 @@ static bt_status_t set_browsed_player_rsp(const RawAddress& bd_addr, avrc_rsp.br_player.status = status; } else /* error received from above layer */ { - log::warn( - "Error in parsing the received setbrowsed command. status: 0x{:02x}", - avrc_rsp.br_player.status); + log::warn("Error in parsing the received setbrowsed command. status: 0x{:02x}", + avrc_rsp.br_player.status); status = avrc_rsp.br_player.status; } @@ -2473,16 +2350,13 @@ static bt_status_t set_browsed_player_rsp(const RawAddress& bd_addr, if (status == AVRC_STS_NO_ERROR) { code = p_dev->rc_pdu_info[IDX_SET_BROWSED_PLAYER_RSP].ctype; ctype = get_rsp_type_code(avrc_rsp.br_player.status, code); - BTA_AvMetaRsp(p_dev->rc_handle, - p_dev->rc_pdu_info[IDX_SET_BROWSED_PLAYER_RSP].label, ctype, + BTA_AvMetaRsp(p_dev->rc_handle, p_dev->rc_pdu_info[IDX_SET_BROWSED_PLAYER_RSP].label, ctype, p_msg); - } else /* Error occured, send reject response */ - { - log::error("Error status: 0x{:02X}. Sending reject rsp", - avrc_rsp.br_player.status); - send_reject_response( - p_dev->rc_handle, p_dev->rc_pdu_info[IDX_SET_BROWSED_PLAYER_RSP].label, - avrc_rsp.pdu, avrc_rsp.br_player.status, avrc_rsp.get_items.opcode); + } else { + /* Error occurred, send reject response */ + log::error("Error status: 0x{:02X}. Sending reject rsp", avrc_rsp.br_player.status); + send_reject_response(p_dev->rc_handle, p_dev->rc_pdu_info[IDX_SET_BROWSED_PLAYER_RSP].label, + avrc_rsp.pdu, avrc_rsp.br_player.status, avrc_rsp.get_items.opcode); } /* Reset values for set_browsed_player pdu.*/ @@ -2505,8 +2379,7 @@ static bt_status_t set_browsed_player_rsp(const RawAddress& bd_addr, * BT_STATUS_SUCCESS - always if RC is connected * **************************************************************************/ -static bt_status_t change_path_rsp(const RawAddress& bd_addr, - btrc_status_t rsp_status, +static bt_status_t change_path_rsp(const RawAddress& bd_addr, btrc_status_t rsp_status, uint32_t num_items) { tAVRC_RESPONSE avrc_rsp; btif_rc_device_cb_t* p_dev = btif_rc_get_device_by_bda(bd_addr); @@ -2520,8 +2393,7 @@ static bt_status_t change_path_rsp(const RawAddress& bd_addr, avrc_rsp.chg_path.status = status_code_map[rsp_status]; /* Send the response. */ - send_metamsg_rsp(p_dev, IDX_CHG_PATH_RSP, - p_dev->rc_pdu_info[IDX_CHG_PATH_RSP].label, + send_metamsg_rsp(p_dev, IDX_CHG_PATH_RSP, p_dev->rc_pdu_info[IDX_CHG_PATH_RSP].label, p_dev->rc_pdu_info[IDX_CHG_PATH_RSP].ctype, &avrc_rsp); return BT_STATUS_SUCCESS; @@ -2538,9 +2410,8 @@ static bt_status_t change_path_rsp(const RawAddress& bd_addr, * BT_STATUS_SUCCESS - always if RC is connected * **************************************************************************/ -static bt_status_t search_rsp(const RawAddress& bd_addr, - btrc_status_t rsp_status, uint32_t uid_counter, - uint32_t num_items) { +static bt_status_t search_rsp(const RawAddress& bd_addr, btrc_status_t rsp_status, + uint32_t uid_counter, uint32_t num_items) { tAVRC_RESPONSE avrc_rsp; btif_rc_device_cb_t* p_dev = btif_rc_get_device_by_bda(bd_addr); @@ -2554,8 +2425,7 @@ static bt_status_t search_rsp(const RawAddress& bd_addr, avrc_rsp.search.status = status_code_map[rsp_status]; /* Send the response. */ - send_metamsg_rsp(p_dev, IDX_SEARCH_RSP, - p_dev->rc_pdu_info[IDX_SEARCH_RSP].label, + send_metamsg_rsp(p_dev, IDX_SEARCH_RSP, p_dev->rc_pdu_info[IDX_SEARCH_RSP].label, p_dev->rc_pdu_info[IDX_SEARCH_RSP].ctype, &avrc_rsp); return BT_STATUS_SUCCESS; @@ -2572,9 +2442,8 @@ static bt_status_t search_rsp(const RawAddress& bd_addr, * BT_STATUS_SUCCESS - always if RC is connected * **************************************************************************/ -static bt_status_t get_item_attr_rsp(const RawAddress& bd_addr, - btrc_status_t rsp_status, uint8_t num_attr, - btrc_element_attr_val_t* p_attrs) { +static bt_status_t get_item_attr_rsp(const RawAddress& bd_addr, btrc_status_t rsp_status, + uint8_t num_attr, btrc_element_attr_val_t* p_attrs) { tAVRC_RESPONSE avrc_rsp; tAVRC_ATTR_ENTRY item_attrs[BTRC_MAX_ELEM_ATTR_SIZE]; btif_rc_device_cb_t* p_dev = btif_rc_get_device_by_bda(bd_addr); @@ -2595,8 +2464,7 @@ static bt_status_t get_item_attr_rsp(const RawAddress& bd_addr, avrc_rsp.get_attrs.opcode = opcode_from_pdu(AVRC_PDU_GET_ITEM_ATTRIBUTES); /* Send the response. */ - send_metamsg_rsp(p_dev, IDX_GET_ITEM_ATTR_RSP, - p_dev->rc_pdu_info[IDX_GET_ITEM_ATTR_RSP].label, + send_metamsg_rsp(p_dev, IDX_GET_ITEM_ATTR_RSP, p_dev->rc_pdu_info[IDX_GET_ITEM_ATTR_RSP].label, p_dev->rc_pdu_info[IDX_GET_ITEM_ATTR_RSP].ctype, &avrc_rsp); return BT_STATUS_SUCCESS; @@ -2614,8 +2482,7 @@ static bt_status_t get_item_attr_rsp(const RawAddress& bd_addr, * BT_STATUS_SUCCESS - always if RC is connected * **************************************************************************/ -static bt_status_t add_to_now_playing_rsp(const RawAddress& bd_addr, - btrc_status_t rsp_status) { +static bt_status_t add_to_now_playing_rsp(const RawAddress& bd_addr, btrc_status_t rsp_status) { tAVRC_RESPONSE avrc_rsp; btif_rc_device_cb_t* p_dev = btif_rc_get_device_by_bda(bd_addr); @@ -2629,8 +2496,7 @@ static bt_status_t add_to_now_playing_rsp(const RawAddress& bd_addr, /* Send the response. */ send_metamsg_rsp(p_dev, IDX_ADD_TO_NOW_PLAYING_RSP, p_dev->rc_pdu_info[IDX_ADD_TO_NOW_PLAYING_RSP].label, - p_dev->rc_pdu_info[IDX_ADD_TO_NOW_PLAYING_RSP].ctype, - &avrc_rsp); + p_dev->rc_pdu_info[IDX_ADD_TO_NOW_PLAYING_RSP].ctype, &avrc_rsp); return BT_STATUS_SUCCESS; } @@ -2646,8 +2512,7 @@ static bt_status_t add_to_now_playing_rsp(const RawAddress& bd_addr, * BT_STATUS_SUCCESS - always if RC is connected * **************************************************************************/ -static bt_status_t play_item_rsp(const RawAddress& bd_addr, - btrc_status_t rsp_status) { +static bt_status_t play_item_rsp(const RawAddress& bd_addr, btrc_status_t rsp_status) { tAVRC_RESPONSE avrc_rsp; btif_rc_device_cb_t* p_dev = btif_rc_get_device_by_bda(bd_addr); @@ -2659,8 +2524,7 @@ static bt_status_t play_item_rsp(const RawAddress& bd_addr, avrc_rsp.play_item.status = status_code_map[rsp_status]; /* Send the response. */ - send_metamsg_rsp(p_dev, IDX_PLAY_ITEM_RSP, - p_dev->rc_pdu_info[IDX_PLAY_ITEM_RSP].label, + send_metamsg_rsp(p_dev, IDX_PLAY_ITEM_RSP, p_dev->rc_pdu_info[IDX_PLAY_ITEM_RSP].label, p_dev->rc_pdu_info[IDX_PLAY_ITEM_RSP].ctype, &avrc_rsp); return BT_STATUS_SUCCESS; @@ -2678,10 +2542,8 @@ static bt_status_t play_item_rsp(const RawAddress& bd_addr, * BT_STATUS_SUCCESS - always if RC is connected * **************************************************************************/ -static bt_status_t get_total_num_of_items_rsp(const RawAddress& bd_addr, - btrc_status_t rsp_status, - uint32_t uid_counter, - uint32_t num_items) { +static bt_status_t get_total_num_of_items_rsp(const RawAddress& bd_addr, btrc_status_t rsp_status, + uint32_t uid_counter, uint32_t num_items) { tAVRC_RESPONSE avrc_rsp; btif_rc_device_cb_t* p_dev = btif_rc_get_device_by_bda(bd_addr); @@ -2689,8 +2551,7 @@ static bt_status_t get_total_num_of_items_rsp(const RawAddress& bd_addr, CHECK_RC_CONNECTED(p_dev); avrc_rsp.get_num_of_items.pdu = AVRC_PDU_GET_TOTAL_NUM_OF_ITEMS; - avrc_rsp.get_num_of_items.opcode = - opcode_from_pdu(AVRC_PDU_GET_TOTAL_NUM_OF_ITEMS); + avrc_rsp.get_num_of_items.opcode = opcode_from_pdu(AVRC_PDU_GET_TOTAL_NUM_OF_ITEMS); avrc_rsp.get_num_of_items.num_items = num_items; avrc_rsp.get_num_of_items.uid_counter = uid_counter; avrc_rsp.get_num_of_items.status = status_code_map[rsp_status]; @@ -2698,8 +2559,7 @@ static bt_status_t get_total_num_of_items_rsp(const RawAddress& bd_addr, /* Send the response. */ send_metamsg_rsp(p_dev, IDX_GET_TOTAL_NUM_OF_ITEMS_RSP, p_dev->rc_pdu_info[IDX_GET_TOTAL_NUM_OF_ITEMS_RSP].label, - p_dev->rc_pdu_info[IDX_GET_TOTAL_NUM_OF_ITEMS_RSP].ctype, - &avrc_rsp); + p_dev->rc_pdu_info[IDX_GET_TOTAL_NUM_OF_ITEMS_RSP].ctype, &avrc_rsp); return BT_STATUS_SUCCESS; } @@ -2713,7 +2573,7 @@ static bt_status_t get_total_num_of_items_rsp(const RawAddress& bd_addr, * This can be enhanced to support Relative Volume (AVRCP 1.0). * With RelateVolume, we will send VOLUME_UP/VOLUME_DOWN * as opposed to absolute volume level - * volume: Should be in the range 0-127. bit7 is reseved and cannot be set + * volume: Should be in the range 0-127. bit7 is reserved and cannot be set * * Returns bt_status_t * @@ -2724,7 +2584,9 @@ static bt_status_t set_volume(uint8_t volume) { for (int idx = 0; idx < BTIF_RC_NUM_CONN; idx++) { btif_rc_device_cb_t* p_dev = &btif_rc_cb.rc_multi_cb[idx]; - if (!p_dev->rc_connected) continue; + if (!p_dev->rc_connected) { + continue; + } if (p_dev->rc_volume == volume) { status = BT_STATUS_DONE; @@ -2732,9 +2594,7 @@ static bt_status_t set_volume(uint8_t volume) { continue; } - if ((p_dev->rc_volume == volume) || - p_dev->rc_state != - BTRC_CONNECTION_STATE_CONNECTED) { + if ((p_dev->rc_volume == volume) || p_dev->rc_state != BTRC_CONNECTION_STATE_CONNECTED) { continue; } @@ -2743,8 +2603,9 @@ static bt_status_t set_volume(uint8_t volume) { continue; } - if (!(p_dev->rc_features & BTA_AV_FEAT_ADV_CTRL)) + if (!(p_dev->rc_features & BTA_AV_FEAT_ADV_CTRL)) { continue; + } log::verbose("Peer supports absolute volume. newVolume: {}", volume); @@ -2755,25 +2616,23 @@ static bt_status_t set_volume(uint8_t volume) { BT_HDR* p_msg = NULL; if (AVRC_BldCommand(&avrc_cmd, &p_msg) != AVRC_STS_NO_ERROR) { - log::error("failed to build absolute volume command. status: 0x{:02x}", - status); + log::error("failed to build absolute volume command. status: 0x{:02x}", status); status = BT_STATUS_FAIL; continue; } rc_transaction_context_t context = { - .rc_addr = p_dev->rc_addr, - .label = MAX_LABEL, - .opcode = AVRC_OP_VENDOR, - .command = { - .vendor = {AVRC_PDU_SET_ABSOLUTE_VOLUME, AVRC_EVT_INVALID}}}; + .rc_addr = p_dev->rc_addr, + .label = MAX_LABEL, + .opcode = AVRC_OP_VENDOR, + .command = {.vendor = {AVRC_PDU_SET_ABSOLUTE_VOLUME, AVRC_EVT_INVALID}}}; rc_transaction_t* p_transaction = NULL; bt_status_t tran_status = get_transaction(p_dev, context, &p_transaction); if (tran_status != BT_STATUS_SUCCESS || !p_transaction) { osi_free_and_reset((void**)&p_msg); - log::error("failed to get label, pdu_id={}, status=0x{:02x}", - dump_rc_pdu(avrc_cmd.pdu), tran_status); + log::error("failed to get label, pdu_id={}, status=0x{:02x}", dump_rc_pdu(avrc_cmd.pdu), + tran_status); status = BT_STATUS_FAIL; continue; } @@ -2808,11 +2667,10 @@ static void register_volumechange(btif_rc_device_cb_t* p_dev) { rc_transaction_t* p_transaction = NULL; rc_transaction_context_t context = { - .rc_addr = p_dev->rc_addr, - .label = MAX_LABEL, - .opcode = AVRC_OP_VENDOR, - .command = { - .vendor = {AVRC_PDU_REGISTER_NOTIFICATION, AVRC_EVT_VOLUME_CHANGE}}}; + .rc_addr = p_dev->rc_addr, + .label = MAX_LABEL, + .opcode = AVRC_OP_VENDOR, + .command = {.vendor = {AVRC_PDU_REGISTER_NOTIFICATION, AVRC_EVT_VOLUME_CHANGE}}}; bt_status_t status = BT_STATUS_NOT_READY; if (MAX_LABEL == p_dev->rc_vol_label) { status = get_transaction(p_dev, context, &p_transaction); @@ -2842,8 +2700,7 @@ static void register_volumechange(btif_rc_device_cb_t* p_dev) { BldResp = AVRC_BldCommand(&avrc_cmd, &p_msg); if (AVRC_STS_NO_ERROR == BldResp && p_msg) { - BTA_AvMetaCmd(p_dev->rc_handle, p_transaction->label, AVRC_CMD_NOTIF, - p_msg); + BTA_AvMetaCmd(p_dev->rc_handle, p_transaction->label, AVRC_CMD_NOTIF, p_msg); log::verbose("BTA_AvMetaCmd called"); } else { log::error("failed to build command: {}", BldResp); @@ -2859,8 +2716,7 @@ static void register_volumechange(btif_rc_device_cb_t* p_dev) { * Returns void * **************************************************************************/ -static void handle_rc_metamsg_rsp(tBTA_AV_META_MSG* pmeta_msg, - btif_rc_device_cb_t* p_dev) { +static void handle_rc_metamsg_rsp(tBTA_AV_META_MSG* pmeta_msg, btif_rc_device_cb_t* p_dev) { tAVRC_RESPONSE avrc_response = {0}; uint8_t scratch_buf[512] = {0}; tAVRC_STS status = BT_STATUS_UNSUPPORTED; @@ -2868,16 +2724,13 @@ static void handle_rc_metamsg_rsp(tBTA_AV_META_MSG* pmeta_msg, log::verbose(""); if (AVRC_OP_VENDOR == pmeta_msg->p_msg->hdr.opcode && - (AVRC_RSP_CHANGED == pmeta_msg->code || - AVRC_RSP_INTERIM == pmeta_msg->code || + (AVRC_RSP_CHANGED == pmeta_msg->code || AVRC_RSP_INTERIM == pmeta_msg->code || AVRC_RSP_ACCEPT == pmeta_msg->code || AVRC_RSP_REJ == pmeta_msg->code || AVRC_RSP_NOT_IMPL == pmeta_msg->code)) { - status = AVRC_ParsResponse(pmeta_msg->p_msg, &avrc_response, scratch_buf, - sizeof(scratch_buf)); - log::verbose( - "code:{}, event ID: {}, PDU: {:x}, parsing status: {}, label: {}", - pmeta_msg->code, avrc_response.reg_notif.event_id, - avrc_response.reg_notif.pdu, status, pmeta_msg->label); + status = AVRC_ParsResponse(pmeta_msg->p_msg, &avrc_response, scratch_buf, sizeof(scratch_buf)); + log::verbose("code:{}, event ID: {}, PDU: {:x}, parsing status: {}, label: {}", pmeta_msg->code, + avrc_response.reg_notif.event_id, avrc_response.reg_notif.pdu, status, + pmeta_msg->label); if (status != AVRC_STS_NO_ERROR) { if (AVRC_PDU_REGISTER_NOTIFICATION == avrc_response.rsp.pdu && @@ -2896,16 +2749,14 @@ static void handle_rc_metamsg_rsp(tBTA_AV_META_MSG* pmeta_msg, p_dev->rc_vol_label != pmeta_msg->label) { // Just discard the message, if the device sends back with an incorrect // label - log::verbose( - "Discarding register notification in rsp.code: {} and label: {}", - pmeta_msg->code, pmeta_msg->label); + log::verbose("Discarding register notification in rsp.code: {} and label: {}", + pmeta_msg->code, pmeta_msg->label); return; } if (AVRC_PDU_REGISTER_NOTIFICATION == avrc_response.rsp.pdu && AVRC_EVT_VOLUME_CHANGE == avrc_response.reg_notif.event_id && - (AVRC_RSP_REJ == pmeta_msg->code || - AVRC_RSP_NOT_IMPL == pmeta_msg->code)) { + (AVRC_RSP_REJ == pmeta_msg->code || AVRC_RSP_NOT_IMPL == pmeta_msg->code)) { log::verbose("remove AbsoluteVolume feature flag."); p_dev->rc_features &= ~BTA_AV_FEAT_ADV_CTRL; handle_rc_features(p_dev); @@ -2913,9 +2764,9 @@ static void handle_rc_metamsg_rsp(tBTA_AV_META_MSG* pmeta_msg, } } else { log::verbose( - "Received vendor dependent in adv ctrl rsp. code: {} len: {}. Not " - "processing it.", - pmeta_msg->code, pmeta_msg->len); + "Received vendor dependent in adv ctrl rsp. code: {} len: {}. Not " + "processing it.", + pmeta_msg->code, pmeta_msg->len); return; } @@ -2930,10 +2781,9 @@ static void handle_rc_metamsg_rsp(tBTA_AV_META_MSG* pmeta_msg, release_transaction(p_dev, pmeta_msg->label); } - log::verbose("Passing received metamsg response to app. pdu: {}", - dump_rc_pdu(avrc_response.pdu)); - btif_rc_upstreams_rsp_evt((uint16_t)avrc_response.rsp.pdu, &avrc_response, - pmeta_msg->code, pmeta_msg->label, p_dev); + log::verbose("Passing received metamsg response to app. pdu: {}", dump_rc_pdu(avrc_response.pdu)); + btif_rc_upstreams_rsp_evt((uint16_t)avrc_response.rsp.pdu, &avrc_response, pmeta_msg->code, + pmeta_msg->label, p_dev); } /*************************************************************************** @@ -2968,8 +2818,7 @@ bool iterate_supported_event_list_for_interim_rsp(void* data, void* cb_data) { * Returns None * **************************************************************************/ -static void rc_notification_interim_timeout(btif_rc_device_cb_t* p_dev, - uint8_t event_id) { +static void rc_notification_interim_timeout(btif_rc_device_cb_t* p_dev, uint8_t event_id) { /* Device disconnections clear the event list but can't free the timer */ if (p_dev == NULL || p_dev->rc_supported_event_list == NULL) { log::warn("timeout for null device or event list"); @@ -2979,8 +2828,7 @@ static void rc_notification_interim_timeout(btif_rc_device_cb_t* p_dev, // Remove the timed out event from the supported events list list_node_t* node = list_begin(p_dev->rc_supported_event_list); while (node != NULL) { - btif_rc_supported_event_t* p_event = - (btif_rc_supported_event_t*)list_node(node); + btif_rc_supported_event_t* p_event = (btif_rc_supported_event_t*)list_node(node); if (p_event != nullptr && p_event->event_id == event_id) { list_remove(p_dev->rc_supported_event_list, p_event); break; @@ -3024,8 +2872,7 @@ static void register_for_event_notification(btif_rc_supported_event_t* p_event, if (p_event->event_id == AVRC_EVT_PLAY_POS_CHANGED) { interval_in_seconds = 2; } - bt_status_t status = - register_notification_cmd(p_event->event_id, interval_in_seconds, p_dev); + bt_status_t status = register_notification_cmd(p_event->event_id, interval_in_seconds, p_dev); if (status != BT_STATUS_SUCCESS) { log::error("failed, status={}", status); return; @@ -3047,15 +2894,13 @@ static void register_for_event_notification(btif_rc_supported_event_t* p_event, * otherwise BT_STATUS_FAIL * **************************************************************************/ -static bt_status_t build_and_send_vendor_cmd(tAVRC_COMMAND* avrc_cmd, - tBTA_AV_CODE cmd_code, +static bt_status_t build_and_send_vendor_cmd(tAVRC_COMMAND* avrc_cmd, tBTA_AV_CODE cmd_code, btif_rc_device_cb_t* p_dev) { rc_transaction_t* p_transaction = NULL; - rc_transaction_context_t context = { - .rc_addr = p_dev->rc_addr, - .label = MAX_LABEL, - .opcode = AVRC_OP_VENDOR, - .command = {.vendor = {avrc_cmd->pdu, AVRC_EVT_INVALID}}}; + rc_transaction_context_t context = {.rc_addr = p_dev->rc_addr, + .label = MAX_LABEL, + .opcode = AVRC_OP_VENDOR, + .command = {.vendor = {avrc_cmd->pdu, AVRC_EVT_INVALID}}}; // Set the event ID in the context if this is a notification registration if (avrc_cmd->pdu == AVRC_PDU_REGISTER_NOTIFICATION) { @@ -3064,8 +2909,8 @@ static bt_status_t build_and_send_vendor_cmd(tAVRC_COMMAND* avrc_cmd, bt_status_t tran_status = get_transaction(p_dev, context, &p_transaction); if (BT_STATUS_SUCCESS != tran_status || p_transaction == NULL) { - log::error("failed to get label, pdu_id={}, status=0x{:02x}", - dump_rc_pdu(avrc_cmd->pdu), tran_status); + log::error("failed to get label, pdu_id={}, status=0x{:02x}", dump_rc_pdu(avrc_cmd->pdu), + tran_status); return BT_STATUS_FAIL; } @@ -3073,10 +2918,9 @@ static bt_status_t build_and_send_vendor_cmd(tAVRC_COMMAND* avrc_cmd, tAVRC_STS status = AVRC_BldCommand(avrc_cmd, &p_msg); if (status == AVRC_STS_NO_ERROR && p_msg != NULL) { uint8_t* data_start = (uint8_t*)(p_msg + 1) + p_msg->offset; - log::verbose("{} msgreq being sent out with label: {}", - dump_rc_pdu(avrc_cmd->pdu), p_transaction->label); - BTA_AvVendorCmd(p_dev->rc_handle, p_transaction->label, cmd_code, - data_start, p_msg->len); + log::verbose("{} msgreq being sent out with label: {}", dump_rc_pdu(avrc_cmd->pdu), + p_transaction->label); + BTA_AvVendorCmd(p_dev->rc_handle, p_transaction->label, cmd_code, data_start, p_msg->len); status = BT_STATUS_SUCCESS; start_transaction_timer(p_dev, p_transaction->label, BTIF_RC_TIMEOUT_MS); } else { @@ -3101,7 +2945,7 @@ static bt_status_t build_and_send_vendor_cmd(tAVRC_COMMAND* avrc_cmd, * **************************************************************************/ static bt_status_t build_and_send_browsing_cmd(tAVRC_COMMAND* avrc_cmd, - btif_rc_device_cb_t* p_dev) { + btif_rc_device_cb_t* p_dev) { rc_transaction_t* p_transaction = NULL; rc_transaction_context_t context = {.rc_addr = p_dev->rc_addr, .label = MAX_LABEL, @@ -3110,8 +2954,8 @@ static bt_status_t build_and_send_browsing_cmd(tAVRC_COMMAND* avrc_cmd, bt_status_t tran_status = get_transaction(p_dev, context, &p_transaction); if (tran_status != BT_STATUS_SUCCESS || p_transaction == NULL) { - log::error("failed to get label, pdu_id={}, status=0x{:02x}", - dump_rc_pdu(avrc_cmd->pdu), tran_status); + log::error("failed to get label, pdu_id={}, status=0x{:02x}", dump_rc_pdu(avrc_cmd->pdu), + tran_status); return BT_STATUS_FAIL; } @@ -3123,8 +2967,7 @@ static bt_status_t build_and_send_browsing_cmd(tAVRC_COMMAND* avrc_cmd, return BT_STATUS_FAIL; } - log::verbose("Send pdu_id={}, label={}", dump_rc_pdu(avrc_cmd->pdu), - p_transaction->label); + log::verbose("Send pdu_id={}, label={}", dump_rc_pdu(avrc_cmd->pdu), p_transaction->label); BTA_AvMetaCmd(p_dev->rc_handle, p_transaction->label, AVRC_CMD_CTRL, p_msg); start_transaction_timer(p_dev, p_transaction->label, BTIF_RC_TIMEOUT_MS); return BT_STATUS_SUCCESS; @@ -3140,11 +2983,9 @@ static bt_status_t build_and_send_browsing_cmd(tAVRC_COMMAND* avrc_cmd, * Returns None * **************************************************************************/ -static void handle_get_capability_response(tBTA_AV_META_MSG* pmeta_msg, - tAVRC_GET_CAPS_RSP* p_rsp) { +static void handle_get_capability_response(tBTA_AV_META_MSG* pmeta_msg, tAVRC_GET_CAPS_RSP* p_rsp) { int xx = 0; - btif_rc_device_cb_t* p_dev = - btif_rc_get_device_by_handle(pmeta_msg->rc_handle); + btif_rc_device_cb_t* p_dev = btif_rc_get_device_by_handle(pmeta_msg->rc_handle); /* Todo: Do we need to retry on command timeout */ if (p_rsp->status != AVRC_STS_NO_ERROR) { @@ -3167,8 +3008,7 @@ static void handle_get_capability_response(tBTA_AV_META_MSG* pmeta_msg, (p_rsp->param.event_id[xx] == AVRC_EVT_ADDR_PLAYER_CHANGE) || (p_rsp->param.event_id[xx] == AVRC_EVT_UIDS_CHANGE) || (p_rsp->param.event_id[xx] == AVRC_EVT_AVAL_PLAYERS_CHANGE)) { - p_event = (btif_rc_supported_event_t*)osi_malloc( - sizeof(btif_rc_supported_event_t)); + p_event = (btif_rc_supported_event_t*)osi_malloc(sizeof(btif_rc_supported_event_t)); p_event->event_id = p_rsp->param.event_id[xx]; p_event->status = eNOT_REGISTERED; list_append(p_dev->rc_supported_event_list, p_event); @@ -3183,8 +3023,7 @@ static void handle_get_capability_response(tBTA_AV_META_MSG* pmeta_msg, return; } - p_event = - (btif_rc_supported_event_t*)list_front(p_dev->rc_supported_event_list); + p_event = (btif_rc_supported_event_t*)list_front(p_dev->rc_supported_event_list); if (p_event != NULL) { register_for_event_notification(p_event, p_dev); } @@ -3226,20 +3065,16 @@ bool rc_is_track_id_valid(tAVRC_UID uid) { * Returns None * **************************************************************************/ -static void handle_notification_response(tBTA_AV_META_MSG* pmeta_msg, - tAVRC_REG_NOTIF_RSP* p_rsp) { - btif_rc_device_cb_t* p_dev = - btif_rc_get_device_by_handle(pmeta_msg->rc_handle); +static void handle_notification_response(tBTA_AV_META_MSG* pmeta_msg, tAVRC_REG_NOTIF_RSP* p_rsp) { + btif_rc_device_cb_t* p_dev = btif_rc_get_device_by_handle(pmeta_msg->rc_handle); if (p_dev == NULL) { log::error("p_dev NULL"); return; } - if (btif_av_src_sink_coexist_enabled() && - p_rsp->event_id == AVRC_EVT_VOLUME_CHANGE) { - log::error( - "legacy TG don't handle absolute volume change. leave it to new avrcp"); + if (btif_av_src_sink_coexist_enabled() && p_rsp->event_id == AVRC_EVT_VOLUME_CHANGE) { + log::error("legacy TG don't handle absolute volume change. leave it to new avrcp"); return; } @@ -3254,9 +3089,9 @@ static void handle_notification_response(tBTA_AV_META_MSG* pmeta_msg, switch (p_rsp->event_id) { case AVRC_EVT_PLAY_STATUS_CHANGE: get_play_status_cmd(p_dev); - do_in_jni_thread(base::BindOnce( - bt_rc_ctrl_callbacks->play_status_changed_cb, p_dev->rc_addr, - (btrc_play_status_t)p_rsp->param.play_status)); + do_in_jni_thread(base::BindOnce(bt_rc_ctrl_callbacks->play_status_changed_cb, + p_dev->rc_addr, + (btrc_play_status_t)p_rsp->param.play_status)); break; case AVRC_EVT_TRACK_CHANGE: @@ -3266,8 +3101,7 @@ static void handle_notification_response(tBTA_AV_META_MSG* pmeta_msg, uint8_t* p_data = p_rsp->param.track; BE_STREAM_TO_UINT64(p_dev->rc_playing_uid, p_data); get_play_status_cmd(p_dev); - get_metadata_attribute_cmd(attr_list_size, attr_list, - p_dev); + get_metadata_attribute_cmd(attr_list_size, attr_list, p_dev); } break; @@ -3275,27 +3109,24 @@ static void handle_notification_response(tBTA_AV_META_MSG* pmeta_msg, break; case AVRC_EVT_NOW_PLAYING_CHANGE: - do_in_jni_thread(base::BindOnce( - bt_rc_ctrl_callbacks->now_playing_contents_changed_cb, - p_dev->rc_addr)); + do_in_jni_thread(base::BindOnce(bt_rc_ctrl_callbacks->now_playing_contents_changed_cb, + p_dev->rc_addr)); break; case AVRC_EVT_AVAL_PLAYERS_CHANGE: log::verbose("AVRC_EVT_AVAL_PLAYERS_CHANGE"); - do_in_jni_thread(base::BindOnce( - bt_rc_ctrl_callbacks->available_player_changed_cb, p_dev->rc_addr)); + do_in_jni_thread( + base::BindOnce(bt_rc_ctrl_callbacks->available_player_changed_cb, p_dev->rc_addr)); break; case AVRC_EVT_ADDR_PLAYER_CHANGE: - do_in_jni_thread( - base::BindOnce(bt_rc_ctrl_callbacks->addressed_player_changed_cb, - p_dev->rc_addr, p_rsp->param.addr_player.player_id)); + do_in_jni_thread(base::BindOnce(bt_rc_ctrl_callbacks->addressed_player_changed_cb, + p_dev->rc_addr, p_rsp->param.addr_player.player_id)); break; case AVRC_EVT_PLAY_POS_CHANGED: - do_in_jni_thread( - base::BindOnce(bt_rc_ctrl_callbacks->play_position_changed_cb, - p_dev->rc_addr, 0, p_rsp->param.play_pos)); + do_in_jni_thread(base::BindOnce(bt_rc_ctrl_callbacks->play_position_changed_cb, + p_dev->rc_addr, 0, p_rsp->param.play_pos)); break; case AVRC_EVT_UIDS_CHANGE: @@ -3310,8 +3141,7 @@ static void handle_notification_response(tBTA_AV_META_MSG* pmeta_msg, return; } - list_foreach(p_dev->rc_supported_event_list, - iterate_supported_event_list_for_interim_rsp, + list_foreach(p_dev->rc_supported_event_list, iterate_supported_event_list_for_interim_rsp, &p_rsp->event_id); node = list_begin(p_dev->rc_supported_event_list); @@ -3361,9 +3191,9 @@ static void handle_notification_response(tBTA_AV_META_MSG* pmeta_msg, /* Start timer to get play status periodically * if the play state is playing. */ - do_in_jni_thread(base::BindOnce( - bt_rc_ctrl_callbacks->play_status_changed_cb, p_dev->rc_addr, - (btrc_play_status_t)p_rsp->param.play_status)); + do_in_jni_thread(base::BindOnce(bt_rc_ctrl_callbacks->play_status_changed_cb, + p_dev->rc_addr, + (btrc_play_status_t)p_rsp->param.play_status)); break; @@ -3381,12 +3211,10 @@ static void handle_notification_response(tBTA_AV_META_MSG* pmeta_msg, app_settings.num_attr = p_rsp->param.player_setting.num_attr; for (xx = 0; xx < app_settings.num_attr; xx++) { app_settings.attr_ids[xx] = p_rsp->param.player_setting.attr_id[xx]; - app_settings.attr_values[xx] = - p_rsp->param.player_setting.attr_value[xx]; + app_settings.attr_values[xx] = p_rsp->param.player_setting.attr_value[xx]; } - do_in_jni_thread(base::BindOnce( - bt_rc_ctrl_callbacks->playerapplicationsetting_changed_cb, - p_dev->rc_addr, app_settings)); + do_in_jni_thread(base::BindOnce(bt_rc_ctrl_callbacks->playerapplicationsetting_changed_cb, + p_dev->rc_addr, app_settings)); } break; case AVRC_EVT_NOW_PLAYING_CHANGE: @@ -3425,15 +3253,12 @@ static void handle_notification_response(tBTA_AV_META_MSG* pmeta_msg, * Returns None * **************************************************************************/ -static void handle_app_attr_response(tBTA_AV_META_MSG* pmeta_msg, - tAVRC_LIST_APP_ATTR_RSP* p_rsp) { +static void handle_app_attr_response(tBTA_AV_META_MSG* pmeta_msg, tAVRC_LIST_APP_ATTR_RSP* p_rsp) { uint8_t xx; - btif_rc_device_cb_t* p_dev = - btif_rc_get_device_by_handle(pmeta_msg->rc_handle); + btif_rc_device_cb_t* p_dev = btif_rc_get_device_by_handle(pmeta_msg->rc_handle); if (p_dev == NULL || p_rsp->status != AVRC_STS_NO_ERROR) { - log::error("Error getting Player application settings: 0x{:2X}", - p_rsp->status); + log::error("Error getting Player application settings: 0x{:2X}", p_rsp->status); rc_ctrl_procedure_complete(p_dev); return; } @@ -3457,8 +3282,7 @@ static void handle_app_attr_response(tBTA_AV_META_MSG* pmeta_msg, p_dev->rc_app_settings.ext_attr_index = 0; p_dev->rc_app_settings.ext_val_index = 0; if (p_rsp->num_attr) { - list_player_app_setting_value_cmd(p_dev->rc_app_settings.attrs[0].attr_id, - p_dev); + list_player_app_setting_value_cmd(p_dev->rc_app_settings.attrs[0].attr_id, p_dev); } else { log::error("No Player application settings found"); } @@ -3476,13 +3300,11 @@ static void handle_app_attr_response(tBTA_AV_META_MSG* pmeta_msg, * Returns None * **************************************************************************/ -static void handle_app_val_response(tBTA_AV_META_MSG* pmeta_msg, - tAVRC_LIST_APP_VALUES_RSP* p_rsp) { +static void handle_app_val_response(tBTA_AV_META_MSG* pmeta_msg, tAVRC_LIST_APP_VALUES_RSP* p_rsp) { uint8_t xx, attr_index; uint8_t attrs[AVRC_MAX_APP_ATTR_SIZE]; btif_rc_player_app_settings_t* p_app_settings; - btif_rc_device_cb_t* p_dev = - btif_rc_get_device_by_handle(pmeta_msg->rc_handle); + btif_rc_device_cb_t* p_dev = btif_rc_get_device_by_handle(pmeta_msg->rc_handle); /* Todo: Do we need to retry on command timeout */ if (p_dev == NULL || p_rsp->status != AVRC_STS_NO_ERROR) { @@ -3501,43 +3323,39 @@ static void handle_app_val_response(tBTA_AV_META_MSG* pmeta_msg, attr_index++; p_app_settings->attr_index++; if (attr_index < p_app_settings->num_attrs) { - list_player_app_setting_value_cmd( - p_app_settings->attrs[p_app_settings->attr_index].attr_id, p_dev); + list_player_app_setting_value_cmd(p_app_settings->attrs[p_app_settings->attr_index].attr_id, + p_dev); } else if (p_app_settings->ext_attr_index < p_app_settings->num_ext_attrs) { attr_index = 0; p_app_settings->ext_attr_index = 0; - list_player_app_setting_value_cmd( - p_app_settings->ext_attrs[attr_index].attr_id, p_dev); + list_player_app_setting_value_cmd(p_app_settings->ext_attrs[attr_index].attr_id, p_dev); } else { for (xx = 0; xx < p_app_settings->num_attrs; xx++) { attrs[xx] = p_app_settings->attrs[xx].attr_id; } get_player_app_setting_cmd(p_app_settings->num_attrs, attrs, p_dev); - do_in_jni_thread(base::BindOnce( - bt_rc_ctrl_callbacks->playerapplicationsetting_cb, p_dev->rc_addr, - p_app_settings->num_attrs, p_app_settings->attrs, 0, nullptr)); + do_in_jni_thread(base::BindOnce(bt_rc_ctrl_callbacks->playerapplicationsetting_cb, + p_dev->rc_addr, p_app_settings->num_attrs, + p_app_settings->attrs, 0, nullptr)); } } else if (p_app_settings->ext_attr_index < p_app_settings->num_ext_attrs) { attr_index = p_app_settings->ext_attr_index; p_app_settings->ext_attrs[attr_index].num_val = p_rsp->num_val; for (xx = 0; xx < p_rsp->num_val; xx++) { - p_app_settings->ext_attrs[attr_index].ext_attr_val[xx].val = - p_rsp->vals[xx]; + p_app_settings->ext_attrs[attr_index].ext_attr_val[xx].val = p_rsp->vals[xx]; } attr_index++; p_app_settings->ext_attr_index++; if (attr_index < p_app_settings->num_ext_attrs) { list_player_app_setting_value_cmd( - p_app_settings->ext_attrs[p_app_settings->ext_attr_index].attr_id, - p_dev); + p_app_settings->ext_attrs[p_app_settings->ext_attr_index].attr_id, p_dev); } else { uint8_t attr[AVRC_MAX_APP_ATTR_SIZE]; for (uint8_t xx = 0; xx < p_app_settings->num_ext_attrs; xx++) { attr[xx] = p_app_settings->ext_attrs[xx].attr_id; } - get_player_app_setting_attr_text_cmd(attr, p_app_settings->num_ext_attrs, - p_dev); + get_player_app_setting_attr_text_cmd(attr, p_app_settings->num_ext_attrs, p_dev); } } } @@ -3569,7 +3387,6 @@ static void handle_app_cur_val_response(tBTA_AV_META_MSG* pmeta_msg, return; } - app_settings.num_attr = p_rsp->num_val; if (app_settings.num_attr > BTRC_MAX_APP_SETTINGS) { @@ -3581,9 +3398,8 @@ static void handle_app_cur_val_response(tBTA_AV_META_MSG* pmeta_msg, app_settings.attr_values[xx] = p_rsp->p_vals[xx].attr_val; } - do_in_jni_thread( - base::BindOnce(bt_rc_ctrl_callbacks->playerapplicationsetting_changed_cb, - p_dev->rc_addr, app_settings)); + do_in_jni_thread(base::BindOnce(bt_rc_ctrl_callbacks->playerapplicationsetting_changed_cb, + p_dev->rc_addr, app_settings)); /* Application settings are fetched only once for initial values * initiate anything that follows after RC procedure. * Defer it if browsing is supported till players query @@ -3608,8 +3424,7 @@ static void handle_app_attr_txt_response(tBTA_AV_META_MSG* pmeta_msg, uint8_t xx; uint8_t vals[AVRC_MAX_APP_ATTR_SIZE]; btif_rc_player_app_settings_t* p_app_settings; - btif_rc_device_cb_t* p_dev = - btif_rc_get_device_by_handle(pmeta_msg->rc_handle); + btif_rc_device_cb_t* p_dev = btif_rc_get_device_by_handle(pmeta_msg->rc_handle); if (p_dev == NULL) { log::error("p_dev NULL"); @@ -3628,21 +3443,18 @@ static void handle_app_attr_txt_response(tBTA_AV_META_MSG* pmeta_msg, * for standard attributes. */ p_app_settings->num_ext_attrs = 0; - for (xx = 0; - xx < p_app_settings->ext_attr_index && xx < AVRC_MAX_APP_ATTR_SIZE; - xx++) { + for (xx = 0; xx < p_app_settings->ext_attr_index && xx < AVRC_MAX_APP_ATTR_SIZE; xx++) { osi_free_and_reset((void**)&p_app_settings->ext_attrs[xx].p_str); } p_app_settings->ext_attr_index = 0; - for (xx = 0; xx < p_app_settings->num_attrs && xx < AVRC_MAX_APP_ATTR_SIZE; - xx++) { + for (xx = 0; xx < p_app_settings->num_attrs && xx < AVRC_MAX_APP_ATTR_SIZE; xx++) { attrs[xx] = p_app_settings->attrs[xx].attr_id; } - do_in_jni_thread(base::BindOnce( - bt_rc_ctrl_callbacks->playerapplicationsetting_cb, p_dev->rc_addr, - p_app_settings->num_attrs, p_app_settings->attrs, 0, nullptr)); + do_in_jni_thread(base::BindOnce(bt_rc_ctrl_callbacks->playerapplicationsetting_cb, + p_dev->rc_addr, p_app_settings->num_attrs, + p_app_settings->attrs, 0, nullptr)); get_player_app_setting_cmd(xx, attrs, p_dev); return; @@ -3650,8 +3462,7 @@ static void handle_app_attr_txt_response(tBTA_AV_META_MSG* pmeta_msg, for (xx = 0; xx < p_rsp->num_attr; xx++) { uint8_t x; - for (x = 0; x < p_app_settings->num_ext_attrs && x < AVRC_MAX_APP_ATTR_SIZE; - x++) { + for (x = 0; x < p_app_settings->num_ext_attrs && x < AVRC_MAX_APP_ATTR_SIZE; x++) { if (p_app_settings->ext_attrs[x].attr_id == p_rsp->p_attrs[xx].attr_id) { p_app_settings->ext_attrs[x].charset_id = p_rsp->p_attrs[xx].charset_id; p_app_settings->ext_attrs[x].str_len = p_rsp->p_attrs[xx].str_len; @@ -3661,9 +3472,7 @@ static void handle_app_attr_txt_response(tBTA_AV_META_MSG* pmeta_msg, } } - for (xx = 0; - xx < p_app_settings->ext_attrs[0].num_val && xx < BTRC_MAX_APP_ATTR_SIZE; - xx++) { + for (xx = 0; xx < p_app_settings->ext_attrs[0].num_val && xx < BTRC_MAX_APP_ATTR_SIZE; xx++) { vals[xx] = p_app_settings->ext_attrs[0].ext_attr_val[xx].val; } get_player_app_setting_value_text_cmd(vals, xx, p_dev); @@ -3679,14 +3488,13 @@ static void handle_app_attr_txt_response(tBTA_AV_META_MSG* pmeta_msg, * Returns None * **************************************************************************/ -static void handle_app_attr_val_txt_response( - tBTA_AV_META_MSG* pmeta_msg, tAVRC_GET_APP_ATTR_TXT_RSP* p_rsp) { +static void handle_app_attr_val_txt_response(tBTA_AV_META_MSG* pmeta_msg, + tAVRC_GET_APP_ATTR_TXT_RSP* p_rsp) { uint8_t xx, attr_index; uint8_t vals[AVRC_MAX_APP_ATTR_SIZE]; uint8_t attrs[AVRC_MAX_APP_ATTR_SIZE]; btif_rc_player_app_settings_t* p_app_settings; - btif_rc_device_cb_t* p_dev = - btif_rc_get_device_by_handle(pmeta_msg->rc_handle); + btif_rc_device_cb_t* p_dev = btif_rc_get_device_by_handle(pmeta_msg->rc_handle); if (p_dev == NULL) { log::error("p_dev NULL"); @@ -3706,14 +3514,13 @@ static void handle_app_attr_val_txt_response( * for standard attributes. */ p_app_settings->num_ext_attrs = 0; - for (xx = 0; - xx < p_app_settings->ext_attr_index && xx < AVRC_MAX_APP_ATTR_SIZE; - xx++) { + for (xx = 0; xx < p_app_settings->ext_attr_index && xx < AVRC_MAX_APP_ATTR_SIZE; xx++) { int x; btrc_player_app_ext_attr_t* p_ext_attr = &p_app_settings->ext_attrs[xx]; - for (x = 0; x < p_ext_attr->num_val && x < BTRC_MAX_APP_ATTR_SIZE; x++) + for (x = 0; x < p_ext_attr->num_val && x < BTRC_MAX_APP_ATTR_SIZE; x++) { osi_free_and_reset((void**)&p_ext_attr->ext_attr_val[x].p_str); + } p_ext_attr->num_val = 0; osi_free_and_reset((void**)&p_app_settings->ext_attrs[xx].p_str); } @@ -3722,17 +3529,16 @@ static void handle_app_attr_val_txt_response( for (xx = 0; xx < p_app_settings->num_attrs; xx++) { attrs[xx] = p_app_settings->attrs[xx].attr_id; } - do_in_jni_thread(base::BindOnce( - bt_rc_ctrl_callbacks->playerapplicationsetting_cb, p_dev->rc_addr, - p_app_settings->num_attrs, p_app_settings->attrs, 0, nullptr)); + do_in_jni_thread(base::BindOnce(bt_rc_ctrl_callbacks->playerapplicationsetting_cb, + p_dev->rc_addr, p_app_settings->num_attrs, + p_app_settings->attrs, 0, nullptr)); get_player_app_setting_cmd(xx, attrs, p_dev); return; } if (p_app_settings->ext_val_index >= AVRC_MAX_APP_ATTR_SIZE) { - log::error("ext_val_index is 0x{:02x}, overflow!", - p_app_settings->ext_val_index); + log::error("ext_val_index is 0x{:02x}, overflow!", p_app_settings->ext_val_index); return; } @@ -3766,17 +3572,16 @@ static void handle_app_attr_val_txt_response( for (x = 0; x < p_app_settings->num_ext_attrs; x++) { attrs[xx + x] = p_app_settings->ext_attrs[x].attr_id; } - do_in_jni_thread(base::BindOnce( - bt_rc_ctrl_callbacks->playerapplicationsetting_cb, p_dev->rc_addr, - p_app_settings->num_attrs, p_app_settings->attrs, - p_app_settings->num_ext_attrs, p_app_settings->ext_attrs)); + do_in_jni_thread(base::BindOnce(bt_rc_ctrl_callbacks->playerapplicationsetting_cb, + p_dev->rc_addr, p_app_settings->num_attrs, + p_app_settings->attrs, p_app_settings->num_ext_attrs, + p_app_settings->ext_attrs)); get_player_app_setting_cmd(xx + x, attrs, p_dev); /* Free the application settings information after sending to * application. */ - do_in_jni_thread( - base::BindOnce(cleanup_app_attr_val_txt_response, p_app_settings)); + do_in_jni_thread(base::BindOnce(cleanup_app_attr_val_txt_response, p_app_settings)); p_app_settings->num_attrs = 0; } } @@ -3789,11 +3594,8 @@ static void handle_app_attr_val_txt_response( * application settings. * Returns None **************************************************************************/ -static void cleanup_app_attr_val_txt_response( - btif_rc_player_app_settings_t* p_app_settings) { - for (uint8_t xx = 0; - xx < p_app_settings->ext_attr_index && xx < AVRC_MAX_APP_ATTR_SIZE; - xx++) { +static void cleanup_app_attr_val_txt_response(btif_rc_player_app_settings_t* p_app_settings) { + for (uint8_t xx = 0; xx < p_app_settings->ext_attr_index && xx < AVRC_MAX_APP_ATTR_SIZE; xx++) { int x; btrc_player_app_ext_attr_t* p_ext_attr = &p_app_settings->ext_attrs[xx]; for (x = 0; x < p_ext_attr->num_val && x < BTRC_MAX_APP_ATTR_SIZE; x++) { @@ -3813,27 +3615,23 @@ static void cleanup_app_attr_val_txt_response( * Returns None * **************************************************************************/ -static void handle_set_app_attr_val_response(tBTA_AV_META_MSG* pmeta_msg, - tAVRC_RSP* p_rsp) { +static void handle_set_app_attr_val_response(tBTA_AV_META_MSG* pmeta_msg, tAVRC_RSP* p_rsp) { uint8_t accepted = 0; - btif_rc_device_cb_t* p_dev = - btif_rc_get_device_by_handle(pmeta_msg->rc_handle); + btif_rc_device_cb_t* p_dev = btif_rc_get_device_by_handle(pmeta_msg->rc_handle); if (p_dev == NULL) { log::error("p_dev NULL"); return; } - /* For timeout pmeta_msg will be NULL, else we need to * check if this is accepted by TG */ if (pmeta_msg && (pmeta_msg->code == AVRC_RSP_ACCEPT)) { accepted = 1; } - do_in_jni_thread( - base::BindOnce(bt_rc_ctrl_callbacks->setplayerappsetting_rsp_cb, - p_dev->rc_addr, accepted)); + do_in_jni_thread(base::BindOnce(bt_rc_ctrl_callbacks->setplayerappsetting_rsp_cb, p_dev->rc_addr, + accepted)); } /*************************************************************************** @@ -3846,35 +3644,31 @@ static void handle_set_app_attr_val_response(tBTA_AV_META_MSG* pmeta_msg, * **************************************************************************/ static void handle_get_metadata_attr_response(tBTA_AV_META_MSG* pmeta_msg, - tAVRC_GET_ATTRS_RSP* p_rsp) { - btif_rc_device_cb_t* p_dev = - btif_rc_get_device_by_handle(pmeta_msg->rc_handle); + tAVRC_GET_ATTRS_RSP* p_rsp) { + btif_rc_device_cb_t* p_dev = btif_rc_get_device_by_handle(pmeta_msg->rc_handle); if (p_rsp->status == AVRC_STS_NO_ERROR) { size_t buf_size = p_rsp->num_attrs * sizeof(btrc_element_attr_val_t); - btrc_element_attr_val_t* p_attr = - (btrc_element_attr_val_t*)osi_calloc(buf_size); + btrc_element_attr_val_t* p_attr = (btrc_element_attr_val_t*)osi_calloc(buf_size); if (p_dev == NULL) { log::error("p_dev NULL"); return; } - for (int i = 0; i < p_rsp->num_attrs; i++) { p_attr[i].attr_id = p_rsp->p_attrs[i].attr_id; - /* Todo. Legth limit check to include null */ + /* Todo. Length limit check to include null */ if (p_rsp->p_attrs[i].name.str_len && p_rsp->p_attrs[i].name.p_str) { - memcpy(p_attr[i].text, p_rsp->p_attrs[i].name.p_str, - p_rsp->p_attrs[i].name.str_len); + memcpy(p_attr[i].text, p_rsp->p_attrs[i].name.p_str, p_rsp->p_attrs[i].name.str_len); osi_free_and_reset((void**)&p_rsp->p_attrs[i].name.p_str); } } osi_free_and_reset((void**)&p_rsp->p_attrs); - do_in_jni_thread(base::BindOnce(bt_rc_ctrl_callbacks->track_changed_cb, - p_dev->rc_addr, p_rsp->num_attrs, p_attr)); + do_in_jni_thread(base::BindOnce(bt_rc_ctrl_callbacks->track_changed_cb, p_dev->rc_addr, + p_rsp->num_attrs, p_attr)); do_in_jni_thread(base::BindOnce(osi_free, p_attr)); } else if (p_rsp->status == BTIF_RC_STS_TIMEOUT) { /* Retry for timeout case, this covers error handling @@ -3899,23 +3693,18 @@ static void handle_get_metadata_attr_response(tBTA_AV_META_MSG* pmeta_msg, **************************************************************************/ static void handle_get_playstatus_response(tBTA_AV_META_MSG* pmeta_msg, tAVRC_GET_PLAY_STATUS_RSP* p_rsp) { - - btif_rc_device_cb_t* p_dev = - btif_rc_get_device_by_handle(pmeta_msg->rc_handle); + btif_rc_device_cb_t* p_dev = btif_rc_get_device_by_handle(pmeta_msg->rc_handle); if (p_dev == NULL) { log::error("p_dev NULL"); return; } - if (p_rsp->status == AVRC_STS_NO_ERROR) { - do_in_jni_thread( - base::BindOnce(bt_rc_ctrl_callbacks->play_status_changed_cb, - p_dev->rc_addr, (btrc_play_status_t)p_rsp->play_status)); - do_in_jni_thread( - base::BindOnce(bt_rc_ctrl_callbacks->play_position_changed_cb, - p_dev->rc_addr, p_rsp->song_len, p_rsp->song_pos)); + do_in_jni_thread(base::BindOnce(bt_rc_ctrl_callbacks->play_status_changed_cb, p_dev->rc_addr, + (btrc_play_status_t)p_rsp->play_status)); + do_in_jni_thread(base::BindOnce(bt_rc_ctrl_callbacks->play_position_changed_cb, p_dev->rc_addr, + p_rsp->song_len, p_rsp->song_pos)); } else { log::error("Error in get play status procedure: {}", p_rsp->status); } @@ -3930,22 +3719,17 @@ static void handle_get_playstatus_response(tBTA_AV_META_MSG* pmeta_msg, * Returns None * **************************************************************************/ -static void handle_set_addressed_player_response(tBTA_AV_META_MSG* pmeta_msg, - tAVRC_RSP* p_rsp) { - - btif_rc_device_cb_t* p_dev = - btif_rc_get_device_by_handle(pmeta_msg->rc_handle); +static void handle_set_addressed_player_response(tBTA_AV_META_MSG* pmeta_msg, tAVRC_RSP* p_rsp) { + btif_rc_device_cb_t* p_dev = btif_rc_get_device_by_handle(pmeta_msg->rc_handle); if (p_dev == NULL) { log::error("p_dev NULL"); return; } - if (p_rsp->status == AVRC_STS_NO_ERROR) { - do_in_jni_thread( - base::BindOnce(bt_rc_ctrl_callbacks->set_addressed_player_cb, - p_dev->rc_addr, p_rsp->status)); + do_in_jni_thread(base::BindOnce(bt_rc_ctrl_callbacks->set_addressed_player_cb, p_dev->rc_addr, + p_rsp->status)); } else { log::error("Error in get play status procedure {}", p_rsp->status); } @@ -3962,16 +3746,15 @@ static void handle_set_addressed_player_response(tBTA_AV_META_MSG* pmeta_msg, **************************************************************************/ static void handle_get_folder_items_response(tBTA_AV_META_MSG* pmeta_msg, tAVRC_GET_ITEMS_RSP* p_rsp) { - btif_rc_device_cb_t* p_dev = - btif_rc_get_device_by_handle(pmeta_msg->rc_handle); + btif_rc_device_cb_t* p_dev = btif_rc_get_device_by_handle(pmeta_msg->rc_handle); if (p_rsp->status == AVRC_STS_NO_ERROR) { /* Convert the internal folder listing into a response that can * be passed onto JNI via HAL_CBACK */ uint8_t item_count = p_rsp->item_count; - btrc_folder_items_t* btrc_items = (btrc_folder_items_t*)osi_malloc( - sizeof(btrc_folder_items_t) * item_count); + btrc_folder_items_t* btrc_items = + (btrc_folder_items_t*)osi_malloc(sizeof(btrc_folder_items_t) * item_count); for (uint8_t i = 0; i < item_count; i++) { const tAVRC_ITEM* avrc_item = &(p_rsp->p_item_list[i]); btrc_folder_items_t* btrc_item = &(btrc_items[i]); @@ -3982,7 +3765,7 @@ static void handle_get_folder_items_response(tBTA_AV_META_MSG* pmeta_msg, /* Allocate Space for Attributes */ btrc_item->media.num_attrs = avrc_item->u.media.attr_count; btrc_item->media.p_attrs = (btrc_element_attr_val_t*)osi_malloc( - btrc_item->media.num_attrs * sizeof(btrc_element_attr_val_t)); + btrc_item->media.num_attrs * sizeof(btrc_element_attr_val_t)); get_folder_item_type_media(avrc_item, btrc_item); break; @@ -3997,16 +3780,14 @@ static void handle_get_folder_items_response(tBTA_AV_META_MSG* pmeta_msg, break; default: - log::error("cannot understand folder item type {}", - avrc_item->item_type); + log::error("cannot understand folder item type {}", avrc_item->item_type); } } - do_in_jni_thread( - base::BindOnce(bt_rc_ctrl_callbacks->get_folder_items_cb, - p_dev->rc_addr, BTRC_STS_NO_ERROR, - /* We want to make the ownership explicit in native */ - btrc_items, item_count)); + do_in_jni_thread(base::BindOnce(bt_rc_ctrl_callbacks->get_folder_items_cb, p_dev->rc_addr, + BTRC_STS_NO_ERROR, + /* We want to make the ownership explicit in native */ + btrc_items, item_count)); if (item_count > 0) { if (btrc_items[0].item_type == AVRC_ITEM_PLAYER && @@ -4017,14 +3798,12 @@ static void handle_get_folder_items_response(tBTA_AV_META_MSG* pmeta_msg, /* Release the memory block for items and attributes allocated here. * Since the executor for do_in_jni_thread is a Single Thread Task Runner it * is okay to queue up the cleanup of btrc_items */ - do_in_jni_thread( - base::BindOnce(cleanup_btrc_folder_items, btrc_items, item_count)); + do_in_jni_thread(base::BindOnce(cleanup_btrc_folder_items, btrc_items, item_count)); log::verbose("get_folder_items_cb sent to JNI thread"); } else { log::error("Error {}", p_rsp->status); - do_in_jni_thread(base::BindOnce(bt_rc_ctrl_callbacks->get_folder_items_cb, - p_dev->rc_addr, + do_in_jni_thread(base::BindOnce(bt_rc_ctrl_callbacks->get_folder_items_cb, p_dev->rc_addr, (btrc_status_t)p_rsp->status, nullptr, 0)); } } @@ -4036,8 +3815,7 @@ static void handle_get_folder_items_response(tBTA_AV_META_MSG* pmeta_msg, * items. * Returns None **************************************************************************/ -static void cleanup_btrc_folder_items(btrc_folder_items_t* btrc_items, - uint8_t item_count) { +static void cleanup_btrc_folder_items(btrc_folder_items_t* btrc_items, uint8_t item_count) { for (uint8_t i = 0; i < item_count; i++) { btrc_folder_items_t* btrc_item = &(btrc_items[i]); switch (btrc_item->item_type) { @@ -4064,15 +3842,13 @@ static void cleanup_btrc_folder_items(btrc_folder_items_t* btrc_items, * Returns None * **************************************************************************/ -void get_folder_item_type_media(const tAVRC_ITEM* avrc_item, - btrc_folder_items_t* btrc_item) { +void get_folder_item_type_media(const tAVRC_ITEM* avrc_item, btrc_folder_items_t* btrc_item) { btrc_item->item_type = BTRC_ITEM_MEDIA; const tAVRC_ITEM_MEDIA* avrc_item_media = &(avrc_item->u.media); btrc_item_media_t* btrc_item_media = &(btrc_item->media); /* UID */ memset(btrc_item_media->uid, 0, BTRC_UID_SIZE * sizeof(uint8_t)); - memcpy(btrc_item_media->uid, avrc_item_media->uid, - sizeof(uint8_t) * BTRC_UID_SIZE); + memcpy(btrc_item_media->uid, avrc_item_media->uid, sizeof(uint8_t) * BTRC_UID_SIZE); /* Audio/Video type */ switch (avrc_item_media->type) { @@ -4088,8 +3864,7 @@ void get_folder_item_type_media(const tAVRC_ITEM* avrc_item, btrc_item_media->charset_id = avrc_item_media->name.charset_id; /* Copy the name */ - log::verbose("max len {} str len {}", BTRC_MAX_ATTR_STR_LEN, - avrc_item_media->name.str_len); + log::verbose("max len {} str len {}", BTRC_MAX_ATTR_STR_LEN, avrc_item_media->name.str_len); memset(btrc_item_media->name, 0, BTRC_MAX_ATTR_STR_LEN * sizeof(uint8_t)); memcpy(btrc_item_media->name, avrc_item_media->name.p_str, sizeof(uint8_t) * (avrc_item_media->name.str_len)); @@ -4132,8 +3907,7 @@ void get_folder_item_type_media(const tAVRC_ITEM* avrc_item, } memset(btrc_attr_pair->text, 0, BTRC_MAX_ATTR_STR_LEN * sizeof(uint8_t)); - memcpy(btrc_attr_pair->text, avrc_attr_pair->name.p_str, - avrc_attr_pair->name.str_len); + memcpy(btrc_attr_pair->text, avrc_attr_pair->name.p_str, avrc_attr_pair->name.str_len); } } @@ -4146,15 +3920,13 @@ void get_folder_item_type_media(const tAVRC_ITEM* avrc_item, * Returns None * **************************************************************************/ -void get_folder_item_type_folder(const tAVRC_ITEM* avrc_item, - btrc_folder_items_t* btrc_item) { +void get_folder_item_type_folder(const tAVRC_ITEM* avrc_item, btrc_folder_items_t* btrc_item) { btrc_item->item_type = BTRC_ITEM_FOLDER; const tAVRC_ITEM_FOLDER* avrc_item_folder = &(avrc_item->u.folder); btrc_item_folder_t* btrc_item_folder = &(btrc_item->folder); /* Copy the UID */ memset(btrc_item_folder->uid, 0, BTRC_UID_SIZE * sizeof(uint8_t)); - memcpy(btrc_item_folder->uid, avrc_item_folder->uid, - sizeof(uint8_t) * BTRC_UID_SIZE); + memcpy(btrc_item_folder->uid, avrc_item_folder->uid, sizeof(uint8_t) * BTRC_UID_SIZE); /* Copy the type */ switch (avrc_item_folder->type) { @@ -4185,8 +3957,7 @@ void get_folder_item_type_folder(const tAVRC_ITEM* avrc_item, btrc_item_folder->playable = avrc_item_folder->playable; /* Copy name */ - log::verbose("max len {} str len {}", BTRC_MAX_ATTR_STR_LEN, - avrc_item_folder->name.str_len); + log::verbose("max len {} str len {}", BTRC_MAX_ATTR_STR_LEN, avrc_item_folder->name.str_len); memset(btrc_item_folder->name, 0, BTRC_MAX_ATTR_STR_LEN * sizeof(uint8_t)); memcpy(btrc_item_folder->name, avrc_item_folder->name.p_str, avrc_item_folder->name.str_len * sizeof(uint8_t)); @@ -4204,8 +3975,7 @@ void get_folder_item_type_folder(const tAVRC_ITEM* avrc_item, * Returns None * **************************************************************************/ -void get_folder_item_type_player(const tAVRC_ITEM* avrc_item, - btrc_folder_items_t* btrc_item) { +void get_folder_item_type_player(const tAVRC_ITEM* avrc_item, btrc_folder_items_t* btrc_item) { btrc_item->item_type = BTRC_ITEM_PLAYER; const tAVRC_ITEM_PLAYER* avrc_item_player = &(avrc_item->u.player); btrc_item_player_t* btrc_item_player = &(btrc_item->player); @@ -4218,12 +3988,10 @@ void get_folder_item_type_player(const tAVRC_ITEM* avrc_item, /* Play status */ btrc_item_player->play_status = avrc_item_player->play_status; /* Features */ - memcpy(btrc_item_player->features, avrc_item_player->features, - BTRC_FEATURE_BIT_MASK_SIZE); + memcpy(btrc_item_player->features, avrc_item_player->features, BTRC_FEATURE_BIT_MASK_SIZE); memset(btrc_item_player->name, 0, BTRC_MAX_ATTR_STR_LEN * sizeof(uint8_t)); - memcpy(btrc_item_player->name, avrc_item_player->name.p_str, - avrc_item_player->name.str_len); + memcpy(btrc_item_player->name, avrc_item_player->name.p_str, avrc_item_player->name.str_len); } /*************************************************************************** @@ -4235,10 +4003,8 @@ void get_folder_item_type_player(const tAVRC_ITEM* avrc_item, * Returns None * **************************************************************************/ -static void handle_change_path_response(tBTA_AV_META_MSG* pmeta_msg, - tAVRC_CHG_PATH_RSP* p_rsp) { - btif_rc_device_cb_t* p_dev = - btif_rc_get_device_by_handle(pmeta_msg->rc_handle); +static void handle_change_path_response(tBTA_AV_META_MSG* pmeta_msg, tAVRC_CHG_PATH_RSP* p_rsp) { + btif_rc_device_cb_t* p_dev = btif_rc_get_device_by_handle(pmeta_msg->rc_handle); if (p_dev == NULL) { log::error("Invalid rc handle"); @@ -4246,8 +4012,8 @@ static void handle_change_path_response(tBTA_AV_META_MSG* pmeta_msg, } if (p_rsp->status == AVRC_STS_NO_ERROR) { - do_in_jni_thread(base::BindOnce(bt_rc_ctrl_callbacks->change_folder_path_cb, - p_dev->rc_addr, p_rsp->num_items)); + do_in_jni_thread(base::BindOnce(bt_rc_ctrl_callbacks->change_folder_path_cb, p_dev->rc_addr, + p_rsp->num_items)); } else { log::error("error in handle_change_path_response {}", p_rsp->status); } @@ -4264,8 +4030,7 @@ static void handle_change_path_response(tBTA_AV_META_MSG* pmeta_msg, **************************************************************************/ static void handle_set_browsed_player_response(tBTA_AV_META_MSG* pmeta_msg, tAVRC_SET_BR_PLAYER_RSP* p_rsp) { - btif_rc_device_cb_t* p_dev = - btif_rc_get_device_by_handle(pmeta_msg->rc_handle); + btif_rc_device_cb_t* p_dev = btif_rc_get_device_by_handle(pmeta_msg->rc_handle); if (p_dev == NULL) { log::error("Invalid rc handle"); @@ -4273,9 +4038,8 @@ static void handle_set_browsed_player_response(tBTA_AV_META_MSG* pmeta_msg, } if (p_rsp->status == AVRC_STS_NO_ERROR) { - do_in_jni_thread(base::BindOnce(bt_rc_ctrl_callbacks->set_browsed_player_cb, - p_dev->rc_addr, p_rsp->num_items, - p_rsp->folder_depth)); + do_in_jni_thread(base::BindOnce(bt_rc_ctrl_callbacks->set_browsed_player_cb, p_dev->rc_addr, + p_rsp->num_items, p_rsp->folder_depth)); } else { log::error("error {}", p_rsp->status); } @@ -4321,17 +4085,14 @@ static void handle_avk_rc_metamsg_rsp(tBTA_AV_META_MSG* pmeta_msg) { tAVRC_STS status; btif_rc_device_cb_t* p_dev = NULL; - log::verbose("opcode: {} rsp_code: {}", pmeta_msg->p_msg->hdr.opcode, - pmeta_msg->code); + log::verbose("opcode: {} rsp_code: {}", pmeta_msg->p_msg->hdr.opcode, pmeta_msg->code); p_dev = btif_rc_get_device_by_handle(pmeta_msg->rc_handle); - status = AVRC_Ctrl_ParsResponse(pmeta_msg->p_msg, &avrc_response, scratch_buf, - &buf_len); - if ((AVRC_OP_VENDOR == pmeta_msg->p_msg->hdr.opcode) && - (pmeta_msg->code >= AVRC_RSP_NOT_IMPL) && + status = AVRC_Ctrl_ParsResponse(pmeta_msg->p_msg, &avrc_response, scratch_buf, &buf_len); + if ((AVRC_OP_VENDOR == pmeta_msg->p_msg->hdr.opcode) && (pmeta_msg->code >= AVRC_RSP_NOT_IMPL) && (pmeta_msg->code <= AVRC_RSP_INTERIM)) { - log::verbose("parse status {} pdu = {} rsp_status = {}", status, - avrc_response.pdu, pmeta_msg->p_msg->vendor.hdr.ctype); + log::verbose("parse status {} pdu = {} rsp_status = {}", status, avrc_response.pdu, + pmeta_msg->p_msg->vendor.hdr.ctype); switch (avrc_response.pdu) { case AVRC_PDU_REGISTER_NOTIFICATION: @@ -4360,13 +4121,11 @@ static void handle_avk_rc_metamsg_rsp(tBTA_AV_META_MSG* pmeta_msg) { break; case AVRC_PDU_GET_PLAYER_APP_ATTR_TEXT: - handle_app_attr_txt_response(pmeta_msg, - &avrc_response.get_app_attr_txt); + handle_app_attr_txt_response(pmeta_msg, &avrc_response.get_app_attr_txt); break; case AVRC_PDU_GET_PLAYER_APP_VALUE_TEXT: - handle_app_attr_val_txt_response(pmeta_msg, - &avrc_response.get_app_val_txt); + handle_app_attr_val_txt_response(pmeta_msg, &avrc_response.get_app_val_txt); break; case AVRC_PDU_SET_PLAYER_APP_VALUE: @@ -4378,8 +4137,7 @@ static void handle_avk_rc_metamsg_rsp(tBTA_AV_META_MSG* pmeta_msg) { break; case AVRC_PDU_GET_PLAY_STATUS: - handle_get_playstatus_response(pmeta_msg, - &avrc_response.get_play_status); + handle_get_playstatus_response(pmeta_msg, &avrc_response.get_play_status); break; case AVRC_PDU_SET_ADDRESSED_PLAYER: @@ -4406,8 +4164,8 @@ static void handle_avk_rc_metamsg_rsp(tBTA_AV_META_MSG* pmeta_msg) { log::error("cannot handle browse pdu {}", pmeta_msg->p_msg->hdr.opcode); } } else { - log::verbose("Invalid Vendor Command code: {} len: {}. Not processing it.", - pmeta_msg->code, pmeta_msg->len); + log::verbose("Invalid Vendor Command code: {} len: {}. Not processing it.", pmeta_msg->code, + pmeta_msg->len); return; } log::verbose("release transaction {}", pmeta_msg->label); @@ -4428,28 +4186,25 @@ static void handle_avk_rc_metamsg_cmd(tBTA_AV_META_MSG* pmeta_msg) { tAVRC_STS status = BT_STATUS_UNSUPPORTED; btif_rc_device_cb_t* p_dev = NULL; - log::verbose("opcode: {} rsp_code: {}", pmeta_msg->p_msg->hdr.opcode, - pmeta_msg->code); + log::verbose("opcode: {} rsp_code: {}", pmeta_msg->p_msg->hdr.opcode, pmeta_msg->code); status = AVRC_Ctrl_ParsCommand(pmeta_msg->p_msg, &avrc_cmd); - if ((AVRC_OP_VENDOR == pmeta_msg->p_msg->hdr.opcode) && - (pmeta_msg->code <= AVRC_CMD_GEN_INQ)) { - log::verbose("Received vendor command.code {}, PDU {} label {}", - pmeta_msg->code, avrc_cmd.pdu, pmeta_msg->label); + if ((AVRC_OP_VENDOR == pmeta_msg->p_msg->hdr.opcode) && (pmeta_msg->code <= AVRC_CMD_GEN_INQ)) { + log::verbose("Received vendor command.code {}, PDU {} label {}", pmeta_msg->code, avrc_cmd.pdu, + pmeta_msg->label); if (status != AVRC_STS_NO_ERROR) { /* return error */ - log::warn("Error in parsing received metamsg command. status: 0x{:02x}", - status); + log::warn("Error in parsing received metamsg command. status: 0x{:02x}", status); if (true == btif_av_both_enable()) { if (AVRC_PDU_GET_CAPABILITIES == avrc_cmd.pdu || - AVRC_PDU_GET_ELEMENT_ATTR == avrc_cmd.pdu || - AVRC_PDU_GET_PLAY_STATUS == avrc_cmd.pdu || + AVRC_PDU_GET_ELEMENT_ATTR == avrc_cmd.pdu || AVRC_PDU_GET_PLAY_STATUS == avrc_cmd.pdu || AVRC_PDU_GET_FOLDER_ITEMS == avrc_cmd.pdu || - AVRC_PDU_GET_ITEM_ATTRIBUTES == avrc_cmd.pdu) + AVRC_PDU_GET_ITEM_ATTRIBUTES == avrc_cmd.pdu) { return; + } } - send_reject_response(pmeta_msg->rc_handle, pmeta_msg->label, avrc_cmd.pdu, - status, pmeta_msg->p_msg->hdr.opcode); + send_reject_response(pmeta_msg->rc_handle, pmeta_msg->label, avrc_cmd.pdu, status, + pmeta_msg->p_msg->hdr.opcode); } else { p_dev = btif_rc_get_device_by_handle(pmeta_msg->rc_handle); if (p_dev == NULL) { @@ -4459,18 +4214,16 @@ static void handle_avk_rc_metamsg_cmd(tBTA_AV_META_MSG* pmeta_msg) { if (avrc_cmd.pdu == AVRC_PDU_REGISTER_NOTIFICATION) { uint8_t event_id = avrc_cmd.reg_notif.event_id; - log::verbose("Register notification event_id: {}", - dump_rc_notification_event_id(event_id)); + log::verbose("Register notification event_id: {}", dump_rc_notification_event_id(event_id)); } else if (avrc_cmd.pdu == AVRC_PDU_SET_ABSOLUTE_VOLUME) { log::verbose("Abs Volume Cmd Recvd"); } - btif_rc_ctrl_upstreams_rsp_cmd(avrc_cmd.pdu, &avrc_cmd, pmeta_msg->label, - p_dev); + btif_rc_ctrl_upstreams_rsp_cmd(avrc_cmd.pdu, &avrc_cmd, pmeta_msg->label, p_dev); } } else { - log::verbose("Invalid Vendor Command code: {} len: {}. Not processing it.", - pmeta_msg->code, pmeta_msg->len); + log::verbose("Invalid Vendor Command code: {} len: {}. Not processing it.", pmeta_msg->code, + pmeta_msg->len); return; } } @@ -4492,8 +4245,7 @@ static void cleanup() { for (int idx = 0; idx < BTIF_RC_NUM_CONN; idx++) { alarm_free(btif_rc_cb.rc_multi_cb[idx].rc_play_status_timer); - memset(&btif_rc_cb.rc_multi_cb[idx], 0, - sizeof(btif_rc_cb.rc_multi_cb[idx])); + memset(&btif_rc_cb.rc_multi_cb[idx], 0, sizeof(btif_rc_cb.rc_multi_cb[idx])); } log::verbose("completed"); @@ -4517,8 +4269,7 @@ static void cleanup_ctrl() { for (int idx = 0; idx < BTIF_RC_NUM_CONN; idx++) { alarm_free(btif_rc_cb.rc_multi_cb[idx].rc_play_status_timer); - memset(&btif_rc_cb.rc_multi_cb[idx], 0, - sizeof(btif_rc_cb.rc_multi_cb[idx])); + memset(&btif_rc_cb.rc_multi_cb[idx], 0, sizeof(btif_rc_cb.rc_multi_cb[idx])); } memset(&btif_rc_cb.rc_multi_cb, 0, sizeof(btif_rc_cb.rc_multi_cb)); @@ -4534,8 +4285,7 @@ static void cleanup_ctrl() { * Returns void * **************************************************************************/ -static bt_status_t getcapabilities_cmd(uint8_t cap_id, - btif_rc_device_cb_t* p_dev) { +static bt_status_t getcapabilities_cmd(uint8_t cap_id, btif_rc_device_cb_t* p_dev) { log::verbose("cap_id: {}", cap_id); CHECK_RC_CONNECTED(p_dev); @@ -4557,8 +4307,7 @@ static bt_status_t getcapabilities_cmd(uint8_t cap_id, * Returns void * **************************************************************************/ -static bt_status_t list_player_app_setting_attrib_cmd( - btif_rc_device_cb_t* p_dev) { +static bt_status_t list_player_app_setting_attrib_cmd(btif_rc_device_cb_t* p_dev) { log::verbose(""); CHECK_RC_CONNECTED(p_dev); @@ -4579,8 +4328,8 @@ static bt_status_t list_player_app_setting_attrib_cmd( * Returns void * **************************************************************************/ -static bt_status_t list_player_app_setting_value_cmd( - uint8_t attrib_id, btif_rc_device_cb_t* p_dev) { +static bt_status_t list_player_app_setting_value_cmd(uint8_t attrib_id, + btif_rc_device_cb_t* p_dev) { log::verbose("attrib_id: {}", attrib_id); CHECK_RC_CONNECTED(p_dev); @@ -4602,8 +4351,7 @@ static bt_status_t list_player_app_setting_value_cmd( * Returns void * **************************************************************************/ -static bt_status_t get_player_app_setting_cmd(uint8_t num_attrib, - uint8_t* attrib_ids, +static bt_status_t get_player_app_setting_cmd(uint8_t num_attrib, uint8_t* attrib_ids, btif_rc_device_cb_t* p_dev) { log::verbose("num_attrib: {}", num_attrib); CHECK_RC_CONNECTED(p_dev); @@ -4672,12 +4420,10 @@ static bt_status_t get_playback_state_cmd(const RawAddress& bd_addr) { * BT_STATUS_FAIL. * **************************************************************************/ -static bt_status_t get_now_playing_list_cmd(const RawAddress& bd_addr, - uint32_t start_item, +static bt_status_t get_now_playing_list_cmd(const RawAddress& bd_addr, uint32_t start_item, uint32_t end_item) { log::verbose("start, end: ({}, {})", start_item, end_item); - return get_folder_items_cmd(bd_addr, AVRC_SCOPE_NOW_PLAYING, start_item, - end_item); + return get_folder_items_cmd(bd_addr, AVRC_SCOPE_NOW_PLAYING, start_item, end_item); } /*************************************************************************** @@ -4695,10 +4441,8 @@ static bt_status_t get_now_playing_list_cmd(const RawAddress& bd_addr, * otherwise BT_STATUS_FAIL * **************************************************************************/ -static bt_status_t get_item_attribute_cmd(uint64_t uid, int scope, - uint8_t num_attribute, - const uint32_t* p_attr_ids, - btif_rc_device_cb_t* p_dev) { +static bt_status_t get_item_attribute_cmd(uint64_t uid, int scope, uint8_t num_attribute, + const uint32_t* p_attr_ids, btif_rc_device_cb_t* p_dev) { tAVRC_COMMAND avrc_cmd = {0}; avrc_cmd.pdu = AVRC_PDU_GET_ITEM_ATTRIBUTES; avrc_cmd.get_attrs.scope = scope; @@ -4722,11 +4466,10 @@ static bt_status_t get_item_attribute_cmd(uint64_t uid, int scope, * BT_STATUS_FAIL. * **************************************************************************/ -static bt_status_t get_folder_list_cmd(const RawAddress& bd_addr, - uint32_t start_item, uint32_t end_item) { +static bt_status_t get_folder_list_cmd(const RawAddress& bd_addr, uint32_t start_item, + uint32_t end_item) { log::verbose("start, end: ({}, {})", start_item, end_item); - return get_folder_items_cmd(bd_addr, AVRC_SCOPE_FILE_SYSTEM, start_item, - end_item); + return get_folder_items_cmd(bd_addr, AVRC_SCOPE_FILE_SYSTEM, start_item, end_item); } /*************************************************************************** @@ -4742,11 +4485,10 @@ static bt_status_t get_folder_list_cmd(const RawAddress& bd_addr, * BT_STATUS_FAIL. * **************************************************************************/ -static bt_status_t get_player_list_cmd(const RawAddress& bd_addr, - uint32_t start_item, uint32_t end_item) { +static bt_status_t get_player_list_cmd(const RawAddress& bd_addr, uint32_t start_item, + uint32_t end_item) { log::verbose("start, end: ({}, {})", start_item, end_item); - return get_folder_items_cmd(bd_addr, AVRC_SCOPE_PLAYER_LIST, start_item, - end_item); + return get_folder_items_cmd(bd_addr, AVRC_SCOPE_PLAYER_LIST, start_item, end_item); } /*************************************************************************** @@ -4764,8 +4506,8 @@ static bt_status_t get_player_list_cmd(const RawAddress& bd_addr, * BT_STATUS_FAIL. * **************************************************************************/ -static bt_status_t change_folder_path_cmd(const RawAddress& bd_addr, - uint8_t direction, uint8_t* uid) { +static bt_status_t change_folder_path_cmd(const RawAddress& bd_addr, uint8_t direction, + uint8_t* uid) { log::verbose("direction {}", direction); btif_rc_device_cb_t* p_dev = btif_rc_get_device_by_bda(bd_addr); CHECK_RC_CONNECTED(p_dev); @@ -4797,8 +4539,7 @@ static bt_status_t change_folder_path_cmd(const RawAddress& bd_addr, * BT_STATUS_FAIL. * **************************************************************************/ -static bt_status_t set_browsed_player_cmd(const RawAddress& bd_addr, - uint16_t id) { +static bt_status_t set_browsed_player_cmd(const RawAddress& bd_addr, uint16_t id) { log::verbose("id {}", id); btif_rc_device_cb_t* p_dev = btif_rc_get_device_by_bda(bd_addr); CHECK_RC_CONNECTED(p_dev); @@ -4825,8 +4566,7 @@ static bt_status_t set_browsed_player_cmd(const RawAddress& bd_addr, ** BT_STATUS_FAIL. ** ***************************************************************************/ -static bt_status_t set_addressed_player_cmd(const RawAddress& bd_addr, - uint16_t id) { +static bt_status_t set_addressed_player_cmd(const RawAddress& bd_addr, uint16_t id) { log::verbose("id {}", id); btif_rc_device_cb_t* p_dev = btif_rc_get_device_by_bda(bd_addr); @@ -4858,9 +4598,8 @@ static bt_status_t set_addressed_player_cmd(const RawAddress& bd_addr, * BT_STATUS_FAIL. * **************************************************************************/ -static bt_status_t get_folder_items_cmd(const RawAddress& bd_addr, - uint8_t scope, uint32_t start_item, - uint32_t end_item) { +static bt_status_t get_folder_items_cmd(const RawAddress& bd_addr, uint8_t scope, + uint32_t start_item, uint32_t end_item) { /* Check that both avrcp and browse channel are connected. */ btif_rc_device_cb_t* p_dev = btif_rc_get_device_by_bda(bd_addr); log::verbose(""); @@ -4891,10 +4630,8 @@ static bt_status_t get_folder_items_cmd(const RawAddress& bd_addr, * Returns void * **************************************************************************/ -static bt_status_t change_player_app_setting(const RawAddress& bd_addr, - uint8_t num_attrib, - uint8_t* attrib_ids, - uint8_t* attrib_vals) { +static bt_status_t change_player_app_setting(const RawAddress& bd_addr, uint8_t num_attrib, + uint8_t* attrib_ids, uint8_t* attrib_vals) { log::verbose("num_attrib: {}", num_attrib); btif_rc_device_cb_t* p_dev = btif_rc_get_device_by_bda(bd_addr); CHECK_RC_CONNECTED(p_dev); @@ -4905,7 +4642,7 @@ static bt_status_t change_player_app_setting(const RawAddress& bd_addr, avrc_cmd.set_app_val.num_val = num_attrib; avrc_cmd.set_app_val.pdu = AVRC_PDU_SET_PLAYER_APP_VALUE; avrc_cmd.set_app_val.p_vals = - (tAVRC_APP_SETTING*)osi_malloc(sizeof(tAVRC_APP_SETTING) * num_attrib); + (tAVRC_APP_SETTING*)osi_malloc(sizeof(tAVRC_APP_SETTING) * num_attrib); for (int count = 0; count < num_attrib; count++) { avrc_cmd.set_app_val.p_vals[count].attr_id = attrib_ids[count]; avrc_cmd.set_app_val.p_vals[count].attr_val = attrib_vals[count]; @@ -4925,8 +4662,8 @@ static bt_status_t change_player_app_setting(const RawAddress& bd_addr, * Returns void * **************************************************************************/ -static bt_status_t play_item_cmd(const RawAddress& bd_addr, uint8_t scope, - uint8_t* uid, uint16_t uid_counter) { +static bt_status_t play_item_cmd(const RawAddress& bd_addr, uint8_t scope, uint8_t* uid, + uint16_t uid_counter) { log::verbose("scope {} uid_counter {}", scope, uid_counter); btif_rc_device_cb_t* p_dev = btif_rc_get_device_by_bda(bd_addr); CHECK_RC_CONNECTED(p_dev); @@ -4952,8 +4689,8 @@ static bt_status_t play_item_cmd(const RawAddress& bd_addr, uint8_t scope, * Returns void * **************************************************************************/ -static bt_status_t get_player_app_setting_attr_text_cmd( - uint8_t* attrs, uint8_t num_attrs, btif_rc_device_cb_t* p_dev) { +static bt_status_t get_player_app_setting_attr_text_cmd(uint8_t* attrs, uint8_t num_attrs, + btif_rc_device_cb_t* p_dev) { log::verbose("num attrs: {}", num_attrs); CHECK_RC_CONNECTED(p_dev); @@ -4978,8 +4715,8 @@ static bt_status_t get_player_app_setting_attr_text_cmd( * Returns void * **************************************************************************/ -static bt_status_t get_player_app_setting_value_text_cmd( - uint8_t* vals, uint8_t num_vals, btif_rc_device_cb_t* p_dev) { +static bt_status_t get_player_app_setting_value_text_cmd(uint8_t* vals, uint8_t num_vals, + btif_rc_device_cb_t* p_dev) { log::verbose("num_vals: {}", num_vals); CHECK_RC_CONNECTED(p_dev); @@ -5004,8 +4741,7 @@ static bt_status_t get_player_app_setting_value_text_cmd( * Returns void * **************************************************************************/ -static bt_status_t register_notification_cmd(uint8_t event_id, - uint32_t event_value, +static bt_status_t register_notification_cmd(uint8_t event_id, uint32_t event_value, btif_rc_device_cb_t* p_dev) { log::verbose("event_id: {} event_value {}", event_id, event_value); CHECK_RC_CONNECTED(p_dev); @@ -5032,17 +4768,14 @@ static bt_status_t register_notification_cmd(uint8_t event_id, * otherwise BT_STATUS_FAIL * **************************************************************************/ -static bt_status_t get_metadata_attribute_cmd(uint8_t num_attribute, - const uint32_t* p_attr_ids, +static bt_status_t get_metadata_attribute_cmd(uint8_t num_attribute, const uint32_t* p_attr_ids, btif_rc_device_cb_t* p_dev) { - log::verbose("num_attribute: {} attribute_id: {}", num_attribute, - p_attr_ids[0]); + log::verbose("num_attribute: {} attribute_id: {}", num_attribute, p_attr_ids[0]); // If browsing is connected then send the command out that channel if (p_dev->br_connected) { - return get_item_attribute_cmd(p_dev->rc_playing_uid, - AVRC_SCOPE_NOW_PLAYING, num_attribute, - p_attr_ids, p_dev); + return get_item_attribute_cmd(p_dev->rc_playing_uid, AVRC_SCOPE_NOW_PLAYING, num_attribute, + p_attr_ids, p_dev); } // Otherwise, default to the control channel @@ -5058,11 +4791,9 @@ static bt_status_t get_metadata_attribute_cmd(uint8_t num_attribute, * Returns void * **************************************************************************/ -static bt_status_t get_element_attribute_cmd(uint8_t num_attribute, - const uint32_t* p_attr_ids, +static bt_status_t get_element_attribute_cmd(uint8_t num_attribute, const uint32_t* p_attr_ids, btif_rc_device_cb_t* p_dev) { - log::verbose("num_attribute: {} attribute_id: {}", num_attribute, - p_attr_ids[0]); + log::verbose("num_attribute: {} attribute_id: {}", num_attribute, p_attr_ids[0]); CHECK_RC_CONNECTED(p_dev); tAVRC_COMMAND avrc_cmd = {0}; avrc_cmd.get_elem_attrs.opcode = AVRC_OP_VENDOR; @@ -5106,8 +4837,7 @@ static bt_status_t get_play_status_cmd(btif_rc_device_cb_t* p_dev) { * Returns void * **************************************************************************/ -static bt_status_t set_volume_rsp(const RawAddress& bd_addr, uint8_t abs_vol, - uint8_t label) { +static bt_status_t set_volume_rsp(const RawAddress& bd_addr, uint8_t abs_vol, uint8_t label) { tAVRC_STS status = BT_STATUS_UNSUPPORTED; tAVRC_RESPONSE avrc_rsp; BT_HDR* p_msg = NULL; @@ -5126,8 +4856,7 @@ static bt_status_t set_volume_rsp(const RawAddress& bd_addr, uint8_t abs_vol, uint8_t* data_start = (uint8_t*)(p_msg + 1) + p_msg->offset; log::verbose("msgreq being sent out with label: {}", p_dev->rc_vol_label); if (p_msg != NULL) { - BTA_AvVendorRsp(p_dev->rc_handle, label, AVRC_RSP_ACCEPT, data_start, - p_msg->len, 0); + BTA_AvVendorRsp(p_dev->rc_handle, label, AVRC_RSP_ACCEPT, data_start, p_msg->len, 0); status = BT_STATUS_SUCCESS; } } else { @@ -5146,9 +4875,9 @@ static bt_status_t set_volume_rsp(const RawAddress& bd_addr, uint8_t abs_vol, * Returns void * **************************************************************************/ -static bt_status_t volume_change_notification_rsp( - const RawAddress& bd_addr, btrc_notification_type_t rsp_type, - uint8_t abs_vol, uint8_t label) { +static bt_status_t volume_change_notification_rsp(const RawAddress& bd_addr, + btrc_notification_type_t rsp_type, + uint8_t abs_vol, uint8_t label) { tAVRC_STS status = BT_STATUS_UNSUPPORTED; tAVRC_RESPONSE avrc_rsp; BT_HDR* p_msg = NULL; @@ -5168,11 +4897,10 @@ static bt_status_t volume_change_notification_rsp( if (status == AVRC_STS_NO_ERROR) { log::verbose("msgreq being sent out with label: {}", label); uint8_t* data_start = (uint8_t*)(p_msg + 1) + p_msg->offset; - BTA_AvVendorRsp(p_dev->rc_handle, label, - (rsp_type == BTRC_NOTIFICATION_TYPE_INTERIM) - ? AVRC_RSP_INTERIM - : AVRC_RSP_CHANGED, - data_start, p_msg->len, 0); + BTA_AvVendorRsp( + p_dev->rc_handle, label, + (rsp_type == BTRC_NOTIFICATION_TYPE_INTERIM) ? AVRC_RSP_INTERIM : AVRC_RSP_CHANGED, + data_start, p_msg->len, 0); status = BT_STATUS_SUCCESS; } else { log::error("failed to build command. status: 0x{:02x}", status); @@ -5191,8 +4919,7 @@ static bt_status_t volume_change_notification_rsp( * Returns void * **************************************************************************/ -static bt_status_t send_groupnavigation_cmd(const RawAddress& bd_addr, - uint8_t key_code, +static bt_status_t send_groupnavigation_cmd(const RawAddress& bd_addr, uint8_t key_code, uint8_t key_state) { tAVRC_STS status = BT_STATUS_UNSUPPORTED; rc_transaction_t* p_transaction = NULL; @@ -5203,10 +4930,10 @@ static bt_status_t send_groupnavigation_cmd(const RawAddress& bd_addr, if (p_dev->rc_features & BTA_AV_FEAT_RCTG) { rc_transaction_context_t context = { - .rc_addr = p_dev->rc_addr, - .label = MAX_LABEL, - .opcode = AVRC_OP_PASS_THRU, - .command = {.passthru = {AVRC_ID_VENDOR, key_state, key_code}}}; + .rc_addr = p_dev->rc_addr, + .label = MAX_LABEL, + .opcode = AVRC_OP_PASS_THRU, + .command = {.passthru = {AVRC_ID_VENDOR, key_state, key_code}}}; bt_status_t tran_status = get_transaction(p_dev, context, &p_transaction); if ((BT_STATUS_SUCCESS == tran_status) && (NULL != p_transaction)) { uint8_t buffer[AVRC_PASS_THRU_GROUP_LEN] = {0}; @@ -5214,17 +4941,16 @@ static bt_status_t send_groupnavigation_cmd(const RawAddress& bd_addr, UINT24_TO_BE_STREAM(start, AVRC_CO_METADATA); *(start)++ = 0; UINT8_TO_BE_STREAM(start, key_code); - BTA_AvRemoteVendorUniqueCmd(p_dev->rc_handle, p_transaction->label, - (tBTA_AV_STATE)key_state, buffer, - AVRC_PASS_THRU_GROUP_LEN); + BTA_AvRemoteVendorUniqueCmd(p_dev->rc_handle, p_transaction->label, (tBTA_AV_STATE)key_state, + buffer, AVRC_PASS_THRU_GROUP_LEN); status = BT_STATUS_SUCCESS; start_transaction_timer(p_dev, p_transaction->label, BTIF_RC_TIMEOUT_MS); - log::verbose("Send command, key-code={}, key-state={}, label={}", - key_code, key_state, p_transaction->label); + log::verbose("Send command, key-code={}, key-state={}, label={}", key_code, key_state, + p_transaction->label); } else { status = BT_STATUS_FAIL; - log::error("failed to get label, key-code={}, key-state={}, status={}", - key_code, key_state, tran_status); + log::error("failed to get label, key-code={}, key-state={}, status={}", key_code, key_state, + tran_status); } } else { status = BT_STATUS_UNSUPPORTED; @@ -5242,8 +4968,8 @@ static bt_status_t send_groupnavigation_cmd(const RawAddress& bd_addr, * Returns void * **************************************************************************/ -static bt_status_t send_passthrough_cmd(const RawAddress& bd_addr, - uint8_t key_code, uint8_t key_state) { +static bt_status_t send_passthrough_cmd(const RawAddress& bd_addr, uint8_t key_code, + uint8_t key_state) { tAVRC_STS status = BT_STATUS_UNSUPPORTED; btif_rc_device_cb_t* p_dev = NULL; log::error("calling btif_rc_get_device_by_bda"); @@ -5255,22 +4981,22 @@ static bt_status_t send_passthrough_cmd(const RawAddress& bd_addr, log::verbose("key-code: {}, key-state: {}", key_code, key_state); if (p_dev->rc_features & BTA_AV_FEAT_RCTG) { rc_transaction_context_t context = { - .rc_addr = p_dev->rc_addr, - .label = MAX_LABEL, - .opcode = AVRC_OP_PASS_THRU, - .command = {.passthru = {AVRC_ID_VENDOR, key_state, key_code}}}; + .rc_addr = p_dev->rc_addr, + .label = MAX_LABEL, + .opcode = AVRC_OP_PASS_THRU, + .command = {.passthru = {AVRC_ID_VENDOR, key_state, key_code}}}; bt_status_t tran_status = get_transaction(p_dev, context, &p_transaction); if (BT_STATUS_SUCCESS == tran_status && NULL != p_transaction) { - BTA_AvRemoteCmd(p_dev->rc_handle, p_transaction->label, - (tBTA_AV_RC)key_code, (tBTA_AV_STATE)key_state); + BTA_AvRemoteCmd(p_dev->rc_handle, p_transaction->label, (tBTA_AV_RC)key_code, + (tBTA_AV_STATE)key_state); status = BT_STATUS_SUCCESS; start_transaction_timer(p_dev, p_transaction->label, BTIF_RC_TIMEOUT_MS); - log::verbose("Send command, key-code={}, key-state={}, label={}", - key_code, key_state, p_transaction->label); + log::verbose("Send command, key-code={}, key-state={}, label={}", key_code, key_state, + p_transaction->label); } else { status = BT_STATUS_FAIL; - log::error("failed to get label, key-code={}, key-state={}, status={}", - key_code, key_state, tran_status); + log::error("failed to get label, key-code={}, key-state={}, status={}", key_code, key_state, + tran_status); } } else { status = BT_STATUS_UNSUPPORTED; @@ -5280,48 +5006,48 @@ static bt_status_t send_passthrough_cmd(const RawAddress& bd_addr, } static const btrc_interface_t bt_rc_interface = { - sizeof(bt_rc_interface), - init, - get_play_status_rsp, - NULL, /* list_player_app_attr_rsp */ - NULL, /* list_player_app_value_rsp */ - NULL, /* get_player_app_value_rsp */ - NULL, /* get_player_app_attr_text_rsp */ - NULL, /* get_player_app_value_text_rsp */ - get_element_attr_rsp, - NULL, /* set_player_app_value_rsp */ - register_notification_rsp, - set_volume, - set_addressed_player_rsp, - set_browsed_player_rsp, - get_folder_items_list_rsp, - change_path_rsp, - get_item_attr_rsp, - play_item_rsp, - get_total_num_of_items_rsp, - search_rsp, - add_to_now_playing_rsp, - cleanup, + sizeof(bt_rc_interface), + init, + get_play_status_rsp, + NULL, /* list_player_app_attr_rsp */ + NULL, /* list_player_app_value_rsp */ + NULL, /* get_player_app_value_rsp */ + NULL, /* get_player_app_attr_text_rsp */ + NULL, /* get_player_app_value_text_rsp */ + get_element_attr_rsp, + NULL, /* set_player_app_value_rsp */ + register_notification_rsp, + set_volume, + set_addressed_player_rsp, + set_browsed_player_rsp, + get_folder_items_list_rsp, + change_path_rsp, + get_item_attr_rsp, + play_item_rsp, + get_total_num_of_items_rsp, + search_rsp, + add_to_now_playing_rsp, + cleanup, }; static const btrc_ctrl_interface_t bt_rc_ctrl_interface = { - sizeof(bt_rc_ctrl_interface), - init_ctrl, - send_passthrough_cmd, - send_groupnavigation_cmd, - change_player_app_setting, - play_item_cmd, - get_current_metadata_cmd, - get_playback_state_cmd, - get_now_playing_list_cmd, - get_folder_list_cmd, - get_player_list_cmd, - change_folder_path_cmd, - set_browsed_player_cmd, - set_addressed_player_cmd, - set_volume_rsp, - volume_change_notification_rsp, - cleanup_ctrl, + sizeof(bt_rc_ctrl_interface), + init_ctrl, + send_passthrough_cmd, + send_groupnavigation_cmd, + change_player_app_setting, + play_item_cmd, + get_current_metadata_cmd, + get_playback_state_cmd, + get_now_playing_list_cmd, + get_folder_list_cmd, + get_player_list_cmd, + change_folder_path_cmd, + set_browsed_player_cmd, + set_addressed_player_cmd, + set_volume_rsp, + volume_change_notification_rsp, + cleanup_ctrl, }; /******************************************************************************* @@ -5360,28 +5086,28 @@ const btrc_ctrl_interface_t* btif_rc_ctrl_get_interface(void) { * Returns void ******************************************************************************/ static void initialize_transaction(btif_rc_device_cb_t* p_dev, uint8_t lbl) { - if (p_dev == nullptr) return; + if (p_dev == nullptr) { + return; + } rc_transaction_set_t* transaction_set = &(p_dev->transaction_set); std::unique_lock lock(transaction_set->label_lock); if (lbl < MAX_TRANSACTIONS_PER_SESSION) { - log::verbose("initialize transaction, dev={}, label={}", p_dev->rc_addr, - lbl); + log::verbose("initialize transaction, dev={}, label={}", p_dev->rc_addr, lbl); if (alarm_is_scheduled(transaction_set->transaction[lbl].timer)) { - log::warn("clearing pending timer event, dev={}, label={}", - p_dev->rc_addr, lbl); + log::warn("clearing pending timer event, dev={}, label={}", p_dev->rc_addr, lbl); clear_cmd_timeout(p_dev, lbl); } transaction_set->transaction[lbl] = { - .in_use = false, - .label = lbl, - .context = - { - .rc_addr = RawAddress::kEmpty, - .label = MAX_LABEL, - .opcode = AVRC_OP_INVALID, - .command = {}, - }, - .timer = nullptr, + .in_use = false, + .label = lbl, + .context = + { + .rc_addr = RawAddress::kEmpty, + .label = MAX_LABEL, + .opcode = AVRC_OP_INVALID, + .command = {}, + }, + .timer = nullptr, }; } } @@ -5395,7 +5121,9 @@ static void initialize_transaction(btif_rc_device_cb_t* p_dev, uint8_t lbl) { * Returns void ******************************************************************************/ void init_all_transactions(btif_rc_device_cb_t* p_dev) { - if (p_dev == nullptr) return; + if (p_dev == nullptr) { + return; + } for (uint8_t i = 0; i < MAX_TRANSACTIONS_PER_SESSION; ++i) { initialize_transaction(p_dev, i); } @@ -5410,9 +5138,10 @@ void init_all_transactions(btif_rc_device_cb_t* p_dev) { * * Returns bt_status_t ******************************************************************************/ -rc_transaction_t* get_transaction_by_lbl(btif_rc_device_cb_t* p_dev, - uint8_t lbl) { - if (p_dev == nullptr) return nullptr; +rc_transaction_t* get_transaction_by_lbl(btif_rc_device_cb_t* p_dev, uint8_t lbl) { + if (p_dev == nullptr) { + return nullptr; + } rc_transaction_t* transaction = NULL; rc_transaction_set_t* transaction_set = &(p_dev->transaction_set); @@ -5437,10 +5166,11 @@ rc_transaction_t* get_transaction_by_lbl(btif_rc_device_cb_t* p_dev, * * Returns bt_status_t ******************************************************************************/ -static bt_status_t get_transaction(btif_rc_device_cb_t* p_dev, - rc_transaction_context_t& context, +static bt_status_t get_transaction(btif_rc_device_cb_t* p_dev, rc_transaction_context_t& context, rc_transaction_t** ptransaction) { - if (p_dev == NULL) return BT_STATUS_PARM_INVALID; + if (p_dev == NULL) { + return BT_STATUS_PARM_INVALID; + } rc_transaction_set_t* transaction_set = &(p_dev->transaction_set); std::unique_lock lock(transaction_set->label_lock); @@ -5451,8 +5181,8 @@ static bt_status_t get_transaction(btif_rc_device_cb_t* p_dev, transaction_set->transaction[i].context = context; transaction_set->transaction[i].in_use = true; *ptransaction = &(transaction_set->transaction[i]); - log::verbose("Assigned transaction, dev={}, transaction={}", - p_dev->rc_addr, dump_transaction(*ptransaction)); + log::verbose("Assigned transaction, dev={}, transaction={}", p_dev->rc_addr, + dump_transaction(*ptransaction)); return BT_STATUS_SUCCESS; } } @@ -5483,12 +5213,11 @@ static void start_transaction_timer(btif_rc_device_cb_t* p_dev, uint8_t label, } std::stringstream ss; - ss << "btif_rc." << p_dev->rc_addr.ToColonSepHexString() << "." - << transaction->label; + ss << "btif_rc." << p_dev->rc_addr.ToColonSepHexString() << "." << transaction->label; alarm_free(transaction->timer); transaction->timer = alarm_new(ss.str().c_str()); - alarm_set_on_mloop(transaction->timer, timeout_ms, - btif_rc_transaction_timer_timeout, &transaction->context); + alarm_set_on_mloop(transaction->timer, timeout_ms, btif_rc_transaction_timer_timeout, + &transaction->context); } /******************************************************************************* @@ -5514,8 +5243,8 @@ void release_transaction(btif_rc_device_cb_t* p_dev, uint8_t lbl) { log::verbose("Released transaction, dev={}, label={}", p_dev->rc_addr, lbl); initialize_transaction(p_dev, lbl); } else { - log::warn("Failed to release transaction, could not find dev={}, label={}", - p_dev->rc_addr, lbl); + log::warn("Failed to release transaction, could not find dev={}, label={}", p_dev->rc_addr, + lbl); } } @@ -5541,8 +5270,7 @@ static std::string dump_transaction(const rc_transaction_t* const transaction) { case AVRC_OP_VENDOR: ss << " pdu_id=" << dump_rc_pdu(context.command.vendor.pdu_id); if (context.command.vendor.pdu_id == AVRC_PDU_REGISTER_NOTIFICATION) { - ss << " event_id=" - << dump_rc_notification_event_id(context.command.vendor.event_id); + ss << " event_id=" << dump_rc_notification_event_id(context.command.vendor.event_id); } break; case AVRC_OP_BROWSE: @@ -5558,8 +5286,7 @@ static std::string dump_transaction(const rc_transaction_t* const transaction) { ss << " alarm="; alarm_t* alarm = transaction->timer; if (alarm != nullptr) { - ss << "(set=" << alarm_is_scheduled(alarm) - << " left=" << alarm_get_remaining_ms(alarm) << ")"; + ss << "(set=" << alarm_is_scheduled(alarm) << " left=" << alarm_get_remaining_ms(alarm) << ")"; } else { ss << "null"; } @@ -5574,8 +5301,7 @@ static std::string dump_transaction(const rc_transaction_t* const transaction) { * Returns None * **************************************************************************/ -static void vendor_cmd_timeout_handler(btif_rc_device_cb_t* p_dev, - uint8_t label, +static void vendor_cmd_timeout_handler(btif_rc_device_cb_t* p_dev, uint8_t label, rc_vendor_context_t* p_context) { if (p_dev == NULL) { log::error("p_dev NULL"); @@ -5585,9 +5311,8 @@ static void vendor_cmd_timeout_handler(btif_rc_device_cb_t* p_dev, tAVRC_RESPONSE avrc_response = {0}; tBTA_AV_META_MSG meta_msg = {.rc_handle = p_dev->rc_handle}; - log::warn("timeout, addr={}, label={}, pdu_id={}, event_id={}", - p_dev->rc_addr, label, dump_rc_pdu(p_context->pdu_id), - dump_rc_notification_event_id(p_context->event_id)); + log::warn("timeout, addr={}, label={}, pdu_id={}, event_id={}", p_dev->rc_addr, label, + dump_rc_pdu(p_context->pdu_id), dump_rc_notification_event_id(p_context->event_id)); switch (p_context->pdu_id) { case AVRC_PDU_REGISTER_NOTIFICATION: @@ -5657,8 +5382,7 @@ static void vendor_cmd_timeout_handler(btif_rc_device_cb_t* p_dev, * Returns None * **************************************************************************/ -static void browse_cmd_timeout_handler(btif_rc_device_cb_t* p_dev, - uint8_t label, +static void browse_cmd_timeout_handler(btif_rc_device_cb_t* p_dev, uint8_t label, rc_browse_context_t* p_context) { if (p_dev == NULL) { log::error("p_dev NULL"); @@ -5667,13 +5391,13 @@ static void browse_cmd_timeout_handler(btif_rc_device_cb_t* p_dev, tAVRC_RESPONSE avrc_response = {0}; tBTA_AV_META_MSG meta_msg = { - .rc_handle = p_dev->rc_handle, - .len = 0, - .label = 0, - .code = 0, - .company_id = 0, - .p_data = nullptr, - .p_msg = nullptr, + .rc_handle = p_dev->rc_handle, + .len = 0, + .label = 0, + .code = 0, + .company_id = 0, + .p_data = nullptr, + .p_msg = nullptr, }; log::warn("timeout, addr={}, label={}, pdu_id={}", p_dev->rc_addr, label, @@ -5710,16 +5434,15 @@ static void browse_cmd_timeout_handler(btif_rc_device_cb_t* p_dev, * Returns None * **************************************************************************/ -static void passthru_cmd_timeout_handler(btif_rc_device_cb_t* p_dev, - uint8_t label, +static void passthru_cmd_timeout_handler(btif_rc_device_cb_t* p_dev, uint8_t label, rc_passthru_context_t* p_context) { if (p_dev == NULL) { log::error("p_dev NULL"); return; } - log::warn("timeout, addr={}, label={}, rc_id={}, key_state={}", - p_dev->rc_addr, label, p_context->rc_id, p_context->key_state); + log::warn("timeout, addr={}, label={}, rc_id={}, key_state={}", p_dev->rc_addr, label, + p_context->rc_id, p_context->key_state); // Other requests are wrapped in a tAVRC_RESPONSE response object, but these // passthru events are not in there. As well, the upper layers don't handle @@ -5736,8 +5459,7 @@ static void passthru_cmd_timeout_handler(btif_rc_device_cb_t* p_dev, * Returns None * **************************************************************************/ -static void btif_rc_transaction_timeout_handler(uint16_t /* event */, - char* data) { +static void btif_rc_transaction_timeout_handler(uint16_t /* event */, char* data) { rc_transaction_context_t* p_context = (rc_transaction_context_t*)data; if (p_context == nullptr) { log::error("p_context is null"); @@ -5759,8 +5481,7 @@ static void btif_rc_transaction_timeout_handler(uint16_t /* event */, browse_cmd_timeout_handler(p_dev, label, &(p_context->command.browse)); break; case AVRC_OP_PASS_THRU: - passthru_cmd_timeout_handler(p_dev, label, - &(p_context->command.passthru)); + passthru_cmd_timeout_handler(p_dev, label, &(p_context->command.passthru)); break; default: log::warn("received timeout for unknown opcode={}", p_context->opcode); @@ -5830,8 +5551,7 @@ void btif_debug_rc_dump(int fd) { std::unique_lock lock(transaction_set->label_lock); dprintf(fd, " Transaction Labels:\n"); for (auto j = 0; j < MAX_TRANSACTIONS_PER_SESSION; ++j) { - dprintf(fd, " %s\n", - dump_transaction(&transaction_set->transaction[j]).c_str()); + dprintf(fd, " %s\n", dump_transaction(&transaction_set->transaction[j]).c_str()); } } } diff --git a/system/btif/src/btif_sdp.cc b/system/btif/src/btif_sdp.cc index 7688c3cc766..bc336acbf65 100644 --- a/system/btif/src/btif_sdp.cc +++ b/system/btif/src/btif_sdp.cc @@ -48,16 +48,15 @@ using namespace bluetooth; *****************************************************************************/ bt_status_t sdp_server_init(); void sdp_server_cleanup(); -bt_status_t create_sdp_record(bluetooth_sdp_record* records, - int* record_handles); +bt_status_t create_sdp_record(bluetooth_sdp_record* records, int* record_handles); bt_status_t remove_sdp_record(int record_handle); void on_create_record_event(int handle); void on_remove_record_event(int handle); // Utility functions: int get_sdp_records_size(bluetooth_sdp_record* in_record, int count); -void copy_sdp_records(bluetooth_sdp_record* in_records, - bluetooth_sdp_record* out_records, int count); +void copy_sdp_records(bluetooth_sdp_record* in_records, bluetooth_sdp_record* out_records, + int count); /***************************************************************************** * Static variables @@ -69,30 +68,32 @@ static void btif_sdp_search_comp_evt(uint16_t event, char* p_param) { tBTA_SDP_SEARCH_COMP* evt_data = (tBTA_SDP_SEARCH_COMP*)p_param; log::verbose("event = {}", event); - if (event != BTA_SDP_SEARCH_COMP_EVT) return; + if (event != BTA_SDP_SEARCH_COMP_EVT) { + return; + } - HAL_CBACK(bt_sdp_callbacks, sdp_search_cb, (bt_status_t)evt_data->status, - evt_data->remote_addr, evt_data->uuid, evt_data->record_count, - evt_data->records); + HAL_CBACK(bt_sdp_callbacks, sdp_search_cb, (bt_status_t)evt_data->status, evt_data->remote_addr, + evt_data->uuid, evt_data->record_count, evt_data->records); } -static void sdp_search_comp_copy_cb(uint16_t event, char* p_dest, - const char* p_src) { +static void sdp_search_comp_copy_cb(uint16_t event, char* p_dest, const char* p_src) { tBTA_SDP_SEARCH_COMP* p_dest_data = (tBTA_SDP_SEARCH_COMP*)p_dest; tBTA_SDP_SEARCH_COMP* p_src_data = (tBTA_SDP_SEARCH_COMP*)p_src; - if (!p_src) return; + if (!p_src) { + return; + } - if (event != BTA_SDP_SEARCH_COMP_EVT) return; + if (event != BTA_SDP_SEARCH_COMP_EVT) { + return; + } maybe_non_aligned_memcpy(p_dest_data, p_src_data, sizeof(*p_src_data)); - copy_sdp_records(p_src_data->records, p_dest_data->records, - p_src_data->record_count); + copy_sdp_records(p_src_data->records, p_dest_data->records, p_src_data->record_count); } -static void sdp_dm_cback(tBTA_SDP_EVT event, tBTA_SDP* p_data, - void* user_data) { +static void sdp_dm_cback(tBTA_SDP_EVT event, tBTA_SDP* p_data, void* user_data) { switch (event) { case BTA_SDP_SEARCH_COMP_EVT: { int size = sizeof(tBTA_SDP); @@ -100,8 +101,8 @@ static void sdp_dm_cback(tBTA_SDP_EVT event, tBTA_SDP* p_data, p_data->sdp_search_comp.record_count); /* need to deep copy the record content */ - btif_transfer_context(btif_sdp_search_comp_evt, event, (char*)p_data, - size, sdp_search_comp_copy_cb); + btif_transfer_context(btif_sdp_search_comp_evt, event, (char*)p_data, size, + sdp_search_comp_copy_cb); break; } case BTA_SDP_CREATE_RECORD_USER_EVT: { @@ -144,8 +145,7 @@ static bt_status_t search(RawAddress* bd_addr, const Uuid& uuid) { } static const btsdp_interface_t sdp_if = { - sizeof(btsdp_interface_t), init, deinit, search, create_sdp_record, - remove_sdp_record}; + sizeof(btsdp_interface_t), init, deinit, search, create_sdp_record, remove_sdp_record}; const btsdp_interface_t* btif_sdp_get_interface(void) { log::verbose(""); diff --git a/system/btif/src/btif_sdp_server.cc b/system/btif/src/btif_sdp_server.cc index 9dea4988fba..6ffb5fd4c7d 100644 --- a/system/btif/src/btif_sdp_server.cc +++ b/system/btif/src/btif_sdp_server.cc @@ -101,7 +101,7 @@ static int free_sdp_slot(int id); * point will be linked to a specific SDP handle. * 2) createRecord() requests the BTU task(thread) to call a callback in SDP * which creates the actual record, and updates the ID<->SDPHandle map - * based on the ID beeing passed to BTA as user_data. + * based on the ID being passed to BTA as user_data. *****************************************************************************/ static void init_sdp_slots() { @@ -127,9 +127,9 @@ void sdp_server_cleanup() { int i; for (i = 0; i < MAX_SDP_SLOTS; i++) { /*remove_sdp_record(i); we cannot send messages to the other threads, since - * they might - * have been shut down already. Just do local cleanup. - */ + * they might + * have been shut down already. Just do local cleanup. + */ free_sdp_slot(i); } } @@ -154,28 +154,25 @@ int get_sdp_records_size(bluetooth_sdp_record* in_record, int count) { /* Deep copy all content of in_records into out_records. * out_records must point to a chunk of memory large enough to contain all * the data. Use getSdpRecordsSize() to calculate the needed size. */ -void copy_sdp_records(bluetooth_sdp_record* in_records, - bluetooth_sdp_record* out_records, int count) { +void copy_sdp_records(bluetooth_sdp_record* in_records, bluetooth_sdp_record* out_records, + int count) { int i; bluetooth_sdp_record* in_record; bluetooth_sdp_record* out_record; - char* free_ptr = - (char*)(&out_records[count]); /* set pointer to after the last entry */ + char* free_ptr = (char*)(&out_records[count]); /* set pointer to after the last entry */ for (i = 0; i < count; i++) { in_record = &in_records[i]; out_record = &out_records[i]; *out_record = *in_record; - if (in_record->hdr.service_name == NULL || - in_record->hdr.service_name_length == 0) { + if (in_record->hdr.service_name == NULL || in_record->hdr.service_name_length == 0) { out_record->hdr.service_name = NULL; out_record->hdr.service_name_length = 0; } else { out_record->hdr.service_name = free_ptr; // Update service_name pointer // Copy string - memcpy(free_ptr, in_record->hdr.service_name, - in_record->hdr.service_name_length); + memcpy(free_ptr, in_record->hdr.service_name, in_record->hdr.service_name_length); free_ptr += in_record->hdr.service_name_length; *(free_ptr) = '\0'; // Set '\0' termination of string free_ptr++; @@ -267,9 +264,8 @@ static const sdp_slot_t* start_create_sdp(int id) { std::unique_lock lock(sdp_lock); if (sdp_slots[id].state != SDP_RECORD_ALLOCED) { /* The record have been removed before this event occurred - e.g. deinit */ - log::error( - "failed - state for id {} is sdp_slots[id].state = {} expected {}", id, - sdp_slots[id].state, SDP_RECORD_ALLOCED); + log::error("failed - state for id {} is sdp_slots[id].state = {} expected {}", id, + sdp_slots[id].state, SDP_RECORD_ALLOCED); return NULL; } @@ -281,14 +277,15 @@ static void set_sdp_handle(int id, int handle) { sdp_slots[id].sdp_handle = handle; } -bt_status_t create_sdp_record(bluetooth_sdp_record* record, - int* record_handle) { +bt_status_t create_sdp_record(bluetooth_sdp_record* record, int* record_handle) { int handle; handle = alloc_sdp_slot(record); log::verbose("handle = 0x{:08x}", handle); - if (handle < 0) return BT_STATUS_NOMEM; + if (handle < 0) { + return BT_STATUS_NOMEM; + } BTA_SdpCreateRecordByUser(INT_TO_PTR(handle)); @@ -458,8 +455,7 @@ static int add_maps_sdp(const bluetooth_sdp_mas_record* rec) { } /* add service class */ - status &= get_legacy_stack_sdp_api()->handle.SDP_AddServiceClassIdList( - sdp_handle, 1, &service); + status &= get_legacy_stack_sdp_api()->handle.SDP_AddServiceClassIdList(sdp_handle, 1, &service); memset(protoList, 0, 3 * sizeof(tSDP_PROTOCOL_ELEM)); /* add protocol list, including RFCOMM scn */ @@ -470,46 +466,43 @@ static int add_maps_sdp(const bluetooth_sdp_mas_record* rec) { protoList[1].params[0] = rec->hdr.rfcomm_channel_number; protoList[2].protocol_uuid = UUID_PROTOCOL_OBEX; protoList[2].num_params = 0; - status &= get_legacy_stack_sdp_api()->handle.SDP_AddProtocolList( - sdp_handle, 3, protoList); + status &= get_legacy_stack_sdp_api()->handle.SDP_AddProtocolList(sdp_handle, 3, protoList); /* Add a name entry */ status &= get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - sdp_handle, (uint16_t)ATTR_ID_SERVICE_NAME, (uint8_t)TEXT_STR_DESC_TYPE, - (uint32_t)(rec->hdr.service_name_length + 1), - (uint8_t*)rec->hdr.service_name); + sdp_handle, (uint16_t)ATTR_ID_SERVICE_NAME, (uint8_t)TEXT_STR_DESC_TYPE, + (uint32_t)(rec->hdr.service_name_length + 1), (uint8_t*)rec->hdr.service_name); /* Add in the Bluetooth Profile Descriptor List */ status &= get_legacy_stack_sdp_api()->handle.SDP_AddProfileDescriptorList( - sdp_handle, UUID_SERVCLASS_MAP_PROFILE, rec->hdr.profile_version); + sdp_handle, UUID_SERVCLASS_MAP_PROFILE, rec->hdr.profile_version); /* Add MAS instance ID */ - status &= get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - sdp_handle, ATTR_ID_MAS_INSTANCE_ID, UINT_DESC_TYPE, (uint32_t)1, - (uint8_t*)&rec->mas_instance_id); + status &= get_legacy_stack_sdp_api()->handle.SDP_AddAttribute(sdp_handle, ATTR_ID_MAS_INSTANCE_ID, + UINT_DESC_TYPE, (uint32_t)1, + (uint8_t*)&rec->mas_instance_id); /* Add supported message types */ status &= get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - sdp_handle, ATTR_ID_SUPPORTED_MSG_TYPE, UINT_DESC_TYPE, (uint32_t)1, - (uint8_t*)&rec->supported_message_types); + sdp_handle, ATTR_ID_SUPPORTED_MSG_TYPE, UINT_DESC_TYPE, (uint32_t)1, + (uint8_t*)&rec->supported_message_types); /* Add supported feature */ UINT32_TO_BE_STREAM(p_temp, rec->supported_features); status &= get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - sdp_handle, ATTR_ID_MAP_SUPPORTED_FEATURES, UINT_DESC_TYPE, (uint32_t)4, - temp); + sdp_handle, ATTR_ID_MAP_SUPPORTED_FEATURES, UINT_DESC_TYPE, (uint32_t)4, temp); /* Add the L2CAP PSM if present */ if (rec->hdr.l2cap_psm != -1) { p_temp = temp; // The macro modifies p_temp, hence rewind. UINT16_TO_BE_STREAM(p_temp, rec->hdr.l2cap_psm); status &= get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - sdp_handle, ATTR_ID_GOEP_L2CAP_PSM, UINT_DESC_TYPE, (uint32_t)2, temp); + sdp_handle, ATTR_ID_GOEP_L2CAP_PSM, UINT_DESC_TYPE, (uint32_t)2, temp); } /* Make the service browseable */ status &= get_legacy_stack_sdp_api()->handle.SDP_AddUuidSequence( - sdp_handle, ATTR_ID_BROWSE_GROUP_LIST, 1, &browse); + sdp_handle, ATTR_ID_BROWSE_GROUP_LIST, 1, &browse); if (!status) { if (!get_legacy_stack_sdp_api()->handle.SDP_DeleteRecord(sdp_handle)) { @@ -542,8 +535,7 @@ static int add_mapc_sdp(const bluetooth_sdp_mns_record* rec) { } /* add service class */ - status &= get_legacy_stack_sdp_api()->handle.SDP_AddServiceClassIdList( - sdp_handle, 1, &service); + status &= get_legacy_stack_sdp_api()->handle.SDP_AddServiceClassIdList(sdp_handle, 1, &service); memset(protoList, 0, 3 * sizeof(tSDP_PROTOCOL_ELEM)); /* add protocol list, including RFCOMM scn */ @@ -554,36 +546,33 @@ static int add_mapc_sdp(const bluetooth_sdp_mns_record* rec) { protoList[1].params[0] = rec->hdr.rfcomm_channel_number; protoList[2].protocol_uuid = UUID_PROTOCOL_OBEX; protoList[2].num_params = 0; - status &= get_legacy_stack_sdp_api()->handle.SDP_AddProtocolList( - sdp_handle, 3, protoList); + status &= get_legacy_stack_sdp_api()->handle.SDP_AddProtocolList(sdp_handle, 3, protoList); /* Add a name entry */ status &= get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - sdp_handle, (uint16_t)ATTR_ID_SERVICE_NAME, (uint8_t)TEXT_STR_DESC_TYPE, - (uint32_t)(rec->hdr.service_name_length + 1), - (uint8_t*)rec->hdr.service_name); + sdp_handle, (uint16_t)ATTR_ID_SERVICE_NAME, (uint8_t)TEXT_STR_DESC_TYPE, + (uint32_t)(rec->hdr.service_name_length + 1), (uint8_t*)rec->hdr.service_name); /* Add in the Bluetooth Profile Descriptor List */ status &= get_legacy_stack_sdp_api()->handle.SDP_AddProfileDescriptorList( - sdp_handle, UUID_SERVCLASS_MAP_PROFILE, rec->hdr.profile_version); + sdp_handle, UUID_SERVCLASS_MAP_PROFILE, rec->hdr.profile_version); /* Add supported feature */ UINT32_TO_BE_STREAM(p_temp, rec->supported_features); status &= get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - sdp_handle, ATTR_ID_MAP_SUPPORTED_FEATURES, UINT_DESC_TYPE, (uint32_t)4, - temp); + sdp_handle, ATTR_ID_MAP_SUPPORTED_FEATURES, UINT_DESC_TYPE, (uint32_t)4, temp); /* Add the L2CAP PSM if present */ if (rec->hdr.l2cap_psm != -1) { p_temp = temp; // The macro modifies p_temp, hence rewind. UINT16_TO_BE_STREAM(p_temp, rec->hdr.l2cap_psm); status &= get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - sdp_handle, ATTR_ID_GOEP_L2CAP_PSM, UINT_DESC_TYPE, (uint32_t)2, temp); + sdp_handle, ATTR_ID_GOEP_L2CAP_PSM, UINT_DESC_TYPE, (uint32_t)2, temp); } /* Make the service browseable */ status &= get_legacy_stack_sdp_api()->handle.SDP_AddUuidSequence( - sdp_handle, ATTR_ID_BROWSE_GROUP_LIST, 1, &browse); + sdp_handle, ATTR_ID_BROWSE_GROUP_LIST, 1, &browse); if (!status) { if (!get_legacy_stack_sdp_api()->handle.SDP_DeleteRecord(sdp_handle)) { @@ -612,22 +601,20 @@ static int add_pbapc_sdp(const bluetooth_sdp_pce_record* rec) { return sdp_handle; } - status &= get_legacy_stack_sdp_api()->handle.SDP_AddServiceClassIdList( - sdp_handle, 1, &service); + status &= get_legacy_stack_sdp_api()->handle.SDP_AddServiceClassIdList(sdp_handle, 1, &service); /* Add a name entry */ status &= get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - sdp_handle, (uint16_t)ATTR_ID_SERVICE_NAME, (uint8_t)TEXT_STR_DESC_TYPE, - (uint32_t)(rec->hdr.service_name_length + 1), - (uint8_t*)rec->hdr.service_name); + sdp_handle, (uint16_t)ATTR_ID_SERVICE_NAME, (uint8_t)TEXT_STR_DESC_TYPE, + (uint32_t)(rec->hdr.service_name_length + 1), (uint8_t*)rec->hdr.service_name); /* Add in the Bluetooth Profile Descriptor List */ status &= get_legacy_stack_sdp_api()->handle.SDP_AddProfileDescriptorList( - sdp_handle, UUID_SERVCLASS_PHONE_ACCESS, rec->hdr.profile_version); + sdp_handle, UUID_SERVCLASS_PHONE_ACCESS, rec->hdr.profile_version); /* Make the service browseable */ status &= get_legacy_stack_sdp_api()->handle.SDP_AddUuidSequence( - sdp_handle, ATTR_ID_BROWSE_GROUP_LIST, 1, &browse); + sdp_handle, ATTR_ID_BROWSE_GROUP_LIST, 1, &browse); if (!status) { if (!get_legacy_stack_sdp_api()->handle.SDP_DeleteRecord(sdp_handle)) { @@ -660,8 +647,7 @@ static int add_pbaps_sdp(const bluetooth_sdp_pse_record* rec) { } /* add service class */ - status &= get_legacy_stack_sdp_api()->handle.SDP_AddServiceClassIdList( - sdp_handle, 1, &service); + status &= get_legacy_stack_sdp_api()->handle.SDP_AddServiceClassIdList(sdp_handle, 1, &service); memset(protoList, 0, 3 * sizeof(tSDP_PROTOCOL_ELEM)); /* add protocol list, including RFCOMM scn */ @@ -672,16 +658,13 @@ static int add_pbaps_sdp(const bluetooth_sdp_pse_record* rec) { protoList[1].params[0] = rec->hdr.rfcomm_channel_number; protoList[2].protocol_uuid = UUID_PROTOCOL_OBEX; protoList[2].num_params = 0; - status &= get_legacy_stack_sdp_api()->handle.SDP_AddProtocolList( - sdp_handle, 3, protoList); + status &= get_legacy_stack_sdp_api()->handle.SDP_AddProtocolList(sdp_handle, 3, protoList); /* Add a name entry */ status &= get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - sdp_handle, (uint16_t)ATTR_ID_SERVICE_NAME, (uint8_t)TEXT_STR_DESC_TYPE, - (uint32_t)(rec->hdr.service_name_length + 1), - (uint8_t*)rec->hdr.service_name); - if (bluetooth::common::init_flags:: - pbap_pse_dynamic_version_upgrade_is_enabled()) { + sdp_handle, (uint16_t)ATTR_ID_SERVICE_NAME, (uint8_t)TEXT_STR_DESC_TYPE, + (uint32_t)(rec->hdr.service_name_length + 1), (uint8_t*)rec->hdr.service_name); + if (bluetooth::common::init_flags::pbap_pse_dynamic_version_upgrade_is_enabled()) { /* PBAP 1.1.1 repositories bits Bit 0 = Local Phonebook @@ -689,43 +672,38 @@ static int add_pbaps_sdp(const bluetooth_sdp_pse_record* rec) { Bit 2~7 reserved for future use */ uint8_t supported_repositories_1_1_mask = 0x03; uint8_t supported_repositories_1_1 = - ((uint8_t)rec->supported_repositories) & - supported_repositories_1_1_mask; + ((uint8_t)rec->supported_repositories) & supported_repositories_1_1_mask; status &= get_legacy_stack_sdp_api()->handle.SDP_AddProfileDescriptorList( - sdp_handle, UUID_SERVCLASS_PHONE_ACCESS, 0x0101); + sdp_handle, UUID_SERVCLASS_PHONE_ACCESS, 0x0101); /* Add supported repositories 1 byte */ status &= get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - sdp_handle, ATTR_ID_SUPPORTED_REPOSITORIES, UINT_DESC_TYPE, (uint32_t)1, - (uint8_t*)&supported_repositories_1_1); - log::verbose("supported_repositories_1_1: 0x{:x}", - supported_repositories_1_1); - sdp_save_local_pse_record_attributes( - rec->hdr.rfcomm_channel_number, rec->hdr.l2cap_psm, - rec->hdr.profile_version, rec->supported_features, - rec->supported_repositories); + sdp_handle, ATTR_ID_SUPPORTED_REPOSITORIES, UINT_DESC_TYPE, (uint32_t)1, + (uint8_t*)&supported_repositories_1_1); + log::verbose("supported_repositories_1_1: 0x{:x}", supported_repositories_1_1); + sdp_save_local_pse_record_attributes(rec->hdr.rfcomm_channel_number, rec->hdr.l2cap_psm, + rec->hdr.profile_version, rec->supported_features, + rec->supported_repositories); } else { /* Add in the Bluetooth Profile Descriptor List */ status &= get_legacy_stack_sdp_api()->handle.SDP_AddProfileDescriptorList( - sdp_handle, UUID_SERVCLASS_PHONE_ACCESS, rec->hdr.profile_version); + sdp_handle, UUID_SERVCLASS_PHONE_ACCESS, rec->hdr.profile_version); /* Add supported repositories 1 byte */ status &= get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - sdp_handle, ATTR_ID_SUPPORTED_REPOSITORIES, UINT_DESC_TYPE, (uint32_t)1, - (uint8_t*)&rec->supported_repositories); + sdp_handle, ATTR_ID_SUPPORTED_REPOSITORIES, UINT_DESC_TYPE, (uint32_t)1, + (uint8_t*)&rec->supported_repositories); /* Add supported feature 4 bytes*/ UINT32_TO_BE_STREAM(p_temp, rec->supported_features); status &= get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - sdp_handle, ATTR_ID_PBAP_SUPPORTED_FEATURES, UINT_DESC_TYPE, - (uint32_t)4, temp); + sdp_handle, ATTR_ID_PBAP_SUPPORTED_FEATURES, UINT_DESC_TYPE, (uint32_t)4, temp); /* Add the L2CAP PSM if present */ if (rec->hdr.l2cap_psm != -1) { p_temp = temp; // The macro modifies p_temp, hence rewind. UINT16_TO_BE_STREAM(p_temp, rec->hdr.l2cap_psm); status &= get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - sdp_handle, ATTR_ID_GOEP_L2CAP_PSM, UINT_DESC_TYPE, (uint32_t)2, - temp); + sdp_handle, ATTR_ID_GOEP_L2CAP_PSM, UINT_DESC_TYPE, (uint32_t)2, temp); } #if 0 status &= get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( @@ -759,7 +737,7 @@ static int add_pbaps_sdp(const bluetooth_sdp_pse_record* rec) { /* Make the service browseable */ status &= get_legacy_stack_sdp_api()->handle.SDP_AddUuidSequence( - sdp_handle, ATTR_ID_BROWSE_GROUP_LIST, 1, &browse); + sdp_handle, ATTR_ID_BROWSE_GROUP_LIST, 1, &browse); if (!status) { if (!get_legacy_stack_sdp_api()->handle.SDP_DeleteRecord(sdp_handle)) { @@ -797,8 +775,7 @@ static int add_opps_sdp(const bluetooth_sdp_ops_record* rec) { } /* add service class */ - status &= get_legacy_stack_sdp_api()->handle.SDP_AddServiceClassIdList( - sdp_handle, 1, &service); + status &= get_legacy_stack_sdp_api()->handle.SDP_AddServiceClassIdList(sdp_handle, 1, &service); memset(protoList, 0, 3 * sizeof(tSDP_PROTOCOL_ELEM)); /* add protocol list, including RFCOMM scn */ @@ -809,18 +786,16 @@ static int add_opps_sdp(const bluetooth_sdp_ops_record* rec) { protoList[1].params[0] = rec->hdr.rfcomm_channel_number; protoList[2].protocol_uuid = UUID_PROTOCOL_OBEX; protoList[2].num_params = 0; - status &= get_legacy_stack_sdp_api()->handle.SDP_AddProtocolList( - sdp_handle, 3, protoList); + status &= get_legacy_stack_sdp_api()->handle.SDP_AddProtocolList(sdp_handle, 3, protoList); /* Add a name entry */ status &= get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - sdp_handle, (uint16_t)ATTR_ID_SERVICE_NAME, (uint8_t)TEXT_STR_DESC_TYPE, - (uint32_t)(rec->hdr.service_name_length + 1), - (uint8_t*)rec->hdr.service_name); + sdp_handle, (uint16_t)ATTR_ID_SERVICE_NAME, (uint8_t)TEXT_STR_DESC_TYPE, + (uint32_t)(rec->hdr.service_name_length + 1), (uint8_t*)rec->hdr.service_name); /* Add in the Bluetooth Profile Descriptor List */ status &= get_legacy_stack_sdp_api()->handle.SDP_AddProfileDescriptorList( - sdp_handle, UUID_SERVCLASS_OBEX_OBJECT_PUSH, rec->hdr.profile_version); + sdp_handle, UUID_SERVCLASS_OBEX_OBJECT_PUSH, rec->hdr.profile_version); /* add sequence for supported types */ for (i = 0, j = 0; i < rec->supported_formats_list_len; i++) { @@ -830,21 +805,20 @@ static int add_opps_sdp(const bluetooth_sdp_ops_record* rec) { } status &= get_legacy_stack_sdp_api()->handle.SDP_AddSequence( - sdp_handle, (uint16_t)ATTR_ID_SUPPORTED_FORMATS_LIST, - (uint8_t)rec->supported_formats_list_len, desc_type, type_len, - type_value); + sdp_handle, (uint16_t)ATTR_ID_SUPPORTED_FORMATS_LIST, + (uint8_t)rec->supported_formats_list_len, desc_type, type_len, type_value); /* Add the L2CAP PSM if present */ if (rec->hdr.l2cap_psm != -1) { p_temp = temp; // The macro modifies p_temp, hence rewind. UINT16_TO_BE_STREAM(p_temp, rec->hdr.l2cap_psm); status &= get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - sdp_handle, ATTR_ID_GOEP_L2CAP_PSM, UINT_DESC_TYPE, (uint32_t)2, temp); + sdp_handle, ATTR_ID_GOEP_L2CAP_PSM, UINT_DESC_TYPE, (uint32_t)2, temp); } /* Make the service browseable */ status &= get_legacy_stack_sdp_api()->handle.SDP_AddUuidSequence( - sdp_handle, ATTR_ID_BROWSE_GROUP_LIST, 1, &browse); + sdp_handle, ATTR_ID_BROWSE_GROUP_LIST, 1, &browse); if (!status) { if (!get_legacy_stack_sdp_api()->handle.SDP_DeleteRecord(sdp_handle)) { @@ -882,8 +856,7 @@ static int add_saps_sdp(const bluetooth_sdp_sap_record* rec) { services[1] = UUID_SERVCLASS_GENERIC_TELEPHONY; // add service class - status &= get_legacy_stack_sdp_api()->handle.SDP_AddServiceClassIdList( - sdp_handle, 2, services); + status &= get_legacy_stack_sdp_api()->handle.SDP_AddServiceClassIdList(sdp_handle, 2, services); memset(protoList, 0, 2 * sizeof(tSDP_PROTOCOL_ELEM)); // add protocol list, including RFCOMM scn @@ -892,22 +865,20 @@ static int add_saps_sdp(const bluetooth_sdp_sap_record* rec) { protoList[1].protocol_uuid = UUID_PROTOCOL_RFCOMM; protoList[1].num_params = 1; protoList[1].params[0] = rec->hdr.rfcomm_channel_number; - status &= get_legacy_stack_sdp_api()->handle.SDP_AddProtocolList( - sdp_handle, 2, protoList); + status &= get_legacy_stack_sdp_api()->handle.SDP_AddProtocolList(sdp_handle, 2, protoList); // Add a name entry status &= get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - sdp_handle, (uint16_t)ATTR_ID_SERVICE_NAME, (uint8_t)TEXT_STR_DESC_TYPE, - (uint32_t)(rec->hdr.service_name_length + 1), - (uint8_t*)rec->hdr.service_name); + sdp_handle, (uint16_t)ATTR_ID_SERVICE_NAME, (uint8_t)TEXT_STR_DESC_TYPE, + (uint32_t)(rec->hdr.service_name_length + 1), (uint8_t*)rec->hdr.service_name); // Add in the Bluetooth Profile Descriptor List status &= get_legacy_stack_sdp_api()->handle.SDP_AddProfileDescriptorList( - sdp_handle, UUID_SERVCLASS_SAP, rec->hdr.profile_version); + sdp_handle, UUID_SERVCLASS_SAP, rec->hdr.profile_version); // Make the service browseable status &= get_legacy_stack_sdp_api()->handle.SDP_AddUuidSequence( - sdp_handle, ATTR_ID_BROWSE_GROUP_LIST, 1, &browse); + sdp_handle, ATTR_ID_BROWSE_GROUP_LIST, 1, &browse); if (!status) { if (!get_legacy_stack_sdp_api()->handle.SDP_DeleteRecord(sdp_handle)) { @@ -936,29 +907,28 @@ static int add_mps_sdp(const bluetooth_sdp_mps_record* rec) { return sdp_handle; } - status &= get_legacy_stack_sdp_api()->handle.SDP_AddServiceClassIdList( - sdp_handle, 1, &service); + status &= get_legacy_stack_sdp_api()->handle.SDP_AddServiceClassIdList(sdp_handle, 1, &service); /* Add in the Bluetooth Profile Descriptor List */ status &= get_legacy_stack_sdp_api()->handle.SDP_AddProfileDescriptorList( - sdp_handle, UUID_SERVCLASS_MPS_PROFILE, rec->hdr.profile_version); + sdp_handle, UUID_SERVCLASS_MPS_PROFILE, rec->hdr.profile_version); /* Add supported scenarios MPSD */ status &= get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - sdp_handle, ATTR_ID_MPS_SUPPORTED_SCENARIOS_MPSD, UINT_DESC_TYPE, - (uint32_t)8, (uint8_t*)&rec->supported_scenarios_mpsd); + sdp_handle, ATTR_ID_MPS_SUPPORTED_SCENARIOS_MPSD, UINT_DESC_TYPE, (uint32_t)8, + (uint8_t*)&rec->supported_scenarios_mpsd); /* Add supported scenarios MPMD */ status &= get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - sdp_handle, ATTR_ID_MPS_SUPPORTED_SCENARIOS_MPMD, UINT_DESC_TYPE, - (uint32_t)8, (uint8_t*)&rec->supported_scenarios_mpmd); + sdp_handle, ATTR_ID_MPS_SUPPORTED_SCENARIOS_MPMD, UINT_DESC_TYPE, (uint32_t)8, + (uint8_t*)&rec->supported_scenarios_mpmd); /* Add supported dependencies */ status &= get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - sdp_handle, ATTR_ID_MPS_SUPPORTED_DEPENDENCIES, UINT_DESC_TYPE, - (uint32_t)2, (uint8_t*)&rec->supported_dependencies); + sdp_handle, ATTR_ID_MPS_SUPPORTED_DEPENDENCIES, UINT_DESC_TYPE, (uint32_t)2, + (uint8_t*)&rec->supported_dependencies); /* Make the service browseable */ status &= get_legacy_stack_sdp_api()->handle.SDP_AddUuidSequence( - sdp_handle, ATTR_ID_BROWSE_GROUP_LIST, 1, &browse); + sdp_handle, ATTR_ID_BROWSE_GROUP_LIST, 1, &browse); if (!status) { if (!get_legacy_stack_sdp_api()->handle.SDP_DeleteRecord(sdp_handle)) { diff --git a/system/btif/src/btif_sock.cc b/system/btif/src/btif_sock.cc index 6b60fa8e1c2..83a20c27a61 100644 --- a/system/btif/src/btif_sock.cc +++ b/system/btif/src/btif_sock.cc @@ -45,17 +45,13 @@ using bluetooth::Uuid; using namespace bluetooth; -static bt_status_t btsock_listen(btsock_type_t type, const char* service_name, - const Uuid* uuid, int channel, int* sock_fd, - int flags, int app_uid); -static bt_status_t btsock_connect(const RawAddress* bd_addr, btsock_type_t type, - const Uuid* uuid, int channel, int* sock_fd, - int flags, int app_uid); +static bt_status_t btsock_listen(btsock_type_t type, const char* service_name, const Uuid* uuid, + int channel, int* sock_fd, int flags, int app_uid); +static bt_status_t btsock_connect(const RawAddress* bd_addr, btsock_type_t type, const Uuid* uuid, + int channel, int* sock_fd, int flags, int app_uid); static void btsock_request_max_tx_data_length(const RawAddress& bd_addr); -static bt_status_t btsock_control_req(uint8_t dlci, const RawAddress& bd_addr, - uint8_t modem_signal, - uint8_t break_signal, - uint8_t discard_buffers, +static bt_status_t btsock_control_req(uint8_t dlci, const RawAddress& bd_addr, uint8_t modem_signal, + uint8_t break_signal, uint8_t discard_buffers, uint8_t break_signal_seq, bool fc); static void btsock_signaled(int fd, int type, int flags, uint32_t user_id); @@ -68,14 +64,14 @@ static thread_t* thread; const btsock_interface_t* btif_sock_get_interface(void) { static btsock_interface_t interface = { - sizeof(interface), - btsock_listen, - btsock_connect, - btsock_request_max_tx_data_length, - btsock_control_req, - btsock_disconnect_all, - btsock_get_l2cap_local_cid, - btsock_get_l2cap_remote_cid, + sizeof(interface), + btsock_listen, + btsock_connect, + btsock_request_max_tx_data_length, + btsock_control_req, + btsock_disconnect_all, + btsock_get_l2cap_local_cid, + btsock_get_l2cap_remote_cid, }; return &interface; @@ -124,7 +120,9 @@ bt_status_t btif_sock_init(uid_set_t* uid_set) { error:; thread_free(thread); thread = NULL; - if (thread_handle != -1) btsock_thread_exit(thread_handle); + if (thread_handle != -1) { + btsock_thread_exit(thread_handle); + } thread_handle = -1; uid_set = NULL; return BT_STATUS_SOCKET_ERROR; @@ -132,7 +130,9 @@ error:; void btif_sock_cleanup(void) { int saved_handle = thread_handle; - if (std::atomic_exchange(&thread_handle, -1) == -1) return; + if (std::atomic_exchange(&thread_handle, -1) == -1) { + return; + } btsock_thread_exit(saved_handle); btsock_rfc_cleanup(); @@ -142,18 +142,16 @@ void btif_sock_cleanup(void) { thread = NULL; } -static bt_status_t btsock_control_req(uint8_t dlci, const RawAddress& bd_addr, - uint8_t modem_signal, - uint8_t break_signal, - uint8_t discard_buffers, +static bt_status_t btsock_control_req(uint8_t dlci, const RawAddress& bd_addr, uint8_t modem_signal, + uint8_t break_signal, uint8_t discard_buffers, uint8_t break_signal_seq, bool fc) { - return btsock_rfc_control_req(dlci, bd_addr, modem_signal, break_signal, - discard_buffers, break_signal_seq, fc); + return btsock_rfc_control_req(dlci, bd_addr, modem_signal, break_signal, discard_buffers, + break_signal_seq, fc); } static bt_status_t btsock_listen(btsock_type_t type, const char* service_name, - const Uuid* service_uuid, int channel, - int* sock_fd, int flags, int app_uid) { + const Uuid* service_uuid, int channel, int* sock_fd, int flags, + int app_uid) { if ((flags & BTSOCK_FLAG_NO_SDP) == 0) { log::assert_that(sock_fd != NULL, "assert failed: sock_fd != NULL"); } @@ -162,24 +160,21 @@ static bt_status_t btsock_listen(btsock_type_t type, const char* service_name, bt_status_t status = BT_STATUS_SOCKET_ERROR; log::info( - "Attempting listen for socket connections for device: {}, type: {}, " - "channel: {}, app_uid: {}", - RawAddress::kEmpty, type, channel, app_uid); - btif_sock_connection_logger( - RawAddress::kEmpty, 0, type, SOCKET_CONNECTION_STATE_LISTENING, - SOCKET_ROLE_LISTEN, app_uid, channel, 0, 0, service_name); + "Attempting listen for socket connections for device: {}, type: {}, " + "channel: {}, app_uid: {}", + RawAddress::kEmpty, type, channel, app_uid); + btif_sock_connection_logger(RawAddress::kEmpty, 0, type, SOCKET_CONNECTION_STATE_LISTENING, + SOCKET_ROLE_LISTEN, app_uid, channel, 0, 0, service_name); switch (type) { case BTSOCK_RFCOMM: - status = btsock_rfc_listen(service_name, service_uuid, channel, sock_fd, - flags, app_uid); + status = btsock_rfc_listen(service_name, service_uuid, channel, sock_fd, flags, app_uid); break; case BTSOCK_L2CAP: - status = - btsock_l2cap_listen(service_name, channel, sock_fd, flags, app_uid); + status = btsock_l2cap_listen(service_name, channel, sock_fd, flags, app_uid); break; case BTSOCK_L2CAP_LE: - status = btsock_l2cap_listen(service_name, channel, sock_fd, - flags | BTSOCK_FLAG_LE_COC, app_uid); + status = btsock_l2cap_listen(service_name, channel, sock_fd, flags | BTSOCK_FLAG_LE_COC, + app_uid); break; case BTSOCK_SCO: status = btsock_sco_listen(sock_fd, flags); @@ -192,46 +187,42 @@ static bt_status_t btsock_listen(btsock_type_t type, const char* service_name, } if (status != BT_STATUS_SUCCESS) { log::error( - "failed to listen for socket connections for device: {}, type: {}, " - "channel: {}, app_uid: {}", - RawAddress::kEmpty, type, channel, app_uid); - btif_sock_connection_logger( - RawAddress::kEmpty, 0, type, SOCKET_CONNECTION_STATE_DISCONNECTED, - SOCKET_ROLE_LISTEN, app_uid, channel, 0, 0, service_name); + "failed to listen for socket connections for device: {}, type: {}, " + "channel: {}, app_uid: {}", + RawAddress::kEmpty, type, channel, app_uid); + btif_sock_connection_logger(RawAddress::kEmpty, 0, type, SOCKET_CONNECTION_STATE_DISCONNECTED, + SOCKET_ROLE_LISTEN, app_uid, channel, 0, 0, service_name); } return status; } -static bt_status_t btsock_connect(const RawAddress* bd_addr, btsock_type_t type, - const Uuid* uuid, int channel, int* sock_fd, - int flags, int app_uid) { +static bt_status_t btsock_connect(const RawAddress* bd_addr, btsock_type_t type, const Uuid* uuid, + int channel, int* sock_fd, int flags, int app_uid) { log::assert_that(bd_addr != NULL, "assert failed: bd_addr != NULL"); log::assert_that(sock_fd != NULL, "assert failed: sock_fd != NULL"); log::info( - "Attempting socket connection for device: {}, type: {}, channel: {}, " - "app_uid: {}", - *bd_addr, type, channel, app_uid); + "Attempting socket connection for device: {}, type: {}, channel: {}, " + "app_uid: {}", + *bd_addr, type, channel, app_uid); *sock_fd = INVALID_FD; bt_status_t status = BT_STATUS_SOCKET_ERROR; - btif_sock_connection_logger(*bd_addr, 0, type, - SOCKET_CONNECTION_STATE_CONNECTING, + btif_sock_connection_logger(*bd_addr, 0, type, SOCKET_CONNECTION_STATE_CONNECTING, SOCKET_ROLE_CONNECTION, app_uid, channel, 0, 0, uuid ? uuid->ToString().c_str() : ""); switch (type) { case BTSOCK_RFCOMM: - status = - btsock_rfc_connect(bd_addr, uuid, channel, sock_fd, flags, app_uid); + status = btsock_rfc_connect(bd_addr, uuid, channel, sock_fd, flags, app_uid); break; case BTSOCK_L2CAP: status = btsock_l2cap_connect(bd_addr, channel, sock_fd, flags, app_uid); break; case BTSOCK_L2CAP_LE: - status = btsock_l2cap_connect(bd_addr, channel, sock_fd, - (flags | BTSOCK_FLAG_LE_COC), app_uid); + status = btsock_l2cap_connect(bd_addr, channel, sock_fd, (flags | BTSOCK_FLAG_LE_COC), + app_uid); break; case BTSOCK_SCO: status = btsock_sco_connect(bd_addr, sock_fd, flags); @@ -244,11 +235,10 @@ static bt_status_t btsock_connect(const RawAddress* bd_addr, btsock_type_t type, } if (status != BT_STATUS_SUCCESS) { log::error( - "Socket connection failed for device: {}, type: {}, channel: {}, " - "app_uid: {}", - *bd_addr, type, channel, app_uid); - btif_sock_connection_logger(*bd_addr, 0, type, - SOCKET_CONNECTION_STATE_DISCONNECTED, + "Socket connection failed for device: {}, type: {}, channel: {}, " + "app_uid: {}", + *bd_addr, type, channel, app_uid); + btif_sock_connection_logger(*bd_addr, 0, type, SOCKET_CONNECTION_STATE_DISCONNECTED, SOCKET_ROLE_CONNECTION, app_uid, channel, 0, 0, uuid ? uuid->ToString().c_str() : ""); } @@ -271,8 +261,8 @@ static void btsock_signaled(int fd, int type, int flags, uint32_t user_id) { btsock_l2cap_signaled(fd, flags, user_id); break; default: - log::fatal("Invalid socket type! type={} fd={} flags={} user_id={}", type, - fd, flags, user_id); + log::fatal("Invalid socket type! type={} fd={} flags={} user_id={}", type, fd, flags, + user_id); break; } } diff --git a/system/btif/src/btif_sock_l2cap.cc b/system/btif/src/btif_sock_l2cap.cc index b2a17c8b194..1a46cb504b9 100644 --- a/system/btif/src/btif_sock_l2cap.cc +++ b/system/btif/src/btif_sock_l2cap.cc @@ -91,8 +91,7 @@ static uint32_t last_sock_id = 0; static uid_set_t* uid_set = NULL; static int pth = -1; -static void btsock_l2cap_cbk(tBTA_JV_EVT event, tBTA_JV* p_data, - uint32_t l2cap_socket_id); +static void btsock_l2cap_cbk(tBTA_JV_EVT event, tBTA_JV* p_data, uint32_t l2cap_socket_id); /* TODO: Consider to remove this buffer, as we have a buffer in l2cap as well, * and we risk @@ -109,21 +108,29 @@ static void btsock_l2cap_cbk(tBTA_JV_EVT event, tBTA_JV* p_data, * confirming the l2cap_ind until we have more space in the buffer. */ /* returns false if none - caller must free "data" memory when done with it */ -static char packet_get_head_l(l2cap_socket* sock, uint8_t** data, - uint32_t* len) { +static char packet_get_head_l(l2cap_socket* sock, uint8_t** data, uint32_t* len) { struct packet* p = sock->first_packet; - if (!p) return false; + if (!p) { + return false; + } - if (data) *data = sock->first_packet->data; - if (len) *len = sock->first_packet->len; + if (data) { + *data = sock->first_packet->data; + } + if (len) { + *len = sock->first_packet->len; + } sock->first_packet = p->next; - if (sock->first_packet) + if (sock->first_packet) { sock->first_packet->prev = NULL; - else + } else { sock->last_packet = NULL; + } - if (len) sock->bytes_buffered -= *len; + if (len) { + sock->bytes_buffered -= *len; + } osi_free(p); @@ -141,8 +148,7 @@ static struct packet* packet_alloc(const uint8_t* data, uint32_t len) { } /* makes a copy of the data, returns true on success */ -static char packet_put_head_l(l2cap_socket* sock, const void* data, - uint32_t len) { +static char packet_put_head_l(l2cap_socket* sock, const void* data, uint32_t len) { struct packet* p = packet_alloc((const uint8_t*)data, len); /* @@ -152,15 +158,18 @@ static char packet_put_head_l(l2cap_socket* sock, const void* data, * that function is used to put new data into the queue. */ - if (!p) return false; + if (!p) { + return false; + } p->prev = NULL; p->next = sock->first_packet; sock->first_packet = p; - if (p->next) + if (p->next) { p->next->prev = p; - else + } else { sock->last_packet = p; + } sock->bytes_buffered += len; @@ -168,11 +177,9 @@ static char packet_put_head_l(l2cap_socket* sock, const void* data, } /* makes a copy of the data, returns true on success */ -static char packet_put_tail_l(l2cap_socket* sock, const void* data, - uint32_t len) { +static char packet_put_tail_l(l2cap_socket* sock, const void* data, uint32_t len) { if (sock->bytes_buffered >= L2CAP_MAX_RX_BUFFER) { - log::error("Unable to add to buffer due to buffer overflow socket_id:{}", - sock->id); + log::error("Unable to add to buffer due to buffer overflow socket_id:{}", sock->id); return false; } @@ -180,10 +187,11 @@ static char packet_put_tail_l(l2cap_socket* sock, const void* data, p->next = NULL; p->prev = sock->last_packet; sock->last_packet = p; - if (p->prev) + if (p->prev) { p->prev->next = p; - else + } else { sock->first_packet = p; + } sock->bytes_buffered += len; @@ -199,7 +207,9 @@ static char is_inited(void) { static l2cap_socket* btsock_l2cap_find_by_id_l(uint32_t id) { l2cap_socket* sock = socks; - while (sock && sock->id != id) sock = sock->next; + while (sock && sock->id != id) { + sock = sock->next; + } return sock; } @@ -222,37 +232,44 @@ static void btsock_l2cap_free_l(l2cap_socket* sock) { uint8_t* buf; l2cap_socket* t = socks; - while (t && t != sock) t = t->next; + while (t && t != sock) { + t = t->next; + } - if (!t) /* prever double-frees */ + if (!t) { /* prever double-frees */ return; + } log::info( - "Disconnected L2CAP connection for device: {}, channel: {}, app_uid: {}, " - "id: {}, is_le: {}", - sock->addr, sock->channel, sock->app_uid, sock->id, sock->is_le_coc); + "Disconnected L2CAP connection for device: {}, channel: {}, app_uid: {}, " + "id: {}, is_le: {}", + sock->addr, sock->channel, sock->app_uid, sock->id, sock->is_le_coc); btif_sock_connection_logger( - sock->addr, sock->id, sock->is_le_coc ? BTSOCK_L2CAP_LE : BTSOCK_L2CAP, - SOCKET_CONNECTION_STATE_DISCONNECTED, - sock->server ? SOCKET_ROLE_LISTEN : SOCKET_ROLE_CONNECTION, sock->app_uid, - sock->channel, sock->tx_bytes, sock->rx_bytes, sock->name); - if (sock->next) sock->next->prev = sock->prev; + sock->addr, sock->id, sock->is_le_coc ? BTSOCK_L2CAP_LE : BTSOCK_L2CAP, + SOCKET_CONNECTION_STATE_DISCONNECTED, + sock->server ? SOCKET_ROLE_LISTEN : SOCKET_ROLE_CONNECTION, sock->app_uid, sock->channel, + sock->tx_bytes, sock->rx_bytes, sock->name); + if (sock->next) { + sock->next->prev = sock->prev; + } - if (sock->prev) + if (sock->prev) { sock->prev->next = sock->next; - else + } else { socks = sock->next; + } shutdown(sock->our_fd, SHUT_RDWR); close(sock->our_fd); if (sock->app_fd != -1) { close(sock->app_fd); } else { - log::info("Application has already closed l2cap socket socket_id:{}", - sock->id); + log::info("Application has already closed l2cap socket socket_id:{}", sock->id); } - while (packet_get_head_l(sock, &buf, NULL)) osi_free(buf); + while (packet_get_head_l(sock, &buf, NULL)) { + osi_free(buf); + } // lower-level close() should be idempotent... so let's call it and see... if (sock->is_le_coc) { @@ -262,8 +279,7 @@ static void btsock_l2cap_free_l(l2cap_socket* sock) { } if ((sock->channel >= 0) && (sock->server)) { BTA_JvFreeChannel(sock->channel, tBTA_JV_CONN_TYPE::L2CAP_LE); - log::info("Stopped L2CAP LE COC server socket_id:{} channel:{}", sock->id, - sock->channel); + log::info("Stopped L2CAP LE COC server socket_id:{} channel:{}", sock->id, sock->channel); BTA_JvL2capStopServer(sock->channel, sock->id); } } else { @@ -280,25 +296,28 @@ static void btsock_l2cap_free_l(l2cap_socket* sock) { osi_free(sock); } -static l2cap_socket* btsock_l2cap_alloc_l(const char* name, - const RawAddress* addr, - char is_server, int flags) { +static l2cap_socket* btsock_l2cap_alloc_l(const char* name, const RawAddress* addr, char is_server, + int flags) { unsigned security = 0; int fds[2]; l2cap_socket* sock = (l2cap_socket*)osi_calloc(sizeof(*sock)); int sock_type = SOCK_SEQPACKET; - if (flags & BTSOCK_FLAG_ENCRYPT) + if (flags & BTSOCK_FLAG_ENCRYPT) { security |= is_server ? BTM_SEC_IN_ENCRYPT : BTM_SEC_OUT_ENCRYPT; - if (flags & BTSOCK_FLAG_AUTH) + } + if (flags & BTSOCK_FLAG_AUTH) { security |= is_server ? BTM_SEC_IN_AUTHENTICATE : BTM_SEC_OUT_AUTHENTICATE; - if (flags & BTSOCK_FLAG_AUTH_MITM) + } + if (flags & BTSOCK_FLAG_AUTH_MITM) { security |= is_server ? BTM_SEC_IN_MITM : BTM_SEC_OUT_MITM; - if (flags & BTSOCK_FLAG_AUTH_16_DIGIT) + } + if (flags & BTSOCK_FLAG_AUTH_16_DIGIT) { security |= BTM_SEC_IN_MIN_16_DIGIT_PIN; + } - // For Floss, set socket as SOCK_STREAM - // TODO(b:271828292): Set SOCK_STREAM for everyone after verification tests + // For Floss, set socket as SOCK_STREAM + // TODO(b:271828292): Set SOCK_STREAM for everyone after verification tests #if TARGET_FLOSS sock_type = SOCK_STREAM; #endif @@ -316,8 +335,12 @@ static l2cap_socket* btsock_l2cap_alloc_l(const char* name, sock->server_psm_sent = false; sock->app_uid = -1; - if (name) strncpy(sock->name, name, sizeof(sock->name) - 1); - if (addr) sock->addr = *addr; + if (name) { + strncpy(sock->name, name, sizeof(sock->name) - 1); + } + if (addr) { + sock->addr = *addr; + } sock->first_packet = NULL; sock->last_packet = NULL; @@ -326,7 +349,9 @@ static l2cap_socket* btsock_l2cap_alloc_l(const char* name, sock->next = socks; sock->prev = NULL; - if (socks) socks->prev = sock; + if (socks) { + socks->prev = sock; + } sock->id = last_sock_id + 1; sock->tx_bytes = 0; sock->rx_bytes = 0; @@ -339,11 +364,13 @@ static l2cap_socket* btsock_l2cap_alloc_l(const char* name, while (t && t->id != sock->id) { t = t->next; } - if (!t && sock->id) /* non-zeor handle is unique -> we're done */ + if (!t && sock->id) { /* non-zeor handle is unique -> we're done */ break; + } /* if we're here, we found a duplicate */ - if (!++sock->id) /* no zero IDs allowed */ + if (!++sock->id) { /* no zero IDs allowed */ sock->id++; + } } last_sock_id = sock->id; log::info("Allocated l2cap socket structure socket_id:{}", sock->id); @@ -365,27 +392,26 @@ bt_status_t btsock_l2cap_init(int handle, uid_set_t* set) { bt_status_t btsock_l2cap_cleanup() { std::unique_lock lock(state_lock); pth = -1; - while (socks) btsock_l2cap_free_l(socks); + while (socks) { + btsock_l2cap_free_l(socks); + } return BT_STATUS_SUCCESS; } static inline bool send_app_psm_or_chan_l(l2cap_socket* sock) { - log::info("Sending l2cap socket socket_id:{} channel:{}", sock->id, - sock->channel); - return sock_send_all(sock->our_fd, (const uint8_t*)&sock->channel, - sizeof(sock->channel)) == sizeof(sock->channel); + log::info("Sending l2cap socket socket_id:{} channel:{}", sock->id, sock->channel); + return sock_send_all(sock->our_fd, (const uint8_t*)&sock->channel, sizeof(sock->channel)) == + sizeof(sock->channel); } static bool send_app_err_code(l2cap_socket* sock, tBTA_JV_L2CAP_REASON code) { - log::info("Sending l2cap failure reason socket_id:{} reason code:{}", - sock->id, code); + log::info("Sending l2cap failure reason socket_id:{} reason code:{}", sock->id, code); int err_channel = 0; - if (sock_send_all(sock->our_fd, (const uint8_t*)&err_channel, - sizeof(err_channel)) != sizeof(err_channel)) { + if (sock_send_all(sock->our_fd, (const uint8_t*)&err_channel, sizeof(err_channel)) != + sizeof(err_channel)) { return false; } - return sock_send_all(sock->our_fd, (const uint8_t*)&code, sizeof(code)) == - sizeof(code); + return sock_send_all(sock->our_fd, (const uint8_t*)&code, sizeof(code)) == sizeof(code); } static uint64_t uuid_lsb(const Uuid& uuid) { @@ -412,9 +438,9 @@ static uint64_t uuid_msb(const Uuid& uuid) { return msb; } -static bool send_app_connect_signal(int fd, const RawAddress* addr, int channel, - int status, int send_fd, uint16_t rx_mtu, - uint16_t tx_mtu, const Uuid& conn_uuid) { +static bool send_app_connect_signal(int fd, const RawAddress* addr, int channel, int status, + int send_fd, uint16_t rx_mtu, uint16_t tx_mtu, + const Uuid& conn_uuid) { sock_connect_signal_t cs; cs.size = sizeof(cs); cs.bd_addr = *addr; @@ -425,9 +451,9 @@ static bool send_app_connect_signal(int fd, const RawAddress* addr, int channel, cs.conn_uuid_lsb = uuid_lsb(conn_uuid); cs.conn_uuid_msb = uuid_msb(conn_uuid); if (send_fd != -1) { - if (sock_send_fd(fd, (const uint8_t*)&cs, sizeof(cs), send_fd) == - sizeof(cs)) + if (sock_send_fd(fd, (const uint8_t*)&cs, sizeof(cs), send_fd) == sizeof(cs)) { return true; + } } else if (sock_send_all(fd, (const uint8_t*)&cs, sizeof(cs)) == sizeof(cs)) { return true; } @@ -436,8 +462,7 @@ static bool send_app_connect_signal(int fd, const RawAddress* addr, int channel, return false; } -static void on_srv_l2cap_listen_started(tBTA_JV_L2CAP_START* p_start, - uint32_t id) { +static void on_srv_l2cap_listen_started(tBTA_JV_L2CAP_START* p_start, uint32_t id) { l2cap_socket* sock; std::unique_lock lock(state_lock); @@ -456,14 +481,14 @@ static void on_srv_l2cap_listen_started(tBTA_JV_L2CAP_START* p_start, sock->handle = p_start->handle; log::info( - "Listening for L2CAP connection for device: {}, channel: {}, app_uid: " - "{}, id: {}, is_le: {}", - sock->addr, sock->channel, sock->app_uid, sock->id, sock->is_le_coc); - btif_sock_connection_logger( - sock->addr, sock->id, sock->is_le_coc ? BTSOCK_L2CAP_LE : BTSOCK_L2CAP, - SOCKET_CONNECTION_STATE_LISTENING, - sock->server ? SOCKET_ROLE_LISTEN : SOCKET_ROLE_CONNECTION, sock->app_uid, - sock->channel, 0, 0, sock->name); + "Listening for L2CAP connection for device: {}, channel: {}, app_uid: " + "{}, id: {}, is_le: {}", + sock->addr, sock->channel, sock->app_uid, sock->id, sock->is_le_coc); + btif_sock_connection_logger(sock->addr, sock->id, + sock->is_le_coc ? BTSOCK_L2CAP_LE : BTSOCK_L2CAP, + SOCKET_CONNECTION_STATE_LISTENING, + sock->server ? SOCKET_ROLE_LISTEN : SOCKET_ROLE_CONNECTION, + sock->app_uid, sock->channel, 0, 0, sock->name); if (!sock->server_psm_sent) { if (!send_app_psm_or_chan_l(sock)) { @@ -499,24 +524,20 @@ static void on_cl_l2cap_init(tBTA_JV_L2CAP_CL_INIT* p_init, uint32_t id) { * Here we allocate a new sock instance to mimic the BluetoothSocket. The socket * will be a clone of the sock representing the BluetoothServerSocket. * */ -static void on_srv_l2cap_psm_connect_l(tBTA_JV_L2CAP_OPEN* p_open, - l2cap_socket* sock) { +static void on_srv_l2cap_psm_connect_l(tBTA_JV_L2CAP_OPEN* p_open, l2cap_socket* sock) { // std::mutex locked by caller - l2cap_socket* accept_rs = - btsock_l2cap_alloc_l(sock->name, &p_open->rem_bda, false, 0); + l2cap_socket* accept_rs = btsock_l2cap_alloc_l(sock->name, &p_open->rem_bda, false, 0); accept_rs->connected = true; accept_rs->security = sock->security; accept_rs->channel = sock->channel; accept_rs->handle = sock->handle; accept_rs->app_uid = sock->app_uid; - sock->handle = - -1; /* We should no longer associate this handle with the server socket */ + sock->handle = -1; /* We should no longer associate this handle with the server socket */ accept_rs->is_le_coc = sock->is_le_coc; accept_rs->tx_mtu = sock->tx_mtu = p_open->tx_mtu; accept_rs->local_cid = p_open->local_cid; accept_rs->remote_cid = p_open->remote_cid; - Uuid uuid = - Uuid::From128BitBE(bluetooth::os::GenerateRandom()); + Uuid uuid = Uuid::From128BitBE(bluetooth::os::GenerateRandom()); accept_rs->conn_uuid = uuid; /* Swap IDs to hand over the GAP connection to the accepted socket, and start @@ -526,67 +547,57 @@ static void on_srv_l2cap_psm_connect_l(tBTA_JV_L2CAP_OPEN* p_open, sock->id = new_listen_id; log::info( - "Connected to L2CAP connection for device: {}, channel: {}, app_uid: {}, " - "id: {}, is_le: {}", - sock->addr, sock->channel, sock->app_uid, sock->id, sock->is_le_coc); - btif_sock_connection_logger( - accept_rs->addr, accept_rs->id, - accept_rs->is_le_coc ? BTSOCK_L2CAP_LE : BTSOCK_L2CAP, - SOCKET_CONNECTION_STATE_CONNECTED, - accept_rs->server ? SOCKET_ROLE_LISTEN : SOCKET_ROLE_CONNECTION, - accept_rs->app_uid, accept_rs->channel, 0, 0, accept_rs->name); + "Connected to L2CAP connection for device: {}, channel: {}, app_uid: {}, " + "id: {}, is_le: {}", + sock->addr, sock->channel, sock->app_uid, sock->id, sock->is_le_coc); + btif_sock_connection_logger(accept_rs->addr, accept_rs->id, + accept_rs->is_le_coc ? BTSOCK_L2CAP_LE : BTSOCK_L2CAP, + SOCKET_CONNECTION_STATE_CONNECTED, + accept_rs->server ? SOCKET_ROLE_LISTEN : SOCKET_ROLE_CONNECTION, + accept_rs->app_uid, accept_rs->channel, 0, 0, accept_rs->name); // start monitor the socket - btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, - SOCK_THREAD_FD_EXCEPTION, sock->id); - btsock_thread_add_fd(pth, accept_rs->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_RD, - accept_rs->id); - send_app_connect_signal(sock->our_fd, &accept_rs->addr, sock->channel, 0, - accept_rs->app_fd, sock->rx_mtu, p_open->tx_mtu, - accept_rs->conn_uuid); - accept_rs->app_fd = - -1; // The fd is closed after sent to app in send_app_connect_signal() + btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_EXCEPTION, sock->id); + btsock_thread_add_fd(pth, accept_rs->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_RD, accept_rs->id); + send_app_connect_signal(sock->our_fd, &accept_rs->addr, sock->channel, 0, accept_rs->app_fd, + sock->rx_mtu, p_open->tx_mtu, accept_rs->conn_uuid); + accept_rs->app_fd = -1; // The fd is closed after sent to app in send_app_connect_signal() // But for some reason we still leak a FD - either the server socket // one or the accept socket one. btsock_l2cap_server_listen(sock); } -static void on_cl_l2cap_psm_connect_l(tBTA_JV_L2CAP_OPEN* p_open, - l2cap_socket* sock) { +static void on_cl_l2cap_psm_connect_l(tBTA_JV_L2CAP_OPEN* p_open, l2cap_socket* sock) { sock->addr = p_open->rem_bda; sock->tx_mtu = p_open->tx_mtu; sock->local_cid = p_open->local_cid; sock->remote_cid = p_open->remote_cid; - Uuid uuid = - Uuid::From128BitBE(bluetooth::os::GenerateRandom()); + Uuid uuid = Uuid::From128BitBE(bluetooth::os::GenerateRandom()); sock->conn_uuid = uuid; if (!send_app_psm_or_chan_l(sock)) { - log::error("Unable to send l2cap socket to application socket_id:{}", - sock->id); + log::error("Unable to send l2cap socket to application socket_id:{}", sock->id); return; } - if (!send_app_connect_signal(sock->our_fd, &sock->addr, sock->channel, 0, -1, - sock->rx_mtu, p_open->tx_mtu, sock->conn_uuid)) { - log::error("Unable to connect l2cap socket to application socket_id:{}", - sock->id); + if (!send_app_connect_signal(sock->our_fd, &sock->addr, sock->channel, 0, -1, sock->rx_mtu, + p_open->tx_mtu, sock->conn_uuid)) { + log::error("Unable to connect l2cap socket to application socket_id:{}", sock->id); return; } log::info( - "Connected to L2CAP connection for device: {}, channel: {}, app_uid: {}, " - "id: {}, is_le: {}", - sock->addr, sock->channel, sock->app_uid, sock->id, sock->is_le_coc); - btif_sock_connection_logger( - sock->addr, sock->id, sock->is_le_coc ? BTSOCK_L2CAP_LE : BTSOCK_L2CAP, - SOCKET_CONNECTION_STATE_CONNECTED, - sock->server ? SOCKET_ROLE_LISTEN : SOCKET_ROLE_CONNECTION, sock->app_uid, - sock->channel, 0, 0, sock->name); + "Connected to L2CAP connection for device: {}, channel: {}, app_uid: {}, " + "id: {}, is_le: {}", + sock->addr, sock->channel, sock->app_uid, sock->id, sock->is_le_coc); + btif_sock_connection_logger(sock->addr, sock->id, + sock->is_le_coc ? BTSOCK_L2CAP_LE : BTSOCK_L2CAP, + SOCKET_CONNECTION_STATE_CONNECTED, + sock->server ? SOCKET_ROLE_LISTEN : SOCKET_ROLE_CONNECTION, + sock->app_uid, sock->channel, 0, 0, sock->name); // start monitoring the socketpair to get call back when app writing data - btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_RD, - sock->id); + btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_RD, sock->id); log::info("Connected l2cap socket socket_id:{}", sock->id); sock->connected = true; } @@ -611,8 +622,7 @@ static void on_l2cap_connect(tBTA_JV* p_data, uint32_t id) { on_srv_l2cap_psm_connect_l(psm_open, sock); } } else { - log::error("Unable to open socket after receiving connection socket_id:{}", - sock->id); + log::error("Unable to open socket after receiving connection socket_id:{}", sock->id); btsock_l2cap_free_l(sock); } } @@ -623,25 +633,22 @@ static void on_l2cap_close(tBTA_JV_L2CAP_CLOSE* p_close, uint32_t id) { std::unique_lock lock(state_lock); sock = btsock_l2cap_find_by_id_l(id); if (!sock) { - log::info( - "Unable to find probably already closed l2cap socket with socket_id:{}", - id); + log::info("Unable to find probably already closed l2cap socket with socket_id:{}", id); return; } log::info( - "Disconnecting from L2CAP connection for device: {}, channel: {}, " - "app_uid: {}, id: {}, is_le: {}", - sock->addr, sock->channel, sock->app_uid, sock->id, sock->is_le_coc); - btif_sock_connection_logger( - sock->addr, sock->id, sock->is_le_coc ? BTSOCK_L2CAP_LE : BTSOCK_L2CAP, - SOCKET_CONNECTION_STATE_DISCONNECTING, - sock->server ? SOCKET_ROLE_LISTEN : SOCKET_ROLE_CONNECTION, sock->app_uid, - sock->channel, 0, 0, sock->name); + "Disconnecting from L2CAP connection for device: {}, channel: {}, " + "app_uid: {}, id: {}, is_le: {}", + sock->addr, sock->channel, sock->app_uid, sock->id, sock->is_le_coc); + btif_sock_connection_logger(sock->addr, sock->id, + sock->is_le_coc ? BTSOCK_L2CAP_LE : BTSOCK_L2CAP, + SOCKET_CONNECTION_STATE_DISCONNECTING, + sock->server ? SOCKET_ROLE_LISTEN : SOCKET_ROLE_CONNECTION, + sock->app_uid, sock->channel, 0, 0, sock->name); if (!send_app_err_code(sock, p_close->reason)) { - log::error("Unable to send l2cap socket to application socket_id:{}", - sock->id); + log::error("Unable to send l2cap socket to application socket_id:{}", sock->id); } // TODO: This does not seem to be called... // I'm not sure if this will be called for non-server sockets? @@ -664,10 +671,8 @@ static void on_l2cap_outgoing_congest(tBTA_JV_L2CAP_CONG* p, uint32_t id) { sock->outgoing_congest = p->cong ? 1 : 0; if (!sock->outgoing_congest) { - log::verbose("Monitoring l2cap socket for outgoing data socket_id:{}", - sock->id); - btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_RD, - sock->id); + log::verbose("Monitoring l2cap socket for outgoing data socket_id:{}", sock->id); + btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_RD, sock->id); } } @@ -681,8 +686,7 @@ static void on_l2cap_write_done(uint16_t len, uint32_t id) { int app_uid = sock->app_uid; if (!sock->outgoing_congest) { - btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_RD, - sock->id); + btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_RD, sock->id); } else { log::info("Socket congestion on socket_id:{}", sock->id); } @@ -710,16 +714,12 @@ static void on_l2cap_data_ind(tBTA_JV* evt, uint32_t id) { if (BTA_JvL2capReady(sock->handle, &count) == tBTA_JV_STATUS::SUCCESS) { std::vector buffer(count); - if (BTA_JvL2capRead(sock->handle, sock->id, buffer.data(), count) == - tBTA_JV_STATUS::SUCCESS) { + if (BTA_JvL2capRead(sock->handle, sock->id, buffer.data(), count) == tBTA_JV_STATUS::SUCCESS) { if (packet_put_tail_l(sock, buffer.data(), count)) { bytes_read = count; - btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_WR, - sock->id); + btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_WR, sock->id); } else { // connection must be dropped - log::warn( - "Closing socket as unable to push data to socket socket_id:{}", - sock->id); + log::warn("Closing socket as unable to push data to socket socket_id:{}", sock->id); BTA_JvL2capClose(sock->handle); btsock_l2cap_free_l(sock); return; @@ -731,8 +731,7 @@ static void on_l2cap_data_ind(tBTA_JV* evt, uint32_t id) { uid_set_add_rx(uid_set, app_uid, bytes_read); } -static void btsock_l2cap_cbk(tBTA_JV_EVT event, tBTA_JV* p_data, - uint32_t l2cap_socket_id) { +static void btsock_l2cap_cbk(tBTA_JV_EVT event, tBTA_JV* p_data, uint32_t l2cap_socket_id) { switch (event) { case BTA_JV_L2CAP_START_EVT: on_srv_l2cap_listen_started(&p_data->l2c_start, l2cap_socket_id); @@ -744,8 +743,7 @@ static void btsock_l2cap_cbk(tBTA_JV_EVT event, tBTA_JV* p_data, case BTA_JV_L2CAP_OPEN_EVT: on_l2cap_connect(p_data, l2cap_socket_id); - BTA_JvSetPmProfile(p_data->l2c_open.handle, BTA_JV_PM_ID_1, - BTA_JV_CONN_OPEN); + BTA_JvSetPmProfile(p_data->l2c_open.handle, BTA_JV_PM_ID_1, BTA_JV_CONN_OPEN); break; case BTA_JV_L2CAP_CLOSE_EVT: @@ -768,8 +766,8 @@ static void btsock_l2cap_cbk(tBTA_JV_EVT event, tBTA_JV* p_data, break; default: - log::error("Unhandled event:{} l2cap_socket_id:{}", - bta_jv_event_text(event), l2cap_socket_id); + log::error("Unhandled event:{} l2cap_socket_id:{}", bta_jv_event_text(event), + l2cap_socket_id); break; } } @@ -801,7 +799,7 @@ void on_l2cap_psm_assigned(int id, int psm) { static void btsock_l2cap_server_listen(l2cap_socket* sock) { tBTA_JV_CONN_TYPE connection_type = - sock->is_le_coc ? tBTA_JV_CONN_TYPE::L2CAP_LE : tBTA_JV_CONN_TYPE::L2CAP; + sock->is_le_coc ? tBTA_JV_CONN_TYPE::L2CAP_LE : tBTA_JV_CONN_TYPE::L2CAP; /* If we have a channel specified in the request, just start the server, * else we request a PSM and start the server after we receive a PSM. */ @@ -812,24 +810,23 @@ static void btsock_l2cap_server_listen(l2cap_socket* sock) { /* Setup ETM settings: mtu will be set below */ std::unique_ptr cfg = std::make_unique( - tL2CAP_CFG_INFO{.fcr_present = true, .fcr = kDefaultErtmOptions}); + tL2CAP_CFG_INFO{.fcr_present = true, .fcr = kDefaultErtmOptions}); std::unique_ptr ertm_info; if (!sock->is_le_coc) { ertm_info.reset(new tL2CAP_ERTM_INFO(obex_l2c_etm_opt)); } - BTA_JvL2capStartServer(connection_type, sock->security, std::move(ertm_info), - sock->channel, sock->rx_mtu, std::move(cfg), - btsock_l2cap_cbk, sock->id); + BTA_JvL2capStartServer(connection_type, sock->security, std::move(ertm_info), sock->channel, + sock->rx_mtu, std::move(cfg), btsock_l2cap_cbk, sock->id); } -static bt_status_t btsock_l2cap_listen_or_connect(const char* name, - const RawAddress* addr, - int channel, int* sock_fd, - int flags, char listen, +static bt_status_t btsock_l2cap_listen_or_connect(const char* name, const RawAddress* addr, + int channel, int* sock_fd, int flags, char listen, int app_uid) { - if (!is_inited()) return BT_STATUS_NOT_READY; + if (!is_inited()) { + return BT_STATUS_NOT_READY; + } bool is_le_coc = (flags & BTSOCK_FLAG_LE_COC) != 0; @@ -870,22 +867,20 @@ static bt_status_t btsock_l2cap_listen_or_connect(const char* name, if (listen) { btsock_l2cap_server_listen(sock); } else { - tBTA_JV_CONN_TYPE connection_type = sock->is_le_coc - ? tBTA_JV_CONN_TYPE::L2CAP_LE - : tBTA_JV_CONN_TYPE::L2CAP; + tBTA_JV_CONN_TYPE connection_type = + sock->is_le_coc ? tBTA_JV_CONN_TYPE::L2CAP_LE : tBTA_JV_CONN_TYPE::L2CAP; /* Setup ETM settings: mtu will be set below */ std::unique_ptr cfg = std::make_unique( - tL2CAP_CFG_INFO{.fcr_present = true, .fcr = kDefaultErtmOptions}); + tL2CAP_CFG_INFO{.fcr_present = true, .fcr = kDefaultErtmOptions}); std::unique_ptr ertm_info; if (!sock->is_le_coc) { ertm_info.reset(new tL2CAP_ERTM_INFO(obex_l2c_etm_opt)); } - BTA_JvL2capConnect(connection_type, sock->security, std::move(ertm_info), - channel, sock->rx_mtu, std::move(cfg), sock->addr, - btsock_l2cap_cbk, sock->id); + BTA_JvL2capConnect(connection_type, sock->security, std::move(ertm_info), channel, sock->rx_mtu, + std::move(cfg), sock->addr, btsock_l2cap_cbk, sock->id); } *sock_fd = sock->app_fd; @@ -895,22 +890,19 @@ static bt_status_t btsock_l2cap_listen_or_connect(const char* name, sock->app_fd = -1; /*This leaks the file descriptor. The FD should be closed in JAVA but it * apparently do not work */ - btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, - SOCK_THREAD_FD_EXCEPTION, sock->id); + btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_EXCEPTION, sock->id); return BT_STATUS_SUCCESS; } -bt_status_t btsock_l2cap_listen(const char* name, int channel, int* sock_fd, - int flags, int app_uid) { - return btsock_l2cap_listen_or_connect(name, NULL, channel, sock_fd, flags, 1, - app_uid); +bt_status_t btsock_l2cap_listen(const char* name, int channel, int* sock_fd, int flags, + int app_uid) { + return btsock_l2cap_listen_or_connect(name, NULL, channel, sock_fd, flags, 1, app_uid); } -bt_status_t btsock_l2cap_connect(const RawAddress* bd_addr, int channel, - int* sock_fd, int flags, int app_uid) { - return btsock_l2cap_listen_or_connect(NULL, bd_addr, channel, sock_fd, flags, - 0, app_uid); +bt_status_t btsock_l2cap_connect(const RawAddress* bd_addr, int channel, int* sock_fd, int flags, + int app_uid) { + return btsock_l2cap_listen_or_connect(NULL, bd_addr, channel, sock_fd, flags, 0, app_uid); } /* return true if we have more to send and should wait for user readiness, false @@ -926,13 +918,14 @@ static bool flush_incoming_que_on_wr_signal_l(l2cap_socket* sock) { OSI_NO_INTR(sent = send(sock->our_fd, buf, len, MSG_DONTWAIT)); int saved_errno = errno; - if (sent == (signed)len) + if (sent == (signed)len) { osi_free(buf); - else if (sent >= 0) { + } else if (sent >= 0) { packet_put_head_l(sock, buf + sent, len - sent); osi_free(buf); - if (!sent) /* special case if other end not keeping up */ + if (!sent) { /* special case if other end not keeping up */ return true; + } } else { packet_put_head_l(sock, buf, len); osi_free(buf); @@ -945,8 +938,7 @@ static bool flush_incoming_que_on_wr_signal_l(l2cap_socket* sock) { inline BT_HDR* malloc_l2cap_buf(uint16_t len) { // We need FCS only for L2CAP_FCR_ERTM_MODE, but it's just 2 bytes so it's ok - BT_HDR* msg = (BT_HDR*)osi_malloc(BT_HDR_SIZE + L2CAP_MIN_OFFSET + len + - L2CAP_FCS_LENGTH); + BT_HDR* msg = (BT_HDR*)osi_malloc(BT_HDR_SIZE + L2CAP_MIN_OFFSET + len + L2CAP_FCS_LENGTH); msg->offset = L2CAP_MIN_OFFSET; msg->len = len; return msg; @@ -963,7 +955,9 @@ void btsock_l2cap_signaled(int fd, int flags, uint32_t user_id) { * hold the lock. */ std::unique_lock lock(state_lock); l2cap_socket* sock = btsock_l2cap_find_by_id_l(user_id); - if (!sock) return; + if (!sock) { + return; + } if ((flags & SOCK_THREAD_FD_RD) && !sock->server) { // app sending data @@ -1001,25 +995,31 @@ void btsock_l2cap_signaled(int fd, int flags, uint32_t user_id) { // will take care of freeing buffer BTA_JvL2capWrite(sock->handle, PTR_TO_UINT(buffer), buffer, user_id); } - } else + } else { drop_it = true; + } } if (flags & SOCK_THREAD_FD_WR) { // app is ready to receive more data, tell stack to enable the data flow - if (flush_incoming_que_on_wr_signal_l(sock) && sock->connected) - btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_WR, - sock->id); + if (flush_incoming_que_on_wr_signal_l(sock) && sock->connected) { + btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_WR, sock->id); + } } if (drop_it || (flags & SOCK_THREAD_FD_EXCEPTION)) { int size = 0; - if (drop_it || ioctl(sock->our_fd, FIONREAD, &size) != 0 || size == 0) + if (drop_it || ioctl(sock->our_fd, FIONREAD, &size) != 0 || size == 0) { btsock_l2cap_free_l(sock); + } } } bt_status_t btsock_l2cap_disconnect(const RawAddress* bd_addr) { - if (!bd_addr) return BT_STATUS_PARM_INVALID; - if (!is_inited()) return BT_STATUS_NOT_READY; + if (!bd_addr) { + return BT_STATUS_PARM_INVALID; + } + if (!is_inited()) { + return BT_STATUS_NOT_READY; + } std::unique_lock lock(state_lock); l2cap_socket* sock = socks; @@ -1041,8 +1041,7 @@ bt_status_t btsock_l2cap_get_l2cap_local_cid(Uuid& conn_uuid, uint16_t* cid) { std::unique_lock lock(state_lock); sock = btsock_l2cap_find_by_conn_uuid_l(conn_uuid); if (!sock) { - log::error("Unable to find l2cap socket with conn_uuid:{}", - conn_uuid.ToString()); + log::error("Unable to find l2cap socket with conn_uuid:{}", conn_uuid.ToString()); return BT_STATUS_SOCKET_ERROR; } *cid = sock->local_cid; @@ -1055,8 +1054,7 @@ bt_status_t btsock_l2cap_get_l2cap_remote_cid(Uuid& conn_uuid, uint16_t* cid) { std::unique_lock lock(state_lock); sock = btsock_l2cap_find_by_conn_uuid_l(conn_uuid); if (!sock) { - log::error("Unable to find l2cap socket with conn_uuid:{}", - conn_uuid.ToString()); + log::error("Unable to find l2cap socket with conn_uuid:{}", conn_uuid.ToString()); return BT_STATUS_SOCKET_ERROR; } *cid = sock->remote_cid; diff --git a/system/btif/src/btif_sock_logging.cc b/system/btif/src/btif_sock_logging.cc index 2c581f9773c..cf9c1793512 100644 --- a/system/btif/src/btif_sock_logging.cc +++ b/system/btif/src/btif_sock_logging.cc @@ -49,24 +49,22 @@ static std::atomic logger_index; static SockConnectionEvent connection_logger[SOCK_LOGGER_SIZE_MAX]; -static android::bluetooth::SocketConnectionstateEnum toConnectionStateEnum( - int state); +static android::bluetooth::SocketConnectionstateEnum toConnectionStateEnum(int state); static android::bluetooth::SocketRoleEnum toSocketRoleEnum(int role); -void btif_sock_connection_logger(const RawAddress& address, int port, int type, - int state, int role, int uid, int server_port, - int64_t tx_bytes, int64_t rx_bytes, +void btif_sock_connection_logger(const RawAddress& address, int port, int type, int state, int role, + int uid, int server_port, int64_t tx_bytes, int64_t rx_bytes, const char* server_name) { uint8_t index = logger_index++ % SOCK_LOGGER_SIZE_MAX; connection_logger[index] = { - .used = true, - .addr = address, - .state = state, - .role = role, - .channel = server_port, - .type = type, - .server_name = {'\0'}, + .used = true, + .addr = address, + .state = state, + .role = role, + .channel = server_port, + .type = type, + .server_name = {'\0'}, }; if (server_name != nullptr) { @@ -75,9 +73,8 @@ void btif_sock_connection_logger(const RawAddress& address, int port, int type, } clock_gettime(CLOCK_REALTIME, &connection_logger[index].timestamp); - log_socket_connection_state(address, port, type, toConnectionStateEnum(state), - tx_bytes, rx_bytes, uid, server_port, - toSocketRoleEnum(role)); + log_socket_connection_state(address, port, type, toConnectionStateEnum(state), tx_bytes, rx_bytes, + uid, server_port, toSocketRoleEnum(role)); } void btif_sock_dump(int fd) { @@ -107,8 +104,7 @@ void SockConnectionEvent::dump(const int fd) { char temptime[20]; struct tm* tstamp = localtime(×tamp.tv_sec); strftime(temptime, sizeof(temptime), "%H:%M:%S", tstamp); - snprintf(eventtime, sizeof(eventtime), "%s.%03ld", temptime, - timestamp.tv_nsec / 1000000); + snprintf(eventtime, sizeof(eventtime), "%s.%03ld", temptime, timestamp.tv_nsec / 1000000); const char* str_state; switch (state) { @@ -165,32 +161,24 @@ void SockConnectionEvent::dump(const int fd) { } dprintf(fd, " %s\t%s\t%s \t%s \t%d \t%s\t%s\n", eventtime, - ADDRESS_TO_LOGGABLE_CSTR(addr), str_state, str_role, channel, - str_type, server_name); + ADDRESS_TO_LOGGABLE_CSTR(addr), str_state, str_role, channel, str_type, server_name); } -static android::bluetooth::SocketConnectionstateEnum toConnectionStateEnum( - int state) { +static android::bluetooth::SocketConnectionstateEnum toConnectionStateEnum(int state) { switch (state) { case SOCKET_CONNECTION_STATE_LISTENING: - return android::bluetooth::SocketConnectionstateEnum:: - SOCKET_CONNECTION_STATE_LISTENING; + return android::bluetooth::SocketConnectionstateEnum::SOCKET_CONNECTION_STATE_LISTENING; break; case SOCKET_CONNECTION_STATE_CONNECTING: - return android::bluetooth::SocketConnectionstateEnum:: - SOCKET_CONNECTION_STATE_CONNECTING; + return android::bluetooth::SocketConnectionstateEnum::SOCKET_CONNECTION_STATE_CONNECTING; case SOCKET_CONNECTION_STATE_CONNECTED: - return android::bluetooth::SocketConnectionstateEnum:: - SOCKET_CONNECTION_STATE_CONNECTED; + return android::bluetooth::SocketConnectionstateEnum::SOCKET_CONNECTION_STATE_CONNECTED; case SOCKET_CONNECTION_STATE_DISCONNECTING: - return android::bluetooth::SocketConnectionstateEnum:: - SOCKET_CONNECTION_STATE_DISCONNECTING; + return android::bluetooth::SocketConnectionstateEnum::SOCKET_CONNECTION_STATE_DISCONNECTING; case SOCKET_CONNECTION_STATE_DISCONNECTED: - return android::bluetooth::SocketConnectionstateEnum:: - SOCKET_CONNECTION_STATE_DISCONNECTED; + return android::bluetooth::SocketConnectionstateEnum::SOCKET_CONNECTION_STATE_DISCONNECTED; } - return android::bluetooth::SocketConnectionstateEnum:: - SOCKET_CONNECTION_STATE_UNKNOWN; + return android::bluetooth::SocketConnectionstateEnum::SOCKET_CONNECTION_STATE_UNKNOWN; } static android::bluetooth::SocketRoleEnum toSocketRoleEnum(int role) { diff --git a/system/btif/src/btif_sock_rfc.cc b/system/btif/src/btif_sock_rfc.cc index 68388e4fc54..b820f6e381e 100644 --- a/system/btif/src/btif_sock_rfc.cc +++ b/system/btif/src/btif_sock_rfc.cc @@ -100,8 +100,7 @@ static uid_set_t* uid_set = NULL; static rfc_slot_t* find_free_slot(void); static void cleanup_rfc_slot(rfc_slot_t* rs); static void jv_dm_cback(tBTA_JV_EVT event, tBTA_JV* p_data, uint32_t id); -static uint32_t rfcomm_cback(tBTA_JV_EVT event, tBTA_JV* p_data, - uint32_t rfcomm_slot_id); +static uint32_t rfcomm_cback(tBTA_JV_EVT event, tBTA_JV* p_data, uint32_t rfcomm_slot_id); static bool send_app_scn(rfc_slot_t* rs); static void handle_discovery_comp(tBTA_JV_STATUS status, int scn, uint32_t id); @@ -134,7 +133,9 @@ void btsock_rfc_cleanup(void) { std::unique_lock lock(slot_lock); for (size_t i = 0; i < ARRAY_SIZE(rfc_slots); ++i) { - if (rfc_slots[i].id) cleanup_rfc_slot(&rfc_slots[i]); + if (rfc_slots[i].id) { + cleanup_rfc_slot(&rfc_slots[i]); + } list_free(rfc_slots[i].incoming_queue); rfc_slots[i].incoming_queue = NULL; } @@ -145,16 +146,22 @@ void btsock_rfc_cleanup(void) { } static rfc_slot_t* find_free_slot(void) { - for (size_t i = 0; i < ARRAY_SIZE(rfc_slots); ++i) - if (rfc_slots[i].fd == INVALID_FD) return &rfc_slots[i]; + for (size_t i = 0; i < ARRAY_SIZE(rfc_slots); ++i) { + if (rfc_slots[i].fd == INVALID_FD) { + return &rfc_slots[i]; + } + } return NULL; } static rfc_slot_t* find_rfc_slot_by_id(uint32_t id) { CHECK(id != 0); - for (size_t i = 0; i < ARRAY_SIZE(rfc_slots); ++i) - if (rfc_slots[i].id == id) return &rfc_slots[i]; + for (size_t i = 0; i < ARRAY_SIZE(rfc_slots); ++i) { + if (rfc_slots[i].id == id) { + return &rfc_slots[i]; + } + } return NULL; } @@ -162,37 +169,41 @@ static rfc_slot_t* find_rfc_slot_by_id(uint32_t id) { static rfc_slot_t* find_rfc_slot_by_pending_sdp(void) { uint32_t min_id = UINT32_MAX; int slot = -1; - for (size_t i = 0; i < ARRAY_SIZE(rfc_slots); ++i) - if (rfc_slots[i].id && rfc_slots[i].f.pending_sdp_request && - rfc_slots[i].id < min_id) { + for (size_t i = 0; i < ARRAY_SIZE(rfc_slots); ++i) { + if (rfc_slots[i].id && rfc_slots[i].f.pending_sdp_request && rfc_slots[i].id < min_id) { min_id = rfc_slots[i].id; slot = i; } + } return (slot == -1) ? NULL : &rfc_slots[slot]; } static bool is_requesting_sdp(void) { - for (size_t i = 0; i < ARRAY_SIZE(rfc_slots); ++i) + for (size_t i = 0; i < ARRAY_SIZE(rfc_slots); ++i) { if (rfc_slots[i].id && rfc_slots[i].f.doing_sdp_request) { log::info("slot id {} is doing sdp request", rfc_slots[i].id); return true; } + } return false; } -static rfc_slot_t* alloc_rfc_slot(const RawAddress* addr, const char* name, - const Uuid& uuid, int channel, int flags, - bool server) { +static rfc_slot_t* alloc_rfc_slot(const RawAddress* addr, const char* name, const Uuid& uuid, + int channel, int flags, bool server) { int security = 0; - if (flags & BTSOCK_FLAG_ENCRYPT) + if (flags & BTSOCK_FLAG_ENCRYPT) { security |= server ? BTM_SEC_IN_ENCRYPT : BTM_SEC_OUT_ENCRYPT; - if (flags & BTSOCK_FLAG_AUTH) + } + if (flags & BTSOCK_FLAG_AUTH) { security |= server ? BTM_SEC_IN_AUTHENTICATE : BTM_SEC_OUT_AUTHENTICATE; - if (flags & BTSOCK_FLAG_AUTH_MITM) + } + if (flags & BTSOCK_FLAG_AUTH_MITM) { security |= server ? BTM_SEC_IN_MITM : BTM_SEC_OUT_MITM; - if (flags & BTSOCK_FLAG_AUTH_16_DIGIT) + } + if (flags & BTSOCK_FLAG_AUTH_16_DIGIT) { security |= BTM_SEC_IN_MIN_16_DIGIT_PIN; + } rfc_slot_t* slot = find_free_slot(); if (!slot) { @@ -207,7 +218,9 @@ static rfc_slot_t* alloc_rfc_slot(const RawAddress* addr, const char* name, } // Increment slot id and make sure we don't use id=0. - if (++rfc_slot_id == 0) rfc_slot_id = 1; + if (++rfc_slot_id == 0) { + rfc_slot_id = 1; + } slot->fd = fds[0]; slot->app_fd = fds[1]; @@ -236,12 +249,10 @@ static rfc_slot_t* alloc_rfc_slot(const RawAddress* addr, const char* name, return slot; } -static rfc_slot_t* create_srv_accept_rfc_slot(rfc_slot_t* srv_rs, - const RawAddress* addr, - int open_handle, - int new_listen_handle) { - rfc_slot_t* accept_rs = alloc_rfc_slot( - addr, srv_rs->service_name, srv_rs->service_uuid, srv_rs->scn, 0, false); +static rfc_slot_t* create_srv_accept_rfc_slot(rfc_slot_t* srv_rs, const RawAddress* addr, + int open_handle, int new_listen_handle) { + rfc_slot_t* accept_rs = + alloc_rfc_slot(addr, srv_rs->service_name, srv_rs->service_uuid, srv_rs->scn, 0, false); if (!accept_rs) { log::error("unable to allocate RFCOMM slot."); return NULL; @@ -261,13 +272,12 @@ static rfc_slot_t* create_srv_accept_rfc_slot(rfc_slot_t* srv_rs, if (accept_rs->rfc_port_handle == srv_rs->rfc_port_handle) { log::error( - "accept_rs->rfc_port_handle == srv_rs->rfc_port_handle, " - "rfc_port_handle={}", - accept_rs->rfc_port_handle); + "accept_rs->rfc_port_handle == srv_rs->rfc_port_handle, " + "rfc_port_handle={}", + accept_rs->rfc_port_handle); } - log::assert_that( - accept_rs->rfc_port_handle != srv_rs->rfc_port_handle, - "assert failed: accept_rs->rfc_port_handle != srv_rs->rfc_port_handle"); + log::assert_that(accept_rs->rfc_port_handle != srv_rs->rfc_port_handle, + "assert failed: accept_rs->rfc_port_handle != srv_rs->rfc_port_handle"); // now swap the slot id uint32_t new_listen_id = accept_rs->id; @@ -277,13 +287,11 @@ static rfc_slot_t* create_srv_accept_rfc_slot(rfc_slot_t* srv_rs, return accept_rs; } -bt_status_t btsock_rfc_control_req(uint8_t dlci, const RawAddress& bd_addr, - uint8_t modem_signal, uint8_t break_signal, - uint8_t discard_buffers, +bt_status_t btsock_rfc_control_req(uint8_t dlci, const RawAddress& bd_addr, uint8_t modem_signal, + uint8_t break_signal, uint8_t discard_buffers, uint8_t break_signal_seq, bool fc) { - int status = - RFCOMM_ControlReqFromBTSOCK(dlci, bd_addr, modem_signal, break_signal, - discard_buffers, break_signal_seq, fc); + int status = RFCOMM_ControlReqFromBTSOCK(dlci, bd_addr, modem_signal, break_signal, + discard_buffers, break_signal_seq, fc); if (status != PORT_SUCCESS) { log::warn("failed to send control parameters, status={}", status); return BT_STATUS_FAIL; @@ -291,15 +299,13 @@ bt_status_t btsock_rfc_control_req(uint8_t dlci, const RawAddress& bd_addr, return BT_STATUS_SUCCESS; } -bt_status_t btsock_rfc_listen(const char* service_name, - const Uuid* service_uuid, int channel, +bt_status_t btsock_rfc_listen(const char* service_name, const Uuid* service_uuid, int channel, int* sock_fd, int flags, int app_uid) { log::assert_that(sock_fd != NULL, "assert failed: sock_fd != NULL"); - log::assert_that( - (service_uuid != NULL) || (channel >= 1 && channel <= MAX_RFC_CHANNEL) || - ((flags & BTSOCK_FLAG_NO_SDP) != 0), - "assert failed: (service_uuid != NULL) || (channel >= 1 && channel <= " - "MAX_RFC_CHANNEL) || ((flags & BTSOCK_FLAG_NO_SDP) != 0)"); + log::assert_that((service_uuid != NULL) || (channel >= 1 && channel <= MAX_RFC_CHANNEL) || + ((flags & BTSOCK_FLAG_NO_SDP) != 0), + "assert failed: (service_uuid != NULL) || (channel >= 1 && channel <= " + "MAX_RFC_CHANNEL) || ((flags & BTSOCK_FLAG_NO_SDP) != 0)"); *sock_fd = INVALID_FD; @@ -327,14 +333,12 @@ bt_status_t btsock_rfc_listen(const char* service_name, std::unique_lock lock(slot_lock); - rfc_slot_t* slot = - alloc_rfc_slot(NULL, service_name, *service_uuid, channel, flags, true); + rfc_slot_t* slot = alloc_rfc_slot(NULL, service_name, *service_uuid, channel, flags, true); if (!slot) { log::error("unable to allocate RFCOMM slot"); return BT_STATUS_NOMEM; } - log::info("Adding listening socket service_name: {} - channel: {}", - service_name, channel); + log::info("Adding listening socket service_name: {} - channel: {}", service_name, channel); BTA_JvGetChannelId(tBTA_JV_CONN_TYPE::RFCOMM, slot->id, channel); *sock_fd = slot->app_fd; // Transfer ownership of fd to caller. /*TODO: @@ -347,20 +351,17 @@ bt_status_t btsock_rfc_listen(const char* service_name, // close(rs->app_fd); slot->app_fd = INVALID_FD; // Drop our reference to the fd. slot->app_uid = app_uid; - btsock_thread_add_fd(pth, slot->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_EXCEPTION, - slot->id); + btsock_thread_add_fd(pth, slot->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_EXCEPTION, slot->id); return BT_STATUS_SUCCESS; } -bt_status_t btsock_rfc_connect(const RawAddress* bd_addr, - const Uuid* service_uuid, int channel, +bt_status_t btsock_rfc_connect(const RawAddress* bd_addr, const Uuid* service_uuid, int channel, int* sock_fd, int flags, int app_uid) { log::assert_that(sock_fd != NULL, "assert failed: sock_fd != NULL"); - log::assert_that( - (service_uuid != NULL) || (channel >= 1 && channel <= MAX_RFC_CHANNEL), - "assert failed: (service_uuid != NULL) || (channel >= 1 && channel <= " - "MAX_RFC_CHANNEL)"); + log::assert_that((service_uuid != NULL) || (channel >= 1 && channel <= MAX_RFC_CHANNEL), + "assert failed: (service_uuid != NULL) || (channel >= 1 && channel <= " + "MAX_RFC_CHANNEL)"); *sock_fd = INVALID_FD; @@ -375,20 +376,18 @@ bt_status_t btsock_rfc_connect(const RawAddress* bd_addr, std::unique_lock lock(slot_lock); - rfc_slot_t* slot = - alloc_rfc_slot(bd_addr, NULL, *service_uuid, channel, flags, false); + rfc_slot_t* slot = alloc_rfc_slot(bd_addr, NULL, *service_uuid, channel, flags, false); if (!slot) { log::error("unable to allocate RFCOMM slot. bd_addr:{}", *bd_addr); return BT_STATUS_NOMEM; } if (!service_uuid || service_uuid->IsEmpty()) { - tBTA_JV_STATUS ret = BTA_JvRfcommConnect( - slot->security, slot->scn, slot->addr, rfcomm_cback, slot->id); + tBTA_JV_STATUS ret = + BTA_JvRfcommConnect(slot->security, slot->scn, slot->addr, rfcomm_cback, slot->id); if (ret != tBTA_JV_STATUS::SUCCESS) { - log::error( - "unable to initiate RFCOMM connection. status:{}, scn:{}, bd_addr:{}", - bta_jv_status_text(ret), slot->scn, slot->addr); + log::error("unable to initiate RFCOMM connection. status:{}, scn:{}, bd_addr:{}", + bta_jv_status_text(ret), slot->scn, slot->addr); cleanup_rfc_slot(slot); return BT_STATUS_SOCKET_ERROR; } @@ -399,8 +398,8 @@ bt_status_t btsock_rfc_connect(const RawAddress* bd_addr, return BT_STATUS_SOCKET_ERROR; } } else { - log::info("service_uuid:{}, bd_addr:{}, slot_id:{}", - service_uuid->ToString(), *bd_addr, slot->id); + log::info("service_uuid:{}, bd_addr:{}, slot_id:{}", service_uuid->ToString(), *bd_addr, + slot->id); if (!is_requesting_sdp()) { BTA_JvStartDiscovery(*bd_addr, 1, service_uuid, slot->id); slot->f.pending_sdp_request = false; @@ -414,8 +413,7 @@ bt_status_t btsock_rfc_connect(const RawAddress* bd_addr, *sock_fd = slot->app_fd; // Transfer ownership of fd to caller. slot->app_fd = INVALID_FD; // Drop our reference to the fd. slot->app_uid = app_uid; - btsock_thread_add_fd(pth, slot->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_RD, - slot->id); + btsock_thread_add_fd(pth, slot->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_RD, slot->id); return BT_STATUS_SUCCESS; } @@ -424,20 +422,23 @@ static int create_server_sdp_record(rfc_slot_t* slot) { if (slot->scn == 0) { return false; } - slot->sdp_handle = - add_rfc_sdp_rec(slot->service_name, slot->service_uuid, slot->scn); - return (slot->sdp_handle > 0); + slot->sdp_handle = add_rfc_sdp_rec(slot->service_name, slot->service_uuid, slot->scn); + return slot->sdp_handle > 0; } static void free_rfc_slot_scn(rfc_slot_t* slot) { - if (slot->scn <= 0) return; + if (slot->scn <= 0) { + return; + } if (slot->f.server && !slot->f.closing && slot->rfc_handle) { BTA_JvRfcommStopServer(slot->rfc_handle, slot->id); slot->rfc_handle = 0; } - if (slot->f.server) BTA_FreeSCN(slot->scn); + if (slot->f.server) { + BTA_FreeSCN(slot->scn); + } slot->scn = 0; } @@ -446,16 +447,14 @@ static void cleanup_rfc_slot(rfc_slot_t* slot) { shutdown(slot->fd, SHUT_RDWR); close(slot->fd); log::info( - "disconnected from RFCOMM socket connections for device: {}, scn: {}, " - "app_uid: {}, id: {}", - slot->addr, slot->scn, slot->app_uid, slot->id); + "disconnected from RFCOMM socket connections for device: {}, scn: {}, " + "app_uid: {}, id: {}", + slot->addr, slot->scn, slot->app_uid, slot->id); btif_sock_connection_logger( - slot->addr, slot->id, BTSOCK_RFCOMM, - SOCKET_CONNECTION_STATE_DISCONNECTED, - slot->f.server ? SOCKET_ROLE_LISTEN : SOCKET_ROLE_CONNECTION, - slot->app_uid, slot->scn, slot->tx_bytes, slot->rx_bytes, - slot->role ? slot->service_name - : slot->service_uuid.ToString().c_str()); + slot->addr, slot->id, BTSOCK_RFCOMM, SOCKET_CONNECTION_STATE_DISCONNECTED, + slot->f.server ? SOCKET_ROLE_LISTEN : SOCKET_ROLE_CONNECTION, slot->app_uid, slot->scn, + slot->tx_bytes, slot->rx_bytes, + slot->role ? slot->service_name : slot->service_uuid.ToString().c_str()); slot->fd = INVALID_FD; } @@ -493,12 +492,12 @@ static bool send_app_scn(rfc_slot_t* slot) { } log::debug("Sending scn for slot {}. bd_addr:{}", slot->id, slot->addr); slot->scn_notified = true; - return sock_send_all(slot->fd, (const uint8_t*)&slot->scn, - sizeof(slot->scn)) == sizeof(slot->scn); + return sock_send_all(slot->fd, (const uint8_t*)&slot->scn, sizeof(slot->scn)) == + sizeof(slot->scn); } -static bool send_app_connect_signal(int fd, const RawAddress* addr, int channel, - int status, int send_fd) { +static bool send_app_connect_signal(int fd, const RawAddress* addr, int channel, int status, + int send_fd) { sock_connect_signal_t cs; cs.size = sizeof(cs); cs.bd_addr = *addr; @@ -508,11 +507,11 @@ static bool send_app_connect_signal(int fd, const RawAddress* addr, int channel, cs.max_tx_packet_size = 0; // not used for RFCOMM cs.conn_uuid_lsb = 0; // not used for RFCOMM cs.conn_uuid_msb = 0; // not used for RFCOMM - if (send_fd == INVALID_FD) + if (send_fd == INVALID_FD) { return sock_send_all(fd, (const uint8_t*)&cs, sizeof(cs)) == sizeof(cs); + } - return sock_send_fd(fd, (const uint8_t*)&cs, sizeof(cs), send_fd) == - sizeof(cs); + return sock_send_fd(fd, (const uint8_t*)&cs, sizeof(cs), send_fd) == sizeof(cs); } static void on_cl_rfc_init(tBTA_JV_RFCOMM_CL_INIT* p_init, uint32_t id) { @@ -530,8 +529,7 @@ static void on_cl_rfc_init(tBTA_JV_RFCOMM_CL_INIT* p_init, uint32_t id) { } } -static void on_srv_rfc_listen_started(tBTA_JV_RFCOMM_START* p_start, - uint32_t id) { +static void on_srv_rfc_listen_started(tBTA_JV_RFCOMM_START* p_start, uint32_t id) { std::unique_lock lock(slot_lock); rfc_slot_t* slot = find_rfc_slot_by_id(id); if (!slot) { @@ -546,17 +544,16 @@ static void on_srv_rfc_listen_started(tBTA_JV_RFCOMM_START* p_start, slot->rfc_handle = p_start->handle; log::info( - "listening for RFCOMM socket connections for device: {}, scn: {}, " - "app_uid: {}, id: {}", - slot->addr, slot->scn, slot->app_uid, id); - btif_sock_connection_logger( - slot->addr, slot->id, BTSOCK_RFCOMM, SOCKET_CONNECTION_STATE_LISTENING, - slot->f.server ? SOCKET_ROLE_LISTEN : SOCKET_ROLE_CONNECTION, - slot->app_uid, slot->scn, 0, 0, slot->service_name); + "listening for RFCOMM socket connections for device: {}, scn: {}, " + "app_uid: {}, id: {}", + slot->addr, slot->scn, slot->app_uid, id); + btif_sock_connection_logger(slot->addr, slot->id, BTSOCK_RFCOMM, + SOCKET_CONNECTION_STATE_LISTENING, + slot->f.server ? SOCKET_ROLE_LISTEN : SOCKET_ROLE_CONNECTION, + slot->app_uid, slot->scn, 0, 0, slot->service_name); } -static uint32_t on_srv_rfc_connect(tBTA_JV_RFCOMM_SRV_OPEN* p_open, - uint32_t id) { +static uint32_t on_srv_rfc_connect(tBTA_JV_RFCOMM_SRV_OPEN* p_open, uint32_t id) { log::verbose("id:{}", id); std::unique_lock lock(slot_lock); rfc_slot_t* accept_rs; @@ -566,29 +563,26 @@ static uint32_t on_srv_rfc_connect(tBTA_JV_RFCOMM_SRV_OPEN* p_open, return 0; } - accept_rs = create_srv_accept_rfc_slot( - srv_rs, &p_open->rem_bda, p_open->handle, p_open->new_listen_handle); - if (!accept_rs) return 0; + accept_rs = create_srv_accept_rfc_slot(srv_rs, &p_open->rem_bda, p_open->handle, + p_open->new_listen_handle); + if (!accept_rs) { + return 0; + } log::info( - "connected to RFCOMM socket connections for device: {}, scn: {}, " - "app_uid: {}, id: {}", - accept_rs->addr, accept_rs->scn, accept_rs->app_uid, id); - btif_sock_connection_logger( - accept_rs->addr, accept_rs->id, BTSOCK_RFCOMM, - SOCKET_CONNECTION_STATE_DISCONNECTED, - accept_rs->f.server ? SOCKET_ROLE_LISTEN : SOCKET_ROLE_CONNECTION, - accept_rs->app_uid, accept_rs->scn, 0, 0, accept_rs->service_name); + "connected to RFCOMM socket connections for device: {}, scn: {}, " + "app_uid: {}, id: {}", + accept_rs->addr, accept_rs->scn, accept_rs->app_uid, id); + btif_sock_connection_logger(accept_rs->addr, accept_rs->id, BTSOCK_RFCOMM, + SOCKET_CONNECTION_STATE_DISCONNECTED, + accept_rs->f.server ? SOCKET_ROLE_LISTEN : SOCKET_ROLE_CONNECTION, + accept_rs->app_uid, accept_rs->scn, 0, 0, accept_rs->service_name); // Start monitoring the socket. - btsock_thread_add_fd(pth, srv_rs->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_EXCEPTION, - srv_rs->id); - btsock_thread_add_fd(pth, accept_rs->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_RD, - accept_rs->id); - send_app_connect_signal(srv_rs->fd, &accept_rs->addr, srv_rs->scn, 0, - accept_rs->app_fd); - accept_rs->app_fd = - INVALID_FD; // Ownership of the application fd has been transferred. + btsock_thread_add_fd(pth, srv_rs->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_EXCEPTION, srv_rs->id); + btsock_thread_add_fd(pth, accept_rs->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_RD, accept_rs->id); + send_app_connect_signal(srv_rs->fd, &accept_rs->addr, srv_rs->scn, 0, accept_rs->app_fd); + accept_rs->app_fd = INVALID_FD; // Ownership of the application fd has been transferred. return srv_rs->id; } @@ -612,13 +606,13 @@ static void on_cli_rfc_connect(tBTA_JV_RFCOMM_OPEN* p_open, uint32_t id) { slot->addr = p_open->rem_bda; log::info( - "connected to RFCOMM socket connections for device: {}, scn: {}, " - "app_uid: {}, id: {}", - slot->addr, slot->scn, slot->app_uid, id); + "connected to RFCOMM socket connections for device: {}, scn: {}, " + "app_uid: {}, id: {}", + slot->addr, slot->scn, slot->app_uid, id); btif_sock_connection_logger( - slot->addr, slot->id, BTSOCK_RFCOMM, SOCKET_CONNECTION_STATE_CONNECTED, - slot->f.server ? SOCKET_ROLE_LISTEN : SOCKET_ROLE_CONNECTION, - slot->app_uid, slot->scn, 0, 0, slot->service_uuid.ToString().c_str()); + slot->addr, slot->id, BTSOCK_RFCOMM, SOCKET_CONNECTION_STATE_CONNECTED, + slot->f.server ? SOCKET_ROLE_LISTEN : SOCKET_ROLE_CONNECTION, slot->app_uid, slot->scn, 0, + 0, slot->service_uuid.ToString().c_str()); if (send_app_connect_signal(slot->fd, &slot->addr, slot->scn, 0, -1)) { slot->f.connected = true; @@ -637,12 +631,11 @@ static void on_rfc_close(tBTA_JV_RFCOMM_CLOSE* /* p_close */, uint32_t id) { log::warn("RFCOMM slot with id {} not found.", id); return; } - log_socket_connection_state( - slot->addr, slot->id, BTSOCK_RFCOMM, - android::bluetooth::SOCKET_CONNECTION_STATE_DISCONNECTING, 0, 0, - slot->app_uid, slot->scn, - slot->f.server ? android::bluetooth::SOCKET_ROLE_LISTEN - : android::bluetooth::SOCKET_ROLE_CONNECTION); + log_socket_connection_state(slot->addr, slot->id, BTSOCK_RFCOMM, + android::bluetooth::SOCKET_CONNECTION_STATE_DISCONNECTING, 0, 0, + slot->app_uid, slot->scn, + slot->f.server ? android::bluetooth::SOCKET_ROLE_LISTEN + : android::bluetooth::SOCKET_ROLE_CONNECTION); cleanup_rfc_slot(slot); } @@ -661,9 +654,9 @@ static void on_rfc_write_done(tBTA_JV_RFCOMM_WRITE* p, uint32_t id) { return; } app_uid = slot->app_uid; - if (!slot->f.outgoing_congest) - btsock_thread_add_fd(pth, slot->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_RD, - slot->id); + if (!slot->f.outgoing_congest) { + btsock_thread_add_fd(pth, slot->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_RD, slot->id); + } slot->tx_bytes += p->len; uid_set_add_tx(uid_set, app_uid, p->len); } @@ -678,59 +671,49 @@ static void on_rfc_outgoing_congest(tBTA_JV_RFCOMM_CONG* p, uint32_t id) { } slot->f.outgoing_congest = p->cong ? 1 : 0; - if (!slot->f.outgoing_congest) - btsock_thread_add_fd(pth, slot->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_RD, - slot->id); + if (!slot->f.outgoing_congest) { + btsock_thread_add_fd(pth, slot->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_RD, slot->id); + } } -static uint32_t rfcomm_cback(tBTA_JV_EVT event, tBTA_JV* p_data, - uint32_t rfcomm_slot_id) { +static uint32_t rfcomm_cback(tBTA_JV_EVT event, tBTA_JV* p_data, uint32_t rfcomm_slot_id) { uint32_t id = 0; switch (event) { case BTA_JV_RFCOMM_START_EVT: - log::info("handling {}, rfcomm_slot_id:{}", bta_jv_event_text(event), - rfcomm_slot_id); + log::info("handling {}, rfcomm_slot_id:{}", bta_jv_event_text(event), rfcomm_slot_id); on_srv_rfc_listen_started(&p_data->rfc_start, rfcomm_slot_id); break; case BTA_JV_RFCOMM_CL_INIT_EVT: - log::info("handling {}, rfcomm_slot_id:{}", bta_jv_event_text(event), - rfcomm_slot_id); + log::info("handling {}, rfcomm_slot_id:{}", bta_jv_event_text(event), rfcomm_slot_id); on_cl_rfc_init(&p_data->rfc_cl_init, rfcomm_slot_id); break; case BTA_JV_RFCOMM_OPEN_EVT: - log::info("handling {}, rfcomm_slot_id:{}", bta_jv_event_text(event), - rfcomm_slot_id); - BTA_JvSetPmProfile(p_data->rfc_open.handle, BTA_JV_PM_ID_1, - BTA_JV_CONN_OPEN); + log::info("handling {}, rfcomm_slot_id:{}", bta_jv_event_text(event), rfcomm_slot_id); + BTA_JvSetPmProfile(p_data->rfc_open.handle, BTA_JV_PM_ID_1, BTA_JV_CONN_OPEN); on_cli_rfc_connect(&p_data->rfc_open, rfcomm_slot_id); break; case BTA_JV_RFCOMM_SRV_OPEN_EVT: - log::info("handling {}, rfcomm_slot_id:{}", bta_jv_event_text(event), - rfcomm_slot_id); - BTA_JvSetPmProfile(p_data->rfc_srv_open.handle, BTA_JV_PM_ALL, - BTA_JV_CONN_OPEN); + log::info("handling {}, rfcomm_slot_id:{}", bta_jv_event_text(event), rfcomm_slot_id); + BTA_JvSetPmProfile(p_data->rfc_srv_open.handle, BTA_JV_PM_ALL, BTA_JV_CONN_OPEN); id = on_srv_rfc_connect(&p_data->rfc_srv_open, rfcomm_slot_id); break; case BTA_JV_RFCOMM_CLOSE_EVT: - log::info("handling {}, rfcomm_slot_id:{}", bta_jv_event_text(event), - rfcomm_slot_id); + log::info("handling {}, rfcomm_slot_id:{}", bta_jv_event_text(event), rfcomm_slot_id); on_rfc_close(&p_data->rfc_close, rfcomm_slot_id); break; case BTA_JV_RFCOMM_WRITE_EVT: - log::verbose("handling {}, rfcomm_slot_id:{}", bta_jv_event_text(event), - rfcomm_slot_id); + log::verbose("handling {}, rfcomm_slot_id:{}", bta_jv_event_text(event), rfcomm_slot_id); on_rfc_write_done(&p_data->rfc_write, rfcomm_slot_id); break; case BTA_JV_RFCOMM_CONG_EVT: - log::verbose("handling {}, rfcomm_slot_id:{}", bta_jv_event_text(event), - rfcomm_slot_id); + log::verbose("handling {}, rfcomm_slot_id:{}", bta_jv_event_text(event), rfcomm_slot_id); on_rfc_outgoing_congest(&p_data->rfc_cong, rfcomm_slot_id); break; @@ -739,8 +722,7 @@ static uint32_t rfcomm_cback(tBTA_JV_EVT event, tBTA_JV* p_data, break; default: - log::warn("unhandled event {}, slot id: {}", bta_jv_event_text(event), - rfcomm_slot_id); + log::warn("unhandled event {}, slot id: {}", bta_jv_event_text(event), rfcomm_slot_id); break; } return id; @@ -753,14 +735,11 @@ static void jv_dm_cback(tBTA_JV_EVT event, tBTA_JV* p_data, uint32_t id) { std::unique_lock lock(slot_lock); rfc_slot_t* rs = find_rfc_slot_by_id(id); if (!rs) { - log::error("RFCOMM slot with id {} not found. event:{}", id, - bta_jv_event_text(event)); + log::error("RFCOMM slot with id {} not found. event:{}", id, bta_jv_event_text(event)); break; } if (p_data->scn == 0) { - log::error( - "Unable to allocate scn: all resources exhausted. slot found: {}", - fmt::ptr(rs)); + log::error("Unable to allocate scn: all resources exhausted. slot found: {}", fmt::ptr(rs)); cleanup_rfc_slot(rs); break; } @@ -783,11 +762,10 @@ static void jv_dm_cback(tBTA_JV_EVT event, tBTA_JV* p_data, uint32_t id) { // create_sdp_record() will be called from Java when it has received the // RFCOMM and L2CAP channel numbers through the sockets. log::debug( - "Since UUID is not valid; not setting SDP-record and just starting " - "the RFCOMM server"); + "Since UUID is not valid; not setting SDP-record and just starting " + "the RFCOMM server"); // now start the rfcomm server after sdp & channel # assigned - BTA_JvRfcommStartServer(rs->security, rs->scn, MAX_RFC_SESSION, - rfcomm_cback, rs->id); + BTA_JvRfcommStartServer(rs->security, rs->scn, MAX_RFC_SESSION, rfcomm_cback, rs->id); } break; } @@ -803,8 +781,7 @@ static void jv_dm_cback(tBTA_JV_EVT event, tBTA_JV* p_data, uint32_t id) { rfc_slot_t* slot = find_rfc_slot_by_id(id); if (!slot) { - log::error("RFCOMM slot with id {} not found. event:{}", id, - bta_jv_event_text(event)); + log::error("RFCOMM slot with id {} not found. event:{}", id, bta_jv_event_text(event)); break; } @@ -815,15 +792,13 @@ static void jv_dm_cback(tBTA_JV_EVT event, tBTA_JV* p_data, uint32_t id) { } // Start the rfcomm server after sdp & channel # assigned. - BTA_JvRfcommStartServer(slot->security, slot->scn, MAX_RFC_SESSION, - rfcomm_cback, slot->id); + BTA_JvRfcommStartServer(slot->security, slot->scn, MAX_RFC_SESSION, rfcomm_cback, slot->id); break; } case BTA_JV_DISCOVERY_COMP_EVT: { std::unique_lock lock(slot_lock); - handle_discovery_comp(p_data->disc_comp.status, p_data->disc_comp.scn, - id); + handle_discovery_comp(p_data->disc_comp.status, p_data->disc_comp.scn, id); // Find the next slot that needs to perform an SDP request and service it. rfc_slot_t* slot = find_rfc_slot_by_pending_sdp(); if (slot) { @@ -835,8 +810,7 @@ static void jv_dm_cback(tBTA_JV_EVT event, tBTA_JV* p_data, uint32_t id) { } default: - log::debug("unhandled event:{}, slot id:{}", bta_jv_event_text(event), - id); + log::debug("unhandled event:{}, slot id:{}", bta_jv_event_text(event), id); break; } } @@ -844,34 +818,30 @@ static void jv_dm_cback(tBTA_JV_EVT event, tBTA_JV* p_data, uint32_t id) { static void handle_discovery_comp(tBTA_JV_STATUS status, int scn, uint32_t id) { rfc_slot_t* slot = find_rfc_slot_by_id(id); if (!slot) { - log::error( - "RFCOMM slot with id {} not found. event: BTA_JV_DISCOVERY_COMP_EVT", - id); + log::error("RFCOMM slot with id {} not found. event: BTA_JV_DISCOVERY_COMP_EVT", id); return; } if (!slot->f.doing_sdp_request) { - log::error( - "SDP response returned but RFCOMM slot {} did not request SDP record.", - id); + log::error("SDP response returned but RFCOMM slot {} did not request SDP record.", id); return; } if (status != tBTA_JV_STATUS::SUCCESS || !scn) { log::error( - "SDP service discovery completed for slot id: {} with the result " - "status: {}, scn: {}", - id, bta_jv_status_text(status), scn); + "SDP service discovery completed for slot id: {} with the result " + "status: {}, scn: {}", + id, bta_jv_status_text(status), scn); cleanup_rfc_slot(slot); return; } - if (BTA_JvRfcommConnect(slot->security, scn, slot->addr, rfcomm_cback, - slot->id) != tBTA_JV_STATUS::SUCCESS) { + if (BTA_JvRfcommConnect(slot->security, scn, slot->addr, rfcomm_cback, slot->id) != + tBTA_JV_STATUS::SUCCESS) { log::warn( - "BTA_JvRfcommConnect() returned BTA_JV_FAILURE for RFCOMM slot with " - "id: {}", - id); + "BTA_JvRfcommConnect() returned BTA_JV_FAILURE for RFCOMM slot with " + "id: {}", + id); cleanup_rfc_slot(slot); return; } @@ -894,21 +864,28 @@ typedef enum { } sent_status_t; static sent_status_t send_data_to_app(int fd, BT_HDR* p_buf) { - if (p_buf->len == 0) return SENT_ALL; + if (p_buf->len == 0) { + return SENT_ALL; + } ssize_t sent; - OSI_NO_INTR( - sent = send(fd, p_buf->data + p_buf->offset, p_buf->len, MSG_DONTWAIT)); + OSI_NO_INTR(sent = send(fd, p_buf->data + p_buf->offset, p_buf->len, MSG_DONTWAIT)); if (sent == -1) { - if (errno == EAGAIN || errno == EWOULDBLOCK) return SENT_NONE; + if (errno == EAGAIN || errno == EWOULDBLOCK) { + return SENT_NONE; + } log::error("error writing RFCOMM data back to app: {}", strerror(errno)); return SENT_FAILED; } - if (sent == 0) return SENT_FAILED; + if (sent == 0) { + return SENT_FAILED; + } - if (sent == p_buf->len) return SENT_ALL; + if (sent == p_buf->len) { + return SENT_ALL; + } p_buf->offset += sent; p_buf->len -= sent; @@ -922,8 +899,7 @@ static bool flush_incoming_que_on_wr_signal(rfc_slot_t* slot) { case SENT_NONE: case SENT_PARTIAL: // monitor the fd to get callback when app is ready to receive data - btsock_thread_add_fd(pth, slot->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_WR, - slot->id); + btsock_thread_add_fd(pth, slot->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_WR, slot->id); return true; case SENT_ALL: @@ -938,9 +914,8 @@ static bool flush_incoming_que_on_wr_signal(rfc_slot_t* slot) { // app is ready to receive data, tell stack to start the data flow // fix me: need a jv flow control api to serialize the call in stack - log::verbose( - "enable data flow, rfc_handle:0x{:x}, rfc_port_handle:0x{:x}, user_id:{}", - slot->rfc_handle, slot->rfc_port_handle, slot->id); + log::verbose("enable data flow, rfc_handle:0x{:x}, rfc_port_handle:0x{:x}, user_id:{}", + slot->rfc_handle, slot->rfc_port_handle, slot->id); if (PORT_FlowControl_MaxCredit(slot->rfc_port_handle, true) != PORT_SUCCESS) { log::warn("Unable to open RFCOMM port peer:{}", slot->addr); } @@ -961,14 +936,12 @@ void btsock_rfc_signaled(int /* fd */, int flags, uint32_t id) { if (slot->f.connected) { // Make sure there's data pending in case the peer closed the socket. int size = 0; - if (!(flags & SOCK_THREAD_FD_EXCEPTION) || - (ioctl(slot->fd, FIONREAD, &size) == 0 && size)) { + if (!(flags & SOCK_THREAD_FD_EXCEPTION) || (ioctl(slot->fd, FIONREAD, &size) == 0 && size)) { BTA_JvRfcommWrite(slot->rfc_handle, slot->id); } } else { - log::error( - "socket signaled for read while disconnected, slot: {}, channel: {}", - slot->id, slot->scn); + log::error("socket signaled for read while disconnected, slot: {}, channel: {}", slot->id, + slot->scn); need_close = true; } } @@ -977,9 +950,9 @@ void btsock_rfc_signaled(int /* fd */, int flags, uint32_t id) { // App is ready to receive more data, tell stack to enable data flow. if (!slot->f.connected || !flush_incoming_que_on_wr_signal(slot)) { log::error( - "socket signaled for write while disconnected (or write failure), " - "slot: {}, channel: {}", - slot->id, slot->scn); + "socket signaled for write while disconnected (or write failure), " + "slot: {}, channel: {}", + slot->id, slot->scn); need_close = true; } } @@ -987,8 +960,9 @@ void btsock_rfc_signaled(int /* fd */, int flags, uint32_t id) { if (need_close || (flags & SOCK_THREAD_FD_EXCEPTION)) { // Clean up if there's no data pending. int size = 0; - if (need_close || ioctl(slot->fd, FIONREAD, &size) != 0 || !size) + if (need_close || ioctl(slot->fd, FIONREAD, &size) != 0 || !size) { cleanup_rfc_slot(slot); + } } } @@ -1011,8 +985,7 @@ int bta_co_rfc_data_incoming(uint32_t id, BT_HDR* p_buf) { case SENT_NONE: case SENT_PARTIAL: list_append(slot->incoming_queue, p_buf); - btsock_thread_add_fd(pth, slot->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_WR, - slot->id); + btsock_thread_add_fd(pth, slot->fd, BTSOCK_RFCOMM, SOCK_THREAD_FD_WR, slot->id); break; case SENT_ALL: @@ -1045,8 +1018,8 @@ int bta_co_rfc_data_outgoing_size(uint32_t id, int* size) { } if (ioctl(slot->fd, FIONREAD, size) != 0) { - log::error("unable to determine bytes remaining to be read on fd {}: {}", - slot->fd, strerror(errno)); + log::error("unable to determine bytes remaining to be read on fd {}: {}", slot->fd, + strerror(errno)); cleanup_rfc_slot(slot); return false; } diff --git a/system/btif/src/btif_sock_sco.cc b/system/btif/src/btif_sock_sco.cc index 1873858426d..6ba1222f430 100644 --- a/system/btif/src/btif_sock_sco.cc +++ b/system/btif/src/btif_sock_sco.cc @@ -62,14 +62,12 @@ typedef struct { bool connect_completed; } sco_socket_t; -static sco_socket_t* sco_socket_establish_locked(bool is_listening, - const RawAddress* bd_addr, +static sco_socket_t* sco_socket_establish_locked(bool is_listening, const RawAddress* bd_addr, int* sock_fd); static sco_socket_t* sco_socket_new(void); static void sco_socket_free_locked(sco_socket_t* socket); static sco_socket_t* sco_socket_find_locked(uint16_t sco_handle); -static void connection_request_cb(tBTM_ESCO_EVT event, - tBTM_ESCO_EVT_DATA* data); +static void connection_request_cb(tBTM_ESCO_EVT event, tBTM_ESCO_EVT_DATA* data); static void connect_completed_cb(uint16_t sco_handle); static void disconnect_completed_cb(uint16_t sco_handle); static void socket_read_ready_cb(socket_t* socket, void* context); @@ -77,7 +75,7 @@ static void socket_read_ready_cb(socket_t* socket, void* context); // |sco_lock| protects all of the static variables below and // calls into the BTM layer. static std::mutex sco_lock; -static list_t* sco_sockets; // Owns a collection of sco_socket_t objects. +static list_t* sco_sockets; // Owns a collection of sco_socket_t objects. static sco_socket_t* listen_sco_socket; // Not owned, do not free. static thread_t* thread; // Not owned, do not free. @@ -85,7 +83,9 @@ bt_status_t btsock_sco_init(thread_t* thread_) { log::assert_that(thread_ != NULL, "assert failed: thread_ != NULL"); sco_sockets = list_new((list_free_cb)sco_socket_free_locked); - if (!sco_sockets) return BT_STATUS_SOCKET_ERROR; + if (!sco_sockets) { + return BT_STATUS_SOCKET_ERROR; + } thread = thread_; enh_esco_params_t params = esco_parameters_for_codec(SCO_CODEC_CVSD_D1, true); @@ -108,10 +108,12 @@ bt_status_t btsock_sco_listen(int* sock_fd, int /* flags */) { std::unique_lock lock(sco_lock); sco_socket_t* sco_socket = sco_socket_establish_locked(true, NULL, sock_fd); - if (!sco_socket) return BT_STATUS_SOCKET_ERROR; + if (!sco_socket) { + return BT_STATUS_SOCKET_ERROR; + } - if (get_btm_client_interface().sco.BTM_RegForEScoEvts( - sco_socket->sco_handle, connection_request_cb) != BTM_SUCCESS) { + if (get_btm_client_interface().sco.BTM_RegForEScoEvts(sco_socket->sco_handle, + connection_request_cb) != BTM_SUCCESS) { log::warn("Unable to register for ESCO events"); } listen_sco_socket = sco_socket; @@ -119,21 +121,18 @@ bt_status_t btsock_sco_listen(int* sock_fd, int /* flags */) { return BT_STATUS_SUCCESS; } -bt_status_t btsock_sco_connect(const RawAddress* bd_addr, int* sock_fd, - int /* flags */) { +bt_status_t btsock_sco_connect(const RawAddress* bd_addr, int* sock_fd, int /* flags */) { log::assert_that(bd_addr != NULL, "assert failed: bd_addr != NULL"); log::assert_that(sock_fd != NULL, "assert failed: sock_fd != NULL"); std::unique_lock lock(sco_lock); - sco_socket_t* sco_socket = - sco_socket_establish_locked(false, bd_addr, sock_fd); + sco_socket_t* sco_socket = sco_socket_establish_locked(false, bd_addr, sock_fd); return (sco_socket != NULL) ? BT_STATUS_SUCCESS : BT_STATUS_SOCKET_ERROR; } // Must be called with |lock| held. -static sco_socket_t* sco_socket_establish_locked(bool is_listening, - const RawAddress* bd_addr, +static sco_socket_t* sco_socket_establish_locked(bool is_listening, const RawAddress* bd_addr, int* sock_fd) { int pair[2] = {INVALID_FD, INVALID_FD}; sco_socket_t* sco_socket = NULL; @@ -152,9 +151,8 @@ static sco_socket_t* sco_socket_establish_locked(bool is_listening, } params = esco_parameters_for_codec(SCO_CODEC_CVSD_D1, true); - status = BTM_CreateSco(bd_addr, !is_listening, params.packet_types, - &sco_socket->sco_handle, connect_completed_cb, - disconnect_completed_cb); + status = BTM_CreateSco(bd_addr, !is_listening, params.packet_types, &sco_socket->sco_handle, + connect_completed_cb, disconnect_completed_cb); if (status != BTM_CMD_STARTED) { log::error("unable to create SCO socket: {}", status); goto error; @@ -170,13 +168,16 @@ static sco_socket_t* sco_socket_establish_locked(bool is_listening, sco_socket->socket = socket; // Hang on to the other end. list_append(sco_sockets, sco_socket); - socket_register(socket, thread_get_reactor(thread), sco_socket, - socket_read_ready_cb, NULL); + socket_register(socket, thread_get_reactor(thread), sco_socket, socket_read_ready_cb, NULL); return sco_socket; error:; - if (pair[0] != INVALID_FD) close(pair[0]); - if (pair[1] != INVALID_FD) close(pair[1]); + if (pair[0] != INVALID_FD) { + close(pair[0]); + } + if (pair[1] != INVALID_FD) { + close(pair[1]); + } sco_socket_free_locked(sco_socket); return NULL; @@ -192,11 +193,12 @@ static sco_socket_t* sco_socket_new(void) { // socket thread // is no longer alive. static void sco_socket_free_locked(sco_socket_t* sco_socket) { - if (!sco_socket) return; + if (!sco_socket) { + return; + } if (sco_socket->sco_handle != BTM_INVALID_SCO_INDEX) { - if (get_btm_client_interface().sco.BTM_RemoveSco(sco_socket->sco_handle) != - BTM_SUCCESS) { + if (get_btm_client_interface().sco.BTM_RemoveSco(sco_socket->sco_handle) != BTM_SUCCESS) { log::warn("Unable to remove SCO handle:{}", sco_socket->sco_handle); } } @@ -206,20 +208,23 @@ static void sco_socket_free_locked(sco_socket_t* sco_socket) { // Must be called with |lock| held. static sco_socket_t* sco_socket_find_locked(uint16_t sco_handle) { - for (const list_node_t* node = list_begin(sco_sockets); - node != list_end(sco_sockets); node = list_next(node)) { + for (const list_node_t* node = list_begin(sco_sockets); node != list_end(sco_sockets); + node = list_next(node)) { sco_socket_t* sco_socket = (sco_socket_t*)list_node(node); - if (sco_socket->sco_handle == sco_handle) return sco_socket; + if (sco_socket->sco_handle == sco_handle) { + return sco_socket; + } } return NULL; } -static void connection_request_cb(tBTM_ESCO_EVT event, - tBTM_ESCO_EVT_DATA* data) { +static void connection_request_cb(tBTM_ESCO_EVT event, tBTM_ESCO_EVT_DATA* data) { log::assert_that(data != NULL, "assert failed: data != NULL"); // Don't care about change of link parameters, only connection requests. - if (event != BTM_ESCO_CONN_REQ_EVT) return; + if (event != BTM_ESCO_CONN_REQ_EVT) { + return; + } std::unique_lock lock(sco_lock); @@ -258,25 +263,24 @@ static void connection_request_cb(tBTM_ESCO_EVT event, connect_signal.channel = 0; connect_signal.status = 0; - if (socket_write_and_transfer_fd(sco_socket->socket, &connect_signal, - sizeof(connect_signal), + if (socket_write_and_transfer_fd(sco_socket->socket, &connect_signal, sizeof(connect_signal), client_fd) != sizeof(connect_signal)) { log::error("unable to send new file descriptor to listening socket."); goto error; } - if (get_btm_client_interface().sco.BTM_RegForEScoEvts( - listen_sco_socket->sco_handle, connection_request_cb) != - BTM_SUCCESS) { - log::warn("Unable to register for ESCO events handle:{}", - listen_sco_socket->sco_handle); + if (get_btm_client_interface().sco.BTM_RegForEScoEvts(listen_sco_socket->sco_handle, + connection_request_cb) != BTM_SUCCESS) { + log::warn("Unable to register for ESCO events handle:{}", listen_sco_socket->sco_handle); } BTM_EScoConnRsp(conn_data->sco_inx, HCI_SUCCESS, NULL); return; error:; - if (client_fd != INVALID_FD) close(client_fd); + if (client_fd != INVALID_FD) { + close(client_fd); + } BTM_EScoConnRsp(conn_data->sco_inx, HCI_ERR_HOST_REJECT_RESOURCES, NULL); } @@ -293,8 +297,7 @@ static void connect_completed_cb(uint16_t sco_handle) { // app-level // interest in the SCO socket. if (!sco_socket->socket) { - if (get_btm_client_interface().sco.BTM_RemoveSco(sco_socket->sco_handle) != - BTM_SUCCESS) { + if (get_btm_client_interface().sco.BTM_RemoveSco(sco_socket->sco_handle) != BTM_SUCCESS) { log::warn("Unable to remove SCO handle:{}", sco_socket->sco_handle); } list_remove(sco_sockets, sco_socket); @@ -330,8 +333,11 @@ static void socket_read_ready_cb(socket_t* /* socket */, void* context) { // routine that the socket is no longer desired and should be torn // down. if (sco_socket->connect_completed || sco_socket == listen_sco_socket) { - if (BTM_RemoveSco(sco_socket->sco_handle) == BTM_SUCCESS) + if (BTM_RemoveSco(sco_socket->sco_handle) == BTM_SUCCESS) { list_remove(sco_sockets, sco_socket); - if (sco_socket == listen_sco_socket) listen_sco_socket = NULL; + } + if (sco_socket == listen_sco_socket) { + listen_sco_socket = NULL; + } } } diff --git a/system/btif/src/btif_sock_sdp.cc b/system/btif/src/btif_sock_sdp.cc index f928f366531..a01ef457ef0 100644 --- a/system/btif/src/btif_sock_sdp.cc +++ b/system/btif/src/btif_sock_sdp.cc @@ -54,27 +54,27 @@ using bluetooth::Uuid; #define BTA_PBS_USERID_REQ FALSE static const tBTA_PBS_CFG bta_pbs_cfg = { - BTA_PBS_REALM_CHARSET, // realm_charset: Server only - BTA_PBS_USERID_REQ, // userid_req: Server only - (BTA_PBS_SUPF_DOWNLOAD | BTA_PBS_SURF_BROWSE), // supported_features - BTA_PBS_REPOSIT_LOCAL, // supported_repositories + BTA_PBS_REALM_CHARSET, // realm_charset: Server only + BTA_PBS_USERID_REQ, // userid_req: Server only + (BTA_PBS_SUPF_DOWNLOAD | BTA_PBS_SURF_BROWSE), // supported_features + BTA_PBS_REPOSIT_LOCAL, // supported_repositories }; // object format lookup table #define OBEX_PUSH_NUM_FORMATS 7 static const tBTA_OP_FMT bta_ops_obj_fmt[OBEX_PUSH_NUM_FORMATS] = { - BTA_OP_VCARD21_FMT, BTA_OP_VCARD30_FMT, BTA_OP_VCAL_FMT, BTA_OP_ICAL_FMT, - BTA_OP_VNOTE_FMT, BTA_OP_VMSG_FMT, BTA_OP_OTHER_FMT}; + BTA_OP_VCARD21_FMT, BTA_OP_VCARD30_FMT, BTA_OP_VCAL_FMT, BTA_OP_ICAL_FMT, + BTA_OP_VNOTE_FMT, BTA_OP_VMSG_FMT, BTA_OP_OTHER_FMT}; // TODO(jtgans): Figure out if we actually need this define. This is ifndef // defined in bt_target.h, but nowhere else, so right now, unless something // overrides this before bt_target.h sets it, it will always be bt_target.h's // version. #ifndef BTUI_OPS_FORMATS -#define BTUI_OPS_FORMATS \ - (BTA_OP_VCARD21_MASK | BTA_OP_VCARD30_MASK | BTA_OP_VCAL_MASK | \ - BTA_OP_ICAL_MASK | BTA_OP_VNOTE_MASK | BTA_OP_VMSG_MASK | BTA_OP_ANY_MASK) +#define BTUI_OPS_FORMATS \ + (BTA_OP_VCARD21_MASK | BTA_OP_VCARD30_MASK | BTA_OP_VCAL_MASK | BTA_OP_ICAL_MASK | \ + BTA_OP_VNOTE_MASK | BTA_OP_VMSG_MASK | BTA_OP_ANY_MASK) #endif #define RESERVED_SCN_PBS 19 @@ -91,10 +91,9 @@ static const tBTA_OP_FMT bta_ops_obj_fmt[OBEX_PUSH_NUM_FORMATS] = { // at the end of the protocol list. // // Returns true if successful, otherwise false. -static bool create_base_record(const uint32_t sdp_handle, const char* name, - const uint16_t channel, const bool with_obex) { - log::verbose("create_base_record: scn: {}, name: {}, with_obex: {}", channel, - name, with_obex); +static bool create_base_record(const uint32_t sdp_handle, const char* name, const uint16_t channel, + const bool with_obex) { + log::verbose("create_base_record: scn: {}, name: {}, with_obex: {}", channel, name, with_obex); // Setup the protocol list and add it. tSDP_PROTOCOL_ELEM proto_list[SDP_MAX_LIST_ELEMS]; @@ -117,50 +116,50 @@ static bool create_base_record(const uint32_t sdp_handle, const char* name, uint16_t list = UUID_SERVCLASS_PUBLIC_BROWSE_GROUP; const char* stage = "protocol_list"; - if (!get_legacy_stack_sdp_api()->handle.SDP_AddProtocolList( - sdp_handle, num_proto_elements, proto_list)) + if (!get_legacy_stack_sdp_api()->handle.SDP_AddProtocolList(sdp_handle, num_proto_elements, + proto_list)) { goto error; + } // Add the name to the SDP record. if (name[0] != '\0') { stage = "service_name"; if (!get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - sdp_handle, ATTR_ID_SERVICE_NAME, TEXT_STR_DESC_TYPE, - (uint32_t)strlen(name), (uint8_t*)name)) + sdp_handle, ATTR_ID_SERVICE_NAME, TEXT_STR_DESC_TYPE, (uint32_t)strlen(name), + (uint8_t*)name)) { goto error; + } } stage = "browseable"; - if (!get_legacy_stack_sdp_api()->handle.SDP_AddUuidSequence( - sdp_handle, ATTR_ID_BROWSE_GROUP_LIST, 1, &list)) + if (!get_legacy_stack_sdp_api()->handle.SDP_AddUuidSequence(sdp_handle, ATTR_ID_BROWSE_GROUP_LIST, + 1, &list)) { goto error; + } log::verbose( - "create_base_record: successfully created base service record, handle: " - "0x{:08x}, scn: {}, name: {}, with_obex: {}", - sdp_handle, channel, name, with_obex); + "create_base_record: successfully created base service record, handle: " + "0x{:08x}, scn: {}, name: {}, with_obex: {}", + sdp_handle, channel, name, with_obex); return true; error: log::error( - "create_base_record: failed to create base service record, stage: {}, " - "scn: {}, name: {}, with_obex: {}", - stage, channel, name, with_obex); + "create_base_record: failed to create base service record, stage: {}, " + "scn: {}, name: {}, with_obex: {}", + stage, channel, name, with_obex); return false; } // Registers a service with the given |name|, |uuid|, and |channel| in the SDP // database as a generic L2CAP RFCOMM protocol, storing its |uuid| as a service // class sequence. -static int add_sdp_by_uuid(const char* name, const Uuid& uuid, - const uint16_t channel) { - log::verbose("uuid: {}, scn: {}, service_name: {}", uuid.ToString(), channel, - name); +static int add_sdp_by_uuid(const char* name, const Uuid& uuid, const uint16_t channel) { + log::verbose("uuid: {}, scn: {}, service_name: {}", uuid.ToString(), channel, name); uint32_t handle = get_legacy_stack_sdp_api()->handle.SDP_CreateRecord(); if (handle == 0) { - log::error("failed to create sdp record, scn: {}, service_name: {}", - channel, name); + log::error("failed to create sdp record, scn: {}, service_name: {}", channel, name); return 0; } @@ -176,8 +175,9 @@ static int add_sdp_by_uuid(const char* name, const Uuid& uuid, // Create the base SDP record. const char* stage = "create_base_record"; - if (!create_base_record(handle, name, channel, false /* with_obex */)) + if (!create_base_record(handle, name, channel, false /* with_obex */)) { goto error; + } // Do the conversion to big-endian -- tmp is only used to iterate through the // UUID array in the macro and serves no other purpose as the conversion @@ -186,14 +186,13 @@ static int add_sdp_by_uuid(const char* name, const Uuid& uuid, { ARRAY_TO_BE_STREAM(tmp, uuid.To128BitBE().data(), UUID_MAX_LENGTH); } stage = "service_class_sequence"; - if (!get_legacy_stack_sdp_api()->handle.SDP_AddSequence( - handle, (uint16_t)ATTR_ID_SERVICE_CLASS_ID_LIST, 1, &type, &type_len, - &type_buf_ptr)) + if (!get_legacy_stack_sdp_api()->handle.SDP_AddSequence(handle, + (uint16_t)ATTR_ID_SERVICE_CLASS_ID_LIST, + 1, &type, &type_len, &type_buf_ptr)) { goto error; + } - log::verbose( - "service registered successfully, service_name: {}, handle: 0x{:08x}", - name, handle); + log::verbose("service registered successfully, service_name: {}, handle: 0x{:08x}", name, handle); { // Write the custom 128-bit UUID to EIR @@ -207,8 +206,7 @@ error: if (get_legacy_stack_sdp_api()->handle.SDP_DeleteRecord(handle)) { log::warn("Unable to delete SDP record handle:{}", handle); } - log::error("failed to register service stage: {}, service_name: {}", stage, - name); + log::error("failed to register service stage: {}, service_name: {}", stage, name); return 0; } @@ -219,8 +217,7 @@ static int add_pbap_sdp(const char* name, const int channel) { uint32_t handle = get_legacy_stack_sdp_api()->handle.SDP_CreateRecord(); if (handle == 0) { - log::error("add_pbap_sdp: failed to create sdp record, service_name: {}", - name); + log::error("add_pbap_sdp: failed to create sdp record, service_name: {}", name); return 0; } @@ -228,34 +225,37 @@ static int add_pbap_sdp(const char* name, const int channel) { // Create the base SDP record. const char* stage = "create_base_record"; - if (!create_base_record(handle, name, channel, true /* with_obex */)) + if (!create_base_record(handle, name, channel, true /* with_obex */)) { goto error; + } // Add service class stage = "service_class"; - if (!get_legacy_stack_sdp_api()->handle.SDP_AddServiceClassIdList(handle, 1, - &service)) + if (!get_legacy_stack_sdp_api()->handle.SDP_AddServiceClassIdList(handle, 1, &service)) { goto error; + } // Add in the phone access descriptor stage = "profile_descriptor_list"; if (!get_legacy_stack_sdp_api()->handle.SDP_AddProfileDescriptorList( - handle, UUID_SERVCLASS_PHONE_ACCESS, BTA_PBS_DEFAULT_VERSION)) + handle, UUID_SERVCLASS_PHONE_ACCESS, BTA_PBS_DEFAULT_VERSION)) { goto error; + } // Set up our supported repositories stage = "supported_repositories"; if (!get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - handle, ATTR_ID_SUPPORTED_REPOSITORIES, UINT_DESC_TYPE, 1, - (uint8_t*)&bta_pbs_cfg.supported_repositories)) + handle, ATTR_ID_SUPPORTED_REPOSITORIES, UINT_DESC_TYPE, 1, + (uint8_t*)&bta_pbs_cfg.supported_repositories)) { goto error; + } // Notify the system that we've got a new service class UUID. bta_sys_add_uuid(UUID_SERVCLASS_PBAP_PSE); log::verbose( - "add_pbap_sdp: service registered successfully, service_name: {}, " - "handle: 0x{:08x}", - name, handle); + "add_pbap_sdp: service registered successfully, service_name: {}, " + "handle: 0x{:08x}", + name, handle); return handle; @@ -264,9 +264,9 @@ error: log::warn("Unable to delete SDP record handle:{}", handle); } log::error( - "add_pbap_sdp: failed to register PBAP service, stage: {}, service_name: " - "{}", - stage, name); + "add_pbap_sdp: failed to register PBAP service, stage: {}, service_name: " + "{}", + stage, name); return 0; } // Registers a service with the given |name| and |channel| as an OBEX Push @@ -276,8 +276,7 @@ static int add_ops_sdp(const char* name, const int channel) { uint32_t handle = get_legacy_stack_sdp_api()->handle.SDP_CreateRecord(); if (handle == 0) { - log::error("add_ops_sdp: failed to create sdp record, service_name: {}", - name); + log::error("add_ops_sdp: failed to create sdp record, service_name: {}", name); return 0; } @@ -292,20 +291,22 @@ static int add_ops_sdp(const char* name, const int channel) { // Create the base SDP record. const char* stage = "create_base_record"; - if (!create_base_record(handle, name, channel, true /* with_obex */)) + if (!create_base_record(handle, name, channel, true /* with_obex */)) { goto error; + } // Add service class. stage = "service_class"; - if (!get_legacy_stack_sdp_api()->handle.SDP_AddServiceClassIdList(handle, 1, - &service)) + if (!get_legacy_stack_sdp_api()->handle.SDP_AddServiceClassIdList(handle, 1, &service)) { goto error; + } // Add the OBEX push profile descriptor. stage = "profile_descriptor_list"; if (!get_legacy_stack_sdp_api()->handle.SDP_AddProfileDescriptorList( - handle, UUID_SERVCLASS_OBEX_OBJECT_PUSH, 0x0100)) + handle, UUID_SERVCLASS_OBEX_OBJECT_PUSH, 0x0100)) { goto error; + } for (int i = 0; i < OBEX_PUSH_NUM_FORMATS; i++) { if ((BTUI_OPS_FORMATS >> i) & 1) { @@ -316,22 +317,25 @@ static int add_ops_sdp(const char* name, const int channel) { } stage = "supported_types"; - if (!get_legacy_stack_sdp_api()->handle.SDP_AddSequence( - handle, (uint16_t)ATTR_ID_SUPPORTED_FORMATS_LIST, j, desc_type, - type_len, type_value)) + if (!get_legacy_stack_sdp_api()->handle.SDP_AddSequence(handle, + (uint16_t)ATTR_ID_SUPPORTED_FORMATS_LIST, + j, desc_type, type_len, type_value)) { goto error; + } // Set class of device. cod.service = BTM_COD_SERVICE_OBJ_TRANSFER; stage = "class_of_device"; - if (!utl_set_device_class(&cod, BTA_UTL_SET_COD_SERVICE_CLASS)) goto error; + if (!utl_set_device_class(&cod, BTA_UTL_SET_COD_SERVICE_CLASS)) { + goto error; + } // Notify the system that we've got a new service class UUID. bta_sys_add_uuid(UUID_SERVCLASS_OBEX_OBJECT_PUSH); log::verbose( - "ad_maps_sdp: service registered successfully, service_name: {}, handle " - "0x{:08x})", - name, handle); + "ad_maps_sdp: service registered successfully, service_name: {}, handle " + "0x{:08x})", + name, handle); return handle; @@ -340,9 +344,9 @@ error: log::warn("Unable to delete SDP record handle:{}", handle); } log::error( - "add_ops_sdp: failed to register OPS service, stage: {}, service_name: " - "{}", - stage, name); + "add_ops_sdp: failed to register OPS service, stage: {}, service_name: " + "{}", + stage, name); return 0; } @@ -353,8 +357,7 @@ static int add_spp_sdp(const char* name, const int channel) { int handle = get_legacy_stack_sdp_api()->handle.SDP_CreateRecord(); if (handle == 0) { - log::error("add_spp_sdp: failed to create sdp record, service_name: {}", - name); + log::error("add_spp_sdp: failed to create sdp record, service_name: {}", name); return 0; } @@ -362,23 +365,25 @@ static int add_spp_sdp(const char* name, const int channel) { const char* stage = "create_base_record"; uint16_t service = UUID_SERVCLASS_SERIAL_PORT; - if (!create_base_record(handle, name, channel, false /* with_obex */)) + if (!create_base_record(handle, name, channel, false /* with_obex */)) { goto error; + } stage = "service_class"; - if (!get_legacy_stack_sdp_api()->handle.SDP_AddServiceClassIdList(handle, 1, - &service)) + if (!get_legacy_stack_sdp_api()->handle.SDP_AddServiceClassIdList(handle, 1, &service)) { goto error; + } stage = "profile_descriptor_list"; if (!get_legacy_stack_sdp_api()->handle.SDP_AddProfileDescriptorList( - handle, UUID_SERVCLASS_SERIAL_PORT, SPP_PROFILE_VERSION)) + handle, UUID_SERVCLASS_SERIAL_PORT, SPP_PROFILE_VERSION)) { goto error; + } log::verbose( - "add_spp_sdp: service registered successfully, service_name: {}, handle " - "0x{:08x})", - name, handle); + "add_spp_sdp: service registered successfully, service_name: {}, handle " + "0x{:08x})", + name, handle); return handle; @@ -387,9 +392,9 @@ error: log::warn("Unable to delete SDP record handle:{}", handle); } log::error( - "add_spp_sdp: failed to register SPP service, stage: {}, service_name: " - "{}", - stage, name); + "add_spp_sdp: failed to register SPP service, stage: {}, service_name: " + "{}", + stage, name); return 0; } @@ -397,10 +402,8 @@ error: // |channel|. This function attempts to identify the type of the service based // upon its |uuid|, and will override the |channel| with a reserved channel // number if the |uuid| matches one of the preregistered bluez SDP records. -static int add_rfc_sdp_by_uuid(const char* name, const Uuid& uuid, - const int channel) { - log::verbose("uuid: {}, service_name: {}, channel: {}", uuid.ToString(), name, - channel); +static int add_rfc_sdp_by_uuid(const char* name, const Uuid& uuid, const int channel) { + log::verbose("uuid: {}, service_name: {}, channel: {}", uuid.ToString(), name, channel); /* * Bluetooth Socket API relies on having preregistered bluez sdp records for diff --git a/system/btif/src/btif_sock_thread.cc b/system/btif/src/btif_sock_thread.cc index 59a4dff65a7..81c093b9ce5 100644 --- a/system/btif/src/btif_sock_thread.cc +++ b/system/btif/src/btif_sock_thread.cc @@ -50,17 +50,18 @@ #include "os/log.h" #include "osi/include/osi.h" // OSI_NO_INTR -#define asrt(s) \ - do { \ - if (!(s)) log::error("## assert {} failed ##", #s); \ +#define asrt(s) \ + do { \ + if (!(s)) \ + log::error("## assert {} failed ##", #s); \ } while (0) #define MAX_THREAD 8 #define MAX_POLL 64 #define POLL_EXCEPTION_EVENTS (POLLHUP | POLLRDHUP | POLLERR | POLLNVAL) -#define IS_EXCEPTION(e) ((e)&POLL_EXCEPTION_EVENTS) -#define IS_READ(e) ((e)&POLLIN) -#define IS_WRITE(e) ((e)&POLLOUT) +#define IS_EXCEPTION(e) ((e) & POLL_EXCEPTION_EVENTS) +#define IS_READ(e) ((e) & POLLIN) +#define IS_WRITE(e) ((e) & POLLOUT) /*cmd executes in socket poll thread */ #define CMD_WAKEUP 1 #define CMD_EXIT 2 @@ -91,13 +92,11 @@ static thread_slot_t ts[MAX_THREAD]; static void* sock_poll_thread(void* arg); static inline void close_cmd_fd(int h); -static inline void add_poll(int h, int fd, int type, int flags, - uint32_t user_id); +static inline void add_poll(int h, int fd, int type, int flags, uint32_t user_id); static std::recursive_mutex thread_slot_lock; -static inline int create_thread(void* (*start_routine)(void*), void* arg, - pthread_t* thread_id) { +static inline int create_thread(void* (*start_routine)(void*), void* arg, pthread_t* thread_id) { pthread_attr_t thread_attr; pthread_attr_init(&thread_attr); pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_JOINABLE); @@ -139,8 +138,9 @@ static void free_thread_slot(int h) { if (0 <= h && h < MAX_THREAD) { close_cmd_fd(h); ts[h].used = 0; - } else + } else { log::error("invalid thread handle:{}", h); + } } void btsock_thread_init() { static int initialized; @@ -157,8 +157,7 @@ void btsock_thread_init() { } } } -int btsock_thread_create(btsock_signaled_cb callback, - btsock_cmd_cb cmd_callback) { +int btsock_thread_create(btsock_signaled_cb callback, btsock_cmd_cb cmd_callback) { asrt(callback || cmd_callback); int h = alloc_thread_slot(); if (h >= 0) { @@ -222,8 +221,7 @@ int btsock_thread_add_fd(int h, int fd, int type, int flags, uint32_t user_id) { add_poll(h, fd, type, flags, user_id); return true; } - log::warn( - "THREAD_ADD_FD_SYNC is not called in poll thread, fallback to async"); + log::warn("THREAD_ADD_FD_SYNC is not called in poll thread, fallback to async"); } sock_cmd_t cmd = {CMD_ADD_FD, fd, type, flags, user_id}; @@ -286,26 +284,28 @@ static void init_poll(int h) { } static inline unsigned int flags2pevents(int flags) { unsigned int pevents = 0; - if (flags & SOCK_THREAD_FD_WR) pevents |= POLLOUT; - if (flags & SOCK_THREAD_FD_RD) pevents |= POLLIN; + if (flags & SOCK_THREAD_FD_WR) { + pevents |= POLLOUT; + } + if (flags & SOCK_THREAD_FD_RD) { + pevents |= POLLIN; + } pevents |= POLL_EXCEPTION_EVENTS; return pevents; } -static inline void set_poll(poll_slot_t* ps, int fd, int type, int flags, - uint32_t user_id) { +static inline void set_poll(poll_slot_t* ps, int fd, int type, int flags, uint32_t user_id) { ps->pfd.fd = fd; ps->user_id = user_id; - if (ps->type != 0 && ps->type != type) - log::error("poll socket type should not changed! type was:{}, type now:{}", - ps->type, type); + if (ps->type != 0 && ps->type != type) { + log::error("poll socket type should not changed! type was:{}, type now:{}", ps->type, type); + } ps->type = type; ps->flags = flags; ps->pfd.events = flags2pevents(flags); ps->pfd.revents = 0; } -static inline void add_poll(int h, int fd, int type, int flags, - uint32_t user_id) { +static inline void add_poll(int h, int fd, int type, int flags, uint32_t user_id) { asrt(fd != -1); int i; int empty = -1; @@ -317,8 +317,9 @@ static inline void add_poll(int h, int fd, int type, int flags, set_poll(&ps[i], fd, type, flags | ps[i].flags, user_id); return; - } else if (empty < 0 && ps[i].pfd.fd == -1) + } else if (empty < 0 && ps[i].pfd.fd == -1) { empty = i; + } } if (empty >= 0) { asrt(ts[h].poll_count < MAX_POLL); @@ -370,8 +371,9 @@ static int process_cmd_sock(int h) { break; case CMD_USER_PRIVATE: asrt(ts[h].cmd_callback); - if (ts[h].cmd_callback) + if (ts[h].cmd_callback) { ts[h].cmd_callback(fd, cmd.type, cmd.flags, cmd.user_id); + } break; case CMD_EXIT: return false; @@ -382,8 +384,7 @@ static int process_cmd_sock(int h) { return true; } -static void process_data_sock(int h, struct pollfd* pfds, int pfds_count, - int event_count) { +static void process_data_sock(int h, struct pollfd* pfds, int pfds_count, int event_count) { asrt(event_count <= pfds_count); int i; for (i = 1; i < pfds_count; i++) { @@ -407,10 +408,13 @@ static void process_data_sock(int h, struct pollfd* pfds, int pfds_count, flags |= SOCK_THREAD_FD_EXCEPTION; // remove the whole slot not flags remove_poll(h, &ts[h].ps[ps_i], ts[h].ps[ps_i].flags); - } else if (flags) + } else if (flags) { remove_poll(h, &ts[h].ps[ps_i], flags); // remove the monitor flags that already processed - if (flags) ts[h].callback(pfds[i].fd, type, flags, user_id); + } + if (flags) { + ts[h].callback(pfds[i].fd, type, flags, user_id); + } } } } @@ -423,9 +427,9 @@ static void prepare_poll_fds(int h, struct pollfd* pfds) { while (count < ts[h].poll_count) { if (ps_i >= MAX_POLL) { log::error( - "exceed max poll range, ps_i:{}, MAX_POLL:{}, count:{}, " - "ts[h].poll_count:{}", - ps_i, MAX_POLL, count, ts[h].poll_count); + "exceed max poll range, ps_i:{}, MAX_POLL:{}, count:{}, " + "ts[h].poll_count:{}", + ps_i, MAX_POLL, count, ts[h].poll_count); return; } if (ts[h].ps[ps_i].pfd.fd >= 0) { @@ -447,8 +451,7 @@ static void* sock_poll_thread(void* arg) { int ret; OSI_NO_INTR(ret = poll(pfds.data(), ts[h].poll_count, -1)); if (ret == -1) { - log::error("poll ret -1, exit the thread, errno:{}, err:{}", errno, - strerror(errno)); + log::error("poll ret -1, exit the thread, errno:{}, err:{}", errno, strerror(errno)); break; } if (ret != 0) { @@ -461,13 +464,15 @@ static void* sock_poll_thread(void* arg) { log::info("h:{}, process_cmd_sock return false, exit...", h); break; } - if (ret == 1) + if (ret == 1) { need_process_data_fd = false; - else + } else { ret--; // exclude the cmd fd + } } - if (need_process_data_fd) + if (need_process_data_fd) { process_data_sock(h, pfds.data(), pfds_count, ret); + } } else { log::info("no data, select ret: {}", ret); }; diff --git a/system/btif/src/btif_sock_util.cc b/system/btif/src/btif_sock_util.cc index ccdf71d155f..5b79bce333d 100644 --- a/system/btif/src/btif_sock_util.cc +++ b/system/btif/src/btif_sock_util.cc @@ -37,9 +37,10 @@ #include "os/log.h" #include "osi/include/osi.h" -#define asrt(s) \ - do { \ - if (!(s)) log::error("## assert {} failed ##", #s); \ +#define asrt(s) \ + do { \ + if (!(s)) \ + log::error("## assert {} failed ##", #s); \ } while (0) using namespace bluetooth; @@ -83,7 +84,9 @@ int sock_send_fd(int sock_fd, const uint8_t* buf, int len, int send_fd) { struct cmsghdr* cmsg; char msgbuf[CMSG_SPACE(1)]; asrt(send_fd != -1); - if (sock_fd == -1 || send_fd == -1) return -1; + if (sock_fd == -1 || send_fd == -1) { + return -1; + } // Add any pending outbound file descriptors to the message // See "man cmsg" really msg.msg_control = msgbuf; @@ -109,8 +112,8 @@ int sock_send_fd(int sock_fd, const uint8_t* buf, int len, int send_fd) { ssize_t ret; OSI_NO_INTR(ret = sendmsg(sock_fd, &msg, MSG_NOSIGNAL)); if (ret < 0) { - log::error("fd:{}, send_fd:{}, sendmsg ret:{}, errno:{}, {}", sock_fd, - send_fd, (int)ret, errno, strerror(errno)); + log::error("fd:{}, send_fd:{}, sendmsg ret:{}, errno:{}, {}", sock_fd, send_fd, (int)ret, + errno, strerror(errno)); ret_len = -1; break; } diff --git a/system/btif/src/btif_storage.cc b/system/btif/src/btif_storage.cc index f5fe0280122..b65b3584a11 100644 --- a/system/btif/src/btif_storage.cc +++ b/system/btif/src/btif_storage.cc @@ -75,24 +75,18 @@ struct BtifStorageKey { uint8_t size; }; static const BtifStorageKey BTIF_STORAGE_LE_KEYS[] = { - {BTM_LE_KEY_PENC, BTIF_STORAGE_KEY_LE_KEY_PENC, sizeof(tBTM_LE_PENC_KEYS)}, - {BTM_LE_KEY_PID, BTIF_STORAGE_KEY_LE_KEY_PID, sizeof(tBTM_LE_PID_KEYS)}, - {BTM_LE_KEY_PCSRK, BTIF_STORAGE_KEY_LE_KEY_PCSRK, - sizeof(tBTM_LE_PCSRK_KEYS)}, - {BTM_LE_KEY_LENC, BTIF_STORAGE_KEY_LE_KEY_LENC, sizeof(tBTM_LE_LENC_KEYS)}, - {BTM_LE_KEY_LCSRK, BTIF_STORAGE_KEY_LE_KEY_LCSRK, - sizeof(tBTM_LE_LCSRK_KEYS)}, - {BTM_LE_KEY_LID, BTIF_STORAGE_KEY_LE_KEY_LID, sizeof(tBTM_LE_PID_KEYS)}, + {BTM_LE_KEY_PENC, BTIF_STORAGE_KEY_LE_KEY_PENC, sizeof(tBTM_LE_PENC_KEYS)}, + {BTM_LE_KEY_PID, BTIF_STORAGE_KEY_LE_KEY_PID, sizeof(tBTM_LE_PID_KEYS)}, + {BTM_LE_KEY_PCSRK, BTIF_STORAGE_KEY_LE_KEY_PCSRK, sizeof(tBTM_LE_PCSRK_KEYS)}, + {BTM_LE_KEY_LENC, BTIF_STORAGE_KEY_LE_KEY_LENC, sizeof(tBTM_LE_LENC_KEYS)}, + {BTM_LE_KEY_LCSRK, BTIF_STORAGE_KEY_LE_KEY_LCSRK, sizeof(tBTM_LE_LCSRK_KEYS)}, + {BTM_LE_KEY_LID, BTIF_STORAGE_KEY_LE_KEY_LID, sizeof(tBTM_LE_PID_KEYS)}, }; static const BtifStorageKey BTIF_STORAGE_LOCAL_LE_KEYS[] = { - {BTIF_DM_LE_LOCAL_KEY_IR, BTIF_STORAGE_KEY_LE_LOCAL_KEY_IR, - sizeof(Octet16)}, - {BTIF_DM_LE_LOCAL_KEY_IRK, BTIF_STORAGE_KEY_LE_LOCAL_KEY_IRK, - sizeof(Octet16)}, - {BTIF_DM_LE_LOCAL_KEY_DHK, BTIF_STORAGE_KEY_LE_LOCAL_KEY_DHK, - sizeof(Octet16)}, - {BTIF_DM_LE_LOCAL_KEY_ER, BTIF_STORAGE_KEY_LE_LOCAL_KEY_ER, - sizeof(Octet16)}, + {BTIF_DM_LE_LOCAL_KEY_IR, BTIF_STORAGE_KEY_LE_LOCAL_KEY_IR, sizeof(Octet16)}, + {BTIF_DM_LE_LOCAL_KEY_IRK, BTIF_STORAGE_KEY_LE_LOCAL_KEY_IRK, sizeof(Octet16)}, + {BTIF_DM_LE_LOCAL_KEY_DHK, BTIF_STORAGE_KEY_LE_LOCAL_KEY_DHK, sizeof(Octet16)}, + {BTIF_DM_LE_LOCAL_KEY_ER, BTIF_STORAGE_KEY_LE_LOCAL_KEY_ER, sizeof(Octet16)}, }; /******************************************************************************* @@ -128,15 +122,14 @@ static bool prop2cfg(const RawAddress* remote_bd_addr, bt_property_t* prop) { char value[1024]; if (prop->len <= 0 || prop->len > static_cast(sizeof(value)) - 1) { log::warn( - "Unable to save property to configuration file type:{}, len:{} is " - "invalid", - prop->type, prop->len); + "Unable to save property to configuration file type:{}, len:{} is " + "invalid", + prop->type, prop->len); return false; } switch (prop->type) { case BT_PROPERTY_REMOTE_DEVICE_TIMESTAMP: - btif_config_set_int(bdstr, BTIF_STORAGE_KEY_TIMESTAMP, - static_cast(time(NULL))); + btif_config_set_int(bdstr, BTIF_STORAGE_KEY_TIMESTAMP, static_cast(time(NULL))); break; case BT_PROPERTY_BDNAME: { int name_length = prop->len > BD_NAME_LEN ? BD_NAME_LEN : prop->len; @@ -145,8 +138,7 @@ static bool prop2cfg(const RawAddress* remote_bd_addr, bt_property_t* prop) { if (remote_bd_addr) { btif_config_set_str(bdstr, BTIF_STORAGE_KEY_NAME, value); } else { - btif_config_set_str(BTIF_STORAGE_SECTION_ADAPTER, BTIF_STORAGE_KEY_NAME, - value); + btif_config_set_str(BTIF_STORAGE_SECTION_ADAPTER, BTIF_STORAGE_KEY_NAME, value); } break; } @@ -156,17 +148,14 @@ static bool prop2cfg(const RawAddress* remote_bd_addr, bt_property_t* prop) { btif_config_set_str(bdstr, BTIF_STORAGE_KEY_ALIAS, value); break; case BT_PROPERTY_ADAPTER_DISCOVERABLE_TIMEOUT: - btif_config_set_int(BTIF_STORAGE_SECTION_ADAPTER, - BTIF_STORAGE_KEY_DISC_TIMEOUT, + btif_config_set_int(BTIF_STORAGE_SECTION_ADAPTER, BTIF_STORAGE_KEY_DISC_TIMEOUT, *reinterpret_cast(prop->val)); break; case BT_PROPERTY_CLASS_OF_DEVICE: - btif_config_set_int(bdstr, BTIF_STORAGE_KEY_DEV_CLASS, - *reinterpret_cast(prop->val)); + btif_config_set_int(bdstr, BTIF_STORAGE_KEY_DEV_CLASS, *reinterpret_cast(prop->val)); break; case BT_PROPERTY_TYPE_OF_DEVICE: - btif_config_set_int(bdstr, BTIF_STORAGE_KEY_DEV_TYPE, - *reinterpret_cast(prop->val)); + btif_config_set_int(bdstr, BTIF_STORAGE_KEY_DEV_TYPE, *reinterpret_cast(prop->val)); break; case BT_PROPERTY_UUIDS: { std::string val; @@ -178,29 +167,27 @@ static bool prop2cfg(const RawAddress* remote_bd_addr, bt_property_t* prop) { break; } case BT_PROPERTY_REMOTE_VERSION_INFO: { - bt_remote_version_t* info = - reinterpret_cast(prop->val); + bt_remote_version_t* info = reinterpret_cast(prop->val); - if (!info) return false; + if (!info) { + return false; + } - btif_config_set_int(bdstr, BTIF_STORAGE_KEY_REMOTE_VER_MFCT, - info->manufacturer); - btif_config_set_int(bdstr, BTIF_STORAGE_KEY_REMOTE_VER_VER, - info->version); - btif_config_set_int(bdstr, BTIF_STORAGE_KEY_REMOTE_VER_SUBVER, - info->sub_ver); + btif_config_set_int(bdstr, BTIF_STORAGE_KEY_REMOTE_VER_MFCT, info->manufacturer); + btif_config_set_int(bdstr, BTIF_STORAGE_KEY_REMOTE_VER_VER, info->version); + btif_config_set_int(bdstr, BTIF_STORAGE_KEY_REMOTE_VER_SUBVER, info->sub_ver); } break; case BT_PROPERTY_APPEARANCE: { int val = *reinterpret_cast(prop->val); btif_config_set_int(bdstr, BTIF_STORAGE_KEY_APPEARANCE, val); } break; case BT_PROPERTY_VENDOR_PRODUCT_INFO: { - bt_vendor_product_info_t* info = - reinterpret_cast(prop->val); - if (!info) return false; + bt_vendor_product_info_t* info = reinterpret_cast(prop->val); + if (!info) { + return false; + } - btif_config_set_int(bdstr, BTIF_STORAGE_KEY_VENDOR_ID_SOURCE, - info->vendor_id_src); + btif_config_set_int(bdstr, BTIF_STORAGE_KEY_VENDOR_ID_SOURCE, info->vendor_id_src); btif_config_set_int(bdstr, BTIF_STORAGE_KEY_VENDOR_ID, info->vendor_id); btif_config_set_int(bdstr, BTIF_STORAGE_KEY_PRODUCT_ID, info->product_id); btif_config_set_int(bdstr, BTIF_STORAGE_KEY_VERSION, info->version); @@ -232,26 +219,27 @@ static bool cfg2prop(const RawAddress* remote_bd_addr, bt_property_t* prop) { bdstr = remote_bd_addr->ToString(); } if (prop->len <= 0) { - log::warn("Invalid property read from configuration file type:{}, len:{}", - prop->type, prop->len); + log::warn("Invalid property read from configuration file type:{}, len:{}", prop->type, + prop->len); return false; } bool ret = false; switch (prop->type) { case BT_PROPERTY_REMOTE_DEVICE_TIMESTAMP: - if (prop->len >= static_cast(sizeof(int))) + if (prop->len >= static_cast(sizeof(int))) { ret = btif_config_get_int(bdstr, BTIF_STORAGE_KEY_TIMESTAMP, reinterpret_cast(prop->val)); + } break; case BT_PROPERTY_BDNAME: { int len = prop->len; - if (remote_bd_addr) - ret = btif_config_get_str(bdstr, BTIF_STORAGE_KEY_NAME, - reinterpret_cast(prop->val), &len); - else - ret = btif_config_get_str(BTIF_STORAGE_SECTION_ADAPTER, - BTIF_STORAGE_KEY_NAME, + if (remote_bd_addr) { + ret = btif_config_get_str(bdstr, BTIF_STORAGE_KEY_NAME, reinterpret_cast(prop->val), + &len); + } else { + ret = btif_config_get_str(BTIF_STORAGE_SECTION_ADAPTER, BTIF_STORAGE_KEY_NAME, reinterpret_cast(prop->val), &len); + } if (ret && len && len <= prop->len) { prop->len = len - 1; } else { @@ -262,8 +250,8 @@ static bool cfg2prop(const RawAddress* remote_bd_addr, bt_property_t* prop) { } case BT_PROPERTY_REMOTE_FRIENDLY_NAME: { int len = prop->len; - ret = btif_config_get_str(bdstr, BTIF_STORAGE_KEY_ALIAS, - reinterpret_cast(prop->val), &len); + ret = btif_config_get_str(bdstr, BTIF_STORAGE_KEY_ALIAS, reinterpret_cast(prop->val), + &len); if (ret && len && len <= prop->len) { prop->len = len - 1; } else { @@ -273,29 +261,29 @@ static bool cfg2prop(const RawAddress* remote_bd_addr, bt_property_t* prop) { break; } case BT_PROPERTY_ADAPTER_DISCOVERABLE_TIMEOUT: - if (prop->len >= static_cast(sizeof(int))) - ret = btif_config_get_int(BTIF_STORAGE_SECTION_ADAPTER, - BTIF_STORAGE_KEY_DISC_TIMEOUT, + if (prop->len >= static_cast(sizeof(int))) { + ret = btif_config_get_int(BTIF_STORAGE_SECTION_ADAPTER, BTIF_STORAGE_KEY_DISC_TIMEOUT, reinterpret_cast(prop->val)); + } break; case BT_PROPERTY_CLASS_OF_DEVICE: - if (prop->len >= static_cast(sizeof(int))) + if (prop->len >= static_cast(sizeof(int))) { ret = btif_config_get_int(bdstr, BTIF_STORAGE_KEY_DEV_CLASS, reinterpret_cast(prop->val)); + } break; case BT_PROPERTY_TYPE_OF_DEVICE: - if (prop->len >= static_cast(sizeof(int))) + if (prop->len >= static_cast(sizeof(int))) { ret = btif_config_get_int(bdstr, BTIF_STORAGE_KEY_DEV_TYPE, reinterpret_cast(prop->val)); + } break; case BT_PROPERTY_UUIDS: { char value[1280]; int size = sizeof(value); - if (btif_config_get_str(bdstr, BTIF_STORAGE_KEY_REMOTE_SERVICE, value, - &size)) { + if (btif_config_get_str(bdstr, BTIF_STORAGE_KEY_REMOTE_SERVICE, value, &size)) { Uuid* p_uuid = reinterpret_cast(prop->val); - size_t num_uuids = - btif_split_uuids_string(value, p_uuid, BT_MAX_NUM_UUIDS); + size_t num_uuids = btif_split_uuids_string(value, p_uuid, BT_MAX_NUM_UUIDS); prop->len = num_uuids * sizeof(Uuid); ret = true; } else { @@ -305,20 +293,18 @@ static bool cfg2prop(const RawAddress* remote_bd_addr, bt_property_t* prop) { } break; case BT_PROPERTY_REMOTE_VERSION_INFO: { - bt_remote_version_t* info = - reinterpret_cast(prop->val); + bt_remote_version_t* info = reinterpret_cast(prop->val); if (prop->len >= static_cast(sizeof(bt_remote_version_t))) { - ret = btif_config_get_int(bdstr, BTIF_STORAGE_KEY_REMOTE_VER_MFCT, - &info->manufacturer); + ret = btif_config_get_int(bdstr, BTIF_STORAGE_KEY_REMOTE_VER_MFCT, &info->manufacturer); - if (ret) - ret = btif_config_get_int(bdstr, BTIF_STORAGE_KEY_REMOTE_VER_VER, - &info->version); + if (ret) { + ret = btif_config_get_int(bdstr, BTIF_STORAGE_KEY_REMOTE_VER_VER, &info->version); + } - if (ret) - ret = btif_config_get_int(bdstr, BTIF_STORAGE_KEY_REMOTE_VER_SUBVER, - &info->sub_ver); + if (ret) { + ret = btif_config_get_int(bdstr, BTIF_STORAGE_KEY_REMOTE_VER_SUBVER, &info->sub_ver); + } } } break; @@ -332,13 +318,11 @@ static bool cfg2prop(const RawAddress* remote_bd_addr, bt_property_t* prop) { } break; case BT_PROPERTY_VENDOR_PRODUCT_INFO: { - bt_vendor_product_info_t* info = - reinterpret_cast(prop->val); + bt_vendor_product_info_t* info = reinterpret_cast(prop->val); int val; if (prop->len >= static_cast(sizeof(bt_vendor_product_info_t))) { - ret = - btif_config_get_int(bdstr, BTIF_STORAGE_KEY_VENDOR_ID_SOURCE, &val); + ret = btif_config_get_int(bdstr, BTIF_STORAGE_KEY_VENDOR_ID_SOURCE, &val); info->vendor_id_src = static_cast(val); if (ret) { @@ -381,8 +365,7 @@ static bool cfg2prop(const RawAddress* remote_bd_addr, bt_property_t* prop) { int val; if (prop->len >= static_cast(sizeof(uint8_t))) { - ret = btif_config_get_int( - bdstr, BTIF_STORAGE_KEY_SECURE_CONNECTIONS_SUPPORTED, &val); + ret = btif_config_get_int(bdstr, BTIF_STORAGE_KEY_SECURE_CONNECTIONS_SUPPORTED, &val); *reinterpret_cast(prop->val) = (uint8_t)val; } } break; @@ -391,8 +374,7 @@ static bool cfg2prop(const RawAddress* remote_bd_addr, bt_property_t* prop) { int val; if (prop->len >= static_cast(sizeof(uint8_t))) { - ret = btif_config_get_int(bdstr, BTIF_STORAGE_KEY_MAX_SESSION_KEY_SIZE, - &val); + ret = btif_config_get_int(bdstr, BTIF_STORAGE_KEY_MAX_SESSION_KEY_SIZE, &val); *reinterpret_cast(prop->val) = (uint8_t)val; } } break; @@ -419,18 +401,15 @@ bt_status_t btif_in_fetch_bonded_device(const std::string& bdstr) { LinkKey link_key; size_t size = link_key.size(); - if (btif_config_get_bin(bdstr, BTIF_STORAGE_KEY_LINK_KEY, link_key.data(), - &size)) { + if (btif_config_get_bin(bdstr, BTIF_STORAGE_KEY_LINK_KEY, link_key.data(), &size)) { int linkkey_type; - if (btif_config_get_int(bdstr, BTIF_STORAGE_KEY_LINK_KEY_TYPE, - &linkkey_type)) { + if (btif_config_get_int(bdstr, BTIF_STORAGE_KEY_LINK_KEY_TYPE, &linkkey_type)) { bt_linkkey_file_found = true; } else { bt_linkkey_file_found = false; } } - if ((btif_in_fetch_bonded_ble_device(bdstr, false, NULL) != - BT_STATUS_SUCCESS) && + if ((btif_in_fetch_bonded_ble_device(bdstr, false, NULL) != BT_STATUS_SUCCESS) && (!bt_linkkey_file_found)) { return BT_STATUS_DEVICE_NOT_FOUND; } @@ -447,8 +426,7 @@ bt_status_t btif_in_fetch_bonded_device(const std::string& bdstr) { * Returns BT_STATUS_SUCCESS if successful, BT_STATUS_FAIL otherwise * ******************************************************************************/ -static bt_status_t btif_in_fetch_bonded_devices( - btif_bonded_devices_t* p_bonded_devices, int add) { +static bt_status_t btif_in_fetch_bonded_devices(btif_bonded_devices_t* p_bonded_devices, int add) { memset(p_bonded_devices, 0, sizeof(btif_bonded_devices_t)); bool bt_linkkey_file_found = false; @@ -460,23 +438,20 @@ static bt_status_t btif_in_fetch_bonded_devices( log::verbose("Remote device:{}", bd_addr); LinkKey link_key; size_t size = sizeof(link_key); - if (btif_config_get_bin(name, BTIF_STORAGE_KEY_LINK_KEY, link_key.data(), - &size)) { + if (btif_config_get_bin(name, BTIF_STORAGE_KEY_LINK_KEY, link_key.data(), &size)) { int linkkey_type; - if (btif_config_get_int(name, BTIF_STORAGE_KEY_LINK_KEY_TYPE, - &linkkey_type)) { + if (btif_config_get_int(name, BTIF_STORAGE_KEY_LINK_KEY_TYPE, &linkkey_type)) { if (add) { DEV_CLASS dev_class = {0, 0, 0}; int cod; int pin_length = 0; - if (btif_config_get_int(name, BTIF_STORAGE_KEY_DEV_CLASS, &cod)) + if (btif_config_get_int(name, BTIF_STORAGE_KEY_DEV_CLASS, &cod)) { dev_class = uint2devclass((uint32_t)cod); + } btif_config_get_int(name, BTIF_STORAGE_KEY_PIN_LENGTH, &pin_length); - BTA_DmAddDevice(bd_addr, dev_class, link_key, (uint8_t)linkkey_type, - pin_length); + BTA_DmAddDevice(bd_addr, dev_class, link_key, (uint8_t)linkkey_type, pin_length); - if (btif_config_get_int(name, BTIF_STORAGE_KEY_DEV_TYPE, - &device_type) && + if (btif_config_get_int(name, BTIF_STORAGE_KEY_DEV_TYPE, &device_type) && (device_type == BT_DEVICE_TYPE_DUMO)) { btif_gatts_add_bonded_dev_from_nv(bd_addr); } @@ -491,27 +466,23 @@ static bt_status_t btif_in_fetch_bonded_devices( bt_linkkey_file_found = false; } } - if (!btif_in_fetch_bonded_ble_device(name, add, p_bonded_devices) && - !bt_linkkey_file_found) { + if (!btif_in_fetch_bonded_ble_device(name, add, p_bonded_devices) && !bt_linkkey_file_found) { log::verbose("No link key or ble key found for device:{}", bd_addr); } } return BT_STATUS_SUCCESS; } -static void btif_read_le_key(const uint8_t key_type, const size_t key_len, - RawAddress bd_addr, const tBLE_ADDR_TYPE addr_type, - const bool add_key, bool* device_added, +static void btif_read_le_key(const uint8_t key_type, const size_t key_len, RawAddress bd_addr, + const tBLE_ADDR_TYPE addr_type, const bool add_key, bool* device_added, bool* key_found) { - log::assert_that(device_added != nullptr, - "assert failed: device_added != nullptr"); + log::assert_that(device_added != nullptr, "assert failed: device_added != nullptr"); log::assert_that(key_found != nullptr, "assert failed: key_found != nullptr"); tBTA_LE_KEY_VALUE key; memset(&key, 0, sizeof(key)); - if (btif_storage_get_ble_bonding_key(bd_addr, key_type, - reinterpret_cast(&key), + if (btif_storage_get_ble_bonding_key(bd_addr, key_type, reinterpret_cast(&key), key_len) == BT_STATUS_SUCCESS) { if (add_key) { if (!*device_added) { @@ -547,32 +518,34 @@ static void btif_read_le_key(const uint8_t key_type, const size_t key_len, * Returns Number of UUIDs parsed from the supplied string * ******************************************************************************/ -size_t btif_split_uuids_string(const char* str, bluetooth::Uuid* p_uuid, - size_t max_uuids) { +size_t btif_split_uuids_string(const char* str, bluetooth::Uuid* p_uuid, size_t max_uuids) { log::assert_that(str != nullptr, "assert failed: str != nullptr"); log::assert_that(p_uuid != nullptr, "assert failed: p_uuid != nullptr"); size_t num_uuids = 0; while (str && num_uuids < max_uuids) { bool is_valid; - bluetooth::Uuid tmp = - Uuid::FromString(std::string(str, Uuid::kString128BitLen), &is_valid); - if (!is_valid) break; + bluetooth::Uuid tmp = Uuid::FromString(std::string(str, Uuid::kString128BitLen), &is_valid); + if (!is_valid) { + break; + } *p_uuid = tmp; p_uuid++; num_uuids++; str = strchr(str, ' '); - if (str) str++; + if (str) { + str++; + } } return num_uuids; } /** Helper function for fetching a bt_property of the adapter. */ -bt_status_t btif_storage_get_adapter_prop(bt_property_type_t type, void* buf, - int size, bt_property_t* property) { +bt_status_t btif_storage_get_adapter_prop(bt_property_type_t type, void* buf, int size, + bt_property_t* property) { property->type = type; property->val = buf; property->len = size; @@ -603,8 +576,7 @@ bt_status_t btif_storage_get_adapter_property(bt_property_t* property) { return BT_STATUS_NOT_READY; } else { log::info("Controller ready!"); - *bd_addr = bluetooth::ToRawAddress( - bluetooth::shim::GetController()->GetMacAddress()); + *bd_addr = bluetooth::ToRawAddress(bluetooth::shim::GetController()->GetMacAddress()); } property->len = RawAddress::kLength; return BT_STATUS_SUCCESS; @@ -613,9 +585,8 @@ bt_status_t btif_storage_get_adapter_property(bt_property_t* property) { btif_in_fetch_bonded_devices(&bonded_devices, 0); - log::verbose( - "BT_PROPERTY_ADAPTER_BONDED_DEVICES: Number of bonded devices={}", - bonded_devices.num_devices); + log::verbose("BT_PROPERTY_ADAPTER_BONDED_DEVICES: Number of bonded devices={}", + bonded_devices.num_devices); property->len = bonded_devices.num_devices * RawAddress::kLength; memcpy(property->val, bonded_devices.devices, property->len); @@ -636,21 +607,18 @@ bt_status_t btif_storage_get_adapter_property(bt_property_t* property) { if (service_mask & (tBTA_SERVICE_MASK)(1 << i)) { switch (i) { case BTA_HFP_SERVICE_ID: { - *(p_uuid + num_uuids) = - Uuid::From16Bit(UUID_SERVCLASS_AG_HANDSFREE); + *(p_uuid + num_uuids) = Uuid::From16Bit(UUID_SERVCLASS_AG_HANDSFREE); num_uuids++; } FALLTHROUGH_INTENDED; /* FALLTHROUGH */ /* intentional fall through: Send both BFP & HSP UUIDs if HFP is * enabled */ case BTA_HSP_SERVICE_ID: { - *(p_uuid + num_uuids) = - Uuid::From16Bit(UUID_SERVCLASS_HEADSET_AUDIO_GATEWAY); + *(p_uuid + num_uuids) = Uuid::From16Bit(UUID_SERVCLASS_HEADSET_AUDIO_GATEWAY); num_uuids++; } break; case BTA_A2DP_SOURCE_SERVICE_ID: { - *(p_uuid + num_uuids) = - Uuid::From16Bit(UUID_SERVCLASS_AUDIO_SOURCE); + *(p_uuid + num_uuids) = Uuid::From16Bit(UUID_SERVCLASS_AUDIO_SOURCE); num_uuids++; } break; case BTA_A2DP_SINK_SERVICE_ID: { @@ -662,18 +630,15 @@ bt_status_t btif_storage_get_adapter_property(bt_property_t* property) { num_uuids++; } break; case BTA_HFP_HS_SERVICE_ID: { - *(p_uuid + num_uuids) = - Uuid::From16Bit(UUID_SERVCLASS_HF_HANDSFREE); + *(p_uuid + num_uuids) = Uuid::From16Bit(UUID_SERVCLASS_HF_HANDSFREE); num_uuids++; } break; case BTA_MAP_SERVICE_ID: { - *(p_uuid + num_uuids) = - Uuid::From16Bit(UUID_SERVCLASS_MESSAGE_ACCESS); + *(p_uuid + num_uuids) = Uuid::From16Bit(UUID_SERVCLASS_MESSAGE_ACCESS); num_uuids++; } break; case BTA_MN_SERVICE_ID: { - *(p_uuid + num_uuids) = - Uuid::From16Bit(UUID_SERVCLASS_MESSAGE_NOTIFICATION); + *(p_uuid + num_uuids) = Uuid::From16Bit(UUID_SERVCLASS_MESSAGE_NOTIFICATION); num_uuids++; } break; case BTA_PCE_SERVICE_ID: { @@ -710,9 +675,8 @@ bt_status_t btif_storage_set_adapter_property(bt_property_t* property) { } /** Helper function for fetching a bt_property of a remote device. */ -bt_status_t btif_storage_get_remote_prop(RawAddress* remote_addr, - bt_property_type_t type, void* buf, - int size, bt_property_t* property) { +bt_status_t btif_storage_get_remote_prop(RawAddress* remote_addr, bt_property_type_t type, + void* buf, int size, bt_property_t* property) { property->type = type; property->val = buf; property->len = size; @@ -732,10 +696,9 @@ bt_status_t btif_storage_get_remote_prop(RawAddress* remote_addr, * BT_STATUS_FAIL otherwise * ******************************************************************************/ -bt_status_t btif_storage_get_remote_device_property( - const RawAddress* remote_bd_addr, bt_property_t* property) { - return cfg2prop(remote_bd_addr, property) ? BT_STATUS_SUCCESS - : BT_STATUS_FAIL; +bt_status_t btif_storage_get_remote_device_property(const RawAddress* remote_bd_addr, + bt_property_t* property) { + return cfg2prop(remote_bd_addr, property) ? BT_STATUS_SUCCESS : BT_STATUS_FAIL; } /******************************************************************************* * @@ -748,10 +711,9 @@ bt_status_t btif_storage_get_remote_device_property( * BT_STATUS_FAIL otherwise * ******************************************************************************/ -bt_status_t btif_storage_set_remote_device_property( - const RawAddress* remote_bd_addr, bt_property_t* property) { - return prop2cfg(remote_bd_addr, property) ? BT_STATUS_SUCCESS - : BT_STATUS_FAIL; +bt_status_t btif_storage_set_remote_device_property(const RawAddress* remote_bd_addr, + bt_property_t* property) { + return prop2cfg(remote_bd_addr, property) ? BT_STATUS_SUCCESS : BT_STATUS_FAIL; } /******************************************************************************* @@ -767,8 +729,7 @@ bt_status_t btif_storage_set_remote_device_property( * ******************************************************************************/ bt_status_t btif_storage_add_remote_device(const RawAddress* remote_bd_addr, - uint32_t num_properties, - bt_property_t* properties) { + uint32_t num_properties, bt_property_t* properties) { uint32_t i = 0; /* TODO: If writing a property, fails do we go back undo the earlier * written properties? */ @@ -807,16 +768,12 @@ bt_status_t btif_storage_add_remote_device(const RawAddress* remote_bd_addr, * ******************************************************************************/ -bt_status_t btif_storage_add_bonded_device(RawAddress* remote_bd_addr, - LinkKey link_key, uint8_t key_type, - uint8_t pin_length) { +bt_status_t btif_storage_add_bonded_device(RawAddress* remote_bd_addr, LinkKey link_key, + uint8_t key_type, uint8_t pin_length) { std::string bdstr = remote_bd_addr->ToString(); - bool ret = btif_config_set_int(bdstr, BTIF_STORAGE_KEY_LINK_KEY_TYPE, - static_cast(key_type)); - ret &= btif_config_set_int(bdstr, BTIF_STORAGE_KEY_PIN_LENGTH, - static_cast(pin_length)); - ret &= btif_config_set_bin(bdstr, BTIF_STORAGE_KEY_LINK_KEY, link_key.data(), - link_key.size()); + bool ret = btif_config_set_int(bdstr, BTIF_STORAGE_KEY_LINK_KEY_TYPE, static_cast(key_type)); + ret &= btif_config_set_int(bdstr, BTIF_STORAGE_KEY_PIN_LENGTH, static_cast(pin_length)); + ret &= btif_config_set_bin(bdstr, BTIF_STORAGE_KEY_LINK_KEY, link_key.data(), link_key.size()); if (ret) { btif_storage_set_mode(remote_bd_addr); @@ -834,8 +791,7 @@ bt_status_t btif_storage_add_bonded_device(RawAddress* remote_bd_addr, * BT_STATUS_FAIL otherwise * ******************************************************************************/ -bt_status_t btif_storage_remove_bonded_device( - const RawAddress* remote_bd_addr) { +bt_status_t btif_storage_remove_bonded_device(const RawAddress* remote_bd_addr) { std::string bdstr = remote_bd_addr->ToString(); log::info("Removing bonded device addr={}", *remote_bd_addr); @@ -843,8 +799,7 @@ bt_status_t btif_storage_remove_bonded_device( /* Check the length of the paired devices, and if 0 then reset IRK */ auto paired_devices = btif_config_get_paired_devices(); - if (paired_devices.empty() && - bluetooth::common::init_flags::irk_rotation_is_enabled()) { + if (paired_devices.empty() && bluetooth::common::init_flags::irk_rotation_is_enabled()) { log::info("Last paired device removed, resetting IRK"); BTA_DmBleResetId(); } @@ -866,9 +821,8 @@ static void remove_devices_with_sample_ltk() { tBTA_LE_KEY_VALUE key; memset(&key, 0, sizeof(key)); - if (btif_storage_get_ble_bonding_key( - bd_addr, BTM_LE_KEY_PENC, reinterpret_cast(&key), - sizeof(tBTM_LE_PENC_KEYS)) == BT_STATUS_SUCCESS) { + if (btif_storage_get_ble_bonding_key(bd_addr, BTM_LE_KEY_PENC, reinterpret_cast(&key), + sizeof(tBTM_LE_PENC_KEYS)) == BT_STATUS_SUCCESS) { if (is_sample_ltk(key.penc_key.ltk)) { bad_ltk.push_back(bd_addr); } @@ -906,20 +860,17 @@ void btif_storage_load_le_devices(void) { for (uint16_t i = 0; i < bonded_devices.num_devices; i++) { // RawAddress* p_remote_addr; tBTA_LE_KEY_VALUE key = {}; - if (btif_storage_get_ble_bonding_key( - bonded_devices.devices[i], BTM_LE_KEY_PID, - reinterpret_cast(&key), - sizeof(tBTM_LE_PID_KEYS)) == BT_STATUS_SUCCESS) { + if (btif_storage_get_ble_bonding_key(bonded_devices.devices[i], BTM_LE_KEY_PID, + reinterpret_cast(&key), + sizeof(tBTM_LE_PID_KEYS)) == BT_STATUS_SUCCESS) { if (bonded_devices.devices[i] != key.pid_key.identity_addr) { - log::info("Found device with a known identity address {} {}", - bonded_devices.devices[i], key.pid_key.identity_addr); + log::info("Found device with a known identity address {} {}", bonded_devices.devices[i], + key.pid_key.identity_addr); - if (bonded_devices.devices[i].IsEmpty() || - key.pid_key.identity_addr.IsEmpty()) { + if (bonded_devices.devices[i].IsEmpty() || key.pid_key.identity_addr.IsEmpty()) { log::warn("Address is empty! Skip"); } else { - consolidated_devices.emplace_back(bonded_devices.devices[i], - key.pid_key.identity_addr); + consolidated_devices.emplace_back(bonded_devices.devices[i], key.pid_key.identity_addr); } } } @@ -929,27 +880,23 @@ void btif_storage_load_le_devices(void) { /* Send the adapter_properties_cb with bonded consolidated device */ { /* BONDED_DEVICES */ - auto devices_list = - std::make_unique(consolidated_devices.size()); + auto devices_list = std::make_unique(consolidated_devices.size()); adapter_prop.type = BT_PROPERTY_ADAPTER_BONDED_DEVICES; adapter_prop.len = consolidated_devices.size() * sizeof(RawAddress); adapter_prop.val = devices_list.get(); for (uint16_t i = 0; i < consolidated_devices.size(); i++) { devices_list[i] = consolidated_devices[i].first; } - btif_adapter_properties_evt(BT_STATUS_SUCCESS, /* num_props */ 1, - &adapter_prop); + btif_adapter_properties_evt(BT_STATUS_SUCCESS, /* num_props */ 1, &adapter_prop); } for (const auto& device : consolidated_devices) { if (bonded_addresses.find(device.second) != bonded_addresses.end()) { // Invokes address consolidation for DuMo devices - GetInterfaceToProfiles()->events->invoke_address_consolidate_cb( - device.first, device.second); + GetInterfaceToProfiles()->events->invoke_address_consolidate_cb(device.first, device.second); } else { // Associates RPA & identity address for LE-only devices - GetInterfaceToProfiles()->events->invoke_le_address_associate_cb( - device.first, device.second); + GetInterfaceToProfiles()->events->invoke_le_address_associate_cb(device.first, device.second); } } } @@ -990,8 +937,8 @@ bt_status_t btif_storage_load_bonded_devices(void) { memset(adapter_props, 0, sizeof(adapter_props)); /* address */ - status = btif_storage_get_adapter_prop( - BT_PROPERTY_BDADDR, &addr, sizeof(addr), &adapter_props[num_props]); + status = btif_storage_get_adapter_prop(BT_PROPERTY_BDADDR, &addr, sizeof(addr), + &adapter_props[num_props]); // Add BT_PROPERTY_BDADDR property into list only when successful. // Otherwise, skip this property entry. if (status == BT_STATUS_SUCCESS) { @@ -1004,17 +951,15 @@ bt_status_t btif_storage_load_bonded_devices(void) { num_props++; /* DISC_TIMEOUT */ - btif_storage_get_adapter_prop(BT_PROPERTY_ADAPTER_DISCOVERABLE_TIMEOUT, - &disc_timeout, sizeof(disc_timeout), - &adapter_props[num_props]); + btif_storage_get_adapter_prop(BT_PROPERTY_ADAPTER_DISCOVERABLE_TIMEOUT, &disc_timeout, + sizeof(disc_timeout), &adapter_props[num_props]); num_props++; /* BONDED_DEVICES */ RawAddress* devices_list = reinterpret_cast( - osi_malloc(sizeof(RawAddress) * bonded_devices.num_devices)); + osi_malloc(sizeof(RawAddress) * bonded_devices.num_devices)); adapter_props[num_props].type = BT_PROPERTY_ADAPTER_BONDED_DEVICES; - adapter_props[num_props].len = - bonded_devices.num_devices * sizeof(RawAddress); + adapter_props[num_props].len = bonded_devices.num_devices * sizeof(RawAddress); adapter_props[num_props].val = devices_list; for (i = 0; i < bonded_devices.num_devices; i++) { devices_list[i] = bonded_devices.devices[i]; @@ -1022,8 +967,7 @@ bt_status_t btif_storage_load_bonded_devices(void) { num_props++; /* LOCAL UUIDs */ - btif_storage_get_adapter_prop(BT_PROPERTY_UUIDS, local_uuids, - sizeof(local_uuids), + btif_storage_get_adapter_prop(BT_PROPERTY_UUIDS, local_uuids, sizeof(local_uuids), &adapter_props[num_props]); num_props++; @@ -1047,66 +991,57 @@ bt_status_t btif_storage_load_bonded_devices(void) { num_props = 0; p_remote_addr = &bonded_devices.devices[i]; memset(remote_properties, 0, sizeof(remote_properties)); - btif_storage_get_remote_prop(p_remote_addr, BT_PROPERTY_BDNAME, &name, - sizeof(name), &remote_properties[num_props]); + btif_storage_get_remote_prop(p_remote_addr, BT_PROPERTY_BDNAME, &name, sizeof(name), + &remote_properties[num_props]); num_props++; - btif_storage_get_remote_prop( - p_remote_addr, BT_PROPERTY_REMOTE_FRIENDLY_NAME, &alias, - sizeof(alias), &remote_properties[num_props]); + btif_storage_get_remote_prop(p_remote_addr, BT_PROPERTY_REMOTE_FRIENDLY_NAME, &alias, + sizeof(alias), &remote_properties[num_props]); num_props++; - btif_storage_get_remote_prop(p_remote_addr, BT_PROPERTY_CLASS_OF_DEVICE, - &cod, sizeof(cod), + btif_storage_get_remote_prop(p_remote_addr, BT_PROPERTY_CLASS_OF_DEVICE, &cod, sizeof(cod), &remote_properties[num_props]); num_props++; - btif_storage_get_remote_prop(p_remote_addr, BT_PROPERTY_TYPE_OF_DEVICE, - &devtype, sizeof(devtype), - &remote_properties[num_props]); + btif_storage_get_remote_prop(p_remote_addr, BT_PROPERTY_TYPE_OF_DEVICE, &devtype, + sizeof(devtype), &remote_properties[num_props]); num_props++; - btif_storage_get_remote_prop(p_remote_addr, BT_PROPERTY_UUIDS, - remote_uuids, sizeof(remote_uuids), - &remote_properties[num_props]); + btif_storage_get_remote_prop(p_remote_addr, BT_PROPERTY_UUIDS, remote_uuids, + sizeof(remote_uuids), &remote_properties[num_props]); num_props++; // Floss needs appearance for metrics purposes uint16_t appearance = 0; - if (btif_storage_get_remote_prop(p_remote_addr, BT_PROPERTY_APPEARANCE, - &appearance, sizeof(appearance), - &remote_properties[num_props]) == - BT_STATUS_SUCCESS) { + if (btif_storage_get_remote_prop(p_remote_addr, BT_PROPERTY_APPEARANCE, &appearance, + sizeof(appearance), + &remote_properties[num_props]) == BT_STATUS_SUCCESS) { num_props++; } #if TARGET_FLOSS // Floss needs VID:PID for metrics purposes bt_vendor_product_info_t vp_info; - if (btif_storage_get_remote_prop( - p_remote_addr, BT_PROPERTY_VENDOR_PRODUCT_INFO, &vp_info, - sizeof(vp_info), - &remote_properties[num_props]) == BT_STATUS_SUCCESS) { + if (btif_storage_get_remote_prop(p_remote_addr, BT_PROPERTY_VENDOR_PRODUCT_INFO, &vp_info, + sizeof(vp_info), + &remote_properties[num_props]) == BT_STATUS_SUCCESS) { num_props++; } // Floss needs address type for diagnosis API uint8_t addr_type; - if (btif_storage_get_remote_prop( - p_remote_addr, BT_PROPERTY_REMOTE_ADDR_TYPE, &addr_type, - sizeof(addr_type), - &remote_properties[num_props]) == BT_STATUS_SUCCESS) { + if (btif_storage_get_remote_prop(p_remote_addr, BT_PROPERTY_REMOTE_ADDR_TYPE, &addr_type, + sizeof(addr_type), + &remote_properties[num_props]) == BT_STATUS_SUCCESS) { num_props++; } #endif - btif_storage_get_remote_prop(p_remote_addr, BT_PROPERTY_REMOTE_MODEL_NUM, - &model_name, sizeof(model_name), - &remote_properties[num_props]); + btif_storage_get_remote_prop(p_remote_addr, BT_PROPERTY_REMOTE_MODEL_NUM, &model_name, + sizeof(model_name), &remote_properties[num_props]); num_props++; - btif_remote_properties_evt(BT_STATUS_SUCCESS, p_remote_addr, num_props, - remote_properties); + btif_remote_properties_evt(BT_STATUS_SUCCESS, p_remote_addr, num_props, remote_properties); } } return BT_STATUS_SUCCESS; @@ -1124,15 +1059,12 @@ bt_status_t btif_storage_load_bonded_devices(void) { * ******************************************************************************/ -bt_status_t btif_storage_add_ble_bonding_key(RawAddress* remote_bd_addr, - const uint8_t* key_value, - uint8_t key_type, - uint8_t key_length) { +bt_status_t btif_storage_add_ble_bonding_key(RawAddress* remote_bd_addr, const uint8_t* key_value, + uint8_t key_type, uint8_t key_length) { for (size_t i = 0; i < std::size(BTIF_STORAGE_LE_KEYS); i++) { auto key = BTIF_STORAGE_LE_KEYS[i]; if (key.type == key_type) { - bool ret = btif_config_set_bin(remote_bd_addr->ToString(), key.name, - key_value, key_length); + bool ret = btif_config_set_bin(remote_bd_addr->ToString(), key.name, key_value, key_length); if (ret) { btif_storage_set_mode(remote_bd_addr); @@ -1155,16 +1087,13 @@ bt_status_t btif_storage_add_ble_bonding_key(RawAddress* remote_bd_addr, * BT_STATUS_FAIL otherwise * ******************************************************************************/ -bt_status_t btif_storage_get_ble_bonding_key(const RawAddress& remote_bd_addr, - uint8_t key_type, - uint8_t* key_value, - int key_length) { +bt_status_t btif_storage_get_ble_bonding_key(const RawAddress& remote_bd_addr, uint8_t key_type, + uint8_t* key_value, int key_length) { for (size_t i = 0; i < std::size(BTIF_STORAGE_LE_KEYS); i++) { auto key = BTIF_STORAGE_LE_KEYS[i]; if (key.type == key_type) { size_t length = key_length; - bool ret = btif_config_get_bin(remote_bd_addr.ToString(), key.name, - key_value, &length); + bool ret = btif_config_get_bin(remote_bd_addr.ToString(), key.name, key_value, &length); return ret ? BT_STATUS_SUCCESS : BT_STATUS_FAIL; } } @@ -1183,15 +1112,15 @@ bt_status_t btif_storage_get_ble_bonding_key(const RawAddress& remote_bd_addr, * BT_STATUS_FAIL otherwise * ******************************************************************************/ -bt_status_t btif_storage_remove_ble_bonding_keys( - const RawAddress* remote_bd_addr) { +bt_status_t btif_storage_remove_ble_bonding_keys(const RawAddress* remote_bd_addr) { std::string bdstr = remote_bd_addr->ToString(); log::info("Removing bonding keys for bd addr:{}", *remote_bd_addr); bool ret = true; for (size_t i = 0; i < std::size(BTIF_STORAGE_LE_KEYS); i++) { auto key_name = BTIF_STORAGE_LE_KEYS[i].name; - if (btif_config_exist(bdstr, key_name)) + if (btif_config_exist(bdstr, key_name)) { ret &= btif_config_remove(bdstr, key_name); + } } return ret ? BT_STATUS_SUCCESS : BT_STATUS_FAIL; @@ -1207,13 +1136,12 @@ bt_status_t btif_storage_remove_ble_bonding_keys( * BT_STATUS_FAIL otherwise * ******************************************************************************/ -bt_status_t btif_storage_add_ble_local_key(const Octet16& key_value, - uint8_t key_type) { +bt_status_t btif_storage_add_ble_local_key(const Octet16& key_value, uint8_t key_type) { for (size_t i = 0; i < std::size(BTIF_STORAGE_LOCAL_LE_KEYS); i++) { auto key = BTIF_STORAGE_LOCAL_LE_KEYS[i]; if (key.type == key_type) { - bool ret = btif_config_set_bin(BTIF_STORAGE_SECTION_ADAPTER, key.name, - key_value.data(), key_value.size()); + bool ret = btif_config_set_bin(BTIF_STORAGE_SECTION_ADAPTER, key.name, key_value.data(), + key_value.size()); return ret ? BT_STATUS_SUCCESS : BT_STATUS_FAIL; } @@ -1226,14 +1154,13 @@ bt_status_t btif_storage_add_ble_local_key(const Octet16& key_value, * Returns BT_STATUS_SUCCESS if the fetch was successful, BT_STATUS_FAIL * otherwise */ -bt_status_t btif_storage_get_ble_local_key(uint8_t key_type, - Octet16* key_value) { +bt_status_t btif_storage_get_ble_local_key(uint8_t key_type, Octet16* key_value) { for (size_t i = 0; i < std::size(BTIF_STORAGE_LOCAL_LE_KEYS); i++) { auto key = BTIF_STORAGE_LOCAL_LE_KEYS[i]; if (key.type == key_type) { size_t length = key_value->size(); - bool ret = btif_config_get_bin(BTIF_STORAGE_SECTION_ADAPTER, key.name, - key_value->data(), &length); + bool ret = btif_config_get_bin(BTIF_STORAGE_SECTION_ADAPTER, key.name, key_value->data(), + &length); return ret ? BT_STATUS_SUCCESS : BT_STATUS_FAIL; } @@ -1242,9 +1169,8 @@ bt_status_t btif_storage_get_ble_local_key(uint8_t key_type, return BT_STATUS_FAIL; } -bt_status_t btif_in_fetch_bonded_ble_device( - const std::string& remote_bd_addr, int add, - btif_bonded_devices_t* p_bonded_devices) { +bt_status_t btif_in_fetch_bonded_ble_device(const std::string& remote_bd_addr, int add, + btif_bonded_devices_t* p_bonded_devices) { int device_type; tBLE_ADDR_TYPE addr_type; bool device_added = false; @@ -1253,24 +1179,22 @@ bt_status_t btif_in_fetch_bonded_ble_device( RawAddress::FromString(remote_bd_addr, bd_addr); - if (!btif_config_get_int(remote_bd_addr, BTIF_STORAGE_KEY_DEV_TYPE, - &device_type)) + if (!btif_config_get_int(remote_bd_addr, BTIF_STORAGE_KEY_DEV_TYPE, &device_type)) { return BT_STATUS_FAIL; + } if ((device_type & BT_DEVICE_TYPE_BLE) == BT_DEVICE_TYPE_BLE || btif_has_ble_keys(remote_bd_addr)) { log::verbose("Found a LE device: {}", bd_addr); - if (btif_storage_get_remote_addr_type(&bd_addr, &addr_type) != - BT_STATUS_SUCCESS) { + if (btif_storage_get_remote_addr_type(&bd_addr, &addr_type) != BT_STATUS_SUCCESS) { addr_type = BLE_ADDR_PUBLIC; btif_storage_set_remote_addr_type(&bd_addr, BLE_ADDR_PUBLIC); } for (size_t i = 0; i < std::size(BTIF_STORAGE_LE_KEYS); i++) { auto key = BTIF_STORAGE_LE_KEYS[i]; - btif_read_le_key(key.type, key.size, bd_addr, addr_type, add, - &device_added, &key_found); + btif_read_le_key(key.type, key.size, bd_addr, addr_type, add, &device_added, &key_found); } // Fill in the bonded devices @@ -1283,7 +1207,9 @@ bt_status_t btif_in_fetch_bonded_ble_device( btif_gatts_add_bonded_dev_from_nv(bd_addr); } - if (key_found) return BT_STATUS_SUCCESS; + if (key_found) { + return BT_STATUS_SUCCESS; + } } return BT_STATUS_DEVICE_NOT_FOUND; } @@ -1292,17 +1218,15 @@ void btif_storage_invoke_addr_type_update(const RawAddress& remote_bd_addr, const tBLE_ADDR_TYPE& addr_type) { bt_property_t prop; prop.type = BT_PROPERTY_REMOTE_ADDR_TYPE; - prop.val = const_cast( - reinterpret_cast(&addr_type)); + prop.val = const_cast(reinterpret_cast(&addr_type)); prop.len = sizeof(tBLE_ADDR_TYPE); - GetInterfaceToProfiles()->events->invoke_remote_device_properties_cb( - BT_STATUS_SUCCESS, remote_bd_addr, 1, &prop); + GetInterfaceToProfiles()->events->invoke_remote_device_properties_cb(BT_STATUS_SUCCESS, + remote_bd_addr, 1, &prop); } bt_status_t btif_storage_set_remote_addr_type(const RawAddress* remote_bd_addr, tBLE_ADDR_TYPE addr_type) { - bool ret = btif_config_set_int(remote_bd_addr->ToString(), - BTIF_STORAGE_KEY_ADDR_TYPE, + bool ret = btif_config_set_int(remote_bd_addr->ToString(), BTIF_STORAGE_KEY_ADDR_TYPE, static_cast(addr_type)); #if TARGET_FLOSS @@ -1330,8 +1254,7 @@ bool btif_has_ble_keys(const std::string& bdstr) { bt_status_t btif_storage_get_remote_addr_type(const RawAddress* remote_bd_addr, tBLE_ADDR_TYPE* addr_type) { int val; - bool ret = btif_config_get_int(remote_bd_addr->ToString(), - BTIF_STORAGE_KEY_ADDR_TYPE, &val); + bool ret = btif_config_get_int(remote_bd_addr->ToString(), BTIF_STORAGE_KEY_ADDR_TYPE, &val); *addr_type = static_cast(val); return ret ? BT_STATUS_SUCCESS : BT_STATUS_FAIL; } @@ -1339,16 +1262,15 @@ bt_status_t btif_storage_get_remote_addr_type(const RawAddress* remote_bd_addr, /** Stores information about GATT server supported features */ void btif_storage_set_gatt_sr_supp_feat(const RawAddress& addr, uint8_t feat) { do_in_jni_thread(Bind( - [](const RawAddress& addr, uint8_t feat) { - std::string bdstr = addr.ToString(); - log::verbose( - "GATT server supported features for: {} features: " - "{}", - addr, feat); - btif_config_set_int(bdstr, BTIF_STORAGE_KEY_GATT_SERVER_SUPPORTED, - feat); - }, - addr, feat)); + [](const RawAddress& addr, uint8_t feat) { + std::string bdstr = addr.ToString(); + log::verbose( + "GATT server supported features for: {} features: " + "{}", + addr, feat); + btif_config_set_int(bdstr, BTIF_STORAGE_KEY_GATT_SERVER_SUPPORTED, feat); + }, + addr, feat)); } /** Gets information about GATT server supported features */ @@ -1357,8 +1279,7 @@ uint8_t btif_storage_get_sr_supp_feat(const RawAddress& bd_addr) { int value = 0; btif_config_get_int(name, BTIF_STORAGE_KEY_GATT_SERVER_SUPPORTED, &value); - log::verbose("Remote device: {} GATT server supported features 0x{:02x}", - bd_addr, value); + log::verbose("Remote device: {} GATT server supported features 0x{:02x}", bd_addr, value); return value; } @@ -1376,33 +1297,28 @@ uint8_t btif_storage_get_sr_supp_feat(const RawAddress& bd_addr) { ******************************************************************************/ bool btif_storage_is_restricted_device(const RawAddress* remote_bd_addr) { int val; - return btif_config_get_int(remote_bd_addr->ToString(), - BTIF_STORAGE_KEY_RESTRICTED, &val); + return btif_config_get_int(remote_bd_addr->ToString(), BTIF_STORAGE_KEY_RESTRICTED, &val); } // Get the name of a device from btif for interop database matching. -bool btif_storage_get_stored_remote_name(const RawAddress& bd_addr, - char* name) { +bool btif_storage_get_stored_remote_name(const RawAddress& bd_addr, char* name) { bt_property_t property; property.type = BT_PROPERTY_BDNAME; property.len = BD_NAME_LEN; property.val = name; - return (btif_storage_get_remote_device_property(&bd_addr, &property) == - BT_STATUS_SUCCESS); + return btif_storage_get_remote_device_property(&bd_addr, &property) == BT_STATUS_SUCCESS; } /** Stores information about GATT Client supported features support */ -void btif_storage_set_gatt_cl_supp_feat(const RawAddress& bd_addr, - uint8_t feat) { +void btif_storage_set_gatt_cl_supp_feat(const RawAddress& bd_addr, uint8_t feat) { do_in_jni_thread(Bind( - [](const RawAddress& bd_addr, uint8_t feat) { - std::string bdstr = bd_addr.ToString(); - log::verbose("saving gatt client supported feat: {}", bd_addr); - btif_config_set_int(bdstr, BTIF_STORAGE_KEY_GATT_CLIENT_SUPPORTED, - feat); - }, - bd_addr, feat)); + [](const RawAddress& bd_addr, uint8_t feat) { + std::string bdstr = bd_addr.ToString(); + log::verbose("saving gatt client supported feat: {}", bd_addr); + btif_config_set_int(bdstr, BTIF_STORAGE_KEY_GATT_CLIENT_SUPPORTED, feat); + }, + bd_addr, feat)); } /** Get client supported features */ @@ -1411,8 +1327,7 @@ uint8_t btif_storage_get_gatt_cl_supp_feat(const RawAddress& bd_addr) { int value = 0; btif_config_get_int(name, BTIF_STORAGE_KEY_GATT_CLIENT_SUPPORTED, &value); - log::verbose("Remote device: {} GATT client supported features 0x{:02x}", - bd_addr, value); + log::verbose("Remote device: {} GATT client supported features 0x{:02x}", bd_addr, value); return value; } @@ -1420,24 +1335,24 @@ uint8_t btif_storage_get_gatt_cl_supp_feat(const RawAddress& bd_addr) { /** Remove client supported features */ void btif_storage_remove_gatt_cl_supp_feat(const RawAddress& bd_addr) { do_in_jni_thread(Bind( - [](const RawAddress& bd_addr) { - auto bdstr = bd_addr.ToString(); - if (btif_config_exist(bdstr, BTIF_STORAGE_KEY_GATT_CLIENT_SUPPORTED)) { - btif_config_remove(bdstr, BTIF_STORAGE_KEY_GATT_CLIENT_SUPPORTED); - } - }, - bd_addr)); + [](const RawAddress& bd_addr) { + auto bdstr = bd_addr.ToString(); + if (btif_config_exist(bdstr, BTIF_STORAGE_KEY_GATT_CLIENT_SUPPORTED)) { + btif_config_remove(bdstr, BTIF_STORAGE_KEY_GATT_CLIENT_SUPPORTED); + } + }, + bd_addr)); } /** Store last server database hash for remote client */ void btif_storage_set_gatt_cl_db_hash(const RawAddress& bd_addr, Octet16 hash) { do_in_jni_thread(Bind( - [](const RawAddress& bd_addr, Octet16 hash) { - auto bdstr = bd_addr.ToString(); - btif_config_set_bin(bdstr, BTIF_STORAGE_KEY_GATT_CLIENT_DB_HASH, - hash.data(), hash.size()); - }, - bd_addr, hash)); + [](const RawAddress& bd_addr, Octet16 hash) { + auto bdstr = bd_addr.ToString(); + btif_config_set_bin(bdstr, BTIF_STORAGE_KEY_GATT_CLIENT_DB_HASH, hash.data(), + hash.size()); + }, + bd_addr, hash)); } /** Get last server database hash for remote client */ @@ -1446,8 +1361,7 @@ Octet16 btif_storage_get_gatt_cl_db_hash(const RawAddress& bd_addr) { Octet16 hash; size_t size = hash.size(); - btif_config_get_bin(bdstr, BTIF_STORAGE_KEY_GATT_CLIENT_DB_HASH, hash.data(), - &size); + btif_config_get_bin(bdstr, BTIF_STORAGE_KEY_GATT_CLIENT_DB_HASH, hash.data(), &size); return hash; } @@ -1455,13 +1369,13 @@ Octet16 btif_storage_get_gatt_cl_db_hash(const RawAddress& bd_addr) { /** Remove las server database hash for remote client */ void btif_storage_remove_gatt_cl_db_hash(const RawAddress& bd_addr) { do_in_jni_thread(Bind( - [](const RawAddress& bd_addr) { - auto bdstr = bd_addr.ToString(); - if (btif_config_exist(bdstr, BTIF_STORAGE_KEY_GATT_CLIENT_DB_HASH)) { - btif_config_remove(bdstr, BTIF_STORAGE_KEY_GATT_CLIENT_DB_HASH); - } - }, - bd_addr)); + [](const RawAddress& bd_addr) { + auto bdstr = bd_addr.ToString(); + if (btif_config_exist(bdstr, BTIF_STORAGE_KEY_GATT_CLIENT_DB_HASH)) { + btif_config_remove(bdstr, BTIF_STORAGE_KEY_GATT_CLIENT_DB_HASH); + } + }, + bd_addr)); } void btif_debug_linkkey_type_dump(int fd) { @@ -1472,8 +1386,7 @@ void btif_debug_linkkey_type_dump(int fd) { dprintf(fd, " %s\n", ADDRESS_TO_LOGGABLE_CSTR(bd_addr)); dprintf(fd, " BR: "); - if (btif_config_get_int(bdstr, BTIF_STORAGE_KEY_LINK_KEY_TYPE, - &linkkey_type)) { + if (btif_config_get_int(bdstr, BTIF_STORAGE_KEY_LINK_KEY_TYPE, &linkkey_type)) { dprintf(fd, "%s", linkkey_type_text(linkkey_type).c_str()); } dprintf(fd, "\n"); @@ -1481,8 +1394,9 @@ void btif_debug_linkkey_type_dump(int fd) { dprintf(fd, " LE:"); for (size_t i = 0; i < std::size(BTIF_STORAGE_LE_KEYS); i++) { const std::string& key_name = BTIF_STORAGE_LE_KEYS[i].name; - if (btif_config_exist(bdstr, key_name)) + if (btif_config_exist(bdstr, key_name)) { dprintf(fd, " %s", key_name.c_str()); + } } dprintf(fd, "\n"); diff --git a/system/btif/src/btif_uid.cc b/system/btif/src/btif_uid.cc index 1d8a3dcbb44..bd0cd479e9b 100644 --- a/system/btif/src/btif_uid.cc +++ b/system/btif/src/btif_uid.cc @@ -22,9 +22,10 @@ * socket usage per app UID. * ******************************************************************************/ +#include "btif_uid.h" + #include -#include "btif_uid.h" #include "osi/include/allocator.h" static std::mutex set_lock; @@ -56,8 +57,7 @@ void uid_set_destroy(uid_set_t* set) { } // Lock in uid_set_t must be held. -static uid_set_node_t* uid_set_find_or_create_node(uid_set_t* set, - int32_t app_uid) { +static uid_set_node_t* uid_set_find_or_create_node(uid_set_t* set, int32_t app_uid) { uid_set_node_t* node = set->head; while (node && node->data.app_uid != app_uid) { node = node->next; @@ -73,7 +73,9 @@ static uid_set_node_t* uid_set_find_or_create_node(uid_set_t* set, } void uid_set_add_tx(uid_set_t* set, int32_t app_uid, uint64_t bytes) { - if (app_uid == -1 || bytes == 0) return; + if (app_uid == -1 || bytes == 0) { + return; + } std::unique_lock guard(set_lock); uid_set_node_t* node = uid_set_find_or_create_node(set, app_uid); @@ -81,7 +83,9 @@ void uid_set_add_tx(uid_set_t* set, int32_t app_uid, uint64_t bytes) { } void uid_set_add_rx(uid_set_t* set, int32_t app_uid, uint64_t bytes) { - if (app_uid == -1 || bytes == 0) return; + if (app_uid == -1 || bytes == 0) { + return; + } std::unique_lock guard(set_lock); uid_set_node_t* node = uid_set_find_or_create_node(set, app_uid); @@ -101,8 +105,7 @@ bt_uid_traffic_t* uid_set_read_and_clear(uid_set_t* set) { // Allocate an array of elements + 1, to signify the end with app_uid set to // -1. - bt_uid_traffic_t* result = - (bt_uid_traffic_t*)osi_calloc(sizeof(bt_uid_traffic_t) * (len + 1)); + bt_uid_traffic_t* result = (bt_uid_traffic_t*)osi_calloc(sizeof(bt_uid_traffic_t) * (len + 1)); bt_uid_traffic_t* data = result; node = set->head; diff --git a/system/btif/src/btif_util.cc b/system/btif/src/btif_util.cc index 96b8e28a437..39dcb054710 100644 --- a/system/btif/src/btif_util.cc +++ b/system/btif/src/btif_util.cc @@ -87,24 +87,26 @@ int ascii_2_hex(const char* p_ascii, int len, uint8_t* p_hex) { uint8_t c; for (x = 0; (x < len) && (*p_ascii); x++) { - if (ISDIGIT(*p_ascii)) + if (ISDIGIT(*p_ascii)) { c = (*p_ascii - '0') << 4; - else + } else { c = (toupper(*p_ascii) - 'A' + 10) << 4; + } p_ascii++; if (*p_ascii) { - if (ISDIGIT(*p_ascii)) + if (ISDIGIT(*p_ascii)) { c |= (*p_ascii - '0'); - else + } else { c |= (toupper(*p_ascii) - 'A' + 10); + } p_ascii++; } *p_hex++ = c; } - return (x); + return x; } std::string dump_dm_search_event(uint16_t event) { diff --git a/system/btif/src/btif_vc.cc b/system/btif/src/btif_vc.cc index 5b1979b2286..8a1fd4e2c87 100644 --- a/system/btif/src/btif_vc.cc +++ b/system/btif/src/btif_vc.cc @@ -40,17 +40,15 @@ namespace { std::unique_ptr vc_instance; std::atomic_bool initialized = false; -class VolumeControlInterfaceImpl : public VolumeControlInterface, - public VolumeControlCallbacks { +class VolumeControlInterfaceImpl : public VolumeControlInterface, public VolumeControlCallbacks { ~VolumeControlInterfaceImpl() override = default; void Init(VolumeControlCallbacks* callbacks) override { this->callbacks_ = callbacks; do_in_main_thread( - FROM_HERE, - Bind(&VolumeControl::Initialize, this, - jni_thread_wrapper( - Bind(&btif_storage_load_bonded_volume_control_devices)))); + FROM_HERE, + Bind(&VolumeControl::Initialize, this, + jni_thread_wrapper(Bind(&btif_storage_load_bonded_volume_control_devices)))); /* It might be not yet initialized, but setting this flag here is safe, * because other calls will check this and the native instance @@ -58,233 +56,206 @@ class VolumeControlInterfaceImpl : public VolumeControlInterface, initialized = true; } - void OnConnectionState(ConnectionState state, - const RawAddress& address) override { - do_in_jni_thread(Bind(&VolumeControlCallbacks::OnConnectionState, - Unretained(callbacks_), state, address)); + void OnConnectionState(ConnectionState state, const RawAddress& address) override { + do_in_jni_thread(Bind(&VolumeControlCallbacks::OnConnectionState, Unretained(callbacks_), state, + address)); } - void OnVolumeStateChanged(const RawAddress& address, uint8_t volume, - bool mute, bool isAutonomous) override { - do_in_jni_thread(Bind(&VolumeControlCallbacks::OnVolumeStateChanged, - Unretained(callbacks_), address, volume, mute, - isAutonomous)); + void OnVolumeStateChanged(const RawAddress& address, uint8_t volume, bool mute, + bool isAutonomous) override { + do_in_jni_thread(Bind(&VolumeControlCallbacks::OnVolumeStateChanged, Unretained(callbacks_), + address, volume, mute, isAutonomous)); } void OnGroupVolumeStateChanged(int group_id, uint8_t volume, bool mute, bool isAutonomous) override { do_in_jni_thread(Bind(&VolumeControlCallbacks::OnGroupVolumeStateChanged, - Unretained(callbacks_), group_id, volume, mute, - isAutonomous)); + Unretained(callbacks_), group_id, volume, mute, isAutonomous)); } - void OnDeviceAvailable(const RawAddress& address, - uint8_t num_offset) override { - do_in_jni_thread(Bind(&VolumeControlCallbacks::OnDeviceAvailable, - Unretained(callbacks_), address, num_offset)); + void OnDeviceAvailable(const RawAddress& address, uint8_t num_offset) override { + do_in_jni_thread(Bind(&VolumeControlCallbacks::OnDeviceAvailable, Unretained(callbacks_), + address, num_offset)); } /* Callbacks for Volume Offset Control Service (VOCS) - Extended Audio Outputs */ - void OnExtAudioOutVolumeOffsetChanged(const RawAddress& address, - uint8_t ext_output_id, + void OnExtAudioOutVolumeOffsetChanged(const RawAddress& address, uint8_t ext_output_id, int16_t offset) override { - do_in_jni_thread( - Bind(&VolumeControlCallbacks::OnExtAudioOutVolumeOffsetChanged, - Unretained(callbacks_), address, ext_output_id, offset)); + do_in_jni_thread(Bind(&VolumeControlCallbacks::OnExtAudioOutVolumeOffsetChanged, + Unretained(callbacks_), address, ext_output_id, offset)); } - void OnExtAudioOutLocationChanged(const RawAddress& address, - uint8_t ext_output_id, + void OnExtAudioOutLocationChanged(const RawAddress& address, uint8_t ext_output_id, uint32_t location) override { do_in_jni_thread(Bind(&VolumeControlCallbacks::OnExtAudioOutLocationChanged, - Unretained(callbacks_), address, ext_output_id, - location)); + Unretained(callbacks_), address, ext_output_id, location)); } - void OnExtAudioOutDescriptionChanged(const RawAddress& address, - uint8_t ext_output_id, + void OnExtAudioOutDescriptionChanged(const RawAddress& address, uint8_t ext_output_id, std::string descr) override { - do_in_jni_thread( - Bind(&VolumeControlCallbacks::OnExtAudioOutDescriptionChanged, - Unretained(callbacks_), address, ext_output_id, descr)); + do_in_jni_thread(Bind(&VolumeControlCallbacks::OnExtAudioOutDescriptionChanged, + Unretained(callbacks_), address, ext_output_id, descr)); } void Connect(const RawAddress& address) override { if (!initialized || !VolumeControl::IsVolumeControlRunning()) { log::verbose( - "call ignored, due to already started cleanup procedure or service " - "being not read"); + "call ignored, due to already started cleanup procedure or service " + "being not read"); return; } do_in_main_thread(FROM_HERE, - Bind(&VolumeControl::Connect, - Unretained(VolumeControl::Get()), address)); + Bind(&VolumeControl::Connect, Unretained(VolumeControl::Get()), address)); } void Disconnect(const RawAddress& address) override { if (!initialized || !VolumeControl::IsVolumeControlRunning()) { log::verbose( - "call ignored, due to already started cleanup procedure or service " - "being not read"); + "call ignored, due to already started cleanup procedure or service " + "being not read"); return; } do_in_main_thread(FROM_HERE, - Bind(&VolumeControl::Disconnect, - Unretained(VolumeControl::Get()), address)); + Bind(&VolumeControl::Disconnect, Unretained(VolumeControl::Get()), address)); } - void SetVolume(std::variant addr_or_group_id, - uint8_t volume) override { + void SetVolume(std::variant addr_or_group_id, uint8_t volume) override { if (!initialized || !VolumeControl::IsVolumeControlRunning()) { log::verbose( - "call ignored, due to already started cleanup procedure or service " - "being not read"); + "call ignored, due to already started cleanup procedure or service " + "being not read"); return; } - do_in_main_thread(FROM_HERE, Bind(&VolumeControl::SetVolume, - Unretained(VolumeControl::Get()), + do_in_main_thread(FROM_HERE, Bind(&VolumeControl::SetVolume, Unretained(VolumeControl::Get()), std::move(addr_or_group_id), volume)); } void Mute(std::variant addr_or_group_id) override { if (!initialized || !VolumeControl::IsVolumeControlRunning()) { log::verbose( - "call ignored, due to already started cleanup procedure or service " - "being not read"); + "call ignored, due to already started cleanup procedure or service " + "being not read"); return; } - do_in_main_thread( - FROM_HERE, Bind(&VolumeControl::Mute, Unretained(VolumeControl::Get()), - std::move(addr_or_group_id))); + do_in_main_thread(FROM_HERE, Bind(&VolumeControl::Mute, Unretained(VolumeControl::Get()), + std::move(addr_or_group_id))); } void Unmute(std::variant addr_or_group_id) override { if (!initialized || !VolumeControl::IsVolumeControlRunning()) { log::verbose( - "call ignored, due to already started cleanup procedure or service " - "being not read"); + "call ignored, due to already started cleanup procedure or service " + "being not read"); return; } - do_in_main_thread(FROM_HERE, Bind(&VolumeControl::UnMute, - Unretained(VolumeControl::Get()), + do_in_main_thread(FROM_HERE, Bind(&VolumeControl::UnMute, Unretained(VolumeControl::Get()), std::move(addr_or_group_id))); } void RemoveDevice(const RawAddress& address) override { if (!initialized || !VolumeControl::IsVolumeControlRunning()) { log::verbose( - "call ignored, due to already started cleanup procedure or service " - "being not read"); + "call ignored, due to already started cleanup procedure or service " + "being not read"); return; } /* RemoveDevice can be called on devices that don't have HA enabled */ if (VolumeControl::IsVolumeControlRunning()) { do_in_main_thread(FROM_HERE, - Bind(&VolumeControl::Remove, - Unretained(VolumeControl::Get()), address)); + Bind(&VolumeControl::Remove, Unretained(VolumeControl::Get()), address)); } } - void GetExtAudioOutVolumeOffset(const RawAddress& address, - uint8_t ext_output_id) override { + void GetExtAudioOutVolumeOffset(const RawAddress& address, uint8_t ext_output_id) override { if (!initialized || !VolumeControl::IsVolumeControlRunning()) { log::verbose( - "call ignored, due to already started cleanup procedure or service " - "being not read"); + "call ignored, due to already started cleanup procedure or service " + "being not read"); return; } - do_in_main_thread( - FROM_HERE, - Bind(&VolumeControl::GetExtAudioOutVolumeOffset, - Unretained(VolumeControl::Get()), address, ext_output_id)); + do_in_main_thread(FROM_HERE, Bind(&VolumeControl::GetExtAudioOutVolumeOffset, + Unretained(VolumeControl::Get()), address, ext_output_id)); } - void SetExtAudioOutVolumeOffset(const RawAddress& address, - uint8_t ext_output_id, + void SetExtAudioOutVolumeOffset(const RawAddress& address, uint8_t ext_output_id, int16_t offset_val) override { if (!initialized || !VolumeControl::IsVolumeControlRunning()) { log::verbose( - "call ignored, due to already started cleanup procedure or service " - "being not read"); + "call ignored, due to already started cleanup procedure or service " + "being not read"); return; } do_in_main_thread(FROM_HERE, Bind(&VolumeControl::SetExtAudioOutVolumeOffset, - Unretained(VolumeControl::Get()), address, - ext_output_id, offset_val)); + Unretained(VolumeControl::Get()), address, ext_output_id, offset_val)); } - void GetExtAudioOutLocation(const RawAddress& address, - uint8_t ext_output_id) override { + void GetExtAudioOutLocation(const RawAddress& address, uint8_t ext_output_id) override { if (!initialized || !VolumeControl::IsVolumeControlRunning()) { log::verbose( - "call ignored, due to already started cleanup procedure or service " - "being not read"); + "call ignored, due to already started cleanup procedure or service " + "being not read"); return; } do_in_main_thread(FROM_HERE, Bind(&VolumeControl::GetExtAudioOutLocation, - Unretained(VolumeControl::Get()), address, - ext_output_id)); + Unretained(VolumeControl::Get()), address, ext_output_id)); } void SetExtAudioOutLocation(const RawAddress& address, uint8_t ext_output_id, uint32_t location) override { if (!initialized || !VolumeControl::IsVolumeControlRunning()) { log::verbose( - "call ignored, due to already started cleanup procedure or service " - "being not read"); + "call ignored, due to already started cleanup procedure or service " + "being not read"); return; } - do_in_main_thread(FROM_HERE, Bind(&VolumeControl::SetExtAudioOutLocation, - Unretained(VolumeControl::Get()), address, - ext_output_id, location)); + do_in_main_thread(FROM_HERE, + Bind(&VolumeControl::SetExtAudioOutLocation, Unretained(VolumeControl::Get()), + address, ext_output_id, location)); } - void GetExtAudioOutDescription(const RawAddress& address, - uint8_t ext_output_id) override { + void GetExtAudioOutDescription(const RawAddress& address, uint8_t ext_output_id) override { if (!initialized || !VolumeControl::IsVolumeControlRunning()) { log::verbose( - "call ignored, due to already started cleanup procedure or service " - "being not read"); + "call ignored, due to already started cleanup procedure or service " + "being not read"); return; } do_in_main_thread(FROM_HERE, Bind(&VolumeControl::GetExtAudioOutDescription, - Unretained(VolumeControl::Get()), address, - ext_output_id)); + Unretained(VolumeControl::Get()), address, ext_output_id)); } - void SetExtAudioOutDescription(const RawAddress& address, - uint8_t ext_output_id, + void SetExtAudioOutDescription(const RawAddress& address, uint8_t ext_output_id, std::string descr) override { if (!initialized || !VolumeControl::IsVolumeControlRunning()) { log::verbose( - "call ignored, due to already started cleanup procedure or service " - "being not read"); + "call ignored, due to already started cleanup procedure or service " + "being not read"); return; } - do_in_main_thread(FROM_HERE, Bind(&VolumeControl::SetExtAudioOutDescription, - Unretained(VolumeControl::Get()), address, - ext_output_id, descr)); + do_in_main_thread(FROM_HERE, + Bind(&VolumeControl::SetExtAudioOutDescription, + Unretained(VolumeControl::Get()), address, ext_output_id, descr)); } void Cleanup(void) override { if (!initialized || !VolumeControl::IsVolumeControlRunning()) { log::verbose( - "call ignored, due to already started cleanup procedure or service " - "being not read"); + "call ignored, due to already started cleanup procedure or service " + "being not read"); return; } @@ -292,14 +263,16 @@ class VolumeControlInterfaceImpl : public VolumeControlInterface, do_in_main_thread(FROM_HERE, Bind(&VolumeControl::CleanUp)); } - private: +private: VolumeControlCallbacks* callbacks_; }; } /* namespace */ VolumeControlInterface* btif_volume_control_get_interface(void) { - if (!vc_instance) vc_instance.reset(new VolumeControlInterfaceImpl()); + if (!vc_instance) { + vc_instance.reset(new VolumeControlInterfaceImpl()); + } return vc_instance.get(); } diff --git a/system/btif/src/stack_manager.cc b/system/btif/src/stack_manager.cc index 63641e0ee73..3956a3632fa 100644 --- a/system/btif/src/stack_manager.cc +++ b/system/btif/src/stack_manager.cc @@ -74,37 +74,33 @@ // Once BTA_PAN_INCLUDED is no longer exposed via bt_target.h // this check and error statement may be removed. -static_assert( - BTA_PAN_INCLUDED, - "#define BTA_PAN_INCLUDED preprocessor compilation flag is unsupported" - " Pan profile is always included in the bluetooth stack" - "*** Conditional Compilation Directive error"); +static_assert(BTA_PAN_INCLUDED, + "#define BTA_PAN_INCLUDED preprocessor compilation flag is unsupported" + " Pan profile is always included in the bluetooth stack" + "*** Conditional Compilation Directive error"); // Once PAN_SUPPORTS_ROLE_NAP is no longer exposed via bt_target.h // this check and error statement may be removed. -static_assert( - PAN_SUPPORTS_ROLE_NAP, - "#define PAN_SUPPORTS_ROLE_NAP preprocessor compilation flag is unsupported" - " Pan profile always supports network access point in the bluetooth stack" - "*** Conditional Compilation Directive error"); +static_assert(PAN_SUPPORTS_ROLE_NAP, + "#define PAN_SUPPORTS_ROLE_NAP preprocessor compilation flag is unsupported" + " Pan profile always supports network access point in the bluetooth stack" + "*** Conditional Compilation Directive error"); // Once PAN_SUPPORTS_ROLE_PANU is no longer exposed via bt_target.h // this check and error statement may be removed. -static_assert( - PAN_SUPPORTS_ROLE_PANU, - "#define PAN_SUPPORTS_ROLE_PANU preprocessor compilation flag is " - "unsupported" - " Pan profile always supports user as a client in the bluetooth stack" - "*** Conditional Compilation Directive error"); +static_assert(PAN_SUPPORTS_ROLE_PANU, + "#define PAN_SUPPORTS_ROLE_PANU preprocessor compilation flag is " + "unsupported" + " Pan profile always supports user as a client in the bluetooth stack" + "*** Conditional Compilation Directive error"); // Once BTA_HH_INCLUDED is no longer exposed via bt_target.h // this check and error statement may be removed. -static_assert( - BTA_HH_INCLUDED, - "#define BTA_HH_INCLUDED preprocessor compilation flag is " - "unsupported" - " Host interface device profile is always enabled in the bluetooth stack" - "*** Conditional Compilation Directive error"); +static_assert(BTA_HH_INCLUDED, + "#define BTA_HH_INCLUDED preprocessor compilation flag is " + "unsupported" + " Host interface device profile is always enabled in the bluetooth stack" + "*** Conditional Compilation Directive error"); void BTA_dm_on_hw_on(); void BTA_dm_on_hw_off(); @@ -120,14 +116,12 @@ static bool stack_is_initialized; // If running, the stack is fully up and able to bluetooth. static bool stack_is_running; -static void event_init_stack(std::promise promise, - bluetooth::core::CoreInterface* interface); +static void event_init_stack(std::promise promise, bluetooth::core::CoreInterface* interface); static void event_start_up_stack(bluetooth::core::CoreInterface* interface, ProfileStartCallback startProfiles, ProfileStopCallback stopProfiles); static void event_shut_down_stack(ProfileStopCallback stopProfiles); -static void event_clean_up_stack(std::promise promise, - ProfileStopCallback stopProfiles); +static void event_clean_up_stack(std::promise promise, ProfileStopCallback stopProfiles); static void event_start_up_rust_module(); static void event_shut_down_rust_module(); @@ -136,9 +130,7 @@ static void event_signal_stack_down(void* context); static bluetooth::core::CoreInterface* interfaceToProfiles; -bluetooth::core::CoreInterface* GetInterfaceToProfiles() { - return interfaceToProfiles; -} +bluetooth::core::CoreInterface* GetInterfaceToProfiles() { return interfaceToProfiles; } // Unvetted includes/imports, etc which should be removed or vetted in the // future @@ -154,9 +146,8 @@ static void init_stack(bluetooth::core::CoreInterface* interface) { // and do not overlap. std::promise promise; auto future = promise.get_future(); - management_thread.DoInThread( - FROM_HERE, base::BindOnce(event_init_stack, std::move(promise), - base::Unretained(interface))); + management_thread.DoInThread(FROM_HERE, base::BindOnce(event_init_stack, std::move(promise), + base::Unretained(interface))); future.wait(); } @@ -164,13 +155,11 @@ static void start_up_stack_async(bluetooth::core::CoreInterface* interface, ProfileStartCallback startProfiles, ProfileStopCallback stopProfiles) { management_thread.DoInThread( - FROM_HERE, base::BindOnce(event_start_up_stack, interface, startProfiles, - stopProfiles)); + FROM_HERE, base::BindOnce(event_start_up_stack, interface, startProfiles, stopProfiles)); } static void shut_down_stack_async(ProfileStopCallback stopProfiles) { - management_thread.DoInThread( - FROM_HERE, base::BindOnce(event_shut_down_stack, stopProfiles)); + management_thread.DoInThread(FROM_HERE, base::BindOnce(event_shut_down_stack, stopProfiles)); } static void clean_up_stack(ProfileStopCallback stopProfiles) { @@ -179,11 +168,9 @@ static void clean_up_stack(ProfileStopCallback stopProfiles) { std::promise promise; auto future = promise.get_future(); management_thread.DoInThread( - FROM_HERE, - base::BindOnce(event_clean_up_stack, std::move(promise), stopProfiles)); + FROM_HERE, base::BindOnce(event_clean_up_stack, std::move(promise), stopProfiles)); - auto status = - future.wait_for(std::chrono::milliseconds(BT_STACK_CLEANUP_WAIT_MS)); + auto status = future.wait_for(std::chrono::milliseconds(BT_STACK_CLEANUP_WAIT_MS)); if (status == std::future_status::ready) { management_thread.ShutDown(); } else { @@ -192,11 +179,11 @@ static void clean_up_stack(ProfileStopCallback stopProfiles) { } static void start_up_rust_module_async() { - management_thread.DoInThread(FROM_HERE, base::BindOnce(event_start_up_rust_module)); + management_thread.DoInThread(FROM_HERE, base::BindOnce(event_start_up_rust_module)); } static void shut_down_rust_module_async() { - management_thread.DoInThread(FROM_HERE, base::BindOnce(event_shut_down_rust_module)); + management_thread.DoInThread(FROM_HERE, base::BindOnce(event_shut_down_rust_module)); } static bool get_stack_is_running() { return stack_is_running; } @@ -217,14 +204,14 @@ struct module_lookup { }; const struct module_lookup module_table[] = { - {BTIF_CONFIG_MODULE, &btif_config_module}, - {GD_SHIM_MODULE, &gd_shim_module}, - {INTEROP_MODULE, &interop_module}, - {OSI_MODULE, &osi_module}, - {RUST_MODULE, &rust_module}, - {STACK_CONFIG_MODULE, &stack_config_module}, - {DEVICE_IOT_CONFIG_MODULE, &device_iot_config_module}, - {NULL, NULL}, + {BTIF_CONFIG_MODULE, &btif_config_module}, + {GD_SHIM_MODULE, &gd_shim_module}, + {INTEROP_MODULE, &interop_module}, + {OSI_MODULE, &osi_module}, + {RUST_MODULE, &rust_module}, + {STACK_CONFIG_MODULE, &stack_config_module}, + {DEVICE_IOT_CONFIG_MODULE, &device_iot_config_module}, + {NULL, NULL}, }; inline const module_t* get_local_module(const char* name) { @@ -277,8 +264,7 @@ static void event_init_stack(std::promise promise, promise.set_value(); } -static void ensure_stack_is_initialized( - bluetooth::core::CoreInterface* interface) { +static void ensure_stack_is_initialized(bluetooth::core::CoreInterface* interface) { if (!stack_is_initialized) { log::warn("found the stack was uninitialized. Initializing now."); // No future needed since we are calling it directly @@ -398,9 +384,9 @@ static void event_shut_down_stack(ProfileStopCallback stopProfiles) { } static void event_start_up_rust_module() { - log::info("is bringing up the Rust module"); - module_start_up(get_local_module(RUST_MODULE)); - log::info("finished"); + log::info("is bringing up the Rust module"); + module_start_up(get_local_module(RUST_MODULE)); + log::info("finished"); } static void event_shut_down_rust_module() { @@ -417,8 +403,7 @@ static void ensure_stack_is_not_running(ProfileStopCallback stopProfiles) { } // Synchronous function to clean up the stack -static void event_clean_up_stack(std::promise promise, - ProfileStopCallback stopProfiles) { +static void event_clean_up_stack(std::promise promise, ProfileStopCallback stopProfiles) { if (!stack_is_initialized) { log::info("found the stack already in a clean state"); goto cleanup; @@ -454,18 +439,18 @@ static void event_signal_stack_up(void* /* context */) { // Notify BTIF connect queue that we've brought up the stack. It's // now time to dispatch all the pending profile connect requests. btif_queue_connect_next(); - GetInterfaceToProfiles()->events->invoke_adapter_state_changed_cb( - BT_STATE_ON); + GetInterfaceToProfiles()->events->invoke_adapter_state_changed_cb(BT_STATE_ON); } static void event_signal_stack_down(void* /* context */) { - GetInterfaceToProfiles()->events->invoke_adapter_state_changed_cb( - BT_STATE_OFF); + GetInterfaceToProfiles()->events->invoke_adapter_state_changed_cb(BT_STATE_OFF); future_ready(stack_manager_get_hack_future(), FUTURE_SUCCESS); } static void ensure_manager_initialized() { - if (management_thread.IsRunning()) return; + if (management_thread.IsRunning()) { + return; + } management_thread.StartUp(); if (!management_thread.IsRunning()) { @@ -474,10 +459,10 @@ static void ensure_manager_initialized() { } } -static const stack_manager_t interface = {init_stack, start_up_stack_async, - shut_down_stack_async, clean_up_stack, - start_up_rust_module_async, shut_down_rust_module_async, - get_stack_is_running}; +static const stack_manager_t interface = { + init_stack, start_up_stack_async, shut_down_stack_async, + clean_up_stack, start_up_rust_module_async, shut_down_rust_module_async, + get_stack_is_running}; const stack_manager_t* stack_manager_get_interface() { ensure_manager_initialized(); @@ -490,8 +475,7 @@ namespace bluetooth { namespace legacy { namespace testing { -void set_interface_to_profiles( - bluetooth::core::CoreInterface* interfaceToProfiles) { +void set_interface_to_profiles(bluetooth::core::CoreInterface* interfaceToProfiles) { ::interfaceToProfiles = interfaceToProfiles; } diff --git a/system/btif/test/btif_avrcp_audio_track_test.cc b/system/btif/test/btif_avrcp_audio_track_test.cc index 8f219d4bfe4..f34172b0683 100644 --- a/system/btif/test/btif_avrcp_audio_track_test.cc +++ b/system/btif/test/btif_avrcp_audio_track_test.cc @@ -47,8 +47,7 @@ class BtifAvrcpAudioTrackTest : public ::testing::Test {}; TEST_F(BtifAvrcpAudioTrackTest, setAudioTrackGain_maxGainSet) { void* track_handle = BtifAvrcpAudioTrackCreate(10, 16, 3); BtifAvrcpSetAudioTrackGain(track_handle, 1.0f); - BtifAvrcpAudioTrack* trackHolder = - static_cast(track_handle); + BtifAvrcpAudioTrack* trackHolder = static_cast(track_handle); EXPECT_EQ(trackHolder->gain, 1.0f); BtifAvrcpAudioTrackDelete(track_handle); } @@ -56,42 +55,35 @@ TEST_F(BtifAvrcpAudioTrackTest, setAudioTrackGain_maxGainSet) { TEST_F(BtifAvrcpAudioTrackTest, setAudioTrackGain_minimumGainSet) { void* track_handle = BtifAvrcpAudioTrackCreate(10, 16, 3); BtifAvrcpSetAudioTrackGain(track_handle, 0.0f); - BtifAvrcpAudioTrack* trackHolder = - static_cast(track_handle); + BtifAvrcpAudioTrack* trackHolder = static_cast(track_handle); EXPECT_EQ(trackHolder->gain, 0.0f); BtifAvrcpAudioTrackDelete(track_handle); } -TEST_F(BtifAvrcpAudioTrackTest, - setAudioTrackGain_maxGainOutOfBounds_setsCappedGain) { +TEST_F(BtifAvrcpAudioTrackTest, setAudioTrackGain_maxGainOutOfBounds_setsCappedGain) { void* track_handle = BtifAvrcpAudioTrackCreate(10, 16, 3); - BtifAvrcpAudioTrack* trackHolder = - static_cast(track_handle); + BtifAvrcpAudioTrack* trackHolder = static_cast(track_handle); BtifAvrcpSetAudioTrackGain(track_handle, 2.0f); EXPECT_EQ(trackHolder->gain, 1.0f); BtifAvrcpAudioTrackDelete(track_handle); } -TEST_F(BtifAvrcpAudioTrackTest, - setAudioTrackGain_minGainOutOfBounds_setsCappedGain) { +TEST_F(BtifAvrcpAudioTrackTest, setAudioTrackGain_minGainOutOfBounds_setsCappedGain) { void* track_handle = BtifAvrcpAudioTrackCreate(10, 16, 3); - BtifAvrcpAudioTrack* trackHolder = - static_cast(track_handle); + BtifAvrcpAudioTrack* trackHolder = static_cast(track_handle); BtifAvrcpSetAudioTrackGain(track_handle, -2.0f); EXPECT_EQ(trackHolder->gain, 0.0f); BtifAvrcpAudioTrackDelete(track_handle); } -TEST_F(BtifAvrcpAudioTrackTest, - setMaxAudioTrackGain_minGain_bufferStreamDucked) { +TEST_F(BtifAvrcpAudioTrackTest, setMaxAudioTrackGain_minGain_bufferStreamDucked) { constexpr float scaleQ15ToFloat = 1.0f / 32768.0f; constexpr size_t bufferLength = 100; constexpr int bitsPerSample = 16; constexpr size_t sampleSize = bitsPerSample / 8; constexpr auto gainValue = 0.5f; void* track_handle = BtifAvrcpAudioTrackCreate(10, bitsPerSample, 3); - BtifAvrcpAudioTrack* trackHolder = - static_cast(track_handle); + BtifAvrcpAudioTrack* trackHolder = static_cast(track_handle); std::unique_ptr stream(new AAudioStream); // Set the values to track holder as mock audio lib APIs are a no-op. trackHolder->stream = stream.get(); diff --git a/system/btif/test/btif_core_test.cc b/system/btif/test/btif_core_test.cc index c9734c82e9b..759d3085005 100644 --- a/system/btif/test/btif_core_test.cc +++ b/system/btif/test/btif_core_test.cc @@ -62,8 +62,7 @@ void set_hal_cbacks(bt_callbacks_t* callbacks); namespace bluetooth::legacy::testing { void bta_dm_acl_down(const RawAddress& bd_addr, tBT_TRANSPORT transport); -void bta_dm_acl_up(const RawAddress& bd_addr, tBT_TRANSPORT transport, - uint16_t acl_handle); +void bta_dm_acl_up(const RawAddress& bd_addr, tBT_TRANSPORT transport, uint16_t acl_handle); } // namespace bluetooth::legacy::testing const tBTA_AG_RES_DATA tBTA_AG_RES_DATA::kEmpty = {}; @@ -115,10 +114,8 @@ module_t rust_module; namespace { -PacketView BuilderToView( - std::unique_ptr builder) { - std::shared_ptr> packet_bytes = - std::make_shared>(); +PacketView BuilderToView(std::unique_ptr builder) { + std::shared_ptr> packet_bytes = std::make_shared>(); BitInserter it(*packet_bytes); builder->Serialize(it); return PacketView(packet_bytes); @@ -135,53 +132,39 @@ std::map> callback_map_; callback_map_[__func__](); void adapter_state_changed_callback(bt_state_t /* state */) {} -void adapter_properties_callback(bt_status_t /* status */, - int /* num_properties */, +void adapter_properties_callback(bt_status_t /* status */, int /* num_properties */, bt_property_t* /* properties */) {} -void remote_device_properties_callback(bt_status_t /* status */, - RawAddress* /* bd_addr */, - int /* num_properties */, - bt_property_t* /* properties */) {} -void device_found_callback(int /* num_properties */, - bt_property_t* /* properties */) {} +void remote_device_properties_callback(bt_status_t /* status */, RawAddress* /* bd_addr */, + int /* num_properties */, bt_property_t* /* properties */) {} +void device_found_callback(int /* num_properties */, bt_property_t* /* properties */) {} void discovery_state_changed_callback(bt_discovery_state_t /* state */) {} -void pin_request_callback(RawAddress* /* remote_bd_addr */, - bt_bdname_t* /* bd_name */, uint32_t /* cod */, - bool /* min_16_digit */) {} -void ssp_request_callback(RawAddress* /* remote_bd_addr */, - bt_ssp_variant_t /* pairing_variant */, +void pin_request_callback(RawAddress* /* remote_bd_addr */, bt_bdname_t* /* bd_name */, + uint32_t /* cod */, bool /* min_16_digit */) {} +void ssp_request_callback(RawAddress* /* remote_bd_addr */, bt_ssp_variant_t /* pairing_variant */, uint32_t /* pass_key */) {} -void bond_state_changed_callback(bt_status_t /* status */, - RawAddress* /* remote_bd_addr */, - bt_bond_state_t /* state */, - int /* fail_reason */) {} +void bond_state_changed_callback(bt_status_t /* status */, RawAddress* /* remote_bd_addr */, + bt_bond_state_t /* state */, int /* fail_reason */) {} void address_consolidate_callback(RawAddress* /* main_bd_addr */, RawAddress* /* secondary_bd_addr */) {} void le_address_associate_callback(RawAddress* /* main_bd_addr */, RawAddress* /* secondary_bd_addr */) {} -void acl_state_changed_callback(bt_status_t /* status */, - RawAddress* /* remote_bd_addr */, - bt_acl_state_t /* state */, - int /* transport_link_type */, +void acl_state_changed_callback(bt_status_t /* status */, RawAddress* /* remote_bd_addr */, + bt_acl_state_t /* state */, int /* transport_link_type */, bt_hci_error_code_t /* hci_reason */, - bt_conn_direction_t /* direction */, - uint16_t /* acl_handle */) {} -void link_quality_report_callback(uint64_t /* timestamp */, int /* report_id */, - int /* rssi */, int /* snr */, - int /* retransmission_count */, + bt_conn_direction_t /* direction */, uint16_t /* acl_handle */) {} +void link_quality_report_callback(uint64_t /* timestamp */, int /* report_id */, int /* rssi */, + int /* snr */, int /* retransmission_count */, int /* packets_not_receive_count */, int /* negative_acknowledgement_count */) { TESTCB; } void callback_thread_event(bt_cb_thread_evt /* evt */) { TESTCB; } -void dut_mode_recv_callback(uint16_t /* opcode */, uint8_t* /* buf */, - uint8_t /* len */) {} -void le_test_mode_callback(bt_status_t /* status */, - uint16_t /* num_packets */) {} +void dut_mode_recv_callback(uint16_t /* opcode */, uint8_t* /* buf */, uint8_t /* len */) {} +void le_test_mode_callback(bt_status_t /* status */, uint16_t /* num_packets */) {} void energy_info_callback(bt_activity_energy_info* /* energy_info */, bt_uid_traffic_t* /* uid_data */) {} -void generate_local_oob_data_callback(tBT_TRANSPORT /* transport */, - bt_oob_data_t /* oob_data */) {} +void generate_local_oob_data_callback(tBT_TRANSPORT /* transport */, bt_oob_data_t /* oob_data */) { +} void switch_buffer_size_callback(bool /* is_low_latency_buffer_size */) {} void switch_codec_callback(bool /* is_low_latency_buffer_size */) {} void le_rand_callback(uint64_t /* random */) {} @@ -189,28 +172,28 @@ void key_missing_callback(const RawAddress /* bd_addr */) {} #undef TESTCB bt_callbacks_t callbacks = { - .size = sizeof(bt_callbacks_t), - .adapter_state_changed_cb = adapter_state_changed_callback, - .adapter_properties_cb = adapter_properties_callback, - .remote_device_properties_cb = remote_device_properties_callback, - .device_found_cb = device_found_callback, - .discovery_state_changed_cb = discovery_state_changed_callback, - .pin_request_cb = pin_request_callback, - .ssp_request_cb = ssp_request_callback, - .bond_state_changed_cb = bond_state_changed_callback, - .address_consolidate_cb = address_consolidate_callback, - .le_address_associate_cb = le_address_associate_callback, - .acl_state_changed_cb = acl_state_changed_callback, - .thread_evt_cb = callback_thread_event, - .dut_mode_recv_cb = dut_mode_recv_callback, - .le_test_mode_cb = le_test_mode_callback, - .energy_info_cb = energy_info_callback, - .link_quality_report_cb = link_quality_report_callback, - .generate_local_oob_data_cb = generate_local_oob_data_callback, - .switch_buffer_size_cb = switch_buffer_size_callback, - .switch_codec_cb = switch_codec_callback, - .le_rand_cb = le_rand_callback, - .key_missing_cb = key_missing_callback, + .size = sizeof(bt_callbacks_t), + .adapter_state_changed_cb = adapter_state_changed_callback, + .adapter_properties_cb = adapter_properties_callback, + .remote_device_properties_cb = remote_device_properties_callback, + .device_found_cb = device_found_callback, + .discovery_state_changed_cb = discovery_state_changed_callback, + .pin_request_cb = pin_request_callback, + .ssp_request_cb = ssp_request_callback, + .bond_state_changed_cb = bond_state_changed_callback, + .address_consolidate_cb = address_consolidate_callback, + .le_address_associate_cb = le_address_associate_callback, + .acl_state_changed_cb = acl_state_changed_callback, + .thread_evt_cb = callback_thread_event, + .dut_mode_recv_cb = dut_mode_recv_callback, + .le_test_mode_cb = le_test_mode_callback, + .energy_info_cb = energy_info_callback, + .link_quality_report_cb = link_quality_report_callback, + .generate_local_oob_data_cb = generate_local_oob_data_callback, + .switch_buffer_size_cb = switch_buffer_size_callback, + .switch_codec_cb = switch_codec_callback, + .le_rand_cb = le_rand_callback, + .key_missing_cb = key_missing_callback, }; } // namespace @@ -218,16 +201,14 @@ bt_callbacks_t callbacks = { class BtifUtilsTest : public ::testing::Test {}; class BtifCoreTest : public ::testing::Test { - protected: +protected: void SetUp() override { callback_map_.clear(); bluetooth::hci::testing::mock_controller_ = &controller_; bluetooth::testing::set_hal_cbacks(&callbacks); auto promise = std::promise(); auto future = promise.get_future(); - callback_map_["callback_thread_event"] = [&promise]() { - promise.set_value(); - }; + callback_map_["callback_thread_event"] = [&promise]() { promise.set_value(); }; InitializeCoreInterface(); ASSERT_EQ(std::future_status::ready, future.wait_for(timeout_time)); callback_map_.erase("callback_thread_event"); @@ -236,9 +217,7 @@ class BtifCoreTest : public ::testing::Test { void TearDown() override { auto promise = std::promise(); auto future = promise.get_future(); - callback_map_["callback_thread_event"] = [&promise]() { - promise.set_value(); - }; + callback_map_["callback_thread_event"] = [&promise]() { promise.set_value(); }; CleanCoreInterface(); ASSERT_EQ(std::future_status::ready, future.wait_for(timeout_time)); bluetooth::hci::testing::mock_controller_ = nullptr; @@ -248,7 +227,7 @@ class BtifCoreTest : public ::testing::Test { }; class BtifCoreWithControllerTest : public BtifCoreTest { - protected: +protected: void SetUp() override { BtifCoreTest::SetUp(); ON_CALL(controller_, SupportsSniffSubrating).WillByDefault(Return(true)); @@ -258,11 +237,10 @@ class BtifCoreWithControllerTest : public BtifCoreTest { }; class BtifCoreWithConnectionTest : public BtifCoreWithControllerTest { - protected: +protected: void SetUp() override { BtifCoreWithControllerTest::SetUp(); - bluetooth::legacy::testing::bta_dm_acl_up(kRawAddress, BT_TRANSPORT_AUTO, - kHciHandle); + bluetooth::legacy::testing::bta_dm_acl_up(kRawAddress, BT_TRANSPORT_AUTO, kHciHandle); } void TearDown() override { @@ -313,31 +291,30 @@ TEST_F(BtifCoreTest, test_post_on_bt_jni_simple3) { extern const char* dump_av_sm_event_name(int event); TEST_F(BtifUtilsTest, dump_av_sm_event_name) { std::vector> events = { - std::make_pair(BTA_AV_ENABLE_EVT, "BTA_AV_ENABLE_EVT"), - std::make_pair(BTA_AV_REGISTER_EVT, "BTA_AV_REGISTER_EVT"), - std::make_pair(BTA_AV_OPEN_EVT, "BTA_AV_OPEN_EVT"), - std::make_pair(BTA_AV_CLOSE_EVT, "BTA_AV_CLOSE_EVT"), - std::make_pair(BTA_AV_START_EVT, "BTA_AV_START_EVT"), - std::make_pair(BTA_AV_STOP_EVT, "BTA_AV_STOP_EVT"), - std::make_pair(BTA_AV_PROTECT_REQ_EVT, "BTA_AV_PROTECT_REQ_EVT"), - std::make_pair(BTA_AV_PROTECT_RSP_EVT, "BTA_AV_PROTECT_RSP_EVT"), - std::make_pair(BTA_AV_RC_OPEN_EVT, "BTA_AV_RC_OPEN_EVT"), - std::make_pair(BTA_AV_RC_CLOSE_EVT, "BTA_AV_RC_CLOSE_EVT"), - std::make_pair(BTA_AV_RC_BROWSE_OPEN_EVT, "BTA_AV_RC_BROWSE_OPEN_EVT"), - std::make_pair(BTA_AV_RC_BROWSE_CLOSE_EVT, "BTA_AV_RC_BROWSE_CLOSE_EVT"), - std::make_pair(BTA_AV_REMOTE_CMD_EVT, "BTA_AV_REMOTE_CMD_EVT"), - std::make_pair(BTA_AV_REMOTE_RSP_EVT, "BTA_AV_REMOTE_RSP_EVT"), - std::make_pair(BTA_AV_VENDOR_CMD_EVT, "BTA_AV_VENDOR_CMD_EVT"), - std::make_pair(BTA_AV_VENDOR_RSP_EVT, "BTA_AV_VENDOR_RSP_EVT"), - std::make_pair(BTA_AV_RECONFIG_EVT, "BTA_AV_RECONFIG_EVT"), - std::make_pair(BTA_AV_SUSPEND_EVT, "BTA_AV_SUSPEND_EVT"), - std::make_pair(BTA_AV_PENDING_EVT, "BTA_AV_PENDING_EVT"), - std::make_pair(BTA_AV_META_MSG_EVT, "BTA_AV_META_MSG_EVT"), - std::make_pair(BTA_AV_REJECT_EVT, "BTA_AV_REJECT_EVT"), - std::make_pair(BTA_AV_RC_FEAT_EVT, "BTA_AV_RC_FEAT_EVT"), - std::make_pair(BTA_AV_RC_PSM_EVT, "BTA_AV_RC_PSM_EVT"), - std::make_pair(BTA_AV_OFFLOAD_START_RSP_EVT, - "BTA_AV_OFFLOAD_START_RSP_EVT"), + std::make_pair(BTA_AV_ENABLE_EVT, "BTA_AV_ENABLE_EVT"), + std::make_pair(BTA_AV_REGISTER_EVT, "BTA_AV_REGISTER_EVT"), + std::make_pair(BTA_AV_OPEN_EVT, "BTA_AV_OPEN_EVT"), + std::make_pair(BTA_AV_CLOSE_EVT, "BTA_AV_CLOSE_EVT"), + std::make_pair(BTA_AV_START_EVT, "BTA_AV_START_EVT"), + std::make_pair(BTA_AV_STOP_EVT, "BTA_AV_STOP_EVT"), + std::make_pair(BTA_AV_PROTECT_REQ_EVT, "BTA_AV_PROTECT_REQ_EVT"), + std::make_pair(BTA_AV_PROTECT_RSP_EVT, "BTA_AV_PROTECT_RSP_EVT"), + std::make_pair(BTA_AV_RC_OPEN_EVT, "BTA_AV_RC_OPEN_EVT"), + std::make_pair(BTA_AV_RC_CLOSE_EVT, "BTA_AV_RC_CLOSE_EVT"), + std::make_pair(BTA_AV_RC_BROWSE_OPEN_EVT, "BTA_AV_RC_BROWSE_OPEN_EVT"), + std::make_pair(BTA_AV_RC_BROWSE_CLOSE_EVT, "BTA_AV_RC_BROWSE_CLOSE_EVT"), + std::make_pair(BTA_AV_REMOTE_CMD_EVT, "BTA_AV_REMOTE_CMD_EVT"), + std::make_pair(BTA_AV_REMOTE_RSP_EVT, "BTA_AV_REMOTE_RSP_EVT"), + std::make_pair(BTA_AV_VENDOR_CMD_EVT, "BTA_AV_VENDOR_CMD_EVT"), + std::make_pair(BTA_AV_VENDOR_RSP_EVT, "BTA_AV_VENDOR_RSP_EVT"), + std::make_pair(BTA_AV_RECONFIG_EVT, "BTA_AV_RECONFIG_EVT"), + std::make_pair(BTA_AV_SUSPEND_EVT, "BTA_AV_SUSPEND_EVT"), + std::make_pair(BTA_AV_PENDING_EVT, "BTA_AV_PENDING_EVT"), + std::make_pair(BTA_AV_META_MSG_EVT, "BTA_AV_META_MSG_EVT"), + std::make_pair(BTA_AV_REJECT_EVT, "BTA_AV_REJECT_EVT"), + std::make_pair(BTA_AV_RC_FEAT_EVT, "BTA_AV_RC_FEAT_EVT"), + std::make_pair(BTA_AV_RC_PSM_EVT, "BTA_AV_RC_PSM_EVT"), + std::make_pair(BTA_AV_OFFLOAD_START_RSP_EVT, "BTA_AV_OFFLOAD_START_RSP_EVT"), }; for (const auto& event : events) { ASSERT_EQ(event.second, dump_av_sm_event_name(event.first)); @@ -349,484 +326,422 @@ TEST_F(BtifUtilsTest, dump_av_sm_event_name) { TEST_F(BtifUtilsTest, dump_dm_search_event) { std::vector> events = { - std::make_pair(BTA_DM_INQ_RES_EVT, "BTA_DM_INQ_RES_EVT"), - std::make_pair(BTA_DM_INQ_CMPL_EVT, "BTA_DM_INQ_CMPL_EVT"), - std::make_pair(BTA_DM_DISC_CMPL_EVT, "BTA_DM_DISC_CMPL_EVT"), - std::make_pair(BTA_DM_SEARCH_CANCEL_CMPL_EVT, - "BTA_DM_SEARCH_CANCEL_CMPL_EVT"), - std::make_pair(BTA_DM_NAME_READ_EVT, "BTA_DM_NAME_READ_EVT"), + std::make_pair(BTA_DM_INQ_RES_EVT, "BTA_DM_INQ_RES_EVT"), + std::make_pair(BTA_DM_INQ_CMPL_EVT, "BTA_DM_INQ_CMPL_EVT"), + std::make_pair(BTA_DM_DISC_CMPL_EVT, "BTA_DM_DISC_CMPL_EVT"), + std::make_pair(BTA_DM_SEARCH_CANCEL_CMPL_EVT, "BTA_DM_SEARCH_CANCEL_CMPL_EVT"), + std::make_pair(BTA_DM_NAME_READ_EVT, "BTA_DM_NAME_READ_EVT"), }; for (const auto& event : events) { ASSERT_TRUE(dump_dm_search_event(event.first).starts_with(event.second)); } - ASSERT_TRUE(dump_dm_search_event(std::numeric_limits::max()) - .starts_with("Unknown")); + ASSERT_TRUE(dump_dm_search_event(std::numeric_limits::max()).starts_with("Unknown")); } TEST_F(BtifUtilsTest, dump_property_type) { std::vector> types = { - std::make_pair(BT_PROPERTY_BDNAME, "BT_PROPERTY_BDNAME"), - std::make_pair(BT_PROPERTY_BDADDR, "BT_PROPERTY_BDADDR"), - std::make_pair(BT_PROPERTY_UUIDS, "BT_PROPERTY_UUIDS"), - std::make_pair(BT_PROPERTY_CLASS_OF_DEVICE, - "BT_PROPERTY_CLASS_OF_DEVICE"), - std::make_pair(BT_PROPERTY_TYPE_OF_DEVICE, "BT_PROPERTY_TYPE_OF_DEVICE"), - std::make_pair(BT_PROPERTY_REMOTE_RSSI, "BT_PROPERTY_REMOTE_RSSI"), - std::make_pair(BT_PROPERTY_ADAPTER_DISCOVERABLE_TIMEOUT, - "BT_PROPERTY_ADAPTER_DISCOVERABLE_TIMEOUT"), - std::make_pair(BT_PROPERTY_ADAPTER_BONDED_DEVICES, - "BT_PROPERTY_ADAPTER_BONDED_DEVICES"), - std::make_pair(BT_PROPERTY_REMOTE_FRIENDLY_NAME, - "BT_PROPERTY_REMOTE_FRIENDLY_NAME"), + std::make_pair(BT_PROPERTY_BDNAME, "BT_PROPERTY_BDNAME"), + std::make_pair(BT_PROPERTY_BDADDR, "BT_PROPERTY_BDADDR"), + std::make_pair(BT_PROPERTY_UUIDS, "BT_PROPERTY_UUIDS"), + std::make_pair(BT_PROPERTY_CLASS_OF_DEVICE, "BT_PROPERTY_CLASS_OF_DEVICE"), + std::make_pair(BT_PROPERTY_TYPE_OF_DEVICE, "BT_PROPERTY_TYPE_OF_DEVICE"), + std::make_pair(BT_PROPERTY_REMOTE_RSSI, "BT_PROPERTY_REMOTE_RSSI"), + std::make_pair(BT_PROPERTY_ADAPTER_DISCOVERABLE_TIMEOUT, + "BT_PROPERTY_ADAPTER_DISCOVERABLE_TIMEOUT"), + std::make_pair(BT_PROPERTY_ADAPTER_BONDED_DEVICES, "BT_PROPERTY_ADAPTER_BONDED_DEVICES"), + std::make_pair(BT_PROPERTY_REMOTE_FRIENDLY_NAME, "BT_PROPERTY_REMOTE_FRIENDLY_NAME"), }; for (const auto& type : types) { EXPECT_TRUE(dump_property_type(type.first).starts_with(type.second)); } - EXPECT_TRUE(dump_property_type(static_cast( - std::numeric_limits::max())) + EXPECT_TRUE( + dump_property_type(static_cast(std::numeric_limits::max())) .starts_with("Unknown")); } TEST_F(BtifUtilsTest, dump_dm_event) { std::vector> events = { - std::make_pair(BTA_DM_PIN_REQ_EVT, "BTA_DM_PIN_REQ_EVT"), - std::make_pair(BTA_DM_AUTH_CMPL_EVT, "BTA_DM_AUTH_CMPL_EVT"), - std::make_pair(BTA_DM_LINK_UP_EVT, "BTA_DM_LINK_UP_EVT"), - std::make_pair(BTA_DM_LINK_DOWN_EVT, "BTA_DM_LINK_DOWN_EVT"), - std::make_pair(BTA_DM_BOND_CANCEL_CMPL_EVT, - "BTA_DM_BOND_CANCEL_CMPL_EVT"), - std::make_pair(BTA_DM_SP_CFM_REQ_EVT, "BTA_DM_SP_CFM_REQ_EVT"), - std::make_pair(BTA_DM_SP_KEY_NOTIF_EVT, "BTA_DM_SP_KEY_NOTIF_EVT"), - std::make_pair(BTA_DM_BLE_KEY_EVT, "BTA_DM_BLE_KEY_EVT"), - std::make_pair(BTA_DM_BLE_SEC_REQ_EVT, "BTA_DM_BLE_SEC_REQ_EVT"), - std::make_pair(BTA_DM_BLE_PASSKEY_NOTIF_EVT, - "BTA_DM_BLE_PASSKEY_NOTIF_EVT"), - std::make_pair(BTA_DM_BLE_PASSKEY_REQ_EVT, "BTA_DM_BLE_PASSKEY_REQ_EVT"), - std::make_pair(BTA_DM_BLE_OOB_REQ_EVT, "BTA_DM_BLE_OOB_REQ_EVT"), - std::make_pair(BTA_DM_BLE_SC_OOB_REQ_EVT, "BTA_DM_BLE_SC_OOB_REQ_EVT"), - std::make_pair(BTA_DM_BLE_LOCAL_IR_EVT, "BTA_DM_BLE_LOCAL_IR_EVT"), - std::make_pair(BTA_DM_BLE_LOCAL_ER_EVT, "BTA_DM_BLE_LOCAL_ER_EVT"), - std::make_pair(BTA_DM_BLE_AUTH_CMPL_EVT, "BTA_DM_BLE_AUTH_CMPL_EVT"), - std::make_pair(BTA_DM_DEV_UNPAIRED_EVT, "BTA_DM_DEV_UNPAIRED_EVT"), - std::make_pair(BTA_DM_ENER_INFO_READ, "BTA_DM_ENER_INFO_READ"), + std::make_pair(BTA_DM_PIN_REQ_EVT, "BTA_DM_PIN_REQ_EVT"), + std::make_pair(BTA_DM_AUTH_CMPL_EVT, "BTA_DM_AUTH_CMPL_EVT"), + std::make_pair(BTA_DM_LINK_UP_EVT, "BTA_DM_LINK_UP_EVT"), + std::make_pair(BTA_DM_LINK_DOWN_EVT, "BTA_DM_LINK_DOWN_EVT"), + std::make_pair(BTA_DM_BOND_CANCEL_CMPL_EVT, "BTA_DM_BOND_CANCEL_CMPL_EVT"), + std::make_pair(BTA_DM_SP_CFM_REQ_EVT, "BTA_DM_SP_CFM_REQ_EVT"), + std::make_pair(BTA_DM_SP_KEY_NOTIF_EVT, "BTA_DM_SP_KEY_NOTIF_EVT"), + std::make_pair(BTA_DM_BLE_KEY_EVT, "BTA_DM_BLE_KEY_EVT"), + std::make_pair(BTA_DM_BLE_SEC_REQ_EVT, "BTA_DM_BLE_SEC_REQ_EVT"), + std::make_pair(BTA_DM_BLE_PASSKEY_NOTIF_EVT, "BTA_DM_BLE_PASSKEY_NOTIF_EVT"), + std::make_pair(BTA_DM_BLE_PASSKEY_REQ_EVT, "BTA_DM_BLE_PASSKEY_REQ_EVT"), + std::make_pair(BTA_DM_BLE_OOB_REQ_EVT, "BTA_DM_BLE_OOB_REQ_EVT"), + std::make_pair(BTA_DM_BLE_SC_OOB_REQ_EVT, "BTA_DM_BLE_SC_OOB_REQ_EVT"), + std::make_pair(BTA_DM_BLE_LOCAL_IR_EVT, "BTA_DM_BLE_LOCAL_IR_EVT"), + std::make_pair(BTA_DM_BLE_LOCAL_ER_EVT, "BTA_DM_BLE_LOCAL_ER_EVT"), + std::make_pair(BTA_DM_BLE_AUTH_CMPL_EVT, "BTA_DM_BLE_AUTH_CMPL_EVT"), + std::make_pair(BTA_DM_DEV_UNPAIRED_EVT, "BTA_DM_DEV_UNPAIRED_EVT"), + std::make_pair(BTA_DM_ENER_INFO_READ, "BTA_DM_ENER_INFO_READ"), }; for (const auto& event : events) { ASSERT_TRUE(dump_dm_event(event.first).starts_with(event.second)); } - ASSERT_TRUE(dump_dm_event(std::numeric_limits::max()) - .starts_with("Unknown")); + ASSERT_TRUE(dump_dm_event(std::numeric_limits::max()).starts_with("Unknown")); } TEST_F(BtifUtilsTest, dump_hf_event) { std::vector> events = { - std::make_pair(BTA_AG_ENABLE_EVT, "BTA_AG_ENABLE_EVT"), - std::make_pair(BTA_AG_REGISTER_EVT, "BTA_AG_REGISTER_EVT"), - std::make_pair(BTA_AG_OPEN_EVT, "BTA_AG_OPEN_EVT"), - std::make_pair(BTA_AG_CLOSE_EVT, "BTA_AG_CLOSE_EVT"), - std::make_pair(BTA_AG_CONN_EVT, "BTA_AG_CONN_EVT"), - std::make_pair(BTA_AG_AUDIO_OPEN_EVT, "BTA_AG_AUDIO_OPEN_EVT"), - std::make_pair(BTA_AG_AUDIO_CLOSE_EVT, "BTA_AG_AUDIO_CLOSE_EVT"), - std::make_pair(BTA_AG_SPK_EVT, "BTA_AG_SPK_EVT"), - std::make_pair(BTA_AG_MIC_EVT, "BTA_AG_MIC_EVT"), - std::make_pair(BTA_AG_AT_CKPD_EVT, "BTA_AG_AT_CKPD_EVT"), - std::make_pair(BTA_AG_DISABLE_EVT, "BTA_AG_DISABLE_EVT"), - std::make_pair(BTA_AG_CODEC_EVT, "BTA_AG_CODEC_EVT"), - std::make_pair(BTA_AG_AT_A_EVT, "BTA_AG_AT_A_EVT"), - std::make_pair(BTA_AG_AT_D_EVT, "BTA_AG_AT_D_EVT"), - std::make_pair(BTA_AG_AT_CHLD_EVT, "BTA_AG_AT_CHLD_EVT"), - std::make_pair(BTA_AG_AT_CHUP_EVT, "BTA_AG_AT_CHUP_EVT"), - std::make_pair(BTA_AG_AT_CIND_EVT, "BTA_AG_AT_CIND_EVT"), - std::make_pair(BTA_AG_AT_VTS_EVT, "BTA_AG_AT_VTS_EVT"), - std::make_pair(BTA_AG_AT_BINP_EVT, "BTA_AG_AT_BINP_EVT"), - std::make_pair(BTA_AG_AT_BLDN_EVT, "BTA_AG_AT_BLDN_EVT"), - std::make_pair(BTA_AG_AT_BVRA_EVT, "BTA_AG_AT_BVRA_EVT"), - std::make_pair(BTA_AG_AT_NREC_EVT, "BTA_AG_AT_NREC_EVT"), - std::make_pair(BTA_AG_AT_CNUM_EVT, "BTA_AG_AT_CNUM_EVT"), - std::make_pair(BTA_AG_AT_BTRH_EVT, "BTA_AG_AT_BTRH_EVT"), - std::make_pair(BTA_AG_AT_CLCC_EVT, "BTA_AG_AT_CLCC_EVT"), - std::make_pair(BTA_AG_AT_COPS_EVT, "BTA_AG_AT_COPS_EVT"), - std::make_pair(BTA_AG_AT_UNAT_EVT, "BTA_AG_AT_UNAT_EVT"), - std::make_pair(BTA_AG_AT_CBC_EVT, "BTA_AG_AT_CBC_EVT"), - std::make_pair(BTA_AG_AT_BAC_EVT, "BTA_AG_AT_BAC_EVT"), - std::make_pair(BTA_AG_AT_BCS_EVT, "BTA_AG_AT_BCS_EVT"), - std::make_pair(BTA_AG_AT_BIND_EVT, "BTA_AG_AT_BIND_EVT"), - std::make_pair(BTA_AG_AT_BIEV_EVT, "BTA_AG_AT_BIEV_EVT"), - std::make_pair(BTA_AG_AT_BIA_EVT, "BTA_AG_AT_BIA_EVT"), + std::make_pair(BTA_AG_ENABLE_EVT, "BTA_AG_ENABLE_EVT"), + std::make_pair(BTA_AG_REGISTER_EVT, "BTA_AG_REGISTER_EVT"), + std::make_pair(BTA_AG_OPEN_EVT, "BTA_AG_OPEN_EVT"), + std::make_pair(BTA_AG_CLOSE_EVT, "BTA_AG_CLOSE_EVT"), + std::make_pair(BTA_AG_CONN_EVT, "BTA_AG_CONN_EVT"), + std::make_pair(BTA_AG_AUDIO_OPEN_EVT, "BTA_AG_AUDIO_OPEN_EVT"), + std::make_pair(BTA_AG_AUDIO_CLOSE_EVT, "BTA_AG_AUDIO_CLOSE_EVT"), + std::make_pair(BTA_AG_SPK_EVT, "BTA_AG_SPK_EVT"), + std::make_pair(BTA_AG_MIC_EVT, "BTA_AG_MIC_EVT"), + std::make_pair(BTA_AG_AT_CKPD_EVT, "BTA_AG_AT_CKPD_EVT"), + std::make_pair(BTA_AG_DISABLE_EVT, "BTA_AG_DISABLE_EVT"), + std::make_pair(BTA_AG_CODEC_EVT, "BTA_AG_CODEC_EVT"), + std::make_pair(BTA_AG_AT_A_EVT, "BTA_AG_AT_A_EVT"), + std::make_pair(BTA_AG_AT_D_EVT, "BTA_AG_AT_D_EVT"), + std::make_pair(BTA_AG_AT_CHLD_EVT, "BTA_AG_AT_CHLD_EVT"), + std::make_pair(BTA_AG_AT_CHUP_EVT, "BTA_AG_AT_CHUP_EVT"), + std::make_pair(BTA_AG_AT_CIND_EVT, "BTA_AG_AT_CIND_EVT"), + std::make_pair(BTA_AG_AT_VTS_EVT, "BTA_AG_AT_VTS_EVT"), + std::make_pair(BTA_AG_AT_BINP_EVT, "BTA_AG_AT_BINP_EVT"), + std::make_pair(BTA_AG_AT_BLDN_EVT, "BTA_AG_AT_BLDN_EVT"), + std::make_pair(BTA_AG_AT_BVRA_EVT, "BTA_AG_AT_BVRA_EVT"), + std::make_pair(BTA_AG_AT_NREC_EVT, "BTA_AG_AT_NREC_EVT"), + std::make_pair(BTA_AG_AT_CNUM_EVT, "BTA_AG_AT_CNUM_EVT"), + std::make_pair(BTA_AG_AT_BTRH_EVT, "BTA_AG_AT_BTRH_EVT"), + std::make_pair(BTA_AG_AT_CLCC_EVT, "BTA_AG_AT_CLCC_EVT"), + std::make_pair(BTA_AG_AT_COPS_EVT, "BTA_AG_AT_COPS_EVT"), + std::make_pair(BTA_AG_AT_UNAT_EVT, "BTA_AG_AT_UNAT_EVT"), + std::make_pair(BTA_AG_AT_CBC_EVT, "BTA_AG_AT_CBC_EVT"), + std::make_pair(BTA_AG_AT_BAC_EVT, "BTA_AG_AT_BAC_EVT"), + std::make_pair(BTA_AG_AT_BCS_EVT, "BTA_AG_AT_BCS_EVT"), + std::make_pair(BTA_AG_AT_BIND_EVT, "BTA_AG_AT_BIND_EVT"), + std::make_pair(BTA_AG_AT_BIEV_EVT, "BTA_AG_AT_BIEV_EVT"), + std::make_pair(BTA_AG_AT_BIA_EVT, "BTA_AG_AT_BIA_EVT"), }; for (const auto& event : events) { ASSERT_TRUE(dump_hf_event(event.first).starts_with(event.second)); } - ASSERT_TRUE(dump_hf_event(std::numeric_limits::max()) - .starts_with("Unknown")); + ASSERT_TRUE(dump_hf_event(std::numeric_limits::max()).starts_with("Unknown")); } TEST_F(BtifUtilsTest, dump_hf_client_event) { std::vector> events = { - std::make_pair(BTA_HF_CLIENT_ENABLE_EVT, "BTA_HF_CLIENT_ENABLE_EVT"), - std::make_pair(BTA_HF_CLIENT_REGISTER_EVT, "BTA_HF_CLIENT_REGISTER_EVT"), - std::make_pair(BTA_HF_CLIENT_OPEN_EVT, "BTA_HF_CLIENT_OPEN_EVT"), - std::make_pair(BTA_HF_CLIENT_CLOSE_EVT, "BTA_HF_CLIENT_CLOSE_EVT"), - std::make_pair(BTA_HF_CLIENT_CONN_EVT, "BTA_HF_CLIENT_CONN_EVT"), - std::make_pair(BTA_HF_CLIENT_AUDIO_OPEN_EVT, - "BTA_HF_CLIENT_AUDIO_OPEN_EVT"), - std::make_pair(BTA_HF_CLIENT_AUDIO_MSBC_OPEN_EVT, - "BTA_HF_CLIENT_AUDIO_MSBC_OPEN_EVT"), - std::make_pair(BTA_HF_CLIENT_AUDIO_LC3_OPEN_EVT, - "BTA_HF_CLIENT_AUDIO_LC3_OPEN_EVT"), - std::make_pair(BTA_HF_CLIENT_AUDIO_CLOSE_EVT, - "BTA_HF_CLIENT_AUDIO_CLOSE_EVT"), - std::make_pair(BTA_HF_CLIENT_SPK_EVT, "BTA_HF_CLIENT_SPK_EVT"), - std::make_pair(BTA_HF_CLIENT_MIC_EVT, "BTA_HF_CLIENT_MIC_EVT"), - std::make_pair(BTA_HF_CLIENT_DISABLE_EVT, "BTA_HF_CLIENT_DISABLE_EVT"), - std::make_pair(BTA_HF_CLIENT_IND_EVT, "BTA_HF_CLIENT_IND_EVT"), - std::make_pair(BTA_HF_CLIENT_VOICE_REC_EVT, - "BTA_HF_CLIENT_VOICE_REC_EVT"), - std::make_pair(BTA_HF_CLIENT_OPERATOR_NAME_EVT, - "BTA_HF_CLIENT_OPERATOR_NAME_EVT"), - std::make_pair(BTA_HF_CLIENT_CLIP_EVT, "BTA_HF_CLIENT_CLIP_EVT"), - std::make_pair(BTA_HF_CLIENT_CCWA_EVT, "BTA_HF_CLIENT_CCWA_EVT"), - std::make_pair(BTA_HF_CLIENT_AT_RESULT_EVT, - "BTA_HF_CLIENT_AT_RESULT_EVT"), - std::make_pair(BTA_HF_CLIENT_CLCC_EVT, "BTA_HF_CLIENT_CLCC_EVT"), - std::make_pair(BTA_HF_CLIENT_CNUM_EVT, "BTA_HF_CLIENT_CNUM_EVT"), - std::make_pair(BTA_HF_CLIENT_BTRH_EVT, "BTA_HF_CLIENT_BTRH_EVT"), - std::make_pair(BTA_HF_CLIENT_BSIR_EVT, "BTA_HF_CLIENT_BSIR_EVT"), - std::make_pair(BTA_HF_CLIENT_BINP_EVT, "BTA_HF_CLIENT_BINP_EVT"), - std::make_pair(BTA_HF_CLIENT_RING_INDICATION, - "BTA_HF_CLIENT_RING_INDICATION"), + std::make_pair(BTA_HF_CLIENT_ENABLE_EVT, "BTA_HF_CLIENT_ENABLE_EVT"), + std::make_pair(BTA_HF_CLIENT_REGISTER_EVT, "BTA_HF_CLIENT_REGISTER_EVT"), + std::make_pair(BTA_HF_CLIENT_OPEN_EVT, "BTA_HF_CLIENT_OPEN_EVT"), + std::make_pair(BTA_HF_CLIENT_CLOSE_EVT, "BTA_HF_CLIENT_CLOSE_EVT"), + std::make_pair(BTA_HF_CLIENT_CONN_EVT, "BTA_HF_CLIENT_CONN_EVT"), + std::make_pair(BTA_HF_CLIENT_AUDIO_OPEN_EVT, "BTA_HF_CLIENT_AUDIO_OPEN_EVT"), + std::make_pair(BTA_HF_CLIENT_AUDIO_MSBC_OPEN_EVT, "BTA_HF_CLIENT_AUDIO_MSBC_OPEN_EVT"), + std::make_pair(BTA_HF_CLIENT_AUDIO_LC3_OPEN_EVT, "BTA_HF_CLIENT_AUDIO_LC3_OPEN_EVT"), + std::make_pair(BTA_HF_CLIENT_AUDIO_CLOSE_EVT, "BTA_HF_CLIENT_AUDIO_CLOSE_EVT"), + std::make_pair(BTA_HF_CLIENT_SPK_EVT, "BTA_HF_CLIENT_SPK_EVT"), + std::make_pair(BTA_HF_CLIENT_MIC_EVT, "BTA_HF_CLIENT_MIC_EVT"), + std::make_pair(BTA_HF_CLIENT_DISABLE_EVT, "BTA_HF_CLIENT_DISABLE_EVT"), + std::make_pair(BTA_HF_CLIENT_IND_EVT, "BTA_HF_CLIENT_IND_EVT"), + std::make_pair(BTA_HF_CLIENT_VOICE_REC_EVT, "BTA_HF_CLIENT_VOICE_REC_EVT"), + std::make_pair(BTA_HF_CLIENT_OPERATOR_NAME_EVT, "BTA_HF_CLIENT_OPERATOR_NAME_EVT"), + std::make_pair(BTA_HF_CLIENT_CLIP_EVT, "BTA_HF_CLIENT_CLIP_EVT"), + std::make_pair(BTA_HF_CLIENT_CCWA_EVT, "BTA_HF_CLIENT_CCWA_EVT"), + std::make_pair(BTA_HF_CLIENT_AT_RESULT_EVT, "BTA_HF_CLIENT_AT_RESULT_EVT"), + std::make_pair(BTA_HF_CLIENT_CLCC_EVT, "BTA_HF_CLIENT_CLCC_EVT"), + std::make_pair(BTA_HF_CLIENT_CNUM_EVT, "BTA_HF_CLIENT_CNUM_EVT"), + std::make_pair(BTA_HF_CLIENT_BTRH_EVT, "BTA_HF_CLIENT_BTRH_EVT"), + std::make_pair(BTA_HF_CLIENT_BSIR_EVT, "BTA_HF_CLIENT_BSIR_EVT"), + std::make_pair(BTA_HF_CLIENT_BINP_EVT, "BTA_HF_CLIENT_BINP_EVT"), + std::make_pair(BTA_HF_CLIENT_RING_INDICATION, "BTA_HF_CLIENT_RING_INDICATION"), }; for (const auto& event : events) { ASSERT_TRUE(dump_hf_client_event(event.first).starts_with(event.second)); } - ASSERT_TRUE(dump_hf_client_event(std::numeric_limits::max()) - .starts_with("Unknown")); + ASSERT_TRUE(dump_hf_client_event(std::numeric_limits::max()).starts_with("Unknown")); } TEST_F(BtifCoreTest, bta_hh_event_text) { std::vector> events = { - std::make_pair(BTA_HH_EMPTY_EVT, "BTA_HH_EMPTY_EVT"), - std::make_pair(BTA_HH_ENABLE_EVT, "BTA_HH_ENABLE_EVT"), - std::make_pair(BTA_HH_DISABLE_EVT, "BTA_HH_DISABLE_EVT"), - std::make_pair(BTA_HH_OPEN_EVT, "BTA_HH_OPEN_EVT"), - std::make_pair(BTA_HH_CLOSE_EVT, "BTA_HH_CLOSE_EVT"), - std::make_pair(BTA_HH_GET_DSCP_EVT, "BTA_HH_GET_DSCP_EVT"), - std::make_pair(BTA_HH_GET_PROTO_EVT, "BTA_HH_GET_PROTO_EVT"), - std::make_pair(BTA_HH_GET_RPT_EVT, "BTA_HH_GET_RPT_EVT"), - std::make_pair(BTA_HH_GET_IDLE_EVT, "BTA_HH_GET_IDLE_EVT"), - std::make_pair(BTA_HH_SET_PROTO_EVT, "BTA_HH_SET_PROTO_EVT"), - std::make_pair(BTA_HH_SET_RPT_EVT, "BTA_HH_SET_RPT_EVT"), - std::make_pair(BTA_HH_SET_IDLE_EVT, "BTA_HH_SET_IDLE_EVT"), - std::make_pair(BTA_HH_VC_UNPLUG_EVT, "BTA_HH_VC_UNPLUG_EVT"), - std::make_pair(BTA_HH_ADD_DEV_EVT, "BTA_HH_ADD_DEV_EVT"), - std::make_pair(BTA_HH_RMV_DEV_EVT, "BTA_HH_RMV_DEV_EVT"), - std::make_pair(BTA_HH_API_ERR_EVT, "BTA_HH_API_ERR_EVT"), + std::make_pair(BTA_HH_EMPTY_EVT, "BTA_HH_EMPTY_EVT"), + std::make_pair(BTA_HH_ENABLE_EVT, "BTA_HH_ENABLE_EVT"), + std::make_pair(BTA_HH_DISABLE_EVT, "BTA_HH_DISABLE_EVT"), + std::make_pair(BTA_HH_OPEN_EVT, "BTA_HH_OPEN_EVT"), + std::make_pair(BTA_HH_CLOSE_EVT, "BTA_HH_CLOSE_EVT"), + std::make_pair(BTA_HH_GET_DSCP_EVT, "BTA_HH_GET_DSCP_EVT"), + std::make_pair(BTA_HH_GET_PROTO_EVT, "BTA_HH_GET_PROTO_EVT"), + std::make_pair(BTA_HH_GET_RPT_EVT, "BTA_HH_GET_RPT_EVT"), + std::make_pair(BTA_HH_GET_IDLE_EVT, "BTA_HH_GET_IDLE_EVT"), + std::make_pair(BTA_HH_SET_PROTO_EVT, "BTA_HH_SET_PROTO_EVT"), + std::make_pair(BTA_HH_SET_RPT_EVT, "BTA_HH_SET_RPT_EVT"), + std::make_pair(BTA_HH_SET_IDLE_EVT, "BTA_HH_SET_IDLE_EVT"), + std::make_pair(BTA_HH_VC_UNPLUG_EVT, "BTA_HH_VC_UNPLUG_EVT"), + std::make_pair(BTA_HH_ADD_DEV_EVT, "BTA_HH_ADD_DEV_EVT"), + std::make_pair(BTA_HH_RMV_DEV_EVT, "BTA_HH_RMV_DEV_EVT"), + std::make_pair(BTA_HH_API_ERR_EVT, "BTA_HH_API_ERR_EVT"), }; for (const auto& event : events) { ASSERT_TRUE(bta_hh_event_text(event.first).starts_with(event.second)); } - ASSERT_TRUE(bta_hh_event_text(std::numeric_limits::max()) - .starts_with("Unknown")); + ASSERT_TRUE(bta_hh_event_text(std::numeric_limits::max()).starts_with("Unknown")); } TEST_F(BtifUtilsTest, dump_hd_event) { std::vector> events = { - std::make_pair(BTA_HD_ENABLE_EVT, "BTA_HD_ENABLE_EVT"), - std::make_pair(BTA_HD_DISABLE_EVT, "BTA_HD_DISABLE_EVT"), - std::make_pair(BTA_HD_REGISTER_APP_EVT, "BTA_HD_REGISTER_APP_EVT"), - std::make_pair(BTA_HD_UNREGISTER_APP_EVT, "BTA_HD_UNREGISTER_APP_EVT"), - std::make_pair(BTA_HD_OPEN_EVT, "BTA_HD_OPEN_EVT"), - std::make_pair(BTA_HD_CLOSE_EVT, "BTA_HD_CLOSE_EVT"), - std::make_pair(BTA_HD_GET_REPORT_EVT, "BTA_HD_GET_REPORT_EVT"), - std::make_pair(BTA_HD_SET_REPORT_EVT, "BTA_HD_SET_REPORT_EVT"), - std::make_pair(BTA_HD_SET_PROTOCOL_EVT, "BTA_HD_SET_PROTOCOL_EVT"), - std::make_pair(BTA_HD_INTR_DATA_EVT, "BTA_HD_INTR_DATA_EVT"), - std::make_pair(BTA_HD_VC_UNPLUG_EVT, "BTA_HD_VC_UNPLUG_EVT"), - std::make_pair(BTA_HD_CONN_STATE_EVT, "BTA_HD_CONN_STATE_EVT"), - std::make_pair(BTA_HD_API_ERR_EVT, "BTA_HD_API_ERR_EVT"), + std::make_pair(BTA_HD_ENABLE_EVT, "BTA_HD_ENABLE_EVT"), + std::make_pair(BTA_HD_DISABLE_EVT, "BTA_HD_DISABLE_EVT"), + std::make_pair(BTA_HD_REGISTER_APP_EVT, "BTA_HD_REGISTER_APP_EVT"), + std::make_pair(BTA_HD_UNREGISTER_APP_EVT, "BTA_HD_UNREGISTER_APP_EVT"), + std::make_pair(BTA_HD_OPEN_EVT, "BTA_HD_OPEN_EVT"), + std::make_pair(BTA_HD_CLOSE_EVT, "BTA_HD_CLOSE_EVT"), + std::make_pair(BTA_HD_GET_REPORT_EVT, "BTA_HD_GET_REPORT_EVT"), + std::make_pair(BTA_HD_SET_REPORT_EVT, "BTA_HD_SET_REPORT_EVT"), + std::make_pair(BTA_HD_SET_PROTOCOL_EVT, "BTA_HD_SET_PROTOCOL_EVT"), + std::make_pair(BTA_HD_INTR_DATA_EVT, "BTA_HD_INTR_DATA_EVT"), + std::make_pair(BTA_HD_VC_UNPLUG_EVT, "BTA_HD_VC_UNPLUG_EVT"), + std::make_pair(BTA_HD_CONN_STATE_EVT, "BTA_HD_CONN_STATE_EVT"), + std::make_pair(BTA_HD_API_ERR_EVT, "BTA_HD_API_ERR_EVT"), }; for (const auto& event : events) { ASSERT_TRUE(dump_hd_event(event.first).starts_with(event.second)); } - ASSERT_TRUE(dump_hd_event(std::numeric_limits::max()) - .starts_with("Unknown")); + ASSERT_TRUE(dump_hd_event(std::numeric_limits::max()).starts_with("Unknown")); } TEST_F(BtifUtilsTest, dump_thread_evt) { std::vector> events = { - std::make_pair(ASSOCIATE_JVM, "ASSOCIATE_JVM"), - std::make_pair(DISASSOCIATE_JVM, "DISASSOCIATE_JVM"), + std::make_pair(ASSOCIATE_JVM, "ASSOCIATE_JVM"), + std::make_pair(DISASSOCIATE_JVM, "DISASSOCIATE_JVM"), }; for (const auto& event : events) { ASSERT_TRUE(dump_thread_evt(event.first).starts_with(event.second)); } - ASSERT_TRUE(dump_thread_evt(static_cast( - std::numeric_limits::max())) - .starts_with("Unknown")); + ASSERT_TRUE(dump_thread_evt(static_cast(std::numeric_limits::max())) + .starts_with("Unknown")); } TEST_F(BtifUtilsTest, dump_av_conn_state) { std::vector> events = { - std::make_pair(BTAV_CONNECTION_STATE_DISCONNECTED, - "BTAV_CONNECTION_STATE_DISCONNECTED"), - std::make_pair(BTAV_CONNECTION_STATE_CONNECTING, - "BTAV_CONNECTION_STATE_CONNECTING"), - std::make_pair(BTAV_CONNECTION_STATE_CONNECTED, - "BTAV_CONNECTION_STATE_CONNECTED"), - std::make_pair(BTAV_CONNECTION_STATE_DISCONNECTING, - "BTAV_CONNECTION_STATE_DISCONNECTING"), + std::make_pair(BTAV_CONNECTION_STATE_DISCONNECTED, "BTAV_CONNECTION_STATE_DISCONNECTED"), + std::make_pair(BTAV_CONNECTION_STATE_CONNECTING, "BTAV_CONNECTION_STATE_CONNECTING"), + std::make_pair(BTAV_CONNECTION_STATE_CONNECTED, "BTAV_CONNECTION_STATE_CONNECTED"), + std::make_pair(BTAV_CONNECTION_STATE_DISCONNECTING, + "BTAV_CONNECTION_STATE_DISCONNECTING"), }; for (const auto& event : events) { ASSERT_TRUE(dump_av_conn_state(event.first).starts_with(event.second)); } - ASSERT_TRUE(dump_av_conn_state(std::numeric_limits::max()) - .starts_with("Unknown")); + ASSERT_TRUE(dump_av_conn_state(std::numeric_limits::max()).starts_with("Unknown")); } TEST_F(BtifUtilsTest, dump_av_audio_state) { std::vector> events = { - std::make_pair(BTAV_AUDIO_STATE_REMOTE_SUSPEND, - "BTAV_AUDIO_STATE_REMOTE_SUSPEND"), - std::make_pair(BTAV_AUDIO_STATE_STOPPED, "BTAV_AUDIO_STATE_STOPPED"), - std::make_pair(BTAV_AUDIO_STATE_STARTED, "BTAV_AUDIO_STATE_STARTED"), + std::make_pair(BTAV_AUDIO_STATE_REMOTE_SUSPEND, "BTAV_AUDIO_STATE_REMOTE_SUSPEND"), + std::make_pair(BTAV_AUDIO_STATE_STOPPED, "BTAV_AUDIO_STATE_STOPPED"), + std::make_pair(BTAV_AUDIO_STATE_STARTED, "BTAV_AUDIO_STATE_STARTED"), }; for (const auto& event : events) { ASSERT_TRUE(dump_av_audio_state(event.first).starts_with(event.second)); } - ASSERT_TRUE(dump_av_audio_state(std::numeric_limits::max()) - .starts_with("Unknown")); + ASSERT_TRUE(dump_av_audio_state(std::numeric_limits::max()).starts_with("Unknown")); } TEST_F(BtifUtilsTest, dump_adapter_scan_mode) { std::vector> events = { - std::make_pair(BT_SCAN_MODE_NONE, "BT_SCAN_MODE_NONE"), - std::make_pair(BT_SCAN_MODE_CONNECTABLE, "BT_SCAN_MODE_CONNECTABLE"), - std::make_pair(BT_SCAN_MODE_CONNECTABLE_DISCOVERABLE, - "BT_SCAN_MODE_CONNECTABLE_DISCOVERABLE"), + std::make_pair(BT_SCAN_MODE_NONE, "BT_SCAN_MODE_NONE"), + std::make_pair(BT_SCAN_MODE_CONNECTABLE, "BT_SCAN_MODE_CONNECTABLE"), + std::make_pair(BT_SCAN_MODE_CONNECTABLE_DISCOVERABLE, + "BT_SCAN_MODE_CONNECTABLE_DISCOVERABLE"), }; for (const auto& event : events) { ASSERT_TRUE(dump_adapter_scan_mode(event.first).starts_with(event.second)); } - ASSERT_TRUE(dump_adapter_scan_mode( - static_cast(std::numeric_limits::max())) - .starts_with("Unknown")); + ASSERT_TRUE(dump_adapter_scan_mode(static_cast(std::numeric_limits::max())) + .starts_with("Unknown")); } TEST_F(BtifUtilsTest, dump_bt_status) { std::vector> events = { - std::make_pair(BT_STATUS_SUCCESS, "BT_STATUS_SUCCESS"), - std::make_pair(BT_STATUS_FAIL, "BT_STATUS_FAIL"), - std::make_pair(BT_STATUS_NOT_READY, "BT_STATUS_NOT_READY"), - std::make_pair(BT_STATUS_NOMEM, "BT_STATUS_NOMEM"), - std::make_pair(BT_STATUS_BUSY, "BT_STATUS_BUSY"), - std::make_pair(BT_STATUS_UNSUPPORTED, "BT_STATUS_UNSUPPORTED"), + std::make_pair(BT_STATUS_SUCCESS, "BT_STATUS_SUCCESS"), + std::make_pair(BT_STATUS_FAIL, "BT_STATUS_FAIL"), + std::make_pair(BT_STATUS_NOT_READY, "BT_STATUS_NOT_READY"), + std::make_pair(BT_STATUS_NOMEM, "BT_STATUS_NOMEM"), + std::make_pair(BT_STATUS_BUSY, "BT_STATUS_BUSY"), + std::make_pair(BT_STATUS_UNSUPPORTED, "BT_STATUS_UNSUPPORTED"), }; for (const auto& event : events) { ASSERT_TRUE(dump_bt_status(event.first).starts_with(event.second)); } - ASSERT_TRUE( - dump_bt_status(static_cast(std::numeric_limits::max())) - .starts_with("Unknown")); + ASSERT_TRUE(dump_bt_status(static_cast(std::numeric_limits::max())) + .starts_with("Unknown")); } TEST_F(BtifUtilsTest, dump_rc_event) { std::vector> events = { - std::make_pair(BTA_AV_RC_OPEN_EVT, "BTA_AV_RC_OPEN_EVT"), - std::make_pair(BTA_AV_RC_CLOSE_EVT, "BTA_AV_RC_CLOSE_EVT"), - std::make_pair(BTA_AV_RC_BROWSE_OPEN_EVT, "BTA_AV_RC_BROWSE_OPEN_EVT"), - std::make_pair(BTA_AV_RC_BROWSE_CLOSE_EVT, "BTA_AV_RC_BROWSE_CLOSE_EVT"), - std::make_pair(BTA_AV_REMOTE_CMD_EVT, "BTA_AV_REMOTE_CMD_EVT"), - std::make_pair(BTA_AV_REMOTE_RSP_EVT, "BTA_AV_REMOTE_RSP_EVT"), - std::make_pair(BTA_AV_VENDOR_CMD_EVT, "BTA_AV_VENDOR_CMD_EVT"), - std::make_pair(BTA_AV_VENDOR_RSP_EVT, "BTA_AV_VENDOR_RSP_EVT"), - std::make_pair(BTA_AV_META_MSG_EVT, "BTA_AV_META_MSG_EVT"), - std::make_pair(BTA_AV_RC_FEAT_EVT, "BTA_AV_RC_FEAT_EVT"), - std::make_pair(BTA_AV_RC_PSM_EVT, "BTA_AV_RC_PSM_EVT"), + std::make_pair(BTA_AV_RC_OPEN_EVT, "BTA_AV_RC_OPEN_EVT"), + std::make_pair(BTA_AV_RC_CLOSE_EVT, "BTA_AV_RC_CLOSE_EVT"), + std::make_pair(BTA_AV_RC_BROWSE_OPEN_EVT, "BTA_AV_RC_BROWSE_OPEN_EVT"), + std::make_pair(BTA_AV_RC_BROWSE_CLOSE_EVT, "BTA_AV_RC_BROWSE_CLOSE_EVT"), + std::make_pair(BTA_AV_REMOTE_CMD_EVT, "BTA_AV_REMOTE_CMD_EVT"), + std::make_pair(BTA_AV_REMOTE_RSP_EVT, "BTA_AV_REMOTE_RSP_EVT"), + std::make_pair(BTA_AV_VENDOR_CMD_EVT, "BTA_AV_VENDOR_CMD_EVT"), + std::make_pair(BTA_AV_VENDOR_RSP_EVT, "BTA_AV_VENDOR_RSP_EVT"), + std::make_pair(BTA_AV_META_MSG_EVT, "BTA_AV_META_MSG_EVT"), + std::make_pair(BTA_AV_RC_FEAT_EVT, "BTA_AV_RC_FEAT_EVT"), + std::make_pair(BTA_AV_RC_PSM_EVT, "BTA_AV_RC_PSM_EVT"), }; for (const auto& event : events) { ASSERT_TRUE(dump_rc_event(event.first).starts_with(event.second)); } - ASSERT_TRUE(dump_rc_event(std::numeric_limits::max()) - .starts_with("Unknown")); + ASSERT_TRUE(dump_rc_event(std::numeric_limits::max()).starts_with("Unknown")); } TEST_F(BtifUtilsTest, dump_rc_notification_event_id) { std::vector> events = { - std::make_pair(AVRC_EVT_PLAY_STATUS_CHANGE, - "AVRC_EVT_PLAY_STATUS_CHANGE"), - std::make_pair(AVRC_EVT_TRACK_CHANGE, "AVRC_EVT_TRACK_CHANGE"), - std::make_pair(AVRC_EVT_TRACK_REACHED_END, "AVRC_EVT_TRACK_REACHED_END"), - std::make_pair(AVRC_EVT_TRACK_REACHED_START, - "AVRC_EVT_TRACK_REACHED_START"), - std::make_pair(AVRC_EVT_PLAY_POS_CHANGED, "AVRC_EVT_PLAY_POS_CHANGED"), - std::make_pair(AVRC_EVT_BATTERY_STATUS_CHANGE, - "AVRC_EVT_BATTERY_STATUS_CHANGE"), - std::make_pair(AVRC_EVT_SYSTEM_STATUS_CHANGE, - "AVRC_EVT_SYSTEM_STATUS_CHANGE"), - std::make_pair(AVRC_EVT_APP_SETTING_CHANGE, - "AVRC_EVT_APP_SETTING_CHANGE"), - std::make_pair(AVRC_EVT_VOLUME_CHANGE, "AVRC_EVT_VOLUME_CHANGE"), - std::make_pair(AVRC_EVT_ADDR_PLAYER_CHANGE, - "AVRC_EVT_ADDR_PLAYER_CHANGE"), - std::make_pair(AVRC_EVT_AVAL_PLAYERS_CHANGE, - "AVRC_EVT_AVAL_PLAYERS_CHANGE"), - std::make_pair(AVRC_EVT_NOW_PLAYING_CHANGE, - "AVRC_EVT_NOW_PLAYING_CHANGE"), - std::make_pair(AVRC_EVT_UIDS_CHANGE, "AVRC_EVT_UIDS_CHANGE"), + std::make_pair(AVRC_EVT_PLAY_STATUS_CHANGE, "AVRC_EVT_PLAY_STATUS_CHANGE"), + std::make_pair(AVRC_EVT_TRACK_CHANGE, "AVRC_EVT_TRACK_CHANGE"), + std::make_pair(AVRC_EVT_TRACK_REACHED_END, "AVRC_EVT_TRACK_REACHED_END"), + std::make_pair(AVRC_EVT_TRACK_REACHED_START, "AVRC_EVT_TRACK_REACHED_START"), + std::make_pair(AVRC_EVT_PLAY_POS_CHANGED, "AVRC_EVT_PLAY_POS_CHANGED"), + std::make_pair(AVRC_EVT_BATTERY_STATUS_CHANGE, "AVRC_EVT_BATTERY_STATUS_CHANGE"), + std::make_pair(AVRC_EVT_SYSTEM_STATUS_CHANGE, "AVRC_EVT_SYSTEM_STATUS_CHANGE"), + std::make_pair(AVRC_EVT_APP_SETTING_CHANGE, "AVRC_EVT_APP_SETTING_CHANGE"), + std::make_pair(AVRC_EVT_VOLUME_CHANGE, "AVRC_EVT_VOLUME_CHANGE"), + std::make_pair(AVRC_EVT_ADDR_PLAYER_CHANGE, "AVRC_EVT_ADDR_PLAYER_CHANGE"), + std::make_pair(AVRC_EVT_AVAL_PLAYERS_CHANGE, "AVRC_EVT_AVAL_PLAYERS_CHANGE"), + std::make_pair(AVRC_EVT_NOW_PLAYING_CHANGE, "AVRC_EVT_NOW_PLAYING_CHANGE"), + std::make_pair(AVRC_EVT_UIDS_CHANGE, "AVRC_EVT_UIDS_CHANGE"), }; for (const auto& event : events) { - ASSERT_TRUE( - dump_rc_notification_event_id(event.first).starts_with(event.second)); + ASSERT_TRUE(dump_rc_notification_event_id(event.first).starts_with(event.second)); } ASSERT_TRUE(dump_rc_notification_event_id(std::numeric_limits::max()) - .starts_with("Unknown")); + .starts_with("Unknown")); } TEST_F(BtifUtilsTest, dump_rc_pdu) { std::vector> pdus = { - std::make_pair(AVRC_PDU_LIST_PLAYER_APP_ATTR, - "AVRC_PDU_LIST_PLAYER_APP_ATTR"), - std::make_pair(AVRC_PDU_LIST_PLAYER_APP_VALUES, - "AVRC_PDU_LIST_PLAYER_APP_VALUES"), - std::make_pair(AVRC_PDU_GET_CUR_PLAYER_APP_VALUE, - "AVRC_PDU_GET_CUR_PLAYER_APP_VALUE"), - std::make_pair(AVRC_PDU_SET_PLAYER_APP_VALUE, - "AVRC_PDU_SET_PLAYER_APP_VALUE"), - std::make_pair(AVRC_PDU_GET_PLAYER_APP_ATTR_TEXT, - "AVRC_PDU_GET_PLAYER_APP_ATTR_TEXT"), - std::make_pair(AVRC_PDU_GET_PLAYER_APP_VALUE_TEXT, - "AVRC_PDU_GET_PLAYER_APP_VALUE_TEXT"), - std::make_pair(AVRC_PDU_INFORM_DISPLAY_CHARSET, - "AVRC_PDU_INFORM_DISPLAY_CHARSET"), - std::make_pair(AVRC_PDU_INFORM_BATTERY_STAT_OF_CT, - "AVRC_PDU_INFORM_BATTERY_STAT_OF_CT"), - std::make_pair(AVRC_PDU_GET_ELEMENT_ATTR, "AVRC_PDU_GET_ELEMENT_ATTR"), - std::make_pair(AVRC_PDU_GET_PLAY_STATUS, "AVRC_PDU_GET_PLAY_STATUS"), - std::make_pair(AVRC_PDU_REGISTER_NOTIFICATION, - "AVRC_PDU_REGISTER_NOTIFICATION"), - std::make_pair(AVRC_PDU_REQUEST_CONTINUATION_RSP, - "AVRC_PDU_REQUEST_CONTINUATION_RSP"), - std::make_pair(AVRC_PDU_ABORT_CONTINUATION_RSP, - "AVRC_PDU_ABORT_CONTINUATION_RSP"), - std::make_pair(AVRC_PDU_SET_ABSOLUTE_VOLUME, - "AVRC_PDU_SET_ABSOLUTE_VOLUME"), - std::make_pair(AVRC_PDU_SET_ADDRESSED_PLAYER, - "AVRC_PDU_SET_ADDRESSED_PLAYER"), - std::make_pair(AVRC_PDU_CHANGE_PATH, "AVRC_PDU_CHANGE_PATH"), - std::make_pair(AVRC_PDU_GET_CAPABILITIES, "AVRC_PDU_GET_CAPABILITIES"), - std::make_pair(AVRC_PDU_SET_BROWSED_PLAYER, - "AVRC_PDU_SET_BROWSED_PLAYER"), - std::make_pair(AVRC_PDU_GET_FOLDER_ITEMS, "AVRC_PDU_GET_FOLDER_ITEMS"), - std::make_pair(AVRC_PDU_GET_ITEM_ATTRIBUTES, - "AVRC_PDU_GET_ITEM_ATTRIBUTES"), - std::make_pair(AVRC_PDU_PLAY_ITEM, "AVRC_PDU_PLAY_ITEM"), - std::make_pair(AVRC_PDU_SEARCH, "AVRC_PDU_SEARCH"), - std::make_pair(AVRC_PDU_ADD_TO_NOW_PLAYING, - "AVRC_PDU_ADD_TO_NOW_PLAYING"), - std::make_pair(AVRC_PDU_GET_TOTAL_NUM_OF_ITEMS, - "AVRC_PDU_GET_TOTAL_NUM_OF_ITEMS"), - std::make_pair(AVRC_PDU_GENERAL_REJECT, "AVRC_PDU_GENERAL_REJECT"), + std::make_pair(AVRC_PDU_LIST_PLAYER_APP_ATTR, "AVRC_PDU_LIST_PLAYER_APP_ATTR"), + std::make_pair(AVRC_PDU_LIST_PLAYER_APP_VALUES, "AVRC_PDU_LIST_PLAYER_APP_VALUES"), + std::make_pair(AVRC_PDU_GET_CUR_PLAYER_APP_VALUE, "AVRC_PDU_GET_CUR_PLAYER_APP_VALUE"), + std::make_pair(AVRC_PDU_SET_PLAYER_APP_VALUE, "AVRC_PDU_SET_PLAYER_APP_VALUE"), + std::make_pair(AVRC_PDU_GET_PLAYER_APP_ATTR_TEXT, "AVRC_PDU_GET_PLAYER_APP_ATTR_TEXT"), + std::make_pair(AVRC_PDU_GET_PLAYER_APP_VALUE_TEXT, "AVRC_PDU_GET_PLAYER_APP_VALUE_TEXT"), + std::make_pair(AVRC_PDU_INFORM_DISPLAY_CHARSET, "AVRC_PDU_INFORM_DISPLAY_CHARSET"), + std::make_pair(AVRC_PDU_INFORM_BATTERY_STAT_OF_CT, "AVRC_PDU_INFORM_BATTERY_STAT_OF_CT"), + std::make_pair(AVRC_PDU_GET_ELEMENT_ATTR, "AVRC_PDU_GET_ELEMENT_ATTR"), + std::make_pair(AVRC_PDU_GET_PLAY_STATUS, "AVRC_PDU_GET_PLAY_STATUS"), + std::make_pair(AVRC_PDU_REGISTER_NOTIFICATION, "AVRC_PDU_REGISTER_NOTIFICATION"), + std::make_pair(AVRC_PDU_REQUEST_CONTINUATION_RSP, "AVRC_PDU_REQUEST_CONTINUATION_RSP"), + std::make_pair(AVRC_PDU_ABORT_CONTINUATION_RSP, "AVRC_PDU_ABORT_CONTINUATION_RSP"), + std::make_pair(AVRC_PDU_SET_ABSOLUTE_VOLUME, "AVRC_PDU_SET_ABSOLUTE_VOLUME"), + std::make_pair(AVRC_PDU_SET_ADDRESSED_PLAYER, "AVRC_PDU_SET_ADDRESSED_PLAYER"), + std::make_pair(AVRC_PDU_CHANGE_PATH, "AVRC_PDU_CHANGE_PATH"), + std::make_pair(AVRC_PDU_GET_CAPABILITIES, "AVRC_PDU_GET_CAPABILITIES"), + std::make_pair(AVRC_PDU_SET_BROWSED_PLAYER, "AVRC_PDU_SET_BROWSED_PLAYER"), + std::make_pair(AVRC_PDU_GET_FOLDER_ITEMS, "AVRC_PDU_GET_FOLDER_ITEMS"), + std::make_pair(AVRC_PDU_GET_ITEM_ATTRIBUTES, "AVRC_PDU_GET_ITEM_ATTRIBUTES"), + std::make_pair(AVRC_PDU_PLAY_ITEM, "AVRC_PDU_PLAY_ITEM"), + std::make_pair(AVRC_PDU_SEARCH, "AVRC_PDU_SEARCH"), + std::make_pair(AVRC_PDU_ADD_TO_NOW_PLAYING, "AVRC_PDU_ADD_TO_NOW_PLAYING"), + std::make_pair(AVRC_PDU_GET_TOTAL_NUM_OF_ITEMS, "AVRC_PDU_GET_TOTAL_NUM_OF_ITEMS"), + std::make_pair(AVRC_PDU_GENERAL_REJECT, "AVRC_PDU_GENERAL_REJECT"), }; for (const auto& pdu : pdus) { ASSERT_TRUE(dump_rc_pdu(pdu.first).starts_with(pdu.second)); } - ASSERT_TRUE( - dump_rc_pdu(std::numeric_limits::max()).starts_with("Unknown")); + ASSERT_TRUE(dump_rc_pdu(std::numeric_limits::max()).starts_with("Unknown")); } TEST_F(BtifCoreWithControllerTest, btif_dm_get_connection_state__unconnected) { ASSERT_EQ(0, btif_dm_get_connection_state(kRawAddress)); } -TEST_F(BtifCoreWithConnectionTest, - btif_dm_get_connection_state__connected_no_encryption) { - test::mock::stack_btm_sec::BTM_IsEncrypted.body = - [](const RawAddress& /* bd_addr */, tBT_TRANSPORT transport) { - switch (transport) { - case BT_TRANSPORT_BR_EDR: - return false; - case BT_TRANSPORT_LE: - return false; - } +TEST_F(BtifCoreWithConnectionTest, btif_dm_get_connection_state__connected_no_encryption) { + test::mock::stack_btm_sec::BTM_IsEncrypted.body = [](const RawAddress& /* bd_addr */, + tBT_TRANSPORT transport) { + switch (transport) { + case BT_TRANSPORT_BR_EDR: + return false; + case BT_TRANSPORT_LE: return false; - }; + } + return false; + }; ASSERT_EQ(1, btif_dm_get_connection_state(kRawAddress)); test::mock::stack_btm_sec::BTM_IsEncrypted = {}; } -TEST_F(BtifCoreWithConnectionTest, - btif_dm_get_connection_state__connected_classic_encryption) { - test::mock::stack_btm_sec::BTM_IsEncrypted.body = - [](const RawAddress& /* bd_addr */, tBT_TRANSPORT transport) { - switch (transport) { - case BT_TRANSPORT_BR_EDR: - return true; - case BT_TRANSPORT_LE: - return false; - } +TEST_F(BtifCoreWithConnectionTest, btif_dm_get_connection_state__connected_classic_encryption) { + test::mock::stack_btm_sec::BTM_IsEncrypted.body = [](const RawAddress& /* bd_addr */, + tBT_TRANSPORT transport) { + switch (transport) { + case BT_TRANSPORT_BR_EDR: + return true; + case BT_TRANSPORT_LE: return false; - }; + } + return false; + }; ASSERT_EQ(3, btif_dm_get_connection_state(kRawAddress)); test::mock::stack_btm_sec::BTM_IsEncrypted = {}; } -TEST_F(BtifCoreWithConnectionTest, - btif_dm_get_connection_state__connected_le_encryption) { - test::mock::stack_btm_sec::BTM_IsEncrypted.body = - [](const RawAddress& /* bd_addr */, tBT_TRANSPORT transport) { - switch (transport) { - case BT_TRANSPORT_BR_EDR: - return false; - case BT_TRANSPORT_LE: - return true; - } +TEST_F(BtifCoreWithConnectionTest, btif_dm_get_connection_state__connected_le_encryption) { + test::mock::stack_btm_sec::BTM_IsEncrypted.body = [](const RawAddress& /* bd_addr */, + tBT_TRANSPORT transport) { + switch (transport) { + case BT_TRANSPORT_BR_EDR: return false; - }; + case BT_TRANSPORT_LE: + return true; + } + return false; + }; ASSERT_EQ(5, btif_dm_get_connection_state(kRawAddress)); test::mock::stack_btm_sec::BTM_IsEncrypted = {}; } -TEST_F(BtifCoreWithConnectionTest, - btif_dm_get_connection_state__connected_both_encryption) { - test::mock::stack_btm_sec::BTM_IsEncrypted.body = - [](const RawAddress& /* bd_addr */, tBT_TRANSPORT transport) { - switch (transport) { - case BT_TRANSPORT_BR_EDR: - return true; - case BT_TRANSPORT_LE: - return true; - } - return false; - }; +TEST_F(BtifCoreWithConnectionTest, btif_dm_get_connection_state__connected_both_encryption) { + test::mock::stack_btm_sec::BTM_IsEncrypted.body = [](const RawAddress& /* bd_addr */, + tBT_TRANSPORT transport) { + switch (transport) { + case BT_TRANSPORT_BR_EDR: + return true; + case BT_TRANSPORT_LE: + return true; + } + return false; + }; ASSERT_EQ(7, btif_dm_get_connection_state(kRawAddress)); test::mock::stack_btm_sec::BTM_IsEncrypted = {}; } TEST_F(BtifCoreWithConnectionTest, btif_dm_get_connection_state_sync) { - test::mock::stack_btm_sec::BTM_IsEncrypted.body = - [](const RawAddress& /* bd_addr */, tBT_TRANSPORT transport) { - switch (transport) { - case BT_TRANSPORT_BR_EDR: - return true; - case BT_TRANSPORT_LE: - return true; - } - return false; - }; + test::mock::stack_btm_sec::BTM_IsEncrypted.body = [](const RawAddress& /* bd_addr */, + tBT_TRANSPORT transport) { + switch (transport) { + case BT_TRANSPORT_BR_EDR: + return true; + case BT_TRANSPORT_LE: + return true; + } + return false; + }; ASSERT_EQ(7, btif_dm_get_connection_state_sync(kRawAddress)); test::mock::stack_btm_sec::BTM_IsEncrypted = {}; } -auto get_properties = [](const char* key, char* value, - const char* /* default_value */) -> size_t { +auto get_properties = [](const char* key, char* value, const char* /* default_value */) -> size_t { static bluetooth::bqr::BqrConfiguration config{ - .report_action = bluetooth::bqr::REPORT_ACTION_ADD, - .quality_event_mask = 0x1ffff, // Everything - .minimum_report_interval_ms = 1000, - .vnd_quality_mask = 29, - .vnd_trace_mask = 5, - .report_interval_multiple = 2, + .report_action = bluetooth::bqr::REPORT_ACTION_ADD, + .quality_event_mask = 0x1ffff, // Everything + .minimum_report_interval_ms = 1000, + .vnd_quality_mask = 29, + .vnd_trace_mask = 5, + .report_interval_multiple = 2, }; if (std::string(key) == bluetooth::bqr::kpPropertyEventMask) { std::string event_mask = std::to_string(config.quality_event_mask); @@ -849,28 +764,25 @@ TEST_F(BtifCoreWithControllerTest, debug_dump_unconfigured) { auto reading_promise = std::make_unique>(); auto reading_done = reading_promise->get_future(); - do_in_main_thread(FROM_HERE, - BindOnce([]() { bluetooth::bqr::DebugDump(write_fd); })); - do_in_main_thread( - FROM_HERE, BindOnce( - [](std::unique_ptr> done_promise) { - char line_buf[1024] = ""; - int bytes_read = read(read_fd, line_buf, 1024); - EXPECT_GT(bytes_read, 0); - EXPECT_NE( - std::string(line_buf).find("Event queue is empty"), - std::string::npos); - done_promise->set_value(); - }, - std::move(reading_promise))); - EXPECT_EQ(std::future_status::ready, - reading_done.wait_for(std::chrono::seconds(1))); + do_in_main_thread(FROM_HERE, BindOnce([]() { bluetooth::bqr::DebugDump(write_fd); })); + do_in_main_thread(FROM_HERE, BindOnce( + [](std::unique_ptr> done_promise) { + char line_buf[1024] = ""; + int bytes_read = read(read_fd, line_buf, 1024); + EXPECT_GT(bytes_read, 0); + EXPECT_NE( + std::string(line_buf).find("Event queue is empty"), + std::string::npos); + done_promise->set_value(); + }, + std::move(reading_promise))); + EXPECT_EQ(std::future_status::ready, reading_done.wait_for(std::chrono::seconds(1))); close(write_fd); close(read_fd); } class BtifCoreWithVendorSupportTest : public BtifCoreWithControllerTest { - protected: +protected: void SetUp() override { BtifCoreWithControllerTest::SetUp(); bluetooth::hci::testing::mock_hci_layer_ = &hci_; @@ -878,76 +790,57 @@ class BtifCoreWithVendorSupportTest : public BtifCoreWithControllerTest { std::promise configuration_promise; auto configuration_done = configuration_promise.get_future(); - EXPECT_CALL( - hci_, - EnqueueCommand( - _, Matcher>(_))) - .WillOnce( - // Replace with real PDL for 0xfc17 - [&configuration_promise]( - std::unique_ptr cmd, - ContextualOnceCallback callback) { - auto cmd_view = VendorCommandView::Create( - CommandView::Create(BuilderToView(std::move(cmd)))); - EXPECT_TRUE(cmd_view.IsValid()); - auto response = CommandCompleteView::Create(EventView::Create( - BuilderToView(CommandCompleteBuilder::Create( - 1, cmd_view.GetOpCode(), - std::make_unique())))); - EXPECT_TRUE(response.IsValid()); - callback(response); - configuration_promise.set_value(); - }) - .RetiresOnSaturation(); - EXPECT_CALL( - hci_, - EnqueueCommand( - _, Matcher>(_))) - .WillOnce( - [](std::unique_ptr cmd, - ContextualOnceCallback callback) { - auto cmd_view = - ControllerBqrView::Create(VendorCommandView::Create( + EXPECT_CALL(hci_, + EnqueueCommand(_, Matcher>(_))) + .WillOnce( + // Replace with real PDL for 0xfc17 + [&configuration_promise]( + std::unique_ptr cmd, + ContextualOnceCallback callback) { + auto cmd_view = VendorCommandView::Create( + CommandView::Create(BuilderToView(std::move(cmd)))); + EXPECT_TRUE(cmd_view.IsValid()); + auto response = CommandCompleteView::Create( + EventView::Create(BuilderToView(CommandCompleteBuilder::Create( + 1, cmd_view.GetOpCode(), std::make_unique())))); + EXPECT_TRUE(response.IsValid()); + callback(response); + configuration_promise.set_value(); + }) + .RetiresOnSaturation(); + EXPECT_CALL(hci_, + EnqueueCommand(_, Matcher>(_))) + .WillOnce([](std::unique_ptr cmd, + ContextualOnceCallback callback) { + auto cmd_view = ControllerBqrView::Create(VendorCommandView::Create( CommandView::Create(BuilderToView(std::move(cmd))))); EXPECT_TRUE(cmd_view.IsValid()); - auto response = ControllerBqrCompleteView::Create( - CommandCompleteView::Create(EventView::Create( - BuilderToView(ControllerBqrCompleteBuilder::Create( - 1, ErrorCode::SUCCESS, - cmd_view.GetBqrQualityEventMask()))))); + auto response = ControllerBqrCompleteView::Create(CommandCompleteView::Create( + EventView::Create(BuilderToView(ControllerBqrCompleteBuilder::Create( + 1, ErrorCode::SUCCESS, cmd_view.GetBqrQualityEventMask()))))); EXPECT_TRUE(response.IsValid()); callback(response); }) - .RetiresOnSaturation(); - EXPECT_CALL( - hci_, - RegisterVendorSpecificEventHandler(VseSubeventCode::BQR_EVENT, _)) - .WillOnce(SaveArg<1>(&this->vse_callback_)); - do_in_main_thread(FROM_HERE, BindOnce([]() { - bluetooth::bqr::EnableBtQualityReport(get_main()); - })); - ASSERT_EQ(std::future_status::ready, - configuration_done.wait_for(std::chrono::seconds(1))); + .RetiresOnSaturation(); + EXPECT_CALL(hci_, RegisterVendorSpecificEventHandler(VseSubeventCode::BQR_EVENT, _)) + .WillOnce(SaveArg<1>(&this->vse_callback_)); + do_in_main_thread(FROM_HERE, + BindOnce([]() { bluetooth::bqr::EnableBtQualityReport(get_main()); })); + ASSERT_EQ(std::future_status::ready, configuration_done.wait_for(std::chrono::seconds(1))); } void TearDown() override { std::promise disable_promise; auto disable_future = disable_promise.get_future(); auto set_promise = [&disable_promise]() { disable_promise.set_value(); }; - EXPECT_CALL( - hci_, - UnregisterVendorSpecificEventHandler(VseSubeventCode::BQR_EVENT)); - EXPECT_CALL( - hci_, - EnqueueCommand( - _, Matcher>(_))) - .WillOnce(Invoke(set_promise)) - .RetiresOnSaturation(); - do_in_main_thread(FROM_HERE, BindOnce([]() { - bluetooth::bqr::EnableBtQualityReport(nullptr); - })); - ASSERT_EQ(std::future_status::ready, - disable_future.wait_for(std::chrono::seconds(1))); + EXPECT_CALL(hci_, UnregisterVendorSpecificEventHandler(VseSubeventCode::BQR_EVENT)); + EXPECT_CALL(hci_, + EnqueueCommand(_, Matcher>(_))) + .WillOnce(Invoke(set_promise)) + .RetiresOnSaturation(); + do_in_main_thread(FROM_HERE, + BindOnce([]() { bluetooth::bqr::EnableBtQualityReport(nullptr); })); + ASSERT_EQ(std::future_status::ready, disable_future.wait_for(std::chrono::seconds(1))); bluetooth::hci::testing::mock_hci_layer_ = nullptr; BtifCoreWithControllerTest::TearDown(); @@ -966,27 +859,26 @@ TEST_F(BtifCoreWithVendorSupportTest, send_a2dp_audio_choppy) { a2dp_event_promise.set_value(); }; auto view = VendorSpecificEventView::Create( - EventView::Create(BuilderToView(BqrLinkQualityEventBuilder::Create( - QualityReportId::A2DP_AUDIO_CHOPPY, BqrPacketType::TYPE_3DH3, 0x123, - Role::CENTRAL, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - std::make_unique())))); + EventView::Create(BuilderToView(BqrLinkQualityEventBuilder::Create( + QualityReportId::A2DP_AUDIO_CHOPPY, BqrPacketType::TYPE_3DH3, 0x123, + Role::CENTRAL, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + std::make_unique())))); EXPECT_TRUE(view.IsValid()); vse_callback_(view); - ASSERT_EQ(std::future_status::ready, - event_reported.wait_for(std::chrono::seconds(1))); + ASSERT_EQ(std::future_status::ready, event_reported.wait_for(std::chrono::seconds(1))); } TEST_F(BtifCoreWithVendorSupportTest, send_lmp_ll_trace) { auto payload = std::make_unique(); payload->AddOctets({'d', 'a', 't', 'a'}); - auto view = VendorSpecificEventView::Create(EventView::Create(BuilderToView( - BqrLmpLlMessageTraceEventBuilder::Create(0x123, std::move(payload))))); + auto view = VendorSpecificEventView::Create(EventView::Create( + BuilderToView(BqrLmpLlMessageTraceEventBuilder::Create(0x123, std::move(payload))))); EXPECT_TRUE(view.IsValid()); vse_callback_(view); } class BtifCoreVseWithSocketTest : public BtifCoreWithVendorSupportTest { - protected: +protected: void SetUp() override { BtifCoreWithVendorSupportTest::SetUp(); int fds[2]; @@ -1009,22 +901,19 @@ TEST_F(BtifCoreVseWithSocketTest, debug_dump_empty) { auto reading_promise = std::make_unique>(); auto reading_done = reading_promise->get_future(); - do_in_main_thread(FROM_HERE, - BindOnce([]() { bluetooth::bqr::DebugDump(write_fd); })); - do_in_main_thread( - FROM_HERE, BindOnce( - [](std::unique_ptr> done_promise) { - char line_buf[1024] = ""; - int bytes_read = read(read_fd, line_buf, 1024); - EXPECT_GT(bytes_read, 0); - EXPECT_NE( - std::string(line_buf).find("Event queue is empty"), - std::string::npos); - done_promise->set_value(); - }, - std::move(reading_promise))); - EXPECT_EQ(std::future_status::ready, - reading_done.wait_for(std::chrono::seconds(1))); + do_in_main_thread(FROM_HERE, BindOnce([]() { bluetooth::bqr::DebugDump(write_fd); })); + do_in_main_thread(FROM_HERE, BindOnce( + [](std::unique_ptr> done_promise) { + char line_buf[1024] = ""; + int bytes_read = read(read_fd, line_buf, 1024); + EXPECT_GT(bytes_read, 0); + EXPECT_NE( + std::string(line_buf).find("Event queue is empty"), + std::string::npos); + done_promise->set_value(); + }, + std::move(reading_promise))); + EXPECT_EQ(std::future_status::ready, reading_done.wait_for(std::chrono::seconds(1))); } namespace bluetooth::bqr::testing { @@ -1034,8 +923,8 @@ void set_lmp_trace_log_fd(int fd); TEST_F(BtifCoreVseWithSocketTest, send_lmp_ll_msg) { auto payload = std::make_unique(); payload->AddOctets({'d', 'a', 't', 'a'}); - auto view = VendorSpecificEventView::Create(EventView::Create(BuilderToView( - BqrLmpLlMessageTraceEventBuilder::Create(0x123, std::move(payload))))); + auto view = VendorSpecificEventView::Create(EventView::Create( + BuilderToView(BqrLmpLlMessageTraceEventBuilder::Create(0x123, std::move(payload))))); EXPECT_TRUE(view.IsValid()); static int read_fd = read_fd_; @@ -1043,37 +932,32 @@ TEST_F(BtifCoreVseWithSocketTest, send_lmp_ll_msg) { auto reading_done = reading_promise->get_future(); static int write_fd = write_fd_; - do_in_main_thread(FROM_HERE, BindOnce([]() { - bluetooth::bqr::testing::set_lmp_trace_log_fd(write_fd); - })); + do_in_main_thread(FROM_HERE, + BindOnce([]() { bluetooth::bqr::testing::set_lmp_trace_log_fd(write_fd); })); vse_callback_(view); - do_in_main_thread(FROM_HERE, - BindOnce( - [](std::unique_ptr> done_promise) { - char line_buf[1024] = ""; - std::string line; - int bytes_read = read(read_fd, line_buf, 1024); - EXPECT_GT(bytes_read, 0); - line = std::string(line_buf); - EXPECT_NE(line.find("Handle: 0x0123"), - std::string::npos); - EXPECT_NE(line.find("data"), std::string::npos); - done_promise->set_value(); - }, - std::move(reading_promise))); - EXPECT_EQ(std::future_status::ready, - reading_done.wait_for(std::chrono::seconds(1))); + do_in_main_thread(FROM_HERE, BindOnce( + [](std::unique_ptr> done_promise) { + char line_buf[1024] = ""; + std::string line; + int bytes_read = read(read_fd, line_buf, 1024); + EXPECT_GT(bytes_read, 0); + line = std::string(line_buf); + EXPECT_NE(line.find("Handle: 0x0123"), std::string::npos); + EXPECT_NE(line.find("data"), std::string::npos); + done_promise->set_value(); + }, + std::move(reading_promise))); + EXPECT_EQ(std::future_status::ready, reading_done.wait_for(std::chrono::seconds(1))); } TEST_F(BtifCoreVseWithSocketTest, debug_dump_a2dp_choppy_no_payload) { auto payload = std::make_unique(); auto view = VendorSpecificEventView::Create( - EventView::Create(BuilderToView(BqrA2dpAudioChoppyEventBuilder::Create( - BqrPacketType::TYPE_3DH3, 0x123, Role::CENTRAL, 1, 2 /* rssi */, 3, 4, - 5 /* afh_select_uni */, 6 /* lsto */, 7, 8, 9, 10, - 11 /* last_tx_ack_timestamp */, 12, 13, 14, - 15 /* buffer_underflow_bytes */, std::move(payload))))); + EventView::Create(BuilderToView(BqrA2dpAudioChoppyEventBuilder::Create( + BqrPacketType::TYPE_3DH3, 0x123, Role::CENTRAL, 1, 2 /* rssi */, 3, 4, + 5 /* afh_select_uni */, 6 /* lsto */, 7, 8, 9, 10, 11 /* last_tx_ack_timestamp */, + 12, 13, 14, 15 /* buffer_underflow_bytes */, std::move(payload))))); EXPECT_TRUE(view.IsValid()); vse_callback_(view); @@ -1082,35 +966,32 @@ TEST_F(BtifCoreVseWithSocketTest, debug_dump_a2dp_choppy_no_payload) { auto reading_promise = std::make_unique>(); auto reading_done = reading_promise->get_future(); - do_in_main_thread(FROM_HERE, - BindOnce([]() { bluetooth::bqr::DebugDump(write_fd); })); - do_in_main_thread( - FROM_HERE, - BindOnce( - [](std::unique_ptr> done_promise) { - char line_buf[1024] = ""; - std::string line; - int bytes_read = read(read_fd, line_buf, 1024); - EXPECT_GT(bytes_read, 0); - line = std::string(line_buf); - EXPECT_EQ(line.find("Event queue is empty"), std::string::npos); - EXPECT_NE(line.find("Handle: 0x0123"), std::string::npos); - EXPECT_NE(line.find("UndFlow: 15"), std::string::npos); - EXPECT_NE(line.find("A2DP Choppy"), std::string::npos); - done_promise->set_value(); - }, - std::move(reading_promise))); - EXPECT_EQ(std::future_status::ready, - reading_done.wait_for(std::chrono::seconds(1))); + do_in_main_thread(FROM_HERE, BindOnce([]() { bluetooth::bqr::DebugDump(write_fd); })); + do_in_main_thread(FROM_HERE, BindOnce( + [](std::unique_ptr> done_promise) { + char line_buf[1024] = ""; + std::string line; + int bytes_read = read(read_fd, line_buf, 1024); + EXPECT_GT(bytes_read, 0); + line = std::string(line_buf); + EXPECT_EQ(line.find("Event queue is empty"), + std::string::npos); + EXPECT_NE(line.find("Handle: 0x0123"), std::string::npos); + EXPECT_NE(line.find("UndFlow: 15"), std::string::npos); + EXPECT_NE(line.find("A2DP Choppy"), std::string::npos); + done_promise->set_value(); + }, + std::move(reading_promise))); + EXPECT_EQ(std::future_status::ready, reading_done.wait_for(std::chrono::seconds(1))); } TEST_F(BtifCoreVseWithSocketTest, debug_dump_a2dp_choppy) { auto payload = std::make_unique(); payload->AddOctets({'d', 'a', 't', 'a'}); auto view = VendorSpecificEventView::Create( - EventView::Create(BuilderToView(BqrA2dpAudioChoppyEventBuilder::Create( - BqrPacketType::TYPE_3DH3, 0x123, Role::CENTRAL, 1, 2, 3, 4, 5, 6, 7, - 8, 9, 10, 11, 12, 13, 14, 15, std::move(payload))))); + EventView::Create(BuilderToView(BqrA2dpAudioChoppyEventBuilder::Create( + BqrPacketType::TYPE_3DH3, 0x123, Role::CENTRAL, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, + 12, 13, 14, 15, std::move(payload))))); EXPECT_TRUE(view.IsValid()); vse_callback_(view); @@ -1119,24 +1000,21 @@ TEST_F(BtifCoreVseWithSocketTest, debug_dump_a2dp_choppy) { auto reading_promise = std::make_unique>(); auto reading_done = reading_promise->get_future(); - do_in_main_thread(FROM_HERE, - BindOnce([]() { bluetooth::bqr::DebugDump(write_fd); })); - do_in_main_thread( - FROM_HERE, - BindOnce( - [](std::unique_ptr> done_promise) { - char line_buf[1024] = ""; - std::string line; - int bytes_read = read(read_fd, line_buf, 1024); - EXPECT_GT(bytes_read, 0); - line = std::string(line_buf); - EXPECT_EQ(line.find("Event queue is empty"), std::string::npos); - EXPECT_NE(line.find("Handle: 0x0123"), std::string::npos); - EXPECT_NE(line.find("UndFlow: 15"), std::string::npos); - EXPECT_NE(line.find("A2DP Choppy"), std::string::npos); - done_promise->set_value(); - }, - std::move(reading_promise))); - EXPECT_EQ(std::future_status::ready, - reading_done.wait_for(std::chrono::seconds(1))); + do_in_main_thread(FROM_HERE, BindOnce([]() { bluetooth::bqr::DebugDump(write_fd); })); + do_in_main_thread(FROM_HERE, BindOnce( + [](std::unique_ptr> done_promise) { + char line_buf[1024] = ""; + std::string line; + int bytes_read = read(read_fd, line_buf, 1024); + EXPECT_GT(bytes_read, 0); + line = std::string(line_buf); + EXPECT_EQ(line.find("Event queue is empty"), + std::string::npos); + EXPECT_NE(line.find("Handle: 0x0123"), std::string::npos); + EXPECT_NE(line.find("UndFlow: 15"), std::string::npos); + EXPECT_NE(line.find("A2DP Choppy"), std::string::npos); + done_promise->set_value(); + }, + std::move(reading_promise))); + EXPECT_EQ(std::future_status::ready, reading_done.wait_for(std::chrono::seconds(1))); } diff --git a/system/btif/test/btif_dm_test.cc b/system/btif/test/btif_dm_test.cc index c2210650e45..9d1a3d5e696 100644 --- a/system/btif/test/btif_dm_test.cc +++ b/system/btif/test/btif_dm_test.cc @@ -45,17 +45,14 @@ namespace bluetooth { namespace legacy { namespace testing { -void set_interface_to_profiles( - bluetooth::core::CoreInterface* interfaceToProfiles); +void set_interface_to_profiles(bluetooth::core::CoreInterface* interfaceToProfiles); -void bta_energy_info_cb(tBTM_BLE_TX_TIME_MS tx_time, - tBTM_BLE_RX_TIME_MS rx_time, - tBTM_BLE_IDLE_TIME_MS idle_time, - tBTM_BLE_ENERGY_USED energy_used, +void bta_energy_info_cb(tBTM_BLE_TX_TIME_MS tx_time, tBTM_BLE_RX_TIME_MS rx_time, + tBTM_BLE_IDLE_TIME_MS idle_time, tBTM_BLE_ENERGY_USED energy_used, tBTM_CONTRL_STATE ctrl_state, tBTA_STATUS status); -void btif_on_name_read(RawAddress bd_addr, tHCI_ERROR_CODE hci_status, - const BD_NAME bd_name, bool during_device_search); +void btif_on_name_read(RawAddress bd_addr, tHCI_ERROR_CODE hci_status, const BD_NAME bd_name, + bool during_device_search); } // namespace testing } // namespace legacy @@ -69,7 +66,7 @@ constexpr tBTM_BLE_ENERGY_USED energy_used = 0x13579bdf; } // namespace class BtifDmWithMocksTest : public ::testing::Test { - protected: +protected: void SetUp() override { fake_osi_ = std::make_unique(); } void TearDown() override { fake_osi_.reset(); } @@ -78,12 +75,11 @@ class BtifDmWithMocksTest : public ::testing::Test { }; class BtifDmTest : public BtifDmWithMocksTest { - protected: +protected: void SetUp() override { BtifDmWithMocksTest::SetUp(); mock_core_interface_ = std::make_unique(); - bluetooth::legacy::testing::set_interface_to_profiles( - mock_core_interface_.get()); + bluetooth::legacy::testing::set_interface_to_profiles(mock_core_interface_.get()); } void TearDown() override { @@ -98,20 +94,18 @@ class BtifDmTest : public BtifDmWithMocksTest { TEST_F(BtifDmTest, bta_energy_info_cb__with_no_uid) { static bool invoke_energy_info_cb_entered = false; bluetooth::core::testing::mock_event_callbacks.invoke_energy_info_cb = - [](bt_activity_energy_info /* energy_info */, - bt_uid_traffic_t* /* uid_data */) { - invoke_energy_info_cb_entered = true; - }; + [](bt_activity_energy_info /* energy_info */, bt_uid_traffic_t* /* uid_data */) { + invoke_energy_info_cb_entered = true; + }; - bluetooth::legacy::testing::bta_energy_info_cb( - tx_time, rx_time, idle_time, energy_used, BTM_CONTRL_UNKNOWN, - BTA_SUCCESS); + bluetooth::legacy::testing::bta_energy_info_cb(tx_time, rx_time, idle_time, energy_used, + BTM_CONTRL_UNKNOWN, BTA_SUCCESS); ASSERT_FALSE(invoke_energy_info_cb_entered); } class BtifDmWithUidTest : public BtifDmTest { - protected: +protected: void SetUp() override { BtifDmTest::SetUp(); btif_dm_init(uid_set_create()); @@ -126,26 +120,23 @@ class BtifDmWithUidTest : public BtifDmTest { TEST_F(BtifDmWithUidTest, bta_energy_info_cb__with_uid) { static bool invoke_energy_info_cb_entered = false; bluetooth::core::testing::mock_event_callbacks.invoke_energy_info_cb = - [](bt_activity_energy_info /* energy_info */, - bt_uid_traffic_t* /* uid_data */) { - invoke_energy_info_cb_entered = true; - }; - bluetooth::legacy::testing::bta_energy_info_cb( - tx_time, rx_time, idle_time, energy_used, BTM_CONTRL_UNKNOWN, - BTA_SUCCESS); + [](bt_activity_energy_info /* energy_info */, bt_uid_traffic_t* /* uid_data */) { + invoke_energy_info_cb_entered = true; + }; + bluetooth::legacy::testing::bta_energy_info_cb(tx_time, rx_time, idle_time, energy_used, + BTM_CONTRL_UNKNOWN, BTA_SUCCESS); ASSERT_TRUE(invoke_energy_info_cb_entered); } class BtifDmWithStackTest : public BtifDmTest { - protected: +protected: void SetUp() override { BtifDmTest::SetUp(); modules_.add(); bluetooth::shim::Stack::GetInstance()->StartModuleStack( - &modules_, - new bluetooth::os::Thread("gd_stack_thread", - bluetooth::os::Thread::Priority::NORMAL)); + &modules_, + new bluetooth::os::Thread("gd_stack_thread", bluetooth::os::Thread::Priority::NORMAL)); } void TearDown() override { @@ -155,49 +146,42 @@ class BtifDmWithStackTest : public BtifDmTest { bluetooth::ModuleList modules_; }; -TEST_F_WITH_FLAGS(BtifDmWithStackTest, - btif_dm_search_services_evt__BTA_DM_NAME_READ_EVT) { +TEST_F_WITH_FLAGS(BtifDmWithStackTest, btif_dm_search_services_evt__BTA_DM_NAME_READ_EVT) { static struct { bt_status_t status; RawAddress bd_addr; int num_properties; std::vector properties; } invoke_remote_device_properties_cb{ - .status = BT_STATUS_NOT_READY, - .bd_addr = RawAddress::kEmpty, - .num_properties = -1, - .properties = {}, + .status = BT_STATUS_NOT_READY, + .bd_addr = RawAddress::kEmpty, + .num_properties = -1, + .properties = {}, }; - bluetooth::core::testing::mock_event_callbacks - .invoke_remote_device_properties_cb = - [](bt_status_t status, RawAddress bd_addr, int num_properties, - bt_property_t* properties) { - invoke_remote_device_properties_cb = { - .status = status, - .bd_addr = bd_addr, - .num_properties = num_properties, - .properties = std::vector( - properties, properties + (size_t)num_properties), - }; - }; + bluetooth::core::testing::mock_event_callbacks.invoke_remote_device_properties_cb = + [](bt_status_t status, RawAddress bd_addr, int num_properties, + bt_property_t* properties) { + invoke_remote_device_properties_cb = { + .status = status, + .bd_addr = bd_addr, + .num_properties = num_properties, + .properties = std::vector(properties, + properties + (size_t)num_properties), + }; + }; BD_NAME bd_name; bd_name_from_char_pointer(bd_name, kBdName); - bluetooth::legacy::testing::btif_on_name_read(kRawAddress, HCI_SUCCESS, - bd_name, true); + bluetooth::legacy::testing::btif_on_name_read(kRawAddress, HCI_SUCCESS, bd_name, true); ASSERT_EQ(BT_STATUS_SUCCESS, invoke_remote_device_properties_cb.status); ASSERT_EQ(kRawAddress, invoke_remote_device_properties_cb.bd_addr); ASSERT_EQ(1, invoke_remote_device_properties_cb.num_properties); - ASSERT_EQ(BT_PROPERTY_BDNAME, - invoke_remote_device_properties_cb.properties[0].type); - ASSERT_EQ((int)strlen(kBdName), - invoke_remote_device_properties_cb.properties[0].len); - ASSERT_STREQ( - kBdName, - (const char*)invoke_remote_device_properties_cb.properties[0].val); + ASSERT_EQ(BT_PROPERTY_BDNAME, invoke_remote_device_properties_cb.properties[0].type); + ASSERT_EQ((int)strlen(kBdName), invoke_remote_device_properties_cb.properties[0].len); + ASSERT_STREQ(kBdName, (const char*)invoke_remote_device_properties_cb.properties[0].val); } TEST_F(BtifDmWithStackTest, btif_dm_get_local_class_of_device__default) { @@ -208,11 +192,11 @@ TEST_F(BtifDmWithStackTest, btif_dm_get_local_class_of_device__default) { std::string kClassOfDeviceText = "1,2,3"; DEV_CLASS kClassOfDevice = {1, 2, 3}; TEST_F(BtifDmWithStackTest, btif_dm_get_local_class_of_device__with_property) { - test::mock::osi_properties::osi_property_get.body = - [](const char* /* key */, char* value, const char* /* default_value */) { - std::copy(kClassOfDeviceText.begin(), kClassOfDeviceText.end(), value); - return kClassOfDeviceText.size(); - }; + test::mock::osi_properties::osi_property_get.body = [](const char* /* key */, char* value, + const char* /* default_value */) { + std::copy(kClassOfDeviceText.begin(), kClassOfDeviceText.end(), value); + return kClassOfDeviceText.size(); + }; DEV_CLASS dev_class = btif_dm_get_local_class_of_device(); if (dev_class != kClassOfDevice) { diff --git a/system/btif/test/btif_hf_client_service_test.cc b/system/btif/test/btif_hf_client_service_test.cc index 76cb1c403ff..cfba41ff874 100644 --- a/system/btif/test/btif_hf_client_service_test.cc +++ b/system/btif/test/btif_hf_client_service_test.cc @@ -13,32 +13,30 @@ int get_default_hfp_version() { } int get_default_hf_client_features() { -#define DEFAULT_BTIF_HF_CLIENT_FEATURES \ - (BTA_HF_CLIENT_FEAT_ECNR | BTA_HF_CLIENT_FEAT_3WAY | \ - BTA_HF_CLIENT_FEAT_CLI | BTA_HF_CLIENT_FEAT_VREC | BTA_HF_CLIENT_FEAT_VOL | \ - BTA_HF_CLIENT_FEAT_ECS | BTA_HF_CLIENT_FEAT_ECC | BTA_HF_CLIENT_FEAT_CODEC) +#define DEFAULT_BTIF_HF_CLIENT_FEATURES \ + (BTA_HF_CLIENT_FEAT_ECNR | BTA_HF_CLIENT_FEAT_3WAY | BTA_HF_CLIENT_FEAT_CLI | \ + BTA_HF_CLIENT_FEAT_VREC | BTA_HF_CLIENT_FEAT_VOL | BTA_HF_CLIENT_FEAT_ECS | \ + BTA_HF_CLIENT_FEAT_ECC | BTA_HF_CLIENT_FEAT_CODEC) return android::sysprop::bluetooth::Hfp::hf_client_features().value_or( DEFAULT_BTIF_HF_CLIENT_FEATURES); } -tBTA_STATUS BTA_HfClientEnable(tBTA_HF_CLIENT_CBACK* p_cback, - tBTA_HF_CLIENT_FEAT features, +tBTA_STATUS BTA_HfClientEnable(tBTA_HF_CLIENT_CBACK* p_cback, tBTA_HF_CLIENT_FEAT features, const char* p_service_name) { gFeatures = features; return BTA_SUCCESS; } -void BTA_HfClientDisable(void) { } -bt_status_t btif_transfer_context(tBTIF_CBACK* p_cback, uint16_t event, - char* p_params, int param_len, - tBTIF_COPY_CBACK* p_copy_cback) { +void BTA_HfClientDisable(void) {} +bt_status_t btif_transfer_context(tBTIF_CBACK* p_cback, uint16_t event, char* p_params, + int param_len, tBTIF_COPY_CBACK* p_copy_cback) { return BT_STATUS_SUCCESS; } void btif_queue_advance() {} std::string dump_hf_client_event(uint16_t event) { return "UNKNOWN MSG ID"; } class BtifHfClientTest : public ::testing::Test { - protected: +protected: void SetUp() override { gFeatures = get_default_hf_client_features(); } void TearDown() override {} @@ -51,6 +49,5 @@ TEST_F(BtifHfClientTest, test_btif_hf_cleint_service) { ASSERT_EQ((gFeatures & BTA_HF_CLIENT_FEAT_ESCO_S4) > 0, get_default_hfp_version() >= HFP_VERSION_1_7); - ASSERT_EQ((gFeatures & BTA_HF_CLIENT_FEAT_SWB) > 0, - get_default_hfp_version() >= HFP_VERSION_1_9); + ASSERT_EQ((gFeatures & BTA_HF_CLIENT_FEAT_SWB) > 0, get_default_hfp_version() >= HFP_VERSION_1_9); } diff --git a/system/btif/test/btif_hh_test.cc b/system/btif/test/btif_hh_test.cc index f22726f449e..92b88d72ed4 100644 --- a/system/btif/test/btif_hh_test.cc +++ b/system/btif/test/btif_hh_test.cc @@ -68,9 +68,9 @@ extern bool bluetooth_shim_is_gd_stack_started_up; namespace { std::array data32 = { - 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, - 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, - 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, + 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, + 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, + 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, }; const RawAddress kDeviceAddress({0x11, 0x22, 0x33, 0x44, 0x55, 0x66}); @@ -102,58 +102,55 @@ std::promise g_bthh_connection_state_promise; } // namespace bt_callbacks_t bt_callbacks = { - .size = sizeof(bt_callbacks_t), - .adapter_state_changed_cb = nullptr, // adapter_state_changed_callback - .adapter_properties_cb = nullptr, // adapter_properties_callback - .remote_device_properties_cb = - nullptr, // remote_device_properties_callback - .device_found_cb = nullptr, // device_found_callback - .discovery_state_changed_cb = nullptr, // discovery_state_changed_callback - .pin_request_cb = nullptr, // pin_request_callback - .ssp_request_cb = nullptr, // ssp_request_callback - .bond_state_changed_cb = nullptr, // bond_state_changed_callback - .address_consolidate_cb = nullptr, // address_consolidate_callback - .le_address_associate_cb = nullptr, // le_address_associate_callback - .acl_state_changed_cb = nullptr, // acl_state_changed_callback - .thread_evt_cb = nullptr, // callback_thread_event - .dut_mode_recv_cb = nullptr, // dut_mode_recv_callback - .le_test_mode_cb = nullptr, // le_test_mode_callback - .energy_info_cb = nullptr, // energy_info_callback - .link_quality_report_cb = nullptr, // link_quality_report_callback - .generate_local_oob_data_cb = nullptr, // generate_local_oob_data_callback - .switch_buffer_size_cb = nullptr, // switch_buffer_size_callback - .switch_codec_cb = nullptr, // switch_codec_callback - .le_rand_cb = nullptr, // le_rand_callback + .size = sizeof(bt_callbacks_t), + .adapter_state_changed_cb = nullptr, // adapter_state_changed_callback + .adapter_properties_cb = nullptr, // adapter_properties_callback + .remote_device_properties_cb = nullptr, // remote_device_properties_callback + .device_found_cb = nullptr, // device_found_callback + .discovery_state_changed_cb = nullptr, // discovery_state_changed_callback + .pin_request_cb = nullptr, // pin_request_callback + .ssp_request_cb = nullptr, // ssp_request_callback + .bond_state_changed_cb = nullptr, // bond_state_changed_callback + .address_consolidate_cb = nullptr, // address_consolidate_callback + .le_address_associate_cb = nullptr, // le_address_associate_callback + .acl_state_changed_cb = nullptr, // acl_state_changed_callback + .thread_evt_cb = nullptr, // callback_thread_event + .dut_mode_recv_cb = nullptr, // dut_mode_recv_callback + .le_test_mode_cb = nullptr, // le_test_mode_callback + .energy_info_cb = nullptr, // energy_info_callback + .link_quality_report_cb = nullptr, // link_quality_report_callback + .generate_local_oob_data_cb = nullptr, // generate_local_oob_data_callback + .switch_buffer_size_cb = nullptr, // switch_buffer_size_callback + .switch_codec_cb = nullptr, // switch_codec_callback + .le_rand_cb = nullptr, // le_rand_callback }; bthh_callbacks_t bthh_callbacks = { - .size = sizeof(bthh_callbacks_t), - .connection_state_cb = nullptr, // bthh_connection_state_callback - .hid_info_cb = nullptr, // bthh_hid_info_callback - .protocol_mode_cb = nullptr, // bthh_protocol_mode_callback - .idle_time_cb = nullptr, // bthh_idle_time_callback - .get_report_cb = nullptr, // bthh_get_report_callback - .virtual_unplug_cb = nullptr, // bthh_virtual_unplug_callback - .handshake_cb = nullptr, // bthh_handshake_callback + .size = sizeof(bthh_callbacks_t), + .connection_state_cb = nullptr, // bthh_connection_state_callback + .hid_info_cb = nullptr, // bthh_hid_info_callback + .protocol_mode_cb = nullptr, // bthh_protocol_mode_callback + .idle_time_cb = nullptr, // bthh_idle_time_callback + .get_report_cb = nullptr, // bthh_get_report_callback + .virtual_unplug_cb = nullptr, // bthh_virtual_unplug_callback + .handshake_cb = nullptr, // bthh_handshake_callback }; class BtifHhWithMockTest : public ::testing::Test { - protected: +protected: void SetUp() override { reset_mock_function_count_map(); } void TearDown() override {} }; class BtifHhWithHalCallbacksTest : public BtifHhWithMockTest { - protected: +protected: void SetUp() override { BtifHhWithMockTest::SetUp(); bluetooth::common::InitFlags::SetAllForTesting(); g_thread_evt_promise = std::promise(); auto future = g_thread_evt_promise.get_future(); - bt_callbacks.thread_evt_cb = [](bt_cb_thread_evt evt) { - g_thread_evt_promise.set_value(evt); - }; + bt_callbacks.thread_evt_cb = [](bt_cb_thread_evt evt) { g_thread_evt_promise.set_value(evt); }; bluetooth::testing::set_hal_cbacks(&bt_callbacks); // Start the jni callback thread InitializeCoreInterface(); @@ -166,9 +163,7 @@ class BtifHhWithHalCallbacksTest : public BtifHhWithMockTest { void TearDown() override { g_thread_evt_promise = std::promise(); auto future = g_thread_evt_promise.get_future(); - bt_callbacks.thread_evt_cb = [](bt_cb_thread_evt evt) { - g_thread_evt_promise.set_value(evt); - }; + bt_callbacks.thread_evt_cb = [](bt_cb_thread_evt evt) { g_thread_evt_promise.set_value(evt); }; CleanCoreInterface(); ASSERT_EQ(std::future_status::ready, future.wait_for(2s)); ASSERT_EQ(DISASSOCIATE_JVM, future.get()); @@ -179,12 +174,11 @@ class BtifHhWithHalCallbacksTest : public BtifHhWithMockTest { }; class BtifHhAdapterReady : public BtifHhWithHalCallbacksTest { - protected: +protected: void SetUp() override { BtifHhWithHalCallbacksTest::SetUp(); test::mock::bluetooth_shim_is_gd_stack_started_up = true; - ASSERT_EQ(BT_STATUS_SUCCESS, - btif_hh_get_interface()->init(&bthh_callbacks)); + ASSERT_EQ(BT_STATUS_SUCCESS, btif_hh_get_interface()->init(&bthh_callbacks)); } void TearDown() override { @@ -194,7 +188,7 @@ class BtifHhAdapterReady : public BtifHhWithHalCallbacksTest { }; class BtifHhWithDevice : public BtifHhAdapterReady { - protected: +protected: void SetUp() override { BtifHhAdapterReady::SetUp(); @@ -215,36 +209,34 @@ static uint8_t report_data[sizeof(BT_HDR) + data32.size()]; TEST_F(BtifHhWithDevice, BTA_HH_GET_RPT_EVT) { tBTA_HH data = { - .hs_data = - { - .status = BTA_HH_OK, - .handle = kHhHandle, - .rsp_data = + .hs_data = { - .p_rpt_data = reinterpret_cast(report_data), + .status = BTA_HH_OK, + .handle = kHhHandle, + .rsp_data = + { + .p_rpt_data = reinterpret_cast(report_data), + }, }, - }, }; // Fill out the deep copy data data.hs_data.rsp_data.p_rpt_data->len = static_cast(data32.size()); std::copy(data32.begin(), data32.begin() + data32.size(), - reinterpret_cast((data.hs_data.rsp_data.p_rpt_data + 1))); + reinterpret_cast(data.hs_data.rsp_data.p_rpt_data + 1)); g_bthh_callbacks_get_report_promise = std::promise(); auto future = g_bthh_callbacks_get_report_promise.get_future(); - bthh_callbacks.get_report_cb = [](RawAddress* bd_addr, - tBLE_ADDR_TYPE /* addr_type */, - tBT_TRANSPORT /* transport */, - bthh_status_t hh_status, uint8_t* rpt_data, - int rpt_size) { + bthh_callbacks.get_report_cb = [](RawAddress* bd_addr, tBLE_ADDR_TYPE /* addr_type */, + tBT_TRANSPORT /* transport */, bthh_status_t hh_status, + uint8_t* rpt_data, int rpt_size) { get_report_cb_t report = { - .raw_address = *bd_addr, - .status = hh_status, - .data = std::vector(), + .raw_address = *bd_addr, + .status = hh_status, + .data = std::vector(), }; report.data.assign(rpt_data, rpt_data + rpt_size), - g_bthh_callbacks_get_report_promise.set_value(report); + g_bthh_callbacks_get_report_promise.set_value(report); }; bluetooth::legacy::testing::bte_hh_evt(BTA_HH_GET_RPT_EVT, &data); @@ -253,8 +245,7 @@ TEST_F(BtifHhWithDevice, BTA_HH_GET_RPT_EVT) { auto report = future.get(); // Verify data was delivered - ASSERT_STREQ(kDeviceAddress.ToString().c_str(), - report.raw_address.ToString().c_str()); + ASSERT_STREQ(kDeviceAddress.ToString().c_str(), report.raw_address.ToString().c_str()); ASSERT_EQ(BTHH_OK, report.status); int i = 0; for (const auto& data : data32) { @@ -263,16 +254,15 @@ TEST_F(BtifHhWithDevice, BTA_HH_GET_RPT_EVT) { } class BtifHHVirtualUnplugTest : public BtifHhAdapterReady { - protected: +protected: void SetUp() override { BtifHhAdapterReady::SetUp(); - bthh_callbacks.connection_state_cb = [](RawAddress* bd_addr, - tBLE_ADDR_TYPE /* addr_type */, + bthh_callbacks.connection_state_cb = [](RawAddress* bd_addr, tBLE_ADDR_TYPE /* addr_type */, tBT_TRANSPORT /* transport */, bthh_connection_state_t state) { connection_state_cb_t connection_state = { - .raw_address = *bd_addr, - .state = state, + .raw_address = *bd_addr, + .state = state, }; g_bthh_connection_state_promise.set_value(connection_state); }; @@ -280,9 +270,8 @@ class BtifHHVirtualUnplugTest : public BtifHhAdapterReady { void TearDown() override { bthh_callbacks.connection_state_cb = - [](RawAddress* /* bd_addr */, tBLE_ADDR_TYPE /* addr_type */, - tBT_TRANSPORT /* transport */, - bthh_connection_state_t /* state */) {}; + [](RawAddress* /* bd_addr */, tBLE_ADDR_TYPE /* addr_type */, + tBT_TRANSPORT /* transport */, bthh_connection_state_t /* state */) {}; BtifHhAdapterReady::TearDown(); } }; @@ -298,11 +287,9 @@ TEST_F(BtifHHVirtualUnplugTest, test_btif_hh_virtual_unplug_device_not_open) { ASSERT_EQ(std::future_status::ready, future.wait_for(2s)); auto res = future.get(); - ASSERT_STREQ(kDeviceAddressConnecting.ToString().c_str(), - res.raw_address.ToString().c_str()); + ASSERT_STREQ(kDeviceAddressConnecting.ToString().c_str(), res.raw_address.ToString().c_str()); ASSERT_EQ(BTHH_CONN_STATE_CONNECTING, res.state); - g_bthh_connection_state_promise = std::promise(); future = g_bthh_connection_state_promise.get_future(); btif_hh_virtual_unplug(kDeviceConnecting); @@ -311,7 +298,6 @@ TEST_F(BtifHHVirtualUnplugTest, test_btif_hh_virtual_unplug_device_not_open) { // Verify data was delivered res = future.get(); - ASSERT_STREQ(kDeviceAddressConnecting.ToString().c_str(), - res.raw_address.ToString().c_str()); + ASSERT_STREQ(kDeviceAddressConnecting.ToString().c_str(), res.raw_address.ToString().c_str()); ASSERT_EQ(BTHH_CONN_STATE_DISCONNECTED, res.state); } diff --git a/system/btif/test/btif_keystore_test.cc b/system/btif/test/btif_keystore_test.cc index 0f525a38055..0137e6fe3f3 100644 --- a/system/btif/test/btif_keystore_test.cc +++ b/system/btif/test/btif_keystore_test.cc @@ -16,24 +16,24 @@ * ******************************************************************************/ +#include "btif/include/btif_keystore.h" + #include #include -#include -#include "btif/include/btif_keystore.h" +#include using namespace bluetooth; class BtifKeystoreTest : public ::testing::Test { - protected: +protected: std::unique_ptr btif_keystore_; void SetUp() override { android::ProcessState::self()->startThreadPool(); - btif_keystore_ = - std::make_unique(static_cast( - new keystore::KeystoreClientImpl)); - }; - void TearDown() override { btif_keystore_ = nullptr; }; + btif_keystore_ = std::make_unique( + static_cast(new keystore::KeystoreClientImpl)); + } + void TearDown() override { btif_keystore_ = nullptr; } }; TEST_F(BtifKeystoreTest, test_encrypt_decrypt) { diff --git a/system/btif/test/btif_profile_queue_test.cc b/system/btif/test/btif_profile_queue_test.cc index abdddb58f7d..d39164b36b6 100644 --- a/system/btif/test/btif_profile_queue_test.cc +++ b/system/btif/test/btif_profile_queue_test.cc @@ -32,8 +32,8 @@ typedef void(tBTIF_COPY_CBACK)(uint16_t event, char* p_dest, const char* p_src); // NOTE: Local re-implementation of functions to avoid thread context switching static bool sStackRunning; bool get_stack_is_running(void) { return sStackRunning; } -static stack_manager_t sStackManager = {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, - get_stack_is_running}; +static stack_manager_t sStackManager = { + nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, get_stack_is_running}; const stack_manager_t* stack_manager_get_interface() { return &sStackManager; } bt_status_t do_in_jni_thread(base::OnceClosure task) { std::move(task).Run(); @@ -41,36 +41,27 @@ bt_status_t do_in_jni_thread(base::OnceClosure task) { } bool is_on_jni_thread() { return true; } -enum ResultType { - NOT_SET = 0, - UNKNOWN, - UUID1_ADDR1, - UUID1_ADDR2, - UUID2_ADDR1, - UUID2_ADDR2 -}; +enum ResultType { NOT_SET = 0, UNKNOWN, UUID1_ADDR1, UUID1_ADDR2, UUID2_ADDR1, UUID2_ADDR2 }; static ResultType sResult; class BtifProfileQueueTest : public ::testing::Test { - public: +public: static const uint16_t kTestUuid1 = 0x9527; static const uint16_t kTestUuid2 = 0x819F; static const RawAddress kTestAddr1; static const RawAddress kTestAddr2; - protected: +protected: void SetUp() override { sStackRunning = true; sResult = NOT_SET; - }; - void TearDown() override { btif_queue_release(); }; + } + void TearDown() override { btif_queue_release(); } }; -const RawAddress BtifProfileQueueTest::kTestAddr1{ - {0x11, 0x22, 0x33, 0x44, 0x55, 0x66}}; -const RawAddress BtifProfileQueueTest::kTestAddr2{ - {0xAB, 0xCD, 0xEF, 0x12, 0x34, 0x56}}; +const RawAddress BtifProfileQueueTest::kTestAddr1{{0x11, 0x22, 0x33, 0x44, 0x55, 0x66}}; +const RawAddress BtifProfileQueueTest::kTestAddr2{{0xAB, 0xCD, 0xEF, 0x12, 0x34, 0x56}}; static bt_status_t test_connect_cb(RawAddress* bda, uint16_t uuid) { sResult = UNKNOWN; diff --git a/system/btif/test/btif_rc_test.cc b/system/btif/test/btif_rc_test.cc index b25b92805a6..bcd03e6851f 100644 --- a/system/btif/test/btif_rc_test.cc +++ b/system/btif/test/btif_rc_test.cc @@ -40,29 +40,21 @@ namespace avrcp { int VolChanged = 0; AvrcpService* AvrcpService::instance_ = nullptr; -void AvrcpService::SendMediaUpdate(bool track_changed, bool play_state, - bool queue){}; -void AvrcpService::SendFolderUpdate(bool available_players, - bool addressed_players, bool uids){}; -void AvrcpService::SendActiveDeviceChanged(const RawAddress& address){}; -void AvrcpService::SendPlayerSettingsChanged( - std::vector attributes, std::vector values){}; -void AvrcpService::ServiceInterfaceImpl::Init( - MediaInterface* media_interface, VolumeInterface* volume_interface, - PlayerSettingsInterface* player_settings_interface){}; -void AvrcpService::ServiceInterfaceImpl::RegisterBipServer(int psm){}; -void AvrcpService::ServiceInterfaceImpl::UnregisterBipServer(){}; -bool AvrcpService::ServiceInterfaceImpl::ConnectDevice( - const RawAddress& bdaddr) { - return true; -}; -bool AvrcpService::ServiceInterfaceImpl::DisconnectDevice( - const RawAddress& bdaddr) { - return true; -}; -void AvrcpService::ServiceInterfaceImpl::SetBipClientStatus( - const RawAddress& bdaddr, bool connected){}; -bool AvrcpService::ServiceInterfaceImpl::Cleanup() { return true; }; +void AvrcpService::SendMediaUpdate(bool track_changed, bool play_state, bool queue) {} +void AvrcpService::SendFolderUpdate(bool available_players, bool addressed_players, bool uids) {} +void AvrcpService::SendActiveDeviceChanged(const RawAddress& address) {} +void AvrcpService::SendPlayerSettingsChanged(std::vector attributes, + std::vector values) {} +void AvrcpService::ServiceInterfaceImpl::Init(MediaInterface* media_interface, + VolumeInterface* volume_interface, + PlayerSettingsInterface* player_settings_interface) {} +void AvrcpService::ServiceInterfaceImpl::RegisterBipServer(int psm) {} +void AvrcpService::ServiceInterfaceImpl::UnregisterBipServer() {} +bool AvrcpService::ServiceInterfaceImpl::ConnectDevice(const RawAddress& bdaddr) { return true; } +bool AvrcpService::ServiceInterfaceImpl::DisconnectDevice(const RawAddress& bdaddr) { return true; } +void AvrcpService::ServiceInterfaceImpl::SetBipClientStatus(const RawAddress& bdaddr, + bool connected) {} +bool AvrcpService::ServiceInterfaceImpl::Cleanup() { return true; } AvrcpService* AvrcpService::Get() { EXPECT_EQ(instance_, nullptr); @@ -70,9 +62,7 @@ AvrcpService* AvrcpService::Get() { return instance_; } -void AvrcpService::RegisterVolChanged(const RawAddress& bdaddr) { - VolChanged++; -} +void AvrcpService::RegisterVolChanged(const RawAddress& bdaddr) { VolChanged++; } } // namespace avrcp } // namespace bluetooth @@ -86,25 +76,17 @@ bool btif_av_is_connected(const A2dpType local_a2dp_type) { return true; } bool btif_av_is_sink_enabled(void) { return true; } RawAddress btif_av_sink_active_peer(void) { return RawAddress(); } RawAddress btif_av_source_active_peer(void) { return RawAddress(); } -bool btif_av_stream_started_ready(const A2dpType local_a2dp_type) { - return false; -} -bt_status_t btif_transfer_context(tBTIF_CBACK* p_cback, uint16_t event, - char* p_params, int param_len, - tBTIF_COPY_CBACK* p_copy_cback) { +bool btif_av_stream_started_ready(const A2dpType local_a2dp_type) { return false; } +bt_status_t btif_transfer_context(tBTIF_CBACK* p_cback, uint16_t event, char* p_params, + int param_len, tBTIF_COPY_CBACK* p_copy_cback) { return BT_STATUS_SUCCESS; } bool btif_av_src_sink_coexist_enabled() { return true; } -bool btif_av_is_connected_addr(const RawAddress& peer_address, - const A2dpType local_a2dp_type) { - return true; -} -bool btif_av_peer_is_connected_sink(const RawAddress& peer_address) { - return false; -} -bool btif_av_peer_is_connected_source(const RawAddress& peer_address) { +bool btif_av_is_connected_addr(const RawAddress& peer_address, const A2dpType local_a2dp_type) { return true; } +bool btif_av_peer_is_connected_sink(const RawAddress& peer_address) { return false; } +bool btif_av_peer_is_connected_source(const RawAddress& peer_address) { return true; } bool btif_av_peer_is_sink(const RawAddress& peer_address) { return false; } bool btif_av_peer_is_source(const RawAddress& peer_address) { return true; } bool btif_av_both_enable(void) { return true; } @@ -118,16 +100,13 @@ bt_status_t do_in_jni_thread(base::OnceClosure task) { return BT_STATUS_SUCCESS; } bluetooth::common::MessageLoopThread* get_main_thread() { return nullptr; } -bool interop_match_addr(const interop_feature_t feature, - const RawAddress* addr) { - return false; -} +bool interop_match_addr(const interop_feature_t feature, const RawAddress* addr) { return false; } /** * Test class to test selected functionality in hci/src/hci_layer.cc */ class BtifRcTest : public ::testing::Test { - protected: +protected: void SetUp() override { reset_mock_function_count_map(); } void TearDown() override {} }; @@ -135,16 +114,13 @@ class BtifRcTest : public ::testing::Test { TEST_F(BtifRcTest, get_element_attr_rsp) { btif_rc_cb.rc_multi_cb[0].rc_addr = kDeviceAddress; btif_rc_cb.rc_multi_cb[0].rc_connected = true; - btif_rc_cb.rc_multi_cb[0] - .rc_pdu_info[IDX_GET_ELEMENT_ATTR_RSP] - .is_rsp_pending = true; + btif_rc_cb.rc_multi_cb[0].rc_pdu_info[IDX_GET_ELEMENT_ATTR_RSP].is_rsp_pending = true; btif_rc_cb.rc_multi_cb[0].rc_state = BTRC_CONNECTION_STATE_CONNECTED; btrc_element_attr_val_t p_attrs[BTRC_MAX_ELEM_ATTR_SIZE]; uint8_t num_attr = BTRC_MAX_ELEM_ATTR_SIZE + 1; - ASSERT_EQ(get_element_attr_rsp(kDeviceAddress, num_attr, p_attrs), - BT_STATUS_SUCCESS); + ASSERT_EQ(get_element_attr_rsp(kDeviceAddress, num_attr, p_attrs), BT_STATUS_SUCCESS); ASSERT_EQ(1, get_func_call_count("AVRC_BldResponse")); } @@ -160,56 +136,48 @@ TEST_F(BtifRcTest, btif_rc_get_addr_by_handle) { } static btrc_ctrl_callbacks_t default_btrc_ctrl_callbacks = { - .size = sizeof(btrc_ctrl_callbacks_t), - .passthrough_rsp_cb = [](const RawAddress& /* bd_addr */, int /* id */, - int /* key_state */) { FAIL(); }, - .groupnavigation_rsp_cb = [](int /* id */, int /* key_state */) { FAIL(); }, - .connection_state_cb = [](bool /* rc_connect */, bool /* bt_connect */, - const RawAddress& /* bd_addr */) { FAIL(); }, - .getrcfeatures_cb = [](const RawAddress& /* bd_addr */, - int /* features */) { FAIL(); }, - .setplayerappsetting_rsp_cb = [](const RawAddress& /* bd_addr */, - uint8_t /* accepted */) { FAIL(); }, - .playerapplicationsetting_cb = - [](const RawAddress& /* bd_addr */, uint8_t /* num_attr */, - btrc_player_app_attr_t* /* app_attrs */, uint8_t /* num_ext_attr */, - btrc_player_app_ext_attr_t* /* ext_attrs */) { FAIL(); }, - .playerapplicationsetting_changed_cb = - [](const RawAddress& /* bd_addr */, - const btrc_player_settings_t& /* vals */) { FAIL(); }, - .setabsvol_cmd_cb = [](const RawAddress& /* bd_addr */, - uint8_t /* abs_vol */, - uint8_t /* label */) { FAIL(); }, - .registernotification_absvol_cb = [](const RawAddress& /* bd_addr */, - uint8_t /* label */) { FAIL(); }, - .track_changed_cb = [](const RawAddress& /* bd_addr */, - uint8_t /* num_attr */, - btrc_element_attr_val_t* /* p_attrs */) { FAIL(); }, - .play_position_changed_cb = [](const RawAddress& /* bd_addr */, - uint32_t /* song_len */, - uint32_t /* song_pos */) { FAIL(); }, - .play_status_changed_cb = - [](const RawAddress& /* bd_addr */, - btrc_play_status_t /* play_status */) { FAIL(); }, - .get_folder_items_cb = [](const RawAddress& /* bd_addr */, - btrc_status_t /* status */, - const btrc_folder_items_t* /* folder_items */, - uint8_t /* count */) { FAIL(); }, - .change_folder_path_cb = [](const RawAddress& /* bd_addr */, - uint32_t /* count */) { FAIL(); }, - .set_browsed_player_cb = [](const RawAddress& /* bd_addr */, - uint8_t /* num_items */, - uint8_t /* depth */) { FAIL(); }, - .set_addressed_player_cb = [](const RawAddress& /* bd_addr */, - uint8_t /* status */) { FAIL(); }, - .addressed_player_changed_cb = [](const RawAddress& /* bd_addr */, - uint16_t /* id */) { FAIL(); }, - .now_playing_contents_changed_cb = - [](const RawAddress& /* bd_addr */) { FAIL(); }, - .available_player_changed_cb = - [](const RawAddress& /* bd_addr */) { FAIL(); }, - .get_cover_art_psm_cb = [](const RawAddress& /* bd_addr */, - const uint16_t /* psm */) { FAIL(); }, + .size = sizeof(btrc_ctrl_callbacks_t), + .passthrough_rsp_cb = [](const RawAddress& /* bd_addr */, int /* id */, + int /* key_state */) { FAIL(); }, + .groupnavigation_rsp_cb = [](int /* id */, int /* key_state */) { FAIL(); }, + .connection_state_cb = [](bool /* rc_connect */, bool /* bt_connect */, + const RawAddress& /* bd_addr */) { FAIL(); }, + .getrcfeatures_cb = [](const RawAddress& /* bd_addr */, int /* features */) { FAIL(); }, + .setplayerappsetting_rsp_cb = [](const RawAddress& /* bd_addr */, + uint8_t /* accepted */) { FAIL(); }, + .playerapplicationsetting_cb = [](const RawAddress& /* bd_addr */, uint8_t /* num_attr */, + btrc_player_app_attr_t* /* app_attrs */, + uint8_t /* num_ext_attr */, + btrc_player_app_ext_attr_t* /* ext_attrs */) { FAIL(); }, + .playerapplicationsetting_changed_cb = + [](const RawAddress& /* bd_addr */, const btrc_player_settings_t& /* vals */) { + FAIL(); + }, + .setabsvol_cmd_cb = [](const RawAddress& /* bd_addr */, uint8_t /* abs_vol */, + uint8_t /* label */) { FAIL(); }, + .registernotification_absvol_cb = [](const RawAddress& /* bd_addr */, + uint8_t /* label */) { FAIL(); }, + .track_changed_cb = [](const RawAddress& /* bd_addr */, uint8_t /* num_attr */, + btrc_element_attr_val_t* /* p_attrs */) { FAIL(); }, + .play_position_changed_cb = [](const RawAddress& /* bd_addr */, uint32_t /* song_len */, + uint32_t /* song_pos */) { FAIL(); }, + .play_status_changed_cb = [](const RawAddress& /* bd_addr */, + btrc_play_status_t /* play_status */) { FAIL(); }, + .get_folder_items_cb = [](const RawAddress& /* bd_addr */, btrc_status_t /* status */, + const btrc_folder_items_t* /* folder_items */, + uint8_t /* count */) { FAIL(); }, + .change_folder_path_cb = [](const RawAddress& /* bd_addr */, + uint32_t /* count */) { FAIL(); }, + .set_browsed_player_cb = [](const RawAddress& /* bd_addr */, uint8_t /* num_items */, + uint8_t /* depth */) { FAIL(); }, + .set_addressed_player_cb = [](const RawAddress& /* bd_addr */, + uint8_t /* status */) { FAIL(); }, + .addressed_player_changed_cb = [](const RawAddress& /* bd_addr */, + uint16_t /* id */) { FAIL(); }, + .now_playing_contents_changed_cb = [](const RawAddress& /* bd_addr */) { FAIL(); }, + .available_player_changed_cb = [](const RawAddress& /* bd_addr */) { FAIL(); }, + .get_cover_art_psm_cb = [](const RawAddress& /* bd_addr */, + const uint16_t /* psm */) { FAIL(); }, }; static btrc_ctrl_callbacks_t btrc_ctrl_callbacks = default_btrc_ctrl_callbacks; @@ -228,17 +196,16 @@ static std::promise g_btrc_connection_state_promise; static std::promise g_btrc_feature; class BtifRcWithCallbacksTest : public BtifRcTest { - protected: +protected: void SetUp() override { BtifRcTest::SetUp(); btrc_ctrl_callbacks = default_btrc_ctrl_callbacks; init_ctrl(&btrc_ctrl_callbacks); jni_thread.StartUp(); - btrc_ctrl_callbacks.getrcfeatures_cb = [](const RawAddress& bd_addr, - int features) { + btrc_ctrl_callbacks.getrcfeatures_cb = [](const RawAddress& bd_addr, int features) { rc_feature_cb_t rc_feature = { - .feature = features, - .raw_address = bd_addr, + .feature = features, + .raw_address = bd_addr, }; g_btrc_feature.set_value(rc_feature); }; @@ -246,8 +213,7 @@ class BtifRcWithCallbacksTest : public BtifRcTest { void TearDown() override { jni_thread.ShutDown(); - bt_rc_ctrl_callbacks->getrcfeatures_cb = [](const RawAddress& bd_addr, - int features) {}; + bt_rc_ctrl_callbacks->getrcfeatures_cb = [](const RawAddress& bd_addr, int features) {}; btrc_ctrl_callbacks = default_btrc_ctrl_callbacks; BtifRcTest::TearDown(); } @@ -259,24 +225,22 @@ TEST_F(BtifRcWithCallbacksTest, handle_rc_ctrl_features) { btif_rc_device_cb_t p_dev; p_dev.peer_tg_features = - (BTA_AV_FEAT_RCTG | BTA_AV_FEAT_ADV_CTRL | BTA_AV_FEAT_RCCT | - BTA_AV_FEAT_METADATA | BTA_AV_FEAT_VENDOR | BTA_AV_FEAT_BROWSE | - BTA_AV_FEAT_COVER_ARTWORK); + (BTA_AV_FEAT_RCTG | BTA_AV_FEAT_ADV_CTRL | BTA_AV_FEAT_RCCT | BTA_AV_FEAT_METADATA | + BTA_AV_FEAT_VENDOR | BTA_AV_FEAT_BROWSE | BTA_AV_FEAT_COVER_ARTWORK); p_dev.rc_connected = true; handle_rc_ctrl_features(&p_dev); ASSERT_EQ(1, get_func_call_count("AVRC_BldCommand")); - ASSERT_EQ(std::future_status::ready, - future.wait_for(std::chrono::seconds(2))); + ASSERT_EQ(std::future_status::ready, future.wait_for(std::chrono::seconds(2))); auto res = future.get(); log::info("FEATURES:{}", res.feature); - ASSERT_EQ(res.feature, (BTRC_FEAT_ABSOLUTE_VOLUME | BTRC_FEAT_METADATA | - BTRC_FEAT_BROWSE | BTRC_FEAT_COVER_ARTWORK)); + ASSERT_EQ(res.feature, (BTRC_FEAT_ABSOLUTE_VOLUME | BTRC_FEAT_METADATA | BTRC_FEAT_BROWSE | + BTRC_FEAT_COVER_ARTWORK)); } class BtifRcBrowseConnectionTest : public BtifRcTest { - protected: +protected: void SetUp() override { BtifRcTest::SetUp(); init_ctrl(&btrc_ctrl_callbacks); @@ -284,9 +248,9 @@ class BtifRcBrowseConnectionTest : public BtifRcTest { btrc_ctrl_callbacks.connection_state_cb = [](bool rc_state, bool bt_state, const RawAddress& bd_addr) { rc_connection_state_cb_t rc_connection_state = { - .rc_state = rc_state, - .bt_state = bt_state, - .raw_address = bd_addr, + .rc_state = rc_state, + .bt_state = bt_state, + .raw_address = bd_addr, }; g_btrc_connection_state_promise.set_value(rc_connection_state); }; @@ -294,21 +258,20 @@ class BtifRcBrowseConnectionTest : public BtifRcTest { void TearDown() override { jni_thread.ShutDown(); - bt_rc_ctrl_callbacks->connection_state_cb = - [](bool rc_state, bool bt_state, const RawAddress& bd_addr) {}; + bt_rc_ctrl_callbacks->connection_state_cb = [](bool rc_state, bool bt_state, + const RawAddress& bd_addr) {}; BtifRcTest::TearDown(); } }; TEST_F(BtifRcBrowseConnectionTest, handle_rc_browse_connect) { g_btrc_connection_state_promise = std::promise(); - std::future future = - g_btrc_connection_state_promise.get_future(); + std::future future = g_btrc_connection_state_promise.get_future(); tBTA_AV_RC_BROWSE_OPEN browse_data = { - .rc_handle = 0, - .peer_addr = {}, - .status = BTA_AV_SUCCESS, + .rc_handle = 0, + .peer_addr = {}, + .status = BTA_AV_SUCCESS, }; btif_rc_cb.rc_multi_cb[0].rc_handle = 0; @@ -318,27 +281,25 @@ TEST_F(BtifRcBrowseConnectionTest, handle_rc_browse_connect) { /* process unit test handle_rc_browse_connect */ handle_rc_browse_connect(&browse_data); - ASSERT_EQ(std::future_status::ready, - future.wait_for(std::chrono::seconds(2))); + ASSERT_EQ(std::future_status::ready, future.wait_for(std::chrono::seconds(2))); auto res = future.get(); ASSERT_TRUE(res.bt_state); } class BtifRcConnectionTest : public BtifRcTest { - protected: +protected: void SetUp() override { BtifRcTest::SetUp(); init_ctrl(&btrc_ctrl_callbacks); jni_thread.StartUp(); g_btrc_connection_state_promise = std::promise(); - g_btrc_connection_state_future = - g_btrc_connection_state_promise.get_future(); + g_btrc_connection_state_future = g_btrc_connection_state_promise.get_future(); btrc_ctrl_callbacks.connection_state_cb = [](bool rc_state, bool bt_state, const RawAddress& bd_addr) { rc_connection_state_cb_t rc_connection_state = { - .rc_state = rc_state, - .bt_state = bt_state, - .raw_address = bd_addr, + .rc_state = rc_state, + .bt_state = bt_state, + .raw_address = bd_addr, }; g_btrc_connection_state_promise.set_value(rc_connection_state); }; @@ -346,8 +307,8 @@ class BtifRcConnectionTest : public BtifRcTest { void TearDown() override { jni_thread.ShutDown(); - bt_rc_ctrl_callbacks->connection_state_cb = - [](bool rc_state, bool bt_state, const RawAddress& bd_addr) {}; + bt_rc_ctrl_callbacks->connection_state_cb = [](bool rc_state, bool bt_state, + const RawAddress& bd_addr) {}; BtifRcTest::TearDown(); } std::future g_btrc_connection_state_future; @@ -357,9 +318,9 @@ TEST_F(BtifRcConnectionTest, btif_rc_connection_test) {} TEST_F(BtifRcConnectionTest, handle_rc_browse_connect) { tBTA_AV_RC_BROWSE_OPEN browse_data = { - .rc_handle = 0, - .peer_addr = {}, - .status = BTA_AV_SUCCESS, + .rc_handle = 0, + .peer_addr = {}, + .status = BTA_AV_SUCCESS, }; btif_rc_cb.rc_multi_cb[0].rc_handle = 0; @@ -381,8 +342,7 @@ TEST_F(BtifRcConnectionTest, btif_rc_check_pending_cmd) { btif_rc_cb.rc_multi_cb[0].rc_state = BTRC_CONNECTION_STATE_CONNECTED; btif_rc_cb.rc_multi_cb[0].rc_connected = true; btif_rc_cb.rc_multi_cb[0].launch_cmd_pending |= - (RC_PENDING_ACT_REG_VOL | RC_PENDING_ACT_GET_CAP | - RC_PENDING_ACT_REPORT_CONN); + (RC_PENDING_ACT_REG_VOL | RC_PENDING_ACT_GET_CAP | RC_PENDING_ACT_REPORT_CONN); btif_rc_check_pending_cmd(kDeviceAddress); ASSERT_EQ(1, get_func_call_count("AVRC_BldCommand")); @@ -396,22 +356,21 @@ TEST_F(BtifRcConnectionTest, btif_rc_check_pending_cmd) { TEST_F(BtifRcConnectionTest, bt_av_rc_open_evt) { btrc_ctrl_callbacks.get_cover_art_psm_cb = [](const RawAddress& /* bd_addr */, const uint16_t /* psm */) {}; - btrc_ctrl_callbacks.getrcfeatures_cb = [](const RawAddress& /* bd_addr */, - int /* features */) {}; + btrc_ctrl_callbacks.getrcfeatures_cb = [](const RawAddress& /* bd_addr */, int /* features */) {}; /* handle_rc_connect */ tBTA_AV data = { - .rc_open = - { - .rc_handle = 0, - .cover_art_psm = 0, - .peer_features = 0, - .peer_ct_features = 0, - .peer_tg_features = (BTA_AV_FEAT_METADATA | BTA_AV_FEAT_VENDOR | - BTA_AV_FEAT_RCTG | BTA_AV_FEAT_RCCT), - .peer_addr = kDeviceAddress, - .status = BTA_AV_SUCCESS, - }, + .rc_open = + { + .rc_handle = 0, + .cover_art_psm = 0, + .peer_features = 0, + .peer_ct_features = 0, + .peer_tg_features = (BTA_AV_FEAT_METADATA | BTA_AV_FEAT_VENDOR | + BTA_AV_FEAT_RCTG | BTA_AV_FEAT_RCCT), + .peer_addr = kDeviceAddress, + .status = BTA_AV_SUCCESS, + }, }; btif_rc_cb.rc_multi_cb[0].rc_handle = 0; btif_rc_cb.rc_multi_cb[0].rc_addr = RawAddress::kEmpty; @@ -431,21 +390,21 @@ TEST_F(BtifRcConnectionTest, bt_av_rc_open_evt) { } class BtifTrackChangeCBTest : public BtifRcTest { - protected: +protected: void SetUp() override { BtifRcTest::SetUp(); init_ctrl(&btrc_ctrl_callbacks); jni_thread.StartUp(); - btrc_ctrl_callbacks.track_changed_cb = [](const RawAddress& bd_addr, - uint8_t num_attr, btrc_element_attr_val_t* p_attrs) { + btrc_ctrl_callbacks.track_changed_cb = [](const RawAddress& bd_addr, uint8_t num_attr, + btrc_element_attr_val_t* p_attrs) { btif_rc_cb.rc_multi_cb[0].rc_addr = bd_addr; }; } void TearDown() override { jni_thread.ShutDown(); - btrc_ctrl_callbacks.track_changed_cb = [](const RawAddress& bd_addr, - uint8_t num_attr, btrc_element_attr_val_t* p_attrs) {}; + btrc_ctrl_callbacks.track_changed_cb = [](const RawAddress& bd_addr, uint8_t num_attr, + btrc_element_attr_val_t* p_attrs) {}; BtifRcTest::TearDown(); } }; @@ -474,21 +433,21 @@ TEST_F(BtifTrackChangeCBTest, handle_get_metadata_attr_response) { ASSERT_TRUE(btif_rc_get_device_by_handle(kRcHandle)); tBTA_AV_META_MSG meta_msg = { - .rc_handle = kRcHandle, - .len = 0, - .label = 0, - .code{}, - .company_id = 0, - .p_data = {}, - .p_msg = nullptr, + .rc_handle = kRcHandle, + .len = 0, + .label = 0, + .code{}, + .company_id = 0, + .p_data = {}, + .p_msg = nullptr, }; tAVRC_GET_ATTRS_RSP rsp = { - .pdu = 0, - .status = AVRC_STS_NO_ERROR, - .opcode = 0, - .num_attrs = 0, - .p_attrs = nullptr, + .pdu = 0, + .status = AVRC_STS_NO_ERROR, + .opcode = 0, + .num_attrs = 0, + .p_attrs = nullptr, }; handle_get_metadata_attr_response(&meta_msg, &rsp); diff --git a/system/btif/test/btif_storage_test.cc b/system/btif/test/btif_storage_test.cc index deb07633bb5..49fd74352ab 100644 --- a/system/btif/test/btif_storage_test.cc +++ b/system/btif/test/btif_storage_test.cc @@ -27,8 +27,8 @@ using bluetooth::Uuid; TEST(BtifStorageTest, test_uuid_split_multiple) { const char* s1 = - "e39c6285-867f-4b1d-9db0-35fbd9aebf22 " - "e39c6285-867f-4b1d-9db0-35fbd9aebf23"; + "e39c6285-867f-4b1d-9db0-35fbd9aebf22 " + "e39c6285-867f-4b1d-9db0-35fbd9aebf23"; const uint8_t u1[] = {0xe3, 0x9c, 0x62, 0x85, 0x86, 0x7f, 0x4b, 0x1d, 0x9d, 0xb0, 0x35, 0xfb, 0xd9, 0xae, 0xbf, 0x22}; const uint8_t u2[] = {0xe3, 0x9c, 0x62, 0x85, 0x86, 0x7f, 0x4b, 0x1d, @@ -43,8 +43,8 @@ TEST(BtifStorageTest, test_uuid_split_multiple) { TEST(BtifStorageTest, test_uuid_split_partial) { const char* s1 = - "e39c6285-867f-4b1d-9db0-35fbd9aebf22 " - "e39c6285-867f-4b1d-9db0-35fbd9aebf23"; + "e39c6285-867f-4b1d-9db0-35fbd9aebf22 " + "e39c6285-867f-4b1d-9db0-35fbd9aebf23"; Uuid uuids[2]; size_t num_uuids = btif_split_uuids_string(s1, uuids, 1); diff --git a/system/common/address_obfuscator.cc b/system/common/address_obfuscator.cc index d28038c40d6..2cd30108d96 100644 --- a/system/common/address_obfuscator.cc +++ b/system/common/address_obfuscator.cc @@ -30,8 +30,7 @@ namespace bluetooth { namespace common { bool AddressObfuscator::IsSaltValid(const Octet32& salt_256bit) { - return !std::all_of(salt_256bit.begin(), salt_256bit.end(), - [](uint8_t i) { return i == 0; }); + return !std::all_of(salt_256bit.begin(), salt_256bit.end(), [](uint8_t i) { return i == 0; }); } void AddressObfuscator::Initialize(const Octet32& salt_256bit) { @@ -49,15 +48,13 @@ std::string AddressObfuscator::Obfuscate(const RawAddress& address) { log::assert_that(IsInitialized(), "assert failed: IsInitialized()"); std::array result = {}; unsigned int out_len = 0; - log::assert_that(::HMAC(EVP_sha256(), salt_256bit_.data(), - salt_256bit_.size(), address.address, address.kLength, - result.data(), &out_len) != nullptr, + log::assert_that(::HMAC(EVP_sha256(), salt_256bit_.data(), salt_256bit_.size(), address.address, + address.kLength, result.data(), &out_len) != nullptr, "assert failed: ::HMAC(EVP_sha256(), salt_256bit_.data(), " "salt_256bit_.size(), address.address, address.kLength, " "result.data(), &out_len) != nullptr"); - log::assert_that( - out_len == static_cast(kOctet32Length), - "assert failed: out_len == static_cast(kOctet32Length)"); + log::assert_that(out_len == static_cast(kOctet32Length), + "assert failed: out_len == static_cast(kOctet32Length)"); return std::string(reinterpret_cast(result.data()), out_len); } diff --git a/system/common/address_obfuscator.h b/system/common/address_obfuscator.h index fef975321d7..3caff715cae 100644 --- a/system/common/address_obfuscator.h +++ b/system/common/address_obfuscator.h @@ -28,7 +28,7 @@ namespace bluetooth { namespace common { class AddressObfuscator { - public: +public: static constexpr unsigned int kOctet32Length = hci::kOctet32Length; using Octet32 = hci::Octet32; static AddressObfuscator* GetInstance() { @@ -66,7 +66,7 @@ class AddressObfuscator { */ std::string Obfuscate(const RawAddress& address); - private: +private: AddressObfuscator() : salt_256bit_({0}) {} Octet32 salt_256bit_; std::recursive_mutex instance_mutex_; diff --git a/system/common/address_obfuscator_unittest.cc b/system/common/address_obfuscator_unittest.cc index 62157deb691..5937cd70e8c 100644 --- a/system/common/address_obfuscator_unittest.cc +++ b/system/common/address_obfuscator_unittest.cc @@ -27,50 +27,46 @@ using bluetooth::common::AddressObfuscator; constexpr AddressObfuscator::Octet32 kEmptyKey = {0}; constexpr AddressObfuscator::Octet32 kTestKey1 = { - 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, - 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, - 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, + 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, + 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, + 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, }; static RawAddress kTestData1 = {{0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff}}; constexpr AddressObfuscator::Octet32 kTestResultRaw1 = { - 0x9b, 0x52, 0xb9, 0xb9, 0xb9, 0x34, 0x80, 0x1d, 0x98, 0x0b, 0x10, - 0xbe, 0x45, 0xa2, 0x6d, 0xaa, 0x99, 0xc3, 0x04, 0x10, 0x08, 0x03, - 0xb7, 0xb4, 0xa9, 0xde, 0xcf, 0x89, 0xe1, 0x5d, 0xd4, 0xaa}; -static std::string kTestResult1( - reinterpret_cast(kTestResultRaw1.data()), - kTestResultRaw1.size()); - -constexpr AddressObfuscator::Octet32 kTestKey2 = { - 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, - 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, - 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20}; + 0x9b, 0x52, 0xb9, 0xb9, 0xb9, 0x34, 0x80, 0x1d, 0x98, 0x0b, 0x10, + 0xbe, 0x45, 0xa2, 0x6d, 0xaa, 0x99, 0xc3, 0x04, 0x10, 0x08, 0x03, + 0xb7, 0xb4, 0xa9, 0xde, 0xcf, 0x89, 0xe1, 0x5d, 0xd4, 0xaa}; +static std::string kTestResult1(reinterpret_cast(kTestResultRaw1.data()), + kTestResultRaw1.size()); + +constexpr AddressObfuscator::Octet32 kTestKey2 = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, + 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, + 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, + 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20}; static RawAddress kTestData2_1 = {{0x9e, 0xf5, 0x3d, 0x6c, 0x2e, 0x33}}; constexpr AddressObfuscator::Octet32 kTestResultRaw2_1 = { - 0xb4, 0xe2, 0xfc, 0xb9, 0x59, 0x0d, 0x1f, 0xcf, 0x68, 0x80, 0xb2, - 0x3d, 0x08, 0x55, 0x4e, 0x64, 0xf5, 0x3b, 0x33, 0x0d, 0xb6, 0x31, - 0x9a, 0xbc, 0x4e, 0xce, 0x61, 0xbd, 0x46, 0x66, 0x45, 0x94}; -static std::string kTestResult2_1( - reinterpret_cast(kTestResultRaw2_1.data()), - kTestResultRaw2_1.size()); + 0xb4, 0xe2, 0xfc, 0xb9, 0x59, 0x0d, 0x1f, 0xcf, 0x68, 0x80, 0xb2, + 0x3d, 0x08, 0x55, 0x4e, 0x64, 0xf5, 0x3b, 0x33, 0x0d, 0xb6, 0x31, + 0x9a, 0xbc, 0x4e, 0xce, 0x61, 0xbd, 0x46, 0x66, 0x45, 0x94}; +static std::string kTestResult2_1(reinterpret_cast(kTestResultRaw2_1.data()), + kTestResultRaw2_1.size()); static RawAddress kTestData2_2 = {{0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}; constexpr AddressObfuscator::Octet32 kTestResultRaw2_2 = { - 0xd4, 0xd8, 0x23, 0xc0, 0x24, 0xba, 0xde, 0xe3, 0x1c, 0xad, 0x84, - 0x8b, 0x3d, 0xc6, 0xda, 0x93, 0x88, 0xb2, 0x5c, 0x60, 0x13, 0xe5, - 0xe2, 0x3e, 0x75, 0x5f, 0xd7, 0x15, 0x56, 0xf7, 0xaf, 0x27}; -static std::string kTestResult2_2( - reinterpret_cast(kTestResultRaw2_2.data()), - kTestResultRaw2_2.size()); + 0xd4, 0xd8, 0x23, 0xc0, 0x24, 0xba, 0xde, 0xe3, 0x1c, 0xad, 0x84, + 0x8b, 0x3d, 0xc6, 0xda, 0x93, 0x88, 0xb2, 0x5c, 0x60, 0x13, 0xe5, + 0xe2, 0x3e, 0x75, 0x5f, 0xd7, 0x15, 0x56, 0xf7, 0xaf, 0x27}; +static std::string kTestResult2_2(reinterpret_cast(kTestResultRaw2_2.data()), + kTestResultRaw2_2.size()); static RawAddress kTestData2_3 = {{0xff, 0xff, 0xff, 0xff, 0xff, 0xff}}; constexpr AddressObfuscator::Octet32 kTestResultRaw2_3 = { - 0x6f, 0x7c, 0x3d, 0x23, 0xcc, 0x7a, 0xf2, 0x68, 0xee, 0xe8, 0x6c, - 0x0f, 0xb5, 0xe0, 0x0c, 0x88, 0xf6, 0x38, 0x71, 0x44, 0x88, 0x09, - 0x45, 0x0a, 0xa2, 0xd7, 0xf6, 0x70, 0xba, 0x8c, 0xe9, 0x79}; -static std::string kTestResult2_3( - reinterpret_cast(kTestResultRaw2_3.data()), - kTestResultRaw2_3.size()); + 0x6f, 0x7c, 0x3d, 0x23, 0xcc, 0x7a, 0xf2, 0x68, 0xee, 0xe8, 0x6c, + 0x0f, 0xb5, 0xe0, 0x0c, 0x88, 0xf6, 0x38, 0x71, 0x44, 0x88, 0x09, + 0x45, 0x0a, 0xa2, 0xd7, 0xf6, 0x70, 0xba, 0x8c, 0xe9, 0x79}; +static std::string kTestResult2_3(reinterpret_cast(kTestResultRaw2_3.data()), + kTestResultRaw2_3.size()); TEST(AddressObfuscatorTest, test_invalid_key) { EXPECT_FALSE(AddressObfuscator::IsSaltValid(kEmptyKey)); @@ -99,24 +95,21 @@ TEST(AddressObfuscatorTest, test_obfuscate_address_key1) { TEST(AddressObfuscatorTest, test_obfuscate_address_key2) { AddressObfuscator::GetInstance()->Initialize(kTestKey2); - std::string result = - AddressObfuscator::GetInstance()->Obfuscate(kTestData2_1); + std::string result = AddressObfuscator::GetInstance()->Obfuscate(kTestData2_1); EXPECT_EQ(result.size(), AddressObfuscator::kOctet32Length); EXPECT_EQ(result, kTestResult2_1); } TEST(AddressObfuscatorTest, test_obfuscate_address_key2_empty_adddress) { AddressObfuscator::GetInstance()->Initialize(kTestKey2); - std::string result = - AddressObfuscator::GetInstance()->Obfuscate(kTestData2_2); + std::string result = AddressObfuscator::GetInstance()->Obfuscate(kTestData2_2); EXPECT_EQ(result.size(), AddressObfuscator::kOctet32Length); EXPECT_EQ(result, kTestResult2_2); } TEST(AddressObfuscatorTest, test_obfuscate_address_key2_max_address) { AddressObfuscator::GetInstance()->Initialize(kTestKey2); - std::string result = - AddressObfuscator::GetInstance()->Obfuscate(kTestData2_3); + std::string result = AddressObfuscator::GetInstance()->Obfuscate(kTestData2_3); EXPECT_EQ(result.size(), AddressObfuscator::kOctet32Length); EXPECT_EQ(result, kTestResult2_3); } diff --git a/system/common/base_bind_unittest.cc b/system/common/base_bind_unittest.cc index 7c77f97f91a..d31ea01642e 100644 --- a/system/common/base_bind_unittest.cc +++ b/system/common/base_bind_unittest.cc @@ -27,8 +27,8 @@ #include "os/log.h" class BaseBindThreadTest : public ::testing::Test { - public: - protected: +public: +protected: }; namespace { @@ -37,9 +37,7 @@ struct Vars { int b{0}; int c{0}; - bool operator==(const Vars& rhs) const { - return (a == rhs.a && b == rhs.b && c == rhs.c); - } + bool operator==(const Vars& rhs) const { return a == rhs.a && b == rhs.b && c == rhs.c; } } g_vars; diff --git a/system/common/benchmark/thread_performance_benchmark.cc b/system/common/benchmark/thread_performance_benchmark.cc index 60ba2e545ce..1a9828d3944 100644 --- a/system/common/benchmark/thread_performance_benchmark.cc +++ b/system/common/benchmark/thread_performance_benchmark.cc @@ -40,8 +40,7 @@ static std::unique_ptr> g_counter_promise = nullptr; void pthread_callback_batch(void* context) { auto queue = static_cast(context); - bluetooth::log::assert_that(queue != nullptr, - "assert failed: queue != nullptr"); + bluetooth::log::assert_that(queue != nullptr, "assert failed: queue != nullptr"); fixed_queue_dequeue(queue); g_counter++; if (g_counter >= NUM_MESSAGES_TO_SEND) { @@ -52,15 +51,13 @@ void pthread_callback_batch(void* context) { void callback_sequential(void* context) { g_counter_promise->set_value(); } void callback_sequential_queue(fixed_queue_t* queue, void* context) { - bluetooth::log::assert_that(queue != nullptr, - "assert failed: queue != nullptr"); + bluetooth::log::assert_that(queue != nullptr, "assert failed: queue != nullptr"); fixed_queue_dequeue(queue); g_counter_promise->set_value(); } void callback_batch(fixed_queue_t* queue, void* data) { - bluetooth::log::assert_that(queue != nullptr, - "assert failed: queue != nullptr"); + bluetooth::log::assert_that(queue != nullptr, "assert failed: queue != nullptr"); fixed_queue_dequeue(queue); g_counter++; if (g_counter >= NUM_MESSAGES_TO_SEND) { @@ -69,7 +66,7 @@ void callback_batch(fixed_queue_t* queue, void* data) { } class BM_ThreadPerformance : public ::benchmark::Fixture { - protected: +protected: void SetUp(State& st) override { benchmark::Fixture::SetUp(st); set_up_promise_ = std::make_unique>(); @@ -88,7 +85,7 @@ class BM_ThreadPerformance : public ::benchmark::Fixture { }; class BM_MessageLoop : public BM_ThreadPerformance { - public: +public: static void RunThread(void* context) { auto test = static_cast(context); test->RunMessageLoop(); @@ -101,9 +98,9 @@ class BM_MessageLoop : public BM_ThreadPerformance { void RunMessageLoop() { message_loop_ = new btbase::AbstractMessageLoop(); run_loop_ = new base::RunLoop(); - message_loop_->task_runner()->PostTask( - FROM_HERE, base::BindOnce(&std::promise::set_value, - base::Unretained(set_up_promise_.get()))); + message_loop_->task_runner()->PostTask(FROM_HERE, + base::BindOnce(&std::promise::set_value, + base::Unretained(set_up_promise_.get()))); run_loop_->Run(); delete message_loop_; message_loop_ = nullptr; @@ -111,13 +108,13 @@ class BM_MessageLoop : public BM_ThreadPerformance { run_loop_ = nullptr; } - protected: +protected: btbase::AbstractMessageLoop* message_loop_ = nullptr; base::RunLoop* run_loop_ = nullptr; }; class BM_MessageLoopOsiThread : public BM_MessageLoop { - protected: +protected: void SetUp(State& st) override { BM_MessageLoop::SetUp(st); std::future set_up_future = set_up_promise_->get_future(); @@ -127,8 +124,7 @@ class BM_MessageLoopOsiThread : public BM_MessageLoop { } void TearDown(State& st) override { - message_loop_->task_runner()->PostTask(FROM_HERE, - run_loop_->QuitWhenIdleClosure()); + message_loop_->task_runner()->PostTask(FROM_HERE, run_loop_->QuitWhenIdleClosure()); thread_free(thread_); thread_ = nullptr; BM_MessageLoop::TearDown(st); @@ -145,26 +141,26 @@ BENCHMARK_F(BM_MessageLoopOsiThread, batch_enque_dequeue)(State& state) { for (int i = 0; i < NUM_MESSAGES_TO_SEND; i++) { fixed_queue_enqueue(bt_msg_queue_, (void*)&g_counter); message_loop_->task_runner()->PostTask( - FROM_HERE, base::BindOnce(&callback_batch, bt_msg_queue_, nullptr)); + FROM_HERE, base::BindOnce(&callback_batch, bt_msg_queue_, nullptr)); } counter_future.wait(); } -}; +} BENCHMARK_F(BM_MessageLoopOsiThread, sequential_execution)(State& state) { for (auto _ : state) { for (int i = 0; i < NUM_MESSAGES_TO_SEND; i++) { g_counter_promise = std::make_unique>(); std::future counter_future = g_counter_promise->get_future(); - message_loop_->task_runner()->PostTask( - FROM_HERE, base::BindOnce(&callback_sequential, nullptr)); + message_loop_->task_runner()->PostTask(FROM_HERE, + base::BindOnce(&callback_sequential, nullptr)); counter_future.wait(); } } -}; +} class BM_MessageLoopStlThread : public BM_MessageLoop { - protected: +protected: void SetUp(State& st) override { BM_MessageLoop::SetUp(st); std::future set_up_future = set_up_promise_->get_future(); @@ -173,8 +169,7 @@ class BM_MessageLoopStlThread : public BM_MessageLoop { } void TearDown(State& st) override { - message_loop_->task_runner()->PostTask(FROM_HERE, - run_loop_->QuitWhenIdleClosure()); + message_loop_->task_runner()->PostTask(FROM_HERE, run_loop_->QuitWhenIdleClosure()); thread_->join(); delete thread_; thread_ = nullptr; @@ -192,26 +187,26 @@ BENCHMARK_F(BM_MessageLoopStlThread, batch_enque_dequeue)(State& state) { for (int i = 0; i < NUM_MESSAGES_TO_SEND; i++) { fixed_queue_enqueue(bt_msg_queue_, (void*)&g_counter); message_loop_->task_runner()->PostTask( - FROM_HERE, base::BindOnce(&callback_batch, bt_msg_queue_, nullptr)); + FROM_HERE, base::BindOnce(&callback_batch, bt_msg_queue_, nullptr)); } counter_future.wait(); } -}; +} BENCHMARK_F(BM_MessageLoopStlThread, sequential_execution)(State& state) { for (auto _ : state) { for (int i = 0; i < NUM_MESSAGES_TO_SEND; i++) { g_counter_promise = std::make_unique>(); std::future counter_future = g_counter_promise->get_future(); - message_loop_->task_runner()->PostTask( - FROM_HERE, base::BindOnce(&callback_sequential, nullptr)); + message_loop_->task_runner()->PostTask(FROM_HERE, + base::BindOnce(&callback_sequential, nullptr)); counter_future.wait(); } } -}; +} class BM_MessageLoopPosixThread : public BM_MessageLoop { - protected: +protected: void SetUp(State& st) override { BM_MessageLoop::SetUp(st); std::future set_up_future = set_up_promise_->get_future(); @@ -220,8 +215,7 @@ class BM_MessageLoopPosixThread : public BM_MessageLoop { } void TearDown(State& st) override { - message_loop_->task_runner()->PostTask(FROM_HERE, - run_loop_->QuitWhenIdleClosure()); + message_loop_->task_runner()->PostTask(FROM_HERE, run_loop_->QuitWhenIdleClosure()); pthread_join(thread_, nullptr); BM_MessageLoop::TearDown(st); } @@ -237,26 +231,26 @@ BENCHMARK_F(BM_MessageLoopPosixThread, batch_enque_dequeue)(State& state) { for (int i = 0; i < NUM_MESSAGES_TO_SEND; i++) { fixed_queue_enqueue(bt_msg_queue_, (void*)&g_counter); message_loop_->task_runner()->PostTask( - FROM_HERE, base::BindOnce(&callback_batch, bt_msg_queue_, nullptr)); + FROM_HERE, base::BindOnce(&callback_batch, bt_msg_queue_, nullptr)); } counter_future.wait(); } -}; +} BENCHMARK_F(BM_MessageLoopPosixThread, sequential_execution)(State& state) { for (auto _ : state) { for (int i = 0; i < NUM_MESSAGES_TO_SEND; i++) { g_counter_promise = std::make_unique>(); std::future counter_future = g_counter_promise->get_future(); - message_loop_->task_runner()->PostTask( - FROM_HERE, base::BindOnce(&callback_sequential, nullptr)); + message_loop_->task_runner()->PostTask(FROM_HERE, + base::BindOnce(&callback_sequential, nullptr)); counter_future.wait(); } } -}; +} class BM_OsiReactorThread : public BM_ThreadPerformance { - protected: +protected: void SetUp(State& st) override { BM_ThreadPerformance::SetUp(st); thread_ = thread_new("BM_OsiReactorThread thread"); @@ -283,7 +277,7 @@ BENCHMARK_F(BM_OsiReactorThread, batch_enque_dequeue_using_thread_post) } counter_future.wait(); } -}; +} BENCHMARK_F(BM_OsiReactorThread, sequential_execution_using_thread_post) (State& state) { @@ -295,12 +289,11 @@ BENCHMARK_F(BM_OsiReactorThread, sequential_execution_using_thread_post) counter_future.wait(); } } -}; +} BENCHMARK_F(BM_OsiReactorThread, batch_enque_dequeue_using_reactor) (State& state) { - fixed_queue_register_dequeue(bt_msg_queue_, thread_get_reactor(thread_), - callback_batch, nullptr); + fixed_queue_register_dequeue(bt_msg_queue_, thread_get_reactor(thread_), callback_batch, nullptr); for (auto _ : state) { g_counter = 0; g_counter_promise = std::make_unique>(); @@ -310,7 +303,7 @@ BENCHMARK_F(BM_OsiReactorThread, batch_enque_dequeue_using_reactor) } counter_future.wait(); } -}; +} BENCHMARK_F(BM_OsiReactorThread, sequential_execution_using_reactor) (State& state) { @@ -324,19 +317,18 @@ BENCHMARK_F(BM_OsiReactorThread, sequential_execution_using_reactor) counter_future.wait(); } } -}; +} class BM_MessageLooopThread : public BM_ThreadPerformance { - protected: +protected: void SetUp(State& st) override { BM_ThreadPerformance::SetUp(st); std::future set_up_future = set_up_promise_->get_future(); - message_loop_thread_ = - new MessageLoopThread("BM_MessageLooopThread thread"); + message_loop_thread_ = new MessageLoopThread("BM_MessageLooopThread thread"); message_loop_thread_->StartUp(); - message_loop_thread_->DoInThread( - FROM_HERE, base::BindOnce(&std::promise::set_value, - base::Unretained(set_up_promise_.get()))); + message_loop_thread_->DoInThread(FROM_HERE, + base::BindOnce(&std::promise::set_value, + base::Unretained(set_up_promise_.get()))); set_up_future.wait(); } @@ -357,35 +349,34 @@ BENCHMARK_F(BM_MessageLooopThread, batch_enque_dequeue)(State& state) { std::future counter_future = g_counter_promise->get_future(); for (int i = 0; i < NUM_MESSAGES_TO_SEND; i++) { fixed_queue_enqueue(bt_msg_queue_, (void*)&g_counter); - message_loop_thread_->DoInThread( - FROM_HERE, base::BindOnce(&callback_batch, bt_msg_queue_, nullptr)); + message_loop_thread_->DoInThread(FROM_HERE, + base::BindOnce(&callback_batch, bt_msg_queue_, nullptr)); } counter_future.wait(); } -}; +} BENCHMARK_F(BM_MessageLooopThread, sequential_execution)(State& state) { for (auto _ : state) { for (int i = 0; i < NUM_MESSAGES_TO_SEND; i++) { g_counter_promise = std::make_unique>(); std::future counter_future = g_counter_promise->get_future(); - message_loop_thread_->DoInThread( - FROM_HERE, base::BindOnce(&callback_sequential, nullptr)); + message_loop_thread_->DoInThread(FROM_HERE, base::BindOnce(&callback_sequential, nullptr)); counter_future.wait(); } } -}; +} class BM_LibChromeThread : public BM_ThreadPerformance { - protected: +protected: void SetUp(State& st) override { BM_ThreadPerformance::SetUp(st); std::future set_up_future = set_up_promise_->get_future(); thread_ = new base::Thread("BM_LibChromeThread thread"); thread_->Start(); - thread_->task_runner()->PostTask( - FROM_HERE, base::BindOnce(&std::promise::set_value, - base::Unretained(set_up_promise_.get()))); + thread_->task_runner()->PostTask(FROM_HERE, + base::BindOnce(&std::promise::set_value, + base::Unretained(set_up_promise_.get()))); set_up_future.wait(); } @@ -406,24 +397,23 @@ BENCHMARK_F(BM_LibChromeThread, batch_enque_dequeue)(State& state) { std::future counter_future = g_counter_promise->get_future(); for (int i = 0; i < NUM_MESSAGES_TO_SEND; i++) { fixed_queue_enqueue(bt_msg_queue_, (void*)&g_counter); - thread_->task_runner()->PostTask( - FROM_HERE, base::BindOnce(&callback_batch, bt_msg_queue_, nullptr)); + thread_->task_runner()->PostTask(FROM_HERE, + base::BindOnce(&callback_batch, bt_msg_queue_, nullptr)); } counter_future.wait(); } -}; +} BENCHMARK_F(BM_LibChromeThread, sequential_execution)(State& state) { for (auto _ : state) { for (int i = 0; i < NUM_MESSAGES_TO_SEND; i++) { g_counter_promise = std::make_unique>(); std::future counter_future = g_counter_promise->get_future(); - thread_->task_runner()->PostTask( - FROM_HERE, base::BindOnce(&callback_sequential, nullptr)); + thread_->task_runner()->PostTask(FROM_HERE, base::BindOnce(&callback_sequential, nullptr)); counter_future.wait(); } } -}; +} int main(int argc, char** argv) { ::benchmark::Initialize(&argc, argv); diff --git a/system/common/id_generator.h b/system/common/id_generator.h index 202d6459658..e404ff4585a 100644 --- a/system/common/id_generator.h +++ b/system/common/id_generator.h @@ -21,7 +21,7 @@ /* Helper class generating N unique ids, from 0 to N-1 */ template class IdGenerator { - public: +public: static int ALL_USED; IdGenerator() : in_use_{} {} @@ -40,7 +40,7 @@ class IdGenerator { /* Release given ID */ void Release(int id) { in_use_[id] = false; } - private: +private: std::array in_use_; }; diff --git a/system/common/leaky_bonded_queue.h b/system/common/leaky_bonded_queue.h index 087b192cfc2..df96147b831 100644 --- a/system/common/leaky_bonded_queue.h +++ b/system/common/leaky_bonded_queue.h @@ -41,7 +41,7 @@ namespace common { */ template class LeakyBondedQueue { - public: +public: LeakyBondedQueue(size_t capacity); /* Default destructor * @@ -79,7 +79,7 @@ class LeakyBondedQueue { */ void Clear(); - private: +private: // Put item in unique_ptr so that they get freed automatically when poped or // when queue_ is freed std::queue> queue_; diff --git a/system/common/leaky_bonded_queue_unittest.cc b/system/common/leaky_bonded_queue_unittest.cc index d265b434234..b35a991251a 100644 --- a/system/common/leaky_bonded_queue_unittest.cc +++ b/system/common/leaky_bonded_queue_unittest.cc @@ -33,14 +33,14 @@ using namespace bluetooth; } while (0) class Item { - public: +public: Item(int i) { index = i; } virtual ~Item() {} int index; }; class MockItem : public Item { - public: +public: MockItem(int i) : Item(i) {} ~MockItem() override { Destruct(); } MOCK_METHOD0(Destruct, void()); diff --git a/system/common/lru.h b/system/common/lru.h index 95278e954a4..ca0a5a1c359 100644 --- a/system/common/lru.h +++ b/system/common/lru.h @@ -34,7 +34,7 @@ namespace common { template class LegacyLruCache { - public: +public: using Node = std::pair; /** * Constructor of the cache @@ -42,8 +42,7 @@ class LegacyLruCache { * @param capacity maximum size of the cache * @param log_tag, keyword to put at the head of log. */ - LegacyLruCache(const size_t& capacity, const std::string& log_tag) - : capacity_(capacity) { + LegacyLruCache(const size_t& capacity, const std::string& log_tag) : capacity_(capacity) { if (capacity_ == 0) { // don't allow invalid capacity log::fatal("{} unable to have 0 LRU Cache capacity", log_tag); @@ -177,7 +176,7 @@ class LegacyLruCache { return lru_map_.size(); } - private: +private: std::list node_list_; size_t capacity_; std::unordered_map::iterator> lru_map_; diff --git a/system/common/lru_unittest.cc b/system/common/lru_unittest.cc index 34786cb3e6e..7b41143ec5e 100644 --- a/system/common/lru_unittest.cc +++ b/system/common/lru_unittest.cc @@ -16,13 +16,14 @@ * ******************************************************************************/ +#include "common/lru.h" + #include #include + #include #include -#include "common/lru.h" - namespace testing { using bluetooth::common::LegacyLruCache; diff --git a/system/common/message_loop_thread.cc b/system/common/message_loop_thread.cc index 6d81a7b67ad..3cf5f1af389 100644 --- a/system/common/message_loop_thread.cc +++ b/system/common/message_loop_thread.cc @@ -66,32 +66,27 @@ void MessageLoopThread::StartUp() { return; } - thread_ = new std::thread(&MessageLoopThread::RunThread, this, - std::move(start_up_promise)); + thread_ = new std::thread(&MessageLoopThread::RunThread, this, std::move(start_up_promise)); } start_up_future.wait(); } -bool MessageLoopThread::DoInThread(const base::Location& from_here, - base::OnceClosure task) { - return DoInThreadDelayed(from_here, std::move(task), - std::chrono::microseconds(0)); +bool MessageLoopThread::DoInThread(const base::Location& from_here, base::OnceClosure task) { + return DoInThreadDelayed(from_here, std::move(task), std::chrono::microseconds(0)); } -bool MessageLoopThread::DoInThreadDelayed(const base::Location& from_here, - base::OnceClosure task, +bool MessageLoopThread::DoInThreadDelayed(const base::Location& from_here, base::OnceClosure task, std::chrono::microseconds delay) { std::lock_guard api_lock(api_mutex_); if (message_loop_ == nullptr) { - log::error("message loop is null for thread {}, from {}", *this, - from_here.ToString()); + log::error("message loop is null for thread {}, from {}", *this, from_here.ToString()); return false; } - if (!message_loop_->task_runner()->PostDelayedTask( - from_here, std::move(task), timeDeltaFromMicroseconds(delay))) { - log::error("failed to post task to message loop for thread {}, from {}", - *this, from_here.ToString()); + if (!message_loop_->task_runner()->PostDelayedTask(from_here, std::move(task), + timeDeltaFromMicroseconds(delay))) { + log::error("failed to post task to message loop for thread {}, from {}", *this, + from_here.ToString()); return false; } return true; @@ -114,8 +109,7 @@ void MessageLoopThread::ShutDown() { } shutting_down_ = true; log::assert_that(thread_id_ != base::PlatformThread::CurrentId(), - "should not be called on the thread itself. Otherwise, " - "deadlock may happen."); + "should not be called on the thread itself. Otherwise, deadlock may happen."); run_loop_->QuitWhenIdle(); } thread_->join(); @@ -145,8 +139,7 @@ bool MessageLoopThread::IsRunning() const { } // Non API method, should not be protected by API mutex -void MessageLoopThread::RunThread(MessageLoopThread* thread, - std::promise start_up_promise) { +void MessageLoopThread::RunThread(MessageLoopThread* thread, std::promise start_up_promise) { thread->Run(std::move(start_up_promise)); } @@ -164,14 +157,11 @@ bool MessageLoopThread::EnableRealTimeScheduling() { return false; } - struct sched_param rt_params = {.sched_priority = - kRealTimeFifoSchedulingPriority}; + struct sched_param rt_params = {.sched_priority = kRealTimeFifoSchedulingPriority}; int rc = sched_setscheduler(linux_tid_, SCHED_FIFO, &rt_params); if (rc != 0) { - log::error( - "unable to set SCHED_FIFO priority {} for linux_tid {}, thread {}, " - "error: {}", - kRealTimeFifoSchedulingPriority, linux_tid_, *this, strerror(errno)); + log::error("unable to set SCHED_FIFO priority {} for linux_tid {}, thread {}, error: {}", + kRealTimeFifoSchedulingPriority, linux_tid_, *this, strerror(errno)); return false; } return true; diff --git a/system/common/message_loop_thread.h b/system/common/message_loop_thread.h index 3c43dafe3d6..3c842a01e72 100644 --- a/system/common/message_loop_thread.h +++ b/system/common/message_loop_thread.h @@ -38,7 +38,7 @@ namespace common { * An interface to various thread related functionality */ class MessageLoopThread final : public PostableContext { - public: +public: /** * Create a message loop thread with name. Thread won't be running until * StartUp is called. @@ -165,8 +165,7 @@ class MessageLoopThread final : public PostableContext { * @return true if task is successfully scheduled, false if task cannot be * scheduled */ - bool DoInThreadDelayed(const base::Location& from_here, - base::OnceClosure task, + bool DoInThreadDelayed(const base::Location& from_here, base::OnceClosure task, std::chrono::microseconds delay); /** * Wrapper around DoInThread without a location. @@ -178,7 +177,7 @@ class MessageLoopThread final : public PostableContext { */ PostableContext* Postable(); - private: +private: /** * Static method to run the thread * @@ -188,8 +187,7 @@ class MessageLoopThread final : public PostableContext { * @param start_up_promise a std::promise that is used to notify calling * thread the completion of message loop start-up */ - static void RunThread(MessageLoopThread* context, - std::promise start_up_promise); + static void RunThread(MessageLoopThread* context, std::promise start_up_promise); /** * Actual method to run the thread, blocking until ShutDown() is called @@ -211,8 +209,7 @@ class MessageLoopThread final : public PostableContext { bool shutting_down_; }; -inline std::ostream& operator<<(std::ostream& os, - const bluetooth::common::MessageLoopThread& a) { +inline std::ostream& operator<<(std::ostream& os, const bluetooth::common::MessageLoopThread& a) { os << a.ToString(); return os; } diff --git a/system/common/message_loop_thread_unittest.cc b/system/common/message_loop_thread_unittest.cc index e904e3fcc5a..21f05f68c26 100644 --- a/system/common/message_loop_thread_unittest.cc +++ b/system/common/message_loop_thread_unittest.cc @@ -33,7 +33,7 @@ using namespace bluetooth; * Unit tests to verify MessageLoopThread. Must have CAP_SYS_NICE capability. */ class MessageLoopThreadTest : public ::testing::Test { - public: +public: void ShouldNotHappen() { FAIL() << "Should not happen"; } void GetThreadId(std::promise thread_id_promise) { @@ -50,8 +50,7 @@ class MessageLoopThreadTest : public ::testing::Test { name_promise.set_value(my_name); } - void GetSchedulingPolicyAndPriority(int* scheduling_policy, - int* schedule_priority, + void GetSchedulingPolicyAndPriority(int* scheduling_policy, int* schedule_priority, std::promise execution_promise) { *scheduling_policy = sched_getscheduler(0); struct sched_param param = {}; @@ -65,17 +64,14 @@ class MessageLoopThreadTest : public ::testing::Test { GetName(std::move(name_promise)); } - protected: +protected: static bool CanSetCurrentThreadPriority() { - struct __user_cap_header_struct linux_user_header = { - .version = _LINUX_CAPABILITY_VERSION_3}; + struct __user_cap_header_struct linux_user_header = {.version = _LINUX_CAPABILITY_VERSION_3}; struct __user_cap_data_struct linux_user_data[2] = {}; if (capget(&linux_user_header, linux_user_data) != 0) { - log::error("Failed to get capability for current thread, error: {}", - strerror(errno)); + log::error("Failed to get capability for current thread, error: {}", strerror(errno)); // Log record in XML - RecordProperty("MessageLoopThreadTestCannotGetCapabilityReason", - strerror(errno)); + RecordProperty("MessageLoopThreadTestCannotGetCapabilityReason", strerror(errno)); return false; } return ((linux_user_data[0].permitted >> CAP_SYS_NICE) & 0x1) != 0; @@ -106,8 +102,7 @@ TEST_F(MessageLoopThreadTest, test_not_self) { MessageLoopThread message_loop_thread("test_thread"); message_loop_thread.StartUp(); ASSERT_GE(message_loop_thread.GetThreadId(), 0); - ASSERT_NE(message_loop_thread.GetThreadId(), - base::PlatformThread::CurrentId()); + ASSERT_NE(message_loop_thread.GetThreadId(), base::PlatformThread::CurrentId()); } TEST_F(MessageLoopThreadTest, test_shutdown_without_start) { @@ -120,8 +115,8 @@ TEST_F(MessageLoopThreadTest, test_do_in_thread_before_start) { std::string name = "test_thread"; MessageLoopThread message_loop_thread(name); ASSERT_FALSE(message_loop_thread.DoInThread( - FROM_HERE, base::BindOnce(&MessageLoopThreadTest::ShouldNotHappen, - base::Unretained(this)))); + FROM_HERE, + base::BindOnce(&MessageLoopThreadTest::ShouldNotHappen, base::Unretained(this)))); } TEST_F(MessageLoopThreadTest, test_do_in_thread_after_shutdown) { @@ -130,8 +125,8 @@ TEST_F(MessageLoopThreadTest, test_do_in_thread_after_shutdown) { message_loop_thread.StartUp(); message_loop_thread.ShutDown(); ASSERT_FALSE(message_loop_thread.DoInThread( - FROM_HERE, base::BindOnce(&MessageLoopThreadTest::ShouldNotHappen, - base::Unretained(this)))); + FROM_HERE, + base::BindOnce(&MessageLoopThreadTest::ShouldNotHappen, base::Unretained(this)))); } TEST_F(MessageLoopThreadTest, test_name) { @@ -142,9 +137,8 @@ TEST_F(MessageLoopThreadTest, test_name) { std::promise name_promise; std::future name_future = name_promise.get_future(); message_loop_thread.DoInThread( - FROM_HERE, - base::BindOnce(&MessageLoopThreadTest::GetName, base::Unretained(this), - std::move(name_promise))); + FROM_HERE, base::BindOnce(&MessageLoopThreadTest::GetName, base::Unretained(this), + std::move(name_promise))); std::string my_name = name_future.get(); ASSERT_EQ(name, my_name); ASSERT_EQ(name, message_loop_thread.GetName()); @@ -157,12 +151,10 @@ TEST_F(MessageLoopThreadTest, test_thread_id) { base::PlatformThreadId thread_id = message_loop_thread.GetThreadId(); ASSERT_GE(thread_id, 0); std::promise thread_id_promise; - std::future thread_id_future = - thread_id_promise.get_future(); + std::future thread_id_future = thread_id_promise.get_future(); message_loop_thread.DoInThread( - FROM_HERE, - base::BindOnce(&MessageLoopThreadTest::GetThreadId, - base::Unretained(this), std::move(thread_id_promise))); + FROM_HERE, base::BindOnce(&MessageLoopThreadTest::GetThreadId, base::Unretained(this), + std::move(thread_id_promise))); base::PlatformThreadId my_thread_id = thread_id_future.get(); ASSERT_EQ(thread_id, my_thread_id); } @@ -183,8 +175,8 @@ TEST_F(MessageLoopThreadTest, test_set_realtime_priority_success) { FAIL() << "Cannot set real time priority even though we have permission"; } else { log::warn( - "Allowing EnableRealTimeScheduling to fail because we don't have " - "CAP_SYS_NICE capability"); + "Allowing EnableRealTimeScheduling to fail because we don't have " + "CAP_SYS_NICE capability"); // Log record in XML RecordProperty("MessageLoopThreadTestConditionalSuccess", "Mark test as success even though EnableRealTimeScheduling" @@ -198,10 +190,9 @@ TEST_F(MessageLoopThreadTest, test_set_realtime_priority_success) { int scheduling_policy = -1; int scheduling_priority = -1; message_loop_thread.DoInThread( - FROM_HERE, - base::BindOnce(&MessageLoopThreadTest::GetSchedulingPolicyAndPriority, - base::Unretained(this), &scheduling_policy, - &scheduling_priority, std::move(execution_promise))); + FROM_HERE, base::BindOnce(&MessageLoopThreadTest::GetSchedulingPolicyAndPriority, + base::Unretained(this), &scheduling_policy, + &scheduling_priority, std::move(execution_promise))); execution_future.wait(); ASSERT_EQ(scheduling_policy, SCHED_FIFO); // Internal implementation verified here @@ -209,9 +200,8 @@ TEST_F(MessageLoopThreadTest, test_set_realtime_priority_success) { std::promise tid_promise; std::future tid_future = tid_promise.get_future(); message_loop_thread.DoInThread( - FROM_HERE, - base::BindOnce(&MessageLoopThreadTest::GetLinuxTid, - base::Unretained(this), std::move(tid_promise))); + FROM_HERE, base::BindOnce(&MessageLoopThreadTest::GetLinuxTid, base::Unretained(this), + std::move(tid_promise))); pid_t linux_tid = tid_future.get(); ASSERT_GT(linux_tid, 0); ASSERT_EQ(sched_getscheduler(linux_tid), SCHED_FIFO); @@ -254,14 +244,12 @@ TEST_F(MessageLoopThreadTest, test_to_string_method) { ASSERT_FALSE(thread_string_running.empty()); log::info("Running: {}", message_loop_thread); // String representation should look different when thread is not running - ASSERT_STRNE(thread_string_running.c_str(), - thread_string_before_start.c_str()); + ASSERT_STRNE(thread_string_running.c_str(), thread_string_before_start.c_str()); message_loop_thread.ShutDown(); std::string thread_string_after_shutdown = message_loop_thread.ToString(); log::info("After shutdown: {}", message_loop_thread); // String representation should look the same when thread is not running - ASSERT_STREQ(thread_string_after_shutdown.c_str(), - thread_string_before_start.c_str()); + ASSERT_STREQ(thread_string_after_shutdown.c_str(), thread_string_before_start.c_str()); } // Verify the message loop thread will shutdown after callback finishes @@ -273,9 +261,8 @@ TEST_F(MessageLoopThreadTest, shut_down_while_in_callback) { std::future name_future = name_promise.get_future(); uint32_t delay_ms = 5; message_loop_thread.DoInThread( - FROM_HERE, base::BindOnce(&MessageLoopThreadTest::SleepAndGetName, - base::Unretained(this), std::move(name_promise), - delay_ms)); + FROM_HERE, base::BindOnce(&MessageLoopThreadTest::SleepAndGetName, base::Unretained(this), + std::move(name_promise), delay_ms)); message_loop_thread.ShutDown(); std::string my_name = name_future.get(); ASSERT_EQ(name, my_name); @@ -287,9 +274,8 @@ TEST_F(MessageLoopThreadTest, shut_down_while_in_callback_check_lock) { MessageLoopThread message_loop_thread(name); message_loop_thread.StartUp(); message_loop_thread.DoInThread( - FROM_HERE, - base::BindOnce([](MessageLoopThread* thread) { thread->IsRunning(); }, - &message_loop_thread)); + FROM_HERE, base::BindOnce([](MessageLoopThread* thread) { thread->IsRunning(); }, + &message_loop_thread)); message_loop_thread.ShutDown(); } @@ -337,14 +323,12 @@ TEST_F(MessageLoopThreadTest, test_post_twice) { MessageLoopThread message_loop_thread(name); int counter = 0; message_loop_thread.StartUp(); - message_loop_thread.Post( - base::BindOnce([](MessageLoopThread* thread, - int* counter) { ASSERT_EQ((*counter)++, 0); }, - &message_loop_thread, &counter)); - message_loop_thread.Post( - base::BindOnce([](MessageLoopThread* thread, - int* counter) { ASSERT_EQ((*counter)++, 1); }, - &message_loop_thread, &counter)); + message_loop_thread.Post(base::BindOnce( + [](MessageLoopThread* thread, int* counter) { ASSERT_EQ((*counter)++, 0); }, + &message_loop_thread, &counter)); + message_loop_thread.Post(base::BindOnce( + [](MessageLoopThread* thread, int* counter) { ASSERT_EQ((*counter)++, 1); }, + &message_loop_thread, &counter)); message_loop_thread.ShutDown(); ASSERT_EQ(counter, 2); } diff --git a/system/common/metric_id_allocator.cc b/system/common/metric_id_allocator.cc index 0d2cf1cf268..041e272815c 100644 --- a/system/common/metric_id_allocator.cc +++ b/system/common/metric_id_allocator.cc @@ -40,7 +40,7 @@ const int MetricIdAllocator::kMaxId = 65534; // 2^16 - 2 // kMaxNumUnpairedDevicesInMemory static_assert((MetricIdAllocator::kMaxNumUnpairedDevicesInMemory + MetricIdAllocator::kMaxNumPairedDevicesInMemory) < - (MetricIdAllocator::kMaxId - MetricIdAllocator::kMinId), + (MetricIdAllocator::kMaxId - MetricIdAllocator::kMinId), "id space should always be larger than " "kMaxNumPairedDevicesInMemory + MaxNumUnpairedDevicesInMemory"); @@ -48,9 +48,8 @@ MetricIdAllocator::MetricIdAllocator() : paired_device_cache_(kMaxNumPairedDevicesInMemory, LOGGING_TAG), temporary_device_cache_(kMaxNumUnpairedDevicesInMemory, LOGGING_TAG) {} -bool MetricIdAllocator::Init( - const std::unordered_map& paired_device_map, - Callback save_id_callback, Callback forget_device_callback) { +bool MetricIdAllocator::Init(const std::unordered_map& paired_device_map, + Callback save_id_callback, Callback forget_device_callback) { std::lock_guard lock(id_allocator_mutex_); if (initialized_) { return false; @@ -58,9 +57,7 @@ bool MetricIdAllocator::Init( // init paired_devices_map if (paired_device_map.size() > kMaxNumPairedDevicesInMemory) { - log::fatal( - "{}Paired device map is bigger than kMaxNumPairedDevicesInMemory", - LOGGING_TAG); + log::fatal("{}Paired device map is bigger than kMaxNumPairedDevicesInMemory", LOGGING_TAG); // fail loudly to let caller know return false; } @@ -109,8 +106,7 @@ MetricIdAllocator& MetricIdAllocator::GetInstance() { bool MetricIdAllocator::IsEmpty() const { std::lock_guard lock(id_allocator_mutex_); - return paired_device_cache_.Size() == 0 && - temporary_device_cache_.Size() == 0; + return paired_device_cache_.Size() == 0 && temporary_device_cache_.Size() == 0; } // call this function when a new device is scanned @@ -155,14 +151,13 @@ bool MetricIdAllocator::SaveDevice(const RawAddress& mac_address) { } if (!temporary_device_cache_.Get(mac_address, &id)) { log::error( - "{}Failed to save device because device is not in " - "temporary_device_cache_", - LOGGING_TAG); + "{}Failed to save device because device is not in " + "temporary_device_cache_", + LOGGING_TAG); return false; } if (!temporary_device_cache_.Remove(mac_address)) { - log::error("{}Failed to remove device from temporary_device_cache_", - LOGGING_TAG); + log::error("{}Failed to remove device from temporary_device_cache_", LOGGING_TAG); return false; } auto evicted = paired_device_cache_.Put(mac_address, id); @@ -170,8 +165,7 @@ bool MetricIdAllocator::SaveDevice(const RawAddress& mac_address) { ForgetDevicePostprocess(evicted->first, evicted->second); } if (!save_id_callback_(mac_address, id)) { - log::error("{}Callback returned false after saving the device", - LOGGING_TAG); + log::error("{}Callback returned false after saving the device", LOGGING_TAG); return false; } return true; @@ -183,25 +177,21 @@ void MetricIdAllocator::ForgetDevice(const RawAddress& mac_address) { int id = 0; if (!paired_device_cache_.Get(mac_address, &id)) { log::error( - "{}Failed to forget device because device is not in " - "paired_device_cache_", - LOGGING_TAG); + "{}Failed to forget device because device is not in " + "paired_device_cache_", + LOGGING_TAG); return; } if (!paired_device_cache_.Remove(mac_address)) { - log::error("{}Failed to remove device from paired_device_cache_", - LOGGING_TAG); + log::error("{}Failed to remove device from paired_device_cache_", LOGGING_TAG); return; } ForgetDevicePostprocess(mac_address, id); } -bool MetricIdAllocator::IsValidId(const int id) { - return id >= kMinId && id <= kMaxId; -} +bool MetricIdAllocator::IsValidId(const int id) { return id >= kMinId && id <= kMaxId; } -void MetricIdAllocator::ForgetDevicePostprocess(const RawAddress& mac_address, - const int id) { +void MetricIdAllocator::ForgetDevicePostprocess(const RawAddress& mac_address, const int id) { id_set_.erase(id); forget_device_callback_(mac_address, id); } diff --git a/system/common/metric_id_allocator.h b/system/common/metric_id_allocator.h index cd18d5cfc8b..a89f03ab7f9 100644 --- a/system/common/metric_id_allocator.h +++ b/system/common/metric_id_allocator.h @@ -22,16 +22,16 @@ #include #include #include -#include "raw_address.h" #include "lru.h" +#include "raw_address.h" namespace bluetooth { namespace common { class MetricIdAllocator { - public: +public: using Callback = std::function; static const size_t kMaxNumUnpairedDevicesInMemory; @@ -60,8 +60,8 @@ class MetricIdAllocator { * successful id deletion for forgotten device, * @return true if successfully initialized */ - bool Init(const std::unordered_map& paired_device_map, - Callback save_id_callback, Callback forget_device_callback); + bool Init(const std::unordered_map& paired_device_map, Callback save_id_callback, + Callback forget_device_callback); /** * Close the allocator. should be called when Bluetooth process is killed @@ -111,11 +111,11 @@ class MetricIdAllocator { */ static bool IsValidId(const int id); - protected: +protected: // Singleton MetricIdAllocator(); - private: +private: static const std::string LOGGING_TAG; mutable std::mutex id_allocator_mutex_; diff --git a/system/common/metric_id_allocator_unittest.cc b/system/common/metric_id_allocator_unittest.cc index 68cc1ff8a7a..028540a94e6 100644 --- a/system/common/metric_id_allocator_unittest.cc +++ b/system/common/metric_id_allocator_unittest.cc @@ -52,9 +52,7 @@ std::unordered_map generateAddresses(const uint32_t num) { TEST(BluetoothMetricIdAllocatorTest, MetricIdAllocatorInitCloseTest) { auto& allocator = MetricIdAllocator::GetInstance(); std::unordered_map paired_device_map; - MetricIdAllocator::Callback callback = [](const RawAddress&, const int) { - return true; - }; + MetricIdAllocator::Callback callback = [](const RawAddress&, const int) { return true; }; EXPECT_TRUE(allocator.Init(paired_device_map, callback, callback)); EXPECT_FALSE(allocator.Init(paired_device_map, callback, callback)); EXPECT_TRUE(allocator.Close()); @@ -63,9 +61,7 @@ TEST(BluetoothMetricIdAllocatorTest, MetricIdAllocatorInitCloseTest) { TEST(BluetoothMetricIdAllocatorTest, MetricIdAllocatorNotCloseTest) { auto& allocator = MetricIdAllocator::GetInstance(); std::unordered_map paired_device_map; - MetricIdAllocator::Callback callback = [](const RawAddress&, const int) { - return true; - }; + MetricIdAllocator::Callback callback = [](const RawAddress&, const int) { return true; }; EXPECT_TRUE(allocator.Init(paired_device_map, callback, callback)); // should fail because it isn't closed @@ -76,9 +72,7 @@ TEST(BluetoothMetricIdAllocatorTest, MetricIdAllocatorNotCloseTest) { TEST(BluetoothMetricIdAllocatorTest, MetricIdAllocatorScanDeviceFromEmptyTest) { auto& allocator = MetricIdAllocator::GetInstance(); std::unordered_map paired_device_map; - MetricIdAllocator::Callback callback = [](const RawAddress&, const int) { - return true; - }; + MetricIdAllocator::Callback callback = [](const RawAddress&, const int) { return true; }; // test empty map, next id should be kMinId EXPECT_TRUE(allocator.Init(paired_device_map, callback, callback)); EXPECT_EQ(allocator.AllocateId(kthAddress(0)), MetricIdAllocator::kMinId); @@ -88,18 +82,14 @@ TEST(BluetoothMetricIdAllocatorTest, MetricIdAllocatorScanDeviceFromEmptyTest) { EXPECT_TRUE(allocator.Close()); } -TEST(BluetoothMetricIdAllocatorTest, - MetricIdAllocatorScanDeviceFromFilledTest) { +TEST(BluetoothMetricIdAllocatorTest, MetricIdAllocatorScanDeviceFromFilledTest) { auto& allocator = MetricIdAllocator::GetInstance(); std::unordered_map paired_device_map; - MetricIdAllocator::Callback callback = [](const RawAddress&, const int) { - return true; - }; + MetricIdAllocator::Callback callback = [](const RawAddress&, const int) { return true; }; int id = static_cast(MetricIdAllocator::kMaxNumPairedDevicesInMemory) + MetricIdAllocator::kMinId; // next id should be MetricIdAllocator::kMaxNumPairedDevicesInMemory - paired_device_map = - generateAddresses(MetricIdAllocator::kMaxNumPairedDevicesInMemory); + paired_device_map = generateAddresses(MetricIdAllocator::kMaxNumPairedDevicesInMemory); EXPECT_TRUE(allocator.Init(paired_device_map, callback, callback)); // try new values not in the map, should get new id. EXPECT_EQ(allocator.AllocateId(kthAddress(INT_MAX)), id); @@ -112,11 +102,9 @@ TEST(BluetoothMetricIdAllocatorTest, TEST(BluetoothMetricIdAllocatorTest, MetricIdAllocatorAllocateExistingTest) { auto& allocator = MetricIdAllocator::GetInstance(); std::unordered_map paired_device_map = - generateAddresses(MetricIdAllocator::kMaxNumPairedDevicesInMemory); + generateAddresses(MetricIdAllocator::kMaxNumPairedDevicesInMemory); - MetricIdAllocator::Callback callback = [](const RawAddress&, const int) { - return true; - }; + MetricIdAllocator::Callback callback = [](const RawAddress&, const int) { return true; }; int id = MetricIdAllocator::kMinId; // next id should be MetricIdAllocator::kMaxNumPairedDevicesInMemory EXPECT_TRUE(allocator.Init(paired_device_map, callback, callback)); @@ -134,21 +122,17 @@ TEST(BluetoothMetricIdAllocatorTest, MetricIdAllocatorMainTest1) { std::unordered_map paired_device_map; int dummy = 22; int* pointer = &dummy; - MetricIdAllocator::Callback save_callback = [pointer](const RawAddress&, - const int) { + MetricIdAllocator::Callback save_callback = [pointer](const RawAddress&, const int) { *pointer = *pointer * 2; return true; }; - MetricIdAllocator::Callback forget_callback = [pointer](const RawAddress&, - const int) { + MetricIdAllocator::Callback forget_callback = [pointer](const RawAddress&, const int) { *pointer = *pointer / 2; return true; }; - EXPECT_TRUE( - allocator.Init(paired_device_map, save_callback, forget_callback)); - EXPECT_EQ(allocator.AllocateId(RawAddress({0, 0, 0, 0, 0, 0})), - MetricIdAllocator::kMinId); + EXPECT_TRUE(allocator.Init(paired_device_map, save_callback, forget_callback)); + EXPECT_EQ(allocator.AllocateId(RawAddress({0, 0, 0, 0, 0, 0})), MetricIdAllocator::kMinId); // save it and make sure the callback is called EXPECT_TRUE(allocator.SaveDevice(RawAddress({0, 0, 0, 0, 0, 0}))); EXPECT_EQ(dummy, 44); @@ -158,10 +142,8 @@ TEST(BluetoothMetricIdAllocatorTest, MetricIdAllocatorMainTest1) { EXPECT_EQ(dummy, 44); // save it and make sure the callback is called - EXPECT_EQ(allocator.AllocateId(RawAddress({0, 0, 0, 0, 0, 2})), - MetricIdAllocator::kMinId + 1); - EXPECT_EQ(allocator.AllocateId(RawAddress({0, 0, 0, 0, 0, 3})), - MetricIdAllocator::kMinId + 2); + EXPECT_EQ(allocator.AllocateId(RawAddress({0, 0, 0, 0, 0, 2})), MetricIdAllocator::kMinId + 1); + EXPECT_EQ(allocator.AllocateId(RawAddress({0, 0, 0, 0, 0, 3})), MetricIdAllocator::kMinId + 2); EXPECT_TRUE(allocator.SaveDevice(RawAddress({0, 0, 0, 0, 0, 2}))); EXPECT_EQ(dummy, 88); EXPECT_TRUE(allocator.SaveDevice(RawAddress({0, 0, 0, 0, 0, 3}))); @@ -184,31 +166,25 @@ TEST(BluetoothMetricIdAllocatorTest, MetricIdAllocatorFullPairedMap) { auto& allocator = MetricIdAllocator::GetInstance(); // preset a full map std::unordered_map paired_device_map = - generateAddresses(MetricIdAllocator::kMaxNumPairedDevicesInMemory); + generateAddresses(MetricIdAllocator::kMaxNumPairedDevicesInMemory); int dummy = 243; int* pointer = &dummy; - MetricIdAllocator::Callback save_callback = [pointer](const RawAddress&, - const int) { + MetricIdAllocator::Callback save_callback = [pointer](const RawAddress&, const int) { *pointer = *pointer * 2; return true; }; - MetricIdAllocator::Callback forget_callback = [pointer](const RawAddress&, - const int) { + MetricIdAllocator::Callback forget_callback = [pointer](const RawAddress&, const int) { *pointer = *pointer / 3; return true; }; - EXPECT_TRUE( - allocator.Init(paired_device_map, save_callback, forget_callback)); + EXPECT_TRUE(allocator.Init(paired_device_map, save_callback, forget_callback)); // check if all preset ids are there. // comments based on kMaxNumPairedDevicesInMemory = 200. It can change. int key = 0; - for (key = 0; - key < static_cast(MetricIdAllocator::kMaxNumPairedDevicesInMemory); - key++) { - EXPECT_EQ(allocator.AllocateId(kthAddress(key)), - key + MetricIdAllocator::kMinId); + for (key = 0; key < static_cast(MetricIdAllocator::kMaxNumPairedDevicesInMemory); key++) { + EXPECT_EQ(allocator.AllocateId(kthAddress(key)), key + MetricIdAllocator::kMinId); } // paired: 0, 1, 2 ... 199, // scanned: @@ -312,8 +288,8 @@ TEST(BluetoothMetricIdAllocatorTest, MetricIdAllocatorFullPairedMap) { dummy = 4; EXPECT_TRUE(allocator.SaveDevice(kthAddress(0))); EXPECT_TRUE(allocator.SaveDevice(kthAddress(1))); - EXPECT_TRUE(allocator.SaveDevice( - kthAddress(MetricIdAllocator::kMaxNumPairedDevicesInMemory + 5))); + EXPECT_TRUE( + allocator.SaveDevice(kthAddress(MetricIdAllocator::kMaxNumPairedDevicesInMemory + 5))); EXPECT_EQ(dummy, 32); EXPECT_TRUE(allocator.Close()); @@ -324,36 +300,28 @@ TEST(BluetoothMetricIdAllocatorTest, MetricIdAllocatorFullScannedMap) { std::unordered_map paired_device_map; int dummy = 22; int* pointer = &dummy; - MetricIdAllocator::Callback save_callback = [pointer](const RawAddress&, - const int) { + MetricIdAllocator::Callback save_callback = [pointer](const RawAddress&, const int) { *pointer = *pointer * 2; return true; }; - MetricIdAllocator::Callback forget_callback = [pointer](const RawAddress&, - const int) { + MetricIdAllocator::Callback forget_callback = [pointer](const RawAddress&, const int) { *pointer = *pointer / 2; return true; }; - EXPECT_TRUE( - allocator.Init(paired_device_map, save_callback, forget_callback)); + EXPECT_TRUE(allocator.Init(paired_device_map, save_callback, forget_callback)); // allocate kMaxNumUnpairedDevicesInMemory ids // comments based on kMaxNumUnpairedDevicesInMemory = 200 - for (int key = 0; - key < - static_cast(MetricIdAllocator::kMaxNumUnpairedDevicesInMemory); + for (int key = 0; key < static_cast(MetricIdAllocator::kMaxNumUnpairedDevicesInMemory); key++) { - EXPECT_EQ(allocator.AllocateId(kthAddress(key)), - key + MetricIdAllocator::kMinId); + EXPECT_EQ(allocator.AllocateId(kthAddress(key)), key + MetricIdAllocator::kMinId); } // scanned: 0, 1, 2 ... 199, // paired: - int id = MetricIdAllocator::kMaxNumUnpairedDevicesInMemory + - MetricIdAllocator::kMinId; - RawAddress addr = - kthAddress(MetricIdAllocator::kMaxNumUnpairedDevicesInMemory); + int id = MetricIdAllocator::kMaxNumUnpairedDevicesInMemory + MetricIdAllocator::kMinId; + RawAddress addr = kthAddress(MetricIdAllocator::kMaxNumUnpairedDevicesInMemory); EXPECT_EQ(allocator.AllocateId(addr), id); // scanned: 1, 2 ... 199, 200 @@ -373,9 +341,7 @@ TEST(BluetoothMetricIdAllocatorTest, MetricIdAllocatorFullScannedMap) { // try to allocate for device 0, 1, 2, 3, 4....199 // we should have a new id every time, // since the scanned map is full at this point - for (int key = 0; - key < - static_cast(MetricIdAllocator::kMaxNumUnpairedDevicesInMemory); + for (int key = 0; key < static_cast(MetricIdAllocator::kMaxNumUnpairedDevicesInMemory); key++) { EXPECT_EQ(allocator.AllocateId(kthAddress(key)), id++); } @@ -387,24 +353,19 @@ TEST(BluetoothMetricIdAllocatorTest, MetricIdAllocatorMultiThreadPressureTest) { auto& allocator = MetricIdAllocator::GetInstance(); int dummy = 22; int* pointer = &dummy; - MetricIdAllocator::Callback save_callback = [pointer](const RawAddress&, - const int) { + MetricIdAllocator::Callback save_callback = [pointer](const RawAddress&, const int) { *pointer = *pointer + 1; return true; }; - MetricIdAllocator::Callback forget_callback = [pointer](const RawAddress&, - const int) { + MetricIdAllocator::Callback forget_callback = [pointer](const RawAddress&, const int) { *pointer = *pointer - 1; return true; }; - EXPECT_TRUE( - allocator.Init(paired_device_map, save_callback, forget_callback)); + EXPECT_TRUE(allocator.Init(paired_device_map, save_callback, forget_callback)); // make sure no deadlock std::vector workers; - for (int key = 0; - key < - static_cast(MetricIdAllocator::kMaxNumUnpairedDevicesInMemory); + for (int key = 0; key < static_cast(MetricIdAllocator::kMaxNumUnpairedDevicesInMemory); key++) { workers.push_back(std::thread([key]() { auto& allocator = MetricIdAllocator::GetInstance(); @@ -424,9 +385,7 @@ TEST(BluetoothMetricIdAllocatorTest, MetricIdAllocatorMultiThreadPressureTest) { TEST(BluetoothMetricIdAllocatorTest, MetricIdAllocatorWrapAroundTest1) { std::unordered_map paired_device_map; auto& allocator = MetricIdAllocator::GetInstance(); - MetricIdAllocator::Callback callback = [](const RawAddress&, const int) { - return true; - }; + MetricIdAllocator::Callback callback = [](const RawAddress&, const int) { return true; }; // make a sparse paired_device_map int min_id = MetricIdAllocator::kMinId; @@ -454,9 +413,7 @@ TEST(BluetoothMetricIdAllocatorTest, MetricIdAllocatorWrapAroundTest1) { TEST(BluetoothMetricIdAllocatorTest, MetricIdAllocatorWrapAroundTest2) { std::unordered_map paired_device_map; auto& allocator = MetricIdAllocator::GetInstance(); - MetricIdAllocator::Callback callback = [](const RawAddress&, const int) { - return true; - }; + MetricIdAllocator::Callback callback = [](const RawAddress&, const int) { return true; }; // make a sparse paired_device_map int min_id = MetricIdAllocator::kMinId; diff --git a/system/common/metrics.cc b/system/common/metrics.cc index badfcd851fa..c976e4063cd 100644 --- a/system/common/metrics.cc +++ b/system/common/metrics.cc @@ -38,13 +38,13 @@ #include "hci/address.h" #include "internal_include/bt_trace.h" #include "leaky_bonded_queue.h" +#include "main/shim/metric_id_api.h" #include "metric_id_allocator.h" #include "metrics/metrics_state.h" #include "os/metrics.h" #include "osi/include/osi.h" #include "time_util.h" #include "types/raw_address.h" -#include "main/shim/metric_id_api.h" namespace fmt { template <> @@ -67,14 +67,13 @@ struct formatter namespace bluetooth { namespace common { +using bluetooth::hci::Address; using bluetooth::metrics::BluetoothMetricsProto::A2DPSession; using bluetooth::metrics::BluetoothMetricsProto::A2dpSourceCodec; using bluetooth::metrics::BluetoothMetricsProto::BluetoothLog; using bluetooth::metrics::BluetoothMetricsProto::BluetoothSession; -using bluetooth::metrics::BluetoothMetricsProto:: - BluetoothSession_ConnectionTechnologyType; -using bluetooth::metrics::BluetoothMetricsProto:: - BluetoothSession_DisconnectReasonType; +using bluetooth::metrics::BluetoothMetricsProto::BluetoothSession_ConnectionTechnologyType; +using bluetooth::metrics::BluetoothMetricsProto::BluetoothSession_DisconnectReasonType; using bluetooth::metrics::BluetoothMetricsProto::DeviceInfo; using bluetooth::metrics::BluetoothMetricsProto::DeviceInfo_DeviceType; using bluetooth::metrics::BluetoothMetricsProto::HeadsetProfileConnectionStats; @@ -89,10 +88,8 @@ using bluetooth::metrics::BluetoothMetricsProto::ScanEvent_ScanEventType; using bluetooth::metrics::BluetoothMetricsProto::ScanEvent_ScanTechnologyType; using bluetooth::metrics::BluetoothMetricsProto::WakeEvent; using bluetooth::metrics::BluetoothMetricsProto::WakeEvent_WakeEventType; -using bluetooth::hci::Address; -static float combine_averages(float avg_a, int64_t ct_a, float avg_b, - int64_t ct_b) { +static float combine_averages(float avg_a, int64_t ct_a, float avg_b, int64_t ct_b) { if (ct_a > 0 && ct_b > 0) { return (avg_a * ct_a + avg_b * ct_b) / (ct_a + ct_b); } else if (ct_b > 0) { @@ -102,8 +99,7 @@ static float combine_averages(float avg_a, int64_t ct_a, float avg_b, } } -static int32_t combine_averages(int32_t avg_a, int64_t ct_a, int32_t avg_b, - int64_t ct_b) { +static int32_t combine_averages(int32_t avg_a, int64_t ct_a, int32_t avg_b, int64_t ct_b) { if (ct_a > 0 && ct_b > 0) { return (avg_a * ct_a + avg_b * ct_b) / (ct_a + ct_b); } else if (ct_b > 0) { @@ -122,43 +118,39 @@ void A2dpSessionMetrics::Update(const A2dpSessionMetrics& metrics) { if (media_timer_min_ms < 0) { media_timer_min_ms = metrics.media_timer_min_ms; } else { - media_timer_min_ms = - std::min(media_timer_min_ms, metrics.media_timer_min_ms); + media_timer_min_ms = std::min(media_timer_min_ms, metrics.media_timer_min_ms); } } if (metrics.media_timer_max_ms >= 0) { - media_timer_max_ms = - std::max(media_timer_max_ms, metrics.media_timer_max_ms); + media_timer_max_ms = std::max(media_timer_max_ms, metrics.media_timer_max_ms); } if (metrics.media_timer_avg_ms >= 0 && metrics.total_scheduling_count >= 0) { if (media_timer_avg_ms < 0 || total_scheduling_count < 0) { media_timer_avg_ms = metrics.media_timer_avg_ms; total_scheduling_count = metrics.total_scheduling_count; } else { - media_timer_avg_ms = combine_averages( - media_timer_avg_ms, total_scheduling_count, - metrics.media_timer_avg_ms, metrics.total_scheduling_count); + media_timer_avg_ms = + combine_averages(media_timer_avg_ms, total_scheduling_count, + metrics.media_timer_avg_ms, metrics.total_scheduling_count); total_scheduling_count += metrics.total_scheduling_count; } } if (metrics.buffer_overruns_max_count >= 0) { buffer_overruns_max_count = - std::max(buffer_overruns_max_count, metrics.buffer_overruns_max_count); + std::max(buffer_overruns_max_count, metrics.buffer_overruns_max_count); } if (metrics.buffer_overruns_total >= 0) { - buffer_overruns_total = - std::max(static_cast(0), buffer_overruns_total); + buffer_overruns_total = std::max(static_cast(0), buffer_overruns_total); buffer_overruns_total += metrics.buffer_overruns_total; } - if (metrics.buffer_underruns_average >= 0 && - metrics.buffer_underruns_count >= 0) { + if (metrics.buffer_underruns_average >= 0 && metrics.buffer_underruns_count >= 0) { if (buffer_underruns_average < 0 || buffer_underruns_count < 0) { buffer_underruns_average = metrics.buffer_underruns_average; buffer_underruns_count = metrics.buffer_underruns_count; } else { - buffer_underruns_average = combine_averages( - buffer_underruns_average, buffer_underruns_count, - metrics.buffer_underruns_average, metrics.buffer_underruns_count); + buffer_underruns_average = + combine_averages(buffer_underruns_average, buffer_underruns_count, + metrics.buffer_underruns_average, metrics.buffer_underruns_count); buffer_underruns_count += metrics.buffer_underruns_count; } } @@ -179,8 +171,7 @@ bool A2dpSessionMetrics::operator==(const A2dpSessionMetrics& rhs) const { buffer_overruns_max_count == rhs.buffer_overruns_max_count && buffer_overruns_total == rhs.buffer_overruns_total && buffer_underruns_average == rhs.buffer_underruns_average && - buffer_underruns_count == rhs.buffer_underruns_count && - codec_index == rhs.codec_index && + buffer_underruns_count == rhs.buffer_underruns_count && codec_index == rhs.codec_index && is_a2dp_offload == rhs.is_a2dp_offload; } @@ -198,37 +189,32 @@ static DeviceInfo_DeviceType get_device_type(device_type_t type) { } } -static BluetoothSession_ConnectionTechnologyType get_connection_tech_type( - connection_tech_t type) { +static BluetoothSession_ConnectionTechnologyType get_connection_tech_type(connection_tech_t type) { switch (type) { case CONNECTION_TECHNOLOGY_TYPE_LE: return BluetoothSession_ConnectionTechnologyType:: - BluetoothSession_ConnectionTechnologyType_CONNECTION_TECHNOLOGY_TYPE_LE; + BluetoothSession_ConnectionTechnologyType_CONNECTION_TECHNOLOGY_TYPE_LE; case CONNECTION_TECHNOLOGY_TYPE_BREDR: return BluetoothSession_ConnectionTechnologyType:: - BluetoothSession_ConnectionTechnologyType_CONNECTION_TECHNOLOGY_TYPE_BREDR; + BluetoothSession_ConnectionTechnologyType_CONNECTION_TECHNOLOGY_TYPE_BREDR; case CONNECTION_TECHNOLOGY_TYPE_UNKNOWN: default: return BluetoothSession_ConnectionTechnologyType:: - BluetoothSession_ConnectionTechnologyType_CONNECTION_TECHNOLOGY_TYPE_UNKNOWN; + BluetoothSession_ConnectionTechnologyType_CONNECTION_TECHNOLOGY_TYPE_UNKNOWN; } } static ScanEvent_ScanTechnologyType get_scan_tech_type(scan_tech_t type) { switch (type) { case SCAN_TECH_TYPE_LE: - return ScanEvent_ScanTechnologyType:: - ScanEvent_ScanTechnologyType_SCAN_TECH_TYPE_LE; + return ScanEvent_ScanTechnologyType::ScanEvent_ScanTechnologyType_SCAN_TECH_TYPE_LE; case SCAN_TECH_TYPE_BREDR: - return ScanEvent_ScanTechnologyType:: - ScanEvent_ScanTechnologyType_SCAN_TECH_TYPE_BREDR; + return ScanEvent_ScanTechnologyType::ScanEvent_ScanTechnologyType_SCAN_TECH_TYPE_BREDR; case SCAN_TECH_TYPE_BOTH: - return ScanEvent_ScanTechnologyType:: - ScanEvent_ScanTechnologyType_SCAN_TECH_TYPE_BOTH; + return ScanEvent_ScanTechnologyType::ScanEvent_ScanTechnologyType_SCAN_TECH_TYPE_BOTH; case SCAN_TYPE_UNKNOWN: default: - return ScanEvent_ScanTechnologyType:: - ScanEvent_ScanTechnologyType_SCAN_TYPE_UNKNOWN; + return ScanEvent_ScanTechnologyType::ScanEvent_ScanTechnologyType_SCAN_TYPE_UNKNOWN; } } @@ -244,19 +230,17 @@ static WakeEvent_WakeEventType get_wake_event_type(wake_event_type_t type) { } } -static BluetoothSession_DisconnectReasonType get_disconnect_reason_type( - disconnect_reason_t type) { +static BluetoothSession_DisconnectReasonType get_disconnect_reason_type(disconnect_reason_t type) { switch (type) { case DISCONNECT_REASON_METRICS_DUMP: return BluetoothSession_DisconnectReasonType:: - BluetoothSession_DisconnectReasonType_METRICS_DUMP; + BluetoothSession_DisconnectReasonType_METRICS_DUMP; case DISCONNECT_REASON_NEXT_START_WITHOUT_END_PREVIOUS: return BluetoothSession_DisconnectReasonType:: - BluetoothSession_DisconnectReasonType_NEXT_START_WITHOUT_END_PREVIOUS; + BluetoothSession_DisconnectReasonType_NEXT_START_WITHOUT_END_PREVIOUS; case DISCONNECT_REASON_UNKNOWN: default: - return BluetoothSession_DisconnectReasonType:: - BluetoothSession_DisconnectReasonType_UNKNOWN; + return BluetoothSession_DisconnectReasonType::BluetoothSession_DisconnectReasonType_UNKNOWN; } } @@ -278,10 +262,9 @@ static A2dpSourceCodec get_a2dp_source_codec(int64_t codec_index) { } struct BluetoothMetricsLogger::impl { - impl(size_t max_bluetooth_session, size_t max_pair_event, - size_t max_wake_event, size_t max_scan_event) - : bt_session_queue_( - new LeakyBondedQueue(max_bluetooth_session)), + impl(size_t max_bluetooth_session, size_t max_pair_event, size_t max_wake_event, + size_t max_scan_event) + : bt_session_queue_(new LeakyBondedQueue(max_bluetooth_session)), pair_event_queue_(new LeakyBondedQueue(max_pair_event)), wake_event_queue_(new LeakyBondedQueue(max_wake_event)), scan_event_queue_(new LeakyBondedQueue(max_scan_event)) { @@ -294,8 +277,7 @@ struct BluetoothMetricsLogger::impl { /* Bluetooth log lock protected */ BluetoothLog* bluetooth_log_; - std::array - headset_profile_connection_counts_; + std::array headset_profile_connection_counts_; std::recursive_mutex bluetooth_log_lock_; /* End Bluetooth log lock protected */ /* Bluetooth session lock protected */ @@ -311,13 +293,11 @@ struct BluetoothMetricsLogger::impl { }; BluetoothMetricsLogger::BluetoothMetricsLogger() - : pimpl_(new impl(kMaxNumBluetoothSession, kMaxNumPairEvent, - kMaxNumWakeEvent, kMaxNumScanEvent)) {} + : pimpl_(new impl(kMaxNumBluetoothSession, kMaxNumPairEvent, kMaxNumWakeEvent, + kMaxNumScanEvent)) {} -void BluetoothMetricsLogger::LogPairEvent(uint32_t disconnect_reason, - uint64_t timestamp_ms, - uint32_t device_class, - device_type_t device_type) { +void BluetoothMetricsLogger::LogPairEvent(uint32_t disconnect_reason, uint64_t timestamp_ms, + uint32_t device_class, device_type_t device_type) { PairEvent* event = new PairEvent(); DeviceInfo* info = event->mutable_device_paired_with(); info->set_device_class(device_class); @@ -327,15 +307,12 @@ void BluetoothMetricsLogger::LogPairEvent(uint32_t disconnect_reason, pimpl_->pair_event_queue_->Enqueue(event); { std::lock_guard lock(pimpl_->bluetooth_log_lock_); - pimpl_->bluetooth_log_->set_num_pair_event( - pimpl_->bluetooth_log_->num_pair_event() + 1); + pimpl_->bluetooth_log_->set_num_pair_event(pimpl_->bluetooth_log_->num_pair_event() + 1); } } -void BluetoothMetricsLogger::LogWakeEvent(wake_event_type_t type, - const std::string& requestor, - const std::string& name, - uint64_t timestamp_ms) { +void BluetoothMetricsLogger::LogWakeEvent(wake_event_type_t type, const std::string& requestor, + const std::string& name, uint64_t timestamp_ms) { WakeEvent* event = new WakeEvent(); event->set_wake_event_type(get_wake_event_type(type)); event->set_requestor(requestor); @@ -344,13 +321,11 @@ void BluetoothMetricsLogger::LogWakeEvent(wake_event_type_t type, pimpl_->wake_event_queue_->Enqueue(event); { std::lock_guard lock(pimpl_->bluetooth_log_lock_); - pimpl_->bluetooth_log_->set_num_wake_event( - pimpl_->bluetooth_log_->num_wake_event() + 1); + pimpl_->bluetooth_log_->set_num_wake_event(pimpl_->bluetooth_log_->num_wake_event() + 1); } } -void BluetoothMetricsLogger::LogScanEvent(bool start, - const std::string& initator, +void BluetoothMetricsLogger::LogScanEvent(bool start, const std::string& initiator, scan_tech_t type, uint32_t results, uint64_t timestamp_ms) { ScanEvent* event = new ScanEvent(); @@ -359,24 +334,22 @@ void BluetoothMetricsLogger::LogScanEvent(bool start, } else { event->set_scan_event_type(ScanEvent::SCAN_EVENT_STOP); } - event->set_initiator(initator); + event->set_initiator(initiator); event->set_scan_technology_type(get_scan_tech_type(type)); event->set_number_results(results); event->set_event_time_millis(timestamp_ms); pimpl_->scan_event_queue_->Enqueue(event); { std::lock_guard lock(pimpl_->bluetooth_log_lock_); - pimpl_->bluetooth_log_->set_num_scan_event( - pimpl_->bluetooth_log_->num_scan_event() + 1); + pimpl_->bluetooth_log_->set_num_scan_event(pimpl_->bluetooth_log_->num_scan_event() + 1); } } -void BluetoothMetricsLogger::LogBluetoothSessionStart( - connection_tech_t connection_tech_type, uint64_t timestamp_ms) { +void BluetoothMetricsLogger::LogBluetoothSessionStart(connection_tech_t connection_tech_type, + uint64_t timestamp_ms) { std::lock_guard lock(pimpl_->bluetooth_session_lock_); if (pimpl_->bluetooth_session_ != nullptr) { - LogBluetoothSessionEnd(DISCONNECT_REASON_NEXT_START_WITHOUT_END_PREVIOUS, - 0); + LogBluetoothSessionEnd(DISCONNECT_REASON_NEXT_START_WITHOUT_END_PREVIOUS, 0); } if (timestamp_ms == 0) { timestamp_ms = bluetooth::common::time_get_os_boottime_ms(); @@ -384,11 +357,11 @@ void BluetoothMetricsLogger::LogBluetoothSessionStart( pimpl_->bluetooth_session_start_time_ms_ = timestamp_ms; pimpl_->bluetooth_session_ = new BluetoothSession(); pimpl_->bluetooth_session_->set_connection_technology_type( - get_connection_tech_type(connection_tech_type)); + get_connection_tech_type(connection_tech_type)); } -void BluetoothMetricsLogger::LogBluetoothSessionEnd( - disconnect_reason_t disconnect_reason, uint64_t timestamp_ms) { +void BluetoothMetricsLogger::LogBluetoothSessionEnd(disconnect_reason_t disconnect_reason, + uint64_t timestamp_ms) { std::lock_guard lock(pimpl_->bluetooth_session_lock_); if (pimpl_->bluetooth_session_ == nullptr) { return; @@ -396,23 +369,22 @@ void BluetoothMetricsLogger::LogBluetoothSessionEnd( if (timestamp_ms == 0) { timestamp_ms = bluetooth::common::time_get_os_boottime_ms(); } - int64_t session_duration_sec = - (timestamp_ms - pimpl_->bluetooth_session_start_time_ms_) / 1000; + int64_t session_duration_sec = (timestamp_ms - pimpl_->bluetooth_session_start_time_ms_) / 1000; pimpl_->bluetooth_session_->set_session_duration_sec(session_duration_sec); pimpl_->bluetooth_session_->set_disconnect_reason_type( - get_disconnect_reason_type(disconnect_reason)); + get_disconnect_reason_type(disconnect_reason)); pimpl_->bt_session_queue_->Enqueue(pimpl_->bluetooth_session_); pimpl_->bluetooth_session_ = nullptr; pimpl_->a2dp_session_metrics_ = A2dpSessionMetrics(); { std::lock_guard log_lock(pimpl_->bluetooth_log_lock_); pimpl_->bluetooth_log_->set_num_bluetooth_session( - pimpl_->bluetooth_log_->num_bluetooth_session() + 1); + pimpl_->bluetooth_log_->num_bluetooth_session() + 1); } } -void BluetoothMetricsLogger::LogBluetoothSessionDeviceInfo( - uint32_t device_class, device_type_t device_type) { +void BluetoothMetricsLogger::LogBluetoothSessionDeviceInfo(uint32_t device_class, + device_type_t device_type) { std::lock_guard lock(pimpl_->bluetooth_session_lock_); if (pimpl_->bluetooth_session_ == nullptr) { LogBluetoothSessionStart(CONNECTION_TECHNOLOGY_TYPE_UNKNOWN, 0); @@ -422,8 +394,7 @@ void BluetoothMetricsLogger::LogBluetoothSessionDeviceInfo( info->set_device_type(DeviceInfo::DEVICE_TYPE_BREDR); } -void BluetoothMetricsLogger::LogA2dpSession( - const A2dpSessionMetrics& a2dp_session_metrics) { +void BluetoothMetricsLogger::LogA2dpSession(const A2dpSessionMetrics& a2dp_session_metrics) { std::lock_guard lock(pimpl_->bluetooth_session_lock_); if (pimpl_->bluetooth_session_ == nullptr) { // When no bluetooth session exist, create one on system's behalf @@ -434,32 +405,22 @@ void BluetoothMetricsLogger::LogA2dpSession( // Accumulate metrics pimpl_->a2dp_session_metrics_.Update(a2dp_session_metrics); // Get or allocate new A2DP session object - A2DPSession* a2dp_session = - pimpl_->bluetooth_session_->mutable_a2dp_session(); - a2dp_session->set_audio_duration_millis( - pimpl_->a2dp_session_metrics_.audio_duration_ms); - a2dp_session->set_media_timer_min_millis( - pimpl_->a2dp_session_metrics_.media_timer_min_ms); - a2dp_session->set_media_timer_max_millis( - pimpl_->a2dp_session_metrics_.media_timer_max_ms); - a2dp_session->set_media_timer_avg_millis( - pimpl_->a2dp_session_metrics_.media_timer_avg_ms); + A2DPSession* a2dp_session = pimpl_->bluetooth_session_->mutable_a2dp_session(); + a2dp_session->set_audio_duration_millis(pimpl_->a2dp_session_metrics_.audio_duration_ms); + a2dp_session->set_media_timer_min_millis(pimpl_->a2dp_session_metrics_.media_timer_min_ms); + a2dp_session->set_media_timer_max_millis(pimpl_->a2dp_session_metrics_.media_timer_max_ms); + a2dp_session->set_media_timer_avg_millis(pimpl_->a2dp_session_metrics_.media_timer_avg_ms); a2dp_session->set_buffer_overruns_max_count( - pimpl_->a2dp_session_metrics_.buffer_overruns_max_count); - a2dp_session->set_buffer_overruns_total( - pimpl_->a2dp_session_metrics_.buffer_overruns_total); + pimpl_->a2dp_session_metrics_.buffer_overruns_max_count); + a2dp_session->set_buffer_overruns_total(pimpl_->a2dp_session_metrics_.buffer_overruns_total); a2dp_session->set_buffer_underruns_average( - pimpl_->a2dp_session_metrics_.buffer_underruns_average); - a2dp_session->set_buffer_underruns_count( - pimpl_->a2dp_session_metrics_.buffer_underruns_count); - a2dp_session->set_source_codec( - get_a2dp_source_codec(pimpl_->a2dp_session_metrics_.codec_index)); - a2dp_session->set_is_a2dp_offload( - pimpl_->a2dp_session_metrics_.is_a2dp_offload); + pimpl_->a2dp_session_metrics_.buffer_underruns_average); + a2dp_session->set_buffer_underruns_count(pimpl_->a2dp_session_metrics_.buffer_underruns_count); + a2dp_session->set_source_codec(get_a2dp_source_codec(pimpl_->a2dp_session_metrics_.codec_index)); + a2dp_session->set_is_a2dp_offload(pimpl_->a2dp_session_metrics_.is_a2dp_offload); } -void BluetoothMetricsLogger::LogHeadsetProfileRfcConnection( - tBTA_SERVICE_ID service_id) { +void BluetoothMetricsLogger::LogHeadsetProfileRfcConnection(tBTA_SERVICE_ID service_id) { std::lock_guard lock(pimpl_->bluetooth_log_lock_); switch (service_id) { case BTA_HSP_SERVICE_ID: @@ -469,8 +430,7 @@ void BluetoothMetricsLogger::LogHeadsetProfileRfcConnection( pimpl_->headset_profile_connection_counts_[HeadsetProfileType::HFP]++; break; default: - pimpl_->headset_profile_connection_counts_ - [HeadsetProfileType::HEADSET_PROFILE_UNKNOWN]++; + pimpl_->headset_profile_connection_counts_[HeadsetProfileType::HEADSET_PROFILE_UNKNOWN]++; break; } return; @@ -506,14 +466,12 @@ void BluetoothMetricsLogger::WriteBase64(int fd) { void BluetoothMetricsLogger::CutoffSession() { std::lock_guard lock(pimpl_->bluetooth_session_lock_); if (pimpl_->bluetooth_session_ != nullptr) { - BluetoothSession* new_bt_session = - new BluetoothSession(*pimpl_->bluetooth_session_); + BluetoothSession* new_bt_session = new BluetoothSession(*pimpl_->bluetooth_session_); new_bt_session->clear_a2dp_session(); new_bt_session->clear_rfcomm_session(); LogBluetoothSessionEnd(DISCONNECT_REASON_METRICS_DUMP, 0); pimpl_->bluetooth_session_ = new_bt_session; - pimpl_->bluetooth_session_start_time_ms_ = - bluetooth::common::time_get_os_boottime_ms(); + pimpl_->bluetooth_session_start_time_ms_ = bluetooth::common::time_get_os_boottime_ms(); pimpl_->a2dp_session_metrics_ = A2dpSessionMetrics(); } } @@ -524,44 +482,38 @@ void BluetoothMetricsLogger::Build() { BluetoothLog* bluetooth_log = pimpl_->bluetooth_log_; while (!pimpl_->bt_session_queue_->Empty() && static_cast(bluetooth_log->session_size()) <= - pimpl_->bt_session_queue_->Capacity()) { - bluetooth_log->mutable_session()->AddAllocated( - pimpl_->bt_session_queue_->Dequeue()); + pimpl_->bt_session_queue_->Capacity()) { + bluetooth_log->mutable_session()->AddAllocated(pimpl_->bt_session_queue_->Dequeue()); } while (!pimpl_->pair_event_queue_->Empty() && static_cast(bluetooth_log->pair_event_size()) <= - pimpl_->pair_event_queue_->Capacity()) { - bluetooth_log->mutable_pair_event()->AddAllocated( - pimpl_->pair_event_queue_->Dequeue()); + pimpl_->pair_event_queue_->Capacity()) { + bluetooth_log->mutable_pair_event()->AddAllocated(pimpl_->pair_event_queue_->Dequeue()); } while (!pimpl_->scan_event_queue_->Empty() && static_cast(bluetooth_log->scan_event_size()) <= - pimpl_->scan_event_queue_->Capacity()) { - bluetooth_log->mutable_scan_event()->AddAllocated( - pimpl_->scan_event_queue_->Dequeue()); + pimpl_->scan_event_queue_->Capacity()) { + bluetooth_log->mutable_scan_event()->AddAllocated(pimpl_->scan_event_queue_->Dequeue()); } while (!pimpl_->wake_event_queue_->Empty() && static_cast(bluetooth_log->wake_event_size()) <= - pimpl_->wake_event_queue_->Capacity()) { - bluetooth_log->mutable_wake_event()->AddAllocated( - pimpl_->wake_event_queue_->Dequeue()); + pimpl_->wake_event_queue_->Capacity()) { + bluetooth_log->mutable_wake_event()->AddAllocated(pimpl_->wake_event_queue_->Dequeue()); } while (!pimpl_->bt_session_queue_->Empty() && static_cast(bluetooth_log->wake_event_size()) <= - pimpl_->wake_event_queue_->Capacity()) { - bluetooth_log->mutable_wake_event()->AddAllocated( - pimpl_->wake_event_queue_->Dequeue()); + pimpl_->wake_event_queue_->Capacity()) { + bluetooth_log->mutable_wake_event()->AddAllocated(pimpl_->wake_event_queue_->Dequeue()); } for (size_t i = 0; i < HeadsetProfileType_ARRAYSIZE; ++i) { int num_times_connected = pimpl_->headset_profile_connection_counts_[i]; if (HeadsetProfileType_IsValid(i) && num_times_connected > 0) { HeadsetProfileConnectionStats* headset_profile_connection_stats = - bluetooth_log->add_headset_profile_connection_stats(); + bluetooth_log->add_headset_profile_connection_stats(); // Able to static_cast because HeadsetProfileType_IsValid(i) is true headset_profile_connection_stats->set_headset_profile_type( - static_cast(i)); - headset_profile_connection_stats->set_num_times_connected( - num_times_connected); + static_cast(i)); + headset_profile_connection_stats->set_num_times_connected(num_times_connected); } } pimpl_->headset_profile_connection_counts_.fill(0); @@ -591,11 +543,9 @@ void BluetoothMetricsLogger::Reset() { pimpl_->scan_event_queue_->Clear(); } -void LogLinkLayerConnectionEvent(const RawAddress* address, - uint32_t connection_handle, - android::bluetooth::DirectionEnum direction, - uint16_t link_type, uint32_t hci_cmd, - uint16_t hci_event, uint16_t hci_ble_event, +void LogLinkLayerConnectionEvent(const RawAddress* address, uint32_t connection_handle, + android::bluetooth::DirectionEnum direction, uint16_t link_type, + uint32_t hci_cmd, uint16_t hci_event, uint16_t hci_ble_event, uint16_t cmd_status, uint16_t reason_code) { std::string obfuscated_id; int metric_id = 0; @@ -606,22 +556,20 @@ void LogLinkLayerConnectionEvent(const RawAddress* address, // nullptr and size 0 represent missing value for obfuscated_id BytesField bytes_field(address != nullptr ? obfuscated_id.c_str() : nullptr, address != nullptr ? obfuscated_id.size() : 0); - int ret = - stats_write(BLUETOOTH_LINK_LAYER_CONNECTION_EVENT, bytes_field, - connection_handle, direction, link_type, hci_cmd, hci_event, - hci_ble_event, cmd_status, reason_code, metric_id); + int ret = stats_write(BLUETOOTH_LINK_LAYER_CONNECTION_EVENT, bytes_field, connection_handle, + direction, link_type, hci_cmd, hci_event, hci_ble_event, cmd_status, + reason_code, metric_id); if (ret < 0) { log::warn( - "failed to log status 0x{:x}, reason 0x{:x} from cmd 0x{:x}, event " - "0x{:x}, ble_event 0x{:x} for {}, handle {}, type 0x{:x}, error {}", - cmd_status, reason_code, hci_cmd, hci_event, hci_ble_event, *address, - connection_handle, link_type, ret); + "failed to log status 0x{:x}, reason 0x{:x} from cmd 0x{:x}, event " + "0x{:x}, ble_event 0x{:x} for {}, handle {}, type 0x{:x}, error {}", + cmd_status, reason_code, hci_cmd, hci_event, hci_ble_event, *address, connection_handle, + link_type, ret); } } void LogHciTimeoutEvent(uint32_t hci_cmd) { - int ret = stats_write(BLUETOOTH_HCI_TIMEOUT_REPORTED, - static_cast(hci_cmd)); + int ret = stats_write(BLUETOOTH_HCI_TIMEOUT_REPORTED, static_cast(hci_cmd)); if (ret < 0) { log::warn("failed for opcode 0x{:x}, error {}", hci_cmd, ret); } @@ -629,18 +577,17 @@ void LogHciTimeoutEvent(uint32_t hci_cmd) { void LogRemoteVersionInfo(uint16_t handle, uint8_t status, uint8_t version, uint16_t manufacturer_name, uint16_t subversion) { - int ret = stats_write(BLUETOOTH_REMOTE_VERSION_INFO_REPORTED, handle, status, - version, manufacturer_name, subversion); + int ret = stats_write(BLUETOOTH_REMOTE_VERSION_INFO_REPORTED, handle, status, version, + manufacturer_name, subversion); if (ret < 0) { log::warn( - "failed for handle {}, status 0x{:x}, version 0x{:x}, " - "manufacturer_name 0x{:x}, subversion 0x{:x}, error {}", - handle, status, version, manufacturer_name, subversion, ret); + "failed for handle {}, status 0x{:x}, version 0x{:x}, " + "manufacturer_name 0x{:x}, subversion 0x{:x}, error {}", + handle, status, version, manufacturer_name, subversion, ret); } } -void LogA2dpAudioUnderrunEvent(const RawAddress& address, - uint64_t encoding_interval_millis, +void LogA2dpAudioUnderrunEvent(const RawAddress& address, uint64_t encoding_interval_millis, int num_missing_pcm_bytes) { std::string obfuscated_id; int metric_id = 0; @@ -652,21 +599,18 @@ void LogA2dpAudioUnderrunEvent(const RawAddress& address, BytesField bytes_field(address.IsEmpty() ? nullptr : obfuscated_id.c_str(), address.IsEmpty() ? 0 : obfuscated_id.size()); int64_t encoding_interval_nanos = encoding_interval_millis * 1000000; - int ret = - stats_write(BLUETOOTH_A2DP_AUDIO_UNDERRUN_REPORTED, bytes_field, - encoding_interval_nanos, num_missing_pcm_bytes, metric_id); + int ret = stats_write(BLUETOOTH_A2DP_AUDIO_UNDERRUN_REPORTED, bytes_field, + encoding_interval_nanos, num_missing_pcm_bytes, metric_id); if (ret < 0) { log::warn( - "failed for {}, encoding_interval_nanos {}, num_missing_pcm_bytes {}, " - "error {}", - address, encoding_interval_nanos, num_missing_pcm_bytes, ret); + "failed for {}, encoding_interval_nanos {}, num_missing_pcm_bytes {}, " + "error {}", + address, encoding_interval_nanos, num_missing_pcm_bytes, ret); } } -void LogA2dpAudioOverrunEvent(const RawAddress& address, - uint64_t encoding_interval_millis, - int num_dropped_buffers, - int num_dropped_encoded_frames, +void LogA2dpAudioOverrunEvent(const RawAddress& address, uint64_t encoding_interval_millis, + int num_dropped_buffers, int num_dropped_encoded_frames, int num_dropped_encoded_bytes) { std::string obfuscated_id; int metric_id = 0; @@ -678,22 +622,20 @@ void LogA2dpAudioOverrunEvent(const RawAddress& address, BytesField bytes_field(address.IsEmpty() ? nullptr : obfuscated_id.c_str(), address.IsEmpty() ? 0 : obfuscated_id.size()); int64_t encoding_interval_nanos = encoding_interval_millis * 1000000; - int ret = stats_write(BLUETOOTH_A2DP_AUDIO_OVERRUN_REPORTED, bytes_field, - encoding_interval_nanos, num_dropped_buffers, - num_dropped_encoded_frames, num_dropped_encoded_bytes, + int ret = stats_write(BLUETOOTH_A2DP_AUDIO_OVERRUN_REPORTED, bytes_field, encoding_interval_nanos, + num_dropped_buffers, num_dropped_encoded_frames, num_dropped_encoded_bytes, metric_id); if (ret < 0) { log::warn( - "failed to log for {}, encoding_interval_nanos {}, num_dropped_buffers " - "{}, num_dropped_encoded_frames {}, num_dropped_encoded_bytes {}, " - "error {}", - address, encoding_interval_nanos, num_dropped_buffers, - num_dropped_encoded_frames, num_dropped_encoded_bytes, ret); + "failed to log for {}, encoding_interval_nanos {}, num_dropped_buffers " + "{}, num_dropped_encoded_frames {}, num_dropped_encoded_bytes {}, " + "error {}", + address, encoding_interval_nanos, num_dropped_buffers, num_dropped_encoded_frames, + num_dropped_encoded_bytes, ret); } } -void LogA2dpPlaybackEvent(const RawAddress& address, int playback_state, - int audio_coding_mode) { +void LogA2dpPlaybackEvent(const RawAddress& address, int playback_state, int audio_coding_mode) { std::string obfuscated_id; int metric_id = 0; if (!address.IsEmpty()) { @@ -703,18 +645,18 @@ void LogA2dpPlaybackEvent(const RawAddress& address, int playback_state, // nullptr and size 0 represent missing value for obfuscated_id BytesField bytes_field(address.IsEmpty() ? nullptr : obfuscated_id.c_str(), address.IsEmpty() ? 0 : obfuscated_id.size()); - int ret = stats_write(BLUETOOTH_A2DP_PLAYBACK_STATE_CHANGED, bytes_field, - playback_state, audio_coding_mode, metric_id); + int ret = stats_write(BLUETOOTH_A2DP_PLAYBACK_STATE_CHANGED, bytes_field, playback_state, + audio_coding_mode, metric_id); if (ret < 0) { log::warn( - "failed to log for {}, playback_state {}, audio_coding_mode {}, error " - "{}", - address, playback_state, audio_coding_mode, ret); + "failed to log for {}, playback_state {}, audio_coding_mode {}, error " + "{}", + address, playback_state, audio_coding_mode, ret); } } -void LogReadRssiResult(const RawAddress& address, uint16_t handle, - uint32_t cmd_status, int8_t rssi) { +void LogReadRssiResult(const RawAddress& address, uint16_t handle, uint32_t cmd_status, + int8_t rssi) { std::string obfuscated_id; int metric_id = 0; if (!address.IsEmpty()) { @@ -724,17 +666,16 @@ void LogReadRssiResult(const RawAddress& address, uint16_t handle, // nullptr and size 0 represent missing value for obfuscated_id BytesField bytes_field(address.IsEmpty() ? nullptr : obfuscated_id.c_str(), address.IsEmpty() ? 0 : obfuscated_id.size()); - int ret = stats_write(BLUETOOTH_DEVICE_RSSI_REPORTED, bytes_field, handle, - cmd_status, rssi, metric_id); + int ret = stats_write(BLUETOOTH_DEVICE_RSSI_REPORTED, bytes_field, handle, cmd_status, rssi, + metric_id); if (ret < 0) { - log::warn("failed for {}, handle {}, status 0x{:x}, rssi {} dBm, error {}", - address, handle, cmd_status, rssi, ret); + log::warn("failed for {}, handle {}, status 0x{:x}, rssi {} dBm, error {}", address, handle, + cmd_status, rssi, ret); } } -void LogReadFailedContactCounterResult(const RawAddress& address, - uint16_t handle, uint32_t cmd_status, - int32_t failed_contact_counter) { +void LogReadFailedContactCounterResult(const RawAddress& address, uint16_t handle, + uint32_t cmd_status, int32_t failed_contact_counter) { std::string obfuscated_id; int metric_id = 0; if (!address.IsEmpty()) { @@ -744,19 +685,17 @@ void LogReadFailedContactCounterResult(const RawAddress& address, // nullptr and size 0 represent missing value for obfuscated_id BytesField bytes_field(address.IsEmpty() ? nullptr : obfuscated_id.c_str(), address.IsEmpty() ? 0 : obfuscated_id.size()); - int ret = - stats_write(BLUETOOTH_DEVICE_FAILED_CONTACT_COUNTER_REPORTED, bytes_field, - handle, cmd_status, failed_contact_counter, metric_id); + int ret = stats_write(BLUETOOTH_DEVICE_FAILED_CONTACT_COUNTER_REPORTED, bytes_field, handle, + cmd_status, failed_contact_counter, metric_id); if (ret < 0) { log::warn( - "failed for {}, handle {}, status 0x{:x}, failed_contact_counter {} " - "packets, error {}", - address, handle, cmd_status, failed_contact_counter, ret); + "failed for {}, handle {}, status 0x{:x}, failed_contact_counter {} " + "packets, error {}", + address, handle, cmd_status, failed_contact_counter, ret); } } -void LogReadTxPowerLevelResult(const RawAddress& address, uint16_t handle, - uint32_t cmd_status, +void LogReadTxPowerLevelResult(const RawAddress& address, uint16_t handle, uint32_t cmd_status, int32_t transmit_power_level) { std::string obfuscated_id; int metric_id = 0; @@ -767,19 +706,18 @@ void LogReadTxPowerLevelResult(const RawAddress& address, uint16_t handle, // nullptr and size 0 represent missing value for obfuscated_id BytesField bytes_field(address.IsEmpty() ? nullptr : obfuscated_id.c_str(), address.IsEmpty() ? 0 : obfuscated_id.size()); - int ret = stats_write(BLUETOOTH_DEVICE_TX_POWER_LEVEL_REPORTED, bytes_field, - handle, cmd_status, transmit_power_level, metric_id); + int ret = stats_write(BLUETOOTH_DEVICE_TX_POWER_LEVEL_REPORTED, bytes_field, handle, cmd_status, + transmit_power_level, metric_id); if (ret < 0) { log::warn( - "failed for {}, handle {}, status 0x{:x}, transmit_power_level {} " - "packets, error {}", - address, handle, cmd_status, transmit_power_level, ret); + "failed for {}, handle {}, status 0x{:x}, transmit_power_level {} " + "packets, error {}", + address, handle, cmd_status, transmit_power_level, ret); } } void LogSmpPairingEvent(const RawAddress& address, uint8_t smp_cmd, - android::bluetooth::DirectionEnum direction, - uint8_t smp_fail_reason) { + android::bluetooth::DirectionEnum direction, uint8_t smp_fail_reason) { std::string obfuscated_id; int metric_id = 0; if (!address.IsEmpty()) { @@ -787,22 +725,21 @@ void LogSmpPairingEvent(const RawAddress& address, uint8_t smp_cmd, metric_id = MetricIdAllocator::GetInstance().AllocateId(address); } // nullptr and size 0 represent missing value for obfuscated_id - BytesField obfuscated_id_field( - address.IsEmpty() ? nullptr : obfuscated_id.c_str(), - address.IsEmpty() ? 0 : obfuscated_id.size()); - int ret = - stats_write(BLUETOOTH_SMP_PAIRING_EVENT_REPORTED, obfuscated_id_field, - smp_cmd, direction, smp_fail_reason, metric_id); + BytesField obfuscated_id_field(address.IsEmpty() ? nullptr : obfuscated_id.c_str(), + address.IsEmpty() ? 0 : obfuscated_id.size()); + int ret = stats_write(BLUETOOTH_SMP_PAIRING_EVENT_REPORTED, obfuscated_id_field, smp_cmd, + direction, smp_fail_reason, metric_id); if (ret < 0) { log::warn( - "failed for {}, smp_cmd 0x{:x}, direction {}, smp_fail_reason 0x{:x}, " - "error {}", - address, smp_cmd, direction, smp_fail_reason, ret); + "failed for {}, smp_cmd 0x{:x}, direction {}, smp_fail_reason 0x{:x}, " + "error {}", + address, smp_cmd, direction, smp_fail_reason, ret); } } -void LogClassicPairingEvent(const RawAddress& address, uint16_t handle, uint32_t hci_cmd, uint16_t hci_event, - uint16_t cmd_status, uint16_t reason_code, int64_t event_value) { +void LogClassicPairingEvent(const RawAddress& address, uint16_t handle, uint32_t hci_cmd, + uint16_t hci_event, uint16_t cmd_status, uint16_t reason_code, + int64_t event_value) { std::string obfuscated_id; int metric_id = 0; if (!address.IsEmpty()) { @@ -810,24 +747,20 @@ void LogClassicPairingEvent(const RawAddress& address, uint16_t handle, uint32_t metric_id = MetricIdAllocator::GetInstance().AllocateId(address); } // nullptr and size 0 represent missing value for obfuscated_id - BytesField obfuscated_id_field( - address.IsEmpty() ? nullptr : obfuscated_id.c_str(), - address.IsEmpty() ? 0 : obfuscated_id.size()); - int ret = stats_write(BLUETOOTH_CLASSIC_PAIRING_EVENT_REPORTED, - obfuscated_id_field, handle, hci_cmd, hci_event, - cmd_status, reason_code, event_value, metric_id); + BytesField obfuscated_id_field(address.IsEmpty() ? nullptr : obfuscated_id.c_str(), + address.IsEmpty() ? 0 : obfuscated_id.size()); + int ret = stats_write(BLUETOOTH_CLASSIC_PAIRING_EVENT_REPORTED, obfuscated_id_field, handle, + hci_cmd, hci_event, cmd_status, reason_code, event_value, metric_id); if (ret < 0) { log::warn( - "failed for {}, handle {}, hci_cmd 0x{:x}, hci_event 0x{:x}, " - "cmd_status 0x{:x}, reason 0x{:x}, event_value {}, error {}", - address, handle, hci_cmd, hci_event, cmd_status, reason_code, - event_value, ret); + "failed for {}, handle {}, hci_cmd 0x{:x}, hci_event 0x{:x}, " + "cmd_status 0x{:x}, reason 0x{:x}, event_value {}, error {}", + address, handle, hci_cmd, hci_event, cmd_status, reason_code, event_value, ret); } } -void LogSdpAttribute(const RawAddress& address, uint16_t protocol_uuid, - uint16_t attribute_id, size_t attribute_size, - const char* attribute_value) { +void LogSdpAttribute(const RawAddress& address, uint16_t protocol_uuid, uint16_t attribute_id, + size_t attribute_size, const char* attribute_value) { std::string obfuscated_id; int metric_id = 0; if (!address.IsEmpty()) { @@ -835,25 +768,21 @@ void LogSdpAttribute(const RawAddress& address, uint16_t protocol_uuid, metric_id = MetricIdAllocator::GetInstance().AllocateId(address); } // nullptr and size 0 represent missing value for obfuscated_id - BytesField obfuscated_id_field( - address.IsEmpty() ? nullptr : obfuscated_id.c_str(), - address.IsEmpty() ? 0 : obfuscated_id.size()); + BytesField obfuscated_id_field(address.IsEmpty() ? nullptr : obfuscated_id.c_str(), + address.IsEmpty() ? 0 : obfuscated_id.size()); BytesField attribute_field(attribute_value, attribute_size); - int ret = - stats_write(BLUETOOTH_SDP_ATTRIBUTE_REPORTED, obfuscated_id_field, - protocol_uuid, attribute_id, attribute_field, metric_id); + int ret = stats_write(BLUETOOTH_SDP_ATTRIBUTE_REPORTED, obfuscated_id_field, protocol_uuid, + attribute_id, attribute_field, metric_id); if (ret < 0) { - log::warn( - "failed for {}, protocol_uuid 0x{:x}, attribute_id 0x{:x}, error {}", - address, protocol_uuid, attribute_id, ret); + log::warn("failed for {}, protocol_uuid 0x{:x}, attribute_id 0x{:x}, error {}", address, + protocol_uuid, attribute_id, ret); } } -void LogSocketConnectionState( - const RawAddress& address, int port, int type, - android::bluetooth::SocketConnectionstateEnum connection_state, - int64_t tx_bytes, int64_t rx_bytes, int uid, int server_port, - android::bluetooth::SocketRoleEnum socket_role) { +void LogSocketConnectionState(const RawAddress& address, int port, int type, + android::bluetooth::SocketConnectionstateEnum connection_state, + int64_t tx_bytes, int64_t rx_bytes, int uid, int server_port, + android::bluetooth::SocketRoleEnum socket_role) { std::string obfuscated_id; int metric_id = 0; if (!address.IsEmpty()) { @@ -861,29 +790,25 @@ void LogSocketConnectionState( metric_id = MetricIdAllocator::GetInstance().AllocateId(address); } // nullptr and size 0 represent missing value for obfuscated_id - BytesField obfuscated_id_field( - address.IsEmpty() ? nullptr : obfuscated_id.c_str(), - address.IsEmpty() ? 0 : obfuscated_id.size()); - int ret = - stats_write(BLUETOOTH_SOCKET_CONNECTION_STATE_CHANGED, - obfuscated_id_field, port, type, connection_state, tx_bytes, - rx_bytes, uid, server_port, socket_role, metric_id); + BytesField obfuscated_id_field(address.IsEmpty() ? nullptr : obfuscated_id.c_str(), + address.IsEmpty() ? 0 : obfuscated_id.size()); + int ret = stats_write(BLUETOOTH_SOCKET_CONNECTION_STATE_CHANGED, obfuscated_id_field, port, type, + connection_state, tx_bytes, rx_bytes, uid, server_port, socket_role, + metric_id); if (ret < 0) { log::warn( - "failed for {}, port {}, type {}, state {}, tx_bytes {}, rx_bytes {}, " - "uid {}, server_port {}, socket_role {}, error {}", - address, port, type, connection_state, tx_bytes, rx_bytes, uid, - server_port, socket_role, ret); + "failed for {}, port {}, type {}, state {}, tx_bytes {}, rx_bytes {}, " + "uid {}, server_port {}, socket_role {}, error {}", + address, port, type, connection_state, tx_bytes, rx_bytes, uid, server_port, + socket_role, ret); } } void LogManufacturerInfo(const RawAddress& address, android::bluetooth::AddressTypeEnum address_type, android::bluetooth::DeviceInfoSrcEnum source_type, - const std::string& source_name, - const std::string& manufacturer, - const std::string& model, - const std::string& hardware_version, + const std::string& source_name, const std::string& manufacturer, + const std::string& model, const std::string& hardware_version, const std::string& software_version) { std::string obfuscated_id; int metric_id = 0; @@ -892,22 +817,20 @@ void LogManufacturerInfo(const RawAddress& address, metric_id = MetricIdAllocator::GetInstance().AllocateId(address); } // nullptr and size 0 represent missing value for obfuscated_id - BytesField obfuscated_id_field( - address.IsEmpty() ? nullptr : obfuscated_id.c_str(), - address.IsEmpty() ? 0 : obfuscated_id.size()); - int ret = stats_write( - BLUETOOTH_DEVICE_INFO_REPORTED, obfuscated_id_field, source_type, - source_name.c_str(), manufacturer.c_str(), model.c_str(), - hardware_version.c_str(), software_version.c_str(), metric_id, - address_type, address.address[5], address.address[4], address.address[3]); + BytesField obfuscated_id_field(address.IsEmpty() ? nullptr : obfuscated_id.c_str(), + address.IsEmpty() ? 0 : obfuscated_id.size()); + int ret = stats_write(BLUETOOTH_DEVICE_INFO_REPORTED, obfuscated_id_field, source_type, + source_name.c_str(), manufacturer.c_str(), model.c_str(), + hardware_version.c_str(), software_version.c_str(), metric_id, address_type, + address.address[5], address.address[4], address.address[3]); if (ret < 0) { log::warn( - "failed for {}, source_type {}, source_name {}, manufacturer {}, model " - "{}, hardware_version {}, software_version {} MAC address type {} MAC " - "address prefix {} {} {}, error {}", - address, source_type, source_name, manufacturer, model, - hardware_version, software_version, address_type, address.address[5], - address.address[4], address.address[3], ret); + "failed for {}, source_type {}, source_name {}, manufacturer {}, model " + "{}, hardware_version {}, software_version {} MAC address type {} MAC " + "address prefix {} {} {}, error {}", + address, source_type, source_name, manufacturer, model, hardware_version, + software_version, address_type, address.address[5], address.address[4], + address.address[3], ret); } } @@ -918,59 +841,53 @@ void LogBluetoothHalCrashReason(const RawAddress& address, uint32_t error_code, obfuscated_id = AddressObfuscator::GetInstance()->Obfuscate(address); } // nullptr and size 0 represent missing value for obfuscated_id - BytesField obfuscated_id_field( - address.IsEmpty() ? nullptr : obfuscated_id.c_str(), - address.IsEmpty() ? 0 : obfuscated_id.size()); - int ret = stats_write(BLUETOOTH_HAL_CRASH_REASON_REPORTED, 0, - obfuscated_id_field, error_code, vendor_error_code); + BytesField obfuscated_id_field(address.IsEmpty() ? nullptr : obfuscated_id.c_str(), + address.IsEmpty() ? 0 : obfuscated_id.size()); + int ret = stats_write(BLUETOOTH_HAL_CRASH_REASON_REPORTED, 0, obfuscated_id_field, error_code, + vendor_error_code); if (ret < 0) { - log::warn( - "failed for {}, error_code 0x{:x}, vendor_error_code 0x{:x}, error {}", - address, error_code, vendor_error_code, ret); - } -} - -void LogLeAudioConnectionSessionReported( - int32_t group_size, int32_t group_metric_id, - int64_t connection_duration_nanos, - std::vector& device_connecting_offset_nanos, - std::vector& device_connected_offset_nanos, - std::vector& device_connection_duration_nanos, - std::vector& device_connection_status, - std::vector& device_disconnection_status, - std::vector& device_address, - std::vector& streaming_offset_nanos, - std::vector& streaming_duration_nanos, - std::vector& streaming_context_type) { + log::warn("failed for {}, error_code 0x{:x}, vendor_error_code 0x{:x}, error {}", address, + error_code, vendor_error_code, ret); + } +} + +void LogLeAudioConnectionSessionReported(int32_t group_size, int32_t group_metric_id, + int64_t connection_duration_nanos, + std::vector& device_connecting_offset_nanos, + std::vector& device_connected_offset_nanos, + std::vector& device_connection_duration_nanos, + std::vector& device_connection_status, + std::vector& device_disconnection_status, + std::vector& device_address, + std::vector& streaming_offset_nanos, + std::vector& streaming_duration_nanos, + std::vector& streaming_context_type) { std::vector device_metric_id(device_address.size()); for (uint64_t i = 0; i < device_address.size(); i++) { if (!device_address[i].IsEmpty()) { - device_metric_id[i] = - bluetooth::shim::AllocateIdFromMetricIdAllocator(device_address[i]); + device_metric_id[i] = bluetooth::shim::AllocateIdFromMetricIdAllocator(device_address[i]); } else { device_metric_id[i] = 0; } } - int ret = stats_write( - LE_AUDIO_CONNECTION_SESSION_REPORTED, group_size, group_metric_id, - connection_duration_nanos, device_connecting_offset_nanos, - device_connected_offset_nanos, device_connection_duration_nanos, - device_connection_status, device_disconnection_status, device_metric_id, - streaming_offset_nanos, streaming_duration_nanos, streaming_context_type); + int ret = stats_write(LE_AUDIO_CONNECTION_SESSION_REPORTED, group_size, group_metric_id, + connection_duration_nanos, device_connecting_offset_nanos, + device_connected_offset_nanos, device_connection_duration_nanos, + device_connection_status, device_disconnection_status, device_metric_id, + streaming_offset_nanos, streaming_duration_nanos, streaming_context_type); if (ret < 0) { log::warn( - "failed for group {}device_connecting_offset_nanos[{}], " - "device_connected_offset_nanos[{}], " - "device_connection_duration_nanos[{}], device_connection_status[{}], " - "device_disconnection_status[{}], device_metric_id[{}], " - "streaming_offset_nanos[{}], streaming_duration_nanos[{}], " - "streaming_context_type[{}]", - group_metric_id, device_connecting_offset_nanos.size(), - device_connected_offset_nanos.size(), - device_connection_duration_nanos.size(), - device_connection_status.size(), device_disconnection_status.size(), - device_metric_id.size(), streaming_offset_nanos.size(), - streaming_duration_nanos.size(), streaming_context_type.size()); + "failed for group {}device_connecting_offset_nanos[{}], " + "device_connected_offset_nanos[{}], " + "device_connection_duration_nanos[{}], device_connection_status[{}], " + "device_disconnection_status[{}], device_metric_id[{}], " + "streaming_offset_nanos[{}], streaming_duration_nanos[{}], " + "streaming_context_type[{}]", + group_metric_id, device_connecting_offset_nanos.size(), + device_connected_offset_nanos.size(), device_connection_duration_nanos.size(), + device_connection_status.size(), device_disconnection_status.size(), + device_metric_id.size(), streaming_offset_nanos.size(), streaming_duration_nanos.size(), + streaming_context_type.size()); } } @@ -982,16 +899,13 @@ void LogLeAudioBroadcastSessionReported(int64_t duration_nanos) { } void LogLeBluetoothConnectionMetricEventReported( - const Address& address, - android::bluetooth::le::LeConnectionOriginType origin_type, - android::bluetooth::le::LeConnectionType connection_type, - android::bluetooth::le::LeConnectionState transaction_state, - std::vector> - argument_list) { + const Address& address, android::bluetooth::le::LeConnectionOriginType origin_type, + android::bluetooth::le::LeConnectionType connection_type, + android::bluetooth::le::LeConnectionState transaction_state, + std::vector> argument_list) { // Log the events for the State Management - metrics::MetricsCollector::GetLEConnectionMetricsCollector() - ->AddStateChangedEvent(address, origin_type, connection_type, - transaction_state, argument_list); + metrics::MetricsCollector::GetLEConnectionMetricsCollector()->AddStateChangedEvent( + address, origin_type, connection_type, transaction_state, argument_list); } } // namespace common diff --git a/system/common/metrics.h b/system/common/metrics.h index 182d0b03879..c40b184bf8e 100644 --- a/system/common/metrics.h +++ b/system/common/metrics.h @@ -89,7 +89,7 @@ typedef enum { * NOTE: Negative values are invalid */ class A2dpSessionMetrics { - public: +public: A2dpSessionMetrics() {} /* @@ -121,7 +121,7 @@ class A2dpSessionMetrics { }; class BluetoothMetricsLogger { - public: +public: static BluetoothMetricsLogger* GetInstance() { static BluetoothMetricsLogger* instance = new BluetoothMetricsLogger(); return instance; @@ -137,8 +137,8 @@ class BluetoothMetricsLogger { * disconnect_reason: HCI reason for pairing disconnection. * See: stack/include/hcidefs.h */ - void LogPairEvent(uint32_t disconnect_reason, uint64_t timestamp_ms, - uint32_t device_class, device_type_t device_type); + void LogPairEvent(uint32_t disconnect_reason, uint64_t timestamp_ms, uint32_t device_class, + device_type_t device_type); /* * Record a wake event @@ -149,8 +149,8 @@ class BluetoothMetricsLogger { * requestor: if provided is the service requesting the wake lock * name: the name of the wake lock held */ - void LogWakeEvent(wake_event_type_t type, const std::string& requestor, - const std::string& name, uint64_t timestamp_ms); + void LogWakeEvent(wake_event_type_t type, const std::string& requestor, const std::string& name, + uint64_t timestamp_ms); /* * Record a scan event @@ -162,8 +162,8 @@ class BluetoothMetricsLogger { * type: whether the scan reports BR/EDR, LE, or both. * results: number of results to be reported. */ - void LogScanEvent(bool start, const std::string& initator, scan_tech_t type, - uint32_t results, uint64_t timestamp_ms); + void LogScanEvent(bool start, const std::string& initiator, scan_tech_t type, uint32_t results, + uint64_t timestamp_ms); /* * Start logging a Bluetooth session @@ -180,8 +180,7 @@ class BluetoothMetricsLogger { * timestamp_ms : the timestamp for session start, 0 means now * */ - void LogBluetoothSessionStart(connection_tech_t connection_tech_type, - uint64_t timestamp_ms); + void LogBluetoothSessionStart(connection_tech_t connection_tech_type, uint64_t timestamp_ms); /* * Stop logging a Bluetooth session and pushes it to the log queue @@ -193,8 +192,7 @@ class BluetoothMetricsLogger { * timestamp_ms : the timestamp of session end, 0 means now * */ - void LogBluetoothSessionEnd(disconnect_reason_t disconnect_reason, - uint64_t timestamp_ms); + void LogBluetoothSessionEnd(disconnect_reason_t disconnect_reason, uint64_t timestamp_ms); /* * Log information about remote device in a current Bluetooth session @@ -206,8 +204,7 @@ class BluetoothMetricsLogger { * device_class : device_class defined in btm_api_types.h * device_type : type of remote device */ - void LogBluetoothSessionDeviceInfo(uint32_t device_class, - device_type_t device_type); + void LogBluetoothSessionDeviceInfo(uint32_t device_class, device_type_t device_type); /* * Log A2DP Audio Session Information @@ -252,7 +249,7 @@ class BluetoothMetricsLogger { static const size_t kMaxNumWakeEvent = 1000; static const size_t kMaxNumScanEvent = 50; - private: +private: BluetoothMetricsLogger(); /* @@ -305,11 +302,9 @@ static const uint32_t kUnknownConnectionHandle = 0xFFFF; * @param cmd_status Command status associated with this event, if any * @param reason_code Reason code associated with this event, if any */ -void LogLinkLayerConnectionEvent(const RawAddress* address, - uint32_t connection_handle, - android::bluetooth::DirectionEnum direction, - uint16_t link_type, uint32_t hci_cmd, - uint16_t hci_event, uint16_t hci_ble_event, +void LogLinkLayerConnectionEvent(const RawAddress* address, uint32_t connection_handle, + android::bluetooth::DirectionEnum direction, uint16_t link_type, + uint32_t hci_cmd, uint16_t hci_event, uint16_t hci_ble_event, uint16_t cmd_status, uint16_t reason_code); /** @@ -345,8 +340,7 @@ void LogRemoteVersionInfo(uint16_t handle, uint8_t status, uint8_t version, * @param num_missing_pcm_bytes number of PCM bytes that cannot be read from * the source */ -void LogA2dpAudioUnderrunEvent(const RawAddress& address, - uint64_t encoding_interval_millis, +void LogA2dpAudioUnderrunEvent(const RawAddress& address, uint64_t encoding_interval_millis, int num_missing_pcm_bytes); /** @@ -360,10 +354,8 @@ void LogA2dpAudioUnderrunEvent(const RawAddress& address, * @param num_dropped_encoded_bytes number of encoded bytes dropped from Tx * queue */ -void LogA2dpAudioOverrunEvent(const RawAddress& address, - uint64_t encoding_interval_millis, - int num_dropped_buffers, - int num_dropped_encoded_frames, +void LogA2dpAudioOverrunEvent(const RawAddress& address, uint64_t encoding_interval_millis, + int num_dropped_buffers, int num_dropped_encoded_frames, int num_dropped_encoded_bytes); /** @@ -373,8 +365,7 @@ void LogA2dpAudioOverrunEvent(const RawAddress& address, * @param playback_state audio playback state * @param audio_coding_mode audio codec encoding mode */ -void LogA2dpPlaybackEvent(const RawAddress& address, int playback_state, - int audio_coding_mode); +void LogA2dpPlaybackEvent(const RawAddress& address, int playback_state, int audio_coding_mode); /** * Log read RSSI result @@ -385,8 +376,8 @@ void LogA2dpPlaybackEvent(const RawAddress& address, int playback_state, * @param cmd_status command status from read RSSI command * @param rssi rssi value in dBm */ -void LogReadRssiResult(const RawAddress& address, uint16_t handle, - uint32_t cmd_status, int8_t rssi); +void LogReadRssiResult(const RawAddress& address, uint16_t handle, uint32_t cmd_status, + int8_t rssi); /** * Log failed contact counter report @@ -398,9 +389,8 @@ void LogReadRssiResult(const RawAddress& address, uint16_t handle, * @param failed_contact_counter Number of consecutive failed contacts for a * connection corresponding to the Handle */ -void LogReadFailedContactCounterResult(const RawAddress& address, - uint16_t handle, uint32_t cmd_status, - int32_t failed_contact_counter); +void LogReadFailedContactCounterResult(const RawAddress& address, uint16_t handle, + uint32_t cmd_status, int32_t failed_contact_counter); /** * Log transmit power level for a particular device after read @@ -412,8 +402,7 @@ void LogReadFailedContactCounterResult(const RawAddress& address, * @param transmit_power_level transmit power level for connection to this * device */ -void LogReadTxPowerLevelResult(const RawAddress& address, uint16_t handle, - uint32_t cmd_status, +void LogReadTxPowerLevelResult(const RawAddress& address, uint16_t handle, uint32_t cmd_status, int32_t transmit_power_level); /** @@ -425,8 +414,7 @@ void LogReadTxPowerLevelResult(const RawAddress& address, uint16_t handle, * @param smp_fail_reason SMP pairing failure reason code from SMP spec */ void LogSmpPairingEvent(const RawAddress& address, uint8_t smp_cmd, - android::bluetooth::DirectionEnum direction, - uint8_t smp_fail_reason); + android::bluetooth::DirectionEnum direction, uint8_t smp_fail_reason); /** * Logs there is an event related Bluetooth classic pairing @@ -440,8 +428,9 @@ void LogSmpPairingEvent(const RawAddress& address, uint8_t smp_cmd, * @param reason_code Reason code associated with this event * @param event_value A status value related to this specific event */ -void LogClassicPairingEvent(const RawAddress& address, uint16_t handle, uint32_t hci_cmd, uint16_t hci_event, - uint16_t cmd_status, uint16_t reason_code, int64_t event_value); +void LogClassicPairingEvent(const RawAddress& address, uint16_t handle, uint32_t hci_cmd, + uint16_t hci_event, uint16_t cmd_status, uint16_t reason_code, + int64_t event_value); /** * Logs when certain Bluetooth SDP attributes are discovered @@ -453,9 +442,8 @@ void LogClassicPairingEvent(const RawAddress& address, uint16_t handle, uint32_t * @param attribute_value pointer to the attribute data, must be larger than * attribute_size */ -void LogSdpAttribute(const RawAddress& address, uint16_t protocol_uuid, - uint16_t attribute_id, size_t attribute_size, - const char* attribute_value); +void LogSdpAttribute(const RawAddress& address, uint16_t protocol_uuid, uint16_t attribute_id, + size_t attribute_size, const char* attribute_value); /** * Logs when there is a change in Bluetooth socket connection state @@ -472,11 +460,10 @@ void LogSdpAttribute(const RawAddress& address, uint16_t protocol_uuid, * @param socket_role role of this socket, server or connection * @param uid socket owner's uid */ -void LogSocketConnectionState( - const RawAddress& address, int port, int type, - android::bluetooth::SocketConnectionstateEnum connection_state, - int64_t tx_bytes, int64_t rx_bytes, int uid, int server_port, - android::bluetooth::SocketRoleEnum socket_role); +void LogSocketConnectionState(const RawAddress& address, int port, int type, + android::bluetooth::SocketConnectionstateEnum connection_state, + int64_t tx_bytes, int64_t rx_bytes, int uid, int server_port, + android::bluetooth::SocketRoleEnum socket_role); /** * Logs when a Bluetooth device's manufacturer information is learnt @@ -492,10 +479,8 @@ void LogSocketConnectionState( void LogManufacturerInfo(const RawAddress& address, android::bluetooth::AddressTypeEnum address_type, android::bluetooth::DeviceInfoSrcEnum source_type, - const std::string& source_name, - const std::string& manufacturer, - const std::string& model, - const std::string& hardware_version, + const std::string& source_name, const std::string& manufacturer, + const std::string& model, const std::string& hardware_version, const std::string& software_version); /** @@ -508,28 +493,25 @@ void LogManufacturerInfo(const RawAddress& address, void LogBluetoothHalCrashReason(const RawAddress& address, uint32_t error_code, uint32_t vendor_error_code); -void LogLeAudioConnectionSessionReported( - int32_t group_size, int32_t group_metric_id, - int64_t connection_duration_nanos, - std::vector& device_connecting_offset_nanos, - std::vector& device_connected_offset_nanos, - std::vector& device_connection_duration_nanos, - std::vector& device_connection_status, - std::vector& device_disconnection_status, - std::vector& device_address, - std::vector& streaming_offset_nanos, - std::vector& streaming_duration_nanos, - std::vector& streaming_context_type); +void LogLeAudioConnectionSessionReported(int32_t group_size, int32_t group_metric_id, + int64_t connection_duration_nanos, + std::vector& device_connecting_offset_nanos, + std::vector& device_connected_offset_nanos, + std::vector& device_connection_duration_nanos, + std::vector& device_connection_status, + std::vector& device_disconnection_status, + std::vector& device_address, + std::vector& streaming_offset_nanos, + std::vector& streaming_duration_nanos, + std::vector& streaming_context_type); void LogLeAudioBroadcastSessionReported(int64_t duration_nanos); void LogLeBluetoothConnectionMetricEventReported( - const RawAddress& raw_address, - android::bluetooth::le::LeConnectionOriginType origin_type, - android::bluetooth::le::LeConnectionType connection_type, - android::bluetooth::le::LeConnectionState transaction_state, - std::vector> - argument_list); + const RawAddress& raw_address, android::bluetooth::le::LeConnectionOriginType origin_type, + android::bluetooth::le::LeConnectionType connection_type, + android::bluetooth::le::LeConnectionState transaction_state, + std::vector> argument_list); } // namespace common diff --git a/system/common/metrics_linux.cc b/system/common/metrics_linux.cc index 59a3b0e3057..04ac50c9d62 100644 --- a/system/common/metrics_linux.cc +++ b/system/common/metrics_linux.cc @@ -34,43 +34,36 @@ bool A2dpSessionMetrics::operator==(const A2dpSessionMetrics& rhs) const { } struct BluetoothMetricsLogger::impl { - impl(size_t max_bluetooth_session, size_t max_pair_event, - size_t max_wake_event, size_t max_scan_event) {} + impl(size_t max_bluetooth_session, size_t max_pair_event, size_t max_wake_event, + size_t max_scan_event) {} }; BluetoothMetricsLogger::BluetoothMetricsLogger() - : pimpl_(new impl(kMaxNumBluetoothSession, kMaxNumPairEvent, - kMaxNumWakeEvent, kMaxNumScanEvent)) {} + : pimpl_(new impl(kMaxNumBluetoothSession, kMaxNumPairEvent, kMaxNumWakeEvent, + kMaxNumScanEvent)) {} -void BluetoothMetricsLogger::LogPairEvent(uint32_t disconnect_reason, - uint64_t timestamp_ms, - uint32_t device_class, - device_type_t device_type) {} +void BluetoothMetricsLogger::LogPairEvent(uint32_t disconnect_reason, uint64_t timestamp_ms, + uint32_t device_class, device_type_t device_type) {} -void BluetoothMetricsLogger::LogWakeEvent(wake_event_type_t type, - const std::string& requestor, - const std::string& name, - uint64_t timestamp_ms) {} +void BluetoothMetricsLogger::LogWakeEvent(wake_event_type_t type, const std::string& requestor, + const std::string& name, uint64_t timestamp_ms) {} -void BluetoothMetricsLogger::LogScanEvent(bool start, - const std::string& initator, +void BluetoothMetricsLogger::LogScanEvent(bool start, const std::string& initiator, scan_tech_t type, uint32_t results, uint64_t timestamp_ms) {} -void BluetoothMetricsLogger::LogBluetoothSessionStart( - connection_tech_t connection_tech_type, uint64_t timestamp_ms) {} +void BluetoothMetricsLogger::LogBluetoothSessionStart(connection_tech_t connection_tech_type, + uint64_t timestamp_ms) {} -void BluetoothMetricsLogger::LogBluetoothSessionEnd( - disconnect_reason_t disconnect_reason, uint64_t timestamp_ms) {} +void BluetoothMetricsLogger::LogBluetoothSessionEnd(disconnect_reason_t disconnect_reason, + uint64_t timestamp_ms) {} -void BluetoothMetricsLogger::LogBluetoothSessionDeviceInfo( - uint32_t device_class, device_type_t device_type) {} +void BluetoothMetricsLogger::LogBluetoothSessionDeviceInfo(uint32_t device_class, + device_type_t device_type) {} -void BluetoothMetricsLogger::LogA2dpSession( - const A2dpSessionMetrics& a2dp_session_metrics) {} +void BluetoothMetricsLogger::LogA2dpSession(const A2dpSessionMetrics& a2dp_session_metrics) {} -void BluetoothMetricsLogger::LogHeadsetProfileRfcConnection( - tBTA_SERVICE_ID service_id) {} +void BluetoothMetricsLogger::LogHeadsetProfileRfcConnection(tBTA_SERVICE_ID service_id) {} void BluetoothMetricsLogger::WriteString(std::string* serialized) {} @@ -88,84 +81,69 @@ void BluetoothMetricsLogger::ResetLog() {} void BluetoothMetricsLogger::Reset() {} -void LogClassicPairingEvent(const RawAddress& address, uint16_t handle, - uint32_t hci_cmd, uint16_t hci_event, - uint16_t cmd_status, uint16_t reason_code, +void LogClassicPairingEvent(const RawAddress& address, uint16_t handle, uint32_t hci_cmd, + uint16_t hci_event, uint16_t cmd_status, uint16_t reason_code, int64_t event_value) {} -void LogSocketConnectionState( - const RawAddress& address, int port, int type, - android::bluetooth::SocketConnectionstateEnum connection_state, - int64_t tx_bytes, int64_t rx_bytes, int uid, int server_port, - android::bluetooth::SocketRoleEnum socket_role) {} +void LogSocketConnectionState(const RawAddress& address, int port, int type, + android::bluetooth::SocketConnectionstateEnum connection_state, + int64_t tx_bytes, int64_t rx_bytes, int uid, int server_port, + android::bluetooth::SocketRoleEnum socket_role) {} void LogHciTimeoutEvent(uint32_t hci_cmd) {} -void LogA2dpAudioUnderrunEvent(const RawAddress& address, - uint64_t encoding_interval_millis, +void LogA2dpAudioUnderrunEvent(const RawAddress& address, uint64_t encoding_interval_millis, int num_missing_pcm_bytes) {} -void LogA2dpAudioOverrunEvent(const RawAddress& address, - uint64_t encoding_interval_millis, - int num_dropped_buffers, - int num_dropped_encoded_frames, +void LogA2dpAudioOverrunEvent(const RawAddress& address, uint64_t encoding_interval_millis, + int num_dropped_buffers, int num_dropped_encoded_frames, int num_dropped_encoded_bytes) {} -void LogA2dpPlaybackEvent(const RawAddress& address, int playback_state, - int audio_coding_mode) {} +void LogA2dpPlaybackEvent(const RawAddress& address, int playback_state, int audio_coding_mode) {} void LogBluetoothHalCrashReason(const RawAddress& address, uint32_t error_code, uint32_t vendor_error_code) {} -void LogReadRssiResult(const RawAddress& address, uint16_t handle, - uint32_t cmd_status, int8_t rssi) {} +void LogReadRssiResult(const RawAddress& address, uint16_t handle, uint32_t cmd_status, + int8_t rssi) {} -void LogReadFailedContactCounterResult(const RawAddress& address, - uint16_t handle, uint32_t cmd_status, - int32_t failed_contact_counter) {} +void LogReadFailedContactCounterResult(const RawAddress& address, uint16_t handle, + uint32_t cmd_status, int32_t failed_contact_counter) {} -void LogReadTxPowerLevelResult(const RawAddress& address, uint16_t handle, - uint32_t cmd_status, +void LogReadTxPowerLevelResult(const RawAddress& address, uint16_t handle, uint32_t cmd_status, int32_t transmit_power_level) {} void LogRemoteVersionInfo(uint16_t handle, uint8_t status, uint8_t version, uint16_t manufacturer_name, uint16_t subversion) {} -void LogLinkLayerConnectionEvent(const RawAddress* address, - uint32_t connection_handle, - android::bluetooth::DirectionEnum direction, - uint16_t link_type, uint32_t hci_cmd, - uint16_t hci_event, uint16_t hci_ble_event, +void LogLinkLayerConnectionEvent(const RawAddress* address, uint32_t connection_handle, + android::bluetooth::DirectionEnum direction, uint16_t link_type, + uint32_t hci_cmd, uint16_t hci_event, uint16_t hci_ble_event, uint16_t cmd_status, uint16_t reason_code) {} void LogManufacturerInfo(const RawAddress& address, android::bluetooth::DeviceInfoSrcEnum source_type, - const std::string& source_name, - const std::string& manufacturer, - const std::string& model, - const std::string& hardware_version, + const std::string& source_name, const std::string& manufacturer, + const std::string& model, const std::string& hardware_version, const std::string& software_version) {} -void LogSdpAttribute(const RawAddress& address, uint16_t protocol_uuid, - uint16_t attribute_id, size_t attribute_size, - const char* attribute_value) {} +void LogSdpAttribute(const RawAddress& address, uint16_t protocol_uuid, uint16_t attribute_id, + size_t attribute_size, const char* attribute_value) {} void LogSmpPairingEvent(const RawAddress& address, uint8_t smp_cmd, - android::bluetooth::DirectionEnum direction, - uint8_t smp_fail_reason) {} - -void LogLeAudioConnectionSessionReported( - int32_t group_size, int32_t group_metric_id, - int64_t connection_duration_nanos, - std::vector& device_connecting_offset_nanos, - std::vector& device_connected_offset_nanos, - std::vector& device_connection_duration_nanos, - std::vector& device_connection_status, - std::vector& device_disconnection_status, - std::vector& device_address, - std::vector& streaming_offset_nanos, - std::vector& streaming_duration_nanos, - std::vector& streaming_context_type) {} + android::bluetooth::DirectionEnum direction, uint8_t smp_fail_reason) {} + +void LogLeAudioConnectionSessionReported(int32_t group_size, int32_t group_metric_id, + int64_t connection_duration_nanos, + std::vector& device_connecting_offset_nanos, + std::vector& device_connected_offset_nanos, + std::vector& device_connection_duration_nanos, + std::vector& device_connection_status, + std::vector& device_disconnection_status, + std::vector& device_address, + std::vector& streaming_offset_nanos, + std::vector& streaming_duration_nanos, + std::vector& streaming_context_type) {} void LogLeAudioBroadcastSessionReported(int64_t duration_nanos) {} diff --git a/system/common/metrics_unittest.cc b/system/common/metrics_unittest.cc index 7db7ec812f2..b2a300f911c 100644 --- a/system/common/metrics_unittest.cc +++ b/system/common/metrics_unittest.cc @@ -40,10 +40,8 @@ using bluetooth::metrics::BluetoothMetricsProto::A2DPSession; using bluetooth::metrics::BluetoothMetricsProto::A2dpSourceCodec; using bluetooth::metrics::BluetoothMetricsProto::BluetoothLog; using bluetooth::metrics::BluetoothMetricsProto::BluetoothSession; -using bluetooth::metrics::BluetoothMetricsProto:: - BluetoothSession_ConnectionTechnologyType; -using bluetooth::metrics::BluetoothMetricsProto:: - BluetoothSession_DisconnectReasonType; +using bluetooth::metrics::BluetoothMetricsProto::BluetoothSession_ConnectionTechnologyType; +using bluetooth::metrics::BluetoothMetricsProto::BluetoothSession_DisconnectReasonType; using bluetooth::metrics::BluetoothMetricsProto::DeviceInfo; using bluetooth::metrics::BluetoothMetricsProto::DeviceInfo_DeviceType; using bluetooth::metrics::BluetoothMetricsProto::HeadsetProfileConnectionStats; @@ -60,30 +58,27 @@ namespace { const size_t kMaxEventGenerationLimit = 5000; } -static void sleep_ms(int64_t t) { - std::this_thread::sleep_for(std::chrono::milliseconds(t)); -} +static void sleep_ms(int64_t t) { std::this_thread::sleep_for(std::chrono::milliseconds(t)); } -DeviceInfo* MakeDeviceInfo(int32_t device_class, - DeviceInfo_DeviceType device_type) { +DeviceInfo* MakeDeviceInfo(int32_t device_class, DeviceInfo_DeviceType device_type) { DeviceInfo* info = new DeviceInfo(); info->set_device_class(device_class); info->set_device_type(device_type); return info; } -PairEvent* MakePairEvent(int32_t disconnect_reason, int64_t timestamp_ms, - DeviceInfo* device_info) { +PairEvent* MakePairEvent(int32_t disconnect_reason, int64_t timestamp_ms, DeviceInfo* device_info) { PairEvent* event = new PairEvent(); event->set_disconnect_reason(disconnect_reason); event->set_event_time_millis(timestamp_ms); - if (device_info) event->set_allocated_device_paired_with(device_info); + if (device_info) { + event->set_allocated_device_paired_with(device_info); + } return event; } -WakeEvent* MakeWakeEvent(WakeEvent_WakeEventType event_type, - const std::string& requestor, const std::string& name, - int64_t timestamp_ms) { +WakeEvent* MakeWakeEvent(WakeEvent_WakeEventType event_type, const std::string& requestor, + const std::string& name, int64_t timestamp_ms) { WakeEvent* event = new WakeEvent(); event->set_wake_event_type(event_type); event->set_requestor(requestor); @@ -92,10 +87,9 @@ WakeEvent* MakeWakeEvent(WakeEvent_WakeEventType event_type, return event; } -ScanEvent* MakeScanEvent(ScanEvent_ScanEventType event_type, - const std::string& initiator, - ScanEvent_ScanTechnologyType tech_type, - int32_t num_results, int64_t timestamp_ms) { +ScanEvent* MakeScanEvent(ScanEvent_ScanEventType event_type, const std::string& initiator, + ScanEvent_ScanTechnologyType tech_type, int32_t num_results, + int64_t timestamp_ms) { ScanEvent* event = new ScanEvent(); event->set_scan_event_type(event_type); event->set_initiator(initiator); @@ -105,8 +99,7 @@ ScanEvent* MakeScanEvent(ScanEvent_ScanEventType event_type, return event; } -A2DPSession* MakeA2DPSession(const A2dpSessionMetrics& metrics, - A2dpSourceCodec source_codec) { +A2DPSession* MakeA2DPSession(const A2dpSessionMetrics& metrics, A2dpSourceCodec source_codec) { A2DPSession* session = new A2DPSession(); session->set_media_timer_min_millis(metrics.media_timer_min_ms); session->set_media_timer_max_millis(metrics.media_timer_max_ms); @@ -121,16 +114,21 @@ A2DPSession* MakeA2DPSession(const A2dpSessionMetrics& metrics, return session; } -BluetoothSession* MakeBluetoothSession( - int64_t session_duration_sec, - BluetoothSession_ConnectionTechnologyType conn_type, - BluetoothSession_DisconnectReasonType disconnect_reason, - DeviceInfo* device_info, RFCommSession* rfcomm_session, - A2DPSession* a2dp_session) { +BluetoothSession* MakeBluetoothSession(int64_t session_duration_sec, + BluetoothSession_ConnectionTechnologyType conn_type, + BluetoothSession_DisconnectReasonType disconnect_reason, + DeviceInfo* device_info, RFCommSession* rfcomm_session, + A2DPSession* a2dp_session) { BluetoothSession* session = new BluetoothSession(); - if (a2dp_session) session->set_allocated_a2dp_session(a2dp_session); - if (rfcomm_session) session->set_allocated_rfcomm_session(rfcomm_session); - if (device_info) session->set_allocated_device_connected_to(device_info); + if (a2dp_session) { + session->set_allocated_a2dp_session(a2dp_session); + } + if (rfcomm_session) { + session->set_allocated_rfcomm_session(rfcomm_session); + } + if (device_info) { + session->set_allocated_device_connected_to(device_info); + } session->set_session_duration_sec(session_duration_sec); session->set_connection_technology_type(conn_type); session->set_disconnect_reason_type(disconnect_reason); @@ -161,31 +159,29 @@ BluetoothLog* MakeBluetoothLog(std::vector bt_sessions, return bt_log; } -void GenerateWakeEvents(size_t start, size_t end, - std::vector* wake_events) { +void GenerateWakeEvents(size_t start, size_t end, std::vector* wake_events) { for (size_t i = start; i < end; ++i) { - wake_events->push_back(MakeWakeEvent( - i % 2 == 0 ? WakeEvent_WakeEventType::WakeEvent_WakeEventType_ACQUIRED - : WakeEvent_WakeEventType::WakeEvent_WakeEventType_RELEASED, - "TEST_REQ", "TEST_NAME", i)); + wake_events->push_back( + MakeWakeEvent(i % 2 == 0 ? WakeEvent_WakeEventType::WakeEvent_WakeEventType_ACQUIRED + : WakeEvent_WakeEventType::WakeEvent_WakeEventType_RELEASED, + "TEST_REQ", "TEST_NAME", i)); } } -#define COMPARE_A2DP_METRICS(a, b) \ - do { \ - EXPECT_EQ((a).audio_duration_ms, (b).audio_duration_ms); \ - EXPECT_EQ((a).media_timer_min_ms, (b).media_timer_min_ms); \ - EXPECT_EQ((a).media_timer_max_ms, (b).media_timer_max_ms); \ - EXPECT_EQ((a).media_timer_avg_ms, (b).media_timer_avg_ms); \ - EXPECT_EQ((a).total_scheduling_count, (b).total_scheduling_count); \ - EXPECT_EQ((a).buffer_overruns_max_count, (b).buffer_overruns_max_count); \ - EXPECT_EQ((a).buffer_overruns_total, (b).buffer_overruns_total); \ - EXPECT_THAT((a).buffer_underruns_average, \ - FloatNear((b).buffer_underruns_average, 0.01)); \ - (a).buffer_underruns_average = (b).buffer_underruns_average; \ - EXPECT_EQ((a).buffer_underruns_count, (b).buffer_underruns_count); \ - EXPECT_EQ((a).codec_index, (b).codec_index); \ - EXPECT_EQ((a).is_a2dp_offload, (b).is_a2dp_offload); \ +#define COMPARE_A2DP_METRICS(a, b) \ + do { \ + EXPECT_EQ((a).audio_duration_ms, (b).audio_duration_ms); \ + EXPECT_EQ((a).media_timer_min_ms, (b).media_timer_min_ms); \ + EXPECT_EQ((a).media_timer_max_ms, (b).media_timer_max_ms); \ + EXPECT_EQ((a).media_timer_avg_ms, (b).media_timer_avg_ms); \ + EXPECT_EQ((a).total_scheduling_count, (b).total_scheduling_count); \ + EXPECT_EQ((a).buffer_overruns_max_count, (b).buffer_overruns_max_count); \ + EXPECT_EQ((a).buffer_overruns_total, (b).buffer_overruns_total); \ + EXPECT_THAT((a).buffer_underruns_average, FloatNear((b).buffer_underruns_average, 0.01)); \ + (a).buffer_underruns_average = (b).buffer_underruns_average; \ + EXPECT_EQ((a).buffer_underruns_count, (b).buffer_underruns_count); \ + EXPECT_EQ((a).codec_index, (b).codec_index); \ + EXPECT_EQ((a).is_a2dp_offload, (b).is_a2dp_offload); \ } while (0) /* @@ -321,7 +317,7 @@ TEST(BluetoothA2DPSessionMetricsTest, TestPartialUpdate) { } class BluetoothMetricsLoggerTest : public Test { - protected: +protected: // Use to hold test protos std::vector pair_events_; std::vector wake_events_; @@ -411,45 +407,42 @@ class BluetoothMetricsLoggerTest : public Test { delete bt_log_; } - public: +public: }; TEST_F(BluetoothMetricsLoggerTest, PairEventTest) { pair_events_.push_back(MakePairEvent( - 35, 12345, - MakeDeviceInfo( - 42, DeviceInfo_DeviceType::DeviceInfo_DeviceType_DEVICE_TYPE_BREDR))); + 35, 12345, + MakeDeviceInfo(42, DeviceInfo_DeviceType::DeviceInfo_DeviceType_DEVICE_TYPE_BREDR))); UpdateLog(); - BluetoothMetricsLogger::GetInstance()->LogPairEvent( - 35, 12345, 42, bluetooth::common::DEVICE_TYPE_BREDR); + BluetoothMetricsLogger::GetInstance()->LogPairEvent(35, 12345, 42, + bluetooth::common::DEVICE_TYPE_BREDR); std::string msg_str; BluetoothMetricsLogger::GetInstance()->WriteString(&msg_str); EXPECT_THAT(msg_str, StrEq(bt_log_str_)); } TEST_F(BluetoothMetricsLoggerTest, WakeEventTest) { - wake_events_.push_back( - MakeWakeEvent(WakeEvent_WakeEventType::WakeEvent_WakeEventType_ACQUIRED, - "TEST_REQ", "TEST_NAME", 12345)); + wake_events_.push_back(MakeWakeEvent(WakeEvent_WakeEventType::WakeEvent_WakeEventType_ACQUIRED, + "TEST_REQ", "TEST_NAME", 12345)); UpdateLog(); - BluetoothMetricsLogger::GetInstance()->LogWakeEvent( - bluetooth::common::WAKE_EVENT_ACQUIRED, "TEST_REQ", "TEST_NAME", 12345); + BluetoothMetricsLogger::GetInstance()->LogWakeEvent(bluetooth::common::WAKE_EVENT_ACQUIRED, + "TEST_REQ", "TEST_NAME", 12345); std::string msg_str; BluetoothMetricsLogger::GetInstance()->WriteString(&msg_str); EXPECT_THAT(msg_str, StrEq(bt_log_str_)); } TEST_F(BluetoothMetricsLoggerTest, WakeEventOverrunTest) { - GenerateWakeEvents( - kMaxEventGenerationLimit - BluetoothMetricsLogger::kMaxNumWakeEvent, - kMaxEventGenerationLimit, &wake_events_); + GenerateWakeEvents(kMaxEventGenerationLimit - BluetoothMetricsLogger::kMaxNumWakeEvent, + kMaxEventGenerationLimit, &wake_events_); num_wake_event_ = kMaxEventGenerationLimit; UpdateLog(); for (size_t i = 0; i < kMaxEventGenerationLimit; ++i) { BluetoothMetricsLogger::GetInstance()->LogWakeEvent( - i % 2 == 0 ? bluetooth::common::WAKE_EVENT_ACQUIRED - : bluetooth::common::WAKE_EVENT_RELEASED, - "TEST_REQ", "TEST_NAME", i); + i % 2 == 0 ? bluetooth::common::WAKE_EVENT_ACQUIRED + : bluetooth::common::WAKE_EVENT_RELEASED, + "TEST_REQ", "TEST_NAME", i); } std::string msg_str; BluetoothMetricsLogger::GetInstance()->WriteString(&msg_str); @@ -458,15 +451,12 @@ TEST_F(BluetoothMetricsLoggerTest, WakeEventOverrunTest) { TEST_F(BluetoothMetricsLoggerTest, ScanEventTest) { scan_events_.push_back(MakeScanEvent( - ScanEvent_ScanEventType::ScanEvent_ScanEventType_SCAN_EVENT_STOP, - "TEST_INITIATOR", - ScanEvent_ScanTechnologyType:: - ScanEvent_ScanTechnologyType_SCAN_TECH_TYPE_BREDR, - 42, 123456)); + ScanEvent_ScanEventType::ScanEvent_ScanEventType_SCAN_EVENT_STOP, "TEST_INITIATOR", + ScanEvent_ScanTechnologyType::ScanEvent_ScanTechnologyType_SCAN_TECH_TYPE_BREDR, 42, + 123456)); UpdateLog(); BluetoothMetricsLogger::GetInstance()->LogScanEvent( - false, "TEST_INITIATOR", bluetooth::common::SCAN_TECH_TYPE_BREDR, 42, - 123456); + false, "TEST_INITIATOR", bluetooth::common::SCAN_TECH_TYPE_BREDR, 42, 123456); std::string msg_str; BluetoothMetricsLogger::GetInstance()->WriteString(&msg_str); EXPECT_THAT(msg_str, StrEq(bt_log_str_)); @@ -474,17 +464,16 @@ TEST_F(BluetoothMetricsLoggerTest, ScanEventTest) { TEST_F(BluetoothMetricsLoggerTest, BluetoothSessionTest) { bt_sessions_.push_back(MakeBluetoothSession( - 10, - BluetoothSession_ConnectionTechnologyType:: - BluetoothSession_ConnectionTechnologyType_CONNECTION_TECHNOLOGY_TYPE_LE, - BluetoothSession_DisconnectReasonType:: - BluetoothSession_DisconnectReasonType_UNKNOWN, - nullptr, nullptr, nullptr)); + 10, + BluetoothSession_ConnectionTechnologyType:: + BluetoothSession_ConnectionTechnologyType_CONNECTION_TECHNOLOGY_TYPE_LE, + BluetoothSession_DisconnectReasonType::BluetoothSession_DisconnectReasonType_UNKNOWN, + nullptr, nullptr, nullptr)); UpdateLog(); BluetoothMetricsLogger::GetInstance()->LogBluetoothSessionStart( - bluetooth::common::CONNECTION_TECHNOLOGY_TYPE_LE, 123456); + bluetooth::common::CONNECTION_TECHNOLOGY_TYPE_LE, 123456); BluetoothMetricsLogger::GetInstance()->LogBluetoothSessionEnd( - bluetooth::common::DISCONNECT_REASON_UNKNOWN, 133456); + bluetooth::common::DISCONNECT_REASON_UNKNOWN, 133456); std::string msg_str; BluetoothMetricsLogger::GetInstance()->WriteString(&msg_str); EXPECT_THAT(msg_str, StrEq(bt_log_str_)); @@ -492,16 +481,15 @@ TEST_F(BluetoothMetricsLoggerTest, BluetoothSessionTest) { TEST_F(BluetoothMetricsLoggerTest, BluetoothSessionDumpBeforeEndTest) { bt_sessions_.push_back(MakeBluetoothSession( - 1, - BluetoothSession_ConnectionTechnologyType:: - BluetoothSession_ConnectionTechnologyType_CONNECTION_TECHNOLOGY_TYPE_LE, - BluetoothSession_DisconnectReasonType:: - BluetoothSession_DisconnectReasonType_METRICS_DUMP, - nullptr, nullptr, nullptr)); + 1, + BluetoothSession_ConnectionTechnologyType:: + BluetoothSession_ConnectionTechnologyType_CONNECTION_TECHNOLOGY_TYPE_LE, + BluetoothSession_DisconnectReasonType::BluetoothSession_DisconnectReasonType_METRICS_DUMP, + nullptr, nullptr, nullptr)); UpdateLog(); BluetoothMetricsLogger::GetInstance()->LogBluetoothSessionStart( - bluetooth::common::CONNECTION_TECHNOLOGY_TYPE_LE, - bluetooth::common::time_get_os_boottime_ms()); + bluetooth::common::CONNECTION_TECHNOLOGY_TYPE_LE, + bluetooth::common::time_get_os_boottime_ms()); sleep_ms(1000); std::string msg_str; BluetoothMetricsLogger::GetInstance()->WriteString(&msg_str); @@ -510,25 +498,24 @@ TEST_F(BluetoothMetricsLoggerTest, BluetoothSessionDumpBeforeEndTest) { TEST_F(BluetoothMetricsLoggerTest, BluetoothSessionStartBeforeEndTest) { bt_sessions_.push_back(MakeBluetoothSession( - 1, - BluetoothSession_ConnectionTechnologyType:: - BluetoothSession_ConnectionTechnologyType_CONNECTION_TECHNOLOGY_TYPE_UNKNOWN, - BluetoothSession_DisconnectReasonType:: - BluetoothSession_DisconnectReasonType_NEXT_START_WITHOUT_END_PREVIOUS, - nullptr, nullptr, nullptr)); + 1, + BluetoothSession_ConnectionTechnologyType:: + BluetoothSession_ConnectionTechnologyType_CONNECTION_TECHNOLOGY_TYPE_UNKNOWN, + BluetoothSession_DisconnectReasonType:: + BluetoothSession_DisconnectReasonType_NEXT_START_WITHOUT_END_PREVIOUS, + nullptr, nullptr, nullptr)); bt_sessions_.push_back(MakeBluetoothSession( - 2, - BluetoothSession_ConnectionTechnologyType:: - BluetoothSession_ConnectionTechnologyType_CONNECTION_TECHNOLOGY_TYPE_LE, - BluetoothSession_DisconnectReasonType:: - BluetoothSession_DisconnectReasonType_METRICS_DUMP, - nullptr, nullptr, nullptr)); + 2, + BluetoothSession_ConnectionTechnologyType:: + BluetoothSession_ConnectionTechnologyType_CONNECTION_TECHNOLOGY_TYPE_LE, + BluetoothSession_DisconnectReasonType::BluetoothSession_DisconnectReasonType_METRICS_DUMP, + nullptr, nullptr, nullptr)); UpdateLog(); BluetoothMetricsLogger::GetInstance()->LogBluetoothSessionStart( - bluetooth::common::CONNECTION_TECHNOLOGY_TYPE_UNKNOWN, 0); + bluetooth::common::CONNECTION_TECHNOLOGY_TYPE_UNKNOWN, 0); sleep_ms(1000); BluetoothMetricsLogger::GetInstance()->LogBluetoothSessionStart( - bluetooth::common::CONNECTION_TECHNOLOGY_TYPE_LE, 0); + bluetooth::common::CONNECTION_TECHNOLOGY_TYPE_LE, 0); sleep_ms(2000); std::string msg_str; BluetoothMetricsLogger::GetInstance()->WriteString(&msg_str); @@ -582,27 +569,24 @@ TEST_F(BluetoothMetricsLoggerTest, A2DPSessionTwoUpdatesTest) { metrics1.is_a2dp_offload = false; metrics2.is_a2dp_offload = true; metrics_sum.is_a2dp_offload = true; - DeviceInfo* info = MakeDeviceInfo( - BTM_COD_MAJOR_AUDIO_TEST, - DeviceInfo_DeviceType::DeviceInfo_DeviceType_DEVICE_TYPE_BREDR); - A2DPSession* session = - MakeA2DPSession(metrics_sum, A2dpSourceCodec::A2DP_SOURCE_CODEC_AAC); + DeviceInfo* info = MakeDeviceInfo(BTM_COD_MAJOR_AUDIO_TEST, + DeviceInfo_DeviceType::DeviceInfo_DeviceType_DEVICE_TYPE_BREDR); + A2DPSession* session = MakeA2DPSession(metrics_sum, A2dpSourceCodec::A2DP_SOURCE_CODEC_AAC); bt_sessions_.push_back(MakeBluetoothSession( - 10, - BluetoothSession_ConnectionTechnologyType:: - BluetoothSession_ConnectionTechnologyType_CONNECTION_TECHNOLOGY_TYPE_BREDR, - BluetoothSession_DisconnectReasonType:: - BluetoothSession_DisconnectReasonType_UNKNOWN, - info, nullptr, session)); + 10, + BluetoothSession_ConnectionTechnologyType:: + BluetoothSession_ConnectionTechnologyType_CONNECTION_TECHNOLOGY_TYPE_BREDR, + BluetoothSession_DisconnectReasonType::BluetoothSession_DisconnectReasonType_UNKNOWN, + info, nullptr, session)); UpdateLog(); BluetoothMetricsLogger::GetInstance()->LogBluetoothSessionStart( - bluetooth::common::CONNECTION_TECHNOLOGY_TYPE_BREDR, 123456); + bluetooth::common::CONNECTION_TECHNOLOGY_TYPE_BREDR, 123456); BluetoothMetricsLogger::GetInstance()->LogBluetoothSessionDeviceInfo( - BTM_COD_MAJOR_AUDIO_TEST, bluetooth::common::DEVICE_TYPE_BREDR); + BTM_COD_MAJOR_AUDIO_TEST, bluetooth::common::DEVICE_TYPE_BREDR); BluetoothMetricsLogger::GetInstance()->LogA2dpSession(metrics1); BluetoothMetricsLogger::GetInstance()->LogA2dpSession(metrics2); BluetoothMetricsLogger::GetInstance()->LogBluetoothSessionEnd( - bluetooth::common::DISCONNECT_REASON_UNKNOWN, 133456); + bluetooth::common::DISCONNECT_REASON_UNKNOWN, 133456); std::string msg_str; BluetoothMetricsLogger::GetInstance()->WriteString(&msg_str); EXPECT_THAT(msg_str, StrEq(bt_log_str_)); @@ -643,45 +627,40 @@ TEST_F(BluetoothMetricsLoggerTest, A2DPSessionTwoUpdatesSeparatedbyDumpTest) { metrics2.buffer_underruns_count = 2400; metrics1.codec_index = BTAV_A2DP_CODEC_INDEX_SOURCE_SBC; metrics2.codec_index = BTAV_A2DP_CODEC_INDEX_SOURCE_AAC; - DeviceInfo* info = MakeDeviceInfo( - BTM_COD_MAJOR_AUDIO_TEST, - DeviceInfo_DeviceType::DeviceInfo_DeviceType_DEVICE_TYPE_BREDR); - A2DPSession* session = - MakeA2DPSession(metrics1, A2dpSourceCodec::A2DP_SOURCE_CODEC_SBC); + DeviceInfo* info = MakeDeviceInfo(BTM_COD_MAJOR_AUDIO_TEST, + DeviceInfo_DeviceType::DeviceInfo_DeviceType_DEVICE_TYPE_BREDR); + A2DPSession* session = MakeA2DPSession(metrics1, A2dpSourceCodec::A2DP_SOURCE_CODEC_SBC); bt_sessions_.push_back(MakeBluetoothSession( - 1, - BluetoothSession_ConnectionTechnologyType:: - BluetoothSession_ConnectionTechnologyType_CONNECTION_TECHNOLOGY_TYPE_BREDR, - BluetoothSession_DisconnectReasonType:: - BluetoothSession_DisconnectReasonType_METRICS_DUMP, - info, nullptr, session)); + 1, + BluetoothSession_ConnectionTechnologyType:: + BluetoothSession_ConnectionTechnologyType_CONNECTION_TECHNOLOGY_TYPE_BREDR, + BluetoothSession_DisconnectReasonType::BluetoothSession_DisconnectReasonType_METRICS_DUMP, + info, nullptr, session)); UpdateLog(); BluetoothMetricsLogger::GetInstance()->LogBluetoothSessionStart( - bluetooth::common::CONNECTION_TECHNOLOGY_TYPE_BREDR, 0); + bluetooth::common::CONNECTION_TECHNOLOGY_TYPE_BREDR, 0); BluetoothMetricsLogger::GetInstance()->LogBluetoothSessionDeviceInfo( - BTM_COD_MAJOR_AUDIO_TEST, bluetooth::common::DEVICE_TYPE_BREDR); + BTM_COD_MAJOR_AUDIO_TEST, bluetooth::common::DEVICE_TYPE_BREDR); BluetoothMetricsLogger::GetInstance()->LogA2dpSession(metrics1); sleep_ms(1000); std::string msg_str; BluetoothMetricsLogger::GetInstance()->WriteString(&msg_str); EXPECT_THAT(msg_str, StrEq(bt_log_str_)); ClearLog(); - info = MakeDeviceInfo( - BTM_COD_MAJOR_AUDIO_TEST, - DeviceInfo_DeviceType::DeviceInfo_DeviceType_DEVICE_TYPE_BREDR); + info = MakeDeviceInfo(BTM_COD_MAJOR_AUDIO_TEST, + DeviceInfo_DeviceType::DeviceInfo_DeviceType_DEVICE_TYPE_BREDR); session = MakeA2DPSession(metrics2, A2dpSourceCodec::A2DP_SOURCE_CODEC_AAC); bt_sessions_.push_back(MakeBluetoothSession( - 1, - BluetoothSession_ConnectionTechnologyType:: - BluetoothSession_ConnectionTechnologyType_CONNECTION_TECHNOLOGY_TYPE_BREDR, - BluetoothSession_DisconnectReasonType:: - BluetoothSession_DisconnectReasonType_UNKNOWN, - info, nullptr, session)); + 1, + BluetoothSession_ConnectionTechnologyType:: + BluetoothSession_ConnectionTechnologyType_CONNECTION_TECHNOLOGY_TYPE_BREDR, + BluetoothSession_DisconnectReasonType::BluetoothSession_DisconnectReasonType_UNKNOWN, + info, nullptr, session)); UpdateLog(); sleep_ms(1000); BluetoothMetricsLogger::GetInstance()->LogA2dpSession(metrics2); BluetoothMetricsLogger::GetInstance()->LogBluetoothSessionEnd( - bluetooth::common::DISCONNECT_REASON_UNKNOWN, 0); + bluetooth::common::DISCONNECT_REASON_UNKNOWN, 0); msg_str.clear(); BluetoothMetricsLogger::GetInstance()->WriteString(&msg_str); EXPECT_THAT(msg_str, StrEq(bt_log_str_)); @@ -712,27 +691,24 @@ TEST_F(BluetoothMetricsLoggerTest, A2DPSessionTwoUpdatesSeparatedbyEndTest) { metrics1.buffer_underruns_average = 80; metrics1.buffer_underruns_count = 1200; metrics1.codec_index = BTAV_A2DP_CODEC_INDEX_SOURCE_SBC; - DeviceInfo* info = MakeDeviceInfo( - BTM_COD_MAJOR_AUDIO_TEST, - DeviceInfo_DeviceType::DeviceInfo_DeviceType_DEVICE_TYPE_BREDR); - A2DPSession* session = - MakeA2DPSession(metrics1, A2dpSourceCodec::A2DP_SOURCE_CODEC_SBC); + DeviceInfo* info = MakeDeviceInfo(BTM_COD_MAJOR_AUDIO_TEST, + DeviceInfo_DeviceType::DeviceInfo_DeviceType_DEVICE_TYPE_BREDR); + A2DPSession* session = MakeA2DPSession(metrics1, A2dpSourceCodec::A2DP_SOURCE_CODEC_SBC); bt_sessions_.push_back(MakeBluetoothSession( - 1, - BluetoothSession_ConnectionTechnologyType:: - BluetoothSession_ConnectionTechnologyType_CONNECTION_TECHNOLOGY_TYPE_BREDR, - BluetoothSession_DisconnectReasonType:: - BluetoothSession_DisconnectReasonType_UNKNOWN, - info, nullptr, session)); + 1, + BluetoothSession_ConnectionTechnologyType:: + BluetoothSession_ConnectionTechnologyType_CONNECTION_TECHNOLOGY_TYPE_BREDR, + BluetoothSession_DisconnectReasonType::BluetoothSession_DisconnectReasonType_UNKNOWN, + info, nullptr, session)); UpdateLog(); BluetoothMetricsLogger::GetInstance()->LogBluetoothSessionStart( - bluetooth::common::CONNECTION_TECHNOLOGY_TYPE_BREDR, 0); + bluetooth::common::CONNECTION_TECHNOLOGY_TYPE_BREDR, 0); BluetoothMetricsLogger::GetInstance()->LogBluetoothSessionDeviceInfo( - BTM_COD_MAJOR_AUDIO_TEST, bluetooth::common::DEVICE_TYPE_BREDR); + BTM_COD_MAJOR_AUDIO_TEST, bluetooth::common::DEVICE_TYPE_BREDR); BluetoothMetricsLogger::GetInstance()->LogA2dpSession(metrics1); sleep_ms(1000); BluetoothMetricsLogger::GetInstance()->LogBluetoothSessionEnd( - bluetooth::common::DISCONNECT_REASON_UNKNOWN, 0); + bluetooth::common::DISCONNECT_REASON_UNKNOWN, 0); std::string msg_str; BluetoothMetricsLogger::GetInstance()->WriteString(&msg_str); EXPECT_THAT(msg_str, StrEq(bt_log_str_)); @@ -749,19 +725,18 @@ TEST_F(BluetoothMetricsLoggerTest, A2DPSessionTwoUpdatesSeparatedbyEndTest) { metrics2.codec_index = BTAV_A2DP_CODEC_INDEX_SOURCE_AAC; session = MakeA2DPSession(metrics2, A2dpSourceCodec::A2DP_SOURCE_CODEC_AAC); bt_sessions_.push_back(MakeBluetoothSession( - 1, - BluetoothSession_ConnectionTechnologyType:: - BluetoothSession_ConnectionTechnologyType_CONNECTION_TECHNOLOGY_TYPE_BREDR, - BluetoothSession_DisconnectReasonType:: - BluetoothSession_DisconnectReasonType_UNKNOWN, - nullptr, nullptr, session)); + 1, + BluetoothSession_ConnectionTechnologyType:: + BluetoothSession_ConnectionTechnologyType_CONNECTION_TECHNOLOGY_TYPE_BREDR, + BluetoothSession_DisconnectReasonType::BluetoothSession_DisconnectReasonType_UNKNOWN, + nullptr, nullptr, session)); UpdateLog(); BluetoothMetricsLogger::GetInstance()->LogBluetoothSessionStart( - bluetooth::common::CONNECTION_TECHNOLOGY_TYPE_BREDR, 0); + bluetooth::common::CONNECTION_TECHNOLOGY_TYPE_BREDR, 0); sleep_ms(1000); BluetoothMetricsLogger::GetInstance()->LogA2dpSession(metrics2); BluetoothMetricsLogger::GetInstance()->LogBluetoothSessionEnd( - bluetooth::common::DISCONNECT_REASON_UNKNOWN, 0); + bluetooth::common::DISCONNECT_REASON_UNKNOWN, 0); msg_str.clear(); BluetoothMetricsLogger::GetInstance()->WriteString(&msg_str); EXPECT_THAT(msg_str, StrEq(bt_log_str_)); @@ -809,18 +784,15 @@ TEST_F(BluetoothMetricsLoggerTest, A2DPSessionOnlyTest) { metrics1.codec_index = BTAV_A2DP_CODEC_INDEX_SOURCE_SBC; metrics2.codec_index = BTAV_A2DP_CODEC_INDEX_SOURCE_AAC; metrics_sum.codec_index = BTAV_A2DP_CODEC_INDEX_SOURCE_SBC; - DeviceInfo* info = MakeDeviceInfo( - BTM_COD_MAJOR_AUDIO_TEST, - DeviceInfo_DeviceType::DeviceInfo_DeviceType_DEVICE_TYPE_BREDR); - A2DPSession* session = - MakeA2DPSession(metrics_sum, A2dpSourceCodec::A2DP_SOURCE_CODEC_SBC); + DeviceInfo* info = MakeDeviceInfo(BTM_COD_MAJOR_AUDIO_TEST, + DeviceInfo_DeviceType::DeviceInfo_DeviceType_DEVICE_TYPE_BREDR); + A2DPSession* session = MakeA2DPSession(metrics_sum, A2dpSourceCodec::A2DP_SOURCE_CODEC_SBC); bt_sessions_.push_back(MakeBluetoothSession( - 1, - BluetoothSession_ConnectionTechnologyType:: - BluetoothSession_ConnectionTechnologyType_CONNECTION_TECHNOLOGY_TYPE_BREDR, - BluetoothSession_DisconnectReasonType:: - BluetoothSession_DisconnectReasonType_METRICS_DUMP, - info, nullptr, session)); + 1, + BluetoothSession_ConnectionTechnologyType:: + BluetoothSession_ConnectionTechnologyType_CONNECTION_TECHNOLOGY_TYPE_BREDR, + BluetoothSession_DisconnectReasonType::BluetoothSession_DisconnectReasonType_METRICS_DUMP, + info, nullptr, session)); UpdateLog(); BluetoothMetricsLogger::GetInstance()->LogA2dpSession(metrics1); BluetoothMetricsLogger::GetInstance()->LogA2dpSession(metrics2); @@ -875,56 +847,48 @@ TEST_F(BluetoothMetricsLoggerTest, A2DPSessionDumpBeforeTwoUpdatesTest) { metrics1.codec_index = BTAV_A2DP_CODEC_INDEX_SOURCE_SBC; metrics2.codec_index = BTAV_A2DP_CODEC_INDEX_SOURCE_AAC; metrics_sum.codec_index = BTAV_A2DP_CODEC_INDEX_SOURCE_SBC; - DeviceInfo* info = MakeDeviceInfo( - BTM_COD_MAJOR_AUDIO_TEST, - DeviceInfo_DeviceType::DeviceInfo_DeviceType_DEVICE_TYPE_BREDR); + DeviceInfo* info = MakeDeviceInfo(BTM_COD_MAJOR_AUDIO_TEST, + DeviceInfo_DeviceType::DeviceInfo_DeviceType_DEVICE_TYPE_BREDR); bt_sessions_.push_back(MakeBluetoothSession( - 1, - BluetoothSession_ConnectionTechnologyType:: - BluetoothSession_ConnectionTechnologyType_CONNECTION_TECHNOLOGY_TYPE_BREDR, - BluetoothSession_DisconnectReasonType:: - BluetoothSession_DisconnectReasonType_METRICS_DUMP, - info, nullptr, nullptr)); + 1, + BluetoothSession_ConnectionTechnologyType:: + BluetoothSession_ConnectionTechnologyType_CONNECTION_TECHNOLOGY_TYPE_BREDR, + BluetoothSession_DisconnectReasonType::BluetoothSession_DisconnectReasonType_METRICS_DUMP, + info, nullptr, nullptr)); UpdateLog(); BluetoothMetricsLogger::GetInstance()->LogBluetoothSessionStart( - bluetooth::common::CONNECTION_TECHNOLOGY_TYPE_BREDR, 0); + bluetooth::common::CONNECTION_TECHNOLOGY_TYPE_BREDR, 0); BluetoothMetricsLogger::GetInstance()->LogBluetoothSessionDeviceInfo( - BTM_COD_MAJOR_AUDIO_TEST, bluetooth::common::DEVICE_TYPE_BREDR); + BTM_COD_MAJOR_AUDIO_TEST, bluetooth::common::DEVICE_TYPE_BREDR); sleep_ms(1000); std::string msg_str; BluetoothMetricsLogger::GetInstance()->WriteString(&msg_str); EXPECT_THAT(msg_str, StrEq(bt_log_str_)); ClearLog(); - info = MakeDeviceInfo( - BTM_COD_MAJOR_AUDIO_TEST, - DeviceInfo_DeviceType::DeviceInfo_DeviceType_DEVICE_TYPE_BREDR); - A2DPSession* session = - MakeA2DPSession(metrics_sum, A2dpSourceCodec::A2DP_SOURCE_CODEC_SBC); + info = MakeDeviceInfo(BTM_COD_MAJOR_AUDIO_TEST, + DeviceInfo_DeviceType::DeviceInfo_DeviceType_DEVICE_TYPE_BREDR); + A2DPSession* session = MakeA2DPSession(metrics_sum, A2dpSourceCodec::A2DP_SOURCE_CODEC_SBC); bt_sessions_.push_back(MakeBluetoothSession( - 1, - BluetoothSession_ConnectionTechnologyType:: - BluetoothSession_ConnectionTechnologyType_CONNECTION_TECHNOLOGY_TYPE_BREDR, - BluetoothSession_DisconnectReasonType:: - BluetoothSession_DisconnectReasonType_UNKNOWN, - info, nullptr, session)); + 1, + BluetoothSession_ConnectionTechnologyType:: + BluetoothSession_ConnectionTechnologyType_CONNECTION_TECHNOLOGY_TYPE_BREDR, + BluetoothSession_DisconnectReasonType::BluetoothSession_DisconnectReasonType_UNKNOWN, + info, nullptr, session)); UpdateLog(); BluetoothMetricsLogger::GetInstance()->LogA2dpSession(metrics1); BluetoothMetricsLogger::GetInstance()->LogA2dpSession(metrics2); sleep_ms(1000); BluetoothMetricsLogger::GetInstance()->LogBluetoothSessionEnd( - bluetooth::common::DISCONNECT_REASON_UNKNOWN, 0); + bluetooth::common::DISCONNECT_REASON_UNKNOWN, 0); msg_str.clear(); BluetoothMetricsLogger::GetInstance()->WriteString(&msg_str); EXPECT_THAT(msg_str, StrEq(bt_log_str_)); } TEST_F(BluetoothMetricsLoggerTest, LogHeadsetProfileRfcConnectionTest) { - BluetoothMetricsLogger::GetInstance()->LogHeadsetProfileRfcConnection( - BTA_HSP_SERVICE_ID); - BluetoothMetricsLogger::GetInstance()->LogHeadsetProfileRfcConnection( - BTA_HFP_SERVICE_ID); - BluetoothMetricsLogger::GetInstance()->LogHeadsetProfileRfcConnection( - BTA_HFP_SERVICE_ID); + BluetoothMetricsLogger::GetInstance()->LogHeadsetProfileRfcConnection(BTA_HSP_SERVICE_ID); + BluetoothMetricsLogger::GetInstance()->LogHeadsetProfileRfcConnection(BTA_HFP_SERVICE_ID); + BluetoothMetricsLogger::GetInstance()->LogHeadsetProfileRfcConnection(BTA_HFP_SERVICE_ID); std::string msg_str; BluetoothMetricsLogger::GetInstance()->WriteString(&msg_str); BluetoothLog* metrics = BluetoothLog::default_instance().New(); @@ -960,14 +924,10 @@ TEST_F(BluetoothMetricsLoggerTest, LogHeadsetProfileRfcConnectionTest) { } TEST_F(BluetoothMetricsLoggerTest, LogHeadsetProfileRfcConnectionErrorTest) { - BluetoothMetricsLogger::GetInstance()->LogHeadsetProfileRfcConnection( - BTA_HSP_SERVICE_ID); - BluetoothMetricsLogger::GetInstance()->LogHeadsetProfileRfcConnection( - BTA_HFP_SERVICE_ID); - BluetoothMetricsLogger::GetInstance()->LogHeadsetProfileRfcConnection( - BTA_BIP_SERVICE_ID); - BluetoothMetricsLogger::GetInstance()->LogHeadsetProfileRfcConnection( - BTA_HSP_SERVICE_ID); + BluetoothMetricsLogger::GetInstance()->LogHeadsetProfileRfcConnection(BTA_HSP_SERVICE_ID); + BluetoothMetricsLogger::GetInstance()->LogHeadsetProfileRfcConnection(BTA_HFP_SERVICE_ID); + BluetoothMetricsLogger::GetInstance()->LogHeadsetProfileRfcConnection(BTA_BIP_SERVICE_ID); + BluetoothMetricsLogger::GetInstance()->LogHeadsetProfileRfcConnection(BTA_HSP_SERVICE_ID); std::string msg_str; BluetoothMetricsLogger::GetInstance()->WriteString(&msg_str); BluetoothLog* metrics = BluetoothLog::default_instance().New(); diff --git a/system/common/repeating_timer.cc b/system/common/repeating_timer.cc index f0a75ea69a5..f1e645182a3 100644 --- a/system/common/repeating_timer.cc +++ b/system/common/repeating_timer.cc @@ -25,8 +25,7 @@ namespace bluetooth { namespace common { -constexpr std::chrono::microseconds kMinimumPeriod = - std::chrono::microseconds(1); +constexpr std::chrono::microseconds kMinimumPeriod = std::chrono::microseconds(1); // This runs on user thread RepeatingTimer::~RepeatingTimer() { @@ -37,10 +36,9 @@ RepeatingTimer::~RepeatingTimer() { } // This runs on user thread -bool RepeatingTimer::SchedulePeriodic( - const base::WeakPtr& thread, - const base::Location& from_here, base::RepeatingClosure task, - std::chrono::microseconds period) { +bool RepeatingTimer::SchedulePeriodic(const base::WeakPtr& thread, + const base::Location& from_here, base::RepeatingClosure task, + std::chrono::microseconds period) { if (period < kMinimumPeriod) { log::error("period must be at least {}", kMinimumPeriod.count()); return false; @@ -56,16 +54,14 @@ bool RepeatingTimer::SchedulePeriodic( CancelAndWait(); expected_time_next_task_us_ = time_next_task_us; task_ = std::move(task); - task_wrapper_.Reset( - base::Bind(&RepeatingTimer::RunTask, base::Unretained(this))); + task_wrapper_.Reset(base::Bind(&RepeatingTimer::RunTask, base::Unretained(this))); message_loop_thread_ = thread; period_ = period; uint64_t time_until_next_us = time_next_task_us - clock_tick_us_(); - if (!thread->DoInThreadDelayed( - from_here, task_wrapper_.callback(), - std::chrono::microseconds(time_until_next_us))) { - log::error("failed to post task to message loop for thread {}, from {}", - *thread, from_here.ToString()); + if (!thread->DoInThreadDelayed(from_here, task_wrapper_.callback(), + std::chrono::microseconds(time_until_next_us))) { + log::error("failed to post task to message loop for thread {}, from {}", *thread, + from_here.ToString()); expected_time_next_task_us_ = 0; task_wrapper_.Cancel(); message_loop_thread_ = nullptr; @@ -102,8 +98,8 @@ void RepeatingTimer::CancelHelper(std::promise promise) { return; } scheduled_thread->DoInThread( - FROM_HERE, base::BindOnce(&RepeatingTimer::CancelClosure, - base::Unretained(this), std::move(promise))); + FROM_HERE, base::BindOnce(&RepeatingTimer::CancelClosure, base::Unretained(this), + std::move(promise))); } // This runs on message loop thread @@ -132,9 +128,8 @@ void RepeatingTimer::RunTask() { log::error("message_loop_thread_ is null or is not running"); return; } - log::assert_that( - message_loop_thread_->GetThreadId() == base::PlatformThread::CurrentId(), - "task must run on message loop thread"); + log::assert_that(message_loop_thread_->GetThreadId() == base::PlatformThread::CurrentId(), + "task must run on message loop thread"); int64_t period_us = period_.count(); expected_time_next_task_us_ += period_us; @@ -145,20 +140,16 @@ void RepeatingTimer::RunTask() { // multiple of period remaining_time_us = (remaining_time_us % period_us + period_us) % period_us; } - message_loop_thread_->DoInThreadDelayed( - FROM_HERE, task_wrapper_.callback(), - std::chrono::microseconds(remaining_time_us)); + message_loop_thread_->DoInThreadDelayed(FROM_HERE, task_wrapper_.callback(), + std::chrono::microseconds(remaining_time_us)); uint64_t time_before_task_us = clock_tick_us_(); task_.Run(); uint64_t time_after_task_us = clock_tick_us_(); - auto task_time_us = - static_cast(time_after_task_us - time_before_task_us); + auto task_time_us = static_cast(time_after_task_us - time_before_task_us); if (task_time_us > period_.count()) { - log::error( - "Periodic task execution took {} microseconds, longer than interval {} " - "microseconds", - task_time_us, period_.count()); + log::error("Periodic task execution took {} microseconds, longer than interval {} microseconds", + task_time_us, period_.count()); } } diff --git a/system/common/repeating_timer.h b/system/common/repeating_timer.h index 7f004c31fc8..6c22f0d4674 100644 --- a/system/common/repeating_timer.h +++ b/system/common/repeating_timer.h @@ -39,9 +39,8 @@ class MessageLoopThread; * being executed */ class RepeatingTimer final { - public: - RepeatingTimer(uint64_t (*clock_tick_us)(void) = - bluetooth::common::time_get_os_boottime_us) +public: + RepeatingTimer(uint64_t (*clock_tick_us)(void) = bluetooth::common::time_get_os_boottime_us) : expected_time_next_task_us_(0), clock_tick_us_(clock_tick_us) {} RepeatingTimer(const RepeatingTimer&) = delete; RepeatingTimer& operator=(const RepeatingTimer&) = delete; @@ -61,8 +60,7 @@ class RepeatingTimer final { * @return true iff task is scheduled successfully */ bool SchedulePeriodic(const base::WeakPtr& thread, - const base::Location& from_here, - base::RepeatingClosure task, + const base::Location& from_here, base::RepeatingClosure task, std::chrono::microseconds period); /** @@ -82,7 +80,7 @@ class RepeatingTimer final { */ bool IsScheduled() const; - private: +private: base::WeakPtr message_loop_thread_; base::CancelableClosure task_wrapper_; base::RepeatingClosure task_; diff --git a/system/common/repeating_timer_unittest.cc b/system/common/repeating_timer_unittest.cc index f8defb5e45b..817f3e9bb0e 100644 --- a/system/common/repeating_timer_unittest.cc +++ b/system/common/repeating_timer_unittest.cc @@ -34,7 +34,7 @@ constexpr uint32_t delay_error_ms = 100; * Unit tests to verify Task Scheduler. */ class RepeatingTimerTest : public ::testing::Test { - public: +public: void ShouldNotHappen() { FAIL() << "Should not happen"; } void IncreaseTaskCounter(int scheduled_tasks, std::promise* promise) { @@ -57,13 +57,12 @@ class RepeatingTimerTest : public ::testing::Test { counter_++; } - void VerifyDelayTimeAndSleep(std::chrono::steady_clock::time_point start_time, - int interval_ms, int scheduled_tasks, - int task_length_ms, + void VerifyDelayTimeAndSleep(std::chrono::steady_clock::time_point start_time, int interval_ms, + int scheduled_tasks, int task_length_ms, std::promise* promise) { auto end_time = std::chrono::steady_clock::now(); - auto actual_delay = std::chrono::duration_cast( - end_time - start_time); + auto actual_delay = + std::chrono::duration_cast(end_time - start_time); counter_++; int64_t scheduled_delay_ms = interval_ms * counter_; if (counter_ == scheduled_tasks) { @@ -82,19 +81,18 @@ class RepeatingTimerTest : public ::testing::Test { auto future = promise_->get_future(); auto start_time = std::chrono::steady_clock::now(); timer_->SchedulePeriodic( - message_loop_thread.GetWeakPtr(), FROM_HERE, - base::BindRepeating(&RepeatingTimerTest::VerifyDelayTimeAndSleep, - base::Unretained(this), start_time, - interval_between_tasks_ms, scheduled_tasks, - task_length_ms, promise_), - std::chrono::milliseconds(interval_between_tasks_ms)); + message_loop_thread.GetWeakPtr(), FROM_HERE, + base::BindRepeating(&RepeatingTimerTest::VerifyDelayTimeAndSleep, + base::Unretained(this), start_time, interval_between_tasks_ms, + scheduled_tasks, task_length_ms, promise_), + std::chrono::milliseconds(interval_between_tasks_ms)); future.get(); timer_->CancelAndWait(); } void CancelRepeatingTimerAndWait() { timer_->CancelAndWait(); } - protected: +protected: void SetUp() override { ::testing::Test::SetUp(); counter_ = 0; @@ -118,9 +116,7 @@ class RepeatingTimerTest : public ::testing::Test { std::promise* promise_; }; -TEST_F(RepeatingTimerTest, initial_is_not_scheduled) { - ASSERT_FALSE(timer_->IsScheduled()); -} +TEST_F(RepeatingTimerTest, initial_is_not_scheduled) { ASSERT_FALSE(timer_->IsScheduled()); } TEST_F(RepeatingTimerTest, cancel_without_scheduling) { std::string name = "test_thread"; @@ -140,11 +136,10 @@ TEST_F(RepeatingTimerTest, periodic_run) { uint32_t delay_ms = 5; int num_tasks = 200; - timer_->SchedulePeriodic( - message_loop_thread.GetWeakPtr(), FROM_HERE, - base::BindRepeating(&RepeatingTimerTest::IncreaseTaskCounter, - base::Unretained(this), num_tasks, promise_), - std::chrono::milliseconds(delay_ms)); + timer_->SchedulePeriodic(message_loop_thread.GetWeakPtr(), FROM_HERE, + base::BindRepeating(&RepeatingTimerTest::IncreaseTaskCounter, + base::Unretained(this), num_tasks, promise_), + std::chrono::milliseconds(delay_ms)); future.get(); ASSERT_GE(counter_, num_tasks); timer_->CancelAndWait(); @@ -157,10 +152,9 @@ TEST_F(RepeatingTimerTest, schedule_periodic_task_zero_interval) { uint32_t interval_ms = 0; ASSERT_FALSE(timer_->SchedulePeriodic( - message_loop_thread.GetWeakPtr(), FROM_HERE, - base::BindRepeating(&RepeatingTimerTest::ShouldNotHappen, - base::Unretained(this)), - std::chrono::milliseconds(interval_ms))); + message_loop_thread.GetWeakPtr(), FROM_HERE, + base::BindRepeating(&RepeatingTimerTest::ShouldNotHappen, base::Unretained(this)), + std::chrono::milliseconds(interval_ms))); std::this_thread::sleep_for(std::chrono::milliseconds(delay_error_ms)); } @@ -171,10 +165,9 @@ TEST_F(RepeatingTimerTest, periodic_delete_without_cancel) { message_loop_thread.StartUp(); uint32_t delay_ms = 5; timer_->SchedulePeriodic( - message_loop_thread.GetWeakPtr(), FROM_HERE, - base::BindRepeating(&RepeatingTimerTest::ShouldNotHappen, - base::Unretained(this)), - std::chrono::milliseconds(delay_ms)); + message_loop_thread.GetWeakPtr(), FROM_HERE, + base::BindRepeating(&RepeatingTimerTest::ShouldNotHappen, base::Unretained(this)), + std::chrono::milliseconds(delay_ms)); delete timer_; timer_ = nullptr; std::this_thread::sleep_for(std::chrono::milliseconds(delay_error_ms)); @@ -185,8 +178,7 @@ TEST_F(RepeatingTimerTest, cancel_single_task_near_fire_no_race_condition) { MessageLoopThread message_loop_thread(name); message_loop_thread.StartUp(); uint32_t delay_ms = 5; - timer_->SchedulePeriodic(message_loop_thread.GetWeakPtr(), FROM_HERE, - base::DoNothing(), + timer_->SchedulePeriodic(message_loop_thread.GetWeakPtr(), FROM_HERE, base::DoNothing(), std::chrono::milliseconds(delay_ms)); std::this_thread::sleep_for(std::chrono::milliseconds(delay_ms)); timer_->CancelAndWait(); @@ -200,18 +192,15 @@ TEST_F(RepeatingTimerTest, cancel_periodic_task) { int num_tasks = 5; auto future = promise_->get_future(); - timer_->SchedulePeriodic( - message_loop_thread.GetWeakPtr(), FROM_HERE, - base::BindRepeating(&RepeatingTimerTest::IncreaseTaskCounter, - base::Unretained(this), num_tasks, promise_), - std::chrono::milliseconds(delay_ms)); + timer_->SchedulePeriodic(message_loop_thread.GetWeakPtr(), FROM_HERE, + base::BindRepeating(&RepeatingTimerTest::IncreaseTaskCounter, + base::Unretained(this), num_tasks, promise_), + std::chrono::milliseconds(delay_ms)); future.wait(); timer_->CancelAndWait(); - std::this_thread::sleep_for( - std::chrono::milliseconds(delay_ms + delay_error_ms)); + std::this_thread::sleep_for(std::chrono::milliseconds(delay_ms + delay_error_ms)); int counter = counter_; - std::this_thread::sleep_for( - std::chrono::milliseconds(delay_ms + delay_error_ms)); + std::this_thread::sleep_for(std::chrono::milliseconds(delay_ms + delay_error_ms)); ASSERT_EQ(counter, counter_); } @@ -227,8 +216,7 @@ TEST_F(RepeatingTimerTest, schedule_multiple_delayed_slow_tasks) { VerifyMultipleDelayedTasks(10, 1, 2); } -TEST_F(RepeatingTimerTest, - message_loop_thread_down_cancel_scheduled_periodic_task) { +TEST_F(RepeatingTimerTest, message_loop_thread_down_cancel_scheduled_periodic_task) { std::string name = "test_thread"; MessageLoopThread message_loop_thread(name); message_loop_thread.StartUp(); @@ -237,17 +225,14 @@ TEST_F(RepeatingTimerTest, uint32_t delay_ms = 5; int num_tasks = 5; - timer_->SchedulePeriodic( - message_loop_thread.GetWeakPtr(), FROM_HERE, - base::BindRepeating(&RepeatingTimerTest::IncreaseTaskCounter, - base::Unretained(this), num_tasks, promise_), - std::chrono::milliseconds(delay_ms)); + timer_->SchedulePeriodic(message_loop_thread.GetWeakPtr(), FROM_HERE, + base::BindRepeating(&RepeatingTimerTest::IncreaseTaskCounter, + base::Unretained(this), num_tasks, promise_), + std::chrono::milliseconds(delay_ms)); future.wait(); message_loop_thread.ShutDown(); - std::this_thread::sleep_for( - std::chrono::milliseconds(delay_ms + delay_error_ms)); + std::this_thread::sleep_for(std::chrono::milliseconds(delay_ms + delay_error_ms)); int counter = counter_; - std::this_thread::sleep_for( - std::chrono::milliseconds(delay_ms + delay_error_ms)); + std::this_thread::sleep_for(std::chrono::milliseconds(delay_ms + delay_error_ms)); ASSERT_EQ(counter, counter_); } diff --git a/system/common/state_machine.h b/system/common/state_machine.h index 912ff9afc36..383028f3685 100644 --- a/system/common/state_machine.h +++ b/system/common/state_machine.h @@ -29,7 +29,7 @@ namespace common { * State machine used by Bluetooth native stack. */ class StateMachine { - public: +public: enum { kStateInvalid = -1 }; /** @@ -38,7 +38,7 @@ class StateMachine { class State { friend class StateMachine; - public: + public: /** * Constructor. * @@ -67,7 +67,7 @@ class StateMachine { */ int StateId() const { return state_id_; } - protected: + protected: /** * Called when a state is entered. */ @@ -91,21 +91,18 @@ class StateMachine { * * @param dest_state the state to transition to. It cannot be nullptr. */ - void TransitionTo(StateMachine::State* dest_state) { - sm_.TransitionTo(dest_state); - } + void TransitionTo(StateMachine::State* dest_state) { sm_.TransitionTo(dest_state); } - private: + private: StateMachine& sm_; int state_id_; }; - StateMachine() - : initial_state_(nullptr), - previous_state_(nullptr), - current_state_(nullptr) {} + StateMachine() : initial_state_(nullptr), previous_state_(nullptr), current_state_(nullptr) {} ~StateMachine() { - for (auto& kv : states_) delete kv.second; + for (auto& kv : states_) { + delete kv.second; + } } /** @@ -152,7 +149,9 @@ class StateMachine { * @return true if the processing was completed, otherwise false */ bool ProcessEvent(uint32_t event, void* p_data) { - if (current_state_ == nullptr) return false; + if (current_state_ == nullptr) { + return false; + } return current_state_->ProcessEvent(event, p_data); } @@ -165,8 +164,7 @@ class StateMachine { void TransitionTo(int dest_state_id) { auto it = states_.find(dest_state_id); - log::assert_that(it != states_.end(), "Unknown State ID: {}", - dest_state_id); + log::assert_that(it != states_.end(), "Unknown State ID: {}", dest_state_id); State* dest_state = it->second; TransitionTo(dest_state); } @@ -192,9 +190,7 @@ class StateMachine { * * @param state the state to add */ - void AddState(State* state) { - states_.insert(std::make_pair(state->StateId(), state)); - } + void AddState(State* state) { states_.insert(std::make_pair(state->StateId(), state)); } /** * Set the initial state of the State Machine. @@ -203,7 +199,7 @@ class StateMachine { */ void SetInitialState(State* initial_state) { initial_state_ = initial_state; } - private: +private: State* initial_state_; State* previous_state_; State* current_state_; diff --git a/system/common/state_machine_unittest.cc b/system/common/state_machine_unittest.cc index 896e983357f..3feac315f7e 100644 --- a/system/common/state_machine_unittest.cc +++ b/system/common/state_machine_unittest.cc @@ -16,10 +16,10 @@ * ******************************************************************************/ -#include - #include "common/state_machine.h" +#include + using bluetooth::common::StateMachine; namespace { @@ -34,7 +34,7 @@ static char dataTwo = 2; } // namespace class StateMachineImpl : public StateMachine { - public: +public: enum { kStateZero, kStateOne, @@ -42,7 +42,7 @@ class StateMachineImpl : public StateMachine { }; class StateZero : public State { - public: + public: StateZero(StateMachine& sm) : State(sm, kStateZero), on_enter_(false), @@ -71,7 +71,7 @@ class StateMachineImpl : public StateMachine { }; class StateOne : public State { - public: + public: StateOne(StateMachine& sm) : State(sm, kStateOne), on_enter_(false), @@ -100,7 +100,7 @@ class StateMachineImpl : public StateMachine { }; class StateTwo : public State { - public: + public: StateTwo(StateMachine& sm) : State(sm, kStateTwo), on_enter_(false), @@ -145,7 +145,7 @@ class StateMachineImpl : public StateMachine { }; class StateMachineTest : public ::testing::Test { - protected: +protected: StateMachineTest() {} void SetUp() override { sm_.Start(); } @@ -245,7 +245,7 @@ TEST_F(StateMachineTest, test_process_event) { // Process an event and transition to StateZero // NOTE: StateZero was exited before and has local state ASSERT_FALSE(sm_.state_zero_->on_enter_); - ASSERT_TRUE(sm_.state_zero_->on_exit_); // NOTE: already exited before + ASSERT_TRUE(sm_.state_zero_->on_exit_); // NOTE: already exited before ASSERT_EQ(sm_.state_zero_->event_, kEventZero); // NOTE: state from before ASSERT_EQ(sm_.state_zero_->data_, &dataZero); // NOTE: state from before ASSERT_TRUE(sm_.ProcessEvent(kEventTwo, &dataTwo)); diff --git a/system/common/stop_watch_legacy.cc b/system/common/stop_watch_legacy.cc index de2a8bfdef7..e7884b5f04e 100644 --- a/system/common/stop_watch_legacy.cc +++ b/system/common/stop_watch_legacy.cc @@ -40,11 +40,10 @@ void StopWatchLegacy::RecordLog(StopWatchLog log) { std::unique_lock lock(stopwatch_log_mutex, std::defer_lock); if (!lock.try_lock()) { log::info("try_lock fail. log content: {}, took {} us", log.message, - static_cast( - std::chrono::duration_cast( - stopwatch_logs[current_buffer_index].end_timestamp - - stopwatch_logs[current_buffer_index].start_timestamp) - .count())); + static_cast(std::chrono::duration_cast( + stopwatch_logs[current_buffer_index].end_timestamp - + stopwatch_logs[current_buffer_index].start_timestamp) + .count())); return; } if (current_buffer_index >= LOG_BUFFER_LENGTH) { @@ -69,20 +68,17 @@ void StopWatchLegacy::DumpStopWatchLog() { } std::stringstream ss; auto now = stopwatch_logs[current_buffer_index].timestamp; - auto millis = std::chrono::duration_cast( - now.time_since_epoch()) % - 1000; + auto millis = + std::chrono::duration_cast(now.time_since_epoch()) % 1000; auto now_time_t = std::chrono::system_clock::to_time_t(now); ss << std::put_time(std::localtime(&now_time_t), "%Y-%m-%d %H:%M:%S"); ss << '.' << std::setfill('0') << std::setw(3) << millis.count(); std::string start_timestamp = ss.str(); - log::info("{}: {}: took {} us", start_timestamp, - stopwatch_logs[current_buffer_index].message, - static_cast( - std::chrono::duration_cast( - stopwatch_logs[current_buffer_index].end_timestamp - - stopwatch_logs[current_buffer_index].start_timestamp) - .count())); + log::info("{}: {}: took {} us", start_timestamp, stopwatch_logs[current_buffer_index].message, + static_cast(std::chrono::duration_cast( + stopwatch_logs[current_buffer_index].end_timestamp - + stopwatch_logs[current_buffer_index].start_timestamp) + .count())); current_buffer_index++; } log::info("=-----------------------------------="); diff --git a/system/common/stop_watch_legacy.h b/system/common/stop_watch_legacy.h index 2573d99cdf3..f2bc5ddf5e0 100644 --- a/system/common/stop_watch_legacy.h +++ b/system/common/stop_watch_legacy.h @@ -30,12 +30,12 @@ typedef struct { } StopWatchLog; class StopWatchLegacy { - public: +public: static void DumpStopWatchLog(void); StopWatchLegacy(std::string text); ~StopWatchLegacy(); - private: +private: std::string text_; std::chrono::system_clock::time_point timestamp_; std::chrono::high_resolution_clock::time_point start_timestamp_; diff --git a/system/common/test/thread_performance_test.cc b/system/common/test/thread_performance_test.cc index c8805baafa4..66964862701 100644 --- a/system/common/test/thread_performance_test.cc +++ b/system/common/test/thread_performance_test.cc @@ -50,7 +50,7 @@ void callback_batch(fixed_queue_t* queue, void* data) { } class PerformanceTest : public testing::Test { - protected: +protected: void SetUp() override { set_up_promise_ = std::make_unique>(); g_counter = 0; @@ -67,7 +67,7 @@ class PerformanceTest : public testing::Test { }; class MessageLoopPerformanceTest : public PerformanceTest { - public: +public: static void RunThread(void* context) { auto test = static_cast(context); test->RunMessageLoop(); @@ -81,8 +81,8 @@ class MessageLoopPerformanceTest : public PerformanceTest { message_loop_ = new btbase::AbstractMessageLoop(); run_loop_ = new base::RunLoop(); message_loop_->task_runner()->PostTask( - FROM_HERE, base::Bind(&std::promise::set_value, - base::Unretained(set_up_promise_.get()))); + FROM_HERE, + base::Bind(&std::promise::set_value, base::Unretained(set_up_promise_.get()))); run_loop_->Run(); delete message_loop_; message_loop_ = nullptr; @@ -90,13 +90,13 @@ class MessageLoopPerformanceTest : public PerformanceTest { run_loop_ = nullptr; } - protected: +protected: btbase::AbstractMessageLoop* message_loop_ = nullptr; base::RunLoop* run_loop_ = nullptr; }; class OsiThreadMessageLoopPerformanceTest : public MessageLoopPerformanceTest { - protected: +protected: void SetUp() override { MessageLoopPerformanceTest::SetUp(); std::future set_up_future = set_up_promise_->get_future(); @@ -106,8 +106,7 @@ class OsiThreadMessageLoopPerformanceTest : public MessageLoopPerformanceTest { } void TearDown() override { - message_loop_->task_runner()->PostTask(FROM_HERE, - run_loop_->QuitWhenIdleClosure()); + message_loop_->task_runner()->PostTask(FROM_HERE, run_loop_->QuitWhenIdleClosure()); thread_free(thread_); thread_ = nullptr; MessageLoopPerformanceTest::TearDown(); @@ -120,28 +119,25 @@ TEST_F(OsiThreadMessageLoopPerformanceTest, message_loop_speed_test) { g_counter = 0; g_counter_promise = std::make_unique>(); std::future counter_future = g_counter_promise->get_future(); - std::chrono::steady_clock::time_point start_time = - std::chrono::steady_clock::now(); + std::chrono::steady_clock::time_point start_time = std::chrono::steady_clock::now(); for (int i = 0; i < NUM_MESSAGES_TO_SEND; i++) { fixed_queue_enqueue(bt_msg_queue_, (void*)&g_counter); - message_loop_->task_runner()->PostTask( - FROM_HERE, base::Bind(&callback_batch, bt_msg_queue_, nullptr)); + message_loop_->task_runner()->PostTask(FROM_HERE, + base::Bind(&callback_batch, bt_msg_queue_, nullptr)); } counter_future.wait(); - std::chrono::steady_clock::time_point end_time = - std::chrono::steady_clock::now(); + std::chrono::steady_clock::time_point end_time = std::chrono::steady_clock::now(); std::chrono::milliseconds duration = - std::chrono::duration_cast(end_time - - start_time); + std::chrono::duration_cast(end_time - start_time); - log::info("OsiThreadMessageLoopPerformanceTest, {} ms, {} messages", - duration.count(), NUM_MESSAGES_TO_SEND); + log::info("OsiThreadMessageLoopPerformanceTest, {} ms, {} messages", duration.count(), + NUM_MESSAGES_TO_SEND); } class StlThreadMessageLoopPerformanceTest : public MessageLoopPerformanceTest { - protected: +protected: void SetUp() override { MessageLoopPerformanceTest::SetUp(); std::future set_up_future = set_up_promise_->get_future(); @@ -150,8 +146,7 @@ class StlThreadMessageLoopPerformanceTest : public MessageLoopPerformanceTest { } void TearDown() override { - message_loop_->task_runner()->PostTask(FROM_HERE, - run_loop_->QuitWhenIdleClosure()); + message_loop_->task_runner()->PostTask(FROM_HERE, run_loop_->QuitWhenIdleClosure()); thread_->join(); delete thread_; thread_ = nullptr; @@ -165,40 +160,34 @@ TEST_F(StlThreadMessageLoopPerformanceTest, stl_thread_speed_test) { g_counter = 0; g_counter_promise = std::make_unique>(); std::future counter_future = g_counter_promise->get_future(); - std::chrono::steady_clock::time_point start_time = - std::chrono::steady_clock::now(); + std::chrono::steady_clock::time_point start_time = std::chrono::steady_clock::now(); for (int i = 0; i < NUM_MESSAGES_TO_SEND; i++) { fixed_queue_enqueue(bt_msg_queue_, (void*)&g_counter); - message_loop_->task_runner()->PostTask( - FROM_HERE, base::Bind(&callback_batch, bt_msg_queue_, nullptr)); + message_loop_->task_runner()->PostTask(FROM_HERE, + base::Bind(&callback_batch, bt_msg_queue_, nullptr)); } counter_future.wait(); - std::chrono::steady_clock::time_point end_time = - std::chrono::steady_clock::now(); + std::chrono::steady_clock::time_point end_time = std::chrono::steady_clock::now(); std::chrono::milliseconds duration = - std::chrono::duration_cast(end_time - - start_time); + std::chrono::duration_cast(end_time - start_time); - log::info("StlThreadMessageLoopPerformanceTest, {} ms, {} messages", - duration.count(), NUM_MESSAGES_TO_SEND); + log::info("StlThreadMessageLoopPerformanceTest, {} ms, {} messages", duration.count(), + NUM_MESSAGES_TO_SEND); } -class PosixThreadMessageLoopPerformanceTest - : public MessageLoopPerformanceTest { - protected: +class PosixThreadMessageLoopPerformanceTest : public MessageLoopPerformanceTest { +protected: void SetUp() override { MessageLoopPerformanceTest::SetUp(); std::future set_up_future = set_up_promise_->get_future(); - pthread_create(&thread_, nullptr, &MessageLoopPerformanceTest::RunPThread, - (void*)this); + pthread_create(&thread_, nullptr, &MessageLoopPerformanceTest::RunPThread, (void*)this); set_up_future.wait(); } void TearDown() override { - message_loop_->task_runner()->PostTask(FROM_HERE, - run_loop_->QuitWhenIdleClosure()); + message_loop_->task_runner()->PostTask(FROM_HERE, run_loop_->QuitWhenIdleClosure()); pthread_join(thread_, nullptr); MessageLoopPerformanceTest::TearDown(); } @@ -211,28 +200,25 @@ TEST_F(PosixThreadMessageLoopPerformanceTest, stl_thread_speed_test) { g_counter_promise = std::make_unique>(); std::future counter_future = g_counter_promise->get_future(); - std::chrono::steady_clock::time_point start_time = - std::chrono::steady_clock::now(); + std::chrono::steady_clock::time_point start_time = std::chrono::steady_clock::now(); for (int i = 0; i < NUM_MESSAGES_TO_SEND; i++) { fixed_queue_enqueue(bt_msg_queue_, (void*)&g_counter); - message_loop_->task_runner()->PostTask( - FROM_HERE, base::Bind(&callback_batch, bt_msg_queue_, nullptr)); + message_loop_->task_runner()->PostTask(FROM_HERE, + base::Bind(&callback_batch, bt_msg_queue_, nullptr)); } counter_future.wait(); - std::chrono::steady_clock::time_point end_time = - std::chrono::steady_clock::now(); + std::chrono::steady_clock::time_point end_time = std::chrono::steady_clock::now(); std::chrono::milliseconds duration = - std::chrono::duration_cast(end_time - - start_time); + std::chrono::duration_cast(end_time - start_time); - log::info("PosixThreadMessageLoopPerformanceTest, {} ms, {} messages", - duration.count(), NUM_MESSAGES_TO_SEND); + log::info("PosixThreadMessageLoopPerformanceTest, {} ms, {} messages", duration.count(), + NUM_MESSAGES_TO_SEND); } class ReactorPerformanceTest : public PerformanceTest { - protected: +protected: void SetUp() override { PerformanceTest::SetUp(); thread_ = thread_new("ReactorPerformanceTest thread"); @@ -251,39 +237,32 @@ TEST_F(ReactorPerformanceTest, reactor_thread_speed_test) { g_counter = 0; g_counter_promise = std::make_unique>(); std::future counter_future = g_counter_promise->get_future(); - fixed_queue_register_dequeue(bt_msg_queue_, thread_get_reactor(thread_), - callback_batch, nullptr); + fixed_queue_register_dequeue(bt_msg_queue_, thread_get_reactor(thread_), callback_batch, nullptr); - std::chrono::steady_clock::time_point start_time = - std::chrono::steady_clock::now(); + std::chrono::steady_clock::time_point start_time = std::chrono::steady_clock::now(); for (int i = 0; i < NUM_MESSAGES_TO_SEND; i++) { fixed_queue_enqueue(bt_msg_queue_, (void*)&g_counter); } counter_future.wait(); - std::chrono::steady_clock::time_point end_time = - std::chrono::steady_clock::now(); + std::chrono::steady_clock::time_point end_time = std::chrono::steady_clock::now(); std::chrono::milliseconds duration = - std::chrono::duration_cast(end_time - - start_time); + std::chrono::duration_cast(end_time - start_time); fixed_queue_unregister_dequeue(bt_msg_queue_); - log::info("ReactorPerformanceTest, {} ms, {} messages", duration.count(), - NUM_MESSAGES_TO_SEND); + log::info("ReactorPerformanceTest, {} ms, {} messages", duration.count(), NUM_MESSAGES_TO_SEND); } class WorkerThreadPerformanceTest : public PerformanceTest { - protected: +protected: void SetUp() override { PerformanceTest::SetUp(); std::future set_up_future = set_up_promise_->get_future(); - worker_thread_ = - new MessageLoopThread("WorkerThreadPerformanceTest thread"); + worker_thread_ = new MessageLoopThread("WorkerThreadPerformanceTest thread"); worker_thread_->StartUp(); - worker_thread_->DoInThread( - FROM_HERE, base::BindOnce(&std::promise::set_value, - base::Unretained(set_up_promise_.get()))); + worker_thread_->DoInThread(FROM_HERE, base::BindOnce(&std::promise::set_value, + base::Unretained(set_up_promise_.get()))); set_up_future.wait(); } @@ -302,36 +281,32 @@ TEST_F(WorkerThreadPerformanceTest, worker_thread_speed_test) { g_counter_promise = std::make_unique>(); std::future counter_future = g_counter_promise->get_future(); - std::chrono::steady_clock::time_point start_time = - std::chrono::steady_clock::now(); + std::chrono::steady_clock::time_point start_time = std::chrono::steady_clock::now(); for (int i = 0; i < NUM_MESSAGES_TO_SEND; i++) { fixed_queue_enqueue(bt_msg_queue_, (void*)&g_counter); - worker_thread_->DoInThread( - FROM_HERE, base::BindOnce(&callback_batch, bt_msg_queue_, nullptr)); + worker_thread_->DoInThread(FROM_HERE, base::BindOnce(&callback_batch, bt_msg_queue_, nullptr)); } counter_future.wait(); - std::chrono::steady_clock::time_point end_time = - std::chrono::steady_clock::now(); + std::chrono::steady_clock::time_point end_time = std::chrono::steady_clock::now(); std::chrono::milliseconds duration = - std::chrono::duration_cast(end_time - - start_time); + std::chrono::duration_cast(end_time - start_time); log::info("WorkerThreadPerformanceTest, {} ms, {} messages", duration.count(), NUM_MESSAGES_TO_SEND); } class LibChromeThreadPerformanceTest : public PerformanceTest { - protected: +protected: void SetUp() override { PerformanceTest::SetUp(); std::future set_up_future = set_up_promise_->get_future(); thread_ = new base::Thread("LibChromeThreadPerformanceTest thread"); thread_->Start(); thread_->task_runner()->PostTask( - FROM_HERE, base::Bind(&std::promise::set_value, - base::Unretained(set_up_promise_.get()))); + FROM_HERE, + base::Bind(&std::promise::set_value, base::Unretained(set_up_promise_.get()))); set_up_future.wait(); } @@ -350,22 +325,19 @@ TEST_F(LibChromeThreadPerformanceTest, worker_thread_speed_test) { g_counter_promise = std::make_unique>(); std::future counter_future = g_counter_promise->get_future(); - std::chrono::steady_clock::time_point start_time = - std::chrono::steady_clock::now(); + std::chrono::steady_clock::time_point start_time = std::chrono::steady_clock::now(); for (int i = 0; i < NUM_MESSAGES_TO_SEND; i++) { fixed_queue_enqueue(bt_msg_queue_, (void*)&g_counter); - thread_->task_runner()->PostTask( - FROM_HERE, base::Bind(&callback_batch, bt_msg_queue_, nullptr)); + thread_->task_runner()->PostTask(FROM_HERE, + base::Bind(&callback_batch, bt_msg_queue_, nullptr)); } counter_future.wait(); - std::chrono::steady_clock::time_point end_time = - std::chrono::steady_clock::now(); + std::chrono::steady_clock::time_point end_time = std::chrono::steady_clock::now(); std::chrono::milliseconds duration = - std::chrono::duration_cast(end_time - - start_time); + std::chrono::duration_cast(end_time - start_time); - log::info("LibChromeThreadPerformanceTest, {} ms, {} messages", - duration.count(), NUM_MESSAGES_TO_SEND); + log::info("LibChromeThreadPerformanceTest, {} ms, {} messages", duration.count(), + NUM_MESSAGES_TO_SEND); } diff --git a/system/common/time_util.cc b/system/common/time_util.cc index 6799270ddf1..10277d69110 100644 --- a/system/common/time_util.cc +++ b/system/common/time_util.cc @@ -39,23 +39,20 @@ uint64_t time_get_os_boottime_us() { struct timespec ts_now = {}; clock_gettime(CLOCK_BOOTTIME, &ts_now); - return ((uint64_t)ts_now.tv_sec * 1000000L) + - ((uint64_t)ts_now.tv_nsec / 1000); + return ((uint64_t)ts_now.tv_sec * 1000000L) + ((uint64_t)ts_now.tv_nsec / 1000); } uint64_t time_gettimeofday_us() { struct timeval tv = {}; gettimeofday(&tv, nullptr); - return static_cast(tv.tv_sec) * 1000000ULL + - static_cast(tv.tv_usec); + return static_cast(tv.tv_sec) * 1000000ULL + static_cast(tv.tv_usec); } uint64_t time_get_os_monotonic_raw_us() { struct timespec ts_now = {}; clock_gettime(CLOCK_MONOTONIC_RAW, &ts_now); - return ((uint64_t)ts_now.tv_sec * 1000000L) + - ((uint64_t)ts_now.tv_nsec / 1000); + return ((uint64_t)ts_now.tv_sec * 1000000L) + ((uint64_t)ts_now.tv_nsec / 1000); } } // namespace common diff --git a/system/common/time_util_unittest.cc b/system/common/time_util_unittest.cc index 848ef067466..72533c86a52 100644 --- a/system/common/time_util_unittest.cc +++ b/system/common/time_util_unittest.cc @@ -16,10 +16,10 @@ * ******************************************************************************/ -#include - #include "common/time_util.h" +#include + // Generous upper bound: 10 seconds static const uint32_t TEST_TIME_DELTA_UPPER_BOUND_MS = 10 * 1000; diff --git a/system/conf/interop_database.conf b/system/conf/interop_database.conf index 72d0a76a2e1..ba5c679b22d 100644 --- a/system/conf/interop_database.conf +++ b/system/conf/interop_database.conf @@ -750,7 +750,7 @@ HAVAL M6 = Name_Based [INTEROP_DELAY_SCO_FOR_MO_CALL] 00:09:93 = Address_Based -# some remote hid devices cannot work properly as they laod special hid usb driver in kernel, +# some remote hid devices cannot work properly as they load special hid usb driver in kernel, # so modify their vid/pid so that generic hid driver are loaded. [INTEROP_CHANGE_HID_VID_PID] RK-Bluetooth keyboard = Name_Based diff --git a/system/device/fuzzer/btdevice_esco_fuzzer.cpp b/system/device/fuzzer/btdevice_esco_fuzzer.cpp index dfa014aa30e..821d3492981 100644 --- a/system/device/fuzzer/btdevice_esco_fuzzer.cpp +++ b/system/device/fuzzer/btdevice_esco_fuzzer.cpp @@ -27,73 +27,71 @@ using namespace std; constexpr size_t kNumAddressOctets = 6; constexpr size_t kMaxStringLength = 10; constexpr interop_feature_t kInteropFeature[] = { - interop_feature_t::INTEROP_DISABLE_LE_SECURE_CONNECTIONS, - interop_feature_t::INTEROP_AUTO_RETRY_PAIRING, - interop_feature_t::INTEROP_DISABLE_ABSOLUTE_VOLUME, - interop_feature_t::INTEROP_DISABLE_AUTO_PAIRING, - interop_feature_t::INTEROP_KEYBOARD_REQUIRES_FIXED_PIN, - interop_feature_t::INTEROP_2MBPS_LINK_ONLY, - interop_feature_t::INTEROP_DISABLE_SDP_AFTER_PAIRING, - interop_feature_t::INTEROP_REMOVE_HID_DIG_DESCRIPTOR, - interop_feature_t::INTEROP_DISABLE_SNIFF_DURING_SCO, - interop_feature_t::INTEROP_HID_PREF_CONN_SUP_TIMEOUT_3S, - interop_feature_t::INTEROP_GATTC_NO_SERVICE_CHANGED_IND, - interop_feature_t::INTEROP_INCREASE_AG_CONN_TIMEOUT, - interop_feature_t::INTEROP_DISABLE_LE_CONN_PREFERRED_PARAMS, - interop_feature_t::INTEROP_DISABLE_AAC_CODEC, - interop_feature_t::INTEROP_DISABLE_AAC_VBR_CODEC, - interop_feature_t::INTEROP_ENABLE_AAC_CODEC, - interop_feature_t::INTEROP_DISABLE_ROLE_SWITCH_POLICY, - interop_feature_t::INTEROP_HFP_1_7_DENYLIST, - interop_feature_t::INTEROP_HFP_1_8_DENYLIST, - interop_feature_t::INTEROP_ADV_PBAP_VER_1_1, - interop_feature_t::INTEROP_UPDATE_HID_SSR_MAX_LAT, - interop_feature_t::INTEROP_DISABLE_AUTH_FOR_HID_POINTING, - interop_feature_t::INTEROP_DISABLE_AVDTP_RECONFIGURE, - interop_feature_t::INTEROP_DYNAMIC_ROLE_SWITCH, - interop_feature_t::INTEROP_DISABLE_HF_INDICATOR, - interop_feature_t::INTEROP_DISABLE_ROLE_SWITCH, - interop_feature_t::INTEROP_DELAY_SCO_FOR_MT_CALL, - interop_feature_t::INTEROP_DISABLE_CODEC_NEGOTIATION, - interop_feature_t::INTEROP_DISABLE_PLAYER_APPLICATION_SETTING_CMDS, - interop_feature_t::INTEROP_DISABLE_CONNECTION_AFTER_COLLISION, - interop_feature_t::INTEROP_DISABLE_LE_CONN_UPDATES, - interop_feature_t::INTEROP_ADV_PBAP_VER_1_2, - interop_feature_t::INTEROP_DISABLE_PCE_SDP_AFTER_PAIRING, - interop_feature_t::INTEROP_AVRCP_BROWSE_OPEN_CHANNEL_COLLISION, - interop_feature_t::INTEROP_DISABLE_SNIFF_LINK_DURING_SCO, - interop_feature_t::INTEROP_DISABLE_SNIFF_DURING_CALL, - interop_feature_t::INTEROP_HID_HOST_LIMIT_SNIFF_INTERVAL, - interop_feature_t::INTEROP_DISABLE_REFRESH_ACCEPT_SIG_TIMER, - interop_feature_t::INTEROP_SKIP_INCOMING_STATE, - interop_feature_t::INTEROP_NOT_UPDATE_AVRCP_PAUSED_TO_REMOTE, - interop_feature_t:: - INTEROP_PHONE_POLICY_INCREASED_DELAY_CONNECT_OTHER_PROFILES, - interop_feature_t::INTEROP_DISABLE_NAME_REQUEST, - interop_feature_t::INTEROP_AVRCP_1_4_ONLY, - interop_feature_t::INTEROP_DISABLE_SNIFF, - interop_feature_t::INTEROP_DISABLE_AVDTP_SUSPEND, - interop_feature_t::INTEROP_SLC_SKIP_BIND_COMMAND, - interop_feature_t::INTEROP_AVRCP_1_3_ONLY, - interop_feature_t:: - INTEROP_PHONE_POLICY_REDUCED_DELAY_CONNECT_OTHER_PROFILES, - interop_feature_t::INTEROP_HFP_FAKE_INCOMING_CALL_INDICATOR, - interop_feature_t::INTEROP_HFP_SEND_CALL_INDICATORS_BACK_TO_BACK, - interop_feature_t::INTEROP_SETUP_SCO_WITH_NO_DELAY_AFTER_SLC_DURING_CALL, - interop_feature_t::INTEROP_ENABLE_PREFERRED_CONN_PARAMETER, - interop_feature_t::INTEROP_RETRY_SCO_AFTER_REMOTE_REJECT_SCO, - interop_feature_t::INTEROP_DELAY_SCO_FOR_MO_CALL, - interop_feature_t::INTEROP_CHANGE_HID_VID_PID, - interop_feature_t::INTEROP_DISABLE_ROLE_SWITCH_DURING_CONNECTION, - interop_feature_t::INTEROP_DISABLE_ROBUST_CACHING, - interop_feature_t::INTEROP_HFP_1_7_ALLOWLIST, - interop_feature_t::INTEROP_IGNORE_DISC_BEFORE_SIGNALLING_TIMEOUT, + interop_feature_t::INTEROP_DISABLE_LE_SECURE_CONNECTIONS, + interop_feature_t::INTEROP_AUTO_RETRY_PAIRING, + interop_feature_t::INTEROP_DISABLE_ABSOLUTE_VOLUME, + interop_feature_t::INTEROP_DISABLE_AUTO_PAIRING, + interop_feature_t::INTEROP_KEYBOARD_REQUIRES_FIXED_PIN, + interop_feature_t::INTEROP_2MBPS_LINK_ONLY, + interop_feature_t::INTEROP_DISABLE_SDP_AFTER_PAIRING, + interop_feature_t::INTEROP_REMOVE_HID_DIG_DESCRIPTOR, + interop_feature_t::INTEROP_DISABLE_SNIFF_DURING_SCO, + interop_feature_t::INTEROP_HID_PREF_CONN_SUP_TIMEOUT_3S, + interop_feature_t::INTEROP_GATTC_NO_SERVICE_CHANGED_IND, + interop_feature_t::INTEROP_INCREASE_AG_CONN_TIMEOUT, + interop_feature_t::INTEROP_DISABLE_LE_CONN_PREFERRED_PARAMS, + interop_feature_t::INTEROP_DISABLE_AAC_CODEC, + interop_feature_t::INTEROP_DISABLE_AAC_VBR_CODEC, + interop_feature_t::INTEROP_ENABLE_AAC_CODEC, + interop_feature_t::INTEROP_DISABLE_ROLE_SWITCH_POLICY, + interop_feature_t::INTEROP_HFP_1_7_DENYLIST, + interop_feature_t::INTEROP_HFP_1_8_DENYLIST, + interop_feature_t::INTEROP_ADV_PBAP_VER_1_1, + interop_feature_t::INTEROP_UPDATE_HID_SSR_MAX_LAT, + interop_feature_t::INTEROP_DISABLE_AUTH_FOR_HID_POINTING, + interop_feature_t::INTEROP_DISABLE_AVDTP_RECONFIGURE, + interop_feature_t::INTEROP_DYNAMIC_ROLE_SWITCH, + interop_feature_t::INTEROP_DISABLE_HF_INDICATOR, + interop_feature_t::INTEROP_DISABLE_ROLE_SWITCH, + interop_feature_t::INTEROP_DELAY_SCO_FOR_MT_CALL, + interop_feature_t::INTEROP_DISABLE_CODEC_NEGOTIATION, + interop_feature_t::INTEROP_DISABLE_PLAYER_APPLICATION_SETTING_CMDS, + interop_feature_t::INTEROP_DISABLE_CONNECTION_AFTER_COLLISION, + interop_feature_t::INTEROP_DISABLE_LE_CONN_UPDATES, + interop_feature_t::INTEROP_ADV_PBAP_VER_1_2, + interop_feature_t::INTEROP_DISABLE_PCE_SDP_AFTER_PAIRING, + interop_feature_t::INTEROP_AVRCP_BROWSE_OPEN_CHANNEL_COLLISION, + interop_feature_t::INTEROP_DISABLE_SNIFF_LINK_DURING_SCO, + interop_feature_t::INTEROP_DISABLE_SNIFF_DURING_CALL, + interop_feature_t::INTEROP_HID_HOST_LIMIT_SNIFF_INTERVAL, + interop_feature_t::INTEROP_DISABLE_REFRESH_ACCEPT_SIG_TIMER, + interop_feature_t::INTEROP_SKIP_INCOMING_STATE, + interop_feature_t::INTEROP_NOT_UPDATE_AVRCP_PAUSED_TO_REMOTE, + interop_feature_t::INTEROP_PHONE_POLICY_INCREASED_DELAY_CONNECT_OTHER_PROFILES, + interop_feature_t::INTEROP_DISABLE_NAME_REQUEST, + interop_feature_t::INTEROP_AVRCP_1_4_ONLY, + interop_feature_t::INTEROP_DISABLE_SNIFF, + interop_feature_t::INTEROP_DISABLE_AVDTP_SUSPEND, + interop_feature_t::INTEROP_SLC_SKIP_BIND_COMMAND, + interop_feature_t::INTEROP_AVRCP_1_3_ONLY, + interop_feature_t::INTEROP_PHONE_POLICY_REDUCED_DELAY_CONNECT_OTHER_PROFILES, + interop_feature_t::INTEROP_HFP_FAKE_INCOMING_CALL_INDICATOR, + interop_feature_t::INTEROP_HFP_SEND_CALL_INDICATORS_BACK_TO_BACK, + interop_feature_t::INTEROP_SETUP_SCO_WITH_NO_DELAY_AFTER_SLC_DURING_CALL, + interop_feature_t::INTEROP_ENABLE_PREFERRED_CONN_PARAMETER, + interop_feature_t::INTEROP_RETRY_SCO_AFTER_REMOTE_REJECT_SCO, + interop_feature_t::INTEROP_DELAY_SCO_FOR_MO_CALL, + interop_feature_t::INTEROP_CHANGE_HID_VID_PID, + interop_feature_t::INTEROP_DISABLE_ROLE_SWITCH_DURING_CONNECTION, + interop_feature_t::INTEROP_DISABLE_ROBUST_CACHING, + interop_feature_t::INTEROP_HFP_1_7_ALLOWLIST, + interop_feature_t::INTEROP_IGNORE_DISC_BEFORE_SIGNALLING_TIMEOUT, }; constexpr esco_codec_t kEscoCodec[] = { - esco_codec_t::SCO_CODEC_CVSD_D1, esco_codec_t::ESCO_CODEC_CVSD_S3, - esco_codec_t::ESCO_CODEC_CVSD_S4, esco_codec_t::ESCO_CODEC_MSBC_T1, - esco_codec_t::ESCO_CODEC_MSBC_T2, esco_codec_t::ESCO_CODEC_LC3_T1, - esco_codec_t::ESCO_CODEC_LC3_T2, + esco_codec_t::SCO_CODEC_CVSD_D1, esco_codec_t::ESCO_CODEC_CVSD_S3, + esco_codec_t::ESCO_CODEC_CVSD_S4, esco_codec_t::ESCO_CODEC_MSBC_T1, + esco_codec_t::ESCO_CODEC_MSBC_T2, esco_codec_t::ESCO_CODEC_LC3_T1, + esco_codec_t::ESCO_CODEC_LC3_T2, }; void generateString(FuzzedDataProvider& fdp, string& addressString) { @@ -119,159 +117,133 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { module_init(&interop_module); while (mFuzzedDataProvider.remaining_bytes()) { - auto invokeBtDeviceApi = mFuzzedDataProvider.PickValueInArray< - const std::function>({ - [&]() { - generateString(mFuzzedDataProvider, addressString); - RawAddress::FromString(addressString, fuzzAddress); - interop_match_addr(mFuzzedDataProvider.PickValueInArray( - kInteropFeature) /* feature */, - &fuzzAddress); - }, - [&]() { - interop_match_name( - mFuzzedDataProvider.PickValueInArray( - kInteropFeature) /* feature */, - mFuzzedDataProvider.ConsumeRandomLengthString(kMaxStringLength) - .c_str() /* name */ - ); - }, - [&]() { - interop_match_manufacturer( - mFuzzedDataProvider.PickValueInArray( - kInteropFeature) /* feature */, - mFuzzedDataProvider.ConsumeIntegral() /* manufacturer */ - ); - }, - [&]() { - interop_match_vendor_product_ids( - mFuzzedDataProvider.PickValueInArray( - kInteropFeature) /* feature */, - mFuzzedDataProvider.ConsumeIntegral() /* vendor_id */, - mFuzzedDataProvider.ConsumeIntegral() /* product_id */ - ); - }, - [&]() { - generateString(mFuzzedDataProvider, addressString); - RawAddress::FromString(addressString, fuzzAddress); - interop_database_add( - mFuzzedDataProvider.PickValueInArray( - kInteropFeature) /* feature */, - &fuzzAddress, - mFuzzedDataProvider.ConsumeIntegralInRange( - 1, RawAddress::kLength - 1) /* length */ - ); - }, - [&]() { interop_database_clear(); }, - [&]() { - interop_database_match_version( - mFuzzedDataProvider.PickValueInArray( - kInteropFeature) /* feature */, - mFuzzedDataProvider.ConsumeIntegral() /* version */ - ); - }, - [&]() { - generateString(mFuzzedDataProvider, addressString); - RawAddress::FromString(addressString, fuzzAddress); - uint16_t max_lat = 0; - interop_match_addr_get_max_lat(mFuzzedDataProvider.PickValueInArray( - kInteropFeature) /* feature */, - &fuzzAddress, &max_lat); - }, - [&]() { - generateString(mFuzzedDataProvider, addressString); - RawAddress::FromString(addressString, fuzzAddress); - interop_feature_name_to_feature_id(addressString.c_str()); - }, - [&]() { - esco_parameters_for_codec( - mFuzzedDataProvider.PickValueInArray(kEscoCodec) /* codec */, - true); - }, - [&]() { - interop_database_add_manufacturer( - mFuzzedDataProvider.PickValueInArray( - kInteropFeature) /* feature */, - mFuzzedDataProvider - .ConsumeIntegral() /* manufacturer */); - }, - [&]() { - interop_database_add_vndr_prdt( - mFuzzedDataProvider.PickValueInArray( - kInteropFeature) /* feature */, - mFuzzedDataProvider.ConsumeIntegral() /* vendor_id */, - mFuzzedDataProvider.ConsumeIntegral() /* product_id */); - }, - [&]() { - generateString(mFuzzedDataProvider, addressString); - RawAddress::FromString(addressString, fuzzAddress); - interop_database_add_addr_max_lat( - mFuzzedDataProvider.PickValueInArray( - kInteropFeature) /* feature */, - &fuzzAddress, - mFuzzedDataProvider.ConsumeIntegral() /* max_lat */); - }, - [&]() { - interop_database_add_version( - mFuzzedDataProvider.PickValueInArray( - kInteropFeature) /* feature */, - mFuzzedDataProvider.ConsumeIntegral() /* version */); - }, - [&]() { - interop_database_add_addr_lmp_version( - mFuzzedDataProvider.PickValueInArray( - kInteropFeature) /* feature */, - &fuzzAddress, - mFuzzedDataProvider.ConsumeIntegral() /* lmp_ver */, - mFuzzedDataProvider - .ConsumeIntegral() /* lmp_sub_ver */); - }, - [&]() { - uint8_t lmp_ver = 0; - uint16_t lmp_sub_ver = 0; - interop_database_match_addr_get_lmp_ver( - mFuzzedDataProvider.PickValueInArray( - kInteropFeature) /* feature */, - &fuzzAddress, &lmp_ver, &lmp_sub_ver); - }, - [&]() { - interop_database_remove_manufacturer( - mFuzzedDataProvider.PickValueInArray( - kInteropFeature) /* feature */, - mFuzzedDataProvider - .ConsumeIntegral() /* manufacturer */); - }, - [&]() { - interop_database_remove_vndr_prdt( - mFuzzedDataProvider.PickValueInArray( - kInteropFeature) /* feature */, - mFuzzedDataProvider.ConsumeIntegral() /* vendor_id */, - mFuzzedDataProvider.ConsumeIntegral() /* product_id */); - }, - [&]() { - generateString(mFuzzedDataProvider, addressString); - RawAddress::FromString(addressString, fuzzAddress); - interop_database_remove_addr_max_lat( - mFuzzedDataProvider.PickValueInArray( - kInteropFeature) /* feature */, - &fuzzAddress, - mFuzzedDataProvider.ConsumeIntegral() /* max_lat */); - }, - [&]() { - interop_database_remove_version( - mFuzzedDataProvider.PickValueInArray( - kInteropFeature) /* feature */, - mFuzzedDataProvider.ConsumeIntegral() /*version*/); - }, - [&]() { - interop_database_remove_addr_lmp_version( - mFuzzedDataProvider.PickValueInArray( - kInteropFeature) /* feature */, - &fuzzAddress, - mFuzzedDataProvider.ConsumeIntegral() /* lmp_ver */, - mFuzzedDataProvider - .ConsumeIntegral() /* lmp_sub_ver */); - }, + auto invokeBtDeviceApi = mFuzzedDataProvider.PickValueInArray>({ + [&]() { + generateString(mFuzzedDataProvider, addressString); + RawAddress::FromString(addressString, fuzzAddress); + interop_match_addr( + mFuzzedDataProvider.PickValueInArray(kInteropFeature) /* feature */, + &fuzzAddress); + }, + [&]() { + interop_match_name( + mFuzzedDataProvider.PickValueInArray(kInteropFeature) /* feature */, + mFuzzedDataProvider.ConsumeRandomLengthString(kMaxStringLength) + .c_str() /* name */ + ); + }, + [&]() { + interop_match_manufacturer( + mFuzzedDataProvider.PickValueInArray(kInteropFeature) /* feature */, + mFuzzedDataProvider.ConsumeIntegral() /* manufacturer */ + ); + }, + [&]() { + interop_match_vendor_product_ids( + mFuzzedDataProvider.PickValueInArray(kInteropFeature) /* feature */, + mFuzzedDataProvider.ConsumeIntegral() /* vendor_id */, + mFuzzedDataProvider.ConsumeIntegral() /* product_id */ + ); + }, + [&]() { + generateString(mFuzzedDataProvider, addressString); + RawAddress::FromString(addressString, fuzzAddress); + interop_database_add( + mFuzzedDataProvider.PickValueInArray(kInteropFeature) /* feature */, + &fuzzAddress, + mFuzzedDataProvider.ConsumeIntegralInRange( + 1, RawAddress::kLength - 1) /* length */ + ); + }, + [&]() { interop_database_clear(); }, + [&]() { + interop_database_match_version( + mFuzzedDataProvider.PickValueInArray(kInteropFeature) /* feature */, + mFuzzedDataProvider.ConsumeIntegral() /* version */ + ); + }, + [&]() { + generateString(mFuzzedDataProvider, addressString); + RawAddress::FromString(addressString, fuzzAddress); + uint16_t max_lat = 0; + interop_match_addr_get_max_lat( + mFuzzedDataProvider.PickValueInArray(kInteropFeature) /* feature */, + &fuzzAddress, &max_lat); + }, + [&]() { + generateString(mFuzzedDataProvider, addressString); + RawAddress::FromString(addressString, fuzzAddress); + interop_feature_name_to_feature_id(addressString.c_str()); + }, + [&]() { + esco_parameters_for_codec( + mFuzzedDataProvider.PickValueInArray(kEscoCodec) /* codec */, true); + }, + [&]() { + interop_database_add_manufacturer( + mFuzzedDataProvider.PickValueInArray(kInteropFeature) /* feature */, + mFuzzedDataProvider.ConsumeIntegral() /* manufacturer */); + }, + [&]() { + interop_database_add_vndr_prdt( + mFuzzedDataProvider.PickValueInArray(kInteropFeature) /* feature */, + mFuzzedDataProvider.ConsumeIntegral() /* vendor_id */, + mFuzzedDataProvider.ConsumeIntegral() /* product_id */); + }, + [&]() { + generateString(mFuzzedDataProvider, addressString); + RawAddress::FromString(addressString, fuzzAddress); + interop_database_add_addr_max_lat( + mFuzzedDataProvider.PickValueInArray(kInteropFeature) /* feature */, + &fuzzAddress, mFuzzedDataProvider.ConsumeIntegral() /* max_lat */); + }, + [&]() { + interop_database_add_version( + mFuzzedDataProvider.PickValueInArray(kInteropFeature) /* feature */, + mFuzzedDataProvider.ConsumeIntegral() /* version */); + }, + [&]() { + interop_database_add_addr_lmp_version( + mFuzzedDataProvider.PickValueInArray(kInteropFeature) /* feature */, + &fuzzAddress, mFuzzedDataProvider.ConsumeIntegral() /* lmp_ver */, + mFuzzedDataProvider.ConsumeIntegral() /* lmp_sub_ver */); + }, + [&]() { + uint8_t lmp_ver = 0; + uint16_t lmp_sub_ver = 0; + interop_database_match_addr_get_lmp_ver( + mFuzzedDataProvider.PickValueInArray(kInteropFeature) /* feature */, + &fuzzAddress, &lmp_ver, &lmp_sub_ver); + }, + [&]() { + interop_database_remove_manufacturer( + mFuzzedDataProvider.PickValueInArray(kInteropFeature) /* feature */, + mFuzzedDataProvider.ConsumeIntegral() /* manufacturer */); + }, + [&]() { + interop_database_remove_vndr_prdt( + mFuzzedDataProvider.PickValueInArray(kInteropFeature) /* feature */, + mFuzzedDataProvider.ConsumeIntegral() /* vendor_id */, + mFuzzedDataProvider.ConsumeIntegral() /* product_id */); + }, + [&]() { + generateString(mFuzzedDataProvider, addressString); + RawAddress::FromString(addressString, fuzzAddress); + interop_database_remove_addr_max_lat( + mFuzzedDataProvider.PickValueInArray(kInteropFeature) /* feature */, + &fuzzAddress, mFuzzedDataProvider.ConsumeIntegral() /* max_lat */); + }, + [&]() { + interop_database_remove_version( + mFuzzedDataProvider.PickValueInArray(kInteropFeature) /* feature */, + mFuzzedDataProvider.ConsumeIntegral() /*version*/); + }, + [&]() { + interop_database_remove_addr_lmp_version( + mFuzzedDataProvider.PickValueInArray(kInteropFeature) /* feature */, + &fuzzAddress, mFuzzedDataProvider.ConsumeIntegral() /* lmp_ver */, + mFuzzedDataProvider.ConsumeIntegral() /* lmp_sub_ver */); + }, }); invokeBtDeviceApi(); } diff --git a/system/device/include/device_iot_conf_defs.h b/system/device/include/device_iot_conf_defs.h index 5ffc9882886..4132deab545 100644 --- a/system/device/include/device_iot_conf_defs.h +++ b/system/device/include/device_iot_conf_defs.h @@ -39,8 +39,7 @@ #define IOT_CONF_KEY_GAP_CONN_FAIL_COUNT "ProfileGap_ConnectFailCount" #define IOT_CONF_KEY_GAP_DISC_COUNT "ProfileGap_DiscCount" #define IOT_CONF_KEY_GAP_DISC_AUTHFAIL_COUNT "ProfileGap_DiscAuthFailCount" -#define IOT_CONF_KEY_GAP_DISC_CONNTIMEOUT_COUNT \ - "ProfileGap_DiscConnTimeoutCount" +#define IOT_CONF_KEY_GAP_DISC_CONNTIMEOUT_COUNT "ProfileGap_DiscConnTimeoutCount" #define IOT_CONF_KEY_A2DP_ROLE "ProfileA2dp_Role" #define IOT_CONF_KEY_A2DP_VERSION "ProfileA2dp_Version" #define IOT_CONF_KEY_A2DP_CODECTYPE "ProfileA2dp_CodecType" diff --git a/system/device/include/device_iot_config.h b/system/device/include/device_iot_config.h index 74ef574dd9e..28275d46b42 100644 --- a/system/device/include/device_iot_config.h +++ b/system/device/include/device_iot_config.h @@ -29,33 +29,23 @@ static const char DEVICE_IOT_CONFIG_MODULE[] = "device_iot_config_module"; -bool device_iot_config_get_int(const std::string& section, - const std::string& key, int& value); -bool device_iot_config_set_int(const std::string& section, - const std::string& key, int value); -bool device_iot_config_int_add_one(const std::string& section, - const std::string& key); -bool device_iot_config_get_hex(const std::string& section, - const std::string& key, int& value); -bool device_iot_config_set_hex(const std::string& section, - const std::string& key, int value, int byte_num); -bool device_iot_config_set_hex_if_greater(const std::string& section, - const std::string& key, int value, - int byte_num); -bool device_iot_config_get_str(const std::string& section, - const std::string& key, char* value, +bool device_iot_config_get_int(const std::string& section, const std::string& key, int& value); +bool device_iot_config_set_int(const std::string& section, const std::string& key, int value); +bool device_iot_config_int_add_one(const std::string& section, const std::string& key); +bool device_iot_config_get_hex(const std::string& section, const std::string& key, int& value); +bool device_iot_config_set_hex(const std::string& section, const std::string& key, int value, + int byte_num); +bool device_iot_config_set_hex_if_greater(const std::string& section, const std::string& key, + int value, int byte_num); +bool device_iot_config_get_str(const std::string& section, const std::string& key, char* value, int* size_bytes); -bool device_iot_config_set_str(const std::string& section, - const std::string& key, +bool device_iot_config_set_str(const std::string& section, const std::string& key, const std::string& value); -bool device_iot_config_get_bin(const std::string& section, - const std::string& key, uint8_t* value, +bool device_iot_config_get_bin(const std::string& section, const std::string& key, uint8_t* value, size_t* length); -bool device_iot_config_set_bin(const std::string& section, - const std::string& key, const uint8_t* value, - size_t length); -size_t device_iot_config_get_bin_length(const std::string& section, - const std::string& key); +bool device_iot_config_set_bin(const std::string& section, const std::string& key, + const uint8_t* value, size_t length); +size_t device_iot_config_get_bin_length(const std::string& section, const std::string& key); #define DEVICE_IOT_CONFIG_ADDR(method, addr, ...) \ device_iot_config_##method((addr).ToString(), ##__VA_ARGS__) @@ -94,10 +84,8 @@ size_t device_iot_config_get_bin_length(const std::string& section, DEVICE_IOT_CONFIG_ADDR(get_bin, addr, ##__VA_ARGS__) bool device_iot_config_has_section(const std::string& section); -bool device_iot_config_exist(const std::string& section, - const std::string& key); -bool device_iot_config_remove(const std::string& section, - const std::string& key); +bool device_iot_config_exist(const std::string& section, const std::string& key); +bool device_iot_config_remove(const std::string& section, const std::string& key); void device_iot_config_flush(void); bool device_iot_config_clear(void); diff --git a/system/device/include/esco_parameters.h b/system/device/include/esco_parameters.h index 18886e969b7..eb0327cc442 100644 --- a/system/device/include/esco_parameters.h +++ b/system/device/include/esco_parameters.h @@ -61,8 +61,7 @@ typedef enum { typedef uint8_t esco_coding_format_t; // PCM Data Formats (BT 4.1 or later Assigned numbers) -#define ESCO_PCM_DATA_FORMAT_NA \ - ((uint8_t)0x00) /* N/A to coding format in use */ +#define ESCO_PCM_DATA_FORMAT_NA ((uint8_t)0x00) /* N/A to coding format in use */ #define ESCO_PCM_DATA_FORMAT_1_COMP ((uint8_t)0x01) /* 1's complement */ #define ESCO_PCM_DATA_FORMAT_2_COMP ((uint8_t)0x02) /* 2's complement */ #define ESCO_PCM_DATA_FORMAT_SIGN ((uint8_t)0x03) /* Sign-magnitude */ @@ -70,8 +69,8 @@ typedef uint8_t esco_coding_format_t; typedef uint8_t esco_pcm_data_format_t; // SCO Data Path -#define ESCO_DATA_PATH_PCM 1 /* 0x01-0xFE (PCM Chan) */ -#define ESCO_DATA_PATH_HCI 0 /* HCI-0, 0x01-0xFE (PCM Chan) */ +#define ESCO_DATA_PATH_PCM 1 /* 0x01-0xFE (PCM Chan) */ +#define ESCO_DATA_PATH_HCI 0 /* HCI-0, 0x01-0xFE (PCM Chan) */ typedef uint8_t esco_data_path_t; // eSCO constants @@ -107,45 +106,39 @@ typedef uint16_t esco_packet_types_t; // type definition typedef struct { esco_coding_format_t coding_format; /* Coding Format*/ - uint16_t company_id; /* Company ID from BT SIG Assigned Numbers */ - uint16_t vendor_specific_codec_id; /* Vendor Specific Codec ID */ + uint16_t company_id; /* Company ID from BT SIG Assigned Numbers */ + uint16_t vendor_specific_codec_id; /* Vendor Specific Codec ID */ } esco_coding_id_format_t; // Enhanced setup/accept synchronous connection See BT 4.1 or later HCI spec for // details typedef struct { - esco_txrx_bandwidth_t - transmit_bandwidth; /* Transmit Bandwidth (in octets/second) */ - esco_txrx_bandwidth_t receive_bandwidth; /* RX BW (# of octets/second) */ - esco_coding_id_format_t transmit_coding_format; /* TX coding format */ - esco_coding_id_format_t receive_coding_format; /* RX coding format */ - uint16_t transmit_codec_frame_size; /* TX CODEC frame size (OTA frame size) */ - uint16_t receive_codec_frame_size; /* RX CODEC frame size (OTA frame size) */ - esco_io_bandwidth_t input_bandwidth; /* Input BW (nominal rate octets/sec) */ - esco_io_bandwidth_t - output_bandwidth; /* Output BW (nominal rate octets/sec) */ - esco_coding_id_format_t input_coding_format; /* Input coding format */ - esco_coding_id_format_t output_coding_format; /* Output coding format */ - uint16_t input_coded_data_size; /* Input coded data size (in bits) */ - uint16_t output_coded_data_size; /* Output coded data size (in bits) */ - esco_pcm_data_format_t - input_pcm_data_format; /* Input PCM data format (see hcidefs.h) */ - esco_pcm_data_format_t - output_pcm_data_format; /* Output PCM data format (see hcidefs.h) */ - uint8_t input_pcm_payload_msb_position; /* Input PCM sample payload MSB - position */ - uint8_t output_pcm_payload_msb_position; /* Output PCM sample payload MSB - position */ - esco_data_path_t input_data_path; /* 0x00 - HCI, or 0x01-0xFE for VS) */ - esco_data_path_t output_data_path; /* 0x00 - HCI, or 0x01-0xFE for VS) */ - uint8_t input_transport_unit_size; /* Input transport unit size */ - uint8_t output_transport_unit_size; /* Output transport unit size */ - uint16_t max_latency_ms; /* Maximum latency (0x4-0xFFFE in msecs) */ - esco_packet_types_t packet_types; /* Packet Types */ - esco_retransmission_effort_t - retransmission_effort; /* 0x00-0x02, 0xFF don't care */ - esco_coding_format_t - coding_format; /* Extra field to store codec when TX/RX is transparent */ + esco_txrx_bandwidth_t transmit_bandwidth; /* Transmit Bandwidth (in octets/second) */ + esco_txrx_bandwidth_t receive_bandwidth; /* RX BW (# of octets/second) */ + esco_coding_id_format_t transmit_coding_format; /* TX coding format */ + esco_coding_id_format_t receive_coding_format; /* RX coding format */ + uint16_t transmit_codec_frame_size; /* TX CODEC frame size (OTA frame size) */ + uint16_t receive_codec_frame_size; /* RX CODEC frame size (OTA frame size) */ + esco_io_bandwidth_t input_bandwidth; /* Input BW (nominal rate octets/sec) */ + esco_io_bandwidth_t output_bandwidth; /* Output BW (nominal rate octets/sec) */ + esco_coding_id_format_t input_coding_format; /* Input coding format */ + esco_coding_id_format_t output_coding_format; /* Output coding format */ + uint16_t input_coded_data_size; /* Input coded data size (in bits) */ + uint16_t output_coded_data_size; /* Output coded data size (in bits) */ + esco_pcm_data_format_t input_pcm_data_format; /* Input PCM data format (see hcidefs.h) */ + esco_pcm_data_format_t output_pcm_data_format; /* Output PCM data format (see hcidefs.h) */ + uint8_t input_pcm_payload_msb_position; /* Input PCM sample payload MSB + position */ + uint8_t output_pcm_payload_msb_position; /* Output PCM sample payload MSB + position */ + esco_data_path_t input_data_path; /* 0x00 - HCI, or 0x01-0xFE for VS) */ + esco_data_path_t output_data_path; /* 0x00 - HCI, or 0x01-0xFE for VS) */ + uint8_t input_transport_unit_size; /* Input transport unit size */ + uint8_t output_transport_unit_size; /* Output transport unit size */ + uint16_t max_latency_ms; /* Maximum latency (0x4-0xFFFE in msecs) */ + esco_packet_types_t packet_types; /* Packet Types */ + esco_retransmission_effort_t retransmission_effort; /* 0x00-0x02, 0xFF don't care */ + esco_coding_format_t coding_format; /* Extra field to store codec when TX/RX is transparent */ } enh_esco_params_t; // Get the enhanced eSCO configuration parameters for the provided |codec| diff --git a/system/device/include/interop.h b/system/device/include/interop.h index 2231b2571c6..25967aafa30 100644 --- a/system/device/include/interop.h +++ b/system/device/include/interop.h @@ -308,7 +308,7 @@ typedef enum { // are sent before sco is opened INTEROP_DELAY_SCO_FOR_MO_CALL, - // Some remote hid devices cannot work properly as they laod special hid usb + // Some remote hid devices cannot work properly as they load special hid usb // driver in kernel, so modify their vid/pid so that generic hid driver are // loaded. INTEROP_CHANGE_HID_VID_PID, @@ -363,8 +363,7 @@ typedef enum { // identified by the |interop_feature_t| enum. This API is used for simple // address based lookups where more information is not available. No // look-ups or random address resolution are performed on |addr|. -bool interop_match_addr(const interop_feature_t feature, - const RawAddress* addr); +bool interop_match_addr(const interop_feature_t feature, const RawAddress* addr); // Check if a given remote device |name| matches a known workaround. // Name comparisons are case sensitive and do not allow for partial matches. @@ -377,23 +376,21 @@ bool interop_match_name(const interop_feature_t feature, const char* name); // This api will lookup remote name with |addr| by btif_storage api internally. // Then if either interop_match_addr or interop_match_name is matched, this // function will return true. -bool interop_match_addr_or_name(const interop_feature_t feature, - const RawAddress* addr, - bt_status_t (*get_remote_device_property)( - const RawAddress*, bt_property_t*)); +bool interop_match_addr_or_name(const interop_feature_t feature, const RawAddress* addr, + bt_status_t (*get_remote_device_property)(const RawAddress*, + bt_property_t*)); // Check if a given |manufacturer| matches a known interoperability workaround // as identified by the |interop_feature_t| enum. This API is used for // manufacturer based lookups where more information is not available. -bool interop_match_manufacturer(const interop_feature_t feature, - uint16_t manufacturer); +bool interop_match_manufacturer(const interop_feature_t feature, uint16_t manufacturer); // Check if a given |vendor_id, |product_id| matches a known // interoperability workaround as identified by the |interop_feature_t| // enum. This API is used for simple name based lookups where more information // is not available. -bool interop_match_vendor_product_ids(const interop_feature_t feature, - uint16_t vendor_id, uint16_t product_id); +bool interop_match_vendor_product_ids(const interop_feature_t feature, uint16_t vendor_id, + uint16_t product_id); // Add a dynamic interop database entry for a device matching the first |length| // bytes of |addr|, implementing the workaround identified by |feature|. @@ -401,22 +398,20 @@ bool interop_match_vendor_product_ids(const interop_feature_t feature, // |length| must be greater than 0 and less than RawAddress::kLength. // As |interop_feature_t| is not exposed in the public API, feature must be a // valid integer representing an option in the enum. -void interop_database_add(const uint16_t feature, const RawAddress* addr, - size_t length); +void interop_database_add(const uint16_t feature, const RawAddress* addr, size_t length); // Clear the dynamic portion of the interoperability workaround database. void interop_database_clear(void); // check if device version is matching with the interop database -bool interop_database_match_version(const interop_feature_t feature, - uint16_t version); +bool interop_database_match_version(const interop_feature_t feature, uint16_t version); // Check if a given |addr| matches a known interoperability workaround as // identified by the |interop_feature_t| enum. This API is used for simple // address based lookups where more information is not available. No look-ups or // random address resolution are performed on |addr|. If address is matched, max // latency for SSR stored for particular remote device is returned. -bool interop_match_addr_get_max_lat(const interop_feature_t feature, - const RawAddress* addr, uint16_t* max_lat); +bool interop_match_addr_get_max_lat(const interop_feature_t feature, const RawAddress* addr, + uint16_t* max_lat); // Return feature's enum value according to feature'name. int interop_feature_name_to_feature_id(const char* feature_name); diff --git a/system/device/include/interop_config.h b/system/device/include/interop_config.h index aed4087f2cb..e0584b9aa2e 100644 --- a/system/device/include/interop_config.h +++ b/system/device/include/interop_config.h @@ -26,58 +26,40 @@ typedef uint16_t UINT16; // API's for adding entries to dynamic interop database -void interop_database_add_addr(const uint16_t feature, const RawAddress* addr, - size_t length); +void interop_database_add_addr(const uint16_t feature, const RawAddress* addr, size_t length); void interop_database_add_name(const uint16_t feature, const char* name); -void interop_database_add_manufacturer(const interop_feature_t feature, - uint16_t manufacturer); -void interop_database_add_vndr_prdt(const interop_feature_t feature, - uint16_t vendor_id, uint16_t product_id); -void interop_database_add_addr_max_lat(const interop_feature_t feature, - const RawAddress* addr, +void interop_database_add_manufacturer(const interop_feature_t feature, uint16_t manufacturer); +void interop_database_add_vndr_prdt(const interop_feature_t feature, uint16_t vendor_id, + uint16_t product_id); +void interop_database_add_addr_max_lat(const interop_feature_t feature, const RawAddress* addr, uint16_t max_lat); -void interop_database_add_version(const interop_feature_t feature, - uint16_t version); -void interop_database_add_addr_lmp_version(const interop_feature_t feature, - const RawAddress* addr, - uint8_t lmp_ver, - uint16_t lmp_sub_ver); +void interop_database_add_version(const interop_feature_t feature, uint16_t version); +void interop_database_add_addr_lmp_version(const interop_feature_t feature, const RawAddress* addr, + uint8_t lmp_ver, uint16_t lmp_sub_ver); // API's for removing entries from dynamic interop database -bool interop_database_remove_addr(const interop_feature_t feature, - const RawAddress* addr); -bool interop_database_remove_name(const interop_feature_t feature, - const char* name); -bool interop_database_remove_manufacturer(const interop_feature_t feature, - uint16_t manufacturer); -bool interop_database_remove_vndr_prdt(const interop_feature_t feature, - uint16_t vendor_id, uint16_t product_id); -bool interop_database_remove_addr_max_lat(const interop_feature_t feature, - const RawAddress* addr, +bool interop_database_remove_addr(const interop_feature_t feature, const RawAddress* addr); +bool interop_database_remove_name(const interop_feature_t feature, const char* name); +bool interop_database_remove_manufacturer(const interop_feature_t feature, uint16_t manufacturer); +bool interop_database_remove_vndr_prdt(const interop_feature_t feature, uint16_t vendor_id, + uint16_t product_id); +bool interop_database_remove_addr_max_lat(const interop_feature_t feature, const RawAddress* addr, uint16_t max_lat); -bool interop_database_remove_version(const interop_feature_t feature, - uint16_t version); +bool interop_database_remove_version(const interop_feature_t feature, uint16_t version); bool interop_database_remove_feature(const interop_feature_t feature); bool interop_database_remove_addr_lmp_version(const interop_feature_t feature, - const RawAddress* addr, - uint8_t lmp_ver, + const RawAddress* addr, uint8_t lmp_ver, uint16_t lmp_sub_ver); // API's to match entries with in dynamic interop database -bool interop_database_match_addr(const interop_feature_t feature, - const RawAddress* addr); -bool interop_database_match_name(const interop_feature_t feature, - const char* name); -bool interop_database_match_manufacturer(const interop_feature_t feature, - uint16_t manufacturer); -bool interop_database_match_vndr_prdt(const interop_feature_t feature, - uint16_t vendor_id, uint16_t product_id); +bool interop_database_match_addr(const interop_feature_t feature, const RawAddress* addr); +bool interop_database_match_name(const interop_feature_t feature, const char* name); +bool interop_database_match_manufacturer(const interop_feature_t feature, uint16_t manufacturer); +bool interop_database_match_vndr_prdt(const interop_feature_t feature, uint16_t vendor_id, + uint16_t product_id); bool interop_database_match_addr_get_max_lat(const interop_feature_t feature, - const RawAddress* addr, - uint16_t* max_lat); -bool interop_database_match_version(const interop_feature_t feature, - uint16_t version); + const RawAddress* addr, uint16_t* max_lat); +bool interop_database_match_version(const interop_feature_t feature, uint16_t version); bool interop_database_match_addr_get_lmp_ver(const interop_feature_t feature, - const RawAddress* addr, - uint8_t* lmp_ver, + const RawAddress* addr, uint8_t* lmp_ver, uint16_t* lmp_sub_ver); diff --git a/system/device/src/device_iot_config.cc b/system/device/src/device_iot_config.cc index f3534fbf642..0918a54f7be 100644 --- a/system/device/src/device_iot_config.cc +++ b/system/device/src/device_iot_config.cc @@ -50,8 +50,9 @@ alarm_t* config_timer; using namespace bluetooth; bool device_iot_config_has_section(const std::string& section) { - if (!com::android::bluetooth::flags::device_iot_config_logging()) + if (!com::android::bluetooth::flags::device_iot_config_logging()) { return false; + } log::assert_that(config != NULL, "assert failed: config != NULL"); @@ -59,10 +60,10 @@ bool device_iot_config_has_section(const std::string& section) { return config_has_section(*config, section); } -bool device_iot_config_exist(const std::string& section, - const std::string& key) { - if (!com::android::bluetooth::flags::device_iot_config_logging()) +bool device_iot_config_exist(const std::string& section, const std::string& key) { + if (!com::android::bluetooth::flags::device_iot_config_logging()) { return false; + } log::assert_that(config != NULL, "assert failed: config != NULL"); @@ -70,31 +71,35 @@ bool device_iot_config_exist(const std::string& section, return config_has_key(*config, section, key); } -bool device_iot_config_get_int(const std::string& section, - const std::string& key, int& value) { - if (!com::android::bluetooth::flags::device_iot_config_logging()) +bool device_iot_config_get_int(const std::string& section, const std::string& key, int& value) { + if (!com::android::bluetooth::flags::device_iot_config_logging()) { return false; + } log::assert_that(config != NULL, "assert failed: config != NULL"); std::unique_lock lock(config_lock); bool ret = config_has_key(*config, section, key); - if (ret) value = config_get_int(*config, section, key, value); + if (ret) { + value = config_get_int(*config, section, key, value); + } return ret; } -bool device_iot_config_set_int(const std::string& section, - const std::string& key, int value) { - if (!com::android::bluetooth::flags::device_iot_config_logging()) +bool device_iot_config_set_int(const std::string& section, const std::string& key, int value) { + if (!com::android::bluetooth::flags::device_iot_config_logging()) { return false; + } log::assert_that(config != NULL, "assert failed: config != NULL"); std::unique_lock lock(config_lock); char value_str[32] = {0}; snprintf(value_str, sizeof(value_str), "%d", value); - if (device_iot_config_has_key_value(section, key, value_str)) return true; + if (device_iot_config_has_key_value(section, key, value_str)) { + return true; + } config_set_string(config.get(), section, key, value_str); device_iot_config_save_async(); @@ -102,10 +107,10 @@ bool device_iot_config_set_int(const std::string& section, return true; } -bool device_iot_config_int_add_one(const std::string& section, - const std::string& key) { - if (!com::android::bluetooth::flags::device_iot_config_logging()) +bool device_iot_config_int_add_one(const std::string& section, const std::string& key) { + if (!com::android::bluetooth::flags::device_iot_config_logging()) { return false; + } log::assert_that(config != NULL, "assert failed: config != NULL"); @@ -123,49 +128,59 @@ bool device_iot_config_int_add_one(const std::string& section, return true; } -bool device_iot_config_get_hex(const std::string& section, - const std::string& key, int& value) { - if (!com::android::bluetooth::flags::device_iot_config_logging()) +bool device_iot_config_get_hex(const std::string& section, const std::string& key, int& value) { + if (!com::android::bluetooth::flags::device_iot_config_logging()) { return false; + } log::assert_that(config != NULL, "assert failed: config != NULL"); std::unique_lock lock(config_lock); - const std::string* stored_value = - config_get_string(*config, section, key, NULL); - if (!stored_value) return false; + const std::string* stored_value = config_get_string(*config, section, key, NULL); + if (!stored_value) { + return false; + } errno = 0; char* endptr = nullptr; int result = strtoul(stored_value->c_str(), &endptr, 16); - if (stored_value->c_str() == endptr) return false; - if (endptr == nullptr || endptr[0] != '\0') return false; - if (errno) return false; + if (stored_value->c_str() == endptr) { + return false; + } + if (endptr == nullptr || endptr[0] != '\0') { + return false; + } + if (errno) { + return false; + } value = result; return true; } -bool device_iot_config_set_hex(const std::string& section, - const std::string& key, int value, +bool device_iot_config_set_hex(const std::string& section, const std::string& key, int value, int byte_num) { - if (!com::android::bluetooth::flags::device_iot_config_logging()) + if (!com::android::bluetooth::flags::device_iot_config_logging()) { return false; + } log::assert_that(config != NULL, "assert failed: config != NULL"); char value_str[32] = {0}; - if (byte_num == 1) + if (byte_num == 1) { snprintf(value_str, sizeof(value_str), "%02x", value); - else if (byte_num == 2) + } else if (byte_num == 2) { snprintf(value_str, sizeof(value_str), "%04x", value); - else if (byte_num == 3) + } else if (byte_num == 3) { snprintf(value_str, sizeof(value_str), "%06x", value); - else if (byte_num == 4) + } else if (byte_num == 4) { snprintf(value_str, sizeof(value_str), "%08x", value); + } std::unique_lock lock(config_lock); - if (device_iot_config_has_key_value(section, key, value_str)) return true; + if (device_iot_config_has_key_value(section, key, value_str)) { + return true; + } config_set_string(config.get(), section, key, value_str); device_iot_config_save_async(); @@ -173,34 +188,37 @@ bool device_iot_config_set_hex(const std::string& section, return true; } -bool device_iot_config_set_hex_if_greater(const std::string& section, - const std::string& key, int value, - int byte_num) { - if (!com::android::bluetooth::flags::device_iot_config_logging()) +bool device_iot_config_set_hex_if_greater(const std::string& section, const std::string& key, + int value, int byte_num) { + if (!com::android::bluetooth::flags::device_iot_config_logging()) { return false; + } int stored_value = 0; bool ret = device_iot_config_get_hex(section, key, stored_value); - if (ret && stored_value >= value) return true; + if (ret && stored_value >= value) { + return true; + } return device_iot_config_set_hex(section, key, value, byte_num); } -bool device_iot_config_get_str(const std::string& section, - const std::string& key, char* value, +bool device_iot_config_get_str(const std::string& section, const std::string& key, char* value, int* size_bytes) { - if (!com::android::bluetooth::flags::device_iot_config_logging()) + if (!com::android::bluetooth::flags::device_iot_config_logging()) { return false; + } log::assert_that(config != NULL, "assert failed: config != NULL"); log::assert_that(value != NULL, "assert failed: value != NULL"); log::assert_that(size_bytes != NULL, "assert failed: size_bytes != NULL"); std::unique_lock lock(config_lock); - const std::string* stored_value = - config_get_string(*config, section, key, NULL); + const std::string* stored_value = config_get_string(*config, section, key, NULL); - if (!stored_value) return false; + if (!stored_value) { + return false; + } strlcpy(value, stored_value->c_str(), *size_bytes); *size_bytes = strlen(value) + 1; @@ -208,16 +226,18 @@ bool device_iot_config_get_str(const std::string& section, return true; } -bool device_iot_config_set_str(const std::string& section, - const std::string& key, +bool device_iot_config_set_str(const std::string& section, const std::string& key, const std::string& value) { - if (!com::android::bluetooth::flags::device_iot_config_logging()) + if (!com::android::bluetooth::flags::device_iot_config_logging()) { return false; + } log::assert_that(config != NULL, "assert failed: config != NULL"); std::unique_lock lock(config_lock); - if (device_iot_config_has_key_value(section, key, value)) return true; + if (device_iot_config_has_key_value(section, key, value)) { + return true; + } config_set_string(config.get(), section, key, value); device_iot_config_save_async(); @@ -225,70 +245,86 @@ bool device_iot_config_set_str(const std::string& section, return true; } -bool device_iot_config_get_bin(const std::string& section, - const std::string& key, uint8_t* value, +bool device_iot_config_get_bin(const std::string& section, const std::string& key, uint8_t* value, size_t* length) { - if (!com::android::bluetooth::flags::device_iot_config_logging()) + if (!com::android::bluetooth::flags::device_iot_config_logging()) { return false; + } log::assert_that(config != NULL, "assert failed: config != NULL"); log::assert_that(value != NULL, "assert failed: value != NULL"); log::assert_that(length != NULL, "assert failed: length != NULL"); std::unique_lock lock(config_lock); - const std::string* value_string = - config_get_string(*config, section, key, NULL); + const std::string* value_string = config_get_string(*config, section, key, NULL); - if (!value_string) return false; + if (!value_string) { + return false; + } const char* value_str = value_string->c_str(); size_t value_len = strlen(value_str); - if ((value_len % 2) != 0 || *length < (value_len / 2)) return false; + if ((value_len % 2) != 0 || *length < (value_len / 2)) { + return false; + } - for (size_t i = 0; i < value_len; ++i) - if (!isxdigit(value_str[i])) return false; + for (size_t i = 0; i < value_len; ++i) { + if (!isxdigit(value_str[i])) { + return false; + } + } for (*length = 0; *value_str; value_str += 2, *length += 1) { errno = 0; char* endptr = nullptr; value[*length] = strtoul(value_str, &endptr, 16); - if (value_str == endptr) return false; - if (*endptr) return false; - if (errno) return false; + if (value_str == endptr) { + return false; + } + if (*endptr) { + return false; + } + if (errno) { + return false; + } } return true; } -size_t device_iot_config_get_bin_length(const std::string& section, - const std::string& key) { - if (!com::android::bluetooth::flags::device_iot_config_logging()) return 0; +size_t device_iot_config_get_bin_length(const std::string& section, const std::string& key) { + if (!com::android::bluetooth::flags::device_iot_config_logging()) { + return 0; + } log::assert_that(config != NULL, "assert failed: config != NULL"); std::unique_lock lock(config_lock); const std::string* value_str = config_get_string(*config, section, key, NULL); - if (!value_str) return 0; + if (!value_str) { + return 0; + } size_t value_len = strlen(value_str->c_str()); return ((value_len % 2) != 0) ? 0 : (value_len / 2); } -bool device_iot_config_set_bin(const std::string& section, - const std::string& key, const uint8_t* value, - size_t length) { - if (!com::android::bluetooth::flags::device_iot_config_logging()) +bool device_iot_config_set_bin(const std::string& section, const std::string& key, + const uint8_t* value, size_t length) { + if (!com::android::bluetooth::flags::device_iot_config_logging()) { return false; + } const char* lookup = "0123456789abcdef"; log::assert_that(config != NULL, "assert failed: config != NULL"); log::verbose("Key = {}", key); - if (length > 0) + if (length > 0) { log::assert_that(value != NULL, "assert failed: value != NULL"); + } char* str = (char*)osi_calloc(length * 2 + 1); if (str == NULL) { @@ -314,10 +350,10 @@ bool device_iot_config_set_bin(const std::string& section, return true; } -bool device_iot_config_remove(const std::string& section, - const std::string& key) { - if (!com::android::bluetooth::flags::device_iot_config_logging()) +bool device_iot_config_remove(const std::string& section, const std::string& key) { + if (!com::android::bluetooth::flags::device_iot_config_logging()) { return false; + } log::assert_that(config != NULL, "assert failed: config != NULL"); @@ -326,20 +362,24 @@ bool device_iot_config_remove(const std::string& section, } void device_iot_config_flush(void) { - if (!com::android::bluetooth::flags::device_iot_config_logging()) return; + if (!com::android::bluetooth::flags::device_iot_config_logging()) { + return; + } log::assert_that(config != NULL, "assert failed: config != NULL"); log::assert_that(config_timer != NULL, "assert failed: config_timer != NULL"); - int event = alarm_is_scheduled(config_timer) ? IOT_CONFIG_SAVE_TIMER_FIRED_EVT - : IOT_CONFIG_FLUSH_EVT; + int event = + alarm_is_scheduled(config_timer) ? IOT_CONFIG_SAVE_TIMER_FIRED_EVT : IOT_CONFIG_FLUSH_EVT; log::verbose("evt={}", event); alarm_cancel(config_timer); device_iot_config_write(event, NULL); } bool device_iot_config_clear(void) { - if (!com::android::bluetooth::flags::device_iot_config_logging()) return true; + if (!com::android::bluetooth::flags::device_iot_config_logging()) { + return true; + } log::assert_that(config != NULL, "assert failed: config != NULL"); log::assert_that(config_timer != NULL, "assert failed: config_timer != NULL"); @@ -361,7 +401,9 @@ bool device_iot_config_clear(void) { } void device_debug_iot_config_dump(int fd) { - if (!com::android::bluetooth::flags::device_iot_config_logging()) return; + if (!com::android::bluetooth::flags::device_iot_config_logging()) { + return; + } dprintf(fd, "\nBluetooth Iot Config:\n"); diff --git a/system/device/src/device_iot_config_int.cc b/system/device/src/device_iot_config_int.cc index e42afa0c733..60f2d884bd7 100644 --- a/system/device/src/device_iot_config_int.cc +++ b/system/device/src/device_iot_config_int.cc @@ -74,8 +74,7 @@ future_t* device_iot_config_module_init(void) { config = config_new(IOT_CONFIG_FILE_PATH); device_iot_config_source = ORIGINAL; if (!config) { - log::warn("Unable to load config file: {}; using backup.", - IOT_CONFIG_FILE_PATH); + log::warn("Unable to load config file: {}; using backup.", IOT_CONFIG_FILE_PATH); config = config_new(IOT_CONFIG_BACKUP_PATH); device_iot_config_source = BACKUP; } @@ -116,8 +115,7 @@ future_t* device_iot_config_module_init(void) { cleanup(); return future_new_immediate(FUTURE_FAIL); } - config_set_int(config.get(), INFO_SECTION, VERSION_KEY, - DEVICE_IOT_INFO_CURRENT_VERSION); + config_set_int(config.get(), INFO_SECTION, VERSION_KEY, DEVICE_IOT_INFO_CURRENT_VERSION); device_iot_config_source = NEW_FILE; } @@ -126,17 +124,16 @@ future_t* device_iot_config_module_init(void) { // Read or set config file creation timestamp const std::string* time_str = - config_get_string(*config, INFO_SECTION, FILE_CREATED_TIMESTAMP, NULL); + config_get_string(*config, INFO_SECTION, FILE_CREATED_TIMESTAMP, NULL); if (time_str != NULL) { - strncpy(device_iot_config_time_created, time_str->c_str(), - TIME_STRING_LENGTH); + strncpy(device_iot_config_time_created, time_str->c_str(), TIME_STRING_LENGTH); } else { // Read or set config file creation timestamp time_t current_time = time(NULL); struct tm* time_created = localtime(¤t_time); if (time_created) { - strftime(device_iot_config_time_created, TIME_STRING_LENGTH, - TIME_STRING_FORMAT, time_created); + strftime(device_iot_config_time_created, TIME_STRING_LENGTH, TIME_STRING_FORMAT, + time_created); config_set_string(config.get(), INFO_SECTION, FILE_CREATED_TIMESTAMP, std::string(device_iot_config_time_created)); } @@ -168,8 +165,9 @@ future_t* device_iot_config_module_shut_down(void) { future_t* device_iot_config_module_clean_up(void) { log::info(""); - if (config_timer != NULL && alarm_is_scheduled(config_timer)) + if (config_timer != NULL && alarm_is_scheduled(config_timer)) { device_iot_config_flush(); + } alarm_free(config_timer); config_timer = NULL; @@ -180,15 +178,16 @@ future_t* device_iot_config_module_clean_up(void) { return future_new_immediate(FUTURE_SUCCESS); } -EXPORT_SYMBOL module_t device_iot_config_module = { - .name = DEVICE_IOT_CONFIG_MODULE, - .init = device_iot_config_module_init, - .start_up = device_iot_config_module_start_up, - .shut_down = device_iot_config_module_shut_down, - .clean_up = device_iot_config_module_clean_up}; +EXPORT_SYMBOL module_t device_iot_config_module = {.name = DEVICE_IOT_CONFIG_MODULE, + .init = device_iot_config_module_init, + .start_up = device_iot_config_module_start_up, + .shut_down = device_iot_config_module_shut_down, + .clean_up = device_iot_config_module_clean_up}; void device_iot_config_write(uint16_t event, UNUSED_ATTR char* p_param) { - if (!com::android::bluetooth::flags::device_iot_config_logging()) return; + if (!com::android::bluetooth::flags::device_iot_config_logging()) { + return; + } log::assert_that(config != NULL, "assert failed: config != NULL"); log::assert_that(config_timer != NULL, "assert failed: config_timer != NULL"); @@ -201,44 +200,45 @@ void device_iot_config_write(uint16_t event, UNUSED_ATTR char* p_param) { rename(IOT_CONFIG_FILE_PATH, IOT_CONFIG_BACKUP_PATH); device_iot_config_restrict_device_num(*config); - device_iot_config_sections_sort_by_entry_key(*config, - device_iot_config_compare_key); + device_iot_config_sections_sort_by_entry_key(*config, device_iot_config_compare_key); config_save(*config, IOT_CONFIG_FILE_PATH); } -void device_iot_config_sections_sort_by_entry_key(config_t& config, - compare_func comp) { +void device_iot_config_sections_sort_by_entry_key(config_t& config, compare_func comp) { for (auto& entry : config.sections) { entry.entries.sort(comp); } } -bool device_iot_config_has_key_value(const std::string& section, - const std::string& key, +bool device_iot_config_has_key_value(const std::string& section, const std::string& key, const std::string& value_str) { log::assert_that(config != NULL, "assert failed: config != NULL"); - const std::string* stored_value = - config_get_string(*config, section, key, NULL); + const std::string* stored_value = config_get_string(*config, section, key, NULL); - if (!stored_value || value_str.compare(*stored_value) != 0) return false; + if (!stored_value || value_str.compare(*stored_value) != 0) { + return false; + } return true; } void device_iot_config_save_async(void) { - if (!com::android::bluetooth::flags::device_iot_config_logging()) return; + if (!com::android::bluetooth::flags::device_iot_config_logging()) { + return; + } log::assert_that(config != NULL, "assert failed: config != NULL"); log::assert_that(config_timer != NULL, "assert failed: config_timer != NULL"); log::verbose(""); - alarm_set(config_timer, CONFIG_SETTLE_PERIOD_MS, - device_iot_config_timer_save_cb, NULL); + alarm_set(config_timer, CONFIG_SETTLE_PERIOD_MS, device_iot_config_timer_save_cb, NULL); } int device_iot_config_get_device_num(const config_t& conf) { - if (!com::android::bluetooth::flags::device_iot_config_logging()) return 0; + if (!com::android::bluetooth::flags::device_iot_config_logging()) { + return 0; + } int devices = 0; @@ -259,10 +259,8 @@ void device_iot_config_restrict_device_num(config_t& config) { return; } - need_remove_devices_num = - curr_num - DEVICES_MAX_NUM_IN_IOT_INFO_FILE + DEVICES_NUM_MARGIN; - log::info("curr_num={}, need_remove_num={}", curr_num, - need_remove_devices_num); + need_remove_devices_num = curr_num - DEVICES_MAX_NUM_IN_IOT_INFO_FILE + DEVICES_NUM_MARGIN; + log::info("curr_num={}, need_remove_num={}", curr_num, need_remove_devices_num); std::list::iterator i = config.sections.begin(); while (i != config.sections.end()) { @@ -278,11 +276,9 @@ void device_iot_config_restrict_device_num(config_t& config) { } } -bool device_iot_config_compare_key(const entry_t& first, - const entry_t& second) { +bool device_iot_config_compare_key(const entry_t& first, const entry_t& second) { bool first_is_profile_key = strncasecmp(first.key.c_str(), "Profile", 7) == 0; - bool second_is_profile_key = - strncasecmp(second.key.c_str(), "Profile", 7) == 0; + bool second_is_profile_key = strncasecmp(second.key.c_str(), "Profile", 7) == 0; if (!first_is_profile_key && !second_is_profile_key) { return true; } else if (first_is_profile_key && second_is_profile_key) { @@ -297,8 +293,7 @@ void device_iot_config_timer_save_cb(void* /* data */) { // it usually takes a lot of time to be completed, introducing // delays during A2DP playback causing blips or choppiness. log::verbose(""); - btif_transfer_context(device_iot_config_write, - IOT_CONFIG_SAVE_TIMER_FIRED_EVT, NULL, 0, NULL); + btif_transfer_context(device_iot_config_write, IOT_CONFIG_SAVE_TIMER_FIRED_EVT, NULL, 0, NULL); } void device_iot_config_set_modified_time() { @@ -306,8 +301,8 @@ void device_iot_config_set_modified_time() { struct tm* time_modified = localtime(¤t_time); char device_iot_config_time_modified[TIME_STRING_LENGTH]; if (time_modified) { - strftime(device_iot_config_time_modified, TIME_STRING_LENGTH, - TIME_STRING_FORMAT, time_modified); + strftime(device_iot_config_time_modified, TIME_STRING_LENGTH, TIME_STRING_FORMAT, + time_modified); config_set_string(config.get(), INFO_SECTION, FILE_MODIFIED_TIMESTAMP, device_iot_config_time_modified); } diff --git a/system/device/src/device_iot_config_int.h b/system/device/src/device_iot_config_int.h index 1267eaa7a2e..d378dbe4544 100644 --- a/system/device/src/device_iot_config_int.h +++ b/system/device/src/device_iot_config_int.h @@ -21,8 +21,7 @@ #include "osi/include/config.h" -#define PROPERTY_ENABLE_LOGGING \ - "persist.bluetooth.device_iot_config.enablelogging" +#define PROPERTY_ENABLE_LOGGING "persist.bluetooth.device_iot_config.enablelogging" #define PROPERTY_FACTORY_RESET "persist.bluetooth.factoryreset" #define INFO_SECTION "Info" @@ -49,10 +48,8 @@ static const char* TIME_STRING_FORMAT = "%Y-%m-%d %H:%M:%S"; #define IOT_CONFIG_SAVE_TIMER_FIRED_EVT 1 #ifdef __ANDROID__ -static const char* IOT_CONFIG_FILE_PATH = - "/data/misc/bluedroid/bt_remote_dev_info.conf"; -static const char* IOT_CONFIG_BACKUP_PATH = - "/data/misc/bluedroid/bt_remote_dev_info.bak"; +static const char* IOT_CONFIG_FILE_PATH = "/data/misc/bluedroid/bt_remote_dev_info.conf"; +static const char* IOT_CONFIG_BACKUP_PATH = "/data/misc/bluedroid/bt_remote_dev_info.bak"; #else // !__ANDROID__ static const char* IOT_CONFIG_FILE_PATH = "bt_remote_dev_info.conf"; static const char* IOT_CONFIG_BACKUP_PATH = "bt_remote_dev_info.bak"; @@ -74,10 +71,8 @@ future_t* device_iot_config_module_clean_up(void); void device_iot_config_write(uint16_t event, char* p_param); // config_lock is used by the caller of the following methods -void device_iot_config_sections_sort_by_entry_key(config_t& config, - compare_func comp); -bool device_iot_config_has_key_value(const std::string& section, - const std::string& key, +void device_iot_config_sections_sort_by_entry_key(config_t& config, compare_func comp); +bool device_iot_config_has_key_value(const std::string& section, const std::string& key, const std::string& value_str); void device_iot_config_save_async(void); int device_iot_config_get_device_num(const config_t& config); diff --git a/system/device/src/esco_parameters.cc b/system/device/src/esco_parameters.cc index 44f6fe98259..ed84fbdb730 100644 --- a/system/device/src/esco_parameters.cc +++ b/system/device/src/esco_parameters.cc @@ -27,348 +27,340 @@ using namespace bluetooth; static const enh_esco_params_t default_esco_parameters[ESCO_NUM_CODECS] = { - // CVSD D1 - { - .transmit_bandwidth = TXRX_64KBITS_RATE, - .receive_bandwidth = TXRX_64KBITS_RATE, - .transmit_coding_format = {.coding_format = ESCO_CODING_FORMAT_CVSD, - .company_id = 0x0000, + // CVSD D1 + { + .transmit_bandwidth = TXRX_64KBITS_RATE, + .receive_bandwidth = TXRX_64KBITS_RATE, + .transmit_coding_format = {.coding_format = ESCO_CODING_FORMAT_CVSD, + .company_id = 0x0000, + .vendor_specific_codec_id = 0x0000}, + .receive_coding_format = {.coding_format = ESCO_CODING_FORMAT_CVSD, + .company_id = 0x0000, + .vendor_specific_codec_id = 0x0000}, + .transmit_codec_frame_size = 60, + .receive_codec_frame_size = 60, + .input_bandwidth = INPUT_OUTPUT_64K_RATE, + .output_bandwidth = INPUT_OUTPUT_64K_RATE, + .input_coding_format = {.coding_format = ESCO_CODING_FORMAT_LINEAR, + .company_id = 0x0000, + .vendor_specific_codec_id = 0x0000}, + .output_coding_format = {.coding_format = ESCO_CODING_FORMAT_LINEAR, + .company_id = 0x0000, + .vendor_specific_codec_id = 0x0000}, + .input_coded_data_size = 16, + .output_coded_data_size = 16, + .input_pcm_data_format = ESCO_PCM_DATA_FORMAT_2_COMP, + .output_pcm_data_format = ESCO_PCM_DATA_FORMAT_2_COMP, + .input_pcm_payload_msb_position = 0, + .output_pcm_payload_msb_position = 0, + .input_data_path = ESCO_DATA_PATH_PCM, + .output_data_path = ESCO_DATA_PATH_PCM, + .input_transport_unit_size = 0x00, + .output_transport_unit_size = 0x00, + .max_latency_ms = 0xFFFF, // Don't care + .packet_types = (ESCO_PKT_TYPES_MASK_HV1 | ESCO_PKT_TYPES_MASK_HV2 | + ESCO_PKT_TYPES_MASK_HV3), + .retransmission_effort = ESCO_RETRANSMISSION_OFF, + .coding_format = ESCO_CODING_FORMAT_CVSD, + }, // CVSD S1 + { + .transmit_bandwidth = TXRX_64KBITS_RATE, + .receive_bandwidth = TXRX_64KBITS_RATE, + .transmit_coding_format = {.coding_format = ESCO_CODING_FORMAT_CVSD, + .company_id = 0x0000, + .vendor_specific_codec_id = 0x0000}, + .receive_coding_format = {.coding_format = ESCO_CODING_FORMAT_CVSD, + .company_id = 0x0000, + .vendor_specific_codec_id = 0x0000}, + .transmit_codec_frame_size = 60, + .receive_codec_frame_size = 60, + .input_bandwidth = INPUT_OUTPUT_64K_RATE, + .output_bandwidth = INPUT_OUTPUT_64K_RATE, + .input_coding_format = {.coding_format = ESCO_CODING_FORMAT_LINEAR, + .company_id = 0x0000, + .vendor_specific_codec_id = 0x0000}, + .output_coding_format = {.coding_format = ESCO_CODING_FORMAT_LINEAR, + .company_id = 0x0000, + .vendor_specific_codec_id = 0x0000}, + .input_coded_data_size = 16, + .output_coded_data_size = 16, + .input_pcm_data_format = ESCO_PCM_DATA_FORMAT_2_COMP, + .output_pcm_data_format = ESCO_PCM_DATA_FORMAT_2_COMP, + .input_pcm_payload_msb_position = 0, + .output_pcm_payload_msb_position = 0, + .input_data_path = ESCO_DATA_PATH_PCM, + .output_data_path = ESCO_DATA_PATH_PCM, + .input_transport_unit_size = 0x00, + .output_transport_unit_size = 0x00, + .max_latency_ms = 7, + .packet_types = (ESCO_PKT_TYPES_MASK_HV1 | ESCO_PKT_TYPES_MASK_HV2 | + ESCO_PKT_TYPES_MASK_HV3 | ESCO_PKT_TYPES_MASK_EV3 | + ESCO_PKT_TYPES_MASK_EV4 | ESCO_PKT_TYPES_MASK_EV5 | + ESCO_PKT_TYPES_MASK_NO_3_EV3 | ESCO_PKT_TYPES_MASK_NO_2_EV5 | + ESCO_PKT_TYPES_MASK_NO_3_EV5), + .retransmission_effort = ESCO_RETRANSMISSION_POWER, + .coding_format = ESCO_CODING_FORMAT_CVSD, + }, + // CVSD S3 + { + .transmit_bandwidth = TXRX_64KBITS_RATE, + .receive_bandwidth = TXRX_64KBITS_RATE, + .transmit_coding_format = {.coding_format = ESCO_CODING_FORMAT_CVSD, + .company_id = 0x0000, + .vendor_specific_codec_id = 0x0000}, + .receive_coding_format = {.coding_format = ESCO_CODING_FORMAT_CVSD, + .company_id = 0x0000, + .vendor_specific_codec_id = 0x0000}, + .transmit_codec_frame_size = 60, + .receive_codec_frame_size = 60, + .input_bandwidth = INPUT_OUTPUT_64K_RATE, + .output_bandwidth = INPUT_OUTPUT_64K_RATE, + .input_coding_format = {.coding_format = ESCO_CODING_FORMAT_LINEAR, + .company_id = 0x0000, + .vendor_specific_codec_id = 0x0000}, + .output_coding_format = {.coding_format = ESCO_CODING_FORMAT_LINEAR, + .company_id = 0x0000, + .vendor_specific_codec_id = 0x0000}, + .input_coded_data_size = 16, + .output_coded_data_size = 16, + .input_pcm_data_format = ESCO_PCM_DATA_FORMAT_2_COMP, + .output_pcm_data_format = ESCO_PCM_DATA_FORMAT_2_COMP, + .input_pcm_payload_msb_position = 0, + .output_pcm_payload_msb_position = 0, + .input_data_path = ESCO_DATA_PATH_PCM, + .output_data_path = ESCO_DATA_PATH_PCM, + .input_transport_unit_size = 0x00, + .output_transport_unit_size = 0x00, + .max_latency_ms = 10, + .packet_types = (ESCO_PKT_TYPES_MASK_HV1 | ESCO_PKT_TYPES_MASK_HV2 | + ESCO_PKT_TYPES_MASK_HV3 | ESCO_PKT_TYPES_MASK_EV3 | + ESCO_PKT_TYPES_MASK_EV4 | ESCO_PKT_TYPES_MASK_EV5 | + ESCO_PKT_TYPES_MASK_NO_3_EV3 | ESCO_PKT_TYPES_MASK_NO_2_EV5 | + ESCO_PKT_TYPES_MASK_NO_3_EV5), + .retransmission_effort = ESCO_RETRANSMISSION_POWER, + .coding_format = ESCO_CODING_FORMAT_CVSD, + }, + // CVSD S4 + { + .transmit_bandwidth = TXRX_64KBITS_RATE, + .receive_bandwidth = TXRX_64KBITS_RATE, + .transmit_coding_format = {.coding_format = ESCO_CODING_FORMAT_CVSD, + .company_id = 0x0000, + .vendor_specific_codec_id = 0x0000}, + .receive_coding_format = {.coding_format = ESCO_CODING_FORMAT_CVSD, + .company_id = 0x0000, + .vendor_specific_codec_id = 0x0000}, + .transmit_codec_frame_size = 60, + .receive_codec_frame_size = 60, + .input_bandwidth = INPUT_OUTPUT_64K_RATE, + .output_bandwidth = INPUT_OUTPUT_64K_RATE, + .input_coding_format = {.coding_format = ESCO_CODING_FORMAT_LINEAR, + .company_id = 0x0000, + .vendor_specific_codec_id = 0x0000}, + .output_coding_format = {.coding_format = ESCO_CODING_FORMAT_LINEAR, + .company_id = 0x0000, + .vendor_specific_codec_id = 0x0000}, + .input_coded_data_size = 16, + .output_coded_data_size = 16, + .input_pcm_data_format = ESCO_PCM_DATA_FORMAT_2_COMP, + .output_pcm_data_format = ESCO_PCM_DATA_FORMAT_2_COMP, + .input_pcm_payload_msb_position = 0, + .output_pcm_payload_msb_position = 0, + .input_data_path = ESCO_DATA_PATH_PCM, + .output_data_path = ESCO_DATA_PATH_PCM, + .input_transport_unit_size = 0x00, + .output_transport_unit_size = 0x00, + .max_latency_ms = 12, + .packet_types = (ESCO_PKT_TYPES_MASK_HV1 | ESCO_PKT_TYPES_MASK_HV2 | + ESCO_PKT_TYPES_MASK_HV3 | ESCO_PKT_TYPES_MASK_EV3 | + ESCO_PKT_TYPES_MASK_EV4 | ESCO_PKT_TYPES_MASK_EV5 | + ESCO_PKT_TYPES_MASK_NO_3_EV3 | ESCO_PKT_TYPES_MASK_NO_2_EV5 | + ESCO_PKT_TYPES_MASK_NO_3_EV5), + .retransmission_effort = ESCO_RETRANSMISSION_QUALITY, + .coding_format = ESCO_CODING_FORMAT_CVSD, + }, + // mSBC T1 + { + .transmit_bandwidth = TXRX_64KBITS_RATE, + .receive_bandwidth = TXRX_64KBITS_RATE, + .transmit_coding_format = {.coding_format = ESCO_CODING_FORMAT_MSBC, + .company_id = 0x0000, + .vendor_specific_codec_id = 0x0000}, + .receive_coding_format = {.coding_format = ESCO_CODING_FORMAT_MSBC, + .company_id = 0x0000, + .vendor_specific_codec_id = 0x0000}, + .transmit_codec_frame_size = 60, + .receive_codec_frame_size = 60, + .input_bandwidth = INPUT_OUTPUT_128K_RATE, + .output_bandwidth = INPUT_OUTPUT_128K_RATE, + .input_coding_format = {.coding_format = ESCO_CODING_FORMAT_LINEAR, + .company_id = 0x0000, + .vendor_specific_codec_id = 0x0000}, + .output_coding_format = {.coding_format = ESCO_CODING_FORMAT_LINEAR, + .company_id = 0x0000, + .vendor_specific_codec_id = 0x0000}, + .input_coded_data_size = 16, + .output_coded_data_size = 16, + .input_pcm_data_format = ESCO_PCM_DATA_FORMAT_2_COMP, + .output_pcm_data_format = ESCO_PCM_DATA_FORMAT_2_COMP, + .input_pcm_payload_msb_position = 0, + .output_pcm_payload_msb_position = 0, + .input_data_path = ESCO_DATA_PATH_PCM, + .output_data_path = ESCO_DATA_PATH_PCM, + .input_transport_unit_size = 0x00, + .output_transport_unit_size = 0x00, + .max_latency_ms = 8, + .packet_types = (ESCO_PKT_TYPES_MASK_EV3 | ESCO_PKT_TYPES_MASK_NO_3_EV3 | + ESCO_PKT_TYPES_MASK_NO_2_EV5 | ESCO_PKT_TYPES_MASK_NO_3_EV5 | + ESCO_PKT_TYPES_MASK_NO_2_EV3), + .retransmission_effort = ESCO_RETRANSMISSION_QUALITY, + .coding_format = ESCO_CODING_FORMAT_MSBC, + }, + // mSBC T2 + { + .transmit_bandwidth = TXRX_64KBITS_RATE, + .receive_bandwidth = TXRX_64KBITS_RATE, + .transmit_coding_format = {.coding_format = ESCO_CODING_FORMAT_MSBC, + .company_id = 0x0000, + .vendor_specific_codec_id = 0x0000}, + .receive_coding_format = {.coding_format = ESCO_CODING_FORMAT_MSBC, + .company_id = 0x0000, + .vendor_specific_codec_id = 0x0000}, + .transmit_codec_frame_size = 60, + .receive_codec_frame_size = 60, + .input_bandwidth = INPUT_OUTPUT_128K_RATE, + .output_bandwidth = INPUT_OUTPUT_128K_RATE, + .input_coding_format = {.coding_format = ESCO_CODING_FORMAT_LINEAR, + .company_id = 0x0000, + .vendor_specific_codec_id = 0x0000}, + .output_coding_format = {.coding_format = ESCO_CODING_FORMAT_LINEAR, + .company_id = 0x0000, + .vendor_specific_codec_id = 0x0000}, + .input_coded_data_size = 16, + .output_coded_data_size = 16, + .input_pcm_data_format = ESCO_PCM_DATA_FORMAT_2_COMP, + .output_pcm_data_format = ESCO_PCM_DATA_FORMAT_2_COMP, + .input_pcm_payload_msb_position = 0, + .output_pcm_payload_msb_position = 0, + .input_data_path = ESCO_DATA_PATH_PCM, + .output_data_path = ESCO_DATA_PATH_PCM, + .input_transport_unit_size = 0x00, + .output_transport_unit_size = 0x00, + .max_latency_ms = 13, + .packet_types = (ESCO_PKT_TYPES_MASK_EV3 | ESCO_PKT_TYPES_MASK_NO_3_EV3 | + ESCO_PKT_TYPES_MASK_NO_2_EV5 | ESCO_PKT_TYPES_MASK_NO_3_EV5), + .retransmission_effort = ESCO_RETRANSMISSION_QUALITY, + .coding_format = ESCO_CODING_FORMAT_MSBC, + }, + // LC3 T1 + { + .transmit_bandwidth = TXRX_64KBITS_RATE, + .receive_bandwidth = TXRX_64KBITS_RATE, + .transmit_coding_format = {.coding_format = ESCO_CODING_FORMAT_LC3, + .company_id = 0x0000, + .vendor_specific_codec_id = 0x0000}, + .receive_coding_format = {.coding_format = ESCO_CODING_FORMAT_LC3, + .company_id = 0x0000, + .vendor_specific_codec_id = 0x0000}, + .transmit_codec_frame_size = 60, + .receive_codec_frame_size = 60, + .input_bandwidth = INPUT_OUTPUT_256K_RATE, + .output_bandwidth = INPUT_OUTPUT_256K_RATE, + .input_coding_format = {.coding_format = ESCO_CODING_FORMAT_LINEAR, + .company_id = 0x0000, + .vendor_specific_codec_id = 0x0000}, + .output_coding_format = {.coding_format = ESCO_CODING_FORMAT_LINEAR, + .company_id = 0x0000, + .vendor_specific_codec_id = 0x0000}, + .input_coded_data_size = 16, + .output_coded_data_size = 16, + .input_pcm_data_format = ESCO_PCM_DATA_FORMAT_2_COMP, + .output_pcm_data_format = ESCO_PCM_DATA_FORMAT_2_COMP, + .input_pcm_payload_msb_position = 0, + .output_pcm_payload_msb_position = 0, + .input_data_path = ESCO_DATA_PATH_PCM, + .output_data_path = ESCO_DATA_PATH_PCM, + .input_transport_unit_size = 0x00, + .output_transport_unit_size = 0x00, + .max_latency_ms = 8, + .packet_types = (ESCO_PKT_TYPES_MASK_EV3 | ESCO_PKT_TYPES_MASK_NO_3_EV3 | + ESCO_PKT_TYPES_MASK_NO_2_EV5 | ESCO_PKT_TYPES_MASK_NO_3_EV5 | + ESCO_PKT_TYPES_MASK_NO_2_EV3), + .retransmission_effort = ESCO_RETRANSMISSION_QUALITY, + .coding_format = ESCO_CODING_FORMAT_LC3, + }, + // LC3 T2 + { + .transmit_bandwidth = TXRX_64KBITS_RATE, + .receive_bandwidth = TXRX_64KBITS_RATE, + .transmit_coding_format = {.coding_format = ESCO_CODING_FORMAT_LC3, + .company_id = 0x0000, + .vendor_specific_codec_id = 0x0000}, + .receive_coding_format = {.coding_format = ESCO_CODING_FORMAT_LC3, + .company_id = 0x0000, + .vendor_specific_codec_id = 0x0000}, + .transmit_codec_frame_size = 60, + .receive_codec_frame_size = 60, + .input_bandwidth = INPUT_OUTPUT_256K_RATE, + .output_bandwidth = INPUT_OUTPUT_256K_RATE, + .input_coding_format = {.coding_format = ESCO_CODING_FORMAT_LINEAR, + .company_id = 0x0000, + .vendor_specific_codec_id = 0x0000}, + .output_coding_format = {.coding_format = ESCO_CODING_FORMAT_LINEAR, + .company_id = 0x0000, + .vendor_specific_codec_id = 0x0000}, + .input_coded_data_size = 16, + .output_coded_data_size = 16, + .input_pcm_data_format = ESCO_PCM_DATA_FORMAT_2_COMP, + .output_pcm_data_format = ESCO_PCM_DATA_FORMAT_2_COMP, + .input_pcm_payload_msb_position = 0, + .output_pcm_payload_msb_position = 0, + .input_data_path = ESCO_DATA_PATH_PCM, + .output_data_path = ESCO_DATA_PATH_PCM, + .input_transport_unit_size = 0x00, + .output_transport_unit_size = 0x00, + .max_latency_ms = 13, + .packet_types = (ESCO_PKT_TYPES_MASK_NO_3_EV3 | ESCO_PKT_TYPES_MASK_NO_2_EV5 | + ESCO_PKT_TYPES_MASK_NO_3_EV5), + .retransmission_effort = ESCO_RETRANSMISSION_QUALITY, + .coding_format = ESCO_CODING_FORMAT_LC3, + }, + // aptX Voice SWB + {.transmit_bandwidth = TXRX_64KBITS_RATE, + .receive_bandwidth = TXRX_64KBITS_RATE, + .transmit_coding_format = {.coding_format = ESCO_CODING_FORMAT_VS, + .company_id = 0x000A, + .vendor_specific_codec_id = 0x0000}, + .receive_coding_format = {.coding_format = ESCO_CODING_FORMAT_VS, + .company_id = 0x000A, .vendor_specific_codec_id = 0x0000}, - .receive_coding_format = {.coding_format = ESCO_CODING_FORMAT_CVSD, - .company_id = 0x0000, - .vendor_specific_codec_id = 0x0000}, - .transmit_codec_frame_size = 60, - .receive_codec_frame_size = 60, - .input_bandwidth = INPUT_OUTPUT_64K_RATE, - .output_bandwidth = INPUT_OUTPUT_64K_RATE, - .input_coding_format = {.coding_format = ESCO_CODING_FORMAT_LINEAR, - .company_id = 0x0000, - .vendor_specific_codec_id = 0x0000}, - .output_coding_format = {.coding_format = ESCO_CODING_FORMAT_LINEAR, - .company_id = 0x0000, - .vendor_specific_codec_id = 0x0000}, - .input_coded_data_size = 16, - .output_coded_data_size = 16, - .input_pcm_data_format = ESCO_PCM_DATA_FORMAT_2_COMP, - .output_pcm_data_format = ESCO_PCM_DATA_FORMAT_2_COMP, - .input_pcm_payload_msb_position = 0, - .output_pcm_payload_msb_position = 0, - .input_data_path = ESCO_DATA_PATH_PCM, - .output_data_path = ESCO_DATA_PATH_PCM, - .input_transport_unit_size = 0x00, - .output_transport_unit_size = 0x00, - .max_latency_ms = 0xFFFF, // Don't care - .packet_types = (ESCO_PKT_TYPES_MASK_HV1 | ESCO_PKT_TYPES_MASK_HV2 | - ESCO_PKT_TYPES_MASK_HV3), - .retransmission_effort = ESCO_RETRANSMISSION_OFF, - .coding_format = ESCO_CODING_FORMAT_CVSD, - }, // CVSD S1 - { - .transmit_bandwidth = TXRX_64KBITS_RATE, - .receive_bandwidth = TXRX_64KBITS_RATE, - .transmit_coding_format = {.coding_format = ESCO_CODING_FORMAT_CVSD, - .company_id = 0x0000, - .vendor_specific_codec_id = 0x0000}, - .receive_coding_format = {.coding_format = ESCO_CODING_FORMAT_CVSD, - .company_id = 0x0000, - .vendor_specific_codec_id = 0x0000}, - .transmit_codec_frame_size = 60, - .receive_codec_frame_size = 60, - .input_bandwidth = INPUT_OUTPUT_64K_RATE, - .output_bandwidth = INPUT_OUTPUT_64K_RATE, - .input_coding_format = {.coding_format = ESCO_CODING_FORMAT_LINEAR, - .company_id = 0x0000, - .vendor_specific_codec_id = 0x0000}, - .output_coding_format = {.coding_format = ESCO_CODING_FORMAT_LINEAR, - .company_id = 0x0000, - .vendor_specific_codec_id = 0x0000}, - .input_coded_data_size = 16, - .output_coded_data_size = 16, - .input_pcm_data_format = ESCO_PCM_DATA_FORMAT_2_COMP, - .output_pcm_data_format = ESCO_PCM_DATA_FORMAT_2_COMP, - .input_pcm_payload_msb_position = 0, - .output_pcm_payload_msb_position = 0, - .input_data_path = ESCO_DATA_PATH_PCM, - .output_data_path = ESCO_DATA_PATH_PCM, - .input_transport_unit_size = 0x00, - .output_transport_unit_size = 0x00, - .max_latency_ms = 7, - .packet_types = - (ESCO_PKT_TYPES_MASK_HV1 | ESCO_PKT_TYPES_MASK_HV2 | - ESCO_PKT_TYPES_MASK_HV3 | ESCO_PKT_TYPES_MASK_EV3 | - ESCO_PKT_TYPES_MASK_EV4 | ESCO_PKT_TYPES_MASK_EV5 | - ESCO_PKT_TYPES_MASK_NO_3_EV3 | ESCO_PKT_TYPES_MASK_NO_2_EV5 | - ESCO_PKT_TYPES_MASK_NO_3_EV5), - .retransmission_effort = ESCO_RETRANSMISSION_POWER, - .coding_format = ESCO_CODING_FORMAT_CVSD, - }, - // CVSD S3 - { - .transmit_bandwidth = TXRX_64KBITS_RATE, - .receive_bandwidth = TXRX_64KBITS_RATE, - .transmit_coding_format = {.coding_format = ESCO_CODING_FORMAT_CVSD, - .company_id = 0x0000, - .vendor_specific_codec_id = 0x0000}, - .receive_coding_format = {.coding_format = ESCO_CODING_FORMAT_CVSD, - .company_id = 0x0000, - .vendor_specific_codec_id = 0x0000}, - .transmit_codec_frame_size = 60, - .receive_codec_frame_size = 60, - .input_bandwidth = INPUT_OUTPUT_64K_RATE, - .output_bandwidth = INPUT_OUTPUT_64K_RATE, - .input_coding_format = {.coding_format = ESCO_CODING_FORMAT_LINEAR, - .company_id = 0x0000, - .vendor_specific_codec_id = 0x0000}, - .output_coding_format = {.coding_format = ESCO_CODING_FORMAT_LINEAR, + .transmit_codec_frame_size = 60, + .receive_codec_frame_size = 60, + .input_bandwidth = INPUT_OUTPUT_128K_RATE, + .output_bandwidth = INPUT_OUTPUT_128K_RATE, + .input_coding_format = {.coding_format = ESCO_CODING_FORMAT_LINEAR, .company_id = 0x0000, .vendor_specific_codec_id = 0x0000}, - .input_coded_data_size = 16, - .output_coded_data_size = 16, - .input_pcm_data_format = ESCO_PCM_DATA_FORMAT_2_COMP, - .output_pcm_data_format = ESCO_PCM_DATA_FORMAT_2_COMP, - .input_pcm_payload_msb_position = 0, - .output_pcm_payload_msb_position = 0, - .input_data_path = ESCO_DATA_PATH_PCM, - .output_data_path = ESCO_DATA_PATH_PCM, - .input_transport_unit_size = 0x00, - .output_transport_unit_size = 0x00, - .max_latency_ms = 10, - .packet_types = - (ESCO_PKT_TYPES_MASK_HV1 | ESCO_PKT_TYPES_MASK_HV2 | - ESCO_PKT_TYPES_MASK_HV3 | ESCO_PKT_TYPES_MASK_EV3 | - ESCO_PKT_TYPES_MASK_EV4 | ESCO_PKT_TYPES_MASK_EV5 | - ESCO_PKT_TYPES_MASK_NO_3_EV3 | ESCO_PKT_TYPES_MASK_NO_2_EV5 | - ESCO_PKT_TYPES_MASK_NO_3_EV5), - .retransmission_effort = ESCO_RETRANSMISSION_POWER, - .coding_format = ESCO_CODING_FORMAT_CVSD, - }, - // CVSD S4 - { - .transmit_bandwidth = TXRX_64KBITS_RATE, - .receive_bandwidth = TXRX_64KBITS_RATE, - .transmit_coding_format = {.coding_format = ESCO_CODING_FORMAT_CVSD, - .company_id = 0x0000, - .vendor_specific_codec_id = 0x0000}, - .receive_coding_format = {.coding_format = ESCO_CODING_FORMAT_CVSD, - .company_id = 0x0000, - .vendor_specific_codec_id = 0x0000}, - .transmit_codec_frame_size = 60, - .receive_codec_frame_size = 60, - .input_bandwidth = INPUT_OUTPUT_64K_RATE, - .output_bandwidth = INPUT_OUTPUT_64K_RATE, - .input_coding_format = {.coding_format = ESCO_CODING_FORMAT_LINEAR, - .company_id = 0x0000, - .vendor_specific_codec_id = 0x0000}, - .output_coding_format = {.coding_format = ESCO_CODING_FORMAT_LINEAR, - .company_id = 0x0000, - .vendor_specific_codec_id = 0x0000}, - .input_coded_data_size = 16, - .output_coded_data_size = 16, - .input_pcm_data_format = ESCO_PCM_DATA_FORMAT_2_COMP, - .output_pcm_data_format = ESCO_PCM_DATA_FORMAT_2_COMP, - .input_pcm_payload_msb_position = 0, - .output_pcm_payload_msb_position = 0, - .input_data_path = ESCO_DATA_PATH_PCM, - .output_data_path = ESCO_DATA_PATH_PCM, - .input_transport_unit_size = 0x00, - .output_transport_unit_size = 0x00, - .max_latency_ms = 12, - .packet_types = - (ESCO_PKT_TYPES_MASK_HV1 | ESCO_PKT_TYPES_MASK_HV2 | - ESCO_PKT_TYPES_MASK_HV3 | ESCO_PKT_TYPES_MASK_EV3 | - ESCO_PKT_TYPES_MASK_EV4 | ESCO_PKT_TYPES_MASK_EV5 | - ESCO_PKT_TYPES_MASK_NO_3_EV3 | ESCO_PKT_TYPES_MASK_NO_2_EV5 | - ESCO_PKT_TYPES_MASK_NO_3_EV5), - .retransmission_effort = ESCO_RETRANSMISSION_QUALITY, - .coding_format = ESCO_CODING_FORMAT_CVSD, - }, - // mSBC T1 - { - .transmit_bandwidth = TXRX_64KBITS_RATE, - .receive_bandwidth = TXRX_64KBITS_RATE, - .transmit_coding_format = {.coding_format = ESCO_CODING_FORMAT_MSBC, - .company_id = 0x0000, - .vendor_specific_codec_id = 0x0000}, - .receive_coding_format = {.coding_format = ESCO_CODING_FORMAT_MSBC, + .output_coding_format = {.coding_format = ESCO_CODING_FORMAT_LINEAR, .company_id = 0x0000, .vendor_specific_codec_id = 0x0000}, - .transmit_codec_frame_size = 60, - .receive_codec_frame_size = 60, - .input_bandwidth = INPUT_OUTPUT_128K_RATE, - .output_bandwidth = INPUT_OUTPUT_128K_RATE, - .input_coding_format = {.coding_format = ESCO_CODING_FORMAT_LINEAR, - .company_id = 0x0000, - .vendor_specific_codec_id = 0x0000}, - .output_coding_format = {.coding_format = ESCO_CODING_FORMAT_LINEAR, - .company_id = 0x0000, - .vendor_specific_codec_id = 0x0000}, - .input_coded_data_size = 16, - .output_coded_data_size = 16, - .input_pcm_data_format = ESCO_PCM_DATA_FORMAT_2_COMP, - .output_pcm_data_format = ESCO_PCM_DATA_FORMAT_2_COMP, - .input_pcm_payload_msb_position = 0, - .output_pcm_payload_msb_position = 0, - .input_data_path = ESCO_DATA_PATH_PCM, - .output_data_path = ESCO_DATA_PATH_PCM, - .input_transport_unit_size = 0x00, - .output_transport_unit_size = 0x00, - .max_latency_ms = 8, - .packet_types = - (ESCO_PKT_TYPES_MASK_EV3 | ESCO_PKT_TYPES_MASK_NO_3_EV3 | - ESCO_PKT_TYPES_MASK_NO_2_EV5 | ESCO_PKT_TYPES_MASK_NO_3_EV5 | - ESCO_PKT_TYPES_MASK_NO_2_EV3), - .retransmission_effort = ESCO_RETRANSMISSION_QUALITY, - .coding_format = ESCO_CODING_FORMAT_MSBC, - }, - // mSBC T2 - { - .transmit_bandwidth = TXRX_64KBITS_RATE, - .receive_bandwidth = TXRX_64KBITS_RATE, - .transmit_coding_format = {.coding_format = ESCO_CODING_FORMAT_MSBC, - .company_id = 0x0000, - .vendor_specific_codec_id = 0x0000}, - .receive_coding_format = {.coding_format = ESCO_CODING_FORMAT_MSBC, - .company_id = 0x0000, - .vendor_specific_codec_id = 0x0000}, - .transmit_codec_frame_size = 60, - .receive_codec_frame_size = 60, - .input_bandwidth = INPUT_OUTPUT_128K_RATE, - .output_bandwidth = INPUT_OUTPUT_128K_RATE, - .input_coding_format = {.coding_format = ESCO_CODING_FORMAT_LINEAR, - .company_id = 0x0000, - .vendor_specific_codec_id = 0x0000}, - .output_coding_format = {.coding_format = ESCO_CODING_FORMAT_LINEAR, - .company_id = 0x0000, - .vendor_specific_codec_id = 0x0000}, - .input_coded_data_size = 16, - .output_coded_data_size = 16, - .input_pcm_data_format = ESCO_PCM_DATA_FORMAT_2_COMP, - .output_pcm_data_format = ESCO_PCM_DATA_FORMAT_2_COMP, - .input_pcm_payload_msb_position = 0, - .output_pcm_payload_msb_position = 0, - .input_data_path = ESCO_DATA_PATH_PCM, - .output_data_path = ESCO_DATA_PATH_PCM, - .input_transport_unit_size = 0x00, - .output_transport_unit_size = 0x00, - .max_latency_ms = 13, - .packet_types = - (ESCO_PKT_TYPES_MASK_EV3 | ESCO_PKT_TYPES_MASK_NO_3_EV3 | - ESCO_PKT_TYPES_MASK_NO_2_EV5 | ESCO_PKT_TYPES_MASK_NO_3_EV5), - .retransmission_effort = ESCO_RETRANSMISSION_QUALITY, - .coding_format = ESCO_CODING_FORMAT_MSBC, - }, - // LC3 T1 - { - .transmit_bandwidth = TXRX_64KBITS_RATE, - .receive_bandwidth = TXRX_64KBITS_RATE, - .transmit_coding_format = {.coding_format = ESCO_CODING_FORMAT_LC3, - .company_id = 0x0000, - .vendor_specific_codec_id = 0x0000}, - .receive_coding_format = {.coding_format = ESCO_CODING_FORMAT_LC3, - .company_id = 0x0000, - .vendor_specific_codec_id = 0x0000}, - .transmit_codec_frame_size = 60, - .receive_codec_frame_size = 60, - .input_bandwidth = INPUT_OUTPUT_256K_RATE, - .output_bandwidth = INPUT_OUTPUT_256K_RATE, - .input_coding_format = {.coding_format = ESCO_CODING_FORMAT_LINEAR, - .company_id = 0x0000, - .vendor_specific_codec_id = 0x0000}, - .output_coding_format = {.coding_format = ESCO_CODING_FORMAT_LINEAR, - .company_id = 0x0000, - .vendor_specific_codec_id = 0x0000}, - .input_coded_data_size = 16, - .output_coded_data_size = 16, - .input_pcm_data_format = ESCO_PCM_DATA_FORMAT_2_COMP, - .output_pcm_data_format = ESCO_PCM_DATA_FORMAT_2_COMP, - .input_pcm_payload_msb_position = 0, - .output_pcm_payload_msb_position = 0, - .input_data_path = ESCO_DATA_PATH_PCM, - .output_data_path = ESCO_DATA_PATH_PCM, - .input_transport_unit_size = 0x00, - .output_transport_unit_size = 0x00, - .max_latency_ms = 8, - .packet_types = - (ESCO_PKT_TYPES_MASK_EV3 | ESCO_PKT_TYPES_MASK_NO_3_EV3 | - ESCO_PKT_TYPES_MASK_NO_2_EV5 | ESCO_PKT_TYPES_MASK_NO_3_EV5 | - ESCO_PKT_TYPES_MASK_NO_2_EV3), - .retransmission_effort = ESCO_RETRANSMISSION_QUALITY, - .coding_format = ESCO_CODING_FORMAT_LC3, - }, - // LC3 T2 - { - .transmit_bandwidth = TXRX_64KBITS_RATE, - .receive_bandwidth = TXRX_64KBITS_RATE, - .transmit_coding_format = {.coding_format = ESCO_CODING_FORMAT_LC3, - .company_id = 0x0000, - .vendor_specific_codec_id = 0x0000}, - .receive_coding_format = {.coding_format = ESCO_CODING_FORMAT_LC3, - .company_id = 0x0000, - .vendor_specific_codec_id = 0x0000}, - .transmit_codec_frame_size = 60, - .receive_codec_frame_size = 60, - .input_bandwidth = INPUT_OUTPUT_256K_RATE, - .output_bandwidth = INPUT_OUTPUT_256K_RATE, - .input_coding_format = {.coding_format = ESCO_CODING_FORMAT_LINEAR, - .company_id = 0x0000, - .vendor_specific_codec_id = 0x0000}, - .output_coding_format = {.coding_format = ESCO_CODING_FORMAT_LINEAR, - .company_id = 0x0000, - .vendor_specific_codec_id = 0x0000}, - .input_coded_data_size = 16, - .output_coded_data_size = 16, - .input_pcm_data_format = ESCO_PCM_DATA_FORMAT_2_COMP, - .output_pcm_data_format = ESCO_PCM_DATA_FORMAT_2_COMP, - .input_pcm_payload_msb_position = 0, - .output_pcm_payload_msb_position = 0, - .input_data_path = ESCO_DATA_PATH_PCM, - .output_data_path = ESCO_DATA_PATH_PCM, - .input_transport_unit_size = 0x00, - .output_transport_unit_size = 0x00, - .max_latency_ms = 13, - .packet_types = - (ESCO_PKT_TYPES_MASK_NO_3_EV3 | ESCO_PKT_TYPES_MASK_NO_2_EV5 | - ESCO_PKT_TYPES_MASK_NO_3_EV5), - .retransmission_effort = ESCO_RETRANSMISSION_QUALITY, - .coding_format = ESCO_CODING_FORMAT_LC3, - }, - // aptX Voice SWB - {.transmit_bandwidth = TXRX_64KBITS_RATE, - .receive_bandwidth = TXRX_64KBITS_RATE, - .transmit_coding_format = {.coding_format = ESCO_CODING_FORMAT_VS, - .company_id = 0x000A, - .vendor_specific_codec_id = 0x0000}, - .receive_coding_format = {.coding_format = ESCO_CODING_FORMAT_VS, - .company_id = 0x000A, - .vendor_specific_codec_id = 0x0000}, - .transmit_codec_frame_size = 60, - .receive_codec_frame_size = 60, - .input_bandwidth = INPUT_OUTPUT_128K_RATE, - .output_bandwidth = INPUT_OUTPUT_128K_RATE, - .input_coding_format = {.coding_format = ESCO_CODING_FORMAT_LINEAR, - .company_id = 0x0000, - .vendor_specific_codec_id = 0x0000}, - .output_coding_format = {.coding_format = ESCO_CODING_FORMAT_LINEAR, - .company_id = 0x0000, - .vendor_specific_codec_id = 0x0000}, - .input_coded_data_size = 16, - .output_coded_data_size = 16, - .input_pcm_data_format = ESCO_PCM_DATA_FORMAT_2_COMP, - .output_pcm_data_format = ESCO_PCM_DATA_FORMAT_2_COMP, - .input_pcm_payload_msb_position = 0, - .output_pcm_payload_msb_position = 0, - .input_data_path = ESCO_DATA_PATH_PCM, - .output_data_path = ESCO_DATA_PATH_PCM, - .input_transport_unit_size = 0x00, - .output_transport_unit_size = 0x00, - .max_latency_ms = 14, - .packet_types = 0x0380, - .retransmission_effort = ESCO_RETRANSMISSION_QUALITY}}; + .input_coded_data_size = 16, + .output_coded_data_size = 16, + .input_pcm_data_format = ESCO_PCM_DATA_FORMAT_2_COMP, + .output_pcm_data_format = ESCO_PCM_DATA_FORMAT_2_COMP, + .input_pcm_payload_msb_position = 0, + .output_pcm_payload_msb_position = 0, + .input_data_path = ESCO_DATA_PATH_PCM, + .output_data_path = ESCO_DATA_PATH_PCM, + .input_transport_unit_size = 0x00, + .output_transport_unit_size = 0x00, + .max_latency_ms = 14, + .packet_types = 0x0380, + .retransmission_effort = ESCO_RETRANSMISSION_QUALITY}}; enh_esco_params_t esco_parameters_for_codec(esco_codec_t codec, bool offload) { log::assert_that((int)codec >= 0, "codec index {}< 0", (int)codec); - log::assert_that(codec < ESCO_NUM_CODECS, "codec index {} > {}", (int)codec, - ESCO_NUM_CODECS); + log::assert_that(codec < ESCO_NUM_CODECS, "codec index {} > {}", (int)codec, ESCO_NUM_CODECS); std::vector codecIds; @@ -377,8 +369,7 @@ enh_esco_params_t esco_parameters_for_codec(esco_codec_t codec, bool offload) { log::warn("controller is null"); } else { codecIds = controller->GetLocalSupportedBrEdrCodecIds(); - if (std::find(codecIds.begin(), codecIds.end(), ESCO_CODING_FORMAT_LC3) == - codecIds.end()) { + if (std::find(codecIds.begin(), codecIds.end(), ESCO_CODING_FORMAT_LC3) == codecIds.end()) { if (codec == ESCO_CODEC_LC3_T1 || codec == ESCO_CODEC_LC3_T2) { log::info("BT controller does not support LC3 codec, use DSP codec"); enh_esco_params_t param = default_esco_parameters[codec]; @@ -392,15 +383,15 @@ enh_esco_params_t esco_parameters_for_codec(esco_codec_t codec, bool offload) { } if (offload) { - if (codec == ESCO_CODEC_SWB_Q0 || codec == ESCO_CODEC_SWB_Q1 || - codec == ESCO_CODEC_SWB_Q2 || codec == ESCO_CODEC_SWB_Q3) { + if (codec == ESCO_CODEC_SWB_Q0 || codec == ESCO_CODEC_SWB_Q1 || codec == ESCO_CODEC_SWB_Q2 || + codec == ESCO_CODEC_SWB_Q3) { return default_esco_parameters[ESCO_CODEC_SWB_Q0]; } return default_esco_parameters[codec]; } - log::assert_that(codec < ESCO_LEGACY_NUM_CODECS, "legacy codec index {} > {}", - (int)codec, ESCO_LEGACY_NUM_CODECS); + log::assert_that(codec < ESCO_LEGACY_NUM_CODECS, "legacy codec index {} > {}", (int)codec, + ESCO_LEGACY_NUM_CODECS); enh_esco_params_t param = default_esco_parameters[codec]; param.input_data_path = param.output_data_path = ESCO_DATA_PATH_HCI; @@ -415,22 +406,19 @@ enh_esco_params_t esco_parameters_for_codec(esco_codec_t codec, bool offload) { if (com::android::bluetooth::flags::fix_hfp_qual_1_9()) { esco_packet_types_t new_packet_types = param.packet_types; - if (codec == ESCO_CODEC_CVSD_S3 || codec == ESCO_CODEC_CVSD_S4 || - codec == ESCO_CODEC_MSBC_T2 || codec == ESCO_CODEC_LC3_T2) { - new_packet_types = - (ESCO_PKT_TYPES_MASK_NO_3_EV3 | ESCO_PKT_TYPES_MASK_NO_2_EV5 | - ESCO_PKT_TYPES_MASK_NO_3_EV5); + if (codec == ESCO_CODEC_CVSD_S3 || codec == ESCO_CODEC_CVSD_S4 || codec == ESCO_CODEC_MSBC_T2 || + codec == ESCO_CODEC_LC3_T2) { + new_packet_types = (ESCO_PKT_TYPES_MASK_NO_3_EV3 | ESCO_PKT_TYPES_MASK_NO_2_EV5 | + ESCO_PKT_TYPES_MASK_NO_3_EV5); } else if (codec == ESCO_CODEC_CVSD_S1) { - new_packet_types = - (ESCO_PKT_TYPES_MASK_EV3 | ESCO_PKT_TYPES_MASK_EV4 | - ESCO_PKT_TYPES_MASK_EV5 | ESCO_PKT_TYPES_MASK_NO_3_EV3 | - ESCO_PKT_TYPES_MASK_NO_2_EV5 | ESCO_PKT_TYPES_MASK_NO_3_EV5); + new_packet_types = (ESCO_PKT_TYPES_MASK_EV3 | ESCO_PKT_TYPES_MASK_EV4 | + ESCO_PKT_TYPES_MASK_EV5 | ESCO_PKT_TYPES_MASK_NO_3_EV3 | + ESCO_PKT_TYPES_MASK_NO_2_EV5 | ESCO_PKT_TYPES_MASK_NO_3_EV5); } if (param.packet_types != new_packet_types) { - log::info( - "Applying restricted packet types for codec {}: 0x{:04x} -> 0x{:04x}", - (int)codec, param.packet_types, new_packet_types); + log::info("Applying restricted packet types for codec {}: 0x{:04x} -> 0x{:04x}", (int)codec, + param.packet_types, new_packet_types); param.packet_types = new_packet_types; } } diff --git a/system/device/src/interop.cc b/system/device/src/interop.cc index f6f9e0d859f..2a400e30791 100644 --- a/system/device/src/interop.cc +++ b/system/device/src/interop.cc @@ -51,37 +51,32 @@ using namespace bluetooth; #ifdef __ANDROID__ -static const char* INTEROP_DYNAMIC_FILE_PATH = - "/data/misc/bluedroid/interop_database_dynamic.conf"; +static const char* INTEROP_DYNAMIC_FILE_PATH = "/data/misc/bluedroid/interop_database_dynamic.conf"; static const char* INTEROP_STATIC_FILE_PATH = - "/apex/com.android.btservices/etc/bluetooth/interop_database.conf"; + "/apex/com.android.btservices/etc/bluetooth/interop_database.conf"; #elif TARGET_FLOSS #include #include static const std::filesystem::path kDynamicConfigFileConfigFile = - std::filesystem::temp_directory_path() / "interop_database_dynamic.conf"; -static const char* INTEROP_DYNAMIC_FILE_PATH = - kDynamicConfigFileConfigFile.c_str(); + std::filesystem::temp_directory_path() / "interop_database_dynamic.conf"; +static const char* INTEROP_DYNAMIC_FILE_PATH = kDynamicConfigFileConfigFile.c_str(); -static const char* INTEROP_STATIC_FILE_PATH = - "/var/lib/bluetooth/interop_database.conf"; +static const char* INTEROP_STATIC_FILE_PATH = "/var/lib/bluetooth/interop_database.conf"; #else // !TARGET_FLOSS and !__ANDROID__ #include #include static const std::filesystem::path kDynamicConfigFileConfigFile = - std::filesystem::temp_directory_path() / "interop_database_dynamic.conf"; -static const char* INTEROP_DYNAMIC_FILE_PATH = - kDynamicConfigFileConfigFile.c_str(); + std::filesystem::temp_directory_path() / "interop_database_dynamic.conf"; +static const char* INTEROP_DYNAMIC_FILE_PATH = kDynamicConfigFileConfigFile.c_str(); static const std::filesystem::path kStaticConfigFileConfigFile = - std::filesystem::temp_directory_path() / "interop_database.conf"; + std::filesystem::temp_directory_path() / "interop_database.conf"; -static const char* INTEROP_STATIC_FILE_PATH = - kStaticConfigFileConfigFile.c_str(); +static const char* INTEROP_STATIC_FILE_PATH = kStaticConfigFileConfigFile.c_str(); #endif // __ANDROID__ #define CASE_RETURN_STR(const) \ @@ -202,30 +197,26 @@ static void interop_config_cleanup(void); static void load_config(); static void interop_database_add_(interop_db_entry_t* db_entry, bool persist); static bool interop_database_remove_(interop_db_entry_t* entry); -static bool interop_database_match(interop_db_entry_t* entry, - interop_db_entry_t** ret_entry, +static bool interop_database_match(interop_db_entry_t* entry, interop_db_entry_t** ret_entry, interop_entry_type entry_type); static void interop_config_flush(void); -static bool interop_config_remove(const std::string& section, - const std::string& key); +static bool interop_config_remove(const std::string& section, const std::string& key); // Interface functions -bool interop_match_addr(const interop_feature_t feature, - const RawAddress* addr) { +bool interop_match_addr(const interop_feature_t feature, const RawAddress* addr) { log::assert_that(addr != nullptr, "assert failed: addr != nullptr"); - return (interop_database_match_addr(feature, addr)); + return interop_database_match_addr(feature, addr); } bool interop_match_name(const interop_feature_t feature, const char* name) { log::assert_that(name != nullptr, "assert failed: name != nullptr"); - return (interop_database_match_name(feature, name)); + return interop_database_match_name(feature, name); } -bool interop_match_addr_or_name(const interop_feature_t feature, - const RawAddress* addr, - bt_status_t (*get_remote_device_property)( - const RawAddress*, bt_property_t*)) { +bool interop_match_addr_or_name(const interop_feature_t feature, const RawAddress* addr, + bt_status_t (*get_remote_device_property)(const RawAddress*, + bt_property_t*)) { log::assert_that(addr != nullptr, "assert failed: addr != nullptr"); log::assert_that(get_remote_device_property != nullptr, "assert failed: get_remote_device_property != nullptr"); @@ -233,49 +224,49 @@ bool interop_match_addr_or_name(const interop_feature_t feature, bt_bdname_t bdname; bt_property_t prop_name; - if (interop_match_addr(feature, addr)) return true; + if (interop_match_addr(feature, addr)) { + return true; + } - BTIF_STORAGE_FILL_PROPERTY(&prop_name, BT_PROPERTY_BDNAME, - sizeof(bt_bdname_t), bdname.name); + BTIF_STORAGE_FILL_PROPERTY(&prop_name, BT_PROPERTY_BDNAME, sizeof(bt_bdname_t), bdname.name); - if (get_remote_device_property(addr, &prop_name) != BT_STATUS_SUCCESS) + if (get_remote_device_property(addr, &prop_name) != BT_STATUS_SUCCESS) { return false; - if (strlen((const char*)bdname.name) == 0) return false; + } + if (strlen((const char*)bdname.name) == 0) { + return false; + } return interop_match_name(feature, (const char*)bdname.name); } -bool interop_match_manufacturer(const interop_feature_t feature, - uint16_t manufacturer) { - return (interop_database_match_manufacturer(feature, manufacturer)); +bool interop_match_manufacturer(const interop_feature_t feature, uint16_t manufacturer) { + return interop_database_match_manufacturer(feature, manufacturer); } -bool interop_match_vendor_product_ids(const interop_feature_t feature, - uint16_t vendor_id, uint16_t product_id) { +bool interop_match_vendor_product_ids(const interop_feature_t feature, uint16_t vendor_id, + uint16_t product_id) { return interop_database_match_vndr_prdt(feature, vendor_id, product_id); } -bool interop_match_addr_get_max_lat(const interop_feature_t feature, - const RawAddress* addr, uint16_t* max_lat) { +bool interop_match_addr_get_max_lat(const interop_feature_t feature, const RawAddress* addr, + uint16_t* max_lat) { return interop_database_match_addr_get_max_lat(feature, addr, max_lat); } -void interop_database_add(const uint16_t feature, const RawAddress* addr, - size_t length) { +void interop_database_add(const uint16_t feature, const RawAddress* addr, size_t length) { log::assert_that(addr != nullptr, "assert failed: addr != nullptr"); log::assert_that(length > 0, "assert failed: length > 0"); - log::assert_that(length < sizeof(RawAddress), - "assert failed: length < sizeof(RawAddress)"); + log::assert_that(length < sizeof(RawAddress), "assert failed: length < sizeof(RawAddress)"); interop_database_add_addr(feature, addr, length); } void interop_database_clear() { - log::debug("interop_is_initialized: {} interop_list: {}", - interop_is_initialized, fmt::ptr(interop_list)); + log::debug("interop_is_initialized: {} interop_list: {}", interop_is_initialized, + fmt::ptr(interop_list)); if (interop_is_initialized && interop_list) { - for (int feature = BEGINNING_OF_INTEROP_LIST; - feature != END_OF_INTEROP_LIST; feature++) { + for (int feature = BEGINNING_OF_INTEROP_LIST; feature != END_OF_INTEROP_LIST; feature++) { interop_database_remove_feature((interop_feature_t)feature); } } @@ -288,11 +279,11 @@ static void interop_init_feature_name_id_map() { int feature; - for (feature = BEGINNING_OF_INTEROP_LIST; feature < END_OF_INTEROP_LIST; - feature++) { - const char* feature_name = - interop_feature_string_((interop_feature_t)feature); - if (!strcmp(UNKNOWN_INTEROP_FEATURE, feature_name)) continue; + for (feature = BEGINNING_OF_INTEROP_LIST; feature < END_OF_INTEROP_LIST; feature++) { + const char* feature_name = interop_feature_string_((interop_feature_t)feature); + if (!strcmp(UNKNOWN_INTEROP_FEATURE, feature_name)) { + continue; + } feature_name_id_map.insert({feature_name, feature}); } @@ -320,12 +311,12 @@ static future_t* interop_clean_up(void) { } EXPORT_SYMBOL module_t interop_module = { - .name = INTEROP_MODULE, - .init = interop_init, - .start_up = NULL, - .shut_down = NULL, - .clean_up = interop_clean_up, - .dependencies = {NULL}, + .name = INTEROP_MODULE, + .init = interop_init, + .start_up = NULL, + .shut_down = NULL, + .clean_up = interop_clean_up, + .dependencies = {NULL}, }; // Local functions @@ -425,8 +416,7 @@ static int interop_config_init(void) { if (!stat(INTEROP_STATIC_FILE_PATH, &sts) && sts.st_size) { if (!(config_static = config_new(INTEROP_STATIC_FILE_PATH))) { - log::warn("unable to load static config file for : {}", - INTEROP_STATIC_FILE_PATH); + log::warn("unable to load static config file for : {}", INTEROP_STATIC_FILE_PATH); } } if (!config_static && !(config_static = config_new_empty())) { @@ -435,8 +425,7 @@ static int interop_config_init(void) { if (!stat(INTEROP_DYNAMIC_FILE_PATH, &sts) && sts.st_size) { if (!(config_dynamic = config_new(INTEROP_DYNAMIC_FILE_PATH))) { - log::warn("unable to load dynamic config file for : {}", - INTEROP_DYNAMIC_FILE_PATH); + log::warn("unable to load dynamic config file for : {}", INTEROP_DYNAMIC_FILE_PATH); } } if (!config_dynamic && !(config_dynamic = config_new_empty())) { @@ -453,18 +442,15 @@ error: } static void interop_config_flush(void) { - log::assert_that(config_dynamic.get() != NULL, - "assert failed: config_dynamic.get() != NULL"); + log::assert_that(config_dynamic.get() != NULL, "assert failed: config_dynamic.get() != NULL"); pthread_mutex_lock(&file_lock); config_save(*config_dynamic, INTEROP_DYNAMIC_FILE_PATH); pthread_mutex_unlock(&file_lock); } -static bool interop_config_remove(const std::string& section, - const std::string& key) { - log::assert_that(config_dynamic.get() != NULL, - "assert failed: config_dynamic.get() != NULL"); +static bool interop_config_remove(const std::string& section, const std::string& key) { + log::assert_that(config_dynamic.get() != NULL, "assert failed: config_dynamic.get() != NULL"); pthread_mutex_lock(&file_lock); bool ret = config_remove_key(config_dynamic.get(), section, key); @@ -474,8 +460,7 @@ static bool interop_config_remove(const std::string& section, } static bool interop_config_remove_section(const std::string& section) { - log::assert_that(config_dynamic.get() != NULL, - "assert failed: config_dynamic.get() != NULL"); + log::assert_that(config_dynamic.get() != NULL, "assert failed: config_dynamic.get() != NULL"); pthread_mutex_lock(&file_lock); bool ret = config_remove_section(config_dynamic.get(), section); @@ -484,11 +469,9 @@ static bool interop_config_remove_section(const std::string& section) { return ret; } -static bool interop_config_set_str(const std::string& section, - const std::string& key, +static bool interop_config_set_str(const std::string& section, const std::string& key, const std::string& value) { - log::assert_that(config_dynamic.get() != NULL, - "assert failed: config_dynamic.get() != NULL"); + log::assert_that(config_dynamic.get() != NULL, "assert failed: config_dynamic.get() != NULL"); pthread_mutex_lock(&file_lock); config_set_string(config_dynamic.get(), section, key, value); @@ -511,8 +494,7 @@ int interop_feature_name_to_feature_id(const char* feature_name) { return it->second; } -static bool interop_config_add_or_remove(interop_db_entry_t* db_entry, - bool add) { +static bool interop_config_add_or_remove(interop_db_entry_t* db_entry, bool add) { bool status = true; std::string key; std::string value; @@ -523,8 +505,8 @@ static bool interop_config_add_or_remove(interop_db_entry_t* db_entry, case INTEROP_BL_TYPE_ADDR: { interop_addr_entry_t addr_entry = db_entry->entry_type.addr_entry; - const std::string bdstr = addr_entry.addr.ToColonSepHexString().substr( - 0, addr_entry.length * 3 - 1); + const std::string bdstr = + addr_entry.addr.ToColonSepHexString().substr(0, addr_entry.length * 3 - 1); feature = db_entry->entry_type.addr_entry.feature; key.assign(bdstr); @@ -563,12 +545,10 @@ static bool interop_config_add_or_remove(interop_db_entry_t* db_entry, break; } case INTEROP_BL_TYPE_SSR_MAX_LAT: { - interop_hid_ssr_max_lat_t ssr_entry = - db_entry->entry_type.ssr_max_lat_entry; + interop_hid_ssr_max_lat_t ssr_entry = db_entry->entry_type.ssr_max_lat_entry; char m_ssr_max_lat[KEY_MAX_LENGTH] = {'\0'}; - const std::string bdstr = - ssr_entry.addr.ToColonSepHexString().substr(0, 3 * 3 - 1); + const std::string bdstr = ssr_entry.addr.ToColonSepHexString().substr(0, 3 * 3 - 1); snprintf(m_ssr_max_lat, sizeof(m_ssr_max_lat), "%s-0x%04x", bdstr.c_str(), db_entry->entry_type.ssr_max_lat_entry.max_lat); @@ -581,8 +561,7 @@ static bool interop_config_add_or_remove(interop_db_entry_t* db_entry, } case INTEROP_BL_TYPE_VERSION: { char m_version[KEY_MAX_LENGTH] = {'\0'}; - snprintf(m_version, sizeof(m_version), "0x%04x", - db_entry->entry_type.version_entry.version); + snprintf(m_version, sizeof(m_version), "0x%04x", db_entry->entry_type.version_entry.version); feature = db_entry->entry_type.version_entry.feature; key.assign(m_version); @@ -591,14 +570,12 @@ static bool interop_config_add_or_remove(interop_db_entry_t* db_entry, break; } case INTEROP_BL_TYPE_LMP_VERSION: { - interop_lmp_version_t lmp_version_entry = - db_entry->entry_type.lmp_version_entry; + interop_lmp_version_t lmp_version_entry = db_entry->entry_type.lmp_version_entry; char m_lmp_version[KEY_MAX_LENGTH] = {'\0'}; - const std::string bdstr = - lmp_version_entry.addr.ToColonSepHexString().substr(0, 3 * 3 - 1); + const std::string bdstr = lmp_version_entry.addr.ToColonSepHexString().substr(0, 3 * 3 - 1); - snprintf(m_lmp_version, sizeof(m_lmp_version), "%s-0x%02x-0x%04x", - bdstr.c_str(), db_entry->entry_type.lmp_version_entry.lmp_ver, + snprintf(m_lmp_version, sizeof(m_lmp_version), "%s-0x%02x-0x%04x", bdstr.c_str(), + db_entry->entry_type.lmp_version_entry.lmp_ver, db_entry->entry_type.lmp_version_entry.lmp_sub_ver); feature = db_entry->entry_type.lmp_version_entry.feature; @@ -627,10 +604,9 @@ static bool interop_config_add_or_remove(interop_db_entry_t* db_entry, static void interop_database_add_(interop_db_entry_t* db_entry, bool persist) { interop_db_entry_t* ret_entry = NULL; - bool match_found = - interop_database_match(db_entry, &ret_entry, - (interop_entry_type)(INTEROP_ENTRY_TYPE_STATIC | - INTEROP_ENTRY_TYPE_DYNAMIC)); + bool match_found = interop_database_match( + db_entry, &ret_entry, + (interop_entry_type)(INTEROP_ENTRY_TYPE_STATIC | INTEROP_ENTRY_TYPE_DYNAMIC)); if (match_found) { // return as the entry is already present @@ -654,8 +630,7 @@ static void interop_database_add_(interop_db_entry_t* db_entry, bool persist) { interop_config_add_or_remove(db_entry, true); } -static bool interop_database_match(interop_db_entry_t* entry, - interop_db_entry_t** ret_entry, +static bool interop_database_match(interop_db_entry_t* entry, interop_db_entry_t** ret_entry, interop_entry_type entry_type) { log::assert_that(entry != nullptr, "assert failed: entry != nullptr"); bool found = false; @@ -676,8 +651,7 @@ static bool interop_database_match(interop_db_entry_t* entry, continue; } - if ((entry_type == INTEROP_ENTRY_TYPE_STATIC) || - (entry_type == INTEROP_ENTRY_TYPE_DYNAMIC)) { + if ((entry_type == INTEROP_ENTRY_TYPE_STATIC) || (entry_type == INTEROP_ENTRY_TYPE_DYNAMIC)) { if (entry->bl_entry_type != db_entry->bl_entry_type) { node = list_next(node); continue; @@ -688,8 +662,7 @@ static bool interop_database_match(interop_db_entry_t* entry, case INTEROP_BL_TYPE_ADDR: { interop_addr_entry_t* src = &entry->entry_type.addr_entry; interop_addr_entry_t* cur = &db_entry->entry_type.addr_entry; - if ((src->feature == cur->feature) && - (!memcmp(&src->addr, &cur->addr, cur->length))) { + if ((src->feature == cur->feature) && (!memcmp(&src->addr, &cur->addr, cur->length))) { /* cur len is used to remove src entry from config file, when * interop_database_remove_addr is called. */ src->length = cur->length; @@ -701,8 +674,7 @@ static bool interop_database_match(interop_db_entry_t* entry, interop_name_entry_t* src = &entry->entry_type.name_entry; interop_name_entry_t* cur = &db_entry->entry_type.name_entry; - if ((src->feature == cur->feature) && - (strcasestr(src->name, cur->name) == src->name)) { + if ((src->feature == cur->feature) && (strcasestr(src->name, cur->name) == src->name)) { found = true; } break; @@ -711,8 +683,7 @@ static bool interop_database_match(interop_db_entry_t* entry, interop_manufacturer_t* src = &entry->entry_type.mnfr_entry; interop_manufacturer_t* cur = &db_entry->entry_type.mnfr_entry; - if (src->feature == cur->feature && - src->manufacturer == cur->manufacturer) { + if (src->feature == cur->feature && src->manufacturer == cur->manufacturer) { found = true; } break; @@ -721,8 +692,7 @@ static bool interop_database_match(interop_db_entry_t* entry, interop_hid_multitouch_t* src = &entry->entry_type.vnr_pdt_entry; interop_hid_multitouch_t* cur = &db_entry->entry_type.vnr_pdt_entry; - if ((src->feature == cur->feature) && - (src->vendor_id == cur->vendor_id) && + if ((src->feature == cur->feature) && (src->vendor_id == cur->vendor_id) && (src->product_id == cur->product_id)) { found = true; } @@ -730,11 +700,9 @@ static bool interop_database_match(interop_db_entry_t* entry, } case INTEROP_BL_TYPE_SSR_MAX_LAT: { interop_hid_ssr_max_lat_t* src = &entry->entry_type.ssr_max_lat_entry; - interop_hid_ssr_max_lat_t* cur = - &db_entry->entry_type.ssr_max_lat_entry; + interop_hid_ssr_max_lat_t* cur = &db_entry->entry_type.ssr_max_lat_entry; - if ((src->feature == cur->feature) && - !memcmp(&src->addr, &cur->addr, 3)) { + if ((src->feature == cur->feature) && !memcmp(&src->addr, &cur->addr, 3)) { found = true; } break; @@ -752,21 +720,18 @@ static bool interop_database_match(interop_db_entry_t* entry, interop_lmp_version_t* src = &entry->entry_type.lmp_version_entry; interop_lmp_version_t* cur = &db_entry->entry_type.lmp_version_entry; - if ((src->feature == cur->feature) && - (!memcmp(&src->addr, &cur->addr, 3))) { + if ((src->feature == cur->feature) && (!memcmp(&src->addr, &cur->addr, 3))) { found = true; } break; } case INTEROP_BL_TYPE_ADDR_RANGE: { interop_addr_range_entry_t* src = &entry->entry_type.addr_range_entry; - interop_addr_range_entry_t* cur = - &db_entry->entry_type.addr_range_entry; + interop_addr_range_entry_t* cur = &db_entry->entry_type.addr_range_entry; // src->addr_start has the actual address, which need to be searched in // the range - if ((src->feature == cur->feature) && - (src->addr_start >= cur->addr_start) && + if ((src->feature == cur->feature) && (src->addr_start >= cur->addr_start) && (src->addr_start <= cur->addr_end)) { found = true; } @@ -790,9 +755,8 @@ static bool interop_database_match(interop_db_entry_t* entry, static bool interop_database_remove_(interop_db_entry_t* entry) { interop_db_entry_t* ret_entry = NULL; - if (!interop_database_match( - entry, &ret_entry, - (interop_entry_type)(INTEROP_ENTRY_TYPE_DYNAMIC))) { + if (!interop_database_match(entry, &ret_entry, + (interop_entry_type)(INTEROP_ENTRY_TYPE_DYNAMIC))) { log::error("Entry not found in the list"); return false; } @@ -806,12 +770,18 @@ static bool interop_database_remove_(interop_db_entry_t* entry) { } static char* trim(char* str) { - while (isspace(*str)) ++str; + while (isspace(*str)) { + ++str; + } - if (!*str) return str; + if (!*str) { + return str; + } char* end_str = str + strlen(str) - 1; - while (end_str > str && isspace(*end_str)) --end_str; + while (end_str > str && isspace(*end_str)) { + --end_str; + } end_str[1] = '\0'; return str; @@ -824,12 +794,13 @@ bool token_to_ul(char* token, uint16_t* ul) { token = trim(token); errno = 0; *ul = (uint16_t)strtoul(token, &e, 16); - if ((e != NULL) && errno != EINVAL && errno != ERANGE) ret_value = true; + if ((e != NULL) && errno != EINVAL && errno != ERANGE) { + ret_value = true; + } return ret_value; } -static bool get_vendor_product_id(char* vendorstr, uint16_t* vendor, - uint16_t* product) { +static bool get_vendor_product_id(char* vendorstr, uint16_t* vendor, uint16_t* product) { char* token; char* saveptr = NULL; bool ret_value = false; @@ -838,8 +809,7 @@ static bool get_vendor_product_id(char* vendorstr, uint16_t* vendor, ret_value = token_to_ul(token, vendor); } - if (ret_value && - (token = strtok_r(NULL, VENDOR_VALUE_SEPARATOR, &saveptr)) != NULL) { + if (ret_value && (token = strtok_r(NULL, VENDOR_VALUE_SEPARATOR, &saveptr)) != NULL) { ret_value = token_to_ul(token, product); } return ret_value; @@ -863,8 +833,7 @@ static bool get_addr_maxlat(char* str, char* bdaddrstr, uint16_t* max_lat) { return ret_value; } -static bool get_addr_range(char* str, RawAddress* addr_start, - RawAddress* addr_end) { +static bool get_addr_range(char* str, RawAddress* addr_start, RawAddress* addr_end) { char* token; char* saveptr = NULL; bool ret_value = false; @@ -874,7 +843,9 @@ static bool get_addr_range(char* str, RawAddress* addr_start, if ((token = strtok_r(str, VENDOR_VALUE_SEPARATOR, &saveptr)) != NULL) { trim(token); strlcpy(addr_start_str, token, 18); - if (!RawAddress::FromString(addr_start_str, *addr_start)) return false; + if (!RawAddress::FromString(addr_start_str, *addr_start)) { + return false; + } } else { return false; } @@ -882,13 +853,14 @@ static bool get_addr_range(char* str, RawAddress* addr_start, if ((token = strtok_r(NULL, VENDOR_VALUE_SEPARATOR, &saveptr)) != NULL) { trim(token); strlcpy(addr_end_str, token, 18); - if (RawAddress::FromString(addr_end_str, *addr_end)) ret_value = true; + if (RawAddress::FromString(addr_end_str, *addr_end)) { + ret_value = true; + } } return ret_value; } -static bool get_addr_lmp_ver(char* str, char* bdaddrstr, uint8_t* lmp_ver, - uint16_t* lmp_sub_ver) { +static bool get_addr_lmp_ver(char* str, char* bdaddrstr, uint8_t* lmp_ver, uint16_t* lmp_sub_ver) { char* token; char* saveptr = NULL; char* e; @@ -904,7 +876,9 @@ static bool get_addr_lmp_ver(char* str, char* bdaddrstr, uint8_t* lmp_ver, trim(token); errno = 0; *lmp_ver = (uint8_t)strtoul(token, &e, 16); - if (errno == EINVAL || errno == ERANGE) return false; + if (errno == EINVAL || errno == ERANGE) { + return false; + } } else { return false; } @@ -929,18 +903,16 @@ static bool load_to_database(int feature, const char* key, const char* value, std::string bdstr(key); std::string append_str(":00"); - for (int i = 6; i > len; i--) bdstr.append(append_str); + for (int i = 6; i > len; i--) { + bdstr.append(append_str); + } if (!RawAddress::FromString(bdstr, addr)) { - log::warn( - "key {} or Bluetooth Address {} is invalid, not added to interop " - "list", - key, addr); + log::warn("key {} or Bluetooth Address {} is invalid, not added to interop list", key, addr); return false; } - interop_db_entry_t* entry = - (interop_db_entry_t*)osi_calloc(sizeof(interop_db_entry_t)); + interop_db_entry_t* entry = (interop_db_entry_t*)osi_calloc(sizeof(interop_db_entry_t)); entry->bl_type = INTEROP_BL_TYPE_ADDR; entry->bl_entry_type = entry_type; entry->entry_type.addr_entry.addr = addr; @@ -953,12 +925,10 @@ static bool load_to_database(int feature, const char* key, const char* value, log::warn("ignoring {} due to invalid length", key); return false; } - interop_db_entry_t* entry = - (interop_db_entry_t*)osi_calloc(sizeof(interop_db_entry_t)); + interop_db_entry_t* entry = (interop_db_entry_t*)osi_calloc(sizeof(interop_db_entry_t)); entry->bl_type = INTEROP_BL_TYPE_NAME; entry->bl_entry_type = entry_type; - strlcpy(entry->entry_type.name_entry.name, key, - sizeof(entry->entry_type.name_entry.name)); + strlcpy(entry->entry_type.name_entry.name, key, sizeof(entry->entry_type.name_entry.name)); entry->entry_type.name_entry.feature = (interop_feature_t)feature; entry->entry_type.name_entry.length = strlen(key); interop_database_add_(entry, false); @@ -967,15 +937,15 @@ static bool load_to_database(int feature, const char* key, const char* value, uint16_t manufacturer; if (strlen(key) != VALID_MNFR_STR_LEN) { - log::warn("ignoring {} due to invalid Manufacturer id in config file", - key); + log::warn("ignoring {} due to invalid Manufacturer id in config file", key); return false; } - if (token_to_ul((char*)key, &manufacturer) == false) return false; + if (token_to_ul((char*)key, &manufacturer) == false) { + return false; + } - interop_db_entry_t* entry = - (interop_db_entry_t*)osi_calloc(sizeof(interop_db_entry_t)); + interop_db_entry_t* entry = (interop_db_entry_t*)osi_calloc(sizeof(interop_db_entry_t)); entry->bl_type = INTEROP_BL_TYPE_MANUFACTURE; entry->bl_entry_type = entry_type; entry->entry_type.mnfr_entry.feature = (interop_feature_t)feature; @@ -988,8 +958,7 @@ static bool load_to_database(int feature, const char* key, const char* value, char tmp_key[VALID_VNDR_PRDT_LEN + 1] = {'\0'}; if (strlen(key) != VALID_VNDR_PRDT_LEN) { - log::warn("ignoring {} due to invalid vendor/product id in config file", - key); + log::warn("ignoring {} due to invalid vendor/product id in config file", key); return false; } @@ -999,23 +968,20 @@ static bool load_to_database(int feature, const char* key, const char* value, return false; } - interop_db_entry_t* entry = - (interop_db_entry_t*)osi_calloc(sizeof(interop_db_entry_t)); + interop_db_entry_t* entry = (interop_db_entry_t*)osi_calloc(sizeof(interop_db_entry_t)); entry->bl_type = INTEROP_BL_TYPE_VNDR_PRDT; entry->bl_entry_type = entry_type; entry->entry_type.vnr_pdt_entry.feature = (interop_feature_t)feature; entry->entry_type.vnr_pdt_entry.vendor_id = vendor_id; entry->entry_type.vnr_pdt_entry.product_id = product_id; interop_database_add_(entry, false); - } else if (!strncasecmp(value, SSR_MAX_LAT_BASED, - strlen(SSR_MAX_LAT_BASED))) { + } else if (!strncasecmp(value, SSR_MAX_LAT_BASED, strlen(SSR_MAX_LAT_BASED))) { uint16_t max_lat; char tmp_key[KEY_MAX_LENGTH] = {'\0'}; char bdaddr_str[KEY_MAX_LENGTH] = {'\0'}; if (strlen(key) != VALID_SSR_LAT_LEN) { - log::warn("ignoring {} due to invalid key for ssr max lat in config file", - key); + log::warn("ignoring {} due to invalid key for ssr max lat in config file", key); return false; } @@ -1040,15 +1006,11 @@ static bool load_to_database(int feature, const char* key, const char* value, bdstr.append(append_str); if (!RawAddress::FromString(bdstr, addr)) { - log::warn( - "key {} or Bluetooth Address {} is invalid, not added to interop " - "list", - key, addr); + log::warn("key {} or Bluetooth Address {} is invalid, not added to interop list", key, addr); return false; } - interop_db_entry_t* entry = - (interop_db_entry_t*)osi_calloc(sizeof(interop_db_entry_t)); + interop_db_entry_t* entry = (interop_db_entry_t*)osi_calloc(sizeof(interop_db_entry_t)); entry->bl_type = INTEROP_BL_TYPE_SSR_MAX_LAT; entry->bl_entry_type = entry_type; entry->entry_type.ssr_max_lat_entry.feature = (interop_feature_t)feature; @@ -1063,25 +1025,24 @@ static bool load_to_database(int feature, const char* key, const char* value, return false; } - if (token_to_ul((char*)key, &version) == false) return false; + if (token_to_ul((char*)key, &version) == false) { + return false; + } - interop_db_entry_t* entry = - (interop_db_entry_t*)osi_calloc(sizeof(interop_db_entry_t)); + interop_db_entry_t* entry = (interop_db_entry_t*)osi_calloc(sizeof(interop_db_entry_t)); entry->bl_type = INTEROP_BL_TYPE_VERSION; entry->bl_entry_type = entry_type; entry->entry_type.version_entry.feature = (interop_feature_t)feature; entry->entry_type.version_entry.version = version; interop_database_add_(entry, false); - } else if (!strncasecmp(value, LMP_VERSION_BASED, - strlen(LMP_VERSION_BASED))) { + } else if (!strncasecmp(value, LMP_VERSION_BASED, strlen(LMP_VERSION_BASED))) { uint8_t lmp_ver; uint16_t lmp_sub_ver; char tmp_key[KEY_MAX_LENGTH] = {'\0'}; char bdaddr_str[KEY_MAX_LENGTH] = {'\0'}; if (strlen(key) != VALID_LMP_VERSION_LEN) { - log::warn("ignoring {} due to invalid key for lmp ver in config file", - key); + log::warn("ignoring {} due to invalid key for lmp ver in config file", key); return false; } @@ -1106,15 +1067,11 @@ static bool load_to_database(int feature, const char* key, const char* value, bdstr.append(append_str); if (!RawAddress::FromString(bdstr, addr)) { - log::warn( - "key {} or Bluetooth Address {} is invalid, not added to interop " - "list", - key, addr); + log::warn("key {} or Bluetooth Address {} is invalid, not added to interop list", key, addr); return false; } - interop_db_entry_t* entry = - (interop_db_entry_t*)osi_calloc(sizeof(interop_db_entry_t)); + interop_db_entry_t* entry = (interop_db_entry_t*)osi_calloc(sizeof(interop_db_entry_t)); entry->bl_type = INTEROP_BL_TYPE_LMP_VERSION; entry->bl_entry_type = entry_type; entry->entry_type.lmp_version_entry.feature = (interop_feature_t)feature; @@ -1134,15 +1091,13 @@ static bool load_to_database(int feature, const char* key, const char* value, strlcpy(tmp_key, key, VALID_ADDR_RANGE_LEN + 1); if (!get_addr_range(tmp_key, &addr_start, &addr_end)) { - log::warn( - "key: {} addr_start {} or addr end {} is added to interop list", key, - addr_start, addr_end); + log::warn("key: {} addr_start {} or addr end {} is added to interop list", key, addr_start, + addr_end); return false; } - interop_db_entry_t* entry = - (interop_db_entry_t*)osi_calloc(sizeof(interop_db_entry_t)); + interop_db_entry_t* entry = (interop_db_entry_t*)osi_calloc(sizeof(interop_db_entry_t)); entry->bl_type = INTEROP_BL_TYPE_ADDR_RANGE; entry->bl_entry_type = entry_type; entry->entry_type.addr_range_entry.addr_start = addr_start; @@ -1166,8 +1121,7 @@ static void load_config() { pthread_mutex_lock(&file_lock); for (const section_t& sec : config_static.get()->sections) { int feature = -1; - if ((feature = interop_feature_name_to_feature_id(sec.name.c_str())) != - -1) { + if ((feature = interop_feature_name_to_feature_id(sec.name.c_str())) != -1) { for (const entry_t& entry : sec.entries) { load_to_database(feature, entry.key.c_str(), entry.value.c_str(), INTEROP_ENTRY_TYPE_STATIC); @@ -1179,8 +1133,7 @@ static void load_config() { for (const section_t& sec : config_dynamic.get()->sections) { int feature = -1; - if ((feature = interop_feature_name_to_feature_id(sec.name.c_str())) != - -1) { + if ((feature = interop_feature_name_to_feature_id(sec.name.c_str())) != -1) { for (const entry_t& entry : sec.entries) { load_to_database(feature, entry.key.c_str(), entry.value.c_str(), INTEROP_ENTRY_TYPE_DYNAMIC); @@ -1200,15 +1153,12 @@ static void interop_config_cleanup(void) { pthread_mutex_destroy(&file_lock); } -void interop_database_add_addr(const uint16_t feature, const RawAddress* addr, - size_t length) { +void interop_database_add_addr(const uint16_t feature, const RawAddress* addr, size_t length) { log::assert_that(addr != nullptr, "assert failed: addr != nullptr"); log::assert_that(length > 0, "assert failed: length > 0"); - log::assert_that(length < sizeof(RawAddress), - "assert failed: length < sizeof(RawAddress)"); + log::assert_that(length < sizeof(RawAddress), "assert failed: length < sizeof(RawAddress)"); - interop_db_entry_t* entry = - (interop_db_entry_t*)osi_calloc(sizeof(interop_db_entry_t)); + interop_db_entry_t* entry = (interop_db_entry_t*)osi_calloc(sizeof(interop_db_entry_t)); entry->bl_type = INTEROP_BL_TYPE_ADDR; entry->bl_entry_type = INTEROP_ENTRY_TYPE_DYNAMIC; memcpy(&entry->entry_type.addr_entry.addr, addr, length); @@ -1220,24 +1170,19 @@ void interop_database_add_addr(const uint16_t feature, const RawAddress* addr, void interop_database_add_name(const uint16_t feature, const char* name) { log::assert_that(name != nullptr, "assert failed: name != nullptr"); const size_t name_length = strlen(name); - log::assert_that(name_length < KEY_MAX_LENGTH, - "assert failed: name_length < KEY_MAX_LENGTH"); + log::assert_that(name_length < KEY_MAX_LENGTH, "assert failed: name_length < KEY_MAX_LENGTH"); - interop_db_entry_t* entry = - (interop_db_entry_t*)osi_calloc(sizeof(interop_db_entry_t)); + interop_db_entry_t* entry = (interop_db_entry_t*)osi_calloc(sizeof(interop_db_entry_t)); entry->bl_type = INTEROP_BL_TYPE_NAME; entry->bl_entry_type = INTEROP_ENTRY_TYPE_DYNAMIC; - strlcpy(entry->entry_type.name_entry.name, name, - sizeof(entry->entry_type.name_entry.name)); + strlcpy(entry->entry_type.name_entry.name, name, sizeof(entry->entry_type.name_entry.name)); entry->entry_type.name_entry.feature = (interop_feature_t)feature; entry->entry_type.name_entry.length = name_length; interop_database_add_(entry, true); } -void interop_database_add_manufacturer(const interop_feature_t feature, - uint16_t manufacturer) { - interop_db_entry_t* entry = - (interop_db_entry_t*)osi_calloc(sizeof(interop_db_entry_t)); +void interop_database_add_manufacturer(const interop_feature_t feature, uint16_t manufacturer) { + interop_db_entry_t* entry = (interop_db_entry_t*)osi_calloc(sizeof(interop_db_entry_t)); entry->bl_type = INTEROP_BL_TYPE_MANUFACTURE; entry->bl_entry_type = INTEROP_ENTRY_TYPE_DYNAMIC; entry->entry_type.mnfr_entry.feature = feature; @@ -1245,10 +1190,9 @@ void interop_database_add_manufacturer(const interop_feature_t feature, interop_database_add_(entry, true); } -void interop_database_add_vndr_prdt(const interop_feature_t feature, - uint16_t vendor_id, uint16_t product_id) { - interop_db_entry_t* entry = - (interop_db_entry_t*)osi_calloc(sizeof(interop_db_entry_t)); +void interop_database_add_vndr_prdt(const interop_feature_t feature, uint16_t vendor_id, + uint16_t product_id) { + interop_db_entry_t* entry = (interop_db_entry_t*)osi_calloc(sizeof(interop_db_entry_t)); entry->bl_type = INTEROP_BL_TYPE_VNDR_PRDT; entry->bl_entry_type = INTEROP_ENTRY_TYPE_DYNAMIC; entry->entry_type.vnr_pdt_entry.feature = (interop_feature_t)feature; @@ -1257,13 +1201,11 @@ void interop_database_add_vndr_prdt(const interop_feature_t feature, interop_database_add_(entry, true); } -void interop_database_add_addr_max_lat(const interop_feature_t feature, - const RawAddress* addr, +void interop_database_add_addr_max_lat(const interop_feature_t feature, const RawAddress* addr, uint16_t max_lat) { log::assert_that(addr != nullptr, "assert failed: addr != nullptr"); - interop_db_entry_t* entry = - (interop_db_entry_t*)osi_calloc(sizeof(interop_db_entry_t)); + interop_db_entry_t* entry = (interop_db_entry_t*)osi_calloc(sizeof(interop_db_entry_t)); entry->bl_type = INTEROP_BL_TYPE_SSR_MAX_LAT; entry->bl_entry_type = INTEROP_ENTRY_TYPE_DYNAMIC; entry->entry_type.ssr_max_lat_entry.addr = *addr; @@ -1272,10 +1214,8 @@ void interop_database_add_addr_max_lat(const interop_feature_t feature, interop_database_add_(entry, true); } -void interop_database_add_version(const interop_feature_t feature, - uint16_t version) { - interop_db_entry_t* entry = - (interop_db_entry_t*)osi_calloc(sizeof(interop_db_entry_t)); +void interop_database_add_version(const interop_feature_t feature, uint16_t version) { + interop_db_entry_t* entry = (interop_db_entry_t*)osi_calloc(sizeof(interop_db_entry_t)); entry->bl_type = INTEROP_BL_TYPE_VERSION; entry->bl_entry_type = INTEROP_ENTRY_TYPE_DYNAMIC; entry->entry_type.version_entry.feature = (interop_feature_t)feature; @@ -1283,14 +1223,11 @@ void interop_database_add_version(const interop_feature_t feature, interop_database_add_(entry, true); } -void interop_database_add_addr_lmp_version(const interop_feature_t feature, - const RawAddress* addr, - uint8_t lmp_ver, - uint16_t lmp_sub_ver) { +void interop_database_add_addr_lmp_version(const interop_feature_t feature, const RawAddress* addr, + uint8_t lmp_ver, uint16_t lmp_sub_ver) { log::assert_that(addr != nullptr, "assert failed: addr != nullptr"); - interop_db_entry_t* entry = - (interop_db_entry_t*)osi_calloc(sizeof(interop_db_entry_t)); + interop_db_entry_t* entry = (interop_db_entry_t*)osi_calloc(sizeof(interop_db_entry_t)); entry->bl_type = INTEROP_BL_TYPE_LMP_VERSION; entry->bl_entry_type = INTEROP_ENTRY_TYPE_DYNAMIC; entry->entry_type.lmp_version_entry.addr = *addr; @@ -1300,8 +1237,7 @@ void interop_database_add_addr_lmp_version(const interop_feature_t feature, interop_database_add_(entry, true); } -bool interop_database_match_manufacturer(const interop_feature_t feature, - uint16_t manufacturer) { +bool interop_database_match_manufacturer(const interop_feature_t feature, uint16_t manufacturer) { interop_db_entry_t entry; entry.bl_type = INTEROP_BL_TYPE_MANUFACTURE; @@ -1309,20 +1245,17 @@ bool interop_database_match_manufacturer(const interop_feature_t feature, entry.entry_type.mnfr_entry.manufacturer = manufacturer; if (interop_database_match( - &entry, NULL, - (interop_entry_type)(INTEROP_ENTRY_TYPE_STATIC | - INTEROP_ENTRY_TYPE_DYNAMIC))) { - log::warn( - "Device with manufacturer id: {} is a match for interop workaround {}", - manufacturer, interop_feature_string_(feature)); + &entry, NULL, + (interop_entry_type)(INTEROP_ENTRY_TYPE_STATIC | INTEROP_ENTRY_TYPE_DYNAMIC))) { + log::warn("Device with manufacturer id: {} is a match for interop workaround {}", manufacturer, + interop_feature_string_(feature)); return true; } return false; } -bool interop_database_match_name(const interop_feature_t feature, - const char* name) { +bool interop_database_match_name(const interop_feature_t feature, const char* name) { char trim_name[KEY_MAX_LENGTH] = {'\0'}; log::assert_that(name != nullptr, "assert failed: name != nullptr"); @@ -1335,9 +1268,8 @@ bool interop_database_match_name(const interop_feature_t feature, entry.entry_type.name_entry.length = strlen(entry.entry_type.name_entry.name); if (interop_database_match( - &entry, NULL, - (interop_entry_type)(INTEROP_ENTRY_TYPE_STATIC | - INTEROP_ENTRY_TYPE_DYNAMIC))) { + &entry, NULL, + (interop_entry_type)(INTEROP_ENTRY_TYPE_STATIC | INTEROP_ENTRY_TYPE_DYNAMIC))) { log::warn("Device with name: {} is a match for interop workaround {}", name, interop_feature_string_(feature)); return true; @@ -1346,8 +1278,7 @@ bool interop_database_match_name(const interop_feature_t feature, return false; } -bool interop_database_match_addr(const interop_feature_t feature, - const RawAddress* addr) { +bool interop_database_match_addr(const interop_feature_t feature, const RawAddress* addr) { log::assert_that(addr != nullptr, "assert failed: addr != nullptr"); interop_db_entry_t entry; @@ -1358,9 +1289,8 @@ bool interop_database_match_addr(const interop_feature_t feature, entry.entry_type.addr_entry.length = sizeof(RawAddress); if (interop_database_match( - &entry, NULL, - (interop_entry_type)(INTEROP_ENTRY_TYPE_STATIC | - INTEROP_ENTRY_TYPE_DYNAMIC))) { + &entry, NULL, + (interop_entry_type)(INTEROP_ENTRY_TYPE_STATIC | INTEROP_ENTRY_TYPE_DYNAMIC))) { log::warn("Device {} is a match for interop workaround {}.", *addr, interop_feature_string_(feature)); return true; @@ -1371,8 +1301,7 @@ bool interop_database_match_addr(const interop_feature_t feature, entry.entry_type.addr_range_entry.addr_start = *addr; entry.entry_type.addr_range_entry.feature = (interop_feature_t)feature; - if (interop_database_match(&entry, NULL, - (interop_entry_type)(INTEROP_ENTRY_TYPE_STATIC))) { + if (interop_database_match(&entry, NULL, (interop_entry_type)(INTEROP_ENTRY_TYPE_STATIC))) { log::warn("Device {} is a match for interop workaround {}.", *addr, interop_feature_string_(feature)); return true; @@ -1381,8 +1310,8 @@ bool interop_database_match_addr(const interop_feature_t feature, return false; } -bool interop_database_match_vndr_prdt(const interop_feature_t feature, - uint16_t vendor_id, uint16_t product_id) { +bool interop_database_match_vndr_prdt(const interop_feature_t feature, uint16_t vendor_id, + uint16_t product_id) { interop_db_entry_t entry; entry.bl_type = INTEROP_BL_TYPE_VNDR_PRDT; @@ -1391,13 +1320,10 @@ bool interop_database_match_vndr_prdt(const interop_feature_t feature, entry.entry_type.vnr_pdt_entry.vendor_id = vendor_id; entry.entry_type.vnr_pdt_entry.product_id = product_id; if (interop_database_match( - &entry, NULL, - (interop_entry_type)(INTEROP_ENTRY_TYPE_STATIC | - INTEROP_ENTRY_TYPE_DYNAMIC))) { - log::warn( - "Device with vendor_id: {} product_id: {} is a match for interop " - "workaround {}", - vendor_id, product_id, interop_feature_string_(feature)); + &entry, NULL, + (interop_entry_type)(INTEROP_ENTRY_TYPE_STATIC | INTEROP_ENTRY_TYPE_DYNAMIC))) { + log::warn("Device with vendor_id: {} product_id: {} is a match for interop workaround {}", + vendor_id, product_id, interop_feature_string_(feature)); return true; } @@ -1405,8 +1331,7 @@ bool interop_database_match_vndr_prdt(const interop_feature_t feature, } bool interop_database_match_addr_get_max_lat(const interop_feature_t feature, - const RawAddress* addr, - uint16_t* max_lat) { + const RawAddress* addr, uint16_t* max_lat) { interop_db_entry_t entry; interop_db_entry_t* ret_entry = NULL; @@ -1416,9 +1341,8 @@ bool interop_database_match_addr_get_max_lat(const interop_feature_t feature, entry.entry_type.ssr_max_lat_entry.addr = *addr; entry.entry_type.ssr_max_lat_entry.feature = feature; if (interop_database_match( - &entry, &ret_entry, - (interop_entry_type)(INTEROP_ENTRY_TYPE_STATIC | - INTEROP_ENTRY_TYPE_DYNAMIC))) { + &entry, &ret_entry, + (interop_entry_type)(INTEROP_ENTRY_TYPE_STATIC | INTEROP_ENTRY_TYPE_DYNAMIC))) { log::warn("Device {} is a match for interop workaround {}.", *addr, interop_feature_string_(feature)); *max_lat = ret_entry->entry_type.ssr_max_lat_entry.max_lat; @@ -1428,8 +1352,7 @@ bool interop_database_match_addr_get_max_lat(const interop_feature_t feature, return false; } -bool interop_database_match_version(const interop_feature_t feature, - uint16_t version) { +bool interop_database_match_version(const interop_feature_t feature, uint16_t version) { interop_db_entry_t entry; entry.bl_type = INTEROP_BL_TYPE_VERSION; @@ -1437,12 +1360,10 @@ bool interop_database_match_version(const interop_feature_t feature, entry.entry_type.version_entry.feature = (interop_feature_t)feature; entry.entry_type.version_entry.version = version; if (interop_database_match( - &entry, NULL, - (interop_entry_type)(INTEROP_ENTRY_TYPE_STATIC | - INTEROP_ENTRY_TYPE_DYNAMIC))) { - log::warn( - "Device with version: 0x{:04x} is a match for interop workaround {}", - version, interop_feature_string_(feature)); + &entry, NULL, + (interop_entry_type)(INTEROP_ENTRY_TYPE_STATIC | INTEROP_ENTRY_TYPE_DYNAMIC))) { + log::warn("Device with version: 0x{:04x} is a match for interop workaround {}", version, + interop_feature_string_(feature)); return true; } @@ -1450,8 +1371,7 @@ bool interop_database_match_version(const interop_feature_t feature, } bool interop_database_match_addr_get_lmp_ver(const interop_feature_t feature, - const RawAddress* addr, - uint8_t* lmp_ver, + const RawAddress* addr, uint8_t* lmp_ver, uint16_t* lmp_sub_ver) { interop_db_entry_t entry; interop_db_entry_t* ret_entry = NULL; @@ -1462,9 +1382,8 @@ bool interop_database_match_addr_get_lmp_ver(const interop_feature_t feature, entry.entry_type.lmp_version_entry.addr = *addr; entry.entry_type.lmp_version_entry.feature = feature; if (interop_database_match( - &entry, &ret_entry, - (interop_entry_type)(INTEROP_ENTRY_TYPE_STATIC | - INTEROP_ENTRY_TYPE_DYNAMIC))) { + &entry, &ret_entry, + (interop_entry_type)(INTEROP_ENTRY_TYPE_STATIC | INTEROP_ENTRY_TYPE_DYNAMIC))) { log::warn("Device {} is a match for interop workaround {}.", *addr, interop_feature_string_(feature)); *lmp_ver = ret_entry->entry_type.lmp_version_entry.lmp_ver; @@ -1475,8 +1394,7 @@ bool interop_database_match_addr_get_lmp_ver(const interop_feature_t feature, return false; } -bool interop_database_remove_name(const interop_feature_t feature, - const char* name) { +bool interop_database_remove_name(const interop_feature_t feature, const char* name) { log::assert_that(name != nullptr, "assert failed: name != nullptr"); interop_db_entry_t entry; @@ -1487,16 +1405,15 @@ bool interop_database_remove_name(const interop_feature_t feature, entry.entry_type.name_entry.feature = (interop_feature_t)feature; entry.entry_type.name_entry.length = strlen(entry.entry_type.name_entry.name); if (interop_database_remove_(&entry)) { - log::warn("Device with name: {} is removed from interop workaround {}", - name, interop_feature_string_(feature)); + log::warn("Device with name: {} is removed from interop workaround {}", name, + interop_feature_string_(feature)); return true; } return false; } -bool interop_database_remove_manufacturer(const interop_feature_t feature, - uint16_t manufacturer) { +bool interop_database_remove_manufacturer(const interop_feature_t feature, uint16_t manufacturer) { interop_db_entry_t entry; entry.bl_type = INTEROP_BL_TYPE_MANUFACTURE; @@ -1504,17 +1421,15 @@ bool interop_database_remove_manufacturer(const interop_feature_t feature, entry.entry_type.mnfr_entry.feature = feature; entry.entry_type.mnfr_entry.manufacturer = manufacturer; if (interop_database_remove_(&entry)) { - log::warn( - "Device with manufacturer id: {} is removed from interop workaround {}", - manufacturer, interop_feature_string_(feature)); + log::warn("Device with manufacturer id: {} is removed from interop workaround {}", manufacturer, + interop_feature_string_(feature)); return true; } return false; } -bool interop_database_remove_addr(const interop_feature_t feature, - const RawAddress* addr) { +bool interop_database_remove_addr(const interop_feature_t feature, const RawAddress* addr) { log::assert_that(addr != nullptr, "assert failed: addr != nullptr"); interop_db_entry_t entry; @@ -1534,12 +1449,13 @@ bool interop_database_remove_addr(const interop_feature_t feature, } bool interop_database_remove_feature(const interop_feature_t feature) { - if (interop_list == NULL || list_length(interop_list) == 0) return false; + if (interop_list == NULL || list_length(interop_list) == 0) { + return false; + } list_node_t* node = list_begin(interop_list); while (node != list_end(interop_list)) { - interop_db_entry_t* entry = - static_cast(list_node(node)); + interop_db_entry_t* entry = static_cast(list_node(node)); log::assert_that(entry != nullptr, "assert failed: entry != nullptr"); bool entry_match = false; @@ -1605,8 +1521,7 @@ bool interop_database_remove_feature(const interop_feature_t feature) { return false; } -bool interop_database_remove_vndr_prdt(const interop_feature_t feature, - uint16_t vendor_id, +bool interop_database_remove_vndr_prdt(const interop_feature_t feature, uint16_t vendor_id, uint16_t product_id) { interop_db_entry_t entry; @@ -1618,17 +1533,14 @@ bool interop_database_remove_vndr_prdt(const interop_feature_t feature, entry.entry_type.vnr_pdt_entry.product_id = product_id; if (interop_database_remove_(&entry)) { - log::warn( - "Device with vendor_id: {} product_id: {} is removed from interop " - "workaround {}", - vendor_id, product_id, interop_feature_string_(feature)); + log::warn("Device with vendor_id: {} product_id: {} is removed from interop workaround {}", + vendor_id, product_id, interop_feature_string_(feature)); return true; } return false; } -bool interop_database_remove_addr_max_lat(const interop_feature_t feature, - const RawAddress* addr, +bool interop_database_remove_addr_max_lat(const interop_feature_t feature, const RawAddress* addr, uint16_t max_lat) { interop_db_entry_t entry; @@ -1647,8 +1559,7 @@ bool interop_database_remove_addr_max_lat(const interop_feature_t feature, return false; } -bool interop_database_remove_version(const interop_feature_t feature, - uint16_t version) { +bool interop_database_remove_version(const interop_feature_t feature, uint16_t version) { interop_db_entry_t entry; entry.bl_type = INTEROP_BL_TYPE_VERSION; @@ -1658,17 +1569,15 @@ bool interop_database_remove_version(const interop_feature_t feature, entry.entry_type.version_entry.version = version; if (interop_database_remove_(&entry)) { - log::warn( - "Device with version: 0x{:04x} is removed from interop workaround {}", - version, interop_feature_string_(feature)); + log::warn("Device with version: 0x{:04x} is removed from interop workaround {}", version, + interop_feature_string_(feature)); return true; } return false; } bool interop_database_remove_addr_lmp_version(const interop_feature_t feature, - const RawAddress* addr, - uint8_t lmp_ver, + const RawAddress* addr, uint8_t lmp_ver, uint16_t lmp_sub_ver) { interop_db_entry_t entry; diff --git a/system/device/test/device_iot_config_test.cc b/system/device/test/device_iot_config_test.cc index 47176645ffa..676fad4888e 100644 --- a/system/device/test/device_iot_config_test.cc +++ b/system/device/test/device_iot_config_test.cc @@ -41,20 +41,19 @@ using namespace testing; extern module_t device_iot_config_module; -bt_status_t btif_transfer_context(tBTIF_CBACK* p_cback, uint16_t event, - char* p_params, int param_len, - tBTIF_COPY_CBACK* p_copy_cback) { +bt_status_t btif_transfer_context(tBTIF_CBACK* p_cback, uint16_t event, char* p_params, + int param_len, tBTIF_COPY_CBACK* p_copy_cback) { inc_func_call_count(__func__); return BT_STATUS_SUCCESS; } struct alarm_t { - alarm_t(const char* name){}; + alarm_t(const char* name) {} int any_value; }; struct future_t { - future_t(void* value){}; + future_t(void* value) {} void* value; }; @@ -63,53 +62,52 @@ struct future_t placeholder_future(NULL); std::string true_val = "true"; class DeviceIotConfigModuleTest : public testing::Test { - protected: +protected: void SetUp() override { test::mock::osi_alarm::alarm_new.body = [&](const char* name) -> alarm_t* { return &placeholder_alarm; }; test::mock::osi_properties::osi_property_get_bool.body = - [&](const char* key, bool default_value) -> int { return false; }; + [&](const char* key, bool default_value) -> int { return false; }; - test::mock::osi_alarm::alarm_set.body = - [&](alarm_t* alarm, uint64_t interval_ms, alarm_callback_t cb, - void* data) { return; }; + test::mock::osi_alarm::alarm_set.body = [&](alarm_t* alarm, uint64_t interval_ms, + alarm_callback_t cb, void* data) { return; }; test::mock::osi_alarm::alarm_free.body = [](alarm_t* alarm) {}; - test::mock::osi_alarm::alarm_is_scheduled.body = - [&](const alarm_t* alarm) -> bool { return false; }; + test::mock::osi_alarm::alarm_is_scheduled.body = [&](const alarm_t* alarm) -> bool { + return false; + }; - test::mock::osi_future::future_new_immediate.body = - [&](void* value) -> future_t* { return &placeholder_future; }; + test::mock::osi_future::future_new_immediate.body = [&](void* value) -> future_t* { + return &placeholder_future; + }; - test::mock::osi_config::config_new_empty.body = - [&]() -> std::unique_ptr { + test::mock::osi_config::config_new_empty.body = [&]() -> std::unique_ptr { return std::make_unique(); }; test::mock::osi_config::config_new.body = - [&](const char* filename) -> std::unique_ptr { + [&](const char* filename) -> std::unique_ptr { return std::make_unique(); }; test::mock::osi_config::config_get_int.body = - [&](const config_t& config, const std::string& section, - const std::string& key, int def_value) { return def_value; }; + [&](const config_t& config, const std::string& section, const std::string& key, + int def_value) { return def_value; }; - test::mock::osi_config::config_set_int.body = - [&](config_t* config, const std::string& section, - const std::string& key, int value) { return; }; + test::mock::osi_config::config_set_int.body = [&](config_t* config, const std::string& section, + const std::string& key, + int value) { return; }; test::mock::osi_config::config_get_string.body = - [&](const config_t& config, const std::string& section, - const std::string& key, - const std::string* def_value) { return def_value; }; + [&](const config_t& config, const std::string& section, const std::string& key, + const std::string* def_value) { return def_value; }; test::mock::osi_config::config_set_string.body = - [&](config_t* config, const std::string& section, - const std::string& key, const std::string& value) { return; }; + [&](config_t* config, const std::string& section, const std::string& key, + const std::string& value) { return; }; test::mock::osi_allocator::osi_free.body = [&](void* ptr) {}; @@ -133,18 +131,14 @@ class DeviceIotConfigModuleTest : public testing::Test { } }; -TEST_F_WITH_FLAGS( - DeviceIotConfigModuleTest, - test_device_iot_config_module_init_is_factory_reset, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { +TEST_F_WITH_FLAGS(DeviceIotConfigModuleTest, test_device_iot_config_module_init_is_factory_reset, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { bool is_factory_reset = false; config_t* config_new_return_value = NULL; config_t* config_new_empty_return_value = NULL; test::mock::osi_properties::osi_property_get_bool.body = - [&](const char* key, bool default_value) -> int { - return is_factory_reset; - }; + [&](const char* key, bool default_value) -> int { return is_factory_reset; }; test::mock::osi_config::config_new.body = [&](const char* filename) { return std::unique_ptr(config_new_return_value); @@ -165,13 +159,12 @@ TEST_F_WITH_FLAGS( int file_fd = -1; int backup_fd = -1; - file_fd = open(IOT_CONFIG_FILE_PATH, O_CREAT | O_RDWR | O_TRUNC | O_CLOEXEC, - S_IRUSR | S_IWUSR); + file_fd = open(IOT_CONFIG_FILE_PATH, O_CREAT | O_RDWR | O_TRUNC | O_CLOEXEC, S_IRUSR | S_IWUSR); EXPECT_TRUE(file_fd > 0); EXPECT_EQ(errno, 0); - backup_fd = open(IOT_CONFIG_BACKUP_PATH, - O_CREAT | O_RDWR | O_TRUNC | O_CLOEXEC, S_IRUSR | S_IWUSR); + backup_fd = + open(IOT_CONFIG_BACKUP_PATH, O_CREAT | O_RDWR | O_TRUNC | O_CLOEXEC, S_IRUSR | S_IWUSR); EXPECT_TRUE(backup_fd > 0); EXPECT_EQ(errno, 0); @@ -198,9 +191,8 @@ TEST_F_WITH_FLAGS( test::mock::osi_config::config_new_empty.body = {}; } -TEST_F_WITH_FLAGS( - DeviceIotConfigModuleTest, test_device_iot_config_module_init_no_config, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { +TEST_F_WITH_FLAGS(DeviceIotConfigModuleTest, test_device_iot_config_module_init_no_config, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { test::mock::osi_config::config_new.body = [&](const char* filename) { return std::unique_ptr(nullptr); }; @@ -224,9 +216,8 @@ TEST_F_WITH_FLAGS( test::mock::osi_config::config_new_empty.body = {}; } -TEST_F_WITH_FLAGS( - DeviceIotConfigModuleTest, test_device_iot_config_module_init_original, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { +TEST_F_WITH_FLAGS(DeviceIotConfigModuleTest, test_device_iot_config_module_init_original, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { std::string enable_logging_property_get_value; std::string factory_reset_property_get_value; config_t* config_new_return_value = NULL; @@ -251,15 +242,12 @@ TEST_F_WITH_FLAGS( std::string config_get_string_return_value(TIME_STRING_FORMAT); test::mock::osi_config::config_get_int.body = - [&](const config_t& config, const std::string& section, - const std::string& key, - int def_value) { return config_get_int_return_value; }; + [&](const config_t& config, const std::string& section, const std::string& key, + int def_value) { return config_get_int_return_value; }; test::mock::osi_config::config_get_string.body = - [&](const config_t& config, const std::string& section, - const std::string& key, const std::string* def_value) { - return &config_get_string_return_value; - }; + [&](const config_t& config, const std::string& section, const std::string& key, + const std::string* def_value) { return &config_get_string_return_value; }; device_iot_config_module_init(); @@ -277,9 +265,8 @@ TEST_F_WITH_FLAGS( test::mock::osi_config::config_new_empty.body = {}; } -TEST_F_WITH_FLAGS( - DeviceIotConfigModuleTest, test_device_iot_config_module_init_backup, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { +TEST_F_WITH_FLAGS(DeviceIotConfigModuleTest, test_device_iot_config_module_init_backup, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { std::string enable_logging_property_get_value; std::string factory_reset_property_get_value; config_t* config_new_return_value = NULL; @@ -307,15 +294,12 @@ TEST_F_WITH_FLAGS( std::string config_get_string_return_value(TIME_STRING_FORMAT); test::mock::osi_config::config_get_int.body = - [&](const config_t& config, const std::string& section, - const std::string& key, - int def_value) { return config_get_int_return_value; }; + [&](const config_t& config, const std::string& section, const std::string& key, + int def_value) { return config_get_int_return_value; }; test::mock::osi_config::config_get_string.body = - [&](const config_t& config, const std::string& section, - const std::string& key, const std::string* def_value) { - return &config_get_string_return_value; - }; + [&](const config_t& config, const std::string& section, const std::string& key, + const std::string* def_value) { return &config_get_string_return_value; }; device_iot_config_module_init(); @@ -333,9 +317,8 @@ TEST_F_WITH_FLAGS( test::mock::osi_config::config_new_empty.body = {}; } -TEST_F_WITH_FLAGS( - DeviceIotConfigModuleTest, test_device_iot_config_module_init_new_file, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { +TEST_F_WITH_FLAGS(DeviceIotConfigModuleTest, test_device_iot_config_module_init_new_file, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { std::string enable_logging_property_get_value; std::string factory_reset_property_get_value; config_t* config_new_return_value = NULL; @@ -359,10 +342,8 @@ TEST_F_WITH_FLAGS( std::string config_get_string_return_value(TIME_STRING_FORMAT); test::mock::osi_config::config_get_string.body = - [&](const config_t& config, const std::string& section, - const std::string& key, const std::string* def_value) { - return &config_get_string_return_value; - }; + [&](const config_t& config, const std::string& section, const std::string& key, + const std::string* def_value) { return &config_get_string_return_value; }; device_iot_config_module_init(); @@ -380,10 +361,8 @@ TEST_F_WITH_FLAGS( test::mock::osi_config::config_new_empty.body = {}; } -TEST_F_WITH_FLAGS( - DeviceIotConfigModuleTest, - test_device_iot_config_module_init_version_invalid, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { +TEST_F_WITH_FLAGS(DeviceIotConfigModuleTest, test_device_iot_config_module_init_version_invalid, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { std::string enable_logging_property_get_value; std::string factory_reset_property_get_value; config_t* config_new_return_value = NULL; @@ -408,15 +387,12 @@ TEST_F_WITH_FLAGS( std::string config_get_string_return_value(TIME_STRING_FORMAT); test::mock::osi_config::config_get_int.body = - [&](const config_t& config, const std::string& section, - const std::string& key, - int def_value) { return config_get_int_return_value; }; + [&](const config_t& config, const std::string& section, const std::string& key, + int def_value) { return config_get_int_return_value; }; test::mock::osi_config::config_get_string.body = - [&](const config_t& config, const std::string& section, - const std::string& key, const std::string* def_value) { - return &config_get_string_return_value; - }; + [&](const config_t& config, const std::string& section, const std::string& key, + const std::string* def_value) { return &config_get_string_return_value; }; device_iot_config_module_init(); @@ -434,10 +410,9 @@ TEST_F_WITH_FLAGS( test::mock::osi_config::config_new_empty.body = {}; } -TEST_F_WITH_FLAGS( - DeviceIotConfigModuleTest, - test_device_iot_config_module_init_version_new_config_new_empty_success, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { +TEST_F_WITH_FLAGS(DeviceIotConfigModuleTest, + test_device_iot_config_module_init_version_new_config_new_empty_success, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { std::string enable_logging_property_get_value; std::string factory_reset_property_get_value; config_t* config_new_return_value = NULL; @@ -462,28 +437,24 @@ TEST_F_WITH_FLAGS( std::string config_get_string_return_value(TIME_STRING_FORMAT); test::mock::osi_config::config_get_int.body = - [&](const config_t& config, const std::string& section, - const std::string& key, - int def_value) { return config_get_int_return_value; }; + [&](const config_t& config, const std::string& section, const std::string& key, + int def_value) { return config_get_int_return_value; }; test::mock::osi_config::config_get_string.body = - [&](const config_t& config, const std::string& section, - const std::string& key, const std::string* def_value) { - return &config_get_string_return_value; - }; + [&](const config_t& config, const std::string& section, const std::string& key, + const std::string* def_value) { return &config_get_string_return_value; }; int file_fd = -1; int backup_fd = -1; errno = 0; - file_fd = open(IOT_CONFIG_FILE_PATH, O_CREAT | O_RDWR | O_TRUNC | O_CLOEXEC, - S_IRUSR | S_IWUSR); + file_fd = open(IOT_CONFIG_FILE_PATH, O_CREAT | O_RDWR | O_TRUNC | O_CLOEXEC, S_IRUSR | S_IWUSR); EXPECT_TRUE(file_fd > 0); EXPECT_EQ(errno, 0); errno = 0; - backup_fd = open(IOT_CONFIG_BACKUP_PATH, - O_CREAT | O_RDWR | O_TRUNC | O_CLOEXEC, S_IRUSR | S_IWUSR); + backup_fd = + open(IOT_CONFIG_BACKUP_PATH, O_CREAT | O_RDWR | O_TRUNC | O_CLOEXEC, S_IRUSR | S_IWUSR); EXPECT_TRUE(backup_fd > 0); EXPECT_EQ(errno, 0); @@ -514,10 +485,9 @@ TEST_F_WITH_FLAGS( test::mock::osi_config::config_new_empty.body = {}; } -TEST_F_WITH_FLAGS( - DeviceIotConfigModuleTest, - test_device_iot_config_module_init_version_new_config_new_empty_fail, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { +TEST_F_WITH_FLAGS(DeviceIotConfigModuleTest, + test_device_iot_config_module_init_version_new_config_new_empty_fail, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { std::string enable_logging_property_get_value; std::string factory_reset_property_get_value; config_t* config_new_return_value = NULL; @@ -542,28 +512,24 @@ TEST_F_WITH_FLAGS( std::string config_get_string_return_value(TIME_STRING_FORMAT); test::mock::osi_config::config_get_int.body = - [&](const config_t& config, const std::string& section, - const std::string& key, - int def_value) { return config_get_int_return_value; }; + [&](const config_t& config, const std::string& section, const std::string& key, + int def_value) { return config_get_int_return_value; }; test::mock::osi_config::config_get_string.body = - [&](const config_t& config, const std::string& section, - const std::string& key, const std::string* def_value) { - return &config_get_string_return_value; - }; + [&](const config_t& config, const std::string& section, const std::string& key, + const std::string* def_value) { return &config_get_string_return_value; }; int file_fd = -1; int backup_fd = -1; errno = 0; - file_fd = open(IOT_CONFIG_FILE_PATH, O_CREAT | O_RDWR | O_TRUNC | O_CLOEXEC, - S_IRUSR | S_IWUSR); + file_fd = open(IOT_CONFIG_FILE_PATH, O_CREAT | O_RDWR | O_TRUNC | O_CLOEXEC, S_IRUSR | S_IWUSR); EXPECT_TRUE(file_fd > 0); EXPECT_EQ(errno, 0); errno = 0; - backup_fd = open(IOT_CONFIG_BACKUP_PATH, - O_CREAT | O_RDWR | O_TRUNC | O_CLOEXEC, S_IRUSR | S_IWUSR); + backup_fd = + open(IOT_CONFIG_BACKUP_PATH, O_CREAT | O_RDWR | O_TRUNC | O_CLOEXEC, S_IRUSR | S_IWUSR); EXPECT_TRUE(backup_fd > 0); EXPECT_EQ(errno, 0); @@ -594,10 +560,9 @@ TEST_F_WITH_FLAGS( test::mock::osi_config::config_new_empty.body = {}; } -TEST_F_WITH_FLAGS( - DeviceIotConfigModuleTest, - test_device_iot_config_module_init_original_timestamp_null, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { +TEST_F_WITH_FLAGS(DeviceIotConfigModuleTest, + test_device_iot_config_module_init_original_timestamp_null, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { std::string enable_logging_property_get_value; std::string factory_reset_property_get_value; config_t* config_new_return_value = NULL; @@ -621,14 +586,12 @@ TEST_F_WITH_FLAGS( int config_get_int_return_value = DEVICE_IOT_INFO_CURRENT_VERSION; test::mock::osi_config::config_get_int.body = - [&](const config_t& config, const std::string& section, - const std::string& key, - int def_value) { return config_get_int_return_value; }; + [&](const config_t& config, const std::string& section, const std::string& key, + int def_value) { return config_get_int_return_value; }; test::mock::osi_config::config_get_string.body = - [&](const config_t& config, const std::string& section, - const std::string& key, - const std::string* def_value) { return nullptr; }; + [&](const config_t& config, const std::string& section, const std::string& key, + const std::string* def_value) { return nullptr; }; device_iot_config_module_init(); @@ -646,10 +609,8 @@ TEST_F_WITH_FLAGS( test::mock::osi_config::config_new_empty.body = {}; } -TEST_F_WITH_FLAGS( - DeviceIotConfigModuleTest, - test_device_iot_config_module_init_alarm_new_fail, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { +TEST_F_WITH_FLAGS(DeviceIotConfigModuleTest, test_device_iot_config_module_init_alarm_new_fail, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { std::string enable_logging_property_get_value; std::string factory_reset_property_get_value; config_t* config_new_return_value = NULL; @@ -674,19 +635,14 @@ TEST_F_WITH_FLAGS( std::string config_get_string_return_value(TIME_STRING_FORMAT); test::mock::osi_config::config_get_int.body = - [&](const config_t& config, const std::string& section, - const std::string& key, - int def_value) { return config_get_int_return_value; }; + [&](const config_t& config, const std::string& section, const std::string& key, + int def_value) { return config_get_int_return_value; }; test::mock::osi_config::config_get_string.body = - [&](const config_t& config, const std::string& section, - const std::string& key, const std::string* def_value) { - return &config_get_string_return_value; - }; + [&](const config_t& config, const std::string& section, const std::string& key, + const std::string* def_value) { return &config_get_string_return_value; }; - test::mock::osi_alarm::alarm_new.body = [&](const char* name) { - return nullptr; - }; + test::mock::osi_alarm::alarm_new.body = [&](const char* name) { return nullptr; }; device_iot_config_module_init(); @@ -704,9 +660,8 @@ TEST_F_WITH_FLAGS( test::mock::osi_config::config_new_empty.body = {}; } -TEST_F_WITH_FLAGS( - DeviceIotConfigModuleTest, test_device_iot_config_module_start_up, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { +TEST_F_WITH_FLAGS(DeviceIotConfigModuleTest, test_device_iot_config_module_start_up, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { std::string enable_logging_property_get_value; std::string factory_reset_property_get_value; @@ -729,15 +684,15 @@ TEST_F_WITH_FLAGS( test::mock::osi_config::config_new_empty.body = {}; } -TEST_F_WITH_FLAGS( - DeviceIotConfigModuleTest, test_device_iot_config_module_shutdown, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { +TEST_F_WITH_FLAGS(DeviceIotConfigModuleTest, test_device_iot_config_module_shutdown, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { bool return_value; std::string enable_logging_property_get_value; std::string factory_reset_property_get_value; - test::mock::osi_alarm::alarm_is_scheduled.body = - [&](const alarm_t* alarm) -> bool { return return_value; }; + test::mock::osi_alarm::alarm_is_scheduled.body = [&](const alarm_t* alarm) -> bool { + return return_value; + }; enable_logging_property_get_value = "true"; device_iot_config_module_init(); @@ -775,15 +730,15 @@ TEST_F_WITH_FLAGS( test::mock::osi_alarm::alarm_is_scheduled.body = {}; } -TEST_F_WITH_FLAGS( - DeviceIotConfigModuleTest, test_device_iot_config_module_clean_up, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { +TEST_F_WITH_FLAGS(DeviceIotConfigModuleTest, test_device_iot_config_module_clean_up, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { bool return_value; std::string enable_logging_property_get_value; std::string factory_reset_property_get_value; - test::mock::osi_alarm::alarm_is_scheduled.body = - [&](const alarm_t* alarm) -> bool { return return_value; }; + test::mock::osi_alarm::alarm_is_scheduled.body = [&](const alarm_t* alarm) -> bool { + return return_value; + }; enable_logging_property_get_value = "true"; device_iot_config_module_init(); @@ -824,53 +779,52 @@ TEST_F_WITH_FLAGS( } class DeviceIotConfigTest : public testing::Test { - protected: +protected: void SetUp() override { test::mock::osi_alarm::alarm_new.body = [&](const char* name) -> alarm_t* { return &placeholder_alarm; }; test::mock::osi_properties::osi_property_get_bool.body = - [&](const char* key, bool default_value) -> int { return false; }; + [&](const char* key, bool default_value) -> int { return false; }; - test::mock::osi_alarm::alarm_set.body = - [&](alarm_t* alarm, uint64_t interval_ms, alarm_callback_t cb, - void* data) { return; }; + test::mock::osi_alarm::alarm_set.body = [&](alarm_t* alarm, uint64_t interval_ms, + alarm_callback_t cb, void* data) { return; }; test::mock::osi_alarm::alarm_free.body = [](alarm_t* alarm) {}; - test::mock::osi_alarm::alarm_is_scheduled.body = - [&](const alarm_t* alarm) -> bool { return false; }; + test::mock::osi_alarm::alarm_is_scheduled.body = [&](const alarm_t* alarm) -> bool { + return false; + }; - test::mock::osi_future::future_new_immediate.body = - [&](void* value) -> future_t* { return &placeholder_future; }; + test::mock::osi_future::future_new_immediate.body = [&](void* value) -> future_t* { + return &placeholder_future; + }; - test::mock::osi_config::config_new_empty.body = - [&]() -> std::unique_ptr { + test::mock::osi_config::config_new_empty.body = [&]() -> std::unique_ptr { return std::make_unique(); }; test::mock::osi_config::config_new.body = - [&](const char* filename) -> std::unique_ptr { + [&](const char* filename) -> std::unique_ptr { return std::make_unique(); }; test::mock::osi_config::config_get_int.body = - [&](const config_t& config, const std::string& section, - const std::string& key, int def_value) { return def_value; }; + [&](const config_t& config, const std::string& section, const std::string& key, + int def_value) { return def_value; }; - test::mock::osi_config::config_set_int.body = - [&](config_t* config, const std::string& section, - const std::string& key, int value) { return; }; + test::mock::osi_config::config_set_int.body = [&](config_t* config, const std::string& section, + const std::string& key, + int value) { return; }; test::mock::osi_config::config_get_string.body = - [&](const config_t& config, const std::string& section, - const std::string& key, - const std::string* def_value) { return def_value; }; + [&](const config_t& config, const std::string& section, const std::string& key, + const std::string* def_value) { return def_value; }; test::mock::osi_config::config_set_string.body = - [&](config_t* config, const std::string& section, - const std::string& key, const std::string& value) { return; }; + [&](config_t* config, const std::string& section, const std::string& key, + const std::string& value) { return; }; test::mock::osi_allocator::osi_free.body = [&](void* ptr) {}; @@ -897,9 +851,8 @@ class DeviceIotConfigTest : public testing::Test { } }; -TEST_F_WITH_FLAGS( - DeviceIotConfigTest, test_device_iot_config_sections_sort_by_entry_key, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { +TEST_F_WITH_FLAGS(DeviceIotConfigTest, test_device_iot_config_sections_sort_by_entry_key, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { { config_t conf; device_iot_config_sections_sort_by_entry_key(conf, NULL); @@ -908,43 +861,43 @@ TEST_F_WITH_FLAGS( { config_t conf; conf.sections = { - section_t{.entries = - { - entry_t{ - .key = "a", - }, - entry_t{ - .key = "b", - }, - entry_t{ - .key = "c", - }, - entry_t{ - .key = "d", - }, - }}, - - section_t{.entries = - { - entry_t{ - .key = "d", - }, - entry_t{ - .key = "c", - }, - entry_t{ - .key = "b", - }, - entry_t{ - .key = "a", - }, - }}, + section_t{.entries = + { + entry_t{ + .key = "a", + }, + entry_t{ + .key = "b", + }, + entry_t{ + .key = "c", + }, + entry_t{ + .key = "d", + }, + }}, + + section_t{.entries = + { + entry_t{ + .key = "d", + }, + entry_t{ + .key = "c", + }, + entry_t{ + .key = "b", + }, + entry_t{ + .key = "a", + }, + }}, }; - device_iot_config_sections_sort_by_entry_key( - conf, [](const entry_t& first, const entry_t& second) { - return first.key.compare(second.key) >= 0; - }); + device_iot_config_sections_sort_by_entry_key(conf, + [](const entry_t& first, const entry_t& second) { + return first.key.compare(second.key) >= 0; + }); auto& sec1 = conf.sections.front(); auto& sec2 = conf.sections.back(); @@ -957,17 +910,16 @@ TEST_F_WITH_FLAGS( } } -TEST_F_WITH_FLAGS( - DeviceIotConfigTest, test_device_iot_config_has_section, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { +TEST_F_WITH_FLAGS(DeviceIotConfigTest, test_device_iot_config_has_section, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { std::string actual_section, expected_section = "abc"; bool return_value = false; - test::mock::osi_config::config_has_section.body = - [&](const config_t& config, const std::string& section) { - actual_section = section; - return return_value; - }; + test::mock::osi_config::config_has_section.body = [&](const config_t& config, + const std::string& section) { + actual_section = section; + return return_value; + }; { reset_mock_function_count_map(); @@ -991,26 +943,22 @@ TEST_F_WITH_FLAGS( test::mock::osi_config::config_has_section.body = {}; } -TEST_F_WITH_FLAGS( - DeviceIotConfigTest, test_device_iot_config_exist, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { - std::string actual_section, actual_key, expected_section = "abc", - expected_key = "def"; +TEST_F_WITH_FLAGS(DeviceIotConfigTest, test_device_iot_config_exist, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { + std::string actual_section, actual_key, expected_section = "abc", expected_key = "def"; bool return_value = false; - test::mock::osi_config::config_has_key.body = [&](const config_t& config, - const std::string& section, - const std::string& key) { - actual_section = section; - actual_key = key; - return return_value; - }; + test::mock::osi_config::config_has_key.body = + [&](const config_t& config, const std::string& section, const std::string& key) { + actual_section = section; + actual_key = key; + return return_value; + }; { reset_mock_function_count_map(); - EXPECT_EQ(device_iot_config_exist(expected_section, expected_key), - return_value); + EXPECT_EQ(device_iot_config_exist(expected_section, expected_key), return_value); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); @@ -1022,8 +970,7 @@ TEST_F_WITH_FLAGS( return_value = true; - EXPECT_EQ(device_iot_config_exist(expected_section, expected_key), - return_value); + EXPECT_EQ(device_iot_config_exist(expected_section, expected_key), return_value); EXPECT_EQ(get_func_call_count("config_has_key"), 1); } @@ -1031,29 +978,27 @@ TEST_F_WITH_FLAGS( test::mock::osi_config::config_has_key.body = {}; } -TEST_F_WITH_FLAGS( - DeviceIotConfigTest, test_device_iot_config_has_key_value, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { - std::string actual_section, actual_key, expected_section = "abc", - expected_key = "def"; +TEST_F_WITH_FLAGS(DeviceIotConfigTest, test_device_iot_config_has_key_value, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { + std::string actual_section, actual_key, expected_section = "abc", expected_key = "def"; std::string expected_value_str = "xyz", actual_value_str; const std::string* actual_def_value = NULL; const std::string* return_value = NULL; test::mock::osi_config::config_get_string.body = - [&](const config_t& config, const std::string& section, - const std::string& key, const std::string* def_value) { - actual_section = section; - actual_key = key; - actual_def_value = def_value; - return return_value; - }; + [&](const config_t& config, const std::string& section, const std::string& key, + const std::string* def_value) { + actual_section = section; + actual_key = key; + actual_def_value = def_value; + return return_value; + }; { reset_mock_function_count_map(); - EXPECT_FALSE(device_iot_config_has_key_value(expected_section, expected_key, - expected_value_str)); + EXPECT_FALSE( + device_iot_config_has_key_value(expected_section, expected_key, expected_value_str)); EXPECT_TRUE(actual_def_value == NULL); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); @@ -1066,8 +1011,8 @@ TEST_F_WITH_FLAGS( actual_value_str = "xyy"; return_value = &actual_value_str; - EXPECT_FALSE(device_iot_config_has_key_value(expected_section, expected_key, - expected_value_str)); + EXPECT_FALSE( + device_iot_config_has_key_value(expected_section, expected_key, expected_value_str)); EXPECT_TRUE(actual_def_value == NULL); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); @@ -1080,8 +1025,8 @@ TEST_F_WITH_FLAGS( actual_value_str = "xy"; return_value = &actual_value_str; - EXPECT_FALSE(device_iot_config_has_key_value(expected_section, expected_key, - expected_value_str)); + EXPECT_FALSE( + device_iot_config_has_key_value(expected_section, expected_key, expected_value_str)); EXPECT_TRUE(actual_def_value == NULL); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); @@ -1094,8 +1039,8 @@ TEST_F_WITH_FLAGS( actual_value_str = "xyyy"; return_value = &actual_value_str; - EXPECT_FALSE(device_iot_config_has_key_value(expected_section, expected_key, - expected_value_str)); + EXPECT_FALSE( + device_iot_config_has_key_value(expected_section, expected_key, expected_value_str)); EXPECT_TRUE(actual_def_value == NULL); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); @@ -1108,8 +1053,8 @@ TEST_F_WITH_FLAGS( actual_value_str = "xyz"; return_value = &actual_value_str; - EXPECT_TRUE(device_iot_config_has_key_value(expected_section, expected_key, - expected_value_str)); + EXPECT_TRUE( + device_iot_config_has_key_value(expected_section, expected_key, expected_value_str)); EXPECT_TRUE(actual_def_value == NULL); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); @@ -1120,32 +1065,27 @@ TEST_F_WITH_FLAGS( test::mock::osi_config::config_get_string.body = {}; } -TEST_F_WITH_FLAGS( - DeviceIotConfigTest, test_device_iot_config_get_int, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { - std::string actual_section, actual_key, expected_section = "abc", - expected_key = "def"; +TEST_F_WITH_FLAGS(DeviceIotConfigTest, test_device_iot_config_get_int, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { + std::string actual_section, actual_key, expected_section = "abc", expected_key = "def"; bool return_value = false; int int_value = 0, new_value = 0xff; - test::mock::osi_config::config_has_key.body = [&](const config_t& config, - const std::string& section, - const std::string& key) { - actual_section = section; - actual_key = key; - return return_value; - }; + test::mock::osi_config::config_has_key.body = + [&](const config_t& config, const std::string& section, const std::string& key) { + actual_section = section; + actual_key = key; + return return_value; + }; test::mock::osi_config::config_get_int.body = - [&](const config_t& config, const std::string& section, - const std::string& key, int def_value) { return new_value; }; + [&](const config_t& config, const std::string& section, const std::string& key, + int def_value) { return new_value; }; { reset_mock_function_count_map(); - EXPECT_EQ( - device_iot_config_get_int(expected_section, expected_key, int_value), - return_value); + EXPECT_EQ(device_iot_config_get_int(expected_section, expected_key, int_value), return_value); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); @@ -1158,9 +1098,7 @@ TEST_F_WITH_FLAGS( return_value = true; - EXPECT_EQ( - device_iot_config_get_int(expected_section, expected_key, int_value), - return_value); + EXPECT_EQ(device_iot_config_get_int(expected_section, expected_key, int_value), return_value); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); EXPECT_EQ(int_value, new_value); @@ -1173,33 +1111,29 @@ TEST_F_WITH_FLAGS( test::mock::osi_config::config_get_int.body = {}; } -TEST_F_WITH_FLAGS( - DeviceIotConfigTest, test_device_iot_config_addr_get_int, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { +TEST_F_WITH_FLAGS(DeviceIotConfigTest, test_device_iot_config_addr_get_int, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { const RawAddress peer_addr{}; - std::string actual_section, actual_key, - expected_section = "00:00:00:00:00:00", expected_key = "def"; + std::string actual_section, actual_key, expected_section = "00:00:00:00:00:00", + expected_key = "def"; bool return_value = false; int int_value = 0, new_value = 0xff; - test::mock::osi_config::config_has_key.body = [&](const config_t& config, - const std::string& section, - const std::string& key) { - actual_section = section; - actual_key = key; - return return_value; - }; + test::mock::osi_config::config_has_key.body = + [&](const config_t& config, const std::string& section, const std::string& key) { + actual_section = section; + actual_key = key; + return return_value; + }; test::mock::osi_config::config_get_int.body = - [&](const config_t& config, const std::string& section, - const std::string& key, int def_value) { return new_value; }; + [&](const config_t& config, const std::string& section, const std::string& key, + int def_value) { return new_value; }; { reset_mock_function_count_map(); - EXPECT_EQ( - DEVICE_IOT_CONFIG_ADDR_GET_INT(peer_addr, expected_key, int_value), - return_value); + EXPECT_EQ(DEVICE_IOT_CONFIG_ADDR_GET_INT(peer_addr, expected_key, int_value), return_value); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); @@ -1212,9 +1146,7 @@ TEST_F_WITH_FLAGS( return_value = true; - EXPECT_EQ( - DEVICE_IOT_CONFIG_ADDR_GET_INT(peer_addr, expected_key, int_value), - return_value); + EXPECT_EQ(DEVICE_IOT_CONFIG_ADDR_GET_INT(peer_addr, expected_key, int_value), return_value); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); EXPECT_EQ(int_value, new_value); @@ -1227,37 +1159,33 @@ TEST_F_WITH_FLAGS( test::mock::osi_config::config_get_int.body = {}; } -TEST_F_WITH_FLAGS( - DeviceIotConfigTest, test_device_iot_config_set_int, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { - std::string actual_section, actual_key, expected_section = "abc", - expected_key = "def"; +TEST_F_WITH_FLAGS(DeviceIotConfigTest, test_device_iot_config_set_int, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { + std::string actual_section, actual_key, expected_section = "abc", expected_key = "def"; std::string string_return_value = "123456789"; std::string old_string_value = string_return_value; std::string new_string_value; int int_value = 123456789; test::mock::osi_config::config_get_string.body = - [&](const config_t& config, const std::string& section, - const std::string& key, const std::string* def_value) { - actual_section = section; - actual_key = key; - return &string_return_value; - }; + [&](const config_t& config, const std::string& section, const std::string& key, + const std::string* def_value) { + actual_section = section; + actual_key = key; + return &string_return_value; + }; test::mock::osi_config::config_set_string.body = - [&](config_t* config, const std::string& section, const std::string& key, - const std::string& value) { new_string_value = value; }; + [&](config_t* config, const std::string& section, const std::string& key, + const std::string& value) { new_string_value = value; }; - test::mock::osi_alarm::alarm_set.body = - [&](alarm_t* alarm, uint64_t interval_ms, alarm_callback_t cb, - void* data) {}; + test::mock::osi_alarm::alarm_set.body = [&](alarm_t* alarm, uint64_t interval_ms, + alarm_callback_t cb, void* data) {}; { reset_mock_function_count_map(); - EXPECT_TRUE( - device_iot_config_set_int(expected_section, expected_key, int_value)); + EXPECT_TRUE(device_iot_config_set_int(expected_section, expected_key, int_value)); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); @@ -1271,8 +1199,7 @@ TEST_F_WITH_FLAGS( string_return_value = "123"; - EXPECT_TRUE( - device_iot_config_set_int(expected_section, expected_key, int_value)); + EXPECT_TRUE(device_iot_config_set_int(expected_section, expected_key, int_value)); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); EXPECT_EQ(new_string_value, old_string_value); @@ -1287,9 +1214,8 @@ TEST_F_WITH_FLAGS( test::mock::osi_alarm::alarm_set.body = {}; } -TEST_F_WITH_FLAGS( - DeviceIotConfigTest, test_device_iot_config_addr_set_int, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { +TEST_F_WITH_FLAGS(DeviceIotConfigTest, test_device_iot_config_addr_set_int, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { const RawAddress peer_addr{}; std::string actual_key, expected_key = "def"; std::string actual_section, expected_section = "00:00:00:00:00:00"; @@ -1299,26 +1225,24 @@ TEST_F_WITH_FLAGS( int int_value = 123456789; test::mock::osi_config::config_get_string.body = - [&](const config_t& config, const std::string& section, - const std::string& key, const std::string* def_value) { - actual_section = section; - actual_key = key; - return &string_return_value; - }; + [&](const config_t& config, const std::string& section, const std::string& key, + const std::string* def_value) { + actual_section = section; + actual_key = key; + return &string_return_value; + }; test::mock::osi_config::config_set_string.body = - [&](config_t* config, const std::string& section, const std::string& key, - const std::string& value) { new_string_value = value; }; + [&](config_t* config, const std::string& section, const std::string& key, + const std::string& value) { new_string_value = value; }; - test::mock::osi_alarm::alarm_set.body = - [&](alarm_t* alarm, uint64_t interval_ms, alarm_callback_t cb, - void* data) {}; + test::mock::osi_alarm::alarm_set.body = [&](alarm_t* alarm, uint64_t interval_ms, + alarm_callback_t cb, void* data) {}; { reset_mock_function_count_map(); - EXPECT_TRUE( - DEVICE_IOT_CONFIG_ADDR_SET_INT(peer_addr, expected_key, int_value)); + EXPECT_TRUE(DEVICE_IOT_CONFIG_ADDR_SET_INT(peer_addr, expected_key, int_value)); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); @@ -1332,8 +1256,7 @@ TEST_F_WITH_FLAGS( string_return_value = "123"; - EXPECT_TRUE( - DEVICE_IOT_CONFIG_ADDR_SET_INT(peer_addr, expected_key, int_value)); + EXPECT_TRUE(DEVICE_IOT_CONFIG_ADDR_SET_INT(peer_addr, expected_key, int_value)); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); EXPECT_EQ(new_string_value, old_string_value); @@ -1348,29 +1271,26 @@ TEST_F_WITH_FLAGS( test::mock::osi_alarm::alarm_set.body = {}; } -TEST_F_WITH_FLAGS( - DeviceIotConfigTest, test_device_iot_config_int_add_one, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { - std::string actual_section, actual_key, expected_section = "abc", - expected_key = "def"; +TEST_F_WITH_FLAGS(DeviceIotConfigTest, test_device_iot_config_int_add_one, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { + std::string actual_section, actual_key, expected_section = "abc", expected_key = "def"; int int_value = 0, get_default_value, set_value; - test::mock::osi_config::config_get_int.body = - [&](const config_t& config, const std::string& section, - const std::string& key, int def_value) { - actual_section = section; - actual_key = key; - get_default_value = def_value; - return int_value; - }; + test::mock::osi_config::config_get_int.body = [&](const config_t& config, + const std::string& section, + const std::string& key, int def_value) { + actual_section = section; + actual_key = key; + get_default_value = def_value; + return int_value; + }; - test::mock::osi_config::config_set_int.body = - [&](config_t* config, const std::string& section, const std::string& key, - int val) { set_value = val; }; + test::mock::osi_config::config_set_int.body = [&](config_t* config, const std::string& section, + const std::string& key, + int val) { set_value = val; }; - test::mock::osi_alarm::alarm_set.body = - [&](alarm_t* alarm, uint64_t interval_ms, alarm_callback_t cb, - void* data) {}; + test::mock::osi_alarm::alarm_set.body = [&](alarm_t* alarm, uint64_t interval_ms, + alarm_callback_t cb, void* data) {}; { reset_mock_function_count_map(); @@ -1458,30 +1378,28 @@ TEST_F_WITH_FLAGS( test::mock::osi_alarm::alarm_set.body = {}; } -TEST_F_WITH_FLAGS( - DeviceIotConfigTest, test_device_iot_config_addr_int_add_one, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { +TEST_F_WITH_FLAGS(DeviceIotConfigTest, test_device_iot_config_addr_int_add_one, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { const RawAddress peer_addr{}; - std::string actual_section, actual_key, - expected_section = "00:00:00:00:00:00", expected_key = "def"; + std::string actual_section, actual_key, expected_section = "00:00:00:00:00:00", + expected_key = "def"; int int_value = 0, get_default_value, set_value; - test::mock::osi_config::config_get_int.body = - [&](const config_t& config, const std::string& section, - const std::string& key, int def_value) { - actual_section = section; - actual_key = key; - get_default_value = def_value; - return int_value; - }; + test::mock::osi_config::config_get_int.body = [&](const config_t& config, + const std::string& section, + const std::string& key, int def_value) { + actual_section = section; + actual_key = key; + get_default_value = def_value; + return int_value; + }; - test::mock::osi_config::config_set_int.body = - [&](config_t* config, const std::string& section, const std::string& key, - int val) { set_value = val; }; + test::mock::osi_config::config_set_int.body = [&](config_t* config, const std::string& section, + const std::string& key, + int val) { set_value = val; }; - test::mock::osi_alarm::alarm_set.body = - [&](alarm_t* alarm, uint64_t interval_ms, alarm_callback_t cb, - void* data) {}; + test::mock::osi_alarm::alarm_set.body = [&](alarm_t* alarm, uint64_t interval_ms, + alarm_callback_t cb, void* data) {}; { reset_mock_function_count_map(); @@ -1568,28 +1486,26 @@ TEST_F_WITH_FLAGS( test::mock::osi_alarm::alarm_set.body = {}; } -TEST_F_WITH_FLAGS( - DeviceIotConfigTest, test_device_iot_config_get_hex, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { - std::string actual_section, actual_key, - expected_section = "00:00:00:00:00:00", expected_key = "def"; +TEST_F_WITH_FLAGS(DeviceIotConfigTest, test_device_iot_config_get_hex, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { + std::string actual_section, actual_key, expected_section = "00:00:00:00:00:00", + expected_key = "def"; int int_value = 0; std::string string_value; std::string* get_string_return_value = NULL; test::mock::osi_config::config_get_string.body = - [&](const config_t& config, const std::string& section, - const std::string& key, const std::string* def_value) { - actual_section = section; - actual_key = key; - return get_string_return_value; - }; + [&](const config_t& config, const std::string& section, const std::string& key, + const std::string* def_value) { + actual_section = section; + actual_key = key; + return get_string_return_value; + }; { reset_mock_function_count_map(); - EXPECT_FALSE( - device_iot_config_get_hex(expected_section, expected_key, int_value)); + EXPECT_FALSE(device_iot_config_get_hex(expected_section, expected_key, int_value)); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); EXPECT_EQ(int_value, 0); @@ -1602,8 +1518,7 @@ TEST_F_WITH_FLAGS( string_value = "g"; get_string_return_value = &string_value; - EXPECT_FALSE( - device_iot_config_get_hex(expected_section, expected_key, int_value)); + EXPECT_FALSE(device_iot_config_get_hex(expected_section, expected_key, int_value)); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); EXPECT_EQ(int_value, 0); @@ -1616,8 +1531,7 @@ TEST_F_WITH_FLAGS( string_value = "abcg"; get_string_return_value = &string_value; - EXPECT_FALSE( - device_iot_config_get_hex(expected_section, expected_key, int_value)); + EXPECT_FALSE(device_iot_config_get_hex(expected_section, expected_key, int_value)); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); EXPECT_EQ(int_value, 0); @@ -1630,8 +1544,7 @@ TEST_F_WITH_FLAGS( string_value = "f"; get_string_return_value = &string_value; - EXPECT_TRUE( - device_iot_config_get_hex(expected_section, expected_key, int_value)); + EXPECT_TRUE(device_iot_config_get_hex(expected_section, expected_key, int_value)); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); EXPECT_EQ(int_value, 15); @@ -1644,8 +1557,7 @@ TEST_F_WITH_FLAGS( string_value = "0"; get_string_return_value = &string_value; - EXPECT_TRUE( - device_iot_config_get_hex(expected_section, expected_key, int_value)); + EXPECT_TRUE(device_iot_config_get_hex(expected_section, expected_key, int_value)); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); EXPECT_EQ(int_value, 0); @@ -1658,8 +1570,7 @@ TEST_F_WITH_FLAGS( string_value = "1"; get_string_return_value = &string_value; - EXPECT_TRUE( - device_iot_config_get_hex(expected_section, expected_key, int_value)); + EXPECT_TRUE(device_iot_config_get_hex(expected_section, expected_key, int_value)); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); EXPECT_EQ(int_value, 1); @@ -1672,8 +1583,7 @@ TEST_F_WITH_FLAGS( string_value = "-e"; get_string_return_value = &string_value; - EXPECT_TRUE( - device_iot_config_get_hex(expected_section, expected_key, int_value)); + EXPECT_TRUE(device_iot_config_get_hex(expected_section, expected_key, int_value)); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); EXPECT_EQ(int_value, -14); @@ -1686,8 +1596,7 @@ TEST_F_WITH_FLAGS( string_value = "-f"; get_string_return_value = &string_value; - EXPECT_TRUE( - device_iot_config_get_hex(expected_section, expected_key, int_value)); + EXPECT_TRUE(device_iot_config_get_hex(expected_section, expected_key, int_value)); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); EXPECT_EQ(int_value, -15); @@ -1700,8 +1609,7 @@ TEST_F_WITH_FLAGS( string_value = "0x7fffffff"; get_string_return_value = &string_value; - EXPECT_TRUE( - device_iot_config_get_hex(expected_section, expected_key, int_value)); + EXPECT_TRUE(device_iot_config_get_hex(expected_section, expected_key, int_value)); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); EXPECT_EQ(int_value, INT_MAX); @@ -1714,8 +1622,7 @@ TEST_F_WITH_FLAGS( string_value = "-0x80000000"; get_string_return_value = &string_value; - EXPECT_TRUE( - device_iot_config_get_hex(expected_section, expected_key, int_value)); + EXPECT_TRUE(device_iot_config_get_hex(expected_section, expected_key, int_value)); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); EXPECT_EQ(int_value, INT_MIN); @@ -1728,8 +1635,7 @@ TEST_F_WITH_FLAGS( string_value = "0xffffffff"; get_string_return_value = &string_value; - EXPECT_TRUE( - device_iot_config_get_hex(expected_section, expected_key, int_value)); + EXPECT_TRUE(device_iot_config_get_hex(expected_section, expected_key, int_value)); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); EXPECT_EQ(int_value, -1); @@ -1740,29 +1646,27 @@ TEST_F_WITH_FLAGS( test::mock::osi_config::config_get_string.body = {}; } -TEST_F_WITH_FLAGS( - DeviceIotConfigTest, test_device_iot_config_addr_get_hex, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { +TEST_F_WITH_FLAGS(DeviceIotConfigTest, test_device_iot_config_addr_get_hex, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { const RawAddress peer_addr{}; - std::string actual_section, actual_key, - expected_section = "00:00:00:00:00:00", expected_key = "def"; + std::string actual_section, actual_key, expected_section = "00:00:00:00:00:00", + expected_key = "def"; int int_value = 0; std::string string_value; std::string* get_string_return_value = NULL; test::mock::osi_config::config_get_string.body = - [&](const config_t& config, const std::string& section, - const std::string& key, const std::string* def_value) { - actual_section = section; - actual_key = key; - return get_string_return_value; - }; + [&](const config_t& config, const std::string& section, const std::string& key, + const std::string* def_value) { + actual_section = section; + actual_key = key; + return get_string_return_value; + }; { reset_mock_function_count_map(); - EXPECT_FALSE( - DEVICE_IOT_CONFIG_ADDR_GET_HEX(peer_addr, expected_key, int_value)); + EXPECT_FALSE(DEVICE_IOT_CONFIG_ADDR_GET_HEX(peer_addr, expected_key, int_value)); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); EXPECT_EQ(int_value, 0); @@ -1776,8 +1680,7 @@ TEST_F_WITH_FLAGS( string_value = "g"; get_string_return_value = &string_value; - EXPECT_FALSE( - DEVICE_IOT_CONFIG_ADDR_GET_HEX(peer_addr, expected_key, int_value)); + EXPECT_FALSE(DEVICE_IOT_CONFIG_ADDR_GET_HEX(peer_addr, expected_key, int_value)); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); EXPECT_EQ(int_value, 0); @@ -1791,8 +1694,7 @@ TEST_F_WITH_FLAGS( string_value = "f"; get_string_return_value = &string_value; - EXPECT_TRUE( - DEVICE_IOT_CONFIG_ADDR_GET_HEX(peer_addr, expected_key, int_value)); + EXPECT_TRUE(DEVICE_IOT_CONFIG_ADDR_GET_HEX(peer_addr, expected_key, int_value)); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); EXPECT_EQ(int_value, 15); @@ -1806,8 +1708,7 @@ TEST_F_WITH_FLAGS( string_value = "0"; get_string_return_value = &string_value; - EXPECT_TRUE( - DEVICE_IOT_CONFIG_ADDR_GET_HEX(peer_addr, expected_key, int_value)); + EXPECT_TRUE(DEVICE_IOT_CONFIG_ADDR_GET_HEX(peer_addr, expected_key, int_value)); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); EXPECT_EQ(int_value, 0); @@ -1821,8 +1722,7 @@ TEST_F_WITH_FLAGS( string_value = "1"; get_string_return_value = &string_value; - EXPECT_TRUE( - DEVICE_IOT_CONFIG_ADDR_GET_HEX(peer_addr, expected_key, int_value)); + EXPECT_TRUE(DEVICE_IOT_CONFIG_ADDR_GET_HEX(peer_addr, expected_key, int_value)); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); EXPECT_EQ(int_value, 1); @@ -1836,8 +1736,7 @@ TEST_F_WITH_FLAGS( string_value = "-e"; get_string_return_value = &string_value; - EXPECT_TRUE( - DEVICE_IOT_CONFIG_ADDR_GET_HEX(peer_addr, expected_key, int_value)); + EXPECT_TRUE(DEVICE_IOT_CONFIG_ADDR_GET_HEX(peer_addr, expected_key, int_value)); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); EXPECT_EQ(int_value, -14); @@ -1851,8 +1750,7 @@ TEST_F_WITH_FLAGS( string_value = "-f"; get_string_return_value = &string_value; - EXPECT_TRUE( - DEVICE_IOT_CONFIG_ADDR_GET_HEX(peer_addr, expected_key, int_value)); + EXPECT_TRUE(DEVICE_IOT_CONFIG_ADDR_GET_HEX(peer_addr, expected_key, int_value)); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); EXPECT_EQ(int_value, -15); @@ -1866,8 +1764,7 @@ TEST_F_WITH_FLAGS( string_value = "0x7fffffff"; get_string_return_value = &string_value; - EXPECT_TRUE( - DEVICE_IOT_CONFIG_ADDR_GET_HEX(peer_addr, expected_key, int_value)); + EXPECT_TRUE(DEVICE_IOT_CONFIG_ADDR_GET_HEX(peer_addr, expected_key, int_value)); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); EXPECT_EQ(int_value, INT_MAX); @@ -1881,8 +1778,7 @@ TEST_F_WITH_FLAGS( string_value = "-0x80000000"; get_string_return_value = &string_value; - EXPECT_TRUE( - DEVICE_IOT_CONFIG_ADDR_GET_HEX(peer_addr, expected_key, int_value)); + EXPECT_TRUE(DEVICE_IOT_CONFIG_ADDR_GET_HEX(peer_addr, expected_key, int_value)); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); EXPECT_EQ(int_value, INT_MIN); @@ -1896,8 +1792,7 @@ TEST_F_WITH_FLAGS( string_value = "0xffffffff"; get_string_return_value = &string_value; - EXPECT_TRUE( - DEVICE_IOT_CONFIG_ADDR_GET_HEX(peer_addr, expected_key, int_value)); + EXPECT_TRUE(DEVICE_IOT_CONFIG_ADDR_GET_HEX(peer_addr, expected_key, int_value)); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); EXPECT_EQ(int_value, -1); @@ -1908,9 +1803,8 @@ TEST_F_WITH_FLAGS( test::mock::osi_config::config_get_string.body = {}; } -TEST_F_WITH_FLAGS( - DeviceIotConfigTest, test_device_iot_config_set_hex, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { +TEST_F_WITH_FLAGS(DeviceIotConfigTest, test_device_iot_config_set_hex, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { std::string actual_key, expected_key = "def"; std::string actual_section, expected_section = "00:00:00:00:00:00"; std::string string_return_value; @@ -1919,20 +1813,19 @@ TEST_F_WITH_FLAGS( int int_value, byte_num; test::mock::osi_config::config_get_string.body = - [&](const config_t& config, const std::string& section, - const std::string& key, const std::string* def_value) { - actual_section = section; - actual_key = key; - return get_string_return_value; - }; + [&](const config_t& config, const std::string& section, const std::string& key, + const std::string* def_value) { + actual_section = section; + actual_key = key; + return get_string_return_value; + }; test::mock::osi_config::config_set_string.body = - [&](config_t* config, const std::string& section, const std::string& key, - const std::string& value) { new_string_value = value; }; + [&](config_t* config, const std::string& section, const std::string& key, + const std::string& value) { new_string_value = value; }; - test::mock::osi_alarm::alarm_set.body = - [&](alarm_t* alarm, uint64_t interval_ms, alarm_callback_t cb, - void* data) {}; + test::mock::osi_alarm::alarm_set.body = [&](alarm_t* alarm, uint64_t interval_ms, + alarm_callback_t cb, void* data) {}; { reset_mock_function_count_map(); @@ -1942,8 +1835,7 @@ TEST_F_WITH_FLAGS( byte_num = 1; get_string_return_value = &string_return_value; - EXPECT_TRUE(device_iot_config_set_hex(expected_section, expected_key, - int_value, byte_num)); + EXPECT_TRUE(device_iot_config_set_hex(expected_section, expected_key, int_value, byte_num)); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); @@ -1959,8 +1851,7 @@ TEST_F_WITH_FLAGS( int_value = 1; byte_num = 2; get_string_return_value = &string_return_value; - EXPECT_TRUE(device_iot_config_set_hex(expected_section, expected_key, - int_value, byte_num)); + EXPECT_TRUE(device_iot_config_set_hex(expected_section, expected_key, int_value, byte_num)); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); @@ -1976,8 +1867,7 @@ TEST_F_WITH_FLAGS( int_value = 1; byte_num = 3; get_string_return_value = &string_return_value; - EXPECT_TRUE(device_iot_config_set_hex(expected_section, expected_key, - int_value, byte_num)); + EXPECT_TRUE(device_iot_config_set_hex(expected_section, expected_key, int_value, byte_num)); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); @@ -1994,8 +1884,7 @@ TEST_F_WITH_FLAGS( byte_num = 4; get_string_return_value = &string_return_value; - EXPECT_TRUE(device_iot_config_set_hex(expected_section, expected_key, - int_value, byte_num)); + EXPECT_TRUE(device_iot_config_set_hex(expected_section, expected_key, int_value, byte_num)); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); @@ -2012,8 +1901,7 @@ TEST_F_WITH_FLAGS( byte_num = 0; get_string_return_value = &string_return_value; - EXPECT_TRUE(device_iot_config_set_hex(expected_section, expected_key, - int_value, byte_num)); + EXPECT_TRUE(device_iot_config_set_hex(expected_section, expected_key, int_value, byte_num)); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); @@ -2030,8 +1918,7 @@ TEST_F_WITH_FLAGS( byte_num = 5; get_string_return_value = &string_return_value; - EXPECT_TRUE(device_iot_config_set_hex(expected_section, expected_key, - int_value, byte_num)); + EXPECT_TRUE(device_iot_config_set_hex(expected_section, expected_key, int_value, byte_num)); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); @@ -2049,8 +1936,7 @@ TEST_F_WITH_FLAGS( get_string_return_value = &string_return_value; std::string expected_string_value = "01"; - EXPECT_TRUE(device_iot_config_set_hex(expected_section, expected_key, - int_value, byte_num)); + EXPECT_TRUE(device_iot_config_set_hex(expected_section, expected_key, int_value, byte_num)); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); EXPECT_EQ(new_string_value, expected_string_value); @@ -2065,9 +1951,8 @@ TEST_F_WITH_FLAGS( test::mock::osi_alarm::alarm_set.body = {}; } -TEST_F_WITH_FLAGS( - DeviceIotConfigTest, test_device_iot_config_addr_set_hex, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { +TEST_F_WITH_FLAGS(DeviceIotConfigTest, test_device_iot_config_addr_set_hex, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { const RawAddress peer_addr{}; std::string actual_key, expected_key = "def"; std::string actual_section, expected_section = "00:00:00:00:00:00"; @@ -2079,20 +1964,19 @@ TEST_F_WITH_FLAGS( int byte_num = 1; test::mock::osi_config::config_get_string.body = - [&](const config_t& config, const std::string& section, - const std::string& key, const std::string* def_value) { - actual_section = section; - actual_key = key; - return get_string_return_value; - }; + [&](const config_t& config, const std::string& section, const std::string& key, + const std::string* def_value) { + actual_section = section; + actual_key = key; + return get_string_return_value; + }; test::mock::osi_config::config_set_string.body = - [&](config_t* config, const std::string& section, const std::string& key, - const std::string& value) { new_string_value = value; }; + [&](config_t* config, const std::string& section, const std::string& key, + const std::string& value) { new_string_value = value; }; - test::mock::osi_alarm::alarm_set.body = - [&](alarm_t* alarm, uint64_t interval_ms, alarm_callback_t cb, - void* data) {}; + test::mock::osi_alarm::alarm_set.body = [&](alarm_t* alarm, uint64_t interval_ms, + alarm_callback_t cb, void* data) {}; { reset_mock_function_count_map(); @@ -2102,8 +1986,7 @@ TEST_F_WITH_FLAGS( byte_num = 1; get_string_return_value = &string_return_value; - EXPECT_TRUE(DEVICE_IOT_CONFIG_ADDR_SET_HEX(peer_addr, expected_key, - int_value, byte_num)); + EXPECT_TRUE(DEVICE_IOT_CONFIG_ADDR_SET_HEX(peer_addr, expected_key, int_value, byte_num)); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); @@ -2120,8 +2003,7 @@ TEST_F_WITH_FLAGS( byte_num = 2; get_string_return_value = &string_return_value; - EXPECT_TRUE(DEVICE_IOT_CONFIG_ADDR_SET_HEX(peer_addr, expected_key, - int_value, byte_num)); + EXPECT_TRUE(DEVICE_IOT_CONFIG_ADDR_SET_HEX(peer_addr, expected_key, int_value, byte_num)); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); @@ -2138,8 +2020,7 @@ TEST_F_WITH_FLAGS( byte_num = 3; get_string_return_value = &string_return_value; - EXPECT_TRUE(DEVICE_IOT_CONFIG_ADDR_SET_HEX(peer_addr, expected_key, - int_value, byte_num)); + EXPECT_TRUE(DEVICE_IOT_CONFIG_ADDR_SET_HEX(peer_addr, expected_key, int_value, byte_num)); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); @@ -2156,8 +2037,7 @@ TEST_F_WITH_FLAGS( byte_num = 4; get_string_return_value = &string_return_value; - EXPECT_TRUE(DEVICE_IOT_CONFIG_ADDR_SET_HEX(peer_addr, expected_key, - int_value, byte_num)); + EXPECT_TRUE(DEVICE_IOT_CONFIG_ADDR_SET_HEX(peer_addr, expected_key, int_value, byte_num)); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); @@ -2174,8 +2054,7 @@ TEST_F_WITH_FLAGS( byte_num = 0; get_string_return_value = &string_return_value; - EXPECT_TRUE(DEVICE_IOT_CONFIG_ADDR_SET_HEX(peer_addr, expected_key, - int_value, byte_num)); + EXPECT_TRUE(DEVICE_IOT_CONFIG_ADDR_SET_HEX(peer_addr, expected_key, int_value, byte_num)); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); @@ -2192,8 +2071,7 @@ TEST_F_WITH_FLAGS( byte_num = 5; get_string_return_value = &string_return_value; - EXPECT_TRUE(DEVICE_IOT_CONFIG_ADDR_SET_HEX(peer_addr, expected_key, - int_value, byte_num)); + EXPECT_TRUE(DEVICE_IOT_CONFIG_ADDR_SET_HEX(peer_addr, expected_key, int_value, byte_num)); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); @@ -2211,8 +2089,7 @@ TEST_F_WITH_FLAGS( get_string_return_value = &string_return_value; std::string expected_string_value = "01"; - EXPECT_TRUE(DEVICE_IOT_CONFIG_ADDR_SET_HEX(peer_addr, expected_key, - int_value, byte_num)); + EXPECT_TRUE(DEVICE_IOT_CONFIG_ADDR_SET_HEX(peer_addr, expected_key, int_value, byte_num)); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); EXPECT_EQ(new_string_value, expected_string_value); @@ -2227,9 +2104,8 @@ TEST_F_WITH_FLAGS( test::mock::osi_alarm::alarm_set.body = {}; } -TEST_F_WITH_FLAGS( - DeviceIotConfigTest, test_device_iot_config_addr_set_hex_if_greater, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { +TEST_F_WITH_FLAGS(DeviceIotConfigTest, test_device_iot_config_addr_set_hex_if_greater, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { const RawAddress peer_addr{}; std::string actual_key, expected_key = "def"; std::string actual_section, expected_section = "00:00:00:00:00:00"; @@ -2241,20 +2117,19 @@ TEST_F_WITH_FLAGS( int byte_num = 1; test::mock::osi_config::config_get_string.body = - [&](const config_t& config, const std::string& section, - const std::string& key, const std::string* def_value) { - actual_section = section; - actual_key = key; - return get_string_return_value; - }; + [&](const config_t& config, const std::string& section, const std::string& key, + const std::string* def_value) { + actual_section = section; + actual_key = key; + return get_string_return_value; + }; test::mock::osi_config::config_set_string.body = - [&](config_t* config, const std::string& section, const std::string& key, - const std::string& value) { new_string_value = value; }; + [&](config_t* config, const std::string& section, const std::string& key, + const std::string& value) { new_string_value = value; }; - test::mock::osi_alarm::alarm_set.body = - [&](alarm_t* alarm, uint64_t interval_ms, alarm_callback_t cb, - void* data) {}; + test::mock::osi_alarm::alarm_set.body = [&](alarm_t* alarm, uint64_t interval_ms, + alarm_callback_t cb, void* data) {}; { reset_mock_function_count_map(); @@ -2264,8 +2139,8 @@ TEST_F_WITH_FLAGS( byte_num = 1; get_string_return_value = &string_return_value; - EXPECT_TRUE(DEVICE_IOT_CONFIG_ADDR_SET_HEX_IF_GREATER( - peer_addr, expected_key, int_value, byte_num)); + EXPECT_TRUE(DEVICE_IOT_CONFIG_ADDR_SET_HEX_IF_GREATER(peer_addr, expected_key, int_value, + byte_num)); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); @@ -2282,8 +2157,8 @@ TEST_F_WITH_FLAGS( byte_num = 1; get_string_return_value = &string_return_value; - EXPECT_TRUE(DEVICE_IOT_CONFIG_ADDR_SET_HEX_IF_GREATER( - peer_addr, expected_key, int_value, byte_num)); + EXPECT_TRUE(DEVICE_IOT_CONFIG_ADDR_SET_HEX_IF_GREATER(peer_addr, expected_key, int_value, + byte_num)); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); @@ -2300,8 +2175,8 @@ TEST_F_WITH_FLAGS( byte_num = 1; get_string_return_value = &string_return_value; - EXPECT_TRUE(DEVICE_IOT_CONFIG_ADDR_SET_HEX_IF_GREATER( - peer_addr, expected_key, int_value, byte_num)); + EXPECT_TRUE(DEVICE_IOT_CONFIG_ADDR_SET_HEX_IF_GREATER(peer_addr, expected_key, int_value, + byte_num)); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); @@ -2315,23 +2190,21 @@ TEST_F_WITH_FLAGS( test::mock::osi_alarm::alarm_set.body = {}; } -TEST_F_WITH_FLAGS( - DeviceIotConfigTest, test_device_iot_config_get_str, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { - std::string actual_section, actual_key, expected_section = "abc", - expected_key = "def"; +TEST_F_WITH_FLAGS(DeviceIotConfigTest, test_device_iot_config_get_str, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { + std::string actual_section, actual_key, expected_section = "abc", expected_key = "def"; std::string actual_value_str; const std::string* actual_def_value = NULL; const std::string* return_value = NULL; test::mock::osi_config::config_get_string.body = - [&](const config_t& config, const std::string& section, - const std::string& key, const std::string* def_value) { - actual_section = section; - actual_key = key; - actual_def_value = def_value; - return return_value; - }; + [&](const config_t& config, const std::string& section, const std::string& key, + const std::string* def_value) { + actual_section = section; + actual_key = key; + actual_def_value = def_value; + return return_value; + }; { reset_mock_function_count_map(); @@ -2339,8 +2212,8 @@ TEST_F_WITH_FLAGS( int initial_size_bytes = 30; int size_bytes = initial_size_bytes; char get_value_str[size_bytes]; - EXPECT_FALSE(device_iot_config_get_str(expected_section, expected_key, - get_value_str, &size_bytes)); + EXPECT_FALSE( + device_iot_config_get_str(expected_section, expected_key, get_value_str, &size_bytes)); EXPECT_TRUE(actual_def_value == NULL); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); @@ -2358,14 +2231,13 @@ TEST_F_WITH_FLAGS( actual_value_str = "abc"; return_value = &actual_value_str; - EXPECT_TRUE(device_iot_config_get_str(expected_section, expected_key, - get_value_str, &size_bytes)); + EXPECT_TRUE( + device_iot_config_get_str(expected_section, expected_key, get_value_str, &size_bytes)); EXPECT_TRUE(actual_def_value == NULL); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); EXPECT_EQ(size_bytes, (int)actual_value_str.length() + 1); - EXPECT_TRUE(strncmp(get_value_str, actual_value_str.c_str(), size_bytes) == - 0); + EXPECT_TRUE(strncmp(get_value_str, actual_value_str.c_str(), size_bytes) == 0); EXPECT_EQ(get_func_call_count("config_get_string"), 1); } @@ -2373,9 +2245,8 @@ TEST_F_WITH_FLAGS( test::mock::osi_config::config_get_string.body = {}; } -TEST_F_WITH_FLAGS( - DeviceIotConfigTest, test_device_iot_config_set_str, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { +TEST_F_WITH_FLAGS(DeviceIotConfigTest, test_device_iot_config_set_str, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { std::string actual_key, expected_key = "def"; std::string actual_section, expected_section = "00:00:00:00:00:00"; std::string input_value; @@ -2386,20 +2257,19 @@ TEST_F_WITH_FLAGS( std::string str_value; test::mock::osi_config::config_get_string.body = - [&](const config_t& config, const std::string& section, - const std::string& key, const std::string* def_value) { - actual_section = section; - actual_key = key; - return get_string_return_value; - }; + [&](const config_t& config, const std::string& section, const std::string& key, + const std::string* def_value) { + actual_section = section; + actual_key = key; + return get_string_return_value; + }; test::mock::osi_config::config_set_string.body = - [&](config_t* config, const std::string& section, const std::string& key, - const std::string& value) { new_string_value = value; }; + [&](config_t* config, const std::string& section, const std::string& key, + const std::string& value) { new_string_value = value; }; - test::mock::osi_alarm::alarm_set.body = - [&](alarm_t* alarm, uint64_t interval_ms, alarm_callback_t cb, - void* data) {}; + test::mock::osi_alarm::alarm_set.body = [&](alarm_t* alarm, uint64_t interval_ms, + alarm_callback_t cb, void* data) {}; { reset_mock_function_count_map(); @@ -2408,8 +2278,7 @@ TEST_F_WITH_FLAGS( get_string_return_value = &string_return_value; input_value = "01"; - EXPECT_TRUE( - device_iot_config_set_str(expected_section, expected_key, input_value)); + EXPECT_TRUE(device_iot_config_set_str(expected_section, expected_key, input_value)); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); @@ -2425,8 +2294,7 @@ TEST_F_WITH_FLAGS( get_string_return_value = &string_return_value; input_value = "01"; - EXPECT_TRUE( - device_iot_config_set_str(expected_section, expected_key, input_value)); + EXPECT_TRUE(device_iot_config_set_str(expected_section, expected_key, input_value)); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); EXPECT_EQ(new_string_value, input_value); @@ -2441,9 +2309,8 @@ TEST_F_WITH_FLAGS( test::mock::osi_alarm::alarm_set.body = {}; } -TEST_F_WITH_FLAGS( - DeviceIotConfigTest, test_device_iot_config_addr_set_str, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { +TEST_F_WITH_FLAGS(DeviceIotConfigTest, test_device_iot_config_addr_set_str, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { const RawAddress peer_addr{}; std::string actual_key, expected_key = "def"; std::string actual_section, expected_section = "00:00:00:00:00:00"; @@ -2455,20 +2322,19 @@ TEST_F_WITH_FLAGS( std::string str_value; test::mock::osi_config::config_get_string.body = - [&](const config_t& config, const std::string& section, - const std::string& key, const std::string* def_value) { - actual_section = section; - actual_key = key; - return get_string_return_value; - }; + [&](const config_t& config, const std::string& section, const std::string& key, + const std::string* def_value) { + actual_section = section; + actual_key = key; + return get_string_return_value; + }; test::mock::osi_config::config_set_string.body = - [&](config_t* config, const std::string& section, const std::string& key, - const std::string& value) { new_string_value = value; }; + [&](config_t* config, const std::string& section, const std::string& key, + const std::string& value) { new_string_value = value; }; - test::mock::osi_alarm::alarm_set.body = - [&](alarm_t* alarm, uint64_t interval_ms, alarm_callback_t cb, - void* data) {}; + test::mock::osi_alarm::alarm_set.body = [&](alarm_t* alarm, uint64_t interval_ms, + alarm_callback_t cb, void* data) {}; { reset_mock_function_count_map(); @@ -2477,8 +2343,7 @@ TEST_F_WITH_FLAGS( get_string_return_value = &string_return_value; input_value = "01"; - EXPECT_TRUE( - DEVICE_IOT_CONFIG_ADDR_SET_STR(peer_addr, expected_key, input_value)); + EXPECT_TRUE(DEVICE_IOT_CONFIG_ADDR_SET_STR(peer_addr, expected_key, input_value)); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); @@ -2494,8 +2359,7 @@ TEST_F_WITH_FLAGS( get_string_return_value = &string_return_value; input_value = "01"; - EXPECT_TRUE( - DEVICE_IOT_CONFIG_ADDR_SET_STR(peer_addr, expected_key, input_value)); + EXPECT_TRUE(DEVICE_IOT_CONFIG_ADDR_SET_STR(peer_addr, expected_key, input_value)); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); EXPECT_EQ(new_string_value, input_value); @@ -2510,23 +2374,21 @@ TEST_F_WITH_FLAGS( test::mock::osi_alarm::alarm_set.body = {}; } -TEST_F_WITH_FLAGS( - DeviceIotConfigTest, test_device_iot_config_get_bin, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { - std::string actual_section, actual_key, expected_section = "abc", - expected_key = "def"; +TEST_F_WITH_FLAGS(DeviceIotConfigTest, test_device_iot_config_get_bin, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { + std::string actual_section, actual_key, expected_section = "abc", expected_key = "def"; std::string actual_value_str; const std::string* actual_def_value = NULL; const std::string* return_value = NULL; test::mock::osi_config::config_get_string.body = - [&](const config_t& config, const std::string& section, - const std::string& key, const std::string* def_value) { - actual_section = section; - actual_key = key; - actual_def_value = def_value; - return return_value; - }; + [&](const config_t& config, const std::string& section, const std::string& key, + const std::string* def_value) { + actual_section = section; + actual_key = key; + actual_def_value = def_value; + return return_value; + }; { reset_mock_function_count_map(); @@ -2535,8 +2397,7 @@ TEST_F_WITH_FLAGS( size_t size_bytes = initial_size_bytes; uint8_t value[size_bytes]; - EXPECT_FALSE(device_iot_config_get_bin(expected_section, expected_key, - value, &size_bytes)); + EXPECT_FALSE(device_iot_config_get_bin(expected_section, expected_key, value, &size_bytes)); EXPECT_TRUE(actual_def_value == NULL); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); @@ -2554,8 +2415,7 @@ TEST_F_WITH_FLAGS( actual_value_str = "abc"; return_value = &actual_value_str; - EXPECT_FALSE(device_iot_config_get_bin(expected_section, expected_key, - value, &size_bytes)); + EXPECT_FALSE(device_iot_config_get_bin(expected_section, expected_key, value, &size_bytes)); EXPECT_TRUE(actual_def_value == NULL); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); @@ -2573,8 +2433,7 @@ TEST_F_WITH_FLAGS( actual_value_str = "aabbccdd"; return_value = &actual_value_str; - EXPECT_FALSE(device_iot_config_get_bin(expected_section, expected_key, - value, &size_bytes)); + EXPECT_FALSE(device_iot_config_get_bin(expected_section, expected_key, value, &size_bytes)); EXPECT_TRUE(actual_def_value == NULL); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); @@ -2592,8 +2451,7 @@ TEST_F_WITH_FLAGS( actual_value_str = "abcdefgh"; return_value = &actual_value_str; - EXPECT_FALSE(device_iot_config_get_bin(expected_section, expected_key, - value, &size_bytes)); + EXPECT_FALSE(device_iot_config_get_bin(expected_section, expected_key, value, &size_bytes)); EXPECT_TRUE(actual_def_value == NULL); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); @@ -2611,8 +2469,7 @@ TEST_F_WITH_FLAGS( actual_value_str = "abcdef"; return_value = &actual_value_str; - EXPECT_TRUE(device_iot_config_get_bin(expected_section, expected_key, value, - &size_bytes)); + EXPECT_TRUE(device_iot_config_get_bin(expected_section, expected_key, value, &size_bytes)); EXPECT_TRUE(actual_def_value == NULL); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); @@ -2624,28 +2481,25 @@ TEST_F_WITH_FLAGS( test::mock::osi_config::config_get_string.body = {}; } -TEST_F_WITH_FLAGS( - DeviceIotConfigTest, test_device_iot_config_get_bin_length, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { - std::string actual_section, actual_key, expected_section = "abc", - expected_key = "def"; +TEST_F_WITH_FLAGS(DeviceIotConfigTest, test_device_iot_config_get_bin_length, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { + std::string actual_section, actual_key, expected_section = "abc", expected_key = "def"; std::string actual_value_str; const std::string* actual_def_value = NULL; const std::string* return_value = NULL; test::mock::osi_config::config_get_string.body = - [&](const config_t& config, const std::string& section, - const std::string& key, const std::string* def_value) { - actual_section = section; - actual_key = key; - actual_def_value = def_value; - return return_value; - }; + [&](const config_t& config, const std::string& section, const std::string& key, + const std::string* def_value) { + actual_section = section; + actual_key = key; + actual_def_value = def_value; + return return_value; + }; { reset_mock_function_count_map(); - EXPECT_EQ(device_iot_config_get_bin_length(expected_section, expected_key), - 0u); + EXPECT_EQ(device_iot_config_get_bin_length(expected_section, expected_key), 0u); EXPECT_TRUE(actual_def_value == NULL); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); @@ -2657,8 +2511,7 @@ TEST_F_WITH_FLAGS( actual_value_str = "abc"; return_value = &actual_value_str; - EXPECT_EQ(device_iot_config_get_bin_length(expected_section, expected_key), - 0u); + EXPECT_EQ(device_iot_config_get_bin_length(expected_section, expected_key), 0u); EXPECT_TRUE(actual_def_value == NULL); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); @@ -2670,8 +2523,7 @@ TEST_F_WITH_FLAGS( actual_value_str = "aabbccdd"; return_value = &actual_value_str; - EXPECT_EQ(device_iot_config_get_bin_length(expected_section, expected_key), - 4u); + EXPECT_EQ(device_iot_config_get_bin_length(expected_section, expected_key), 4u); EXPECT_TRUE(actual_def_value == NULL); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); @@ -2684,8 +2536,7 @@ TEST_F_WITH_FLAGS( actual_value_str = "abcdefgh"; return_value = &actual_value_str; - EXPECT_EQ(device_iot_config_get_bin_length(expected_section, expected_key), - 4u); + EXPECT_EQ(device_iot_config_get_bin_length(expected_section, expected_key), 4u); EXPECT_TRUE(actual_def_value == NULL); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); @@ -2697,8 +2548,7 @@ TEST_F_WITH_FLAGS( actual_value_str = "abcdef"; return_value = &actual_value_str; - EXPECT_EQ(device_iot_config_get_bin_length(expected_section, expected_key), - 3u); + EXPECT_EQ(device_iot_config_get_bin_length(expected_section, expected_key), 3u); EXPECT_TRUE(actual_def_value == NULL); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); @@ -2708,9 +2558,8 @@ TEST_F_WITH_FLAGS( test::mock::osi_config::config_get_string.body = {}; } -TEST_F_WITH_FLAGS( - DeviceIotConfigTest, test_device_iot_config_set_bin, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { +TEST_F_WITH_FLAGS(DeviceIotConfigTest, test_device_iot_config_set_bin, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { std::string actual_key, expected_key = "def"; std::string actual_section, expected_section = "00:00:00:00:00:00"; std::string string_return_value; @@ -2720,24 +2569,21 @@ TEST_F_WITH_FLAGS( std::string str_value; test::mock::osi_config::config_get_string.body = - [&](const config_t& config, const std::string& section, - const std::string& key, const std::string* def_value) { - actual_section = section; - actual_key = key; - return get_string_return_value; - }; + [&](const config_t& config, const std::string& section, const std::string& key, + const std::string* def_value) { + actual_section = section; + actual_key = key; + return get_string_return_value; + }; test::mock::osi_config::config_set_string.body = - [&](config_t* config, const std::string& section, const std::string& key, - const std::string& value) { new_string_value = value; }; + [&](config_t* config, const std::string& section, const std::string& key, + const std::string& value) { new_string_value = value; }; - test::mock::osi_alarm::alarm_set.body = - [&](alarm_t* alarm, uint64_t interval_ms, alarm_callback_t cb, - void* data) {}; + test::mock::osi_alarm::alarm_set.body = [&](alarm_t* alarm, uint64_t interval_ms, + alarm_callback_t cb, void* data) {}; - test::mock::osi_allocator::osi_calloc.body = [&](size_t size) { - return new char[size]; - }; + test::mock::osi_allocator::osi_calloc.body = [&](size_t size) { return new char[size]; }; { reset_mock_function_count_map(); @@ -2747,8 +2593,7 @@ TEST_F_WITH_FLAGS( uint8_t input_value[] = {0x01, 0x02, 0x03}; size_t length = sizeof(input_value); - EXPECT_TRUE(device_iot_config_set_bin(expected_section, expected_key, - input_value, length)); + EXPECT_TRUE(device_iot_config_set_bin(expected_section, expected_key, input_value, length)); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); @@ -2767,8 +2612,7 @@ TEST_F_WITH_FLAGS( uint8_t input_value[] = {0x01, 0x02, 0x03}; size_t length = 0; - EXPECT_TRUE(device_iot_config_set_bin(expected_section, expected_key, - input_value, length)); + EXPECT_TRUE(device_iot_config_set_bin(expected_section, expected_key, input_value, length)); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); @@ -2787,8 +2631,7 @@ TEST_F_WITH_FLAGS( uint8_t input_value[] = {0x01, 0x02, 0x03}; size_t length = sizeof(input_value); - EXPECT_TRUE(device_iot_config_set_bin(expected_section, expected_key, - input_value, length)); + EXPECT_TRUE(device_iot_config_set_bin(expected_section, expected_key, input_value, length)); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); @@ -2801,15 +2644,12 @@ TEST_F_WITH_FLAGS( { reset_mock_function_count_map(); - test::mock::osi_allocator::osi_calloc.body = [&](size_t size) { - return nullptr; - }; + test::mock::osi_allocator::osi_calloc.body = [&](size_t size) { return nullptr; }; uint8_t input_value[] = {0x01, 0x02, 0x03}; size_t length = sizeof(input_value); - EXPECT_FALSE(device_iot_config_set_bin(expected_section, expected_key, - input_value, length)); + EXPECT_FALSE(device_iot_config_set_bin(expected_section, expected_key, input_value, length)); EXPECT_EQ(get_func_call_count("osi_calloc"), 1); EXPECT_EQ(get_func_call_count("config_get_string"), 0); @@ -2825,9 +2665,8 @@ TEST_F_WITH_FLAGS( test::mock::osi_alarm::alarm_set.body = {}; } -TEST_F_WITH_FLAGS( - DeviceIotConfigTest, test_device_iot_config_addr_set_bin, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { +TEST_F_WITH_FLAGS(DeviceIotConfigTest, test_device_iot_config_addr_set_bin, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { const RawAddress peer_addr{}; std::string actual_key, expected_key = "def"; std::string actual_section, expected_section = "00:00:00:00:00:00"; @@ -2838,24 +2677,21 @@ TEST_F_WITH_FLAGS( std::string str_value; test::mock::osi_config::config_get_string.body = - [&](const config_t& config, const std::string& section, - const std::string& key, const std::string* def_value) { - actual_section = section; - actual_key = key; - return get_string_return_value; - }; + [&](const config_t& config, const std::string& section, const std::string& key, + const std::string* def_value) { + actual_section = section; + actual_key = key; + return get_string_return_value; + }; test::mock::osi_config::config_set_string.body = - [&](config_t* config, const std::string& section, const std::string& key, - const std::string& value) { new_string_value = value; }; + [&](config_t* config, const std::string& section, const std::string& key, + const std::string& value) { new_string_value = value; }; - test::mock::osi_alarm::alarm_set.body = - [&](alarm_t* alarm, uint64_t interval_ms, alarm_callback_t cb, - void* data) {}; + test::mock::osi_alarm::alarm_set.body = [&](alarm_t* alarm, uint64_t interval_ms, + alarm_callback_t cb, void* data) {}; - test::mock::osi_allocator::osi_calloc.body = [&](size_t size) { - return new char[size]; - }; + test::mock::osi_allocator::osi_calloc.body = [&](size_t size) { return new char[size]; }; { reset_mock_function_count_map(); @@ -2865,8 +2701,7 @@ TEST_F_WITH_FLAGS( uint8_t input_value[] = {0x01, 0x02, 0x03}; size_t length = sizeof(input_value); - EXPECT_TRUE(DEVICE_IOT_CONFIG_ADDR_SET_BIN(peer_addr, expected_key, - input_value, length)); + EXPECT_TRUE(DEVICE_IOT_CONFIG_ADDR_SET_BIN(peer_addr, expected_key, input_value, length)); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); @@ -2885,8 +2720,7 @@ TEST_F_WITH_FLAGS( uint8_t input_value[] = {0x01, 0x02, 0x03}; size_t length = 0; - EXPECT_TRUE(DEVICE_IOT_CONFIG_ADDR_SET_BIN(peer_addr, expected_key, - input_value, length)); + EXPECT_TRUE(DEVICE_IOT_CONFIG_ADDR_SET_BIN(peer_addr, expected_key, input_value, length)); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); @@ -2905,8 +2739,7 @@ TEST_F_WITH_FLAGS( uint8_t input_value[] = {0x01, 0x02, 0x03}; size_t length = sizeof(input_value); - EXPECT_TRUE(DEVICE_IOT_CONFIG_ADDR_SET_BIN(peer_addr, expected_key, - input_value, length)); + EXPECT_TRUE(DEVICE_IOT_CONFIG_ADDR_SET_BIN(peer_addr, expected_key, input_value, length)); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); @@ -2919,15 +2752,12 @@ TEST_F_WITH_FLAGS( { reset_mock_function_count_map(); - test::mock::osi_allocator::osi_calloc.body = [&](size_t size) { - return nullptr; - }; + test::mock::osi_allocator::osi_calloc.body = [&](size_t size) { return nullptr; }; uint8_t input_value[] = {0x01, 0x02, 0x03}; size_t length = sizeof(input_value); - EXPECT_FALSE(DEVICE_IOT_CONFIG_ADDR_SET_BIN(peer_addr, expected_key, - input_value, length)); + EXPECT_FALSE(DEVICE_IOT_CONFIG_ADDR_SET_BIN(peer_addr, expected_key, input_value, length)); EXPECT_EQ(get_func_call_count("osi_calloc"), 1); EXPECT_EQ(get_func_call_count("config_get_string"), 0); @@ -2943,28 +2773,25 @@ TEST_F_WITH_FLAGS( test::mock::osi_alarm::alarm_set.body = {}; } -TEST_F_WITH_FLAGS( - DeviceIotConfigTest, test_device_iot_config_remove, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { +TEST_F_WITH_FLAGS(DeviceIotConfigTest, test_device_iot_config_remove, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { std::string actual_key, expected_key = "def"; std::string actual_section, expected_section = "00:00:00:00:00:00"; bool return_value; - test::mock::osi_config::config_remove_key.body = - [&](config_t* config, const std::string& section, - const std::string& key) { - actual_section = section; - actual_key = key; - return return_value; - }; + test::mock::osi_config::config_remove_key.body = [&](config_t* config, const std::string& section, + const std::string& key) { + actual_section = section; + actual_key = key; + return return_value; + }; { reset_mock_function_count_map(); return_value = false; - EXPECT_EQ(device_iot_config_remove(expected_section, expected_key), - return_value); + EXPECT_EQ(device_iot_config_remove(expected_section, expected_key), return_value); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); @@ -2976,8 +2803,7 @@ TEST_F_WITH_FLAGS( return_value = true; - EXPECT_EQ(device_iot_config_remove(expected_section, expected_key), - return_value); + EXPECT_EQ(device_iot_config_remove(expected_section, expected_key), return_value); EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); @@ -2987,9 +2813,8 @@ TEST_F_WITH_FLAGS( test::mock::osi_config::config_remove_key.body = {}; } -TEST_F_WITH_FLAGS( - DeviceIotConfigTest, test_device_iot_config_save_async, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { +TEST_F_WITH_FLAGS(DeviceIotConfigTest, test_device_iot_config_save_async, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { { reset_mock_function_count_map(); @@ -2999,13 +2824,13 @@ TEST_F_WITH_FLAGS( } } -TEST_F_WITH_FLAGS( - DeviceIotConfigTest, test_device_iot_config_flush, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { +TEST_F_WITH_FLAGS(DeviceIotConfigTest, test_device_iot_config_flush, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { bool return_value; - test::mock::osi_alarm::alarm_is_scheduled.body = - [&](const alarm_t* alarm) -> bool { return return_value; }; + test::mock::osi_alarm::alarm_is_scheduled.body = [&](const alarm_t* alarm) -> bool { + return return_value; + }; { reset_mock_function_count_map(); @@ -3036,9 +2861,8 @@ TEST_F_WITH_FLAGS( test::mock::osi_alarm::alarm_is_scheduled.body = {}; } -TEST_F_WITH_FLAGS( - DeviceIotConfigTest, test_device_iot_config_clear, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { +TEST_F_WITH_FLAGS(DeviceIotConfigTest, test_device_iot_config_clear, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { config_t* config_new_empty_return_value; bool config_save_return_value; @@ -3048,8 +2872,8 @@ TEST_F_WITH_FLAGS( return std::unique_ptr(config_new_empty_return_value); }; - test::mock::osi_config::config_save.body = - [&](const config_t& config, const std::string& filename) -> bool { + test::mock::osi_config::config_save.body = [&](const config_t& config, + const std::string& filename) -> bool { return config_save_return_value; }; @@ -3096,9 +2920,8 @@ TEST_F_WITH_FLAGS( test::mock::osi_config::config_save.body = {}; } -TEST_F_WITH_FLAGS( - DeviceIotConfigTest, test_device_iot_config_timer_save_cb, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { +TEST_F_WITH_FLAGS(DeviceIotConfigTest, test_device_iot_config_timer_save_cb, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { { reset_mock_function_count_map(); @@ -3108,9 +2931,8 @@ TEST_F_WITH_FLAGS( } } -TEST_F_WITH_FLAGS( - DeviceIotConfigTest, test_device_iot_config_set_modified_time, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { +TEST_F_WITH_FLAGS(DeviceIotConfigTest, test_device_iot_config_set_modified_time, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { { reset_mock_function_count_map(); @@ -3120,9 +2942,8 @@ TEST_F_WITH_FLAGS( } } -TEST_F_WITH_FLAGS( - DeviceIotConfigTest, test_device_iot_config_get_device_num, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { +TEST_F_WITH_FLAGS(DeviceIotConfigTest, test_device_iot_config_get_device_num, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { { config_t config; auto num = device_iot_config_get_device_num(config); @@ -3144,9 +2965,8 @@ TEST_F_WITH_FLAGS( } } -TEST_F_WITH_FLAGS( - DeviceIotConfigTest, test_device_iot_config_restrict_device_num, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { +TEST_F_WITH_FLAGS(DeviceIotConfigTest, test_device_iot_config_restrict_device_num, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { section_t section = {.name = "00:01:02:03:04:05"}; { @@ -3197,16 +3017,15 @@ TEST_F_WITH_FLAGS( } } -TEST_F_WITH_FLAGS( - DeviceIotConfigTest, test_device_iot_config_compare_key, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { +TEST_F_WITH_FLAGS(DeviceIotConfigTest, test_device_iot_config_compare_key, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { { entry_t first = - { - .key = "NotProfile/a", - }, + { + .key = "NotProfile/a", + }, second = { - .key = "NotProfile/b", + .key = "NotProfile/b", }; EXPECT_TRUE(device_iot_config_compare_key(first, second)); @@ -3214,11 +3033,11 @@ TEST_F_WITH_FLAGS( { entry_t first = - { - .key = "Profile/a", - }, + { + .key = "Profile/a", + }, second = { - .key = "Profile/b", + .key = "Profile/b", }; EXPECT_TRUE(device_iot_config_compare_key(first, second)); @@ -3226,11 +3045,11 @@ TEST_F_WITH_FLAGS( { entry_t first = - { - .key = "Profile/b", - }, + { + .key = "Profile/b", + }, second = { - .key = "Profile/a", + .key = "Profile/a", }; EXPECT_FALSE(device_iot_config_compare_key(first, second)); @@ -3238,11 +3057,11 @@ TEST_F_WITH_FLAGS( { entry_t first = - { - .key = "Profile/b", - }, + { + .key = "Profile/b", + }, second = { - .key = "NotProfile/a", + .key = "NotProfile/a", }; EXPECT_FALSE(device_iot_config_compare_key(first, second)); @@ -3250,24 +3069,21 @@ TEST_F_WITH_FLAGS( { entry_t first = - { - .key = "NotProfile/b", - }, + { + .key = "NotProfile/b", + }, second = { - .key = "Profile/a", + .key = "Profile/a", }; EXPECT_TRUE(device_iot_config_compare_key(first, second)); } } -TEST_F_WITH_FLAGS( - DeviceIotConfigTest, test_device_iot_config_write, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { +TEST_F_WITH_FLAGS(DeviceIotConfigTest, test_device_iot_config_write, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { test::mock::osi_config::config_save.body = - [&](const config_t& config, const std::string& filename) -> bool { - return true; - }; + [&](const config_t& config, const std::string& filename) -> bool { return true; }; { reset_mock_function_count_map(); @@ -3291,17 +3107,15 @@ TEST_F_WITH_FLAGS( test::mock::osi_config::config_save.body = {}; } -TEST_F_WITH_FLAGS( - DeviceIotConfigTest, test_device_debug_iot_config_dump, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { +TEST_F_WITH_FLAGS(DeviceIotConfigTest, test_device_debug_iot_config_dump, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { { errno = 0; int fd = -1; const int BUF_SIZE = 100; char buf[BUF_SIZE] = {0}; - fd = open(IOT_CONFIG_FILE_PATH, O_CREAT | O_RDWR | O_TRUNC | O_CLOEXEC, - S_IRUSR | S_IWUSR); + fd = open(IOT_CONFIG_FILE_PATH, O_CREAT | O_RDWR | O_TRUNC | O_CLOEXEC, S_IRUSR | S_IWUSR); EXPECT_TRUE(fd > 0); EXPECT_EQ(errno, 0); @@ -3323,12 +3137,11 @@ TEST_F_WITH_FLAGS( } } -TEST_F_WITH_FLAGS( - DeviceIotConfigTest, test_device_iot_config_is_factory_reset, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { +TEST_F_WITH_FLAGS(DeviceIotConfigTest, test_device_iot_config_is_factory_reset, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { bool return_value; test::mock::osi_properties::osi_property_get_bool.body = - [&](const char* key, bool default_value) -> bool { return return_value; }; + [&](const char* key, bool default_value) -> bool { return return_value; }; { return_value = false; @@ -3341,21 +3154,19 @@ TEST_F_WITH_FLAGS( } } -TEST_F_WITH_FLAGS( - DeviceIotConfigTest, test_device_debug_iot_config_delete_files, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { +TEST_F_WITH_FLAGS(DeviceIotConfigTest, test_device_debug_iot_config_delete_files, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { { errno = 0; int file_fd = -1; int backup_fd = -1; - file_fd = open(IOT_CONFIG_FILE_PATH, O_CREAT | O_RDWR | O_TRUNC | O_CLOEXEC, - S_IRUSR | S_IWUSR); + file_fd = open(IOT_CONFIG_FILE_PATH, O_CREAT | O_RDWR | O_TRUNC | O_CLOEXEC, S_IRUSR | S_IWUSR); EXPECT_TRUE(file_fd > 0); EXPECT_EQ(errno, 0); - backup_fd = open(IOT_CONFIG_BACKUP_PATH, - O_CREAT | O_RDWR | O_TRUNC | O_CLOEXEC, S_IRUSR | S_IWUSR); + backup_fd = + open(IOT_CONFIG_BACKUP_PATH, O_CREAT | O_RDWR | O_TRUNC | O_CLOEXEC, S_IRUSR | S_IWUSR); EXPECT_TRUE(backup_fd > 0); EXPECT_EQ(errno, 0); @@ -3374,50 +3185,49 @@ TEST_F_WITH_FLAGS( } } class DeviceIotConfigDisabledTest : public testing::Test { - protected: +protected: void SetUp() override { test::mock::osi_alarm::alarm_new.body = [&](const char* name) -> alarm_t* { return &placeholder_alarm; }; - test::mock::osi_alarm::alarm_set.body = - [&](alarm_t* alarm, uint64_t interval_ms, alarm_callback_t cb, - void* data) { return; }; + test::mock::osi_alarm::alarm_set.body = [&](alarm_t* alarm, uint64_t interval_ms, + alarm_callback_t cb, void* data) { return; }; test::mock::osi_alarm::alarm_free.body = [](alarm_t* alarm) {}; - test::mock::osi_alarm::alarm_is_scheduled.body = - [&](const alarm_t* alarm) -> bool { return false; }; + test::mock::osi_alarm::alarm_is_scheduled.body = [&](const alarm_t* alarm) -> bool { + return false; + }; - test::mock::osi_future::future_new_immediate.body = - [&](void* value) -> future_t* { return &placeholder_future; }; + test::mock::osi_future::future_new_immediate.body = [&](void* value) -> future_t* { + return &placeholder_future; + }; - test::mock::osi_config::config_new_empty.body = - [&]() -> std::unique_ptr { + test::mock::osi_config::config_new_empty.body = [&]() -> std::unique_ptr { return std::make_unique(); }; test::mock::osi_config::config_new.body = - [&](const char* filename) -> std::unique_ptr { + [&](const char* filename) -> std::unique_ptr { return std::make_unique(); }; test::mock::osi_config::config_get_int.body = - [&](const config_t& config, const std::string& section, - const std::string& key, int def_value) { return def_value; }; + [&](const config_t& config, const std::string& section, const std::string& key, + int def_value) { return def_value; }; - test::mock::osi_config::config_set_int.body = - [&](config_t* config, const std::string& section, - const std::string& key, int value) { return; }; + test::mock::osi_config::config_set_int.body = [&](config_t* config, const std::string& section, + const std::string& key, + int value) { return; }; test::mock::osi_config::config_get_string.body = - [&](const config_t& config, const std::string& section, - const std::string& key, - const std::string* def_value) { return def_value; }; + [&](const config_t& config, const std::string& section, const std::string& key, + const std::string* def_value) { return def_value; }; test::mock::osi_config::config_set_string.body = - [&](config_t* config, const std::string& section, - const std::string& key, const std::string& value) { return; }; + [&](config_t* config, const std::string& section, const std::string& key, + const std::string& value) { return; }; test::mock::osi_allocator::osi_free.body = [&](void* ptr) {}; @@ -3444,9 +3254,8 @@ class DeviceIotConfigDisabledTest : public testing::Test { } }; -TEST_F_WITH_FLAGS( - DeviceIotConfigDisabledTest, test_device_iot_config_disabled, - REQUIRES_FLAGS_DISABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { +TEST_F_WITH_FLAGS(DeviceIotConfigDisabledTest, test_device_iot_config_disabled, + REQUIRES_FLAGS_DISABLED(ACONFIG_FLAG(TEST_BT, device_iot_config_logging))) { const RawAddress peer_addr{}; std::string section, key, value_str; int value_int{}; @@ -3538,8 +3347,7 @@ TEST_F_WITH_FLAGS( { reset_mock_function_count_map(); - EXPECT_FALSE( - DEVICE_IOT_CONFIG_ADDR_SET_HEX_IF_GREATER(peer_addr, key, 0, 0)); + EXPECT_FALSE(DEVICE_IOT_CONFIG_ADDR_SET_HEX_IF_GREATER(peer_addr, key, 0, 0)); EXPECT_EQ(get_func_call_size(), 0); } diff --git a/system/device/test/interop_test.cc b/system/device/test/interop_test.cc index 3ad3db2ce96..e0c44b1cb71 100644 --- a/system/device/test/interop_test.cc +++ b/system/device/test/interop_test.cc @@ -32,12 +32,11 @@ #include static const std::filesystem::path kStaticConfigFileConfigFile = - std::filesystem::temp_directory_path() / "interop_database.conf"; + std::filesystem::temp_directory_path() / "interop_database.conf"; -static const char* INTEROP_STATIC_FILE_PATH = - kStaticConfigFileConfigFile.c_str(); +static const char* INTEROP_STATIC_FILE_PATH = kStaticConfigFileConfigFile.c_str(); static const char INTEROP_STATIC_FILE_CONTENT[] = - " \n\ + " \n\ #Disable secure connections \n\ #This is for pre BT 4.1/2 devices that do not handle secure mode very well. \n\ [INTEROP_DISABLE_LE_SECURE_CONNECTIONS] \n\ @@ -68,7 +67,7 @@ A0:E9:DB = Address_Based Motorola Keyboard KZ500 = Name_Based \n\ 0x22b8-0x093D = Vndr_Prdt_Based \n\ \n\ -# some remote hid devices cannot work properly as they laod special hid usb driver in kernel,\n\ +# some remote hid devices cannot work properly as they load special hid usb driver in kernel,\n\ # so modify their vid/pid so that generic hid driver are loaded. \n\ [INTEROP_CHANGE_HID_VID_PID] \n\ CK87BT = Name_Based \n\ @@ -97,17 +96,15 @@ DC:2C:26-0x0000 = SSR_Max_Lat_Based extern const module_t interop_module; class InteropTest : public ::testing::Test { - protected: +protected: virtual void SetUp() override { #ifndef __ANDROID__ FILE* fp = fopen(INTEROP_STATIC_FILE_PATH, "wte"); ASSERT_NE(fp, nullptr); - ASSERT_EQ(fwrite(INTEROP_STATIC_FILE_CONTENT, 1, - sizeof(INTEROP_STATIC_FILE_CONTENT), fp), + ASSERT_EQ(fwrite(INTEROP_STATIC_FILE_CONTENT, 1, sizeof(INTEROP_STATIC_FILE_CONTENT), fp), sizeof(INTEROP_STATIC_FILE_CONTENT)); // Force data to be flushed on disk and not only in user-space - ASSERT_EQ(fsync(fileno(fp)), 0) - << "Associated ERRNO error is: " << strerror(errno); + ASSERT_EQ(fsync(fileno(fp)), 0) << "Associated ERRNO error is: " << strerror(errno); ASSERT_EQ(fclose(fp), 0); #endif } @@ -115,7 +112,7 @@ class InteropTest : public ::testing::Test { #ifndef __ANDROID__ std::error_code ec; EXPECT_TRUE(std::filesystem::remove(kStaticConfigFileConfigFile, ec)) - << "Associated error is: " << ec; + << "Associated error is: " << ec; #endif } }; @@ -126,8 +123,7 @@ TEST_F(InteropTest, test_lookup_hit) { RawAddress test_address; RawAddress::FromString("38:2c:4a:e6:67:89", test_address); - EXPECT_TRUE( - interop_match_addr(INTEROP_DISABLE_LE_SECURE_CONNECTIONS, &test_address)); + EXPECT_TRUE(interop_match_addr(INTEROP_DISABLE_LE_SECURE_CONNECTIONS, &test_address)); RawAddress::FromString("34:c7:31:12:34:56", test_address); EXPECT_TRUE(interop_match_addr(INTEROP_DISABLE_AUTO_PAIRING, &test_address)); @@ -137,27 +133,22 @@ TEST_F(InteropTest, test_lookup_hit) { EXPECT_TRUE(interop_match_addr(INTEROP_AUTO_RETRY_PAIRING, &test_address)); RawAddress::FromString("a0:e9:db:e6:67:89", test_address); - EXPECT_TRUE( - interop_match_addr(INTEROP_DISABLE_ABSOLUTE_VOLUME, &test_address)); + EXPECT_TRUE(interop_match_addr(INTEROP_DISABLE_ABSOLUTE_VOLUME, &test_address)); RawAddress::FromString("00:0f:f6:e6:67:89", test_address); - EXPECT_TRUE( - interop_match_addr(INTEROP_KEYBOARD_REQUIRES_FIXED_PIN, &test_address)); + EXPECT_TRUE(interop_match_addr(INTEROP_KEYBOARD_REQUIRES_FIXED_PIN, &test_address)); RawAddress::FromString("00:18:91:12:34:56", test_address); EXPECT_TRUE(interop_match_addr(INTEROP_2MBPS_LINK_ONLY, &test_address)); RawAddress::FromString("00:12:a1:e6:67:89", test_address); - EXPECT_TRUE( - interop_match_addr(INTEROP_DISABLE_AUTH_FOR_HID_POINTING, &test_address)); + EXPECT_TRUE(interop_match_addr(INTEROP_DISABLE_AUTH_FOR_HID_POINTING, &test_address)); RawAddress::FromString("20:4c:10:12:34:56", test_address); - EXPECT_TRUE( - interop_match_addr(INTEROP_DISABLE_SNIFF_DURING_SCO, &test_address)); + EXPECT_TRUE(interop_match_addr(INTEROP_DISABLE_SNIFF_DURING_SCO, &test_address)); RawAddress::FromString("00:14:09:e6:67:89", test_address); - EXPECT_TRUE( - interop_match_addr(INTEROP_INCREASE_AG_CONN_TIMEOUT, &test_address)); + EXPECT_TRUE(interop_match_addr(INTEROP_INCREASE_AG_CONN_TIMEOUT, &test_address)); RawAddress::FromString("fc:c2:de:12:34:56", test_address); EXPECT_TRUE(interop_match_addr(INTEROP_DISABLE_ROLE_SWITCH, &test_address)); @@ -172,8 +163,7 @@ TEST_F(InteropTest, test_lookup_hit) { EXPECT_TRUE(interop_match_addr(INTEROP_ENABLE_AAC_CODEC, &test_address)); RawAddress::FromString("ac:fd:ce:e6:67:89", test_address); - EXPECT_TRUE( - interop_match_addr(INTEROP_DISABLE_PCE_SDP_AFTER_PAIRING, &test_address)); + EXPECT_TRUE(interop_match_addr(INTEROP_DISABLE_PCE_SDP_AFTER_PAIRING, &test_address)); RawAddress::FromString("98:7b:f3:12:34:56", test_address); EXPECT_TRUE(interop_match_addr(INTEROP_DISABLE_HF_INDICATOR, &test_address)); @@ -185,63 +175,50 @@ TEST_F(InteropTest, test_lookup_hit) { EXPECT_TRUE(interop_match_addr(INTEROP_DELAY_SCO_FOR_MT_CALL, &test_address)); RawAddress::FromString("00:08:8a:f0:1d:8a", test_address); - EXPECT_TRUE( - interop_match_addr(INTEROP_DISABLE_CODEC_NEGOTIATION, &test_address)); + EXPECT_TRUE(interop_match_addr(INTEROP_DISABLE_CODEC_NEGOTIATION, &test_address)); RawAddress::FromString("a0:56:b2:4f:86:a8", test_address); - EXPECT_TRUE(interop_match_addr( - INTEROP_DISABLE_PLAYER_APPLICATION_SETTING_CMDS, &test_address)); + EXPECT_TRUE(interop_match_addr(INTEROP_DISABLE_PLAYER_APPLICATION_SETTING_CMDS, &test_address)); RawAddress::FromString("a0:14:3d:e6:67:89", test_address); - EXPECT_TRUE(interop_match_addr(INTEROP_DISABLE_CONNECTION_AFTER_COLLISION, - &test_address)); + EXPECT_TRUE(interop_match_addr(INTEROP_DISABLE_CONNECTION_AFTER_COLLISION, &test_address)); RawAddress::FromString("38:2c:4a:c9:34:56", test_address); - EXPECT_TRUE( - interop_match_addr(INTEROP_HID_PREF_CONN_SUP_TIMEOUT_3S, &test_address)); + EXPECT_TRUE(interop_match_addr(INTEROP_HID_PREF_CONN_SUP_TIMEOUT_3S, &test_address)); RawAddress::FromString("00:1d:86:e6:67:89", test_address); - EXPECT_TRUE( - interop_match_addr(INTEROP_DISABLE_AVDTP_RECONFIGURE, &test_address)); + EXPECT_TRUE(interop_match_addr(INTEROP_DISABLE_AVDTP_RECONFIGURE, &test_address)); RawAddress::FromString("2c:dc:ad:08:91:89", test_address); - EXPECT_TRUE(interop_match_addr(INTEROP_AVRCP_BROWSE_OPEN_CHANNEL_COLLISION, - &test_address)); + EXPECT_TRUE(interop_match_addr(INTEROP_AVRCP_BROWSE_OPEN_CHANNEL_COLLISION, &test_address)); RawAddress::FromString("10:b7:f6:03:38:b0", test_address); - EXPECT_TRUE( - interop_match_addr(INTEROP_DISABLE_SNIFF_DURING_CALL, &test_address)); + EXPECT_TRUE(interop_match_addr(INTEROP_DISABLE_SNIFF_DURING_CALL, &test_address)); RawAddress::FromString("00:0e:9f:12:34:56", test_address); EXPECT_TRUE(interop_match_addr(INTEROP_SKIP_INCOMING_STATE, &test_address)); RawAddress::FromString("98:b6:e9:e6:67:89", test_address); - EXPECT_TRUE( - interop_match_addr(INTEROP_HID_HOST_LIMIT_SNIFF_INTERVAL, &test_address)); + EXPECT_TRUE(interop_match_addr(INTEROP_HID_HOST_LIMIT_SNIFF_INTERVAL, &test_address)); RawAddress::FromString("04:4e:af:a8:a0:01", test_address); - EXPECT_TRUE(interop_match_addr(INTEROP_DISABLE_REFRESH_ACCEPT_SIG_TIMER, - &test_address)); + EXPECT_TRUE(interop_match_addr(INTEROP_DISABLE_REFRESH_ACCEPT_SIG_TIMER, &test_address)); RawAddress::FromString("bc:30:7e:5e:f6:27", test_address); - EXPECT_TRUE(interop_match_addr(INTEROP_NOT_UPDATE_AVRCP_PAUSED_TO_REMOTE, - &test_address)); + EXPECT_TRUE(interop_match_addr(INTEROP_NOT_UPDATE_AVRCP_PAUSED_TO_REMOTE, &test_address)); RawAddress::FromString("10:4f:a8:08:91:89", test_address); - EXPECT_TRUE(interop_match_addr( - INTEROP_PHONE_POLICY_REDUCED_DELAY_CONNECT_OTHER_PROFILES, - &test_address)); + EXPECT_TRUE(interop_match_addr(INTEROP_PHONE_POLICY_REDUCED_DELAY_CONNECT_OTHER_PROFILES, + &test_address)); RawAddress::FromString("00:15:83:03:38:b0", test_address); - EXPECT_TRUE(interop_match_addr(INTEROP_HFP_FAKE_INCOMING_CALL_INDICATOR, - &test_address)); + EXPECT_TRUE(interop_match_addr(INTEROP_HFP_FAKE_INCOMING_CALL_INDICATOR, &test_address)); RawAddress::FromString("00:09:93:a6:c5:4d", test_address); EXPECT_TRUE(interop_match_addr(INTEROP_DELAY_SCO_FOR_MO_CALL, &test_address)); RawAddress::FromString("48:eb:62:e6:67:89", test_address); - EXPECT_TRUE(interop_match_addr(INTEROP_DISABLE_ROLE_SWITCH_DURING_CONNECTION, - &test_address)); + EXPECT_TRUE(interop_match_addr(INTEROP_DISABLE_ROLE_SWITCH_DURING_CONNECTION, &test_address)); RawAddress::FromString("9c:df:03:a8:a0:01", test_address); EXPECT_TRUE(interop_match_addr(INTEROP_AUTO_RETRY_PAIRING, &test_address)); @@ -271,116 +248,77 @@ TEST_F(InteropTest, test_lookup_miss) { RawAddress test_address; RawAddress::FromString("00:00:00:00:00:00", test_address); - EXPECT_FALSE( - interop_match_addr(INTEROP_DISABLE_LE_SECURE_CONNECTIONS, &test_address)); + EXPECT_FALSE(interop_match_addr(INTEROP_DISABLE_LE_SECURE_CONNECTIONS, &test_address)); RawAddress::FromString("ff:ff:ff:ff:ff:ff", test_address); EXPECT_FALSE(interop_match_addr(INTEROP_AUTO_RETRY_PAIRING, &test_address)); RawAddress::FromString("42:08:15:ae:ae:ae", test_address); - EXPECT_FALSE( - interop_match_addr(INTEROP_DISABLE_LE_SECURE_CONNECTIONS, &test_address)); + EXPECT_FALSE(interop_match_addr(INTEROP_DISABLE_LE_SECURE_CONNECTIONS, &test_address)); RawAddress::FromString("38:2c:4a:59:67:89", test_address); EXPECT_FALSE(interop_match_addr(INTEROP_AUTO_RETRY_PAIRING, &test_address)); RawAddress::FromString("ff:ff:ff:ff:ff:ff", test_address); - EXPECT_FALSE( - interop_match_addr(INTEROP_DISABLE_LE_SECURE_CONNECTIONS, &test_address)); + EXPECT_FALSE(interop_match_addr(INTEROP_DISABLE_LE_SECURE_CONNECTIONS, &test_address)); EXPECT_FALSE(interop_match_addr(INTEROP_AUTO_RETRY_PAIRING, &test_address)); - EXPECT_FALSE( - interop_match_addr(INTEROP_DISABLE_ABSOLUTE_VOLUME, &test_address)); + EXPECT_FALSE(interop_match_addr(INTEROP_DISABLE_ABSOLUTE_VOLUME, &test_address)); EXPECT_FALSE(interop_match_addr(INTEROP_DISABLE_AUTO_PAIRING, &test_address)); - EXPECT_FALSE( - interop_match_addr(INTEROP_KEYBOARD_REQUIRES_FIXED_PIN, &test_address)); + EXPECT_FALSE(interop_match_addr(INTEROP_KEYBOARD_REQUIRES_FIXED_PIN, &test_address)); EXPECT_FALSE(interop_match_addr(INTEROP_2MBPS_LINK_ONLY, &test_address)); - EXPECT_FALSE( - interop_match_addr(INTEROP_HID_PREF_CONN_SUP_TIMEOUT_3S, &test_address)); - EXPECT_FALSE( - interop_match_addr(INTEROP_GATTC_NO_SERVICE_CHANGED_IND, &test_address)); - EXPECT_FALSE( - interop_match_addr(INTEROP_DISABLE_SDP_AFTER_PAIRING, &test_address)); - EXPECT_FALSE( - interop_match_addr(INTEROP_DISABLE_AUTH_FOR_HID_POINTING, &test_address)); - EXPECT_FALSE( - interop_match_addr(INTEROP_REMOVE_HID_DIG_DESCRIPTOR, &test_address)); - EXPECT_FALSE( - interop_match_addr(INTEROP_DISABLE_SNIFF_DURING_SCO, &test_address)); - EXPECT_FALSE( - interop_match_addr(INTEROP_INCREASE_AG_CONN_TIMEOUT, &test_address)); - EXPECT_FALSE(interop_match_addr(INTEROP_DISABLE_LE_CONN_PREFERRED_PARAMS, - &test_address)); + EXPECT_FALSE(interop_match_addr(INTEROP_HID_PREF_CONN_SUP_TIMEOUT_3S, &test_address)); + EXPECT_FALSE(interop_match_addr(INTEROP_GATTC_NO_SERVICE_CHANGED_IND, &test_address)); + EXPECT_FALSE(interop_match_addr(INTEROP_DISABLE_SDP_AFTER_PAIRING, &test_address)); + EXPECT_FALSE(interop_match_addr(INTEROP_DISABLE_AUTH_FOR_HID_POINTING, &test_address)); + EXPECT_FALSE(interop_match_addr(INTEROP_REMOVE_HID_DIG_DESCRIPTOR, &test_address)); + EXPECT_FALSE(interop_match_addr(INTEROP_DISABLE_SNIFF_DURING_SCO, &test_address)); + EXPECT_FALSE(interop_match_addr(INTEROP_INCREASE_AG_CONN_TIMEOUT, &test_address)); + EXPECT_FALSE(interop_match_addr(INTEROP_DISABLE_LE_CONN_PREFERRED_PARAMS, &test_address)); EXPECT_FALSE(interop_match_addr(INTEROP_DISABLE_AAC_CODEC, &test_address)); - EXPECT_FALSE( - interop_match_addr(INTEROP_DISABLE_AAC_VBR_CODEC, &test_address)); + EXPECT_FALSE(interop_match_addr(INTEROP_DISABLE_AAC_VBR_CODEC, &test_address)); EXPECT_FALSE(interop_match_addr(INTEROP_DYNAMIC_ROLE_SWITCH, &test_address)); EXPECT_FALSE(interop_match_addr(INTEROP_DISABLE_ROLE_SWITCH, &test_address)); - EXPECT_FALSE( - interop_match_addr(INTEROP_DISABLE_ROLE_SWITCH_POLICY, &test_address)); + EXPECT_FALSE(interop_match_addr(INTEROP_DISABLE_ROLE_SWITCH_POLICY, &test_address)); EXPECT_FALSE(interop_match_addr(INTEROP_HFP_1_7_DENYLIST, &test_address)); EXPECT_FALSE(interop_match_addr(INTEROP_ADV_PBAP_VER_1_1, &test_address)); - EXPECT_FALSE( - interop_match_addr(INTEROP_UPDATE_HID_SSR_MAX_LAT, &test_address)); - EXPECT_FALSE( - interop_match_addr(INTEROP_DISABLE_AVDTP_RECONFIGURE, &test_address)); + EXPECT_FALSE(interop_match_addr(INTEROP_UPDATE_HID_SSR_MAX_LAT, &test_address)); + EXPECT_FALSE(interop_match_addr(INTEROP_DISABLE_AVDTP_RECONFIGURE, &test_address)); EXPECT_FALSE(interop_match_addr(INTEROP_DISABLE_HF_INDICATOR, &test_address)); - EXPECT_FALSE( - interop_match_addr(INTEROP_DISABLE_LE_CONN_UPDATES, &test_address)); - EXPECT_FALSE( - interop_match_addr(INTEROP_DELAY_SCO_FOR_MT_CALL, &test_address)); - EXPECT_FALSE( - interop_match_addr(INTEROP_DISABLE_CODEC_NEGOTIATION, &test_address)); - EXPECT_FALSE(interop_match_addr( - INTEROP_DISABLE_PLAYER_APPLICATION_SETTING_CMDS, &test_address)); + EXPECT_FALSE(interop_match_addr(INTEROP_DISABLE_LE_CONN_UPDATES, &test_address)); + EXPECT_FALSE(interop_match_addr(INTEROP_DELAY_SCO_FOR_MT_CALL, &test_address)); + EXPECT_FALSE(interop_match_addr(INTEROP_DISABLE_CODEC_NEGOTIATION, &test_address)); + EXPECT_FALSE(interop_match_addr(INTEROP_DISABLE_PLAYER_APPLICATION_SETTING_CMDS, &test_address)); EXPECT_FALSE(interop_match_addr(INTEROP_ENABLE_AAC_CODEC, &test_address)); - EXPECT_FALSE(interop_match_addr(INTEROP_DISABLE_CONNECTION_AFTER_COLLISION, - &test_address)); - EXPECT_FALSE(interop_match_addr(INTEROP_AVRCP_BROWSE_OPEN_CHANNEL_COLLISION, - &test_address)); + EXPECT_FALSE(interop_match_addr(INTEROP_DISABLE_CONNECTION_AFTER_COLLISION, &test_address)); + EXPECT_FALSE(interop_match_addr(INTEROP_AVRCP_BROWSE_OPEN_CHANNEL_COLLISION, &test_address)); EXPECT_FALSE(interop_match_addr(INTEROP_ADV_PBAP_VER_1_2, &test_address)); - EXPECT_FALSE( - interop_match_addr(INTEROP_DISABLE_PCE_SDP_AFTER_PAIRING, &test_address)); - EXPECT_FALSE( - interop_match_addr(INTEROP_DISABLE_SNIFF_LINK_DURING_SCO, &test_address)); - EXPECT_FALSE( - interop_match_addr(INTEROP_DISABLE_SNIFF_DURING_CALL, &test_address)); - EXPECT_FALSE( - interop_match_addr(INTEROP_HID_HOST_LIMIT_SNIFF_INTERVAL, &test_address)); - EXPECT_FALSE(interop_match_addr(INTEROP_DISABLE_REFRESH_ACCEPT_SIG_TIMER, - &test_address)); + EXPECT_FALSE(interop_match_addr(INTEROP_DISABLE_PCE_SDP_AFTER_PAIRING, &test_address)); + EXPECT_FALSE(interop_match_addr(INTEROP_DISABLE_SNIFF_LINK_DURING_SCO, &test_address)); + EXPECT_FALSE(interop_match_addr(INTEROP_DISABLE_SNIFF_DURING_CALL, &test_address)); + EXPECT_FALSE(interop_match_addr(INTEROP_HID_HOST_LIMIT_SNIFF_INTERVAL, &test_address)); + EXPECT_FALSE(interop_match_addr(INTEROP_DISABLE_REFRESH_ACCEPT_SIG_TIMER, &test_address)); EXPECT_FALSE(interop_match_addr(INTEROP_SKIP_INCOMING_STATE, &test_address)); - EXPECT_FALSE(interop_match_addr(INTEROP_NOT_UPDATE_AVRCP_PAUSED_TO_REMOTE, - &test_address)); - EXPECT_FALSE(interop_match_addr( - INTEROP_PHONE_POLICY_INCREASED_DELAY_CONNECT_OTHER_PROFILES, - &test_address)); - EXPECT_FALSE(interop_match_addr( - INTEROP_PHONE_POLICY_REDUCED_DELAY_CONNECT_OTHER_PROFILES, - &test_address)); - EXPECT_FALSE(interop_match_addr(INTEROP_HFP_FAKE_INCOMING_CALL_INDICATOR, - &test_address)); - EXPECT_FALSE(interop_match_addr(INTEROP_HFP_SEND_CALL_INDICATORS_BACK_TO_BACK, - &test_address)); - EXPECT_FALSE(interop_match_addr( - INTEROP_SETUP_SCO_WITH_NO_DELAY_AFTER_SLC_DURING_CALL, &test_address)); - EXPECT_FALSE(interop_match_addr(INTEROP_ENABLE_PREFERRED_CONN_PARAMETER, + EXPECT_FALSE(interop_match_addr(INTEROP_NOT_UPDATE_AVRCP_PAUSED_TO_REMOTE, &test_address)); + EXPECT_FALSE(interop_match_addr(INTEROP_PHONE_POLICY_INCREASED_DELAY_CONNECT_OTHER_PROFILES, &test_address)); - EXPECT_FALSE(interop_match_addr(INTEROP_RETRY_SCO_AFTER_REMOTE_REJECT_SCO, + EXPECT_FALSE(interop_match_addr(INTEROP_PHONE_POLICY_REDUCED_DELAY_CONNECT_OTHER_PROFILES, &test_address)); + EXPECT_FALSE(interop_match_addr(INTEROP_HFP_FAKE_INCOMING_CALL_INDICATOR, &test_address)); + EXPECT_FALSE(interop_match_addr(INTEROP_HFP_SEND_CALL_INDICATORS_BACK_TO_BACK, &test_address)); EXPECT_FALSE( - interop_match_addr(INTEROP_DELAY_SCO_FOR_MO_CALL, &test_address)); + interop_match_addr(INTEROP_SETUP_SCO_WITH_NO_DELAY_AFTER_SLC_DURING_CALL, &test_address)); + EXPECT_FALSE(interop_match_addr(INTEROP_ENABLE_PREFERRED_CONN_PARAMETER, &test_address)); + EXPECT_FALSE(interop_match_addr(INTEROP_RETRY_SCO_AFTER_REMOTE_REJECT_SCO, &test_address)); + EXPECT_FALSE(interop_match_addr(INTEROP_DELAY_SCO_FOR_MO_CALL, &test_address)); EXPECT_FALSE(interop_match_addr(INTEROP_CHANGE_HID_VID_PID, &test_address)); EXPECT_FALSE(interop_match_addr(END_OF_INTEROP_LIST, &test_address)); EXPECT_FALSE(interop_match_addr(INTEROP_HFP_1_8_DENYLIST, &test_address)); - EXPECT_FALSE(interop_match_addr(INTEROP_DISABLE_ROLE_SWITCH_DURING_CONNECTION, - &test_address)); + EXPECT_FALSE(interop_match_addr(INTEROP_DISABLE_ROLE_SWITCH_DURING_CONNECTION, &test_address)); EXPECT_FALSE(interop_match_addr(INTEROP_DISABLE_NAME_REQUEST, &test_address)); EXPECT_FALSE(interop_match_addr(INTEROP_AVRCP_1_4_ONLY, &test_address)); EXPECT_FALSE(interop_match_addr(INTEROP_DISABLE_SNIFF, &test_address)); - EXPECT_FALSE( - interop_match_addr(INTEROP_DISABLE_AVDTP_SUSPEND, &test_address)); - EXPECT_FALSE( - interop_match_addr(INTEROP_SLC_SKIP_BIND_COMMAND, &test_address)); + EXPECT_FALSE(interop_match_addr(INTEROP_DISABLE_AVDTP_SUSPEND, &test_address)); + EXPECT_FALSE(interop_match_addr(INTEROP_SLC_SKIP_BIND_COMMAND, &test_address)); EXPECT_FALSE(interop_match_addr(INTEROP_AVRCP_1_3_ONLY, &test_address)); module_clean_up(&interop_module); @@ -392,12 +330,10 @@ TEST_F(InteropTest, test_dynamic_db_clear) { RawAddress test_address; RawAddress::FromString("11:22:33:44:55:66", test_address); - EXPECT_FALSE( - interop_match_addr(INTEROP_DISABLE_LE_SECURE_CONNECTIONS, &test_address)); + EXPECT_FALSE(interop_match_addr(INTEROP_DISABLE_LE_SECURE_CONNECTIONS, &test_address)); interop_database_add(INTEROP_DISABLE_LE_SECURE_CONNECTIONS, &test_address, 3); - EXPECT_TRUE( - interop_match_addr(INTEROP_DISABLE_LE_SECURE_CONNECTIONS, &test_address)); + EXPECT_TRUE(interop_match_addr(INTEROP_DISABLE_LE_SECURE_CONNECTIONS, &test_address)); EXPECT_FALSE(interop_match_addr(INTEROP_AUTO_RETRY_PAIRING, &test_address)); RawAddress::FromString("66:55:44:33:22:11", test_address); @@ -405,8 +341,7 @@ TEST_F(InteropTest, test_dynamic_db_clear) { interop_database_add(INTEROP_AUTO_RETRY_PAIRING, &test_address, 3); EXPECT_TRUE(interop_match_addr(INTEROP_AUTO_RETRY_PAIRING, &test_address)); - EXPECT_FALSE( - interop_match_addr(INTEROP_DISABLE_LE_SECURE_CONNECTIONS, &test_address)); + EXPECT_FALSE(interop_match_addr(INTEROP_DISABLE_LE_SECURE_CONNECTIONS, &test_address)); interop_database_clear(); @@ -425,39 +360,28 @@ TEST_F(InteropTest, test_name_hit) { EXPECT_TRUE(interop_match_name(INTEROP_DISABLE_AUTO_PAIRING, "Caramel")); // Starts with "Car" ;) - EXPECT_TRUE( - interop_match_name(INTEROP_GATTC_NO_SERVICE_CHANGED_IND, "MiMouse")); + EXPECT_TRUE(interop_match_name(INTEROP_GATTC_NO_SERVICE_CHANGED_IND, "MiMouse")); EXPECT_TRUE(interop_match_name(INTEROP_DISABLE_AUTH_FOR_HID_POINTING, "Targus BT Laser Notebook Mouse")); - EXPECT_TRUE(interop_match_name(INTEROP_REMOVE_HID_DIG_DESCRIPTOR, - "Motorola Keyboard KZ500")); - EXPECT_TRUE(interop_match_name(INTEROP_DISABLE_LE_CONN_PREFERRED_PARAMS, - "BSMBB09DS")); + EXPECT_TRUE(interop_match_name(INTEROP_REMOVE_HID_DIG_DESCRIPTOR, "Motorola Keyboard KZ500")); + EXPECT_TRUE(interop_match_name(INTEROP_DISABLE_LE_CONN_PREFERRED_PARAMS, "BSMBB09DS")); EXPECT_TRUE(interop_match_name(INTEROP_DISABLE_AAC_CODEC, "abramtek M1")); - EXPECT_TRUE( - interop_match_name(INTEROP_DISABLE_AAC_VBR_CODEC, "Audi_MMI_2781")); - EXPECT_TRUE( - interop_match_name(INTEROP_DISABLE_AVDTP_RECONFIGURE, "KMM-BT51*HD")); + EXPECT_TRUE(interop_match_name(INTEROP_DISABLE_AAC_VBR_CODEC, "Audi_MMI_2781")); + EXPECT_TRUE(interop_match_name(INTEROP_DISABLE_AVDTP_RECONFIGURE, "KMM-BT51*HD")); EXPECT_TRUE(interop_match_name(INTEROP_DISABLE_LE_CONN_UPDATES, "ITAG")); EXPECT_TRUE(interop_match_name(INTEROP_DELAY_SCO_FOR_MT_CALL, "AirPods Pro")); - EXPECT_TRUE( - interop_match_name(INTEROP_DISABLE_CODEC_NEGOTIATION, "JABRA EASYGO")); + EXPECT_TRUE(interop_match_name(INTEROP_DISABLE_CODEC_NEGOTIATION, "JABRA EASYGO")); EXPECT_TRUE(interop_match_name(INTEROP_ENABLE_AAC_CODEC, "MDR-1RBT")); - EXPECT_TRUE( - interop_match_name(INTEROP_DISABLE_SNIFF_LINK_DURING_SCO, "AirPods")); + EXPECT_TRUE(interop_match_name(INTEROP_DISABLE_SNIFF_LINK_DURING_SCO, "AirPods")); EXPECT_TRUE(interop_match_name(INTEROP_DISABLE_SNIFF_DURING_CALL, "AirPods")); + EXPECT_TRUE(interop_match_name(INTEROP_HID_HOST_LIMIT_SNIFF_INTERVAL, "Joy-Con")); + EXPECT_TRUE(interop_match_name(INTEROP_DISABLE_REFRESH_ACCEPT_SIG_TIMER, "HB20")); + EXPECT_TRUE(interop_match_name(INTEROP_NOT_UPDATE_AVRCP_PAUSED_TO_REMOTE, "Audi")); EXPECT_TRUE( - interop_match_name(INTEROP_HID_HOST_LIMIT_SNIFF_INTERVAL, "Joy-Con")); - EXPECT_TRUE( - interop_match_name(INTEROP_DISABLE_REFRESH_ACCEPT_SIG_TIMER, "HB20")); + interop_match_name(INTEROP_SETUP_SCO_WITH_NO_DELAY_AFTER_SLC_DURING_CALL, "Geely_BT")); EXPECT_TRUE( - interop_match_name(INTEROP_NOT_UPDATE_AVRCP_PAUSED_TO_REMOTE, "Audi")); - EXPECT_TRUE(interop_match_name( - INTEROP_SETUP_SCO_WITH_NO_DELAY_AFTER_SLC_DURING_CALL, "Geely_BT")); - EXPECT_TRUE(interop_match_name(INTEROP_ENABLE_PREFERRED_CONN_PARAMETER, - "Microsoft Bluetooth Mouse")); - EXPECT_TRUE(interop_match_name(INTEROP_RETRY_SCO_AFTER_REMOTE_REJECT_SCO, - "HAVAL M6")); + interop_match_name(INTEROP_ENABLE_PREFERRED_CONN_PARAMETER, "Microsoft Bluetooth Mouse")); + EXPECT_TRUE(interop_match_name(INTEROP_RETRY_SCO_AFTER_REMOTE_REJECT_SCO, "HAVAL M6")); EXPECT_TRUE(interop_match_name(INTEROP_CHANGE_HID_VID_PID, "CK87BT")); #endif @@ -470,25 +394,20 @@ TEST_F(InteropTest, test_name_miss) { EXPECT_FALSE(interop_match_name(INTEROP_DISABLE_AUTO_PAIRING, "__GOOGLE__")); EXPECT_FALSE(interop_match_name(INTEROP_DISABLE_AUTO_PAIRING, "BM")); EXPECT_FALSE(interop_match_name(INTEROP_AUTO_RETRY_PAIRING, "BMW M3")); - EXPECT_FALSE( - interop_match_name(INTEROP_DISABLE_LE_SECURE_CONNECTIONS, "TEST")); + EXPECT_FALSE(interop_match_name(INTEROP_DISABLE_LE_SECURE_CONNECTIONS, "TEST")); EXPECT_FALSE(interop_match_name(INTEROP_AUTO_RETRY_PAIRING, "TEST")); EXPECT_FALSE(interop_match_name(INTEROP_DISABLE_ABSOLUTE_VOLUME, "TEST")); EXPECT_FALSE(interop_match_name(INTEROP_DISABLE_AUTO_PAIRING, "TEST")); EXPECT_FALSE(interop_match_name(INTEROP_KEYBOARD_REQUIRES_FIXED_PIN, "TEST")); EXPECT_FALSE(interop_match_name(INTEROP_2MBPS_LINK_ONLY, "TEST")); - EXPECT_FALSE( - interop_match_name(INTEROP_HID_PREF_CONN_SUP_TIMEOUT_3S, "TEST")); - EXPECT_FALSE( - interop_match_name(INTEROP_GATTC_NO_SERVICE_CHANGED_IND, "TEST")); + EXPECT_FALSE(interop_match_name(INTEROP_HID_PREF_CONN_SUP_TIMEOUT_3S, "TEST")); + EXPECT_FALSE(interop_match_name(INTEROP_GATTC_NO_SERVICE_CHANGED_IND, "TEST")); EXPECT_FALSE(interop_match_name(INTEROP_DISABLE_SDP_AFTER_PAIRING, "TEST")); - EXPECT_FALSE( - interop_match_name(INTEROP_DISABLE_AUTH_FOR_HID_POINTING, "TEST")); + EXPECT_FALSE(interop_match_name(INTEROP_DISABLE_AUTH_FOR_HID_POINTING, "TEST")); EXPECT_FALSE(interop_match_name(INTEROP_REMOVE_HID_DIG_DESCRIPTOR, "TEST")); EXPECT_FALSE(interop_match_name(INTEROP_DISABLE_SNIFF_DURING_SCO, "TEST")); EXPECT_FALSE(interop_match_name(INTEROP_INCREASE_AG_CONN_TIMEOUT, "TEST")); - EXPECT_FALSE( - interop_match_name(INTEROP_DISABLE_LE_CONN_PREFERRED_PARAMS, "TEST")); + EXPECT_FALSE(interop_match_name(INTEROP_DISABLE_LE_CONN_PREFERRED_PARAMS, "TEST")); EXPECT_FALSE(interop_match_name(INTEROP_DISABLE_AAC_CODEC, "TEST")); EXPECT_FALSE(interop_match_name(INTEROP_DISABLE_AAC_VBR_CODEC, "TEST")); EXPECT_FALSE(interop_match_name(INTEROP_DYNAMIC_ROLE_SWITCH, "TEST")); @@ -502,45 +421,31 @@ TEST_F(InteropTest, test_name_miss) { EXPECT_FALSE(interop_match_name(INTEROP_DISABLE_LE_CONN_UPDATES, "TEST")); EXPECT_FALSE(interop_match_name(INTEROP_DELAY_SCO_FOR_MT_CALL, "TEST")); EXPECT_FALSE(interop_match_name(INTEROP_DISABLE_CODEC_NEGOTIATION, "TEST")); - EXPECT_FALSE(interop_match_name( - INTEROP_DISABLE_PLAYER_APPLICATION_SETTING_CMDS, "TEST")); + EXPECT_FALSE(interop_match_name(INTEROP_DISABLE_PLAYER_APPLICATION_SETTING_CMDS, "TEST")); EXPECT_FALSE(interop_match_name(INTEROP_ENABLE_AAC_CODEC, "TEST")); - EXPECT_FALSE( - interop_match_name(INTEROP_DISABLE_CONNECTION_AFTER_COLLISION, "TEST")); - EXPECT_FALSE( - interop_match_name(INTEROP_AVRCP_BROWSE_OPEN_CHANNEL_COLLISION, "TEST")); + EXPECT_FALSE(interop_match_name(INTEROP_DISABLE_CONNECTION_AFTER_COLLISION, "TEST")); + EXPECT_FALSE(interop_match_name(INTEROP_AVRCP_BROWSE_OPEN_CHANNEL_COLLISION, "TEST")); EXPECT_FALSE(interop_match_name(INTEROP_ADV_PBAP_VER_1_2, "TEST")); - EXPECT_FALSE( - interop_match_name(INTEROP_DISABLE_PCE_SDP_AFTER_PAIRING, "TEST")); - EXPECT_FALSE( - interop_match_name(INTEROP_DISABLE_SNIFF_LINK_DURING_SCO, "TEST")); + EXPECT_FALSE(interop_match_name(INTEROP_DISABLE_PCE_SDP_AFTER_PAIRING, "TEST")); + EXPECT_FALSE(interop_match_name(INTEROP_DISABLE_SNIFF_LINK_DURING_SCO, "TEST")); EXPECT_FALSE(interop_match_name(INTEROP_DISABLE_SNIFF_DURING_CALL, "TEST")); - EXPECT_FALSE( - interop_match_name(INTEROP_HID_HOST_LIMIT_SNIFF_INTERVAL, "TEST")); - EXPECT_FALSE( - interop_match_name(INTEROP_DISABLE_REFRESH_ACCEPT_SIG_TIMER, "TEST")); + EXPECT_FALSE(interop_match_name(INTEROP_HID_HOST_LIMIT_SNIFF_INTERVAL, "TEST")); + EXPECT_FALSE(interop_match_name(INTEROP_DISABLE_REFRESH_ACCEPT_SIG_TIMER, "TEST")); EXPECT_FALSE(interop_match_name(INTEROP_SKIP_INCOMING_STATE, "TEST")); + EXPECT_FALSE(interop_match_name(INTEROP_NOT_UPDATE_AVRCP_PAUSED_TO_REMOTE, "TEST")); EXPECT_FALSE( - interop_match_name(INTEROP_NOT_UPDATE_AVRCP_PAUSED_TO_REMOTE, "TEST")); - EXPECT_FALSE(interop_match_name( - INTEROP_PHONE_POLICY_INCREASED_DELAY_CONNECT_OTHER_PROFILES, "TEST")); - EXPECT_FALSE(interop_match_name( - INTEROP_PHONE_POLICY_REDUCED_DELAY_CONNECT_OTHER_PROFILES, "TEST")); - EXPECT_FALSE( - interop_match_name(INTEROP_HFP_FAKE_INCOMING_CALL_INDICATOR, "TEST")); - EXPECT_FALSE(interop_match_name(INTEROP_HFP_SEND_CALL_INDICATORS_BACK_TO_BACK, - "TEST")); - EXPECT_FALSE(interop_match_name( - INTEROP_SETUP_SCO_WITH_NO_DELAY_AFTER_SLC_DURING_CALL, "TEST")); + interop_match_name(INTEROP_PHONE_POLICY_INCREASED_DELAY_CONNECT_OTHER_PROFILES, "TEST")); EXPECT_FALSE( - interop_match_name(INTEROP_ENABLE_PREFERRED_CONN_PARAMETER, "TEST")); - EXPECT_FALSE( - interop_match_name(INTEROP_RETRY_SCO_AFTER_REMOTE_REJECT_SCO, "TEST")); + interop_match_name(INTEROP_PHONE_POLICY_REDUCED_DELAY_CONNECT_OTHER_PROFILES, "TEST")); + EXPECT_FALSE(interop_match_name(INTEROP_HFP_FAKE_INCOMING_CALL_INDICATOR, "TEST")); + EXPECT_FALSE(interop_match_name(INTEROP_HFP_SEND_CALL_INDICATORS_BACK_TO_BACK, "TEST")); + EXPECT_FALSE(interop_match_name(INTEROP_SETUP_SCO_WITH_NO_DELAY_AFTER_SLC_DURING_CALL, "TEST")); + EXPECT_FALSE(interop_match_name(INTEROP_ENABLE_PREFERRED_CONN_PARAMETER, "TEST")); + EXPECT_FALSE(interop_match_name(INTEROP_RETRY_SCO_AFTER_REMOTE_REJECT_SCO, "TEST")); EXPECT_FALSE(interop_match_name(INTEROP_DELAY_SCO_FOR_MO_CALL, "TEST")); EXPECT_FALSE(interop_match_name(INTEROP_CHANGE_HID_VID_PID, "TEST")); EXPECT_FALSE(interop_match_name(INTEROP_HFP_1_8_DENYLIST, "TEST")); - EXPECT_FALSE(interop_match_name(INTEROP_DISABLE_ROLE_SWITCH_DURING_CONNECTION, - "TEST")); + EXPECT_FALSE(interop_match_name(INTEROP_DISABLE_ROLE_SWITCH_DURING_CONNECTION, "TEST")); EXPECT_FALSE(interop_match_name(INTEROP_DISABLE_NAME_REQUEST, "TEST")); EXPECT_FALSE(interop_match_name(INTEROP_AVRCP_1_4_ONLY, "TEST")); EXPECT_FALSE(interop_match_name(INTEROP_DISABLE_SNIFF, "TEST")); @@ -556,14 +461,11 @@ TEST_F(InteropTest, test_range_hit) { RawAddress test_address; RawAddress::FromString("00:0f:59:50:00:00", test_address); - EXPECT_TRUE( - interop_match_addr(INTEROP_DISABLE_ABSOLUTE_VOLUME, &test_address)); + EXPECT_TRUE(interop_match_addr(INTEROP_DISABLE_ABSOLUTE_VOLUME, &test_address)); RawAddress::FromString("00:0f:59:59:12:34", test_address); - EXPECT_TRUE( - interop_match_addr(INTEROP_DISABLE_ABSOLUTE_VOLUME, &test_address)); + EXPECT_TRUE(interop_match_addr(INTEROP_DISABLE_ABSOLUTE_VOLUME, &test_address)); RawAddress::FromString("00:0f:59:6f:ff:ff", test_address); - EXPECT_TRUE( - interop_match_addr(INTEROP_DISABLE_ABSOLUTE_VOLUME, &test_address)); + EXPECT_TRUE(interop_match_addr(INTEROP_DISABLE_ABSOLUTE_VOLUME, &test_address)); module_clean_up(&interop_module); } @@ -573,11 +475,9 @@ TEST_F(InteropTest, test_range_miss) { RawAddress test_address; RawAddress::FromString("00:0f:59:49:12:34", test_address); - EXPECT_FALSE( - interop_match_addr(INTEROP_DISABLE_ABSOLUTE_VOLUME, &test_address)); + EXPECT_FALSE(interop_match_addr(INTEROP_DISABLE_ABSOLUTE_VOLUME, &test_address)); RawAddress::FromString("00:0f:59:70:12:34", test_address); - EXPECT_FALSE( - interop_match_addr(INTEROP_DISABLE_ABSOLUTE_VOLUME, &test_address)); + EXPECT_FALSE(interop_match_addr(INTEROP_DISABLE_ABSOLUTE_VOLUME, &test_address)); module_clean_up(&interop_module); } @@ -588,14 +488,13 @@ TEST_F(InteropTest, test_vndr_prdt_hit) { uint16_t vendor_id = 0x22b8; uint16_t product_id = 0x093D; - EXPECT_TRUE(interop_database_match_vndr_prdt( - INTEROP_REMOVE_HID_DIG_DESCRIPTOR, vendor_id, product_id)); + EXPECT_TRUE(interop_database_match_vndr_prdt(INTEROP_REMOVE_HID_DIG_DESCRIPTOR, vendor_id, + product_id)); vendor_id = 0x05ac; product_id = 0x0255; - EXPECT_TRUE(interop_database_match_vndr_prdt(INTEROP_CHANGE_HID_VID_PID, - vendor_id, product_id)); + EXPECT_TRUE(interop_database_match_vndr_prdt(INTEROP_CHANGE_HID_VID_PID, vendor_id, product_id)); module_clean_up(&interop_module); } @@ -606,8 +505,8 @@ TEST_F(InteropTest, test_vndr_prdt_miss) { uint16_t vendor_id = 0x22b9; uint16_t product_id = 0x093D; - EXPECT_FALSE(interop_database_match_vndr_prdt( - INTEROP_REMOVE_HID_DIG_DESCRIPTOR, vendor_id, product_id)); + EXPECT_FALSE(interop_database_match_vndr_prdt(INTEROP_REMOVE_HID_DIG_DESCRIPTOR, vendor_id, + product_id)); module_clean_up(&interop_module); } @@ -617,8 +516,7 @@ TEST_F(InteropTest, test_manufacturer_hit) { uint16_t manufacturer = 0x004C; - EXPECT_TRUE(interop_database_match_manufacturer( - INTEROP_DISABLE_SNIFF_DURING_SCO, manufacturer)); + EXPECT_TRUE(interop_database_match_manufacturer(INTEROP_DISABLE_SNIFF_DURING_SCO, manufacturer)); module_clean_up(&interop_module); } @@ -628,8 +526,7 @@ TEST_F(InteropTest, test_manufacturer_miss) { uint16_t manufacturer = 0x004D; - EXPECT_FALSE(interop_database_match_manufacturer( - INTEROP_DISABLE_SNIFF_DURING_SCO, manufacturer)); + EXPECT_FALSE(interop_database_match_manufacturer(INTEROP_DISABLE_SNIFF_DURING_SCO, manufacturer)); module_clean_up(&interop_module); } @@ -641,8 +538,8 @@ TEST_F(InteropTest, test_ssr_max_latency_hit) { RawAddress::FromString("00:1b:dc:70:12:34", test_address); uint16_t max_lat = 0; - EXPECT_TRUE(interop_database_match_addr_get_max_lat( - INTEROP_UPDATE_HID_SSR_MAX_LAT, &test_address, &max_lat)); + EXPECT_TRUE(interop_database_match_addr_get_max_lat(INTEROP_UPDATE_HID_SSR_MAX_LAT, &test_address, + &max_lat)); EXPECT_TRUE(max_lat == 0x0012); module_clean_up(&interop_module); @@ -655,8 +552,8 @@ TEST_F(InteropTest, test_ssr_max_latency_miss) { RawAddress::FromString("00:1b:db:70:12:34", test_address); uint16_t max_lat = 0; - EXPECT_FALSE(interop_database_match_addr_get_max_lat( - INTEROP_UPDATE_HID_SSR_MAX_LAT, &test_address, &max_lat)); + EXPECT_FALSE(interop_database_match_addr_get_max_lat(INTEROP_UPDATE_HID_SSR_MAX_LAT, + &test_address, &max_lat)); module_clean_up(&interop_module); } @@ -667,18 +564,13 @@ TEST_F(InteropTest, test_dynamic_addr) { RawAddress test_address; RawAddress::FromString("11:22:33:44:55:66", test_address); - EXPECT_FALSE( - interop_match_addr(INTEROP_DISABLE_LE_SECURE_CONNECTIONS, &test_address)); + EXPECT_FALSE(interop_match_addr(INTEROP_DISABLE_LE_SECURE_CONNECTIONS, &test_address)); - interop_database_add_addr(INTEROP_DISABLE_LE_SECURE_CONNECTIONS, - &test_address, 3); - EXPECT_TRUE( - interop_match_addr(INTEROP_DISABLE_LE_SECURE_CONNECTIONS, &test_address)); + interop_database_add_addr(INTEROP_DISABLE_LE_SECURE_CONNECTIONS, &test_address, 3); + EXPECT_TRUE(interop_match_addr(INTEROP_DISABLE_LE_SECURE_CONNECTIONS, &test_address)); - interop_database_remove_addr(INTEROP_DISABLE_LE_SECURE_CONNECTIONS, - &test_address); - EXPECT_FALSE( - interop_match_addr(INTEROP_DISABLE_LE_SECURE_CONNECTIONS, &test_address)); + interop_database_remove_addr(INTEROP_DISABLE_LE_SECURE_CONNECTIONS, &test_address); + EXPECT_FALSE(interop_match_addr(INTEROP_DISABLE_LE_SECURE_CONNECTIONS, &test_address)); module_clean_up(&interop_module); } @@ -686,16 +578,13 @@ TEST_F(InteropTest, test_dynamic_addr) { TEST_F(InteropTest, test_dynamic_name) { module_init(&interop_module); - EXPECT_FALSE( - interop_match_name(INTEROP_DISABLE_LE_SECURE_CONNECTIONS, "TEST")); + EXPECT_FALSE(interop_match_name(INTEROP_DISABLE_LE_SECURE_CONNECTIONS, "TEST")); interop_database_add_name(INTEROP_DISABLE_LE_SECURE_CONNECTIONS, "TEST"); - EXPECT_TRUE( - interop_match_name(INTEROP_DISABLE_LE_SECURE_CONNECTIONS, "TEST")); + EXPECT_TRUE(interop_match_name(INTEROP_DISABLE_LE_SECURE_CONNECTIONS, "TEST")); interop_database_remove_name(INTEROP_DISABLE_LE_SECURE_CONNECTIONS, "TEST"); - EXPECT_FALSE( - interop_match_name(INTEROP_DISABLE_LE_SECURE_CONNECTIONS, "TEST")); + EXPECT_FALSE(interop_match_name(INTEROP_DISABLE_LE_SECURE_CONNECTIONS, "TEST")); module_clean_up(&interop_module); } @@ -706,19 +595,16 @@ TEST_F(InteropTest, test_dynamic_vndr_prdt) { uint16_t vendor_id = 0x11b8; uint16_t product_id = 0x193D; - EXPECT_FALSE(interop_database_match_vndr_prdt( - INTEROP_REMOVE_HID_DIG_DESCRIPTOR, vendor_id, product_id)); + EXPECT_FALSE(interop_database_match_vndr_prdt(INTEROP_REMOVE_HID_DIG_DESCRIPTOR, vendor_id, + product_id)); - interop_database_add_vndr_prdt(INTEROP_REMOVE_HID_DIG_DESCRIPTOR, vendor_id, - product_id); - EXPECT_TRUE(interop_database_match_vndr_prdt( - INTEROP_REMOVE_HID_DIG_DESCRIPTOR, vendor_id, product_id)); + interop_database_add_vndr_prdt(INTEROP_REMOVE_HID_DIG_DESCRIPTOR, vendor_id, product_id); + EXPECT_TRUE(interop_database_match_vndr_prdt(INTEROP_REMOVE_HID_DIG_DESCRIPTOR, vendor_id, + product_id)); - interop_database_remove_vndr_prdt(INTEROP_REMOVE_HID_DIG_DESCRIPTOR, - vendor_id, product_id); + interop_database_remove_vndr_prdt(INTEROP_REMOVE_HID_DIG_DESCRIPTOR, vendor_id, product_id); - EXPECT_FALSE(interop_database_match_vndr_prdt(INTEROP_CHANGE_HID_VID_PID, - vendor_id, product_id)); + EXPECT_FALSE(interop_database_match_vndr_prdt(INTEROP_CHANGE_HID_VID_PID, vendor_id, product_id)); module_clean_up(&interop_module); } @@ -730,21 +616,18 @@ TEST_F(InteropTest, test_dynamic_addr_get_ssr_max_lat) { RawAddress::FromString("11:22:33:44:55:66", test_address); uint16_t max_lat = 0; - EXPECT_FALSE(interop_database_match_addr_get_max_lat( - INTEROP_UPDATE_HID_SSR_MAX_LAT, &test_address, &max_lat)); - interop_database_add_addr_max_lat(INTEROP_UPDATE_HID_SSR_MAX_LAT, - &test_address, 0x0012); + EXPECT_FALSE(interop_database_match_addr_get_max_lat(INTEROP_UPDATE_HID_SSR_MAX_LAT, + &test_address, &max_lat)); + interop_database_add_addr_max_lat(INTEROP_UPDATE_HID_SSR_MAX_LAT, &test_address, 0x0012); - interop_database_match_addr_get_max_lat(INTEROP_UPDATE_HID_SSR_MAX_LAT, - &test_address, &max_lat); + interop_database_match_addr_get_max_lat(INTEROP_UPDATE_HID_SSR_MAX_LAT, &test_address, &max_lat); EXPECT_TRUE(max_lat == 0x0012); - interop_database_remove_addr_max_lat(INTEROP_UPDATE_HID_SSR_MAX_LAT, - &test_address, 0x0012); + interop_database_remove_addr_max_lat(INTEROP_UPDATE_HID_SSR_MAX_LAT, &test_address, 0x0012); max_lat = 0; - EXPECT_FALSE(interop_database_match_addr_get_max_lat( - INTEROP_UPDATE_HID_SSR_MAX_LAT, &test_address, &max_lat)); + EXPECT_FALSE(interop_database_match_addr_get_max_lat(INTEROP_UPDATE_HID_SSR_MAX_LAT, + &test_address, &max_lat)); EXPECT_FALSE(max_lat == 0x0012); @@ -756,20 +639,15 @@ TEST_F(InteropTest, test_dynamic_manufacturer) { uint16_t manufacturer = 0xFFFF; - EXPECT_FALSE(interop_database_match_manufacturer( - INTEROP_DISABLE_SNIFF_DURING_SCO, manufacturer)); + EXPECT_FALSE(interop_database_match_manufacturer(INTEROP_DISABLE_SNIFF_DURING_SCO, manufacturer)); - interop_database_add_manufacturer(INTEROP_DISABLE_SNIFF_DURING_SCO, - manufacturer); + interop_database_add_manufacturer(INTEROP_DISABLE_SNIFF_DURING_SCO, manufacturer); - EXPECT_TRUE(interop_database_match_manufacturer( - INTEROP_DISABLE_SNIFF_DURING_SCO, manufacturer)); + EXPECT_TRUE(interop_database_match_manufacturer(INTEROP_DISABLE_SNIFF_DURING_SCO, manufacturer)); - interop_database_remove_manufacturer(INTEROP_DISABLE_SNIFF_DURING_SCO, - manufacturer); + interop_database_remove_manufacturer(INTEROP_DISABLE_SNIFF_DURING_SCO, manufacturer); - EXPECT_FALSE(interop_database_match_manufacturer( - INTEROP_DISABLE_SNIFF_DURING_SCO, manufacturer)); + EXPECT_FALSE(interop_database_match_manufacturer(INTEROP_DISABLE_SNIFF_DURING_SCO, manufacturer)); module_clean_up(&interop_module); } @@ -783,26 +661,23 @@ TEST_F(InteropTest, test_dynamic_addr_get_lmp_version) { uint16_t lmp_sub_version = 0; EXPECT_FALSE(interop_database_match_addr_get_lmp_ver( - INTEROP_DISABLE_SNIFF_DURING_SCO, &test_address, &lmp_version, - &lmp_sub_version)); - interop_database_add_addr_lmp_version(INTEROP_DISABLE_SNIFF_DURING_SCO, - &test_address, 0xFF, 0xFFFF); + INTEROP_DISABLE_SNIFF_DURING_SCO, &test_address, &lmp_version, &lmp_sub_version)); + interop_database_add_addr_lmp_version(INTEROP_DISABLE_SNIFF_DURING_SCO, &test_address, 0xFF, + 0xFFFF); EXPECT_TRUE(interop_database_match_addr_get_lmp_ver( - INTEROP_DISABLE_SNIFF_DURING_SCO, &test_address, &lmp_version, - &lmp_sub_version)); + INTEROP_DISABLE_SNIFF_DURING_SCO, &test_address, &lmp_version, &lmp_sub_version)); EXPECT_TRUE(lmp_version == 0xFF && lmp_sub_version == 0xFFFF); - interop_database_remove_addr_lmp_version(INTEROP_DISABLE_SNIFF_DURING_SCO, - &test_address, 0xFF, 0xFFFF); + interop_database_remove_addr_lmp_version(INTEROP_DISABLE_SNIFF_DURING_SCO, &test_address, 0xFF, + 0xFFFF); lmp_version = 0; lmp_sub_version = 0; EXPECT_FALSE(interop_database_match_addr_get_lmp_ver( - INTEROP_DISABLE_SNIFF_DURING_SCO, &test_address, &lmp_version, - &lmp_sub_version)); + INTEROP_DISABLE_SNIFF_DURING_SCO, &test_address, &lmp_version, &lmp_sub_version)); EXPECT_FALSE(lmp_version == 0xFF && lmp_sub_version == 0xFFFF); @@ -816,18 +691,14 @@ TEST_F(InteropTest, test_dynamic_did_version) { RawAddress::FromString("11:22:33:44:55:66", test_address); uint16_t did_version = 0xABCD; - EXPECT_FALSE(interop_database_match_version(INTEROP_DISABLE_SNIFF_DURING_SCO, - did_version)); + EXPECT_FALSE(interop_database_match_version(INTEROP_DISABLE_SNIFF_DURING_SCO, did_version)); interop_database_add_version(INTEROP_DISABLE_SNIFF_DURING_SCO, did_version); - EXPECT_TRUE(interop_database_match_version(INTEROP_DISABLE_SNIFF_DURING_SCO, - did_version)); + EXPECT_TRUE(interop_database_match_version(INTEROP_DISABLE_SNIFF_DURING_SCO, did_version)); - interop_database_remove_version(INTEROP_DISABLE_SNIFF_DURING_SCO, - did_version); + interop_database_remove_version(INTEROP_DISABLE_SNIFF_DURING_SCO, did_version); - EXPECT_FALSE(interop_database_match_version(INTEROP_DISABLE_SNIFF_DURING_SCO, - did_version)); + EXPECT_FALSE(interop_database_match_version(INTEROP_DISABLE_SNIFF_DURING_SCO, did_version)); module_clean_up(&interop_module); } diff --git a/system/embdrv/encoder_for_aptx/include/aptXbtenc.h b/system/embdrv/encoder_for_aptx/include/aptXbtenc.h index bce6ee7527b..d42bb4fc44b 100644 --- a/system/embdrv/encoder_for_aptx/include/aptXbtenc.h +++ b/system/embdrv/encoder_for_aptx/include/aptXbtenc.h @@ -61,8 +61,7 @@ APTXBTENCEXPORT int aptxbtenc_setsync_mode(void* _state, int32_t sync_mode); /* StereoEncode will take 8 audio samples (16-bit per sample) * and generate one 32-bit codeword with autosync inserted. */ -APTXBTENCEXPORT int aptxbtenc_encodestereo(void* _state, void* _pcmL, - void* _pcmR, void* _buffer); +APTXBTENCEXPORT int aptxbtenc_encodestereo(void* _state, void* _pcmL, void* _pcmR, void* _buffer); #ifdef __cplusplus } // /extern "C" diff --git a/system/embdrv/encoder_for_aptx/src/AptxEncoder.h b/system/embdrv/encoder_for_aptx/src/AptxEncoder.h index 229029b4a03..60c20740d10 100644 --- a/system/embdrv/encoder_for_aptx/src/AptxEncoder.h +++ b/system/embdrv/encoder_for_aptx/src/AptxEncoder.h @@ -49,50 +49,38 @@ XBT_INLINE_ void aptxEncode(const int32_t pcm[4], Qmf_storage* Qmf_St, /* Update codeword history, then generate new dither values. */ EncoderDataPt->m_codewordHistory = - xbtEncupdateCodewordHistory(qCodes, EncoderDataPt->m_codewordHistory); - EncoderDataPt->m_dithSyncRandBit = xbtEncgenerateDither( - EncoderDataPt->m_codewordHistory, EncoderDataPt->m_ditherOutputs); + xbtEncupdateCodewordHistory(qCodes, EncoderDataPt->m_codewordHistory); + EncoderDataPt->m_dithSyncRandBit = + xbtEncgenerateDither(EncoderDataPt->m_codewordHistory, EncoderDataPt->m_ditherOutputs); /* Run the analysis QMF */ QmfAnalysisFilter(pcm, Qmf_St, predVals, aqmfOutputs); /* Run the quantiser for each subband */ quantiseDifferenceLL(aqmfOutputs[0], EncoderDataPt->m_ditherOutputs[0], - EncoderDataPt->m_SubbandData[0].m_iqdata.delta, - &EncoderDataPt->m_qdata[0]); + EncoderDataPt->m_SubbandData[0].m_iqdata.delta, &EncoderDataPt->m_qdata[0]); quantiseDifferenceLH(aqmfOutputs[1], EncoderDataPt->m_ditherOutputs[1], - EncoderDataPt->m_SubbandData[1].m_iqdata.delta, - &EncoderDataPt->m_qdata[1]); + EncoderDataPt->m_SubbandData[1].m_iqdata.delta, &EncoderDataPt->m_qdata[1]); quantiseDifferenceHL(aqmfOutputs[2], EncoderDataPt->m_ditherOutputs[2], - EncoderDataPt->m_SubbandData[2].m_iqdata.delta, - &EncoderDataPt->m_qdata[2]); + EncoderDataPt->m_SubbandData[2].m_iqdata.delta, &EncoderDataPt->m_qdata[2]); quantiseDifferenceHH(aqmfOutputs[3], EncoderDataPt->m_ditherOutputs[3], - EncoderDataPt->m_SubbandData[3].m_iqdata.delta, - &EncoderDataPt->m_qdata[3]); + EncoderDataPt->m_SubbandData[3].m_iqdata.delta, &EncoderDataPt->m_qdata[3]); } XBT_INLINE_ void aptxPostEncode(Encoder_data* EncoderDataPt) { /* Run the remaining subband processing for each subband */ /* Manual inlining on the 4 subband */ - processSubbandLL(EncoderDataPt->m_qdata[0].qCode, - EncoderDataPt->m_ditherOutputs[0], - &EncoderDataPt->m_SubbandData[0], - &EncoderDataPt->m_SubbandData[0].m_iqdata); + processSubbandLL(EncoderDataPt->m_qdata[0].qCode, EncoderDataPt->m_ditherOutputs[0], + &EncoderDataPt->m_SubbandData[0], &EncoderDataPt->m_SubbandData[0].m_iqdata); - processSubband(EncoderDataPt->m_qdata[1].qCode, - EncoderDataPt->m_ditherOutputs[1], - &EncoderDataPt->m_SubbandData[1], - &EncoderDataPt->m_SubbandData[1].m_iqdata); + processSubband(EncoderDataPt->m_qdata[1].qCode, EncoderDataPt->m_ditherOutputs[1], + &EncoderDataPt->m_SubbandData[1], &EncoderDataPt->m_SubbandData[1].m_iqdata); - processSubbandHL(EncoderDataPt->m_qdata[2].qCode, - EncoderDataPt->m_ditherOutputs[2], - &EncoderDataPt->m_SubbandData[2], - &EncoderDataPt->m_SubbandData[2].m_iqdata); + processSubbandHL(EncoderDataPt->m_qdata[2].qCode, EncoderDataPt->m_ditherOutputs[2], + &EncoderDataPt->m_SubbandData[2], &EncoderDataPt->m_SubbandData[2].m_iqdata); - processSubband(EncoderDataPt->m_qdata[3].qCode, - EncoderDataPt->m_ditherOutputs[3], - &EncoderDataPt->m_SubbandData[3], - &EncoderDataPt->m_SubbandData[3].m_iqdata); + processSubband(EncoderDataPt->m_qdata[3].qCode, EncoderDataPt->m_ditherOutputs[3], + &EncoderDataPt->m_SubbandData[3], &EncoderDataPt->m_SubbandData[3].m_iqdata); } #ifdef _GCC diff --git a/system/embdrv/encoder_for_aptx/src/AptxTables.h b/system/embdrv/encoder_for_aptx/src/AptxTables.h index 7c017bfcdf4..82cf5fff56e 100644 --- a/system/embdrv/encoder_for_aptx/src/AptxTables.h +++ b/system/embdrv/encoder_for_aptx/src/AptxTables.h @@ -27,126 +27,116 @@ /* Quantisation threshold, logDelta increment and dither tables for 2-bit codes */ static const int32_t dq2bit16_sl1[3] = { - -194080, - 194080, - 890562, + -194080, + 194080, + 890562, }; static const int32_t q2incr16[3] = { - 0, - -33, - 136, + 0, + -33, + 136, }; static const int32_t dq2dith16_sf1[3] = { - 194080, - 194080, - 502402, + 194080, + 194080, + 502402, }; static const int32_t dq2mLamb16[2] = { - 0, - -77081, + 0, + -77081, }; /* Quantisation threshold, logDelta increment and dither tables for 3-bit codes */ static const int32_t dq3bit16_sl1[5] = { - -163006, 163006, 542708, 1120554, 2669238, + -163006, 163006, 542708, 1120554, 2669238, }; static const int32_t q3incr16[5] = { - 0, -8, 33, 95, 262, + 0, -8, 33, 95, 262, }; static const int32_t dq3dith16_sf1[5] = { - 163006, 163006, 216698, 361148, 1187538, + 163006, 163006, 216698, 361148, 1187538, }; static const int32_t dq3mLamb16[4] = { - 0, - -13423, - -36113, - -206598, + 0, + -13423, + -36113, + -206598, }; /* Quantisation threshold, logDelta increment and dither tables for 4-bit codes */ static const int32_t dq4bit16_sl1[9] = { - -89806, 89806, 278502, 494338, 759442, 1113112, 1652322, 2720256, 5190186, + -89806, 89806, 278502, 494338, 759442, 1113112, 1652322, 2720256, 5190186, }; static const int32_t q4incr16[9] = { - 0, -14, 6, 29, 58, 96, 154, 270, 521, + 0, -14, 6, 29, 58, 96, 154, 270, 521, }; static const int32_t dq4dith16_sf1[9] = { - 89806, 89806, 98890, 116946, 148158, 205512, 333698, 734236, 1735696, + 89806, 89806, 98890, 116946, 148158, 205512, 333698, 734236, 1735696, }; static const int32_t dq4mLamb16[8] = { - 0, -2271, -4514, -7803, -14339, -32047, -100135, -250365, + 0, -2271, -4514, -7803, -14339, -32047, -100135, -250365, }; /* Quantisation threshold, logDelta increment and dither tables for 7-bit codes */ static const int32_t dq7bit16_sl1[65] = { - -9948, 9948, 29860, 49808, 69822, 89926, 110144, 130502, - 151026, 171738, 192666, 213832, 235264, 256982, 279014, 301384, - 324118, 347244, 370790, 394782, 419250, 444226, 469742, 495832, - 522536, 549890, 577936, 606720, 636290, 666700, 698006, 730270, - 763562, 797958, 833538, 870398, 908640, 948376, 989740, 1032874, - 1077948, 1125150, 1174700, 1226850, 1281900, 1340196, 1402156, 1468282, - 1539182, 1615610, 1698514, 1789098, 1888944, 2000168, 2125700, 2269750, - 2438670, 2642660, 2899462, 3243240, 3746078, 4535138, 5664098, 7102424, - 8897462, + -9948, 9948, 29860, 49808, 69822, 89926, 110144, 130502, 151026, 171738, + 192666, 213832, 235264, 256982, 279014, 301384, 324118, 347244, 370790, 394782, + 419250, 444226, 469742, 495832, 522536, 549890, 577936, 606720, 636290, 666700, + 698006, 730270, 763562, 797958, 833538, 870398, 908640, 948376, 989740, 1032874, + 1077948, 1125150, 1174700, 1226850, 1281900, 1340196, 1402156, 1468282, 1539182, 1615610, + 1698514, 1789098, 1888944, 2000168, 2125700, 2269750, 2438670, 2642660, 2899462, 3243240, + 3746078, 4535138, 5664098, 7102424, 8897462, }; static const int32_t q7incr16[65] = { - 0, -21, -19, -17, -15, -12, -10, -8, -6, -4, -1, 1, 3, - 6, 8, 10, 13, 15, 18, 20, 23, 26, 29, 31, 34, 37, - 40, 43, 47, 50, 53, 57, 60, 64, 68, 72, 76, 80, 85, - 89, 94, 99, 105, 110, 116, 123, 129, 136, 144, 152, 161, 171, - 182, 194, 207, 223, 241, 263, 291, 328, 382, 467, 522, 522, 522, + 0, -21, -19, -17, -15, -12, -10, -8, -6, -4, -1, 1, 3, 6, 8, 10, 13, + 15, 18, 20, 23, 26, 29, 31, 34, 37, 40, 43, 47, 50, 53, 57, 60, 64, + 68, 72, 76, 80, 85, 89, 94, 99, 105, 110, 116, 123, 129, 136, 144, 152, 161, + 171, 182, 194, 207, 223, 241, 263, 291, 328, 382, 467, 522, 522, 522, }; static const int32_t dq7dith16_sf1[65] = { - 9948, 9948, 9962, 9988, 10026, 10078, 10142, 10218, 10306, - 10408, 10520, 10646, 10784, 10934, 11098, 11274, 11462, 11664, - 11880, 12112, 12358, 12618, 12898, 13194, 13510, 13844, 14202, - 14582, 14988, 15422, 15884, 16380, 16912, 17484, 18098, 18762, - 19480, 20258, 21106, 22030, 23044, 24158, 25390, 26760, 28290, - 30008, 31954, 34172, 36728, 39700, 43202, 47382, 52462, 58762, - 66770, 77280, 91642, 112348, 144452, 199326, 303512, 485546, 643414, - 794914, 1000124, + 9948, 9948, 9962, 9988, 10026, 10078, 10142, 10218, 10306, 10408, 10520, + 10646, 10784, 10934, 11098, 11274, 11462, 11664, 11880, 12112, 12358, 12618, + 12898, 13194, 13510, 13844, 14202, 14582, 14988, 15422, 15884, 16380, 16912, + 17484, 18098, 18762, 19480, 20258, 21106, 22030, 23044, 24158, 25390, 26760, + 28290, 30008, 31954, 34172, 36728, 39700, 43202, 47382, 52462, 58762, 66770, + 77280, 91642, 112348, 144452, 199326, 303512, 485546, 643414, 794914, 1000124, }; static const int32_t dq7mLamb16[65] = { - 0, -4, -7, -10, -13, -16, -19, -22, -26, -28, - -32, -35, -38, -41, -44, -47, -51, -54, -58, -62, - -65, -70, -74, -79, -84, -90, -95, -102, -109, -116, - -124, -133, -143, -154, -166, -180, -195, -212, -231, -254, - -279, -308, -343, -383, -430, -487, -555, -639, -743, -876, - -1045, -1270, -1575, -2002, -2628, -3591, -5177, -8026, -13719, -26047, - -45509, -39467, -37875, -51303, 0, + 0, -4, -7, -10, -13, -16, -19, -22, -26, -28, -32, + -35, -38, -41, -44, -47, -51, -54, -58, -62, -65, -70, + -74, -79, -84, -90, -95, -102, -109, -116, -124, -133, -143, + -154, -166, -180, -195, -212, -231, -254, -279, -308, -343, -383, + -430, -487, -555, -639, -743, -876, -1045, -1270, -1575, -2002, -2628, + -3591, -5177, -8026, -13719, -26047, -45509, -39467, -37875, -51303, 0, }; /* Array of structures containing subband parameters. */ static const SubbandParameters subbandParameters[NUMSUBBANDS] = { - /* LL band */ - {0, dq7bit16_sl1, 0, dq7dith16_sf1, dq7mLamb16, q7incr16, 7, (18 * 256) - 1, - -20, 24}, + /* LL band */ + {0, dq7bit16_sl1, 0, dq7dith16_sf1, dq7mLamb16, q7incr16, 7, (18 * 256) - 1, -20, 24}, - /* LH band */ - {0, dq4bit16_sl1, 0, dq4dith16_sf1, dq4mLamb16, q4incr16, 4, (21 * 256) - 1, - -23, 12}, + /* LH band */ + {0, dq4bit16_sl1, 0, dq4dith16_sf1, dq4mLamb16, q4incr16, 4, (21 * 256) - 1, -23, 12}, - /* HL band */ - {0, dq2bit16_sl1, 0, dq2dith16_sf1, dq2mLamb16, q2incr16, 2, (23 * 256) - 1, - -25, 6}, + /* HL band */ + {0, dq2bit16_sl1, 0, dq2dith16_sf1, dq2mLamb16, q2incr16, 2, (23 * 256) - 1, -25, 6}, - /* HH band */ - {0, dq3bit16_sl1, 0, dq3dith16_sf1, dq3mLamb16, q3incr16, 3, (22 * 256) - 1, - -24, 12}}; + /* HH band */ + {0, dq3bit16_sl1, 0, dq3dith16_sf1, dq3mLamb16, q3incr16, 3, (22 * 256) - 1, -24, 12}}; #endif // APTXTABLES_H diff --git a/system/embdrv/encoder_for_aptx/src/CodewordPacker.h b/system/embdrv/encoder_for_aptx/src/CodewordPacker.h index a4b96ebf95c..ec24ec94735 100644 --- a/system/embdrv/encoder_for_aptx/src/CodewordPacker.h +++ b/system/embdrv/encoder_for_aptx/src/CodewordPacker.h @@ -27,8 +27,7 @@ #include "AptxParameters.h" -XBT_INLINE_ int16_t packCodeword(Encoder_data* EncoderDataPt, - uint32_t aligned) { +XBT_INLINE_ int16_t packCodeword(Encoder_data* EncoderDataPt, uint32_t aligned) { int32_t syncContribution; int32_t hhCode; int32_t codeword; @@ -39,19 +38,17 @@ XBT_INLINE_ int16_t packCodeword(Encoder_data* EncoderDataPt, * channel give the actual sync bit value. The per-channel sync bit * contribution overwrites the HH code lsb in the packed codeword. */ if (aligned != no_sync) { - syncContribution = - (EncoderDataPt->m_qdata[0].qCode ^ EncoderDataPt->m_qdata[1].qCode ^ - EncoderDataPt->m_qdata[2].qCode ^ EncoderDataPt->m_qdata[3].qCode ^ - EncoderDataPt->m_dithSyncRandBit) & - 0x1; + syncContribution = (EncoderDataPt->m_qdata[0].qCode ^ EncoderDataPt->m_qdata[1].qCode ^ + EncoderDataPt->m_qdata[2].qCode ^ EncoderDataPt->m_qdata[3].qCode ^ + EncoderDataPt->m_dithSyncRandBit) & + 0x1; hhCode = (EncoderDataPt->m_qdata[HH].qCode & 0x6) | syncContribution; /* Pack the 16-bit codeword with the appropriate number of lsbs from each * quantised code (LL=7, LH=4, HL=2, HH=3). */ codeword = (EncoderDataPt->m_qdata[LL].qCode & 0x7fL) | ((EncoderDataPt->m_qdata[LH].qCode & 0xfL) << 7) | - ((EncoderDataPt->m_qdata[HL].qCode & 0x3L) << 11) | - (hhCode << 13); + ((EncoderDataPt->m_qdata[HL].qCode & 0x3L) << 11) | (hhCode << 13); } else { // don't add sync contribution for non-autosync mode codeword = (EncoderDataPt->m_qdata[LL].qCode & 0x7fL) | ((EncoderDataPt->m_qdata[LH].qCode & 0xfL) << 7) | diff --git a/system/embdrv/encoder_for_aptx/src/DitherGenerator.h b/system/embdrv/encoder_for_aptx/src/DitherGenerator.h index baa5605491f..4a6c80a17a7 100644 --- a/system/embdrv/encoder_for_aptx/src/DitherGenerator.h +++ b/system/embdrv/encoder_for_aptx/src/DitherGenerator.h @@ -44,23 +44,20 @@ XBT_INLINE_ int32_t xbtEncupdateCodewordHistory(const int32_t quantisedCodes[4], const uint32_t numNewBits = 4; /* Make a 4-bit vector from particular bits from 3 quantised codes */ - newBits = (quantisedCodes[LL] & llMask) + - ((quantisedCodes[LH] & lhMask) << lhShift) + + newBits = (quantisedCodes[LL] & llMask) + ((quantisedCodes[LH] & lhMask) << lhShift) + ((quantisedCodes[HL] & hlMask) << hlShift); /* Add the 4 new bits to the codeword history. Note that this is a 24-bit * value LEFT-JUSTIFIED in a 32-bit signed variable. Maintaining the history * as signed is useful in the dither generation process below. */ - updatedCodewordHistory = - (m_codewordHistory << numNewBits) + (newBits << leftJustifyShift); + updatedCodewordHistory = (m_codewordHistory << numNewBits) + (newBits << leftJustifyShift); return updatedCodewordHistory; } /* Function to generate a dither value for each subband based * on the current contents of the codewordHistory bit-pool. */ -XBT_INLINE_ int32_t xbtEncgenerateDither(int32_t m_codewordHistory, - int32_t* m_ditherOutputs) { +XBT_INLINE_ int32_t xbtEncgenerateDither(int32_t m_codewordHistory, int32_t* m_ditherOutputs) { int32_t history24b; int32_t upperAcc; int32_t lowerAcc; @@ -110,6 +107,6 @@ XBT_INLINE_ int32_t xbtEncgenerateDither(int32_t m_codewordHistory, m_ditherOutputs[LL] = ditherSample << (15 + leftJustifyShift); return m_dithSyncRandBit; -}; +} #endif // DITHERGENERATOR_H diff --git a/system/embdrv/encoder_for_aptx/src/ProcessSubband.c b/system/embdrv/encoder_for_aptx/src/ProcessSubband.c index e1cc1e35f49..f0a6ef1a93d 100644 --- a/system/embdrv/encoder_for_aptx/src/ProcessSubband.c +++ b/system/embdrv/encoder_for_aptx/src/ProcessSubband.c @@ -19,14 +19,13 @@ /* This function carries out all subband processing (common to both encode and * decode). */ -void processSubband(const int32_t qCode, const int32_t ditherVal, - Subband_data* SubbandDataPt, IQuantiser_data* iqDataPt) { +void processSubband(const int32_t qCode, const int32_t ditherVal, Subband_data* SubbandDataPt, + IQuantiser_data* iqDataPt) { /* Inverse quantisation */ invertQuantisation(qCode, ditherVal, iqDataPt); /* Predictor pole coefficient update */ - updatePredictorPoleCoefficients(iqDataPt->invQ, - SubbandDataPt->m_predData.m_zeroVal, + updatePredictorPoleCoefficients(iqDataPt->invQ, SubbandDataPt->m_predData.m_zeroVal, &SubbandDataPt->m_PoleCoeffData); /* Predictor filtering */ @@ -34,14 +33,13 @@ void processSubband(const int32_t qCode, const int32_t ditherVal, } /* processSubbandLL is used for the LL subband only. */ -void processSubbandLL(const int32_t qCode, const int32_t ditherVal, - Subband_data* SubbandDataPt, IQuantiser_data* iqDataPt) { +void processSubbandLL(const int32_t qCode, const int32_t ditherVal, Subband_data* SubbandDataPt, + IQuantiser_data* iqDataPt) { /* Inverse quantisation */ invertQuantisation(qCode, ditherVal, iqDataPt); /* Predictor pole coefficient update */ - updatePredictorPoleCoefficients(iqDataPt->invQ, - SubbandDataPt->m_predData.m_zeroVal, + updatePredictorPoleCoefficients(iqDataPt->invQ, SubbandDataPt->m_predData.m_zeroVal, &SubbandDataPt->m_PoleCoeffData); /* Predictor filtering */ @@ -49,14 +47,13 @@ void processSubbandLL(const int32_t qCode, const int32_t ditherVal, } /* processSubbandHL is used for the HL subband only. */ -void processSubbandHL(const int32_t qCode, const int32_t ditherVal, - Subband_data* SubbandDataPt, IQuantiser_data* iqDataPt) { +void processSubbandHL(const int32_t qCode, const int32_t ditherVal, Subband_data* SubbandDataPt, + IQuantiser_data* iqDataPt) { /* Inverse quantisation */ invertQuantisationHL(qCode, ditherVal, iqDataPt); /* Predictor pole coefficient update */ - updatePredictorPoleCoefficients(iqDataPt->invQ, - SubbandDataPt->m_predData.m_zeroVal, + updatePredictorPoleCoefficients(iqDataPt->invQ, SubbandDataPt->m_predData.m_zeroVal, &SubbandDataPt->m_PoleCoeffData); /* Predictor filtering */ diff --git a/system/embdrv/encoder_for_aptx/src/Qmf.h b/system/embdrv/encoder_for_aptx/src/Qmf.h index 0d7fa7f8d06..4a57289b268 100644 --- a/system/embdrv/encoder_for_aptx/src/Qmf.h +++ b/system/embdrv/encoder_for_aptx/src/Qmf.h @@ -41,45 +41,44 @@ typedef struct { * different coefficients). The table in defined in QmfConv.c */ #ifndef _STDQMFOUTERCOEFF static const int32_t Qmf_outerCoeffs[12] = { - /* (C(1/30)C(3/28)), C(5/26), C(7/24) */ - 0xFE6302DA, - 0xFFFFDA75, - 0x0000AA6A, - /* C(9/22), C(11/20), C(13/18), C(15/16) */ - 0xFFFE273E, - 0x00041E95, - 0xFFF710B5, - 0x002AC12E, - /* C(17/14), C(19/12), (C(21/10)C(23/8)) */ - 0x000AA328, - 0xFFFD8D1F, - 0x211E6BDB, - /* (C(25/6)C(27/4)), (C(29/2)C(31/0)) */ - 0x0DB7D8C5, - 0xFC7F02B0, + /* (C(1/30)C(3/28)), C(5/26), C(7/24) */ + 0xFE6302DA, + 0xFFFFDA75, + 0x0000AA6A, + /* C(9/22), C(11/20), C(13/18), C(15/16) */ + 0xFFFE273E, + 0x00041E95, + 0xFFF710B5, + 0x002AC12E, + /* C(17/14), C(19/12), (C(21/10)C(23/8)) */ + 0x000AA328, + 0xFFFD8D1F, + 0x211E6BDB, + /* (C(25/6)C(27/4)), (C(29/2)C(31/0)) */ + 0x0DB7D8C5, + 0xFC7F02B0, }; #else static const int32_t Qmf_outerCoeffs[16] = { - 730, -413, -9611, 43626, -121026, 269973, -585547, 2801966, - 697128, -160481, 27611, 8478, -10043, 3511, 688, -897, + 730, -413, -9611, 43626, -121026, 269973, -585547, 2801966, + 697128, -160481, 27611, 8478, -10043, 3511, 688, -897, }; #endif /* Each inner QMF filter for Enhanced aptX is a symmetrical 32-tap filter (16 * different coefficients) */ static const int32_t Qmf_innerCoeffs[16] = { - 1033, -584, -13592, 61697, -171156, 381799, -828088, 3962579, - 985888, -226954, 39048, 11990, -14203, 4966, 973, -1268, + 1033, -584, -13592, 61697, -171156, 381799, -828088, 3962579, + 985888, -226954, 39048, 11990, -14203, 4966, 973, -1268, }; -void AsmQmfConvI(const int32_t* p1dl_buffPtr, const int32_t* p2dl_buffPtr, - const int32_t* coeffPtr, int32_t* filterOutputs); -void AsmQmfConvO(const int16_t* p1dl_buffPtr, const int16_t* p2dl_buffPtr, - const int32_t* coeffPtr, int32_t* convSumDiff); +void AsmQmfConvI(const int32_t* p1dl_buffPtr, const int32_t* p2dl_buffPtr, const int32_t* coeffPtr, + int32_t* filterOutputs); +void AsmQmfConvO(const int16_t* p1dl_buffPtr, const int16_t* p2dl_buffPtr, const int32_t* coeffPtr, + int32_t* convSumDiff); XBT_INLINE_ void QmfAnalysisFilter(const int32_t pcm[4], Qmf_storage* Qmf_St, - const int32_t predVals[4], - int32_t* aqmfOutputs) { + const int32_t predVals[4], int32_t* aqmfOutputs) { int32_t convSumDiff[4]; int32_t filterOutputs[4]; @@ -98,8 +97,8 @@ XBT_INLINE_ void QmfAnalysisFilter(const int32_t pcm[4], Qmf_storage* Qmf_St, Qmf_St->QmfH_buf[lc_QmfO_pt++] = (int16_t)pcm[SecondPcm]; lc_QmfO_pt &= 0xF; - AsmQmfConvO(&Qmf_St->QmfL_buf[lc_QmfO_pt + 15], &Qmf_St->QmfH_buf[lc_QmfO_pt], - Qmf_outerCoeffs, &convSumDiff[0]); + AsmQmfConvO(&Qmf_St->QmfL_buf[lc_QmfO_pt + 15], &Qmf_St->QmfH_buf[lc_QmfO_pt], Qmf_outerCoeffs, + &convSumDiff[0]); /* Load outer filter phase1 and phase2 delay lines with the second 2 PCM * samples. Convolve the filter and get the 2 convolution results. */ @@ -109,8 +108,8 @@ XBT_INLINE_ void QmfAnalysisFilter(const int32_t pcm[4], Qmf_storage* Qmf_St, Qmf_St->QmfH_buf[lc_QmfO_pt++] = (int16_t)pcm[FourthPcm]; lc_QmfO_pt &= 0xF; - AsmQmfConvO(&Qmf_St->QmfL_buf[lc_QmfO_pt + 15], &Qmf_St->QmfH_buf[lc_QmfO_pt], - Qmf_outerCoeffs, &convSumDiff[1]); + AsmQmfConvO(&Qmf_St->QmfL_buf[lc_QmfO_pt + 15], &Qmf_St->QmfH_buf[lc_QmfO_pt], Qmf_outerCoeffs, + &convSumDiff[1]); /* Load the first inner filter phase1 and phase2 delay lines with the 2 * convolution sum (low-pass) outer filter outputs. Convolve the filter and @@ -121,9 +120,8 @@ XBT_INLINE_ void QmfAnalysisFilter(const int32_t pcm[4], Qmf_storage* Qmf_St, Qmf_St->QmfLH_buf[lc_QmfI_pt + 16] = convSumDiff[1]; Qmf_St->QmfLH_buf[lc_QmfI_pt] = convSumDiff[1]; - AsmQmfConvI(&Qmf_St->QmfLL_buf[lc_QmfI_pt + 16], - &Qmf_St->QmfLH_buf[lc_QmfI_pt + 1], &Qmf_innerCoeffs[0], - &filterOutputs[LL]); + AsmQmfConvI(&Qmf_St->QmfLL_buf[lc_QmfI_pt + 16], &Qmf_St->QmfLH_buf[lc_QmfI_pt + 1], + &Qmf_innerCoeffs[0], &filterOutputs[LL]); /* Load the second inner filter phase1 and phase2 delay lines with the 2 * convolution difference (high-pass) outer filter outputs. Convolve the @@ -136,9 +134,8 @@ XBT_INLINE_ void QmfAnalysisFilter(const int32_t pcm[4], Qmf_storage* Qmf_St, Qmf_St->QmfHH_buf[lc_QmfI_pt++] = convSumDiff[3]; lc_QmfI_pt &= 0xF; - AsmQmfConvI(&Qmf_St->QmfHL_buf[lc_QmfI_pt + 15], - &Qmf_St->QmfHH_buf[lc_QmfI_pt], &Qmf_innerCoeffs[0], - &filterOutputs[HL]); + AsmQmfConvI(&Qmf_St->QmfHL_buf[lc_QmfI_pt + 15], &Qmf_St->QmfHH_buf[lc_QmfI_pt], + &Qmf_innerCoeffs[0], &filterOutputs[HL]); /* Subtracted the previous predicted value from the filter output on a * per-subband basis. Ensure these values are saturated, if necessary. diff --git a/system/embdrv/encoder_for_aptx/src/QmfConv.c b/system/embdrv/encoder_for_aptx/src/QmfConv.c index 4f24d1e894f..d68e059c903 100644 --- a/system/embdrv/encoder_for_aptx/src/QmfConv.c +++ b/system/embdrv/encoder_for_aptx/src/QmfConv.c @@ -21,8 +21,8 @@ #include "Qmf.h" -void AsmQmfConvO(const int16_t* p1dl_buffPtr, const int16_t* p2dl_buffPtr, - const int32_t* coeffPtr, int32_t* convSumDiff) { +void AsmQmfConvO(const int16_t* p1dl_buffPtr, const int16_t* p2dl_buffPtr, const int32_t* coeffPtr, + int32_t* convSumDiff) { /* Since all manipulated data are "int16_t" it is possible to * reduce the number of loads by using int32_t type and manipulating * pairs of data @@ -191,8 +191,8 @@ void AsmQmfConvO(const int16_t* p1dl_buffPtr, const int16_t* p2dl_buffPtr, *(convSumDiff + 2) = convDiff; } -void AsmQmfConvI(const int32_t* p1dl_buffPtr, const int32_t* p2dl_buffPtr, - const int32_t* coeffPtr, int32_t* filterOutputs) { +void AsmQmfConvI(const int32_t* p1dl_buffPtr, const int32_t* p2dl_buffPtr, const int32_t* coeffPtr, + int32_t* filterOutputs) { int32_t acc; // WARNING: This inlining assumes that m_qmfDelayLineLength == 16 int32_t tmp_round0; @@ -309,7 +309,7 @@ void AsmQmfConvI(const int32_t* p1dl_buffPtr, const int32_t* p2dl_buffPtr, local_acc0 += 0x00400000L; acc = (int32_t)(local_acc0 >> 23); - if ((((tmp_round0 << 8) ^ 0x40000000) == 0)) { + if (((tmp_round0 << 8) ^ 0x40000000) == 0) { acc--; } @@ -325,7 +325,7 @@ void AsmQmfConvI(const int32_t* p1dl_buffPtr, const int32_t* p2dl_buffPtr, local_acc1 += 0x00400000L; acc = (int32_t)(local_acc1 >> 23); - if ((((tmp_round0 << 8) ^ 0x40000000) == 0)) { + if (((tmp_round0 << 8) ^ 0x40000000) == 0) { acc--; } diff --git a/system/embdrv/encoder_for_aptx/src/QuantiseDifference.c b/system/embdrv/encoder_for_aptx/src/QuantiseDifference.c index 5f6c865859b..d0179ce2ef7 100644 --- a/system/embdrv/encoder_for_aptx/src/QuantiseDifference.c +++ b/system/embdrv/encoder_for_aptx/src/QuantiseDifference.c @@ -17,8 +17,7 @@ #include "AptxTables.h" #include "Quantiser.h" -XBT_INLINE_ int32_t BsearchLL(const int32_t absDiffSignalShifted, - const int32_t delta, +XBT_INLINE_ int32_t BsearchLL(const int32_t absDiffSignalShifted, const int32_t delta, const int32_t* dqbitTablePrt) { int32_t qCode; reg64_t tmp_acc; @@ -68,22 +67,20 @@ XBT_INLINE_ int32_t BsearchLL(const int32_t absDiffSignalShifted, qCode++; } - return (qCode); + return qCode; } -XBT_INLINE_ int32_t BsearchHL(const int32_t absDiffSignalShifted, - const int32_t delta) { +XBT_INLINE_ int32_t BsearchHL(const int32_t absDiffSignalShifted, const int32_t delta) { reg64_t tmp_acc; int32_t lc_delta = delta << 8; /* first iteration */ tmp_acc.s64 = (int64_t)lc_delta * (int64_t)(97040 << 1); tmp_acc.s32.h -= absDiffSignalShifted; - return (tmp_acc.s64 <= 0); + return tmp_acc.s64 <= 0; } -XBT_INLINE_ int32_t BsearchHH(const int32_t absDiffSignalShifted, - const int32_t delta, +XBT_INLINE_ int32_t BsearchHH(const int32_t absDiffSignalShifted, const int32_t delta, const int32_t* dqbitTablePrt) { int32_t qCode; reg64_t tmp_acc; @@ -105,11 +102,10 @@ XBT_INLINE_ int32_t BsearchHH(const int32_t absDiffSignalShifted, qCode++; } - return (qCode); + return qCode; } -XBT_INLINE_ int32_t BsearchLH(const int32_t absDiffSignalShifted, - const int32_t delta, +XBT_INLINE_ int32_t BsearchLH(const int32_t absDiffSignalShifted, const int32_t delta, const int32_t* dqbitTablePrt) { int32_t qCode; reg64_t tmp_acc; @@ -139,11 +135,11 @@ XBT_INLINE_ int32_t BsearchLH(const int32_t absDiffSignalShifted, qCode++; } - return (qCode); + return qCode; } -void quantiseDifferenceHL(const int32_t diffSignal, const int32_t ditherVal, - const int32_t delta, Quantiser_data* qdata_pt) { +void quantiseDifferenceHL(const int32_t diffSignal, const int32_t ditherVal, const int32_t delta, + Quantiser_data* qdata_pt) { int32_t absDiffSignal; int32_t absDiffSignalShifted; int32_t index; @@ -233,8 +229,7 @@ void quantiseDifferenceHL(const int32_t diffSignal, const int32_t ditherVal, /* Form the threshold table difference at index and index-1. Ensure * saturation is applied to the difference calculation. */ - threshDiff = qdata_pt->thresholdTablePtr_sl1[index + 1] - - qdata_pt->thresholdTablePtr_sl1[index]; + threshDiff = qdata_pt->thresholdTablePtr_sl1[index + 1] - qdata_pt->thresholdTablePtr_sl1[index]; /* Based on the sign of the difference signal, either add or subtract the * threshold table difference from the accumulated value. Recover the final @@ -299,8 +294,8 @@ void quantiseDifferenceHL(const int32_t diffSignal, const int32_t ditherVal, qdata_pt->qCode = tmp_qCode; } -void quantiseDifferenceHH(const int32_t diffSignal, const int32_t ditherVal, - const int32_t delta, Quantiser_data* qdata_pt) { +void quantiseDifferenceHH(const int32_t diffSignal, const int32_t ditherVal, const int32_t delta, + Quantiser_data* qdata_pt) { int32_t absDiffSignal; int32_t absDiffSignalShifted; int32_t index; @@ -330,8 +325,7 @@ void quantiseDifferenceHH(const int32_t diffSignal, const int32_t ditherVal, * table index of the LARGEST threshold table value for which * absDiffSignalShifted >= (delta * threshold) */ - index = - BsearchHH(absDiffSignalShifted, delta, qdata_pt->thresholdTablePtr_sl1); + index = BsearchHH(absDiffSignalShifted, delta, qdata_pt->thresholdTablePtr_sl1); /* We actually wanted the SMALLEST magnitude quantised code for which * absDiffSignalShifted < (delta * threshold) @@ -391,8 +385,7 @@ void quantiseDifferenceHH(const int32_t diffSignal, const int32_t ditherVal, /* Form the threshold table difference at index and index-1. Ensure * saturation is applied to the difference calculation. */ - threshDiff = qdata_pt->thresholdTablePtr_sl1[index + 1] - - qdata_pt->thresholdTablePtr_sl1[index]; + threshDiff = qdata_pt->thresholdTablePtr_sl1[index + 1] - qdata_pt->thresholdTablePtr_sl1[index]; /* Based on the sign of the difference signal, either add or subtract the * threshold table difference from the accumulated value. Recover the final @@ -456,8 +449,8 @@ void quantiseDifferenceHH(const int32_t diffSignal, const int32_t ditherVal, qdata_pt->qCode = tmp_qCode; } -void quantiseDifferenceLL(const int32_t diffSignal, const int32_t ditherVal, - const int32_t delta, Quantiser_data* qdata_pt) { +void quantiseDifferenceLL(const int32_t diffSignal, const int32_t ditherVal, const int32_t delta, + Quantiser_data* qdata_pt) { int32_t absDiffSignal; int32_t absDiffSignalShifted; int32_t index; @@ -486,8 +479,7 @@ void quantiseDifferenceLL(const int32_t diffSignal, const int32_t ditherVal, * table index of the LARGEST threshold table value for which * absDiffSignalShifted >= (delta * threshold) */ - index = - BsearchLL(absDiffSignalShifted, delta, qdata_pt->thresholdTablePtr_sl1); + index = BsearchLL(absDiffSignalShifted, delta, qdata_pt->thresholdTablePtr_sl1); /* We actually wanted the SMALLEST magnitude quantised code for which * absDiffSignalShifted < (delta * threshold) @@ -548,8 +540,7 @@ void quantiseDifferenceLL(const int32_t diffSignal, const int32_t ditherVal, /* Form the threshold table difference at index and index-1. Ensure * saturation is applied to the difference calculation. */ - threshDiff = qdata_pt->thresholdTablePtr_sl1[index + 1] - - qdata_pt->thresholdTablePtr_sl1[index]; + threshDiff = qdata_pt->thresholdTablePtr_sl1[index + 1] - qdata_pt->thresholdTablePtr_sl1[index]; /* Based on the sign of the difference signal, either add or subtract the * threshold table difference from the accumulated value. Recover the final @@ -614,8 +605,8 @@ void quantiseDifferenceLL(const int32_t diffSignal, const int32_t ditherVal, qdata_pt->qCode = tmp_qCode; } -void quantiseDifferenceLH(const int32_t diffSignal, const int32_t ditherVal, - const int32_t delta, Quantiser_data* qdata_pt) { +void quantiseDifferenceLH(const int32_t diffSignal, const int32_t ditherVal, const int32_t delta, + Quantiser_data* qdata_pt) { int32_t absDiffSignal; int32_t absDiffSignalShifted; int32_t index; @@ -644,8 +635,7 @@ void quantiseDifferenceLH(const int32_t diffSignal, const int32_t ditherVal, * table index of the LARGEST threshold table value for which * absDiffSignalShifted >= (delta * threshold) */ - index = - BsearchLH(absDiffSignalShifted, delta, qdata_pt->thresholdTablePtr_sl1); + index = BsearchLH(absDiffSignalShifted, delta, qdata_pt->thresholdTablePtr_sl1); /* We actually wanted the SMALLEST magnitude quantised code for which * absDiffSignalShifted < (delta * threshold) @@ -703,8 +693,7 @@ void quantiseDifferenceLH(const int32_t diffSignal, const int32_t ditherVal, /* Form the threshold table difference at index and index-1. Ensure * saturation is applied to the difference calculation. */ - threshDiff = qdata_pt->thresholdTablePtr_sl1[index + 1] - - qdata_pt->thresholdTablePtr_sl1[index]; + threshDiff = qdata_pt->thresholdTablePtr_sl1[index + 1] - qdata_pt->thresholdTablePtr_sl1[index]; /* Based on the sign of the difference signal, either add or subtract the * threshold table difference from the accumulated value. Recover the final diff --git a/system/embdrv/encoder_for_aptx/src/Quantiser.h b/system/embdrv/encoder_for_aptx/src/Quantiser.h index 16f0416c076..a9399c94bc8 100644 --- a/system/embdrv/encoder_for_aptx/src/Quantiser.h +++ b/system/embdrv/encoder_for_aptx/src/Quantiser.h @@ -28,14 +28,14 @@ #include "AptxParameters.h" -void quantiseDifferenceLL(const int32_t diffSignal, const int32_t ditherVal, - const int32_t delta, Quantiser_data* qdata_pt); -void quantiseDifferenceHL(const int32_t diffSignal, const int32_t ditherVal, - const int32_t delta, Quantiser_data* qdata_pt); -void quantiseDifferenceLH(const int32_t diffSignal, const int32_t ditherVal, - const int32_t delta, Quantiser_data* qdata_pt); -void quantiseDifferenceHH(const int32_t diffSignal, const int32_t ditherVal, - const int32_t delta, Quantiser_data* qdata_pt); +void quantiseDifferenceLL(const int32_t diffSignal, const int32_t ditherVal, const int32_t delta, + Quantiser_data* qdata_pt); +void quantiseDifferenceHL(const int32_t diffSignal, const int32_t ditherVal, const int32_t delta, + Quantiser_data* qdata_pt); +void quantiseDifferenceLH(const int32_t diffSignal, const int32_t ditherVal, const int32_t delta, + Quantiser_data* qdata_pt); +void quantiseDifferenceHH(const int32_t diffSignal, const int32_t ditherVal, const int32_t delta, + Quantiser_data* qdata_pt); #ifdef _GCC #pragma GCC visibility pop diff --git a/system/embdrv/encoder_for_aptx/src/SubbandFunctions.h b/system/embdrv/encoder_for_aptx/src/SubbandFunctions.h index ef5bee8d6a0..5ec5775c5f8 100644 --- a/system/embdrv/encoder_for_aptx/src/SubbandFunctions.h +++ b/system/embdrv/encoder_for_aptx/src/SubbandFunctions.h @@ -30,9 +30,8 @@ #include "AptxParameters.h" -XBT_INLINE_ void updatePredictorPoleCoefficients( - const int32_t invQ, const int32_t prevZfiltOutput, - PoleCoeff_data* PoleCoeffDataPt) { +XBT_INLINE_ void updatePredictorPoleCoefficients(const int32_t invQ, const int32_t prevZfiltOutput, + PoleCoeff_data* PoleCoeffDataPt) { int32_t adaptSum; int32_t sgnP[3]; int32_t newCoeffs[2]; @@ -68,22 +67,19 @@ XBT_INLINE_ void updatePredictorPoleCoefficients( sgnP[k] = minusOneQ22; sgnP[k_1] = -(((int32_t)PoleCoeffDataPt->m_poleAdaptDelayLine.s16.l) << 22); sgnP[k_2] = -(((int32_t)PoleCoeffDataPt->m_poleAdaptDelayLine.s16.h) << 22); - PoleCoeffDataPt->m_poleAdaptDelayLine.s16.h = - PoleCoeffDataPt->m_poleAdaptDelayLine.s16.l; + PoleCoeffDataPt->m_poleAdaptDelayLine.s16.h = PoleCoeffDataPt->m_poleAdaptDelayLine.s16.l; PoleCoeffDataPt->m_poleAdaptDelayLine.s16.l = -1; } else if (adaptSum == 0L) { sgnP[k] = 0L; sgnP[k_1] = 0L; sgnP[k_2] = 0L; - PoleCoeffDataPt->m_poleAdaptDelayLine.s16.h = - PoleCoeffDataPt->m_poleAdaptDelayLine.s16.l; + PoleCoeffDataPt->m_poleAdaptDelayLine.s16.h = PoleCoeffDataPt->m_poleAdaptDelayLine.s16.l; PoleCoeffDataPt->m_poleAdaptDelayLine.s16.l = 1; } else { // adaptSum > 0L sgnP[k] = oneQ22; sgnP[k_1] = ((int32_t)PoleCoeffDataPt->m_poleAdaptDelayLine.s16.l) << 22; sgnP[k_2] = ((int32_t)PoleCoeffDataPt->m_poleAdaptDelayLine.s16.h) << 22; - PoleCoeffDataPt->m_poleAdaptDelayLine.s16.h = - PoleCoeffDataPt->m_poleAdaptDelayLine.s16.l; + PoleCoeffDataPt->m_poleAdaptDelayLine.s16.h = PoleCoeffDataPt->m_poleAdaptDelayLine.s16.l; PoleCoeffDataPt->m_poleAdaptDelayLine.s16.l = 1; } diff --git a/system/embdrv/encoder_for_aptx/src/SubbandFunctionsCommon.h b/system/embdrv/encoder_for_aptx/src/SubbandFunctionsCommon.h index cfd16e2447e..e2c17e6bfdd 100644 --- a/system/embdrv/encoder_for_aptx/src/SubbandFunctionsCommon.h +++ b/system/embdrv/encoder_for_aptx/src/SubbandFunctionsCommon.h @@ -27,16 +27,15 @@ enum reg64_reg { reg64_H = 1, reg64_L = 0 }; -void processSubband(const int32_t qCode, const int32_t ditherVal, - Subband_data* SubbandDataPt, IQuantiser_data* iqDataPt); -void processSubbandLL(const int32_t qCode, const int32_t ditherVal, - Subband_data* SubbandDataPt, IQuantiser_data* iqDataPt); -void processSubbandHL(const int32_t qCode, const int32_t ditherVal, - Subband_data* SubbandDataPt, IQuantiser_data* iqDataPt); +void processSubband(const int32_t qCode, const int32_t ditherVal, Subband_data* SubbandDataPt, + IQuantiser_data* iqDataPt); +void processSubbandLL(const int32_t qCode, const int32_t ditherVal, Subband_data* SubbandDataPt, + IQuantiser_data* iqDataPt); +void processSubbandHL(const int32_t qCode, const int32_t ditherVal, Subband_data* SubbandDataPt, + IQuantiser_data* iqDataPt); /* Function to carry out inverse quantisation for LL, LH and HH subband types */ -XBT_INLINE_ void invertQuantisation(const int32_t qCode, - const int32_t ditherVal, +XBT_INLINE_ void invertQuantisation(const int32_t qCode, const int32_t ditherVal, IQuantiser_data* iqdata_pt) { int32_t invQ; int32_t index; @@ -136,8 +135,7 @@ XBT_INLINE_ void invertQuantisation(const int32_t qCode, } /* Function to carry out inverse quantisation for a HL subband type */ -XBT_INLINE_ void invertQuantisationHL(const int32_t qCode, - const int32_t ditherVal, +XBT_INLINE_ void invertQuantisationHL(const int32_t qCode, const int32_t ditherVal, IQuantiser_data* iqdata_pt) { int32_t invQ; int32_t index; @@ -237,8 +235,7 @@ XBT_INLINE_ void invertQuantisationHL(const int32_t qCode, /* Function to carry out prediction ARMA filtering for the current subband * performPredictionFiltering should only be used for HH and LH subband! */ -XBT_INLINE_ void performPredictionFiltering(const int32_t invQ, - Subband_data* SubbandDataPt) { +XBT_INLINE_ void performPredictionFiltering(const int32_t invQ, Subband_data* SubbandDataPt) { int32_t poleVal; int32_t acc; int64_t accL; @@ -266,8 +263,7 @@ XBT_INLINE_ void performPredictionFiltering(const int32_t invQ, /* Pole filter convolution. Shift convolution result 1 place to the left * before retrieving it, since the pole coefficients are Q22 (data is Q23) * and we want a Q23 result */ - accL = ((int64_t)poleCoeff[a2] * - (int64_t)SubbandDataPt->m_predData.m_poleDelayLine[a2]); + accL = ((int64_t)poleCoeff[a2] * (int64_t)SubbandDataPt->m_predData.m_poleDelayLine[a2]); /* Update the pole delay line for the next pass by writing the new input * sample into the 2nd element */ SubbandDataPt->m_predData.m_poleDelayLine[a2] = poleDelayLine; @@ -333,15 +329,14 @@ XBT_INLINE_ void performPredictionFiltering(const int32_t invQ, /* Update the zero filter delay line by writing the new input sample to the * circular buffer. */ SubbandDataPt->m_predData.m_zeroDelayLine - .buffer[SubbandDataPt->m_predData.m_zeroDelayLine.pointer] = - SubbandDataPt->m_predData.m_zeroDelayLine.modulo; + .buffer[SubbandDataPt->m_predData.m_zeroDelayLine.pointer] = + SubbandDataPt->m_predData.m_zeroDelayLine.modulo; SubbandDataPt->m_predData.m_zeroDelayLine - .buffer[SubbandDataPt->m_predData.m_zeroDelayLine.pointer + 12] = - SubbandDataPt->m_predData.m_zeroDelayLine.modulo; + .buffer[SubbandDataPt->m_predData.m_zeroDelayLine.pointer + 12] = + SubbandDataPt->m_predData.m_zeroDelayLine.modulo; } -XBT_INLINE_ void performPredictionFilteringLL(const int32_t invQ, - Subband_data* SubbandDataPt) { +XBT_INLINE_ void performPredictionFilteringLL(const int32_t invQ, Subband_data* SubbandDataPt) { int32_t poleVal; int32_t acc; int64_t accL; @@ -368,8 +363,7 @@ XBT_INLINE_ void performPredictionFilteringLL(const int32_t invQ, /* Pole filter convolution. Shift convolution result 1 place to the left * before retrieving it, since the pole coefficients are Q22 (data is Q23) * and we want a Q23 result */ - accL = ((int64_t)poleCoeff[a2] * - (int64_t)SubbandDataPt->m_predData.m_poleDelayLine[a2]); + accL = ((int64_t)poleCoeff[a2] * (int64_t)SubbandDataPt->m_predData.m_poleDelayLine[a2]); /* Update the pole delay line for the next pass by writing the new input * sample into the 2nd element */ SubbandDataPt->m_predData.m_poleDelayLine[a2] = poleDelayLine; @@ -438,15 +432,14 @@ XBT_INLINE_ void performPredictionFilteringLL(const int32_t invQ, /* Update the zero filter delay line by writing the new input sample to the * circular buffer. */ SubbandDataPt->m_predData.m_zeroDelayLine - .buffer[SubbandDataPt->m_predData.m_zeroDelayLine.pointer] = - SubbandDataPt->m_predData.m_zeroDelayLine.modulo; + .buffer[SubbandDataPt->m_predData.m_zeroDelayLine.pointer] = + SubbandDataPt->m_predData.m_zeroDelayLine.modulo; SubbandDataPt->m_predData.m_zeroDelayLine - .buffer[SubbandDataPt->m_predData.m_zeroDelayLine.pointer + 24] = - SubbandDataPt->m_predData.m_zeroDelayLine.modulo; + .buffer[SubbandDataPt->m_predData.m_zeroDelayLine.pointer + 24] = + SubbandDataPt->m_predData.m_zeroDelayLine.modulo; } -XBT_INLINE_ void performPredictionFilteringHL(const int32_t invQ, - Subband_data* SubbandDataPt) { +XBT_INLINE_ void performPredictionFilteringHL(const int32_t invQ, Subband_data* SubbandDataPt) { int32_t poleVal; int32_t acc; int64_t accL; @@ -475,8 +468,7 @@ XBT_INLINE_ void performPredictionFilteringHL(const int32_t invQ, /* Pole filter convolution. Shift convolution result 1 place to the left * before retrieving it, since the pole coefficients are Q22 (data is Q23) * and we want a Q23 result */ - accL = ((int64_t)poleCoeff[a2] * - (int64_t)SubbandDataPt->m_predData.m_poleDelayLine[a2]); + accL = ((int64_t)poleCoeff[a2] * (int64_t)SubbandDataPt->m_predData.m_poleDelayLine[a2]); /* Update the pole delay line for the next pass by writing the new input * sample into the 2nd element */ SubbandDataPt->m_predData.m_poleDelayLine[a2] = poleDelayLine; @@ -542,11 +534,11 @@ XBT_INLINE_ void performPredictionFilteringHL(const int32_t invQ, /* Update the zero filter delay line by writing the new input sample to the * circular buffer. */ SubbandDataPt->m_predData.m_zeroDelayLine - .buffer[SubbandDataPt->m_predData.m_zeroDelayLine.pointer] = - SubbandDataPt->m_predData.m_zeroDelayLine.modulo; + .buffer[SubbandDataPt->m_predData.m_zeroDelayLine.pointer] = + SubbandDataPt->m_predData.m_zeroDelayLine.modulo; SubbandDataPt->m_predData.m_zeroDelayLine - .buffer[SubbandDataPt->m_predData.m_zeroDelayLine.pointer + 6] = - SubbandDataPt->m_predData.m_zeroDelayLine.modulo; + .buffer[SubbandDataPt->m_predData.m_zeroDelayLine.pointer + 6] = + SubbandDataPt->m_predData.m_zeroDelayLine.modulo; } #endif // SUBBANDFUNCTIONSCOMMON_H diff --git a/system/embdrv/encoder_for_aptx/src/SyncInserter.h b/system/embdrv/encoder_for_aptx/src/SyncInserter.h index c55ac537dd3..58c748b56df 100644 --- a/system/embdrv/encoder_for_aptx/src/SyncInserter.h +++ b/system/embdrv/encoder_for_aptx/src/SyncInserter.h @@ -33,8 +33,7 @@ /* Function to insert sync information into one of the 8 quantised codes * spread across 2 aptX codewords (1 codeword per channel) */ XBT_INLINE_ void xbtEncinsertSync(Encoder_data* leftChannelEncoder, - Encoder_data* rightChannelEncoder, - uint32_t* syncWordPhase) { + Encoder_data* rightChannelEncoder, uint32_t* syncWordPhase) { /* Currently using 0x1 as the 8-bit sync pattern */ static const uint32_t syncWord = 0x1; uint32_t tmp_var; @@ -65,8 +64,7 @@ XBT_INLINE_ void xbtEncinsertSync(Encoder_data* leftChannelEncoder, * of the left LL quantiser. Initialise the code lsbs XOR variable with the * left LL quantised code lsbs and also XOR in the left and right random * dither bit generated by the 2 encoders. */ - xorCodeLsbs = ((rightQuant[LL]->qCode) & 0x1) ^ - leftChannelEncoder->m_dithSyncRandBit ^ + xorCodeLsbs = ((rightQuant[LL]->qCode) & 0x1) ^ leftChannelEncoder->m_dithSyncRandBit ^ rightChannelEncoder->m_dithSyncRandBit; minPenaltyQuantiser = rightQuant[LH]; diff --git a/system/embdrv/encoder_for_aptx/src/aptXbtenc.c b/system/embdrv/encoder_for_aptx/src/aptXbtenc.c index 6286ca942d9..668ca761b60 100644 --- a/system/embdrv/encoder_for_aptx/src/aptXbtenc.c +++ b/system/embdrv/encoder_for_aptx/src/aptXbtenc.c @@ -48,13 +48,11 @@ typedef struct aptxbtenc_t { /* Log to linear lookup table used in inverse quantiser*/ /* Size of Table: 32*4 = 128 bytes */ static const int32_t IQuant_tableLogT[32] = { - 16384 * 256, 16744 * 256, 17112 * 256, 17488 * 256, 17864 * 256, - 18256 * 256, 18656 * 256, 19064 * 256, 19480 * 256, 19912 * 256, - 20344 * 256, 20792 * 256, 21248 * 256, 21712 * 256, 22192 * 256, - 22672 * 256, 23168 * 256, 23680 * 256, 24200 * 256, 24728 * 256, - 25264 * 256, 25824 * 256, 26384 * 256, 26968 * 256, 27552 * 256, - 28160 * 256, 28776 * 256, 29408 * 256, 30048 * 256, 30704 * 256, - 31376 * 256, 32064 * 256}; + 16384 * 256, 16744 * 256, 17112 * 256, 17488 * 256, 17864 * 256, 18256 * 256, 18656 * 256, + 19064 * 256, 19480 * 256, 19912 * 256, 20344 * 256, 20792 * 256, 21248 * 256, 21712 * 256, + 22192 * 256, 22672 * 256, 23168 * 256, 23680 * 256, 24200 * 256, 24728 * 256, 25264 * 256, + 25824 * 256, 26384 * 256, 26968 * 256, 27552 * 256, 28160 * 256, 28776 * 256, 29408 * 256, + 30048 * 256, 30704 * 256, 31376 * 256, 32064 * 256}; static void clearmem(void* mem, int32_t sz) { int8_t* m = (int8_t*)mem; @@ -65,9 +63,9 @@ static void clearmem(void* mem, int32_t sz) { } } -APTXBTENCEXPORT int SizeofAptxbtenc(void) { return (sizeof(aptxbtenc)); } +APTXBTENCEXPORT int SizeofAptxbtenc(void) { return sizeof(aptxbtenc); } -APTXBTENCEXPORT const char* aptxbtenc_version() { return (swversion); } +APTXBTENCEXPORT const char* aptxbtenc_version() { return swversion; } APTXBTENCEXPORT int aptxbtenc_init(void* _state, short endian) { aptxbtenc* state = (aptxbtenc*)_state; @@ -100,40 +98,31 @@ APTXBTENCEXPORT int aptxbtenc_init(void* _state, short endian) { for (i = LL; i <= HH; i++) { encode_dat->m_codewordHistory = 0L; - encode_dat->m_qdata[i].thresholdTablePtr = - subbandParameters[i].threshTable; - encode_dat->m_qdata[i].thresholdTablePtr_sl1 = - subbandParameters[i].threshTable_sl1; + encode_dat->m_qdata[i].thresholdTablePtr = subbandParameters[i].threshTable; + encode_dat->m_qdata[i].thresholdTablePtr_sl1 = subbandParameters[i].threshTable_sl1; encode_dat->m_qdata[i].ditherTablePtr = subbandParameters[i].dithTable; - encode_dat->m_qdata[i].minusLambdaDTable = - subbandParameters[i].minusLambdaDTable; + encode_dat->m_qdata[i].minusLambdaDTable = subbandParameters[i].minusLambdaDTable; encode_dat->m_qdata[i].codeBits = subbandParameters[i].numBits; encode_dat->m_qdata[i].qCode = 0L; encode_dat->m_qdata[i].altQcode = 0L; encode_dat->m_qdata[i].distPenalty = 0L; /* initialisation of inverseQuantiser data */ - encode_dat->m_SubbandData[i].m_iqdata.thresholdTablePtr = - subbandParameters[i].threshTable; + encode_dat->m_SubbandData[i].m_iqdata.thresholdTablePtr = subbandParameters[i].threshTable; encode_dat->m_SubbandData[i].m_iqdata.thresholdTablePtr_sl1 = - subbandParameters[i].threshTable_sl1; - encode_dat->m_SubbandData[i].m_iqdata.ditherTablePtr_sf1 = - subbandParameters[i].dithTable_sh1; - encode_dat->m_SubbandData[i].m_iqdata.incrTablePtr = - subbandParameters[i].incrTable; - encode_dat->m_SubbandData[i].m_iqdata.maxLogDelta = - subbandParameters[i].maxLogDelta; - encode_dat->m_SubbandData[i].m_iqdata.minLogDelta = - subbandParameters[i].minLogDelta; + subbandParameters[i].threshTable_sl1; + encode_dat->m_SubbandData[i].m_iqdata.ditherTablePtr_sf1 = subbandParameters[i].dithTable_sh1; + encode_dat->m_SubbandData[i].m_iqdata.incrTablePtr = subbandParameters[i].incrTable; + encode_dat->m_SubbandData[i].m_iqdata.maxLogDelta = subbandParameters[i].maxLogDelta; + encode_dat->m_SubbandData[i].m_iqdata.minLogDelta = subbandParameters[i].minLogDelta; encode_dat->m_SubbandData[i].m_iqdata.delta = 0; encode_dat->m_SubbandData[i].m_iqdata.logDelta = 0; encode_dat->m_SubbandData[i].m_iqdata.invQ = 0; - encode_dat->m_SubbandData[i].m_iqdata.iquantTableLogPtr = - &IQuant_tableLogT[0]; + encode_dat->m_SubbandData[i].m_iqdata.iquantTableLogPtr = &IQuant_tableLogT[0]; // Initializing data for predictor filter encode_dat->m_SubbandData[i].m_predData.m_zeroDelayLine.modulo = - subbandParameters[i].numZeros; + subbandParameters[i].numZeros; for (t = 0; t < 48; t++) { encode_dat->m_SubbandData[i].m_predData.m_zeroDelayLine.buffer[t] = 0; @@ -144,8 +133,7 @@ APTXBTENCEXPORT int aptxbtenc_init(void* _state, short endian) { */ encode_dat->m_SubbandData[i].m_predData.m_zeroVal = 0L; encode_dat->m_SubbandData[i].m_predData.m_predVal = 0L; - encode_dat->m_SubbandData[i].m_predData.m_numZeros = - subbandParameters[i].numZeros; + encode_dat->m_SubbandData[i].m_predData.m_numZeros = subbandParameters[i].numZeros; /* Initialise the contents of the pole data delay line to zero */ encode_dat->m_SubbandData[i].m_predData.m_poleDelayLine[0] = 0L; encode_dat->m_SubbandData[i].m_predData.m_poleDelayLine[1] = 0L; @@ -154,13 +142,11 @@ APTXBTENCEXPORT int aptxbtenc_init(void* _state, short endian) { encode_dat->m_SubbandData[i].m_ZeroCoeffData.m_zeroCoeff[k] = 0; } // Initializing data for zerocoeff update function. - encode_dat->m_SubbandData[i].m_ZeroCoeffData.m_numZeros = - subbandParameters[i].numZeros; + encode_dat->m_SubbandData[i].m_ZeroCoeffData.m_numZeros = subbandParameters[i].numZeros; /* Initializing data for PoleCoeff Update function. * Fill the adaptation delay line with +1 initially */ - encode_dat->m_SubbandData[i].m_PoleCoeffData.m_poleAdaptDelayLine.s32 = - 0x00010001; + encode_dat->m_SubbandData[i].m_PoleCoeffData.m_poleAdaptDelayLine.s32 = 0x00010001; /* Zero the pole coefficients */ encode_dat->m_SubbandData[i].m_PoleCoeffData.m_poleCoeff[0] = 0L; @@ -177,8 +163,7 @@ APTXBTENCEXPORT int aptxbtenc_setsync_mode(void* _state, int32_t sync_mode) { return 0; } -APTXBTENCEXPORT int aptxbtenc_encodestereo(void* _state, void* _pcmL, - void* _pcmR, void* _buffer) { +APTXBTENCEXPORT int aptxbtenc_encodestereo(void* _state, void* _pcmL, void* _pcmR, void* _buffer) { aptxbtenc* state = (aptxbtenc*)_state; int32_t* pcmL = (int32_t*)_pcmL; int32_t* pcmR = (int32_t*)_pcmR; @@ -195,13 +180,11 @@ APTXBTENCEXPORT int aptxbtenc_encodestereo(void* _state, void* _pcmL, if (state->m_sync_mode != no_sync) { if (state->m_sync_mode == stereo) { // Insert the autosync information into the stereo quantised codes - xbtEncinsertSync(&state->m_encoderData[0], &state->m_encoderData[1], - &state->m_syncWordPhase); + xbtEncinsertSync(&state->m_encoderData[0], &state->m_encoderData[1], &state->m_syncWordPhase); } else { // Insert the autosync information into the two individual mono quantised // codes - xbtEncinsertSyncDualMono(&state->m_encoderData[0], - &state->m_encoderData[1], + xbtEncinsertSyncDualMono(&state->m_encoderData[0], &state->m_encoderData[1], &state->m_syncWordPhase); } } diff --git a/system/embdrv/encoder_for_aptxhd/include/aptXHDbtenc.h b/system/embdrv/encoder_for_aptxhd/include/aptXHDbtenc.h index 9c18ab1388d..dc7a305ec4b 100644 --- a/system/embdrv/encoder_for_aptxhd/include/aptXHDbtenc.h +++ b/system/embdrv/encoder_for_aptxhd/include/aptXHDbtenc.h @@ -53,8 +53,8 @@ APTXHDBTENCEXPORT int aptxhdbtenc_init(void* _state, short endian); /* StereoEncode will take 8 audio samples (24-bit per sample) * and generate two 24-bit codeword with autosync inserted. * The bitstream is compatible with be BC05 implementation. */ -APTXHDBTENCEXPORT int aptxhdbtenc_encodestereo(void* _state, void* _pcmL, - void* _pcmR, void* _buffer); +APTXHDBTENCEXPORT int aptxhdbtenc_encodestereo(void* _state, void* _pcmL, void* _pcmR, + void* _buffer); #ifdef __cplusplus } // /extern "C" diff --git a/system/embdrv/encoder_for_aptxhd/src/AptxEncoder.h b/system/embdrv/encoder_for_aptxhd/src/AptxEncoder.h index 600ff345cb5..d0363ba0c40 100644 --- a/system/embdrv/encoder_for_aptxhd/src/AptxEncoder.h +++ b/system/embdrv/encoder_for_aptxhd/src/AptxEncoder.h @@ -35,8 +35,7 @@ #include "SubbandFunctionsCommon.h" /* Function to carry out a single-channel aptX HD encode on 4 new PCM samples */ -XBT_INLINE_ void aptxhdEncode(int32_t pcm[4], Qmf_storage* Qmf_St, - Encoder_data* EncoderDataPt) { +XBT_INLINE_ void aptxhdEncode(int32_t pcm[4], Qmf_storage* Qmf_St, Encoder_data* EncoderDataPt) { int32_t predVals[4]; int32_t qCodes[4]; int32_t aqmfOutputs[4]; @@ -56,9 +55,9 @@ XBT_INLINE_ void aptxhdEncode(int32_t pcm[4], Qmf_storage* Qmf_St, /* Update codeword history, then generate new dither values. */ EncoderDataPt->m_codewordHistory = - xbtEncupdateCodewordHistory(qCodes, EncoderDataPt->m_codewordHistory); - EncoderDataPt->m_dithSyncRandBit = xbtEncgenerateDither( - EncoderDataPt->m_codewordHistory, EncoderDataPt->m_ditherOutputs); + xbtEncupdateCodewordHistory(qCodes, EncoderDataPt->m_codewordHistory); + EncoderDataPt->m_dithSyncRandBit = + xbtEncgenerateDither(EncoderDataPt->m_codewordHistory, EncoderDataPt->m_ditherOutputs); /* Run the analysis QMF */ QmfAnalysisFilter(pcm, Qmf_St, predVals, aqmfOutputs); @@ -81,25 +80,17 @@ XBT_INLINE_ void aptxhdEncode(int32_t pcm[4], Qmf_storage* Qmf_St, XBT_INLINE_ void aptxhdPostEncode(Encoder_data* EncoderDataPt) { /* Run the remaining subband processing for each subband */ /* Manual inlining on the 4 subband */ - processSubband_HDLL(EncoderDataPt->m_qdata[0].qCode, - EncoderDataPt->m_ditherOutputs[0], - &EncoderDataPt->m_SubbandData[0], - &EncoderDataPt->m_SubbandData[0].m_iqdata); + processSubband_HDLL(EncoderDataPt->m_qdata[0].qCode, EncoderDataPt->m_ditherOutputs[0], + &EncoderDataPt->m_SubbandData[0], &EncoderDataPt->m_SubbandData[0].m_iqdata); - processSubband_HD(EncoderDataPt->m_qdata[1].qCode, - EncoderDataPt->m_ditherOutputs[1], - &EncoderDataPt->m_SubbandData[1], - &EncoderDataPt->m_SubbandData[1].m_iqdata); + processSubband_HD(EncoderDataPt->m_qdata[1].qCode, EncoderDataPt->m_ditherOutputs[1], + &EncoderDataPt->m_SubbandData[1], &EncoderDataPt->m_SubbandData[1].m_iqdata); - processSubband_HDHL(EncoderDataPt->m_qdata[2].qCode, - EncoderDataPt->m_ditherOutputs[2], - &EncoderDataPt->m_SubbandData[2], - &EncoderDataPt->m_SubbandData[2].m_iqdata); + processSubband_HDHL(EncoderDataPt->m_qdata[2].qCode, EncoderDataPt->m_ditherOutputs[2], + &EncoderDataPt->m_SubbandData[2], &EncoderDataPt->m_SubbandData[2].m_iqdata); - processSubband_HD(EncoderDataPt->m_qdata[3].qCode, - EncoderDataPt->m_ditherOutputs[3], - &EncoderDataPt->m_SubbandData[3], - &EncoderDataPt->m_SubbandData[3].m_iqdata); + processSubband_HD(EncoderDataPt->m_qdata[3].qCode, EncoderDataPt->m_ditherOutputs[3], + &EncoderDataPt->m_SubbandData[3], &EncoderDataPt->m_SubbandData[3].m_iqdata); } #ifdef _GCC diff --git a/system/embdrv/encoder_for_aptxhd/src/AptxTables.h b/system/embdrv/encoder_for_aptxhd/src/AptxTables.h index 460e7abd04e..b7bf2d79332 100644 --- a/system/embdrv/encoder_for_aptxhd/src/AptxTables.h +++ b/system/embdrv/encoder_for_aptxhd/src/AptxTables.h @@ -27,207 +27,179 @@ /* Quantisation threshold, logDelta increment and dither tables for 4-bit codes */ static const int32_t dq4bit24_sl1[9] = { - -95044, 95044, 295844, 528780, 821332, 1226438, 1890540, 3344850, 6450664, + -95044, 95044, 295844, 528780, 821332, 1226438, 1890540, 3344850, 6450664, }; static const int32_t q4incr24[9] = { - 0, -17, 5, 30, 62, 105, 177, 334, 518, + 0, -17, 5, 30, 62, 105, 177, 334, 518, }; static const int32_t dq4dith24_sf1[9] = { - 95044, 95044, 105754, 127180, 165372, 39736, 424366, 1029946, 2075866, + 95044, 95044, 105754, 127180, 165372, 39736, 424366, 1029946, 2075866, }; static const int32_t dq4mLamb24[8] = { - 0, -2678, -5357, -9548, 31409, -96158, -151395, -261480, + 0, -2678, -5357, -9548, 31409, -96158, -151395, -261480, }; /* Quantisation threshold, logDelta increment and dither tables for 5-bit codes */ static const int32_t dq5bit24_sl1[17] = { - -45754, 45754, 138496, 234896, 337336, 448310, - 570738, 708380, 866534, 1053262, 1281958, 1577438, - 1993050, 2665984, 3900982, 5902844, 8897462, + -45754, 45754, 138496, 234896, 337336, 448310, 570738, 708380, 866534, + 1053262, 1281958, 1577438, 1993050, 2665984, 3900982, 5902844, 8897462, }; static const int32_t q5incr24[17] = { - 0, -18, -8, 2, 13, 25, 38, 53, 70, 90, 115, 147, 192, 264, 398, 521, 521, + 0, -18, -8, 2, 13, 25, 38, 53, 70, 90, 115, 147, 192, 264, 398, 521, 521, }; static const int32_t dq5dith24_sf1[17] = { - 45754, 45754, 46988, 49412, 53026, 57950, 64478, 73164, 84988, - 101740, 126958, 168522, 247092, 425842, 809154, 1192708, 1801910, + 45754, 45754, 46988, 49412, 53026, 57950, 64478, 73164, 84988, + 101740, 126958, 168522, 247092, 425842, 809154, 1192708, 1801910, }; static const int32_t dq5mLamb24[16] = { - 0, -309, -606, -904, -1231, -1632, -2172, -2956, - -4188, -6305, -10391, -19643, -44688, -95828, -95889, -152301, + 0, -309, -606, -904, -1231, -1632, -2172, -2956, + -4188, -6305, -10391, -19643, -44688, -95828, -95889, -152301, }; /* Quantisation threshold, logDelta increment and dither tables for 6-bit codes */ static const int32_t dq6bit24_sl1[33] = { - -21236, 21236, 63830, 106798, 150386, 194832, 240376, - 287258, 335726, 386034, 438460, 493308, 550924, 611696, - 676082, 744626, 817986, 896968, 982580, 1076118, 1179278, - 1294344, 1424504, 1574386, 1751090, 1966260, 2240868, 2617662, - 3196432, 4176450, 5658260, 7671068, 10380372, + -21236, 21236, 63830, 106798, 150386, 194832, 240376, 287258, 335726, + 386034, 438460, 493308, 550924, 611696, 676082, 744626, 817986, 896968, + 982580, 1076118, 1179278, 1294344, 1424504, 1574386, 1751090, 1966260, 2240868, + 2617662, 3196432, 4176450, 5658260, 7671068, 10380372, }; static const int32_t q6incr24[33] = { - 0, -21, -16, -12, -7, -2, 3, 8, 13, 19, 24, - 30, 36, 43, 50, 57, 65, 74, 83, 93, 104, 117, - 131, 147, 166, 189, 219, 259, 322, 427, 521, 521, 521, + 0, -21, -16, -12, -7, -2, 3, 8, 13, 19, 24, 30, 36, 43, 50, 57, 65, + 74, 83, 93, 104, 117, 131, 147, 166, 189, 219, 259, 322, 427, 521, 521, 521, }; static const int32_t dq6dith24_sf1[33] = { - 21236, 21236, 21360, 21608, 21978, 22468, 23076, 23806, 24660, - 25648, 26778, 28070, 29544, 31228, 33158, 35386, 37974, 41008, - 44606, 48934, 54226, 60840, 69320, 80564, 96140, 119032, 155576, - 221218, 357552, 622468, 859344, 1153464, 1555840, + 21236, 21236, 21360, 21608, 21978, 22468, 23076, 23806, 24660, 25648, 26778, + 28070, 29544, 31228, 33158, 35386, 37974, 41008, 44606, 48934, 54226, 60840, + 69320, 80564, 96140, 119032, 155576, 221218, 357552, 622468, 859344, 1153464, 1555840, }; static const int32_t dq6mLamb24[32] = { - 0, -31, -62, -93, -123, -152, -183, -214, - -247, -283, -323, -369, -421, -483, -557, -647, - -759, -900, -1082, -1323, -1654, -2120, -2811, -3894, - -5723, -9136, -16411, -34084, -66229, -59219, -73530, -100594, + 0, -31, -62, -93, -123, -152, -183, -214, -247, -283, -323, + -369, -421, -483, -557, -647, -759, -900, -1082, -1323, -1654, -2120, + -2811, -3894, -5723, -9136, -16411, -34084, -66229, -59219, -73530, -100594, }; /* Quantisation threshold, logDelta increment and dither tables for 9-bit codes */ static const int32_t dq9bit24_sl1[257] = { - -2436, 2436, 7308, 12180, 17054, 21930, 26806, 31686, - 36566, 41450, 46338, 51230, 56124, 61024, 65928, 70836, - 75750, 80670, 85598, 90530, 95470, 100418, 105372, 110336, - 115308, 120288, 125278, 130276, 135286, 140304, 145334, 150374, - 155426, 160490, 165566, 170654, 175756, 180870, 185998, 191138, - 196294, 201466, 206650, 211850, 217068, 222300, 227548, 232814, - 238096, 243396, 248714, 254050, 259406, 264778, 270172, 275584, - 281018, 286470, 291944, 297440, 302956, 308496, 314056, 319640, - 325248, 330878, 336532, 342212, 347916, 353644, 359398, 365178, - 370986, 376820, 382680, 388568, 394486, 400430, 406404, 412408, - 418442, 424506, 430600, 436726, 442884, 449074, 455298, 461554, - 467844, 474168, 480528, 486922, 493354, 499820, 506324, 512866, - 519446, 526064, 532722, 539420, 546160, 552940, 559760, 566624, - 573532, 580482, 587478, 594520, 601606, 608740, 615920, 623148, - 630426, 637754, 645132, 652560, 660042, 667576, 675164, 682808, - 690506, 698262, 706074, 713946, 721876, 729868, 737920, 746036, - 754216, 762460, 770770, 779148, 787594, 796108, 804694, 813354, - 822086, 830892, 839774, 848736, 857776, 866896, 876100, 885386, - 894758, 904218, 913766, 923406, 933138, 942964, 952886, 962908, - 973030, 983254, 993582, 1004020, 1014566, 1025224, 1035996, 1046886, - 1057894, 1069026, 1080284, 1091670, 1103186, 1114838, 1126628, 1138558, - 1150634, 1162858, 1175236, 1187768, 1200462, 1213320, 1226346, 1239548, - 1252928, 1266490, 1280242, 1294188, 1308334, 1322688, 1337252, 1352034, - 1367044, 1382284, 1397766, 1413494, 1429478, 1445728, 1462252, 1479058, - 1496158, 1513562, 1531280, 1549326, 1567710, 1586446, 1605550, 1625034, - 1644914, 1665208, 1685932, 1707108, 1728754, 1750890, 1773542, 1796732, - 1820488, 1844840, 1869816, 1895452, 1921780, 1948842, 1976680, 2005338, - 2034868, 2065322, 2096766, 2129260, 2162880, 2197708, 2233832, 2271352, - 2310384, 2351050, 2393498, 2437886, 2484404, 2533262, 2584710, 2639036, - 2696578, 2757738, 2822998, 2892940, 2968278, 3049896, 3138912, 3236760, - 3345312, 3467068, 3605434, 3765154, 3952904, 4177962, 4452178, 4787134, - 5187290, 5647128, 6159120, 6720518, 7332904, 8000032, 8726664, 9518152, - 10380372, + -2436, 2436, 7308, 12180, 17054, 21930, 26806, 31686, 36566, 41450, + 46338, 51230, 56124, 61024, 65928, 70836, 75750, 80670, 85598, 90530, + 95470, 100418, 105372, 110336, 115308, 120288, 125278, 130276, 135286, 140304, + 145334, 150374, 155426, 160490, 165566, 170654, 175756, 180870, 185998, 191138, + 196294, 201466, 206650, 211850, 217068, 222300, 227548, 232814, 238096, 243396, + 248714, 254050, 259406, 264778, 270172, 275584, 281018, 286470, 291944, 297440, + 302956, 308496, 314056, 319640, 325248, 330878, 336532, 342212, 347916, 353644, + 359398, 365178, 370986, 376820, 382680, 388568, 394486, 400430, 406404, 412408, + 418442, 424506, 430600, 436726, 442884, 449074, 455298, 461554, 467844, 474168, + 480528, 486922, 493354, 499820, 506324, 512866, 519446, 526064, 532722, 539420, + 546160, 552940, 559760, 566624, 573532, 580482, 587478, 594520, 601606, 608740, + 615920, 623148, 630426, 637754, 645132, 652560, 660042, 667576, 675164, 682808, + 690506, 698262, 706074, 713946, 721876, 729868, 737920, 746036, 754216, 762460, + 770770, 779148, 787594, 796108, 804694, 813354, 822086, 830892, 839774, 848736, + 857776, 866896, 876100, 885386, 894758, 904218, 913766, 923406, 933138, 942964, + 952886, 962908, 973030, 983254, 993582, 1004020, 1014566, 1025224, 1035996, 1046886, + 1057894, 1069026, 1080284, 1091670, 1103186, 1114838, 1126628, 1138558, 1150634, 1162858, + 1175236, 1187768, 1200462, 1213320, 1226346, 1239548, 1252928, 1266490, 1280242, 1294188, + 1308334, 1322688, 1337252, 1352034, 1367044, 1382284, 1397766, 1413494, 1429478, 1445728, + 1462252, 1479058, 1496158, 1513562, 1531280, 1549326, 1567710, 1586446, 1605550, 1625034, + 1644914, 1665208, 1685932, 1707108, 1728754, 1750890, 1773542, 1796732, 1820488, 1844840, + 1869816, 1895452, 1921780, 1948842, 1976680, 2005338, 2034868, 2065322, 2096766, 2129260, + 2162880, 2197708, 2233832, 2271352, 2310384, 2351050, 2393498, 2437886, 2484404, 2533262, + 2584710, 2639036, 2696578, 2757738, 2822998, 2892940, 2968278, 3049896, 3138912, 3236760, + 3345312, 3467068, 3605434, 3765154, 3952904, 4177962, 4452178, 4787134, 5187290, 5647128, + 6159120, 6720518, 7332904, 8000032, 8726664, 9518152, 10380372, }; static const int32_t q9incr24[257] = { - 0, -22, -21, -21, -20, -20, -19, -19, -18, -18, -17, -17, -16, -16, -15, - -14, -14, -13, -13, -12, -12, -11, -11, -10, -10, -9, -9, -8, -7, -7, - -6, -6, -5, -5, -4, -4, -3, -3, -2, -1, -1, 0, 0, 1, 1, - 2, 2, 3, 4, 4, 5, 5, 6, 6, 7, 8, 8, 9, 9, 10, - 11, 11, 12, 12, 13, 14, 14, 15, 15, 16, 17, 17, 18, 19, 19, - 20, 20, 21, 22, 22, 23, 24, 24, 25, 26, 26, 27, 28, 28, 29, - 30, 30, 31, 32, 33, 33, 34, 35, 35, 36, 37, 38, 38, 39, 40, - 41, 41, 42, 43, 44, 44, 45, 46, 47, 48, 48, 49, 50, 51, 52, - 52, 53, 54, 55, 56, 57, 58, 58, 59, 60, 61, 62, 63, 64, 65, - 66, 67, 68, 69, 69, 70, 71, 72, 73, 74, 75, 77, 78, 79, 80, - 81, 82, 83, 84, 85, 86, 87, 89, 90, 91, 92, 93, 94, 96, 97, - 98, 99, 101, 102, 103, 105, 106, 107, 109, 110, 112, 113, 115, 116, 118, - 119, 121, 122, 124, 125, 127, 129, 130, 132, 134, 136, 137, 139, 141, 143, - 145, 147, 149, 151, 153, 155, 158, 160, 162, 164, 167, 169, 172, 174, 177, - 180, 182, 185, 188, 191, 194, 197, 201, 204, 208, 211, 215, 219, 223, 227, - 232, 236, 241, 246, 251, 257, 263, 269, 275, 283, 290, 298, 307, 317, 327, - 339, 352, 367, 384, 404, 429, 458, 494, 522, 522, 522, 522, 522, 522, 522, - 522, 522, + 0, -22, -21, -21, -20, -20, -19, -19, -18, -18, -17, -17, -16, -16, -15, -14, -14, -13, + -13, -12, -12, -11, -11, -10, -10, -9, -9, -8, -7, -7, -6, -6, -5, -5, -4, -4, + -3, -3, -2, -1, -1, 0, 0, 1, 1, 2, 2, 3, 4, 4, 5, 5, 6, 6, + 7, 8, 8, 9, 9, 10, 11, 11, 12, 12, 13, 14, 14, 15, 15, 16, 17, 17, + 18, 19, 19, 20, 20, 21, 22, 22, 23, 24, 24, 25, 26, 26, 27, 28, 28, 29, + 30, 30, 31, 32, 33, 33, 34, 35, 35, 36, 37, 38, 38, 39, 40, 41, 41, 42, + 43, 44, 44, 45, 46, 47, 48, 48, 49, 50, 51, 52, 52, 53, 54, 55, 56, 57, + 58, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 69, 70, 71, 72, 73, + 74, 75, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 89, 90, 91, 92, 93, + 94, 96, 97, 98, 99, 101, 102, 103, 105, 106, 107, 109, 110, 112, 113, 115, 116, 118, + 119, 121, 122, 124, 125, 127, 129, 130, 132, 134, 136, 137, 139, 141, 143, 145, 147, 149, + 151, 153, 155, 158, 160, 162, 164, 167, 169, 172, 174, 177, 180, 182, 185, 188, 191, 194, + 197, 201, 204, 208, 211, 215, 219, 223, 227, 232, 236, 241, 246, 251, 257, 263, 269, 275, + 283, 290, 298, 307, 317, 327, 339, 352, 367, 384, 404, 429, 458, 494, 522, 522, 522, 522, + 522, 522, 522, 522, 522, }; static const int32_t dq9dith24_sf1[257] = { - 2436, 2436, 2436, 2436, 2438, 2438, 2438, 2440, 2442, - 2442, 2444, 2446, 2448, 2450, 2454, 2456, 2458, 2462, - 2464, 2468, 2472, 2476, 2480, 2484, 2488, 2492, 2498, - 2502, 2506, 2512, 2518, 2524, 2528, 2534, 2540, 2548, - 2554, 2560, 2568, 2574, 2582, 2588, 2596, 2604, 2612, - 2620, 2628, 2636, 2646, 2654, 2664, 2672, 2682, 2692, - 2702, 2712, 2722, 2732, 2742, 2752, 2764, 2774, 2786, - 2798, 2810, 2822, 2834, 2846, 2858, 2870, 2884, 2896, - 2910, 2924, 2938, 2952, 2966, 2980, 2994, 3010, 3024, - 3040, 3056, 3070, 3086, 3104, 3120, 3136, 3154, 3170, - 3188, 3206, 3224, 3242, 3262, 3280, 3300, 3320, 3338, - 3360, 3380, 3400, 3422, 3442, 3464, 3486, 3508, 3532, - 3554, 3578, 3602, 3626, 3652, 3676, 3702, 3728, 3754, - 3780, 3808, 3836, 3864, 3892, 3920, 3950, 3980, 4010, - 4042, 4074, 4106, 4138, 4172, 4206, 4240, 4276, 4312, - 4348, 4384, 4422, 4460, 4500, 4540, 4580, 4622, 4664, - 4708, 4752, 4796, 4842, 4890, 4938, 4986, 5036, 5086, - 5138, 5192, 5246, 5300, 5358, 5416, 5474, 5534, 5596, - 5660, 5726, 5792, 5860, 5930, 6002, 6074, 6150, 6226, - 6306, 6388, 6470, 6556, 6644, 6736, 6828, 6924, 7022, - 7124, 7228, 7336, 7448, 7562, 7680, 7802, 7928, 8058, - 8192, 8332, 8476, 8624, 8780, 8940, 9106, 9278, 9458, - 9644, 9840, 10042, 10252, 10472, 10702, 10942, 11194, 11458, - 11734, 12024, 12328, 12648, 12986, 13342, 13720, 14118, 14540, - 14990, 15466, 15976, 16520, 17102, 17726, 18398, 19124, 19908, - 20760, 21688, 22702, 23816, 25044, 26404, 27922, 29622, 31540, - 33720, 36222, 39116, 42502, 46514, 51334, 57218, 64536, 73830, - 85890, 101860, 123198, 151020, 183936, 216220, 243618, 268374, 293022, - 319362, 347768, 378864, 412626, 449596, + 2436, 2436, 2436, 2436, 2438, 2438, 2438, 2440, 2442, 2442, 2444, + 2446, 2448, 2450, 2454, 2456, 2458, 2462, 2464, 2468, 2472, 2476, + 2480, 2484, 2488, 2492, 2498, 2502, 2506, 2512, 2518, 2524, 2528, + 2534, 2540, 2548, 2554, 2560, 2568, 2574, 2582, 2588, 2596, 2604, + 2612, 2620, 2628, 2636, 2646, 2654, 2664, 2672, 2682, 2692, 2702, + 2712, 2722, 2732, 2742, 2752, 2764, 2774, 2786, 2798, 2810, 2822, + 2834, 2846, 2858, 2870, 2884, 2896, 2910, 2924, 2938, 2952, 2966, + 2980, 2994, 3010, 3024, 3040, 3056, 3070, 3086, 3104, 3120, 3136, + 3154, 3170, 3188, 3206, 3224, 3242, 3262, 3280, 3300, 3320, 3338, + 3360, 3380, 3400, 3422, 3442, 3464, 3486, 3508, 3532, 3554, 3578, + 3602, 3626, 3652, 3676, 3702, 3728, 3754, 3780, 3808, 3836, 3864, + 3892, 3920, 3950, 3980, 4010, 4042, 4074, 4106, 4138, 4172, 4206, + 4240, 4276, 4312, 4348, 4384, 4422, 4460, 4500, 4540, 4580, 4622, + 4664, 4708, 4752, 4796, 4842, 4890, 4938, 4986, 5036, 5086, 5138, + 5192, 5246, 5300, 5358, 5416, 5474, 5534, 5596, 5660, 5726, 5792, + 5860, 5930, 6002, 6074, 6150, 6226, 6306, 6388, 6470, 6556, 6644, + 6736, 6828, 6924, 7022, 7124, 7228, 7336, 7448, 7562, 7680, 7802, + 7928, 8058, 8192, 8332, 8476, 8624, 8780, 8940, 9106, 9278, 9458, + 9644, 9840, 10042, 10252, 10472, 10702, 10942, 11194, 11458, 11734, 12024, + 12328, 12648, 12986, 13342, 13720, 14118, 14540, 14990, 15466, 15976, 16520, + 17102, 17726, 18398, 19124, 19908, 20760, 21688, 22702, 23816, 25044, 26404, + 27922, 29622, 31540, 33720, 36222, 39116, 42502, 46514, 51334, 57218, 64536, + 73830, 85890, 101860, 123198, 151020, 183936, 216220, 243618, 268374, 293022, 319362, + 347768, 378864, 412626, 449596, }; static const int32_t dq9mLamb24[256] = { - 0, 0, 0, -1, 0, 0, -1, -1, 0, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -2, -1, -1, -2, -2, -2, -1, -2, - -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, - -2, -2, -2, -3, -2, -3, -2, -3, -3, -3, -3, - -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, - -3, -3, -3, -4, -3, -4, -4, -4, -4, -4, -4, - -4, -4, -4, -4, -4, -4, -4, -5, -4, -4, -5, - -4, -5, -5, -5, -5, -5, -5, -5, -5, -5, -6, - -5, -5, -6, -5, -6, -6, -6, -6, -6, -6, -6, - -6, -7, -6, -7, -7, -7, -7, -7, -7, -7, -7, - -7, -8, -8, -8, -8, -8, -8, -8, -9, -9, -9, - -9, -9, -9, -9, -10, -10, -10, -10, -10, -11, -11, - -11, -11, -11, -12, -12, -12, -12, -13, -13, -13, -14, - -14, -14, -15, -15, -15, -15, -16, -16, -17, -17, -17, - -18, -18, -18, -19, -19, -20, -21, -21, -22, -22, -23, - -23, -24, -25, -26, -26, -27, -28, -29, -30, -31, -32, - -33, -34, -35, -36, -37, -39, -40, -42, -43, -45, -47, - -49, -51, -53, -55, -58, -60, -63, -66, -69, -73, -76, - -80, -85, -89, -95, -100, -106, -113, -119, -128, -136, -146, - -156, -168, -182, -196, -213, -232, -254, -279, -307, -340, -380, - -425, -480, -545, -626, -724, -847, -1003, -1205, -1471, -1830, -2324, - -3015, -3993, -5335, -6956, -8229, -8071, -6850, -6189, -6162, -6585, -7102, - -7774, -8441, -9243, + 0, 0, 0, -1, 0, 0, -1, -1, 0, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -2, + -1, -1, -2, -2, -2, -1, -2, -2, -2, -2, -2, -2, -2, + -2, -2, -2, -2, -2, -2, -2, -2, -3, -2, -3, -2, -3, + -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, + -3, -3, -3, -3, -4, -3, -4, -4, -4, -4, -4, -4, -4, + -4, -4, -4, -4, -4, -4, -5, -4, -4, -5, -4, -5, -5, + -5, -5, -5, -5, -5, -5, -5, -6, -5, -5, -6, -5, -6, + -6, -6, -6, -6, -6, -6, -6, -7, -6, -7, -7, -7, -7, + -7, -7, -7, -7, -7, -8, -8, -8, -8, -8, -8, -8, -9, + -9, -9, -9, -9, -9, -9, -10, -10, -10, -10, -10, -11, -11, + -11, -11, -11, -12, -12, -12, -12, -13, -13, -13, -14, -14, -14, + -15, -15, -15, -15, -16, -16, -17, -17, -17, -18, -18, -18, -19, + -19, -20, -21, -21, -22, -22, -23, -23, -24, -25, -26, -26, -27, + -28, -29, -30, -31, -32, -33, -34, -35, -36, -37, -39, -40, -42, + -43, -45, -47, -49, -51, -53, -55, -58, -60, -63, -66, -69, -73, + -76, -80, -85, -89, -95, -100, -106, -113, -119, -128, -136, -146, -156, + -168, -182, -196, -213, -232, -254, -279, -307, -340, -380, -425, -480, -545, + -626, -724, -847, -1003, -1205, -1471, -1830, -2324, -3015, -3993, -5335, -6956, -8229, + -8071, -6850, -6189, -6162, -6585, -7102, -7774, -8441, -9243, }; /* Array of structures containing subband parameters. */ static const SubbandParameters subbandParameters[NUMSUBBANDS] = { - /* LL band */ - {0, dq9bit24_sl1, 0, dq9dith24_sf1, dq9mLamb24, q9incr24, 9, (18 * 256) - 1, - -20, 24}, + /* LL band */ + {0, dq9bit24_sl1, 0, dq9dith24_sf1, dq9mLamb24, q9incr24, 9, (18 * 256) - 1, -20, 24}, - /* LH band */ - {0, dq6bit24_sl1, 0, dq6dith24_sf1, dq6mLamb24, q6incr24, 6, (21 * 256) - 1, - -23, 12}, + /* LH band */ + {0, dq6bit24_sl1, 0, dq6dith24_sf1, dq6mLamb24, q6incr24, 6, (21 * 256) - 1, -23, 12}, - /* HL band */ - {0, dq4bit24_sl1, 0, dq4dith24_sf1, dq4mLamb24, q4incr24, 4, (23 * 256) - 1, - -25, 6}, + /* HL band */ + {0, dq4bit24_sl1, 0, dq4dith24_sf1, dq4mLamb24, q4incr24, 4, (23 * 256) - 1, -25, 6}, - /* HH band */ - {0, dq5bit24_sl1, 0, dq5dith24_sf1, dq5mLamb24, q5incr24, 5, (22 * 256) - 1, - -24, 12}}; + /* HH band */ + {0, dq5bit24_sl1, 0, dq5dith24_sf1, dq5mLamb24, q5incr24, 5, (22 * 256) - 1, -24, 12}}; #endif // APTXTABLES_H diff --git a/system/embdrv/encoder_for_aptxhd/src/CodewordPacker.h b/system/embdrv/encoder_for_aptxhd/src/CodewordPacker.h index 90f8c4c358a..bc0efbb5cd7 100644 --- a/system/embdrv/encoder_for_aptxhd/src/CodewordPacker.h +++ b/system/embdrv/encoder_for_aptxhd/src/CodewordPacker.h @@ -39,11 +39,10 @@ XBT_INLINE_ int32_t packCodeword(Encoder_data* EncoderDataPt) { * such that the XOR of the sync contributions from the left and right * channel give the actual sync bit value. The per-channel sync bit * contribution overwrites the HH code lsb in the packed codeword. */ - syncContribution = - (EncoderDataPt->m_qdata[0].qCode ^ EncoderDataPt->m_qdata[1].qCode ^ - EncoderDataPt->m_qdata[2].qCode ^ EncoderDataPt->m_qdata[3].qCode ^ - EncoderDataPt->m_dithSyncRandBit) & - 0x1; + syncContribution = (EncoderDataPt->m_qdata[0].qCode ^ EncoderDataPt->m_qdata[1].qCode ^ + EncoderDataPt->m_qdata[2].qCode ^ EncoderDataPt->m_qdata[3].qCode ^ + EncoderDataPt->m_dithSyncRandBit) & + 0x1; hhCode = (EncoderDataPt->m_qdata[HH].qCode & 0x1eL) | syncContribution; /* Pack the 24-bit codeword with the appropriate number of lsbs from each diff --git a/system/embdrv/encoder_for_aptxhd/src/DitherGenerator.h b/system/embdrv/encoder_for_aptxhd/src/DitherGenerator.h index 26a6071ab9f..daf3563c348 100644 --- a/system/embdrv/encoder_for_aptxhd/src/DitherGenerator.h +++ b/system/embdrv/encoder_for_aptxhd/src/DitherGenerator.h @@ -44,23 +44,20 @@ XBT_INLINE_ int32_t xbtEncupdateCodewordHistory(const int32_t quantisedCodes[4], const uint32_t numNewBits = 4; /* Make a 4-bit vector from particular bits from 3 quantised codes */ - newBits = (quantisedCodes[LL] & llMask) + - ((quantisedCodes[LH] & lhMask) << lhShift) + + newBits = (quantisedCodes[LL] & llMask) + ((quantisedCodes[LH] & lhMask) << lhShift) + ((quantisedCodes[HL] & hlMask) << hlShift); /* Add the 4 new bits to the codeword history. Note that this is a 24-bit * value LEFT-JUSTIFIED in a 32-bit signed variable. Maintaining the history * as signed is useful in the dither generation process below. */ - updatedCodewordHistory = - (m_codewordHistory << numNewBits) + (newBits << leftJustifyShift); + updatedCodewordHistory = (m_codewordHistory << numNewBits) + (newBits << leftJustifyShift); return updatedCodewordHistory; } /* Function to generate a dither value for each subband based * on the current contents of the codewordHistory bit-pool. */ -XBT_INLINE_ int32_t xbtEncgenerateDither(int32_t m_codewordHistory, - int32_t* m_ditherOutputs) { +XBT_INLINE_ int32_t xbtEncgenerateDither(int32_t m_codewordHistory, int32_t* m_ditherOutputs) { int32_t history24b; int32_t upperAcc; int32_t lowerAcc; diff --git a/system/embdrv/encoder_for_aptxhd/src/ProcessSubband.c b/system/embdrv/encoder_for_aptxhd/src/ProcessSubband.c index 12c45717d7a..abea3c4c6f6 100644 --- a/system/embdrv/encoder_for_aptxhd/src/ProcessSubband.c +++ b/system/embdrv/encoder_for_aptxhd/src/ProcessSubband.c @@ -19,14 +19,13 @@ /* This function carries out all subband processing (common to both encode and * decode). */ -void processSubband_HD(const int32_t qCode, const int32_t ditherVal, - Subband_data* SubbandDataPt, IQuantiser_data* iqDataPt) { +void processSubband_HD(const int32_t qCode, const int32_t ditherVal, Subband_data* SubbandDataPt, + IQuantiser_data* iqDataPt) { /* Inverse quantisation */ invertQuantisation(qCode, ditherVal, iqDataPt); /* Predictor pole coefficient update */ - updatePredictorPoleCoefficients(iqDataPt->invQ, - SubbandDataPt->m_predData.m_zeroVal, + updatePredictorPoleCoefficients(iqDataPt->invQ, SubbandDataPt->m_predData.m_zeroVal, &SubbandDataPt->m_PoleCoeffData); /* Predictor filtering */ @@ -34,15 +33,13 @@ void processSubband_HD(const int32_t qCode, const int32_t ditherVal, } /* processSubband_HDLL is used for the LL subband only. */ -void processSubband_HDLL(const int32_t qCode, const int32_t ditherVal, - Subband_data* SubbandDataPt, +void processSubband_HDLL(const int32_t qCode, const int32_t ditherVal, Subband_data* SubbandDataPt, IQuantiser_data* iqDataPt) { /* Inverse quantisation */ invertQuantisation(qCode, ditherVal, iqDataPt); /* Predictor pole coefficient update */ - updatePredictorPoleCoefficients(iqDataPt->invQ, - SubbandDataPt->m_predData.m_zeroVal, + updatePredictorPoleCoefficients(iqDataPt->invQ, SubbandDataPt->m_predData.m_zeroVal, &SubbandDataPt->m_PoleCoeffData); /* Predictor filtering */ @@ -50,15 +47,13 @@ void processSubband_HDLL(const int32_t qCode, const int32_t ditherVal, } /* processSubband_HDLL is used for the HL subband only. */ -void processSubband_HDHL(const int32_t qCode, const int32_t ditherVal, - Subband_data* SubbandDataPt, +void processSubband_HDHL(const int32_t qCode, const int32_t ditherVal, Subband_data* SubbandDataPt, IQuantiser_data* iqDataPt) { /* Inverse quantisation */ invertQuantisationHL(qCode, ditherVal, iqDataPt); /* Predictor pole coefficient update */ - updatePredictorPoleCoefficients(iqDataPt->invQ, - SubbandDataPt->m_predData.m_zeroVal, + updatePredictorPoleCoefficients(iqDataPt->invQ, SubbandDataPt->m_predData.m_zeroVal, &SubbandDataPt->m_PoleCoeffData); /* Predictor filtering */ diff --git a/system/embdrv/encoder_for_aptxhd/src/Qmf.h b/system/embdrv/encoder_for_aptxhd/src/Qmf.h index 984c93b9ee1..bc5a11cd877 100644 --- a/system/embdrv/encoder_for_aptxhd/src/Qmf.h +++ b/system/embdrv/encoder_for_aptxhd/src/Qmf.h @@ -41,35 +41,35 @@ typedef struct { * different coefficients). The table defined in QmfConv.c */ #ifndef _STDQMFOUTERCOEFF static const int32_t Qmf_outerCoeffs[12] = { - /* (C(1/30)C(3/28)), C(5/26), C(7/24) */ - 0xFE6302DA, - 0xFFFFDA75, - 0x0000AA6A, - /* C(9/22), C(11/20), C(13/18), C(15/16) */ - 0xFFFE273E, - 0x00041E95, - 0xFFF710B5, - 0x002AC12E, - /* C(17/14), C(19/12), (C(21/10)C(23/8)) */ - 0x000AA328, - 0xFFFD8D1F, - 0x211E6BDB, - /* (C(25/6)C(27/4)), (C(29/2)C(31/0)) */ - 0x0DB7D8C5, - 0xFC7F02B0, + /* (C(1/30)C(3/28)), C(5/26), C(7/24) */ + 0xFE6302DA, + 0xFFFFDA75, + 0x0000AA6A, + /* C(9/22), C(11/20), C(13/18), C(15/16) */ + 0xFFFE273E, + 0x00041E95, + 0xFFF710B5, + 0x002AC12E, + /* C(17/14), C(19/12), (C(21/10)C(23/8)) */ + 0x000AA328, + 0xFFFD8D1F, + 0x211E6BDB, + /* (C(25/6)C(27/4)), (C(29/2)C(31/0)) */ + 0x0DB7D8C5, + 0xFC7F02B0, }; #else static const int32_t Qmf_outerCoeffs[16] = { - 730, -413, -9611, 43626, -121026, 269973, -585547, 2801966, - 697128, -160481, 27611, 8478, -10043, 3511, 688, -897, + 730, -413, -9611, 43626, -121026, 269973, -585547, 2801966, + 697128, -160481, 27611, 8478, -10043, 3511, 688, -897, }; #endif /* Each inner QMF filter for aptX HD is a symmetrical 32-tap filter (16 * different coefficients) */ static const int32_t Qmf_innerCoeffs[16] = { - 1033, -584, -13592, 61697, -171156, 381799, -828088, 3962579, - 985888, -226954, 39048, 11990, -14203, 4966, 973, -1268, + 1033, -584, -13592, 61697, -171156, 381799, -828088, 3962579, + 985888, -226954, 39048, 11990, -14203, 4966, 973, -1268, }; void AsmQmfConvI_HD(const int32_t* p1dl_buffPtr, const int32_t* p2dl_buffPtr, @@ -78,8 +78,7 @@ void AsmQmfConvO_HD(const int32_t* p1dl_buffPtr, const int32_t* p2dl_buffPtr, const int32_t* coeffPtr, int32_t* convSumDiff); XBT_INLINE_ void QmfAnalysisFilter(const int32_t pcm[4], Qmf_storage* Qmf_St, - const int32_t* predVals, - int32_t* aqmfOutputs) { + const int32_t* predVals, int32_t* aqmfOutputs) { int32_t convSumDiff[4]; int32_t filterOutputs[4]; @@ -99,8 +98,7 @@ XBT_INLINE_ void QmfAnalysisFilter(const int32_t pcm[4], Qmf_storage* Qmf_St, Qmf_St->QmfH_buf[lc_QmfO_pt++] = pcm[SecondPcm]; lc_QmfO_pt &= 0xF; - AsmQmfConvO_HD(&Qmf_St->QmfL_buf[lc_QmfO_pt + 15], - &Qmf_St->QmfH_buf[lc_QmfO_pt], Qmf_outerCoeffs, + AsmQmfConvO_HD(&Qmf_St->QmfL_buf[lc_QmfO_pt + 15], &Qmf_St->QmfH_buf[lc_QmfO_pt], Qmf_outerCoeffs, &convSumDiff[0]); /* Load outer filter phase1 and phase2 delay lines with the second 2 PCM @@ -111,8 +109,7 @@ XBT_INLINE_ void QmfAnalysisFilter(const int32_t pcm[4], Qmf_storage* Qmf_St, Qmf_St->QmfH_buf[lc_QmfO_pt++] = pcm[FourthPcm]; lc_QmfO_pt &= 0xF; - AsmQmfConvO_HD(&Qmf_St->QmfL_buf[lc_QmfO_pt + 15], - &Qmf_St->QmfH_buf[lc_QmfO_pt], Qmf_outerCoeffs, + AsmQmfConvO_HD(&Qmf_St->QmfL_buf[lc_QmfO_pt + 15], &Qmf_St->QmfH_buf[lc_QmfO_pt], Qmf_outerCoeffs, &convSumDiff[1]); /* Load the first inner filter phase1 and phase2 delay lines with the 2 @@ -124,9 +121,8 @@ XBT_INLINE_ void QmfAnalysisFilter(const int32_t pcm[4], Qmf_storage* Qmf_St, Qmf_St->QmfLH_buf[lc_QmfI_pt + 16] = convSumDiff[1]; Qmf_St->QmfLH_buf[lc_QmfI_pt] = convSumDiff[1]; - AsmQmfConvI_HD(&Qmf_St->QmfLL_buf[lc_QmfI_pt + 16], - &Qmf_St->QmfLH_buf[lc_QmfI_pt + 1], &Qmf_innerCoeffs[0], - &filterOutputs[LL]); + AsmQmfConvI_HD(&Qmf_St->QmfLL_buf[lc_QmfI_pt + 16], &Qmf_St->QmfLH_buf[lc_QmfI_pt + 1], + &Qmf_innerCoeffs[0], &filterOutputs[LL]); /* Load the second inner filter phase1 and phase2 delay lines with the 2 * convolution difference (high-pass) outer filter outputs. Convolve the @@ -139,9 +135,8 @@ XBT_INLINE_ void QmfAnalysisFilter(const int32_t pcm[4], Qmf_storage* Qmf_St, Qmf_St->QmfHH_buf[lc_QmfI_pt++] = convSumDiff[3]; lc_QmfI_pt &= 0xF; - AsmQmfConvI_HD(&Qmf_St->QmfHL_buf[lc_QmfI_pt + 15], - &Qmf_St->QmfHH_buf[lc_QmfI_pt], &Qmf_innerCoeffs[0], - &filterOutputs[HL]); + AsmQmfConvI_HD(&Qmf_St->QmfHL_buf[lc_QmfI_pt + 15], &Qmf_St->QmfHH_buf[lc_QmfI_pt], + &Qmf_innerCoeffs[0], &filterOutputs[HL]); /* Subtracted the previous predicted value from the filter output on a * per-subband basis. Ensure these values are saturated, if necessary. diff --git a/system/embdrv/encoder_for_aptxhd/src/QmfConv.c b/system/embdrv/encoder_for_aptxhd/src/QmfConv.c index 5312f65e50f..a5d406e5551 100644 --- a/system/embdrv/encoder_for_aptxhd/src/QmfConv.c +++ b/system/embdrv/encoder_for_aptxhd/src/QmfConv.c @@ -146,7 +146,7 @@ void AsmQmfConvO_HD(const int32_t* p1dl_buffPtr, const int32_t* p2dl_buffPtr, local_acc0 += 0x00400000L; acc = (int32_t)(local_acc0 >> 23); - if ((((tmp_round0 << 8) ^ 0x40000000) == 0)) { + if (((tmp_round0 << 8) ^ 0x40000000) == 0) { acc--; } @@ -163,7 +163,7 @@ void AsmQmfConvO_HD(const int32_t* p1dl_buffPtr, const int32_t* p2dl_buffPtr, local_acc1 += 0x00400000L; acc = (int32_t)(local_acc1 >> 23); - if ((((tmp_round0 << 8) ^ 0x40000000) == 0)) { + if (((tmp_round0 << 8) ^ 0x40000000) == 0) { acc--; } @@ -315,7 +315,7 @@ void AsmQmfConvI_HD(const int32_t* p1dl_buffPtr, const int32_t* p2dl_buffPtr, local_acc0 += 0x00400000L; acc = (int32_t)(local_acc0 >> 23); - if ((((tmp_round0 << 8) ^ 0x40000000) == 0)) { + if (((tmp_round0 << 8) ^ 0x40000000) == 0) { acc--; } @@ -332,7 +332,7 @@ void AsmQmfConvI_HD(const int32_t* p1dl_buffPtr, const int32_t* p2dl_buffPtr, local_acc1 += 0x00400000L; acc = (int32_t)(local_acc1 >> 23); - if ((((tmp_round0 << 8) ^ 0x40000000) == 0)) { + if (((tmp_round0 << 8) ^ 0x40000000) == 0) { acc--; } diff --git a/system/embdrv/encoder_for_aptxhd/src/QuantiseDifference.c b/system/embdrv/encoder_for_aptxhd/src/QuantiseDifference.c index cac8bf3aeb2..a07be07f1c7 100644 --- a/system/embdrv/encoder_for_aptxhd/src/QuantiseDifference.c +++ b/system/embdrv/encoder_for_aptxhd/src/QuantiseDifference.c @@ -16,8 +16,7 @@ #include "Quantiser.h" -XBT_INLINE_ int32_t BsearchLL(const int32_t absDiffSignalShifted, - const int32_t delta, +XBT_INLINE_ int32_t BsearchLL(const int32_t absDiffSignalShifted, const int32_t delta, const int32_t* dqbitTablePrt) { int32_t qCode = 0; reg64_t tmp_acc; @@ -79,11 +78,10 @@ XBT_INLINE_ int32_t BsearchLL(const int32_t absDiffSignalShifted, qCode++; } - return (qCode); + return qCode; } -XBT_INLINE_ int32_t BsearchHL(const int32_t absDiffSignalShifted, - const int32_t delta, +XBT_INLINE_ int32_t BsearchHL(const int32_t absDiffSignalShifted, const int32_t delta, const int32_t* dqbitTablePrt) { int32_t qCode = 0; reg64_t tmp_acc; @@ -111,11 +109,10 @@ XBT_INLINE_ int32_t BsearchHL(const int32_t absDiffSignalShifted, qCode++; } - return (qCode); + return qCode; } -XBT_INLINE_ int32_t BsearchHH(const int32_t absDiffSignalShifted, - const int32_t delta, +XBT_INLINE_ int32_t BsearchHH(const int32_t absDiffSignalShifted, const int32_t delta, const int32_t* dqbitTablePrt) { int32_t qCode = 0; reg64_t tmp_acc; @@ -150,11 +147,11 @@ XBT_INLINE_ int32_t BsearchHH(const int32_t absDiffSignalShifted, qCode++; } - return (qCode); + return qCode; } -void quantiseDifference_HDHL(const int32_t diffSignal, const int32_t ditherVal, - const int32_t delta, Quantiser_data* qdata_pt) { +void quantiseDifference_HDHL(const int32_t diffSignal, const int32_t ditherVal, const int32_t delta, + Quantiser_data* qdata_pt) { int32_t absDiffSignal = 0; int32_t absDiffSignalShifted = 0; int32_t index = 0; @@ -183,8 +180,7 @@ void quantiseDifference_HDHL(const int32_t diffSignal, const int32_t ditherVal, * table index of the LARGEST threshold table value for which * absDiffSignalShifted >= (delta * threshold) */ - index = - BsearchHL(absDiffSignalShifted, delta, qdata_pt->thresholdTablePtr_sl1); + index = BsearchHL(absDiffSignalShifted, delta, qdata_pt->thresholdTablePtr_sl1); /* We actually wanted the SMALLEST magnitude quantised code for which * absDiffSignalShifted < (delta * threshold) @@ -242,8 +238,7 @@ void quantiseDifference_HDHL(const int32_t diffSignal, const int32_t ditherVal, /* Form the threshold table difference at index and index-1. Ensure * saturation is applied to the difference calculation. */ - threshDiff = qdata_pt->thresholdTablePtr_sl1[index + 1] - - qdata_pt->thresholdTablePtr_sl1[index]; + threshDiff = qdata_pt->thresholdTablePtr_sl1[index + 1] - qdata_pt->thresholdTablePtr_sl1[index]; /* Based on the sign of the difference signal, either add or subtract the * threshold table difference from the accumulated value. Recover the final @@ -308,8 +303,8 @@ void quantiseDifference_HDHL(const int32_t diffSignal, const int32_t ditherVal, qdata_pt->qCode = tmp_qCode; } -void quantiseDifference_HDHH(const int32_t diffSignal, const int32_t ditherVal, - const int32_t delta, Quantiser_data* qdata_pt) { +void quantiseDifference_HDHH(const int32_t diffSignal, const int32_t ditherVal, const int32_t delta, + Quantiser_data* qdata_pt) { int32_t absDiffSignal; int32_t absDiffSignalShifted; int32_t index; @@ -338,8 +333,7 @@ void quantiseDifference_HDHH(const int32_t diffSignal, const int32_t ditherVal, * table index of the LARGEST threshold table value for which * absDiffSignalShifted >= (delta * threshold) */ - index = - BsearchHH(absDiffSignalShifted, delta, qdata_pt->thresholdTablePtr_sl1); + index = BsearchHH(absDiffSignalShifted, delta, qdata_pt->thresholdTablePtr_sl1); /* We actually wanted the SMALLEST magnitude quantised code for which * absDiffSignalShifted < (delta * threshold) @@ -398,8 +392,7 @@ void quantiseDifference_HDHH(const int32_t diffSignal, const int32_t ditherVal, /* Form the threshold table difference at index and index-1. Ensure * saturation is applied to the difference calculation. */ - threshDiff = qdata_pt->thresholdTablePtr_sl1[index + 1] - - qdata_pt->thresholdTablePtr_sl1[index]; + threshDiff = qdata_pt->thresholdTablePtr_sl1[index + 1] - qdata_pt->thresholdTablePtr_sl1[index]; /* Based on the sign of the difference signal, either add or subtract the * threshold table difference from the accumulated value. Recover the final @@ -463,8 +456,8 @@ void quantiseDifference_HDHH(const int32_t diffSignal, const int32_t ditherVal, qdata_pt->qCode = tmp_qCode; } -void quantiseDifference_HDLL(const int32_t diffSignal, const int32_t ditherVal, - const int32_t delta, Quantiser_data* qdata_pt) { +void quantiseDifference_HDLL(const int32_t diffSignal, const int32_t ditherVal, const int32_t delta, + Quantiser_data* qdata_pt) { int32_t absDiffSignal; int32_t absDiffSignalShifted; int32_t index; @@ -493,8 +486,7 @@ void quantiseDifference_HDLL(const int32_t diffSignal, const int32_t ditherVal, * table index of the LARGEST threshold table value for which * absDiffSignalShifted >= (delta * threshold) */ - index = - BsearchLL(absDiffSignalShifted, delta, qdata_pt->thresholdTablePtr_sl1); + index = BsearchLL(absDiffSignalShifted, delta, qdata_pt->thresholdTablePtr_sl1); /* We actually wanted the SMALLEST magnitude quantised code for which * absDiffSignalShifted < (delta * threshold) @@ -554,8 +546,7 @@ void quantiseDifference_HDLL(const int32_t diffSignal, const int32_t ditherVal, /* Form the threshold table difference at index and index-1. Ensure * saturation is applied to the difference calculation. */ - threshDiff = qdata_pt->thresholdTablePtr_sl1[index + 1] - - qdata_pt->thresholdTablePtr_sl1[index]; + threshDiff = qdata_pt->thresholdTablePtr_sl1[index + 1] - qdata_pt->thresholdTablePtr_sl1[index]; /* Based on the sign of the difference signal, either add or subtract the * threshold table difference from the accumulated value. Recover the final @@ -622,8 +613,8 @@ void quantiseDifference_HDLL(const int32_t diffSignal, const int32_t ditherVal, qdata_pt->qCode = tmp_qCode; } -static int32_t BsearchLH(const int32_t absDiffSignalShifted, - const int32_t delta, const int32_t* dqbitTablePrt) { +static int32_t BsearchLH(const int32_t absDiffSignalShifted, const int32_t delta, + const int32_t* dqbitTablePrt) { int32_t qCode; reg64_t tmp_acc; int32_t tmp; @@ -666,11 +657,11 @@ static int32_t BsearchLH(const int32_t absDiffSignalShifted, qCode++; } - return (qCode); + return qCode; } -void quantiseDifference_HDLH(const int32_t diffSignal, const int32_t ditherVal, - const int32_t delta, Quantiser_data* qdata_pt) { +void quantiseDifference_HDLH(const int32_t diffSignal, const int32_t ditherVal, const int32_t delta, + Quantiser_data* qdata_pt) { int32_t absDiffSignal = 0; int32_t absDiffSignalShifted = 0; int32_t index = 0; @@ -702,8 +693,7 @@ void quantiseDifference_HDLH(const int32_t diffSignal, const int32_t ditherVal, */ /* first iteration */ - index = - BsearchLH(absDiffSignalShifted, delta, qdata_pt->thresholdTablePtr_sl1); + index = BsearchLH(absDiffSignalShifted, delta, qdata_pt->thresholdTablePtr_sl1); /* We actually wanted the SMALLEST magnitude quantised code for which * absDiffSignalShifted < (delta * threshold) @@ -764,8 +754,7 @@ void quantiseDifference_HDLH(const int32_t diffSignal, const int32_t ditherVal, /* Form the threshold table difference at index and index-1. Ensure * saturation is applied to the difference calculation. */ - threshDiff = qdata_pt->thresholdTablePtr_sl1[index + 1] - - qdata_pt->thresholdTablePtr_sl1[index]; + threshDiff = qdata_pt->thresholdTablePtr_sl1[index + 1] - qdata_pt->thresholdTablePtr_sl1[index]; /* Based on the sign of the difference signal, either add or subtract the * threshold table difference from the accumulated value. Recover the final diff --git a/system/embdrv/encoder_for_aptxhd/src/Quantiser.h b/system/embdrv/encoder_for_aptxhd/src/Quantiser.h index 119f193ed2d..45df94557ae 100644 --- a/system/embdrv/encoder_for_aptxhd/src/Quantiser.h +++ b/system/embdrv/encoder_for_aptxhd/src/Quantiser.h @@ -28,14 +28,14 @@ #include "AptxParameters.h" -void quantiseDifference_HDLL(const int32_t diffSignal, const int32_t ditherVal, - const int32_t delta, Quantiser_data* qdata_pt); -void quantiseDifference_HDHL(const int32_t diffSignal, const int32_t ditherVal, - const int32_t delta, Quantiser_data* qdata_pt); -void quantiseDifference_HDLH(const int32_t diffSignal, const int32_t ditherVal, - const int32_t delta, Quantiser_data* qdata_pt); -void quantiseDifference_HDHH(const int32_t diffSignal, const int32_t ditherVal, - const int32_t delta, Quantiser_data* qdata_p); +void quantiseDifference_HDLL(const int32_t diffSignal, const int32_t ditherVal, const int32_t delta, + Quantiser_data* qdata_pt); +void quantiseDifference_HDHL(const int32_t diffSignal, const int32_t ditherVal, const int32_t delta, + Quantiser_data* qdata_pt); +void quantiseDifference_HDLH(const int32_t diffSignal, const int32_t ditherVal, const int32_t delta, + Quantiser_data* qdata_pt); +void quantiseDifference_HDHH(const int32_t diffSignal, const int32_t ditherVal, const int32_t delta, + Quantiser_data* qdata_p); #ifdef _GCC #pragma GCC visibility pop diff --git a/system/embdrv/encoder_for_aptxhd/src/SubbandFunctions.h b/system/embdrv/encoder_for_aptxhd/src/SubbandFunctions.h index 8802af72573..a3d509f0a6a 100644 --- a/system/embdrv/encoder_for_aptxhd/src/SubbandFunctions.h +++ b/system/embdrv/encoder_for_aptxhd/src/SubbandFunctions.h @@ -30,9 +30,8 @@ #include "AptxParameters.h" -XBT_INLINE_ void updatePredictorPoleCoefficients( - const int32_t invQ, const int32_t prevZfiltOutput, - PoleCoeff_data* PoleCoeffDataPt) { +XBT_INLINE_ void updatePredictorPoleCoefficients(const int32_t invQ, const int32_t prevZfiltOutput, + PoleCoeff_data* PoleCoeffDataPt) { int32_t adaptSum; int32_t sgnP[3]; int32_t newCoeffs[2]; @@ -68,24 +67,21 @@ XBT_INLINE_ void updatePredictorPoleCoefficients( sgnP[k] = minusOneQ22; sgnP[k_1] = -(((int32_t)PoleCoeffDataPt->m_poleAdaptDelayLine.s16.l) << 22); sgnP[k_2] = -(((int32_t)PoleCoeffDataPt->m_poleAdaptDelayLine.s16.h) << 22); - PoleCoeffDataPt->m_poleAdaptDelayLine.s16.h = - PoleCoeffDataPt->m_poleAdaptDelayLine.s16.l; + PoleCoeffDataPt->m_poleAdaptDelayLine.s16.h = PoleCoeffDataPt->m_poleAdaptDelayLine.s16.l; PoleCoeffDataPt->m_poleAdaptDelayLine.s16.l = -1; } if (adaptSum == 0L) { sgnP[k] = 0L; sgnP[k_1] = 0L; sgnP[k_2] = 0L; - PoleCoeffDataPt->m_poleAdaptDelayLine.s16.h = - PoleCoeffDataPt->m_poleAdaptDelayLine.s16.l; + PoleCoeffDataPt->m_poleAdaptDelayLine.s16.h = PoleCoeffDataPt->m_poleAdaptDelayLine.s16.l; PoleCoeffDataPt->m_poleAdaptDelayLine.s16.l = 1; } if (adaptSum > 0L) { sgnP[k] = oneQ22; sgnP[k_1] = ((int32_t)PoleCoeffDataPt->m_poleAdaptDelayLine.s16.l) << 22; sgnP[k_2] = ((int32_t)PoleCoeffDataPt->m_poleAdaptDelayLine.s16.h) << 22; - PoleCoeffDataPt->m_poleAdaptDelayLine.s16.h = - PoleCoeffDataPt->m_poleAdaptDelayLine.s16.l; + PoleCoeffDataPt->m_poleAdaptDelayLine.s16.h = PoleCoeffDataPt->m_poleAdaptDelayLine.s16.l; PoleCoeffDataPt->m_poleAdaptDelayLine.s16.l = 1; } diff --git a/system/embdrv/encoder_for_aptxhd/src/SubbandFunctionsCommon.h b/system/embdrv/encoder_for_aptxhd/src/SubbandFunctionsCommon.h index c52b7c66650..868b6786d2a 100644 --- a/system/embdrv/encoder_for_aptxhd/src/SubbandFunctionsCommon.h +++ b/system/embdrv/encoder_for_aptxhd/src/SubbandFunctionsCommon.h @@ -27,18 +27,15 @@ enum reg64_reg { reg64_H = 1, reg64_L = 0 }; -void processSubband_HD(const int32_t qCode, const int32_t ditherVal, - Subband_data* SubbandDataPt, IQuantiser_data* iqDataPt); -void processSubband_HDLL(const int32_t qCode, const int32_t ditherVal, - Subband_data* SubbandDataPt, +void processSubband_HD(const int32_t qCode, const int32_t ditherVal, Subband_data* SubbandDataPt, + IQuantiser_data* iqDataPt); +void processSubband_HDLL(const int32_t qCode, const int32_t ditherVal, Subband_data* SubbandDataPt, IQuantiser_data* iqDataPt); -void processSubband_HDHL(const int32_t qCode, const int32_t ditherVal, - Subband_data* SubbandDataPt, +void processSubband_HDHL(const int32_t qCode, const int32_t ditherVal, Subband_data* SubbandDataPt, IQuantiser_data* iqDataPt); /* Function to carry out inverse quantisation for a subband */ -XBT_INLINE_ void invertQuantisation(const int32_t qCode, - const int32_t ditherVal, +XBT_INLINE_ void invertQuantisation(const int32_t qCode, const int32_t ditherVal, IQuantiser_data* iqdata_pt) { int32_t invQ; int32_t index; @@ -135,8 +132,7 @@ XBT_INLINE_ void invertQuantisation(const int32_t qCode, iqdata_pt->invQ = invQ; } -XBT_INLINE_ void invertQuantisationHL(const int32_t qCode, - const int32_t ditherVal, +XBT_INLINE_ void invertQuantisationHL(const int32_t qCode, const int32_t ditherVal, IQuantiser_data* iqdata_pt) { int32_t invQ; int32_t index; @@ -235,8 +231,7 @@ XBT_INLINE_ void invertQuantisationHL(const int32_t qCode, /* Function to carry out prediction ARMA filtering for the current subband * performPredictionFiltering should only be used for HH and LH subband! */ -XBT_INLINE_ void performPredictionFiltering(const int32_t invQ, - Subband_data* SubbandDataPt) { +XBT_INLINE_ void performPredictionFiltering(const int32_t invQ, Subband_data* SubbandDataPt) { int32_t poleVal; int32_t acc; int64_t accL; @@ -263,8 +258,7 @@ XBT_INLINE_ void performPredictionFiltering(const int32_t invQ, /* Pole filter convolution. Shift convolution result 1 place to the left * before retrieving it, since the pole coefficients are Q22 (data is Q23) * and we want a Q23 result */ - accL = ((int64_t)poleCoeff[a2] * - (int64_t)SubbandDataPt->m_predData.m_poleDelayLine[a2]); + accL = ((int64_t)poleCoeff[a2] * (int64_t)SubbandDataPt->m_predData.m_poleDelayLine[a2]); /* Update the pole delay line for the next pass by writing the new input * sample into the 2nd element */ SubbandDataPt->m_predData.m_poleDelayLine[a2] = poleDelayLine; @@ -333,15 +327,14 @@ XBT_INLINE_ void performPredictionFiltering(const int32_t invQ, /* Update the zero filter delay line by writing the new input sample to the * circular buffer. */ SubbandDataPt->m_predData.m_zeroDelayLine - .buffer[SubbandDataPt->m_predData.m_zeroDelayLine.pointer] = - SubbandDataPt->m_predData.m_zeroDelayLine.modulo; + .buffer[SubbandDataPt->m_predData.m_zeroDelayLine.pointer] = + SubbandDataPt->m_predData.m_zeroDelayLine.modulo; SubbandDataPt->m_predData.m_zeroDelayLine - .buffer[SubbandDataPt->m_predData.m_zeroDelayLine.pointer + 12] = - SubbandDataPt->m_predData.m_zeroDelayLine.modulo; + .buffer[SubbandDataPt->m_predData.m_zeroDelayLine.pointer + 12] = + SubbandDataPt->m_predData.m_zeroDelayLine.modulo; } -XBT_INLINE_ void performPredictionFilteringLL(const int32_t invQ, - Subband_data* SubbandDataPt) { +XBT_INLINE_ void performPredictionFilteringLL(const int32_t invQ, Subband_data* SubbandDataPt) { int32_t poleVal; int32_t acc; int64_t accL; @@ -368,8 +361,7 @@ XBT_INLINE_ void performPredictionFilteringLL(const int32_t invQ, /* Pole filter convolution. Shift convolution result 1 place to the left * before retrieving it, since the pole coefficients are Q22 (data is Q23) * and we want a Q23 result */ - accL = ((int64_t)poleCoeff[a2] * - (int64_t)SubbandDataPt->m_predData.m_poleDelayLine[a2]); + accL = ((int64_t)poleCoeff[a2] * (int64_t)SubbandDataPt->m_predData.m_poleDelayLine[a2]); /* Update the pole delay line for the next pass by writing the new input * sample into the 2nd element */ SubbandDataPt->m_predData.m_poleDelayLine[a2] = poleDelayLine; @@ -438,15 +430,14 @@ XBT_INLINE_ void performPredictionFilteringLL(const int32_t invQ, /* Update the zero filter delay line by writing the new input sample to the * circular buffer. */ SubbandDataPt->m_predData.m_zeroDelayLine - .buffer[SubbandDataPt->m_predData.m_zeroDelayLine.pointer] = - SubbandDataPt->m_predData.m_zeroDelayLine.modulo; + .buffer[SubbandDataPt->m_predData.m_zeroDelayLine.pointer] = + SubbandDataPt->m_predData.m_zeroDelayLine.modulo; SubbandDataPt->m_predData.m_zeroDelayLine - .buffer[SubbandDataPt->m_predData.m_zeroDelayLine.pointer + 24] = - SubbandDataPt->m_predData.m_zeroDelayLine.modulo; + .buffer[SubbandDataPt->m_predData.m_zeroDelayLine.pointer + 24] = + SubbandDataPt->m_predData.m_zeroDelayLine.modulo; } -XBT_INLINE_ void performPredictionFilteringHL(const int32_t invQ, - Subband_data* SubbandDataPt) { +XBT_INLINE_ void performPredictionFilteringHL(const int32_t invQ, Subband_data* SubbandDataPt) { int32_t poleVal; int32_t acc; int64_t accL; @@ -474,8 +465,7 @@ XBT_INLINE_ void performPredictionFilteringHL(const int32_t invQ, /* Pole filter convolution. Shift convolution result 1 place to the left * before retrieving it, since the pole coefficients are Q22 (data is Q23) * and we want a Q23 result */ - accL = ((int64_t)poleCoeff[a2] * - (int64_t)SubbandDataPt->m_predData.m_poleDelayLine[a2]); + accL = ((int64_t)poleCoeff[a2] * (int64_t)SubbandDataPt->m_predData.m_poleDelayLine[a2]); /* Update the pole delay line for the next pass by writing the new input * sample into the 2nd element */ SubbandDataPt->m_predData.m_poleDelayLine[a2] = poleDelayLine; @@ -544,11 +534,11 @@ XBT_INLINE_ void performPredictionFilteringHL(const int32_t invQ, /* Update the zero filter delay line by writing the new input sample to the * circular buffer. */ SubbandDataPt->m_predData.m_zeroDelayLine - .buffer[SubbandDataPt->m_predData.m_zeroDelayLine.pointer] = - SubbandDataPt->m_predData.m_zeroDelayLine.modulo; + .buffer[SubbandDataPt->m_predData.m_zeroDelayLine.pointer] = + SubbandDataPt->m_predData.m_zeroDelayLine.modulo; SubbandDataPt->m_predData.m_zeroDelayLine - .buffer[SubbandDataPt->m_predData.m_zeroDelayLine.pointer + 6] = - SubbandDataPt->m_predData.m_zeroDelayLine.modulo; + .buffer[SubbandDataPt->m_predData.m_zeroDelayLine.pointer + 6] = + SubbandDataPt->m_predData.m_zeroDelayLine.modulo; } #endif // SUBBANDFUNCTIONSCOMMON_H diff --git a/system/embdrv/encoder_for_aptxhd/src/SyncInserter.h b/system/embdrv/encoder_for_aptxhd/src/SyncInserter.h index 1e21e8b816b..b1c62193467 100644 --- a/system/embdrv/encoder_for_aptxhd/src/SyncInserter.h +++ b/system/embdrv/encoder_for_aptxhd/src/SyncInserter.h @@ -33,8 +33,7 @@ * quantised codes spread across 2 aptX HD codewords (1 codeword * per channel) */ XBT_INLINE_ void xbtEncinsertSync(Encoder_data* leftChannelEncoder, - Encoder_data* rightChannelEncoder, - uint32_t* syncWordPhase) { + Encoder_data* rightChannelEncoder, uint32_t* syncWordPhase) { /* Currently using 0x1 as the 8-bit sync pattern */ static const uint32_t syncWord = 0x1; uint32_t tmp_var; @@ -65,8 +64,7 @@ XBT_INLINE_ void xbtEncinsertSync(Encoder_data* leftChannelEncoder, * of the left LL quantiser. Initialise the code lsbs XOR variable with the * left LL quantised code lsbs and also XOR in the left and right random * dither bit generated by the 2 encoders. */ - xorCodeLsbs = ((rightQuant[LL]->qCode) & 0x1) ^ - leftChannelEncoder->m_dithSyncRandBit ^ + xorCodeLsbs = ((rightQuant[LL]->qCode) & 0x1) ^ leftChannelEncoder->m_dithSyncRandBit ^ rightChannelEncoder->m_dithSyncRandBit; minPenaltyQuantiser = rightQuant[LH]; diff --git a/system/embdrv/encoder_for_aptxhd/src/aptXHDbtenc.c b/system/embdrv/encoder_for_aptxhd/src/aptXHDbtenc.c index 8d93d9d37c7..34b3424445c 100644 --- a/system/embdrv/encoder_for_aptxhd/src/aptXHDbtenc.c +++ b/system/embdrv/encoder_for_aptxhd/src/aptXHDbtenc.c @@ -42,13 +42,11 @@ typedef struct aptxhdbtenc_t { /* Log to linear lookup table used in inverse quantiser*/ /* Size of Table: 32*4 = 128 bytes */ static const int32_t IQuant_tableLogT[32] = { - 16384 * 256, 16744 * 256, 17112 * 256, 17488 * 256, 17864 * 256, - 18256 * 256, 18656 * 256, 19064 * 256, 19480 * 256, 19912 * 256, - 20344 * 256, 20792 * 256, 21248 * 256, 21712 * 256, 22192 * 256, - 22672 * 256, 23168 * 256, 23680 * 256, 24200 * 256, 24728 * 256, - 25264 * 256, 25824 * 256, 26384 * 256, 26968 * 256, 27552 * 256, - 28160 * 256, 28776 * 256, 29408 * 256, 30048 * 256, 30704 * 256, - 31376 * 256, 32064 * 256}; + 16384 * 256, 16744 * 256, 17112 * 256, 17488 * 256, 17864 * 256, 18256 * 256, 18656 * 256, + 19064 * 256, 19480 * 256, 19912 * 256, 20344 * 256, 20792 * 256, 21248 * 256, 21712 * 256, + 22192 * 256, 22672 * 256, 23168 * 256, 23680 * 256, 24200 * 256, 24728 * 256, 25264 * 256, + 25824 * 256, 26384 * 256, 26968 * 256, 27552 * 256, 28160 * 256, 28776 * 256, 29408 * 256, + 30048 * 256, 30704 * 256, 31376 * 256, 32064 * 256}; static void clearmem_HD(void* mem, int32_t sz) { int8_t* m = (int8_t*)mem; @@ -59,9 +57,9 @@ static void clearmem_HD(void* mem, int32_t sz) { } } -APTXHDBTENCEXPORT int SizeofAptxhdbtenc() { return (sizeof(aptxhdbtenc)); } +APTXHDBTENCEXPORT int SizeofAptxhdbtenc() { return sizeof(aptxhdbtenc); } -APTXHDBTENCEXPORT const char* aptxhdbtenc_version() { return (swversion); } +APTXHDBTENCEXPORT const char* aptxhdbtenc_version() { return swversion; } APTXHDBTENCEXPORT int aptxhdbtenc_init(void* _state, short endian) { aptxhdbtenc* state = (aptxhdbtenc*)_state; @@ -87,40 +85,31 @@ APTXHDBTENCEXPORT int aptxhdbtenc_init(void* _state, short endian) { for (i = LL; i <= HH; i++) { encode_dat->m_codewordHistory = 0L; - encode_dat->m_qdata[i].thresholdTablePtr = - subbandParameters[i].threshTable; - encode_dat->m_qdata[i].thresholdTablePtr_sl1 = - subbandParameters[i].threshTable_sl1; + encode_dat->m_qdata[i].thresholdTablePtr = subbandParameters[i].threshTable; + encode_dat->m_qdata[i].thresholdTablePtr_sl1 = subbandParameters[i].threshTable_sl1; encode_dat->m_qdata[i].ditherTablePtr = subbandParameters[i].dithTable; - encode_dat->m_qdata[i].minusLambdaDTable = - subbandParameters[i].minusLambdaDTable; + encode_dat->m_qdata[i].minusLambdaDTable = subbandParameters[i].minusLambdaDTable; encode_dat->m_qdata[i].codeBits = subbandParameters[i].numBits; encode_dat->m_qdata[i].qCode = 0L; encode_dat->m_qdata[i].altQcode = 0L; encode_dat->m_qdata[i].distPenalty = 0L; /* initialisation of inverseQuantiser data */ - encode_dat->m_SubbandData[i].m_iqdata.thresholdTablePtr = - subbandParameters[i].threshTable; + encode_dat->m_SubbandData[i].m_iqdata.thresholdTablePtr = subbandParameters[i].threshTable; encode_dat->m_SubbandData[i].m_iqdata.thresholdTablePtr_sl1 = - subbandParameters[i].threshTable_sl1; - encode_dat->m_SubbandData[i].m_iqdata.ditherTablePtr_sf1 = - subbandParameters[i].dithTable_sh1; - encode_dat->m_SubbandData[i].m_iqdata.incrTablePtr = - subbandParameters[i].incrTable; - encode_dat->m_SubbandData[i].m_iqdata.maxLogDelta = - subbandParameters[i].maxLogDelta; - encode_dat->m_SubbandData[i].m_iqdata.minLogDelta = - subbandParameters[i].minLogDelta; + subbandParameters[i].threshTable_sl1; + encode_dat->m_SubbandData[i].m_iqdata.ditherTablePtr_sf1 = subbandParameters[i].dithTable_sh1; + encode_dat->m_SubbandData[i].m_iqdata.incrTablePtr = subbandParameters[i].incrTable; + encode_dat->m_SubbandData[i].m_iqdata.maxLogDelta = subbandParameters[i].maxLogDelta; + encode_dat->m_SubbandData[i].m_iqdata.minLogDelta = subbandParameters[i].minLogDelta; encode_dat->m_SubbandData[i].m_iqdata.delta = 0; encode_dat->m_SubbandData[i].m_iqdata.logDelta = 0; encode_dat->m_SubbandData[i].m_iqdata.invQ = 0; - encode_dat->m_SubbandData[i].m_iqdata.iquantTableLogPtr = - &IQuant_tableLogT[0]; + encode_dat->m_SubbandData[i].m_iqdata.iquantTableLogPtr = &IQuant_tableLogT[0]; // Initializing data for predictor filter encode_dat->m_SubbandData[i].m_predData.m_zeroDelayLine.modulo = - subbandParameters[i].numZeros; + subbandParameters[i].numZeros; for (int t = 0; t < 48; t++) { encode_dat->m_SubbandData[i].m_predData.m_zeroDelayLine.buffer[t] = 0; @@ -131,8 +120,7 @@ APTXHDBTENCEXPORT int aptxhdbtenc_init(void* _state, short endian) { */ encode_dat->m_SubbandData[i].m_predData.m_zeroVal = 0L; encode_dat->m_SubbandData[i].m_predData.m_predVal = 0L; - encode_dat->m_SubbandData[i].m_predData.m_numZeros = - subbandParameters[i].numZeros; + encode_dat->m_SubbandData[i].m_predData.m_numZeros = subbandParameters[i].numZeros; /* Initialise the contents of the pole data delay line to zero */ encode_dat->m_SubbandData[i].m_predData.m_poleDelayLine[0] = 0L; encode_dat->m_SubbandData[i].m_predData.m_poleDelayLine[1] = 0L; @@ -142,13 +130,11 @@ APTXHDBTENCEXPORT int aptxhdbtenc_init(void* _state, short endian) { } // Initializing data for zerocoeff update function. - encode_dat->m_SubbandData[i].m_ZeroCoeffData.m_numZeros = - subbandParameters[i].numZeros; + encode_dat->m_SubbandData[i].m_ZeroCoeffData.m_numZeros = subbandParameters[i].numZeros; /* Initializing data for PoleCoeff Update function. * Fill the adaptation delay line with +1 initially */ - encode_dat->m_SubbandData[i].m_PoleCoeffData.m_poleAdaptDelayLine.s32 = - 0x00010001; + encode_dat->m_SubbandData[i].m_PoleCoeffData.m_poleAdaptDelayLine.s32 = 0x00010001; /* Zero the pole coefficients */ encode_dat->m_SubbandData[i].m_PoleCoeffData.m_poleCoeff[0] = 0L; @@ -158,8 +144,8 @@ APTXHDBTENCEXPORT int aptxhdbtenc_init(void* _state, short endian) { return 0; } -APTXHDBTENCEXPORT int aptxhdbtenc_encodestereo(void* _state, void* _pcmL, - void* _pcmR, void* _buffer) { +APTXHDBTENCEXPORT int aptxhdbtenc_encodestereo(void* _state, void* _pcmL, void* _pcmR, + void* _buffer) { aptxhdbtenc* state = (aptxhdbtenc*)_state; int32_t* pcmL = (int32_t*)_pcmL; int32_t* pcmR = (int32_t*)_pcmR; @@ -170,8 +156,7 @@ APTXHDBTENCEXPORT int aptxhdbtenc_encodestereo(void* _state, void* _pcmL, aptxhdEncode(pcmR, &state->m_qmf_r, &state->m_encoderData[1]); // Insert the autosync information into the stereo quantised codes - xbtEncinsertSync(&state->m_encoderData[0], &state->m_encoderData[1], - &state->m_syncWordPhase); + xbtEncinsertSync(&state->m_encoderData[0], &state->m_encoderData[1], &state->m_syncWordPhase); aptxhdPostEncode(&state->m_encoderData[0]); aptxhdPostEncode(&state->m_encoderData[1]); diff --git a/system/embdrv/g722/fuzzer/g722_fuzzer.cc b/system/embdrv/g722/fuzzer/g722_fuzzer.cc index 6dd14c28839..de079d0e7dd 100644 --- a/system/embdrv/g722/fuzzer/g722_fuzzer.cc +++ b/system/embdrv/g722/fuzzer/g722_fuzzer.cc @@ -22,7 +22,7 @@ namespace { uint32_t get_rate_from_fdp(FuzzedDataProvider* fdp) { uint32_t rate = fdp->ConsumeIntegralInRange( - 0, 3); // Currently 3 different bit rates are available in G.722 codec + 0, 3); // Currently 3 different bit rates are available in G.722 codec switch (rate) { case 0: return 48000; @@ -37,8 +37,7 @@ void fuzz_encode(FuzzedDataProvider* fdp) { uint32_t rate = get_rate_from_fdp(fdp); std::vector buff = fdp->ConsumeRemainingBytes(); - int num_samples = - buff.size() / (2 /*bytes_per_sample*/ * 2 /*number of channels*/); + int num_samples = buff.size() / (2 /*bytes_per_sample*/ * 2 /*number of channels*/); // The G.722 codec accept only even number of samples for encoding if (num_samples % 2 != 0) { @@ -72,9 +71,8 @@ void fuzz_encode(FuzzedDataProvider* fdp) { // used "size" of the input that libfuzzer generates as the initial // parameter to resize encoded_data.resize(buff.size()); - int encoded_size = - g722_encode(encoder_state, encoded_data.data(), - (const int16_t*)channel_data.data(), channel_data.size()); + int encoded_size = g722_encode(encoder_state, encoded_data.data(), + (const int16_t*)channel_data.data(), channel_data.size()); encoded_data.resize(encoded_size); // Encoder release @@ -95,15 +93,13 @@ void fuzz_decode(FuzzedDataProvider* fdp) { decoder_state = g722_decode_init(decoder_state, rate, options); std::vector encoded_input = fdp->ConsumeRemainingBytes(); - int out_len = - encoded_input.size() * 2 /*bytes_per_sample*/ * 2 /*number of channels*/; + int out_len = encoded_input.size() * 2 /*bytes_per_sample*/ * 2 /*number of channels*/; // Decode std::vector decoded_output; decoded_output.resize(out_len); int decoded_size = g722_decode(decoder_state, decoded_output.data(), - (const uint8_t*)encoded_input.data(), - encoded_input.size(), gain); + (const uint8_t*)encoded_input.data(), encoded_input.size(), gain); if (decoded_size > decoded_output.size()) { abort(); } diff --git a/system/embdrv/g722/g722_decode.cc b/system/embdrv/g722/g722_decode.cc index 356e6db34bc..5b43b0b289c 100644 --- a/system/embdrv/g722/g722_decode.cc +++ b/system/embdrv/g722/g722_decode.cc @@ -7,7 +7,7 @@ * * Copyright (C) 2005 Steve Underwood * - * Despite my general liking of the GPL, I place my own contributions + * Despite my general liking of the GPL, I place my own contributions * to this code in the public domain for the benefit of all mankind - * even the slimy ones who might try to proprietize my work and use it * to my detriment. @@ -23,12 +23,12 @@ /*! \file */ -#include #include #include +#include -#include "g722_typedefs.h" #include "g722_enc_dec.h" +#include "g722_typedefs.h" #if !defined(FALSE) #define FALSE 0 @@ -37,33 +37,29 @@ #define TRUE (!FALSE) #endif -#define PACKED_INPUT (0) +#define PACKED_INPUT (0) #define BITS_PER_SAMPLE (8) #ifndef BUILD_FEATURE_G722_USE_INTRINSIC_SAT -static __inline int16_t __ssat16(int32_t amp) -{ - int16_t amp16; - - /* Hopefully this is optimised for the common case - not clipping */ - amp16 = (int16_t) amp; - if (amp == amp16) - return amp16; - if (amp > 0x7fff) - return 0x7fff; - return 0x8000; +static __inline int16_t __ssat16(int32_t amp) { + int16_t amp16; + + /* Hopefully this is optimised for the common case - not clipping */ + amp16 = (int16_t)amp; + if (amp == amp16) { + return amp16; + } + if (amp > 0x7fff) { + return 0x7fff; + } + return 0x8000; } /*- End of function --------------------------------------------------------*/ #else -static __inline int16_t __ssat16( int32_t val) -{ - register int32_t res; - __asm volatile ( - "SSAT %0, #16, %1\n\t" - :"=r"(res) - :"r"(val) - :); - return (int16_t)res; +static __inline int16_t __ssat16(int32_t val) { + register int32_t res; + __asm volatile("SSAT %0, #16, %1\n\t" : "=r"(res) : "r"(val) :); + return (int16_t)res; } #endif @@ -71,154 +67,140 @@ static __inline int16_t __ssat16( int32_t val) static void block4(g722_band_t *band, int d); -static void block4(g722_band_t *band, int d) -{ - int wd1; - int wd2; - int wd3; - int i; - int sg[7]; - int ap1, ap2; - int sg0, sgi; - int sz; - - /* Block 4, RECONS */ - band->d[0] = d; - band->r[0] = __ssat16(band->s + d); - - /* Block 4, PARREC */ - band->p[0] = __ssat16(band->sz + d); - - /* Block 4, UPPOL2 */ - for (i = 0; i < 3; i++) - { - sg[i] = band->p[i] >> 15; - } - wd1 = __ssat16(band->a[1] << 2); - - wd2 = (sg[0] == sg[1]) ? -wd1 : wd1; - if (wd2 > 32767) - wd2 = 32767; - - ap2 = (sg[0] == sg[2]) ? 128 : -128; - ap2 += (wd2 >> 7); - ap2 += (band->a[2]*32512) >> 15; - if (ap2 > 12288) - ap2 = 12288; - else if (ap2 < -12288) - ap2 = -12288; - band->ap[2] = ap2; - - /* Block 4, UPPOL1 */ - sg[0] = band->p[0] >> 15; - sg[1] = band->p[1] >> 15; - wd1 = (sg[0] == sg[1]) ? 192 : -192; - wd2 = (band->a[1]*32640) >> 15; - - ap1 = __ssat16(wd1 + wd2); - wd3 = __ssat16(15360 - band->ap[2]); - if (ap1 > wd3) - ap1 = wd3; - else if (ap1 < -wd3) - ap1 = -wd3; - band->ap[1] = ap1; - - /* Block 4, UPZERO */ - /* Block 4, FILTEZ */ - wd1 = (d == 0) ? 0 : 128; - - sg0 = sg[0] = d >> 15; - for (i = 1; i < 7; i++) - { - sgi = band->d[i] >> 15; - wd2 = (sgi == sg0) ? wd1 : -wd1; - wd3 = (band->b[i]*32640) >> 15; - band->bp[i] = __ssat16(wd2 + wd3); - } - - /* Block 4, DELAYA */ - sz = 0; - for (i = 6; i > 0; i--) - { - int bi; - - band->d[i] = band->d[i - 1]; - bi = band->b[i] = band->bp[i]; - wd1 = __ssat16(band->d[i] + band->d[i]); - sz += (bi*wd1) >> 15; - } - band->sz = sz; - - for (i = 2; i > 0; i--) - { - band->r[i] = band->r[i - 1]; - band->p[i] = band->p[i - 1]; - band->a[i] = band->ap[i]; - } - - /* Block 4, FILTEP */ - wd1 = __ssat16(band->r[1] + band->r[1]); - wd1 = (band->a[1]*wd1) >> 15; - wd2 = __ssat16(band->r[2] + band->r[2]); - wd2 = (band->a[2]*wd2) >> 15; - band->sp = __ssat16(wd1 + wd2); - - /* Block 4, PREDIC */ - band->s = __ssat16(band->sp + band->sz); +static void block4(g722_band_t *band, int d) { + int wd1; + int wd2; + int wd3; + int i; + int sg[7]; + int ap1, ap2; + int sg0, sgi; + int sz; + + /* Block 4, RECONS */ + band->d[0] = d; + band->r[0] = __ssat16(band->s + d); + + /* Block 4, PARREC */ + band->p[0] = __ssat16(band->sz + d); + + /* Block 4, UPPOL2 */ + for (i = 0; i < 3; i++) { + sg[i] = band->p[i] >> 15; + } + wd1 = __ssat16(band->a[1] << 2); + + wd2 = (sg[0] == sg[1]) ? -wd1 : wd1; + if (wd2 > 32767) { + wd2 = 32767; + } + + ap2 = (sg[0] == sg[2]) ? 128 : -128; + ap2 += (wd2 >> 7); + ap2 += (band->a[2] * 32512) >> 15; + if (ap2 > 12288) { + ap2 = 12288; + } else if (ap2 < -12288) { + ap2 = -12288; + } + band->ap[2] = ap2; + + /* Block 4, UPPOL1 */ + sg[0] = band->p[0] >> 15; + sg[1] = band->p[1] >> 15; + wd1 = (sg[0] == sg[1]) ? 192 : -192; + wd2 = (band->a[1] * 32640) >> 15; + + ap1 = __ssat16(wd1 + wd2); + wd3 = __ssat16(15360 - band->ap[2]); + if (ap1 > wd3) { + ap1 = wd3; + } else if (ap1 < -wd3) { + ap1 = -wd3; + } + band->ap[1] = ap1; + + /* Block 4, UPZERO */ + /* Block 4, FILTEZ */ + wd1 = (d == 0) ? 0 : 128; + + sg0 = sg[0] = d >> 15; + for (i = 1; i < 7; i++) { + sgi = band->d[i] >> 15; + wd2 = (sgi == sg0) ? wd1 : -wd1; + wd3 = (band->b[i] * 32640) >> 15; + band->bp[i] = __ssat16(wd2 + wd3); + } + + /* Block 4, DELAYA */ + sz = 0; + for (i = 6; i > 0; i--) { + int bi; + + band->d[i] = band->d[i - 1]; + bi = band->b[i] = band->bp[i]; + wd1 = __ssat16(band->d[i] + band->d[i]); + sz += (bi * wd1) >> 15; + } + band->sz = sz; + + for (i = 2; i > 0; i--) { + band->r[i] = band->r[i - 1]; + band->p[i] = band->p[i - 1]; + band->a[i] = band->ap[i]; + } + + /* Block 4, FILTEP */ + wd1 = __ssat16(band->r[1] + band->r[1]); + wd1 = (band->a[1] * wd1) >> 15; + wd2 = __ssat16(band->r[2] + band->r[2]); + wd2 = (band->a[2] * wd2) >> 15; + band->sp = __ssat16(wd1 + wd2); + + /* Block 4, PREDIC */ + band->s = __ssat16(band->sp + band->sz); } /*- End of function --------------------------------------------------------*/ -g722_decode_state_t *g722_decode_init(g722_decode_state_t *s, unsigned int rate, int options) -{ - if (s == NULL) - { +g722_decode_state_t *g722_decode_init(g722_decode_state_t *s, unsigned int rate, int options) { + if (s == NULL) { #ifdef G722_SUPPORT_MALLOC - if ((s = (g722_decode_state_t *) malloc(sizeof(*s))) == NULL) + if ((s = (g722_decode_state_t *)malloc(sizeof(*s))) == NULL) #endif - return NULL; - } - memset(s, 0, sizeof(*s)); - if (rate == 48000) - s->bits_per_sample = 6; - else if (rate == 56000) - s->bits_per_sample = 7; - else - s->bits_per_sample = 8; - s->dac_pcm = options & G722_FORMAT_DAC12; - s->band[0].det = 32; - s->band[1].det = 8; - return s; + return NULL; + } + memset(s, 0, sizeof(*s)); + if (rate == 48000) { + s->bits_per_sample = 6; + } else if (rate == 56000) { + s->bits_per_sample = 7; + } else { + s->bits_per_sample = 8; + } + s->dac_pcm = options & G722_FORMAT_DAC12; + s->band[0].det = 32; + s->band[1].det = 8; + return s; } /*- End of function --------------------------------------------------------*/ -int g722_decode_release(g722_decode_state_t *s) -{ - free(s); - return 0; +int g722_decode_release(g722_decode_state_t *s) { + free(s); + return 0; } /*- End of function --------------------------------------------------------*/ -static int16_t wl[8] = {-60, -30, 58, 172, 334, 538, 1198, 3042 }; -static int16_t rl42[16] = {0, 7, 6, 5, 4, 3, 2, 1, 7, 6, 5, 4, 3, 2, 1, 0 }; -static int16_t ilb[32] = -{ - 2048, 2093, 2139, 2186, 2233, 2282, 2332, - 2383, 2435, 2489, 2543, 2599, 2656, 2714, - 2774, 2834, 2896, 2960, 3025, 3091, 3158, - 3228, 3298, 3371, 3444, 3520, 3597, 3676, - 3756, 3838, 3922, 4008 -}; +static int16_t wl[8] = {-60, -30, 58, 172, 334, 538, 1198, 3042}; +static int16_t rl42[16] = {0, 7, 6, 5, 4, 3, 2, 1, 7, 6, 5, 4, 3, 2, 1, 0}; +static int16_t ilb[32] = {2048, 2093, 2139, 2186, 2233, 2282, 2332, 2383, 2435, 2489, 2543, + 2599, 2656, 2714, 2774, 2834, 2896, 2960, 3025, 3091, 3158, 3228, + 3298, 3371, 3444, 3520, 3597, 3676, 3756, 3838, 3922, 4008}; static int16_t wh[3] = {0, -214, 798}; static int16_t rh2[4] = {2, 1, 2, 1}; -static int16_t qm2[4] = {-7408, -1616, 7408, 1616}; -static int16_t qm4[16] = -{ - 0, -20456, -12896, -8968, - -6288, -4240, -2584, -1200, - 20456, 12896, 8968, 6288, - 4240, 2584, 1200, 0 -}; +static int16_t qm2[4] = {-7408, -1616, 7408, 1616}; +static int16_t qm4[16] = {0, -20456, -12896, -8968, -6288, -4240, -2584, -1200, + 20456, 12896, 8968, 6288, 4240, 2584, 1200, 0}; #if 0 static const int qm5[32] = { @@ -232,190 +214,164 @@ static const int qm5[32] = 1520, 880, 280, -280 }; #endif -static int16_t qm6[64] = -{ - -136, -136, -136, -136, - -24808, -21904, -19008, -16704, - -14984, -13512, -12280, -11192, - -10232, -9360, -8576, -7856, - -7192, -6576, -6000, -5456, - -4944, -4464, -4008, -3576, - -3168, -2776, -2400, -2032, - -1688, -1360, -1040, -728, - 24808, 21904, 19008, 16704, - 14984, 13512, 12280, 11192, - 10232, 9360, 8576, 7856, - 7192, 6576, 6000, 5456, - 4944, 4464, 4008, 3576, - 3168, 2776, 2400, 2032, - 1688, 1360, 1040, 728, - 432, 136, -432, -136 -}; -static int16_t qmf_coeffs_even[12] = -{ - 3, -11, 12, 32, -210, 951, 3876, -805, 362, -156, 53, -11, -}; -static int16_t qmf_coeffs_odd[12] = -{ - -11, 53, -156, 362, -805, 3876, 951, -210, 32, 12, -11, 3 +static int16_t qm6[64] = { + -136, -136, -136, -136, -24808, -21904, -19008, -16704, -14984, -13512, -12280, + -11192, -10232, -9360, -8576, -7856, -7192, -6576, -6000, -5456, -4944, -4464, + -4008, -3576, -3168, -2776, -2400, -2032, -1688, -1360, -1040, -728, 24808, + 21904, 19008, 16704, 14984, 13512, 12280, 11192, 10232, 9360, 8576, 7856, + 7192, 6576, 6000, 5456, 4944, 4464, 4008, 3576, 3168, 2776, 2400, + 2032, 1688, 1360, 1040, 728, 432, 136, -432, -136}; +static int16_t qmf_coeffs_even[12] = { + 3, -11, 12, 32, -210, 951, 3876, -805, 362, -156, 53, -11, }; - -uint32_t g722_decode(g722_decode_state_t *s, int16_t amp[], const uint8_t g722_data[], int len, uint16_t gain) -{ - - int dlowt; - int rlow; - int ihigh; - int dhigh; - int rhigh; - int xout1; - int xout2; - int wd1; - int wd2; - int wd3; - int code; - uint32_t outlen; - int i; - int j; - - outlen = 0; - rhigh = 0; - - for (j = 0; j < len; ) - { +static int16_t qmf_coeffs_odd[12] = {-11, 53, -156, 362, -805, 3876, 951, -210, 32, 12, -11, 3}; + +uint32_t g722_decode(g722_decode_state_t *s, int16_t amp[], const uint8_t g722_data[], int len, + uint16_t gain) { + int dlowt; + int rlow; + int ihigh; + int dhigh; + int rhigh; + int xout1; + int xout2; + int wd1; + int wd2; + int wd3; + int code; + uint32_t outlen; + int i; + int j; + + outlen = 0; + rhigh = 0; + + for (j = 0; j < len;) { #if PACKED_INPUT == 1 - /* Unpack the code bits */ - if (s->in_bits < s->bits_per_sample) - { - s->in_buffer |= (g722_data[j++] << s->in_bits); - s->in_bits += 8; - } - code = s->in_buffer & ((1 << s->bits_per_sample) - 1); - s->in_buffer >>= s->bits_per_sample; - s->in_bits -= s->bits_per_sample; + /* Unpack the code bits */ + if (s->in_bits < s->bits_per_sample) { + s->in_buffer |= (g722_data[j++] << s->in_bits); + s->in_bits += 8; + } + code = s->in_buffer & ((1 << s->bits_per_sample) - 1); + s->in_buffer >>= s->bits_per_sample; + s->in_bits -= s->bits_per_sample; #else - code = g722_data[j++]; + code = g722_data[j++]; #endif #if BITS_PER_SAMPLE == 8 - wd1 = code & 0x3F; - ihigh = (code >> 6) & 0x03; - wd2 = qm6[wd1]; - wd1 >>= 2; + wd1 = code & 0x3F; + ihigh = (code >> 6) & 0x03; + wd2 = qm6[wd1]; + wd1 >>= 2; #elif BITS_PER_SAMPLE == 7 - wd1 = code & 0x1F; - ihigh = (code >> 5) & 0x03; - wd2 = qm5[wd1]; - wd1 >>= 1; + wd1 = code & 0x1F; + ihigh = (code >> 5) & 0x03; + wd2 = qm5[wd1]; + wd1 >>= 1; #elif BITS_PER_SAMPLE == 6 - wd1 = code & 0x0F; - ihigh = (code >> 4) & 0x03; - wd2 = qm4[wd1]; + wd1 = code & 0x0F; + ihigh = (code >> 4) & 0x03; + wd2 = qm4[wd1]; #endif - /* Block 5L, LOW BAND INVQBL */ - wd2 = (s->band[0].det*wd2) >> 15; - /* Block 5L, RECONS */ - rlow = s->band[0].s + wd2; - /* Block 6L, LIMIT */ - - // ANDREA - // rlow=ssat(rlow,2<<14) - if (rlow > 16383) - { - rlow = 16383; - } - else if (rlow < -16384) - { - rlow = -16384; - } - - /* Block 2L, INVQAL */ - wd2 = qm4[wd1]; - dlowt = (s->band[0].det*wd2) >> 15; - - /* Block 3L, LOGSCL */ - wd2 = rl42[wd1]; - wd1 = (s->band[0].nb*127) >> 7; - wd1 += wl[wd2]; - if (wd1 < 0) - { - wd1 = 0; - } - else if (wd1 > 18432) - { - wd1 = 18432; - } - s->band[0].nb = wd1; - - /* Block 3L, SCALEL */ - wd1 = (s->band[0].nb >> 6) & 31; - wd2 = 8 - (s->band[0].nb >> 11); - wd3 = (wd2 < 0) ? (ilb[wd1] << -wd2) : (ilb[wd1] >> wd2); - s->band[0].det = wd3 << 2; - - block4(&s->band[0], dlowt); - - /* Block 2H, INVQAH */ - wd2 = qm2[ihigh]; - dhigh = (s->band[1].det*wd2) >> 15; - /* Block 5H, RECONS */ - rhigh = dhigh + s->band[1].s; - /* Block 6H, LIMIT */ - - // ANDREA - // rhigh=ssat(rhigh,2<<14) - - if (rhigh > 16383) - rhigh = 16383; - else if (rhigh < -16384) - rhigh = -16384; - - /* Block 2H, INVQAH */ - wd2 = rh2[ihigh]; - wd1 = (s->band[1].nb*127) >> 7; - wd1 += wh[wd2]; - if (wd1 < 0) - wd1 = 0; - else if (wd1 > 22528) - wd1 = 22528; - s->band[1].nb = wd1; - - /* Block 3H, SCALEH */ - wd1 = (s->band[1].nb >> 6) & 31; - wd2 = 10 - (s->band[1].nb >> 11); - wd3 = (wd2 < 0) ? (ilb[wd1] << -wd2) : (ilb[wd1] >> wd2); - s->band[1].det = wd3 << 2; - - block4(&s->band[1], dhigh); - - /* Apply the receive QMF */ - for (i = 0; i < 22; i++) - s->x[i] = s->x[i + 2]; - s->x[22] = rlow + rhigh; - s->x[23] = rlow - rhigh; - - // we should get PERF numbers for the following loop - xout1 = 0; - xout2 = 0; - for (i = 0; i < 12; i++) - { - xout2 += s->x[2*i] * qmf_coeffs_even[i]; - xout1 += s->x[2*i+1] * qmf_coeffs_odd[i]; - } - xout1 = NLDECOMPRESS_PREPROCESS_SAMPLE_WITH_GAIN((int16_t) __ssat16(xout1 >> 11), gain); - xout2 = NLDECOMPRESS_PREPROCESS_SAMPLE_WITH_GAIN((int16_t) __ssat16(xout2 >> 11), gain); - if (s->dac_pcm) - { - amp[outlen++] = ((int16_t) (xout1 >> 4) + 2048); - amp[outlen++] = ((int16_t) (xout2 >> 4) + 2048); - } - else - { - amp[outlen++] = xout1; - amp[outlen++] = xout2; - } + /* Block 5L, LOW BAND INVQBL */ + wd2 = (s->band[0].det * wd2) >> 15; + /* Block 5L, RECONS */ + rlow = s->band[0].s + wd2; + /* Block 6L, LIMIT */ + + // ANDREA + // rlow=ssat(rlow,2<<14) + if (rlow > 16383) { + rlow = 16383; + } else if (rlow < -16384) { + rlow = -16384; + } + + /* Block 2L, INVQAL */ + wd2 = qm4[wd1]; + dlowt = (s->band[0].det * wd2) >> 15; + + /* Block 3L, LOGSCL */ + wd2 = rl42[wd1]; + wd1 = (s->band[0].nb * 127) >> 7; + wd1 += wl[wd2]; + if (wd1 < 0) { + wd1 = 0; + } else if (wd1 > 18432) { + wd1 = 18432; + } + s->band[0].nb = wd1; + + /* Block 3L, SCALEL */ + wd1 = (s->band[0].nb >> 6) & 31; + wd2 = 8 - (s->band[0].nb >> 11); + wd3 = (wd2 < 0) ? (ilb[wd1] << -wd2) : (ilb[wd1] >> wd2); + s->band[0].det = wd3 << 2; + + block4(&s->band[0], dlowt); + + /* Block 2H, INVQAH */ + wd2 = qm2[ihigh]; + dhigh = (s->band[1].det * wd2) >> 15; + /* Block 5H, RECONS */ + rhigh = dhigh + s->band[1].s; + /* Block 6H, LIMIT */ + + // ANDREA + // rhigh=ssat(rhigh,2<<14) + + if (rhigh > 16383) { + rhigh = 16383; + } else if (rhigh < -16384) { + rhigh = -16384; + } + + /* Block 2H, INVQAH */ + wd2 = rh2[ihigh]; + wd1 = (s->band[1].nb * 127) >> 7; + wd1 += wh[wd2]; + if (wd1 < 0) { + wd1 = 0; + } else if (wd1 > 22528) { + wd1 = 22528; + } + s->band[1].nb = wd1; + + /* Block 3H, SCALEH */ + wd1 = (s->band[1].nb >> 6) & 31; + wd2 = 10 - (s->band[1].nb >> 11); + wd3 = (wd2 < 0) ? (ilb[wd1] << -wd2) : (ilb[wd1] >> wd2); + s->band[1].det = wd3 << 2; + + block4(&s->band[1], dhigh); + + /* Apply the receive QMF */ + for (i = 0; i < 22; i++) { + s->x[i] = s->x[i + 2]; + } + s->x[22] = rlow + rhigh; + s->x[23] = rlow - rhigh; + + // we should get PERF numbers for the following loop + xout1 = 0; + xout2 = 0; + for (i = 0; i < 12; i++) { + xout2 += s->x[2 * i] * qmf_coeffs_even[i]; + xout1 += s->x[2 * i + 1] * qmf_coeffs_odd[i]; + } + xout1 = NLDECOMPRESS_PREPROCESS_SAMPLE_WITH_GAIN((int16_t)__ssat16(xout1 >> 11), gain); + xout2 = NLDECOMPRESS_PREPROCESS_SAMPLE_WITH_GAIN((int16_t)__ssat16(xout2 >> 11), gain); + if (s->dac_pcm) { + amp[outlen++] = ((int16_t)(xout1 >> 4) + 2048); + amp[outlen++] = ((int16_t)(xout2 >> 4) + 2048); + } else { + amp[outlen++] = xout1; + amp[outlen++] = xout2; } - return outlen; + } + return outlen; } /*- End of function --------------------------------------------------------*/ /*- End of file ------------------------------------------------------------*/ diff --git a/system/embdrv/g722/g722_enc_dec.h b/system/embdrv/g722/g722_enc_dec.h index f06cd203ad4..2751fe7e166 100644 --- a/system/embdrv/g722/g722_enc_dec.h +++ b/system/embdrv/g722/g722_enc_dec.h @@ -7,7 +7,7 @@ * * Copyright (C) 2005 Steve Underwood * - * Despite my general liking of the GPL, I place my own contributions + * Despite my general liking of the GPL, I place my own contributions * to this code in the public domain for the benefit of all mankind - * even the slimy ones who might try to proprietize my work and use it * to my detriment. @@ -21,12 +21,13 @@ * $Id: g722.h 48959 2006-12-25 06:42:15Z rizzo $ */ - /*! \file */ #if !defined(_G722_H_) #define _G722_H_ +#include "g722_typedefs.h" + /*! \page g722_page G.722 encoding and decoding \section g722_page_sec_1 What does it do? The G.722 module is a bit exact implementation of the ITU G.722 specification for all three @@ -43,90 +44,88 @@ codec is considerably faster, and still fully compatible with wideband terminals /* Format DAC12 is added to decode directly into samples suitable for a 12-bit DAC using offset binary representation. */ -enum -{ - G722_SAMPLE_RATE_8000 = 0x0001, - G722_PACKED = 0x0002, - G722_FORMAT_DAC12 = 0x0004, +enum { + G722_SAMPLE_RATE_8000 = 0x0001, + G722_PACKED = 0x0002, + G722_FORMAT_DAC12 = 0x0004, }; #ifdef BUILD_FEATURE_DAC -#define NLDECOMPRESS_APPLY_GAIN(s,g) (((s) * (int32_t)(g)) >> 16) +#define NLDECOMPRESS_APPLY_GAIN(s, g) (((s) * (int32_t)(g)) >> 16) // Equivalent to shift 16, add 0x8000, shift 4 -#define NLDECOMPRESS_APPLY_GAIN_CONVERTED_DAC(s,g) (uint16_t)((uint16_t)(((s) * (int32_t)(g)) >> 20) + 0x800) +#define NLDECOMPRESS_APPLY_GAIN_CONVERTED_DAC(s, g) \ + (uint16_t)((uint16_t)(((s) * (int32_t)(g)) >> 20) + 0x800) #else -#define NLDECOMPRESS_APPLY_GAIN(s,g) (((int32_t)(s) * (int32_t)(g)) >> 16) +#define NLDECOMPRESS_APPLY_GAIN(s, g) (((int32_t)(s) * (int32_t)(g)) >> 16) #endif #ifdef BUILD_FEATURE_DAC -#define NLDECOMPRESS_PREPROCESS_PCM_SAMPLE_WITH_GAIN(s,g) NLDECOMPRESS_APPLY_GAIN_CONVERTED_DAC((s),(g)) -#define NLDECOMPRESS_PREPROCESS_SAMPLE_WITH_GAIN(s,g) ((int16_t)NLDECOMPRESS_APPLY_GAIN((s),(g))) +#define NLDECOMPRESS_PREPROCESS_PCM_SAMPLE_WITH_GAIN(s, g) \ + NLDECOMPRESS_APPLY_GAIN_CONVERTED_DAC((s), (g)) +#define NLDECOMPRESS_PREPROCESS_SAMPLE_WITH_GAIN(s, g) ((int16_t)NLDECOMPRESS_APPLY_GAIN((s), (g))) #else #define NLDECOMPRESS_PREPROCESS_PCM_SAMPLE_WITH_GAIN NLDECOMPRESS_PREPROCESS_SAMPLE_WITH_GAIN -#define NLDECOMPRESS_PREPROCESS_SAMPLE_WITH_GAIN(s,g) ((int16_t)(NLDECOMPRESS_APPLY_GAIN((s),(g)))) +#define NLDECOMPRESS_PREPROCESS_SAMPLE_WITH_GAIN(s, g) \ + ((int16_t)(NLDECOMPRESS_APPLY_GAIN((s), (g)))) #endif typedef struct { - int s; - int sp; - int sz; - int r[3]; - int a[3]; - int ap[3]; - int p[3]; - int d[7]; - int b[7]; - int bp[7]; - int nb; - int det; + int s; + int sp; + int sz; + int r[3]; + int a[3]; + int ap[3]; + int p[3]; + int d[7]; + int b[7]; + int bp[7]; + int nb; + int det; } g722_band_t; -typedef struct -{ - /*! TRUE if the operating in the special ITU test mode, with the band split filters - disabled. */ - int itu_test_mode; - /*! TRUE if the G.722 data is packed */ - int packed; - /*! TRUE if encode from 8k samples/second */ - int eight_k; - /*! 6 for 48000kbps, 7 for 56000kbps, or 8 for 64000kbps. */ - int bits_per_sample; - - /*! Signal history for the QMF */ - int x[24]; - - g722_band_t band[2]; - - unsigned int in_buffer; - int in_bits; - unsigned int out_buffer; - int out_bits; +typedef struct { + /*! TRUE if the operating in the special ITU test mode, with the band split filters disabled. */ + int itu_test_mode; + /*! TRUE if the G.722 data is packed */ + int packed; + /*! TRUE if encode from 8k samples/second */ + int eight_k; + /*! 6 for 48000kbps, 7 for 56000kbps, or 8 for 64000kbps. */ + int bits_per_sample; + + /*! Signal history for the QMF */ + int x[24]; + + g722_band_t band[2]; + + unsigned int in_buffer; + int in_bits; + unsigned int out_buffer; + int out_bits; } g722_encode_state_t; -typedef struct -{ - /*! TRUE if the operating in the special ITU test mode, with the band split filters - disabled. */ - int itu_test_mode; - /*! TRUE if the G.722 data is packed */ - int packed; - /*! TRUE if decode to 8k samples/second */ - int eight_k; - /*! 6 for 48000kbps, 7 for 56000kbps, or 8 for 64000kbps. */ - int bits_per_sample; - /*! TRUE if offset binary for a 12-bit DAC */ - int dac_pcm; - - /*! Signal history for the QMF */ - int x[24]; - - g722_band_t band[2]; - - unsigned int in_buffer; - int in_bits; - unsigned int out_buffer; - int out_bits; +typedef struct { + /*! TRUE if the operating in the special ITU test mode, with the band split filters disabled. */ + int itu_test_mode; + /*! TRUE if the G.722 data is packed */ + int packed; + /*! TRUE if decode to 8k samples/second */ + int eight_k; + /*! 6 for 48000kbps, 7 for 56000kbps, or 8 for 64000kbps. */ + int bits_per_sample; + /*! TRUE if offset binary for a 12-bit DAC */ + int dac_pcm; + + /*! Signal history for the QMF */ + int x[24]; + + g722_band_t band[2]; + + unsigned int in_buffer; + int in_bits; + unsigned int out_buffer; + int out_bits; } g722_decode_state_t; #ifdef __cplusplus @@ -139,7 +138,8 @@ int g722_encode(g722_encode_state_t *s, uint8_t g722_data[], const int16_t amp[] g722_decode_state_t *g722_decode_init(g722_decode_state_t *s, unsigned int rate, int options); int g722_decode_release(g722_decode_state_t *s); -uint32_t g722_decode(g722_decode_state_t *s, int16_t amp[], const uint8_t g722_data[], int len, uint16_t aGain); +uint32_t g722_decode(g722_decode_state_t *s, int16_t amp[], const uint8_t g722_data[], int len, + uint16_t aGain); #ifdef __cplusplus } diff --git a/system/embdrv/g722/g722_encode.cc b/system/embdrv/g722/g722_encode.cc index c68a4a19e3a..ede7de541c2 100644 --- a/system/embdrv/g722/g722_encode.cc +++ b/system/embdrv/g722/g722_encode.cc @@ -9,7 +9,7 @@ * * All rights reserved. * - * Despite my general liking of the GPL, I place my own contributions + * Despite my general liking of the GPL, I place my own contributions * to this code in the public domain for the benefit of all mankind - * even the slimy ones who might try to proprietize my work and use it * to my detriment. @@ -25,11 +25,11 @@ /*! \file */ -#include #include +#include -#include "g722_typedefs.h" #include "g722_enc_dec.h" +#include "g722_typedefs.h" #if !defined(FALSE) #define FALSE 0 @@ -38,157 +38,150 @@ #define TRUE (!FALSE) #endif -#define PACKED_OUTPUT (0) +#define PACKED_OUTPUT (0) #define BITS_PER_SAMPLE (8) #ifndef BUILD_FEATURE_G722_USE_INTRINSIC_SAT -static __inline int16_t saturate(int32_t amp) -{ - int16_t amp16; - - /* Hopefully this is optimised for the common case - not clipping */ - amp16 = (int16_t) amp; - if (amp == amp16) - return amp16; - if (amp > 0x7FFF) - return 0x7FFF; - return 0x8000; +static __inline int16_t saturate(int32_t amp) { + int16_t amp16; + + /* Hopefully this is optimised for the common case - not clipping */ + amp16 = (int16_t)amp; + if (amp == amp16) { + return amp16; + } + if (amp > 0x7FFF) { + return 0x7FFF; + } + return 0x8000; } #else -static __inline int16_t saturate(int32_t val) -{ - register int32_t res; - __asm volatile ( - "SSAT %0, #16, %1\n\t" - :"=r"(res) - :"r"(val) - :); - return (int16_t)res; +static __inline int16_t saturate(int32_t val) { + register int32_t res; + __asm volatile("SSAT %0, #16, %1\n\t" : "=r"(res) : "r"(val) :); + return (int16_t)res; } #endif /*- End of function --------------------------------------------------------*/ -static void block4(g722_band_t *band, int d) -{ - int wd1; - int wd2; - int wd3; - int i; - int sg[7]; - int ap1, ap2; - int sg0, sgi; - int sz; - - /* Block 4, RECONS */ - band->d[0] = d; - band->r[0] = saturate(band->s + d); - - /* Block 4, PARREC */ - band->p[0] = saturate(band->sz + d); - - /* Block 4, UPPOL2 */ - for (i = 0; i < 3; i++) - sg[i] = band->p[i] >> 15; - wd1 = saturate(band->a[1] << 2); - - wd2 = (sg[0] == sg[1]) ? -wd1 : wd1; - if (wd2 > 32767) - wd2 = 32767; - - ap2 = (wd2 >> 7) + ((sg[0] == sg[2]) ? 128 : -128); - ap2 += (band->a[2]*32512) >> 15; - if (ap2 > 12288) - ap2 = 12288; - else if (ap2 < -12288) - ap2 = -12288; - band->ap[2] = ap2; - - /* Block 4, UPPOL1 */ - sg[0] = band->p[0] >> 15; - sg[1] = band->p[1] >> 15; - wd1 = (sg[0] == sg[1]) ? 192 : -192; - wd2 = (band->a[1]*32640) >> 15; - - ap1 = saturate(wd1 + wd2); - wd3 = saturate(15360 - band->ap[2]); - if (ap1 > wd3) - ap1 = wd3; - else if (ap1 < -wd3) - ap1 = -wd3; - band->ap[1] = ap1; - - /* Block 4, UPZERO */ - /* Block 4, FILTEZ */ - wd1 = (d == 0) ? 0 : 128; - - sg0 = sg[0] = d >> 15; - for (i = 1; i < 7; i++) - { - sgi = band->d[i] >> 15; - wd2 = (sgi == sg0) ? wd1 : -wd1; - wd3 = (band->b[i]*32640) >> 15; - band->bp[i] = saturate(wd2 + wd3); - } - - /* Block 4, DELAYA */ - sz = 0; - for (i = 6; i > 0; i--) - { - int bi; - - band->d[i] = band->d[i - 1]; - bi = band->b[i] = band->bp[i]; - wd1 = saturate(band->d[i] + band->d[i]); - sz += (bi*wd1) >> 15; - } - band->sz = sz; - - for (i = 2; i > 0; i--) - { - band->r[i] = band->r[i - 1]; - band->p[i] = band->p[i - 1]; - band->a[i] = band->ap[i]; - } - - /* Block 4, FILTEP */ - wd1 = saturate(band->r[1] + band->r[1]); - wd1 = (band->a[1]*wd1) >> 15; - wd2 = saturate(band->r[2] + band->r[2]); - wd2 = (band->a[2]*wd2) >> 15; - band->sp = saturate(wd1 + wd2); - - /* Block 4, PREDIC */ - band->s = saturate(band->sp + band->sz); +static void block4(g722_band_t *band, int d) { + int wd1; + int wd2; + int wd3; + int i; + int sg[7]; + int ap1, ap2; + int sg0, sgi; + int sz; + + /* Block 4, RECONS */ + band->d[0] = d; + band->r[0] = saturate(band->s + d); + + /* Block 4, PARREC */ + band->p[0] = saturate(band->sz + d); + + /* Block 4, UPPOL2 */ + for (i = 0; i < 3; i++) { + sg[i] = band->p[i] >> 15; + } + wd1 = saturate(band->a[1] << 2); + + wd2 = (sg[0] == sg[1]) ? -wd1 : wd1; + if (wd2 > 32767) { + wd2 = 32767; + } + + ap2 = (wd2 >> 7) + ((sg[0] == sg[2]) ? 128 : -128); + ap2 += (band->a[2] * 32512) >> 15; + if (ap2 > 12288) { + ap2 = 12288; + } else if (ap2 < -12288) { + ap2 = -12288; + } + band->ap[2] = ap2; + + /* Block 4, UPPOL1 */ + sg[0] = band->p[0] >> 15; + sg[1] = band->p[1] >> 15; + wd1 = (sg[0] == sg[1]) ? 192 : -192; + wd2 = (band->a[1] * 32640) >> 15; + + ap1 = saturate(wd1 + wd2); + wd3 = saturate(15360 - band->ap[2]); + if (ap1 > wd3) { + ap1 = wd3; + } else if (ap1 < -wd3) { + ap1 = -wd3; + } + band->ap[1] = ap1; + + /* Block 4, UPZERO */ + /* Block 4, FILTEZ */ + wd1 = (d == 0) ? 0 : 128; + + sg0 = sg[0] = d >> 15; + for (i = 1; i < 7; i++) { + sgi = band->d[i] >> 15; + wd2 = (sgi == sg0) ? wd1 : -wd1; + wd3 = (band->b[i] * 32640) >> 15; + band->bp[i] = saturate(wd2 + wd3); + } + + /* Block 4, DELAYA */ + sz = 0; + for (i = 6; i > 0; i--) { + int bi; + + band->d[i] = band->d[i - 1]; + bi = band->b[i] = band->bp[i]; + wd1 = saturate(band->d[i] + band->d[i]); + sz += (bi * wd1) >> 15; + } + band->sz = sz; + + for (i = 2; i > 0; i--) { + band->r[i] = band->r[i - 1]; + band->p[i] = band->p[i - 1]; + band->a[i] = band->ap[i]; + } + + /* Block 4, FILTEP */ + wd1 = saturate(band->r[1] + band->r[1]); + wd1 = (band->a[1] * wd1) >> 15; + wd2 = saturate(band->r[2] + band->r[2]); + wd2 = (band->a[2] * wd2) >> 15; + band->sp = saturate(wd1 + wd2); + + /* Block 4, PREDIC */ + band->s = saturate(band->sp + band->sz); } /*- End of function --------------------------------------------------------*/ -g722_encode_state_t *g722_encode_init(g722_encode_state_t *s, - unsigned int rate, int options) -{ - if (s == NULL) - { +g722_encode_state_t *g722_encode_init(g722_encode_state_t *s, unsigned int rate, int options) { + if (s == NULL) { #ifdef G722_SUPPORT_MALLOC - if ((s = (g722_encode_state_t *) malloc(sizeof(*s))) == NULL) + if ((s = (g722_encode_state_t *)malloc(sizeof(*s))) == NULL) #endif - return NULL; - } - memset(s, 0, sizeof(*s)); - if (rate == 48000) - s->bits_per_sample = 6; - else if (rate == 56000) - s->bits_per_sample = 7; - else - s->bits_per_sample = 8; - s->band[0].det = 32; - s->band[1].det = 8; - return s; + return NULL; + } + memset(s, 0, sizeof(*s)); + if (rate == 48000) { + s->bits_per_sample = 6; + } else if (rate == 56000) { + s->bits_per_sample = 7; + } else { + s->bits_per_sample = 8; + } + s->band[0].det = 32; + s->band[1].det = 8; + return s; } /*- End of function --------------------------------------------------------*/ -int g722_encode_release(g722_encode_state_t *s) -{ - free(s); - return 0; +int g722_encode_release(g722_encode_state_t *s) { + free(s); + return 0; } /*- End of function --------------------------------------------------------*/ @@ -196,242 +189,200 @@ int g722_encode_release(g722_encode_state_t *s) * Only define the following if bit-exactness with reference implementation * is needed. Will only have any effect if input signal is saturated. */ -//#define RUN_LIKE_REFERENCE_G722 +// #define RUN_LIKE_REFERENCE_G722 #ifdef RUN_LIKE_REFERENCE_G722 -int16_t limitValues (int16_t rl) -{ - - int16_t yl; +int16_t limitValues(int16_t rl) { + int16_t yl; - yl = (rl > 16383) ? 16383 : ((rl < -16384) ? -16384 : rl); + yl = (rl > 16383) ? 16383 : ((rl < -16384) ? -16384 : rl); - return (yl); + return yl; } /*- End of function --------------------------------------------------------*/ #endif -static int16_t q6[32] = -{ - 0, 35, 72, 110, 150, 190, 233, 276, - 323, 370, 422, 473, 530, 587, 650, 714, - 786, 858, 940, 1023, 1121, 1219, 1339, 1458, - 1612, 1765, 1980, 2195, 2557, 2919, 0, 0 -}; -static int16_t iln[32] = -{ - 0, 63, 62, 31, 30, 29, 28, 27, - 26, 25, 24, 23, 22, 21, 20, 19, - 18, 17, 16, 15, 14, 13, 12, 11, - 10, 9, 8, 7, 6, 5, 4, 0 -}; -static int16_t ilp[32] = -{ - 0, 61, 60, 59, 58, 57, 56, 55, - 54, 53, 52, 51, 50, 49, 48, 47, - 46, 45, 44, 43, 42, 41, 40, 39, - 38, 37, 36, 35, 34, 33, 32, 0 -}; -static int16_t wl[8] = -{ - -60, -30, 58, 172, 334, 538, 1198, 3042 -}; -static int16_t rl42[16] = -{ - 0, 7, 6, 5, 4, 3, 2, 1, 7, 6, 5, 4, 3, 2, 1, 0 -}; -static int16_t ilb[32] = -{ - 2048, 2093, 2139, 2186, 2233, 2282, 2332, - 2383, 2435, 2489, 2543, 2599, 2656, 2714, - 2774, 2834, 2896, 2960, 3025, 3091, 3158, - 3228, 3298, 3371, 3444, 3520, 3597, 3676, - 3756, 3838, 3922, 4008 -}; -static int16_t qm4[16] = -{ - 0, -20456, -12896, -8968, - -6288, -4240, -2584, -1200, - 20456, 12896, 8968, 6288, - 4240, 2584, 1200, 0 -}; -static int16_t qm2[4] = -{ - -7408, -1616, 7408, 1616 -}; -static int16_t qmf_coeffs[12] = -{ - 3, -11, 12, 32, -210, 951, 3876, -805, 362, -156, 53, -11, +static int16_t q6[32] = {0, 35, 72, 110, 150, 190, 233, 276, 323, 370, 422, + 473, 530, 587, 650, 714, 786, 858, 940, 1023, 1121, 1219, + 1339, 1458, 1612, 1765, 1980, 2195, 2557, 2919, 0, 0}; +static int16_t iln[32] = {0, 63, 62, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, + 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 0}; +static int16_t ilp[32] = {0, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, + 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 0}; +static int16_t wl[8] = {-60, -30, 58, 172, 334, 538, 1198, 3042}; +static int16_t rl42[16] = {0, 7, 6, 5, 4, 3, 2, 1, 7, 6, 5, 4, 3, 2, 1, 0}; +static int16_t ilb[32] = {2048, 2093, 2139, 2186, 2233, 2282, 2332, 2383, 2435, 2489, 2543, + 2599, 2656, 2714, 2774, 2834, 2896, 2960, 3025, 3091, 3158, 3228, + 3298, 3371, 3444, 3520, 3597, 3676, 3756, 3838, 3922, 4008}; +static int16_t qm4[16] = {0, -20456, -12896, -8968, -6288, -4240, -2584, -1200, + 20456, 12896, 8968, 6288, 4240, 2584, 1200, 0}; +static int16_t qm2[4] = {-7408, -1616, 7408, 1616}; +static int16_t qmf_coeffs[12] = { + 3, -11, 12, 32, -210, 951, 3876, -805, 362, -156, 53, -11, }; static int16_t ihn[3] = {0, 1, 0}; static int16_t ihp[3] = {0, 3, 2}; static int16_t wh[3] = {0, -214, 798}; static int16_t rh2[4] = {2, 1, 2, 1}; -int g722_encode(g722_encode_state_t *s, uint8_t g722_data[], - const int16_t amp[], int len) -{ - int dlow; - int dhigh; - int el; - int wd; - int wd1; - int ril; - int wd2; - int il4; - int ih2; - int wd3; - int eh; - int mih; - int i; - int j; - /* Low and high band PCM from the QMF */ - int xlow; - int xhigh; - int g722_bytes; - /* Even and odd tap accumulators */ - int sumeven; - int sumodd; - int ihigh; - int ilow; - int code; - - g722_bytes = 0; - xhigh = 0; - for (j = 0; j < len; ) - { - if (s->itu_test_mode) - { - xlow = - xhigh = amp[j++] >> 1; +int g722_encode(g722_encode_state_t *s, uint8_t g722_data[], const int16_t amp[], int len) { + int dlow; + int dhigh; + int el; + int wd; + int wd1; + int ril; + int wd2; + int il4; + int ih2; + int wd3; + int eh; + int mih; + int i; + int j; + /* Low and high band PCM from the QMF */ + int xlow; + int xhigh; + int g722_bytes; + /* Even and odd tap accumulators */ + int sumeven; + int sumodd; + int ihigh; + int ilow; + int code; + + g722_bytes = 0; + xhigh = 0; + for (j = 0; j < len;) { + if (s->itu_test_mode) { + xlow = xhigh = amp[j++] >> 1; + } else { + { + /* Apply the transmit QMF */ + /* Shuffle the buffer down */ + for (i = 0; i < 22; i++) { + s->x[i] = s->x[i + 2]; + } + // TODO: if len is odd, then this can be a buffer overrun + s->x[22] = amp[j++]; + s->x[23] = amp[j++]; + + /* Discard every other QMF output */ + sumeven = 0; + sumodd = 0; + for (i = 0; i < 12; i++) { + sumodd += s->x[2 * i] * qmf_coeffs[i]; + sumeven += s->x[2 * i + 1] * qmf_coeffs[11 - i]; } - else - { - { - /* Apply the transmit QMF */ - /* Shuffle the buffer down */ - for (i = 0; i < 22; i++) - s->x[i] = s->x[i + 2]; - //TODO: if len is odd, then this can be a buffer overrun - s->x[22] = amp[j++]; - s->x[23] = amp[j++]; - - /* Discard every other QMF output */ - sumeven = 0; - sumodd = 0; - for (i = 0; i < 12; i++) - { - sumodd += s->x[2*i]*qmf_coeffs[i]; - sumeven += s->x[2*i + 1]*qmf_coeffs[11 - i]; - } - /* We shift by 12 to allow for the QMF filters (DC gain = 4096), plus 1 - to allow for us summing two filters, plus 1 to allow for the 15 bit - input to the G.722 algorithm. */ - xlow = (sumeven + sumodd) >> 14; - xhigh = (sumeven - sumodd) >> 14; + /* We shift by 12 to allow for the QMF filters (DC gain = 4096), plus 1 + to allow for us summing two filters, plus 1 to allow for the 15 bit + input to the G.722 algorithm. */ + xlow = (sumeven + sumodd) >> 14; + xhigh = (sumeven - sumodd) >> 14; #ifdef RUN_LIKE_REFERENCE_G722 - /* The following lines are only used to verify bit-exactness - * with reference implementation of G.722. Higher precision - * is achieved without limiting the values. - */ - xlow = limitValues(xlow); - xhigh = limitValues(xhigh); + /* The following lines are only used to verify bit-exactness + * with reference implementation of G.722. Higher precision + * is achieved without limiting the values. + */ + xlow = limitValues(xlow); + xhigh = limitValues(xhigh); #endif - } - } - /* Block 1L, SUBTRA */ - el = saturate(xlow - s->band[0].s); + } + } + /* Block 1L, SUBTRA */ + el = saturate(xlow - s->band[0].s); - /* Block 1L, QUANTL */ - wd = (el >= 0) ? el : -(el + 1); + /* Block 1L, QUANTL */ + wd = (el >= 0) ? el : -(el + 1); - for (i = 1; i < 30; i++) - { - wd1 = (q6[i]*s->band[0].det) >> 12; - if (wd < wd1) - break; - } - ilow = (el < 0) ? iln[i] : ilp[i]; - - /* Block 2L, INVQAL */ - ril = ilow >> 2; - wd2 = qm4[ril]; - dlow = (s->band[0].det*wd2) >> 15; - - /* Block 3L, LOGSCL */ - il4 = rl42[ril]; - wd = (s->band[0].nb*127) >> 7; - s->band[0].nb = wd + wl[il4]; - if (s->band[0].nb < 0) - s->band[0].nb = 0; - else if (s->band[0].nb > 18432) - s->band[0].nb = 18432; - - /* Block 3L, SCALEL */ - wd1 = (s->band[0].nb >> 6) & 31; - wd2 = 8 - (s->band[0].nb >> 11); - wd3 = (wd2 < 0) ? (ilb[wd1] << -wd2) : (ilb[wd1] >> wd2); - s->band[0].det = wd3 << 2; - - block4(&s->band[0], dlow); - { - int nb; - - /* Block 1H, SUBTRA */ - eh = saturate(xhigh - s->band[1].s); - - /* Block 1H, QUANTH */ - wd = (eh >= 0) ? eh : -(eh + 1); - wd1 = (564*s->band[1].det) >> 12; - mih = (wd >= wd1) ? 2 : 1; - ihigh = (eh < 0) ? ihn[mih] : ihp[mih]; - - /* Block 2H, INVQAH */ - wd2 = qm2[ihigh]; - dhigh = (s->band[1].det*wd2) >> 15; - - /* Block 3H, LOGSCH */ - ih2 = rh2[ihigh]; - wd = (s->band[1].nb*127) >> 7; - - nb = wd + wh[ih2]; - if (nb < 0) - nb = 0; - else if (nb > 22528) - nb = 22528; - s->band[1].nb = nb; - - /* Block 3H, SCALEH */ - wd1 = (s->band[1].nb >> 6) & 31; - wd2 = 10 - (s->band[1].nb >> 11); - wd3 = (wd2 < 0) ? (ilb[wd1] << -wd2) : (ilb[wd1] >> wd2); - s->band[1].det = wd3 << 2; - - block4(&s->band[1], dhigh); -#if BITS_PER_SAMPLE == 8 - code = ((ihigh << 6) | ilow); + for (i = 1; i < 30; i++) { + wd1 = (q6[i] * s->band[0].det) >> 12; + if (wd < wd1) { + break; + } + } + ilow = (el < 0) ? iln[i] : ilp[i]; + + /* Block 2L, INVQAL */ + ril = ilow >> 2; + wd2 = qm4[ril]; + dlow = (s->band[0].det * wd2) >> 15; + + /* Block 3L, LOGSCL */ + il4 = rl42[ril]; + wd = (s->band[0].nb * 127) >> 7; + s->band[0].nb = wd + wl[il4]; + if (s->band[0].nb < 0) { + s->band[0].nb = 0; + } else if (s->band[0].nb > 18432) { + s->band[0].nb = 18432; + } + + /* Block 3L, SCALEL */ + wd1 = (s->band[0].nb >> 6) & 31; + wd2 = 8 - (s->band[0].nb >> 11); + wd3 = (wd2 < 0) ? (ilb[wd1] << -wd2) : (ilb[wd1] >> wd2); + s->band[0].det = wd3 << 2; + + block4(&s->band[0], dlow); + { + int nb; + + /* Block 1H, SUBTRA */ + eh = saturate(xhigh - s->band[1].s); + + /* Block 1H, QUANTH */ + wd = (eh >= 0) ? eh : -(eh + 1); + wd1 = (564 * s->band[1].det) >> 12; + mih = (wd >= wd1) ? 2 : 1; + ihigh = (eh < 0) ? ihn[mih] : ihp[mih]; + + /* Block 2H, INVQAH */ + wd2 = qm2[ihigh]; + dhigh = (s->band[1].det * wd2) >> 15; + + /* Block 3H, LOGSCH */ + ih2 = rh2[ihigh]; + wd = (s->band[1].nb * 127) >> 7; + + nb = wd + wh[ih2]; + if (nb < 0) { + nb = 0; + } else if (nb > 22528) { + nb = 22528; + } + s->band[1].nb = nb; + + /* Block 3H, SCALEH */ + wd1 = (s->band[1].nb >> 6) & 31; + wd2 = 10 - (s->band[1].nb >> 11); + wd3 = (wd2 < 0) ? (ilb[wd1] << -wd2) : (ilb[wd1] >> wd2); + s->band[1].det = wd3 << 2; + + block4(&s->band[1], dhigh); +#if BITS_PER_SAMPLE == 8 + code = ((ihigh << 6) | ilow); #elif BITS_PER_SAMPLE == 7 - code = ((ihigh << 6) | ilow) >> 1; + code = ((ihigh << 6) | ilow) >> 1; #elif BITS_PER_SAMPLE == 6 - code = ((ihigh << 6) | ilow) >> 2; + code = ((ihigh << 6) | ilow) >> 2; #endif - } + } #if PACKED_OUTPUT == 1 - /* Pack the code bits */ - s->out_buffer |= (code << s->out_bits); - s->out_bits += s->bits_per_sample; - if (s->out_bits >= 8) - { - g722_data[g722_bytes++] = (uint8_t) (s->out_buffer & 0xFF); - s->out_bits -= 8; - s->out_buffer >>= 8; - } + /* Pack the code bits */ + s->out_buffer |= (code << s->out_bits); + s->out_bits += s->bits_per_sample; + if (s->out_bits >= 8) { + g722_data[g722_bytes++] = (uint8_t)(s->out_buffer & 0xFF); + s->out_bits -= 8; + s->out_buffer >>= 8; + } #else - g722_data[g722_bytes++] = (uint8_t) code; + g722_data[g722_bytes++] = (uint8_t)code; #endif - } - return g722_bytes; + } + return g722_bytes; } /*- End of function --------------------------------------------------------*/ /*- End of file ------------------------------------------------------------*/ diff --git a/system/embdrv/g722/g722_typedefs.h b/system/embdrv/g722/g722_typedefs.h index b99075c61eb..1a243a3faeb 100644 --- a/system/embdrv/g722/g722_typedefs.h +++ b/system/embdrv/g722/g722_typedefs.h @@ -35,10 +35,10 @@ // TODO(ajm): We'd prefer to control platform defines here, but this is // currently provided by the Android makefiles. Commented to avoid duplicate // definition warnings. -//#define WEBRTC_ARCH_ARM +// #define WEBRTC_ARCH_ARM // TODO(ajm): Chromium uses the following two defines. Should we switch? -//#define WEBRTC_ARCH_ARM_FAMILY -//#define WEBRTC_ARCH_ARMEL +// #define WEBRTC_ARCH_ARM_FAMILY +// #define WEBRTC_ARCH_ARMEL #define WEBRTC_ARCH_32_BITS #define WEBRTC_ARCH_LITTLE_ENDIAN #elif defined(__MIPSEL__) @@ -58,8 +58,8 @@ #error Define either WEBRTC_ARCH_LITTLE_ENDIAN or WEBRTC_ARCH_BIG_ENDIAN #endif -#if (defined(WEBRTC_ARCH_X86_FAMILY) && !defined(__SSE2__)) || \ - (defined(WEBRTC_ARCH_ARM_V7) && !defined(WEBRTC_ARCH_ARM_NEON)) +#if (defined(WEBRTC_ARCH_X86_FAMILY) && !defined(__SSE2__)) || \ + (defined(WEBRTC_ARCH_ARM_V7) && !defined(WEBRTC_ARCH_ARM_NEON)) #define WEBRTC_CPU_DETECTION #endif @@ -67,14 +67,14 @@ #include #else // Define C99 equivalent types, since pre-2010 MSVC doesn't provide stdint.h. -typedef signed char int8_t; -typedef signed short int16_t; -typedef signed int int32_t; -typedef __int64 int64_t; -typedef unsigned char uint8_t; -typedef unsigned short uint16_t; -typedef unsigned int uint32_t; -typedef unsigned __int64 uint64_t; +typedef signed char int8_t; +typedef signed short int16_t; +typedef signed int int32_t; +typedef __int64 int64_t; +typedef unsigned char uint8_t; +typedef unsigned short uint16_t; +typedef unsigned int uint32_t; +typedef unsigned __int64 uint64_t; #endif // Borrowed from Chromium's base/compiler_specific.h. @@ -92,7 +92,7 @@ typedef unsigned __int64 uint64_t; #pragma clang diagnostic ignored "-Wc++11-extensions" #define OVERRIDE override #elif defined(__GNUC__) && __cplusplus >= 201103 && \ - (__GNUC__ * 10000 + __GNUC_MINOR__ * 100) >= 40700 + (__GNUC__ * 10000 + __GNUC_MINOR__ * 100) >= 40700 // GCC 4.7 supports explicit virtual overrides when C++11 support is enabled. #define OVERRIDE override #else diff --git a/system/embdrv/sbc/decoder/include/oi_assert.h b/system/embdrv/sbc/decoder/include/oi_assert.h index 4a429e15f12..e458c2d1d62 100644 --- a/system/embdrv/sbc/decoder/include/oi_assert.h +++ b/system/embdrv/sbc/decoder/include/oi_assert.h @@ -48,9 +48,10 @@ extern "C" { */ void OI_AssertFail(char* file, int line, char* reason); -#define OI_ASSERT(condition) \ - { \ - if (!(condition)) OI_AssertFail(__FILE__, __LINE__, #condition); \ +#define OI_ASSERT(condition) \ + { \ + if (!(condition)) \ + OI_AssertFail(__FILE__, __LINE__, #condition); \ } #define OI_ASSERT_FAIL(msg) \ diff --git a/system/embdrv/sbc/decoder/include/oi_bitstream.h b/system/embdrv/sbc/decoder/include/oi_bitstream.h index 003cfa38580..1450cc3d5f4 100644 --- a/system/embdrv/sbc/decoder/include/oi_bitstream.h +++ b/system/embdrv/sbc/decoder/include/oi_bitstream.h @@ -50,8 +50,7 @@ INLINE uint8_t OI_BITSTREAM_ReadUINT4Aligned(OI_BITSTREAM* bs); INLINE uint8_t OI_BITSTREAM_ReadUINT8Aligned(OI_BITSTREAM* bs); -INLINE void OI_BITSTREAM_WriteUINT(OI_BITSTREAM* bs, uint16_t value, - OI_UINT bits); +INLINE void OI_BITSTREAM_WriteUINT(OI_BITSTREAM* bs, uint16_t value, OI_UINT bits); /* * Use knowledge that the bitstream is aligned to optimize the write of a byte @@ -62,8 +61,7 @@ PRIVATE void OI_BITSTREAM_WriteUINT8Aligned(OI_BITSTREAM* bs, uint8_t datum); * Use knowledge that the bitstream is aligned to optimize the writing of a * pair of nibbles. */ -PRIVATE void OI_BITSTREAM_Write2xUINT4Aligned(OI_BITSTREAM* bs, uint8_t datum1, - uint8_t datum2); +PRIVATE void OI_BITSTREAM_Write2xUINT4Aligned(OI_BITSTREAM* bs, uint8_t datum1, uint8_t datum2); /** Internally the bitstream looks ahead in the stream. When * OI_SBC_ReadScalefactors() goes to temporarily break the abstraction, it will diff --git a/system/embdrv/sbc/decoder/include/oi_bt_spec.h b/system/embdrv/sbc/decoder/include/oi_bt_spec.h index 939308f589a..c0091cbe737 100644 --- a/system/embdrv/sbc/decoder/include/oi_bt_spec.h +++ b/system/embdrv/sbc/decoder/include/oi_bt_spec.h @@ -200,10 +200,10 @@ typedef uint32_t OI_BT_DEVICE_CLASS; */ #define OI_BT_TICK 625 /* some macros to convert to/from baseband clock ticks - no floating point! */ -#define OI_SECONDS_TO_BT_TICKS(secs) ((secs)*1600) +#define OI_SECONDS_TO_BT_TICKS(secs) ((secs) * 1600) #define OI_BT_TICKS_TO_SECONDS(ticks) ((ticks) / 1600) -#define OI_MSECS_TO_BT_TICKS(msecs) (((msecs)*8) / 5) -#define OI_BT_TICKS_TO_MSECS(ticks) (((ticks)*5) / 8) +#define OI_MSECS_TO_BT_TICKS(msecs) (((msecs) * 8) / 5) +#define OI_BT_TICKS_TO_MSECS(ticks) (((ticks) * 5) / 8) /** EIR byte order */ #define OI_EIR_BYTE_ORDER OI_LITTLE_ENDIAN_BYTE_ORDER diff --git a/system/embdrv/sbc/decoder/include/oi_codec_sbc.h b/system/embdrv/sbc/decoder/include/oi_codec_sbc.h index 3e69ff30444..af37bf83efc 100644 --- a/system/embdrv/sbc/decoder/include/oi_codec_sbc.h +++ b/system/embdrv/sbc/decoder/include/oi_codec_sbc.h @@ -68,14 +68,12 @@ Declarations of codec functions, data types, and macros. #define SBC_WBS_SAMPLES_PER_FRAME 128 #define SBC_HEADER_LEN 4 -#define SBC_MAX_FRAME_LEN \ - (SBC_HEADER_LEN + \ - ((SBC_MAX_BANDS * SBC_MAX_CHANNELS / 2) + \ - (SBC_MAX_BANDS + SBC_MAX_BLOCKS * SBC_MAX_BITPOOL + 7) / 8)) +#define SBC_MAX_FRAME_LEN \ + (SBC_HEADER_LEN + ((SBC_MAX_BANDS * SBC_MAX_CHANNELS / 2) + \ + (SBC_MAX_BANDS + SBC_MAX_BLOCKS * SBC_MAX_BITPOOL + 7) / 8)) #define SBC_MAX_SAMPLES_PER_FRAME (SBC_MAX_BANDS * SBC_MAX_BLOCKS) -#define SBC_MAX_SCALEFACTOR_BYTES \ - ((4 * (SBC_MAX_CHANNELS * SBC_MAX_BANDS) + 7) / 8) +#define SBC_MAX_SCALEFACTOR_BYTES ((4 * (SBC_MAX_CHANNELS * SBC_MAX_BANDS) + 7) / 8) #define OI_SBC_SYNCWORD 0x9c #define OI_SBC_ENHANCED_SYNCWORD 0x9d @@ -174,7 +172,7 @@ typedef struct { Input parameter. */ uint8_t subbands; - uint8_t mode; /**< The mode of the encoded channel. Input parameter. */ + uint8_t mode; /**< The mode of the encoded channel. Input parameter. */ uint8_t nrof_channels; /**< The number of channels of the encoded stream. */ uint8_t alloc; /**< The bit allocation method. Input parameter. */ @@ -229,7 +227,7 @@ typedef struct { * SBC_DECODER_FAST_SYNTHESIS_BUFFERS)]; * */ #define CODEC_DATA_WORDS(numChannels, numBuffers) \ - (((sizeof(int32_t) * SBC_MAX_BLOCKS * (numChannels)*SBC_MAX_BANDS) + \ + (((sizeof(int32_t) * SBC_MAX_BLOCKS * (numChannels) * SBC_MAX_BANDS) + \ (sizeof(SBC_BUFFER_T) * SBC_MAX_CHANNELS * SBC_MAX_BANDS * (numBuffers)) + \ (sizeof(uint32_t) - 1)) / \ sizeof(uint32_t)) @@ -274,11 +272,9 @@ typedef struct { * by an enhanced encoder, or there is a small possibility * for decoding glitches if synchronization were to be lost. */ -OI_STATUS OI_CODEC_SBC_DecoderReset(OI_CODEC_SBC_DECODER_CONTEXT* context, - uint32_t* decoderData, - uint32_t decoderDataBytes, - uint8_t maxChannels, uint8_t pcmStride, - OI_BOOL enhanced); +OI_STATUS OI_CODEC_SBC_DecoderReset(OI_CODEC_SBC_DECODER_CONTEXT* context, uint32_t* decoderData, + uint32_t decoderDataBytes, uint8_t maxChannels, + uint8_t pcmStride, OI_BOOL enhanced); /** * This function restricts the kind of SBC frames that the Decoder will @@ -299,11 +295,10 @@ OI_STATUS OI_CODEC_SBC_DecoderReset(OI_CODEC_SBC_DECODER_CONTEXT* context, * the requested number of subbands. * */ -OI_STATUS OI_CODEC_SBC_DecoderLimit(OI_CODEC_SBC_DECODER_CONTEXT* context, - OI_BOOL enhanced, uint8_t subbands); +OI_STATUS OI_CODEC_SBC_DecoderLimit(OI_CODEC_SBC_DECODER_CONTEXT* context, OI_BOOL enhanced, + uint8_t subbands); -OI_STATUS OI_CODEC_SBC_DecoderConfigureMSbc( - OI_CODEC_SBC_DECODER_CONTEXT* context); +OI_STATUS OI_CODEC_SBC_DecoderConfigureMSbc(OI_CODEC_SBC_DECODER_CONTEXT* context); /** * This function sets the decoder parameters for a raw decode where the decoder @@ -331,10 +326,9 @@ OI_STATUS OI_CODEC_SBC_DecoderConfigureMSbc( * * @param maxBitpool The maximum bitpool size for this context */ -OI_STATUS OI_CODEC_SBC_DecoderConfigureRaw( - OI_CODEC_SBC_DECODER_CONTEXT* context, OI_BOOL enhanced, uint8_t frequency, - uint8_t mode, uint8_t subbands, uint8_t blocks, uint8_t alloc, - uint8_t maxBitpool); +OI_STATUS OI_CODEC_SBC_DecoderConfigureRaw(OI_CODEC_SBC_DECODER_CONTEXT* context, OI_BOOL enhanced, + uint8_t frequency, uint8_t mode, uint8_t subbands, + uint8_t blocks, uint8_t alloc, uint8_t maxBitpool); /** * Decode one SBC frame. The frame has no header bytes. The context must have @@ -367,9 +361,8 @@ OI_STATUS OI_CODEC_SBC_DecoderConfigureRaw( * written. Note that this differs from the semantics of * frameBytes. */ -OI_STATUS OI_CODEC_SBC_DecodeRaw(OI_CODEC_SBC_DECODER_CONTEXT* context, - uint8_t bitpool, const OI_BYTE** frameData, - uint32_t* frameBytes, int16_t* pcmData, +OI_STATUS OI_CODEC_SBC_DecodeRaw(OI_CODEC_SBC_DECODER_CONTEXT* context, uint8_t bitpool, + const OI_BYTE** frameData, uint32_t* frameBytes, int16_t* pcmData, uint32_t* pcmBytes); /** @@ -398,10 +391,8 @@ OI_STATUS OI_CODEC_SBC_DecodeRaw(OI_CODEC_SBC_DECODER_CONTEXT* context, * written. Note that this differs from the semantics of * frameBytes. */ -OI_STATUS OI_CODEC_SBC_DecodeFrame(OI_CODEC_SBC_DECODER_CONTEXT* context, - const OI_BYTE** frameData, - uint32_t* frameBytes, int16_t* pcmData, - uint32_t* pcmBytes); +OI_STATUS OI_CODEC_SBC_DecodeFrame(OI_CODEC_SBC_DECODER_CONTEXT* context, const OI_BYTE** frameData, + uint32_t* frameBytes, int16_t* pcmData, uint32_t* pcmBytes); /** * Calculate the number of SBC frames but don't decode. CRC's are not checked, @@ -431,8 +422,7 @@ uint8_t OI_CODEC_SBC_FrameCount(OI_BYTE* frameData, uint32_t frameBytes); * operation. * */ -OI_STATUS OI_CODEC_SBC_SkipFrame(OI_CODEC_SBC_DECODER_CONTEXT* context, - const OI_BYTE** frameData, +OI_STATUS OI_CODEC_SBC_SkipFrame(OI_CODEC_SBC_DECODER_CONTEXT* context, const OI_BYTE** frameData, uint32_t* frameBytes); /* Common functions */ @@ -455,8 +445,7 @@ uint16_t OI_CODEC_SBC_CalculateFramelen(OI_CODEC_SBC_FRAME_INFO* frame); * * @return the maximum bitpool that will fit in the specified frame length */ -uint16_t OI_CODEC_SBC_CalculateBitpool(OI_CODEC_SBC_FRAME_INFO* frame, - uint16_t frameLen); +uint16_t OI_CODEC_SBC_CalculateBitpool(OI_CODEC_SBC_FRAME_INFO* frame, uint16_t frameLen); /** Calculate the bit rate. diff --git a/system/embdrv/sbc/decoder/include/oi_codec_sbc_private.h b/system/embdrv/sbc/decoder/include/oi_codec_sbc_private.h index 7d4e5ec421b..aa80ff1e29d 100644 --- a/system/embdrv/sbc/decoder/include/oi_codec_sbc_private.h +++ b/system/embdrv/sbc/decoder/include/oi_codec_sbc_private.h @@ -132,16 +132,14 @@ typedef struct { #define DCTIII_8_SHIFT_IN 3 #define DCTIII_8_SHIFT_OUT 14 -OI_UINT computeBitneed(OI_CODEC_SBC_COMMON_CONTEXT* common, uint8_t* bitneeds, - OI_UINT ch, OI_UINT* preferredBitpool); +OI_UINT computeBitneed(OI_CODEC_SBC_COMMON_CONTEXT* common, uint8_t* bitneeds, OI_UINT ch, + OI_UINT* preferredBitpool); -void oneChannelBitAllocation(OI_CODEC_SBC_COMMON_CONTEXT* common, - BITNEED_UNION1* bitneeds, OI_UINT ch, - OI_UINT bitcount); +void oneChannelBitAllocation(OI_CODEC_SBC_COMMON_CONTEXT* common, BITNEED_UNION1* bitneeds, + OI_UINT ch, OI_UINT bitcount); -OI_INT adjustToFitBitpool(const OI_UINT bitpool, uint32_t* bitneeds, - const OI_UINT subbands, OI_UINT bitcount, - OI_UINT* excess); +OI_INT adjustToFitBitpool(const OI_UINT bitpool, uint32_t* bitneeds, const OI_UINT subbands, + OI_UINT bitcount, OI_UINT* excess); INLINE OI_INT allocAdjustedBits(uint8_t* dest, OI_INT bits, OI_INT excess); @@ -155,74 +153,59 @@ void monoBitAllocation(OI_CODEC_SBC_COMMON_CONTEXT* common); typedef void (*BIT_ALLOC)(OI_CODEC_SBC_COMMON_CONTEXT* common); -PRIVATE OI_STATUS internal_DecodeRaw(OI_CODEC_SBC_DECODER_CONTEXT* context, - uint8_t bitpool, const OI_BYTE** frameData, - uint32_t* frameBytes, int16_t* pcmData, - uint32_t* pcmBytes); +PRIVATE OI_STATUS internal_DecodeRaw(OI_CODEC_SBC_DECODER_CONTEXT* context, uint8_t bitpool, + const OI_BYTE** frameData, uint32_t* frameBytes, + int16_t* pcmData, uint32_t* pcmBytes); -INLINE OI_STATUS internal_DecoderReset(OI_CODEC_SBC_DECODER_CONTEXT* context, - uint32_t* decoderData, - uint32_t decoderDataBytes, - OI_BYTE maxChannels, OI_BYTE pcmStride, - OI_BOOL enhanced); +INLINE OI_STATUS internal_DecoderReset(OI_CODEC_SBC_DECODER_CONTEXT* context, uint32_t* decoderData, + uint32_t decoderDataBytes, OI_BYTE maxChannels, + OI_BYTE pcmStride, OI_BOOL enhanced); -INLINE uint16_t OI_SBC_CalculateFrameAndHeaderlen( - OI_CODEC_SBC_FRAME_INFO* frame, OI_UINT* headerLen_); +INLINE uint16_t OI_SBC_CalculateFrameAndHeaderlen(OI_CODEC_SBC_FRAME_INFO* frame, + OI_UINT* headerLen_); PRIVATE uint32_t OI_SBC_MaxBitpool(OI_CODEC_SBC_FRAME_INFO* frame); PRIVATE void OI_SBC_ComputeBitAllocation(OI_CODEC_SBC_COMMON_CONTEXT* frame); -PRIVATE uint8_t OI_SBC_CalculateChecksum(OI_CODEC_SBC_FRAME_INFO* frame, - OI_BYTE const* data); +PRIVATE uint8_t OI_SBC_CalculateChecksum(OI_CODEC_SBC_FRAME_INFO* frame, OI_BYTE const* data); /* Transform functions */ -PRIVATE void shift_buffer(SBC_BUFFER_T* dest, SBC_BUFFER_T* src, - OI_UINT wordCount); -PRIVATE void cosineModulateSynth4(SBC_BUFFER_T* RESTRICT out, - int32_t const* RESTRICT in); -PRIVATE void SynthWindow40_int32_int32_symmetry_with_sum( - int16_t* pcm, SBC_BUFFER_T buffer[80], OI_UINT strideShift); +PRIVATE void shift_buffer(SBC_BUFFER_T* dest, SBC_BUFFER_T* src, OI_UINT wordCount); +PRIVATE void cosineModulateSynth4(SBC_BUFFER_T* RESTRICT out, int32_t const* RESTRICT in); +PRIVATE void SynthWindow40_int32_int32_symmetry_with_sum(int16_t* pcm, SBC_BUFFER_T buffer[80], + OI_UINT strideShift); INLINE void dct3_4(int32_t* RESTRICT out, int32_t const* RESTRICT in); -PRIVATE void analyze4_generated(SBC_BUFFER_T analysisBuffer[RESTRICT 40], - int16_t* pcm, OI_UINT strideShift, - int32_t subband[4]); +PRIVATE void analyze4_generated(SBC_BUFFER_T analysisBuffer[RESTRICT 40], int16_t* pcm, + OI_UINT strideShift, int32_t subband[4]); INLINE void dct3_8(int32_t* RESTRICT out, int32_t const* RESTRICT in); -PRIVATE void analyze8_generated(SBC_BUFFER_T analysisBuffer[RESTRICT 80], - int16_t* pcm, OI_UINT strideShift, - int32_t subband[8]); +PRIVATE void analyze8_generated(SBC_BUFFER_T analysisBuffer[RESTRICT 80], int16_t* pcm, + OI_UINT strideShift, int32_t subband[8]); #ifdef SBC_ENHANCED -PRIVATE void analyze8_enhanced_generated( - SBC_BUFFER_T analysisBuffer[RESTRICT 112], int16_t* pcm, - OI_UINT strideShift, int32_t subband[8]); +PRIVATE void analyze8_enhanced_generated(SBC_BUFFER_T analysisBuffer[RESTRICT 112], int16_t* pcm, + OI_UINT strideShift, int32_t subband[8]); #endif /* Decoder functions */ -INLINE void OI_SBC_ReadHeader(OI_CODEC_SBC_COMMON_CONTEXT* common, - const OI_BYTE* data); -PRIVATE void OI_SBC_ReadScalefactors(OI_CODEC_SBC_COMMON_CONTEXT* common, - const OI_BYTE* b, OI_BITSTREAM* bs); -PRIVATE void OI_SBC_ReadSamples(OI_CODEC_SBC_DECODER_CONTEXT* common, - OI_BITSTREAM* ob); -PRIVATE void OI_SBC_ReadSamplesJoint(OI_CODEC_SBC_DECODER_CONTEXT* common, - OI_BITSTREAM* global_bs); -PRIVATE void OI_SBC_SynthFrame(OI_CODEC_SBC_DECODER_CONTEXT* context, - int16_t* pcm, OI_UINT start_block, - OI_UINT nrof_blocks); +INLINE void OI_SBC_ReadHeader(OI_CODEC_SBC_COMMON_CONTEXT* common, const OI_BYTE* data); +PRIVATE void OI_SBC_ReadScalefactors(OI_CODEC_SBC_COMMON_CONTEXT* common, const OI_BYTE* b, + OI_BITSTREAM* bs); +PRIVATE void OI_SBC_ReadSamples(OI_CODEC_SBC_DECODER_CONTEXT* common, OI_BITSTREAM* ob); +PRIVATE void OI_SBC_ReadSamplesJoint(OI_CODEC_SBC_DECODER_CONTEXT* common, OI_BITSTREAM* global_bs); +PRIVATE void OI_SBC_SynthFrame(OI_CODEC_SBC_DECODER_CONTEXT* context, int16_t* pcm, + OI_UINT start_block, OI_UINT nrof_blocks); INLINE int32_t OI_SBC_Dequant(uint32_t raw, OI_UINT scale_factor, OI_UINT bits); -PRIVATE OI_BOOL OI_SBC_ExamineCommandPacket( - OI_CODEC_SBC_DECODER_CONTEXT* context, const OI_BYTE* data, uint32_t len); -PRIVATE void OI_SBC_GenerateTestSignal(int16_t pcmData[][2], - uint32_t sampleCount); +PRIVATE OI_BOOL OI_SBC_ExamineCommandPacket(OI_CODEC_SBC_DECODER_CONTEXT* context, + const OI_BYTE* data, uint32_t len); +PRIVATE void OI_SBC_GenerateTestSignal(int16_t pcmData[][2], uint32_t sampleCount); PRIVATE void OI_SBC_ExpandFrameFields(OI_CODEC_SBC_FRAME_INFO* frame); PRIVATE OI_STATUS OI_CODEC_SBC_Alloc(OI_CODEC_SBC_COMMON_CONTEXT* common, - uint32_t* codecDataAligned, - uint32_t codecDataBytes, + uint32_t* codecDataAligned, uint32_t codecDataBytes, uint8_t maxChannels, uint8_t pcmStride); /** @} diff --git a/system/embdrv/sbc/decoder/include/oi_cpu_dep.h b/system/embdrv/sbc/decoder/include/oi_cpu_dep.h index b628b4a7505..82be63049f8 100644 --- a/system/embdrv/sbc/decoder/include/oi_cpu_dep.h +++ b/system/embdrv/sbc/decoder/include/oi_cpu_dep.h @@ -59,27 +59,26 @@ extern "C" { 2 /**< ARM processor family. \ @deprecated Use #OI_CPU_ARM7_LEND or \ #OI_CPU_ARM7_BEND. */ -#define OI_CPU_ARC \ - 3 /**< ARC processor family. \ - @deprecated Use #OI_CPU_ARC_LEND or \ - #OI_CPU_ARC_BEND. */ -#define OI_CPU_SH3 4 /**< Hitachi SH-3 processor family */ -#define OI_CPU_H8 5 /**< Hitachi H8 processor family */ -#define OI_CPU_MIPS 6 /**< MIPS processor family */ -#define OI_CPU_SPARC 7 /**< SPARC processor family */ -#define OI_CPU_M68000 8 /**< Motorola M68000 processor family */ -#define OI_CPU_PPC 9 /**< PowerPC (PPC) processor family */ -#define OI_CPU_SH4_7750 \ - 10 /**< Hitachi SH7750 series in SH-4 processor family */ -#define OI_CPU_SH2 11 /**< Hitachi SH-2 processor family */ -#define OI_CPU_ARM7_LEND 12 /**< ARM7, little-endian */ -#define OI_CPU_ARM7_BEND 13 /**< ARM7, big-endian */ -#define OI_CPU_GDM1202 14 /**< GCT GDM1202 */ -#define OI_CPU_ARC_LEND 15 /**< ARC processor family, little-endian */ -#define OI_CPU_ARC_BEND 16 /**< ARC processor family, big-endian */ -#define OI_CPU_M30833F 17 /**< Mitsubishi M308 processor family */ -#define OI_CPU_CR16C 18 /**< National Semiconductor 16 bit processor family */ -#define OI_CPU_M64111 19 /**< Renesas M64111 processor (M32R family) */ +#define OI_CPU_ARC \ + 3 /**< ARC processor family. \ + @deprecated Use #OI_CPU_ARC_LEND or \ + #OI_CPU_ARC_BEND. */ +#define OI_CPU_SH3 4 /**< Hitachi SH-3 processor family */ +#define OI_CPU_H8 5 /**< Hitachi H8 processor family */ +#define OI_CPU_MIPS 6 /**< MIPS processor family */ +#define OI_CPU_SPARC 7 /**< SPARC processor family */ +#define OI_CPU_M68000 8 /**< Motorola M68000 processor family */ +#define OI_CPU_PPC 9 /**< PowerPC (PPC) processor family */ +#define OI_CPU_SH4_7750 10 /**< Hitachi SH7750 series in SH-4 processor family */ +#define OI_CPU_SH2 11 /**< Hitachi SH-2 processor family */ +#define OI_CPU_ARM7_LEND 12 /**< ARM7, little-endian */ +#define OI_CPU_ARM7_BEND 13 /**< ARM7, big-endian */ +#define OI_CPU_GDM1202 14 /**< GCT GDM1202 */ +#define OI_CPU_ARC_LEND 15 /**< ARC processor family, little-endian */ +#define OI_CPU_ARC_BEND 16 /**< ARC processor family, big-endian */ +#define OI_CPU_M30833F 17 /**< Mitsubishi M308 processor family */ +#define OI_CPU_CR16C 18 /**< National Semiconductor 16 bit processor family */ +#define OI_CPU_M64111 19 /**< Renesas M64111 processor (M32R family) */ #define OI_CPU_ARMV5_LEND 20 //*< ARM5, little-endian */ #define OI_CPU_TYPE 12 @@ -107,10 +106,8 @@ extern "C" { * @{ */ -typedef int - OI_BOOL; /**< Boolean values use native integer data type for target CPU. */ -typedef int - OI_INT; /**< Integer values use native integer data type for target CPU. */ +typedef int OI_BOOL; /**< Boolean values use native integer data type for target CPU. */ +typedef int OI_INT; /**< Integer values use native integer data type for target CPU. */ typedef unsigned int OI_UINT; /**< Unsigned integer values use native unsigned integer data type for target CPU. */ typedef unsigned char OI_BYTE; /**< Raw bytes type uses native character data @@ -127,7 +124,7 @@ typedef uint32_t OI_ELEMENT_UNION; /**< Type for first element of a union to #define OI_CPU_BYTE_ORDER \ OI_LITTLE_ENDIAN_BYTE_ORDER /**< x86 platform byte ordering is little-endian \ - */ + */ #endif @@ -200,7 +197,7 @@ typedef uint32_t OI_ELEMENT_UNION; /**< Type for first element of a union to #if OI_CPU_TYPE == OI_CPU_M68000 #define OI_CPU_BYTE_ORDER \ OI_BIG_ENDIAN_BYTE_ORDER /**< M68000 platform byte ordering is big-endian. \ - */ + */ #endif /******************************************************************************/ @@ -214,7 +211,7 @@ typedef uint32_t OI_ELEMENT_UNION; /**< Type for first element of a union to #if OI_CPU_TYPE == OI_CPU_SH4_7750 #define OI_CPU_BYTE_ORDER \ OI_BIG_ENDIAN_BYTE_ORDER /**< SH7750 platform byte ordering is big-endian. \ - */ + */ #endif /******************************************************************************/ diff --git a/system/embdrv/sbc/decoder/include/oi_modules.h b/system/embdrv/sbc/decoder/include/oi_modules.h index 272a31a71f0..d4fa0cf2d1d 100644 --- a/system/embdrv/sbc/decoder/include/oi_modules.h +++ b/system/embdrv/sbc/decoder/include/oi_modules.h @@ -118,12 +118,12 @@ typedef enum { OI_MODULE_SDPDB, /**< 54 Service Discovery Protocol database */ OI_MODULE_SECMGR, /**< 55 Security Manager */ OI_MODULE_SNIFFLOG, /**< 56 sniff log */ - OI_MODULE_SUPPORT, /**< 57 support functions, including CThru Dispatcher, time - functions, and stack initialization */ - OI_MODULE_TRANSPORT, /**< 58 transport layer between HCI command layer and - driver */ - OI_MODULE_TEST, /**< 59 used to debug output from internal test programs */ - OI_MODULE_XML, /**< 60 XML/CSS parser */ + OI_MODULE_SUPPORT, /**< 57 support functions, including CThru Dispatcher, time + functions, and stack initialization */ + OI_MODULE_TRANSPORT, /**< 58 transport layer between HCI command layer and + driver */ + OI_MODULE_TEST, /**< 59 used to debug output from internal test programs */ + OI_MODULE_XML, /**< 60 XML/CSS parser */ OI_MODULE_DI, /**< 61 Device Identification Profile */ @@ -134,10 +134,10 @@ typedef enum { OI_MODULE_BHSRV, /**< 64 BLUEmagic Host API server side */ OI_MODULE_MSGQ, /**< 65 module that handles message queuing */ OI_MODULE_BHAPI_TRANSPORT, /**< 66 module that handles message queuing */ - OI_MODULE_BLST_SRV, /**< 67 module that provides server side BHAPI Lightweight - Serial Transport */ - OI_MODULE_BLST_CLI, /**< 68 module that provides client side BHAPI Lightweight - Serial Transport */ + OI_MODULE_BLST_SRV, /**< 67 module that provides server side BHAPI Lightweight + Serial Transport */ + OI_MODULE_BLST_CLI, /**< 68 module that provides client side BHAPI Lightweight + Serial Transport */ // OEM files --> Updates to oi_debug.c OI_MODULE_OEM, /**< 69 Application Memory allocation */ diff --git a/system/embdrv/sbc/decoder/include/oi_status.h b/system/embdrv/sbc/decoder/include/oi_status.h index 7750758d2a7..28d9f04f0ac 100644 --- a/system/embdrv/sbc/decoder/include/oi_status.h +++ b/system/embdrv/sbc/decoder/include/oi_status.h @@ -40,249 +40,200 @@ extern "C" { */ typedef enum { - OI_STATUS_SUCCESS = 0, /**< function call succeeded alias for #OI_OK */ - OI_OK = 0, /**< function call succeeded alias for #OI_STATUS_SUCCESS */ + OI_STATUS_SUCCESS = 0, /**< function call succeeded alias for #OI_OK */ + OI_OK = 0, /**< function call succeeded alias for #OI_STATUS_SUCCESS */ OI_STATUS_INVALID_PARAMETERS = 101, /**< invalid function input parameters */ - OI_STATUS_NOT_IMPLEMENTED = - 102, /**< attempt to use an unimplemented function */ - OI_STATUS_NOT_INITIALIZED = 103, /**< data not initialized */ - OI_STATUS_NO_RESOURCES = - 104, /**< generic resource allocation failure status */ - OI_STATUS_INTERNAL_ERROR = 105, /**< internal inconsistency */ - OI_STATUS_OUT_OF_MEMORY = 106, /**< generally, OI_Malloc failed */ - OI_ILLEGAL_REENTRANT_CALL = - 107, /**< violation of non-reentrant module policy */ - OI_STATUS_INITIALIZATION_FAILED = 108, /**< module initialization failed */ - OI_STATUS_INITIALIZATION_PENDING = - 109, /**< inititialization not yet complete */ - OI_STATUS_NO_SCO_SUPPORT = - 110, /**< SCO operation rejected; system not configured for SCO */ + OI_STATUS_NOT_IMPLEMENTED = 102, /**< attempt to use an unimplemented function */ + OI_STATUS_NOT_INITIALIZED = 103, /**< data not initialized */ + OI_STATUS_NO_RESOURCES = 104, /**< generic resource allocation failure status */ + OI_STATUS_INTERNAL_ERROR = 105, /**< internal inconsistency */ + OI_STATUS_OUT_OF_MEMORY = 106, /**< generally, OI_Malloc failed */ + OI_ILLEGAL_REENTRANT_CALL = 107, /**< violation of non-reentrant module policy */ + OI_STATUS_INITIALIZATION_FAILED = 108, /**< module initialization failed */ + OI_STATUS_INITIALIZATION_PENDING = 109, /**< initialization not yet complete */ + OI_STATUS_NO_SCO_SUPPORT = 110, /**< SCO operation rejected; system not configured for SCO */ OI_STATUS_OUT_OF_STATIC_MEMORY = 111, /**< static malloc failed */ OI_TIMEOUT = 112, /**< generic timeout */ OI_OS_ERROR = 113, /**< some operating system error */ OI_FAIL = 114, /**< generic failure */ - OI_STRING_FORMAT_ERROR = 115, /**< error in VarString formatting string */ - OI_STATUS_PENDING = 116, /**< The operation is pending. */ - OI_STATUS_INVALID_COMMAND = 117, /**< The command was invalid. */ - OI_BUSY_FAIL = 118, /**< command rejected due to busy */ - OI_STATUS_ALREADY_REGISTERED = - 119, /**< The registration has already been performed. */ - OI_STATUS_NOT_FOUND = 120, /**< The referenced resource was not found. */ - OI_STATUS_NOT_REGISTERED = 121, /**< not registered */ - OI_STATUS_NOT_CONNECTED = 122, /**< not connected */ - OI_CALLBACK_FUNCTION_REQUIRED = - 123, /**< A callback function parameter was required. */ - OI_STATUS_MBUF_OVERFLOW = - 124, /**< There is no room to add another buffer to an mbuf. */ - OI_STATUS_MBUF_UNDERFLOW = - 125, /**< There was an attempt to pull too many bytes from an mbuf. */ - OI_STATUS_CONNECTION_EXISTS = 126, /**< connection exists */ - OI_STATUS_NOT_CONFIGURED = 127, /**< module not configured */ - OI_LOWER_STACK_ERROR = 128, /**< An error was reported by lower stack API. - This is used for embedded platforms. */ - OI_STATUS_RESET_IN_PROGRESS = - 129, /**< Request failed/rejected because we're busy resetting. */ - OI_STATUS_ACCESS_DENIED = 130, /**< Generic access denied error. */ - OI_STATUS_DATA_ERROR = 131, /**< Generic data error. */ - OI_STATUS_INVALID_ROLE = 132, /**< The requested role was invalid. */ - OI_STATUS_ALREADY_CONNECTED = - 133, /**< The requested connection is already established. */ + OI_STRING_FORMAT_ERROR = 115, /**< error in VarString formatting string */ + OI_STATUS_PENDING = 116, /**< The operation is pending. */ + OI_STATUS_INVALID_COMMAND = 117, /**< The command was invalid. */ + OI_BUSY_FAIL = 118, /**< command rejected due to busy */ + OI_STATUS_ALREADY_REGISTERED = 119, /**< The registration has already been performed. */ + OI_STATUS_NOT_FOUND = 120, /**< The referenced resource was not found. */ + OI_STATUS_NOT_REGISTERED = 121, /**< not registered */ + OI_STATUS_NOT_CONNECTED = 122, /**< not connected */ + OI_CALLBACK_FUNCTION_REQUIRED = 123, /**< A callback function parameter was required. */ + OI_STATUS_MBUF_OVERFLOW = 124, /**< There is no room to add another buffer to an mbuf. */ + OI_STATUS_MBUF_UNDERFLOW = 125, /**< There was an attempt to pull too many bytes from an mbuf. */ + OI_STATUS_CONNECTION_EXISTS = 126, /**< connection exists */ + OI_STATUS_NOT_CONFIGURED = 127, /**< module not configured */ + OI_LOWER_STACK_ERROR = 128, /**< An error was reported by lower stack API. + This is used for embedded platforms. */ + OI_STATUS_RESET_IN_PROGRESS = 129, /**< Request failed/rejected because we're busy resetting. */ + OI_STATUS_ACCESS_DENIED = 130, /**< Generic access denied error. */ + OI_STATUS_DATA_ERROR = 131, /**< Generic data error. */ + OI_STATUS_INVALID_ROLE = 132, /**< The requested role was invalid. */ + OI_STATUS_ALREADY_CONNECTED = 133, /**< The requested connection is already established. */ OI_STATUS_PARSE_ERROR = 134, /**< Parse error */ OI_STATUS_END_OF_FILE = 135, /**< End of file */ OI_STATUS_READ_ERROR = 136, /**< Generic read error */ OI_STATUS_WRITE_ERROR = 137, /**< Generic write error */ OI_STATUS_NEGOTIATION_FAILURE = 138, /**< Error in negotiation */ OI_STATUS_READ_IN_PROGRESS = 139, /**< A read is already in progress */ - OI_STATUS_ALREADY_INITIALIZED = - 140, /**< Initialization has already been done */ - OI_STATUS_STILL_CONNECTED = 141, /**< The service cannot be shutdown because - there are still active connections. */ - OI_STATUS_MTU_EXCEEDED = 142, /**< The packet is too big */ - OI_STATUS_LINK_TERMINATED = 143, /**< The link was terminated */ - OI_STATUS_PIN_CODE_TOO_LONG = - 144, /**< Application gave us a pin code that is too long */ - OI_STATUS_STILL_REGISTERED = 145, /**< The service cannot be shutdown because - there are still active registrations. */ - OI_STATUS_SPEC_VIOLATION = - 146, /**< Some application behavior contrary to BT specifications */ + OI_STATUS_ALREADY_INITIALIZED = 140, /**< Initialization has already been done */ + OI_STATUS_STILL_CONNECTED = 141, /**< The service cannot be shutdown because + there are still active connections. */ + OI_STATUS_MTU_EXCEEDED = 142, /**< The packet is too big */ + OI_STATUS_LINK_TERMINATED = 143, /**< The link was terminated */ + OI_STATUS_PIN_CODE_TOO_LONG = 144, /**< Application gave us a pin code that is too long */ + OI_STATUS_STILL_REGISTERED = 145, /**< The service cannot be shutdown because + there are still active registrations. */ + OI_STATUS_SPEC_VIOLATION = 146, /**< Some application behavior contrary to BT specifications */ OI_STATUS_PSM_ALREADY_REGISTERED = - 402, /**< L2CAP: The specified PSM has already been registered. */ - OI_STATUS_INVALID_CID = 403, /**< L2CAP: CID is invalid or no longer valid - (connection terminated) */ - OI_STATUS_CID_NOT_FOUND = - 404, /**< L2CAP: CID does not represent a current connection */ - OI_STATUS_CHANNEL_NOT_FOUND = - 406, /**< L2CAP: CID does not represent a current connection */ + 402, /**< L2CAP: The specified PSM has already been registered. */ + OI_STATUS_INVALID_CID = 403, /**< L2CAP: CID is invalid or no longer valid + (connection terminated) */ + OI_STATUS_CID_NOT_FOUND = 404, /**< L2CAP: CID does not represent a current connection */ + OI_STATUS_CHANNEL_NOT_FOUND = 406, /**< L2CAP: CID does not represent a current connection */ OI_STATUS_PSM_NOT_FOUND = 407, /**< L2CAP: PSM not found */ OI_STATUS_INVALID_STATE = 408, /**< L2CAP: invalid state */ OI_STATUS_WRITE_IN_PROGRESS = 410, /**< L2CAP: write in progress */ OI_STATUS_INVALID_PACKET = 411, /**< L2CAP: invalid packet */ OI_STATUS_SEND_COMPLETE = 412, /**< L2CAP: send is complete */ OI_STATUS_INVALID_HANDLE = 414, /**< L2CAP: handle is invalid */ - OI_STATUS_GROUP_FULL = - 418, /**< L2CAP: No more members can be added to the specified group. */ - OI_STATUS_DEVICE_ALREADY_IN_GROUP = - 423, /**< L2CAP: The device already exists in the group. */ - OI_STATUS_DUPLICATE_GROUP = - 425, /**< L2CAP: attempt to add more than one group */ - OI_STATUS_EMPTY_GROUP = 426, /**< L2CAP: group is empty */ - OI_STATUS_PACKET_NOT_FOUND = 427, /**< L2CAP: packet not found */ - OI_STATUS_BUFFER_TOO_SMALL = 428, /**< L2CAP: The buffer size is too small. */ - OI_STATUS_IDENTIFIER_NOT_FOUND = 429, /**< L2CAP: identifier not found */ - - OI_L2CAP_DISCONNECT_LOWER_LAYER = - 430, /**< L2CAP: The lower level forced a disconnect. */ - OI_L2CAP_DISCONNECT_REMOTE_REQUEST = - 431, /**< L2CAP: The remote device requested a disconnect. */ - OI_L2CAP_GROUP_ADD_CONNECT_FAIL = 433, /**< L2CAP: Group add connect faiL */ - OI_L2CAP_GROUP_REMOVE_FAILURE = 434, /**< L2CAP: Group remove failure */ - OI_L2CAP_DATA_WRITE_ERROR_LINK_TERM = - 435, /**< L2CAP: Data write error LINK_TERM */ - OI_L2CAP_DISCONNECT_LOCAL_REQUEST = - 436, /**< L2CAP: Disconnect local request */ + OI_STATUS_GROUP_FULL = 418, /**< L2CAP: No more members can be added to the specified group. */ + OI_STATUS_DEVICE_ALREADY_IN_GROUP = 423, /**< L2CAP: The device already exists in the group. */ + OI_STATUS_DUPLICATE_GROUP = 425, /**< L2CAP: attempt to add more than one group */ + OI_STATUS_EMPTY_GROUP = 426, /**< L2CAP: group is empty */ + OI_STATUS_PACKET_NOT_FOUND = 427, /**< L2CAP: packet not found */ + OI_STATUS_BUFFER_TOO_SMALL = 428, /**< L2CAP: The buffer size is too small. */ + OI_STATUS_IDENTIFIER_NOT_FOUND = 429, /**< L2CAP: identifier not found */ + + OI_L2CAP_DISCONNECT_LOWER_LAYER = 430, /**< L2CAP: The lower level forced a disconnect. */ + OI_L2CAP_DISCONNECT_REMOTE_REQUEST = 431, /**< L2CAP: The remote device requested a disconnect. */ + OI_L2CAP_GROUP_ADD_CONNECT_FAIL = 433, /**< L2CAP: Group add connect faiL */ + OI_L2CAP_GROUP_REMOVE_FAILURE = 434, /**< L2CAP: Group remove failure */ + OI_L2CAP_DATA_WRITE_ERROR_LINK_TERM = 435, /**< L2CAP: Data write error LINK_TERM */ + OI_L2CAP_DISCONNECT_LOCAL_REQUEST = 436, /**< L2CAP: Disconnect local request */ OI_L2CAP_CONNECT_TIMEOUT = 437, /**< L2CAP: Connect timeout */ OI_L2CAP_DISCONNECT_TIMEOUT = 439, /**< L2CAP: Disconnect timeout */ OI_L2CAP_PING_TIMEOUT = 440, /**< L2CAP: Ping timeout */ OI_L2CAP_GET_INFO_TIMEOUT = 441, /**< L2CAP: Get info timeout */ OI_L2CAP_INVALID_ADDRESS = 444, /**< L2CAP: Invalid address */ - OI_L2CAP_CMD_REJECT_RCVD = - 445, /**< L2CAP: remote sent us 'command reject' response */ - - OI_L2CAP_CONNECT_BASE = 450, /**< L2CAP: Connect base */ - OI_L2CAP_CONNECT_PENDING = 451, /**< L2CAP: Connect pending */ - OI_L2CAP_CONNECT_REFUSED_INVALID_PSM = - 452, /**< L2CAP: Connect refused invalid PSM */ - OI_L2CAP_CONNECT_REFUSED_SECURITY = - 453, /**< L2CAP: Connect refused security */ - OI_L2CAP_CONNECT_REFUSED_NO_RESOURCES = - 454, /**< L2CAP: Connect refused no resources */ - - OI_L2CAP_CONFIG_BASE = 460, /**< L2CAP: Config base */ - OI_L2CAP_CONFIG_FAIL_INVALID_PARAMETERS = - 461, /**< L2CAP: Config fail invalid parameters */ - OI_L2CAP_CONFIG_FAIL_NO_REASON = 462, /**< L2CAP: Config fail no reason */ - OI_L2CAP_CONFIG_FAIL_UNKNOWN_OPTIONS = - 463, /**< L2CAP: Config fail unknown options */ + OI_L2CAP_CMD_REJECT_RCVD = 445, /**< L2CAP: remote sent us 'command reject' response */ + + OI_L2CAP_CONNECT_BASE = 450, /**< L2CAP: Connect base */ + OI_L2CAP_CONNECT_PENDING = 451, /**< L2CAP: Connect pending */ + OI_L2CAP_CONNECT_REFUSED_INVALID_PSM = 452, /**< L2CAP: Connect refused invalid PSM */ + OI_L2CAP_CONNECT_REFUSED_SECURITY = 453, /**< L2CAP: Connect refused security */ + OI_L2CAP_CONNECT_REFUSED_NO_RESOURCES = 454, /**< L2CAP: Connect refused no resources */ + + OI_L2CAP_CONFIG_BASE = 460, /**< L2CAP: Config base */ + OI_L2CAP_CONFIG_FAIL_INVALID_PARAMETERS = 461, /**< L2CAP: Config fail invalid parameters */ + OI_L2CAP_CONFIG_FAIL_NO_REASON = 462, /**< L2CAP: Config fail no reason */ + OI_L2CAP_CONFIG_FAIL_UNKNOWN_OPTIONS = 463, /**< L2CAP: Config fail unknown options */ OI_L2CAP_GET_INFO_BASE = 470, /**< L2CAP: Get info base */ OI_L2CAP_GET_INFO_NOT_SUPPORTED = 471, /**< L2CAP: Get info not supported */ - OI_L2CAP_MTU_EXCEEDED = - 472, /**< L2CAP: The MTU of the channel was exceeded */ - OI_L2CAP_INVALID_PSM = 482, /**< L2CAP: Invalid PSM */ - OI_L2CAP_INVALID_MTU = 483, /**< L2CAP: Invalid MTU */ - OI_L2CAP_INVALID_FLUSHTO = 484, /**< L2CAP: Invalid flush timeout */ - - OI_HCI_NO_SUCH_CONNECTION = - 601, /**< HCI: caller specified a non-existent connection handle */ - OI_HCI_CB_LIST_FULL = - 603, /**< HCI: callback list is full, cannot attempt to send command */ - OI_HCI_EVENT_UNDERRUN = - 605, /**< HCI: parsing event packet, premature end-of-parameters */ - OI_HCI_UNKNOWN_EVENT_CODE = - 607, /**< HCI: event received - event code is unknown */ - OI_HCI_BAD_EVENT_PARM_LEN = - 608, /**< HCI: event - parameter length is incorrect */ - OI_HCI_CMD_QUEUE_FULL = 611, /**< HCI: command queue is full */ - OI_HCI_SHORT_EVENT = - 612, /**< HCI: event received, missing event code and/or parm len */ - OI_HCI_TRANSMIT_NOT_READY = 613, /**< HCI: ACL/SCO transmit request failed - - busy or no buffers available */ - OI_HCI_ORPHAN_SENT_EVENT = - 614, /**< HCI: got spurious 'sent' event from transport layer */ - OI_HCI_CMD_TABLE_ERROR = - 615, /**< HCI: inconsistency in the internal command table */ - OI_HCI_UNKNOWN_CMD_ID = 616, /**< HCI: HciApi Command - unknown command id */ + OI_L2CAP_MTU_EXCEEDED = 472, /**< L2CAP: The MTU of the channel was exceeded */ + OI_L2CAP_INVALID_PSM = 482, /**< L2CAP: Invalid PSM */ + OI_L2CAP_INVALID_MTU = 483, /**< L2CAP: Invalid MTU */ + OI_L2CAP_INVALID_FLUSHTO = 484, /**< L2CAP: Invalid flush timeout */ + + OI_HCI_NO_SUCH_CONNECTION = 601, /**< HCI: caller specified a non-existent connection handle */ + OI_HCI_CB_LIST_FULL = 603, /**< HCI: callback list is full, cannot attempt to send command */ + OI_HCI_EVENT_UNDERRUN = 605, /**< HCI: parsing event packet, premature end-of-parameters */ + OI_HCI_UNKNOWN_EVENT_CODE = 607, /**< HCI: event received - event code is unknown */ + OI_HCI_BAD_EVENT_PARAM_LEN = 608, /**< HCI: event - parameter length is incorrect */ + OI_HCI_CMD_QUEUE_FULL = 611, /**< HCI: command queue is full */ + OI_HCI_SHORT_EVENT = 612, /**< HCI: event received, missing event code and/or param len */ + OI_HCI_TRANSMIT_NOT_READY = 613, /**< HCI: ACL/SCO transmit request failed - + busy or no buffers available */ + OI_HCI_ORPHAN_SENT_EVENT = 614, /**< HCI: got spurious 'sent' event from transport layer */ + OI_HCI_CMD_TABLE_ERROR = 615, /**< HCI: inconsistency in the internal command table */ + OI_HCI_UNKNOWN_CMD_ID = 616, /**< HCI: HciApi Command - unknown command id */ OI_HCI_UNEXPECTED_EVENT = - 619, /**< HCI: event received which only occurs in response to our cmd */ - OI_HCI_EVENT_TABLE_ERROR = - 620, /**< HCI: inconsistency in the internal event table */ - OI_HCI_EXPECTED_EVENT_TIMOUT = - 621, /**< HCI: timed out waiting for an expected event */ + 619, /**< HCI: event received which only occurs in response to our cmd */ + OI_HCI_EVENT_TABLE_ERROR = 620, /**< HCI: inconsistency in the internal event table */ + OI_HCI_EXPECTED_EVENT_TIMEOUT = 621, /**< HCI: timed out waiting for an expected event */ OI_HCI_NO_CMD_DESC_FOR_OPCODE = 622, /**< HCI: event opcode is not known */ OI_HCI_INVALID_OPCODE_ERROR = 623, /**< HCI: command opcode is invalid */ OI_HCI_FLOW_CONTROL_DISABLED = 624, /**< HCI: can not use host flow control APIs if disabled in configuration */ - OI_HCI_TX_COMPLETE = - 625, /**< HCI: packet delivery to Host Controler complete */ - OI_HCI_TX_ERROR = 626, /**< HCI: failed to deliver packet to Host Controler */ + OI_HCI_TX_COMPLETE = 625, /**< HCI: packet delivery to Host Controller complete */ + OI_HCI_TX_ERROR = 626, /**< HCI: failed to deliver packet to Host Controller */ OI_HCI_DEVICE_NOT_INITIALIZED = 627, /**< HCI: commands from upper layers disallowed until device is up and running */ - OI_HCI_UNSUPPORTED_COMMAND = - 628, /**< HCI: command requested is not supported by local device */ - OI_HCI_PASSTHROUGH_ERROR = - 629, /**< HCI: Error processing passthrough command */ - OI_HCI_PASSTHROUGH_ALREADY_SET = - 630, /**< HCI: Passthrough mode already enabled */ - OI_HCI_RESET_FAILURE = 631, /**< HCI: failed to reset the device/baseband */ - OI_HCI_TRANSPORT_RESET = 632, /**< HCI: some operation failed because of a - reset in the transport */ - OI_HCIERR_HCIIFC_INIT_FAILURE = - 633, /**< HCI: failed to initialize transport layer interface */ - - OI_HCIERR_FIRST_ERROR_VALUE = 701, /**< marker for first HCI protocol error */ - OI_HCIERR_UNKNOWN_HCI_COMMAND = 701, /**< HCI: protocol error 0x01 */ - OI_HCIERR_NO_CONNECTION = 702, /**< HCI: protocol error 0x02 */ - OI_HCIERR_HARDWARE_FAILURE = 703, /**< HCI: protocol error 0x03 */ - OI_HCIERR_PAGE_TIMEOUT = 704, /**< HCI: protocol error 0x04 */ - OI_HCIERR_AUTHENTICATION_FAILURE = 705, /**< HCI: protocol error 0x05 */ - OI_HCIERR_KEY_MISSING = 706, /**< HCI: protocol error 0x06 */ - OI_HCIERR_MEMORY_FULL = 707, /**< HCI: protocol error 0x07 */ - OI_HCIERR_CONNECTION_TIMEOUT = 708, /**< HCI: protocol error 0x08 */ - OI_HCIERR_MAX_NUM_OF_CONNECTIONS = 709, /**< HCI: protocol error 0x09 */ - OI_HCIERR_MAX_NUM_OF_SCO_CONNECTIONS = 710, /**< HCI: protocol error 0x0A */ - OI_HCIERR_ACL_CONNECTION_ALREADY_EXISTS = - 711, /**< HCI: protocol error 0x0B */ - OI_HCIERR_COMMAND_DISALLOWED = 712, /**< HCI: protocol error 0x0C */ - OI_HCIERR_HOST_REJECTED_RESOURCES = 713, /**< HCI: protocol error 0x0D */ - OI_HCIERR_HOST_REJECTED_SECURITY = 714, /**< HCI: protocol error 0x0E */ - OI_HCIERR_HOST_REJECTED_PERSONAL_DEVICE = - 715, /**< HCI: protocol error 0x0F */ - OI_HCIERR_HOST_TIMEOUT = 716, /**< HCI: protocol error 0x10 */ - OI_HCIERR_UNSUPPORTED = 717, /**< HCI: protocol error 0x11 */ - OI_HCIERR_INVALID_PARAMETERS = 718, /**< HCI: protocol error 0x12 */ - OI_HCIERR_OTHER_END_USER_DISCONNECT = 719, /**< HCI: protocol error 0x13 */ - OI_HCIERR_OTHER_END_LOW_RESOURCES = 720, /**< HCI: protocol error 0x14 */ - OI_HCIERR_OTHER_END_POWERING_OFF = 721, /**< HCI: protocol error 0x15 */ - OI_HCIERR_CONNECTION_TERMINATED_LOCALLY = - 722, /**< HCI: protocol error 0x16 */ - OI_HCIERR_REPEATED_ATTEMPTS = 723, /**< HCI: protocol error 0x17 */ - OI_HCIERR_PAIRING_NOT_ALLOWED = 724, /**< HCI: protocol error 0x18 */ - OI_HCIERR_UNKNOWN_LMP_PDU = 725, /**< HCI: protocol error 0x19 */ - OI_HCIERR_UNSUPPORTED_REMOTE_FEATURE = 726, /**< HCI: protocol error 0x1A */ - OI_HCIERR_SCO_OFFSET_REJECTED = 727, /**< HCI: protocol error 0x1B */ - OI_HCIERR_SCO_INTERVAL_REJECTED = 728, /**< HCI: protocol error 0x1C */ - OI_HCIERR_SCO_AIR_MODE_REJECTED = 729, /**< HCI: protocol error 0x1D */ - OI_HCIERR_INVALID_LMP_PARMS = 730, /**< HCI: protocol error 0x1E */ - OI_HCIERR_UNSPECIFIED_ERROR = 731, /**< HCI: protocol error 0x1F */ - OI_HCIERR_UNSUPPORTED_LMP_PARAMETERS = 732, /**< HCI: protocol error 0x20 */ - OI_HCIERR_ROLE_CHANGE_NOT_ALLOWED = 733, /**< HCI: protocol error 0x21 */ - OI_HCIERR_LMP_RESPONSE_TIMEOUT = 734, /**< HCI: protocol error 0x22 */ - OI_HCIERR_LMP_ERROR_TRANS_COLLISION = 735, /**< HCI: protocol error 0x23 */ - OI_HCIERR_LMP_PDU_NOT_ALLOWED = 736, /**< HCI: protocol error 0x24 */ - OI_HCIERR_ENCRYPTION_MODE_NOT_ACCEPTABLE = - 737, /**< HCI: protocol error 0x25 */ - OI_HCIERR_UNIT_KEY_USED = 738, /**< HCI: protocol error 0x26 */ - OI_HCIERR_QOS_NOT_SUPPORTED = 739, /**< HCI: protocol error 0x27 */ - OI_HCIERR_INSTANT_PASSED = 740, /**< HCI: protocol error 0x28 */ - OI_HCIERR_UNIT_KEY_PAIRING_UNSUPPORTED = 741, /**< HCI: protocol error 0x29 */ - OI_HCIERR_DIFFERENT_TRANS_COLLISION = 742, /**< HCI: protocol error 0x2A */ - OI_HCIERR_RESERVED_2B = 743, /**< HCI: protocol error 0x2B */ - OI_HCIERR_QOS_UNACCEPTABLE_PARAMETER = 744, /**< HCI: protocol error 0x2C */ - OI_HCIERR_QOS_REJECTED = 745, /**< HCI: protocol error 0x2D */ - OI_HCIERR_CHANNEL_CLASSIFICATION_NS = 746, /**< HCI: protocol error 0x2E */ - OI_HCIERR_INSUFFICIENT_SECURITY = 747, /**< HCI: protocol error 0x2F */ - OI_HCIERR_PARM_OUT_OF_MANDATORY_RANGE = 748, /**< HCI: protocol error 0x30 */ - OI_HCIERR_RESERVED_31 = 749, /**< HCI: protocol error 0x31 */ - OI_HCIERR_ROLE_SWITCH_PENDING = 750, /**< HCI: protocol error 0x32 */ - OI_HCIERR_RESERVED_33 = 751, /**< HCI: protocol error 0x33 */ - OI_HCIERR_RESERVED_SLOT_VIOLATION = 752, /**< HCI: protocol error 0x34 */ - OI_HCIERR_ROLE_SWITCH_FAILED = 753, /**< HCI: protocol error 0x35 */ - OI_HCIERR_EIR_TOO_LARGE = 754, /**< HCI: protocol error 0x36 */ - OI_HCIERR_SSP_NOT_SUPPORTED_BY_HOST = 755, /**< HCI: protocol error 0x37 */ - OI_HCIERR_HOST_BUSY_PAIRING = 756, /**< HCI: protocol error 0x38 */ + OI_HCI_UNSUPPORTED_COMMAND = 628, /**< HCI: command requested is not supported by local device */ + OI_HCI_PASSTHROUGH_ERROR = 629, /**< HCI: Error processing passthrough command */ + OI_HCI_PASSTHROUGH_ALREADY_SET = 630, /**< HCI: Passthrough mode already enabled */ + OI_HCI_RESET_FAILURE = 631, /**< HCI: failed to reset the device/baseband */ + OI_HCI_TRANSPORT_RESET = 632, /**< HCI: some operation failed because of a + reset in the transport */ + OI_HCIERR_HCIIFC_INIT_FAILURE = 633, /**< HCI: failed to initialize transport layer interface */ + + OI_HCIERR_FIRST_ERROR_VALUE = 701, /**< marker for first HCI protocol error */ + OI_HCIERR_UNKNOWN_HCI_COMMAND = 701, /**< HCI: protocol error 0x01 */ + OI_HCIERR_NO_CONNECTION = 702, /**< HCI: protocol error 0x02 */ + OI_HCIERR_HARDWARE_FAILURE = 703, /**< HCI: protocol error 0x03 */ + OI_HCIERR_PAGE_TIMEOUT = 704, /**< HCI: protocol error 0x04 */ + OI_HCIERR_AUTHENTICATION_FAILURE = 705, /**< HCI: protocol error 0x05 */ + OI_HCIERR_KEY_MISSING = 706, /**< HCI: protocol error 0x06 */ + OI_HCIERR_MEMORY_FULL = 707, /**< HCI: protocol error 0x07 */ + OI_HCIERR_CONNECTION_TIMEOUT = 708, /**< HCI: protocol error 0x08 */ + OI_HCIERR_MAX_NUM_OF_CONNECTIONS = 709, /**< HCI: protocol error 0x09 */ + OI_HCIERR_MAX_NUM_OF_SCO_CONNECTIONS = 710, /**< HCI: protocol error 0x0A */ + OI_HCIERR_ACL_CONNECTION_ALREADY_EXISTS = 711, /**< HCI: protocol error 0x0B */ + OI_HCIERR_COMMAND_DISALLOWED = 712, /**< HCI: protocol error 0x0C */ + OI_HCIERR_HOST_REJECTED_RESOURCES = 713, /**< HCI: protocol error 0x0D */ + OI_HCIERR_HOST_REJECTED_SECURITY = 714, /**< HCI: protocol error 0x0E */ + OI_HCIERR_HOST_REJECTED_PERSONAL_DEVICE = 715, /**< HCI: protocol error 0x0F */ + OI_HCIERR_HOST_TIMEOUT = 716, /**< HCI: protocol error 0x10 */ + OI_HCIERR_UNSUPPORTED = 717, /**< HCI: protocol error 0x11 */ + OI_HCIERR_INVALID_PARAMETERS = 718, /**< HCI: protocol error 0x12 */ + OI_HCIERR_OTHER_END_USER_DISCONNECT = 719, /**< HCI: protocol error 0x13 */ + OI_HCIERR_OTHER_END_LOW_RESOURCES = 720, /**< HCI: protocol error 0x14 */ + OI_HCIERR_OTHER_END_POWERING_OFF = 721, /**< HCI: protocol error 0x15 */ + OI_HCIERR_CONNECTION_TERMINATED_LOCALLY = 722, /**< HCI: protocol error 0x16 */ + OI_HCIERR_REPEATED_ATTEMPTS = 723, /**< HCI: protocol error 0x17 */ + OI_HCIERR_PAIRING_NOT_ALLOWED = 724, /**< HCI: protocol error 0x18 */ + OI_HCIERR_UNKNOWN_LMP_PDU = 725, /**< HCI: protocol error 0x19 */ + OI_HCIERR_UNSUPPORTED_REMOTE_FEATURE = 726, /**< HCI: protocol error 0x1A */ + OI_HCIERR_SCO_OFFSET_REJECTED = 727, /**< HCI: protocol error 0x1B */ + OI_HCIERR_SCO_INTERVAL_REJECTED = 728, /**< HCI: protocol error 0x1C */ + OI_HCIERR_SCO_AIR_MODE_REJECTED = 729, /**< HCI: protocol error 0x1D */ + OI_HCIERR_INVALID_LMP_PARAMS = 730, /**< HCI: protocol error 0x1E */ + OI_HCIERR_UNSPECIFIED_ERROR = 731, /**< HCI: protocol error 0x1F */ + OI_HCIERR_UNSUPPORTED_LMP_PARAMETERS = 732, /**< HCI: protocol error 0x20 */ + OI_HCIERR_ROLE_CHANGE_NOT_ALLOWED = 733, /**< HCI: protocol error 0x21 */ + OI_HCIERR_LMP_RESPONSE_TIMEOUT = 734, /**< HCI: protocol error 0x22 */ + OI_HCIERR_LMP_ERROR_TRANS_COLLISION = 735, /**< HCI: protocol error 0x23 */ + OI_HCIERR_LMP_PDU_NOT_ALLOWED = 736, /**< HCI: protocol error 0x24 */ + OI_HCIERR_ENCRYPTION_MODE_NOT_ACCEPTABLE = 737, /**< HCI: protocol error 0x25 */ + OI_HCIERR_UNIT_KEY_USED = 738, /**< HCI: protocol error 0x26 */ + OI_HCIERR_QOS_NOT_SUPPORTED = 739, /**< HCI: protocol error 0x27 */ + OI_HCIERR_INSTANT_PASSED = 740, /**< HCI: protocol error 0x28 */ + OI_HCIERR_UNIT_KEY_PAIRING_UNSUPPORTED = 741, /**< HCI: protocol error 0x29 */ + OI_HCIERR_DIFFERENT_TRANS_COLLISION = 742, /**< HCI: protocol error 0x2A */ + OI_HCIERR_RESERVED_2B = 743, /**< HCI: protocol error 0x2B */ + OI_HCIERR_QOS_UNACCEPTABLE_PARAMETER = 744, /**< HCI: protocol error 0x2C */ + OI_HCIERR_QOS_REJECTED = 745, /**< HCI: protocol error 0x2D */ + OI_HCIERR_CHANNEL_CLASSIFICATION_NS = 746, /**< HCI: protocol error 0x2E */ + OI_HCIERR_INSUFFICIENT_SECURITY = 747, /**< HCI: protocol error 0x2F */ + OI_HCIERR_PARAM_OUT_OF_MANDATORY_RANGE = 748, /**< HCI: protocol error 0x30 */ + OI_HCIERR_RESERVED_31 = 749, /**< HCI: protocol error 0x31 */ + OI_HCIERR_ROLE_SWITCH_PENDING = 750, /**< HCI: protocol error 0x32 */ + OI_HCIERR_RESERVED_33 = 751, /**< HCI: protocol error 0x33 */ + OI_HCIERR_RESERVED_SLOT_VIOLATION = 752, /**< HCI: protocol error 0x34 */ + OI_HCIERR_ROLE_SWITCH_FAILED = 753, /**< HCI: protocol error 0x35 */ + OI_HCIERR_EIR_TOO_LARGE = 754, /**< HCI: protocol error 0x36 */ + OI_HCIERR_SSP_NOT_SUPPORTED_BY_HOST = 755, /**< HCI: protocol error 0x37 */ + OI_HCIERR_HOST_BUSY_PAIRING = 756, /**< HCI: protocol error 0x38 */ OI_HCIERR_UNKNOWN_ERROR = 757, /**< HCI: unknown error code */ OI_HCIERR_LAST_ERROR_VALUE = 757, /**< marker for last HCI protocol error */ @@ -290,462 +241,360 @@ typedef enum { OI_SDP_SPEC_ERROR = 800, /**< SDP: Base error status for mapping OI_STATUS codes to SDP errors */ OI_SDP_INVALID_SERVICE_RECORD_HANDLE = - (OI_SDP_SPEC_ERROR + - 2), /**< SDP: protocol error Invalid Service Record Handle */ + (OI_SDP_SPEC_ERROR + 2), /**< SDP: protocol error Invalid Service Record Handle */ OI_SDP_INVALID_REQUEST_SYNTAX = - (OI_SDP_SPEC_ERROR + - 3), /**< SDP: protocol error Invalid Request Syntax */ - OI_SDP_INVALID_PDU_SIZE = - (OI_SDP_SPEC_ERROR + 4), /**< SDP: protocol error Invalid PDU Size */ + (OI_SDP_SPEC_ERROR + 3), /**< SDP: protocol error Invalid Request Syntax */ + OI_SDP_INVALID_PDU_SIZE = (OI_SDP_SPEC_ERROR + 4), /**< SDP: protocol error Invalid PDU Size */ OI_SDP_INVALID_CONTINUATION_STATE = - (OI_SDP_SPEC_ERROR + - 5), /**< SDP: protocol error Invalid Continuation State */ + (OI_SDP_SPEC_ERROR + 5), /**< SDP: protocol error Invalid Continuation State */ OI_SDP_INSUFFICIENT_RESOURCES = - (OI_SDP_SPEC_ERROR + - 6), /**< SDP: protocol error Insufficient Resources */ - OI_SDP_ERROR = 807, /**< SDP: server returned an error code */ - OI_SDP_CORRUPT_DATA_ELEMENT = - 808, /**< SDP: Invalid or corrupt data element representation */ - OI_SDP_SERVER_NOT_CONNECTED = - 810, /**< SDP: Attempt to disconnect from an unconnected server */ - OI_SDP_ACCESS_DENIED = 811, /**< SDP: Server denied access to server */ + (OI_SDP_SPEC_ERROR + 6), /**< SDP: protocol error Insufficient Resources */ + OI_SDP_ERROR = 807, /**< SDP: server returned an error code */ + OI_SDP_CORRUPT_DATA_ELEMENT = 808, /**< SDP: Invalid or corrupt data element representation */ + OI_SDP_SERVER_NOT_CONNECTED = 810, /**< SDP: Attempt to disconnect from an unconnected server */ + OI_SDP_ACCESS_DENIED = 811, /**< SDP: Server denied access to server */ OI_SDP_ATTRIBUTES_OUT_OF_ORDER = - 812, /**< SDP: Attributes in attribute list not in ascending order */ + 812, /**< SDP: Attributes in attribute list not in ascending order */ OI_SDP_DEVICE_DOES_NOT_SUPPORT_SDP = - 813, /**< SDP: Tried to connect to a device that does not support SDP */ - OI_SDP_NO_MORE_DATA = - 815, /**< SDP: Server does not have more continuation data */ + 813, /**< SDP: Tried to connect to a device that does not support SDP */ + OI_SDP_NO_MORE_DATA = 815, /**< SDP: Server does not have more continuation data */ OI_SDP_REQUEST_PARAMS_TOO_LONG = - 816, /**< SDP: Parameters for a request exceed the L2CAP buffer size */ + 816, /**< SDP: Parameters for a request exceed the L2CAP buffer size */ OI_SDP_REQUEST_PENDING = 817, /**< SDP: Cannot make a request when another request is being processed */ - OI_SDP_SERVER_CONNECT_FAILED = - 819, /**< SDP: Failed attempt to connect to an SDP server */ + OI_SDP_SERVER_CONNECT_FAILED = 819, /**< SDP: Failed attempt to connect to an SDP server */ OI_SDP_SERVER_TOO_MANY_CONNECTIONS = - 821, /**< SDP: Exceeded maximum number of simultaneous server connections - */ - OI_SDP_NO_MATCHING_SERVICE_RECORD = - 823, /**< SDP: No service record matched the UUID list */ - OI_SDP_PARTIAL_RESPONSE = 824, /**< SDP: Internal use only */ - OI_SDP_ILLEGAL_ARGUMENT = - 825, /**< SDP: Illegal argument passed to an SDP function */ + 821, /**< SDP: Exceeded maximum number of simultaneous server connections + */ + OI_SDP_NO_MATCHING_SERVICE_RECORD = 823, /**< SDP: No service record matched the UUID list */ + OI_SDP_PARTIAL_RESPONSE = 824, /**< SDP: Internal use only */ + OI_SDP_ILLEGAL_ARGUMENT = 825, /**< SDP: Illegal argument passed to an SDP function */ OI_SDP_ATTRIBUTE_NOT_FOUND = - 826, /**< SDP: A requested attribute was not found in a service record */ - OI_SDP_DATABASE_OUT_OF_RESOURCES = - 827, /**< SDP: server database is out of memory */ - OI_SDP_SHORT_PDU = 829, /**< SDP: Not enough bytes in the packet */ - OI_SDP_TRANSACTION_ID_MISMATCH = - 830, /**< SDP: Transaction Id was not as expected */ - OI_SDP_UNEXPECTED_RESPONSE_PDU_ID = - 831, /**< SDP: Did not expect this response PDU */ - OI_SDP_REQUEST_TIMEOUT = - 832, /**< SDP: Did not get a response within the timeout period */ - OI_SDP_INVALID_RESPONSE_SYNTAX = - 833, /**< SDP: Response is not correctly formatted */ - OI_SDP_CONNECTION_TIMEOUT = - 834, /**< SDP: Connection attempt timed out at a lower layer */ - OI_SDP_RESPONSE_DATA_ERROR = - 835, /**< SDP: Response to a service request appears to be corrupt */ - OI_SDP_TOO_MANY_ATTRIBUTE_BYTES = - 836, /**< SDP: Response contained more bytes than requested. */ + 826, /**< SDP: A requested attribute was not found in a service record */ + OI_SDP_DATABASE_OUT_OF_RESOURCES = 827, /**< SDP: server database is out of memory */ + OI_SDP_SHORT_PDU = 829, /**< SDP: Not enough bytes in the packet */ + OI_SDP_TRANSACTION_ID_MISMATCH = 830, /**< SDP: Transaction Id was not as expected */ + OI_SDP_UNEXPECTED_RESPONSE_PDU_ID = 831, /**< SDP: Did not expect this response PDU */ + OI_SDP_REQUEST_TIMEOUT = 832, /**< SDP: Did not get a response within the timeout period */ + OI_SDP_INVALID_RESPONSE_SYNTAX = 833, /**< SDP: Response is not correctly formatted */ + OI_SDP_CONNECTION_TIMEOUT = 834, /**< SDP: Connection attempt timed out at a lower layer */ + OI_SDP_RESPONSE_DATA_ERROR = 835, /**< SDP: Response to a service request appears to be corrupt */ + OI_SDP_TOO_MANY_ATTRIBUTE_BYTES = 836, /**< SDP: Response contained more bytes than requested. */ OI_SDP_TOO_MANY_SERVICE_RECORDS = - 837, /**< SDP: Response contained more service records than requested. */ - OI_SDP_INVALID_CONNECTION_ID = - 838, /**< SDP: Invalid connection ID in an SDP request */ - OI_SDP_CANNOT_SET_ATTRIBUTE = - 839, /**< SDP: Attempt to set a dynamic attribute value failed */ + 837, /**< SDP: Response contained more service records than requested. */ + OI_SDP_INVALID_CONNECTION_ID = 838, /**< SDP: Invalid connection ID in an SDP request */ + OI_SDP_CANNOT_SET_ATTRIBUTE = 839, /**< SDP: Attempt to set a dynamic attribute value failed */ OI_SDP_BADLY_FORMED_ATTRIBUTE_VALUE = - 840, /**< SDP: An attribute value has the wrong type or structure */ - OI_SDP_NO_ATTRIBUTE_LIST_TO_REMOVE = - 841, /**< SDP: Attempt to remove a non-existent attribute list from a - service record */ + 840, /**< SDP: An attribute value has the wrong type or structure */ + OI_SDP_NO_ATTRIBUTE_LIST_TO_REMOVE = 841, /**< SDP: Attempt to remove a non-existent attribute + list from a service record */ OI_SDP_ATTRIBUTE_LIST_ALREADY_ADDED = 842, /**< SDP: An attribute list has already been added to the service record */ - OI_SDP_DATA_ELEMENT_TRUNCATED = - 843, /**< SDP: Data element truncated (too few bytes) */ - - OI_RFCOMM_WRITE_IN_PROGRESS = 901, /**< RFCOMM: Write in progress */ - OI_RFCOMM_INVALID_BAUDRATE = 903, /**< RFCOMM: Invalid baudrate */ - OI_RFCOMM_INVALID_DATABIT = 904, /**< RFCOMM: Invalid databit */ - OI_RFCOMM_INVALID_STOPBIT = 905, /**< RFCOMM: Invalid stopbit */ - OI_RFCOMM_INVALID_PARITY = 906, /**< RFCOMM: Invalid parity */ - OI_RFCOMM_INVALID_PARITYTYPE = 907, /**< RFCOMM: Invalid paritytype */ - OI_RFCOMM_INVALID_FLOWCONTROL = 908, /**< RFCOMM: Invalid flowcontrol */ - OI_RFCOMM_SESSION_EXISTS = 909, /**< RFCOMM: Session exists */ - OI_RFCOMM_INVALID_CHANNEL = 910, /**< RFCOMM: Invalid channel */ - OI_RFCOMM_DLCI_EXISTS = 911, /**< RFCOMM: DLCI exists */ - OI_RFCOMM_LINK_NOT_FOUND = 912, /**< RFCOMM: Link not found */ - OI_RFCOMM_REMOTE_REJECT = 913, /**< RFCOMM: Remote reject */ - OI_RFCOMM_TEST_IN_PROGRESS = 915, /**< RFCOMM: Test in progress */ - OI_RFCOMM_SESSION_NOT_FOUND = 916, /**< RFCOMM: Session not found */ - OI_RFCOMM_INVALID_PACKET = 917, /**< RFCOMM: Invalid packet */ - OI_RFCOMM_FRAMESIZE_EXCEEDED = 918, /**< RFCOMM: Framesize exceeded */ - OI_RFCOMM_INVALID_DLCI = 920, /**< RFCOMM: Invalid dlci */ - OI_RFCOMM_SERVER_NOT_REGISTERED = 921, /**< RFCOMM: Server not registered */ - OI_RFCOMM_CREDIT_ERROR = 922, /**< RFCOMM: Credit error */ - OI_RFCOMM_NO_CHANNEL_NUMBER = 923, /**< RFCOMM: No channel number */ - OI_RFCOMM_QUERY_IN_PROGRESS = 924, /**< RFCOMM: Query in progress */ - OI_RFCOMM_SESSION_SHUTDOWN = 925, /**< RFCOMM: Session shutdown */ - OI_RFCOMM_LOCAL_DEVICE_DISCONNECTED = - 926, /**< RFCOMM: Local device disconnected */ - OI_RFCOMM_REMOTE_DEVICE_DISCONNECTED = - 927, /**< RFCOMM: Remote device disconnected */ - OI_RFCOMM_OUT_OF_SERVER_CHANNELS = 928, /**< RFCOMM: Out of server channels */ - - OI_DISPATCH_INVALID_CB_HANDLE = - 1001, /**< Dispatcher was handed an invalid callback handle */ - OI_DISPATCH_TABLE_OVERFLOW = 1002, /**< Dispatcher table is full */ + OI_SDP_DATA_ELEMENT_TRUNCATED = 843, /**< SDP: Data element truncated (too few bytes) */ + + OI_RFCOMM_WRITE_IN_PROGRESS = 901, /**< RFCOMM: Write in progress */ + OI_RFCOMM_INVALID_BAUDRATE = 903, /**< RFCOMM: Invalid baudrate */ + OI_RFCOMM_INVALID_DATABIT = 904, /**< RFCOMM: Invalid databit */ + OI_RFCOMM_INVALID_STOPBIT = 905, /**< RFCOMM: Invalid stopbit */ + OI_RFCOMM_INVALID_PARITY = 906, /**< RFCOMM: Invalid parity */ + OI_RFCOMM_INVALID_PARITYTYPE = 907, /**< RFCOMM: Invalid paritytype */ + OI_RFCOMM_INVALID_FLOWCONTROL = 908, /**< RFCOMM: Invalid flowcontrol */ + OI_RFCOMM_SESSION_EXISTS = 909, /**< RFCOMM: Session exists */ + OI_RFCOMM_INVALID_CHANNEL = 910, /**< RFCOMM: Invalid channel */ + OI_RFCOMM_DLCI_EXISTS = 911, /**< RFCOMM: DLCI exists */ + OI_RFCOMM_LINK_NOT_FOUND = 912, /**< RFCOMM: Link not found */ + OI_RFCOMM_REMOTE_REJECT = 913, /**< RFCOMM: Remote reject */ + OI_RFCOMM_TEST_IN_PROGRESS = 915, /**< RFCOMM: Test in progress */ + OI_RFCOMM_SESSION_NOT_FOUND = 916, /**< RFCOMM: Session not found */ + OI_RFCOMM_INVALID_PACKET = 917, /**< RFCOMM: Invalid packet */ + OI_RFCOMM_FRAMESIZE_EXCEEDED = 918, /**< RFCOMM: Framesize exceeded */ + OI_RFCOMM_INVALID_DLCI = 920, /**< RFCOMM: Invalid dlci */ + OI_RFCOMM_SERVER_NOT_REGISTERED = 921, /**< RFCOMM: Server not registered */ + OI_RFCOMM_CREDIT_ERROR = 922, /**< RFCOMM: Credit error */ + OI_RFCOMM_NO_CHANNEL_NUMBER = 923, /**< RFCOMM: No channel number */ + OI_RFCOMM_QUERY_IN_PROGRESS = 924, /**< RFCOMM: Query in progress */ + OI_RFCOMM_SESSION_SHUTDOWN = 925, /**< RFCOMM: Session shutdown */ + OI_RFCOMM_LOCAL_DEVICE_DISCONNECTED = 926, /**< RFCOMM: Local device disconnected */ + OI_RFCOMM_REMOTE_DEVICE_DISCONNECTED = 927, /**< RFCOMM: Remote device disconnected */ + OI_RFCOMM_OUT_OF_SERVER_CHANNELS = 928, /**< RFCOMM: Out of server channels */ + + OI_DISPATCH_INVALID_CB_HANDLE = 1001, /**< Dispatcher was handed an invalid callback handle */ + OI_DISPATCH_TABLE_OVERFLOW = 1002, /**< Dispatcher table is full */ OI_TEST_UNKNOWN_TEST = 1101, /**< TEST: Unknown test */ OI_TEST_FAIL = 1102, /**< TEST: Fail */ - OI_HCITRANS_CANNOT_CONNECT_TO_DEVICE = - 1201, /**< TRANSPORT: Cannot connect to device */ - OI_HCITRANS_BUFFER_TOO_SMALL = 1203, /**< TRANSPORT: Buffer too small */ - OI_HCITRANS_NULL_DEVICE_HANDLE = 1204, /**< TRANSPORT: Null device handle */ - OI_HCITRANS_IO_ERROR = 1205, /**< TRANSPORT: IO error */ - OI_HCITRANS_DEVICE_NOT_READY = 1206, /**< TRANSPORT: Device not ready */ - OI_HCITRANS_FUNCTION_NOT_SUPPORTED = - 1207, /**< TRANSPORT: Function not supporteD */ - OI_HCITRANS_ACCESS_DENIED = 1209, /**< TRANSPORT: win32 */ - OI_HCITRANS_ACL_DATA_ERROR = 1210, /**< TRANSPORT: ACL data error */ - OI_HCITRANS_SCO_DATA_ERROR = 1211, /**< TRANSPORT: SCO data error */ - OI_HCITRANS_EVENT_DATA_ERROR = 1212, /**< TRANSPORT: HCI event data error */ - OI_HCITRANS_INTERNAL_ERROR = - 1214, /**< TRANSPORT: Internal error in the transport */ - OI_HCITRANS_LINK_NOT_ACTIVE = - 1215, /**< TRANSPORT: Link to the device is not currently active */ - OI_HCITRANS_INITIALIZING = 1216, /**< TRANSPORT: Transport is initializing */ - - OI_DEVMGR_NO_CONNECTION = 1301, /**< DEVMGR: No connection */ - OI_DEVMGR_HARDWARE_ERROR = 1305, /**< DEVMGR: error reported by HCI */ - OI_DEVMGR_PENDING_CONNECT_LIST_FULL = - 1307, /**< DEVMGR: Pending connect list full */ - OI_DEVMGR_CONNECTION_LIST_FULL = 1309, /**< DEVMGR: Connection list full */ - OI_DEVMGR_NO_SUCH_CONNECTION = 1310, /**< DEVMGR: No such connection */ - OI_DEVMGR_INQUIRY_IN_PROGRESS = 1311, /**< DEVMGR: Inquiry in progress */ - OI_DEVMGR_PERIODIC_INQUIRY_ACTIVE = - 1312, /**< DEVMGR: Periodic inquiry active */ - OI_DEVMGR_NO_INQUIRIES_ACTIVE = - 1313, /**< DEVMGR: can not cancel/exit if not active */ - OI_DEVMGR_DUPLICATE_CONNECTION = 1314, /**< DEVMGR: internal error */ - OI_DEVMGR_DUPLICATE_EVENT_CALLBACK = - 1316, /**< DEVMGR: attempt to register same callback twice */ + OI_HCITRANS_CANNOT_CONNECT_TO_DEVICE = 1201, /**< TRANSPORT: Cannot connect to device */ + OI_HCITRANS_BUFFER_TOO_SMALL = 1203, /**< TRANSPORT: Buffer too small */ + OI_HCITRANS_NULL_DEVICE_HANDLE = 1204, /**< TRANSPORT: Null device handle */ + OI_HCITRANS_IO_ERROR = 1205, /**< TRANSPORT: IO error */ + OI_HCITRANS_DEVICE_NOT_READY = 1206, /**< TRANSPORT: Device not ready */ + OI_HCITRANS_FUNCTION_NOT_SUPPORTED = 1207, /**< TRANSPORT: Function not supported */ + OI_HCITRANS_ACCESS_DENIED = 1209, /**< TRANSPORT: win32 */ + OI_HCITRANS_ACL_DATA_ERROR = 1210, /**< TRANSPORT: ACL data error */ + OI_HCITRANS_SCO_DATA_ERROR = 1211, /**< TRANSPORT: SCO data error */ + OI_HCITRANS_EVENT_DATA_ERROR = 1212, /**< TRANSPORT: HCI event data error */ + OI_HCITRANS_INTERNAL_ERROR = 1214, /**< TRANSPORT: Internal error in the transport */ + OI_HCITRANS_LINK_NOT_ACTIVE = 1215, /**< TRANSPORT: Link to the device is not currently active */ + OI_HCITRANS_INITIALIZING = 1216, /**< TRANSPORT: Transport is initializing */ + + OI_DEVMGR_NO_CONNECTION = 1301, /**< DEVMGR: No connection */ + OI_DEVMGR_HARDWARE_ERROR = 1305, /**< DEVMGR: error reported by HCI */ + OI_DEVMGR_PENDING_CONNECT_LIST_FULL = 1307, /**< DEVMGR: Pending connect list full */ + OI_DEVMGR_CONNECTION_LIST_FULL = 1309, /**< DEVMGR: Connection list full */ + OI_DEVMGR_NO_SUCH_CONNECTION = 1310, /**< DEVMGR: No such connection */ + OI_DEVMGR_INQUIRY_IN_PROGRESS = 1311, /**< DEVMGR: Inquiry in progress */ + OI_DEVMGR_PERIODIC_INQUIRY_ACTIVE = 1312, /**< DEVMGR: Periodic inquiry active */ + OI_DEVMGR_NO_INQUIRIES_ACTIVE = 1313, /**< DEVMGR: can not cancel/exit if not active */ + OI_DEVMGR_DUPLICATE_CONNECTION = 1314, /**< DEVMGR: internal error */ + OI_DEVMGR_DUPLICATE_EVENT_CALLBACK = 1316, /**< DEVMGR: attempt to register same callback twice */ OI_DEVMGR_EVENT_CALLBACK_LIST_FULL = - 1317, /**< DEVMGR: can not register event callback, list is full */ - OI_DEVMGR_EVENT_CALLBACK_NOT_FOUND = - 1318, /**< DEVMGR: attempt to unregister callback failed */ - OI_DEVMGR_BUSY = - 1319, /**< DEVMGR: some operations can only execute one at a time */ + 1317, /**< DEVMGR: can not register event callback, list is full */ + OI_DEVMGR_EVENT_CALLBACK_NOT_FOUND = 1318, /**< DEVMGR: attempt to unregister callback failed */ + OI_DEVMGR_BUSY = 1319, /**< DEVMGR: some operations can only execute one at a time */ OI_DEVMGR_ENUM_UNEXPECTED_INQ_COMPLETE = 1320, /**< DEVMGR: inquiry complete event in inappropriate enumeration state */ - OI_DEVMGR_ENUM_UNEXPECTED_INQ_RESULT = 1321, /**< DEVMGR: inquiry result event - in inappropriate enumeration - state */ - OI_DEVMGR_ENUM_DATABASE_FULL = 1322, /**< DEVMGR: device enumeration, database - is full, couldn't add a new device */ - OI_DEVMGR_ENUM_INQUIRIES_OVERLAP = 1323, /**< DEVMGR: device enumeration, - periodic inquiries occurring too - close together */ - OI_DEVMGR_UNKNOWN_LINK_TYPE = - 1324, /**< DEVMGR: HCI connect request with unkown link type */ - OI_DEVMGR_PARAM_IO_ACTIVE = 1325, /**< DEVMGR: request for parameter - read/write while param read/write active - */ - OI_DEVMGR_UNKNOWN_IAC_LAP = 1326, /**< DEVMGR: unrecognized IAC LAP */ - OI_DEVMGR_SCO_ALREADY_REGISTERED = - 1327, /**< DEVMGR: only one application can use SCO */ + OI_DEVMGR_ENUM_UNEXPECTED_INQ_RESULT = 1321, /**< DEVMGR: inquiry result event + in inappropriate enumeration + state */ + OI_DEVMGR_ENUM_DATABASE_FULL = 1322, /**< DEVMGR: device enumeration, database + is full, couldn't add a new device */ + OI_DEVMGR_ENUM_INQUIRIES_OVERLAP = 1323, /**< DEVMGR: device enumeration, + periodic inquiries occurring too + close together */ + OI_DEVMGR_UNKNOWN_LINK_TYPE = 1324, /**< DEVMGR: HCI connect request with unknown link type */ + OI_DEVMGR_PARAM_IO_ACTIVE = 1325, /**< DEVMGR: request for parameter + read/write while param read/write active + */ + OI_DEVMGR_UNKNOWN_IAC_LAP = 1326, /**< DEVMGR: unrecognized IAC LAP */ + OI_DEVMGR_SCO_ALREADY_REGISTERED = 1327, /**< DEVMGR: only one application can use SCO */ OI_DEVMGR_SCO_NOT_REGISTERED = - 1328, /**< DEVMGR: SCO applications must register before using the API */ - OI_DEVMGR_SCO_WITHOUT_ACL = 1329, /**< DEVMGR: Got SCO connection but there is - no underlying ACL connection */ - OI_DEVMGR_NO_SUPPORT = - 1330, /**< DEVMGR: Request is not supported by the device */ + 1328, /**< DEVMGR: SCO applications must register before using the API */ + OI_DEVMGR_SCO_WITHOUT_ACL = 1329, /**< DEVMGR: Got SCO connection but there is + no underlying ACL connection */ + OI_DEVMGR_NO_SUPPORT = 1330, /**< DEVMGR: Request is not supported by the device */ OI_DEVMGR_WRITE_POLICY_FAILED = 1331, /**< DEVMGR: connection attempt failed - unable to write link policy */ OI_DEVMGR_NOT_IN_MASTER_MODE = 1332, /**< DEVMGR: OI_DEVMGR EndMasterMode without prior OI_DEVMGR_BeginMasterMode */ - OI_DEVMGR_POLICY_VIOLATION = 1333, /**< DEVMGR: low-power request is rejected - - link policy does not allow it */ - OI_DEVMGR_BUSY_TIMEOUT = 1334, /**< DEVMGR: queued operation timed out while -in the queue; \n -timeout configurable via @ref OI_CONFIG_DEVMGR::connectQueueTimeoutSecs -"connectQueueTimeoutSecs" */ - OI_DEVMGR_REENCRYPT_FAILED = - 1335, /**< DEVMGR: failed to re-encrypt link after role switch */ + OI_DEVMGR_POLICY_VIOLATION = 1333, /**< DEVMGR: low-power request is rejected + - link policy does not allow it */ + OI_DEVMGR_BUSY_TIMEOUT = 1334, /**< DEVMGR: queued operation timed out while + in the queue; \n + timeout configurable via @ref OI_CONFIG_DEVMGR::connectQueueTimeoutSecs + "connectQueueTimeoutSecs" */ + OI_DEVMGR_REENCRYPT_FAILED = 1335, /**< DEVMGR: failed to re-encrypt link after role switch */ OI_DEVMGR_ROLE_POLICY_CONFLICT = - 1336, /**< DEVMGR: requested role conflicts with current policy */ - OI_DEVMGR_BAD_INTERVAL = 1337, /**< DEVMGR: current linkTO outside range of - requested min/max interval */ - OI_DEVMGR_INVALID_SCO_HANDLE = - 1338, /**< DEVMGR: HCI SCO event, invalid handle */ + 1336, /**< DEVMGR: requested role conflicts with current policy */ + OI_DEVMGR_BAD_INTERVAL = 1337, /**< DEVMGR: current linkTO outside range of + requested min/max interval */ + OI_DEVMGR_INVALID_SCO_HANDLE = 1338, /**< DEVMGR: HCI SCO event, invalid handle */ OI_DEVMGR_CONNECTION_OVERLAP = 1339, /**< DEVMGR: Connection failed due to race condition with remote side */ - OI_DEVMGR_ORPHAN_SUBRATE_COMPLETE = - 1340, /**< DEVMGR: sniff subrate complete, but no callback */ + OI_DEVMGR_ORPHAN_SUBRATE_COMPLETE = 1340, /**< DEVMGR: sniff subrate complete, but no callback */ OI_DEVMGR_EIR_RESPONSE_2_LARGE = - 1341, /**< DEVMGR: eir builder, response length would exceed spec max */ - - OI_SECMGR_NO_POLICY = - 1401, /**< SECMGR: no security policy has been established */ - OI_SECMGR_INTERNAL_ERROR = 1402, /**< SECMGR: internal inconsistency */ - OI_SECMGR_ORPHANED_CALLBACK = - 1403, /**< SECMGR: we've been called back, but CB context is gone */ - OI_SECMGR_BUSY = - 1404, /**< SECMGR: configure and access request cannot be concurrent */ - OI_SECMGR_DEVICE_NOT_TRUSTED = - 1405, /**< SECMGR: l2cap access denied - device is not trusted */ + 1341, /**< DEVMGR: eir builder, response length would exceed spec max */ + + OI_SECMGR_NO_POLICY = 1401, /**< SECMGR: no security policy has been established */ + OI_SECMGR_INTERNAL_ERROR = 1402, /**< SECMGR: internal inconsistency */ + OI_SECMGR_ORPHANED_CALLBACK = 1403, /**< SECMGR: we've been called back, but CB context is gone */ + OI_SECMGR_BUSY = 1404, /**< SECMGR: configure and access request cannot be concurrent */ + OI_SECMGR_DEVICE_NOT_TRUSTED = 1405, /**< SECMGR: l2cap access denied - device is not trusted */ OI_SECMGR_DEVICE_ENCRYPT_FAIL = - 1407, /**< SECMGR: l2cap access denied - failed to start encryption */ - OI_SECMGR_DISCONNECTED_FAIL = - 1408, /**< SECMGR: l2cap access denied - disconnected */ - OI_SECMGR_ACCESS_PENDING = - 1409, /**< SECMGR: l2cap access request is still pending */ - OI_SECMGR_PIN_CODE_TOO_SHORT = 1410, /**< SECMGR: Higher-layer process gave us - a pin code that is too short */ + 1407, /**< SECMGR: l2cap access denied - failed to start encryption */ + OI_SECMGR_DISCONNECTED_FAIL = 1408, /**< SECMGR: l2cap access denied - disconnected */ + OI_SECMGR_ACCESS_PENDING = 1409, /**< SECMGR: l2cap access request is still pending */ + OI_SECMGR_PIN_CODE_TOO_SHORT = 1410, /**< SECMGR: Higher-layer process gave us + a pin code that is too short */ OI_SECMGR_UNKNOWN_ENCRYPT_VALUE = 1411, /**< SECMGR: got EncryptionChange event, unknown encryption enable value */ - OI_SECMGR_INVALID_POLICY = 1412, /**< SECMGR: the specified security policy is - not valid for security mode */ - OI_SECMGR_AUTHORIZATION_FAILED = - 1413, /**< SECMGR: device authorization failed */ - OI_SECMGR_ENCRYPTION_FAILED = 1414, /**< SECMGR: device encryption failed */ + OI_SECMGR_INVALID_POLICY = 1412, /**< SECMGR: the specified security policy is + not valid for security mode */ + OI_SECMGR_AUTHORIZATION_FAILED = 1413, /**< SECMGR: device authorization failed */ + OI_SECMGR_ENCRYPTION_FAILED = 1414, /**< SECMGR: device encryption failed */ OI_SECMGR_UNIT_KEY_UNSUPPORTED = - 1415, /**< SECMGR: authentication failed due to non-support of unit keys - */ - OI_SECMGR_NOT_REGISTERED = - 1416, /**< SECMGR: required registrations have not yet occurred */ + 1415, /**< SECMGR: authentication failed due to non-support of unit keys + */ + OI_SECMGR_NOT_REGISTERED = 1416, /**< SECMGR: required registrations have not yet occurred */ OI_SECMGR_ILLEGAL_WRITE_SSP_MODE = - 1417, /**< SECMGR: 2.1 HCI spec does not allow SSP mode to be disabled */ + 1417, /**< SECMGR: 2.1 HCI spec does not allow SSP mode to be disabled */ OI_SECMGR_INVALID_SEC_LEVEL = - 1418, /**< SECMGR: security level for a service is not a valid value */ + 1418, /**< SECMGR: security level for a service is not a valid value */ OI_SECMGR_INSUFFICIENT_LINK_KEY = 1419, /**< SECMGR: link key type is not sufficient to meet service requirements */ - OI_SECMGR_INVALID_KEY_TYPE = - 1420, /**< SECMGR: link key type is not a valid value */ - OI_SECMGR_SSP_NOT_ENCRYPTED = - 1421, /**< SECMGR: ssp required encryption on incoming link */ - OI_SECMGR_ORPHAN_EVENT = 1422, /**< SECMGR: some HCI security event unrelated - to current processes */ - OI_SECMGR_NOT_BONDABLE = 1423, /**< SECMGR: not in bondable mode */ + OI_SECMGR_INVALID_KEY_TYPE = 1420, /**< SECMGR: link key type is not a valid value */ + OI_SECMGR_SSP_NOT_ENCRYPTED = 1421, /**< SECMGR: ssp required encryption on incoming link */ + OI_SECMGR_ORPHAN_EVENT = 1422, /**< SECMGR: some HCI security event unrelated + to current processes */ + OI_SECMGR_NOT_BONDABLE = 1423, /**< SECMGR: not in bondable mode */ OI_TCS_INVALID_ELEMENT_TYPE = 1602, /**< TCS: element type is invalid */ - OI_TCS_INVALID_PACKET = 1603, /**< TCS: packet is invalide */ + OI_TCS_INVALID_PACKET = 1603, /**< TCS: packet is invalid */ OI_TCS_CALL_IN_PROGRESS = 1604, /**< TCS: call is in progress */ OI_TCS_NO_CALL_IN_PROGRESS = 1605, /**< TCS: no call in progress */ - OI_OBEX_CONTINUE = 1701, /**< OBEX: Continue processing OBEX request */ - OI_OBEX_COMMAND_ERROR = - 1702, /**< OBEX: An unrecognized OBEX command opcode */ - OI_OBEX_CONNECTION_TIMEOUT = - 1703, /**< OBEX: Timeout waiting for a response to a request */ - OI_OBEX_CONNECT_FAILED = - 1704, /**< OBEX: An OBEX connection request did not succeed */ - OI_OBEX_DISCONNECT_FAILED = 1705, /**< OBEX: A disconnect failed probably - because the connection did not exist */ - OI_OBEX_ERROR = 1706, /**< OBEX: Unspecified OBEX error */ - OI_OBEX_INCOMPLETE_PACKET = 1707, /**< OBEX: Packet too short or corrupt */ - OI_OBEX_LENGTH_REQUIRED = - 1708, /**< OBEX: Length header required in OBEX command */ - OI_OBEX_NOT_CONNECTED = 1709, /**< OBEX: No connection to OBEX server */ - OI_OBEX_NO_MORE_CONNECTIONS = - 1710, /**< OBEX: Reached max connections limit */ + OI_OBEX_CONTINUE = 1701, /**< OBEX: Continue processing OBEX request */ + OI_OBEX_COMMAND_ERROR = 1702, /**< OBEX: An unrecognized OBEX command opcode */ + OI_OBEX_CONNECTION_TIMEOUT = 1703, /**< OBEX: Timeout waiting for a response to a request */ + OI_OBEX_CONNECT_FAILED = 1704, /**< OBEX: An OBEX connection request did not succeed */ + OI_OBEX_DISCONNECT_FAILED = 1705, /**< OBEX: A disconnect failed probably + because the connection did not exist */ + OI_OBEX_ERROR = 1706, /**< OBEX: Unspecified OBEX error */ + OI_OBEX_INCOMPLETE_PACKET = 1707, /**< OBEX: Packet too short or corrupt */ + OI_OBEX_LENGTH_REQUIRED = 1708, /**< OBEX: Length header required in OBEX command */ + OI_OBEX_NOT_CONNECTED = 1709, /**< OBEX: No connection to OBEX server */ + OI_OBEX_NO_MORE_CONNECTIONS = 1710, /**< OBEX: Reached max connections limit */ OI_OBEX_OPERATION_IN_PROGRESS = - 1711, /**< OBEX: Another operation is still in progress on a connection */ - OI_OBEX_PUT_RESPONSE_ERROR = - 1712, /**< OBEX: An error in the response to a PUT command */ - OI_OBEX_GET_RESPONSE_ERROR = - 1713, /**< OBEX: An error in the response to a GET command */ - OI_OBEX_REQUIRED_HEADER_NOT_FOUND = - 1714, /**< OBEX: packet was missing a required header */ - OI_OBEX_SERVICE_UNAVAILABLE = - 1715, /**< OBEX: Unown OBEX target or required service */ - OI_OBEX_TOO_MANY_HEADER_BYTES = - 1716, /**< OBEX: Headers will not fit in single OBEX packet */ - OI_OBEX_UNKNOWN_COMMAND = 1717, /**< OBEX: Unrecognized OBEX command */ - OI_OBEX_UNSUPPORTED_VERSION = 1718, /**< OBEX: Version mismatch */ - OI_OBEX_CLIENT_ABORTED_COMMAND = - 1719, /**< OBEX: server received abort command */ - OI_OBEX_BAD_PACKET = 1720, /**< OBEX: Any malformed OBEX packet */ - OI_OBEX_BAD_REQUEST = - 1721, /**< OBEX: Maps to OBEX response of the same name */ - OI_OBEX_OBJECT_OVERFLOW = 1723, /**< OBEX: Too many bytes received. */ - OI_OBEX_NOT_FOUND = 1724, /**< OBEX: Maps to obex response of same name */ - OI_OBEX_ACCESS_DENIED = - 1735, /**< OBEX: Object could not be read or written. */ + 1711, /**< OBEX: Another operation is still in progress on a connection */ + OI_OBEX_PUT_RESPONSE_ERROR = 1712, /**< OBEX: An error in the response to a PUT command */ + OI_OBEX_GET_RESPONSE_ERROR = 1713, /**< OBEX: An error in the response to a GET command */ + OI_OBEX_REQUIRED_HEADER_NOT_FOUND = 1714, /**< OBEX: packet was missing a required header */ + OI_OBEX_SERVICE_UNAVAILABLE = 1715, /**< OBEX: Unown OBEX target or required service */ + OI_OBEX_TOO_MANY_HEADER_BYTES = 1716, /**< OBEX: Headers will not fit in single OBEX packet */ + OI_OBEX_UNKNOWN_COMMAND = 1717, /**< OBEX: Unrecognized OBEX command */ + OI_OBEX_UNSUPPORTED_VERSION = 1718, /**< OBEX: Version mismatch */ + OI_OBEX_CLIENT_ABORTED_COMMAND = 1719, /**< OBEX: server received abort command */ + OI_OBEX_BAD_PACKET = 1720, /**< OBEX: Any malformed OBEX packet */ + OI_OBEX_BAD_REQUEST = 1721, /**< OBEX: Maps to OBEX response of the same name */ + OI_OBEX_OBJECT_OVERFLOW = 1723, /**< OBEX: Too many bytes received. */ + OI_OBEX_NOT_FOUND = 1724, /**< OBEX: Maps to obex response of same name */ + OI_OBEX_ACCESS_DENIED = 1735, /**< OBEX: Object could not be read or written. */ OI_OBEX_VALUE_NOT_ACCEPTABLE = - 1736, /**< OBEX: Value in a command was not in the acceptable range. */ - OI_OBEX_PACKET_OVERFLOW = - 1737, /**< OBEX: Buffer will not fit in a single OBEX packet. */ - OI_OBEX_NO_SUCH_FOLDER = - 1738, /**< OBEX: Error returned by a setpath operation. */ - OI_OBEX_NAME_REQUIRED = - 1739, /**< OBEX: Name must be non-null and non-empty. */ + 1736, /**< OBEX: Value in a command was not in the acceptable range. */ + OI_OBEX_PACKET_OVERFLOW = 1737, /**< OBEX: Buffer will not fit in a single OBEX packet. */ + OI_OBEX_NO_SUCH_FOLDER = 1738, /**< OBEX: Error returned by a setpath operation. */ + OI_OBEX_NAME_REQUIRED = 1739, /**< OBEX: Name must be non-null and non-empty. */ OI_OBEX_PASSWORD_TOO_LONG = - 1740, /**< OBEX: Password exceeds implementation imposed length limit. */ - OI_OBEX_PRECONDITION_FAILED = 1741, /**< OBEX: response Precondition Failed */ - OI_OBEX_UNAUTHORIZED = 1742, /**< OBEX: authentication was not successful. */ - OI_OBEX_NOT_IMPLEMENTED = 1743, /**< OBEX: Unimplemented feature. */ - OI_OBEX_INVALID_AUTH_DIGEST = - 1744, /**< OBEX: An authentication digest was bad. */ - OI_OBEX_INVALID_OPERATION = - 1745, /**< OBEX: Operation not allowed at this time. */ - OI_OBEX_DATABASE_FULL = 1746, /**< OBEX: Sync database full. */ - OI_OBEX_DATABASE_LOCKED = 1747, /**< OBEX: Sync database locked. */ - OI_OBEX_INTERNAL_SERVER_ERROR = - 1748, /**< OBEX: response Internal Server Error */ - OI_OBEX_UNSUPPORTED_MEDIA_TYPE = - 1749, /**< OBEX: response Unsupported Media Type */ - OI_OBEX_PARTIAL_CONTENT = 1750, /**< OBEX: response Partial Content */ - OI_OBEX_METHOD_NOT_ALLOWED = 1751, /**< OBEX: response Method Not Allowed */ - OI_OBEXSRV_INCOMPLETE_GET = 1752, /**< OBEX: Indicates to a GET handler that - the request phase is still in progress */ + 1740, /**< OBEX: Password exceeds implementation imposed length limit. */ + OI_OBEX_PRECONDITION_FAILED = 1741, /**< OBEX: response Precondition Failed */ + OI_OBEX_UNAUTHORIZED = 1742, /**< OBEX: authentication was not successful. */ + OI_OBEX_NOT_IMPLEMENTED = 1743, /**< OBEX: Unimplemented feature. */ + OI_OBEX_INVALID_AUTH_DIGEST = 1744, /**< OBEX: An authentication digest was bad. */ + OI_OBEX_INVALID_OPERATION = 1745, /**< OBEX: Operation not allowed at this time. */ + OI_OBEX_DATABASE_FULL = 1746, /**< OBEX: Sync database full. */ + OI_OBEX_DATABASE_LOCKED = 1747, /**< OBEX: Sync database locked. */ + OI_OBEX_INTERNAL_SERVER_ERROR = 1748, /**< OBEX: response Internal Server Error */ + OI_OBEX_UNSUPPORTED_MEDIA_TYPE = 1749, /**< OBEX: response Unsupported Media Type */ + OI_OBEX_PARTIAL_CONTENT = 1750, /**< OBEX: response Partial Content */ + OI_OBEX_METHOD_NOT_ALLOWED = 1751, /**< OBEX: response Method Not Allowed */ + OI_OBEXSRV_INCOMPLETE_GET = 1752, /**< OBEX: Indicates to a GET handler that + the request phase is still in progress */ OI_OBEX_FOLDER_BROWSING_NOT_ALLOWED = 1753, /**< OBEX: Indicates that an FTP server does not allow folder browsing */ OI_OBEX_SERVER_FORCED_DISCONNECT = - 1754, /**< OBEX: connection was forcibly terminated by the server */ - OI_OBEX_OFS_ERROR = 1755, /**< OBEX: OPP object file system error occurred */ - OI_OBEX_FILEOP_ERROR = - 1756, /**< OBEX: FTP/PBAP file operation system error occurred */ - OI_OBEX_USERID_TOO_LONG = - 1757, /**< OBEX: User Id exceeds spec limited length limit. */ - - OI_HANDSFREE_EVENT_REPORTING_DISABLED = - 1801, /**< HANDSFREE: Event reporting disabled */ - OI_HANDSFREE_NOT_CONNECTED = 1802, /**< HANDSFREE: Not connected */ - OI_HANDSFREE_SERVICE_NOT_STARTED = 1803, /**< HANDSFREE: Cannot connect to - handsfree AG if handsfree service - not started */ - OI_HANDSFREE_AG_SERVICE_NOT_STARTED = - 1804, /**< HANDSFREE: Cannot connect to handsfree device if handsfree AG - service not started */ - OI_HANDSFREE_COMMAND_IN_PROGRESS = - 1805, /**< HANDSFREE: Cannot accept a command at this time */ - OI_HANDSFREE_AUDIO_ALREADY_CONNECTED = - 1806, /**< HANDSFREE: Audio is already connected */ - OI_HANDSFREE_AUDIO_NOT_CONNECTED = - 1807, /**< HANDSFREE: Audio is not connected */ - OI_HANDSFREE_FEATURE_NOT_SUPPORTED = 1808, /**< HANDSFREE: Local or remote - feature not supported for - requested command */ - - OI_HEADSET_SERVICE_NOT_STARTED = 1901, /**< HEADSET: Cannot connect to headset - AG if headset service not started */ + 1754, /**< OBEX: connection was forcibly terminated by the server */ + OI_OBEX_OFS_ERROR = 1755, /**< OBEX: OPP object file system error occurred */ + OI_OBEX_FILEOP_ERROR = 1756, /**< OBEX: FTP/PBAP file operation system error occurred */ + OI_OBEX_USERID_TOO_LONG = 1757, /**< OBEX: User Id exceeds spec limited length limit. */ + + OI_HANDSFREE_EVENT_REPORTING_DISABLED = 1801, /**< HANDSFREE: Event reporting disabled */ + OI_HANDSFREE_NOT_CONNECTED = 1802, /**< HANDSFREE: Not connected */ + OI_HANDSFREE_SERVICE_NOT_STARTED = 1803, /**< HANDSFREE: Cannot connect to + handsfree AG if handsfree service + not started */ + OI_HANDSFREE_AG_SERVICE_NOT_STARTED = 1804, /**< HANDSFREE: Cannot connect to handsfree device if + handsfree AG service not started */ + OI_HANDSFREE_COMMAND_IN_PROGRESS = 1805, /**< HANDSFREE: Cannot accept a command at this time */ + OI_HANDSFREE_AUDIO_ALREADY_CONNECTED = 1806, /**< HANDSFREE: Audio is already connected */ + OI_HANDSFREE_AUDIO_NOT_CONNECTED = 1807, /**< HANDSFREE: Audio is not connected */ + OI_HANDSFREE_FEATURE_NOT_SUPPORTED = 1808, /**< HANDSFREE: Local or remote + feature not supported for + requested command */ + + OI_HEADSET_SERVICE_NOT_STARTED = 1901, /**< HEADSET: Cannot connect to headset + AG if headset service not started */ OI_HEADSET_AG_SERVICE_NOT_STARTED = 1902, /**< HEADSET: Cannot connect to headset device if headset AG service not started */ - OI_HEADSET_COMMAND_IN_PROGRESS = - 1903, /**< HEADSET: Cannot accept a command at this time */ + OI_HEADSET_COMMAND_IN_PROGRESS = 1903, /**< HEADSET: Cannot accept a command at this time */ - OI_BNEP_INVALID_MTU = - 2001, /**< BNEP: The remote device cannot support the minimum BNEP MTU */ + OI_BNEP_INVALID_MTU = 2001, /**< BNEP: The remote device cannot support the minimum BNEP MTU */ OI_BNEP_SETUP_TIMEOUT = 2002, /**< BNEP: The setup request timed out. */ - OI_BNEP_SERVICE_NOT_REGISTERED = - 2003, /**< BNEP: The requested service was not found. */ - OI_BNEP_INVALID_HANDLE = - 2004, /**< BNEP: The specified connection handle is not valid. */ - OI_BNEP_RESPONSE_TIMEOUT = - 2005, /**< BNEP: The timer for receiving a response has expired. */ + OI_BNEP_SERVICE_NOT_REGISTERED = 2003, /**< BNEP: The requested service was not found. */ + OI_BNEP_INVALID_HANDLE = 2004, /**< BNEP: The specified connection handle is not valid. */ + OI_BNEP_RESPONSE_TIMEOUT = 2005, /**< BNEP: The timer for receiving a response has expired. */ OI_BNEP_INVALID_CONNECTION = 2006, /**< BNEP: Invalid connection */ - OI_BNEP_INVALID_FILTER = 2007, /**< BNEP: The supplied filter was invalid. */ + OI_BNEP_INVALID_FILTER = 2007, /**< BNEP: The supplied filter was invalid. */ OI_BNEP_CONNECTION_EXISTS = - 2008, /**< BNEP: An attempt was made to create a duplicate connection. */ + 2008, /**< BNEP: An attempt was made to create a duplicate connection. */ OI_BNEP_NOT_INITIALIZED = 2009, /**< BNEP: Init has not been called */ OI_BNEP_CONNECT_BASE = 2010, /**< BNEP: connection response codes */ OI_BNEP_CONNECT_FAILED_INVALID_DEST_UUID = - 2011, /**< BNEP: connect response code Invalid Dest UUID */ + 2011, /**< BNEP: connect response code Invalid Dest UUID */ OI_BNEP_CONNECT_FAILED_INVALID_SOURCE_UUID = - 2012, /**< BNEP: connect response code Invalid Source UUID */ + 2012, /**< BNEP: connect response code Invalid Source UUID */ OI_BNEP_CONNECT_FAILED_INVALID_UUID_SIZE = - 2013, /**< BNEP: connect response code Invalid UUID Size */ - OI_BNEP_CONNECT_FAILED_NOT_ALLOWED = - 2014, /**< BNEP: connect response code Not Allowed */ - OI_BNEP_FILTER_NET_BASE = 2020, /**< BNEP: filter response codes */ + 2013, /**< BNEP: connect response code Invalid UUID Size */ + OI_BNEP_CONNECT_FAILED_NOT_ALLOWED = 2014, /**< BNEP: connect response code Not Allowed */ + OI_BNEP_FILTER_NET_BASE = 2020, /**< BNEP: filter response codes */ OI_BNEP_FILTER_NET_UNSUPPORTED_REQUEST = - 2021, /**< BNEP: filter response code Unsupported Request */ + 2021, /**< BNEP: filter response code Unsupported Request */ OI_BNEP_FILTER_NET_FAILED_INVALID_PROTOCOL_TYPE = - 2022, /**< BNEP: filter response code Invalid Protocol Type */ + 2022, /**< BNEP: filter response code Invalid Protocol Type */ OI_BNEP_FILTER_NET_FAILED_MAX_LIMIT_REACHED = - 2023, /**< BNEP: filter response code Max Limit Reached */ - OI_BNEP_FILTER_NET_FAILED_SECURITY = - 2024, /**< BNEP: filter response code Security */ - OI_BNEP_FILTER_MULTI_BASE = 2030, /**< BNEP: multicast response codes */ + 2023, /**< BNEP: filter response code Max Limit Reached */ + OI_BNEP_FILTER_NET_FAILED_SECURITY = 2024, /**< BNEP: filter response code Security */ + OI_BNEP_FILTER_MULTI_BASE = 2030, /**< BNEP: multicast response codes */ OI_BNEP_FILTER_MULTI_UNSUPPORTED_REQUEST = - 2031, /**< BNEP: multicast response code Unsupported Request */ + 2031, /**< BNEP: multicast response code Unsupported Request */ OI_BNEP_FILTER_MULTI_FAILED_INVALID_ADDRESS = - 2032, /**< BNEP: multicast response code Invalid Address */ + 2032, /**< BNEP: multicast response code Invalid Address */ OI_BNEP_FILTER_MULTI_FAILED_MAX_LIMIT_REACHED = - 2033, /**< BNEP: multicast response code Max Limit Reached */ - OI_BNEP_FILTER_MULTI_FAILED_SECURITY = - 2034, /**< BNEP: multicast response code Security */ + 2033, /**< BNEP: multicast response code Max Limit Reached */ + OI_BNEP_FILTER_MULTI_FAILED_SECURITY = 2034, /**< BNEP: multicast response code Security */ OI_BNEP_LOCAL_DEVICE_MUST_BE_CENTRAL = - 2040, /**< BNEP: Device must be central of the piconet for this function - */ - OI_BNEP_PACKET_FILTERED_OUT = - 2041, /**< BNEP: Packet did not pass current filters */ + 2040, /**< BNEP: Device must be central of the piconet for this function + */ + OI_BNEP_PACKET_FILTERED_OUT = 2041, /**< BNEP: Packet did not pass current filters */ - OI_NETIFC_UP_FAILED = - 2101, /**< NETIFC: Could not bring up network interface */ + OI_NETIFC_UP_FAILED = 2101, /**< NETIFC: Could not bring up network interface */ OI_NETIFC_COULD_NOT_CREATE_THREAD = - 2102, /**< NETIFC: Network interface could not create a read thread */ - OI_NETIFC_INITIALIZATION_FAILED = - 2103, /**< NETIFC: Error in network interface initialization */ - OI_NETIFC_INTERFACE_ALREADY_UP = - 2104, /**< NETIFC: Network interface is already up */ - OI_NETIFC_INTERFACE_NOT_UP = 2105, /**< NETIFC: Network interface is not up */ - OI_NETIFC_PACKET_TOO_BIG = 2106, /**< NETIFC: The packet is too big */ - - OI_PAN_ROLE_ALREADY_REGISTERED = - 2201, /**< PAN: This PAN role was already registered */ - OI_PAN_ROLE_NOT_ALLOWED = - 2202, /**< PAN: The PAN role is not currently allowed */ - OI_PAN_INCOMPATIBLE_ROLES = 2203, /**< PAN: Only certain local and remote role - combinations are permitted */ - OI_PAN_INVALID_ROLE = - 2204, /**< PAN: Role specified is not one the defined PAN roles */ - OI_PAN_CONNECTION_IN_PROGRESS = - 2205, /**< PAN: A PAN connection is currently being established */ - OI_PAN_USER_ALREADY_CONNECTED = - 2206, /**< PAN: PAN user role only allows a single connection */ - OI_PAN_DEVICE_CONNECTED = - 2207, /**< PAN: A PAN connection already exists to specified device */ + 2102, /**< NETIFC: Network interface could not create a read thread */ + OI_NETIFC_INITIALIZATION_FAILED = 2103, /**< NETIFC: Error in network interface initialization */ + OI_NETIFC_INTERFACE_ALREADY_UP = 2104, /**< NETIFC: Network interface is already up */ + OI_NETIFC_INTERFACE_NOT_UP = 2105, /**< NETIFC: Network interface is not up */ + OI_NETIFC_PACKET_TOO_BIG = 2106, /**< NETIFC: The packet is too big */ + + OI_PAN_ROLE_ALREADY_REGISTERED = 2201, /**< PAN: This PAN role was already registered */ + OI_PAN_ROLE_NOT_ALLOWED = 2202, /**< PAN: The PAN role is not currently allowed */ + OI_PAN_INCOMPATIBLE_ROLES = 2203, /**< PAN: Only certain local and remote role + combinations are permitted */ + OI_PAN_INVALID_ROLE = 2204, /**< PAN: Role specified is not one the defined PAN roles */ + OI_PAN_CONNECTION_IN_PROGRESS = 2205, /**< PAN: A PAN connection is currently being established */ + OI_PAN_USER_ALREADY_CONNECTED = 2206, /**< PAN: PAN user role only allows a single connection */ + OI_PAN_DEVICE_CONNECTED = 2207, /**< PAN: A PAN connection already exists to specified device */ OI_CODEC_SBC_NO_SYNCWORD = 2301, /**< CODEC: Couldn't find an SBC SYNCWORD */ OI_CODEC_SBC_NOT_ENOUGH_HEADER_DATA = - 2302, /**< CODEC: Not enough data provided to decode an SBC header */ - OI_CODEC_SBC_NOT_ENOUGH_BODY_DATA = - 2303, /**< CODEC: Decoded the header, but not enough data to contain the - rest of the frame */ - OI_CODEC_SBC_NOT_ENOUGH_AUDIO_DATA = - 2304, /**< CODEC: Not enough audio data for this frame */ - OI_CODEC_SBC_CHECKSUM_MISMATCH = - 2305, /**< CODEC: The frame header didn't match the checksum */ + 2302, /**< CODEC: Not enough data provided to decode an SBC header */ + OI_CODEC_SBC_NOT_ENOUGH_BODY_DATA = 2303, /**< CODEC: Decoded the header, but not enough data to + contain the rest of the frame */ + OI_CODEC_SBC_NOT_ENOUGH_AUDIO_DATA = 2304, /**< CODEC: Not enough audio data for this frame */ + OI_CODEC_SBC_CHECKSUM_MISMATCH = 2305, /**< CODEC: The frame header didn't match the checksum */ OI_CODEC_SBC_PARTIAL_DECODE = - 2306, /**< CODEC: Decoding was successful, but frame data still remains. - Next call will provide audio without consuming input data. */ + 2306, /**< CODEC: Decoding was successful, but frame data still remains. + Next call will provide audio without consuming input data. */ OI_FIFOQ_QUEUE_NOT_ALIGNED = 2401, /**< FIFOQ: queue must be 32-bit aligned */ - OI_FIFOQ_INVALID_Q = 2402, /**< FIFOQ: queue parameter is not a valid queue */ - OI_FIFOQ_BUF_TOO_LARGE = - 2403, /**< FIFOQ: attempt to queue a buffer which is too large */ - OI_FIFOQ_FULL = 2404, /**< FIFOQ: enqueue() failed, queue is full */ - OI_FIFOQ_NOT_ALLOCATED = - 2405, /**< FIFOQ: Enqueue QBuf() failed, buffer not allocated */ + OI_FIFOQ_INVALID_Q = 2402, /**< FIFOQ: queue parameter is not a valid queue */ + OI_FIFOQ_BUF_TOO_LARGE = 2403, /**< FIFOQ: attempt to queue a buffer which is too large */ + OI_FIFOQ_FULL = 2404, /**< FIFOQ: enqueue() failed, queue is full */ + OI_FIFOQ_NOT_ALLOCATED = 2405, /**< FIFOQ: Enqueue QBuf() failed, buffer not allocated */ OI_FIFOQ_INVALID_DATA_PTR = - 2406, /**< FIFOQ: Enqueue QBuf() failed, data pointer does not match */ + 2406, /**< FIFOQ: Enqueue QBuf() failed, data pointer does not match */ OI_HID_HOST_SERVICE_NOT_STARTED = 2601, /**< HID: Cannot connect to a HID device unless HID host is started */ OI_HID_DEVICE_SERVICE_NOT_STARTED = - 2602, /**< HID: Cannot connect to a HID host unless HID device is started - */ + 2602, /**< HID: Cannot connect to a HID host unless HID device is started + */ OI_AT_ERROR = 2701, /**< AT: ERROR response */ OI_AT_NO_CARRIER = 2702, /**< AT: NO CARRIER response */ @@ -756,66 +605,59 @@ timeout configurable via @ref OI_CONFIG_DEVMGR::connectQueueTimeoutSecs OI_AT_CME_ERROR = 2707, /**< AT: +CME ERROR response */ OI_AT_CMS_ERROR = 2708, /**< AT: +CMS ERROR response */ - OI_BLST_CHARACTER_TIMEOUT = 2801, /**< BLST: Timeout expired while waiting for - a character from the client. */ - OI_BLST_ACKNOWLDGE_TIMEOUT = - 2802, /**< BLST: Timeout expired while waiting for event acknowledgment - from the client */ - OI_BLST_TX_NOT_READY = 2803, /**< BLST: BLST is not ready to send a BHAPI - message to the client. */ - OI_BLST_TX_BUSY = 2804, /**< BLST: BLST transmit buffer is in use. */ - - OI_AVDTP_CONNECTION_SEQ_ERROR = - 2901, /**< AVDTP: sequencing of signalling/media channel connections - broken. */ - OI_AVDTP_OUT_OF_RESOURCES = 2902, /**< AVDTP: Tried to allocate too many - endpoints or signalling channels. */ + OI_BLST_CHARACTER_TIMEOUT = 2801, /**< BLST: Timeout expired while waiting for + a character from the client. */ + OI_BLST_ACKNOWLEDGE_TIMEOUT = 2802, /**< BLST: Timeout expired while waiting for event + acknowledgment from the client */ + OI_BLST_TX_NOT_READY = 2803, /**< BLST: BLST is not ready to send a BHAPI + message to the client. */ + OI_BLST_TX_BUSY = 2804, /**< BLST: BLST transmit buffer is in use. */ + + OI_AVDTP_CONNECTION_SEQ_ERROR = 2901, /**< AVDTP: sequencing of signalling/media channel + connections broken. */ + OI_AVDTP_OUT_OF_RESOURCES = 2902, /**< AVDTP: Tried to allocate too many + endpoints or signalling channels. */ OI_PBAP_REPOSITORY_NOT_SET = 3001, /**< PBAP: Phonebook repository must be set for operation to complete. */ - OI_PBAP_PHONEBOOK_NOT_SET = - 3002, /**< PBAP: Phonebook be set for operation to complete. */ + OI_PBAP_PHONEBOOK_NOT_SET = 3002, /**< PBAP: Phonebook be set for operation to complete. */ OI_AADP_BAD_ENDPOINT = 3101, /**< AADP: Invalid local endpoint specified */ - OI_AADP_BAD_STATE = - 3102, /**< AADP: AADP State is not correct for this operation. */ - - OI_UNICODE_INVALID_SOURCE = 3200, /**< Unicode Conversion: Source string has - invalid character encoding. */ - OI_UNICODE_SOURCE_EXHAUSTED = 3201, /**< Unicode Conversion: Incomplete - Unicode character at end of source - buffer. */ + OI_AADP_BAD_STATE = 3102, /**< AADP: AADP State is not correct for this operation. */ + + OI_UNICODE_INVALID_SOURCE = 3200, /**< Unicode Conversion: Source string has + invalid character encoding. */ + OI_UNICODE_SOURCE_EXHAUSTED = 3201, /**< Unicode Conversion: Incomplete + Unicode character at end of source + buffer. */ OI_UNICODE_DESTINATION_EXHAUSTED = 3202, /**< Unicode Conversion: Destination buffer not large enough to hold resulting Unicode string. */ OI_AVRCP_TOO_MANY_CONNECTIONS = 3300, /**< AVRCP: Exceeded maximum number of simultaneous AVCTP connections. */ - OI_AVRCP_NOT_IMPLEMENTED = - 3301, /**< AVRCP: The target does not implement the command specified by - the opcode and operand. */ - OI_AVRCP_REJECTED = 3302, /**< AVRCP: The target cannot respond because of - invalid operands in command packet. */ + OI_AVRCP_NOT_IMPLEMENTED = 3301, /**< AVRCP: The target does not implement the command specified + by the opcode and operand. */ + OI_AVRCP_REJECTED = 3302, /**< AVRCP: The target cannot respond because of + invalid operands in command packet. */ OI_AVRCP_INVALID_RESPONSE = 3303, /**< AVRCP: The controller received the response with invalid parameters */ OI_AVRCP_RESPONSE_PACKET_OVERFLOW = - 3304, /**< AVRCP: The response message does not fir in one AVRCP packet - (512 bytes), has to be fragmented. */ - OI_AVRCP_RESPONSE_INVALID_PDU = 3305, /**< AVRCP: Command rejected: target - received a PDU that it did not - understand. */ - OI_AVRCP_RESPONSE_INVALID_PARAMETER = 3306, /**< AVRCP: Command rejected: - target received a PDU with a - parameter ID that it did not - understand. */ - OI_AVRCP_RESPONSE_PARAMETER_NOT_FOUND = - 3307, /**< AVRCP: Command rejected: specified parameter not found, sent if - the parameter ID is understood, but content is wrong or - corrupted.*/ - OI_AVRCP_RESPONSE_INTERNAL_ERROR = - 3308, /**< AVRCP: Command rejected: target detected other error - conditions. */ - OI_MAX_BM3_STATUS_VAL, /* Maximum BM3 status code */ + 3304, /**< AVRCP: The response message does not fir in one + AVRCP packet (512 bytes), has to be fragmented. */ + OI_AVRCP_RESPONSE_INVALID_PDU = 3305, /**< AVRCP: Command rejected: target + received a PDU that it did not + understand. */ + OI_AVRCP_RESPONSE_INVALID_PARAMETER = 3306, /**< AVRCP: Command rejected: + target received a PDU with a + parameter ID that it did not + understand. */ + OI_AVRCP_RESPONSE_PARAMETER_NOT_FOUND = 3307, /**< AVRCP: Command rejected: specified parameter + not found, sent if the parameter ID is + understood, but content is wrong or corrupted.*/ + OI_AVRCP_RESPONSE_INTERNAL_ERROR = 3308, /**< AVRCP: Command rejected: target detected other error + conditions. */ + OI_MAX_BM3_STATUS_VAL, /* Maximum BM3 status code */ /* Status code values reserved for BM3 SDK platform-specific implementations */ @@ -845,7 +687,7 @@ timeout configurable via @ref OI_CONFIG_DEVMGR::connectQueueTimeoutSecs } OI_STATUS; -/* Remeber to update the #define below when new reserved blocks are added to +/* Remember to update the #define below when new reserved blocks are added to * the list above. */ #define OI_NUM_RESERVED_STATUS_BLOCKS \ 4 /**< Number of status code blocks reserved, including user apps */ diff --git a/system/embdrv/sbc/decoder/include/oi_stddefs.h b/system/embdrv/sbc/decoder/include/oi_stddefs.h index e6196358499..1cf03b7bbe6 100644 --- a/system/embdrv/sbc/decoder/include/oi_stddefs.h +++ b/system/embdrv/sbc/decoder/include/oi_stddefs.h @@ -39,8 +39,7 @@ extern "C" { #endif #ifndef FALSE -#define FALSE \ - 0 /**< This define statement sets FALSE as a preprocessor alias for 0. */ +#define FALSE 0 /**< This define statement sets FALSE as a preprocessor alias for 0. */ #endif #ifndef TRUE @@ -74,17 +73,16 @@ extern "C" { #define OI_INT16_MAX ((int16_t)0x7FFF) /**< decimal value: 32767 */ #define OI_INT32_MIN \ ((int32_t)0x80000000) /**< decimal value: -2,147,483,648 \ - */ -#define OI_INT32_MAX \ - ((int32_t)0x7FFFFFFF) /**< decimal value: 2,147,483,647 \ - */ -#define OI_UINT8_MIN ((uint8_t)0) /**< decimal value: 0 */ -#define OI_UINT8_MAX ((uint8_t)0xFF) /**< decimal value: 255 */ -#define OI_UINT16_MIN ((uint16_t)0) /**< decimal value: 0 */ -#define OI_UINT16_MAX ((uint16_t)0xFFFF) /**< decimal value: 65535 */ -#define OI_UINT32_MIN ((uint32_t)0) /**< decimal value: 0 */ -#define OI_UINT32_MAX \ - ((uint32_t)0xFFFFFFFF) /**< decimal value: 4,294,967,295 */ + */ +#define OI_INT32_MAX \ + ((int32_t)0x7FFFFFFF) /**< decimal value: 2,147,483,647 \ + */ +#define OI_UINT8_MIN ((uint8_t)0) /**< decimal value: 0 */ +#define OI_UINT8_MAX ((uint8_t)0xFF) /**< decimal value: 255 */ +#define OI_UINT16_MIN ((uint16_t)0) /**< decimal value: 0 */ +#define OI_UINT16_MAX ((uint16_t)0xFFFF) /**< decimal value: 65535 */ +#define OI_UINT32_MIN ((uint32_t)0) /**< decimal value: 0 */ +#define OI_UINT32_MAX ((uint32_t)0xFFFFFFFF) /**< decimal value: 4,294,967,295 */ /** * @} @@ -127,16 +125,10 @@ typedef struct { uint32_t I4; /**< least significant 32 bits */ } OI_UINT128; -#define OI_UINT128_MIN \ - { \ - (uint32_t)0x00000000, (uint32_t)0x00000000, (uint32_t)0x00000000, \ - (uint32_t)0x00000000 \ - } -#define OI_UINT128_MAX \ - { \ - (uint32_t)0XFFFFFFFF, (uint32_t)0XFFFFFFFF, (uint32_t)0XFFFFFFFF, \ - (uint32_t)0XFFFFFFFF \ - } +#define OI_UINT128_MIN \ + { (uint32_t)0x00000000, (uint32_t)0x00000000, (uint32_t)0x00000000, (uint32_t)0x00000000 } +#define OI_UINT128_MAX \ + { (uint32_t)0XFFFFFFFF, (uint32_t)0XFFFFFFFF, (uint32_t)0XFFFFFFFF, (uint32_t)0XFFFFFFFF } /* signed 128-bit integer as a structure of three unsigned 32-bit integers and * one signed 32-bit integer */ @@ -147,16 +139,10 @@ typedef struct { uint32_t I4; /**< least significant 32 bits as an unsigned integer */ } OI_INT128; -#define OI_INT128_MIN \ - { \ - (uint32_t)0x80000000, (uint32_t)0x00000000, (uint32_t)0x00000000, \ - (uint32_t)0x00000000 \ - } -#define OI_INT128_MAX \ - { \ - (uint32_t)0X7FFFFFFF, (uint32_t)0XFFFFFFFF, (uint32_t)0XFFFFFFFF, \ - (uint32_t)0XFFFFFFFF \ - } +#define OI_INT128_MIN \ + { (uint32_t)0x80000000, (uint32_t)0x00000000, (uint32_t)0x00000000, (uint32_t)0x00000000 } +#define OI_INT128_MAX \ + { (uint32_t)0X7FFFFFFF, (uint32_t)0XFFFFFFFF, (uint32_t)0XFFFFFFFF, (uint32_t)0XFFFFFFFF } /** * @} diff --git a/system/embdrv/sbc/decoder/include/oi_time.h b/system/embdrv/sbc/decoder/include/oi_time.h index d183ccb0297..5fa1d3505f1 100644 --- a/system/embdrv/sbc/decoder/include/oi_time.h +++ b/system/embdrv/sbc/decoder/include/oi_time.h @@ -64,23 +64,22 @@ typedef uint16_t OI_INTERVAL; * Macro to convert seconds to OI_INTERVAL time units */ -#define OI_SECONDS(n) ((OI_INTERVAL)((n)*OI_INTERVALS_PER_SECOND)) +#define OI_SECONDS(n) ((OI_INTERVAL)((n) * OI_INTERVALS_PER_SECOND)) /** * Macro to convert milliseconds to OI_INTERVAL time units (Rounded Up) */ -#define OI_MSECONDS(n) \ - ((OI_INTERVAL)(((n) + MSECS_PER_OI_INTERVAL - 1) / MSECS_PER_OI_INTERVAL)) +#define OI_MSECONDS(n) ((OI_INTERVAL)(((n) + MSECS_PER_OI_INTERVAL - 1) / MSECS_PER_OI_INTERVAL)) /** * Macro to convert minutes to OI_INTERVAL time units */ -#define OI_MINUTES(n) ((OI_INTERVAL)((n)*OI_SECONDS(60))) +#define OI_MINUTES(n) ((OI_INTERVAL)((n) * OI_SECONDS(60))) /** Convert an OI_INTERVAL to milliseconds. */ -#define OI_INTERVAL_TO_MILLISECONDS(i) ((i)*MSECS_PER_OI_INTERVAL) +#define OI_INTERVAL_TO_MILLISECONDS(i) ((i) * MSECS_PER_OI_INTERVAL) /** * The stack depends on relative not absolute time. Any mapping between the diff --git a/system/embdrv/sbc/decoder/include/oi_utils.h b/system/embdrv/sbc/decoder/include/oi_utils.h index 269114f7775..c6834b76ab0 100644 --- a/system/embdrv/sbc/decoder/include/oi_utils.h +++ b/system/embdrv/sbc/decoder/include/oi_utils.h @@ -33,6 +33,7 @@ ******************************************************************************/ #include + #include "oi_bt_spec.h" #include "oi_common.h" #include "oi_string.h" @@ -80,9 +81,8 @@ typedef void (*OI_SCHEDULED_CALLBACK)(void* arg); * @return OI_OK if the function was registered, or an error * status. */ -OI_STATUS OI_ScheduleCallbackFunction(OI_SCHEDULED_CALLBACK callbackFunction, - void* arg, OI_INTERVAL timeout, - OI_CALLBACK_HANDLE* handle); +OI_STATUS OI_ScheduleCallbackFunction(OI_SCHEDULED_CALLBACK callbackFunction, void* arg, + OI_INTERVAL timeout, OI_CALLBACK_HANDLE* handle); /** * Cancels a function registered with OI_ScheduleCallbackFunction() before its @@ -222,8 +222,7 @@ void OI_VPrintf(const OI_CHAR* format, va_list argp); * * @return Number of characters written or -1 in the case of an error. */ -int32_t OI_SNPrintf(OI_CHAR* buffer, uint16_t bufLen, const OI_CHAR* format, - ...); +int32_t OI_SNPrintf(OI_CHAR* buffer, uint16_t bufLen, const OI_CHAR* format, ...); /** * Var-args version OI_SNPrintf @@ -238,8 +237,7 @@ int32_t OI_SNPrintf(OI_CHAR* buffer, uint16_t bufLen, const OI_CHAR* format, * * @return Number of characters written or -1 in the case of an error. */ -int32_t OI_VSNPrintf(OI_CHAR* buffer, uint16_t bufLen, const OI_CHAR* format, - va_list argp); +int32_t OI_VSNPrintf(OI_CHAR* buffer, uint16_t bufLen, const OI_CHAR* format, va_list argp); /** * Convert a string to an integer. @@ -314,8 +312,7 @@ const OI_CHAR* OI_ScanStr(const OI_CHAR* str, OI_CHAR* outStr, uint16_t len); * @return A pointer to the first character following the matched value or * the pointer passed in if there was no matching text. */ -const OI_CHAR* OI_ScanAlt(const OI_CHAR* str, const OI_CHAR* alts, - OI_INT* index); +const OI_CHAR* OI_ScanAlt(const OI_CHAR* str, const OI_CHAR* alts, OI_INT* index); /** Get a character from a digit integer value (0 - 9). */ #define OI_DigitToChar(d) ((d) + '0') diff --git a/system/embdrv/sbc/decoder/sbcdecoder_fuzzer.c b/system/embdrv/sbc/decoder/sbcdecoder_fuzzer.c index e63d93ac35e..336187116ca 100644 --- a/system/embdrv/sbc/decoder/sbcdecoder_fuzzer.c +++ b/system/embdrv/sbc/decoder/sbcdecoder_fuzzer.c @@ -3,7 +3,7 @@ #include "oi_codec_sbc.h" #define CODEC_DATA_WORDS(numChannels, numBuffers) \ - (((sizeof(int32_t) * SBC_MAX_BLOCKS * (numChannels)*SBC_MAX_BANDS) + \ + (((sizeof(int32_t) * SBC_MAX_BLOCKS * (numChannels) * SBC_MAX_BANDS) + \ (sizeof(SBC_BUFFER_T) * SBC_MAX_CHANNELS * SBC_MAX_BANDS * (numBuffers)) + \ (sizeof(uint32_t) - 1)) / \ sizeof(uint32_t)) @@ -30,17 +30,14 @@ #define SBC_MAX_SAMPLES_PER_FRAME (SBC_MAX_BANDS * SBC_MAX_BLOCKS) static OI_CODEC_SBC_DECODER_CONTEXT btif_a2dp_sink_context; -static uint32_t btif_a2dp_sink_context_data[CODEC_DATA_WORDS( - 2, SBC_CODEC_FAST_FILTER_BUFFERS)]; +static uint32_t btif_a2dp_sink_context_data[CODEC_DATA_WORDS(2, SBC_CODEC_FAST_FILTER_BUFFERS)]; -static int16_t - btif_a2dp_sink_pcm_data[15 * SBC_MAX_SAMPLES_PER_FRAME * SBC_MAX_CHANNELS]; +static int16_t btif_a2dp_sink_pcm_data[15 * SBC_MAX_SAMPLES_PER_FRAME * SBC_MAX_CHANNELS]; int LLVMFuzzerInitialize(int argc, char** argv) { (void)argc; (void)argv; - OI_CODEC_SBC_DecoderReset(&btif_a2dp_sink_context, - btif_a2dp_sink_context_data, + OI_CODEC_SBC_DecoderReset(&btif_a2dp_sink_context, btif_a2dp_sink_context_data, sizeof(btif_a2dp_sink_context_data), 2, 2, 0); return 0; @@ -49,13 +46,12 @@ int LLVMFuzzerInitialize(int argc, char** argv) { int LLVMFuzzerTestOneInput(const uint8_t* buf, size_t len) { uint32_t pcmBytes, availPcmBytes; int16_t* pcmDataPointer = - btif_a2dp_sink_pcm_data; /* Will be overwritten on next packet receipt */ + btif_a2dp_sink_pcm_data; /* Will be overwritten on next packet receipt */ availPcmBytes = sizeof(btif_a2dp_sink_pcm_data); pcmBytes = availPcmBytes; - OI_CODEC_SBC_DecodeFrame(&btif_a2dp_sink_context, (const OI_BYTE**)&buf, - (uint32_t*)&len, (int16_t*)pcmDataPointer, - (uint32_t*)&pcmBytes); + OI_CODEC_SBC_DecodeFrame(&btif_a2dp_sink_context, (const OI_BYTE**)&buf, (uint32_t*)&len, + (int16_t*)pcmDataPointer, (uint32_t*)&pcmBytes); return 0; } diff --git a/system/embdrv/sbc/decoder/srce/alloc.c b/system/embdrv/sbc/decoder/srce/alloc.c index bc6e5435431..10996b3df2f 100644 --- a/system/embdrv/sbc/decoder/srce/alloc.c +++ b/system/embdrv/sbc/decoder/srce/alloc.c @@ -27,8 +27,7 @@ ******************************************************************************/ PRIVATE OI_STATUS OI_CODEC_SBC_Alloc(OI_CODEC_SBC_COMMON_CONTEXT* common, - uint32_t* codecDataAligned, - uint32_t codecDataBytes, + uint32_t* codecDataAligned, uint32_t codecDataBytes, uint8_t maxChannels, uint8_t pcmStride) { int i; size_t filterBufferCount; @@ -48,15 +47,13 @@ PRIVATE OI_STATUS OI_CODEC_SBC_Alloc(OI_CODEC_SBC_COMMON_CONTEXT* common, /* Compute sizes needed for the memory regions, and bail if we don't have * enough memory for them. */ - subdataSize = - maxChannels * sizeof(common->subdata[0]) * SBC_MAX_BANDS * SBC_MAX_BLOCKS; + subdataSize = maxChannels * sizeof(common->subdata[0]) * SBC_MAX_BANDS * SBC_MAX_BLOCKS; if (subdataSize > codecDataBytes) { return OI_STATUS_OUT_OF_MEMORY; } - filterBufferCount = - (codecDataBytes - subdataSize) / - (sizeof(common->filterBuffer[0][0]) * SBC_MAX_BANDS * maxChannels); + filterBufferCount = (codecDataBytes - subdataSize) / + (sizeof(common->filterBuffer[0][0]) * SBC_MAX_BANDS * maxChannels); if (filterBufferCount < SBC_CODEC_MIN_FILTER_BUFFERS) { return OI_STATUS_OUT_OF_MEMORY; } @@ -70,8 +67,7 @@ PRIVATE OI_STATUS OI_CODEC_SBC_Alloc(OI_CODEC_SBC_COMMON_CONTEXT* common, /* Allocate memory for the synthesis buffers */ for (i = 0; i < maxChannels; ++i) { - size_t allocSize = - common->filterBufferLen * sizeof(common->filterBuffer[0][0]); + size_t allocSize = common->filterBufferLen * sizeof(common->filterBuffer[0][0]); common->filterBuffer[i] = (SBC_BUFFER_T*)codecData; OI_ASSERT(codecDataBytes >= allocSize); codecData += allocSize; diff --git a/system/embdrv/sbc/decoder/srce/bitalloc-sbc.c b/system/embdrv/sbc/decoder/srce/bitalloc-sbc.c index caf6bdf1fbc..2263fb77418 100644 --- a/system/embdrv/sbc/decoder/srce/bitalloc-sbc.c +++ b/system/embdrv/sbc/decoder/srce/bitalloc-sbc.c @@ -57,24 +57,21 @@ static void stereoBitAllocation(OI_CODEC_SBC_COMMON_CONTEXT* common) { OI_UINT bitpoolPreference = 0; bitcount = computeBitneed(common, &bitneeds.uint8[0], 0, &bitpoolPreference); - bitcount += computeBitneed(common, &bitneeds.uint8[nrof_subbands], 1, - &bitpoolPreference); + bitcount += computeBitneed(common, &bitneeds.uint8[nrof_subbands], 1, &bitpoolPreference); { OI_UINT ex; - bitadjust = adjustToFitBitpool(common->frameInfo.bitpool, bitneeds.uint32, - 2 * nrof_subbands, bitcount, &ex); + bitadjust = adjustToFitBitpool(common->frameInfo.bitpool, bitneeds.uint32, 2 * nrof_subbands, + bitcount, &ex); /* We want the compiler to put excess into a register */ excess = ex; } sbL = 0; sbR = nrof_subbands; while (sbL < nrof_subbands) { - excess = allocAdjustedBits(&common->bits.uint8[sbL], - bitneeds.uint8[sbL] + bitadjust, excess); + excess = allocAdjustedBits(&common->bits.uint8[sbL], bitneeds.uint8[sbL] + bitadjust, excess); ++sbL; - excess = allocAdjustedBits(&common->bits.uint8[sbR], - bitneeds.uint8[sbR] + bitadjust, excess); + excess = allocAdjustedBits(&common->bits.uint8[sbR], bitneeds.uint8[sbR] + bitadjust, excess); ++sbR; } sbL = 0; @@ -91,10 +88,10 @@ static void stereoBitAllocation(OI_CODEC_SBC_COMMON_CONTEXT* common) { } static const BIT_ALLOC balloc[] = { - monoBitAllocation, /* SBC_MONO */ - dualBitAllocation, /* SBC_DUAL_CHANNEL */ - stereoBitAllocation, /* SBC_STEREO */ - stereoBitAllocation /* SBC_JOINT_STEREO */ + monoBitAllocation, /* SBC_MONO */ + dualBitAllocation, /* SBC_DUAL_CHANNEL */ + stereoBitAllocation, /* SBC_STEREO */ + stereoBitAllocation /* SBC_JOINT_STEREO */ }; PRIVATE void OI_SBC_ComputeBitAllocation(OI_CODEC_SBC_COMMON_CONTEXT* common) { @@ -126,8 +123,7 @@ uint8_t OI_CODEC_SBC_GetMaxBitneed(OI_CODEC_SBC_COMMON_CONTEXT* common) { /* * Calculates the bitpool size for a given frame length */ -uint16_t OI_CODEC_SBC_CalculateBitpool(OI_CODEC_SBC_FRAME_INFO* frame, - uint16_t frameLen) { +uint16_t OI_CODEC_SBC_CalculateBitpool(OI_CODEC_SBC_FRAME_INFO* frame, uint16_t frameLen) { uint16_t nrof_subbands = frame->nrof_subbands; uint16_t nrof_blocks = frame->nrof_blocks; uint16_t hdr; diff --git a/system/embdrv/sbc/decoder/srce/bitalloc.c b/system/embdrv/sbc/decoder/srce/bitalloc.c index db8a3b5de12..0d5df57f5f5 100644 --- a/system/embdrv/sbc/decoder/srce/bitalloc.c +++ b/system/embdrv/sbc/decoder/srce/bitalloc.c @@ -38,6 +38,7 @@ frame length and bitrate. */ #include + #include "oi_utils.h" uint32_t OI_SBC_MaxBitpool(OI_CODEC_SBC_FRAME_INFO* frame) { @@ -79,14 +80,12 @@ PRIVATE uint32_t internal_CalculateBitrate(OI_CODEC_SBC_FRAME_INFO* frame) { OI_UINT blocksbands; blocksbands = frame->nrof_subbands * frame->nrof_blocks; - return DIVIDE(8 * internal_CalculateFramelen(frame) * frame->frequency, - blocksbands); + return DIVIDE(8 * internal_CalculateFramelen(frame) * frame->frequency, blocksbands); } -INLINE uint16_t OI_SBC_CalculateFrameAndHeaderlen( - OI_CODEC_SBC_FRAME_INFO* frame, OI_UINT* headerLen_) { - OI_UINT headerLen = - SBC_HEADER_LEN + frame->nrof_subbands * frame->nrof_channels / 2; +INLINE uint16_t OI_SBC_CalculateFrameAndHeaderlen(OI_CODEC_SBC_FRAME_INFO* frame, + OI_UINT* headerLen_) { + OI_UINT headerLen = SBC_HEADER_LEN + frame->nrof_subbands * frame->nrof_channels / 2; if (frame->mode == SBC_JOINT_STEREO) { headerLen++; @@ -121,10 +120,9 @@ INLINE uint16_t OI_SBC_CalculateFrameAndHeaderlen( * @return The SBC bit need * */ -OI_UINT computeBitneed(OI_CODEC_SBC_COMMON_CONTEXT* common, uint8_t* bitneeds, - OI_UINT ch, OI_UINT* preferredBitpool) { - static const int8_t offset4[4][4] = { - {-1, 0, 0, 0}, {-2, 0, 0, 1}, {-2, 0, 0, 1}, {-2, 0, 0, 1}}; +OI_UINT computeBitneed(OI_CODEC_SBC_COMMON_CONTEXT* common, uint8_t* bitneeds, OI_UINT ch, + OI_UINT* preferredBitpool) { + static const int8_t offset4[4][4] = {{-1, 0, 0, 0}, {-2, 0, 0, 1}, {-2, 0, 0, 1}, {-2, 0, 0, 1}}; static const int8_t offset8[4][8] = {{-2, 0, 0, 0, 0, 0, 0, 1}, {-3, 0, 0, 0, 0, 0, 1, 2}, @@ -242,9 +240,8 @@ OI_UINT computeBitneed(OI_CODEC_SBC_COMMON_CONTEXT* common, uint8_t* bitneeds, * * @return The adjustment. */ -OI_INT adjustToFitBitpool(const OI_UINT bitpool, uint32_t* bitneeds, - const OI_UINT subbands, OI_UINT bitcount, - OI_UINT* excess) { +OI_INT adjustToFitBitpool(const OI_UINT bitpool, uint32_t* bitneeds, const OI_UINT subbands, + OI_UINT bitcount, OI_UINT* excess) { OI_INT maxBitadjust = 0; OI_INT bitadjust = (bitcount > bitpool) ? -8 : 8; OI_INT chop = 8; @@ -329,9 +326,8 @@ INLINE OI_INT allocExcessBits(uint8_t* dest, OI_INT excess) { } } -void oneChannelBitAllocation(OI_CODEC_SBC_COMMON_CONTEXT* common, - BITNEED_UNION1* bitneeds, OI_UINT ch, - OI_UINT bitcount) { +void oneChannelBitAllocation(OI_CODEC_SBC_COMMON_CONTEXT* common, BITNEED_UNION1* bitneeds, + OI_UINT ch, OI_UINT bitcount) { const uint8_t nrof_subbands = common->frameInfo.nrof_subbands; OI_UINT excess; OI_UINT sb; @@ -340,8 +336,8 @@ void oneChannelBitAllocation(OI_CODEC_SBC_COMMON_CONTEXT* common, { OI_UINT ex; - bitadjust = adjustToFitBitpool(common->frameInfo.bitpool, bitneeds->uint32, - nrof_subbands, bitcount, &ex); + bitadjust = adjustToFitBitpool(common->frameInfo.bitpool, bitneeds->uint32, nrof_subbands, + bitcount, &ex); /* We want the compiler to put excess into a register */ excess = ex; } @@ -353,8 +349,7 @@ void oneChannelBitAllocation(OI_CODEC_SBC_COMMON_CONTEXT* common, sb = 0; while (sb < nrof_subbands) { - excess = allocAdjustedBits(&allocBits[sb], bitneeds->uint8[sb] + bitadjust, - excess); + excess = allocAdjustedBits(&allocBits[sb], bitneeds->uint8[sb] + bitadjust, excess); ++sb; } sb = 0; diff --git a/system/embdrv/sbc/decoder/srce/decoder-oina.c b/system/embdrv/sbc/decoder/srce/decoder-oina.c index 199986891b5..dedccc1bc39 100644 --- a/system/embdrv/sbc/decoder/srce/decoder-oina.c +++ b/system/embdrv/sbc/decoder/srce/decoder-oina.c @@ -35,10 +35,9 @@ This file exposes OINA-specific interfaces to decoder functions. #include -OI_STATUS OI_CODEC_SBC_DecoderConfigureRaw( - OI_CODEC_SBC_DECODER_CONTEXT* context, OI_BOOL enhanced, uint8_t frequency, - uint8_t mode, uint8_t subbands, uint8_t blocks, uint8_t alloc, - uint8_t maxBitpool) { +OI_STATUS OI_CODEC_SBC_DecoderConfigureRaw(OI_CODEC_SBC_DECODER_CONTEXT* context, OI_BOOL enhanced, + uint8_t frequency, uint8_t mode, uint8_t subbands, + uint8_t blocks, uint8_t alloc, uint8_t maxBitpool) { if (frequency > SBC_FREQ_48000) { return OI_STATUS_INVALID_PARAMETERS; } @@ -90,16 +89,14 @@ OI_STATUS OI_CODEC_SBC_DecoderConfigureRaw( return OI_OK; } -OI_STATUS OI_CODEC_SBC_DecodeRaw(OI_CODEC_SBC_DECODER_CONTEXT* context, - uint8_t bitpool, const OI_BYTE** frameData, - uint32_t* frameBytes, int16_t* pcmData, +OI_STATUS OI_CODEC_SBC_DecodeRaw(OI_CODEC_SBC_DECODER_CONTEXT* context, uint8_t bitpool, + const OI_BYTE** frameData, uint32_t* frameBytes, int16_t* pcmData, uint32_t* pcmBytes) { - return internal_DecodeRaw(context, bitpool, frameData, frameBytes, pcmData, - pcmBytes); + return internal_DecodeRaw(context, bitpool, frameData, frameBytes, pcmData, pcmBytes); } -OI_STATUS OI_CODEC_SBC_DecoderLimit(OI_CODEC_SBC_DECODER_CONTEXT* context, - OI_BOOL enhanced, uint8_t subbands) { +OI_STATUS OI_CODEC_SBC_DecoderLimit(OI_CODEC_SBC_DECODER_CONTEXT* context, OI_BOOL enhanced, + uint8_t subbands) { if (enhanced) { #ifdef SBC_ENHANCED context->enhancedEnabled = TRUE; diff --git a/system/embdrv/sbc/decoder/srce/decoder-private.c b/system/embdrv/sbc/decoder/srce/decoder-private.c index 47ddb72d0b3..26d13fc14a4 100644 --- a/system/embdrv/sbc/decoder/srce/decoder-private.c +++ b/system/embdrv/sbc/decoder/srce/decoder-private.c @@ -38,14 +38,12 @@ This file drives SBC decoding. #include "oi_codec_sbc_private.h" OI_CHAR* const OI_Codec_Copyright = - "Copyright 2002-2007 Open Interface North America, Inc. All rights " - "reserved"; - -INLINE OI_STATUS internal_DecoderReset(OI_CODEC_SBC_DECODER_CONTEXT* context, - uint32_t* decoderData, - uint32_t decoderDataBytes, - OI_BYTE maxChannels, OI_BYTE pcmStride, - OI_BOOL enhanced) { + "Copyright 2002-2007 Open Interface North America, Inc. All rights " + "reserved"; + +INLINE OI_STATUS internal_DecoderReset(OI_CODEC_SBC_DECODER_CONTEXT* context, uint32_t* decoderData, + uint32_t decoderDataBytes, OI_BYTE maxChannels, + OI_BYTE pcmStride, OI_BOOL enhanced) { OI_UINT i; OI_STATUS status; @@ -62,8 +60,8 @@ INLINE OI_STATUS internal_DecoderReset(OI_CODEC_SBC_DECODER_CONTEXT* context, } #endif - status = OI_CODEC_SBC_Alloc(&context->common, decoderData, decoderDataBytes, - maxChannels, pcmStride); + status = OI_CODEC_SBC_Alloc(&context->common, decoderData, decoderDataBytes, maxChannels, + pcmStride); if (!OI_SUCCESS(status)) { return status; @@ -84,8 +82,7 @@ INLINE OI_STATUS internal_DecoderReset(OI_CODEC_SBC_DECODER_CONTEXT* context, * syncword has already been examined, and the enhanced mode flag set, by * FindSyncword. */ -INLINE void OI_SBC_ReadHeader(OI_CODEC_SBC_COMMON_CONTEXT* common, - const OI_BYTE* data) { +INLINE void OI_SBC_ReadHeader(OI_CODEC_SBC_COMMON_CONTEXT* common, const OI_BYTE* data) { OI_CODEC_SBC_FRAME_INFO* frame = &common->frameInfo; uint8_t d1; @@ -121,20 +118,19 @@ INLINE void OI_SBC_ReadHeader(OI_CODEC_SBC_COMMON_CONTEXT* common, frame->crc = data[3]; } -#define LOW(x) ((x)&0xf) +#define LOW(x) ((x) & 0xf) #define HIGH(x) ((x) >> 4) /* * Read scalefactor values and prepare the bitstream for OI_SBC_ReadSamples */ -PRIVATE void OI_SBC_ReadScalefactors(OI_CODEC_SBC_COMMON_CONTEXT* common, - const OI_BYTE* b, OI_BITSTREAM* bs) { +PRIVATE void OI_SBC_ReadScalefactors(OI_CODEC_SBC_COMMON_CONTEXT* common, const OI_BYTE* b, + OI_BITSTREAM* bs) { OI_UINT i = common->frameInfo.nrof_subbands * common->frameInfo.nrof_channels; int8_t* scale_factor = common->scale_factor; OI_UINT f; - if (common->frameInfo.nrof_subbands == 8 || - common->frameInfo.mode != SBC_JOINT_STEREO) { + if (common->frameInfo.nrof_subbands == 8 || common->frameInfo.mode != SBC_JOINT_STEREO) { if (common->frameInfo.mode == SBC_JOINT_STEREO) { common->frameInfo.join = *b++; } else { @@ -152,8 +148,7 @@ PRIVATE void OI_SBC_ReadScalefactors(OI_CODEC_SBC_COMMON_CONTEXT* common, */ OI_BITSTREAM_ReadInit(bs, b); } else { - OI_ASSERT(common->frameInfo.nrof_subbands == 4 && - common->frameInfo.mode == SBC_JOINT_STEREO); + OI_ASSERT(common->frameInfo.nrof_subbands == 4 && common->frameInfo.mode == SBC_JOINT_STEREO); common->frameInfo.join = HIGH(f = *b++); i = (i - 1) / 2; do { @@ -174,16 +169,14 @@ PRIVATE void OI_SBC_ReadScalefactors(OI_CODEC_SBC_COMMON_CONTEXT* common, } /** Read quantized subband samples from the input bitstream and expand them. */ -PRIVATE void OI_SBC_ReadSamples(OI_CODEC_SBC_DECODER_CONTEXT* context, - OI_BITSTREAM* global_bs) { +PRIVATE void OI_SBC_ReadSamples(OI_CODEC_SBC_DECODER_CONTEXT* context, OI_BITSTREAM* global_bs) { OI_CODEC_SBC_COMMON_CONTEXT* common = &context->common; OI_UINT nrof_blocks = common->frameInfo.nrof_blocks; int32_t* RESTRICT s = common->subdata; const uint8_t* ptr = global_bs->ptr.r; uint32_t value = global_bs->value; OI_UINT bitPtr = global_bs->bitPtr; - const OI_UINT iter_count = - common->frameInfo.nrof_channels * common->frameInfo.nrof_subbands; + const OI_UINT iter_count = common->frameInfo.nrof_channels * common->frameInfo.nrof_subbands; do { OI_UINT n; for (n = 0; n < iter_count; ++n) { diff --git a/system/embdrv/sbc/decoder/srce/decoder-sbc.c b/system/embdrv/sbc/decoder/srce/decoder-sbc.c index 8080d3b3ddf..4b3b4a70c43 100644 --- a/system/embdrv/sbc/decoder/srce/decoder-sbc.c +++ b/system/embdrv/sbc/decoder/srce/decoder-sbc.c @@ -44,8 +44,7 @@ * set for enhanced operation using OI_CODEC_SBC_DecoderReset(), it will search * for both a standard and an enhanced syncword. */ -PRIVATE OI_STATUS FindSyncword(OI_CODEC_SBC_DECODER_CONTEXT* context, - const OI_BYTE** frameData, +PRIVATE OI_STATUS FindSyncword(OI_CODEC_SBC_DECODER_CONTEXT* context, const OI_BYTE** frameData, uint32_t* frameBytes) { if (*frameBytes == 0) { return OI_CODEC_SBC_NOT_ENOUGH_HEADER_DATA; @@ -83,8 +82,7 @@ PRIVATE OI_STATUS FindSyncword(OI_CODEC_SBC_DECODER_CONTEXT* context, /* Syncword found, *frameData points to it, and *frameBytes correctly * reflects the number of bytes available to read, including the * syncword. */ - context->common.frameInfo.enhanced = - (**frameData == OI_SBC_ENHANCED_SYNCWORD); + context->common.frameInfo.enhanced = (**frameData == OI_SBC_ENHANCED_SYNCWORD); return OI_OK; } else { /* No syncword was found anywhere in the provided input data. @@ -112,28 +110,24 @@ PRIVATE OI_STATUS FindSyncword(OI_CODEC_SBC_DECODER_CONTEXT* context, #endif // SBC_ENHANCED } -static OI_STATUS DecodeBody(OI_CODEC_SBC_DECODER_CONTEXT* context, - const OI_BYTE* bodyData, int16_t* pcmData, - uint32_t* pcmBytes, OI_BOOL allowPartial) { +static OI_STATUS DecodeBody(OI_CODEC_SBC_DECODER_CONTEXT* context, const OI_BYTE* bodyData, + int16_t* pcmData, uint32_t* pcmBytes, OI_BOOL allowPartial) { OI_BITSTREAM bs; - OI_UINT frameSamples = context->common.frameInfo.nrof_blocks * - context->common.frameInfo.nrof_subbands; + OI_UINT frameSamples = + context->common.frameInfo.nrof_blocks * context->common.frameInfo.nrof_subbands; OI_UINT decode_block_count; /* * Based on the header data, make sure that there is enough room to write the * output samples. */ - if (*pcmBytes < - (sizeof(int16_t) * frameSamples * context->common.pcmStride) && - !allowPartial) { + if (*pcmBytes < (sizeof(int16_t) * frameSamples * context->common.pcmStride) && !allowPartial) { /* If we're not allowing partial decodes, we need room for the entire * codec frame */ TRACE(("-OI_CODEC_SBC_Decode: OI_CODEC_SBC_NOT_ENOUGH_AUDIO_DATA")); return OI_CODEC_SBC_NOT_ENOUGH_AUDIO_DATA; - } else if (*pcmBytes < sizeof(int16_t) * - context->common.frameInfo.nrof_subbands * - context->common.pcmStride) { + } else if (*pcmBytes < sizeof(int16_t) * context->common.frameInfo.nrof_subbands * + context->common.pcmStride) { /* Even if we're allowing partials, we can still only decode on a frame * boundary */ return OI_CODEC_SBC_NOT_ENOUGH_AUDIO_DATA; @@ -157,8 +151,7 @@ static OI_STATUS DecodeBody(OI_CODEC_SBC_DECODER_CONTEXT* context, } if (allowPartial) { - decode_block_count = *pcmBytes / sizeof(int16_t) / - context->common.pcmStride / + decode_block_count = *pcmBytes / sizeof(int16_t) / context->common.pcmStride / context->common.frameInfo.nrof_subbands; if (decode_block_count > context->bufferedBlocks) { @@ -171,8 +164,7 @@ static OI_STATUS DecodeBody(OI_CODEC_SBC_DECODER_CONTEXT* context, TRACE(("Synthesizing frame")); { - OI_UINT start_block = - context->common.frameInfo.nrof_blocks - context->bufferedBlocks; + OI_UINT start_block = context->common.frameInfo.nrof_blocks - context->bufferedBlocks; OI_SBC_SynthFrame(context, pcmData, start_block, decode_block_count); } @@ -184,8 +176,7 @@ static OI_STATUS DecodeBody(OI_CODEC_SBC_DECODER_CONTEXT* context, /* * When decoding mono into a stride-2 array, copy pcm data to second channel */ - if (context->common.frameInfo.nrof_channels == 1 && - context->common.pcmStride == 2) { + if (context->common.frameInfo.nrof_channels == 1 && context->common.pcmStride == 2) { OI_UINT i; for (i = 0; i < frameSamples; ++i) { pcmData[2 * i + 1] = pcmData[2 * i]; @@ -203,10 +194,9 @@ static OI_STATUS DecodeBody(OI_CODEC_SBC_DECODER_CONTEXT* context, } } -PRIVATE OI_STATUS internal_DecodeRaw(OI_CODEC_SBC_DECODER_CONTEXT* context, - uint8_t bitpool, const OI_BYTE** frameData, - uint32_t* frameBytes, int16_t* pcmData, - uint32_t* pcmBytes) { +PRIVATE OI_STATUS internal_DecodeRaw(OI_CODEC_SBC_DECODER_CONTEXT* context, uint8_t bitpool, + const OI_BYTE** frameData, uint32_t* frameBytes, + int16_t* pcmData, uint32_t* pcmBytes) { OI_STATUS status; OI_UINT bodyLen; @@ -220,8 +210,7 @@ PRIVATE OI_STATUS internal_DecodeRaw(OI_CODEC_SBC_DECODER_CONTEXT* context, /* * Compute the frame length and check we have enough frame data to proceed */ - bodyLen = OI_CODEC_SBC_CalculateFramelen(&context->common.frameInfo) - - SBC_HEADER_LEN; + bodyLen = OI_CODEC_SBC_CalculateFramelen(&context->common.frameInfo) - SBC_HEADER_LEN; if (*frameBytes < bodyLen) { TRACE(("-OI_CODEC_SBC_Decode: OI_CODEC_SBC_NOT_ENOUGH_BODY_DATA")); return OI_CODEC_SBC_NOT_ENOUGH_BODY_DATA; @@ -242,17 +231,14 @@ PRIVATE OI_STATUS internal_DecodeRaw(OI_CODEC_SBC_DECODER_CONTEXT* context, return status; } -OI_STATUS OI_CODEC_SBC_DecoderReset(OI_CODEC_SBC_DECODER_CONTEXT* context, - uint32_t* decoderData, - uint32_t decoderDataBytes, - uint8_t maxChannels, uint8_t pcmStride, - OI_BOOL enhanced) { - return internal_DecoderReset(context, decoderData, decoderDataBytes, - maxChannels, pcmStride, enhanced); +OI_STATUS OI_CODEC_SBC_DecoderReset(OI_CODEC_SBC_DECODER_CONTEXT* context, uint32_t* decoderData, + uint32_t decoderDataBytes, uint8_t maxChannels, + uint8_t pcmStride, OI_BOOL enhanced) { + return internal_DecoderReset(context, decoderData, decoderDataBytes, maxChannels, pcmStride, + enhanced); } -OI_STATUS OI_CODEC_SBC_DecoderConfigureMSbc( - OI_CODEC_SBC_DECODER_CONTEXT* context) { +OI_STATUS OI_CODEC_SBC_DecoderConfigureMSbc(OI_CODEC_SBC_DECODER_CONTEXT* context) { context->mSbcEnabled = TRUE; context->common.frameInfo.enhanced = FALSE; context->common.frameInfo.freqIndex = SBC_FREQ_16000; @@ -267,10 +253,8 @@ OI_STATUS OI_CODEC_SBC_DecoderConfigureMSbc( return OI_OK; } -OI_STATUS OI_CODEC_SBC_DecodeFrame(OI_CODEC_SBC_DECODER_CONTEXT* context, - const OI_BYTE** frameData, - uint32_t* frameBytes, int16_t* pcmData, - uint32_t* pcmBytes) { +OI_STATUS OI_CODEC_SBC_DecodeFrame(OI_CODEC_SBC_DECODER_CONTEXT* context, const OI_BYTE** frameData, + uint32_t* frameBytes, int16_t* pcmData, uint32_t* pcmBytes) { OI_STATUS status; OI_UINT framelen; uint8_t crc; @@ -308,19 +292,17 @@ OI_STATUS OI_CODEC_SBC_DecodeFrame(OI_CODEC_SBC_DECODER_CONTEXT* context, */ if (context->limitFrameFormat && (context->common.frameInfo.subbands != context->restrictSubbands)) { - ERROR(("SBC parameters incompatible with loaded overlay")); + ERROR("SBC parameters incompatible with loaded overlay"); return OI_STATUS_INVALID_PARAMETERS; } if (context->common.frameInfo.nrof_channels > context->common.maxChannels) { - ERROR( - ("SBC parameters incompatible with number of channels specified during " - "reset")); + ERROR("SBC parameters incompatible with number of channels specified during reset"); return OI_STATUS_INVALID_PARAMETERS; } if (context->common.pcmStride < 1 || context->common.pcmStride > 2) { - ERROR(("PCM stride not set correctly during reset")); + ERROR("PCM stride not set correctly during reset"); return OI_STATUS_INVALID_PARAMETERS; } @@ -345,8 +327,7 @@ OI_STATUS OI_CODEC_SBC_DecodeFrame(OI_CODEC_SBC_DECODER_CONTEXT* context, crc = OI_SBC_CalculateChecksum(&context->common.frameInfo, *frameData); if (crc != context->common.frameInfo.crc) { - TRACE(("CRC Mismatch: calc=%02x read=%02x\n", crc, - context->common.frameInfo.crc)); + TRACE(("CRC Mismatch: calc=%02x read=%02x\n", crc, context->common.frameInfo.crc)); TRACE(("-OI_CODEC_SBC_DecodeFrame: OI_CODEC_SBC_CHECKSUM_MISMATCH")); return OI_CODEC_SBC_CHECKSUM_MISMATCH; } @@ -356,15 +337,12 @@ OI_STATUS OI_CODEC_SBC_DecodeFrame(OI_CODEC_SBC_DECODER_CONTEXT* context, */ if ((context->common.frameInfo.bitpool < SBC_MIN_BITPOOL) && !context->common.frameInfo.enhanced) { - ERROR(("Bitpool too small: %d (must be >= 2)", - context->common.frameInfo.bitpool)); + ERROR(("Bitpool too small: %d (must be >= 2)", context->common.frameInfo.bitpool)); return OI_STATUS_INVALID_PARAMETERS; } - if (context->common.frameInfo.bitpool > - OI_SBC_MaxBitpool(&context->common.frameInfo)) { - ERROR(("Bitpool too large: %d (must be <= %ld)", - context->common.frameInfo.bitpool, - OI_SBC_MaxBitpool(&context->common.frameInfo))); + if (context->common.frameInfo.bitpool > OI_SBC_MaxBitpool(&context->common.frameInfo)) { + ERROR(("Bitpool too large: %d (must be <= %ld)", context->common.frameInfo.bitpool, + OI_SBC_MaxBitpool(&context->common.frameInfo))); return OI_STATUS_INVALID_PARAMETERS; } @@ -373,8 +351,7 @@ OI_STATUS OI_CODEC_SBC_DecodeFrame(OI_CODEC_SBC_DECODER_CONTEXT* context, * stream, so pass FALSE to decode body to have it enforce the old rule that * you have to decode a whole packet at a time. */ - status = DecodeBody(context, *frameData + SBC_HEADER_LEN, pcmData, pcmBytes, - FALSE); + status = DecodeBody(context, *frameData + SBC_HEADER_LEN, pcmData, pcmBytes, FALSE); if (OI_SUCCESS(status)) { *frameData += framelen; *frameBytes -= framelen; @@ -389,8 +366,7 @@ OI_STATUS OI_CODEC_SBC_DecodeFrame(OI_CODEC_SBC_DECODER_CONTEXT* context, return status; } -OI_STATUS OI_CODEC_SBC_SkipFrame(OI_CODEC_SBC_DECODER_CONTEXT* context, - const OI_BYTE** frameData, +OI_STATUS OI_CODEC_SBC_SkipFrame(OI_CODEC_SBC_DECODER_CONTEXT* context, const OI_BYTE** frameData, uint32_t* frameBytes) { OI_STATUS status; OI_UINT framelen; @@ -405,8 +381,7 @@ OI_STATUS OI_CODEC_SBC_SkipFrame(OI_CODEC_SBC_DECODER_CONTEXT* context, return OI_CODEC_SBC_NOT_ENOUGH_HEADER_DATA; } OI_SBC_ReadHeader(&context->common, *frameData); - framelen = - OI_SBC_CalculateFrameAndHeaderlen(&context->common.frameInfo, &headerlen); + framelen = OI_SBC_CalculateFrameAndHeaderlen(&context->common.frameInfo, &headerlen); if (*frameBytes < headerlen) { return OI_CODEC_SBC_NOT_ENOUGH_HEADER_DATA; } @@ -496,8 +471,7 @@ PRIVATE void OI_SBC_ReadSamplesJoint8(OI_CODEC_SBC_DECODER_CONTEXT* context, #undef NROF_SUBBANDS } -typedef void (*READ_SAMPLES)(OI_CODEC_SBC_DECODER_CONTEXT* context, - OI_BITSTREAM* global_bs); +typedef void (*READ_SAMPLES)(OI_CODEC_SBC_DECODER_CONTEXT* context, OI_BITSTREAM* global_bs); static const READ_SAMPLES SpecializedReadSamples[] = {OI_SBC_ReadSamplesJoint4, OI_SBC_ReadSamplesJoint8}; diff --git a/system/embdrv/sbc/decoder/srce/dequant.c b/system/embdrv/sbc/decoder/srce/dequant.c index 2dccd73fe68..213561f75eb 100644 --- a/system/embdrv/sbc/decoder/srce/dequant.c +++ b/system/embdrv/sbc/decoder/srce/dequant.c @@ -118,61 +118,61 @@ #endif const uint32_t dequant_long_scaled[17] = { - 0, 0, - 0x1ee9e116, /* bits=2 0.24151243 1/3 * (1/1.38019122262781) - (0x00000008)*/ - 0x0d3fa99c, /* bits=3 0.10350533 1/7 * (1/1.38019122262781) - (0x00000013)*/ - 0x062ec69e, /* bits=4 0.04830249 1/15 * (1/1.38019122262781) - (0x00000029)*/ - 0x02fddbfa, /* bits=5 0.02337217 1/31 * (1/1.38019122262781) - (0x00000055)*/ - 0x0178d9f5, /* bits=6 0.01150059 1/63 * (1/1.38019122262781) - (0x000000ad)*/ - 0x00baf129, /* bits=7 0.00570502 1/127 * (1/1.38019122262781) - (0x0000015e)*/ - 0x005d1abe, /* bits=8 0.00284132 1/255 * (1/1.38019122262781) - (0x000002bf)*/ - 0x002e760d, /* bits=9 0.00141788 1/511 * (1/1.38019122262781) - (0x00000582)*/ - 0x00173536, /* bits=10 0.00070825 1/1023 * (1/1.38019122262781) - (0x00000b07)*/ - 0x000b9928, /* bits=11 0.00035395 1/2047 * (1/1.38019122262781) - (0x00001612)*/ - 0x0005cc37, /* bits=12 0.00017693 1/4095 * (1/1.38019122262781) - (0x00002c27)*/ - 0x0002e604, /* bits=13 0.00008846 1/8191 * (1/1.38019122262781) - (0x00005852)*/ - 0x000172fc, /* bits=14 0.00004422 1/16383 * (1/1.38019122262781) - (0x0000b0a7)*/ - 0x0000b97d, /* bits=15 0.00002211 1/32767 * (1/1.38019122262781) - (0x00016150)*/ - 0x00005cbe, /* bits=16 0.00001106 1/65535 * (1/1.38019122262781) - (0x0002c2a5)*/ + 0, 0, + 0x1ee9e116, /* bits=2 0.24151243 1/3 * (1/1.38019122262781) + (0x00000008)*/ + 0x0d3fa99c, /* bits=3 0.10350533 1/7 * (1/1.38019122262781) + (0x00000013)*/ + 0x062ec69e, /* bits=4 0.04830249 1/15 * (1/1.38019122262781) + (0x00000029)*/ + 0x02fddbfa, /* bits=5 0.02337217 1/31 * (1/1.38019122262781) + (0x00000055)*/ + 0x0178d9f5, /* bits=6 0.01150059 1/63 * (1/1.38019122262781) + (0x000000ad)*/ + 0x00baf129, /* bits=7 0.00570502 1/127 * (1/1.38019122262781) + (0x0000015e)*/ + 0x005d1abe, /* bits=8 0.00284132 1/255 * (1/1.38019122262781) + (0x000002bf)*/ + 0x002e760d, /* bits=9 0.00141788 1/511 * (1/1.38019122262781) + (0x00000582)*/ + 0x00173536, /* bits=10 0.00070825 1/1023 * (1/1.38019122262781) + (0x00000b07)*/ + 0x000b9928, /* bits=11 0.00035395 1/2047 * (1/1.38019122262781) + (0x00001612)*/ + 0x0005cc37, /* bits=12 0.00017693 1/4095 * (1/1.38019122262781) + (0x00002c27)*/ + 0x0002e604, /* bits=13 0.00008846 1/8191 * (1/1.38019122262781) + (0x00005852)*/ + 0x000172fc, /* bits=14 0.00004422 1/16383 * (1/1.38019122262781) + (0x0000b0a7)*/ + 0x0000b97d, /* bits=15 0.00002211 1/32767 * (1/1.38019122262781) + (0x00016150)*/ + 0x00005cbe, /* bits=16 0.00001106 1/65535 * (1/1.38019122262781) + (0x0002c2a5)*/ }; const uint32_t dequant_long_unscaled[17] = { - 0, 0, 0x2aaaaaab, /* bits=2 0.33333333 1/3 (0x00000005)*/ - 0x12492492, /* bits=3 0.14285714 1/7 (0x0000000e)*/ - 0x08888889, /* bits=4 0.06666667 1/15 (0x0000001d)*/ - 0x04210842, /* bits=5 0.03225806 1/31 (0x0000003e)*/ - 0x02082082, /* bits=6 0.01587302 1/63 (0x0000007e)*/ - 0x01020408, /* bits=7 0.00787402 1/127 (0x000000fe)*/ - 0x00808081, /* bits=8 0.00392157 1/255 (0x000001fd)*/ - 0x00402010, /* bits=9 0.00195695 1/511 (0x000003fe)*/ - 0x00200802, /* bits=10 0.00097752 1/1023 (0x000007fe)*/ - 0x00100200, /* bits=11 0.00048852 1/2047 (0x00000ffe)*/ - 0x00080080, /* bits=12 0.00024420 1/4095 (0x00001ffe)*/ - 0x00040020, /* bits=13 0.00012209 1/8191 (0x00003ffe)*/ - 0x00020008, /* bits=14 0.00006104 1/16383 (0x00007ffe)*/ - 0x00010002, /* bits=15 0.00003052 1/32767 (0x0000fffe)*/ - 0x00008001, /* bits=16 0.00001526 1/65535 (0x0001fffc)*/ + 0, 0, 0x2aaaaaab, /* bits=2 0.33333333 1/3 (0x00000005)*/ + 0x12492492, /* bits=3 0.14285714 1/7 (0x0000000e)*/ + 0x08888889, /* bits=4 0.06666667 1/15 (0x0000001d)*/ + 0x04210842, /* bits=5 0.03225806 1/31 (0x0000003e)*/ + 0x02082082, /* bits=6 0.01587302 1/63 (0x0000007e)*/ + 0x01020408, /* bits=7 0.00787402 1/127 (0x000000fe)*/ + 0x00808081, /* bits=8 0.00392157 1/255 (0x000001fd)*/ + 0x00402010, /* bits=9 0.00195695 1/511 (0x000003fe)*/ + 0x00200802, /* bits=10 0.00097752 1/1023 (0x000007fe)*/ + 0x00100200, /* bits=11 0.00048852 1/2047 (0x00000ffe)*/ + 0x00080080, /* bits=12 0.00024420 1/4095 (0x00001ffe)*/ + 0x00040020, /* bits=13 0.00012209 1/8191 (0x00003ffe)*/ + 0x00020008, /* bits=14 0.00006104 1/16383 (0x00007ffe)*/ + 0x00010002, /* bits=15 0.00003052 1/32767 (0x0000fffe)*/ + 0x00008001, /* bits=16 0.00001526 1/65535 (0x0001fffc)*/ }; /** Scales x by y bits to the right, adding a rounding factor. */ #ifndef SCALE -#define SCALE(x, y) (((x) + (1 << ((y)-1))) >> (y)) +#define SCALE(x, y) (((x) + (1 << ((y) - 1))) >> (y)) #endif #ifdef DEBUG_DEQUANTIZATION @@ -180,8 +180,7 @@ const uint32_t dequant_long_unscaled[17] = { #include INLINE float dequant_float(uint32_t raw, OI_UINT scale_factor, OI_UINT bits) { - float result = (1 << (scale_factor + 1)) * - ((raw * 2.0f + 1.0f) / ((1 << bits) - 1.0f) - 1.0f); + float result = (1 << (scale_factor + 1)) * ((raw * 2.0f + 1.0f) / ((1 << bits) - 1.0f) - 1.0f); result /= SBC_DEQUANT_SCALING_FACTOR; @@ -197,8 +196,7 @@ INLINE float dequant_float(uint32_t raw, OI_UINT scale_factor, OI_UINT bits) { #endif -INLINE int32_t OI_SBC_Dequant(uint32_t raw, OI_UINT scale_factor, - OI_UINT bits) { +INLINE int32_t OI_SBC_Dequant(uint32_t raw, OI_UINT scale_factor, OI_UINT bits) { uint32_t d; int32_t result; @@ -236,8 +234,7 @@ INLINE int32_t OI_SBC_Dequant(uint32_t raw, OI_UINT scale_factor, * the encoder is conformant) the result will fit a 24 bit fixed point signed * value.*/ -INLINE int32_t OI_SBC_Dequant_Unscaled(uint32_t raw, OI_UINT scale_factor, - OI_UINT bits) { +INLINE int32_t OI_SBC_Dequant_Unscaled(uint32_t raw, OI_UINT scale_factor, OI_UINT bits) { uint32_t d; int32_t result; diff --git a/system/embdrv/sbc/decoder/srce/framing-sbc.c b/system/embdrv/sbc/decoder/srce/framing-sbc.c index 9aea461f3b5..633c0803e5c 100644 --- a/system/embdrv/sbc/decoder/srce/framing-sbc.c +++ b/system/embdrv/sbc/decoder/srce/framing-sbc.c @@ -31,14 +31,13 @@ #include "oi_codec_sbc_private.h" -const OI_CHAR* const OI_CODEC_SBC_FreqText[] = { - "SBC_FREQ_16000", "SBC_FREQ_32000", "SBC_FREQ_44100", "SBC_FREQ_48000"}; -const OI_CHAR* const OI_CODEC_SBC_ModeText[] = { - "SBC_MONO", "SBC_DUAL_CHANNEL", "SBC_STEREO", "SBC_JOINT_STEREO"}; -const OI_CHAR* const OI_CODEC_SBC_SubbandsText[] = {"SBC_SUBBANDS_4", - "SBC_SUBBANDS_8"}; -const OI_CHAR* const OI_CODEC_SBC_BlocksText[] = { - "SBC_BLOCKS_4", "SBC_BLOCKS_8", "SBC_BLOCKS_12", "SBC_BLOCKS_16"}; +const OI_CHAR* const OI_CODEC_SBC_FreqText[] = {"SBC_FREQ_16000", "SBC_FREQ_32000", + "SBC_FREQ_44100", "SBC_FREQ_48000"}; +const OI_CHAR* const OI_CODEC_SBC_ModeText[] = {"SBC_MONO", "SBC_DUAL_CHANNEL", "SBC_STEREO", + "SBC_JOINT_STEREO"}; +const OI_CHAR* const OI_CODEC_SBC_SubbandsText[] = {"SBC_SUBBANDS_4", "SBC_SUBBANDS_8"}; +const OI_CHAR* const OI_CODEC_SBC_BlocksText[] = {"SBC_BLOCKS_4", "SBC_BLOCKS_8", "SBC_BLOCKS_12", + "SBC_BLOCKS_16"}; const OI_CHAR* const OI_CODEC_SBC_AllocText[] = {"SBC_LOUDNESS", "SBC_SNR"}; #ifdef OI_DEBUG diff --git a/system/embdrv/sbc/decoder/srce/framing.c b/system/embdrv/sbc/decoder/srce/framing.c index d581bdb6ef0..ca83b7ab8dc 100644 --- a/system/embdrv/sbc/decoder/srce/framing.c +++ b/system/embdrv/sbc/decoder/srce/framing.c @@ -51,50 +51,42 @@ Checksum and header-related functions. #ifdef USE_WIDE_CRC /* Save space if a char is 16 bits, such as on the C54x */ const OI_BYTE crc8_wide[128] = { - 0x001d, 0x3a27, 0x7469, 0x4e53, 0xe8f5, 0xd2cf, 0x9c81, 0xa6bb, 0xcdd0, - 0xf7ea, 0xb9a4, 0x839e, 0x2538, 0x1f02, 0x514c, 0x6b76, 0x879a, 0xbda0, - 0xf3ee, 0xc9d4, 0x6f72, 0x5548, 0x1b06, 0x213c, 0x4a57, 0x706d, 0x3e23, - 0x0419, 0xa2bf, 0x9885, 0xd6cb, 0xecf1, 0x130e, 0x2934, 0x677a, 0x5d40, - 0xfbe6, 0xc1dc, 0x8f92, 0xb5a8, 0xdec3, 0xe4f9, 0xaab7, 0x908d, 0x362b, - 0x0c11, 0x425f, 0x7865, 0x9489, 0xaeb3, 0xe0fd, 0xdac7, 0x7c61, 0x465b, - 0x0815, 0x322f, 0x5944, 0x637e, 0x2d30, 0x170a, 0xb1ac, 0x8b96, 0xc5d8, - 0xffe2, 0x263b, 0x1c01, 0x524f, 0x6875, 0xced3, 0xf4e9, 0xbaa7, 0x809d, - 0xebf6, 0xd1cc, 0x9f82, 0xa5b8, 0x031e, 0x3924, 0x776a, 0x4d50, 0xa1bc, - 0x9b86, 0xd5c8, 0xeff2, 0x4954, 0x736e, 0x3d20, 0x071a, 0x6c71, 0x564b, - 0x1805, 0x223f, 0x8499, 0xbea3, 0xf0ed, 0xcad7, 0x3528, 0x0f12, 0x415c, - 0x7b66, 0xddc0, 0xe7fa, 0xa9b4, 0x938e, 0xf8e5, 0xc2df, 0x8c91, 0xb6ab, - 0x100d, 0x2a37, 0x6479, 0x5e43, 0xb2af, 0x8895, 0xc6db, 0xfce1, 0x5a47, - 0x607d, 0x2e33, 0x1409, 0x7f62, 0x4558, 0x0b16, 0x312c, 0x978a, 0xadb0, - 0xe3fe, 0xd9c4, + 0x001d, 0x3a27, 0x7469, 0x4e53, 0xe8f5, 0xd2cf, 0x9c81, 0xa6bb, 0xcdd0, 0xf7ea, 0xb9a4, + 0x839e, 0x2538, 0x1f02, 0x514c, 0x6b76, 0x879a, 0xbda0, 0xf3ee, 0xc9d4, 0x6f72, 0x5548, + 0x1b06, 0x213c, 0x4a57, 0x706d, 0x3e23, 0x0419, 0xa2bf, 0x9885, 0xd6cb, 0xecf1, 0x130e, + 0x2934, 0x677a, 0x5d40, 0xfbe6, 0xc1dc, 0x8f92, 0xb5a8, 0xdec3, 0xe4f9, 0xaab7, 0x908d, + 0x362b, 0x0c11, 0x425f, 0x7865, 0x9489, 0xaeb3, 0xe0fd, 0xdac7, 0x7c61, 0x465b, 0x0815, + 0x322f, 0x5944, 0x637e, 0x2d30, 0x170a, 0xb1ac, 0x8b96, 0xc5d8, 0xffe2, 0x263b, 0x1c01, + 0x524f, 0x6875, 0xced3, 0xf4e9, 0xbaa7, 0x809d, 0xebf6, 0xd1cc, 0x9f82, 0xa5b8, 0x031e, + 0x3924, 0x776a, 0x4d50, 0xa1bc, 0x9b86, 0xd5c8, 0xeff2, 0x4954, 0x736e, 0x3d20, 0x071a, + 0x6c71, 0x564b, 0x1805, 0x223f, 0x8499, 0xbea3, 0xf0ed, 0xcad7, 0x3528, 0x0f12, 0x415c, + 0x7b66, 0xddc0, 0xe7fa, 0xa9b4, 0x938e, 0xf8e5, 0xc2df, 0x8c91, 0xb6ab, 0x100d, 0x2a37, + 0x6479, 0x5e43, 0xb2af, 0x8895, 0xc6db, 0xfce1, 0x5a47, 0x607d, 0x2e33, 0x1409, 0x7f62, + 0x4558, 0x0b16, 0x312c, 0x978a, 0xadb0, 0xe3fe, 0xd9c4, }; #elif defined(USE_NIBBLEWISE_CRC) -const OI_BYTE crc8_narrow[16] = {0x00, 0x1d, 0x3a, 0x27, 0x74, 0x69, - 0x4e, 0x53, 0xe8, 0xf5, 0xd2, 0xcf, - 0x9c, 0x81, 0xa6, 0xbb}; +const OI_BYTE crc8_narrow[16] = {0x00, 0x1d, 0x3a, 0x27, 0x74, 0x69, 0x4e, 0x53, + 0xe8, 0xf5, 0xd2, 0xcf, 0x9c, 0x81, 0xa6, 0xbb}; #else const OI_BYTE crc8_narrow[256] = { - 0x00, 0x1d, 0x3a, 0x27, 0x74, 0x69, 0x4e, 0x53, 0xe8, 0xf5, 0xd2, 0xcf, - 0x9c, 0x81, 0xa6, 0xbb, 0xcd, 0xd0, 0xf7, 0xea, 0xb9, 0xa4, 0x83, 0x9e, - 0x25, 0x38, 0x1f, 0x02, 0x51, 0x4c, 0x6b, 0x76, 0x87, 0x9a, 0xbd, 0xa0, - 0xf3, 0xee, 0xc9, 0xd4, 0x6f, 0x72, 0x55, 0x48, 0x1b, 0x06, 0x21, 0x3c, - 0x4a, 0x57, 0x70, 0x6d, 0x3e, 0x23, 0x04, 0x19, 0xa2, 0xbf, 0x98, 0x85, - 0xd6, 0xcb, 0xec, 0xf1, 0x13, 0x0e, 0x29, 0x34, 0x67, 0x7a, 0x5d, 0x40, - 0xfb, 0xe6, 0xc1, 0xdc, 0x8f, 0x92, 0xb5, 0xa8, 0xde, 0xc3, 0xe4, 0xf9, - 0xaa, 0xb7, 0x90, 0x8d, 0x36, 0x2b, 0x0c, 0x11, 0x42, 0x5f, 0x78, 0x65, - 0x94, 0x89, 0xae, 0xb3, 0xe0, 0xfd, 0xda, 0xc7, 0x7c, 0x61, 0x46, 0x5b, - 0x08, 0x15, 0x32, 0x2f, 0x59, 0x44, 0x63, 0x7e, 0x2d, 0x30, 0x17, 0x0a, - 0xb1, 0xac, 0x8b, 0x96, 0xc5, 0xd8, 0xff, 0xe2, 0x26, 0x3b, 0x1c, 0x01, - 0x52, 0x4f, 0x68, 0x75, 0xce, 0xd3, 0xf4, 0xe9, 0xba, 0xa7, 0x80, 0x9d, - 0xeb, 0xf6, 0xd1, 0xcc, 0x9f, 0x82, 0xa5, 0xb8, 0x03, 0x1e, 0x39, 0x24, - 0x77, 0x6a, 0x4d, 0x50, 0xa1, 0xbc, 0x9b, 0x86, 0xd5, 0xc8, 0xef, 0xf2, - 0x49, 0x54, 0x73, 0x6e, 0x3d, 0x20, 0x07, 0x1a, 0x6c, 0x71, 0x56, 0x4b, - 0x18, 0x05, 0x22, 0x3f, 0x84, 0x99, 0xbe, 0xa3, 0xf0, 0xed, 0xca, 0xd7, - 0x35, 0x28, 0x0f, 0x12, 0x41, 0x5c, 0x7b, 0x66, 0xdd, 0xc0, 0xe7, 0xfa, - 0xa9, 0xb4, 0x93, 0x8e, 0xf8, 0xe5, 0xc2, 0xdf, 0x8c, 0x91, 0xb6, 0xab, - 0x10, 0x0d, 0x2a, 0x37, 0x64, 0x79, 0x5e, 0x43, 0xb2, 0xaf, 0x88, 0x95, - 0xc6, 0xdb, 0xfc, 0xe1, 0x5a, 0x47, 0x60, 0x7d, 0x2e, 0x33, 0x14, 0x09, - 0x7f, 0x62, 0x45, 0x58, 0x0b, 0x16, 0x31, 0x2c, 0x97, 0x8a, 0xad, 0xb0, - 0xe3, 0xfe, 0xd9, 0xc4}; + 0x00, 0x1d, 0x3a, 0x27, 0x74, 0x69, 0x4e, 0x53, 0xe8, 0xf5, 0xd2, 0xcf, 0x9c, 0x81, 0xa6, + 0xbb, 0xcd, 0xd0, 0xf7, 0xea, 0xb9, 0xa4, 0x83, 0x9e, 0x25, 0x38, 0x1f, 0x02, 0x51, 0x4c, + 0x6b, 0x76, 0x87, 0x9a, 0xbd, 0xa0, 0xf3, 0xee, 0xc9, 0xd4, 0x6f, 0x72, 0x55, 0x48, 0x1b, + 0x06, 0x21, 0x3c, 0x4a, 0x57, 0x70, 0x6d, 0x3e, 0x23, 0x04, 0x19, 0xa2, 0xbf, 0x98, 0x85, + 0xd6, 0xcb, 0xec, 0xf1, 0x13, 0x0e, 0x29, 0x34, 0x67, 0x7a, 0x5d, 0x40, 0xfb, 0xe6, 0xc1, + 0xdc, 0x8f, 0x92, 0xb5, 0xa8, 0xde, 0xc3, 0xe4, 0xf9, 0xaa, 0xb7, 0x90, 0x8d, 0x36, 0x2b, + 0x0c, 0x11, 0x42, 0x5f, 0x78, 0x65, 0x94, 0x89, 0xae, 0xb3, 0xe0, 0xfd, 0xda, 0xc7, 0x7c, + 0x61, 0x46, 0x5b, 0x08, 0x15, 0x32, 0x2f, 0x59, 0x44, 0x63, 0x7e, 0x2d, 0x30, 0x17, 0x0a, + 0xb1, 0xac, 0x8b, 0x96, 0xc5, 0xd8, 0xff, 0xe2, 0x26, 0x3b, 0x1c, 0x01, 0x52, 0x4f, 0x68, + 0x75, 0xce, 0xd3, 0xf4, 0xe9, 0xba, 0xa7, 0x80, 0x9d, 0xeb, 0xf6, 0xd1, 0xcc, 0x9f, 0x82, + 0xa5, 0xb8, 0x03, 0x1e, 0x39, 0x24, 0x77, 0x6a, 0x4d, 0x50, 0xa1, 0xbc, 0x9b, 0x86, 0xd5, + 0xc8, 0xef, 0xf2, 0x49, 0x54, 0x73, 0x6e, 0x3d, 0x20, 0x07, 0x1a, 0x6c, 0x71, 0x56, 0x4b, + 0x18, 0x05, 0x22, 0x3f, 0x84, 0x99, 0xbe, 0xa3, 0xf0, 0xed, 0xca, 0xd7, 0x35, 0x28, 0x0f, + 0x12, 0x41, 0x5c, 0x7b, 0x66, 0xdd, 0xc0, 0xe7, 0xfa, 0xa9, 0xb4, 0x93, 0x8e, 0xf8, 0xe5, + 0xc2, 0xdf, 0x8c, 0x91, 0xb6, 0xab, 0x10, 0x0d, 0x2a, 0x37, 0x64, 0x79, 0x5e, 0x43, 0xb2, + 0xaf, 0x88, 0x95, 0xc6, 0xdb, 0xfc, 0xe1, 0x5a, 0x47, 0x60, 0x7d, 0x2e, 0x33, 0x14, 0x09, + 0x7f, 0x62, 0x45, 0x58, 0x0b, 0x16, 0x31, 0x2c, 0x97, 0x8a, 0xad, 0xb0, 0xe3, 0xfe, 0xd9, + 0xc4}; #endif #if defined(OI_DEBUG) || defined(PRINT_SAMPLES) || defined(PRINT_SCALEFACTORS) @@ -144,16 +136,13 @@ INLINE uint8_t crc_iterate(uint8_t crc, uint8_t next) { } #else // USE_NIBBLEWISE_CRC -INLINE uint8_t crc_iterate(uint8_t crc, uint8_t next) { - return crc8_narrow[crc ^ next]; -} +INLINE uint8_t crc_iterate(uint8_t crc, uint8_t next) { return crc8_narrow[crc ^ next]; } #endif // USE_NIBBLEWISE_CRC #endif // USE_WIDE_CRC -PRIVATE uint8_t OI_SBC_CalculateChecksum(OI_CODEC_SBC_FRAME_INFO* frame, - OI_BYTE const* data) { +PRIVATE uint8_t OI_SBC_CalculateChecksum(OI_CODEC_SBC_FRAME_INFO* frame, OI_BYTE const* data) { OI_UINT i; uint8_t crc = 0x0f; /* Count is the number of whole bytes subject to CRC. Actually, it's one @@ -207,8 +196,7 @@ void OI_SBC_ExpandFrameFields(OI_CODEC_SBC_FRAME_INFO* frame) { #if defined(USE_PLATFORM_MEMMOVE) || defined(USE_PLATFORM_MEMCPY) #include #endif -PRIVATE void shift_buffer(SBC_BUFFER_T* dest, SBC_BUFFER_T* src, - OI_UINT wordCount) { +PRIVATE void shift_buffer(SBC_BUFFER_T* dest, SBC_BUFFER_T* src, OI_UINT wordCount) { #ifdef USE_PLATFORM_MEMMOVE memmove(dest, src, wordCount * sizeof(SBC_BUFFER_T)); #elif defined(USE_PLATFORM_MEMCPY) diff --git a/system/embdrv/sbc/decoder/srce/oi_codec_version.c b/system/embdrv/sbc/decoder/srce/oi_codec_version.c index 70c005f18ce..d3fd41636d7 100644 --- a/system/embdrv/sbc/decoder/srce/oi_codec_version.c +++ b/system/embdrv/sbc/decoder/srce/oi_codec_version.c @@ -40,11 +40,11 @@ version number of the eSBC codec /** Version string for the BLUEmagic 3.0 protocol stack and profiles */ PRIVATE OI_CHAR* const codecVersion = - "v1.5" + "v1.5" #ifdef OI_SBC_EVAL - " (Evaluation version)" + " (Evaluation version)" #endif - ; + ; /* This function returns the version string for the BLUEmagic 3.0 protocol stack and profiles */ diff --git a/system/embdrv/sbc/decoder/srce/synthesis-8-generated.c b/system/embdrv/sbc/decoder/srce/synthesis-8-generated.c index 1656dc44270..5732a9da43f 100644 --- a/system/embdrv/sbc/decoder/srce/synthesis-8-generated.c +++ b/system/embdrv/sbc/decoder/srce/synthesis-8-generated.c @@ -47,8 +47,7 @@ #define MUL_16S_16S(_x, _y) ((_x) * (_y)) -PRIVATE void SynthWindow80_generated(int16_t* pcm, - SBC_BUFFER_T const* RESTRICT buffer, +PRIVATE void SynthWindow80_generated(int16_t* pcm, SBC_BUFFER_T const* RESTRICT buffer, OI_UINT strideShift) { int32_t pcm_a, pcm_b; /* 1 - stage 0 */ pcm_b = 0; diff --git a/system/embdrv/sbc/decoder/srce/synthesis-dct8.c b/system/embdrv/sbc/decoder/srce/synthesis-dct8.c index 2dfe753442b..23f25bac109 100644 --- a/system/embdrv/sbc/decoder/srce/synthesis-dct8.c +++ b/system/embdrv/sbc/decoder/srce/synthesis-dct8.c @@ -48,7 +48,7 @@ /** Scales x by y bits to the right, adding a rounding factor. */ #ifndef SCALE -#define SCALE(x, y) (((x) + (1 << ((y)-1))) >> (y)) +#define SCALE(x, y) (((x) + (1 << ((y) - 1))) >> (y)) #endif /** @@ -81,8 +81,7 @@ INLINE int32_t default_mul_32s_32s_hi(int32_t u, int32_t v) { #ifdef DEBUG_DCT PRIVATE void float_dct2_8(float* RESTRICT out, int32_t const* RESTRICT in) { -#define FIX(x, bits) \ - (((int)floor(0.5f + ((x) * ((float)(1 << bits))))) / ((float)(1 << bits))) +#define FIX(x, bits) (((int)floor(0.5f + ((x) * ((float)(1 << bits))))) / ((float)(1 << bits))) #define FLOAT_BUTTERFLY(x, y) \ x += y; \ y = x - (y * 2); \ diff --git a/system/embdrv/sbc/decoder/srce/synthesis-sbc.c b/system/embdrv/sbc/decoder/srce/synthesis-sbc.c index a5111ae3a7a..ee2ca1f8043 100644 --- a/system/embdrv/sbc/decoder/srce/synthesis-sbc.c +++ b/system/embdrv/sbc/decoder/srce/synthesis-sbc.c @@ -166,27 +166,27 @@ The output samples X[0..7] are defined as sums of W: #include "oi_codec_sbc_private.h" const int32_t dec_window_4[21] = { - 0, /* +0.00000000E+00 */ - 97, /* +5.36548976E-04 */ - 270, /* +1.49188357E-03 */ - 495, /* +2.73370904E-03 */ - 694, /* +3.83720193E-03 */ - 704, /* +3.89205149E-03 */ - 338, /* +1.86581691E-03 */ - -554, /* -3.06012286E-03 */ - 1974, /* +1.09137620E-02 */ - 3697, /* +2.04385087E-02 */ - 5224, /* +2.88757392E-02 */ - 5824, /* +3.21939290E-02 */ - 4681, /* +2.58767811E-02 */ - 1109, /* +6.13245186E-03 */ - -5214, /* -2.88217274E-02 */ - -14047, /* -7.76463494E-02 */ - 24529, /* +1.35593274E-01 */ - 35274, /* +1.94987841E-01 */ - 44618, /* +2.46636662E-01 */ - 50984, /* +2.81828203E-01 */ - 53243, /* +2.94315332E-01 */ + 0, /* +0.00000000E+00 */ + 97, /* +5.36548976E-04 */ + 270, /* +1.49188357E-03 */ + 495, /* +2.73370904E-03 */ + 694, /* +3.83720193E-03 */ + 704, /* +3.89205149E-03 */ + 338, /* +1.86581691E-03 */ + -554, /* -3.06012286E-03 */ + 1974, /* +1.09137620E-02 */ + 3697, /* +2.04385087E-02 */ + 5224, /* +2.88757392E-02 */ + 5824, /* +3.21939290E-02 */ + 4681, /* +2.58767811E-02 */ + 1109, /* +6.13245186E-03 */ + -5214, /* -2.88217274E-02 */ + -14047, /* -7.76463494E-02 */ + 24529, /* +1.35593274E-01 */ + 35274, /* +1.94987841E-01 */ + 44618, /* +2.46636662E-01 */ + 50984, /* +2.81828203E-01 */ + 53243, /* +2.94315332E-01 */ }; #define DCTII_4_K06_FIX (11585) /* S1.14 11585 0.707107*/ @@ -200,7 +200,7 @@ const int32_t dec_window_4[21] = { /** Scales x by y bits to the right, adding a rounding factor. */ #ifndef SCALE -#define SCALE(x, y) (((x) + (1 << ((y)-1))) >> (y)) +#define SCALE(x, y) (((x) + (1 << ((y) - 1))) >> (y)) #endif #ifndef CLIP_INT16 @@ -243,16 +243,14 @@ INLINE int32_t default_mul_16s_32s_hi(int16_t u, int32_t v) { #define LONG_MULT_DCT(K, sample) (MUL_16S_32S_HI(K, sample) << 2) -PRIVATE void SynthWindow80_generated(int16_t* pcm, - SBC_BUFFER_T const* RESTRICT buffer, +PRIVATE void SynthWindow80_generated(int16_t* pcm, SBC_BUFFER_T const* RESTRICT buffer, OI_UINT strideShift); -PRIVATE void SynthWindow112_generated(int16_t* pcm, - SBC_BUFFER_T const* RESTRICT buffer, +PRIVATE void SynthWindow112_generated(int16_t* pcm, SBC_BUFFER_T const* RESTRICT buffer, OI_UINT strideShift); PRIVATE void dct2_8(SBC_BUFFER_T* RESTRICT out, int32_t const* RESTRICT x); -typedef void (*SYNTH_FRAME)(OI_CODEC_SBC_DECODER_CONTEXT* context, int16_t* pcm, - OI_UINT blkstart, OI_UINT blkcount); +typedef void (*SYNTH_FRAME)(OI_CODEC_SBC_DECODER_CONTEXT* context, int16_t* pcm, OI_UINT blkstart, + OI_UINT blkcount); #ifndef COPY_BACKWARD_32BIT_ALIGNED_72_HALFWORDS #define COPY_BACKWARD_32BIT_ALIGNED_72_HALFWORDS(dest, src) \ @@ -273,9 +271,8 @@ typedef void (*SYNTH_FRAME)(OI_CODEC_SBC_DECODER_CONTEXT* context, int16_t* pcm, #define SYNTH112 SynthWindow112_generated #endif -PRIVATE void OI_SBC_SynthFrame_80(OI_CODEC_SBC_DECODER_CONTEXT* context, - int16_t* pcm, OI_UINT blkstart, - OI_UINT blkcount) { +PRIVATE void OI_SBC_SynthFrame_80(OI_CODEC_SBC_DECODER_CONTEXT* context, int16_t* pcm, + OI_UINT blkstart, OI_UINT blkcount) { OI_UINT blk; OI_UINT ch; OI_UINT nrof_channels = context->common.frameInfo.nrof_channels; @@ -287,14 +284,12 @@ PRIVATE void OI_SBC_SynthFrame_80(OI_CODEC_SBC_DECODER_CONTEXT* context, for (blk = blkstart; blk < blkstop; blk++) { if (offset == 0) { COPY_BACKWARD_32BIT_ALIGNED_72_HALFWORDS( - context->common.filterBuffer[0] + context->common.filterBufferLen - - 72, - context->common.filterBuffer[0]); + context->common.filterBuffer[0] + context->common.filterBufferLen - 72, + context->common.filterBuffer[0]); if (nrof_channels == 2) { COPY_BACKWARD_32BIT_ALIGNED_72_HALFWORDS( - context->common.filterBuffer[1] + context->common.filterBufferLen - - 72, - context->common.filterBuffer[1]); + context->common.filterBuffer[1] + context->common.filterBufferLen - 72, + context->common.filterBuffer[1]); } offset = context->common.filterBufferLen - 80; } else { @@ -303,8 +298,7 @@ PRIVATE void OI_SBC_SynthFrame_80(OI_CODEC_SBC_DECODER_CONTEXT* context, for (ch = 0; ch < nrof_channels; ch++) { DCT2_8(context->common.filterBuffer[ch] + offset, s); - SYNTH80(pcm + ch, context->common.filterBuffer[ch] + offset, - pcmStrideShift); + SYNTH80(pcm + ch, context->common.filterBuffer[ch] + offset, pcmStrideShift); s += 8; } pcm += (8 << pcmStrideShift); @@ -312,9 +306,8 @@ PRIVATE void OI_SBC_SynthFrame_80(OI_CODEC_SBC_DECODER_CONTEXT* context, context->common.filterBufferOffset = offset; } -PRIVATE void OI_SBC_SynthFrame_4SB(OI_CODEC_SBC_DECODER_CONTEXT* context, - int16_t* pcm, OI_UINT blkstart, - OI_UINT blkcount) { +PRIVATE void OI_SBC_SynthFrame_4SB(OI_CODEC_SBC_DECODER_CONTEXT* context, int16_t* pcm, + OI_UINT blkstart, OI_UINT blkcount) { OI_UINT blk; OI_UINT ch; OI_UINT nrof_channels = context->common.frameInfo.nrof_channels; @@ -326,14 +319,12 @@ PRIVATE void OI_SBC_SynthFrame_4SB(OI_CODEC_SBC_DECODER_CONTEXT* context, for (blk = blkstart; blk < blkstop; blk++) { if (offset == 0) { COPY_BACKWARD_32BIT_ALIGNED_72_HALFWORDS( - context->common.filterBuffer[0] + context->common.filterBufferLen - - 72, - context->common.filterBuffer[0]); + context->common.filterBuffer[0] + context->common.filterBufferLen - 72, + context->common.filterBuffer[0]); if (nrof_channels == 2) { COPY_BACKWARD_32BIT_ALIGNED_72_HALFWORDS( - context->common.filterBuffer[1] + context->common.filterBufferLen - - 72, - context->common.filterBuffer[1]); + context->common.filterBuffer[1] + context->common.filterBufferLen - 72, + context->common.filterBuffer[1]); } offset = context->common.filterBufferLen - 80; } else { @@ -342,7 +333,7 @@ PRIVATE void OI_SBC_SynthFrame_4SB(OI_CODEC_SBC_DECODER_CONTEXT* context, for (ch = 0; ch < nrof_channels; ch++) { cosineModulateSynth4(context->common.filterBuffer[ch] + offset, s); SynthWindow40_int32_int32_symmetry_with_sum( - pcm + ch, context->common.filterBuffer[ch] + offset, pcmStrideShift); + pcm + ch, context->common.filterBuffer[ch] + offset, pcmStrideShift); s += 4; } pcm += (4 << pcmStrideShift); @@ -352,9 +343,8 @@ PRIVATE void OI_SBC_SynthFrame_4SB(OI_CODEC_SBC_DECODER_CONTEXT* context, #ifdef SBC_ENHANCED -PRIVATE void OI_SBC_SynthFrame_Enhanced(OI_CODEC_SBC_DECODER_CONTEXT* context, - int16_t* pcm, OI_UINT blkstart, - OI_UINT blkcount) { +PRIVATE void OI_SBC_SynthFrame_Enhanced(OI_CODEC_SBC_DECODER_CONTEXT* context, int16_t* pcm, + OI_UINT blkstart, OI_UINT blkcount) { OI_UINT blk; OI_UINT ch; OI_UINT nrof_channels = context->common.frameInfo.nrof_channels; @@ -366,14 +356,12 @@ PRIVATE void OI_SBC_SynthFrame_Enhanced(OI_CODEC_SBC_DECODER_CONTEXT* context, for (blk = blkstart; blk < blkstop; blk++) { if (offset == 0) { COPY_BACKWARD_32BIT_ALIGNED_104_HALFWORDS( - context->common.filterBuffer[0] + context->common.filterBufferLen - - 104, - context->common.filterBuffer[0]); + context->common.filterBuffer[0] + context->common.filterBufferLen - 104, + context->common.filterBuffer[0]); if (nrof_channels == 2) { COPY_BACKWARD_32BIT_ALIGNED_104_HALFWORDS( - context->common.filterBuffer[1] + context->common.filterBufferLen - - 104, - context->common.filterBuffer[1]); + context->common.filterBuffer[1] + context->common.filterBufferLen - 104, + context->common.filterBuffer[1]); } offset = context->common.filterBufferLen - 112; } else { @@ -381,8 +369,7 @@ PRIVATE void OI_SBC_SynthFrame_Enhanced(OI_CODEC_SBC_DECODER_CONTEXT* context, } for (ch = 0; ch < nrof_channels; ++ch) { DCT2_8(context->common.filterBuffer[ch] + offset, s); - SYNTH112(pcm + ch, context->common.filterBuffer[ch] + offset, - pcmStrideShift); + SYNTH112(pcm + ch, context->common.filterBuffer[ch] + offset, pcmStrideShift); s += 8; } pcm += (8 << pcmStrideShift); @@ -391,28 +378,27 @@ PRIVATE void OI_SBC_SynthFrame_Enhanced(OI_CODEC_SBC_DECODER_CONTEXT* context, } static const SYNTH_FRAME SynthFrameEnhanced[] = { - NULL, /* invalid */ - OI_SBC_SynthFrame_Enhanced, /* mono */ - OI_SBC_SynthFrame_Enhanced /* stereo */ + NULL, /* invalid */ + OI_SBC_SynthFrame_Enhanced, /* mono */ + OI_SBC_SynthFrame_Enhanced /* stereo */ }; #endif static const SYNTH_FRAME SynthFrame8SB[] = { - NULL, /* invalid */ - OI_SBC_SynthFrame_80, /* mono */ - OI_SBC_SynthFrame_80 /* stereo */ + NULL, /* invalid */ + OI_SBC_SynthFrame_80, /* mono */ + OI_SBC_SynthFrame_80 /* stereo */ }; static const SYNTH_FRAME SynthFrame4SB[] = { - NULL, /* invalid */ - OI_SBC_SynthFrame_4SB, /* mono */ - OI_SBC_SynthFrame_4SB /* stereo */ + NULL, /* invalid */ + OI_SBC_SynthFrame_4SB, /* mono */ + OI_SBC_SynthFrame_4SB /* stereo */ }; -PRIVATE void OI_SBC_SynthFrame(OI_CODEC_SBC_DECODER_CONTEXT* context, - int16_t* pcm, OI_UINT start_block, - OI_UINT nrof_blocks) { +PRIVATE void OI_SBC_SynthFrame(OI_CODEC_SBC_DECODER_CONTEXT* context, int16_t* pcm, + OI_UINT start_block, OI_UINT nrof_blocks) { OI_UINT nrof_subbands = context->common.frameInfo.nrof_subbands; OI_UINT nrof_channels = context->common.frameInfo.nrof_channels; @@ -428,8 +414,7 @@ PRIVATE void OI_SBC_SynthFrame(OI_CODEC_SBC_DECODER_CONTEXT* context, } } -void SynthWindow40_int32_int32_symmetry_with_sum(int16_t* pcm, - SBC_BUFFER_T buffer[80], +void SynthWindow40_int32_int32_symmetry_with_sum(int16_t* pcm, SBC_BUFFER_T buffer[80], OI_UINT strideShift) { int32_t pa; int32_t pb; @@ -483,16 +468,11 @@ void SynthWindow40_int32_int32_symmetry_with_sum(int16_t* pcm, CLIP_INT16(pb); pcm[3 << strideShift] = (int16_t)(pb); - pa = dec_window_4[2] * - (/*buffer[ 2] + */ buffer[78]); /* buffer[ 2] is always zero */ - pa += dec_window_4[6] * - (buffer[14] /* + buffer[66]*/); /* buffer[66] is always zero */ - pa += dec_window_4[10] * - (/*buffer[18] + */ buffer[62]); /* buffer[18] is always zero */ - pa += dec_window_4[14] * - (buffer[30] /* + buffer[50]*/); /* buffer[50] is always zero */ - pa += dec_window_4[18] * - (/*buffer[34] + */ buffer[46]); /* buffer[34] is always zero */ + pa = dec_window_4[2] * (/*buffer[ 2] + */ buffer[78]); /* buffer[ 2] is always zero */ + pa += dec_window_4[6] * (buffer[14] /* + buffer[66]*/); /* buffer[66] is always zero */ + pa += dec_window_4[10] * (/*buffer[18] + */ buffer[62]); /* buffer[18] is always zero */ + pa += dec_window_4[14] * (buffer[30] /* + buffer[50]*/); /* buffer[50] is always zero */ + pa += dec_window_4[18] * (/*buffer[34] + */ buffer[46]); /* buffer[34] is always zero */ pa = SCALE(-pa, 15); CLIP_INT16(pa); pcm[2 << strideShift] = (int16_t)(pa); @@ -523,8 +503,7 @@ void SynthWindow40_int32_int32_symmetry_with_sum(int16_t* pcm, algebra system, manually converted to fixed-point arithmetic. S4 can be implemented using only assignment and negation. */ -PRIVATE void cosineModulateSynth4(SBC_BUFFER_T* RESTRICT out, - int32_t const* RESTRICT in) { +PRIVATE void cosineModulateSynth4(SBC_BUFFER_T* RESTRICT out, int32_t const* RESTRICT in) { int32_t f0, f1, f2, f3, f4, f7, f8, f9, f10; int32_t y0, y1, y2, y3; diff --git a/system/embdrv/sbc/encoder/include/sbc_dct.h b/system/embdrv/sbc/encoder/include/sbc_dct.h index 86130b73be7..42e1d4fb0da 100644 --- a/system/embdrv/sbc/encoder/include/sbc_dct.h +++ b/system/embdrv/sbc/encoder/include/sbc_dct.h @@ -31,7 +31,7 @@ #define SBC_MULT_32_16_SIMPLIFIED(s16In2, s32In1, s32OutLow) \ { \ __asm { \ - MUL s32OutLow,(int32_t)s16In2, (s32In1>>15) } \ + MUL s32OutLow,(int32_t)s16In2, (s32In1>>15) } \ } #else #if (SBC_DSP_OPT == TRUE) @@ -73,11 +73,10 @@ s32OutLow=(int32_t)((int32_t)(s16In2)*(int32_t)(s32In1>>15)); s32OutLow <<= 1; \ } #if (SBC_IS_64_MULT_IN_IDCT == TRUE) -#define SBC_MULT_64(s32In1, s32In2, s32OutLow, s32OutHi) \ - { \ - s32OutLow = \ - (int32_t)(((int64_t)s32In1 * (int64_t)s32In2) & 0x00000000FFFFFFFF); \ - s32OutHi = (int32_t)(((int64_t)s32In1 * (int64_t)s32In2) >> 32); \ +#define SBC_MULT_64(s32In1, s32In2, s32OutLow, s32OutHi) \ + { \ + s32OutLow = (int32_t)(((int64_t)s32In1 * (int64_t)s32In2) & 0x00000000FFFFFFFF); \ + s32OutHi = (int32_t)(((int64_t)s32In1 * (int64_t)s32In2) >> 32); \ } #define SBC_MULT_32_32(s32In2, s32In1, s32OutLow) \ { \ diff --git a/system/embdrv/sbc/encoder/include/sbc_encoder.h b/system/embdrv/sbc/encoder/include/sbc_encoder.h index 811fecf7384..4c8d2c6fb46 100644 --- a/system/embdrv/sbc/encoder/include/sbc_encoder.h +++ b/system/embdrv/sbc/encoder/include/sbc_encoder.h @@ -157,9 +157,8 @@ /*constants used for index calculation*/ #define SBC_BLK (SBC_MAX_NUM_OF_CHANNELS * SBC_MAX_NUM_OF_SUBBANDS) -#define SBC_MAX_PCM_BUFFER_SIZE \ - (SBC_MAX_NUM_FRAME * SBC_MAX_NUM_OF_BLOCKS * SBC_MAX_NUM_OF_CHANNELS * \ - SBC_MAX_NUM_OF_SUBBANDS) +#define SBC_MAX_PCM_BUFFER_SIZE \ + (SBC_MAX_NUM_FRAME * SBC_MAX_NUM_OF_BLOCKS * SBC_MAX_NUM_OF_CHANNELS * SBC_MAX_NUM_OF_SUBBANDS) typedef struct SBC_ENC_PARAMS_TAG { int16_t s16SamplingFreq; /* 16k, 32k, 44.1k or 48k*/ @@ -180,8 +179,7 @@ typedef struct SBC_ENC_PARAMS_TAG { int16_t s16ScartchMemForBitAlloc[16]; - int32_t s32SbBuffer[SBC_MAX_NUM_OF_CHANNELS * SBC_MAX_NUM_OF_SUBBANDS * - SBC_MAX_NUM_OF_BLOCKS]; + int32_t s32SbBuffer[SBC_MAX_NUM_OF_CHANNELS * SBC_MAX_NUM_OF_SUBBANDS * SBC_MAX_NUM_OF_BLOCKS]; int16_t as16Bits[SBC_MAX_NUM_OF_CHANNELS * SBC_MAX_NUM_OF_SUBBANDS]; @@ -197,8 +195,7 @@ extern "C" { /* Encode the frame using SBC. The output is written into |output|. Return * number of bytes written. */ -uint32_t SBC_Encode(SBC_ENC_PARAMS* strEncParams, int16_t* input, - uint8_t* output); +uint32_t SBC_Encode(SBC_ENC_PARAMS* strEncParams, int16_t* input, uint8_t* output); void SBC_Encoder_Init(SBC_ENC_PARAMS* strEncParams); #ifdef __cplusplus diff --git a/system/embdrv/sbc/encoder/srce/sbc_analysis.c b/system/embdrv/sbc/encoder/srce/sbc_analysis.c index b9a9a5c8e03..6f5066d992c 100644 --- a/system/embdrv/sbc/encoder/srce/sbc_analysis.c +++ b/system/embdrv/sbc/encoder/srce/sbc_analysis.c @@ -23,6 +23,7 @@ * ******************************************************************************/ #include + #include "sbc_enc_func_declare.h" #include "sbc_encoder.h" /*#include */ @@ -34,42 +35,24 @@ #define WIND_4_SUBBANDS_0_2 \ (int32_t)0x115B1ED2 /* gas32CoeffFor4SBs[16] = -gas32CoeffFor4SBs[24] = \ 0x115B1ED2 */ -#define WIND_4_SUBBANDS_1_0 \ - (int32_t)0x001194E6 /* gas32CoeffFor4SBs[1 et 39] = 0x001194E6 */ -#define WIND_4_SUBBANDS_1_1 \ - (int32_t)0x029DBAA3 /* gas32CoeffFor4SBs[9 et 31] = 0x029DBAA3 */ -#define WIND_4_SUBBANDS_1_2 \ - (int32_t)0x18F55C90 /* gas32CoeffFor4SBs[17 et 23] = 0x18F55C90 */ -#define WIND_4_SUBBANDS_1_3 \ - (int32_t)0xF60FAF37 /* gas32CoeffFor4SBs[15 et 25] = 0xF60FAF37 */ -#define WIND_4_SUBBANDS_1_4 \ - (int32_t)0xFF9BB9D5 /* gas32CoeffFor4SBs[7 et 33] = 0xFF9BB9D5 */ -#define WIND_4_SUBBANDS_2_0 \ - (int32_t)0x0030E2D3 /* gas32CoeffFor4SBs[2 et 38] = 0x0030E2D3 */ -#define WIND_4_SUBBANDS_2_1 \ - (int32_t)0x03B23341 /* gas32CoeffFor4SBs[10 et 30] = 0x03B23341 */ -#define WIND_4_SUBBANDS_2_2 \ - (int32_t)0x1F91CA46 /* gas32CoeffFor4SBs[18 et 22] = 0x1F91CA46 */ -#define WIND_4_SUBBANDS_2_3 \ - (int32_t)0xFC4F91D4 /* gas32CoeffFor4SBs[14 et 26] = 0xFC4F91D4 */ -#define WIND_4_SUBBANDS_2_4 \ - (int32_t)0x003D239B /* gas32CoeffFor4SBs[6 et 34] = 0x003D239B */ -#define WIND_4_SUBBANDS_3_0 \ - (int32_t)0x00599403 /* gas32CoeffFor4SBs[3 et 37] = 0x00599403 */ -#define WIND_4_SUBBANDS_3_1 \ - (int32_t)0x041EEE40 /* gas32CoeffFor4SBs[11 et 29] = 0x041EEE40 */ -#define WIND_4_SUBBANDS_3_2 \ - (int32_t)0x2412F251 /* gas32CoeffFor4SBs[19 et 21] = 0x2412F251 */ -#define WIND_4_SUBBANDS_3_3 \ - (int32_t)0x00C8F2BC /* gas32CoeffFor4SBs[13 et 27] = 0x00C8F2BC */ -#define WIND_4_SUBBANDS_3_4 \ - (int32_t)0x007F88E4 /* gas32CoeffFor4SBs[5 et 35] = 0x007F88E4 */ -#define WIND_4_SUBBANDS_4_0 \ - (int32_t)0x007DBCC8 /* gas32CoeffFor4SBs[4 et 36] = 0x007DBCC8 */ -#define WIND_4_SUBBANDS_4_1 \ - (int32_t)0x034FEE2C /* gas32CoeffFor4SBs[12 et 28] = 0x034FEE2C */ -#define WIND_4_SUBBANDS_4_2 \ - (int32_t)0x25AC1FF2 /* gas32CoeffFor4SBs[20] = 0x25AC1FF2 */ +#define WIND_4_SUBBANDS_1_0 (int32_t)0x001194E6 /* gas32CoeffFor4SBs[1 et 39] = 0x001194E6 */ +#define WIND_4_SUBBANDS_1_1 (int32_t)0x029DBAA3 /* gas32CoeffFor4SBs[9 et 31] = 0x029DBAA3 */ +#define WIND_4_SUBBANDS_1_2 (int32_t)0x18F55C90 /* gas32CoeffFor4SBs[17 et 23] = 0x18F55C90 */ +#define WIND_4_SUBBANDS_1_3 (int32_t)0xF60FAF37 /* gas32CoeffFor4SBs[15 et 25] = 0xF60FAF37 */ +#define WIND_4_SUBBANDS_1_4 (int32_t)0xFF9BB9D5 /* gas32CoeffFor4SBs[7 et 33] = 0xFF9BB9D5 */ +#define WIND_4_SUBBANDS_2_0 (int32_t)0x0030E2D3 /* gas32CoeffFor4SBs[2 et 38] = 0x0030E2D3 */ +#define WIND_4_SUBBANDS_2_1 (int32_t)0x03B23341 /* gas32CoeffFor4SBs[10 et 30] = 0x03B23341 */ +#define WIND_4_SUBBANDS_2_2 (int32_t)0x1F91CA46 /* gas32CoeffFor4SBs[18 et 22] = 0x1F91CA46 */ +#define WIND_4_SUBBANDS_2_3 (int32_t)0xFC4F91D4 /* gas32CoeffFor4SBs[14 et 26] = 0xFC4F91D4 */ +#define WIND_4_SUBBANDS_2_4 (int32_t)0x003D239B /* gas32CoeffFor4SBs[6 et 34] = 0x003D239B */ +#define WIND_4_SUBBANDS_3_0 (int32_t)0x00599403 /* gas32CoeffFor4SBs[3 et 37] = 0x00599403 */ +#define WIND_4_SUBBANDS_3_1 (int32_t)0x041EEE40 /* gas32CoeffFor4SBs[11 et 29] = 0x041EEE40 */ +#define WIND_4_SUBBANDS_3_2 (int32_t)0x2412F251 /* gas32CoeffFor4SBs[19 et 21] = 0x2412F251 */ +#define WIND_4_SUBBANDS_3_3 (int32_t)0x00C8F2BC /* gas32CoeffFor4SBs[13 et 27] = 0x00C8F2BC */ +#define WIND_4_SUBBANDS_3_4 (int32_t)0x007F88E4 /* gas32CoeffFor4SBs[5 et 35] = 0x007F88E4 */ +#define WIND_4_SUBBANDS_4_0 (int32_t)0x007DBCC8 /* gas32CoeffFor4SBs[4 et 36] = 0x007DBCC8 */ +#define WIND_4_SUBBANDS_4_1 (int32_t)0x034FEE2C /* gas32CoeffFor4SBs[12 et 28] = 0x034FEE2C */ +#define WIND_4_SUBBANDS_4_2 (int32_t)0x25AC1FF2 /* gas32CoeffFor4SBs[20] = 0x25AC1FF2 */ #define WIND_8_SUBBANDS_0_1 (int32_t)0x00B97348 /* 16 0x00B97348 */ #define WIND_8_SUBBANDS_0_2 (int32_t)0x08B4307A /* 32 0x08B4307A */ @@ -115,45 +98,27 @@ #define WIND_4_SUBBANDS_0_1 \ (int16_t)0x0166 /* gas32CoeffFor4SBs[8] = -gas32CoeffFor4SBs[32] = \ 0x01659F45 */ -#define WIND_4_SUBBANDS_0_2 \ - (int16_t)0x115B /* gas32CoeffFor4SBs[16] = -gas32CoeffFor4SBs[24] = \ - 0x115B1ED2 */ -#define WIND_4_SUBBANDS_1_0 \ - (int16_t)0x0012 /* gas32CoeffFor4SBs[1 et 39] = 0x001194E6 */ -#define WIND_4_SUBBANDS_1_1 \ - (int16_t)0x029E /* gas32CoeffFor4SBs[9 et 31] = 0x029DBAA3 */ -#define WIND_4_SUBBANDS_1_2 \ - (int16_t)0x18F5 /* gas32CoeffFor4SBs[17 et 23] = 0x18F55C90 */ -#define WIND_4_SUBBANDS_1_3 \ - (int16_t)0xF610 /* gas32CoeffFor4SBs[15 et 25] = 0xF60FAF37 */ -#define WIND_4_SUBBANDS_1_4 \ - (int16_t)0xFF9C /* gas32CoeffFor4SBs[7 et 33] = 0xFF9BB9D5 */ -#define WIND_4_SUBBANDS_2_0 \ - (int16_t)0x0031 /* gas32CoeffFor4SBs[2 et 38] = 0x0030E2D3 */ -#define WIND_4_SUBBANDS_2_1 \ - (int16_t)0x03B2 /* gas32CoeffFor4SBs[10 et 30] = 0x03B23341 */ -#define WIND_4_SUBBANDS_2_2 \ - (int16_t)0x1F91 /* gas32CoeffFor4SBs[18 et 22] = 0x1F91CA46 */ -#define WIND_4_SUBBANDS_2_3 \ - (int16_t)0xFC50 /* gas32CoeffFor4SBs[14 et 26] = 0xFC4F91D4 */ -#define WIND_4_SUBBANDS_2_4 \ - (int16_t)0x003D /* gas32CoeffFor4SBs[6 et 34] = 0x003D239B */ -#define WIND_4_SUBBANDS_3_0 \ - (int16_t)0x005A /* gas32CoeffFor4SBs[3 et 37] = 0x00599403 */ -#define WIND_4_SUBBANDS_3_1 \ - (int16_t)0x041F /* gas32CoeffFor4SBs[11 et 29] = 0x041EEE40 */ -#define WIND_4_SUBBANDS_3_2 \ - (int16_t)0x2413 /* gas32CoeffFor4SBs[19 et 21] = 0x2412F251 */ -#define WIND_4_SUBBANDS_3_3 \ - (int16_t)0x00C9 /* gas32CoeffFor4SBs[13 et 27] = 0x00C8F2BC */ -#define WIND_4_SUBBANDS_3_4 \ - (int16_t)0x0080 /* gas32CoeffFor4SBs[5 et 35] = 0x007F88E4 */ -#define WIND_4_SUBBANDS_4_0 \ - (int16_t)0x007E /* gas32CoeffFor4SBs[4 et 36] = 0x007DBCC8 */ -#define WIND_4_SUBBANDS_4_1 \ - (int16_t)0x0350 /* gas32CoeffFor4SBs[12 et 28] = 0x034FEE2C */ -#define WIND_4_SUBBANDS_4_2 \ - (int16_t)0x25AC /* gas32CoeffFor4SBs[20] = 25AC1FF2 */ +#define WIND_4_SUBBANDS_0_2 \ + (int16_t)0x115B /* gas32CoeffFor4SBs[16] = -gas32CoeffFor4SBs[24] = \ + 0x115B1ED2 */ +#define WIND_4_SUBBANDS_1_0 (int16_t)0x0012 /* gas32CoeffFor4SBs[1 et 39] = 0x001194E6 */ +#define WIND_4_SUBBANDS_1_1 (int16_t)0x029E /* gas32CoeffFor4SBs[9 et 31] = 0x029DBAA3 */ +#define WIND_4_SUBBANDS_1_2 (int16_t)0x18F5 /* gas32CoeffFor4SBs[17 et 23] = 0x18F55C90 */ +#define WIND_4_SUBBANDS_1_3 (int16_t)0xF610 /* gas32CoeffFor4SBs[15 et 25] = 0xF60FAF37 */ +#define WIND_4_SUBBANDS_1_4 (int16_t)0xFF9C /* gas32CoeffFor4SBs[7 et 33] = 0xFF9BB9D5 */ +#define WIND_4_SUBBANDS_2_0 (int16_t)0x0031 /* gas32CoeffFor4SBs[2 et 38] = 0x0030E2D3 */ +#define WIND_4_SUBBANDS_2_1 (int16_t)0x03B2 /* gas32CoeffFor4SBs[10 et 30] = 0x03B23341 */ +#define WIND_4_SUBBANDS_2_2 (int16_t)0x1F91 /* gas32CoeffFor4SBs[18 et 22] = 0x1F91CA46 */ +#define WIND_4_SUBBANDS_2_3 (int16_t)0xFC50 /* gas32CoeffFor4SBs[14 et 26] = 0xFC4F91D4 */ +#define WIND_4_SUBBANDS_2_4 (int16_t)0x003D /* gas32CoeffFor4SBs[6 et 34] = 0x003D239B */ +#define WIND_4_SUBBANDS_3_0 (int16_t)0x005A /* gas32CoeffFor4SBs[3 et 37] = 0x00599403 */ +#define WIND_4_SUBBANDS_3_1 (int16_t)0x041F /* gas32CoeffFor4SBs[11 et 29] = 0x041EEE40 */ +#define WIND_4_SUBBANDS_3_2 (int16_t)0x2413 /* gas32CoeffFor4SBs[19 et 21] = 0x2412F251 */ +#define WIND_4_SUBBANDS_3_3 (int16_t)0x00C9 /* gas32CoeffFor4SBs[13 et 27] = 0x00C8F2BC */ +#define WIND_4_SUBBANDS_3_4 (int16_t)0x0080 /* gas32CoeffFor4SBs[5 et 35] = 0x007F88E4 */ +#define WIND_4_SUBBANDS_4_0 (int16_t)0x007E /* gas32CoeffFor4SBs[4 et 36] = 0x007DBCC8 */ +#define WIND_4_SUBBANDS_4_1 (int16_t)0x0350 /* gas32CoeffFor4SBs[12 et 28] = 0x034FEE2C */ +#define WIND_4_SUBBANDS_4_2 (int16_t)0x25AC /* gas32CoeffFor4SBs[20] = 25AC1FF2 */ #define WIND_8_SUBBANDS_0_1 (int16_t)0x00B9 /* 16 0x12CF6C75 */ #define WIND_8_SUBBANDS_0_2 (int16_t)0x08B4 /* 32 0x08B4307A */ @@ -202,8 +167,7 @@ #endif static int32_t s32DCTY[16] = {0}; static int32_t s32X[ENC_VX_BUFFER_SIZE / 2]; -static int16_t* s16X = - (int16_t*)s32X; /* s16X must be 32 bits aligned cf SHIFTUP_X8_2*/ +static int16_t* s16X = (int16_t*)s32X; /* s16X must be 32 bits aligned cf SHIFTUP_X8_2*/ #if (SBC_USE_ARM_PRAGMA == TRUE) #pragma arm section zidata #endif @@ -275,16 +239,16 @@ static int16_t* s16X = } #if (SBC_ARM_ASM_OPT == TRUE) -#define WINDOW_ACCU_8_0 \ - { \ +#define WINDOW_ACCU_8_0 \ + { \ __asm {\ MUL s32Hi,WIND_8_SUBBANDS_0_1,(s16X[ChOffset+16]-s16X[ChOffset+64]);\ MLA s32Hi,WIND_8_SUBBANDS_0_2,(s16X[ChOffset+32]-s16X[ChOffset+48]),s32Hi;\ - MOV s32DCTY[0],s32Hi; \ - } \ + MOV s32DCTY[0],s32Hi; \ + } \ } -#define WINDOW_ACCU_8_1_15 \ - { \ +#define WINDOW_ACCU_8_1_15 \ + { \ __asm {\ MUL s32Hi,WIND_8_SUBBANDS_1_0,s16X[ChOffset+1];\ MUL s32Hi2,WIND_8_SUBBANDS_1_0,s16X[ChOffset+64+15];\ @@ -297,11 +261,11 @@ static int16_t* s16X = MLA s32Hi,WIND_8_SUBBANDS_1_4,s16X[ChOffset+64+1],s32Hi;\ MLA s32Hi2,WIND_8_SUBBANDS_1_4,s16X[ChOffset+15],s32Hi2;\ MOV s32DCTY[1],s32Hi;\ - MOV s32DCTY[15],s32Hi2; \ - } \ + MOV s32DCTY[15],s32Hi2; \ + } \ } -#define WINDOW_ACCU_8_2_14 \ - { \ +#define WINDOW_ACCU_8_2_14 \ + { \ __asm {\ MUL s32Hi,WIND_8_SUBBANDS_2_0,s16X[ChOffset+2];\ MUL s32Hi2,WIND_8_SUBBANDS_2_0,s16X[ChOffset+64+14];\ @@ -314,11 +278,11 @@ static int16_t* s16X = MLA s32Hi,WIND_8_SUBBANDS_2_4,s16X[ChOffset+64+2],s32Hi;\ MLA s32Hi2,WIND_8_SUBBANDS_2_4,s16X[ChOffset+14],s32Hi2;\ MOV s32DCTY[2],s32Hi;\ - MOV s32DCTY[14],s32Hi2; \ - } \ + MOV s32DCTY[14],s32Hi2; \ + } \ } -#define WINDOW_ACCU_8_3_13 \ - { \ +#define WINDOW_ACCU_8_3_13 \ + { \ __asm {\ MUL s32Hi,WIND_8_SUBBANDS_3_0,s16X[ChOffset+3];\ MUL s32Hi2,WIND_8_SUBBANDS_3_0,s16X[ChOffset+64+13];\ @@ -331,11 +295,11 @@ static int16_t* s16X = MLA s32Hi,WIND_8_SUBBANDS_3_4,s16X[ChOffset+64+3],s32Hi;\ MLA s32Hi2,WIND_8_SUBBANDS_3_4,s16X[ChOffset+13],s32Hi2;\ MOV s32DCTY[3],s32Hi;\ - MOV s32DCTY[13],s32Hi2; \ - } \ + MOV s32DCTY[13],s32Hi2; \ + } \ } -#define WINDOW_ACCU_8_4_12 \ - { \ +#define WINDOW_ACCU_8_4_12 \ + { \ __asm {\ MUL s32Hi,WIND_8_SUBBANDS_4_0,s16X[ChOffset+4];\ MUL s32Hi2,WIND_8_SUBBANDS_4_0,s16X[ChOffset+64+12];\ @@ -348,11 +312,11 @@ static int16_t* s16X = MLA s32Hi,WIND_8_SUBBANDS_4_4,s16X[ChOffset+64+4],s32Hi;\ MLA s32Hi2,WIND_8_SUBBANDS_4_4,s16X[ChOffset+12],s32Hi2;\ MOV s32DCTY[4],s32Hi;\ - MOV s32DCTY[12],s32Hi2; \ - } \ + MOV s32DCTY[12],s32Hi2; \ + } \ } -#define WINDOW_ACCU_8_5_11 \ - { \ +#define WINDOW_ACCU_8_5_11 \ + { \ __asm {\ MUL s32Hi,WIND_8_SUBBANDS_5_0,s16X[ChOffset+5];\ MUL s32Hi2,WIND_8_SUBBANDS_5_0,s16X[ChOffset+64+11];\ @@ -365,11 +329,11 @@ static int16_t* s16X = MLA s32Hi,WIND_8_SUBBANDS_5_4,s16X[ChOffset+64+5],s32Hi;\ MLA s32Hi2,WIND_8_SUBBANDS_5_4,s16X[ChOffset+11],s32Hi2;\ MOV s32DCTY[5],s32Hi;\ - MOV s32DCTY[11],s32Hi2; \ - } \ + MOV s32DCTY[11],s32Hi2; \ + } \ } -#define WINDOW_ACCU_8_6_10 \ - { \ +#define WINDOW_ACCU_8_6_10 \ + { \ __asm {\ MUL s32Hi,WIND_8_SUBBANDS_6_0,s16X[ChOffset+6];\ MUL s32Hi2,WIND_8_SUBBANDS_6_0,s16X[ChOffset+64+10];\ @@ -382,11 +346,11 @@ static int16_t* s16X = MLA s32Hi,WIND_8_SUBBANDS_6_4,s16X[ChOffset+64+6],s32Hi;\ MLA s32Hi2,WIND_8_SUBBANDS_6_4,s16X[ChOffset+10],s32Hi2;\ MOV s32DCTY[6],s32Hi;\ - MOV s32DCTY[10],s32Hi2; \ - } \ + MOV s32DCTY[10],s32Hi2; \ + } \ } -#define WINDOW_ACCU_8_7_9 \ - { \ +#define WINDOW_ACCU_8_7_9 \ + { \ __asm {\ MUL s32Hi,WIND_8_SUBBANDS_7_0,s16X[ChOffset+7];\ MUL s32Hi2,WIND_8_SUBBANDS_7_0,s16X[ChOffset+64+9];\ @@ -399,28 +363,28 @@ static int16_t* s16X = MLA s32Hi,WIND_8_SUBBANDS_7_4,s16X[ChOffset+64+7],s32Hi;\ MLA s32Hi2,WIND_8_SUBBANDS_7_4,s16X[ChOffset+9],s32Hi2;\ MOV s32DCTY[7],s32Hi;\ - MOV s32DCTY[9],s32Hi2; \ - } \ + MOV s32DCTY[9],s32Hi2; \ + } \ } -#define WINDOW_ACCU_8_8 \ - { \ +#define WINDOW_ACCU_8_8 \ + { \ __asm {\ MUL s32Hi,WIND_8_SUBBANDS_8_0,(s16X[ChOffset+8]+s16X[ChOffset+8+64]);\ MLA s32Hi,WIND_8_SUBBANDS_8_1,(s16X[ChOffset+8+16]+s16X[ChOffset+8+64]),s32Hi;\ MLA s32Hi,WIND_8_SUBBANDS_8_2,s16X[ChOffset+8+32],s32Hi;\ - MOV s32DCTY[8],s32Hi; \ - } \ + MOV s32DCTY[8],s32Hi; \ + } \ } -#define WINDOW_ACCU_4_0 \ - { \ +#define WINDOW_ACCU_4_0 \ + { \ __asm {\ MUL s32Hi,WIND_4_SUBBANDS_0_1,(s16X[ChOffset+8]-s16X[ChOffset+32]);\ MLA s32Hi,WIND_4_SUBBANDS_0_2,(s16X[ChOffset+16]-s16X[ChOffset+24]),s32Hi;\ - MOV s32DCTY[0],s32Hi; \ - } \ + MOV s32DCTY[0],s32Hi; \ + } \ } -#define WINDOW_ACCU_4_1_7 \ - { \ +#define WINDOW_ACCU_4_1_7 \ + { \ __asm {\ MUL s32Hi,WIND_4_SUBBANDS_1_0,s16X[ChOffset+1];\ MUL s32Hi2,WIND_4_SUBBANDS_1_0,s16X[ChOffset+32+7];\ @@ -433,11 +397,11 @@ static int16_t* s16X = MLA s32Hi,WIND_4_SUBBANDS_1_4,s16X[ChOffset+32+1],s32Hi;\ MLA s32Hi2,WIND_4_SUBBANDS_1_4,s16X[ChOffset+7],s32Hi2;\ MOV s32DCTY[1],s32Hi;\ - MOV s32DCTY[7],s32Hi2; \ - } \ + MOV s32DCTY[7],s32Hi2; \ + } \ } -#define WINDOW_ACCU_4_2_6 \ - { \ +#define WINDOW_ACCU_4_2_6 \ + { \ __asm {\ MUL s32Hi,WIND_4_SUBBANDS_2_0,s16X[ChOffset+2];\ MUL s32Hi2,WIND_4_SUBBANDS_2_0,s16X[ChOffset+32+6];\ @@ -450,11 +414,11 @@ static int16_t* s16X = MLA s32Hi,WIND_4_SUBBANDS_2_4,s16X[ChOffset+32+2],s32Hi;\ MLA s32Hi2,WIND_4_SUBBANDS_2_4,s16X[ChOffset+6],s32Hi2;\ MOV s32DCTY[2],s32Hi;\ - MOV s32DCTY[6],s32Hi2; \ - } \ + MOV s32DCTY[6],s32Hi2; \ + } \ } -#define WINDOW_ACCU_4_3_5 \ - { \ +#define WINDOW_ACCU_4_3_5 \ + { \ __asm {\ MUL s32Hi,WIND_4_SUBBANDS_3_0,s16X[ChOffset+3];\ MUL s32Hi2,WIND_4_SUBBANDS_3_0,s16X[ChOffset+32+5];\ @@ -467,17 +431,17 @@ static int16_t* s16X = MLA s32Hi,WIND_4_SUBBANDS_3_4,s16X[ChOffset+32+3],s32Hi;\ MLA s32Hi2,WIND_4_SUBBANDS_3_4,s16X[ChOffset+5],s32Hi2;\ MOV s32DCTY[3],s32Hi;\ - MOV s32DCTY[5],s32Hi2; \ - } \ + MOV s32DCTY[5],s32Hi2; \ + } \ } -#define WINDOW_ACCU_4_4 \ - { \ +#define WINDOW_ACCU_4_4 \ + { \ __asm {\ MUL s32Hi,WIND_4_SUBBANDS_4_0,(s16X[ChOffset+4]+s16X[ChOffset+4+32]);\ MLA s32Hi,WIND_4_SUBBANDS_4_1,(s16X[ChOffset+4+8]+s16X[ChOffset+4+24]),s32Hi;\ MLA s32Hi,WIND_4_SUBBANDS_4_2,s16X[ChOffset+4+16],s32Hi;\ - MOV s32DCTY[4],s32Hi; \ - } \ + MOV s32DCTY[4],s32Hi; \ + } \ } #define WINDOW_PARTIAL_4 \ @@ -506,534 +470,372 @@ static int16_t* s16X = #if (SBC_IPAQ_OPT == TRUE) #if (SBC_IS_64_MULT_IN_WINDOW_ACCU == TRUE) -#define WINDOW_ACCU_8_0 \ - { \ - s64Temp = (int64_t)WIND_8_SUBBANDS_0_1 * \ - (int64_t)(s16X[ChOffset + 16] - s16X[ChOffset + 64]); \ - s64Temp += (int64_t)WIND_8_SUBBANDS_0_2 * \ - (int64_t)(s16X[ChOffset + 32] - s16X[ChOffset + 48]); \ - s32DCTY[0] = (int32_t)(s64Temp >> 16); \ +#define WINDOW_ACCU_8_0 \ + { \ + s64Temp = (int64_t)WIND_8_SUBBANDS_0_1 * (int64_t)(s16X[ChOffset + 16] - s16X[ChOffset + 64]); \ + s64Temp += \ + (int64_t)WIND_8_SUBBANDS_0_2 * (int64_t)(s16X[ChOffset + 32] - s16X[ChOffset + 48]); \ + s32DCTY[0] = (int32_t)(s64Temp >> 16); \ } -#define WINDOW_ACCU_8_1_15 \ - { \ - s64Temp = (int64_t)WIND_8_SUBBANDS_1_0 * (int64_t)s16X[ChOffset + 1]; \ - s64Temp2 = \ - (int64_t)WIND_8_SUBBANDS_1_0 * (int64_t)s16X[ChOffset + 64 + 15]; \ - s64Temp += \ - (int64_t)WIND_8_SUBBANDS_1_1 * (int64_t)s16X[ChOffset + 16 + 1]; \ - s64Temp2 += \ - (int64_t)WIND_8_SUBBANDS_1_1 * (int64_t)s16X[ChOffset + 48 + 15]; \ - s64Temp += \ - (int64_t)WIND_8_SUBBANDS_1_2 * (int64_t)s16X[ChOffset + 32 + 1]; \ - s64Temp2 += \ - (int64_t)WIND_8_SUBBANDS_1_2 * (int64_t)s16X[ChOffset + 32 + 15]; \ - s64Temp += \ - (int64_t)WIND_8_SUBBANDS_1_3 * (int64_t)s16X[ChOffset + 48 + 1]; \ - s64Temp2 += \ - (int64_t)WIND_8_SUBBANDS_1_3 * (int64_t)s16X[ChOffset + 16 + 15]; \ - s64Temp += \ - (int64_t)WIND_8_SUBBANDS_1_4 * (int64_t)s16X[ChOffset + 64 + 1]; \ - s64Temp2 += (int64_t)WIND_8_SUBBANDS_1_4 * (int64_t)s16X[ChOffset + 15]; \ - s32DCTY[1] = (int32_t)(s64Temp >> 16); \ - s32DCTY[15] = (int32_t)(s64Temp2 >> 16); \ +#define WINDOW_ACCU_8_1_15 \ + { \ + s64Temp = (int64_t)WIND_8_SUBBANDS_1_0 * (int64_t)s16X[ChOffset + 1]; \ + s64Temp2 = (int64_t)WIND_8_SUBBANDS_1_0 * (int64_t)s16X[ChOffset + 64 + 15]; \ + s64Temp += (int64_t)WIND_8_SUBBANDS_1_1 * (int64_t)s16X[ChOffset + 16 + 1]; \ + s64Temp2 += (int64_t)WIND_8_SUBBANDS_1_1 * (int64_t)s16X[ChOffset + 48 + 15]; \ + s64Temp += (int64_t)WIND_8_SUBBANDS_1_2 * (int64_t)s16X[ChOffset + 32 + 1]; \ + s64Temp2 += (int64_t)WIND_8_SUBBANDS_1_2 * (int64_t)s16X[ChOffset + 32 + 15]; \ + s64Temp += (int64_t)WIND_8_SUBBANDS_1_3 * (int64_t)s16X[ChOffset + 48 + 1]; \ + s64Temp2 += (int64_t)WIND_8_SUBBANDS_1_3 * (int64_t)s16X[ChOffset + 16 + 15]; \ + s64Temp += (int64_t)WIND_8_SUBBANDS_1_4 * (int64_t)s16X[ChOffset + 64 + 1]; \ + s64Temp2 += (int64_t)WIND_8_SUBBANDS_1_4 * (int64_t)s16X[ChOffset + 15]; \ + s32DCTY[1] = (int32_t)(s64Temp >> 16); \ + s32DCTY[15] = (int32_t)(s64Temp2 >> 16); \ } -#define WINDOW_ACCU_8_2_14 \ - { \ - s64Temp = (int64_t)WIND_8_SUBBANDS_2_0 * (int64_t)s16X[ChOffset + 2]; \ - s64Temp2 = \ - (int64_t)WIND_8_SUBBANDS_2_0 * (int64_t)s16X[ChOffset + 64 + 14]; \ - s64Temp += \ - (int64_t)WIND_8_SUBBANDS_2_1 * (int64_t)s16X[ChOffset + 16 + 2]; \ - s64Temp2 += \ - (int64_t)WIND_8_SUBBANDS_2_1 * (int64_t)s16X[ChOffset + 48 + 14]; \ - s64Temp += \ - (int64_t)WIND_8_SUBBANDS_2_2 * (int64_t)s16X[ChOffset + 32 + 2]; \ - s64Temp2 += \ - (int64_t)WIND_8_SUBBANDS_2_2 * (int64_t)s16X[ChOffset + 32 + 14]; \ - s64Temp += \ - (int64_t)WIND_8_SUBBANDS_2_3 * (int64_t)s16X[ChOffset + 48 + 2]; \ - s64Temp2 += \ - (int64_t)WIND_8_SUBBANDS_2_3 * (int64_t)s16X[ChOffset + 16 + 14]; \ - s64Temp += \ - (int64_t)WIND_8_SUBBANDS_2_4 * (int64_t)s16X[ChOffset + 64 + 2]; \ - s64Temp2 += (int64_t)WIND_8_SUBBANDS_2_4 * (int64_t)s16X[ChOffset + 14]; \ - s32DCTY[2] = (int32_t)(s64Temp >> 16); \ - s32DCTY[14] = (int32_t)(s64Temp2 >> 16); \ +#define WINDOW_ACCU_8_2_14 \ + { \ + s64Temp = (int64_t)WIND_8_SUBBANDS_2_0 * (int64_t)s16X[ChOffset + 2]; \ + s64Temp2 = (int64_t)WIND_8_SUBBANDS_2_0 * (int64_t)s16X[ChOffset + 64 + 14]; \ + s64Temp += (int64_t)WIND_8_SUBBANDS_2_1 * (int64_t)s16X[ChOffset + 16 + 2]; \ + s64Temp2 += (int64_t)WIND_8_SUBBANDS_2_1 * (int64_t)s16X[ChOffset + 48 + 14]; \ + s64Temp += (int64_t)WIND_8_SUBBANDS_2_2 * (int64_t)s16X[ChOffset + 32 + 2]; \ + s64Temp2 += (int64_t)WIND_8_SUBBANDS_2_2 * (int64_t)s16X[ChOffset + 32 + 14]; \ + s64Temp += (int64_t)WIND_8_SUBBANDS_2_3 * (int64_t)s16X[ChOffset + 48 + 2]; \ + s64Temp2 += (int64_t)WIND_8_SUBBANDS_2_3 * (int64_t)s16X[ChOffset + 16 + 14]; \ + s64Temp += (int64_t)WIND_8_SUBBANDS_2_4 * (int64_t)s16X[ChOffset + 64 + 2]; \ + s64Temp2 += (int64_t)WIND_8_SUBBANDS_2_4 * (int64_t)s16X[ChOffset + 14]; \ + s32DCTY[2] = (int32_t)(s64Temp >> 16); \ + s32DCTY[14] = (int32_t)(s64Temp2 >> 16); \ } -#define WINDOW_ACCU_8_3_13 \ - { \ - s64Temp = (int64_t)WIND_8_SUBBANDS_3_0 * (int64_t)s16X[ChOffset + 3]; \ - s64Temp2 = \ - (int64_t)WIND_8_SUBBANDS_3_0 * (int64_t)s16X[ChOffset + 64 + 13]; \ - s64Temp += \ - (int64_t)WIND_8_SUBBANDS_3_1 * (int64_t)s16X[ChOffset + 16 + 3]; \ - s64Temp2 += \ - (int64_t)WIND_8_SUBBANDS_3_1 * (int64_t)s16X[ChOffset + 48 + 13]; \ - s64Temp += \ - (int64_t)WIND_8_SUBBANDS_3_2 * (int64_t)s16X[ChOffset + 32 + 3]; \ - s64Temp2 += \ - (int64_t)WIND_8_SUBBANDS_3_2 * (int64_t)s16X[ChOffset + 32 + 13]; \ - s64Temp += \ - (int64_t)WIND_8_SUBBANDS_3_3 * (int64_t)s16X[ChOffset + 48 + 3]; \ - s64Temp2 += \ - (int64_t)WIND_8_SUBBANDS_3_3 * (int64_t)s16X[ChOffset + 16 + 13]; \ - s64Temp += \ - (int64_t)WIND_8_SUBBANDS_3_4 * (int64_t)s16X[ChOffset + 64 + 3]; \ - s64Temp2 += (int64_t)WIND_8_SUBBANDS_3_4 * (int64_t)s16X[ChOffset + 13]; \ - s32DCTY[3] = (int32_t)(s64Temp >> 16); \ - s32DCTY[13] = (int32_t)(s64Temp2 >> 16); \ +#define WINDOW_ACCU_8_3_13 \ + { \ + s64Temp = (int64_t)WIND_8_SUBBANDS_3_0 * (int64_t)s16X[ChOffset + 3]; \ + s64Temp2 = (int64_t)WIND_8_SUBBANDS_3_0 * (int64_t)s16X[ChOffset + 64 + 13]; \ + s64Temp += (int64_t)WIND_8_SUBBANDS_3_1 * (int64_t)s16X[ChOffset + 16 + 3]; \ + s64Temp2 += (int64_t)WIND_8_SUBBANDS_3_1 * (int64_t)s16X[ChOffset + 48 + 13]; \ + s64Temp += (int64_t)WIND_8_SUBBANDS_3_2 * (int64_t)s16X[ChOffset + 32 + 3]; \ + s64Temp2 += (int64_t)WIND_8_SUBBANDS_3_2 * (int64_t)s16X[ChOffset + 32 + 13]; \ + s64Temp += (int64_t)WIND_8_SUBBANDS_3_3 * (int64_t)s16X[ChOffset + 48 + 3]; \ + s64Temp2 += (int64_t)WIND_8_SUBBANDS_3_3 * (int64_t)s16X[ChOffset + 16 + 13]; \ + s64Temp += (int64_t)WIND_8_SUBBANDS_3_4 * (int64_t)s16X[ChOffset + 64 + 3]; \ + s64Temp2 += (int64_t)WIND_8_SUBBANDS_3_4 * (int64_t)s16X[ChOffset + 13]; \ + s32DCTY[3] = (int32_t)(s64Temp >> 16); \ + s32DCTY[13] = (int32_t)(s64Temp2 >> 16); \ } -#define WINDOW_ACCU_8_4_12 \ - { \ - s64Temp = (int64_t)WIND_8_SUBBANDS_4_0 * (int64_t)s16X[ChOffset + 4]; \ - s64Temp2 = \ - (int64_t)WIND_8_SUBBANDS_4_0 * (int64_t)s16X[ChOffset + 64 + 12]; \ - s64Temp += \ - (int64_t)WIND_8_SUBBANDS_4_1 * (int64_t)s16X[ChOffset + 16 + 4]; \ - s64Temp2 += \ - (int64_t)WIND_8_SUBBANDS_4_1 * (int64_t)s16X[ChOffset + 48 + 12]; \ - s64Temp += \ - (int64_t)WIND_8_SUBBANDS_4_2 * (int64_t)s16X[ChOffset + 32 + 4]; \ - s64Temp2 += \ - (int64_t)WIND_8_SUBBANDS_4_2 * (int64_t)s16X[ChOffset + 32 + 12]; \ - s64Temp += \ - (int64_t)WIND_8_SUBBANDS_4_3 * (int64_t)s16X[ChOffset + 48 + 4]; \ - s64Temp2 += \ - (int64_t)WIND_8_SUBBANDS_4_3 * (int64_t)s16X[ChOffset + 16 + 12]; \ - s64Temp += \ - (int64_t)WIND_8_SUBBANDS_4_4 * (int64_t)s16X[ChOffset + 64 + 4]; \ - s64Temp2 += (int64_t)WIND_8_SUBBANDS_4_4 * (int64_t)s16X[ChOffset + 12]; \ - s32DCTY[4] = (int32_t)(s64Temp >> 16); \ - s32DCTY[12] = (int32_t)(s64Temp2 >> 16); \ +#define WINDOW_ACCU_8_4_12 \ + { \ + s64Temp = (int64_t)WIND_8_SUBBANDS_4_0 * (int64_t)s16X[ChOffset + 4]; \ + s64Temp2 = (int64_t)WIND_8_SUBBANDS_4_0 * (int64_t)s16X[ChOffset + 64 + 12]; \ + s64Temp += (int64_t)WIND_8_SUBBANDS_4_1 * (int64_t)s16X[ChOffset + 16 + 4]; \ + s64Temp2 += (int64_t)WIND_8_SUBBANDS_4_1 * (int64_t)s16X[ChOffset + 48 + 12]; \ + s64Temp += (int64_t)WIND_8_SUBBANDS_4_2 * (int64_t)s16X[ChOffset + 32 + 4]; \ + s64Temp2 += (int64_t)WIND_8_SUBBANDS_4_2 * (int64_t)s16X[ChOffset + 32 + 12]; \ + s64Temp += (int64_t)WIND_8_SUBBANDS_4_3 * (int64_t)s16X[ChOffset + 48 + 4]; \ + s64Temp2 += (int64_t)WIND_8_SUBBANDS_4_3 * (int64_t)s16X[ChOffset + 16 + 12]; \ + s64Temp += (int64_t)WIND_8_SUBBANDS_4_4 * (int64_t)s16X[ChOffset + 64 + 4]; \ + s64Temp2 += (int64_t)WIND_8_SUBBANDS_4_4 * (int64_t)s16X[ChOffset + 12]; \ + s32DCTY[4] = (int32_t)(s64Temp >> 16); \ + s32DCTY[12] = (int32_t)(s64Temp2 >> 16); \ } -#define WINDOW_ACCU_8_5_11 \ - { \ - s64Temp = (int64_t)WIND_8_SUBBANDS_5_0 * (int64_t)s16X[ChOffset + 5]; \ - s64Temp2 = \ - (int64_t)WIND_8_SUBBANDS_5_0 * (int64_t)s16X[ChOffset + 64 + 11]; \ - s64Temp += \ - (int64_t)WIND_8_SUBBANDS_5_1 * (int64_t)s16X[ChOffset + 16 + 5]; \ - s64Temp2 += \ - (int64_t)WIND_8_SUBBANDS_5_1 * (int64_t)s16X[ChOffset + 48 + 11]; \ - s64Temp += \ - (int64_t)WIND_8_SUBBANDS_5_2 * (int64_t)s16X[ChOffset + 32 + 5]; \ - s64Temp2 += \ - (int64_t)WIND_8_SUBBANDS_5_2 * (int64_t)s16X[ChOffset + 32 + 11]; \ - s64Temp += \ - (int64_t)WIND_8_SUBBANDS_5_3 * (int64_t)s16X[ChOffset + 48 + 5]; \ - s64Temp2 += \ - (int64_t)WIND_8_SUBBANDS_5_3 * (int64_t)s16X[ChOffset + 16 + 11]; \ - s64Temp += \ - (int64_t)WIND_8_SUBBANDS_5_4 * (int64_t)s16X[ChOffset + 64 + 5]; \ - s64Temp2 += (int64_t)WIND_8_SUBBANDS_5_4 * (int64_t)s16X[ChOffset + 11]; \ - s32DCTY[5] = (int32_t)(s64Temp >> 16); \ - s32DCTY[11] = (int32_t)(s64Temp2 >> 16); \ +#define WINDOW_ACCU_8_5_11 \ + { \ + s64Temp = (int64_t)WIND_8_SUBBANDS_5_0 * (int64_t)s16X[ChOffset + 5]; \ + s64Temp2 = (int64_t)WIND_8_SUBBANDS_5_0 * (int64_t)s16X[ChOffset + 64 + 11]; \ + s64Temp += (int64_t)WIND_8_SUBBANDS_5_1 * (int64_t)s16X[ChOffset + 16 + 5]; \ + s64Temp2 += (int64_t)WIND_8_SUBBANDS_5_1 * (int64_t)s16X[ChOffset + 48 + 11]; \ + s64Temp += (int64_t)WIND_8_SUBBANDS_5_2 * (int64_t)s16X[ChOffset + 32 + 5]; \ + s64Temp2 += (int64_t)WIND_8_SUBBANDS_5_2 * (int64_t)s16X[ChOffset + 32 + 11]; \ + s64Temp += (int64_t)WIND_8_SUBBANDS_5_3 * (int64_t)s16X[ChOffset + 48 + 5]; \ + s64Temp2 += (int64_t)WIND_8_SUBBANDS_5_3 * (int64_t)s16X[ChOffset + 16 + 11]; \ + s64Temp += (int64_t)WIND_8_SUBBANDS_5_4 * (int64_t)s16X[ChOffset + 64 + 5]; \ + s64Temp2 += (int64_t)WIND_8_SUBBANDS_5_4 * (int64_t)s16X[ChOffset + 11]; \ + s32DCTY[5] = (int32_t)(s64Temp >> 16); \ + s32DCTY[11] = (int32_t)(s64Temp2 >> 16); \ } -#define WINDOW_ACCU_8_6_10 \ - { \ - s64Temp = (int64_t)WIND_8_SUBBANDS_6_0 * (int64_t)s16X[ChOffset + 6]; \ - s64Temp2 = \ - (int64_t)WIND_8_SUBBANDS_6_0 * (int64_t)s16X[ChOffset + 64 + 10]; \ - s64Temp += \ - (int64_t)WIND_8_SUBBANDS_6_1 * (int64_t)s16X[ChOffset + 16 + 6]; \ - s64Temp2 += \ - (int64_t)WIND_8_SUBBANDS_6_1 * (int64_t)s16X[ChOffset + 48 + 10]; \ - s64Temp += \ - (int64_t)WIND_8_SUBBANDS_6_2 * (int64_t)s16X[ChOffset + 32 + 6]; \ - s64Temp2 += \ - (int64_t)WIND_8_SUBBANDS_6_2 * (int64_t)s16X[ChOffset + 32 + 10]; \ - s64Temp += \ - (int64_t)WIND_8_SUBBANDS_6_3 * (int64_t)s16X[ChOffset + 48 + 6]; \ - s64Temp2 += \ - (int64_t)WIND_8_SUBBANDS_6_3 * (int64_t)s16X[ChOffset + 16 + 10]; \ - s64Temp += \ - (int64_t)WIND_8_SUBBANDS_6_4 * (int64_t)s16X[ChOffset + 64 + 6]; \ - s64Temp2 += (int64_t)WIND_8_SUBBANDS_6_4 * (int64_t)s16X[ChOffset + 10]; \ - s32DCTY[6] = (int32_t)(s64Temp >> 16); \ - s32DCTY[10] = (int32_t)(s64Temp2 >> 16); \ +#define WINDOW_ACCU_8_6_10 \ + { \ + s64Temp = (int64_t)WIND_8_SUBBANDS_6_0 * (int64_t)s16X[ChOffset + 6]; \ + s64Temp2 = (int64_t)WIND_8_SUBBANDS_6_0 * (int64_t)s16X[ChOffset + 64 + 10]; \ + s64Temp += (int64_t)WIND_8_SUBBANDS_6_1 * (int64_t)s16X[ChOffset + 16 + 6]; \ + s64Temp2 += (int64_t)WIND_8_SUBBANDS_6_1 * (int64_t)s16X[ChOffset + 48 + 10]; \ + s64Temp += (int64_t)WIND_8_SUBBANDS_6_2 * (int64_t)s16X[ChOffset + 32 + 6]; \ + s64Temp2 += (int64_t)WIND_8_SUBBANDS_6_2 * (int64_t)s16X[ChOffset + 32 + 10]; \ + s64Temp += (int64_t)WIND_8_SUBBANDS_6_3 * (int64_t)s16X[ChOffset + 48 + 6]; \ + s64Temp2 += (int64_t)WIND_8_SUBBANDS_6_3 * (int64_t)s16X[ChOffset + 16 + 10]; \ + s64Temp += (int64_t)WIND_8_SUBBANDS_6_4 * (int64_t)s16X[ChOffset + 64 + 6]; \ + s64Temp2 += (int64_t)WIND_8_SUBBANDS_6_4 * (int64_t)s16X[ChOffset + 10]; \ + s32DCTY[6] = (int32_t)(s64Temp >> 16); \ + s32DCTY[10] = (int32_t)(s64Temp2 >> 16); \ } -#define WINDOW_ACCU_8_7_9 \ - { \ - s64Temp = (int64_t)WIND_8_SUBBANDS_7_0 * (int64_t)s16X[ChOffset + 7]; \ - s64Temp2 = \ - (int64_t)WIND_8_SUBBANDS_7_0 * (int64_t)s16X[ChOffset + 64 + 9]; \ - s64Temp += \ - (int64_t)WIND_8_SUBBANDS_7_1 * (int64_t)s16X[ChOffset + 16 + 7]; \ - s64Temp2 += \ - (int64_t)WIND_8_SUBBANDS_7_1 * (int64_t)s16X[ChOffset + 48 + 9]; \ - s64Temp += \ - (int64_t)WIND_8_SUBBANDS_7_2 * (int64_t)s16X[ChOffset + 32 + 7]; \ - s64Temp2 += \ - (int64_t)WIND_8_SUBBANDS_7_2 * (int64_t)s16X[ChOffset + 32 + 9]; \ - s64Temp += \ - (int64_t)WIND_8_SUBBANDS_7_3 * (int64_t)s16X[ChOffset + 48 + 7]; \ - s64Temp2 += \ - (int64_t)WIND_8_SUBBANDS_7_3 * (int64_t)s16X[ChOffset + 16 + 9]; \ - s64Temp += \ - (int64_t)WIND_8_SUBBANDS_7_4 * (int64_t)s16X[ChOffset + 64 + 7]; \ - s64Temp2 += (int64_t)WIND_8_SUBBANDS_7_4 * (int64_t)s16X[ChOffset + 9]; \ - s32DCTY[7] = (int32_t)(s64Temp >> 16); \ - s32DCTY[9] = (int32_t)(s64Temp2 >> 16); \ +#define WINDOW_ACCU_8_7_9 \ + { \ + s64Temp = (int64_t)WIND_8_SUBBANDS_7_0 * (int64_t)s16X[ChOffset + 7]; \ + s64Temp2 = (int64_t)WIND_8_SUBBANDS_7_0 * (int64_t)s16X[ChOffset + 64 + 9]; \ + s64Temp += (int64_t)WIND_8_SUBBANDS_7_1 * (int64_t)s16X[ChOffset + 16 + 7]; \ + s64Temp2 += (int64_t)WIND_8_SUBBANDS_7_1 * (int64_t)s16X[ChOffset + 48 + 9]; \ + s64Temp += (int64_t)WIND_8_SUBBANDS_7_2 * (int64_t)s16X[ChOffset + 32 + 7]; \ + s64Temp2 += (int64_t)WIND_8_SUBBANDS_7_2 * (int64_t)s16X[ChOffset + 32 + 9]; \ + s64Temp += (int64_t)WIND_8_SUBBANDS_7_3 * (int64_t)s16X[ChOffset + 48 + 7]; \ + s64Temp2 += (int64_t)WIND_8_SUBBANDS_7_3 * (int64_t)s16X[ChOffset + 16 + 9]; \ + s64Temp += (int64_t)WIND_8_SUBBANDS_7_4 * (int64_t)s16X[ChOffset + 64 + 7]; \ + s64Temp2 += (int64_t)WIND_8_SUBBANDS_7_4 * (int64_t)s16X[ChOffset + 9]; \ + s32DCTY[7] = (int32_t)(s64Temp >> 16); \ + s32DCTY[9] = (int32_t)(s64Temp2 >> 16); \ } -#define WINDOW_ACCU_8_8 \ - { \ - s64Temp = (int64_t)WIND_8_SUBBANDS_8_0 * \ - (int64_t)(s16X[ChOffset + 8] + s16X[ChOffset + 64 + 8]); \ - s64Temp += (int64_t)WIND_8_SUBBANDS_8_1 * \ - (int64_t)(s16X[ChOffset + 16 + 8] + s16X[ChOffset + 48 + 8]); \ - s64Temp += \ - (int64_t)WIND_8_SUBBANDS_8_2 * (int64_t)s16X[ChOffset + 32 + 8]; \ - s32DCTY[8] = (int32_t)(s64Temp >> 16); \ +#define WINDOW_ACCU_8_8 \ + { \ + s64Temp = (int64_t)WIND_8_SUBBANDS_8_0 * \ + (int64_t)(s16X[ChOffset + 8] + s16X[ChOffset + 64 + 8]); \ + s64Temp += (int64_t)WIND_8_SUBBANDS_8_1 * \ + (int64_t)(s16X[ChOffset + 16 + 8] + s16X[ChOffset + 48 + 8]); \ + s64Temp += (int64_t)WIND_8_SUBBANDS_8_2 * (int64_t)s16X[ChOffset + 32 + 8]; \ + s32DCTY[8] = (int32_t)(s64Temp >> 16); \ } -#define WINDOW_ACCU_4_0 \ - { \ - s64Temp = (int64_t)WIND_4_SUBBANDS_0_1 * \ - (int64_t)(s16X[ChOffset + 8] - s16X[ChOffset + 32]); \ - s64Temp += (int64_t)WIND_4_SUBBANDS_0_2 * \ - (int64_t)(s16X[ChOffset + 16] - s16X[ChOffset + 24]); \ - s32DCTY[0] = (int32_t)(s64Temp >> 16); \ +#define WINDOW_ACCU_4_0 \ + { \ + s64Temp = (int64_t)WIND_4_SUBBANDS_0_1 * (int64_t)(s16X[ChOffset + 8] - s16X[ChOffset + 32]); \ + s64Temp += \ + (int64_t)WIND_4_SUBBANDS_0_2 * (int64_t)(s16X[ChOffset + 16] - s16X[ChOffset + 24]); \ + s32DCTY[0] = (int32_t)(s64Temp >> 16); \ } -#define WINDOW_ACCU_4_1_7 \ - { \ - s64Temp = (int64_t)WIND_4_SUBBANDS_1_0 * (int64_t)s16X[ChOffset + 1]; \ - s64Temp2 = \ - (int64_t)WIND_4_SUBBANDS_1_0 * (int64_t)s16X[ChOffset + 32 + 7]; \ - s64Temp += (int64_t)WIND_4_SUBBANDS_1_1 * (int64_t)s16X[ChOffset + 8 + 1]; \ - s64Temp2 += \ - (int64_t)WIND_4_SUBBANDS_1_1 * (int64_t)s16X[ChOffset + 24 + 7]; \ - s64Temp += \ - (int64_t)WIND_4_SUBBANDS_1_2 * (int64_t)s16X[ChOffset + 16 + 1]; \ - s64Temp2 += \ - (int64_t)WIND_4_SUBBANDS_1_2 * (int64_t)s16X[ChOffset + 16 + 7]; \ - s64Temp += \ - (int64_t)WIND_4_SUBBANDS_1_3 * (int64_t)s16X[ChOffset + 24 + 1]; \ - s64Temp2 += \ - (int64_t)WIND_4_SUBBANDS_1_3 * (int64_t)s16X[ChOffset + 8 + 7]; \ - s64Temp += \ - (int64_t)WIND_4_SUBBANDS_1_4 * (int64_t)s16X[ChOffset + 32 + 1]; \ - s64Temp2 += (int64_t)WIND_4_SUBBANDS_1_4 * (int64_t)s16X[ChOffset + 7]; \ - s32DCTY[1] = (int32_t)(s64Temp >> 16); \ - s32DCTY[7] = (int32_t)(s64Temp2 >> 16); \ +#define WINDOW_ACCU_4_1_7 \ + { \ + s64Temp = (int64_t)WIND_4_SUBBANDS_1_0 * (int64_t)s16X[ChOffset + 1]; \ + s64Temp2 = (int64_t)WIND_4_SUBBANDS_1_0 * (int64_t)s16X[ChOffset + 32 + 7]; \ + s64Temp += (int64_t)WIND_4_SUBBANDS_1_1 * (int64_t)s16X[ChOffset + 8 + 1]; \ + s64Temp2 += (int64_t)WIND_4_SUBBANDS_1_1 * (int64_t)s16X[ChOffset + 24 + 7]; \ + s64Temp += (int64_t)WIND_4_SUBBANDS_1_2 * (int64_t)s16X[ChOffset + 16 + 1]; \ + s64Temp2 += (int64_t)WIND_4_SUBBANDS_1_2 * (int64_t)s16X[ChOffset + 16 + 7]; \ + s64Temp += (int64_t)WIND_4_SUBBANDS_1_3 * (int64_t)s16X[ChOffset + 24 + 1]; \ + s64Temp2 += (int64_t)WIND_4_SUBBANDS_1_3 * (int64_t)s16X[ChOffset + 8 + 7]; \ + s64Temp += (int64_t)WIND_4_SUBBANDS_1_4 * (int64_t)s16X[ChOffset + 32 + 1]; \ + s64Temp2 += (int64_t)WIND_4_SUBBANDS_1_4 * (int64_t)s16X[ChOffset + 7]; \ + s32DCTY[1] = (int32_t)(s64Temp >> 16); \ + s32DCTY[7] = (int32_t)(s64Temp2 >> 16); \ } -#define WINDOW_ACCU_4_2_6 \ - { \ - s64Temp = (int64_t)WIND_4_SUBBANDS_2_0 * (int64_t)s16X[ChOffset + 2]; \ - s64Temp2 = \ - (int64_t)WIND_4_SUBBANDS_2_0 * (int64_t)s16X[ChOffset + 32 + 6]; \ - s64Temp += (int64_t)WIND_4_SUBBANDS_2_1 * (int64_t)s16X[ChOffset + 8 + 2]; \ - s64Temp2 += \ - (int64_t)WIND_4_SUBBANDS_2_1 * (int64_t)s16X[ChOffset + 24 + 6]; \ - s64Temp += \ - (int64_t)WIND_4_SUBBANDS_2_2 * (int64_t)s16X[ChOffset + 16 + 2]; \ - s64Temp2 += \ - (int64_t)WIND_4_SUBBANDS_2_2 * (int64_t)s16X[ChOffset + 16 + 6]; \ - s64Temp += \ - (int64_t)WIND_4_SUBBANDS_2_3 * (int64_t)s16X[ChOffset + 24 + 2]; \ - s64Temp2 += \ - (int64_t)WIND_4_SUBBANDS_2_3 * (int64_t)s16X[ChOffset + 8 + 6]; \ - s64Temp += \ - (int64_t)WIND_4_SUBBANDS_2_4 * (int64_t)s16X[ChOffset + 32 + 2]; \ - s64Temp2 += (int64_t)WIND_4_SUBBANDS_2_4 * (int64_t)s16X[ChOffset + 6]; \ - s32DCTY[2] = (int32_t)(s64Temp >> 16); \ - s32DCTY[6] = (int32_t)(s64Temp2 >> 16); \ +#define WINDOW_ACCU_4_2_6 \ + { \ + s64Temp = (int64_t)WIND_4_SUBBANDS_2_0 * (int64_t)s16X[ChOffset + 2]; \ + s64Temp2 = (int64_t)WIND_4_SUBBANDS_2_0 * (int64_t)s16X[ChOffset + 32 + 6]; \ + s64Temp += (int64_t)WIND_4_SUBBANDS_2_1 * (int64_t)s16X[ChOffset + 8 + 2]; \ + s64Temp2 += (int64_t)WIND_4_SUBBANDS_2_1 * (int64_t)s16X[ChOffset + 24 + 6]; \ + s64Temp += (int64_t)WIND_4_SUBBANDS_2_2 * (int64_t)s16X[ChOffset + 16 + 2]; \ + s64Temp2 += (int64_t)WIND_4_SUBBANDS_2_2 * (int64_t)s16X[ChOffset + 16 + 6]; \ + s64Temp += (int64_t)WIND_4_SUBBANDS_2_3 * (int64_t)s16X[ChOffset + 24 + 2]; \ + s64Temp2 += (int64_t)WIND_4_SUBBANDS_2_3 * (int64_t)s16X[ChOffset + 8 + 6]; \ + s64Temp += (int64_t)WIND_4_SUBBANDS_2_4 * (int64_t)s16X[ChOffset + 32 + 2]; \ + s64Temp2 += (int64_t)WIND_4_SUBBANDS_2_4 * (int64_t)s16X[ChOffset + 6]; \ + s32DCTY[2] = (int32_t)(s64Temp >> 16); \ + s32DCTY[6] = (int32_t)(s64Temp2 >> 16); \ } -#define WINDOW_ACCU_4_3_5 \ - { \ - s64Temp = (int64_t)WIND_4_SUBBANDS_3_0 * (int64_t)s16X[ChOffset + 3]; \ - s64Temp2 = \ - (int64_t)WIND_4_SUBBANDS_3_0 * (int64_t)s16X[ChOffset + 32 + 5]; \ - s64Temp += (int64_t)WIND_4_SUBBANDS_3_1 * (int64_t)s16X[ChOffset + 8 + 3]; \ - s64Temp2 += \ - (int64_t)WIND_4_SUBBANDS_3_1 * (int64_t)s16X[ChOffset + 24 + 5]; \ - s64Temp += \ - (int64_t)WIND_4_SUBBANDS_3_2 * (int64_t)s16X[ChOffset + 16 + 3]; \ - s64Temp2 += \ - (int64_t)WIND_4_SUBBANDS_3_2 * (int64_t)s16X[ChOffset + 16 + 5]; \ - s64Temp += \ - (int64_t)WIND_4_SUBBANDS_3_3 * (int64_t)s16X[ChOffset + 24 + 3]; \ - s64Temp2 += \ - (int64_t)WIND_4_SUBBANDS_3_3 * (int64_t)s16X[ChOffset + 8 + 5]; \ - s64Temp += \ - (int64_t)WIND_4_SUBBANDS_3_4 * (int64_t)s16X[ChOffset + 32 + 3]; \ - s64Temp2 += (int64_t)WIND_4_SUBBANDS_3_4 * (int64_t)s16X[ChOffset + 5]; \ - s32DCTY[3] = (int32_t)(s64Temp >> 16); \ - s32DCTY[5] = (int32_t)(s64Temp2 >> 16); \ +#define WINDOW_ACCU_4_3_5 \ + { \ + s64Temp = (int64_t)WIND_4_SUBBANDS_3_0 * (int64_t)s16X[ChOffset + 3]; \ + s64Temp2 = (int64_t)WIND_4_SUBBANDS_3_0 * (int64_t)s16X[ChOffset + 32 + 5]; \ + s64Temp += (int64_t)WIND_4_SUBBANDS_3_1 * (int64_t)s16X[ChOffset + 8 + 3]; \ + s64Temp2 += (int64_t)WIND_4_SUBBANDS_3_1 * (int64_t)s16X[ChOffset + 24 + 5]; \ + s64Temp += (int64_t)WIND_4_SUBBANDS_3_2 * (int64_t)s16X[ChOffset + 16 + 3]; \ + s64Temp2 += (int64_t)WIND_4_SUBBANDS_3_2 * (int64_t)s16X[ChOffset + 16 + 5]; \ + s64Temp += (int64_t)WIND_4_SUBBANDS_3_3 * (int64_t)s16X[ChOffset + 24 + 3]; \ + s64Temp2 += (int64_t)WIND_4_SUBBANDS_3_3 * (int64_t)s16X[ChOffset + 8 + 5]; \ + s64Temp += (int64_t)WIND_4_SUBBANDS_3_4 * (int64_t)s16X[ChOffset + 32 + 3]; \ + s64Temp2 += (int64_t)WIND_4_SUBBANDS_3_4 * (int64_t)s16X[ChOffset + 5]; \ + s32DCTY[3] = (int32_t)(s64Temp >> 16); \ + s32DCTY[5] = (int32_t)(s64Temp2 >> 16); \ } -#define WINDOW_ACCU_4_4 \ - { \ - s64Temp = (int64_t)WIND_4_SUBBANDS_4_0 * \ - (int64_t)(s16X[ChOffset + 4] + s16X[ChOffset + 4 + 32]); \ - s64Temp += (int64_t)WIND_4_SUBBANDS_4_1 * \ - (int64_t)(s16X[ChOffset + 4 + 8] + s16X[ChOffset + 4 + 24]); \ - s64Temp += \ - (int64_t)WIND_4_SUBBANDS_4_2 * (int64_t)s16X[ChOffset + 4 + 16]; \ - s32DCTY[4] = (int32_t)(s64Temp >> 16); \ +#define WINDOW_ACCU_4_4 \ + { \ + s64Temp = (int64_t)WIND_4_SUBBANDS_4_0 * \ + (int64_t)(s16X[ChOffset + 4] + s16X[ChOffset + 4 + 32]); \ + s64Temp += (int64_t)WIND_4_SUBBANDS_4_1 * \ + (int64_t)(s16X[ChOffset + 4 + 8] + s16X[ChOffset + 4 + 24]); \ + s64Temp += (int64_t)WIND_4_SUBBANDS_4_2 * (int64_t)s16X[ChOffset + 4 + 16]; \ + s32DCTY[4] = (int32_t)(s64Temp >> 16); \ } #else /* SBC_IS_64_MULT_IN_WINDOW_ACCU == FALSE */ -#define WINDOW_ACCU_8_0 \ - { \ - s32Temp = (int32_t)WIND_8_SUBBANDS_0_1 * \ - (int32_t)(s16X[ChOffset + 16] - s16X[ChOffset + 64]); \ - s32Temp += (int32_t)WIND_8_SUBBANDS_0_2 * \ - (int32_t)(s16X[ChOffset + 32] - s16X[ChOffset + 48]); \ - s32DCTY[0] = (int32_t)s32Temp; \ +#define WINDOW_ACCU_8_0 \ + { \ + s32Temp = (int32_t)WIND_8_SUBBANDS_0_1 * (int32_t)(s16X[ChOffset + 16] - s16X[ChOffset + 64]); \ + s32Temp += \ + (int32_t)WIND_8_SUBBANDS_0_2 * (int32_t)(s16X[ChOffset + 32] - s16X[ChOffset + 48]); \ + s32DCTY[0] = (int32_t)s32Temp; \ } -#define WINDOW_ACCU_8_1_15 \ - { \ - s32Temp = (int32_t)WIND_8_SUBBANDS_1_0 * (int32_t)s16X[ChOffset + 1]; \ - s32Temp2 = \ - (int32_t)WIND_8_SUBBANDS_1_0 * (int32_t)s16X[ChOffset + 64 + 15]; \ - s32Temp += \ - (int32_t)WIND_8_SUBBANDS_1_1 * (int32_t)s16X[ChOffset + 16 + 1]; \ - s32Temp2 += \ - (int32_t)WIND_8_SUBBANDS_1_1 * (int32_t)s16X[ChOffset + 48 + 15]; \ - s32Temp += \ - (int32_t)WIND_8_SUBBANDS_1_2 * (int32_t)s16X[ChOffset + 32 + 1]; \ - s32Temp2 += \ - (int32_t)WIND_8_SUBBANDS_1_2 * (int32_t)s16X[ChOffset + 32 + 15]; \ - s32Temp += \ - (int32_t)WIND_8_SUBBANDS_1_3 * (int32_t)s16X[ChOffset + 48 + 1]; \ - s32Temp2 += \ - (int32_t)WIND_8_SUBBANDS_1_3 * (int32_t)s16X[ChOffset + 16 + 15]; \ - s32Temp += \ - (int32_t)WIND_8_SUBBANDS_1_4 * (int32_t)s16X[ChOffset + 64 + 1]; \ - s32Temp2 += (int32_t)WIND_8_SUBBANDS_1_4 * (int32_t)s16X[ChOffset + 15]; \ - s32DCTY[1] = (int32_t)s32Temp; \ - s32DCTY[15] = (int32_t)s32Temp2; \ +#define WINDOW_ACCU_8_1_15 \ + { \ + s32Temp = (int32_t)WIND_8_SUBBANDS_1_0 * (int32_t)s16X[ChOffset + 1]; \ + s32Temp2 = (int32_t)WIND_8_SUBBANDS_1_0 * (int32_t)s16X[ChOffset + 64 + 15]; \ + s32Temp += (int32_t)WIND_8_SUBBANDS_1_1 * (int32_t)s16X[ChOffset + 16 + 1]; \ + s32Temp2 += (int32_t)WIND_8_SUBBANDS_1_1 * (int32_t)s16X[ChOffset + 48 + 15]; \ + s32Temp += (int32_t)WIND_8_SUBBANDS_1_2 * (int32_t)s16X[ChOffset + 32 + 1]; \ + s32Temp2 += (int32_t)WIND_8_SUBBANDS_1_2 * (int32_t)s16X[ChOffset + 32 + 15]; \ + s32Temp += (int32_t)WIND_8_SUBBANDS_1_3 * (int32_t)s16X[ChOffset + 48 + 1]; \ + s32Temp2 += (int32_t)WIND_8_SUBBANDS_1_3 * (int32_t)s16X[ChOffset + 16 + 15]; \ + s32Temp += (int32_t)WIND_8_SUBBANDS_1_4 * (int32_t)s16X[ChOffset + 64 + 1]; \ + s32Temp2 += (int32_t)WIND_8_SUBBANDS_1_4 * (int32_t)s16X[ChOffset + 15]; \ + s32DCTY[1] = (int32_t)s32Temp; \ + s32DCTY[15] = (int32_t)s32Temp2; \ } -#define WINDOW_ACCU_8_2_14 \ - { \ - s32Temp = (int32_t)WIND_8_SUBBANDS_2_0 * (int32_t)s16X[ChOffset + 2]; \ - s32Temp2 = \ - (int32_t)WIND_8_SUBBANDS_2_0 * (int32_t)s16X[ChOffset + 64 + 14]; \ - s32Temp += \ - (int32_t)WIND_8_SUBBANDS_2_1 * (int32_t)s16X[ChOffset + 16 + 2]; \ - s32Temp2 += \ - (int32_t)WIND_8_SUBBANDS_2_1 * (int32_t)s16X[ChOffset + 48 + 14]; \ - s32Temp += \ - (int32_t)WIND_8_SUBBANDS_2_2 * (int32_t)s16X[ChOffset + 32 + 2]; \ - s32Temp2 += \ - (int32_t)WIND_8_SUBBANDS_2_2 * (int32_t)s16X[ChOffset + 32 + 14]; \ - s32Temp += \ - (int32_t)WIND_8_SUBBANDS_2_3 * (int32_t)s16X[ChOffset + 48 + 2]; \ - s32Temp2 += \ - (int32_t)WIND_8_SUBBANDS_2_3 * (int32_t)s16X[ChOffset + 16 + 14]; \ - s32Temp += \ - (int32_t)WIND_8_SUBBANDS_2_4 * (int32_t)s16X[ChOffset + 64 + 2]; \ - s32Temp2 += (int32_t)WIND_8_SUBBANDS_2_4 * (int32_t)s16X[ChOffset + 14]; \ - s32DCTY[2] = (int32_t)s32Temp; \ - s32DCTY[14] = (int32_t)s32Temp2; \ +#define WINDOW_ACCU_8_2_14 \ + { \ + s32Temp = (int32_t)WIND_8_SUBBANDS_2_0 * (int32_t)s16X[ChOffset + 2]; \ + s32Temp2 = (int32_t)WIND_8_SUBBANDS_2_0 * (int32_t)s16X[ChOffset + 64 + 14]; \ + s32Temp += (int32_t)WIND_8_SUBBANDS_2_1 * (int32_t)s16X[ChOffset + 16 + 2]; \ + s32Temp2 += (int32_t)WIND_8_SUBBANDS_2_1 * (int32_t)s16X[ChOffset + 48 + 14]; \ + s32Temp += (int32_t)WIND_8_SUBBANDS_2_2 * (int32_t)s16X[ChOffset + 32 + 2]; \ + s32Temp2 += (int32_t)WIND_8_SUBBANDS_2_2 * (int32_t)s16X[ChOffset + 32 + 14]; \ + s32Temp += (int32_t)WIND_8_SUBBANDS_2_3 * (int32_t)s16X[ChOffset + 48 + 2]; \ + s32Temp2 += (int32_t)WIND_8_SUBBANDS_2_3 * (int32_t)s16X[ChOffset + 16 + 14]; \ + s32Temp += (int32_t)WIND_8_SUBBANDS_2_4 * (int32_t)s16X[ChOffset + 64 + 2]; \ + s32Temp2 += (int32_t)WIND_8_SUBBANDS_2_4 * (int32_t)s16X[ChOffset + 14]; \ + s32DCTY[2] = (int32_t)s32Temp; \ + s32DCTY[14] = (int32_t)s32Temp2; \ } -#define WINDOW_ACCU_8_3_13 \ - { \ - s32Temp = (int32_t)WIND_8_SUBBANDS_3_0 * (int32_t)s16X[ChOffset + 3]; \ - s32Temp2 = \ - (int32_t)WIND_8_SUBBANDS_3_0 * (int32_t)s16X[ChOffset + 64 + 13]; \ - s32Temp += \ - (int32_t)WIND_8_SUBBANDS_3_1 * (int32_t)s16X[ChOffset + 16 + 3]; \ - s32Temp2 += \ - (int32_t)WIND_8_SUBBANDS_3_1 * (int32_t)s16X[ChOffset + 48 + 13]; \ - s32Temp += \ - (int32_t)WIND_8_SUBBANDS_3_2 * (int32_t)s16X[ChOffset + 32 + 3]; \ - s32Temp2 += \ - (int32_t)WIND_8_SUBBANDS_3_2 * (int32_t)s16X[ChOffset + 32 + 13]; \ - s32Temp += \ - (int32_t)WIND_8_SUBBANDS_3_3 * (int32_t)s16X[ChOffset + 48 + 3]; \ - s32Temp2 += \ - (int32_t)WIND_8_SUBBANDS_3_3 * (int32_t)s16X[ChOffset + 16 + 13]; \ - s32Temp += \ - (int32_t)WIND_8_SUBBANDS_3_4 * (int32_t)s16X[ChOffset + 64 + 3]; \ - s32Temp2 += (int32_t)WIND_8_SUBBANDS_3_4 * (int32_t)s16X[ChOffset + 13]; \ - s32DCTY[3] = (int32_t)s32Temp; \ - s32DCTY[13] = (int32_t)s32Temp2; \ +#define WINDOW_ACCU_8_3_13 \ + { \ + s32Temp = (int32_t)WIND_8_SUBBANDS_3_0 * (int32_t)s16X[ChOffset + 3]; \ + s32Temp2 = (int32_t)WIND_8_SUBBANDS_3_0 * (int32_t)s16X[ChOffset + 64 + 13]; \ + s32Temp += (int32_t)WIND_8_SUBBANDS_3_1 * (int32_t)s16X[ChOffset + 16 + 3]; \ + s32Temp2 += (int32_t)WIND_8_SUBBANDS_3_1 * (int32_t)s16X[ChOffset + 48 + 13]; \ + s32Temp += (int32_t)WIND_8_SUBBANDS_3_2 * (int32_t)s16X[ChOffset + 32 + 3]; \ + s32Temp2 += (int32_t)WIND_8_SUBBANDS_3_2 * (int32_t)s16X[ChOffset + 32 + 13]; \ + s32Temp += (int32_t)WIND_8_SUBBANDS_3_3 * (int32_t)s16X[ChOffset + 48 + 3]; \ + s32Temp2 += (int32_t)WIND_8_SUBBANDS_3_3 * (int32_t)s16X[ChOffset + 16 + 13]; \ + s32Temp += (int32_t)WIND_8_SUBBANDS_3_4 * (int32_t)s16X[ChOffset + 64 + 3]; \ + s32Temp2 += (int32_t)WIND_8_SUBBANDS_3_4 * (int32_t)s16X[ChOffset + 13]; \ + s32DCTY[3] = (int32_t)s32Temp; \ + s32DCTY[13] = (int32_t)s32Temp2; \ } -#define WINDOW_ACCU_8_4_12 \ - { \ - s32Temp = (int32_t)WIND_8_SUBBANDS_4_0 * (int32_t)s16X[ChOffset + 4]; \ - s32Temp2 = \ - (int32_t)WIND_8_SUBBANDS_4_0 * (int32_t)s16X[ChOffset + 64 + 12]; \ - s32Temp += \ - (int32_t)WIND_8_SUBBANDS_4_1 * (int32_t)s16X[ChOffset + 16 + 4]; \ - s32Temp2 += \ - (int32_t)WIND_8_SUBBANDS_4_1 * (int32_t)s16X[ChOffset + 48 + 12]; \ - s32Temp += \ - (int32_t)WIND_8_SUBBANDS_4_2 * (int32_t)s16X[ChOffset + 32 + 4]; \ - s32Temp2 += \ - (int32_t)WIND_8_SUBBANDS_4_2 * (int32_t)s16X[ChOffset + 32 + 12]; \ - s32Temp += \ - (int32_t)WIND_8_SUBBANDS_4_3 * (int32_t)s16X[ChOffset + 48 + 4]; \ - s32Temp2 += \ - (int32_t)WIND_8_SUBBANDS_4_3 * (int32_t)s16X[ChOffset + 16 + 12]; \ - s32Temp += \ - (int32_t)WIND_8_SUBBANDS_4_4 * (int32_t)s16X[ChOffset + 64 + 4]; \ - s32Temp2 += (int32_t)WIND_8_SUBBANDS_4_4 * (int32_t)s16X[ChOffset + 12]; \ - s32DCTY[4] = (int32_t)s32Temp; \ - s32DCTY[12] = (int32_t)s32Temp2; \ +#define WINDOW_ACCU_8_4_12 \ + { \ + s32Temp = (int32_t)WIND_8_SUBBANDS_4_0 * (int32_t)s16X[ChOffset + 4]; \ + s32Temp2 = (int32_t)WIND_8_SUBBANDS_4_0 * (int32_t)s16X[ChOffset + 64 + 12]; \ + s32Temp += (int32_t)WIND_8_SUBBANDS_4_1 * (int32_t)s16X[ChOffset + 16 + 4]; \ + s32Temp2 += (int32_t)WIND_8_SUBBANDS_4_1 * (int32_t)s16X[ChOffset + 48 + 12]; \ + s32Temp += (int32_t)WIND_8_SUBBANDS_4_2 * (int32_t)s16X[ChOffset + 32 + 4]; \ + s32Temp2 += (int32_t)WIND_8_SUBBANDS_4_2 * (int32_t)s16X[ChOffset + 32 + 12]; \ + s32Temp += (int32_t)WIND_8_SUBBANDS_4_3 * (int32_t)s16X[ChOffset + 48 + 4]; \ + s32Temp2 += (int32_t)WIND_8_SUBBANDS_4_3 * (int32_t)s16X[ChOffset + 16 + 12]; \ + s32Temp += (int32_t)WIND_8_SUBBANDS_4_4 * (int32_t)s16X[ChOffset + 64 + 4]; \ + s32Temp2 += (int32_t)WIND_8_SUBBANDS_4_4 * (int32_t)s16X[ChOffset + 12]; \ + s32DCTY[4] = (int32_t)s32Temp; \ + s32DCTY[12] = (int32_t)s32Temp2; \ } -#define WINDOW_ACCU_8_5_11 \ - { \ - s32Temp = (int32_t)WIND_8_SUBBANDS_5_0 * (int32_t)s16X[ChOffset + 5]; \ - s32Temp2 = \ - (int32_t)WIND_8_SUBBANDS_5_0 * (int32_t)s16X[ChOffset + 64 + 11]; \ - s32Temp += \ - (int32_t)WIND_8_SUBBANDS_5_1 * (int32_t)s16X[ChOffset + 16 + 5]; \ - s32Temp2 += \ - (int32_t)WIND_8_SUBBANDS_5_1 * (int32_t)s16X[ChOffset + 48 + 11]; \ - s32Temp += \ - (int32_t)WIND_8_SUBBANDS_5_2 * (int32_t)s16X[ChOffset + 32 + 5]; \ - s32Temp2 += \ - (int32_t)WIND_8_SUBBANDS_5_2 * (int32_t)s16X[ChOffset + 32 + 11]; \ - s32Temp += \ - (int32_t)WIND_8_SUBBANDS_5_3 * (int32_t)s16X[ChOffset + 48 + 5]; \ - s32Temp2 += \ - (int32_t)WIND_8_SUBBANDS_5_3 * (int32_t)s16X[ChOffset + 16 + 11]; \ - s32Temp += \ - (int32_t)WIND_8_SUBBANDS_5_4 * (int32_t)s16X[ChOffset + 64 + 5]; \ - s32Temp2 += (int32_t)WIND_8_SUBBANDS_5_4 * (int32_t)s16X[ChOffset + 11]; \ - s32DCTY[5] = (int32_t)s32Temp; \ - s32DCTY[11] = (int32_t)s32Temp2; \ +#define WINDOW_ACCU_8_5_11 \ + { \ + s32Temp = (int32_t)WIND_8_SUBBANDS_5_0 * (int32_t)s16X[ChOffset + 5]; \ + s32Temp2 = (int32_t)WIND_8_SUBBANDS_5_0 * (int32_t)s16X[ChOffset + 64 + 11]; \ + s32Temp += (int32_t)WIND_8_SUBBANDS_5_1 * (int32_t)s16X[ChOffset + 16 + 5]; \ + s32Temp2 += (int32_t)WIND_8_SUBBANDS_5_1 * (int32_t)s16X[ChOffset + 48 + 11]; \ + s32Temp += (int32_t)WIND_8_SUBBANDS_5_2 * (int32_t)s16X[ChOffset + 32 + 5]; \ + s32Temp2 += (int32_t)WIND_8_SUBBANDS_5_2 * (int32_t)s16X[ChOffset + 32 + 11]; \ + s32Temp += (int32_t)WIND_8_SUBBANDS_5_3 * (int32_t)s16X[ChOffset + 48 + 5]; \ + s32Temp2 += (int32_t)WIND_8_SUBBANDS_5_3 * (int32_t)s16X[ChOffset + 16 + 11]; \ + s32Temp += (int32_t)WIND_8_SUBBANDS_5_4 * (int32_t)s16X[ChOffset + 64 + 5]; \ + s32Temp2 += (int32_t)WIND_8_SUBBANDS_5_4 * (int32_t)s16X[ChOffset + 11]; \ + s32DCTY[5] = (int32_t)s32Temp; \ + s32DCTY[11] = (int32_t)s32Temp2; \ } -#define WINDOW_ACCU_8_6_10 \ - { \ - s32Temp = (int32_t)WIND_8_SUBBANDS_6_0 * (int32_t)s16X[ChOffset + 6]; \ - s32Temp2 = \ - (int32_t)WIND_8_SUBBANDS_6_0 * (int32_t)s16X[ChOffset + 64 + 10]; \ - s32Temp += \ - (int32_t)WIND_8_SUBBANDS_6_1 * (int32_t)s16X[ChOffset + 16 + 6]; \ - s32Temp2 += \ - (int32_t)WIND_8_SUBBANDS_6_1 * (int32_t)s16X[ChOffset + 48 + 10]; \ - s32Temp += \ - (int32_t)WIND_8_SUBBANDS_6_2 * (int32_t)s16X[ChOffset + 32 + 6]; \ - s32Temp2 += \ - (int32_t)WIND_8_SUBBANDS_6_2 * (int32_t)s16X[ChOffset + 32 + 10]; \ - s32Temp += \ - (int32_t)WIND_8_SUBBANDS_6_3 * (int32_t)s16X[ChOffset + 48 + 6]; \ - s32Temp2 += \ - (int32_t)WIND_8_SUBBANDS_6_3 * (int32_t)s16X[ChOffset + 16 + 10]; \ - s32Temp += \ - (int32_t)WIND_8_SUBBANDS_6_4 * (int32_t)s16X[ChOffset + 64 + 6]; \ - s32Temp2 += (int32_t)WIND_8_SUBBANDS_6_4 * (int32_t)s16X[ChOffset + 10]; \ - s32DCTY[6] = (int32_t)s32Temp; \ - s32DCTY[10] = (int32_t)s32Temp2; \ +#define WINDOW_ACCU_8_6_10 \ + { \ + s32Temp = (int32_t)WIND_8_SUBBANDS_6_0 * (int32_t)s16X[ChOffset + 6]; \ + s32Temp2 = (int32_t)WIND_8_SUBBANDS_6_0 * (int32_t)s16X[ChOffset + 64 + 10]; \ + s32Temp += (int32_t)WIND_8_SUBBANDS_6_1 * (int32_t)s16X[ChOffset + 16 + 6]; \ + s32Temp2 += (int32_t)WIND_8_SUBBANDS_6_1 * (int32_t)s16X[ChOffset + 48 + 10]; \ + s32Temp += (int32_t)WIND_8_SUBBANDS_6_2 * (int32_t)s16X[ChOffset + 32 + 6]; \ + s32Temp2 += (int32_t)WIND_8_SUBBANDS_6_2 * (int32_t)s16X[ChOffset + 32 + 10]; \ + s32Temp += (int32_t)WIND_8_SUBBANDS_6_3 * (int32_t)s16X[ChOffset + 48 + 6]; \ + s32Temp2 += (int32_t)WIND_8_SUBBANDS_6_3 * (int32_t)s16X[ChOffset + 16 + 10]; \ + s32Temp += (int32_t)WIND_8_SUBBANDS_6_4 * (int32_t)s16X[ChOffset + 64 + 6]; \ + s32Temp2 += (int32_t)WIND_8_SUBBANDS_6_4 * (int32_t)s16X[ChOffset + 10]; \ + s32DCTY[6] = (int32_t)s32Temp; \ + s32DCTY[10] = (int32_t)s32Temp2; \ } -#define WINDOW_ACCU_8_7_9 \ - { \ - s32Temp = (int32_t)WIND_8_SUBBANDS_7_0 * (int32_t)s16X[ChOffset + 7]; \ - s32Temp2 = \ - (int32_t)WIND_8_SUBBANDS_7_0 * (int32_t)s16X[ChOffset + 64 + 9]; \ - s32Temp += \ - (int32_t)WIND_8_SUBBANDS_7_1 * (int32_t)s16X[ChOffset + 16 + 7]; \ - s32Temp2 += \ - (int32_t)WIND_8_SUBBANDS_7_1 * (int32_t)s16X[ChOffset + 48 + 9]; \ - s32Temp += \ - (int32_t)WIND_8_SUBBANDS_7_2 * (int32_t)s16X[ChOffset + 32 + 7]; \ - s32Temp2 += \ - (int32_t)WIND_8_SUBBANDS_7_2 * (int32_t)s16X[ChOffset + 32 + 9]; \ - s32Temp += \ - (int32_t)WIND_8_SUBBANDS_7_3 * (int32_t)s16X[ChOffset + 48 + 7]; \ - s32Temp2 += \ - (int32_t)WIND_8_SUBBANDS_7_3 * (int32_t)s16X[ChOffset + 16 + 9]; \ - s32Temp += \ - (int32_t)WIND_8_SUBBANDS_7_4 * (int32_t)s16X[ChOffset + 64 + 7]; \ - s32Temp2 += (int32_t)WIND_8_SUBBANDS_7_4 * (int32_t)s16X[ChOffset + 9]; \ - s32DCTY[7] = (int32_t)s32Temp; \ - s32DCTY[9] = (int32_t)s32Temp2; \ +#define WINDOW_ACCU_8_7_9 \ + { \ + s32Temp = (int32_t)WIND_8_SUBBANDS_7_0 * (int32_t)s16X[ChOffset + 7]; \ + s32Temp2 = (int32_t)WIND_8_SUBBANDS_7_0 * (int32_t)s16X[ChOffset + 64 + 9]; \ + s32Temp += (int32_t)WIND_8_SUBBANDS_7_1 * (int32_t)s16X[ChOffset + 16 + 7]; \ + s32Temp2 += (int32_t)WIND_8_SUBBANDS_7_1 * (int32_t)s16X[ChOffset + 48 + 9]; \ + s32Temp += (int32_t)WIND_8_SUBBANDS_7_2 * (int32_t)s16X[ChOffset + 32 + 7]; \ + s32Temp2 += (int32_t)WIND_8_SUBBANDS_7_2 * (int32_t)s16X[ChOffset + 32 + 9]; \ + s32Temp += (int32_t)WIND_8_SUBBANDS_7_3 * (int32_t)s16X[ChOffset + 48 + 7]; \ + s32Temp2 += (int32_t)WIND_8_SUBBANDS_7_3 * (int32_t)s16X[ChOffset + 16 + 9]; \ + s32Temp += (int32_t)WIND_8_SUBBANDS_7_4 * (int32_t)s16X[ChOffset + 64 + 7]; \ + s32Temp2 += (int32_t)WIND_8_SUBBANDS_7_4 * (int32_t)s16X[ChOffset + 9]; \ + s32DCTY[7] = (int32_t)s32Temp; \ + s32DCTY[9] = (int32_t)s32Temp2; \ } -#define WINDOW_ACCU_8_8 \ - { \ - s32Temp = (int32_t)WIND_8_SUBBANDS_8_0 * \ - (int32_t)(s16X[ChOffset + 8] + s16X[ChOffset + 64 + 8]); \ - s32Temp += (int32_t)WIND_8_SUBBANDS_8_1 * \ - (int32_t)(s16X[ChOffset + 16 + 8] + s16X[ChOffset + 48 + 8]); \ - s32Temp += \ - (int32_t)WIND_8_SUBBANDS_8_2 * (int32_t)s16X[ChOffset + 32 + 8]; \ - s32DCTY[8] = (int32_t)s32Temp; \ +#define WINDOW_ACCU_8_8 \ + { \ + s32Temp = (int32_t)WIND_8_SUBBANDS_8_0 * \ + (int32_t)(s16X[ChOffset + 8] + s16X[ChOffset + 64 + 8]); \ + s32Temp += (int32_t)WIND_8_SUBBANDS_8_1 * \ + (int32_t)(s16X[ChOffset + 16 + 8] + s16X[ChOffset + 48 + 8]); \ + s32Temp += (int32_t)WIND_8_SUBBANDS_8_2 * (int32_t)s16X[ChOffset + 32 + 8]; \ + s32DCTY[8] = (int32_t)s32Temp; \ } -#define WINDOW_ACCU_4_0 \ - { \ - s32Temp = (int32_t)WIND_4_SUBBANDS_0_1 * \ - (int32_t)(s16X[ChOffset + 8] - s16X[ChOffset + 32]); \ - s32Temp += (int32_t)WIND_4_SUBBANDS_0_2 * \ - (int32_t)(s16X[ChOffset + 16] - s16X[ChOffset + 24]); \ - s32DCTY[0] = (int32_t)(s32Temp); \ +#define WINDOW_ACCU_4_0 \ + { \ + s32Temp = (int32_t)WIND_4_SUBBANDS_0_1 * (int32_t)(s16X[ChOffset + 8] - s16X[ChOffset + 32]); \ + s32Temp += \ + (int32_t)WIND_4_SUBBANDS_0_2 * (int32_t)(s16X[ChOffset + 16] - s16X[ChOffset + 24]); \ + s32DCTY[0] = (int32_t)(s32Temp); \ } -#define WINDOW_ACCU_4_1_7 \ - { \ - s32Temp = (int32_t)WIND_4_SUBBANDS_1_0 * (int32_t)s16X[ChOffset + 1]; \ - s32Temp2 = \ - (int32_t)WIND_4_SUBBANDS_1_0 * (int32_t)s16X[ChOffset + 32 + 7]; \ - s32Temp += (int32_t)WIND_4_SUBBANDS_1_1 * (int32_t)s16X[ChOffset + 8 + 1]; \ - s32Temp2 += \ - (int32_t)WIND_4_SUBBANDS_1_1 * (int32_t)s16X[ChOffset + 24 + 7]; \ - s32Temp += \ - (int32_t)WIND_4_SUBBANDS_1_2 * (int32_t)s16X[ChOffset + 16 + 1]; \ - s32Temp2 += \ - (int32_t)WIND_4_SUBBANDS_1_2 * (int32_t)s16X[ChOffset + 16 + 7]; \ - s32Temp += \ - (int32_t)WIND_4_SUBBANDS_1_3 * (int32_t)s16X[ChOffset + 24 + 1]; \ - s32Temp2 += \ - (int32_t)WIND_4_SUBBANDS_1_3 * (int32_t)s16X[ChOffset + 8 + 7]; \ - s32Temp += \ - (int32_t)WIND_4_SUBBANDS_1_4 * (int32_t)s16X[ChOffset + 32 + 1]; \ - s32Temp2 += (int32_t)WIND_4_SUBBANDS_1_4 * (int32_t)s16X[ChOffset + 7]; \ - s32DCTY[1] = (int32_t)(s32Temp); \ - s32DCTY[7] = (int32_t)(s32Temp2); \ +#define WINDOW_ACCU_4_1_7 \ + { \ + s32Temp = (int32_t)WIND_4_SUBBANDS_1_0 * (int32_t)s16X[ChOffset + 1]; \ + s32Temp2 = (int32_t)WIND_4_SUBBANDS_1_0 * (int32_t)s16X[ChOffset + 32 + 7]; \ + s32Temp += (int32_t)WIND_4_SUBBANDS_1_1 * (int32_t)s16X[ChOffset + 8 + 1]; \ + s32Temp2 += (int32_t)WIND_4_SUBBANDS_1_1 * (int32_t)s16X[ChOffset + 24 + 7]; \ + s32Temp += (int32_t)WIND_4_SUBBANDS_1_2 * (int32_t)s16X[ChOffset + 16 + 1]; \ + s32Temp2 += (int32_t)WIND_4_SUBBANDS_1_2 * (int32_t)s16X[ChOffset + 16 + 7]; \ + s32Temp += (int32_t)WIND_4_SUBBANDS_1_3 * (int32_t)s16X[ChOffset + 24 + 1]; \ + s32Temp2 += (int32_t)WIND_4_SUBBANDS_1_3 * (int32_t)s16X[ChOffset + 8 + 7]; \ + s32Temp += (int32_t)WIND_4_SUBBANDS_1_4 * (int32_t)s16X[ChOffset + 32 + 1]; \ + s32Temp2 += (int32_t)WIND_4_SUBBANDS_1_4 * (int32_t)s16X[ChOffset + 7]; \ + s32DCTY[1] = (int32_t)(s32Temp); \ + s32DCTY[7] = (int32_t)(s32Temp2); \ } -#define WINDOW_ACCU_4_2_6 \ - { \ - s32Temp = (int32_t)WIND_4_SUBBANDS_2_0 * (int32_t)s16X[ChOffset + 2]; \ - s32Temp2 = \ - (int32_t)WIND_4_SUBBANDS_2_0 * (int32_t)s16X[ChOffset + 32 + 6]; \ - s32Temp += (int32_t)WIND_4_SUBBANDS_2_1 * (int32_t)s16X[ChOffset + 8 + 2]; \ - s32Temp2 += \ - (int32_t)WIND_4_SUBBANDS_2_1 * (int32_t)s16X[ChOffset + 24 + 6]; \ - s32Temp += \ - (int32_t)WIND_4_SUBBANDS_2_2 * (int32_t)s16X[ChOffset + 16 + 2]; \ - s32Temp2 += \ - (int32_t)WIND_4_SUBBANDS_2_2 * (int32_t)s16X[ChOffset + 16 + 6]; \ - s32Temp += \ - (int32_t)WIND_4_SUBBANDS_2_3 * (int32_t)s16X[ChOffset + 24 + 2]; \ - s32Temp2 += \ - (int32_t)WIND_4_SUBBANDS_2_3 * (int32_t)s16X[ChOffset + 8 + 6]; \ - s32Temp += \ - (int32_t)WIND_4_SUBBANDS_2_4 * (int32_t)s16X[ChOffset + 32 + 2]; \ - s32Temp2 += (int32_t)WIND_4_SUBBANDS_2_4 * (int32_t)s16X[ChOffset + 6]; \ - s32DCTY[2] = (int32_t)(s32Temp); \ - s32DCTY[6] = (int32_t)(s32Temp2); \ +#define WINDOW_ACCU_4_2_6 \ + { \ + s32Temp = (int32_t)WIND_4_SUBBANDS_2_0 * (int32_t)s16X[ChOffset + 2]; \ + s32Temp2 = (int32_t)WIND_4_SUBBANDS_2_0 * (int32_t)s16X[ChOffset + 32 + 6]; \ + s32Temp += (int32_t)WIND_4_SUBBANDS_2_1 * (int32_t)s16X[ChOffset + 8 + 2]; \ + s32Temp2 += (int32_t)WIND_4_SUBBANDS_2_1 * (int32_t)s16X[ChOffset + 24 + 6]; \ + s32Temp += (int32_t)WIND_4_SUBBANDS_2_2 * (int32_t)s16X[ChOffset + 16 + 2]; \ + s32Temp2 += (int32_t)WIND_4_SUBBANDS_2_2 * (int32_t)s16X[ChOffset + 16 + 6]; \ + s32Temp += (int32_t)WIND_4_SUBBANDS_2_3 * (int32_t)s16X[ChOffset + 24 + 2]; \ + s32Temp2 += (int32_t)WIND_4_SUBBANDS_2_3 * (int32_t)s16X[ChOffset + 8 + 6]; \ + s32Temp += (int32_t)WIND_4_SUBBANDS_2_4 * (int32_t)s16X[ChOffset + 32 + 2]; \ + s32Temp2 += (int32_t)WIND_4_SUBBANDS_2_4 * (int32_t)s16X[ChOffset + 6]; \ + s32DCTY[2] = (int32_t)(s32Temp); \ + s32DCTY[6] = (int32_t)(s32Temp2); \ } -#define WINDOW_ACCU_4_3_5 \ - { \ - s32Temp = (int32_t)WIND_4_SUBBANDS_3_0 * (int32_t)s16X[ChOffset + 3]; \ - s32Temp2 = \ - (int32_t)WIND_4_SUBBANDS_3_0 * (int32_t)s16X[ChOffset + 32 + 5]; \ - s32Temp += (int32_t)WIND_4_SUBBANDS_3_1 * (int32_t)s16X[ChOffset + 8 + 3]; \ - s32Temp2 += \ - (int32_t)WIND_4_SUBBANDS_3_1 * (int32_t)s16X[ChOffset + 24 + 5]; \ - s32Temp += \ - (int32_t)WIND_4_SUBBANDS_3_2 * (int32_t)s16X[ChOffset + 16 + 3]; \ - s32Temp2 += \ - (int32_t)WIND_4_SUBBANDS_3_2 * (int32_t)s16X[ChOffset + 16 + 5]; \ - s32Temp += \ - (int32_t)WIND_4_SUBBANDS_3_3 * (int32_t)s16X[ChOffset + 24 + 3]; \ - s32Temp2 += \ - (int32_t)WIND_4_SUBBANDS_3_3 * (int32_t)s16X[ChOffset + 8 + 5]; \ - s32Temp += \ - (int32_t)WIND_4_SUBBANDS_3_4 * (int32_t)s16X[ChOffset + 32 + 3]; \ - s32Temp2 += (int32_t)WIND_4_SUBBANDS_3_4 * (int32_t)s16X[ChOffset + 5]; \ - s32DCTY[3] = (int32_t)(s32Temp); \ - s32DCTY[5] = (int32_t)(s32Temp2); \ +#define WINDOW_ACCU_4_3_5 \ + { \ + s32Temp = (int32_t)WIND_4_SUBBANDS_3_0 * (int32_t)s16X[ChOffset + 3]; \ + s32Temp2 = (int32_t)WIND_4_SUBBANDS_3_0 * (int32_t)s16X[ChOffset + 32 + 5]; \ + s32Temp += (int32_t)WIND_4_SUBBANDS_3_1 * (int32_t)s16X[ChOffset + 8 + 3]; \ + s32Temp2 += (int32_t)WIND_4_SUBBANDS_3_1 * (int32_t)s16X[ChOffset + 24 + 5]; \ + s32Temp += (int32_t)WIND_4_SUBBANDS_3_2 * (int32_t)s16X[ChOffset + 16 + 3]; \ + s32Temp2 += (int32_t)WIND_4_SUBBANDS_3_2 * (int32_t)s16X[ChOffset + 16 + 5]; \ + s32Temp += (int32_t)WIND_4_SUBBANDS_3_3 * (int32_t)s16X[ChOffset + 24 + 3]; \ + s32Temp2 += (int32_t)WIND_4_SUBBANDS_3_3 * (int32_t)s16X[ChOffset + 8 + 5]; \ + s32Temp += (int32_t)WIND_4_SUBBANDS_3_4 * (int32_t)s16X[ChOffset + 32 + 3]; \ + s32Temp2 += (int32_t)WIND_4_SUBBANDS_3_4 * (int32_t)s16X[ChOffset + 5]; \ + s32DCTY[3] = (int32_t)(s32Temp); \ + s32DCTY[5] = (int32_t)(s32Temp2); \ } -#define WINDOW_ACCU_4_4 \ - { \ - s32Temp = (int32_t)WIND_4_SUBBANDS_4_0 * \ - (int32_t)(s16X[ChOffset + 4] + s16X[ChOffset + 4 + 32]); \ - s32Temp += (int32_t)WIND_4_SUBBANDS_4_1 * \ - (int32_t)(s16X[ChOffset + 4 + 8] + s16X[ChOffset + 4 + 24]); \ - s32Temp += \ - (int32_t)WIND_4_SUBBANDS_4_2 * (int32_t)s16X[ChOffset + 4 + 16]; \ - s32DCTY[4] = (int32_t)(s32Temp); \ +#define WINDOW_ACCU_4_4 \ + { \ + s32Temp = (int32_t)WIND_4_SUBBANDS_4_0 * \ + (int32_t)(s16X[ChOffset + 4] + s16X[ChOffset + 4 + 32]); \ + s32Temp += (int32_t)WIND_4_SUBBANDS_4_1 * \ + (int32_t)(s16X[ChOffset + 4 + 8] + s16X[ChOffset + 4 + 24]); \ + s32Temp += (int32_t)WIND_4_SUBBANDS_4_2 * (int32_t)s16X[ChOffset + 4 + 16]; \ + s32DCTY[4] = (int32_t)(s32Temp); \ } #endif #define WINDOW_PARTIAL_4 \ @@ -1059,47 +861,38 @@ static int16_t* s16X = } #else #if (SBC_IS_64_MULT_IN_WINDOW_ACCU == TRUE) -#define WINDOW_ACCU_4(i) \ - { \ - s64Temp = ((int64_t)gas32CoeffFor4SBs[i] * (int64_t)s16X[ChOffset + i]); \ - s64Temp += ((int64_t)gas32CoeffFor4SBs[(i + 8)] * \ - (int64_t)s16X[ChOffset + i + 8]); \ - s64Temp += ((int64_t)gas32CoeffFor4SBs[(i + 16)] * \ - (int64_t)s16X[ChOffset + i + 16]); \ - s64Temp += ((int64_t)gas32CoeffFor4SBs[(i + 24)] * \ - (int64_t)s16X[ChOffset + i + 24]); \ - s64Temp += ((int64_t)gas32CoeffFor4SBs[(i + 32)] * \ - (int64_t)s16X[ChOffset + i + 32]); \ - s32DCTY[i] = (int32_t)(s64Temp >> 16); \ - /*printf("s32DCTY4: 0x%x \n", s32DCTY[i]);*/ \ +#define WINDOW_ACCU_4(i) \ + { \ + s64Temp = ((int64_t)gas32CoeffFor4SBs[i] * (int64_t)s16X[ChOffset + i]); \ + s64Temp += ((int64_t)gas32CoeffFor4SBs[(i + 8)] * (int64_t)s16X[ChOffset + i + 8]); \ + s64Temp += ((int64_t)gas32CoeffFor4SBs[(i + 16)] * (int64_t)s16X[ChOffset + i + 16]); \ + s64Temp += ((int64_t)gas32CoeffFor4SBs[(i + 24)] * (int64_t)s16X[ChOffset + i + 24]); \ + s64Temp += ((int64_t)gas32CoeffFor4SBs[(i + 32)] * (int64_t)s16X[ChOffset + i + 32]); \ + s32DCTY[i] = (int32_t)(s64Temp >> 16); \ + /*printf("s32DCTY4: 0x%x \n", s32DCTY[i]);*/ \ } #else -#define WINDOW_ACCU_4(i) \ - { \ - s32DCTY[i] = (gas32CoeffFor4SBs[i * 2] * s16X[ChOffset + i]) + \ - (((int32_t)(uint16_t)(gas32CoeffFor4SBs[(i * 2) + 1]) * \ - s16X[ChOffset + i]) >> \ - 16); \ - s32DCTY[i] += \ - (gas32CoeffFor4SBs[(i + 8) * 2] * s16X[ChOffset + i + 8]) + \ - (((int32_t)(uint16_t)(gas32CoeffFor4SBs[((i + 8) * 2) + 1]) * \ - s16X[ChOffset + i + 8]) >> \ - 16); \ - s32DCTY[i] += \ - (gas32CoeffFor4SBs[(i + 16) * 2] * s16X[ChOffset + i + 16]) + \ - (((int32_t)(uint16_t)(gas32CoeffFor4SBs[((i + 16) * 2) + 1]) * \ - s16X[ChOffset + i + 16]) >> \ - 16); \ - s32DCTY[i] += \ - (gas32CoeffFor4SBs[(i + 24) * 2] * s16X[ChOffset + i + 24]) + \ - (((int32_t)(uint16_t)(gas32CoeffFor4SBs[((i + 24) * 2) + 1]) * \ - s16X[ChOffset + i + 24]) >> \ - 16); \ - s32DCTY[i] += \ - (gas32CoeffFor4SBs[(i + 32) * 2] * s16X[ChOffset + i + 32]) + \ - (((int32_t)(uint16_t)(gas32CoeffFor4SBs[((i + 32) * 2) + 1]) * \ - s16X[ChOffset + i + 32]) >> \ - 16); \ +#define WINDOW_ACCU_4(i) \ + { \ + s32DCTY[i] = \ + (gas32CoeffFor4SBs[i * 2] * s16X[ChOffset + i]) + \ + (((int32_t)(uint16_t)(gas32CoeffFor4SBs[(i * 2) + 1]) * s16X[ChOffset + i]) >> 16); \ + s32DCTY[i] += (gas32CoeffFor4SBs[(i + 8) * 2] * s16X[ChOffset + i + 8]) + \ + (((int32_t)(uint16_t)(gas32CoeffFor4SBs[((i + 8) * 2) + 1]) * \ + s16X[ChOffset + i + 8]) >> \ + 16); \ + s32DCTY[i] += (gas32CoeffFor4SBs[(i + 16) * 2] * s16X[ChOffset + i + 16]) + \ + (((int32_t)(uint16_t)(gas32CoeffFor4SBs[((i + 16) * 2) + 1]) * \ + s16X[ChOffset + i + 16]) >> \ + 16); \ + s32DCTY[i] += (gas32CoeffFor4SBs[(i + 24) * 2] * s16X[ChOffset + i + 24]) + \ + (((int32_t)(uint16_t)(gas32CoeffFor4SBs[((i + 24) * 2) + 1]) * \ + s16X[ChOffset + i + 24]) >> \ + 16); \ + s32DCTY[i] += (gas32CoeffFor4SBs[(i + 32) * 2] * s16X[ChOffset + i + 32]) + \ + (((int32_t)(uint16_t)(gas32CoeffFor4SBs[((i + 32) * 2) + 1]) * \ + s16X[ChOffset + i + 32]) >> \ + 16); \ } #endif #define WINDOW_PARTIAL_4 \ @@ -1115,52 +908,42 @@ static int16_t* s16X = } #if (SBC_IS_64_MULT_IN_WINDOW_ACCU == TRUE) -#define WINDOW_ACCU_8(i) \ - { \ - s64Temp = \ - ((((int64_t)gas32CoeffFor8SBs[i] * (int64_t)s16X[ChOffset + i]))); \ - s64Temp += ((((int64_t)gas32CoeffFor8SBs[(i + 16)] * \ - (int64_t)s16X[ChOffset + i + 16]))); \ - s64Temp += ((((int64_t)gas32CoeffFor8SBs[(i + 32)] * \ - (int64_t)s16X[ChOffset + i + 32]))); \ - s64Temp += ((((int64_t)gas32CoeffFor8SBs[(i + 48)] * \ - (int64_t)s16X[ChOffset + i + 48]))); \ - s64Temp += ((((int64_t)gas32CoeffFor8SBs[(i + 64)] * \ - (int64_t)s16X[ChOffset + i + 64]))); \ - /*printf("s32DCTY8: %d= 0x%x * %d\n", s32DCTY[i], gas32CoeffFor8SBs[i], \ - * s16X[ChOffset+i]);*/ \ - s32DCTY[i] = (int32_t)(s64Temp >> 16); \ +#define WINDOW_ACCU_8(i) \ + { \ + s64Temp = ((((int64_t)gas32CoeffFor8SBs[i] * (int64_t)s16X[ChOffset + i]))); \ + s64Temp += ((((int64_t)gas32CoeffFor8SBs[(i + 16)] * (int64_t)s16X[ChOffset + i + 16]))); \ + s64Temp += ((((int64_t)gas32CoeffFor8SBs[(i + 32)] * (int64_t)s16X[ChOffset + i + 32]))); \ + s64Temp += ((((int64_t)gas32CoeffFor8SBs[(i + 48)] * (int64_t)s16X[ChOffset + i + 48]))); \ + s64Temp += ((((int64_t)gas32CoeffFor8SBs[(i + 64)] * (int64_t)s16X[ChOffset + i + 64]))); \ + /*printf("s32DCTY8: %d= 0x%x * %d\n", s32DCTY[i], gas32CoeffFor8SBs[i], \ + * s16X[ChOffset+i]);*/ \ + s32DCTY[i] = (int32_t)(s64Temp >> 16); \ } #else -#define WINDOW_ACCU_8(i) \ - { \ - s32DCTY[i] = (gas32CoeffFor8SBs[i * 2] * s16X[ChOffset + i]) + \ - (((int32_t)(uint16_t)(gas32CoeffFor8SBs[(i * 2) + 1]) * \ - s16X[ChOffset + i]) >> \ - 16); \ - s32DCTY[i] += \ - (gas32CoeffFor8SBs[(i + 16) * 2] * s16X[ChOffset + i + 16]) + \ - (((int32_t)(uint16_t)(gas32CoeffFor8SBs[((i + 16) * 2) + 1]) * \ - s16X[ChOffset + i + 16]) >> \ - 16); \ - s32DCTY[i] += \ - (gas32CoeffFor8SBs[(i + 32) * 2] * s16X[ChOffset + i + 32]) + \ - (((int32_t)(uint16_t)(gas32CoeffFor8SBs[((i + 32) * 2) + 1]) * \ - s16X[ChOffset + i + 32]) >> \ - 16); \ - s32DCTY[i] += \ - (gas32CoeffFor8SBs[(i + 48) * 2] * s16X[ChOffset + i + 48]) + \ - (((int32_t)(uint16_t)(gas32CoeffFor8SBs[((i + 48) * 2) + 1]) * \ - s16X[ChOffset + i + 48]) >> \ - 16); \ - s32DCTY[i] += \ - (gas32CoeffFor8SBs[(i + 64) * 2] * s16X[ChOffset + i + 64]) + \ - (((int32_t)(uint16_t)(gas32CoeffFor8SBs[((i + 64) * 2) + 1]) * \ - s16X[ChOffset + i + 64]) >> \ - 16); \ - /*printf("s32DCTY8: %d = 0x%4x%4x * %d\n", s32DCTY[i], gas32CoeffFor8SBs[i \ - * * 2], (gas32CoeffFor8SBs[(i * 2) + 1]), s16X[ChOffset+i]);*/ \ - /*s32DCTY[i]=(int32_t)(s64Temp>>16);*/ \ +#define WINDOW_ACCU_8(i) \ + { \ + s32DCTY[i] = \ + (gas32CoeffFor8SBs[i * 2] * s16X[ChOffset + i]) + \ + (((int32_t)(uint16_t)(gas32CoeffFor8SBs[(i * 2) + 1]) * s16X[ChOffset + i]) >> 16); \ + s32DCTY[i] += (gas32CoeffFor8SBs[(i + 16) * 2] * s16X[ChOffset + i + 16]) + \ + (((int32_t)(uint16_t)(gas32CoeffFor8SBs[((i + 16) * 2) + 1]) * \ + s16X[ChOffset + i + 16]) >> \ + 16); \ + s32DCTY[i] += (gas32CoeffFor8SBs[(i + 32) * 2] * s16X[ChOffset + i + 32]) + \ + (((int32_t)(uint16_t)(gas32CoeffFor8SBs[((i + 32) * 2) + 1]) * \ + s16X[ChOffset + i + 32]) >> \ + 16); \ + s32DCTY[i] += (gas32CoeffFor8SBs[(i + 48) * 2] * s16X[ChOffset + i + 48]) + \ + (((int32_t)(uint16_t)(gas32CoeffFor8SBs[((i + 48) * 2) + 1]) * \ + s16X[ChOffset + i + 48]) >> \ + 16); \ + s32DCTY[i] += (gas32CoeffFor8SBs[(i + 64) * 2] * s16X[ChOffset + i + 64]) + \ + (((int32_t)(uint16_t)(gas32CoeffFor8SBs[((i + 64) * 2) + 1]) * \ + s16X[ChOffset + i + 64]) >> \ + 16); \ + /*printf("s32DCTY8: %d = 0x%4x%4x * %d\n", s32DCTY[i], gas32CoeffFor8SBs[i \ + * * 2], (gas32CoeffFor8SBs[(i * 2) + 1]), s16X[ChOffset+i]);*/ \ + /*s32DCTY[i]=(int32_t)(s64Temp>>16);*/ \ } #endif #define WINDOW_PARTIAL_8 \ @@ -1188,10 +971,10 @@ static int16_t* s16X = static int16_t ShiftCounter = 0; extern int16_t EncMaxShiftCounter; /**************************************************************************** -* SbcAnalysisFilter - performs Analysis of the input audio stream -* -* RETURNS : N/A -*/ + * SbcAnalysisFilter - performs Analysis of the input audio stream + * + * RETURNS : N/A + */ void SbcAnalysisFilter4(SBC_ENC_PARAMS* pstrEncParams, int16_t* input) { int16_t* ps16PcmBuf; int32_t* ps32SbBuf; diff --git a/system/embdrv/sbc/encoder/srce/sbc_dct.c b/system/embdrv/sbc/encoder/srce/sbc_dct.c index 9f0efe445ae..fa9734b3c91 100644 --- a/system/embdrv/sbc/encoder/srce/sbc_dct.c +++ b/system/embdrv/sbc/encoder/srce/sbc_dct.c @@ -23,6 +23,7 @@ ******************************************************************************/ #include "sbc_dct.h" + #include "sbc_enc_func_declare.h" #include "sbc_encoder.h" @@ -39,37 +40,24 @@ ******************************************************************************/ #if (SBC_IS_64_MULT_IN_IDCT == FALSE) -#define SBC_COS_PI_SUR_4 \ - (0x00005a82) /* ((0x8000) * 0.7071) = cos(pi/4) \ - */ -#define SBC_COS_PI_SUR_8 \ - (0x00007641) /* ((0x8000) * 0.9239) = (cos(pi/8)) */ -#define SBC_COS_3PI_SUR_8 \ - (0x000030fb) /* ((0x8000) * 0.3827) = (cos(3*pi/8)) */ -#define SBC_COS_PI_SUR_16 \ - (0x00007d8a) /* ((0x8000) * 0.9808)) = (cos(pi/16)) */ -#define SBC_COS_3PI_SUR_16 \ - (0x00006a6d) /* ((0x8000) * 0.8315)) = (cos(3*pi/16)) */ -#define SBC_COS_5PI_SUR_16 \ - (0x0000471c) /* ((0x8000) * 0.5556)) = (cos(5*pi/16)) */ -#define SBC_COS_7PI_SUR_16 \ - (0x000018f8) /* ((0x8000) * 0.1951)) = (cos(7*pi/16)) */ +#define SBC_COS_PI_SUR_4 \ + (0x00005a82) /* ((0x8000) * 0.7071) = cos(pi/4) \ + */ +#define SBC_COS_PI_SUR_8 (0x00007641) /* ((0x8000) * 0.9239) = (cos(pi/8)) */ +#define SBC_COS_3PI_SUR_8 (0x000030fb) /* ((0x8000) * 0.3827) = (cos(3*pi/8)) */ +#define SBC_COS_PI_SUR_16 (0x00007d8a) /* ((0x8000) * 0.9808)) = (cos(pi/16)) */ +#define SBC_COS_3PI_SUR_16 (0x00006a6d) /* ((0x8000) * 0.8315)) = (cos(3*pi/16)) */ +#define SBC_COS_5PI_SUR_16 (0x0000471c) /* ((0x8000) * 0.5556)) = (cos(5*pi/16)) */ +#define SBC_COS_7PI_SUR_16 (0x000018f8) /* ((0x8000) * 0.1951)) = (cos(7*pi/16)) */ #define SBC_IDCT_MULT(a, b, c) SBC_MULT_32_16_SIMPLIFIED(a, b, c) #else -#define SBC_COS_PI_SUR_4 \ - (0x5A827999) /* ((0x80000000) * 0.707106781) = (cos(pi/4) ) */ -#define SBC_COS_PI_SUR_8 \ - (0x7641AF3C) /* ((0x80000000) * 0.923879533) = (cos(pi/8) ) */ -#define SBC_COS_3PI_SUR_8 \ - (0x30FBC54D) /* ((0x80000000) * 0.382683432) = (cos(3*pi/8) ) */ -#define SBC_COS_PI_SUR_16 \ - (0x7D8A5F3F) /* ((0x80000000) * 0.98078528 )) = (cos(pi/16) ) */ -#define SBC_COS_3PI_SUR_16 \ - (0x6A6D98A4) /* ((0x80000000) * 0.831469612)) = (cos(3*pi/16)) */ -#define SBC_COS_5PI_SUR_16 \ - (0x471CECE6) /* ((0x80000000) * 0.555570233)) = (cos(5*pi/16)) */ -#define SBC_COS_7PI_SUR_16 \ - (0x18F8B83C) /* ((0x80000000) * 0.195090322)) = (cos(7*pi/16)) */ +#define SBC_COS_PI_SUR_4 (0x5A827999) /* ((0x80000000) * 0.707106781) = (cos(pi/4) ) */ +#define SBC_COS_PI_SUR_8 (0x7641AF3C) /* ((0x80000000) * 0.923879533) = (cos(pi/8) ) */ +#define SBC_COS_3PI_SUR_8 (0x30FBC54D) /* ((0x80000000) * 0.382683432) = (cos(3*pi/8) ) */ +#define SBC_COS_PI_SUR_16 (0x7D8A5F3F) /* ((0x80000000) * 0.98078528 )) = (cos(pi/16) ) */ +#define SBC_COS_3PI_SUR_16 (0x6A6D98A4) /* ((0x80000000) * 0.831469612)) = (cos(3*pi/16)) */ +#define SBC_COS_5PI_SUR_16 (0x471CECE6) /* ((0x80000000) * 0.555570233)) = (cos(5*pi/16)) */ +#define SBC_COS_7PI_SUR_16 (0x18F8B83C) /* ((0x80000000) * 0.195090322)) = (cos(7*pi/16)) */ #define SBC_IDCT_MULT(a, b, c) SBC_MULT_32_32(a, b, c) #endif /* SBC_IS_64_MULT_IN_IDCT */ @@ -112,10 +100,8 @@ void SBC_FastIDCT8(int32_t* pInVect, int32_t* pOutVect) { /* 2-point IDCT of x0 and x4 as in (11) */ temp = x0; - SBC_IDCT_MULT(SBC_COS_PI_SUR_4, (x0 + x4), - x0); /*x0 = ( x0 + x4 ) * cos(1*pi/4) ; */ - SBC_IDCT_MULT(SBC_COS_PI_SUR_4, (temp - x4), - x4); /*x4 = ( temp - x4 ) * cos(1*pi/4) ; */ + SBC_IDCT_MULT(SBC_COS_PI_SUR_4, (x0 + x4), x0); /*x0 = ( x0 + x4 ) * cos(1*pi/4) ; */ + SBC_IDCT_MULT(SBC_COS_PI_SUR_4, (temp - x4), x4); /*x4 = ( temp - x4 ) * cos(1*pi/4) ; */ /* rearrangement of x2 and x6 as in (15) */ x2 -= x6; @@ -124,10 +110,8 @@ void SBC_FastIDCT8(int32_t* pInVect, int32_t* pOutVect) { /* 2-point IDCT of x2 and x6 and post-multiplication as in (15) */ SBC_IDCT_MULT(SBC_COS_PI_SUR_4, x6, x6); /*x6 = x6 * cos(1*pi/4) ; */ temp = x2; - SBC_IDCT_MULT(SBC_COS_PI_SUR_8, (x2 + x6), - x2); /*x2 = ( x2 + x6 ) * cos(1*pi/8) ; */ - SBC_IDCT_MULT(SBC_COS_3PI_SUR_8, (temp - x6), - x6); /*x6 = ( temp - x6 ) * cos(3*pi/8) ;*/ + SBC_IDCT_MULT(SBC_COS_PI_SUR_8, (x2 + x6), x2); /*x2 = ( x2 + x6 ) * cos(1*pi/8) ; */ + SBC_IDCT_MULT(SBC_COS_3PI_SUR_8, (temp - x6), x6); /*x6 = ( temp - x6 ) * cos(3*pi/8) ;*/ /* 4-point IDCT of x0,x2,x4 and x6 as in (11) */ res_even[0] = x0 + x2; @@ -154,10 +138,8 @@ void SBC_FastIDCT8(int32_t* pInVect, int32_t* pOutVect) { /* 2-point IDCT of x3 and x7 and post-multiplication as in (15) */ temp = x3; - SBC_IDCT_MULT(SBC_COS_PI_SUR_8, (x3 + x7), - x3); /*x3 = ( x3 + x7 ) * cos(1*pi/8) ; */ - SBC_IDCT_MULT(SBC_COS_3PI_SUR_8, (temp - x7), - x7); /*x7 = ( temp - x7 ) * cos(3*pi/8) ;*/ + SBC_IDCT_MULT(SBC_COS_PI_SUR_8, (x3 + x7), x3); /*x3 = ( x3 + x7 ) * cos(1*pi/8) ; */ + SBC_IDCT_MULT(SBC_COS_3PI_SUR_8, (temp - x7), x7); /*x7 = ( temp - x7 ) * cos(3*pi/8) ;*/ /* 4-point IDCT of x1,x3,x5 and x7 and post multiplication by diagonal matrix * as in (14) */ @@ -189,9 +171,7 @@ void SBC_FastIDCT8(int32_t* pInVect, int32_t* pOutVect) { /*temp += (int32_t)(((int64_t)M[(Index*strEncParams->numOfSubBands*2)+k] * * Y[k]) >> 16 );*/ temp += (gas16AnalDCTcoeff8[(Index * 8 * 2) + k] * (pInVect[k] >> 16)); - temp += - ((gas16AnalDCTcoeff8[(Index * 8 * 2) + k] * (pInVect[k] & 0xFFFF)) >> - 16); + temp += ((gas16AnalDCTcoeff8[(Index * 8 * 2) + k] * (pInVect[k] & 0xFFFF)) >> 16); } pOutVect[Index] = temp; } @@ -258,9 +238,7 @@ void SBC_FastIDCT4(int32_t* pInVect, int32_t* pOutVect) { /*temp += (int32_t)(((int64_t)M[(Index*strEncParams->numOfSubBands*2)+k] * * Y[k]) >> 16 ); */ temp += (gas16AnalDCTcoeff4[(Index * 4 * 2) + k] * (pInVect[k] >> 16)); - temp += - ((gas16AnalDCTcoeff4[(Index * 4 * 2) + k] * (pInVect[k] & 0xFFFF)) >> - 16); + temp += ((gas16AnalDCTcoeff4[(Index * 4 * 2) + k] * (pInVect[k] & 0xFFFF)) >> 16); } pOutVect[Index] = temp; } diff --git a/system/embdrv/sbc/encoder/srce/sbc_dct_coeffs.c b/system/embdrv/sbc/encoder/srce/sbc_dct_coeffs.c index fd7e9cdb1ce..538371ff034 100644 --- a/system/embdrv/sbc/encoder/srce/sbc_dct_coeffs.c +++ b/system/embdrv/sbc/encoder/srce/sbc_dct_coeffs.c @@ -27,90 +27,65 @@ /*DCT coeff for 4 sub-band case.*/ #if (SBC_FAST_DCT == FALSE) const int16_t gas16AnalDCTcoeff4[] = { - (int16_t)(0.7071 * 32768), (int16_t)(0.9239 * 32768), - (int16_t)(1.0000 * 32767), (int16_t)(0.9239 * 32768), - (int16_t)(0.7071 * 32768), (int16_t)(0.3827 * 32768), - (int16_t)(0.0000 * 32768), (int16_t)(-0.3827 * 32768), + (int16_t)(0.7071 * 32768), (int16_t)(0.9239 * 32768), (int16_t)(1.0000 * 32767), + (int16_t)(0.9239 * 32768), (int16_t)(0.7071 * 32768), (int16_t)(0.3827 * 32768), + (int16_t)(0.0000 * 32768), (int16_t)(-0.3827 * 32768), - (int16_t)(-0.7071 * 32768), (int16_t)(0.3827 * 32768), - (int16_t)(1.0000 * 32767), (int16_t)(0.3827 * 32768), - (int16_t)(-0.7071 * 32768), (int16_t)(-0.9239 * 32768), - (int16_t)(-0.0000 * 32768), (int16_t)(0.9239 * 32768), + (int16_t)(-0.7071 * 32768), (int16_t)(0.3827 * 32768), (int16_t)(1.0000 * 32767), + (int16_t)(0.3827 * 32768), (int16_t)(-0.7071 * 32768), (int16_t)(-0.9239 * 32768), + (int16_t)(-0.0000 * 32768), (int16_t)(0.9239 * 32768), - (int16_t)(-0.7071 * 32768), (int16_t)(-0.3827 * 32768), - (int16_t)(1.0000 * 32767), (int16_t)(-0.3827 * 32768), - (int16_t)(-0.7071 * 32768), (int16_t)(0.9239 * 32768), - (int16_t)(0.0000 * 32768), (int16_t)(-0.9239 * 32768), + (int16_t)(-0.7071 * 32768), (int16_t)(-0.3827 * 32768), (int16_t)(1.0000 * 32767), + (int16_t)(-0.3827 * 32768), (int16_t)(-0.7071 * 32768), (int16_t)(0.9239 * 32768), + (int16_t)(0.0000 * 32768), (int16_t)(-0.9239 * 32768), - (int16_t)(0.7071 * 32768), (int16_t)(-0.9239 * 32768), - (int16_t)(1.0000 * 32767), (int16_t)(-0.9239 * 32768), - (int16_t)(0.7071 * 32768), (int16_t)(-0.3827 * 32768), - (int16_t)(-0.0000 * 32768), (int16_t)(0.3827 * 32768)}; + (int16_t)(0.7071 * 32768), (int16_t)(-0.9239 * 32768), (int16_t)(1.0000 * 32767), + (int16_t)(-0.9239 * 32768), (int16_t)(0.7071 * 32768), (int16_t)(-0.3827 * 32768), + (int16_t)(-0.0000 * 32768), (int16_t)(0.3827 * 32768)}; /*DCT coeff for 8 sub-band case.*/ const int16_t gas16AnalDCTcoeff8[] = { - (int16_t)(0.7071 * 32768), (int16_t)(0.8315 * 32768), - (int16_t)(0.9239 * 32768), (int16_t)(0.9808 * 32768), - (int16_t)(1.0000 * 32767), (int16_t)(0.9808 * 32768), - (int16_t)(0.9239 * 32768), (int16_t)(0.8315 * 32768), - (int16_t)(0.7071 * 32768), (int16_t)(0.5556 * 32768), - (int16_t)(0.3827 * 32768), (int16_t)(0.1951 * 32768), - (int16_t)(0.0000 * 32768), (int16_t)(-0.1951 * 32768), - (int16_t)(-0.3827 * 32768), (int16_t)(-0.5556 * 32768), - (int16_t)(-0.7071 * 32768), (int16_t)(-0.1951 * 32768), - (int16_t)(0.3827 * 32768), (int16_t)(0.8315 * 32768), - (int16_t)(1.0000 * 32767), (int16_t)(0.8315 * 32768), - (int16_t)(0.3827 * 32768), (int16_t)(-0.1951 * 32768), - (int16_t)(-0.7071 * 32768), (int16_t)(-0.9808 * 32768), - (int16_t)(-0.9239 * 32768), (int16_t)(-0.5556 * 32768), - (int16_t)(-0.0000 * 32768), (int16_t)(0.5556 * 32768), - (int16_t)(0.9239 * 32768), (int16_t)(0.9808 * 32768), - (int16_t)(-0.7071 * 32768), (int16_t)(-0.9808 * 32768), - (int16_t)(-0.3827 * 32768), (int16_t)(0.5556 * 32768), - (int16_t)(1.0000 * 32767), (int16_t)(0.5556 * 32768), - (int16_t)(-0.3827 * 32768), (int16_t)(-0.9808 * 32768), - (int16_t)(-0.7071 * 32768), (int16_t)(0.1951 * 32768), - (int16_t)(0.9239 * 32768), (int16_t)(0.8315 * 32768), - (int16_t)(0.0000 * 32768), (int16_t)(-0.8315 * 32768), - (int16_t)(-0.9239 * 32768), (int16_t)(-0.1951 * 32768), - (int16_t)(0.7071 * 32768), (int16_t)(-0.5556 * 32768), - (int16_t)(-0.9239 * 32768), (int16_t)(0.1951 * 32768), - (int16_t)(1.0000 * 32767), (int16_t)(0.1951 * 32768), - (int16_t)(-0.9239 * 32768), (int16_t)(-0.5556 * 32768), - (int16_t)(0.7071 * 32768), (int16_t)(0.8315 * 32768), - (int16_t)(-0.3827 * 32768), (int16_t)(-0.9808 * 32768), - (int16_t)(-0.0000 * 32768), (int16_t)(0.9808 * 32768), - (int16_t)(0.3827 * 32768), (int16_t)(-0.8315 * 32768), - (int16_t)(0.7071 * 32768), (int16_t)(0.5556 * 32768), - (int16_t)(-0.9239 * 32768), (int16_t)(-0.1951 * 32768), - (int16_t)(1.0000 * 32767), (int16_t)(-0.1951 * 32768), - (int16_t)(-0.9239 * 32768), (int16_t)(0.5556 * 32768), - (int16_t)(0.7071 * 32768), (int16_t)(-0.8315 * 32768), - (int16_t)(-0.3827 * 32768), (int16_t)(0.9808 * 32768), - (int16_t)(0.0000 * 32768), (int16_t)(-0.9808 * 32768), - (int16_t)(0.3827 * 32768), (int16_t)(0.8315 * 32768), - (int16_t)(-0.7071 * 32768), (int16_t)(0.9808 * 32768), - (int16_t)(-0.3827 * 32768), (int16_t)(-0.5556 * 32768), - (int16_t)(1.0000 * 32767), (int16_t)(-0.5556 * 32768), - (int16_t)(-0.3827 * 32768), (int16_t)(0.9808 * 32768), - (int16_t)(-0.7071 * 32768), (int16_t)(-0.1951 * 32768), - (int16_t)(0.9239 * 32768), (int16_t)(-0.8315 * 32768), - (int16_t)(-0.0000 * 32768), (int16_t)(0.8315 * 32768), - (int16_t)(-0.9239 * 32768), (int16_t)(0.1951 * 32768), - (int16_t)(-0.7071 * 32768), (int16_t)(0.1951 * 32768), - (int16_t)(0.3827 * 32768), (int16_t)(-0.8315 * 32768), - (int16_t)(1.0000 * 32767), (int16_t)(-0.8315 * 32768), - (int16_t)(0.3827 * 32768), (int16_t)(0.1951 * 32768), - (int16_t)(-0.7071 * 32768), (int16_t)(0.9808 * 32768), - (int16_t)(-0.9239 * 32768), (int16_t)(0.5556 * 32768), - (int16_t)(-0.0000 * 32768), (int16_t)(-0.5556 * 32768), - (int16_t)(0.9239 * 32768), (int16_t)(-0.9808 * 32768), - (int16_t)(0.7071 * 32768), (int16_t)(-0.8315 * 32768), - (int16_t)(0.9239 * 32768), (int16_t)(-0.9808 * 32768), - (int16_t)(1.0000 * 32767), (int16_t)(-0.9808 * 32768), - (int16_t)(0.9239 * 32768), (int16_t)(-0.8315 * 32768), - (int16_t)(0.7071 * 32768), (int16_t)(-0.5556 * 32768), - (int16_t)(0.3827 * 32768), (int16_t)(-0.1951 * 32768), - (int16_t)(-0.0000 * 32768), (int16_t)(0.1951 * 32768), - (int16_t)(-0.3827 * 32768), (int16_t)(0.5556 * 32768)}; + (int16_t)(0.7071 * 32768), (int16_t)(0.8315 * 32768), (int16_t)(0.9239 * 32768), + (int16_t)(0.9808 * 32768), (int16_t)(1.0000 * 32767), (int16_t)(0.9808 * 32768), + (int16_t)(0.9239 * 32768), (int16_t)(0.8315 * 32768), (int16_t)(0.7071 * 32768), + (int16_t)(0.5556 * 32768), (int16_t)(0.3827 * 32768), (int16_t)(0.1951 * 32768), + (int16_t)(0.0000 * 32768), (int16_t)(-0.1951 * 32768), (int16_t)(-0.3827 * 32768), + (int16_t)(-0.5556 * 32768), (int16_t)(-0.7071 * 32768), (int16_t)(-0.1951 * 32768), + (int16_t)(0.3827 * 32768), (int16_t)(0.8315 * 32768), (int16_t)(1.0000 * 32767), + (int16_t)(0.8315 * 32768), (int16_t)(0.3827 * 32768), (int16_t)(-0.1951 * 32768), + (int16_t)(-0.7071 * 32768), (int16_t)(-0.9808 * 32768), (int16_t)(-0.9239 * 32768), + (int16_t)(-0.5556 * 32768), (int16_t)(-0.0000 * 32768), (int16_t)(0.5556 * 32768), + (int16_t)(0.9239 * 32768), (int16_t)(0.9808 * 32768), (int16_t)(-0.7071 * 32768), + (int16_t)(-0.9808 * 32768), (int16_t)(-0.3827 * 32768), (int16_t)(0.5556 * 32768), + (int16_t)(1.0000 * 32767), (int16_t)(0.5556 * 32768), (int16_t)(-0.3827 * 32768), + (int16_t)(-0.9808 * 32768), (int16_t)(-0.7071 * 32768), (int16_t)(0.1951 * 32768), + (int16_t)(0.9239 * 32768), (int16_t)(0.8315 * 32768), (int16_t)(0.0000 * 32768), + (int16_t)(-0.8315 * 32768), (int16_t)(-0.9239 * 32768), (int16_t)(-0.1951 * 32768), + (int16_t)(0.7071 * 32768), (int16_t)(-0.5556 * 32768), (int16_t)(-0.9239 * 32768), + (int16_t)(0.1951 * 32768), (int16_t)(1.0000 * 32767), (int16_t)(0.1951 * 32768), + (int16_t)(-0.9239 * 32768), (int16_t)(-0.5556 * 32768), (int16_t)(0.7071 * 32768), + (int16_t)(0.8315 * 32768), (int16_t)(-0.3827 * 32768), (int16_t)(-0.9808 * 32768), + (int16_t)(-0.0000 * 32768), (int16_t)(0.9808 * 32768), (int16_t)(0.3827 * 32768), + (int16_t)(-0.8315 * 32768), (int16_t)(0.7071 * 32768), (int16_t)(0.5556 * 32768), + (int16_t)(-0.9239 * 32768), (int16_t)(-0.1951 * 32768), (int16_t)(1.0000 * 32767), + (int16_t)(-0.1951 * 32768), (int16_t)(-0.9239 * 32768), (int16_t)(0.5556 * 32768), + (int16_t)(0.7071 * 32768), (int16_t)(-0.8315 * 32768), (int16_t)(-0.3827 * 32768), + (int16_t)(0.9808 * 32768), (int16_t)(0.0000 * 32768), (int16_t)(-0.9808 * 32768), + (int16_t)(0.3827 * 32768), (int16_t)(0.8315 * 32768), (int16_t)(-0.7071 * 32768), + (int16_t)(0.9808 * 32768), (int16_t)(-0.3827 * 32768), (int16_t)(-0.5556 * 32768), + (int16_t)(1.0000 * 32767), (int16_t)(-0.5556 * 32768), (int16_t)(-0.3827 * 32768), + (int16_t)(0.9808 * 32768), (int16_t)(-0.7071 * 32768), (int16_t)(-0.1951 * 32768), + (int16_t)(0.9239 * 32768), (int16_t)(-0.8315 * 32768), (int16_t)(-0.0000 * 32768), + (int16_t)(0.8315 * 32768), (int16_t)(-0.9239 * 32768), (int16_t)(0.1951 * 32768), + (int16_t)(-0.7071 * 32768), (int16_t)(0.1951 * 32768), (int16_t)(0.3827 * 32768), + (int16_t)(-0.8315 * 32768), (int16_t)(1.0000 * 32767), (int16_t)(-0.8315 * 32768), + (int16_t)(0.3827 * 32768), (int16_t)(0.1951 * 32768), (int16_t)(-0.7071 * 32768), + (int16_t)(0.9808 * 32768), (int16_t)(-0.9239 * 32768), (int16_t)(0.5556 * 32768), + (int16_t)(-0.0000 * 32768), (int16_t)(-0.5556 * 32768), (int16_t)(0.9239 * 32768), + (int16_t)(-0.9808 * 32768), (int16_t)(0.7071 * 32768), (int16_t)(-0.8315 * 32768), + (int16_t)(0.9239 * 32768), (int16_t)(-0.9808 * 32768), (int16_t)(1.0000 * 32767), + (int16_t)(-0.9808 * 32768), (int16_t)(0.9239 * 32768), (int16_t)(-0.8315 * 32768), + (int16_t)(0.7071 * 32768), (int16_t)(-0.5556 * 32768), (int16_t)(0.3827 * 32768), + (int16_t)(-0.1951 * 32768), (int16_t)(-0.0000 * 32768), (int16_t)(0.1951 * 32768), + (int16_t)(-0.3827 * 32768), (int16_t)(0.5556 * 32768)}; #endif diff --git a/system/embdrv/sbc/encoder/srce/sbc_enc_bit_alloc_mono.c b/system/embdrv/sbc/encoder/srce/sbc_enc_bit_alloc_mono.c index 868ce6f0dca..ea4c4608871 100644 --- a/system/embdrv/sbc/encoder/srce/sbc_enc_bit_alloc_mono.c +++ b/system/embdrv/sbc/encoder/srce/sbc_enc_bit_alloc_mono.c @@ -29,18 +29,18 @@ /*global arrays*/ const int16_t sbc_enc_as16Offset4[4][4] = { - {-1, 0, 0, 0}, {-2, 0, 0, 1}, {-2, 0, 0, 1}, {-2, 0, 0, 1}}; + {-1, 0, 0, 0}, {-2, 0, 0, 1}, {-2, 0, 0, 1}, {-2, 0, 0, 1}}; const int16_t sbc_enc_as16Offset8[4][8] = {{-2, 0, 0, 0, 0, 0, 0, 1}, {-3, 0, 0, 0, 0, 0, 1, 2}, {-4, 0, 0, 0, 0, 0, 1, 2}, {-4, 0, 0, 0, 0, 0, 1, 2}}; /**************************************************************************** -* BitAlloc - Calculates the required number of bits for the given scale factor -* and the number of subbands. -* -* RETURNS : N/A -*/ + * BitAlloc - Calculates the required number of bits for the given scale factor + * and the number of subbands. + * + * RETURNS : N/A + */ void sbc_enc_bit_alloc_mono(SBC_ENC_PARAMS* pstrCodecParams) { int32_t s32MaxBitNeed; /*to store the max bits needed per sb*/ @@ -69,25 +69,22 @@ void sbc_enc_bit_alloc_mono(SBC_ENC_PARAMS* pstrCodecParams) { } else { ps16GenBufPtr = ps16BitNeed + s32Ch * s32NumOfSubBands; if (s32NumOfSubBands == 4) { - ps16GenTabPtr = - (int16_t*)sbc_enc_as16Offset4[pstrCodecParams->s16SamplingFreq]; + ps16GenTabPtr = (int16_t*)sbc_enc_as16Offset4[pstrCodecParams->s16SamplingFreq]; } else { - ps16GenTabPtr = - (int16_t*)sbc_enc_as16Offset8[pstrCodecParams->s16SamplingFreq]; + ps16GenTabPtr = (int16_t*)sbc_enc_as16Offset8[pstrCodecParams->s16SamplingFreq]; } for (s32Sb = 0; s32Sb < s32NumOfSubBands; s32Sb++) { - if (pstrCodecParams - ->as16ScaleFactor[s32Ch * s32NumOfSubBands + s32Sb] == 0) + if (pstrCodecParams->as16ScaleFactor[s32Ch * s32NumOfSubBands + s32Sb] == 0) { *(ps16GenBufPtr) = -5; - else { - s32Loudness = (int32_t)( - pstrCodecParams - ->as16ScaleFactor[s32Ch * s32NumOfSubBands + s32Sb] - - *ps16GenTabPtr); - if (s32Loudness > 0) + } else { + s32Loudness = + (int32_t)(pstrCodecParams->as16ScaleFactor[s32Ch * s32NumOfSubBands + s32Sb] - + *ps16GenTabPtr); + if (s32Loudness > 0) { *(ps16GenBufPtr) = (int16_t)(s32Loudness >> 1); - else + } else { *(ps16GenBufPtr) = (int16_t)s32Loudness; + } } ps16GenBufPtr++; ps16GenTabPtr++; @@ -98,7 +95,9 @@ void sbc_enc_bit_alloc_mono(SBC_ENC_PARAMS* pstrCodecParams) { s32MaxBitNeed = 0; ps16GenBufPtr = ps16BitNeed + s32Ch * s32NumOfSubBands; for (s32Sb = 0; s32Sb < s32NumOfSubBands; s32Sb++) { - if (*(ps16GenBufPtr) > s32MaxBitNeed) s32MaxBitNeed = *(ps16GenBufPtr); + if (*(ps16GenBufPtr) > s32MaxBitNeed) { + s32MaxBitNeed = *(ps16GenBufPtr); + } ps16GenBufPtr++; } @@ -113,12 +112,12 @@ void sbc_enc_bit_alloc_mono(SBC_ENC_PARAMS* pstrCodecParams) { s32SliceCount = 0; for (s32Sb = 0; s32Sb < s32NumOfSubBands; s32Sb++) { - if ((((*ps16GenBufPtr - s32BitSlice) < 16) && - (*ps16GenBufPtr - s32BitSlice) >= 1)) { - if ((*ps16GenBufPtr - s32BitSlice) == 1) + if (((*ps16GenBufPtr - s32BitSlice) < 16) && (*ps16GenBufPtr - s32BitSlice) >= 1) { + if ((*ps16GenBufPtr - s32BitSlice) == 1) { s32SliceCount += 2; - else + } else { s32SliceCount++; + } } ps16GenBufPtr++; @@ -135,12 +134,13 @@ void sbc_enc_bit_alloc_mono(SBC_ENC_PARAMS* pstrCodecParams) { ps16GenArrPtr = pstrCodecParams->as16Bits + s32Ch * s32NumOfSubBands; ps16GenBufPtr = ps16BitNeed + s32Ch * s32NumOfSubBands; for (s32Sb = 0; s32Sb < s32NumOfSubBands; s32Sb++) { - if (*(ps16GenBufPtr) < s32BitSlice + 2) + if (*(ps16GenBufPtr) < s32BitSlice + 2) { *(ps16GenArrPtr) = 0; - else + } else { *(ps16GenArrPtr) = ((*(ps16GenBufPtr)-s32BitSlice) < 16) - ? (int16_t)(*(ps16GenBufPtr)-s32BitSlice) - : 16; + ? (int16_t)(*(ps16GenBufPtr)-s32BitSlice) + : 16; + } ps16GenBufPtr++; ps16GenArrPtr++; diff --git a/system/embdrv/sbc/encoder/srce/sbc_enc_bit_alloc_ste.c b/system/embdrv/sbc/encoder/srce/sbc_enc_bit_alloc_ste.c index 00ee65b00ad..f1098886e19 100644 --- a/system/embdrv/sbc/encoder/srce/sbc_enc_bit_alloc_ste.c +++ b/system/embdrv/sbc/encoder/srce/sbc_enc_bit_alloc_ste.c @@ -32,11 +32,11 @@ extern const int16_t sbc_enc_as16Offset4[4][4]; extern const int16_t sbc_enc_as16Offset8[4][8]; /**************************************************************************** -* BitAlloc - Calculates the required number of bits for the given scale factor -* and the number of subbands. -* -* RETURNS : N/A -*/ + * BitAlloc - Calculates the required number of bits for the given scale factor + * and the number of subbands. + * + * RETURNS : N/A + */ void sbc_enc_bit_alloc_ste(SBC_ENC_PARAMS* pstrCodecParams) { /* CAUTIOM -> mips optim for arm 32 require to use int32_t instead of int16_t @@ -67,26 +67,27 @@ void sbc_enc_bit_alloc_ste(SBC_ENC_PARAMS* pstrCodecParams) { ps16GenBufPtr = ps16BitNeed; for (s32Ch = 0; s32Ch < 2; s32Ch++) { if (s32NumOfSubBands == 4) { - ps16GenTabPtr = - (int16_t*)sbc_enc_as16Offset4[pstrCodecParams->s16SamplingFreq]; + ps16GenTabPtr = (int16_t*)sbc_enc_as16Offset4[pstrCodecParams->s16SamplingFreq]; } else { - ps16GenTabPtr = - (int16_t*)sbc_enc_as16Offset8[pstrCodecParams->s16SamplingFreq]; + ps16GenTabPtr = (int16_t*)sbc_enc_as16Offset8[pstrCodecParams->s16SamplingFreq]; } for (s32Sb = 0; s32Sb < s32NumOfSubBands; s32Sb++) { - if (*pas16ScaleFactor == 0) + if (*pas16ScaleFactor == 0) { *ps16GenBufPtr = -5; - else { + } else { s32Loudness = (int32_t)(*pas16ScaleFactor - *ps16GenTabPtr); - if (s32Loudness > 0) + if (s32Loudness > 0) { *ps16GenBufPtr = (int16_t)(s32Loudness >> 1); - else + } else { *ps16GenBufPtr = (int16_t)s32Loudness; + } } - if (*ps16GenBufPtr > s32MaxBitNeed) s32MaxBitNeed = *ps16GenBufPtr; + if (*ps16GenBufPtr > s32MaxBitNeed) { + s32MaxBitNeed = *ps16GenBufPtr; + } pas16ScaleFactor++; ps16GenBufPtr++; ps16GenTabPtr++; @@ -105,12 +106,12 @@ void sbc_enc_bit_alloc_ste(SBC_ENC_PARAMS* pstrCodecParams) { ps16GenBufPtr = ps16BitNeed; for (s32Sb = 0; s32Sb < 2 * s32NumOfSubBands; s32Sb++) { - if ((*ps16GenBufPtr >= s32BitSlice + 1) && - (*ps16GenBufPtr < s32BitSlice + 16)) { - if (*(ps16GenBufPtr) == s32BitSlice + 1) + if ((*ps16GenBufPtr >= s32BitSlice + 1) && (*ps16GenBufPtr < s32BitSlice + 16)) { + if (*(ps16GenBufPtr) == s32BitSlice + 1) { s32SliceCount += 2; - else + } else { s32SliceCount++; + } } ps16GenBufPtr++; } @@ -126,12 +127,13 @@ void sbc_enc_bit_alloc_ste(SBC_ENC_PARAMS* pstrCodecParams) { ps16GenArrPtr = pstrCodecParams->as16Bits; for (s32Ch = 0; s32Ch < 2; s32Ch++) { for (s32Sb = 0; s32Sb < s32NumOfSubBands; s32Sb++) { - if (*ps16GenBufPtr < s32BitSlice + 2) + if (*ps16GenBufPtr < s32BitSlice + 2) { *ps16GenArrPtr = 0; - else + } else { *ps16GenArrPtr = ((*(ps16GenBufPtr)-s32BitSlice) < 16) - ? (int16_t)(*(ps16GenBufPtr)-s32BitSlice) - : 16; + ? (int16_t)(*(ps16GenBufPtr)-s32BitSlice) + : 16; + } ps16GenBufPtr++; ps16GenArrPtr++; } diff --git a/system/embdrv/sbc/encoder/srce/sbc_enc_coeffs.c b/system/embdrv/sbc/encoder/srce/sbc_enc_coeffs.c index 2536b796dde..f356af48d7e 100644 --- a/system/embdrv/sbc/encoder/srce/sbc_enc_coeffs.c +++ b/system/embdrv/sbc/encoder/srce/sbc_enc_coeffs.c @@ -27,218 +27,202 @@ #if (SBC_ARM_ASM_OPT == FALSE && SBC_IPAQ_OPT == FALSE) #if (SBC_IS_64_MULT_IN_WINDOW_ACCU == FALSE) /*Window coeff for 4 sub band case*/ -const int16_t gas32CoeffFor4SBs[] = { - (int16_t)((int32_t)0x00000000 >> 16), (int16_t)0x00000000, - (int16_t)((int32_t)0x001194E6 >> 16), (int16_t)0x001194E6, - (int16_t)((int32_t)0x0030E2D3 >> 16), (int16_t)0x0030E2D3, - (int16_t)((int32_t)0x00599403 >> 16), (int16_t)0x00599403, - (int16_t)((int32_t)0x007DBCC8 >> 16), (int16_t)0x007DBCC8, - (int16_t)((int32_t)0x007F88E4 >> 16), (int16_t)0x007F88E4, - (int16_t)((int32_t)0x003D239B >> 16), (int16_t)0x003D239B, - (int16_t)((int32_t)0xFF9BB9D5 >> 16), (int16_t)0xFF9BB9D5, - - (int16_t)((int32_t)0x01659F45 >> 16), (int16_t)0x01659F45, - (int16_t)((int32_t)0x029DBAA3 >> 16), (int16_t)0x029DBAA3, - (int16_t)((int32_t)0x03B23341 >> 16), (int16_t)0x03B23341, - (int16_t)((int32_t)0x041EEE40 >> 16), (int16_t)0x041EEE40, - (int16_t)((int32_t)0x034FEE2C >> 16), (int16_t)0x034FEE2C, - (int16_t)((int32_t)0x00C8F2BC >> 16), (int16_t)0x00C8F2BC, - (int16_t)((int32_t)0xFC4F91D4 >> 16), (int16_t)0xFC4F91D4, - (int16_t)((int32_t)0xF60FAF37 >> 16), (int16_t)0xF60FAF37, - - (int16_t)((int32_t)0x115B1ED2 >> 16), (int16_t)0x115B1ED2, - (int16_t)((int32_t)0x18F55C90 >> 16), (int16_t)0x18F55C90, - (int16_t)((int32_t)0x1F91CA46 >> 16), (int16_t)0x1F91CA46, - (int16_t)((int32_t)0x2412F251 >> 16), (int16_t)0x2412F251, - (int16_t)((int32_t)0x25AC1FF2 >> 16), (int16_t)0x25AC1FF2, - (int16_t)((int32_t)0x2412F251 >> 16), (int16_t)0x2412F251, - (int16_t)((int32_t)0x1F91CA46 >> 16), (int16_t)0x1F91CA46, - (int16_t)((int32_t)0x18F55C90 >> 16), (int16_t)0x18F55C90, - - (int16_t)((int32_t)0xEEA4E12E >> 16), (int16_t)0xEEA4E12E, - (int16_t)((int32_t)0xF60FAF37 >> 16), (int16_t)0xF60FAF37, - (int16_t)((int32_t)0xFC4F91D4 >> 16), (int16_t)0xFC4F91D4, - (int16_t)((int32_t)0x00C8F2BC >> 16), (int16_t)0x00C8F2BC, - (int16_t)((int32_t)0x034FEE2C >> 16), (int16_t)0x034FEE2C, - (int16_t)((int32_t)0x041EEE40 >> 16), (int16_t)0x041EEE40, - (int16_t)((int32_t)0x03B23341 >> 16), (int16_t)0x03B23341, - (int16_t)((int32_t)0x029DBAA3 >> 16), (int16_t)0x029DBAA3, - - (int16_t)((int32_t)0xFE9A60BB >> 16), (int16_t)0xFE9A60BB, - (int16_t)((int32_t)0xFF9BB9D5 >> 16), (int16_t)0xFF9BB9D5, - (int16_t)((int32_t)0x003D239B >> 16), (int16_t)0x003D239B, - (int16_t)((int32_t)0x007F88E4 >> 16), (int16_t)0x007F88E4, - (int16_t)((int32_t)0x007DBCC8 >> 16), (int16_t)0x007DBCC8, - (int16_t)((int32_t)0x00599403 >> 16), (int16_t)0x00599403, - (int16_t)((int32_t)0x0030E2D3 >> 16), (int16_t)0x0030E2D3, - (int16_t)((int32_t)0x001194E6 >> 16), (int16_t)0x001194E6}; +const int16_t gas32CoeffFor4SBs[] = {(int16_t)((int32_t)0x00000000 >> 16), (int16_t)0x00000000, + (int16_t)((int32_t)0x001194E6 >> 16), (int16_t)0x001194E6, + (int16_t)((int32_t)0x0030E2D3 >> 16), (int16_t)0x0030E2D3, + (int16_t)((int32_t)0x00599403 >> 16), (int16_t)0x00599403, + (int16_t)((int32_t)0x007DBCC8 >> 16), (int16_t)0x007DBCC8, + (int16_t)((int32_t)0x007F88E4 >> 16), (int16_t)0x007F88E4, + (int16_t)((int32_t)0x003D239B >> 16), (int16_t)0x003D239B, + (int16_t)((int32_t)0xFF9BB9D5 >> 16), (int16_t)0xFF9BB9D5, + + (int16_t)((int32_t)0x01659F45 >> 16), (int16_t)0x01659F45, + (int16_t)((int32_t)0x029DBAA3 >> 16), (int16_t)0x029DBAA3, + (int16_t)((int32_t)0x03B23341 >> 16), (int16_t)0x03B23341, + (int16_t)((int32_t)0x041EEE40 >> 16), (int16_t)0x041EEE40, + (int16_t)((int32_t)0x034FEE2C >> 16), (int16_t)0x034FEE2C, + (int16_t)((int32_t)0x00C8F2BC >> 16), (int16_t)0x00C8F2BC, + (int16_t)((int32_t)0xFC4F91D4 >> 16), (int16_t)0xFC4F91D4, + (int16_t)((int32_t)0xF60FAF37 >> 16), (int16_t)0xF60FAF37, + + (int16_t)((int32_t)0x115B1ED2 >> 16), (int16_t)0x115B1ED2, + (int16_t)((int32_t)0x18F55C90 >> 16), (int16_t)0x18F55C90, + (int16_t)((int32_t)0x1F91CA46 >> 16), (int16_t)0x1F91CA46, + (int16_t)((int32_t)0x2412F251 >> 16), (int16_t)0x2412F251, + (int16_t)((int32_t)0x25AC1FF2 >> 16), (int16_t)0x25AC1FF2, + (int16_t)((int32_t)0x2412F251 >> 16), (int16_t)0x2412F251, + (int16_t)((int32_t)0x1F91CA46 >> 16), (int16_t)0x1F91CA46, + (int16_t)((int32_t)0x18F55C90 >> 16), (int16_t)0x18F55C90, + + (int16_t)((int32_t)0xEEA4E12E >> 16), (int16_t)0xEEA4E12E, + (int16_t)((int32_t)0xF60FAF37 >> 16), (int16_t)0xF60FAF37, + (int16_t)((int32_t)0xFC4F91D4 >> 16), (int16_t)0xFC4F91D4, + (int16_t)((int32_t)0x00C8F2BC >> 16), (int16_t)0x00C8F2BC, + (int16_t)((int32_t)0x034FEE2C >> 16), (int16_t)0x034FEE2C, + (int16_t)((int32_t)0x041EEE40 >> 16), (int16_t)0x041EEE40, + (int16_t)((int32_t)0x03B23341 >> 16), (int16_t)0x03B23341, + (int16_t)((int32_t)0x029DBAA3 >> 16), (int16_t)0x029DBAA3, + + (int16_t)((int32_t)0xFE9A60BB >> 16), (int16_t)0xFE9A60BB, + (int16_t)((int32_t)0xFF9BB9D5 >> 16), (int16_t)0xFF9BB9D5, + (int16_t)((int32_t)0x003D239B >> 16), (int16_t)0x003D239B, + (int16_t)((int32_t)0x007F88E4 >> 16), (int16_t)0x007F88E4, + (int16_t)((int32_t)0x007DBCC8 >> 16), (int16_t)0x007DBCC8, + (int16_t)((int32_t)0x00599403 >> 16), (int16_t)0x00599403, + (int16_t)((int32_t)0x0030E2D3 >> 16), (int16_t)0x0030E2D3, + (int16_t)((int32_t)0x001194E6 >> 16), (int16_t)0x001194E6}; /*Window coeff for 8 sub band case*/ const int16_t gas32CoeffFor8SBs[] = { - (int16_t)((int32_t)0x00000000 >> 16), (int16_t)0x00000000, - (int16_t)((int32_t)0x00052173 >> 16), (int16_t)0x00052173, - (int16_t)((int32_t)0x000B3F71 >> 16), (int16_t)0x000B3F71, - (int16_t)((int32_t)0x00122C7D >> 16), (int16_t)0x00122C7D, - (int16_t)((int32_t)0x001AFF89 >> 16), (int16_t)0x001AFF89, - (int16_t)((int32_t)0x00255A62 >> 16), (int16_t)0x00255A62, - (int16_t)((int32_t)0x003060F4 >> 16), (int16_t)0x003060F4, - (int16_t)((int32_t)0x003A72E7 >> 16), (int16_t)0x003A72E7, - - (int16_t)((int32_t)0x0041EC6A >> 16), (int16_t)0x0041EC6A, /* 8 */ - (int16_t)((int32_t)0x0044EF48 >> 16), (int16_t)0x0044EF48, - (int16_t)((int32_t)0x00415B75 >> 16), (int16_t)0x00415B75, - (int16_t)((int32_t)0x0034F8B6 >> 16), (int16_t)0x0034F8B6, - (int16_t)((int32_t)0x001D8FD2 >> 16), (int16_t)0x001D8FD2, - (int16_t)((int32_t)0xFFFA2413 >> 16), (int16_t)0xFFFA2413, - (int16_t)((int32_t)0xFFC9F10E >> 16), (int16_t)0xFFC9F10E, - (int16_t)((int32_t)0xFF8D6793 >> 16), (int16_t)0xFF8D6793, - - (int16_t)((int32_t)0x00B97348 >> 16), (int16_t)0x00B97348, /* 16 */ - (int16_t)((int32_t)0x01071B96 >> 16), (int16_t)0x01071B96, - (int16_t)((int32_t)0x0156B3CA >> 16), (int16_t)0x0156B3CA, - (int16_t)((int32_t)0x01A1B38B >> 16), (int16_t)0x01A1B38B, - (int16_t)((int32_t)0x01E0224C >> 16), (int16_t)0x01E0224C, - (int16_t)((int32_t)0x0209291F >> 16), (int16_t)0x0209291F, - (int16_t)((int32_t)0x02138653 >> 16), (int16_t)0x02138653, - (int16_t)((int32_t)0x01F5F424 >> 16), (int16_t)0x01F5F424, - - (int16_t)((int32_t)0x01A7ECEF >> 16), (int16_t)0x01A7ECEF, /* 24 */ - (int16_t)((int32_t)0x01223EBA >> 16), (int16_t)0x01223EBA, - (int16_t)((int32_t)0x005FD0FF >> 16), (int16_t)0x005FD0FF, - (int16_t)((int32_t)0xFF5EEB73 >> 16), (int16_t)0xFF5EEB73, - (int16_t)((int32_t)0xFE20435D >> 16), (int16_t)0xFE20435D, - (int16_t)((int32_t)0xFCA86E7E >> 16), (int16_t)0xFCA86E7E, - (int16_t)((int32_t)0xFAFF95FC >> 16), (int16_t)0xFAFF95FC, - (int16_t)((int32_t)0xF9312891 >> 16), (int16_t)0xF9312891, - - (int16_t)((int32_t)0x08B4307A >> 16), (int16_t)0x08B4307A, /* 32 */ - (int16_t)((int32_t)0x0A9F3E9A >> 16), (int16_t)0x0A9F3E9A, - (int16_t)((int32_t)0x0C7D59B6 >> 16), (int16_t)0x0C7D59B6, - (int16_t)((int32_t)0x0E3BB16F >> 16), (int16_t)0x0E3BB16F, - (int16_t)((int32_t)0x0FC721F9 >> 16), (int16_t)0x0FC721F9, - (int16_t)((int32_t)0x110ECEF0 >> 16), (int16_t)0x110ECEF0, - (int16_t)((int32_t)0x120435FA >> 16), (int16_t)0x120435FA, - (int16_t)((int32_t)0x129C226F >> 16), (int16_t)0x129C226F, - - (int16_t)((int32_t)0x12CF6C75 >> 16), (int16_t)0x12CF6C75, /* 40 */ - (int16_t)((int32_t)0x129C226F >> 16), (int16_t)0x129C226F, - (int16_t)((int32_t)0x120435FA >> 16), (int16_t)0x120435FA, - (int16_t)((int32_t)0x110ECEF0 >> 16), (int16_t)0x110ECEF0, - (int16_t)((int32_t)0x0FC721F9 >> 16), (int16_t)0x0FC721F9, - (int16_t)((int32_t)0x0E3BB16F >> 16), (int16_t)0x0E3BB16F, - (int16_t)((int32_t)0x0C7D59B6 >> 16), (int16_t)0x0C7D59B6, - (int16_t)((int32_t)0x0A9F3E9A >> 16), (int16_t)0x0A9F3E9A, - - (int16_t)((int32_t)0xF74BCF86 >> 16), (int16_t)0xF74BCF86, /* 48 */ - (int16_t)((int32_t)0xF9312891 >> 16), (int16_t)0xF9312891, - (int16_t)((int32_t)0xFAFF95FC >> 16), (int16_t)0xFAFF95FC, - (int16_t)((int32_t)0xFCA86E7E >> 16), (int16_t)0xFCA86E7E, - (int16_t)((int32_t)0xFE20435D >> 16), (int16_t)0xFE20435D, - (int16_t)((int32_t)0xFF5EEB73 >> 16), (int16_t)0xFF5EEB73, - (int16_t)((int32_t)0x005FD0FF >> 16), (int16_t)0x005FD0FF, - (int16_t)((int32_t)0x01223EBA >> 16), (int16_t)0x01223EBA, - - (int16_t)((int32_t)0x01A7ECEF >> 16), (int16_t)0x01A7ECEF, /* 56 */ - (int16_t)((int32_t)0x01F5F424 >> 16), (int16_t)0x01F5F424, - (int16_t)((int32_t)0x02138653 >> 16), (int16_t)0x02138653, - (int16_t)((int32_t)0x0209291F >> 16), (int16_t)0x0209291F, - (int16_t)((int32_t)0x01E0224C >> 16), (int16_t)0x01E0224C, - (int16_t)((int32_t)0x01A1B38B >> 16), (int16_t)0x01A1B38B, - (int16_t)((int32_t)0x0156B3CA >> 16), (int16_t)0x0156B3CA, - (int16_t)((int32_t)0x01071B96 >> 16), (int16_t)0x01071B96, - - (int16_t)((int32_t)0xFF468CB8 >> 16), (int16_t)0xFF468CB8, /* 64 */ - (int16_t)((int32_t)0xFF8D6793 >> 16), (int16_t)0xFF8D6793, - (int16_t)((int32_t)0xFFC9F10E >> 16), (int16_t)0xFFC9F10E, - (int16_t)((int32_t)0xFFFA2413 >> 16), (int16_t)0xFFFA2413, - (int16_t)((int32_t)0x001D8FD2 >> 16), (int16_t)0x001D8FD2, - (int16_t)((int32_t)0x0034F8B6 >> 16), (int16_t)0x0034F8B6, - (int16_t)((int32_t)0x00415B75 >> 16), (int16_t)0x00415B75, - (int16_t)((int32_t)0x0044EF48 >> 16), (int16_t)0x0044EF48, - - (int16_t)((int32_t)0x0041EC6A >> 16), (int16_t)0x0041EC6A, /* 72 */ - (int16_t)((int32_t)0x003A72E7 >> 16), (int16_t)0x003A72E7, - (int16_t)((int32_t)0x003060F4 >> 16), (int16_t)0x003060F4, - (int16_t)((int32_t)0x00255A62 >> 16), (int16_t)0x00255A62, - (int16_t)((int32_t)0x001AFF89 >> 16), (int16_t)0x001AFF89, - (int16_t)((int32_t)0x00122C7D >> 16), (int16_t)0x00122C7D, - (int16_t)((int32_t)0x000B3F71 >> 16), (int16_t)0x000B3F71, - (int16_t)((int32_t)0x00052173 >> 16), (int16_t)0x00052173}; + (int16_t)((int32_t)0x00000000 >> 16), (int16_t)0x00000000, + (int16_t)((int32_t)0x00052173 >> 16), (int16_t)0x00052173, + (int16_t)((int32_t)0x000B3F71 >> 16), (int16_t)0x000B3F71, + (int16_t)((int32_t)0x00122C7D >> 16), (int16_t)0x00122C7D, + (int16_t)((int32_t)0x001AFF89 >> 16), (int16_t)0x001AFF89, + (int16_t)((int32_t)0x00255A62 >> 16), (int16_t)0x00255A62, + (int16_t)((int32_t)0x003060F4 >> 16), (int16_t)0x003060F4, + (int16_t)((int32_t)0x003A72E7 >> 16), (int16_t)0x003A72E7, + + (int16_t)((int32_t)0x0041EC6A >> 16), (int16_t)0x0041EC6A, /* 8 */ + (int16_t)((int32_t)0x0044EF48 >> 16), (int16_t)0x0044EF48, + (int16_t)((int32_t)0x00415B75 >> 16), (int16_t)0x00415B75, + (int16_t)((int32_t)0x0034F8B6 >> 16), (int16_t)0x0034F8B6, + (int16_t)((int32_t)0x001D8FD2 >> 16), (int16_t)0x001D8FD2, + (int16_t)((int32_t)0xFFFA2413 >> 16), (int16_t)0xFFFA2413, + (int16_t)((int32_t)0xFFC9F10E >> 16), (int16_t)0xFFC9F10E, + (int16_t)((int32_t)0xFF8D6793 >> 16), (int16_t)0xFF8D6793, + + (int16_t)((int32_t)0x00B97348 >> 16), (int16_t)0x00B97348, /* 16 */ + (int16_t)((int32_t)0x01071B96 >> 16), (int16_t)0x01071B96, + (int16_t)((int32_t)0x0156B3CA >> 16), (int16_t)0x0156B3CA, + (int16_t)((int32_t)0x01A1B38B >> 16), (int16_t)0x01A1B38B, + (int16_t)((int32_t)0x01E0224C >> 16), (int16_t)0x01E0224C, + (int16_t)((int32_t)0x0209291F >> 16), (int16_t)0x0209291F, + (int16_t)((int32_t)0x02138653 >> 16), (int16_t)0x02138653, + (int16_t)((int32_t)0x01F5F424 >> 16), (int16_t)0x01F5F424, + + (int16_t)((int32_t)0x01A7ECEF >> 16), (int16_t)0x01A7ECEF, /* 24 */ + (int16_t)((int32_t)0x01223EBA >> 16), (int16_t)0x01223EBA, + (int16_t)((int32_t)0x005FD0FF >> 16), (int16_t)0x005FD0FF, + (int16_t)((int32_t)0xFF5EEB73 >> 16), (int16_t)0xFF5EEB73, + (int16_t)((int32_t)0xFE20435D >> 16), (int16_t)0xFE20435D, + (int16_t)((int32_t)0xFCA86E7E >> 16), (int16_t)0xFCA86E7E, + (int16_t)((int32_t)0xFAFF95FC >> 16), (int16_t)0xFAFF95FC, + (int16_t)((int32_t)0xF9312891 >> 16), (int16_t)0xF9312891, + + (int16_t)((int32_t)0x08B4307A >> 16), (int16_t)0x08B4307A, /* 32 */ + (int16_t)((int32_t)0x0A9F3E9A >> 16), (int16_t)0x0A9F3E9A, + (int16_t)((int32_t)0x0C7D59B6 >> 16), (int16_t)0x0C7D59B6, + (int16_t)((int32_t)0x0E3BB16F >> 16), (int16_t)0x0E3BB16F, + (int16_t)((int32_t)0x0FC721F9 >> 16), (int16_t)0x0FC721F9, + (int16_t)((int32_t)0x110ECEF0 >> 16), (int16_t)0x110ECEF0, + (int16_t)((int32_t)0x120435FA >> 16), (int16_t)0x120435FA, + (int16_t)((int32_t)0x129C226F >> 16), (int16_t)0x129C226F, + + (int16_t)((int32_t)0x12CF6C75 >> 16), (int16_t)0x12CF6C75, /* 40 */ + (int16_t)((int32_t)0x129C226F >> 16), (int16_t)0x129C226F, + (int16_t)((int32_t)0x120435FA >> 16), (int16_t)0x120435FA, + (int16_t)((int32_t)0x110ECEF0 >> 16), (int16_t)0x110ECEF0, + (int16_t)((int32_t)0x0FC721F9 >> 16), (int16_t)0x0FC721F9, + (int16_t)((int32_t)0x0E3BB16F >> 16), (int16_t)0x0E3BB16F, + (int16_t)((int32_t)0x0C7D59B6 >> 16), (int16_t)0x0C7D59B6, + (int16_t)((int32_t)0x0A9F3E9A >> 16), (int16_t)0x0A9F3E9A, + + (int16_t)((int32_t)0xF74BCF86 >> 16), (int16_t)0xF74BCF86, /* 48 */ + (int16_t)((int32_t)0xF9312891 >> 16), (int16_t)0xF9312891, + (int16_t)((int32_t)0xFAFF95FC >> 16), (int16_t)0xFAFF95FC, + (int16_t)((int32_t)0xFCA86E7E >> 16), (int16_t)0xFCA86E7E, + (int16_t)((int32_t)0xFE20435D >> 16), (int16_t)0xFE20435D, + (int16_t)((int32_t)0xFF5EEB73 >> 16), (int16_t)0xFF5EEB73, + (int16_t)((int32_t)0x005FD0FF >> 16), (int16_t)0x005FD0FF, + (int16_t)((int32_t)0x01223EBA >> 16), (int16_t)0x01223EBA, + + (int16_t)((int32_t)0x01A7ECEF >> 16), (int16_t)0x01A7ECEF, /* 56 */ + (int16_t)((int32_t)0x01F5F424 >> 16), (int16_t)0x01F5F424, + (int16_t)((int32_t)0x02138653 >> 16), (int16_t)0x02138653, + (int16_t)((int32_t)0x0209291F >> 16), (int16_t)0x0209291F, + (int16_t)((int32_t)0x01E0224C >> 16), (int16_t)0x01E0224C, + (int16_t)((int32_t)0x01A1B38B >> 16), (int16_t)0x01A1B38B, + (int16_t)((int32_t)0x0156B3CA >> 16), (int16_t)0x0156B3CA, + (int16_t)((int32_t)0x01071B96 >> 16), (int16_t)0x01071B96, + + (int16_t)((int32_t)0xFF468CB8 >> 16), (int16_t)0xFF468CB8, /* 64 */ + (int16_t)((int32_t)0xFF8D6793 >> 16), (int16_t)0xFF8D6793, + (int16_t)((int32_t)0xFFC9F10E >> 16), (int16_t)0xFFC9F10E, + (int16_t)((int32_t)0xFFFA2413 >> 16), (int16_t)0xFFFA2413, + (int16_t)((int32_t)0x001D8FD2 >> 16), (int16_t)0x001D8FD2, + (int16_t)((int32_t)0x0034F8B6 >> 16), (int16_t)0x0034F8B6, + (int16_t)((int32_t)0x00415B75 >> 16), (int16_t)0x00415B75, + (int16_t)((int32_t)0x0044EF48 >> 16), (int16_t)0x0044EF48, + + (int16_t)((int32_t)0x0041EC6A >> 16), (int16_t)0x0041EC6A, /* 72 */ + (int16_t)((int32_t)0x003A72E7 >> 16), (int16_t)0x003A72E7, + (int16_t)((int32_t)0x003060F4 >> 16), (int16_t)0x003060F4, + (int16_t)((int32_t)0x00255A62 >> 16), (int16_t)0x00255A62, + (int16_t)((int32_t)0x001AFF89 >> 16), (int16_t)0x001AFF89, + (int16_t)((int32_t)0x00122C7D >> 16), (int16_t)0x00122C7D, + (int16_t)((int32_t)0x000B3F71 >> 16), (int16_t)0x000B3F71, + (int16_t)((int32_t)0x00052173 >> 16), (int16_t)0x00052173}; #else /*Window coeff for 4 sub band case*/ const int32_t gas32CoeffFor4SBs[] = { - (int32_t)0x00000000, (int32_t)0x001194E6, (int32_t)0x0030E2D3, - (int32_t)0x00599403, (int32_t)0x007DBCC8, (int32_t)0x007F88E4, - (int32_t)0x003D239B, (int32_t)0xFF9BB9D5, + (int32_t)0x00000000, (int32_t)0x001194E6, (int32_t)0x0030E2D3, (int32_t)0x00599403, + (int32_t)0x007DBCC8, (int32_t)0x007F88E4, (int32_t)0x003D239B, (int32_t)0xFF9BB9D5, - (int32_t)0x01659F45, (int32_t)0x029DBAA3, (int32_t)0x03B23341, - (int32_t)0x041EEE40, (int32_t)0x034FEE2C, (int32_t)0x00C8F2BC, - (int32_t)0xFC4F91D4, (int32_t)0xF60FAF37, + (int32_t)0x01659F45, (int32_t)0x029DBAA3, (int32_t)0x03B23341, (int32_t)0x041EEE40, + (int32_t)0x034FEE2C, (int32_t)0x00C8F2BC, (int32_t)0xFC4F91D4, (int32_t)0xF60FAF37, - (int32_t)0x115B1ED2, (int32_t)0x18F55C90, (int32_t)0x1F91CA46, - (int32_t)0x2412F251, (int32_t)0x25AC1FF2, (int32_t)0x2412F251, - (int32_t)0x1F91CA46, (int32_t)0x18F55C90, + (int32_t)0x115B1ED2, (int32_t)0x18F55C90, (int32_t)0x1F91CA46, (int32_t)0x2412F251, + (int32_t)0x25AC1FF2, (int32_t)0x2412F251, (int32_t)0x1F91CA46, (int32_t)0x18F55C90, - (int32_t)0xEEA4E12E, (int32_t)0xF60FAF37, (int32_t)0xFC4F91D4, - (int32_t)0x00C8F2BC, (int32_t)0x034FEE2C, (int32_t)0x041EEE40, - (int32_t)0x03B23341, (int32_t)0x029DBAA3, + (int32_t)0xEEA4E12E, (int32_t)0xF60FAF37, (int32_t)0xFC4F91D4, (int32_t)0x00C8F2BC, + (int32_t)0x034FEE2C, (int32_t)0x041EEE40, (int32_t)0x03B23341, (int32_t)0x029DBAA3, - (int32_t)0xFE9A60BB, (int32_t)0xFF9BB9D5, (int32_t)0x003D239B, - (int32_t)0x007F88E4, (int32_t)0x007DBCC8, (int32_t)0x00599403, - (int32_t)0x0030E2D3, (int32_t)0x001194E6}; + (int32_t)0xFE9A60BB, (int32_t)0xFF9BB9D5, (int32_t)0x003D239B, (int32_t)0x007F88E4, + (int32_t)0x007DBCC8, (int32_t)0x00599403, (int32_t)0x0030E2D3, (int32_t)0x001194E6}; /*Window coeff for 8 sub band case*/ const int32_t gas32CoeffFor8SBs[] = { - (int32_t)0x00000000, (int32_t)0x00052173, (int32_t)0x000B3F71, - (int32_t)0x00122C7D, (int32_t)0x001AFF89, (int32_t)0x00255A62, - (int32_t)0x003060F4, (int32_t)0x003A72E7, - - (int32_t)0x0041EC6A, /* 8 */ - (int32_t)0x0044EF48, (int32_t)0x00415B75, (int32_t)0x0034F8B6, - (int32_t)0x001D8FD2, (int32_t)0xFFFA2413, (int32_t)0xFFC9F10E, - (int32_t)0xFF8D6793, - - (int32_t)0x00B97348, /* 16 */ - (int32_t)0x01071B96, (int32_t)0x0156B3CA, (int32_t)0x01A1B38B, - (int32_t)0x01E0224C, (int32_t)0x0209291F, (int32_t)0x02138653, - (int32_t)0x01F5F424, - - (int32_t)0x01A7ECEF, /* 24 */ - (int32_t)0x01223EBA, (int32_t)0x005FD0FF, (int32_t)0xFF5EEB73, - (int32_t)0xFE20435D, (int32_t)0xFCA86E7E, (int32_t)0xFAFF95FC, - (int32_t)0xF9312891, - - (int32_t)0x08B4307A, /* 32 */ - (int32_t)0x0A9F3E9A, (int32_t)0x0C7D59B6, (int32_t)0x0E3BB16F, - (int32_t)0x0FC721F9, (int32_t)0x110ECEF0, (int32_t)0x120435FA, - (int32_t)0x129C226F, - - (int32_t)0x12CF6C75, /* 40 */ - (int32_t)0x129C226F, (int32_t)0x120435FA, (int32_t)0x110ECEF0, - (int32_t)0x0FC721F9, (int32_t)0x0E3BB16F, (int32_t)0x0C7D59B6, - (int32_t)0x0A9F3E9A, - - (int32_t)0xF74BCF86, /* 48 */ - (int32_t)0xF9312891, (int32_t)0xFAFF95FC, (int32_t)0xFCA86E7E, - (int32_t)0xFE20435D, (int32_t)0xFF5EEB73, (int32_t)0x005FD0FF, - (int32_t)0x01223EBA, - - (int32_t)0x01A7ECEF, /* 56 */ - (int32_t)0x01F5F424, (int32_t)0x02138653, (int32_t)0x0209291F, - (int32_t)0x01E0224C, (int32_t)0x01A1B38B, (int32_t)0x0156B3CA, - (int32_t)0x01071B96, - - (int32_t)0xFF468CB8, /* 64 */ - (int32_t)0xFF8D6793, (int32_t)0xFFC9F10E, (int32_t)0xFFFA2413, - (int32_t)0x001D8FD2, (int32_t)0x0034F8B6, (int32_t)0x00415B75, - (int32_t)0x0044EF48, - - (int32_t)0x0041EC6A, /* 72 */ - (int32_t)0x003A72E7, (int32_t)0x003060F4, (int32_t)0x00255A62, - (int32_t)0x001AFF89, (int32_t)0x00122C7D, (int32_t)0x000B3F71, - (int32_t)0x00052173}; + (int32_t)0x00000000, (int32_t)0x00052173, (int32_t)0x000B3F71, (int32_t)0x00122C7D, + (int32_t)0x001AFF89, (int32_t)0x00255A62, (int32_t)0x003060F4, (int32_t)0x003A72E7, + + (int32_t)0x0041EC6A, /* 8 */ + (int32_t)0x0044EF48, (int32_t)0x00415B75, (int32_t)0x0034F8B6, (int32_t)0x001D8FD2, + (int32_t)0xFFFA2413, (int32_t)0xFFC9F10E, (int32_t)0xFF8D6793, + + (int32_t)0x00B97348, /* 16 */ + (int32_t)0x01071B96, (int32_t)0x0156B3CA, (int32_t)0x01A1B38B, (int32_t)0x01E0224C, + (int32_t)0x0209291F, (int32_t)0x02138653, (int32_t)0x01F5F424, + + (int32_t)0x01A7ECEF, /* 24 */ + (int32_t)0x01223EBA, (int32_t)0x005FD0FF, (int32_t)0xFF5EEB73, (int32_t)0xFE20435D, + (int32_t)0xFCA86E7E, (int32_t)0xFAFF95FC, (int32_t)0xF9312891, + + (int32_t)0x08B4307A, /* 32 */ + (int32_t)0x0A9F3E9A, (int32_t)0x0C7D59B6, (int32_t)0x0E3BB16F, (int32_t)0x0FC721F9, + (int32_t)0x110ECEF0, (int32_t)0x120435FA, (int32_t)0x129C226F, + + (int32_t)0x12CF6C75, /* 40 */ + (int32_t)0x129C226F, (int32_t)0x120435FA, (int32_t)0x110ECEF0, (int32_t)0x0FC721F9, + (int32_t)0x0E3BB16F, (int32_t)0x0C7D59B6, (int32_t)0x0A9F3E9A, + + (int32_t)0xF74BCF86, /* 48 */ + (int32_t)0xF9312891, (int32_t)0xFAFF95FC, (int32_t)0xFCA86E7E, (int32_t)0xFE20435D, + (int32_t)0xFF5EEB73, (int32_t)0x005FD0FF, (int32_t)0x01223EBA, + + (int32_t)0x01A7ECEF, /* 56 */ + (int32_t)0x01F5F424, (int32_t)0x02138653, (int32_t)0x0209291F, (int32_t)0x01E0224C, + (int32_t)0x01A1B38B, (int32_t)0x0156B3CA, (int32_t)0x01071B96, + + (int32_t)0xFF468CB8, /* 64 */ + (int32_t)0xFF8D6793, (int32_t)0xFFC9F10E, (int32_t)0xFFFA2413, (int32_t)0x001D8FD2, + (int32_t)0x0034F8B6, (int32_t)0x00415B75, (int32_t)0x0044EF48, + + (int32_t)0x0041EC6A, /* 72 */ + (int32_t)0x003A72E7, (int32_t)0x003060F4, (int32_t)0x00255A62, (int32_t)0x001AFF89, + (int32_t)0x00122C7D, (int32_t)0x000B3F71, (int32_t)0x00052173}; #endif #endif diff --git a/system/embdrv/sbc/encoder/srce/sbc_encoder.c b/system/embdrv/sbc/encoder/srce/sbc_encoder.c index e69b1b6153d..36fb5a73eb6 100644 --- a/system/embdrv/sbc/encoder/srce/sbc_encoder.c +++ b/system/embdrv/sbc/encoder/srce/sbc_encoder.c @@ -18,7 +18,7 @@ /****************************************************************************** * - * contains code for encoder flow and initalization of encoder + * contains code for encoder flow and initialization of encoder * ******************************************************************************/ @@ -35,8 +35,7 @@ int32_t s32LRDiff[SBC_MAX_NUM_OF_BLOCKS] = {0}; int32_t s32LRSum[SBC_MAX_NUM_OF_BLOCKS] = {0}; #endif -uint32_t SBC_Encode(SBC_ENC_PARAMS* pstrEncParams, int16_t* input, - uint8_t* output) { +uint32_t SBC_Encode(SBC_ENC_PARAMS* pstrEncParams, int16_t* input, uint8_t* output) { int32_t s32Ch; /* counter for ch*/ int32_t s32Sb; /* counter for sub-band*/ uint32_t u32Count, maxBit = 0; /* loop count*/ @@ -54,10 +53,11 @@ uint32_t SBC_Encode(SBC_ENC_PARAMS* pstrEncParams, int16_t* input, register int32_t s32NumOfSubBands = pstrEncParams->s16NumOfSubBands; /* SBC ananlysis filter*/ - if (s32NumOfSubBands == 4) + if (s32NumOfSubBands == 4) { SbcAnalysisFilter4(pstrEncParams, input); - else + } else { SbcAnalysisFilter8(pstrEncParams, input); + } /* compute the scale factor, and save the max */ ps16ScfL = pstrEncParams->as16ScaleFactor; @@ -67,23 +67,29 @@ uint32_t SBC_Encode(SBC_ENC_PARAMS* pstrEncParams, int16_t* input, SbBuffer = pstrEncParams->s32SbBuffer + s32Sb; s32MaxValue = 0; for (s32Blk = s32NumOfBlocks; s32Blk > 0; s32Blk--) { - if (s32MaxValue < abs32(*SbBuffer)) s32MaxValue = abs32(*SbBuffer); + if (s32MaxValue < abs32(*SbBuffer)) { + s32MaxValue = abs32(*SbBuffer); + } SbBuffer += s32Ch; } u32Count = (s32MaxValue > 0x800000) ? 9 : 0; for (; u32Count < 15; u32Count++) { - if (s32MaxValue <= (int32_t)(0x8000 << u32Count)) break; + if (s32MaxValue <= (int32_t)(0x8000 << u32Count)) { + break; + } } *ps16ScfL++ = (int16_t)u32Count; - if (u32Count > maxBit) maxBit = u32Count; + if (u32Count > maxBit) { + maxBit = u32Count; + } } /* In case of JS processing,check whether to use JS */ #if (SBC_JOINT_STE_INCLUDED == TRUE) if (pstrEncParams->s16ChannelMode == SBC_JOINT_STEREO) { - /* Calculate sum and differance scale factors for making JS decision */ + /* Calculate sum and difference scale factors for making JS decision */ ps16ScfL = pstrEncParams->as16ScaleFactor; /* calculate the scale factor of Joint stereo max sum and diff */ for (s32Sb = 0; s32Sb < s32NumOfSubBands - 1; s32Sb++) { @@ -94,28 +100,39 @@ uint32_t SBC_Encode(SBC_ENC_PARAMS* pstrEncParams, int16_t* input, pDiff = s32LRDiff; for (s32Blk = 0; s32Blk < s32NumOfBlocks; s32Blk++) { *pSum = (*SbBuffer + *(SbBuffer + s32NumOfSubBands)) >> 1; - if (abs32(*pSum) > s32MaxValue) s32MaxValue = abs32(*pSum); + if (abs32(*pSum) > s32MaxValue) { + s32MaxValue = abs32(*pSum); + } pSum++; *pDiff = (*SbBuffer - *(SbBuffer + s32NumOfSubBands)) >> 1; - if (abs32(*pDiff) > s32MaxValue2) s32MaxValue2 = abs32(*pDiff); + if (abs32(*pDiff) > s32MaxValue2) { + s32MaxValue2 = abs32(*pDiff); + } pDiff++; SbBuffer += s32Ch; } u32Count = (s32MaxValue > 0x800000) ? 9 : 0; for (; u32Count < 15; u32Count++) { - if (s32MaxValue <= (int32_t)(0x8000 << u32Count)) break; + if (s32MaxValue <= (int32_t)(0x8000 << u32Count)) { + break; + } } u32CountSum = u32Count; u32Count = (s32MaxValue2 > 0x800000) ? 9 : 0; for (; u32Count < 15; u32Count++) { - if (s32MaxValue2 <= (int32_t)(0x8000 << u32Count)) break; + if (s32MaxValue2 <= (int32_t)(0x8000 << u32Count)) { + break; + } } u32CountDiff = u32Count; - if ((*ps16ScfL + *(ps16ScfL + s32NumOfSubBands)) > - (int16_t)(u32CountSum + u32CountDiff)) { - if (u32CountSum > maxBit) maxBit = u32CountSum; + if ((*ps16ScfL + *(ps16ScfL + s32NumOfSubBands)) > (int16_t)(u32CountSum + u32CountDiff)) { + if (u32CountSum > maxBit) { + maxBit = u32CountSum; + } - if (u32CountDiff > maxBit) maxBit = u32CountDiff; + if (u32CountDiff > maxBit) { + maxBit = u32CountDiff; + } *ps16ScfL = (int16_t)u32CountSum; *(ps16ScfL + s32NumOfSubBands) = (int16_t)u32CountDiff; @@ -147,20 +164,21 @@ uint32_t SBC_Encode(SBC_ENC_PARAMS* pstrEncParams, int16_t* input, /* bit allocation */ if ((pstrEncParams->s16ChannelMode == SBC_STEREO) || - (pstrEncParams->s16ChannelMode == SBC_JOINT_STEREO)) + (pstrEncParams->s16ChannelMode == SBC_JOINT_STEREO)) { sbc_enc_bit_alloc_ste(pstrEncParams); - else + } else { sbc_enc_bit_alloc_mono(pstrEncParams); + } /* Quantize the encoded audio */ return EncPacking(pstrEncParams, output); } /**************************************************************************** -* InitSbcAnalysisFilt - Initalizes the input data to 0 -* -* RETURNS : N/A -*/ + * InitSbcAnalysisFilt - Initializes the input data to 0 + * + * RETURNS : N/A + */ void SBC_Encoder_Init(SBC_ENC_PARAMS* pstrEncParams) { uint16_t s16SamplingFreq; /*temp variable to store smpling freq*/ int16_t s16Bitpool; /*to store bit pool value*/ @@ -169,66 +187,65 @@ void SBC_Encoder_Init(SBC_ENC_PARAMS* pstrEncParams) { uint16_t HeaderParams; /* Required number of channels */ - if (pstrEncParams->s16ChannelMode == SBC_MONO) + if (pstrEncParams->s16ChannelMode == SBC_MONO) { pstrEncParams->s16NumOfChannels = 1; - else + } else { pstrEncParams->s16NumOfChannels = 2; + } /* Bit pool calculation */ - if (pstrEncParams->s16SamplingFreq == SBC_sf16000) + if (pstrEncParams->s16SamplingFreq == SBC_sf16000) { s16SamplingFreq = 16000; - else if (pstrEncParams->s16SamplingFreq == SBC_sf32000) + } else if (pstrEncParams->s16SamplingFreq == SBC_sf32000) { s16SamplingFreq = 32000; - else if (pstrEncParams->s16SamplingFreq == SBC_sf44100) + } else if (pstrEncParams->s16SamplingFreq == SBC_sf44100) { s16SamplingFreq = 44100; - else + } else { s16SamplingFreq = 48000; + } if ((pstrEncParams->s16ChannelMode == SBC_JOINT_STEREO) || (pstrEncParams->s16ChannelMode == SBC_STEREO)) { s16Bitpool = - (int16_t)((pstrEncParams->u16BitRate * pstrEncParams->s16NumOfSubBands * - 1000 / s16SamplingFreq) - - ((32 + (4 * pstrEncParams->s16NumOfSubBands * - pstrEncParams->s16NumOfChannels) + - ((pstrEncParams->s16ChannelMode - 2) * - pstrEncParams->s16NumOfSubBands)) / - pstrEncParams->s16NumOfBlocks)); - - s16FrameLen = 4 + - (4 * pstrEncParams->s16NumOfSubBands * - pstrEncParams->s16NumOfChannels) / - 8 + - (((pstrEncParams->s16ChannelMode - 2) * - pstrEncParams->s16NumOfSubBands) + + (int16_t)((pstrEncParams->u16BitRate * pstrEncParams->s16NumOfSubBands * 1000 / + s16SamplingFreq) - + ((32 + + (4 * pstrEncParams->s16NumOfSubBands * pstrEncParams->s16NumOfChannels) + + ((pstrEncParams->s16ChannelMode - 2) * pstrEncParams->s16NumOfSubBands)) / + pstrEncParams->s16NumOfBlocks)); + + s16FrameLen = 4 + (4 * pstrEncParams->s16NumOfSubBands * pstrEncParams->s16NumOfChannels) / 8 + + (((pstrEncParams->s16ChannelMode - 2) * pstrEncParams->s16NumOfSubBands) + (pstrEncParams->s16NumOfBlocks * s16Bitpool)) / - 8; + 8; s16BitRate = (8 * s16FrameLen * s16SamplingFreq) / - (pstrEncParams->s16NumOfSubBands * - pstrEncParams->s16NumOfBlocks * 1000); + (pstrEncParams->s16NumOfSubBands * pstrEncParams->s16NumOfBlocks * 1000); - if (s16BitRate > pstrEncParams->u16BitRate) s16Bitpool--; + if (s16BitRate > pstrEncParams->u16BitRate) { + s16Bitpool--; + } - if (pstrEncParams->s16NumOfSubBands == 8) + if (pstrEncParams->s16NumOfSubBands == 8) { pstrEncParams->s16BitPool = (s16Bitpool > 255) ? 255 : s16Bitpool; - else + } else { pstrEncParams->s16BitPool = (s16Bitpool > 128) ? 128 : s16Bitpool; + } } else { - s16Bitpool = (int16_t)( - ((pstrEncParams->s16NumOfSubBands * pstrEncParams->u16BitRate * 1000) / - (s16SamplingFreq * pstrEncParams->s16NumOfChannels)) - - (((32 / pstrEncParams->s16NumOfChannels) + - (4 * pstrEncParams->s16NumOfSubBands)) / - pstrEncParams->s16NumOfBlocks)); - - pstrEncParams->s16BitPool = - (s16Bitpool > (16 * pstrEncParams->s16NumOfSubBands)) - ? (16 * pstrEncParams->s16NumOfSubBands) - : s16Bitpool; + s16Bitpool = (int16_t)(((pstrEncParams->s16NumOfSubBands * pstrEncParams->u16BitRate * 1000) / + (s16SamplingFreq * pstrEncParams->s16NumOfChannels)) - + (((32 / pstrEncParams->s16NumOfChannels) + + (4 * pstrEncParams->s16NumOfSubBands)) / + pstrEncParams->s16NumOfBlocks)); + + pstrEncParams->s16BitPool = (s16Bitpool > (16 * pstrEncParams->s16NumOfSubBands)) + ? (16 * pstrEncParams->s16NumOfSubBands) + : s16Bitpool; } - if (pstrEncParams->s16BitPool < 0) pstrEncParams->s16BitPool = 0; + if (pstrEncParams->s16BitPool < 0) { + pstrEncParams->s16BitPool = 0; + } /* sampling freq */ HeaderParams = ((pstrEncParams->s16SamplingFreq & 3) << 6); @@ -244,15 +261,17 @@ void SBC_Encoder_Init(SBC_ENC_PARAMS* pstrEncParams) { pstrEncParams->FrameHeader = HeaderParams; if (pstrEncParams->s16NumOfSubBands == 4) { - if (pstrEncParams->s16NumOfChannels == 1) + if (pstrEncParams->s16NumOfChannels == 1) { EncMaxShiftCounter = ((ENC_VX_BUFFER_SIZE - 4 * 10) >> 2) << 2; - else + } else { EncMaxShiftCounter = ((ENC_VX_BUFFER_SIZE - 4 * 10 * 2) >> 3) << 2; + } } else { - if (pstrEncParams->s16NumOfChannels == 1) + if (pstrEncParams->s16NumOfChannels == 1) { EncMaxShiftCounter = ((ENC_VX_BUFFER_SIZE - 8 * 10) >> 3) << 3; - else + } else { EncMaxShiftCounter = ((ENC_VX_BUFFER_SIZE - 8 * 10 * 2) >> 4) << 3; + } } SbcAnalysisInit(); diff --git a/system/embdrv/sbc/encoder/srce/sbc_packing.c b/system/embdrv/sbc/encoder/srce/sbc_packing.c index 73a708f6a10..29880b2169b 100644 --- a/system/embdrv/sbc/encoder/srce/sbc_packing.c +++ b/system/embdrv/sbc/encoder/srce/sbc_packing.c @@ -26,19 +26,18 @@ #include "sbc_encoder.h" #if (SBC_ARM_ASM_OPT == TRUE) -#define Mult32(s32In1, s32In2, s32OutLow) \ - { \ +#define Mult32(s32In1, s32In2, s32OutLow) \ + { \ __asm { \ - MUL s32OutLow,s32In1,s32In2; } \ + MUL s32OutLow,s32In1,s32In2; } \ } -#define Mult64(s32In1, s32In2, s32OutLow, s32OutHi) \ - { \ +#define Mult64(s32In1, s32In2, s32OutLow, s32OutHi) \ + { \ __asm { \ - SMULL s32OutLow,s32OutHi,s32In1,s32In2 } \ + SMULL s32OutLow,s32OutHi,s32In1,s32In2 } \ } #else -#define Mult32(s32In1, s32In2, s32OutLow) \ - s32OutLow = (int32_t)(s32In1) * (int32_t)(s32In2); +#define Mult32(s32In1, s32In2, s32OutLow) s32OutLow = (int32_t)(s32In1) * (int32_t)(s32In2); #define Mult64(s32In1, s32In2, s32OutLow, s32OutHi) \ { \ __builtin_mul_overflow(s32In1, (uint16_t)s32In2, &s64OutTemp); \ @@ -56,12 +55,11 @@ uint32_t EncPacking(SBC_ENC_PARAMS* pstrEncParams, uint8_t* output) { int32_t s32Sb; /* counter for sub-band*/ int32_t s32PresentBit; /* represents bit to be stored*/ /*int32_t s32LoopCountI; loop counter*/ - int32_t s32LoopCountJ; /* loop counter*/ - uint32_t u32QuantizedSbValue, - u32QuantizedSbValue0; /* temp variable to store quantized sb val*/ - int32_t s32LoopCount; /* loop counter*/ - uint8_t u8XoredVal; /* to store XORed value in CRC calculation*/ - uint8_t u8CRC; /* to store CRC value*/ + int32_t s32LoopCountJ; /* loop counter*/ + uint32_t u32QuantizedSbValue, u32QuantizedSbValue0; /* temp variable to store quantized sb val*/ + int32_t s32LoopCount; /* loop counter*/ + uint8_t u8XoredVal; /* to store XORed value in CRC calculation*/ + uint8_t u8CRC; /* to store CRC value*/ int16_t* ps16GenPtr; int32_t s32NumOfBlocks; int32_t s32NumOfSubBands = pstrEncParams->s16NumOfSubBands; @@ -240,8 +238,7 @@ uint32_t EncPacking(SBC_ENC_PARAMS* pstrEncParams, uint8_t* output) { } if (pstrEncParams->s16ChannelMode == SBC_JOINT_STEREO) { - for (s32LoopCountJ = 7; s32LoopCountJ >= (8 - s32NumOfSubBands); - s32LoopCountJ--) { + for (s32LoopCountJ = 7; s32LoopCountJ >= (8 - s32NumOfSubBands); s32LoopCountJ--) { u8XoredVal = ((u8CRC >> 7) & 0x01) ^ ((Temp >> s32LoopCountJ) & 0x01); u8CRC <<= 1; u8CRC ^= (u8XoredVal * 0x1D); diff --git a/system/embdrv/tests/src/aptx.cc b/system/embdrv/tests/src/aptx.cc index e41250f71a8..14482c495c5 100644 --- a/system/embdrv/tests/src/aptx.cc +++ b/system/embdrv/tests/src/aptx.cc @@ -28,10 +28,10 @@ #define BYTES_PER_CODEWORD 16 class LibAptxEncTest : public ::testing::Test { - private: +private: void* aptxbtenc = nullptr; - protected: +protected: void SetUp() override { aptxbtenc = malloc(SizeofAptxbtenc()); ASSERT_NE(aptxbtenc, nullptr); @@ -56,14 +56,12 @@ class LibAptxEncTest : public ::testing::Test { TEST_F(LibAptxEncTest, encode_fake_data) { const char input[] = - "012345678901234567890123456789012345678901234567890123456789012345678901" - "23456789"; - const uint32_t aptx_codeword[] = {1270827967, 134154239, 670640127, - 1280265295, 2485752873}; + "012345678901234567890123456789012345678901234567890123456789012345678901" + "23456789"; + const uint32_t aptx_codeword[] = {1270827967, 134154239, 670640127, 1280265295, 2485752873}; ASSERT_EQ((sizeof(input) - 1) % BYTES_PER_CODEWORD, 0); - ASSERT_EQ((sizeof(input) - 1) / BYTES_PER_CODEWORD, - sizeof(aptx_codeword) / sizeof(uint32_t)); + ASSERT_EQ((sizeof(input) - 1) / BYTES_PER_CODEWORD, sizeof(aptx_codeword) / sizeof(uint32_t)); size_t idx = 0; diff --git a/system/embdrv/tests/src/aptxhd.cc b/system/embdrv/tests/src/aptxhd.cc index 7e406a36319..b029aabd3f9 100644 --- a/system/embdrv/tests/src/aptxhd.cc +++ b/system/embdrv/tests/src/aptxhd.cc @@ -28,8 +28,8 @@ #define BYTES_PER_CODEWORD 24 class LibAptxHdEncTest : public ::testing::Test { - private: - protected: +private: +protected: void* aptxhdbtenc = nullptr; void SetUp() override { aptxhdbtenc = malloc(SizeofAptxhdbtenc()); @@ -39,8 +39,7 @@ class LibAptxHdEncTest : public ::testing::Test { void TearDown() override { free(aptxhdbtenc); } - void codeword_cmp(const uint8_t p[BYTES_PER_CODEWORD], - const uint32_t codeword[2]) { + void codeword_cmp(const uint8_t p[BYTES_PER_CODEWORD], const uint32_t codeword[2]) { uint32_t pcmL[4]; uint32_t pcmR[4]; for (size_t i = 0; i < 4; i++) { @@ -59,11 +58,10 @@ class LibAptxHdEncTest : public ::testing::Test { TEST_F(LibAptxHdEncTest, encode_fake_data) { const char input[] = - "012345678901234567890123456789012345678901234567890123456789012345678901" - "234567890123456789012345678901234567890123456789"; - const uint32_t aptxhd_codeword[] = {7585535, 7585535, 32767, 32767, - 557055, 557027, 7586105, 7586109, - 9748656, 10764446}; + "012345678901234567890123456789012345678901234567890123456789012345678901" + "234567890123456789012345678901234567890123456789"; + const uint32_t aptxhd_codeword[] = {7585535, 7585535, 32767, 32767, 557055, + 557027, 7586105, 7586109, 9748656, 10764446}; ASSERT_EQ((sizeof(input) - 1) % BYTES_PER_CODEWORD, 0); ASSERT_EQ((sizeof(input) - 1) / BYTES_PER_CODEWORD, diff --git a/system/gd/common/audit_log.cc b/system/gd/common/audit_log.cc index 686e1120fd7..74be6f25c99 100644 --- a/system/gd/common/audit_log.cc +++ b/system/gd/common/audit_log.cc @@ -21,7 +21,7 @@ #include "os/log.h" namespace { -#if defined(__ANDROID__) && !defined (FUZZ_TARGET) +#if defined(__ANDROID__) && !defined(FUZZ_TARGET) // Tags for security logging, should be in sync with // frameworks/base/core/java/android/app/admin/SecurityLogTags.logtags @@ -33,15 +33,16 @@ constexpr int SEC_TAG_BLUETOOTH_CONNECTION = 210039; namespace bluetooth { namespace common { -void LogConnectionAdminAuditEvent( - [[maybe_unused]] const char* action, - [[maybe_unused]] const hci::Address& address, - [[maybe_unused]] hci::ErrorCode status) { -#if defined(__ANDROID__) && !defined (FUZZ_TARGET) +void LogConnectionAdminAuditEvent([[maybe_unused]] const char* action, + [[maybe_unused]] const hci::Address& address, + [[maybe_unused]] hci::ErrorCode status) { +#if defined(__ANDROID__) && !defined(FUZZ_TARGET) android_log_event_list(SEC_TAG_BLUETOOTH_CONNECTION) - << ADDRESS_TO_LOGGABLE_CSTR(address) << /* success */ int32_t(status == hci::ErrorCode::SUCCESS) - << common::StringFormat("%s: %s", action, ErrorCodeText(status).c_str()).c_str() << LOG_ID_SECURITY; + << ADDRESS_TO_LOGGABLE_CSTR(address) + << /* success */ int32_t(status == hci::ErrorCode::SUCCESS) + << common::StringFormat("%s: %s", action, ErrorCodeText(status).c_str()).c_str() + << LOG_ID_SECURITY; #endif /* defined(__ANDROID__) && !defined (FUZZ_TARGET) */ } diff --git a/system/gd/common/audit_log.h b/system/gd/common/audit_log.h index d96aab28d2c..7ce403e9310 100644 --- a/system/gd/common/audit_log.h +++ b/system/gd/common/audit_log.h @@ -21,7 +21,8 @@ namespace bluetooth { namespace common { -void LogConnectionAdminAuditEvent(const char* action, const hci::Address& address, hci::ErrorCode status); +void LogConnectionAdminAuditEvent(const char* action, const hci::Address& address, + hci::ErrorCode status); } // namespace common } // namespace bluetooth \ No newline at end of file diff --git a/system/gd/common/bidi_queue.h b/system/gd/common/bidi_queue.h index 0fdf0858d7a..924c2816a02 100644 --- a/system/gd/common/bidi_queue.h +++ b/system/gd/common/bidi_queue.h @@ -25,57 +25,49 @@ namespace bluetooth { namespace common { template -class BidiQueueEnd : public ::bluetooth::os::IQueueEnqueue, public ::bluetooth::os::IQueueDequeue { - public: +class BidiQueueEnd : public ::bluetooth::os::IQueueEnqueue, + public ::bluetooth::os::IQueueDequeue { +public: using EnqueueCallback = Callback()>; using DequeueCallback = Callback; - BidiQueueEnd(::bluetooth::os::IQueueEnqueue* tx, ::bluetooth::os::IQueueDequeue* rx) + BidiQueueEnd(::bluetooth::os::IQueueEnqueue* tx, + ::bluetooth::os::IQueueDequeue* rx) : tx_(tx), rx_(rx) {} void RegisterEnqueue(::bluetooth::os::Handler* handler, EnqueueCallback callback) override { tx_->RegisterEnqueue(handler, callback); } - void UnregisterEnqueue() override { - tx_->UnregisterEnqueue(); - } + void UnregisterEnqueue() override { tx_->UnregisterEnqueue(); } void RegisterDequeue(::bluetooth::os::Handler* handler, DequeueCallback callback) override { rx_->RegisterDequeue(handler, callback); } - void UnregisterDequeue() override { - rx_->UnregisterDequeue(); - } + void UnregisterDequeue() override { rx_->UnregisterDequeue(); } - std::unique_ptr TryDequeue() override { - return rx_->TryDequeue(); - } + std::unique_ptr TryDequeue() override { return rx_->TryDequeue(); } - private: +private: ::bluetooth::os::IQueueEnqueue* tx_; ::bluetooth::os::IQueueDequeue* rx_; }; template class BidiQueue { - public: +public: explicit BidiQueue(size_t capacity) : up_queue_(capacity), down_queue_(capacity), up_end_(&down_queue_, &up_queue_), down_end_(&up_queue_, &down_queue_) {} - BidiQueueEnd* GetUpEnd() { - return &up_end_; - } + BidiQueueEnd* GetUpEnd() { return &up_end_; } - BidiQueueEnd* GetDownEnd() { - return &down_end_; - } + BidiQueueEnd* GetDownEnd() { return &down_end_; } - private: +private: ::bluetooth::os::Queue up_queue_; ::bluetooth::os::Queue down_queue_; BidiQueueEnd up_end_; diff --git a/system/gd/common/bidi_queue_unittest.cc b/system/gd/common/bidi_queue_unittest.cc index 155927537c1..3505d16cdb9 100644 --- a/system/gd/common/bidi_queue_unittest.cc +++ b/system/gd/common/bidi_queue_unittest.cc @@ -31,7 +31,7 @@ namespace common { namespace { class BidiQueueTest : public ::testing::Test { - protected: +protected: void SetUp() override { up_thread_ = new Thread("up_thread", Thread::Priority::NORMAL); up_handler_ = new Handler(up_thread_); @@ -58,39 +58,31 @@ class B {}; template class TestBidiQueueEnd { - public: - explicit TestBidiQueueEnd(BidiQueueEnd* end, Handler* handler) : handler_(handler), end_(end) {} +public: + explicit TestBidiQueueEnd(BidiQueueEnd* end, Handler* handler) + : handler_(handler), end_(end) {} - ~TestBidiQueueEnd() { - handler_->Clear(); - } + ~TestBidiQueueEnd() { handler_->Clear(); } std::promise* Send(TA* value) { std::promise* promise = new std::promise(); - handler_->Post(BindOnce( - &TestBidiQueueEnd::handle_send, - common::Unretained(this), - common::Unretained(value), - common::Unretained(promise))); + handler_->Post(BindOnce(&TestBidiQueueEnd::handle_send, common::Unretained(this), + common::Unretained(value), common::Unretained(promise))); return promise; } std::promise* Receive() { std::promise* promise = new std::promise(); - handler_->Post( - BindOnce(&TestBidiQueueEnd::handle_receive, common::Unretained(this), common::Unretained(promise))); + handler_->Post(BindOnce(&TestBidiQueueEnd::handle_receive, common::Unretained(this), + common::Unretained(promise))); return promise; } void handle_send(TA* value, std::promise* promise) { - end_->RegisterEnqueue( - handler_, - Bind( - &TestBidiQueueEnd::handle_register_enqueue, - common::Unretained(this), - common::Unretained(value), - common::Unretained(promise))); + end_->RegisterEnqueue(handler_, Bind(&TestBidiQueueEnd::handle_register_enqueue, + common::Unretained(this), common::Unretained(value), + common::Unretained(promise))); } std::unique_ptr handle_register_enqueue(TA* value, std::promise* promise) { @@ -100,10 +92,8 @@ class TestBidiQueueEnd { } void handle_receive(std::promise* promise) { - end_->RegisterDequeue( - handler_, - Bind( - &TestBidiQueueEnd::handle_register_dequeue, common::Unretained(this), common::Unretained(promise))); + end_->RegisterDequeue(handler_, Bind(&TestBidiQueueEnd::handle_register_dequeue, + common::Unretained(this), common::Unretained(promise))); } void handle_register_dequeue(std::promise* promise) { @@ -111,7 +101,7 @@ class TestBidiQueueEnd { promise->set_value(end_->TryDequeue().get()); } - private: +private: Handler* handler_; BidiQueueEnd* end_; }; diff --git a/system/gd/common/bind.h b/system/gd/common/bind.h index f653976431a..9385c79dc5f 100644 --- a/system/gd/common/bind.h +++ b/system/gd/common/bind.h @@ -31,7 +31,8 @@ using base::Unretained; template inline auto BindOn(T* obj, Functor&& functor, Args&&... args) { - return common::Bind(std::forward(functor), common::Unretained(obj), std::forward(args)...); + return common::Bind(std::forward(functor), common::Unretained(obj), + std::forward(args)...); } } // namespace common diff --git a/system/gd/common/blocking_queue.h b/system/gd/common/blocking_queue.h index 622ca086fa4..4b68e514ab3 100644 --- a/system/gd/common/blocking_queue.h +++ b/system/gd/common/blocking_queue.h @@ -26,14 +26,14 @@ namespace common { template class BlockingQueue { - public: +public: void push(T data) { std::unique_lock lock(mutex_); queue_.push(std::move(data)); if (queue_.size() == 1) { not_empty_.notify_all(); } - }; + } T take() { std::unique_lock lock(mutex_); @@ -43,7 +43,7 @@ class BlockingQueue { T data = queue_.front(); queue_.pop(); return data; - }; + } // Returns true if take() will not block within a time period bool wait_to_take(std::chrono::milliseconds time) { @@ -59,15 +59,15 @@ class BlockingQueue { bool empty() const { std::unique_lock lock(mutex_); return queue_.empty(); - }; + } void clear() { std::unique_lock lock(mutex_); std::queue empty; std::swap(queue_, empty); - }; + } - private: +private: std::queue queue_; mutable std::mutex mutex_; std::condition_variable not_empty_; diff --git a/system/gd/common/blocking_queue_unittest.cc b/system/gd/common/blocking_queue_unittest.cc index b6c96321c86..2b109ffe5f3 100644 --- a/system/gd/common/blocking_queue_unittest.cc +++ b/system/gd/common/blocking_queue_unittest.cc @@ -24,22 +24,16 @@ namespace bluetooth { namespace common { namespace { class BlockingQueueTest : public ::testing::Test { - protected: - void SetUp() override { - EXPECT_TRUE(queue_.empty()); - } +protected: + void SetUp() override { EXPECT_TRUE(queue_.empty()); } // Postcondition for each test case: clear the blocking queue - void TearDown() override { - EXPECT_TRUE(queue_.empty()); - } + void TearDown() override { EXPECT_TRUE(queue_.empty()); } BlockingQueue queue_; }; -TEST_F(BlockingQueueTest, initial_empty) { - EXPECT_TRUE(queue_.empty()); -} +TEST_F(BlockingQueueTest, initial_empty) { EXPECT_TRUE(queue_.empty()); } TEST_F(BlockingQueueTest, same_thread_push_and_pop) { int data = 1; @@ -99,7 +93,8 @@ TEST_F(BlockingQueueTest, wait_to_take_after_non_empty) { TEST_F(BlockingQueueTest, wait_to_take_before_non_empty) { int data = 1; - std::thread waiter_thread([this] { EXPECT_TRUE(queue_.wait_to_take(std::chrono::milliseconds(3))); }); + std::thread waiter_thread( + [this] { EXPECT_TRUE(queue_.wait_to_take(std::chrono::milliseconds(3))); }); queue_.push(data); waiter_thread.join(); queue_.clear(); @@ -119,15 +114,11 @@ TEST_F(BlockingQueueTest, wait_for_non_empty_batch) { } class VectorBlockingQueueTest : public ::testing::Test { - protected: - void SetUp() override { - EXPECT_TRUE(queue_.empty()); - } +protected: + void SetUp() override { EXPECT_TRUE(queue_.empty()); } // Postcondition for each test case: clear the blocking queue - void TearDown() override { - EXPECT_TRUE(queue_.empty()); - } + void TearDown() override { EXPECT_TRUE(queue_.empty()); } BlockingQueue> queue_; }; diff --git a/system/gd/common/byte_array.h b/system/gd/common/byte_array.h index 6f2f529441e..29c58d8d8d2 100644 --- a/system/gd/common/byte_array.h +++ b/system/gd/common/byte_array.h @@ -33,48 +33,28 @@ namespace common { template class ByteArray : public packet::CustomFieldFixedSizeInterface>, public storage::Serializable> { - public: +public: static constexpr size_t kLength = LENGTH; ByteArray() = default; - ByteArray(const uint8_t (&d)[kLength]) { - std::copy(d, d + kLength, data()); - } + ByteArray(const uint8_t (&d)[kLength]) { std::copy(d, d + kLength, data()); } ByteArray(std::array a) : bytes(std::move(a)) {} std::array bytes = {}; - uint8_t* data() override { - return bytes.data(); - } + uint8_t* data() override { return bytes.data(); } - const uint8_t* data() const override { - return bytes.data(); - } + const uint8_t* data() const override { return bytes.data(); } // operators - bool operator<(const ByteArray& rhs) const { - return bytes < rhs.bytes; - } - bool operator==(const ByteArray& rhs) const { - return bytes == rhs.bytes; - } - bool operator>(const ByteArray& rhs) const { - return (rhs < *this); - } - bool operator<=(const ByteArray& rhs) const { - return !(*this > rhs); - } - bool operator>=(const ByteArray& rhs) const { - return !(*this < rhs); - } - bool operator!=(const ByteArray& rhs) const { - return !(*this == rhs); - } + bool operator<(const ByteArray& rhs) const { return bytes < rhs.bytes; } + bool operator==(const ByteArray& rhs) const { return bytes == rhs.bytes; } + bool operator>(const ByteArray& rhs) const { return rhs < *this; } + bool operator<=(const ByteArray& rhs) const { return !(*this > rhs); } + bool operator>=(const ByteArray& rhs) const { return !(*this < rhs); } + bool operator!=(const ByteArray& rhs) const { return !(*this == rhs); } // storage::Serializable methods - std::string ToString() const override { - return common::ToHexString(bytes.begin(), bytes.end()); - } + std::string ToString() const override { return common::ToHexString(bytes.begin(), bytes.end()); } static std::optional> FromString(const std::string& from) { if (from.length() != (kLength * 2)) { return std::nullopt; @@ -87,9 +67,7 @@ class ByteArray : public packet::CustomFieldFixedSizeInterface std::move(vec->data(), vec->data() + vec->size(), byte_array.data()); return byte_array; } - std::string ToLegacyConfigString() const override { - return ToString(); - } + std::string ToLegacyConfigString() const override { return ToString(); } static std::optional> FromLegacyConfigString(const std::string& from) { return FromString(from); } diff --git a/system/gd/common/byte_array_test.cc b/system/gd/common/byte_array_test.cc index 7a3e3edb659..4798faccf03 100644 --- a/system/gd/common/byte_array_test.cc +++ b/system/gd/common/byte_array_test.cc @@ -24,17 +24,19 @@ using bluetooth::common::ByteArray; namespace { const char* byte_string16 = "4c68384139f574d836bcf34e9dfb01bf\0"; -const uint8_t byte_data16[16] = { - 0x4c, 0x68, 0x38, 0x41, 0x39, 0xf5, 0x74, 0xd8, 0x36, 0xbc, 0xf3, 0x4e, 0x9d, 0xfb, 0x01, 0xbf}; +const uint8_t byte_data16[16] = {0x4c, 0x68, 0x38, 0x41, 0x39, 0xf5, 0x74, 0xd8, + 0x36, 0xbc, 0xf3, 0x4e, 0x9d, 0xfb, 0x01, 0xbf}; const char* byte_string21 = "4c68384139f574d836bcf34e9dfb01bf0011223344\0"; const uint8_t byte_data21[21] = {0x4c, 0x68, 0x38, 0x41, 0x39, 0xf5, 0x74, 0xd8, 0x36, 0xbc, 0xf3, 0x4e, 0x9d, 0xfb, 0x01, 0xbf, 0x00, 0x11, 0x22, 0x33, 0x44}; const char* byte_string23 = "4c68384139f574d836bcf34e9dfb01bf00112233445566\0"; -const uint8_t byte_data23[23] = {0x4c, 0x68, 0x38, 0x41, 0x39, 0xf5, 0x74, 0xd8, 0x36, 0xbc, 0xf3, 0x4e, - 0x9d, 0xfb, 0x01, 0xbf, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66}; +const uint8_t byte_data23[23] = {0x4c, 0x68, 0x38, 0x41, 0x39, 0xf5, 0x74, 0xd8, + 0x36, 0xbc, 0xf3, 0x4e, 0x9d, 0xfb, 0x01, 0xbf, + 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66}; const char* byte_string28 = "4c68384139f574d836bcf34e9dfb01bf00112233445566778899aabb\0"; -const uint8_t byte_data28[28] = {0x4c, 0x68, 0x38, 0x41, 0x39, 0xf5, 0x74, 0xd8, 0x36, 0xbc, 0xf3, 0x4e, 0x9d, 0xfb, - 0x01, 0xbf, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb}; +const uint8_t byte_data28[28] = {0x4c, 0x68, 0x38, 0x41, 0x39, 0xf5, 0x74, 0xd8, 0x36, 0xbc, + 0xf3, 0x4e, 0x9d, 0xfb, 0x01, 0xbf, 0x00, 0x11, 0x22, 0x33, + 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb}; template void simple_constructor_test(const T (&data)[N]) { diff --git a/system/gd/common/circular_buffer.h b/system/gd/common/circular_buffer.h index 64d7f231732..b008d5edda6 100644 --- a/system/gd/common/circular_buffer.h +++ b/system/gd/common/circular_buffer.h @@ -28,7 +28,7 @@ namespace common { template class CircularBuffer { - public: +public: explicit CircularBuffer(size_t size); // Push one item to the circular buffer @@ -38,23 +38,24 @@ class CircularBuffer { // Drain everything from the circular buffer and return them as a vector std::vector Drain(); - private: +private: const size_t size_; std::deque queue_; mutable std::mutex mutex_; }; class Timestamper { - public: +public: virtual long long GetTimestamp() const = 0; virtual ~Timestamper() {} }; class TimestamperInMilliseconds : public Timestamper { - public: +public: long long GetTimestamp() const override { - return std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()) - .count(); + return std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()) + .count(); } virtual ~TimestamperInMilliseconds() {} }; @@ -67,15 +68,16 @@ struct TimestampedEntry { template class TimestampedCircularBuffer : public CircularBuffer> { - public: +public: explicit TimestampedCircularBuffer( - size_t size, std::unique_ptr timestamper = std::make_unique()); + size_t size, + std::unique_ptr timestamper = std::make_unique()); void Push(T item); std::vector> Pull() const; std::vector> Drain(); - private: +private: std::unique_ptr timestamper_{std::make_unique()}; }; @@ -103,14 +105,15 @@ std::vector bluetooth::common::CircularBuffer::Pull() const { template std::vector bluetooth::common::CircularBuffer::Drain() { std::unique_lock lock(mutex_); - std::vector items(std::make_move_iterator(queue_.begin()), std::make_move_iterator(queue_.end())); + std::vector items(std::make_move_iterator(queue_.begin()), + std::make_move_iterator(queue_.end())); queue_.clear(); return items; } template bluetooth::common::TimestampedCircularBuffer::TimestampedCircularBuffer( - size_t size, std::unique_ptr timestamper) + size_t size, std::unique_ptr timestamper) : CircularBuffer>(size), timestamper_(std::move(timestamper)) {} template @@ -120,12 +123,13 @@ void bluetooth::common::TimestampedCircularBuffer::Push(const T item) { } template -std::vector> bluetooth::common::TimestampedCircularBuffer::Pull() - const { +std::vector> +bluetooth::common::TimestampedCircularBuffer::Pull() const { return bluetooth::common::CircularBuffer>::Pull(); } template -std::vector> bluetooth::common::TimestampedCircularBuffer::Drain() { +std::vector> +bluetooth::common::TimestampedCircularBuffer::Drain() { return bluetooth::common::CircularBuffer>::Drain(); } diff --git a/system/gd/common/circular_buffer_test.cc b/system/gd/common/circular_buffer_test.cc index 9a2ef4e30f9..577bb6681b1 100644 --- a/system/gd/common/circular_buffer_test.cc +++ b/system/gd/common/circular_buffer_test.cc @@ -14,21 +14,21 @@ * limitations under the License. */ +#include "common/circular_buffer.h" + #include #include + #include #include -#include "common/circular_buffer.h" #include "os/log.h" namespace testing { long long timestamp_{0}; struct TestTimestamper : public bluetooth::common::Timestamper { - virtual long long GetTimestamp() const override { - return timestamp_++; - } + virtual long long GetTimestamp() const override { return timestamp_++; } }; TEST(CircularBufferTest, simple) { @@ -69,7 +69,8 @@ TEST(CircularBufferTest, simple_drain) { TEST(CircularBufferTest, test_timestamps) { timestamp_ = 0; - bluetooth::common::TimestampedCircularBuffer buffer(10, std::make_unique()); + bluetooth::common::TimestampedCircularBuffer buffer( + 10, std::make_unique()); buffer.Push(std::string("One")); buffer.Push(std::string("Two")); diff --git a/system/gd/common/contextual_callback.h b/system/gd/common/contextual_callback.h index a5f565c3952..548936d68bf 100644 --- a/system/gd/common/contextual_callback.h +++ b/system/gd/common/contextual_callback.h @@ -29,7 +29,7 @@ class ContextualOnceCallback; // A callback bound to an execution context that can be invoked only once. template class ContextualOnceCallback { - public: +public: ContextualOnceCallback(common::OnceCallback&& callback, IPostableContext* context) : callback_(std::move(callback)), context_(context) {} @@ -44,18 +44,16 @@ class ContextualOnceCallback { context_->Post(common::BindOnce(std::move(callback_), std::forward(args)...)); } - operator bool() const { - return context_ && callback_; - } + operator bool() const { return context_ && callback_; } - private: +private: common::OnceCallback callback_; IPostableContext* context_; }; template ContextualOnceCallback(Callback&& callback, IPostableContext* context) - -> ContextualOnceCallback; + -> ContextualOnceCallback; template class ContextualCallback; @@ -63,7 +61,7 @@ class ContextualCallback; // A callback bound to an execution context that can be invoked multiple times. template class ContextualCallback { - public: +public: ContextualCallback(common::Callback&& callback, IPostableContext* context) : callback_(std::move(callback)), context_(context) {} @@ -78,18 +76,16 @@ class ContextualCallback { context_->Post(common::BindOnce(callback_, std::forward(args)...)); } - operator bool() const { - return context_ && callback_; - } + operator bool() const { return context_ && callback_; } - private: +private: common::Callback callback_; IPostableContext* context_; }; template -ContextualCallback(Callback&& callback, IPostableContext* context) - -> ContextualCallback; +ContextualCallback(Callback&& callback, + IPostableContext* context) -> ContextualCallback; } // namespace common } // namespace bluetooth diff --git a/system/gd/common/i_postable_context.h b/system/gd/common/i_postable_context.h index c17297069c8..b421579ca86 100644 --- a/system/gd/common/i_postable_context.h +++ b/system/gd/common/i_postable_context.h @@ -22,8 +22,8 @@ namespace bluetooth { namespace common { class IPostableContext { - public: - virtual ~IPostableContext(){}; +public: + virtual ~IPostableContext() {} virtual void Post(base::OnceClosure closure) = 0; }; diff --git a/system/gd/common/init_flags.h b/system/gd/common/init_flags.h index 543238e6d23..6c40ed8ae99 100644 --- a/system/gd/common/init_flags.h +++ b/system/gd/common/init_flags.h @@ -24,7 +24,7 @@ namespace bluetooth { namespace common { class InitFlags final { - public: +public: inline static void Load(const char** flags) { rust::Vec rusted_flags = rust::Vec(); while (flags != nullptr && *flags != nullptr) { @@ -42,13 +42,9 @@ class InitFlags final { return init_flags::use_rsi_from_cached_inqiry_results_is_enabled(); } - inline static int GetAdapterIndex() { - return init_flags::get_hci_adapter(); - } + inline static int GetAdapterIndex() { return init_flags::get_hci_adapter(); } - inline static void SetAllForTesting() { - init_flags::set_all_for_testing(); - } + inline static void SetAllForTesting() { init_flags::set_all_for_testing(); } }; } // namespace common diff --git a/system/gd/common/interfaces/ILoggable.h b/system/gd/common/interfaces/ILoggable.h index ad2b8ab0b88..0a0899511ca 100644 --- a/system/gd/common/interfaces/ILoggable.h +++ b/system/gd/common/interfaces/ILoggable.h @@ -24,7 +24,7 @@ namespace bluetooth { namespace common { class ILoggable { - public: +public: // the interface for // converting an object to a string for feeding to loggers // e.g.. logcat @@ -33,7 +33,7 @@ class ILoggable { }; class IRedactableLoggable : public ILoggable { - public: +public: // the interface for // converting an object to a string with sensitive info redacted // to avoid violating privacy diff --git a/system/gd/common/list_map.h b/system/gd/common/list_map.h index babf8697c1f..802602bde73 100644 --- a/system/gd/common/list_map.h +++ b/system/gd/common/list_map.h @@ -28,8 +28,9 @@ namespace bluetooth { namespace common { -// A map that maintains order of its element as a list. An element that is put earlier will appear before an element -// that is put later when iterating through this map's entries. Keys must be unique. +// A map that maintains order of its element as a list. An element that is put earlier will appear +// before an element that is put later when iterating through this map's entries. Keys must be +// unique. // // Performance: // - Key look-up and modification is O(1) @@ -43,7 +44,7 @@ namespace common { // - T value template class ListMap { - public: +public: using value_type = std::pair; // different from c++17 node_type on purpose as we want node to be copyable using node_type = std::pair; @@ -80,16 +81,10 @@ class ListMap { } // comparison operators - bool operator==(const ListMap& rhs) const { - return node_list_ == rhs.node_list_; - } - bool operator!=(const ListMap& rhs) const { - return !(*this == rhs); - } + bool operator==(const ListMap& rhs) const { return node_list_ == rhs.node_list_; } + bool operator!=(const ListMap& rhs) const { return !(*this == rhs); } - ~ListMap() { - clear(); - } + ~ListMap() { clear(); } // Clear the list map void clear() { @@ -98,9 +93,7 @@ class ListMap { } // const version of find() - const_iterator find(const Key& key) const { - return const_cast(this)->find(key); - } + const_iterator find(const Key& key) const { return const_cast(this)->find(key); } // Get the value of a key. Return iterator to the item if found, end() if not found iterator find(const Key& key) { @@ -112,13 +105,12 @@ class ListMap { } // Check if key exist in the map. Return true if key exist in map, false if not. - bool contains(const Key& key) const { - return find(key) != end(); - } + bool contains(const Key& key) const { return find(key) != end(); } - // Try emplace an element before a specific position |pos| of the list map. If the |key| already exists, does nothing. - // Moved arguments won't be moved when key already exists. Return when key does not exist, when key exist and iterator is the position where it was placed. + // Try emplace an element before a specific position |pos| of the list map. If the |key| already + // exists, does nothing. Moved arguments won't be moved when key already exists. Return when key does not exist, when key exist and iterator is the position + // where it was placed. template std::pair try_emplace(const_iterator pos, const Key& key, Args&&... args) { auto map_iterator = key_map_.find(key); @@ -130,16 +122,16 @@ class ListMap { return std::make_pair(list_iterator, true); } - // Try emplace an element before the end of the list map. If the key already exists, does nothing. Moved arguments - // won't be moved when key already exists return when key does not exist, when key - // exist and iterator is the position where it was placed + // Try emplace an element before the end of the list map. If the key already exists, does nothing. + // Moved arguments won't be moved when key already exists return when key does + // not exist, when key exist and iterator is the position where it was placed template std::pair try_emplace_back(const Key& key, Args&&... args) { return try_emplace(end(), key, std::forward(args)...); } - // Put a key-value pair to the map before position. If key already exist, |pos| will be ignored and existing value - // will be replaced + // Put a key-value pair to the map before position. If key already exist, |pos| will be ignored + // and existing value will be replaced void insert_or_assign(const_iterator pos, const Key& key, T value) { auto map_iterator = key_map_.find(key); if (map_iterator != key_map_.end()) { @@ -150,10 +142,9 @@ class ListMap { key_map_.emplace(key, list_iterator); } - // Put a key-value pair to the tail of the map or replace the current value without moving the key if key exists - void insert_or_assign(const Key& key, T value) { - insert_or_assign(end(), key, std::move(value)); - } + // Put a key-value pair to the tail of the map or replace the current value without moving the key + // if key exists + void insert_or_assign(const Key& key, T value) { insert_or_assign(end(), key, std::move(value)); } // STL splice, same as std::list::splice // - pos: element before which the content will be inserted @@ -167,8 +158,9 @@ class ListMap { node_list_.splice(pos, other.node_list_, it); } - // Remove a key from the list map and return removed value if key exits, std::nullopt if not. The return value will be - // evaluated to true in a boolean context if a value is contained by std::optional, false otherwise. + // Remove a key from the list map and return removed value if key exits, std::nullopt if not. The + // return value will be evaluated to true in a boolean context if a value is contained by + // std::optional, false otherwise. std::optional extract(const Key& key) { auto map_iterator = key_map_.find(key); if (map_iterator == key_map_.end()) { @@ -180,38 +172,29 @@ class ListMap { return removed_node; } - // Remove an iterator pointed item from the list map and return the iterator immediately after the erased item + // Remove an iterator pointed item from the list map and return the iterator immediately after the + // erased item iterator erase(const_iterator iter) { key_map_.erase(iter->first); return node_list_.erase(iter); } // Return size of the list map - inline size_t size() const { - return node_list_.size(); - } + inline size_t size() const { return node_list_.size(); } // Return iterator interface for begin - inline iterator begin() { - return node_list_.begin(); - } + inline iterator begin() { return node_list_.begin(); } // Iterator interface for begin, const - inline const_iterator begin() const { - return node_list_.begin(); - } + inline const_iterator begin() const { return node_list_.begin(); } // Iterator interface for end - inline iterator end() { - return node_list_.end(); - } + inline iterator end() { return node_list_.end(); } // Iterator interface for end, const - inline const_iterator end() const { - return node_list_.end(); - } + inline const_iterator end() const { return node_list_.end(); } - private: +private: std::list node_list_; std::unordered_map key_map_; }; diff --git a/system/gd/common/list_map_test.cc b/system/gd/common/list_map_test.cc index b587e016724..991fd25c581 100644 --- a/system/gd/common/list_map_test.cc +++ b/system/gd/common/list_map_test.cc @@ -14,12 +14,12 @@ * limitations under the License. */ -#include +#include "common/list_map.h" #include #include -#include "common/list_map.h" +#include namespace testing { diff --git a/system/gd/common/lru_cache.h b/system/gd/common/lru_cache.h index 63e41ef07c2..75b104f2686 100644 --- a/system/gd/common/lru_cache.h +++ b/system/gd/common/lru_cache.h @@ -53,7 +53,7 @@ namespace common { // */ template class LruCache { - public: +public: using value_type = typename ListMap::value_type; // different from c++17 node_type on purpose as we want node to be copyable using node_type = typename ListMap::node_type; @@ -88,30 +88,24 @@ class LruCache { bool operator==(const LruCache& rhs) const { return capacity_ == rhs.capacity_ && list_map_ == rhs.list_map_; } - bool operator!=(const LruCache& rhs) const { - return !(*this == rhs); - } + bool operator!=(const LruCache& rhs) const { return !(*this == rhs); } - ~LruCache() { - clear(); - } + ~LruCache() { clear(); } // Clear the cache - void clear() { - list_map_.clear(); - } + void clear() { list_map_.clear(); } - // Find the value of a key, and move the key to the head of cache, if there is one. Return iterator to value if key - // exists, end() if not. Iterator might be invalidated when removed or evicted. Const version. + // Find the value of a key, and move the key to the head of cache, if there is one. Return + // iterator to value if key exists, end() if not. Iterator might be invalidated when removed or + // evicted. Const version. // // LRU: Will warm up key // LRU: Access to returned iterator won't move key in LRU - const_iterator find(const Key& key) const { - return const_cast(this)->find(key); - } + const_iterator find(const Key& key) const { return const_cast(this)->find(key); } - // Find the value of a key, and move the key to the head of cache, if there is one. Return iterator to value if key - // exists, end() if not. Iterator might be invalidated when removed or evicted + // Find the value of a key, and move the key to the head of cache, if there is one. Return + // iterator to value if key exists, end() if not. Iterator might be invalidated when removed or + // evicted // // LRU: Will warm up key // LRU: Access to returned iterator won't move key in LRU @@ -128,14 +122,12 @@ class LruCache { // Check if key exist in the cache. Return true if key exist in cache, false, if not // // LRU: Will warm up key - bool contains(const Key& key) const { - return find(key) != list_map_.end(); - } + bool contains(const Key& key) const { return find(key) != list_map_.end(); } - // Put a key-value pair to the head of cache, evict the oldest key if cache is at capacity. Eviction is based on key - // ONLY. Hence, updating a key will not evict the oldest key. Return evicted value if old value was evicted, - // std::nullopt if not. The return value will be evaluated to true in a boolean context if a value is contained by - // std::optional, false otherwise. + // Put a key-value pair to the head of cache, evict the oldest key if cache is at capacity. + // Eviction is based on key ONLY. Hence, updating a key will not evict the oldest key. Return + // evicted value if old value was evicted, std::nullopt if not. The return value will be evaluated + // to true in a boolean context if a value is contained by std::optional, false otherwise. // // LRU: Will warm up key std::optional insert_or_assign(const Key& key, T value) { @@ -154,10 +146,11 @@ class LruCache { return evicted_node; } - // Put a key-value pair to the head of cache, evict the oldest key if cache is at capacity. Eviction is based on key - // ONLY. Hence, updating a key will not evict the oldest key. This method tries to construct the value in-place. If - // the key already exist, this method only update the value. Return inserted iterator, whether insertion happens, and - // evicted value if old value was evicted or std::nullopt + // Put a key-value pair to the head of cache, evict the oldest key if cache is at capacity. + // Eviction is based on key ONLY. Hence, updating a key will not evict the oldest key. This method + // tries to construct the value in-place. If the key already exist, this method only update the + // value. Return inserted iterator, whether insertion happens, and evicted value if old value was + // evicted or std::nullopt // // LRU: Will warm up key template @@ -176,43 +169,31 @@ class LruCache { return std::make_tuple(pair.first, pair.second, std::move(evicted_node)); } - // Delete a key from cache, return removed value if old value was evicted, std::nullopt if not. The return value will - // be evaluated to true in a boolean context if a value is contained by std::optional, false otherwise. - inline std::optional extract(const Key& key) { - return list_map_.extract(key); - } + // Delete a key from cache, return removed value if old value was evicted, std::nullopt if not. + // The return value will be evaluated to true in a boolean context if a value is contained by + // std::optional, false otherwise. + inline std::optional extract(const Key& key) { return list_map_.extract(key); } - /// Remove an iterator pointed item from the lru cache and return the iterator immediately after the erased item - iterator erase(const_iterator iter) { - return list_map_.erase(iter); - } + /// Remove an iterator pointed item from the lru cache and return the iterator immediately after + /// the erased item + iterator erase(const_iterator iter) { return list_map_.erase(iter); } // Return size of the cache - inline size_t size() const { - return list_map_.size(); - } + inline size_t size() const { return list_map_.size(); } // Iterator interface for begin - inline iterator begin() { - return list_map_.begin(); - } + inline iterator begin() { return list_map_.begin(); } // Return iterator interface for begin, const - inline const_iterator begin() const { - return list_map_.begin(); - } + inline const_iterator begin() const { return list_map_.begin(); } // Return iterator interface for end - inline iterator end() { - return list_map_.end(); - } + inline iterator end() { return list_map_.end(); } // Iterator interface for end, const - inline const_iterator end() const { - return list_map_.end(); - } + inline const_iterator end() const { return list_map_.end(); } - private: +private: size_t capacity_; ListMap list_map_; }; diff --git a/system/gd/common/lru_cache_test.cc b/system/gd/common/lru_cache_test.cc index 8018d2a62b5..555a04edd2b 100644 --- a/system/gd/common/lru_cache_test.cc +++ b/system/gd/common/lru_cache_test.cc @@ -14,12 +14,12 @@ * limitations under the License. */ -#include +#include "common/lru_cache.h" #include #include -#include "common/lru_cache.h" +#include namespace testing { diff --git a/system/gd/common/metric_id_manager.cc b/system/gd/common/metric_id_manager.cc index 5a8acab0800..84268dba1df 100644 --- a/system/gd/common/metric_id_manager.cc +++ b/system/gd/common/metric_id_manager.cc @@ -43,7 +43,7 @@ const int MetricIdManager::kMaxId = 65534; // 2^16 - 2 // kMaxNumUnpairedDevicesInMemory static_assert((MetricIdManager::kMaxNumUnpairedDevicesInMemory + MetricIdManager::kMaxNumPairedDevicesInMemory) < - (MetricIdManager::kMaxId - MetricIdManager::kMinId), + (MetricIdManager::kMaxId - MetricIdManager::kMinId), "id space should always be larger than " "kMaxNumPairedDevicesInMemory + MaxNumUnpairedDevicesInMemory"); @@ -51,9 +51,8 @@ MetricIdManager::MetricIdManager() : paired_device_cache_(kMaxNumPairedDevicesInMemory), temporary_device_cache_(kMaxNumUnpairedDevicesInMemory) {} -bool MetricIdManager::Init( - const std::unordered_map& paired_device_map, - Callback save_id_callback, Callback forget_device_callback) { +bool MetricIdManager::Init(const std::unordered_map& paired_device_map, + Callback save_id_callback, Callback forget_device_callback) { std::lock_guard lock(id_allocator_mutex_); if (initialized_) { return false; @@ -62,9 +61,8 @@ bool MetricIdManager::Init( // init paired_devices_map if (paired_device_map.size() > kMaxNumPairedDevicesInMemory) { log::fatal( - "Paired device map has size {}, which is bigger than kMaxNumPairedDevicesInMemory {}", - paired_device_map.size(), - kMaxNumPairedDevicesInMemory); + "Paired device map has size {}, which is bigger than kMaxNumPairedDevicesInMemory {}", + paired_device_map.size(), kMaxNumPairedDevicesInMemory); // fail loudly to let caller know return false; } @@ -72,12 +70,8 @@ bool MetricIdManager::Init( next_id_ = kMinId; for (const auto& p : paired_device_map) { if (p.second < kMinId || p.second > kMaxId) { - log::fatal( - "Invalid Bluetooth Metric Id in config. Id {} of {} is out of range [{}, {}]", - p.second, - p.first, - kMinId, - kMaxId); + log::fatal("Invalid Bluetooth Metric Id in config. Id {} of {} is out of range [{}, {}]", + p.second, p.first, kMinId, kMaxId); } auto evicted = paired_device_cache_.insert_or_assign(p.first, p.second); if (evicted) { @@ -118,8 +112,7 @@ MetricIdManager& MetricIdManager::GetInstance() { bool MetricIdManager::IsEmpty() const { std::lock_guard lock(id_allocator_mutex_); - return paired_device_cache_.size() == 0 && - temporary_device_cache_.size() == 0; + return paired_device_cache_.size() == 0 && temporary_device_cache_.size() == 0; } // call this function when a new device is scanned @@ -194,12 +187,9 @@ void MetricIdManager::ForgetDevice(const Address& mac_address) { ForgetDevicePostprocess(mac_address, opt->second); } -bool MetricIdManager::IsValidId(const int id) { - return id >= kMinId && id <= kMaxId; -} +bool MetricIdManager::IsValidId(const int id) { return id >= kMinId && id <= kMaxId; } -void MetricIdManager::ForgetDevicePostprocess(const Address& mac_address, - const int id) { +void MetricIdManager::ForgetDevicePostprocess(const Address& mac_address, const int id) { id_set_.erase(id); forget_device_callback_(mac_address, id); } diff --git a/system/gd/common/metric_id_manager.h b/system/gd/common/metric_id_manager.h index e238e22c8a8..01f099c3639 100644 --- a/system/gd/common/metric_id_manager.h +++ b/system/gd/common/metric_id_manager.h @@ -30,7 +30,7 @@ namespace bluetooth { namespace common { class MetricIdManager { - public: +public: using Callback = std::function; static const size_t kMaxNumUnpairedDevicesInMemory; @@ -59,10 +59,8 @@ class MetricIdManager { * successful id deletion for forgotten device, * @return true if successfully initialized */ - bool Init( - const std::unordered_map& paired_device_map, - Callback save_id_callback, - Callback forget_device_callback); + bool Init(const std::unordered_map& paired_device_map, + Callback save_id_callback, Callback forget_device_callback); /** * Close the allocator. should be called when Bluetooth process is killed @@ -112,11 +110,11 @@ class MetricIdManager { */ static bool IsValidId(const int id); - protected: +protected: // Singleton MetricIdManager(); - private: +private: mutable std::mutex id_allocator_mutex_; LruCache paired_device_cache_; @@ -128,8 +126,7 @@ class MetricIdManager { Callback save_id_callback_; Callback forget_device_callback_; - void ForgetDevicePostprocess(const hci::Address& mac_address, - const int id); + void ForgetDevicePostprocess(const hci::Address& mac_address, const int id); // delete copy constructor for singleton MetricIdManager(MetricIdManager const&) = delete; diff --git a/system/gd/common/metric_id_manager_unittest.cc b/system/gd/common/metric_id_manager_unittest.cc index a64002b0bbf..2b23c59db4b 100644 --- a/system/gd/common/metric_id_manager_unittest.cc +++ b/system/gd/common/metric_id_manager_unittest.cc @@ -15,12 +15,12 @@ * limitations under the License. * ******************************************************************************/ -#include +#include "common/metric_id_manager.h" #include #include -#include "common/metric_id_manager.h" +#include namespace testing { @@ -36,8 +36,7 @@ bluetooth::hci::Address kthAddress(uint32_t k) { return addr; } -std::unordered_map generateAddresses( - const uint32_t num) { +std::unordered_map generateAddresses(const uint32_t num) { // generate first num of mac address -> id pairs // input may is always valid 256^6 = 2^48 > 2^32 std::unordered_map device_map; @@ -50,8 +49,7 @@ std::unordered_map generateAddresses( TEST(BluetoothMetricIdManagerTest, MetricIdManagerInitCloseTest) { auto& manager = MetricIdManager::GetInstance(); std::unordered_map paired_device_map; - MetricIdManager::Callback callback = []( - const bluetooth::hci::Address&, const int) { + MetricIdManager::Callback callback = [](const bluetooth::hci::Address&, const int) { return true; }; ASSERT_TRUE(manager.Init(paired_device_map, callback, callback)); @@ -62,8 +60,7 @@ TEST(BluetoothMetricIdManagerTest, MetricIdManagerInitCloseTest) { TEST(BluetoothMetricIdManagerTest, MetricIdManagerNotCloseTest) { auto& manager = MetricIdManager::GetInstance(); std::unordered_map paired_device_map; - MetricIdManager::Callback callback = []( - const bluetooth::hci::Address&, const int) { + MetricIdManager::Callback callback = [](const bluetooth::hci::Address&, const int) { return true; }; ASSERT_TRUE(manager.Init(paired_device_map, callback, callback)); @@ -76,8 +73,7 @@ TEST(BluetoothMetricIdManagerTest, MetricIdManagerNotCloseTest) { TEST(BluetoothMetricIdManagerTest, MetricIdManagerScanDeviceFromEmptyTest) { auto& manager = MetricIdManager::GetInstance(); std::unordered_map paired_device_map; - MetricIdManager::Callback callback = []( - const bluetooth::hci::Address&, const int) { + MetricIdManager::Callback callback = [](const bluetooth::hci::Address&, const int) { return true; }; // test empty map, next id should be kMinId @@ -89,19 +85,16 @@ TEST(BluetoothMetricIdManagerTest, MetricIdManagerScanDeviceFromEmptyTest) { ASSERT_TRUE(manager.Close()); } -TEST(BluetoothMetricIdManagerTest, - MetricIdManagerScanDeviceFromFilledTest) { +TEST(BluetoothMetricIdManagerTest, MetricIdManagerScanDeviceFromFilledTest) { auto& manager = MetricIdManager::GetInstance(); std::unordered_map paired_device_map; - MetricIdManager::Callback callback = []( - const bluetooth::hci::Address&, const int) { + MetricIdManager::Callback callback = [](const bluetooth::hci::Address&, const int) { return true; }; - int id = static_cast(MetricIdManager::kMaxNumPairedDevicesInMemory) + - MetricIdManager::kMinId; + int id = + static_cast(MetricIdManager::kMaxNumPairedDevicesInMemory) + MetricIdManager::kMinId; // next id should be MetricIdManager::kMaxNumPairedDevicesInMemory - paired_device_map = - generateAddresses(MetricIdManager::kMaxNumPairedDevicesInMemory); + paired_device_map = generateAddresses(MetricIdManager::kMaxNumPairedDevicesInMemory); ASSERT_TRUE(manager.Init(paired_device_map, callback, callback)); // try new values not in the map, should get new id. ASSERT_EQ(manager.AllocateId(kthAddress(INT_MAX)), id); @@ -114,10 +107,9 @@ TEST(BluetoothMetricIdManagerTest, TEST(BluetoothMetricIdManagerTest, MetricIdManagerAllocateExistingTest) { auto& manager = MetricIdManager::GetInstance(); std::unordered_map paired_device_map = - generateAddresses(MetricIdManager::kMaxNumPairedDevicesInMemory); + generateAddresses(MetricIdManager::kMaxNumPairedDevicesInMemory); - MetricIdManager::Callback callback = []( - const bluetooth::hci::Address&, const int) { + MetricIdManager::Callback callback = [](const bluetooth::hci::Address&, const int) { return true; }; int id = MetricIdManager::kMinId; @@ -125,16 +117,10 @@ TEST(BluetoothMetricIdManagerTest, MetricIdManagerAllocateExistingTest) { ASSERT_TRUE(manager.Init(paired_device_map, callback, callback)); // try values already in the map, should get new id. - ASSERT_EQ( - manager.AllocateId(bluetooth::hci::Address({0, 0, 0, 0, 0, 0})), id); - ASSERT_EQ( - manager.AllocateId( - bluetooth::hci::Address({0, 0, 0, 0, 0, 1})), id + 1); - ASSERT_EQ( - manager.AllocateId(bluetooth::hci::Address({0, 0, 0, 0, 0, 0})), id); - ASSERT_EQ( - manager.AllocateId( - bluetooth::hci::Address({0, 0, 0, 0, 0, 2})), id + 2); + ASSERT_EQ(manager.AllocateId(bluetooth::hci::Address({0, 0, 0, 0, 0, 0})), id); + ASSERT_EQ(manager.AllocateId(bluetooth::hci::Address({0, 0, 0, 0, 0, 1})), id + 1); + ASSERT_EQ(manager.AllocateId(bluetooth::hci::Address({0, 0, 0, 0, 0, 0})), id); + ASSERT_EQ(manager.AllocateId(bluetooth::hci::Address({0, 0, 0, 0, 0, 2})), id + 2); ASSERT_TRUE(manager.Close()); } @@ -143,31 +129,24 @@ TEST(BluetoothMetricIdManagerTest, MetricIdManagerMainTest1) { std::unordered_map paired_device_map; int placeholder = 22; int* pointer = &placeholder; - MetricIdManager::Callback save_callback = [pointer]( - const bluetooth::hci::Address&, - const int) { + MetricIdManager::Callback save_callback = [pointer](const bluetooth::hci::Address&, const int) { *pointer = *pointer * 2; return true; }; - MetricIdManager::Callback forget_callback = [pointer]( - const bluetooth::hci::Address&, - const int) { + MetricIdManager::Callback forget_callback = [pointer](const bluetooth::hci::Address&, const int) { *pointer = *pointer / 2; return true; }; - ASSERT_TRUE( - manager.Init(paired_device_map, save_callback, forget_callback)); + ASSERT_TRUE(manager.Init(paired_device_map, save_callback, forget_callback)); ASSERT_EQ(manager.AllocateId(bluetooth::hci::Address({0, 0, 0, 0, 0, 0})), MetricIdManager::kMinId); // save it and make sure the callback is called - ASSERT_TRUE( - manager.SaveDevice(bluetooth::hci::Address({0, 0, 0, 0, 0, 0}))); + ASSERT_TRUE(manager.SaveDevice(bluetooth::hci::Address({0, 0, 0, 0, 0, 0}))); ASSERT_EQ(placeholder, 44); // should fail, since id of device is not allocated - ASSERT_FALSE( - manager.SaveDevice(bluetooth::hci::Address({0, 0, 0, 0, 0, 1}))); + ASSERT_FALSE(manager.SaveDevice(bluetooth::hci::Address({0, 0, 0, 0, 0, 1}))); ASSERT_EQ(placeholder, 44); // save it and make sure the callback is called @@ -175,16 +154,13 @@ TEST(BluetoothMetricIdManagerTest, MetricIdManagerMainTest1) { MetricIdManager::kMinId + 1); ASSERT_EQ(manager.AllocateId(bluetooth::hci::Address({0, 0, 0, 0, 0, 3})), MetricIdManager::kMinId + 2); - ASSERT_TRUE( - manager.SaveDevice(bluetooth::hci::Address({0, 0, 0, 0, 0, 2}))); + ASSERT_TRUE(manager.SaveDevice(bluetooth::hci::Address({0, 0, 0, 0, 0, 2}))); ASSERT_EQ(placeholder, 88); - ASSERT_TRUE( - manager.SaveDevice(bluetooth::hci::Address({0, 0, 0, 0, 0, 3}))); + ASSERT_TRUE(manager.SaveDevice(bluetooth::hci::Address({0, 0, 0, 0, 0, 3}))); ASSERT_EQ(placeholder, 176); // should be true but callback won't be called, since id had been saved - ASSERT_TRUE( - manager.SaveDevice(bluetooth::hci::Address({0, 0, 0, 0, 0, 0}))); + ASSERT_TRUE(manager.SaveDevice(bluetooth::hci::Address({0, 0, 0, 0, 0, 0}))); ASSERT_EQ(placeholder, 176); // forget @@ -200,39 +176,31 @@ TEST(BluetoothMetricIdManagerTest, MetricIdManagerFullPairedMap) { auto& manager = MetricIdManager::GetInstance(); // preset a full map std::unordered_map paired_device_map = - generateAddresses(MetricIdManager::kMaxNumPairedDevicesInMemory); + generateAddresses(MetricIdManager::kMaxNumPairedDevicesInMemory); int placeholder = 243; int* pointer = &placeholder; - MetricIdManager::Callback save_callback = [pointer]( - const bluetooth::hci::Address&, - const int) { + MetricIdManager::Callback save_callback = [pointer](const bluetooth::hci::Address&, const int) { *pointer = *pointer * 2; return true; }; - MetricIdManager::Callback forget_callback = [pointer]( - const bluetooth::hci::Address&, - const int) { + MetricIdManager::Callback forget_callback = [pointer](const bluetooth::hci::Address&, const int) { *pointer = *pointer / 3; return true; }; - ASSERT_TRUE( - manager.Init(paired_device_map, save_callback, forget_callback)); + ASSERT_TRUE(manager.Init(paired_device_map, save_callback, forget_callback)); // check if all preset ids are there. // comments based on kMaxNumPairedDevicesInMemory = 200. It can change. int key = 0; - for (key = 0; - key < static_cast(MetricIdManager::kMaxNumPairedDevicesInMemory); - key++) { - ASSERT_EQ(manager.AllocateId(kthAddress(key)), - key + MetricIdManager::kMinId); + for (key = 0; key < static_cast(MetricIdManager::kMaxNumPairedDevicesInMemory); key++) { + ASSERT_EQ(manager.AllocateId(kthAddress(key)), key + MetricIdManager::kMinId); } // paired: 0, 1, 2 ... 199, // scanned: - int id = static_cast(MetricIdManager::kMaxNumPairedDevicesInMemory + - MetricIdManager::kMinId); + int id = + static_cast(MetricIdManager::kMaxNumPairedDevicesInMemory + MetricIdManager::kMinId); // next id should be MetricIdManager::kMaxNumPairedDevicesInMemory + // MetricIdManager::kMinId @@ -335,8 +303,7 @@ TEST(BluetoothMetricIdManagerTest, MetricIdManagerFullPairedMap) { placeholder = 4; ASSERT_TRUE(manager.SaveDevice(kthAddress(0))); ASSERT_TRUE(manager.SaveDevice(kthAddress(1))); - ASSERT_TRUE(manager.SaveDevice( - kthAddress(MetricIdManager::kMaxNumPairedDevicesInMemory + 5))); + ASSERT_TRUE(manager.SaveDevice(kthAddress(MetricIdManager::kMaxNumPairedDevicesInMemory + 5))); ASSERT_EQ(placeholder, 32); ASSERT_TRUE(manager.Close()); @@ -347,36 +314,28 @@ TEST(BluetoothMetricIdManagerTest, MetricIdManagerFullScannedMap) { std::unordered_map paired_device_map; int placeholder = 22; int* pointer = &placeholder; - MetricIdManager::Callback save_callback = [pointer]( - const bluetooth::hci::Address&,const int) { + MetricIdManager::Callback save_callback = [pointer](const bluetooth::hci::Address&, const int) { *pointer = *pointer * 2; return true; }; - MetricIdManager::Callback forget_callback = [pointer]( - const bluetooth::hci::Address&,const int) { + MetricIdManager::Callback forget_callback = [pointer](const bluetooth::hci::Address&, const int) { *pointer = *pointer / 2; return true; }; - ASSERT_TRUE( - manager.Init(paired_device_map, save_callback, forget_callback)); + ASSERT_TRUE(manager.Init(paired_device_map, save_callback, forget_callback)); // allocate kMaxNumUnpairedDevicesInMemory ids // comments based on kMaxNumUnpairedDevicesInMemory = 200 - for (int key = 0; - key < - static_cast(MetricIdManager::kMaxNumUnpairedDevicesInMemory); + for (int key = 0; key < static_cast(MetricIdManager::kMaxNumUnpairedDevicesInMemory); key++) { - ASSERT_EQ(manager.AllocateId(kthAddress(key)), - key + MetricIdManager::kMinId); + ASSERT_EQ(manager.AllocateId(kthAddress(key)), key + MetricIdManager::kMinId); } // scanned: 0, 1, 2 ... 199, // paired: - int id = MetricIdManager::kMaxNumUnpairedDevicesInMemory + - MetricIdManager::kMinId; - bluetooth::hci::Address addr = - kthAddress(MetricIdManager::kMaxNumUnpairedDevicesInMemory); + int id = MetricIdManager::kMaxNumUnpairedDevicesInMemory + MetricIdManager::kMinId; + bluetooth::hci::Address addr = kthAddress(MetricIdManager::kMaxNumUnpairedDevicesInMemory); ASSERT_EQ(manager.AllocateId(addr), id); // scanned: 1, 2 ... 199, 200 @@ -396,9 +355,7 @@ TEST(BluetoothMetricIdManagerTest, MetricIdManagerFullScannedMap) { // try to allocate for device 0, 1, 2, 3, 4....199 // we should have a new id every time, // since the scanned map is full at this point - for (int key = 0; - key < - static_cast(MetricIdManager::kMaxNumUnpairedDevicesInMemory); + for (int key = 0; key < static_cast(MetricIdManager::kMaxNumUnpairedDevicesInMemory); key++) { ASSERT_EQ(manager.AllocateId(kthAddress(key)), id++); } @@ -410,24 +367,19 @@ TEST(BluetoothMetricIdManagerTest, MetricIdManagerMultiThreadPressureTest) { auto& manager = MetricIdManager::GetInstance(); int placeholder = 22; int* pointer = &placeholder; - MetricIdManager::Callback save_callback = [pointer]( - const bluetooth::hci::Address&, const int) { + MetricIdManager::Callback save_callback = [pointer](const bluetooth::hci::Address&, const int) { *pointer = *pointer + 1; return true; }; - MetricIdManager::Callback forget_callback = [pointer]( - const bluetooth::hci::Address&, const int) { + MetricIdManager::Callback forget_callback = [pointer](const bluetooth::hci::Address&, const int) { *pointer = *pointer - 1; return true; }; - ASSERT_TRUE( - manager.Init(paired_device_map, save_callback, forget_callback)); + ASSERT_TRUE(manager.Init(paired_device_map, save_callback, forget_callback)); // make sure no deadlock std::vector workers; - for (int key = 0; - key < - static_cast(MetricIdManager::kMaxNumUnpairedDevicesInMemory); + for (int key = 0; key < static_cast(MetricIdManager::kMaxNumUnpairedDevicesInMemory); key++) { workers.push_back(std::thread([key]() { auto& manager = MetricIdManager::GetInstance(); @@ -447,8 +399,7 @@ TEST(BluetoothMetricIdManagerTest, MetricIdManagerMultiThreadPressureTest) { TEST(BluetoothMetricIdManagerTest, MetricIdManagerWrapAroundTest1) { std::unordered_map paired_device_map; auto& manager = MetricIdManager::GetInstance(); - MetricIdManager::Callback callback = []( - const bluetooth::hci::Address&, const int) { + MetricIdManager::Callback callback = [](const bluetooth::hci::Address&, const int) { return true; }; @@ -478,8 +429,7 @@ TEST(BluetoothMetricIdManagerTest, MetricIdManagerWrapAroundTest1) { TEST(BluetoothMetricIdManagerTest, MetricIdManagerWrapAroundTest2) { std::unordered_map paired_device_map; auto& manager = MetricIdManager::GetInstance(); - MetricIdManager::Callback callback = []( - const bluetooth::hci::Address&, const int) { + MetricIdManager::Callback callback = [](const bluetooth::hci::Address&, const int) { return true; }; diff --git a/system/gd/common/multi_priority_queue.h b/system/gd/common/multi_priority_queue.h index 0546cd9c7cb..a60f48818c2 100644 --- a/system/gd/common/multi_priority_queue.h +++ b/system/gd/common/multi_priority_queue.h @@ -28,25 +28,20 @@ namespace common { * A queue implementation which supports items with multiple priorities. * Items with greater priority value will be dequeued first. * When Enqueuing, the user can specify the priority (0 by default). - * This can be used by ACL or L2CAP lower queue end sender to prioritize some link or channel, used by A2DP. + * This can be used by ACL or L2CAP lower queue end sender to prioritize some link or channel, used + * by A2DP. */ template class MultiPriorityQueue { static_assert(NUM_PRIORITY_LEVELS > 1); - public: +public: // Get the front item with the highest priority. Queue must be non-empty. - T& front() { - return queues_[next_to_dequeue_.top()].front(); - } + T& front() { return queues_[next_to_dequeue_.top()].front(); } - [[nodiscard]] bool empty() const { - return next_to_dequeue_.empty(); - } + [[nodiscard]] bool empty() const { return next_to_dequeue_.empty(); } - [[nodiscard]] size_t size() const { - return next_to_dequeue_.size(); - } + [[nodiscard]] size_t size() const { return next_to_dequeue_.size(); } // Push the item with specified priority void push(const T& t, int priority = 0) { @@ -66,7 +61,7 @@ class MultiPriorityQueue { next_to_dequeue_.pop(); } - private: +private: std::array, NUM_PRIORITY_LEVELS> queues_; std::priority_queue next_to_dequeue_; }; diff --git a/system/gd/common/multi_priority_queue_test.cc b/system/gd/common/multi_priority_queue_test.cc index b40095205ec..435e1ad3cd5 100644 --- a/system/gd/common/multi_priority_queue_test.cc +++ b/system/gd/common/multi_priority_queue_test.cc @@ -16,10 +16,10 @@ * ******************************************************************************/ -#include - #include "common/multi_priority_queue.h" +#include + namespace bluetooth { namespace common { diff --git a/system/gd/common/numbers.h b/system/gd/common/numbers.h index a2e9621e429..826615a71f2 100644 --- a/system/gd/common/numbers.h +++ b/system/gd/common/numbers.h @@ -28,9 +28,8 @@ bool IsNumberInNumericLimits(InputType input) { // Only arithmetic types are supported static_assert(std::is_arithmetic_v && std::is_arithmetic_v); // Either both are signed or both are unsigned - static_assert( - (std::is_signed_v && std::is_signed_v) || - (std::is_unsigned_v && std::is_unsigned_v)); + static_assert((std::is_signed_v && std::is_signed_v) || + (std::is_unsigned_v && std::is_unsigned_v)); if (std::numeric_limits::max() > std::numeric_limits::max()) { if (input > std::numeric_limits::max()) { return false; diff --git a/system/gd/common/numbers_test.cc b/system/gd/common/numbers_test.cc index ac4c3d708dc..ee1b92a87be 100644 --- a/system/gd/common/numbers_test.cc +++ b/system/gd/common/numbers_test.cc @@ -16,10 +16,10 @@ #include "common/numbers.h" -#include - #include +#include + namespace testing { using bluetooth::common::IsNumberInNumericLimits; diff --git a/system/gd/common/postable_context.h b/system/gd/common/postable_context.h index e44850cd854..4a9514870f2 100644 --- a/system/gd/common/postable_context.h +++ b/system/gd/common/postable_context.h @@ -23,35 +23,35 @@ namespace bluetooth::common { class PostableContext : public IPostableContext { - public: +public: virtual ~PostableContext() = default; template auto BindOnce(Functor&& functor, Args&&... args) { return common::ContextualOnceCallback( - common::BindOnce(std::forward(functor), std::forward(args)...), this); + common::BindOnce(std::forward(functor), std::forward(args)...), this); } template auto BindOnceOn(T* obj, Functor&& functor, Args&&... args) { return common::ContextualOnceCallback( - common::BindOnce( - std::forward(functor), common::Unretained(obj), std::forward(args)...), - this); + common::BindOnce(std::forward(functor), common::Unretained(obj), + std::forward(args)...), + this); } template auto Bind(Functor&& functor, Args&&... args) { return common::ContextualCallback( - common::Bind(std::forward(functor), std::forward(args)...), this); + common::Bind(std::forward(functor), std::forward(args)...), this); } template auto BindOn(T* obj, Functor&& functor, Args&&... args) { return common::ContextualCallback( - common::Bind( - std::forward(functor), common::Unretained(obj), std::forward(args)...), - this); + common::Bind(std::forward(functor), common::Unretained(obj), + std::forward(args)...), + this); } }; diff --git a/system/gd/common/stop_watch.cc b/system/gd/common/stop_watch.cc index 2a64f2ccd55..9fcacd5986d 100644 --- a/system/gd/common/stop_watch.cc +++ b/system/gd/common/stop_watch.cc @@ -39,13 +39,11 @@ static std::recursive_mutex stopwatch_log_mutex; void StopWatch::RecordLog(StopWatchLog log) { std::unique_lock lock(stopwatch_log_mutex, std::defer_lock); if (!lock.try_lock()) { - log::info( - "try_lock fail. log content: {}, took {} us", - log.message, - static_cast(std::chrono::duration_cast( - stopwatch_logs[current_buffer_index].end_timestamp - - stopwatch_logs[current_buffer_index].start_timestamp) - .count())); + log::info("try_lock fail. log content: {}, took {} us", log.message, + static_cast(std::chrono::duration_cast( + stopwatch_logs[current_buffer_index].end_timestamp - + stopwatch_logs[current_buffer_index].start_timestamp) + .count())); return; } if (current_buffer_index >= LOG_BUFFER_LENGTH) { @@ -70,21 +68,17 @@ void StopWatch::DumpStopWatchLog() { } std::stringstream ss; auto now = stopwatch_logs[current_buffer_index].timestamp; - auto millis = std::chrono::duration_cast( - now.time_since_epoch()) % - 1000; + auto millis = + std::chrono::duration_cast(now.time_since_epoch()) % 1000; auto now_time_t = std::chrono::system_clock::to_time_t(now); ss << std::put_time(std::localtime(&now_time_t), "%Y-%m-%d %H:%M:%S"); ss << '.' << std::setfill('0') << std::setw(3) << millis.count(); std::string start_timestamp = ss.str(); - log::info( - "{}: {}: took {} us", - start_timestamp, - stopwatch_logs[current_buffer_index].message, - static_cast(std::chrono::duration_cast( - stopwatch_logs[current_buffer_index].end_timestamp - - stopwatch_logs[current_buffer_index].start_timestamp) - .count())); + log::info("{}: {}: took {} us", start_timestamp, stopwatch_logs[current_buffer_index].message, + static_cast(std::chrono::duration_cast( + stopwatch_logs[current_buffer_index].end_timestamp - + stopwatch_logs[current_buffer_index].start_timestamp) + .count())); current_buffer_index++; } log::info("=-----------------------------------="); diff --git a/system/gd/common/stop_watch.h b/system/gd/common/stop_watch.h index 4d7d54474d4..792229172e5 100644 --- a/system/gd/common/stop_watch.h +++ b/system/gd/common/stop_watch.h @@ -30,12 +30,12 @@ typedef struct { } StopWatchLog; class StopWatch { - public: +public: static void DumpStopWatchLog(void); StopWatch(std::string text); ~StopWatch(); - private: +private: std::string text_; std::chrono::system_clock::time_point timestamp_; std::chrono::high_resolution_clock::time_point start_timestamp_; diff --git a/system/gd/common/strings.cc b/system/gd/common/strings.cc index 89feb1bda39..db42acfcf49 100644 --- a/system/gd/common/strings.cc +++ b/system/gd/common/strings.cc @@ -30,15 +30,11 @@ namespace { struct IsSpace { - bool operator()(std::string::value_type v) { - return isspace(static_cast(v)); - } + bool operator()(std::string::value_type v) { return isspace(static_cast(v)); } }; struct IsHexDigit { - bool operator()(std::string::value_type v) { - return isxdigit(static_cast(v)); - } + bool operator()(std::string::value_type v) { return isxdigit(static_cast(v)); } }; } // namespace @@ -83,13 +79,15 @@ std::string StringTrim(std::string str) { return str; } -std::vector StringSplit(const std::string& str, const std::string& delim, size_t max_token) { +std::vector StringSplit(const std::string& str, const std::string& delim, + size_t max_token) { log::assert_that(!delim.empty(), "delim cannot be empty"); std::vector tokens; // Use std::string::find and std::string::substr to avoid copying str into a stringstream std::string::size_type starting_index = 0; auto index_of_delim = str.find(delim); - while ((max_token == 0 || tokens.size() < (max_token - 1)) && index_of_delim != std::string::npos) { + while ((max_token == 0 || tokens.size() < (max_token - 1)) && + index_of_delim != std::string::npos) { tokens.push_back(str.substr(starting_index, index_of_delim - starting_index)); starting_index = index_of_delim + delim.size(); index_of_delim = str.find(delim, starting_index); @@ -131,9 +129,7 @@ std::optional Int64FromString(const std::string& str) { return value; } -std::string ToString(int64_t value) { - return std::to_string(value); -} +std::string ToString(int64_t value) { return std::to_string(value); } std::optional Uint64FromString(const std::string& str) { if (str.find('-') != std::string::npos) { @@ -158,9 +154,7 @@ std::optional Uint64FromString(const std::string& str) { return value; } -std::string ToString(uint64_t value) { - return std::to_string(value); -} +std::string ToString(uint64_t value) { return std::to_string(value); } std::optional BoolFromString(const std::string& str) { if (str == "true") { @@ -173,9 +167,7 @@ std::optional BoolFromString(const std::string& str) { } } -std::string ToString(bool value) { - return value ? "true" : "false"; -} +std::string ToString(bool value) { return value ? "true" : "false"; } } // namespace common } // namespace bluetooth diff --git a/system/gd/common/strings.h b/system/gd/common/strings.h index 19f5d630f03..ed5af390aa3 100644 --- a/system/gd/common/strings.h +++ b/system/gd/common/strings.h @@ -48,39 +48,44 @@ inline std::string ToString(const T& value) { template std::string ToHexString(T x) { if (x < 0) { - if (x == INT_MIN) return "INT_MIN"; + if (x == INT_MIN) { + return "INT_MIN"; + } return "-" + ToHexString(-x); } std::stringstream tmp; - tmp << "0x" << std::internal << std::hex << std::setfill('0') << std::setw(sizeof(T) * 2) << (unsigned long)x; + tmp << "0x" << std::internal << std::hex << std::setfill('0') << std::setw(sizeof(T) * 2) + << (unsigned long)x; return tmp.str(); } template <> inline std::string ToHexString<>(signed long x) { if (x < 0) { - if (x == LONG_MIN) return "LONG_MIN"; + if (x == LONG_MIN) { + return "LONG_MIN"; + } return "-" + ToHexString(-x); } std::stringstream tmp; - tmp << "0x" << std::internal << std::hex << std::setfill('0') << std::setw(sizeof(signed long) * 2) - << (unsigned long)x; + tmp << "0x" << std::internal << std::hex << std::setfill('0') + << std::setw(sizeof(signed long) * 2) << (unsigned long)x; return tmp.str(); } template <> inline std::string ToHexString<>(unsigned int x) { std::stringstream tmp; - tmp << "0x" << std::internal << std::hex << std::setfill('0') << std::setw(sizeof(unsigned int) * 2) - << (unsigned long)x; + tmp << "0x" << std::internal << std::hex << std::setfill('0') + << std::setw(sizeof(unsigned int) * 2) << (unsigned long)x; return tmp.str(); } // Convert value into a hex decimal formatted string in lower case, prefixed with 0s template std::string ToHexString(InputIt first, InputIt last) { - static_assert( - std::is_same_v::value_type, uint8_t>, "Must use uint8_t iterator"); + static_assert(std::is_same_v::value_type, uint8_t>, + "Must use uint8_t iterator"); std::stringstream ss; for (InputIt it = first; it != last; ++it) { // +(byte) to prevent an uint8_t to be interpreted as a char @@ -88,7 +93,8 @@ std::string ToHexString(InputIt first, InputIt last) { } return ss.str(); } -// Convenience method for normal cases and initializer list, e.g. ToHexString({0x12, 0x34, 0x56, 0xab}) +// Convenience method for normal cases and initializer list, e.g. ToHexString({0x12, 0x34, 0x56, +// 0xab}) std::string ToHexString(const std::vector& value); // Return true if |str| is a valid hex demical strings contains only hex decimal chars [0-9a-fA-F] @@ -100,8 +106,10 @@ std::optional> FromHexString(const std::string& str); // Remove whitespace from both ends of the |str|, returning a copy std::string StringTrim(std::string str); -// Split |str| into at most |max_token| tokens delimited by |delim|, unlimited tokens when |max_token| is 0 -std::vector StringSplit(const std::string& str, const std::string& delim, size_t max_token = 0); +// Split |str| into at most |max_token| tokens delimited by |delim|, unlimited tokens when +// |max_token| is 0 +std::vector StringSplit(const std::string& str, const std::string& delim, + size_t max_token = 0); // Join |strings| into a single string using |delim| std::string StringJoin(const std::vector& strings, const std::string& delim); @@ -124,13 +132,8 @@ std::string StringFormat(const std::string& format, Args... args) { // Add 1 for terminating null byte std::vector buffer(size + 1); auto actual_size = std::snprintf(buffer.data(), buffer.size(), format.c_str(), args...); - log::assert_that( - size == actual_size, - "asked size {}, actual size {}, error {}, text '{}'", - size, - actual_size, - errno, - strerror(errno)); + log::assert_that(size == actual_size, "asked size {}, actual size {}, error {}, text '{}'", size, + actual_size, errno, strerror(errno)); // Exclude the terminating null byte return std::string(buffer.data(), size); } @@ -142,9 +145,8 @@ inline std::string StringFormatTime(const std::string& format, const struct std: } inline std::string StringFormatTimeWithMilliseconds( - const std::string& format, - std::chrono::time_point time_point, - struct tm* (*calendar_to_tm)(const time_t* timep) = localtime) { + const std::string& format, std::chrono::time_point time_point, + struct tm* (*calendar_to_tm)(const time_t* timep) = localtime) { std::time_t epoch_time = std::chrono::system_clock::to_time_t(time_point); auto millis = time_point.time_since_epoch() / std::chrono::milliseconds(1) % 1000; std::tm tm = *calendar_to_tm(&epoch_time); diff --git a/system/gd/common/strings_test.cc b/system/gd/common/strings_test.cc index b68507fe2d4..c252429ec94 100644 --- a/system/gd/common/strings_test.cc +++ b/system/gd/common/strings_test.cc @@ -38,12 +38,8 @@ using bluetooth::common::ToHexString; using bluetooth::common::ToString; using bluetooth::common::Uint64FromString; -static inline bool is_arch32() { - return sizeof(long) == 4; -} -static inline bool is_arch64() { - return sizeof(long) == 8; -} +static inline bool is_arch32() { return sizeof(long) == 4; } +static inline bool is_arch64() { return sizeof(long) == 8; } #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winteger-overflow" @@ -76,7 +72,7 @@ TEST(StringsTest, to_hex_string_from_number) { ASSERT_EQ(ToHexString(LONG_MIN + 1L), "-0x7fffffffffffffff"); } else { bluetooth::log::error("Unknown architecture"); - ASSERT_TRUE(false); + FAIL(); } ASSERT_EQ(ToHexString('a'), "0x61"); } @@ -142,7 +138,8 @@ TEST(StringsTest, to_hex_string_test) { TEST(StringsTest, from_hex_string_test) { // normal - ASSERT_THAT(FromHexString("aabbccdd1122"), Optional(ElementsAre(0xaa, 0xbb, 0xcc, 0xdd, 0x11, 0x22))); + ASSERT_THAT(FromHexString("aabbccdd1122"), + Optional(ElementsAre(0xaa, 0xbb, 0xcc, 0xdd, 0x11, 0x22))); // empty ASSERT_THAT(FromHexString(""), Optional(IsEmpty())); // unary @@ -184,7 +181,8 @@ TEST(StringsTest, int64_from_and_to_string_test) { // INT64_MAX+1 ASSERT_FALSE(Int64FromString("9223372036854775808")); // INT64_MIN - ASSERT_THAT(Int64FromString("-9223372036854775808"), Optional(Eq(int64_t(-9223372036854775807LL - 1)))); + ASSERT_THAT(Int64FromString("-9223372036854775808"), + Optional(Eq(int64_t(-9223372036854775807LL - 1)))); ASSERT_THAT(ToString(int64_t(-9223372036854775807LL - 1)), StrEq("-9223372036854775808")); // INT64_MIN-1 ASSERT_FALSE(Int64FromString("-9223372036854775809")); @@ -207,7 +205,8 @@ TEST(StringsTest, uint64_from_and_to_string_test) { ASSERT_THAT(Uint64FromString("4294967295"), Optional(Eq(uint64_t(4294967295)))); ASSERT_THAT(ToString(uint64_t(4294967295)), StrEq("4294967295")); // UINT64_MAX - ASSERT_THAT(Uint64FromString("18446744073709551615"), Optional(Eq(uint64_t(18446744073709551615ULL)))); + ASSERT_THAT(Uint64FromString("18446744073709551615"), + Optional(Eq(uint64_t(18446744073709551615ULL)))); ASSERT_THAT(ToString(uint64_t(18446744073709551615ULL)), StrEq("18446744073709551615")); // UINT64_MAX+1 ASSERT_FALSE(Uint64FromString("18446744073709551616")); @@ -242,22 +241,28 @@ TEST(StringsTest, string_format_time_test) { TEST(StringsTest, string_format_time_with_ms_in_the_beginning_test) { std::string format("%Y-%m-%d %H:%M:%S"); std::time_t from_time = 0; - std::chrono::time_point time_point = std::chrono::system_clock::from_time_t(from_time); + std::chrono::time_point time_point = + std::chrono::system_clock::from_time_t(from_time); - ASSERT_THAT(StringFormatTimeWithMilliseconds(format, time_point, gmtime), StrEq("1970-01-01 00:00:00.000")); + ASSERT_THAT(StringFormatTimeWithMilliseconds(format, time_point, gmtime), + StrEq("1970-01-01 00:00:00.000")); } TEST(StringsTest, string_format_time_with_ms_test) { std::string format("%Y-%m-%d %H:%M:%S"); std::time_t from_time1 = 1234567890; - std::chrono::time_point time_point1 = std::chrono::system_clock::from_time_t(from_time1); + std::chrono::time_point time_point1 = + std::chrono::system_clock::from_time_t(from_time1); std::time_t from_time2 = 1234567890; - std::chrono::time_point time_point2 = std::chrono::system_clock::from_time_t(from_time2); + std::chrono::time_point time_point2 = + std::chrono::system_clock::from_time_t(from_time2); time_point2 += std::chrono::milliseconds(1); - ASSERT_THAT(StringFormatTimeWithMilliseconds(format, time_point1, gmtime), StrEq("2009-02-13 23:31:30.000")); - ASSERT_THAT(StringFormatTimeWithMilliseconds(format, time_point2, gmtime), StrEq("2009-02-13 23:31:30.001")); + ASSERT_THAT(StringFormatTimeWithMilliseconds(format, time_point1, gmtime), + StrEq("2009-02-13 23:31:30.000")); + ASSERT_THAT(StringFormatTimeWithMilliseconds(format, time_point2, gmtime), + StrEq("2009-02-13 23:31:30.001")); } class ExampleClass {}; diff --git a/system/gd/common/sync_map_count.h b/system/gd/common/sync_map_count.h index 6cb6dcf4dd0..b9cfab30498 100644 --- a/system/gd/common/sync_map_count.h +++ b/system/gd/common/sync_map_count.h @@ -22,13 +22,13 @@ template class SyncMapCount { - public: +public: struct Item { T item; size_t count; }; - private: +private: std::map map_; size_t max_size_{SIZE_MAX}; mutable std::mutex mutex_; @@ -43,18 +43,21 @@ class SyncMapCount { std::vector GetSorted(std::function sort_func) const { std::vector vec = Vectorize(); - sort(vec.begin(), vec.end(), [=](const Item& a, const Item& b) -> bool { return sort_func(a, b); }); + sort(vec.begin(), vec.end(), + [=](const Item& a, const Item& b) -> bool { return sort_func(a, b); }); return vec; } - public: +public: SyncMapCount() : max_size_(SIZE_MAX) {} explicit SyncMapCount(size_t max_size) : max_size_(max_size) {} ~SyncMapCount() = default; void Put(const T item) { std::unique_lock lock(mutex_); - if (map_.size() == max_size_) return; + if (map_.size() == max_size_) { + return; + } (map_.count(item) > 0) ? map_[item] += 1 : map_[item] = 1; } diff --git a/system/gd/common/sync_map_count_test.cc b/system/gd/common/sync_map_count_test.cc index d8692003894..189e6f47c6a 100644 --- a/system/gd/common/sync_map_count_test.cc +++ b/system/gd/common/sync_map_count_test.cc @@ -28,15 +28,7 @@ namespace testing { const char* data[] = { - "One", - "Two", - "Two", - "Three", - "Three", - "Three", - "AAA", - "ZZZ", - nullptr, + "One", "Two", "Two", "Three", "Three", "Three", "AAA", "ZZZ", nullptr, }; namespace { @@ -86,18 +78,12 @@ TEST(SyncMapCount, sorted_string_value_high_to_low) { struct TestString { TestString(std::string string) : string_(string) {} - std::string String() const { - return string_; - } + std::string String() const { return string_; } - bool operator<(const TestString& other) const { - return (other.string_ > string_); - } - bool operator==(const TestString& other) const { - return (other.string_ == string_); - } + bool operator<(const TestString& other) const { return other.string_ > string_; } + bool operator==(const TestString& other) const { return other.string_ == string_; } - private: +private: std::string string_; }; diff --git a/system/gd/common/testing/wired_pair_of_bidi_queues.h b/system/gd/common/testing/wired_pair_of_bidi_queues.h index 027798d1d4d..ca401cb9e09 100644 --- a/system/gd/common/testing/wired_pair_of_bidi_queues.h +++ b/system/gd/common/testing/wired_pair_of_bidi_queues.h @@ -33,20 +33,25 @@ namespace bluetooth { namespace common { namespace testing { -/* This class is a pair of BiDiQueues, that have down ends "wired" together. It can be used i.e. to mock L2cap - * interface, and provide two queues, where each sends packets of type A, and receives packets of type B */ +/* This class is a pair of BiDiQueues, that have down ends "wired" together. It can be used i.e. to + * mock L2cap interface, and provide two queues, where each sends packets of type A, and receives + * packets of type B */ template (*A_TO_B)(std::unique_ptr)> class WiredPairOfBiDiQueues { void dequeue_callback_a() { auto down_thing = queue_a_.GetDownEnd()->TryDequeue(); - if (!down_thing) log::error("Received dequeue, but no data ready..."); + if (!down_thing) { + log::error("Received dequeue, but no data ready..."); + } down_buffer_b_.Enqueue(A_TO_B(std::move(down_thing)), handler_); } void dequeue_callback_b() { auto down_thing = queue_b_.GetDownEnd()->TryDequeue(); - if (!down_thing) log::error("Received dequeue, but no data ready..."); + if (!down_thing) { + log::error("Received dequeue, but no data ready..."); + } down_buffer_a_.Enqueue(A_TO_B(std::move(down_thing)), handler_); } @@ -57,12 +62,14 @@ class WiredPairOfBiDiQueues { os::EnqueueBuffer down_buffer_a_{queue_a_.GetDownEnd()}; os::EnqueueBuffer down_buffer_b_{queue_b_.GetDownEnd()}; - public: +public: WiredPairOfBiDiQueues(os::Handler* handler) : handler_(handler) { queue_a_.GetDownEnd()->RegisterDequeue( - handler_, common::Bind(&WiredPairOfBiDiQueues::dequeue_callback_a, common::Unretained(this))); + handler_, + common::Bind(&WiredPairOfBiDiQueues::dequeue_callback_a, common::Unretained(this))); queue_b_.GetDownEnd()->RegisterDequeue( - handler_, common::Bind(&WiredPairOfBiDiQueues::dequeue_callback_b, common::Unretained(this))); + handler_, + common::Bind(&WiredPairOfBiDiQueues::dequeue_callback_b, common::Unretained(this))); } ~WiredPairOfBiDiQueues() { @@ -71,19 +78,15 @@ class WiredPairOfBiDiQueues { } /* This methd returns the UpEnd of queue A */ - common::BidiQueueEnd* GetQueueAUpEnd() { - return queue_a_.GetUpEnd(); - } + common::BidiQueueEnd* GetQueueAUpEnd() { return queue_a_.GetUpEnd(); } /* This methd returns the UpEnd of queue B */ - common::BidiQueueEnd* GetQueueBUpEnd() { - return queue_b_.GetUpEnd(); - } + common::BidiQueueEnd* GetQueueBUpEnd() { return queue_b_.GetUpEnd(); } }; namespace { std::unique_ptr> BuilderToView( - std::unique_ptr up_thing) { + std::unique_ptr up_thing) { auto bytes = std::make_shared>(); bluetooth::packet::BitInserter i(*bytes); bytes->reserve(up_thing->size()); @@ -93,7 +96,8 @@ std::unique_ptr> BuilderToView( } // namespace using WiredPairOfL2capQueues = - WiredPairOfBiDiQueues, BuilderToView>; + WiredPairOfBiDiQueues, + BuilderToView>; } // namespace testing } // namespace common diff --git a/system/gd/crypto_toolbox/aes.cc b/system/gd/crypto_toolbox/aes.cc index 395642cd36b..c40950e33d7 100644 --- a/system/gd/crypto_toolbox/aes.cc +++ b/system/gd/crypto_toolbox/aes.cc @@ -78,8 +78,10 @@ typedef uint32_t uint_32t; #define f1(x) (x) #define f2(x) (((x) << 1) ^ ((((x) >> 7) & 1) * WPOLY)) #define f4(x) (((x) << 2) ^ ((((x) >> 6) & 1) * WPOLY) ^ ((((x) >> 6) & 2) * WPOLY)) -#define f8(x) (((x) << 3) ^ ((((x) >> 5) & 1) * WPOLY) ^ ((((x) >> 5) & 2) * WPOLY) ^ ((((x) >> 5) & 4) * WPOLY)) -#define d2(x) (((x) >> 1) ^ ((x)&1 ? DPOLY : 0)) +#define f8(x) \ + (((x) << 3) ^ ((((x) >> 5) & 1) * WPOLY) ^ ((((x) >> 5) & 2) * WPOLY) ^ \ + ((((x) >> 5) & 4) * WPOLY)) +#define d2(x) (((x) >> 1) ^ ((x) & 1 ? DPOLY : 0)) #define f3(x) (f2(x) ^ (x)) #define f9(x) (f8(x) ^ (x)) @@ -89,82 +91,103 @@ typedef uint32_t uint_32t; #if defined(USE_TABLES) -#define sb_data(w) \ - { /* S Box data values */ \ - w(0x63), w(0x7c), w(0x77), w(0x7b), w(0xf2), w(0x6b), w(0x6f), w(0xc5), w(0x30), w(0x01), w(0x67), w(0x2b), \ - w(0xfe), w(0xd7), w(0xab), w(0x76), w(0xca), w(0x82), w(0xc9), w(0x7d), w(0xfa), w(0x59), w(0x47), w(0xf0), \ - w(0xad), w(0xd4), w(0xa2), w(0xaf), w(0x9c), w(0xa4), w(0x72), w(0xc0), w(0xb7), w(0xfd), w(0x93), w(0x26), \ - w(0x36), w(0x3f), w(0xf7), w(0xcc), w(0x34), w(0xa5), w(0xe5), w(0xf1), w(0x71), w(0xd8), w(0x31), w(0x15), \ - w(0x04), w(0xc7), w(0x23), w(0xc3), w(0x18), w(0x96), w(0x05), w(0x9a), w(0x07), w(0x12), w(0x80), w(0xe2), \ - w(0xeb), w(0x27), w(0xb2), w(0x75), w(0x09), w(0x83), w(0x2c), w(0x1a), w(0x1b), w(0x6e), w(0x5a), w(0xa0), \ - w(0x52), w(0x3b), w(0xd6), w(0xb3), w(0x29), w(0xe3), w(0x2f), w(0x84), w(0x53), w(0xd1), w(0x00), w(0xed), \ - w(0x20), w(0xfc), w(0xb1), w(0x5b), w(0x6a), w(0xcb), w(0xbe), w(0x39), w(0x4a), w(0x4c), w(0x58), w(0xcf), \ - w(0xd0), w(0xef), w(0xaa), w(0xfb), w(0x43), w(0x4d), w(0x33), w(0x85), w(0x45), w(0xf9), w(0x02), w(0x7f), \ - w(0x50), w(0x3c), w(0x9f), w(0xa8), w(0x51), w(0xa3), w(0x40), w(0x8f), w(0x92), w(0x9d), w(0x38), w(0xf5), \ - w(0xbc), w(0xb6), w(0xda), w(0x21), w(0x10), w(0xff), w(0xf3), w(0xd2), w(0xcd), w(0x0c), w(0x13), w(0xec), \ - w(0x5f), w(0x97), w(0x44), w(0x17), w(0xc4), w(0xa7), w(0x7e), w(0x3d), w(0x64), w(0x5d), w(0x19), w(0x73), \ - w(0x60), w(0x81), w(0x4f), w(0xdc), w(0x22), w(0x2a), w(0x90), w(0x88), w(0x46), w(0xee), w(0xb8), w(0x14), \ - w(0xde), w(0x5e), w(0x0b), w(0xdb), w(0xe0), w(0x32), w(0x3a), w(0x0a), w(0x49), w(0x06), w(0x24), w(0x5c), \ - w(0xc2), w(0xd3), w(0xac), w(0x62), w(0x91), w(0x95), w(0xe4), w(0x79), w(0xe7), w(0xc8), w(0x37), w(0x6d), \ - w(0x8d), w(0xd5), w(0x4e), w(0xa9), w(0x6c), w(0x56), w(0xf4), w(0xea), w(0x65), w(0x7a), w(0xae), w(0x08), \ - w(0xba), w(0x78), w(0x25), w(0x2e), w(0x1c), w(0xa6), w(0xb4), w(0xc6), w(0xe8), w(0xdd), w(0x74), w(0x1f), \ - w(0x4b), w(0xbd), w(0x8b), w(0x8a), w(0x70), w(0x3e), w(0xb5), w(0x66), w(0x48), w(0x03), w(0xf6), w(0x0e), \ - w(0x61), w(0x35), w(0x57), w(0xb9), w(0x86), w(0xc1), w(0x1d), w(0x9e), w(0xe1), w(0xf8), w(0x98), w(0x11), \ - w(0x69), w(0xd9), w(0x8e), w(0x94), w(0x9b), w(0x1e), w(0x87), w(0xe9), w(0xce), w(0x55), w(0x28), w(0xdf), \ - w(0x8c), w(0xa1), w(0x89), w(0x0d), w(0xbf), w(0xe6), w(0x42), w(0x68), w(0x41), w(0x99), w(0x2d), w(0x0f), \ - w(0xb0), w(0x54), w(0xbb), w(0x16) \ +#define sb_data(w) \ + { /* S Box data values */ \ + w(0x63), w(0x7c), w(0x77), w(0x7b), w(0xf2), w(0x6b), w(0x6f), w(0xc5), w(0x30), w(0x01), \ + w(0x67), w(0x2b), w(0xfe), w(0xd7), w(0xab), w(0x76), w(0xca), w(0x82), w(0xc9), \ + w(0x7d), w(0xfa), w(0x59), w(0x47), w(0xf0), w(0xad), w(0xd4), w(0xa2), w(0xaf), \ + w(0x9c), w(0xa4), w(0x72), w(0xc0), w(0xb7), w(0xfd), w(0x93), w(0x26), w(0x36), \ + w(0x3f), w(0xf7), w(0xcc), w(0x34), w(0xa5), w(0xe5), w(0xf1), w(0x71), w(0xd8), \ + w(0x31), w(0x15), w(0x04), w(0xc7), w(0x23), w(0xc3), w(0x18), w(0x96), w(0x05), \ + w(0x9a), w(0x07), w(0x12), w(0x80), w(0xe2), w(0xeb), w(0x27), w(0xb2), w(0x75), \ + w(0x09), w(0x83), w(0x2c), w(0x1a), w(0x1b), w(0x6e), w(0x5a), w(0xa0), w(0x52), \ + w(0x3b), w(0xd6), w(0xb3), w(0x29), w(0xe3), w(0x2f), w(0x84), w(0x53), w(0xd1), \ + w(0x00), w(0xed), w(0x20), w(0xfc), w(0xb1), w(0x5b), w(0x6a), w(0xcb), w(0xbe), \ + w(0x39), w(0x4a), w(0x4c), w(0x58), w(0xcf), w(0xd0), w(0xef), w(0xaa), w(0xfb), \ + w(0x43), w(0x4d), w(0x33), w(0x85), w(0x45), w(0xf9), w(0x02), w(0x7f), w(0x50), \ + w(0x3c), w(0x9f), w(0xa8), w(0x51), w(0xa3), w(0x40), w(0x8f), w(0x92), w(0x9d), \ + w(0x38), w(0xf5), w(0xbc), w(0xb6), w(0xda), w(0x21), w(0x10), w(0xff), w(0xf3), \ + w(0xd2), w(0xcd), w(0x0c), w(0x13), w(0xec), w(0x5f), w(0x97), w(0x44), w(0x17), \ + w(0xc4), w(0xa7), w(0x7e), w(0x3d), w(0x64), w(0x5d), w(0x19), w(0x73), w(0x60), \ + w(0x81), w(0x4f), w(0xdc), w(0x22), w(0x2a), w(0x90), w(0x88), w(0x46), w(0xee), \ + w(0xb8), w(0x14), w(0xde), w(0x5e), w(0x0b), w(0xdb), w(0xe0), w(0x32), w(0x3a), \ + w(0x0a), w(0x49), w(0x06), w(0x24), w(0x5c), w(0xc2), w(0xd3), w(0xac), w(0x62), \ + w(0x91), w(0x95), w(0xe4), w(0x79), w(0xe7), w(0xc8), w(0x37), w(0x6d), w(0x8d), \ + w(0xd5), w(0x4e), w(0xa9), w(0x6c), w(0x56), w(0xf4), w(0xea), w(0x65), w(0x7a), \ + w(0xae), w(0x08), w(0xba), w(0x78), w(0x25), w(0x2e), w(0x1c), w(0xa6), w(0xb4), \ + w(0xc6), w(0xe8), w(0xdd), w(0x74), w(0x1f), w(0x4b), w(0xbd), w(0x8b), w(0x8a), \ + w(0x70), w(0x3e), w(0xb5), w(0x66), w(0x48), w(0x03), w(0xf6), w(0x0e), w(0x61), \ + w(0x35), w(0x57), w(0xb9), w(0x86), w(0xc1), w(0x1d), w(0x9e), w(0xe1), w(0xf8), \ + w(0x98), w(0x11), w(0x69), w(0xd9), w(0x8e), w(0x94), w(0x9b), w(0x1e), w(0x87), \ + w(0xe9), w(0xce), w(0x55), w(0x28), w(0xdf), w(0x8c), w(0xa1), w(0x89), w(0x0d), \ + w(0xbf), w(0xe6), w(0x42), w(0x68), w(0x41), w(0x99), w(0x2d), w(0x0f), w(0xb0), \ + w(0x54), w(0xbb), w(0x16) \ } -#define isb_data(w) \ - { /* inverse S Box data values */ \ - w(0x52), w(0x09), w(0x6a), w(0xd5), w(0x30), w(0x36), w(0xa5), w(0x38), w(0xbf), w(0x40), w(0xa3), w(0x9e), \ - w(0x81), w(0xf3), w(0xd7), w(0xfb), w(0x7c), w(0xe3), w(0x39), w(0x82), w(0x9b), w(0x2f), w(0xff), w(0x87), \ - w(0x34), w(0x8e), w(0x43), w(0x44), w(0xc4), w(0xde), w(0xe9), w(0xcb), w(0x54), w(0x7b), w(0x94), w(0x32), \ - w(0xa6), w(0xc2), w(0x23), w(0x3d), w(0xee), w(0x4c), w(0x95), w(0x0b), w(0x42), w(0xfa), w(0xc3), w(0x4e), \ - w(0x08), w(0x2e), w(0xa1), w(0x66), w(0x28), w(0xd9), w(0x24), w(0xb2), w(0x76), w(0x5b), w(0xa2), w(0x49), \ - w(0x6d), w(0x8b), w(0xd1), w(0x25), w(0x72), w(0xf8), w(0xf6), w(0x64), w(0x86), w(0x68), w(0x98), w(0x16), \ - w(0xd4), w(0xa4), w(0x5c), w(0xcc), w(0x5d), w(0x65), w(0xb6), w(0x92), w(0x6c), w(0x70), w(0x48), w(0x50), \ - w(0xfd), w(0xed), w(0xb9), w(0xda), w(0x5e), w(0x15), w(0x46), w(0x57), w(0xa7), w(0x8d), w(0x9d), w(0x84), \ - w(0x90), w(0xd8), w(0xab), w(0x00), w(0x8c), w(0xbc), w(0xd3), w(0x0a), w(0xf7), w(0xe4), w(0x58), w(0x05), \ - w(0xb8), w(0xb3), w(0x45), w(0x06), w(0xd0), w(0x2c), w(0x1e), w(0x8f), w(0xca), w(0x3f), w(0x0f), w(0x02), \ - w(0xc1), w(0xaf), w(0xbd), w(0x03), w(0x01), w(0x13), w(0x8a), w(0x6b), w(0x3a), w(0x91), w(0x11), w(0x41), \ - w(0x4f), w(0x67), w(0xdc), w(0xea), w(0x97), w(0xf2), w(0xcf), w(0xce), w(0xf0), w(0xb4), w(0xe6), w(0x73), \ - w(0x96), w(0xac), w(0x74), w(0x22), w(0xe7), w(0xad), w(0x35), w(0x85), w(0xe2), w(0xf9), w(0x37), w(0xe8), \ - w(0x1c), w(0x75), w(0xdf), w(0x6e), w(0x47), w(0xf1), w(0x1a), w(0x71), w(0x1d), w(0x29), w(0xc5), w(0x89), \ - w(0x6f), w(0xb7), w(0x62), w(0x0e), w(0xaa), w(0x18), w(0xbe), w(0x1b), w(0xfc), w(0x56), w(0x3e), w(0x4b), \ - w(0xc6), w(0xd2), w(0x79), w(0x20), w(0x9a), w(0xdb), w(0xc0), w(0xfe), w(0x78), w(0xcd), w(0x5a), w(0xf4), \ - w(0x1f), w(0xdd), w(0xa8), w(0x33), w(0x88), w(0x07), w(0xc7), w(0x31), w(0xb1), w(0x12), w(0x10), w(0x59), \ - w(0x27), w(0x80), w(0xec), w(0x5f), w(0x60), w(0x51), w(0x7f), w(0xa9), w(0x19), w(0xb5), w(0x4a), w(0x0d), \ - w(0x2d), w(0xe5), w(0x7a), w(0x9f), w(0x93), w(0xc9), w(0x9c), w(0xef), w(0xa0), w(0xe0), w(0x3b), w(0x4d), \ - w(0xae), w(0x2a), w(0xf5), w(0xb0), w(0xc8), w(0xeb), w(0xbb), w(0x3c), w(0x83), w(0x53), w(0x99), w(0x61), \ - w(0x17), w(0x2b), w(0x04), w(0x7e), w(0xba), w(0x77), w(0xd6), w(0x26), w(0xe1), w(0x69), w(0x14), w(0x63), \ - w(0x55), w(0x21), w(0x0c), w(0x7d) \ +#define isb_data(w) \ + { /* inverse S Box data values */ \ + w(0x52), w(0x09), w(0x6a), w(0xd5), w(0x30), w(0x36), w(0xa5), w(0x38), w(0xbf), w(0x40), \ + w(0xa3), w(0x9e), w(0x81), w(0xf3), w(0xd7), w(0xfb), w(0x7c), w(0xe3), w(0x39), \ + w(0x82), w(0x9b), w(0x2f), w(0xff), w(0x87), w(0x34), w(0x8e), w(0x43), w(0x44), \ + w(0xc4), w(0xde), w(0xe9), w(0xcb), w(0x54), w(0x7b), w(0x94), w(0x32), w(0xa6), \ + w(0xc2), w(0x23), w(0x3d), w(0xee), w(0x4c), w(0x95), w(0x0b), w(0x42), w(0xfa), \ + w(0xc3), w(0x4e), w(0x08), w(0x2e), w(0xa1), w(0x66), w(0x28), w(0xd9), w(0x24), \ + w(0xb2), w(0x76), w(0x5b), w(0xa2), w(0x49), w(0x6d), w(0x8b), w(0xd1), w(0x25), \ + w(0x72), w(0xf8), w(0xf6), w(0x64), w(0x86), w(0x68), w(0x98), w(0x16), w(0xd4), \ + w(0xa4), w(0x5c), w(0xcc), w(0x5d), w(0x65), w(0xb6), w(0x92), w(0x6c), w(0x70), \ + w(0x48), w(0x50), w(0xfd), w(0xed), w(0xb9), w(0xda), w(0x5e), w(0x15), w(0x46), \ + w(0x57), w(0xa7), w(0x8d), w(0x9d), w(0x84), w(0x90), w(0xd8), w(0xab), w(0x00), \ + w(0x8c), w(0xbc), w(0xd3), w(0x0a), w(0xf7), w(0xe4), w(0x58), w(0x05), w(0xb8), \ + w(0xb3), w(0x45), w(0x06), w(0xd0), w(0x2c), w(0x1e), w(0x8f), w(0xca), w(0x3f), \ + w(0x0f), w(0x02), w(0xc1), w(0xaf), w(0xbd), w(0x03), w(0x01), w(0x13), w(0x8a), \ + w(0x6b), w(0x3a), w(0x91), w(0x11), w(0x41), w(0x4f), w(0x67), w(0xdc), w(0xea), \ + w(0x97), w(0xf2), w(0xcf), w(0xce), w(0xf0), w(0xb4), w(0xe6), w(0x73), w(0x96), \ + w(0xac), w(0x74), w(0x22), w(0xe7), w(0xad), w(0x35), w(0x85), w(0xe2), w(0xf9), \ + w(0x37), w(0xe8), w(0x1c), w(0x75), w(0xdf), w(0x6e), w(0x47), w(0xf1), w(0x1a), \ + w(0x71), w(0x1d), w(0x29), w(0xc5), w(0x89), w(0x6f), w(0xb7), w(0x62), w(0x0e), \ + w(0xaa), w(0x18), w(0xbe), w(0x1b), w(0xfc), w(0x56), w(0x3e), w(0x4b), w(0xc6), \ + w(0xd2), w(0x79), w(0x20), w(0x9a), w(0xdb), w(0xc0), w(0xfe), w(0x78), w(0xcd), \ + w(0x5a), w(0xf4), w(0x1f), w(0xdd), w(0xa8), w(0x33), w(0x88), w(0x07), w(0xc7), \ + w(0x31), w(0xb1), w(0x12), w(0x10), w(0x59), w(0x27), w(0x80), w(0xec), w(0x5f), \ + w(0x60), w(0x51), w(0x7f), w(0xa9), w(0x19), w(0xb5), w(0x4a), w(0x0d), w(0x2d), \ + w(0xe5), w(0x7a), w(0x9f), w(0x93), w(0xc9), w(0x9c), w(0xef), w(0xa0), w(0xe0), \ + w(0x3b), w(0x4d), w(0xae), w(0x2a), w(0xf5), w(0xb0), w(0xc8), w(0xeb), w(0xbb), \ + w(0x3c), w(0x83), w(0x53), w(0x99), w(0x61), w(0x17), w(0x2b), w(0x04), w(0x7e), \ + w(0xba), w(0x77), w(0xd6), w(0x26), w(0xe1), w(0x69), w(0x14), w(0x63), w(0x55), \ + w(0x21), w(0x0c), w(0x7d) \ } -#define mm_data(w) \ - { /* basic data for forming finite field tables */ \ - w(0x00), w(0x01), w(0x02), w(0x03), w(0x04), w(0x05), w(0x06), w(0x07), w(0x08), w(0x09), w(0x0a), w(0x0b), \ - w(0x0c), w(0x0d), w(0x0e), w(0x0f), w(0x10), w(0x11), w(0x12), w(0x13), w(0x14), w(0x15), w(0x16), w(0x17), \ - w(0x18), w(0x19), w(0x1a), w(0x1b), w(0x1c), w(0x1d), w(0x1e), w(0x1f), w(0x20), w(0x21), w(0x22), w(0x23), \ - w(0x24), w(0x25), w(0x26), w(0x27), w(0x28), w(0x29), w(0x2a), w(0x2b), w(0x2c), w(0x2d), w(0x2e), w(0x2f), \ - w(0x30), w(0x31), w(0x32), w(0x33), w(0x34), w(0x35), w(0x36), w(0x37), w(0x38), w(0x39), w(0x3a), w(0x3b), \ - w(0x3c), w(0x3d), w(0x3e), w(0x3f), w(0x40), w(0x41), w(0x42), w(0x43), w(0x44), w(0x45), w(0x46), w(0x47), \ - w(0x48), w(0x49), w(0x4a), w(0x4b), w(0x4c), w(0x4d), w(0x4e), w(0x4f), w(0x50), w(0x51), w(0x52), w(0x53), \ - w(0x54), w(0x55), w(0x56), w(0x57), w(0x58), w(0x59), w(0x5a), w(0x5b), w(0x5c), w(0x5d), w(0x5e), w(0x5f), \ - w(0x60), w(0x61), w(0x62), w(0x63), w(0x64), w(0x65), w(0x66), w(0x67), w(0x68), w(0x69), w(0x6a), w(0x6b), \ - w(0x6c), w(0x6d), w(0x6e), w(0x6f), w(0x70), w(0x71), w(0x72), w(0x73), w(0x74), w(0x75), w(0x76), w(0x77), \ - w(0x78), w(0x79), w(0x7a), w(0x7b), w(0x7c), w(0x7d), w(0x7e), w(0x7f), w(0x80), w(0x81), w(0x82), w(0x83), \ - w(0x84), w(0x85), w(0x86), w(0x87), w(0x88), w(0x89), w(0x8a), w(0x8b), w(0x8c), w(0x8d), w(0x8e), w(0x8f), \ - w(0x90), w(0x91), w(0x92), w(0x93), w(0x94), w(0x95), w(0x96), w(0x97), w(0x98), w(0x99), w(0x9a), w(0x9b), \ - w(0x9c), w(0x9d), w(0x9e), w(0x9f), w(0xa0), w(0xa1), w(0xa2), w(0xa3), w(0xa4), w(0xa5), w(0xa6), w(0xa7), \ - w(0xa8), w(0xa9), w(0xaa), w(0xab), w(0xac), w(0xad), w(0xae), w(0xaf), w(0xb0), w(0xb1), w(0xb2), w(0xb3), \ - w(0xb4), w(0xb5), w(0xb6), w(0xb7), w(0xb8), w(0xb9), w(0xba), w(0xbb), w(0xbc), w(0xbd), w(0xbe), w(0xbf), \ - w(0xc0), w(0xc1), w(0xc2), w(0xc3), w(0xc4), w(0xc5), w(0xc6), w(0xc7), w(0xc8), w(0xc9), w(0xca), w(0xcb), \ - w(0xcc), w(0xcd), w(0xce), w(0xcf), w(0xd0), w(0xd1), w(0xd2), w(0xd3), w(0xd4), w(0xd5), w(0xd6), w(0xd7), \ - w(0xd8), w(0xd9), w(0xda), w(0xdb), w(0xdc), w(0xdd), w(0xde), w(0xdf), w(0xe0), w(0xe1), w(0xe2), w(0xe3), \ - w(0xe4), w(0xe5), w(0xe6), w(0xe7), w(0xe8), w(0xe9), w(0xea), w(0xeb), w(0xec), w(0xed), w(0xee), w(0xef), \ - w(0xf0), w(0xf1), w(0xf2), w(0xf3), w(0xf4), w(0xf5), w(0xf6), w(0xf7), w(0xf8), w(0xf9), w(0xfa), w(0xfb), \ - w(0xfc), w(0xfd), w(0xfe), w(0xff) \ +#define mm_data(w) \ + { /* basic data for forming finite field tables */ \ + w(0x00), w(0x01), w(0x02), w(0x03), w(0x04), w(0x05), w(0x06), w(0x07), w(0x08), w(0x09), \ + w(0x0a), w(0x0b), w(0x0c), w(0x0d), w(0x0e), w(0x0f), w(0x10), w(0x11), w(0x12), \ + w(0x13), w(0x14), w(0x15), w(0x16), w(0x17), w(0x18), w(0x19), w(0x1a), w(0x1b), \ + w(0x1c), w(0x1d), w(0x1e), w(0x1f), w(0x20), w(0x21), w(0x22), w(0x23), w(0x24), \ + w(0x25), w(0x26), w(0x27), w(0x28), w(0x29), w(0x2a), w(0x2b), w(0x2c), w(0x2d), \ + w(0x2e), w(0x2f), w(0x30), w(0x31), w(0x32), w(0x33), w(0x34), w(0x35), w(0x36), \ + w(0x37), w(0x38), w(0x39), w(0x3a), w(0x3b), w(0x3c), w(0x3d), w(0x3e), w(0x3f), \ + w(0x40), w(0x41), w(0x42), w(0x43), w(0x44), w(0x45), w(0x46), w(0x47), w(0x48), \ + w(0x49), w(0x4a), w(0x4b), w(0x4c), w(0x4d), w(0x4e), w(0x4f), w(0x50), w(0x51), \ + w(0x52), w(0x53), w(0x54), w(0x55), w(0x56), w(0x57), w(0x58), w(0x59), w(0x5a), \ + w(0x5b), w(0x5c), w(0x5d), w(0x5e), w(0x5f), w(0x60), w(0x61), w(0x62), w(0x63), \ + w(0x64), w(0x65), w(0x66), w(0x67), w(0x68), w(0x69), w(0x6a), w(0x6b), w(0x6c), \ + w(0x6d), w(0x6e), w(0x6f), w(0x70), w(0x71), w(0x72), w(0x73), w(0x74), w(0x75), \ + w(0x76), w(0x77), w(0x78), w(0x79), w(0x7a), w(0x7b), w(0x7c), w(0x7d), w(0x7e), \ + w(0x7f), w(0x80), w(0x81), w(0x82), w(0x83), w(0x84), w(0x85), w(0x86), w(0x87), \ + w(0x88), w(0x89), w(0x8a), w(0x8b), w(0x8c), w(0x8d), w(0x8e), w(0x8f), w(0x90), \ + w(0x91), w(0x92), w(0x93), w(0x94), w(0x95), w(0x96), w(0x97), w(0x98), w(0x99), \ + w(0x9a), w(0x9b), w(0x9c), w(0x9d), w(0x9e), w(0x9f), w(0xa0), w(0xa1), w(0xa2), \ + w(0xa3), w(0xa4), w(0xa5), w(0xa6), w(0xa7), w(0xa8), w(0xa9), w(0xaa), w(0xab), \ + w(0xac), w(0xad), w(0xae), w(0xaf), w(0xb0), w(0xb1), w(0xb2), w(0xb3), w(0xb4), \ + w(0xb5), w(0xb6), w(0xb7), w(0xb8), w(0xb9), w(0xba), w(0xbb), w(0xbc), w(0xbd), \ + w(0xbe), w(0xbf), w(0xc0), w(0xc1), w(0xc2), w(0xc3), w(0xc4), w(0xc5), w(0xc6), \ + w(0xc7), w(0xc8), w(0xc9), w(0xca), w(0xcb), w(0xcc), w(0xcd), w(0xce), w(0xcf), \ + w(0xd0), w(0xd1), w(0xd2), w(0xd3), w(0xd4), w(0xd5), w(0xd6), w(0xd7), w(0xd8), \ + w(0xd9), w(0xda), w(0xdb), w(0xdc), w(0xdd), w(0xde), w(0xdf), w(0xe0), w(0xe1), \ + w(0xe2), w(0xe3), w(0xe4), w(0xe5), w(0xe6), w(0xe7), w(0xe8), w(0xe9), w(0xea), \ + w(0xeb), w(0xec), w(0xed), w(0xee), w(0xef), w(0xf0), w(0xf1), w(0xf2), w(0xf3), \ + w(0xf4), w(0xf5), w(0xf6), w(0xf7), w(0xf8), w(0xf9), w(0xfa), w(0xfb), w(0xfc), \ + w(0xfd), w(0xfe), w(0xff) \ } static const uint_8t sbox[256] = sb_data(f1); @@ -207,10 +230,12 @@ static uint_8t hibit(const uint_8t x) { static uint_8t gf_inv(const uint_8t x) { uint_8t p1 = x, p2 = BPOLY, n1 = hibit(x), n2 = 0x80, v1 = 1, v2 = 0; - if (x < 2) return x; + if (x < 2) { + return x; + } for (;;) { - if (n1) + if (n1) { while (n2 >= n1) /* divide polynomial p2 by p1 */ { n2 /= n1; /* shift smaller polynomial left */ @@ -218,18 +243,20 @@ static uint_8t gf_inv(const uint_8t x) { v2 ^= (v1 * n2); /* shift accumulated value and */ n2 = hibit(p2); /* add into result */ } - else + } else { return v1; + } - if (n2) /* repeat with values swapped */ + if (n2) { /* repeat with values swapped */ while (n1 >= n2) { n1 /= n2; p1 ^= p2 * n1; v1 ^= v2 * n1; n1 = hibit(p1); } - else + } else { return v2; + } } } @@ -240,7 +267,8 @@ uint_8t fwd_affine(const uint_8t x) { w ^= (w << 1) ^ (w << 2) ^ (w << 3) ^ (w << 4); return 0x63 ^ ((w ^ (w >> 8)) & 0xff); #else - return 0x63 ^ x ^ (x << 1) ^ (x << 2) ^ (x << 3) ^ (x << 4) ^ (x >> 7) ^ (x >> 6) ^ (x >> 5) ^ (x >> 4); + return 0x63 ^ x ^ (x << 1) ^ (x << 2) ^ (x << 3) ^ (x << 4) ^ (x >> 7) ^ (x >> 6) ^ (x >> 5) ^ + (x >> 4); #endif } @@ -301,7 +329,9 @@ static void copy_block(void* d, const void* s) { } static void copy_block_nn(void* d, const void* s, uint_8t nn) { - while (nn--) *((uint_8t*)d)++ = *((uint_8t*)s)++; + while (nn--) { + *((uint_8t*)d)++ = *((uint_8t*)s)++; + } } #endif @@ -360,9 +390,7 @@ static void copy_and_key(void* d, const void* s, const void* k) { #endif } -static void add_round_key(uint_8t d[N_BLOCK], const uint_8t k[N_BLOCK]) { - xor_block(d, k); -} +static void add_round_key(uint_8t d[N_BLOCK], const uint_8t k[N_BLOCK]) { xor_block(d, k); } static void shift_sub_rows(uint_8t st[N_BLOCK]) { uint_8t tt; @@ -543,7 +571,8 @@ return_type aes_set_key(const unsigned char key[], length_type keylen, aes_conte /* Encrypt a single block of 16 bytes */ -return_type aes_encrypt(const unsigned char in[N_BLOCK], unsigned char out[N_BLOCK], const aes_context ctx[1]) { +return_type aes_encrypt(const unsigned char in[N_BLOCK], unsigned char out[N_BLOCK], + const aes_context ctx[1]) { if (ctx->rnd) { uint_8t s1[N_BLOCK], r; copy_and_key(s1, in, ctx->ksch); @@ -563,18 +592,21 @@ return_type aes_encrypt(const unsigned char in[N_BLOCK], unsigned char out[N_BLO #endif shift_sub_rows(s1); copy_and_key(out, s1, ctx->ksch + r * N_BLOCK); - } else + } else { return (return_type)-1; + } return 0; } /* CBC encrypt a number of blocks (input and return an IV) */ -return_type aes_cbc_encrypt( - const unsigned char* in, unsigned char* out, int n_block, unsigned char iv[N_BLOCK], const aes_context ctx[1]) { +return_type aes_cbc_encrypt(const unsigned char* in, unsigned char* out, int n_block, + unsigned char iv[N_BLOCK], const aes_context ctx[1]) { while (n_block--) { xor_block(iv, in); - if (aes_encrypt(iv, iv, ctx) != EXIT_SUCCESS) return EXIT_FAILURE; + if (aes_encrypt(iv, iv, ctx) != EXIT_SUCCESS) { + return EXIT_FAILURE; + } memcpy(out, iv, N_BLOCK); in += N_BLOCK; out += N_BLOCK; @@ -588,7 +620,8 @@ return_type aes_cbc_encrypt( /* Decrypt a single block of 16 bytes */ -return_type aes_decrypt(const unsigned char in[N_BLOCK], unsigned char out[N_BLOCK], const aes_context ctx[1]) { +return_type aes_decrypt(const unsigned char in[N_BLOCK], unsigned char out[N_BLOCK], + const aes_context ctx[1]) { if (ctx->rnd) { uint_8t s1[N_BLOCK], r; copy_and_key(s1, in, ctx->ksch + ctx->rnd * N_BLOCK); @@ -608,20 +641,23 @@ return_type aes_decrypt(const unsigned char in[N_BLOCK], unsigned char out[N_BLO } #endif copy_and_key(out, s1, ctx->ksch); - } else + } else { return (return_type)-1; + } return 0; } /* CBC decrypt a number of blocks (input and return an IV) */ -return_type aes_cbc_decrypt( - const unsigned char* in, unsigned char* out, int n_block, unsigned char iv[N_BLOCK], const aes_context ctx[1]) { +return_type aes_cbc_decrypt(const unsigned char* in, unsigned char* out, int n_block, + unsigned char iv[N_BLOCK], const aes_context ctx[1]) { while (n_block--) { uint_8t tmp[N_BLOCK]; memcpy(tmp, in, N_BLOCK); - if (aes_decrypt(in, out, ctx) != EXIT_SUCCESS) return EXIT_FAILURE; + if (aes_decrypt(in, out, ctx) != EXIT_SUCCESS) { + return EXIT_FAILURE; + } xor_block(out, iv); memcpy(iv, tmp, N_BLOCK); in += N_BLOCK; @@ -655,14 +691,13 @@ static void update_encrypt_key_128(uint_8t k[N_BLOCK], uint_8t* rc) { /* Encrypt a single block of 16 bytes with 'on the fly' 128 bit keying */ -void aes_encrypt_128( - const unsigned char in[N_BLOCK], - unsigned char out[N_BLOCK], - const unsigned char key[N_BLOCK], - unsigned char o_key[N_BLOCK]) { +void aes_encrypt_128(const unsigned char in[N_BLOCK], unsigned char out[N_BLOCK], + const unsigned char key[N_BLOCK], unsigned char o_key[N_BLOCK]) { uint_8t s1[N_BLOCK], r, rc = 1; - if (o_key != key) block_copy(o_key, key); + if (o_key != key) { + block_copy(o_key, key); + } copy_and_key(s1, in, o_key); for (r = 1; r < 10; ++r) @@ -710,13 +745,12 @@ static void update_decrypt_key_128(uint_8t k[N_BLOCK], uint_8t* rc) { /* Decrypt a single block of 16 bytes with 'on the fly' 128 bit keying */ -void aes_decrypt_128( - const unsigned char in[N_BLOCK], - unsigned char out[N_BLOCK], - const unsigned char key[N_BLOCK], - unsigned char o_key[N_BLOCK]) { +void aes_decrypt_128(const unsigned char in[N_BLOCK], unsigned char out[N_BLOCK], + const unsigned char key[N_BLOCK], unsigned char o_key[N_BLOCK]) { uint_8t s1[N_BLOCK], r, rc = 0x6c; - if (o_key != key) block_copy(o_key, key); + if (o_key != key) { + block_copy(o_key, key); + } copy_and_key(s1, in, o_key); inv_shift_sub_rows(s1); @@ -777,11 +811,8 @@ static void update_encrypt_key_256(uint_8t k[2 * N_BLOCK], uint_8t* rc) { /* Encrypt a single block of 16 bytes with 'on the fly' 256 bit keying */ -void aes_encrypt_256( - const unsigned char in[N_BLOCK], - unsigned char out[N_BLOCK], - const unsigned char key[2 * N_BLOCK], - unsigned char o_key[2 * N_BLOCK]) { +void aes_encrypt_256(const unsigned char in[N_BLOCK], unsigned char out[N_BLOCK], + const unsigned char key[2 * N_BLOCK], unsigned char o_key[2 * N_BLOCK]) { uint_8t s1[N_BLOCK], r, rc = 1; if (o_key != key) { block_copy(o_key, key); @@ -793,9 +824,9 @@ void aes_encrypt_256( #if defined(VERSION_1) { mix_sub_columns(s1); - if (r & 1) + if (r & 1) { add_round_key(s1, o_key + 16); - else { + } else { update_encrypt_key_256(o_key, &rc); add_round_key(s1, o_key); } @@ -804,9 +835,9 @@ void aes_encrypt_256( { uint_8t s2[N_BLOCK]; mix_sub_columns(s2, s1); - if (r & 1) + if (r & 1) { copy_and_key(s1, s2, o_key + 16); - else { + } else { update_encrypt_key_256(o_key, &rc); copy_and_key(s1, s2, o_key); } @@ -856,11 +887,8 @@ static void update_decrypt_key_256(uint_8t k[2 * N_BLOCK], uint_8t* rc) { /* Decrypt a single block of 16 bytes with 'on the fly' 256 bit keying */ -void aes_decrypt_256( - const unsigned char in[N_BLOCK], - unsigned char out[N_BLOCK], - const unsigned char key[2 * N_BLOCK], - unsigned char o_key[2 * N_BLOCK]) { +void aes_decrypt_256(const unsigned char in[N_BLOCK], unsigned char out[N_BLOCK], + const unsigned char key[2 * N_BLOCK], unsigned char o_key[2 * N_BLOCK]) { uint_8t s1[N_BLOCK], r, rc = 0x80; if (o_key != key) { @@ -874,21 +902,23 @@ void aes_decrypt_256( for (r = 14; --r;) #if defined(VERSION_1) { - if ((r & 1)) { + if (r & 1) { update_decrypt_key_256(o_key, &rc); add_round_key(s1, o_key + 16); - } else + } else { add_round_key(s1, o_key); + } inv_mix_sub_columns(s1); } #else { uint_8t s2[N_BLOCK]; - if ((r & 1)) { + if (r & 1) { update_decrypt_key_256(o_key, &rc); copy_and_key(s2, s1, o_key + 16); - } else + } else { copy_and_key(s2, s1, o_key); + } inv_mix_sub_columns(s1, s2); } #endif diff --git a/system/gd/crypto_toolbox/aes.h b/system/gd/crypto_toolbox/aes.h index 6d59743b477..877f98bbd5d 100644 --- a/system/gd/crypto_toolbox/aes.h +++ b/system/gd/crypto_toolbox/aes.h @@ -85,18 +85,20 @@ return_type aes_set_key(const unsigned char key[], length_type keylen, aes_conte #if defined(AES_ENC_PREKEYED) -return_type aes_encrypt(const unsigned char in[N_BLOCK], unsigned char out[N_BLOCK], const aes_context ctx[1]); +return_type aes_encrypt(const unsigned char in[N_BLOCK], unsigned char out[N_BLOCK], + const aes_context ctx[1]); -return_type aes_cbc_encrypt( - const unsigned char* in, unsigned char* out, int n_block, unsigned char iv[N_BLOCK], const aes_context ctx[1]); +return_type aes_cbc_encrypt(const unsigned char* in, unsigned char* out, int n_block, + unsigned char iv[N_BLOCK], const aes_context ctx[1]); #endif #if defined(AES_DEC_PREKEYED) -return_type aes_decrypt(const unsigned char in[N_BLOCK], unsigned char out[N_BLOCK], const aes_context ctx[1]); +return_type aes_decrypt(const unsigned char in[N_BLOCK], unsigned char out[N_BLOCK], + const aes_context ctx[1]); -return_type aes_cbc_decrypt( - const unsigned char* in, unsigned char* out, int n_block, unsigned char iv[N_BLOCK], const aes_context ctx[1]); +return_type aes_cbc_decrypt(const unsigned char* in, unsigned char* out, int n_block, + unsigned char iv[N_BLOCK], const aes_context ctx[1]); #endif /* The following calls are for 'on the fly' keying. In this case the @@ -120,35 +122,23 @@ return_type aes_cbc_decrypt( */ #if defined(AES_ENC_128_OTFK) -void aes_encrypt_128( - const unsigned char in[N_BLOCK], - unsigned char out[N_BLOCK], - const unsigned char key[N_BLOCK], - uint_8t o_key[N_BLOCK]); +void aes_encrypt_128(const unsigned char in[N_BLOCK], unsigned char out[N_BLOCK], + const unsigned char key[N_BLOCK], uint_8t o_key[N_BLOCK]); #endif #if defined(AES_DEC_128_OTFK) -void aes_decrypt_128( - const unsigned char in[N_BLOCK], - unsigned char out[N_BLOCK], - const unsigned char key[N_BLOCK], - unsigned char o_key[N_BLOCK]); +void aes_decrypt_128(const unsigned char in[N_BLOCK], unsigned char out[N_BLOCK], + const unsigned char key[N_BLOCK], unsigned char o_key[N_BLOCK]); #endif #if defined(AES_ENC_256_OTFK) -void aes_encrypt_256( - const unsigned char in[N_BLOCK], - unsigned char out[N_BLOCK], - const unsigned char key[2 * N_BLOCK], - unsigned char o_key[2 * N_BLOCK]); +void aes_encrypt_256(const unsigned char in[N_BLOCK], unsigned char out[N_BLOCK], + const unsigned char key[2 * N_BLOCK], unsigned char o_key[2 * N_BLOCK]); #endif #if defined(AES_DEC_256_OTFK) -void aes_decrypt_256( - const unsigned char in[N_BLOCK], - unsigned char out[N_BLOCK], - const unsigned char key[2 * N_BLOCK], - unsigned char o_key[2 * N_BLOCK]); +void aes_decrypt_256(const unsigned char in[N_BLOCK], unsigned char out[N_BLOCK], + const unsigned char key[2 * N_BLOCK], unsigned char o_key[2 * N_BLOCK]); #endif #endif diff --git a/system/gd/crypto_toolbox/aes_cmac.cc b/system/gd/crypto_toolbox/aes_cmac.cc index d7ecde62c74..be3fc1e166b 100644 --- a/system/gd/crypto_toolbox/aes_cmac.cc +++ b/system/gd/crypto_toolbox/aes_cmac.cc @@ -47,7 +47,8 @@ typedef struct { thread_local tCMAC_CB cmac_cb; /* Rb for AES-128 as block cipher, LSB as [0] */ -Octet16 const_Rb{0x87, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; +Octet16 const_Rb{0x87, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; /** utility function to do an biteise exclusive-OR of two bit strings of the * length of kOctet16Length. Result is stored in first argument. @@ -85,7 +86,9 @@ Octet16 aes_128(const Octet16& key, const Octet16& message) { static void padding(Octet16* dest, uint8_t length) { uint8_t i, *p = dest->data(); /* original last block */ - for (i = length; i < kOctet16Length; i++) p[kOctet16Length - i - 1] = (i == length) ? 0x80 : 0; + for (i = length; i < kOctet16Length; i++) { + p[kOctet16Length - i - 1] = (i == length) ? 0x80 : 0; + } } /** utility function to left shift one bit for a 128 bits value. */ @@ -179,7 +182,9 @@ Octet16 aes_cmac(const Octet16& key, const uint8_t* input, uint16_t length) { /* n is number of rounds */ uint16_t n = (length + kOctet16Length - 1) / kOctet16Length; - if (n == 0) n = 1; + if (n == 0) { + n = 1; + } len = n * kOctet16Length; // log::verbose("AES128_CMAC started, allocate buffer size={}", len); diff --git a/system/gd/crypto_toolbox/crypto_toolbox.cc b/system/gd/crypto_toolbox/crypto_toolbox.cc index 6b78ec84f73..286b208ed4c 100644 --- a/system/gd/crypto_toolbox/crypto_toolbox.cc +++ b/system/gd/crypto_toolbox/crypto_toolbox.cc @@ -33,13 +33,11 @@ Octet16 h6(const Octet16& w, std::array keyid) { return aes_cmac(w, keyid.data(), keyid.size()); } -Octet16 h7(const Octet16& salt, const Octet16& w) { - return aes_cmac(salt, w.data(), w.size()); -} +Octet16 h7(const Octet16& salt, const Octet16& w) { return aes_cmac(salt, w.data(), w.size()); } Octet16 f4(const uint8_t* u, const uint8_t* v, const Octet16& x, uint8_t z) { constexpr size_t msg_len = - kOctet32Length /* U size */ + kOctet32Length /* V size */ + 1 /* Z size */; + kOctet32Length /* U size */ + kOctet32Length /* V size */ + 1 /* Z size */; #if 0 log::verbose("U={}, V={}, X={}, Z={:x}", HexEncode(u, kOctet32Length), @@ -55,15 +53,9 @@ Octet16 f4(const uint8_t* u, const uint8_t* v, const Octet16& x, uint8_t z) { } /** helper for f5 */ -static Octet16 calculate_mac_key_or_ltk( - const Octet16& t, - uint8_t counter, - uint8_t* key_id, - const Octet16& n1, - const Octet16& n2, - uint8_t* a1, - uint8_t* a2, - uint8_t* length) { +static Octet16 calculate_mac_key_or_ltk(const Octet16& t, uint8_t counter, uint8_t* key_id, + const Octet16& n1, const Octet16& n2, uint8_t* a1, + uint8_t* a2, uint8_t* length) { constexpr size_t msg_len = 1 /* Counter size */ + 4 /* keyID size */ + kOctet16Length /* N1 size */ + kOctet16Length /* N2 size */ + 7 /* A1 size*/ + 7 /* A2 size*/ + 2 /* Length size */; @@ -81,21 +73,16 @@ static Octet16 calculate_mac_key_or_ltk( return aes_cmac(t, msg.data(), msg.size()); } -void f5( - const uint8_t* w, - const Octet16& n1, - const Octet16& n2, - uint8_t* a1, - uint8_t* a2, - Octet16* mac_key, - Octet16* ltk) { +void f5(const uint8_t* w, const Octet16& n1, const Octet16& n2, uint8_t* a1, uint8_t* a2, + Octet16* mac_key, Octet16* ltk) { #if 0 log::verbose("W={}, N1={}, N2={}, A1={}, A2={}", HexEncode(w, kOctet32Length), HexEncode(n1.data(), n1.size()), HexEncode(n2.data(), n2.size()), HexEncode(a1, 7), HexEncode(a2, 7)); #endif - const Octet16 salt{0xBE, 0x83, 0x60, 0x5A, 0xDB, 0x0B, 0x37, 0x60, 0x38, 0xA5, 0xF5, 0xAA, 0x91, 0x83, 0x88, 0x6C}; + const Octet16 salt{0xBE, 0x83, 0x60, 0x5A, 0xDB, 0x0B, 0x37, 0x60, + 0x38, 0xA5, 0xF5, 0xAA, 0x91, 0x83, 0x88, 0x6C}; Octet16 t = aes_cmac(salt, w, kOctet32Length); #if 0 @@ -115,8 +102,8 @@ void f5( #endif } -Octet16 -f6(const Octet16& w, const Octet16& n1, const Octet16& n2, const Octet16& r, uint8_t* iocap, uint8_t* a1, uint8_t* a2) { +Octet16 f6(const Octet16& w, const Octet16& n1, const Octet16& n2, const Octet16& r, uint8_t* iocap, + uint8_t* a1, uint8_t* a2) { const uint8_t msg_len = kOctet16Length /* N1 size */ + kOctet16Length /* N2 size */ + kOctet16Length /* R size */ + 3 /* IOcap size */ + 7 /* A1 size*/ + 7 /* A2 size*/; @@ -163,8 +150,8 @@ uint32_t g2(const uint8_t* u, const uint8_t* v, const Octet16& x, const Octet16& Octet16 ltk_to_link_key(const Octet16& ltk, bool use_h7) { Octet16 ilk; /* intermidiate link key */ if (use_h7) { - constexpr Octet16 salt{ - 0x31, 0x70, 0x6D, 0x74, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + constexpr Octet16 salt{0x31, 0x70, 0x6D, 0x74, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; ilk = h7(salt, ltk); } else { /* "tmp1" mapping to extended ASCII, little endian*/ @@ -180,8 +167,8 @@ Octet16 ltk_to_link_key(const Octet16& ltk, bool use_h7) { Octet16 link_key_to_ltk(const Octet16& link_key, bool use_h7) { Octet16 iltk; /* intermidiate long term key */ if (use_h7) { - constexpr Octet16 salt{ - 0x32, 0x70, 0x6D, 0x74, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + constexpr Octet16 salt{0x32, 0x70, 0x6D, 0x74, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; iltk = h7(salt, link_key); } else { /* "tmp2" mapping to extended ASCII, little endian */ @@ -194,15 +181,8 @@ Octet16 link_key_to_ltk(const Octet16& link_key, bool use_h7) { return h6(iltk, keyID_brle); } -Octet16 c1( - const Octet16& k, - const Octet16& r, - const uint8_t* preq, - const uint8_t* pres, - const uint8_t iat, - const uint8_t* ia, - const uint8_t rat, - const uint8_t* ra) { +Octet16 c1(const Octet16& k, const Octet16& r, const uint8_t* preq, const uint8_t* pres, + const uint8_t iat, const uint8_t* ia, const uint8_t rat, const uint8_t* ra) { Octet16 p1; auto it = p1.begin(); it = std::copy(&iat, &iat + 1, it); diff --git a/system/gd/crypto_toolbox/crypto_toolbox.h b/system/gd/crypto_toolbox/crypto_toolbox.h index eff79f0b324..dafbdb99342 100644 --- a/system/gd/crypto_toolbox/crypto_toolbox.h +++ b/system/gd/crypto_toolbox/crypto_toolbox.h @@ -24,68 +24,42 @@ namespace crypto_toolbox { -bluetooth::hci::Octet16 c1( - const bluetooth::hci::Octet16& k, - const bluetooth::hci::Octet16& r, - const uint8_t* pres, - const uint8_t* preq, - const uint8_t iat, - const uint8_t* ia, - const uint8_t rat, - const uint8_t* ra); -bluetooth::hci::Octet16 s1( - const bluetooth::hci::Octet16& k, - const bluetooth::hci::Octet16& r1, - const bluetooth::hci::Octet16& r2); +bluetooth::hci::Octet16 c1(const bluetooth::hci::Octet16& k, const bluetooth::hci::Octet16& r, + const uint8_t* pres, const uint8_t* preq, const uint8_t iat, + const uint8_t* ia, const uint8_t rat, const uint8_t* ra); +bluetooth::hci::Octet16 s1(const bluetooth::hci::Octet16& k, const bluetooth::hci::Octet16& r1, + const bluetooth::hci::Octet16& r2); -bluetooth::hci::Octet16 aes_128( - const bluetooth::hci::Octet16& key, const bluetooth::hci::Octet16& message); -bluetooth::hci::Octet16 aes_cmac( - const bluetooth::hci::Octet16& key, const uint8_t* message, uint16_t length); -bluetooth::hci::Octet16 f4( - const uint8_t* u, const uint8_t* v, const bluetooth::hci::Octet16& x, uint8_t z); -void f5( - const uint8_t* w, - const bluetooth::hci::Octet16& n1, - const bluetooth::hci::Octet16& n2, - uint8_t* a1, - uint8_t* a2, - bluetooth::hci::Octet16* mac_key, - bluetooth::hci::Octet16* ltk); -bluetooth::hci::Octet16 f6( - const bluetooth::hci::Octet16& w, - const bluetooth::hci::Octet16& n1, - const bluetooth::hci::Octet16& n2, - const bluetooth::hci::Octet16& r, - uint8_t* iocap, - uint8_t* a1, - uint8_t* a2); +bluetooth::hci::Octet16 aes_128(const bluetooth::hci::Octet16& key, + const bluetooth::hci::Octet16& message); +bluetooth::hci::Octet16 aes_cmac(const bluetooth::hci::Octet16& key, const uint8_t* message, + uint16_t length); +bluetooth::hci::Octet16 f4(const uint8_t* u, const uint8_t* v, const bluetooth::hci::Octet16& x, + uint8_t z); +void f5(const uint8_t* w, const bluetooth::hci::Octet16& n1, const bluetooth::hci::Octet16& n2, + uint8_t* a1, uint8_t* a2, bluetooth::hci::Octet16* mac_key, bluetooth::hci::Octet16* ltk); +bluetooth::hci::Octet16 f6(const bluetooth::hci::Octet16& w, const bluetooth::hci::Octet16& n1, + const bluetooth::hci::Octet16& n2, const bluetooth::hci::Octet16& r, + uint8_t* iocap, uint8_t* a1, uint8_t* a2); bluetooth::hci::Octet16 h6(const bluetooth::hci::Octet16& w, std::array keyid); bluetooth::hci::Octet16 h7(const bluetooth::hci::Octet16& salt, const bluetooth::hci::Octet16& w); -uint32_t g2( - const uint8_t* u, - const uint8_t* v, - const bluetooth::hci::Octet16& x, - const bluetooth::hci::Octet16& y); +uint32_t g2(const uint8_t* u, const uint8_t* v, const bluetooth::hci::Octet16& x, + const bluetooth::hci::Octet16& y); bluetooth::hci::Octet16 ltk_to_link_key(const bluetooth::hci::Octet16& ltk, bool use_h7); bluetooth::hci::Octet16 link_key_to_ltk(const bluetooth::hci::Octet16& link_key, bool use_h7); -// |tlen| - lenth of mac desired +// |tlen| - length of mac desired // |p_signature| - data pointer to where signed data to be stored, tlen long. -inline void aes_cmac( - const bluetooth::hci::Octet16& key, - const uint8_t* message, - uint16_t length, - uint16_t tlen, - uint8_t* p_signature) { +inline void aes_cmac(const bluetooth::hci::Octet16& key, const uint8_t* message, uint16_t length, + uint16_t tlen, uint8_t* p_signature) { bluetooth::hci::Octet16 signature = aes_cmac(key, message, length); uint8_t* p_mac = signature.data() + (bluetooth::hci::kOctet16Length - tlen); memcpy(p_signature, p_mac, tlen); } -inline bluetooth::hci::Octet16 aes_cmac( - const bluetooth::hci::Octet16& key, const bluetooth::hci::Octet16& message) { +inline bluetooth::hci::Octet16 aes_cmac(const bluetooth::hci::Octet16& key, + const bluetooth::hci::Octet16& message) { return aes_cmac(key, message.data(), message.size()); } diff --git a/system/gd/crypto_toolbox/crypto_toolbox_test.cc b/system/gd/crypto_toolbox/crypto_toolbox_test.cc index e438ccca525..c3d081e709c 100644 --- a/system/gd/crypto_toolbox/crypto_toolbox_test.cc +++ b/system/gd/crypto_toolbox/crypto_toolbox_test.cc @@ -32,12 +32,14 @@ using bluetooth::hci::Octet16; // BT Spec 5.0 | Vol 3, Part H D.1 TEST(CryptoToolboxTest, bt_spec_test_d_1_test) { - uint8_t k[] = {0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c}; + uint8_t k[] = {0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, + 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c}; - uint8_t m[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + uint8_t m[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; - uint8_t aes_cmac_k_m[] = { - 0x7d, 0xf7, 0x6b, 0x0c, 0x1a, 0xb8, 0x99, 0xb3, 0x3e, 0x42, 0xf0, 0x47, 0xb9, 0x1b, 0x54, 0x6f}; + uint8_t aes_cmac_k_m[] = {0x7d, 0xf7, 0x6b, 0x0c, 0x1a, 0xb8, 0x99, 0xb3, + 0x3e, 0x42, 0xf0, 0x47, 0xb9, 0x1b, 0x54, 0x6f}; uint8_t output[16]; aes_context ctx; @@ -54,9 +56,11 @@ TEST(CryptoToolboxTest, bt_spec_test_d_1_test) { // BT Spec 5.0 | Vol 3, Part H D.1.1 TEST(CryptoToolboxTest, bt_spec_example_d_1_1_test) { - Octet16 k{0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c}; + Octet16 k{0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, + 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c}; - Octet16 aes_cmac_k_m{0xbb, 0x1d, 0x69, 0x29, 0xe9, 0x59, 0x37, 0x28, 0x7f, 0xa3, 0x7d, 0x12, 0x9b, 0x75, 0x67, 0x46}; + Octet16 aes_cmac_k_m{0xbb, 0x1d, 0x69, 0x29, 0xe9, 0x59, 0x37, 0x28, + 0x7f, 0xa3, 0x7d, 0x12, 0x9b, 0x75, 0x67, 0x46}; // algorithm expect all input to be in little endian format, so reverse std::reverse(std::begin(k), std::end(k)); @@ -73,11 +77,14 @@ TEST(CryptoToolboxTest, bt_spec_example_d_1_1_test) { // BT Spec 5.0 | Vol 3, Part H D.1.2 TEST(CryptoToolboxTest, bt_spec_example_d_1_2_test) { - Octet16 k{0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c}; + Octet16 k{0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, + 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c}; - Octet16 m = {0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96, 0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93, 0x17, 0x2a}; + Octet16 m = {0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96, + 0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93, 0x17, 0x2a}; - Octet16 aes_cmac_k_m{0x07, 0x0a, 0x16, 0xb4, 0x6b, 0x4d, 0x41, 0x44, 0xf7, 0x9b, 0xdd, 0x9d, 0xd0, 0x4a, 0x28, 0x7c}; + Octet16 aes_cmac_k_m{0x07, 0x0a, 0x16, 0xb4, 0x6b, 0x4d, 0x41, 0x44, + 0xf7, 0x9b, 0xdd, 0x9d, 0xd0, 0x4a, 0x28, 0x7c}; // algorithm expect all input to be in little endian format, so reverse std::reverse(std::begin(k), std::end(k)); @@ -96,13 +103,15 @@ TEST(CryptoToolboxTest, bt_spec_example_d_1_2_test) { // BT Spec 5.0 | Vol 3, Part H D.1.3 TEST(CryptoToolboxTest, bt_spec_example_d_1_3_test) { - Octet16 k{0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c}; + Octet16 k{0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, + 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c}; uint8_t m[] = {0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96, 0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93, 0x17, 0x2a, 0xae, 0x2d, 0x8a, 0x57, 0x1e, 0x03, 0xac, 0x9c, 0x9e, 0xb7, 0x6f, 0xac, 0x45, 0xaf, 0x8e, 0x51, 0x30, 0xc8, 0x1c, 0x46, 0xa3, 0x5c, 0xe4, 0x11}; - Octet16 aes_cmac_k_m{0xdf, 0xa6, 0x67, 0x47, 0xde, 0x9a, 0xe6, 0x30, 0x30, 0xca, 0x32, 0x61, 0x14, 0x97, 0xc8, 0x27}; + Octet16 aes_cmac_k_m{0xdf, 0xa6, 0x67, 0x47, 0xde, 0x9a, 0xe6, 0x30, + 0x30, 0xca, 0x32, 0x61, 0x14, 0x97, 0xc8, 0x27}; // algorithm expect all input to be in little endian format, so reverse std::reverse(std::begin(k), std::end(k)); @@ -115,14 +124,17 @@ TEST(CryptoToolboxTest, bt_spec_example_d_1_3_test) { // BT Spec 5.0 | Vol 3, Part H D.1.4 TEST(CryptoToolboxTest, bt_spec_example_d_1_4_test) { - Octet16 k{0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c}; + Octet16 k{0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, + 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c}; - uint8_t m[] = {0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96, 0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93, 0x17, 0x2a, - 0xae, 0x2d, 0x8a, 0x57, 0x1e, 0x03, 0xac, 0x9c, 0x9e, 0xb7, 0x6f, 0xac, 0x45, 0xaf, 0x8e, 0x51, - 0x30, 0xc8, 0x1c, 0x46, 0xa3, 0x5c, 0xe4, 0x11, 0xe5, 0xfb, 0xc1, 0x19, 0x1a, 0x0a, 0x52, 0xef, - 0xf6, 0x9f, 0x24, 0x45, 0xdf, 0x4f, 0x9b, 0x17, 0xad, 0x2b, 0x41, 0x7b, 0xe6, 0x6c, 0x37, 0x10}; + uint8_t m[] = {0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96, 0xe9, 0x3d, 0x7e, 0x11, 0x73, + 0x93, 0x17, 0x2a, 0xae, 0x2d, 0x8a, 0x57, 0x1e, 0x03, 0xac, 0x9c, 0x9e, 0xb7, + 0x6f, 0xac, 0x45, 0xaf, 0x8e, 0x51, 0x30, 0xc8, 0x1c, 0x46, 0xa3, 0x5c, 0xe4, + 0x11, 0xe5, 0xfb, 0xc1, 0x19, 0x1a, 0x0a, 0x52, 0xef, 0xf6, 0x9f, 0x24, 0x45, + 0xdf, 0x4f, 0x9b, 0x17, 0xad, 0x2b, 0x41, 0x7b, 0xe6, 0x6c, 0x37, 0x10}; - Octet16 aes_cmac_k_m{0x51, 0xf0, 0xbe, 0xbf, 0x7e, 0x3b, 0x9d, 0x92, 0xfc, 0x49, 0x74, 0x17, 0x79, 0x36, 0x3c, 0xfe}; + Octet16 aes_cmac_k_m{0x51, 0xf0, 0xbe, 0xbf, 0x7e, 0x3b, 0x9d, 0x92, + 0xfc, 0x49, 0x74, 0x17, 0x79, 0x36, 0x3c, 0xfe}; // algorithm expect all input to be in little endian format, so reverse std::reverse(std::begin(k), std::end(k)); @@ -142,10 +154,12 @@ TEST(CryptoToolboxTest, bt_spec_example_d_2_test) { std::vector v{0x55, 0x18, 0x8b, 0x3d, 0x32, 0xf6, 0xbb, 0x9a, 0x90, 0x0a, 0xfc, 0xfb, 0xee, 0xd4, 0xe7, 0x2a, 0x59, 0xcb, 0x9a, 0xc2, 0xf1, 0x9d, 0x7c, 0xfb, 0x6b, 0x4f, 0xdd, 0x49, 0xf4, 0x7f, 0xc5, 0xfd}; - Octet16 x{0xd5, 0xcb, 0x84, 0x54, 0xd1, 0x77, 0x73, 0x3e, 0xff, 0xff, 0xb2, 0xec, 0x71, 0x2b, 0xae, 0xab}; + Octet16 x{0xd5, 0xcb, 0x84, 0x54, 0xd1, 0x77, 0x73, 0x3e, + 0xff, 0xff, 0xb2, 0xec, 0x71, 0x2b, 0xae, 0xab}; uint8_t z = 0x00; - Octet16 aes_cmac_k_m{0xf2, 0xc9, 0x16, 0xf1, 0x07, 0xa9, 0xbd, 0x1c, 0xf1, 0xed, 0xa1, 0xbe, 0xa9, 0x74, 0x87, 0x2d}; + Octet16 aes_cmac_k_m{0xf2, 0xc9, 0x16, 0xf1, 0x07, 0xa9, 0xbd, 0x1c, + 0xf1, 0xed, 0xa1, 0xbe, 0xa9, 0x74, 0x87, 0x2d}; // algorithm expect all input to be in little endian format, so reverse std::reverse(std::begin(u), std::end(u)); @@ -163,14 +177,17 @@ TEST(CryptoToolboxTest, bt_spec_example_d_3_test) { std::array dhkey_w{0xec, 0x02, 0x34, 0xa3, 0x57, 0xc8, 0xad, 0x05, 0x34, 0x10, 0x10, 0xa6, 0x0a, 0x39, 0x7d, 0x9b, 0x99, 0x79, 0x6b, 0x13, 0xb4, 0xf8, 0x66, 0xf1, 0x86, 0x8d, 0x34, 0xf3, 0x73, 0xbf, 0xa6, 0x98}; - Octet16 n1{0xd5, 0xcb, 0x84, 0x54, 0xd1, 0x77, 0x73, 0x3e, 0xff, 0xff, 0xb2, 0xec, 0x71, 0x2b, 0xae, 0xab}; - Octet16 n2{0xa6, 0xe8, 0xe7, 0xcc, 0x25, 0xa7, 0x5f, 0x6e, 0x21, 0x65, 0x83, 0xf7, 0xff, 0x3d, 0xc4, 0xcf}; + Octet16 n1{0xd5, 0xcb, 0x84, 0x54, 0xd1, 0x77, 0x73, 0x3e, + 0xff, 0xff, 0xb2, 0xec, 0x71, 0x2b, 0xae, 0xab}; + Octet16 n2{0xa6, 0xe8, 0xe7, 0xcc, 0x25, 0xa7, 0x5f, 0x6e, + 0x21, 0x65, 0x83, 0xf7, 0xff, 0x3d, 0xc4, 0xcf}; std::array a1{0x00, 0x56, 0x12, 0x37, 0x37, 0xbf, 0xce}; std::array a2{0x00, 0xa7, 0x13, 0x70, 0x2d, 0xcf, 0xc1}; - Octet16 expected_ltk{0x69, 0x86, 0x79, 0x11, 0x69, 0xd7, 0xcd, 0x23, 0x98, 0x05, 0x22, 0xb5, 0x94, 0x75, 0x0a, 0x38}; - Octet16 expected_mac_key{ - 0x29, 0x65, 0xf1, 0x76, 0xa1, 0x08, 0x4a, 0x02, 0xfd, 0x3f, 0x6a, 0x20, 0xce, 0x63, 0x6e, 0x20}; + Octet16 expected_ltk{0x69, 0x86, 0x79, 0x11, 0x69, 0xd7, 0xcd, 0x23, + 0x98, 0x05, 0x22, 0xb5, 0x94, 0x75, 0x0a, 0x38}; + Octet16 expected_mac_key{0x29, 0x65, 0xf1, 0x76, 0xa1, 0x08, 0x4a, 0x02, + 0xfd, 0x3f, 0x6a, 0x20, 0xce, 0x63, 0x6e, 0x20}; // algorithm expect all input to be in little endian format, so reverse std::reverse(std::begin(dhkey_w), std::end(dhkey_w)); @@ -190,17 +207,21 @@ TEST(CryptoToolboxTest, bt_spec_example_d_3_test) { // BT Spec 5.0 | Vol 3, Part H D.4 TEST(CryptoToolboxTest, bt_spec_example_d_4_test) { - Octet16 n1{0xd5, 0xcb, 0x84, 0x54, 0xd1, 0x77, 0x73, 0x3e, 0xff, 0xff, 0xb2, 0xec, 0x71, 0x2b, 0xae, 0xab}; - Octet16 n2{0xa6, 0xe8, 0xe7, 0xcc, 0x25, 0xa7, 0x5f, 0x6e, 0x21, 0x65, 0x83, 0xf7, 0xff, 0x3d, 0xc4, 0xcf}; - Octet16 r{0x12, 0xa3, 0x34, 0x3b, 0xb4, 0x53, 0xbb, 0x54, 0x08, 0xda, 0x42, 0xd2, 0x0c, 0x2d, 0x0f, 0xc8}; + Octet16 n1{0xd5, 0xcb, 0x84, 0x54, 0xd1, 0x77, 0x73, 0x3e, + 0xff, 0xff, 0xb2, 0xec, 0x71, 0x2b, 0xae, 0xab}; + Octet16 n2{0xa6, 0xe8, 0xe7, 0xcc, 0x25, 0xa7, 0x5f, 0x6e, + 0x21, 0x65, 0x83, 0xf7, 0xff, 0x3d, 0xc4, 0xcf}; + Octet16 r{0x12, 0xa3, 0x34, 0x3b, 0xb4, 0x53, 0xbb, 0x54, + 0x08, 0xda, 0x42, 0xd2, 0x0c, 0x2d, 0x0f, 0xc8}; std::vector IOcap{0x01, 0x01, 0x02}; std::vector a1{0x00, 0x56, 0x12, 0x37, 0x37, 0xbf, 0xce}; std::vector a2{0x00, 0xa7, 0x13, 0x70, 0x2d, 0xcf, 0xc1}; - Octet16 MacKey{0x29, 0x65, 0xf1, 0x76, 0xa1, 0x08, 0x4a, 0x02, 0xfd, 0x3f, 0x6a, 0x20, 0xce, 0x63, 0x6e, 0x20}; + Octet16 MacKey{0x29, 0x65, 0xf1, 0x76, 0xa1, 0x08, 0x4a, 0x02, + 0xfd, 0x3f, 0x6a, 0x20, 0xce, 0x63, 0x6e, 0x20}; - Octet16 expected_aes_cmac{ - 0xe3, 0xc4, 0x73, 0x98, 0x9c, 0xd0, 0xe8, 0xc5, 0xd2, 0x6c, 0x0b, 0x09, 0xda, 0x95, 0x8f, 0x61}; + Octet16 expected_aes_cmac{0xe3, 0xc4, 0x73, 0x98, 0x9c, 0xd0, 0xe8, 0xc5, + 0xd2, 0x6c, 0x0b, 0x09, 0xda, 0x95, 0x8f, 0x61}; // algorithm expect all input to be in little endian format, so reverse std::reverse(std::begin(n1), std::end(n1)); @@ -226,8 +247,10 @@ TEST(CryptoToolboxTest, bt_spec_example_d_5_test) { 0xfb, 0xee, 0xd4, 0xe7, 0x2a, 0x59, 0xcb, 0x9a, 0xc2, 0xf1, 0x9d, 0x7c, 0xfb, 0x6b, 0x4f, 0xdd, 0x49, 0xf4, 0x7f, 0xc5, 0xfd}; - Octet16 x{0xd5, 0xcb, 0x84, 0x54, 0xd1, 0x77, 0x73, 0x3e, 0xff, 0xff, 0xb2, 0xec, 0x71, 0x2b, 0xae, 0xab}; - Octet16 y{0xa6, 0xe8, 0xe7, 0xcc, 0x25, 0xa7, 0x5f, 0x6e, 0x21, 0x65, 0x83, 0xf7, 0xff, 0x3d, 0xc4, 0xcf}; + Octet16 x{0xd5, 0xcb, 0x84, 0x54, 0xd1, 0x77, 0x73, 0x3e, + 0xff, 0xff, 0xb2, 0xec, 0x71, 0x2b, 0xae, 0xab}; + Octet16 y{0xa6, 0xe8, 0xe7, 0xcc, 0x25, 0xa7, 0x5f, 0x6e, + 0x21, 0x65, 0x83, 0xf7, 0xff, 0x3d, 0xc4, 0xcf}; // algorithm expect all input to be in little endian format, so reverse std::reverse(std::begin(u), std::end(u)); @@ -244,10 +267,11 @@ TEST(CryptoToolboxTest, bt_spec_example_d_5_test) { // BT Spec 5.0 | Vol 3, Part H D.6 TEST(CryptoToolboxTest, bt_spec_example_d_6_test) { - Octet16 key{0xec, 0x02, 0x34, 0xa3, 0x57, 0xc8, 0xad, 0x05, 0x34, 0x10, 0x10, 0xa6, 0x0a, 0x39, 0x7d, 0x9b}; + Octet16 key{0xec, 0x02, 0x34, 0xa3, 0x57, 0xc8, 0xad, 0x05, + 0x34, 0x10, 0x10, 0xa6, 0x0a, 0x39, 0x7d, 0x9b}; std::array keyID{0x6c, 0x65, 0x62, 0x72}; - Octet16 expected_aes_cmac{ - 0x2d, 0x9a, 0xe1, 0x02, 0xe7, 0x6d, 0xc9, 0x1c, 0xe8, 0xd3, 0xa9, 0xe2, 0x80, 0xb1, 0x63, 0x99}; + Octet16 expected_aes_cmac{0x2d, 0x9a, 0xe1, 0x02, 0xe7, 0x6d, 0xc9, 0x1c, + 0xe8, 0xd3, 0xa9, 0xe2, 0x80, 0xb1, 0x63, 0x99}; // algorithm expect all input to be in little endian format, so reverse std::reverse(std::begin(key), std::end(key)); @@ -260,10 +284,12 @@ TEST(CryptoToolboxTest, bt_spec_example_d_6_test) { // BT Spec 5.0 | Vol 3, Part H D.7 TEST(CryptoToolboxTest, bt_spec_example_d_7_test) { - Octet16 IRK{0xec, 0x02, 0x34, 0xa3, 0x57, 0xc8, 0xad, 0x05, 0x34, 0x10, 0x10, 0xa6, 0x0a, 0x39, 0x7d, 0x9b}; - Octet16 prand{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x70, 0x81, 0x94}; - Octet16 expected_aes_128{ - 0x15, 0x9d, 0x5f, 0xb7, 0x2e, 0xbe, 0x23, 0x11, 0xa4, 0x8c, 0x1b, 0xdc, 0xc4, 0x0d, 0xfb, 0xaa}; + Octet16 IRK{0xec, 0x02, 0x34, 0xa3, 0x57, 0xc8, 0xad, 0x05, + 0x34, 0x10, 0x10, 0xa6, 0x0a, 0x39, 0x7d, 0x9b}; + Octet16 prand{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x70, 0x81, 0x94}; + Octet16 expected_aes_128{0x15, 0x9d, 0x5f, 0xb7, 0x2e, 0xbe, 0x23, 0x11, + 0xa4, 0x8c, 0x1b, 0xdc, 0xc4, 0x0d, 0xfb, 0xaa}; std::array expected_ah{0x0d, 0xfb, 0xaa}; // algorithm expect all input to be in little endian format, so reverse @@ -283,10 +309,12 @@ TEST(CryptoToolboxTest, bt_spec_example_d_7_test) { // BT Spec 5.0 | Vol 3, Part H D.8 TEST(CryptoToolboxTest, bt_spec_example_d_8_test) { - Octet16 Key{0xec, 0x02, 0x34, 0xa3, 0x57, 0xc8, 0xad, 0x05, 0x34, 0x10, 0x10, 0xa6, 0x0a, 0x39, 0x7d, 0x9b}; - Octet16 SALT{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x74, 0x6D, 0x70, 0x31}; - Octet16 expected_aes_cmac{ - 0xfb, 0x17, 0x35, 0x97, 0xc6, 0xa3, 0xc0, 0xec, 0xd2, 0x99, 0x8c, 0x2a, 0x75, 0xa5, 0x70, 0x11}; + Octet16 Key{0xec, 0x02, 0x34, 0xa3, 0x57, 0xc8, 0xad, 0x05, + 0x34, 0x10, 0x10, 0xa6, 0x0a, 0x39, 0x7d, 0x9b}; + Octet16 SALT{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x74, 0x6D, 0x70, 0x31}; + Octet16 expected_aes_cmac{0xfb, 0x17, 0x35, 0x97, 0xc6, 0xa3, 0xc0, 0xec, + 0xd2, 0x99, 0x8c, 0x2a, 0x75, 0xa5, 0x70, 0x11}; // algorithm expect all input to be in little endian format, so reverse std::reverse(std::begin(Key), std::end(Key)); @@ -301,9 +329,10 @@ Octet16 smp_calculate_ltk_to_link_key(const Octet16& ltk, bool use_h7); // BT Spec 5.0 | Vol 3, Part H D.9 TEST(CryptoToolboxTest, bt_spec_example_d_9_test) { - Octet16 LTK{0x36, 0x8d, 0xf9, 0xbc, 0xe3, 0x26, 0x4b, 0x58, 0xbd, 0x06, 0x6c, 0x33, 0x33, 0x4f, 0xbf, 0x64}; - Octet16 expected_link_key{ - 0x28, 0x7a, 0xd3, 0x79, 0xdc, 0xa4, 0x02, 0x53, 0x0a, 0x39, 0xf1, 0xf4, 0x30, 0x47, 0xb8, 0x35}; + Octet16 LTK{0x36, 0x8d, 0xf9, 0xbc, 0xe3, 0x26, 0x4b, 0x58, + 0xbd, 0x06, 0x6c, 0x33, 0x33, 0x4f, 0xbf, 0x64}; + Octet16 expected_link_key{0x28, 0x7a, 0xd3, 0x79, 0xdc, 0xa4, 0x02, 0x53, + 0x0a, 0x39, 0xf1, 0xf4, 0x30, 0x47, 0xb8, 0x35}; // algorithm expect all input to be in little endian format, so reverse std::reverse(std::begin(LTK), std::end(LTK)); @@ -315,9 +344,10 @@ TEST(CryptoToolboxTest, bt_spec_example_d_9_test) { // BT Spec 5.0 | Vol 3, Part H D.10 TEST(CryptoToolboxTest, bt_spec_example_d_10_test) { - Octet16 LTK{0x36, 0x8d, 0xf9, 0xbc, 0xe3, 0x26, 0x4b, 0x58, 0xbd, 0x06, 0x6c, 0x33, 0x33, 0x4f, 0xbf, 0x64}; - Octet16 expected_link_key{ - 0xbc, 0x1c, 0xa4, 0xef, 0x63, 0x3f, 0xc1, 0xbd, 0x0d, 0x82, 0x30, 0xaf, 0xee, 0x38, 0x8f, 0xb0}; + Octet16 LTK{0x36, 0x8d, 0xf9, 0xbc, 0xe3, 0x26, 0x4b, 0x58, + 0xbd, 0x06, 0x6c, 0x33, 0x33, 0x4f, 0xbf, 0x64}; + Octet16 expected_link_key{0xbc, 0x1c, 0xa4, 0xef, 0x63, 0x3f, 0xc1, 0xbd, + 0x0d, 0x82, 0x30, 0xaf, 0xee, 0x38, 0x8f, 0xb0}; // algorithm expect all input to be in little endian format, so reverse std::reverse(std::begin(LTK), std::end(LTK)); @@ -329,8 +359,10 @@ TEST(CryptoToolboxTest, bt_spec_example_d_10_test) { // // BT Spec 5.0 | Vol 3, Part H D.11 TEST(CryptoToolboxTest, bt_spec_example_d_11_test) { - Octet16 link_key{0x05, 0x04, 0x03, 0x02, 0x01, 0x00, 0x09, 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00}; - Octet16 expected_ltk{0xe8, 0x5e, 0x09, 0xeb, 0x5e, 0xcc, 0xb3, 0xe2, 0x69, 0x41, 0x8a, 0x13, 0x32, 0x11, 0xbc, 0x79}; + Octet16 link_key{0x05, 0x04, 0x03, 0x02, 0x01, 0x00, 0x09, 0x08, + 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00}; + Octet16 expected_ltk{0xe8, 0x5e, 0x09, 0xeb, 0x5e, 0xcc, 0xb3, 0xe2, + 0x69, 0x41, 0x8a, 0x13, 0x32, 0x11, 0xbc, 0x79}; // algorithm expect all input to be in little endian format, so reverse std::reverse(std::begin(link_key), std::end(link_key)); @@ -342,8 +374,10 @@ TEST(CryptoToolboxTest, bt_spec_example_d_11_test) { // BT Spec 5.0 | Vol 3, Part H D.12 TEST(CryptoToolboxTest, bt_spec_example_d_12_test) { - Octet16 link_key{0x05, 0x04, 0x03, 0x02, 0x01, 0x00, 0x09, 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00}; - Octet16 expected_ltk{0xa8, 0x13, 0xfb, 0x72, 0xf1, 0xa3, 0xdf, 0xa1, 0x8a, 0x2c, 0x9a, 0x43, 0xf1, 0x0d, 0x0a, 0x30}; + Octet16 link_key{0x05, 0x04, 0x03, 0x02, 0x01, 0x00, 0x09, 0x08, + 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00}; + Octet16 expected_ltk{0xa8, 0x13, 0xfb, 0x72, 0xf1, 0xa3, 0xdf, 0xa1, + 0x8a, 0x2c, 0x9a, 0x43, 0xf1, 0x0d, 0x0a, 0x30}; // algorithm expect all input to be in little endian format, so reverse std::reverse(std::begin(link_key), std::end(link_key)); diff --git a/system/gd/discovery/device/bt_property.cc b/system/gd/discovery/device/bt_property.cc index 99fa670b800..ab61b8ebca9 100644 --- a/system/gd/discovery/device/bt_property.cc +++ b/system/gd/discovery/device/bt_property.cc @@ -61,43 +61,35 @@ std::string bt_property_type_text(const bt_property_type_t& type) { std::string bt_property_text(const bt_property_t& property) { switch (property.type) { case BT_PROPERTY_BDNAME: - return base::StringPrintf( - "type:%s name:%s", - bt_property_type_text(property.type).c_str(), - (const char*)property.val); + return base::StringPrintf("type:%s name:%s", bt_property_type_text(property.type).c_str(), + (const char*)property.val); case BT_PROPERTY_BDADDR: - return base::StringPrintf( - "type:%s addr:%s", - bt_property_type_text(property.type).c_str(), - ((const RawAddress*)property.val)->ToString().c_str()); + return base::StringPrintf("type:%s addr:%s", bt_property_type_text(property.type).c_str(), + ((const RawAddress*)property.val)->ToString().c_str()); case BT_PROPERTY_UUIDS: { std::ostringstream oss; const bluetooth::Uuid* it = (const bluetooth::Uuid*)property.val; for (size_t i = 0; i < (size_t)property.len; i += sizeof(bluetooth::Uuid), it++) { (i == 0) ? oss << *it : oss << " " << *it; } - return base::StringPrintf( - "type:%s uuids:%s", bt_property_type_text(property.type).c_str(), oss.str().c_str()); + return base::StringPrintf("type:%s uuids:%s", bt_property_type_text(property.type).c_str(), + oss.str().c_str()); } case BT_PROPERTY_CLASS_OF_DEVICE: - return base::StringPrintf( - "type:%s cod:0x%x", - bt_property_type_text(property.type).c_str(), - *(uint32_t*)(property.val)); + return base::StringPrintf("type:%s cod:0x%x", bt_property_type_text(property.type).c_str(), + *(uint32_t*)(property.val)); case BT_PROPERTY_TYPE_OF_DEVICE: - return base::StringPrintf( - "type:%s type_of_device:%d", - bt_property_type_text(property.type).c_str(), - *(uint32_t*)(property.val)); + return base::StringPrintf("type:%s type_of_device:%d", + bt_property_type_text(property.type).c_str(), + *(uint32_t*)(property.val)); case BT_PROPERTY_SERVICE_RECORD: - return base::StringPrintf( - "type:%s uuid:%s channel:%u name:\"%s\"", - bt_property_type_text(property.type).c_str(), - (((bt_service_record_t*)property.val)->uuid).ToString().c_str(), - (((bt_service_record_t*)property.val)->channel), - (((bt_service_record_t*)property.val)->name)); + return base::StringPrintf("type:%s uuid:%s channel:%u name:\"%s\"", + bt_property_type_text(property.type).c_str(), + (((bt_service_record_t*)property.val)->uuid).ToString().c_str(), + (((bt_service_record_t*)property.val)->channel), + (((bt_service_record_t*)property.val)->name)); case BT_PROPERTY_ADAPTER_BONDED_DEVICES: { std::ostringstream oss; @@ -105,141 +97,127 @@ std::string bt_property_text(const bt_property_t& property) { for (size_t i = 0; i < (size_t)property.len; i += sizeof(RawAddress), it++) { (i == 0) ? oss << *it : oss << " " << *it; } - return base::StringPrintf( - "type:%s addrs:%s", bt_property_type_text(property.type).c_str(), oss.str().c_str()); + return base::StringPrintf("type:%s addrs:%s", bt_property_type_text(property.type).c_str(), + oss.str().c_str()); } case BT_PROPERTY_ADAPTER_DISCOVERABLE_TIMEOUT: - return base::StringPrintf( - "type:%s discoverable_timeout:%u", - bt_property_type_text(property.type).c_str(), - *((uint32_t*)property.val)); + return base::StringPrintf("type:%s discoverable_timeout:%u", + bt_property_type_text(property.type).c_str(), + *((uint32_t*)property.val)); case BT_PROPERTY_REMOTE_FRIENDLY_NAME: - return base::StringPrintf( - "type:%s remote_friendly_name:%s", - bt_property_type_text(property.type).c_str(), - (uint8_t*)property.val); + return base::StringPrintf("type:%s remote_friendly_name:%s", + bt_property_type_text(property.type).c_str(), + (uint8_t*)property.val); case BT_PROPERTY_REMOTE_RSSI: - return base::StringPrintf( - "type:%s rssi:%hhd", - bt_property_type_text(property.type).c_str(), - *(int8_t*)property.val); + return base::StringPrintf("type:%s rssi:%hhd", bt_property_type_text(property.type).c_str(), + *(int8_t*)property.val); case BT_PROPERTY_REMOTE_VERSION_INFO: - return base::StringPrintf( - "type:%s version:%d sub:%d mfr:%d", - bt_property_type_text(property.type).c_str(), - ((bt_remote_version_t*)property.val)->version, - ((bt_remote_version_t*)property.val)->sub_ver, - ((bt_remote_version_t*)property.val)->manufacturer); + return base::StringPrintf("type:%s version:%d sub:%d mfr:%d", + bt_property_type_text(property.type).c_str(), + ((bt_remote_version_t*)property.val)->version, + ((bt_remote_version_t*)property.val)->sub_ver, + ((bt_remote_version_t*)property.val)->manufacturer); case BT_PROPERTY_LOCAL_LE_FEATURES: return base::StringPrintf( - "type:%s version_supported:%d local_privacy_enabled:%d" - " max_adv_instance:%d rpa_offload_supported:%d max_irk_list_size:%d" - " max_adv_filter_supported:%d activity_energy_info_supported:%d" - " scan_result_storage_size:%d total_trackable_advertisers:%d" - " extended_scan_support:%d debug_logging_supported:%d le_2m_phy_supported:%d" - " le_coded_phy_supported:%d le_extended_advertising_supported:%d" - " le_periodic_advertising_supported:%d le_maximum_advertising_data_length:%d" - " dynamic_audio_buffer_supported:%d " - "le_periodic_advertising_sync_transfer_sender_supported:%d" - " le_connected_isochronous_stream_central_supported:%d " - "le_isochronous_broadcast_supported:%d" - " le_periodic_advertising_sync_transfer_recipient_supported:%d " - "adv_filter_extended_features_mask:%d" - "le_channel_sounding_supported:%d ", - bt_property_type_text(property.type).c_str(), - ((bt_local_le_features_t*)property.val)->version_supported, - ((bt_local_le_features_t*)property.val)->local_privacy_enabled, - ((bt_local_le_features_t*)property.val)->max_adv_instance, - ((bt_local_le_features_t*)property.val)->rpa_offload_supported, - ((bt_local_le_features_t*)property.val)->max_irk_list_size, - ((bt_local_le_features_t*)property.val)->max_adv_filter_supported, - ((bt_local_le_features_t*)property.val)->activity_energy_info_supported, - ((bt_local_le_features_t*)property.val)->scan_result_storage_size, - ((bt_local_le_features_t*)property.val)->total_trackable_advertisers, - ((bt_local_le_features_t*)property.val)->extended_scan_support, - ((bt_local_le_features_t*)property.val)->debug_logging_supported, - ((bt_local_le_features_t*)property.val)->le_2m_phy_supported, - ((bt_local_le_features_t*)property.val)->le_coded_phy_supported, - ((bt_local_le_features_t*)property.val)->le_extended_advertising_supported, - ((bt_local_le_features_t*)property.val)->le_periodic_advertising_supported, - ((bt_local_le_features_t*)property.val)->le_maximum_advertising_data_length, - ((bt_local_le_features_t*)property.val)->dynamic_audio_buffer_supported, - ((bt_local_le_features_t*)property.val) - ->le_periodic_advertising_sync_transfer_sender_supported, - ((bt_local_le_features_t*)property.val) - ->le_connected_isochronous_stream_central_supported, - ((bt_local_le_features_t*)property.val)->le_isochronous_broadcast_supported, - ((bt_local_le_features_t*)property.val) - ->le_periodic_advertising_sync_transfer_recipient_supported, - ((bt_local_le_features_t*)property.val)->adv_filter_extended_features_mask, - ((bt_local_le_features_t*)property.val)->le_channel_sounding_supported); + "type:%s version_supported:%d local_privacy_enabled:%d" + " max_adv_instance:%d rpa_offload_supported:%d max_irk_list_size:%d" + " max_adv_filter_supported:%d activity_energy_info_supported:%d" + " scan_result_storage_size:%d total_trackable_advertisers:%d" + " extended_scan_support:%d debug_logging_supported:%d le_2m_phy_supported:%d" + " le_coded_phy_supported:%d le_extended_advertising_supported:%d" + " le_periodic_advertising_supported:%d le_maximum_advertising_data_length:%d" + " dynamic_audio_buffer_supported:%d " + "le_periodic_advertising_sync_transfer_sender_supported:%d" + " le_connected_isochronous_stream_central_supported:%d " + "le_isochronous_broadcast_supported:%d" + " le_periodic_advertising_sync_transfer_recipient_supported:%d " + "adv_filter_extended_features_mask:%d" + "le_channel_sounding_supported:%d ", + bt_property_type_text(property.type).c_str(), + ((bt_local_le_features_t*)property.val)->version_supported, + ((bt_local_le_features_t*)property.val)->local_privacy_enabled, + ((bt_local_le_features_t*)property.val)->max_adv_instance, + ((bt_local_le_features_t*)property.val)->rpa_offload_supported, + ((bt_local_le_features_t*)property.val)->max_irk_list_size, + ((bt_local_le_features_t*)property.val)->max_adv_filter_supported, + ((bt_local_le_features_t*)property.val)->activity_energy_info_supported, + ((bt_local_le_features_t*)property.val)->scan_result_storage_size, + ((bt_local_le_features_t*)property.val)->total_trackable_advertisers, + ((bt_local_le_features_t*)property.val)->extended_scan_support, + ((bt_local_le_features_t*)property.val)->debug_logging_supported, + ((bt_local_le_features_t*)property.val)->le_2m_phy_supported, + ((bt_local_le_features_t*)property.val)->le_coded_phy_supported, + ((bt_local_le_features_t*)property.val)->le_extended_advertising_supported, + ((bt_local_le_features_t*)property.val)->le_periodic_advertising_supported, + ((bt_local_le_features_t*)property.val)->le_maximum_advertising_data_length, + ((bt_local_le_features_t*)property.val)->dynamic_audio_buffer_supported, + ((bt_local_le_features_t*)property.val) + ->le_periodic_advertising_sync_transfer_sender_supported, + ((bt_local_le_features_t*)property.val) + ->le_connected_isochronous_stream_central_supported, + ((bt_local_le_features_t*)property.val)->le_isochronous_broadcast_supported, + ((bt_local_le_features_t*)property.val) + ->le_periodic_advertising_sync_transfer_recipient_supported, + ((bt_local_le_features_t*)property.val)->adv_filter_extended_features_mask, + ((bt_local_le_features_t*)property.val)->le_channel_sounding_supported); case BT_PROPERTY_DYNAMIC_AUDIO_BUFFER: return base::StringPrintf("type:%s", bt_property_type_text(property.type).c_str()); case BT_PROPERTY_REMOTE_IS_COORDINATED_SET_MEMBER: - return base::StringPrintf( - "type:%s is_coordinated_set_member:%s", - bt_property_type_text(property.type).c_str(), - (*(bool*)property.val) ? "true" : "false"); + return base::StringPrintf("type:%s is_coordinated_set_member:%s", + bt_property_type_text(property.type).c_str(), + (*(bool*)property.val) ? "true" : "false"); case BT_PROPERTY_APPEARANCE: - return base::StringPrintf( - "type:%s appearance:0x%x", - bt_property_type_text(property.type).c_str(), - (*(uint16_t*)property.val)); + return base::StringPrintf("type:%s appearance:0x%x", + bt_property_type_text(property.type).c_str(), + (*(uint16_t*)property.val)); case BT_PROPERTY_VENDOR_PRODUCT_INFO: return base::StringPrintf( - "type:%s vendor_id_src:%hhu vendor_id:%hu product_id:%hu version:%hu", - bt_property_type_text(property.type).c_str(), - ((bt_vendor_product_info_t*)property.val)->vendor_id_src, - ((bt_vendor_product_info_t*)property.val)->vendor_id, - ((bt_vendor_product_info_t*)property.val)->product_id, - ((bt_vendor_product_info_t*)property.val)->version); + "type:%s vendor_id_src:%hhu vendor_id:%hu product_id:%hu version:%hu", + bt_property_type_text(property.type).c_str(), + ((bt_vendor_product_info_t*)property.val)->vendor_id_src, + ((bt_vendor_product_info_t*)property.val)->vendor_id, + ((bt_vendor_product_info_t*)property.val)->product_id, + ((bt_vendor_product_info_t*)property.val)->version); case BT_PROPERTY_REMOTE_ASHA_CAPABILITY: - return base::StringPrintf( - "type:%s remote_asha_capability:%hd", - bt_property_type_text(property.type).c_str(), - (*(int16_t*)property.val)); + return base::StringPrintf("type:%s remote_asha_capability:%hd", + bt_property_type_text(property.type).c_str(), + (*(int16_t*)property.val)); case BT_PROPERTY_REMOTE_ASHA_TRUNCATED_HISYNCID: - return base::StringPrintf( - "type:%s remote_asha_truncated_hisyncid:%u", - bt_property_type_text(property.type).c_str(), - (*(uint32_t*)property.val)); + return base::StringPrintf("type:%s remote_asha_truncated_hisyncid:%u", + bt_property_type_text(property.type).c_str(), + (*(uint32_t*)property.val)); case BT_PROPERTY_REMOTE_MODEL_NUM: - return base::StringPrintf( - "type:%s remote_model_num:%s", - bt_property_type_text(property.type).c_str(), - (char*)property.val); + return base::StringPrintf("type:%s remote_model_num:%s", + bt_property_type_text(property.type).c_str(), (char*)property.val); case BT_PROPERTY_REMOTE_ADDR_TYPE: - return base::StringPrintf( - "type:%s remote_asha_truncated_hisyncid:0x%x", - bt_property_type_text(property.type).c_str(), - (*(uint8_t*)property.val)); + return base::StringPrintf("type:%s remote_asha_truncated_hisyncid:0x%x", + bt_property_type_text(property.type).c_str(), + (*(uint8_t*)property.val)); case BT_PROPERTY_REMOTE_DEVICE_TIMESTAMP: return base::StringPrintf("type:%s", bt_property_type_text(property.type).c_str()); case BT_PROPERTY_REMOTE_SECURE_CONNECTIONS_SUPPORTED: - return base::StringPrintf( - "type:%s remote secure connections supported:%hhd", - bt_property_type_text(property.type).c_str(), - (*(uint8_t*)property.val)); + return base::StringPrintf("type:%s remote secure connections supported:%hhd", + bt_property_type_text(property.type).c_str(), + (*(uint8_t*)property.val)); case BT_PROPERTY_REMOTE_MAX_SESSION_KEY_SIZE: - return base::StringPrintf( - "type:%s remote max session key size:%hhd", - bt_property_type_text(property.type).c_str(), - (*(uint8_t*)property.val)); + return base::StringPrintf("type:%s remote max session key size:%hhd", + bt_property_type_text(property.type).c_str(), + (*(uint8_t*)property.val)); case BT_PROPERTY_RESERVED_07: case BT_PROPERTY_RESERVED_0E: @@ -258,9 +236,9 @@ BtPropertyLegacy::BtPropertyLegacy(const std::vector std::vector::iterator it = properties_.begin(); for (const auto& p : bt_properties) { *it++ = { - .type = p->Type(), - .len = (int)p->Size(), - .val = (void*)p->Val(), + .type = p->Type(), + .len = (int)p->Size(), + .val = (void*)p->Val(), }; } } @@ -271,20 +249,16 @@ void BtPropertyLegacy::Export(bt_property_t* bt_properties, size_t size) { for (const auto& p : bt_properties_) { *bt_properties++ = { - .type = p->Type(), - .len = (int)p->Size(), - .val = (void*)p->Val(), + .type = p->Type(), + .len = (int)p->Size(), + .val = (void*)p->Val(), }; } } -size_t BtPropertyLegacy::NumProperties() const { - return properties_.size(); -} +size_t BtPropertyLegacy::NumProperties() const { return properties_.size(); } -const std::vector& BtPropertyLegacy::Properties() const { - return properties_; -} +const std::vector& BtPropertyLegacy::Properties() const { return properties_; } std::shared_ptr BdName::Create(const BD_NAME bd_name) { return std::make_shared(BdName(bd_name)); @@ -304,17 +278,17 @@ std::shared_ptr TypeOfDevice::Create(const bt_device_type_t& type) std::shared_ptr ServiceRecord::Create(const bt_service_record_t& record) { return std::make_shared(ServiceRecord(record)); } -std::shared_ptr AdapterBondedDevices::Create( - const RawAddress* bd_addr, size_t len) { +std::shared_ptr AdapterBondedDevices::Create(const RawAddress* bd_addr, + size_t len) { log::assert_that(bd_addr != nullptr, "assert failed: bd_addr != nullptr"); return std::make_shared(AdapterBondedDevices(bd_addr, len)); } std::shared_ptr AdapterDiscoverableTimeout::Create( - const uint32_t& timeout) { + const uint32_t& timeout) { return std::make_shared(AdapterDiscoverableTimeout(timeout)); } -std::shared_ptr RemoteFriendlyName::Create( - const uint8_t bd_name[], size_t len) { +std::shared_ptr RemoteFriendlyName::Create(const uint8_t bd_name[], + size_t len) { return std::make_shared(RemoteFriendlyName(bd_name, len)); } std::shared_ptr RemoteRSSI::Create(const int8_t& rssi) { @@ -327,9 +301,9 @@ std::shared_ptr LocalLeFeatures::Create(const bt_local_le_featu return std::make_shared(LocalLeFeatures(features)); } std::shared_ptr RemoteIsCoordinatedSetMember::Create( - const bool& is_set_member) { + const bool& is_set_member) { return std::make_shared( - RemoteIsCoordinatedSetMember(is_set_member)); + RemoteIsCoordinatedSetMember(is_set_member)); } std::shared_ptr Appearance::Create(const uint16_t& appearance) { return std::make_shared(Appearance(appearance)); @@ -341,7 +315,7 @@ std::shared_ptr RemoteASHACapability::Create(const int16_t return std::make_shared(RemoteASHACapability(capability)); } std::shared_ptr RemoteASHATruncatedHiSyncId::Create( - const uint32_t& id) { + const uint32_t& id) { return std::make_shared(RemoteASHATruncatedHiSyncId(id)); } std::shared_ptr RemoteModelNum::Create(const bt_bdname_t& name) { diff --git a/system/gd/discovery/device/bt_property.h b/system/gd/discovery/device/bt_property.h index 2cc139e6852..0ed94d98af0 100644 --- a/system/gd/discovery/device/bt_property.h +++ b/system/gd/discovery/device/bt_property.h @@ -31,31 +31,27 @@ namespace bluetooth { namespace property { class BtProperty { - public: +public: // Return size in bytes of property data value virtual size_t Size() const = 0; // Returns raw pointer to the data value virtual const void* Val() const = 0; - bt_property_type_t Type() const { - return type_; - } + bt_property_type_t Type() const { return type_; } - std::string ToString() const { - return bt_property_type_text(type_); - } + std::string ToString() const { return bt_property_type_text(type_); } - protected: +protected: BtProperty(bt_property_type_t type) : type_(type) {} virtual ~BtProperty() = default; - private: +private: const bt_property_type_t type_; }; // Provide pointer/size access to properties for legacy jni API class BtPropertyLegacy { - public: +public: BtPropertyLegacy(const std::vector>& bt_properties); void Export(bt_property_t* bt_properties, size_t size); @@ -64,48 +60,36 @@ class BtPropertyLegacy { const std::vector& Properties() const; - bt_property_t* Ptr() const { - return const_cast(&properties_[0]); - } - int Len() const { - return static_cast(properties_.size()); - } + bt_property_t* Ptr() const { return const_cast(&properties_[0]); } + int Len() const { return static_cast(properties_.size()); } - private: +private: const std::vector> bt_properties_; std::vector properties_; }; template class BtPropertySimple : public BtProperty { - public: - virtual size_t Size() const override { - return sizeof(T); - } +public: + virtual size_t Size() const override { return sizeof(T); } - const void* Val() const override { - return (const void*)val_.get(); - } + const void* Val() const override { return (const void*)val_.get(); } - protected: +protected: BtPropertySimple(bt_property_type_t type, T val) : BtProperty(type), val_(std::make_shared(val)) {} - private: +private: std::shared_ptr val_; }; template class BtPropertyVector : public BtProperty { - public: - virtual size_t Size() const override { - return sizeof(T) * val_->size(); - } - const void* Val() const override { - return (const void*)&(*val_)[0]; - } +public: + virtual size_t Size() const override { return sizeof(T) * val_->size(); } + const void* Val() const override { return (const void*)&(*val_)[0]; } - protected: +protected: // Create a vector property from another vector BtPropertyVector(bt_property_type_t type, const std::vector& val) : BtProperty(type), val_(std::make_shared>(val)) {} @@ -114,13 +98,13 @@ class BtPropertyVector : public BtProperty { BtPropertyVector(bt_property_type_t type, const T* val, size_t size) : BtProperty(type), val_(std::make_shared>(val, val + size)) {} - protected: +protected: std::shared_ptr> val_; }; template class BtPropertyVectorWithPad : public BtPropertyVector { - protected: +protected: // Create a vector property from a raw pointer and size with pad element BtPropertyVectorWithPad(bt_property_type_t type, const T* val, size_t size, T pad) : BtPropertyVector(type, val, size) { @@ -129,7 +113,7 @@ class BtPropertyVectorWithPad : public BtPropertyVector { }; class BdName : public BtPropertyVectorWithPad { - public: +public: BdName(const BD_NAME bd_name) : BtPropertyVectorWithPad(BT_PROPERTY_BDNAME, bd_name, kBdNameLength, kBdNameDelim) { } @@ -138,14 +122,14 @@ class BdName : public BtPropertyVectorWithPad { }; class BdAddr : public BtPropertySimple { - public: +public: BdAddr(const RawAddress& bd_addr) : BtPropertySimple(BT_PROPERTY_BDADDR, bd_addr) {} static std::shared_ptr Create(const RawAddress& bd_addr); }; class Uuids : public BtPropertyVector { - public: +public: Uuids(const std::vector& uuids) : BtPropertyVector(BT_PROPERTY_UUIDS, uuids) {} @@ -153,28 +137,28 @@ class Uuids : public BtPropertyVector { }; class ClassOfDevice : public BtPropertySimple { - public: +public: ClassOfDevice(const uint32_t& cod) : BtPropertySimple(BT_PROPERTY_CLASS_OF_DEVICE, cod) {} static std::shared_ptr Create(const uint32_t& bd_addr); }; class TypeOfDevice : public BtPropertySimple { - public: +public: TypeOfDevice(const bt_device_type_t& device_type) : BtPropertySimple(BT_PROPERTY_TYPE_OF_DEVICE, device_type) {} static std::shared_ptr Create(const bt_device_type_t& device_type); }; class ServiceRecord : public BtPropertySimple { - public: +public: ServiceRecord(const bt_service_record_t& record) : BtPropertySimple(BT_PROPERTY_SERVICE_RECORD, record) {} static std::shared_ptr Create(const bt_service_record_t& record); }; class AdapterBondedDevices : public BtPropertyVector { - public: +public: AdapterBondedDevices(const RawAddress* bd_addr, size_t len) : BtPropertyVector(BT_PROPERTY_ADAPTER_BONDED_DEVICES, bd_addr, len) {} @@ -182,7 +166,7 @@ class AdapterBondedDevices : public BtPropertyVector { }; class AdapterDiscoverableTimeout : public BtPropertySimple { - public: +public: AdapterDiscoverableTimeout(const uint32_t& timeout) : BtPropertySimple(BT_PROPERTY_ADAPTER_DISCOVERABLE_TIMEOUT, timeout) {} @@ -190,23 +174,23 @@ class AdapterDiscoverableTimeout : public BtPropertySimple { }; class RemoteFriendlyName : public BtPropertyVectorWithPad { - public: +public: RemoteFriendlyName(const uint8_t bd_name[], size_t len) - : BtPropertyVectorWithPad( - BT_PROPERTY_REMOTE_FRIENDLY_NAME, bd_name, len, kBdNameDelim) {} + : BtPropertyVectorWithPad(BT_PROPERTY_REMOTE_FRIENDLY_NAME, bd_name, len, + kBdNameDelim) {} static std::shared_ptr Create(const uint8_t bd_name[], size_t len); }; class RemoteRSSI : public BtPropertySimple { - public: +public: RemoteRSSI(const int8_t& rssi) : BtPropertySimple(BT_PROPERTY_REMOTE_RSSI, rssi) {} static std::shared_ptr Create(const int8_t& rssi); }; class RemoteVersionInfo : public BtPropertySimple { - public: +public: RemoteVersionInfo(const bt_remote_version_t& info) : BtPropertySimple(BT_PROPERTY_REMOTE_VERSION_INFO, info) {} @@ -214,7 +198,7 @@ class RemoteVersionInfo : public BtPropertySimple { }; class LocalLeFeatures : public BtPropertySimple { - public: +public: LocalLeFeatures(const bt_local_le_features_t& features) : BtPropertySimple(BT_PROPERTY_LOCAL_LE_FEATURES, features) {} @@ -222,7 +206,7 @@ class LocalLeFeatures : public BtPropertySimple { }; class RemoteIsCoordinatedSetMember : public BtPropertySimple { - public: +public: RemoteIsCoordinatedSetMember(const bool& is_set_member) : BtPropertySimple(BT_PROPERTY_REMOTE_IS_COORDINATED_SET_MEMBER, is_set_member) {} @@ -230,7 +214,7 @@ class RemoteIsCoordinatedSetMember : public BtPropertySimple { }; class Appearance : public BtPropertySimple { - public: +public: Appearance(const uint16_t& appearance) : BtPropertySimple(BT_PROPERTY_APPEARANCE, appearance) {} @@ -238,7 +222,7 @@ class Appearance : public BtPropertySimple { }; class VendorProductInfo : public BtPropertySimple { - public: +public: VendorProductInfo(const bt_vendor_product_info_t& info) : BtPropertySimple(BT_PROPERTY_VENDOR_PRODUCT_INFO, info) {} @@ -246,7 +230,7 @@ class VendorProductInfo : public BtPropertySimple { }; class RemoteASHACapability : public BtPropertySimple { - public: +public: RemoteASHACapability(const int16_t capability) : BtPropertySimple(BT_PROPERTY_REMOTE_ASHA_CAPABILITY, capability) {} @@ -254,7 +238,7 @@ class RemoteASHACapability : public BtPropertySimple { }; class RemoteASHATruncatedHiSyncId : public BtPropertySimple { - public: +public: RemoteASHATruncatedHiSyncId(const uint32_t id) : BtPropertySimple(BT_PROPERTY_REMOTE_ASHA_TRUNCATED_HISYNCID, id) {} @@ -262,19 +246,17 @@ class RemoteASHATruncatedHiSyncId : public BtPropertySimple { }; class RemoteModelNum : public BtPropertyVectorWithPad { - public: +public: RemoteModelNum(const bt_bdname_t& name) - : BtPropertyVectorWithPad( - BT_PROPERTY_REMOTE_MODEL_NUM, - name.name, - sizeof(bt_bdname_t) - sizeof(kBdNameDelim), - kBdNameDelim) {} + : BtPropertyVectorWithPad(BT_PROPERTY_REMOTE_MODEL_NUM, name.name, + sizeof(bt_bdname_t) - sizeof(kBdNameDelim), kBdNameDelim) { + } static std::shared_ptr Create(const bt_bdname_t& name); }; class RemoteAddrType : public BtPropertySimple { - public: +public: RemoteAddrType(const uint8_t& type) : BtPropertySimple(BT_PROPERTY_REMOTE_ADDR_TYPE, type) {} @@ -282,7 +264,7 @@ class RemoteAddrType : public BtPropertySimple { }; class RemoteDeviceTimestamp : public BtPropertySimple { - public: +public: RemoteDeviceTimestamp(const int& timestamp) : BtPropertySimple(BT_PROPERTY_REMOTE_DEVICE_TIMESTAMP, timestamp) {} diff --git a/system/gd/discovery/device/bt_property_unittest.cc b/system/gd/discovery/device/bt_property_unittest.cc index a1654168fd4..557e018199d 100644 --- a/system/gd/discovery/device/bt_property_unittest.cc +++ b/system/gd/discovery/device/bt_property_unittest.cc @@ -33,9 +33,11 @@ constexpr size_t kNumberTestedProperties = 20; constexpr size_t kBdPropNameLength = kBdNameLength + sizeof(kBdNameDelim); constexpr uint8_t kReallyLongName[kBdPropNameLength] = - "aaaaaaaaaAaaaaaaaaaAaaaaaaaaaAaaaaaaaaaAaaaaaaaaaAaaaaaaaaaAaaaaaaaaaAaaaaaaaaaAaaaaaaaaaAaaaa" - "aaaaaAaaaaaaaaaAaaaaaaaaaAaaaaaaaaaAaaaaaaaaaAaaaaaaaaaAaaaaaaaaaAaaaaaaaaaAaaaaaaaaaAaaaaaaaa" - "aAaaaaaaaaaAaaaaaaaaaAaaaaaaaaaAaaaaaaaaaAaaaaaaaaaAaaaaaaaa"; + "aaaaaaaaaAaaaaaaaaaAaaaaaaaaaAaaaaaaaaaAaaaaaaaaaAaaaaaaaaaAaaaaaaaaaAaaaaaaaaaAaaaaaaaaaA" + "aaaa" + "aaaaaAaaaaaaaaaAaaaaaaaaaAaaaaaaaaaAaaaaaaaaaAaaaaaaaaaAaaaaaaaaaAaaaaaaaaaAaaaaaaaaaAaaaa" + "aaaa" + "aAaaaaaaaaaAaaaaaaaaaAaaaaaaaaaAaaaaaaaaaAaaaaaaaaaAaaaaaaaa"; // BT_PROPERTY_BDNAME constexpr BD_NAME kBdName{'k', 'B', 'd', 'N', 'a', 'm', 'e', '\0'}; @@ -45,9 +47,9 @@ const RawAddress kRawAddress{{0x11, 0x22, 0x33, 0x44, 0x55, 0x66}}; // BT_PROPERTY_UUIDS const bluetooth::Uuid uuids[] = { - {bluetooth::Uuid::FromString("00000001-1001-1000-8000-00805f9b34fb")}, - {bluetooth::Uuid::FromString("00000001-1002-1000-8000-00805f9b34fb")}, - {bluetooth::Uuid::FromString("00000001-1003-1000-8000-00805f9b34fb")}, + {bluetooth::Uuid::FromString("00000001-1001-1000-8000-00805f9b34fb")}, + {bluetooth::Uuid::FromString("00000001-1002-1000-8000-00805f9b34fb")}, + {bluetooth::Uuid::FromString("00000001-1003-1000-8000-00805f9b34fb")}, }; const std::vector kUuids(uuids, uuids + sizeof(uuids) / sizeof(uuids[0])); @@ -59,22 +61,20 @@ constexpr bt_device_type_t kTypeOfDevice{BT_DEVICE_DEVTYPE_BREDR}; // BT_PROPERTY_SERVICE_RECORD const bt_service_record_t kServiceRecord{ - .uuid = uuids[0], - .channel = 0x1234, - .name = {'k', 'S', 'e', 'r', 'v', 'i', 'c', 'e', 'R', 'e', - 'c', 'o', 'r', 'd', '.', 'n', 'a', 'm', 'e', '\0'}, + .uuid = uuids[0], + .channel = 0x1234, + .name = {'k', 'S', 'e', 'r', 'v', 'i', 'c', 'e', 'R', 'e', + 'c', 'o', 'r', 'd', '.', 'n', 'a', 'm', 'e', '\0'}, }; // BT_PROPERTY_ADAPTER_BONDED_DEVICES const RawAddress kAdapterBondedDevices[] = { - {{0x11, 0x22, 0x33, 0x44, 0x55}}, - {{0x12, 0x22, 0x33, 0x44, 0x55}}, - {{0x13, 0x22, 0x33, 0x44, 0x55}}, - {{0x14, 0x22, 0x33, 0x44, 0x55}}, - {{0x15, 0x22, 0x33, 0x44, 0x55}}, + {{0x11, 0x22, 0x33, 0x44, 0x55}}, {{0x12, 0x22, 0x33, 0x44, 0x55}}, + {{0x13, 0x22, 0x33, 0x44, 0x55}}, {{0x14, 0x22, 0x33, 0x44, 0x55}}, + {{0x15, 0x22, 0x33, 0x44, 0x55}}, }; constexpr size_t kNumBondedDevices = - sizeof(kAdapterBondedDevices) / sizeof(kAdapterBondedDevices[0]); + sizeof(kAdapterBondedDevices) / sizeof(kAdapterBondedDevices[0]); // BT_PROPERTY_ADAPTER_DISCOVERABLE_TIMEOUT constexpr uint32_t kAdapterDiscoverableTimeout{0x4488cc00}; @@ -88,36 +88,36 @@ constexpr int8_t kRemoteRssi{0x10}; // BT_PROPERTY_REMOTE_VERSION_INFO bt_remote_version_t kRemoteVersionInfo{ - .version = 1, - .sub_ver = 2, - .manufacturer = 3, + .version = 1, + .sub_ver = 2, + .manufacturer = 3, }; // BT_PROPERTY_LOCAL_LE_FEATURES constexpr bt_local_le_features_t kLocalLeFeatures{ - .version_supported = 0x1234, - .local_privacy_enabled = 0x11, - .max_adv_instance = 0x22, - .rpa_offload_supported = 0x33, - .max_irk_list_size = 0x44, - .max_adv_filter_supported = 0x55, - .activity_energy_info_supported = 0x66, - .scan_result_storage_size = 0x5678, - .total_trackable_advertisers = 0x9abc, - .extended_scan_support = true, - .debug_logging_supported = true, - .le_2m_phy_supported = true, - .le_coded_phy_supported = true, - .le_extended_advertising_supported = true, - .le_periodic_advertising_supported = true, - .le_maximum_advertising_data_length = 0x1357, - .dynamic_audio_buffer_supported = 0x22446688, - .le_periodic_advertising_sync_transfer_sender_supported = true, - .le_connected_isochronous_stream_central_supported = true, - .le_isochronous_broadcast_supported = true, - .le_periodic_advertising_sync_transfer_recipient_supported = true, - .adv_filter_extended_features_mask = 0x3366, - .le_channel_sounding_supported = true, + .version_supported = 0x1234, + .local_privacy_enabled = 0x11, + .max_adv_instance = 0x22, + .rpa_offload_supported = 0x33, + .max_irk_list_size = 0x44, + .max_adv_filter_supported = 0x55, + .activity_energy_info_supported = 0x66, + .scan_result_storage_size = 0x5678, + .total_trackable_advertisers = 0x9abc, + .extended_scan_support = true, + .debug_logging_supported = true, + .le_2m_phy_supported = true, + .le_coded_phy_supported = true, + .le_extended_advertising_supported = true, + .le_periodic_advertising_supported = true, + .le_maximum_advertising_data_length = 0x1357, + .dynamic_audio_buffer_supported = 0x22446688, + .le_periodic_advertising_sync_transfer_sender_supported = true, + .le_connected_isochronous_stream_central_supported = true, + .le_isochronous_broadcast_supported = true, + .le_periodic_advertising_sync_transfer_recipient_supported = true, + .adv_filter_extended_features_mask = 0x3366, + .le_channel_sounding_supported = true, }; // BT_PROPERTY_RESERVED_0F @@ -131,10 +131,10 @@ constexpr uint16_t kAppearance{0x44}; // BT_PROPERTY_VENDOR_PRODUCT_INFO constexpr bt_vendor_product_info_t kVendorProductInfo{ - .vendor_id_src = 0x02, - .vendor_id = 0x1235, - .product_id = 0x5679, - .version = 0x9abd, + .vendor_id_src = 0x02, + .vendor_id = 0x1235, + .product_id = 0x5679, + .version = 0x9abd, }; // BT_PROPERTY_REMOTE_ASHA_CAPABILITY @@ -145,7 +145,7 @@ constexpr uint32_t kRemoteAshaTruncatedHisyncId{0x22446688}; // BT_PROPERTY_REMOTE_MODEL_NUM constexpr bt_bdname_t kRemoteModelNum{ - .name = {'k', 'R', 'e', 'm', 'o', 't', 'e', 'M', 'o', 'd', 'e', 'l', 'N', 'u', 'm', '\0'}, + .name = {'k', 'R', 'e', 'm', 'o', 't', 'e', 'M', 'o', 'd', 'e', 'l', 'N', 'u', 'm', '\0'}, }; // BT_PROPERTY_REMOTE_ADDR_TYPE @@ -155,8 +155,8 @@ constexpr uint8_t kRemoteAddrType{0x55}; constexpr int kRemoteDeviceTimestamp{0x12345678}; // Fill the given property type with the well known property data set -void fill_property( - const bt_property_type_t& type, std::vector>& properties) { +void fill_property(const bt_property_type_t& type, + std::vector>& properties) { switch (type) { case BT_PROPERTY_BDNAME: { properties.push_back(BdName::Create(kBdName)); @@ -200,7 +200,7 @@ void fill_property( case BT_PROPERTY_REMOTE_FRIENDLY_NAME: { properties.push_back( - RemoteFriendlyName::Create(kRemoteFriendlyName, sizeof(kRemoteFriendlyName))); + RemoteFriendlyName::Create(kRemoteFriendlyName, sizeof(kRemoteFriendlyName))); ASSERT_EQ(sizeof(kRemoteFriendlyName) + sizeof(kBdNameDelim), properties.back()->Size()); } break; @@ -336,87 +336,63 @@ void verify_property(const bt_property_type_t& type, const bt_property_t& proper ASSERT_EQ((int)sizeof(bt_remote_version_t), property.len); ASSERT_EQ(kRemoteVersionInfo.version, ((bt_remote_version_t*)property.val)->version); ASSERT_EQ(kRemoteVersionInfo.sub_ver, ((bt_remote_version_t*)property.val)->sub_ver); - ASSERT_EQ( - kRemoteVersionInfo.manufacturer, ((bt_remote_version_t*)property.val)->manufacturer); + ASSERT_EQ(kRemoteVersionInfo.manufacturer, + ((bt_remote_version_t*)property.val)->manufacturer); break; case BT_PROPERTY_LOCAL_LE_FEATURES: ASSERT_EQ((int)sizeof(bt_local_le_features_t), property.len); - ASSERT_EQ( - kLocalLeFeatures.version_supported, - ((bt_local_le_features_t*)property.val)->version_supported); - ASSERT_EQ( - kLocalLeFeatures.local_privacy_enabled, - ((bt_local_le_features_t*)property.val)->local_privacy_enabled); - ASSERT_EQ( - kLocalLeFeatures.local_privacy_enabled, - ((bt_local_le_features_t*)property.val)->local_privacy_enabled); - ASSERT_EQ( - kLocalLeFeatures.max_adv_instance, - ((bt_local_le_features_t*)property.val)->max_adv_instance); - ASSERT_EQ( - kLocalLeFeatures.rpa_offload_supported, - ((bt_local_le_features_t*)property.val)->rpa_offload_supported); - ASSERT_EQ( - kLocalLeFeatures.max_irk_list_size, - ((bt_local_le_features_t*)property.val)->max_irk_list_size); - ASSERT_EQ( - kLocalLeFeatures.max_adv_filter_supported, - ((bt_local_le_features_t*)property.val)->max_adv_filter_supported); - ASSERT_EQ( - kLocalLeFeatures.activity_energy_info_supported, - ((bt_local_le_features_t*)property.val)->activity_energy_info_supported); - ASSERT_EQ( - kLocalLeFeatures.scan_result_storage_size, - ((bt_local_le_features_t*)property.val)->scan_result_storage_size); - ASSERT_EQ( - kLocalLeFeatures.total_trackable_advertisers, - ((bt_local_le_features_t*)property.val)->total_trackable_advertisers); - ASSERT_EQ( - kLocalLeFeatures.extended_scan_support, - ((bt_local_le_features_t*)property.val)->extended_scan_support); - ASSERT_EQ( - kLocalLeFeatures.debug_logging_supported, - ((bt_local_le_features_t*)property.val)->debug_logging_supported); - ASSERT_EQ( - kLocalLeFeatures.le_2m_phy_supported, - ((bt_local_le_features_t*)property.val)->le_2m_phy_supported); - ASSERT_EQ( - kLocalLeFeatures.le_coded_phy_supported, - ((bt_local_le_features_t*)property.val)->le_coded_phy_supported); - ASSERT_EQ( - kLocalLeFeatures.le_extended_advertising_supported, - ((bt_local_le_features_t*)property.val)->le_extended_advertising_supported); - ASSERT_EQ( - kLocalLeFeatures.le_periodic_advertising_supported, - ((bt_local_le_features_t*)property.val)->le_periodic_advertising_supported); - ASSERT_EQ( - kLocalLeFeatures.le_maximum_advertising_data_length, - ((bt_local_le_features_t*)property.val)->le_maximum_advertising_data_length); - ASSERT_EQ( - kLocalLeFeatures.dynamic_audio_buffer_supported, - ((bt_local_le_features_t*)property.val)->dynamic_audio_buffer_supported); - ASSERT_EQ( - kLocalLeFeatures.le_periodic_advertising_sync_transfer_sender_supported, - ((bt_local_le_features_t*)property.val) - ->le_periodic_advertising_sync_transfer_sender_supported); - ASSERT_EQ( - kLocalLeFeatures.le_connected_isochronous_stream_central_supported, - ((bt_local_le_features_t*)property.val) - ->le_connected_isochronous_stream_central_supported); - ASSERT_EQ( - kLocalLeFeatures.le_isochronous_broadcast_supported, - ((bt_local_le_features_t*)property.val)->le_isochronous_broadcast_supported); - ASSERT_EQ( - kLocalLeFeatures.le_periodic_advertising_sync_transfer_recipient_supported, - ((bt_local_le_features_t*)property.val) - ->le_periodic_advertising_sync_transfer_recipient_supported); - ASSERT_EQ( - kLocalLeFeatures.adv_filter_extended_features_mask, - ((bt_local_le_features_t*)property.val)->adv_filter_extended_features_mask); - ASSERT_EQ( - kLocalLeFeatures.le_channel_sounding_supported, - ((bt_local_le_features_t*)property.val)->le_channel_sounding_supported); + ASSERT_EQ(kLocalLeFeatures.version_supported, + ((bt_local_le_features_t*)property.val)->version_supported); + ASSERT_EQ(kLocalLeFeatures.local_privacy_enabled, + ((bt_local_le_features_t*)property.val)->local_privacy_enabled); + ASSERT_EQ(kLocalLeFeatures.local_privacy_enabled, + ((bt_local_le_features_t*)property.val)->local_privacy_enabled); + ASSERT_EQ(kLocalLeFeatures.max_adv_instance, + ((bt_local_le_features_t*)property.val)->max_adv_instance); + ASSERT_EQ(kLocalLeFeatures.rpa_offload_supported, + ((bt_local_le_features_t*)property.val)->rpa_offload_supported); + ASSERT_EQ(kLocalLeFeatures.max_irk_list_size, + ((bt_local_le_features_t*)property.val)->max_irk_list_size); + ASSERT_EQ(kLocalLeFeatures.max_adv_filter_supported, + ((bt_local_le_features_t*)property.val)->max_adv_filter_supported); + ASSERT_EQ(kLocalLeFeatures.activity_energy_info_supported, + ((bt_local_le_features_t*)property.val)->activity_energy_info_supported); + ASSERT_EQ(kLocalLeFeatures.scan_result_storage_size, + ((bt_local_le_features_t*)property.val)->scan_result_storage_size); + ASSERT_EQ(kLocalLeFeatures.total_trackable_advertisers, + ((bt_local_le_features_t*)property.val)->total_trackable_advertisers); + ASSERT_EQ(kLocalLeFeatures.extended_scan_support, + ((bt_local_le_features_t*)property.val)->extended_scan_support); + ASSERT_EQ(kLocalLeFeatures.debug_logging_supported, + ((bt_local_le_features_t*)property.val)->debug_logging_supported); + ASSERT_EQ(kLocalLeFeatures.le_2m_phy_supported, + ((bt_local_le_features_t*)property.val)->le_2m_phy_supported); + ASSERT_EQ(kLocalLeFeatures.le_coded_phy_supported, + ((bt_local_le_features_t*)property.val)->le_coded_phy_supported); + ASSERT_EQ(kLocalLeFeatures.le_extended_advertising_supported, + ((bt_local_le_features_t*)property.val)->le_extended_advertising_supported); + ASSERT_EQ(kLocalLeFeatures.le_periodic_advertising_supported, + ((bt_local_le_features_t*)property.val)->le_periodic_advertising_supported); + ASSERT_EQ(kLocalLeFeatures.le_maximum_advertising_data_length, + ((bt_local_le_features_t*)property.val)->le_maximum_advertising_data_length); + ASSERT_EQ(kLocalLeFeatures.dynamic_audio_buffer_supported, + ((bt_local_le_features_t*)property.val)->dynamic_audio_buffer_supported); + ASSERT_EQ(kLocalLeFeatures.le_periodic_advertising_sync_transfer_sender_supported, + ((bt_local_le_features_t*)property.val) + ->le_periodic_advertising_sync_transfer_sender_supported); + ASSERT_EQ(kLocalLeFeatures.le_connected_isochronous_stream_central_supported, + ((bt_local_le_features_t*)property.val) + ->le_connected_isochronous_stream_central_supported); + ASSERT_EQ(kLocalLeFeatures.le_isochronous_broadcast_supported, + ((bt_local_le_features_t*)property.val)->le_isochronous_broadcast_supported); + ASSERT_EQ(kLocalLeFeatures.le_periodic_advertising_sync_transfer_recipient_supported, + ((bt_local_le_features_t*)property.val) + ->le_periodic_advertising_sync_transfer_recipient_supported); + ASSERT_EQ(kLocalLeFeatures.adv_filter_extended_features_mask, + ((bt_local_le_features_t*)property.val)->adv_filter_extended_features_mask); + ASSERT_EQ(kLocalLeFeatures.le_channel_sounding_supported, + ((bt_local_le_features_t*)property.val)->le_channel_sounding_supported); break; case BT_PROPERTY_RESERVED_0E: @@ -436,12 +412,11 @@ void verify_property(const bt_property_type_t& type, const bt_property_t& proper case BT_PROPERTY_VENDOR_PRODUCT_INFO: ASSERT_EQ((int)sizeof(bt_vendor_product_info_t), property.len); - ASSERT_EQ( - kVendorProductInfo.vendor_id_src, - ((bt_vendor_product_info_t*)property.val)->vendor_id_src); + ASSERT_EQ(kVendorProductInfo.vendor_id_src, + ((bt_vendor_product_info_t*)property.val)->vendor_id_src); ASSERT_EQ(kVendorProductInfo.vendor_id, ((bt_vendor_product_info_t*)property.val)->vendor_id); - ASSERT_EQ( - kVendorProductInfo.product_id, ((bt_vendor_product_info_t*)property.val)->product_id); + ASSERT_EQ(kVendorProductInfo.product_id, + ((bt_vendor_product_info_t*)property.val)->product_id); ASSERT_EQ(kVendorProductInfo.version, ((bt_vendor_product_info_t*)property.val)->version); break; @@ -504,7 +479,7 @@ void fill_properties(std::vector>& properties) { } // namespace // class BtPropertyTest : public testing::Test { - protected: +protected: void SetUp() override {} void TearDown() override {} }; @@ -512,224 +487,221 @@ class BtPropertyTest : public testing::Test { TEST_F(BtPropertyTest, bt_property_text_test) { { bt_property_t prop = { - .type = BT_PROPERTY_BDNAME, - .len = (int)sizeof(kBdName), - .val = (void*)kBdName, + .type = BT_PROPERTY_BDNAME, + .len = (int)sizeof(kBdName), + .val = (void*)kBdName, }; ASSERT_STREQ("type:BT_PROPERTY_BDNAME name:kBdName", bt_property_text(prop).c_str()); } { bt_property_t prop = { - .type = BT_PROPERTY_BDADDR, - .len = (int)sizeof(kRawAddress), - .val = (void*)&kRawAddress, + .type = BT_PROPERTY_BDADDR, + .len = (int)sizeof(kRawAddress), + .val = (void*)&kRawAddress, }; ASSERT_STREQ("type:BT_PROPERTY_BDADDR addr:11:22:33:44:55:66", bt_property_text(prop).c_str()); } { bt_property_t prop = { - .type = BT_PROPERTY_UUIDS, - .len = (int)(sizeof(bluetooth::Uuid) * kUuids.size()), - .val = (void*)&kUuids[0], + .type = BT_PROPERTY_UUIDS, + .len = (int)(sizeof(bluetooth::Uuid) * kUuids.size()), + .val = (void*)&kUuids[0], }; ASSERT_STREQ( - "type:BT_PROPERTY_UUIDS uuids:00000001-1001-1000-8000-00805f9b34fb " - "00000001-1002-1000-8000-00805f9b34fb 00000001-1003-1000-8000-00805f9b34fb", - bt_property_text(prop).c_str()); + "type:BT_PROPERTY_UUIDS uuids:00000001-1001-1000-8000-00805f9b34fb " + "00000001-1002-1000-8000-00805f9b34fb 00000001-1003-1000-8000-00805f9b34fb", + bt_property_text(prop).c_str()); } { bt_property_t prop = { - .type = BT_PROPERTY_CLASS_OF_DEVICE, - .len = (int)sizeof(kClassOfDevice), - .val = (void*)&kClassOfDevice, + .type = BT_PROPERTY_CLASS_OF_DEVICE, + .len = (int)sizeof(kClassOfDevice), + .val = (void*)&kClassOfDevice, }; ASSERT_STREQ("type:BT_PROPERTY_CLASS_OF_DEVICE cod:0x99663300", bt_property_text(prop).c_str()); } { bt_property_t prop = { - .type = BT_PROPERTY_TYPE_OF_DEVICE, - .len = (int)sizeof(kTypeOfDevice), - .val = (void*)&kTypeOfDevice, + .type = BT_PROPERTY_TYPE_OF_DEVICE, + .len = (int)sizeof(kTypeOfDevice), + .val = (void*)&kTypeOfDevice, }; - ASSERT_STREQ( - "type:BT_PROPERTY_TYPE_OF_DEVICE type_of_device:1", bt_property_text(prop).c_str()); + ASSERT_STREQ("type:BT_PROPERTY_TYPE_OF_DEVICE type_of_device:1", + bt_property_text(prop).c_str()); } { bt_property_t prop = { - .type = BT_PROPERTY_SERVICE_RECORD, - .len = (int)sizeof(kServiceRecord), - .val = (void*)&kServiceRecord, + .type = BT_PROPERTY_SERVICE_RECORD, + .len = (int)sizeof(kServiceRecord), + .val = (void*)&kServiceRecord, }; ASSERT_STREQ( - "type:BT_PROPERTY_SERVICE_RECORD uuid:00000001-1001-1000-8000-00805f9b34fb channel:4660 " - "name:\"kServiceRecord.name\"", - bt_property_text(prop).c_str()); + "type:BT_PROPERTY_SERVICE_RECORD uuid:00000001-1001-1000-8000-00805f9b34fb " + "channel:4660 " + "name:\"kServiceRecord.name\"", + bt_property_text(prop).c_str()); } { bt_property_t prop = { - .type = BT_PROPERTY_ADAPTER_BONDED_DEVICES, - .len = (int)(sizeof(kAdapterBondedDevices)), - .val = (void*)kAdapterBondedDevices, + .type = BT_PROPERTY_ADAPTER_BONDED_DEVICES, + .len = (int)(sizeof(kAdapterBondedDevices)), + .val = (void*)kAdapterBondedDevices, }; ASSERT_STREQ( - "type:BT_PROPERTY_ADAPTER_BONDED_DEVICES addrs:11:22:33:44:55:00 12:22:33:44:55:00 " - "13:22:33:44:55:00 14:22:33:44:55:00 15:22:33:44:55:00", - bt_property_text(prop).c_str()); + "type:BT_PROPERTY_ADAPTER_BONDED_DEVICES addrs:11:22:33:44:55:00 12:22:33:44:55:00 " + "13:22:33:44:55:00 14:22:33:44:55:00 15:22:33:44:55:00", + bt_property_text(prop).c_str()); } { bt_property_t prop = { - .type = BT_PROPERTY_ADAPTER_DISCOVERABLE_TIMEOUT, - .len = (int)sizeof(kAdapterDiscoverableTimeout), - .val = (void*)&kAdapterDiscoverableTimeout, + .type = BT_PROPERTY_ADAPTER_DISCOVERABLE_TIMEOUT, + .len = (int)sizeof(kAdapterDiscoverableTimeout), + .val = (void*)&kAdapterDiscoverableTimeout, }; - ASSERT_STREQ( - "type:BT_PROPERTY_ADAPTER_DISCOVERABLE_TIMEOUT discoverable_timeout:1149815808", - bt_property_text(prop).c_str()); + ASSERT_STREQ("type:BT_PROPERTY_ADAPTER_DISCOVERABLE_TIMEOUT discoverable_timeout:1149815808", + bt_property_text(prop).c_str()); } { bt_bdname_t bd_name; bd_name_from_char_pointer(bd_name.name, (const char*)kRemoteFriendlyName); bt_property_t prop = { - .type = BT_PROPERTY_REMOTE_FRIENDLY_NAME, - .len = (int)sizeof(bd_name.name), - .val = (void*)&bd_name.name, + .type = BT_PROPERTY_REMOTE_FRIENDLY_NAME, + .len = (int)sizeof(bd_name.name), + .val = (void*)&bd_name.name, }; - ASSERT_STREQ( - "type:BT_PROPERTY_REMOTE_FRIENDLY_NAME remote_friendly_name:kRemoteFriendlyName", - bt_property_text(prop).c_str()); + ASSERT_STREQ("type:BT_PROPERTY_REMOTE_FRIENDLY_NAME remote_friendly_name:kRemoteFriendlyName", + bt_property_text(prop).c_str()); } { bt_property_t prop = { - .type = BT_PROPERTY_REMOTE_RSSI, - .len = (int)sizeof(kRemoteRssi), - .val = (void*)&kRemoteRssi, + .type = BT_PROPERTY_REMOTE_RSSI, + .len = (int)sizeof(kRemoteRssi), + .val = (void*)&kRemoteRssi, }; ASSERT_STREQ("type:BT_PROPERTY_REMOTE_RSSI rssi:16", bt_property_text(prop).c_str()); } { bt_property_t prop = { - .type = BT_PROPERTY_REMOTE_VERSION_INFO, - .len = (int)sizeof(kRemoteVersionInfo), - .val = (void*)&kRemoteVersionInfo, + .type = BT_PROPERTY_REMOTE_VERSION_INFO, + .len = (int)sizeof(kRemoteVersionInfo), + .val = (void*)&kRemoteVersionInfo, }; - ASSERT_STREQ( - "type:BT_PROPERTY_REMOTE_VERSION_INFO version:1 sub:2 mfr:3", - bt_property_text(prop).c_str()); + ASSERT_STREQ("type:BT_PROPERTY_REMOTE_VERSION_INFO version:1 sub:2 mfr:3", + bt_property_text(prop).c_str()); } { bt_property_t prop = { - .type = BT_PROPERTY_LOCAL_LE_FEATURES, - .len = (int)sizeof(kLocalLeFeatures), - .val = (void*)&kLocalLeFeatures, + .type = BT_PROPERTY_LOCAL_LE_FEATURES, + .len = (int)sizeof(kLocalLeFeatures), + .val = (void*)&kLocalLeFeatures, }; ASSERT_STREQ( - "type:BT_PROPERTY_LOCAL_LE_FEATURES version_supported:4660 local_privacy_enabled:17 " - "max_adv_instance:34 rpa_offload_supported:51 max_irk_list_size:68 " - "max_adv_filter_supported:85 activity_energy_info_supported:102 " - "scan_result_storage_size:22136 total_trackable_advertisers:39612 extended_scan_support:1 " - "debug_logging_supported:1 le_2m_phy_supported:1 le_coded_phy_supported:1 " - "le_extended_advertising_supported:1 le_periodic_advertising_supported:1 " - "le_maximum_advertising_data_length:4951 dynamic_audio_buffer_supported:574908040 " - "le_periodic_advertising_sync_transfer_sender_supported:1 " - "le_connected_isochronous_stream_central_supported:1 le_isochronous_broadcast_supported:1 " - "le_periodic_advertising_sync_transfer_recipient_supported:1 " - "adv_filter_extended_features_mask:13158" - "le_channel_sounding_supported:1 ", - bt_property_text(prop).c_str()); + "type:BT_PROPERTY_LOCAL_LE_FEATURES version_supported:4660 local_privacy_enabled:17 " + "max_adv_instance:34 rpa_offload_supported:51 max_irk_list_size:68 " + "max_adv_filter_supported:85 activity_energy_info_supported:102 " + "scan_result_storage_size:22136 total_trackable_advertisers:39612 " + "extended_scan_support:1 " + "debug_logging_supported:1 le_2m_phy_supported:1 le_coded_phy_supported:1 " + "le_extended_advertising_supported:1 le_periodic_advertising_supported:1 " + "le_maximum_advertising_data_length:4951 dynamic_audio_buffer_supported:574908040 " + "le_periodic_advertising_sync_transfer_sender_supported:1 " + "le_connected_isochronous_stream_central_supported:1 " + "le_isochronous_broadcast_supported:1 " + "le_periodic_advertising_sync_transfer_recipient_supported:1 " + "adv_filter_extended_features_mask:13158" + "le_channel_sounding_supported:1 ", + bt_property_text(prop).c_str()); } { bt_property_t prop = { - .type = BT_PROPERTY_REMOTE_IS_COORDINATED_SET_MEMBER, - .len = (int)sizeof(kRemoteIsCoordinatedSetMember), - .val = (void*)&kRemoteIsCoordinatedSetMember, + .type = BT_PROPERTY_REMOTE_IS_COORDINATED_SET_MEMBER, + .len = (int)sizeof(kRemoteIsCoordinatedSetMember), + .val = (void*)&kRemoteIsCoordinatedSetMember, }; - ASSERT_STREQ( - "type:BT_PROPERTY_REMOTE_IS_COORDINATED_SET_MEMBER is_coordinated_set_member:true", - bt_property_text(prop).c_str()); + ASSERT_STREQ("type:BT_PROPERTY_REMOTE_IS_COORDINATED_SET_MEMBER is_coordinated_set_member:true", + bt_property_text(prop).c_str()); } { bt_property_t prop = { - .type = BT_PROPERTY_APPEARANCE, - .len = (int)sizeof(kAppearance), - .val = (void*)&kAppearance, + .type = BT_PROPERTY_APPEARANCE, + .len = (int)sizeof(kAppearance), + .val = (void*)&kAppearance, }; ASSERT_STREQ("type:BT_PROPERTY_APPEARANCE appearance:0x44", bt_property_text(prop).c_str()); } { bt_property_t prop = { - .type = BT_PROPERTY_VENDOR_PRODUCT_INFO, - .len = (int)sizeof(kVendorProductInfo), - .val = (void*)&kVendorProductInfo, + .type = BT_PROPERTY_VENDOR_PRODUCT_INFO, + .len = (int)sizeof(kVendorProductInfo), + .val = (void*)&kVendorProductInfo, }; ASSERT_STREQ( - "type:BT_PROPERTY_VENDOR_PRODUCT_INFO vendor_id_src:2 vendor_id:4661 product_id:22137 " - "version:39613", - bt_property_text(prop).c_str()); + "type:BT_PROPERTY_VENDOR_PRODUCT_INFO vendor_id_src:2 vendor_id:4661 product_id:22137 " + "version:39613", + bt_property_text(prop).c_str()); } { bt_property_t prop = { - .type = BT_PROPERTY_REMOTE_ASHA_CAPABILITY, - .len = (int)sizeof(kRemoteAshaCapability), - .val = (void*)&kRemoteAshaCapability, + .type = BT_PROPERTY_REMOTE_ASHA_CAPABILITY, + .len = (int)sizeof(kRemoteAshaCapability), + .val = (void*)&kRemoteAshaCapability, }; - ASSERT_STREQ( - "type:BT_PROPERTY_REMOTE_ASHA_CAPABILITY remote_asha_capability:137", - bt_property_text(prop).c_str()); + ASSERT_STREQ("type:BT_PROPERTY_REMOTE_ASHA_CAPABILITY remote_asha_capability:137", + bt_property_text(prop).c_str()); } { bt_property_t prop = { - .type = BT_PROPERTY_REMOTE_ASHA_TRUNCATED_HISYNCID, - .len = (int)sizeof(kRemoteAshaTruncatedHisyncId), - .val = (void*)&kRemoteAshaTruncatedHisyncId, + .type = BT_PROPERTY_REMOTE_ASHA_TRUNCATED_HISYNCID, + .len = (int)sizeof(kRemoteAshaTruncatedHisyncId), + .val = (void*)&kRemoteAshaTruncatedHisyncId, }; ASSERT_STREQ( - "type:BT_PROPERTY_REMOTE_ASHA_TRUNCATED_HISYNCID remote_asha_truncated_hisyncid:574908040", - bt_property_text(prop).c_str()); + "type:BT_PROPERTY_REMOTE_ASHA_TRUNCATED_HISYNCID " + "remote_asha_truncated_hisyncid:574908040", + bt_property_text(prop).c_str()); } { bt_property_t prop = { - .type = BT_PROPERTY_REMOTE_MODEL_NUM, - .len = (int)sizeof(kRemoteModelNum.name), - .val = (void*)kRemoteModelNum.name, + .type = BT_PROPERTY_REMOTE_MODEL_NUM, + .len = (int)sizeof(kRemoteModelNum.name), + .val = (void*)kRemoteModelNum.name, }; - ASSERT_STREQ( - "type:BT_PROPERTY_REMOTE_MODEL_NUM remote_model_num:kRemoteModelNum", - bt_property_text(prop).c_str()); + ASSERT_STREQ("type:BT_PROPERTY_REMOTE_MODEL_NUM remote_model_num:kRemoteModelNum", + bt_property_text(prop).c_str()); } { bt_property_t prop = { - .type = BT_PROPERTY_REMOTE_ADDR_TYPE, - .len = (int)sizeof(kRemoteAddrType), - .val = (void*)&kRemoteAddrType, + .type = BT_PROPERTY_REMOTE_ADDR_TYPE, + .len = (int)sizeof(kRemoteAddrType), + .val = (void*)&kRemoteAddrType, }; - ASSERT_STREQ( - "type:BT_PROPERTY_REMOTE_ADDR_TYPE remote_asha_truncated_hisyncid:0x55", - bt_property_text(prop).c_str()); + ASSERT_STREQ("type:BT_PROPERTY_REMOTE_ADDR_TYPE remote_asha_truncated_hisyncid:0x55", + bt_property_text(prop).c_str()); } { bt_property_t prop = { - .type = BT_PROPERTY_REMOTE_DEVICE_TIMESTAMP, - .len = (int)sizeof(kRemoteDeviceTimestamp), - .val = (void*)&kRemoteDeviceTimestamp, + .type = BT_PROPERTY_REMOTE_DEVICE_TIMESTAMP, + .len = (int)sizeof(kRemoteDeviceTimestamp), + .val = (void*)&kRemoteDeviceTimestamp, }; ASSERT_STREQ("type:BT_PROPERTY_REMOTE_DEVICE_TIMESTAMP", bt_property_text(prop).c_str()); } @@ -778,10 +750,8 @@ TEST_F(BtPropertyTest, name_too_long) { } class BtPropertyArrayTest : public testing::Test { - protected: - void SetUp() override { - fill_properties(properties); - } +protected: + void SetUp() override { fill_properties(properties); } void TearDown() override {} std::vector> properties; bt_property_t props[kNumberTestedProperties]; @@ -812,14 +782,12 @@ TEST_F(BtPropertyArrayTest, async_data) { } class BtPropertyDynamicArrayTest : public testing::Test { - protected: +protected: void SetUp() override { fill_properties(properties); props = (bt_property_t*)malloc(sizeof(bt_property_t) * properties.size()); } - void TearDown() override { - free(props); - } + void TearDown() override { free(props); } bt_property_t* props{nullptr}; std::vector> properties; @@ -839,7 +807,7 @@ TEST_F(BtPropertyDynamicArrayTest, serialize_and_verify) { } class BtPropertyMultiAllocationTest : public testing::Test { - protected: +protected: static constexpr size_t kNumProperties = 1; static constexpr size_t kNumThreads = 20; @@ -865,8 +833,8 @@ TEST_F(BtPropertyMultiAllocationTest, async_data_multi) { for (size_t i = 0; i < kNumThreads; i++) { std::vector> props = future_vector[i].get(); BtPropertyLegacy legacy(props); - memcpy( - bt_properties[i], (const void*)legacy.Ptr(), (size_t)legacy.Len() * sizeof(bt_property_t)); + memcpy(bt_properties[i], (const void*)legacy.Ptr(), + (size_t)legacy.Len() * sizeof(bt_property_t)); ASSERT_EQ(BT_PROPERTY_REMOTE_DEVICE_TIMESTAMP, (int)bt_properties[i]->type); ASSERT_EQ((int)sizeof(uint32_t), bt_properties[i]->len); diff --git a/system/gd/discovery/device/data_parser.cc b/system/gd/discovery/device/data_parser.cc index 2e9acdc78ef..7439be07dd9 100644 --- a/system/gd/discovery/device/data_parser.cc +++ b/system/gd/discovery/device/data_parser.cc @@ -36,9 +36,7 @@ DataParser::DataParser(const std::vector& data) { } } -size_t DataParser::GetNumGapData() const { - return gap_data_.size(); -} +size_t DataParser::GetNumGapData() const { return gap_data_.size(); } std::vector DataParser::GetData() const { return std::vector(gap_data_); @@ -46,7 +44,9 @@ std::vector DataParser::GetData() const { std::vector DataParser::GetDataTypes() const { std::vector types; - for (const auto& gap_data : gap_data_) types.push_back(gap_data.data_type_); + for (const auto& gap_data : gap_data_) { + types.push_back(gap_data.data_type_); + } return types; } diff --git a/system/gd/discovery/device/data_parser.h b/system/gd/discovery/device/data_parser.h index d96726ea636..75ebe88118a 100644 --- a/system/gd/discovery/device/data_parser.h +++ b/system/gd/discovery/device/data_parser.h @@ -25,14 +25,14 @@ namespace discovery { namespace device { class DataParser { - public: +public: DataParser(const std::vector& data); std::vector GetData() const; std::vector GetDataTypes() const; size_t GetNumGapData() const; - protected: +protected: std::vector gap_data_; }; diff --git a/system/gd/discovery/device/data_parser_unittest.cc b/system/gd/discovery/device/data_parser_unittest.cc index 8ed0223694c..89e375d0c83 100644 --- a/system/gd/discovery/device/data_parser_unittest.cc +++ b/system/gd/discovery/device/data_parser_unittest.cc @@ -28,26 +28,16 @@ using bluetooth::discovery::device::DataParser; namespace { constexpr uint8_t kOneFlag32Data[] = { - 0x5, static_cast(GapDataType::FLAGS), 0xde, 0xad, 0xbe, 0xef}; + 0x5, static_cast(GapDataType::FLAGS), 0xde, 0xad, 0xbe, 0xef}; constexpr uint8_t kTwoFlag32Data[] = { - 0x5, - static_cast(GapDataType::FLAGS), - 0xde, - 0xad, - 0xbe, - 0xef, - 0x5, - static_cast(GapDataType::FLAGS), - 0x11, - 0x22, - 0x33, - 0x44}; -constexpr uint8_t kNoUuid16Data[] = { - 0x2, static_cast(GapDataType::COMPLETE_LIST_16_BIT_UUIDS)}; + 0x5, static_cast(GapDataType::FLAGS), 0xde, 0xad, 0xbe, 0xef, + 0x5, static_cast(GapDataType::FLAGS), 0x11, 0x22, 0x33, 0x44}; +constexpr uint8_t kNoUuid16Data[] = {0x2, + static_cast(GapDataType::COMPLETE_LIST_16_BIT_UUIDS)}; constexpr uint8_t kPartialUuid16Data[] = { - 0x2, static_cast(GapDataType::COMPLETE_LIST_16_BIT_UUIDS), 0x12}; + 0x2, static_cast(GapDataType::COMPLETE_LIST_16_BIT_UUIDS), 0x12}; constexpr uint8_t kOneUuid16Data[] = { - 0x3, static_cast(GapDataType::COMPLETE_LIST_16_BIT_UUIDS), 0x12, 0x34}; + 0x3, static_cast(GapDataType::COMPLETE_LIST_16_BIT_UUIDS), 0x12, 0x34}; uint32_t toLeInt(const std::vector& v) { return v[3] | (v[2] << 8) | (v[1] << 16) | (v[0] << 24); @@ -100,8 +90,8 @@ TEST(DataParserTest, all_ones_data) { } TEST(DataParserTest, simple_flag) { - auto data = std::make_shared>( - kOneFlag32Data, kOneFlag32Data + sizeof(kOneFlag32Data)); + auto data = std::make_shared>(kOneFlag32Data, + kOneFlag32Data + sizeof(kOneFlag32Data)); auto it = Iterator(data); GapData gap_data; @@ -113,8 +103,8 @@ TEST(DataParserTest, simple_flag) { } TEST(DataParserTest, two_flags) { - auto data = std::make_shared>( - kTwoFlag32Data, kTwoFlag32Data + sizeof(kTwoFlag32Data)); + auto data = std::make_shared>(kTwoFlag32Data, + kTwoFlag32Data + sizeof(kTwoFlag32Data)); auto it = Iterator(data); GapData gap_data[2]; @@ -132,8 +122,8 @@ TEST(DataParserTest, two_flags) { } TEST(DataParserTest, no_uuid16) { - auto data = - std::make_shared>(kNoUuid16Data, kNoUuid16Data + sizeof(kNoUuid16Data)); + auto data = std::make_shared>(kNoUuid16Data, + kNoUuid16Data + sizeof(kNoUuid16Data)); auto it = Iterator(data); GapData gap_data; @@ -146,7 +136,7 @@ TEST(DataParserTest, no_uuid16) { TEST(DataParserTest, partial_uuid16) { auto data = std::make_shared>( - kPartialUuid16Data, kPartialUuid16Data + sizeof(kPartialUuid16Data)); + kPartialUuid16Data, kPartialUuid16Data + sizeof(kPartialUuid16Data)); auto it = Iterator(data); GapData gap_data; @@ -158,8 +148,8 @@ TEST(DataParserTest, partial_uuid16) { } TEST(DataParserTest, one_uuid16) { - auto data = std::make_shared>( - kOneUuid16Data, kOneUuid16Data + sizeof(kOneUuid16Data)); + auto data = std::make_shared>(kOneUuid16Data, + kOneUuid16Data + sizeof(kOneUuid16Data)); auto it = Iterator(data); GapData gap_data; it = GapData::Parse(&gap_data, it); @@ -183,8 +173,8 @@ TEST(DataParserTest, simple_data_parser) { ASSERT_EQ(2U, flags.size()); uint32_t value[2] = { - toLeInt(flags[0].data_), - toLeInt(flags[1].data_), + toLeInt(flags[0].data_), + toLeInt(flags[1].data_), }; ASSERT_EQ((unsigned)0xdeadbeef, value[0]); ASSERT_EQ((unsigned)0x11223344, value[1]); @@ -206,8 +196,8 @@ TEST(DataParserTest, two_flags_backing_store_cleared) { ASSERT_EQ(2U, flags.size()); uint32_t value[2] = { - toLeInt(flags[0].data_), - toLeInt(flags[1].data_), + toLeInt(flags[0].data_), + toLeInt(flags[1].data_), }; ASSERT_EQ((unsigned)0xdeadbeef, value[0]); ASSERT_EQ((unsigned)0x11223344, value[1]); @@ -231,8 +221,8 @@ TEST(DataParserTest, backing_store_freed) { ASSERT_EQ(2U, flags.size()); uint32_t value[2] = { - toLeInt(flags[0].data_), - toLeInt(flags[1].data_), + toLeInt(flags[0].data_), + toLeInt(flags[1].data_), }; ASSERT_EQ((unsigned)0xdeadbeef, value[0]); ASSERT_EQ((unsigned)0x11223344, value[1]); @@ -241,10 +231,9 @@ TEST(DataParserTest, backing_store_freed) { std::string GapDataToString(const GapData& data) { std::stringstream ss; ss << std::hex << std::showbase << "LengthAndData { "; - ss << "data = " - << "VECTOR["; + ss << "data = " << "VECTOR["; for (size_t index = 0; index < data.data_.size(); index++) { - ss << ((index == 0) ? "" : ", ") << static_cast((data.data_[index])); + ss << ((index == 0) ? "" : ", ") << static_cast(data.data_[index]); } ss << "]"; ss << " }"; diff --git a/system/gd/discovery/device/eir_data.cc b/system/gd/discovery/device/eir_data.cc index 50a4f8ed785..3e8f765e826 100644 --- a/system/gd/discovery/device/eir_data.cc +++ b/system/gd/discovery/device/eir_data.cc @@ -165,11 +165,13 @@ bool EirData::GetSecurityManagerOobFlags(std::vector>& flag bool EirData::GetServiceUuuids16(std::vector& uuids) const { for (const auto& gap_data : gap_data_) { if (gap_data.data_type_ == hci::GapDataType::SERVICE_DATA_16_BIT_UUIDS) { - if (gap_data.data_.size() < Uuid::kNumBytes16) continue; + if (gap_data.data_.size() < Uuid::kNumBytes16) { + continue; + } auto it = gap_data.data_.begin(); uuids.push_back({ - .uuid = (uint16_t)(*it | *(it + 1) << 8), - .data = std::vector(it + Uuid::kNumBytes16, gap_data.data_.end()), + .uuid = (uint16_t)(*it | *(it + 1) << 8), + .data = std::vector(it + Uuid::kNumBytes16, gap_data.data_.end()), }); } } @@ -179,11 +181,13 @@ bool EirData::GetServiceUuuids16(std::vector& uuids) const { bool EirData::GetServiceUuuids32(std::vector& uuids) const { for (const auto& gap_data : gap_data_) { if (gap_data.data_type_ == hci::GapDataType::SERVICE_DATA_32_BIT_UUIDS) { - if (gap_data.data_.size() < Uuid::kNumBytes32) continue; + if (gap_data.data_.size() < Uuid::kNumBytes32) { + continue; + } auto it = gap_data.data_.begin(); uuids.push_back({ - .uuid = (uint32_t)(*it | *(it + 1) << 8 | *(it + 2) << 16 | *(it + 3) << 24), - .data = std::vector(it + Uuid::kNumBytes32, gap_data.data_.end()), + .uuid = (uint32_t)(*it | *(it + 1) << 8 | *(it + 2) << 16 | *(it + 3) << 24), + .data = std::vector(it + Uuid::kNumBytes32, gap_data.data_.end()), }); } } @@ -193,8 +197,9 @@ bool EirData::GetServiceUuuids32(std::vector& uuids) const { bool EirData::GetTxPowerLevel(std::vector& tx_power_level) const { for (const auto& gap_data : gap_data_) { if (gap_data.data_type_ == hci::GapDataType::TX_POWER_LEVEL) { - if (gap_data.data_.size() == 1U) + if (gap_data.data_.size() == 1U) { tx_power_level.push_back(static_cast(gap_data.data_[0])); + } } } return !tx_power_level.empty(); diff --git a/system/gd/discovery/device/eir_data.h b/system/gd/discovery/device/eir_data.h index d4752aec18c..90657cdeaff 100644 --- a/system/gd/discovery/device/eir_data.h +++ b/system/gd/discovery/device/eir_data.h @@ -37,7 +37,7 @@ struct service_uuid32_t { }; class EirData : public DataParser { - public: +public: EirData(const std::vector& data); bool GetCompleteNames(std::vector>&) const; diff --git a/system/gd/discovery/device/eir_data_unittest.cc b/system/gd/discovery/device/eir_data_unittest.cc index 681dfd69bd8..202e4aad6ad 100644 --- a/system/gd/discovery/device/eir_data_unittest.cc +++ b/system/gd/discovery/device/eir_data_unittest.cc @@ -29,9 +29,9 @@ using bluetooth::discovery::device::EirData; namespace { constexpr uint8_t kPartialUuid16Data[] = { - 0x2, static_cast(hci::GapDataType::COMPLETE_LIST_16_BIT_UUIDS), 0x34}; + 0x2, static_cast(hci::GapDataType::COMPLETE_LIST_16_BIT_UUIDS), 0x34}; constexpr uint8_t kOneUuid16Data[] = { - 0x3, static_cast(hci::GapDataType::COMPLETE_LIST_16_BIT_UUIDS), 0x34, 0x12}; + 0x3, static_cast(hci::GapDataType::COMPLETE_LIST_16_BIT_UUIDS), 0x34, 0x12}; constexpr char kAudiMmi9962[] = "Audi_MMI_9962"; constexpr char kChromeBoxForMeetings[] = "Chromebox for Meetings"; @@ -52,8 +52,8 @@ void LogUuids128(const std::vector& uuids128) { } // namespace debug TEST(EirDataTest, partial_uuid16) { - const EirData eir_data( - std::vector(kPartialUuid16Data, kPartialUuid16Data + sizeof(kPartialUuid16Data))); + const EirData eir_data(std::vector(kPartialUuid16Data, + kPartialUuid16Data + sizeof(kPartialUuid16Data))); std::vector uuids; ASSERT_FALSE(eir_data.GetUuids16(uuids)); @@ -61,7 +61,7 @@ TEST(EirDataTest, partial_uuid16) { TEST(EirDataTest, one_uuid16) { const EirData eir_data( - std::vector(kOneUuid16Data, kOneUuid16Data + sizeof(kOneUuid16Data))); + std::vector(kOneUuid16Data, kOneUuid16Data + sizeof(kOneUuid16Data))); std::vector uuids; ASSERT_TRUE(eir_data.GetUuids16(uuids)); @@ -192,14 +192,14 @@ TEST(EirDataTest, test_select_packets__pktAsha) { ASSERT_EQ(10, tx_power_level[0]); const std::vector v1 = - std::vector({0x01, 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x6c, 0x00}); + std::vector({0x01, 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x6c, 0x00}); std::vector> device_ids; ASSERT_TRUE(eir_data.GetDeviceId(device_ids)); ASSERT_EQ(v1.size(), device_ids[0].size()); ASSERT_THAT(v1, testing::ContainerEq(device_ids[0])); const std::vector v2 = - std::vector({0x1800, 0x1801, 0x180a, 0x110e, 0x110c, 0x111f, 0x110a}); + std::vector({0x1800, 0x1801, 0x180a, 0x110e, 0x110c, 0x111f, 0x110a}); std::vector uuids16; ASSERT_TRUE(eir_data.GetUuids16(uuids16)); ASSERT_EQ(v2.size(), uuids16.size()); diff --git a/system/gd/discovery/device/eir_test_data_packets.cc b/system/gd/discovery/device/eir_test_data_packets.cc index cf2a21c99f4..db37ff24304 100644 --- a/system/gd/discovery/device/eir_test_data_packets.cc +++ b/system/gd/discovery/device/eir_test_data_packets.cc @@ -20,13483 +20,13480 @@ // Frame (258 bytes) static const unsigned char pkt34638[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x0b, 0x7e, 0x2c, 0x2d, // ./...~,- - 0x7c, 0x00, 0x01, 0x00, 0x3c, 0x04, 0x0c, 0xba, // |...<... - 0x0a, 0x9c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x0b, 0x7e, 0x2c, 0x2d, // ./...~,- + 0x7c, 0x00, 0x01, 0x00, 0x3c, 0x04, 0x0c, 0xba, // |...<... + 0x0a, 0x9c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt34639[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x16, 0xaa, 0x9c, 0x85, // ./...... - 0x5a, 0x88, 0x01, 0x00, 0x08, 0x04, 0x34, 0xc7, // Z.....4. - 0x71, 0xc0, 0x1d, 0x03, 0x2e, 0x11, 0x05, 0x11, // q....... - 0x00, 0x12, 0x00, 0x18, 0x01, 0x18, 0x4c, 0xfe, // ......L. - 0x0e, 0x11, 0x0f, 0x11, 0x0c, 0x11, 0x0b, 0x11, // ........ - 0x1e, 0x11, 0x03, 0x12, 0x1f, 0x11, 0x0a, 0x18, // ........ - 0x01, 0x05, 0x31, 0x07, 0xff, 0xca, 0xca, 0xde, // ..1..... - 0xaf, 0xde, 0xca, 0xde, 0xde, 0xfa, 0xca, 0xde, // ........ - 0x00, 0x00, 0x00, 0x00, 0x66, 0x9a, 0x0c, 0x20, // ....f.. - 0x00, 0x08, 0xf4, 0xbd, 0xe6, 0x11, 0xcb, 0x52, // .......R - 0x00, 0x7a, 0xe1, 0x4d, 0xd3, 0x1f, 0xbf, 0x50, // .z.M...P - 0x5d, 0x57, 0x27, 0x97, 0xa2, 0x40, 0x41, 0xcd, // ]W'..@A. - 0x48, 0x43, 0x88, 0xec, 0x02, 0x0a, 0x04, 0x0e, // HC...... - 0x09, 0x41, 0x75, 0x64, 0x69, 0x5f, 0x4d, 0x4d, // .Audi_MM - 0x49, 0x5f, 0x39, 0x39, 0x36, 0x32, 0x00, 0x00, // I_9962.. - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x16, 0xaa, 0x9c, 0x85, // ./...... + 0x5a, 0x88, 0x01, 0x00, 0x08, 0x04, 0x34, 0xc7, // Z.....4. + 0x71, 0xc0, 0x1d, 0x03, 0x2e, 0x11, 0x05, 0x11, // q....... + 0x00, 0x12, 0x00, 0x18, 0x01, 0x18, 0x4c, 0xfe, // ......L. + 0x0e, 0x11, 0x0f, 0x11, 0x0c, 0x11, 0x0b, 0x11, // ........ + 0x1e, 0x11, 0x03, 0x12, 0x1f, 0x11, 0x0a, 0x18, // ........ + 0x01, 0x05, 0x31, 0x07, 0xff, 0xca, 0xca, 0xde, // ..1..... + 0xaf, 0xde, 0xca, 0xde, 0xde, 0xfa, 0xca, 0xde, // ........ + 0x00, 0x00, 0x00, 0x00, 0x66, 0x9a, 0x0c, 0x20, // ....f.. + 0x00, 0x08, 0xf4, 0xbd, 0xe6, 0x11, 0xcb, 0x52, // .......R + 0x00, 0x7a, 0xe1, 0x4d, 0xd3, 0x1f, 0xbf, 0x50, // .z.M...P + 0x5d, 0x57, 0x27, 0x97, 0xa2, 0x40, 0x41, 0xcd, // ]W'..@A. + 0x48, 0x43, 0x88, 0xec, 0x02, 0x0a, 0x04, 0x0e, // HC...... + 0x09, 0x41, 0x75, 0x64, 0x69, 0x5f, 0x4d, 0x4d, // .Audi_MM + 0x49, 0x5f, 0x39, 0x39, 0x36, 0x32, 0x00, 0x00, // I_9962.. + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt2048[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x2f, 0xa9, 0x08, 0x71, // ./../..q - 0xeb, 0x50, 0x01, 0x00, 0x04, 0x01, 0x48, 0xb9, // .P....H. - 0x57, 0x7f, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // W...Chro - 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo - 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin - 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... - 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x6c, 0x00, 0x0f, // .....l.. - 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ - 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x2f, 0xa9, 0x08, 0x71, // ./../..q + 0xeb, 0x50, 0x01, 0x00, 0x04, 0x01, 0x48, 0xb9, // .P....H. + 0x57, 0x7f, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // W...Chro + 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo + 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin + 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... + 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x6c, 0x00, 0x0f, // .....l.. + 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ + 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt2062[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x97, 0xa8, 0x0a, 0x71, // ./.....q - 0xeb, 0x50, 0x01, 0x00, 0x04, 0x01, 0x48, 0x49, // .P....HI - 0x42, 0x7f, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // B...Chro - 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo - 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin - 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... - 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x67, 0x00, 0x0f, // .....g.. - 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ - 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x97, 0xa8, 0x0a, 0x71, // ./.....q + 0xeb, 0x50, 0x01, 0x00, 0x04, 0x01, 0x48, 0x49, // .P....HI + 0x42, 0x7f, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // B...Chro + 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo + 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin + 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... + 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x67, 0x00, 0x0f, // .....g.. + 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ + 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt2063[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x4f, 0xd1, 0xf1, 0x2a, // ./..O..* - 0x9a, 0xb8, 0x01, 0x00, 0x04, 0x01, 0x48, 0x5e, // ......H^ - 0x43, 0x7f, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // C...Chro - 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo - 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin - 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... - 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x6c, 0x00, 0x0f, // .....l.. - 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ - 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x4f, 0xd1, 0xf1, 0x2a, // ./..O..* + 0x9a, 0xb8, 0x01, 0x00, 0x04, 0x01, 0x48, 0x5e, // ......H^ + 0x43, 0x7f, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // C...Chro + 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo + 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin + 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... + 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x6c, 0x00, 0x0f, // .....l.. + 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ + 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt2064[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x4f, 0xd1, 0xf1, 0x2a, // ./..O..* - 0x9a, 0xb8, 0x01, 0x00, 0x04, 0x01, 0x48, 0x5e, // ......H^ - 0x43, 0x7f, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // C...Chro - 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo - 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin - 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... - 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x6c, 0x00, 0x0f, // .....l.. - 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ - 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x4f, 0xd1, 0xf1, 0x2a, // ./..O..* + 0x9a, 0xb8, 0x01, 0x00, 0x04, 0x01, 0x48, 0x5e, // ......H^ + 0x43, 0x7f, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // C...Chro + 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo + 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin + 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... + 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x6c, 0x00, 0x0f, // .....l.. + 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ + 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt2067[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x9c, 0xa1, 0x20, 0x23, // ./.... # - 0xce, 0xf4, 0x01, 0x00, 0x04, 0x01, 0x48, 0x93, // ......H. - 0x36, 0x7f, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // 6...Chro - 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo - 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin - 0x67, 0x73, 0x02, 0x0a, 0x0c, 0x09, 0x10, 0x01, // gs...... - 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x67, 0x00, 0x0f, // .....g.. - 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ - 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x9c, 0xa1, 0x20, 0x23, // ./.... # + 0xce, 0xf4, 0x01, 0x00, 0x04, 0x01, 0x48, 0x93, // ......H. + 0x36, 0x7f, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // 6...Chro + 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo + 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin + 0x67, 0x73, 0x02, 0x0a, 0x0c, 0x09, 0x10, 0x01, // gs...... + 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x67, 0x00, 0x0f, // .....g.. + 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ + 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt2072[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xc6, 0x4b, 0xd8, 0xb6, // ./...K.. - 0x80, 0x5c, 0x01, 0x00, 0x04, 0x01, 0x48, 0xfb, // .\....H. - 0x41, 0x7f, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // A...Chro - 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo - 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin - 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... - 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x67, 0x00, 0x0f, // .....g.. - 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ - 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xc6, 0x4b, 0xd8, 0xb6, // ./...K.. + 0x80, 0x5c, 0x01, 0x00, 0x04, 0x01, 0x48, 0xfb, // .\....H. + 0x41, 0x7f, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // A...Chro + 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo + 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin + 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... + 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x67, 0x00, 0x0f, // .....g.. + 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ + 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt2075[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x77, 0x08, 0x25, 0x99, // ./..w.%. - 0xec, 0x40, 0x01, 0x00, 0x04, 0x01, 0x48, 0xf4, // .@....H. - 0x18, 0x7f, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // ....Chro - 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo - 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin - 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... - 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x67, 0x00, 0x0f, // .....g.. - 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ - 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x77, 0x08, 0x25, 0x99, // ./..w.%. + 0xec, 0x40, 0x01, 0x00, 0x04, 0x01, 0x48, 0xf4, // .@....H. + 0x18, 0x7f, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // ....Chro + 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo + 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin + 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... + 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x67, 0x00, 0x0f, // .....g.. + 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ + 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt2076[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xc4, 0x8d, 0x25, 0x99, // ./....%. - 0xec, 0x40, 0x01, 0x00, 0x04, 0x01, 0x48, 0x41, // .@....HA - 0x5d, 0x7f, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // ]...Chro - 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo - 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin - 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... - 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x6c, 0x00, 0x0f, // .....l.. - 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ - 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xc4, 0x8d, 0x25, 0x99, // ./....%. + 0xec, 0x40, 0x01, 0x00, 0x04, 0x01, 0x48, 0x41, // .@....HA + 0x5d, 0x7f, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // ]...Chro + 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo + 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin + 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... + 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x6c, 0x00, 0x0f, // .....l.. + 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ + 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt19189[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xc6, 0x4b, 0xd8, 0xb6, // ./...K.. - 0x80, 0x5c, 0x01, 0x00, 0x04, 0x01, 0x48, 0xfa, // .\....H. - 0x41, 0x7f, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // A...Chro - 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo - 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin - 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... - 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x67, 0x00, 0x0f, // .....g.. - 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ - 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xc6, 0x4b, 0xd8, 0xb6, // ./...K.. + 0x80, 0x5c, 0x01, 0x00, 0x04, 0x01, 0x48, 0xfa, // .\....H. + 0x41, 0x7f, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // A...Chro + 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo + 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin + 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... + 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x67, 0x00, 0x0f, // .....g.. + 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ + 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt19190[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xf6, 0x8b, 0xf4, 0x2a, // ./.....* - 0x9a, 0xb8, 0x01, 0x00, 0x04, 0x01, 0x48, 0xfc, // ......H. - 0x75, 0x7f, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // u...Chro - 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo - 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin - 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... - 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x67, 0x00, 0x0f, // .....g.. - 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ - 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xf6, 0x8b, 0xf4, 0x2a, // ./.....* + 0x9a, 0xb8, 0x01, 0x00, 0x04, 0x01, 0x48, 0xfc, // ......H. + 0x75, 0x7f, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // u...Chro + 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo + 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin + 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... + 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x67, 0x00, 0x0f, // .....g.. + 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ + 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt19191[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x77, 0x08, 0x25, 0x99, // ./..w.%. - 0xec, 0x40, 0x01, 0x00, 0x04, 0x01, 0x48, 0xf2, // .@....H. - 0x18, 0x7f, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // ....Chro - 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo - 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin - 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... - 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x67, 0x00, 0x0f, // .....g.. - 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ - 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x77, 0x08, 0x25, 0x99, // ./..w.%. + 0xec, 0x40, 0x01, 0x00, 0x04, 0x01, 0x48, 0xf2, // .@....H. + 0x18, 0x7f, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // ....Chro + 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo + 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin + 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... + 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x67, 0x00, 0x0f, // .....g.. + 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ + 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt19192[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x2f, 0xa9, 0x08, 0x71, // ./../..q - 0xeb, 0x50, 0x01, 0x00, 0x04, 0x01, 0x48, 0xb8, // .P....H. - 0x57, 0x7f, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // W...Chro - 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo - 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin - 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... - 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x6c, 0x00, 0x0f, // .....l.. - 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ - 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x2f, 0xa9, 0x08, 0x71, // ./../..q + 0xeb, 0x50, 0x01, 0x00, 0x04, 0x01, 0x48, 0xb8, // .P....H. + 0x57, 0x7f, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // W...Chro + 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo + 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin + 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... + 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x6c, 0x00, 0x0f, // .....l.. + 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ + 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt19193[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x4f, 0xd1, 0xf1, 0x2a, // ./..O..* - 0x9a, 0xb8, 0x01, 0x00, 0x04, 0x01, 0x48, 0x5c, // ......H - 0x43, 0x7f, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // C...Chro - 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo - 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin - 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... - 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x6c, 0x00, 0x0f, // .....l.. - 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ - 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x4f, 0xd1, 0xf1, 0x2a, // ./..O..* + 0x9a, 0xb8, 0x01, 0x00, 0x04, 0x01, 0x48, 0x5c, // ......H + 0x43, 0x7f, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // C...Chro + 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo + 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin + 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... + 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x6c, 0x00, 0x0f, // .....l.. + 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ + 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt19194[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x5e, 0x64, 0xc3, 0x50, // ./..^d.P - 0x59, 0xa0, 0x01, 0x00, 0x04, 0x01, 0x48, 0xac, // Y.....H. - 0x5a, 0x7f, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // Z...Chro - 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo - 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin - 0x67, 0x73, 0x02, 0x0a, 0x0c, 0x09, 0x10, 0x01, // gs...... - 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x67, 0x00, 0x0f, // .....g.. - 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ - 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x5e, 0x64, 0xc3, 0x50, // ./..^d.P + 0x59, 0xa0, 0x01, 0x00, 0x04, 0x01, 0x48, 0xac, // Y.....H. + 0x5a, 0x7f, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // Z...Chro + 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo + 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin + 0x67, 0x73, 0x02, 0x0a, 0x0c, 0x09, 0x10, 0x01, // gs...... + 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x67, 0x00, 0x0f, // .....g.. + 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ + 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt19198[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xf1, 0xaf, 0xf3, 0x2a, // ./.....* - 0x9a, 0xb8, 0x01, 0x00, 0x04, 0x01, 0x48, 0xba, // ......H. - 0x10, 0x7f, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // ....Chro - 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo - 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin - 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... - 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x6c, 0x00, 0x0f, // .....l.. - 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ - 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xf1, 0xaf, 0xf3, 0x2a, // ./.....* + 0x9a, 0xb8, 0x01, 0x00, 0x04, 0x01, 0x48, 0xba, // ......H. + 0x10, 0x7f, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // ....Chro + 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo + 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin + 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... + 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x6c, 0x00, 0x0f, // .....l.. + 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ + 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt19200[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x98, 0xa7, 0xcd, 0xd2, // ./...... - 0x96, 0x7c, 0x01, 0x00, 0x18, 0x04, 0x24, 0x21, // .|....$! - 0x55, 0x7f, 0x09, 0x10, 0x01, 0x00, 0x0a, 0x00, // U....... - 0xff, 0xff, 0xff, 0xff, 0x02, 0x0a, 0x04, 0x0f, // ........ - 0x02, 0x0d, 0x11, 0x0b, 0x11, 0x0e, 0x11, 0x0f, // ........ - 0x11, 0x1e, 0x11, 0x08, 0x11, 0x31, 0x11, 0x06, // .....1.. - 0x09, 0x41, 0x63, 0x72, 0x75, 0x78, 0x00, 0x00, // .Acrux.. - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x98, 0xa7, 0xcd, 0xd2, // ./...... + 0x96, 0x7c, 0x01, 0x00, 0x18, 0x04, 0x24, 0x21, // .|....$! + 0x55, 0x7f, 0x09, 0x10, 0x01, 0x00, 0x0a, 0x00, // U....... + 0xff, 0xff, 0xff, 0xff, 0x02, 0x0a, 0x04, 0x0f, // ........ + 0x02, 0x0d, 0x11, 0x0b, 0x11, 0x0e, 0x11, 0x0f, // ........ + 0x11, 0x1e, 0x11, 0x08, 0x11, 0x31, 0x11, 0x06, // .....1.. + 0x09, 0x41, 0x63, 0x72, 0x75, 0x78, 0x00, 0x00, // .Acrux.. + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt19201[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x1d, 0xee, 0x9d, 0xdf, // ./...... - 0xcc, 0x90, 0x01, 0x00, 0x04, 0x01, 0x48, 0x76, // ......Hv - 0x1b, 0x7f, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // ....Chro - 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo - 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin - 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... - 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x67, 0x00, 0x0f, // .....g.. - 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ - 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x1d, 0xee, 0x9d, 0xdf, // ./...... + 0xcc, 0x90, 0x01, 0x00, 0x04, 0x01, 0x48, 0x76, // ......Hv + 0x1b, 0x7f, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // ....Chro + 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo + 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin + 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... + 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x67, 0x00, 0x0f, // .....g.. + 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ + 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt19835[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xc6, 0x4b, 0xd8, 0xb6, // ./...K.. - 0x80, 0x5c, 0x01, 0x00, 0x04, 0x01, 0x48, 0xfa, // .\....H. - 0x41, 0xbe, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // A...Chro - 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo - 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin - 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... - 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x67, 0x00, 0x0f, // .....g.. - 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ - 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xc6, 0x4b, 0xd8, 0xb6, // ./...K.. + 0x80, 0x5c, 0x01, 0x00, 0x04, 0x01, 0x48, 0xfa, // .\....H. + 0x41, 0xbe, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // A...Chro + 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo + 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin + 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... + 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x67, 0x00, 0x0f, // .....g.. + 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ + 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt19844[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xf6, 0x8b, 0xf4, 0x2a, // ./.....* - 0x9a, 0xb8, 0x01, 0x00, 0x04, 0x01, 0x48, 0xfb, // ......H. - 0x75, 0xb5, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // u...Chro - 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo - 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin - 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... - 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x67, 0x00, 0x0f, // .....g.. - 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ - 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xf6, 0x8b, 0xf4, 0x2a, // ./.....* + 0x9a, 0xb8, 0x01, 0x00, 0x04, 0x01, 0x48, 0xfb, // ......H. + 0x75, 0xb5, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // u...Chro + 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo + 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin + 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... + 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x67, 0x00, 0x0f, // .....g.. + 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ + 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt19845[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x77, 0x08, 0x25, 0x99, // ./..w.%. - 0xec, 0x40, 0x01, 0x00, 0x04, 0x01, 0x48, 0xf2, // .@....H. - 0x18, 0xb3, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // ....Chro - 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo - 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin - 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... - 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x67, 0x00, 0x0f, // .....g.. - 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ - 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x77, 0x08, 0x25, 0x99, // ./..w.%. + 0xec, 0x40, 0x01, 0x00, 0x04, 0x01, 0x48, 0xf2, // .@....H. + 0x18, 0xb3, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // ....Chro + 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo + 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin + 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... + 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x67, 0x00, 0x0f, // .....g.. + 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ + 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt19846[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x21, 0x51, 0xeb, 0xd5, // ./..!Q.. - 0xab, 0xd0, 0x01, 0x00, 0x04, 0x01, 0x48, 0x99, // ......H. - 0x06, 0xc6, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // ....Chro - 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo - 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin - 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... - 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x67, 0x00, 0x0f, // .....g.. - 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ - 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x21, 0x51, 0xeb, 0xd5, // ./..!Q.. + 0xab, 0xd0, 0x01, 0x00, 0x04, 0x01, 0x48, 0x99, // ......H. + 0x06, 0xc6, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // ....Chro + 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo + 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin + 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... + 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x67, 0x00, 0x0f, // .....g.. + 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ + 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt19857[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xdc, 0xd0, 0xf1, 0x2a, // ./.....* - 0x9a, 0xb8, 0x01, 0x00, 0x04, 0x01, 0x48, 0xbb, // ......H. - 0x6b, 0x13, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // k...Chro - 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo - 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin - 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... - 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x6c, 0x00, 0x0f, // .....l.. - 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ - 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xdc, 0xd0, 0xf1, 0x2a, // ./.....* + 0x9a, 0xb8, 0x01, 0x00, 0x04, 0x01, 0x48, 0xbb, // ......H. + 0x6b, 0x13, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // k...Chro + 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo + 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin + 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... + 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x6c, 0x00, 0x0f, // .....l.. + 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ + 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt19863[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x4f, 0xd1, 0xf1, 0x2a, // ./..O..* - 0x9a, 0xb8, 0x01, 0x00, 0x04, 0x01, 0x48, 0x5c, // ......H - 0x43, 0xb7, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // C...Chro - 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo - 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin - 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... - 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x6c, 0x00, 0x0f, // .....l.. - 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ - 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x4f, 0xd1, 0xf1, 0x2a, // ./..O..* + 0x9a, 0xb8, 0x01, 0x00, 0x04, 0x01, 0x48, 0x5c, // ......H + 0x43, 0xb7, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // C...Chro + 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo + 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin + 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... + 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x6c, 0x00, 0x0f, // .....l.. + 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ + 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt19871[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xf1, 0xaf, 0xf3, 0x2a, // ./.....* - 0x9a, 0xb8, 0x01, 0x00, 0x04, 0x01, 0x48, 0xb8, // ......H. - 0x10, 0xaf, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // ....Chro - 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo - 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin - 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... - 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x6c, 0x00, 0x0f, // .....l.. - 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ - 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xf1, 0xaf, 0xf3, 0x2a, // ./.....* + 0x9a, 0xb8, 0x01, 0x00, 0x04, 0x01, 0x48, 0xb8, // ......H. + 0x10, 0xaf, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // ....Chro + 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo + 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin + 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... + 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x6c, 0x00, 0x0f, // .....l.. + 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ + 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt19885[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xa1, 0x7b, 0x78, 0x83, // ./...{x. - 0xf8, 0xd8, 0x01, 0x00, 0x04, 0x01, 0x48, 0x80, // ......H. - 0x7f, 0xae, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // ....Chro - 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo - 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin - 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... - 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x67, 0x00, 0x0f, // .....g.. - 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ - 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xa1, 0x7b, 0x78, 0x83, // ./...{x. + 0xf8, 0xd8, 0x01, 0x00, 0x04, 0x01, 0x48, 0x80, // ......H. + 0x7f, 0xae, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // ....Chro + 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo + 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin + 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... + 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x67, 0x00, 0x0f, // .....g.. + 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ + 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt19886[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x1d, 0xee, 0x9d, 0xdf, // ./...... - 0xcc, 0x90, 0x01, 0x00, 0x04, 0x01, 0x48, 0x75, // ......Hu - 0x1b, 0xa7, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // ....Chro - 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo - 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin - 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... - 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x67, 0x00, 0x0f, // .....g.. - 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ - 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x1d, 0xee, 0x9d, 0xdf, // ./...... + 0xcc, 0x90, 0x01, 0x00, 0x04, 0x01, 0x48, 0x75, // ......Hu + 0x1b, 0xa7, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // ....Chro + 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo + 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin + 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... + 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x67, 0x00, 0x0f, // .....g.. + 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ + 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt19898[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xe0, 0x76, 0x2f, 0xd5, // ./...v/. - 0xab, 0xd0, 0x01, 0x00, 0x04, 0x01, 0x48, 0xcc, // ......H. - 0x13, 0xad, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // ....Chro - 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo - 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin - 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... - 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x67, 0x00, 0x0f, // .....g.. - 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ - 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xe0, 0x76, 0x2f, 0xd5, // ./...v/. + 0xab, 0xd0, 0x01, 0x00, 0x04, 0x01, 0x48, 0xcc, // ......H. + 0x13, 0xad, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // ....Chro + 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo + 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin + 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... + 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x67, 0x00, 0x0f, // .....g.. + 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ + 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt19899[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x87, 0xa8, 0xf1, 0x2a, // ./.....* - 0x9a, 0xb8, 0x01, 0x00, 0x04, 0x01, 0x48, 0xf1, // ......H. - 0x15, 0xa7, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // ....Chro - 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo - 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin - 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... - 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x67, 0x00, 0x0f, // .....g.. - 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ - 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x87, 0xa8, 0xf1, 0x2a, // ./.....* + 0x9a, 0xb8, 0x01, 0x00, 0x04, 0x01, 0x48, 0xf1, // ......H. + 0x15, 0xa7, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // ....Chro + 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo + 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin + 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... + 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x67, 0x00, 0x0f, // .....g.. + 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ + 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt19904[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x09, 0x1e, 0x87, 0x83, // ./...... - 0xf8, 0xd8, 0x01, 0x00, 0x04, 0x01, 0x48, 0x1b, // ......H. - 0x4d, 0x9f, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // M...Chro - 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo - 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin - 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... - 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x67, 0x00, 0x0f, // .....g.. - 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ - 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x09, 0x1e, 0x87, 0x83, // ./...... + 0xf8, 0xd8, 0x01, 0x00, 0x04, 0x01, 0x48, 0x1b, // ......H. + 0x4d, 0x9f, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // M...Chro + 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo + 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin + 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... + 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x67, 0x00, 0x0f, // .....g.. + 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ + 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt19908[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xc4, 0x8d, 0x25, 0x99, // ./....%. - 0xec, 0x40, 0x01, 0x00, 0x04, 0x01, 0x48, 0x40, // .@....H@ - 0x5d, 0xb5, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // ]...Chro - 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo - 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin - 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... - 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x6c, 0x00, 0x0f, // .....l.. - 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ - 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xc4, 0x8d, 0x25, 0x99, // ./....%. + 0xec, 0x40, 0x01, 0x00, 0x04, 0x01, 0x48, 0x40, // .@....H@ + 0x5d, 0xb5, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // ]...Chro + 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo + 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin + 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... + 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x6c, 0x00, 0x0f, // .....l.. + 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ + 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt33190[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x98, 0xa7, 0xcd, 0xd2, // ./...... - 0x96, 0x7c, 0x01, 0x00, 0x18, 0x04, 0x24, 0xc0, // .|....$. - 0x46, 0xd1, 0x09, 0x10, 0x01, 0x00, 0x0a, 0x00, // F....... - 0xff, 0xff, 0xff, 0xff, 0x02, 0x0a, 0x04, 0x0f, // ........ - 0x02, 0x0d, 0x11, 0x0b, 0x11, 0x0e, 0x11, 0x0f, // ........ - 0x11, 0x1e, 0x11, 0x08, 0x11, 0x31, 0x11, 0x06, // .....1.. - 0x09, 0x41, 0x63, 0x72, 0x75, 0x78, 0x00, 0x00, // .Acrux.. - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x98, 0xa7, 0xcd, 0xd2, // ./...... + 0x96, 0x7c, 0x01, 0x00, 0x18, 0x04, 0x24, 0xc0, // .|....$. + 0x46, 0xd1, 0x09, 0x10, 0x01, 0x00, 0x0a, 0x00, // F....... + 0xff, 0xff, 0xff, 0xff, 0x02, 0x0a, 0x04, 0x0f, // ........ + 0x02, 0x0d, 0x11, 0x0b, 0x11, 0x0e, 0x11, 0x0f, // ........ + 0x11, 0x1e, 0x11, 0x08, 0x11, 0x31, 0x11, 0x06, // .....1.. + 0x09, 0x41, 0x63, 0x72, 0x75, 0x78, 0x00, 0x00, // .Acrux.. + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt33191[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x1a, 0x02, 0xd8, 0xb6, // ./...... - 0x80, 0x5c, 0x01, 0x00, 0x04, 0x01, 0x48, 0xff, // .\....H. - 0x06, 0xa4, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // ....Chro - 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo - 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin - 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... - 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x6c, 0x00, 0x0f, // .....l.. - 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ - 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x1a, 0x02, 0xd8, 0xb6, // ./...... + 0x80, 0x5c, 0x01, 0x00, 0x04, 0x01, 0x48, 0xff, // .\....H. + 0x06, 0xa4, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // ....Chro + 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo + 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin + 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... + 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x6c, 0x00, 0x0f, // .....l.. + 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ + 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt33217[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xc4, 0x8d, 0x25, 0x99, // ./....%. - 0xec, 0x40, 0x01, 0x00, 0x04, 0x01, 0x48, 0x3f, // .@....H? - 0x5d, 0xb6, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // ]...Chro - 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo - 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin - 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... - 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x6c, 0x00, 0x0f, // .....l.. - 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ - 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xc4, 0x8d, 0x25, 0x99, // ./....%. + 0xec, 0x40, 0x01, 0x00, 0x04, 0x01, 0x48, 0x3f, // .@....H? + 0x5d, 0xb6, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // ]...Chro + 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo + 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin + 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... + 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x6c, 0x00, 0x0f, // .....l.. + 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ + 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt34019[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xa1, 0x7b, 0x78, 0x83, // ./...{x. - 0xf8, 0xd8, 0x01, 0x00, 0x04, 0x01, 0x48, 0x7e, // ......H~ - 0x7f, 0xa9, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // ....Chro - 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo - 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin - 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... - 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x67, 0x00, 0x0f, // .....g.. - 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ - 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xa1, 0x7b, 0x78, 0x83, // ./...{x. + 0xf8, 0xd8, 0x01, 0x00, 0x04, 0x01, 0x48, 0x7e, // ......H~ + 0x7f, 0xa9, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // ....Chro + 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo + 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin + 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... + 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x67, 0x00, 0x0f, // .....g.. + 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ + 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt34020[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x98, 0xa7, 0xcd, 0xd2, // ./...... - 0x96, 0x7c, 0x01, 0x00, 0x18, 0x04, 0x24, 0xa7, // .|....$. - 0x42, 0xd0, 0x09, 0x10, 0x01, 0x00, 0x0a, 0x00, // B....... - 0xff, 0xff, 0xff, 0xff, 0x02, 0x0a, 0x04, 0x0f, // ........ - 0x02, 0x0d, 0x11, 0x0b, 0x11, 0x0e, 0x11, 0x0f, // ........ - 0x11, 0x1e, 0x11, 0x08, 0x11, 0x31, 0x11, 0x06, // .....1.. - 0x09, 0x41, 0x63, 0x72, 0x75, 0x78, 0x00, 0x00, // .Acrux.. - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x98, 0xa7, 0xcd, 0xd2, // ./...... + 0x96, 0x7c, 0x01, 0x00, 0x18, 0x04, 0x24, 0xa7, // .|....$. + 0x42, 0xd0, 0x09, 0x10, 0x01, 0x00, 0x0a, 0x00, // B....... + 0xff, 0xff, 0xff, 0xff, 0x02, 0x0a, 0x04, 0x0f, // ........ + 0x02, 0x0d, 0x11, 0x0b, 0x11, 0x0e, 0x11, 0x0f, // ........ + 0x11, 0x1e, 0x11, 0x08, 0x11, 0x31, 0x11, 0x06, // .....1.. + 0x09, 0x41, 0x63, 0x72, 0x75, 0x78, 0x00, 0x00, // .Acrux.. + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt19975[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x72, 0x5f, 0x1e, 0x2a, // ./..r_.* - 0x9a, 0xb8, 0x01, 0x00, 0x04, 0x01, 0x48, 0xa0, // ......H. - 0x04, 0xa9, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // ....Chro - 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo - 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin - 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... - 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x6c, 0x00, 0x0f, // .....l.. - 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ - 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x72, 0x5f, 0x1e, 0x2a, // ./..r_.* + 0x9a, 0xb8, 0x01, 0x00, 0x04, 0x01, 0x48, 0xa0, // ......H. + 0x04, 0xa9, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // ....Chro + 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo + 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin + 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... + 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x6c, 0x00, 0x0f, // .....l.. + 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ + 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt19988[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x03, 0xe3, 0x63, 0x83, // ./....c. - 0x1c, 0x40, 0x01, 0x00, 0x04, 0x01, 0x48, 0x2c, // .@....H, - 0x27, 0xaf, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // '...Chro - 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo - 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin - 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... - 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x72, 0x00, 0x0f, // .....r.. - 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ - 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x03, 0xe3, 0x63, 0x83, // ./....c. + 0x1c, 0x40, 0x01, 0x00, 0x04, 0x01, 0x48, 0x2c, // .@....H, + 0x27, 0xaf, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // '...Chro + 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo + 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin + 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... + 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x72, 0x00, 0x0f, // .....r.. + 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ + 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt20036[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x83, 0x35, 0x3c, 0x4b, // ./...5.. - 0x01, 0x07, 0xe1, 0xb5, 0x0b, 0x70, 0x00, 0x00, // .....p.. - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xa8, 0xc7, 0xb3, 0x4b, // ./.....K + 0x04, 0x00, 0x01, 0x00, 0x24, 0x04, 0x28, 0x32, // ....$.(2 + 0x27, 0x7f, 0x07, 0x09, 0x53, 0x68, 0x69, 0x65, // '...Shie + 0x6c, 0x64, 0xff, 0x11, 0x00, 0x00, 0x00, 0x00, // ld...... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x24, // .......$ + 0xb8, 0xcb, 0xed, 0x03, 0xe5, 0x3e, 0x01, 0x05, // .....>.. + 0x01, 0x07, 0xe1, 0xb5, 0x0b, 0x70, 0x00, 0x00, // .....p.. + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt29927[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x4c, 0xd6, 0x93, 0xd5, // ./..L... - 0xd6, 0x48, 0x01, 0x00, 0x00, 0x04, 0x24, 0x78, // .H....$x - 0x79, 0xc3, 0x07, 0x09, 0x53, 0x68, 0x69, 0x65, // y...Shie - 0x6c, 0x64, 0xff, 0x11, 0x00, 0x00, 0x00, 0x00, // ld...... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x24, // .......$ - 0xb8, 0xcb, 0xed, 0x03, 0xe5, 0x3e, 0x01, 0x05, // .....>.. - 0x01, 0x07, 0xe1, 0xb5, 0x0b, 0x70, 0x00, 0x00, // .....p.. - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x4c, 0xd6, 0x93, 0xd5, // ./..L... + 0xd6, 0x48, 0x01, 0x00, 0x00, 0x04, 0x24, 0x78, // .H....$x + 0x79, 0xc3, 0x07, 0x09, 0x53, 0x68, 0x69, 0x65, // y...Shie + 0x6c, 0x64, 0xff, 0x11, 0x00, 0x00, 0x00, 0x00, // ld...... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x24, // .......$ + 0xb8, 0xcb, 0xed, 0x03, 0xe5, 0x3e, 0x01, 0x05, // .....>.. + 0x01, 0x07, 0xe1, 0xb5, 0x0b, 0x70, 0x00, 0x00, // .....p.. + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt29928[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xa8, 0xc7, 0xb3, 0x4b, // ./.....K - 0x04, 0x00, 0x01, 0x00, 0x24, 0x04, 0x28, 0x32, // ....$.(2 - 0x27, 0xc7, 0x07, 0x09, 0x53, 0x68, 0x69, 0x65, // '...Shie - 0x6c, 0x64, 0x09, 0x03, 0x0a, 0x11, 0x0c, 0x11, // ld...... - 0x0e, 0x11, 0x00, 0x12, 0x01, 0x05, 0x81, 0x07, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xa8, 0xc7, 0xb3, 0x4b, // ./.....K + 0x04, 0x00, 0x01, 0x00, 0x24, 0x04, 0x28, 0x32, // ....$.(2 + 0x27, 0xc7, 0x07, 0x09, 0x53, 0x68, 0x69, 0x65, // '...Shie + 0x6c, 0x64, 0x09, 0x03, 0x0a, 0x11, 0x0c, 0x11, // ld...... + 0x0e, 0x11, 0x00, 0x12, 0x01, 0x05, 0x81, 0x07, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt29931[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x4c, 0xd6, 0x93, 0xd5, // ./..L... - 0xd6, 0x48, 0x01, 0x00, 0x00, 0x04, 0x24, 0x78, // .H....$x - 0x79, 0xc8, 0x09, 0x09, 0x48, 0x6f, 0x6d, 0x65, // y...Home - 0x20, 0x4d, 0x61, 0x78, 0x09, 0x03, 0x0b, 0x11, // Max.... - 0x0c, 0x11, 0x0e, 0x11, 0x00, 0x12, 0x01, 0x05, // ........ - 0x01, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x4c, 0xd6, 0x93, 0xd5, // ./..L... + 0xd6, 0x48, 0x01, 0x00, 0x00, 0x04, 0x24, 0x78, // .H....$x + 0x79, 0xc8, 0x09, 0x09, 0x48, 0x6f, 0x6d, 0x65, // y...Home + 0x20, 0x4d, 0x61, 0x78, 0x09, 0x03, 0x0b, 0x11, // Max.... + 0x0c, 0x11, 0x0e, 0x11, 0x00, 0x12, 0x01, 0x05, // ........ + 0x01, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt23904[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xf9, 0xe8, 0xa0, 0x26, // ./.....& - 0xe5, 0xee, 0x01, 0x00, 0x04, 0x44, 0x24, 0x4b, // .....D$K - 0x1e, 0xb6, 0x0e, 0x09, 0x4c, 0x52, 0x31, 0x30, // ....LR10 - 0x5f, 0x4e, 0x46, 0x46, 0x5f, 0x65, 0x38, 0x66, // _NFF_e8f - 0x39, 0x09, 0x03, 0x0b, 0x11, 0x0c, 0x11, 0x0e, // 9....... - 0x11, 0x1e, 0x11, 0x51, 0x07, 0xb5, 0xf7, 0x08, // ...Q.... - 0xa7, 0x64, 0xf7, 0x51, 0x89, 0x4c, 0x4c, 0xce, // .d.Q.LL. - 0x24, 0xf7, 0x7f, 0xe9, 0x25, 0x7c, 0x92, 0x67, // $...%|.g - 0x4d, 0x2c, 0xf1, 0x86, 0x88, 0xdb, 0x4f, 0x15, // M,....O. - 0x25, 0x2c, 0xfe, 0x21, 0xdf, 0xb4, 0xf7, 0x08, // %,.!.... - 0xa7, 0x64, 0xf7, 0x51, 0x89, 0x4c, 0x4c, 0xce, // .d.Q.LL. - 0x24, 0xf7, 0x7f, 0xe9, 0x25, 0x85, 0x98, 0xa9, // $...%... - 0x83, 0x48, 0xfe, 0x2f, 0x85, 0x15, 0x41, 0xe5, // .H./..A. - 0xd5, 0x65, 0xcc, 0xe6, 0xfb, 0xf5, 0x21, 0x01, // .e....!. - 0xeb, 0x59, 0x9d, 0x19, 0x86, 0x36, 0x47, 0x26, // .Y...6G& - 0xce, 0xf0, 0x0b, 0x27, 0x4b, 0x00, 0x00, 0x00, // ...'K... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xf9, 0xe8, 0xa0, 0x26, // ./.....& + 0xe5, 0xee, 0x01, 0x00, 0x04, 0x44, 0x24, 0x4b, // .....D$K + 0x1e, 0xb6, 0x0e, 0x09, 0x4c, 0x52, 0x31, 0x30, // ....LR10 + 0x5f, 0x4e, 0x46, 0x46, 0x5f, 0x65, 0x38, 0x66, // _NFF_e8f + 0x39, 0x09, 0x03, 0x0b, 0x11, 0x0c, 0x11, 0x0e, // 9....... + 0x11, 0x1e, 0x11, 0x51, 0x07, 0xb5, 0xf7, 0x08, // ...Q.... + 0xa7, 0x64, 0xf7, 0x51, 0x89, 0x4c, 0x4c, 0xce, // .d.Q.LL. + 0x24, 0xf7, 0x7f, 0xe9, 0x25, 0x7c, 0x92, 0x67, // $...%|.g + 0x4d, 0x2c, 0xf1, 0x86, 0x88, 0xdb, 0x4f, 0x15, // M,....O. + 0x25, 0x2c, 0xfe, 0x21, 0xdf, 0xb4, 0xf7, 0x08, // %,.!.... + 0xa7, 0x64, 0xf7, 0x51, 0x89, 0x4c, 0x4c, 0xce, // .d.Q.LL. + 0x24, 0xf7, 0x7f, 0xe9, 0x25, 0x85, 0x98, 0xa9, // $...%... + 0x83, 0x48, 0xfe, 0x2f, 0x85, 0x15, 0x41, 0xe5, // .H./..A. + 0xd5, 0x65, 0xcc, 0xe6, 0xfb, 0xf5, 0x21, 0x01, // .e....!. + 0xeb, 0x59, 0x9d, 0x19, 0x86, 0x36, 0x47, 0x26, // .Y...6G& + 0xce, 0xf0, 0x0b, 0x27, 0x4b, 0x00, 0x00, 0x00, // ...'K... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt24033[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xf1, 0x53, 0xf3, 0xfe, // ./...S.. - 0x72, 0x70, 0x01, 0x00, 0x0c, 0x01, 0x28, 0xa0, // rp....(. - 0x2b, 0xc6, 0x1c, 0x09, 0x4d, 0x6f, 0x72, 0x74, // +...Mort - 0x65, 0x7a, 0x61, 0xe2, 0x80, 0x99, 0x73, 0x20, // eza...s - 0x4d, 0x61, 0x63, 0x42, 0x6f, 0x6f, 0x6b, 0x20, // MacBook - 0x50, 0x72, 0x6f, 0x20, 0x28, 0x32, 0x29, 0x0b, // Pro (2). - 0x03, 0x00, 0x12, 0x1f, 0x11, 0x0a, 0x11, 0x0c, // ........ - 0x11, 0x01, 0x18, 0x01, 0x05, 0x01, 0x07, 0x27, // .......' - 0xff, 0x00, 0x4c, 0x02, 0x24, 0x02, 0x00, 0x00, // ..L.$... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xf1, 0x53, 0xf3, 0xfe, // ./...S.. + 0x72, 0x70, 0x01, 0x00, 0x0c, 0x01, 0x28, 0xa0, // rp....(. + 0x2b, 0xc6, 0x1c, 0x09, 0x4d, 0x6f, 0x72, 0x74, // +...Mort + 0x65, 0x7a, 0x61, 0xe2, 0x80, 0x99, 0x73, 0x20, // eza...s + 0x4d, 0x61, 0x63, 0x42, 0x6f, 0x6f, 0x6b, 0x20, // MacBook + 0x50, 0x72, 0x6f, 0x20, 0x28, 0x32, 0x29, 0x0b, // Pro (2). + 0x03, 0x00, 0x12, 0x1f, 0x11, 0x0a, 0x11, 0x0c, // ........ + 0x11, 0x01, 0x18, 0x01, 0x05, 0x01, 0x07, 0x27, // .......' + 0xff, 0x00, 0x4c, 0x02, 0x24, 0x02, 0x00, 0x00, // ..L.$... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt24158[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x5c, 0xfa, 0x47, 0x2c, // ./..\.G, - 0x3a, 0xd4, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0x04, // :....BZ. - 0x72, 0xd6, 0x0b, 0x09, 0x48, 0x69, 0x20, 0x72, // r...Hi r - 0x65, 0x6e, 0x65, 0x73, 0x61, 0x73, 0x19, 0x03, // enesas.. - 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, 0x0e, 0x11, // ........ - 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, 0x1f, 0x11, // ........ - 0x2d, 0x11, 0x2f, 0x11, 0x00, 0x12, 0x32, 0x11, // -./...2. - 0x01, 0x05, 0x81, 0x07, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x5c, 0xfa, 0x47, 0x2c, // ./..\.G, + 0x3a, 0xd4, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0x04, // :....BZ. + 0x72, 0xd6, 0x0b, 0x09, 0x48, 0x69, 0x20, 0x72, // r...Hi r + 0x65, 0x6e, 0x65, 0x73, 0x61, 0x73, 0x19, 0x03, // enesas.. + 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, 0x0e, 0x11, // ........ + 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, 0x1f, 0x11, // ........ + 0x2d, 0x11, 0x2f, 0x11, 0x00, 0x12, 0x32, 0x11, // -./...2. + 0x01, 0x05, 0x81, 0x07, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt24446[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x6f, 0xff, 0xf6, 0x11, // ./..o... - 0x8c, 0xfc, 0x01, 0x00, 0x0c, 0x41, 0x2a, 0x03, // .....A*. - 0x64, 0xcc, 0x09, 0x09, 0x4d, 0x53, 0x46, 0x54, // d...MSFT - 0x55, 0x50, 0x46, 0x31, 0x02, 0x0a, 0x0b, 0x0d, // UPF1.... - 0x03, 0x0a, 0x11, 0x0b, 0x11, 0x0c, 0x11, 0x0e, // ........ - 0x11, 0x1f, 0x11, 0x1e, 0x11, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x6f, 0xff, 0xf6, 0x11, // ./..o... + 0x8c, 0xfc, 0x01, 0x00, 0x0c, 0x41, 0x2a, 0x03, // .....A*. + 0x64, 0xcc, 0x09, 0x09, 0x4d, 0x53, 0x46, 0x54, // d...MSFT + 0x55, 0x50, 0x46, 0x31, 0x02, 0x0a, 0x0b, 0x0d, // UPF1.... + 0x03, 0x0a, 0x11, 0x0b, 0x11, 0x0c, 0x11, 0x0e, // ........ + 0x11, 0x1f, 0x11, 0x1e, 0x11, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt24658[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xdf, 0xf4, 0x7f, 0x79, // ./.....y - 0x50, 0x7c, 0x01, 0x00, 0x0c, 0x41, 0x2a, 0x66, // P|...A*f - 0x51, 0xc1, 0x10, 0x09, 0x44, 0x45, 0x53, 0x4b, // Q...DESK - 0x54, 0x4f, 0x50, 0x2d, 0x48, 0x4c, 0x48, 0x46, // TOP-HLHF - 0x52, 0x30, 0x49, 0x02, 0x0a, 0x0c, 0x0d, 0x03, // R0I..... - 0x0a, 0x11, 0x0b, 0x11, 0x0c, 0x11, 0x0e, 0x11, // ........ - 0x1f, 0x11, 0x1e, 0x11, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xdf, 0xf4, 0x7f, 0x79, // ./.....y + 0x50, 0x7c, 0x01, 0x00, 0x0c, 0x41, 0x2a, 0x66, // P|...A*f + 0x51, 0xc1, 0x10, 0x09, 0x44, 0x45, 0x53, 0x4b, // Q...DESK + 0x54, 0x4f, 0x50, 0x2d, 0x48, 0x4c, 0x48, 0x46, // TOP-HLHF + 0x52, 0x30, 0x49, 0x02, 0x0a, 0x0c, 0x0d, 0x03, // R0I..... + 0x0a, 0x11, 0x0b, 0x11, 0x0c, 0x11, 0x0e, 0x11, // ........ + 0x1f, 0x11, 0x1e, 0x11, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt25745[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xaa, 0xcc, 0x40, 0x6a, // ./....@j - 0x01, 0x43, 0x01, 0x00, 0x04, 0x44, 0x24, 0x82, // .C...D$. - 0x37, 0xc5, 0x06, 0x09, 0x61, 0x34, 0x63, 0x63, // 7...a4cc - 0x63, 0x09, 0x03, 0x0b, 0x11, 0x0c, 0x11, 0x0e, // c....... - 0x11, 0x1e, 0x11, 0x51, 0x07, 0xfb, 0x34, 0x9b, // ...Q..4. - 0x5f, 0x80, 0x00, 0x00, 0x80, 0x00, 0x10, 0x00, // _....... - 0x00, 0x01, 0x11, 0x00, 0x00, 0x7c, 0x92, 0x67, // .....|.g - 0x4d, 0x2c, 0xf1, 0x86, 0x88, 0xdb, 0x4f, 0x15, // M,....O. - 0x25, 0x2c, 0xfe, 0x21, 0xdf, 0x95, 0xa8, 0x7e, // %,.!...~ - 0x16, 0x9f, 0xa6, 0x6d, 0x97, 0x40, 0x4e, 0xe3, // ...m.@N. - 0xb2, 0x66, 0xd6, 0x34, 0x12, 0x15, 0x0e, 0x33, // .f.4...3 - 0xc9, 0x96, 0xff, 0x24, 0x80, 0x34, 0x43, 0x66, // ...$.4Cf - 0x79, 0xe4, 0xfb, 0xd1, 0xf8, 0x51, 0x33, 0x59, // y....Q3Y - 0x88, 0xf9, 0x05, 0xff, 0xa1, 0x3e, 0x44, 0x91, // .....>D. - 0x05, 0x2a, 0xe7, 0xc2, 0x81, 0x00, 0x00, 0x00, // .*...... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xaa, 0xcc, 0x40, 0x6a, // ./....@j + 0x01, 0x43, 0x01, 0x00, 0x04, 0x44, 0x24, 0x82, // .C...D$. + 0x37, 0xc5, 0x06, 0x09, 0x61, 0x34, 0x63, 0x63, // 7...a4cc + 0x63, 0x09, 0x03, 0x0b, 0x11, 0x0c, 0x11, 0x0e, // c....... + 0x11, 0x1e, 0x11, 0x51, 0x07, 0xfb, 0x34, 0x9b, // ...Q..4. + 0x5f, 0x80, 0x00, 0x00, 0x80, 0x00, 0x10, 0x00, // _....... + 0x00, 0x01, 0x11, 0x00, 0x00, 0x7c, 0x92, 0x67, // .....|.g + 0x4d, 0x2c, 0xf1, 0x86, 0x88, 0xdb, 0x4f, 0x15, // M,....O. + 0x25, 0x2c, 0xfe, 0x21, 0xdf, 0x95, 0xa8, 0x7e, // %,.!...~ + 0x16, 0x9f, 0xa6, 0x6d, 0x97, 0x40, 0x4e, 0xe3, // ...m.@N. + 0xb2, 0x66, 0xd6, 0x34, 0x12, 0x15, 0x0e, 0x33, // .f.4...3 + 0xc9, 0x96, 0xff, 0x24, 0x80, 0x34, 0x43, 0x66, // ...$.4Cf + 0x79, 0xe4, 0xfb, 0xd1, 0xf8, 0x51, 0x33, 0x59, // y....Q3Y + 0x88, 0xf9, 0x05, 0xff, 0xa1, 0x3e, 0x44, 0x91, // .....>D. + 0x05, 0x2a, 0xe7, 0xc2, 0x81, 0x00, 0x00, 0x00, // .*...... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt25751[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x15, 0xb8, 0xde, 0xea, // ./...... - 0x5f, 0xac, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x93, // _.....Z. - 0x42, 0xb5, 0x0b, 0x09, 0x4f, 0x6e, 0x65, 0x50, // B...OneP - 0x6c, 0x75, 0x73, 0x20, 0x38, 0x54, 0x17, 0x03, // lus 8T.. - 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, 0x0e, 0x11, // ........ - 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, 0x1f, 0x11, // ........ - 0x2f, 0x11, 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, // /...2... - 0x81, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x15, 0xb8, 0xde, 0xea, // ./...... + 0x5f, 0xac, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x93, // _.....Z. + 0x42, 0xb5, 0x0b, 0x09, 0x4f, 0x6e, 0x65, 0x50, // B...OneP + 0x6c, 0x75, 0x73, 0x20, 0x38, 0x54, 0x17, 0x03, // lus 8T.. + 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, 0x0e, 0x11, // ........ + 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, 0x1f, 0x11, // ........ + 0x2f, 0x11, 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, // /...2... + 0x81, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt26171[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xf1, 0x53, 0xf3, 0xfe, // ./...S.. - 0x72, 0x70, 0x01, 0x00, 0x0c, 0x01, 0x28, 0xa1, // rp....(. - 0x2b, 0xb9, 0x1c, 0x09, 0x4d, 0x6f, 0x72, 0x74, // +...Mort - 0x65, 0x7a, 0x61, 0xe2, 0x80, 0x99, 0x73, 0x20, // eza...s - 0x4d, 0x61, 0x63, 0x42, 0x6f, 0x6f, 0x6b, 0x20, // MacBook - 0x50, 0x72, 0x6f, 0x20, 0x28, 0x32, 0x29, 0x0b, // Pro (2). - 0x03, 0x00, 0x12, 0x1f, 0x11, 0x0a, 0x11, 0x0c, // ........ - 0x11, 0x01, 0x18, 0x01, 0x05, 0x01, 0x07, 0x27, // .......' - 0xff, 0x00, 0x4c, 0x02, 0x24, 0x02, 0x00, 0x00, // ..L.$... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xf1, 0x53, 0xf3, 0xfe, // ./...S.. + 0x72, 0x70, 0x01, 0x00, 0x0c, 0x01, 0x28, 0xa1, // rp....(. + 0x2b, 0xb9, 0x1c, 0x09, 0x4d, 0x6f, 0x72, 0x74, // +...Mort + 0x65, 0x7a, 0x61, 0xe2, 0x80, 0x99, 0x73, 0x20, // eza...s + 0x4d, 0x61, 0x63, 0x42, 0x6f, 0x6f, 0x6b, 0x20, // MacBook + 0x50, 0x72, 0x6f, 0x20, 0x28, 0x32, 0x29, 0x0b, // Pro (2). + 0x03, 0x00, 0x12, 0x1f, 0x11, 0x0a, 0x11, 0x0c, // ........ + 0x11, 0x01, 0x18, 0x01, 0x05, 0x01, 0x07, 0x27, // .......' + 0xff, 0x00, 0x4c, 0x02, 0x24, 0x02, 0x00, 0x00, // ..L.$... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt26175[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x51, 0x33, 0x33, 0x22, // ./..Q33" - 0x11, 0x11, 0x01, 0x00, 0x04, 0x44, 0x24, 0xeb, // .....D$. - 0x43, 0xbc, 0x0a, 0x09, 0x42, 0x45, 0x53, 0x2d, // C...BES- - 0x42, 0x52, 0x45, 0x44, 0x52, 0x15, 0x03, 0x01, // BREDR... - 0x00, 0x0e, 0x11, 0x0f, 0x11, 0x0c, 0x11, 0x0b, // ........ - 0x11, 0x1e, 0x11, 0x03, 0x12, 0x08, 0x11, 0x03, // ........ - 0x12, 0x01, 0x11, 0x01, 0x05, 0x01, 0x07, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x51, 0x33, 0x33, 0x22, // ./..Q33" + 0x11, 0x11, 0x01, 0x00, 0x04, 0x44, 0x24, 0xeb, // .....D$. + 0x43, 0xbc, 0x0a, 0x09, 0x42, 0x45, 0x53, 0x2d, // C...BES- + 0x42, 0x52, 0x45, 0x44, 0x52, 0x15, 0x03, 0x01, // BREDR... + 0x00, 0x0e, 0x11, 0x0f, 0x11, 0x0c, 0x11, 0x0b, // ........ + 0x11, 0x1e, 0x11, 0x03, 0x12, 0x08, 0x11, 0x03, // ........ + 0x12, 0x01, 0x11, 0x01, 0x05, 0x01, 0x07, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt26328[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x02, 0x00, 0xf4, 0x35, // ./.....5 - 0x23, 0x48, 0x00, 0x00, 0x18, 0x04, 0x00, 0x3a, // #H.....: - 0x33, 0xc0, 0x0a, 0x09, 0x41, 0x70, 0x70, 0x32, // 3...App2 - 0x5f, 0x30, 0x30, 0x30, 0x32, 0x00, 0x00, 0x00, // _0002... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x02, 0x00, 0xf4, 0x35, // ./.....5 + 0x23, 0x48, 0x00, 0x00, 0x18, 0x04, 0x00, 0x3a, // #H.....: + 0x33, 0xc0, 0x0a, 0x09, 0x41, 0x70, 0x70, 0x32, // 3...App2 + 0x5f, 0x30, 0x30, 0x30, 0x32, 0x00, 0x00, 0x00, // _0002... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt26463[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x9f, 0x73, 0x56, 0x2c, // ./...sV, - 0x3a, 0xd4, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0xa5, // :....BZ. - 0x2d, 0xad, 0x08, 0x09, 0x50, 0x69, 0x78, 0x65, // -...Pixe - 0x6c, 0x20, 0x38, 0x19, 0x03, 0x05, 0x11, 0x0a, // l 8..... - 0x11, 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, // ........ - 0x11, 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, // .....-./ - 0x11, 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, // ...2.... - 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x9f, 0x73, 0x56, 0x2c, // ./...sV, + 0x3a, 0xd4, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0xa5, // :....BZ. + 0x2d, 0xad, 0x08, 0x09, 0x50, 0x69, 0x78, 0x65, // -...Pixe + 0x6c, 0x20, 0x38, 0x19, 0x03, 0x05, 0x11, 0x0a, // l 8..... + 0x11, 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, // ........ + 0x11, 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, // .....-./ + 0x11, 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, // ...2.... + 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt34640[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xd5, 0x29, 0xa3, 0x34, // ./...).4 - 0x29, 0x24, 0x01, 0x00, 0x04, 0x44, 0x24, 0xbf, // )$...D$. - 0x78, 0xcf, 0x1a, 0x09, 0x73, 0x69, 0x64, 0x68, // x...sidh - 0x74, 0x65, 0x73, 0x74, 0x27, 0x73, 0x20, 0x2a, // test's * - 0x2a, 0x2a, 0x2a, 0x2a, 0x20, 0x2a, 0x2a, 0x2a, // **** *** - 0x2a, 0x20, 0x2a, 0x2a, 0x2a, 0x09, 0x03, 0x0b, // * ***... - 0x11, 0x0c, 0x11, 0x0e, 0x11, 0x1e, 0x11, 0x51, // .......Q - 0x07, 0xb5, 0xf7, 0x08, 0xa7, 0x64, 0xf7, 0x51, // .....d.Q - 0x89, 0x4c, 0x4c, 0xce, 0x24, 0xf7, 0x7f, 0xe9, // .LL.$... - 0x25, 0x7c, 0x92, 0x67, 0x4d, 0x2c, 0xf1, 0x86, // %|.gM,.. - 0x88, 0xdb, 0x4f, 0x15, 0x25, 0x2c, 0xfe, 0x21, // ..O.%,.! - 0xdf, 0xb4, 0xf7, 0x08, 0xa7, 0x64, 0xf7, 0x51, // .....d.Q - 0x89, 0x4c, 0x4c, 0xce, 0x24, 0xf7, 0x7f, 0xe9, // .LL.$... - 0x25, 0x15, 0x0e, 0x33, 0xc9, 0x96, 0xff, 0x24, // %..3...$ - 0x80, 0x34, 0x43, 0x66, 0x79, 0xe4, 0xfb, 0xd1, // .4Cfy... - 0xf8, 0x51, 0x33, 0x59, 0x88, 0xf9, 0x05, 0xff, // .Q3Y.... - 0xa1, 0x3e, 0x44, 0x91, 0x05, 0x2a, 0xe7, 0xc2, // .>D..*.. - 0x81, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xd5, 0x29, 0xa3, 0x34, // ./...).4 + 0x29, 0x24, 0x01, 0x00, 0x04, 0x44, 0x24, 0xbf, // )$...D$. + 0x78, 0xcf, 0x1a, 0x09, 0x73, 0x69, 0x64, 0x68, // x...sidh + 0x74, 0x65, 0x73, 0x74, 0x27, 0x73, 0x20, 0x2a, // test's * + 0x2a, 0x2a, 0x2a, 0x2a, 0x20, 0x2a, 0x2a, 0x2a, // **** *** + 0x2a, 0x20, 0x2a, 0x2a, 0x2a, 0x09, 0x03, 0x0b, // * ***... + 0x11, 0x0c, 0x11, 0x0e, 0x11, 0x1e, 0x11, 0x51, // .......Q + 0x07, 0xb5, 0xf7, 0x08, 0xa7, 0x64, 0xf7, 0x51, // .....d.Q + 0x89, 0x4c, 0x4c, 0xce, 0x24, 0xf7, 0x7f, 0xe9, // .LL.$... + 0x25, 0x7c, 0x92, 0x67, 0x4d, 0x2c, 0xf1, 0x86, // %|.gM,.. + 0x88, 0xdb, 0x4f, 0x15, 0x25, 0x2c, 0xfe, 0x21, // ..O.%,.! + 0xdf, 0xb4, 0xf7, 0x08, 0xa7, 0x64, 0xf7, 0x51, // .....d.Q + 0x89, 0x4c, 0x4c, 0xce, 0x24, 0xf7, 0x7f, 0xe9, // .LL.$... + 0x25, 0x15, 0x0e, 0x33, 0xc9, 0x96, 0xff, 0x24, // %..3...$ + 0x80, 0x34, 0x43, 0x66, 0x79, 0xe4, 0xfb, 0xd1, // .4Cfy... + 0xf8, 0x51, 0x33, 0x59, 0x88, 0xf9, 0x05, 0xff, // .Q3Y.... + 0xa1, 0x3e, 0x44, 0x91, 0x05, 0x2a, 0xe7, 0xc2, // .>D..*.. + 0x81, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt34666[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x7f, 0xf4, 0xc3, 0x46, // ./.....F - 0x74, 0x74, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x1d, // tt....Z. - 0x6d, 0xc1, 0x08, 0x09, 0x50, 0x69, 0x78, 0x65, // m...Pixe - 0x6c, 0x20, 0x36, 0x19, 0x03, 0x05, 0x11, 0x0a, // l 6..... - 0x11, 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, // ........ - 0x11, 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, // .....-./ - 0x11, 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, // ...2.... - 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x7f, 0xf4, 0xc3, 0x46, // ./.....F + 0x74, 0x74, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x1d, // tt....Z. + 0x6d, 0xc1, 0x08, 0x09, 0x50, 0x69, 0x78, 0x65, // m...Pixe + 0x6c, 0x20, 0x36, 0x19, 0x03, 0x05, 0x11, 0x0a, // l 6..... + 0x11, 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, // ........ + 0x11, 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, // .....-./ + 0x11, 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, // ...2.... + 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt34778[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x7f, 0xf4, 0xc3, 0x46, // ./.....F - 0x74, 0x74, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x1c, // tt....Z. - 0x6d, 0xbf, 0x08, 0x09, 0x50, 0x69, 0x78, 0x65, // m...Pixe - 0x6c, 0x20, 0x36, 0x19, 0x03, 0x05, 0x11, 0x0a, // l 6..... - 0x11, 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, // ........ - 0x11, 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, // .....-./ - 0x11, 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, // ...2.... - 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x7f, 0xf4, 0xc3, 0x46, // ./.....F + 0x74, 0x74, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x1c, // tt....Z. + 0x6d, 0xbf, 0x08, 0x09, 0x50, 0x69, 0x78, 0x65, // m...Pixe + 0x6c, 0x20, 0x36, 0x19, 0x03, 0x05, 0x11, 0x0a, // l 6..... + 0x11, 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, // ........ + 0x11, 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, // .....-./ + 0x11, 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, // ...2.... + 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt34779[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xd5, 0x29, 0xa3, 0x34, // ./...).4 - 0x29, 0x24, 0x01, 0x00, 0x04, 0x44, 0x24, 0xbf, // )$...D$. - 0x78, 0xd1, 0x1a, 0x09, 0x73, 0x69, 0x64, 0x68, // x...sidh - 0x74, 0x65, 0x73, 0x74, 0x27, 0x73, 0x20, 0x2a, // test's * - 0x2a, 0x2a, 0x2a, 0x2a, 0x20, 0x2a, 0x2a, 0x2a, // **** *** - 0x2a, 0x20, 0x2a, 0x2a, 0x2a, 0x09, 0x03, 0x0b, // * ***... - 0x11, 0x0c, 0x11, 0x0e, 0x11, 0x1e, 0x11, 0x51, // .......Q - 0x07, 0xb5, 0xf7, 0x08, 0xa7, 0x64, 0xf7, 0x51, // .....d.Q - 0x89, 0x4c, 0x4c, 0xce, 0x24, 0xf7, 0x7f, 0xe9, // .LL.$... - 0x25, 0x7c, 0x92, 0x67, 0x4d, 0x2c, 0xf1, 0x86, // %|.gM,.. - 0x88, 0xdb, 0x4f, 0x15, 0x25, 0x2c, 0xfe, 0x21, // ..O.%,.! - 0xdf, 0xb4, 0xf7, 0x08, 0xa7, 0x64, 0xf7, 0x51, // .....d.Q - 0x89, 0x4c, 0x4c, 0xce, 0x24, 0xf7, 0x7f, 0xe9, // .LL.$... - 0x25, 0x15, 0x0e, 0x33, 0xc9, 0x96, 0xff, 0x24, // %..3...$ - 0x80, 0x34, 0x43, 0x66, 0x79, 0xe4, 0xfb, 0xd1, // .4Cfy... - 0xf8, 0x51, 0x33, 0x59, 0x88, 0xf9, 0x05, 0xff, // .Q3Y.... - 0xa1, 0x3e, 0x44, 0x91, 0x05, 0x2a, 0xe7, 0xc2, // .>D..*.. - 0x81, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xd5, 0x29, 0xa3, 0x34, // ./...).4 + 0x29, 0x24, 0x01, 0x00, 0x04, 0x44, 0x24, 0xbf, // )$...D$. + 0x78, 0xd1, 0x1a, 0x09, 0x73, 0x69, 0x64, 0x68, // x...sidh + 0x74, 0x65, 0x73, 0x74, 0x27, 0x73, 0x20, 0x2a, // test's * + 0x2a, 0x2a, 0x2a, 0x2a, 0x20, 0x2a, 0x2a, 0x2a, // **** *** + 0x2a, 0x20, 0x2a, 0x2a, 0x2a, 0x09, 0x03, 0x0b, // * ***... + 0x11, 0x0c, 0x11, 0x0e, 0x11, 0x1e, 0x11, 0x51, // .......Q + 0x07, 0xb5, 0xf7, 0x08, 0xa7, 0x64, 0xf7, 0x51, // .....d.Q + 0x89, 0x4c, 0x4c, 0xce, 0x24, 0xf7, 0x7f, 0xe9, // .LL.$... + 0x25, 0x7c, 0x92, 0x67, 0x4d, 0x2c, 0xf1, 0x86, // %|.gM,.. + 0x88, 0xdb, 0x4f, 0x15, 0x25, 0x2c, 0xfe, 0x21, // ..O.%,.! + 0xdf, 0xb4, 0xf7, 0x08, 0xa7, 0x64, 0xf7, 0x51, // .....d.Q + 0x89, 0x4c, 0x4c, 0xce, 0x24, 0xf7, 0x7f, 0xe9, // .LL.$... + 0x25, 0x15, 0x0e, 0x33, 0xc9, 0x96, 0xff, 0x24, // %..3...$ + 0x80, 0x34, 0x43, 0x66, 0x79, 0xe4, 0xfb, 0xd1, // .4Cfy... + 0xf8, 0x51, 0x33, 0x59, 0x88, 0xf9, 0x05, 0xff, // .Q3Y.... + 0xa1, 0x3e, 0x44, 0x91, 0x05, 0x2a, 0xe7, 0xc2, // .>D..*.. + 0x81, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt34843[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xd5, 0x29, 0xa3, 0x34, // ./...).4 - 0x29, 0x24, 0x01, 0x00, 0x04, 0x44, 0x24, 0xc0, // )$...D$. - 0x78, 0xd3, 0x1a, 0x09, 0x73, 0x69, 0x64, 0x68, // x...sidh - 0x74, 0x65, 0x73, 0x74, 0x27, 0x73, 0x20, 0x2a, // test's * - 0x2a, 0x2a, 0x2a, 0x2a, 0x20, 0x2a, 0x2a, 0x2a, // **** *** - 0x2a, 0x20, 0x2a, 0x2a, 0x2a, 0x09, 0x03, 0x0b, // * ***... - 0x11, 0x0c, 0x11, 0x0e, 0x11, 0x1e, 0x11, 0x51, // .......Q - 0x07, 0xb5, 0xf7, 0x08, 0xa7, 0x64, 0xf7, 0x51, // .....d.Q - 0x89, 0x4c, 0x4c, 0xce, 0x24, 0xf7, 0x7f, 0xe9, // .LL.$... - 0x25, 0x7c, 0x92, 0x67, 0x4d, 0x2c, 0xf1, 0x86, // %|.gM,.. - 0x88, 0xdb, 0x4f, 0x15, 0x25, 0x2c, 0xfe, 0x21, // ..O.%,.! - 0xdf, 0xb4, 0xf7, 0x08, 0xa7, 0x64, 0xf7, 0x51, // .....d.Q - 0x89, 0x4c, 0x4c, 0xce, 0x24, 0xf7, 0x7f, 0xe9, // .LL.$... - 0x25, 0x15, 0x0e, 0x33, 0xc9, 0x96, 0xff, 0x24, // %..3...$ - 0x80, 0x34, 0x43, 0x66, 0x79, 0xe4, 0xfb, 0xd1, // .4Cfy... - 0xf8, 0x51, 0x33, 0x59, 0x88, 0xf9, 0x05, 0xff, // .Q3Y.... - 0xa1, 0x3e, 0x44, 0x91, 0x05, 0x2a, 0xe7, 0xc2, // .>D..*.. - 0x81, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xd5, 0x29, 0xa3, 0x34, // ./...).4 + 0x29, 0x24, 0x01, 0x00, 0x04, 0x44, 0x24, 0xc0, // )$...D$. + 0x78, 0xd3, 0x1a, 0x09, 0x73, 0x69, 0x64, 0x68, // x...sidh + 0x74, 0x65, 0x73, 0x74, 0x27, 0x73, 0x20, 0x2a, // test's * + 0x2a, 0x2a, 0x2a, 0x2a, 0x20, 0x2a, 0x2a, 0x2a, // **** *** + 0x2a, 0x20, 0x2a, 0x2a, 0x2a, 0x09, 0x03, 0x0b, // * ***... + 0x11, 0x0c, 0x11, 0x0e, 0x11, 0x1e, 0x11, 0x51, // .......Q + 0x07, 0xb5, 0xf7, 0x08, 0xa7, 0x64, 0xf7, 0x51, // .....d.Q + 0x89, 0x4c, 0x4c, 0xce, 0x24, 0xf7, 0x7f, 0xe9, // .LL.$... + 0x25, 0x7c, 0x92, 0x67, 0x4d, 0x2c, 0xf1, 0x86, // %|.gM,.. + 0x88, 0xdb, 0x4f, 0x15, 0x25, 0x2c, 0xfe, 0x21, // ..O.%,.! + 0xdf, 0xb4, 0xf7, 0x08, 0xa7, 0x64, 0xf7, 0x51, // .....d.Q + 0x89, 0x4c, 0x4c, 0xce, 0x24, 0xf7, 0x7f, 0xe9, // .LL.$... + 0x25, 0x15, 0x0e, 0x33, 0xc9, 0x96, 0xff, 0x24, // %..3...$ + 0x80, 0x34, 0x43, 0x66, 0x79, 0xe4, 0xfb, 0xd1, // .4Cfy... + 0xf8, 0x51, 0x33, 0x59, 0x88, 0xf9, 0x05, 0xff, // .Q3Y.... + 0xa1, 0x3e, 0x44, 0x91, 0x05, 0x2a, 0xe7, 0xc2, // .>D..*.. + 0x81, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt34847[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x7f, 0xf4, 0xc3, 0x46, // ./.....F - 0x74, 0x74, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x1d, // tt....Z. - 0x6d, 0xc0, 0x08, 0x09, 0x50, 0x69, 0x78, 0x65, // m...Pixe - 0x6c, 0x20, 0x36, 0x19, 0x03, 0x05, 0x11, 0x0a, // l 6..... - 0x11, 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, // ........ - 0x11, 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, // .....-./ - 0x11, 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, // ...2.... - 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x7f, 0xf4, 0xc3, 0x46, // ./.....F + 0x74, 0x74, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x1d, // tt....Z. + 0x6d, 0xc0, 0x08, 0x09, 0x50, 0x69, 0x78, 0x65, // m...Pixe + 0x6c, 0x20, 0x36, 0x19, 0x03, 0x05, 0x11, 0x0a, // l 6..... + 0x11, 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, // ........ + 0x11, 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, // .....-./ + 0x11, 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, // ...2.... + 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt34848[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x8b, 0x6e, 0xf0, 0x85, // ./...n.. - 0xe0, 0x50, 0x01, 0x00, 0x04, 0x01, 0x48, 0x85, // .P....H. - 0x7a, 0xb3, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // z...Chro - 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo - 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin - 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... - 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x67, 0x00, 0x0f, // .....g.. - 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ - 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x8b, 0x6e, 0xf0, 0x85, // ./...n.. + 0xe0, 0x50, 0x01, 0x00, 0x04, 0x01, 0x48, 0x85, // .P....H. + 0x7a, 0xb3, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // z...Chro + 0x6d, 0x65, 0x62, 0x6f, 0x78, 0x20, 0x66, 0x6f, // mebox fo + 0x72, 0x20, 0x4d, 0x65, 0x65, 0x74, 0x69, 0x6e, // r Meetin + 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... + 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x67, 0x00, 0x0f, // .....g.. + 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ + 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt34875[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x7f, 0xf4, 0xc3, 0x46, // ./.....F - 0x74, 0x74, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x1c, // tt....Z. - 0x6d, 0xbd, 0x08, 0x09, 0x50, 0x69, 0x78, 0x65, // m...Pixe - 0x6c, 0x20, 0x36, 0x19, 0x03, 0x05, 0x11, 0x0a, // l 6..... - 0x11, 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, // ........ - 0x11, 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, // .....-./ - 0x11, 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, // ...2.... - 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x7f, 0xf4, 0xc3, 0x46, // ./.....F + 0x74, 0x74, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x1c, // tt....Z. + 0x6d, 0xbd, 0x08, 0x09, 0x50, 0x69, 0x78, 0x65, // m...Pixe + 0x6c, 0x20, 0x36, 0x19, 0x03, 0x05, 0x11, 0x0a, // l 6..... + 0x11, 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, // ........ + 0x11, 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, // .....-./ + 0x11, 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, // ...2.... + 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt19294[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xcb, 0x29, 0xa3, 0x34, // ./...).4 - 0x29, 0x24, 0x01, 0x00, 0x04, 0x44, 0x24, 0x97, // )$...D$. - 0x19, 0xd3, 0x0c, 0x09, 0x41, 0x31, 0x31, 0x5f, // ....A11_ - 0x46, 0x46, 0x5f, 0x32, 0x39, 0x63, 0x62, 0x09, // FF_29cb. - 0x03, 0x0b, 0x11, 0x0c, 0x11, 0x0e, 0x11, 0x1e, // ........ - 0x11, 0x51, 0x07, 0xb5, 0xf7, 0x08, 0xa7, 0x64, // .Q.....d - 0xf7, 0x51, 0x89, 0x4c, 0x4c, 0xce, 0x24, 0xf7, // .Q.LL.$. - 0x7f, 0xe9, 0x25, 0x7c, 0x92, 0x67, 0x4d, 0x2c, // ..%|.gM, - 0xf1, 0x86, 0x88, 0xdb, 0x4f, 0x15, 0x25, 0x2c, // ....O.%, - 0xfe, 0x21, 0xdf, 0xb4, 0xf7, 0x08, 0xa7, 0x64, // .!.....d - 0xf7, 0x51, 0x89, 0x4c, 0x4c, 0xce, 0x24, 0xf7, // .Q.LL.$. - 0x7f, 0xe9, 0x25, 0x15, 0x0e, 0x33, 0xc9, 0x96, // ..%..3.. - 0xff, 0x24, 0x80, 0x34, 0x43, 0x66, 0x79, 0xe4, // .$.4Cfy. - 0xfb, 0xd1, 0xf8, 0x51, 0x33, 0x59, 0x88, 0xf9, // ...Q3Y.. - 0x05, 0xff, 0xa1, 0x3e, 0x44, 0x91, 0x05, 0x2a, // ...>D..* - 0xe7, 0xc2, 0x81, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xcb, 0x29, 0xa3, 0x34, // ./...).4 + 0x29, 0x24, 0x01, 0x00, 0x04, 0x44, 0x24, 0x97, // )$...D$. + 0x19, 0xd3, 0x0c, 0x09, 0x41, 0x31, 0x31, 0x5f, // ....A11_ + 0x46, 0x46, 0x5f, 0x32, 0x39, 0x63, 0x62, 0x09, // FF_29cb. + 0x03, 0x0b, 0x11, 0x0c, 0x11, 0x0e, 0x11, 0x1e, // ........ + 0x11, 0x51, 0x07, 0xb5, 0xf7, 0x08, 0xa7, 0x64, // .Q.....d + 0xf7, 0x51, 0x89, 0x4c, 0x4c, 0xce, 0x24, 0xf7, // .Q.LL.$. + 0x7f, 0xe9, 0x25, 0x7c, 0x92, 0x67, 0x4d, 0x2c, // ..%|.gM, + 0xf1, 0x86, 0x88, 0xdb, 0x4f, 0x15, 0x25, 0x2c, // ....O.%, + 0xfe, 0x21, 0xdf, 0xb4, 0xf7, 0x08, 0xa7, 0x64, // .!.....d + 0xf7, 0x51, 0x89, 0x4c, 0x4c, 0xce, 0x24, 0xf7, // .Q.LL.$. + 0x7f, 0xe9, 0x25, 0x15, 0x0e, 0x33, 0xc9, 0x96, // ..%..3.. + 0xff, 0x24, 0x80, 0x34, 0x43, 0x66, 0x79, 0xe4, // .$.4Cfy. + 0xfb, 0xd1, 0xf8, 0x51, 0x33, 0x59, 0x88, 0xf9, // ...Q3Y.. + 0x05, 0xff, 0xa1, 0x3e, 0x44, 0x91, 0x05, 0x2a, // ...>D..* + 0xe7, 0xc2, 0x81, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt4073[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x52, 0xb4, 0x2e, 0x13, // ./..R... - 0xc4, 0x0c, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0xac, // .....BZ. - 0x1c, 0xd5, 0x4d, 0x09, 0x49, 0x7a, 0x6b, 0x33, // ..M.Izk3 - 0x55, 0x6c, 0x6a, 0x38, 0x6e, 0x31, 0x34, 0x41, // Ulj8n14A - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, // AAAAAAAA - 0x4b, 0x53, 0x49, 0x66, 0x39, 0x54, 0x71, 0x61, // KSIf9Tqa - 0x51, 0x7a, 0x79, 0x6a, 0x36, 0x78, 0x32, 0x72, // Qzyj6x2r - 0x67, 0x35, 0x46, 0x50, 0x52, 0x50, 0x70, 0x5f, // g5FPRPp_ - 0x46, 0x31, 0x4a, 0x46, 0x51, 0x30, 0x56, 0x4a, // F1JFQ0VJ - 0x56, 0x6b, 0x56, 0x53, 0x4c, 0x54, 0x49, 0x30, // VkVSLTI0 - 0x4d, 0x54, 0x4d, 0x78, 0x52, 0x6b, 0x52, 0x49, // MTMxRkRI - 0x4d, 0x6a, 0x41, 0x77, 0x4d, 0x44, 0x5a, 0x4d, // MjAwMDZM - 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, // ........ - 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, // ........ - 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, 0x00, 0x12, // ..-./... - 0x32, 0x11, 0x01, 0x05, 0x71, 0x06, 0x5a, 0x6c, // 2...q.Zl - 0xb1, 0xa7, 0x6d, 0xf1, 0xbc, 0x9b, 0xde, 0x3d, // ..m....= - 0x5c, 0xae, 0x21, 0xfa, 0x2e, 0xa8, 0x00, 0x00, // \.!..... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x52, 0xb4, 0x2e, 0x13, // ./..R... + 0xc4, 0x0c, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0xac, // .....BZ. + 0x1c, 0xd5, 0x4d, 0x09, 0x49, 0x7a, 0x6b, 0x33, // ..M.Izk3 + 0x55, 0x6c, 0x6a, 0x38, 0x6e, 0x31, 0x34, 0x41, // Ulj8n14A + 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, // AAAAAAAA + 0x4b, 0x53, 0x49, 0x66, 0x39, 0x54, 0x71, 0x61, // KSIf9Tqa + 0x51, 0x7a, 0x79, 0x6a, 0x36, 0x78, 0x32, 0x72, // Qzyj6x2r + 0x67, 0x35, 0x46, 0x50, 0x52, 0x50, 0x70, 0x5f, // g5FPRPp_ + 0x46, 0x31, 0x4a, 0x46, 0x51, 0x30, 0x56, 0x4a, // F1JFQ0VJ + 0x56, 0x6b, 0x56, 0x53, 0x4c, 0x54, 0x49, 0x30, // VkVSLTI0 + 0x4d, 0x54, 0x4d, 0x78, 0x52, 0x6b, 0x52, 0x49, // MTMxRkRI + 0x4d, 0x6a, 0x41, 0x77, 0x4d, 0x44, 0x5a, 0x4d, // MjAwMDZM + 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, // ........ + 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, // ........ + 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, 0x00, 0x12, // ..-./... + 0x32, 0x11, 0x01, 0x05, 0x71, 0x06, 0x5a, 0x6c, // 2...q.Zl + 0xb1, 0xa7, 0x6d, 0xf1, 0xbc, 0x9b, 0xde, 0x3d, // ..m....= + 0x5c, 0xae, 0x21, 0xfa, 0x2e, 0xa8, 0x00, 0x00, // \.!..... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt4075[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x36, 0x1a, 0x37, 0x08, // ./..6.7. - 0x9e, 0x08, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0xff, // ......Z. - 0x08, 0xd0, 0x4d, 0x09, 0x49, 0x7a, 0x4e, 0x42, // ..M.IzNB - 0x52, 0x31, 0x6a, 0x38, 0x6e, 0x31, 0x34, 0x41, // R1j8n14A - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, // AAAAAAAA - 0x4b, 0x53, 0x4c, 0x6e, 0x58, 0x75, 0x31, 0x73, // KSLnXu1s - 0x6d, 0x64, 0x54, 0x55, 0x65, 0x4d, 0x50, 0x43, // mdTUeMPC - 0x63, 0x32, 0x35, 0x67, 0x2d, 0x6e, 0x5a, 0x6f, // c25g-nZo - 0x46, 0x31, 0x4a, 0x46, 0x51, 0x30, 0x56, 0x4a, // F1JFQ0VJ - 0x56, 0x6b, 0x56, 0x53, 0x4c, 0x54, 0x41, 0x7a, // VkVSLTAz - 0x4d, 0x54, 0x49, 0x78, 0x53, 0x6b, 0x56, 0x44, // MTIxSkVD - 0x4d, 0x6a, 0x41, 0x77, 0x4d, 0x44, 0x59, 0x31, // MjAwMDY1 - 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, // ........ - 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, // ........ - 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, 0x00, 0x12, // ..-./... - 0x32, 0x11, 0x01, 0x05, 0x71, 0x06, 0x5a, 0x6c, // 2...q.Zl - 0xb1, 0xa7, 0x6d, 0xf1, 0xbc, 0x9b, 0xde, 0x3d, // ..m....= - 0x5c, 0xae, 0x21, 0xfa, 0x2e, 0xa8, 0x00, 0x00, // \.!..... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x36, 0x1a, 0x37, 0x08, // ./..6.7. + 0x9e, 0x08, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0xff, // ......Z. + 0x08, 0xd0, 0x4d, 0x09, 0x49, 0x7a, 0x4e, 0x42, // ..M.IzNB + 0x52, 0x31, 0x6a, 0x38, 0x6e, 0x31, 0x34, 0x41, // R1j8n14A + 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, // AAAAAAAA + 0x4b, 0x53, 0x4c, 0x6e, 0x58, 0x75, 0x31, 0x73, // KSLnXu1s + 0x6d, 0x64, 0x54, 0x55, 0x65, 0x4d, 0x50, 0x43, // mdTUeMPC + 0x63, 0x32, 0x35, 0x67, 0x2d, 0x6e, 0x5a, 0x6f, // c25g-nZo + 0x46, 0x31, 0x4a, 0x46, 0x51, 0x30, 0x56, 0x4a, // F1JFQ0VJ + 0x56, 0x6b, 0x56, 0x53, 0x4c, 0x54, 0x41, 0x7a, // VkVSLTAz + 0x4d, 0x54, 0x49, 0x78, 0x53, 0x6b, 0x56, 0x44, // MTIxSkVD + 0x4d, 0x6a, 0x41, 0x77, 0x4d, 0x44, 0x59, 0x31, // MjAwMDY1 + 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, // ........ + 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, // ........ + 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, 0x00, 0x12, // ..-./... + 0x32, 0x11, 0x01, 0x05, 0x71, 0x06, 0x5a, 0x6c, // 2...q.Zl + 0xb1, 0xa7, 0x6d, 0xf1, 0xbc, 0x9b, 0xde, 0x3d, // ..m....= + 0x5c, 0xae, 0x21, 0xfa, 0x2e, 0xa8, 0x00, 0x00, // \.!..... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt4883[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x52, 0xb4, 0x2e, 0x13, // ./..R... - 0xc4, 0x0c, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0xac, // .....BZ. - 0x1c, 0xd4, 0x4d, 0x09, 0x49, 0x7a, 0x6b, 0x33, // ..M.Izk3 - 0x55, 0x6c, 0x6a, 0x38, 0x6e, 0x31, 0x34, 0x41, // Ulj8n14A - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, // AAAAAAAA - 0x4b, 0x53, 0x49, 0x37, 0x31, 0x59, 0x74, 0x6f, // KSI71Yto - 0x4a, 0x52, 0x6b, 0x31, 0x74, 0x72, 0x51, 0x79, // JRk1trQy - 0x4a, 0x77, 0x53, 0x71, 0x65, 0x35, 0x44, 0x45, // JwSqe5DE - 0x46, 0x31, 0x4a, 0x46, 0x51, 0x30, 0x56, 0x4a, // F1JFQ0VJ - 0x56, 0x6b, 0x56, 0x53, 0x4c, 0x54, 0x49, 0x30, // VkVSLTI0 - 0x4d, 0x54, 0x4d, 0x78, 0x52, 0x6b, 0x52, 0x49, // MTMxRkRI - 0x4d, 0x6a, 0x41, 0x77, 0x4d, 0x44, 0x5a, 0x4d, // MjAwMDZM - 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, // ........ - 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, // ........ - 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, 0x00, 0x12, // ..-./... - 0x32, 0x11, 0x01, 0x05, 0x71, 0x06, 0x5a, 0x6c, // 2...q.Zl - 0xb1, 0xa7, 0x6d, 0xf1, 0xbc, 0x9b, 0xde, 0x3d, // ..m....= - 0x5c, 0xae, 0x21, 0xfa, 0x2e, 0xa8, 0x00, 0x00, // \.!..... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x52, 0xb4, 0x2e, 0x13, // ./..R... + 0xc4, 0x0c, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0xac, // .....BZ. + 0x1c, 0xd4, 0x4d, 0x09, 0x49, 0x7a, 0x6b, 0x33, // ..M.Izk3 + 0x55, 0x6c, 0x6a, 0x38, 0x6e, 0x31, 0x34, 0x41, // Ulj8n14A + 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, // AAAAAAAA + 0x4b, 0x53, 0x49, 0x37, 0x31, 0x59, 0x74, 0x6f, // KSI71Yto + 0x4a, 0x52, 0x6b, 0x31, 0x74, 0x72, 0x51, 0x79, // JRk1trQy + 0x4a, 0x77, 0x53, 0x71, 0x65, 0x35, 0x44, 0x45, // JwSqe5DE + 0x46, 0x31, 0x4a, 0x46, 0x51, 0x30, 0x56, 0x4a, // F1JFQ0VJ + 0x56, 0x6b, 0x56, 0x53, 0x4c, 0x54, 0x49, 0x30, // VkVSLTI0 + 0x4d, 0x54, 0x4d, 0x78, 0x52, 0x6b, 0x52, 0x49, // MTMxRkRI + 0x4d, 0x6a, 0x41, 0x77, 0x4d, 0x44, 0x5a, 0x4d, // MjAwMDZM + 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, // ........ + 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, // ........ + 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, 0x00, 0x12, // ..-./... + 0x32, 0x11, 0x01, 0x05, 0x71, 0x06, 0x5a, 0x6c, // 2...q.Zl + 0xb1, 0xa7, 0x6d, 0xf1, 0xbc, 0x9b, 0xde, 0x3d, // ..m....= + 0x5c, 0xae, 0x21, 0xfa, 0x2e, 0xa8, 0x00, 0x00, // \.!..... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt7384[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x36, 0x1a, 0x37, 0x08, // ./..6.7. - 0x9e, 0x08, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x00, // ......Z. - 0x09, 0xd1, 0x4d, 0x09, 0x49, 0x30, 0x63, 0x33, // ..M.I0c3 - 0x53, 0x46, 0x6e, 0x38, 0x6e, 0x31, 0x34, 0x41, // SFn8n14A - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, // AAAAAAAA - 0x4b, 0x53, 0x4c, 0x4e, 0x4b, 0x47, 0x35, 0x41, // KSLNKG5A - 0x43, 0x7a, 0x6a, 0x44, 0x35, 0x4e, 0x43, 0x38, // CzjD5NC8 - 0x68, 0x78, 0x55, 0x45, 0x61, 0x5f, 0x36, 0x74, // hxUEa_6t - 0x46, 0x31, 0x4a, 0x46, 0x51, 0x30, 0x56, 0x4a, // F1JFQ0VJ - 0x56, 0x6b, 0x56, 0x53, 0x4c, 0x54, 0x41, 0x7a, // VkVSLTAz - 0x4d, 0x54, 0x49, 0x78, 0x53, 0x6b, 0x56, 0x44, // MTIxSkVD - 0x4d, 0x6a, 0x41, 0x77, 0x4d, 0x44, 0x59, 0x31, // MjAwMDY1 - 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, // ........ - 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, // ........ - 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, 0x00, 0x12, // ..-./... - 0x32, 0x11, 0x01, 0x05, 0x71, 0x06, 0x5a, 0x6c, // 2...q.Zl - 0xb1, 0xa7, 0x6d, 0xf1, 0xbc, 0x9b, 0xde, 0x3d, // ..m....= - 0x5c, 0xae, 0x21, 0xfa, 0x2e, 0xa8, 0x00, 0x00, // \.!..... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x36, 0x1a, 0x37, 0x08, // ./..6.7. + 0x9e, 0x08, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x00, // ......Z. + 0x09, 0xd1, 0x4d, 0x09, 0x49, 0x30, 0x63, 0x33, // ..M.I0c3 + 0x53, 0x46, 0x6e, 0x38, 0x6e, 0x31, 0x34, 0x41, // SFn8n14A + 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, // AAAAAAAA + 0x4b, 0x53, 0x4c, 0x4e, 0x4b, 0x47, 0x35, 0x41, // KSLNKG5A + 0x43, 0x7a, 0x6a, 0x44, 0x35, 0x4e, 0x43, 0x38, // CzjD5NC8 + 0x68, 0x78, 0x55, 0x45, 0x61, 0x5f, 0x36, 0x74, // hxUEa_6t + 0x46, 0x31, 0x4a, 0x46, 0x51, 0x30, 0x56, 0x4a, // F1JFQ0VJ + 0x56, 0x6b, 0x56, 0x53, 0x4c, 0x54, 0x41, 0x7a, // VkVSLTAz + 0x4d, 0x54, 0x49, 0x78, 0x53, 0x6b, 0x56, 0x44, // MTIxSkVD + 0x4d, 0x6a, 0x41, 0x77, 0x4d, 0x44, 0x59, 0x31, // MjAwMDY1 + 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, // ........ + 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, // ........ + 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, 0x00, 0x12, // ..-./... + 0x32, 0x11, 0x01, 0x05, 0x71, 0x06, 0x5a, 0x6c, // 2...q.Zl + 0xb1, 0xa7, 0x6d, 0xf1, 0xbc, 0x9b, 0xde, 0x3d, // ..m....= + 0x5c, 0xae, 0x21, 0xfa, 0x2e, 0xa8, 0x00, 0x00, // \.!..... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt7385[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x52, 0xb4, 0x2e, 0x13, // ./..R... - 0xc4, 0x0c, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0xad, // .....BZ. - 0x1c, 0xd6, 0x4d, 0x09, 0x49, 0x7a, 0x4a, 0x56, // ..M.IzJV - 0x4e, 0x45, 0x6a, 0x38, 0x6e, 0x31, 0x34, 0x41, // NEj8n14A - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, // AAAAAAAA - 0x4b, 0x53, 0x4a, 0x54, 0x43, 0x67, 0x54, 0x59, // KSJTCgTY - 0x30, 0x34, 0x55, 0x61, 0x54, 0x71, 0x57, 0x37, // 04UaTqW7 - 0x39, 0x78, 0x62, 0x76, 0x5f, 0x37, 0x69, 0x73, // 9xbv_7is - 0x46, 0x31, 0x4a, 0x46, 0x51, 0x30, 0x56, 0x4a, // F1JFQ0VJ - 0x56, 0x6b, 0x56, 0x53, 0x4c, 0x54, 0x49, 0x30, // VkVSLTI0 - 0x4d, 0x54, 0x4d, 0x78, 0x52, 0x6b, 0x52, 0x49, // MTMxRkRI - 0x4d, 0x6a, 0x41, 0x77, 0x4d, 0x44, 0x5a, 0x4d, // MjAwMDZM - 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, // ........ - 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, // ........ - 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, 0x00, 0x12, // ..-./... - 0x32, 0x11, 0x01, 0x05, 0x71, 0x06, 0x5a, 0x6c, // 2...q.Zl - 0xb1, 0xa7, 0x6d, 0xf1, 0xbc, 0x9b, 0xde, 0x3d, // ..m....= - 0x5c, 0xae, 0x21, 0xfa, 0x2e, 0xa8, 0x00, 0x00, // \.!..... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x52, 0xb4, 0x2e, 0x13, // ./..R... + 0xc4, 0x0c, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0xad, // .....BZ. + 0x1c, 0xd6, 0x4d, 0x09, 0x49, 0x7a, 0x4a, 0x56, // ..M.IzJV + 0x4e, 0x45, 0x6a, 0x38, 0x6e, 0x31, 0x34, 0x41, // NEj8n14A + 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, // AAAAAAAA + 0x4b, 0x53, 0x4a, 0x54, 0x43, 0x67, 0x54, 0x59, // KSJTCgTY + 0x30, 0x34, 0x55, 0x61, 0x54, 0x71, 0x57, 0x37, // 04UaTqW7 + 0x39, 0x78, 0x62, 0x76, 0x5f, 0x37, 0x69, 0x73, // 9xbv_7is + 0x46, 0x31, 0x4a, 0x46, 0x51, 0x30, 0x56, 0x4a, // F1JFQ0VJ + 0x56, 0x6b, 0x56, 0x53, 0x4c, 0x54, 0x49, 0x30, // VkVSLTI0 + 0x4d, 0x54, 0x4d, 0x78, 0x52, 0x6b, 0x52, 0x49, // MTMxRkRI + 0x4d, 0x6a, 0x41, 0x77, 0x4d, 0x44, 0x5a, 0x4d, // MjAwMDZM + 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, // ........ + 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, // ........ + 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, 0x00, 0x12, // ..-./... + 0x32, 0x11, 0x01, 0x05, 0x71, 0x06, 0x5a, 0x6c, // 2...q.Zl + 0xb1, 0xa7, 0x6d, 0xf1, 0xbc, 0x9b, 0xde, 0x3d, // ..m....= + 0x5c, 0xae, 0x21, 0xfa, 0x2e, 0xa8, 0x00, 0x00, // \.!..... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10784[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x64, 0x6f, 0x36, 0x08, // ./..do6. - 0x9e, 0x08, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x0d, // ......Z. - 0x0c, 0xbd, 0x0f, 0x09, 0x39, 0x42, 0x32, 0x37, // ....9B27 - 0x31, 0x46, 0x51, 0x43, 0x32, 0x30, 0x30, 0x30, // 1FQC2000 - 0x37, 0x38, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 78...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x64, 0x6f, 0x36, 0x08, // ./..do6. + 0x9e, 0x08, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x0d, // ......Z. + 0x0c, 0xbd, 0x0f, 0x09, 0x39, 0x42, 0x32, 0x37, // ....9B27 + 0x31, 0x46, 0x51, 0x43, 0x32, 0x30, 0x30, 0x30, // 1FQC2000 + 0x37, 0x38, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 78...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10786[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xc4, 0xd3, 0x3e, 0x13, // ./....>. - 0xc4, 0x0c, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0xf2, // .....BZ. - 0x6d, 0xd0, 0x0f, 0x09, 0x32, 0x36, 0x31, 0x30, // m...2610 - 0x31, 0x46, 0x44, 0x48, 0x33, 0x30, 0x30, 0x30, // 1FDH3000 - 0x43, 0x39, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // C9...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xc4, 0xd3, 0x3e, 0x13, // ./....>. + 0xc4, 0x0c, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0xf2, // .....BZ. + 0x6d, 0xd0, 0x0f, 0x09, 0x32, 0x36, 0x31, 0x30, // m...2610 + 0x31, 0x46, 0x44, 0x48, 0x33, 0x30, 0x30, 0x30, // 1FDH3000 + 0x43, 0x39, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // C9...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10787[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x88, 0xc6, 0xd5, 0x46, // ./.....F - 0x74, 0x74, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0x4f, // tt...BZO - 0x3e, 0xe3, 0x0f, 0x09, 0x33, 0x33, 0x31, 0x33, // >...3313 - 0x31, 0x46, 0x44, 0x48, 0x53, 0x30, 0x30, 0x30, // 1FDHS000 - 0x34, 0x4b, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 4K...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x88, 0xc6, 0xd5, 0x46, // ./.....F + 0x74, 0x74, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0x4f, // tt...BZO + 0x3e, 0xe3, 0x0f, 0x09, 0x33, 0x33, 0x31, 0x33, // >...3313 + 0x31, 0x46, 0x44, 0x48, 0x53, 0x30, 0x30, 0x30, // 1FDHS000 + 0x34, 0x4b, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 4K...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10789[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x85, 0xb3, 0x7e, 0x2f, // ./....~/ - 0x95, 0x24, 0x01, 0x00, 0x10, 0x41, 0x5a, 0x3e, // .$...AZ> - 0x38, 0xd1, 0x0f, 0x09, 0x32, 0x36, 0x31, 0x30, // 8...2610 - 0x31, 0x46, 0x44, 0x48, 0x33, 0x30, 0x30, 0x30, // 1FDH3000 - 0x43, 0x39, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // C9...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x85, 0xb3, 0x7e, 0x2f, // ./....~/ + 0x95, 0x24, 0x01, 0x00, 0x10, 0x41, 0x5a, 0x3e, // .$...AZ> + 0x38, 0xd1, 0x0f, 0x09, 0x32, 0x36, 0x31, 0x30, // 8...2610 + 0x31, 0x46, 0x44, 0x48, 0x33, 0x30, 0x30, 0x30, // 1FDH3000 + 0x43, 0x39, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // C9...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10799[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x3b, 0x8e, 0x1d, 0x52, // ./..;..R - 0xcb, 0x58, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x33, // .X....Z3 - 0x2f, 0xd5, 0x0b, 0x09, 0x39, 0x33, 0x36, 0x41, // /...936A - 0x58, 0x30, 0x34, 0x57, 0x37, 0x4c, 0x19, 0x03, // X04W7L.. - 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, 0x0e, 0x11, // ........ - 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, 0x1f, 0x11, // ........ - 0x2d, 0x11, 0x2f, 0x11, 0x00, 0x12, 0x32, 0x11, // -./...2. - 0x01, 0x05, 0x81, 0x07, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x3b, 0x8e, 0x1d, 0x52, // ./..;..R + 0xcb, 0x58, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x33, // .X....Z3 + 0x2f, 0xd5, 0x0b, 0x09, 0x39, 0x33, 0x36, 0x41, // /...936A + 0x58, 0x30, 0x34, 0x57, 0x37, 0x4c, 0x19, 0x03, // X04W7L.. + 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, 0x0e, 0x11, // ........ + 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, 0x1f, 0x11, // ........ + 0x2d, 0x11, 0x2f, 0x11, 0x00, 0x12, 0x32, 0x11, // -./...2. + 0x01, 0x05, 0x81, 0x07, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10800[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xf4, 0x9a, 0x38, 0x6e, // ./....8n - 0xb7, 0x60, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x74, // .`....Zt - 0x3f, 0xd6, 0x0f, 0x09, 0x30, 0x42, 0x31, 0x31, // ?...0B11 - 0x31, 0x46, 0x51, 0x43, 0x42, 0x30, 0x30, 0x30, // 1FQCB000 - 0x36, 0x33, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 63...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xf4, 0x9a, 0x38, 0x6e, // ./....8n + 0xb7, 0x60, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x74, // .`....Zt + 0x3f, 0xd6, 0x0f, 0x09, 0x30, 0x42, 0x31, 0x31, // ?...0B11 + 0x31, 0x46, 0x51, 0x43, 0x42, 0x30, 0x30, 0x30, // 1FQCB000 + 0x36, 0x33, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 63...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10801[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x26, 0x75, 0x2f, 0x13, // ./..&u/. - 0xc4, 0x0c, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0xa2, // .....BZ. - 0x6b, 0xc8, 0x0f, 0x09, 0x32, 0x36, 0x31, 0x36, // k...2616 - 0x31, 0x46, 0x44, 0x48, 0x32, 0x30, 0x30, 0x31, // 1FDH2001 - 0x35, 0x59, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 5Y...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x5a, 0x6c, 0xb1, 0xa7, 0x6d, 0xf1, 0xbc, 0x9b, // Zl..m... - 0xde, 0x3d, 0x5c, 0xae, 0x21, 0xfa, 0x2e, 0xa8, // .=\.!... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x26, 0x75, 0x2f, 0x13, // ./..&u/. + 0xc4, 0x0c, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0xa2, // .....BZ. + 0x6b, 0xc8, 0x0f, 0x09, 0x32, 0x36, 0x31, 0x36, // k...2616 + 0x31, 0x46, 0x44, 0x48, 0x32, 0x30, 0x30, 0x31, // 1FDH2001 + 0x35, 0x59, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 5Y...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x5a, 0x6c, 0xb1, 0xa7, 0x6d, 0xf1, 0xbc, 0x9b, // Zl..m... + 0xde, 0x3d, 0x5c, 0xae, 0x21, 0xfa, 0x2e, 0xa8, // .=\.!... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10804[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x0b, 0x06, 0x7b, 0x43, // ./....{C - 0x37, 0xac, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0xb9, // 7.....Z. - 0x22, 0xcb, 0x0d, 0x09, 0x48, 0x54, 0x36, 0x41, // "...HT6A - 0x36, 0x30, 0x32, 0x30, 0x33, 0x31, 0x33, 0x36, // 60203136 - 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, // ........ - 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, // ........ - 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, 0x00, 0x12, // ..-./... - 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, 0x00, 0x00, // 2....... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x0b, 0x06, 0x7b, 0x43, // ./....{C + 0x37, 0xac, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0xb9, // 7.....Z. + 0x22, 0xcb, 0x0d, 0x09, 0x48, 0x54, 0x36, 0x41, // "...HT6A + 0x36, 0x30, 0x32, 0x30, 0x33, 0x31, 0x33, 0x36, // 60203136 + 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, // ........ + 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, // ........ + 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, 0x00, 0x12, // ..-./... + 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, 0x00, 0x00, // 2....... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10806[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x6f, 0x07, 0xa5, 0x46, // ./..o..F - 0x74, 0x74, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0xa2, // tt...BZ. - 0x12, 0xc9, 0x0f, 0x09, 0x32, 0x37, 0x32, 0x39, // ....2729 - 0x31, 0x46, 0x51, 0x48, 0x4e, 0x30, 0x30, 0x31, // 1FQHN001 - 0x31, 0x33, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 13...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x6f, 0x07, 0xa5, 0x46, // ./..o..F + 0x74, 0x74, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0xa2, // tt...BZ. + 0x12, 0xc9, 0x0f, 0x09, 0x32, 0x37, 0x32, 0x39, // ....2729 + 0x31, 0x46, 0x51, 0x48, 0x4e, 0x30, 0x30, 0x31, // 1FQHN001 + 0x31, 0x33, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 13...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10807[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xe0, 0xd5, 0x3d, 0x1f, // ./....=. - 0x54, 0x88, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x9d, // T.....Z. - 0x6e, 0xe5, 0x0f, 0x09, 0x30, 0x34, 0x33, 0x30, // n...0430 - 0x31, 0x46, 0x51, 0x43, 0x42, 0x30, 0x30, 0x32, // 1FQCB002 - 0x36, 0x34, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 64...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xe0, 0xd5, 0x3d, 0x1f, // ./....=. + 0x54, 0x88, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x9d, // T.....Z. + 0x6e, 0xe5, 0x0f, 0x09, 0x30, 0x34, 0x33, 0x30, // n...0430 + 0x31, 0x46, 0x51, 0x43, 0x42, 0x30, 0x30, 0x32, // 1FQCB002 + 0x36, 0x34, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 64...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10808[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xa2, 0x70, 0x36, 0x08, // ./...p6. - 0x9e, 0x08, 0x01, 0x00, 0x18, 0x04, 0x34, 0x25, // ......4% - 0x6d, 0xc5, 0x05, 0x09, 0x5a, 0x32, 0x45, 0x77, // m...Z2Ew - 0x11, 0x03, 0x05, 0x11, 0x0b, 0x11, 0x0c, 0x11, // ........ - 0x0e, 0x11, 0x1e, 0x11, 0x2e, 0x11, 0x00, 0x12, // ........ - 0x33, 0x11, 0x01, 0x05, 0x81, 0x07, 0x00, 0x00, // 3....... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xa2, 0x70, 0x36, 0x08, // ./...p6. + 0x9e, 0x08, 0x01, 0x00, 0x18, 0x04, 0x34, 0x25, // ......4% + 0x6d, 0xc5, 0x05, 0x09, 0x5a, 0x32, 0x45, 0x77, // m...Z2Ew + 0x11, 0x03, 0x05, 0x11, 0x0b, 0x11, 0x0c, 0x11, // ........ + 0x0e, 0x11, 0x1e, 0x11, 0x2e, 0x11, 0x00, 0x12, // ........ + 0x33, 0x11, 0x01, 0x05, 0x81, 0x07, 0x00, 0x00, // 3....... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10809[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xe4, 0xa5, 0xd5, 0x46, // ./.....F - 0x74, 0x74, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0x49, // tt...BZI - 0x2c, 0xe1, 0x0f, 0x09, 0x33, 0x33, 0x30, 0x37, // ,...3307 - 0x31, 0x46, 0x44, 0x48, 0x53, 0x30, 0x30, 0x30, // 1FDHS000 - 0x36, 0x48, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 6H...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xe4, 0xa5, 0xd5, 0x46, // ./.....F + 0x74, 0x74, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0x49, // tt...BZI + 0x2c, 0xe1, 0x0f, 0x09, 0x33, 0x33, 0x30, 0x37, // ,...3307 + 0x31, 0x46, 0x44, 0x48, 0x53, 0x30, 0x30, 0x30, // 1FDHS000 + 0x36, 0x48, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 6H...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10816[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x86, 0x4b, 0x99, 0x3b, // ./...K.; - 0x22, 0x14, 0x01, 0x00, 0x04, 0x07, 0x2a, 0x3c, // ".....*< - 0x2f, 0xbc, 0x13, 0x09, 0x47, 0x6f, 0x6f, 0x67, // /...Goog - 0x6c, 0x65, 0x20, 0x50, 0x69, 0x78, 0x65, 0x6c, // le Pixel - 0x20, 0x57, 0x61, 0x74, 0x63, 0x68, 0x0d, 0x03, // Watch.. - 0x0a, 0x11, 0x0c, 0x11, 0x0e, 0x11, 0x1e, 0x11, // ........ - 0x1f, 0x11, 0x00, 0x12, 0x01, 0x05, 0x81, 0x07, // ........ - 0x66, 0x9a, 0x0c, 0x20, 0x00, 0x08, 0xe2, 0xa5, // f.. .... - 0xe3, 0x11, 0x25, 0x95, 0xb0, 0x45, 0x89, 0x5e, // ..%..E.^ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x86, 0x4b, 0x99, 0x3b, // ./...K.; + 0x22, 0x14, 0x01, 0x00, 0x04, 0x07, 0x2a, 0x3c, // ".....*< + 0x2f, 0xbc, 0x13, 0x09, 0x47, 0x6f, 0x6f, 0x67, // /...Goog + 0x6c, 0x65, 0x20, 0x50, 0x69, 0x78, 0x65, 0x6c, // le Pixel + 0x20, 0x57, 0x61, 0x74, 0x63, 0x68, 0x0d, 0x03, // Watch.. + 0x0a, 0x11, 0x0c, 0x11, 0x0e, 0x11, 0x1e, 0x11, // ........ + 0x1f, 0x11, 0x00, 0x12, 0x01, 0x05, 0x81, 0x07, // ........ + 0x66, 0x9a, 0x0c, 0x20, 0x00, 0x08, 0xe2, 0xa5, // f.. .... + 0xe3, 0x11, 0x25, 0x95, 0xb0, 0x45, 0x89, 0x5e, // ..%..E.^ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10818[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x03, 0xf1, 0xdc, 0x20, // ./..... - 0x8d, 0x3c, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x53, // .<....ZS - 0x16, 0xba, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x03, 0xf1, 0xdc, 0x20, // ./..... + 0x8d, 0x3c, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x53, // .<....ZS + 0x16, 0xba, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10821[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x70, 0x30, 0xf4, 0x2b, // ./..p0.+ - 0x1a, 0xf8, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x86, // ......Z. - 0x78, 0xcc, 0x0f, 0x09, 0x32, 0x31, 0x30, 0x36, // x...2106 - 0x31, 0x46, 0x51, 0x47, 0x52, 0x30, 0x30, 0x31, // 1FQGR001 - 0x30, 0x33, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 03...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x70, 0x30, 0xf4, 0x2b, // ./..p0.+ + 0x1a, 0xf8, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x86, // ......Z. + 0x78, 0xcc, 0x0f, 0x09, 0x32, 0x31, 0x30, 0x36, // x...2106 + 0x31, 0x46, 0x51, 0x47, 0x52, 0x30, 0x30, 0x31, // 1FQGR001 + 0x30, 0x33, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 03...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10823[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x70, 0x31, 0xf4, 0x2b, // ./..p1.+ - 0x1a, 0xf8, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x1c, // ......Z. - 0x61, 0xcd, 0x0f, 0x09, 0x32, 0x31, 0x30, 0x36, // a...2106 - 0x31, 0x46, 0x51, 0x47, 0x52, 0x30, 0x30, 0x31, // 1FQGR001 - 0x30, 0x32, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 02...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x70, 0x31, 0xf4, 0x2b, // ./..p1.+ + 0x1a, 0xf8, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x1c, // ......Z. + 0x61, 0xcd, 0x0f, 0x09, 0x32, 0x31, 0x30, 0x36, // a...2106 + 0x31, 0x46, 0x51, 0x47, 0x52, 0x30, 0x30, 0x31, // 1FQGR001 + 0x30, 0x32, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 02...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10826[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x0d, 0xa2, 0xd5, 0x46, // ./.....F - 0x74, 0x74, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0x9a, // tt...BZ. - 0x14, 0xd8, 0x0f, 0x09, 0x33, 0x33, 0x30, 0x36, // ....3306 - 0x31, 0x46, 0x44, 0x48, 0x53, 0x30, 0x30, 0x30, // 1FDHS000 - 0x37, 0x42, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 7B...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x0d, 0xa2, 0xd5, 0x46, // ./.....F + 0x74, 0x74, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0x9a, // tt...BZ. + 0x14, 0xd8, 0x0f, 0x09, 0x33, 0x33, 0x30, 0x36, // ....3306 + 0x31, 0x46, 0x44, 0x48, 0x53, 0x30, 0x30, 0x30, // 1FDHS000 + 0x37, 0x42, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 7B...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10838[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x61, 0x4a, 0xdd, 0x20, // ./..aJ. - 0x8d, 0x3c, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x03, // .<....Z. - 0x01, 0xbb, 0x0b, 0x09, 0x38, 0x42, 0x4c, 0x41, // ....8BLA - 0x59, 0x30, 0x30, 0x44, 0x55, 0x43, 0x19, 0x03, // Y00DUC.. - 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, 0x0e, 0x11, // ........ - 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, 0x1f, 0x11, // ........ - 0x2d, 0x11, 0x2f, 0x11, 0x00, 0x12, 0x32, 0x11, // -./...2. - 0x01, 0x05, 0x81, 0x07, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x61, 0x4a, 0xdd, 0x20, // ./..aJ. + 0x8d, 0x3c, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x03, // .<....Z. + 0x01, 0xbb, 0x0b, 0x09, 0x38, 0x42, 0x4c, 0x41, // ....8BLA + 0x59, 0x30, 0x30, 0x44, 0x55, 0x43, 0x19, 0x03, // Y00DUC.. + 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, 0x0e, 0x11, // ........ + 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, 0x1f, 0x11, // ........ + 0x2d, 0x11, 0x2f, 0x11, 0x00, 0x12, 0x32, 0x11, // -./...2. + 0x01, 0x05, 0x81, 0x07, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10839[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x98, 0xc3, 0xf3, 0x2b, // ./.....+ - 0x1a, 0xf8, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x8e, // ......Z. - 0x71, 0xcd, 0x0f, 0x09, 0x32, 0x31, 0x30, 0x36, // q...2106 - 0x31, 0x46, 0x51, 0x47, 0x52, 0x30, 0x30, 0x31, // 1FQGR001 - 0x36, 0x33, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 63...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x5a, 0x6c, 0xb1, 0xa7, 0x6d, 0xf1, 0xbc, 0x9b, // Zl..m... - 0xde, 0x3d, 0x5c, 0xae, 0x21, 0xfa, 0x2e, 0xa8, // .=\.!... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x98, 0xc3, 0xf3, 0x2b, // ./.....+ + 0x1a, 0xf8, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x8e, // ......Z. + 0x71, 0xcd, 0x0f, 0x09, 0x32, 0x31, 0x30, 0x36, // q...2106 + 0x31, 0x46, 0x51, 0x47, 0x52, 0x30, 0x30, 0x31, // 1FQGR001 + 0x36, 0x33, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 63...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x5a, 0x6c, 0xb1, 0xa7, 0x6d, 0xf1, 0xbc, 0x9b, // Zl..m... + 0xde, 0x3d, 0x5c, 0xae, 0x21, 0xfa, 0x2e, 0xa8, // .=\.!... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10840[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xda, 0xb2, 0x0a, 0x1f, // ./...... - 0x54, 0x88, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x60, // T.....Z` - 0x34, 0xd2, 0x0f, 0x09, 0x30, 0x34, 0x31, 0x36, // 4...0416 - 0x31, 0x46, 0x51, 0x43, 0x42, 0x30, 0x30, 0x30, // 1FQCB000 - 0x31, 0x32, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 12...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xda, 0xb2, 0x0a, 0x1f, // ./...... + 0x54, 0x88, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x60, // T.....Z` + 0x34, 0xd2, 0x0f, 0x09, 0x30, 0x34, 0x31, 0x36, // 4...0416 + 0x31, 0x46, 0x51, 0x43, 0x42, 0x30, 0x30, 0x30, // 1FQCB000 + 0x31, 0x32, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 12...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10841[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xaa, 0xb2, 0x0a, 0x1f, // ./...... - 0x54, 0x88, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x96, // T.....Z. - 0x00, 0xd2, 0x0f, 0x09, 0x30, 0x34, 0x31, 0x33, // ....0413 - 0x31, 0x46, 0x51, 0x43, 0x42, 0x30, 0x30, 0x34, // 1FQCB004 - 0x36, 0x36, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 66...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xaa, 0xb2, 0x0a, 0x1f, // ./...... + 0x54, 0x88, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x96, // T.....Z. + 0x00, 0xd2, 0x0f, 0x09, 0x30, 0x34, 0x31, 0x33, // ....0413 + 0x31, 0x46, 0x51, 0x43, 0x42, 0x30, 0x30, 0x34, // 1FQCB004 + 0x36, 0x36, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 66...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10842[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x6c, 0x9c, 0xdc, 0x5b, // ./..l..[ - 0xe5, 0xdc, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0xfc, // ......Z. - 0x2b, 0xc1, 0x0f, 0x09, 0x31, 0x39, 0x32, 0x30, // +...1920 - 0x31, 0x46, 0x44, 0x45, 0x45, 0x30, 0x30, 0x38, // 1FDEE008 - 0x33, 0x44, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 3D...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x5a, 0x6c, 0xb1, 0xa7, 0x6d, 0xf1, 0xbc, 0x9b, // Zl..m... - 0xde, 0x3d, 0x5c, 0xae, 0x21, 0xfa, 0x2e, 0xa8, // .=\.!... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x6c, 0x9c, 0xdc, 0x5b, // ./..l..[ + 0xe5, 0xdc, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0xfc, // ......Z. + 0x2b, 0xc1, 0x0f, 0x09, 0x31, 0x39, 0x32, 0x30, // +...1920 + 0x31, 0x46, 0x44, 0x45, 0x45, 0x30, 0x30, 0x38, // 1FDEE008 + 0x33, 0x44, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 3D...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x5a, 0x6c, 0xb1, 0xa7, 0x6d, 0xf1, 0xbc, 0x9b, // Zl..m... + 0xde, 0x3d, 0x5c, 0xae, 0x21, 0xfa, 0x2e, 0xa8, // .=\.!... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10843[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x9b, 0xee, 0x36, 0x08, // ./....6. - 0x9e, 0x08, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0xea, // ......Z. - 0x55, 0xd2, 0x0f, 0x09, 0x30, 0x37, 0x32, 0x38, // U...0728 - 0x31, 0x4a, 0x45, 0x43, 0x42, 0x30, 0x30, 0x33, // 1JECB003 - 0x35, 0x37, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 57...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x9b, 0xee, 0x36, 0x08, // ./....6. + 0x9e, 0x08, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0xea, // ......Z. + 0x55, 0xd2, 0x0f, 0x09, 0x30, 0x37, 0x32, 0x38, // U...0728 + 0x31, 0x4a, 0x45, 0x43, 0x42, 0x30, 0x30, 0x33, // 1JECB003 + 0x35, 0x37, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 57...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10845[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x10, 0xbe, 0xf3, 0x2b, // ./.....+ - 0x1a, 0xf8, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x53, // ......ZS - 0x51, 0xd0, 0x0f, 0x09, 0x32, 0x31, 0x30, 0x36, // Q...2106 - 0x31, 0x46, 0x51, 0x47, 0x52, 0x30, 0x30, 0x31, // 1FQGR001 - 0x36, 0x34, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 64...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x10, 0xbe, 0xf3, 0x2b, // ./.....+ + 0x1a, 0xf8, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x53, // ......ZS + 0x51, 0xd0, 0x0f, 0x09, 0x32, 0x31, 0x30, 0x36, // Q...2106 + 0x31, 0x46, 0x51, 0x47, 0x52, 0x30, 0x30, 0x31, // 1FQGR001 + 0x36, 0x34, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 64...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10857[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xaf, 0x05, 0x7b, 0x43, // ./....{C - 0x37, 0xac, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x6b, // 7.....Zk - 0x5f, 0xcc, 0x0d, 0x09, 0x48, 0x54, 0x36, 0x41, // _...HT6A - 0x36, 0x30, 0x32, 0x30, 0x33, 0x31, 0x32, 0x37, // 60203127 - 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, // ........ - 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, // ........ - 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, 0x00, 0x12, // ..-./... - 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, 0x00, 0x00, // 2....... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xaf, 0x05, 0x7b, 0x43, // ./....{C + 0x37, 0xac, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x6b, // 7.....Zk + 0x5f, 0xcc, 0x0d, 0x09, 0x48, 0x54, 0x36, 0x41, // _...HT6A + 0x36, 0x30, 0x32, 0x30, 0x33, 0x31, 0x32, 0x37, // 60203127 + 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, // ........ + 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, // ........ + 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, 0x00, 0x12, // ..-./... + 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, 0x00, 0x00, // 2....... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10858[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x24, 0x4c, 0xd4, 0x29, // ./..$L.) - 0x24, 0x58, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x47, // $X....ZG - 0x41, 0xc0, 0x0f, 0x09, 0x31, 0x37, 0x30, 0x37, // A...1707 - 0x31, 0x46, 0x44, 0x45, 0x45, 0x30, 0x30, 0x32, // 1FDEE002 - 0x33, 0x47, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 3G...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x5a, 0x6c, 0xb1, 0xa7, 0x6d, 0xf1, 0xbc, 0x9b, // Zl..m... - 0xde, 0x3d, 0x5c, 0xae, 0x21, 0xfa, 0x2e, 0xa8, // .=\.!... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x24, 0x4c, 0xd4, 0x29, // ./..$L.) + 0x24, 0x58, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x47, // $X....ZG + 0x41, 0xc0, 0x0f, 0x09, 0x31, 0x37, 0x30, 0x37, // A...1707 + 0x31, 0x46, 0x44, 0x45, 0x45, 0x30, 0x30, 0x32, // 1FDEE002 + 0x33, 0x47, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 3G...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x5a, 0x6c, 0xb1, 0xa7, 0x6d, 0xf1, 0xbc, 0x9b, // Zl..m... + 0xde, 0x3d, 0x5c, 0xae, 0x21, 0xfa, 0x2e, 0xa8, // .=\.!... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10859[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x81, 0x6a, 0x2f, 0x13, // ./...j/. - 0xc4, 0x0c, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0xdc, // .....BZ. - 0x1b, 0xca, 0x0f, 0x09, 0x32, 0x36, 0x31, 0x35, // ....2615 - 0x31, 0x46, 0x44, 0x48, 0x32, 0x30, 0x30, 0x30, // 1FDH2000 - 0x5a, 0x4d, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // ZM...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x5a, 0x6c, 0xb1, 0xa7, 0x6d, 0xf1, 0xbc, 0x9b, // Zl..m... - 0xde, 0x3d, 0x5c, 0xae, 0x21, 0xfa, 0x2e, 0xa8, // .=\.!... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x81, 0x6a, 0x2f, 0x13, // ./...j/. + 0xc4, 0x0c, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0xdc, // .....BZ. + 0x1b, 0xca, 0x0f, 0x09, 0x32, 0x36, 0x31, 0x35, // ....2615 + 0x31, 0x46, 0x44, 0x48, 0x32, 0x30, 0x30, 0x30, // 1FDH2000 + 0x5a, 0x4d, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // ZM...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x5a, 0x6c, 0xb1, 0xa7, 0x6d, 0xf1, 0xbc, 0x9b, // Zl..m... + 0xde, 0x3d, 0x5c, 0xae, 0x21, 0xfa, 0x2e, 0xa8, // .=\.!... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10860[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xe1, 0xd1, 0x3e, 0x13, // ./....>. - 0xc4, 0x0c, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0x40, // .....BZ@ - 0x1a, 0xcc, 0x0f, 0x09, 0x32, 0x36, 0x31, 0x31, // ....2611 - 0x31, 0x46, 0x44, 0x48, 0x33, 0x30, 0x30, 0x30, // 1FDH3000 - 0x34, 0x41, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 4A...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xe1, 0xd1, 0x3e, 0x13, // ./....>. + 0xc4, 0x0c, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0x40, // .....BZ@ + 0x1a, 0xcc, 0x0f, 0x09, 0x32, 0x36, 0x31, 0x31, // ....2611 + 0x31, 0x46, 0x44, 0x48, 0x33, 0x30, 0x30, 0x30, // 1FDH3000 + 0x34, 0x41, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 4A...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10871[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xac, 0xb8, 0xd5, 0x46, // ./.....F - 0x74, 0x74, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0x44, // tt...BZD - 0x65, 0xe4, 0x0f, 0x09, 0x33, 0x33, 0x30, 0x36, // e...3306 - 0x31, 0x46, 0x44, 0x48, 0x53, 0x30, 0x30, 0x30, // 1FDHS000 - 0x34, 0x45, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 4E...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xac, 0xb8, 0xd5, 0x46, // ./.....F + 0x74, 0x74, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0x44, // tt...BZD + 0x65, 0xe4, 0x0f, 0x09, 0x33, 0x33, 0x30, 0x36, // e...3306 + 0x31, 0x46, 0x44, 0x48, 0x53, 0x30, 0x30, 0x30, // 1FDHS000 + 0x34, 0x45, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 4E...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10872[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xe7, 0x2e, 0xf4, 0x2b, // ./.....+ - 0x1a, 0xf8, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0xf2, // ......Z. - 0x5b, 0xd4, 0x0f, 0x09, 0x32, 0x31, 0x30, 0x36, // [...2106 - 0x31, 0x46, 0x51, 0x47, 0x52, 0x30, 0x30, 0x31, // 1FQGR001 - 0x32, 0x30, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 20...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xe7, 0x2e, 0xf4, 0x2b, // ./.....+ + 0x1a, 0xf8, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0xf2, // ......Z. + 0x5b, 0xd4, 0x0f, 0x09, 0x32, 0x31, 0x30, 0x36, // [...2106 + 0x31, 0x46, 0x51, 0x47, 0x52, 0x30, 0x30, 0x31, // 1FQGR001 + 0x32, 0x30, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 20...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10874[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x69, 0x98, 0x38, 0x6e, // ./..i.8n - 0xb7, 0x60, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0xe6, // .`....Z. - 0x0a, 0xcc, 0x0f, 0x09, 0x30, 0x42, 0x31, 0x31, // ....0B11 - 0x31, 0x46, 0x51, 0x43, 0x42, 0x30, 0x30, 0x31, // 1FQCB001 - 0x30, 0x38, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 08...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x5a, 0x6c, 0xb1, 0xa7, 0x6d, 0xf1, 0xbc, 0x9b, // Zl..m... - 0xde, 0x3d, 0x5c, 0xae, 0x21, 0xfa, 0x2e, 0xa8, // .=\.!... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x69, 0x98, 0x38, 0x6e, // ./..i.8n + 0xb7, 0x60, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0xe6, // .`....Z. + 0x0a, 0xcc, 0x0f, 0x09, 0x30, 0x42, 0x31, 0x31, // ....0B11 + 0x31, 0x46, 0x51, 0x43, 0x42, 0x30, 0x30, 0x31, // 1FQCB001 + 0x30, 0x38, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 08...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x5a, 0x6c, 0xb1, 0xa7, 0x6d, 0xf1, 0xbc, 0x9b, // Zl..m... + 0xde, 0x3d, 0x5c, 0xae, 0x21, 0xfa, 0x2e, 0xa8, // .=\.!... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10876[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x98, 0x6b, 0x36, 0x08, // ./...... - 0x9e, 0x08, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x65, // ......Ze - 0x27, 0xc9, 0x0f, 0x09, 0x39, 0x42, 0x32, 0x37, // '...9B27 - 0x31, 0x46, 0x51, 0x43, 0x32, 0x30, 0x30, 0x32, // 1FQC2002 - 0x34, 0x37, 0x17, 0x03, 0x05, 0x11, 0x0a, 0x11, // 47...... - 0x0c, 0x11, 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, // ........ - 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, 0x00, 0x12, // ..-./... - 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, 0x00, 0x00, // 2....... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x98, 0x6b, 0x36, 0x08, // ./...... + 0x9e, 0x08, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x65, // ......Ze + 0x27, 0xc9, 0x0f, 0x09, 0x39, 0x42, 0x32, 0x37, // '...9B27 + 0x31, 0x46, 0x51, 0x43, 0x32, 0x30, 0x30, 0x32, // 1FQC2002 + 0x34, 0x37, 0x17, 0x03, 0x05, 0x11, 0x0a, 0x11, // 47...... + 0x0c, 0x11, 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, // ........ + 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, 0x00, 0x12, // ..-./... + 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, 0x00, 0x00, // 2....... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10877[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x73, 0x94, 0xf3, 0x2b, // ./..s..+ - 0x1a, 0xf8, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0xab, // ......Z. - 0x12, 0xd6, 0x0f, 0x09, 0x31, 0x39, 0x32, 0x37, // ....1927 - 0x31, 0x46, 0x51, 0x47, 0x52, 0x30, 0x30, 0x30, // 1FQGR000 - 0x32, 0x38, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 28...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x5a, 0x6c, 0xb1, 0xa7, 0x6d, 0xf1, 0xbc, 0x9b, // Zl..m... - 0xde, 0x3d, 0x5c, 0xae, 0x21, 0xfa, 0x2e, 0xa8, // .=\.!... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x73, 0x94, 0xf3, 0x2b, // ./..s..+ + 0x1a, 0xf8, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0xab, // ......Z. + 0x12, 0xd6, 0x0f, 0x09, 0x31, 0x39, 0x32, 0x37, // ....1927 + 0x31, 0x46, 0x51, 0x47, 0x52, 0x30, 0x30, 0x30, // 1FQGR000 + 0x32, 0x38, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 28...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x5a, 0x6c, 0xb1, 0xa7, 0x6d, 0xf1, 0xbc, 0x9b, // Zl..m... + 0xde, 0x3d, 0x5c, 0xae, 0x21, 0xfa, 0x2e, 0xa8, // .=\.!... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10887[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xe9, 0x6e, 0x36, 0x08, // ./...n6. - 0x9e, 0x08, 0x01, 0x00, 0x18, 0x04, 0x34, 0x62, // ......4b - 0x35, 0xc6, 0x05, 0x09, 0x4b, 0x6c, 0x54, 0x76, // 5...KlTv - 0x11, 0x03, 0x05, 0x11, 0x0b, 0x11, 0x0c, 0x11, // ........ - 0x0e, 0x11, 0x1e, 0x11, 0x2e, 0x11, 0x00, 0x12, // ........ - 0x33, 0x11, 0x01, 0x05, 0x81, 0x07, 0x00, 0x00, // 3....... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xe9, 0x6e, 0x36, 0x08, // ./...n6. + 0x9e, 0x08, 0x01, 0x00, 0x18, 0x04, 0x34, 0x62, // ......4b + 0x35, 0xc6, 0x05, 0x09, 0x4b, 0x6c, 0x54, 0x76, // 5...KlTv + 0x11, 0x03, 0x05, 0x11, 0x0b, 0x11, 0x0c, 0x11, // ........ + 0x0e, 0x11, 0x1e, 0x11, 0x2e, 0x11, 0x00, 0x12, // ........ + 0x33, 0x11, 0x01, 0x05, 0x81, 0x07, 0x00, 0x00, // 3....... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10888[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x72, 0x70, 0x36, 0x08, // ./..rp6. - 0x9e, 0x08, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x7b, // ......Z{ - 0x39, 0xcd, 0x0f, 0x09, 0x39, 0x43, 0x30, 0x34, // 9...9C04 - 0x31, 0x46, 0x51, 0x43, 0x32, 0x30, 0x30, 0x33, // 1FQC2003 - 0x30, 0x38, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 08...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x5a, 0x6c, 0xb1, 0xa7, 0x6d, 0xf1, 0xbc, 0x9b, // Zl..m... - 0xde, 0x3d, 0x5c, 0xae, 0x21, 0xfa, 0x2e, 0xa8, // .=\.!... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x72, 0x70, 0x36, 0x08, // ./..rp6. + 0x9e, 0x08, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x7b, // ......Z{ + 0x39, 0xcd, 0x0f, 0x09, 0x39, 0x43, 0x30, 0x34, // 9...9C04 + 0x31, 0x46, 0x51, 0x43, 0x32, 0x30, 0x30, 0x33, // 1FQC2003 + 0x30, 0x38, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 08...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x5a, 0x6c, 0xb1, 0xa7, 0x6d, 0xf1, 0xbc, 0x9b, // Zl..m... + 0xde, 0x3d, 0x5c, 0xae, 0x21, 0xfa, 0x2e, 0xa8, // .=\.!... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10890[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x5a, 0x6d, 0x36, 0x08, // ./..Zm6. - 0x9e, 0x08, 0x01, 0x00, 0x18, 0x04, 0x34, 0xc4, // ......4. - 0x5c, 0xc8, 0x05, 0x09, 0x50, 0x4e, 0x54, 0x39, // \...PNT9 - 0x11, 0x03, 0x05, 0x11, 0x0b, 0x11, 0x0c, 0x11, // ........ - 0x0e, 0x11, 0x1e, 0x11, 0x2e, 0x11, 0x00, 0x12, // ........ - 0x33, 0x11, 0x01, 0x05, 0x81, 0x07, 0x00, 0x00, // 3....... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x5a, 0x6d, 0x36, 0x08, // ./..Zm6. + 0x9e, 0x08, 0x01, 0x00, 0x18, 0x04, 0x34, 0xc4, // ......4. + 0x5c, 0xc8, 0x05, 0x09, 0x50, 0x4e, 0x54, 0x39, // \...PNT9 + 0x11, 0x03, 0x05, 0x11, 0x0b, 0x11, 0x0c, 0x11, // ........ + 0x0e, 0x11, 0x1e, 0x11, 0x2e, 0x11, 0x00, 0x12, // ........ + 0x33, 0x11, 0x01, 0x05, 0x81, 0x07, 0x00, 0x00, // 3....... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10891[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xd8, 0x8b, 0x3e, 0x13, // ./....>. - 0xc4, 0x0c, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0x26, // .....BZ& - 0x3c, 0xc5, 0x0f, 0x09, 0x32, 0x36, 0x31, 0x31, // <...2611 - 0x31, 0x46, 0x44, 0x48, 0x33, 0x30, 0x30, 0x30, // 1FDH3000 - 0x31, 0x38, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 18...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xd8, 0x8b, 0x3e, 0x13, // ./....>. + 0xc4, 0x0c, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0x26, // .....BZ& + 0x3c, 0xc5, 0x0f, 0x09, 0x32, 0x36, 0x31, 0x31, // <...2611 + 0x31, 0x46, 0x44, 0x48, 0x33, 0x30, 0x30, 0x30, // 1FDH3000 + 0x31, 0x38, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 18...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10893[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x36, 0xcc, 0xa4, 0x46, // ./..6..F - 0x74, 0x74, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0xe3, // tt...BZ. - 0x38, 0xcd, 0x0f, 0x09, 0x32, 0x39, 0x30, 0x38, // 8...2908 - 0x31, 0x46, 0x51, 0x48, 0x4e, 0x30, 0x30, 0x31, // 1FQHN001 - 0x35, 0x34, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 54...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x36, 0xcc, 0xa4, 0x46, // ./..6..F + 0x74, 0x74, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0xe3, // tt...BZ. + 0x38, 0xcd, 0x0f, 0x09, 0x32, 0x39, 0x30, 0x38, // 8...2908 + 0x31, 0x46, 0x51, 0x48, 0x4e, 0x30, 0x30, 0x31, // 1FQHN001 + 0x35, 0x34, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 54...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10895[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x59, 0x80, 0x36, 0x08, // ./..Y.6. - 0x9e, 0x08, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x47, // ......ZG - 0x17, 0xcd, 0x0f, 0x09, 0x39, 0x43, 0x31, 0x32, // ....9C12 - 0x31, 0x46, 0x51, 0x43, 0x32, 0x30, 0x30, 0x32, // 1FQC2002 - 0x33, 0x32, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 32...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x59, 0x80, 0x36, 0x08, // ./..Y.6. + 0x9e, 0x08, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x47, // ......ZG + 0x17, 0xcd, 0x0f, 0x09, 0x39, 0x43, 0x31, 0x32, // ....9C12 + 0x31, 0x46, 0x51, 0x43, 0x32, 0x30, 0x30, 0x32, // 1FQC2002 + 0x33, 0x32, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 32...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10904[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x5f, 0xc8, 0xdc, 0x20, // ./.._.. - 0x8d, 0x3c, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x8f, // .<....Z. - 0x1c, 0xc3, 0x0b, 0x09, 0x38, 0x39, 0x4e, 0x41, // ....89NA - 0x58, 0x30, 0x30, 0x36, 0x45, 0x4a, 0x19, 0x03, // X006EJ.. - 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, 0x0e, 0x11, // ........ - 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, 0x1f, 0x11, // ........ - 0x2d, 0x11, 0x2f, 0x11, 0x00, 0x12, 0x32, 0x11, // -./...2. - 0x01, 0x05, 0x81, 0x07, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x5f, 0xc8, 0xdc, 0x20, // ./.._.. + 0x8d, 0x3c, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x8f, // .<....Z. + 0x1c, 0xc3, 0x0b, 0x09, 0x38, 0x39, 0x4e, 0x41, // ....89NA + 0x58, 0x30, 0x30, 0x36, 0x45, 0x4a, 0x19, 0x03, // X006EJ.. + 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, 0x0e, 0x11, // ........ + 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, 0x1f, 0x11, // ........ + 0x2d, 0x11, 0x2f, 0x11, 0x00, 0x12, 0x32, 0x11, // -./...2. + 0x01, 0x05, 0x81, 0x07, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10906[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xad, 0xad, 0x36, 0x08, // ./....6. - 0x9e, 0x08, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x73, // ......Zs - 0x44, 0xdf, 0x0f, 0x09, 0x30, 0x31, 0x30, 0x38, // D...0108 - 0x31, 0x46, 0x51, 0x43, 0x32, 0x30, 0x30, 0x37, // 1FQC2007 - 0x34, 0x37, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 47...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xad, 0xad, 0x36, 0x08, // ./....6. + 0x9e, 0x08, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x73, // ......Zs + 0x44, 0xdf, 0x0f, 0x09, 0x30, 0x31, 0x30, 0x38, // D...0108 + 0x31, 0x46, 0x51, 0x43, 0x32, 0x30, 0x30, 0x37, // 1FQC2007 + 0x34, 0x37, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 47...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10910[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x5d, 0x39, 0x57, 0x2c, // ./..]9W, - 0x3a, 0xd4, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0x5b, // :....BZ[ - 0x71, 0xc7, 0x0f, 0x09, 0x33, 0x33, 0x31, 0x34, // q...3314 - 0x31, 0x46, 0x44, 0x4a, 0x47, 0x30, 0x30, 0x30, // 1FDJG000 - 0x50, 0x41, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // PA...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x5d, 0x39, 0x57, 0x2c, // ./..]9W, + 0x3a, 0xd4, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0x5b, // :....BZ[ + 0x71, 0xc7, 0x0f, 0x09, 0x33, 0x33, 0x31, 0x34, // q...3314 + 0x31, 0x46, 0x44, 0x4a, 0x47, 0x30, 0x30, 0x30, // 1FDJG000 + 0x50, 0x41, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // PA...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10911[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xf8, 0x4a, 0xd4, 0x29, // ./...J.) - 0x24, 0x58, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x0d, // $X....Z. - 0x1a, 0xd1, 0x0f, 0x09, 0x31, 0x37, 0x30, 0x37, // ....1707 - 0x31, 0x46, 0x44, 0x45, 0x45, 0x30, 0x30, 0x32, // 1FDEE002 - 0x34, 0x47, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 4G...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x5a, 0x6c, 0xb1, 0xa7, 0x6d, 0xf1, 0xbc, 0x9b, // Zl..m... - 0xde, 0x3d, 0x5c, 0xae, 0x21, 0xfa, 0x2e, 0xa8, // .=\.!... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xf8, 0x4a, 0xd4, 0x29, // ./...J.) + 0x24, 0x58, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x0d, // $X....Z. + 0x1a, 0xd1, 0x0f, 0x09, 0x31, 0x37, 0x30, 0x37, // ....1707 + 0x31, 0x46, 0x44, 0x45, 0x45, 0x30, 0x30, 0x32, // 1FDEE002 + 0x34, 0x47, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 4G...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x5a, 0x6c, 0xb1, 0xa7, 0x6d, 0xf1, 0xbc, 0x9b, // Zl..m... + 0xde, 0x3d, 0x5c, 0xae, 0x21, 0xfa, 0x2e, 0xa8, // .=\.!... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10915[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x93, 0x02, 0xd4, 0x29, // ./.....) - 0x24, 0x58, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x24, // $X....Z$ - 0x77, 0xd2, 0x0f, 0x09, 0x31, 0x34, 0x32, 0x38, // w...1428 - 0x31, 0x46, 0x44, 0x45, 0x45, 0x30, 0x30, 0x30, // 1FDEE000 - 0x44, 0x47, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // DG...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x5a, 0x6c, 0xb1, 0xa7, 0x6d, 0xf1, 0xbc, 0x9b, // Zl..m... - 0xde, 0x3d, 0x5c, 0xae, 0x21, 0xfa, 0x2e, 0xa8, // .=\.!... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x93, 0x02, 0xd4, 0x29, // ./.....) + 0x24, 0x58, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x24, // $X....Z$ + 0x77, 0xd2, 0x0f, 0x09, 0x31, 0x34, 0x32, 0x38, // w...1428 + 0x31, 0x46, 0x44, 0x45, 0x45, 0x30, 0x30, 0x30, // 1FDEE000 + 0x44, 0x47, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // DG...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x5a, 0x6c, 0xb1, 0xa7, 0x6d, 0xf1, 0xbc, 0x9b, // Zl..m... + 0xde, 0x3d, 0x5c, 0xae, 0x21, 0xfa, 0x2e, 0xa8, // .=\.!... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10916[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x5a, 0x75, 0x39, 0x6e, // ./..Zu9n - 0xb7, 0x60, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x45, // .`....ZE - 0x3a, 0xdb, 0x0f, 0x09, 0x31, 0x34, 0x32, 0x30, // :...1420 - 0x31, 0x4a, 0x45, 0x43, 0x42, 0x30, 0x30, 0x32, // 1JECB002 - 0x34, 0x32, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 42...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x5a, 0x6c, 0xb1, 0xa7, 0x6d, 0xf1, 0xbc, 0x9b, // Zl..m... - 0xde, 0x3d, 0x5c, 0xae, 0x21, 0xfa, 0x2e, 0xa8, // .=\.!... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x5a, 0x75, 0x39, 0x6e, // ./..Zu9n + 0xb7, 0x60, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x45, // .`....ZE + 0x3a, 0xdb, 0x0f, 0x09, 0x31, 0x34, 0x32, 0x30, // :...1420 + 0x31, 0x4a, 0x45, 0x43, 0x42, 0x30, 0x30, 0x32, // 1JECB002 + 0x34, 0x32, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 42...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x5a, 0x6c, 0xb1, 0xa7, 0x6d, 0xf1, 0xbc, 0x9b, // Zl..m... + 0xde, 0x3d, 0x5c, 0xae, 0x21, 0xfa, 0x2e, 0xa8, // .=\.!... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10922[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x31, 0x5b, 0x7f, 0x2f, // ./..1[./ - 0x95, 0x24, 0x01, 0x00, 0x10, 0x41, 0x5a, 0xf1, // .$...AZ. - 0x19, 0xd4, 0x0f, 0x09, 0x33, 0x32, 0x30, 0x32, // ....3202 - 0x31, 0x30, 0x35, 0x48, 0x38, 0x30, 0x33, 0x43, // 105H803C - 0x4e, 0x57, 0x13, 0x03, 0x05, 0x11, 0x0a, 0x11, // NW...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x00, 0x12, 0x01, 0x05, // ........ - 0x81, 0x07, 0x5a, 0x6c, 0xb1, 0xa7, 0x6d, 0xf1, // ..Zl..m. - 0xbc, 0x9b, 0xde, 0x3d, 0x5c, 0xae, 0x21, 0xfa, // ...=\.!. - 0x2e, 0xa8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x31, 0x5b, 0x7f, 0x2f, // ./..1[./ + 0x95, 0x24, 0x01, 0x00, 0x10, 0x41, 0x5a, 0xf1, // .$...AZ. + 0x19, 0xd4, 0x0f, 0x09, 0x33, 0x32, 0x30, 0x32, // ....3202 + 0x31, 0x30, 0x35, 0x48, 0x38, 0x30, 0x33, 0x43, // 105H803C + 0x4e, 0x57, 0x13, 0x03, 0x05, 0x11, 0x0a, 0x11, // NW...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x00, 0x12, 0x01, 0x05, // ........ + 0x81, 0x07, 0x5a, 0x6c, 0xb1, 0xa7, 0x6d, 0xf1, // ..Zl..m. + 0xbc, 0x9b, 0xde, 0x3d, 0x5c, 0xae, 0x21, 0xfa, // ...=\.!. + 0x2e, 0xa8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10927[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x4d, 0x7a, 0x4f, 0x52, // ./..MzOR - 0xcb, 0x58, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0xd9, // .X....Z. - 0x45, 0xcd, 0x0b, 0x09, 0x39, 0x35, 0x39, 0x41, // E...959A - 0x58, 0x30, 0x46, 0x36, 0x4a, 0x5a, 0x19, 0x03, // X0F6JZ.. - 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, 0x0e, 0x11, // ........ - 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, 0x1f, 0x11, // ........ - 0x2d, 0x11, 0x2f, 0x11, 0x00, 0x12, 0x32, 0x11, // -./...2. - 0x01, 0x05, 0x81, 0x07, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x4d, 0x7a, 0x4f, 0x52, // ./..MzOR + 0xcb, 0x58, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0xd9, // .X....Z. + 0x45, 0xcd, 0x0b, 0x09, 0x39, 0x35, 0x39, 0x41, // E...959A + 0x58, 0x30, 0x46, 0x36, 0x4a, 0x5a, 0x19, 0x03, // X0F6JZ.. + 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, 0x0e, 0x11, // ........ + 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, 0x1f, 0x11, // ........ + 0x2d, 0x11, 0x2f, 0x11, 0x00, 0x12, 0x32, 0x11, // -./...2. + 0x01, 0x05, 0x81, 0x07, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10928[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x34, 0x64, 0x3e, 0x13, // ./..4d>. - 0xc4, 0x0c, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0xc4, // .....BZ. - 0x7d, 0xd1, 0x0f, 0x09, 0x32, 0x35, 0x30, 0x35, // }...2505 - 0x31, 0x46, 0x44, 0x48, 0x33, 0x30, 0x30, 0x30, // 1FDH3000 - 0x34, 0x37, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 47...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x5a, 0x6c, 0xb1, 0xa7, 0x6d, 0xf1, 0xbc, 0x9b, // Zl..m... - 0xde, 0x3d, 0x5c, 0xae, 0x21, 0xfa, 0x2e, 0xa8, // .=\.!... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x34, 0x64, 0x3e, 0x13, // ./..4d>. + 0xc4, 0x0c, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0xc4, // .....BZ. + 0x7d, 0xd1, 0x0f, 0x09, 0x32, 0x35, 0x30, 0x35, // }...2505 + 0x31, 0x46, 0x44, 0x48, 0x33, 0x30, 0x30, 0x30, // 1FDH3000 + 0x34, 0x37, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 47...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x5a, 0x6c, 0xb1, 0xa7, 0x6d, 0xf1, 0xbc, 0x9b, // Zl..m... + 0xde, 0x3d, 0x5c, 0xae, 0x21, 0xfa, 0x2e, 0xa8, // .=\.!... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10930[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x23, 0x47, 0x04, 0x36, // ./..#G.6 - 0x4e, 0x40, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x8b, // N@....Z. - 0x45, 0xcb, 0x0d, 0x09, 0x48, 0x54, 0x37, 0x33, // E...HT73 - 0x52, 0x31, 0x41, 0x30, 0x30, 0x30, 0x30, 0x35, // R1A00005 - 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, // ........ - 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, // ........ - 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, 0x00, 0x12, // ..-./... - 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, 0x00, 0x00, // 2....... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x23, 0x47, 0x04, 0x36, // ./..#G.6 + 0x4e, 0x40, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x8b, // N@....Z. + 0x45, 0xcb, 0x0d, 0x09, 0x48, 0x54, 0x37, 0x33, // E...HT73 + 0x52, 0x31, 0x41, 0x30, 0x30, 0x30, 0x30, 0x35, // R1A00005 + 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, // ........ + 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, // ........ + 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, 0x00, 0x12, // ..-./... + 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, 0x00, 0x00, // 2....... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10931[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xb2, 0x65, 0xdd, 0x20, // ./...e. - 0x8d, 0x3c, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0xe8, // .<....Z. - 0x45, 0xc7, 0x0b, 0x09, 0x38, 0x39, 0x4e, 0x41, // E...89NA - 0x59, 0x30, 0x30, 0x38, 0x32, 0x44, 0x19, 0x03, // Y0082D.. - 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, 0x0e, 0x11, // ........ - 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, 0x1f, 0x11, // ........ - 0x2d, 0x11, 0x2f, 0x11, 0x00, 0x12, 0x32, 0x11, // -./...2. - 0x01, 0x05, 0x81, 0x07, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xb2, 0x65, 0xdd, 0x20, // ./...e. + 0x8d, 0x3c, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0xe8, // .<....Z. + 0x45, 0xc7, 0x0b, 0x09, 0x38, 0x39, 0x4e, 0x41, // E...89NA + 0x59, 0x30, 0x30, 0x38, 0x32, 0x44, 0x19, 0x03, // Y0082D.. + 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, 0x0e, 0x11, // ........ + 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, 0x1f, 0x11, // ........ + 0x2d, 0x11, 0x2f, 0x11, 0x00, 0x12, 0x32, 0x11, // -./...2. + 0x01, 0x05, 0x81, 0x07, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10932[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x62, 0x38, 0xd5, 0x46, // ./..b8.F - 0x74, 0x74, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0xc7, // tt...BZ. - 0x2e, 0xca, 0x0f, 0x09, 0x33, 0x32, 0x30, 0x34, // ....3204 - 0x31, 0x46, 0x44, 0x48, 0x53, 0x30, 0x30, 0x30, // 1FDHS000 - 0x36, 0x59, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 6Y...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x62, 0x38, 0xd5, 0x46, // ./..b8.F + 0x74, 0x74, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0xc7, // tt...BZ. + 0x2e, 0xca, 0x0f, 0x09, 0x33, 0x32, 0x30, 0x34, // ....3204 + 0x31, 0x46, 0x44, 0x48, 0x53, 0x30, 0x30, 0x30, // 1FDHS000 + 0x36, 0x59, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 6Y...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10934[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x06, 0x82, 0x52, 0x52, // ./....RR - 0xcb, 0x58, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x44, // .X....ZD - 0x28, 0xca, 0x0b, 0x09, 0x39, 0x36, 0x4b, 0x41, // (...96KA - 0x58, 0x30, 0x48, 0x32, 0x5a, 0x32, 0x19, 0x03, // X0H2Z2.. - 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, 0x0e, 0x11, // ........ - 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, 0x1f, 0x11, // ........ - 0x2d, 0x11, 0x2f, 0x11, 0x00, 0x12, 0x32, 0x11, // -./...2. - 0x01, 0x05, 0x81, 0x07, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x06, 0x82, 0x52, 0x52, // ./....RR + 0xcb, 0x58, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x44, // .X....ZD + 0x28, 0xca, 0x0b, 0x09, 0x39, 0x36, 0x4b, 0x41, // (...96KA + 0x58, 0x30, 0x48, 0x32, 0x5a, 0x32, 0x19, 0x03, // X0H2Z2.. + 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, 0x0e, 0x11, // ........ + 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, 0x1f, 0x11, // ........ + 0x2d, 0x11, 0x2f, 0x11, 0x00, 0x12, 0x32, 0x11, // -./...2. + 0x01, 0x05, 0x81, 0x07, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10940[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x30, 0xcb, 0xd5, 0x46, // ./..0..F - 0x74, 0x74, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0x8d, // tt...BZ. - 0x7c, 0xe3, 0x0f, 0x09, 0x33, 0x33, 0x31, 0x33, // |...3313 - 0x31, 0x46, 0x44, 0x48, 0x53, 0x30, 0x30, 0x30, // 1FDHS000 - 0x34, 0x35, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 45...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x30, 0xcb, 0xd5, 0x46, // ./..0..F + 0x74, 0x74, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0x8d, // tt...BZ. + 0x7c, 0xe3, 0x0f, 0x09, 0x33, 0x33, 0x31, 0x33, // |...3313 + 0x31, 0x46, 0x44, 0x48, 0x53, 0x30, 0x30, 0x30, // 1FDHS000 + 0x34, 0x35, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 45...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10952[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xae, 0xee, 0x55, 0x52, // ./....UR - 0xcb, 0x58, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0xbb, // .X....Z. - 0x1d, 0xc2, 0x0b, 0x09, 0x39, 0x39, 0x47, 0x41, // ....99GA - 0x58, 0x30, 0x4b, 0x42, 0x44, 0x31, 0x19, 0x03, // X0KBD1.. - 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, 0x0e, 0x11, // ........ - 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, 0x1f, 0x11, // ........ - 0x2d, 0x11, 0x2f, 0x11, 0x00, 0x12, 0x32, 0x11, // -./...2. - 0x01, 0x05, 0x81, 0x07, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xae, 0xee, 0x55, 0x52, // ./....UR + 0xcb, 0x58, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0xbb, // .X....Z. + 0x1d, 0xc2, 0x0b, 0x09, 0x39, 0x39, 0x47, 0x41, // ....99GA + 0x58, 0x30, 0x4b, 0x42, 0x44, 0x31, 0x19, 0x03, // X0KBD1.. + 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, 0x0e, 0x11, // ........ + 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, 0x1f, 0x11, // ........ + 0x2d, 0x11, 0x2f, 0x11, 0x00, 0x12, 0x32, 0x11, // -./...2. + 0x01, 0x05, 0x81, 0x07, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10953[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xec, 0xd5, 0x3d, 0x1f, // ./....=. - 0x54, 0x88, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0xe7, // T.....Z. - 0x57, 0xd8, 0x0f, 0x09, 0x30, 0x34, 0x33, 0x30, // W...0430 - 0x31, 0x46, 0x51, 0x43, 0x42, 0x30, 0x30, 0x32, // 1FQCB002 - 0x36, 0x30, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 60...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xec, 0xd5, 0x3d, 0x1f, // ./....=. + 0x54, 0x88, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0xe7, // T.....Z. + 0x57, 0xd8, 0x0f, 0x09, 0x30, 0x34, 0x33, 0x30, // W...0430 + 0x31, 0x46, 0x51, 0x43, 0x42, 0x30, 0x30, 0x32, // 1FQCB002 + 0x36, 0x30, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 60...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10959[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xa7, 0x67, 0xdd, 0x20, // ./...g. - 0x8d, 0x3c, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0xe6, // .<....Z. - 0x0e, 0xc3, 0x0b, 0x09, 0x38, 0x39, 0x37, 0x41, // ....897A - 0x59, 0x30, 0x30, 0x31, 0x5a, 0x58, 0x17, 0x03, // Y001ZX.. - 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, 0x12, 0x11, // ........ - 0x15, 0x11, 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, // ......-. - 0x2f, 0x11, 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, // /...2... - 0x81, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xa7, 0x67, 0xdd, 0x20, // ./...g. + 0x8d, 0x3c, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0xe6, // .<....Z. + 0x0e, 0xc3, 0x0b, 0x09, 0x38, 0x39, 0x37, 0x41, // ....897A + 0x59, 0x30, 0x30, 0x31, 0x5a, 0x58, 0x17, 0x03, // Y001ZX.. + 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, 0x12, 0x11, // ........ + 0x15, 0x11, 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, // ......-. + 0x2f, 0x11, 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, // /...2... + 0x81, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10962[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x18, 0xae, 0xdd, 0x29, // ./.....) - 0x24, 0x58, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0xbe, // $X....Z. - 0x50, 0xcc, 0x0f, 0x09, 0x31, 0x37, 0x31, 0x33, // P...1713 - 0x31, 0x46, 0x44, 0x46, 0x36, 0x30, 0x30, 0x30, // 1FDF6000 - 0x43, 0x4a, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // CJ...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x18, 0xae, 0xdd, 0x29, // ./.....) + 0x24, 0x58, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0xbe, // $X....Z. + 0x50, 0xcc, 0x0f, 0x09, 0x31, 0x37, 0x31, 0x33, // P...1713 + 0x31, 0x46, 0x44, 0x46, 0x36, 0x30, 0x30, 0x30, // 1FDF6000 + 0x43, 0x4a, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // CJ...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10965[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x2a, 0x4e, 0xd4, 0x29, // ./..*N.) - 0x24, 0x58, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0xa1, // $X....Z. - 0x38, 0xcb, 0x0f, 0x09, 0x31, 0x37, 0x30, 0x37, // 8...1707 - 0x31, 0x46, 0x44, 0x45, 0x45, 0x30, 0x30, 0x32, // 1FDEE002 - 0x39, 0x32, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 92...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x5a, 0x6c, 0xb1, 0xa7, 0x6d, 0xf1, 0xbc, 0x9b, // Zl..m... - 0xde, 0x3d, 0x5c, 0xae, 0x21, 0xfa, 0x2e, 0xa8, // .=\.!... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x2a, 0x4e, 0xd4, 0x29, // ./..*N.) + 0x24, 0x58, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0xa1, // $X....Z. + 0x38, 0xcb, 0x0f, 0x09, 0x31, 0x37, 0x30, 0x37, // 8...1707 + 0x31, 0x46, 0x44, 0x45, 0x45, 0x30, 0x30, 0x32, // 1FDEE002 + 0x39, 0x32, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 92...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x5a, 0x6c, 0xb1, 0xa7, 0x6d, 0xf1, 0xbc, 0x9b, // Zl..m... + 0xde, 0x3d, 0x5c, 0xae, 0x21, 0xfa, 0x2e, 0xa8, // .=\.!... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10967[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xa8, 0x4f, 0xd4, 0x29, // ./...O.) - 0x24, 0x58, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x23, // $X....Z# - 0x47, 0xc4, 0x0f, 0x09, 0x31, 0x37, 0x30, 0x37, // G...1707 - 0x31, 0x46, 0x44, 0x45, 0x45, 0x30, 0x30, 0x32, // 1FDEE002 - 0x36, 0x42, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 6B...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xa8, 0x4f, 0xd4, 0x29, // ./...O.) + 0x24, 0x58, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x23, // $X....Z# + 0x47, 0xc4, 0x0f, 0x09, 0x31, 0x37, 0x30, 0x37, // G...1707 + 0x31, 0x46, 0x44, 0x45, 0x45, 0x30, 0x30, 0x32, // 1FDEE002 + 0x36, 0x42, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 6B...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10973[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x9f, 0x98, 0x38, 0x6e, // ./....8n - 0xb7, 0x60, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0xf4, // .`....Z. - 0x2c, 0xcf, 0x0f, 0x09, 0x30, 0x42, 0x31, 0x31, // ,...0B11 - 0x31, 0x46, 0x51, 0x43, 0x42, 0x30, 0x30, 0x30, // 1FQCB000 - 0x38, 0x39, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 89...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x9f, 0x98, 0x38, 0x6e, // ./....8n + 0xb7, 0x60, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0xf4, // .`....Z. + 0x2c, 0xcf, 0x0f, 0x09, 0x30, 0x42, 0x31, 0x31, // ,...0B11 + 0x31, 0x46, 0x51, 0x43, 0x42, 0x30, 0x30, 0x30, // 1FQCB000 + 0x38, 0x39, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 89...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10976[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x85, 0x6f, 0x36, 0x08, // ./...o6. - 0x9e, 0x08, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x32, // ......Z2 - 0x0c, 0xc8, 0x0f, 0x09, 0x39, 0x42, 0x32, 0x37, // ....9B27 - 0x31, 0x46, 0x51, 0x43, 0x32, 0x30, 0x30, 0x31, // 1FQC2001 - 0x39, 0x33, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 93...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x5a, 0x6c, 0xb1, 0xa7, 0x6d, 0xf1, 0xbc, 0x9b, // Zl..m... - 0xde, 0x3d, 0x5c, 0xae, 0x21, 0xfa, 0x2e, 0xa8, // .=\.!... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x85, 0x6f, 0x36, 0x08, // ./...o6. + 0x9e, 0x08, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x32, // ......Z2 + 0x0c, 0xc8, 0x0f, 0x09, 0x39, 0x42, 0x32, 0x37, // ....9B27 + 0x31, 0x46, 0x51, 0x43, 0x32, 0x30, 0x30, 0x31, // 1FQC2001 + 0x39, 0x33, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 93...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x5a, 0x6c, 0xb1, 0xa7, 0x6d, 0xf1, 0xbc, 0x9b, // Zl..m... + 0xde, 0x3d, 0x5c, 0xae, 0x21, 0xfa, 0x2e, 0xa8, // .=\.!... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10982[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x79, 0xb0, 0x7e, 0x2f, // ./..y.~/ - 0x95, 0x24, 0x01, 0x00, 0x10, 0x41, 0x5a, 0x66, // .$...AZf - 0x05, 0xca, 0x0f, 0x09, 0x33, 0x32, 0x30, 0x32, // ....3202 - 0x31, 0x30, 0x35, 0x48, 0x38, 0x30, 0x31, 0x31, // 105H8011 - 0x4e, 0x31, 0x13, 0x03, 0x05, 0x11, 0x0a, 0x11, // N1...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x00, 0x12, 0x01, 0x05, // ........ - 0x81, 0x07, 0x5a, 0x6c, 0xb1, 0xa7, 0x6d, 0xf1, // ..Zl..m. - 0xbc, 0x9b, 0xde, 0x3d, 0x5c, 0xae, 0x21, 0xfa, // ...=\.!. - 0x2e, 0xa8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x79, 0xb0, 0x7e, 0x2f, // ./..y.~/ + 0x95, 0x24, 0x01, 0x00, 0x10, 0x41, 0x5a, 0x66, // .$...AZf + 0x05, 0xca, 0x0f, 0x09, 0x33, 0x32, 0x30, 0x32, // ....3202 + 0x31, 0x30, 0x35, 0x48, 0x38, 0x30, 0x31, 0x31, // 105H8011 + 0x4e, 0x31, 0x13, 0x03, 0x05, 0x11, 0x0a, 0x11, // N1...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x00, 0x12, 0x01, 0x05, // ........ + 0x81, 0x07, 0x5a, 0x6c, 0xb1, 0xa7, 0x6d, 0xf1, // ..Zl..m. + 0xbc, 0x9b, 0xde, 0x3d, 0x5c, 0xae, 0x21, 0xfa, // ...=\.!. + 0x2e, 0xa8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10984[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x82, 0xba, 0xdc, 0x20, // ./..... - 0x8d, 0x3c, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x93, // .<....Z. - 0x47, 0xc8, 0x0b, 0x09, 0x38, 0x39, 0x4d, 0x41, // G...89MA - 0x58, 0x30, 0x30, 0x36, 0x34, 0x34, 0x19, 0x03, // X00644.. - 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, 0x0e, 0x11, // ........ - 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, 0x1f, 0x11, // ........ - 0x2d, 0x11, 0x2f, 0x11, 0x00, 0x12, 0x32, 0x11, // -./...2. - 0x01, 0x05, 0x81, 0x07, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x82, 0xba, 0xdc, 0x20, // ./..... + 0x8d, 0x3c, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x93, // .<....Z. + 0x47, 0xc8, 0x0b, 0x09, 0x38, 0x39, 0x4d, 0x41, // G...89MA + 0x58, 0x30, 0x30, 0x36, 0x34, 0x34, 0x19, 0x03, // X00644.. + 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, 0x0e, 0x11, // ........ + 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, 0x1f, 0x11, // ........ + 0x2d, 0x11, 0x2f, 0x11, 0x00, 0x12, 0x32, 0x11, // -./...2. + 0x01, 0x05, 0x81, 0x07, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10986[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xa9, 0x51, 0x2f, 0x13, // ./...Q/. - 0xc4, 0x0c, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0xba, // .....BZ. - 0x30, 0xc3, 0x0f, 0x09, 0x32, 0x36, 0x31, 0x36, // 0...2616 - 0x31, 0x46, 0x44, 0x48, 0x32, 0x30, 0x30, 0x31, // 1FDH2001 - 0x36, 0x31, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 61...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x5a, 0x6c, 0xb1, 0xa7, 0x6d, 0xf1, 0xbc, 0x9b, // Zl..m... - 0xde, 0x3d, 0x5c, 0xae, 0x21, 0xfa, 0x2e, 0xa8, // .=\.!... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xa9, 0x51, 0x2f, 0x13, // ./...Q/. + 0xc4, 0x0c, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0xba, // .....BZ. + 0x30, 0xc3, 0x0f, 0x09, 0x32, 0x36, 0x31, 0x36, // 0...2616 + 0x31, 0x46, 0x44, 0x48, 0x32, 0x30, 0x30, 0x31, // 1FDH2001 + 0x36, 0x31, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 61...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x5a, 0x6c, 0xb1, 0xa7, 0x6d, 0xf1, 0xbc, 0x9b, // Zl..m... + 0xde, 0x3d, 0x5c, 0xae, 0x21, 0xfa, 0x2e, 0xa8, // .=\.!... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10987[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xf5, 0xd5, 0x3d, 0x1f, // ./....=. - 0x54, 0x88, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x20, // T.....Z - 0x17, 0xd9, 0x0f, 0x09, 0x30, 0x34, 0x33, 0x30, // ....0430 - 0x31, 0x46, 0x51, 0x43, 0x42, 0x30, 0x30, 0x31, // 1FQCB001 - 0x35, 0x35, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 55...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xf5, 0xd5, 0x3d, 0x1f, // ./....=. + 0x54, 0x88, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x20, // T.....Z + 0x17, 0xd9, 0x0f, 0x09, 0x30, 0x34, 0x33, 0x30, // ....0430 + 0x31, 0x46, 0x51, 0x43, 0x42, 0x30, 0x30, 0x31, // 1FQCB001 + 0x35, 0x35, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 55...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10997[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xd7, 0xb2, 0x0a, 0x1f, // ./...... - 0x54, 0x88, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0xb9, // T.....Z. - 0x08, 0xd4, 0x0f, 0x09, 0x30, 0x34, 0x31, 0x36, // ....0416 - 0x31, 0x46, 0x51, 0x43, 0x42, 0x30, 0x30, 0x31, // 1FQCB001 - 0x30, 0x32, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 02...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xd7, 0xb2, 0x0a, 0x1f, // ./...... + 0x54, 0x88, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0xb9, // T.....Z. + 0x08, 0xd4, 0x0f, 0x09, 0x30, 0x34, 0x31, 0x36, // ....0416 + 0x31, 0x46, 0x51, 0x43, 0x42, 0x30, 0x30, 0x31, // 1FQCB001 + 0x30, 0x32, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 02...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt10999[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xc6, 0xcf, 0x0a, 0x1f, // ./...... - 0x54, 0x88, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x7f, // T.....Z. - 0x26, 0xd7, 0x0f, 0x09, 0x30, 0x36, 0x31, 0x30, // &...0610 - 0x31, 0x46, 0x51, 0x43, 0x42, 0x30, 0x30, 0x33, // 1FQCB003 - 0x34, 0x33, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 43...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xc6, 0xcf, 0x0a, 0x1f, // ./...... + 0x54, 0x88, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x7f, // T.....Z. + 0x26, 0xd7, 0x0f, 0x09, 0x30, 0x36, 0x31, 0x30, // &...0610 + 0x31, 0x46, 0x51, 0x43, 0x42, 0x30, 0x30, 0x33, // 1FQCB003 + 0x34, 0x33, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 43...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt11008[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xd6, 0xb0, 0x2e, 0x13, // ./...... - 0xc4, 0x0c, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0x58, // .....BZX - 0x73, 0xd3, 0x0f, 0x09, 0x32, 0x31, 0x30, 0x35, // s...2105 - 0x31, 0x46, 0x44, 0x48, 0x32, 0x30, 0x30, 0x30, // 1FDH2000 - 0x33, 0x36, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 36...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x5a, 0x6c, 0xb1, 0xa7, 0x6d, 0xf1, 0xbc, 0x9b, // Zl..m... - 0xde, 0x3d, 0x5c, 0xae, 0x21, 0xfa, 0x2e, 0xa8, // .=\.!... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xd6, 0xb0, 0x2e, 0x13, // ./...... + 0xc4, 0x0c, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0x58, // .....BZX + 0x73, 0xd3, 0x0f, 0x09, 0x32, 0x31, 0x30, 0x35, // s...2105 + 0x31, 0x46, 0x44, 0x48, 0x32, 0x30, 0x30, 0x30, // 1FDH2000 + 0x33, 0x36, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 36...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x5a, 0x6c, 0xb1, 0xa7, 0x6d, 0xf1, 0xbc, 0x9b, // Zl..m... + 0xde, 0x3d, 0x5c, 0xae, 0x21, 0xfa, 0x2e, 0xa8, // .=\.!... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt11009[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xd9, 0x91, 0x57, 0x2c, // ./....W, - 0x3a, 0xd4, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0xa9, // :....BZ. - 0x06, 0xc1, 0x0f, 0x09, 0x33, 0x33, 0x31, 0x36, // ....3316 - 0x31, 0x46, 0x44, 0x4a, 0x47, 0x30, 0x30, 0x30, // 1FDJG000 - 0x38, 0x31, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 81...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xd9, 0x91, 0x57, 0x2c, // ./....W, + 0x3a, 0xd4, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0xa9, // :....BZ. + 0x06, 0xc1, 0x0f, 0x09, 0x33, 0x33, 0x31, 0x36, // ....3316 + 0x31, 0x46, 0x44, 0x4a, 0x47, 0x30, 0x30, 0x30, // 1FDJG000 + 0x38, 0x31, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 81...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt11020[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xbc, 0x67, 0xdd, 0x20, // ./...g. - 0x8d, 0x3c, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x0e, // .<....Z. - 0x06, 0xc8, 0x0b, 0x09, 0x38, 0x39, 0x37, 0x41, // ....897A - 0x59, 0x30, 0x30, 0x32, 0x30, 0x34, 0x19, 0x03, // Y00204.. - 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, 0x0e, 0x11, // ........ - 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, 0x1f, 0x11, // ........ - 0x2d, 0x11, 0x2f, 0x11, 0x00, 0x12, 0x32, 0x11, // -./...2. - 0x01, 0x05, 0x81, 0x07, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xbc, 0x67, 0xdd, 0x20, // ./...g. + 0x8d, 0x3c, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x0e, // .<....Z. + 0x06, 0xc8, 0x0b, 0x09, 0x38, 0x39, 0x37, 0x41, // ....897A + 0x59, 0x30, 0x30, 0x32, 0x30, 0x34, 0x19, 0x03, // Y00204.. + 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, 0x0e, 0x11, // ........ + 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, 0x1f, 0x11, // ........ + 0x2d, 0x11, 0x2f, 0x11, 0x00, 0x12, 0x32, 0x11, // -./...2. + 0x01, 0x05, 0x81, 0x07, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt11021[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x88, 0x8f, 0x1d, 0x52, // ./.....R - 0xcb, 0x58, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x2a, // .X....Z* - 0x75, 0xb9, 0x0b, 0x09, 0x39, 0x33, 0x36, 0x41, // u...936A - 0x58, 0x30, 0x34, 0x55, 0x4b, 0x33, 0x19, 0x03, // X04UK3.. - 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, 0x0e, 0x11, // ........ - 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, 0x1f, 0x11, // ........ - 0x2d, 0x11, 0x2f, 0x11, 0x00, 0x12, 0x32, 0x11, // -./...2. - 0x01, 0x05, 0x81, 0x07, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x88, 0x8f, 0x1d, 0x52, // ./.....R + 0xcb, 0x58, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x2a, // .X....Z* + 0x75, 0xb9, 0x0b, 0x09, 0x39, 0x33, 0x36, 0x41, // u...936A + 0x58, 0x30, 0x34, 0x55, 0x4b, 0x33, 0x19, 0x03, // X04UK3.. + 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, 0x0e, 0x11, // ........ + 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, 0x1f, 0x11, // ........ + 0x2d, 0x11, 0x2f, 0x11, 0x00, 0x12, 0x32, 0x11, // -./...2. + 0x01, 0x05, 0x81, 0x07, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt11023[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xe3, 0xd5, 0x3d, 0x1f, // ./....=. - 0x54, 0x88, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x8b, // T.....Z. - 0x5f, 0xd3, 0x0f, 0x09, 0x30, 0x34, 0x33, 0x30, // _...0430 - 0x31, 0x46, 0x51, 0x43, 0x42, 0x30, 0x30, 0x31, // 1FQCB001 - 0x33, 0x39, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 39...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xe3, 0xd5, 0x3d, 0x1f, // ./....=. + 0x54, 0x88, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x8b, // T.....Z. + 0x5f, 0xd3, 0x0f, 0x09, 0x30, 0x34, 0x33, 0x30, // _...0430 + 0x31, 0x46, 0x51, 0x43, 0x42, 0x30, 0x30, 0x31, // 1FQCB001 + 0x33, 0x39, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 39...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt11025[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xf5, 0xdf, 0x3e, 0x13, // ./....>. - 0xc4, 0x0c, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0xee, // .....BZ. - 0x37, 0xc8, 0x0f, 0x09, 0x32, 0x36, 0x31, 0x31, // 7...2611 - 0x31, 0x46, 0x44, 0x48, 0x33, 0x30, 0x30, 0x30, // 1FDH3000 - 0x33, 0x46, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 3F...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xf5, 0xdf, 0x3e, 0x13, // ./....>. + 0xc4, 0x0c, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0xee, // .....BZ. + 0x37, 0xc8, 0x0f, 0x09, 0x32, 0x36, 0x31, 0x31, // 7...2611 + 0x31, 0x46, 0x44, 0x48, 0x33, 0x30, 0x30, 0x30, // 1FDH3000 + 0x33, 0x46, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 3F...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt11039[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xeb, 0xd2, 0xa4, 0x46, // ./.....F - 0x74, 0x74, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0x5b, // tt...BZ[ - 0x6f, 0xcc, 0x0f, 0x09, 0x32, 0x39, 0x30, 0x38, // o...2908 - 0x31, 0x46, 0x51, 0x48, 0x4e, 0x30, 0x30, 0x31, // 1FQHN001 - 0x32, 0x34, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 24...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xeb, 0xd2, 0xa4, 0x46, // ./.....F + 0x74, 0x74, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0x5b, // tt...BZ[ + 0x6f, 0xcc, 0x0f, 0x09, 0x32, 0x39, 0x30, 0x38, // o...2908 + 0x31, 0x46, 0x51, 0x48, 0x4e, 0x30, 0x30, 0x31, // 1FQHN001 + 0x32, 0x34, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 24...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt11047[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x85, 0xb3, 0x7e, 0x2f, // ./....~/ - 0x95, 0x24, 0x01, 0x00, 0x10, 0x41, 0x5a, 0x3e, // .$...AZ> - 0x38, 0xce, 0x0f, 0x09, 0x33, 0x32, 0x30, 0x32, // 8...3202 - 0x31, 0x30, 0x35, 0x48, 0x38, 0x30, 0x31, 0x4c, // 105H801L - 0x47, 0x4d, 0x13, 0x03, 0x05, 0x11, 0x0a, 0x11, // GM...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x00, 0x12, 0x01, 0x05, // ........ - 0x81, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x85, 0xb3, 0x7e, 0x2f, // ./....~/ + 0x95, 0x24, 0x01, 0x00, 0x10, 0x41, 0x5a, 0x3e, // .$...AZ> + 0x38, 0xce, 0x0f, 0x09, 0x33, 0x32, 0x30, 0x32, // 8...3202 + 0x31, 0x30, 0x35, 0x48, 0x38, 0x30, 0x31, 0x4c, // 105H801L + 0x47, 0x4d, 0x13, 0x03, 0x05, 0x11, 0x0a, 0x11, // GM...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x00, 0x12, 0x01, 0x05, // ........ + 0x81, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt11048[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x03, 0xf1, 0xdc, 0x20, // ./..... - 0x8d, 0x3c, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x53, // .<....ZS - 0x16, 0xb2, 0x0b, 0x09, 0x38, 0x39, 0x4d, 0x41, // ....89MA - 0x58, 0x30, 0x30, 0x35, 0x5a, 0x42, 0x19, 0x03, // X005ZB.. - 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, 0x0e, 0x11, // ........ - 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, 0x1f, 0x11, // ........ - 0x2d, 0x11, 0x2f, 0x11, 0x00, 0x12, 0x32, 0x11, // -./...2. - 0x01, 0x05, 0x81, 0x07, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x03, 0xf1, 0xdc, 0x20, // ./..... + 0x8d, 0x3c, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x53, // .<....ZS + 0x16, 0xb2, 0x0b, 0x09, 0x38, 0x39, 0x4d, 0x41, // ....89MA + 0x58, 0x30, 0x30, 0x35, 0x5a, 0x42, 0x19, 0x03, // X005ZB.. + 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, 0x0e, 0x11, // ........ + 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, 0x1f, 0x11, // ........ + 0x2d, 0x11, 0x2f, 0x11, 0x00, 0x12, 0x32, 0x11, // -./...2. + 0x01, 0x05, 0x81, 0x07, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt11049[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xdb, 0x04, 0x7b, 0x43, // ./....{C - 0x37, 0xac, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0xff, // 7.....Z. - 0x56, 0xce, 0x0d, 0x09, 0x48, 0x54, 0x36, 0x41, // V...HT6A - 0x36, 0x30, 0x32, 0x30, 0x33, 0x30, 0x39, 0x34, // 60203094 - 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, // ........ - 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, // ........ - 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, 0x00, 0x12, // ..-./... - 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, 0x00, 0x00, // 2....... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xdb, 0x04, 0x7b, 0x43, // ./....{C + 0x37, 0xac, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0xff, // 7.....Z. + 0x56, 0xce, 0x0d, 0x09, 0x48, 0x54, 0x36, 0x41, // V...HT6A + 0x36, 0x30, 0x32, 0x30, 0x33, 0x30, 0x39, 0x34, // 60203094 + 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, // ........ + 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, // ........ + 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, 0x00, 0x12, // ..-./... + 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, 0x00, 0x00, // 2....... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt11067[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x90, 0x60, 0xdd, 0x20, // ./...`. - 0x8d, 0x3c, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x94, // .<....Z. - 0x2f, 0xbb, 0x0b, 0x09, 0x38, 0x39, 0x4c, 0x41, // /...89LA - 0x59, 0x30, 0x30, 0x37, 0x35, 0x33, 0x19, 0x03, // Y00753.. - 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, 0x0e, 0x11, // ........ - 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, 0x1f, 0x11, // ........ - 0x2d, 0x11, 0x2f, 0x11, 0x00, 0x12, 0x32, 0x11, // -./...2. - 0x01, 0x05, 0x81, 0x07, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x90, 0x60, 0xdd, 0x20, // ./...`. + 0x8d, 0x3c, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x94, // .<....Z. + 0x2f, 0xbb, 0x0b, 0x09, 0x38, 0x39, 0x4c, 0x41, // /...89LA + 0x59, 0x30, 0x30, 0x37, 0x35, 0x33, 0x19, 0x03, // Y00753.. + 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, 0x0e, 0x11, // ........ + 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, 0x1f, 0x11, // ........ + 0x2d, 0x11, 0x2f, 0x11, 0x00, 0x12, 0x32, 0x11, // -./...2. + 0x01, 0x05, 0x81, 0x07, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt11080[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xdf, 0x8c, 0x1d, 0x52, // ./.....R - 0xcb, 0x58, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0xcd, // .X....Z. - 0x39, 0xbb, 0x0b, 0x09, 0x39, 0x33, 0x36, 0x41, // 9...936A - 0x58, 0x30, 0x34, 0x56, 0x31, 0x4e, 0x19, 0x03, // X04V1N.. - 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, 0x0e, 0x11, // ........ - 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, 0x1f, 0x11, // ........ - 0x2d, 0x11, 0x2f, 0x11, 0x00, 0x12, 0x32, 0x11, // -./...2. - 0x01, 0x05, 0x81, 0x07, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xdf, 0x8c, 0x1d, 0x52, // ./.....R + 0xcb, 0x58, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0xcd, // .X....Z. + 0x39, 0xbb, 0x0b, 0x09, 0x39, 0x33, 0x36, 0x41, // 9...936A + 0x58, 0x30, 0x34, 0x56, 0x31, 0x4e, 0x19, 0x03, // X04V1N.. + 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, 0x0e, 0x11, // ........ + 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, 0x1f, 0x11, // ........ + 0x2d, 0x11, 0x2f, 0x11, 0x00, 0x12, 0x32, 0x11, // -./...2. + 0x01, 0x05, 0x81, 0x07, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt11081[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x8a, 0xcf, 0x2e, 0x13, // ./...... - 0xc4, 0x0c, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0xd6, // .....BZ. - 0x1b, 0xbe, 0x0f, 0x09, 0x32, 0x34, 0x32, 0x35, // ....2425 - 0x31, 0x46, 0x44, 0x48, 0x32, 0x30, 0x30, 0x31, // 1FDH2001 - 0x32, 0x58, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 2X...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x8a, 0xcf, 0x2e, 0x13, // ./...... + 0xc4, 0x0c, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0xd6, // .....BZ. + 0x1b, 0xbe, 0x0f, 0x09, 0x32, 0x34, 0x32, 0x35, // ....2425 + 0x31, 0x46, 0x44, 0x48, 0x32, 0x30, 0x30, 0x31, // 1FDH2001 + 0x32, 0x58, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 2X...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt11083[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x74, 0x4b, 0x7f, 0x2f, // ./..tK./ - 0x95, 0x24, 0x01, 0x00, 0x10, 0x41, 0x5a, 0xb0, // .$...AZ. - 0x0b, 0xc4, 0x0f, 0x09, 0x33, 0x32, 0x30, 0x32, // ....3202 - 0x31, 0x30, 0x35, 0x48, 0x38, 0x30, 0x32, 0x30, // 105H8020 - 0x51, 0x4c, 0x13, 0x03, 0x05, 0x11, 0x0a, 0x11, // QL...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x00, 0x12, 0x01, 0x05, // ........ - 0x81, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x74, 0x4b, 0x7f, 0x2f, // ./..tK./ + 0x95, 0x24, 0x01, 0x00, 0x10, 0x41, 0x5a, 0xb0, // .$...AZ. + 0x0b, 0xc4, 0x0f, 0x09, 0x33, 0x32, 0x30, 0x32, // ....3202 + 0x31, 0x30, 0x35, 0x48, 0x38, 0x30, 0x32, 0x30, // 105H8020 + 0x51, 0x4c, 0x13, 0x03, 0x05, 0x11, 0x0a, 0x11, // QL...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x00, 0x12, 0x01, 0x05, // ........ + 0x81, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt11092[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x18, 0x6d, 0x36, 0x08, // ./...m6. - 0x9e, 0x08, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x57, // ......ZW - 0x28, 0xc9, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // (....... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x18, 0x6d, 0x36, 0x08, // ./...m6. + 0x9e, 0x08, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x57, // ......ZW + 0x28, 0xc9, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // (....... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt11093[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x5a, 0x7c, 0x36, 0x08, // ./..Z|6. - 0x9e, 0x08, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0xaa, // ......Z. - 0x4c, 0xc1, 0x0f, 0x09, 0x39, 0x43, 0x31, 0x37, // L...9C17 - 0x31, 0x46, 0x51, 0x43, 0x32, 0x30, 0x30, 0x34, // 1FQC2004 - 0x33, 0x34, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 34...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x5a, 0x7c, 0x36, 0x08, // ./..Z|6. + 0x9e, 0x08, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0xaa, // ......Z. + 0x4c, 0xc1, 0x0f, 0x09, 0x39, 0x43, 0x31, 0x37, // L...9C17 + 0x31, 0x46, 0x51, 0x43, 0x32, 0x30, 0x30, 0x34, // 1FQC2004 + 0x33, 0x34, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 34...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt11108[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x9c, 0x98, 0x38, 0x6e, // ./....8n - 0xb7, 0x60, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0xf3, // .`....Z. - 0x26, 0xc8, 0x0f, 0x09, 0x30, 0x42, 0x31, 0x31, // &...0B11 - 0x31, 0x46, 0x51, 0x43, 0x42, 0x30, 0x30, 0x31, // 1FQCB001 - 0x30, 0x36, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 06...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x9c, 0x98, 0x38, 0x6e, // ./....8n + 0xb7, 0x60, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0xf3, // .`....Z. + 0x26, 0xc8, 0x0f, 0x09, 0x30, 0x42, 0x31, 0x31, // &...0B11 + 0x31, 0x46, 0x51, 0x43, 0x42, 0x30, 0x30, 0x31, // 1FQCB001 + 0x30, 0x36, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 06...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt11141[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x55, 0x11, 0x3e, 0x13, // ./..U.>. - 0xc4, 0x0c, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0xfc, // .....BZ. - 0x0b, 0xc6, 0x0f, 0x09, 0x32, 0x32, 0x32, 0x34, // ....2224 - 0x31, 0x46, 0x44, 0x48, 0x33, 0x30, 0x30, 0x30, // 1FDH3000 - 0x30, 0x4b, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 0K...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x5a, 0x6c, 0xb1, 0xa7, 0x6d, 0xf1, 0xbc, 0x9b, // Zl..m... - 0xde, 0x3d, 0x5c, 0xae, 0x21, 0xfa, 0x2e, 0xa8, // .=\.!... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x55, 0x11, 0x3e, 0x13, // ./..U.>. + 0xc4, 0x0c, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0xfc, // .....BZ. + 0x0b, 0xc6, 0x0f, 0x09, 0x32, 0x32, 0x32, 0x34, // ....2224 + 0x31, 0x46, 0x44, 0x48, 0x33, 0x30, 0x30, 0x30, // 1FDH3000 + 0x30, 0x4b, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 0K...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x5a, 0x6c, 0xb1, 0xa7, 0x6d, 0xf1, 0xbc, 0x9b, // Zl..m... + 0xde, 0x3d, 0x5c, 0xae, 0x21, 0xfa, 0x2e, 0xa8, // .=\.!... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt11152[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x30, 0xdc, 0xa4, 0x46, // ./..0..F - 0x74, 0x74, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0xbd, // tt...BZ. - 0x79, 0xcb, 0x05, 0x09, 0x4a, 0x5a, 0x6f, 0x46, // y...JZoF - 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, // ........ - 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, // ........ - 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, 0x00, 0x12, // ..-./... - 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, 0x00, 0x00, // 2....... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x30, 0xdc, 0xa4, 0x46, // ./..0..F + 0x74, 0x74, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0xbd, // tt...BZ. + 0x79, 0xcb, 0x05, 0x09, 0x4a, 0x5a, 0x6f, 0x46, // y...JZoF + 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, // ........ + 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, // ........ + 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, 0x00, 0x12, // ..-./... + 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, 0x00, 0x00, // 2....... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt11154[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x14, 0x90, 0x2a, 0x52, // ./....*R - 0xcb, 0x58, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0xdd, // .X....Z. - 0x66, 0xc9, 0x0b, 0x09, 0x39, 0x33, 0x58, 0x41, // f...93XA - 0x58, 0x30, 0x42, 0x52, 0x57, 0x4c, 0x19, 0x03, // X0BRWL.. - 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, 0x0e, 0x11, // ........ - 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, 0x1f, 0x11, // ........ - 0x2d, 0x11, 0x2f, 0x11, 0x00, 0x12, 0x32, 0x11, // -./...2. - 0x01, 0x05, 0x81, 0x07, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x14, 0x90, 0x2a, 0x52, // ./....*R + 0xcb, 0x58, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0xdd, // .X....Z. + 0x66, 0xc9, 0x0b, 0x09, 0x39, 0x33, 0x58, 0x41, // f...93XA + 0x58, 0x30, 0x42, 0x52, 0x57, 0x4c, 0x19, 0x03, // X0BRWL.. + 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, 0x0e, 0x11, // ........ + 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, 0x1f, 0x11, // ........ + 0x2d, 0x11, 0x2f, 0x11, 0x00, 0x12, 0x32, 0x11, // -./...2. + 0x01, 0x05, 0x81, 0x07, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt11155[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x80, 0x6b, 0x36, 0x08, // ./...... - 0x9e, 0x08, 0x01, 0x00, 0x18, 0x04, 0x34, 0xa0, // ......4. - 0x13, 0xbf, 0x05, 0x09, 0x4c, 0x34, 0x50, 0x6d, // ....L4Pm - 0x11, 0x03, 0x05, 0x11, 0x0b, 0x11, 0x0c, 0x11, // ........ - 0x0e, 0x11, 0x1e, 0x11, 0x2e, 0x11, 0x00, 0x12, // ........ - 0x33, 0x11, 0x01, 0x05, 0x81, 0x07, 0x00, 0x00, // 3....... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x80, 0x6b, 0x36, 0x08, // ./...... + 0x9e, 0x08, 0x01, 0x00, 0x18, 0x04, 0x34, 0xa0, // ......4. + 0x13, 0xbf, 0x05, 0x09, 0x4c, 0x34, 0x50, 0x6d, // ....L4Pm + 0x11, 0x03, 0x05, 0x11, 0x0b, 0x11, 0x0c, 0x11, // ........ + 0x0e, 0x11, 0x1e, 0x11, 0x2e, 0x11, 0x00, 0x12, // ........ + 0x33, 0x11, 0x01, 0x05, 0x81, 0x07, 0x00, 0x00, // 3....... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt11156[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xb5, 0x4b, 0x99, 0x3b, // ./...K.; - 0x22, 0x14, 0x01, 0x00, 0x04, 0x07, 0x2a, 0x10, // ".....*. - 0x77, 0xc2, 0x13, 0x09, 0x47, 0x6f, 0x6f, 0x67, // w...Goog - 0x6c, 0x65, 0x20, 0x50, 0x69, 0x78, 0x65, 0x6c, // le Pixel - 0x20, 0x57, 0x61, 0x74, 0x63, 0x68, 0x0d, 0x03, // Watch.. - 0x0a, 0x11, 0x0c, 0x11, 0x0e, 0x11, 0x1e, 0x11, // ........ - 0x1f, 0x11, 0x00, 0x12, 0x01, 0x05, 0x81, 0x07, // ........ - 0x66, 0x9a, 0x0c, 0x20, 0x00, 0x08, 0xe2, 0xa5, // f.. .... - 0xe3, 0x11, 0x25, 0x95, 0xb0, 0x45, 0x89, 0x5e, // ..%..E.^ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xb5, 0x4b, 0x99, 0x3b, // ./...K.; + 0x22, 0x14, 0x01, 0x00, 0x04, 0x07, 0x2a, 0x10, // ".....*. + 0x77, 0xc2, 0x13, 0x09, 0x47, 0x6f, 0x6f, 0x67, // w...Goog + 0x6c, 0x65, 0x20, 0x50, 0x69, 0x78, 0x65, 0x6c, // le Pixel + 0x20, 0x57, 0x61, 0x74, 0x63, 0x68, 0x0d, 0x03, // Watch.. + 0x0a, 0x11, 0x0c, 0x11, 0x0e, 0x11, 0x1e, 0x11, // ........ + 0x1f, 0x11, 0x00, 0x12, 0x01, 0x05, 0x81, 0x07, // ........ + 0x66, 0x9a, 0x0c, 0x20, 0x00, 0x08, 0xe2, 0xa5, // f.. .... + 0xe3, 0x11, 0x25, 0x95, 0xb0, 0x45, 0x89, 0x5e, // ..%..E.^ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt11158[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x89, 0x0c, 0xa6, 0x46, // ./.....F - 0x74, 0x74, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0x0d, // tt...BZ. - 0x4c, 0xd1, 0x0f, 0x09, 0x32, 0x42, 0x32, 0x31, // L...2B21 - 0x31, 0x4a, 0x45, 0x48, 0x4e, 0x30, 0x38, 0x35, // 1JEHN085 - 0x38, 0x39, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 89...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x5a, 0x6c, 0xb1, 0xa7, 0x6d, 0xf1, 0xbc, 0x9b, // Zl..m... - 0xde, 0x3d, 0x5c, 0xae, 0x21, 0xfa, 0x2e, 0xa8, // .=\.!... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x89, 0x0c, 0xa6, 0x46, // ./.....F + 0x74, 0x74, 0x01, 0x00, 0x0c, 0x42, 0x5a, 0x0d, // tt...BZ. + 0x4c, 0xd1, 0x0f, 0x09, 0x32, 0x42, 0x32, 0x31, // L...2B21 + 0x31, 0x4a, 0x45, 0x48, 0x4e, 0x30, 0x38, 0x35, // 1JEHN085 + 0x38, 0x39, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 89...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x5a, 0x6c, 0xb1, 0xa7, 0x6d, 0xf1, 0xbc, 0x9b, // Zl..m... + 0xde, 0x3d, 0x5c, 0xae, 0x21, 0xfa, 0x2e, 0xa8, // .=\.!... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt11159[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xc2, 0x09, 0x87, 0x2c, // ./....., - 0x3a, 0xd4, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0xba, // :.....Z. - 0x28, 0xc4, 0x0f, 0x09, 0x32, 0x39, 0x31, 0x39, // (...2919 - 0x31, 0x4a, 0x45, 0x47, 0x52, 0x31, 0x30, 0x34, // 1JEGR104 - 0x31, 0x34, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 14...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x5a, 0x6c, 0xb1, 0xa7, 0x6d, 0xf1, 0xbc, 0x9b, // Zl..m... - 0xde, 0x3d, 0x5c, 0xae, 0x21, 0xfa, 0x2e, 0xa8, // .=\.!... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xc2, 0x09, 0x87, 0x2c, // ./....., + 0x3a, 0xd4, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0xba, // :.....Z. + 0x28, 0xc4, 0x0f, 0x09, 0x32, 0x39, 0x31, 0x39, // (...2919 + 0x31, 0x4a, 0x45, 0x47, 0x52, 0x31, 0x30, 0x34, // 1JEGR104 + 0x31, 0x34, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 14...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x5a, 0x6c, 0xb1, 0xa7, 0x6d, 0xf1, 0xbc, 0x9b, // Zl..m... + 0xde, 0x3d, 0x5c, 0xae, 0x21, 0xfa, 0x2e, 0xa8, // .=\.!... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt473[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xf8, 0xdf, 0x28, 0xf4, // ./....(. - 0x81, 0x34, 0x01, 0x00, 0x00, 0x1f, 0x00, 0x59, // .4.....Y - 0x20, 0xb8, 0x10, 0x09, 0x45, 0x54, 0x2d, 0x42, // ...ET-B - 0x54, 0x47, 0x50, 0x53, 0x2d, 0x37, 0x30, 0x39, // TGPS-709 - 0x31, 0x33, 0x38, 0x05, 0xff, 0x42, 0x4d, 0x37, // 138..BM7 - 0x38, 0x02, 0x0a, 0x02, 0x03, 0x02, 0x01, 0x11, // 8....... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xf8, 0xdf, 0x28, 0xf4, // ./....(. + 0x81, 0x34, 0x01, 0x00, 0x00, 0x1f, 0x00, 0x59, // .4.....Y + 0x20, 0xb8, 0x10, 0x09, 0x45, 0x54, 0x2d, 0x42, // ...ET-B + 0x54, 0x47, 0x50, 0x53, 0x2d, 0x37, 0x30, 0x39, // TGPS-709 + 0x31, 0x33, 0x38, 0x05, 0xff, 0x42, 0x4d, 0x37, // 138..BM7 + 0x38, 0x02, 0x0a, 0x02, 0x03, 0x02, 0x01, 0x11, // 8....... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt474[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xf1, 0xd6, 0x28, 0xf4, // ./....(. - 0x81, 0x34, 0x01, 0x00, 0x00, 0x1f, 0x00, 0xa6, // .4...... - 0x7b, 0xb1, 0x10, 0x09, 0x45, 0x54, 0x2d, 0x42, // {...ET-B - 0x54, 0x47, 0x50, 0x53, 0x2d, 0x37, 0x30, 0x39, // TGPS-709 - 0x31, 0x33, 0x34, 0x05, 0xff, 0x42, 0x4d, 0x37, // 134..BM7 - 0x38, 0x02, 0x0a, 0x02, 0x03, 0x02, 0x01, 0x11, // 8....... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xf1, 0xd6, 0x28, 0xf4, // ./....(. + 0x81, 0x34, 0x01, 0x00, 0x00, 0x1f, 0x00, 0xa6, // .4...... + 0x7b, 0xb1, 0x10, 0x09, 0x45, 0x54, 0x2d, 0x42, // {...ET-B + 0x54, 0x47, 0x50, 0x53, 0x2d, 0x37, 0x30, 0x39, // TGPS-709 + 0x31, 0x33, 0x34, 0x05, 0xff, 0x42, 0x4d, 0x37, // 134..BM7 + 0x38, 0x02, 0x0a, 0x02, 0x03, 0x02, 0x01, 0x11, // 8....... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt488[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x0e, 0x8b, 0x20, 0xa5, // ./.... . - 0x92, 0x00, 0x01, 0x00, 0x20, 0x04, 0x36, 0x9a, // .... .6. - 0x09, 0xc0, 0x0a, 0x09, 0x4d, 0x6f, 0x74, 0x72, // ....Motr - 0x65, 0x78, 0x20, 0x48, 0x55, 0x0b, 0x03, 0x0b, // ex HU... - 0x11, 0x1e, 0x11, 0x2e, 0x11, 0x00, 0x12, 0x33, // .......3 - 0x11, 0x41, 0x07, 0xd3, 0x1f, 0xbf, 0x50, 0x5d, // .A....P] - 0x57, 0x27, 0x97, 0xa2, 0x40, 0x41, 0xcd, 0x48, // W'..@A.H - 0x43, 0x88, 0xec, 0xff, 0xca, 0xca, 0xde, 0xaf, // C....... - 0xde, 0xca, 0xde, 0xde, 0xfa, 0xca, 0xde, 0x00, // ........ - 0x00, 0x00, 0x00, 0x66, 0x9a, 0x0c, 0x20, 0x00, // ...f.. . - 0x08, 0xf4, 0xbd, 0xe6, 0x11, 0xcb, 0x52, 0x00, // ......R. - 0x7a, 0xe1, 0x4d, 0x7c, 0x92, 0x67, 0x4d, 0x2c, // z.M|.gM, - 0xf1, 0x86, 0x88, 0xdb, 0x4f, 0x15, 0x25, 0x2c, // ....O.%, - 0xfe, 0x21, 0xdf, 0x02, 0x0a, 0x04, 0x00, 0x00, // .!...... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x0e, 0x8b, 0x20, 0xa5, // ./.... . + 0x92, 0x00, 0x01, 0x00, 0x20, 0x04, 0x36, 0x9a, // .... .6. + 0x09, 0xc0, 0x0a, 0x09, 0x4d, 0x6f, 0x74, 0x72, // ....Motr + 0x65, 0x78, 0x20, 0x48, 0x55, 0x0b, 0x03, 0x0b, // ex HU... + 0x11, 0x1e, 0x11, 0x2e, 0x11, 0x00, 0x12, 0x33, // .......3 + 0x11, 0x41, 0x07, 0xd3, 0x1f, 0xbf, 0x50, 0x5d, // .A....P] + 0x57, 0x27, 0x97, 0xa2, 0x40, 0x41, 0xcd, 0x48, // W'..@A.H + 0x43, 0x88, 0xec, 0xff, 0xca, 0xca, 0xde, 0xaf, // C....... + 0xde, 0xca, 0xde, 0xde, 0xfa, 0xca, 0xde, 0x00, // ........ + 0x00, 0x00, 0x00, 0x66, 0x9a, 0x0c, 0x20, 0x00, // ...f.. . + 0x08, 0xf4, 0xbd, 0xe6, 0x11, 0xcb, 0x52, 0x00, // ......R. + 0x7a, 0xe1, 0x4d, 0x7c, 0x92, 0x67, 0x4d, 0x2c, // z.M|.gM, + 0xf1, 0x86, 0x88, 0xdb, 0x4f, 0x15, 0x25, 0x2c, // ....O.%, + 0xfe, 0x21, 0xdf, 0x02, 0x0a, 0x04, 0x00, 0x00, // .!...... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt489[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x6c, 0x53, 0xdf, 0x05, // ./..lS.. - 0x05, 0x30, 0x01, 0x00, 0x0c, 0x01, 0x08, 0x44, // .0.....D - 0x4d, 0xd5, 0x10, 0x09, 0x4d, 0x47, 0x4b, 0x52, // M...MGKR - 0x44, 0x31, 0x30, 0x2d, 0x4e, 0x41, 0x31, 0x30, // D10-NA10 - 0x4d, 0x49, 0x50, 0x02, 0x0a, 0x0b, 0x09, 0x03, // MIP..... - 0x0c, 0x11, 0x0a, 0x11, 0x0e, 0x11, 0x0b, 0x11, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x6c, 0x53, 0xdf, 0x05, // ./..lS.. + 0x05, 0x30, 0x01, 0x00, 0x0c, 0x01, 0x08, 0x44, // .0.....D + 0x4d, 0xd5, 0x10, 0x09, 0x4d, 0x47, 0x4b, 0x52, // M...MGKR + 0x44, 0x31, 0x30, 0x2d, 0x4e, 0x41, 0x31, 0x30, // D10-NA10 + 0x4d, 0x49, 0x50, 0x02, 0x0a, 0x0b, 0x09, 0x03, // MIP..... + 0x0c, 0x11, 0x0a, 0x11, 0x0e, 0x11, 0x0b, 0x11, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt512[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x74, 0x15, 0x29, 0xf4, // ./..t.). - 0x81, 0x34, 0x01, 0x00, 0x00, 0x1f, 0x00, 0x84, // .4...... - 0x5f, 0xbf, 0x10, 0x09, 0x45, 0x54, 0x2d, 0x42, // _...ET-B - 0x54, 0x41, 0x46, 0x44, 0x2d, 0x37, 0x30, 0x39, // TAFD-709 - 0x30, 0x36, 0x33, 0x05, 0xff, 0x42, 0x4d, 0x37, // 063..BM7 - 0x38, 0x02, 0x0a, 0x02, 0x03, 0x02, 0x01, 0x11, // 8....... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x74, 0x15, 0x29, 0xf4, // ./..t.). + 0x81, 0x34, 0x01, 0x00, 0x00, 0x1f, 0x00, 0x84, // .4...... + 0x5f, 0xbf, 0x10, 0x09, 0x45, 0x54, 0x2d, 0x42, // _...ET-B + 0x54, 0x41, 0x46, 0x44, 0x2d, 0x37, 0x30, 0x39, // TAFD-709 + 0x30, 0x36, 0x33, 0x05, 0xff, 0x42, 0x4d, 0x37, // 063..BM7 + 0x38, 0x02, 0x0a, 0x02, 0x03, 0x02, 0x01, 0x11, // 8....... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt513[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x02, 0xd8, 0x28, 0xf4, // ./....(. - 0x81, 0x34, 0x01, 0x00, 0x00, 0x1f, 0x00, 0x85, // .4...... - 0x5a, 0xbf, 0x10, 0x09, 0x45, 0x54, 0x2d, 0x42, // Z...ET-B - 0x54, 0x47, 0x50, 0x53, 0x2d, 0x37, 0x30, 0x39, // TGPS-709 - 0x31, 0x34, 0x30, 0x05, 0xff, 0x42, 0x4d, 0x37, // 140..BM7 - 0x38, 0x02, 0x0a, 0x02, 0x03, 0x02, 0x01, 0x11, // 8....... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x02, 0xd8, 0x28, 0xf4, // ./....(. + 0x81, 0x34, 0x01, 0x00, 0x00, 0x1f, 0x00, 0x85, // .4...... + 0x5a, 0xbf, 0x10, 0x09, 0x45, 0x54, 0x2d, 0x42, // Z...ET-B + 0x54, 0x47, 0x50, 0x53, 0x2d, 0x37, 0x30, 0x39, // TGPS-709 + 0x31, 0x34, 0x30, 0x05, 0xff, 0x42, 0x4d, 0x37, // 140..BM7 + 0x38, 0x02, 0x0a, 0x02, 0x03, 0x02, 0x01, 0x11, // 8....... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt530[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x14, 0xdc, 0x28, 0xf4, // ./....(. - 0x81, 0x34, 0x01, 0x00, 0x00, 0x1f, 0x00, 0x74, // .4.....t - 0x01, 0xb6, 0x10, 0x09, 0x45, 0x54, 0x2d, 0x42, // ....ET-B - 0x54, 0x41, 0x46, 0x44, 0x2d, 0x37, 0x30, 0x39, // TAFD-709 - 0x30, 0x38, 0x35, 0x05, 0xff, 0x42, 0x4d, 0x37, // 085..BM7 - 0x38, 0x02, 0x0a, 0x02, 0x03, 0x02, 0x01, 0x11, // 8....... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x14, 0xdc, 0x28, 0xf4, // ./....(. + 0x81, 0x34, 0x01, 0x00, 0x00, 0x1f, 0x00, 0x74, // .4.....t + 0x01, 0xb6, 0x10, 0x09, 0x45, 0x54, 0x2d, 0x42, // ....ET-B + 0x54, 0x41, 0x46, 0x44, 0x2d, 0x37, 0x30, 0x39, // TAFD-709 + 0x30, 0x38, 0x35, 0x05, 0xff, 0x42, 0x4d, 0x37, // 085..BM7 + 0x38, 0x02, 0x0a, 0x02, 0x03, 0x02, 0x01, 0x11, // 8....... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt545[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xcd, 0x7b, 0xc0, 0x68, // ./...{.h - 0x10, 0xd8, 0x01, 0x00, 0x20, 0x04, 0x74, 0xf0, // .... .t. - 0x23, 0xb5, 0x17, 0x03, 0x3b, 0x11, 0x00, 0x12, // #...;... - 0x1e, 0x11, 0x03, 0x12, 0x2e, 0x11, 0x33, 0x11, // ......3. - 0x01, 0x11, 0x0b, 0x11, 0x0e, 0x11, 0x0f, 0x11, // ........ - 0x0c, 0x11, 0x01, 0x05, 0x41, 0x07, 0x1b, 0xc5, // ....A... - 0xd5, 0xa5, 0x02, 0x00, 0xa0, 0x80, 0xe4, 0x11, // ........ - 0x16, 0xe4, 0x40, 0xed, 0x28, 0x37, 0xff, 0xca, // ..@.(7.. - 0xca, 0xde, 0xaf, 0xde, 0xca, 0xde, 0xde, 0xfa, // ........ - 0xca, 0xde, 0x00, 0x00, 0x00, 0x00, 0xec, 0x88, // ........ - 0x43, 0x48, 0xcd, 0x41, 0x40, 0xa2, 0x97, 0x27, // CH.A@..' - 0x57, 0x5d, 0x50, 0xbf, 0x1f, 0xd3, 0x66, 0x9a, // W]P...f. - 0x0c, 0x20, 0x00, 0x08, 0xf4, 0xbd, 0xe6, 0x11, // . ...... - 0xcb, 0x52, 0x00, 0x7a, 0xe1, 0x4d, 0x02, 0x0a, // .R.z.M.. - 0x06, 0x0b, 0x09, 0x4d, 0x79, 0x20, 0x56, 0x57, // ...My VW - 0x20, 0x37, 0x42, 0x43, 0x44, 0x00, 0x00, 0x00, // 7BCD... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xcd, 0x7b, 0xc0, 0x68, // ./...{.h + 0x10, 0xd8, 0x01, 0x00, 0x20, 0x04, 0x74, 0xf0, // .... .t. + 0x23, 0xb5, 0x17, 0x03, 0x3b, 0x11, 0x00, 0x12, // #...;... + 0x1e, 0x11, 0x03, 0x12, 0x2e, 0x11, 0x33, 0x11, // ......3. + 0x01, 0x11, 0x0b, 0x11, 0x0e, 0x11, 0x0f, 0x11, // ........ + 0x0c, 0x11, 0x01, 0x05, 0x41, 0x07, 0x1b, 0xc5, // ....A... + 0xd5, 0xa5, 0x02, 0x00, 0xa0, 0x80, 0xe4, 0x11, // ........ + 0x16, 0xe4, 0x40, 0xed, 0x28, 0x37, 0xff, 0xca, // ..@.(7.. + 0xca, 0xde, 0xaf, 0xde, 0xca, 0xde, 0xde, 0xfa, // ........ + 0xca, 0xde, 0x00, 0x00, 0x00, 0x00, 0xec, 0x88, // ........ + 0x43, 0x48, 0xcd, 0x41, 0x40, 0xa2, 0x97, 0x27, // CH.A@..' + 0x57, 0x5d, 0x50, 0xbf, 0x1f, 0xd3, 0x66, 0x9a, // W]P...f. + 0x0c, 0x20, 0x00, 0x08, 0xf4, 0xbd, 0xe6, 0x11, // . ...... + 0xcb, 0x52, 0x00, 0x7a, 0xe1, 0x4d, 0x02, 0x0a, // .R.z.M.. + 0x06, 0x0b, 0x09, 0x4d, 0x79, 0x20, 0x56, 0x57, // ...My VW + 0x20, 0x37, 0x42, 0x43, 0x44, 0x00, 0x00, 0x00, // 7BCD... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt871[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x6c, 0x53, 0xdf, 0x05, // ./..lS.. - 0x05, 0x30, 0x01, 0x00, 0x0c, 0x01, 0x08, 0x44, // .0.....D - 0x4d, 0xd5, 0x10, 0x09, 0x4d, 0x47, 0x4b, 0x52, // M...MGKR - 0x44, 0x31, 0x30, 0x2d, 0x4e, 0x41, 0x31, 0x30, // D10-NA10 - 0x4d, 0x49, 0x50, 0x02, 0x0a, 0x0b, 0x09, 0x03, // MIP..... - 0x0c, 0x11, 0x0a, 0x11, 0x0e, 0x11, 0x0b, 0x11, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x6c, 0x53, 0xdf, 0x05, // ./..lS.. + 0x05, 0x30, 0x01, 0x00, 0x0c, 0x01, 0x08, 0x44, // .0.....D + 0x4d, 0xd5, 0x10, 0x09, 0x4d, 0x47, 0x4b, 0x52, // M...MGKR + 0x44, 0x31, 0x30, 0x2d, 0x4e, 0x41, 0x31, 0x30, // D10-NA10 + 0x4d, 0x49, 0x50, 0x02, 0x0a, 0x0b, 0x09, 0x03, // MIP..... + 0x0c, 0x11, 0x0a, 0x11, 0x0e, 0x11, 0x0b, 0x11, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt27834[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xb8, 0x20, 0xb8, 0x68, // ./... .h - 0x10, 0xd8, 0x01, 0x00, 0x20, 0x04, 0x74, 0xda, // .... .t. - 0x68, 0xc2, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // h....... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xb8, 0x20, 0xb8, 0x68, // ./... .h + 0x10, 0xd8, 0x01, 0x00, 0x20, 0x04, 0x74, 0xda, // .... .t. + 0x68, 0xc2, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // h....... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt27876[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xb8, 0x20, 0xb8, 0x68, // ./... .h - 0x10, 0xd8, 0x01, 0x00, 0x20, 0x04, 0x74, 0x6a, // .... .tj - 0x6a, 0xc4, 0x19, 0x03, 0x3b, 0x11, 0x00, 0x12, // j...;... - 0x1e, 0x11, 0x03, 0x12, 0x2e, 0x11, 0x33, 0x11, // ......3. - 0x0b, 0x11, 0x0e, 0x11, 0x0f, 0x11, 0xae, 0x7f, // ........ - 0x0c, 0x11, 0xad, 0x7f, 0x01, 0x05, 0x41, 0x07, // ......A. - 0x1b, 0xc5, 0xd5, 0xa5, 0x02, 0x00, 0xa0, 0x80, // ........ - 0xe4, 0x11, 0x16, 0xe4, 0x40, 0xed, 0x28, 0x37, // ....@.(7 - 0xff, 0xca, 0xca, 0xde, 0xaf, 0xde, 0xca, 0xde, // ........ - 0xde, 0xfa, 0xca, 0xde, 0x00, 0x00, 0x00, 0x00, // ........ - 0xec, 0x88, 0x43, 0x48, 0xcd, 0x41, 0x40, 0xa2, // ..CH.A@. - 0x97, 0x27, 0x57, 0x5d, 0x50, 0xbf, 0x1f, 0xd3, // .'W]P... - 0x66, 0x9a, 0x0c, 0x20, 0x00, 0x08, 0xf4, 0xbd, // f.. .... - 0xe6, 0x11, 0xcb, 0x52, 0x00, 0x7a, 0xe1, 0x4d, // ...R.z.M - 0x02, 0x0a, 0x04, 0x0b, 0x09, 0x4d, 0x79, 0x20, // .....My - 0x56, 0x57, 0x20, 0x32, 0x36, 0x36, 0x33, 0x00, // VW 2663. - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xb8, 0x20, 0xb8, 0x68, // ./... .h + 0x10, 0xd8, 0x01, 0x00, 0x20, 0x04, 0x74, 0x6a, // .... .tj + 0x6a, 0xc4, 0x19, 0x03, 0x3b, 0x11, 0x00, 0x12, // j...;... + 0x1e, 0x11, 0x03, 0x12, 0x2e, 0x11, 0x33, 0x11, // ......3. + 0x0b, 0x11, 0x0e, 0x11, 0x0f, 0x11, 0xae, 0x7f, // ........ + 0x0c, 0x11, 0xad, 0x7f, 0x01, 0x05, 0x41, 0x07, // ......A. + 0x1b, 0xc5, 0xd5, 0xa5, 0x02, 0x00, 0xa0, 0x80, // ........ + 0xe4, 0x11, 0x16, 0xe4, 0x40, 0xed, 0x28, 0x37, // ....@.(7 + 0xff, 0xca, 0xca, 0xde, 0xaf, 0xde, 0xca, 0xde, // ........ + 0xde, 0xfa, 0xca, 0xde, 0x00, 0x00, 0x00, 0x00, // ........ + 0xec, 0x88, 0x43, 0x48, 0xcd, 0x41, 0x40, 0xa2, // ..CH.A@. + 0x97, 0x27, 0x57, 0x5d, 0x50, 0xbf, 0x1f, 0xd3, // .'W]P... + 0x66, 0x9a, 0x0c, 0x20, 0x00, 0x08, 0xf4, 0xbd, // f.. .... + 0xe6, 0x11, 0xcb, 0x52, 0x00, 0x7a, 0xe1, 0x4d, // ...R.z.M + 0x02, 0x0a, 0x04, 0x0b, 0x09, 0x4d, 0x79, 0x20, // .....My + 0x56, 0x57, 0x20, 0x32, 0x36, 0x36, 0x33, 0x00, // VW 2663. + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt649[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xf6, 0xc5, 0x54, 0x1a, // ./....T. - 0x94, 0xa0, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0xfe, // ......Z. - 0x0a, 0xc5, 0x1c, 0x09, 0xe3, 0x82, 0x81, 0xe3, // ........ - 0x82, 0x81, 0xe3, 0x81, 0xbf, 0xe3, 0x81, 0xa1, // ........ - 0xe4, 0xb8, 0x96, 0xe7, 0x95, 0x8c, 0xe4, 0xb8, // ........ - 0x80, 0xe6, 0x8e, 0xa8, 0xe3, 0x81, 0x97, 0x17, // ........ - 0x03, 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, 0x0e, // ........ - 0x11, 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, 0x1f, // ........ - 0x11, 0x2f, 0x11, 0x00, 0x12, 0x32, 0x11, 0x01, // ./...2.. - 0x05, 0x81, 0x07, 0x00, 0xdf, 0x0c, 0xa9, 0x80, // ........ - 0xbb, 0x4f, 0x9f, 0x5c, 0x49, 0x06, 0xcb, 0x15, // .O.\I... - 0xaa, 0x9e, 0xa4, 0x00, 0xdf, 0x0c, 0xa9, 0x80, // ........ - 0xbb, 0x4f, 0x9f, 0x5c, 0x49, 0x06, 0xcb, 0x15, // .O.\I... - 0xcc, 0x9e, 0xa4, 0x5a, 0x6c, 0xb1, 0xa7, 0x6d, // ...Zl..m - 0xf1, 0xbc, 0x9b, 0xde, 0x3d, 0x5c, 0xae, 0x21, // ....=\.! - 0xfa, 0x2e, 0xa8, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xf6, 0xc5, 0x54, 0x1a, // ./....T. + 0x94, 0xa0, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0xfe, // ......Z. + 0x0a, 0xc5, 0x1c, 0x09, 0xe3, 0x82, 0x81, 0xe3, // ........ + 0x82, 0x81, 0xe3, 0x81, 0xbf, 0xe3, 0x81, 0xa1, // ........ + 0xe4, 0xb8, 0x96, 0xe7, 0x95, 0x8c, 0xe4, 0xb8, // ........ + 0x80, 0xe6, 0x8e, 0xa8, 0xe3, 0x81, 0x97, 0x17, // ........ + 0x03, 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, 0x0e, // ........ + 0x11, 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, 0x1f, // ........ + 0x11, 0x2f, 0x11, 0x00, 0x12, 0x32, 0x11, 0x01, // ./...2.. + 0x05, 0x81, 0x07, 0x00, 0xdf, 0x0c, 0xa9, 0x80, // ........ + 0xbb, 0x4f, 0x9f, 0x5c, 0x49, 0x06, 0xcb, 0x15, // .O.\I... + 0xaa, 0x9e, 0xa4, 0x00, 0xdf, 0x0c, 0xa9, 0x80, // ........ + 0xbb, 0x4f, 0x9f, 0x5c, 0x49, 0x06, 0xcb, 0x15, // .O.\I... + 0xcc, 0x9e, 0xa4, 0x5a, 0x6c, 0xb1, 0xa7, 0x6d, // ...Zl..m + 0xf1, 0xbc, 0x9b, 0xde, 0x3d, 0x5c, 0xae, 0x21, // ....=\.! + 0xfa, 0x2e, 0xa8, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt677[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xc9, 0xfd, 0x14, 0x45, // ./.....E - 0x0a, 0x00, 0x01, 0x00, 0x04, 0x04, 0x24, 0x66, // ......$f - 0x17, 0xb2, 0x0e, 0x09, 0x41, 0x54, 0x48, 0x2d, // ....ATH- - 0x43, 0x4b, 0x53, 0x33, 0x33, 0x30, 0x58, 0x42, // CKS330XB - 0x54, 0x15, 0x03, 0x31, 0x11, 0x08, 0x11, 0x03, // T..1.... - 0x12, 0x1e, 0x11, 0x0c, 0x11, 0x0f, 0x11, 0x0e, // ........ - 0x11, 0x0b, 0x11, 0x00, 0x12, 0x00, 0x10, 0x01, // ........ - 0x05, 0x01, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xc9, 0xfd, 0x14, 0x45, // ./.....E + 0x0a, 0x00, 0x01, 0x00, 0x04, 0x04, 0x24, 0x66, // ......$f + 0x17, 0xb2, 0x0e, 0x09, 0x41, 0x54, 0x48, 0x2d, // ....ATH- + 0x43, 0x4b, 0x53, 0x33, 0x33, 0x30, 0x58, 0x42, // CKS330XB + 0x54, 0x15, 0x03, 0x31, 0x11, 0x08, 0x11, 0x03, // T..1.... + 0x12, 0x1e, 0x11, 0x0c, 0x11, 0x0f, 0x11, 0x0e, // ........ + 0x11, 0x0b, 0x11, 0x00, 0x12, 0x00, 0x10, 0x01, // ........ + 0x05, 0x01, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt689[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xd3, 0x4d, 0x3b, 0xe9, // ./...M;. - 0xbc, 0x4c, 0x01, 0x00, 0x3c, 0x24, 0x0c, 0xe3, // .L..<$.. - 0x49, 0xae, 0x1a, 0x09, 0x5b, 0x4c, 0x47, 0x5d, // I...[LG] - 0x20, 0x77, 0x65, 0x62, 0x4f, 0x53, 0x20, 0x54, // webOS T - 0x56, 0x20, 0x4f, 0x4c, 0x45, 0x44, 0x35, 0x35, // V OLED55 - 0x43, 0x31, 0x50, 0x53, 0x42, 0x07, 0x03, 0x0b, // C1PSB... - 0x11, 0x0e, 0x11, 0x00, 0x12, 0x01, 0x05, 0x01, // ........ - 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xd3, 0x4d, 0x3b, 0xe9, // ./...M;. + 0xbc, 0x4c, 0x01, 0x00, 0x3c, 0x24, 0x0c, 0xe3, // .L..<$.. + 0x49, 0xae, 0x1a, 0x09, 0x5b, 0x4c, 0x47, 0x5d, // I...[LG] + 0x20, 0x77, 0x65, 0x62, 0x4f, 0x53, 0x20, 0x54, // webOS T + 0x56, 0x20, 0x4f, 0x4c, 0x45, 0x44, 0x35, 0x35, // V OLED55 + 0x43, 0x31, 0x50, 0x53, 0x42, 0x07, 0x03, 0x0b, // C1PSB... + 0x11, 0x0e, 0x11, 0x00, 0x12, 0x01, 0x05, 0x01, // ........ + 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt709[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x6a, 0x78, 0xbf, 0x09, // ./..jx.. - 0x95, 0x3c, 0x01, 0x00, 0x0c, 0x01, 0x2a, 0xdf, // .<....*. - 0x15, 0xa6, 0x10, 0x09, 0x44, 0x45, 0x53, 0x4b, // ....DESK - 0x54, 0x4f, 0x50, 0x2d, 0x39, 0x38, 0x41, 0x31, // TOP-98A1 - 0x41, 0x42, 0x53, 0x02, 0x0a, 0x00, 0x0d, 0x03, // ABS..... - 0x0c, 0x11, 0x0a, 0x11, 0x0e, 0x11, 0x0b, 0x11, // ........ - 0x1f, 0x11, 0x1e, 0x11, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x6a, 0x78, 0xbf, 0x09, // ./..jx.. + 0x95, 0x3c, 0x01, 0x00, 0x0c, 0x01, 0x2a, 0xdf, // .<....*. + 0x15, 0xa6, 0x10, 0x09, 0x44, 0x45, 0x53, 0x4b, // ....DESK + 0x54, 0x4f, 0x50, 0x2d, 0x39, 0x38, 0x41, 0x31, // TOP-98A1 + 0x41, 0x42, 0x53, 0x02, 0x0a, 0x00, 0x0d, 0x03, // ABS..... + 0x0c, 0x11, 0x0a, 0x11, 0x0e, 0x11, 0x0b, 0x11, // ........ + 0x1f, 0x11, 0x1e, 0x11, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt763[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x30, 0x25, 0x92, 0xda, // ./..0%.. - 0xb0, 0xcc, 0x01, 0x00, 0x0c, 0x01, 0x2a, 0x5c, // ......* - 0x04, 0xb2, 0x0b, 0x09, 0x54, 0x32, 0x32, 0x30, // ....T220 - 0x34, 0x30, 0x2d, 0x44, 0x55, 0x54, 0x02, 0x0a, // 40-DUT.. - 0x00, 0x0d, 0x03, 0x0c, 0x11, 0x0a, 0x11, 0x0e, // ........ - 0x11, 0x0b, 0x11, 0x1f, 0x11, 0x1e, 0x11, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x30, 0x25, 0x92, 0xda, // ./..0%.. + 0xb0, 0xcc, 0x01, 0x00, 0x0c, 0x01, 0x2a, 0x5c, // ......* + 0x04, 0xb2, 0x0b, 0x09, 0x54, 0x32, 0x32, 0x30, // ....T220 + 0x34, 0x30, 0x2d, 0x44, 0x55, 0x54, 0x02, 0x0a, // 40-DUT.. + 0x00, 0x0d, 0x03, 0x0c, 0x11, 0x0a, 0x11, 0x0e, // ........ + 0x11, 0x0b, 0x11, 0x1f, 0x11, 0x1e, 0x11, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt771[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x39, 0xf0, 0x33, 0xd3, // ./..9.3. - 0x5f, 0x98, 0x01, 0x00, 0x0c, 0x01, 0x2a, 0xb0, // _.....*. - 0x20, 0xcc, 0x10, 0x09, 0x44, 0x45, 0x53, 0x4b, // ...DESK - 0x54, 0x4f, 0x50, 0x2d, 0x56, 0x38, 0x30, 0x41, // TOP-V80A - 0x51, 0x4a, 0x34, 0x02, 0x0a, 0x04, 0x0d, 0x03, // QJ4..... - 0x0c, 0x11, 0x0a, 0x11, 0x0e, 0x11, 0x0b, 0x11, // ........ - 0x1f, 0x11, 0x1e, 0x11, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x39, 0xf0, 0x33, 0xd3, // ./..9.3. + 0x5f, 0x98, 0x01, 0x00, 0x0c, 0x01, 0x2a, 0xb0, // _.....*. + 0x20, 0xcc, 0x10, 0x09, 0x44, 0x45, 0x53, 0x4b, // ...DESK + 0x54, 0x4f, 0x50, 0x2d, 0x56, 0x38, 0x30, 0x41, // TOP-V80A + 0x51, 0x4a, 0x34, 0x02, 0x0a, 0x04, 0x0d, 0x03, // QJ4..... + 0x0c, 0x11, 0x0a, 0x11, 0x0e, 0x11, 0x0b, 0x11, // ........ + 0x1f, 0x11, 0x1e, 0x11, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt795[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x44, 0xc6, 0xee, 0x6b, // ./..D..k - 0x21, 0x00, 0x01, 0x00, 0x0c, 0x01, 0x2a, 0xe5, // !.....*. - 0x62, 0xa7, 0x0b, 0x09, 0x31, 0x31, 0x30, 0x30, // b...1100 - 0x30, 0x37, 0x2d, 0x44, 0x55, 0x54, 0x02, 0x0a, // 07-DUT.. - 0x0c, 0x0b, 0x03, 0x0a, 0x11, 0x0c, 0x11, 0x0e, // ........ - 0x11, 0x1f, 0x11, 0x1e, 0x11, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x44, 0xc6, 0xee, 0x6b, // ./..D..k + 0x21, 0x00, 0x01, 0x00, 0x0c, 0x01, 0x2a, 0xe5, // !.....*. + 0x62, 0xa7, 0x0b, 0x09, 0x31, 0x31, 0x30, 0x30, // b...1100 + 0x30, 0x37, 0x2d, 0x44, 0x55, 0x54, 0x02, 0x0a, // 07-DUT.. + 0x0c, 0x0b, 0x03, 0x0a, 0x11, 0x0c, 0x11, 0x0e, // ........ + 0x11, 0x1f, 0x11, 0x1e, 0x11, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt951[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xf6, 0xc5, 0x54, 0x1a, // ./....T. - 0x94, 0xa0, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0xff, // ......Z. - 0x0a, 0xc6, 0x1c, 0x09, 0xe3, 0x82, 0x81, 0xe3, // ........ - 0x82, 0x81, 0xe3, 0x81, 0xbf, 0xe3, 0x81, 0xa1, // ........ - 0xe4, 0xb8, 0x96, 0xe7, 0x95, 0x8c, 0xe4, 0xb8, // ........ - 0x80, 0xe6, 0x8e, 0xa8, 0xe3, 0x81, 0x97, 0x17, // ........ - 0x03, 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, 0x0e, // ........ - 0x11, 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, 0x1f, // ........ - 0x11, 0x2f, 0x11, 0x00, 0x12, 0x32, 0x11, 0x01, // ./...2.. - 0x05, 0x81, 0x07, 0x00, 0xdf, 0x0c, 0xa9, 0x80, // ........ - 0xbb, 0x4f, 0x9f, 0x5c, 0x49, 0x06, 0xcb, 0x15, // .O.\I... - 0xaa, 0x9e, 0xa4, 0x00, 0xdf, 0x0c, 0xa9, 0x80, // ........ - 0xbb, 0x4f, 0x9f, 0x5c, 0x49, 0x06, 0xcb, 0x15, // .O.\I... - 0xcc, 0x9e, 0xa4, 0x5a, 0x6c, 0xb1, 0xa7, 0x6d, // ...Zl..m - 0xf1, 0xbc, 0x9b, 0xde, 0x3d, 0x5c, 0xae, 0x21, // ....=\.! - 0xfa, 0x2e, 0xa8, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xf6, 0xc5, 0x54, 0x1a, // ./....T. + 0x94, 0xa0, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0xff, // ......Z. + 0x0a, 0xc6, 0x1c, 0x09, 0xe3, 0x82, 0x81, 0xe3, // ........ + 0x82, 0x81, 0xe3, 0x81, 0xbf, 0xe3, 0x81, 0xa1, // ........ + 0xe4, 0xb8, 0x96, 0xe7, 0x95, 0x8c, 0xe4, 0xb8, // ........ + 0x80, 0xe6, 0x8e, 0xa8, 0xe3, 0x81, 0x97, 0x17, // ........ + 0x03, 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, 0x0e, // ........ + 0x11, 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, 0x1f, // ........ + 0x11, 0x2f, 0x11, 0x00, 0x12, 0x32, 0x11, 0x01, // ./...2.. + 0x05, 0x81, 0x07, 0x00, 0xdf, 0x0c, 0xa9, 0x80, // ........ + 0xbb, 0x4f, 0x9f, 0x5c, 0x49, 0x06, 0xcb, 0x15, // .O.\I... + 0xaa, 0x9e, 0xa4, 0x00, 0xdf, 0x0c, 0xa9, 0x80, // ........ + 0xbb, 0x4f, 0x9f, 0x5c, 0x49, 0x06, 0xcb, 0x15, // .O.\I... + 0xcc, 0x9e, 0xa4, 0x5a, 0x6c, 0xb1, 0xa7, 0x6d, // ...Zl..m + 0xf1, 0xbc, 0x9b, 0xde, 0x3d, 0x5c, 0xae, 0x21, // ....=\.! + 0xfa, 0x2e, 0xa8, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt952[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x39, 0xf0, 0x33, 0xd3, // ./..9.3. - 0x5f, 0x98, 0x01, 0x00, 0x0c, 0x01, 0x2a, 0xb0, // _.....*. - 0x20, 0xd1, 0x10, 0x09, 0x44, 0x45, 0x53, 0x4b, // ...DESK - 0x54, 0x4f, 0x50, 0x2d, 0x56, 0x38, 0x30, 0x41, // TOP-V80A - 0x51, 0x4a, 0x34, 0x02, 0x0a, 0x04, 0x0d, 0x03, // QJ4..... - 0x0c, 0x11, 0x0a, 0x11, 0x0e, 0x11, 0x0b, 0x11, // ........ - 0x1f, 0x11, 0x1e, 0x11, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x39, 0xf0, 0x33, 0xd3, // ./..9.3. + 0x5f, 0x98, 0x01, 0x00, 0x0c, 0x01, 0x2a, 0xb0, // _.....*. + 0x20, 0xd1, 0x10, 0x09, 0x44, 0x45, 0x53, 0x4b, // ...DESK + 0x54, 0x4f, 0x50, 0x2d, 0x56, 0x38, 0x30, 0x41, // TOP-V80A + 0x51, 0x4a, 0x34, 0x02, 0x0a, 0x04, 0x0d, 0x03, // QJ4..... + 0x0c, 0x11, 0x0a, 0x11, 0x0e, 0x11, 0x0b, 0x11, // ........ + 0x1f, 0x11, 0x1e, 0x11, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt953[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xd3, 0x4d, 0x3b, 0xe9, // ./...M;. - 0xbc, 0x4c, 0x01, 0x00, 0x3c, 0x24, 0x0c, 0xe3, // .L..<$.. - 0x49, 0xb2, 0x1a, 0x09, 0x5b, 0x4c, 0x47, 0x5d, // I...[LG] - 0x20, 0x77, 0x65, 0x62, 0x4f, 0x53, 0x20, 0x54, // webOS T - 0x56, 0x20, 0x4f, 0x4c, 0x45, 0x44, 0x35, 0x35, // V OLED55 - 0x43, 0x31, 0x50, 0x53, 0x42, 0x07, 0x03, 0x0b, // C1PSB... - 0x11, 0x0e, 0x11, 0x00, 0x12, 0x01, 0x05, 0x01, // ........ - 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xd3, 0x4d, 0x3b, 0xe9, // ./...M;. + 0xbc, 0x4c, 0x01, 0x00, 0x3c, 0x24, 0x0c, 0xe3, // .L..<$.. + 0x49, 0xb2, 0x1a, 0x09, 0x5b, 0x4c, 0x47, 0x5d, // I...[LG] + 0x20, 0x77, 0x65, 0x62, 0x4f, 0x53, 0x20, 0x54, // webOS T + 0x56, 0x20, 0x4f, 0x4c, 0x45, 0x44, 0x35, 0x35, // V OLED55 + 0x43, 0x31, 0x50, 0x53, 0x42, 0x07, 0x03, 0x0b, // C1PSB... + 0x11, 0x0e, 0x11, 0x00, 0x12, 0x01, 0x05, 0x01, // ........ + 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt954[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x6a, 0x78, 0xbf, 0x09, // ./..jx.. - 0x95, 0x3c, 0x01, 0x00, 0x0c, 0x01, 0x2a, 0xdf, // .<....*. - 0x15, 0xad, 0x10, 0x09, 0x44, 0x45, 0x53, 0x4b, // ....DESK - 0x54, 0x4f, 0x50, 0x2d, 0x39, 0x38, 0x41, 0x31, // TOP-98A1 - 0x41, 0x42, 0x53, 0x02, 0x0a, 0x00, 0x0d, 0x03, // ABS..... - 0x0c, 0x11, 0x0a, 0x11, 0x0e, 0x11, 0x0b, 0x11, // ........ - 0x1f, 0x11, 0x1e, 0x11, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x6a, 0x78, 0xbf, 0x09, // ./..jx.. + 0x95, 0x3c, 0x01, 0x00, 0x0c, 0x01, 0x2a, 0xdf, // .<....*. + 0x15, 0xad, 0x10, 0x09, 0x44, 0x45, 0x53, 0x4b, // ....DESK + 0x54, 0x4f, 0x50, 0x2d, 0x39, 0x38, 0x41, 0x31, // TOP-98A1 + 0x41, 0x42, 0x53, 0x02, 0x0a, 0x00, 0x0d, 0x03, // ABS..... + 0x0c, 0x11, 0x0a, 0x11, 0x0e, 0x11, 0x0b, 0x11, // ........ + 0x1f, 0x11, 0x1e, 0x11, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt451[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xf6, 0xc5, 0x54, 0x1a, // ./....T. - 0x94, 0xa0, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x98, // ......Z. - 0x44, 0xc5, 0x1c, 0x09, 0xe3, 0x82, 0x81, 0xe3, // D....... - 0x82, 0x81, 0xe3, 0x81, 0xbf, 0xe3, 0x81, 0xa1, // ........ - 0xe4, 0xb8, 0x96, 0xe7, 0x95, 0x8c, 0xe4, 0xb8, // ........ - 0x80, 0xe6, 0x8e, 0xa8, 0xe3, 0x81, 0x97, 0x17, // ........ - 0x03, 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, 0x0e, // ........ - 0x11, 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, 0x1f, // ........ - 0x11, 0x2f, 0x11, 0x00, 0x12, 0x32, 0x11, 0x01, // ./...2.. - 0x05, 0x81, 0x07, 0x00, 0xdf, 0x0c, 0xa9, 0x80, // ........ - 0xbb, 0x4f, 0x9f, 0x5c, 0x49, 0x06, 0xcb, 0x15, // .O.\I... - 0xaa, 0x9e, 0xa4, 0x00, 0xdf, 0x0c, 0xa9, 0x80, // ........ - 0xbb, 0x4f, 0x9f, 0x5c, 0x49, 0x06, 0xcb, 0x15, // .O.\I... - 0xcc, 0x9e, 0xa4, 0x5a, 0x6c, 0xb1, 0xa7, 0x6d, // ...Zl..m - 0xf1, 0xbc, 0x9b, 0xde, 0x3d, 0x5c, 0xae, 0x21, // ....=\.! - 0xfa, 0x2e, 0xa8, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xf6, 0xc5, 0x54, 0x1a, // ./....T. + 0x94, 0xa0, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x98, // ......Z. + 0x44, 0xc5, 0x1c, 0x09, 0xe3, 0x82, 0x81, 0xe3, // D....... + 0x82, 0x81, 0xe3, 0x81, 0xbf, 0xe3, 0x81, 0xa1, // ........ + 0xe4, 0xb8, 0x96, 0xe7, 0x95, 0x8c, 0xe4, 0xb8, // ........ + 0x80, 0xe6, 0x8e, 0xa8, 0xe3, 0x81, 0x97, 0x17, // ........ + 0x03, 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, 0x0e, // ........ + 0x11, 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, 0x1f, // ........ + 0x11, 0x2f, 0x11, 0x00, 0x12, 0x32, 0x11, 0x01, // ./...2.. + 0x05, 0x81, 0x07, 0x00, 0xdf, 0x0c, 0xa9, 0x80, // ........ + 0xbb, 0x4f, 0x9f, 0x5c, 0x49, 0x06, 0xcb, 0x15, // .O.\I... + 0xaa, 0x9e, 0xa4, 0x00, 0xdf, 0x0c, 0xa9, 0x80, // ........ + 0xbb, 0x4f, 0x9f, 0x5c, 0x49, 0x06, 0xcb, 0x15, // .O.\I... + 0xcc, 0x9e, 0xa4, 0x5a, 0x6c, 0xb1, 0xa7, 0x6d, // ...Zl..m + 0xf1, 0xbc, 0x9b, 0xde, 0x3d, 0x5c, 0xae, 0x21, // ....=\.! + 0xfa, 0x2e, 0xa8, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt482[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x30, 0x25, 0x92, 0xda, // ./..0%.. - 0xb0, 0xcc, 0x01, 0x00, 0x0c, 0x01, 0x2a, 0xf9, // ......*. - 0x3d, 0xbe, 0x0b, 0x09, 0x54, 0x32, 0x32, 0x30, // =...T220 - 0x34, 0x30, 0x2d, 0x44, 0x55, 0x54, 0x02, 0x0a, // 40-DUT.. - 0x00, 0x0d, 0x03, 0x0c, 0x11, 0x0a, 0x11, 0x0e, // ........ - 0x11, 0x0b, 0x11, 0x1f, 0x11, 0x1e, 0x11, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x30, 0x25, 0x92, 0xda, // ./..0%.. + 0xb0, 0xcc, 0x01, 0x00, 0x0c, 0x01, 0x2a, 0xf9, // ......*. + 0x3d, 0xbe, 0x0b, 0x09, 0x54, 0x32, 0x32, 0x30, // =...T220 + 0x34, 0x30, 0x2d, 0x44, 0x55, 0x54, 0x02, 0x0a, // 40-DUT.. + 0x00, 0x0d, 0x03, 0x0c, 0x11, 0x0a, 0x11, 0x0e, // ........ + 0x11, 0x0b, 0x11, 0x1f, 0x11, 0x1e, 0x11, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt496[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x44, 0xc6, 0xee, 0x6b, // ./..D..k - 0x21, 0x00, 0x01, 0x00, 0x0c, 0x01, 0x2a, 0x7e, // !.....*~ - 0x1c, 0xaf, 0x0b, 0x09, 0x31, 0x31, 0x30, 0x30, // ....1100 - 0x30, 0x37, 0x2d, 0x44, 0x55, 0x54, 0x02, 0x0a, // 07-DUT.. - 0x0c, 0x0b, 0x03, 0x0a, 0x11, 0x0c, 0x11, 0x0e, // ........ - 0x11, 0x1f, 0x11, 0x1e, 0x11, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x44, 0xc6, 0xee, 0x6b, // ./..D..k + 0x21, 0x00, 0x01, 0x00, 0x0c, 0x01, 0x2a, 0x7e, // !.....*~ + 0x1c, 0xaf, 0x0b, 0x09, 0x31, 0x31, 0x30, 0x30, // ....1100 + 0x30, 0x37, 0x2d, 0x44, 0x55, 0x54, 0x02, 0x0a, // 07-DUT.. + 0x0c, 0x0b, 0x03, 0x0a, 0x11, 0x0c, 0x11, 0x0e, // ........ + 0x11, 0x1f, 0x11, 0x1e, 0x11, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt511[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xd3, 0x4d, 0x3b, 0xe9, // ./...M;. - 0xbc, 0x4c, 0x01, 0x00, 0x3c, 0x24, 0x0c, 0x8b, // .L..<$.. - 0x03, 0xae, 0x1a, 0x09, 0x5b, 0x4c, 0x47, 0x5d, // ....[LG] - 0x20, 0x77, 0x65, 0x62, 0x4f, 0x53, 0x20, 0x54, // webOS T - 0x56, 0x20, 0x4f, 0x4c, 0x45, 0x44, 0x35, 0x35, // V OLED55 - 0x43, 0x31, 0x50, 0x53, 0x42, 0x07, 0x03, 0x0b, // C1PSB... - 0x11, 0x0e, 0x11, 0x00, 0x12, 0x01, 0x05, 0x01, // ........ - 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xd3, 0x4d, 0x3b, 0xe9, // ./...M;. + 0xbc, 0x4c, 0x01, 0x00, 0x3c, 0x24, 0x0c, 0x8b, // .L..<$.. + 0x03, 0xae, 0x1a, 0x09, 0x5b, 0x4c, 0x47, 0x5d, // ....[LG] + 0x20, 0x77, 0x65, 0x62, 0x4f, 0x53, 0x20, 0x54, // webOS T + 0x56, 0x20, 0x4f, 0x4c, 0x45, 0x44, 0x35, 0x35, // V OLED55 + 0x43, 0x31, 0x50, 0x53, 0x42, 0x07, 0x03, 0x0b, // C1PSB... + 0x11, 0x0e, 0x11, 0x00, 0x12, 0x01, 0x05, 0x01, // ........ + 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt523[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xc9, 0xfd, 0x14, 0x45, // ./.....E - 0x0a, 0x00, 0x01, 0x00, 0x04, 0x04, 0x24, 0x16, // ......$. - 0x51, 0xbe, 0x0e, 0x09, 0x41, 0x54, 0x48, 0x2d, // Q...ATH- - 0x43, 0x4b, 0x53, 0x33, 0x33, 0x30, 0x58, 0x42, // CKS330XB - 0x54, 0x15, 0x03, 0x31, 0x11, 0x08, 0x11, 0x03, // T..1.... - 0x12, 0x1e, 0x11, 0x0c, 0x11, 0x0f, 0x11, 0x0e, // ........ - 0x11, 0x0b, 0x11, 0x00, 0x12, 0x00, 0x10, 0x01, // ........ - 0x05, 0x01, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xc9, 0xfd, 0x14, 0x45, // ./.....E + 0x0a, 0x00, 0x01, 0x00, 0x04, 0x04, 0x24, 0x16, // ......$. + 0x51, 0xbe, 0x0e, 0x09, 0x41, 0x54, 0x48, 0x2d, // Q...ATH- + 0x43, 0x4b, 0x53, 0x33, 0x33, 0x30, 0x58, 0x42, // CKS330XB + 0x54, 0x15, 0x03, 0x31, 0x11, 0x08, 0x11, 0x03, // T..1.... + 0x12, 0x1e, 0x11, 0x0c, 0x11, 0x0f, 0x11, 0x0e, // ........ + 0x11, 0x0b, 0x11, 0x00, 0x12, 0x00, 0x10, 0x01, // ........ + 0x05, 0x01, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt534[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x6a, 0x78, 0xbf, 0x09, // ./..jx.. - 0x95, 0x3c, 0x01, 0x00, 0x0c, 0x01, 0x2a, 0x7c, // .<....*| - 0x4f, 0xbb, 0x10, 0x09, 0x44, 0x45, 0x53, 0x4b, // O...DESK - 0x54, 0x4f, 0x50, 0x2d, 0x39, 0x38, 0x41, 0x31, // TOP-98A1 - 0x41, 0x42, 0x53, 0x02, 0x0a, 0x00, 0x0d, 0x03, // ABS..... - 0x0c, 0x11, 0x0a, 0x11, 0x0e, 0x11, 0x0b, 0x11, // ........ - 0x1f, 0x11, 0x1e, 0x11, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x6a, 0x78, 0xbf, 0x09, // ./..jx.. + 0x95, 0x3c, 0x01, 0x00, 0x0c, 0x01, 0x2a, 0x7c, // .<....*| + 0x4f, 0xbb, 0x10, 0x09, 0x44, 0x45, 0x53, 0x4b, // O...DESK + 0x54, 0x4f, 0x50, 0x2d, 0x39, 0x38, 0x41, 0x31, // TOP-98A1 + 0x41, 0x42, 0x53, 0x02, 0x0a, 0x00, 0x0d, 0x03, // ABS..... + 0x0c, 0x11, 0x0a, 0x11, 0x0e, 0x11, 0x0b, 0x11, // ........ + 0x1f, 0x11, 0x1e, 0x11, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt706[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x1c, 0xfb, 0xd3, 0x29, // ./.....) - 0x24, 0x58, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x1a, // $X....Z. - 0x0c, 0xbe, 0x0f, 0x09, 0x50, 0x69, 0x78, 0x65, // ....Pixe - 0x6c, 0x20, 0x36, 0x20, 0x50, 0x72, 0x6f, 0x20, // l 6 Pro - 0x30, 0x36, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 06...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x22, 0x1e, 0x7e, 0xb0, 0x4e, 0x50, 0x5d, 0x8b, // ".~.NP]. - 0x27, 0x47, 0x79, 0x5f, 0x63, 0x0b, 0xe5, 0xce, // 'Gy_c... - 0x5a, 0x6c, 0xb1, 0xa7, 0x6d, 0xf1, 0xbc, 0x9b, // Zl..m... - 0xde, 0x3d, 0x5c, 0xae, 0x21, 0xfa, 0x2e, 0xa8, // .=\.!... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x1c, 0xfb, 0xd3, 0x29, // ./.....) + 0x24, 0x58, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x1a, // $X....Z. + 0x0c, 0xbe, 0x0f, 0x09, 0x50, 0x69, 0x78, 0x65, // ....Pixe + 0x6c, 0x20, 0x36, 0x20, 0x50, 0x72, 0x6f, 0x20, // l 6 Pro + 0x30, 0x36, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 06...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x22, 0x1e, 0x7e, 0xb0, 0x4e, 0x50, 0x5d, 0x8b, // ".~.NP]. + 0x27, 0x47, 0x79, 0x5f, 0x63, 0x0b, 0xe5, 0xce, // 'Gy_c... + 0x5a, 0x6c, 0xb1, 0xa7, 0x6d, 0xf1, 0xbc, 0x9b, // Zl..m... + 0xde, 0x3d, 0x5c, 0xae, 0x21, 0xfa, 0x2e, 0xa8, // .=\.!... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt707[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xda, 0xbd, 0x68, 0x72, // ./....hr - 0x6e, 0xb0, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0xc7, // n.....Z. - 0x5b, 0xab, 0x10, 0x09, 0x72, 0x65, 0x61, 0x6c, // [...real - 0x6d, 0x65, 0x20, 0x47, 0x54, 0x20, 0x4e, 0x45, // me GT NE - 0x4f, 0x20, 0x33, 0x19, 0x03, 0x05, 0x11, 0x0a, // O 3..... - 0x11, 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, // ........ - 0x11, 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, // .....-./ - 0x11, 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, // ...2.... - 0x07, 0x00, 0xdf, 0x0c, 0xa9, 0x80, 0xbb, 0x4f, // .......O - 0x9f, 0x5c, 0x49, 0x06, 0xcb, 0x15, 0xaa, 0x9e, // .\I..... - 0xa4, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xda, 0xbd, 0x68, 0x72, // ./....hr + 0x6e, 0xb0, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0xc7, // n.....Z. + 0x5b, 0xab, 0x10, 0x09, 0x72, 0x65, 0x61, 0x6c, // [...real + 0x6d, 0x65, 0x20, 0x47, 0x54, 0x20, 0x4e, 0x45, // me GT NE + 0x4f, 0x20, 0x33, 0x19, 0x03, 0x05, 0x11, 0x0a, // O 3..... + 0x11, 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, // ........ + 0x11, 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, // .....-./ + 0x11, 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, // ...2.... + 0x07, 0x00, 0xdf, 0x0c, 0xa9, 0x80, 0xbb, 0x4f, // .......O + 0x9f, 0x5c, 0x49, 0x06, 0xcb, 0x15, 0xaa, 0x9e, // .\I..... + 0xa4, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt786[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x30, 0x25, 0x92, 0xda, // ./..0%.. - 0xb0, 0xcc, 0x01, 0x00, 0x0c, 0x01, 0x2a, 0xf8, // ......*. - 0x3d, 0xb5, 0x0b, 0x09, 0x54, 0x32, 0x32, 0x30, // =...T220 - 0x34, 0x30, 0x2d, 0x44, 0x55, 0x54, 0x02, 0x0a, // 40-DUT.. - 0x00, 0x0d, 0x03, 0x0c, 0x11, 0x0a, 0x11, 0x0e, // ........ - 0x11, 0x0b, 0x11, 0x1f, 0x11, 0x1e, 0x11, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x30, 0x25, 0x92, 0xda, // ./..0%.. + 0xb0, 0xcc, 0x01, 0x00, 0x0c, 0x01, 0x2a, 0xf8, // ......*. + 0x3d, 0xb5, 0x0b, 0x09, 0x54, 0x32, 0x32, 0x30, // =...T220 + 0x34, 0x30, 0x2d, 0x44, 0x55, 0x54, 0x02, 0x0a, // 40-DUT.. + 0x00, 0x0d, 0x03, 0x0c, 0x11, 0x0a, 0x11, 0x0e, // ........ + 0x11, 0x0b, 0x11, 0x1f, 0x11, 0x1e, 0x11, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt787[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xf6, 0xc5, 0x54, 0x1a, // ./....T. - 0x94, 0xa0, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x98, // ......Z. - 0x44, 0xc6, 0x1c, 0x09, 0xe3, 0x82, 0x81, 0xe3, // D....... - 0x82, 0x81, 0xe3, 0x81, 0xbf, 0xe3, 0x81, 0xa1, // ........ - 0xe4, 0xb8, 0x96, 0xe7, 0x95, 0x8c, 0xe4, 0xb8, // ........ - 0x80, 0xe6, 0x8e, 0xa8, 0xe3, 0x81, 0x97, 0x17, // ........ - 0x03, 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, 0x0e, // ........ - 0x11, 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, 0x1f, // ........ - 0x11, 0x2f, 0x11, 0x00, 0x12, 0x32, 0x11, 0x01, // ./...2.. - 0x05, 0x81, 0x07, 0x00, 0xdf, 0x0c, 0xa9, 0x80, // ........ - 0xbb, 0x4f, 0x9f, 0x5c, 0x49, 0x06, 0xcb, 0x15, // .O.\I... - 0xaa, 0x9e, 0xa4, 0x00, 0xdf, 0x0c, 0xa9, 0x80, // ........ - 0xbb, 0x4f, 0x9f, 0x5c, 0x49, 0x06, 0xcb, 0x15, // .O.\I... - 0xcc, 0x9e, 0xa4, 0x5a, 0x6c, 0xb1, 0xa7, 0x6d, // ...Zl..m - 0xf1, 0xbc, 0x9b, 0xde, 0x3d, 0x5c, 0xae, 0x21, // ....=\.! - 0xfa, 0x2e, 0xa8, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xf6, 0xc5, 0x54, 0x1a, // ./....T. + 0x94, 0xa0, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x98, // ......Z. + 0x44, 0xc6, 0x1c, 0x09, 0xe3, 0x82, 0x81, 0xe3, // D....... + 0x82, 0x81, 0xe3, 0x81, 0xbf, 0xe3, 0x81, 0xa1, // ........ + 0xe4, 0xb8, 0x96, 0xe7, 0x95, 0x8c, 0xe4, 0xb8, // ........ + 0x80, 0xe6, 0x8e, 0xa8, 0xe3, 0x81, 0x97, 0x17, // ........ + 0x03, 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, 0x0e, // ........ + 0x11, 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, 0x1f, // ........ + 0x11, 0x2f, 0x11, 0x00, 0x12, 0x32, 0x11, 0x01, // ./...2.. + 0x05, 0x81, 0x07, 0x00, 0xdf, 0x0c, 0xa9, 0x80, // ........ + 0xbb, 0x4f, 0x9f, 0x5c, 0x49, 0x06, 0xcb, 0x15, // .O.\I... + 0xaa, 0x9e, 0xa4, 0x00, 0xdf, 0x0c, 0xa9, 0x80, // ........ + 0xbb, 0x4f, 0x9f, 0x5c, 0x49, 0x06, 0xcb, 0x15, // .O.\I... + 0xcc, 0x9e, 0xa4, 0x5a, 0x6c, 0xb1, 0xa7, 0x6d, // ...Zl..m + 0xf1, 0xbc, 0x9b, 0xde, 0x3d, 0x5c, 0xae, 0x21, // ....=\.! + 0xfa, 0x2e, 0xa8, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt800[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x44, 0xc6, 0xee, 0x6b, // ./..D..k - 0x21, 0x00, 0x01, 0x00, 0x0c, 0x01, 0x2a, 0x7f, // !.....*. - 0x1c, 0xb0, 0x0b, 0x09, 0x31, 0x31, 0x30, 0x30, // ....1100 - 0x30, 0x37, 0x2d, 0x44, 0x55, 0x54, 0x02, 0x0a, // 07-DUT.. - 0x0c, 0x0b, 0x03, 0x0a, 0x11, 0x0c, 0x11, 0x0e, // ........ - 0x11, 0x1f, 0x11, 0x1e, 0x11, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x44, 0xc6, 0xee, 0x6b, // ./..D..k + 0x21, 0x00, 0x01, 0x00, 0x0c, 0x01, 0x2a, 0x7f, // !.....*. + 0x1c, 0xb0, 0x0b, 0x09, 0x31, 0x31, 0x30, 0x30, // ....1100 + 0x30, 0x37, 0x2d, 0x44, 0x55, 0x54, 0x02, 0x0a, // 07-DUT.. + 0x0c, 0x0b, 0x03, 0x0a, 0x11, 0x0c, 0x11, 0x0e, // ........ + 0x11, 0x1f, 0x11, 0x1e, 0x11, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt821[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x6a, 0x78, 0xbf, 0x09, // ./..jx.. - 0x95, 0x3c, 0x01, 0x00, 0x0c, 0x01, 0x2a, 0x7c, // .<....*| - 0x4f, 0xb2, 0x10, 0x09, 0x44, 0x45, 0x53, 0x4b, // O...DESK - 0x54, 0x4f, 0x50, 0x2d, 0x39, 0x38, 0x41, 0x31, // TOP-98A1 - 0x41, 0x42, 0x53, 0x02, 0x0a, 0x00, 0x0d, 0x03, // ABS..... - 0x0c, 0x11, 0x0a, 0x11, 0x0e, 0x11, 0x0b, 0x11, // ........ - 0x1f, 0x11, 0x1e, 0x11, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x6a, 0x78, 0xbf, 0x09, // ./..jx.. + 0x95, 0x3c, 0x01, 0x00, 0x0c, 0x01, 0x2a, 0x7c, // .<....*| + 0x4f, 0xb2, 0x10, 0x09, 0x44, 0x45, 0x53, 0x4b, // O...DESK + 0x54, 0x4f, 0x50, 0x2d, 0x39, 0x38, 0x41, 0x31, // TOP-98A1 + 0x41, 0x42, 0x53, 0x02, 0x0a, 0x00, 0x0d, 0x03, // ABS..... + 0x0c, 0x11, 0x0a, 0x11, 0x0e, 0x11, 0x0b, 0x11, // ........ + 0x1f, 0x11, 0x1e, 0x11, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt840[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x1c, 0xfb, 0xd3, 0x29, // ./.....) - 0x24, 0x58, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x1a, // $X....Z. - 0x0c, 0xba, 0x0f, 0x09, 0x50, 0x69, 0x78, 0x65, // ....Pixe - 0x6c, 0x20, 0x36, 0x20, 0x50, 0x72, 0x6f, 0x20, // l 6 Pro - 0x30, 0x36, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 06...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x22, 0x1e, 0x7e, 0xb0, 0x4e, 0x50, 0x5d, 0x8b, // ".~.NP]. - 0x27, 0x47, 0x79, 0x5f, 0x63, 0x0b, 0xe5, 0xce, // 'Gy_c... - 0x5a, 0x6c, 0xb1, 0xa7, 0x6d, 0xf1, 0xbc, 0x9b, // Zl..m... - 0xde, 0x3d, 0x5c, 0xae, 0x21, 0xfa, 0x2e, 0xa8, // .=\.!... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x1c, 0xfb, 0xd3, 0x29, // ./.....) + 0x24, 0x58, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x1a, // $X....Z. + 0x0c, 0xba, 0x0f, 0x09, 0x50, 0x69, 0x78, 0x65, // ....Pixe + 0x6c, 0x20, 0x36, 0x20, 0x50, 0x72, 0x6f, 0x20, // l 6 Pro + 0x30, 0x36, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 06...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x22, 0x1e, 0x7e, 0xb0, 0x4e, 0x50, 0x5d, 0x8b, // ".~.NP]. + 0x27, 0x47, 0x79, 0x5f, 0x63, 0x0b, 0xe5, 0xce, // 'Gy_c... + 0x5a, 0x6c, 0xb1, 0xa7, 0x6d, 0xf1, 0xbc, 0x9b, // Zl..m... + 0xde, 0x3d, 0x5c, 0xae, 0x21, 0xfa, 0x2e, 0xa8, // .=\.!... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt848[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xd3, 0x4d, 0x3b, 0xe9, // ./...M;. - 0xbc, 0x4c, 0x01, 0x00, 0x3c, 0x24, 0x0c, 0x8a, // .L..<$.. - 0x03, 0xac, 0x1a, 0x09, 0x5b, 0x4c, 0x47, 0x5d, // ....[LG] - 0x20, 0x77, 0x65, 0x62, 0x4f, 0x53, 0x20, 0x54, // webOS T - 0x56, 0x20, 0x4f, 0x4c, 0x45, 0x44, 0x35, 0x35, // V OLED55 - 0x43, 0x31, 0x50, 0x53, 0x42, 0x07, 0x03, 0x0b, // C1PSB... - 0x11, 0x0e, 0x11, 0x00, 0x12, 0x01, 0x05, 0x01, // ........ - 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xd3, 0x4d, 0x3b, 0xe9, // ./...M;. + 0xbc, 0x4c, 0x01, 0x00, 0x3c, 0x24, 0x0c, 0x8a, // .L..<$.. + 0x03, 0xac, 0x1a, 0x09, 0x5b, 0x4c, 0x47, 0x5d, // ....[LG] + 0x20, 0x77, 0x65, 0x62, 0x4f, 0x53, 0x20, 0x54, // webOS T + 0x56, 0x20, 0x4f, 0x4c, 0x45, 0x44, 0x35, 0x35, // V OLED55 + 0x43, 0x31, 0x50, 0x53, 0x42, 0x07, 0x03, 0x0b, // C1PSB... + 0x11, 0x0e, 0x11, 0x00, 0x12, 0x01, 0x05, 0x01, // ........ + 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt865[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xc9, 0xfd, 0x14, 0x45, // ./.....E - 0x0a, 0x00, 0x01, 0x00, 0x04, 0x04, 0x24, 0x16, // ......$. - 0x51, 0xb5, 0x0e, 0x09, 0x41, 0x54, 0x48, 0x2d, // Q...ATH- - 0x43, 0x4b, 0x53, 0x33, 0x33, 0x30, 0x58, 0x42, // CKS330XB - 0x54, 0x15, 0x03, 0x31, 0x11, 0x08, 0x11, 0x03, // T..1.... - 0x12, 0x1e, 0x11, 0x0c, 0x11, 0x0f, 0x11, 0x0e, // ........ - 0x11, 0x0b, 0x11, 0x00, 0x12, 0x00, 0x10, 0x01, // ........ - 0x05, 0x01, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xc9, 0xfd, 0x14, 0x45, // ./.....E + 0x0a, 0x00, 0x01, 0x00, 0x04, 0x04, 0x24, 0x16, // ......$. + 0x51, 0xb5, 0x0e, 0x09, 0x41, 0x54, 0x48, 0x2d, // Q...ATH- + 0x43, 0x4b, 0x53, 0x33, 0x33, 0x30, 0x58, 0x42, // CKS330XB + 0x54, 0x15, 0x03, 0x31, 0x11, 0x08, 0x11, 0x03, // T..1.... + 0x12, 0x1e, 0x11, 0x0c, 0x11, 0x0f, 0x11, 0x0e, // ........ + 0x11, 0x0b, 0x11, 0x00, 0x12, 0x00, 0x10, 0x01, // ........ + 0x05, 0x01, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt910[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xb0, 0x27, 0x7f, 0x19, // ./...'.. - 0x28, 0xf8, 0x01, 0x00, 0x0c, 0x01, 0x2a, 0xee, // (.....*. - 0x75, 0xae, 0x0b, 0x09, 0x31, 0x30, 0x34, 0x30, // u...1040 - 0x38, 0x39, 0x2d, 0x44, 0x55, 0x54, 0x02, 0x0a, // 89-DUT.. - 0x00, 0x0b, 0x03, 0x0a, 0x11, 0x0c, 0x11, 0x0e, // ........ - 0x11, 0x1f, 0x11, 0x1e, 0x11, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xb0, 0x27, 0x7f, 0x19, // ./...'.. + 0x28, 0xf8, 0x01, 0x00, 0x0c, 0x01, 0x2a, 0xee, // (.....*. + 0x75, 0xae, 0x0b, 0x09, 0x31, 0x30, 0x34, 0x30, // u...1040 + 0x38, 0x39, 0x2d, 0x44, 0x55, 0x54, 0x02, 0x0a, // 89-DUT.. + 0x00, 0x0b, 0x03, 0x0a, 0x11, 0x0c, 0x11, 0x0e, // ........ + 0x11, 0x1f, 0x11, 0x1e, 0x11, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt911[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xda, 0xbd, 0x68, 0x72, // ./....hr - 0x6e, 0xb0, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0xc7, // n.....Z. - 0x5b, 0xac, 0x10, 0x09, 0x72, 0x65, 0x61, 0x6c, // [...real - 0x6d, 0x65, 0x20, 0x47, 0x54, 0x20, 0x4e, 0x45, // me GT NE - 0x4f, 0x20, 0x33, 0x19, 0x03, 0x05, 0x11, 0x0a, // O 3..... - 0x11, 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, // ........ - 0x11, 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, // .....-./ - 0x11, 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, // ...2.... - 0x07, 0x00, 0xdf, 0x0c, 0xa9, 0x80, 0xbb, 0x4f, // .......O - 0x9f, 0x5c, 0x49, 0x06, 0xcb, 0x15, 0xaa, 0x9e, // .\I..... - 0xa4, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xda, 0xbd, 0x68, 0x72, // ./....hr + 0x6e, 0xb0, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0xc7, // n.....Z. + 0x5b, 0xac, 0x10, 0x09, 0x72, 0x65, 0x61, 0x6c, // [...real + 0x6d, 0x65, 0x20, 0x47, 0x54, 0x20, 0x4e, 0x45, // me GT NE + 0x4f, 0x20, 0x33, 0x19, 0x03, 0x05, 0x11, 0x0a, // O 3..... + 0x11, 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, // ........ + 0x11, 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, // .....-./ + 0x11, 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, // ...2.... + 0x07, 0x00, 0xdf, 0x0c, 0xa9, 0x80, 0xbb, 0x4f, // .......O + 0x9f, 0x5c, 0x49, 0x06, 0xcb, 0x15, 0xaa, 0x9e, // .\I..... + 0xa4, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt1093[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xc2, 0x3c, 0x42, 0xd9, // ./...\....za - 0x06, 0xaf, 0x12, 0x09, 0xe5, 0x98, 0x8e, 0xe5, // ........ - 0x98, 0x8e, 0x20, 0xe7, 0x9a, 0x84, 0x20, 0x69, // .. ... i - 0x50, 0x68, 0x6f, 0x6e, 0x65, 0x11, 0x03, 0x00, // Phone... - 0x12, 0x1f, 0x11, 0x2f, 0x11, 0x0a, 0x11, 0x0c, // .../.... - 0x11, 0x16, 0x11, 0x32, 0x11, 0x01, 0x18, 0x01, // ...2.... - 0x05, 0x31, 0x07, 0xfe, 0xca, 0xca, 0xde, 0xaf, // .1...... - 0xde, 0xca, 0xde, 0xde, 0xfa, 0xca, 0xde, 0x00, // ........ - 0x00, 0x00, 0x00, 0x77, 0x0a, 0x6a, 0x10, 0xa2, // ...w.j.. - 0x22, 0xf2, 0x86, 0x5f, 0x41, 0x19, 0x1d, 0x02, // ".._A... - 0x03, 0x03, 0x02, 0x1a, 0x29, 0xea, 0xab, 0x01, // ....)... - 0x73, 0xbc, 0x88, 0x1c, 0x45, 0x4d, 0xe1, 0x66, // s...EM.f - 0x24, 0x8d, 0x2d, 0x27, 0xff, 0x00, 0x4c, 0x02, // $.-'..L. - 0x24, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // $....... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x0d, 0x19, 0xf0, 0x1b, // ./...... + 0x3e, 0x5c, 0x01, 0x00, 0x0c, 0x02, 0x7a, 0x61, // >\....za + 0x06, 0xaf, 0x12, 0x09, 0xe5, 0x98, 0x8e, 0xe5, // ........ + 0x98, 0x8e, 0x20, 0xe7, 0x9a, 0x84, 0x20, 0x69, // .. ... i + 0x50, 0x68, 0x6f, 0x6e, 0x65, 0x11, 0x03, 0x00, // Phone... + 0x12, 0x1f, 0x11, 0x2f, 0x11, 0x0a, 0x11, 0x0c, // .../.... + 0x11, 0x16, 0x11, 0x32, 0x11, 0x01, 0x18, 0x01, // ...2.... + 0x05, 0x31, 0x07, 0xfe, 0xca, 0xca, 0xde, 0xaf, // .1...... + 0xde, 0xca, 0xde, 0xde, 0xfa, 0xca, 0xde, 0x00, // ........ + 0x00, 0x00, 0x00, 0x77, 0x0a, 0x6a, 0x10, 0xa2, // ...w.j.. + 0x22, 0xf2, 0x86, 0x5f, 0x41, 0x19, 0x1d, 0x02, // ".._A... + 0x03, 0x03, 0x02, 0x1a, 0x29, 0xea, 0xab, 0x01, // ....)... + 0x73, 0xbc, 0x88, 0x1c, 0x45, 0x4d, 0xe1, 0x66, // s...EM.f + 0x24, 0x8d, 0x2d, 0x27, 0xff, 0x00, 0x4c, 0x02, // $.-'..L. + 0x24, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // $....... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt3393[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xd3, 0x4d, 0x3b, 0xe9, // ./...M;. - 0xbc, 0x4c, 0x01, 0x00, 0x3c, 0x24, 0x0c, 0x85, // .L..<$.. - 0x03, 0xaa, 0x1a, 0x09, 0x5b, 0x4c, 0x47, 0x5d, // ....[LG] - 0x20, 0x77, 0x65, 0x62, 0x4f, 0x53, 0x20, 0x54, // webOS T - 0x56, 0x20, 0x4f, 0x4c, 0x45, 0x44, 0x35, 0x35, // V OLED55 - 0x43, 0x31, 0x50, 0x53, 0x42, 0x07, 0x03, 0x0b, // C1PSB... - 0x11, 0x0e, 0x11, 0x00, 0x12, 0x01, 0x05, 0x01, // ........ - 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xd3, 0x4d, 0x3b, 0xe9, // ./...M;. + 0xbc, 0x4c, 0x01, 0x00, 0x3c, 0x24, 0x0c, 0x85, // .L..<$.. + 0x03, 0xaa, 0x1a, 0x09, 0x5b, 0x4c, 0x47, 0x5d, // ....[LG] + 0x20, 0x77, 0x65, 0x62, 0x4f, 0x53, 0x20, 0x54, // webOS T + 0x56, 0x20, 0x4f, 0x4c, 0x45, 0x44, 0x35, 0x35, // V OLED55 + 0x43, 0x31, 0x50, 0x53, 0x42, 0x07, 0x03, 0x0b, // C1PSB... + 0x11, 0x0e, 0x11, 0x00, 0x12, 0x01, 0x05, 0x01, // ........ + 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt3436[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x6a, 0x78, 0xbf, 0x09, // ./..jx.. - 0x95, 0x3c, 0x01, 0x00, 0x0c, 0x01, 0x2a, 0x79, // .<....*y - 0x4f, 0xba, 0x10, 0x09, 0x44, 0x45, 0x53, 0x4b, // O...DESK - 0x54, 0x4f, 0x50, 0x2d, 0x39, 0x38, 0x41, 0x31, // TOP-98A1 - 0x41, 0x42, 0x53, 0x02, 0x0a, 0x00, 0x0d, 0x03, // ABS..... - 0x0c, 0x11, 0x0a, 0x11, 0x0e, 0x11, 0x0b, 0x11, // ........ - 0x1f, 0x11, 0x1e, 0x11, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x6a, 0x78, 0xbf, 0x09, // ./..jx.. + 0x95, 0x3c, 0x01, 0x00, 0x0c, 0x01, 0x2a, 0x79, // .<....*y + 0x4f, 0xba, 0x10, 0x09, 0x44, 0x45, 0x53, 0x4b, // O...DESK + 0x54, 0x4f, 0x50, 0x2d, 0x39, 0x38, 0x41, 0x31, // TOP-98A1 + 0x41, 0x42, 0x53, 0x02, 0x0a, 0x00, 0x0d, 0x03, // ABS..... + 0x0c, 0x11, 0x0a, 0x11, 0x0e, 0x11, 0x0b, 0x11, // ........ + 0x1f, 0x11, 0x1e, 0x11, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt3437[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x30, 0x25, 0x92, 0xda, // ./..0%.. - 0xb0, 0xcc, 0x01, 0x00, 0x0c, 0x01, 0x2a, 0xf6, // ......*. - 0x3d, 0xb9, 0x0b, 0x09, 0x54, 0x32, 0x32, 0x30, // =...T220 - 0x34, 0x30, 0x2d, 0x44, 0x55, 0x54, 0x02, 0x0a, // 40-DUT.. - 0x00, 0x0d, 0x03, 0x0c, 0x11, 0x0a, 0x11, 0x0e, // ........ - 0x11, 0x0b, 0x11, 0x1f, 0x11, 0x1e, 0x11, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x30, 0x25, 0x92, 0xda, // ./..0%.. + 0xb0, 0xcc, 0x01, 0x00, 0x0c, 0x01, 0x2a, 0xf6, // ......*. + 0x3d, 0xb9, 0x0b, 0x09, 0x54, 0x32, 0x32, 0x30, // =...T220 + 0x34, 0x30, 0x2d, 0x44, 0x55, 0x54, 0x02, 0x0a, // 40-DUT.. + 0x00, 0x0d, 0x03, 0x0c, 0x11, 0x0a, 0x11, 0x0e, // ........ + 0x11, 0x0b, 0x11, 0x1f, 0x11, 0x1e, 0x11, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt3439[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xda, 0xbd, 0x68, 0x72, // ./....hr - 0x6e, 0xb0, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0xc4, // n.....Z. - 0x5b, 0xb1, 0x10, 0x09, 0x72, 0x65, 0x61, 0x6c, // [...real - 0x6d, 0x65, 0x20, 0x47, 0x54, 0x20, 0x4e, 0x45, // me GT NE - 0x4f, 0x20, 0x33, 0x19, 0x03, 0x05, 0x11, 0x0a, // O 3..... - 0x11, 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, // ........ - 0x11, 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, // .....-./ - 0x11, 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, // ...2.... - 0x07, 0x00, 0xdf, 0x0c, 0xa9, 0x80, 0xbb, 0x4f, // .......O - 0x9f, 0x5c, 0x49, 0x06, 0xcb, 0x15, 0xaa, 0x9e, // .\I..... - 0xa4, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xda, 0xbd, 0x68, 0x72, // ./....hr + 0x6e, 0xb0, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0xc4, // n.....Z. + 0x5b, 0xb1, 0x10, 0x09, 0x72, 0x65, 0x61, 0x6c, // [...real + 0x6d, 0x65, 0x20, 0x47, 0x54, 0x20, 0x4e, 0x45, // me GT NE + 0x4f, 0x20, 0x33, 0x19, 0x03, 0x05, 0x11, 0x0a, // O 3..... + 0x11, 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, // ........ + 0x11, 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, // .....-./ + 0x11, 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, // ...2.... + 0x07, 0x00, 0xdf, 0x0c, 0xa9, 0x80, 0xbb, 0x4f, // .......O + 0x9f, 0x5c, 0x49, 0x06, 0xcb, 0x15, 0xaa, 0x9e, // .\I..... + 0xa4, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt4807[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x44, 0xc6, 0xee, 0x6b, // ./..D..k - 0x21, 0x00, 0x01, 0x00, 0x0c, 0x01, 0x2a, 0x7c, // !.....*| - 0x1c, 0xab, 0x0b, 0x09, 0x31, 0x31, 0x30, 0x30, // ....1100 - 0x30, 0x37, 0x2d, 0x44, 0x55, 0x54, 0x02, 0x0a, // 07-DUT.. - 0x0c, 0x0b, 0x03, 0x0a, 0x11, 0x0c, 0x11, 0x0e, // ........ - 0x11, 0x1f, 0x11, 0x1e, 0x11, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x44, 0xc6, 0xee, 0x6b, // ./..D..k + 0x21, 0x00, 0x01, 0x00, 0x0c, 0x01, 0x2a, 0x7c, // !.....*| + 0x1c, 0xab, 0x0b, 0x09, 0x31, 0x31, 0x30, 0x30, // ....1100 + 0x30, 0x37, 0x2d, 0x44, 0x55, 0x54, 0x02, 0x0a, // 07-DUT.. + 0x0c, 0x0b, 0x03, 0x0a, 0x11, 0x0c, 0x11, 0x0e, // ........ + 0x11, 0x1f, 0x11, 0x1e, 0x11, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt4817[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xd3, 0x4d, 0x3b, 0xe9, // ./...M;. - 0xbc, 0x4c, 0x01, 0x00, 0x3c, 0x24, 0x0c, 0x81, // .L..<$.. - 0x03, 0xb6, 0x1a, 0x09, 0x5b, 0x4c, 0x47, 0x5d, // ....[LG] - 0x20, 0x77, 0x65, 0x62, 0x4f, 0x53, 0x20, 0x54, // webOS T - 0x56, 0x20, 0x4f, 0x4c, 0x45, 0x44, 0x35, 0x35, // V OLED55 - 0x43, 0x31, 0x50, 0x53, 0x42, 0x07, 0x03, 0x0b, // C1PSB... - 0x11, 0x0e, 0x11, 0x00, 0x12, 0x01, 0x05, 0x01, // ........ - 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xd3, 0x4d, 0x3b, 0xe9, // ./...M;. + 0xbc, 0x4c, 0x01, 0x00, 0x3c, 0x24, 0x0c, 0x81, // .L..<$.. + 0x03, 0xb6, 0x1a, 0x09, 0x5b, 0x4c, 0x47, 0x5d, // ....[LG] + 0x20, 0x77, 0x65, 0x62, 0x4f, 0x53, 0x20, 0x54, // webOS T + 0x56, 0x20, 0x4f, 0x4c, 0x45, 0x44, 0x35, 0x35, // V OLED55 + 0x43, 0x31, 0x50, 0x53, 0x42, 0x07, 0x03, 0x0b, // C1PSB... + 0x11, 0x0e, 0x11, 0x00, 0x12, 0x01, 0x05, 0x01, // ........ + 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt4844[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x6a, 0x78, 0xbf, 0x09, // ./..jx.. - 0x95, 0x3c, 0x01, 0x00, 0x0c, 0x01, 0x2a, 0x79, // .<....*y - 0x4f, 0xbc, 0x10, 0x09, 0x44, 0x45, 0x53, 0x4b, // O...DESK - 0x54, 0x4f, 0x50, 0x2d, 0x39, 0x38, 0x41, 0x31, // TOP-98A1 - 0x41, 0x42, 0x53, 0x02, 0x0a, 0x00, 0x0d, 0x03, // ABS..... - 0x0c, 0x11, 0x0a, 0x11, 0x0e, 0x11, 0x0b, 0x11, // ........ - 0x1f, 0x11, 0x1e, 0x11, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x6a, 0x78, 0xbf, 0x09, // ./..jx.. + 0x95, 0x3c, 0x01, 0x00, 0x0c, 0x01, 0x2a, 0x79, // .<....*y + 0x4f, 0xbc, 0x10, 0x09, 0x44, 0x45, 0x53, 0x4b, // O...DESK + 0x54, 0x4f, 0x50, 0x2d, 0x39, 0x38, 0x41, 0x31, // TOP-98A1 + 0x41, 0x42, 0x53, 0x02, 0x0a, 0x00, 0x0d, 0x03, // ABS..... + 0x0c, 0x11, 0x0a, 0x11, 0x0e, 0x11, 0x0b, 0x11, // ........ + 0x1f, 0x11, 0x1e, 0x11, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt4845[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x30, 0x25, 0x92, 0xda, // ./..0%.. - 0xb0, 0xcc, 0x01, 0x00, 0x0c, 0x01, 0x2a, 0xf6, // ......*. - 0x3d, 0xb6, 0x0b, 0x09, 0x54, 0x32, 0x32, 0x30, // =...T220 - 0x34, 0x30, 0x2d, 0x44, 0x55, 0x54, 0x02, 0x0a, // 40-DUT.. - 0x00, 0x0d, 0x03, 0x0c, 0x11, 0x0a, 0x11, 0x0e, // ........ - 0x11, 0x0b, 0x11, 0x1f, 0x11, 0x1e, 0x11, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x30, 0x25, 0x92, 0xda, // ./..0%.. + 0xb0, 0xcc, 0x01, 0x00, 0x0c, 0x01, 0x2a, 0xf6, // ......*. + 0x3d, 0xb6, 0x0b, 0x09, 0x54, 0x32, 0x32, 0x30, // =...T220 + 0x34, 0x30, 0x2d, 0x44, 0x55, 0x54, 0x02, 0x0a, // 40-DUT.. + 0x00, 0x0d, 0x03, 0x0c, 0x11, 0x0a, 0x11, 0x0e, // ........ + 0x11, 0x0b, 0x11, 0x1f, 0x11, 0x1e, 0x11, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt4925[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xc9, 0xfd, 0x14, 0x45, // ./.....E - 0x0a, 0x00, 0x01, 0x00, 0x04, 0x04, 0x24, 0x09, // ......$. - 0x51, 0xac, 0x0e, 0x09, 0x41, 0x54, 0x48, 0x2d, // Q...ATH- - 0x43, 0x4b, 0x53, 0x33, 0x33, 0x30, 0x58, 0x42, // CKS330XB - 0x54, 0x15, 0x03, 0x31, 0x11, 0x08, 0x11, 0x03, // T..1.... - 0x12, 0x1e, 0x11, 0x0c, 0x11, 0x0f, 0x11, 0x0e, // ........ - 0x11, 0x0b, 0x11, 0x00, 0x12, 0x00, 0x10, 0x01, // ........ - 0x05, 0x01, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0xc9, 0xfd, 0x14, 0x45, // ./.....E + 0x0a, 0x00, 0x01, 0x00, 0x04, 0x04, 0x24, 0x09, // ......$. + 0x51, 0xac, 0x0e, 0x09, 0x41, 0x54, 0x48, 0x2d, // Q...ATH- + 0x43, 0x4b, 0x53, 0x33, 0x33, 0x30, 0x58, 0x42, // CKS330XB + 0x54, 0x15, 0x03, 0x31, 0x11, 0x08, 0x11, 0x03, // T..1.... + 0x12, 0x1e, 0x11, 0x0c, 0x11, 0x0f, 0x11, 0x0e, // ........ + 0x11, 0x0b, 0x11, 0x00, 0x12, 0x00, 0x10, 0x01, // ........ + 0x05, 0x01, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt4962[258] = { - 0x04, 0x2f, 0xff, 0x01, 0x1c, 0xfb, 0xd3, 0x29, // ./.....) - 0x24, 0x58, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x1c, // $X....Z. - 0x0c, 0xc0, 0x0f, 0x09, 0x50, 0x69, 0x78, 0x65, // ....Pixe - 0x6c, 0x20, 0x36, 0x20, 0x50, 0x72, 0x6f, 0x20, // l 6 Pro - 0x30, 0x36, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 06...... - 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ - 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... - 0x22, 0x1e, 0x7e, 0xb0, 0x4e, 0x50, 0x5d, 0x8b, // ".~.NP]. - 0x27, 0x47, 0x79, 0x5f, 0x63, 0x0b, 0xe5, 0xce, // 'Gy_c... - 0x5a, 0x6c, 0xb1, 0xa7, 0x6d, 0xf1, 0xbc, 0x9b, // Zl..m... - 0xde, 0x3d, 0x5c, 0xae, 0x21, 0xfa, 0x2e, 0xa8, // .=\.!... - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00 // .. + 0x04, 0x2f, 0xff, 0x01, 0x1c, 0xfb, 0xd3, 0x29, // ./.....) + 0x24, 0x58, 0x01, 0x00, 0x0c, 0x02, 0x5a, 0x1c, // $X....Z. + 0x0c, 0xc0, 0x0f, 0x09, 0x50, 0x69, 0x78, 0x65, // ....Pixe + 0x6c, 0x20, 0x36, 0x20, 0x50, 0x72, 0x6f, 0x20, // l 6 Pro + 0x30, 0x36, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, // 06...... + 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, // ........ + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, // ....-./. + 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, // ..2..... + 0x22, 0x1e, 0x7e, 0xb0, 0x4e, 0x50, 0x5d, 0x8b, // ".~.NP]. + 0x27, 0x47, 0x79, 0x5f, 0x63, 0x0b, 0xe5, 0xce, // 'Gy_c... + 0x5a, 0x6c, 0xb1, 0xa7, 0x6d, 0xf1, 0xbc, 0x9b, // Zl..m... + 0xde, 0x3d, 0x5c, 0xae, 0x21, 0xfa, 0x2e, 0xa8, // .=\.!... + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x00, 0x00 // .. }; // Frame (258 bytes) static const unsigned char pkt4979[258] = { - 0x04, 0x2f, 0xff, 0x01, 0xc2, 0x3c, 0x42, 0xd9, // ./... selected_packets = { - {"pkt19200", pkt19200}, - {"pkt2062", pkt2062}, - {"pkt26171", pkt26171}, - {"pkt34639", pkt34639}, - {"pktAsha", pktAsha}, + {"pkt19200", pkt19200}, {"pkt2062", pkt2062}, {"pkt26171", pkt26171}, + {"pkt34639", pkt34639}, {"pktAsha", pktAsha}, }; std::vector data_packets = { - pkt34638, pkt34639, pkt2048, pkt2062, pkt2063, pkt2064, pkt2067, pkt2072, pkt2075, - pkt2076, pkt19189, pkt19190, pkt19191, pkt19192, pkt19193, pkt19194, pkt19198, pkt19200, - pkt19201, pkt19835, pkt19844, pkt19845, pkt19846, pkt19857, pkt19863, pkt19871, pkt19885, - pkt19886, pkt19898, pkt19899, pkt19904, pkt19908, pkt33190, pkt33191, pkt33217, pkt34019, - pkt34020, pkt19975, pkt19988, pkt20036, pkt575, pkt764, pkt29692, pkt29730, pkt29777, - pkt29785, pkt29830, pkt29836, pkt29922, pkt29927, pkt29928, pkt29931, pkt23904, pkt24033, - pkt24158, pkt24446, pkt24658, pkt25745, pkt25751, pkt26171, pkt26175, pkt26328, pkt26463, - pkt34640, pkt34666, pkt34778, pkt34779, pkt34843, pkt34847, pkt34848, pkt34875, pkt19294, - pkt4073, pkt4075, pkt4883, pkt7384, pkt7385, pkt10784, pkt10786, pkt10787, pkt10789, - pkt10799, pkt10800, pkt10801, pkt10804, pkt10806, pkt10807, pkt10808, pkt10809, pkt10816, - pkt10818, pkt10821, pkt10823, pkt10826, pkt10838, pkt10839, pkt10840, pkt10841, pkt10842, - pkt10843, pkt10845, pkt10857, pkt10858, pkt10859, pkt10860, pkt10871, pkt10872, pkt10874, - pkt10876, pkt10877, pkt10887, pkt10888, pkt10890, pkt10891, pkt10893, pkt10895, pkt10904, - pkt10906, pkt10910, pkt10911, pkt10915, pkt10916, pkt10922, pkt10927, pkt10928, pkt10930, - pkt10931, pkt10932, pkt10934, pkt10940, pkt10952, pkt10953, pkt10959, pkt10962, pkt10965, - pkt10967, pkt10973, pkt10976, pkt10982, pkt10984, pkt10986, pkt10987, pkt10997, pkt10999, - pkt11008, pkt11009, pkt11020, pkt11021, pkt11023, pkt11025, pkt11039, pkt11047, pkt11048, - pkt11049, pkt11067, pkt11080, pkt11081, pkt11083, pkt11092, pkt11093, pkt11108, pkt11141, - pkt11152, pkt11154, pkt11155, pkt11156, pkt11158, pkt11159, pkt473, pkt474, pkt488, - pkt489, pkt512, pkt513, pkt530, pkt545, pkt871, pkt27834, pkt27876, pkt649, - pkt677, pkt689, pkt709, pkt763, pkt771, pkt795, pkt951, pkt952, pkt953, - pkt954, pkt451, pkt482, pkt496, pkt511, pkt523, pkt534, pkt706, pkt707, - pkt786, pkt787, pkt800, pkt821, pkt840, pkt848, pkt865, pkt910, pkt911, - pkt1093, pkt1128, pkt1148, pkt1150, pkt1242, pkt1243, pkt1263, pkt1302, pkt1316, - pkt1358, pkt1359, pkt1428, pkt1564, pkt1587, pkt1596, pkt1597, pkt1614, pkt1615, - pkt1662, pkt1678, pkt1764, pkt1775, pkt1796, pkt1797, pkt1821, pkt1840, pkt1855, - pkt2092, pkt2098, pkt2128, pkt2150, pkt2151, pkt2204, pkt2304, pkt2432, pkt2450, - pkt2457, pkt2458, pkt2468, pkt2469, pkt2506, pkt2516, pkt2599, pkt2759, pkt2761, - pkt2778, pkt2779, pkt2780, pkt2788, pkt2818, pkt2890, pkt2931, pkt3390, pkt3391, - pkt3392, pkt3393, pkt3436, pkt3437, pkt3439, pkt4807, pkt4817, pkt4844, pkt4845, - pkt4925, pkt4962, pkt4979, pkt5162, pkt5163, pkt5178, pkt5192, pkt5193, pkt5238, - pkt5264, pkt5448, pkt5482, pkt5501, pkt5509, pkt5511, pkt5544, pkt5633, pkt5634, - pkt22626, pkt22660, pkt22727, pkt22959, pkt36316, pkt36383, pkt41746, pkt3253, pkt3259, - pkt3805, pkt3837, pkt3841, pkt4170, pkt4171, pkt4183, pkt4209, pkt4226, pkt4227, - pkt4247, pkt4257, pkt4266, pkt4450, pkt4459, pkt4468, pkt4469, pkt4473, pkt4485, - pkt4486, pkt4490, pkt4491, pkt4504, pkt4518, pkt4528, pkt5034, pkt5036, pkt5082, - pkt5118, pkt5119, pkt5261, pkt5306, pkt5318, pkt5328, pkt5878, pkt5920, pkt6423, - pkt6434, pkt6503, pkt6504, pkt6511, pkt6512, pkt6513, pkt6518, pkt6525, pkt6540, - pkt6567, pkt6854, pkt6867, pkt6870, pkt6871, pkt6875, pkt6876, pkt6886, pkt6895, - pkt6900, pkt6901, pkt6907, pkt6908, pkt6935, pkt7024, pkt7030, pkt7035, pkt7038, - pkt7049, pkt7050, pktAsha, + pkt34638, pkt34639, pkt2048, pkt2062, pkt2063, pkt2064, pkt2067, pkt2072, pkt2075, + pkt2076, pkt19189, pkt19190, pkt19191, pkt19192, pkt19193, pkt19194, pkt19198, pkt19200, + pkt19201, pkt19835, pkt19844, pkt19845, pkt19846, pkt19857, pkt19863, pkt19871, pkt19885, + pkt19886, pkt19898, pkt19899, pkt19904, pkt19908, pkt33190, pkt33191, pkt33217, pkt34019, + pkt34020, pkt19975, pkt19988, pkt20036, pkt575, pkt764, pkt29692, pkt29730, pkt29777, + pkt29785, pkt29830, pkt29836, pkt29922, pkt29927, pkt29928, pkt29931, pkt23904, pkt24033, + pkt24158, pkt24446, pkt24658, pkt25745, pkt25751, pkt26171, pkt26175, pkt26328, pkt26463, + pkt34640, pkt34666, pkt34778, pkt34779, pkt34843, pkt34847, pkt34848, pkt34875, pkt19294, + pkt4073, pkt4075, pkt4883, pkt7384, pkt7385, pkt10784, pkt10786, pkt10787, pkt10789, + pkt10799, pkt10800, pkt10801, pkt10804, pkt10806, pkt10807, pkt10808, pkt10809, pkt10816, + pkt10818, pkt10821, pkt10823, pkt10826, pkt10838, pkt10839, pkt10840, pkt10841, pkt10842, + pkt10843, pkt10845, pkt10857, pkt10858, pkt10859, pkt10860, pkt10871, pkt10872, pkt10874, + pkt10876, pkt10877, pkt10887, pkt10888, pkt10890, pkt10891, pkt10893, pkt10895, pkt10904, + pkt10906, pkt10910, pkt10911, pkt10915, pkt10916, pkt10922, pkt10927, pkt10928, pkt10930, + pkt10931, pkt10932, pkt10934, pkt10940, pkt10952, pkt10953, pkt10959, pkt10962, pkt10965, + pkt10967, pkt10973, pkt10976, pkt10982, pkt10984, pkt10986, pkt10987, pkt10997, pkt10999, + pkt11008, pkt11009, pkt11020, pkt11021, pkt11023, pkt11025, pkt11039, pkt11047, pkt11048, + pkt11049, pkt11067, pkt11080, pkt11081, pkt11083, pkt11092, pkt11093, pkt11108, pkt11141, + pkt11152, pkt11154, pkt11155, pkt11156, pkt11158, pkt11159, pkt473, pkt474, pkt488, + pkt489, pkt512, pkt513, pkt530, pkt545, pkt871, pkt27834, pkt27876, pkt649, + pkt677, pkt689, pkt709, pkt763, pkt771, pkt795, pkt951, pkt952, pkt953, + pkt954, pkt451, pkt482, pkt496, pkt511, pkt523, pkt534, pkt706, pkt707, + pkt786, pkt787, pkt800, pkt821, pkt840, pkt848, pkt865, pkt910, pkt911, + pkt1093, pkt1128, pkt1148, pkt1150, pkt1242, pkt1243, pkt1263, pkt1302, pkt1316, + pkt1358, pkt1359, pkt1428, pkt1564, pkt1587, pkt1596, pkt1597, pkt1614, pkt1615, + pkt1662, pkt1678, pkt1764, pkt1775, pkt1796, pkt1797, pkt1821, pkt1840, pkt1855, + pkt2092, pkt2098, pkt2128, pkt2150, pkt2151, pkt2204, pkt2304, pkt2432, pkt2450, + pkt2457, pkt2458, pkt2468, pkt2469, pkt2506, pkt2516, pkt2599, pkt2759, pkt2761, + pkt2778, pkt2779, pkt2780, pkt2788, pkt2818, pkt2890, pkt2931, pkt3390, pkt3391, + pkt3392, pkt3393, pkt3436, pkt3437, pkt3439, pkt4807, pkt4817, pkt4844, pkt4845, + pkt4925, pkt4962, pkt4979, pkt5162, pkt5163, pkt5178, pkt5192, pkt5193, pkt5238, + pkt5264, pkt5448, pkt5482, pkt5501, pkt5509, pkt5511, pkt5544, pkt5633, pkt5634, + pkt22626, pkt22660, pkt22727, pkt22959, pkt36316, pkt36383, pkt41746, pkt3253, pkt3259, + pkt3805, pkt3837, pkt3841, pkt4170, pkt4171, pkt4183, pkt4209, pkt4226, pkt4227, + pkt4247, pkt4257, pkt4266, pkt4450, pkt4459, pkt4468, pkt4469, pkt4473, pkt4485, + pkt4486, pkt4490, pkt4491, pkt4504, pkt4518, pkt4528, pkt5034, pkt5036, pkt5082, + pkt5118, pkt5119, pkt5261, pkt5306, pkt5318, pkt5328, pkt5878, pkt5920, pkt6423, + pkt6434, pkt6503, pkt6504, pkt6511, pkt6512, pkt6513, pkt6518, pkt6525, pkt6540, + pkt6567, pkt6854, pkt6867, pkt6870, pkt6871, pkt6875, pkt6876, pkt6886, pkt6895, + pkt6900, pkt6901, pkt6907, pkt6908, pkt6935, pkt7024, pkt7030, pkt7035, pkt7038, + pkt7049, pkt7050, pktAsha, }; diff --git a/system/gd/dumpsys/bluetooth_flatbuffer_test.cc b/system/gd/dumpsys/bluetooth_flatbuffer_test.cc index 4b836763c97..7c77e1075d6 100644 --- a/system/gd/dumpsys/bluetooth_flatbuffer_test.cc +++ b/system/gd/dumpsys/bluetooth_flatbuffer_test.cc @@ -26,7 +26,7 @@ namespace bluetooth { namespace dumpsys { class BluetoothFlatbufferTest : public ::testing::Test { - protected: +protected: void SetUp() override {} void TearDown() override {} diff --git a/system/gd/dumpsys/bundler/bundler.cc b/system/gd/dumpsys/bundler/bundler.cc index 1f688bb93d3..099c75bc452 100644 --- a/system/gd/dumpsys/bundler/bundler.cc +++ b/system/gd/dumpsys/bundler/bundler.cc @@ -75,11 +75,10 @@ bool VerifyBinarySchema(const std::vector& raw_schema) { * * @return: True if operation successful, false otherwise. */ -bool CreateBinarySchemaBundle( - flatbuffers::FlatBufferBuilder* builder, - const std::vector& filenames, - std::vector>* vector_map, - std::list* bundled_names) { +bool CreateBinarySchemaBundle(flatbuffers::FlatBufferBuilder* builder, + const std::vector& filenames, + std::vector>* vector_map, + std::list* bundled_names) { assert(builder != nullptr); assert(vector_map != nullptr); assert(bundled_names != nullptr); @@ -98,7 +97,8 @@ bool CreateBinarySchemaBundle( const reflection::Schema* schema = reflection::GetSchema(raw_schema.data()); if (schema->root_table() == nullptr) { - fprintf(stderr, "Unable to find root table for binary flatbuffer schema:%s\n", filename.c_str()); + fprintf(stderr, "Unable to find root table for binary flatbuffer schema:%s\n", + filename.c_str()); return false; } @@ -141,14 +141,15 @@ void WriteHeaderFile(FILE* fp, const uint8_t* data, size_t data_len) { } std::string namespace_prefix; - for (const auto& name : namespaces) namespace_prefix += (name + '_'); - - fprintf( - fp, - "// Generated file by bluetooth_flatbuffer bundler\n" - "#include \n"); - for_each( - namespaces.begin(), namespaces.end(), [fp](const std::string& s) { fprintf(fp, "namespace %s {\n", s.c_str()); }); + for (const auto& name : namespaces) { + namespace_prefix += (name + '_'); + } + + fprintf(fp, + "// Generated file by bluetooth_flatbuffer bundler\n" + "#include \n"); + for_each(namespaces.begin(), namespaces.end(), + [fp](const std::string& s) { fprintf(fp, "namespace %s {\n", s.c_str()); }); fprintf(fp, "extern const std::string& GetBundledSchemaData();\n"); fprintf(fp, "const unsigned char %sdata_[%zu] = {\n", namespace_prefix.c_str(), data_len); @@ -162,18 +163,14 @@ void WriteHeaderFile(FILE* fp, const uint8_t* data, size_t data_len) { } } fprintf(fp, " };\n"); - fprintf( - fp, - "const std::string %sstring_data_(%sdata_, %sdata_ + sizeof(%sdata_));\n", - namespace_prefix.c_str(), - namespace_prefix.c_str(), - namespace_prefix.c_str(), - namespace_prefix.c_str()); - fprintf(fp, "const std::string& GetBundledSchemaData() { return %sstring_data_; }\n", namespace_prefix.c_str()); - - for_each(namespaces.crbegin(), namespaces.crend(), [fp](const std::string& s) { - fprintf(fp, "} // namespace %s\n", s.c_str()); - }); + fprintf(fp, "const std::string %sstring_data_(%sdata_, %sdata_ + sizeof(%sdata_));\n", + namespace_prefix.c_str(), namespace_prefix.c_str(), namespace_prefix.c_str(), + namespace_prefix.c_str()); + fprintf(fp, "const std::string& GetBundledSchemaData() { return %sstring_data_; }\n", + namespace_prefix.c_str()); + + for_each(namespaces.crbegin(), namespaces.crend(), + [fp](const std::string& s) { fprintf(fp, "} // namespace %s\n", s.c_str()); }); } int ReadBundledSchema() { @@ -226,7 +223,8 @@ int WriteBundledSchema() { return EXIT_FAILURE; } - if (std::find(bundled_names.begin(), bundled_names.end(), main_root_name) == bundled_names.end()) { + if (std::find(bundled_names.begin(), bundled_names.end(), main_root_name) == + bundled_names.end()) { fprintf(stderr, "The main root name must match one of the bundled schema names\n"); fprintf(stderr, " main root name:%s\n", main_root_name); for (auto name : bundled_names) { @@ -242,8 +240,8 @@ int WriteBundledSchema() { std::string final_filename(opts.gen); final_filename.append("/"); final_filename.append(filename); - if (!flatbuffers::SaveFile( - final_filename.c_str(), (const char*)builder.GetBufferPointer(), builder.GetSize(), helper::AsBinaryFile)) { + if (!flatbuffers::SaveFile(final_filename.c_str(), (const char*)builder.GetBufferPointer(), + builder.GetSize(), helper::AsBinaryFile)) { fprintf(stderr, "Unable to save file:%s\n", final_filename.c_str()); return EXIT_FAILURE; } @@ -261,13 +259,14 @@ int WriteBundledSchema() { } int Usage(int argc, char** argv) { - fprintf( - stderr, - "Usage: %s [-r | -w] [-f ] [-g ] [-n ] [-v] -m \n", - argv[0]); + fprintf(stderr, + "Usage: %s [-r | -w] [-f ] [-g ] [-n ] [-v] -m " + " \n", + argv[0]); fprintf(stderr, " -r|-w : Read or write a dumpsys file\n"); - fprintf(stderr, " -f : Filename bundled schema to read or write (default:%s)\n", kDefaultBundleDataFile); + fprintf(stderr, " -f : Filename bundled schema to read or write (default:%s)\n", + kDefaultBundleDataFile); fprintf(stderr, " -g : Generated file output path\n"); fprintf(stderr, " -n : Namespace to embed binary output bundle data source\n"); fprintf(stderr, " -m : Name of the main root of this bundle\n"); diff --git a/system/gd/dumpsys/bundler/test.cc b/system/gd/dumpsys/bundler/test.cc index 24d2f913f29..eebd2eacbb9 100644 --- a/system/gd/dumpsys/bundler/test.cc +++ b/system/gd/dumpsys/bundler/test.cc @@ -29,14 +29,13 @@ constexpr char kTestFilename[] = "test.bfbs"; bool LoadBinarySchema(const char* filename, std::string* binary_schema); bool VerifyBinarySchema(const std::vector& raw_schema); bool CreateBinarySchemaBundle( - flatbuffers::FlatBufferBuilder* builder, - const std::vector& filenames, - std::vector>* vector_map, - std::list* bundled_names); + flatbuffers::FlatBufferBuilder* builder, const std::vector& filenames, + std::vector>* vector_map, + std::list* bundled_names); int WriteHeaderFile(FILE* fp, const uint8_t* data, size_t data_len); class BundlerTest : public ::testing::Test { - public: +public: void SetUp() override {} void TearDown() override {} diff --git a/system/gd/dumpsys/filter.cc b/system/gd/dumpsys/filter.cc index 8b51b5fda82..13cd2e5adf0 100644 --- a/system/gd/dumpsys/filter.cc +++ b/system/gd/dumpsys/filter.cc @@ -24,8 +24,9 @@ using namespace bluetooth; using namespace dumpsys; class Filter { - public: - Filter(const dumpsys::ReflectionSchema& reflection_schema) : reflection_schema_(reflection_schema) {} +public: + Filter(const dumpsys::ReflectionSchema& reflection_schema) + : reflection_schema_(reflection_schema) {} virtual ~Filter() = default; @@ -33,7 +34,7 @@ class Filter { static std::unique_ptr Factory(const dumpsys::ReflectionSchema& reflection_schema); - protected: +protected: /** * Given both reflection field data and the populated flatbuffer table data, if any, * filter the contents of the field based upon the filtering privacy level. @@ -59,8 +60,8 @@ class Filter { * @param table The populated field data, if any * */ - virtual void FilterObject( - const reflection::Object* /* object */, flatbuffers::Table* /* table */){}; + virtual void FilterObject(const reflection::Object* /* object */, + flatbuffers::Table* /* table */) {} /** * Given both reflection field data and the populated table data, if any, @@ -70,25 +71,25 @@ class Filter { * @param table The populated field data, if any * */ - virtual void FilterTable( - const reflection::Schema* /* schema */, flatbuffers::Table* /* table */){}; + virtual void FilterTable(const reflection::Schema* /* schema */, + flatbuffers::Table* /* table */) {} const dumpsys::ReflectionSchema& reflection_schema_; }; class DeveloperPrivacyFilter : public Filter { - public: - DeveloperPrivacyFilter(const dumpsys::ReflectionSchema& reflection_schema) : Filter(reflection_schema) {} - void FilterInPlace(char* /* dumpsys_data */) override { /* Nothing to do in this mode */ - } +public: + DeveloperPrivacyFilter(const dumpsys::ReflectionSchema& reflection_schema) + : Filter(reflection_schema) {} + void FilterInPlace(char* /* dumpsys_data */) override { /* Nothing to do in this mode */ } }; std::unique_ptr Filter::Factory(const dumpsys::ReflectionSchema& reflection_schema) { return std::make_unique(reflection_schema); } -void bluetooth::dumpsys::FilterSchema( - const ReflectionSchema& reflection_schema, std::string* dumpsys_data) { +void bluetooth::dumpsys::FilterSchema(const ReflectionSchema& reflection_schema, + std::string* dumpsys_data) { auto filter = Filter::Factory(reflection_schema); filter->FilterInPlace(dumpsys_data->data()); } diff --git a/system/gd/dumpsys/filter.h b/system/gd/dumpsys/filter.h index 02c62e3d16b..b932b4c6bfb 100644 --- a/system/gd/dumpsys/filter.h +++ b/system/gd/dumpsys/filter.h @@ -15,6 +15,7 @@ */ #include + #include "dumpsys/reflection_schema.h" namespace bluetooth { diff --git a/system/gd/dumpsys/filter_test.cc b/system/gd/dumpsys/filter_test.cc index 5b555135cf4..139279f6de9 100644 --- a/system/gd/dumpsys/filter_test.cc +++ b/system/gd/dumpsys/filter_test.cc @@ -34,7 +34,7 @@ using namespace bluetooth; namespace testing { class DumpsysFilterTest : public Test { - protected: +protected: void SetUp() override { test_data_classes_.push_back(std::make_unique()); test_data_classes_.push_back(std::make_unique()); @@ -80,7 +80,8 @@ std::string DumpsysFilterTest::PopulateTestSchema() { } fb_builder.Finish(builder.Finish()); - return std::string(fb_builder.GetBufferPointer(), fb_builder.GetBufferPointer() + fb_builder.GetSize()); + return std::string(fb_builder.GetBufferPointer(), + fb_builder.GetBufferPointer() + fb_builder.GetSize()); } TEST_F(DumpsysFilterTest, filter_as_developer) { diff --git a/system/gd/dumpsys/internal/filter_internal.cc b/system/gd/dumpsys/internal/filter_internal.cc index 38efba200f2..a26c56383f6 100644 --- a/system/gd/dumpsys/internal/filter_internal.cc +++ b/system/gd/dumpsys/internal/filter_internal.cc @@ -70,7 +70,7 @@ const char* internal::PrivacyLevelName(PrivacyLevel privacy_level) { return "Any"; break; } -}; +} internal::PrivacyLevel internal::GetPrivacyLevelAttribute(const std::string& string) { if (string == "Any") { return kAny; @@ -97,7 +97,8 @@ internal::PrivacyLevel internal::FindFieldPrivacyLevel(const reflection::Field& } const reflection::Object* internal::FindReflectionObject( - const flatbuffers::Vector>* objects, const flatbuffers::String* name) { + const flatbuffers::Vector>* objects, + const flatbuffers::String* name) { log::assert_that(objects != nullptr, "assert failed: objects != nullptr"); log::assert_that(name != nullptr, "assert failed: name != nullptr"); for (auto it = objects->cbegin(); it != objects->cend(); ++it) { @@ -108,7 +109,8 @@ const reflection::Object* internal::FindReflectionObject( return nullptr; } -bool internal::FilterTypeBool(const reflection::Field& field, flatbuffers::Table* table, PrivacyLevel privacy_level) { +bool internal::FilterTypeBool(const reflection::Field& field, flatbuffers::Table* table, + PrivacyLevel privacy_level) { log::assert_that(table != nullptr, "assert failed: table != nullptr"); const bool default_val = flatbuffers::GetFieldDefaultI(field); @@ -129,12 +131,11 @@ bool internal::FilterTypeBool(const reflection::Field& field, flatbuffers::Table return kFieldHasBeenFiltered; } -bool internal::FilterTypeInteger( - const reflection::Field& field, flatbuffers::Table* table, PrivacyLevel privacy_level) { +bool internal::FilterTypeInteger(const reflection::Field& field, flatbuffers::Table* table, + PrivacyLevel privacy_level) { log::assert_that(table != nullptr, "assert failed: table != nullptr"); - log::assert_that( - flatbuffers::IsInteger(field.type()->base_type()), - "assert failed: flatbuffers::IsInteger(field.type()->base_type())"); + log::assert_that(flatbuffers::IsInteger(field.type()->base_type()), + "assert failed: flatbuffers::IsInteger(field.type()->base_type())"); int32_t default_val = flatbuffers::GetFieldDefaultI(field); flatbuffers::voffset_t field_offset = field.offset(); @@ -150,7 +151,8 @@ bool internal::FilterTypeInteger( break; case kAnonymized: { auto target_field = flatbuffers::GetFieldI(*table, field); - int32_t new_val = static_cast(std::hash{}(std::to_string(target_field))); + int32_t new_val = + static_cast(std::hash{}(std::to_string(target_field))); flatbuffers::SetField(table, field, new_val); } break; default: @@ -159,22 +161,18 @@ bool internal::FilterTypeInteger( } if (DBG) { - log::info( - "Integer Field_name:{} privacy_level:{} old_value:{} / 0x{:x} ==> new_value:{}", - field.name()->c_str(), - PrivacyLevelName(privacy_level), - val, - val, - table->GetField(field_offset, default_val)); + log::info("Integer Field_name:{} privacy_level:{} old_value:{} / 0x{:x} ==> new_value:{}", + field.name()->c_str(), PrivacyLevelName(privacy_level), val, val, + table->GetField(field_offset, default_val)); } return kFieldHasBeenFiltered; } -bool internal::FilterTypeFloat(const reflection::Field& field, flatbuffers::Table* table, PrivacyLevel privacy_level) { +bool internal::FilterTypeFloat(const reflection::Field& field, flatbuffers::Table* table, + PrivacyLevel privacy_level) { log::assert_that(table != nullptr, "assert failed: table != nullptr"); - log::assert_that( - flatbuffers::IsFloat(field.type()->base_type()), - "assert failed: flatbuffers::IsFloat(field.type()->base_type())"); + log::assert_that(flatbuffers::IsFloat(field.type()->base_type()), + "assert failed: flatbuffers::IsFloat(field.type()->base_type())"); float default_val = flatbuffers::GetFieldDefaultI(field); flatbuffers::voffset_t field_offset = field.offset(); @@ -197,17 +195,15 @@ bool internal::FilterTypeFloat(const reflection::Field& field, flatbuffers::Tabl break; } if (DBG) { - log::info( - "Float Field_name:{} privacy_level:{} old_value:{:f} ==> new_value:{:f}", - field.name()->c_str(), - PrivacyLevelName(privacy_level), - val, - table->GetField(field_offset, default_val)); + log::info("Float Field_name:{} privacy_level:{} old_value:{:f} ==> new_value:{:f}", + field.name()->c_str(), PrivacyLevelName(privacy_level), val, + table->GetField(field_offset, default_val)); } return kFieldHasBeenFiltered; } -bool internal::FilterTypeLong(const reflection::Field& field, flatbuffers::Table* table, PrivacyLevel privacy_level) { +bool internal::FilterTypeLong(const reflection::Field& field, flatbuffers::Table* table, + PrivacyLevel privacy_level) { log::assert_that(table != nullptr, "assert failed: table != nullptr"); const int64_t default_val = flatbuffers::GetFieldDefaultI(field); @@ -223,7 +219,8 @@ bool internal::FilterTypeLong(const reflection::Field& field, flatbuffers::Table break; case kAnonymized: { auto target_field = flatbuffers::GetFieldI(*table, field); - int64_t new_val = static_cast(std::hash{}(std::to_string(target_field))); + int64_t new_val = + static_cast(std::hash{}(std::to_string(target_field))); flatbuffers::SetField(table, field, new_val); } break; default: @@ -233,11 +230,11 @@ bool internal::FilterTypeLong(const reflection::Field& field, flatbuffers::Table return kFieldHasBeenFiltered; } -bool internal::FilterTypeString(const reflection::Field& field, flatbuffers::Table* table, PrivacyLevel privacy_level) { +bool internal::FilterTypeString(const reflection::Field& field, flatbuffers::Table* table, + PrivacyLevel privacy_level) { log::assert_that(table != nullptr, "assert failed: table != nullptr"); - log::assert_that( - field.type()->base_type() == reflection::BaseType::String, - "assert failed: field.type()->base_type() == reflection::BaseType::String"); + log::assert_that(field.type()->base_type() == reflection::BaseType::String, + "assert failed: field.type()->base_type() == reflection::BaseType::String"); flatbuffers::voffset_t field_offset = field.offset(); @@ -266,22 +263,18 @@ bool internal::FilterTypeString(const reflection::Field& field, flatbuffers::Tab break; } if (DBG) { - log::info( - "Field_name:{} size:{} privacy_level:{} old_string:{} ==> new_string:{}", - field.name()->c_str(), - string->size(), - PrivacyLevelName(privacy_level), - old_string, - string->c_str()); + log::info("Field_name:{} size:{} privacy_level:{} old_string:{} ==> new_string:{}", + field.name()->c_str(), string->size(), PrivacyLevelName(privacy_level), old_string, + string->c_str()); } return kFieldHasBeenFiltered; } -bool internal::FilterTypeStruct(const reflection::Field& field, flatbuffers::Table* table, PrivacyLevel privacy_level) { +bool internal::FilterTypeStruct(const reflection::Field& field, flatbuffers::Table* table, + PrivacyLevel privacy_level) { log::assert_that(table != nullptr, "assert failed: table != nullptr"); - log::assert_that( - !flatbuffers::IsScalar(field.type()->base_type()), - "assert failed: !flatbuffers::IsScalar(field.type()->base_type())"); + log::assert_that(!flatbuffers::IsScalar(field.type()->base_type()), + "assert failed: !flatbuffers::IsScalar(field.type()->base_type())"); flatbuffers::voffset_t field_offset = field.offset(); @@ -289,10 +282,8 @@ bool internal::FilterTypeStruct(const reflection::Field& field, flatbuffers::Tab flatbuffers::SetFieldT(table, field, nullptr); internal::ScrubFromTable(table, field_offset); if (DBG) { - log::info( - "Table Removing field name:{} privacy_level:{}", - field.name()->c_str(), - PrivacyLevelName(privacy_level)); + log::info("Table Removing field name:{} privacy_level:{}", field.name()->c_str(), + PrivacyLevelName(privacy_level)); } } return kFieldContinueFiltering; diff --git a/system/gd/dumpsys/internal/filter_internal.h b/system/gd/dumpsys/internal/filter_internal.h index ea23b005801..a18575c72f0 100644 --- a/system/gd/dumpsys/internal/filter_internal.h +++ b/system/gd/dumpsys/internal/filter_internal.h @@ -104,7 +104,8 @@ PrivacyLevel GetPrivacyLevelAttribute(const std::string& name); * @return Reflection object if found, nullptr otherwise. */ const reflection::Object* FindReflectionObject( - const flatbuffers::Vector>* objects, const flatbuffers::String* name); + const flatbuffers::Vector>* objects, + const flatbuffers::String* name); /** * Process and filter the respective data types. @@ -115,12 +116,18 @@ const reflection::Object* FindReflectionObject( * * @return true if successfully filtered, false otherwise. */ -bool FilterTypeBool(const reflection::Field& field, flatbuffers::Table* table, PrivacyLevel privacy_level); -bool FilterTypeFloat(const reflection::Field& field, flatbuffers::Table* table, PrivacyLevel privacy_level); -bool FilterTypeInteger(const reflection::Field& field, flatbuffers::Table* table, PrivacyLevel privacy_level); -bool FilterTypeLong(const reflection::Field& field, flatbuffers::Table* table, PrivacyLevel privacy_level); -bool FilterTypeString(const reflection::Field& field, flatbuffers::Table* table, PrivacyLevel privacy_level); -bool FilterTypeStruct(const reflection::Field& field, flatbuffers::Table* table, PrivacyLevel privacy_level); +bool FilterTypeBool(const reflection::Field& field, flatbuffers::Table* table, + PrivacyLevel privacy_level); +bool FilterTypeFloat(const reflection::Field& field, flatbuffers::Table* table, + PrivacyLevel privacy_level); +bool FilterTypeInteger(const reflection::Field& field, flatbuffers::Table* table, + PrivacyLevel privacy_level); +bool FilterTypeLong(const reflection::Field& field, flatbuffers::Table* table, + PrivacyLevel privacy_level); +bool FilterTypeString(const reflection::Field& field, flatbuffers::Table* table, + PrivacyLevel privacy_level); +bool FilterTypeStruct(const reflection::Field& field, flatbuffers::Table* table, + PrivacyLevel privacy_level); inline std::string FlatbufferTypeText(const flatbuffers::BaseType& type) { switch (type) { diff --git a/system/gd/dumpsys/internal/filter_internal_test.cc b/system/gd/dumpsys/internal/filter_internal_test.cc index d3c7801812a..5fcce93141f 100644 --- a/system/gd/dumpsys/internal/filter_internal_test.cc +++ b/system/gd/dumpsys/internal/filter_internal_test.cc @@ -32,7 +32,7 @@ namespace testing { class DumpsysFilterInternalTest : public Test { - protected: +protected: void SetUp() override {} void TearDown() override {} @@ -52,15 +52,13 @@ class DumpsysFilterInternalTest : public Test { const reflection::Schema* schema_{nullptr}; flatbuffers::FlatBufferBuilder fb_builder_ = std::move(flatbuffers::FlatBufferBuilder(1024)); - private: +private: std::vector reflection_schema_; }; class DumpsysFilterInternalIntegerTest : public DumpsysFilterInternalTest { - protected: - void SetUp() override { - this->ParseReflectionSchema(integer_bfbs, integer_bfbs_len); - } +protected: + void SetUp() override { this->ParseReflectionSchema(integer_bfbs, integer_bfbs_len); } const testing::TestTableInteger* CreateInteger(int32_t value) { TestTableIntegerBuilder builder(fb_builder_); @@ -71,10 +69,8 @@ class DumpsysFilterInternalIntegerTest : public DumpsysFilterInternalTest { }; class DumpsysFilterInternalFloatTest : public DumpsysFilterInternalTest { - protected: - void SetUp() override { - this->ParseReflectionSchema(float_bfbs, float_bfbs_len); - } +protected: + void SetUp() override { this->ParseReflectionSchema(float_bfbs, float_bfbs_len); } const testing::TestTableFloat* CreateFloat(double value) { TestTableFloatBuilder builder(fb_builder_); @@ -85,10 +81,8 @@ class DumpsysFilterInternalFloatTest : public DumpsysFilterInternalTest { }; class DumpsysFilterInternalStringTest : public DumpsysFilterInternalTest { - protected: - void SetUp() override { - this->ParseReflectionSchema(string_bfbs, string_bfbs_len); - } +protected: + void SetUp() override { this->ParseReflectionSchema(string_bfbs, string_bfbs_len); } const testing::TestTableString* CreateString(std::string string) { auto test_string = fb_builder_.CreateString(string); @@ -100,10 +94,8 @@ class DumpsysFilterInternalStringTest : public DumpsysFilterInternalTest { }; class DumpsysFilterInternalStructTest : public DumpsysFilterInternalTest { - protected: - void SetUp() override { - this->ParseReflectionSchema(struct_bfbs, struct_bfbs_len); - } +protected: + void SetUp() override { this->ParseReflectionSchema(struct_bfbs, struct_bfbs_len); } flatbuffers::Offset CreateSubTable(int val) { TestSubTableBuilder builder(fb_builder_); @@ -131,7 +123,8 @@ TEST_F(DumpsysFilterInternalIntegerTest, filter_type_integer_any) { ASSERT_TRUE(object != nullptr); for (auto it = object->fields()->cbegin(); it != object->fields()->cend(); ++it) { - bluetooth::dumpsys::internal::FilterTypeInteger(**it, table, bluetooth::dumpsys::internal::PrivacyLevel::kAny); + bluetooth::dumpsys::internal::FilterTypeInteger( + **it, table, bluetooth::dumpsys::internal::PrivacyLevel::kAny); } ASSERT_EQ(123, test_table->test_int()); } @@ -147,7 +140,7 @@ TEST_F(DumpsysFilterInternalIntegerTest, filter_type_integer_anonymized) { for (auto it = object->fields()->cbegin(); it != object->fields()->cend(); ++it) { bluetooth::dumpsys::internal::FilterTypeInteger( - **it, table, bluetooth::dumpsys::internal::PrivacyLevel::kAnonymized); + **it, table, bluetooth::dumpsys::internal::PrivacyLevel::kAnonymized); } ASSERT_NE(123, test_table->test_int()); } @@ -162,7 +155,8 @@ TEST_F(DumpsysFilterInternalIntegerTest, filter_type_integer_opaque) { ASSERT_TRUE(object != nullptr); for (auto it = object->fields()->cbegin(); it != object->fields()->cend(); ++it) { - bluetooth::dumpsys::internal::FilterTypeInteger(**it, table, bluetooth::dumpsys::internal::PrivacyLevel::kOpaque); + bluetooth::dumpsys::internal::FilterTypeInteger( + **it, table, bluetooth::dumpsys::internal::PrivacyLevel::kOpaque); } ASSERT_EQ(0, test_table->test_int()); } @@ -177,7 +171,8 @@ TEST_F(DumpsysFilterInternalIntegerTest, filter_type_integer_privacy) { ASSERT_TRUE(object != nullptr); for (auto it = object->fields()->cbegin(); it != object->fields()->cend(); ++it) { - bluetooth::dumpsys::internal::FilterTypeInteger(**it, table, bluetooth::dumpsys::internal::PrivacyLevel::kPrivate); + bluetooth::dumpsys::internal::FilterTypeInteger( + **it, table, bluetooth::dumpsys::internal::PrivacyLevel::kPrivate); } ASSERT_EQ(0, test_table->test_int()); } @@ -192,7 +187,8 @@ TEST_F(DumpsysFilterInternalFloatTest, filter_type_float_any) { ASSERT_TRUE(object != nullptr); for (auto it = object->fields()->cbegin(); it != object->fields()->cend(); ++it) { - bluetooth::dumpsys::internal::FilterTypeFloat(**it, table, bluetooth::dumpsys::internal::PrivacyLevel::kAny); + bluetooth::dumpsys::internal::FilterTypeFloat(**it, table, + bluetooth::dumpsys::internal::PrivacyLevel::kAny); } ASSERT_FLOAT_EQ(1.23, test_table->test_float()); } @@ -207,7 +203,8 @@ TEST_F(DumpsysFilterInternalFloatTest, filter_type_float_anonymized) { ASSERT_TRUE(object != nullptr); for (auto it = object->fields()->cbegin(); it != object->fields()->cend(); ++it) { - bluetooth::dumpsys::internal::FilterTypeFloat(**it, table, bluetooth::dumpsys::internal::PrivacyLevel::kAnonymized); + bluetooth::dumpsys::internal::FilterTypeFloat( + **it, table, bluetooth::dumpsys::internal::PrivacyLevel::kAnonymized); } ASSERT_THAT(test_table->test_float(), Not(FloatEq(1.23))); } @@ -222,7 +219,8 @@ TEST_F(DumpsysFilterInternalFloatTest, filter_type_float_opaque) { ASSERT_TRUE(object != nullptr); for (auto it = object->fields()->cbegin(); it != object->fields()->cend(); ++it) { - bluetooth::dumpsys::internal::FilterTypeFloat(**it, table, bluetooth::dumpsys::internal::PrivacyLevel::kOpaque); + bluetooth::dumpsys::internal::FilterTypeFloat( + **it, table, bluetooth::dumpsys::internal::PrivacyLevel::kOpaque); } ASSERT_FLOAT_EQ(0.0, test_table->test_float()); } @@ -237,7 +235,8 @@ TEST_F(DumpsysFilterInternalFloatTest, filter_type_float_private) { ASSERT_TRUE(object != nullptr); for (auto it = object->fields()->cbegin(); it != object->fields()->cend(); ++it) { - bluetooth::dumpsys::internal::FilterTypeFloat(**it, table, bluetooth::dumpsys::internal::PrivacyLevel::kPrivate); + bluetooth::dumpsys::internal::FilterTypeFloat( + **it, table, bluetooth::dumpsys::internal::PrivacyLevel::kPrivate); } ASSERT_FLOAT_EQ(0.0, test_table->test_float()); } @@ -252,7 +251,8 @@ TEST_F(DumpsysFilterInternalStringTest, filter_type_string_any) { ASSERT_TRUE(object != nullptr); for (auto it = object->fields()->cbegin(); it != object->fields()->cend(); ++it) { - bluetooth::dumpsys::internal::FilterTypeString(**it, table, bluetooth::dumpsys::internal::PrivacyLevel::kAny); + bluetooth::dumpsys::internal::FilterTypeString( + **it, table, bluetooth::dumpsys::internal::PrivacyLevel::kAny); } ASSERT_STREQ("This is a string", test_table->test_string()->c_str()); } @@ -268,7 +268,7 @@ TEST_F(DumpsysFilterInternalStringTest, filter_type_string_anonymous) { for (auto it = object->fields()->cbegin(); it != object->fields()->cend(); ++it) { bluetooth::dumpsys::internal::FilterTypeString( - **it, table, bluetooth::dumpsys::internal::PrivacyLevel::kAnonymized); + **it, table, bluetooth::dumpsys::internal::PrivacyLevel::kAnonymized); } ASSERT_NE("This is a string", test_table->test_string()->c_str()); } @@ -284,14 +284,16 @@ TEST_F(DumpsysFilterInternalStringTest, filter_type_string_anonymous_small) { for (auto it = object->fields()->cbegin(); it != object->fields()->cend(); ++it) { bluetooth::dumpsys::internal::FilterTypeString( - **it, table, bluetooth::dumpsys::internal::PrivacyLevel::kAnonymized); + **it, table, bluetooth::dumpsys::internal::PrivacyLevel::kAnonymized); } ASSERT_NE("A", test_table->test_string()->c_str()); } TEST_F(DumpsysFilterInternalStringTest, filter_type_string_anonymous_large) { - const testing::TestTableString* test_table = CreateString("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"); - ASSERT_STREQ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", test_table->test_string()->c_str()); + const testing::TestTableString* test_table = + CreateString("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"); + ASSERT_STREQ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", + test_table->test_string()->c_str()); flatbuffers::Table* table = GetMutableTable(); @@ -300,9 +302,10 @@ TEST_F(DumpsysFilterInternalStringTest, filter_type_string_anonymous_large) { for (auto it = object->fields()->cbegin(); it != object->fields()->cend(); ++it) { bluetooth::dumpsys::internal::FilterTypeString( - **it, table, bluetooth::dumpsys::internal::PrivacyLevel::kAnonymized); + **it, table, bluetooth::dumpsys::internal::PrivacyLevel::kAnonymized); } - ASSERT_NE("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", test_table->test_string()->c_str()); + ASSERT_NE("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", + test_table->test_string()->c_str()); } TEST_F(DumpsysFilterInternalStringTest, filter_type_string_opaque) { @@ -315,7 +318,8 @@ TEST_F(DumpsysFilterInternalStringTest, filter_type_string_opaque) { ASSERT_TRUE(object != nullptr); for (auto it = object->fields()->cbegin(); it != object->fields()->cend(); ++it) { - bluetooth::dumpsys::internal::FilterTypeString(**it, table, bluetooth::dumpsys::internal::PrivacyLevel::kOpaque); + bluetooth::dumpsys::internal::FilterTypeString( + **it, table, bluetooth::dumpsys::internal::PrivacyLevel::kOpaque); } std::string opaque_expected(strlen("This is a string"), '*'); @@ -332,7 +336,8 @@ TEST_F(DumpsysFilterInternalStringTest, filter_type_string_private) { ASSERT_TRUE(object != nullptr); for (auto it = object->fields()->cbegin(); it != object->fields()->cend(); ++it) { - bluetooth::dumpsys::internal::FilterTypeString(**it, table, bluetooth::dumpsys::internal::PrivacyLevel::kPrivate); + bluetooth::dumpsys::internal::FilterTypeString( + **it, table, bluetooth::dumpsys::internal::PrivacyLevel::kPrivate); } ASSERT_EQ(nullptr, test_table->test_string()); } @@ -347,7 +352,8 @@ TEST_F(DumpsysFilterInternalStringTest, filter_type_string_private_small) { ASSERT_TRUE(object != nullptr); for (auto it = object->fields()->cbegin(); it != object->fields()->cend(); ++it) { - bluetooth::dumpsys::internal::FilterTypeString(**it, table, bluetooth::dumpsys::internal::PrivacyLevel::kPrivate); + bluetooth::dumpsys::internal::FilterTypeString( + **it, table, bluetooth::dumpsys::internal::PrivacyLevel::kPrivate); } ASSERT_EQ(nullptr, test_table->test_string()); } @@ -362,7 +368,8 @@ TEST_F(DumpsysFilterInternalStructTest, filter_type_struct_any) { ASSERT_TRUE(object != nullptr); for (auto it = object->fields()->cbegin(); it != object->fields()->cend(); ++it) { - bluetooth::dumpsys::internal::FilterTypeStruct(**it, table, bluetooth::dumpsys::internal::PrivacyLevel::kAny); + bluetooth::dumpsys::internal::FilterTypeStruct( + **it, table, bluetooth::dumpsys::internal::PrivacyLevel::kAny); } ASSERT_EQ(456, test_table->sub_table()->placeholder()); } @@ -378,7 +385,7 @@ TEST_F(DumpsysFilterInternalStructTest, filter_type_struct_anonymous) { for (auto it = object->fields()->cbegin(); it != object->fields()->cend(); ++it) { bluetooth::dumpsys::internal::FilterTypeStruct( - **it, table, bluetooth::dumpsys::internal::PrivacyLevel::kAnonymized); + **it, table, bluetooth::dumpsys::internal::PrivacyLevel::kAnonymized); } ASSERT_EQ(nullptr, test_table->sub_table()); } @@ -393,7 +400,8 @@ TEST_F(DumpsysFilterInternalStructTest, filter_type_struct_opaque) { ASSERT_TRUE(object != nullptr); for (auto it = object->fields()->cbegin(); it != object->fields()->cend(); ++it) { - bluetooth::dumpsys::internal::FilterTypeStruct(**it, table, bluetooth::dumpsys::internal::PrivacyLevel::kOpaque); + bluetooth::dumpsys::internal::FilterTypeStruct( + **it, table, bluetooth::dumpsys::internal::PrivacyLevel::kOpaque); } ASSERT_EQ(nullptr, test_table->sub_table()); } @@ -408,7 +416,8 @@ TEST_F(DumpsysFilterInternalStructTest, filter_type_struct_private) { ASSERT_TRUE(object != nullptr); for (auto it = object->fields()->cbegin(); it != object->fields()->cend(); ++it) { - bluetooth::dumpsys::internal::FilterTypeStruct(**it, table, bluetooth::dumpsys::internal::PrivacyLevel::kPrivate); + bluetooth::dumpsys::internal::FilterTypeStruct( + **it, table, bluetooth::dumpsys::internal::PrivacyLevel::kPrivate); } ASSERT_EQ(nullptr, test_table->sub_table()); } diff --git a/system/gd/dumpsys/internal/test_data/float_bfbs.h b/system/gd/dumpsys/internal/test_data/float_bfbs.h index 2c0313525c7..06488b95a8a 100644 --- a/system/gd/dumpsys/internal/test_data/float_bfbs.h +++ b/system/gd/dumpsys/internal/test_data/float_bfbs.h @@ -1,15 +1,18 @@ unsigned char float_bfbs[] = { - 0x18, 0x00, 0x00, 0x00, 0x42, 0x46, 0x42, 0x53, 0x10, 0x00, 0x1c, 0x00, 0x04, 0x00, 0x08, 0x00, 0x0c, 0x00, 0x10, - 0x00, 0x14, 0x00, 0x18, 0x00, 0x10, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x1c, 0x00, - 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x01, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x14, 0x00, 0x14, 0x00, 0x04, 0x00, 0x08, 0x00, 0x00, 0x00, 0x0c, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x14, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x14, 0x00, - 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, - 0x00, 0x00, 0x00, 0x2c, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0x74, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x2e, - 0x54, 0x65, 0x73, 0x74, 0x54, 0x61, 0x62, 0x6c, 0x65, 0x46, 0x6c, 0x6f, 0x61, 0x74, 0x00, 0x00, 0x0c, 0x00, 0x10, - 0x00, 0x08, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x06, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x24, 0x00, - 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x10, 0x00, 0x0c, 0x00, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x08, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0b, 0x01, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, - 0x74, 0x65, 0x73, 0x74, 0x5f, 0x66, 0x6c, 0x6f, 0x61, 0x74, 0x00, 0x00}; + 0x18, 0x00, 0x00, 0x00, 0x42, 0x46, 0x42, 0x53, 0x10, 0x00, 0x1c, 0x00, 0x04, 0x00, 0x08, + 0x00, 0x0c, 0x00, 0x10, 0x00, 0x14, 0x00, 0x18, 0x00, 0x10, 0x00, 0x00, 0x00, 0x30, 0x00, + 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x3c, + 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x01, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x14, 0x00, 0x14, 0x00, 0x04, 0x00, + 0x08, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x14, + 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, + 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, + 0x00, 0x2c, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0x74, 0x65, 0x73, 0x74, 0x69, 0x6e, + 0x67, 0x2e, 0x54, 0x65, 0x73, 0x74, 0x54, 0x61, 0x62, 0x6c, 0x65, 0x46, 0x6c, 0x6f, 0x61, + 0x74, 0x00, 0x00, 0x0c, 0x00, 0x10, 0x00, 0x08, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x06, 0x00, + 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x24, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, + 0x00, 0x10, 0x00, 0x0c, 0x00, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x08, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0b, 0x01, 0x00, 0x00, 0x00, 0x0a, + 0x00, 0x00, 0x00, 0x74, 0x65, 0x73, 0x74, 0x5f, 0x66, 0x6c, 0x6f, 0x61, 0x74, 0x00, 0x00}; unsigned int float_bfbs_len = 240; diff --git a/system/gd/dumpsys/internal/test_data/integer_bfbs.h b/system/gd/dumpsys/internal/test_data/integer_bfbs.h index 4e47e32f6cc..7f6ba61d7e8 100644 --- a/system/gd/dumpsys/internal/test_data/integer_bfbs.h +++ b/system/gd/dumpsys/internal/test_data/integer_bfbs.h @@ -1,15 +1,19 @@ unsigned char integer_bfbs[] = { - 0x18, 0x00, 0x00, 0x00, 0x42, 0x46, 0x42, 0x53, 0x10, 0x00, 0x1c, 0x00, 0x04, 0x00, 0x08, 0x00, 0x0c, 0x00, 0x10, - 0x00, 0x14, 0x00, 0x18, 0x00, 0x10, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x1c, 0x00, - 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x01, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x14, 0x00, 0x14, 0x00, 0x04, 0x00, 0x08, 0x00, 0x00, 0x00, 0x0c, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x14, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x14, 0x00, - 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, - 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x74, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x2e, - 0x54, 0x65, 0x73, 0x74, 0x54, 0x61, 0x62, 0x6c, 0x65, 0x49, 0x6e, 0x74, 0x65, 0x67, 0x65, 0x72, 0x00, 0x00, 0x00, - 0x00, 0x0c, 0x00, 0x10, 0x00, 0x08, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x06, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x04, 0x00, 0x24, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x10, 0x00, 0x0c, 0x00, 0x07, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x01, 0x00, 0x00, 0x00, - 0x08, 0x00, 0x00, 0x00, 0x74, 0x65, 0x73, 0x74, 0x5f, 0x69, 0x6e, 0x74, 0x00, 0x00, 0x00, 0x00}; + 0x18, 0x00, 0x00, 0x00, 0x42, 0x46, 0x42, 0x53, 0x10, 0x00, 0x1c, 0x00, 0x04, 0x00, 0x08, + 0x00, 0x0c, 0x00, 0x10, 0x00, 0x14, 0x00, 0x18, 0x00, 0x10, 0x00, 0x00, 0x00, 0x30, 0x00, + 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x3c, + 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x01, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x14, 0x00, 0x14, 0x00, 0x04, 0x00, + 0x08, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x14, + 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, + 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, + 0x00, 0x30, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x74, 0x65, 0x73, 0x74, 0x69, 0x6e, + 0x67, 0x2e, 0x54, 0x65, 0x73, 0x74, 0x54, 0x61, 0x62, 0x6c, 0x65, 0x49, 0x6e, 0x74, 0x65, + 0x67, 0x65, 0x72, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x10, 0x00, 0x08, 0x00, 0x0c, 0x00, + 0x00, 0x00, 0x06, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x24, 0x00, 0x00, + 0x00, 0x14, 0x00, 0x00, 0x00, 0x10, 0x00, 0x0c, 0x00, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x01, + 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x74, 0x65, 0x73, 0x74, 0x5f, 0x69, 0x6e, 0x74, + 0x00, 0x00, 0x00, 0x00}; unsigned int integer_bfbs_len = 244; diff --git a/system/gd/dumpsys/internal/test_data/string_bfbs.h b/system/gd/dumpsys/internal/test_data/string_bfbs.h index 9d614ef4646..1b241352cee 100644 --- a/system/gd/dumpsys/internal/test_data/string_bfbs.h +++ b/system/gd/dumpsys/internal/test_data/string_bfbs.h @@ -1,13 +1,16 @@ unsigned char string_bfbs[] = { - 0x18, 0x00, 0x00, 0x00, 0x42, 0x46, 0x42, 0x53, 0x10, 0x00, 0x1c, 0x00, 0x04, 0x00, 0x08, 0x00, 0x0c, 0x00, 0x10, - 0x00, 0x14, 0x00, 0x18, 0x00, 0x10, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x1c, 0x00, - 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x34, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x01, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x10, 0x00, 0x04, 0x00, 0x08, 0x00, 0x00, 0x00, 0x0c, - 0x00, 0x0c, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, - 0x00, 0x00, 0x2c, 0x00, 0x00, 0x00, 0x17, 0x00, 0x00, 0x00, 0x74, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x2e, 0x54, - 0x65, 0x73, 0x74, 0x54, 0x61, 0x62, 0x6c, 0x65, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x00, 0x0c, 0x00, 0x12, 0x00, - 0x08, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x06, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x18, 0x00, 0x00, - 0x00, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x08, 0x00, 0x07, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x0d, 0x0b, 0x00, 0x00, 0x00, 0x74, 0x65, 0x73, 0x74, 0x5f, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x00}; + 0x18, 0x00, 0x00, 0x00, 0x42, 0x46, 0x42, 0x53, 0x10, 0x00, 0x1c, 0x00, 0x04, 0x00, 0x08, + 0x00, 0x0c, 0x00, 0x10, 0x00, 0x14, 0x00, 0x18, 0x00, 0x10, 0x00, 0x00, 0x00, 0x30, 0x00, + 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x34, + 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x01, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x10, 0x00, 0x04, 0x00, + 0x08, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x08, + 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x00, 0x00, + 0x17, 0x00, 0x00, 0x00, 0x74, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x2e, 0x54, 0x65, 0x73, + 0x74, 0x54, 0x61, 0x62, 0x6c, 0x65, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x00, 0x0c, 0x00, + 0x12, 0x00, 0x08, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x06, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x04, 0x00, 0x18, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, + 0x08, 0x00, 0x07, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0d, 0x0b, 0x00, 0x00, + 0x00, 0x74, 0x65, 0x73, 0x74, 0x5f, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x00}; unsigned int string_bfbs_len = 208; diff --git a/system/gd/dumpsys/internal/test_data/struct_bfbs.h b/system/gd/dumpsys/internal/test_data/struct_bfbs.h index 9d955dc9642..5df51a98f4e 100644 --- a/system/gd/dumpsys/internal/test_data/struct_bfbs.h +++ b/system/gd/dumpsys/internal/test_data/struct_bfbs.h @@ -1,23 +1,29 @@ unsigned char struct_bfbs[] = { - 0x18, 0x00, 0x00, 0x00, 0x42, 0x46, 0x42, 0x53, 0x10, 0x00, 0x1c, 0x00, 0x04, 0x00, 0x08, 0x00, 0x0c, 0x00, 0x10, - 0x00, 0x14, 0x00, 0x18, 0x00, 0x10, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x1c, 0x00, - 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x02, 0x00, 0x00, 0x00, 0xb0, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x6c, 0xff, 0xff, 0xff, 0x18, 0x00, 0x00, - 0x00, 0x0c, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0xac, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x3c, 0x00, - 0x00, 0x00, 0x17, 0x00, 0x00, 0x00, 0x74, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x2e, 0x54, 0x65, 0x73, 0x74, 0x54, - 0x61, 0x62, 0x6c, 0x65, 0x53, 0x74, 0x72, 0x75, 0x63, 0x74, 0x00, 0x1c, 0x00, 0x10, 0x00, 0x08, 0x00, 0x0c, 0x00, - 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, - 0x00, 0x1c, 0x00, 0x00, 0x00, 0x00, 0x01, 0x04, 0x00, 0x28, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x10, 0x00, - 0x10, 0x00, 0x07, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 0x73, 0x75, 0x62, 0x5f, - 0x74, 0x61, 0x62, 0x6c, 0x65, 0x00, 0x00, 0x00, 0x14, 0x00, 0x14, 0x00, 0x04, 0x00, 0x08, 0x00, 0x00, 0x00, 0x0c, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x14, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x14, 0x00, - 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, - 0x00, 0x00, 0x00, 0x2c, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x74, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x2e, - 0x54, 0x65, 0x73, 0x74, 0x53, 0x75, 0x62, 0x54, 0x61, 0x62, 0x6c, 0x65, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x10, - 0x00, 0x08, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x06, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x24, 0x00, - 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x10, 0x00, 0x0c, 0x00, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x08, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x01, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, - 0x70, 0x6c, 0x61, 0x63, 0x65, 0x68, 0x6f, 0x6c, 0x64, 0x65, 0x72, 0x00}; + 0x18, 0x00, 0x00, 0x00, 0x42, 0x46, 0x42, 0x53, 0x10, 0x00, 0x1c, 0x00, 0x04, 0x00, 0x08, + 0x00, 0x0c, 0x00, 0x10, 0x00, 0x14, 0x00, 0x18, 0x00, 0x10, 0x00, 0x00, 0x00, 0x30, 0x00, + 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x2c, + 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x02, 0x00, 0x00, 0x00, 0xb0, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x6c, 0xff, + 0xff, 0xff, 0x18, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0xac, + 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x00, 0x17, 0x00, 0x00, 0x00, + 0x74, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x2e, 0x54, 0x65, 0x73, 0x74, 0x54, 0x61, 0x62, + 0x6c, 0x65, 0x53, 0x74, 0x72, 0x75, 0x63, 0x74, 0x00, 0x1c, 0x00, 0x10, 0x00, 0x08, 0x00, + 0x0c, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x00, 0x01, 0x04, 0x00, + 0x28, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x10, 0x00, 0x10, 0x00, 0x07, 0x00, 0x00, + 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 0x73, + 0x75, 0x62, 0x5f, 0x74, 0x61, 0x62, 0x6c, 0x65, 0x00, 0x00, 0x00, 0x14, 0x00, 0x14, 0x00, + 0x04, 0x00, 0x08, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, + 0x00, 0x14, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x01, 0x00, + 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, + 0x00, 0x00, 0x00, 0x2c, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x74, 0x65, 0x73, 0x74, + 0x69, 0x6e, 0x67, 0x2e, 0x54, 0x65, 0x73, 0x74, 0x53, 0x75, 0x62, 0x54, 0x61, 0x62, 0x6c, + 0x65, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x10, 0x00, 0x08, 0x00, 0x0c, 0x00, 0x00, 0x00, + 0x06, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x24, 0x00, 0x00, 0x00, 0x14, + 0x00, 0x00, 0x00, 0x10, 0x00, 0x0c, 0x00, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x08, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x01, 0x00, 0x00, + 0x00, 0x0b, 0x00, 0x00, 0x00, 0x70, 0x6c, 0x61, 0x63, 0x65, 0x68, 0x6f, 0x6c, 0x64, 0x65, + 0x72, 0x00}; unsigned int struct_bfbs_len = 392; diff --git a/system/gd/dumpsys/reflection_schema.cc b/system/gd/dumpsys/reflection_schema.cc index 6b2db369edf..3ab9fc2803a 100644 --- a/system/gd/dumpsys/reflection_schema.cc +++ b/system/gd/dumpsys/reflection_schema.cc @@ -29,7 +29,8 @@ using namespace bluetooth; dumpsys::ReflectionSchema::ReflectionSchema(const std::string& pre_bundled_schema) : pre_bundled_schema_(pre_bundled_schema) { - bundled_schema_ = flatbuffers::GetRoot(pre_bundled_schema_.data()); + bundled_schema_ = + flatbuffers::GetRoot(pre_bundled_schema_.data()); log::assert_that(bundled_schema_ != nullptr, "assert failed: bundled_schema_ != nullptr"); } @@ -37,9 +38,7 @@ int dumpsys::ReflectionSchema::GetNumberOfBundledSchemas() const { return bundled_schema_->map()->size(); } -std::string dumpsys::ReflectionSchema::GetTitle() const { - return bundled_schema_->title()->str(); -} +std::string dumpsys::ReflectionSchema::GetTitle() const { return bundled_schema_->title()->str(); } std::string dumpsys::ReflectionSchema::GetRootName() const { return bundled_schema_->root_name()->str(); @@ -49,12 +48,15 @@ const reflection::Schema* dumpsys::ReflectionSchema::GetRootReflectionSchema() c return FindInReflectionSchema(GetRootName()); } -const reflection::Schema* dumpsys::ReflectionSchema::FindInReflectionSchema(const std::string& name) const { - const flatbuffers::Vector>* map = bundled_schema_->map(); +const reflection::Schema* dumpsys::ReflectionSchema::FindInReflectionSchema( + const std::string& name) const { + const flatbuffers::Vector>* map = + bundled_schema_->map(); for (auto it = map->cbegin(); it != map->cend(); ++it) { if (it->name()->str() == name) { - flatbuffers::Verifier verifier(reinterpret_cast(it->data()->Data()), it->data()->size()); + flatbuffers::Verifier verifier(reinterpret_cast(it->data()->Data()), + it->data()->size()); if (!reflection::VerifySchemaBuffer(verifier)) { log::warn("Unable to verify schema buffer name:{}", name); return nullptr; @@ -66,21 +68,22 @@ const reflection::Schema* dumpsys::ReflectionSchema::FindInReflectionSchema(cons } void dumpsys::ReflectionSchema::PrintReflectionSchema() const { - const flatbuffers::Vector>* map = bundled_schema_->map(); - log::info( - "Bundled schema title:{} root_name:{}", - bundled_schema_->title()->c_str(), - bundled_schema_->root_name()->c_str()); + const flatbuffers::Vector>* map = + bundled_schema_->map(); + log::info("Bundled schema title:{} root_name:{}", bundled_schema_->title()->c_str(), + bundled_schema_->root_name()->c_str()); for (auto it = map->cbegin(); it != map->cend(); ++it) { log::info("schema:{}", it->name()->c_str()); } } bool dumpsys::ReflectionSchema::VerifyReflectionSchema() const { - const flatbuffers::Vector>* map = bundled_schema_->map(); + const flatbuffers::Vector>* map = + bundled_schema_->map(); for (auto it = map->cbegin(); it != map->cend(); ++it) { - flatbuffers::Verifier verifier(reinterpret_cast(it->data()->Data()), it->data()->size()); + flatbuffers::Verifier verifier(reinterpret_cast(it->data()->Data()), + it->data()->size()); if (!reflection::VerifySchemaBuffer(verifier)) { return false; } diff --git a/system/gd/dumpsys/reflection_schema.h b/system/gd/dumpsys/reflection_schema.h index c4496448b2b..7100a6b1b64 100644 --- a/system/gd/dumpsys/reflection_schema.h +++ b/system/gd/dumpsys/reflection_schema.h @@ -26,7 +26,7 @@ namespace bluetooth { namespace dumpsys { class ReflectionSchema { - public: +public: ReflectionSchema(const std::string& pre_bundled_schema); std::string GetTitle() const; @@ -38,7 +38,7 @@ class ReflectionSchema { const reflection::Schema* FindInReflectionSchema(const std::string& name) const; void PrintReflectionSchema() const; - private: +private: const BundledSchema* bundled_schema_; const std::string pre_bundled_schema_; }; diff --git a/system/gd/dumpsys/reflection_schema_test.cc b/system/gd/dumpsys/reflection_schema_test.cc index 99ec49c866f..727dd41ccf5 100644 --- a/system/gd/dumpsys/reflection_schema_test.cc +++ b/system/gd/dumpsys/reflection_schema_test.cc @@ -33,7 +33,7 @@ namespace testing { using namespace bluetooth; class ReflectionSchemaTest : public Test { - protected: +protected: void SetUp() override {} void TearDown() override {} diff --git a/system/gd/dumpsys/test_data/bar.h b/system/gd/dumpsys/test_data/bar.h index 0fa531b36ac..26af6c09e29 100644 --- a/system/gd/dumpsys/test_data/bar.h +++ b/system/gd/dumpsys/test_data/bar.h @@ -8,7 +8,7 @@ namespace testing { class BarTestDataClass : public DumpsysTestDataClass { - public: +public: TableAddFunction GetTable(flatbuffers::FlatBufferBuilder& /* fb_builder */) override { return [](DumpsysTestDataRootBuilder* /* builder */) {}; } diff --git a/system/gd/dumpsys/test_data/baz.h b/system/gd/dumpsys/test_data/baz.h index 7797085c43b..326f025bb98 100644 --- a/system/gd/dumpsys/test_data/baz.h +++ b/system/gd/dumpsys/test_data/baz.h @@ -6,7 +6,7 @@ namespace testing { class BazTestDataClass : public DumpsysTestDataClass { - public: +public: TableAddFunction GetTable(flatbuffers::FlatBufferBuilder& fb_builder) override { auto sub_name_private = fb_builder.CreateString("Baz Subtable Private"); auto sub_name_opaque = fb_builder.CreateString("Baz Subtable Opaque"); @@ -25,7 +25,9 @@ class BazTestDataClass : public DumpsysTestDataClass { builder.add_sub_table_any(any_subtable); auto baz_table = builder.Finish(); - return [baz_table](DumpsysTestDataRootBuilder* builder) { builder->add_baz_module_data(baz_table); }; + return [baz_table](DumpsysTestDataRootBuilder* builder) { + builder->add_baz_module_data(baz_table); + }; } }; diff --git a/system/gd/dumpsys/test_data/foo.h b/system/gd/dumpsys/test_data/foo.h index 01a7bd92beb..7d346657d42 100644 --- a/system/gd/dumpsys/test_data/foo.h +++ b/system/gd/dumpsys/test_data/foo.h @@ -6,7 +6,7 @@ namespace testing { class FooTestDataClass : public DumpsysTestDataClass { - public: +public: TableAddFunction GetTable(flatbuffers::FlatBufferBuilder& fb_builder) override { auto int_string = fb_builder.CreateString("123"); auto float_string = fb_builder.CreateString("123.456"); @@ -33,7 +33,9 @@ class FooTestDataClass : public DumpsysTestDataClass { auto foo_table = builder.Finish(); - return [foo_table](DumpsysTestDataRootBuilder* builder) { builder->add_foo_module_data(foo_table); }; + return [foo_table](DumpsysTestDataRootBuilder* builder) { + builder->add_foo_module_data(foo_table); + }; } }; diff --git a/system/gd/dumpsys/test_data/qux.h b/system/gd/dumpsys/test_data/qux.h index be89d3d51c6..1e70de38792 100644 --- a/system/gd/dumpsys/test_data/qux.h +++ b/system/gd/dumpsys/test_data/qux.h @@ -6,7 +6,7 @@ namespace testing { class QuxTestDataClass : public DumpsysTestDataClass { - public: +public: TableAddFunction GetTable(flatbuffers::FlatBufferBuilder& fb_builder) override { auto name = fb_builder.CreateString("Qux Module String"); @@ -19,7 +19,9 @@ class QuxTestDataClass : public DumpsysTestDataClass { auto qux_table = builder.Finish(); - return [qux_table](DumpsysTestDataRootBuilder* builder) { builder->add_qux_module_data(qux_table); }; + return [qux_table](DumpsysTestDataRootBuilder* builder) { + builder->add_qux_module_data(qux_table); + }; } }; diff --git a/system/gd/facade/facade_main.cc b/system/gd/facade/facade_main.cc index 4dc62727670..68709264e3b 100644 --- a/system/gd/facade/facade_main.cc +++ b/system/gd/facade/facade_main.cc @@ -46,9 +46,7 @@ using ::bluetooth::hal::HciHalHostRootcanalConfig; using ::bluetooth::os::Thread; using namespace bluetooth; -extern "C" const char* __asan_default_options() { - return "detect_container_overflow=0"; -} +extern "C" const char* __asan_default_options() { return "detect_container_overflow=0"; } namespace { ::bluetooth::facade::GrpcRootServer grpc_root_server; @@ -60,13 +58,14 @@ struct sigaction old_act = {}; void interrupt_handler(int signal_number) { if (!interrupted) { interrupted = true; - log::info( - "Stopping gRPC root server due to signal: {}[{}]", strsignal(signal_number), signal_number); + log::info("Stopping gRPC root server due to signal: {}[{}]", strsignal(signal_number), + signal_number); interrupt_promise.set_value(); } else { log::warn("Already interrupted by signal: {}[{}]", strsignal(signal_number), signal_number); } - if (old_act.sa_handler != nullptr && old_act.sa_handler != SIG_IGN && old_act.sa_handler != SIG_DFL) { + if (old_act.sa_handler != nullptr && old_act.sa_handler != SIG_IGN && + old_act.sa_handler != SIG_DFL) { log::info("Calling saved signal handler"); old_act.sa_handler(signal_number); } @@ -79,11 +78,8 @@ bool crash_callback(const void* crash_context, size_t crash_context_size, void* auto* ctx = static_cast(crash_context); tid = ctx->tid; int signal_number = ctx->siginfo.si_signo; - log::error( - "Process crashed, signal: {}[{}], tid: {}", - strsignal(signal_number), - signal_number, - ctx->tid); + log::error("Process crashed, signal: {}[{}], tid: {}", strsignal(signal_number), signal_number, + ctx->tid); } else { log::error("Process crashed, signal: unknown, tid: unknown"); } @@ -113,7 +109,8 @@ void thread_check_shutdown() { // The entry point for the binary with libbluetooth + facades int main(int argc, const char** argv) { - google_breakpad::MinidumpDescriptor descriptor(google_breakpad::MinidumpDescriptor::kMicrodumpOnConsole); + google_breakpad::MinidumpDescriptor descriptor( + google_breakpad::MinidumpDescriptor::kMicrodumpOnConsole); google_breakpad::ExceptionHandler eh(descriptor, nullptr, nullptr, nullptr, true, -1); eh.set_crash_handler(crash_callback); @@ -145,13 +142,12 @@ int main(int argc, const char** argv) { if (arg.find(arg_btsnoop_path) == 0) { auto btsnoop_path = arg.substr(arg_btsnoop_path.size()); ::bluetooth::os::ParameterProvider::OverrideSnoopLogFilePath(btsnoop_path); - log::assert_that( - ::bluetooth::os::SetSystemProperty( - ::bluetooth::hal::SnoopLogger::kBtSnoopLogModeProperty, - ::bluetooth::hal::SnoopLogger::kBtSnoopLogModeFull), - "assert failed: ::bluetooth::os::SetSystemProperty( " - "::bluetooth::hal::SnoopLogger::kBtSnoopLogModeProperty, " - "::bluetooth::hal::SnoopLogger::kBtSnoopLogModeFull)"); + log::assert_that(::bluetooth::os::SetSystemProperty( + ::bluetooth::hal::SnoopLogger::kBtSnoopLogModeProperty, + ::bluetooth::hal::SnoopLogger::kBtSnoopLogModeFull), + "assert failed: ::bluetooth::os::SetSystemProperty( " + "::bluetooth::hal::SnoopLogger::kBtSnoopLogModeProperty, " + "::bluetooth::hal::SnoopLogger::kBtSnoopLogModeFull)"); } if (arg.find(arg_btsnooz_path) == 0) { auto btsnooz_path = arg.substr(arg_btsnooz_path.size()); diff --git a/system/gd/facade/grpc_root_server.cc b/system/gd/facade/grpc_root_server.cc index 4aae129de5c..95b5184a943 100644 --- a/system/gd/facade/grpc_root_server.cc +++ b/system/gd/facade/grpc_root_server.cc @@ -45,13 +45,12 @@ using ::bluetooth::grpc::GrpcModule; using ::bluetooth::os::Thread; class RootFacadeService : public ::blueberry::facade::RootFacade::Service { - public: +public: explicit RootFacadeService(int grpc_port) : grpc_port_(grpc_port) {} - ::grpc::Status StartStack( - ::grpc::ServerContext* /* context */, - const ::blueberry::facade::StartStackRequest* request, - ::blueberry::facade::StartStackResponse* /* response */) override { + ::grpc::Status StartStack(::grpc::ServerContext* /* context */, + const ::blueberry::facade::StartStackRequest* request, + ::blueberry::facade::StartStackResponse* /* response */) override { if (is_running_) { return ::grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, "stack is running"); } @@ -110,16 +109,16 @@ class RootFacadeService : public ::blueberry::facade::RootFacade::Service { GrpcModule* grpc_module = stack_manager_.GetInstance(); grpc_module->StartServer("0.0.0.0", grpc_port_); - grpc_loop_thread_ = std::make_unique([grpc_module] { grpc_module->RunGrpcLoop(); }); + grpc_loop_thread_ = + std::make_unique([grpc_module] { grpc_module->RunGrpcLoop(); }); is_running_ = true; return ::grpc::Status::OK; } - ::grpc::Status StopStack( - ::grpc::ServerContext* /* context */, - const ::blueberry::facade::StopStackRequest* /* request */, - ::blueberry::facade::StopStackResponse* /* response */) override { + ::grpc::Status StopStack(::grpc::ServerContext* /* context */, + const ::blueberry::facade::StopStackRequest* /* request */, + ::blueberry::facade::StopStackResponse* /* response */) override { if (!is_running_) { return ::grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, "stack is not running"); } @@ -134,7 +133,7 @@ class RootFacadeService : public ::blueberry::facade::RootFacade::Service { return ::grpc::Status::OK; } - private: +private: std::unique_ptr stack_thread_ = nullptr; bool is_running_ = false; std::unique_ptr grpc_loop_thread_ = nullptr; @@ -152,7 +151,8 @@ GrpcRootServer::GrpcRootServer() : pimpl_(new impl()) {} GrpcRootServer::~GrpcRootServer() = default; -void GrpcRootServer::StartServer(const std::string& address, int grpc_root_server_port, int grpc_port) { +void GrpcRootServer::StartServer(const std::string& address, int grpc_root_server_port, + int grpc_port) { log::assert_that(!pimpl_->started_, "assert failed: !pimpl_->started_"); pimpl_->started_ = true; diff --git a/system/gd/facade/grpc_root_server.h b/system/gd/facade/grpc_root_server.h index 2b310e2054b..062ddcf1502 100644 --- a/system/gd/facade/grpc_root_server.h +++ b/system/gd/facade/grpc_root_server.h @@ -25,7 +25,7 @@ namespace bluetooth { namespace facade { class GrpcRootServer { - public: +public: GrpcRootServer(); ~GrpcRootServer(); @@ -35,7 +35,7 @@ class GrpcRootServer { void RunGrpcLoop(); - private: +private: struct impl; std::unique_ptr pimpl_; }; diff --git a/system/gd/facade/read_only_property_server.cc b/system/gd/facade/read_only_property_server.cc index 36ddd3903fe..d8a646d774d 100644 --- a/system/gd/facade/read_only_property_server.cc +++ b/system/gd/facade/read_only_property_server.cc @@ -22,18 +22,17 @@ namespace bluetooth { namespace facade { class ReadOnlyPropertyService : public blueberry::facade::ReadOnlyProperty::Service { - public: +public: ReadOnlyPropertyService(hci::Controller* controller) : controller_(controller) {} - ::grpc::Status ReadLocalAddress( - ::grpc::ServerContext* /* context */, - const ::google::protobuf::Empty* /* request */, - ::blueberry::facade::BluetoothAddress* response) override { + ::grpc::Status ReadLocalAddress(::grpc::ServerContext* /* context */, + const ::google::protobuf::Empty* /* request */, + ::blueberry::facade::BluetoothAddress* response) override { auto address = controller_->GetMacAddress().ToString(); response->set_address(address); return ::grpc::Status::OK; } - private: +private: hci::Controller* controller_; }; @@ -49,12 +48,10 @@ void ReadOnlyPropertyServerModule::Stop() { service_.reset(); GrpcFacadeModule::Stop(); } -::grpc::Service* ReadOnlyPropertyServerModule::GetService() const { - return service_.get(); -} +::grpc::Service* ReadOnlyPropertyServerModule::GetService() const { return service_.get(); } const ModuleFactory ReadOnlyPropertyServerModule::Factory = - ::bluetooth::ModuleFactory([]() { return new ReadOnlyPropertyServerModule(); }); + ::bluetooth::ModuleFactory([]() { return new ReadOnlyPropertyServerModule(); }); } // namespace facade } // namespace bluetooth diff --git a/system/gd/facade/read_only_property_server.h b/system/gd/facade/read_only_property_server.h index 4345cf1aa11..a71d5fbd93e 100644 --- a/system/gd/facade/read_only_property_server.h +++ b/system/gd/facade/read_only_property_server.h @@ -29,7 +29,7 @@ namespace facade { class ReadOnlyPropertyService; class ReadOnlyPropertyServerModule : public ::bluetooth::grpc::GrpcFacadeModule { - public: +public: static const ModuleFactory Factory; void ListDependencies(ModuleList* list) const override; @@ -37,7 +37,7 @@ class ReadOnlyPropertyServerModule : public ::bluetooth::grpc::GrpcFacadeModule void Stop() override; ::grpc::Service* GetService() const override; - private: +private: std::unique_ptr service_; }; diff --git a/system/gd/fuzz/helpers.cc b/system/gd/fuzz/helpers.cc index 29e53056ca2..a03f04aab85 100644 --- a/system/gd/fuzz/helpers.cc +++ b/system/gd/fuzz/helpers.cc @@ -22,8 +22,8 @@ namespace bluetooth { namespace fuzz { // cribbed from https://github.com/google/fuzzing/blob/master/docs/split-inputs.md#magic-separator -std::vector> SplitInput( - const uint8_t* data, size_t size, const uint8_t* separator, size_t separatorSize) { +std::vector> SplitInput(const uint8_t* data, size_t size, + const uint8_t* separator, size_t separatorSize) { std::vector> result; assert(separatorSize > 0); auto beg = data; diff --git a/system/gd/fuzz/helpers.h b/system/gd/fuzz/helpers.h index f4ca1627307..7b90ff82bc8 100644 --- a/system/gd/fuzz/helpers.h +++ b/system/gd/fuzz/helpers.h @@ -26,8 +26,8 @@ namespace bluetooth { namespace fuzz { -std::vector> SplitInput( - const uint8_t* data, size_t size, const uint8_t* separator, size_t separatorSize); +std::vector> SplitInput(const uint8_t* data, size_t size, + const uint8_t* separator, size_t separatorSize); std::vector GetArbitraryBytes(FuzzedDataProvider* fdp); @@ -38,7 +38,8 @@ std::vector GetArbitraryBytes(FuzzedDataProvider* fdp); } template -void InvokeIfValid(common::ContextualOnceCallback callback, std::vector data) { +void InvokeIfValid(common::ContextualOnceCallback callback, + std::vector data) { auto packet = TView::FromBytes(data); if (!packet.IsValid()) { return; diff --git a/system/gd/grpc/grpc_event_queue.h b/system/gd/grpc/grpc_event_queue.h index 88e6c433774..c181573ab1d 100644 --- a/system/gd/grpc/grpc_event_queue.h +++ b/system/gd/grpc/grpc_event_queue.h @@ -32,17 +32,18 @@ namespace grpc { template class GrpcEventQueue { - public: +public: /** * Create a GrpcEventQueue that can be used to shuffle event from one thread to another * @param log_name */ - explicit GrpcEventQueue(std::string log_name) : log_name_(std::move(log_name)){}; + explicit GrpcEventQueue(std::string log_name) : log_name_(std::move(log_name)) {} /** * Run the event loop and blocks until client cancels the stream request - * Event queue will be cleared before entering the loop. Hence, only events occurred after gRPC request will be - * delivered to the user. Hence user is advised to run the loop before generating pending events. + * Event queue will be cleared before entering the loop. Hence, only events occurred after gRPC + * request will be delivered to the user. Hence user is advised to run the loop before generating + * pending events. * * @param context client context * @param writer output writer @@ -76,7 +77,7 @@ class GrpcEventQueue { pending_events_.push(std::move(event)); } - private: +private: std::string log_name_; std::atomic running_{true}; common::BlockingQueue pending_events_; diff --git a/system/gd/grpc/grpc_module.cc b/system/gd/grpc/grpc_module.cc index 4183c1609ce..93979f533e1 100644 --- a/system/gd/grpc/grpc_module.cc +++ b/system/gd/grpc/grpc_module.cc @@ -28,13 +28,9 @@ namespace grpc { void GrpcModule::ListDependencies(ModuleList* /* list */) const {} -void GrpcModule::Start() { - log::assert_that(!started_, "assert failed: !started_"); -} +void GrpcModule::Start() { log::assert_that(!started_, "assert failed: !started_"); } -void GrpcModule::Stop() { - log::assert_that(!started_, "assert failed: !started_"); -} +void GrpcModule::Stop() { log::assert_that(!started_, "assert failed: !started_"); } void GrpcModule::StartServer(const std::string& address, int port) { log::assert_that(!started_, "assert failed: !started_"); @@ -101,27 +97,18 @@ void GrpcModule::RunGrpcLoop() { } } -std::string GrpcModule::ToString() const { - return "Grpc Module"; -} +std::string GrpcModule::ToString() const { return "Grpc Module"; } -const ::bluetooth::ModuleFactory GrpcModule::Factory = ::bluetooth::ModuleFactory([]() { return new GrpcModule(); }); +const ::bluetooth::ModuleFactory GrpcModule::Factory = + ::bluetooth::ModuleFactory([]() { return new GrpcModule(); }); -void GrpcFacadeModule::ListDependencies(ModuleList* list) const { - list->add(); -} +void GrpcFacadeModule::ListDependencies(ModuleList* list) const { list->add(); } -void GrpcFacadeModule::Start() { - GetDependency()->Register(this); -} +void GrpcFacadeModule::Start() { GetDependency()->Register(this); } -void GrpcFacadeModule::Stop() { - GetDependency()->Unregister(this); -} +void GrpcFacadeModule::Stop() { GetDependency()->Unregister(this); } -std::string GrpcFacadeModule::ToString() const { - return "Grpc Facade Module"; -} +std::string GrpcFacadeModule::ToString() const { return "Grpc Facade Module"; } } // namespace grpc } // namespace bluetooth diff --git a/system/gd/grpc/grpc_module.h b/system/gd/grpc/grpc_module.h index 3e47df715ca..e1b8158b82e 100644 --- a/system/gd/grpc/grpc_module.h +++ b/system/gd/grpc/grpc_module.h @@ -28,7 +28,7 @@ namespace grpc { class GrpcFacadeModule; class GrpcModule : public ::bluetooth::Module { - public: +public: static const ModuleFactory Factory; void StartServer(const std::string& address, int port); @@ -42,7 +42,7 @@ class GrpcModule : public ::bluetooth::Module { // Blocks for incoming gRPC requests void RunGrpcLoop(); - protected: +protected: void ListDependencies(ModuleList* list) const override; void Start() override; @@ -51,7 +51,7 @@ class GrpcModule : public ::bluetooth::Module { std::string ToString() const override; - private: +private: bool started_; std::unique_ptr<::grpc::Server> server_ = nullptr; std::unique_ptr<::grpc::ServerCompletionQueue> completion_queue_ = nullptr; @@ -61,7 +61,7 @@ class GrpcModule : public ::bluetooth::Module { class GrpcFacadeModule : public ::bluetooth::Module { friend GrpcModule; - protected: +protected: void ListDependencies(ModuleList* list) const override; void Start() override; diff --git a/system/gd/hal/facade.cc b/system/gd/hal/facade.cc index 1182e494647..9cfefd7a772 100644 --- a/system/gd/hal/facade.cc +++ b/system/gd/hal/facade.cc @@ -32,19 +32,16 @@ namespace hal { class HciHalFacadeService : public blueberry::facade::hal::HciHalFacade::Service, public ::bluetooth::hal::HciHalCallbacks { - public: +public: explicit HciHalFacadeService(HciHal* hal) : hal_(hal) { hal->registerIncomingPacketCallback(this); } - ~HciHalFacadeService() { - hal_->unregisterIncomingPacketCallback(); - } + ~HciHalFacadeService() { hal_->unregisterIncomingPacketCallback(); } - ::grpc::Status SendCommand( - ::grpc::ServerContext* /* context */, - const ::blueberry::facade::Data* request, - ::google::protobuf::Empty* /* response */) override { + ::grpc::Status SendCommand(::grpc::ServerContext* /* context */, + const ::blueberry::facade::Data* request, + ::google::protobuf::Empty* /* response */) override { std::unique_lock lock(mutex_); can_send_hci_command_ = false; std::string req_string = request->payload(); @@ -55,51 +52,45 @@ class HciHalFacadeService : public blueberry::facade::hal::HciHalFacade::Service return ::grpc::Status::OK; } - ::grpc::Status SendAcl( - ::grpc::ServerContext* /* context */, - const ::blueberry::facade::Data* request, - ::google::protobuf::Empty* /* response */) override { + ::grpc::Status SendAcl(::grpc::ServerContext* /* context */, + const ::blueberry::facade::Data* request, + ::google::protobuf::Empty* /* response */) override { std::string req_string = request->payload(); hal_->sendAclData(std::vector(req_string.begin(), req_string.end())); return ::grpc::Status::OK; } - ::grpc::Status SendSco( - ::grpc::ServerContext* /* context */, - const ::blueberry::facade::Data* request, - ::google::protobuf::Empty* /* response */) override { + ::grpc::Status SendSco(::grpc::ServerContext* /* context */, + const ::blueberry::facade::Data* request, + ::google::protobuf::Empty* /* response */) override { std::string req_string = request->payload(); hal_->sendScoData(std::vector(req_string.begin(), req_string.end())); return ::grpc::Status::OK; } - ::grpc::Status StreamEvents( - ::grpc::ServerContext* context, - const ::google::protobuf::Empty* /* request */, - ::grpc::ServerWriter<::blueberry::facade::Data>* writer) override { + ::grpc::Status StreamEvents(::grpc::ServerContext* context, + const ::google::protobuf::Empty* /* request */, + ::grpc::ServerWriter<::blueberry::facade::Data>* writer) override { return pending_hci_events_.RunLoop(context, writer); - }; + } - ::grpc::Status StreamAcl( - ::grpc::ServerContext* context, - const ::google::protobuf::Empty* /* request */, - ::grpc::ServerWriter<::blueberry::facade::Data>* writer) override { + ::grpc::Status StreamAcl(::grpc::ServerContext* context, + const ::google::protobuf::Empty* /* request */, + ::grpc::ServerWriter<::blueberry::facade::Data>* writer) override { return pending_acl_events_.RunLoop(context, writer); - }; + } - ::grpc::Status StreamSco( - ::grpc::ServerContext* context, - const ::google::protobuf::Empty* /* request */, - ::grpc::ServerWriter<::blueberry::facade::Data>* writer) override { + ::grpc::Status StreamSco(::grpc::ServerContext* context, + const ::google::protobuf::Empty* /* request */, + ::grpc::ServerWriter<::blueberry::facade::Data>* writer) override { return pending_sco_events_.RunLoop(context, writer); - }; + } - ::grpc::Status StreamIso( - ::grpc::ServerContext* context, - const ::google::protobuf::Empty* /* request */, - ::grpc::ServerWriter<::blueberry::facade::Data>* writer) override { + ::grpc::Status StreamIso(::grpc::ServerContext* context, + const ::google::protobuf::Empty* /* request */, + ::grpc::ServerWriter<::blueberry::facade::Data>* writer) override { return pending_iso_events_.RunLoop(context, writer); - }; + } void hciEventReceived(bluetooth::hal::HciPacket event) override { { @@ -129,7 +120,7 @@ class HciHalFacadeService : public blueberry::facade::hal::HciHalFacade::Service pending_iso_events_.OnIncomingEvent(std::move(response)); } - private: +private: HciHal* hal_; bool can_send_hci_command_ = true; mutable std::mutex mutex_; @@ -155,11 +146,10 @@ void HciHalFacadeModule::Stop() { ::bluetooth::grpc::GrpcFacadeModule::Stop(); } -::grpc::Service* HciHalFacadeModule::GetService() const { - return service_; -} +::grpc::Service* HciHalFacadeModule::GetService() const { return service_; } -const ModuleFactory HciHalFacadeModule::Factory = ::bluetooth::ModuleFactory([]() { return new HciHalFacadeModule(); }); +const ModuleFactory HciHalFacadeModule::Factory = + ::bluetooth::ModuleFactory([]() { return new HciHalFacadeModule(); }); } // namespace hal } // namespace bluetooth diff --git a/system/gd/hal/facade.h b/system/gd/hal/facade.h index 7b4b1ad34a5..edf785631ac 100644 --- a/system/gd/hal/facade.h +++ b/system/gd/hal/facade.h @@ -30,7 +30,7 @@ namespace hal { class HciHalFacadeService; class HciHalFacadeModule : public ::bluetooth::grpc::GrpcFacadeModule { - public: +public: static const ModuleFactory Factory; void ListDependencies(ModuleList* list) const override; @@ -40,7 +40,7 @@ class HciHalFacadeModule : public ::bluetooth::grpc::GrpcFacadeModule { ::grpc::Service* GetService() const override; - private: +private: HciHalFacadeService* service_; }; diff --git a/system/gd/hal/fuzz/fuzz_hci_hal.cc b/system/gd/hal/fuzz/fuzz_hci_hal.cc index cc41a178292..a0db9f01d98 100644 --- a/system/gd/hal/fuzz/fuzz_hci_hal.cc +++ b/system/gd/hal/fuzz/fuzz_hci_hal.cc @@ -28,9 +28,7 @@ void FuzzHciHal::registerIncomingPacketCallback(HciHalCallbacks* callbacks) { callbacks_ = callbacks; } -void FuzzHciHal::unregisterIncomingPacketCallback() { - callbacks_ = nullptr; -} +void FuzzHciHal::unregisterIncomingPacketCallback() { callbacks_ = nullptr; } void FuzzHciHal::injectArbitrary(FuzzedDataProvider& fdp) { const uint8_t action = fdp.ConsumeIntegralInRange(0, 4); diff --git a/system/gd/hal/fuzz/fuzz_hci_hal.h b/system/gd/hal/fuzz/fuzz_hci_hal.h index 845607ba36c..07a3593e7cd 100644 --- a/system/gd/hal/fuzz/fuzz_hci_hal.h +++ b/system/gd/hal/fuzz/fuzz_hci_hal.h @@ -25,7 +25,7 @@ namespace hal { namespace fuzz { class FuzzHciHal : public HciHal { - public: +public: void registerIncomingPacketCallback(HciHalCallbacks* callbacks) override; void unregisterIncomingPacketCallback() override; @@ -36,18 +36,16 @@ class FuzzHciHal : public HciHal { void injectArbitrary(FuzzedDataProvider& fdp); - std::string ToString() const override { - return "HciHalFuzz"; - } + std::string ToString() const override { return "HciHalFuzz"; } static const ModuleFactory Factory; - protected: +protected: void ListDependencies(ModuleList* /* list */) const override {} void Start() override {} void Stop() override {} - private: +private: void injectAclData(std::vector data); void injectHciEvent(std::vector data); void injectScoData(std::vector data); diff --git a/system/gd/hal/hci_backend.h b/system/gd/hal/hci_backend.h index 34d4cf35341..5c107ef8a1f 100644 --- a/system/gd/hal/hci_backend.h +++ b/system/gd/hal/hci_backend.h @@ -29,7 +29,7 @@ namespace bluetooth::hal { class HciBackendCallbacks { - public: +public: virtual ~HciBackendCallbacks() = default; virtual void initializationComplete(void) = 0; virtual void hciEventReceived(const std::vector&) = 0; @@ -39,7 +39,7 @@ class HciBackendCallbacks { }; class HciBackend { - public: +public: static std::shared_ptr CreateAidl(); static std::shared_ptr CreateHidl(::bluetooth::os::Handler*); diff --git a/system/gd/hal/hci_backend_aidl.cc b/system/gd/hal/hci_backend_aidl.cc index 3f3e3d98245..04bd67f992e 100644 --- a/system/gd/hal/hci_backend_aidl.cc +++ b/system/gd/hal/hci_backend_aidl.cc @@ -26,7 +26,7 @@ namespace bluetooth::hal { class AidlHciCallbacks : public ::aidl::android::hardware::bluetooth::BnBluetoothHciCallbacks { - public: +public: AidlHciCallbacks(std::shared_ptr callbacks) : callbacks_(callbacks) {} using AidlStatus = ::aidl::android::hardware::bluetooth::Status; @@ -56,34 +56,34 @@ class AidlHciCallbacks : public ::aidl::android::hardware::bluetooth::BnBluetoot return ::ndk::ScopedAStatus::ok(); } - private: +private: std::shared_ptr callbacks_; }; class AidlHci : public HciBackend { - public: +public: AidlHci(const char* service_name) { ::ndk::SpAIBinder binder(AServiceManager_waitForService(service_name)); hci_ = aidl::android::hardware::bluetooth::IBluetoothHci::fromBinder(binder); log::assert_that(hci_ != nullptr, "Failed to retrieve AIDL interface."); death_recipient_ = - ::ndk::ScopedAIBinder_DeathRecipient(AIBinder_DeathRecipient_new([](void* /* cookie*/) { - log::error("The Bluetooth HAL service died. Dumping logs and crashing in 1 second."); - common::StopWatch::DumpStopWatchLog(); - // At shutdown, sometimes the HAL service gets killed before Bluetooth. - std::this_thread::sleep_for(std::chrono::seconds(1)); - log::fatal("The Bluetooth HAL died."); - })); + ::ndk::ScopedAIBinder_DeathRecipient(AIBinder_DeathRecipient_new([](void* /* cookie*/) { + log::error("The Bluetooth HAL service died. Dumping logs and crashing in 1 second."); + common::StopWatch::DumpStopWatchLog(); + // At shutdown, sometimes the HAL service gets killed before Bluetooth. + std::this_thread::sleep_for(std::chrono::seconds(1)); + log::fatal("The Bluetooth HAL died."); + })); auto death_link = AIBinder_linkToDeath(hci_->asBinder().get(), death_recipient_.get(), this); - log::assert_that( - death_link == STATUS_OK, "Unable to set the death recipient for the Bluetooth HAL"); + log::assert_that(death_link == STATUS_OK, + "Unable to set the death recipient for the Bluetooth HAL"); } ~AidlHci() { auto death_unlink = - AIBinder_unlinkToDeath(hci_->asBinder().get(), death_recipient_.get(), this); + AIBinder_unlinkToDeath(hci_->asBinder().get(), death_recipient_.get(), this); if (death_unlink != STATUS_OK) { log::error("Error unlinking death recipient from the Bluetooth HAL"); } @@ -102,19 +102,13 @@ class AidlHci : public HciBackend { hci_->sendHciCommand(command); } - void sendAclData(const std::vector& packet) override { - hci_->sendAclData(packet); - } + void sendAclData(const std::vector& packet) override { hci_->sendAclData(packet); } - void sendScoData(const std::vector& packet) override { - hci_->sendScoData(packet); - } + void sendScoData(const std::vector& packet) override { hci_->sendScoData(packet); } - void sendIsoData(const std::vector& packet) override { - hci_->sendIsoData(packet); - } + void sendIsoData(const std::vector& packet) override { hci_->sendIsoData(packet); } - private: +private: ::ndk::ScopedAIBinder_DeathRecipient death_recipient_; std::shared_ptr hci_; std::shared_ptr hci_callbacks_; @@ -122,10 +116,11 @@ class AidlHci : public HciBackend { std::shared_ptr HciBackend::CreateAidl() { static constexpr char kBluetoothAidlHalServiceName[] = - "android.hardware.bluetooth.IBluetoothHci/default"; + "android.hardware.bluetooth.IBluetoothHci/default"; - if (AServiceManager_isDeclared(kBluetoothAidlHalServiceName)) + if (AServiceManager_isDeclared(kBluetoothAidlHalServiceName)) { return std::make_shared(kBluetoothAidlHalServiceName); + } return std::shared_ptr(); } diff --git a/system/gd/hal/hci_backend_hidl.cc b/system/gd/hal/hci_backend_hidl.cc index fd46841d4e2..bb70912a067 100644 --- a/system/gd/hal/hci_backend_hidl.cc +++ b/system/gd/hal/hci_backend_hidl.cc @@ -41,7 +41,7 @@ using IBluetoothHciCallbacks_1_1 = ::android::hardware::bluetooth::V1_1::IBlueto namespace bluetooth::hal { class HidlHciCallbacks : public IBluetoothHciCallbacks_1_1 { - public: +public: HidlHciCallbacks(std::shared_ptr callbacks) : callbacks_(callbacks) {} using HidlStatus = ::android::hardware::bluetooth::V1_0::Status; @@ -71,15 +71,15 @@ class HidlHciCallbacks : public IBluetoothHciCallbacks_1_1 { return Void(); } - private: +private: std::shared_ptr callbacks_; }; class HidlHci : public HciBackend { class DeathRecipient : public ::android::hardware::hidl_death_recipient { - public: - virtual void serviceDied( - uint64_t /*cookie*/, const android::wp<::android::hidl::base::V1_0::IBase>& /*who*/) { + public: + virtual void serviceDied(uint64_t /*cookie*/, + const android::wp<::android::hidl::base::V1_0::IBase>& /*who*/) { log::error("The Bluetooth HAL service died. Dumping logs and crashing in 1 second."); common::StopWatch::DumpStopWatchLog(); // At shutdown, sometimes the HAL service gets killed before Bluetooth. @@ -88,35 +88,38 @@ class HidlHci : public HciBackend { } }; - public: +public: HidlHci(Handler* module_handler) { log::info("Trying to find a HIDL interface"); auto get_service_alarm = new os::Alarm(module_handler); - get_service_alarm->Schedule( - BindOnce([] { - const std::string kBoardProperty = "ro.product.board"; - const std::string kCuttlefishBoard = "cutf"; - auto board_name = os::GetSystemProperty(kBoardProperty); - bool emulator = board_name.has_value() && board_name.value() == kCuttlefishBoard; - if (emulator) { - log::error("board_name: {}", board_name.value()); - log::error( - "Unable to get a Bluetooth service after 500ms, start the HAL before starting " - "Bluetooth"); - return; - } - log::fatal( - "Unable to get a Bluetooth service after 500ms, start the HAL before starting " - "Bluetooth"); - }), - std::chrono::milliseconds(500)); + get_service_alarm->Schedule(BindOnce([] { + const std::string kBoardProperty = "ro.product.board"; + const std::string kCuttlefishBoard = "cutf"; + auto board_name = os::GetSystemProperty(kBoardProperty); + bool emulator = board_name.has_value() && + board_name.value() == kCuttlefishBoard; + if (emulator) { + log::error("board_name: {}", board_name.value()); + log::error( + "Unable to get a Bluetooth service after 500ms, start " + "the HAL before starting " + "Bluetooth"); + return; + } + log::fatal( + "Unable to get a Bluetooth service after 500ms, start " + "the HAL before starting " + "Bluetooth"); + }), + std::chrono::milliseconds(500)); hci_1_1_ = IBluetoothHci_1_1::getService(); - if (hci_1_1_) + if (hci_1_1_) { hci_ = hci_1_1_; - else + } else { hci_ = IBluetoothHci_1_0::getService(); + } get_service_alarm->Cancel(); delete get_service_alarm; @@ -144,23 +147,20 @@ class HidlHci : public HciBackend { void initialize(std::shared_ptr callbacks) override { hci_callbacks_ = new HidlHciCallbacks(callbacks); - if (hci_1_1_ != nullptr) + if (hci_1_1_ != nullptr) { hci_1_1_->initialize_1_1(hci_callbacks_); - else + } else { hci_->initialize(hci_callbacks_); + } } void sendHciCommand(const std::vector& command) override { hci_->sendHciCommand(command); } - void sendAclData(const std::vector& packet) override { - hci_->sendAclData(packet); - } + void sendAclData(const std::vector& packet) override { hci_->sendAclData(packet); } - void sendScoData(const std::vector& packet) override { - hci_->sendScoData(packet); - } + void sendScoData(const std::vector& packet) override { hci_->sendScoData(packet); } void sendIsoData(const std::vector& packet) override { if (hci_1_1_ == nullptr) { @@ -170,7 +170,7 @@ class HidlHci : public HciBackend { hci_1_1_->sendIsoData(packet); } - private: +private: android::sp death_recipient_; android::sp hci_callbacks_; android::sp hci_; diff --git a/system/gd/hal/hci_hal.h b/system/gd/hal/hci_hal.h index 318ce63560a..705b1774241 100644 --- a/system/gd/hal/hci_hal.h +++ b/system/gd/hal/hci_hal.h @@ -27,12 +27,12 @@ using HciPacket = std::vector; enum class Status : int32_t { SUCCESS, TRANSPORT_ERROR, INITIALIZATION_ERROR, UNKNOWN }; -// Mirrors hardware/interfaces/bluetooth/1.0/IBluetoothHciCallbacks.hal in Android, but moved initializationComplete -// callback to BluetoothInitializationCompleteCallback +// Mirrors hardware/interfaces/bluetooth/1.0/IBluetoothHciCallbacks.hal in Android, but moved +// initializationComplete callback to BluetoothInitializationCompleteCallback // The interface from the Bluetooth Controller to the stack class HciHalCallbacks { - public: +public: virtual ~HciHalCallbacks() = default; // This function is invoked when an HCI event is received from the @@ -62,7 +62,7 @@ class HciHalCallbacks { // implementation-specific details related to the hardware. // LINT.IfChange class HciHal : public ::bluetooth::Module { - public: +public: static const ModuleFactory Factory; virtual ~HciHal() = default; @@ -100,9 +100,7 @@ class HciHal : public ::bluetooth::Module { // Get the MSFT opcode (as specified in Microsoft-defined Bluetooth HCI // extensions) - virtual uint16_t getMsftOpcode() { - return 0; - } + virtual uint16_t getMsftOpcode() { return 0; } }; // LINT.ThenChange(fuzz/fuzz_hci_hal.h) diff --git a/system/gd/hal/hci_hal_android.cc b/system/gd/hal/hci_hal_android.cc index 4db608f0308..1c823c59bdf 100644 --- a/system/gd/hal/hci_hal_android.cc +++ b/system/gd/hal/hci_hal_android.cc @@ -31,15 +31,13 @@ namespace bluetooth::hal { template std::string GetTimerText(const char* func_name, VecType vec) { return common::StringFormat( - "%s: len %zu, 1st 5 bytes '%s'", - func_name, - vec.size(), - common::ToHexString(vec.begin(), std::min(vec.end(), vec.begin() + 5)).c_str()); + "%s: len %zu, 1st 5 bytes '%s'", func_name, vec.size(), + common::ToHexString(vec.begin(), std::min(vec.end(), vec.begin() + 5)).c_str()); } class HciCallbacksImpl : public HciBackendCallbacks { class : public HciHalCallbacks { - public: + public: void hciEventReceived(HciPacket) override { log::warn("Dropping HCI Event, since callback is not set"); } @@ -54,7 +52,7 @@ class HciCallbacksImpl : public HciBackendCallbacks { } } kNullCallbacks; - public: +public: std::promise* const init_promise = &init_promise_; HciCallbacksImpl(SnoopLogger* btsnoop_logger, LinkClocker* link_clocker) @@ -81,8 +79,8 @@ class HciCallbacksImpl : public HciBackendCallbacks { void hciEventReceived(const std::vector& packet) override { common::StopWatch stop_watch(GetTimerText(__func__, packet)); link_clocker_->OnHciEvent(packet); - btsnoop_logger_->Capture( - packet, SnoopLogger::Direction::INCOMING, SnoopLogger::PacketType::EVT); + btsnoop_logger_->Capture(packet, SnoopLogger::Direction::INCOMING, + SnoopLogger::PacketType::EVT); { std::lock_guard lock(mutex_); callback_->hciEventReceived(packet); @@ -91,8 +89,8 @@ class HciCallbacksImpl : public HciBackendCallbacks { void aclDataReceived(const std::vector& packet) override { common::StopWatch stop_watch(GetTimerText(__func__, packet)); - btsnoop_logger_->Capture( - packet, SnoopLogger::Direction::INCOMING, SnoopLogger::PacketType::ACL); + btsnoop_logger_->Capture(packet, SnoopLogger::Direction::INCOMING, + SnoopLogger::PacketType::ACL); { std::lock_guard lock(mutex_); callback_->aclDataReceived(packet); @@ -101,8 +99,8 @@ class HciCallbacksImpl : public HciBackendCallbacks { void scoDataReceived(const std::vector& packet) override { common::StopWatch stop_watch(GetTimerText(__func__, packet)); - btsnoop_logger_->Capture( - packet, SnoopLogger::Direction::INCOMING, SnoopLogger::PacketType::SCO); + btsnoop_logger_->Capture(packet, SnoopLogger::Direction::INCOMING, + SnoopLogger::PacketType::SCO); { std::lock_guard lock(mutex_); callback_->scoDataReceived(packet); @@ -111,15 +109,15 @@ class HciCallbacksImpl : public HciBackendCallbacks { void isoDataReceived(const std::vector& packet) override { common::StopWatch stop_watch(GetTimerText(__func__, packet)); - btsnoop_logger_->Capture( - packet, SnoopLogger::Direction::INCOMING, SnoopLogger::PacketType::ISO); + btsnoop_logger_->Capture(packet, SnoopLogger::Direction::INCOMING, + SnoopLogger::PacketType::ISO); { std::lock_guard lock(mutex_); callback_->isoDataReceived(packet); } } - private: +private: std::mutex mutex_; std::promise init_promise_; HciHalCallbacks* callback_ = &kNullCallbacks; @@ -128,40 +126,38 @@ class HciCallbacksImpl : public HciBackendCallbacks { }; class HciHalImpl : public HciHal { - public: +public: void registerIncomingPacketCallback(HciHalCallbacks* callback) override { callbacks_->SetCallback(callback); } - void unregisterIncomingPacketCallback() override { - callbacks_->ResetCallback(); - } + void unregisterIncomingPacketCallback() override { callbacks_->ResetCallback(); } void sendHciCommand(HciPacket packet) override { - btsnoop_logger_->Capture( - packet, SnoopLogger::Direction::OUTGOING, SnoopLogger::PacketType::CMD); + btsnoop_logger_->Capture(packet, SnoopLogger::Direction::OUTGOING, + SnoopLogger::PacketType::CMD); backend_->sendHciCommand(packet); } void sendAclData(HciPacket packet) override { - btsnoop_logger_->Capture( - packet, SnoopLogger::Direction::OUTGOING, SnoopLogger::PacketType::ACL); + btsnoop_logger_->Capture(packet, SnoopLogger::Direction::OUTGOING, + SnoopLogger::PacketType::ACL); backend_->sendAclData(packet); } void sendScoData(HciPacket packet) override { - btsnoop_logger_->Capture( - packet, SnoopLogger::Direction::OUTGOING, SnoopLogger::PacketType::SCO); + btsnoop_logger_->Capture(packet, SnoopLogger::Direction::OUTGOING, + SnoopLogger::PacketType::SCO); backend_->sendScoData(packet); } void sendIsoData(HciPacket packet) override { - btsnoop_logger_->Capture( - packet, SnoopLogger::Direction::OUTGOING, SnoopLogger::PacketType::ISO); + btsnoop_logger_->Capture(packet, SnoopLogger::Direction::OUTGOING, + SnoopLogger::PacketType::ISO); backend_->sendIsoData(packet); } - protected: +protected: void ListDependencies(ModuleList* list) const override { list->add(); list->add(); @@ -169,14 +165,16 @@ class HciHalImpl : public HciHal { void Start() override { common::StopWatch stop_watch(__func__); - log::assert_that( - backend_ == nullptr, "Start can't be called more than once before Stop is called."); + log::assert_that(backend_ == nullptr, + "Start can't be called more than once before Stop is called."); link_clocker_ = GetDependency(); btsnoop_logger_ = GetDependency(); backend_ = HciBackend::CreateAidl(); - if (!backend_) backend_ = HciBackend::CreateHidl(GetHandler()); + if (!backend_) { + backend_ = HciBackend::CreateHidl(GetHandler()); + } log::assert_that(backend_ != nullptr, "No backend available"); @@ -193,11 +191,9 @@ class HciHalImpl : public HciHal { link_clocker_ = nullptr; } - std::string ToString() const override { - return std::string("HciHal"); - } + std::string ToString() const override { return std::string("HciHal"); } - private: +private: std::shared_ptr callbacks_; std::shared_ptr backend_; SnoopLogger* btsnoop_logger_ = nullptr; diff --git a/system/gd/hal/hci_hal_android_test.cc b/system/gd/hal/hci_hal_android_test.cc index 4f64db35735..28ce1453790 100644 --- a/system/gd/hal/hci_hal_android_test.cc +++ b/system/gd/hal/hci_hal_android_test.cc @@ -29,7 +29,7 @@ using ::bluetooth::os::Thread; namespace bluetooth::hal { class TestBackend : public HciBackend { - public: +public: static std::chrono::milliseconds initialization_delay; std::shared_ptr callbacks; @@ -40,26 +40,18 @@ class TestBackend : public HciBackend { void initialize(std::shared_ptr callbacks) override { this->callbacks = callbacks; std::thread( - [callbacks](std::chrono::milliseconds delay) { - std::this_thread::sleep_for(delay); - callbacks->initializationComplete(); - }, - TestBackend::initialization_delay) - .detach(); + [callbacks](std::chrono::milliseconds delay) { + std::this_thread::sleep_for(delay); + callbacks->initializationComplete(); + }, + TestBackend::initialization_delay) + .detach(); } - void sendHciCommand(const std::vector& command) override { - queues.cmd.push(command); - } - void sendAclData(const std::vector& packet) override { - queues.acl.push(packet); - } - void sendScoData(const std::vector& packet) override { - queues.sco.push(packet); - } - void sendIsoData(const std::vector& packet) override { - queues.iso.push(packet); - } + void sendHciCommand(const std::vector& command) override { queues.cmd.push(command); } + void sendAclData(const std::vector& packet) override { queues.acl.push(packet); } + void sendScoData(const std::vector& packet) override { queues.sco.push(packet); } + void sendIsoData(const std::vector& packet) override { queues.iso.push(packet); } }; std::shared_ptr backend; @@ -71,7 +63,7 @@ std::shared_ptr HciBackend::CreateAidl() { } std::shared_ptr HciBackend::CreateHidl( - [[maybe_unused]] ::bluetooth::os::Handler* handler) { + [[maybe_unused]] ::bluetooth::os::Handler* handler) { backend = std::make_shared(); return backend; } @@ -79,7 +71,7 @@ std::shared_ptr HciBackend::CreateHidl( namespace { class HciHalAndroidTest : public ::testing::Test { - protected: +protected: void SetUp() override { thread_ = new Thread("test_thread", Thread::Priority::NORMAL); hal = fake_registry_.Start(thread_); @@ -92,7 +84,7 @@ class HciHalAndroidTest : public ::testing::Test { HciHal* hal; - private: +private: ModuleRegistry fake_registry_; Thread* thread_; }; diff --git a/system/gd/hal/hci_hal_fake.cc b/system/gd/hal/hci_hal_fake.cc index 55d6e7bc1f3..2a29017c905 100644 --- a/system/gd/hal/hci_hal_fake.cc +++ b/system/gd/hal/hci_hal_fake.cc @@ -23,17 +23,11 @@ void TestHciHal::sendHciCommand(hal::HciPacket command) { outgoing_commands_.push(std::move(command)); } -void TestHciHal::sendAclData(hal::HciPacket data) { - outgoing_acl_.push(std::move(data)); -} +void TestHciHal::sendAclData(hal::HciPacket data) { outgoing_acl_.push(std::move(data)); } -void TestHciHal::sendScoData(hal::HciPacket data) { - outgoing_sco_.push(std::move(data)); -} +void TestHciHal::sendScoData(hal::HciPacket data) { outgoing_sco_.push(std::move(data)); } -void TestHciHal::sendIsoData(hal::HciPacket data) { - outgoing_iso_.push(std::move(data)); -} +void TestHciHal::sendIsoData(hal::HciPacket data) { outgoing_iso_.push(std::move(data)); } packet::PacketView TestHciHal::GetPacketView(hal::HciPacket data) { auto shared = std::make_shared>(data); @@ -75,8 +69,8 @@ std::optional TestHciHal::GetSentIso(std::chrono::milliseconds tim // Timed out return {}; } - log::assert_that( - outgoing_iso_.wait_to_take(timeout), "assert failed: outgoing_iso_.wait_to_take(timeout)"); + log::assert_that(outgoing_iso_.wait_to_take(timeout), + "assert failed: outgoing_iso_.wait_to_take(timeout)"); auto iso = hci::IsoView::Create(GetPacketView(std::move(outgoing_iso_.take()))); log::assert_that(iso.IsValid(), "assert failed: iso.IsValid()"); return iso; diff --git a/system/gd/hal/hci_hal_fake.h b/system/gd/hal/hci_hal_fake.h index ae4aa41014c..1d94f768ce9 100644 --- a/system/gd/hal/hci_hal_fake.h +++ b/system/gd/hal/hci_hal_fake.h @@ -31,7 +31,7 @@ namespace bluetooth { namespace hal { class TestHciHal : public hal::HciHal { - public: +public: TestHciHal() : hal::HciHal() {} ~TestHciHal() { @@ -44,9 +44,7 @@ class TestHciHal : public hal::HciHal { callbacks = callback; } - void unregisterIncomingPacketCallback() override { - callbacks = nullptr; - } + void unregisterIncomingPacketCallback() override { callbacks = nullptr; } void sendHciCommand(hal::HciPacket command) override; @@ -61,16 +59,16 @@ class TestHciHal : public hal::HciHal { packet::PacketView GetPacketView(hal::HciPacket data); std::optional GetSentCommand( - std::chrono::milliseconds timeout = std::chrono::seconds(1)); + std::chrono::milliseconds timeout = std::chrono::seconds(1)); std::optional GetSentAcl( - std::chrono::milliseconds timeout = std::chrono::seconds(1)); + std::chrono::milliseconds timeout = std::chrono::seconds(1)); std::optional GetSentSco( - std::chrono::milliseconds timeout = std::chrono::seconds(1)); + std::chrono::milliseconds timeout = std::chrono::seconds(1)); std::optional GetSentIso( - std::chrono::milliseconds timeout = std::chrono::seconds(1)); + std::chrono::milliseconds timeout = std::chrono::seconds(1)); void InjectEvent(std::unique_ptr event); @@ -80,13 +78,11 @@ class TestHciHal : public hal::HciHal { void ListDependencies(ModuleList* /* list */) const {} - std::string ToString() const override { - return std::string("TestHciHal"); - } + std::string ToString() const override { return std::string("TestHciHal"); } static const ModuleFactory Factory; - private: +private: common::BlockingQueue outgoing_commands_; common::BlockingQueue outgoing_acl_; common::BlockingQueue outgoing_sco_; diff --git a/system/gd/hal/hci_hal_host.cc b/system/gd/hal/hci_hal_host.cc index db18340078e..3384fd047c6 100644 --- a/system/gd/hal/hci_hal_host.cc +++ b/system/gd/hal/hci_hal_host.cc @@ -53,7 +53,8 @@ constexpr uint8_t kHciAclHeaderSize = 4; constexpr uint8_t kHciScoHeaderSize = 3; constexpr uint8_t kHciEvtHeaderSize = 2; constexpr uint8_t kHciIsoHeaderSize = 4; -constexpr int kBufSize = 1024 + 4 + 1; // DeviceProperties::acl_data_packet_size_ + ACL header + H4 header +constexpr int kBufSize = + 1024 + 4 + 1; // DeviceProperties::acl_data_packet_size_ + ACL header + H4 header constexpr uint8_t BTPROTO_HCI = 1; constexpr uint16_t HCI_CHANNEL_USER = 1; @@ -152,7 +153,9 @@ int waitHciDev(int hci_interface) { cc = (struct mgmt_event_read_index*)ev.data; - if (cc->cc_opcode != MGMT_OP_INDEX_LIST) continue; + if (cc->cc_opcode != MGMT_OP_INDEX_LIST) { + continue; + } // Find the interface in the list of available indices. If unavailable, // the result is -1. @@ -166,8 +169,8 @@ int waitHciDev(int hci_interface) { } // Chipset might be lost. Wait for index added event. - bluetooth::log::error( - "HCI interface({}) not found in the MGMT lndex list", hci_interface); + bluetooth::log::error("HCI interface({}) not found in the MGMT lndex list", + hci_interface); } else { // Unlikely event (probably developer error or driver shut down). bluetooth::log::error("Failed to read index list: status({})", cc->status); @@ -217,21 +220,21 @@ int ConnectToSocket() { bluetooth::log::info("HCI device ready"); return socket_fd; } -} +} // namespace namespace bluetooth { namespace hal { class HciHalHost : public HciHal { - public: +public: void registerIncomingPacketCallback(HciHalCallbacks* callback) override { std::lock_guard lock(api_mutex_); log::info("before"); { std::lock_guard incoming_packet_callback_lock(incoming_packet_callback_mutex_); log::assert_that( - incoming_packet_callback_ == nullptr && callback != nullptr, - "assert failed: incoming_packet_callback_ == nullptr && callback != nullptr"); + incoming_packet_callback_ == nullptr && callback != nullptr, + "assert failed: incoming_packet_callback_ == nullptr && callback != nullptr"); incoming_packet_callback_ = callback; } log::info("after"); @@ -251,7 +254,8 @@ class HciHalHost : public HciHal { std::lock_guard lock(api_mutex_); log::assert_that(sock_fd_ != INVALID_FD, "assert failed: sock_fd_ != INVALID_FD"); std::vector packet = std::move(command); - btsnoop_logger_->Capture(packet, SnoopLogger::Direction::OUTGOING, SnoopLogger::PacketType::CMD); + btsnoop_logger_->Capture(packet, SnoopLogger::Direction::OUTGOING, + SnoopLogger::PacketType::CMD); packet.insert(packet.cbegin(), kH4Command); write_to_fd(packet); } @@ -260,7 +264,8 @@ class HciHalHost : public HciHal { std::lock_guard lock(api_mutex_); log::assert_that(sock_fd_ != INVALID_FD, "assert failed: sock_fd_ != INVALID_FD"); std::vector packet = std::move(data); - btsnoop_logger_->Capture(packet, SnoopLogger::Direction::OUTGOING, SnoopLogger::PacketType::ACL); + btsnoop_logger_->Capture(packet, SnoopLogger::Direction::OUTGOING, + SnoopLogger::PacketType::ACL); packet.insert(packet.cbegin(), kH4Acl); write_to_fd(packet); } @@ -269,7 +274,8 @@ class HciHalHost : public HciHal { std::lock_guard lock(api_mutex_); log::assert_that(sock_fd_ != INVALID_FD, "assert failed: sock_fd_ != INVALID_FD"); std::vector packet = std::move(data); - btsnoop_logger_->Capture(packet, SnoopLogger::Direction::OUTGOING, SnoopLogger::PacketType::SCO); + btsnoop_logger_->Capture(packet, SnoopLogger::Direction::OUTGOING, + SnoopLogger::PacketType::SCO); packet.insert(packet.cbegin(), kH4Sco); write_to_fd(packet); } @@ -278,16 +284,15 @@ class HciHalHost : public HciHal { std::lock_guard lock(api_mutex_); log::assert_that(sock_fd_ != INVALID_FD, "assert failed: sock_fd_ != INVALID_FD"); std::vector packet = std::move(data); - btsnoop_logger_->Capture(packet, SnoopLogger::Direction::OUTGOING, SnoopLogger::PacketType::ISO); + btsnoop_logger_->Capture(packet, SnoopLogger::Direction::OUTGOING, + SnoopLogger::PacketType::ISO); packet.insert(packet.cbegin(), kH4Iso); write_to_fd(packet); } - uint16_t getMsftOpcode() override { - return Mgmt().get_vs_opcode(MGMT_VS_OPCODE_MSFT); - } + uint16_t getMsftOpcode() override { return Mgmt().get_vs_opcode(MGMT_VS_OPCODE_MSFT); } - protected: +protected: void ListDependencies(ModuleList* list) const { list->add(); list->add(); @@ -307,10 +312,10 @@ class HciHalHost : public HciHal { } reactable_ = hci_incoming_thread_.GetReactor()->Register( - sock_fd_, - common::Bind(&HciHalHost::incoming_packet_received, common::Unretained(this)), - common::Bind(&HciHalHost::send_packet_ready, common::Unretained(this))); - hci_incoming_thread_.GetReactor()->ModifyRegistration(reactable_, os::Reactor::REACT_ON_READ_ONLY); + sock_fd_, common::Bind(&HciHalHost::incoming_packet_received, common::Unretained(this)), + common::Bind(&HciHalHost::send_packet_ready, common::Unretained(this))); + hci_incoming_thread_.GetReactor()->ModifyRegistration(reactable_, + os::Reactor::REACT_ON_READ_ONLY); link_clocker_ = GetDependency(); btsnoop_logger_ = GetDependency(); log::info("HAL opened successfully"); @@ -323,7 +328,8 @@ class HciHalHost : public HciHal { hci_incoming_thread_.GetReactor()->Unregister(reactable_); log::info("HAL is stopping, start waiting for last callback"); // Wait up to 1 second for the last incoming packet callback to finish - hci_incoming_thread_.GetReactor()->WaitForUnregisteredReactable(std::chrono::milliseconds(1000)); + hci_incoming_thread_.GetReactor()->WaitForUnregisteredReactable( + std::chrono::milliseconds(1000)); log::info("HAL is stopping, finished waiting for last callback"); log::assert_that(sock_fd_ != INVALID_FD, "assert failed: sock_fd_ != INVALID_FD"); } @@ -337,18 +343,16 @@ class HciHalHost : public HciHal { log::info("HAL is closed"); } - std::string ToString() const override { - return std::string("HciHalHost"); - } + std::string ToString() const override { return std::string("HciHalHost"); } - private: +private: // Held when APIs are called, NOT to be held during callbacks std::mutex api_mutex_; HciHalCallbacks* incoming_packet_callback_ = nullptr; std::mutex incoming_packet_callback_mutex_; int sock_fd_ = INVALID_FD; bluetooth::os::Thread hci_incoming_thread_ = - bluetooth::os::Thread("hci_incoming_thread", bluetooth::os::Thread::Priority::NORMAL); + bluetooth::os::Thread("hci_incoming_thread", bluetooth::os::Thread::Priority::NORMAL); bluetooth::os::Reactor::Reactable* reactable_ = nullptr; std::queue> hci_outgoing_queue_; SnoopLogger* btsnoop_logger_ = nullptr; @@ -358,13 +362,16 @@ class HciHalHost : public HciHal { // TODO: replace this with new queue when it's ready hci_outgoing_queue_.emplace(packet); if (hci_outgoing_queue_.size() == 1) { - hci_incoming_thread_.GetReactor()->ModifyRegistration(reactable_, os::Reactor::REACT_ON_READ_WRITE); + hci_incoming_thread_.GetReactor()->ModifyRegistration(reactable_, + os::Reactor::REACT_ON_READ_WRITE); } } void send_packet_ready() { std::lock_guard lock(api_mutex_); - if (hci_outgoing_queue_.empty()) return; + if (hci_outgoing_queue_.empty()) { + return; + } auto packet_to_send = hci_outgoing_queue_.front(); auto bytes_written = write(sock_fd_, (void*)packet_to_send.data(), packet_to_send.size()); hci_outgoing_queue_.pop(); @@ -372,7 +379,8 @@ class HciHalHost : public HciHal { abort(); } if (hci_outgoing_queue_.empty()) { - hci_incoming_thread_.GetReactor()->ModifyRegistration(reactable_, os::Reactor::REACT_ON_READ_ONLY); + hci_incoming_thread_.GetReactor()->ModifyRegistration(reactable_, + os::Reactor::REACT_ON_READ_ONLY); } } @@ -406,22 +414,20 @@ class HciHalHost : public HciHal { } if (buf[0] == kH4Event) { - log::assert_that( - received_size >= kH4HeaderSize + kHciEvtHeaderSize, - "Received bad HCI_EVT packet size: {}", - received_size); + log::assert_that(received_size >= kH4HeaderSize + kHciEvtHeaderSize, + "Received bad HCI_EVT packet size: {}", received_size); uint8_t hci_evt_parameter_total_length = buf[2]; ssize_t payload_size = received_size - (kH4HeaderSize + kHciEvtHeaderSize); - log::assert_that( - payload_size == hci_evt_parameter_total_length, - "malformed HCI event total parameter size received: {} != {}", - payload_size, - hci_evt_parameter_total_length); + log::assert_that(payload_size == hci_evt_parameter_total_length, + "malformed HCI event total parameter size received: {} != {}", payload_size, + hci_evt_parameter_total_length); HciPacket receivedHciPacket; - receivedHciPacket.assign(buf + kH4HeaderSize, buf + kH4HeaderSize + kHciEvtHeaderSize + payload_size); + receivedHciPacket.assign(buf + kH4HeaderSize, + buf + kH4HeaderSize + kHciEvtHeaderSize + payload_size); link_clocker_->OnHciEvent(receivedHciPacket); - btsnoop_logger_->Capture(receivedHciPacket, SnoopLogger::Direction::INCOMING, SnoopLogger::PacketType::EVT); + btsnoop_logger_->Capture(receivedHciPacket, SnoopLogger::Direction::INCOMING, + SnoopLogger::PacketType::EVT); { std::lock_guard incoming_packet_callback_lock(incoming_packet_callback_mutex_); if (incoming_packet_callback_ == nullptr) { @@ -433,25 +439,21 @@ class HciHalHost : public HciHal { } if (buf[0] == kH4Acl) { - log::assert_that( - received_size >= kH4HeaderSize + kHciAclHeaderSize, - "Received bad HCI_ACL packet size: {}", - received_size); + log::assert_that(received_size >= kH4HeaderSize + kHciAclHeaderSize, + "Received bad HCI_ACL packet size: {}", received_size); int payload_size = received_size - (kH4HeaderSize + kHciAclHeaderSize); uint16_t hci_acl_data_total_length = (buf[4] << 8) + buf[3]; - log::assert_that( - payload_size == hci_acl_data_total_length, - "malformed ACL length received: {} != {}", - payload_size, - hci_acl_data_total_length); - log::assert_that( - hci_acl_data_total_length <= kBufSize - kH4HeaderSize - kHciAclHeaderSize, - "packet too long"); + log::assert_that(payload_size == hci_acl_data_total_length, + "malformed ACL length received: {} != {}", payload_size, + hci_acl_data_total_length); + log::assert_that(hci_acl_data_total_length <= kBufSize - kH4HeaderSize - kHciAclHeaderSize, + "packet too long"); HciPacket receivedHciPacket; - receivedHciPacket.assign( - buf + kH4HeaderSize, buf + kH4HeaderSize + kHciAclHeaderSize + payload_size); - btsnoop_logger_->Capture(receivedHciPacket, SnoopLogger::Direction::INCOMING, SnoopLogger::PacketType::ACL); + receivedHciPacket.assign(buf + kH4HeaderSize, + buf + kH4HeaderSize + kHciAclHeaderSize + payload_size); + btsnoop_logger_->Capture(receivedHciPacket, SnoopLogger::Direction::INCOMING, + SnoopLogger::PacketType::ACL); { std::lock_guard incoming_packet_callback_lock(incoming_packet_callback_mutex_); if (incoming_packet_callback_ == nullptr) { @@ -463,21 +465,19 @@ class HciHalHost : public HciHal { } if (buf[0] == kH4Sco) { - log::assert_that( - received_size >= kH4HeaderSize + kHciScoHeaderSize, - "Received bad HCI_SCO packet size: {}", - received_size); + log::assert_that(received_size >= kH4HeaderSize + kHciScoHeaderSize, + "Received bad HCI_SCO packet size: {}", received_size); int payload_size = received_size - (kH4HeaderSize + kHciScoHeaderSize); uint8_t hci_sco_data_total_length = buf[3]; - log::assert_that( - payload_size == hci_sco_data_total_length, - "malformed SCO length received: {} != {}", - payload_size, - hci_sco_data_total_length); + log::assert_that(payload_size == hci_sco_data_total_length, + "malformed SCO length received: {} != {}", payload_size, + hci_sco_data_total_length); HciPacket receivedHciPacket; - receivedHciPacket.assign(buf + kH4HeaderSize, buf + kH4HeaderSize + kHciScoHeaderSize + payload_size); - btsnoop_logger_->Capture(receivedHciPacket, SnoopLogger::Direction::INCOMING, SnoopLogger::PacketType::SCO); + receivedHciPacket.assign(buf + kH4HeaderSize, + buf + kH4HeaderSize + kHciScoHeaderSize + payload_size); + btsnoop_logger_->Capture(receivedHciPacket, SnoopLogger::Direction::INCOMING, + SnoopLogger::PacketType::SCO); { std::lock_guard incoming_packet_callback_lock(incoming_packet_callback_mutex_); if (incoming_packet_callback_ == nullptr) { @@ -489,21 +489,19 @@ class HciHalHost : public HciHal { } if (buf[0] == kH4Iso) { - log::assert_that( - received_size >= kH4HeaderSize + kHciIsoHeaderSize, - "Received bad HCI_ISO packet size: {}", - received_size); + log::assert_that(received_size >= kH4HeaderSize + kHciIsoHeaderSize, + "Received bad HCI_ISO packet size: {}", received_size); int payload_size = received_size - (kH4HeaderSize + kHciIsoHeaderSize); uint16_t hci_iso_data_total_length = ((buf[4] & 0x3f) << 8) + buf[3]; - log::assert_that( - payload_size == hci_iso_data_total_length, - "malformed ISO length received: {} != {}", - payload_size, - hci_iso_data_total_length); + log::assert_that(payload_size == hci_iso_data_total_length, + "malformed ISO length received: {} != {}", payload_size, + hci_iso_data_total_length); HciPacket receivedHciPacket; - receivedHciPacket.assign(buf + kH4HeaderSize, buf + kH4HeaderSize + kHciIsoHeaderSize + payload_size); - btsnoop_logger_->Capture(receivedHciPacket, SnoopLogger::Direction::INCOMING, SnoopLogger::PacketType::ISO); + receivedHciPacket.assign(buf + kH4HeaderSize, + buf + kH4HeaderSize + kHciIsoHeaderSize + payload_size); + btsnoop_logger_->Capture(receivedHciPacket, SnoopLogger::Direction::INCOMING, + SnoopLogger::PacketType::ISO); { std::lock_guard incoming_packet_callback_lock(incoming_packet_callback_mutex_); if (incoming_packet_callback_ == nullptr) { diff --git a/system/gd/hal/hci_hal_host.h b/system/gd/hal/hci_hal_host.h index f6ef81ab65d..9f1350b2655 100644 --- a/system/gd/hal/hci_hal_host.h +++ b/system/gd/hal/hci_hal_host.h @@ -24,33 +24,25 @@ namespace hal { // Singleton object to store runtime configuration for rootcanal class HciHalHostRootcanalConfig { - public: +public: static HciHalHostRootcanalConfig* Get() { static HciHalHostRootcanalConfig instance; return &instance; } // Get the listening TCP port for rootcanal HCI socket - uint16_t GetPort() { - return port_; - } + uint16_t GetPort() { return port_; } // Set the listening TCP port for rootcanal HCI socket - void SetPort(uint16_t port) { - port_ = port; - } + void SetPort(uint16_t port) { port_ = port; } // Get the server address for rootcanal HCI socket - std::string GetServerAddress() { - return server_address_; - } + std::string GetServerAddress() { return server_address_; } // Set the server address for rootcanal HCI socket - void SetServerAddress(const std::string& address) { - server_address_ = address; - } + void SetServerAddress(const std::string& address) { server_address_ = address; } - private: +private: HciHalHostRootcanalConfig() = default; uint16_t port_ = 6402; // Default server TCP port std::string server_address_ = "127.0.0.1"; // Default server address diff --git a/system/gd/hal/hci_hal_host_rootcanal.cc b/system/gd/hal/hci_hal_host_rootcanal.cc index bf9e8ccfab7..26ffa848942 100644 --- a/system/gd/hal/hci_hal_host_rootcanal.cc +++ b/system/gd/hal/hci_hal_host_rootcanal.cc @@ -49,7 +49,8 @@ constexpr uint8_t kHciAclHeaderSize = 4; constexpr uint8_t kHciScoHeaderSize = 3; constexpr uint8_t kHciEvtHeaderSize = 2; constexpr uint8_t kHciIsoHeaderSize = 4; -constexpr int kBufSize = 1024 + 4 + 1; // DeviceProperties::acl_data_packet_size_ + ACL header + H4 header +constexpr int kBufSize = + 1024 + 4 + 1; // DeviceProperties::acl_data_packet_size_ + ACL header + H4 header int ConnectToSocket() { auto* config = bluetooth::hal::HciHalHostRootcanalConfig::Get(); @@ -82,8 +83,8 @@ int ConnectToSocket() { } timeval socket_timeout{ - .tv_sec = 3, - .tv_usec = 0, + .tv_sec = 3, + .tv_usec = 0, }; int ret = setsockopt(socket_fd, SOL_SOCKET, SO_RCVTIMEO, &socket_timeout, sizeof(socket_timeout)); if (ret == -1) { @@ -98,15 +99,15 @@ namespace bluetooth { namespace hal { class HciHalHost : public HciHal { - public: +public: void registerIncomingPacketCallback(HciHalCallbacks* callback) override { std::lock_guard lock(api_mutex_); log::info("before"); { std::lock_guard incoming_packet_callback_lock(incoming_packet_callback_mutex_); log::assert_that( - incoming_packet_callback_ == nullptr && callback != nullptr, - "assert failed: incoming_packet_callback_ == nullptr && callback != nullptr"); + incoming_packet_callback_ == nullptr && callback != nullptr, + "assert failed: incoming_packet_callback_ == nullptr && callback != nullptr"); incoming_packet_callback_ = callback; } log::info("after"); @@ -126,7 +127,8 @@ class HciHalHost : public HciHal { std::lock_guard lock(api_mutex_); log::assert_that(sock_fd_ != INVALID_FD, "assert failed: sock_fd_ != INVALID_FD"); std::vector packet = std::move(command); - btsnoop_logger_->Capture(packet, SnoopLogger::Direction::OUTGOING, SnoopLogger::PacketType::CMD); + btsnoop_logger_->Capture(packet, SnoopLogger::Direction::OUTGOING, + SnoopLogger::PacketType::CMD); packet.insert(packet.cbegin(), kH4Command); write_to_fd(packet); } @@ -135,7 +137,8 @@ class HciHalHost : public HciHal { std::lock_guard lock(api_mutex_); log::assert_that(sock_fd_ != INVALID_FD, "assert failed: sock_fd_ != INVALID_FD"); std::vector packet = std::move(data); - btsnoop_logger_->Capture(packet, SnoopLogger::Direction::OUTGOING, SnoopLogger::PacketType::ACL); + btsnoop_logger_->Capture(packet, SnoopLogger::Direction::OUTGOING, + SnoopLogger::PacketType::ACL); packet.insert(packet.cbegin(), kH4Acl); write_to_fd(packet); } @@ -144,7 +147,8 @@ class HciHalHost : public HciHal { std::lock_guard lock(api_mutex_); log::assert_that(sock_fd_ != INVALID_FD, "assert failed: sock_fd_ != INVALID_FD"); std::vector packet = std::move(data); - btsnoop_logger_->Capture(packet, SnoopLogger::Direction::OUTGOING, SnoopLogger::PacketType::SCO); + btsnoop_logger_->Capture(packet, SnoopLogger::Direction::OUTGOING, + SnoopLogger::PacketType::SCO); packet.insert(packet.cbegin(), kH4Sco); write_to_fd(packet); } @@ -153,12 +157,13 @@ class HciHalHost : public HciHal { std::lock_guard lock(api_mutex_); log::assert_that(sock_fd_ != INVALID_FD, "assert failed: sock_fd_ != INVALID_FD"); std::vector packet = std::move(data); - btsnoop_logger_->Capture(packet, SnoopLogger::Direction::OUTGOING, SnoopLogger::PacketType::ISO); + btsnoop_logger_->Capture(packet, SnoopLogger::Direction::OUTGOING, + SnoopLogger::PacketType::ISO); packet.insert(packet.cbegin(), kH4Iso); write_to_fd(packet); } - protected: +protected: void ListDependencies(ModuleList* list) const { list->add(); list->add(); @@ -170,10 +175,10 @@ class HciHalHost : public HciHal { sock_fd_ = ConnectToSocket(); log::assert_that(sock_fd_ != INVALID_FD, "assert failed: sock_fd_ != INVALID_FD"); reactable_ = hci_incoming_thread_.GetReactor()->Register( - sock_fd_, - common::Bind(&HciHalHost::incoming_packet_received, common::Unretained(this)), - common::Bind(&HciHalHost::send_packet_ready, common::Unretained(this))); - hci_incoming_thread_.GetReactor()->ModifyRegistration(reactable_, os::Reactor::REACT_ON_READ_ONLY); + sock_fd_, common::Bind(&HciHalHost::incoming_packet_received, common::Unretained(this)), + common::Bind(&HciHalHost::send_packet_ready, common::Unretained(this))); + hci_incoming_thread_.GetReactor()->ModifyRegistration(reactable_, + os::Reactor::REACT_ON_READ_ONLY); btsnoop_logger_ = GetDependency(); log::info("HAL opened successfully"); } @@ -185,7 +190,8 @@ class HciHalHost : public HciHal { hci_incoming_thread_.GetReactor()->Unregister(reactable_); log::info("HAL is stopping, start waiting for last callback"); // Wait up to 1 second for the last incoming packet callback to finish - hci_incoming_thread_.GetReactor()->WaitForUnregisteredReactable(std::chrono::milliseconds(1000)); + hci_incoming_thread_.GetReactor()->WaitForUnregisteredReactable( + std::chrono::milliseconds(1000)); log::info("HAL is stopping, finished waiting for last callback"); log::assert_that(sock_fd_ != INVALID_FD, "assert failed: sock_fd_ != INVALID_FD"); } @@ -199,18 +205,16 @@ class HciHalHost : public HciHal { log::info("HAL is closed"); } - std::string ToString() const override { - return std::string("HciHalHost"); - } + std::string ToString() const override { return std::string("HciHalHost"); } - private: +private: // Held when APIs are called, NOT to be held during callbacks std::mutex api_mutex_; HciHalCallbacks* incoming_packet_callback_ = nullptr; std::mutex incoming_packet_callback_mutex_; int sock_fd_ = INVALID_FD; bluetooth::os::Thread hci_incoming_thread_ = - bluetooth::os::Thread("hci_incoming_thread", bluetooth::os::Thread::Priority::NORMAL); + bluetooth::os::Thread("hci_incoming_thread", bluetooth::os::Thread::Priority::NORMAL); bluetooth::os::Reactor::Reactable* reactable_ = nullptr; std::queue> hci_outgoing_queue_; SnoopLogger* btsnoop_logger_ = nullptr; @@ -219,13 +223,16 @@ class HciHalHost : public HciHal { // TODO: replace this with new queue when it's ready hci_outgoing_queue_.emplace(packet); if (hci_outgoing_queue_.size() == 1) { - hci_incoming_thread_.GetReactor()->ModifyRegistration(reactable_, os::Reactor::REACT_ON_READ_WRITE); + hci_incoming_thread_.GetReactor()->ModifyRegistration(reactable_, + os::Reactor::REACT_ON_READ_WRITE); } } void send_packet_ready() { std::lock_guard lock(api_mutex_); - if (hci_outgoing_queue_.empty()) return; + if (hci_outgoing_queue_.empty()) { + return; + } auto packet_to_send = hci_outgoing_queue_.front(); auto bytes_written = write(sock_fd_, (void*)packet_to_send.data(), packet_to_send.size()); hci_outgoing_queue_.pop(); @@ -233,7 +240,8 @@ class HciHalHost : public HciHal { abort(); } if (hci_outgoing_queue_.empty()) { - hci_incoming_thread_.GetReactor()->ModifyRegistration(reactable_, os::Reactor::REACT_ON_READ_ONLY); + hci_incoming_thread_.GetReactor()->ModifyRegistration(reactable_, + os::Reactor::REACT_ON_READ_ONLY); } } @@ -271,21 +279,19 @@ class HciHalHost : public HciHal { } if (buf[0] == kH4Event) { - log::assert_that( - socketRecvAll(buf + kH4HeaderSize, kHciEvtHeaderSize), - "Can't receive from socket: {}", - strerror(errno)); + log::assert_that(socketRecvAll(buf + kH4HeaderSize, kHciEvtHeaderSize), + "Can't receive from socket: {}", strerror(errno)); uint8_t hci_evt_parameter_total_length = buf[2]; - log::assert_that( - socketRecvAll(buf + kH4HeaderSize + kHciEvtHeaderSize, hci_evt_parameter_total_length), - "Can't receive from socket: {}", - strerror(errno)); + log::assert_that(socketRecvAll(buf + kH4HeaderSize + kHciEvtHeaderSize, + hci_evt_parameter_total_length), + "Can't receive from socket: {}", strerror(errno)); HciPacket receivedHciPacket; - receivedHciPacket.assign( - buf + kH4HeaderSize, buf + kH4HeaderSize + kHciEvtHeaderSize + hci_evt_parameter_total_length); - btsnoop_logger_->Capture(receivedHciPacket, SnoopLogger::Direction::INCOMING, SnoopLogger::PacketType::EVT); + receivedHciPacket.assign(buf + kH4HeaderSize, buf + kH4HeaderSize + kHciEvtHeaderSize + + hci_evt_parameter_total_length); + btsnoop_logger_->Capture(receivedHciPacket, SnoopLogger::Direction::INCOMING, + SnoopLogger::PacketType::EVT); { std::lock_guard incoming_packet_callback_lock(incoming_packet_callback_mutex_); if (incoming_packet_callback_ == nullptr) { @@ -297,21 +303,19 @@ class HciHalHost : public HciHal { } if (buf[0] == kH4Acl) { - log::assert_that( - socketRecvAll(buf + kH4HeaderSize, kHciAclHeaderSize), - "Can't receive from socket: {}", - strerror(errno)); + log::assert_that(socketRecvAll(buf + kH4HeaderSize, kHciAclHeaderSize), + "Can't receive from socket: {}", strerror(errno)); uint16_t hci_acl_data_total_length = (buf[4] << 8) + buf[3]; log::assert_that( - socketRecvAll(buf + kH4HeaderSize + kHciAclHeaderSize, hci_acl_data_total_length), - "Can't receive from socket: {}", - strerror(errno)); + socketRecvAll(buf + kH4HeaderSize + kHciAclHeaderSize, hci_acl_data_total_length), + "Can't receive from socket: {}", strerror(errno)); HciPacket receivedHciPacket; - receivedHciPacket.assign( - buf + kH4HeaderSize, buf + kH4HeaderSize + kHciAclHeaderSize + hci_acl_data_total_length); - btsnoop_logger_->Capture(receivedHciPacket, SnoopLogger::Direction::INCOMING, SnoopLogger::PacketType::ACL); + receivedHciPacket.assign(buf + kH4HeaderSize, + buf + kH4HeaderSize + kHciAclHeaderSize + hci_acl_data_total_length); + btsnoop_logger_->Capture(receivedHciPacket, SnoopLogger::Direction::INCOMING, + SnoopLogger::PacketType::ACL); { std::lock_guard incoming_packet_callback_lock(incoming_packet_callback_mutex_); if (incoming_packet_callback_ == nullptr) { @@ -323,21 +327,19 @@ class HciHalHost : public HciHal { } if (buf[0] == kH4Sco) { - log::assert_that( - socketRecvAll(buf + kH4HeaderSize, kHciScoHeaderSize), - "Can't receive from socket: {}", - strerror(errno)); + log::assert_that(socketRecvAll(buf + kH4HeaderSize, kHciScoHeaderSize), + "Can't receive from socket: {}", strerror(errno)); uint8_t hci_sco_data_total_length = buf[3]; log::assert_that( - socketRecvAll(buf + kH4HeaderSize + kHciScoHeaderSize, hci_sco_data_total_length), - "Can't receive from socket: {}", - strerror(errno)); + socketRecvAll(buf + kH4HeaderSize + kHciScoHeaderSize, hci_sco_data_total_length), + "Can't receive from socket: {}", strerror(errno)); HciPacket receivedHciPacket; - receivedHciPacket.assign( - buf + kH4HeaderSize, buf + kH4HeaderSize + kHciScoHeaderSize + hci_sco_data_total_length); - btsnoop_logger_->Capture(receivedHciPacket, SnoopLogger::Direction::INCOMING, SnoopLogger::PacketType::SCO); + receivedHciPacket.assign(buf + kH4HeaderSize, + buf + kH4HeaderSize + kHciScoHeaderSize + hci_sco_data_total_length); + btsnoop_logger_->Capture(receivedHciPacket, SnoopLogger::Direction::INCOMING, + SnoopLogger::PacketType::SCO); { std::lock_guard incoming_packet_callback_lock(incoming_packet_callback_mutex_); if (incoming_packet_callback_ == nullptr) { @@ -349,21 +351,19 @@ class HciHalHost : public HciHal { } if (buf[0] == kH4Iso) { - log::assert_that( - socketRecvAll(buf + kH4HeaderSize, kHciIsoHeaderSize), - "Can't receive from socket: {}", - strerror(errno)); + log::assert_that(socketRecvAll(buf + kH4HeaderSize, kHciIsoHeaderSize), + "Can't receive from socket: {}", strerror(errno)); uint16_t hci_iso_data_total_length = ((buf[4] & 0x3f) << 8) + buf[3]; log::assert_that( - socketRecvAll(buf + kH4HeaderSize + kHciIsoHeaderSize, hci_iso_data_total_length), - "Can't receive from socket: {}", - strerror(errno)); + socketRecvAll(buf + kH4HeaderSize + kHciIsoHeaderSize, hci_iso_data_total_length), + "Can't receive from socket: {}", strerror(errno)); HciPacket receivedHciPacket; - receivedHciPacket.assign( - buf + kH4HeaderSize, buf + kH4HeaderSize + kHciIsoHeaderSize + hci_iso_data_total_length); - btsnoop_logger_->Capture(receivedHciPacket, SnoopLogger::Direction::INCOMING, SnoopLogger::PacketType::ISO); + receivedHciPacket.assign(buf + kH4HeaderSize, + buf + kH4HeaderSize + kHciIsoHeaderSize + hci_iso_data_total_length); + btsnoop_logger_->Capture(receivedHciPacket, SnoopLogger::Direction::INCOMING, + SnoopLogger::PacketType::ISO); { std::lock_guard incoming_packet_callback_lock(incoming_packet_callback_mutex_); if (incoming_packet_callback_ == nullptr) { diff --git a/system/gd/hal/hci_hal_host_test.cc b/system/gd/hal/hci_hal_host_test.cc index 89311ea8348..14c689738e5 100644 --- a/system/gd/hal/hci_hal_host_test.cc +++ b/system/gd/hal/hci_hal_host_test.cc @@ -58,7 +58,7 @@ using H4Packet = std::vector; std::queue> incoming_packets_queue_; class TestHciHalCallbacks : public HciHalCallbacks { - public: +public: void hciEventReceived(HciPacket packet) override { incoming_packets_queue_.emplace(kH4Event, packet); } @@ -78,7 +78,7 @@ class TestHciHalCallbacks : public HciHalCallbacks { // An implementation of rootcanal desktop HCI server which listens on localhost:kListeningPort class FakeRootcanalDesktopHciServer { - public: +public: FakeRootcanalDesktopHciServer() { struct sockaddr_in listen_address; socklen_t sockaddr_in_size = sizeof(struct sockaddr_in); @@ -107,9 +107,7 @@ class FakeRootcanalDesktopHciServer { } } - ~FakeRootcanalDesktopHciServer() { - close(listen_fd_); - } + ~FakeRootcanalDesktopHciServer() { close(listen_fd_); } int Accept() { int accept_fd; @@ -136,12 +134,12 @@ class FakeRootcanalDesktopHciServer { return accept_fd; } - private: +private: int listen_fd_ = -1; }; class HciHalRootcanalTest : public ::testing::Test { - protected: +protected: void SetUp() override { thread_ = new Thread("test_thread", Thread::Priority::NORMAL); @@ -149,7 +147,8 @@ class HciHalRootcanalTest : public ::testing::Test { fake_server_ = new FakeRootcanalDesktopHciServer; hal_ = fake_registry_.Start(thread_); hal_->registerIncomingPacketCallback(&callbacks_); - fake_server_socket_ = fake_server_->Accept(); // accept() after client is connected to avoid blocking + fake_server_socket_ = + fake_server_->Accept(); // accept() after client is connected to avoid blocking std::queue> empty; std::swap(incoming_packets_queue_, empty); } @@ -176,11 +175,14 @@ class HciHalRootcanalTest : public ::testing::Test { Thread* thread_; }; -void check_packet_equal(std::pair hci_packet1_type_data_pair, H4Packet h4_packet2) { +void check_packet_equal(std::pair hci_packet1_type_data_pair, + H4Packet h4_packet2) { auto packet1_hci_size = hci_packet1_type_data_pair.second.size(); ASSERT_EQ(packet1_hci_size + 1, h4_packet2.size()); ASSERT_EQ(hci_packet1_type_data_pair.first, h4_packet2[0]); - ASSERT_EQ(memcmp(hci_packet1_type_data_pair.second.data(), h4_packet2.data() + 1, packet1_hci_size), 0); + ASSERT_EQ( + memcmp(hci_packet1_type_data_pair.second.data(), h4_packet2.data() + 1, packet1_hci_size), + 0); } HciPacket make_sample_hci_cmd_pkt(uint8_t parameter_total_length) { @@ -416,7 +418,8 @@ TEST_F(HciHalRootcanalTest, send_multiple_acl_sequential) { TEST(HciHalHidlTest, serialize) { std::vector bytes = {1, 2, 3, 4, 5, 6, 7, 8, 9}; - auto packet_bytes = hal::SerializePacket(std::unique_ptr(new packet::RawBuilder(bytes))); + auto packet_bytes = hal::SerializePacket( + std::unique_ptr(new packet::RawBuilder(bytes))); ASSERT_EQ(bytes, packet_bytes); } } // namespace diff --git a/system/gd/hal/link_clocker.cc b/system/gd/hal/link_clocker.cc index a077f126f24..f491e9ee1b0 100644 --- a/system/gd/hal/link_clocker.cc +++ b/system/gd/hal/link_clocker.cc @@ -30,13 +30,9 @@ static class : public ReadClockHandler { static std::atomic g_read_clock_handler = &g_empty_handler; -void LinkClocker::Register(ReadClockHandler* handler) { - g_read_clock_handler = handler; -} +void LinkClocker::Register(ReadClockHandler* handler) { g_read_clock_handler = handler; } -void LinkClocker::Unregister() { - g_read_clock_handler = &g_empty_handler; -} +void LinkClocker::Unregister() { g_read_clock_handler = &g_empty_handler; } void LinkClocker::OnHciEvent(const HciPacket& packet) { const int HCI_CMD_READ_CLOCK = 0x1407; @@ -47,26 +43,34 @@ void LinkClocker::OnHciEvent(const HciPacket& packet) { // | [1] Parameter Total Length // | [2+] Parameters - if (packet.size() < 2) return; + if (packet.size() < 2) { + return; + } const uint8_t* payload = packet.data() + 2; size_t payload_length = std::min(size_t(packet[1]), packet.size() - 2); int event_code = packet[0]; - if (event_code != HCI_EVT_COMMAND_COMPLETE) return; + if (event_code != HCI_EVT_COMMAND_COMPLETE) { + return; + } // HCI Command Complete Event [Core 4.E.7.7.14] // | [0] Num_HCI_Command_Packets, Ignored // | [1..2] Command_Opcode, catch `HCI_LE_Set_CIG_Parameters` // | [3+] Return Parameters - if (payload_length < 3) return; + if (payload_length < 3) { + return; + } uint16_t op_code = payload[1] | (payload[2] << 8); const uint8_t* parameters = payload + 3; size_t parameters_length = payload_length - 3; - if (op_code != HCI_CMD_READ_CLOCK) return; + if (op_code != HCI_CMD_READ_CLOCK) { + return; + } // HCI Read Clock return parameters [Core 4.E.7.5.6] // | [0] Status, 0 when OK @@ -74,11 +78,15 @@ void LinkClocker::OnHciEvent(const HciPacket& packet) { // | [3..6] Clock (28-bits meaningful) // | [7..8] Accuracy - if (parameters_length < 9) return; + if (parameters_length < 9) { + return; + } uint8_t status = parameters[0]; - if (status != 0) return; + if (status != 0) { + return; + } uint32_t bt_clock = ((uint32_t)parameters[3] << 0) | ((uint32_t)parameters[4] << 8) | ((uint32_t)parameters[5] << 16) | ((uint32_t)parameters[6] << 24); diff --git a/system/gd/hal/link_clocker.h b/system/gd/hal/link_clocker.h index 0a293543d1b..acabf0787bc 100644 --- a/system/gd/hal/link_clocker.h +++ b/system/gd/hal/link_clocker.h @@ -22,7 +22,7 @@ namespace bluetooth::hal { class ReadClockHandler { - public: +public: virtual ~ReadClockHandler() = default; /// Report a measurement of the BT clock. @@ -33,7 +33,7 @@ class ReadClockHandler { }; class LinkClocker : public ::bluetooth::Module { - public: +public: static const ModuleFactory Factory; void OnHciEvent(const HciPacket& packet); @@ -41,16 +41,14 @@ class LinkClocker : public ::bluetooth::Module { static void Register(ReadClockHandler*); static void Unregister(); - protected: +protected: LinkClocker() = default; void ListDependencies(ModuleList*) const override {} void Start() override {} void Stop() override {} - std::string ToString() const override { - return std::string("LinkClocker"); - } + std::string ToString() const override { return std::string("LinkClocker"); } }; } // namespace bluetooth::hal diff --git a/system/gd/hal/mgmt.cc b/system/gd/hal/mgmt.cc index 3331f31346d..c2ea46eced1 100644 --- a/system/gd/hal/mgmt.cc +++ b/system/gd/hal/mgmt.cc @@ -58,9 +58,9 @@ static int btsocket_open_mgmt(uint16_t hci) { } struct sockaddr_hci addr = { - .hci_family = AF_BLUETOOTH, - .hci_dev = HCI_DEV_NONE, - .hci_channel = HCI_CHANNEL_CONTROL, + .hci_family = AF_BLUETOOTH, + .hci_dev = HCI_DEV_NONE, + .hci_channel = HCI_CHANNEL_CONTROL, }; int ret = bind(fd, (struct sockaddr*)&addr, sizeof(addr)); @@ -121,8 +121,8 @@ uint16_t Mgmt::get_vs_opcode(uint16_t vendor_specification) { } while (ret > 0); if (ret <= 0) { - log::info( - "Skip because mgmt socket is not writable: ev.opcode 0x{:04x} ret {}", ev.opcode, ret); + log::info("Skip because mgmt socket is not writable: ev.opcode 0x{:04x} ret {}", ev.opcode, + ret); close(fd); return ret_opcode; } @@ -144,9 +144,11 @@ uint16_t Mgmt::get_vs_opcode(uint16_t vendor_specification) { } if (cc_ev.opcode == MGMT_EV_COMMAND_COMPLETE) { - struct mgmt_ev_cmd_complete* cc = reinterpret_cast(cc_ev.data); + struct mgmt_ev_cmd_complete* cc = + reinterpret_cast(cc_ev.data); if (cc->opcode == ev.opcode && cc->status == 0) { - struct mgmt_rp_get_vs_opcode* rp = reinterpret_cast(cc->data); + struct mgmt_rp_get_vs_opcode* rp = + reinterpret_cast(cc->data); if (rp->hci_id == hci) { // If the controller supports the MSFT extension, the returned opcode // will not be HCI_OP_NOP. diff --git a/system/gd/hal/mgmt.h b/system/gd/hal/mgmt.h index 1afdc1c2c46..35b22ccdc00 100644 --- a/system/gd/hal/mgmt.h +++ b/system/gd/hal/mgmt.h @@ -57,7 +57,7 @@ struct mgmt_rp_get_vs_opcode { // This class provides an interface to interact with the kernel. class Mgmt { - public: +public: uint16_t get_vs_opcode(uint16_t vendor_specification); }; diff --git a/system/gd/hal/ranging_hal.h b/system/gd/hal/ranging_hal.h index c2d57bfc67a..2d1be5be6df 100644 --- a/system/gd/hal/ranging_hal.h +++ b/system/gd/hal/ranging_hal.h @@ -42,18 +42,17 @@ struct RangingResult { }; class RangingHalCallback { - public: +public: virtual ~RangingHalCallback() = default; - virtual void OnOpened( - uint16_t connection_handle, - const std::vector& vendor_specific_reply) = 0; + virtual void OnOpened(uint16_t connection_handle, + const std::vector& vendor_specific_reply) = 0; virtual void OnOpenFailed(uint16_t connection_handle) = 0; virtual void OnHandleVendorSpecificReplyComplete(uint16_t connection_handle, bool success) = 0; virtual void OnResult(uint16_t connection_handle, const RangingResult& ranging_result) = 0; }; class RangingHal : public ::bluetooth::Module { - public: +public: static const ModuleFactory Factory; virtual ~RangingHal() = default; @@ -61,12 +60,11 @@ class RangingHal : public ::bluetooth::Module { virtual void RegisterCallback(RangingHalCallback* callback) = 0; virtual std::vector GetVendorSpecificCharacteristics() = 0; virtual void OpenSession( - uint16_t connection_handle, - uint16_t att_handle, - const std::vector& vendor_specific_data) = 0; + uint16_t connection_handle, uint16_t att_handle, + const std::vector& vendor_specific_data) = 0; virtual void HandleVendorSpecificReply( - uint16_t connection_handle, - const std::vector& vendor_specific_reply) = 0; + uint16_t connection_handle, + const std::vector& vendor_specific_reply) = 0; virtual void WriteRawData(uint16_t connection_handle, const ChannelSoundingRawData& raw_data) = 0; }; diff --git a/system/gd/hal/ranging_hal_android.cc b/system/gd/hal/ranging_hal_android.cc index 518f23d2e37..3c2696f669c 100644 --- a/system/gd/hal/ranging_hal_android.cc +++ b/system/gd/hal/ranging_hal_android.cc @@ -44,11 +44,10 @@ namespace bluetooth { namespace hal { class BluetoothChannelSoundingSessionTracker : public BnBluetoothChannelSoundingSessionCallback { - public: - BluetoothChannelSoundingSessionTracker( - uint16_t connection_handle, - RangingHalCallback* ranging_hal_callback, - bool for_vendor_specific_reply) +public: + BluetoothChannelSoundingSessionTracker(uint16_t connection_handle, + RangingHalCallback* ranging_hal_callback, + bool for_vendor_specific_reply) : connection_handle_(connection_handle), ranging_hal_callback_(ranging_hal_callback), for_vendor_specific_reply_(for_vendor_specific_reply) {} @@ -59,10 +58,10 @@ class BluetoothChannelSoundingSessionTracker : public BnBluetoothChannelSounding ranging_hal_callback_->OnHandleVendorSpecificReplyComplete(connection_handle_, true); } return ::ndk::ScopedAStatus::ok(); - }; + } ::ndk::ScopedAStatus onOpenFailed( - ::aidl::android::hardware::bluetooth::ranging::Reason in_reason) { + ::aidl::android::hardware::bluetooth::ranging::Reason in_reason) { log::info("connection_handle 0x{:04x}, reason {}", connection_handle_, (uint16_t)in_reason); bluetooth_channel_sounding_session_ = nullptr; if (for_vendor_specific_reply_) { @@ -71,33 +70,33 @@ class BluetoothChannelSoundingSessionTracker : public BnBluetoothChannelSounding ranging_hal_callback_->OnOpenFailed(connection_handle_); } return ::ndk::ScopedAStatus::ok(); - }; + } ::ndk::ScopedAStatus onResult( - const ::aidl::android::hardware::bluetooth::ranging::RangingResult& in_result) { + const ::aidl::android::hardware::bluetooth::ranging::RangingResult& in_result) { log::verbose("resultMeters {}", in_result.resultMeters); hal::RangingResult ranging_result; ranging_result.result_meters_ = in_result.resultMeters; ranging_hal_callback_->OnResult(connection_handle_, ranging_result); return ::ndk::ScopedAStatus::ok(); - }; + } ::ndk::ScopedAStatus onClose(::aidl::android::hardware::bluetooth::ranging::Reason in_reason) { log::info("reason {}", (uint16_t)in_reason); bluetooth_channel_sounding_session_ = nullptr; return ::ndk::ScopedAStatus::ok(); - }; + } ::ndk::ScopedAStatus onCloseFailed( - ::aidl::android::hardware::bluetooth::ranging::Reason in_reason) { + ::aidl::android::hardware::bluetooth::ranging::Reason in_reason) { log::info("reason {}", (uint16_t)in_reason); return ::ndk::ScopedAStatus::ok(); - }; + } std::shared_ptr& GetSession() { return bluetooth_channel_sounding_session_; - }; + } - private: +private: std::shared_ptr bluetooth_channel_sounding_session_ = nullptr; uint16_t connection_handle_; RangingHalCallback* ranging_hal_callback_; @@ -105,14 +104,10 @@ class BluetoothChannelSoundingSessionTracker : public BnBluetoothChannelSounding }; class RangingHalAndroid : public RangingHal { - public: - bool IsBound() override { - return bluetooth_channel_sounding_ != nullptr; - } +public: + bool IsBound() override { return bluetooth_channel_sounding_ != nullptr; } - void RegisterCallback(RangingHalCallback* callback) { - ranging_hal_callback_ = callback; - } + void RegisterCallback(RangingHalCallback* callback) { ranging_hal_callback_ = callback; } std::vector GetVendorSpecificCharacteristics() override { std::vector vendor_specific_characteristics = {}; @@ -123,7 +118,7 @@ class RangingHalAndroid : public RangingHal { for (auto vendor_specific_data : vendorSpecificDataOptional.value()) { VendorSpecificCharacteristic vendor_specific_characteristic; vendor_specific_characteristic.characteristicUuid_ = - vendor_specific_data->characteristicUuid; + vendor_specific_data->characteristicUuid; vendor_specific_characteristic.value_ = vendor_specific_data->opaqueValue; vendor_specific_characteristics.emplace_back(vendor_specific_characteristic); } @@ -134,20 +129,15 @@ class RangingHalAndroid : public RangingHal { } return vendor_specific_characteristics; - }; - - void OpenSession( - uint16_t connection_handle, - uint16_t att_handle, - const std::vector& vendor_specific_data) { - log::info( - "connection_handle 0x{:04x}, att_handle 0x{:04x} size of vendor_specific_data {}", - connection_handle, - att_handle, - vendor_specific_data.size()); + } + + void OpenSession(uint16_t connection_handle, uint16_t att_handle, + const std::vector& vendor_specific_data) { + log::info("connection_handle 0x{:04x}, att_handle 0x{:04x} size of vendor_specific_data {}", + connection_handle, att_handle, vendor_specific_data.size()); session_trackers_[connection_handle] = - ndk::SharedRefBase::make( - connection_handle, ranging_hal_callback_, false); + ndk::SharedRefBase::make( + connection_handle, ranging_hal_callback_, false); BluetoothChannelSoundingParameters parameters; parameters.aclHandle = connection_handle; parameters.role = aidl::android::hardware::bluetooth::ranging::Role::INITIATOR; @@ -175,12 +165,12 @@ class RangingHalAndroid : public RangingHal { } void HandleVendorSpecificReply( - uint16_t connection_handle, - const std::vector& vendor_specific_reply) { + uint16_t connection_handle, + const std::vector& vendor_specific_reply) { log::info("connection_handle 0x{:04x}", connection_handle); session_trackers_[connection_handle] = - ndk::SharedRefBase::make( - connection_handle, ranging_hal_callback_, true); + ndk::SharedRefBase::make( + connection_handle, ranging_hal_callback_, true); BluetoothChannelSoundingParameters parameters; parameters.aclHandle = connection_handle; parameters.role = aidl::android::hardware::bluetooth::ranging::Role::REFLECTOR; @@ -226,11 +216,10 @@ class RangingHalAndroid : public RangingHal { hal_raw_data.reflectorData.stepTonePcts.value().emplace_back(step_tone_pct); } session_trackers_[connection_handle]->GetSession()->writeRawData(hal_raw_data); - }; + } - void CopyVendorSpecificData( - const std::vector& source, - std::optional>>& dist) { + void CopyVendorSpecificData(const std::vector& source, + std::optional>>& dist) { dist = std::make_optional>>(); for (auto& data : source) { VendorSpecificData vendor_specific_data; @@ -240,7 +229,7 @@ class RangingHalAndroid : public RangingHal { } } - protected: +protected: void ListDependencies(ModuleList* /*list*/) const {} void Start() override { @@ -253,19 +242,15 @@ class RangingHalAndroid : public RangingHal { } } - void Stop() override { - bluetooth_channel_sounding_ = nullptr; - } + void Stop() override { bluetooth_channel_sounding_ = nullptr; } - std::string ToString() const override { - return std::string("RangingHalAndroid"); - } + std::string ToString() const override { return std::string("RangingHalAndroid"); } - private: +private: std::shared_ptr bluetooth_channel_sounding_; RangingHalCallback* ranging_hal_callback_; std::unordered_map> - session_trackers_; + session_trackers_; }; const ModuleFactory RangingHal::Factory = ModuleFactory([]() { return new RangingHalAndroid(); }); diff --git a/system/gd/hal/ranging_hal_host.cc b/system/gd/hal/ranging_hal_host.cc index 462461be1ce..16e44995b6e 100644 --- a/system/gd/hal/ranging_hal_host.cc +++ b/system/gd/hal/ranging_hal_host.cc @@ -25,37 +25,33 @@ namespace bluetooth { namespace hal { class RangingHalHost : public RangingHal { - public: - bool IsBound() override { - return false; - } +public: + bool IsBound() override { return false; } void RegisterCallback(RangingHalCallback* /* callback */) override {} std::vector GetVendorSpecificCharacteristics() override { std::vector vendor_specific_characteristics = {}; return vendor_specific_characteristics; - }; - void OpenSession( - uint16_t /* connection_handle */, - uint16_t /* att_handle */, - const std::vector& /* vendor_specific_data */) override{}; + } + void OpenSession(uint16_t /* connection_handle */, uint16_t /* att_handle */, + const std::vector& /* vendor_specific_data */) + override {} void HandleVendorSpecificReply( - uint16_t /* connection_handle */, - const std::vector& /* vendor_specific_reply */) override{}; + uint16_t /* connection_handle */, + const std::vector& /* vendor_specific_reply */) + override {} - void WriteRawData( - uint16_t /* connection_handle */, const ChannelSoundingRawData& /* raw_data */) override{}; + void WriteRawData(uint16_t /* connection_handle */, + const ChannelSoundingRawData& /* raw_data */) override {} - protected: +protected: void ListDependencies(ModuleList* /*list*/) const {} void Start() override {} void Stop() override {} - std::string ToString() const override { - return std::string("RangingHalHost"); - } + std::string ToString() const override { return std::string("RangingHalHost"); } }; const ModuleFactory RangingHal::Factory = ModuleFactory([]() { return new RangingHalHost(); }); diff --git a/system/gd/hal/snoop_logger.cc b/system/gd/hal/snoop_logger.cc index cc75762b7cd..7a9c1d2390b 100644 --- a/system/gd/hal/snoop_logger.cc +++ b/system/gd/hal/snoop_logger.cc @@ -68,13 +68,11 @@ void FilterTracker::RemoveL2capCid(uint16_t local_cid, uint16_t remote_cid) { l2c_remote_cid.erase(remote_cid); } -void FilterTracker::AddRfcommDlci(uint8_t channel) { - rfcomm_channels.insert(channel); -} +void FilterTracker::AddRfcommDlci(uint8_t channel) { rfcomm_channels.insert(channel); } bool FilterTracker::IsAcceptlistedL2cap(bool local, uint16_t cid) { const auto& set = local ? l2c_local_cid : l2c_remote_cid; - return (set.find(cid) != set.end()); + return set.find(cid) != set.end(); } bool FilterTracker::IsRfcommChannel(bool local, uint16_t cid) { @@ -103,7 +101,7 @@ void ProfilesFilter::SetupProfilesFilter(bool pbap_filtered, bool map_filtered) if (pbap_filtered) { profiles[FILTER_PROFILE_PBAP].enabled = profiles[FILTER_PROFILE_HFP_HS].enabled = - profiles[FILTER_PROFILE_HFP_HF].enabled = true; + profiles[FILTER_PROFILE_HFP_HF].enabled = true; } if (map_filtered) { profiles[FILTER_PROFILE_MAP].enabled = true; @@ -120,13 +118,17 @@ bool ProfilesFilter::IsHfpProfile(bool local, uint16_t cid, uint8_t dlci) { bool ProfilesFilter::IsL2capFlowExt(bool local, uint16_t cid) { profile_type_t profile = CidToProfile(local, cid); - if (profile >= 0) return profiles[profile].flow_ext_l2cap; + if (profile >= 0) { + return profiles[profile].flow_ext_l2cap; + } return false; } bool ProfilesFilter::IsRfcommFlowExt(bool local, uint16_t cid, uint8_t dlci) { profile_type_t profile = DlciToProfile(local, cid, dlci); - if (profile >= 0) current_profile = profile; + if (profile >= 0) { + current_profile = profile; + } return profiles[profile].flow_ext_rfcomm; } @@ -144,7 +146,9 @@ profile_type_t ProfilesFilter::CidToProfile(bool local, uint16_t cid) { } profile_type_t ProfilesFilter::DlciToProfile(bool local, uint16_t cid, uint8_t dlci) { - if (!IsRfcommChannel(local, cid)) return FILTER_PROFILE_NONE; + if (!IsRfcommChannel(local, cid)) { + return FILTER_PROFILE_NONE; + } for (int i = 0; i < FILTER_PROFILE_MAX; i++) { if (profiles[i].enabled && profiles[i].l2cap_opened && profiles[i].rfcomm_opened && @@ -155,18 +159,13 @@ profile_type_t ProfilesFilter::DlciToProfile(bool local, uint16_t cid, uint8_t d return FILTER_PROFILE_NONE; } -void ProfilesFilter::ProfileL2capOpen( - profile_type_t profile, uint16_t lcid, uint16_t rcid, uint16_t psm, bool flow_ext) { +void ProfilesFilter::ProfileL2capOpen(profile_type_t profile, uint16_t lcid, uint16_t rcid, + uint16_t psm, bool flow_ext) { if (profiles[profile].l2cap_opened == true) { log::debug("l2cap for {} was already opened. Override it", profile); } - log::debug( - "lcid:={}, rcid={}, psm={}, flow_ext={}, filter profile={}", - lcid, - rcid, - psm, - flow_ext, - ProfilesFilter::ProfileToString(profile)); + log::debug("lcid:={}, rcid={}, psm={}, flow_ext={}, filter profile={}", lcid, rcid, psm, flow_ext, + ProfilesFilter::ProfileToString(profile)); profiles[profile].lcid = lcid; profiles[profile].rcid = rcid; profiles[profile].psm = psm; @@ -177,22 +176,19 @@ void ProfilesFilter::ProfileL2capOpen( } void ProfilesFilter::ProfileL2capClose(profile_type_t profile) { - if (profile < 0 || profile >= FILTER_PROFILE_MAX) return; + if (profile < 0 || profile >= FILTER_PROFILE_MAX) { + return; + } profiles[profile].l2cap_opened = false; } -void ProfilesFilter::ProfileRfcommOpen( - profile_type_t profile, uint16_t lcid, uint8_t dlci, uint16_t uuid, bool flow_ext) { +void ProfilesFilter::ProfileRfcommOpen(profile_type_t profile, uint16_t lcid, uint8_t dlci, + uint16_t uuid, bool flow_ext) { if (profiles[profile].rfcomm_opened == true) { log::debug("rfcomm for {} was already opened. Override it", profile); } - log::debug( - "lcid:={}, dlci={}, uuid={}, flow_ext={}, filter profile={}", - lcid, - dlci, - uuid, - flow_ext, - ProfilesFilter::ProfileToString(profile)); + log::debug("lcid:={}, dlci={}, uuid={}, flow_ext={}, filter profile={}", lcid, dlci, uuid, + flow_ext, ProfilesFilter::ProfileToString(profile)); profiles[profile].rfcomm_uuid = uuid; profiles[profile].scn = (dlci >> 1); profiles[profile].flow_ext_rfcomm = flow_ext; @@ -203,7 +199,9 @@ void ProfilesFilter::ProfileRfcommOpen( } void ProfilesFilter::ProfileRfcommClose(profile_type_t profile) { - if (profile < 0 || profile >= FILTER_PROFILE_MAX) return; + if (profile < 0 || profile >= FILTER_PROFILE_MAX) { + return; + } profiles[profile].rfcomm_opened = false; } @@ -216,19 +214,12 @@ void ProfilesFilter::PrintProfilesConfig() { for (int i = 0; i < FILTER_PROFILE_MAX; i++) { if (profiles[i].enabled) { log::debug( - "\ntype: {}\nenabled: {}, l2cap_opened: {}, rfcomm_opened: {}\nflow_ext_l2cap: {}, " - "flow_ext_rfcomm: {}\nlcid: {}, rcid: {}, rfcomm_uuid: {}, psm: {}\nscn: {}\n", - ProfilesFilter::ProfileToString(profiles[i].type), - profiles[i].enabled, - profiles[i].l2cap_opened, - profiles[i].rfcomm_opened, - profiles[i].flow_ext_l2cap, - profiles[i].flow_ext_rfcomm, - profiles[i].lcid, - profiles[i].rcid, - profiles[i].rfcomm_uuid, - profiles[i].psm, - profiles[i].psm); + "\ntype: {}\nenabled: {}, l2cap_opened: {}, rfcomm_opened: {}\nflow_ext_l2cap: {}, " + "flow_ext_rfcomm: {}\nlcid: {}, rcid: {}, rfcomm_uuid: {}, psm: {}\nscn: {}\n", + ProfilesFilter::ProfileToString(profiles[i].type), profiles[i].enabled, + profiles[i].l2cap_opened, profiles[i].rfcomm_opened, profiles[i].flow_ext_l2cap, + profiles[i].flow_ext_rfcomm, profiles[i].lcid, profiles[i].rcid, + profiles[i].rfcomm_uuid, profiles[i].psm, profiles[i].psm); } } } @@ -258,7 +249,7 @@ constexpr uint8_t RFCOMM_UIH = 0xEF; // RFCOMM: Unnumbered Information with H constexpr uint8_t START_PACKET_BOUNDARY = 0x02; constexpr uint8_t CONTINUATION_PACKET_BOUNDARY = 0x01; constexpr uint16_t HANDLE_MASK = 0x0FFF; -auto GetBoundaryFlag = [](auto handle) { return (((handle) >> 12) & 0x0003); }; +auto GetBoundaryFlag = [](auto handle) { return ((handle) >> 12) & 0x0003; }; // ProfilesFilter consts constexpr size_t ACL_HEADER_LENGTH = 4; @@ -294,7 +285,7 @@ constexpr size_t kDefaultBtSnoopMaxPacketsPerFile = 0xffff; // We restrict the maximum packet size to 150 bytes constexpr size_t kDefaultBtSnoozMaxBytesPerPacket = 150; constexpr size_t kDefaultBtSnoozMaxPayloadBytesPerPacket = - kDefaultBtSnoozMaxBytesPerPacket - sizeof(SnoopLogger::PacketHeaderType); + kDefaultBtSnoozMaxBytesPerPacket - sizeof(SnoopLogger::PacketHeaderType); using namespace std::chrono_literals; constexpr std::chrono::hours kBtSnoozLogLifeTime = 12h; @@ -325,9 +316,7 @@ std::string get_btsnoop_log_path(std::string log_dir, bool filtered) { return log_dir; } -std::string get_last_log_path(std::string log_file_path) { - return log_file_path.append(".last"); -} +std::string get_last_log_path(std::string log_file_path) { return log_file_path.append(".last"); } void delete_btsnoop_files(const std::string& log_path) { log::info("Deleting logs if they exist"); @@ -348,9 +337,12 @@ void delete_btsnoop_files(const std::string& log_path) { } } -void delete_old_btsnooz_files(const std::string& log_path, const std::chrono::milliseconds log_life_time) { +void delete_old_btsnooz_files(const std::string& log_path, + const std::chrono::milliseconds log_life_time) { auto opt_created_ts = os::FileCreatedTime(log_path); - if (!opt_created_ts) return; + if (!opt_created_ts) { + return; + } #ifdef USE_FAKE_TIMERS auto diff = fake_timerfd_get_clock() - file_creation_time; uint64_t log_lifetime = log_life_time.count(); @@ -367,8 +359,8 @@ void delete_old_btsnooz_files(const std::string& log_path, const std::chrono::mi } } -size_t get_btsnooz_packet_length_to_write( - const HciPacket& packet, SnoopLogger::PacketType type, bool qualcomm_debug_log_enabled) { +size_t get_btsnooz_packet_length_to_write(const HciPacket& packet, SnoopLogger::PacketType type, + bool qualcomm_debug_log_enabled) { static const size_t kAclHeaderSize = 4; static const size_t kL2capHeaderSize = 4; static const size_t kL2capCidOffset = (kAclHeaderSize + 2); @@ -395,11 +387,13 @@ size_t get_btsnooz_packet_length_to_write( // Check if we have enough data for an L2CAP header if (packet.size() > len_hci_acl) { uint16_t l2cap_cid = - static_cast(packet[kL2capCidOffset]) | - static_cast((static_cast(packet[kL2capCidOffset + 1]) << static_cast(8))); + static_cast(packet[kL2capCidOffset]) | + static_cast(static_cast(packet[kL2capCidOffset + 1]) + << static_cast(8)); uint16_t hci_acl_packet_handle = - static_cast(packet[kHciAclHandleOffset]) | - static_cast((static_cast(packet[kHciAclHandleOffset + 1]) << static_cast(8))); + static_cast(packet[kHciAclHandleOffset]) | + static_cast(static_cast(packet[kHciAclHandleOffset + 1]) + << static_cast(8)); hci_acl_packet_handle &= 0x0fff; if (l2cap_cid == kL2capSignalingCid) { @@ -433,23 +427,24 @@ size_t get_btsnooz_packet_length_to_write( const std::string SnoopLogger::kBtSnoopMaxPacketsPerFileProperty = "persist.bluetooth.btsnoopsize"; const std::string SnoopLogger::kIsDebuggableProperty = "ro.debuggable"; const std::string SnoopLogger::kBtSnoopLogModeProperty = "persist.bluetooth.btsnooplogmode"; -const std::string SnoopLogger::kBtSnoopDefaultLogModeProperty = "persist.bluetooth.btsnoopdefaultmode"; +const std::string SnoopLogger::kBtSnoopDefaultLogModeProperty = + "persist.bluetooth.btsnoopdefaultmode"; const std::string SnoopLogger::kBtSnoopLogPersists = "persist.bluetooth.btsnooplogpersists"; // Truncates ACL packets (non-fragment) to fixed (MAX_HCI_ACL_LEN) number of bytes const std::string SnoopLogger::kBtSnoopLogFilterHeadersProperty = - "persist.bluetooth.snooplogfilter.headers.enabled"; + "persist.bluetooth.snooplogfilter.headers.enabled"; // Discards A2DP media packets (non-split mode) const std::string SnoopLogger::kBtSnoopLogFilterProfileA2dpProperty = - "persist.bluetooth.snooplogfilter.profiles.a2dp.enabled"; + "persist.bluetooth.snooplogfilter.profiles.a2dp.enabled"; // Filters MAP packets based on the filter mode const std::string SnoopLogger::kBtSnoopLogFilterProfileMapModeProperty = - "persist.bluetooth.snooplogfilter.profiles.map"; + "persist.bluetooth.snooplogfilter.profiles.map"; // Filters PBAP and HFP packets (CPBR, CLCC) based on the filter mode const std::string SnoopLogger::kBtSnoopLogFilterProfilePbapModeProperty = - "persist.bluetooth.snooplogfilter.profiles.pbap"; + "persist.bluetooth.snooplogfilter.profiles.pbap"; // Truncates RFCOMM UIH packet to fixed (L2CAP_HEADER_SIZE) number of bytes const std::string SnoopLogger::kBtSnoopLogFilterProfileRfcommProperty = - "persist.bluetooth.snooplogfilter.profiles.rfcomm.enabled"; + "persist.bluetooth.snooplogfilter.profiles.rfcomm.enabled"; const std::string SnoopLogger::kSoCManufacturerProperty = "ro.soc.manufacturer"; // persist.bluetooth.btsnooplogmode @@ -475,16 +470,12 @@ const size_t SnoopLogger::PACKET_TYPE_LENGTH = 1; const size_t SnoopLogger::MAX_HCI_ACL_LEN = 14; const uint32_t SnoopLogger::L2CAP_HEADER_SIZE = 8; -SnoopLogger::SnoopLogger( - std::string snoop_log_path, - std::string snooz_log_path, - size_t max_packets_per_file, - size_t max_packets_per_buffer, - const std::string& btsnoop_mode, - bool qualcomm_debug_log_enabled, - const std::chrono::milliseconds snooz_log_life_time, - const std::chrono::milliseconds snooz_log_delete_alarm_interval, - bool snoop_log_persists) +SnoopLogger::SnoopLogger(std::string snoop_log_path, std::string snooz_log_path, + size_t max_packets_per_file, size_t max_packets_per_buffer, + const std::string& btsnoop_mode, bool qualcomm_debug_log_enabled, + const std::chrono::milliseconds snooz_log_life_time, + const std::chrono::milliseconds snooz_log_delete_alarm_interval, + bool snoop_log_persists) : snoop_log_path_(std::move(snoop_log_path)), snooz_log_path_(std::move(snooz_log_path)), max_packets_per_file_(max_packets_per_file), @@ -540,10 +531,8 @@ void SnoopLogger::OpenNextSnoopLogFile() { if (os::FileExists(snoop_log_path_)) { if (!os::RenameFile(snoop_log_path_, last_file_path)) { - log::error( - "Unabled to rename existing snoop log from \"{}\" to \"{}\"", - snoop_log_path_, - last_file_path); + log::error("Unabled to rename existing snoop log from \"{}\" to \"{}\"", snoop_log_path_, + last_file_path); } } else { log::info("Previous log file \"{}\" does not exist, skip renaming", snoop_log_path_); @@ -556,15 +545,14 @@ void SnoopLogger::OpenNextSnoopLogFile() { file_creation_time = fake_timerfd_get_clock(); #endif if (!btsnoop_ostream_.good()) { - log::fatal( - "Unable to open snoop log at \"{}\", error: \"{}\"", snoop_log_path_, strerror(errno)); + log::fatal("Unable to open snoop log at \"{}\", error: \"{}\"", snoop_log_path_, + strerror(errno)); } umask(prevmask); - if (!btsnoop_ostream_.write( - reinterpret_cast(&SnoopLoggerCommon::kBtSnoopFileHeader), - sizeof(SnoopLoggerCommon::FileHeaderType))) { - log::fatal( - "Unable to write file header to \"{}\", error: \"{}\"", snoop_log_path_, strerror(errno)); + if (!btsnoop_ostream_.write(reinterpret_cast(&SnoopLoggerCommon::kBtSnoopFileHeader), + sizeof(SnoopLoggerCommon::FileHeaderType))) { + log::fatal("Unable to write file header to \"{}\", error: \"{}\"", snoop_log_path_, + strerror(errno)); } if (!btsnoop_ostream_.flush()) { log::error("Failed to flush, error: \"{}\"", strerror(errno)); @@ -623,7 +611,7 @@ bool SnoopLogger::IsFilterEnabled(std::string filter_name) { bool SnoopLogger::ShouldFilterLog(bool is_received, uint8_t* packet) { uint16_t conn_handle = - ((((uint16_t)packet[ACL_CHANNEL_OFFSET + 1]) << 8) + packet[ACL_CHANNEL_OFFSET]) & 0x0fff; + ((((uint16_t)packet[ACL_CHANNEL_OFFSET + 1]) << 8) + packet[ACL_CHANNEL_OFFSET]) & 0x0fff; std::lock_guard lock(filter_tracker_list_mutex); auto& filters = filter_tracker_list[conn_handle]; uint16_t cid = (packet[L2CAP_CHANNEL_OFFSET + 1] << 8) + packet[L2CAP_CHANNEL_OFFSET]; @@ -644,11 +632,11 @@ bool SnoopLogger::ShouldFilterLog(bool is_received, uint8_t* packet) { return false; } -void SnoopLogger::CalculateAclPacketLength( - uint32_t& length, uint8_t* packet, bool /* is_received */) { +void SnoopLogger::CalculateAclPacketLength(uint32_t& length, uint8_t* packet, + bool /* is_received */) { uint32_t def_len = - ((((uint16_t)packet[ACL_LENGTH_OFFSET + 1]) << 8) + packet[ACL_LENGTH_OFFSET]) + - ACL_HEADER_LENGTH + PACKET_TYPE_LENGTH; + ((((uint16_t)packet[ACL_LENGTH_OFFSET + 1]) << 8) + packet[ACL_LENGTH_OFFSET]) + + ACL_HEADER_LENGTH + PACKET_TYPE_LENGTH; constexpr uint16_t L2CAP_SIGNALING_CID = 0x0001; if (length == 0) { @@ -656,7 +644,7 @@ void SnoopLogger::CalculateAclPacketLength( } uint16_t handle = - ((((uint16_t)packet[ACL_CHANNEL_OFFSET + 1]) << 8) + packet[ACL_CHANNEL_OFFSET]); + ((((uint16_t)packet[ACL_CHANNEL_OFFSET + 1]) << 8) + packet[ACL_CHANNEL_OFFSET]); uint8_t boundary_flag = GetBoundaryFlag(handle); handle = handle & HANDLE_MASK; @@ -675,26 +663,23 @@ void SnoopLogger::CalculateAclPacketLength( } } -uint32_t SnoopLogger::PayloadStrip( - profile_type_t current_profile, uint8_t* packet, uint32_t hdr_len, uint32_t pl_len) { +uint32_t SnoopLogger::PayloadStrip(profile_type_t current_profile, uint8_t* packet, + uint32_t hdr_len, uint32_t pl_len) { uint32_t len = 0; std::string profile_filter_mode = ""; - log::debug( - "current_profile={}, hdr len={}, total len={}", - ProfilesFilter::ProfileToString(current_profile), - hdr_len, - pl_len); + log::debug("current_profile={}, hdr len={}, total len={}", + ProfilesFilter::ProfileToString(current_profile), hdr_len, pl_len); std::lock_guard lock(snoop_log_filters_mutex); switch (current_profile) { case FILTER_PROFILE_PBAP: case FILTER_PROFILE_HFP_HF: case FILTER_PROFILE_HFP_HS: profile_filter_mode = - kBtSnoopLogFilterMode[SnoopLogger::kBtSnoopLogFilterProfilePbapModeProperty]; + kBtSnoopLogFilterMode[SnoopLogger::kBtSnoopLogFilterProfilePbapModeProperty]; break; case FILTER_PROFILE_MAP: profile_filter_mode = - kBtSnoopLogFilterMode[SnoopLogger::kBtSnoopLogFilterProfileMapModeProperty]; + kBtSnoopLogFilterMode[SnoopLogger::kBtSnoopLogFilterProfileMapModeProperty]; break; default: profile_filter_mode = kBtSnoopLogFilterProfileModeDisabled; @@ -707,25 +692,25 @@ uint32_t SnoopLogger::PayloadStrip( packet[ACL_LENGTH_OFFSET] = static_cast(hdr_len - BASIC_L2CAP_HEADER_LENGTH); packet[ACL_LENGTH_OFFSET + 1] = - static_cast((hdr_len - BASIC_L2CAP_HEADER_LENGTH) >> 8); + static_cast((hdr_len - BASIC_L2CAP_HEADER_LENGTH) >> 8); packet[L2CAP_PDU_LENGTH_OFFSET] = - static_cast(hdr_len - (ACL_HEADER_LENGTH + BASIC_L2CAP_HEADER_LENGTH)); + static_cast(hdr_len - (ACL_HEADER_LENGTH + BASIC_L2CAP_HEADER_LENGTH)); packet[L2CAP_PDU_LENGTH_OFFSET + 1] = - static_cast((hdr_len - (ACL_HEADER_LENGTH + BASIC_L2CAP_HEADER_LENGTH)) >> 8); + static_cast((hdr_len - (ACL_HEADER_LENGTH + BASIC_L2CAP_HEADER_LENGTH)) >> 8); } else if (profile_filter_mode == SnoopLogger::kBtSnoopLogFilterProfileModeMagic) { strcpy(reinterpret_cast(&packet[hdr_len]), payload_fill_magic); packet[ACL_LENGTH_OFFSET] = - static_cast(hdr_len + magic_pat_len - BASIC_L2CAP_HEADER_LENGTH); + static_cast(hdr_len + magic_pat_len - BASIC_L2CAP_HEADER_LENGTH); packet[ACL_LENGTH_OFFSET + 1] = - static_cast((hdr_len + magic_pat_len - BASIC_L2CAP_HEADER_LENGTH) >> 8); + static_cast((hdr_len + magic_pat_len - BASIC_L2CAP_HEADER_LENGTH) >> 8); packet[L2CAP_PDU_LENGTH_OFFSET] = static_cast( - hdr_len + magic_pat_len - (ACL_HEADER_LENGTH + BASIC_L2CAP_HEADER_LENGTH)); + hdr_len + magic_pat_len - (ACL_HEADER_LENGTH + BASIC_L2CAP_HEADER_LENGTH)); packet[L2CAP_PDU_LENGTH_OFFSET + 1] = static_cast( - (hdr_len + magic_pat_len - (ACL_HEADER_LENGTH + BASIC_L2CAP_HEADER_LENGTH)) >> 8); + (hdr_len + magic_pat_len - (ACL_HEADER_LENGTH + BASIC_L2CAP_HEADER_LENGTH)) >> 8); len = hdr_len + magic_pat_len; } else { @@ -735,14 +720,14 @@ uint32_t SnoopLogger::PayloadStrip( return len + PACKET_TYPE_LENGTH; // including packet type byte } -uint32_t SnoopLogger::FilterProfilesHandleHfp( - uint8_t* packet, uint32_t length, uint32_t totlen, uint32_t offset) { +uint32_t SnoopLogger::FilterProfilesHandleHfp(uint8_t* packet, uint32_t length, uint32_t totlen, + uint32_t offset) { if ((totlen - offset) > cpbr_pat_len) { if (memcmp(&packet[offset], cpbr_pattern, cpbr_pat_len) == 0) { length = offset + cpbr_pat_len + 1; packet[L2CAP_PDU_LENGTH_OFFSET] = offset + cpbr_pat_len - BASIC_L2CAP_HEADER_LENGTH; packet[L2CAP_PDU_LENGTH_OFFSET] = - offset + cpbr_pat_len - (ACL_HEADER_LENGTH + BASIC_L2CAP_HEADER_LENGTH); + offset + cpbr_pat_len - (ACL_HEADER_LENGTH + BASIC_L2CAP_HEADER_LENGTH); return length; } @@ -750,23 +735,18 @@ uint32_t SnoopLogger::FilterProfilesHandleHfp( length = offset + cpbr_pat_len + 1; packet[L2CAP_PDU_LENGTH_OFFSET] = offset + clcc_pat_len - BASIC_L2CAP_HEADER_LENGTH; packet[L2CAP_PDU_LENGTH_OFFSET] = - offset + clcc_pat_len - (ACL_HEADER_LENGTH + BASIC_L2CAP_HEADER_LENGTH); + offset + clcc_pat_len - (ACL_HEADER_LENGTH + BASIC_L2CAP_HEADER_LENGTH); } } return length; } -void SnoopLogger::FilterProfilesRfcommChannel( - uint8_t* packet, - uint8_t& current_offset, - uint32_t& length, - profile_type_t& current_profile, - bluetooth::hal::ProfilesFilter& filters, - bool is_received, - uint16_t l2cap_channel, - uint32_t& offset, - uint32_t total_length) { +void SnoopLogger::FilterProfilesRfcommChannel(uint8_t* packet, uint8_t& current_offset, + uint32_t& length, profile_type_t& current_profile, + bluetooth::hal::ProfilesFilter& filters, + bool is_received, uint16_t l2cap_channel, + uint32_t& offset, uint32_t total_length) { uint8_t addr, ctrl, pf; addr = packet[current_offset]; @@ -856,34 +836,23 @@ uint32_t SnoopLogger::FilterProfiles(bool is_received, uint8_t* packet) { } if (filters.IsRfcommChannel(is_received, l2c_chan)) { - FilterProfilesRfcommChannel( - packet, - current_offset, - length, - current_profile, - filters, - is_received, - l2c_chan, - offset, - totlen); + FilterProfilesRfcommChannel(packet, current_offset, length, current_profile, filters, + is_received, l2c_chan, offset, totlen); } } return length; } -void SnoopLogger::AcceptlistL2capChannel( - uint16_t conn_handle, uint16_t local_cid, uint16_t remote_cid) { +void SnoopLogger::AcceptlistL2capChannel(uint16_t conn_handle, uint16_t local_cid, + uint16_t remote_cid) { if (btsnoop_mode_ != kBtSnoopLogModeFiltered || !IsFilterEnabled(kBtSnoopLogFilterProfileRfcommProperty)) { return; } - log::debug( - "Acceptlisting l2cap channel: conn_handle={}, local cid={}, remote cid={}", - conn_handle, - local_cid, - remote_cid); + log::debug("Acceptlisting l2cap channel: conn_handle={}, local cid={}, remote cid={}", + conn_handle, local_cid, remote_cid); std::lock_guard lock(filter_tracker_list_mutex); // This will create the entry if there is no associated filter with the @@ -903,36 +872,30 @@ void SnoopLogger::AcceptlistRfcommDlci(uint16_t conn_handle, uint16_t local_cid, filter_tracker_list[conn_handle].AddRfcommDlci(dlci); } -void SnoopLogger::AddRfcommL2capChannel( - uint16_t conn_handle, uint16_t local_cid, uint16_t remote_cid) { +void SnoopLogger::AddRfcommL2capChannel(uint16_t conn_handle, uint16_t local_cid, + uint16_t remote_cid) { if (btsnoop_mode_ != kBtSnoopLogModeFiltered || !IsFilterEnabled(kBtSnoopLogFilterProfileRfcommProperty)) { return; } - log::debug( - "Rfcomm data going over l2cap channel: conn_handle={} local cid={} remote cid={}", - conn_handle, - local_cid, - remote_cid); + log::debug("Rfcomm data going over l2cap channel: conn_handle={} local cid={} remote cid={}", + conn_handle, local_cid, remote_cid); std::lock_guard lock(filter_tracker_list_mutex); filter_tracker_list[conn_handle].SetRfcommCid(local_cid, remote_cid); local_cid_to_acl.insert({local_cid, conn_handle}); } -void SnoopLogger::ClearL2capAcceptlist( - uint16_t conn_handle, uint16_t local_cid, uint16_t remote_cid) { +void SnoopLogger::ClearL2capAcceptlist(uint16_t conn_handle, uint16_t local_cid, + uint16_t remote_cid) { if (btsnoop_mode_ != kBtSnoopLogModeFiltered || !IsFilterEnabled(kBtSnoopLogFilterProfileRfcommProperty)) { return; } - log::debug( - "Clearing acceptlist from l2cap channel. conn_handle={} local cid={} remote cid={}", - conn_handle, - local_cid, - remote_cid); + log::debug("Clearing acceptlist from l2cap channel. conn_handle={} local cid={} remote cid={}", + conn_handle, local_cid, remote_cid); std::lock_guard lock(filter_tracker_list_mutex); filter_tracker_list[conn_handle].RemoveL2capCid(local_cid, remote_cid); @@ -945,16 +908,18 @@ bool SnoopLogger::IsA2dpMediaChannel(uint16_t conn_handle, uint16_t cid, bool is } std::lock_guard lock(a2dpMediaChannels_mutex); - auto iter = std::find_if( - a2dpMediaChannels.begin(), - a2dpMediaChannels.end(), - [conn_handle, cid, is_local_cid](auto& el) { - if (el.conn_handle != conn_handle) return false; + auto iter = std::find_if(a2dpMediaChannels.begin(), a2dpMediaChannels.end(), + [conn_handle, cid, is_local_cid](auto& el) { + if (el.conn_handle != conn_handle) { + return false; + } - if (is_local_cid) return el.local_cid == cid; + if (is_local_cid) { + return el.local_cid == cid; + } - return el.remote_cid == cid; - }); + return el.remote_cid == cid; + }); return iter != a2dpMediaChannels.end(); } @@ -971,19 +936,16 @@ bool SnoopLogger::IsA2dpMediaPacket(bool is_received, uint8_t* packet) { return IsA2dpMediaChannel(conn_handle, cid, is_local_cid); } -void SnoopLogger::AddA2dpMediaChannel( - uint16_t conn_handle, uint16_t local_cid, uint16_t remote_cid) { +void SnoopLogger::AddA2dpMediaChannel(uint16_t conn_handle, uint16_t local_cid, + uint16_t remote_cid) { if (btsnoop_mode_ != kBtSnoopLogModeFiltered || !IsFilterEnabled(kBtSnoopLogFilterProfileA2dpProperty)) { return; } if (!SnoopLogger::IsA2dpMediaChannel(conn_handle, local_cid, true)) { - log::info( - "Add A2DP media channel filtering. conn_handle={} local cid={} remote cid={}", - conn_handle, - local_cid, - remote_cid); + log::info("Add A2DP media channel filtering. conn_handle={} local cid={} remote cid={}", + conn_handle, local_cid, remote_cid); std::lock_guard lock(a2dpMediaChannels_mutex); a2dpMediaChannels.push_back({conn_handle, local_cid, remote_cid}); } @@ -996,18 +958,16 @@ void SnoopLogger::RemoveA2dpMediaChannel(uint16_t conn_handle, uint16_t local_ci } std::lock_guard lock(a2dpMediaChannels_mutex); - a2dpMediaChannels.erase( - std::remove_if( - a2dpMediaChannels.begin(), - a2dpMediaChannels.end(), - [conn_handle, local_cid](auto& el) { - return (el.conn_handle == conn_handle && el.local_cid == local_cid); - }), - a2dpMediaChannels.end()); + a2dpMediaChannels.erase(std::remove_if(a2dpMediaChannels.begin(), a2dpMediaChannels.end(), + [conn_handle, local_cid](auto& el) { + return el.conn_handle == conn_handle && + el.local_cid == local_cid; + }), + a2dpMediaChannels.end()); } -void SnoopLogger::SetRfcommPortOpen( - uint16_t conn_handle, uint16_t local_cid, uint8_t dlci, uint16_t uuid, bool flow) { +void SnoopLogger::SetRfcommPortOpen(uint16_t conn_handle, uint16_t local_cid, uint8_t dlci, + uint16_t uuid, bool flow) { if (btsnoop_mode_ != kBtSnoopLogModeFiltered || (!IsFilterEnabled(kBtSnoopLogFilterProfilePbapModeProperty) && !IsFilterEnabled(kBtSnoopLogFilterProfileMapModeProperty))) { @@ -1019,23 +979,15 @@ void SnoopLogger::SetRfcommPortOpen( profile_type_t profile = FILTER_PROFILE_NONE; auto& filters = profiles_filter_table[conn_handle]; { - filters.SetupProfilesFilter( - IsFilterEnabled(kBtSnoopLogFilterProfilePbapModeProperty), - IsFilterEnabled(kBtSnoopLogFilterProfileMapModeProperty)); + filters.SetupProfilesFilter(IsFilterEnabled(kBtSnoopLogFilterProfilePbapModeProperty), + IsFilterEnabled(kBtSnoopLogFilterProfileMapModeProperty)); } log::info( - "RFCOMM port is opened: handle={}(0x{:x}), lcid={}(0x{:x}), dlci={}(0x{:x}), " - "uuid={}(0x{:x}){}", - conn_handle, - conn_handle, - local_cid, - local_cid, - dlci, - dlci, - uuid, - uuid, - flow ? " Credit Based Flow Control enabled" : ""); + "RFCOMM port is opened: handle={}(0x{:x}), lcid={}(0x{:x}), dlci={}(0x{:x}), " + "uuid={}(0x{:x}){}", + conn_handle, conn_handle, local_cid, local_cid, dlci, dlci, uuid, uuid, + flow ? " Credit Based Flow Control enabled" : ""); if (uuid == PROFILE_UUID_PBAP || (dlci >> 1) == PROFILE_SCN_PBAP) { profile = FILTER_PROFILE_PBAP; @@ -1052,8 +1004,8 @@ void SnoopLogger::SetRfcommPortOpen( } } -void SnoopLogger::SetRfcommPortClose( - uint16_t handle, uint16_t local_cid, uint8_t dlci, uint16_t uuid) { +void SnoopLogger::SetRfcommPortClose(uint16_t handle, uint16_t local_cid, uint8_t dlci, + uint16_t uuid) { if (btsnoop_mode_ != kBtSnoopLogModeFiltered || (!IsFilterEnabled(kBtSnoopLogFilterProfilePbapModeProperty) && !IsFilterEnabled(kBtSnoopLogFilterProfileMapModeProperty))) { @@ -1064,21 +1016,15 @@ void SnoopLogger::SetRfcommPortClose( auto& filters = profiles_filter_table[handle]; log::info( - "RFCOMM port is closed: handle={}(0x{:x}), lcid={}(0x{:x}), dlci={}(0x{:x}), uuid={}(0x{:x})", - handle, - handle, - local_cid, - local_cid, - dlci, - dlci, - uuid, - uuid); + "RFCOMM port is closed: handle={}(0x{:x}), lcid={}(0x{:x}), dlci={}(0x{:x}), " + "uuid={}(0x{:x})", + handle, handle, local_cid, local_cid, dlci, dlci, uuid, uuid); filters.ProfileRfcommClose(filters.DlciToProfile(true, local_cid, dlci)); } -void SnoopLogger::SetL2capChannelOpen( - uint16_t handle, uint16_t local_cid, uint16_t remote_cid, uint16_t psm, bool flow) { +void SnoopLogger::SetL2capChannelOpen(uint16_t handle, uint16_t local_cid, uint16_t remote_cid, + uint16_t psm, bool flow) { if (btsnoop_mode_ != kBtSnoopLogModeFiltered || (!IsFilterEnabled(kBtSnoopLogFilterProfilePbapModeProperty) && !IsFilterEnabled(kBtSnoopLogFilterProfileMapModeProperty))) { @@ -1089,21 +1035,15 @@ void SnoopLogger::SetL2capChannelOpen( profile_type_t profile = FILTER_PROFILE_NONE; auto& filters = profiles_filter_table[handle]; { - filters.SetupProfilesFilter( - IsFilterEnabled(kBtSnoopLogFilterProfilePbapModeProperty), - IsFilterEnabled(kBtSnoopLogFilterProfileMapModeProperty)); + filters.SetupProfilesFilter(IsFilterEnabled(kBtSnoopLogFilterProfilePbapModeProperty), + IsFilterEnabled(kBtSnoopLogFilterProfileMapModeProperty)); } log::info( - "L2CAP channel is opened: handle={}(0x{:x}), lcid={}(0x{:x}), rcid={}(0x{:x}), psm=0x{:x}{}", - handle, - handle, - local_cid, - local_cid, - remote_cid, - remote_cid, - psm, - flow ? " Standard or Enhanced Control enabled" : ""); + "L2CAP channel is opened: handle={}(0x{:x}), lcid={}(0x{:x}), rcid={}(0x{:x}), " + "psm=0x{:x}{}", + handle, handle, local_cid, local_cid, remote_cid, remote_cid, psm, + flow ? " Standard or Enhanced Control enabled" : ""); if (psm == PROFILE_PSM_RFCOMM) { filters.ch_rfc_l = local_cid; @@ -1130,24 +1070,14 @@ void SnoopLogger::SetL2capChannelClose(uint16_t handle, uint16_t local_cid, uint auto& filters = profiles_filter_table[handle]; - log::info( - "L2CAP channel is closed: handle={}(0x{:x}), lcid={}(0x{:x}), rcid={}(0x{:x})", - handle, - handle, - local_cid, - local_cid, - remote_cid, - remote_cid); + log::info("L2CAP channel is closed: handle={}(0x{:x}), lcid={}(0x{:x}), rcid={}(0x{:x})", handle, + handle, local_cid, local_cid, remote_cid, remote_cid); filters.ProfileL2capClose(filters.CidToProfile(true, local_cid)); } -void SnoopLogger::FilterCapturedPacket( - HciPacket& packet, - Direction direction, - PacketType type, - uint32_t& length, - PacketHeaderType header) { +void SnoopLogger::FilterCapturedPacket(HciPacket& packet, Direction direction, PacketType type, + uint32_t& length, PacketHeaderType header) { if (btsnoop_mode_ != kBtSnoopLogModeFiltered || type != PacketType::ACL) { return; } @@ -1174,13 +1104,15 @@ void SnoopLogger::FilterCapturedPacket( } length = FilterProfiles(direction == Direction::INCOMING, (uint8_t*)packet.data()); - if (length == 0) return; + if (length == 0) { + return; + } } } if (IsFilterEnabled(kBtSnoopLogFilterProfileRfcommProperty)) { bool shouldFilter = - SnoopLogger::ShouldFilterLog(direction == Direction::INCOMING, (uint8_t*)packet.data()); + SnoopLogger::ShouldFilterLog(direction == Direction::INCOMING, (uint8_t*)packet.data()); if (shouldFilter) { length = L2CAP_HEADER_SIZE + PACKET_TYPE_LENGTH; } @@ -1192,9 +1124,9 @@ void SnoopLogger::Capture(const HciPacket& immutable_packet, Direction direction HciPacket mutable_packet(immutable_packet); HciPacket& packet = mutable_packet; ////////////////////////////////////////////////////////////////////////// - uint64_t timestamp_us = - std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()) - .count(); + uint64_t timestamp_us = std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()) + .count(); std::bitset<32> flags = 0; switch (type) { case PacketType::CMD: @@ -1224,7 +1156,8 @@ void SnoopLogger::Capture(const HciPacket& immutable_packet, Direction direction if (btsnoop_mode_ == kBtSnoopLogModeDisabled) { // btsnoop disabled, log in-memory btsnooz log only std::stringstream ss; - size_t included_length = get_btsnooz_packet_length_to_write(packet, type, qualcomm_debug_log_enabled_); + size_t included_length = + get_btsnooz_packet_length_to_write(packet, type, qualcomm_debug_log_enabled_); header.length_captured = htonl(included_length + /* type byte */ PACKET_TYPE_LENGTH); if (!ss.write(reinterpret_cast(&header), sizeof(PacketHeaderType))) { log::error("Failed to write packet header for btsnooz, error: \"{}\"", strerror(errno)); @@ -1260,9 +1193,10 @@ void SnoopLogger::Capture(const HciPacket& immutable_packet, Direction direction socket_->Write(packet.data(), (size_t)(length - 1)); } - // std::ofstream::flush() pushes user data into kernel memory. The data will be written even if this process - // crashes. However, data will be lost if there is a kernel panic, which is out of scope of BT snoop log. - // NOTE: std::ofstream::write() followed by std::ofstream::flush() has similar effect as UNIX write(fd, data, len) + // std::ofstream::flush() pushes user data into kernel memory. The data will be written even if + // this process crashes. However, data will be lost if there is a kernel panic, which is out of + // scope of BT snoop log. NOTE: std::ofstream::write() followed by std::ofstream::flush() has + // similar effect as UNIX write(fd, data, len) // as write() syscall dumps data into kernel memory directly if (!btsnoop_ostream_.flush()) { log::error("Failed to flush, error: \"{}\"", strerror(errno)); @@ -1282,10 +1216,8 @@ void SnoopLogger::DumpSnoozLogToFile(const std::vector& data) const if (os::FileExists(snooz_log_path_)) { if (!os::RenameFile(snooz_log_path_, last_file_path)) { - log::error( - "Unabled to rename existing snooz log from \"{}\" to \"{}\"", - snooz_log_path_, - last_file_path); + log::error("Unabled to rename existing snooz log from \"{}\" to \"{}\"", snooz_log_path_, + last_file_path); } } else { log::info("Previous log file \"{}\" does not exist, skip renaming", snooz_log_path_); @@ -1295,15 +1227,14 @@ void SnoopLogger::DumpSnoozLogToFile(const std::vector& data) const // do not use std::ios::app as we want override the existing file std::ofstream btsnooz_ostream(snooz_log_path_, std::ios::binary | std::ios::out); if (!btsnooz_ostream.good()) { - log::fatal( - "Unable to open snoop log at \"{}\", error: \"{}\"", snooz_log_path_, strerror(errno)); + log::fatal("Unable to open snoop log at \"{}\", error: \"{}\"", snooz_log_path_, + strerror(errno)); } umask(prevmask); - if (!btsnooz_ostream.write( - reinterpret_cast(&SnoopLoggerCommon::kBtSnoopFileHeader), - sizeof(SnoopLoggerCommon::FileHeaderType))) { - log::fatal( - "Unable to write file header to \"{}\", error: \"{}\"", snooz_log_path_, strerror(errno)); + if (!btsnooz_ostream.write(reinterpret_cast(&SnoopLoggerCommon::kBtSnoopFileHeader), + sizeof(SnoopLoggerCommon::FileHeaderType))) { + log::fatal("Unable to write file header to \"{}\", error: \"{}\"", snooz_log_path_, + strerror(errno)); } for (const auto& packet : data) { if (!btsnooz_ostream.write(packet.data(), packet.size())) { @@ -1330,7 +1261,7 @@ void SnoopLogger::Start() { auto snoop_logger_socket = std::make_unique(&syscall_if); snoop_logger_socket_thread_ = - std::make_unique(std::move(snoop_logger_socket)); + std::make_unique(std::move(snoop_logger_socket)); auto thread_started_future = snoop_logger_socket_thread_->Start(); thread_started_future.wait(); if (thread_started_future.get()) { @@ -1342,8 +1273,8 @@ void SnoopLogger::Start() { } } alarm_ = std::make_unique(GetHandler()); - alarm_->Schedule( - common::Bind(&delete_old_btsnooz_files, snooz_log_path_, snooz_log_life_time_), snooz_log_delete_alarm_interval_); + alarm_->Schedule(common::Bind(&delete_old_btsnooz_files, snooz_log_path_, snooz_log_life_time_), + snooz_log_delete_alarm_interval_); } void SnoopLogger::Stop() { @@ -1372,7 +1303,7 @@ void SnoopLogger::Stop() { } DumpsysDataFinisher SnoopLogger::GetDumpsysData( - flatbuffers::FlatBufferBuilder* /* builder */) const { + flatbuffers::FlatBufferBuilder* /* builder */) const { DumpSnoozLogToFile(btsnooz_buffer_.Pull()); return EmptyDumpsysDataFinisher; } @@ -1383,7 +1314,8 @@ size_t SnoopLogger::GetMaxPacketsPerFile() { { auto max_packets_per_file_prop = os::GetSystemProperty(kBtSnoopMaxPacketsPerFileProperty); if (max_packets_per_file_prop) { - auto max_packets_per_file_number = common::Uint64FromString(max_packets_per_file_prop.value()); + auto max_packets_per_file_number = + common::Uint64FromString(max_packets_per_file_prop.value()); if (max_packets_per_file_number) { max_packets_per_file = max_packets_per_file_number.value(); } @@ -1452,23 +1384,19 @@ bool SnoopLogger::IsQualcommDebugLogEnabled() { bool qualcomm_debug_log_enabled = false; { auto soc_manufacturer_prop = os::GetSystemProperty(kSoCManufacturerProperty); - qualcomm_debug_log_enabled = soc_manufacturer_prop.has_value() && - common::StringTrim(soc_manufacturer_prop.value()) == kSoCManufacturerQualcomm; + qualcomm_debug_log_enabled = + soc_manufacturer_prop.has_value() && + common::StringTrim(soc_manufacturer_prop.value()) == kSoCManufacturerQualcomm; } return qualcomm_debug_log_enabled; } const ModuleFactory SnoopLogger::Factory = ModuleFactory([]() { - return new SnoopLogger( - os::ParameterProvider::SnoopLogFilePath(), - os::ParameterProvider::SnoozLogFilePath(), - GetMaxPacketsPerFile(), - GetMaxPacketsPerBuffer(), - GetBtSnoopMode(), - IsQualcommDebugLogEnabled(), - kBtSnoozLogLifeTime, - kBtSnoozLogDeleteRepeatingAlarmInterval, - IsBtSnoopLogPersisted()); + return new SnoopLogger(os::ParameterProvider::SnoopLogFilePath(), + os::ParameterProvider::SnoozLogFilePath(), GetMaxPacketsPerFile(), + GetMaxPacketsPerBuffer(), GetBtSnoopMode(), IsQualcommDebugLogEnabled(), + kBtSnoozLogLifeTime, kBtSnoozLogDeleteRepeatingAlarmInterval, + IsBtSnoopLogPersisted()); }); } // namespace hal diff --git a/system/gd/hal/snoop_logger.h b/system/gd/hal/snoop_logger.h index 96795cc0e75..1b03d1ab6ae 100644 --- a/system/gd/hal/snoop_logger.h +++ b/system/gd/hal/snoop_logger.h @@ -40,7 +40,7 @@ static uint64_t file_creation_time; #endif class FilterTracker { - public: +public: // NOTE: 1 is used as a static CID for L2CAP signaling std::unordered_set l2c_local_cid = {1}; std::unordered_set l2c_remote_cid = {1}; @@ -76,7 +76,7 @@ typedef enum { } profile_type_t; class ProfilesFilter { - public: +public: void SetupProfilesFilter(bool pbap_filtered, bool map_filtered); bool IsHfpProfile(bool local, uint16_t cid, uint8_t dlci); @@ -93,13 +93,13 @@ class ProfilesFilter { profile_type_t DlciToProfile(bool local, uint16_t cid, uint8_t dlci); - void ProfileL2capOpen( - profile_type_t profile, uint16_t lcid, uint16_t rcid, uint16_t psm, bool flow_ext); + void ProfileL2capOpen(profile_type_t profile, uint16_t lcid, uint16_t rcid, uint16_t psm, + bool flow_ext); void ProfileL2capClose(profile_type_t profile); - void ProfileRfcommOpen( - profile_type_t profile, uint16_t lcid, uint8_t dlci, uint16_t uuid, bool flow_ext); + void ProfileRfcommOpen(profile_type_t profile, uint16_t lcid, uint8_t dlci, uint16_t uuid, + bool flow_ext); void ProfileRfcommClose(profile_type_t profile); @@ -127,7 +127,7 @@ class ProfilesFilter { uint16_t ch_rfc_l, ch_rfc_r; // local & remote L2CAP channel for RFCOMM uint16_t ch_last; // last channel seen for fragment packet - private: +private: bool setup_done_flag = false; struct { profile_type_t type; @@ -140,7 +140,7 @@ class ProfilesFilter { }; class SnoopLogger : public ::bluetooth::Module { - public: +public: static const ModuleFactory Factory; static const std::string kBtSnoopMaxPacketsPerFileProperty; @@ -167,13 +167,13 @@ class SnoopLogger : public ::bluetooth::Module { static const std::string kBtSnoopLogFilterProfileModeDisabled; std::unordered_map kBtSnoopLogFilterState = { - {kBtSnoopLogFilterHeadersProperty, false}, - {kBtSnoopLogFilterProfileA2dpProperty, false}, - {kBtSnoopLogFilterProfileRfcommProperty, false}}; + {kBtSnoopLogFilterHeadersProperty, false}, + {kBtSnoopLogFilterProfileA2dpProperty, false}, + {kBtSnoopLogFilterProfileRfcommProperty, false}}; std::unordered_map kBtSnoopLogFilterMode = { - {kBtSnoopLogFilterProfilePbapModeProperty, kBtSnoopLogFilterProfileModeDisabled}, - {kBtSnoopLogFilterProfileMapModeProperty, kBtSnoopLogFilterProfileModeDisabled}}; + {kBtSnoopLogFilterProfilePbapModeProperty, kBtSnoopLogFilterProfileModeDisabled}, + {kBtSnoopLogFilterProfileMapModeProperty, kBtSnoopLogFilterProfileModeDisabled}}; // Put in header for test struct PacketHeaderType { @@ -251,20 +251,20 @@ class SnoopLogger : public ::bluetooth::Module { void RemoveA2dpMediaChannel(uint16_t conn_handle, uint16_t local_cid); // New RFCOMM port is opened. - void SetRfcommPortOpen( - uint16_t conn_handle, uint16_t local_cid, uint8_t dlci, uint16_t uuid, bool flow); + void SetRfcommPortOpen(uint16_t conn_handle, uint16_t local_cid, uint8_t dlci, uint16_t uuid, + bool flow); // RFCOMM port is closed. void SetRfcommPortClose(uint16_t handle, uint16_t local_cid, uint8_t dlci, uint16_t uuid); // New L2CAP channel is opened. - void SetL2capChannelOpen( - uint16_t handle, uint16_t local_cid, uint16_t remote_cid, uint16_t psm, bool flow); + void SetL2capChannelOpen(uint16_t handle, uint16_t local_cid, uint16_t remote_cid, uint16_t psm, + bool flow); // L2CAP channel is closed. void SetL2capChannelClose(uint16_t handle, uint16_t local_cid, uint16_t remote_cid); void RegisterSocket(SnoopLoggerSocketInterface* socket); - protected: +protected: // Packet type length static const size_t PACKET_TYPE_LENGTH; // The size of the L2CAP header. All information past this point is removed from @@ -277,20 +277,13 @@ class SnoopLogger : public ::bluetooth::Module { void Start() override; void Stop() override; DumpsysDataFinisher GetDumpsysData(flatbuffers::FlatBufferBuilder* builder) const override; - std::string ToString() const override { - return std::string("SnoopLogger"); - } + std::string ToString() const override { return std::string("SnoopLogger"); } - SnoopLogger( - std::string snoop_log_path, - std::string snooz_log_path, - size_t max_packets_per_file, - size_t max_packets_per_buffer, - const std::string& btsnoop_mode, - bool qualcomm_debug_log_enabled, - const std::chrono::milliseconds snooz_log_life_time, - const std::chrono::milliseconds snooz_log_delete_alarm_interval, - bool snoop_log_persists); + SnoopLogger(std::string snoop_log_path, std::string snooz_log_path, size_t max_packets_per_file, + size_t max_packets_per_buffer, const std::string& btsnoop_mode, + bool qualcomm_debug_log_enabled, const std::chrono::milliseconds snooz_log_life_time, + const std::chrono::milliseconds snooz_log_delete_alarm_interval, + bool snoop_log_persists); void CloseCurrentSnoopLogFile(); void OpenNextSnoopLogFile(); void DumpSnoozLogToFile(const std::vector& data) const; @@ -305,8 +298,8 @@ class SnoopLogger : public ::bluetooth::Module { // Calculate packet length (snoopheadersfiltered mode) void CalculateAclPacketLength(uint32_t& length, uint8_t* packet, bool is_received); // Strip packet's payload (profilesfiltered mode) - uint32_t PayloadStrip( - profile_type_t current_profile, uint8_t* packet, uint32_t hdr_len, uint32_t pl_len); + uint32_t PayloadStrip(profile_type_t current_profile, uint8_t* packet, uint32_t hdr_len, + uint32_t pl_len); // Filter profile packet according to its filtering mode uint32_t FilterProfiles(bool is_received, uint8_t* packet); // Check if packet is A2DP media packet (a2dppktsfiltered mode) @@ -314,28 +307,18 @@ class SnoopLogger : public ::bluetooth::Module { // Chec if channel is cached in snoop logger for filtering (a2dppktsfiltered mode) bool IsA2dpMediaChannel(uint16_t conn_handle, uint16_t cid, bool is_local_cid); // Handle HFP filtering while profilesfiltered enabled - uint32_t FilterProfilesHandleHfp( - uint8_t* packet, uint32_t length, uint32_t totlen, uint32_t offset); - void FilterProfilesRfcommChannel( - uint8_t* packet, - uint8_t& current_offset, - uint32_t& length, - profile_type_t& current_profile, - bluetooth::hal::ProfilesFilter& filters, - bool is_received, - uint16_t l2cap_channel, - uint32_t& offset, - uint32_t total_length); - void FilterCapturedPacket( - HciPacket& packet, - Direction direction, - PacketType type, - uint32_t& length, - PacketHeaderType header); + uint32_t FilterProfilesHandleHfp(uint8_t* packet, uint32_t length, uint32_t totlen, + uint32_t offset); + void FilterProfilesRfcommChannel(uint8_t* packet, uint8_t& current_offset, uint32_t& length, + profile_type_t& current_profile, + bluetooth::hal::ProfilesFilter& filters, bool is_received, + uint16_t l2cap_channel, uint32_t& offset, uint32_t total_length); + void FilterCapturedPacket(HciPacket& packet, Direction direction, PacketType type, + uint32_t& length, PacketHeaderType header); std::unique_ptr snoop_logger_socket_thread_; - private: +private: static std::string btsnoop_mode_; std::string snoop_log_path_; std::string snooz_log_path_; diff --git a/system/gd/hal/snoop_logger_common.h b/system/gd/hal/snoop_logger_common.h index 89479c04213..89b9eae86a5 100644 --- a/system/gd/hal/snoop_logger_common.h +++ b/system/gd/hal/snoop_logger_common.h @@ -27,10 +27,10 @@ static_assert((isLittleEndian || isBigEndian) && (isLittleEndian != isBigEndian) constexpr uint32_t BTSNOOP_VERSION_NUMBER = isLittleEndian ? 0x01000000 : 1; constexpr uint32_t BTSNOOP_DATALINK_TYPE = - isLittleEndian ? 0xea030000 : 0x03ea; // Datalink Type code for HCI UART (H4) is 1002 + isLittleEndian ? 0xea030000 : 0x03ea; // Datalink Type code for HCI UART (H4) is 1002 class SnoopLoggerCommon { - public: +public: struct FileHeaderType { uint8_t identification_pattern[8]; uint32_t version_number; @@ -38,9 +38,9 @@ class SnoopLoggerCommon { } __attribute__((__packed__)); static constexpr FileHeaderType kBtSnoopFileHeader = { - .identification_pattern = {'b', 't', 's', 'n', 'o', 'o', 'p', 0x00}, - .version_number = BTSNOOP_VERSION_NUMBER, - .datalink_type = BTSNOOP_DATALINK_TYPE}; + .identification_pattern = {'b', 't', 's', 'n', 'o', 'o', 'p', 0x00}, + .version_number = BTSNOOP_VERSION_NUMBER, + .datalink_type = BTSNOOP_DATALINK_TYPE}; }; } // namespace hal diff --git a/system/gd/hal/snoop_logger_socket.cc b/system/gd/hal/snoop_logger_socket.cc index 8b9db3dbc9e..7d7717f95c7 100644 --- a/system/gd/hal/snoop_logger_socket.cc +++ b/system/gd/hal/snoop_logger_socket.cc @@ -48,7 +48,8 @@ static constexpr int INVALID_FD = -1; constexpr int INCOMING_SOCKET_CONNECTIONS_QUEUE_SIZE_ = 10; -SnoopLoggerSocket::SnoopLoggerSocket(SyscallWrapperInterface* syscall_if, int socket_address, int socket_port) +SnoopLoggerSocket::SnoopLoggerSocket(SyscallWrapperInterface* syscall_if, int socket_address, + int socket_port) : syscall_if_(syscall_if), socket_address_(socket_address), socket_port_(socket_port), @@ -60,9 +61,7 @@ SnoopLoggerSocket::SnoopLoggerSocket(SyscallWrapperInterface* syscall_if, int so log::info("address {} port {}", socket_address, socket_port); } -SnoopLoggerSocket::~SnoopLoggerSocket() { - Cleanup(); -} +SnoopLoggerSocket::~SnoopLoggerSocket() { Cleanup(); } void SnoopLoggerSocket::Write(int& client_socket, const void* data, size_t length) { if (client_socket == -1) { @@ -122,7 +121,9 @@ bool SnoopLoggerSocket::ProcessIncomingRequest() { if ((syscall_if_->Select(fd_max_ + 1, &sock_fds, NULL, NULL, NULL)) == -1) { log::error("select failed {}", strerror(syscall_if_->GetErrno())); - if (syscall_if_->GetErrno() == EINTR) return true; + if (syscall_if_->GetErrno() == EINTR) { + return true; + } return false; } @@ -141,7 +142,8 @@ bool SnoopLoggerSocket::ProcessIncomingRequest() { InitializeClientSocket(client_socket); ClientSocketConnected(client_socket); - } else if ((notification_listen_fd_ != -1) && syscall_if_->FDIsSet(notification_listen_fd_, &sock_fds)) { + } else if ((notification_listen_fd_ != -1) && + syscall_if_->FDIsSet(notification_listen_fd_, &sock_fds)) { log::warn("exting from listen_fn_ thread"); return false; } @@ -160,7 +162,8 @@ int SnoopLoggerSocket::AcceptIncomingConnection(int listen_socket, int& client_s socklen_t clen; struct sockaddr_in client_addr; - RUN_NO_INTR(client_socket = syscall_if_->Accept(listen_socket, (struct sockaddr*)&client_addr, &clen, SOCK_CLOEXEC)); + RUN_NO_INTR(client_socket = syscall_if_->Accept(listen_socket, (struct sockaddr*)&client_addr, + &clen, SOCK_CLOEXEC)); if (client_socket == -1) { int errno_ = syscall_if_->GetErrno(); log::warn("error accepting socket: {}", strerror(errno_)); @@ -170,11 +173,8 @@ int SnoopLoggerSocket::AcceptIncomingConnection(int listen_socket, int& client_s return 0; } - log::info( - "Client socket fd: {}, IP address: {}, port: {}", - client_socket, - inet_ntoa(client_addr.sin_addr), - (int)ntohs(client_addr.sin_port)); + log::info("Client socket fd: {}, IP address: {}, port: {}", client_socket, + inet_ntoa(client_addr.sin_addr), (int)ntohs(client_addr.sin_port)); return 0; } @@ -182,10 +182,8 @@ int SnoopLoggerSocket::AcceptIncomingConnection(int listen_socket, int& client_s void SnoopLoggerSocket::InitializeClientSocket(int client_socket) { /* When a new client connects, we have to send the btsnoop file header. This * allows a decoder to treat the session as a new, valid btsnoop file. */ - Write( - client_socket, - reinterpret_cast(&SnoopLoggerCommon::kBtSnoopFileHeader), - sizeof(SnoopLoggerCommon::FileHeaderType)); + Write(client_socket, reinterpret_cast(&SnoopLoggerCommon::kBtSnoopFileHeader), + sizeof(SnoopLoggerCommon::FileHeaderType)); } void SnoopLoggerSocket::ClientSocketConnected(int client_socket) { @@ -201,9 +199,7 @@ bool SnoopLoggerSocket::WaitForClientSocketConnected() { return IsClientSocketConnected(); } -bool SnoopLoggerSocket::IsClientSocketConnected() const { - return client_socket_ != INVALID_FD; -} +bool SnoopLoggerSocket::IsClientSocketConnected() const { return client_socket_ != INVALID_FD; } int SnoopLoggerSocket::CreateSocket() { log::debug(""); diff --git a/system/gd/hal/snoop_logger_socket.h b/system/gd/hal/snoop_logger_socket.h index 3adcb281e10..b9684721383 100644 --- a/system/gd/hal/snoop_logger_socket.h +++ b/system/gd/hal/snoop_logger_socket.h @@ -30,12 +30,12 @@ namespace bluetooth { namespace hal { class SnoopLoggerSocket { - public: +public: static constexpr int DEFAULT_LOCALHOST_ = 0x7F000001; static constexpr int DEFAULT_LISTEN_PORT_ = 8872; - SnoopLoggerSocket( - SyscallWrapperInterface* syscall_if, int address = DEFAULT_LOCALHOST_, int port = DEFAULT_LISTEN_PORT_); + SnoopLoggerSocket(SyscallWrapperInterface* syscall_if, int address = DEFAULT_LOCALHOST_, + int port = DEFAULT_LISTEN_PORT_); SnoopLoggerSocket(const SnoopLoggerSocket&) = delete; SnoopLoggerSocket& operator=(const SnoopLoggerSocket&) = delete; virtual ~SnoopLoggerSocket(); @@ -57,7 +57,7 @@ class SnoopLoggerSocket { SyscallWrapperInterface* GetSyscallWrapperInterface() const; - private: +private: // Pointer to syscall interface SyscallWrapperInterface* syscall_if_; diff --git a/system/gd/hal/snoop_logger_socket_interface.h b/system/gd/hal/snoop_logger_socket_interface.h index acf7ba6d651..221476916c1 100644 --- a/system/gd/hal/snoop_logger_socket_interface.h +++ b/system/gd/hal/snoop_logger_socket_interface.h @@ -24,7 +24,7 @@ namespace bluetooth { namespace hal { class SnoopLoggerSocketInterface { - public: +public: virtual ~SnoopLoggerSocketInterface() = default; virtual void Write(const void* data, size_t length) = 0; diff --git a/system/gd/hal/snoop_logger_socket_test.cc b/system/gd/hal/snoop_logger_socket_test.cc index 6659585e244..6d34fd94aef 100644 --- a/system/gd/hal/snoop_logger_socket_test.cc +++ b/system/gd/hal/snoop_logger_socket_test.cc @@ -38,7 +38,7 @@ using bluetooth::hal::SyscallWrapperMock; static constexpr int INVALID_FD = -1; class SnoopLoggerSocketModuleTest : public Test { - protected: +protected: SnoopLoggerSocketModuleTest() : sls(&mock) {} void InitializeCommunicationsSuccess(SnoopLoggerSocket& sls, SyscallWrapperMock& mock) { @@ -47,10 +47,10 @@ class SnoopLoggerSocketModuleTest : public Test { fds[1] = write_fd; return 0; })); - ON_CALL(mock, Socket).WillByDefault((Return(fd))); - ON_CALL(mock, Setsockopt(Eq(fd), _, _, _, _)).WillByDefault((Return(0))); - ON_CALL(mock, Bind(Eq(fd), _, _)).WillByDefault((Return(0))); - ON_CALL(mock, Listen(Eq(fd), _)).WillByDefault((Return(0))); + ON_CALL(mock, Socket).WillByDefault(Return(fd)); + ON_CALL(mock, Setsockopt(Eq(fd), _, _, _, _)).WillByDefault(Return(0)); + ON_CALL(mock, Bind(Eq(fd), _, _)).WillByDefault(Return(0)); + ON_CALL(mock, Listen(Eq(fd), _)).WillByDefault(Return(0)); EXPECT_CALL(mock, FDZero); EXPECT_CALL(mock, Pipe2(_, _)); @@ -88,12 +88,10 @@ TEST_F(SnoopLoggerSocketModuleTest, test_Constructor_GetSyscallWrapperInterface) TEST_F(SnoopLoggerSocketModuleTest, test_Destructor_implicit_cleanup) {} -TEST_F(SnoopLoggerSocketModuleTest, test_Cleanup_explicit) { - sls.Cleanup(); -} +TEST_F(SnoopLoggerSocketModuleTest, test_Cleanup_explicit) { sls.Cleanup(); } TEST_F(SnoopLoggerSocketModuleTest, test_CreateSocket_fail_on_Socket) { - ON_CALL(mock, Socket(_, _, _)).WillByDefault((Return(-1))); + ON_CALL(mock, Socket(_, _, _)).WillByDefault(Return(-1)); EXPECT_CALL(mock, Socket).Times(1); EXPECT_CALL(mock, GetErrno); @@ -101,8 +99,8 @@ TEST_F(SnoopLoggerSocketModuleTest, test_CreateSocket_fail_on_Socket) { } TEST_F(SnoopLoggerSocketModuleTest, test_CreateSocket_fail_on_Setsockopt) { - ON_CALL(mock, Socket(_, _, _)).WillByDefault((Return(fd))); - ON_CALL(mock, Setsockopt(_, _, _, _, _)).WillByDefault((Return(-1))); + ON_CALL(mock, Socket(_, _, _)).WillByDefault(Return(fd)); + ON_CALL(mock, Setsockopt(_, _, _, _, _)).WillByDefault(Return(-1)); EXPECT_CALL(mock, Socket); EXPECT_CALL(mock, Setsockopt); @@ -114,9 +112,9 @@ TEST_F(SnoopLoggerSocketModuleTest, test_CreateSocket_fail_on_Setsockopt) { } TEST_F(SnoopLoggerSocketModuleTest, test_CreateSocket_fail_on_Bind) { - ON_CALL(mock, Socket(_, _, _)).WillByDefault((Return(fd))); - ON_CALL(mock, Setsockopt(_, _, _, _, _)).WillByDefault((Return(0))); - ON_CALL(mock, Bind(_, _, _)).WillByDefault((Return(-1))); + ON_CALL(mock, Socket(_, _, _)).WillByDefault(Return(fd)); + ON_CALL(mock, Setsockopt(_, _, _, _, _)).WillByDefault(Return(0)); + ON_CALL(mock, Bind(_, _, _)).WillByDefault(Return(-1)); EXPECT_CALL(mock, Socket); EXPECT_CALL(mock, Setsockopt); @@ -129,10 +127,10 @@ TEST_F(SnoopLoggerSocketModuleTest, test_CreateSocket_fail_on_Bind) { } TEST_F(SnoopLoggerSocketModuleTest, test_CreateSocket_fail_on_Listen) { - ON_CALL(mock, Socket(_, _, _)).WillByDefault((Return(fd))); - ON_CALL(mock, Setsockopt(_, _, _, _, _)).WillByDefault((Return(0))); - ON_CALL(mock, Bind(_, _, _)).WillByDefault((Return(0))); - ON_CALL(mock, Listen(_, _)).WillByDefault((Return(-1))); + ON_CALL(mock, Socket(_, _, _)).WillByDefault(Return(fd)); + ON_CALL(mock, Setsockopt(_, _, _, _, _)).WillByDefault(Return(0)); + ON_CALL(mock, Bind(_, _, _)).WillByDefault(Return(0)); + ON_CALL(mock, Listen(_, _)).WillByDefault(Return(-1)); EXPECT_CALL(mock, Socket); EXPECT_CALL(mock, Setsockopt); @@ -146,10 +144,10 @@ TEST_F(SnoopLoggerSocketModuleTest, test_CreateSocket_fail_on_Listen) { } TEST_F(SnoopLoggerSocketModuleTest, test_CreateSocket_success) { - ON_CALL(mock, Socket(_, _, _)).WillByDefault((Return(fd))); - ON_CALL(mock, Setsockopt(_, _, _, _, _)).WillByDefault((Return(0))); - ON_CALL(mock, Bind(_, _, _)).WillByDefault((Return(0))); - ON_CALL(mock, Listen(_, _)).WillByDefault((Return(0))); + ON_CALL(mock, Socket(_, _, _)).WillByDefault(Return(fd)); + ON_CALL(mock, Setsockopt(_, _, _, _, _)).WillByDefault(Return(0)); + ON_CALL(mock, Bind(_, _, _)).WillByDefault(Return(0)); + ON_CALL(mock, Listen(_, _)).WillByDefault(Return(0)); EXPECT_CALL(mock, Socket); EXPECT_CALL(mock, Setsockopt); @@ -168,8 +166,8 @@ TEST_F(SnoopLoggerSocketModuleTest, test_Write_fd_invalid_fd) { TEST_F(SnoopLoggerSocketModuleTest, test_Write_fd_fail_on_Send_ECONNRESET) { char data[10]; - ON_CALL(mock, Send(_, _, _, _)).WillByDefault((Return(-1))); - ON_CALL(mock, GetErrno()).WillByDefault((Return(ECONNRESET))); + ON_CALL(mock, Send(_, _, _, _)).WillByDefault(Return(-1)); + ON_CALL(mock, GetErrno()).WillByDefault(Return(ECONNRESET)); EXPECT_CALL(mock, Send(Eq(fd), Eq(data), Eq(sizeof(data)), _)); EXPECT_CALL(mock, Close(Eq(fd))); @@ -182,8 +180,8 @@ TEST_F(SnoopLoggerSocketModuleTest, test_Write_fd_fail_on_Send_ECONNRESET) { TEST_F(SnoopLoggerSocketModuleTest, test_Write_fd_fail_on_Send_EINVAL) { char data[10]; - ON_CALL(mock, Send(_, _, _, _)).WillByDefault((Return(-1))); - ON_CALL(mock, GetErrno()).WillByDefault((Return(EINVAL))); + ON_CALL(mock, Send(_, _, _, _)).WillByDefault(Return(-1)); + ON_CALL(mock, GetErrno()).WillByDefault(Return(EINVAL)); EXPECT_CALL(mock, Send(Eq(fd), Eq(data), Eq(sizeof(data)), _)); EXPECT_CALL(mock, GetErrno).Times(2); @@ -224,16 +222,16 @@ TEST_F(SnoopLoggerSocketModuleTest, test_Write_fd_fail_on_Send_EINTR) { int intr_count = 5; ON_CALL(mock, Send) - .WillByDefault( - Invoke([&](int /* fd */, const void* /* buf */, size_t /* n */, int /* flags */) { - if (intr_count > 0) { - intr_count--; - errno = EINTR; - return -1; - } - errno = 0; - return 0; - })); + .WillByDefault( + Invoke([&](int /* fd */, const void* /* buf */, size_t /* n */, int /* flags */) { + if (intr_count > 0) { + intr_count--; + errno = EINTR; + return -1; + } + errno = 0; + return 0; + })); EXPECT_CALL(mock, Send(Eq(fd), Eq(data), Eq(sizeof(data)), _)).Times(intr_count + 1); @@ -305,18 +303,16 @@ TEST_F(SnoopLoggerSocketModuleTest, test_AcceptIncomingConnection_fail_on_accept int intr_count = 5; ON_CALL(mock, Accept(Eq(fd), _, _, _)) - .WillByDefault(Invoke([&](int /* fd */, - struct sockaddr* /* addr */, - socklen_t* /* addr_len */, - int /* flags */) { - if (intr_count > 0) { - intr_count--; - errno = EINTR; - return -1; - } - errno = 0; - return client_fd; - })); + .WillByDefault(Invoke([&](int /* fd */, struct sockaddr* /* addr */, + socklen_t* /* addr_len */, int /* flags */) { + if (intr_count > 0) { + intr_count--; + errno = EINTR; + return -1; + } + errno = 0; + return client_fd; + })); EXPECT_CALL(mock, Accept(Eq(fd), _, _, _)).Times(intr_count + 1); // 5 intr + 1 with errno = 0 EXPECT_CALL(mock, GetErrno); @@ -387,8 +383,8 @@ TEST_F(SnoopLoggerSocketModuleTest, test_InitializeCommunications_success) { } TEST_F(SnoopLoggerSocketModuleTest, test_ProcessIncomingRequest_fail_on_Select_EINTR) { - ON_CALL(mock, Select).WillByDefault((Return(-1))); - ON_CALL(mock, GetErrno()).WillByDefault((Return(EINTR))); + ON_CALL(mock, Select).WillByDefault(Return(-1)); + ON_CALL(mock, GetErrno()).WillByDefault(Return(EINTR)); EXPECT_CALL(mock, Select); EXPECT_CALL(mock, GetErrno).Times(2); @@ -396,8 +392,8 @@ TEST_F(SnoopLoggerSocketModuleTest, test_ProcessIncomingRequest_fail_on_Select_E } TEST_F(SnoopLoggerSocketModuleTest, test_ProcessIncomingRequest_fail_on_Select_EINVAL) { - ON_CALL(mock, Select).WillByDefault((Return(-1))); - ON_CALL(mock, GetErrno()).WillByDefault((Return(EINVAL))); + ON_CALL(mock, Select).WillByDefault(Return(-1)); + ON_CALL(mock, GetErrno()).WillByDefault(Return(EINVAL)); EXPECT_CALL(mock, Select); EXPECT_CALL(mock, GetErrno).Times(2); @@ -405,7 +401,7 @@ TEST_F(SnoopLoggerSocketModuleTest, test_ProcessIncomingRequest_fail_on_Select_E } TEST_F(SnoopLoggerSocketModuleTest, test_ProcessIncomingRequest_no_fds) { - ON_CALL(mock, Select).WillByDefault((Return(0))); + ON_CALL(mock, Select).WillByDefault(Return(0)); EXPECT_CALL(mock, Select); ASSERT_TRUE(sls.ProcessIncomingRequest()); @@ -414,9 +410,9 @@ TEST_F(SnoopLoggerSocketModuleTest, test_ProcessIncomingRequest_no_fds) { TEST_F(SnoopLoggerSocketModuleTest, test_ProcessIncomingRequest_FDIsSet_false) { ASSERT_NO_FATAL_FAILURE(InitializeCommunicationsSuccess(sls, mock)); - ON_CALL(mock, Select).WillByDefault((Return(0))); - ON_CALL(mock, FDIsSet(fd, _)).WillByDefault((Return(false))); - ON_CALL(mock, FDIsSet(listen_fd, _)).WillByDefault((Return(false))); + ON_CALL(mock, Select).WillByDefault(Return(0)); + ON_CALL(mock, FDIsSet(fd, _)).WillByDefault(Return(false)); + ON_CALL(mock, FDIsSet(listen_fd, _)).WillByDefault(Return(false)); EXPECT_CALL(mock, Select); EXPECT_CALL(mock, FDIsSet(Eq(fd), _)); @@ -427,9 +423,9 @@ TEST_F(SnoopLoggerSocketModuleTest, test_ProcessIncomingRequest_FDIsSet_false) { TEST_F(SnoopLoggerSocketModuleTest, test_ProcessIncomingRequest_signal_close) { ASSERT_NO_FATAL_FAILURE(InitializeCommunicationsSuccess(sls, mock)); - ON_CALL(mock, Select).WillByDefault((Return(0))); - ON_CALL(mock, FDIsSet(fd, _)).WillByDefault((Return(false))); - ON_CALL(mock, FDIsSet(listen_fd, _)).WillByDefault((Return(true))); + ON_CALL(mock, Select).WillByDefault(Return(0)); + ON_CALL(mock, FDIsSet(fd, _)).WillByDefault(Return(false)); + ON_CALL(mock, FDIsSet(listen_fd, _)).WillByDefault(Return(true)); EXPECT_CALL(mock, Select); EXPECT_CALL(mock, FDIsSet(Eq(fd), _)); @@ -437,12 +433,13 @@ TEST_F(SnoopLoggerSocketModuleTest, test_ProcessIncomingRequest_signal_close) { ASSERT_FALSE(sls.ProcessIncomingRequest()); } -TEST_F(SnoopLoggerSocketModuleTest, test_ProcessIncomingRequest_signal_incoming_connection_fail_on_accept_exit) { +TEST_F(SnoopLoggerSocketModuleTest, + test_ProcessIncomingRequest_signal_incoming_connection_fail_on_accept_exit) { ASSERT_NO_FATAL_FAILURE(InitializeCommunicationsSuccess(sls, mock)); - ON_CALL(mock, Select).WillByDefault((Return(0))); - ON_CALL(mock, FDIsSet(fd, _)).WillByDefault((Return(true))); - ON_CALL(mock, FDIsSet(listen_fd, _)).WillByDefault((Return(false))); + ON_CALL(mock, Select).WillByDefault(Return(0)); + ON_CALL(mock, FDIsSet(fd, _)).WillByDefault(Return(true)); + ON_CALL(mock, FDIsSet(listen_fd, _)).WillByDefault(Return(false)); ON_CALL(mock, Accept(fd, _, _, _)).WillByDefault(Return(INVALID_FD)); ON_CALL(mock, GetErrno()).WillByDefault(Return(EINVAL)); @@ -454,12 +451,13 @@ TEST_F(SnoopLoggerSocketModuleTest, test_ProcessIncomingRequest_signal_incoming_ ASSERT_FALSE(sls.ProcessIncomingRequest()); } -TEST_F(SnoopLoggerSocketModuleTest, test_ProcessIncomingRequest_signal_incoming_connection_fail_on_accept_continue) { +TEST_F(SnoopLoggerSocketModuleTest, + test_ProcessIncomingRequest_signal_incoming_connection_fail_on_accept_continue) { ASSERT_NO_FATAL_FAILURE(InitializeCommunicationsSuccess(sls, mock)); - ON_CALL(mock, Select).WillByDefault((Return(0))); - ON_CALL(mock, FDIsSet(fd, _)).WillByDefault((Return(true))); - ON_CALL(mock, FDIsSet(listen_fd, _)).WillByDefault((Return(false))); + ON_CALL(mock, Select).WillByDefault(Return(0)); + ON_CALL(mock, FDIsSet(fd, _)).WillByDefault(Return(true)); + ON_CALL(mock, FDIsSet(listen_fd, _)).WillByDefault(Return(false)); ON_CALL(mock, Accept(fd, _, _, _)).WillByDefault(Return(INVALID_FD)); ON_CALL(mock, GetErrno()).WillByDefault(Return(ENOMEM)); @@ -471,14 +469,15 @@ TEST_F(SnoopLoggerSocketModuleTest, test_ProcessIncomingRequest_signal_incoming_ ASSERT_TRUE(sls.ProcessIncomingRequest()); } -TEST_F(SnoopLoggerSocketModuleTest, test_ProcessIncomingRequest_signal_incoming_connection_success) { +TEST_F(SnoopLoggerSocketModuleTest, + test_ProcessIncomingRequest_signal_incoming_connection_success) { ASSERT_NO_FATAL_FAILURE(InitializeCommunicationsSuccess(sls, mock)); int client_fd = 23; - ON_CALL(mock, Select).WillByDefault((Return(0))); - ON_CALL(mock, FDIsSet(fd, _)).WillByDefault((Return(true))); - ON_CALL(mock, FDIsSet(listen_fd, _)).WillByDefault((Return(false))); + ON_CALL(mock, Select).WillByDefault(Return(0)); + ON_CALL(mock, FDIsSet(fd, _)).WillByDefault(Return(true)); + ON_CALL(mock, FDIsSet(listen_fd, _)).WillByDefault(Return(false)); ON_CALL(mock, Accept(fd, _, _, _)).WillByDefault(Return(client_fd)); ON_CALL(mock, GetErrno()).WillByDefault(Return(0)); @@ -501,7 +500,7 @@ TEST_F(SnoopLoggerSocketModuleTest, test_NotifySocketListener_no_fd) { TEST_F(SnoopLoggerSocketModuleTest, test_NotifySocketListener_fail_on_write) { ASSERT_NO_FATAL_FAILURE(InitializeCommunicationsSuccess(sls, mock)); - ON_CALL(mock, Write).WillByDefault((Return(-1))); + ON_CALL(mock, Write).WillByDefault(Return(-1)); EXPECT_CALL(mock, Write(write_fd, _, _)).Times(1); ASSERT_EQ(sls.NotifySocketListener(), -1); @@ -530,7 +529,7 @@ TEST_F(SnoopLoggerSocketModuleTest, test_NotifySocketListener_fail_on_write_EINT TEST_F(SnoopLoggerSocketModuleTest, test_NotifySocketListener_success) { ASSERT_NO_FATAL_FAILURE(InitializeCommunicationsSuccess(sls, mock)); - ON_CALL(mock, Write).WillByDefault((Return(0))); + ON_CALL(mock, Write).WillByDefault(Return(0)); EXPECT_CALL(mock, Write(write_fd, _, _)); ASSERT_EQ(sls.NotifySocketListener(), 0); diff --git a/system/gd/hal/snoop_logger_socket_thread.cc b/system/gd/hal/snoop_logger_socket_thread.cc index 3ea45bbaa34..890f5881a9d 100644 --- a/system/gd/hal/snoop_logger_socket_thread.cc +++ b/system/gd/hal/snoop_logger_socket_thread.cc @@ -44,15 +44,14 @@ SnoopLoggerSocketThread::SnoopLoggerSocketThread(std::unique_ptr SnoopLoggerSocketThread::Start() { log::debug(""); std::promise thread_started; auto future = thread_started.get_future(); - listen_thread_ = std::make_unique(&SnoopLoggerSocketThread::Run, this, std::move(thread_started)); + listen_thread_ = std::make_unique(&SnoopLoggerSocketThread::Run, this, + std::move(thread_started)); stop_thread_ = false; return std::move(future); } @@ -73,13 +72,9 @@ void SnoopLoggerSocketThread::Write(const void* data, size_t length) { socket_->Write(data, length); } -bool SnoopLoggerSocketThread::ThreadIsRunning() const { - return listen_thread_running_; -} +bool SnoopLoggerSocketThread::ThreadIsRunning() const { return listen_thread_running_; } -SnoopLoggerSocket* SnoopLoggerSocketThread::GetSocket() { - return socket_.get(); -} +SnoopLoggerSocket* SnoopLoggerSocketThread::GetSocket() { return socket_.get(); } void SnoopLoggerSocketThread::Run(std::promise thread_started) { log::debug(""); diff --git a/system/gd/hal/snoop_logger_socket_thread.h b/system/gd/hal/snoop_logger_socket_thread.h index 9f4187c11c6..bdf62b720db 100644 --- a/system/gd/hal/snoop_logger_socket_thread.h +++ b/system/gd/hal/snoop_logger_socket_thread.h @@ -31,7 +31,7 @@ namespace bluetooth { namespace hal { class SnoopLoggerSocketThread : public SnoopLoggerSocketInterface { - public: +public: SnoopLoggerSocketThread(std::unique_ptr&& socket); SnoopLoggerSocketThread(const SnoopLoggerSocket&) = delete; SnoopLoggerSocketThread& operator=(const SnoopLoggerSocketThread&) = delete; @@ -44,7 +44,7 @@ class SnoopLoggerSocketThread : public SnoopLoggerSocketInterface { SnoopLoggerSocket* GetSocket(); - private: +private: void Run(std::promise thread_started); std::unique_ptr socket_; diff --git a/system/gd/hal/snoop_logger_socket_thread_test.cc b/system/gd/hal/snoop_logger_socket_thread_test.cc index 37be6a84336..557f0d97d8a 100644 --- a/system/gd/hal/snoop_logger_socket_thread_test.cc +++ b/system/gd/hal/snoop_logger_socket_thread_test.cc @@ -166,7 +166,8 @@ TEST_F(SnoopLoggerSocketThreadModuleTest, socket_send_before_connect_test) { thread_start_future.wait(); ASSERT_TRUE(thread_start_future.get()); - char test_data[] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0f}; + char test_data[] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, + 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0f}; sls.Write(test_data, sizeof(test_data)); // // Create a TCP socket file descriptor @@ -257,7 +258,8 @@ TEST_F(SnoopLoggerSocketThreadModuleTest, socket_send_recv_test) { RUN_NO_INTR(ret = connect(socket_fd, (struct sockaddr*)&addr, sizeof(addr))); ASSERT_TRUE(ret == 0); - char test_data[] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0f}; + char test_data[] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, + 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0f}; char recv_buf1[sizeof(SnoopLoggerCommon::FileHeaderType)]; char recv_buf2[sizeof(test_data)]; @@ -274,7 +276,8 @@ TEST_F(SnoopLoggerSocketThreadModuleTest, socket_send_recv_test) { a.wait(); bytes_read = a.get(); - ASSERT_TRUE(std::memcmp(recv_buf1, &SnoopLoggerCommon::kBtSnoopFileHeader, sizeof(recv_buf1)) == 0); + ASSERT_TRUE(std::memcmp(recv_buf1, &SnoopLoggerCommon::kBtSnoopFileHeader, sizeof(recv_buf1)) == + 0); ASSERT_EQ(bytes_read, static_cast(sizeof(test_data))); ASSERT_TRUE(std::memcmp(recv_buf2, test_data, bytes_read) == 0); diff --git a/system/gd/hal/snoop_logger_test.cc b/system/gd/hal/snoop_logger_test.cc index d40ce6ab316..71382bbdb6c 100644 --- a/system/gd/hal/snoop_logger_test.cc +++ b/system/gd/hal/snoop_logger_test.cc @@ -45,69 +45,60 @@ using namespace bluetooth; namespace { std::vector kInformationRequest = { - 0xfe, - 0x2e, - 0x0a, - 0x00, - 0x06, - 0x00, - 0x01, - 0x00, - 0x0a, - 0x02, - 0x02, - 0x00, - 0x02, - 0x00, + 0xfe, 0x2e, 0x0a, 0x00, 0x06, 0x00, 0x01, 0x00, 0x0a, 0x02, 0x02, 0x00, 0x02, 0x00, }; -std::vector kSdpConnectionRequest = { - 0x08, 0x20, 0x0c, 0x00, 0x08, 0x00, 0x01, 0x00, 0x02, 0x0c, 0x04, 0x00, 0x01, 0x00, 0x44, 0x00}; +std::vector kSdpConnectionRequest = {0x08, 0x20, 0x0c, 0x00, 0x08, 0x00, 0x01, 0x00, + 0x02, 0x0c, 0x04, 0x00, 0x01, 0x00, 0x44, 0x00}; -std::vector kAvdtpSuspend = {0x02, 0x02, 0x00, 0x07, 0x00, 0x03, 0x00, 0x8d, 0x00, 0x90, 0x09, 0x04}; +std::vector kAvdtpSuspend = {0x02, 0x02, 0x00, 0x07, 0x00, 0x03, + 0x00, 0x8d, 0x00, 0x90, 0x09, 0x04}; -std::vector kHfpAtNrec0 = {0x02, 0x02, 0x20, 0x13, 0x00, 0x0f, 0x00, 0x41, 0x00, 0x09, 0xff, 0x15, - 0x01, 0x41, 0x54, 0x2b, 0x4e, 0x52, 0x45, 0x43, 0x3d, 0x30, 0x0d, 0x5c}; +std::vector kHfpAtNrec0 = {0x02, 0x02, 0x20, 0x13, 0x00, 0x0f, 0x00, 0x41, + 0x00, 0x09, 0xff, 0x15, 0x01, 0x41, 0x54, 0x2b, + 0x4e, 0x52, 0x45, 0x43, 0x3d, 0x30, 0x0d, 0x5c}; -std::vector kQualcommConnectionRequest = {0xdc, 0x2e, 0x54, 0x00, 0x50, 0x00, 0xff, 0x00, 0x00, 0x0a, - 0x0f, 0x09, 0x01, 0x00, 0x5c, 0x93, 0x01, 0x00, 0x42, 0x00}; +std::vector kQualcommConnectionRequest = {0xdc, 0x2e, 0x54, 0x00, 0x50, 0x00, 0xff, + 0x00, 0x00, 0x0a, 0x0f, 0x09, 0x01, 0x00, + 0x5c, 0x93, 0x01, 0x00, 0x42, 0x00}; std::vector kA2dpMediaPacket = { - 0x0b, 0x20, 0x3a, 0x00, 0x36, 0x00, 0x40, 0xa0, 0x80, 0xe0, 0x07, 0x7f, 0x00, 0x1e, 0x08, 0x00, - 0x00, 0x00, 0x00, 0x02, 0x47, 0xfc, 0x00, 0x00, 0xb0, 0x90, 0x80, 0x03, 0x00, 0x20, 0x21, 0x11, - 0x45, 0x00, 0x14, 0x50, 0x01, 0x46, 0xf0, 0x81, 0x0a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, - 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e, + 0x0b, 0x20, 0x3a, 0x00, 0x36, 0x00, 0x40, 0xa0, 0x80, 0xe0, 0x07, 0x7f, 0x00, + 0x1e, 0x08, 0x00, 0x00, 0x00, 0x00, 0x02, 0x47, 0xfc, 0x00, 0x00, 0xb0, 0x90, + 0x80, 0x03, 0x00, 0x20, 0x21, 0x11, 0x45, 0x00, 0x14, 0x50, 0x01, 0x46, 0xf0, + 0x81, 0x0a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, + 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e, }; std::vector kTestData = { - {0x02, 0x20, 0x11, 0x00, 0x0d, 0x00, 0x41, 0x00, 0x9d, 0xef, 0x35, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - {0x02, 0x00, 0x12, 0x00, 0x0e, 0x00, 0x40, 0x00, 0x9f, 0xff, 0x3f, - 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - {0x02, 0x20, 0x11, 0x00, 0x0d, 0x00, 0x41, 0x00, 0x9d, 0xef, 0x85, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - {0x02, 0x00, 0x12, 0x00, 0x0e, 0x00, 0x40, 0x00, 0x9f, 0xff, 0x1f, - 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - {0x02, 0x20, 0x11, 0x00, 0x0d, 0x00, 0x41, 0x00, 0x9d, 0xef, 0x99, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - {0x02, 0x00, 0x13, 0x00, 0x0f, 0x00, 0x40, 0x00, 0x9f, 0xff, 0xc6, 0x01, - 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - {0x02, 0x20, 0x11, 0x00, 0x0d, 0x00, 0x41, 0x00, 0x9d, 0xef, 0x99, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - {0x02, 0x00, 0x12, 0x00, 0x0e, 0x00, 0x40, 0x00, 0x9f, 0xff, 0x1f, - 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - {0x02, 0x20, 0x12, 0x00, 0x0e, 0x00, 0x41, 0x00, 0x9d, 0xff, 0x01, - 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - {0x02, 0x00, 0x12, 0x00, 0x0e, 0x00, 0x40, 0x00, 0x9f, 0xff, 0x8f, - 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - {0x02, 0x20, 0x11, 0x00, 0x0d, 0x00, 0x41, 0x00, 0x9d, 0xef, 0x89, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - {0x02, 0x00, 0x12, 0x00, 0x0e, 0x00, 0x40, 0x00, 0x9f, 0xff, 0x1f, - 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - {0x02, 0x20, 0x11, 0x00, 0x0d, 0x00, 0x41, 0x00, 0x9d, 0xef, 0x43, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - {0x02, 0x00, 0x12, 0x00, 0x0e, 0x00, 0x40, 0x00, 0x9f, 0xff, 0x11, - 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}; + {0x02, 0x20, 0x11, 0x00, 0x0d, 0x00, 0x41, 0x00, 0x9d, 0xef, 0x35, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, + {0x02, 0x00, 0x12, 0x00, 0x0e, 0x00, 0x40, 0x00, 0x9f, 0xff, 0x3f, + 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, + {0x02, 0x20, 0x11, 0x00, 0x0d, 0x00, 0x41, 0x00, 0x9d, 0xef, 0x85, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, + {0x02, 0x00, 0x12, 0x00, 0x0e, 0x00, 0x40, 0x00, 0x9f, 0xff, 0x1f, + 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, + {0x02, 0x20, 0x11, 0x00, 0x0d, 0x00, 0x41, 0x00, 0x9d, 0xef, 0x99, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, + {0x02, 0x00, 0x13, 0x00, 0x0f, 0x00, 0x40, 0x00, 0x9f, 0xff, 0xc6, 0x01, + 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, + {0x02, 0x20, 0x11, 0x00, 0x0d, 0x00, 0x41, 0x00, 0x9d, 0xef, 0x99, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, + {0x02, 0x00, 0x12, 0x00, 0x0e, 0x00, 0x40, 0x00, 0x9f, 0xff, 0x1f, + 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, + {0x02, 0x20, 0x12, 0x00, 0x0e, 0x00, 0x41, 0x00, 0x9d, 0xff, 0x01, + 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, + {0x02, 0x00, 0x12, 0x00, 0x0e, 0x00, 0x40, 0x00, 0x9f, 0xff, 0x8f, + 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, + {0x02, 0x20, 0x11, 0x00, 0x0d, 0x00, 0x41, 0x00, 0x9d, 0xef, 0x89, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, + {0x02, 0x00, 0x12, 0x00, 0x0e, 0x00, 0x40, 0x00, 0x9f, 0xff, 0x1f, + 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, + {0x02, 0x20, 0x11, 0x00, 0x0d, 0x00, 0x41, 0x00, 0x9d, 0xef, 0x43, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, + {0x02, 0x00, 0x12, 0x00, 0x0e, 0x00, 0x40, 0x00, 0x9f, 0xff, 0x11, + 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}; } // namespace @@ -117,58 +108,37 @@ using namespace std::chrono_literals; // Expose protected constructor for test class TestSnoopLoggerModule : public SnoopLogger { - public: - TestSnoopLoggerModule( - std::string snoop_log_path, - std::string snooz_log_path, - size_t max_packets_per_file, - const std::string& btsnoop_mode, - bool qualcomm_debug_log_enabled, - bool snoop_log_persists) - : SnoopLogger( - std::move(snoop_log_path), - std::move(snooz_log_path), - max_packets_per_file, - SnoopLogger::GetMaxPacketsPerBuffer(), - btsnoop_mode, - qualcomm_debug_log_enabled, - 20ms, - 5ms, - snoop_log_persists) {} - - std::string ToString() const override { - return std::string("TestSnoopLoggerModule"); - } +public: + TestSnoopLoggerModule(std::string snoop_log_path, std::string snooz_log_path, + size_t max_packets_per_file, const std::string& btsnoop_mode, + bool qualcomm_debug_log_enabled, bool snoop_log_persists) + : SnoopLogger(std::move(snoop_log_path), std::move(snooz_log_path), max_packets_per_file, + SnoopLogger::GetMaxPacketsPerBuffer(), btsnoop_mode, qualcomm_debug_log_enabled, + 20ms, 5ms, snoop_log_persists) {} - void CallGetDumpsysData(flatbuffers::FlatBufferBuilder* builder) { - GetDumpsysData(builder); - } + std::string ToString() const override { return std::string("TestSnoopLoggerModule"); } - SnoopLoggerSocketThread* GetSocketThread() { - return snoop_logger_socket_thread_.get(); - } + void CallGetDumpsysData(flatbuffers::FlatBufferBuilder* builder) { GetDumpsysData(builder); } - static uint32_t GetL2capHeaderSize() { - return L2CAP_HEADER_SIZE; - } + SnoopLoggerSocketThread* GetSocketThread() { return snoop_logger_socket_thread_.get(); } - static size_t GetMaxFilteredSize() { - return MAX_HCI_ACL_LEN - PACKET_TYPE_LENGTH; - } + static uint32_t GetL2capHeaderSize() { return L2CAP_HEADER_SIZE; } + + static size_t GetMaxFilteredSize() { return MAX_HCI_ACL_LEN - PACKET_TYPE_LENGTH; } }; class SnoopLoggerModuleTest : public Test { - public: +public: flatbuffers::FlatBufferBuilder* builder_; TestModuleRegistry* test_registry; - protected: +protected: void SetUp() override { const testing::TestInfo* const test_info = - testing::UnitTest::GetInstance()->current_test_info(); + testing::UnitTest::GetInstance()->current_test_info(); - log::debug( - "Setup for test {} in test suite {}.", test_info->name(), test_info->test_suite_name()); + log::debug("Setup for test {} in test suite {}.", test_info->name(), + test_info->test_suite_name()); const std::filesystem::path temp_dir_ = std::filesystem::temp_directory_path(); temp_snoop_log_ = temp_dir_ / (std::string(test_info->name()) + "_btsnoop_hci.log"); @@ -176,9 +146,9 @@ class SnoopLoggerModuleTest : public Test { temp_snooz_log_ = temp_dir_ / (std::string(test_info->name()) + "_btsnooz_hci.log"); temp_snooz_log_last_ = temp_dir_ / (std::string(test_info->name()) + "_btsnooz_hci.log.last"); temp_snoop_log_filtered = - temp_dir_ / (std::string(test_info->name()) + "_btsnoop_hci.log.filtered"); + temp_dir_ / (std::string(test_info->name()) + "_btsnoop_hci.log.filtered"); temp_snoop_log_filtered_last = - temp_dir_ / (std::string(test_info->name()) + "_btsnoop_hci.log.filtered.last"); + temp_dir_ / (std::string(test_info->name()) + "_btsnoop_hci.log.filtered.last"); builder_ = new flatbuffers::FlatBufferBuilder(); DeleteSnoopLogFiles(); @@ -200,9 +170,9 @@ class SnoopLoggerModuleTest : public Test { delete test_registry; const testing::TestInfo* const test_info = - testing::UnitTest::GetInstance()->current_test_info(); - log::debug( - "TearDown for test {} in test suite {}.", test_info->name(), test_info->test_suite_name()); + testing::UnitTest::GetInstance()->current_test_info(); + log::debug("TearDown for test {} in test suite {}.", test_info->name(), + test_info->test_suite_name()); } std::filesystem::path temp_snoop_log_; @@ -212,7 +182,7 @@ class SnoopLoggerModuleTest : public Test { std::filesystem::path temp_snoop_log_filtered; std::filesystem::path temp_snoop_log_filtered_last; - private: +private: void DeleteSnoopLogFiles() { if (std::filesystem::exists(temp_snoop_log_)) { ASSERT_TRUE(std::filesystem::remove(temp_snoop_log_)); @@ -237,13 +207,9 @@ class SnoopLoggerModuleTest : public Test { TEST_F(SnoopLoggerModuleTest, empty_snoop_log_test) { // Actual test - auto* snoop_logger = new TestSnoopLoggerModule( - temp_snoop_log_.string(), - temp_snooz_log_.string(), - 10, - SnoopLogger::kBtSnoopLogModeFull, - false, - false); + auto* snoop_logger = + new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10, + SnoopLogger::kBtSnoopLogModeFull, false, false); test_registry->InjectTestModule(&SnoopLogger::Factory, snoop_logger); test_registry->StopAll(); @@ -255,13 +221,9 @@ TEST_F(SnoopLoggerModuleTest, empty_snoop_log_test) { TEST_F(SnoopLoggerModuleTest, disable_snoop_log_test) { // Actual test - auto* snoop_logger = new TestSnoopLoggerModule( - temp_snoop_log_.string(), - temp_snooz_log_.string(), - 10, - SnoopLogger::kBtSnoopLogModeDisabled, - false, - false); + auto* snoop_logger = + new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10, + SnoopLogger::kBtSnoopLogModeDisabled, false, false); test_registry->InjectTestModule(&SnoopLogger::Factory, snoop_logger); test_registry->StopAll(); @@ -273,45 +235,39 @@ TEST_F(SnoopLoggerModuleTest, disable_snoop_log_test) { TEST_F(SnoopLoggerModuleTest, capture_one_packet_test) { // Actual test - auto* snoop_logger = new TestSnoopLoggerModule( - temp_snoop_log_.string(), - temp_snooz_log_.string(), - 10, - SnoopLogger::kBtSnoopLogModeFull, - false, - false); + auto* snoop_logger = + new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10, + SnoopLogger::kBtSnoopLogModeFull, false, false); test_registry->InjectTestModule(&SnoopLogger::Factory, snoop_logger); - snoop_logger->Capture(kInformationRequest, SnoopLogger::Direction::OUTGOING, SnoopLogger::PacketType::CMD); + snoop_logger->Capture(kInformationRequest, SnoopLogger::Direction::OUTGOING, + SnoopLogger::PacketType::CMD); test_registry->StopAll(); // Verify states after test ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_)); ASSERT_FALSE(std::filesystem::exists(temp_snoop_log_last_)); - ASSERT_EQ( - std::filesystem::file_size(temp_snoop_log_), - sizeof(SnoopLoggerCommon::FileHeaderType) + sizeof(SnoopLogger::PacketHeaderType) + kInformationRequest.size()); + ASSERT_EQ(std::filesystem::file_size(temp_snoop_log_), + sizeof(SnoopLoggerCommon::FileHeaderType) + sizeof(SnoopLogger::PacketHeaderType) + + kInformationRequest.size()); } TEST_F(SnoopLoggerModuleTest, capture_hci_cmd_btsnooz_test) { // Actual test - auto* snoop_logger = new TestSnoopLoggerModule( - temp_snoop_log_.string(), - temp_snooz_log_.string(), - 10, - SnoopLogger::kBtSnoopLogModeDisabled, - false, - false); + auto* snoop_logger = + new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10, + SnoopLogger::kBtSnoopLogModeDisabled, false, false); test_registry->InjectTestModule(&SnoopLogger::Factory, snoop_logger); - snoop_logger->Capture(kInformationRequest, SnoopLogger::Direction::OUTGOING, SnoopLogger::PacketType::CMD); + snoop_logger->Capture(kInformationRequest, SnoopLogger::Direction::OUTGOING, + SnoopLogger::PacketType::CMD); snoop_logger->CallGetDumpsysData(builder_); ASSERT_TRUE(std::filesystem::exists(temp_snooz_log_)); - ASSERT_EQ( - std::filesystem::file_size(temp_snooz_log_), - sizeof(SnoopLoggerCommon::FileHeaderType) + sizeof(SnoopLogger::PacketHeaderType) + kInformationRequest.size()); + ASSERT_EQ(std::filesystem::file_size(temp_snooz_log_), + sizeof(SnoopLoggerCommon::FileHeaderType) + sizeof(SnoopLogger::PacketHeaderType) + + kInformationRequest.size()); test_registry->StopAll(); @@ -323,22 +279,19 @@ TEST_F(SnoopLoggerModuleTest, capture_hci_cmd_btsnooz_test) { TEST_F(SnoopLoggerModuleTest, capture_l2cap_signal_packet_btsnooz_test) { // Actual test - auto* snoop_logger = new TestSnoopLoggerModule( - temp_snoop_log_.string(), - temp_snooz_log_.string(), - 10, - SnoopLogger::kBtSnoopLogModeDisabled, - false, - false); + auto* snoop_logger = + new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10, + SnoopLogger::kBtSnoopLogModeDisabled, false, false); test_registry->InjectTestModule(&SnoopLogger::Factory, snoop_logger); - snoop_logger->Capture(kSdpConnectionRequest, SnoopLogger::Direction::OUTGOING, SnoopLogger::PacketType::ACL); + snoop_logger->Capture(kSdpConnectionRequest, SnoopLogger::Direction::OUTGOING, + SnoopLogger::PacketType::ACL); snoop_logger->CallGetDumpsysData(builder_); ASSERT_TRUE(std::filesystem::exists(temp_snooz_log_)); - ASSERT_EQ( - std::filesystem::file_size(temp_snooz_log_), - sizeof(SnoopLoggerCommon::FileHeaderType) + sizeof(SnoopLogger::PacketHeaderType) + kSdpConnectionRequest.size()); + ASSERT_EQ(std::filesystem::file_size(temp_snooz_log_), + sizeof(SnoopLoggerCommon::FileHeaderType) + sizeof(SnoopLogger::PacketHeaderType) + + kSdpConnectionRequest.size()); test_registry->StopAll(); @@ -350,22 +303,19 @@ TEST_F(SnoopLoggerModuleTest, capture_l2cap_signal_packet_btsnooz_test) { TEST_F(SnoopLoggerModuleTest, capture_l2cap_short_data_packet_btsnooz_test) { // Actual test - auto* snoop_logger = new TestSnoopLoggerModule( - temp_snoop_log_.string(), - temp_snooz_log_.string(), - 10, - SnoopLogger::kBtSnoopLogModeDisabled, - false, - false); + auto* snoop_logger = + new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10, + SnoopLogger::kBtSnoopLogModeDisabled, false, false); test_registry->InjectTestModule(&SnoopLogger::Factory, snoop_logger); - snoop_logger->Capture(kAvdtpSuspend, SnoopLogger::Direction::OUTGOING, SnoopLogger::PacketType::ACL); + snoop_logger->Capture(kAvdtpSuspend, SnoopLogger::Direction::OUTGOING, + SnoopLogger::PacketType::ACL); snoop_logger->CallGetDumpsysData(builder_); ASSERT_TRUE(std::filesystem::exists(temp_snooz_log_)); - ASSERT_EQ( - std::filesystem::file_size(temp_snooz_log_), - sizeof(SnoopLoggerCommon::FileHeaderType) + sizeof(SnoopLogger::PacketHeaderType) + kAvdtpSuspend.size()); + ASSERT_EQ(std::filesystem::file_size(temp_snooz_log_), + sizeof(SnoopLoggerCommon::FileHeaderType) + sizeof(SnoopLogger::PacketHeaderType) + + kAvdtpSuspend.size()); test_registry->StopAll(); @@ -377,22 +327,18 @@ TEST_F(SnoopLoggerModuleTest, capture_l2cap_short_data_packet_btsnooz_test) { TEST_F(SnoopLoggerModuleTest, capture_l2cap_long_data_packet_btsnooz_test) { // Actual test - auto* snoop_logger = new TestSnoopLoggerModule( - temp_snoop_log_.string(), - temp_snooz_log_.string(), - 10, - SnoopLogger::kBtSnoopLogModeDisabled, - false, - false); + auto* snoop_logger = + new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10, + SnoopLogger::kBtSnoopLogModeDisabled, false, false); test_registry->InjectTestModule(&SnoopLogger::Factory, snoop_logger); - snoop_logger->Capture(kHfpAtNrec0, SnoopLogger::Direction::OUTGOING, SnoopLogger::PacketType::ACL); + snoop_logger->Capture(kHfpAtNrec0, SnoopLogger::Direction::OUTGOING, + SnoopLogger::PacketType::ACL); snoop_logger->CallGetDumpsysData(builder_); ASSERT_TRUE(std::filesystem::exists(temp_snooz_log_)); - ASSERT_EQ( - std::filesystem::file_size(temp_snooz_log_), - sizeof(SnoopLoggerCommon::FileHeaderType) + sizeof(SnoopLogger::PacketHeaderType) + 14); + ASSERT_EQ(std::filesystem::file_size(temp_snooz_log_), + sizeof(SnoopLoggerCommon::FileHeaderType) + sizeof(SnoopLogger::PacketHeaderType) + 14); test_registry->StopAll(); @@ -404,23 +350,18 @@ TEST_F(SnoopLoggerModuleTest, capture_l2cap_long_data_packet_btsnooz_test) { TEST_F(SnoopLoggerModuleTest, snoop_log_persists) { // Actual test - auto* snoop_logger = new TestSnoopLoggerModule( - temp_snoop_log_.string(), - temp_snooz_log_.string(), - 10, - SnoopLogger::kBtSnoopLogModeDisabled, - false, - true); + auto* snoop_logger = + new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10, + SnoopLogger::kBtSnoopLogModeDisabled, false, true); test_registry->InjectTestModule(&SnoopLogger::Factory, snoop_logger); - snoop_logger->Capture( - kHfpAtNrec0, SnoopLogger::Direction::OUTGOING, SnoopLogger::PacketType::ACL); + snoop_logger->Capture(kHfpAtNrec0, SnoopLogger::Direction::OUTGOING, + SnoopLogger::PacketType::ACL); snoop_logger->CallGetDumpsysData(builder_); ASSERT_TRUE(std::filesystem::exists(temp_snooz_log_)); - ASSERT_EQ( - std::filesystem::file_size(temp_snooz_log_), - sizeof(SnoopLoggerCommon::FileHeaderType) + sizeof(SnoopLogger::PacketHeaderType) + 14); + ASSERT_EQ(std::filesystem::file_size(temp_snooz_log_), + sizeof(SnoopLoggerCommon::FileHeaderType) + sizeof(SnoopLogger::PacketHeaderType) + 14); test_registry->StopAll(); ASSERT_TRUE(std::filesystem::exists(temp_snooz_log_)); @@ -429,21 +370,17 @@ TEST_F(SnoopLoggerModuleTest, snoop_log_persists) { void sync_handler(bluetooth::os::Handler* handler) { std::promise promise; auto future = promise.get_future(); - handler->Post(bluetooth::common::BindOnce( - &std::promise::set_value, bluetooth::common::Unretained(&promise))); + handler->Post(bluetooth::common::BindOnce(&std::promise::set_value, + bluetooth::common::Unretained(&promise))); auto future_status = future.wait_for(std::chrono::seconds(1)); ASSERT_EQ(future_status, std::future_status::ready); } TEST_F(SnoopLoggerModuleTest, delete_old_snooz_log_files) { // Actual test - auto* snoop_logger = new TestSnoopLoggerModule( - temp_snoop_log_.string(), - temp_snooz_log_.string(), - 10, - SnoopLogger::kBtSnoopLogModeDisabled, - false, - false); + auto* snoop_logger = + new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10, + SnoopLogger::kBtSnoopLogModeDisabled, false, false); test_registry->InjectTestModule(&SnoopLogger::Factory, snoop_logger); std::filesystem::create_directories(temp_snooz_log_); @@ -455,7 +392,8 @@ TEST_F(SnoopLoggerModuleTest, delete_old_snooz_log_files) { handler->Post(bluetooth::common::BindOnce(fake_timerfd_advance, 15)); sync_handler(handler); handler->Post(bluetooth::common::BindOnce( - [](std::filesystem::path path) { ASSERT_FALSE(std::filesystem::exists(path)); }, temp_snooz_log_)); + [](std::filesystem::path path) { ASSERT_FALSE(std::filesystem::exists(path)); }, + temp_snooz_log_)); sync_handler(handler); test_registry->StopAll(); @@ -465,68 +403,56 @@ TEST_F(SnoopLoggerModuleTest, delete_old_snooz_log_files) { TEST_F(SnoopLoggerModuleTest, rotate_file_at_new_session_test) { // Start once { - auto* snoop_logger = new TestSnoopLoggerModule( - temp_snoop_log_.string(), - temp_snooz_log_.string(), - 10, - SnoopLogger::kBtSnoopLogModeFull, - false, - false); + auto* snoop_logger = + new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10, + SnoopLogger::kBtSnoopLogModeFull, false, false); test_registry->InjectTestModule(&SnoopLogger::Factory, snoop_logger); - snoop_logger->Capture( - kInformationRequest, SnoopLogger::Direction::OUTGOING, SnoopLogger::PacketType::CMD); + snoop_logger->Capture(kInformationRequest, SnoopLogger::Direction::OUTGOING, + SnoopLogger::PacketType::CMD); test_registry->StopAll(); } // Verify states after test ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_)); ASSERT_FALSE(std::filesystem::exists(temp_snoop_log_last_)); - ASSERT_EQ( - std::filesystem::file_size(temp_snoop_log_), - sizeof(SnoopLoggerCommon::FileHeaderType) + sizeof(SnoopLogger::PacketHeaderType) + kInformationRequest.size()); + ASSERT_EQ(std::filesystem::file_size(temp_snoop_log_), + sizeof(SnoopLoggerCommon::FileHeaderType) + sizeof(SnoopLogger::PacketHeaderType) + + kInformationRequest.size()); // Start again { - auto* snoop_logger = new TestSnoopLoggerModule( - temp_snoop_log_.string(), - temp_snooz_log_.string(), - 10, - SnoopLogger::kBtSnoopLogModeFull, - false, - false); + auto* snoop_logger = + new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10, + SnoopLogger::kBtSnoopLogModeFull, false, false); test_registry->InjectTestModule(&SnoopLogger::Factory, snoop_logger); - snoop_logger->Capture( - kInformationRequest, SnoopLogger::Direction::OUTGOING, SnoopLogger::PacketType::CMD); - snoop_logger->Capture( - kInformationRequest, SnoopLogger::Direction::OUTGOING, SnoopLogger::PacketType::CMD); + snoop_logger->Capture(kInformationRequest, SnoopLogger::Direction::OUTGOING, + SnoopLogger::PacketType::CMD); + snoop_logger->Capture(kInformationRequest, SnoopLogger::Direction::OUTGOING, + SnoopLogger::PacketType::CMD); test_registry->StopAll(); } // Verify states after test ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_)); ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_last_)); - ASSERT_EQ( - std::filesystem::file_size(temp_snoop_log_), - sizeof(SnoopLoggerCommon::FileHeaderType) + - (sizeof(SnoopLogger::PacketHeaderType) + kInformationRequest.size()) * 2); - ASSERT_EQ( - std::filesystem::file_size(temp_snoop_log_last_), - sizeof(SnoopLoggerCommon::FileHeaderType) + sizeof(SnoopLogger::PacketHeaderType) + kInformationRequest.size()); + ASSERT_EQ(std::filesystem::file_size(temp_snoop_log_), + sizeof(SnoopLoggerCommon::FileHeaderType) + + (sizeof(SnoopLogger::PacketHeaderType) + kInformationRequest.size()) * 2); + ASSERT_EQ(std::filesystem::file_size(temp_snoop_log_last_), + sizeof(SnoopLoggerCommon::FileHeaderType) + sizeof(SnoopLogger::PacketHeaderType) + + kInformationRequest.size()); } TEST_F(SnoopLoggerModuleTest, rotate_file_after_full_test) { // Actual test - auto* snoop_logger = new TestSnoopLoggerModule( - temp_snoop_log_.string(), - temp_snooz_log_.string(), - 10, - SnoopLogger::kBtSnoopLogModeFull, - false, - false); + auto* snoop_logger = + new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10, + SnoopLogger::kBtSnoopLogModeFull, false, false); test_registry->InjectTestModule(&SnoopLogger::Factory, snoop_logger); for (int i = 0; i < 11; i++) { - snoop_logger->Capture(kInformationRequest, SnoopLogger::Direction::OUTGOING, SnoopLogger::PacketType::CMD); + snoop_logger->Capture(kInformationRequest, SnoopLogger::Direction::OUTGOING, + SnoopLogger::PacketType::CMD); } test_registry->StopAll(); @@ -534,34 +460,27 @@ TEST_F(SnoopLoggerModuleTest, rotate_file_after_full_test) { // Verify states after test ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_)); ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_last_)); - ASSERT_EQ( - std::filesystem::file_size(temp_snoop_log_), - sizeof(SnoopLoggerCommon::FileHeaderType) + - (sizeof(SnoopLogger::PacketHeaderType) + kInformationRequest.size()) * 1); - ASSERT_EQ( - std::filesystem::file_size(temp_snoop_log_last_), - sizeof(SnoopLoggerCommon::FileHeaderType) + - (sizeof(SnoopLogger::PacketHeaderType) + kInformationRequest.size()) * 10); + ASSERT_EQ(std::filesystem::file_size(temp_snoop_log_), + sizeof(SnoopLoggerCommon::FileHeaderType) + + (sizeof(SnoopLogger::PacketHeaderType) + kInformationRequest.size()) * 1); + ASSERT_EQ(std::filesystem::file_size(temp_snoop_log_last_), + sizeof(SnoopLoggerCommon::FileHeaderType) + + (sizeof(SnoopLogger::PacketHeaderType) + kInformationRequest.size()) * 10); } TEST_F(SnoopLoggerModuleTest, qualcomm_debug_log_test) { - auto* snoop_logger = new TestSnoopLoggerModule( - temp_snoop_log_.string(), - temp_snooz_log_.string(), - 10, - SnoopLogger::kBtSnoopLogModeDisabled, - true, - false); + auto* snoop_logger = + new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10, + SnoopLogger::kBtSnoopLogModeDisabled, true, false); test_registry->InjectTestModule(&SnoopLogger::Factory, snoop_logger); - snoop_logger->Capture( - kQualcommConnectionRequest, SnoopLogger::Direction::OUTGOING, SnoopLogger::PacketType::ACL); + snoop_logger->Capture(kQualcommConnectionRequest, SnoopLogger::Direction::OUTGOING, + SnoopLogger::PacketType::ACL); snoop_logger->CallGetDumpsysData(builder_); ASSERT_TRUE(std::filesystem::exists(temp_snooz_log_)); - ASSERT_EQ( - std::filesystem::file_size(temp_snooz_log_), - sizeof(SnoopLoggerCommon::FileHeaderType) + sizeof(SnoopLogger::PacketHeaderType) + - kQualcommConnectionRequest.size()); + ASSERT_EQ(std::filesystem::file_size(temp_snooz_log_), + sizeof(SnoopLoggerCommon::FileHeaderType) + sizeof(SnoopLogger::PacketHeaderType) + + kQualcommConnectionRequest.size()); test_registry->StopAll(); @@ -573,22 +492,18 @@ TEST_F(SnoopLoggerModuleTest, qualcomm_debug_log_test) { TEST_F(SnoopLoggerModuleTest, qualcomm_debug_log_regression_test) { { - auto* snoop_logger = new TestSnoopLoggerModule( - temp_snoop_log_.string(), - temp_snooz_log_.string(), - 10, - SnoopLogger::kBtSnoopLogModeDisabled, - true, - false); + auto* snoop_logger = + new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10, + SnoopLogger::kBtSnoopLogModeDisabled, true, false); test_registry->InjectTestModule(&SnoopLogger::Factory, snoop_logger); - snoop_logger->Capture( - kHfpAtNrec0, SnoopLogger::Direction::OUTGOING, SnoopLogger::PacketType::ACL); + snoop_logger->Capture(kHfpAtNrec0, SnoopLogger::Direction::OUTGOING, + SnoopLogger::PacketType::ACL); snoop_logger->CallGetDumpsysData(builder_); ASSERT_TRUE(std::filesystem::exists(temp_snooz_log_)); ASSERT_EQ( - std::filesystem::file_size(temp_snooz_log_), - sizeof(SnoopLoggerCommon::FileHeaderType) + sizeof(SnoopLogger::PacketHeaderType) + 14); + std::filesystem::file_size(temp_snooz_log_), + sizeof(SnoopLoggerCommon::FileHeaderType) + sizeof(SnoopLogger::PacketHeaderType) + 14); test_registry->StopAll(); } @@ -598,22 +513,18 @@ TEST_F(SnoopLoggerModuleTest, qualcomm_debug_log_regression_test) { ASSERT_FALSE(std::filesystem::exists(temp_snooz_log_)); { - auto* snoop_logger = new TestSnoopLoggerModule( - temp_snoop_log_.string(), - temp_snooz_log_.string(), - 10, - SnoopLogger::kBtSnoopLogModeDisabled, - false, - false); + auto* snoop_logger = + new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10, + SnoopLogger::kBtSnoopLogModeDisabled, false, false); test_registry->InjectTestModule(&SnoopLogger::Factory, snoop_logger); - snoop_logger->Capture( - kQualcommConnectionRequest, SnoopLogger::Direction::OUTGOING, SnoopLogger::PacketType::ACL); + snoop_logger->Capture(kQualcommConnectionRequest, SnoopLogger::Direction::OUTGOING, + SnoopLogger::PacketType::ACL); snoop_logger->CallGetDumpsysData(builder_); ASSERT_TRUE(std::filesystem::exists(temp_snooz_log_)); ASSERT_EQ( - std::filesystem::file_size(temp_snooz_log_), - sizeof(SnoopLoggerCommon::FileHeaderType) + sizeof(SnoopLogger::PacketHeaderType) + 14); + std::filesystem::file_size(temp_snooz_log_), + sizeof(SnoopLoggerCommon::FileHeaderType) + sizeof(SnoopLogger::PacketHeaderType) + 14); test_registry->StopAll(); } @@ -657,19 +568,15 @@ TEST_F(SnoopLoggerModuleTest, a2dp_packets_filtered_test) { uint16_t local_cid = 0x0001; uint16_t remote_cid = 0xa040; - ASSERT_TRUE( - bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileA2dpProperty, "true")); + ASSERT_TRUE(bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileA2dpProperty, + "true")); auto filter_a2dp_property = - bluetooth::os::GetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileA2dpProperty); + bluetooth::os::GetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileA2dpProperty); ASSERT_TRUE(filter_a2dp_property && filter_a2dp_property.value() == "true"); - auto* snoop_logger = new TestSnoopLoggerModule( - temp_snoop_log_.string(), - temp_snooz_log_.string(), - 10, - SnoopLogger::kBtSnoopLogModeFiltered, - false, - false); + auto* snoop_logger = + new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10, + SnoopLogger::kBtSnoopLogModeFiltered, false, false); TestModuleRegistry test_registry; test_registry.InjectTestModule(&SnoopLogger::Factory, snoop_logger); @@ -677,22 +584,21 @@ TEST_F(SnoopLoggerModuleTest, a2dp_packets_filtered_test) { // Simulate A2dp Media channel setup snoop_logger->AddA2dpMediaChannel(conn_handle, local_cid, remote_cid); - snoop_logger->Capture( - kA2dpMediaPacket, SnoopLogger::Direction::OUTGOING, SnoopLogger::PacketType::ACL); + snoop_logger->Capture(kA2dpMediaPacket, SnoopLogger::Direction::OUTGOING, + SnoopLogger::PacketType::ACL); ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered)); test_registry.StopAll(); - ASSERT_TRUE( - bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileA2dpProperty, "false")); + ASSERT_TRUE(bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileA2dpProperty, + "false")); // Verify states after test ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered)); // Should filter packet - ASSERT_EQ( - std::filesystem::file_size(temp_snoop_log_filtered), - sizeof(SnoopLoggerCommon::FileHeaderType)); + ASSERT_EQ(std::filesystem::file_size(temp_snoop_log_filtered), + sizeof(SnoopLoggerCommon::FileHeaderType)); ASSERT_TRUE(std::filesystem::remove(temp_snoop_log_filtered)); } @@ -702,19 +608,15 @@ TEST_F(SnoopLoggerModuleTest, a2dp_packets_filtered_negative_test) { uint16_t local_cid = 0x0001; uint16_t remote_cid = 0xa040; - ASSERT_TRUE( - bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileA2dpProperty, "true")); + ASSERT_TRUE(bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileA2dpProperty, + "true")); auto filter_a2dp_property = - bluetooth::os::GetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileA2dpProperty); + bluetooth::os::GetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileA2dpProperty); ASSERT_TRUE(filter_a2dp_property && filter_a2dp_property.value() == "true"); - auto* snoop_logger = new TestSnoopLoggerModule( - temp_snoop_log_.string(), - temp_snooz_log_.string(), - 10, - SnoopLogger::kBtSnoopLogModeFiltered, - false, - false); + auto* snoop_logger = + new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10, + SnoopLogger::kBtSnoopLogModeFiltered, false, false); TestModuleRegistry test_registry; test_registry.InjectTestModule(&SnoopLogger::Factory, snoop_logger); @@ -723,47 +625,42 @@ TEST_F(SnoopLoggerModuleTest, a2dp_packets_filtered_negative_test) { snoop_logger->AddA2dpMediaChannel(conn_handle, local_cid, remote_cid); snoop_logger->RemoveA2dpMediaChannel(conn_handle, local_cid); - snoop_logger->Capture( - kA2dpMediaPacket, SnoopLogger::Direction::OUTGOING, SnoopLogger::PacketType::ACL); + snoop_logger->Capture(kA2dpMediaPacket, SnoopLogger::Direction::OUTGOING, + SnoopLogger::PacketType::ACL); ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered)); test_registry.StopAll(); - ASSERT_TRUE( - bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileA2dpProperty, "false")); + ASSERT_TRUE(bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileA2dpProperty, + "false")); // Verify states after test ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered)); // Should not filter - ASSERT_EQ( - std::filesystem::file_size(temp_snoop_log_filtered), - sizeof(SnoopLoggerCommon::FileHeaderType) + sizeof(SnoopLogger::PacketHeaderType) + - kA2dpMediaPacket.size()); + ASSERT_EQ(std::filesystem::file_size(temp_snoop_log_filtered), + sizeof(SnoopLoggerCommon::FileHeaderType) + sizeof(SnoopLogger::PacketHeaderType) + + kA2dpMediaPacket.size()); ASSERT_TRUE(std::filesystem::remove(temp_snoop_log_filtered)); } TEST_F(SnoopLoggerModuleTest, headers_filtered_test) { ASSERT_TRUE( - bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterHeadersProperty, "true")); + bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterHeadersProperty, "true")); auto filter_headers_property = - bluetooth::os::GetSystemProperty(SnoopLogger::kBtSnoopLogFilterHeadersProperty); + bluetooth::os::GetSystemProperty(SnoopLogger::kBtSnoopLogFilterHeadersProperty); ASSERT_TRUE(filter_headers_property && filter_headers_property.value() == "true"); - auto* snoop_logger = new TestSnoopLoggerModule( - temp_snoop_log_.string(), - temp_snooz_log_.string(), - 10, - SnoopLogger::kBtSnoopLogModeFiltered, - false, - false); + auto* snoop_logger = + new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10, + SnoopLogger::kBtSnoopLogModeFiltered, false, false); TestModuleRegistry test_registry; test_registry.InjectTestModule(&SnoopLogger::Factory, snoop_logger); std::vector kAclPacket = { - 0x0b, 0x20, 0x18, 0x00, 0x14, 0x00, 0x44, 0x00, 0x1b, 0x2f, 0x21, 0x41, 0x54, 0x2b, - 0x43, 0x4d, 0x45, 0x52, 0x3d, 0x33, 0x2c, 0x30, 0x2c, 0x30, 0x2c, 0x31, 0x0d, 0x8f, + 0x0b, 0x20, 0x18, 0x00, 0x14, 0x00, 0x44, 0x00, 0x1b, 0x2f, 0x21, 0x41, 0x54, 0x2b, + 0x43, 0x4d, 0x45, 0x52, 0x3d, 0x33, 0x2c, 0x30, 0x2c, 0x30, 0x2c, 0x31, 0x0d, 0x8f, }; snoop_logger->Capture(kAclPacket, SnoopLogger::Direction::INCOMING, SnoopLogger::PacketType::ACL); @@ -773,13 +670,12 @@ TEST_F(SnoopLoggerModuleTest, headers_filtered_test) { test_registry.StopAll(); ASSERT_TRUE( - bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterHeadersProperty, "false")); + bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterHeadersProperty, "false")); // Verify states after test ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered)); - log::info( - "const size: {}", - (int)(sizeof(SnoopLoggerCommon::FileHeaderType) + sizeof(SnoopLogger::PacketHeaderType))); + log::info("const size: {}", (int)(sizeof(SnoopLoggerCommon::FileHeaderType) + + sizeof(SnoopLogger::PacketHeaderType))); // Packet should be filtered const size_t file_size = (size_t)std::filesystem::file_size(temp_snoop_log_filtered); @@ -796,20 +692,16 @@ TEST_F(SnoopLoggerModuleTest, rfcomm_channel_filtered_sabme_ua_test) { uint16_t local_cid = 0x0044; uint16_t remote_cid = 0x3040; - ASSERT_TRUE(bluetooth::os::SetSystemProperty( - SnoopLogger::kBtSnoopLogFilterProfileRfcommProperty, "true")); + ASSERT_TRUE(bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileRfcommProperty, + "true")); auto filter_rfcomm_property = - bluetooth::os::GetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileRfcommProperty); + bluetooth::os::GetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileRfcommProperty); ASSERT_TRUE(filter_rfcomm_property); ASSERT_TRUE(filter_rfcomm_property.value() == "true"); - auto* snoop_logger = new TestSnoopLoggerModule( - temp_snoop_log_.string(), - temp_snooz_log_.string(), - 10, - SnoopLogger::kBtSnoopLogModeFiltered, - false, - false); + auto* snoop_logger = + new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10, + SnoopLogger::kBtSnoopLogModeFiltered, false, false); TestModuleRegistry test_registry; test_registry.InjectTestModule(&SnoopLogger::Factory, snoop_logger); @@ -817,33 +709,32 @@ TEST_F(SnoopLoggerModuleTest, rfcomm_channel_filtered_sabme_ua_test) { // Simulate Rfcomm channel snoop_logger->AddRfcommL2capChannel(conn_handle, local_cid, remote_cid); std::vector kRfcommSabme = { - 0x0b, 0x20, 0x18, 0x00, 0x14, 0x00, 0x44, 0x00, 0x1b, 0x2f, 0x21, 0x41, 0x54, 0x2b, - 0x43, 0x4d, 0x45, 0x52, 0x3d, 0x33, 0x2c, 0x30, 0x2c, 0x30, 0x2c, 0x31, 0x0d, 0x8f, + 0x0b, 0x20, 0x18, 0x00, 0x14, 0x00, 0x44, 0x00, 0x1b, 0x2f, 0x21, 0x41, 0x54, 0x2b, + 0x43, 0x4d, 0x45, 0x52, 0x3d, 0x33, 0x2c, 0x30, 0x2c, 0x30, 0x2c, 0x31, 0x0d, 0x8f, }; std::vector kRfcommUa = { - 0x0b, 0x20, 0x18, 0x00, 0x14, 0x00, 0x44, 0x00, 0x1b, 0x63, 0x21, 0x41, 0x54, 0x2b, - 0x43, 0x4d, 0x45, 0x52, 0x3d, 0x33, 0x2c, 0x30, 0x2c, 0x30, 0x2c, 0x31, 0x0d, 0x8f, + 0x0b, 0x20, 0x18, 0x00, 0x14, 0x00, 0x44, 0x00, 0x1b, 0x63, 0x21, 0x41, 0x54, 0x2b, + 0x43, 0x4d, 0x45, 0x52, 0x3d, 0x33, 0x2c, 0x30, 0x2c, 0x30, 0x2c, 0x31, 0x0d, 0x8f, }; - snoop_logger->Capture( - kRfcommSabme, SnoopLogger::Direction::INCOMING, SnoopLogger::PacketType::ACL); + snoop_logger->Capture(kRfcommSabme, SnoopLogger::Direction::INCOMING, + SnoopLogger::PacketType::ACL); snoop_logger->Capture(kRfcommUa, SnoopLogger::Direction::INCOMING, SnoopLogger::PacketType::ACL); snoop_logger->ClearL2capAcceptlist(conn_handle, local_cid, remote_cid); ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered)); test_registry.StopAll(); - ASSERT_TRUE(bluetooth::os::SetSystemProperty( - SnoopLogger::kBtSnoopLogFilterProfileRfcommProperty, "false")); + ASSERT_TRUE(bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileRfcommProperty, + "false")); // Verify states after test ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered)); // Packets should not be filtered because because they are SAMBE and UA events. - ASSERT_EQ( - std::filesystem::file_size(temp_snoop_log_filtered), - sizeof(SnoopLoggerCommon::FileHeaderType) + 2 * sizeof(SnoopLogger::PacketHeaderType) + - kRfcommSabme.size() + kRfcommUa.size()); + ASSERT_EQ(std::filesystem::file_size(temp_snoop_log_filtered), + sizeof(SnoopLoggerCommon::FileHeaderType) + 2 * sizeof(SnoopLogger::PacketHeaderType) + + kRfcommSabme.size() + kRfcommUa.size()); ASSERT_TRUE(std::filesystem::remove(temp_snoop_log_filtered)); } @@ -855,20 +746,16 @@ TEST_F(SnoopLoggerModuleTest, rfcomm_channel_filtered_acceptlisted_dlci_test) { uint8_t dlci = 0x04; uint8_t dlci_byte = dlci << 2; - ASSERT_TRUE(bluetooth::os::SetSystemProperty( - SnoopLogger::kBtSnoopLogFilterProfileRfcommProperty, "true")); + ASSERT_TRUE(bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileRfcommProperty, + "true")); auto filter_rfcomm_property = - bluetooth::os::GetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileRfcommProperty); + bluetooth::os::GetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileRfcommProperty); ASSERT_TRUE(filter_rfcomm_property); ASSERT_TRUE(filter_rfcomm_property.value() == "true"); - auto* snoop_logger = new TestSnoopLoggerModule( - temp_snoop_log_.string(), - temp_snooz_log_.string(), - 10, - SnoopLogger::kBtSnoopLogModeFiltered, - false, - false); + auto* snoop_logger = + new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10, + SnoopLogger::kBtSnoopLogModeFiltered, false, false); TestModuleRegistry test_registry; test_registry.InjectTestModule(&SnoopLogger::Factory, snoop_logger); @@ -878,28 +765,27 @@ TEST_F(SnoopLoggerModuleTest, rfcomm_channel_filtered_acceptlisted_dlci_test) { snoop_logger->AcceptlistRfcommDlci(conn_handle, local_cid, dlci); std::vector kRfcommDlci = { - 0x0b, 0x20, 0x12, 0x00, 0x0e, 0x00, 0x41, 0x00, dlci_byte, 0xef, 0x15, - 0x83, 0x11, 0x06, 0xf0, 0x07, 0x00, 0x9d, 0x02, 0x00, 0x07, 0x70, + 0x0b, 0x20, 0x12, 0x00, 0x0e, 0x00, 0x41, 0x00, dlci_byte, 0xef, 0x15, + 0x83, 0x11, 0x06, 0xf0, 0x07, 0x00, 0x9d, 0x02, 0x00, 0x07, 0x70, }; - snoop_logger->Capture( - kRfcommDlci, SnoopLogger::Direction::INCOMING, SnoopLogger::PacketType::ACL); + snoop_logger->Capture(kRfcommDlci, SnoopLogger::Direction::INCOMING, + SnoopLogger::PacketType::ACL); snoop_logger->ClearL2capAcceptlist(conn_handle, local_cid, remote_cid); ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered)); test_registry.StopAll(); - ASSERT_TRUE(bluetooth::os::SetSystemProperty( - SnoopLogger::kBtSnoopLogFilterProfileRfcommProperty, "false")); + ASSERT_TRUE(bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileRfcommProperty, + "false")); // Verify states after test ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered)); // Packet should not be filtered because DLCI acceptlisted - ASSERT_EQ( - std::filesystem::file_size(temp_snoop_log_filtered), - sizeof(SnoopLoggerCommon::FileHeaderType) + sizeof(SnoopLogger::PacketHeaderType) + - kRfcommDlci.size()); + ASSERT_EQ(std::filesystem::file_size(temp_snoop_log_filtered), + sizeof(SnoopLoggerCommon::FileHeaderType) + sizeof(SnoopLogger::PacketHeaderType) + + kRfcommDlci.size()); ASSERT_TRUE(std::filesystem::remove(temp_snoop_log_filtered)); } @@ -911,20 +797,16 @@ TEST_F(SnoopLoggerModuleTest, rfcomm_channel_filtered_not_acceptlisted_dlci_test uint8_t dlci = 0x04; uint8_t dlci_byte = dlci << 2; - ASSERT_TRUE(bluetooth::os::SetSystemProperty( - SnoopLogger::kBtSnoopLogFilterProfileRfcommProperty, "true")); + ASSERT_TRUE(bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileRfcommProperty, + "true")); auto filter_rfcomm_property = - bluetooth::os::GetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileRfcommProperty); + bluetooth::os::GetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileRfcommProperty); ASSERT_TRUE(filter_rfcomm_property); ASSERT_TRUE(filter_rfcomm_property.value() == "true"); - auto* snoop_logger = new TestSnoopLoggerModule( - temp_snoop_log_.string(), - temp_snooz_log_.string(), - 10, - SnoopLogger::kBtSnoopLogModeFiltered, - false, - false); + auto* snoop_logger = + new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10, + SnoopLogger::kBtSnoopLogModeFiltered, false, false); TestModuleRegistry test_registry; test_registry.InjectTestModule(&SnoopLogger::Factory, snoop_logger); @@ -933,29 +815,28 @@ TEST_F(SnoopLoggerModuleTest, rfcomm_channel_filtered_not_acceptlisted_dlci_test snoop_logger->AddRfcommL2capChannel(conn_handle, local_cid, remote_cid); std::vector kRfcommDlci = { - 0x0b, 0x20, 0x12, 0x00, 0x0e, 0x00, 0x41, 0x00, dlci_byte, 0xef, 0x15, - 0x83, 0x11, 0x06, 0xf0, 0x07, 0x00, 0x9d, 0x02, 0x00, 0x07, 0x70, + 0x0b, 0x20, 0x12, 0x00, 0x0e, 0x00, 0x41, 0x00, dlci_byte, 0xef, 0x15, + 0x83, 0x11, 0x06, 0xf0, 0x07, 0x00, 0x9d, 0x02, 0x00, 0x07, 0x70, }; - snoop_logger->Capture( - kRfcommDlci, SnoopLogger::Direction::INCOMING, SnoopLogger::PacketType::ACL); + snoop_logger->Capture(kRfcommDlci, SnoopLogger::Direction::INCOMING, + SnoopLogger::PacketType::ACL); snoop_logger->ClearL2capAcceptlist(conn_handle, local_cid, remote_cid); ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered)); test_registry.StopAll(); - ASSERT_TRUE(bluetooth::os::SetSystemProperty( - SnoopLogger::kBtSnoopLogFilterProfileRfcommProperty, "false")); + ASSERT_TRUE(bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileRfcommProperty, + "false")); // Verify states after test ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered)); // Packet should be filtered because DLCI not acceptlisted - ASSERT_EQ( - std::filesystem::file_size(temp_snoop_log_filtered), - sizeof(SnoopLoggerCommon::FileHeaderType) + sizeof(SnoopLogger::PacketHeaderType) + - TestSnoopLoggerModule::GetL2capHeaderSize()); + ASSERT_EQ(std::filesystem::file_size(temp_snoop_log_filtered), + sizeof(SnoopLoggerCommon::FileHeaderType) + sizeof(SnoopLogger::PacketHeaderType) + + TestSnoopLoggerModule::GetL2capHeaderSize()); ASSERT_TRUE(std::filesystem::remove(temp_snoop_log_filtered)); } @@ -965,48 +846,43 @@ TEST_F(SnoopLoggerModuleTest, rfcomm_channel_filtered_not_acceptlisted_l2cap_cha uint16_t local_cid = 0x0041; uint16_t remote_cid = 0x3040; - ASSERT_TRUE(bluetooth::os::SetSystemProperty( - SnoopLogger::kBtSnoopLogFilterProfileRfcommProperty, "true")); + ASSERT_TRUE(bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileRfcommProperty, + "true")); auto filter_rfcomm_property = - bluetooth::os::GetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileRfcommProperty); + bluetooth::os::GetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileRfcommProperty); ASSERT_TRUE(filter_rfcomm_property); ASSERT_TRUE(filter_rfcomm_property.value() == "true"); - auto* snoop_logger = new TestSnoopLoggerModule( - temp_snoop_log_.string(), - temp_snooz_log_.string(), - 10, - SnoopLogger::kBtSnoopLogModeFiltered, - false, - false); + auto* snoop_logger = + new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10, + SnoopLogger::kBtSnoopLogModeFiltered, false, false); TestModuleRegistry test_registry; test_registry.InjectTestModule(&SnoopLogger::Factory, snoop_logger); std::vector kRfcommL2capChannel = { - 0x0b, 0x20, 0x12, 0x00, 0x0e, 0x00, 0x41, 0x00, 0x00, 0xef, 0x15, - 0x83, 0x11, 0x06, 0xf0, 0x07, 0x00, 0x9d, 0x02, 0x00, 0x07, 0x70, + 0x0b, 0x20, 0x12, 0x00, 0x0e, 0x00, 0x41, 0x00, 0x00, 0xef, 0x15, + 0x83, 0x11, 0x06, 0xf0, 0x07, 0x00, 0x9d, 0x02, 0x00, 0x07, 0x70, }; - snoop_logger->Capture( - kRfcommL2capChannel, SnoopLogger::Direction::INCOMING, SnoopLogger::PacketType::ACL); + snoop_logger->Capture(kRfcommL2capChannel, SnoopLogger::Direction::INCOMING, + SnoopLogger::PacketType::ACL); snoop_logger->ClearL2capAcceptlist(conn_handle, local_cid, remote_cid); ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered)); test_registry.StopAll(); - ASSERT_TRUE(bluetooth::os::SetSystemProperty( - SnoopLogger::kBtSnoopLogFilterProfileRfcommProperty, "false")); + ASSERT_TRUE(bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileRfcommProperty, + "false")); // Verify states after test ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered)); // Packet should be filtered because L2CAP channel not acceptlisted - ASSERT_EQ( - std::filesystem::file_size(temp_snoop_log_filtered), - sizeof(SnoopLoggerCommon::FileHeaderType) + sizeof(SnoopLogger::PacketHeaderType) + - TestSnoopLoggerModule::GetL2capHeaderSize()); + ASSERT_EQ(std::filesystem::file_size(temp_snoop_log_filtered), + sizeof(SnoopLoggerCommon::FileHeaderType) + sizeof(SnoopLogger::PacketHeaderType) + + TestSnoopLoggerModule::GetL2capHeaderSize()); ASSERT_TRUE(std::filesystem::remove(temp_snoop_log_filtered)); } @@ -1016,20 +892,16 @@ TEST_F(SnoopLoggerModuleTest, rfcomm_channel_filtered_acceptlisted_l2cap_channel uint16_t local_cid = 0x0041; uint16_t remote_cid = 0x3040; - ASSERT_TRUE(bluetooth::os::SetSystemProperty( - SnoopLogger::kBtSnoopLogFilterProfileRfcommProperty, "true")); + ASSERT_TRUE(bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileRfcommProperty, + "true")); auto filter_rfcomm_property = - bluetooth::os::GetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileRfcommProperty); + bluetooth::os::GetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileRfcommProperty); ASSERT_TRUE(filter_rfcomm_property); ASSERT_TRUE(filter_rfcomm_property.value() == "true"); - auto* snoop_logger = new TestSnoopLoggerModule( - temp_snoop_log_.string(), - temp_snooz_log_.string(), - 10, - SnoopLogger::kBtSnoopLogModeFiltered, - false, - false); + auto* snoop_logger = + new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10, + SnoopLogger::kBtSnoopLogModeFiltered, false, false); TestModuleRegistry test_registry; test_registry.InjectTestModule(&SnoopLogger::Factory, snoop_logger); @@ -1037,29 +909,28 @@ TEST_F(SnoopLoggerModuleTest, rfcomm_channel_filtered_acceptlisted_l2cap_channel snoop_logger->AcceptlistL2capChannel(conn_handle, local_cid, remote_cid); std::vector kRfcommL2capChannel = { - 0x0b, 0x20, 0x12, 0x00, 0x0e, 0x00, 0x41, 0x00, 0x00, 0xef, 0x15, - 0x83, 0x11, 0x06, 0xf0, 0x07, 0x00, 0x9d, 0x02, 0x00, 0x07, 0x70, + 0x0b, 0x20, 0x12, 0x00, 0x0e, 0x00, 0x41, 0x00, 0x00, 0xef, 0x15, + 0x83, 0x11, 0x06, 0xf0, 0x07, 0x00, 0x9d, 0x02, 0x00, 0x07, 0x70, }; - snoop_logger->Capture( - kRfcommL2capChannel, SnoopLogger::Direction::INCOMING, SnoopLogger::PacketType::ACL); + snoop_logger->Capture(kRfcommL2capChannel, SnoopLogger::Direction::INCOMING, + SnoopLogger::PacketType::ACL); snoop_logger->ClearL2capAcceptlist(conn_handle, local_cid, remote_cid); ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered)); test_registry.StopAll(); - ASSERT_TRUE(bluetooth::os::SetSystemProperty( - SnoopLogger::kBtSnoopLogFilterProfileRfcommProperty, "false")); + ASSERT_TRUE(bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileRfcommProperty, + "false")); // Verify states after test ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered)); // Packet should not be filtered because L2CAP channel acceptlisted - ASSERT_EQ( - std::filesystem::file_size(temp_snoop_log_filtered), - sizeof(SnoopLoggerCommon::FileHeaderType) + sizeof(SnoopLogger::PacketHeaderType) + - kRfcommL2capChannel.size()); + ASSERT_EQ(std::filesystem::file_size(temp_snoop_log_filtered), + sizeof(SnoopLoggerCommon::FileHeaderType) + sizeof(SnoopLogger::PacketHeaderType) + + kRfcommL2capChannel.size()); ASSERT_TRUE(std::filesystem::remove(temp_snoop_log_filtered)); } @@ -1077,32 +948,25 @@ TEST_F(SnoopLoggerModuleTest, profiles_filtered_hfp_hf_test) { const uint16_t HEADER_SIZE = 12; // Set pbap and map filtering modes - ASSERT_TRUE(bluetooth::os::SetSystemProperty( - SnoopLogger::kBtSnoopLogFilterProfilePbapModeProperty, - SnoopLogger::kBtSnoopLogFilterProfileModeMagic)); - auto filterPbapModeProperty = - bluetooth::os::GetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfilePbapModeProperty); ASSERT_TRUE( - filterPbapModeProperty && - (filterPbapModeProperty->find(SnoopLogger::kBtSnoopLogFilterProfileModeMagic) != - std::string::npos)); - ASSERT_TRUE(bluetooth::os::SetSystemProperty( - SnoopLogger::kBtSnoopLogFilterProfileMapModeProperty, - SnoopLogger::kBtSnoopLogFilterProfileModeMagic)); + bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfilePbapModeProperty, + SnoopLogger::kBtSnoopLogFilterProfileModeMagic)); + auto filterPbapModeProperty = + bluetooth::os::GetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfilePbapModeProperty); + ASSERT_TRUE(filterPbapModeProperty && + (filterPbapModeProperty->find(SnoopLogger::kBtSnoopLogFilterProfileModeMagic) != + std::string::npos)); + ASSERT_TRUE(bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileMapModeProperty, + SnoopLogger::kBtSnoopLogFilterProfileModeMagic)); auto filterMapModeProperty = - bluetooth::os::GetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileMapModeProperty); - ASSERT_TRUE( - filterMapModeProperty && - (filterMapModeProperty->find(SnoopLogger::kBtSnoopLogFilterProfileModeMagic) != - std::string::npos)); - - auto* snoop_logger = new TestSnoopLoggerModule( - temp_snoop_log_.string(), - temp_snooz_log_.string(), - 10, - SnoopLogger::kBtSnoopLogModeFiltered, - false, - false); + bluetooth::os::GetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileMapModeProperty); + ASSERT_TRUE(filterMapModeProperty && + (filterMapModeProperty->find(SnoopLogger::kBtSnoopLogFilterProfileModeMagic) != + std::string::npos)); + + auto* snoop_logger = + new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10, + SnoopLogger::kBtSnoopLogModeFiltered, false, false); TestModuleRegistry test_registry; test_registry.InjectTestModule(&SnoopLogger::Factory, snoop_logger); @@ -1111,14 +975,14 @@ TEST_F(SnoopLoggerModuleTest, profiles_filtered_hfp_hf_test) { snoop_logger->SetRfcommPortOpen(conn_handle, local_cid, dlci, profile_uuid_hfp_hf, flow); std::vector kPhoneNumber = { - 0x0b, 0x00, 0x30, 0x00, 0x2c, 0x00, 0x40, 0x30, 0x19, 0xff, 0x4f, 0x01, 0x0d, - 0x0a, 0x2b, 0x43, 0x4c, 0x43, 0x43, 0x3a, 0x20, 0x31, 0x2c, 0x31, 0x2c, 0x34, - 0x2c, 0x30, 0x2c, 0x30, 0x2c, 0x22, 0x2b, 0x39, 0x39, 0x31, 0x32, 0x33, 0x34, - 0x35, 0x36, 0x37, 0x38, 0x39, 0x22, 0x2c, 0x31, 0x34, 0x35, 0x0d, 0x0a, 0x49, + 0x0b, 0x00, 0x30, 0x00, 0x2c, 0x00, 0x40, 0x30, 0x19, 0xff, 0x4f, 0x01, 0x0d, + 0x0a, 0x2b, 0x43, 0x4c, 0x43, 0x43, 0x3a, 0x20, 0x31, 0x2c, 0x31, 0x2c, 0x34, + 0x2c, 0x30, 0x2c, 0x30, 0x2c, 0x22, 0x2b, 0x39, 0x39, 0x31, 0x32, 0x33, 0x34, + 0x35, 0x36, 0x37, 0x38, 0x39, 0x22, 0x2c, 0x31, 0x34, 0x35, 0x0d, 0x0a, 0x49, }; - snoop_logger->Capture( - kPhoneNumber, SnoopLogger::Direction::OUTGOING, SnoopLogger::PacketType::ACL); + snoop_logger->Capture(kPhoneNumber, SnoopLogger::Direction::OUTGOING, + SnoopLogger::PacketType::ACL); snoop_logger->SetL2capChannelClose(conn_handle, local_cid, remote_cid); snoop_logger->SetRfcommPortClose(conn_handle, local_cid, dlci, profile_uuid_hfp_hf); @@ -1126,21 +990,19 @@ TEST_F(SnoopLoggerModuleTest, profiles_filtered_hfp_hf_test) { test_registry.StopAll(); - ASSERT_TRUE(bluetooth::os::SetSystemProperty( - SnoopLogger::kBtSnoopLogFilterProfileMapModeProperty, - SnoopLogger::kBtSnoopLogFilterProfileModeDisabled)); - ASSERT_TRUE(bluetooth::os::SetSystemProperty( - SnoopLogger::kBtSnoopLogFilterProfilePbapModeProperty, - SnoopLogger::kBtSnoopLogFilterProfileModeDisabled)); + ASSERT_TRUE(bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileMapModeProperty, + SnoopLogger::kBtSnoopLogFilterProfileModeDisabled)); + ASSERT_TRUE( + bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfilePbapModeProperty, + SnoopLogger::kBtSnoopLogFilterProfileModeDisabled)); // Verify states after test ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered)); // Packet should be filtered - ASSERT_EQ( - std::filesystem::file_size(temp_snoop_log_filtered), - sizeof(SnoopLoggerCommon::FileHeaderType) + sizeof(SnoopLogger::PacketHeaderType) + - HEADER_SIZE + strlen(clcc_pattern.c_str())); + ASSERT_EQ(std::filesystem::file_size(temp_snoop_log_filtered), + sizeof(SnoopLoggerCommon::FileHeaderType) + sizeof(SnoopLogger::PacketHeaderType) + + HEADER_SIZE + strlen(clcc_pattern.c_str())); ASSERT_TRUE(std::filesystem::remove(temp_snoop_log_filtered)); } @@ -1159,32 +1021,25 @@ TEST_F(SnoopLoggerModuleTest, profiles_filtered_pbap_magic_test) { const uint16_t HEADER_SIZE = 8; // Set pbap and map filtering modes - ASSERT_TRUE(bluetooth::os::SetSystemProperty( - SnoopLogger::kBtSnoopLogFilterProfilePbapModeProperty, - SnoopLogger::kBtSnoopLogFilterProfileModeMagic)); - auto filterPbapModeProperty = - bluetooth::os::GetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfilePbapModeProperty); ASSERT_TRUE( - filterPbapModeProperty && - (filterPbapModeProperty->find(SnoopLogger::kBtSnoopLogFilterProfileModeMagic) != - std::string::npos)); - ASSERT_TRUE(bluetooth::os::SetSystemProperty( - SnoopLogger::kBtSnoopLogFilterProfileMapModeProperty, - SnoopLogger::kBtSnoopLogFilterProfileModeMagic)); + bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfilePbapModeProperty, + SnoopLogger::kBtSnoopLogFilterProfileModeMagic)); + auto filterPbapModeProperty = + bluetooth::os::GetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfilePbapModeProperty); + ASSERT_TRUE(filterPbapModeProperty && + (filterPbapModeProperty->find(SnoopLogger::kBtSnoopLogFilterProfileModeMagic) != + std::string::npos)); + ASSERT_TRUE(bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileMapModeProperty, + SnoopLogger::kBtSnoopLogFilterProfileModeMagic)); auto filterMapModeProperty = - bluetooth::os::GetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileMapModeProperty); - ASSERT_TRUE( - filterMapModeProperty && - (filterMapModeProperty->find(SnoopLogger::kBtSnoopLogFilterProfileModeMagic) != - std::string::npos)); - - auto* snoop_logger = new TestSnoopLoggerModule( - temp_snoop_log_.string(), - temp_snooz_log_.string(), - 15, - SnoopLogger::kBtSnoopLogModeFiltered, - false, - false); + bluetooth::os::GetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileMapModeProperty); + ASSERT_TRUE(filterMapModeProperty && + (filterMapModeProperty->find(SnoopLogger::kBtSnoopLogFilterProfileModeMagic) != + std::string::npos)); + + auto* snoop_logger = + new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 15, + SnoopLogger::kBtSnoopLogModeFiltered, false, false); TestModuleRegistry test_registry; test_registry.InjectTestModule(&SnoopLogger::Factory, snoop_logger); @@ -1193,8 +1048,8 @@ TEST_F(SnoopLoggerModuleTest, profiles_filtered_pbap_magic_test) { snoop_logger->SetRfcommPortOpen(conn_handle, local_cid, dlci, profile_uuid_pbap, flow); for (int i = 0; i < (int)kTestData.size(); i++) { - snoop_logger->Capture( - kTestData[i], (SnoopLogger::Direction)(i % 2), SnoopLogger::PacketType::ACL); + snoop_logger->Capture(kTestData[i], (SnoopLogger::Direction)(i % 2), + SnoopLogger::PacketType::ACL); } snoop_logger->SetL2capChannelClose(conn_handle, local_cid, remote_cid); @@ -1204,22 +1059,20 @@ TEST_F(SnoopLoggerModuleTest, profiles_filtered_pbap_magic_test) { test_registry.StopAll(); - ASSERT_TRUE(bluetooth::os::SetSystemProperty( - SnoopLogger::kBtSnoopLogFilterProfileMapModeProperty, - SnoopLogger::kBtSnoopLogFilterProfileModeDisabled)); - ASSERT_TRUE(bluetooth::os::SetSystemProperty( - SnoopLogger::kBtSnoopLogFilterProfilePbapModeProperty, - SnoopLogger::kBtSnoopLogFilterProfileModeDisabled)); + ASSERT_TRUE(bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileMapModeProperty, + SnoopLogger::kBtSnoopLogFilterProfileModeDisabled)); + ASSERT_TRUE( + bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfilePbapModeProperty, + SnoopLogger::kBtSnoopLogFilterProfileModeDisabled)); // Verify states after test ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered)); // Packets should be filtered - ASSERT_EQ( - std::filesystem::file_size(temp_snoop_log_filtered), - sizeof(SnoopLoggerCommon::FileHeaderType) + - (int)kTestData.size() * - (sizeof(SnoopLogger::PacketHeaderType) + HEADER_SIZE + strlen(magic_string.c_str()))); + ASSERT_EQ(std::filesystem::file_size(temp_snoop_log_filtered), + sizeof(SnoopLoggerCommon::FileHeaderType) + + (int)kTestData.size() * (sizeof(SnoopLogger::PacketHeaderType) + HEADER_SIZE + + strlen(magic_string.c_str()))); ASSERT_TRUE(std::filesystem::remove(temp_snoop_log_filtered)); } @@ -1238,32 +1091,25 @@ TEST_F(SnoopLoggerModuleTest, profiles_filtered_pbap_header_test) { const uint16_t HEADER_SIZE = 8; // Set pbap and map filtering modes - ASSERT_TRUE(bluetooth::os::SetSystemProperty( - SnoopLogger::kBtSnoopLogFilterProfilePbapModeProperty, - SnoopLogger::kBtSnoopLogFilterProfileModeHeader)); - auto filterPbapModeProperty = - bluetooth::os::GetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfilePbapModeProperty); ASSERT_TRUE( - filterPbapModeProperty && - (filterPbapModeProperty->find(SnoopLogger::kBtSnoopLogFilterProfileModeHeader) != - std::string::npos)); - ASSERT_TRUE(bluetooth::os::SetSystemProperty( - SnoopLogger::kBtSnoopLogFilterProfileMapModeProperty, - SnoopLogger::kBtSnoopLogFilterProfileModeHeader)); + bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfilePbapModeProperty, + SnoopLogger::kBtSnoopLogFilterProfileModeHeader)); + auto filterPbapModeProperty = + bluetooth::os::GetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfilePbapModeProperty); + ASSERT_TRUE(filterPbapModeProperty && + (filterPbapModeProperty->find(SnoopLogger::kBtSnoopLogFilterProfileModeHeader) != + std::string::npos)); + ASSERT_TRUE(bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileMapModeProperty, + SnoopLogger::kBtSnoopLogFilterProfileModeHeader)); auto filterMapModeProperty = - bluetooth::os::GetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileMapModeProperty); - ASSERT_TRUE( - filterMapModeProperty && - (filterMapModeProperty->find(SnoopLogger::kBtSnoopLogFilterProfileModeHeader) != - std::string::npos)); - - auto* snoop_logger = new TestSnoopLoggerModule( - temp_snoop_log_.string(), - temp_snooz_log_.string(), - 15, - SnoopLogger::kBtSnoopLogModeFiltered, - false, - false); + bluetooth::os::GetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileMapModeProperty); + ASSERT_TRUE(filterMapModeProperty && + (filterMapModeProperty->find(SnoopLogger::kBtSnoopLogFilterProfileModeHeader) != + std::string::npos)); + + auto* snoop_logger = + new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 15, + SnoopLogger::kBtSnoopLogModeFiltered, false, false); TestModuleRegistry test_registry; test_registry.InjectTestModule(&SnoopLogger::Factory, snoop_logger); @@ -1272,8 +1118,8 @@ TEST_F(SnoopLoggerModuleTest, profiles_filtered_pbap_header_test) { snoop_logger->SetRfcommPortOpen(conn_handle, local_cid, dlci, profile_uuid_pbap, flow); for (int i = 0; i < (int)kTestData.size(); i++) { - snoop_logger->Capture( - kTestData[i], (SnoopLogger::Direction)(i % 2), SnoopLogger::PacketType::ACL); + snoop_logger->Capture(kTestData[i], (SnoopLogger::Direction)(i % 2), + SnoopLogger::PacketType::ACL); } snoop_logger->SetL2capChannelClose(conn_handle, local_cid, remote_cid); @@ -1283,21 +1129,19 @@ TEST_F(SnoopLoggerModuleTest, profiles_filtered_pbap_header_test) { test_registry.StopAll(); - ASSERT_TRUE(bluetooth::os::SetSystemProperty( - SnoopLogger::kBtSnoopLogFilterProfileMapModeProperty, - SnoopLogger::kBtSnoopLogFilterProfileModeDisabled)); - ASSERT_TRUE(bluetooth::os::SetSystemProperty( - SnoopLogger::kBtSnoopLogFilterProfilePbapModeProperty, - SnoopLogger::kBtSnoopLogFilterProfileModeDisabled)); + ASSERT_TRUE(bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileMapModeProperty, + SnoopLogger::kBtSnoopLogFilterProfileModeDisabled)); + ASSERT_TRUE( + bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfilePbapModeProperty, + SnoopLogger::kBtSnoopLogFilterProfileModeDisabled)); // Verify states after test ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered)); // Packets should be filtered - ASSERT_EQ( - std::filesystem::file_size(temp_snoop_log_filtered), - sizeof(SnoopLoggerCommon::FileHeaderType) + - (int)kTestData.size() * (sizeof(SnoopLogger::PacketHeaderType) + HEADER_SIZE)); + ASSERT_EQ(std::filesystem::file_size(temp_snoop_log_filtered), + sizeof(SnoopLoggerCommon::FileHeaderType) + + (int)kTestData.size() * (sizeof(SnoopLogger::PacketHeaderType) + HEADER_SIZE)); ASSERT_TRUE(std::filesystem::remove(temp_snoop_log_filtered)); } @@ -1315,32 +1159,26 @@ TEST_F(SnoopLoggerModuleTest, profiles_filtered_pbap_fullfilter_test) { bool flow = true; // Set pbap and map filtering modes - ASSERT_TRUE(bluetooth::os::SetSystemProperty( - SnoopLogger::kBtSnoopLogFilterProfilePbapModeProperty, - SnoopLogger::kBtSnoopLogFilterProfileModeFullfillter)); + ASSERT_TRUE( + bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfilePbapModeProperty, + SnoopLogger::kBtSnoopLogFilterProfileModeFullfillter)); auto filterPbapModeProperty = - bluetooth::os::GetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfilePbapModeProperty); + bluetooth::os::GetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfilePbapModeProperty); + ASSERT_TRUE(filterPbapModeProperty && + (filterPbapModeProperty->find(SnoopLogger::kBtSnoopLogFilterProfileModeFullfillter) != + std::string::npos)); ASSERT_TRUE( - filterPbapModeProperty && - (filterPbapModeProperty->find(SnoopLogger::kBtSnoopLogFilterProfileModeFullfillter) != - std::string::npos)); - ASSERT_TRUE(bluetooth::os::SetSystemProperty( - SnoopLogger::kBtSnoopLogFilterProfileMapModeProperty, - SnoopLogger::kBtSnoopLogFilterProfileModeFullfillter)); + bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileMapModeProperty, + SnoopLogger::kBtSnoopLogFilterProfileModeFullfillter)); auto filterMapModeProperty = - bluetooth::os::GetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileMapModeProperty); - ASSERT_TRUE( - filterMapModeProperty && - (filterMapModeProperty->find(SnoopLogger::kBtSnoopLogFilterProfileModeFullfillter) != - std::string::npos)); - - auto* snoop_logger = new TestSnoopLoggerModule( - temp_snoop_log_.string(), - temp_snooz_log_.string(), - 15, - SnoopLogger::kBtSnoopLogModeFiltered, - false, - false); + bluetooth::os::GetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileMapModeProperty); + ASSERT_TRUE(filterMapModeProperty && + (filterMapModeProperty->find(SnoopLogger::kBtSnoopLogFilterProfileModeFullfillter) != + std::string::npos)); + + auto* snoop_logger = + new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 15, + SnoopLogger::kBtSnoopLogModeFiltered, false, false); TestModuleRegistry test_registry; test_registry.InjectTestModule(&SnoopLogger::Factory, snoop_logger); @@ -1349,8 +1187,8 @@ TEST_F(SnoopLoggerModuleTest, profiles_filtered_pbap_fullfilter_test) { snoop_logger->SetRfcommPortOpen(conn_handle, local_cid, dlci, profile_uuid_pbap, flow); for (int i = 0; i < (int)kTestData.size(); i++) { - snoop_logger->Capture( - kTestData[i], (SnoopLogger::Direction)(i % 2), SnoopLogger::PacketType::ACL); + snoop_logger->Capture(kTestData[i], (SnoopLogger::Direction)(i % 2), + SnoopLogger::PacketType::ACL); } snoop_logger->SetL2capChannelClose(conn_handle, local_cid, remote_cid); @@ -1360,20 +1198,18 @@ TEST_F(SnoopLoggerModuleTest, profiles_filtered_pbap_fullfilter_test) { test_registry.StopAll(); - ASSERT_TRUE(bluetooth::os::SetSystemProperty( - SnoopLogger::kBtSnoopLogFilterProfileMapModeProperty, - SnoopLogger::kBtSnoopLogFilterProfileModeDisabled)); - ASSERT_TRUE(bluetooth::os::SetSystemProperty( - SnoopLogger::kBtSnoopLogFilterProfilePbapModeProperty, - SnoopLogger::kBtSnoopLogFilterProfileModeDisabled)); + ASSERT_TRUE(bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileMapModeProperty, + SnoopLogger::kBtSnoopLogFilterProfileModeDisabled)); + ASSERT_TRUE( + bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfilePbapModeProperty, + SnoopLogger::kBtSnoopLogFilterProfileModeDisabled)); // Verify states after test ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered)); // Packets should be filtered - ASSERT_EQ( - std::filesystem::file_size(temp_snoop_log_filtered), - sizeof(SnoopLoggerCommon::FileHeaderType)); + ASSERT_EQ(std::filesystem::file_size(temp_snoop_log_filtered), + sizeof(SnoopLoggerCommon::FileHeaderType)); ASSERT_TRUE(std::filesystem::remove(temp_snoop_log_filtered)); } @@ -1381,13 +1217,9 @@ TEST_F(SnoopLoggerModuleTest, profiles_filtered_pbap_fullfilter_test) { static constexpr int INVALID_FD = -1; TEST_F(SnoopLoggerModuleTest, socket_disabled_connect_fail_test) { - auto* snoop_logger = new TestSnoopLoggerModule( - temp_snoop_log_.string(), - temp_snooz_log_.string(), - 10, - SnoopLogger::kBtSnoopLogModeDisabled, - true, - false); + auto* snoop_logger = + new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10, + SnoopLogger::kBtSnoopLogModeDisabled, true, false); test_registry->InjectTestModule(&SnoopLogger::Factory, snoop_logger); // // Create a TCP socket file descriptor @@ -1411,13 +1243,8 @@ TEST_F(SnoopLoggerModuleTest, socket_disabled_connect_fail_test) { TEST_F(SnoopLoggerModuleTest, default_socket_enabled_capture_recv_test) { int ret; - auto* snoop_logger = new TestSnoopLoggerModule( - temp_snoop_log_.string(), - temp_snooz_log_.string(), - 10, - SnoopLogger::kBtSnoopLogModeFull, - true, - false); + auto* snoop_logger = new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), + 10, SnoopLogger::kBtSnoopLogModeFull, true, false); test_registry->InjectTestModule(&SnoopLogger::Factory, snoop_logger); // // Create a TCP socket file descriptor @@ -1446,12 +1273,14 @@ TEST_F(SnoopLoggerModuleTest, default_socket_enabled_capture_recv_test) { snoop_logger->GetSocketThread()->GetSocket()->WaitForClientSocketConnected(); - snoop_logger->Capture(kHfpAtNrec0, SnoopLogger::Direction::OUTGOING, SnoopLogger::PacketType::ACL); + snoop_logger->Capture(kHfpAtNrec0, SnoopLogger::Direction::OUTGOING, + SnoopLogger::PacketType::ACL); a.wait(); bytes_read = a.get(); - ASSERT_TRUE(std::memcmp(recv_buf1, &SnoopLoggerCommon::kBtSnoopFileHeader, sizeof(recv_buf1)) == 0); + ASSERT_TRUE(std::memcmp(recv_buf1, &SnoopLoggerCommon::kBtSnoopFileHeader, sizeof(recv_buf1)) == + 0); ASSERT_EQ(bytes_read, static_cast(kHfpAtNrec0.size())); ASSERT_TRUE(std::memcmp(recv_buf3, kHfpAtNrec0.data(), kHfpAtNrec0.size()) == 0); @@ -1460,18 +1289,14 @@ TEST_F(SnoopLoggerModuleTest, default_socket_enabled_capture_recv_test) { } TEST_F(SnoopLoggerModuleTest, custom_socket_register_enabled_capture_recv_test) { - auto* snoop_logger = new TestSnoopLoggerModule( - temp_snoop_log_.string(), - temp_snooz_log_.string(), - 10, - SnoopLogger::kBtSnoopLogModeFull, - true, - false); + auto* snoop_logger = new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), + 10, SnoopLogger::kBtSnoopLogModeFull, true, false); test_registry->InjectTestModule(&SnoopLogger::Factory, snoop_logger); int new_port = 8873; SyscallWrapperImpl syscall_if; - auto sls = std::make_unique(&syscall_if, SnoopLoggerSocket::DEFAULT_LOCALHOST_, new_port); + auto sls = std::make_unique(&syscall_if, SnoopLoggerSocket::DEFAULT_LOCALHOST_, + new_port); SnoopLoggerSocketThread slsThread(std::move(sls)); auto thread_start_future = slsThread.Start(); thread_start_future.wait(); @@ -1506,12 +1331,14 @@ TEST_F(SnoopLoggerModuleTest, custom_socket_register_enabled_capture_recv_test) slsThread.GetSocket()->WaitForClientSocketConnected(); - snoop_logger->Capture(kHfpAtNrec0, SnoopLogger::Direction::OUTGOING, SnoopLogger::PacketType::ACL); + snoop_logger->Capture(kHfpAtNrec0, SnoopLogger::Direction::OUTGOING, + SnoopLogger::PacketType::ACL); a.wait(); bytes_read = a.get(); - ASSERT_TRUE(std::memcmp(recv_buf1, &SnoopLoggerCommon::kBtSnoopFileHeader, sizeof(recv_buf1)) == 0); + ASSERT_TRUE(std::memcmp(recv_buf1, &SnoopLoggerCommon::kBtSnoopFileHeader, sizeof(recv_buf1)) == + 0); ASSERT_EQ(bytes_read, static_cast(kHfpAtNrec0.size())); ASSERT_TRUE(std::memcmp(recv_buf3, kHfpAtNrec0.data(), kHfpAtNrec0.size()) == 0); @@ -1520,30 +1347,23 @@ TEST_F(SnoopLoggerModuleTest, custom_socket_register_enabled_capture_recv_test) } TEST_F(SnoopLoggerModuleTest, custom_socket_interface_register_logging_disabled_test) { - auto* snoop_logger = new TestSnoopLoggerModule( - temp_snoop_log_.string(), - temp_snooz_log_.string(), - 10, - SnoopLogger::kBtSnoopLogModeDisabled, - true, - false); + auto* snoop_logger = + new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10, + SnoopLogger::kBtSnoopLogModeDisabled, true, false); test_registry->InjectTestModule(&SnoopLogger::Factory, snoop_logger); class SnoopLoggerSocketMock : public SnoopLoggerSocketInterface { - public: + public: bool write_called; - SnoopLoggerSocketMock() { - write_called = false; - } - virtual void Write(const void* /* data */, size_t /* length */) { - write_called = true; - } + SnoopLoggerSocketMock() { write_called = false; } + virtual void Write(const void* /* data */, size_t /* length */) { write_called = true; } }; SnoopLoggerSocketMock mock; snoop_logger->RegisterSocket(&mock); - snoop_logger->Capture(kQualcommConnectionRequest, SnoopLogger::Direction::OUTGOING, SnoopLogger::PacketType::ACL); + snoop_logger->Capture(kQualcommConnectionRequest, SnoopLogger::Direction::OUTGOING, + SnoopLogger::PacketType::ACL); ASSERT_FALSE(mock.write_called); @@ -1551,30 +1371,22 @@ TEST_F(SnoopLoggerModuleTest, custom_socket_interface_register_logging_disabled_ } TEST_F(SnoopLoggerModuleTest, custom_socket_interface_register_logging_enabled_test) { - auto* snoop_logger = new TestSnoopLoggerModule( - temp_snoop_log_.string(), - temp_snooz_log_.string(), - 10, - SnoopLogger::kBtSnoopLogModeFull, - true, - false); + auto* snoop_logger = new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), + 10, SnoopLogger::kBtSnoopLogModeFull, true, false); test_registry->InjectTestModule(&SnoopLogger::Factory, snoop_logger); class SnoopLoggerSocketMock : public SnoopLoggerSocketInterface { - public: + public: bool write_called; - SnoopLoggerSocketMock() { - write_called = false; - } - virtual void Write(const void* /* data */, size_t /* length */) { - write_called = true; - } + SnoopLoggerSocketMock() { write_called = false; } + virtual void Write(const void* /* data */, size_t /* length */) { write_called = true; } }; SnoopLoggerSocketMock mock; snoop_logger->RegisterSocket(&mock); - snoop_logger->Capture(kQualcommConnectionRequest, SnoopLogger::Direction::OUTGOING, SnoopLogger::PacketType::ACL); + snoop_logger->Capture(kQualcommConnectionRequest, SnoopLogger::Direction::OUTGOING, + SnoopLogger::PacketType::ACL); ASSERT_TRUE(mock.write_called); @@ -1593,53 +1405,46 @@ TEST_F(SnoopLoggerModuleTest, custom_socket_profiles_filtered_hfp_hf_test) { const uint16_t HEADER_SIZE = 12; size_t expected_data_size = HEADER_SIZE + strlen(clcc_pattern.c_str()); std::vector kPhoneNumber = { - 0x0b, 0x00, 0x30, 0x00, 0x2c, 0x00, 0x40, 0x30, 0x19, 0xff, 0x4f, 0x01, 0x0d, - 0x0a, 0x2b, 0x43, 0x4c, 0x43, 0x43, 0x3a, 0x20, 0x31, 0x2c, 0x31, 0x2c, 0x34, - 0x2c, 0x30, 0x2c, 0x30, 0x2c, 0x22, 0x2b, 0x39, 0x39, 0x31, 0x32, 0x33, 0x34, - 0x35, 0x36, 0x37, 0x38, 0x39, 0x22, 0x2c, 0x31, 0x34, 0x35, 0x0d, 0x0a, 0x49, + 0x0b, 0x00, 0x30, 0x00, 0x2c, 0x00, 0x40, 0x30, 0x19, 0xff, 0x4f, 0x01, 0x0d, + 0x0a, 0x2b, 0x43, 0x4c, 0x43, 0x43, 0x3a, 0x20, 0x31, 0x2c, 0x31, 0x2c, 0x34, + 0x2c, 0x30, 0x2c, 0x30, 0x2c, 0x22, 0x2b, 0x39, 0x39, 0x31, 0x32, 0x33, 0x34, + 0x35, 0x36, 0x37, 0x38, 0x39, 0x22, 0x2c, 0x31, 0x34, 0x35, 0x0d, 0x0a, 0x49, }; std::vector kExpectedPhoneNumber = { - 0x0b, 0x00, 0x30, 0x00, 0x0c, 0x00, 0x40, 0x30, 0x19, 0xff, 0x4f, 0x01, 0x0d, - 0x0a, 0x2b, 0x43, 0x4c, 0x43, 0x43, 0x3a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x0b, 0x00, 0x30, 0x00, 0x0c, 0x00, 0x40, 0x30, 0x19, 0xff, 0x4f, 0x01, 0x0d, + 0x0a, 0x2b, 0x43, 0x4c, 0x43, 0x43, 0x3a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; // Set pbap and map filtering modes - ASSERT_TRUE(bluetooth::os::SetSystemProperty( - SnoopLogger::kBtSnoopLogFilterProfilePbapModeProperty, - SnoopLogger::kBtSnoopLogFilterProfileModeMagic)); - auto filterPbapModeProperty = - bluetooth::os::GetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfilePbapModeProperty); ASSERT_TRUE( - filterPbapModeProperty && - (filterPbapModeProperty->find(SnoopLogger::kBtSnoopLogFilterProfileModeMagic) != - std::string::npos)); - ASSERT_TRUE(bluetooth::os::SetSystemProperty( - SnoopLogger::kBtSnoopLogFilterProfileMapModeProperty, - SnoopLogger::kBtSnoopLogFilterProfileModeMagic)); + bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfilePbapModeProperty, + SnoopLogger::kBtSnoopLogFilterProfileModeMagic)); + auto filterPbapModeProperty = + bluetooth::os::GetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfilePbapModeProperty); + ASSERT_TRUE(filterPbapModeProperty && + (filterPbapModeProperty->find(SnoopLogger::kBtSnoopLogFilterProfileModeMagic) != + std::string::npos)); + ASSERT_TRUE(bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileMapModeProperty, + SnoopLogger::kBtSnoopLogFilterProfileModeMagic)); auto filterMapModeProperty = - bluetooth::os::GetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileMapModeProperty); - ASSERT_TRUE( - filterMapModeProperty && - (filterMapModeProperty->find(SnoopLogger::kBtSnoopLogFilterProfileModeMagic) != - std::string::npos)); - - auto* snoop_logger = new TestSnoopLoggerModule( - temp_snoop_log_.string(), - temp_snooz_log_.string(), - 10, - SnoopLogger::kBtSnoopLogModeFiltered, - false, - false); + bluetooth::os::GetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileMapModeProperty); + ASSERT_TRUE(filterMapModeProperty && + (filterMapModeProperty->find(SnoopLogger::kBtSnoopLogFilterProfileModeMagic) != + std::string::npos)); + + auto* snoop_logger = + new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10, + SnoopLogger::kBtSnoopLogModeFiltered, false, false); test_registry->InjectTestModule(&SnoopLogger::Factory, snoop_logger); int new_port = 8873; SyscallWrapperImpl syscall_if; - auto sls = std::make_unique( - &syscall_if, SnoopLoggerSocket::DEFAULT_LOCALHOST_, new_port); + auto sls = std::make_unique(&syscall_if, SnoopLoggerSocket::DEFAULT_LOCALHOST_, + new_port); SnoopLoggerSocketThread slsThread(std::move(sls)); auto thread_start_future = slsThread.Start(); thread_start_future.wait(); @@ -1677,25 +1482,24 @@ TEST_F(SnoopLoggerModuleTest, custom_socket_profiles_filtered_hfp_hf_test) { slsThread.GetSocket()->WaitForClientSocketConnected(); - snoop_logger->Capture( - kPhoneNumber, SnoopLogger::Direction::OUTGOING, SnoopLogger::PacketType::ACL); + snoop_logger->Capture(kPhoneNumber, SnoopLogger::Direction::OUTGOING, + SnoopLogger::PacketType::ACL); snoop_logger->SetL2capChannelClose(conn_handle, local_cid, remote_cid); snoop_logger->SetRfcommPortClose(conn_handle, local_cid, dlci, profile_uuid_hfp_hf); a.wait(); bytes_read = a.get(); - ASSERT_TRUE( - std::memcmp(recv_buf1, &SnoopLoggerCommon::kBtSnoopFileHeader, sizeof(recv_buf1)) == 0); + ASSERT_TRUE(std::memcmp(recv_buf1, &SnoopLoggerCommon::kBtSnoopFileHeader, sizeof(recv_buf1)) == + 0); ASSERT_EQ(bytes_read, static_cast(expected_data_size)); ASSERT_TRUE(std::memcmp(recv_buf3, kExpectedPhoneNumber.data(), expected_data_size) == 0); - ASSERT_TRUE(bluetooth::os::SetSystemProperty( - SnoopLogger::kBtSnoopLogFilterProfileMapModeProperty, - SnoopLogger::kBtSnoopLogFilterProfileModeDisabled)); - ASSERT_TRUE(bluetooth::os::SetSystemProperty( - SnoopLogger::kBtSnoopLogFilterProfilePbapModeProperty, - SnoopLogger::kBtSnoopLogFilterProfileModeDisabled)); + ASSERT_TRUE(bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileMapModeProperty, + SnoopLogger::kBtSnoopLogFilterProfileModeDisabled)); + ASSERT_TRUE( + bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfilePbapModeProperty, + SnoopLogger::kBtSnoopLogFilterProfileModeDisabled)); test_registry->StopAll(); close(socket_fd); diff --git a/system/gd/hal/syscall_wrapper_impl.cc b/system/gd/hal/syscall_wrapper_impl.cc index 4fda7909cd2..d2a38863850 100644 --- a/system/gd/hal/syscall_wrapper_impl.cc +++ b/system/gd/hal/syscall_wrapper_impl.cc @@ -55,7 +55,8 @@ ssize_t SyscallWrapperImpl::Recv(int fd, void* buf, size_t n, int flags) { return ret; } -int SyscallWrapperImpl::Setsockopt(int fd, int level, int optname, const void* optval, socklen_t optlen) { +int SyscallWrapperImpl::Setsockopt(int fd, int level, int optname, const void* optval, + socklen_t optlen) { int ret = setsockopt(fd, level, optname, optval, optlen); errno_ = errno; return ret; @@ -91,28 +92,18 @@ int SyscallWrapperImpl::Pipe2(int* pipefd, int flags) { return ret; } -int SyscallWrapperImpl::GetErrno() const { - return errno_; -} +int SyscallWrapperImpl::GetErrno() const { return errno_; } -void SyscallWrapperImpl::FDSet(int fd, fd_set* set) { - FD_SET(fd, set); -} +void SyscallWrapperImpl::FDSet(int fd, fd_set* set) { FD_SET(fd, set); } -void SyscallWrapperImpl::FDClr(int fd, fd_set* set) { - FD_CLR(fd, set); -} +void SyscallWrapperImpl::FDClr(int fd, fd_set* set) { FD_CLR(fd, set); } -bool SyscallWrapperImpl::FDIsSet(int fd, fd_set* set) { - return FD_ISSET(fd, set); -} +bool SyscallWrapperImpl::FDIsSet(int fd, fd_set* set) { return FD_ISSET(fd, set); } -void SyscallWrapperImpl::FDZero(fd_set* set) { - FD_ZERO(set); -} +void SyscallWrapperImpl::FDZero(fd_set* set) { FD_ZERO(set); } -int SyscallWrapperImpl::Select( - int __nfds, fd_set* __readfds, fd_set* __writefds, fd_set* __exceptfds, struct timeval* __timeout) { +int SyscallWrapperImpl::Select(int __nfds, fd_set* __readfds, fd_set* __writefds, + fd_set* __exceptfds, struct timeval* __timeout) { int ret = select(__nfds, __readfds, __writefds, __exceptfds, __timeout); errno_ = errno; return ret; diff --git a/system/gd/hal/syscall_wrapper_impl.h b/system/gd/hal/syscall_wrapper_impl.h index c921a71cc47..d82a8efe047 100644 --- a/system/gd/hal/syscall_wrapper_impl.h +++ b/system/gd/hal/syscall_wrapper_impl.h @@ -56,9 +56,10 @@ class SyscallWrapperImpl : public SyscallWrapperInterface { void FDZero(fd_set* set); - int Select(int __nfds, fd_set* __readfds, fd_set* __writefds, fd_set* __exceptfds, struct timeval* __timeout); + int Select(int __nfds, fd_set* __readfds, fd_set* __writefds, fd_set* __exceptfds, + struct timeval* __timeout); - private: +private: int errno_; }; diff --git a/system/gd/hal/syscall_wrapper_interface.h b/system/gd/hal/syscall_wrapper_interface.h index d0cf4f13f84..2b39c065a96 100644 --- a/system/gd/hal/syscall_wrapper_interface.h +++ b/system/gd/hal/syscall_wrapper_interface.h @@ -25,7 +25,7 @@ namespace bluetooth { namespace hal { class SyscallWrapperInterface { - public: +public: virtual ~SyscallWrapperInterface() = default; /* Wrapper for socket() API */ @@ -77,8 +77,8 @@ class SyscallWrapperInterface { virtual void FDZero(fd_set* set) = 0; /* Wrapper for select() API */ - virtual int Select( - int __nfds, fd_set* __readfds, fd_set* __writefds, fd_set* __exceptfds, struct timeval* __timeout) = 0; + virtual int Select(int __nfds, fd_set* __readfds, fd_set* __writefds, fd_set* __exceptfds, + struct timeval* __timeout) = 0; }; } // namespace hal diff --git a/system/gd/hal/syscall_wrapper_mock.h b/system/gd/hal/syscall_wrapper_mock.h index 13f53b0187e..5b78575d896 100644 --- a/system/gd/hal/syscall_wrapper_mock.h +++ b/system/gd/hal/syscall_wrapper_mock.h @@ -28,7 +28,7 @@ namespace bluetooth { namespace hal { class SyscallWrapperMock : public SyscallWrapperInterface { - public: +public: MOCK_METHOD(int, Socket, (int, int, int)); MOCK_METHOD(int, Bind, (int, const struct sockaddr*, socklen_t)); diff --git a/system/gd/hci/acl_builder_test.cc b/system/gd/hci/acl_builder_test.cc index 00dc7473813..b23581e36f5 100644 --- a/system/gd/hci/acl_builder_test.cc +++ b/system/gd/hci/acl_builder_test.cc @@ -28,7 +28,7 @@ using std::vector; namespace { vector information_request = { - 0xfe, 0x2e, 0x0a, 0x00, 0x06, 0x00, 0x01, 0x00, 0x0a, 0x02, 0x02, 0x00, 0x02, 0x00, + 0xfe, 0x2e, 0x0a, 0x00, 0x06, 0x00, 0x01, 0x00, 0x0a, 0x02, 0x02, 0x00, 0x02, 0x00, }; // 0x00, 0x01, 0x02, 0x03, ... vector counting_bytes; @@ -42,7 +42,7 @@ namespace bluetooth { namespace hci { class AclBuilderTest : public ::testing::Test { - public: +public: AclBuilderTest() { counting_bytes.reserve(count_size); counting_down_bytes.reserve(count_size); @@ -63,12 +63,13 @@ TEST(AclBuilderTest, buildAclCount) { count_payload->AddOctets(counting_bytes); ASSERT_EQ(counting_bytes.size(), count_payload->size()); - std::unique_ptr count_packet = - AclBuilder::Create(handle, packet_boundary_flag, broadcast_flag, std::move(count_payload)); + std::unique_ptr count_packet = AclBuilder::Create( + handle, packet_boundary_flag, broadcast_flag, std::move(count_payload)); ASSERT_EQ(counting_bytes.size() + 4, count_packet->size()); - std::shared_ptr> count_packet_bytes = std::make_shared>(); + std::shared_ptr> count_packet_bytes = + std::make_shared>(); BitInserter it(*count_packet_bytes); count_packet->Serialize(it); @@ -96,12 +97,13 @@ TEST(AclBuilderTest, buildAclCountInverted) { counting_down_bytes_payload->AddOctets(counting_down_bytes); ASSERT_EQ(counting_down_bytes.size(), counting_down_bytes_payload->size()); - std::unique_ptr counting_down_bytes_packet = - AclBuilder::Create(handle, packet_boundary_flag, broadcast_flag, std::move(counting_down_bytes_payload)); + std::unique_ptr counting_down_bytes_packet = AclBuilder::Create( + handle, packet_boundary_flag, broadcast_flag, std::move(counting_down_bytes_payload)); ASSERT_EQ(counting_down_bytes.size() + 4, counting_down_bytes_packet->size()); - std::shared_ptr> counting_down_bytes_packet_bytes = std::make_shared>(); + std::shared_ptr> counting_down_bytes_packet_bytes = + std::make_shared>(); BitInserter it(*counting_down_bytes_packet_bytes); counting_down_bytes_packet->Serialize(it); PacketView counting_down_bytes_packet_bytes_view(counting_down_bytes_packet_bytes); @@ -130,7 +132,7 @@ TEST(AclBuilderTest, buildInformationRequest) { ASSERT_EQ(payload_bytes.size(), payload->size()); std::unique_ptr packet = - AclBuilder::Create(handle, packet_boundary_flag, broadcast_flag, std::move(payload)); + AclBuilder::Create(handle, packet_boundary_flag, broadcast_flag, std::move(payload)); ASSERT_EQ(information_request.size(), packet->size()); diff --git a/system/gd/hci/acl_connection_interface.h b/system/gd/hci/acl_connection_interface.h index a75819b909e..f90b9909d1c 100644 --- a/system/gd/hci/acl_connection_interface.h +++ b/system/gd/hci/acl_connection_interface.h @@ -23,20 +23,20 @@ namespace bluetooth { namespace hci { constexpr EventCode AclConnectionEvents[] = { - EventCode::CONNECTION_PACKET_TYPE_CHANGED, - EventCode::ROLE_CHANGE, - EventCode::CONNECTION_COMPLETE, - EventCode::AUTHENTICATION_COMPLETE, - EventCode::READ_CLOCK_OFFSET_COMPLETE, - EventCode::MODE_CHANGE, - EventCode::SNIFF_SUBRATING, - EventCode::QOS_SETUP_COMPLETE, - EventCode::FLOW_SPECIFICATION_COMPLETE, - EventCode::FLUSH_OCCURRED, - EventCode::READ_REMOTE_SUPPORTED_FEATURES_COMPLETE, - EventCode::READ_REMOTE_EXTENDED_FEATURES_COMPLETE, - EventCode::LINK_SUPERVISION_TIMEOUT_CHANGED, - EventCode::ENHANCED_FLUSH_COMPLETE, + EventCode::CONNECTION_PACKET_TYPE_CHANGED, + EventCode::ROLE_CHANGE, + EventCode::CONNECTION_COMPLETE, + EventCode::AUTHENTICATION_COMPLETE, + EventCode::READ_CLOCK_OFFSET_COMPLETE, + EventCode::MODE_CHANGE, + EventCode::SNIFF_SUBRATING, + EventCode::QOS_SETUP_COMPLETE, + EventCode::FLOW_SPECIFICATION_COMPLETE, + EventCode::FLUSH_OCCURRED, + EventCode::READ_REMOTE_SUPPORTED_FEATURES_COMPLETE, + EventCode::READ_REMOTE_EXTENDED_FEATURES_COMPLETE, + EventCode::LINK_SUPERVISION_TIMEOUT_CHANGED, + EventCode::ENHANCED_FLUSH_COMPLETE, }; typedef CommandInterface AclConnectionInterface; diff --git a/system/gd/hci/acl_manager.cc b/system/gd/hci/acl_manager.cc index dfd49e6e310..ff8ba1e3c21 100644 --- a/system/gd/hci/acl_manager.cc +++ b/system/gd/hci/acl_manager.cc @@ -81,14 +81,9 @@ struct AclManager::impl { bool crash_on_unknown_handle = false; { const std::lock_guard lock(dumpsys_mutex_); - classic_impl_ = new classic_impl( - hci_layer_, - controller_, - handler_, - round_robin_scheduler_, - crash_on_unknown_handle, - acl_scheduler_, - remote_name_request_module_); + classic_impl_ = new classic_impl(hci_layer_, controller_, handler_, round_robin_scheduler_, + crash_on_unknown_handle, acl_scheduler_, + remote_name_request_module_); le_impl_ = new le_impl(hci_layer_, controller_, handler_, round_robin_scheduler_, crash_on_unknown_handle); } @@ -127,21 +122,18 @@ struct AclManager::impl { std::vector unsent_packets; for (const auto& itr : waiting_packets_) { auto handle = itr.GetHandle(); - if (!classic_impl_->send_packet_upward( - handle, - [itr](struct acl_manager::assembler* assembler) { - assembler->on_incoming_packet(itr); - }) && + if (!classic_impl_->send_packet_upward(handle, + [itr](struct acl_manager::assembler* assembler) { + assembler->on_incoming_packet(itr); + }) && !le_impl_->send_packet_upward(handle, [itr](struct acl_manager::assembler* assembler) { assembler->on_incoming_packet(itr); })) { if (!timed_out) { unsent_packets.push_back(itr); } else { - log::error( - "Dropping packet of size {} to unknown connection 0x{:x}", - itr.size(), - itr.GetHandle()); + log::error("Dropping packet of size {} to unknown connection 0x{:x}", itr.size(), + itr.GetHandle()); } } } @@ -168,7 +160,9 @@ struct AclManager::impl { return; } uint16_t handle = packet->GetHandle(); - if (handle == kQualcommDebugHandle || handle == kSamsungDebugHandle) return; + if (handle == kQualcommDebugHandle || handle == kSamsungDebugHandle) { + return; + } if (classic_impl_->send_packet_upward(handle, [&packet](struct acl_manager::assembler* assembler) { assembler->on_incoming_packet(*packet); @@ -184,10 +178,8 @@ struct AclManager::impl { unknown_acl_alarm_.reset(new os::Alarm(handler_)); } waiting_packets_.push_back(*packet); - log::info( - "Saving packet of size {} to unknown connection 0x{:x}", - packet->size(), - packet->GetHandle()); + log::info("Saving packet of size {} to unknown connection 0x{:x}", packet->size(), + packet->GetHandle()); unknown_acl_alarm_->Schedule(BindOnce(&on_unknown_acl_timer, common::Unretained(this)), kWaitBeforeDroppingUnknownAcl); } @@ -217,42 +209,30 @@ struct AclManager::impl { AclManager::AclManager() : pimpl_(std::make_unique(*this)) {} void AclManager::RegisterCallbacks(ConnectionCallbacks* callbacks, os::Handler* handler) { - log::assert_that( - callbacks != nullptr && handler != nullptr, - "assert failed: callbacks != nullptr && handler != nullptr"); - GetHandler()->Post(common::BindOnce( - &classic_impl::handle_register_callbacks, - common::Unretained(pimpl_->classic_impl_), - common::Unretained(callbacks), - common::Unretained(handler))); + log::assert_that(callbacks != nullptr && handler != nullptr, + "assert failed: callbacks != nullptr && handler != nullptr"); + GetHandler()->Post(common::BindOnce(&classic_impl::handle_register_callbacks, + common::Unretained(pimpl_->classic_impl_), + common::Unretained(callbacks), common::Unretained(handler))); } void AclManager::UnregisterCallbacks(ConnectionCallbacks* callbacks, std::promise promise) { log::assert_that(callbacks != nullptr, "assert failed: callbacks != nullptr"); - CallOn( - pimpl_->classic_impl_, - &classic_impl::handle_unregister_callbacks, - common::Unretained(callbacks), - std::move(promise)); + CallOn(pimpl_->classic_impl_, &classic_impl::handle_unregister_callbacks, + common::Unretained(callbacks), std::move(promise)); } void AclManager::RegisterLeCallbacks(LeConnectionCallbacks* callbacks, os::Handler* handler) { - log::assert_that( - callbacks != nullptr && handler != nullptr, - "assert failed: callbacks != nullptr && handler != nullptr"); - CallOn( - pimpl_->le_impl_, - &le_impl::handle_register_le_callbacks, - common::Unretained(callbacks), - common::Unretained(handler)); + log::assert_that(callbacks != nullptr && handler != nullptr, + "assert failed: callbacks != nullptr && handler != nullptr"); + CallOn(pimpl_->le_impl_, &le_impl::handle_register_le_callbacks, common::Unretained(callbacks), + common::Unretained(handler)); } void AclManager::RegisterLeAcceptlistCallbacks(LeAcceptlistCallbacks* callbacks) { log::assert_that(callbacks != nullptr, "assert failed: callbacks != nullptr"); - CallOn( - pimpl_->le_impl_, - &le_impl::handle_register_le_acceptlist_callbacks, - common::Unretained(callbacks)); + CallOn(pimpl_->le_impl_, &le_impl::handle_register_le_acceptlist_callbacks, + common::Unretained(callbacks)); } void AclManager::UnregisterLeCallbacks(LeConnectionCallbacks* callbacks, @@ -262,14 +242,11 @@ void AclManager::UnregisterLeCallbacks(LeConnectionCallbacks* callbacks, std::move(promise)); } -void AclManager::UnregisterLeAcceptlistCallbacks( - LeAcceptlistCallbacks* callbacks, std::promise promise) { +void AclManager::UnregisterLeAcceptlistCallbacks(LeAcceptlistCallbacks* callbacks, + std::promise promise) { log::assert_that(callbacks != nullptr, "assert failed: callbacks != nullptr"); - CallOn( - pimpl_->le_impl_, - &le_impl::handle_unregister_le_acceptlist_callbacks, - common::Unretained(callbacks), - std::move(promise)); + CallOn(pimpl_->le_impl_, &le_impl::handle_unregister_le_acceptlist_callbacks, + common::Unretained(callbacks), std::move(promise)); } void AclManager::CreateConnection(Address address) { @@ -292,51 +269,36 @@ void AclManager::SetLeSuggestedDefaultDataParameters(uint16_t octets, uint16_t t CallOn(pimpl_->le_impl_, &le_impl::set_le_suggested_default_data_parameters, octets, time); } -void AclManager::LeSetDefaultSubrate( - uint16_t subrate_min, uint16_t subrate_max, uint16_t max_latency, uint16_t cont_num, uint16_t sup_tout) { +void AclManager::LeSetDefaultSubrate(uint16_t subrate_min, uint16_t subrate_max, + uint16_t max_latency, uint16_t cont_num, uint16_t sup_tout) { CallOn(pimpl_->le_impl_, &le_impl::LeSetDefaultSubrate, subrate_min, subrate_max, max_latency, cont_num, sup_tout); } void AclManager::SetPrivacyPolicyForInitiatorAddress( - LeAddressManager::AddressPolicy address_policy, - AddressWithType fixed_address, - std::chrono::milliseconds minimum_rotation_time, - std::chrono::milliseconds maximum_rotation_time) { + LeAddressManager::AddressPolicy address_policy, AddressWithType fixed_address, + std::chrono::milliseconds minimum_rotation_time, + std::chrono::milliseconds maximum_rotation_time) { Octet16 rotation_irk{}; auto irk_prop = GetDependency()->GetProperty( - BTIF_STORAGE_SECTION_ADAPTER, BTIF_STORAGE_KEY_LE_LOCAL_KEY_IRK); + BTIF_STORAGE_SECTION_ADAPTER, BTIF_STORAGE_KEY_LE_LOCAL_KEY_IRK); if (irk_prop.has_value()) { auto irk = common::ByteArray<16>::FromString(irk_prop.value()); if (irk.has_value()) { rotation_irk = irk->bytes; } } - CallOn( - pimpl_->le_impl_, - &le_impl::set_privacy_policy_for_initiator_address, - address_policy, - fixed_address, - rotation_irk, - minimum_rotation_time, - maximum_rotation_time); + CallOn(pimpl_->le_impl_, &le_impl::set_privacy_policy_for_initiator_address, address_policy, + fixed_address, rotation_irk, minimum_rotation_time, maximum_rotation_time); } // TODO(jpawlowski): remove once we have config file abstraction in cert tests void AclManager::SetPrivacyPolicyForInitiatorAddressForTest( - LeAddressManager::AddressPolicy address_policy, - AddressWithType fixed_address, - Octet16 rotation_irk, - std::chrono::milliseconds minimum_rotation_time, - std::chrono::milliseconds maximum_rotation_time) { - CallOn( - pimpl_->le_impl_, - &le_impl::set_privacy_policy_for_initiator_address_for_test, - address_policy, - fixed_address, - rotation_irk, - minimum_rotation_time, - maximum_rotation_time); + LeAddressManager::AddressPolicy address_policy, AddressWithType fixed_address, + Octet16 rotation_irk, std::chrono::milliseconds minimum_rotation_time, + std::chrono::milliseconds maximum_rotation_time) { + CallOn(pimpl_->le_impl_, &le_impl::set_privacy_policy_for_initiator_address_for_test, + address_policy, fixed_address, rotation_irk, minimum_rotation_time, maximum_rotation_time); } void AclManager::CancelConnect(Address address) { @@ -358,10 +320,9 @@ void AclManager::ClearFilterAcceptList() { CallOn(pimpl_->le_impl_, &le_impl::clear_filter_accept_list); } -void AclManager::AddDeviceToResolvingList( - AddressWithType address_with_type, - const std::array& peer_irk, - const std::array& local_irk) { +void AclManager::AddDeviceToResolvingList(AddressWithType address_with_type, + const std::array& peer_irk, + const std::array& local_irk) { CallOn(pimpl_->le_impl_, &le_impl::add_device_to_resolving_list, address_with_type, peer_irk, local_irk); } @@ -387,23 +348,16 @@ uint16_t AclManager::ReadDefaultLinkPolicySettings() { void AclManager::WriteDefaultLinkPolicySettings(uint16_t default_link_policy_settings) { pimpl_->default_link_policy_settings_ = default_link_policy_settings; - CallOn(pimpl_->classic_impl_, &classic_impl::write_default_link_policy_settings, default_link_policy_settings); + CallOn(pimpl_->classic_impl_, &classic_impl::write_default_link_policy_settings, + default_link_policy_settings); } -void AclManager::OnAdvertisingSetTerminated( - ErrorCode status, - uint16_t conn_handle, - uint8_t adv_set_id, - hci::AddressWithType adv_address, - bool is_discoverable) { +void AclManager::OnAdvertisingSetTerminated(ErrorCode status, uint16_t conn_handle, + uint8_t adv_set_id, hci::AddressWithType adv_address, + bool is_discoverable) { if (status == ErrorCode::SUCCESS) { - CallOn( - pimpl_->le_impl_, - &le_impl::OnAdvertisingSetTerminated, - conn_handle, - adv_set_id, - adv_address, - is_discoverable); + CallOn(pimpl_->le_impl_, &le_impl::OnAdvertisingSetTerminated, conn_handle, adv_set_id, + adv_address, is_discoverable); } } @@ -436,7 +390,8 @@ Address AclManager::HACK_GetLeAddress(uint16_t connection_handle) { } void AclManager::HACK_SetAclTxPriority(uint8_t handle, bool high_priority) { - CallOn(pimpl_->round_robin_scheduler_, &RoundRobinScheduler::SetLinkPriority, handle, high_priority); + CallOn(pimpl_->round_robin_scheduler_, &RoundRobinScheduler::SetLinkPriority, handle, + high_priority); } void AclManager::ListDependencies(ModuleList* list) const { @@ -447,28 +402,24 @@ void AclManager::ListDependencies(ModuleList* list) const { list->add(); } -void AclManager::Start() { - pimpl_->Start(); -} +void AclManager::Start() { pimpl_->Start(); } -void AclManager::Stop() { - pimpl_->Stop(); -} +void AclManager::Stop() { pimpl_->Stop(); } -std::string AclManager::ToString() const { - return "Acl Manager"; -} +std::string AclManager::ToString() const { return "Acl Manager"; } const ModuleFactory AclManager::Factory = ModuleFactory([]() { return new AclManager(); }); AclManager::~AclManager() = default; -void AclManager::impl::Dump( - std::promise> promise, flatbuffers::FlatBufferBuilder* fb_builder) const { +void AclManager::impl::Dump(std::promise> promise, + flatbuffers::FlatBufferBuilder* fb_builder) const { const std::lock_guard lock(dumpsys_mutex_); - const auto accept_list = (le_impl_ != nullptr) ? le_impl_->accept_list : std::unordered_set(); + const auto accept_list = + (le_impl_ != nullptr) ? le_impl_->accept_list : std::unordered_set(); const auto le_connectability_state_text = - (le_impl_ != nullptr) ? connectability_state_machine_text(le_impl_->connectability_state_) : "INDETERMINATE"; + (le_impl_ != nullptr) ? connectability_state_machine_text(le_impl_->connectability_state_) + : "INDETERMINATE"; const auto le_create_connection_timeout_alarms_count = (le_impl_ != nullptr) ? static_cast(le_impl_->create_connection_timeout_alarms_.size()) diff --git a/system/gd/hci/acl_manager.h b/system/gd/hci/acl_manager.h index 5da01d0e35e..0536d79208c 100644 --- a/system/gd/hci/acl_manager.h +++ b/system/gd/hci/acl_manager.h @@ -50,7 +50,7 @@ class AclManager : public Module { friend class bluetooth::hci::LeScanningManager; friend class bluetooth::hci::DistanceMeasurementManager; - public: +public: AclManager(); AclManager(const AclManager&) = delete; AclManager& operator=(const AclManager&) = delete; @@ -66,17 +66,17 @@ class AclManager : public Module { // Should register only once when user module starts. // Generates OnConnectSuccess when an incoming connection is established. virtual void RegisterCallbacks(acl_manager::ConnectionCallbacks* callbacks, os::Handler* handler); - virtual void UnregisterCallbacks( - acl_manager::ConnectionCallbacks* callbacks, std::promise promise); + virtual void UnregisterCallbacks(acl_manager::ConnectionCallbacks* callbacks, + std::promise promise); // Should register only once when user module starts. - virtual void RegisterLeCallbacks( - acl_manager::LeConnectionCallbacks* callbacks, os::Handler* handler); - virtual void UnregisterLeCallbacks( - acl_manager::LeConnectionCallbacks* callbacks, std::promise promise); + virtual void RegisterLeCallbacks(acl_manager::LeConnectionCallbacks* callbacks, + os::Handler* handler); + virtual void UnregisterLeCallbacks(acl_manager::LeConnectionCallbacks* callbacks, + std::promise promise); void RegisterLeAcceptlistCallbacks(acl_manager::LeAcceptlistCallbacks* callbacks); - void UnregisterLeAcceptlistCallbacks( - acl_manager::LeAcceptlistCallbacks* callbacks, std::promise promise); + void UnregisterLeAcceptlistCallbacks(acl_manager::LeAcceptlistCallbacks* callbacks, + std::promise promise); // Generates OnConnectSuccess if connected, or OnConnectFail otherwise virtual void CreateConnection(Address address); @@ -87,26 +87,19 @@ class AclManager : public Module { // Ask the controller for specific data parameters virtual void SetLeSuggestedDefaultDataParameters(uint16_t octets, uint16_t time); - virtual void LeSetDefaultSubrate( - uint16_t subrate_min, - uint16_t subrate_max, - uint16_t max_latency, - uint16_t cont_num, - uint16_t sup_tout); + virtual void LeSetDefaultSubrate(uint16_t subrate_min, uint16_t subrate_max, uint16_t max_latency, + uint16_t cont_num, uint16_t sup_tout); - virtual void SetPrivacyPolicyForInitiatorAddress( - LeAddressManager::AddressPolicy address_policy, - AddressWithType fixed_address, - std::chrono::milliseconds minimum_rotation_time, - std::chrono::milliseconds maximum_rotation_time); + virtual void SetPrivacyPolicyForInitiatorAddress(LeAddressManager::AddressPolicy address_policy, + AddressWithType fixed_address, + std::chrono::milliseconds minimum_rotation_time, + std::chrono::milliseconds maximum_rotation_time); // TODO(jpawlowski): remove once we have config file abstraction in cert tests virtual void SetPrivacyPolicyForInitiatorAddressForTest( - LeAddressManager::AddressPolicy address_policy, - AddressWithType fixed_address, - Octet16 rotation_irk, - std::chrono::milliseconds minimum_rotation_time, - std::chrono::milliseconds maximum_rotation_time); + LeAddressManager::AddressPolicy address_policy, AddressWithType fixed_address, + Octet16 rotation_irk, std::chrono::milliseconds minimum_rotation_time, + std::chrono::milliseconds maximum_rotation_time); // Generates OnConnectFail with error code "terminated by local host 0x16" if // cancelled, or OnConnectSuccess if not successfully cancelled and already @@ -119,10 +112,9 @@ class AclManager : public Module { virtual void ClearFilterAcceptList(); - virtual void AddDeviceToResolvingList( - AddressWithType address_with_type, - const std::array& peer_irk, - const std::array& local_irk); + virtual void AddDeviceToResolvingList(AddressWithType address_with_type, + const std::array& peer_irk, + const std::array& local_irk); virtual void RemoveDeviceFromResolvingList(AddressWithType address_with_type); virtual void ClearResolvingList(); @@ -132,12 +124,9 @@ class AclManager : public Module { virtual void WriteDefaultLinkPolicySettings(uint16_t default_link_policy_settings); // Callback from Advertising Manager to notify the advitiser (local) address - virtual void OnAdvertisingSetTerminated( - ErrorCode status, - uint16_t conn_handle, - uint8_t adv_set_id, - hci::AddressWithType adv_address, - bool is_discoverable); + virtual void OnAdvertisingSetTerminated(ErrorCode status, uint16_t conn_handle, + uint8_t adv_set_id, hci::AddressWithType adv_address, + bool is_discoverable); virtual LeAddressManager* GetLeAddressManager(); @@ -148,7 +137,7 @@ class AclManager : public Module { static const ModuleFactory Factory; - protected: +protected: void ListDependencies(ModuleList* list) const override; void Start() override; @@ -158,9 +147,9 @@ class AclManager : public Module { std::string ToString() const override; DumpsysDataFinisher GetDumpsysData( - flatbuffers::FlatBufferBuilder* builder) const override; // Module + flatbuffers::FlatBufferBuilder* builder) const override; // Module - private: +private: virtual uint16_t HACK_GetHandle(const Address address); virtual uint16_t HACK_GetLeHandle(const Address address); virtual Address HACK_GetLeAddress(uint16_t connection_handle); diff --git a/system/gd/hci/acl_manager/acl_connection.cc b/system/gd/hci/acl_manager/acl_connection.cc index c678bf978ac..e616416f630 100644 --- a/system/gd/hci/acl_manager/acl_connection.cc +++ b/system/gd/hci/acl_manager/acl_connection.cc @@ -20,9 +20,7 @@ namespace bluetooth { namespace hci { namespace acl_manager { -AclConnection::QueueUpEnd* AclConnection::GetAclQueueEnd() const { - return queue_up_end_; -} +AclConnection::QueueUpEnd* AclConnection::GetAclQueueEnd() const { return queue_up_end_; } } // namespace acl_manager } // namespace hci diff --git a/system/gd/hci/acl_manager/acl_connection.h b/system/gd/hci/acl_manager/acl_connection.h index e2514e1b60d..0a7e7d1f07b 100644 --- a/system/gd/hci/acl_manager/acl_connection.h +++ b/system/gd/hci/acl_manager/acl_connection.h @@ -24,16 +24,14 @@ namespace hci { namespace acl_manager { class AclConnection { - public: - AclConnection() : queue_up_end_(nullptr), handle_(0){}; +public: + AclConnection() : queue_up_end_(nullptr), handle_(0) {} AclConnection(const AclConnection&) = delete; AclConnection& operator=(const AclConnection&) = delete; virtual ~AclConnection() = default; - uint16_t GetHandle() const { - return handle_; - } + uint16_t GetHandle() const { return handle_; } virtual bool ReadRemoteVersionInformation() = 0; @@ -44,8 +42,9 @@ class AclConnection { bool locally_initiated_{false}; - protected: - AclConnection(QueueUpEnd* queue_up_end, uint16_t handle) : queue_up_end_(queue_up_end), handle_(handle) {} +protected: + AclConnection(QueueUpEnd* queue_up_end, uint16_t handle) + : queue_up_end_(queue_up_end), handle_(handle) {} QueueUpEnd* queue_up_end_; uint16_t handle_; }; diff --git a/system/gd/hci/acl_manager/acl_fragmenter.h b/system/gd/hci/acl_manager/acl_fragmenter.h index a7379c6f8b8..28d14c1a3aa 100644 --- a/system/gd/hci/acl_manager/acl_fragmenter.h +++ b/system/gd/hci/acl_manager/acl_fragmenter.h @@ -27,13 +27,13 @@ namespace hci { namespace acl_manager { class AclFragmenter { - public: +public: AclFragmenter(size_t mtu, std::unique_ptr input); virtual ~AclFragmenter() = default; std::vector> GetFragments(); - private: +private: size_t mtu_; std::unique_ptr packet_; }; diff --git a/system/gd/hci/acl_manager/acl_scheduler.cc b/system/gd/hci/acl_manager/acl_scheduler.cc index 4f7afec9166..5d9ae4e689f 100644 --- a/system/gd/hci/acl_manager/acl_scheduler.cc +++ b/system/gd/hci/acl_manager/acl_scheduler.cc @@ -41,8 +41,10 @@ struct RemoteNameRequestQueueEntry { using QueueEntry = std::variant; struct AclScheduler::impl { - void EnqueueOutgoingAclConnection(Address address, common::ContextualOnceCallback start_connection) { - pending_outgoing_operations_.push_back(AclCreateConnectionQueueEntry{address, std::move(start_connection)}); + void EnqueueOutgoingAclConnection(Address address, + common::ContextualOnceCallback start_connection) { + pending_outgoing_operations_.push_back( + AclCreateConnectionQueueEntry{address, std::move(start_connection)}); try_dequeue_next_operation(); } @@ -51,11 +53,11 @@ struct AclScheduler::impl { } void ReportAclConnectionCompletion( - Address address, - common::ContextualOnceCallback handle_outgoing_connection, - common::ContextualOnceCallback handle_incoming_connection, - common::ContextualOnceCallback handle_unknown_connection) { - // Check if an outgoing request (a) exists, (b) is a Create Connection, (c) matches the received address + Address address, common::ContextualOnceCallback handle_outgoing_connection, + common::ContextualOnceCallback handle_incoming_connection, + common::ContextualOnceCallback handle_unknown_connection) { + // Check if an outgoing request (a) exists, (b) is a Create Connection, (c) matches the received + // address if (outgoing_entry_.has_value()) { auto entry = std::get_if(&outgoing_entry_.value()); if (entry != nullptr && entry->address == address) { @@ -91,28 +93,26 @@ struct AclScheduler::impl { try_dequeue_next_operation(); } - void CancelAclConnection( - Address address, - common::ContextualOnceCallback cancel_connection, - common::ContextualOnceCallback cancel_connection_completed) { + void CancelAclConnection(Address address, + common::ContextualOnceCallback cancel_connection, + common::ContextualOnceCallback cancel_connection_completed) { auto ok = cancel_outgoing_or_queued_connection( - [&](auto& entry) { - auto entry_ptr = std::get_if(&entry); - return entry_ptr != nullptr && entry_ptr->address == address; - }, - [&]() { cancel_connection(); }, - [&](auto /* entry */) { cancel_connection_completed(); }); + [&](auto& entry) { + auto entry_ptr = std::get_if(&entry); + return entry_ptr != nullptr && entry_ptr->address == address; + }, + [&]() { cancel_connection(); }, + [&](auto /* entry */) { cancel_connection_completed(); }); if (!ok) { log::error("Attempted to cancel connection to {} that does not exist", address); } } - void EnqueueRemoteNameRequest( - Address address, - common::ContextualOnceCallback start_request, - common::ContextualOnceCallback cancel_request_completed) { - pending_outgoing_operations_.push_back( - RemoteNameRequestQueueEntry{address, std::move(start_request), std::move(cancel_request_completed)}); + void EnqueueRemoteNameRequest(Address address, + common::ContextualOnceCallback start_request, + common::ContextualOnceCallback cancel_request_completed) { + pending_outgoing_operations_.push_back(RemoteNameRequestQueueEntry{ + address, std::move(start_request), std::move(cancel_request_completed)}); try_dequeue_next_operation(); } @@ -123,42 +123,43 @@ struct AclScheduler::impl { } std::visit( - [](auto&& entry) { - using T = std::decay_t; - if constexpr (std::is_same_v) { - log::info("Remote name request completed"); - } else if constexpr (std::is_same_v) { - log::error( - "Received RNR completion when ACL connection is outstanding - assuming the " - "connection has failed and continuing"); - } else { - static_assert(!sizeof(T*), "non-exhaustive visitor!"); - } - }, - outgoing_entry_.value()); + [](auto&& entry) { + using T = std::decay_t; + if constexpr (std::is_same_v) { + log::info("Remote name request completed"); + } else if constexpr (std::is_same_v) { + log::error( + "Received RNR completion when ACL connection is outstanding - assuming the " + "connection has failed and continuing"); + } else { + static_assert(!sizeof(T*), "non-exhaustive visitor!"); + } + }, + outgoing_entry_.value()); outgoing_entry_.reset(); try_dequeue_next_operation(); } - void CancelRemoteNameRequest(Address address, common::ContextualOnceCallback cancel_request) { + void CancelRemoteNameRequest(Address address, + common::ContextualOnceCallback cancel_request) { auto ok = cancel_outgoing_or_queued_connection( - [&](auto& entry) { - auto entry_ptr = std::get_if(&entry); - return entry_ptr != nullptr && entry_ptr->address == address; - }, - [&]() { cancel_request(); }, - [](auto entry) { std::get(entry).callback_when_cancelled(); }); + [&](auto& entry) { + auto entry_ptr = std::get_if(&entry); + return entry_ptr != nullptr && entry_ptr->address == address; + }, + [&]() { cancel_request(); }, + [](auto entry) { + std::get(entry).callback_when_cancelled(); + }); if (!ok) { log::error("Attempted to cancel remote name request to {} that does not exist", address); } - }; - - void Stop() { - stopped_ = true; } - private: + void Stop() { stopped_ = true; } + +private: void try_dequeue_next_operation() { if (stopped_) { return; @@ -183,7 +184,8 @@ struct AclScheduler::impl { } } // Otherwise, clear from the queue - auto it = std::find_if(pending_outgoing_operations_.begin(), pending_outgoing_operations_.end(), matcher); + auto it = std::find_if(pending_outgoing_operations_.begin(), pending_outgoing_operations_.end(), + matcher); if (it == pending_outgoing_operations_.end()) { return false; } @@ -194,7 +196,9 @@ struct AclScheduler::impl { const std::string set_of_incoming_connecting_addresses() const { std::stringstream buffer; - for (const auto& c : incoming_connecting_address_set_) buffer << " " << c; + for (const auto& c : incoming_connecting_address_set_) { + buffer << " " << c; + } return buffer.str(); } @@ -206,31 +210,27 @@ struct AclScheduler::impl { const ModuleFactory AclScheduler::Factory = ModuleFactory([]() { return new AclScheduler(); }); -AclScheduler::AclScheduler() : pimpl_(std::make_unique()){}; +AclScheduler::AclScheduler() : pimpl_(std::make_unique()) {} AclScheduler::~AclScheduler() = default; void AclScheduler::EnqueueOutgoingAclConnection( - Address address, common::ContextualOnceCallback start_connection) { - GetHandler()->Call( - &impl::EnqueueOutgoingAclConnection, common::Unretained(pimpl_.get()), address, std::move(start_connection)); + Address address, common::ContextualOnceCallback start_connection) { + GetHandler()->Call(&impl::EnqueueOutgoingAclConnection, common::Unretained(pimpl_.get()), address, + std::move(start_connection)); } void AclScheduler::RegisterPendingIncomingConnection(Address address) { - GetHandler()->Call(&impl::RegisterPendingIncomingConnection, common::Unretained(pimpl_.get()), address); + GetHandler()->Call(&impl::RegisterPendingIncomingConnection, common::Unretained(pimpl_.get()), + address); } void AclScheduler::ReportAclConnectionCompletion( - Address address, - common::ContextualOnceCallback handle_outgoing_connection, - common::ContextualOnceCallback handle_incoming_connection, - common::ContextualOnceCallback handle_unknown_connection) { - GetHandler()->Call( - &impl::ReportAclConnectionCompletion, - common::Unretained(pimpl_.get()), - address, - std::move(handle_outgoing_connection), - std::move(handle_incoming_connection), - std::move(handle_unknown_connection)); + Address address, common::ContextualOnceCallback handle_outgoing_connection, + common::ContextualOnceCallback handle_incoming_connection, + common::ContextualOnceCallback handle_unknown_connection) { + GetHandler()->Call(&impl::ReportAclConnectionCompletion, common::Unretained(pimpl_.get()), + address, std::move(handle_outgoing_connection), + std::move(handle_incoming_connection), std::move(handle_unknown_connection)); } void AclScheduler::ReportOutgoingAclConnectionFailure() { @@ -238,45 +238,35 @@ void AclScheduler::ReportOutgoingAclConnectionFailure() { } void AclScheduler::CancelAclConnection( - Address address, - common::ContextualOnceCallback cancel_connection, - common::ContextualOnceCallback cancel_connection_completed) { - GetHandler()->Call( - &impl::CancelAclConnection, - common::Unretained(pimpl_.get()), - address, - std::move(cancel_connection), - std::move(cancel_connection_completed)); + Address address, common::ContextualOnceCallback cancel_connection, + common::ContextualOnceCallback cancel_connection_completed) { + GetHandler()->Call(&impl::CancelAclConnection, common::Unretained(pimpl_.get()), address, + std::move(cancel_connection), std::move(cancel_connection_completed)); } void AclScheduler::EnqueueRemoteNameRequest( - Address address, - common::ContextualOnceCallback start_request, - common::ContextualOnceCallback cancel_request_completed) { - GetHandler()->Call( - &impl::EnqueueRemoteNameRequest, - common::Unretained(pimpl_.get()), - address, - std::move(start_request), - std::move(cancel_request_completed)); + Address address, common::ContextualOnceCallback start_request, + common::ContextualOnceCallback cancel_request_completed) { + GetHandler()->Call(&impl::EnqueueRemoteNameRequest, common::Unretained(pimpl_.get()), address, + std::move(start_request), std::move(cancel_request_completed)); } void AclScheduler::ReportRemoteNameRequestCompletion(Address address) { - GetHandler()->Call(&impl::ReportRemoteNameRequestCompletion, common::Unretained(pimpl_.get()), address); + GetHandler()->Call(&impl::ReportRemoteNameRequestCompletion, common::Unretained(pimpl_.get()), + address); } -void AclScheduler::CancelRemoteNameRequest(Address address, common::ContextualOnceCallback cancel_request) { - GetHandler()->Call( - &impl::CancelRemoteNameRequest, common::Unretained(pimpl_.get()), address, std::move(cancel_request)); +void AclScheduler::CancelRemoteNameRequest(Address address, + common::ContextualOnceCallback cancel_request) { + GetHandler()->Call(&impl::CancelRemoteNameRequest, common::Unretained(pimpl_.get()), address, + std::move(cancel_request)); } void AclScheduler::ListDependencies(ModuleList* /* list */) const {} void AclScheduler::Start() {} -void AclScheduler::Stop() { - pimpl_->Stop(); -} +void AclScheduler::Stop() { pimpl_->Stop(); } } // namespace acl_manager } // namespace hci diff --git a/system/gd/hci/acl_manager/acl_scheduler.h b/system/gd/hci/acl_manager/acl_scheduler.h index 77bf2a5f69a..c90ab119833 100644 --- a/system/gd/hci/acl_manager/acl_scheduler.h +++ b/system/gd/hci/acl_manager/acl_scheduler.h @@ -27,69 +27,68 @@ namespace bluetooth { namespace hci { namespace acl_manager { -// The AclScheduler is responsible for *scheduling* ACL connection-related operations (outgoing connections, -// incoming connections, and remote name requests). It maintains a queue of operations initiated by us, and tracks -// all incoming connections. We should never initiate a connection operation directly - instead, it should always -// pass through this class, so that we can be sure that it does not conflict with other operations. +// The AclScheduler is responsible for *scheduling* ACL connection-related operations (outgoing +// connections, incoming connections, and remote name requests). It maintains a queue of operations +// initiated by us, and tracks all incoming connections. We should never initiate a connection +// operation directly - instead, it should always pass through this class, so that we can be sure +// that it does not conflict with other operations. // -// However, it does not perform any actual HCI operations itself - it simply takes in callbacks, and executes them -// at the appropriate time. +// However, it does not perform any actual HCI operations itself - it simply takes in callbacks, and +// executes them at the appropriate time. class AclScheduler : public bluetooth::Module { - public: +public: // Schedule an ACL Create Connection request - void EnqueueOutgoingAclConnection(Address address, common::ContextualOnceCallback start_connection); + void EnqueueOutgoingAclConnection(Address address, + common::ContextualOnceCallback start_connection); - // Inform the scheduler that we are handling an incoming connection. This will block all future outgoing ACL - // connection events until the incoming connection is deregistered. + // Inform the scheduler that we are handling an incoming connection. This will block all future + // outgoing ACL connection events until the incoming connection is deregistered. void RegisterPendingIncomingConnection(Address address); - // Report that an ACL connection has completed, and dispatch to the appropriate callback based on the internal - // state. Then, start the next operation. + // Report that an ACL connection has completed, and dispatch to the appropriate callback based on + // the internal state. Then, start the next operation. virtual void ReportAclConnectionCompletion( - Address address, - common::ContextualOnceCallback handle_outgoing_connection, - common::ContextualOnceCallback handle_incoming_connection, - common::ContextualOnceCallback handle_unknown_connection); + Address address, common::ContextualOnceCallback handle_outgoing_connection, + common::ContextualOnceCallback handle_incoming_connection, + common::ContextualOnceCallback handle_unknown_connection); // Same as above, but for the outgoing ACL connection in particular (and no callbacks) void ReportOutgoingAclConnectionFailure(); - // Cancel an ACL connection. If the request is already outgoing, we will invoke cancel_connection, without clearing - // the outgoing request. Otherwise, we will remove the request from the queue, invoke cancel_connection_completed, - // and execute the next request in the queue. - void CancelAclConnection( - Address address, - common::ContextualOnceCallback cancel_connection, - common::ContextualOnceCallback cancel_connection_completed); - - // Schedule a Remote Name Request. When the request is started, start_request will be invoked. If the request is - // cancelled before it is dequeued, cancel_request_completed will be invoked. - void EnqueueRemoteNameRequest( - Address address, - common::ContextualOnceCallback start_request, - common::ContextualOnceCallback cancel_request_completed); - - // Report that a Remote Name Request connection has completed, so we can resume popping from the queue. + // Cancel an ACL connection. If the request is already outgoing, we will invoke cancel_connection, + // without clearing the outgoing request. Otherwise, we will remove the request from the queue, + // invoke cancel_connection_completed, and execute the next request in the queue. + void CancelAclConnection(Address address, + common::ContextualOnceCallback cancel_connection, + common::ContextualOnceCallback cancel_connection_completed); + + // Schedule a Remote Name Request. When the request is started, start_request will be invoked. If + // the request is cancelled before it is dequeued, cancel_request_completed will be invoked. + void EnqueueRemoteNameRequest(Address address, + common::ContextualOnceCallback start_request, + common::ContextualOnceCallback cancel_request_completed); + + // Report that a Remote Name Request connection has completed, so we can resume popping from the + // queue. void ReportRemoteNameRequestCompletion(Address address); - // Cancel an Remote Name Request. If the request is already outgoing, we will invoke cancel_request, without - // clearing the outgoing request. Otherwise, we will invoke the cancel_request_completed callback registered on - // the initial enqueue. - void CancelRemoteNameRequest(Address address, common::ContextualOnceCallback cancel_request); + // Cancel an Remote Name Request. If the request is already outgoing, we will invoke + // cancel_request, without clearing the outgoing request. Otherwise, we will invoke the + // cancel_request_completed callback registered on the initial enqueue. + void CancelRemoteNameRequest(Address address, + common::ContextualOnceCallback cancel_request); - private: +private: struct impl; std::unique_ptr pimpl_; - protected: +protected: void ListDependencies(ModuleList* list) const override; void Start() override; void Stop() override; - std::string ToString() const override { - return std::string("AclSchedulerModule"); - } + std::string ToString() const override { return std::string("AclSchedulerModule"); } - public: +public: static const ModuleFactory Factory; AclScheduler(); virtual ~AclScheduler(); diff --git a/system/gd/hci/acl_manager/acl_scheduler_test.cc b/system/gd/hci/acl_manager/acl_scheduler_test.cc index 1c64c8c3222..f2ca86b652a 100644 --- a/system/gd/hci/acl_manager/acl_scheduler_test.cc +++ b/system/gd/hci/acl_manager/acl_scheduler_test.cc @@ -45,7 +45,7 @@ MATCHER(IsSet, "Future is set") { } class AclSchedulerTest : public ::testing::Test { - protected: +protected: void SetUp() override { fake_registry_.Start(&thread_); ASSERT_TRUE(fake_registry_.IsStarted()); @@ -53,7 +53,8 @@ class AclSchedulerTest : public ::testing::Test { client_handler_ = fake_registry_.GetTestModuleHandler(&AclScheduler::Factory); ASSERT_NE(client_handler_, nullptr); - acl_scheduler_ = static_cast(fake_registry_.GetModuleUnderTest(&AclScheduler::Factory)); + acl_scheduler_ = + static_cast(fake_registry_.GetModuleUnderTest(&AclScheduler::Factory)); ::testing::FLAGS_gtest_death_test_style = "threadsafe"; } @@ -71,10 +72,11 @@ class AclSchedulerTest : public ::testing::Test { return client_handler_->BindOnce([](std::string /* _ */) {}); } - common::ContextualOnceCallback promiseCallbackTakingString(std::promise promise) { + common::ContextualOnceCallback promiseCallbackTakingString( + std::promise promise) { return client_handler_->BindOnce( - [](std::promise promise, std::string /* _ */) { promise.set_value(); }, - std::move(promise)); + [](std::promise promise, std::string /* _ */) { promise.set_value(); }, + std::move(promise)); } common::ContextualOnceCallback impossibleCallback() { @@ -86,7 +88,8 @@ class AclSchedulerTest : public ::testing::Test { } common::ContextualOnceCallback promiseCallback(std::promise promise) { - return client_handler_->BindOnce([](std::promise promise) { promise.set_value(); }, std::move(promise)); + return client_handler_->BindOnce([](std::promise promise) { promise.set_value(); }, + std::move(promise)); } TestModuleRegistry fake_registry_; @@ -144,8 +147,9 @@ TEST_F(AclSchedulerTest, SingleConnectionCompletionCallback) { acl_scheduler_->EnqueueOutgoingAclConnection(address1, emptyCallback()); // the outgoing connection completes - acl_scheduler_->ReportAclConnectionCompletion( - address1, promiseCallback(std::move(promise)), impossibleCallback(), impossibleCallbackTakingString()); + acl_scheduler_->ReportAclConnectionCompletion(address1, promiseCallback(std::move(promise)), + impossibleCallback(), + impossibleCallbackTakingString()); // the outgoing_connection callback should have executed EXPECT_THAT(future, IsSet()); @@ -161,8 +165,8 @@ TEST_F(AclSchedulerTest, SingleConnectionCompletionDequeueNext) { acl_scheduler_->EnqueueOutgoingAclConnection(address2, promiseCallback(std::move(promise))); // complete the first connection - acl_scheduler_->ReportAclConnectionCompletion( - address1, emptyCallback(), impossibleCallback(), impossibleCallbackTakingString()); + acl_scheduler_->ReportAclConnectionCompletion(address1, emptyCallback(), impossibleCallback(), + impossibleCallbackTakingString()); // the next connection should dequeue now EXPECT_THAT(future, IsSet()); @@ -176,8 +180,9 @@ TEST_F(AclSchedulerTest, IncomingConnectionCallback) { acl_scheduler_->RegisterPendingIncomingConnection(address1); // and completes - acl_scheduler_->ReportAclConnectionCompletion( - address1, impossibleCallback(), promiseCallback(std::move(promise)), impossibleCallbackTakingString()); + acl_scheduler_->ReportAclConnectionCompletion(address1, impossibleCallback(), + promiseCallback(std::move(promise)), + impossibleCallbackTakingString()); // the incoming_connection callback should have executed EXPECT_THAT(future, IsSet()); @@ -194,8 +199,9 @@ TEST_F(AclSchedulerTest, UnknownConnectionCallback) { acl_scheduler_->RegisterPendingIncomingConnection(address2); // then an unknown connection completes - acl_scheduler_->ReportAclConnectionCompletion( - address3, impossibleCallback(), impossibleCallback(), (promiseCallbackTakingString(std::move(promise)))); + acl_scheduler_->ReportAclConnectionCompletion(address3, impossibleCallback(), + impossibleCallback(), + (promiseCallbackTakingString(std::move(promise)))); // the unknown_connection callback should have executed EXPECT_THAT(future, IsSet()); @@ -212,12 +218,13 @@ TEST_F(AclSchedulerTest, TiebreakForOutgoingConnection) { acl_scheduler_->RegisterPendingIncomingConnection(address1); // then the connection to that address completes - acl_scheduler_->ReportAclConnectionCompletion( - address1, promiseCallback(std::move(promise)), impossibleCallback(), impossibleCallbackTakingString()); + acl_scheduler_->ReportAclConnectionCompletion(address1, promiseCallback(std::move(promise)), + impossibleCallback(), + impossibleCallbackTakingString()); // the outgoing_connection callback should have executed, NOT the incoming_connection one - // this preserves working behavior, it is not based on any principled decision (so if you need to break this test, - // go for it) + // this preserves working behavior, it is not based on any principled decision (so if you need to + // break this test, go for it) EXPECT_THAT(future, IsSet()); } @@ -234,15 +241,15 @@ TEST_F(AclSchedulerTest, QueueWhileIncomingConnectionsPending) { acl_scheduler_->RegisterPendingIncomingConnection(address3); // then the first outgoing connection completes - acl_scheduler_->ReportAclConnectionCompletion( - address1, emptyCallback(), impossibleCallback(), impossibleCallbackTakingString()); + acl_scheduler_->ReportAclConnectionCompletion(address1, emptyCallback(), impossibleCallback(), + impossibleCallbackTakingString()); // the outgoing_connection callback should not have executed yet EXPECT_THAT(future.wait_for(timeout), std::future_status::timeout); // now the incoming connection completes - acl_scheduler_->ReportAclConnectionCompletion( - address3, impossibleCallback(), emptyCallback(), impossibleCallbackTakingString()); + acl_scheduler_->ReportAclConnectionCompletion(address3, impossibleCallback(), emptyCallback(), + impossibleCallbackTakingString()); // only now does the next outgoing connection start EXPECT_THAT(future, IsSet()); @@ -265,15 +272,15 @@ TEST_F(AclSchedulerTest, DoNothingWhileIncomingConnectionsExist) { acl_scheduler_->RegisterPendingIncomingConnection(address3); // the first incoming connection completes - acl_scheduler_->ReportAclConnectionCompletion( - address1, impossibleCallback(), emptyCallback(), impossibleCallbackTakingString()); + acl_scheduler_->ReportAclConnectionCompletion(address1, impossibleCallback(), emptyCallback(), + impossibleCallbackTakingString()); // the outgoing_connection callback should *still* not have executed yet EXPECT_THAT(future.wait_for(timeout), std::future_status::timeout); // the second incoming connection completes, so none are left - acl_scheduler_->ReportAclConnectionCompletion( - address3, impossibleCallback(), emptyCallback(), impossibleCallbackTakingString()); + acl_scheduler_->ReportAclConnectionCompletion(address3, impossibleCallback(), emptyCallback(), + impossibleCallbackTakingString()); // only now does the outgoing connection start EXPECT_THAT(future, IsSet()); @@ -295,8 +302,8 @@ TEST_F(AclSchedulerTest, CancelOutgoingConnection) { EXPECT_THAT(future.wait_for(timeout), std::future_status::timeout); // now the cancel completes (with a failed status, in reality, but the scheduler doesn't care) - acl_scheduler_->ReportAclConnectionCompletion( - address1, emptyCallback(), impossibleCallback(), impossibleCallbackTakingString()); + acl_scheduler_->ReportAclConnectionCompletion(address1, emptyCallback(), impossibleCallback(), + impossibleCallbackTakingString()); // so only now do we advance the queue EXPECT_THAT(future, IsSet()); @@ -310,9 +317,11 @@ TEST_F(AclSchedulerTest, CancelOutgoingConnectionCallback) { acl_scheduler_->EnqueueOutgoingAclConnection(address1, emptyCallback()); // cancel the outgoing connection - acl_scheduler_->CancelAclConnection(address1, promiseCallback(std::move(promise)), impossibleCallback()); + acl_scheduler_->CancelAclConnection(address1, promiseCallback(std::move(promise)), + impossibleCallback()); - // we expect the cancel_connection callback to be invoked since we are cancelling an actually active connection + // we expect the cancel_connection callback to be invoked since we are cancelling an actually + // active connection EXPECT_THAT(future, IsSet()); } @@ -350,9 +359,11 @@ TEST_F(AclSchedulerTest, CancelQueuedConnectionCallback) { acl_scheduler_->EnqueueOutgoingAclConnection(address2, emptyCallback()); // cancel the queued connection - acl_scheduler_->CancelAclConnection(address2, impossibleCallback(), promiseCallback(std::move(promise))); + acl_scheduler_->CancelAclConnection(address2, impossibleCallback(), + promiseCallback(std::move(promise))); - // we expect the cancel_connection_completed callback to be invoked since we are cancelling a connection in the queue + // we expect the cancel_connection_completed callback to be invoked since we are cancelling a + // connection in the queue EXPECT_THAT(future, IsSet()); } @@ -361,7 +372,8 @@ TEST_F(AclSchedulerTest, RemoteNameRequestImmediatelyExecuted) { auto future = promise.get_future(); // start an outgoing request - acl_scheduler_->EnqueueRemoteNameRequest(address1, promiseCallback(std::move(promise)), emptyCallback()); + acl_scheduler_->EnqueueRemoteNameRequest(address1, promiseCallback(std::move(promise)), + emptyCallback()); // we expect the start callback to be invoked immediately EXPECT_THAT(future, IsSet()); @@ -374,7 +386,8 @@ TEST_F(AclSchedulerTest, RemoteNameRequestQueuing) { // start an outgoing request acl_scheduler_->EnqueueRemoteNameRequest(address1, emptyCallback(), impossibleCallback()); // enqueue a second one - acl_scheduler_->EnqueueRemoteNameRequest(address2, promiseCallback(std::move(promise)), impossibleCallback()); + acl_scheduler_->EnqueueRemoteNameRequest(address2, promiseCallback(std::move(promise)), + impossibleCallback()); // we should still be queued EXPECT_THAT(future.wait_for(timeout), std::future_status::timeout); @@ -407,7 +420,8 @@ TEST_F(AclSchedulerTest, RemoteNameRequestCancellationWhileQueuedCallback) { // start an outgoing request acl_scheduler_->EnqueueRemoteNameRequest(address1, emptyCallback(), impossibleCallback()); // enqueue a second one - acl_scheduler_->EnqueueRemoteNameRequest(address2, impossibleCallback(), promiseCallback(std::move(promise))); + acl_scheduler_->EnqueueRemoteNameRequest(address2, impossibleCallback(), + promiseCallback(std::move(promise))); // cancel the second one acl_scheduler_->CancelRemoteNameRequest(address2, impossibleCallback()); @@ -431,7 +445,8 @@ TEST_F(AclSchedulerTest, CancelQueuedRemoteNameRequestRemoveFromQueue) { // start another connection that will queue acl_scheduler_->EnqueueRemoteNameRequest(address2, impossibleCallback(), emptyCallback()); // start a third connection that will queue - acl_scheduler_->EnqueueRemoteNameRequest(address3, promiseCallback(std::move(promise)), impossibleCallback()); + acl_scheduler_->EnqueueRemoteNameRequest(address3, promiseCallback(std::move(promise)), + impossibleCallback()); // cancel the first queued connection acl_scheduler_->CancelRemoteNameRequest(address2, impossibleCallback()); @@ -453,7 +468,8 @@ TEST_F(AclSchedulerTest, RemoteNameRequestCancellationShouldDequeueNext) { // start an outgoing request acl_scheduler_->EnqueueRemoteNameRequest(address1, emptyCallback(), impossibleCallback()); // enqueue a second one - acl_scheduler_->EnqueueRemoteNameRequest(address2, promiseCallback(std::move(promise)), impossibleCallback()); + acl_scheduler_->EnqueueRemoteNameRequest(address2, promiseCallback(std::move(promise)), + impossibleCallback()); // we should still be queued EXPECT_THAT(future.wait_for(timeout), std::future_status::timeout); diff --git a/system/gd/hci/acl_manager/assembler.h b/system/gd/hci/acl_manager/assembler.h index 09125dd8551..147cc7a99e2 100644 --- a/system/gd/hci/acl_manager/assembler.h +++ b/system/gd/hci/acl_manager/assembler.h @@ -39,22 +39,18 @@ constexpr size_t kL2capBasicFrameHeaderSize = 4; namespace { // This is a helper class to keep the state of the assembler and expose PacketView<>::Append. class PacketViewForRecombination : public packet::PacketView { - public: +public: PacketViewForRecombination(const PacketView& packetView) : PacketView(packetView), received_first_(true) {} PacketViewForRecombination() : PacketView(PacketView(std::make_shared>())) {} - void AppendPacketView(packet::PacketView to_append) { - Append(to_append); - } + void AppendPacketView(packet::PacketView to_append) { Append(to_append); } - bool ReceivedFirstPacket() { - return received_first_; - } + bool ReceivedFirstPacket() { return received_first_; } - private: +private: bool received_first_{}; }; @@ -71,7 +67,8 @@ size_t GetL2capPduSize(packet::PacketView pdu) { } // namespace struct assembler { - assembler(AddressWithType address_with_type, AclConnection::QueueDownEnd* down_end, os::Handler* handler) + assembler(AddressWithType address_with_type, AclConnection::QueueDownEnd* down_end, + os::Handler* handler) : address_with_type_(address_with_type), down_end_(down_end), handler_(handler) {} AddressWithType address_with_type_; AclConnection::QueueDownEnd* down_end_; @@ -106,8 +103,8 @@ struct assembler { auto packet_boundary_flag = packet.GetPacketBoundaryFlag(); if (packet_boundary_flag == PacketBoundaryFlag::FIRST_NON_AUTOMATICALLY_FLUSHABLE) { log::error( - "Controller is not allowed to send FIRST_NON_AUTOMATICALLY_FLUSHABLE to host except " - "loopback mode"); + "Controller is not allowed to send FIRST_NON_AUTOMATICALLY_FLUSHABLE to host except " + "loopback mode"); return; } if (packet_boundary_flag == PacketBoundaryFlag::CONTINUING_FRAGMENT) { @@ -119,8 +116,9 @@ struct assembler { } else if (packet_boundary_flag == PacketBoundaryFlag::FIRST_AUTOMATICALLY_FLUSHABLE) { if (recombination_stage_.ReceivedFirstPacket()) { log::error( - "Controller sent a starting packet without finishing previous packet. Drop previous " - "one."); + "Controller sent a starting packet without finishing previous packet. Drop " + "previous " + "one."); } recombination_stage_ = payload; } @@ -143,8 +141,8 @@ struct assembler { incoming_queue_.push(recombination_stage_); recombination_stage_ = PacketViewForRecombination(); if (!enqueue_registered_->exchange(true)) { - down_end_->RegisterEnqueue( - handler_, common::Bind(&assembler::on_data_ready, common::Unretained(this))); + down_end_->RegisterEnqueue(handler_, + common::Bind(&assembler::on_data_ready, common::Unretained(this))); } } }; diff --git a/system/gd/hci/acl_manager/classic_acl_connection.cc b/system/gd/hci/acl_manager/classic_acl_connection.cc index 2356a8f42d3..a2b6b9e30e1 100644 --- a/system/gd/hci/acl_manager/classic_acl_connection.cc +++ b/system/gd/hci/acl_manager/classic_acl_connection.cc @@ -29,15 +29,16 @@ namespace hci { namespace acl_manager { class AclConnectionTracker : public ConnectionManagementCallbacks { - public: - AclConnectionTracker( - AclConnectionInterface* acl_connection_interface, const Address& address, uint16_t connection_handle) - : acl_connection_interface_(acl_connection_interface), address_(address), connection_handle_(connection_handle) {} +public: + AclConnectionTracker(AclConnectionInterface* acl_connection_interface, const Address& address, + uint16_t connection_handle) + : acl_connection_interface_(acl_connection_interface), + address_(address), + connection_handle_(connection_handle) {} ~AclConnectionTracker() { // If callbacks were registered, they should have been delivered. - log::assert_that( - client_callbacks_ == nullptr || queued_callbacks_.empty(), - "assert failed: client_callbacks_ == nullptr || queued_callbacks_.empty()"); + log::assert_that(client_callbacks_ == nullptr || queued_callbacks_.empty(), + "assert failed: client_callbacks_ == nullptr || queued_callbacks_.empty()"); } void RegisterCallbacks(ConnectionManagementCallbacks* callbacks, os::Handler* handler) { client_handler_ = handler; @@ -49,13 +50,13 @@ class AclConnectionTracker : public ConnectionManagementCallbacks { } } -#define SAVE_OR_CALL(f, ...) \ - if (client_handler_ == nullptr) { \ - queued_callbacks_.emplace_back( \ - common::BindOnce(&ConnectionManagementCallbacks::f, common::Unretained(this), ##__VA_ARGS__)); \ - } else { \ - client_handler_->Post( \ - common::BindOnce(&ConnectionManagementCallbacks::f, common::Unretained(client_callbacks_), ##__VA_ARGS__)); \ +#define SAVE_OR_CALL(f, ...) \ + if (client_handler_ == nullptr) { \ + queued_callbacks_.emplace_back(common::BindOnce(&ConnectionManagementCallbacks::f, \ + common::Unretained(this), ##__VA_ARGS__)); \ + } else { \ + client_handler_->Post(common::BindOnce(&ConnectionManagementCallbacks::f, \ + common::Unretained(client_callbacks_), ##__VA_ARGS__)); \ } void OnConnectionPacketTypeChanged(uint16_t packet_type) override { @@ -76,33 +77,24 @@ class AclConnectionTracker : public ConnectionManagementCallbacks { void OnModeChange(ErrorCode status, Mode current_mode, uint16_t interval) override { SAVE_OR_CALL(OnModeChange, status, current_mode, interval) } - void OnSniffSubrating( - hci::ErrorCode hci_status, - uint16_t maximum_transmit_latency, - uint16_t maximum_receive_latency, - uint16_t minimum_remote_timeout, - uint16_t minimum_local_timeout) override { - SAVE_OR_CALL( - OnSniffSubrating, - hci_status, - maximum_transmit_latency, - maximum_receive_latency, - minimum_remote_timeout, - minimum_local_timeout); - } - void OnQosSetupComplete(ServiceType service_type, uint32_t token_rate, uint32_t peak_bandwidth, uint32_t latency, - uint32_t delay_variation) override { - SAVE_OR_CALL(OnQosSetupComplete, service_type, token_rate, peak_bandwidth, latency, delay_variation) - } - void OnFlowSpecificationComplete(FlowDirection flow_direction, ServiceType service_type, uint32_t token_rate, - uint32_t token_bucket_size, uint32_t peak_bandwidth, - uint32_t access_latency) override { - SAVE_OR_CALL(OnFlowSpecificationComplete, flow_direction, service_type, token_rate, token_bucket_size, - peak_bandwidth, access_latency) - } - void OnFlushOccurred() override { - SAVE_OR_CALL(OnFlushOccurred) + void OnSniffSubrating(hci::ErrorCode hci_status, uint16_t maximum_transmit_latency, + uint16_t maximum_receive_latency, uint16_t minimum_remote_timeout, + uint16_t minimum_local_timeout) override { + SAVE_OR_CALL(OnSniffSubrating, hci_status, maximum_transmit_latency, maximum_receive_latency, + minimum_remote_timeout, minimum_local_timeout); } + void OnQosSetupComplete(ServiceType service_type, uint32_t token_rate, uint32_t peak_bandwidth, + uint32_t latency, uint32_t delay_variation) override { + SAVE_OR_CALL(OnQosSetupComplete, service_type, token_rate, peak_bandwidth, latency, + delay_variation) + } + void OnFlowSpecificationComplete(FlowDirection flow_direction, ServiceType service_type, + uint32_t token_rate, uint32_t token_bucket_size, + uint32_t peak_bandwidth, uint32_t access_latency) override { + SAVE_OR_CALL(OnFlowSpecificationComplete, flow_direction, service_type, token_rate, + token_bucket_size, peak_bandwidth, access_latency) + } + void OnFlushOccurred() override { SAVE_OR_CALL(OnFlushOccurred) } void OnRoleDiscoveryComplete(Role current_role) override { SAVE_OR_CALL(OnRoleDiscoveryComplete, current_role) } @@ -113,27 +105,30 @@ class AclConnectionTracker : public ConnectionManagementCallbacks { SAVE_OR_CALL(OnReadAutomaticFlushTimeoutComplete, flush_timeout) } void OnReadTransmitPowerLevelComplete(uint8_t transmit_power_level) override { - bluetooth::os::LogMetricReadTxPowerLevelResult( - address_, connection_handle_, static_cast(ErrorCode::SUCCESS), transmit_power_level); + bluetooth::os::LogMetricReadTxPowerLevelResult(address_, connection_handle_, + static_cast(ErrorCode::SUCCESS), + transmit_power_level); SAVE_OR_CALL(OnReadTransmitPowerLevelComplete, transmit_power_level) } void OnReadLinkSupervisionTimeoutComplete(uint16_t link_supervision_timeout) override { SAVE_OR_CALL(OnReadLinkSupervisionTimeoutComplete, link_supervision_timeout) } void OnReadFailedContactCounterComplete(uint16_t failed_contact_counter) override { - bluetooth::os::LogMetricReadFailedContactCounterResult( - address_, connection_handle_, static_cast(ErrorCode::SUCCESS), failed_contact_counter); + bluetooth::os::LogMetricReadFailedContactCounterResult(address_, connection_handle_, + static_cast(ErrorCode::SUCCESS), + failed_contact_counter); SAVE_OR_CALL(OnReadFailedContactCounterComplete, failed_contact_counter); } void OnReadLinkQualityComplete(uint8_t link_quality) override { SAVE_OR_CALL(OnReadLinkQualityComplete, link_quality) } - void OnReadAfhChannelMapComplete(AfhMode afh_mode, std::array afh_channel_map) override { + void OnReadAfhChannelMapComplete(AfhMode afh_mode, + std::array afh_channel_map) override { SAVE_OR_CALL(OnReadAfhChannelMapComplete, afh_mode, afh_channel_map) } void OnReadRssiComplete(uint8_t rssi) override { - bluetooth::os::LogMetricReadRssiResult( - address_, connection_handle_, static_cast(ErrorCode::SUCCESS), rssi); + bluetooth::os::LogMetricReadRssiResult(address_, connection_handle_, + static_cast(ErrorCode::SUCCESS), rssi); SAVE_OR_CALL(OnReadRssiComplete, rssi); } void OnReadClockComplete(uint32_t clock, uint16_t accuracy) override { @@ -145,21 +140,22 @@ class AclConnectionTracker : public ConnectionManagementCallbacks { void OnRoleChange(hci::ErrorCode hci_status, Role new_role) override { SAVE_OR_CALL(OnRoleChange, hci_status, new_role) } - void OnReadRemoteVersionInformationComplete( - hci::ErrorCode hci_status, uint8_t lmp_version, uint16_t manufacturer_name, uint16_t sub_version) override { - bluetooth::os::LogMetricRemoteVersionInfo( - connection_handle_, static_cast(hci_status), lmp_version, manufacturer_name, sub_version); - SAVE_OR_CALL(OnReadRemoteVersionInformationComplete, hci_status, lmp_version, manufacturer_name, sub_version); + void OnReadRemoteVersionInformationComplete(hci::ErrorCode hci_status, uint8_t lmp_version, + uint16_t manufacturer_name, + uint16_t sub_version) override { + bluetooth::os::LogMetricRemoteVersionInfo(connection_handle_, static_cast(hci_status), + lmp_version, manufacturer_name, sub_version); + SAVE_OR_CALL(OnReadRemoteVersionInformationComplete, hci_status, lmp_version, manufacturer_name, + sub_version); } void OnReadRemoteSupportedFeaturesComplete(uint64_t features) override { SAVE_OR_CALL(OnReadRemoteSupportedFeaturesComplete, features); } - void OnReadRemoteExtendedFeaturesComplete(uint8_t page_number, uint8_t max_page_number, uint64_t features) override { + void OnReadRemoteExtendedFeaturesComplete(uint8_t page_number, uint8_t max_page_number, + uint64_t features) override { SAVE_OR_CALL(OnReadRemoteExtendedFeaturesComplete, page_number, max_page_number, features); } - void OnDisconnection(ErrorCode reason) { - SAVE_OR_CALL(OnDisconnection, reason); - } + void OnDisconnection(ErrorCode reason) { SAVE_OR_CALL(OnDisconnection, reason); } #undef SAVE_OR_CALL @@ -199,8 +195,8 @@ class AclConnectionTracker : public ConnectionManagementCallbacks { } else if (complete_view.GetStatus() != ErrorCode::SUCCESS) { auto status = complete_view.GetStatus(); std::string error_code = ErrorCodeText(status); - log::error( - "Received on_read_automatic_flush_timeout_complete with error code {}", error_code); + log::error("Received on_read_automatic_flush_timeout_complete with error code {}", + error_code); return; } OnReadAutomaticFlushTimeoutComplete(complete_view.GetFlushTimeout()); @@ -228,8 +224,8 @@ class AclConnectionTracker : public ConnectionManagementCallbacks { } else if (complete_view.GetStatus() != ErrorCode::SUCCESS) { auto status = complete_view.GetStatus(); std::string error_code = ErrorCodeText(status); - log::error( - "Received on_read_link_supervision_timeout_complete with error code {}", error_code); + log::error("Received on_read_link_supervision_timeout_complete with error code {}", + error_code); return; } OnReadLinkSupervisionTimeoutComplete(complete_view.GetLinkSupervisionTimeout()); @@ -328,20 +324,20 @@ class AclConnectionTracker : public ConnectionManagementCallbacks { }; struct ClassicAclConnection::impl { - impl( - AclConnectionInterface* acl_connection_interface, - std::shared_ptr queue, - const Address& address, - uint16_t connection_handle) + impl(AclConnectionInterface* acl_connection_interface, std::shared_ptr queue, + const Address& address, uint16_t connection_handle) : tracker(acl_connection_interface, address, connection_handle), queue_(std::move(queue)) {} - ConnectionManagementCallbacks* GetEventCallbacks(std::function invalidate_callbacks) { - log::assert_that( - !invalidate_callbacks_, "Already returned event callbacks for this connection"); + ConnectionManagementCallbacks* GetEventCallbacks( + std::function invalidate_callbacks) { + log::assert_that(!invalidate_callbacks_, + "Already returned event callbacks for this connection"); invalidate_callbacks_ = std::move(invalidate_callbacks); return &tracker; } void PutEventCallbacks() { - if (invalidate_callbacks_) invalidate_callbacks_(tracker.connection_handle_); + if (invalidate_callbacks_) { + invalidate_callbacks_(tracker.connection_handle_); + } invalidate_callbacks_ = {}; } @@ -354,261 +350,275 @@ ClassicAclConnection::ClassicAclConnection() : AclConnection(), acl_connection_interface_(nullptr), address_(Address::kEmpty) {} ClassicAclConnection::ClassicAclConnection(std::shared_ptr queue, - AclConnectionInterface* acl_connection_interface, uint16_t handle, - Address address) - : AclConnection(queue->GetUpEnd(), handle), acl_connection_interface_(acl_connection_interface), address_(address) { - pimpl_ = new ClassicAclConnection::impl(acl_connection_interface, std::move(queue), address, handle); + AclConnectionInterface* acl_connection_interface, + uint16_t handle, Address address) + : AclConnection(queue->GetUpEnd(), handle), + acl_connection_interface_(acl_connection_interface), + address_(address) { + pimpl_ = new ClassicAclConnection::impl(acl_connection_interface, std::move(queue), address, + handle); } ClassicAclConnection::~ClassicAclConnection() { - if (pimpl_) pimpl_->PutEventCallbacks(); + if (pimpl_) { + pimpl_->PutEventCallbacks(); + } delete pimpl_; } ConnectionManagementCallbacks* ClassicAclConnection::GetEventCallbacks( - std::function invalidate_callbacks) { + std::function invalidate_callbacks) { return pimpl_->GetEventCallbacks(std::move(invalidate_callbacks)); } -void ClassicAclConnection::RegisterCallbacks(ConnectionManagementCallbacks* callbacks, os::Handler* handler) { +void ClassicAclConnection::RegisterCallbacks(ConnectionManagementCallbacks* callbacks, + os::Handler* handler) { return pimpl_->tracker.RegisterCallbacks(callbacks, handler); } bool ClassicAclConnection::Disconnect(DisconnectReason reason) { acl_connection_interface_->EnqueueCommand( - DisconnectBuilder::Create(handle_, reason), - pimpl_->tracker.client_handler_->BindOnce(check_status)); + DisconnectBuilder::Create(handle_, reason), + pimpl_->tracker.client_handler_->BindOnce(check_status)); return true; } bool ClassicAclConnection::ChangeConnectionPacketType(uint16_t packet_type) { acl_connection_interface_->EnqueueCommand( - ChangeConnectionPacketTypeBuilder::Create(handle_, packet_type), - pimpl_->tracker.client_handler_->BindOnce( - check_status)); + ChangeConnectionPacketTypeBuilder::Create(handle_, packet_type), + pimpl_->tracker.client_handler_->BindOnce( + check_status)); return true; } bool ClassicAclConnection::AuthenticationRequested() { acl_connection_interface_->EnqueueCommand( - AuthenticationRequestedBuilder::Create(handle_), - pimpl_->tracker.client_handler_->BindOnce(check_status)); + AuthenticationRequestedBuilder::Create(handle_), + pimpl_->tracker.client_handler_->BindOnce( + check_status)); return true; } bool ClassicAclConnection::SetConnectionEncryption(Enable enable) { acl_connection_interface_->EnqueueCommand( - SetConnectionEncryptionBuilder::Create(handle_, enable), - pimpl_->tracker.client_handler_->BindOnce(check_status)); + SetConnectionEncryptionBuilder::Create(handle_, enable), + pimpl_->tracker.client_handler_->BindOnce( + check_status)); return true; } bool ClassicAclConnection::ChangeConnectionLinkKey() { acl_connection_interface_->EnqueueCommand( - ChangeConnectionLinkKeyBuilder::Create(handle_), - pimpl_->tracker.client_handler_->BindOnce(check_status)); + ChangeConnectionLinkKeyBuilder::Create(handle_), + pimpl_->tracker.client_handler_->BindOnce( + check_status)); return true; } bool ClassicAclConnection::ReadClockOffset() { acl_connection_interface_->EnqueueCommand( - ReadClockOffsetBuilder::Create(handle_), - pimpl_->tracker.client_handler_->BindOnce(check_status)); + ReadClockOffsetBuilder::Create(handle_), + pimpl_->tracker.client_handler_->BindOnce(check_status)); return true; } bool ClassicAclConnection::HoldMode(uint16_t max_interval, uint16_t min_interval) { acl_connection_interface_->EnqueueCommand( - HoldModeBuilder::Create(handle_, max_interval, min_interval), - pimpl_->tracker.client_handler_->BindOnce(check_status)); + HoldModeBuilder::Create(handle_, max_interval, min_interval), + pimpl_->tracker.client_handler_->BindOnce(check_status)); return true; } -bool ClassicAclConnection::SniffMode(uint16_t max_interval, uint16_t min_interval, uint16_t attempt, uint16_t timeout) { +bool ClassicAclConnection::SniffMode(uint16_t max_interval, uint16_t min_interval, uint16_t attempt, + uint16_t timeout) { acl_connection_interface_->EnqueueCommand( - SniffModeBuilder::Create(handle_, max_interval, min_interval, attempt, timeout), - pimpl_->tracker.client_handler_->BindOnce(check_status)); + SniffModeBuilder::Create(handle_, max_interval, min_interval, attempt, timeout), + pimpl_->tracker.client_handler_->BindOnce(check_status)); return true; } bool ClassicAclConnection::ExitSniffMode() { acl_connection_interface_->EnqueueCommand( - ExitSniffModeBuilder::Create(handle_), - pimpl_->tracker.client_handler_->BindOnce(check_status)); + ExitSniffModeBuilder::Create(handle_), + pimpl_->tracker.client_handler_->BindOnce(check_status)); return true; } -bool ClassicAclConnection::QosSetup(ServiceType service_type, uint32_t token_rate, uint32_t peak_bandwidth, - uint32_t latency, uint32_t delay_variation) { +bool ClassicAclConnection::QosSetup(ServiceType service_type, uint32_t token_rate, + uint32_t peak_bandwidth, uint32_t latency, + uint32_t delay_variation) { acl_connection_interface_->EnqueueCommand( - QosSetupBuilder::Create( - handle_, service_type, token_rate, peak_bandwidth, latency, delay_variation), - pimpl_->tracker.client_handler_->BindOnce(check_status)); + QosSetupBuilder::Create(handle_, service_type, token_rate, peak_bandwidth, latency, + delay_variation), + pimpl_->tracker.client_handler_->BindOnce(check_status)); return true; } bool ClassicAclConnection::RoleDiscovery() { acl_connection_interface_->EnqueueCommand( - RoleDiscoveryBuilder::Create(handle_), - pimpl_->tracker.client_handler_->BindOnceOn(&pimpl_->tracker, &AclConnectionTracker::on_role_discovery_complete)); + RoleDiscoveryBuilder::Create(handle_), + pimpl_->tracker.client_handler_->BindOnceOn( + &pimpl_->tracker, &AclConnectionTracker::on_role_discovery_complete)); return true; } bool ClassicAclConnection::ReadLinkPolicySettings() { acl_connection_interface_->EnqueueCommand( - ReadLinkPolicySettingsBuilder::Create(handle_), - pimpl_->tracker.client_handler_->BindOnceOn(&pimpl_->tracker, - &AclConnectionTracker::on_read_link_policy_settings_complete)); + ReadLinkPolicySettingsBuilder::Create(handle_), + pimpl_->tracker.client_handler_->BindOnceOn( + &pimpl_->tracker, &AclConnectionTracker::on_read_link_policy_settings_complete)); return true; } bool ClassicAclConnection::WriteLinkPolicySettings(uint16_t link_policy_settings) { acl_connection_interface_->EnqueueCommand( - WriteLinkPolicySettingsBuilder::Create(handle_, link_policy_settings), - pimpl_->tracker.client_handler_->BindOnce( - check_complete)); + WriteLinkPolicySettingsBuilder::Create(handle_, link_policy_settings), + pimpl_->tracker.client_handler_->BindOnce( + check_complete)); return true; } bool ClassicAclConnection::FlowSpecification(FlowDirection flow_direction, ServiceType service_type, - uint32_t token_rate, uint32_t token_bucket_size, uint32_t peak_bandwidth, - uint32_t access_latency) { + uint32_t token_rate, uint32_t token_bucket_size, + uint32_t peak_bandwidth, uint32_t access_latency) { acl_connection_interface_->EnqueueCommand( - FlowSpecificationBuilder::Create( - handle_, - flow_direction, - service_type, - token_rate, - token_bucket_size, - peak_bandwidth, - access_latency), - pimpl_->tracker.client_handler_->BindOnce(check_status)); + FlowSpecificationBuilder::Create(handle_, flow_direction, service_type, token_rate, + token_bucket_size, peak_bandwidth, access_latency), + pimpl_->tracker.client_handler_->BindOnce(check_status)); return true; } bool ClassicAclConnection::SniffSubrating(uint16_t maximum_latency, uint16_t minimum_remote_timeout, uint16_t minimum_local_timeout) { acl_connection_interface_->EnqueueCommand( - SniffSubratingBuilder::Create( - handle_, maximum_latency, minimum_remote_timeout, minimum_local_timeout), - pimpl_->tracker.client_handler_->BindOnce(check_complete)); + SniffSubratingBuilder::Create(handle_, maximum_latency, minimum_remote_timeout, + minimum_local_timeout), + pimpl_->tracker.client_handler_->BindOnce(check_complete)); return true; } bool ClassicAclConnection::Flush() { acl_connection_interface_->EnqueueCommand( - EnhancedFlushBuilder::Create(handle_), - pimpl_->tracker.client_handler_->BindOnce(check_status)); + EnhancedFlushBuilder::Create(handle_), + pimpl_->tracker.client_handler_->BindOnce(check_status)); return true; } bool ClassicAclConnection::ReadAutomaticFlushTimeout() { acl_connection_interface_->EnqueueCommand( - ReadAutomaticFlushTimeoutBuilder::Create(handle_), - pimpl_->tracker.client_handler_->BindOnceOn(&pimpl_->tracker, - &AclConnectionTracker::on_read_automatic_flush_timeout_complete)); + ReadAutomaticFlushTimeoutBuilder::Create(handle_), + pimpl_->tracker.client_handler_->BindOnceOn( + &pimpl_->tracker, + &AclConnectionTracker::on_read_automatic_flush_timeout_complete)); return true; } bool ClassicAclConnection::WriteAutomaticFlushTimeout(uint16_t flush_timeout) { acl_connection_interface_->EnqueueCommand( - WriteAutomaticFlushTimeoutBuilder::Create(handle_, flush_timeout), - pimpl_->tracker.client_handler_->BindOnce( - check_complete)); + WriteAutomaticFlushTimeoutBuilder::Create(handle_, flush_timeout), + pimpl_->tracker.client_handler_->BindOnce( + check_complete)); return true; } bool ClassicAclConnection::ReadTransmitPowerLevel(TransmitPowerLevelType type) { acl_connection_interface_->EnqueueCommand( - ReadTransmitPowerLevelBuilder::Create(handle_, type), - pimpl_->tracker.client_handler_->BindOnceOn(&pimpl_->tracker, - &AclConnectionTracker::on_read_transmit_power_level_complete)); + ReadTransmitPowerLevelBuilder::Create(handle_, type), + pimpl_->tracker.client_handler_->BindOnceOn( + &pimpl_->tracker, &AclConnectionTracker::on_read_transmit_power_level_complete)); return true; } bool ClassicAclConnection::ReadLinkSupervisionTimeout() { acl_connection_interface_->EnqueueCommand( - ReadLinkSupervisionTimeoutBuilder::Create(handle_), - pimpl_->tracker.client_handler_->BindOnceOn(&pimpl_->tracker, - &AclConnectionTracker::on_read_link_supervision_timeout_complete)); + ReadLinkSupervisionTimeoutBuilder::Create(handle_), + pimpl_->tracker.client_handler_->BindOnceOn( + &pimpl_->tracker, + &AclConnectionTracker::on_read_link_supervision_timeout_complete)); return true; } bool ClassicAclConnection::WriteLinkSupervisionTimeout(uint16_t link_supervision_timeout) { acl_connection_interface_->EnqueueCommand( - WriteLinkSupervisionTimeoutBuilder::Create(handle_, link_supervision_timeout), - pimpl_->tracker.client_handler_->BindOnce( - check_complete)); + WriteLinkSupervisionTimeoutBuilder::Create(handle_, link_supervision_timeout), + pimpl_->tracker.client_handler_->BindOnce( + check_complete)); return true; } bool ClassicAclConnection::ReadFailedContactCounter() { acl_connection_interface_->EnqueueCommand( - ReadFailedContactCounterBuilder::Create(handle_), - pimpl_->tracker.client_handler_->BindOnceOn(&pimpl_->tracker, - &AclConnectionTracker::on_read_failed_contact_counter_complete)); + ReadFailedContactCounterBuilder::Create(handle_), + pimpl_->tracker.client_handler_->BindOnceOn( + &pimpl_->tracker, + &AclConnectionTracker::on_read_failed_contact_counter_complete)); return true; } bool ClassicAclConnection::ResetFailedContactCounter() { acl_connection_interface_->EnqueueCommand( - ResetFailedContactCounterBuilder::Create(handle_), - pimpl_->tracker.client_handler_->BindOnce( - check_complete)); + ResetFailedContactCounterBuilder::Create(handle_), + pimpl_->tracker.client_handler_->BindOnce( + check_complete)); return true; } bool ClassicAclConnection::ReadLinkQuality() { acl_connection_interface_->EnqueueCommand( - ReadLinkQualityBuilder::Create(handle_), - pimpl_->tracker.client_handler_->BindOnceOn(&pimpl_->tracker, - &AclConnectionTracker::on_read_link_quality_complete)); + ReadLinkQualityBuilder::Create(handle_), + pimpl_->tracker.client_handler_->BindOnceOn( + &pimpl_->tracker, &AclConnectionTracker::on_read_link_quality_complete)); return true; } bool ClassicAclConnection::ReadAfhChannelMap() { acl_connection_interface_->EnqueueCommand( - ReadAfhChannelMapBuilder::Create(handle_), - pimpl_->tracker.client_handler_->BindOnceOn(&pimpl_->tracker, - &AclConnectionTracker::on_read_afh_channel_map_complete)); + ReadAfhChannelMapBuilder::Create(handle_), + pimpl_->tracker.client_handler_->BindOnceOn( + &pimpl_->tracker, &AclConnectionTracker::on_read_afh_channel_map_complete)); return true; } bool ClassicAclConnection::ReadRssi() { acl_connection_interface_->EnqueueCommand( - ReadRssiBuilder::Create(handle_), - pimpl_->tracker.client_handler_->BindOnceOn(&pimpl_->tracker, &AclConnectionTracker::on_read_rssi_complete)); + ReadRssiBuilder::Create(handle_), + pimpl_->tracker.client_handler_->BindOnceOn( + &pimpl_->tracker, &AclConnectionTracker::on_read_rssi_complete)); return true; } bool ClassicAclConnection::ReadRemoteVersionInformation() { acl_connection_interface_->EnqueueCommand( - ReadRemoteVersionInformationBuilder::Create(handle_), - pimpl_->tracker.client_handler_->BindOnceOn(&pimpl_->tracker, - &AclConnectionTracker::on_read_remote_version_information_status)); + ReadRemoteVersionInformationBuilder::Create(handle_), + pimpl_->tracker.client_handler_->BindOnceOn( + &pimpl_->tracker, + &AclConnectionTracker::on_read_remote_version_information_status)); return true; } bool ClassicAclConnection::ReadRemoteSupportedFeatures() { acl_connection_interface_->EnqueueCommand( - ReadRemoteSupportedFeaturesBuilder::Create(handle_), - pimpl_->tracker.client_handler_->BindOnceOn(&pimpl_->tracker, - &AclConnectionTracker::on_read_remote_supported_features_status)); + ReadRemoteSupportedFeaturesBuilder::Create(handle_), + pimpl_->tracker.client_handler_->BindOnceOn( + &pimpl_->tracker, + &AclConnectionTracker::on_read_remote_supported_features_status)); return true; } bool ClassicAclConnection::ReadRemoteExtendedFeatures(uint8_t page_number) { acl_connection_interface_->EnqueueCommand( - ReadRemoteExtendedFeaturesBuilder::Create(handle_, page_number), - pimpl_->tracker.client_handler_->BindOnceOn( - &pimpl_->tracker, &AclConnectionTracker::on_read_remote_extended_features_status)); + ReadRemoteExtendedFeaturesBuilder::Create(handle_, page_number), + pimpl_->tracker.client_handler_->BindOnceOn( + &pimpl_->tracker, + &AclConnectionTracker::on_read_remote_extended_features_status)); return true; } bool ClassicAclConnection::ReadClock(WhichClock which_clock) { pimpl_->tracker.acl_connection_interface_->EnqueueCommand( - ReadClockBuilder::Create(handle_, which_clock), - pimpl_->tracker.client_handler_->BindOnceOn(&pimpl_->tracker, &AclConnectionTracker::on_read_clock_complete)); + ReadClockBuilder::Create(handle_, which_clock), + pimpl_->tracker.client_handler_->BindOnceOn( + &pimpl_->tracker, &AclConnectionTracker::on_read_clock_complete)); return true; } diff --git a/system/gd/hci/acl_manager/classic_acl_connection.h b/system/gd/hci/acl_manager/classic_acl_connection.h index 560c97eccbf..a92761b770a 100644 --- a/system/gd/hci/acl_manager/classic_acl_connection.h +++ b/system/gd/hci/acl_manager/classic_acl_connection.h @@ -28,18 +28,17 @@ namespace hci { namespace acl_manager { class ClassicAclConnection : public AclConnection { - public: +public: ClassicAclConnection(); - ClassicAclConnection(std::shared_ptr queue, AclConnectionInterface* acl_connection_interface, uint16_t handle, + ClassicAclConnection(std::shared_ptr queue, + AclConnectionInterface* acl_connection_interface, uint16_t handle, Address address); ClassicAclConnection(const ClassicAclConnection&) = delete; ClassicAclConnection& operator=(const ClassicAclConnection&) = delete; ~ClassicAclConnection(); - virtual Address GetAddress() const { - return address_; - } + virtual Address GetAddress() const { return address_; } virtual void RegisterCallbacks(ConnectionManagementCallbacks* callbacks, os::Handler* handler); virtual bool Disconnect(DisconnectReason reason); @@ -49,15 +48,17 @@ class ClassicAclConnection : public AclConnection { virtual bool ChangeConnectionLinkKey(); virtual bool ReadClockOffset(); virtual bool HoldMode(uint16_t max_interval, uint16_t min_interval); - virtual bool SniffMode(uint16_t max_interval, uint16_t min_interval, uint16_t attempt, uint16_t timeout); + virtual bool SniffMode(uint16_t max_interval, uint16_t min_interval, uint16_t attempt, + uint16_t timeout); virtual bool ExitSniffMode(); - virtual bool QosSetup(ServiceType service_type, uint32_t token_rate, uint32_t peak_bandwidth, uint32_t latency, - uint32_t delay_variation); + virtual bool QosSetup(ServiceType service_type, uint32_t token_rate, uint32_t peak_bandwidth, + uint32_t latency, uint32_t delay_variation); virtual bool RoleDiscovery(); virtual bool ReadLinkPolicySettings(); virtual bool WriteLinkPolicySettings(uint16_t link_policy_settings); - virtual bool FlowSpecification(FlowDirection flow_direction, ServiceType service_type, uint32_t token_rate, - uint32_t token_bucket_size, uint32_t peak_bandwidth, uint32_t access_latency); + virtual bool FlowSpecification(FlowDirection flow_direction, ServiceType service_type, + uint32_t token_rate, uint32_t token_bucket_size, + uint32_t peak_bandwidth, uint32_t access_latency); virtual bool SniffSubrating(uint16_t maximum_latency, uint16_t minimum_remote_timeout, uint16_t minimum_local_timeout); virtual bool Flush(); @@ -77,15 +78,16 @@ class ClassicAclConnection : public AclConnection { virtual bool ReadRemoteExtendedFeatures(uint8_t page_number); // Called once before passing the connection to the client - virtual ConnectionManagementCallbacks* GetEventCallbacks(std::function invalidate_callbacks); + virtual ConnectionManagementCallbacks* GetEventCallbacks( + std::function invalidate_callbacks); - private: +private: AclConnectionInterface* acl_connection_interface_; - protected: +protected: Address address_; - private: +private: struct impl; struct impl* pimpl_ = nullptr; }; diff --git a/system/gd/hci/acl_manager/classic_acl_connection_test.cc b/system/gd/hci/acl_manager/classic_acl_connection_test.cc index 35f6e59d6b0..8cc66ab8076 100644 --- a/system/gd/hci/acl_manager/classic_acl_connection_test.cc +++ b/system/gd/hci/acl_manager/classic_acl_connection_test.cc @@ -45,59 +45,59 @@ constexpr uint16_t kConnectionHandle = 123; constexpr size_t kQueueSize = 10; std::vector disconnect_reason_vector = { - hci::DisconnectReason::AUTHENTICATION_FAILURE, - hci::DisconnectReason::REMOTE_USER_TERMINATED_CONNECTION, - hci::DisconnectReason::REMOTE_DEVICE_TERMINATED_CONNECTION_LOW_RESOURCES, - hci::DisconnectReason::REMOTE_DEVICE_TERMINATED_CONNECTION_POWER_OFF, - hci::DisconnectReason::UNSUPPORTED_REMOTE_FEATURE, - hci::DisconnectReason::PAIRING_WITH_UNIT_KEY_NOT_SUPPORTED, - hci::DisconnectReason::UNACCEPTABLE_CONNECTION_PARAMETERS, + hci::DisconnectReason::AUTHENTICATION_FAILURE, + hci::DisconnectReason::REMOTE_USER_TERMINATED_CONNECTION, + hci::DisconnectReason::REMOTE_DEVICE_TERMINATED_CONNECTION_LOW_RESOURCES, + hci::DisconnectReason::REMOTE_DEVICE_TERMINATED_CONNECTION_POWER_OFF, + hci::DisconnectReason::UNSUPPORTED_REMOTE_FEATURE, + hci::DisconnectReason::PAIRING_WITH_UNIT_KEY_NOT_SUPPORTED, + hci::DisconnectReason::UNACCEPTABLE_CONNECTION_PARAMETERS, }; std::vector error_code_vector = { - hci::ErrorCode::SUCCESS, - hci::ErrorCode::UNKNOWN_HCI_COMMAND, - hci::ErrorCode::UNKNOWN_CONNECTION, - hci::ErrorCode::HARDWARE_FAILURE, - hci::ErrorCode::PAGE_TIMEOUT, - hci::ErrorCode::AUTHENTICATION_FAILURE, - hci::ErrorCode::PIN_OR_KEY_MISSING, - hci::ErrorCode::MEMORY_CAPACITY_EXCEEDED, - hci::ErrorCode::CONNECTION_TIMEOUT, - hci::ErrorCode::CONNECTION_LIMIT_EXCEEDED, - hci::ErrorCode::SYNCHRONOUS_CONNECTION_LIMIT_EXCEEDED, - hci::ErrorCode::CONNECTION_ALREADY_EXISTS, - hci::ErrorCode::COMMAND_DISALLOWED, - hci::ErrorCode::CONNECTION_REJECTED_LIMITED_RESOURCES, - hci::ErrorCode::CONNECTION_REJECTED_SECURITY_REASONS, - hci::ErrorCode::CONNECTION_REJECTED_UNACCEPTABLE_BD_ADDR, - hci::ErrorCode::CONNECTION_ACCEPT_TIMEOUT, - hci::ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE, - hci::ErrorCode::INVALID_HCI_COMMAND_PARAMETERS, - hci::ErrorCode::REMOTE_USER_TERMINATED_CONNECTION, - hci::ErrorCode::REMOTE_DEVICE_TERMINATED_CONNECTION_LOW_RESOURCES, - hci::ErrorCode::REMOTE_DEVICE_TERMINATED_CONNECTION_POWER_OFF, - hci::ErrorCode::CONNECTION_TERMINATED_BY_LOCAL_HOST, - hci::ErrorCode::REPEATED_ATTEMPTS, - hci::ErrorCode::PAIRING_NOT_ALLOWED, - hci::ErrorCode::UNKNOWN_LMP_PDU, - hci::ErrorCode::UNSUPPORTED_REMOTE_OR_LMP_FEATURE, - hci::ErrorCode::SCO_OFFSET_REJECTED, - hci::ErrorCode::SCO_INTERVAL_REJECTED, - hci::ErrorCode::SCO_AIR_MODE_REJECTED, - hci::ErrorCode::INVALID_LMP_OR_LL_PARAMETERS, - hci::ErrorCode::UNSPECIFIED_ERROR, - hci::ErrorCode::UNSUPPORTED_LMP_OR_LL_PARAMETER, - hci::ErrorCode::ROLE_CHANGE_NOT_ALLOWED, - hci::ErrorCode::TRANSACTION_RESPONSE_TIMEOUT, - hci::ErrorCode::LINK_LAYER_COLLISION, - hci::ErrorCode::ENCRYPTION_MODE_NOT_ACCEPTABLE, - hci::ErrorCode::ROLE_SWITCH_FAILED, - hci::ErrorCode::CONTROLLER_BUSY, - hci::ErrorCode::ADVERTISING_TIMEOUT, - hci::ErrorCode::CONNECTION_FAILED_ESTABLISHMENT, - hci::ErrorCode::LIMIT_REACHED, - hci::ErrorCode::STATUS_UNKNOWN, + hci::ErrorCode::SUCCESS, + hci::ErrorCode::UNKNOWN_HCI_COMMAND, + hci::ErrorCode::UNKNOWN_CONNECTION, + hci::ErrorCode::HARDWARE_FAILURE, + hci::ErrorCode::PAGE_TIMEOUT, + hci::ErrorCode::AUTHENTICATION_FAILURE, + hci::ErrorCode::PIN_OR_KEY_MISSING, + hci::ErrorCode::MEMORY_CAPACITY_EXCEEDED, + hci::ErrorCode::CONNECTION_TIMEOUT, + hci::ErrorCode::CONNECTION_LIMIT_EXCEEDED, + hci::ErrorCode::SYNCHRONOUS_CONNECTION_LIMIT_EXCEEDED, + hci::ErrorCode::CONNECTION_ALREADY_EXISTS, + hci::ErrorCode::COMMAND_DISALLOWED, + hci::ErrorCode::CONNECTION_REJECTED_LIMITED_RESOURCES, + hci::ErrorCode::CONNECTION_REJECTED_SECURITY_REASONS, + hci::ErrorCode::CONNECTION_REJECTED_UNACCEPTABLE_BD_ADDR, + hci::ErrorCode::CONNECTION_ACCEPT_TIMEOUT, + hci::ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE, + hci::ErrorCode::INVALID_HCI_COMMAND_PARAMETERS, + hci::ErrorCode::REMOTE_USER_TERMINATED_CONNECTION, + hci::ErrorCode::REMOTE_DEVICE_TERMINATED_CONNECTION_LOW_RESOURCES, + hci::ErrorCode::REMOTE_DEVICE_TERMINATED_CONNECTION_POWER_OFF, + hci::ErrorCode::CONNECTION_TERMINATED_BY_LOCAL_HOST, + hci::ErrorCode::REPEATED_ATTEMPTS, + hci::ErrorCode::PAIRING_NOT_ALLOWED, + hci::ErrorCode::UNKNOWN_LMP_PDU, + hci::ErrorCode::UNSUPPORTED_REMOTE_OR_LMP_FEATURE, + hci::ErrorCode::SCO_OFFSET_REJECTED, + hci::ErrorCode::SCO_INTERVAL_REJECTED, + hci::ErrorCode::SCO_AIR_MODE_REJECTED, + hci::ErrorCode::INVALID_LMP_OR_LL_PARAMETERS, + hci::ErrorCode::UNSPECIFIED_ERROR, + hci::ErrorCode::UNSUPPORTED_LMP_OR_LL_PARAMETER, + hci::ErrorCode::ROLE_CHANGE_NOT_ALLOWED, + hci::ErrorCode::TRANSACTION_RESPONSE_TIMEOUT, + hci::ErrorCode::LINK_LAYER_COLLISION, + hci::ErrorCode::ENCRYPTION_MODE_NOT_ACCEPTABLE, + hci::ErrorCode::ROLE_SWITCH_FAILED, + hci::ErrorCode::CONTROLLER_BUSY, + hci::ErrorCode::ADVERTISING_TIMEOUT, + hci::ErrorCode::CONNECTION_FAILED_ESTABLISHMENT, + hci::ErrorCode::LIMIT_REACHED, + hci::ErrorCode::STATUS_UNKNOWN, }; // Generic template for all commands @@ -109,17 +109,17 @@ T CreateCommand(U /* u */) { template <> hci::DisconnectView CreateCommand(std::shared_ptr> bytes) { - return hci::DisconnectView::Create( - hci::AclCommandView::Create(hci::CommandView::Create(hci::PacketView(bytes)))); + return hci::DisconnectView::Create(hci::AclCommandView::Create( + hci::CommandView::Create(hci::PacketView(bytes)))); } } // namespace class TestAclConnectionInterface : public hci::AclConnectionInterface { - private: +private: void EnqueueCommand( - std::unique_ptr command, - common::ContextualOnceCallback on_status) override { + std::unique_ptr command, + common::ContextualOnceCallback on_status) override { const std::lock_guard lock(command_queue_mutex_); command_queue_.push(std::move(command)); command_status_callbacks.push_back(std::move(on_status)); @@ -131,8 +131,8 @@ class TestAclConnectionInterface : public hci::AclConnectionInterface { } void EnqueueCommand( - std::unique_ptr command, - common::ContextualOnceCallback on_complete) override { + std::unique_ptr command, + common::ContextualOnceCallback on_complete) override { const std::lock_guard lock(command_queue_mutex_); command_queue_.push(std::move(command)); command_complete_callbacks.push_back(std::move(on_complete)); @@ -143,7 +143,7 @@ class TestAclConnectionInterface : public hci::AclConnectionInterface { } } - public: +public: virtual ~TestAclConnectionInterface() = default; std::unique_ptr DequeueCommand() { @@ -171,8 +171,9 @@ class TestAclConnectionInterface : public hci::AclConnectionInterface { return command_queue_.size(); } - private: - std::list> command_complete_callbacks; +private: + std::list> + command_complete_callbacks; std::list> command_status_callbacks; std::queue> command_queue_; mutable std::mutex command_queue_mutex_; @@ -181,35 +182,26 @@ class TestAclConnectionInterface : public hci::AclConnectionInterface { }; class TestConnectionManagementCallbacks : public hci::acl_manager::ConnectionManagementCallbacks { - public: +public: ~TestConnectionManagementCallbacks() = default; void OnConnectionPacketTypeChanged(uint16_t /* packet_type */) override {} void OnAuthenticationComplete(hci::ErrorCode /* hci_status */) override {} void OnEncryptionChange(hci::EncryptionEnabled /* enabled */) override {} void OnChangeConnectionLinkKeyComplete() override {} void OnReadClockOffsetComplete(uint16_t /* clock_offset */) override {} - void OnModeChange( - hci::ErrorCode /* status */, hci::Mode /* current_mode */, uint16_t /* interval */) override { - } - void OnSniffSubrating( - hci::ErrorCode /* hci_status */, - uint16_t /* maximum_transmit_latency */, - uint16_t /* maximum_receive_latency */, - uint16_t /* minimum_remote_timeout */, - uint16_t /* minimum_local_timeout */) override {} - void OnQosSetupComplete( - hci::ServiceType /* service_type */, - uint32_t /* token_rate */, - uint32_t /* peak_bandwidth */, - uint32_t /* latency */, - uint32_t /* delay_variation */) override {} - void OnFlowSpecificationComplete( - hci::FlowDirection /* flow_direction */, - hci::ServiceType /* service_type */, - uint32_t /* token_rate */, - uint32_t /* token_bucket_size */, - uint32_t /* peak_bandwidth */, - uint32_t /* access_latency */) override {} + void OnModeChange(hci::ErrorCode /* status */, hci::Mode /* current_mode */, + uint16_t /* interval */) override {} + void OnSniffSubrating(hci::ErrorCode /* hci_status */, uint16_t /* maximum_transmit_latency */, + uint16_t /* maximum_receive_latency */, + uint16_t /* minimum_remote_timeout */, + uint16_t /* minimum_local_timeout */) override {} + void OnQosSetupComplete(hci::ServiceType /* service_type */, uint32_t /* token_rate */, + uint32_t /* peak_bandwidth */, uint32_t /* latency */, + uint32_t /* delay_variation */) override {} + void OnFlowSpecificationComplete(hci::FlowDirection /* flow_direction */, + hci::ServiceType /* service_type */, uint32_t /* token_rate */, + uint32_t /* token_bucket_size */, uint32_t /* peak_bandwidth */, + uint32_t /* access_latency */) override {} void OnFlushOccurred() override {} void OnRoleDiscoveryComplete(hci::Role /* current_role */) override {} void OnReadLinkPolicySettingsComplete(uint16_t /* link_policy_settings */) override {} @@ -218,8 +210,8 @@ class TestConnectionManagementCallbacks : public hci::acl_manager::ConnectionMan void OnReadLinkSupervisionTimeoutComplete(uint16_t /* link_supervision_timeout */) override {} void OnReadFailedContactCounterComplete(uint16_t /* failed_contact_counter */) override {} void OnReadLinkQualityComplete(uint8_t /* link_quality */) override {} - void OnReadAfhChannelMapComplete( - hci::AfhMode /* afh_mode */, std::array /* afh_channel_map */) override {} + void OnReadAfhChannelMapComplete(hci::AfhMode /* afh_mode */, + std::array /* afh_channel_map */) override {} void OnReadRssiComplete(uint8_t /* rssi */) override {} void OnReadClockComplete(uint32_t /* clock */, uint16_t /* accuracy */) override {} void OnCentralLinkKeyComplete(hci::KeyFlag /* key_flag */) override {} @@ -227,14 +219,14 @@ class TestConnectionManagementCallbacks : public hci::acl_manager::ConnectionMan void OnDisconnection(hci::ErrorCode reason) override { on_disconnection_error_code_queue_.push(reason); } - void OnReadRemoteVersionInformationComplete( - hci::ErrorCode /* hci_status */, - uint8_t /* lmp_version */, - uint16_t /* manufacturer_name */, - uint16_t /* sub_version */) override {} + void OnReadRemoteVersionInformationComplete(hci::ErrorCode /* hci_status */, + uint8_t /* lmp_version */, + uint16_t /* manufacturer_name */, + uint16_t /* sub_version */) override {} void OnReadRemoteSupportedFeaturesComplete(uint64_t /* features */) override {} - void OnReadRemoteExtendedFeaturesComplete( - uint8_t /* page_number */, uint8_t /* max_page_number */, uint64_t /* features */) override {} + void OnReadRemoteExtendedFeaturesComplete(uint8_t /* page_number */, + uint8_t /* max_page_number */, + uint64_t /* features */) override {} std::queue on_disconnection_error_code_queue_; }; @@ -244,7 +236,7 @@ namespace hci { namespace acl_manager { class ClassicAclConnectionTest : public ::testing::Test { - protected: +protected: void SetUp() override { ASSERT_TRUE(hci::Address::FromString(kAddress, address_)); thread_ = new os::Thread("thread", os::Thread::Priority::NORMAL); @@ -261,9 +253,8 @@ class ClassicAclConnectionTest : public ::testing::Test { void sync_handler() { log::assert_that(thread_ != nullptr, "assert failed: thread_ != nullptr"); - log::assert_that( - thread_->GetReactor()->WaitForIdle(2s), - "assert failed: thread_->GetReactor()->WaitForIdle(2s)"); + log::assert_that(thread_->GetReactor()->WaitForIdle(2s), + "assert failed: thread_->GetReactor()->WaitForIdle(2s)"); } Address address_; @@ -278,22 +269,22 @@ class ClassicAclConnectionTest : public ::testing::Test { TEST_F(ClassicAclConnectionTest, simple) { AclConnectionInterface* acl_connection_interface = nullptr; ClassicAclConnection* connection = - new ClassicAclConnection(queue_, acl_connection_interface, kConnectionHandle, address_); + new ClassicAclConnection(queue_, acl_connection_interface, kConnectionHandle, address_); connection->RegisterCallbacks(&callbacks_, handler_); delete connection; } class ClassicAclConnectionWithCallbacksTest : public ClassicAclConnectionTest { - protected: +protected: void SetUp() override { ClassicAclConnectionTest::SetUp(); - connection_ = - std::make_unique(queue_, &acl_connection_interface_, kConnectionHandle, address_); + connection_ = std::make_unique(queue_, &acl_connection_interface_, + kConnectionHandle, address_); connection_->RegisterCallbacks(&callbacks_, handler_); is_callbacks_registered_ = true; connection_management_callbacks_ = connection_->GetEventCallbacks( - [this](uint16_t /* hci_handle */) { is_callbacks_invalidated_ = true; }); + [this](uint16_t /* hci_handle */) { is_callbacks_invalidated_ = true; }); is_callbacks_invalidated_ = false; } @@ -303,7 +294,7 @@ class ClassicAclConnectionWithCallbacksTest : public ClassicAclConnectionTest { ClassicAclConnectionTest::TearDown(); } - protected: +protected: std::unique_ptr connection_; ConnectionManagementCallbacks* connection_management_callbacks_; bool is_callbacks_registered_{false}; diff --git a/system/gd/hci/acl_manager/classic_impl.h b/system/gd/hci/acl_manager/classic_impl.h index 995c35e0d5d..c6ebd76d6e7 100644 --- a/system/gd/hci/acl_manager/classic_impl.h +++ b/system/gd/hci/acl_manager/classic_impl.h @@ -39,26 +39,20 @@ namespace hci { namespace acl_manager { struct acl_connection { - acl_connection(AddressWithType address_with_type, AclConnection::QueueDownEnd* queue_down_end, os::Handler* handler) + acl_connection(AddressWithType address_with_type, AclConnection::QueueDownEnd* queue_down_end, + os::Handler* handler) : address_with_type_(address_with_type), assembler_(new acl_manager::assembler(address_with_type, queue_down_end, handler)) {} - ~acl_connection() { - delete assembler_; - } + ~acl_connection() { delete assembler_; } AddressWithType address_with_type_; struct acl_manager::assembler* assembler_; ConnectionManagementCallbacks* connection_management_callbacks_ = nullptr; }; struct classic_impl { - classic_impl( - HciLayer* hci_layer, - Controller* controller, - os::Handler* handler, - RoundRobinScheduler* round_robin_scheduler, - bool crash_on_unknown_handle, - AclScheduler* acl_scheduler, - RemoteNameRequestModule* remote_name_request_module) + classic_impl(HciLayer* hci_layer, Controller* controller, os::Handler* handler, + RoundRobinScheduler* round_robin_scheduler, bool crash_on_unknown_handle, + AclScheduler* acl_scheduler, RemoteNameRequestModule* remote_name_request_module) : hci_layer_(hci_layer), controller_(controller), round_robin_scheduler_(round_robin_scheduler), @@ -70,10 +64,10 @@ struct classic_impl { connections.crash_on_unknown_handle_ = crash_on_unknown_handle; should_accept_connection_ = common::Bind([](Address, ClassOfDevice) { return true; }); acl_connection_interface_ = hci_layer_->GetAclConnectionInterface( - handler_->BindOn(this, &classic_impl::on_classic_event), - handler_->BindOn(this, &classic_impl::on_classic_disconnect), - handler_->BindOn(this, &classic_impl::on_incoming_connection), - handler_->BindOn(this, &classic_impl::on_read_remote_version_information)); + handler_->BindOn(this, &classic_impl::on_classic_event), + handler_->BindOn(this, &classic_impl::on_classic_disconnect), + handler_->BindOn(this, &classic_impl::on_incoming_connection), + handler_->BindOn(this, &classic_impl::on_read_remote_version_information)); } ~classic_impl() { @@ -134,15 +128,17 @@ struct classic_impl { } } - private: +private: static constexpr uint16_t kIllegalConnectionHandle = 0xffff; struct { - private: + private: std::map acl_connections_; mutable std::mutex acl_connections_guard_; ConnectionManagementCallbacks* find_callbacks(uint16_t handle) { auto connection = acl_connections_.find(handle); - if (connection == acl_connections_.end()) return nullptr; + if (connection == acl_connections_.end()) { + return nullptr; + } return connection->second.connection_management_callbacks_; } ConnectionManagementCallbacks* find_callbacks(const Address& address) { @@ -161,7 +157,7 @@ struct classic_impl { } } - public: + public: bool crash_on_unknown_handle_ = false; bool is_empty() const { std::unique_lock lock(acl_connections_guard_); @@ -175,44 +171,47 @@ struct classic_impl { std::unique_lock lock(acl_connections_guard_); remove(handle); } - void execute( - uint16_t handle, - std::function execute, - bool remove_afterwards = false) { + void execute(uint16_t handle, + std::function execute, + bool remove_afterwards = false) { std::unique_lock lock(acl_connections_guard_); auto callbacks = find_callbacks(handle); - if (callbacks != nullptr) + if (callbacks != nullptr) { execute(callbacks); - else - log::assert_that( - !crash_on_unknown_handle_, "Received command for unknown handle:0x{:x}", handle); - if (remove_afterwards) remove(handle); + } else { + log::assert_that(!crash_on_unknown_handle_, "Received command for unknown handle:0x{:x}", + handle); + } + if (remove_afterwards) { + remove(handle); + } } - void execute(const Address& address, std::function execute) { + void execute(const Address& address, + std::function execute) { std::unique_lock lock(acl_connections_guard_); auto callbacks = find_callbacks(address); - if (callbacks != nullptr) execute(callbacks); + if (callbacks != nullptr) { + execute(callbacks); + } } - bool send_packet_upward(uint16_t handle, std::function cb) { + bool send_packet_upward(uint16_t handle, + std::function cb) { std::unique_lock lock(acl_connections_guard_); auto connection = acl_connections_.find(handle); - if (connection != acl_connections_.end()) cb(connection->second.assembler_); + if (connection != acl_connections_.end()) { + cb(connection->second.assembler_); + } return connection != acl_connections_.end(); } - void add( - uint16_t handle, - const AddressWithType& remote_address, - AclConnection::QueueDownEnd* queue_end, - os::Handler* handler, - ConnectionManagementCallbacks* connection_management_callbacks) { + void add(uint16_t handle, const AddressWithType& remote_address, + AclConnection::QueueDownEnd* queue_end, os::Handler* handler, + ConnectionManagementCallbacks* connection_management_callbacks) { std::unique_lock lock(acl_connections_guard_); - auto emplace_pair = acl_connections_.emplace( - std::piecewise_construct, - std::forward_as_tuple(handle), - std::forward_as_tuple(remote_address, queue_end, handler)); - log::assert_that( - emplace_pair.second, - "assert failed: emplace_pair.second"); // Make sure the connection is unique + auto emplace_pair = + acl_connections_.emplace(std::piecewise_construct, std::forward_as_tuple(handle), + std::forward_as_tuple(remote_address, queue_end, handler)); + log::assert_that(emplace_pair.second, + "assert failed: emplace_pair.second"); // Make sure the connection is unique emplace_pair.first->second.connection_management_callbacks_ = connection_management_callbacks; } uint16_t HACK_get_handle(const Address& address) const { @@ -243,8 +242,9 @@ struct classic_impl { } } connections; - public: - bool send_packet_upward(uint16_t handle, std::function cb) { +public: + bool send_packet_upward(uint16_t handle, + std::function cb) { return connections.send_packet_upward(handle, cb); } @@ -256,8 +256,8 @@ struct classic_impl { return; } - client_handler_->CallOn( - client_callbacks_, &ConnectionCallbacks::OnConnectRequest, address, cod); + client_handler_->CallOn(client_callbacks_, &ConnectionCallbacks::OnConnectRequest, address, + cod); acl_scheduler_->RegisterPendingIncomingConnection(address); @@ -284,38 +284,38 @@ struct classic_impl { ClockOffsetValid clock_offset_valid = ClockOffsetValid::INVALID; CreateConnectionRoleSwitch allow_role_switch = CreateConnectionRoleSwitch::ALLOW_ROLE_SWITCH; log::assert_that(client_callbacks_ != nullptr, "assert failed: client_callbacks_ != nullptr"); - std::unique_ptr packet = CreateConnectionBuilder::Create( - address, packet_type, page_scan_repetition_mode, clock_offset, clock_offset_valid, allow_role_switch); + std::unique_ptr packet = + CreateConnectionBuilder::Create(address, packet_type, page_scan_repetition_mode, + clock_offset, clock_offset_valid, allow_role_switch); acl_scheduler_->EnqueueOutgoingAclConnection( - address, handler_->BindOnceOn(this, &classic_impl::actually_create_connection, address, std::move(packet))); + address, handler_->BindOnceOn(this, &classic_impl::actually_create_connection, address, + std::move(packet))); } - void actually_create_connection(Address address, std::unique_ptr packet) { + void actually_create_connection(Address address, + std::unique_ptr packet) { if (is_classic_link_already_connected(address)) { log::warn("already connected: {}", address); acl_scheduler_->ReportOutgoingAclConnectionFailure(); return; } acl_connection_interface_->EnqueueCommand( - std::move(packet), handler_->BindOnceOn(this, &classic_impl::on_create_connection_status, address)); + std::move(packet), + handler_->BindOnceOn(this, &classic_impl::on_create_connection_status, address)); } void on_create_connection_status(Address address, CommandStatusView status) { log::assert_that(status.IsValid(), "assert failed: status.IsValid()"); - log::assert_that( - status.GetCommandOpCode() == OpCode::CREATE_CONNECTION, - "assert failed: status.GetCommandOpCode() == OpCode::CREATE_CONNECTION"); + log::assert_that(status.GetCommandOpCode() == OpCode::CREATE_CONNECTION, + "assert failed: status.GetCommandOpCode() == OpCode::CREATE_CONNECTION"); if (status.GetStatus() != hci::ErrorCode::SUCCESS /* = pending */) { // something went wrong, but unblock queue and report to caller log::error("Failed to create connection, reporting failure and continuing"); log::assert_that(client_callbacks_ != nullptr, "assert failed: client_callbacks_ != nullptr"); - client_handler_->Post(common::BindOnce( - &ConnectionCallbacks::OnConnectFail, - common::Unretained(client_callbacks_), - address, - status.GetStatus(), - true /* locally initiated */)); + client_handler_->Post(common::BindOnce(&ConnectionCallbacks::OnConnectFail, + common::Unretained(client_callbacks_), address, + status.GetStatus(), true /* locally initiated */)); acl_scheduler_->ReportOutgoingAclConnectionFailure(); } else { // everything is good, resume when a connection_complete event arrives @@ -328,8 +328,8 @@ struct classic_impl { REMOTE_INITIATED, }; - void create_and_announce_connection( - ConnectionCompleteView connection_complete, Role current_role, Initiator initiator) { + void create_and_announce_connection(ConnectionCompleteView connection_complete, Role current_role, + Initiator initiator) { auto status = connection_complete.GetStatus(); auto address = connection_complete.GetBdAddr(); if (client_callbacks_ == nullptr) { @@ -337,12 +337,9 @@ struct classic_impl { return; } if (status != ErrorCode::SUCCESS) { - client_handler_->Post(common::BindOnce( - &ConnectionCallbacks::OnConnectFail, - common::Unretained(client_callbacks_), - address, - status, - initiator == Initiator::LOCALLY_INITIATED)); + client_handler_->Post(common::BindOnce(&ConnectionCallbacks::OnConnectFail, + common::Unretained(client_callbacks_), address, status, + initiator == Initiator::LOCALLY_INITIATED)); return; } uint16_t handle = connection_complete.GetConnectionHandle(); @@ -350,25 +347,25 @@ struct classic_impl { auto queue_down_end = queue->GetDownEnd(); round_robin_scheduler_->Register(RoundRobinScheduler::ConnectionType::CLASSIC, handle, queue); std::unique_ptr connection( - new ClassicAclConnection(std::move(queue), acl_connection_interface_, handle, address)); + new ClassicAclConnection(std::move(queue), acl_connection_interface_, handle, address)); connection->locally_initiated_ = initiator == Initiator::LOCALLY_INITIATED; - connections.add( - handle, - AddressWithType{address, AddressType::PUBLIC_DEVICE_ADDRESS}, - queue_down_end, - handler_, - connection->GetEventCallbacks([this](uint16_t handle) { this->connections.invalidate(handle); })); + connections.add(handle, AddressWithType{address, AddressType::PUBLIC_DEVICE_ADDRESS}, + queue_down_end, handler_, + connection->GetEventCallbacks( + [this](uint16_t handle) { this->connections.invalidate(handle); })); connections.execute(address, [=, this](ConnectionManagementCallbacks* callbacks) { if (delayed_role_change_ == nullptr) { callbacks->OnRoleChange(hci::ErrorCode::SUCCESS, current_role); } else if (delayed_role_change_->GetBdAddr() == address) { log::info("Sending delayed role change for {}", delayed_role_change_->GetBdAddr()); - callbacks->OnRoleChange(delayed_role_change_->GetStatus(), delayed_role_change_->GetNewRole()); + callbacks->OnRoleChange(delayed_role_change_->GetStatus(), + delayed_role_change_->GetNewRole()); delayed_role_change_.reset(); } }); - client_handler_->Post(common::BindOnce( - &ConnectionCallbacks::OnConnectSuccess, common::Unretained(client_callbacks_), std::move(connection))); + client_handler_->Post(common::BindOnce(&ConnectionCallbacks::OnConnectSuccess, + common::Unretained(client_callbacks_), + std::move(connection))); } void on_connection_complete(EventView packet) { @@ -378,73 +375,60 @@ struct classic_impl { auto address = connection_complete.GetBdAddr(); acl_scheduler_->ReportAclConnectionCompletion( - address, - handler_->BindOnceOn( - this, - &classic_impl::create_and_announce_connection, - connection_complete, - Role::CENTRAL, - Initiator::LOCALLY_INITIATED), - handler_->BindOnceOn( - this, - &classic_impl::create_and_announce_connection, - connection_complete, - Role::PERIPHERAL, - Initiator::REMOTE_INITIATED), - handler_->BindOnce( - [=](RemoteNameRequestModule* remote_name_request_module, - Address address, - ErrorCode status, - std::string valid_incoming_addresses) { - log::warn("No matching connection to {} ({})", address, ErrorCodeText(status)); - log::assert_that( - status != ErrorCode::SUCCESS, - "No prior connection request for {} expecting:{}", - address, - valid_incoming_addresses.c_str()); - remote_name_request_module->ReportRemoteNameRequestCancellation(address); - }, - common::Unretained(remote_name_request_module_), address, - status)); + handler_->BindOnceOn(this, &classic_impl::create_and_announce_connection, + connection_complete, Role::CENTRAL, Initiator::LOCALLY_INITIATED), + handler_->BindOnceOn(this, &classic_impl::create_and_announce_connection, + connection_complete, Role::PERIPHERAL, + Initiator::REMOTE_INITIATED), + handler_->BindOnce( + [=](RemoteNameRequestModule* remote_name_request_module, Address address, + ErrorCode status, std::string valid_incoming_addresses) { + log::warn("No matching connection to {} ({})", address, + ErrorCodeText(status)); + log::assert_that(status != ErrorCode::SUCCESS, + "No prior connection request for {} expecting:{}", address, + valid_incoming_addresses.c_str()); + remote_name_request_module->ReportRemoteNameRequestCancellation(address); + }, + common::Unretained(remote_name_request_module_), address, status)); } void cancel_connect(Address address) { acl_scheduler_->CancelAclConnection( - address, - handler_->BindOnceOn(this, &classic_impl::actually_cancel_connect, address), - client_handler_->BindOnceOn( - client_callbacks_, - &ConnectionCallbacks::OnConnectFail, - address, - ErrorCode::UNKNOWN_CONNECTION, - true /* locally initiated */)); + address, handler_->BindOnceOn(this, &classic_impl::actually_cancel_connect, address), + client_handler_->BindOnceOn(client_callbacks_, &ConnectionCallbacks::OnConnectFail, + address, ErrorCode::UNKNOWN_CONNECTION, + true /* locally initiated */)); } void actually_cancel_connect(Address address) { - std::unique_ptr packet = CreateConnectionCancelBuilder::Create(address); + std::unique_ptr packet = + CreateConnectionCancelBuilder::Create(address); acl_connection_interface_->EnqueueCommand( - std::move(packet), handler_->BindOnce(check_complete)); + std::move(packet), + handler_->BindOnce(check_complete)); } static constexpr bool kRemoveConnectionAfterwards = true; void on_classic_disconnect(uint16_t handle, ErrorCode reason) { bool event_also_routes_to_other_receivers = connections.crash_on_unknown_handle_; bluetooth::os::LogMetricBluetoothDisconnectionReasonReported( - static_cast(reason), connections.get_address(handle), handle); + static_cast(reason), connections.get_address(handle), handle); connections.crash_on_unknown_handle_ = false; connections.execute( - handle, - [=, this](ConnectionManagementCallbacks* callbacks) { - round_robin_scheduler_->Unregister(handle); - callbacks->OnDisconnection(reason); - }, - kRemoveConnectionAfterwards); + handle, + [=, this](ConnectionManagementCallbacks* callbacks) { + round_robin_scheduler_->Unregister(handle); + callbacks->OnDisconnection(reason); + }, + kRemoveConnectionAfterwards); connections.crash_on_unknown_handle_ = event_also_routes_to_other_receivers; } void on_connection_packet_type_changed(EventView packet) { - ConnectionPacketTypeChangedView packet_type_changed = ConnectionPacketTypeChangedView::Create(packet); + ConnectionPacketTypeChangedView packet_type_changed = + ConnectionPacketTypeChangedView::Create(packet); if (!packet_type_changed.IsValid()) { log::error("Received on_connection_packet_type_changed with invalid packet"); return; @@ -491,7 +475,8 @@ struct classic_impl { } void on_change_connection_link_key_complete(EventView packet) { - ChangeConnectionLinkKeyCompleteView complete_view = ChangeConnectionLinkKeyCompleteView::Create(packet); + ChangeConnectionLinkKeyCompleteView complete_view = + ChangeConnectionLinkKeyCompleteView::Create(packet); if (!complete_view.IsValid()) { log::error("Received on_change_connection_link_key_complete with invalid packet"); return; @@ -502,8 +487,9 @@ struct classic_impl { return; } uint16_t handle = complete_view.GetConnectionHandle(); - connections.execute( - handle, [=](ConnectionManagementCallbacks* callbacks) { callbacks->OnChangeConnectionLinkKeyComplete(); }); + connections.execute(handle, [=](ConnectionManagementCallbacks* callbacks) { + callbacks->OnChangeConnectionLinkKeyComplete(); + }); } void on_read_clock_offset_complete(EventView packet) { @@ -532,8 +518,8 @@ struct classic_impl { } uint16_t handle = mode_change_view.GetConnectionHandle(); connections.execute(handle, [=](ConnectionManagementCallbacks* callbacks) { - callbacks->OnModeChange( - mode_change_view.GetStatus(), mode_change_view.GetCurrentMode(), mode_change_view.GetInterval()); + callbacks->OnModeChange(mode_change_view.GetStatus(), mode_change_view.GetCurrentMode(), + mode_change_view.GetInterval()); }); } @@ -545,12 +531,11 @@ struct classic_impl { } uint16_t handle = sniff_subrating_view.GetConnectionHandle(); connections.execute(handle, [=](ConnectionManagementCallbacks* callbacks) { - callbacks->OnSniffSubrating( - sniff_subrating_view.GetStatus(), - sniff_subrating_view.GetMaximumTransmitLatency(), - sniff_subrating_view.GetMaximumReceiveLatency(), - sniff_subrating_view.GetMinimumRemoteTimeout(), - sniff_subrating_view.GetMinimumLocalTimeout()); + callbacks->OnSniffSubrating(sniff_subrating_view.GetStatus(), + sniff_subrating_view.GetMaximumTransmitLatency(), + sniff_subrating_view.GetMaximumReceiveLatency(), + sniff_subrating_view.GetMinimumRemoteTimeout(), + sniff_subrating_view.GetMinimumLocalTimeout()); }); } @@ -572,7 +557,8 @@ struct classic_impl { uint32_t peak_bandwidth = complete_view.GetPeakBandwidth(); uint32_t latency = complete_view.GetLatency(); uint32_t delay_variation = complete_view.GetDelayVariation(); - callbacks->OnQosSetupComplete(service_type, token_rate, peak_bandwidth, latency, delay_variation); + callbacks->OnQosSetupComplete(service_type, token_rate, peak_bandwidth, latency, + delay_variation); }); } @@ -595,8 +581,8 @@ struct classic_impl { uint32_t token_bucket_size = complete_view.GetTokenBucketSize(); uint32_t peak_bandwidth = complete_view.GetPeakBandwidth(); uint32_t access_latency = complete_view.GetAccessLatency(); - callbacks->OnFlowSpecificationComplete( - flow_direction, service_type, token_rate, token_bucket_size, peak_bandwidth, access_latency); + callbacks->OnFlowSpecificationComplete(flow_direction, service_type, token_rate, + token_bucket_size, peak_bandwidth, access_latency); }); } @@ -607,7 +593,9 @@ struct classic_impl { return; } uint16_t handle = flush_occurred_view.GetConnectionHandle(); - connections.execute(handle, [=](ConnectionManagementCallbacks* callbacks) { callbacks->OnFlushOccurred(); }); + connections.execute(handle, [=](ConnectionManagementCallbacks* callbacks) { + callbacks->OnFlushOccurred(); + }); } void on_enhanced_flush_complete(EventView packet) { @@ -618,13 +606,15 @@ struct classic_impl { } uint16_t handle = flush_complete.GetConnectionHandle(); connections.execute( - handle, [](ConnectionManagementCallbacks* callbacks) { callbacks->OnFlushOccurred(); }); + handle, [](ConnectionManagementCallbacks* callbacks) { callbacks->OnFlushOccurred(); }); } - void on_read_remote_version_information( - hci::ErrorCode hci_status, uint16_t handle, uint8_t version, uint16_t manufacturer_name, uint16_t sub_version) { + void on_read_remote_version_information(hci::ErrorCode hci_status, uint16_t handle, + uint8_t version, uint16_t manufacturer_name, + uint16_t sub_version) { connections.execute(handle, [=](ConnectionManagementCallbacks* callbacks) { - callbacks->OnReadRemoteVersionInformationComplete(hci_status, version, manufacturer_name, sub_version); + callbacks->OnReadRemoteVersionInformationComplete(hci_status, version, manufacturer_name, + sub_version); }); } @@ -632,8 +622,8 @@ struct classic_impl { auto view = ReadRemoteSupportedFeaturesCompleteView::Create(packet); log::assert_that(view.IsValid(), "Read remote supported features packet invalid"); uint16_t handle = view.GetConnectionHandle(); - bluetooth::os::LogMetricBluetoothRemoteSupportedFeatures( - connections.get_address(handle), 0, view.GetLmpFeatures(), handle); + bluetooth::os::LogMetricBluetoothRemoteSupportedFeatures(connections.get_address(handle), 0, + view.GetLmpFeatures(), handle); connections.execute(handle, [=](ConnectionManagementCallbacks* callbacks) { callbacks->OnReadRemoteSupportedFeaturesComplete(view.GetLmpFeatures()); }); @@ -643,11 +633,12 @@ struct classic_impl { auto view = ReadRemoteExtendedFeaturesCompleteView::Create(packet); log::assert_that(view.IsValid(), "Read remote extended features packet invalid"); uint16_t handle = view.GetConnectionHandle(); - bluetooth::os::LogMetricBluetoothRemoteSupportedFeatures( - connections.get_address(handle), view.GetPageNumber(), view.GetExtendedLmpFeatures(), handle); + bluetooth::os::LogMetricBluetoothRemoteSupportedFeatures(connections.get_address(handle), + view.GetPageNumber(), + view.GetExtendedLmpFeatures(), handle); connections.execute(handle, [=](ConnectionManagementCallbacks* callbacks) { callbacks->OnReadRemoteExtendedFeaturesComplete( - view.GetPageNumber(), view.GetMaximumPageNumber(), view.GetExtendedLmpFeatures()); + view.GetPageNumber(), view.GetMaximumPageNumber(), view.GetExtendedLmpFeatures()); }); } @@ -671,10 +662,8 @@ struct classic_impl { if (delayed_role_change_ != nullptr) { log::warn("Second delayed role change (@{} dropped)", delayed_role_change_->GetBdAddr()); } - log::info( - "Role change for {} with no matching connection (new role: {})", - role_change_view.GetBdAddr(), - RoleText(role_change_view.GetNewRole())); + log::info("Role change for {} with no matching connection (new role: {})", + role_change_view.GetBdAddr(), RoleText(role_change_view.GetNewRole())); delayed_role_change_ = std::make_unique(role_change_view); } } @@ -696,38 +685,37 @@ struct classic_impl { void central_link_key(KeyFlag key_flag) { std::unique_ptr packet = CentralLinkKeyBuilder::Create(key_flag); acl_connection_interface_->EnqueueCommand( - std::move(packet), handler_->BindOnce(check_status)); + std::move(packet), handler_->BindOnce(check_status)); } void switch_role(Address address, Role role) { std::unique_ptr packet = SwitchRoleBuilder::Create(address, role); acl_connection_interface_->EnqueueCommand( - std::move(packet), handler_->BindOnce(check_status)); + std::move(packet), handler_->BindOnce(check_status)); } void write_default_link_policy_settings(uint16_t default_link_policy_settings) { std::unique_ptr packet = - WriteDefaultLinkPolicySettingsBuilder::Create(default_link_policy_settings); + WriteDefaultLinkPolicySettingsBuilder::Create(default_link_policy_settings); acl_connection_interface_->EnqueueCommand( - std::move(packet), - handler_->BindOnce(check_complete)); + std::move(packet), + handler_->BindOnce(check_complete)); } void accept_connection(Address address) { auto role = AcceptConnectionRequestRole::BECOME_CENTRAL; // We prefer to be central acl_connection_interface_->EnqueueCommand( - AcceptConnectionRequestBuilder::Create(address, role), - handler_->BindOnceOn(this, &classic_impl::on_accept_connection_status, address)); + AcceptConnectionRequestBuilder::Create(address, role), + handler_->BindOnceOn(this, &classic_impl::on_accept_connection_status, address)); } void reject_connection(std::unique_ptr builder) { acl_connection_interface_->EnqueueCommand( - std::move(builder), handler_->BindOnce(check_status)); + std::move(builder), + handler_->BindOnce(check_status)); } - uint16_t HACK_get_handle(Address address) { - return connections.HACK_get_handle(address); - } + uint16_t HACK_get_handle(Address address) { return connections.HACK_get_handle(address); } void handle_register_callbacks(ConnectionCallbacks* callbacks, os::Handler* handler) { log::assert_that(client_callbacks_ == nullptr, "assert failed: client_callbacks_ == nullptr"); @@ -737,9 +725,8 @@ struct classic_impl { } void handle_unregister_callbacks(ConnectionCallbacks* callbacks, std::promise promise) { - log::assert_that( - client_callbacks_ == callbacks, - "Registered callback entity is different then unregister request"); + log::assert_that(client_callbacks_ == callbacks, + "Registered callback entity is different then unregister request"); client_callbacks_ = nullptr; client_handler_ = nullptr; promise.set_value(); diff --git a/system/gd/hci/acl_manager/classic_impl_test.cc b/system/gd/hci/acl_manager/classic_impl_test.cc index e59be364e0a..ec374292366 100644 --- a/system/gd/hci/acl_manager/classic_impl_test.cc +++ b/system/gd/hci/acl_manager/classic_impl_test.cc @@ -57,7 +57,7 @@ namespace { constexpr bool kCrashOnUnknownHandle = true; constexpr char kFixedAddress[] = "c0:aa:bb:cc:dd:ee"; const bluetooth::hci::Address kRemoteAddress = - bluetooth::hci::Address({0x00, 0x11, 0x22, 0x33, 0x44, 0x55}); + bluetooth::hci::Address({0x00, 0x11, 0x22, 0x33, 0x44, 0x55}); [[maybe_unused]] constexpr uint16_t kHciHandle = 123; template std::shared_ptr> Serialize(std::unique_ptr build) { @@ -92,24 +92,24 @@ T CreateEventView(std::shared_ptr> bytes) { return T::Create(hci::EventView::Create(hci::PacketView(bytes))); } -[[maybe_unused]] hci::CommandCompleteView ReturnCommandComplete( - hci::OpCode op_code, hci::ErrorCode error_code) { +[[maybe_unused]] hci::CommandCompleteView ReturnCommandComplete(hci::OpCode op_code, + hci::ErrorCode error_code) { std::vector success_vector{static_cast(error_code)}; - auto builder = hci::CommandCompleteBuilder::Create( - uint8_t{1}, op_code, std::make_unique(success_vector)); + auto builder = hci::CommandCompleteBuilder::Create(uint8_t{1}, op_code, + std::make_unique(success_vector)); auto bytes = Serialize(std::move(builder)); return hci::CommandCompleteView::Create( - hci::EventView::Create(hci::PacketView(bytes))); + hci::EventView::Create(hci::PacketView(bytes))); } -[[maybe_unused]] hci::CommandStatusView ReturnCommandStatus( - hci::OpCode op_code, hci::ErrorCode error_code) { +[[maybe_unused]] hci::CommandStatusView ReturnCommandStatus(hci::OpCode op_code, + hci::ErrorCode error_code) { std::vector success_vector{static_cast(error_code)}; - auto builder = hci::CommandStatusBuilder::Create( - hci::ErrorCode::SUCCESS, uint8_t{1}, op_code, std::make_unique(success_vector)); + auto builder = hci::CommandStatusBuilder::Create(hci::ErrorCode::SUCCESS, uint8_t{1}, op_code, + std::make_unique(success_vector)); auto bytes = Serialize(std::move(builder)); return hci::CommandStatusView::Create( - hci::EventView::Create(hci::PacketView(bytes))); + hci::EventView::Create(hci::PacketView(bytes))); } bool handle_outgoing_connection_ = false; @@ -122,12 +122,11 @@ namespace hci { namespace acl_manager { class MockAclScheduler : public AclScheduler { - public: +public: virtual void ReportAclConnectionCompletion( - Address /* address */, - common::ContextualOnceCallback handle_outgoing_connection, - common::ContextualOnceCallback handle_incoming_connection, - common::ContextualOnceCallback handle_unknown_connection) override { + Address /* address */, common::ContextualOnceCallback handle_outgoing_connection, + common::ContextualOnceCallback handle_incoming_connection, + common::ContextualOnceCallback handle_unknown_connection) override { if (handle_outgoing_connection_) { handle_outgoing_connection(); return; @@ -150,7 +149,7 @@ PacketView GetPacketView(std::unique_ptrRegisterDequeue( - handler_, common::Bind(&ClassicImplTest::HciDownEndDequeue, common::Unretained(this))); + handler_, common::Bind(&ClassicImplTest::HciDownEndDequeue, common::Unretained(this))); acl_scheduler_ = new MockAclScheduler(); rnr_ = new RemoteNameRequestModule(); - classic_impl_ = new acl_manager::classic_impl( - hci_layer_, - controller_, - handler_, - round_robin_scheduler_, - kCrashOnUnknownHandle, - acl_scheduler_, - rnr_); + classic_impl_ = + new acl_manager::classic_impl(hci_layer_, controller_, handler_, round_robin_scheduler_, + kCrashOnUnknownHandle, acl_scheduler_, rnr_); classic_impl_->handle_register_callbacks(&mock_connection_callback_, handler_); Address address; @@ -204,9 +198,7 @@ class ClassicImplTest : public ::testing::Test { MockAclScheduler* acl_scheduler_; RemoteNameRequestModule* rnr_; - void sync_handler() { - thread_->GetReactor()->WaitForIdle(2s); - } + void sync_handler() { thread_->GetReactor()->WaitForIdle(2s); } void HciDownEndDequeue() { auto packet = hci_queue_.GetDownEnd()->TryDequeue(); @@ -228,7 +220,7 @@ class ClassicImplTest : public ::testing::Test { } } - protected: +protected: Address remote_address_; uint16_t packet_count_; @@ -257,12 +249,8 @@ TEST_F(ClassicImplTest, on_classic_event_CONNECTION_COMPLETE__SUCCESS) { EXPECT_CALL(mock_connection_callback_, OnConnectSuccess); handle_outgoing_connection_ = true; - auto command = ConnectionCompleteBuilder::Create( - ErrorCode::SUCCESS, - kHciHandle, - kRemoteAddress, - LinkType::ACL, - bluetooth::hci::Enable::ENABLED); + auto command = ConnectionCompleteBuilder::Create(ErrorCode::SUCCESS, kHciHandle, kRemoteAddress, + LinkType::ACL, bluetooth::hci::Enable::ENABLED); auto bytes = Serialize(std::move(command)); auto view = CreateEventView(bytes); diff --git a/system/gd/hci/acl_manager/connection_callbacks.h b/system/gd/hci/acl_manager/connection_callbacks.h index 5b11da94363..8804b5ad9d8 100644 --- a/system/gd/hci/acl_manager/connection_callbacks.h +++ b/system/gd/hci/acl_manager/connection_callbacks.h @@ -28,7 +28,7 @@ namespace hci { namespace acl_manager { class ConnectionCallbacks { - public: +public: virtual ~ConnectionCallbacks() = default; // Invoked when controller sends Connection Complete event with Success error code virtual void OnConnectSuccess(std::unique_ptr) = 0; diff --git a/system/gd/hci/acl_manager/connection_callbacks_mock.h b/system/gd/hci/acl_manager/connection_callbacks_mock.h index ead64e694e4..64bd067db24 100644 --- a/system/gd/hci/acl_manager/connection_callbacks_mock.h +++ b/system/gd/hci/acl_manager/connection_callbacks_mock.h @@ -28,9 +28,9 @@ namespace hci { namespace acl_manager { class MockConnectionCallback : public ConnectionCallbacks { - public: - MOCK_METHOD( - void, OnConnectSuccess, (std::unique_ptr connection), (override)); +public: + MOCK_METHOD(void, OnConnectSuccess, (std::unique_ptr connection), + (override)); MOCK_METHOD(void, OnConnectRequest, (Address, ClassOfDevice), (override)); MOCK_METHOD(void, OnConnectFail, (Address, ErrorCode reason, bool locally_initiated), (override)); }; diff --git a/system/gd/hci/acl_manager/connection_management_callbacks.h b/system/gd/hci/acl_manager/connection_management_callbacks.h index a88945e09c7..55d0062c0a2 100644 --- a/system/gd/hci/acl_manager/connection_management_callbacks.h +++ b/system/gd/hci/acl_manager/connection_management_callbacks.h @@ -25,7 +25,7 @@ namespace hci { namespace acl_manager { class ConnectionManagementCallbacks { - public: +public: virtual ~ConnectionManagementCallbacks() = default; // Invoked when controller sends Connection Packet Type Changed event with Success error code virtual void OnConnectionPacketTypeChanged(uint16_t packet_type) = 0; @@ -40,43 +40,49 @@ class ConnectionManagementCallbacks { // Invoked when controller sends Mode Change event with Success error code virtual void OnModeChange(ErrorCode status, Mode current_mode, uint16_t interval) = 0; // Invoked when controller sends Sniff Subrating event with Success error code - virtual void OnSniffSubrating( - hci::ErrorCode hci_status, - uint16_t maximum_transmit_latency, - uint16_t maximum_receive_latency, - uint16_t minimum_remote_timeout, - uint16_t minimum_local_timeout) = 0; + virtual void OnSniffSubrating(hci::ErrorCode hci_status, uint16_t maximum_transmit_latency, + uint16_t maximum_receive_latency, uint16_t minimum_remote_timeout, + uint16_t minimum_local_timeout) = 0; // Invoked when controller sends QoS Setup Complete event with Success error code - virtual void OnQosSetupComplete(ServiceType service_type, uint32_t token_rate, uint32_t peak_bandwidth, - uint32_t latency, uint32_t delay_variation) = 0; + virtual void OnQosSetupComplete(ServiceType service_type, uint32_t token_rate, + uint32_t peak_bandwidth, uint32_t latency, + uint32_t delay_variation) = 0; // Invoked when controller sends Flow Specification Complete event with Success error code - virtual void OnFlowSpecificationComplete(FlowDirection flow_direction, ServiceType service_type, uint32_t token_rate, - uint32_t token_bucket_size, uint32_t peak_bandwidth, - uint32_t access_latency) = 0; + virtual void OnFlowSpecificationComplete(FlowDirection flow_direction, ServiceType service_type, + uint32_t token_rate, uint32_t token_bucket_size, + uint32_t peak_bandwidth, uint32_t access_latency) = 0; // Invoked when controller sends Flush Occurred event virtual void OnFlushOccurred() = 0; - // Invoked when controller sends Command Complete event for Role Discovery command with Success error code + // Invoked when controller sends Command Complete event for Role Discovery command with Success + // error code virtual void OnRoleDiscoveryComplete(Role current_role) = 0; - // Invoked when controller sends Command Complete event for Read Link Policy Settings command with Success error code + // Invoked when controller sends Command Complete event for Read Link Policy Settings command with + // Success error code virtual void OnReadLinkPolicySettingsComplete(uint16_t link_policy_settings) = 0; - // Invoked when controller sends Command Complete event for Read Automatic Flush Timeout command with Success error - // code + // Invoked when controller sends Command Complete event for Read Automatic Flush Timeout command + // with Success error code virtual void OnReadAutomaticFlushTimeoutComplete(uint16_t flush_timeout) = 0; - // Invoked when controller sends Command Complete event for Read Transmit Power Level command with Success error code + // Invoked when controller sends Command Complete event for Read Transmit Power Level command with + // Success error code virtual void OnReadTransmitPowerLevelComplete(uint8_t transmit_power_level) = 0; - // Invoked when controller sends Command Complete event for Read Link Supervision Time out command with Success error - // code + // Invoked when controller sends Command Complete event for Read Link Supervision Time out command + // with Success error code virtual void OnReadLinkSupervisionTimeoutComplete(uint16_t link_supervision_timeout) = 0; - // Invoked when controller sends Command Complete event for Read Failed Contact Counter command with Success error - // code + // Invoked when controller sends Command Complete event for Read Failed Contact Counter command + // with Success error code virtual void OnReadFailedContactCounterComplete(uint16_t failed_contact_counter) = 0; - // Invoked when controller sends Command Complete event for Read Link Quality command with Success error code + // Invoked when controller sends Command Complete event for Read Link Quality command with Success + // error code virtual void OnReadLinkQualityComplete(uint8_t link_quality) = 0; - // Invoked when controller sends Command Complete event for Read AFH Channel Map command with Success error code - virtual void OnReadAfhChannelMapComplete(AfhMode afh_mode, std::array afh_channel_map) = 0; - // Invoked when controller sends Command Complete event for Read RSSI command with Success error code + // Invoked when controller sends Command Complete event for Read AFH Channel Map command with + // Success error code + virtual void OnReadAfhChannelMapComplete(AfhMode afh_mode, + std::array afh_channel_map) = 0; + // Invoked when controller sends Command Complete event for Read RSSI command with Success error + // code virtual void OnReadRssiComplete(uint8_t rssi) = 0; - // Invoked when controller sends Command Complete event for Read Clock command with Success error code + // Invoked when controller sends Command Complete event for Read Clock command with Success error + // code virtual void OnReadClockComplete(uint32_t clock, uint16_t accuracy) = 0; // Invoked when controller sends Central Link Key Complete event virtual void OnCentralLinkKeyComplete(KeyFlag key_flag) = 0; @@ -85,13 +91,15 @@ class ConnectionManagementCallbacks { // Invoked when controller sends DisconnectComplete virtual void OnDisconnection(ErrorCode reason) = 0; // Invoked when controller sends Read Remote Version Information Complete - virtual void OnReadRemoteVersionInformationComplete( - hci::ErrorCode hci_status, uint8_t lmp_version, uint16_t manufacturer_name, uint16_t sub_version) = 0; + virtual void OnReadRemoteVersionInformationComplete(hci::ErrorCode hci_status, + uint8_t lmp_version, + uint16_t manufacturer_name, + uint16_t sub_version) = 0; // Invoked when controller sends Read Remote Supported Features Complete virtual void OnReadRemoteSupportedFeaturesComplete(uint64_t features) = 0; // Invoked when controller sends Read Remote Extended Features Complete - virtual void OnReadRemoteExtendedFeaturesComplete( - uint8_t page_number, uint8_t max_page_number, uint64_t features) = 0; + virtual void OnReadRemoteExtendedFeaturesComplete(uint8_t page_number, uint8_t max_page_number, + uint64_t features) = 0; }; } // namespace acl_manager diff --git a/system/gd/hci/acl_manager/connection_management_callbacks_mock.h b/system/gd/hci/acl_manager/connection_management_callbacks_mock.h index 9a6700c45c3..e453ac99fcf 100644 --- a/system/gd/hci/acl_manager/connection_management_callbacks_mock.h +++ b/system/gd/hci/acl_manager/connection_management_callbacks_mock.h @@ -29,73 +29,51 @@ namespace hci { namespace acl_manager { class MockConnectionManagementCallbacks : public ConnectionManagementCallbacks { - public: +public: MOCK_METHOD(void, OnConnectionPacketTypeChanged, (uint16_t packet_type), (override)); MOCK_METHOD(void, OnAuthenticationComplete, (ErrorCode hci_status), (override)); MOCK_METHOD(void, OnEncryptionChange, (EncryptionEnabled enabled)), (override); MOCK_METHOD(void, OnChangeConnectionLinkKeyComplete, (), (override)); MOCK_METHOD(void, OnReadClockOffsetComplete, (uint16_t clock_offse), (override)); - MOCK_METHOD( - void, OnModeChange, (ErrorCode status, Mode current_mode, uint16_t interval), (override)); - MOCK_METHOD( - void, - OnSniffSubrating, - (ErrorCode status, - uint16_t maximum_transmit_latency, - uint16_t maximum_receive_latency, - uint16_t minimum_remote_timeout, - uint16_t minimum_local_timeout), - (override)); - MOCK_METHOD( - void, - OnQosSetupComplete, - (ServiceType service_type, - uint32_t token_rate, - uint32_t peak_bandwidth, - uint32_t latency, - uint32_t delay_variation), - (override)); - MOCK_METHOD( - void, - OnFlowSpecificationComplete, - (FlowDirection flow_direction, - ServiceType service_type, - uint32_t token_rate, - uint32_t token_bucket_size, - uint32_t peak_bandwidth, - uint32_t access_latency), - (override)); + MOCK_METHOD(void, OnModeChange, (ErrorCode status, Mode current_mode, uint16_t interval), + (override)); + MOCK_METHOD(void, OnSniffSubrating, + (ErrorCode status, uint16_t maximum_transmit_latency, + uint16_t maximum_receive_latency, uint16_t minimum_remote_timeout, + uint16_t minimum_local_timeout), + (override)); + MOCK_METHOD(void, OnQosSetupComplete, + (ServiceType service_type, uint32_t token_rate, uint32_t peak_bandwidth, + uint32_t latency, uint32_t delay_variation), + (override)); + MOCK_METHOD(void, OnFlowSpecificationComplete, + (FlowDirection flow_direction, ServiceType service_type, uint32_t token_rate, + uint32_t token_bucket_size, uint32_t peak_bandwidth, uint32_t access_latency), + (override)); MOCK_METHOD(void, OnFlushOccurred, (), (override)); MOCK_METHOD(void, OnRoleDiscoveryComplete, (Role current_role), (override)); MOCK_METHOD(void, OnReadLinkPolicySettingsComplete, (uint16_t link_policy_settings), (override)); MOCK_METHOD(void, OnReadAutomaticFlushTimeoutComplete, (uint16_t flush_timeout), (override)); MOCK_METHOD(void, OnReadTransmitPowerLevelComplete, (uint8_t transmit_power_level), (override)); - MOCK_METHOD( - void, OnReadLinkSupervisionTimeoutComplete, (uint16_t link_supervision_timeout), (override)); - MOCK_METHOD( - void, OnReadFailedContactCounterComplete, (uint16_t failed_contact_counter), (override)); + MOCK_METHOD(void, OnReadLinkSupervisionTimeoutComplete, (uint16_t link_supervision_timeout), + (override)); + MOCK_METHOD(void, OnReadFailedContactCounterComplete, (uint16_t failed_contact_counter), + (override)); MOCK_METHOD(void, OnReadLinkQualityComplete, (uint8_t link_quality), (override)); - MOCK_METHOD( - void, - OnReadAfhChannelMapComplete, - (AfhMode afh_mode, (std::array)afh_channel_map), - (override)); + MOCK_METHOD(void, OnReadAfhChannelMapComplete, + (AfhMode afh_mode, (std::array)afh_channel_map), (override)); MOCK_METHOD(void, OnReadRssiComplete, (uint8_t rssi), (override)); MOCK_METHOD(void, OnReadClockComplete, (uint32_t clock, uint16_t accuracy), (override)); MOCK_METHOD(void, OnCentralLinkKeyComplete, (KeyFlag flag), (override)); MOCK_METHOD(void, OnRoleChange, (ErrorCode hci_status, Role new_role), (override)); MOCK_METHOD(void, OnDisconnection, (ErrorCode reason), (override)); - MOCK_METHOD( - void, - OnReadRemoteVersionInformationComplete, - (ErrorCode hci_status, uint8_t lmp_version, uint16_t manufacturer_name, uint16_t sub_version), - (override)); + MOCK_METHOD(void, OnReadRemoteVersionInformationComplete, + (ErrorCode hci_status, uint8_t lmp_version, uint16_t manufacturer_name, + uint16_t sub_version), + (override)); MOCK_METHOD(void, OnReadRemoteSupportedFeaturesComplete, (uint64_t features), (override)); - MOCK_METHOD( - void, - OnReadRemoteExtendedFeaturesComplete, - (uint8_t page_number, uint8_t max_page_number, uint64_t features), - (override)); + MOCK_METHOD(void, OnReadRemoteExtendedFeaturesComplete, + (uint8_t page_number, uint8_t max_page_number, uint64_t features), (override)); }; } // namespace acl_manager diff --git a/system/gd/hci/acl_manager/le_acceptlist_callbacks.h b/system/gd/hci/acl_manager/le_acceptlist_callbacks.h index 666addb4579..a7b7dd5f5ee 100644 --- a/system/gd/hci/acl_manager/le_acceptlist_callbacks.h +++ b/system/gd/hci/acl_manager/le_acceptlist_callbacks.h @@ -26,7 +26,7 @@ namespace acl_manager { /// @brief These are callbacks needed to track the state of the acceptlist, used by the /// Rust connection manager. class LeAcceptlistCallbacks { - public: +public: virtual ~LeAcceptlistCallbacks() = default; // Invoked when controller sends Connection Complete event with Success error code // AddressWithType is the address returned by the controller. diff --git a/system/gd/hci/acl_manager/le_acl_connection.cc b/system/gd/hci/acl_manager/le_acl_connection.cc index 0a6462aef6a..635c05b41bc 100644 --- a/system/gd/hci/acl_manager/le_acl_connection.cc +++ b/system/gd/hci/acl_manager/le_acl_connection.cc @@ -29,9 +29,11 @@ namespace hci { namespace acl_manager { class LeAclConnectionTracker : public LeConnectionManagementCallbacks { - public: - LeAclConnectionTracker(LeAclConnectionInterface* le_acl_connection_interface, uint16_t connection_handle) - : le_acl_connection_interface_(le_acl_connection_interface), connection_handle_(connection_handle) {} +public: + LeAclConnectionTracker(LeAclConnectionInterface* le_acl_connection_interface, + uint16_t connection_handle) + : le_acl_connection_interface_(le_acl_connection_interface), + connection_handle_(connection_handle) {} ~LeAclConnectionTracker() { log::assert_that(queued_callbacks_.empty(), "assert failed: queued_callbacks_.empty()"); } @@ -45,37 +47,36 @@ class LeAclConnectionTracker : public LeConnectionManagementCallbacks { } } -#define SAVE_OR_CALL(f, ...) \ - if (client_handler_ == nullptr) { \ - queued_callbacks_.emplace_back( \ - common::BindOnce(&LeConnectionManagementCallbacks::f, common::Unretained(this), __VA_ARGS__)); \ - } else { \ - client_handler_->Post( \ - common::BindOnce(&LeConnectionManagementCallbacks::f, common::Unretained(client_callbacks_), __VA_ARGS__)); \ +#define SAVE_OR_CALL(f, ...) \ + if (client_handler_ == nullptr) { \ + queued_callbacks_.emplace_back(common::BindOnce(&LeConnectionManagementCallbacks::f, \ + common::Unretained(this), __VA_ARGS__)); \ + } else { \ + client_handler_->Post(common::BindOnce(&LeConnectionManagementCallbacks::f, \ + common::Unretained(client_callbacks_), __VA_ARGS__)); \ } - void OnConnectionUpdate( - hci::ErrorCode hci_status, uint16_t conn_interval, uint16_t conn_latency, uint16_t supervision_timeout) override { + void OnConnectionUpdate(hci::ErrorCode hci_status, uint16_t conn_interval, uint16_t conn_latency, + uint16_t supervision_timeout) override { SAVE_OR_CALL(OnConnectionUpdate, hci_status, conn_interval, conn_latency, supervision_timeout) } - void OnParameterUpdateRequest( - uint16_t interval_min, - uint16_t interval_max, - uint16_t latency, - uint16_t supervision_timeout) override { + void OnParameterUpdateRequest(uint16_t interval_min, uint16_t interval_max, uint16_t latency, + uint16_t supervision_timeout) override { SAVE_OR_CALL(OnParameterUpdateRequest, interval_min, interval_max, latency, supervision_timeout) } - void OnDataLengthChange(uint16_t tx_octets, uint16_t tx_time, uint16_t rx_octets, uint16_t rx_time) override { + void OnDataLengthChange(uint16_t tx_octets, uint16_t tx_time, uint16_t rx_octets, + uint16_t rx_time) override { SAVE_OR_CALL(OnDataLengthChange, tx_octets, tx_time, rx_octets, rx_time) } - void OnReadRemoteVersionInformationComplete( - hci::ErrorCode hci_status, uint8_t lmp_version, uint16_t manufacturer_name, uint16_t sub_version) { - bluetooth::os::LogMetricRemoteVersionInfo( - connection_handle_, static_cast(hci_status), lmp_version, manufacturer_name, sub_version); - SAVE_OR_CALL(OnReadRemoteVersionInformationComplete, hci_status, lmp_version, manufacturer_name, sub_version); + void OnReadRemoteVersionInformationComplete(hci::ErrorCode hci_status, uint8_t lmp_version, + uint16_t manufacturer_name, uint16_t sub_version) { + bluetooth::os::LogMetricRemoteVersionInfo(connection_handle_, static_cast(hci_status), + lmp_version, manufacturer_name, sub_version); + SAVE_OR_CALL(OnReadRemoteVersionInformationComplete, hci_status, lmp_version, manufacturer_name, + sub_version); } void OnLeReadRemoteFeaturesComplete(hci::ErrorCode hci_status, uint64_t features) override { @@ -85,19 +86,14 @@ class LeAclConnectionTracker : public LeConnectionManagementCallbacks { void OnPhyUpdate(hci::ErrorCode hci_status, uint8_t tx_phy, uint8_t rx_phy) override { SAVE_OR_CALL(OnPhyUpdate, hci_status, tx_phy, rx_phy); } - void OnLeSubrateChange( - hci::ErrorCode hci_status, - uint16_t subrate_factor, - uint16_t peripheral_latency, - uint16_t continuation_number, - uint16_t supervision_timeout) override { - SAVE_OR_CALL( - OnLeSubrateChange, hci_status, subrate_factor, peripheral_latency, continuation_number, supervision_timeout); + void OnLeSubrateChange(hci::ErrorCode hci_status, uint16_t subrate_factor, + uint16_t peripheral_latency, uint16_t continuation_number, + uint16_t supervision_timeout) override { + SAVE_OR_CALL(OnLeSubrateChange, hci_status, subrate_factor, peripheral_latency, + continuation_number, supervision_timeout); } - void OnDisconnection(ErrorCode reason) override { - SAVE_OR_CALL(OnDisconnection, reason); - } + void OnDisconnection(ErrorCode reason) override { SAVE_OR_CALL(OnDisconnection, reason); } #undef SAVE_OR_CALL LeAclConnectionInterface* le_acl_connection_interface_; @@ -108,16 +104,20 @@ class LeAclConnectionTracker : public LeConnectionManagementCallbacks { }; struct LeAclConnection::impl { - impl(LeAclConnectionInterface* le_acl_connection_interface, std::shared_ptr queue, uint16_t connection_handle) + impl(LeAclConnectionInterface* le_acl_connection_interface, std::shared_ptr queue, + uint16_t connection_handle) : queue_(std::move(queue)), tracker(le_acl_connection_interface, connection_handle) {} - LeConnectionManagementCallbacks* GetEventCallbacks(std::function invalidate_callbacks) { - log::assert_that( - !invalidate_callbacks_, "Already returned event callbacks for this connection"); + LeConnectionManagementCallbacks* GetEventCallbacks( + std::function invalidate_callbacks) { + log::assert_that(!invalidate_callbacks_, + "Already returned event callbacks for this connection"); invalidate_callbacks_ = std::move(invalidate_callbacks); return &tracker; } void PutEventCallbacks() { - if (invalidate_callbacks_) invalidate_callbacks_(tracker.connection_handle_); + if (invalidate_callbacks_) { + invalidate_callbacks_(tracker.connection_handle_); + } } std::shared_ptr queue_; LeAclConnectionTracker tracker; @@ -129,12 +129,10 @@ LeAclConnection::LeAclConnection() remote_address_(Address::kEmpty, AddressType::PUBLIC_DEVICE_ADDRESS), role_specific_data_(DataAsUninitializedPeripheral{}) {} -LeAclConnection::LeAclConnection( - std::shared_ptr queue, - LeAclConnectionInterface* le_acl_connection_interface, - uint16_t handle, - RoleSpecificData role_specific_data, - AddressWithType remote_address) +LeAclConnection::LeAclConnection(std::shared_ptr queue, + LeAclConnectionInterface* le_acl_connection_interface, + uint16_t handle, RoleSpecificData role_specific_data, + AddressWithType remote_address) : AclConnection(queue->GetUpEnd(), handle), remote_address_(remote_address), role_specific_data_(role_specific_data) { @@ -142,72 +140,72 @@ LeAclConnection::LeAclConnection( } LeAclConnection::~LeAclConnection() { - if (pimpl_) pimpl_->PutEventCallbacks(); + if (pimpl_) { + pimpl_->PutEventCallbacks(); + } delete pimpl_; } AddressWithType LeAclConnection::GetLocalAddress() const { return std::visit( - [](auto&& data) { - using T = std::decay_t; - if constexpr (std::is_same_v) { - // This case should never happen outside of acl_manager.cc, since once the connection is - // passed into the OnConnectSuccess callback, it should be fully initialized. - log::fatal("Attempted to read the local address of an uninitialized connection"); - return AddressWithType{}; - } else { - return data.local_address; - } - }, - role_specific_data_); + [](auto&& data) { + using T = std::decay_t; + if constexpr (std::is_same_v) { + // This case should never happen outside of acl_manager.cc, since once the connection + // is passed into the OnConnectSuccess callback, it should be fully initialized. + log::fatal("Attempted to read the local address of an uninitialized connection"); + return AddressWithType{}; + } else { + return data.local_address; + } + }, + role_specific_data_); } Role LeAclConnection::GetRole() const { return std::visit( - [](auto&& data) { - using T = std::decay_t; - if constexpr (std::is_same_v) { - return Role::CENTRAL; - } else if constexpr ( - std::is_same_v || - std::is_same_v) { - return Role::PERIPHERAL; - } else { - static_assert(!sizeof(T*), "missing case"); - } - }, - role_specific_data_); + [](auto&& data) { + using T = std::decay_t; + if constexpr (std::is_same_v) { + return Role::CENTRAL; + } else if constexpr (std::is_same_v || + std::is_same_v) { + return Role::PERIPHERAL; + } else { + static_assert(!sizeof(T*), "missing case"); + } + }, + role_specific_data_); } -const RoleSpecificData& LeAclConnection::GetRoleSpecificData() const { - return role_specific_data_; -} +const RoleSpecificData& LeAclConnection::GetRoleSpecificData() const { return role_specific_data_; } -void LeAclConnection::RegisterCallbacks(LeConnectionManagementCallbacks* callbacks, os::Handler* handler) { +void LeAclConnection::RegisterCallbacks(LeConnectionManagementCallbacks* callbacks, + os::Handler* handler) { return pimpl_->tracker.RegisterCallbacks(callbacks, handler); } void LeAclConnection::Disconnect(DisconnectReason reason) { pimpl_->tracker.le_acl_connection_interface_->EnqueueCommand( - DisconnectBuilder::Create(handle_, reason), - pimpl_->tracker.client_handler_->BindOnce([](CommandStatusView status) { - log::assert_that(status.IsValid(), "assert failed: status.IsValid()"); - log::assert_that( - status.GetCommandOpCode() == OpCode::DISCONNECT, - "assert failed: status.GetCommandOpCode() == OpCode::DISCONNECT"); - auto disconnect_status = DisconnectStatusView::Create(status); - log::assert_that(disconnect_status.IsValid(), "assert failed: disconnect_status.IsValid()"); - auto error_code = disconnect_status.GetStatus(); - if (error_code != ErrorCode::SUCCESS) { - log::info("Disconnect status {}", ErrorCodeText(error_code)); - } - })); + DisconnectBuilder::Create(handle_, reason), + pimpl_->tracker.client_handler_->BindOnce([](CommandStatusView status) { + log::assert_that(status.IsValid(), "assert failed: status.IsValid()"); + log::assert_that(status.GetCommandOpCode() == OpCode::DISCONNECT, + "assert failed: status.GetCommandOpCode() == OpCode::DISCONNECT"); + auto disconnect_status = DisconnectStatusView::Create(status); + log::assert_that(disconnect_status.IsValid(), + "assert failed: disconnect_status.IsValid()"); + auto error_code = disconnect_status.GetStatus(); + if (error_code != ErrorCode::SUCCESS) { + log::info("Disconnect status {}", ErrorCodeText(error_code)); + } + })); } void LeAclConnection::OnLeSubrateRequestStatus(CommandStatusView status) { auto subrate_request_status = LeSubrateRequestStatusView::Create(status); - log::assert_that( - subrate_request_status.IsValid(), "assert failed: subrate_request_status.IsValid()"); + log::assert_that(subrate_request_status.IsValid(), + "assert failed: subrate_request_status.IsValid()"); auto hci_status = subrate_request_status.GetStatus(); if (hci_status != ErrorCode::SUCCESS) { log::info("LeSubrateRequest status {}", ErrorCodeText(hci_status)); @@ -215,68 +213,63 @@ void LeAclConnection::OnLeSubrateRequestStatus(CommandStatusView status) { } } -void LeAclConnection::LeSubrateRequest( - uint16_t subrate_min, uint16_t subrate_max, uint16_t max_latency, uint16_t cont_num, uint16_t sup_tout) { +void LeAclConnection::LeSubrateRequest(uint16_t subrate_min, uint16_t subrate_max, + uint16_t max_latency, uint16_t cont_num, uint16_t sup_tout) { pimpl_->tracker.le_acl_connection_interface_->EnqueueCommand( - LeSubrateRequestBuilder::Create(handle_, subrate_min, subrate_max, max_latency, cont_num, sup_tout), - pimpl_->tracker.client_handler_->BindOnceOn(this, &LeAclConnection::OnLeSubrateRequestStatus)); + LeSubrateRequestBuilder::Create(handle_, subrate_min, subrate_max, max_latency, cont_num, + sup_tout), + pimpl_->tracker.client_handler_->BindOnceOn(this, + &LeAclConnection::OnLeSubrateRequestStatus)); } LeConnectionManagementCallbacks* LeAclConnection::GetEventCallbacks( - std::function invalidate_callbacks) { + std::function invalidate_callbacks) { return pimpl_->GetEventCallbacks(std::move(invalidate_callbacks)); } -bool LeAclConnection::LeConnectionUpdate( - uint16_t conn_interval_min, - uint16_t conn_interval_max, - uint16_t conn_latency, - uint16_t supervision_timeout, - uint16_t min_ce_length, - uint16_t max_ce_length) { - if (!check_connection_parameters(conn_interval_min, conn_interval_max, conn_latency, supervision_timeout)) { +bool LeAclConnection::LeConnectionUpdate(uint16_t conn_interval_min, uint16_t conn_interval_max, + uint16_t conn_latency, uint16_t supervision_timeout, + uint16_t min_ce_length, uint16_t max_ce_length) { + if (!check_connection_parameters(conn_interval_min, conn_interval_max, conn_latency, + supervision_timeout)) { log::error("Invalid parameter"); return false; } pimpl_->tracker.le_acl_connection_interface_->EnqueueCommand( - LeConnectionUpdateBuilder::Create( - handle_, - conn_interval_min, - conn_interval_max, - conn_latency, - supervision_timeout, - min_ce_length, - max_ce_length), - pimpl_->tracker.client_handler_->BindOnce(check_status)); + LeConnectionUpdateBuilder::Create(handle_, conn_interval_min, conn_interval_max, + conn_latency, supervision_timeout, min_ce_length, + max_ce_length), + pimpl_->tracker.client_handler_->BindOnce(check_status)); return true; } bool LeAclConnection::ReadRemoteVersionInformation() { pimpl_->tracker.le_acl_connection_interface_->EnqueueCommand( - ReadRemoteVersionInformationBuilder::Create(handle_), - pimpl_->tracker.client_handler_->BindOnce([](CommandStatusView status) { - log::assert_that(status.IsValid(), "assert failed: status.IsValid()"); - log::assert_that( - status.GetCommandOpCode() == OpCode::READ_REMOTE_VERSION_INFORMATION, - "assert failed: status.GetCommandOpCode() == OpCode::READ_REMOTE_VERSION_INFORMATION"); - })); + ReadRemoteVersionInformationBuilder::Create(handle_), + pimpl_->tracker.client_handler_->BindOnce([](CommandStatusView status) { + log::assert_that(status.IsValid(), "assert failed: status.IsValid()"); + log::assert_that(status.GetCommandOpCode() == OpCode::READ_REMOTE_VERSION_INFORMATION, + "assert failed: status.GetCommandOpCode() == " + "OpCode::READ_REMOTE_VERSION_INFORMATION"); + })); return true; } bool LeAclConnection::LeReadRemoteFeatures() { pimpl_->tracker.le_acl_connection_interface_->EnqueueCommand( - LeReadRemoteFeaturesBuilder::Create(handle_), - pimpl_->tracker.client_handler_->BindOnce([](CommandStatusView status) { - log::assert_that(status.IsValid(), "assert failed: status.IsValid()"); - log::assert_that( - status.GetCommandOpCode() == OpCode::LE_READ_REMOTE_FEATURES, - "assert failed: status.GetCommandOpCode() == OpCode::LE_READ_REMOTE_FEATURES"); - })); + LeReadRemoteFeaturesBuilder::Create(handle_), + pimpl_->tracker.client_handler_->BindOnce([](CommandStatusView status) { + log::assert_that(status.IsValid(), "assert failed: status.IsValid()"); + log::assert_that( + status.GetCommandOpCode() == OpCode::LE_READ_REMOTE_FEATURES, + "assert failed: status.GetCommandOpCode() == OpCode::LE_READ_REMOTE_FEATURES"); + })); return true; } -bool LeAclConnection::check_connection_parameters( - uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout) { +bool LeAclConnection::check_connection_parameters(uint16_t conn_interval_min, + uint16_t conn_interval_max, uint16_t conn_latency, + uint16_t supervision_timeout) { if (conn_interval_min < 0x0006 || conn_interval_min > 0x0C80 || conn_interval_max < 0x0006 || conn_interval_max > 0x0C80 || conn_latency > 0x01F3 || supervision_timeout < 0x000A || supervision_timeout > 0x0C80) { @@ -285,8 +278,8 @@ bool LeAclConnection::check_connection_parameters( } // The Maximum interval in milliseconds will be conn_interval_max * 1.25 ms // The Timeout in milliseconds will be expected_supervision_timeout * 10 ms - // The Timeout in milliseconds shall be larger than (1 + Latency) * Interval_Max * 2, where Interval_Max is given in - // milliseconds. + // The Timeout in milliseconds shall be larger than (1 + Latency) * Interval_Max * 2, where + // Interval_Max is given in milliseconds. uint32_t supervision_timeout_min = (uint32_t)(1 + conn_latency) * conn_interval_max * 2 + 1; if (supervision_timeout * 8 < supervision_timeout_min || conn_interval_max < conn_interval_min) { log::error("Invalid parameter"); diff --git a/system/gd/hci/acl_manager/le_acl_connection.h b/system/gd/hci/acl_manager/le_acl_connection.h index 05a3a6787fc..574b104a97a 100644 --- a/system/gd/hci/acl_manager/le_acl_connection.h +++ b/system/gd/hci/acl_manager/le_acl_connection.h @@ -50,17 +50,14 @@ struct DataAsPeripheral { struct DataAsUninitializedPeripheral {}; using RoleSpecificData = - std::variant; + std::variant; class LeAclConnection : public AclConnection { - public: +public: LeAclConnection(); - LeAclConnection( - std::shared_ptr queue, - LeAclConnectionInterface* le_acl_connection_interface, - uint16_t handle, - RoleSpecificData role_specific_data, - AddressWithType remote_address); + LeAclConnection(std::shared_ptr queue, + LeAclConnectionInterface* le_acl_connection_interface, uint16_t handle, + RoleSpecificData role_specific_data, AddressWithType remote_address); LeAclConnection(const LeAclConnection&) = delete; LeAclConnection& operator=(const LeAclConnection&) = delete; @@ -76,9 +73,7 @@ class LeAclConnection : public AclConnection { role_specific_data_ = role_specific_data; } - virtual AddressWithType GetRemoteAddress() const { - return remote_address_; - } + virtual AddressWithType GetRemoteAddress() const { return remote_address_; } // The peer address and type returned from the Connection Complete Event AddressWithType peer_address_with_type_; @@ -99,16 +94,12 @@ class LeAclConnection : public AclConnection { // True if connection address was in the filter accept list, false otherwise bool in_filter_accept_list_; - bool IsInFilterAcceptList() const { - return in_filter_accept_list_; - } + bool IsInFilterAcceptList() const { return in_filter_accept_list_; } Address local_resolvable_private_address_ = Address::kEmpty; Address peer_resolvable_private_address_ = Address::kEmpty; - virtual AddressWithType GetPeerAddress() const { - return peer_address_with_type_; - } + virtual AddressWithType GetPeerAddress() const { return peer_address_with_type_; } // This function return actual peer address which was used for the connection over the air. virtual AddressWithType GetPeerOtaAddress() const { @@ -130,36 +121,32 @@ class LeAclConnection : public AclConnection { virtual void RegisterCallbacks(LeConnectionManagementCallbacks* callbacks, os::Handler* handler); virtual void Disconnect(DisconnectReason reason); - virtual bool LeConnectionUpdate( - uint16_t conn_interval_min, - uint16_t conn_interval_max, - uint16_t conn_latency, - uint16_t supervision_timeout, - uint16_t min_ce_length, - uint16_t max_ce_length); + virtual bool LeConnectionUpdate(uint16_t conn_interval_min, uint16_t conn_interval_max, + uint16_t conn_latency, uint16_t supervision_timeout, + uint16_t min_ce_length, uint16_t max_ce_length); virtual bool ReadRemoteVersionInformation() override; virtual bool LeReadRemoteFeatures(); - virtual void LeSubrateRequest( - uint16_t subrate_min, uint16_t subrate_max, uint16_t max_latency, uint16_t cont_num, uint16_t sup_tout); + virtual void LeSubrateRequest(uint16_t subrate_min, uint16_t subrate_max, uint16_t max_latency, + uint16_t cont_num, uint16_t sup_tout); - // TODO implement LeRemoteConnectionParameterRequestReply, LeRemoteConnectionParameterRequestNegativeReply + // TODO implement LeRemoteConnectionParameterRequestReply, + // LeRemoteConnectionParameterRequestNegativeReply // Called once before passing the connection to the client - virtual LeConnectionManagementCallbacks* GetEventCallbacks(std::function invalidate_callbacks); + virtual LeConnectionManagementCallbacks* GetEventCallbacks( + std::function invalidate_callbacks); - protected: +protected: AddressWithType remote_address_; RoleSpecificData role_specific_data_; - private: +private: void OnLeSubrateRequestStatus(CommandStatusView status); - virtual bool check_connection_parameters( - uint16_t conn_interval_min, - uint16_t conn_interval_max, - uint16_t expected_conn_latency, - uint16_t expected_supervision_timeout); + virtual bool check_connection_parameters(uint16_t conn_interval_min, uint16_t conn_interval_max, + uint16_t expected_conn_latency, + uint16_t expected_supervision_timeout); struct impl; struct impl* pimpl_ = nullptr; }; diff --git a/system/gd/hci/acl_manager/le_acl_connection_test.cc b/system/gd/hci/acl_manager/le_acl_connection_test.cc index ef1f24b01c1..1b80e08ec09 100644 --- a/system/gd/hci/acl_manager/le_acl_connection_test.cc +++ b/system/gd/hci/acl_manager/le_acl_connection_test.cc @@ -62,10 +62,10 @@ namespace bluetooth::hci::acl_manager { namespace { class TestLeAclConnectionInterface : public hci::LeAclConnectionInterface { - private: +private: void EnqueueCommand( - std::unique_ptr command, - common::ContextualOnceCallback on_status) override { + std::unique_ptr command, + common::ContextualOnceCallback on_status) override { const std::lock_guard lock(command_queue_mutex_); command_queue_.push(std::move(command)); command_status_callbacks.push_back(std::move(on_status)); @@ -77,8 +77,8 @@ class TestLeAclConnectionInterface : public hci::LeAclConnectionInterface { } void EnqueueCommand( - std::unique_ptr command, - common::ContextualOnceCallback on_complete) override { + std::unique_ptr command, + common::ContextualOnceCallback on_complete) override { const std::lock_guard lock(command_queue_mutex_); command_queue_.push(std::move(command)); command_complete_callbacks.push_back(std::move(on_complete)); @@ -89,7 +89,7 @@ class TestLeAclConnectionInterface : public hci::LeAclConnectionInterface { } } - public: +public: virtual ~TestLeAclConnectionInterface() = default; std::unique_ptr DequeueCommand() { @@ -123,8 +123,9 @@ class TestLeAclConnectionInterface : public hci::LeAclConnectionInterface { return command_queue_.size(); } - private: - std::list> command_complete_callbacks; +private: + std::list> + command_complete_callbacks; std::list> command_status_callbacks; std::queue> command_queue_; mutable std::mutex command_queue_mutex_; @@ -133,18 +134,14 @@ class TestLeAclConnectionInterface : public hci::LeAclConnectionInterface { }; class LeAclConnectionTest : public ::testing::Test { - protected: +protected: void SetUp() override { thread_ = new os::Thread("thread", os::Thread::Priority::NORMAL); handler_ = new os::Handler(thread_); queue_ = std::make_shared(kQueueSize); sync_handler(); - connection_ = new LeAclConnection( - queue_, - &le_acl_connection_interface_, - kConnectionHandle, - DataAsCentral{address_1}, - address_2); + connection_ = new LeAclConnection(queue_, &le_acl_connection_interface_, kConnectionHandle, + DataAsCentral{address_1}, address_2); connection_->RegisterCallbacks(&callbacks_, handler_); } @@ -157,15 +154,14 @@ class LeAclConnectionTest : public ::testing::Test { void sync_handler() { log::assert_that(thread_ != nullptr, "assert failed: thread_ != nullptr"); - log::assert_that( - thread_->GetReactor()->WaitForIdle(2s), - "assert failed: thread_->GetReactor()->WaitForIdle(2s)"); + log::assert_that(thread_->GetReactor()->WaitForIdle(2s), + "assert failed: thread_->GetReactor()->WaitForIdle(2s)"); } - AddressWithType address_1 = - AddressWithType(Address{{0x11, 0x22, 0x33, 0x44, 0x55, 0x66}}, AddressType::RANDOM_DEVICE_ADDRESS); - AddressWithType address_2 = - AddressWithType(Address{{0x11, 0x22, 0x33, 0x44, 0x55, 0x66}}, AddressType::PUBLIC_DEVICE_ADDRESS); + AddressWithType address_1 = AddressWithType(Address{{0x11, 0x22, 0x33, 0x44, 0x55, 0x66}}, + AddressType::RANDOM_DEVICE_ADDRESS); + AddressWithType address_2 = AddressWithType(Address{{0x11, 0x22, 0x33, 0x44, 0x55, 0x66}}, + AddressType::PUBLIC_DEVICE_ADDRESS); os::Handler* handler_{nullptr}; os::Thread* thread_{nullptr}; std::shared_ptr queue_; @@ -180,9 +176,11 @@ TEST_F(LeAclConnectionTest, simple) { } TEST_F(LeAclConnectionTest, LeSubrateRequest_success) { - connection_->LeSubrateRequest(kIntervalMin, kIntervalMax, kLatency, kContinuationNumber, kTimeout); + connection_->LeSubrateRequest(kIntervalMin, kIntervalMax, kLatency, kContinuationNumber, + kTimeout); - auto command = CreateAclCommandView(le_acl_connection_interface_.DequeueCommandBytes()); + auto command = CreateAclCommandView( + le_acl_connection_interface_.DequeueCommandBytes()); ASSERT_TRUE(command.IsValid()); ASSERT_EQ(kIntervalMin, command.GetSubrateMin()); ASSERT_EQ(kIntervalMax, command.GetSubrateMax()); @@ -203,9 +201,11 @@ TEST_F(LeAclConnectionTest, LeSubrateRequest_success) { TEST_F(LeAclConnectionTest, LeSubrateRequest_error) { EXPECT_CALL(callbacks_, OnLeSubrateChange(ErrorCode::UNKNOWN_HCI_COMMAND, 0, 0, 0, 0)); - connection_->LeSubrateRequest(kIntervalMin, kIntervalMax, kLatency, kContinuationNumber, kTimeout); + connection_->LeSubrateRequest(kIntervalMin, kIntervalMax, kLatency, kContinuationNumber, + kTimeout); - auto command = CreateAclCommandView(le_acl_connection_interface_.DequeueCommandBytes()); + auto command = CreateAclCommandView( + le_acl_connection_interface_.DequeueCommandBytes()); ASSERT_TRUE(command.IsValid()); ASSERT_EQ(kIntervalMin, command.GetSubrateMin()); ASSERT_EQ(kIntervalMax, command.GetSubrateMax()); diff --git a/system/gd/hci/acl_manager/le_connection_callbacks.h b/system/gd/hci/acl_manager/le_connection_callbacks.h index 451e3f65a40..2359c5ac326 100644 --- a/system/gd/hci/acl_manager/le_connection_callbacks.h +++ b/system/gd/hci/acl_manager/le_connection_callbacks.h @@ -27,12 +27,13 @@ namespace hci { namespace acl_manager { class LeConnectionCallbacks { - public: +public: virtual ~LeConnectionCallbacks() = default; // Invoked when controller sends Connection Complete event with Success error code // AddressWithType is always equal to the object used in AclManager#CreateLeConnection virtual void OnLeConnectSuccess(AddressWithType, std::unique_ptr) = 0; - // Invoked when create connection timeout or controller sends Connection Complete event with non-Success error code + // Invoked when create connection timeout or controller sends Connection Complete event with + // non-Success error code virtual void OnLeConnectFail(AddressWithType, ErrorCode reason) = 0; }; diff --git a/system/gd/hci/acl_manager/le_connection_callbacks_mock.h b/system/gd/hci/acl_manager/le_connection_callbacks_mock.h index dc3bd3b8ddc..fca3e93b892 100644 --- a/system/gd/hci/acl_manager/le_connection_callbacks_mock.h +++ b/system/gd/hci/acl_manager/le_connection_callbacks_mock.h @@ -30,14 +30,12 @@ namespace hci { namespace acl_manager { class MockLeConnectionCallbacks : public LeConnectionCallbacks { - public: - MOCK_METHOD( - void, - OnLeConnectSuccess, - (AddressWithType address_with_type, std::unique_ptr connection), - (override)); - MOCK_METHOD( - void, OnLeConnectFail, (AddressWithType address_with_type, ErrorCode reason), (override)); +public: + MOCK_METHOD(void, OnLeConnectSuccess, + (AddressWithType address_with_type, std::unique_ptr connection), + (override)); + MOCK_METHOD(void, OnLeConnectFail, (AddressWithType address_with_type, ErrorCode reason), + (override)); }; } // namespace acl_manager diff --git a/system/gd/hci/acl_manager/le_connection_management_callbacks.h b/system/gd/hci/acl_manager/le_connection_management_callbacks.h index f36ea13dbc6..6ac56af0299 100644 --- a/system/gd/hci/acl_manager/le_connection_management_callbacks.h +++ b/system/gd/hci/acl_manager/le_connection_management_callbacks.h @@ -23,30 +23,24 @@ namespace hci { namespace acl_manager { class LeConnectionManagementCallbacks { - public: +public: virtual ~LeConnectionManagementCallbacks() = default; - virtual void OnConnectionUpdate( - hci::ErrorCode hci_status, - uint16_t connection_interval, - uint16_t connection_latency, - uint16_t supervision_timeout) = 0; - virtual void OnParameterUpdateRequest( - uint16_t interval_min, - uint16_t interval_max, - uint16_t latency, - uint16_t supervision_timeout) = 0; - virtual void OnDataLengthChange(uint16_t tx_octets, uint16_t tx_time, uint16_t rx_octets, uint16_t rx_time) = 0; + virtual void OnConnectionUpdate(hci::ErrorCode hci_status, uint16_t connection_interval, + uint16_t connection_latency, uint16_t supervision_timeout) = 0; + virtual void OnParameterUpdateRequest(uint16_t interval_min, uint16_t interval_max, + uint16_t latency, uint16_t supervision_timeout) = 0; + virtual void OnDataLengthChange(uint16_t tx_octets, uint16_t tx_time, uint16_t rx_octets, + uint16_t rx_time) = 0; virtual void OnDisconnection(hci::ErrorCode reason) = 0; - virtual void OnReadRemoteVersionInformationComplete( - hci::ErrorCode hci_status, uint8_t lmp_version, uint16_t manufacturer_name, uint16_t sub_version) = 0; + virtual void OnReadRemoteVersionInformationComplete(hci::ErrorCode hci_status, + uint8_t lmp_version, + uint16_t manufacturer_name, + uint16_t sub_version) = 0; virtual void OnLeReadRemoteFeaturesComplete(hci::ErrorCode hci_status, uint64_t features) = 0; virtual void OnPhyUpdate(hci::ErrorCode hci_status, uint8_t tx_phy, uint8_t rx_phy) = 0; - virtual void OnLeSubrateChange( - hci::ErrorCode hci_status, - uint16_t subrate_factor, - uint16_t peripheral_latency, - uint16_t continuation_number, - uint16_t supervision_timeout) = 0; + virtual void OnLeSubrateChange(hci::ErrorCode hci_status, uint16_t subrate_factor, + uint16_t peripheral_latency, uint16_t continuation_number, + uint16_t supervision_timeout) = 0; }; } // namespace acl_manager diff --git a/system/gd/hci/acl_manager/le_connection_management_callbacks_mock.h b/system/gd/hci/acl_manager/le_connection_management_callbacks_mock.h index 0b8a248415c..bfbd2147795 100644 --- a/system/gd/hci/acl_manager/le_connection_management_callbacks_mock.h +++ b/system/gd/hci/acl_manager/le_connection_management_callbacks_mock.h @@ -28,53 +28,31 @@ namespace hci { namespace acl_manager { class MockLeConnectionManagementCallbacks : public LeConnectionManagementCallbacks { - public: - MOCK_METHOD( - void, - OnConnectionUpdate, - (hci::ErrorCode hci_status, - uint16_t connection_interval, - uint16_t connection_latency, - uint16_t supervision_timeout), - (override)); - MOCK_METHOD( - void, - OnParameterUpdateRequest, - (uint16_t interval_min, - uint16_t interval_max, - uint16_t latency, - uint16_t supervision_timeout), - (override)); - MOCK_METHOD( - void, - OnDataLengthChange, - (uint16_t tx_octets, uint16_t tx_time, uint16_t rx_octets, uint16_t rx_time), - (override)); +public: + MOCK_METHOD(void, OnConnectionUpdate, + (hci::ErrorCode hci_status, uint16_t connection_interval, uint16_t connection_latency, + uint16_t supervision_timeout), + (override)); + MOCK_METHOD(void, OnParameterUpdateRequest, + (uint16_t interval_min, uint16_t interval_max, uint16_t latency, + uint16_t supervision_timeout), + (override)); + MOCK_METHOD(void, OnDataLengthChange, + (uint16_t tx_octets, uint16_t tx_time, uint16_t rx_octets, uint16_t rx_time), + (override)); MOCK_METHOD(void, OnDisconnection, (ErrorCode reason), (override)); - MOCK_METHOD( - void, - OnReadRemoteVersionInformationComplete, - (hci::ErrorCode hci_status, - uint8_t lmp_version, - uint16_t manufacturer_name, - uint16_t sub_version), - (override)); - MOCK_METHOD( - void, - OnLeReadRemoteFeaturesComplete, - (hci::ErrorCode hci_status, uint64_t features), - (override)); - MOCK_METHOD( - void, OnPhyUpdate, (hci::ErrorCode hci_status, uint8_t tx_phy, uint8_t rx_phy), (override)); - MOCK_METHOD( - void, - OnLeSubrateChange, - (hci::ErrorCode hci_status, - uint16_t subrate_factor, - uint16_t peripheral_latency, - uint16_t continuation_number, - uint16_t supervision_timeout), - (override)); + MOCK_METHOD(void, OnReadRemoteVersionInformationComplete, + (hci::ErrorCode hci_status, uint8_t lmp_version, uint16_t manufacturer_name, + uint16_t sub_version), + (override)); + MOCK_METHOD(void, OnLeReadRemoteFeaturesComplete, (hci::ErrorCode hci_status, uint64_t features), + (override)); + MOCK_METHOD(void, OnPhyUpdate, (hci::ErrorCode hci_status, uint8_t tx_phy, uint8_t rx_phy), + (override)); + MOCK_METHOD(void, OnLeSubrateChange, + (hci::ErrorCode hci_status, uint16_t subrate_factor, uint16_t peripheral_latency, + uint16_t continuation_number, uint16_t supervision_timeout), + (override)); }; } // namespace acl_manager diff --git a/system/gd/hci/acl_manager/le_impl.h b/system/gd/hci/acl_manager/le_impl.h index 85e3451653d..08497b2f26a 100644 --- a/system/gd/hci/acl_manager/le_impl.h +++ b/system/gd/hci/acl_manager/le_impl.h @@ -52,12 +52,12 @@ constexpr uint16_t kConnIntervalMin = 0x0018; constexpr uint16_t kConnIntervalMax = 0x0028; constexpr uint16_t kConnLatency = 0x0000; constexpr uint16_t kSupervisionTimeout = 0x01f4; -constexpr uint16_t kScanIntervalFast = 0x0060; /* 30 ~ 60 ms (use 60) = 96 *0.625 */ -constexpr uint16_t kScanWindowFast = 0x0030; /* 30 ms = 48 *0.625 */ -constexpr uint16_t kScanWindow2mFast = 0x0018; /* 15 ms = 24 *0.625 */ -constexpr uint16_t kScanWindowCodedFast = 0x0018; /* 15 ms = 24 *0.625 */ -constexpr uint16_t kScanIntervalSlow = 0x0800; /* 1.28 s = 2048 *0.625 */ -constexpr uint16_t kScanWindowSlow = 0x0030; /* 30 ms = 48 *0.625 */ +constexpr uint16_t kScanIntervalFast = 0x0060; /* 30 ~ 60 ms (use 60) = 96 *0.625 */ +constexpr uint16_t kScanWindowFast = 0x0030; /* 30 ms = 48 *0.625 */ +constexpr uint16_t kScanWindow2mFast = 0x0018; /* 15 ms = 24 *0.625 */ +constexpr uint16_t kScanWindowCodedFast = 0x0018; /* 15 ms = 24 *0.625 */ +constexpr uint16_t kScanIntervalSlow = 0x0800; /* 1.28 s = 2048 *0.625 */ +constexpr uint16_t kScanWindowSlow = 0x0030; /* 30 ms = 48 *0.625 */ constexpr uint16_t kScanIntervalSystemSuspend = 0x0400; /* 640 ms = 1024 * 0.625 */ constexpr uint16_t kScanWindowSystemSuspend = 0x0012; /* 11.25ms = 18 * 0.625 */ constexpr uint32_t kCreateConnectionTimeoutMs = 30 * 1000; @@ -71,20 +71,28 @@ constexpr bool kEnableBleOnlyInit1mPhy = false; static const std::string kPropertyMinConnInterval = "bluetooth.core.le.min_connection_interval"; static const std::string kPropertyMaxConnInterval = "bluetooth.core.le.max_connection_interval"; static const std::string kPropertyConnLatency = "bluetooth.core.le.connection_latency"; -static const std::string kPropertyConnSupervisionTimeout = "bluetooth.core.le.connection_supervision_timeout"; +static const std::string kPropertyConnSupervisionTimeout = + "bluetooth.core.le.connection_supervision_timeout"; static const std::string kPropertyDirectConnTimeout = "bluetooth.core.le.direct_connection_timeout"; -static const std::string kPropertyConnScanIntervalFast = "bluetooth.core.le.connection_scan_interval_fast"; -static const std::string kPropertyConnScanWindowFast = "bluetooth.core.le.connection_scan_window_fast"; -static const std::string kPropertyConnScanWindow2mFast = "bluetooth.core.le.connection_scan_window_2m_fast"; -static const std::string kPropertyConnScanWindowCodedFast = "bluetooth.core.le.connection_scan_window_coded_fast"; -static const std::string kPropertyConnScanIntervalSlow = "bluetooth.core.le.connection_scan_interval_slow"; -static const std::string kPropertyConnScanWindowSlow = "bluetooth.core.le.connection_scan_window_slow"; +static const std::string kPropertyConnScanIntervalFast = + "bluetooth.core.le.connection_scan_interval_fast"; +static const std::string kPropertyConnScanWindowFast = + "bluetooth.core.le.connection_scan_window_fast"; +static const std::string kPropertyConnScanWindow2mFast = + "bluetooth.core.le.connection_scan_window_2m_fast"; +static const std::string kPropertyConnScanWindowCodedFast = + "bluetooth.core.le.connection_scan_window_coded_fast"; +static const std::string kPropertyConnScanIntervalSlow = + "bluetooth.core.le.connection_scan_interval_slow"; +static const std::string kPropertyConnScanWindowSlow = + "bluetooth.core.le.connection_scan_window_slow"; static const std::string kPropertyConnScanIntervalSystemSuspend = - "bluetooth.core.le.connection_scan_interval_system_suspend"; + "bluetooth.core.le.connection_scan_interval_system_suspend"; static const std::string kPropertyConnScanWindowSystemSuspend = - "bluetooth.core.le.connection_scan_window_system_suspend"; + "bluetooth.core.le.connection_scan_window_system_suspend"; static const std::string kPropertyEnableBlePrivacy = "bluetooth.core.gap.le.privacy.enabled"; -static const std::string kPropertyEnableBleOnlyInit1mPhy = "bluetooth.core.gap.le.conn.only_init_1m_phy.enabled"; +static const std::string kPropertyEnableBleOnlyInit1mPhy = + "bluetooth.core.gap.le.conn.only_init_1m_phy.enabled"; enum class ConnectabilityState { DISARMED = 0, @@ -103,17 +111,13 @@ inline std::string connectability_state_machine_text(const ConnectabilityState& } struct le_acl_connection { - le_acl_connection( - AddressWithType remote_address, - std::unique_ptr pending_connection, - AclConnection::QueueDownEnd* queue_down_end, - os::Handler* handler) + le_acl_connection(AddressWithType remote_address, + std::unique_ptr pending_connection, + AclConnection::QueueDownEnd* queue_down_end, os::Handler* handler) : remote_address_(remote_address), pending_connection_(std::move(pending_connection)), assembler_(new acl_manager::assembler(remote_address, queue_down_end, handler)) {} - ~le_acl_connection() { - delete assembler_; - } + ~le_acl_connection() { delete assembler_; } AddressWithType remote_address_; std::unique_ptr pending_connection_; acl_manager::assembler* assembler_; @@ -121,27 +125,23 @@ struct le_acl_connection { }; struct le_impl : public bluetooth::hci::LeAddressManagerCallback { - le_impl( - HciLayer* hci_layer, - Controller* controller, - os::Handler* handler, - RoundRobinScheduler* round_robin_scheduler, - bool crash_on_unknown_handle) - : hci_layer_(hci_layer), controller_(controller), round_robin_scheduler_(round_robin_scheduler) { + le_impl(HciLayer* hci_layer, Controller* controller, os::Handler* handler, + RoundRobinScheduler* round_robin_scheduler, bool crash_on_unknown_handle) + : hci_layer_(hci_layer), + controller_(controller), + round_robin_scheduler_(round_robin_scheduler) { hci_layer_ = hci_layer; controller_ = controller; handler_ = handler; connections.crash_on_unknown_handle_ = crash_on_unknown_handle; le_acl_connection_interface_ = hci_layer_->GetLeAclConnectionInterface( - handler_->BindOn(this, &le_impl::on_le_event), - handler_->BindOn(this, &le_impl::on_le_disconnect), - handler_->BindOn(this, &le_impl::on_le_read_remote_version_information)); + handler_->BindOn(this, &le_impl::on_le_event), + handler_->BindOn(this, &le_impl::on_le_disconnect), + handler_->BindOn(this, &le_impl::on_le_read_remote_version_information)); le_address_manager_ = new LeAddressManager( - common::Bind(&le_impl::enqueue_command, common::Unretained(this)), - handler_, - controller->GetMacAddress(), - controller->GetLeFilterAcceptListSize(), - controller->GetLeResolvingListSize()); + common::Bind(&le_impl::enqueue_command, common::Unretained(this)), handler_, + controller->GetMacAddress(), controller->GetLeFilterAcceptListSize(), + controller->GetLeResolvingListSize()); } ~le_impl() { @@ -180,15 +180,17 @@ struct le_impl : public bluetooth::hci::LeAddressManagerCallback { } } - private: +private: static constexpr uint16_t kIllegalConnectionHandle = 0xffff; struct { - private: + private: std::map le_acl_connections_; mutable std::mutex le_acl_connections_guard_; LeConnectionManagementCallbacks* find_callbacks(uint16_t handle) { auto connection = le_acl_connections_.find(handle); - if (connection == le_acl_connections_.end()) return nullptr; + if (connection == le_acl_connections_.end()) { + return nullptr; + } return connection->second.le_connection_management_callbacks_; } void remove(uint16_t handle) { @@ -199,7 +201,7 @@ struct le_impl : public bluetooth::hci::LeAddressManagerCallback { } } - public: + public: bool crash_on_unknown_handle_ = false; bool is_empty() const { std::unique_lock lock(le_acl_connections_guard_); @@ -217,45 +219,47 @@ struct le_impl : public bluetooth::hci::LeAddressManagerCallback { std::unique_lock lock(le_acl_connections_guard_); remove(handle); } - void execute( - uint16_t handle, - std::function execute, - bool remove_afterwards = false) { + void execute(uint16_t handle, + std::function execute, + bool remove_afterwards = false) { std::unique_lock lock(le_acl_connections_guard_); auto callbacks = find_callbacks(handle); - if (callbacks != nullptr) + if (callbacks != nullptr) { execute(callbacks); - else - log::assert_that( - !crash_on_unknown_handle_, "Received command for unknown handle:0x{:x}", handle); - if (remove_afterwards) remove(handle); + } else { + log::assert_that(!crash_on_unknown_handle_, "Received command for unknown handle:0x{:x}", + handle); + } + if (remove_afterwards) { + remove(handle); + } } - bool send_packet_upward(uint16_t handle, std::function cb) { + bool send_packet_upward(uint16_t handle, + std::function cb) { std::unique_lock lock(le_acl_connections_guard_); auto connection = le_acl_connections_.find(handle); - if (connection != le_acl_connections_.end()) cb(connection->second.assembler_); + if (connection != le_acl_connections_.end()) { + cb(connection->second.assembler_); + } return connection != le_acl_connections_.end(); } - void add( - uint16_t handle, - const AddressWithType& remote_address, - std::unique_ptr pending_connection, - AclConnection::QueueDownEnd* queue_end, - os::Handler* handler, - LeConnectionManagementCallbacks* le_connection_management_callbacks) { + void add(uint16_t handle, const AddressWithType& remote_address, + std::unique_ptr pending_connection, + AclConnection::QueueDownEnd* queue_end, os::Handler* handler, + LeConnectionManagementCallbacks* le_connection_management_callbacks) { std::unique_lock lock(le_acl_connections_guard_); auto emplace_pair = le_acl_connections_.emplace( - std::piecewise_construct, - std::forward_as_tuple(handle), - std::forward_as_tuple(remote_address, std::move(pending_connection), queue_end, handler)); - log::assert_that( - emplace_pair.second, - "assert failed: emplace_pair.second"); // Make sure the connection is unique - emplace_pair.first->second.le_connection_management_callbacks_ = le_connection_management_callbacks; + std::piecewise_construct, std::forward_as_tuple(handle), + std::forward_as_tuple(remote_address, std::move(pending_connection), queue_end, + handler)); + log::assert_that(emplace_pair.second, + "assert failed: emplace_pair.second"); // Make sure the connection is unique + emplace_pair.first->second.le_connection_management_callbacks_ = + le_connection_management_callbacks; } std::unique_ptr record_peripheral_data_and_extract_pending_connection( - uint16_t handle, DataAsPeripheral data) { + uint16_t handle, DataAsPeripheral data) { std::unique_lock lock(le_acl_connections_guard_); auto connection = le_acl_connections_.find(handle); if (connection != le_acl_connections_.end() && connection->second.pending_connection_.get()) { @@ -297,29 +301,29 @@ struct le_impl : public bluetooth::hci::LeAddressManagerCallback { } connections; - public: +public: void enqueue_command(std::unique_ptr command_packet) { - hci_layer_->EnqueueCommand( - std::move(command_packet), - handler_->BindOnce(&LeAddressManager::OnCommandComplete, common::Unretained(le_address_manager_))); + hci_layer_->EnqueueCommand(std::move(command_packet), + handler_->BindOnce(&LeAddressManager::OnCommandComplete, + common::Unretained(le_address_manager_))); } - bool send_packet_upward(uint16_t handle, std::function cb) { + bool send_packet_upward(uint16_t handle, + std::function cb) { return connections.send_packet_upward(handle, cb); } void report_le_connection_failure(AddressWithType address, ErrorCode status) { - le_client_handler_->Post(common::BindOnce( - &LeConnectionCallbacks::OnLeConnectFail, - common::Unretained(le_client_callbacks_), - address, - status)); + le_client_handler_->Post(common::BindOnce(&LeConnectionCallbacks::OnLeConnectFail, + common::Unretained(le_client_callbacks_), address, + status)); if (le_acceptlist_callbacks_ != nullptr) { le_acceptlist_callbacks_->OnLeConnectFail(address, status); } } - // connection canceled by LeAddressManager.OnPause(), will auto reconnect by LeAddressManager.OnResume() + // connection canceled by LeAddressManager.OnPause(), will auto reconnect by + // LeAddressManager.OnResume() void on_le_connection_canceled_on_pause() { log::assert_that(pause_connection, "Connection must be paused to ack the le address manager"); arm_on_resume_ = true; @@ -347,8 +351,8 @@ struct le_impl : public bluetooth::hci::LeAddressManagerCallback { if (packet.GetSubeventCode() == SubeventCode::CONNECTION_COMPLETE) { LeConnectionCompleteView connection_complete = LeConnectionCompleteView::Create(packet); - log::assert_that( - connection_complete.IsValid(), "assert failed: connection_complete.IsValid()"); + log::assert_that(connection_complete.IsValid(), + "assert failed: connection_complete.IsValid()"); status = connection_complete.GetStatus(); address = connection_complete.GetPeerAddress(); peer_address_type = connection_complete.GetPeerAddressType(); @@ -360,9 +364,9 @@ struct le_impl : public bluetooth::hci::LeAddressManagerCallback { remote_address = AddressWithType(address, peer_address_type); } else if (packet.GetSubeventCode() == SubeventCode::ENHANCED_CONNECTION_COMPLETE) { LeEnhancedConnectionCompleteView connection_complete = - LeEnhancedConnectionCompleteView::Create(packet); - log::assert_that( - connection_complete.IsValid(), "assert failed: connection_complete.IsValid()"); + LeEnhancedConnectionCompleteView::Create(packet); + log::assert_that(connection_complete.IsValid(), + "assert failed: connection_complete.IsValid()"); status = connection_complete.GetStatus(); address = connection_complete.GetPeerAddress(); peer_address_type = connection_complete.GetPeerAddressType(); @@ -417,7 +421,8 @@ struct le_impl : public bluetooth::hci::LeAddressManagerCallback { if (!accept_list.empty()) { AddressWithType empty(Address::kEmpty, AddressType::RANDOM_DEVICE_ADDRESS); - handler_->Post(common::BindOnce(&le_impl::create_le_connection, common::Unretained(this), empty, false, false)); + handler_->Post(common::BindOnce(&le_impl::create_le_connection, common::Unretained(this), + empty, false, false)); } if (le_client_handler_ == nullptr) { @@ -444,14 +449,15 @@ struct le_impl : public bluetooth::hci::LeAddressManagerCallback { } if (in_filter_accept_list) { - log::info( - "Received incoming connection of device in filter accept_list, {}", remote_address); + log::info("Received incoming connection of device in filter accept_list, {}", + remote_address); direct_connect_remove(remote_address); remove_device_from_accept_list(remote_address); } } - if (!check_connection_parameters(conn_interval, conn_interval, conn_latency, supervision_timeout)) { + if (!check_connection_parameters(conn_interval, conn_interval, conn_latency, + supervision_timeout)) { log::error("Receive connection complete with invalid connection parameters"); return; } @@ -459,12 +465,9 @@ struct le_impl : public bluetooth::hci::LeAddressManagerCallback { auto queue = std::make_shared(10); auto queue_down_end = queue->GetDownEnd(); round_robin_scheduler_->Register(RoundRobinScheduler::ConnectionType::LE, handle, queue); - std::unique_ptr connection(new LeAclConnection( - std::move(queue), - le_acl_connection_interface_, - handle, - role_specific_data, - remote_address)); + std::unique_ptr connection( + new LeAclConnection(std::move(queue), le_acl_connection_interface_, handle, + role_specific_data, remote_address)); connection->peer_address_with_type_ = AddressWithType(address, peer_address_type); connection->interval_ = conn_interval; connection->latency_ = conn_latency; @@ -474,37 +477,30 @@ struct le_impl : public bluetooth::hci::LeAddressManagerCallback { if (packet.GetSubeventCode() == SubeventCode::ENHANCED_CONNECTION_COMPLETE) { LeEnhancedConnectionCompleteView connection_complete = - LeEnhancedConnectionCompleteView::Create(packet); - log::assert_that( - connection_complete.IsValid(), "assert failed: connection_complete.IsValid()"); + LeEnhancedConnectionCompleteView::Create(packet); + log::assert_that(connection_complete.IsValid(), + "assert failed: connection_complete.IsValid()"); connection->local_resolvable_private_address_ = - connection_complete.GetLocalResolvablePrivateAddress(); + connection_complete.GetLocalResolvablePrivateAddress(); connection->peer_resolvable_private_address_ = - connection_complete.GetPeerResolvablePrivateAddress(); + connection_complete.GetPeerResolvablePrivateAddress(); } auto connection_callbacks = connection->GetEventCallbacks( - [this](uint16_t handle) { this->connections.invalidate(handle); }); + [this](uint16_t handle) { this->connections.invalidate(handle); }); if (std::holds_alternative(role_specific_data)) { // the OnLeConnectSuccess event will be sent after receiving the On Advertising Set Terminated // event, since we need it to know what local_address / advertising set the peer connected to. // In the meantime, we store it as a pending_connection. - connections.add( - handle, - remote_address, - std::move(connection), - queue_down_end, - handler_, - connection_callbacks); + connections.add(handle, remote_address, std::move(connection), queue_down_end, handler_, + connection_callbacks); } else { - connections.add( - handle, remote_address, nullptr, queue_down_end, handler_, connection_callbacks); - le_client_handler_->Post(common::BindOnce( - &LeConnectionCallbacks::OnLeConnectSuccess, - common::Unretained(le_client_callbacks_), - remote_address, - std::move(connection))); + connections.add(handle, remote_address, nullptr, queue_down_end, handler_, + connection_callbacks); + le_client_handler_->Post(common::BindOnce(&LeConnectionCallbacks::OnLeConnectSuccess, + common::Unretained(le_client_callbacks_), + remote_address, std::move(connection))); if (le_acceptlist_callbacks_ != nullptr) { le_acceptlist_callbacks_->OnLeConnectSuccess(remote_address); } @@ -514,9 +510,8 @@ struct le_impl : public bluetooth::hci::LeAddressManagerCallback { RoleSpecificData initialize_role_specific_data(Role role) { if (role == hci::Role::CENTRAL) { return DataAsCentral{le_address_manager_->GetInitiatorAddress()}; - } else if ( - controller_->SupportsBleExtendedAdvertising() || - controller_->IsSupported(hci::OpCode::LE_MULTI_ADVT)) { + } else if (controller_->SupportsBleExtendedAdvertising() || + controller_->IsSupported(hci::OpCode::LE_MULTI_ADVT)) { // when accepting connection, we must obtain the address from the advertiser. // When we receive "set terminated event", we associate connection handle with advertiser // address @@ -525,9 +520,9 @@ struct le_impl : public bluetooth::hci::LeAddressManagerCallback { // the exception is if we only support legacy advertising - here, our current address is also // our advertised address return DataAsPeripheral{ - le_address_manager_->GetInitiatorAddress(), - {}, - true /* For now, ignore non-discoverable legacy advertising TODO(b/254314964) */}; + le_address_manager_->GetInitiatorAddress(), + {}, + true /* For now, ignore non-discoverable legacy advertising TODO(b/254314964) */}; } } @@ -537,12 +532,12 @@ struct le_impl : public bluetooth::hci::LeAddressManagerCallback { bool event_also_routes_to_other_receivers = connections.crash_on_unknown_handle_; connections.crash_on_unknown_handle_ = false; connections.execute( - handle, - [=, this](LeConnectionManagementCallbacks* callbacks) { - round_robin_scheduler_->Unregister(handle); - callbacks->OnDisconnection(reason); - }, - kRemoveConnectionAfterwards); + handle, + [=, this](LeConnectionManagementCallbacks* callbacks) { + round_robin_scheduler_->Unregister(handle); + callbacks->OnDisconnection(reason); + }, + kRemoveConnectionAfterwards); if (le_acceptlist_callbacks_ != nullptr) { le_acceptlist_callbacks_->OnLeDisconnection(remote_address); } @@ -563,11 +558,9 @@ struct le_impl : public bluetooth::hci::LeAddressManagerCallback { } auto handle = complete_view.GetConnectionHandle(); connections.execute(handle, [=](LeConnectionManagementCallbacks* callbacks) { - callbacks->OnConnectionUpdate( - complete_view.GetStatus(), - complete_view.GetConnInterval(), - complete_view.GetConnLatency(), - complete_view.GetSupervisionTimeout()); + callbacks->OnConnectionUpdate(complete_view.GetStatus(), complete_view.GetConnInterval(), + complete_view.GetConnLatency(), + complete_view.GetSupervisionTimeout()); }); } @@ -579,14 +572,17 @@ struct le_impl : public bluetooth::hci::LeAddressManagerCallback { } auto handle = complete_view.GetConnectionHandle(); connections.execute(handle, [=](LeConnectionManagementCallbacks* callbacks) { - callbacks->OnPhyUpdate(complete_view.GetStatus(), complete_view.GetTxPhy(), complete_view.GetRxPhy()); + callbacks->OnPhyUpdate(complete_view.GetStatus(), complete_view.GetTxPhy(), + complete_view.GetRxPhy()); }); } - void on_le_read_remote_version_information( - hci::ErrorCode hci_status, uint16_t handle, uint8_t version, uint16_t manufacturer_name, uint16_t sub_version) { + void on_le_read_remote_version_information(hci::ErrorCode hci_status, uint16_t handle, + uint8_t version, uint16_t manufacturer_name, + uint16_t sub_version) { connections.execute(handle, [=](LeConnectionManagementCallbacks* callbacks) { - callbacks->OnReadRemoteVersionInformationComplete(hci_status, version, manufacturer_name, sub_version); + callbacks->OnReadRemoteVersionInformationComplete(hci_status, version, manufacturer_name, + sub_version); }); } @@ -599,10 +595,8 @@ struct le_impl : public bluetooth::hci::LeAddressManagerCallback { auto handle = data_length_view.GetConnectionHandle(); connections.execute(handle, [=](LeConnectionManagementCallbacks* callbacks) { callbacks->OnDataLengthChange( - data_length_view.GetMaxTxOctets(), - data_length_view.GetMaxTxTime(), - data_length_view.GetMaxRxOctets(), - data_length_view.GetMaxRxTime()); + data_length_view.GetMaxTxOctets(), data_length_view.GetMaxTxTime(), + data_length_view.GetMaxRxOctets(), data_length_view.GetMaxRxTime()); }); } @@ -613,15 +607,12 @@ struct le_impl : public bluetooth::hci::LeAddressManagerCallback { return; } - connections.execute( - request_view.GetConnectionHandle(), - [request_view](LeConnectionManagementCallbacks* callbacks) { - callbacks->OnParameterUpdateRequest( - request_view.GetIntervalMin(), - request_view.GetIntervalMax(), - request_view.GetLatency(), - request_view.GetTimeout()); - }); + connections.execute(request_view.GetConnectionHandle(), + [request_view](LeConnectionManagementCallbacks* callbacks) { + callbacks->OnParameterUpdateRequest( + request_view.GetIntervalMin(), request_view.GetIntervalMax(), + request_view.GetLatency(), request_view.GetTimeout()); + }); } void on_le_subrate_change(LeMetaEventView view) { @@ -632,58 +623,53 @@ struct le_impl : public bluetooth::hci::LeAddressManagerCallback { } auto handle = subrate_change_view.GetConnectionHandle(); connections.execute(handle, [=](LeConnectionManagementCallbacks* callbacks) { - callbacks->OnLeSubrateChange( - subrate_change_view.GetStatus(), - subrate_change_view.GetSubrateFactor(), - subrate_change_view.GetPeripheralLatency(), - subrate_change_view.GetContinuationNumber(), - subrate_change_view.GetSupervisionTimeout()); + callbacks->OnLeSubrateChange(subrate_change_view.GetStatus(), + subrate_change_view.GetSubrateFactor(), + subrate_change_view.GetPeripheralLatency(), + subrate_change_view.GetContinuationNumber(), + subrate_change_view.GetSupervisionTimeout()); }); } - uint16_t HACK_get_handle(Address address) { - return connections.HACK_get_handle(address); - } + uint16_t HACK_get_handle(Address address) { return connections.HACK_get_handle(address); } Address HACK_get_address(uint16_t connection_handle) { return connections.getAddressWithType(connection_handle).GetAddress(); } - void OnAdvertisingSetTerminated( - uint16_t conn_handle, - uint8_t adv_set_id, - hci::AddressWithType adv_set_address, - bool is_discoverable) { + void OnAdvertisingSetTerminated(uint16_t conn_handle, uint8_t adv_set_id, + hci::AddressWithType adv_set_address, bool is_discoverable) { auto connection = connections.record_peripheral_data_and_extract_pending_connection( - conn_handle, DataAsPeripheral{adv_set_address, adv_set_id, is_discoverable}); + conn_handle, DataAsPeripheral{adv_set_address, adv_set_id, is_discoverable}); if (connection != nullptr) { if (le_acceptlist_callbacks_ != nullptr) { le_acceptlist_callbacks_->OnLeConnectSuccess(connection->GetRemoteAddress()); } le_client_handler_->Post(common::BindOnce( - &LeConnectionCallbacks::OnLeConnectSuccess, - common::Unretained(le_client_callbacks_), - connection->GetRemoteAddress(), - std::move(connection))); + &LeConnectionCallbacks::OnLeConnectSuccess, common::Unretained(le_client_callbacks_), + connection->GetRemoteAddress(), std::move(connection))); } } void direct_connect_add(AddressWithType address_with_type) { direct_connections_.insert(address_with_type); - if (create_connection_timeout_alarms_.find(address_with_type) != create_connection_timeout_alarms_.end()) { + if (create_connection_timeout_alarms_.find(address_with_type) != + create_connection_timeout_alarms_.end()) { return; } auto emplace_result = create_connection_timeout_alarms_.emplace( - std::piecewise_construct, - std::forward_as_tuple(address_with_type.GetAddress(), address_with_type.GetAddressType()), - std::forward_as_tuple(handler_)); + std::piecewise_construct, + std::forward_as_tuple(address_with_type.GetAddress(), + address_with_type.GetAddressType()), + std::forward_as_tuple(handler_)); uint32_t connection_timeout = - os::GetSystemPropertyUint32(kPropertyDirectConnTimeout, kCreateConnectionTimeoutMs); + os::GetSystemPropertyUint32(kPropertyDirectConnTimeout, kCreateConnectionTimeoutMs); emplace_result.first->second.Schedule( - common::BindOnce(&le_impl::on_create_connection_timeout, common::Unretained(this), address_with_type), - std::chrono::milliseconds(connection_timeout)); + common::BindOnce(&le_impl::on_create_connection_timeout, common::Unretained(this), + address_with_type), + std::chrono::milliseconds(connection_timeout)); } void direct_connect_remove(AddressWithType address_with_type) { @@ -709,11 +695,11 @@ struct le_impl : public bluetooth::hci::LeAddressManagerCallback { accept_list.insert(address_with_type); register_with_address_manager(); le_address_manager_->AddDeviceToFilterAcceptList( - address_with_type.ToFilterAcceptListAddressType(), address_with_type.GetAddress()); + address_with_type.ToFilterAcceptListAddressType(), address_with_type.GetAddress()); } bool is_device_in_accept_list(AddressWithType address_with_type) { - return (accept_list.find(address_with_type) != accept_list.end()); + return accept_list.find(address_with_type) != accept_list.end(); } void remove_device_from_accept_list(AddressWithType address_with_type) { @@ -725,7 +711,7 @@ struct le_impl : public bluetooth::hci::LeAddressManagerCallback { connecting_le_.erase(address_with_type); register_with_address_manager(); le_address_manager_->RemoveDeviceFromFilterAcceptList( - address_with_type.ToFilterAcceptListAddressType(), address_with_type.GetAddress()); + address_with_type.ToFilterAcceptListAddressType(), address_with_type.GetAddress()); } void clear_filter_accept_list() { @@ -734,13 +720,13 @@ struct le_impl : public bluetooth::hci::LeAddressManagerCallback { le_address_manager_->ClearFilterAcceptList(); } - void add_device_to_resolving_list( - AddressWithType address_with_type, - const std::array& peer_irk, - const std::array& local_irk) { + void add_device_to_resolving_list(AddressWithType address_with_type, + const std::array& peer_irk, + const std::array& local_irk) { register_with_address_manager(); - le_address_manager_->AddDeviceToResolvingList( - address_with_type.ToPeerAddressType(), address_with_type.GetAddress(), peer_irk, local_irk); + le_address_manager_->AddDeviceToResolvingList(address_with_type.ToPeerAddressType(), + address_with_type.GetAddress(), peer_irk, + local_irk); if (le_acceptlist_callbacks_ != nullptr) { le_acceptlist_callbacks_->OnResolvingListChange(); } @@ -748,8 +734,8 @@ struct le_impl : public bluetooth::hci::LeAddressManagerCallback { void remove_device_from_resolving_list(AddressWithType address_with_type) { register_with_address_manager(); - le_address_manager_->RemoveDeviceFromResolvingList( - address_with_type.ToPeerAddressType(), address_with_type.GetAddress()); + le_address_manager_->RemoveDeviceFromResolvingList(address_with_type.ToPeerAddressType(), + address_with_type.GetAddress()); if (le_acceptlist_callbacks_ != nullptr) { le_acceptlist_callbacks_->OnResolvingListChange(); } @@ -760,21 +746,17 @@ struct le_impl : public bluetooth::hci::LeAddressManagerCallback { case ConnectabilityState::DISARMED: case ConnectabilityState::ARMED: case ConnectabilityState::DISARMING: - log::error( - "Received connectability arm notification for unexpected state:{} status:{}", - connectability_state_machine_text(connectability_state_), - ErrorCodeText(status)); + log::error("Received connectability arm notification for unexpected state:{} status:{}", + connectability_state_machine_text(connectability_state_), ErrorCodeText(status)); break; case ConnectabilityState::ARMING: if (status != ErrorCode::SUCCESS) { log::error("Le connection state machine armed failed status:{}", ErrorCodeText(status)); } - connectability_state_ = - (status == ErrorCode::SUCCESS) ? ConnectabilityState::ARMED : ConnectabilityState::DISARMED; - log::info( - "Le connection state machine armed state:{} status:{}", - connectability_state_machine_text(connectability_state_), - ErrorCodeText(status)); + connectability_state_ = (status == ErrorCode::SUCCESS) ? ConnectabilityState::ARMED + : ConnectabilityState::DISARMED; + log::info("Le connection state machine armed state:{} status:{}", + connectability_state_machine_text(connectability_state_), ErrorCodeText(status)); if (disarmed_while_arming_) { disarmed_while_arming_ = false; disarm_connectability(); @@ -785,67 +767,74 @@ struct le_impl : public bluetooth::hci::LeAddressManagerCallback { void on_extended_create_connection(CommandStatusView status) { log::assert_that(status.IsValid(), "assert failed: status.IsValid()"); log::assert_that( - status.GetCommandOpCode() == OpCode::LE_EXTENDED_CREATE_CONNECTION, - "assert failed: status.GetCommandOpCode() == OpCode::LE_EXTENDED_CREATE_CONNECTION"); + status.GetCommandOpCode() == OpCode::LE_EXTENDED_CREATE_CONNECTION, + "assert failed: status.GetCommandOpCode() == OpCode::LE_EXTENDED_CREATE_CONNECTION"); update_connectability_state_after_armed(status.GetStatus()); } void on_create_connection(CommandStatusView status) { log::assert_that(status.IsValid(), "assert failed: status.IsValid()"); - log::assert_that( - status.GetCommandOpCode() == OpCode::LE_CREATE_CONNECTION, - "assert failed: status.GetCommandOpCode() == OpCode::LE_CREATE_CONNECTION"); + log::assert_that(status.GetCommandOpCode() == OpCode::LE_CREATE_CONNECTION, + "assert failed: status.GetCommandOpCode() == OpCode::LE_CREATE_CONNECTION"); update_connectability_state_after_armed(status.GetStatus()); } void arm_connectability() { if (connectability_state_ != ConnectabilityState::DISARMED) { - log::error( - "Attempting to re-arm le connection state machine in unexpected state:{}", - connectability_state_machine_text(connectability_state_)); + log::error("Attempting to re-arm le connection state machine in unexpected state:{}", + connectability_state_machine_text(connectability_state_)); return; } if (accept_list.empty()) { log::info( - "Ignored request to re-arm le connection state machine when filter accept list is empty"); + "Ignored request to re-arm le connection state machine when filter accept list is " + "empty"); return; } AddressWithType empty(Address::kEmpty, AddressType::RANDOM_DEVICE_ADDRESS); connectability_state_ = ConnectabilityState::ARMING; connecting_le_ = accept_list; - uint16_t le_scan_interval = os::GetSystemPropertyUint32(kPropertyConnScanIntervalSlow, kScanIntervalSlow); - uint16_t le_scan_window = os::GetSystemPropertyUint32(kPropertyConnScanWindowSlow, kScanWindowSlow); + uint16_t le_scan_interval = + os::GetSystemPropertyUint32(kPropertyConnScanIntervalSlow, kScanIntervalSlow); + uint16_t le_scan_window = + os::GetSystemPropertyUint32(kPropertyConnScanWindowSlow, kScanWindowSlow); uint16_t le_scan_window_2m = le_scan_window; uint16_t le_scan_window_coded = le_scan_window; // If there is any direct connection in the connection list, use the fast parameter if (!direct_connections_.empty()) { - le_scan_interval = os::GetSystemPropertyUint32(kPropertyConnScanIntervalFast, kScanIntervalFast); + le_scan_interval = + os::GetSystemPropertyUint32(kPropertyConnScanIntervalFast, kScanIntervalFast); le_scan_window = os::GetSystemPropertyUint32(kPropertyConnScanWindowFast, kScanWindowFast); - le_scan_window_2m = os::GetSystemPropertyUint32(kPropertyConnScanWindow2mFast, kScanWindow2mFast); - le_scan_window_coded = os::GetSystemPropertyUint32(kPropertyConnScanWindowCodedFast, kScanWindowCodedFast); + le_scan_window_2m = + os::GetSystemPropertyUint32(kPropertyConnScanWindow2mFast, kScanWindow2mFast); + le_scan_window_coded = + os::GetSystemPropertyUint32(kPropertyConnScanWindowCodedFast, kScanWindowCodedFast); } // Use specific parameters when in system suspend. if (system_suspend_) { - le_scan_interval = os::GetSystemPropertyUint32( - kPropertyConnScanIntervalSystemSuspend, kScanIntervalSystemSuspend); - le_scan_window = os::GetSystemPropertyUint32( - kPropertyConnScanWindowSystemSuspend, kScanWindowSystemSuspend); + le_scan_interval = os::GetSystemPropertyUint32(kPropertyConnScanIntervalSystemSuspend, + kScanIntervalSystemSuspend); + le_scan_window = os::GetSystemPropertyUint32(kPropertyConnScanWindowSystemSuspend, + kScanWindowSystemSuspend); le_scan_window_2m = le_scan_window; le_scan_window_coded = le_scan_window; } InitiatorFilterPolicy initiator_filter_policy = InitiatorFilterPolicy::USE_FILTER_ACCEPT_LIST; - OwnAddressType own_address_type = - static_cast(le_address_manager_->GetInitiatorAddress().GetAddressType()); - uint16_t conn_interval_min = os::GetSystemPropertyUint32(kPropertyMinConnInterval, kConnIntervalMin); - uint16_t conn_interval_max = os::GetSystemPropertyUint32(kPropertyMaxConnInterval, kConnIntervalMax); + OwnAddressType own_address_type = static_cast( + le_address_manager_->GetInitiatorAddress().GetAddressType()); + uint16_t conn_interval_min = + os::GetSystemPropertyUint32(kPropertyMinConnInterval, kConnIntervalMin); + uint16_t conn_interval_max = + os::GetSystemPropertyUint32(kPropertyMaxConnInterval, kConnIntervalMax); uint16_t conn_latency = os::GetSystemPropertyUint32(kPropertyConnLatency, kConnLatency); - uint16_t supervision_timeout = os::GetSystemPropertyUint32(kPropertyConnSupervisionTimeout, kSupervisionTimeout); + uint16_t supervision_timeout = + os::GetSystemPropertyUint32(kPropertyConnSupervisionTimeout, kSupervisionTimeout); log::assert_that( - check_connection_parameters( - conn_interval_min, conn_interval_max, conn_latency, supervision_timeout), - "assert failed: check_connection_parameters(conn_interval_min, conn_interval_max, " - "conn_latency, supervision_timeout)"); + check_connection_parameters(conn_interval_min, conn_interval_max, conn_latency, + supervision_timeout), + "assert failed: check_connection_parameters(conn_interval_min, conn_interval_max, " + "conn_latency, supervision_timeout)"); AddressWithType address_with_type = connection_peer_address_with_type_; if (initiator_filter_policy == InitiatorFilterPolicy::USE_FILTER_ACCEPT_LIST) { @@ -853,7 +842,8 @@ struct le_impl : public bluetooth::hci::LeAddressManagerCallback { } if (controller_->IsSupported(OpCode::LE_EXTENDED_CREATE_CONNECTION)) { - bool only_init_1m_phy = os::GetSystemPropertyBool(kPropertyEnableBleOnlyInit1mPhy, kEnableBleOnlyInit1mPhy); + bool only_init_1m_phy = + os::GetSystemPropertyBool(kPropertyEnableBleOnlyInit1mPhy, kEnableBleOnlyInit1mPhy); uint8_t initiating_phys = PHY_LE_1M; std::vector parameters = {}; @@ -896,42 +886,31 @@ struct le_impl : public bluetooth::hci::LeAddressManagerCallback { } le_acl_connection_interface_->EnqueueCommand( - LeExtendedCreateConnectionBuilder::Create( - initiator_filter_policy, - own_address_type, - address_with_type.GetAddressType(), - address_with_type.GetAddress(), - initiating_phys, - parameters), - handler_->BindOnce(&le_impl::on_extended_create_connection, common::Unretained(this))); + LeExtendedCreateConnectionBuilder::Create( + initiator_filter_policy, own_address_type, address_with_type.GetAddressType(), + address_with_type.GetAddress(), initiating_phys, parameters), + handler_->BindOnce(&le_impl::on_extended_create_connection, + common::Unretained(this))); } else { le_acl_connection_interface_->EnqueueCommand( - LeCreateConnectionBuilder::Create( - le_scan_interval, - le_scan_window, - initiator_filter_policy, - address_with_type.GetAddressType(), - address_with_type.GetAddress(), - own_address_type, - conn_interval_min, - conn_interval_max, - conn_latency, - supervision_timeout, - 0x00, - 0x00), - handler_->BindOnce(&le_impl::on_create_connection, common::Unretained(this))); + LeCreateConnectionBuilder::Create( + le_scan_interval, le_scan_window, initiator_filter_policy, + address_with_type.GetAddressType(), address_with_type.GetAddress(), + own_address_type, conn_interval_min, conn_interval_max, conn_latency, + supervision_timeout, 0x00, 0x00), + handler_->BindOnce(&le_impl::on_create_connection, common::Unretained(this))); } } void disarm_connectability() { - switch (connectability_state_) { case ConnectabilityState::ARMED: log::info("Disarming LE connection state machine with create connection cancel"); connectability_state_ = ConnectabilityState::DISARMING; le_acl_connection_interface_->EnqueueCommand( - LeCreateConnectionCancelBuilder::Create(), - handler_->BindOnce(&le_impl::on_create_connection_cancel_complete, common::Unretained(this))); + LeCreateConnectionCancelBuilder::Create(), + handler_->BindOnce(&le_impl::on_create_connection_cancel_complete, + common::Unretained(this))); break; case ConnectabilityState::ARMING: @@ -940,14 +919,14 @@ struct le_impl : public bluetooth::hci::LeAddressManagerCallback { break; case ConnectabilityState::DISARMING: case ConnectabilityState::DISARMED: - log::error( - "Attempting to disarm le connection state machine in unexpected state:{}", - connectability_state_machine_text(connectability_state_)); + log::error("Attempting to disarm le connection state machine in unexpected state:{}", + connectability_state_machine_text(connectability_state_)); break; } } - void create_le_connection(AddressWithType address_with_type, bool add_to_accept_list, bool is_direct) { + void create_le_connection(AddressWithType address_with_type, bool add_to_accept_list, + bool is_direct) { if (le_client_callbacks_ == nullptr) { log::error("No callbacks to call"); return; @@ -995,9 +974,8 @@ struct le_impl : public bluetooth::hci::LeAddressManagerCallback { } else { // Ignored, if we add new device to the filter accept list, create connection command will // be sent by OnResume. - log::debug( - "Deferred until filter accept list updated create connection state {}", - connectability_state_machine_text(connectability_state_)); + log::debug("Deferred until filter accept list updated create connection state {}", + connectability_state_machine_text(connectability_state_)); } break; default: @@ -1023,10 +1001,8 @@ struct le_impl : public bluetooth::hci::LeAddressManagerCallback { remove_device_from_accept_list(address_with_type); } le_client_handler_->Post(common::BindOnce( - &LeConnectionCallbacks::OnLeConnectFail, - common::Unretained(le_client_callbacks_), - address_with_type, - ErrorCode::CONNECTION_ACCEPT_TIMEOUT)); + &LeConnectionCallbacks::OnLeConnectFail, common::Unretained(le_client_callbacks_), + address_with_type, ErrorCode::CONNECTION_ACCEPT_TIMEOUT)); } void cancel_connect(AddressWithType address_with_type) { @@ -1038,85 +1014,78 @@ struct le_impl : public bluetooth::hci::LeAddressManagerCallback { void set_le_suggested_default_data_parameters(uint16_t length, uint16_t time) { auto packet = LeWriteSuggestedDefaultDataLengthBuilder::Create(length, time); le_acl_connection_interface_->EnqueueCommand( - std::move(packet), handler_->BindOnce([](CommandCompleteView /* complete */) {})); + std::move(packet), handler_->BindOnce([](CommandCompleteView /* complete */) {})); } - void LeSetDefaultSubrate( - uint16_t subrate_min, uint16_t subrate_max, uint16_t max_latency, uint16_t cont_num, uint16_t sup_tout) { + void LeSetDefaultSubrate(uint16_t subrate_min, uint16_t subrate_max, uint16_t max_latency, + uint16_t cont_num, uint16_t sup_tout) { le_acl_connection_interface_->EnqueueCommand( - LeSetDefaultSubrateBuilder::Create(subrate_min, subrate_max, max_latency, cont_num, sup_tout), - handler_->BindOnce([](CommandCompleteView complete) { - auto complete_view = LeSetDefaultSubrateCompleteView::Create(complete); - log::assert_that(complete_view.IsValid(), "assert failed: complete_view.IsValid()"); - ErrorCode status = complete_view.GetStatus(); - log::assert_that(status == ErrorCode::SUCCESS, "Status = {}", ErrorCodeText(status)); - })); + LeSetDefaultSubrateBuilder::Create(subrate_min, subrate_max, max_latency, cont_num, + sup_tout), + handler_->BindOnce([](CommandCompleteView complete) { + auto complete_view = LeSetDefaultSubrateCompleteView::Create(complete); + log::assert_that(complete_view.IsValid(), "assert failed: complete_view.IsValid()"); + ErrorCode status = complete_view.GetStatus(); + log::assert_that(status == ErrorCode::SUCCESS, "Status = {}", ErrorCodeText(status)); + })); } - void clear_resolving_list() { - le_address_manager_->ClearResolvingList(); - } + void clear_resolving_list() { le_address_manager_->ClearResolvingList(); } - void set_privacy_policy_for_initiator_address( - LeAddressManager::AddressPolicy address_policy, - AddressWithType fixed_address, - Octet16 rotation_irk, - std::chrono::milliseconds minimum_rotation_time, - std::chrono::milliseconds maximum_rotation_time) { + void set_privacy_policy_for_initiator_address(LeAddressManager::AddressPolicy address_policy, + AddressWithType fixed_address, Octet16 rotation_irk, + std::chrono::milliseconds minimum_rotation_time, + std::chrono::milliseconds maximum_rotation_time) { le_address_manager_->SetPrivacyPolicyForInitiatorAddress( - address_policy, - fixed_address, - rotation_irk, - controller_->SupportsBlePrivacy() && os::GetSystemPropertyBool(kPropertyEnableBlePrivacy, kEnableBlePrivacy), - minimum_rotation_time, - maximum_rotation_time); + address_policy, fixed_address, rotation_irk, + controller_->SupportsBlePrivacy() && + os::GetSystemPropertyBool(kPropertyEnableBlePrivacy, kEnableBlePrivacy), + minimum_rotation_time, maximum_rotation_time); } // TODO(jpawlowski): remove once we have config file abstraction in cert tests void set_privacy_policy_for_initiator_address_for_test( - LeAddressManager::AddressPolicy address_policy, - AddressWithType fixed_address, - Octet16 rotation_irk, - std::chrono::milliseconds minimum_rotation_time, - std::chrono::milliseconds maximum_rotation_time) { + LeAddressManager::AddressPolicy address_policy, AddressWithType fixed_address, + Octet16 rotation_irk, std::chrono::milliseconds minimum_rotation_time, + std::chrono::milliseconds maximum_rotation_time) { le_address_manager_->SetPrivacyPolicyForInitiatorAddressForTest( - address_policy, fixed_address, rotation_irk, minimum_rotation_time, maximum_rotation_time); + address_policy, fixed_address, rotation_irk, minimum_rotation_time, + maximum_rotation_time); } void handle_register_le_callbacks(LeConnectionCallbacks* callbacks, os::Handler* handler) { - log::assert_that( - le_client_callbacks_ == nullptr, "assert failed: le_client_callbacks_ == nullptr"); + log::assert_that(le_client_callbacks_ == nullptr, + "assert failed: le_client_callbacks_ == nullptr"); log::assert_that(le_client_handler_ == nullptr, "assert failed: le_client_handler_ == nullptr"); le_client_callbacks_ = callbacks; le_client_handler_ = handler; } void handle_register_le_acceptlist_callbacks(LeAcceptlistCallbacks* callbacks) { - log::assert_that( - le_acceptlist_callbacks_ == nullptr, "assert failed: le_acceptlist_callbacks_ == nullptr"); + log::assert_that(le_acceptlist_callbacks_ == nullptr, + "assert failed: le_acceptlist_callbacks_ == nullptr"); le_acceptlist_callbacks_ = callbacks; } - void handle_unregister_le_callbacks(LeConnectionCallbacks* callbacks, std::promise promise) { - log::assert_that( - le_client_callbacks_ == callbacks, - "Registered le callback entity is different then unregister request"); + void handle_unregister_le_callbacks(LeConnectionCallbacks* callbacks, + std::promise promise) { + log::assert_that(le_client_callbacks_ == callbacks, + "Registered le callback entity is different then unregister request"); le_client_callbacks_ = nullptr; le_client_handler_ = nullptr; promise.set_value(); } - void handle_unregister_le_acceptlist_callbacks( - LeAcceptlistCallbacks* callbacks, std::promise promise) { - log::assert_that( - le_acceptlist_callbacks_ == callbacks, - "Registered le callback entity is different then unregister request"); + void handle_unregister_le_acceptlist_callbacks(LeAcceptlistCallbacks* callbacks, + std::promise promise) { + log::assert_that(le_acceptlist_callbacks_ == callbacks, + "Registered le callback entity is different then unregister request"); le_acceptlist_callbacks_ = nullptr; promise.set_value(); } - bool check_connection_parameters( - uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout) { + bool check_connection_parameters(uint16_t conn_interval_min, uint16_t conn_interval_max, + uint16_t conn_latency, uint16_t supervision_timeout) { if (conn_interval_min < 0x0006 || conn_interval_min > 0x0C80 || conn_interval_max < 0x0006 || conn_interval_max > 0x0C80 || conn_latency > 0x01F3 || supervision_timeout < 0x000A || supervision_timeout > 0x0C80) { @@ -1126,10 +1095,11 @@ struct le_impl : public bluetooth::hci::LeAddressManagerCallback { // The Maximum interval in milliseconds will be conn_interval_max * 1.25 ms // The Timeout in milliseconds will be expected_supervision_timeout * 10 ms - // The Timeout in milliseconds shall be larger than (1 + Latency) * Interval_Max * 2, where Interval_Max is given in - // milliseconds. + // The Timeout in milliseconds shall be larger than (1 + Latency) * Interval_Max * 2, where + // Interval_Max is given in milliseconds. uint32_t supervision_timeout_min = (uint32_t)(1 + conn_latency) * conn_interval_max * 2 + 1; - if (supervision_timeout * 8 < supervision_timeout_min || conn_interval_max < conn_interval_min) { + if (supervision_timeout * 8 < supervision_timeout_min || + conn_interval_max < conn_interval_min) { log::error("Invalid parameter"); return false; } @@ -1145,8 +1115,10 @@ struct le_impl : public bluetooth::hci::LeAddressManagerCallback { background_connections_.erase(address_with_type); } - void is_on_background_connection_list(AddressWithType address_with_type, std::promise promise) { - promise.set_value(background_connections_.find(address_with_type) != background_connections_.end()); + void is_on_background_connection_list(AddressWithType address_with_type, + std::promise promise) { + promise.set_value(background_connections_.find(address_with_type) != + background_connections_.end()); } void OnPause() override { // bluetooth::hci::LeAddressManagerCallback @@ -1191,9 +1163,8 @@ struct le_impl : public bluetooth::hci::LeAddressManagerCallback { } } if (connectability_state_ != ConnectabilityState::DISARMING) { - log::error( - "Attempting to disarm le connection state machine in unexpected state:{}", - connectability_state_machine_text(connectability_state_)); + log::error("Attempting to disarm le connection state machine in unexpected state:{}", + connectability_state_machine_text(connectability_state_)); } } @@ -1206,7 +1177,8 @@ struct le_impl : public bluetooth::hci::LeAddressManagerCallback { } void check_for_unregister() { - if (connections.is_empty() && connecting_le_.empty() && address_manager_registered && ready_to_unregister) { + if (connections.is_empty() && connecting_le_.empty() && address_manager_registered && + ready_to_unregister) { le_address_manager_->Unregister(this); address_manager_registered = false; pause_connection = false; @@ -1214,9 +1186,7 @@ struct le_impl : public bluetooth::hci::LeAddressManagerCallback { } } - void set_system_suspend_state(bool suspended) { - system_suspend_ = suspended; - } + void set_system_suspend_state(bool suspended) { system_suspend_ = suspended; } HciLayer* hci_layer_ = nullptr; Controller* controller_ = nullptr; diff --git a/system/gd/hci/acl_manager/le_impl_test.cc b/system/gd/hci/acl_manager/le_impl_test.cc index 13ecbea9ab2..1e3fd4cebca 100644 --- a/system/gd/hci/acl_manager/le_impl_test.cc +++ b/system/gd/hci/acl_manager/le_impl_test.cc @@ -78,40 +78,40 @@ constexpr uint16_t kTime = 0x1234; constexpr uint16_t kTimeout = 0x80; constexpr uint16_t kContinuationNumber = 0x32; constexpr std::array kPeerIdentityResolvingKey({ - 0x00, - 0x01, - 0x02, - 0x03, - 0x04, - 0x05, - 0x06, - 0x07, - 0x08, - 0x09, - 0x0a, - 0x0b, - 0x0c, - 0x0d, - 0x0e, - 0x0f, + 0x00, + 0x01, + 0x02, + 0x03, + 0x04, + 0x05, + 0x06, + 0x07, + 0x08, + 0x09, + 0x0a, + 0x0b, + 0x0c, + 0x0d, + 0x0e, + 0x0f, }); constexpr std::array kLocalIdentityResolvingKey({ - 0x80, - 0x81, - 0x82, - 0x83, - 0x84, - 0x85, - 0x86, - 0x87, - 0x88, - 0x89, - 0x8a, - 0x8b, - 0x8c, - 0x8d, - 0x8e, - 0x8f, + 0x80, + 0x81, + 0x82, + 0x83, + 0x84, + 0x85, + 0x86, + 0x87, + 0x88, + 0x89, + 0x8a, + 0x8b, + 0x8c, + 0x8d, + 0x8e, + 0x8f, }); template @@ -139,22 +139,26 @@ T CreateLeSecurityCommandView(hci::CommandView command) { template T CreateLeEventView(std::shared_ptr> bytes) { - return T::Create(hci::LeMetaEventView::Create(hci::EventView::Create(hci::PacketView(bytes)))); + return T::Create(hci::LeMetaEventView::Create( + hci::EventView::Create(hci::PacketView(bytes)))); } hci::CommandCompleteView ReturnCommandComplete(hci::OpCode op_code, hci::ErrorCode error_code) { std::vector success_vector{static_cast(error_code)}; - auto builder = hci::CommandCompleteBuilder::Create(uint8_t{1}, op_code, std::make_unique(success_vector)); + auto builder = hci::CommandCompleteBuilder::Create(uint8_t{1}, op_code, + std::make_unique(success_vector)); auto bytes = Serialize(std::move(builder)); - return hci::CommandCompleteView::Create(hci::EventView::Create(hci::PacketView(bytes))); + return hci::CommandCompleteView::Create( + hci::EventView::Create(hci::PacketView(bytes))); } hci::CommandStatusView ReturnCommandStatus(hci::OpCode op_code, hci::ErrorCode error_code) { std::vector success_vector{static_cast(error_code)}; - auto builder = hci::CommandStatusBuilder::Create( - hci::ErrorCode::SUCCESS, uint8_t{1}, op_code, std::make_unique(success_vector)); + auto builder = hci::CommandStatusBuilder::Create(hci::ErrorCode::SUCCESS, uint8_t{1}, op_code, + std::make_unique(success_vector)); auto bytes = Serialize(std::move(builder)); - return hci::CommandStatusView::Create(hci::EventView::Create(hci::PacketView(bytes))); + return hci::CommandStatusView::Create( + hci::EventView::Create(hci::PacketView(bytes))); } } // namespace @@ -166,7 +170,7 @@ namespace acl_manager { namespace { class TestController : public Controller { - public: +public: bool IsSupported(OpCode op_code) const override { log::info("IsSupported"); return supported_opcodes_.count(op_code) == 1; @@ -177,13 +181,9 @@ class TestController : public Controller { supported_opcodes_.insert(op_code); } - uint16_t GetNumAclPacketBuffers() const { - return max_acl_packet_credits_; - } + uint16_t GetNumAclPacketBuffers() const { return max_acl_packet_credits_; } - uint16_t GetAclPacketLength() const { - return hci_mtu_; - } + uint16_t GetAclPacketLength() const { return hci_mtu_; } LeBufferSize GetLeBufferSize() const { LeBufferSize le_buffer_size; @@ -200,22 +200,18 @@ class TestController : public Controller { acl_credits_callback_(handle, credits); } - void UnregisterCompletedAclPacketsCallback() { - acl_credits_callback_ = {}; - } + void UnregisterCompletedAclPacketsCallback() { acl_credits_callback_ = {}; } - bool SupportsBlePrivacy() const override { - return supports_ble_privacy_; - } + bool SupportsBlePrivacy() const override { return supports_ble_privacy_; } bool supports_ble_privacy_{false}; - public: +public: const uint16_t max_acl_packet_credits_ = 10; const uint16_t hci_mtu_ = 1024; const uint16_t le_max_acl_packet_credits_ = 15; const uint16_t le_hci_mtu_ = 27; - private: +private: CompletedAclPacketsCallback acl_credits_callback_; std::set supported_opcodes_{}; }; @@ -223,18 +219,16 @@ class TestController : public Controller { } // namespace class MockLeConnectionCallbacks : public LeConnectionCallbacks { - public: - MOCK_METHOD( - void, - OnLeConnectSuccess, - (AddressWithType address_with_type, std::unique_ptr connection), - (override)); - MOCK_METHOD( - void, OnLeConnectFail, (AddressWithType address_with_type, ErrorCode reason), (override)); +public: + MOCK_METHOD(void, OnLeConnectSuccess, + (AddressWithType address_with_type, std::unique_ptr connection), + (override)); + MOCK_METHOD(void, OnLeConnectFail, (AddressWithType address_with_type, ErrorCode reason), + (override)); }; class MockLeAcceptlistCallbacks : public LeAcceptlistCallbacks { - public: +public: MOCK_METHOD(void, OnLeConnectSuccess, (AddressWithType address), (override)); MOCK_METHOD(void, OnLeConnectFail, (AddressWithType address, ErrorCode reason), (override)); MOCK_METHOD(void, OnLeDisconnection, (AddressWithType address), (override)); @@ -242,7 +236,7 @@ class MockLeAcceptlistCallbacks : public LeAcceptlistCallbacks { }; class LeImplTest : public ::testing::Test { - protected: +protected: void SetUp() override { bluetooth::common::InitFlags::SetAllForTesting(); thread_ = new Thread("thread", Thread::Priority::NORMAL); @@ -252,8 +246,9 @@ class LeImplTest : public ::testing::Test { round_robin_scheduler_ = new RoundRobinScheduler(handler_, controller_, hci_queue_.GetUpEnd()); hci_queue_.GetDownEnd()->RegisterDequeue( - handler_, common::Bind(&LeImplTest::HciDownEndDequeue, common::Unretained(this))); - le_impl_ = new le_impl(hci_layer_, controller_, handler_, round_robin_scheduler_, kCrashOnUnknownHandle); + handler_, common::Bind(&LeImplTest::HciDownEndDequeue, common::Unretained(this))); + le_impl_ = new le_impl(hci_layer_, controller_, handler_, round_robin_scheduler_, + kCrashOnUnknownHandle); le_impl_->handle_register_le_callbacks(&mock_le_connection_callbacks_, handler_); Address address; @@ -261,7 +256,8 @@ class LeImplTest : public ::testing::Test { fixed_address_ = AddressWithType(address, AddressType::PUBLIC_DEVICE_ADDRESS); Address::FromString(kRemoteAddress, remote_address_); - remote_public_address_with_type_ = AddressWithType(remote_address_, AddressType::PUBLIC_DEVICE_ADDRESS); + remote_public_address_with_type_ = + AddressWithType(remote_address_, AddressType::PUBLIC_DEVICE_ADDRESS); Address::FromString(kLocalRandomAddress, local_rpa_); Address::FromString(kRemoteRandomAddress, remote_rpa_); @@ -276,11 +272,8 @@ class LeImplTest : public ::testing::Test { auto minimum_rotation_time = std::chrono::milliseconds(7 * 60 * 1000); auto maximum_rotation_time = std::chrono::milliseconds(15 * 60 * 1000); le_impl_->set_privacy_policy_for_initiator_address( - LeAddressManager::AddressPolicy::USE_STATIC_ADDRESS, - address_with_type, - rotation_irk, - minimum_rotation_time, - maximum_rotation_time); + LeAddressManager::AddressPolicy::USE_STATIC_ADDRESS, address_with_type, rotation_irk, + minimum_rotation_time, maximum_rotation_time); hci_layer_->GetCommand(OpCode::LE_SET_RANDOM_ADDRESS); hci_layer_->IncomingEvent(LeSetRandomAddressCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); } @@ -310,9 +303,8 @@ class LeImplTest : public ::testing::Test { void sync_handler() { log::assert_that(thread_ != nullptr, "assert failed: thread_ != nullptr"); - log::assert_that( - thread_->GetReactor()->WaitForIdle(2s), - "assert failed: thread_->GetReactor()->WaitForIdle(2s)"); + log::assert_that(thread_->GetReactor()->WaitForIdle(2s), + "assert failed: thread_->GetReactor()->WaitForIdle(2s)"); } void HciDownEndDequeue() { @@ -335,11 +327,11 @@ class LeImplTest : public ::testing::Test { } } - protected: - void set_privacy_policy_for_initiator_address( - const AddressWithType& address, const LeAddressManager::AddressPolicy& policy) { - le_impl_->set_privacy_policy_for_initiator_address( - policy, address, kRotationIrk, kMinimumRotationTime, kMaximumRotationTime); +protected: + void set_privacy_policy_for_initiator_address(const AddressWithType& address, + const LeAddressManager::AddressPolicy& policy) { + le_impl_->set_privacy_policy_for_initiator_address(policy, address, kRotationIrk, + kMinimumRotationTime, kMaximumRotationTime); } Address remote_address_; @@ -368,10 +360,11 @@ class LeImplTest : public ::testing::Test { }; class LeImplRegisteredWithAddressManagerTest : public LeImplTest { - protected: +protected: void SetUp() override { LeImplTest::SetUp(); - set_privacy_policy_for_initiator_address(fixed_address_, LeAddressManager::AddressPolicy::USE_PUBLIC_ADDRESS); + set_privacy_policy_for_initiator_address(fixed_address_, + LeAddressManager::AddressPolicy::USE_PUBLIC_ADDRESS); le_impl_->register_with_address_manager(); sync_handler(); // Let |LeAddressManager::register_client| execute on handler @@ -379,36 +372,26 @@ class LeImplRegisteredWithAddressManagerTest : public LeImplTest { ASSERT_TRUE(le_impl_->pause_connection); } - void TearDown() override { - LeImplTest::TearDown(); - } + void TearDown() override { LeImplTest::TearDown(); } }; class LeImplWithConnectionTest : public LeImplTest { - protected: +protected: void SetUp() override { LeImplTest::SetUp(); set_random_device_address_policy(); EXPECT_CALL(mock_le_connection_callbacks_, OnLeConnectSuccess(_, _)) - .WillOnce([&](AddressWithType addr, std::unique_ptr conn) { - remote_address_with_type_ = addr; - connection_ = std::move(conn); - connection_->RegisterCallbacks(&connection_management_callbacks_, handler_); - }); + .WillOnce([&](AddressWithType addr, std::unique_ptr conn) { + remote_address_with_type_ = addr; + connection_ = std::move(conn); + connection_->RegisterCallbacks(&connection_management_callbacks_, handler_); + }); auto command = LeEnhancedConnectionCompleteBuilder::Create( - ErrorCode::SUCCESS, - kHciHandle, - Role::PERIPHERAL, - AddressType::PUBLIC_DEVICE_ADDRESS, - remote_address_, - local_rpa_, - remote_rpa_, - 0x0024, - 0x0000, - 0x0011, - ClockAccuracy::PPM_30); + ErrorCode::SUCCESS, kHciHandle, Role::PERIPHERAL, AddressType::PUBLIC_DEVICE_ADDRESS, + remote_address_, local_rpa_, remote_rpa_, 0x0024, 0x0000, 0x0011, + ClockAccuracy::PPM_30); auto bytes = Serialize(std::move(command)); auto view = CreateLeEventView(bytes); ASSERT_TRUE(view.IsValid()); @@ -428,40 +411,53 @@ class LeImplWithConnectionTest : public LeImplTest { }; TEST_F(LeImplTest, add_device_to_accept_list) { - le_impl_->add_device_to_accept_list({{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}, AddressType::PUBLIC_DEVICE_ADDRESS}); + le_impl_->add_device_to_accept_list( + {{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}, AddressType::PUBLIC_DEVICE_ADDRESS}); ASSERT_EQ(1UL, le_impl_->accept_list.size()); - le_impl_->add_device_to_accept_list({{0x11, 0x12, 0x13, 0x14, 0x15, 0x16}, AddressType::PUBLIC_DEVICE_ADDRESS}); + le_impl_->add_device_to_accept_list( + {{0x11, 0x12, 0x13, 0x14, 0x15, 0x16}, AddressType::PUBLIC_DEVICE_ADDRESS}); ASSERT_EQ(2UL, le_impl_->accept_list.size()); - le_impl_->add_device_to_accept_list({{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}, AddressType::PUBLIC_DEVICE_ADDRESS}); + le_impl_->add_device_to_accept_list( + {{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}, AddressType::PUBLIC_DEVICE_ADDRESS}); ASSERT_EQ(2UL, le_impl_->accept_list.size()); - le_impl_->add_device_to_accept_list({{0x11, 0x12, 0x13, 0x14, 0x15, 0x16}, AddressType::PUBLIC_DEVICE_ADDRESS}); + le_impl_->add_device_to_accept_list( + {{0x11, 0x12, 0x13, 0x14, 0x15, 0x16}, AddressType::PUBLIC_DEVICE_ADDRESS}); ASSERT_EQ(2UL, le_impl_->accept_list.size()); } TEST_F(LeImplTest, remove_device_from_accept_list) { - le_impl_->add_device_to_accept_list({{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}, AddressType::PUBLIC_DEVICE_ADDRESS}); - le_impl_->add_device_to_accept_list({{0x11, 0x12, 0x13, 0x14, 0x15, 0x16}, AddressType::PUBLIC_DEVICE_ADDRESS}); - le_impl_->add_device_to_accept_list({{0x21, 0x22, 0x23, 0x24, 0x25, 0x26}, AddressType::PUBLIC_DEVICE_ADDRESS}); - le_impl_->add_device_to_accept_list({{0x31, 0x32, 0x33, 0x34, 0x35, 0x36}, AddressType::PUBLIC_DEVICE_ADDRESS}); + le_impl_->add_device_to_accept_list( + {{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}, AddressType::PUBLIC_DEVICE_ADDRESS}); + le_impl_->add_device_to_accept_list( + {{0x11, 0x12, 0x13, 0x14, 0x15, 0x16}, AddressType::PUBLIC_DEVICE_ADDRESS}); + le_impl_->add_device_to_accept_list( + {{0x21, 0x22, 0x23, 0x24, 0x25, 0x26}, AddressType::PUBLIC_DEVICE_ADDRESS}); + le_impl_->add_device_to_accept_list( + {{0x31, 0x32, 0x33, 0x34, 0x35, 0x36}, AddressType::PUBLIC_DEVICE_ADDRESS}); ASSERT_EQ(4UL, le_impl_->accept_list.size()); - le_impl_->remove_device_from_accept_list({{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}, AddressType::PUBLIC_DEVICE_ADDRESS}); + le_impl_->remove_device_from_accept_list( + {{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}, AddressType::PUBLIC_DEVICE_ADDRESS}); ASSERT_EQ(3UL, le_impl_->accept_list.size()); - le_impl_->remove_device_from_accept_list({{0x11, 0x12, 0x13, 0x14, 0x15, 0x16}, AddressType::PUBLIC_DEVICE_ADDRESS}); + le_impl_->remove_device_from_accept_list( + {{0x11, 0x12, 0x13, 0x14, 0x15, 0x16}, AddressType::PUBLIC_DEVICE_ADDRESS}); ASSERT_EQ(2UL, le_impl_->accept_list.size()); - le_impl_->remove_device_from_accept_list({{0x11, 0x12, 0x13, 0x14, 0x15, 0x16}, AddressType::PUBLIC_DEVICE_ADDRESS}); + le_impl_->remove_device_from_accept_list( + {{0x11, 0x12, 0x13, 0x14, 0x15, 0x16}, AddressType::PUBLIC_DEVICE_ADDRESS}); ASSERT_EQ(2UL, le_impl_->accept_list.size()); le_impl_->remove_device_from_accept_list({Address::kEmpty, AddressType::PUBLIC_DEVICE_ADDRESS}); ASSERT_EQ(2UL, le_impl_->accept_list.size()); - le_impl_->remove_device_from_accept_list({{0x21, 0x22, 0x23, 0x24, 0x25, 0x26}, AddressType::PUBLIC_DEVICE_ADDRESS}); - le_impl_->remove_device_from_accept_list({{0x31, 0x32, 0x33, 0x34, 0x35, 0x36}, AddressType::PUBLIC_DEVICE_ADDRESS}); + le_impl_->remove_device_from_accept_list( + {{0x21, 0x22, 0x23, 0x24, 0x25, 0x26}, AddressType::PUBLIC_DEVICE_ADDRESS}); + le_impl_->remove_device_from_accept_list( + {{0x31, 0x32, 0x33, 0x34, 0x35, 0x36}, AddressType::PUBLIC_DEVICE_ADDRESS}); ASSERT_EQ(0UL, le_impl_->accept_list.size()); } @@ -470,10 +466,10 @@ TEST_F(LeImplTest, connection_complete_with_periperal_role) { // Create connection le_impl_->create_le_connection( - {{0x21, 0x22, 0x23, 0x24, 0x25, 0x26}, AddressType::PUBLIC_DEVICE_ADDRESS}, true, false); + {{0x21, 0x22, 0x23, 0x24, 0x25, 0x26}, AddressType::PUBLIC_DEVICE_ADDRESS}, true, false); hci_layer_->GetCommand(OpCode::LE_ADD_DEVICE_TO_FILTER_ACCEPT_LIST); hci_layer_->IncomingEvent( - LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); + LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); hci_layer_->GetCommand(OpCode::LE_CREATE_CONNECTION); hci_layer_->IncomingEvent(LeCreateConnectionStatusBuilder::Create(ErrorCode::SUCCESS, 0x01)); sync_handler(); @@ -487,15 +483,8 @@ TEST_F(LeImplTest, connection_complete_with_periperal_role) { hci::AddressWithType address_with_type(remote_address, hci::AddressType::PUBLIC_DEVICE_ADDRESS); EXPECT_CALL(mock_le_connection_callbacks_, OnLeConnectSuccess(address_with_type, _)); hci_layer_->IncomingLeMetaEvent(LeConnectionCompleteBuilder::Create( - ErrorCode::SUCCESS, - 0x0041, - Role::PERIPHERAL, - AddressType::PUBLIC_DEVICE_ADDRESS, - remote_address, - 0x0024, - 0x0000, - 0x0011, - ClockAccuracy::PPM_30)); + ErrorCode::SUCCESS, 0x0041, Role::PERIPHERAL, AddressType::PUBLIC_DEVICE_ADDRESS, + remote_address, 0x0024, 0x0000, 0x0011, ClockAccuracy::PPM_30)); sync_handler(); // Check state is still ARMED @@ -508,13 +497,13 @@ TEST_F(LeImplTest, enhanced_connection_complete_with_periperal_role) { controller_->AddSupported(OpCode::LE_EXTENDED_CREATE_CONNECTION); // Create connection le_impl_->create_le_connection( - {{0x21, 0x22, 0x23, 0x24, 0x25, 0x26}, AddressType::PUBLIC_DEVICE_ADDRESS}, true, false); + {{0x21, 0x22, 0x23, 0x24, 0x25, 0x26}, AddressType::PUBLIC_DEVICE_ADDRESS}, true, false); hci_layer_->GetCommand(OpCode::LE_ADD_DEVICE_TO_FILTER_ACCEPT_LIST); hci_layer_->IncomingEvent( - LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); + LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); hci_layer_->GetCommand(OpCode::LE_EXTENDED_CREATE_CONNECTION); hci_layer_->IncomingEvent( - LeExtendedCreateConnectionStatusBuilder::Create(ErrorCode::SUCCESS, 0x01)); + LeExtendedCreateConnectionStatusBuilder::Create(ErrorCode::SUCCESS, 0x01)); sync_handler(); // Check state is ARMED @@ -526,17 +515,9 @@ TEST_F(LeImplTest, enhanced_connection_complete_with_periperal_role) { hci::AddressWithType address_with_type(remote_address, hci::AddressType::PUBLIC_DEVICE_ADDRESS); EXPECT_CALL(mock_le_connection_callbacks_, OnLeConnectSuccess(address_with_type, _)); hci_layer_->IncomingLeMetaEvent(LeEnhancedConnectionCompleteBuilder::Create( - ErrorCode::SUCCESS, - 0x0041, - Role::PERIPHERAL, - AddressType::PUBLIC_DEVICE_ADDRESS, - remote_address, - Address::kEmpty, - Address::kEmpty, - 0x0024, - 0x0000, - 0x0011, - ClockAccuracy::PPM_30)); + ErrorCode::SUCCESS, 0x0041, Role::PERIPHERAL, AddressType::PUBLIC_DEVICE_ADDRESS, + remote_address, Address::kEmpty, Address::kEmpty, 0x0024, 0x0000, 0x0011, + ClockAccuracy::PPM_30)); sync_handler(); // Check state is still ARMED @@ -553,7 +534,7 @@ TEST_F(LeImplTest, connection_complete_with_central_role) { le_impl_->create_le_connection(address_with_type, true, false); hci_layer_->GetCommand(OpCode::LE_ADD_DEVICE_TO_FILTER_ACCEPT_LIST); hci_layer_->IncomingEvent( - LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); + LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); hci_layer_->GetCommand(OpCode::LE_CREATE_CONNECTION); hci_layer_->IncomingEvent(LeCreateConnectionStatusBuilder::Create(ErrorCode::SUCCESS, 0x01)); sync_handler(); @@ -564,15 +545,8 @@ TEST_F(LeImplTest, connection_complete_with_central_role) { // Receive connection complete of outgoing connection (Role::CENTRAL) EXPECT_CALL(mock_le_connection_callbacks_, OnLeConnectSuccess(address_with_type, _)); hci_layer_->IncomingLeMetaEvent(LeConnectionCompleteBuilder::Create( - ErrorCode::SUCCESS, - 0x0041, - Role::CENTRAL, - AddressType::PUBLIC_DEVICE_ADDRESS, - remote_address, - 0x0024, - 0x0000, - 0x0011, - ClockAccuracy::PPM_30)); + ErrorCode::SUCCESS, 0x0041, Role::CENTRAL, AddressType::PUBLIC_DEVICE_ADDRESS, + remote_address, 0x0024, 0x0000, 0x0011, ClockAccuracy::PPM_30)); sync_handler(); // Check state is DISARMED @@ -590,10 +564,10 @@ TEST_F(LeImplTest, enhanced_connection_complete_with_central_role) { le_impl_->create_le_connection(address_with_type, true, false); hci_layer_->GetCommand(OpCode::LE_ADD_DEVICE_TO_FILTER_ACCEPT_LIST); hci_layer_->IncomingEvent( - LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); + LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); hci_layer_->GetCommand(OpCode::LE_EXTENDED_CREATE_CONNECTION); hci_layer_->IncomingEvent( - LeExtendedCreateConnectionStatusBuilder::Create(ErrorCode::SUCCESS, 0x01)); + LeExtendedCreateConnectionStatusBuilder::Create(ErrorCode::SUCCESS, 0x01)); sync_handler(); // Check state is ARMED @@ -602,17 +576,9 @@ TEST_F(LeImplTest, enhanced_connection_complete_with_central_role) { // Receive connection complete of outgoing connection (Role::CENTRAL) EXPECT_CALL(mock_le_connection_callbacks_, OnLeConnectSuccess(address_with_type, _)); hci_layer_->IncomingLeMetaEvent(LeEnhancedConnectionCompleteBuilder::Create( - ErrorCode::SUCCESS, - 0x0041, - Role::CENTRAL, - AddressType::PUBLIC_DEVICE_ADDRESS, - remote_address, - Address::kEmpty, - Address::kEmpty, - 0x0024, - 0x0000, - 0x0011, - ClockAccuracy::PPM_30)); + ErrorCode::SUCCESS, 0x0041, Role::CENTRAL, AddressType::PUBLIC_DEVICE_ADDRESS, + remote_address, Address::kEmpty, Address::kEmpty, 0x0024, 0x0000, 0x0011, + ClockAccuracy::PPM_30)); sync_handler(); // Check state is DISARMED @@ -624,38 +590,36 @@ TEST_F(LeImplTest, DISABLED_register_with_address_manager__AddressPolicyNotSet) std::promise promise; auto future = promise.get_future(); handler_->Post(common::BindOnce( - [](struct le_impl* le_impl, os::Handler* handler, std::promise promise) { - le_impl->register_with_address_manager(); - handler->Post(common::BindOnce([](std::promise promise) { promise.set_value(); }, std::move(promise))); - }, - le_impl_, - handler_, - std::move(promise))); + [](struct le_impl* le_impl, os::Handler* handler, std::promise promise) { + le_impl->register_with_address_manager(); + handler->Post(common::BindOnce([](std::promise promise) { promise.set_value(); }, + std::move(promise))); + }, + le_impl_, handler_, std::move(promise))); // Let |LeAddressManager::register_client| execute on handler auto status = future.wait_for(2s); ASSERT_EQ(status, std::future_status::ready); handler_->Post(common::BindOnce( - [](struct le_impl* le_impl) { - ASSERT_TRUE(le_impl->address_manager_registered); - ASSERT_TRUE(le_impl->pause_connection); - }, - le_impl_)); + [](struct le_impl* le_impl) { + ASSERT_TRUE(le_impl->address_manager_registered); + ASSERT_TRUE(le_impl->pause_connection); + }, + le_impl_)); std::promise promise2; auto future2 = promise2.get_future(); handler_->Post(common::BindOnce( - [](struct le_impl* le_impl, os::Handler* handler, std::promise promise) { - le_impl->ready_to_unregister = true; - le_impl->check_for_unregister(); - ASSERT_FALSE(le_impl->address_manager_registered); - ASSERT_FALSE(le_impl->pause_connection); - handler->Post(common::BindOnce([](std::promise promise) { promise.set_value(); }, std::move(promise))); - }, - le_impl_, - handler_, - std::move(promise2))); + [](struct le_impl* le_impl, os::Handler* handler, std::promise promise) { + le_impl->ready_to_unregister = true; + le_impl->check_for_unregister(); + ASSERT_FALSE(le_impl->address_manager_registered); + ASSERT_FALSE(le_impl->pause_connection); + handler->Post(common::BindOnce([](std::promise promise) { promise.set_value(); }, + std::move(promise))); + }, + le_impl_, handler_, std::move(promise2))); // Let |LeAddressManager::unregister_client| execute on handler auto status2 = future2.wait_for(2s); @@ -668,7 +632,8 @@ TEST_F(LeImplTest, DISABLED_disarm_connectability_DISARMED) { le_impl_->disarm_connectability(); ASSERT_FALSE(le_impl_->disarmed_while_arming_); - le_impl_->on_create_connection(ReturnCommandStatus(OpCode::LE_CREATE_CONNECTION, ErrorCode::SUCCESS)); + le_impl_->on_create_connection( + ReturnCommandStatus(OpCode::LE_CREATE_CONNECTION, ErrorCode::SUCCESS)); } // b/260917913 @@ -678,7 +643,7 @@ TEST_F(LeImplTest, DISABLED_disarm_connectability_DISARMED_extended) { ASSERT_FALSE(le_impl_->disarmed_while_arming_); le_impl_->on_extended_create_connection( - ReturnCommandStatus(OpCode::LE_EXTENDED_CREATE_CONNECTION, ErrorCode::SUCCESS)); + ReturnCommandStatus(OpCode::LE_EXTENDED_CREATE_CONNECTION, ErrorCode::SUCCESS)); } // b/260917913 @@ -686,7 +651,8 @@ TEST_F(LeImplTest, DISABLED_disarm_connectability_ARMING) { le_impl_->connectability_state_ = ConnectabilityState::ARMING; le_impl_->disarm_connectability(); ASSERT_TRUE(le_impl_->disarmed_while_arming_); - le_impl_->on_create_connection(ReturnCommandStatus(OpCode::LE_CREATE_CONNECTION, ErrorCode::SUCCESS)); + le_impl_->on_create_connection( + ReturnCommandStatus(OpCode::LE_CREATE_CONNECTION, ErrorCode::SUCCESS)); } // b/260917913 @@ -696,7 +662,7 @@ TEST_F(LeImplTest, DISABLED_disarm_connectability_ARMING_extended) { ASSERT_TRUE(le_impl_->disarmed_while_arming_); le_impl_->on_extended_create_connection( - ReturnCommandStatus(OpCode::LE_EXTENDED_CREATE_CONNECTION, ErrorCode::SUCCESS)); + ReturnCommandStatus(OpCode::LE_EXTENDED_CREATE_CONNECTION, ErrorCode::SUCCESS)); } // b/260917913 @@ -705,7 +671,8 @@ TEST_F(LeImplTest, DISABLED_disarm_connectability_ARMED) { le_impl_->disarm_connectability(); ASSERT_FALSE(le_impl_->disarmed_while_arming_); - le_impl_->on_create_connection(ReturnCommandStatus(OpCode::LE_CREATE_CONNECTION, ErrorCode::SUCCESS)); + le_impl_->on_create_connection( + ReturnCommandStatus(OpCode::LE_CREATE_CONNECTION, ErrorCode::SUCCESS)); } // b/260917913 @@ -715,7 +682,7 @@ TEST_F(LeImplTest, DISABLED_disarm_connectability_ARMED_extended) { ASSERT_FALSE(le_impl_->disarmed_while_arming_); le_impl_->on_extended_create_connection( - ReturnCommandStatus(OpCode::LE_EXTENDED_CREATE_CONNECTION, ErrorCode::SUCCESS)); + ReturnCommandStatus(OpCode::LE_EXTENDED_CREATE_CONNECTION, ErrorCode::SUCCESS)); } // b/260917913 @@ -724,7 +691,8 @@ TEST_F(LeImplTest, DISABLED_disarm_connectability_DISARMING) { le_impl_->disarm_connectability(); ASSERT_FALSE(le_impl_->disarmed_while_arming_); - le_impl_->on_create_connection(ReturnCommandStatus(OpCode::LE_CREATE_CONNECTION, ErrorCode::SUCCESS)); + le_impl_->on_create_connection( + ReturnCommandStatus(OpCode::LE_CREATE_CONNECTION, ErrorCode::SUCCESS)); } // b/260917913 @@ -734,12 +702,13 @@ TEST_F(LeImplTest, DISABLED_disarm_connectability_DISARMING_extended) { ASSERT_FALSE(le_impl_->disarmed_while_arming_); le_impl_->on_extended_create_connection( - ReturnCommandStatus(OpCode::LE_EXTENDED_CREATE_CONNECTION, ErrorCode::SUCCESS)); + ReturnCommandStatus(OpCode::LE_EXTENDED_CREATE_CONNECTION, ErrorCode::SUCCESS)); } // b/260917913 TEST_F(LeImplTest, DISABLED_register_with_address_manager__AddressPolicyPublicAddress) { - set_privacy_policy_for_initiator_address(fixed_address_, LeAddressManager::AddressPolicy::USE_PUBLIC_ADDRESS); + set_privacy_policy_for_initiator_address(fixed_address_, + LeAddressManager::AddressPolicy::USE_PUBLIC_ADDRESS); le_impl_->register_with_address_manager(); sync_handler(); // Let |eAddressManager::register_client| execute on handler @@ -756,7 +725,8 @@ TEST_F(LeImplTest, DISABLED_register_with_address_manager__AddressPolicyPublicAd // b/260917913 TEST_F(LeImplTest, DISABLED_register_with_address_manager__AddressPolicyStaticAddress) { - set_privacy_policy_for_initiator_address(fixed_address_, LeAddressManager::AddressPolicy::USE_STATIC_ADDRESS); + set_privacy_policy_for_initiator_address(fixed_address_, + LeAddressManager::AddressPolicy::USE_STATIC_ADDRESS); le_impl_->register_with_address_manager(); sync_handler(); // Let |LeAddressManager::register_client| execute on handler @@ -773,7 +743,8 @@ TEST_F(LeImplTest, DISABLED_register_with_address_manager__AddressPolicyStaticAd // b/260917913 TEST_F(LeImplTest, DISABLED_register_with_address_manager__AddressPolicyNonResolvableAddress) { - set_privacy_policy_for_initiator_address(fixed_address_, LeAddressManager::AddressPolicy::USE_NON_RESOLVABLE_ADDRESS); + set_privacy_policy_for_initiator_address( + fixed_address_, LeAddressManager::AddressPolicy::USE_NON_RESOLVABLE_ADDRESS); le_impl_->register_with_address_manager(); sync_handler(); // Let |LeAddressManager::register_client| execute on handler @@ -790,7 +761,8 @@ TEST_F(LeImplTest, DISABLED_register_with_address_manager__AddressPolicyNonResol // b/260917913 TEST_F(LeImplTest, DISABLED_register_with_address_manager__AddressPolicyResolvableAddress) { - set_privacy_policy_for_initiator_address(fixed_address_, LeAddressManager::AddressPolicy::USE_RESOLVABLE_ADDRESS); + set_privacy_policy_for_initiator_address(fixed_address_, + LeAddressManager::AddressPolicy::USE_RESOLVABLE_ADDRESS); le_impl_->register_with_address_manager(); sync_handler(); // Let |LeAddressManager::register_client| execute on handler @@ -808,7 +780,8 @@ TEST_F(LeImplTest, DISABLED_register_with_address_manager__AddressPolicyResolvab // b/260920739 TEST_F(LeImplTest, DISABLED_add_device_to_resolving_list) { // Some kind of privacy policy must be set for LeAddressManager to operate properly - set_privacy_policy_for_initiator_address(fixed_address_, LeAddressManager::AddressPolicy::USE_PUBLIC_ADDRESS); + set_privacy_policy_for_initiator_address(fixed_address_, + LeAddressManager::AddressPolicy::USE_PUBLIC_ADDRESS); // Let LeAddressManager::resume_registered_clients execute sync_handler(); @@ -820,8 +793,8 @@ TEST_F(LeImplTest, DISABLED_add_device_to_resolving_list) { ASSERT_EQ(0UL, le_impl_->le_address_manager_->NumberCachedCommands()); // Acknowledge that the le_impl has quiesced all relevant controller state - le_impl_->add_device_to_resolving_list( - remote_public_address_with_type_, kPeerIdentityResolvingKey, kLocalIdentityResolvingKey); + le_impl_->add_device_to_resolving_list(remote_public_address_with_type_, + kPeerIdentityResolvingKey, kLocalIdentityResolvingKey); ASSERT_EQ(3UL, le_impl_->le_address_manager_->NumberCachedCommands()); sync_handler(); // Let |LeAddressManager::register_client| execute on handler @@ -834,34 +807,35 @@ TEST_F(LeImplTest, DISABLED_add_device_to_resolving_list) { { // Inform controller to disable address resolution auto command = - CreateLeSecurityCommandView(hci_layer_->GetCommand()); + CreateLeSecurityCommandView(hci_layer_->GetCommand()); ASSERT_TRUE(command.IsValid()); ASSERT_EQ(Enable::DISABLED, command.GetAddressResolutionEnable()); le_impl_->le_address_manager_->OnCommandComplete( - ReturnCommandComplete(OpCode::LE_SET_ADDRESS_RESOLUTION_ENABLE, ErrorCode::SUCCESS)); + ReturnCommandComplete(OpCode::LE_SET_ADDRESS_RESOLUTION_ENABLE, ErrorCode::SUCCESS)); } sync_handler(); // |LeAddressManager::check_cached_commands| { auto command = - CreateLeSecurityCommandView(hci_layer_->GetCommand()); + CreateLeSecurityCommandView(hci_layer_->GetCommand()); ASSERT_TRUE(command.IsValid()); - ASSERT_EQ(PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, command.GetPeerIdentityAddressType()); + ASSERT_EQ(PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, + command.GetPeerIdentityAddressType()); ASSERT_EQ(remote_public_address_with_type_.GetAddress(), command.GetPeerIdentityAddress()); ASSERT_EQ(kPeerIdentityResolvingKey, command.GetPeerIrk()); ASSERT_EQ(kLocalIdentityResolvingKey, command.GetLocalIrk()); le_impl_->le_address_manager_->OnCommandComplete( - ReturnCommandComplete(OpCode::LE_ADD_DEVICE_TO_RESOLVING_LIST, ErrorCode::SUCCESS)); + ReturnCommandComplete(OpCode::LE_ADD_DEVICE_TO_RESOLVING_LIST, ErrorCode::SUCCESS)); } sync_handler(); // |LeAddressManager::check_cached_commands| { auto command = - CreateLeSecurityCommandView(hci_layer_->GetCommand()); + CreateLeSecurityCommandView(hci_layer_->GetCommand()); ASSERT_TRUE(command.IsValid()); ASSERT_EQ(Enable::ENABLED, command.GetAddressResolutionEnable()); le_impl_->le_address_manager_->OnCommandComplete( - ReturnCommandComplete(OpCode::LE_SET_ADDRESS_RESOLUTION_ENABLE, ErrorCode::SUCCESS)); + ReturnCommandComplete(OpCode::LE_SET_ADDRESS_RESOLUTION_ENABLE, ErrorCode::SUCCESS)); } sync_handler(); // |LeAddressManager::check_cached_commands| @@ -880,7 +854,8 @@ TEST_F(LeImplTest, add_device_to_resolving_list__SupportsBlePrivacy) { controller_->supports_ble_privacy_ = true; // Some kind of privacy policy must be set for LeAddressManager to operate properly - set_privacy_policy_for_initiator_address(fixed_address_, LeAddressManager::AddressPolicy::USE_PUBLIC_ADDRESS); + set_privacy_policy_for_initiator_address(fixed_address_, + LeAddressManager::AddressPolicy::USE_PUBLIC_ADDRESS); // Let LeAddressManager::resume_registered_clients execute sync_handler(); @@ -892,8 +867,8 @@ TEST_F(LeImplTest, add_device_to_resolving_list__SupportsBlePrivacy) { ASSERT_EQ(0UL, le_impl_->le_address_manager_->NumberCachedCommands()); // Acknowledge that the le_impl has quiesced all relevant controller state - le_impl_->add_device_to_resolving_list( - remote_public_address_with_type_, kPeerIdentityResolvingKey, kLocalIdentityResolvingKey); + le_impl_->add_device_to_resolving_list(remote_public_address_with_type_, + kPeerIdentityResolvingKey, kLocalIdentityResolvingKey); ASSERT_EQ(4UL, le_impl_->le_address_manager_->NumberCachedCommands()); sync_handler(); // Let |LeAddressManager::register_client| execute on handler @@ -906,24 +881,25 @@ TEST_F(LeImplTest, add_device_to_resolving_list__SupportsBlePrivacy) { { // Inform controller to disable address resolution auto command = - CreateLeSecurityCommandView(hci_layer_->GetCommand()); + CreateLeSecurityCommandView(hci_layer_->GetCommand()); ASSERT_TRUE(command.IsValid()); ASSERT_EQ(Enable::DISABLED, command.GetAddressResolutionEnable()); le_impl_->le_address_manager_->OnCommandComplete( - ReturnCommandComplete(OpCode::LE_SET_ADDRESS_RESOLUTION_ENABLE, ErrorCode::SUCCESS)); + ReturnCommandComplete(OpCode::LE_SET_ADDRESS_RESOLUTION_ENABLE, ErrorCode::SUCCESS)); } sync_handler(); // |LeAddressManager::check_cached_commands| { auto command = - CreateLeSecurityCommandView(hci_layer_->GetCommand()); + CreateLeSecurityCommandView(hci_layer_->GetCommand()); ASSERT_TRUE(command.IsValid()); - ASSERT_EQ(PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, command.GetPeerIdentityAddressType()); + ASSERT_EQ(PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, + command.GetPeerIdentityAddressType()); ASSERT_EQ(remote_public_address_with_type_.GetAddress(), command.GetPeerIdentityAddress()); ASSERT_EQ(kPeerIdentityResolvingKey, command.GetPeerIrk()); ASSERT_EQ(kLocalIdentityResolvingKey, command.GetLocalIrk()); le_impl_->le_address_manager_->OnCommandComplete( - ReturnCommandComplete(OpCode::LE_ADD_DEVICE_TO_RESOLVING_LIST, ErrorCode::SUCCESS)); + ReturnCommandComplete(OpCode::LE_ADD_DEVICE_TO_RESOLVING_LIST, ErrorCode::SUCCESS)); } sync_handler(); // |LeAddressManager::check_cached_commands| @@ -932,19 +908,20 @@ TEST_F(LeImplTest, add_device_to_resolving_list__SupportsBlePrivacy) { ASSERT_TRUE(command.IsValid()); ASSERT_EQ(PrivacyMode::DEVICE, command.GetPrivacyMode()); ASSERT_EQ(remote_public_address_with_type_.GetAddress(), command.GetPeerIdentityAddress()); - ASSERT_EQ(PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, command.GetPeerIdentityAddressType()); + ASSERT_EQ(PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, + command.GetPeerIdentityAddressType()); le_impl_->le_address_manager_->OnCommandComplete( - ReturnCommandComplete(OpCode::LE_SET_PRIVACY_MODE, ErrorCode::SUCCESS)); + ReturnCommandComplete(OpCode::LE_SET_PRIVACY_MODE, ErrorCode::SUCCESS)); } sync_handler(); // |LeAddressManager::check_cached_commands| { auto command = - CreateLeSecurityCommandView(hci_layer_->GetCommand()); + CreateLeSecurityCommandView(hci_layer_->GetCommand()); ASSERT_TRUE(command.IsValid()); ASSERT_EQ(Enable::ENABLED, command.GetAddressResolutionEnable()); le_impl_->le_address_manager_->OnCommandComplete( - ReturnCommandComplete(OpCode::LE_SET_ADDRESS_RESOLUTION_ENABLE, ErrorCode::SUCCESS)); + ReturnCommandComplete(OpCode::LE_SET_ADDRESS_RESOLUTION_ENABLE, ErrorCode::SUCCESS)); } sync_handler(); // |LeAddressManager::check_cached_commands| @@ -959,27 +936,22 @@ TEST_F(LeImplTest, add_device_to_resolving_list__SupportsBlePrivacy) { } TEST_F(LeImplTest, connectability_state_machine_text) { - ASSERT_STREQ( - "ConnectabilityState::DISARMED", connectability_state_machine_text(ConnectabilityState::DISARMED).c_str()); - ASSERT_STREQ("ConnectabilityState::ARMING", connectability_state_machine_text(ConnectabilityState::ARMING).c_str()); - ASSERT_STREQ("ConnectabilityState::ARMED", connectability_state_machine_text(ConnectabilityState::ARMED).c_str()); - ASSERT_STREQ( - "ConnectabilityState::DISARMING", connectability_state_machine_text(ConnectabilityState::DISARMING).c_str()); + ASSERT_STREQ("ConnectabilityState::DISARMED", + connectability_state_machine_text(ConnectabilityState::DISARMED).c_str()); + ASSERT_STREQ("ConnectabilityState::ARMING", + connectability_state_machine_text(ConnectabilityState::ARMING).c_str()); + ASSERT_STREQ("ConnectabilityState::ARMED", + connectability_state_machine_text(ConnectabilityState::ARMED).c_str()); + ASSERT_STREQ("ConnectabilityState::DISARMING", + connectability_state_machine_text(ConnectabilityState::DISARMING).c_str()); } TEST_F(LeImplTest, on_le_event__CONNECTION_COMPLETE_CENTRAL) { EXPECT_CALL(mock_le_connection_callbacks_, OnLeConnectSuccess(_, _)).Times(1); set_random_device_address_policy(); auto command = LeConnectionCompleteBuilder::Create( - ErrorCode::SUCCESS, - kHciHandle, - Role::CENTRAL, - AddressType::PUBLIC_DEVICE_ADDRESS, - remote_address_, - 0x0024, - 0x0000, - 0x0011, - ClockAccuracy::PPM_30); + ErrorCode::SUCCESS, kHciHandle, Role::CENTRAL, AddressType::PUBLIC_DEVICE_ADDRESS, + remote_address_, 0x0024, 0x0000, 0x0011, ClockAccuracy::PPM_30); auto bytes = Serialize(std::move(command)); auto view = CreateLeEventView(bytes); ASSERT_TRUE(view.IsValid()); @@ -990,15 +962,8 @@ TEST_F(LeImplTest, on_le_event__CONNECTION_COMPLETE_PERIPHERAL) { EXPECT_CALL(mock_le_connection_callbacks_, OnLeConnectSuccess(_, _)).Times(1); set_random_device_address_policy(); auto command = LeConnectionCompleteBuilder::Create( - ErrorCode::SUCCESS, - kHciHandle, - Role::PERIPHERAL, - AddressType::PUBLIC_DEVICE_ADDRESS, - remote_address_, - 0x0024, - 0x0000, - 0x0011, - ClockAccuracy::PPM_30); + ErrorCode::SUCCESS, kHciHandle, Role::PERIPHERAL, AddressType::PUBLIC_DEVICE_ADDRESS, + remote_address_, 0x0024, 0x0000, 0x0011, ClockAccuracy::PPM_30); auto bytes = Serialize(std::move(command)); auto view = CreateLeEventView(bytes); ASSERT_TRUE(view.IsValid()); @@ -1009,17 +974,8 @@ TEST_F(LeImplTest, on_le_event__ENHANCED_CONNECTION_COMPLETE_CENTRAL) { EXPECT_CALL(mock_le_connection_callbacks_, OnLeConnectSuccess(_, _)).Times(1); set_random_device_address_policy(); auto command = LeEnhancedConnectionCompleteBuilder::Create( - ErrorCode::SUCCESS, - kHciHandle, - Role::CENTRAL, - AddressType::PUBLIC_DEVICE_ADDRESS, - remote_address_, - local_rpa_, - remote_rpa_, - 0x0024, - 0x0000, - 0x0011, - ClockAccuracy::PPM_30); + ErrorCode::SUCCESS, kHciHandle, Role::CENTRAL, AddressType::PUBLIC_DEVICE_ADDRESS, + remote_address_, local_rpa_, remote_rpa_, 0x0024, 0x0000, 0x0011, ClockAccuracy::PPM_30); auto bytes = Serialize(std::move(command)); auto view = CreateLeEventView(bytes); ASSERT_TRUE(view.IsValid()); @@ -1030,17 +986,8 @@ TEST_F(LeImplTest, on_le_event__ENHANCED_CONNECTION_COMPLETE_PERIPHERAL) { EXPECT_CALL(mock_le_connection_callbacks_, OnLeConnectSuccess(_, _)).Times(1); set_random_device_address_policy(); auto command = LeEnhancedConnectionCompleteBuilder::Create( - ErrorCode::SUCCESS, - kHciHandle, - Role::PERIPHERAL, - AddressType::PUBLIC_DEVICE_ADDRESS, - remote_address_, - local_rpa_, - remote_rpa_, - 0x0024, - 0x0000, - 0x0011, - ClockAccuracy::PPM_30); + ErrorCode::SUCCESS, kHciHandle, Role::PERIPHERAL, AddressType::PUBLIC_DEVICE_ADDRESS, + remote_address_, local_rpa_, remote_rpa_, 0x0024, 0x0000, 0x0011, ClockAccuracy::PPM_30); auto bytes = Serialize(std::move(command)); auto view = CreateLeEventView(bytes); ASSERT_TRUE(view.IsValid()); @@ -1055,11 +1002,11 @@ TEST_F(LeImplWithConnectionTest, on_le_event__PHY_UPDATE_COMPLETE) { // Send a phy update { EXPECT_CALL(connection_management_callbacks_, OnPhyUpdate(_, _, _)) - .WillOnce([&](hci::ErrorCode _hci_status, uint8_t _tx_phy, uint8_t _rx_phy) { - hci_status = _hci_status; - tx_phy = static_cast(_tx_phy); - rx_phy = static_cast(_rx_phy); - }); + .WillOnce([&](hci::ErrorCode _hci_status, uint8_t _tx_phy, uint8_t _rx_phy) { + hci_status = _hci_status; + tx_phy = static_cast(_tx_phy); + rx_phy = static_cast(_rx_phy); + }); auto command = LePhyUpdateCompleteBuilder::Create(ErrorCode::SUCCESS, kHciHandle, 0x01, 0x02); auto bytes = Serialize(std::move(command)); auto view = CreateLeEventView(bytes); @@ -1075,8 +1022,10 @@ TEST_F(LeImplWithConnectionTest, on_le_event__PHY_UPDATE_COMPLETE) { TEST_F(LeImplWithConnectionTest, on_le_event__SUBRATE_CHANGE_EVENT) { // Send a subrate event - EXPECT_CALL(connection_management_callbacks_, OnLeSubrateChange(ErrorCode::SUCCESS, 0x01, 0x02, 0x03, 0x04)); - auto command = LeSubrateChangeBuilder::Create(ErrorCode::SUCCESS, kHciHandle, 0x01, 0x02, 0x03, 0x04); + EXPECT_CALL(connection_management_callbacks_, + OnLeSubrateChange(ErrorCode::SUCCESS, 0x01, 0x02, 0x03, 0x04)); + auto command = + LeSubrateChangeBuilder::Create(ErrorCode::SUCCESS, kHciHandle, 0x01, 0x02, 0x03, 0x04); auto bytes = Serialize(std::move(command)); auto view = CreateLeEventView(bytes); ASSERT_TRUE(view.IsValid()); @@ -1094,12 +1043,13 @@ TEST_F(LeImplWithConnectionTest, on_le_event__DATA_LENGTH_CHANGE) { // Send a data length event { EXPECT_CALL(connection_management_callbacks_, OnDataLengthChange(_, _, _, _)) - .WillOnce([&](uint16_t _tx_octets, uint16_t _tx_time, uint16_t _rx_octets, uint16_t _rx_time) { - tx_octets = _tx_octets; - tx_time = _tx_time; - rx_octets = _rx_octets; - rx_time = _rx_time; - }); + .WillOnce([&](uint16_t _tx_octets, uint16_t _tx_time, uint16_t _rx_octets, + uint16_t _rx_time) { + tx_octets = _tx_octets; + tx_time = _tx_time; + rx_octets = _rx_octets; + rx_time = _rx_time; + }); auto command = LeDataLengthChangeBuilder::Create(kHciHandle, 0x1234, 0x5678, 0x9abc, 0xdef0); auto bytes = Serialize(std::move(command)); auto view = CreateLeEventView(bytes); @@ -1117,14 +1067,13 @@ TEST_F(LeImplWithConnectionTest, on_le_event__DATA_LENGTH_CHANGE) { TEST_F(LeImplWithConnectionTest, on_le_event__REMOTE_CONNECTION_PARAMETER_REQUEST) { std::promise request_promise; auto request = request_promise.get_future(); - EXPECT_CALL( - connection_management_callbacks_, - OnParameterUpdateRequest(kIntervalMin, kIntervalMax, kLatency, kTimeout)) - .WillOnce([&request_promise]() { request_promise.set_value(); }); + EXPECT_CALL(connection_management_callbacks_, + OnParameterUpdateRequest(kIntervalMin, kIntervalMax, kLatency, kTimeout)) + .WillOnce([&request_promise]() { request_promise.set_value(); }); // Send a remote connection parameter request auto command = hci::LeRemoteConnectionParameterRequestBuilder::Create( - kHciHandle, kIntervalMin, kIntervalMax, kLatency, kTimeout); + kHciHandle, kIntervalMin, kIntervalMax, kLatency, kTimeout); auto bytes = Serialize(std::move(command)); { auto view = CreateLeEventView(bytes); @@ -1145,11 +1094,11 @@ TEST_F(LeImplRegisteredWithAddressManagerTest, DISABLED_clear_resolving_list) { { auto view = - CreateLeSecurityCommandView(hci_layer_->GetCommand()); + CreateLeSecurityCommandView(hci_layer_->GetCommand()); ASSERT_TRUE(view.IsValid()); ASSERT_EQ(Enable::DISABLED, view.GetAddressResolutionEnable()); le_impl_->le_address_manager_->OnCommandComplete( - ReturnCommandComplete(OpCode::LE_SET_ADDRESS_RESOLUTION_ENABLE, ErrorCode::SUCCESS)); + ReturnCommandComplete(OpCode::LE_SET_ADDRESS_RESOLUTION_ENABLE, ErrorCode::SUCCESS)); } sync_handler(); // Allow |LeAddressManager::check_cached_commands| to complete @@ -1157,17 +1106,17 @@ TEST_F(LeImplRegisteredWithAddressManagerTest, DISABLED_clear_resolving_list) { auto view = CreateLeSecurityCommandView(hci_layer_->GetCommand()); ASSERT_TRUE(view.IsValid()); le_impl_->le_address_manager_->OnCommandComplete( - ReturnCommandComplete(OpCode::LE_CLEAR_RESOLVING_LIST, ErrorCode::SUCCESS)); + ReturnCommandComplete(OpCode::LE_CLEAR_RESOLVING_LIST, ErrorCode::SUCCESS)); } sync_handler(); // Allow |LeAddressManager::handle_next_command| to complete { auto view = - CreateLeSecurityCommandView(hci_layer_->GetCommand()); + CreateLeSecurityCommandView(hci_layer_->GetCommand()); ASSERT_TRUE(view.IsValid()); ASSERT_EQ(Enable::ENABLED, view.GetAddressResolutionEnable()); le_impl_->le_address_manager_->OnCommandComplete( - ReturnCommandComplete(OpCode::LE_SET_ADDRESS_RESOLUTION_ENABLE, ErrorCode::SUCCESS)); + ReturnCommandComplete(OpCode::LE_SET_ADDRESS_RESOLUTION_ENABLE, ErrorCode::SUCCESS)); } hci_layer_->AssertNoQueuedCommand(); } @@ -1199,14 +1148,14 @@ TEST_F(LeImplTest, on_le_connection_canceled_on_pause) { } TEST_F(LeImplTest, on_create_connection_timeout) { - EXPECT_CALL( - mock_le_connection_callbacks_, OnLeConnectFail(_, ErrorCode::CONNECTION_ACCEPT_TIMEOUT)) - .Times(1); + EXPECT_CALL(mock_le_connection_callbacks_, + OnLeConnectFail(_, ErrorCode::CONNECTION_ACCEPT_TIMEOUT)) + .Times(1); le_impl_->create_connection_timeout_alarms_.emplace( - std::piecewise_construct, - std::forward_as_tuple( - remote_public_address_with_type_.GetAddress(), remote_public_address_with_type_.GetAddressType()), - std::forward_as_tuple(handler_)); + std::piecewise_construct, + std::forward_as_tuple(remote_public_address_with_type_.GetAddress(), + remote_public_address_with_type_.GetAddressType()), + std::forward_as_tuple(handler_)); le_impl_->on_create_connection_timeout(remote_public_address_with_type_); sync_handler(); ASSERT_TRUE(le_impl_->create_connection_timeout_alarms_.empty()); @@ -1220,10 +1169,10 @@ TEST_F(LeImplTest, DISABLED_on_common_le_connection_complete__NoPriorConnection) TEST_F(LeImplTest, cancel_connect) { le_impl_->create_connection_timeout_alarms_.emplace( - std::piecewise_construct, - std::forward_as_tuple( - remote_public_address_with_type_.GetAddress(), remote_public_address_with_type_.GetAddressType()), - std::forward_as_tuple(handler_)); + std::piecewise_construct, + std::forward_as_tuple(remote_public_address_with_type_.GetAddress(), + remote_public_address_with_type_.GetAddressType()), + std::forward_as_tuple(handler_)); le_impl_->cancel_connect(remote_public_address_with_type_); sync_handler(); ASSERT_TRUE(le_impl_->create_connection_timeout_alarms_.empty()); @@ -1233,15 +1182,15 @@ TEST_F(LeImplTest, set_le_suggested_default_data_parameters) { le_impl_->set_le_suggested_default_data_parameters(kLength, kTime); sync_handler(); auto view = CreateLeConnectionManagementCommandView( - hci_layer_->GetCommand()); + hci_layer_->GetCommand()); ASSERT_TRUE(view.IsValid()); ASSERT_EQ(kLength, view.GetTxOctets()); ASSERT_EQ(kTime, view.GetTxTime()); } TEST_F(LeImplTest, LeSetDefaultSubrate) { - le_impl_->LeSetDefaultSubrate( - kIntervalMin, kIntervalMax, kLatency, kContinuationNumber, kTimeout); + le_impl_->LeSetDefaultSubrate(kIntervalMin, kIntervalMax, kLatency, kContinuationNumber, + kTimeout); sync_handler(); auto view = CreateAclCommandView(hci_layer_->GetCommand()); ASSERT_TRUE(view.IsValid()); @@ -1258,9 +1207,8 @@ class LeImplTestParameterizedByConnectionCompleteEventType : public LeImplTest, public ::testing::WithParamInterface {}; -TEST_P( - LeImplTestParameterizedByConnectionCompleteEventType, - ConnectionCompleteAsPeripheralWithAdvertisingSet) { +TEST_P(LeImplTestParameterizedByConnectionCompleteEventType, + ConnectionCompleteAsPeripheralWithAdvertisingSet) { // arrange controller_->AddSupported(hci::OpCode::LE_MULTI_ADVT); set_random_device_address_policy(); @@ -1269,46 +1217,31 @@ TEST_P( hci::Address advertiser_address; Address::FromString("A0:A1:A2:A3:A4:A5", advertiser_address); - hci::AddressWithType advertiser_address_with_type( - advertiser_address, hci::AddressType::PUBLIC_DEVICE_ADDRESS); + hci::AddressWithType advertiser_address_with_type(advertiser_address, + hci::AddressType::PUBLIC_DEVICE_ADDRESS); // expect ::testing::InSequence s; MockFunction check; std::unique_ptr connection{}; EXPECT_CALL(check, Call("terminating_advertising_set")); - EXPECT_CALL( - mock_le_connection_callbacks_, OnLeConnectSuccess(remote_public_address_with_type_, _)) - .WillOnce(WithArg<1>(::testing::Invoke( - [&](std::unique_ptr conn) { connection = std::move(conn); }))); + EXPECT_CALL(mock_le_connection_callbacks_, + OnLeConnectSuccess(remote_public_address_with_type_, _)) + .WillOnce(WithArg<1>(::testing::Invoke( + [&](std::unique_ptr conn) { connection = std::move(conn); }))); // act switch (GetParam()) { case ConnectionCompleteType::CONNECTION_COMPLETE: { hci_layer_->IncomingLeMetaEvent(LeConnectionCompleteBuilder::Create( - ErrorCode::SUCCESS, - kHciHandle, - Role::PERIPHERAL, - AddressType::PUBLIC_DEVICE_ADDRESS, - remote_address_, - 0x0024, - 0x0000, - 0x0011, - ClockAccuracy::PPM_30)); + ErrorCode::SUCCESS, kHciHandle, Role::PERIPHERAL, AddressType::PUBLIC_DEVICE_ADDRESS, + remote_address_, 0x0024, 0x0000, 0x0011, ClockAccuracy::PPM_30)); } break; case ConnectionCompleteType::ENHANCED_CONNECTION_COMPLETE: { hci_layer_->IncomingLeMetaEvent(LeEnhancedConnectionCompleteBuilder::Create( - ErrorCode::SUCCESS, - kHciHandle, - Role::PERIPHERAL, - AddressType::PUBLIC_DEVICE_ADDRESS, - remote_address_, - local_rpa_, - remote_rpa_, - 0x0024, - 0x0000, - 0x0011, - ClockAccuracy::PPM_30)); + ErrorCode::SUCCESS, kHciHandle, Role::PERIPHERAL, AddressType::PUBLIC_DEVICE_ADDRESS, + remote_address_, local_rpa_, remote_rpa_, 0x0024, 0x0000, 0x0011, + ClockAccuracy::PPM_30)); } break; default: { log::fatal("unexpected case"); @@ -1317,25 +1250,22 @@ TEST_P( sync_handler(); check.Call("terminating_advertising_set"); - le_impl_->OnAdvertisingSetTerminated( - kHciHandle, advertising_set_id, advertiser_address_with_type, false /* is_discoverable */); + le_impl_->OnAdvertisingSetTerminated(kHciHandle, advertising_set_id, advertiser_address_with_type, + false /* is_discoverable */); sync_handler(); // assert Mock::VerifyAndClearExpectations(&mock_le_connection_callbacks_); ASSERT_NE(connection, nullptr); - EXPECT_THAT( - connection->GetRoleSpecificData(), - VariantWith(Field( - "local_address", &DataAsPeripheral::local_address, Eq(advertiser_address_with_type)))); + EXPECT_THAT(connection->GetRoleSpecificData(), + VariantWith(Field("local_address", &DataAsPeripheral::local_address, + Eq(advertiser_address_with_type)))); } -INSTANTIATE_TEST_SUITE_P( - ConnectionCompleteAsPeripheralWithAdvertisingSet, - LeImplTestParameterizedByConnectionCompleteEventType, - ::testing::Values( - ConnectionCompleteType::CONNECTION_COMPLETE, - ConnectionCompleteType::ENHANCED_CONNECTION_COMPLETE)); +INSTANTIATE_TEST_SUITE_P(ConnectionCompleteAsPeripheralWithAdvertisingSet, + LeImplTestParameterizedByConnectionCompleteEventType, + ::testing::Values(ConnectionCompleteType::CONNECTION_COMPLETE, + ConnectionCompleteType::ENHANCED_CONNECTION_COMPLETE)); class LeImplTestParameterizedByDiscoverability : public LeImplTest, public ::testing::WithParamInterface {}; @@ -1348,46 +1278,35 @@ TEST_P(LeImplTestParameterizedByDiscoverability, ConnectionCompleteAsDiscoverabl // expect std::unique_ptr connection{}; - EXPECT_CALL( - mock_le_connection_callbacks_, OnLeConnectSuccess(remote_public_address_with_type_, _)) - .WillOnce(WithArg<1>(::testing::Invoke( - [&](std::unique_ptr conn) { connection = std::move(conn); }))); + EXPECT_CALL(mock_le_connection_callbacks_, + OnLeConnectSuccess(remote_public_address_with_type_, _)) + .WillOnce(WithArg<1>(::testing::Invoke( + [&](std::unique_ptr conn) { connection = std::move(conn); }))); // act hci_layer_->IncomingLeMetaEvent(LeConnectionCompleteBuilder::Create( - ErrorCode::SUCCESS, - kHciHandle, - Role::PERIPHERAL, - AddressType::PUBLIC_DEVICE_ADDRESS, - remote_address_, - 0x0024, - 0x0000, - 0x0011, - ClockAccuracy::PPM_30)); + ErrorCode::SUCCESS, kHciHandle, Role::PERIPHERAL, AddressType::PUBLIC_DEVICE_ADDRESS, + remote_address_, 0x0024, 0x0000, 0x0011, ClockAccuracy::PPM_30)); // the sync is needed since otherwise the OnAdvertisingSetTerminated() event arrives first, due to // handler indirection (2 hops vs 1 hop) this isn't a bug in production since there we'd have: // 1. Connection Complete: HCI -> LE_IMPL (2 hops) // 2. Advertising Set Terminated: HCI -> ADV -> LE_IMPL (3 hops) // so this sync is only needed in test sync_handler(); - le_impl_->OnAdvertisingSetTerminated( - kHciHandle, 1 /* advertiser_set_id */, fixed_address_, is_discoverable); + le_impl_->OnAdvertisingSetTerminated(kHciHandle, 1 /* advertiser_set_id */, fixed_address_, + is_discoverable); sync_handler(); // assert ASSERT_NE(connection, nullptr); - EXPECT_THAT( - connection->GetRoleSpecificData(), - VariantWith(Field( - "connected_to_discoverable", - &DataAsPeripheral::connected_to_discoverable, - Eq(is_discoverable)))); + EXPECT_THAT(connection->GetRoleSpecificData(), + VariantWith(Field("connected_to_discoverable", + &DataAsPeripheral::connected_to_discoverable, + Eq(is_discoverable)))); } -INSTANTIATE_TEST_SUITE_P( - LeImplTestParameterizedByDiscoverability, - LeImplTestParameterizedByDiscoverability, - ::testing::Values(false, true)); +INSTANTIATE_TEST_SUITE_P(LeImplTestParameterizedByDiscoverability, + LeImplTestParameterizedByDiscoverability, ::testing::Values(false, true)); TEST_F(LeImplTest, ConnectionCompleteAcceptlistCallback) { // arrange @@ -1403,17 +1322,8 @@ TEST_F(LeImplTest, ConnectionCompleteAcceptlistCallback) { // act auto command = LeEnhancedConnectionCompleteBuilder::Create( - ErrorCode::SUCCESS, - kHciHandle, - Role::PERIPHERAL, - AddressType::PUBLIC_DEVICE_ADDRESS, - remote_address_, - local_rpa_, - remote_rpa_, - 0x0024, - 0x0000, - 0x0011, - ClockAccuracy::PPM_30); + ErrorCode::SUCCESS, kHciHandle, Role::PERIPHERAL, AddressType::PUBLIC_DEVICE_ADDRESS, + remote_address_, local_rpa_, remote_rpa_, 0x0024, 0x0000, 0x0011, ClockAccuracy::PPM_30); auto bytes = Serialize(std::move(command)); auto view = CreateLeEventView(bytes); ASSERT_TRUE(view.IsValid()); @@ -1434,8 +1344,8 @@ TEST_F(LeImplTest, ResolvingListCallback) { EXPECT_CALL(callbacks, OnResolvingListChange()).Times(1); // act - le_impl_->add_device_to_resolving_list( - remote_public_address_with_type_, kPeerIdentityResolvingKey, kLocalIdentityResolvingKey); + le_impl_->add_device_to_resolving_list(remote_public_address_with_type_, + kPeerIdentityResolvingKey, kLocalIdentityResolvingKey); // assert Mock::VerifyAndClearExpectations(&callbacks); @@ -1451,24 +1361,16 @@ TEST_F(LeImplTest, ConnectionFailedAcceptlistCallback) { AddressWithType remote_address; ErrorCode reason; EXPECT_CALL(callbacks, OnLeConnectFail(_, _)) - .WillOnce([&](AddressWithType addr, ErrorCode error) { - remote_address = addr; - reason = error; - }); + .WillOnce([&](AddressWithType addr, ErrorCode error) { + remote_address = addr; + reason = error; + }); // act auto command = LeEnhancedConnectionCompleteBuilder::Create( - ErrorCode::CONTROLLER_BUSY, - kHciHandle, - Role::PERIPHERAL, - AddressType::PUBLIC_DEVICE_ADDRESS, - remote_address_, - local_rpa_, - remote_rpa_, - 0x0024, - 0x0000, - 0x0011, - ClockAccuracy::PPM_30); + ErrorCode::CONTROLLER_BUSY, kHciHandle, Role::PERIPHERAL, + AddressType::PUBLIC_DEVICE_ADDRESS, remote_address_, local_rpa_, remote_rpa_, 0x0024, + 0x0000, 0x0011, ClockAccuracy::PPM_30); auto bytes = Serialize(std::move(command)); auto view = CreateLeEventView(bytes); ASSERT_TRUE(view.IsValid()); @@ -1490,26 +1392,17 @@ TEST_F(LeImplTest, DisconnectionAcceptlistCallback) { // we need to capture the LeAclConnection so it is not immediately dropped => disconnected std::unique_ptr connection; EXPECT_CALL(mock_le_connection_callbacks_, OnLeConnectSuccess(_, _)) - .WillOnce([&](AddressWithType, std::unique_ptr conn) { - connection = std::move(conn); - connection->RegisterCallbacks(&connection_management_callbacks_, handler_); - }); + .WillOnce([&](AddressWithType, std::unique_ptr conn) { + connection = std::move(conn); + connection->RegisterCallbacks(&connection_management_callbacks_, handler_); + }); // arrange: an active connection to a peer le_impl_->handle_register_le_acceptlist_callbacks(&callbacks); set_random_device_address_policy(); auto command = LeEnhancedConnectionCompleteBuilder::Create( - ErrorCode::SUCCESS, - kHciHandle, - Role::PERIPHERAL, - AddressType::PUBLIC_DEVICE_ADDRESS, - remote_address_, - local_rpa_, - remote_rpa_, - 0x0024, - 0x0000, - 0x0011, - ClockAccuracy::PPM_30); + ErrorCode::SUCCESS, kHciHandle, Role::PERIPHERAL, AddressType::PUBLIC_DEVICE_ADDRESS, + remote_address_, local_rpa_, remote_rpa_, 0x0024, 0x0000, 0x0011, ClockAccuracy::PPM_30); auto bytes = Serialize(std::move(command)); auto view = CreateLeEventView(bytes); ASSERT_TRUE(view.IsValid()); @@ -1528,14 +1421,14 @@ TEST_F(LeImplTest, DisconnectionAcceptlistCallback) { TEST_F(LeImplTest, direct_connection_after_background_connection) { set_random_device_address_policy(); - hci::AddressWithType address( - {0x21, 0x22, 0x23, 0x24, 0x25, 0x26}, AddressType::PUBLIC_DEVICE_ADDRESS); + hci::AddressWithType address({0x21, 0x22, 0x23, 0x24, 0x25, 0x26}, + AddressType::PUBLIC_DEVICE_ADDRESS); // arrange: Create background connection le_impl_->create_le_connection(address, true, /* is_direct */ false); hci_layer_->GetCommand(OpCode::LE_ADD_DEVICE_TO_FILTER_ACCEPT_LIST); hci_layer_->IncomingEvent( - LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); + LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); auto raw_bg_create_connection = hci_layer_->GetCommand(OpCode::LE_CREATE_CONNECTION); hci_layer_->IncomingEvent(LeCreateConnectionStatusBuilder::Create(ErrorCode::SUCCESS, 0x01)); sync_handler(); @@ -1545,27 +1438,22 @@ TEST_F(LeImplTest, direct_connection_after_background_connection) { auto cancel_connection = hci_layer_->GetCommand(OpCode::LE_CREATE_CONNECTION_CANCEL); if (cancel_connection.IsValid()) { hci_layer_->IncomingEvent( - LeCreateConnectionCancelCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); + LeCreateConnectionCancelCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); hci_layer_->IncomingLeMetaEvent(LeConnectionCompleteBuilder::Create( - ErrorCode::UNKNOWN_CONNECTION, - kHciHandle, - Role::CENTRAL, - AddressType::PUBLIC_DEVICE_ADDRESS, - Address::kEmpty, - 0x0000, - 0x0000, - 0x0000, - ClockAccuracy::PPM_30)); + ErrorCode::UNKNOWN_CONNECTION, kHciHandle, Role::CENTRAL, + AddressType::PUBLIC_DEVICE_ADDRESS, Address::kEmpty, 0x0000, 0x0000, 0x0000, + ClockAccuracy::PPM_30)); } auto raw_direct_create_connection = hci_layer_->GetCommand(OpCode::LE_CREATE_CONNECTION); // assert - auto bg_create_connection = LeCreateConnectionView::Create( - LeConnectionManagementCommandView::Create(AclCommandView::Create(raw_bg_create_connection))); + auto bg_create_connection = + LeCreateConnectionView::Create(LeConnectionManagementCommandView::Create( + AclCommandView::Create(raw_bg_create_connection))); EXPECT_TRUE(bg_create_connection.IsValid()); auto direct_create_connection = - LeCreateConnectionView::Create(LeConnectionManagementCommandView::Create( - AclCommandView::Create(raw_direct_create_connection))); + LeCreateConnectionView::Create(LeConnectionManagementCommandView::Create( + AclCommandView::Create(raw_direct_create_connection))); EXPECT_TRUE(direct_create_connection.IsValid()); log::info("Scan Interval {}", direct_create_connection.GetLeScanInterval()); ASSERT_NE(direct_create_connection.GetLeScanInterval(), bg_create_connection.GetLeScanInterval()); diff --git a/system/gd/hci/acl_manager/round_robin_scheduler.cc b/system/gd/hci/acl_manager/round_robin_scheduler.cc index 242b0623855..77707f8b22c 100644 --- a/system/gd/hci/acl_manager/round_robin_scheduler.cc +++ b/system/gd/hci/acl_manager/round_robin_scheduler.cc @@ -23,8 +23,8 @@ namespace bluetooth { namespace hci { namespace acl_manager { -RoundRobinScheduler::RoundRobinScheduler( - os::Handler* handler, Controller* controller, common::BidiQueueEnd* hci_queue_end) +RoundRobinScheduler::RoundRobinScheduler(os::Handler* handler, Controller* controller, + common::BidiQueueEnd* hci_queue_end) : handler_(handler), controller_(controller), hci_queue_end_(hci_queue_end) { max_acl_packet_credits_ = controller_->GetNumAclPacketBuffers(); acl_packet_credits_ = max_acl_packet_credits_; @@ -33,7 +33,8 @@ RoundRobinScheduler::RoundRobinScheduler( le_max_acl_packet_credits_ = le_buffer_size.total_num_le_packets_; le_acl_packet_credits_ = le_max_acl_packet_credits_; le_hci_mtu_ = le_buffer_size.le_data_packet_length_; - controller_->RegisterCompletedAclPacketsCallback(handler->BindOn(this, &RoundRobinScheduler::incoming_acl_credits)); + controller_->RegisterCompletedAclPacketsCallback( + handler->BindOn(this, &RoundRobinScheduler::incoming_acl_credits)); } RoundRobinScheduler::~RoundRobinScheduler() { @@ -43,20 +44,19 @@ RoundRobinScheduler::~RoundRobinScheduler() { void RoundRobinScheduler::Register(ConnectionType connection_type, uint16_t handle, std::shared_ptr queue) { - log::assert_that( - acl_queue_handlers_.count(handle) == 0, - "assert failed: acl_queue_handlers_.count(handle) == 0"); + log::assert_that(acl_queue_handlers_.count(handle) == 0, + "assert failed: acl_queue_handlers_.count(handle) == 0"); acl_queue_handler acl_queue_handler = {connection_type, std::move(queue), false, 0}; - acl_queue_handlers_.insert(std::pair(handle, acl_queue_handler)); + acl_queue_handlers_.insert( + std::pair(handle, acl_queue_handler)); if (fragments_to_send_.size() == 0) { start_round_robin(); } } void RoundRobinScheduler::Unregister(uint16_t handle) { - log::assert_that( - acl_queue_handlers_.count(handle) == 1, - "assert failed: acl_queue_handlers_.count(handle) == 1"); + log::assert_that(acl_queue_handlers_.count(handle) == 1, + "assert failed: acl_queue_handlers_.count(handle) == 1"); auto acl_queue_handler = acl_queue_handlers_.find(handle)->second; // Reclaim outstanding packets if (acl_queue_handler.connection_type_ == ConnectionType::CLASSIC) { @@ -83,13 +83,9 @@ void RoundRobinScheduler::SetLinkPriority(uint16_t handle, bool high_priority) { acl_queue_handler->second.high_priority_ = high_priority; } -uint16_t RoundRobinScheduler::GetCredits() { - return acl_packet_credits_; -} +uint16_t RoundRobinScheduler::GetCredits() { return acl_packet_credits_; } -uint16_t RoundRobinScheduler::GetLeCredits() { - return le_acl_packet_credits_; -} +uint16_t RoundRobinScheduler::GetLeCredits() { return le_acl_packet_credits_; } void RoundRobinScheduler::start_round_robin() { if (acl_packet_credits_ == 0 && le_acl_packet_credits_ == 0) { @@ -97,7 +93,8 @@ void RoundRobinScheduler::start_round_robin() { } if (!fragments_to_send_.empty()) { auto connection_type = fragments_to_send_.front().first; - bool classic_buffer_full = acl_packet_credits_ == 0 && connection_type == ConnectionType::CLASSIC; + bool classic_buffer_full = + acl_packet_credits_ == 0 && connection_type == ConnectionType::CLASSIC; bool le_buffer_full = le_acl_packet_credits_ == 0 && connection_type == ConnectionType::LE; if (classic_buffer_full || le_buffer_full) { log::warn("Buffer of connection_type {} is full", connection_type); @@ -119,14 +116,17 @@ void RoundRobinScheduler::start_round_robin() { for (auto acl_queue_handler = starting_point_; count > 0; count--) { // Prevent registration when credits is zero bool classic_buffer_full = - acl_packet_credits_ == 0 && acl_queue_handler->second.connection_type_ == ConnectionType::CLASSIC; - bool le_buffer_full = - le_acl_packet_credits_ == 0 && acl_queue_handler->second.connection_type_ == ConnectionType::LE; - if (!acl_queue_handler->second.dequeue_is_registered_ && !classic_buffer_full && !le_buffer_full) { + acl_packet_credits_ == 0 && + acl_queue_handler->second.connection_type_ == ConnectionType::CLASSIC; + bool le_buffer_full = le_acl_packet_credits_ == 0 && + acl_queue_handler->second.connection_type_ == ConnectionType::LE; + if (!acl_queue_handler->second.dequeue_is_registered_ && !classic_buffer_full && + !le_buffer_full) { acl_queue_handler->second.dequeue_is_registered_ = true; uint16_t acl_handle = acl_queue_handler->first; acl_queue_handler->second.queue_->GetDownEnd()->RegisterDequeue( - handler_, common::Bind(&RoundRobinScheduler::buffer_packet, common::Unretained(this), acl_handle)); + handler_, common::Bind(&RoundRobinScheduler::buffer_packet, common::Unretained(this), + acl_handle)); } acl_queue_handler = std::next(acl_queue_handler); if (acl_queue_handler == acl_queue_handlers_.end()) { @@ -140,7 +140,7 @@ void RoundRobinScheduler::start_round_robin() { void RoundRobinScheduler::buffer_packet(uint16_t acl_handle) { BroadcastFlag broadcast_flag = BroadcastFlag::POINT_TO_POINT; auto acl_queue_handler = acl_queue_handlers_.find(acl_handle); - if( acl_queue_handler == acl_queue_handlers_.end()) { + if (acl_queue_handler == acl_queue_handlers_.end()) { log::error("Ignore since ACL connection vanished with handle: 0x{:X}", acl_handle); return; } @@ -152,24 +152,24 @@ void RoundRobinScheduler::buffer_packet(uint16_t acl_handle) { ConnectionType connection_type = acl_queue_handler->second.connection_type_; size_t mtu = connection_type == ConnectionType::CLASSIC ? hci_mtu_ : le_hci_mtu_; - PacketBoundaryFlag packet_boundary_flag = (packet->IsFlushable()) - ? PacketBoundaryFlag::FIRST_AUTOMATICALLY_FLUSHABLE - : PacketBoundaryFlag::FIRST_NON_AUTOMATICALLY_FLUSHABLE; + PacketBoundaryFlag packet_boundary_flag = + (packet->IsFlushable()) ? PacketBoundaryFlag::FIRST_AUTOMATICALLY_FLUSHABLE + : PacketBoundaryFlag::FIRST_NON_AUTOMATICALLY_FLUSHABLE; int acl_priority = acl_queue_handler->second.high_priority_ ? 1 : 0; if (packet->size() <= mtu) { fragments_to_send_.push( - std::make_pair( - connection_type, AclBuilder::Create(handle, packet_boundary_flag, broadcast_flag, std::move(packet))), - acl_priority); + std::make_pair(connection_type, AclBuilder::Create(handle, packet_boundary_flag, + broadcast_flag, std::move(packet))), + acl_priority); } else { auto fragments = AclFragmenter(mtu, std::move(packet)).GetFragments(); for (size_t i = 0; i < fragments.size(); i++) { fragments_to_send_.push( - std::make_pair( - connection_type, - AclBuilder::Create(handle, packet_boundary_flag, broadcast_flag, std::move(fragments[i]))), - acl_priority); + std::make_pair(connection_type, + AclBuilder::Create(handle, packet_boundary_flag, broadcast_flag, + std::move(fragments[i]))), + acl_priority); packet_boundary_flag = PacketBoundaryFlag::CONTINUING_FRAGMENT; } } @@ -181,7 +181,8 @@ void RoundRobinScheduler::buffer_packet(uint16_t acl_handle) { } void RoundRobinScheduler::unregister_all_connections() { - for (auto acl_queue_handler = acl_queue_handlers_.begin(); acl_queue_handler != acl_queue_handlers_.end(); + for (auto acl_queue_handler = acl_queue_handlers_.begin(); + acl_queue_handler != acl_queue_handlers_.end(); acl_queue_handler = std::next(acl_queue_handler)) { if (acl_queue_handler->second.dequeue_is_registered_) { acl_queue_handler->second.dequeue_is_registered_ = false; @@ -192,8 +193,9 @@ void RoundRobinScheduler::unregister_all_connections() { void RoundRobinScheduler::send_next_fragment() { if (!enqueue_registered_.exchange(true)) { - hci_queue_end_->RegisterEnqueue( - handler_, common::Bind(&RoundRobinScheduler::handle_enqueue_next_fragment, common::Unretained(this))); + hci_queue_end_->RegisterEnqueue(handler_, + common::Bind(&RoundRobinScheduler::handle_enqueue_next_fragment, + common::Unretained(this))); } } @@ -214,10 +216,12 @@ std::unique_ptr RoundRobinScheduler::handle_enqueue_next_fragment() if (enqueue_registered_.exchange(false)) { hci_queue_end_->UnregisterEnqueue(); } - handler_->Post(common::BindOnce(&RoundRobinScheduler::start_round_robin, common::Unretained(this))); + handler_->Post( + common::BindOnce(&RoundRobinScheduler::start_round_robin, common::Unretained(this))); } else { ConnectionType next_connection_type = fragments_to_send_.front().first; - bool classic_buffer_full = next_connection_type == ConnectionType::CLASSIC && acl_packet_credits_ == 0; + bool classic_buffer_full = + next_connection_type == ConnectionType::CLASSIC && acl_packet_credits_ == 0; bool le_buffer_full = next_connection_type == ConnectionType::LE && le_acl_packet_credits_ == 0; if ((classic_buffer_full || le_buffer_full) && enqueue_registered_.exchange(false)) { hci_queue_end_->UnregisterEnqueue(); diff --git a/system/gd/hci/acl_manager/round_robin_scheduler.h b/system/gd/hci/acl_manager/round_robin_scheduler.h index 056f9255fd1..a2c11d74b7e 100644 --- a/system/gd/hci/acl_manager/round_robin_scheduler.h +++ b/system/gd/hci/acl_manager/round_robin_scheduler.h @@ -31,9 +31,9 @@ namespace hci { namespace acl_manager { class RoundRobinScheduler { - public: - RoundRobinScheduler( - os::Handler* handler, Controller* controller, common::BidiQueueEnd* hci_queue_end); +public: + RoundRobinScheduler(os::Handler* handler, Controller* controller, + common::BidiQueueEnd* hci_queue_end); ~RoundRobinScheduler(); enum ConnectionType { CLASSIC, LE }; @@ -53,7 +53,7 @@ class RoundRobinScheduler { uint16_t GetCredits(); uint16_t GetLeCredits(); - private: +private: void start_round_robin(); void buffer_packet(uint16_t acl_handle); void unregister_all_connections(); @@ -64,7 +64,8 @@ class RoundRobinScheduler { os::Handler* handler_ = nullptr; Controller* controller_ = nullptr; std::map acl_queue_handlers_; - common::MultiPriorityQueue>, 2> fragments_to_send_; + common::MultiPriorityQueue>, 2> + fragments_to_send_; uint16_t max_acl_packet_credits_ = 0; uint16_t acl_packet_credits_ = 0; uint16_t le_max_acl_packet_credits_ = 0; diff --git a/system/gd/hci/acl_manager/round_robin_scheduler_test.cc b/system/gd/hci/acl_manager/round_robin_scheduler_test.cc index 0683b466837..210cc71125a 100644 --- a/system/gd/hci/acl_manager/round_robin_scheduler_test.cc +++ b/system/gd/hci/acl_manager/round_robin_scheduler_test.cc @@ -39,14 +39,10 @@ namespace acl_manager { namespace { class TestController : public Controller { - public: - uint16_t GetNumAclPacketBuffers() const { - return max_acl_packet_credits_; - } +public: + uint16_t GetNumAclPacketBuffers() const { return max_acl_packet_credits_; } - uint16_t GetAclPacketLength() const { - return hci_mtu_; - } + uint16_t GetAclPacketLength() const { return hci_mtu_; } LeBufferSize GetLeBufferSize() const { LeBufferSize le_buffer_size; @@ -63,28 +59,27 @@ class TestController : public Controller { acl_credits_callback_(handle, credits); } - void UnregisterCompletedAclPacketsCallback() { - acl_credits_callback_ = {}; - } + void UnregisterCompletedAclPacketsCallback() { acl_credits_callback_ = {}; } const uint16_t max_acl_packet_credits_ = 10; const uint16_t hci_mtu_ = 1024; const uint16_t le_max_acl_packet_credits_ = 15; const uint16_t le_hci_mtu_ = 27; - private: +private: CompletedAclPacketsCallback acl_credits_callback_; }; class RoundRobinSchedulerTest : public ::testing::Test { - public: +public: void SetUp() override { thread_ = new Thread("thread", Thread::Priority::NORMAL); handler_ = new Handler(thread_); controller_ = new TestController(); round_robin_scheduler_ = new RoundRobinScheduler(handler_, controller_, hci_queue_.GetUpEnd()); hci_queue_.GetDownEnd()->RegisterDequeue( - handler_, common::Bind(&RoundRobinSchedulerTest::HciDownEndDequeue, common::Unretained(this))); + handler_, + common::Bind(&RoundRobinSchedulerTest::HciDownEndDequeue, common::Unretained(this))); } void TearDown() override { @@ -98,9 +93,8 @@ class RoundRobinSchedulerTest : public ::testing::Test { void sync_handler() { log::assert_that(thread_ != nullptr, "assert failed: thread_ != nullptr"); - log::assert_that( - thread_->GetReactor()->WaitForIdle(2s), - "assert failed: thread_->GetReactor()->WaitForIdle(2s)"); + log::assert_that(thread_->GetReactor()->WaitForIdle(2s), + "assert failed: thread_->GetReactor()->WaitForIdle(2s)"); } void EnqueueAclUpEnd(AclConnection::QueueUpEnd* queue_up_end, std::vector packet) { @@ -109,18 +103,19 @@ class RoundRobinSchedulerTest : public ::testing::Test { } enqueue_promise_ = std::make_unique>(); enqueue_future_ = std::make_unique>(enqueue_promise_->get_future()); - queue_up_end->RegisterEnqueue(handler_, common::Bind(&RoundRobinSchedulerTest::enqueue_callback, - common::Unretained(this), queue_up_end, packet)); + queue_up_end->RegisterEnqueue(handler_, + common::Bind(&RoundRobinSchedulerTest::enqueue_callback, + common::Unretained(this), queue_up_end, packet)); } - std::unique_ptr enqueue_callback(AclConnection::QueueUpEnd* queue_up_end, - std::vector packet) { + std::unique_ptr enqueue_callback( + AclConnection::QueueUpEnd* queue_up_end, std::vector packet) { auto packet_one = std::make_unique(2000); packet_one->AddOctets(packet); queue_up_end->UnregisterEnqueue(); enqueue_promise_->set_value(); return packet_one; - }; + } void HciDownEndDequeue() { auto packet = hci_queue_.GetDownEnd()->TryDequeue(); @@ -178,14 +173,16 @@ TEST_F(RoundRobinSchedulerTest, startup_teardown) {} TEST_F(RoundRobinSchedulerTest, register_unregister_connection) { uint16_t handle = 0x01; auto connection_queue = std::make_shared(10); - round_robin_scheduler_->Register(RoundRobinScheduler::ConnectionType::CLASSIC, handle, connection_queue); + round_robin_scheduler_->Register(RoundRobinScheduler::ConnectionType::CLASSIC, handle, + connection_queue); round_robin_scheduler_->Unregister(handle); } TEST_F(RoundRobinSchedulerTest, buffer_packet) { uint16_t handle = 0x01; auto connection_queue = std::make_shared(10); - round_robin_scheduler_->Register(RoundRobinScheduler::ConnectionType::CLASSIC, handle, connection_queue); + round_robin_scheduler_->Register(RoundRobinScheduler::ConnectionType::CLASSIC, handle, + connection_queue); ASSERT_NO_FATAL_FAILURE(SetPacketFuture(2)); AclConnection::QueueUpEnd* queue_up_end = connection_queue->GetUpEnd(); @@ -208,8 +205,10 @@ TEST_F(RoundRobinSchedulerTest, buffer_packet_from_two_connections) { auto connection_queue = std::make_shared(10); auto le_connection_queue = std::make_shared(10); - round_robin_scheduler_->Register(RoundRobinScheduler::ConnectionType::CLASSIC, handle, connection_queue); - round_robin_scheduler_->Register(RoundRobinScheduler::ConnectionType::LE, le_handle, le_connection_queue); + round_robin_scheduler_->Register(RoundRobinScheduler::ConnectionType::CLASSIC, handle, + connection_queue); + round_robin_scheduler_->Register(RoundRobinScheduler::ConnectionType::LE, le_handle, + le_connection_queue); ASSERT_NO_FATAL_FAILURE(SetPacketFuture(2)); AclConnection::QueueUpEnd* queue_up_end = connection_queue->GetUpEnd(); @@ -232,7 +231,8 @@ TEST_F(RoundRobinSchedulerTest, buffer_packet_from_two_connections) { TEST_F(RoundRobinSchedulerTest, do_not_register_when_credits_is_zero) { uint16_t handle = 0x01; auto connection_queue = std::make_shared(15); - round_robin_scheduler_->Register(RoundRobinScheduler::ConnectionType::CLASSIC, handle, connection_queue); + round_robin_scheduler_->Register(RoundRobinScheduler::ConnectionType::CLASSIC, handle, + connection_queue); ASSERT_NO_FATAL_FAILURE(SetPacketFuture(10)); AclConnection::QueueUpEnd* queue_up_end = connection_queue->GetUpEnd(); @@ -284,10 +284,14 @@ TEST_F(RoundRobinSchedulerTest, buffer_packet_intervally) { AclConnection::QueueUpEnd* le_queue_up_end1 = le_connection_queue1->GetUpEnd(); AclConnection::QueueUpEnd* le_queue_up_end2 = le_connection_queue2->GetUpEnd(); - round_robin_scheduler_->Register(RoundRobinScheduler::ConnectionType::CLASSIC, handle1, connection_queue1); - round_robin_scheduler_->Register(RoundRobinScheduler::ConnectionType::CLASSIC, handle2, connection_queue2); - round_robin_scheduler_->Register(RoundRobinScheduler::ConnectionType::LE, le_handle1, le_connection_queue1); - round_robin_scheduler_->Register(RoundRobinScheduler::ConnectionType::LE, le_handle2, le_connection_queue2); + round_robin_scheduler_->Register(RoundRobinScheduler::ConnectionType::CLASSIC, handle1, + connection_queue1); + round_robin_scheduler_->Register(RoundRobinScheduler::ConnectionType::CLASSIC, handle2, + connection_queue2); + round_robin_scheduler_->Register(RoundRobinScheduler::ConnectionType::LE, le_handle1, + le_connection_queue1); + round_robin_scheduler_->Register(RoundRobinScheduler::ConnectionType::LE, le_handle2, + le_connection_queue2); std::vector packet = {0x01, 0x02, 0x03}; EnqueueAclUpEnd(queue_up_end1, packet); @@ -332,8 +336,10 @@ TEST_F(RoundRobinSchedulerTest, send_fragments_without_interval) { auto connection_queue = std::make_shared(10); auto le_connection_queue = std::make_shared(10); - round_robin_scheduler_->Register(RoundRobinScheduler::ConnectionType::CLASSIC, handle, connection_queue); - round_robin_scheduler_->Register(RoundRobinScheduler::ConnectionType::LE, le_handle, le_connection_queue); + round_robin_scheduler_->Register(RoundRobinScheduler::ConnectionType::CLASSIC, handle, + connection_queue); + round_robin_scheduler_->Register(RoundRobinScheduler::ConnectionType::LE, le_handle, + le_connection_queue); ASSERT_NO_FATAL_FAILURE(SetPacketFuture(5)); AclConnection::QueueUpEnd* queue_up_end = connection_queue->GetUpEnd(); @@ -378,11 +384,13 @@ TEST_F(RoundRobinSchedulerTest, receive_le_credit_when_next_fragment_is_classic) auto connection_queue = std::make_shared(20); auto le_connection_queue = std::make_shared(20); - round_robin_scheduler_->Register(RoundRobinScheduler::ConnectionType::CLASSIC, handle, connection_queue); - round_robin_scheduler_->Register(RoundRobinScheduler::ConnectionType::LE, le_handle, le_connection_queue); + round_robin_scheduler_->Register(RoundRobinScheduler::ConnectionType::CLASSIC, handle, + connection_queue); + round_robin_scheduler_->Register(RoundRobinScheduler::ConnectionType::LE, le_handle, + le_connection_queue); - ASSERT_NO_FATAL_FAILURE( - SetPacketFuture(controller_->le_max_acl_packet_credits_ + controller_->max_acl_packet_credits_)); + ASSERT_NO_FATAL_FAILURE(SetPacketFuture(controller_->le_max_acl_packet_credits_ + + controller_->max_acl_packet_credits_)); AclConnection::QueueUpEnd* queue_up_end = connection_queue->GetUpEnd(); AclConnection::QueueUpEnd* le_queue_up_end = le_connection_queue->GetUpEnd(); std::vector huge_packet(2000); diff --git a/system/gd/hci/acl_manager_mock.h b/system/gd/hci/acl_manager_mock.h index d19a9156fd9..b02a50c382e 100644 --- a/system/gd/hci/acl_manager_mock.h +++ b/system/gd/hci/acl_manager_mock.h @@ -15,6 +15,8 @@ */ #pragma once +#include + #include "hci/acl_manager.h" #include "hci/acl_manager/classic_acl_connection.h" #include "hci/acl_manager/connection_callbacks.h" @@ -23,8 +25,6 @@ #include "hci/acl_manager/le_connection_callbacks.h" #include "hci/acl_manager/le_connection_management_callbacks.h" -#include - // Unit test interfaces namespace bluetooth { namespace hci { @@ -39,49 +39,47 @@ using acl_manager::ConnectionCallbacks; using acl_manager::ConnectionManagementCallbacks; class MockClassicAclConnection : public ClassicAclConnection { - public: +public: MOCK_METHOD(Address, GetAddress, (), (const, override)); MOCK_METHOD(bool, Disconnect, (DisconnectReason reason), (override)); - MOCK_METHOD(void, RegisterCallbacks, (ConnectionManagementCallbacks * callbacks, os::Handler* handler), (override)); + MOCK_METHOD(void, RegisterCallbacks, + (ConnectionManagementCallbacks * callbacks, os::Handler* handler), (override)); MOCK_METHOD(bool, ReadRemoteVersionInformation, (), (override)); MOCK_METHOD(bool, ReadRemoteSupportedFeatures, (), (override)); MOCK_METHOD(bool, ReadRemoteExtendedFeatures, (uint8_t), (override)); - QueueUpEnd* GetAclQueueEnd() const override { - return acl_queue_.GetUpEnd(); - } + QueueUpEnd* GetAclQueueEnd() const override { return acl_queue_.GetUpEnd(); } mutable common::BidiQueue, BasePacketBuilder> acl_queue_{10}; }; class MockLeAclConnection : public LeAclConnection { - public: +public: MOCK_METHOD(AddressWithType, GetLocalAddress, (), (const, override)); MOCK_METHOD(AddressWithType, GetRemoteAddress, (), (const, override)); MOCK_METHOD(void, Disconnect, (DisconnectReason reason), (override)); - MOCK_METHOD(void, RegisterCallbacks, (LeConnectionManagementCallbacks * callbacks, os::Handler* handler), (override)); + MOCK_METHOD(void, RegisterCallbacks, + (LeConnectionManagementCallbacks * callbacks, os::Handler* handler), (override)); MOCK_METHOD(bool, ReadRemoteVersionInformation, (), (override)); - QueueUpEnd* GetAclQueueEnd() const override { - return acl_queue_.GetUpEnd(); - } + QueueUpEnd* GetAclQueueEnd() const override { return acl_queue_.GetUpEnd(); } mutable common::BidiQueue, BasePacketBuilder> acl_queue_{10}; }; class MockAclManager : public AclManager { - public: - MOCK_METHOD(void, RegisterCallbacks, (ConnectionCallbacks * callbacks, os::Handler* handler), (override)); - MOCK_METHOD(void, RegisterLeCallbacks, (LeConnectionCallbacks * callbacks, os::Handler* handler), (override)); +public: + MOCK_METHOD(void, RegisterCallbacks, (ConnectionCallbacks * callbacks, os::Handler* handler), + (override)); + MOCK_METHOD(void, RegisterLeCallbacks, (LeConnectionCallbacks * callbacks, os::Handler* handler), + (override)); MOCK_METHOD(void, CreateConnection, (Address address), (override)); - MOCK_METHOD(void, CreateLeConnection, (AddressWithType address_with_type, bool is_direct), (override)); + MOCK_METHOD(void, CreateLeConnection, (AddressWithType address_with_type, bool is_direct), + (override)); MOCK_METHOD(void, CancelConnect, (Address address), (override)); - MOCK_METHOD( - void, - SetPrivacyPolicyForInitiatorAddress, - (LeAddressManager::AddressPolicy address_policy, - AddressWithType fixed_address, - std::chrono::milliseconds minimum_rotation_time, - std::chrono::milliseconds maximum_rotation_time), - (override)); + MOCK_METHOD(void, SetPrivacyPolicyForInitiatorAddress, + (LeAddressManager::AddressPolicy address_policy, AddressWithType fixed_address, + std::chrono::milliseconds minimum_rotation_time, + std::chrono::milliseconds maximum_rotation_time), + (override)); }; } // namespace testing diff --git a/system/gd/hci/acl_manager_test.cc b/system/gd/hci/acl_manager_test.cc index ac6ebc0a2cd..13d9b4a1d56 100644 --- a/system/gd/hci/acl_manager_test.cc +++ b/system/gd/hci/acl_manager_test.cc @@ -65,27 +65,20 @@ namespace hci { namespace acl_manager { class TestController : public testing::MockController { - public: +public: void RegisterCompletedAclPacketsCallback( - common::ContextualCallback cb) override { + common::ContextualCallback cb) + override { acl_cb_ = cb; } - void UnregisterCompletedAclPacketsCallback() override { - acl_cb_ = {}; - } + void UnregisterCompletedAclPacketsCallback() override { acl_cb_ = {}; } - uint16_t GetAclPacketLength() const override { - return acl_buffer_length_; - } + uint16_t GetAclPacketLength() const override { return acl_buffer_length_; } - uint16_t GetNumAclPacketBuffers() const override { - return total_acl_buffers_; - } + uint16_t GetNumAclPacketBuffers() const override { return total_acl_buffers_; } - bool IsSupported(bluetooth::hci::OpCode /* op_code */) const override { - return false; - } + bool IsSupported(bluetooth::hci::OpCode /* op_code */) const override { return false; } LeBufferSize GetLeBufferSize() const override { LeBufferSize le_buffer_size; @@ -94,22 +87,20 @@ class TestController : public testing::MockController { return le_buffer_size; } - void CompletePackets(uint16_t handle, uint16_t packets) { - acl_cb_(handle, packets); - } + void CompletePackets(uint16_t handle, uint16_t packets) { acl_cb_(handle, packets); } uint16_t acl_buffer_length_ = 1024; uint16_t total_acl_buffers_ = 2; common::ContextualCallback acl_cb_; - protected: +protected: void Start() override {} void Stop() override {} void ListDependencies(ModuleList* /* list */) const {} }; class AclManagerNoCallbacksTest : public ::testing::Test { - protected: +protected: void SetUp() override { test_hci_layer_ = new HciLayerFake; // Ownership is transferred to registry test_controller_ = new TestController; // Ownership is transferred to registry @@ -124,7 +115,8 @@ class AclManagerNoCallbacksTest : public ::testing::Test { client_handler_ = fake_registry_.GetTestModuleHandler(&HciLayer::Factory); ASSERT_NE(client_handler_, nullptr); fake_registry_.Start(&thread_); - acl_manager_ = static_cast(fake_registry_.GetModuleUnderTest(&AclManager::Factory)); + acl_manager_ = + static_cast(fake_registry_.GetModuleUnderTest(&AclManager::Factory)); Address::FromString("A1:A2:A3:A4:A5:A6", remote); hci::Address address; @@ -133,27 +125,26 @@ class AclManagerNoCallbacksTest : public ::testing::Test { auto minimum_rotation_time = std::chrono::milliseconds(7 * 60 * 1000); auto maximum_rotation_time = std::chrono::milliseconds(15 * 60 * 1000); acl_manager_->SetPrivacyPolicyForInitiatorAddress( - LeAddressManager::AddressPolicy::USE_STATIC_ADDRESS, - address_with_type, - minimum_rotation_time, - maximum_rotation_time); + LeAddressManager::AddressPolicy::USE_STATIC_ADDRESS, address_with_type, + minimum_rotation_time, maximum_rotation_time); auto set_random_address_packet = - LeSetRandomAddressView::Create(LeAdvertisingCommandView::Create( - GetConnectionManagementCommand(OpCode::LE_SET_RANDOM_ADDRESS))); + LeSetRandomAddressView::Create(LeAdvertisingCommandView::Create( + GetConnectionManagementCommand(OpCode::LE_SET_RANDOM_ADDRESS))); ASSERT_TRUE(set_random_address_packet.IsValid()); - my_initiating_address = AddressWithType( - set_random_address_packet.GetRandomAddress(), AddressType::RANDOM_DEVICE_ADDRESS); - test_hci_layer_->IncomingEvent(LeSetRandomAddressCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); + my_initiating_address = AddressWithType(set_random_address_packet.GetRandomAddress(), + AddressType::RANDOM_DEVICE_ADDRESS); + test_hci_layer_->IncomingEvent( + LeSetRandomAddressCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); ON_CALL(mock_connection_callback_, OnConnectSuccess) - .WillByDefault([this](std::unique_ptr connection) { - connections_.push_back(std::move(connection)); - if (connection_promise_ != nullptr) { - connection_promise_->set_value(); - connection_promise_.reset(); - } - }); + .WillByDefault([this](std::unique_ptr connection) { + connections_.push_back(std::move(connection)); + if (connection_promise_ != nullptr) { + connection_promise_->set_value(); + connection_promise_.reset(); + } + }); } void TearDown() override { @@ -167,9 +158,8 @@ class AclManagerNoCallbacksTest : public ::testing::Test { } void sync_client_handler() { - log::assert_that( - thread_.GetReactor()->WaitForIdle(std::chrono::seconds(2)), - "assert failed: thread_.GetReactor()->WaitForIdle(std::chrono::seconds(2))"); + log::assert_that(thread_.GetReactor()->WaitForIdle(std::chrono::seconds(2)), + "assert failed: thread_.GetReactor()->WaitForIdle(std::chrono::seconds(2))"); } TestModuleRegistry fake_registry_; @@ -194,25 +184,22 @@ class AclManagerNoCallbacksTest : public ::testing::Test { return le_connection_promise_->get_future(); } - std::shared_ptr GetLastConnection() { - return connections_.back(); - } + std::shared_ptr GetLastConnection() { return connections_.back(); } - std::shared_ptr GetLastLeConnection() { - return le_connections_.back(); - } + std::shared_ptr GetLastLeConnection() { return le_connections_.back(); } void SendAclData(uint16_t handle, AclConnection::QueueUpEnd* queue_end) { std::promise promise; auto future = promise.get_future(); - queue_end->RegisterEnqueue(client_handler_, - common::Bind( - [](decltype(queue_end) queue_end, uint16_t handle, std::promise promise) { - queue_end->UnregisterEnqueue(); - promise.set_value(); - return NextPayload(handle); - }, - queue_end, handle, common::Passed(std::move(promise)))); + queue_end->RegisterEnqueue( + client_handler_, + common::Bind( + [](decltype(queue_end) queue_end, uint16_t handle, std::promise promise) { + queue_end->UnregisterEnqueue(); + promise.set_value(); + return NextPayload(handle); + }, + queue_end, handle, common::Passed(std::move(promise)))); auto status = future.wait_for(kTimeout); ASSERT_EQ(status, std::future_status::ready); } @@ -220,7 +207,7 @@ class AclManagerNoCallbacksTest : public ::testing::Test { ConnectionManagementCommandView GetConnectionManagementCommand(OpCode op_code) { auto base_command = test_hci_layer_->GetCommand(); ConnectionManagementCommandView command = - ConnectionManagementCommandView::Create(AclCommandView::Create(base_command)); + ConnectionManagementCommandView::Create(AclCommandView::Create(base_command)); EXPECT_TRUE(command.IsValid()); EXPECT_EQ(command.GetOpCode(), op_code); return command; @@ -236,7 +223,7 @@ class AclManagerNoCallbacksTest : public ::testing::Test { }; class AclManagerTest : public AclManagerNoCallbacksTest { - protected: +protected: void SetUp() override { AclManagerNoCallbacksTest::SetUp(); acl_manager_->RegisterCallbacks(&mock_connection_callback_, client_handler_); @@ -245,7 +232,7 @@ class AclManagerTest : public AclManagerNoCallbacksTest { }; class AclManagerWithConnectionTest : public AclManagerTest { - protected: +protected: void SetUp() override { AclManagerTest::SetUp(); @@ -258,11 +245,12 @@ class AclManagerWithConnectionTest : public AclManagerTest { last_command = GetConnectionManagementCommand(OpCode::CREATE_CONNECTION); } - EXPECT_CALL(mock_connection_management_callbacks_, OnRoleChange(hci::ErrorCode::SUCCESS, Role::CENTRAL)); + EXPECT_CALL(mock_connection_management_callbacks_, + OnRoleChange(hci::ErrorCode::SUCCESS, Role::CENTRAL)); auto first_connection = GetConnectionFuture(); - test_hci_layer_->IncomingEvent( - ConnectionCompleteBuilder::Create(ErrorCode::SUCCESS, handle_, remote, LinkType::ACL, Enable::DISABLED)); + test_hci_layer_->IncomingEvent(ConnectionCompleteBuilder::Create( + ErrorCode::SUCCESS, handle_, remote, LinkType::ACL, Enable::DISABLED)); auto first_connection_status = first_connection.wait_for(kTimeout); ASSERT_EQ(first_connection_status, std::future_status::ready); @@ -303,7 +291,7 @@ TEST_F(AclManagerTest, invoke_registered_callback_connection_complete_success) { auto first_connection = GetConnectionFuture(); test_hci_layer_->IncomingEvent(ConnectionCompleteBuilder::Create( - ErrorCode::SUCCESS, kHciHandle, remote, LinkType::ACL, Enable::DISABLED)); + ErrorCode::SUCCESS, kHciHandle, remote, LinkType::ACL, Enable::DISABLED)); auto first_connection_status = first_connection.wait_for(kTimeout); ASSERT_EQ(first_connection_status, std::future_status::ready); @@ -330,12 +318,12 @@ TEST_F(AclManagerTest, invoke_registered_callback_connection_complete_fail) { auto promise = std::promise(); auto future = promise.get_future(); ON_CALL(mock_connection_callback_, OnConnectFail) - .WillByDefault( - [&promise](hci::Address bd_addr, hci::ErrorCode reason, bool is_locally_initiated) { + .WillByDefault([&promise](hci::Address bd_addr, hci::ErrorCode reason, + bool is_locally_initiated) { promise.set_value({ - .bd_addr = bd_addr, - .reason = reason, - .is_locally_initiated = is_locally_initiated, + .bd_addr = bd_addr, + .reason = reason, + .is_locally_initiated = is_locally_initiated, }); }); @@ -343,7 +331,7 @@ TEST_F(AclManagerTest, invoke_registered_callback_connection_complete_fail) { // Remote response event to the connection request test_hci_layer_->IncomingEvent(ConnectionCompleteBuilder::Create( - ErrorCode::PAGE_TIMEOUT, kHciHandle, remote, LinkType::ACL, Enable::DISABLED)); + ErrorCode::PAGE_TIMEOUT, kHciHandle, remote, LinkType::ACL, Enable::DISABLED)); ASSERT_EQ(std::future_status::ready, future.wait_for(kTimeout)); auto callback = future.get(); @@ -354,17 +342,18 @@ TEST_F(AclManagerTest, invoke_registered_callback_connection_complete_fail) { } class AclManagerWithLeConnectionTest : public AclManagerTest { - protected: +protected: void SetUp() override { AclManagerTest::SetUp(); remote_with_type_ = AddressWithType(remote, AddressType::PUBLIC_DEVICE_ADDRESS); acl_manager_->CreateLeConnection(remote_with_type_, true); GetConnectionManagementCommand(OpCode::LE_ADD_DEVICE_TO_FILTER_ACCEPT_LIST); - test_hci_layer_->IncomingEvent(LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); + test_hci_layer_->IncomingEvent( + LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); auto packet = GetConnectionManagementCommand(OpCode::LE_CREATE_CONNECTION); auto le_connection_management_command_view = - LeConnectionManagementCommandView::Create(AclCommandView::Create(packet)); + LeConnectionManagementCommandView::Create(AclCommandView::Create(packet)); auto command_view = LeCreateConnectionView::Create(le_connection_management_command_view); ASSERT_TRUE(command_view.IsValid()); if (use_accept_list_) { @@ -375,19 +364,19 @@ class AclManagerWithLeConnectionTest : public AclManagerTest { ASSERT_EQ(command_view.GetPeerAddressType(), AddressType::PUBLIC_DEVICE_ADDRESS); } - test_hci_layer_->IncomingEvent(LeCreateConnectionStatusBuilder::Create(ErrorCode::SUCCESS, 0x01)); + test_hci_layer_->IncomingEvent( + LeCreateConnectionStatusBuilder::Create(ErrorCode::SUCCESS, 0x01)); auto first_connection = GetLeConnectionFuture(); EXPECT_CALL(mock_le_connection_callbacks_, OnLeConnectSuccess(remote_with_type_, _)) - .WillRepeatedly([this]( - hci::AddressWithType /* address_with_type */, - std::unique_ptr connection) { - le_connections_.push_back(std::move(connection)); - if (le_connection_promise_ != nullptr) { - le_connection_promise_->set_value(); - le_connection_promise_.reset(); - } - }); + .WillRepeatedly([this](hci::AddressWithType /* address_with_type */, + std::unique_ptr connection) { + le_connections_.push_back(std::move(connection)); + if (le_connection_promise_ != nullptr) { + le_connection_promise_->set_value(); + le_connection_promise_.reset(); + } + }); if (send_early_acl_) { log::info("Sending a packet with handle 0x{:02x} ({})", handle_, handle_); @@ -395,18 +384,12 @@ class AclManagerWithLeConnectionTest : public AclManagerTest { } test_hci_layer_->IncomingLeMetaEvent(LeConnectionCompleteBuilder::Create( - ErrorCode::SUCCESS, - handle_, - Role::CENTRAL, - AddressType::PUBLIC_DEVICE_ADDRESS, - remote, - 0x0100, - 0x0010, - 0x0C80, - ClockAccuracy::PPM_30)); + ErrorCode::SUCCESS, handle_, Role::CENTRAL, AddressType::PUBLIC_DEVICE_ADDRESS, remote, + 0x0100, 0x0010, 0x0C80, ClockAccuracy::PPM_30)); GetConnectionManagementCommand(OpCode::LE_REMOVE_DEVICE_FROM_FILTER_ACCEPT_LIST); - test_hci_layer_->IncomingEvent(LeRemoveDeviceFromFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); + test_hci_layer_->IncomingEvent( + LeRemoveDeviceFromFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); auto first_connection_status = first_connection.wait_for(kTimeout); ASSERT_EQ(first_connection_status, std::future_status::ready); @@ -434,7 +417,7 @@ class AclManagerWithLeConnectionTest : public AclManagerTest { }; class AclManagerWithLateLeConnectionTest : public AclManagerWithLeConnectionTest { - protected: +protected: void SetUp() override { send_early_acl_ = true; AclManagerWithLeConnectionTest::SetUp(); @@ -452,10 +435,11 @@ TEST_F(AclManagerTest, invoke_registered_callback_le_connection_complete_fail) { AddressWithType remote_with_type(remote, AddressType::PUBLIC_DEVICE_ADDRESS); acl_manager_->CreateLeConnection(remote_with_type, true); GetConnectionManagementCommand(OpCode::LE_ADD_DEVICE_TO_FILTER_ACCEPT_LIST); - test_hci_layer_->IncomingEvent(LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); + test_hci_layer_->IncomingEvent( + LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); auto packet = GetConnectionManagementCommand(OpCode::LE_CREATE_CONNECTION); auto le_connection_management_command_view = - LeConnectionManagementCommandView::Create(AclCommandView::Create(packet)); + LeConnectionManagementCommandView::Create(AclCommandView::Create(packet)); auto command_view = LeCreateConnectionView::Create(le_connection_management_command_view); ASSERT_TRUE(command_view.IsValid()); if (use_accept_list_) { @@ -467,61 +451,55 @@ TEST_F(AclManagerTest, invoke_registered_callback_le_connection_complete_fail) { test_hci_layer_->IncomingEvent(LeCreateConnectionStatusBuilder::Create(ErrorCode::SUCCESS, 0x01)); - EXPECT_CALL( - mock_le_connection_callbacks_, - OnLeConnectFail(remote_with_type, ErrorCode::CONNECTION_REJECTED_LIMITED_RESOURCES)); + EXPECT_CALL(mock_le_connection_callbacks_, + OnLeConnectFail(remote_with_type, ErrorCode::CONNECTION_REJECTED_LIMITED_RESOURCES)); test_hci_layer_->IncomingLeMetaEvent(LeConnectionCompleteBuilder::Create( - ErrorCode::CONNECTION_REJECTED_LIMITED_RESOURCES, - 0x123, - Role::CENTRAL, - AddressType::PUBLIC_DEVICE_ADDRESS, - remote, - 0x0100, - 0x0010, - 0x0011, - ClockAccuracy::PPM_30)); + ErrorCode::CONNECTION_REJECTED_LIMITED_RESOURCES, 0x123, Role::CENTRAL, + AddressType::PUBLIC_DEVICE_ADDRESS, remote, 0x0100, 0x0010, 0x0011, + ClockAccuracy::PPM_30)); packet = GetConnectionManagementCommand(OpCode::LE_REMOVE_DEVICE_FROM_FILTER_ACCEPT_LIST); - le_connection_management_command_view = LeConnectionManagementCommandView::Create(AclCommandView::Create(packet)); - auto remove_command_view = LeRemoveDeviceFromFilterAcceptListView::Create(le_connection_management_command_view); + le_connection_management_command_view = + LeConnectionManagementCommandView::Create(AclCommandView::Create(packet)); + auto remove_command_view = + LeRemoveDeviceFromFilterAcceptListView::Create(le_connection_management_command_view); ASSERT_TRUE(remove_command_view.IsValid()); - test_hci_layer_->IncomingEvent(LeRemoveDeviceFromFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); + test_hci_layer_->IncomingEvent( + LeRemoveDeviceFromFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); } TEST_F(AclManagerTest, cancel_le_connection) { AddressWithType remote_with_type(remote, AddressType::PUBLIC_DEVICE_ADDRESS); acl_manager_->CreateLeConnection(remote_with_type, true); GetConnectionManagementCommand(OpCode::LE_ADD_DEVICE_TO_FILTER_ACCEPT_LIST); - test_hci_layer_->IncomingEvent(LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); + test_hci_layer_->IncomingEvent( + LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); GetConnectionManagementCommand(OpCode::LE_CREATE_CONNECTION); test_hci_layer_->IncomingEvent(LeCreateConnectionStatusBuilder::Create(ErrorCode::SUCCESS, 0x01)); acl_manager_->CancelLeConnect(remote_with_type); auto packet = GetConnectionManagementCommand(OpCode::LE_CREATE_CONNECTION_CANCEL); auto le_connection_management_command_view = - LeConnectionManagementCommandView::Create(AclCommandView::Create(packet)); + LeConnectionManagementCommandView::Create(AclCommandView::Create(packet)); auto command_view = LeCreateConnectionCancelView::Create(le_connection_management_command_view); ASSERT_TRUE(command_view.IsValid()); - test_hci_layer_->IncomingEvent(LeCreateConnectionCancelCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); + test_hci_layer_->IncomingEvent( + LeCreateConnectionCancelCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); test_hci_layer_->IncomingLeMetaEvent(LeConnectionCompleteBuilder::Create( - ErrorCode::UNKNOWN_CONNECTION, - 0x123, - Role::CENTRAL, - AddressType::PUBLIC_DEVICE_ADDRESS, - remote, - 0x0100, - 0x0010, - 0x0011, - ClockAccuracy::PPM_30)); + ErrorCode::UNKNOWN_CONNECTION, 0x123, Role::CENTRAL, AddressType::PUBLIC_DEVICE_ADDRESS, + remote, 0x0100, 0x0010, 0x0011, ClockAccuracy::PPM_30)); packet = GetConnectionManagementCommand(OpCode::LE_REMOVE_DEVICE_FROM_FILTER_ACCEPT_LIST); - le_connection_management_command_view = LeConnectionManagementCommandView::Create(AclCommandView::Create(packet)); - auto remove_command_view = LeRemoveDeviceFromFilterAcceptListView::Create(le_connection_management_command_view); + le_connection_management_command_view = + LeConnectionManagementCommandView::Create(AclCommandView::Create(packet)); + auto remove_command_view = + LeRemoveDeviceFromFilterAcceptListView::Create(le_connection_management_command_view); ASSERT_TRUE(remove_command_view.IsValid()); - test_hci_layer_->IncomingEvent(LeRemoveDeviceFromFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); + test_hci_layer_->IncomingEvent( + LeRemoveDeviceFromFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); } TEST_F(AclManagerTest, create_connection_with_fast_mode) { @@ -529,11 +507,11 @@ TEST_F(AclManagerTest, create_connection_with_fast_mode) { acl_manager_->CreateLeConnection(remote_with_type, true); GetConnectionManagementCommand(OpCode::LE_ADD_DEVICE_TO_FILTER_ACCEPT_LIST); test_hci_layer_->IncomingEvent( - LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); + LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); auto packet = GetConnectionManagementCommand(OpCode::LE_CREATE_CONNECTION); - auto command_view = - LeCreateConnectionView::Create(LeConnectionManagementCommandView::Create(AclCommandView::Create(packet))); + auto command_view = LeCreateConnectionView::Create( + LeConnectionManagementCommandView::Create(AclCommandView::Create(packet))); ASSERT_TRUE(command_view.IsValid()); ASSERT_EQ(command_view.GetLeScanInterval(), kScanIntervalFast); ASSERT_EQ(command_view.GetLeScanWindow(), kScanWindowFast); @@ -541,29 +519,22 @@ TEST_F(AclManagerTest, create_connection_with_fast_mode) { auto first_connection = GetLeConnectionFuture(); EXPECT_CALL(mock_le_connection_callbacks_, OnLeConnectSuccess(remote_with_type, _)) - .WillRepeatedly([this]( - hci::AddressWithType /* address_with_type */, - std::unique_ptr connection) { - le_connections_.push_back(std::move(connection)); - if (le_connection_promise_ != nullptr) { - le_connection_promise_->set_value(); - le_connection_promise_.reset(); - } - }); + .WillRepeatedly([this](hci::AddressWithType /* address_with_type */, + std::unique_ptr connection) { + le_connections_.push_back(std::move(connection)); + if (le_connection_promise_ != nullptr) { + le_connection_promise_->set_value(); + le_connection_promise_.reset(); + } + }); test_hci_layer_->IncomingLeMetaEvent(LeConnectionCompleteBuilder::Create( - ErrorCode::SUCCESS, - 0x00, - Role::CENTRAL, - AddressType::PUBLIC_DEVICE_ADDRESS, - remote, - 0x0100, - 0x0010, - 0x0C80, - ClockAccuracy::PPM_30)); + ErrorCode::SUCCESS, 0x00, Role::CENTRAL, AddressType::PUBLIC_DEVICE_ADDRESS, remote, + 0x0100, 0x0010, 0x0C80, ClockAccuracy::PPM_30)); GetConnectionManagementCommand(OpCode::LE_REMOVE_DEVICE_FROM_FILTER_ACCEPT_LIST); - test_hci_layer_->IncomingEvent(LeRemoveDeviceFromFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); + test_hci_layer_->IncomingEvent( + LeRemoveDeviceFromFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); auto first_connection_status = first_connection.wait_for(kTimeout); ASSERT_EQ(first_connection_status, std::future_status::ready); } @@ -572,38 +543,32 @@ TEST_F(AclManagerTest, create_connection_with_slow_mode) { AddressWithType remote_with_type(remote, AddressType::PUBLIC_DEVICE_ADDRESS); acl_manager_->CreateLeConnection(remote_with_type, false); GetConnectionManagementCommand(OpCode::LE_ADD_DEVICE_TO_FILTER_ACCEPT_LIST); - test_hci_layer_->IncomingEvent(LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); + test_hci_layer_->IncomingEvent( + LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); auto packet = GetConnectionManagementCommand(OpCode::LE_CREATE_CONNECTION); - auto command_view = - LeCreateConnectionView::Create(LeConnectionManagementCommandView::Create(AclCommandView::Create(packet))); + auto command_view = LeCreateConnectionView::Create( + LeConnectionManagementCommandView::Create(AclCommandView::Create(packet))); ASSERT_TRUE(command_view.IsValid()); ASSERT_EQ(command_view.GetLeScanInterval(), kScanIntervalSlow); ASSERT_EQ(command_view.GetLeScanWindow(), kScanWindowSlow); test_hci_layer_->IncomingEvent(LeCreateConnectionStatusBuilder::Create(ErrorCode::SUCCESS, 0x01)); auto first_connection = GetLeConnectionFuture(); EXPECT_CALL(mock_le_connection_callbacks_, OnLeConnectSuccess(remote_with_type, _)) - .WillRepeatedly([this]( - hci::AddressWithType /* address_with_type */, - std::unique_ptr connection) { - le_connections_.push_back(std::move(connection)); - if (le_connection_promise_ != nullptr) { - le_connection_promise_->set_value(); - le_connection_promise_.reset(); - } - }); + .WillRepeatedly([this](hci::AddressWithType /* address_with_type */, + std::unique_ptr connection) { + le_connections_.push_back(std::move(connection)); + if (le_connection_promise_ != nullptr) { + le_connection_promise_->set_value(); + le_connection_promise_.reset(); + } + }); test_hci_layer_->IncomingLeMetaEvent(LeConnectionCompleteBuilder::Create( - ErrorCode::SUCCESS, - 0x00, - Role::CENTRAL, - AddressType::PUBLIC_DEVICE_ADDRESS, - remote, - 0x0100, - 0x0010, - 0x0C80, - ClockAccuracy::PPM_30)); + ErrorCode::SUCCESS, 0x00, Role::CENTRAL, AddressType::PUBLIC_DEVICE_ADDRESS, remote, + 0x0100, 0x0010, 0x0C80, ClockAccuracy::PPM_30)); GetConnectionManagementCommand(OpCode::LE_REMOVE_DEVICE_FROM_FILTER_ACCEPT_LIST); - test_hci_layer_->IncomingEvent(LeRemoveDeviceFromFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); + test_hci_layer_->IncomingEvent( + LeRemoveDeviceFromFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); auto first_connection_status = first_connection.wait_for(kTimeout); ASSERT_EQ(first_connection_status, std::future_status::ready); } @@ -647,24 +612,20 @@ TEST_F(AclManagerWithLeConnectionTest, invoke_registered_callback_le_connection_ uint16_t connection_interval = (connection_interval_max + connection_interval_min) / 2; uint16_t connection_latency = 0x0001; uint16_t supervision_timeout = 0x0A00; - connection_->LeConnectionUpdate( - connection_interval_min, - connection_interval_max, - connection_latency, - supervision_timeout, - 0x10, - 0x20); + connection_->LeConnectionUpdate(connection_interval_min, connection_interval_max, + connection_latency, supervision_timeout, 0x10, 0x20); auto update_packet = GetConnectionManagementCommand(OpCode::LE_CONNECTION_UPDATE); - auto update_view = - LeConnectionUpdateView::Create(LeConnectionManagementCommandView::Create(AclCommandView::Create(update_packet))); + auto update_view = LeConnectionUpdateView::Create( + LeConnectionManagementCommandView::Create(AclCommandView::Create(update_packet))); ASSERT_TRUE(update_view.IsValid()); EXPECT_EQ(update_view.GetConnectionHandle(), handle_); test_hci_layer_->IncomingEvent(LeConnectionUpdateStatusBuilder::Create(ErrorCode::SUCCESS, 0x1)); - EXPECT_CALL( - mock_le_connection_management_callbacks_, - OnConnectionUpdate(hci_status, connection_interval, connection_latency, supervision_timeout)); + EXPECT_CALL(mock_le_connection_management_callbacks_, + OnConnectionUpdate(hci_status, connection_interval, connection_latency, + supervision_timeout)); test_hci_layer_->IncomingLeMetaEvent(LeConnectionUpdateCompleteBuilder::Create( - ErrorCode::SUCCESS, handle_, connection_interval, connection_latency, supervision_timeout)); + ErrorCode::SUCCESS, handle_, connection_interval, connection_latency, + supervision_timeout)); sync_client_handler(); } @@ -823,9 +784,10 @@ TEST_F(AclManagerWithConnectionTest, send_switch_role) { ASSERT_EQ(command_view.GetBdAddr(), connection_->GetAddress()); ASSERT_EQ(command_view.GetRole(), Role::PERIPHERAL); - EXPECT_CALL(mock_connection_management_callbacks_, OnRoleChange(hci::ErrorCode::SUCCESS, Role::PERIPHERAL)); - test_hci_layer_->IncomingEvent( - RoleChangeBuilder::Create(ErrorCode::SUCCESS, connection_->GetAddress(), Role::PERIPHERAL)); + EXPECT_CALL(mock_connection_management_callbacks_, + OnRoleChange(hci::ErrorCode::SUCCESS, Role::PERIPHERAL)); + test_hci_layer_->IncomingEvent(RoleChangeBuilder::Create( + ErrorCode::SUCCESS, connection_->GetAddress(), Role::PERIPHERAL)); sync_client_handler(); } @@ -839,7 +801,7 @@ TEST_F(AclManagerWithConnectionTest, send_write_default_link_policy_settings) { uint8_t num_packets = 1; test_hci_layer_->IncomingEvent( - WriteDefaultLinkPolicySettingsCompleteBuilder::Create(num_packets, ErrorCode::SUCCESS)); + WriteDefaultLinkPolicySettingsCompleteBuilder::Create(num_packets, ErrorCode::SUCCESS)); sync_client_handler(); ASSERT_EQ(link_policy_settings, acl_manager_->ReadDefaultLinkPolicySettings()); @@ -853,7 +815,7 @@ TEST_F(AclManagerWithConnectionTest, send_authentication_requested) { EXPECT_CALL(mock_connection_management_callbacks_, OnAuthenticationComplete); test_hci_layer_->IncomingEvent( - AuthenticationCompleteBuilder::Create(ErrorCode::SUCCESS, handle_)); + AuthenticationCompleteBuilder::Create(ErrorCode::SUCCESS, handle_)); sync_client_handler(); } @@ -865,7 +827,7 @@ TEST_F(AclManagerWithConnectionTest, send_read_clock_offset) { EXPECT_CALL(mock_connection_management_callbacks_, OnReadClockOffsetComplete(0x0123)); test_hci_layer_->IncomingEvent( - ReadClockOffsetCompleteBuilder::Create(ErrorCode::SUCCESS, handle_, 0x0123)); + ReadClockOffsetCompleteBuilder::Create(ErrorCode::SUCCESS, handle_, 0x0123)); sync_client_handler(); } @@ -877,9 +839,10 @@ TEST_F(AclManagerWithConnectionTest, send_hold_mode) { ASSERT_EQ(command_view.GetHoldModeMaxInterval(), 0x0500); ASSERT_EQ(command_view.GetHoldModeMinInterval(), 0x0020); - EXPECT_CALL(mock_connection_management_callbacks_, OnModeChange(ErrorCode::SUCCESS, Mode::HOLD, 0x0020)); + EXPECT_CALL(mock_connection_management_callbacks_, + OnModeChange(ErrorCode::SUCCESS, Mode::HOLD, 0x0020)); test_hci_layer_->IncomingEvent( - ModeChangeBuilder::Create(ErrorCode::SUCCESS, handle_, Mode::HOLD, 0x0020)); + ModeChangeBuilder::Create(ErrorCode::SUCCESS, handle_, Mode::HOLD, 0x0020)); sync_client_handler(); } @@ -893,9 +856,10 @@ TEST_F(AclManagerWithConnectionTest, send_sniff_mode) { ASSERT_EQ(command_view.GetSniffAttempt(), 0x0040); ASSERT_EQ(command_view.GetSniffTimeout(), 0x0014); - EXPECT_CALL(mock_connection_management_callbacks_, OnModeChange(ErrorCode::SUCCESS, Mode::SNIFF, 0x0028)); + EXPECT_CALL(mock_connection_management_callbacks_, + OnModeChange(ErrorCode::SUCCESS, Mode::SNIFF, 0x0028)); test_hci_layer_->IncomingEvent( - ModeChangeBuilder::Create(ErrorCode::SUCCESS, handle_, Mode::SNIFF, 0x0028)); + ModeChangeBuilder::Create(ErrorCode::SUCCESS, handle_, Mode::SNIFF, 0x0028)); sync_client_handler(); } @@ -905,9 +869,10 @@ TEST_F(AclManagerWithConnectionTest, send_exit_sniff_mode) { auto command_view = ExitSniffModeView::Create(packet); ASSERT_TRUE(command_view.IsValid()); - EXPECT_CALL(mock_connection_management_callbacks_, OnModeChange(ErrorCode::SUCCESS, Mode::ACTIVE, 0x00)); + EXPECT_CALL(mock_connection_management_callbacks_, + OnModeChange(ErrorCode::SUCCESS, Mode::ACTIVE, 0x00)); test_hci_layer_->IncomingEvent( - ModeChangeBuilder::Create(ErrorCode::SUCCESS, handle_, Mode::ACTIVE, 0x00)); + ModeChangeBuilder::Create(ErrorCode::SUCCESS, handle_, Mode::ACTIVE, 0x00)); sync_client_handler(); } @@ -925,13 +890,13 @@ TEST_F(AclManagerWithConnectionTest, send_qos_setup) { EXPECT_CALL(mock_connection_management_callbacks_, OnQosSetupComplete(ServiceType::BEST_EFFORT, 0x1234, 0x1233, 0x1232, 0x1231)); test_hci_layer_->IncomingEvent(QosSetupCompleteBuilder::Create( - ErrorCode::SUCCESS, handle_, ServiceType::BEST_EFFORT, 0x1234, 0x1233, 0x1232, 0x1231)); + ErrorCode::SUCCESS, handle_, ServiceType::BEST_EFFORT, 0x1234, 0x1233, 0x1232, 0x1231)); sync_client_handler(); } TEST_F(AclManagerWithConnectionTest, send_flow_specification) { - connection_->FlowSpecification( - FlowDirection::OUTGOING_FLOW, ServiceType::BEST_EFFORT, 0x1234, 0x1233, 0x1232, 0x1231); + connection_->FlowSpecification(FlowDirection::OUTGOING_FLOW, ServiceType::BEST_EFFORT, 0x1234, + 0x1233, 0x1232, 0x1231); auto packet = GetConnectionManagementCommand(OpCode::FLOW_SPECIFICATION); auto command_view = FlowSpecificationView::Create(packet); ASSERT_TRUE(command_view.IsValid()); @@ -943,17 +908,11 @@ TEST_F(AclManagerWithConnectionTest, send_flow_specification) { ASSERT_EQ(command_view.GetAccessLatency(), 0x1231u); EXPECT_CALL(mock_connection_management_callbacks_, - OnFlowSpecificationComplete(FlowDirection::OUTGOING_FLOW, ServiceType::BEST_EFFORT, 0x1234, 0x1233, - 0x1232, 0x1231)); + OnFlowSpecificationComplete(FlowDirection::OUTGOING_FLOW, ServiceType::BEST_EFFORT, + 0x1234, 0x1233, 0x1232, 0x1231)); test_hci_layer_->IncomingEvent(FlowSpecificationCompleteBuilder::Create( - ErrorCode::SUCCESS, - handle_, - FlowDirection::OUTGOING_FLOW, - ServiceType::BEST_EFFORT, - 0x1234, - 0x1233, - 0x1232, - 0x1231)); + ErrorCode::SUCCESS, handle_, FlowDirection::OUTGOING_FLOW, ServiceType::BEST_EFFORT, + 0x1234, 0x1233, 0x1232, 0x1231)); sync_client_handler(); } @@ -977,7 +936,7 @@ TEST_F(AclManagerWithConnectionTest, send_role_discovery) { EXPECT_CALL(mock_connection_management_callbacks_, OnRoleDiscoveryComplete(Role::CENTRAL)); uint8_t num_packets = 1; test_hci_layer_->IncomingEvent(RoleDiscoveryCompleteBuilder::Create( - num_packets, ErrorCode::SUCCESS, handle_, Role::CENTRAL)); + num_packets, ErrorCode::SUCCESS, handle_, Role::CENTRAL)); sync_client_handler(); } @@ -990,7 +949,7 @@ TEST_F(AclManagerWithConnectionTest, send_read_link_policy_settings) { EXPECT_CALL(mock_connection_management_callbacks_, OnReadLinkPolicySettingsComplete(0x07)); uint8_t num_packets = 1; test_hci_layer_->IncomingEvent(ReadLinkPolicySettingsCompleteBuilder::Create( - num_packets, ErrorCode::SUCCESS, handle_, 0x07)); + num_packets, ErrorCode::SUCCESS, handle_, 0x07)); sync_client_handler(); } @@ -1003,7 +962,7 @@ TEST_F(AclManagerWithConnectionTest, send_write_link_policy_settings) { uint8_t num_packets = 1; test_hci_layer_->IncomingEvent( - WriteLinkPolicySettingsCompleteBuilder::Create(num_packets, ErrorCode::SUCCESS, handle_)); + WriteLinkPolicySettingsCompleteBuilder::Create(num_packets, ErrorCode::SUCCESS, handle_)); sync_client_handler(); } @@ -1018,7 +977,7 @@ TEST_F(AclManagerWithConnectionTest, send_sniff_subrating) { uint8_t num_packets = 1; test_hci_layer_->IncomingEvent( - SniffSubratingCompleteBuilder::Create(num_packets, ErrorCode::SUCCESS, handle_)); + SniffSubratingCompleteBuilder::Create(num_packets, ErrorCode::SUCCESS, handle_)); sync_client_handler(); } @@ -1031,7 +990,7 @@ TEST_F(AclManagerWithConnectionTest, send_read_automatic_flush_timeout) { EXPECT_CALL(mock_connection_management_callbacks_, OnReadAutomaticFlushTimeoutComplete(0x07ff)); uint8_t num_packets = 1; test_hci_layer_->IncomingEvent(ReadAutomaticFlushTimeoutCompleteBuilder::Create( - num_packets, ErrorCode::SUCCESS, handle_, 0x07ff)); + num_packets, ErrorCode::SUCCESS, handle_, 0x07ff)); sync_client_handler(); } @@ -1043,8 +1002,8 @@ TEST_F(AclManagerWithConnectionTest, send_write_automatic_flush_timeout) { ASSERT_EQ(command_view.GetFlushTimeout(), 0x07FF); uint8_t num_packets = 1; - test_hci_layer_->IncomingEvent( - WriteAutomaticFlushTimeoutCompleteBuilder::Create(num_packets, ErrorCode::SUCCESS, handle_)); + test_hci_layer_->IncomingEvent(WriteAutomaticFlushTimeoutCompleteBuilder::Create( + num_packets, ErrorCode::SUCCESS, handle_)); sync_client_handler(); } @@ -1058,7 +1017,7 @@ TEST_F(AclManagerWithConnectionTest, send_read_transmit_power_level) { EXPECT_CALL(mock_connection_management_callbacks_, OnReadTransmitPowerLevelComplete(0x07)); uint8_t num_packets = 1; test_hci_layer_->IncomingEvent(ReadTransmitPowerLevelCompleteBuilder::Create( - num_packets, ErrorCode::SUCCESS, handle_, 0x07)); + num_packets, ErrorCode::SUCCESS, handle_, 0x07)); sync_client_handler(); } @@ -1071,7 +1030,7 @@ TEST_F(AclManagerWithConnectionTest, send_read_link_supervision_timeout) { EXPECT_CALL(mock_connection_management_callbacks_, OnReadLinkSupervisionTimeoutComplete(0x5677)); uint8_t num_packets = 1; test_hci_layer_->IncomingEvent(ReadLinkSupervisionTimeoutCompleteBuilder::Create( - num_packets, ErrorCode::SUCCESS, handle_, 0x5677)); + num_packets, ErrorCode::SUCCESS, handle_, 0x5677)); sync_client_handler(); } @@ -1083,8 +1042,8 @@ TEST_F(AclManagerWithConnectionTest, send_write_link_supervision_timeout) { ASSERT_EQ(command_view.GetLinkSupervisionTimeout(), 0x5678); uint8_t num_packets = 1; - test_hci_layer_->IncomingEvent( - WriteLinkSupervisionTimeoutCompleteBuilder::Create(num_packets, ErrorCode::SUCCESS, handle_)); + test_hci_layer_->IncomingEvent(WriteLinkSupervisionTimeoutCompleteBuilder::Create( + num_packets, ErrorCode::SUCCESS, handle_)); sync_client_handler(); } @@ -1097,7 +1056,7 @@ TEST_F(AclManagerWithConnectionTest, send_read_failed_contact_counter) { EXPECT_CALL(mock_connection_management_callbacks_, OnReadFailedContactCounterComplete(0x00)); uint8_t num_packets = 1; test_hci_layer_->IncomingEvent(ReadFailedContactCounterCompleteBuilder::Create( - num_packets, ErrorCode::SUCCESS, handle_, 0x00)); + num_packets, ErrorCode::SUCCESS, handle_, 0x00)); sync_client_handler(); } @@ -1108,8 +1067,8 @@ TEST_F(AclManagerWithConnectionTest, send_reset_failed_contact_counter) { ASSERT_TRUE(command_view.IsValid()); uint8_t num_packets = 1; - test_hci_layer_->IncomingEvent( - ResetFailedContactCounterCompleteBuilder::Create(num_packets, ErrorCode::SUCCESS, handle_)); + test_hci_layer_->IncomingEvent(ResetFailedContactCounterCompleteBuilder::Create( + num_packets, ErrorCode::SUCCESS, handle_)); sync_client_handler(); } @@ -1122,7 +1081,7 @@ TEST_F(AclManagerWithConnectionTest, send_read_link_quality) { EXPECT_CALL(mock_connection_management_callbacks_, OnReadLinkQualityComplete(0xa9)); uint8_t num_packets = 1; test_hci_layer_->IncomingEvent( - ReadLinkQualityCompleteBuilder::Create(num_packets, ErrorCode::SUCCESS, handle_, 0xa9)); + ReadLinkQualityCompleteBuilder::Create(num_packets, ErrorCode::SUCCESS, handle_, 0xa9)); sync_client_handler(); } @@ -1131,13 +1090,14 @@ TEST_F(AclManagerWithConnectionTest, send_read_afh_channel_map) { auto packet = GetConnectionManagementCommand(OpCode::READ_AFH_CHANNEL_MAP); auto command_view = ReadAfhChannelMapView::Create(packet); ASSERT_TRUE(command_view.IsValid()); - std::array afh_channel_map = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09}; + std::array afh_channel_map = {0x00, 0x01, 0x02, 0x03, 0x04, + 0x05, 0x06, 0x07, 0x08, 0x09}; EXPECT_CALL(mock_connection_management_callbacks_, OnReadAfhChannelMapComplete(AfhMode::AFH_ENABLED, afh_channel_map)); uint8_t num_packets = 1; test_hci_layer_->IncomingEvent(ReadAfhChannelMapCompleteBuilder::Create( - num_packets, ErrorCode::SUCCESS, handle_, AfhMode::AFH_ENABLED, afh_channel_map)); + num_packets, ErrorCode::SUCCESS, handle_, AfhMode::AFH_ENABLED, afh_channel_map)); sync_client_handler(); } @@ -1150,7 +1110,7 @@ TEST_F(AclManagerWithConnectionTest, send_read_rssi) { EXPECT_CALL(mock_connection_management_callbacks_, OnReadRssiComplete(0x00)); uint8_t num_packets = 1; test_hci_layer_->IncomingEvent( - ReadRssiCompleteBuilder::Create(num_packets, ErrorCode::SUCCESS, handle_, 0x00)); + ReadRssiCompleteBuilder::Create(num_packets, ErrorCode::SUCCESS, handle_, 0x00)); sync_client_handler(); } @@ -1163,13 +1123,13 @@ TEST_F(AclManagerWithConnectionTest, send_read_clock) { EXPECT_CALL(mock_connection_management_callbacks_, OnReadClockComplete(0x00002e6a, 0x0000)); uint8_t num_packets = 1; - test_hci_layer_->IncomingEvent(ReadClockCompleteBuilder::Create( - num_packets, ErrorCode::SUCCESS, handle_, 0x00002e6a, 0x0000)); + test_hci_layer_->IncomingEvent(ReadClockCompleteBuilder::Create(num_packets, ErrorCode::SUCCESS, + handle_, 0x00002e6a, 0x0000)); sync_client_handler(); } class AclManagerWithResolvableAddressTest : public AclManagerNoCallbacksTest { - protected: +protected: void SetUp() override { test_hci_layer_ = new HciLayerFake; // Ownership is transferred to registry test_controller_ = new TestController; @@ -1178,7 +1138,8 @@ class AclManagerWithResolvableAddressTest : public AclManagerNoCallbacksTest { client_handler_ = fake_registry_.GetTestModuleHandler(&HciLayer::Factory); ASSERT_NE(client_handler_, nullptr); fake_registry_.Start(&thread_); - acl_manager_ = static_cast(fake_registry_.GetModuleUnderTest(&AclManager::Factory)); + acl_manager_ = + static_cast(fake_registry_.GetModuleUnderTest(&AclManager::Factory)); Address::FromString("A1:A2:A3:A4:A5:A6", remote); hci::Address address; @@ -1189,13 +1150,12 @@ class AclManagerWithResolvableAddressTest : public AclManagerNoCallbacksTest { auto minimum_rotation_time = std::chrono::milliseconds(7 * 60 * 1000); auto maximum_rotation_time = std::chrono::milliseconds(15 * 60 * 1000); acl_manager_->SetPrivacyPolicyForInitiatorAddress( - LeAddressManager::AddressPolicy::USE_RESOLVABLE_ADDRESS, - address_with_type, - minimum_rotation_time, - maximum_rotation_time); + LeAddressManager::AddressPolicy::USE_RESOLVABLE_ADDRESS, address_with_type, + minimum_rotation_time, maximum_rotation_time); GetConnectionManagementCommand(OpCode::LE_SET_RANDOM_ADDRESS); - test_hci_layer_->IncomingEvent(LeSetRandomAddressCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); + test_hci_layer_->IncomingEvent( + LeSetRandomAddressCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); } }; @@ -1206,7 +1166,7 @@ TEST_F(AclManagerWithResolvableAddressTest, create_connection_cancel_fail) { // Add device to connect list GetConnectionManagementCommand(OpCode::LE_ADD_DEVICE_TO_FILTER_ACCEPT_LIST); test_hci_layer_->IncomingEvent( - LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); + LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); // send create connection command GetConnectionManagementCommand(OpCode::LE_CREATE_CONNECTION); @@ -1227,29 +1187,23 @@ TEST_F(AclManagerWithResolvableAddressTest, create_connection_cancel_fail) { // receive connection complete of first device test_hci_layer_->IncomingLeMetaEvent(LeConnectionCompleteBuilder::Create( - ErrorCode::SUCCESS, - 0x123, - Role::PERIPHERAL, - AddressType::PUBLIC_DEVICE_ADDRESS, - remote, - 0x0100, - 0x0010, - 0x0011, - ClockAccuracy::PPM_30)); + ErrorCode::SUCCESS, 0x123, Role::PERIPHERAL, AddressType::PUBLIC_DEVICE_ADDRESS, remote, + 0x0100, 0x0010, 0x0011, ClockAccuracy::PPM_30)); // receive create connection cancel complete with ErrorCode::CONNECTION_ALREADY_EXISTS - test_hci_layer_->IncomingEvent( - LeCreateConnectionCancelCompleteBuilder::Create(0x01, ErrorCode::CONNECTION_ALREADY_EXISTS)); + test_hci_layer_->IncomingEvent(LeCreateConnectionCancelCompleteBuilder::Create( + 0x01, ErrorCode::CONNECTION_ALREADY_EXISTS)); // Add another device to connect list GetConnectionManagementCommand(OpCode::LE_ADD_DEVICE_TO_FILTER_ACCEPT_LIST); - test_hci_layer_->IncomingEvent(LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); + test_hci_layer_->IncomingEvent( + LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); // Sync events. } class AclManagerLifeCycleTest : public AclManagerNoCallbacksTest { - protected: +protected: void SetUp() override { AclManagerNoCallbacksTest::SetUp(); acl_manager_->RegisterCallbacks(&mock_connection_callback_, client_handler_); @@ -1273,8 +1227,8 @@ TEST_F(AclManagerLifeCycleTest, unregister_classic_after_create_connection) { // Inject peer sending connection complete auto connection_future = GetConnectionFuture(); - test_hci_layer_->IncomingEvent( - ConnectionCompleteBuilder::Create(ErrorCode::SUCCESS, handle_, remote, LinkType::ACL, Enable::DISABLED)); + test_hci_layer_->IncomingEvent(ConnectionCompleteBuilder::Create( + ErrorCode::SUCCESS, handle_, remote, LinkType::ACL, Enable::DISABLED)); sync_client_handler(); auto connection_future_status = connection_future.wait_for(kShortTimeout); @@ -1285,11 +1239,12 @@ TEST_F(AclManagerLifeCycleTest, unregister_le_before_connection_complete) { AddressWithType remote_with_type(remote, AddressType::PUBLIC_DEVICE_ADDRESS); acl_manager_->CreateLeConnection(remote_with_type, true); GetConnectionManagementCommand(OpCode::LE_ADD_DEVICE_TO_FILTER_ACCEPT_LIST); - test_hci_layer_->IncomingEvent(LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); + test_hci_layer_->IncomingEvent( + LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); auto packet = GetConnectionManagementCommand(OpCode::LE_CREATE_CONNECTION); auto le_connection_management_command_view = - LeConnectionManagementCommandView::Create(AclCommandView::Create(packet)); + LeConnectionManagementCommandView::Create(AclCommandView::Create(packet)); auto command_view = LeCreateConnectionView::Create(le_connection_management_command_view); ASSERT_TRUE(command_view.IsValid()); if (use_accept_list_) { @@ -1307,15 +1262,8 @@ TEST_F(AclManagerLifeCycleTest, unregister_le_before_connection_complete) { auto connection_future = GetLeConnectionFuture(); test_hci_layer_->IncomingLeMetaEvent(LeConnectionCompleteBuilder::Create( - ErrorCode::SUCCESS, - 0x123, - Role::PERIPHERAL, - AddressType::PUBLIC_DEVICE_ADDRESS, - remote, - 0x0100, - 0x0010, - 0x0500, - ClockAccuracy::PPM_30)); + ErrorCode::SUCCESS, 0x123, Role::PERIPHERAL, AddressType::PUBLIC_DEVICE_ADDRESS, remote, + 0x0100, 0x0010, 0x0500, ClockAccuracy::PPM_30)); sync_client_handler(); auto connection_future_status = connection_future.wait_for(kShortTimeout); @@ -1326,11 +1274,12 @@ TEST_F(AclManagerLifeCycleTest, unregister_le_before_enhanced_connection_complet AddressWithType remote_with_type(remote, AddressType::PUBLIC_DEVICE_ADDRESS); acl_manager_->CreateLeConnection(remote_with_type, true); GetConnectionManagementCommand(OpCode::LE_ADD_DEVICE_TO_FILTER_ACCEPT_LIST); - test_hci_layer_->IncomingEvent(LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); + test_hci_layer_->IncomingEvent( + LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); auto packet = GetConnectionManagementCommand(OpCode::LE_CREATE_CONNECTION); auto le_connection_management_command_view = - LeConnectionManagementCommandView::Create(AclCommandView::Create(packet)); + LeConnectionManagementCommandView::Create(AclCommandView::Create(packet)); auto command_view = LeCreateConnectionView::Create(le_connection_management_command_view); ASSERT_TRUE(command_view.IsValid()); if (use_accept_list_) { @@ -1348,17 +1297,8 @@ TEST_F(AclManagerLifeCycleTest, unregister_le_before_enhanced_connection_complet auto connection_future = GetLeConnectionFuture(); test_hci_layer_->IncomingLeMetaEvent(LeEnhancedConnectionCompleteBuilder::Create( - ErrorCode::SUCCESS, - 0x123, - Role::PERIPHERAL, - AddressType::PUBLIC_DEVICE_ADDRESS, - remote, - Address::kEmpty, - Address::kEmpty, - 0x0100, - 0x0010, - 0x0500, - ClockAccuracy::PPM_30)); + ErrorCode::SUCCESS, 0x123, Role::PERIPHERAL, AddressType::PUBLIC_DEVICE_ADDRESS, remote, + Address::kEmpty, Address::kEmpty, 0x0100, 0x0010, 0x0500, ClockAccuracy::PPM_30)); sync_client_handler(); auto connection_future_status = connection_future.wait_for(kShortTimeout); @@ -1366,7 +1306,7 @@ TEST_F(AclManagerLifeCycleTest, unregister_le_before_enhanced_connection_complet } class AclManagerWithConnectionAssemblerTest : public AclManagerWithConnectionTest { - protected: +protected: void SetUp() override { AclManagerWithConnectionTest::SetUp(); connection_queue_end_ = connection_->GetAclQueueEnd(); @@ -1388,12 +1328,8 @@ class AclManagerWithConnectionAssemblerTest : public AclManagerWithConnectionTes auto payload_builder = std::make_unique(acl_payload); test_hci_layer_->IncomingAclData( - handle_, - AclBuilder::Create( - handle_, - PacketBoundaryFlag::FIRST_AUTOMATICALLY_FLUSHABLE, - BroadcastFlag::POINT_TO_POINT, - std::move(payload_builder))); + handle_, AclBuilder::Create(handle_, PacketBoundaryFlag::FIRST_AUTOMATICALLY_FLUSHABLE, + BroadcastFlag::POINT_TO_POINT, std::move(payload_builder))); } void ReceiveAndCheckSinglePacket(const std::vector& acl_payload) { @@ -1428,30 +1364,21 @@ TEST_F(AclManagerWithConnectionAssemblerTest, assembler_test_single_packet) {} TEST_F(AclManagerWithConnectionAssemblerTest, assembler_test_short_packet_discarded) { std::vector invalid_payload{1, 2}; test_hci_layer_->IncomingAclData( - handle_, - AclBuilder::Create( - handle_, - PacketBoundaryFlag::FIRST_AUTOMATICALLY_FLUSHABLE, - BroadcastFlag::POINT_TO_POINT, - std::make_unique(invalid_payload))); + handle_, AclBuilder::Create(handle_, PacketBoundaryFlag::FIRST_AUTOMATICALLY_FLUSHABLE, + BroadcastFlag::POINT_TO_POINT, + std::make_unique(invalid_payload))); } TEST_F(AclManagerWithConnectionAssemblerTest, assembler_test_two_short_packets_discarded) { std::vector invalid_payload{1, 2}; test_hci_layer_->IncomingAclData( - handle_, - AclBuilder::Create( - handle_, - PacketBoundaryFlag::FIRST_AUTOMATICALLY_FLUSHABLE, - BroadcastFlag::POINT_TO_POINT, - std::make_unique(invalid_payload))); + handle_, AclBuilder::Create(handle_, PacketBoundaryFlag::FIRST_AUTOMATICALLY_FLUSHABLE, + BroadcastFlag::POINT_TO_POINT, + std::make_unique(invalid_payload))); test_hci_layer_->IncomingAclData( - handle_, - AclBuilder::Create( - handle_, - PacketBoundaryFlag::FIRST_AUTOMATICALLY_FLUSHABLE, - BroadcastFlag::POINT_TO_POINT, - std::make_unique(invalid_payload))); + handle_, AclBuilder::Create(handle_, PacketBoundaryFlag::FIRST_AUTOMATICALLY_FLUSHABLE, + BroadcastFlag::POINT_TO_POINT, + std::make_unique(invalid_payload))); } TEST_F(AclManagerWithConnectionAssemblerTest, assembler_test_single_valid_packet) { @@ -1462,22 +1389,16 @@ TEST_F(AclManagerWithConnectionAssemblerTest, assembler_test_one_byte_packets) { size_t payload_size = 0x30; std::vector payload = MakeAclPayload(payload_size, 0xABB /* cid */, 4 /* offset */); test_hci_layer_->IncomingAclData( - handle_, - AclBuilder::Create( - handle_, - PacketBoundaryFlag::FIRST_AUTOMATICALLY_FLUSHABLE, - BroadcastFlag::POINT_TO_POINT, - std::make_unique( - std::vector{payload.cbegin(), payload.cbegin() + 1}))); + handle_, AclBuilder::Create(handle_, PacketBoundaryFlag::FIRST_AUTOMATICALLY_FLUSHABLE, + BroadcastFlag::POINT_TO_POINT, + std::make_unique(std::vector{ + payload.cbegin(), payload.cbegin() + 1}))); for (size_t i = 1; i < payload.size(); i++) { test_hci_layer_->IncomingAclData( - handle_, - AclBuilder::Create( - handle_, - PacketBoundaryFlag::CONTINUING_FRAGMENT, - BroadcastFlag::POINT_TO_POINT, - std::make_unique( - std::vector{payload.cbegin() + i, payload.cbegin() + i + 1}))); + handle_, AclBuilder::Create(handle_, PacketBoundaryFlag::CONTINUING_FRAGMENT, + BroadcastFlag::POINT_TO_POINT, + std::make_unique(std::vector{ + payload.cbegin() + i, payload.cbegin() + i + 1}))); } ReceiveAndCheckSinglePacket(payload); } @@ -1486,22 +1407,17 @@ TEST_F(AclManagerWithConnectionAssemblerTest, assembler_test_two_byte_packets) { size_t payload_size = 0x30; // must be even std::vector payload = MakeAclPayload(payload_size, 0xABB /* cid */, 4 /* offset */); test_hci_layer_->IncomingAclData( - handle_, - AclBuilder::Create( - handle_, - PacketBoundaryFlag::FIRST_AUTOMATICALLY_FLUSHABLE, - BroadcastFlag::POINT_TO_POINT, - std::make_unique( - std::vector{payload.cbegin(), payload.cbegin() + 2}))); + handle_, AclBuilder::Create(handle_, PacketBoundaryFlag::FIRST_AUTOMATICALLY_FLUSHABLE, + BroadcastFlag::POINT_TO_POINT, + std::make_unique(std::vector{ + payload.cbegin(), payload.cbegin() + 2}))); for (size_t i = 1; i < payload.size() / 2; i++) { test_hci_layer_->IncomingAclData( - handle_, - AclBuilder::Create( handle_, - PacketBoundaryFlag::CONTINUING_FRAGMENT, - BroadcastFlag::POINT_TO_POINT, - std::make_unique( - std::vector{payload.cbegin() + 2 * i, payload.cbegin() + 2 * (i + 1)}))); + AclBuilder::Create(handle_, PacketBoundaryFlag::CONTINUING_FRAGMENT, + BroadcastFlag::POINT_TO_POINT, + std::make_unique(std::vector{ + payload.cbegin() + 2 * i, payload.cbegin() + 2 * (i + 1)}))); } ReceiveAndCheckSinglePacket(payload); } @@ -1510,32 +1426,27 @@ TEST_F(AclManagerWithConnectionAssemblerTest, assembler_test_continuation_withou size_t payload_size = 0x30; std::vector payload = MakeAclPayload(payload_size, 0xABB /* cid */, 4 /* offset */); test_hci_layer_->IncomingAclData( - handle_, - AclBuilder::Create( - handle_, - PacketBoundaryFlag::CONTINUING_FRAGMENT, - BroadcastFlag::POINT_TO_POINT, - std::make_unique(std::vector{payload.cbegin(), payload.cend()}))); + handle_, AclBuilder::Create(handle_, PacketBoundaryFlag::CONTINUING_FRAGMENT, + BroadcastFlag::POINT_TO_POINT, + std::make_unique(std::vector{ + payload.cbegin(), payload.cend()}))); } TEST_F(AclManagerWithConnectionAssemblerTest, assembler_test_drop_broadcasts) { test_hci_layer_->IncomingAclData( - handle_, - AclBuilder::Create( - handle_, - PacketBoundaryFlag::FIRST_AUTOMATICALLY_FLUSHABLE, - BroadcastFlag::ACTIVE_PERIPHERAL_BROADCAST, - std::make_unique(MakeAclPayload(20, 0xBBB /* cid */, 5 /* offset */)))); + handle_, AclBuilder::Create(handle_, PacketBoundaryFlag::FIRST_AUTOMATICALLY_FLUSHABLE, + BroadcastFlag::ACTIVE_PERIPHERAL_BROADCAST, + std::make_unique(MakeAclPayload( + 20, 0xBBB /* cid */, 5 /* offset */)))); } TEST_F(AclManagerWithConnectionAssemblerTest, assembler_test_drop_non_flushable) { test_hci_layer_->IncomingAclData( - handle_, - AclBuilder::Create( handle_, - PacketBoundaryFlag::FIRST_NON_AUTOMATICALLY_FLUSHABLE, - BroadcastFlag::POINT_TO_POINT, - std::make_unique(MakeAclPayload(20, 0xAAA /* cid */, 6 /* offset */)))); + AclBuilder::Create(handle_, PacketBoundaryFlag::FIRST_NON_AUTOMATICALLY_FLUSHABLE, + BroadcastFlag::POINT_TO_POINT, + std::make_unique( + MakeAclPayload(20, 0xAAA /* cid */, 6 /* offset */)))); } } // namespace acl_manager diff --git a/system/gd/hci/acl_manager_unittest.cc b/system/gd/hci/acl_manager_unittest.cc index db752f13fc8..5e3cd1959df 100644 --- a/system/gd/hci/acl_manager_unittest.cc +++ b/system/gd/hci/acl_manager_unittest.cc @@ -67,8 +67,8 @@ struct { ClassOfDevice class_of_device; const uint16_t handle; } remote_device[2] = { - {.address = {}, .class_of_device = {}, .handle = kHciHandleA}, - {.address = {}, .class_of_device = {}, .handle = kHciHandleB}, + {.address = {}, .class_of_device = {}, .handle = kHciHandleA}, + {.address = {}, .class_of_device = {}, .handle = kHciHandleB}, }; } // namespace @@ -83,18 +83,12 @@ std::unique_ptr NextPayload(uint16_t handle) { } class TestController : public Controller { - public: - uint16_t GetAclPacketLength() const override { - return acl_buffer_length_; - } +public: + uint16_t GetAclPacketLength() const override { return acl_buffer_length_; } - uint16_t GetNumAclPacketBuffers() const override { - return total_acl_buffers_; - } + uint16_t GetNumAclPacketBuffers() const override { return total_acl_buffers_; } - bool IsSupported(bluetooth::hci::OpCode /* op_code */) const override { - return false; - } + bool IsSupported(bluetooth::hci::OpCode /* op_code */) const override { return false; } LeBufferSize GetLeBufferSize() const override { LeBufferSize le_buffer_size; @@ -103,19 +97,19 @@ class TestController : public Controller { return le_buffer_size; } - protected: +protected: void Start() override {} void Stop() override {} void ListDependencies(ModuleList* /* list */) const {} - private: +private: uint16_t acl_buffer_length_ = 1024; uint16_t total_acl_buffers_ = 2; common::ContextualCallback acl_cb_; }; class MockConnectionCallback : public ConnectionCallbacks { - public: +public: void OnConnectSuccess(std::unique_ptr connection) override { // Convert to std::shared_ptr during push_back() connections_.push_back(std::move(connection)); @@ -127,11 +121,9 @@ class MockConnectionCallback : public ConnectionCallbacks { MOCK_METHOD(void, OnConnectRequest, (Address, ClassOfDevice), (override)); MOCK_METHOD(void, OnConnectFail, (Address, ErrorCode reason, bool locally_initiated), (override)); - size_t NumberOfConnections() const { - return connections_.size(); - } + size_t NumberOfConnections() const { return connections_.size(); } - private: +private: friend class AclManagerWithCallbacksTest; friend class AclManagerNoCallbacksTest; @@ -141,10 +133,9 @@ class MockConnectionCallback : public ConnectionCallbacks { }; class MockLeConnectionCallbacks : public LeConnectionCallbacks { - public: - void OnLeConnectSuccess( - AddressWithType /* address_with_type */, - std::unique_ptr connection) override { +public: + void OnLeConnectSuccess(AddressWithType /* address_with_type */, + std::unique_ptr connection) override { le_connections_.push_back(std::move(connection)); if (le_connection_promise_ != nullptr) { std::promise* prom = le_connection_promise_.release(); @@ -159,7 +150,7 @@ class MockLeConnectionCallbacks : public LeConnectionCallbacks { }; class AclManagerBaseTest : public ::testing::Test { - protected: +protected: void SetUp() override { common::InitFlags::SetAllForTesting(); test_hci_layer_ = new HciLayerFake; // Ownership is transferred to registry @@ -179,7 +170,8 @@ class AclManagerBaseTest : public ::testing::Test { void sync_client_handler() { std::promise promise; auto future = promise.get_future(); - client_handler_->Post(common::BindOnce(&std::promise::set_value, common::Unretained(&promise))); + client_handler_->Post( + common::BindOnce(&std::promise::set_value, common::Unretained(&promise))); auto future_status = future.wait_for(std::chrono::seconds(1)); ASSERT_EQ(future_status, std::future_status::ready); } @@ -194,29 +186,27 @@ class AclManagerBaseTest : public ::testing::Test { }; class AclManagerNoCallbacksTest : public AclManagerBaseTest { - protected: +protected: void SetUp() override { AclManagerBaseTest::SetUp(); - acl_manager_ = static_cast(fake_registry_.GetModuleUnderTest(&AclManager::Factory)); + acl_manager_ = + static_cast(fake_registry_.GetModuleUnderTest(&AclManager::Factory)); - local_address_with_type_ = AddressWithType( - Address::FromString(kLocalRandomAddressString).value(), hci::AddressType::RANDOM_DEVICE_ADDRESS); + local_address_with_type_ = + AddressWithType(Address::FromString(kLocalRandomAddressString).value(), + hci::AddressType::RANDOM_DEVICE_ADDRESS); acl_manager_->SetPrivacyPolicyForInitiatorAddress( - LeAddressManager::AddressPolicy::USE_STATIC_ADDRESS, - local_address_with_type_, - kMinimumRotationTime, - kMaximumRotationTime); + LeAddressManager::AddressPolicy::USE_STATIC_ADDRESS, local_address_with_type_, + kMinimumRotationTime, kMaximumRotationTime); auto command = test_hci_layer_->GetCommand(); ASSERT_TRUE(command.IsValid()); ASSERT_EQ(OpCode::LE_SET_RANDOM_ADDRESS, command.GetOpCode()); } - void TearDown() override { - AclManagerBaseTest::TearDown(); - } + void TearDown() override { AclManagerBaseTest::TearDown(); } AddressWithType local_address_with_type_; const bool use_accept_list_ = true; // gd currently only supports connect list @@ -225,23 +215,21 @@ class AclManagerNoCallbacksTest : public AclManagerBaseTest { std::promise promise; auto future = promise.get_future(); queue_end->RegisterEnqueue( - client_handler_, - common::Bind( - [](decltype(queue_end) queue_end, uint16_t handle, std::promise promise) { - queue_end->UnregisterEnqueue(); - promise.set_value(); - return NextPayload(handle); - }, - queue_end, - handle, - common::Passed(std::move(promise)))); + client_handler_, + common::Bind( + [](decltype(queue_end) queue_end, uint16_t handle, std::promise promise) { + queue_end->UnregisterEnqueue(); + promise.set_value(); + return NextPayload(handle); + }, + queue_end, handle, common::Passed(std::move(promise)))); auto status = future.wait_for(2s); ASSERT_EQ(status, std::future_status::ready); } }; class AclManagerWithCallbacksTest : public AclManagerNoCallbacksTest { - protected: +protected: void SetUp() override { AclManagerNoCallbacksTest::SetUp(); acl_manager_->RegisterCallbacks(&mock_connection_callbacks_, client_handler_); @@ -273,7 +261,8 @@ class AclManagerWithCallbacksTest : public AclManagerNoCallbacksTest { std::future> GetConnectionFuture() { // Run on main thread - mock_connection_callbacks_.connection_promise_ = std::promise>(); + mock_connection_callbacks_.connection_promise_ = + std::promise>(); mock_connection_callbacks_.is_promise_set_ = true; return mock_connection_callbacks_.connection_promise_.get_future(); } @@ -287,24 +276,20 @@ class AclManagerWithCallbacksTest : public AclManagerNoCallbacksTest { return mock_connection_callbacks_.connections_.back(); } - size_t NumberOfConnections() { - return mock_connection_callbacks_.connections_.size(); - } + size_t NumberOfConnections() { return mock_connection_callbacks_.connections_.size(); } std::shared_ptr GetLastLeConnection() { return mock_le_connection_callbacks_.le_connections_.back(); } - size_t NumberOfLeConnections() { - return mock_le_connection_callbacks_.le_connections_.size(); - } + size_t NumberOfLeConnections() { return mock_le_connection_callbacks_.le_connections_.size(); } MockConnectionCallback mock_connection_callbacks_; MockLeConnectionCallbacks mock_le_connection_callbacks_; }; class AclManagerWithConnectionTest : public AclManagerWithCallbacksTest { - protected: +protected: void SetUp() override { AclManagerWithCallbacksTest::SetUp(); @@ -316,11 +301,12 @@ class AclManagerWithConnectionTest : public AclManagerWithCallbacksTest { // Wait for the connection request auto last_command = test_hci_layer_->GetCommand(OpCode::CREATE_CONNECTION); - EXPECT_CALL(mock_connection_management_callbacks_, OnRoleChange(hci::ErrorCode::SUCCESS, Role::CENTRAL)); + EXPECT_CALL(mock_connection_management_callbacks_, + OnRoleChange(hci::ErrorCode::SUCCESS, Role::CENTRAL)); auto first_connection = GetConnectionFuture(); test_hci_layer_->IncomingEvent(ConnectionCompleteBuilder::Create( - ErrorCode::SUCCESS, handle_, remote, LinkType::ACL, Enable::DISABLED)); + ErrorCode::SUCCESS, handle_, remote, LinkType::ACL, Enable::DISABLED)); auto first_connection_status = first_connection.wait_for(2s); ASSERT_EQ(first_connection_status, std::future_status::ready); @@ -340,38 +326,24 @@ class AclManagerWithConnectionTest : public AclManagerWithCallbacksTest { std::shared_ptr connection_; class MockConnectionManagementCallbacks : public ConnectionManagementCallbacks { - public: + public: MOCK_METHOD1(OnConnectionPacketTypeChanged, void(uint16_t packet_type)); MOCK_METHOD1(OnAuthenticationComplete, void(hci::ErrorCode hci_status)); MOCK_METHOD1(OnEncryptionChange, void(EncryptionEnabled enabled)); MOCK_METHOD0(OnChangeConnectionLinkKeyComplete, void()); MOCK_METHOD1(OnReadClockOffsetComplete, void(uint16_t clock_offse)); MOCK_METHOD3(OnModeChange, void(ErrorCode status, Mode current_mode, uint16_t interval)); - MOCK_METHOD5( - OnSniffSubrating, - void( - ErrorCode status, - uint16_t maximum_transmit_latency, - uint16_t maximum_receive_latency, - uint16_t minimum_remote_timeout, - uint16_t minimum_local_timeout)); - MOCK_METHOD5( - OnQosSetupComplete, - void( - ServiceType service_type, - uint32_t token_rate, - uint32_t peak_bandwidth, - uint32_t latency, - uint32_t delay_variation)); - MOCK_METHOD6( - OnFlowSpecificationComplete, - void( - FlowDirection flow_direction, - ServiceType service_type, - uint32_t token_rate, - uint32_t token_bucket_size, - uint32_t peak_bandwidth, - uint32_t access_latency)); + MOCK_METHOD5(OnSniffSubrating, + void(ErrorCode status, uint16_t maximum_transmit_latency, + uint16_t maximum_receive_latency, uint16_t minimum_remote_timeout, + uint16_t minimum_local_timeout)); + MOCK_METHOD5(OnQosSetupComplete, + void(ServiceType service_type, uint32_t token_rate, uint32_t peak_bandwidth, + uint32_t latency, uint32_t delay_variation)); + MOCK_METHOD6(OnFlowSpecificationComplete, + void(FlowDirection flow_direction, ServiceType service_type, uint32_t token_rate, + uint32_t token_bucket_size, uint32_t peak_bandwidth, + uint32_t access_latency)); MOCK_METHOD0(OnFlushOccurred, void()); MOCK_METHOD1(OnRoleDiscoveryComplete, void(Role current_role)); MOCK_METHOD1(OnReadLinkPolicySettingsComplete, void(uint16_t link_policy_settings)); @@ -380,25 +352,26 @@ class AclManagerWithConnectionTest : public AclManagerWithCallbacksTest { MOCK_METHOD1(OnReadLinkSupervisionTimeoutComplete, void(uint16_t link_supervision_timeout)); MOCK_METHOD1(OnReadFailedContactCounterComplete, void(uint16_t failed_contact_counter)); MOCK_METHOD1(OnReadLinkQualityComplete, void(uint8_t link_quality)); - MOCK_METHOD2(OnReadAfhChannelMapComplete, void(AfhMode afh_mode, std::array afh_channel_map)); + MOCK_METHOD2(OnReadAfhChannelMapComplete, + void(AfhMode afh_mode, std::array afh_channel_map)); MOCK_METHOD1(OnReadRssiComplete, void(uint8_t rssi)); MOCK_METHOD2(OnReadClockComplete, void(uint32_t clock, uint16_t accuracy)); MOCK_METHOD1(OnCentralLinkKeyComplete, void(KeyFlag flag)); MOCK_METHOD2(OnRoleChange, void(ErrorCode hci_status, Role new_role)); MOCK_METHOD1(OnDisconnection, void(ErrorCode reason)); - MOCK_METHOD4( - OnReadRemoteVersionInformationComplete, - void(hci::ErrorCode hci_status, uint8_t lmp_version, uint16_t manufacturer_name, uint16_t sub_version)); + MOCK_METHOD4(OnReadRemoteVersionInformationComplete, + void(hci::ErrorCode hci_status, uint8_t lmp_version, uint16_t manufacturer_name, + uint16_t sub_version)); MOCK_METHOD1(OnReadRemoteSupportedFeaturesComplete, void(uint64_t features)); - MOCK_METHOD3( - OnReadRemoteExtendedFeaturesComplete, void(uint8_t page_number, uint8_t max_page_number, uint64_t features)); + MOCK_METHOD3(OnReadRemoteExtendedFeaturesComplete, + void(uint8_t page_number, uint8_t max_page_number, uint64_t features)); } mock_connection_management_callbacks_; }; TEST_F(AclManagerWithCallbacksTest, startup_teardown) {} class AclManagerWithLeConnectionTest : public AclManagerWithCallbacksTest { - protected: +protected: void SetUp() override { AclManagerWithCallbacksTest::SetUp(); @@ -407,10 +380,10 @@ class AclManagerWithLeConnectionTest : public AclManagerWithCallbacksTest { acl_manager_->CreateLeConnection(remote_with_type_, true); test_hci_layer_->GetCommand(OpCode::LE_ADD_DEVICE_TO_FILTER_ACCEPT_LIST); test_hci_layer_->IncomingEvent( - LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); + LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); auto packet = test_hci_layer_->GetCommand(OpCode::LE_CREATE_CONNECTION); auto le_connection_management_command_view = - LeConnectionManagementCommandView::Create(AclCommandView::Create(packet)); + LeConnectionManagementCommandView::Create(AclCommandView::Create(packet)); auto command_view = LeCreateConnectionView::Create(le_connection_management_command_view); ASSERT_TRUE(command_view.IsValid()); if (use_accept_list_) { @@ -422,24 +395,17 @@ class AclManagerWithLeConnectionTest : public AclManagerWithCallbacksTest { } test_hci_layer_->IncomingEvent( - LeCreateConnectionStatusBuilder::Create(ErrorCode::SUCCESS, 0x01)); + LeCreateConnectionStatusBuilder::Create(ErrorCode::SUCCESS, 0x01)); auto first_connection = GetLeConnectionFuture(); test_hci_layer_->IncomingLeMetaEvent(LeConnectionCompleteBuilder::Create( - ErrorCode::SUCCESS, - handle_, - Role::PERIPHERAL, - AddressType::PUBLIC_DEVICE_ADDRESS, - remote_public_address, - 0x0100, - 0x0010, - 0x0C80, - ClockAccuracy::PPM_30)); + ErrorCode::SUCCESS, handle_, Role::PERIPHERAL, AddressType::PUBLIC_DEVICE_ADDRESS, + remote_public_address, 0x0100, 0x0010, 0x0C80, ClockAccuracy::PPM_30)); test_hci_layer_->GetCommand(OpCode::LE_REMOVE_DEVICE_FROM_FILTER_ACCEPT_LIST); test_hci_layer_->IncomingEvent( - LeRemoveDeviceFromFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); + LeRemoveDeviceFromFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); auto first_connection_status = first_connection.wait_for(2s); ASSERT_EQ(first_connection_status, std::future_status::ready); @@ -456,7 +422,8 @@ class AclManagerWithLeConnectionTest : public AclManagerWithCallbacksTest { void sync_client_handler() { std::promise promise; auto future = promise.get_future(); - client_handler_->Post(common::BindOnce(&std::promise::set_value, common::Unretained(&promise))); + client_handler_->Post( + common::BindOnce(&std::promise::set_value, common::Unretained(&promise))); auto future_status = future.wait_for(std::chrono::seconds(1)); ASSERT_EQ(future_status, std::future_status::ready); } @@ -469,7 +436,7 @@ class AclManagerWithLeConnectionTest : public AclManagerWithCallbacksTest { }; class AclManagerWithResolvableAddressTest : public AclManagerWithCallbacksTest { - protected: +protected: void SetUp() override { test_hci_layer_ = new HciLayerFake; // Ownership is transferred to registry test_controller_ = new TestController; @@ -478,7 +445,8 @@ class AclManagerWithResolvableAddressTest : public AclManagerWithCallbacksTest { client_handler_ = fake_registry_.GetTestModuleHandler(&HciLayer::Factory); ASSERT_NE(client_handler_, nullptr); fake_registry_.Start(&thread_); - acl_manager_ = static_cast(fake_registry_.GetModuleUnderTest(&AclManager::Factory)); + acl_manager_ = + static_cast(fake_registry_.GetModuleUnderTest(&AclManager::Factory)); hci::Address address; Address::FromString("D0:05:04:03:02:01", address); hci::AddressWithType address_with_type(address, hci::AddressType::RANDOM_DEVICE_ADDRESS); @@ -487,14 +455,12 @@ class AclManagerWithResolvableAddressTest : public AclManagerWithCallbacksTest { auto minimum_rotation_time = std::chrono::milliseconds(7 * 60 * 1000); auto maximum_rotation_time = std::chrono::milliseconds(15 * 60 * 1000); acl_manager_->SetPrivacyPolicyForInitiatorAddress( - LeAddressManager::AddressPolicy::USE_RESOLVABLE_ADDRESS, - address_with_type, - minimum_rotation_time, - maximum_rotation_time); + LeAddressManager::AddressPolicy::USE_RESOLVABLE_ADDRESS, address_with_type, + minimum_rotation_time, maximum_rotation_time); test_hci_layer_->GetCommand(OpCode::LE_SET_RANDOM_ADDRESS); test_hci_layer_->IncomingEvent( - LeSetRandomAddressCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); + LeSetRandomAddressCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); } }; @@ -513,7 +479,7 @@ TEST_F(AclManagerNoCallbacksTest, unregister_classic_before_connection_request) // Inject peer sending connection request test_hci_layer_->IncomingEvent(ConnectionRequestBuilder::Create( - local_address_with_type_.GetAddress(), class_of_device, ConnectionRequestLinkType::ACL)); + local_address_with_type_.GetAddress(), class_of_device, ConnectionRequestLinkType::ACL)); sync_client_handler(); // There should be no connections @@ -529,9 +495,8 @@ TEST_F(AclManagerWithCallbacksTest, two_remote_connection_requests_ABAB) { { // Device A sends connection request test_hci_layer_->IncomingEvent(ConnectionRequestBuilder::Create( - remote_device[0].address, - remote_device[0].class_of_device, - ConnectionRequestLinkType::ACL)); + remote_device[0].address, remote_device[0].class_of_device, + ConnectionRequestLinkType::ACL)); sync_client_handler(); // Verify we accept this connection auto command = test_hci_layer_->GetCommand(OpCode::ACCEPT_CONNECTION_REQUEST); @@ -540,9 +505,8 @@ TEST_F(AclManagerWithCallbacksTest, two_remote_connection_requests_ABAB) { { // Device B sends connection request test_hci_layer_->IncomingEvent(ConnectionRequestBuilder::Create( - remote_device[1].address, - remote_device[1].class_of_device, - ConnectionRequestLinkType::ACL)); + remote_device[1].address, remote_device[1].class_of_device, + ConnectionRequestLinkType::ACL)); sync_client_handler(); // Verify we accept this connection auto command = test_hci_layer_->GetCommand(OpCode::ACCEPT_CONNECTION_REQUEST); @@ -554,30 +518,28 @@ TEST_F(AclManagerWithCallbacksTest, two_remote_connection_requests_ABAB) { // Device A completes first connection auto future = GetConnectionFuture(); test_hci_layer_->IncomingEvent(ConnectionCompleteBuilder::Create( - ErrorCode::SUCCESS, - remote_device[0].handle, - remote_device[0].address, - LinkType::ACL, - Enable::DISABLED)); - ASSERT_EQ(std::future_status::ready, future.wait_for(2s)) << "Timeout waiting for first connection complete"; + ErrorCode::SUCCESS, remote_device[0].handle, remote_device[0].address, LinkType::ACL, + Enable::DISABLED)); + ASSERT_EQ(std::future_status::ready, future.wait_for(2s)) + << "Timeout waiting for first connection complete"; ASSERT_EQ(1UL, NumberOfConnections()); auto connection = future.get(); - ASSERT_EQ(connection->GetAddress(), remote_device[0].address) << "First connection remote address mismatch"; + ASSERT_EQ(connection->GetAddress(), remote_device[0].address) + << "First connection remote address mismatch"; } { // Device B completes second connection auto future = GetConnectionFuture(); test_hci_layer_->IncomingEvent(ConnectionCompleteBuilder::Create( - ErrorCode::SUCCESS, - remote_device[1].handle, - remote_device[1].address, - LinkType::ACL, - Enable::DISABLED)); - ASSERT_EQ(std::future_status::ready, future.wait_for(2s)) << "Timeout waiting for second connection complete"; + ErrorCode::SUCCESS, remote_device[1].handle, remote_device[1].address, LinkType::ACL, + Enable::DISABLED)); + ASSERT_EQ(std::future_status::ready, future.wait_for(2s)) + << "Timeout waiting for second connection complete"; ASSERT_EQ(2UL, NumberOfConnections()); auto connection = future.get(); - ASSERT_EQ(connection->GetAddress(), remote_device[1].address) << "Second connection remote address mismatch"; + ASSERT_EQ(connection->GetAddress(), remote_device[1].address) + << "Second connection remote address mismatch"; } } @@ -588,9 +550,8 @@ TEST_F(AclManagerWithCallbacksTest, two_remote_connection_requests_ABBA) { { // Device A sends connection request test_hci_layer_->IncomingEvent(ConnectionRequestBuilder::Create( - remote_device[0].address, - remote_device[0].class_of_device, - ConnectionRequestLinkType::ACL)); + remote_device[0].address, remote_device[0].class_of_device, + ConnectionRequestLinkType::ACL)); sync_client_handler(); // Verify we accept this connection auto command = test_hci_layer_->GetCommand(OpCode::ACCEPT_CONNECTION_REQUEST); @@ -599,9 +560,8 @@ TEST_F(AclManagerWithCallbacksTest, two_remote_connection_requests_ABBA) { { // Device B sends connection request test_hci_layer_->IncomingEvent(ConnectionRequestBuilder::Create( - remote_device[1].address, - remote_device[1].class_of_device, - ConnectionRequestLinkType::ACL)); + remote_device[1].address, remote_device[1].class_of_device, + ConnectionRequestLinkType::ACL)); sync_client_handler(); // Verify we accept this connection auto command = test_hci_layer_->GetCommand(OpCode::ACCEPT_CONNECTION_REQUEST); @@ -613,40 +573,39 @@ TEST_F(AclManagerWithCallbacksTest, two_remote_connection_requests_ABBA) { // Device B completes first connection auto future = GetConnectionFuture(); test_hci_layer_->IncomingEvent(ConnectionCompleteBuilder::Create( - ErrorCode::SUCCESS, - remote_device[1].handle, - remote_device[1].address, - LinkType::ACL, - Enable::DISABLED)); - ASSERT_EQ(std::future_status::ready, future.wait_for(2s)) << "Timeout waiting for first connection complete"; + ErrorCode::SUCCESS, remote_device[1].handle, remote_device[1].address, LinkType::ACL, + Enable::DISABLED)); + ASSERT_EQ(std::future_status::ready, future.wait_for(2s)) + << "Timeout waiting for first connection complete"; ASSERT_EQ(1UL, NumberOfConnections()); auto connection = future.get(); - ASSERT_EQ(connection->GetAddress(), remote_device[1].address) << "First connection remote address mismatch"; + ASSERT_EQ(connection->GetAddress(), remote_device[1].address) + << "First connection remote address mismatch"; } { // Device A completes second connection auto future = GetConnectionFuture(); test_hci_layer_->IncomingEvent(ConnectionCompleteBuilder::Create( - ErrorCode::SUCCESS, - remote_device[0].handle, - remote_device[0].address, - LinkType::ACL, - Enable::DISABLED)); - ASSERT_EQ(std::future_status::ready, future.wait_for(2s)) << "Timeout waiting for second connection complete"; + ErrorCode::SUCCESS, remote_device[0].handle, remote_device[0].address, LinkType::ACL, + Enable::DISABLED)); + ASSERT_EQ(std::future_status::ready, future.wait_for(2s)) + << "Timeout waiting for second connection complete"; ASSERT_EQ(2UL, NumberOfConnections()); auto connection = future.get(); - ASSERT_EQ(connection->GetAddress(), remote_device[0].address) << "Second connection remote address mismatch"; + ASSERT_EQ(connection->GetAddress(), remote_device[0].address) + << "Second connection remote address mismatch"; } } TEST_F(AclManagerWithCallbacksTest, test_disconnection_after_request) { Address remote = *Address::FromString("12:34:56:78:9a:bc"); EXPECT_CALL(mock_connection_callbacks_, OnConnectRequest).Times(1); - test_hci_layer_->IncomingEvent(ConnectionRequestBuilder::Create( - remote, ClassOfDevice({1, 2, 3}), ConnectionRequestLinkType::ACL)); - test_hci_layer_->IncomingEvent(ConnectionCompleteBuilder::Create( - ErrorCode::REMOTE_USER_TERMINATED_CONNECTION, 0, remote, LinkType::ACL, Enable::DISABLED)); + test_hci_layer_->IncomingEvent(ConnectionRequestBuilder::Create(remote, ClassOfDevice({1, 2, 3}), + ConnectionRequestLinkType::ACL)); + test_hci_layer_->IncomingEvent( + ConnectionCompleteBuilder::Create(ErrorCode::REMOTE_USER_TERMINATED_CONNECTION, 0, remote, + LinkType::ACL, Enable::DISABLED)); } TEST_F(AclManagerWithCallbacksTest, test_disconnection_after_request_sync) { @@ -657,11 +616,12 @@ TEST_F(AclManagerWithCallbacksTest, test_disconnection_after_request_sync) { EXPECT_CALL(mock_connection_callbacks_, OnConnectRequest).WillOnce([&request_promise]() { request_promise.set_value(); }); - test_hci_layer_->IncomingEvent(ConnectionRequestBuilder::Create( - remote, ClassOfDevice({1, 2, 3}), ConnectionRequestLinkType::ACL)); + test_hci_layer_->IncomingEvent(ConnectionRequestBuilder::Create(remote, ClassOfDevice({1, 2, 3}), + ConnectionRequestLinkType::ACL)); ASSERT_EQ(std::future_status::ready, request_future.wait_for(std::chrono::seconds(1))); - test_hci_layer_->IncomingEvent(ConnectionCompleteBuilder::Create( - ErrorCode::REMOTE_USER_TERMINATED_CONNECTION, 0, remote, LinkType::ACL, Enable::DISABLED)); + test_hci_layer_->IncomingEvent( + ConnectionCompleteBuilder::Create(ErrorCode::REMOTE_USER_TERMINATED_CONNECTION, 0, remote, + LinkType::ACL, Enable::DISABLED)); } } // namespace diff --git a/system/gd/hci/address.cc b/system/gd/hci/address.cc index 74094182743..6960c30c306 100644 --- a/system/gd/hci/address.cc +++ b/system/gd/hci/address.cc @@ -34,9 +34,7 @@ const Address Address::kEmpty{{0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}; // Address cannot initialize member variables as it is a POD type // NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init) -Address::Address(const uint8_t (&addr)[6]) { - std::copy(addr, addr + kLength, data()); -} +Address::Address(const uint8_t (&addr)[6]) { std::copy(addr, addr + kLength, data()); } Address::Address(std::initializer_list l) { std::copy(l.begin(), std::min(l.begin() + kLength, l.end()), data()); @@ -58,25 +56,15 @@ std::string Address::_ToMaskedColonSepHexString(int bytes_to_mask) const { return ss.str(); } -std::string Address::ToString() const { - return _ToMaskedColonSepHexString(0); -} +std::string Address::ToString() const { return _ToMaskedColonSepHexString(0); } -std::string Address::ToColonSepHexString() const { - return _ToMaskedColonSepHexString(0); -} +std::string Address::ToColonSepHexString() const { return _ToMaskedColonSepHexString(0); } -std::string Address::ToStringForLogging() const { - return _ToMaskedColonSepHexString(0); -} +std::string Address::ToStringForLogging() const { return _ToMaskedColonSepHexString(0); } -std::string Address::ToRedactedStringForLogging() const { - return _ToMaskedColonSepHexString(4); -} +std::string Address::ToRedactedStringForLogging() const { return _ToMaskedColonSepHexString(4); } -std::string Address::ToLegacyConfigString() const { - return ToString(); -} +std::string Address::ToLegacyConfigString() const { return ToString(); } std::optional
Address::FromLegacyConfigString(const std::string& str) { return FromString(str); @@ -134,7 +122,7 @@ bool Address::FromString(const std::string& from, Address& to) { size_t Address::FromOctets(const uint8_t* from) { std::copy(from, from + kLength, data()); return kLength; -}; +} bool Address::IsValidAddress(const std::string& address) { return Address::FromString(address).has_value(); diff --git a/system/gd/hci/address.h b/system/gd/hci/address.h index bc0ce891670..3069d404bbd 100644 --- a/system/gd/hci/address.h +++ b/system/gd/hci/address.h @@ -36,7 +36,7 @@ namespace hci { class Address final : public packet::CustomFieldFixedSizeInterface
, public storage::Serializable
, public bluetooth::common::IRedactableLoggable { - public: +public: static constexpr size_t kLength = 6; // Bluetooth MAC address bytes saved in little endian format. @@ -50,12 +50,8 @@ class Address final : public packet::CustomFieldFixedSizeInterface
, Address(std::initializer_list l); // CustomFieldFixedSizeInterface methods - inline uint8_t* data() override { - return address.data(); - } - inline const uint8_t* data() const override { - return address.data(); - } + inline uint8_t* data() override { return address.data(); } + inline const uint8_t* data() const override { return address.data(); } // storage::Serializable methods std::string ToString() const override; @@ -67,28 +63,14 @@ class Address final : public packet::CustomFieldFixedSizeInterface
, std::string ToLegacyConfigString() const override; static std::optional
FromLegacyConfigString(const std::string& str); - bool operator<(const Address& rhs) const { - return address < rhs.address; - } - bool operator==(const Address& rhs) const { - return address == rhs.address; - } - bool operator>(const Address& rhs) const { - return (rhs < *this); - } - bool operator<=(const Address& rhs) const { - return !(*this > rhs); - } - bool operator>=(const Address& rhs) const { - return !(*this < rhs); - } - bool operator!=(const Address& rhs) const { - return !(*this == rhs); - } + bool operator<(const Address& rhs) const { return address < rhs.address; } + bool operator==(const Address& rhs) const { return address == rhs.address; } + bool operator>(const Address& rhs) const { return rhs < *this; } + bool operator<=(const Address& rhs) const { return !(*this > rhs); } + bool operator>=(const Address& rhs) const { return !(*this < rhs); } + bool operator!=(const Address& rhs) const { return !(*this == rhs); } - bool IsEmpty() const { - return *this == kEmpty; - } + bool IsEmpty() const { return *this == kEmpty; } // Converts |string| to Address and places it in |to|. If |from| does // not represent a Bluetooth address, |to| is not modified and this function @@ -103,7 +85,7 @@ class Address final : public packet::CustomFieldFixedSizeInterface
, static const Address kEmpty; // 00:00:00:00:00:00 static const Address kAny; // FF:FF:FF:FF:FF:FF - private: +private: std::string _ToMaskedColonSepHexString(int bytes_to_mask) const; }; @@ -138,8 +120,8 @@ struct formatter : formatter { template typename Context::iterator format(const bluetooth::hci::Address& address, Context& ctx) const { std::string repr = bluetooth::os::should_log_be_redacted() - ? address.ToRedactedStringForLogging() - : address.ToStringForLogging(); + ? address.ToRedactedStringForLogging() + : address.ToStringForLogging(); return fmt::formatter::format(repr, ctx); } }; diff --git a/system/gd/hci/address_with_type.h b/system/gd/hci/address_with_type.h index 604b6a6cb1e..d25ae252b9e 100644 --- a/system/gd/hci/address_with_type.h +++ b/system/gd/hci/address_with_type.h @@ -33,28 +33,28 @@ namespace bluetooth { namespace hci { class AddressWithType final : public bluetooth::common::IRedactableLoggable { - public: +public: AddressWithType(Address address, AddressType address_type) : address_(std::move(address)), address_type_(address_type) {} - explicit AddressWithType() : address_(Address::kEmpty), address_type_(AddressType::PUBLIC_DEVICE_ADDRESS) {} + explicit AddressWithType() + : address_(Address::kEmpty), address_type_(AddressType::PUBLIC_DEVICE_ADDRESS) {} - inline Address GetAddress() const { - return address_; - } + inline Address GetAddress() const { return address_; } - inline AddressType GetAddressType() const { - return address_type_; - } + inline AddressType GetAddressType() const { return address_type_; } /* Is this an Resolvable Private Address ? */ inline bool IsRpa() const { - return address_type_ == hci::AddressType::RANDOM_DEVICE_ADDRESS && ((address_.data())[5] & 0xc0) == 0x40; + return address_type_ == hci::AddressType::RANDOM_DEVICE_ADDRESS && + ((address_.data())[5] & 0xc0) == 0x40; } /* Is this an Resolvable Private Address, that was generated from given irk ? */ bool IsRpaThatMatchesIrk(const hci::Octet16& irk) const { - if (!IsRpa()) return false; + if (!IsRpa()) { + return false; + } /* use the 3 MSB of bd address as prand */ Octet16 prand{}; @@ -81,18 +81,10 @@ class AddressWithType final : public bluetooth::common::IRedactableLoggable { bool operator==(const AddressWithType& rhs) const { return address_ == rhs.address_ && address_type_ == rhs.address_type_; } - bool operator>(const AddressWithType& rhs) const { - return (rhs < *this); - } - bool operator<=(const AddressWithType& rhs) const { - return !(*this > rhs); - } - bool operator>=(const AddressWithType& rhs) const { - return !(*this < rhs); - } - bool operator!=(const AddressWithType& rhs) const { - return !(*this == rhs); - } + bool operator>(const AddressWithType& rhs) const { return rhs < *this; } + bool operator<=(const AddressWithType& rhs) const { return !(*this > rhs); } + bool operator>=(const AddressWithType& rhs) const { return !(*this < rhs); } + bool operator!=(const AddressWithType& rhs) const { return !(*this == rhs); } FilterAcceptListAddressType ToFilterAcceptListAddressType() const { switch (address_type_) { @@ -130,7 +122,7 @@ class AddressWithType final : public bluetooth::common::IRedactableLoggable { return address_.ToStringForLogging() + "[" + AddressTypeText(address_type_) + "]"; } - private: +private: Address address_; AddressType address_type_; }; @@ -147,12 +139,14 @@ namespace std { template <> struct hash { std::size_t operator()(const bluetooth::hci::AddressWithType& val) const { - static_assert(sizeof(uint64_t) >= (bluetooth::hci::Address::kLength + sizeof(bluetooth::hci::AddressType))); + static_assert(sizeof(uint64_t) >= + (bluetooth::hci::Address::kLength + sizeof(bluetooth::hci::AddressType))); uint64_t int_addr = 0; - memcpy(reinterpret_cast(&int_addr), val.GetAddress().data(), bluetooth::hci::Address::kLength); + memcpy(reinterpret_cast(&int_addr), val.GetAddress().data(), + bluetooth::hci::Address::kLength); bluetooth::hci::AddressType address_type = val.GetAddressType(); - memcpy( - reinterpret_cast(&int_addr) + bluetooth::hci::Address::kLength, &address_type, sizeof(address_type)); + memcpy(reinterpret_cast(&int_addr) + bluetooth::hci::Address::kLength, &address_type, + sizeof(address_type)); return std::hash{}(int_addr); } }; @@ -165,11 +159,11 @@ namespace fmt { template <> struct formatter : formatter { template - typename Context::iterator format( - const bluetooth::hci::AddressWithType& address, Context& ctx) const { + typename Context::iterator format(const bluetooth::hci::AddressWithType& address, + Context& ctx) const { std::string repr = bluetooth::os::should_log_be_redacted() - ? address.ToRedactedStringForLogging() - : address.ToStringForLogging(); + ? address.ToRedactedStringForLogging() + : address.ToStringForLogging(); return fmt::formatter::format(repr, ctx); } }; diff --git a/system/gd/hci/address_with_type_test.cc b/system/gd/hci/address_with_type_test.cc index 8a07bc35ab6..3e0f34e4f96 100644 --- a/system/gd/hci/address_with_type_test.cc +++ b/system/gd/hci/address_with_type_test.cc @@ -55,7 +55,8 @@ TEST(AddressWithTypeTest, HashDifferentDiffAddrSameType) { AddressType type = AddressType::PUBLIC_IDENTITY_ADDRESS; AddressWithType address_with_type(addr, type); struct std::hash hasher; - EXPECT_NE(hasher(address_with_type), hasher(AddressWithType(Address::kEmpty, AddressType::PUBLIC_IDENTITY_ADDRESS))); + EXPECT_NE(hasher(address_with_type), + hasher(AddressWithType(Address::kEmpty, AddressType::PUBLIC_IDENTITY_ADDRESS))); } TEST(AddressWithTypeTest, HashDifferentSameAddressDiffType) { @@ -71,46 +72,38 @@ TEST(AddressWithTypeTest, HashDifferentSameAddressDiffType) { TEST(AddressWithTypeTest, IsRpa) { // Public address can't be RPA - EXPECT_FALSE( - AddressWithType(Address{{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}, AddressType::PUBLIC_IDENTITY_ADDRESS).IsRpa()); + EXPECT_FALSE(AddressWithType(Address{{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}, + AddressType::PUBLIC_IDENTITY_ADDRESS) + .IsRpa()); // Must have proper Most Significant Bit configuration - EXPECT_FALSE( - AddressWithType(Address{{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}, AddressType::RANDOM_DEVICE_ADDRESS).IsRpa()); - EXPECT_TRUE( - AddressWithType(Address{{0x01, 0x02, 0x03, 0x04, 0x05, 0x40}}, AddressType::RANDOM_DEVICE_ADDRESS).IsRpa()); - EXPECT_TRUE( - AddressWithType(Address{{0x01, 0x02, 0x03, 0x04, 0x05, 0x50}}, AddressType::RANDOM_DEVICE_ADDRESS).IsRpa()); - EXPECT_TRUE( - AddressWithType(Address{{0x01, 0x02, 0x03, 0x04, 0x05, 0x60}}, AddressType::RANDOM_DEVICE_ADDRESS).IsRpa()); - EXPECT_TRUE( - AddressWithType(Address{{0x01, 0x02, 0x03, 0x04, 0x05, 0x70}}, AddressType::RANDOM_DEVICE_ADDRESS).IsRpa()); - EXPECT_FALSE( - AddressWithType(Address{{0x01, 0x02, 0x03, 0x04, 0x05, 0x80}}, AddressType::RANDOM_DEVICE_ADDRESS).IsRpa()); + EXPECT_FALSE(AddressWithType(Address{{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}, + AddressType::RANDOM_DEVICE_ADDRESS) + .IsRpa()); + EXPECT_TRUE(AddressWithType(Address{{0x01, 0x02, 0x03, 0x04, 0x05, 0x40}}, + AddressType::RANDOM_DEVICE_ADDRESS) + .IsRpa()); + EXPECT_TRUE(AddressWithType(Address{{0x01, 0x02, 0x03, 0x04, 0x05, 0x50}}, + AddressType::RANDOM_DEVICE_ADDRESS) + .IsRpa()); + EXPECT_TRUE(AddressWithType(Address{{0x01, 0x02, 0x03, 0x04, 0x05, 0x60}}, + AddressType::RANDOM_DEVICE_ADDRESS) + .IsRpa()); + EXPECT_TRUE(AddressWithType(Address{{0x01, 0x02, 0x03, 0x04, 0x05, 0x70}}, + AddressType::RANDOM_DEVICE_ADDRESS) + .IsRpa()); + EXPECT_FALSE(AddressWithType(Address{{0x01, 0x02, 0x03, 0x04, 0x05, 0x80}}, + AddressType::RANDOM_DEVICE_ADDRESS) + .IsRpa()); } TEST(AddressWithTypeTest, IsRpaThatMatchesIrk) { - AddressWithType address_1 = - AddressWithType(Address{{0xDE, 0x12, 0xC9, 0x03, 0x02, 0x50}}, AddressType::RANDOM_DEVICE_ADDRESS); - AddressWithType address_2 = - AddressWithType(Address{{0xDD, 0x12, 0xC9, 0x03, 0x02, 0x50}}, AddressType::RANDOM_DEVICE_ADDRESS); - Octet16 irk_1{ - 0x90, - 0x5e, - 0x60, - 0x59, - 0xc9, - 0x11, - 0x43, - 0x7b, - 0x04, - 0x09, - 0x6a, - 0x53, - 0x28, - 0xe6, - 0x59, - 0x6d}; + AddressWithType address_1 = AddressWithType(Address{{0xDE, 0x12, 0xC9, 0x03, 0x02, 0x50}}, + AddressType::RANDOM_DEVICE_ADDRESS); + AddressWithType address_2 = AddressWithType(Address{{0xDD, 0x12, 0xC9, 0x03, 0x02, 0x50}}, + AddressType::RANDOM_DEVICE_ADDRESS); + Octet16 irk_1{0x90, 0x5e, 0x60, 0x59, 0xc9, 0x11, 0x43, 0x7b, + 0x04, 0x09, 0x6a, 0x53, 0x28, 0xe6, 0x59, 0x6d}; EXPECT_TRUE(address_1.IsRpaThatMatchesIrk(irk_1)); EXPECT_FALSE(address_2.IsRpaThatMatchesIrk(irk_1)); @@ -118,46 +111,46 @@ TEST(AddressWithTypeTest, IsRpaThatMatchesIrk) { TEST(AddressWithTypeTest, OperatorLessThan) { { - AddressWithType address_1 = - AddressWithType(Address{{0x50, 0x02, 0x03, 0xC9, 0x12, 0xDE}}, AddressType::RANDOM_DEVICE_ADDRESS); - AddressWithType address_2 = - AddressWithType(Address{{0x50, 0x02, 0x03, 0xC9, 0x12, 0xDD}}, AddressType::RANDOM_DEVICE_ADDRESS); + AddressWithType address_1 = AddressWithType(Address{{0x50, 0x02, 0x03, 0xC9, 0x12, 0xDE}}, + AddressType::RANDOM_DEVICE_ADDRESS); + AddressWithType address_2 = AddressWithType(Address{{0x50, 0x02, 0x03, 0xC9, 0x12, 0xDD}}, + AddressType::RANDOM_DEVICE_ADDRESS); ASSERT_TRUE(address_2 < address_1); } { - AddressWithType address_1 = - AddressWithType(Address{{0x50, 0x02, 0x03, 0xC9, 0x12, 0xDE}}, AddressType::RANDOM_DEVICE_ADDRESS); - AddressWithType address_2 = - AddressWithType(Address{{0x70, 0x02, 0x03, 0xC9, 0x12, 0xDE}}, AddressType::RANDOM_DEVICE_ADDRESS); + AddressWithType address_1 = AddressWithType(Address{{0x50, 0x02, 0x03, 0xC9, 0x12, 0xDE}}, + AddressType::RANDOM_DEVICE_ADDRESS); + AddressWithType address_2 = AddressWithType(Address{{0x70, 0x02, 0x03, 0xC9, 0x12, 0xDE}}, + AddressType::RANDOM_DEVICE_ADDRESS); ASSERT_TRUE(address_1 < address_2); } { - AddressWithType address_1 = - AddressWithType(Address{{0x50, 0x02, 0x03, 0xC9, 0x12, 0xDE}}, AddressType::RANDOM_DEVICE_ADDRESS); - AddressWithType address_2 = - AddressWithType(Address{{0x70, 0x02, 0x03, 0xC9, 0x12, 0xDD}}, AddressType::RANDOM_DEVICE_ADDRESS); + AddressWithType address_1 = AddressWithType(Address{{0x50, 0x02, 0x03, 0xC9, 0x12, 0xDE}}, + AddressType::RANDOM_DEVICE_ADDRESS); + AddressWithType address_2 = AddressWithType(Address{{0x70, 0x02, 0x03, 0xC9, 0x12, 0xDD}}, + AddressType::RANDOM_DEVICE_ADDRESS); ASSERT_TRUE(address_1 < address_2); } { - AddressWithType address_1 = - AddressWithType(Address{{0x11, 0x22, 0x33, 0x44, 0x55, 0x66}}, AddressType::PUBLIC_DEVICE_ADDRESS); - AddressWithType address_2 = - AddressWithType(Address{{0x11, 0x22, 0x33, 0x44, 0x55, 0x66}}, AddressType::RANDOM_DEVICE_ADDRESS); + AddressWithType address_1 = AddressWithType(Address{{0x11, 0x22, 0x33, 0x44, 0x55, 0x66}}, + AddressType::PUBLIC_DEVICE_ADDRESS); + AddressWithType address_2 = AddressWithType(Address{{0x11, 0x22, 0x33, 0x44, 0x55, 0x66}}, + AddressType::RANDOM_DEVICE_ADDRESS); ASSERT_TRUE(address_1 < address_2); } { - AddressWithType address_1 = - AddressWithType(Address{{0x11, 0x22, 0x33, 0x44, 0x55, 0x66}}, AddressType::PUBLIC_DEVICE_ADDRESS); - AddressWithType address_2 = - AddressWithType(Address{{0x11, 0x22, 0x33, 0x44, 0x55, 0x66}}, AddressType::PUBLIC_DEVICE_ADDRESS); + AddressWithType address_1 = AddressWithType(Address{{0x11, 0x22, 0x33, 0x44, 0x55, 0x66}}, + AddressType::PUBLIC_DEVICE_ADDRESS); + AddressWithType address_2 = AddressWithType(Address{{0x11, 0x22, 0x33, 0x44, 0x55, 0x66}}, + AddressType::PUBLIC_DEVICE_ADDRESS); ASSERT_FALSE(address_1 < address_2); } @@ -167,10 +160,10 @@ TEST(AddressWithTypeTest, OrderedMap) { std::map map; { - AddressWithType address_1 = - AddressWithType(Address{{0x50, 0x02, 0x03, 0xC9, 0x12, 0xDE}}, AddressType::RANDOM_DEVICE_ADDRESS); - AddressWithType address_2 = - AddressWithType(Address{{0x70, 0x02, 0x03, 0xC9, 0x12, 0xDD}}, AddressType::RANDOM_DEVICE_ADDRESS); + AddressWithType address_1 = AddressWithType(Address{{0x50, 0x02, 0x03, 0xC9, 0x12, 0xDE}}, + AddressType::RANDOM_DEVICE_ADDRESS); + AddressWithType address_2 = AddressWithType(Address{{0x70, 0x02, 0x03, 0xC9, 0x12, 0xDD}}, + AddressType::RANDOM_DEVICE_ADDRESS); map[address_1] = 1; map[address_2] = 2; @@ -180,10 +173,10 @@ TEST(AddressWithTypeTest, OrderedMap) { } { - AddressWithType address_1 = - AddressWithType(Address{{0x11, 0x22, 0x33, 0x44, 0x55, 0x66}}, AddressType::RANDOM_DEVICE_ADDRESS); - AddressWithType address_2 = - AddressWithType(Address{{0x11, 0x22, 0x33, 0x44, 0x55, 0x66}}, AddressType::PUBLIC_DEVICE_ADDRESS); + AddressWithType address_1 = AddressWithType(Address{{0x11, 0x22, 0x33, 0x44, 0x55, 0x66}}, + AddressType::RANDOM_DEVICE_ADDRESS); + AddressWithType address_2 = AddressWithType(Address{{0x11, 0x22, 0x33, 0x44, 0x55, 0x66}}, + AddressType::PUBLIC_DEVICE_ADDRESS); map[address_1] = 1; map[address_2] = 2; @@ -193,10 +186,10 @@ TEST(AddressWithTypeTest, OrderedMap) { } { - AddressWithType address_1 = - AddressWithType(Address{{0x11, 0x22, 0x33, 0x44, 0x55, 0x66}}, AddressType::PUBLIC_DEVICE_ADDRESS); - AddressWithType address_2 = - AddressWithType(Address{{0x11, 0x22, 0x33, 0x44, 0x55, 0x66}}, AddressType::PUBLIC_DEVICE_ADDRESS); + AddressWithType address_1 = AddressWithType(Address{{0x11, 0x22, 0x33, 0x44, 0x55, 0x66}}, + AddressType::PUBLIC_DEVICE_ADDRESS); + AddressWithType address_2 = AddressWithType(Address{{0x11, 0x22, 0x33, 0x44, 0x55, 0x66}}, + AddressType::PUBLIC_DEVICE_ADDRESS); map[address_1] = 1; map[address_2] = 2; @@ -210,10 +203,10 @@ TEST(AddressWithTypeTest, HashMap) { std::unordered_map map; { - AddressWithType address_1 = - AddressWithType(Address{{0x50, 0x02, 0x03, 0xC9, 0x12, 0xDE}}, AddressType::RANDOM_DEVICE_ADDRESS); - AddressWithType address_2 = - AddressWithType(Address{{0x70, 0x02, 0x03, 0xC9, 0x12, 0xDD}}, AddressType::RANDOM_DEVICE_ADDRESS); + AddressWithType address_1 = AddressWithType(Address{{0x50, 0x02, 0x03, 0xC9, 0x12, 0xDE}}, + AddressType::RANDOM_DEVICE_ADDRESS); + AddressWithType address_2 = AddressWithType(Address{{0x70, 0x02, 0x03, 0xC9, 0x12, 0xDD}}, + AddressType::RANDOM_DEVICE_ADDRESS); map[address_1] = 1; map[address_2] = 2; @@ -223,10 +216,10 @@ TEST(AddressWithTypeTest, HashMap) { } { - AddressWithType address_1 = - AddressWithType(Address{{0x11, 0x22, 0x33, 0x44, 0x55, 0x66}}, AddressType::RANDOM_DEVICE_ADDRESS); - AddressWithType address_2 = - AddressWithType(Address{{0x11, 0x22, 0x33, 0x44, 0x55, 0x66}}, AddressType::PUBLIC_DEVICE_ADDRESS); + AddressWithType address_1 = AddressWithType(Address{{0x11, 0x22, 0x33, 0x44, 0x55, 0x66}}, + AddressType::RANDOM_DEVICE_ADDRESS); + AddressWithType address_2 = AddressWithType(Address{{0x11, 0x22, 0x33, 0x44, 0x55, 0x66}}, + AddressType::PUBLIC_DEVICE_ADDRESS); map[address_1] = 1; map[address_2] = 2; @@ -236,10 +229,10 @@ TEST(AddressWithTypeTest, HashMap) { } { - AddressWithType address_1 = - AddressWithType(Address{{0x11, 0x22, 0x33, 0x44, 0x55, 0x66}}, AddressType::PUBLIC_DEVICE_ADDRESS); - AddressWithType address_2 = - AddressWithType(Address{{0x11, 0x22, 0x33, 0x44, 0x55, 0x66}}, AddressType::PUBLIC_DEVICE_ADDRESS); + AddressWithType address_1 = AddressWithType(Address{{0x11, 0x22, 0x33, 0x44, 0x55, 0x66}}, + AddressType::PUBLIC_DEVICE_ADDRESS); + AddressWithType address_2 = AddressWithType(Address{{0x11, 0x22, 0x33, 0x44, 0x55, 0x66}}, + AddressType::PUBLIC_DEVICE_ADDRESS); map[address_1] = 1; map[address_2] = 2; @@ -251,59 +244,59 @@ TEST(AddressWithTypeTest, HashMap) { TEST(AddressWithTypeTest, ToFilterAcceptListAddressType) { { - AddressWithType address = AddressWithType( - Address{{0x11, 0x22, 0x33, 0x44, 0x55, 0x66}}, AddressType::PUBLIC_DEVICE_ADDRESS); + AddressWithType address = AddressWithType(Address{{0x11, 0x22, 0x33, 0x44, 0x55, 0x66}}, + AddressType::PUBLIC_DEVICE_ADDRESS); ASSERT_EQ(hci::FilterAcceptListAddressType::PUBLIC, address.ToFilterAcceptListAddressType()); } { - AddressWithType address = AddressWithType( - Address{{0x11, 0x22, 0x33, 0x44, 0x55, 0x66}}, AddressType::PUBLIC_IDENTITY_ADDRESS); + AddressWithType address = AddressWithType(Address{{0x11, 0x22, 0x33, 0x44, 0x55, 0x66}}, + AddressType::PUBLIC_IDENTITY_ADDRESS); ASSERT_EQ(hci::FilterAcceptListAddressType::PUBLIC, address.ToFilterAcceptListAddressType()); } { - AddressWithType address = AddressWithType( - Address{{0x11, 0x22, 0x33, 0x44, 0x55, 0x66}}, AddressType::RANDOM_DEVICE_ADDRESS); + AddressWithType address = AddressWithType(Address{{0x11, 0x22, 0x33, 0x44, 0x55, 0x66}}, + AddressType::RANDOM_DEVICE_ADDRESS); ASSERT_EQ(hci::FilterAcceptListAddressType::RANDOM, address.ToFilterAcceptListAddressType()); } { - AddressWithType address = AddressWithType( - Address{{0x11, 0x22, 0x33, 0x44, 0x55, 0x66}}, AddressType::RANDOM_IDENTITY_ADDRESS); + AddressWithType address = AddressWithType(Address{{0x11, 0x22, 0x33, 0x44, 0x55, 0x66}}, + AddressType::RANDOM_IDENTITY_ADDRESS); ASSERT_EQ(hci::FilterAcceptListAddressType::RANDOM, address.ToFilterAcceptListAddressType()); } } TEST(AddressWithTypeTest, ToPeerAddressType) { { - AddressWithType address = AddressWithType( - Address{{0x11, 0x22, 0x33, 0x44, 0x55, 0x66}}, AddressType::PUBLIC_DEVICE_ADDRESS); + AddressWithType address = AddressWithType(Address{{0x11, 0x22, 0x33, 0x44, 0x55, 0x66}}, + AddressType::PUBLIC_DEVICE_ADDRESS); ASSERT_EQ(hci::PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, address.ToPeerAddressType()); } { - AddressWithType address = AddressWithType( - Address{{0x11, 0x22, 0x33, 0x44, 0x55, 0x66}}, AddressType::PUBLIC_IDENTITY_ADDRESS); + AddressWithType address = AddressWithType(Address{{0x11, 0x22, 0x33, 0x44, 0x55, 0x66}}, + AddressType::PUBLIC_IDENTITY_ADDRESS); ASSERT_EQ(hci::PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, address.ToPeerAddressType()); } { - AddressWithType address = AddressWithType( - Address{{0x11, 0x22, 0x33, 0x44, 0x55, 0x66}}, AddressType::RANDOM_DEVICE_ADDRESS); + AddressWithType address = AddressWithType(Address{{0x11, 0x22, 0x33, 0x44, 0x55, 0x66}}, + AddressType::RANDOM_DEVICE_ADDRESS); ASSERT_EQ(hci::PeerAddressType::RANDOM_DEVICE_OR_IDENTITY_ADDRESS, address.ToPeerAddressType()); } { - AddressWithType address = AddressWithType( - Address{{0x11, 0x22, 0x33, 0x44, 0x55, 0x66}}, AddressType::RANDOM_IDENTITY_ADDRESS); + AddressWithType address = AddressWithType(Address{{0x11, 0x22, 0x33, 0x44, 0x55, 0x66}}, + AddressType::RANDOM_IDENTITY_ADDRESS); ASSERT_EQ(hci::PeerAddressType::RANDOM_DEVICE_OR_IDENTITY_ADDRESS, address.ToPeerAddressType()); } } TEST(AddressWithTypeTest, StringStream) { - AddressWithType address_with_type = AddressWithType( - Address{{0x11, 0x22, 0x33, 0x44, 0x55, 0x66}}, AddressType::PUBLIC_DEVICE_ADDRESS); + AddressWithType address_with_type = AddressWithType(Address{{0x11, 0x22, 0x33, 0x44, 0x55, 0x66}}, + AddressType::PUBLIC_DEVICE_ADDRESS); std::stringstream oss; oss << address_with_type; diff --git a/system/gd/hci/class_of_device.cc b/system/gd/hci/class_of_device.cc index 15b64e97890..4ec755b6ed9 100644 --- a/system/gd/hci/class_of_device.cc +++ b/system/gd/hci/class_of_device.cc @@ -31,19 +31,17 @@ namespace hci { // NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init) ClassOfDevice::ClassOfDevice(const uint8_t (&class_of_device)[kLength]) { std::copy(class_of_device, class_of_device + kLength, cod.data()); -}; +} std::string ClassOfDevice::ToString() const { char buffer[] = "000-0-00"; - std::snprintf(&buffer[0], sizeof(buffer), "%03x-%01x-%02x", (static_cast(cod[2]) << 4) | cod[1] >> 4, - cod[1] & 0x0f, cod[0]); + std::snprintf(&buffer[0], sizeof(buffer), "%03x-%01x-%02x", + (static_cast(cod[2]) << 4) | cod[1] >> 4, cod[1] & 0x0f, cod[0]); std::string str(buffer); return str; } -std::string ClassOfDevice::ToLegacyConfigString() const { - return std::to_string(ToUint32Legacy()); -} +std::string ClassOfDevice::ToLegacyConfigString() const { return std::to_string(ToUint32Legacy()); } std::optional ClassOfDevice::FromString(const std::string& str) { if (str.length() != 8) { @@ -118,14 +116,12 @@ std::optional ClassOfDevice::FromLegacyConfigString(const std::st return FromUint32Legacy(static_cast(num)); } -uint32_t ClassOfDevice::ToUint32Legacy() const { - return (cod[2]) | (cod[1] << 8) | (cod[0] << 16); -} +uint32_t ClassOfDevice::ToUint32Legacy() const { return (cod[2]) | (cod[1] << 8) | (cod[0] << 16); } size_t ClassOfDevice::FromOctets(const uint8_t* from) { std::copy(from, from + kLength, data()); return kLength; -}; +} bool ClassOfDevice::IsValid(const std::string& cod) { return ClassOfDevice::FromString(cod).has_value(); diff --git a/system/gd/hci/class_of_device.h b/system/gd/hci/class_of_device.h index 245908a87dc..d3a57fcc331 100644 --- a/system/gd/hci/class_of_device.h +++ b/system/gd/hci/class_of_device.h @@ -30,7 +30,7 @@ namespace hci { class ClassOfDevice final : public packet::CustomFieldFixedSizeInterface, public storage::Serializable { - public: +public: static constexpr size_t kLength = 3; std::array cod = {}; @@ -39,12 +39,8 @@ class ClassOfDevice final : public packet::CustomFieldFixedSizeInterface FromLegacyConfigString(const std::string& str); - bool operator<(const ClassOfDevice& rhs) const { - return cod < rhs.cod; - } - bool operator==(const ClassOfDevice& rhs) const { - return cod == rhs.cod; - } - bool operator>(const ClassOfDevice& rhs) const { - return (rhs < *this); - } - bool operator<=(const ClassOfDevice& rhs) const { - return !(*this > rhs); - } - bool operator>=(const ClassOfDevice& rhs) const { - return !(*this < rhs); - } - bool operator!=(const ClassOfDevice& rhs) const { - return !(*this == rhs); - } + bool operator<(const ClassOfDevice& rhs) const { return cod < rhs.cod; } + bool operator==(const ClassOfDevice& rhs) const { return cod == rhs.cod; } + bool operator>(const ClassOfDevice& rhs) const { return rhs < *this; } + bool operator<=(const ClassOfDevice& rhs) const { return !(*this > rhs); } + bool operator>=(const ClassOfDevice& rhs) const { return !(*this < rhs); } + bool operator!=(const ClassOfDevice& rhs) const { return !(*this == rhs); } // Converts |string| to ClassOfDevice and places it in |to|. If |from| does // not represent a Class of Device, |to| is not modified and this function diff --git a/system/gd/hci/class_of_device_unittest.cc b/system/gd/hci/class_of_device_unittest.cc index 62d304c54b1..1d3f4f8f3ac 100644 --- a/system/gd/hci/class_of_device_unittest.cc +++ b/system/gd/hci/class_of_device_unittest.cc @@ -16,11 +16,11 @@ * ******************************************************************************/ +#include "hci/class_of_device.h" + #include #include -#include "hci/class_of_device.h" - using bluetooth::hci::ClassOfDevice; static const char* test_class = "efc-d-ab"; diff --git a/system/gd/hci/command_interface.h b/system/gd/hci/command_interface.h index 28fa6273f20..21edd42a760 100644 --- a/system/gd/hci/command_interface.h +++ b/system/gd/hci/command_interface.h @@ -26,18 +26,20 @@ namespace hci { template class CommandInterface { - public: +public: CommandInterface() = default; CommandInterface(const CommandInterface&) = delete; CommandInterface& operator=(const CommandInterface&) = delete; virtual ~CommandInterface() = default; - virtual void EnqueueCommand(std::unique_ptr command, - common::ContextualOnceCallback on_complete) = 0; + virtual void EnqueueCommand( + std::unique_ptr command, + common::ContextualOnceCallback on_complete) = 0; - virtual void EnqueueCommand(std::unique_ptr command, - common::ContextualOnceCallback on_status) = 0; + virtual void EnqueueCommand( + std::unique_ptr command, + common::ContextualOnceCallback on_status) = 0; }; } // namespace hci } // namespace bluetooth diff --git a/system/gd/hci/controller.cc b/system/gd/hci/controller.cc index 328babd3859..bbfa3d48367 100644 --- a/system/gd/hci/controller.cc +++ b/system/gd/hci/controller.cc @@ -44,7 +44,7 @@ constexpr uint8_t kMinEncryptionKeySize = 7; // #define MIN_ENCRYPTION_KEY_SIZE constexpr bool kDefaultVendorCapabilitiesEnabled = true; static const std::string kPropertyVendorCapabilitiesEnabled = - "bluetooth.core.le.vendor_capabilities.enabled"; + "bluetooth.core.le.vendor_capabilities.enabled"; using os::Handler; @@ -54,85 +54,96 @@ struct Controller::impl { void Start(hci::HciLayer* hci) { hci_ = hci; Handler* handler = module_.GetHandler(); - hci_->RegisterEventHandler( - EventCode::NUMBER_OF_COMPLETED_PACKETS, handler->BindOn(this, &Controller::impl::NumberOfCompletedPackets)); + hci_->RegisterEventHandler(EventCode::NUMBER_OF_COMPLETED_PACKETS, + handler->BindOn(this, &Controller::impl::NumberOfCompletedPackets)); set_event_mask(kDefaultEventMask); write_le_host_support(Enable::ENABLED, Enable::DISABLED); - hci_->EnqueueCommand(ReadLocalNameBuilder::Create(), - handler->BindOnceOn(this, &Controller::impl::read_local_name_complete_handler)); - hci_->EnqueueCommand(ReadLocalVersionInformationBuilder::Create(), - handler->BindOnceOn(this, &Controller::impl::read_local_version_information_complete_handler)); - hci_->EnqueueCommand(ReadLocalSupportedCommandsBuilder::Create(), - handler->BindOnceOn(this, &Controller::impl::read_local_supported_commands_complete_handler)); + hci_->EnqueueCommand( + ReadLocalNameBuilder::Create(), + handler->BindOnceOn(this, &Controller::impl::read_local_name_complete_handler)); + hci_->EnqueueCommand( + ReadLocalVersionInformationBuilder::Create(), + handler->BindOnceOn( + this, &Controller::impl::read_local_version_information_complete_handler)); + hci_->EnqueueCommand( + ReadLocalSupportedCommandsBuilder::Create(), + handler->BindOnceOn(this, + &Controller::impl::read_local_supported_commands_complete_handler)); hci_->EnqueueCommand( - LeReadLocalSupportedFeaturesBuilder::Create(), - handler->BindOnceOn(this, &Controller::impl::le_read_local_supported_features_handler)); + LeReadLocalSupportedFeaturesBuilder::Create(), + handler->BindOnceOn(this, &Controller::impl::le_read_local_supported_features_handler)); hci_->EnqueueCommand( - LeReadSupportedStatesBuilder::Create(), - handler->BindOnceOn(this, &Controller::impl::le_read_supported_states_handler)); + LeReadSupportedStatesBuilder::Create(), + handler->BindOnceOn(this, &Controller::impl::le_read_supported_states_handler)); // Wait for all extended features read std::promise features_promise; auto features_future = features_promise.get_future(); - hci_->EnqueueCommand(ReadLocalExtendedFeaturesBuilder::Create(0x00), - handler->BindOnceOn(this, &Controller::impl::read_local_extended_features_complete_handler, - std::move(features_promise))); + hci_->EnqueueCommand( + ReadLocalExtendedFeaturesBuilder::Create(0x00), + handler->BindOnceOn(this, + &Controller::impl::read_local_extended_features_complete_handler, + std::move(features_promise))); features_future.wait(); if (com::android::bluetooth::flags::channel_sounding_in_stack() && module_.SupportsBleChannelSounding()) { - le_set_event_mask(MaskLeEventMask( - local_version_information_.hci_version_, kDefaultLeEventMask | kLeCSEventMask)); + le_set_event_mask(MaskLeEventMask(local_version_information_.hci_version_, + kDefaultLeEventMask | kLeCSEventMask)); } else { le_set_event_mask( - MaskLeEventMask(local_version_information_.hci_version_, kDefaultLeEventMask)); + MaskLeEventMask(local_version_information_.hci_version_, kDefaultLeEventMask)); } - hci_->EnqueueCommand(ReadBufferSizeBuilder::Create(), - handler->BindOnceOn(this, &Controller::impl::read_buffer_size_complete_handler)); + hci_->EnqueueCommand( + ReadBufferSizeBuilder::Create(), + handler->BindOnceOn(this, &Controller::impl::read_buffer_size_complete_handler)); - if (common::init_flags::set_min_encryption_is_enabled() && is_supported(OpCode::SET_MIN_ENCRYPTION_KEY_SIZE)) { + if (common::init_flags::set_min_encryption_is_enabled() && + is_supported(OpCode::SET_MIN_ENCRYPTION_KEY_SIZE)) { hci_->EnqueueCommand( - SetMinEncryptionKeySizeBuilder::Create(kMinEncryptionKeySize), - handler->BindOnceOn(this, &Controller::impl::set_min_encryption_key_size_handler)); + SetMinEncryptionKeySizeBuilder::Create(kMinEncryptionKeySize), + handler->BindOnceOn(this, &Controller::impl::set_min_encryption_key_size_handler)); } if (is_supported(OpCode::LE_READ_BUFFER_SIZE_V2)) { hci_->EnqueueCommand( - LeReadBufferSizeV2Builder::Create(), - handler->BindOnceOn(this, &Controller::impl::le_read_buffer_size_v2_handler)); + LeReadBufferSizeV2Builder::Create(), + handler->BindOnceOn(this, &Controller::impl::le_read_buffer_size_v2_handler)); } else { hci_->EnqueueCommand( - LeReadBufferSizeV1Builder::Create(), - handler->BindOnceOn(this, &Controller::impl::le_read_buffer_size_handler)); + LeReadBufferSizeV1Builder::Create(), + handler->BindOnceOn(this, &Controller::impl::le_read_buffer_size_handler)); } if (is_supported(OpCode::READ_LOCAL_SUPPORTED_CODECS_V1)) { hci_->EnqueueCommand( - ReadLocalSupportedCodecsV1Builder::Create(), - handler->BindOnceOn(this, &Controller::impl::read_local_supported_codecs_v1_handler)); + ReadLocalSupportedCodecsV1Builder::Create(), + handler->BindOnceOn(this, &Controller::impl::read_local_supported_codecs_v1_handler)); } hci_->EnqueueCommand( - LeReadFilterAcceptListSizeBuilder::Create(), - handler->BindOnceOn(this, &Controller::impl::le_read_accept_list_size_handler)); + LeReadFilterAcceptListSizeBuilder::Create(), + handler->BindOnceOn(this, &Controller::impl::le_read_accept_list_size_handler)); if (is_supported(OpCode::LE_READ_RESOLVING_LIST_SIZE) && module_.SupportsBlePrivacy()) { hci_->EnqueueCommand( - LeReadResolvingListSizeBuilder::Create(), - handler->BindOnceOn(this, &Controller::impl::le_read_resolving_list_size_handler)); + LeReadResolvingListSizeBuilder::Create(), + handler->BindOnceOn(this, &Controller::impl::le_read_resolving_list_size_handler)); } else { log::info("LE_READ_RESOLVING_LIST_SIZE not supported, defaulting to 0"); le_resolving_list_size_ = 0; } - if (is_supported(OpCode::LE_READ_MAXIMUM_DATA_LENGTH) && module_.SupportsBleDataPacketLengthExtension()) { - hci_->EnqueueCommand(LeReadMaximumDataLengthBuilder::Create(), - handler->BindOnceOn(this, &Controller::impl::le_read_maximum_data_length_handler)); + if (is_supported(OpCode::LE_READ_MAXIMUM_DATA_LENGTH) && + module_.SupportsBleDataPacketLengthExtension()) { + hci_->EnqueueCommand( + LeReadMaximumDataLengthBuilder::Create(), + handler->BindOnceOn(this, &Controller::impl::le_read_maximum_data_length_handler)); } else { log::info("LE_READ_MAXIMUM_DATA_LENGTH not supported, defaulting to 0"); le_maximum_data_length_.supported_max_rx_octets_ = 0; @@ -145,23 +156,28 @@ struct Controller::impl { write_simple_pairing_mode(Enable::ENABLED); if (module_.SupportsSecureConnections()) { hci_->EnqueueCommand( - WriteSecureConnectionsHostSupportBuilder::Create(Enable::ENABLED), - handler->BindOnceOn( - this, &Controller::impl::write_secure_connections_host_support_complete_handler)); + WriteSecureConnectionsHostSupportBuilder::Create(Enable::ENABLED), + handler->BindOnceOn( + this, + &Controller::impl::write_secure_connections_host_support_complete_handler)); } - if (is_supported(OpCode::LE_READ_SUGGESTED_DEFAULT_DATA_LENGTH) && module_.SupportsBleDataPacketLengthExtension()) { + if (is_supported(OpCode::LE_READ_SUGGESTED_DEFAULT_DATA_LENGTH) && + module_.SupportsBleDataPacketLengthExtension()) { hci_->EnqueueCommand( - LeReadSuggestedDefaultDataLengthBuilder::Create(), - handler->BindOnceOn(this, &Controller::impl::le_read_suggested_default_data_length_handler)); + LeReadSuggestedDefaultDataLengthBuilder::Create(), + handler->BindOnceOn( + this, &Controller::impl::le_read_suggested_default_data_length_handler)); } else { log::info("LE_READ_SUGGESTED_DEFAULT_DATA_LENGTH not supported, defaulting to 27 (0x1B)"); le_suggested_default_data_length_ = 27; } - if (is_supported(OpCode::LE_READ_MAXIMUM_ADVERTISING_DATA_LENGTH) && module_.SupportsBleExtendedAdvertising()) { + if (is_supported(OpCode::LE_READ_MAXIMUM_ADVERTISING_DATA_LENGTH) && + module_.SupportsBleExtendedAdvertising()) { hci_->EnqueueCommand( - LeReadMaximumAdvertisingDataLengthBuilder::Create(), - handler->BindOnceOn(this, &Controller::impl::le_read_maximum_advertising_data_length_handler)); + LeReadMaximumAdvertisingDataLengthBuilder::Create(), + handler->BindOnceOn( + this, &Controller::impl::le_read_maximum_advertising_data_length_handler)); } else { log::info("LE_READ_MAXIMUM_ADVERTISING_DATA_LENGTH not supported, defaulting to 31 (0x1F)"); le_maximum_advertising_data_length_ = 31; @@ -170,8 +186,10 @@ struct Controller::impl { if (is_supported(OpCode::LE_READ_NUMBER_OF_SUPPORTED_ADVERTISING_SETS) && module_.SupportsBleExtendedAdvertising()) { hci_->EnqueueCommand( - LeReadNumberOfSupportedAdvertisingSetsBuilder::Create(), - handler->BindOnceOn(this, &Controller::impl::le_read_number_of_supported_advertising_sets_handler)); + LeReadNumberOfSupportedAdvertisingSetsBuilder::Create(), + handler->BindOnceOn( + this, + &Controller::impl::le_read_number_of_supported_advertising_sets_handler)); } else { log::info("LE_READ_NUMBER_OF_SUPPORTED_ADVERTISING_SETS not supported, defaulting to 1"); le_number_supported_advertising_sets_ = 1; @@ -180,53 +198,54 @@ struct Controller::impl { if (is_supported(OpCode::LE_READ_PERIODIC_ADVERTISER_LIST_SIZE) && module_.SupportsBlePeriodicAdvertising()) { hci_->EnqueueCommand( - LeReadPeriodicAdvertiserListSizeBuilder::Create(), - handler->BindOnceOn(this, &Controller::impl::le_read_periodic_advertiser_list_size_handler)); + LeReadPeriodicAdvertiserListSizeBuilder::Create(), + handler->BindOnceOn( + this, &Controller::impl::le_read_periodic_advertiser_list_size_handler)); } else { log::info("LE_READ_PERIODIC_ADVERTISER_LIST_SIZE not supported, defaulting to 0"); le_periodic_advertiser_list_size_ = 0; } - if (is_supported(OpCode::LE_SET_HOST_FEATURE) && module_.SupportsBleConnectedIsochronousStreamCentral()) { + if (is_supported(OpCode::LE_SET_HOST_FEATURE) && + module_.SupportsBleConnectedIsochronousStreamCentral()) { hci_->EnqueueCommand( - LeSetHostFeatureBuilder::Create(LeHostFeatureBits::CONNECTED_ISO_STREAM_HOST_SUPPORT, Enable::ENABLED), - handler->BindOnceOn(this, &Controller::impl::le_set_host_feature_handler)); + LeSetHostFeatureBuilder::Create(LeHostFeatureBits::CONNECTED_ISO_STREAM_HOST_SUPPORT, + Enable::ENABLED), + handler->BindOnceOn(this, &Controller::impl::le_set_host_feature_handler)); } if (common::init_flags::subrating_is_enabled() && is_supported(OpCode::LE_SET_HOST_FEATURE) && module_.SupportsBleConnectionSubrating()) { hci_->EnqueueCommand( - LeSetHostFeatureBuilder::Create( - LeHostFeatureBits::CONNECTION_SUBRATING_HOST_SUPPORT, Enable::ENABLED), - handler->BindOnceOn(this, &Controller::impl::le_set_host_feature_handler)); + LeSetHostFeatureBuilder::Create(LeHostFeatureBits::CONNECTION_SUBRATING_HOST_SUPPORT, + Enable::ENABLED), + handler->BindOnceOn(this, &Controller::impl::le_set_host_feature_handler)); } if (com::android::bluetooth::flags::channel_sounding_in_stack() && module_.SupportsBleChannelSounding()) { hci_->EnqueueCommand( - LeSetHostFeatureBuilder::Create( - LeHostFeatureBits::CHANNEL_SOUNDING_HOST_SUPPORT, Enable::ENABLED), - handler->BindOnceOn(this, &Controller::impl::le_set_host_feature_handler)); + LeSetHostFeatureBuilder::Create(LeHostFeatureBits::CHANNEL_SOUNDING_HOST_SUPPORT, + Enable::ENABLED), + handler->BindOnceOn(this, &Controller::impl::le_set_host_feature_handler)); } if (is_supported(OpCode::READ_DEFAULT_ERRONEOUS_DATA_REPORTING)) { hci_->EnqueueCommand( - ReadDefaultErroneousDataReportingBuilder::Create(), - handler->BindOnceOn( - this, &Controller::impl::read_default_erroneous_data_reporting_handler)); + ReadDefaultErroneousDataReportingBuilder::Create(), + handler->BindOnceOn( + this, &Controller::impl::read_default_erroneous_data_reporting_handler)); } // Skip vendor capabilities check if configured. - if (os::GetSystemPropertyBool( - kPropertyVendorCapabilitiesEnabled, kDefaultVendorCapabilitiesEnabled)) { + if (os::GetSystemPropertyBool(kPropertyVendorCapabilitiesEnabled, + kDefaultVendorCapabilitiesEnabled)) { // More commands can be enqueued from le_get_vendor_capabilities_handler std::promise vendor_promise; auto vendor_future = vendor_promise.get_future(); hci_->EnqueueCommand( - LeGetVendorCapabilitiesBuilder::Create(), - handler->BindOnceOn( - this, - &Controller::impl::le_get_vendor_capabilities_handler, - std::move(vendor_promise))); + LeGetVendorCapabilitiesBuilder::Create(), + handler->BindOnceOn(this, &Controller::impl::le_get_vendor_capabilities_handler, + std::move(vendor_promise))); vendor_future.wait(); } else { vendor_capabilities_.is_supported_ = 0x00; @@ -236,14 +255,13 @@ struct Controller::impl { std::promise promise; auto future = promise.get_future(); hci_->EnqueueCommand( - ReadBdAddrBuilder::Create(), - handler->BindOnceOn(this, &Controller::impl::read_controller_mac_address_handler, std::move(promise))); + ReadBdAddrBuilder::Create(), + handler->BindOnceOn(this, &Controller::impl::read_controller_mac_address_handler, + std::move(promise))); future.wait(); } - void Stop() { - hci_ = nullptr; - } + void Stop() { hci_ = nullptr; } void NumberOfCompletedPackets(EventView event) { if (!acl_credits_callback_) { @@ -319,11 +337,11 @@ struct Controller::impl { local_version_information_ = complete_view.GetLocalVersionInformation(); bluetooth::os::LogMetricBluetoothLocalVersions( - local_version_information_.manufacturer_name_, - static_cast(local_version_information_.lmp_version_), - local_version_information_.lmp_subversion_, - static_cast(local_version_information_.hci_version_), - local_version_information_.hci_revision_); + local_version_information_.manufacturer_name_, + static_cast(local_version_information_.lmp_version_), + local_version_information_.lmp_subversion_, + static_cast(local_version_information_.hci_version_), + local_version_information_.hci_revision_); } void read_local_supported_commands_complete_handler(CommandCompleteView view) { @@ -334,21 +352,24 @@ struct Controller::impl { local_supported_commands_ = complete_view.GetSupportedCommands(); } - void read_local_extended_features_complete_handler(std::promise promise, CommandCompleteView view) { + void read_local_extended_features_complete_handler(std::promise promise, + CommandCompleteView view) { auto complete_view = ReadLocalExtendedFeaturesCompleteView::Create(view); ASSERT(complete_view.IsValid()); ErrorCode status = complete_view.GetStatus(); log::assert_that(status == ErrorCode::SUCCESS, "Status {}", ErrorCodeText(status)); uint8_t page_number = complete_view.GetPageNumber(); extended_lmp_features_array_.push_back(complete_view.GetExtendedLmpFeatures()); - bluetooth::os::LogMetricBluetoothLocalSupportedFeatures(page_number, complete_view.GetExtendedLmpFeatures()); + bluetooth::os::LogMetricBluetoothLocalSupportedFeatures(page_number, + complete_view.GetExtendedLmpFeatures()); // Query all extended features if (page_number < complete_view.GetMaximumPageNumber()) { page_number++; hci_->EnqueueCommand( - ReadLocalExtendedFeaturesBuilder::Create(page_number), - module_.GetHandler()->BindOnceOn(this, &Controller::impl::read_local_extended_features_complete_handler, - std::move(promise))); + ReadLocalExtendedFeaturesBuilder::Create(page_number), + module_.GetHandler()->BindOnceOn( + this, &Controller::impl::read_local_extended_features_complete_handler, + std::move(promise))); } else { promise.set_value(); } @@ -382,7 +403,8 @@ struct Controller::impl { log::assert_that(status == ErrorCode::SUCCESS, "Status {}", ErrorCodeText(status)); le_buffer_size_ = complete_view.GetLeBufferSize(); - // If LE buffer size is zero, then buffers returned by Read_Buffer_Size are shared between BR/EDR and LE. + // If LE buffer size is zero, then buffers returned by Read_Buffer_Size are shared between + // BR/EDR and LE. if (le_buffer_size_.total_num_le_packets_ == 0) { ASSERT(acl_buffers_ != 0); le_buffer_size_.total_num_le_packets_ = acl_buffers_ / 2; @@ -415,7 +437,8 @@ struct Controller::impl { le_buffer_size_ = complete_view.GetLeBufferSize(); iso_buffer_size_ = complete_view.GetIsoBufferSize(); - // If LE buffer size is zero, then buffers returned by Read_Buffer_Size are shared between BR/EDR and LE. + // If LE buffer size is zero, then buffers returned by Read_Buffer_Size are shared between + // BR/EDR and LE. if (le_buffer_size_.total_num_le_packets_ == 0) { ASSERT(acl_buffers_ != 0); le_buffer_size_.total_num_le_packets_ = acl_buffers_ / 2; @@ -458,11 +481,11 @@ struct Controller::impl { if (erroneous_data_reporting == Enable::DISABLED && is_supported(OpCode::WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING)) { std::unique_ptr packet = - WriteDefaultErroneousDataReportingBuilder::Create(Enable::ENABLED); + WriteDefaultErroneousDataReportingBuilder::Create(Enable::ENABLED); hci_->EnqueueCommand( - std::move(packet), - module_.GetHandler()->BindOnceOn( - this, &Controller::impl::write_default_erroneous_data_reporting_handler)); + std::move(packet), + module_.GetHandler()->BindOnceOn( + this, &Controller::impl::write_default_erroneous_data_reporting_handler)); } } @@ -559,8 +582,8 @@ struct Controller::impl { le_periodic_advertiser_list_size_ = complete_view.GetPeriodicAdvertiserListSize(); } - void le_get_vendor_capabilities_handler( - std::promise vendor_promise, CommandCompleteView view) { + void le_get_vendor_capabilities_handler(std::promise vendor_promise, + CommandCompleteView view) { auto complete_view = LeGetVendorCapabilitiesCompleteView::Create(view); vendor_capabilities_.is_supported_ = 0x00; @@ -591,14 +614,14 @@ struct Controller::impl { BaseVendorCapabilities base_vendor_capabilities = complete_view.GetBaseVendorCapabilities(); vendor_capabilities_.max_advt_instances_ = base_vendor_capabilities.max_advt_instances_; vendor_capabilities_.offloaded_resolution_of_private_address_ = - base_vendor_capabilities.offloaded_resolution_of_private_address_; + base_vendor_capabilities.offloaded_resolution_of_private_address_; vendor_capabilities_.total_scan_results_storage_ = - base_vendor_capabilities.total_scan_results_storage_; + base_vendor_capabilities.total_scan_results_storage_; vendor_capabilities_.max_irk_list_sz_ = base_vendor_capabilities.max_irk_list_sz_; vendor_capabilities_.filtering_support_ = base_vendor_capabilities.filtering_support_; vendor_capabilities_.max_filter_ = base_vendor_capabilities.max_filter_; vendor_capabilities_.activity_energy_info_support_ = - base_vendor_capabilities.activity_energy_info_support_; + base_vendor_capabilities.activity_energy_info_support_; if (complete_view.GetPayload().size() == 0) { vendor_capabilities_.version_supported_ = 55; @@ -630,7 +653,7 @@ struct Controller::impl { return; } vendor_capabilities_.le_address_generation_offloading_support_ = - v96.GetLeAddressGenerationOffloadingSupport(); + v96.GetLeAddressGenerationOffloadingSupport(); if (vendor_capabilities_.version_supported_ <= 96 || complete_view.GetPayload().size() == 0) { vendor_promise.set_value(); return; @@ -644,7 +667,7 @@ struct Controller::impl { return; } vendor_capabilities_.a2dp_source_offload_capability_mask_ = - v98.GetA2dpSourceOffloadCapabilityMask(); + v98.GetA2dpSourceOffloadCapabilityMask(); vendor_capabilities_.bluetooth_quality_report_support_ = v98.GetBluetoothQualityReportSupport(); // v1.03 @@ -667,11 +690,10 @@ struct Controller::impl { if (vendor_capabilities_.dynamic_audio_buffer_support_) { hci_->EnqueueCommand( - DabGetAudioBufferTimeCapabilityBuilder::Create(), - module_.GetHandler()->BindOnceOn( - this, - &Controller::impl::le_get_dynamic_audio_buffer_support_handler, - std::move(vendor_promise))); + DabGetAudioBufferTimeCapabilityBuilder::Create(), + module_.GetHandler()->BindOnceOn( + this, &Controller::impl::le_get_dynamic_audio_buffer_support_handler, + std::move(vendor_promise))); return; } @@ -682,16 +704,15 @@ struct Controller::impl { return; } hci_->EnqueueCommand( - DabGetAudioBufferTimeCapabilityBuilder::Create(), - module_.GetHandler()->BindOnceOn( - this, - &Controller::impl::le_get_dynamic_audio_buffer_support_handler, - std::move(vendor_promise))); + DabGetAudioBufferTimeCapabilityBuilder::Create(), + module_.GetHandler()->BindOnceOn( + this, &Controller::impl::le_get_dynamic_audio_buffer_support_handler, + std::move(vendor_promise))); } } - void le_get_dynamic_audio_buffer_support_handler( - std::promise vendor_promise, CommandCompleteView view) { + void le_get_dynamic_audio_buffer_support_handler(std::promise vendor_promise, + CommandCompleteView view) { vendor_promise.set_value(); auto dab_complete_view = DynamicAudioBufferCompleteView::Create(view); if (!dab_complete_view.IsValid()) { @@ -732,23 +753,21 @@ struct Controller::impl { return; } - log::info( - "Configured Media Tx Buffer, time returned = {}", - dab_set_complete.GetCurrentBufferTimeMs()); + log::info("Configured Media Tx Buffer, time returned = {}", + dab_set_complete.GetCurrentBufferTimeMs()); } void set_controller_dab_audio_buffer_time(uint16_t buffer_time_ms) { hci_->EnqueueCommand( - DabSetAudioBufferTimeBuilder::Create(buffer_time_ms), - module_.GetHandler()->BindOnceOn( - this, &Controller::impl::set_controller_dab_audio_buffer_time_complete)); + DabSetAudioBufferTimeBuilder::Create(buffer_time_ms), + module_.GetHandler()->BindOnceOn( + this, &Controller::impl::set_controller_dab_audio_buffer_time_complete)); } void set_event_mask(uint64_t event_mask) { std::unique_ptr packet = SetEventMaskBuilder::Create(event_mask); - hci_->EnqueueCommand( - std::move(packet), - module_.GetHandler()->BindOnce(check_complete)); + hci_->EnqueueCommand(std::move(packet), + module_.GetHandler()->BindOnce(check_complete)); } void write_le_host_support(Enable enable, Enable deprecated_host_bit) { @@ -756,30 +775,32 @@ struct Controller::impl { // Since Bluetooth Core Spec 4.1, this bit should be 0 log::warn("Setting deprecated Simultaneous LE BR/EDR Host bit"); } - std::unique_ptr packet = WriteLeHostSupportBuilder::Create(enable, deprecated_host_bit); + std::unique_ptr packet = + WriteLeHostSupportBuilder::Create(enable, deprecated_host_bit); hci_->EnqueueCommand( - std::move(packet), - module_.GetHandler()->BindOnce(check_complete)); + std::move(packet), + module_.GetHandler()->BindOnce(check_complete)); } void write_simple_pairing_mode(Enable enable) { - std::unique_ptr packet = WriteSimplePairingModeBuilder::Create(enable); + std::unique_ptr packet = + WriteSimplePairingModeBuilder::Create(enable); hci_->EnqueueCommand( - std::move(packet), - module_.GetHandler()->BindOnce(check_complete)); + std::move(packet), + module_.GetHandler()->BindOnce(check_complete)); } void reset() { std::unique_ptr packet = ResetBuilder::Create(); - hci_->EnqueueCommand( - std::move(packet), module_.GetHandler()->BindOnce(check_complete)); + hci_->EnqueueCommand(std::move(packet), + module_.GetHandler()->BindOnce(check_complete)); } void le_rand(LeRandCallback cb) { std::unique_ptr packet = LeRandBuilder::Create(); hci_->EnqueueCommand( - std::move(packet), - module_.GetHandler()->BindOnceOn(this, &Controller::impl::le_rand_cb, std::move(cb))); + std::move(packet), + module_.GetHandler()->BindOnceOn(this, &Controller::impl::le_rand_cb, std::move(cb))); } void le_rand_cb(LeRandCallback cb, CommandCompleteView view) { @@ -791,9 +812,8 @@ struct Controller::impl { } void set_event_filter(std::unique_ptr packet) { - hci_->EnqueueCommand( - std::move(packet), - module_.GetHandler()->BindOnce(check_complete)); + hci_->EnqueueCommand(std::move(packet), module_.GetHandler()->BindOnce( + check_complete)); } void write_local_name(std::string local_name) { @@ -804,26 +824,25 @@ struct Controller::impl { std::copy(std::begin(local_name), std::end(local_name), std::begin(local_name_array)); std::unique_ptr packet = WriteLocalNameBuilder::Create(local_name_array); - hci_->EnqueueCommand( - std::move(packet), - module_.GetHandler()->BindOnce(check_complete)); + hci_->EnqueueCommand(std::move(packet), module_.GetHandler()->BindOnce( + check_complete)); } - void host_buffer_size(uint16_t host_acl_data_packet_length, uint8_t host_synchronous_data_packet_length, - uint16_t host_total_num_acl_data_packets, uint16_t host_total_num_synchronous_data_packets) { - std::unique_ptr packet = - HostBufferSizeBuilder::Create(host_acl_data_packet_length, host_synchronous_data_packet_length, - host_total_num_acl_data_packets, host_total_num_synchronous_data_packets); - hci_->EnqueueCommand( - std::move(packet), - module_.GetHandler()->BindOnce(check_complete)); + void host_buffer_size(uint16_t host_acl_data_packet_length, + uint8_t host_synchronous_data_packet_length, + uint16_t host_total_num_acl_data_packets, + uint16_t host_total_num_synchronous_data_packets) { + std::unique_ptr packet = HostBufferSizeBuilder::Create( + host_acl_data_packet_length, host_synchronous_data_packet_length, + host_total_num_acl_data_packets, host_total_num_synchronous_data_packets); + hci_->EnqueueCommand(std::move(packet), module_.GetHandler()->BindOnce( + check_complete)); } void le_set_event_mask(uint64_t le_event_mask) { std::unique_ptr packet = LeSetEventMaskBuilder::Create(le_event_mask); - hci_->EnqueueCommand( - std::move(packet), - module_.GetHandler()->BindOnce(check_complete)); + hci_->EnqueueCommand(std::move(packet), module_.GetHandler()->BindOnce( + check_complete)); } #define OP_CODE_MAPPING(name) \ @@ -838,8 +857,8 @@ struct Controller::impl { return supported; \ } - void Dump( - std::promise> promise, flatbuffers::FlatBufferBuilder* fb_builder) const; + void Dump(std::promise> promise, + flatbuffers::FlatBufferBuilder* fb_builder) const; bool is_supported(OpCode op_code) { switch (op_code) { @@ -1172,7 +1191,8 @@ struct Controller::impl { return vendor_capabilities_.bluetooth_quality_report_support_ == 0x01; case OpCode::DYNAMIC_AUDIO_BUFFER: return vendor_capabilities_.dynamic_audio_buffer_support_ > 0x00; - // Before MSFT extension is fully supported, return false for the following MSFT_OPCODE_XXXX for now. + // Before MSFT extension is fully supported, return false for the following MSFT_OPCODE_XXXX + // for now. case OpCode::MSFT_OPCODE_INTEL: return false; case OpCode::MSFT_OPCODE_MEDIATEK: @@ -1258,9 +1278,7 @@ void Controller::UnregisterCompletedMonitorAclPacketsCallback() { CallOn(impl_.get(), &impl::unregister_completed_monitor_acl_packets_callback); } -std::string Controller::GetLocalName() const { - return impl_->local_name_; -} +std::string Controller::GetLocalName() const { return impl_->local_name_; } LocalVersionInformation Controller::GetLocalVersionInformation() const { return impl_->local_version_information_; @@ -1273,9 +1291,7 @@ std::vector Controller::GetLocalSupportedBrEdrCodecIds() const { #define BIT(x) (0x1ULL << (x)) #define LOCAL_FEATURE_ACCESSOR(name, page, bit) \ - bool Controller::name() const { \ - return GetLocalFeatures(page) & BIT(bit); \ - } + bool Controller::name() const { return GetLocalFeatures(page) & BIT(bit); } LOCAL_FEATURE_ACCESSOR(Supports3SlotPackets, 0, 0) LOCAL_FEATURE_ACCESSOR(Supports5SlotPackets, 0, 1) @@ -1309,9 +1325,7 @@ LOCAL_FEATURE_ACCESSOR(SupportsNonFlushablePb, 0, 54) LOCAL_FEATURE_ACCESSOR(SupportsSecureConnections, 2, 8) #define LOCAL_LE_FEATURE_ACCESSOR(name, bit) \ - bool Controller::name() const { \ - return GetLocalLeFeatures() & BIT(bit); \ - } + bool Controller::name() const { return GetLocalLeFeatures() & BIT(bit); } LOCAL_LE_FEATURE_ACCESSOR(SupportsBleEncryption, 0) LOCAL_LE_FEATURE_ACCESSOR(SupportsBleConnectionParametersRequest, 1) @@ -1361,37 +1375,23 @@ uint64_t Controller::GetLocalFeatures(uint8_t page_number) const { return 0x00; } -uint16_t Controller::GetAclPacketLength() const { - return impl_->acl_buffer_length_; -} +uint16_t Controller::GetAclPacketLength() const { return impl_->acl_buffer_length_; } -uint16_t Controller::GetNumAclPacketBuffers() const { - return impl_->acl_buffers_; -} +uint16_t Controller::GetNumAclPacketBuffers() const { return impl_->acl_buffers_; } -uint8_t Controller::GetScoPacketLength() const { - return impl_->sco_buffer_length_; -} +uint8_t Controller::GetScoPacketLength() const { return impl_->sco_buffer_length_; } -uint16_t Controller::GetNumScoPacketBuffers() const { - return impl_->sco_buffers_; -} +uint16_t Controller::GetNumScoPacketBuffers() const { return impl_->sco_buffers_; } -Address Controller::GetMacAddress() const { - return impl_->mac_address_; -} +Address Controller::GetMacAddress() const { return impl_->mac_address_; } void Controller::SetEventMask(uint64_t event_mask) { CallOn(impl_.get(), &impl::set_event_mask, event_mask); } -void Controller::Reset() { - CallOn(impl_.get(), &impl::reset); -} +void Controller::Reset() { CallOn(impl_.get(), &impl::reset); } -void Controller::LeRand(LeRandCallback cb) { - CallOn(impl_.get(), &impl::le_rand, std::move(cb)); -} +void Controller::LeRand(LeRandCallback cb) { CallOn(impl_.get(), &impl::le_rand, std::move(cb)); } void Controller::SetEventFilterClearAll() { std::unique_ptr packet = SetEventFilterClearAllBuilder::Create(); @@ -1400,26 +1400,27 @@ void Controller::SetEventFilterClearAll() { void Controller::SetEventFilterInquiryResultAllDevices() { std::unique_ptr packet = - SetEventFilterInquiryResultAllDevicesBuilder::Create(); + SetEventFilterInquiryResultAllDevicesBuilder::Create(); CallOn(impl_.get(), &impl::set_event_filter, std::move(packet)); } void Controller::SetEventFilterInquiryResultClassOfDevice(ClassOfDevice class_of_device, ClassOfDevice class_of_device_mask) { std::unique_ptr packet = - SetEventFilterInquiryResultClassOfDeviceBuilder::Create(class_of_device, class_of_device_mask); + SetEventFilterInquiryResultClassOfDeviceBuilder::Create(class_of_device, + class_of_device_mask); CallOn(impl_.get(), &impl::set_event_filter, std::move(packet)); } void Controller::SetEventFilterInquiryResultAddress(Address address) { std::unique_ptr packet = - SetEventFilterInquiryResultAddressBuilder::Create(address); + SetEventFilterInquiryResultAddressBuilder::Create(address); CallOn(impl_.get(), &impl::set_event_filter, std::move(packet)); } void Controller::SetEventFilterConnectionSetupAllDevices(AutoAcceptFlag auto_accept_flag) { std::unique_ptr packet = - SetEventFilterConnectionSetupAllDevicesBuilder::Create(auto_accept_flag); + SetEventFilterConnectionSetupAllDevicesBuilder::Create(auto_accept_flag); CallOn(impl_.get(), &impl::set_event_filter, std::move(packet)); } @@ -1427,14 +1428,15 @@ void Controller::SetEventFilterConnectionSetupClassOfDevice(ClassOfDevice class_ ClassOfDevice class_of_device_mask, AutoAcceptFlag auto_accept_flag) { std::unique_ptr packet = - SetEventFilterConnectionSetupClassOfDeviceBuilder::Create(class_of_device, class_of_device_mask, - auto_accept_flag); + SetEventFilterConnectionSetupClassOfDeviceBuilder::Create( + class_of_device, class_of_device_mask, auto_accept_flag); CallOn(impl_.get(), &impl::set_event_filter, std::move(packet)); } -void Controller::SetEventFilterConnectionSetupAddress(Address address, AutoAcceptFlag auto_accept_flag) { +void Controller::SetEventFilterConnectionSetupAddress(Address address, + AutoAcceptFlag auto_accept_flag) { std::unique_ptr packet = - SetEventFilterConnectionSetupAddressBuilder::Create(address, auto_accept_flag); + SetEventFilterConnectionSetupAddressBuilder::Create(address, auto_accept_flag); CallOn(impl_.get(), &impl::set_event_filter, std::move(packet)); } @@ -1443,49 +1445,34 @@ void Controller::WriteLocalName(std::string local_name) { CallOn(impl_.get(), &impl::write_local_name, local_name); } -void Controller::HostBufferSize(uint16_t host_acl_data_packet_length, uint8_t host_synchronous_data_packet_length, +void Controller::HostBufferSize(uint16_t host_acl_data_packet_length, + uint8_t host_synchronous_data_packet_length, uint16_t host_total_num_acl_data_packets, uint16_t host_total_num_synchronous_data_packets) { - CallOn( - impl_.get(), - &impl::host_buffer_size, - host_acl_data_packet_length, - host_synchronous_data_packet_length, - host_total_num_acl_data_packets, - host_total_num_synchronous_data_packets); + CallOn(impl_.get(), &impl::host_buffer_size, host_acl_data_packet_length, + host_synchronous_data_packet_length, host_total_num_acl_data_packets, + host_total_num_synchronous_data_packets); } void Controller::LeSetEventMask(uint64_t le_event_mask) { CallOn(impl_.get(), &impl::le_set_event_mask, le_event_mask); } -LeBufferSize Controller::GetLeBufferSize() const { - return impl_->le_buffer_size_; -} +LeBufferSize Controller::GetLeBufferSize() const { return impl_->le_buffer_size_; } -uint64_t Controller::GetLocalLeFeatures() const { - return impl_->le_local_supported_features_; -} +uint64_t Controller::GetLocalLeFeatures() const { return impl_->le_local_supported_features_; } -LeBufferSize Controller::GetControllerIsoBufferSize() const { - return impl_->iso_buffer_size_; -} +LeBufferSize Controller::GetControllerIsoBufferSize() const { return impl_->iso_buffer_size_; } uint64_t Controller::GetControllerLeLocalSupportedFeatures() const { return impl_->le_local_supported_features_; } -uint64_t Controller::GetLeSupportedStates() const { - return impl_->le_supported_states_; -} +uint64_t Controller::GetLeSupportedStates() const { return impl_->le_supported_states_; } -uint8_t Controller::GetLeFilterAcceptListSize() const { - return impl_->le_accept_list_size_; -} +uint8_t Controller::GetLeFilterAcceptListSize() const { return impl_->le_accept_list_size_; } -uint8_t Controller::GetLeResolvingListSize() const { - return impl_->le_resolving_list_size_; -} +uint8_t Controller::GetLeResolvingListSize() const { return impl_->le_resolving_list_size_; } LeMaximumDataLength Controller::GetLeMaximumDataLength() const { return impl_->le_maximum_data_length_; @@ -1507,12 +1494,10 @@ Controller::VendorCapabilities Controller::GetVendorCapabilities() const { return impl_->vendor_capabilities_; } -uint32_t Controller::GetDabSupportedCodecs() const { - return impl_->dab_supported_codecs_; -} +uint32_t Controller::GetDabSupportedCodecs() const { return impl_->dab_supported_codecs_; } const std::array& Controller::GetDabCodecCapabilities() - const { + const { return impl_->dab_codec_capabilities_; } @@ -1560,69 +1545,61 @@ void Controller::ListDependencies(ModuleList* list) const { #endif } -void Controller::Start() { - impl_->Start(GetDependency()); -} +void Controller::Start() { impl_->Start(GetDependency()); } -void Controller::Stop() { - impl_->Stop(); -} +void Controller::Stop() { impl_->Stop(); } -std::string Controller::ToString() const { - return "Controller"; -} +std::string Controller::ToString() const { return "Controller"; } -void Controller::impl::Dump( - std::promise> promise, flatbuffers::FlatBufferBuilder* fb_builder) const { +void Controller::impl::Dump(std::promise> promise, + flatbuffers::FlatBufferBuilder* fb_builder) const { ASSERT(fb_builder != nullptr); auto title = fb_builder->CreateString("----- Hci Controller Dumpsys -----"); auto local_version_information_data = CreateLocalVersionInformationData( - *fb_builder, - fb_builder->CreateString(HciVersionText(local_version_information_.hci_version_)), - local_version_information_.hci_revision_, - fb_builder->CreateString(LmpVersionText(local_version_information_.lmp_version_)), - local_version_information_.manufacturer_name_, - local_version_information_.lmp_subversion_); + *fb_builder, + fb_builder->CreateString(HciVersionText(local_version_information_.hci_version_)), + local_version_information_.hci_revision_, + fb_builder->CreateString(LmpVersionText(local_version_information_.lmp_version_)), + local_version_information_.manufacturer_name_, + local_version_information_.lmp_subversion_); auto acl_buffer_size_data = BufferSizeData(acl_buffer_length_, acl_buffers_); auto sco_buffer_size_data = BufferSizeData(sco_buffer_length_, sco_buffers_); - auto le_buffer_size_data = - BufferSizeData(le_buffer_size_.le_data_packet_length_, le_buffer_size_.total_num_le_packets_); + auto le_buffer_size_data = BufferSizeData(le_buffer_size_.le_data_packet_length_, + le_buffer_size_.total_num_le_packets_); - auto iso_buffer_size_data = - BufferSizeData(iso_buffer_size_.le_data_packet_length_, iso_buffer_size_.total_num_le_packets_); + auto iso_buffer_size_data = BufferSizeData(iso_buffer_size_.le_data_packet_length_, + iso_buffer_size_.total_num_le_packets_); - auto le_maximum_data_length_data = LeMaximumDataLengthData( - le_maximum_data_length_.supported_max_tx_octets_, - le_maximum_data_length_.supported_max_tx_time_, - le_maximum_data_length_.supported_max_rx_octets_, - le_maximum_data_length_.supported_max_rx_time_); + auto le_maximum_data_length_data = + LeMaximumDataLengthData(le_maximum_data_length_.supported_max_tx_octets_, + le_maximum_data_length_.supported_max_tx_time_, + le_maximum_data_length_.supported_max_rx_octets_, + le_maximum_data_length_.supported_max_rx_time_); std::vector local_supported_commands_vector; for (uint8_t index = 0; index < local_supported_commands_.size(); index++) { - local_supported_commands_vector.push_back(LocalSupportedCommandsData(index, local_supported_commands_[index])); + local_supported_commands_vector.push_back( + LocalSupportedCommandsData(index, local_supported_commands_[index])); } - auto local_supported_commands_data = fb_builder->CreateVectorOfStructs(local_supported_commands_vector); + auto local_supported_commands_data = + fb_builder->CreateVectorOfStructs(local_supported_commands_vector); auto vendor_capabilities_data = VendorCapabilitiesData( - vendor_capabilities_.is_supported_, - vendor_capabilities_.max_advt_instances_, - vendor_capabilities_.offloaded_resolution_of_private_address_, - vendor_capabilities_.total_scan_results_storage_, - vendor_capabilities_.max_irk_list_sz_, - vendor_capabilities_.filtering_support_, - vendor_capabilities_.max_filter_, - vendor_capabilities_.activity_energy_info_support_, - vendor_capabilities_.version_supported_, - vendor_capabilities_.total_num_of_advt_tracked_, - vendor_capabilities_.extended_scan_support_, - vendor_capabilities_.debug_logging_supported_, - vendor_capabilities_.le_address_generation_offloading_support_, - vendor_capabilities_.a2dp_source_offload_capability_mask_, - vendor_capabilities_.bluetooth_quality_report_support_); + vendor_capabilities_.is_supported_, vendor_capabilities_.max_advt_instances_, + vendor_capabilities_.offloaded_resolution_of_private_address_, + vendor_capabilities_.total_scan_results_storage_, vendor_capabilities_.max_irk_list_sz_, + vendor_capabilities_.filtering_support_, vendor_capabilities_.max_filter_, + vendor_capabilities_.activity_energy_info_support_, + vendor_capabilities_.version_supported_, vendor_capabilities_.total_num_of_advt_tracked_, + vendor_capabilities_.extended_scan_support_, + vendor_capabilities_.debug_logging_supported_, + vendor_capabilities_.le_address_generation_offloading_support_, + vendor_capabilities_.a2dp_source_offload_capability_mask_, + vendor_capabilities_.bluetooth_quality_report_support_); auto extended_lmp_features_vector = fb_builder->CreateVector(extended_lmp_features_array_); diff --git a/system/gd/hci/controller.h b/system/gd/hci/controller.h index faf5a6bd6f5..9eaa026b230 100644 --- a/system/gd/hci/controller.h +++ b/system/gd/hci/controller.h @@ -31,7 +31,7 @@ namespace bluetooth { namespace hci { class Controller : public Module, public ControllerInterface { - public: +public: Controller(); Controller(const Controller&) = delete; Controller& operator=(const Controller&) = delete; @@ -141,27 +141,25 @@ class Controller : public Module, public ControllerInterface { virtual void SetEventFilterInquiryResultAllDevices() override; virtual void SetEventFilterInquiryResultClassOfDevice( - ClassOfDevice class_of_device, ClassOfDevice class_of_device_mask) override; + ClassOfDevice class_of_device, ClassOfDevice class_of_device_mask) override; virtual void SetEventFilterInquiryResultAddress(Address address) override; virtual void SetEventFilterConnectionSetupAllDevices(AutoAcceptFlag auto_accept_flag) override; - virtual void SetEventFilterConnectionSetupClassOfDevice( - ClassOfDevice class_of_device, - ClassOfDevice class_of_device_mask, - AutoAcceptFlag auto_accept_flag) override; + virtual void SetEventFilterConnectionSetupClassOfDevice(ClassOfDevice class_of_device, + ClassOfDevice class_of_device_mask, + AutoAcceptFlag auto_accept_flag) override; - virtual void SetEventFilterConnectionSetupAddress( - Address address, AutoAcceptFlag auto_accept_flag) override; + virtual void SetEventFilterConnectionSetupAddress(Address address, + AutoAcceptFlag auto_accept_flag) override; virtual void WriteLocalName(std::string local_name) override; - virtual void HostBufferSize( - uint16_t host_acl_data_packet_length, - uint8_t host_synchronous_data_packet_length, - uint16_t host_total_num_acl_data_packets, - uint16_t host_total_num_synchronous_data_packets) override; + virtual void HostBufferSize(uint16_t host_acl_data_packet_length, + uint8_t host_synchronous_data_packet_length, + uint16_t host_total_num_acl_data_packets, + uint16_t host_total_num_synchronous_data_packets) override; // LE controller commands virtual void LeSetEventMask(uint64_t le_event_mask) override; @@ -195,7 +193,7 @@ class Controller : public Module, public ControllerInterface { virtual uint32_t GetDabSupportedCodecs() const override; virtual const std::array& GetDabCodecCapabilities() - const override; + const override; virtual void SetDabAudioBufferTime(uint16_t buffer_time_ms) override; @@ -216,7 +214,7 @@ class Controller : public Module, public ControllerInterface { static uint64_t MaskLeEventMask(HciVersion version, uint64_t mask); - protected: +protected: void ListDependencies(ModuleList* list) const override; void Start() override; @@ -225,9 +223,10 @@ class Controller : public Module, public ControllerInterface { std::string ToString() const override; - DumpsysDataFinisher GetDumpsysData(flatbuffers::FlatBufferBuilder* builder) const override; // Module + DumpsysDataFinisher GetDumpsysData( + flatbuffers::FlatBufferBuilder* builder) const override; // Module - private: +private: virtual uint64_t GetLocalFeatures(uint8_t page_number) const; virtual uint64_t GetLocalLeFeatures() const; diff --git a/system/gd/hci/controller_interface.h b/system/gd/hci/controller_interface.h index ecc7255282e..25148da44c7 100644 --- a/system/gd/hci/controller_interface.h +++ b/system/gd/hci/controller_interface.h @@ -26,12 +26,12 @@ namespace bluetooth { namespace hci { class ControllerInterface { - public: +public: ControllerInterface() = default; virtual ~ControllerInterface() = default; using CompletedAclPacketsCallback = - common::ContextualCallback; + common::ContextualCallback; virtual void RegisterCompletedAclPacketsCallback(CompletedAclPacketsCallback cb) = 0; virtual void UnregisterCompletedAclPacketsCallback() = 0; @@ -133,28 +133,26 @@ class ControllerInterface { virtual void SetEventFilterInquiryResultAllDevices() = 0; - virtual void SetEventFilterInquiryResultClassOfDevice( - ClassOfDevice class_of_device, ClassOfDevice class_of_device_mask) = 0; + virtual void SetEventFilterInquiryResultClassOfDevice(ClassOfDevice class_of_device, + ClassOfDevice class_of_device_mask) = 0; virtual void SetEventFilterInquiryResultAddress(Address address) = 0; virtual void SetEventFilterConnectionSetupAllDevices(AutoAcceptFlag auto_accept_flag) = 0; - virtual void SetEventFilterConnectionSetupClassOfDevice( - ClassOfDevice class_of_device, - ClassOfDevice class_of_device_mask, - AutoAcceptFlag auto_accept_flag) = 0; + virtual void SetEventFilterConnectionSetupClassOfDevice(ClassOfDevice class_of_device, + ClassOfDevice class_of_device_mask, + AutoAcceptFlag auto_accept_flag) = 0; - virtual void SetEventFilterConnectionSetupAddress( - Address address, AutoAcceptFlag auto_accept_flag) = 0; + virtual void SetEventFilterConnectionSetupAddress(Address address, + AutoAcceptFlag auto_accept_flag) = 0; virtual void WriteLocalName(std::string local_name) = 0; - virtual void HostBufferSize( - uint16_t host_acl_data_packet_length, - uint8_t host_synchronous_data_packet_length, - uint16_t host_total_num_acl_data_packets, - uint16_t host_total_num_synchronous_data_packets) = 0; + virtual void HostBufferSize(uint16_t host_acl_data_packet_length, + uint8_t host_synchronous_data_packet_length, + uint16_t host_total_num_acl_data_packets, + uint16_t host_total_num_synchronous_data_packets) = 0; // LE controller commands virtual void LeSetEventMask(uint64_t le_event_mask) = 0; @@ -206,7 +204,7 @@ class ControllerInterface { virtual uint32_t GetDabSupportedCodecs() const = 0; virtual const std::array& GetDabCodecCapabilities() - const = 0; + const = 0; virtual void SetDabAudioBufferTime(uint16_t buffer_time_ms) = 0; diff --git a/system/gd/hci/controller_interface_mock.h b/system/gd/hci/controller_interface_mock.h index af67af31325..6c8a2811d97 100644 --- a/system/gd/hci/controller_interface_mock.h +++ b/system/gd/hci/controller_interface_mock.h @@ -30,7 +30,7 @@ namespace hci { namespace testing { class MockControllerInterface : public ControllerInterface { - public: +public: MOCK_METHOD(void, RegisterCompletedAclPacketsCallback, (CompletedAclPacketsCallback cb)); MOCK_METHOD(void, UnregisterCompletedAclPacketsCallback, ()); MOCK_METHOD(void, RegisterCompletedMonitorAclPacketsCallback, (CompletedAclPacketsCallback cb)); @@ -119,30 +119,20 @@ class MockControllerInterface : public ControllerInterface { MOCK_METHOD(void, LeRand, (LeRandCallback cb)); MOCK_METHOD(void, SetEventFilterClearAll, ()); MOCK_METHOD(void, SetEventFilterInquiryResultAllDevices, ()); - MOCK_METHOD( - void, - SetEventFilterInquiryResultClassOfDevice, - (ClassOfDevice class_of_device, ClassOfDevice class_of_device_mask)); + MOCK_METHOD(void, SetEventFilterInquiryResultClassOfDevice, + (ClassOfDevice class_of_device, ClassOfDevice class_of_device_mask)); MOCK_METHOD(void, SetEventFilterInquiryResultAddress, (Address address)); MOCK_METHOD(void, SetEventFilterConnectionSetupAllDevices, (AutoAcceptFlag auto_accept_flag)); - MOCK_METHOD( - void, - SetEventFilterConnectionSetupClassOfDevice, - (ClassOfDevice class_of_device, - ClassOfDevice class_of_device_mask, - AutoAcceptFlag auto_accept_flag)); - MOCK_METHOD( - void, - SetEventFilterConnectionSetupAddress, - (Address address, AutoAcceptFlag auto_accept_flag)); + MOCK_METHOD(void, SetEventFilterConnectionSetupClassOfDevice, + (ClassOfDevice class_of_device, ClassOfDevice class_of_device_mask, + AutoAcceptFlag auto_accept_flag)); + MOCK_METHOD(void, SetEventFilterConnectionSetupAddress, + (Address address, AutoAcceptFlag auto_accept_flag)); MOCK_METHOD(void, WriteLocalName, (std::string local_name)); - MOCK_METHOD( - void, - HostBufferSize, - (uint16_t host_acl_data_packet_length, - uint8_t host_synchronous_data_packet_length, - uint16_t host_total_num_acl_data_packets, - uint16_t host_total_num_synchronous_data_packets)); + MOCK_METHOD(void, HostBufferSize, + (uint16_t host_acl_data_packet_length, uint8_t host_synchronous_data_packet_length, + uint16_t host_total_num_acl_data_packets, + uint16_t host_total_num_synchronous_data_packets)); // LE controller commands MOCK_METHOD(void, LeSetEventMask, (uint64_t le_event_mask)); MOCK_METHOD(LeBufferSize, GetLeBufferSize, (), (const)); @@ -161,11 +151,8 @@ class MockControllerInterface : public ControllerInterface { MOCK_METHOD(bool, IsSupported, (OpCode op_code), (const)); MOCK_METHOD(uint32_t, GetDabSupportedCodecs, (), (const)); - MOCK_METHOD( - (const std::array&), - GetDabCodecCapabilities, - (), - (const)); + MOCK_METHOD((const std::array&), GetDabCodecCapabilities, + (), (const)); MOCK_METHOD(void, SetDabAudioBufferTime, (uint16_t buffer_time_ms)); }; diff --git a/system/gd/hci/controller_mock.h b/system/gd/hci/controller_mock.h index 153eeecd19a..1c05ad983b8 100644 --- a/system/gd/hci/controller_mock.h +++ b/system/gd/hci/controller_mock.h @@ -30,7 +30,7 @@ namespace hci { namespace testing { class MockController : public Controller { - public: +public: MOCK_METHOD(void, RegisterCompletedAclPacketsCallback, (CompletedAclPacketsCallback cb)); MOCK_METHOD(void, UnregisterCompletedAclPacketsCallback, ()); MOCK_METHOD(void, RegisterCompletedMonitorAclPacketsCallback, (CompletedAclPacketsCallback cb)); @@ -119,25 +119,20 @@ class MockController : public Controller { MOCK_METHOD(void, LeRand, (LeRandCallback cb)); MOCK_METHOD(void, SetEventFilterClearAll, ()); MOCK_METHOD(void, SetEventFilterInquiryResultAllDevices, ()); - MOCK_METHOD( - void, - SetEventFilterInquiryResultClassOfDevice, - (ClassOfDevice class_of_device, ClassOfDevice class_of_device_mask)); + MOCK_METHOD(void, SetEventFilterInquiryResultClassOfDevice, + (ClassOfDevice class_of_device, ClassOfDevice class_of_device_mask)); MOCK_METHOD(void, SetEventFilterInquiryResultAddress, (Address address)); MOCK_METHOD(void, SetEventFilterConnectionSetupAllDevices, (AutoAcceptFlag auto_accept_flag)); - MOCK_METHOD( - void, - SetEventFilterConnectionSetupClassOfDevice, - (ClassOfDevice class_of_device, ClassOfDevice class_of_device_mask, AutoAcceptFlag auto_accept_flag)); - MOCK_METHOD(void, SetEventFilterConnectionSetupAddress, (Address address, AutoAcceptFlag auto_accept_flag)); + MOCK_METHOD(void, SetEventFilterConnectionSetupClassOfDevice, + (ClassOfDevice class_of_device, ClassOfDevice class_of_device_mask, + AutoAcceptFlag auto_accept_flag)); + MOCK_METHOD(void, SetEventFilterConnectionSetupAddress, + (Address address, AutoAcceptFlag auto_accept_flag)); MOCK_METHOD(void, WriteLocalName, (std::string local_name)); - MOCK_METHOD( - void, - HostBufferSize, - (uint16_t host_acl_data_packet_length, - uint8_t host_synchronous_data_packet_length, - uint16_t host_total_num_acl_data_packets, - uint16_t host_total_num_synchronous_data_packets)); + MOCK_METHOD(void, HostBufferSize, + (uint16_t host_acl_data_packet_length, uint8_t host_synchronous_data_packet_length, + uint16_t host_total_num_acl_data_packets, + uint16_t host_total_num_synchronous_data_packets)); // LE controller commands MOCK_METHOD(void, LeSetEventMask, (uint64_t le_event_mask)); MOCK_METHOD(LeBufferSize, GetLeBufferSize, (), (const)); @@ -156,11 +151,8 @@ class MockController : public Controller { MOCK_METHOD(bool, IsSupported, (OpCode op_code), (const)); MOCK_METHOD(uint32_t, GetDabSupportedCodecs, (), (const)); - MOCK_METHOD( - (const std::array&), - GetDabCodecCapabilities, - (), - (const)); + MOCK_METHOD((const std::array&), GetDabCodecCapabilities, + (), (const)); MOCK_METHOD(void, SetDabAudioBufferTime, (uint16_t buffer_time_ms)); }; diff --git a/system/gd/hci/controller_test.cc b/system/gd/hci/controller_test.cc index df5b4cfa2fb..b2e27ef5263 100644 --- a/system/gd/hci/controller_test.cc +++ b/system/gd/hci/controller_test.cc @@ -61,26 +61,23 @@ constexpr char title[] = "hci_controller_test"; namespace { class HciLayerFakeForController : public HciLayerFake { - public: +public: void EnqueueCommand( - std::unique_ptr command, - common::ContextualOnceCallback on_complete) override { - GetHandler()->Post(common::BindOnce( - &HciLayerFakeForController::HandleCommand, - common::Unretained(this), - std::move(command), - std::move(on_complete))); + std::unique_ptr command, + common::ContextualOnceCallback on_complete) override { + GetHandler()->Post(common::BindOnce(&HciLayerFakeForController::HandleCommand, + common::Unretained(this), std::move(command), + std::move(on_complete))); } void EnqueueCommand( - std::unique_ptr /* command */, - common::ContextualOnceCallback /* on_status */) override { + std::unique_ptr /* command */, + common::ContextualOnceCallback /* on_status */) override { FAIL() << "Controller properties should not generate Command Status"; } - void HandleCommand( - std::unique_ptr command_builder, - common::ContextualOnceCallback on_complete) { + void HandleCommand(std::unique_ptr command_builder, + common::ContextualOnceCallback on_complete) { auto bytes = std::make_shared>(); BitInserter i(*bytes); bytes->reserve((command_builder)->size()); @@ -94,7 +91,8 @@ class HciLayerFakeForController : public HciLayerFake { switch (command.GetOpCode()) { case (OpCode::READ_LOCAL_NAME): { std::array local_name = {'D', 'U', 'T', '\0'}; - event_builder = ReadLocalNameCompleteBuilder::Create(num_packets, ErrorCode::SUCCESS, local_name); + event_builder = + ReadLocalNameCompleteBuilder::Create(num_packets, ErrorCode::SUCCESS, local_name); } break; case (OpCode::READ_LOCAL_VERSION_INFORMATION): { LocalVersionInformation local_version_information; @@ -104,7 +102,7 @@ class HciLayerFakeForController : public HciLayerFake { local_version_information.manufacturer_name_ = 0xBAD; local_version_information.lmp_subversion_ = 0x5678; event_builder = ReadLocalVersionInformationCompleteBuilder::Create( - num_packets, ErrorCode::SUCCESS, local_version_information); + num_packets, ErrorCode::SUCCESS, local_version_information); } break; case (OpCode::READ_LOCAL_SUPPORTED_COMMANDS): { std::array supported_commands; @@ -114,14 +112,14 @@ class HciLayerFakeForController : public HciLayerFake { for (int i = 37; i < 64; i++) { supported_commands[i] = 0x00; } - event_builder = - ReadLocalSupportedCommandsCompleteBuilder::Create(num_packets, ErrorCode::SUCCESS, supported_commands); + event_builder = ReadLocalSupportedCommandsCompleteBuilder::Create( + num_packets, ErrorCode::SUCCESS, supported_commands); } break; case (OpCode::READ_LOCAL_SUPPORTED_CODECS_V1): { std::vector supported_codecs{0, 1, 2, 3, 4, 5, 6}; std::vector supported_vendor_codecs; event_builder = ReadLocalSupportedCodecsV1CompleteBuilder::Create( - num_packets, ErrorCode::SUCCESS, supported_codecs, supported_vendor_codecs); + num_packets, ErrorCode::SUCCESS, supported_codecs, supported_vendor_codecs); } break; case (OpCode::READ_LOCAL_EXTENDED_FEATURES): { ReadLocalExtendedFeaturesView read_command = ReadLocalExtendedFeaturesView::Create(command); @@ -130,33 +128,32 @@ class HciLayerFakeForController : public HciLayerFake { uint64_t lmp_features = 0x012345678abcdef; lmp_features += page_bumber; event_builder = ReadLocalExtendedFeaturesCompleteBuilder::Create( - num_packets, ErrorCode::SUCCESS, page_bumber, 0x02, lmp_features); + num_packets, ErrorCode::SUCCESS, page_bumber, 0x02, lmp_features); } break; case (OpCode::READ_BUFFER_SIZE): { event_builder = ReadBufferSizeCompleteBuilder::Create( - num_packets, - ErrorCode::SUCCESS, - acl_data_packet_length, - synchronous_data_packet_length, - total_num_acl_data_packets, - total_num_synchronous_data_packets); + num_packets, ErrorCode::SUCCESS, acl_data_packet_length, + synchronous_data_packet_length, total_num_acl_data_packets, + total_num_synchronous_data_packets); } break; case (OpCode::READ_BD_ADDR): { - event_builder = ReadBdAddrCompleteBuilder::Create(num_packets, ErrorCode::SUCCESS, Address::kAny); + event_builder = + ReadBdAddrCompleteBuilder::Create(num_packets, ErrorCode::SUCCESS, Address::kAny); } break; case (OpCode::LE_READ_BUFFER_SIZE_V1): { LeBufferSize le_buffer_size; le_buffer_size.le_data_packet_length_ = 0x16; le_buffer_size.total_num_le_packets_ = 0x08; - event_builder = LeReadBufferSizeV1CompleteBuilder::Create(num_packets, ErrorCode::SUCCESS, le_buffer_size); + event_builder = LeReadBufferSizeV1CompleteBuilder::Create(num_packets, ErrorCode::SUCCESS, + le_buffer_size); } break; case (OpCode::LE_READ_LOCAL_SUPPORTED_FEATURES): { - event_builder = - LeReadLocalSupportedFeaturesCompleteBuilder::Create(num_packets, ErrorCode::SUCCESS, 0x001f123456789abc); + event_builder = LeReadLocalSupportedFeaturesCompleteBuilder::Create( + num_packets, ErrorCode::SUCCESS, 0x001f123456789abc); } break; case (OpCode::LE_READ_SUPPORTED_STATES): { - event_builder = - LeReadSupportedStatesCompleteBuilder::Create(num_packets, ErrorCode::SUCCESS, 0x001f123456789abe); + event_builder = LeReadSupportedStatesCompleteBuilder::Create( + num_packets, ErrorCode::SUCCESS, 0x001f123456789abe); } break; case (OpCode::LE_READ_MAXIMUM_DATA_LENGTH): { LeMaximumDataLength le_maximum_data_length; @@ -164,16 +161,16 @@ class HciLayerFakeForController : public HciLayerFake { le_maximum_data_length.supported_max_tx_time_ = 0x34; le_maximum_data_length.supported_max_rx_octets_ = 0x56; le_maximum_data_length.supported_max_rx_time_ = 0x78; - event_builder = - LeReadMaximumDataLengthCompleteBuilder::Create(num_packets, ErrorCode::SUCCESS, le_maximum_data_length); + event_builder = LeReadMaximumDataLengthCompleteBuilder::Create( + num_packets, ErrorCode::SUCCESS, le_maximum_data_length); } break; case (OpCode::LE_READ_MAXIMUM_ADVERTISING_DATA_LENGTH): { - event_builder = - LeReadMaximumAdvertisingDataLengthCompleteBuilder::Create(num_packets, ErrorCode::SUCCESS, 0x0672); + event_builder = LeReadMaximumAdvertisingDataLengthCompleteBuilder::Create( + num_packets, ErrorCode::SUCCESS, 0x0672); } break; case (OpCode::LE_READ_NUMBER_OF_SUPPORTED_ADVERTISING_SETS): { - event_builder = - LeReadNumberOfSupportedAdvertisingSetsCompleteBuilder::Create(num_packets, ErrorCode::SUCCESS, 0xF0); + event_builder = LeReadNumberOfSupportedAdvertisingSetsCompleteBuilder::Create( + num_packets, ErrorCode::SUCCESS, 0xF0); } break; case (OpCode::LE_GET_VENDOR_CAPABILITIES): if (vendor_capabilities_ == nullptr) { @@ -188,13 +185,13 @@ class HciLayerFakeForController : public HciLayerFake { auto payload = std::make_unique(); if (feature_spec_version > 55) { - std::vector payload_bytes = { - 0x20, 0x00, 0x01, 0x00, 0x00, 0x1f, 0x00, 0x00, 0x00, 0x00}; + std::vector payload_bytes = {0x20, 0x00, 0x01, 0x00, 0x00, + 0x1f, 0x00, 0x00, 0x00, 0x00}; payload->AddOctets2(feature_spec_version); payload->AddOctets(payload_bytes); } event_builder = LeGetVendorCapabilitiesCompleteBuilder::Create( - num_packets, ErrorCode::SUCCESS, base_vendor_capabilities, std::move(payload)); + num_packets, ErrorCode::SUCCESS, base_vendor_capabilities, std::move(payload)); } else { event_builder = std::move(vendor_capabilities_); vendor_capabilities_.reset(); @@ -202,22 +199,22 @@ class HciLayerFakeForController : public HciLayerFake { break; case (OpCode::DYNAMIC_AUDIO_BUFFER): { auto dab_command = - DynamicAudioBufferView::CreateOptional(VendorCommandView::Create(command)); + DynamicAudioBufferView::CreateOptional(VendorCommandView::Create(command)); if (dab_command->GetDabCommand() == DabCommand::GET_AUDIO_BUFFER_TIME_CAPABILITY) { std::array capabilities{}; capabilities[0] = - DynamicAudioBufferCodecCapability(0x123, 0x103, 0x1234); // sbc_capabilities + DynamicAudioBufferCodecCapability(0x123, 0x103, 0x1234); // sbc_capabilities capabilities[1] = - DynamicAudioBufferCodecCapability(0x223, 0x123, 0x2340); // aac_capabilities + DynamicAudioBufferCodecCapability(0x223, 0x123, 0x2340); // aac_capabilities capabilities[4] = - DynamicAudioBufferCodecCapability(0x323, 0x223, 0x3456); // ldac_capabilities + DynamicAudioBufferCodecCapability(0x323, 0x223, 0x3456); // ldac_capabilities event_builder = DabGetAudioBufferTimeCapabilityCompleteBuilder::Create( - 1, ErrorCode::SUCCESS, kDynamicAudioBufferSupport, capabilities); + 1, ErrorCode::SUCCESS, kDynamicAudioBufferSupport, capabilities); } else { auto set_command = DabSetAudioBufferTimeView::CreateOptional(*dab_command); dynamic_audio_buffer_time = set_command->GetBufferTimeMs(); - event_builder = DabSetAudioBufferTimeCompleteBuilder::Create( - 1, ErrorCode::SUCCESS, dynamic_audio_buffer_time); + event_builder = DabSetAudioBufferTimeCompleteBuilder::Create(1, ErrorCode::SUCCESS, + dynamic_audio_buffer_time); } } break; case (OpCode::SET_EVENT_MASK): { @@ -236,7 +233,8 @@ class HciLayerFakeForController : public HciLayerFake { case (OpCode::LE_RAND): { auto view = LeRandView::Create(LeSecurityCommandView::Create(command)); ASSERT_TRUE(view.IsValid()); - event_builder = LeRandCompleteBuilder::Create(num_packets, ErrorCode::SUCCESS, kRandomNumber); + event_builder = + LeRandCompleteBuilder::Create(num_packets, ErrorCode::SUCCESS, kRandomNumber); } break; // Let the test check and handle these commands. @@ -281,7 +279,7 @@ class HciLayerFakeForController : public HciLayerFake { }; class ControllerTest : public ::testing::Test { - protected: +protected: void SetUp() override { feature_spec_version = feature_spec_version_; bluetooth::common::InitFlags::SetAllForTesting(); @@ -294,9 +292,7 @@ class ControllerTest : public ::testing::Test { controller_ = static_cast(fake_registry_.GetModuleUnderTest(&Controller::Factory)); } - void TearDown() override { - fake_registry_.StopAll(); - } + void TearDown() override { fake_registry_.StopAll(); } TestModuleRegistry fake_registry_; HciLayerFakeForController* test_hci_layer_ = nullptr; @@ -309,7 +305,7 @@ class ControllerTest : public ::testing::Test { } // namespace class Controller055Test : public ControllerTest { - protected: +protected: void SetUp() override { feature_spec_version_ = 55; ControllerTest::SetUp(); @@ -317,7 +313,7 @@ class Controller055Test : public ControllerTest { }; class Controller095Test : public ControllerTest { - protected: +protected: void SetUp() override { feature_spec_version_ = 95; ControllerTest::SetUp(); @@ -325,7 +321,7 @@ class Controller095Test : public ControllerTest { }; class Controller096Test : public ControllerTest { - protected: +protected: void SetUp() override { feature_spec_version_ = 96; ControllerTest::SetUp(); @@ -333,7 +329,7 @@ class Controller096Test : public ControllerTest { }; class Controller103Test : public ControllerTest { - protected: +protected: void SetUp() override { feature_spec_version_ = 0x100 + 0x03; BaseVendorCapabilities base_vendor_capabilities; @@ -345,24 +341,19 @@ class Controller103Test : public ControllerTest { base_vendor_capabilities.max_filter_ = 0x10; base_vendor_capabilities.activity_energy_info_support_ = 0x01; vendor_capabilities_ = LeGetVendorCapabilitiesComplete103Builder::Create( - 1, - ErrorCode::SUCCESS, - base_vendor_capabilities, - feature_spec_version_, - 0x102, - /*extended_scan_support=*/1, - /*debug_logging_supported=*/1, - /*le_address_generation_offloading_support=*/0, - /*a2dp_source_offload_capability_mask=*/0x4, - /*bluetooth_quality_report_support=*/1, - kDynamicAudioBufferSupport, - std::make_unique()); + 1, ErrorCode::SUCCESS, base_vendor_capabilities, feature_spec_version_, 0x102, + /*extended_scan_support=*/1, + /*debug_logging_supported=*/1, + /*le_address_generation_offloading_support=*/0, + /*a2dp_source_offload_capability_mask=*/0x4, + /*bluetooth_quality_report_support=*/1, kDynamicAudioBufferSupport, + std::make_unique()); ControllerTest::SetUp(); } }; class Controller104Test : public ControllerTest { - protected: +protected: void SetUp() override { feature_spec_version_ = 0x100 + 0x04; BaseVendorCapabilities base_vendor_capabilities; @@ -374,19 +365,13 @@ class Controller104Test : public ControllerTest { base_vendor_capabilities.max_filter_ = 0x10; base_vendor_capabilities.activity_energy_info_support_ = 0x01; vendor_capabilities_ = LeGetVendorCapabilitiesComplete104Builder::Create( - 1, - ErrorCode::SUCCESS, - base_vendor_capabilities, - feature_spec_version_, - 0x102, - /*extended_scan_support=*/1, - /*debug_logging_supported=*/1, - /*le_address_generation_offloading_support=*/0, - /*a2dp_source_offload_capability_mask=*/0x4, - /*bluetooth_quality_report_support=*/1, - kDynamicAudioBufferSupport, - /*a2dp_offload_v2_support=*/1, - std::make_unique()); + 1, ErrorCode::SUCCESS, base_vendor_capabilities, feature_spec_version_, 0x102, + /*extended_scan_support=*/1, + /*debug_logging_supported=*/1, + /*le_address_generation_offloading_support=*/0, + /*a2dp_source_offload_capability_mask=*/0x4, + /*bluetooth_quality_report_support=*/1, kDynamicAudioBufferSupport, + /*a2dp_offload_v2_support=*/1, std::make_unique()); ControllerTest::SetUp(); } }; @@ -397,7 +382,8 @@ TEST_F(ControllerTest, read_controller_info) { ASSERT_EQ(controller_->GetAclPacketLength(), test_hci_layer_->acl_data_packet_length); ASSERT_EQ(controller_->GetNumAclPacketBuffers(), test_hci_layer_->total_num_acl_data_packets); ASSERT_EQ(controller_->GetScoPacketLength(), test_hci_layer_->synchronous_data_packet_length); - ASSERT_EQ(controller_->GetNumScoPacketBuffers(), test_hci_layer_->total_num_synchronous_data_packets); + ASSERT_EQ(controller_->GetNumScoPacketBuffers(), + test_hci_layer_->total_num_synchronous_data_packets); ASSERT_EQ(controller_->GetMacAddress(), Address::kAny); LocalVersionInformation local_version_information = controller_->GetLocalVersionInformation(); ASSERT_EQ(local_version_information.hci_version_, HciVersion::V_5_0); @@ -443,8 +429,10 @@ TEST_F(ControllerTest, send_set_event_filter_command) { controller_->SetEventFilterInquiryResultAllDevices(); auto packet = test_hci_layer_->GetCommand(OpCode::SET_EVENT_FILTER); auto set_event_filter_view1 = SetEventFilterView::Create(packet); - auto set_event_filter_inquiry_result_view1 = SetEventFilterInquiryResultView::Create(set_event_filter_view1); - auto command1 = SetEventFilterInquiryResultAllDevicesView::Create(set_event_filter_inquiry_result_view1); + auto set_event_filter_inquiry_result_view1 = + SetEventFilterInquiryResultView::Create(set_event_filter_view1); + auto command1 = + SetEventFilterInquiryResultAllDevicesView::Create(set_event_filter_inquiry_result_view1); ASSERT_TRUE(command1.IsValid()); ClassOfDevice class_of_device({0xab, 0xcd, 0xef}); @@ -452,17 +440,22 @@ TEST_F(ControllerTest, send_set_event_filter_command) { controller_->SetEventFilterInquiryResultClassOfDevice(class_of_device, class_of_device_mask); packet = test_hci_layer_->GetCommand(OpCode::SET_EVENT_FILTER); auto set_event_filter_view2 = SetEventFilterView::Create(packet); - auto set_event_filter_inquiry_result_view2 = SetEventFilterInquiryResultView::Create(set_event_filter_view2); - auto command2 = SetEventFilterInquiryResultClassOfDeviceView::Create(set_event_filter_inquiry_result_view2); + auto set_event_filter_inquiry_result_view2 = + SetEventFilterInquiryResultView::Create(set_event_filter_view2); + auto command2 = SetEventFilterInquiryResultClassOfDeviceView::Create( + set_event_filter_inquiry_result_view2); ASSERT_TRUE(command2.IsValid()); ASSERT_EQ(command2.GetClassOfDevice(), class_of_device); Address bdaddr({0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc}); - controller_->SetEventFilterConnectionSetupAddress(bdaddr, AutoAcceptFlag::AUTO_ACCEPT_ON_ROLE_SWITCH_ENABLED); + controller_->SetEventFilterConnectionSetupAddress( + bdaddr, AutoAcceptFlag::AUTO_ACCEPT_ON_ROLE_SWITCH_ENABLED); packet = test_hci_layer_->GetCommand(OpCode::SET_EVENT_FILTER); auto set_event_filter_view3 = SetEventFilterView::Create(packet); - auto set_event_filter_connection_setup_view = SetEventFilterConnectionSetupView::Create(set_event_filter_view3); - auto command3 = SetEventFilterConnectionSetupAddressView::Create(set_event_filter_connection_setup_view); + auto set_event_filter_connection_setup_view = + SetEventFilterConnectionSetupView::Create(set_event_filter_view3); + auto command3 = + SetEventFilterConnectionSetupAddressView::Create(set_event_filter_connection_setup_view); ASSERT_TRUE(command3.IsValid()); ASSERT_EQ(command3.GetAddress(), bdaddr); } @@ -629,9 +622,7 @@ TEST_F(ControllerTest, aclCreditCallbackListenerUnregistered) { std::promise le_rand_set; -void le_rand_callback(uint64_t random) { - le_rand_set.set_value(random); -} +void le_rand_callback(uint64_t random) { le_rand_set.set_value(random); } TEST_F(ControllerTest, leRandTest) { le_rand_set = std::promise(); diff --git a/system/gd/hci/controller_unittest.cc b/system/gd/hci/controller_unittest.cc index f5083f6d581..6ab8d4d68b3 100644 --- a/system/gd/hci/controller_unittest.cc +++ b/system/gd/hci/controller_unittest.cc @@ -22,7 +22,7 @@ namespace bluetooth { namespace hci { class ControllerUnitTest : public ::testing::Test { - protected: +protected: void SetUp() override {} void TearDown() override {} @@ -35,24 +35,22 @@ TEST_F(ControllerUnitTest, testLeEventMask) { // Update the function and this test when adding new bits. ASSERT_TRUE(Controller::kLeEventMask53 > Controller::kDefaultLeEventMask); - ASSERT_EQ( - Controller::MaskLeEventMask(version.hci_version_, Controller::kDefaultLeEventMask), - Controller::kDefaultLeEventMask); - ASSERT_LE( - Controller::MaskLeEventMask(version.hci_version_, Controller::kDefaultLeEventMask), - Controller::kLeEventMask53); + ASSERT_EQ(Controller::MaskLeEventMask(version.hci_version_, Controller::kDefaultLeEventMask), + Controller::kDefaultLeEventMask); + ASSERT_LE(Controller::MaskLeEventMask(version.hci_version_, Controller::kDefaultLeEventMask), + Controller::kLeEventMask53); version.hci_version_ = HciVersion::V_5_2; - ASSERT_LE( - Controller::MaskLeEventMask(version.hci_version_, Controller::kDefaultLeEventMask), Controller::kLeEventMask52); + ASSERT_LE(Controller::MaskLeEventMask(version.hci_version_, Controller::kDefaultLeEventMask), + Controller::kLeEventMask52); version.hci_version_ = HciVersion::V_5_1; - ASSERT_LE( - Controller::MaskLeEventMask(version.hci_version_, Controller::kDefaultLeEventMask), Controller::kLeEventMask51); + ASSERT_LE(Controller::MaskLeEventMask(version.hci_version_, Controller::kDefaultLeEventMask), + Controller::kLeEventMask51); version.hci_version_ = HciVersion::V_4_2; - ASSERT_LE( - Controller::MaskLeEventMask(version.hci_version_, Controller::kDefaultLeEventMask), Controller::kLeEventMask42); + ASSERT_LE(Controller::MaskLeEventMask(version.hci_version_, Controller::kDefaultLeEventMask), + Controller::kLeEventMask42); version.hci_version_ = HciVersion::V_4_1; - ASSERT_LE( - Controller::MaskLeEventMask(version.hci_version_, Controller::kDefaultLeEventMask), Controller::kLeEventMask41); + ASSERT_LE(Controller::MaskLeEventMask(version.hci_version_, Controller::kDefaultLeEventMask), + Controller::kLeEventMask41); } } // namespace hci diff --git a/system/gd/hci/distance_measurement_interface.h b/system/gd/hci/distance_measurement_interface.h index 91d6ef7bbf0..9b6e7727c39 100644 --- a/system/gd/hci/distance_measurement_interface.h +++ b/system/gd/hci/distance_measurement_interface.h @@ -23,14 +23,14 @@ namespace bluetooth { namespace hci { constexpr hci::SubeventCode DistanceMeasurementEvents[] = { - hci::SubeventCode::LE_CS_TEST_END_COMPLETE, - hci::SubeventCode::LE_CS_SUBEVENT_RESULT_CONTINUE, - hci::SubeventCode::LE_CS_SUBEVENT_RESULT, - hci::SubeventCode::LE_CS_PROCEDURE_ENABLE_COMPLETE, - hci::SubeventCode::LE_CS_CONFIG_COMPLETE, - hci::SubeventCode::LE_CS_SECURITY_ENABLE_COMPLETE, - hci::SubeventCode::LE_CS_READ_REMOTE_FAE_TABLE_COMPLETE, - hci::SubeventCode::LE_CS_READ_REMOTE_SUPPORTED_CAPABILITIES_COMPLETE, + hci::SubeventCode::LE_CS_TEST_END_COMPLETE, + hci::SubeventCode::LE_CS_SUBEVENT_RESULT_CONTINUE, + hci::SubeventCode::LE_CS_SUBEVENT_RESULT, + hci::SubeventCode::LE_CS_PROCEDURE_ENABLE_COMPLETE, + hci::SubeventCode::LE_CS_CONFIG_COMPLETE, + hci::SubeventCode::LE_CS_SECURITY_ENABLE_COMPLETE, + hci::SubeventCode::LE_CS_READ_REMOTE_FAE_TABLE_COMPLETE, + hci::SubeventCode::LE_CS_READ_REMOTE_SUPPORTED_CAPABILITIES_COMPLETE, }; typedef CommandInterface DistanceMeasurementInterface; diff --git a/system/gd/hci/distance_measurement_manager.cc b/system/gd/hci/distance_measurement_manager.cc index 8f6384c6529..1e65ed2c2e8 100644 --- a/system/gd/hci/distance_measurement_manager.cc +++ b/system/gd/hci/distance_measurement_manager.cc @@ -43,7 +43,7 @@ namespace bluetooth { namespace hci { const ModuleFactory DistanceMeasurementManager::Factory = - ModuleFactory([]() { return new DistanceMeasurementManager(); }); + ModuleFactory([]() { return new DistanceMeasurementManager(); }); static constexpr uint16_t kIllegalConnectionHandle = 0xffff; static constexpr uint8_t kTxPowerNotAvailable = 0xfe; static constexpr int8_t kRSSIDropOffAt1M = 41; @@ -54,7 +54,7 @@ static constexpr uint8_t kMinMainModeSteps = 0x02; static constexpr uint8_t kMaxMainModeSteps = 0x05; static constexpr uint8_t kMainModeRepetition = 0x00; // No repetition static constexpr uint8_t kMode0Steps = - 0x03; // Maximum number of mode-0 steps to increase success subevent rate + 0x03; // Maximum number of mode-0 steps to increase success subevent rate static constexpr uint8_t kChannelMapRepetition = 0x01; // No repetition static constexpr uint8_t kCh3cJump = 0x03; // Skip 3 Channels static constexpr uint16_t kMaxProcedureLen = 0x4E20; // 12.5s @@ -71,11 +71,8 @@ static constexpr uint16_t kRangingCounterMask = 0x0FFF; struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { struct CsProcedureData { - CsProcedureData( - uint16_t procedure_counter, - uint8_t num_antenna_paths, - uint8_t configuration_id, - uint8_t selected_tx_power) + CsProcedureData(uint16_t procedure_counter, uint8_t num_antenna_paths, uint8_t configuration_id, + uint8_t selected_tx_power) : counter(procedure_counter), num_antenna_paths(num_antenna_paths) { local_status = CsProcedureDoneStatus::PARTIAL_RESULTS; remote_status = CsProcedureDoneStatus::PARTIAL_RESULTS; @@ -136,24 +133,22 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { }; void OnOpened( - uint16_t connection_handle, - const std::vector& vendor_specific_reply) { - log::info( - "connection_handle:0x{:04x}, vendor_specific_reply size:{}", - connection_handle, - vendor_specific_reply.size()); + uint16_t connection_handle, + const std::vector& vendor_specific_reply) { + log::info("connection_handle:0x{:04x}, vendor_specific_reply size:{}", connection_handle, + vendor_specific_reply.size()); if (cs_trackers_.find(connection_handle) == cs_trackers_.end()) { log::error("Can't find CS tracker for connection_handle {}", connection_handle); distance_measurement_callbacks_->OnDistanceMeasurementStartFail( - cs_trackers_[connection_handle].address, REASON_INTERNAL_ERROR, METHOD_CS); + cs_trackers_[connection_handle].address, REASON_INTERNAL_ERROR, METHOD_CS); return; } auto& tracker = cs_trackers_[connection_handle]; if (!vendor_specific_reply.empty()) { // Send reply to remote - distance_measurement_callbacks_->OnVendorSpecificReply( - tracker.address, vendor_specific_reply); + distance_measurement_callbacks_->OnVendorSpecificReply(tracker.address, + vendor_specific_reply); return; } @@ -163,7 +158,7 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { void OnOpenFailed(uint16_t connection_handle) { log::info("connection_handle:0x{:04x}", connection_handle); distance_measurement_callbacks_->OnDistanceMeasurementStartFail( - cs_trackers_[connection_handle].address, REASON_INTERNAL_ERROR, METHOD_CS); + cs_trackers_[connection_handle].address, REASON_INTERNAL_ERROR, METHOD_CS); } void OnHandleVendorSpecificReplyComplete(uint16_t connection_handle, bool success) { @@ -171,11 +166,11 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { if (cs_trackers_.find(connection_handle) == cs_trackers_.end()) { log::error("Can't find CS tracker for connection_handle {}", connection_handle); distance_measurement_callbacks_->OnDistanceMeasurementStartFail( - cs_trackers_[connection_handle].address, REASON_INTERNAL_ERROR, METHOD_CS); + cs_trackers_[connection_handle].address, REASON_INTERNAL_ERROR, METHOD_CS); return; } distance_measurement_callbacks_->OnHandleVendorSpecificReplyComplete( - cs_trackers_[connection_handle].address, success); + cs_trackers_[connection_handle].address, success); } void OnResult(uint16_t connection_handle, const bluetooth::hal::RangingResult& ranging_result) { @@ -183,51 +178,37 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { log::warn("Can't find CS tracker for connection_handle {}", connection_handle); return; } - log::debug( - "address {}, resultMeters {}", - cs_trackers_[connection_handle].address, - ranging_result.result_meters_); + log::debug("address {}, resultMeters {}", cs_trackers_[connection_handle].address, + ranging_result.result_meters_); distance_measurement_callbacks_->OnDistanceMeasurementResult( - cs_trackers_[connection_handle].address, - ranging_result.result_meters_ * 100, - 0.0, - -1, - -1, - -1, - -1, - DistanceMeasurementMethod::METHOD_CS); + cs_trackers_[connection_handle].address, ranging_result.result_meters_ * 100, 0.0, -1, + -1, -1, -1, DistanceMeasurementMethod::METHOD_CS); } ~impl() {} - void start( - os::Handler* handler, - hal::RangingHal* ranging_hal, - hci::HciLayer* hci_layer, - hci::AclManager* acl_manager) { + void start(os::Handler* handler, hal::RangingHal* ranging_hal, hci::HciLayer* hci_layer, + hci::AclManager* acl_manager) { handler_ = handler; ranging_hal_ = ranging_hal; hci_layer_ = hci_layer; acl_manager_ = acl_manager; - hci_layer_->RegisterLeEventHandler( - hci::SubeventCode::TRANSMIT_POWER_REPORTING, - handler_->BindOn(this, &impl::on_transmit_power_reporting)); + hci_layer_->RegisterLeEventHandler(hci::SubeventCode::TRANSMIT_POWER_REPORTING, + handler_->BindOn(this, &impl::on_transmit_power_reporting)); if (!com::android::bluetooth::flags::channel_sounding_in_stack()) { log::info("IS_FLAG_ENABLED channel_sounding_in_stack: false"); return; } distance_measurement_interface_ = hci_layer_->GetDistanceMeasurementInterface( - handler_->BindOn(this, &DistanceMeasurementManager::impl::handle_event)); + handler_->BindOn(this, &DistanceMeasurementManager::impl::handle_event)); distance_measurement_interface_->EnqueueCommand( - LeCsReadLocalSupportedCapabilitiesBuilder::Create(), - handler_->BindOnceOn(this, &impl::on_cs_read_local_supported_capabilities)); + LeCsReadLocalSupportedCapabilitiesBuilder::Create(), + handler_->BindOnceOn(this, &impl::on_cs_read_local_supported_capabilities)); if (ranging_hal_->IsBound()) { ranging_hal_->RegisterCallback(this); }; } - void stop() { - hci_layer_->UnregisterLeEventHandler(hci::SubeventCode::TRANSMIT_POWER_REPORTING); - } + void stop() { hci_layer_->UnregisterLeEventHandler(hci::SubeventCode::TRANSMIT_POWER_REPORTING); } void register_distance_measurement_callbacks(DistanceMeasurementCallbacks* callbacks) { distance_measurement_callbacks_ = callbacks; @@ -248,7 +229,7 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { if (connection_handle == kIllegalConnectionHandle) { log::warn("Can't find any LE connection for {}", address); distance_measurement_callbacks_->OnDistanceMeasurementStartFail( - address, REASON_NO_LE_CONNECTION, method); + address, REASON_NO_LE_CONNECTION, method); return; } @@ -262,10 +243,10 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { rssi_trackers[address].started = false; rssi_trackers[address].repeating_alarm = std::make_unique(handler_); hci_layer_->EnqueueCommand( - LeReadRemoteTransmitPowerLevelBuilder::Create( - acl_manager_->HACK_GetLeHandle(address), 0x01), - handler_->BindOnceOn( - this, &impl::on_read_remote_transmit_power_level_status, address)); + LeReadRemoteTransmitPowerLevelBuilder::Create( + acl_manager_->HACK_GetLeHandle(address), 0x01), + handler_->BindOnceOn(this, &impl::on_read_remote_transmit_power_level_status, + address)); } else { rssi_trackers[address].interval_ms = interval; } @@ -276,13 +257,13 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { } } - void start_distance_measurement_with_cs( - const Address& cs_remote_address, uint16_t connection_handle, uint16_t interval) { + void start_distance_measurement_with_cs(const Address& cs_remote_address, + uint16_t connection_handle, uint16_t interval) { log::info("connection_handle: {}, address: {}", connection_handle, cs_remote_address); if (!com::android::bluetooth::flags::channel_sounding_in_stack()) { log::error("Channel Sounding is not enabled"); distance_measurement_callbacks_->OnDistanceMeasurementStartFail( - cs_remote_address, REASON_INTERNAL_ERROR, METHOD_CS); + cs_remote_address, REASON_INTERNAL_ERROR, METHOD_CS); return; } @@ -298,7 +279,7 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { // TODO: Check ROLE via CS config. (b/304295768) cs_trackers_[connection_handle].role = CsRole::INITIATOR; cs_trackers_[connection_handle].repeating_alarm = - std::make_unique(handler_); + std::make_unique(handler_); } cs_trackers_[connection_handle].interval_ms = interval; cs_trackers_[connection_handle].waiting_for_start_callback = true; @@ -316,18 +297,14 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { send_le_cs_create_config(connection_handle); return; } - log::info( - "enable cs procedure regularly with interval: {} ms", - cs_trackers_[connection_handle].interval_ms); + log::info("enable cs procedure regularly with interval: {} ms", + cs_trackers_[connection_handle].interval_ms); cs_trackers_[connection_handle].repeating_alarm->Cancel(); send_le_cs_procedure_enable(connection_handle, Enable::ENABLED); cs_trackers_[connection_handle].repeating_alarm->Schedule( - common::Bind( - &impl::send_le_cs_procedure_enable, - common::Unretained(this), - connection_handle, - Enable::ENABLED), - std::chrono::milliseconds(cs_trackers_[connection_handle].interval_ms)); + common::Bind(&impl::send_le_cs_procedure_enable, common::Unretained(this), + connection_handle, Enable::ENABLED), + std::chrono::milliseconds(cs_trackers_[connection_handle].interval_ms)); } void stop_distance_measurement(const Address address, DistanceMeasurementMethod method) { @@ -339,9 +316,10 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { log::warn("Can't find rssi tracker for {}", address); } else { hci_layer_->EnqueueCommand( - LeSetTransmitPowerReportingEnableBuilder::Create( - rssi_trackers[address].handle, 0x00, 0x00), - handler_->BindOnce(check_complete)); + LeSetTransmitPowerReportingEnableBuilder::Create(rssi_trackers[address].handle, + 0x00, 0x00), + handler_->BindOnce( + check_complete)); rssi_trackers[address].repeating_alarm->Cancel(); rssi_trackers[address].repeating_alarm.reset(); rssi_trackers.erase(address); @@ -362,17 +340,13 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { } void handle_ras_connected_event( - const Address address, - uint16_t att_handle, - const std::vector vendor_specific_data) { + const Address address, uint16_t att_handle, + const std::vector vendor_specific_data) { uint16_t connection_handle = acl_manager_->HACK_GetLeHandle(address); log::info( - "address:{}, connection_handle 0x{:04x}, att_handle 0x{:04x}, size of " - "vendor_specific_data {}", - address, - connection_handle, - att_handle, - vendor_specific_data.size()); + "address:{}, connection_handle 0x{:04x}, att_handle 0x{:04x}, size of " + "vendor_specific_data {}", + address, connection_handle, att_handle, vendor_specific_data.size()); if (cs_trackers_.find(connection_handle) == cs_trackers_.end()) { log::warn("can't find tracker for 0x{:04x}", connection_handle); @@ -393,8 +367,8 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { } void handle_vendor_specific_reply( - const Address address, - const std::vector vendor_specific_reply) { + const Address address, + const std::vector vendor_specific_reply) { uint16_t connection_handle = acl_manager_->HACK_GetLeHandle(address); cs_trackers_[connection_handle].address = address; if (ranging_hal_->IsBound()) { @@ -405,18 +379,18 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { void handle_vendor_specific_reply_complete(const Address address, bool success) { uint16_t connection_handle = acl_manager_->HACK_GetLeHandle(address); - log::info( - "address:{}, connection_handle:0x{:04x}, success:{}", address, connection_handle, success); + log::info("address:{}, connection_handle:0x{:04x}, success:{}", address, connection_handle, + success); if (cs_trackers_.find(connection_handle) == cs_trackers_.end()) { log::warn("can't find tracker for 0x{:04x}", connection_handle); distance_measurement_callbacks_->OnDistanceMeasurementStartFail( - address, REASON_INTERNAL_ERROR, METHOD_CS); + address, REASON_INTERNAL_ERROR, METHOD_CS); return; } if (!success) { distance_measurement_callbacks_->OnDistanceMeasurementStartFail( - address, REASON_INTERNAL_ERROR, METHOD_CS); + address, REASON_INTERNAL_ERROR, METHOD_CS); return; } @@ -434,7 +408,7 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { log::warn("Can't find connection for {}", address); if (rssi_trackers.find(address) != rssi_trackers.end()) { distance_measurement_callbacks_->OnDistanceMeasurementStopped( - address, REASON_NO_LE_CONNECTION, METHOD_RSSI); + address, REASON_NO_LE_CONNECTION, METHOD_RSSI); rssi_trackers[address].repeating_alarm->Cancel(); rssi_trackers[address].repeating_alarm.reset(); rssi_trackers.erase(address); @@ -442,9 +416,8 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { return; } - hci_layer_->EnqueueCommand( - ReadRssiBuilder::Create(connection_handle), - handler_->BindOnceOn(this, &impl::on_read_rssi_complete, address)); + hci_layer_->EnqueueCommand(ReadRssiBuilder::Create(connection_handle), + handler_->BindOnceOn(this, &impl::on_read_rssi_complete, address)); } void handle_event(LeMetaEventView event) { @@ -472,7 +445,7 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { } break; case hci::SubeventCode::LE_CS_READ_REMOTE_SUPPORTED_CAPABILITIES_COMPLETE: { on_cs_read_remote_supported_capabilities_complete( - LeCsReadRemoteSupportedCapabilitiesCompleteView::Create(event)); + LeCsReadRemoteSupportedCapabilitiesCompleteView::Create(event)); } break; default: log::info("Unknown subevent {}", hci::SubeventCodeText(event.GetSubeventCode())); @@ -481,26 +454,23 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { void send_le_cs_read_remote_supported_capabilities(uint16_t connection_handle) { hci_layer_->EnqueueCommand( - LeCsReadRemoteSupportedCapabilitiesBuilder::Create(connection_handle), - handler_->BindOnce(check_status)); + LeCsReadRemoteSupportedCapabilitiesBuilder::Create(connection_handle), + handler_->BindOnce(check_status)); } void send_le_cs_security_enable(uint16_t connection_handle) { - hci_layer_->EnqueueCommand( - LeCsSecurityEnableBuilder::Create(connection_handle), - handler_->BindOnce(check_status)); + hci_layer_->EnqueueCommand(LeCsSecurityEnableBuilder::Create(connection_handle), + handler_->BindOnce(check_status)); } void send_le_cs_set_default_settings(uint16_t connection_handle) { uint8_t role_enable = (1 << (uint8_t)CsRole::INITIATOR) | 1 << ((uint8_t)CsRole::REFLECTOR); hci_layer_->EnqueueCommand( - LeCsSetDefaultSettingsBuilder::Create( - connection_handle, - role_enable, - kCsSyncAntennaSelection, - kCsMaxTxPower // max_tx_power - ), - handler_->BindOnceOn(this, &impl::on_cs_set_default_settings_complete)); + LeCsSetDefaultSettingsBuilder::Create(connection_handle, role_enable, + kCsSyncAntennaSelection, + kCsMaxTxPower // max_tx_power + ), + handler_->BindOnceOn(this, &impl::on_cs_set_default_settings_complete)); } void send_le_cs_create_config(uint16_t connection_handle) { @@ -509,45 +479,25 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { std::copy(channel_vector->begin(), channel_vector->end(), channel_map.begin()); std::reverse(channel_map.begin(), channel_map.end()); hci_layer_->EnqueueCommand( - LeCsCreateConfigBuilder::Create( - connection_handle, - kConfigId, - CsCreateContext::BOTH_LOCAL_AND_REMOTE_CONTROLLER, - CsMainModeType::MODE_2, - CsSubModeType::UNUSED, - kMinMainModeSteps, - kMaxMainModeSteps, - kMainModeRepetition, - kMode0Steps, - CsRole::INITIATOR, - CsConfigRttType::RTT_WITH_128_BIT_RANDOM_SEQUENCE, - CsSyncPhy::LE_1M_PHY, - channel_map, - kChannelMapRepetition, - CsChannelSelectionType::TYPE_3B, - CsCh3cShape::HAT_SHAPE, - kCh3cJump, - Enable::DISABLED), - handler_->BindOnce(check_status)); + LeCsCreateConfigBuilder::Create( + connection_handle, kConfigId, CsCreateContext::BOTH_LOCAL_AND_REMOTE_CONTROLLER, + CsMainModeType::MODE_2, CsSubModeType::UNUSED, kMinMainModeSteps, + kMaxMainModeSteps, kMainModeRepetition, kMode0Steps, CsRole::INITIATOR, + CsConfigRttType::RTT_WITH_128_BIT_RANDOM_SEQUENCE, CsSyncPhy::LE_1M_PHY, + channel_map, kChannelMapRepetition, CsChannelSelectionType::TYPE_3B, + CsCh3cShape::HAT_SHAPE, kCh3cJump, Enable::DISABLED), + handler_->BindOnce(check_status)); } void send_le_cs_set_procedure_parameters(uint16_t connection_handle) { CsPreferredPeerAntenna preferred_peer_antenna; hci_layer_->EnqueueCommand( - LeCsSetProcedureParametersBuilder::Create( - connection_handle, - kConfigId, - kMaxProcedureLen, - kMinProcedureInterval, - kMaxProcedureInterval, - kMaxProcedureCount, - kMinSubeventLen, - kMaxSubeventLen, - kToneAntennaConfigSelection, - CsPhy::LE_1M_PHY, - kTxPwrDelta, - preferred_peer_antenna), - handler_->BindOnceOn(this, &impl::on_cs_set_procedure_parameters)); + LeCsSetProcedureParametersBuilder::Create( + connection_handle, kConfigId, kMaxProcedureLen, kMinProcedureInterval, + kMaxProcedureInterval, kMaxProcedureCount, kMinSubeventLen, kMaxSubeventLen, + kToneAntennaConfigSelection, CsPhy::LE_1M_PHY, kTxPwrDelta, + preferred_peer_antenna), + handler_->BindOnceOn(this, &impl::on_cs_set_procedure_parameters)); } void send_le_cs_procedure_enable(uint16_t connection_handle, Enable enable) { @@ -561,15 +511,15 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { if (connection_handle_from_acl_manager == kIllegalConnectionHandle) { log::warn("Can't find connection for {}", address); distance_measurement_callbacks_->OnDistanceMeasurementStopped( - address, REASON_NO_LE_CONNECTION, METHOD_CS); + address, REASON_NO_LE_CONNECTION, METHOD_CS); cs_trackers_[connection_handle].repeating_alarm->Cancel(); cs_trackers_[connection_handle].repeating_alarm.reset(); cs_trackers_.erase(connection_handle); return; } hci_layer_->EnqueueCommand( - LeCsProcedureEnableBuilder::Create(connection_handle, kConfigId, enable), - handler_->BindOnce(check_status)); + LeCsProcedureEnableBuilder::Create(connection_handle, kConfigId, enable), + handler_->BindOnce(check_status)); } void on_cs_read_local_supported_capabilities(CommandCompleteView view) { @@ -579,23 +529,22 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { return; } else if (complete_view.GetStatus() != ErrorCode::SUCCESS) { std::string error_code = ErrorCodeText(complete_view.GetStatus()); - log::warn( - "Received LeCsReadLocalSupportedCapabilitiesComplete with error code {}", error_code); + log::warn("Received LeCsReadLocalSupportedCapabilitiesComplete with error code {}", + error_code); return; } cs_subfeature_supported_ = complete_view.GetOptionalSubfeaturesSupported(); } void on_cs_read_remote_supported_capabilities_complete( - LeCsReadRemoteSupportedCapabilitiesCompleteView event_view) { + LeCsReadRemoteSupportedCapabilitiesCompleteView event_view) { if (!event_view.IsValid()) { log::warn("Get invalid LeCsReadRemoteSupportedCapabilitiesCompleteView"); return; } else if (event_view.GetStatus() != ErrorCode::SUCCESS) { std::string error_code = ErrorCodeText(event_view.GetStatus()); - log::warn( - "Received LeCsReadRemoteSupportedCapabilitiesCompleteView with error code {}", - error_code); + log::warn("Received LeCsReadRemoteSupportedCapabilitiesCompleteView with error code {}", + error_code); return; } uint16_t connection_handle = event_view.GetConnectionHandle(); @@ -613,13 +562,11 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { cs_trackers_[connection_handle].remote_support_phase_based_ranging = true; } log::info( - "connection_handle:{}, num_antennas_supported:{}, max_antenna_paths_supported:{}, " - "roles_supported:{}, phase_based_ranging_supported: {}", - event_view.GetConnectionHandle(), - event_view.GetNumAntennasSupported(), - event_view.GetMaxAntennaPathsSupported(), - event_view.GetRolesSupported().ToString(), - event_view.GetOptionalSubfeaturesSupported().phase_based_ranging_); + "connection_handle:{}, num_antennas_supported:{}, max_antenna_paths_supported:{}, " + "roles_supported:{}, phase_based_ranging_supported: {}", + event_view.GetConnectionHandle(), event_view.GetNumAntennasSupported(), + event_view.GetMaxAntennaPathsSupported(), event_view.GetRolesSupported().ToString(), + event_view.GetOptionalSubfeaturesSupported().phase_based_ranging_); } void on_cs_set_default_settings_complete(CommandCompleteView view) { @@ -649,10 +596,8 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { return; } cs_trackers_[connection_handle].setup_complete = true; - log::info( - "Setup phase complete, connection_handle: {}, address: {}", - connection_handle, - cs_trackers_[connection_handle].address); + log::info("Setup phase complete, connection_handle: {}, address: {}", connection_handle, + cs_trackers_[connection_handle].address); if (cs_trackers_[connection_handle].role == CsRole::INITIATOR) { send_le_cs_create_config(connection_handle); } @@ -704,18 +649,14 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { } if (cs_trackers_[connection_handle].role == CsRole::INITIATOR) { - log::info( - "enable cs procedure regularly with interval: {} ms", - cs_trackers_[connection_handle].interval_ms); + log::info("enable cs procedure regularly with interval: {} ms", + cs_trackers_[connection_handle].interval_ms); cs_trackers_[connection_handle].repeating_alarm->Cancel(); send_le_cs_procedure_enable(connection_handle, Enable::ENABLED); cs_trackers_[connection_handle].repeating_alarm->Schedule( - common::Bind( - &impl::send_le_cs_procedure_enable, - common::Unretained(this), - connection_handle, - Enable::ENABLED), - std::chrono::milliseconds(cs_trackers_[connection_handle].interval_ms)); + common::Bind(&impl::send_le_cs_procedure_enable, common::Unretained(this), + connection_handle, Enable::ENABLED), + std::chrono::milliseconds(cs_trackers_[connection_handle].interval_ms)); } } @@ -729,7 +670,7 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { cs_trackers_[connection_handle].waiting_for_start_callback) { cs_trackers_[connection_handle].waiting_for_start_callback = false; distance_measurement_callbacks_->OnDistanceMeasurementStartFail( - cs_trackers_[connection_handle].address, REASON_INTERNAL_ERROR, METHOD_CS); + cs_trackers_[connection_handle].address, REASON_INTERNAL_ERROR, METHOD_CS); } return; } @@ -745,7 +686,7 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { if (cs_trackers_[connection_handle].waiting_for_start_callback) { cs_trackers_[connection_handle].waiting_for_start_callback = false; distance_measurement_callbacks_->OnDistanceMeasurementStarted( - cs_trackers_[connection_handle].address, METHOD_CS); + cs_trackers_[connection_handle].address, METHOD_CS); } } cs_delete_obsolete_data(event_view.GetConnectionHandle()); @@ -780,14 +721,12 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { log::warn("Can't find any tracker for {}", connection_handle); return; } - CsProcedureData* procedure_data = init_cs_procedure_data( - connection_handle, - cs_event_result.GetProcedureCounter(), - cs_event_result.GetNumAntennaPaths(), - true); + CsProcedureData* procedure_data = + init_cs_procedure_data(connection_handle, cs_event_result.GetProcedureCounter(), + cs_event_result.GetNumAntennaPaths(), true); if (cs_trackers_[connection_handle].role == CsRole::INITIATOR) { procedure_data->frequency_compensation.push_back( - cs_event_result.GetFrequencyCompensation()); + cs_event_result.GetFrequencyCompensation()); } // RAS log::debug("RAS Update subevent_header counter:{}", procedure_data->ras_subevent_counter_++); @@ -816,21 +755,18 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { uint16_t counter = cs_trackers_[connection_handle].local_counter; log::debug( - "Connection_handle {}, procedure_done_status: {}, subevent_done_status: {}, counter: {}", - connection_handle, - CsProcedureDoneStatusText(procedure_done_status), - CsSubeventDoneStatusText(subevent_done_status), - counter); + "Connection_handle {}, procedure_done_status: {}, subevent_done_status: {}, counter: " + "{}", + connection_handle, CsProcedureDoneStatusText(procedure_done_status), + CsSubeventDoneStatusText(subevent_done_status), counter); if (procedure_done_status == CsProcedureDoneStatus::ABORTED || subevent_done_status == CsSubeventDoneStatus::ABORTED) { log::warn( - "Received CS Subevent with procedure_abort_reason:{}, subevent_abort_reason:{}, " - "connection_handle:{}, counter:{}", - ProcedureAbortReasonText(procedure_abort_reason), - SubeventAbortReasonText(subevent_abort_reason), - connection_handle, - counter); + "Received CS Subevent with procedure_abort_reason:{}, subevent_abort_reason:{}, " + "connection_handle:{}, counter:{}", + ProcedureAbortReasonText(procedure_abort_reason), + SubeventAbortReasonText(subevent_abort_reason), connection_handle, counter); } CsProcedureData* procedure_data = get_procedure_data(connection_handle, counter); @@ -845,12 +781,12 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { // handle it when all corresponding remote data received. procedure_data->aborted = true; procedure_data->ras_subevent_header_.ranging_abort_reason_ = - static_cast(procedure_abort_reason); + static_cast(procedure_abort_reason); procedure_data->ras_subevent_header_.subevent_abort_reason_ = - static_cast(subevent_abort_reason); + static_cast(subevent_abort_reason); } - parse_cs_result_data( - result_data_structures, *procedure_data, cs_trackers_[connection_handle].role); + parse_cs_result_data(result_data_structures, *procedure_data, + cs_trackers_[connection_handle].role); // Update procedure status procedure_data->local_status = procedure_done_status; check_cs_procedure_complete(procedure_data, connection_handle); @@ -863,11 +799,11 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { // Send data to RAS server if (subevent_done_status != CsSubeventDoneStatus::PARTIAL_RESULTS) { procedure_data->ras_subevent_header_.ranging_done_status_ = - static_cast(procedure_done_status); + static_cast(procedure_done_status); procedure_data->ras_subevent_header_.subevent_done_status_ = - static_cast(subevent_done_status); - auto builder = RasSubeventBuilder::Create( - procedure_data->ras_subevent_header_, procedure_data->ras_subevent_data_); + static_cast(subevent_done_status); + auto builder = RasSubeventBuilder::Create(procedure_data->ras_subevent_header_, + procedure_data->ras_subevent_data_); auto subevent_raw = builder_to_bytes(std::move(builder)); append_vector(procedure_data->ras_raw_data_, subevent_raw); // erase buffer @@ -879,7 +815,7 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { void send_on_demand_data(Address address, CsProcedureData* procedure_data) { // Check is last segment or not. uint16_t unsent_data_size = - procedure_data->ras_raw_data_.size() - procedure_data->ras_raw_data_index_; + procedure_data->ras_raw_data_.size() - procedure_data->ras_raw_data_index_; if (procedure_data->local_status != CsProcedureDoneStatus::PARTIAL_RESULTS && unsent_data_size <= kMtuForRasData) { procedure_data->segmentation_header_.last_segment_ = 1; @@ -896,15 +832,13 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { procedure_data->ras_raw_data_index_ += copy_size; auto builder = - RangingDataSegmentBuilder::Create(procedure_data->segmentation_header_, subevent_data); + RangingDataSegmentBuilder::Create(procedure_data->segmentation_header_, subevent_data); auto segment_data = builder_to_bytes(std::move(builder)); log::debug("counter: {}, size:{}", procedure_data->counter, (uint16_t)segment_data.size()); distance_measurement_callbacks_->OnRasFragmentReady( - address, - procedure_data->counter, - procedure_data->segmentation_header_.last_segment_, - segment_data); + address, procedure_data->counter, procedure_data->segmentation_header_.last_segment_, + segment_data); procedure_data->segmentation_header_.first_segment_ = 0; procedure_data->segmentation_header_.rolling_segment_counter_++; @@ -919,11 +853,8 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { void handle_remote_data(const Address address, const std::vector raw_data) { uint16_t connection_handle = acl_manager_->HACK_GetLeHandle(address); - log::debug( - "address:{}, connection_handle 0x{:04x}, size:{}", - address.ToString(), - connection_handle, - raw_data.size()); + log::debug("address:{}, connection_handle 0x{:04x}, size:{}", address.ToString(), + connection_handle, raw_data.size()); if (cs_trackers_.find(connection_handle) == cs_trackers_.end()) { log::warn("can't find tracker for 0x{:04x}", connection_handle); @@ -939,10 +870,8 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { return; } - log::debug( - "Receive segment for segment counter {}, size {}", - segmentation_header.rolling_segment_counter_, - raw_data.size()); + log::debug("Receive segment for segment counter {}, size {}", + segmentation_header.rolling_segment_counter_, raw_data.size()); PacketView segment_data(std::make_shared>(raw_data)); if (segmentation_header.first_segment_) { @@ -955,7 +884,7 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { auto begin = segment.GetSegmentationHeader().size() + segment.GetRangingHeader().size(); tracker.segment_data_ = - PacketViewForRecombination(segment.GetLittleEndianSubview(begin, segment.size())); + PacketViewForRecombination(segment.GetLittleEndianSubview(begin, segment.size())); } else { auto segment = RangingDataSegmentView::Create(segment_data); if (!segment.IsValid()) { @@ -963,7 +892,7 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { return; } tracker.segment_data_.AppendPacketView( - segment.GetLittleEndianSubview(segmentation_header.size(), segment.size())); + segment.GetLittleEndianSubview(segmentation_header.size(), segment.size())); } if (segmentation_header.last_segment_) { @@ -971,13 +900,11 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { } } - void parse_ras_segments( - RangingHeader ranging_header, - PacketViewForRecombination& segment_data, - uint16_t connection_handle) { + void parse_ras_segments(RangingHeader ranging_header, PacketViewForRecombination& segment_data, + uint16_t connection_handle) { log::debug("Data size {}, Ranging_header {}", segment_data.size(), ranging_header.ToString()); auto procedure_data = - get_procedure_data_for_ras(connection_handle, ranging_header.ranging_counter_); + get_procedure_data_for_ras(connection_handle, ranging_header.ranging_counter_); if (procedure_data == nullptr) { return; } @@ -1028,8 +955,8 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { LeCsMode0InitatorData tone_data; after = LeCsMode0InitatorData::Parse(&tone_data, parse_index); if (after == parse_index) { - log::warn( - "Error invalid mode {} data, role:{}", step_mode.mode_type_, CsRoleText(role)); + log::warn("Error invalid mode {} data, role:{}", step_mode.mode_type_, + CsRoleText(role)); return; } parse_index = after; @@ -1037,8 +964,8 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { LeCsMode0ReflectorData tone_data; after = LeCsMode0ReflectorData::Parse(&tone_data, parse_index); if (after == parse_index) { - log::warn( - "Error invalid mode {} data, role:{}", step_mode.mode_type_, CsRoleText(role)); + log::warn("Error invalid mode {} data, role:{}", step_mode.mode_type_, + CsRoleText(role)); return; } } @@ -1050,24 +977,24 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { remaining_data_size = std::distance(parse_index, segment_data.end()); if (remaining_data_size < data_len) { log::warn( - "insufficient length for LeCsMode2Data, num_tone_data {}, remaining_data_size {}", - num_tone_data, - remaining_data_size); + "insufficient length for LeCsMode2Data, num_tone_data {}, " + "remaining_data_size {}", + num_tone_data, remaining_data_size); return; } std::vector vector_for_num_tone_data = {num_tone_data}; PacketView packet_view_for_num_tone_data( - std::make_shared>(vector_for_num_tone_data)); + std::make_shared>(vector_for_num_tone_data)); PacketViewForRecombination packet_bytes_view = - PacketViewForRecombination(packet_view_for_num_tone_data); + PacketViewForRecombination(packet_view_for_num_tone_data); auto subview_begin = std::distance(segment_data.begin(), parse_index); packet_bytes_view.AppendPacketView( - segment_data.GetLittleEndianSubview(subview_begin, subview_begin + data_len)); + segment_data.GetLittleEndianSubview(subview_begin, subview_begin + data_len)); LeCsMode2Data tone_data; after = LeCsMode2Data::Parse(&tone_data, packet_bytes_view.begin()); if (after == packet_bytes_view.begin()) { - log::warn( - "Error invalid mode {} data, role:{}", step_mode.mode_type_, CsRoleText(role)); + log::warn("Error invalid mode {} data, role:{}", step_mode.mode_type_, + CsRoleText(role)); return; } parse_index += data_len; @@ -1075,22 +1002,23 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { // Parse in ascending order of antenna position with tone extension data at the end for (uint8_t k = 0; k < num_tone_data; k++) { - uint8_t antenna_path = k == num_antenna_paths - ? num_antenna_paths - : cs_antenna_permutation_array_[permutation_index][k] - 1; + uint8_t antenna_path = + k == num_antenna_paths + ? num_antenna_paths + : cs_antenna_permutation_array_[permutation_index][k] - 1; double i_value = get_iq_value(tone_data.tone_data_[k].i_sample_); double q_value = get_iq_value(tone_data.tone_data_[k].q_sample_); uint8_t tone_quality_indicator = tone_data.tone_data_[k].tone_quality_indicator_; - log::verbose( - "antenna_path {}, {:f}, {:f}", (uint16_t)(antenna_path + 1), i_value, q_value); + log::verbose("antenna_path {}, {:f}, {:f}", (uint16_t)(antenna_path + 1), i_value, + q_value); if (role == CsRole::INITIATOR) { procedure_data->tone_pct_initiator[antenna_path].emplace_back(i_value, q_value); procedure_data->tone_quality_indicator_initiator[antenna_path].emplace_back( - tone_quality_indicator); + tone_quality_indicator); } else { procedure_data->tone_pct_reflector[antenna_path].emplace_back(i_value, q_value); procedure_data->tone_quality_indicator_reflector[antenna_path].emplace_back( - tone_quality_indicator); + tone_quality_indicator); } } } break; @@ -1106,11 +1034,8 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { check_cs_procedure_complete(procedure_data, connection_handle); } - CsProcedureData* init_cs_procedure_data( - uint16_t connection_handle, - uint16_t procedure_counter, - uint8_t num_antenna_paths, - bool local) { + CsProcedureData* init_cs_procedure_data(uint16_t connection_handle, uint16_t procedure_counter, + uint8_t num_antenna_paths, bool local) { // Update procedure count if (local) { cs_trackers_[connection_handle].local_counter = procedure_counter; @@ -1126,11 +1051,9 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { } } log::info("Create data for procedure_counter: {}", procedure_counter); - data_list.emplace_back( - procedure_counter, - num_antenna_paths, - cs_trackers_[connection_handle].config_id, - cs_trackers_[connection_handle].selected_tx_power); + data_list.emplace_back(procedure_counter, num_antenna_paths, + cs_trackers_[connection_handle].config_id, + cs_trackers_[connection_handle].selected_tx_power); // Append ranging header raw data std::vector ranging_header_raw = {}; @@ -1162,14 +1085,14 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { } } if (procedure_data == nullptr) { - log::warn( - "Can't find data for connection_handle:{}, counter: {}", connection_handle, counter); + log::warn("Can't find data for connection_handle:{}, counter: {}", connection_handle, + counter); } return procedure_data; } - CsProcedureData* get_procedure_data_for_ras( - uint16_t connection_handle, uint16_t ranging_counter) { + CsProcedureData* get_procedure_data_for_ras(uint16_t connection_handle, + uint16_t ranging_counter) { std::vector& data_list = cs_trackers_[connection_handle].procedure_data_list; CsProcedureData* procedure_data = nullptr; for (uint8_t i = 0; i < data_list.size(); i++) { @@ -1179,10 +1102,8 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { } } if (procedure_data == nullptr) { - log::warn( - "Can't find data for connection_handle:{}, ranging_counter: {}", - connection_handle, - ranging_counter); + log::warn("Can't find data for connection_handle:{}, ranging_counter: {}", connection_handle, + ranging_counter); } return procedure_data; } @@ -1191,12 +1112,10 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { if (procedure_data->local_status == CsProcedureDoneStatus::ALL_RESULTS_COMPLETE && procedure_data->remote_status == CsProcedureDoneStatus::ALL_RESULTS_COMPLETE && !procedure_data->aborted) { - log::debug( - "Procedure complete counter:{} data size:{}, main_mode_type:{}, sub_mode_type:{}", - (uint16_t)procedure_data->counter, - (uint16_t)procedure_data->step_channel.size(), - (uint16_t)cs_trackers_[connection_handle].main_mode_type, - (uint16_t)cs_trackers_[connection_handle].sub_mode_type); + log::debug("Procedure complete counter:{} data size:{}, main_mode_type:{}, sub_mode_type:{}", + (uint16_t)procedure_data->counter, (uint16_t)procedure_data->step_channel.size(), + (uint16_t)cs_trackers_[connection_handle].main_mode_type, + (uint16_t)cs_trackers_[connection_handle].sub_mode_type); if (ranging_hal_->IsBound()) { // Use algorithm in the HAL @@ -1205,10 +1124,10 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { raw_data.step_channel_ = procedure_data->step_channel; raw_data.tone_pct_initiator_ = procedure_data->tone_pct_initiator; raw_data.tone_quality_indicator_initiator_ = - procedure_data->tone_quality_indicator_initiator; + procedure_data->tone_quality_indicator_initiator; raw_data.tone_pct_reflector_ = procedure_data->tone_pct_reflector; raw_data.tone_quality_indicator_reflector_ = - procedure_data->tone_quality_indicator_reflector; + procedure_data->tone_quality_indicator_reflector; ranging_hal_->WriteRawData(connection_handle, raw_data); return; } @@ -1226,21 +1145,16 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { } } - void parse_cs_result_data( - std::vector result_data_structures, - CsProcedureData& procedure_data, - CsRole role) { + void parse_cs_result_data(std::vector result_data_structures, + CsProcedureData& procedure_data, CsRole role) { uint8_t num_antenna_paths = procedure_data.num_antenna_paths; auto& ras_data = procedure_data.ras_subevent_data_; for (auto result_data_structure : result_data_structures) { uint16_t mode = result_data_structure.step_mode_; uint16_t step_channel = result_data_structure.step_channel_; uint16_t data_length = result_data_structure.step_data_.size(); - log::verbose( - "mode: {}, channel: {}, data_length: {}", - mode, - step_channel, - (uint16_t)result_data_structure.step_data_.size()); + log::verbose("mode: {}, channel: {}, data_length: {}", mode, step_channel, + (uint16_t)result_data_structure.step_data_.size()); ras_data.emplace_back(mode); if (data_length == 0) { ras_data.back() |= (1 << 7); // set step aborted @@ -1255,10 +1169,8 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { bytes->emplace_back(num_antenna_paths + 1); } bytes->reserve(bytes->size() + result_data_structure.step_data_.size()); - bytes->insert( - bytes->end(), - result_data_structure.step_data_.begin(), - result_data_structure.step_data_.end()); + bytes->insert(bytes->end(), result_data_structure.step_data_.begin(), + result_data_structure.step_data_.end()); Iterator iterator(bytes); switch (mode) { case 0: { @@ -1300,22 +1212,23 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { // Parse in ascending order of antenna position with tone extension data at the end uint16_t num_tone_data = num_antenna_paths + 1; for (uint16_t k = 0; k < num_tone_data; k++) { - uint8_t antenna_path = k == num_antenna_paths - ? num_antenna_paths - : cs_antenna_permutation_array_[permutation_index][k] - 1; + uint8_t antenna_path = + k == num_antenna_paths + ? num_antenna_paths + : cs_antenna_permutation_array_[permutation_index][k] - 1; double i_value = get_iq_value(tone_data[k].i_sample_); double q_value = get_iq_value(tone_data[k].q_sample_); uint8_t tone_quality_indicator = tone_data[k].tone_quality_indicator_; - log::verbose( - "antenna_path {}, {:f}, {:f}", (uint16_t)(antenna_path + 1), i_value, q_value); + log::verbose("antenna_path {}, {:f}, {:f}", (uint16_t)(antenna_path + 1), i_value, + q_value); if (role == CsRole::INITIATOR) { procedure_data.tone_pct_initiator[antenna_path].emplace_back(i_value, q_value); procedure_data.tone_quality_indicator_initiator[antenna_path].emplace_back( - tone_quality_indicator); + tone_quality_indicator); } else { procedure_data.tone_pct_reflector[antenna_path].emplace_back(i_value, q_value); procedure_data.tone_quality_indicator_reflector[antenna_path].emplace_back( - tone_quality_indicator); + tone_quality_indicator); } } } break; @@ -1370,13 +1283,13 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { if (!status_view.IsValid()) { log::warn("Invalid LeReadRemoteTransmitPowerLevelStatus event"); distance_measurement_callbacks_->OnDistanceMeasurementStartFail( - address, REASON_INTERNAL_ERROR, METHOD_RSSI); + address, REASON_INTERNAL_ERROR, METHOD_RSSI); rssi_trackers.erase(address); } else if (status_view.GetStatus() != ErrorCode::SUCCESS) { std::string error_code = ErrorCodeText(status_view.GetStatus()); log::warn("Received LeReadRemoteTransmitPowerLevelStatus with error code {}", error_code); distance_measurement_callbacks_->OnDistanceMeasurementStartFail( - address, REASON_INTERNAL_ERROR, METHOD_RSSI); + address, REASON_INTERNAL_ERROR, METHOD_RSSI); rssi_trackers.erase(address); } } @@ -1416,14 +1329,14 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { !rssi_trackers[address].started) { if (status == ErrorCode::SUCCESS) { hci_layer_->EnqueueCommand( - LeSetTransmitPowerReportingEnableBuilder::Create( - event_view.GetConnectionHandle(), 0x00, 0x01), - handler_->BindOnceOn( - this, &impl::on_set_transmit_power_reporting_enable_complete, address)); + LeSetTransmitPowerReportingEnableBuilder::Create(event_view.GetConnectionHandle(), + 0x00, 0x01), + handler_->BindOnceOn(this, &impl::on_set_transmit_power_reporting_enable_complete, + address)); } else { log::warn("Read remote transmit power level fail"); distance_measurement_callbacks_->OnDistanceMeasurementStartFail( - address, REASON_INTERNAL_ERROR, METHOD_RSSI); + address, REASON_INTERNAL_ERROR, METHOD_RSSI); rssi_trackers.erase(address); } } @@ -1434,15 +1347,15 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { if (!complete_view.IsValid()) { log::warn("Invalid LeSetTransmitPowerReportingEnableComplete event"); distance_measurement_callbacks_->OnDistanceMeasurementStartFail( - address, REASON_INTERNAL_ERROR, METHOD_RSSI); + address, REASON_INTERNAL_ERROR, METHOD_RSSI); rssi_trackers.erase(address); return; } else if (complete_view.GetStatus() != ErrorCode::SUCCESS) { std::string error_code = ErrorCodeText(complete_view.GetStatus()); - log::warn( - "Received LeSetTransmitPowerReportingEnableComplete with error code {}", error_code); + log::warn("Received LeSetTransmitPowerReportingEnableComplete with error code {}", + error_code); distance_measurement_callbacks_->OnDistanceMeasurementStartFail( - address, REASON_INTERNAL_ERROR, METHOD_RSSI); + address, REASON_INTERNAL_ERROR, METHOD_RSSI); rssi_trackers.erase(address); return; } @@ -1450,15 +1363,15 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { if (rssi_trackers.find(address) == rssi_trackers.end()) { log::warn("Can't find rssi tracker for {}", address); distance_measurement_callbacks_->OnDistanceMeasurementStartFail( - address, REASON_INTERNAL_ERROR, METHOD_RSSI); + address, REASON_INTERNAL_ERROR, METHOD_RSSI); rssi_trackers.erase(address); } else { log::info("Track rssi for address {}", address); rssi_trackers[address].started = true; distance_measurement_callbacks_->OnDistanceMeasurementStarted(address, METHOD_RSSI); rssi_trackers[address].repeating_alarm->Schedule( - common::Bind(&impl::send_read_rssi, common::Unretained(this), address), - std::chrono::milliseconds(rssi_trackers[address].interval_ms)); + common::Bind(&impl::send_read_rssi, common::Unretained(this), address), + std::chrono::milliseconds(rssi_trackers[address].interval_ms)); } } @@ -1477,14 +1390,8 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { double pow_value = (remote_tx_power - rssi - kRSSIDropOffAt1M) / 20.0; double distance = pow(10.0, pow_value); distance_measurement_callbacks_->OnDistanceMeasurementResult( - address, - distance * 100, - distance * 100, - -1, - -1, - -1, - -1, - DistanceMeasurementMethod::METHOD_RSSI); + address, distance * 100, distance * 100, -1, -1, -1, -1, + DistanceMeasurementMethod::METHOD_RSSI); } std::vector builder_to_bytes(std::unique_ptr> builder) { @@ -1541,15 +1448,13 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { CsOptionalSubfeaturesSupported cs_subfeature_supported_; // Antenna path permutations. See Channel Sounding CR_PR for the details. uint8_t cs_antenna_permutation_array_[24][4] = { - {1, 2, 3, 4}, {2, 1, 3, 4}, {1, 3, 2, 4}, {3, 1, 2, 4}, {3, 2, 1, 4}, {2, 3, 1, 4}, - {1, 2, 4, 3}, {2, 1, 4, 3}, {1, 4, 2, 3}, {4, 1, 2, 3}, {4, 2, 1, 3}, {2, 4, 1, 3}, - {1, 4, 3, 2}, {4, 1, 3, 2}, {1, 3, 4, 2}, {3, 1, 4, 2}, {3, 4, 1, 2}, {4, 3, 1, 2}, - {4, 2, 3, 1}, {2, 4, 3, 1}, {4, 3, 2, 1}, {3, 4, 2, 1}, {3, 2, 4, 1}, {2, 3, 4, 1}}; + {1, 2, 3, 4}, {2, 1, 3, 4}, {1, 3, 2, 4}, {3, 1, 2, 4}, {3, 2, 1, 4}, {2, 3, 1, 4}, + {1, 2, 4, 3}, {2, 1, 4, 3}, {1, 4, 2, 3}, {4, 1, 2, 3}, {4, 2, 1, 3}, {2, 4, 1, 3}, + {1, 4, 3, 2}, {4, 1, 3, 2}, {1, 3, 4, 2}, {3, 1, 4, 2}, {3, 4, 1, 2}, {4, 3, 1, 2}, + {4, 2, 3, 1}, {2, 4, 3, 1}, {4, 3, 2, 1}, {3, 4, 2, 1}, {3, 2, 4, 1}, {2, 3, 4, 1}}; }; -DistanceMeasurementManager::DistanceMeasurementManager() { - pimpl_ = std::make_unique(); -} +DistanceMeasurementManager::DistanceMeasurementManager() { pimpl_ = std::make_unique(); } DistanceMeasurementManager::~DistanceMeasurementManager() = default; @@ -1560,57 +1465,49 @@ void DistanceMeasurementManager::ListDependencies(ModuleList* list) const { } void DistanceMeasurementManager::Start() { - pimpl_->start( - GetHandler(), - GetDependency(), - GetDependency(), - GetDependency()); + pimpl_->start(GetHandler(), GetDependency(), GetDependency(), + GetDependency()); } -void DistanceMeasurementManager::Stop() { - pimpl_->stop(); -} +void DistanceMeasurementManager::Stop() { pimpl_->stop(); } -std::string DistanceMeasurementManager::ToString() const { - return "Distance Measurement Manager"; -} +std::string DistanceMeasurementManager::ToString() const { return "Distance Measurement Manager"; } void DistanceMeasurementManager::RegisterDistanceMeasurementCallbacks( - DistanceMeasurementCallbacks* callbacks) { + DistanceMeasurementCallbacks* callbacks) { CallOn(pimpl_.get(), &impl::register_distance_measurement_callbacks, callbacks); } -void DistanceMeasurementManager::StartDistanceMeasurement( - const Address& address, uint16_t interval, DistanceMeasurementMethod method) { +void DistanceMeasurementManager::StartDistanceMeasurement(const Address& address, uint16_t interval, + DistanceMeasurementMethod method) { CallOn(pimpl_.get(), &impl::start_distance_measurement, address, interval, method); } -void DistanceMeasurementManager::StopDistanceMeasurement( - const Address& address, DistanceMeasurementMethod method) { +void DistanceMeasurementManager::StopDistanceMeasurement(const Address& address, + DistanceMeasurementMethod method) { CallOn(pimpl_.get(), &impl::stop_distance_measurement, address, method); } void DistanceMeasurementManager::HandleRasConnectedEvent( - const Address& address, - uint16_t att_handle, - const std::vector& vendor_specific_data) { - CallOn( - pimpl_.get(), &impl::handle_ras_connected_event, address, att_handle, vendor_specific_data); + const Address& address, uint16_t att_handle, + const std::vector& vendor_specific_data) { + CallOn(pimpl_.get(), &impl::handle_ras_connected_event, address, att_handle, + vendor_specific_data); } void DistanceMeasurementManager::HandleVendorSpecificReply( - const Address& address, - const std::vector& vendor_specific_reply) { + const Address& address, + const std::vector& vendor_specific_reply) { CallOn(pimpl_.get(), &impl::handle_vendor_specific_reply, address, vendor_specific_reply); } -void DistanceMeasurementManager::HandleVendorSpecificReplyComplete( - const Address& address, bool success) { +void DistanceMeasurementManager::HandleVendorSpecificReplyComplete(const Address& address, + bool success) { CallOn(pimpl_.get(), &impl::handle_vendor_specific_reply_complete, address, success); } -void DistanceMeasurementManager::HandleRemoteData( - const Address& address, const std::vector& raw_data) { +void DistanceMeasurementManager::HandleRemoteData(const Address& address, + const std::vector& raw_data) { CallOn(pimpl_.get(), &impl::handle_remote_data, address, raw_data); } diff --git a/system/gd/hci/distance_measurement_manager.h b/system/gd/hci/distance_measurement_manager.h index 3456827d3c7..a7c91207b2f 100644 --- a/system/gd/hci/distance_measurement_manager.h +++ b/system/gd/hci/distance_measurement_manager.h @@ -49,57 +49,51 @@ struct DistanceMeasurementResult { }; class DistanceMeasurementCallbacks { - public: +public: virtual ~DistanceMeasurementCallbacks() = default; virtual void OnDistanceMeasurementStarted(Address address, DistanceMeasurementMethod method) = 0; - virtual void OnDistanceMeasurementStartFail( - Address address, DistanceMeasurementErrorCode reason, DistanceMeasurementMethod method) = 0; - virtual void OnDistanceMeasurementStopped( - Address address, DistanceMeasurementErrorCode reason, DistanceMeasurementMethod method) = 0; - virtual void OnDistanceMeasurementResult( - Address address, - uint32_t centimeter, - uint32_t error_centimeter, - int azimuth_angle, - int error_azimuth_angle, - int altitude_angle, - int error_altitude_angle, - DistanceMeasurementMethod method) = 0; - virtual void OnRasFragmentReady( - Address address, uint16_t procedure_counter, bool is_last, std::vector raw_data) = 0; + virtual void OnDistanceMeasurementStartFail(Address address, DistanceMeasurementErrorCode reason, + DistanceMeasurementMethod method) = 0; + virtual void OnDistanceMeasurementStopped(Address address, DistanceMeasurementErrorCode reason, + DistanceMeasurementMethod method) = 0; + virtual void OnDistanceMeasurementResult(Address address, uint32_t centimeter, + uint32_t error_centimeter, int azimuth_angle, + int error_azimuth_angle, int altitude_angle, + int error_altitude_angle, + DistanceMeasurementMethod method) = 0; + virtual void OnRasFragmentReady(Address address, uint16_t procedure_counter, bool is_last, + std::vector raw_data) = 0; virtual void OnVendorSpecificCharacteristics( - std::vector vendor_specific_characteristics) = 0; - virtual void OnVendorSpecificReply( - Address address, - std::vector - vendor_specific_characteristics) = 0; + std::vector vendor_specific_characteristics) = 0; + virtual void OnVendorSpecificReply(Address address, + std::vector + vendor_specific_characteristics) = 0; virtual void OnHandleVendorSpecificReplyComplete(Address address, bool success) = 0; }; class DistanceMeasurementManager : public bluetooth::Module { - public: +public: DistanceMeasurementManager(); ~DistanceMeasurementManager(); DistanceMeasurementManager(const DistanceMeasurementManager&) = delete; DistanceMeasurementManager& operator=(const DistanceMeasurementManager&) = delete; void RegisterDistanceMeasurementCallbacks(DistanceMeasurementCallbacks* callbacks); - void StartDistanceMeasurement( - const Address&, uint16_t interval, DistanceMeasurementMethod method); + void StartDistanceMeasurement(const Address&, uint16_t interval, + DistanceMeasurementMethod method); void StopDistanceMeasurement(const Address& address, DistanceMeasurementMethod method); void HandleRasConnectedEvent( - const Address& address, - uint16_t att_handle, - const std::vector& vendor_specific_data); + const Address& address, uint16_t att_handle, + const std::vector& vendor_specific_data); void HandleVendorSpecificReply( - const Address& address, - const std::vector& vendor_specific_reply); + const Address& address, + const std::vector& vendor_specific_reply); void HandleVendorSpecificReplyComplete(const Address& address, bool success); void HandleRemoteData(const Address& address, const std::vector& raw_data); static const ModuleFactory Factory; - protected: +protected: void ListDependencies(ModuleList* list) const override; void Start() override; @@ -108,7 +102,7 @@ class DistanceMeasurementManager : public bluetooth::Module { std::string ToString() const override; - private: +private: struct impl; std::unique_ptr pimpl_; }; diff --git a/system/gd/hci/distance_measurement_manager_mock.h b/system/gd/hci/distance_measurement_manager_mock.h index d30c9f85e43..6406dcdbc08 100644 --- a/system/gd/hci/distance_measurement_manager_mock.h +++ b/system/gd/hci/distance_measurement_manager_mock.h @@ -32,22 +32,16 @@ namespace testing { class MockDistanceMeasurementCallbacks : public DistanceMeasurementCallbacks { MOCK_METHOD(void, OnDistanceMeasurementStarted, (Address, DistanceMeasurementMethod)); - MOCK_METHOD( - void, - OnDistanceMeasurementStartFail, - (Address, DistanceMeasurementErrorCode, DistanceMeasurementMethod)); - MOCK_METHOD( - void, - OnDistanceMeasurementStopped, - (Address, DistanceMeasurementErrorCode, DistanceMeasurementMethod)); - MOCK_METHOD( - void, - OnDistanceMeasurementResult, - (Address, uint32_t, uint32_t, int, int, int, int, DistanceMeasurementMethod)); + MOCK_METHOD(void, OnDistanceMeasurementStartFail, + (Address, DistanceMeasurementErrorCode, DistanceMeasurementMethod)); + MOCK_METHOD(void, OnDistanceMeasurementStopped, + (Address, DistanceMeasurementErrorCode, DistanceMeasurementMethod)); + MOCK_METHOD(void, OnDistanceMeasurementResult, + (Address, uint32_t, uint32_t, int, int, int, int, DistanceMeasurementMethod)); }; class MockDistanceMeasurementManager : public DistanceMeasurementManager { - public: +public: MOCK_METHOD(void, RegisterDistanceMeasurementCallbacks, (DistanceMeasurementCallbacks*)); MOCK_METHOD(void, StartDistanceMeasurement, (Address, uint16_t, DistanceMeasurementMethod)); }; diff --git a/system/gd/hci/enum_helper.h b/system/gd/hci/enum_helper.h index adbc3c71e1e..b9b307d7265 100644 --- a/system/gd/hci/enum_helper.h +++ b/system/gd/hci/enum_helper.h @@ -28,7 +28,11 @@ namespace hci { enum DeviceType { UNKNOWN = 0, BR_EDR = 1, LE = 2, DUAL = 3 }; // Scan mode from legacy stack, which is different from hci::ScanEnable -enum LegacyScanMode { BT_SCAN_MODE_NONE = 0, BT_SCAN_MODE_CONNECTABLE = 1, BT_SCAN_MODE_CONNECTABLE_DISCOVERABLE = 2 }; +enum LegacyScanMode { + BT_SCAN_MODE_NONE = 0, + BT_SCAN_MODE_CONNECTABLE = 1, + BT_SCAN_MODE_CONNECTABLE_DISCOVERABLE = 2 +}; } // namespace hci @@ -74,14 +78,16 @@ std::optional FromLegacyConfigString(const std::string& str) { } // Must be defined in bluetooth namespace -template , int>::type = 0> +template , int>::type = 0> std::optional FromLegacyConfigString(const std::string& str) { auto raw_value = common::Int64FromString(str); if (!raw_value) { return std::nullopt; } if (*raw_value < static_cast(hci::LegacyScanMode::BT_SCAN_MODE_NONE) || - *raw_value > static_cast(hci::LegacyScanMode::BT_SCAN_MODE_CONNECTABLE_DISCOVERABLE)) { + *raw_value > + static_cast(hci::LegacyScanMode::BT_SCAN_MODE_CONNECTABLE_DISCOVERABLE)) { return std::nullopt; } return static_cast(*raw_value); diff --git a/system/gd/hci/facade/acl_manager_facade.cc b/system/gd/hci/facade/acl_manager_facade.cc index a502b3c0a79..a2c3e039261 100644 --- a/system/gd/hci/facade/acl_manager_facade.cc +++ b/system/gd/hci/facade/acl_manager_facade.cc @@ -49,7 +49,7 @@ using acl_manager::ConnectionManagementCallbacks; using namespace blueberry::facade::hci; class AclManagerFacadeService : public AclManagerFacade::Service, public ConnectionCallbacks { - public: +public: AclManagerFacadeService(AclManager* acl_manager, ::bluetooth::os::Handler* facade_handler) : acl_manager_(acl_manager), facade_handler_(facade_handler) { acl_manager_->RegisterCallbacks(this, facade_handler_); @@ -62,28 +62,26 @@ class AclManagerFacadeService : public AclManagerFacade::Service, public Connect } } - ::grpc::Status CreateConnection( - ::grpc::ServerContext* context, - const ConnectionMsg* request, - ::grpc::ServerWriter* writer) override { + ::grpc::Status CreateConnection(::grpc::ServerContext* context, const ConnectionMsg* request, + ::grpc::ServerWriter* writer) override { log::info("peer={}", request->address()); Address peer; - log::assert_that( - Address::FromString(request->address(), peer), - "assert failed: Address::FromString(request->address(), peer)"); + log::assert_that(Address::FromString(request->address(), peer), + "assert failed: Address::FromString(request->address(), peer)"); acl_manager_->CreateConnection(peer); if (per_connection_events_.size() > current_connection_request_) { - return ::grpc::Status(::grpc::StatusCode::RESOURCE_EXHAUSTED, "Only one outstanding request is supported"); + return ::grpc::Status(::grpc::StatusCode::RESOURCE_EXHAUSTED, + "Only one outstanding request is supported"); } - per_connection_events_.emplace_back(std::make_unique<::bluetooth::grpc::GrpcEventQueue>( - std::string("connection attempt ") + std::to_string(current_connection_request_))); + per_connection_events_.emplace_back( + std::make_unique<::bluetooth::grpc::GrpcEventQueue>( + std::string("connection attempt ") + + std::to_string(current_connection_request_))); return per_connection_events_[current_connection_request_]->RunLoop(context, writer); } - ::grpc::Status Disconnect( - ::grpc::ServerContext* /* context */, - const HandleMsg* request, - ::google::protobuf::Empty* /* response */) override { + ::grpc::Status Disconnect(::grpc::ServerContext* /* context */, const HandleMsg* request, + ::google::protobuf::Empty* /* response */) override { log::info("handle={}", request->handle()); std::unique_lock lock(acl_connections_mutex_); auto connection = acl_connections_.find(request->handle()); @@ -91,15 +89,15 @@ class AclManagerFacadeService : public AclManagerFacade::Service, public Connect log::error("Invalid handle"); return ::grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, "Invalid handle"); } else { - connection->second.connection_->Disconnect(DisconnectReason::REMOTE_USER_TERMINATED_CONNECTION); + connection->second.connection_->Disconnect( + DisconnectReason::REMOTE_USER_TERMINATED_CONNECTION); return ::grpc::Status::OK; } } - ::grpc::Status AuthenticationRequested( - ::grpc::ServerContext* /* context */, - const HandleMsg* request, - ::google::protobuf::Empty* /* response */) override { + ::grpc::Status AuthenticationRequested(::grpc::ServerContext* /* context */, + const HandleMsg* request, + ::google::protobuf::Empty* /* response */) override { log::info("handle={}", request->handle()); std::unique_lock lock(acl_connections_mutex_); auto connection = acl_connections_.find(request->handle()); @@ -110,7 +108,7 @@ class AclManagerFacadeService : public AclManagerFacade::Service, public Connect connection->second.connection_->AuthenticationRequested(); return ::grpc::Status::OK; } - }; + } #define GET_CONNECTION(view) \ std::map::iterator connection; \ @@ -125,14 +123,13 @@ class AclManagerFacadeService : public AclManagerFacade::Service, public Connect } \ } while (0) - ::grpc::Status ConnectionCommand( - ::grpc::ServerContext* /* context */, - const ConnectionCommandMsg* request, - ::google::protobuf::Empty* /* response */) override { + ::grpc::Status ConnectionCommand(::grpc::ServerContext* /* context */, + const ConnectionCommandMsg* request, + ::google::protobuf::Empty* /* response */) override { log::info("size={}", request->packet().size()); - auto command_view = - ConnectionManagementCommandView::Create(AclCommandView::Create(CommandView::Create(PacketView( - std::make_shared>(request->packet().begin(), request->packet().end()))))); + auto command_view = ConnectionManagementCommandView::Create(AclCommandView::Create( + CommandView::Create(PacketView(std::make_shared>( + request->packet().begin(), request->packet().end()))))); if (!command_view.IsValid()) { return ::grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, "Invalid command packet"); } @@ -174,14 +171,16 @@ class AclManagerFacadeService : public AclManagerFacade::Service, public Connect case OpCode::HOLD_MODE: { auto view = HoldModeView::Create(command_view); GET_CONNECTION(view); - connection->second.connection_->HoldMode(view.GetHoldModeMaxInterval(), view.GetHoldModeMinInterval()); + connection->second.connection_->HoldMode(view.GetHoldModeMaxInterval(), + view.GetHoldModeMinInterval()); return ::grpc::Status::OK; } case OpCode::SNIFF_MODE: { auto view = SniffModeView::Create(command_view); GET_CONNECTION(view); - connection->second.connection_->SniffMode( - view.GetSniffMaxInterval(), view.GetSniffMinInterval(), view.GetSniffAttempt(), view.GetSniffTimeout()); + connection->second.connection_->SniffMode(view.GetSniffMaxInterval(), + view.GetSniffMinInterval(), + view.GetSniffAttempt(), view.GetSniffTimeout()); return ::grpc::Status::OK; } case OpCode::EXIT_SNIFF_MODE: { @@ -219,7 +218,8 @@ class AclManagerFacadeService : public AclManagerFacade::Service, public Connect case OpCode::WRITE_LINK_SUPERVISION_TIMEOUT: { auto view = WriteLinkSupervisionTimeoutView::Create(command_view); GET_CONNECTION(view); - connection->second.connection_->WriteLinkSupervisionTimeout(view.GetLinkSupervisionTimeout()); + connection->second.connection_->WriteLinkSupervisionTimeout( + view.GetLinkSupervisionTimeout()); return ::grpc::Status::OK; } case OpCode::READ_FAILED_CONTACT_COUNTER: { @@ -275,23 +275,23 @@ class AclManagerFacadeService : public AclManagerFacade::Service, public Connect } #undef GET_CONNECTION - ::grpc::Status FetchIncomingConnection( - ::grpc::ServerContext* context, - const google::protobuf::Empty* /* request */, - ::grpc::ServerWriter* writer) override { + ::grpc::Status FetchIncomingConnection(::grpc::ServerContext* context, + const google::protobuf::Empty* /* request */, + ::grpc::ServerWriter* writer) override { log::info("wait for one incoming connection"); if (per_connection_events_.size() > current_connection_request_) { - return ::grpc::Status(::grpc::StatusCode::RESOURCE_EXHAUSTED, "Only one outstanding connection is supported"); + return ::grpc::Status(::grpc::StatusCode::RESOURCE_EXHAUSTED, + "Only one outstanding connection is supported"); } - per_connection_events_.emplace_back(std::make_unique<::bluetooth::grpc::GrpcEventQueue>( - std::string("incoming connection ") + std::to_string(current_connection_request_))); + per_connection_events_.emplace_back( + std::make_unique<::bluetooth::grpc::GrpcEventQueue>( + std::string("incoming connection ") + + std::to_string(current_connection_request_))); return per_connection_events_[current_connection_request_]->RunLoop(context, writer); } - ::grpc::Status SendAclData( - ::grpc::ServerContext* /* context */, - const AclData* request, - ::google::protobuf::Empty* /* response */) override { + ::grpc::Status SendAclData(::grpc::ServerContext* /* context */, const AclData* request, + ::google::protobuf::Empty* /* response */) override { log::info("handle={}, size={}", request->handle(), request->payload().size()); std::promise promise; auto future = promise.get_future(); @@ -303,12 +303,9 @@ class AclManagerFacadeService : public AclManagerFacade::Service, public Connect } // TODO: This is unsafe because connection may have gone connection->second.connection_->GetAclQueueEnd()->RegisterEnqueue( - facade_handler_, - common::Bind( - &AclManagerFacadeService::enqueue_packet, - common::Unretained(this), - common::Unretained(request), - common::Passed(std::move(promise)))); + facade_handler_, + common::Bind(&AclManagerFacadeService::enqueue_packet, common::Unretained(this), + common::Unretained(request), common::Passed(std::move(promise)))); auto status = future.wait_for(std::chrono::milliseconds(1000)); if (status != std::future_status::ready) { return ::grpc::Status(::grpc::StatusCode::RESOURCE_EXHAUSTED, "Can't send packet"); @@ -317,18 +314,19 @@ class AclManagerFacadeService : public AclManagerFacade::Service, public Connect return ::grpc::Status::OK; } - std::unique_ptr enqueue_packet(const AclData* request, std::promise promise) { + std::unique_ptr enqueue_packet(const AclData* request, + std::promise promise) { auto connection = acl_connections_.find(request->handle()); log::assert_that(connection != acl_connections_.end(), "handle {}", request->handle()); connection->second.connection_->GetAclQueueEnd()->UnregisterEnqueue(); - std::unique_ptr packet = - std::make_unique(std::vector(request->payload().begin(), request->payload().end())); + std::unique_ptr packet = std::make_unique( + std::vector(request->payload().begin(), request->payload().end())); promise.set_value(); return packet; } - ::grpc::Status FetchAclData( - ::grpc::ServerContext* context, const HandleMsg* request, ::grpc::ServerWriter* writer) override { + ::grpc::Status FetchAclData(::grpc::ServerContext* context, const HandleMsg* request, + ::grpc::ServerWriter* writer) override { log::info("handle={}", request->handle()); auto connection = acl_connections_.find(request->handle()); if (connection == acl_connections_.end()) { @@ -367,17 +365,17 @@ class AclManagerFacadeService : public AclManagerFacade::Service, public Connect uint16_t handle = to_handle(current_connection_request_); acl_connections_.erase(handle); acl_connections_.emplace( - std::piecewise_construct, - std::forward_as_tuple(handle), - std::forward_as_tuple(handle, shared_connection, per_connection_events_[current_connection_request_])); + std::piecewise_construct, std::forward_as_tuple(handle), + std::forward_as_tuple(handle, shared_connection, + per_connection_events_[current_connection_request_])); shared_connection->GetAclQueueEnd()->RegisterDequeue( - facade_handler_, - common::Bind(&AclManagerFacadeService::on_incoming_acl, common::Unretained(this), shared_connection, handle)); + facade_handler_, common::Bind(&AclManagerFacadeService::on_incoming_acl, + common::Unretained(this), shared_connection, handle)); auto callbacks = acl_connections_.find(handle)->second.GetCallbacks(); shared_connection->RegisterCallbacks(callbacks, facade_handler_); auto addr = shared_connection->GetAddress(); - std::unique_ptr builder = - ConnectionCompleteBuilder::Create(ErrorCode::SUCCESS, handle, addr, LinkType::ACL, Enable::DISABLED); + std::unique_ptr builder = ConnectionCompleteBuilder::Create( + ErrorCode::SUCCESS, handle, addr, LinkType::ACL, Enable::DISABLED); ConnectionEvent success; success.set_payload(builder_to_string(std::move(builder))); per_connection_events_[current_connection_request_]->OnIncomingEvent(success); @@ -391,7 +389,7 @@ class AclManagerFacadeService : public AclManagerFacade::Service, public Connect void OnConnectFail(Address address, ErrorCode reason, bool /* locally_initiated */) override { log::info("addr={}, reason={}", address, ErrorCodeText(reason)); std::unique_ptr builder = - ConnectionCompleteBuilder::Create(reason, 0, address, LinkType::ACL, Enable::DISABLED); + ConnectionCompleteBuilder::Create(reason, 0, address, LinkType::ACL, Enable::DISABLED); ConnectionEvent fail; fail.set_payload(builder_to_string(std::move(builder))); per_connection_events_[current_connection_request_]->OnIncomingEvent(fail); @@ -399,16 +397,14 @@ class AclManagerFacadeService : public AclManagerFacade::Service, public Connect } class Connection : public ConnectionManagementCallbacks { - public: - Connection( - uint16_t handle, - std::shared_ptr connection, - std::shared_ptr<::bluetooth::grpc::GrpcEventQueue> event_stream) - : handle_(handle), connection_(std::move(connection)), event_stream_(std::move(event_stream)) {} + public: + Connection(uint16_t handle, std::shared_ptr connection, + std::shared_ptr<::bluetooth::grpc::GrpcEventQueue> event_stream) + : handle_(handle), + connection_(std::move(connection)), + event_stream_(std::move(event_stream)) {} - ConnectionManagementCallbacks* GetCallbacks() { - return this; - } + ConnectionManagementCallbacks* GetCallbacks() { return this; } void OnCentralLinkKeyComplete(KeyFlag key_flag) override { log::info("key_flag:{}", KeyFlagText(key_flag)); @@ -436,69 +432,46 @@ class AclManagerFacadeService : public AclManagerFacade::Service, public Connect void OnChangeConnectionLinkKeyComplete() override { log::info("OnChangeConnectionLinkKeyComplete"); - }; + } void OnReadClockOffsetComplete(uint16_t clock_offset) override { log::info("OnReadClockOffsetComplete clock_offset:{}", clock_offset); - }; + } void OnModeChange(ErrorCode /* status */, Mode current_mode, uint16_t interval) override { log::info("OnModeChange Mode:{}, interval:{}", (uint8_t)current_mode, interval); - }; - - void OnSniffSubrating( - hci::ErrorCode /* hci_status */, - uint16_t maximum_transmit_latency, - uint16_t maximum_receive_latency, - uint16_t minimum_remote_timeout, - uint16_t minimum_local_timeout) override { - log::info( - "OnSniffSubrating maximum_transmit_latency:{}, maximum_receive_latency:{} " - "minimum_remote_timeout:{} minimum_local_timeout:{}", - maximum_transmit_latency, - maximum_receive_latency, - minimum_remote_timeout, - minimum_local_timeout); - } - - void OnQosSetupComplete( - ServiceType service_type, - uint32_t token_rate, - uint32_t peak_bandwidth, - uint32_t latency, - uint32_t delay_variation) override { + } + + void OnSniffSubrating(hci::ErrorCode /* hci_status */, uint16_t maximum_transmit_latency, + uint16_t maximum_receive_latency, uint16_t minimum_remote_timeout, + uint16_t minimum_local_timeout) override { log::info( - "OnQosSetupComplete service_type:{}, token_rate:{}, peak_bandwidth:{}, latency:{}, " - "delay_variation:{}", - (uint8_t)service_type, - token_rate, - peak_bandwidth, - latency, - delay_variation); - } - - void OnFlowSpecificationComplete( - FlowDirection flow_direction, - ServiceType service_type, - uint32_t token_rate, - uint32_t token_bucket_size, - uint32_t peak_bandwidth, - uint32_t access_latency) override { + "OnSniffSubrating maximum_transmit_latency:{}, maximum_receive_latency:{} " + "minimum_remote_timeout:{} minimum_local_timeout:{}", + maximum_transmit_latency, maximum_receive_latency, minimum_remote_timeout, + minimum_local_timeout); + } + + void OnQosSetupComplete(ServiceType service_type, uint32_t token_rate, uint32_t peak_bandwidth, + uint32_t latency, uint32_t delay_variation) override { log::info( - "OnFlowSpecificationComplete flow_direction:{}. service_type:{}, token_rate:{}, " - "token_bucket_size:{}, peak_bandwidth:{}, access_latency:{}", - (uint8_t)flow_direction, - (uint8_t)service_type, - token_rate, - token_bucket_size, - peak_bandwidth, - access_latency); + "OnQosSetupComplete service_type:{}, token_rate:{}, peak_bandwidth:{}, latency:{}, " + "delay_variation:{}", + (uint8_t)service_type, token_rate, peak_bandwidth, latency, delay_variation); } - void OnFlushOccurred() override { - log::info("OnFlushOccurred"); + void OnFlowSpecificationComplete(FlowDirection flow_direction, ServiceType service_type, + uint32_t token_rate, uint32_t token_bucket_size, + uint32_t peak_bandwidth, uint32_t access_latency) override { + log::info( + "OnFlowSpecificationComplete flow_direction:{}. service_type:{}, token_rate:{}, " + "token_bucket_size:{}, peak_bandwidth:{}, access_latency:{}", + (uint8_t)flow_direction, (uint8_t)service_type, token_rate, token_bucket_size, + peak_bandwidth, access_latency); } + void OnFlushOccurred() override { log::info("OnFlushOccurred"); } + void OnRoleDiscoveryComplete(Role current_role) override { log::info("OnRoleDiscoveryComplete current_role:{}", (uint8_t)current_role); } @@ -512,22 +485,21 @@ class AclManagerFacadeService : public AclManagerFacade::Service, public Connect } void OnReadLinkSupervisionTimeoutComplete(uint16_t link_supervision_timeout) override { - log::info( - "OnReadLinkSupervisionTimeoutComplete link_supervision_timeout:{}", - link_supervision_timeout); + log::info("OnReadLinkSupervisionTimeoutComplete link_supervision_timeout:{}", + link_supervision_timeout); } void OnReadFailedContactCounterComplete(uint16_t failed_contact_counter) override { - log::info( - "OnReadFailedContactCounterComplete failed_contact_counter:{}", failed_contact_counter); + log::info("OnReadFailedContactCounterComplete failed_contact_counter:{}", + failed_contact_counter); } void OnReadLinkQualityComplete(uint8_t link_quality) override { log::info("OnReadLinkQualityComplete link_quality:{}", link_quality); } - void OnReadAfhChannelMapComplete( - AfhMode afh_mode, std::array /* afh_channel_map */) override { + void OnReadAfhChannelMapComplete(AfhMode afh_mode, + std::array /* afh_channel_map */) override { log::info("OnReadAfhChannelMapComplete afh_mode:{}", (uint8_t)afh_mode); } @@ -542,35 +514,29 @@ class AclManagerFacadeService : public AclManagerFacade::Service, public Connect void OnDisconnection(ErrorCode reason) override { log::info("reason: {}", ErrorCodeText(reason)); std::unique_ptr builder = - DisconnectionCompleteBuilder::Create(ErrorCode::SUCCESS, handle_, reason); + DisconnectionCompleteBuilder::Create(ErrorCode::SUCCESS, handle_, reason); ConnectionEvent disconnection; disconnection.set_payload(builder_to_string(std::move(builder))); event_stream_->OnIncomingEvent(disconnection); } - void OnReadRemoteVersionInformationComplete( - hci::ErrorCode /* error_status */, - uint8_t lmp_version, - uint16_t manufacturer_name, - uint16_t sub_version) override { + void OnReadRemoteVersionInformationComplete(hci::ErrorCode /* error_status */, + uint8_t lmp_version, uint16_t manufacturer_name, + uint16_t sub_version) override { log::info( - "OnReadRemoteVersionInformationComplete lmp_version:{} manufacturer_name:{} " - "sub_version:{}", - lmp_version, - manufacturer_name, - sub_version); + "OnReadRemoteVersionInformationComplete lmp_version:{} manufacturer_name:{} " + "sub_version:{}", + lmp_version, manufacturer_name, sub_version); } void OnReadRemoteSupportedFeaturesComplete(uint64_t features) override { - log::info( - "OnReadRemoteSupportedFeaturesComplete features:0x{:x}", - static_cast(features)); + log::info("OnReadRemoteSupportedFeaturesComplete features:0x{:x}", + static_cast(features)); } - void OnReadRemoteExtendedFeaturesComplete( - uint8_t page_number, uint8_t max_page_number, uint64_t features) override { + void OnReadRemoteExtendedFeaturesComplete(uint8_t page_number, uint8_t max_page_number, + uint64_t features) override { log::info( - "OnReadRemoteExtendedFeaturesComplete page_number:{} max_page_number:{} features:0x{:x}", - page_number, - max_page_number, - static_cast(features)); + "OnReadRemoteExtendedFeaturesComplete page_number:{} max_page_number:{} " + "features:0x{:x}", + page_number, max_page_number, static_cast(features)); } uint16_t handle_; @@ -580,12 +546,13 @@ class AclManagerFacadeService : public AclManagerFacade::Service, public Connect std::to_string(handle_)}; }; - private: +private: AclManager* acl_manager_; ::bluetooth::os::Handler* facade_handler_; mutable std::mutex acl_connections_mutex_; std::map acl_connections_; - std::vector>> per_connection_events_; + std::vector>> + per_connection_events_; uint32_t current_connection_request_{0}; }; @@ -604,12 +571,10 @@ void AclManagerFacadeModule::Stop() { ::bluetooth::grpc::GrpcFacadeModule::Stop(); } -::grpc::Service* AclManagerFacadeModule::GetService() const { - return service_; -} +::grpc::Service* AclManagerFacadeModule::GetService() const { return service_; } const ModuleFactory AclManagerFacadeModule::Factory = - ::bluetooth::ModuleFactory([]() { return new AclManagerFacadeModule(); }); + ::bluetooth::ModuleFactory([]() { return new AclManagerFacadeModule(); }); } // namespace facade } // namespace hci diff --git a/system/gd/hci/facade/acl_manager_facade.h b/system/gd/hci/facade/acl_manager_facade.h index 6e153dee3bb..b55937db53a 100644 --- a/system/gd/hci/facade/acl_manager_facade.h +++ b/system/gd/hci/facade/acl_manager_facade.h @@ -28,7 +28,7 @@ namespace facade { class AclManagerFacadeService; class AclManagerFacadeModule : public ::bluetooth::grpc::GrpcFacadeModule { - public: +public: static const ModuleFactory Factory; void ListDependencies(ModuleList* list) const override; @@ -36,7 +36,7 @@ class AclManagerFacadeModule : public ::bluetooth::grpc::GrpcFacadeModule { void Stop() override; ::grpc::Service* GetService() const override; - private: +private: AclManagerFacadeService* service_; }; diff --git a/system/gd/hci/facade/controller_facade.cc b/system/gd/hci/facade/controller_facade.cc index ee075e6aaf8..ad8a4df217e 100644 --- a/system/gd/hci/facade/controller_facade.cc +++ b/system/gd/hci/facade/controller_facade.cc @@ -40,51 +40,45 @@ using namespace blueberry::facade::hci; using blueberry::facade::BluetoothAddress; class ControllerFacadeService : public ControllerFacade::Service { - public: - ControllerFacadeService(Controller* controller, ::bluetooth::os::Handler*) : controller_(controller) {} +public: + ControllerFacadeService(Controller* controller, ::bluetooth::os::Handler*) + : controller_(controller) {} - ::grpc::Status GetMacAddress( - ::grpc::ServerContext* /* context */, - const ::google::protobuf::Empty* /* request */, - BluetoothAddress* response) override { + ::grpc::Status GetMacAddress(::grpc::ServerContext* /* context */, + const ::google::protobuf::Empty* /* request */, + BluetoothAddress* response) override { Address local_address = controller_->GetMacAddress(); response->set_address(local_address.ToString()); return ::grpc::Status::OK; } - ::grpc::Status GetLocalName( - ::grpc::ServerContext* /* context */, - const ::google::protobuf::Empty* /* request */, - NameMsg* response) override { + ::grpc::Status GetLocalName(::grpc::ServerContext* /* context */, + const ::google::protobuf::Empty* /* request */, + NameMsg* response) override { std::string local_name = controller_->GetLocalName(); response->set_name(local_name); return ::grpc::Status::OK; } - ::grpc::Status WriteLocalName( - ::grpc::ServerContext* /* context */, - const NameMsg* request, - ::google::protobuf::Empty* /* response */) override { + ::grpc::Status WriteLocalName(::grpc::ServerContext* /* context */, const NameMsg* request, + ::google::protobuf::Empty* /* response */) override { controller_->WriteLocalName(request->name()); return ::grpc::Status::OK; } - ::grpc::Status IsSupportedCommand( - ::grpc::ServerContext* /* context */, - const OpCodeMsg* request, - SupportedMsg* response) override { + ::grpc::Status IsSupportedCommand(::grpc::ServerContext* /* context */, const OpCodeMsg* request, + SupportedMsg* response) override { bool ret = controller_->IsSupported(static_cast(request->op_code())); response->set_supported(ret); return ::grpc::Status::OK; } -#define SUPPORTED_API(name) \ - ::grpc::Status name( \ - ::grpc::ServerContext* /* context */, \ - const ::google::protobuf::Empty* /* request */, \ - SupportedMsg* response) override { \ - response->set_supported(controller_->name()); \ - return ::grpc::Status::OK; \ +#define SUPPORTED_API(name) \ + ::grpc::Status name(::grpc::ServerContext* /* context */, \ + const ::google::protobuf::Empty* /* request */, SupportedMsg* response) \ + override { \ + response->set_supported(controller_->name()); \ + return ::grpc::Status::OK; \ } SUPPORTED_API(SupportsSimplePairing) @@ -155,15 +149,14 @@ class ControllerFacadeService : public ControllerFacade::Service { SUPPORTED_API(SupportsBlePeriodicAdvertisingAdi) ::grpc::Status GetLeNumberOfSupportedAdvertisingSets( - ::grpc::ServerContext* /* context */, - const ::google::protobuf::Empty* /* request */, - SingleValueMsg* response) override { + ::grpc::ServerContext* /* context */, const ::google::protobuf::Empty* /* request */, + SingleValueMsg* response) override { uint8_t ret = controller_->GetLeNumberOfSupportedAdverisingSets(); response->set_value(ret); return ::grpc::Status::OK; } - private: +private: Controller* controller_; }; @@ -182,12 +175,10 @@ void ControllerFacadeModule::Stop() { ::bluetooth::grpc::GrpcFacadeModule::Stop(); } -::grpc::Service* ControllerFacadeModule::GetService() const { - return service_; -} +::grpc::Service* ControllerFacadeModule::GetService() const { return service_; } const ModuleFactory ControllerFacadeModule::Factory = - ::bluetooth::ModuleFactory([]() { return new ControllerFacadeModule(); }); + ::bluetooth::ModuleFactory([]() { return new ControllerFacadeModule(); }); } // namespace facade } // namespace hci diff --git a/system/gd/hci/facade/controller_facade.h b/system/gd/hci/facade/controller_facade.h index 7037f38b031..2017b107222 100644 --- a/system/gd/hci/facade/controller_facade.h +++ b/system/gd/hci/facade/controller_facade.h @@ -28,7 +28,7 @@ namespace facade { class ControllerFacadeService; class ControllerFacadeModule : public ::bluetooth::grpc::GrpcFacadeModule { - public: +public: static const ModuleFactory Factory; void ListDependencies(ModuleList* list) const override; @@ -36,7 +36,7 @@ class ControllerFacadeModule : public ::bluetooth::grpc::GrpcFacadeModule { void Stop() override; ::grpc::Service* GetService() const override; - private: +private: ControllerFacadeService* service_; }; diff --git a/system/gd/hci/facade/facade.cc b/system/gd/hci/facade/facade.cc index 45a4974e795..7d9d97eaf8f 100644 --- a/system/gd/hci/facade/facade.cc +++ b/system/gd/hci/facade/facade.cc @@ -38,8 +38,9 @@ namespace facade { using namespace blueberry::facade::hci; class HciFacadeService : public HciFacade::Service { - public: - HciFacadeService(HciLayer* hci_layer, Controller* controller, ::bluetooth::os::Handler* facade_handler) +public: + HciFacadeService(HciLayer* hci_layer, Controller* controller, + ::bluetooth::os::Handler* facade_handler) : hci_layer_(hci_layer), controller_(controller), facade_handler_(facade_handler) {} virtual ~HciFacadeService() { @@ -55,120 +56,114 @@ class HciFacadeService : public HciFacade::Service { } class TestCommandBuilder : public CommandBuilder { - public: - explicit TestCommandBuilder(std::vector bytes) : CommandBuilder(OpCode::NONE), bytes_(std::move(bytes)) {} - size_t size() const override { - return bytes_.size(); - } + public: + explicit TestCommandBuilder(std::vector bytes) + : CommandBuilder(OpCode::NONE), bytes_(std::move(bytes)) {} + size_t size() const override { return bytes_.size(); } void Serialize(BitInserter& bit_inserter) const override { for (auto&& b : bytes_) { bit_inserter.insert_byte(b); } } - private: + private: std::vector bytes_; }; - ::grpc::Status SendCommand( - ::grpc::ServerContext* /* context */, - const ::blueberry::facade::Data* command, - ::google::protobuf::Empty* /* response */) override { + ::grpc::Status SendCommand(::grpc::ServerContext* /* context */, + const ::blueberry::facade::Data* command, + ::google::protobuf::Empty* /* response */) override { auto payload = std::vector(command->payload().begin(), command->payload().end()); auto packet = std::make_unique(payload); auto opcode = static_cast(payload.at(1) << 8 | payload.at(0)); if (Checker::IsCommandStatusOpcode(opcode)) { - hci_layer_->EnqueueCommand(std::move(packet), facade_handler_->BindOnceOn(this, &HciFacadeService::on_status)); + hci_layer_->EnqueueCommand(std::move(packet), + facade_handler_->BindOnceOn(this, &HciFacadeService::on_status)); } else { - hci_layer_->EnqueueCommand(std::move(packet), facade_handler_->BindOnceOn(this, &HciFacadeService::on_complete)); + hci_layer_->EnqueueCommand(std::move(packet), + facade_handler_->BindOnceOn(this, &HciFacadeService::on_complete)); } return ::grpc::Status::OK; } - ::grpc::Status RequestEvent( - ::grpc::ServerContext* /* context */, - const ::blueberry::facade::hci::EventRequest* event, - ::google::protobuf::Empty* /* response */) override { - hci_layer_->RegisterEventHandler( - static_cast(event->code()), facade_handler_->BindOn(this, &HciFacadeService::on_event)); + ::grpc::Status RequestEvent(::grpc::ServerContext* /* context */, + const ::blueberry::facade::hci::EventRequest* event, + ::google::protobuf::Empty* /* response */) override { + hci_layer_->RegisterEventHandler(static_cast(event->code()), + facade_handler_->BindOn(this, &HciFacadeService::on_event)); return ::grpc::Status::OK; } - ::grpc::Status RequestLeSubevent( - ::grpc::ServerContext* /* context */, - const ::blueberry::facade::hci::EventRequest* event, - ::google::protobuf::Empty* /* response */) override { + ::grpc::Status RequestLeSubevent(::grpc::ServerContext* /* context */, + const ::blueberry::facade::hci::EventRequest* event, + ::google::protobuf::Empty* /* response */) override { hci_layer_->RegisterLeEventHandler( - static_cast(event->code()), facade_handler_->BindOn(this, &HciFacadeService::on_le_subevent)); + static_cast(event->code()), + facade_handler_->BindOn(this, &HciFacadeService::on_le_subevent)); return ::grpc::Status::OK; } - ::grpc::Status StreamEvents( - ::grpc::ServerContext* context, - const ::google::protobuf::Empty* /* request */, - ::grpc::ServerWriter<::blueberry::facade::Data>* writer) override { + ::grpc::Status StreamEvents(::grpc::ServerContext* context, + const ::google::protobuf::Empty* /* request */, + ::grpc::ServerWriter<::blueberry::facade::Data>* writer) override { return pending_events_.RunLoop(context, writer); - }; + } ::grpc::Status StreamLeSubevents( - ::grpc::ServerContext* context, - const ::google::protobuf::Empty* /* request */, - ::grpc::ServerWriter<::blueberry::facade::Data>* writer) override { + ::grpc::ServerContext* context, const ::google::protobuf::Empty* /* request */, + ::grpc::ServerWriter<::blueberry::facade::Data>* writer) override { return pending_le_events_.RunLoop(context, writer); - }; + } class TestAclBuilder : public AclBuilder { - public: + public: explicit TestAclBuilder(std::vector payload) - : AclBuilder(0xbad, PacketBoundaryFlag::CONTINUING_FRAGMENT, BroadcastFlag::ACTIVE_PERIPHERAL_BROADCAST), + : AclBuilder(0xbad, PacketBoundaryFlag::CONTINUING_FRAGMENT, + BroadcastFlag::ACTIVE_PERIPHERAL_BROADCAST), bytes_(std::move(payload)) {} - size_t size() const override { - return bytes_.size(); - } + size_t size() const override { return bytes_.size(); } void Serialize(BitInserter& bit_inserter) const override { for (auto&& b : bytes_) { bit_inserter.insert_byte(b); } } - private: + private: std::vector bytes_; }; - ::grpc::Status SendAcl( - ::grpc::ServerContext* /* context */, - const ::blueberry::facade::Data* acl, - ::google::protobuf::Empty* /* response */) override { - waiting_acl_packet_ = - std::make_unique(std::vector(acl->payload().begin(), acl->payload().end())); + ::grpc::Status SendAcl(::grpc::ServerContext* /* context */, const ::blueberry::facade::Data* acl, + ::google::protobuf::Empty* /* response */) override { + waiting_acl_packet_ = std::make_unique( + std::vector(acl->payload().begin(), acl->payload().end())); std::promise enqueued; auto future = enqueued.get_future(); if (!completed_packets_callback_registered_) { controller_->RegisterCompletedAclPacketsCallback( - facade_handler_->Bind([](uint16_t, uint16_t) { /* do nothing */ })); + facade_handler_->Bind([](uint16_t, uint16_t) { /* do nothing */ })); completed_packets_callback_registered_ = true; } hci_layer_->GetAclQueueEnd()->RegisterEnqueue( - facade_handler_, - common::Bind(&HciFacadeService::handle_enqueue_acl, common::Unretained(this), common::Unretained(&enqueued))); + facade_handler_, common::Bind(&HciFacadeService::handle_enqueue_acl, + common::Unretained(this), common::Unretained(&enqueued))); auto result = future.wait_for(std::chrono::milliseconds(100)); - log::assert_that( - std::future_status::ready == result, "assert failed: std::future_status::ready == result"); + log::assert_that(std::future_status::ready == result, + "assert failed: std::future_status::ready == result"); return ::grpc::Status::OK; } - ::grpc::Status StreamAcl( - ::grpc::ServerContext* context, - const ::google::protobuf::Empty* /* request */, - ::grpc::ServerWriter<::blueberry::facade::Data>* writer) override { + ::grpc::Status StreamAcl(::grpc::ServerContext* context, + const ::google::protobuf::Empty* /* request */, + ::grpc::ServerWriter<::blueberry::facade::Data>* writer) override { hci_layer_->GetAclQueueEnd()->RegisterDequeue( - facade_handler_, common::Bind(&HciFacadeService::on_acl_ready, common::Unretained(this))); + facade_handler_, + common::Bind(&HciFacadeService::on_acl_ready, common::Unretained(this))); unregister_acl_dequeue_ = true; return pending_acl_events_.RunLoop(context, writer); - }; + } - private: +private: std::unique_ptr handle_enqueue_acl(std::promise* promise) { promise->set_value(); hci_layer_->GetAclQueueEnd()->UnregisterEnqueue(); @@ -221,7 +216,8 @@ class HciFacadeService : public HciFacade::Service { Controller* controller_; ::bluetooth::os::Handler* facade_handler_; ::bluetooth::grpc::GrpcEventQueue<::blueberry::facade::Data> pending_events_{"StreamEvents"}; - ::bluetooth::grpc::GrpcEventQueue<::blueberry::facade::Data> pending_le_events_{"StreamLeSubevents"}; + ::bluetooth::grpc::GrpcEventQueue<::blueberry::facade::Data> pending_le_events_{ + "StreamLeSubevents"}; ::bluetooth::grpc::GrpcEventQueue<::blueberry::facade::Data> pending_acl_events_{"StreamAcl"}; bool unregister_acl_dequeue_{false}; std::unique_ptr waiting_acl_packet_; @@ -236,7 +232,8 @@ void HciFacadeModule::ListDependencies(ModuleList* list) const { void HciFacadeModule::Start() { ::bluetooth::grpc::GrpcFacadeModule::Start(); - service_ = new HciFacadeService(GetDependency(), GetDependency(), GetHandler()); + service_ = new HciFacadeService(GetDependency(), GetDependency(), + GetHandler()); } void HciFacadeModule::Stop() { @@ -244,11 +241,10 @@ void HciFacadeModule::Stop() { ::bluetooth::grpc::GrpcFacadeModule::Stop(); } -::grpc::Service* HciFacadeModule::GetService() const { - return service_; -} +::grpc::Service* HciFacadeModule::GetService() const { return service_; } -const ModuleFactory HciFacadeModule::Factory = ::bluetooth::ModuleFactory([]() { return new HciFacadeModule(); }); +const ModuleFactory HciFacadeModule::Factory = + ::bluetooth::ModuleFactory([]() { return new HciFacadeModule(); }); } // namespace facade } // namespace hci diff --git a/system/gd/hci/facade/facade.h b/system/gd/hci/facade/facade.h index 77ac362ba38..283908ddac0 100644 --- a/system/gd/hci/facade/facade.h +++ b/system/gd/hci/facade/facade.h @@ -28,7 +28,7 @@ namespace facade { class HciFacadeService; class HciFacadeModule : public ::bluetooth::grpc::GrpcFacadeModule { - public: +public: static const ModuleFactory Factory; void ListDependencies(ModuleList* list) const override; @@ -36,7 +36,7 @@ class HciFacadeModule : public ::bluetooth::grpc::GrpcFacadeModule { void Stop() override; ::grpc::Service* GetService() const override; - private: +private: HciFacadeService* service_; }; diff --git a/system/gd/hci/facade/le_acl_manager_facade.cc b/system/gd/hci/facade/le_acl_manager_facade.cc index 9ad021bc873..e80cad40a32 100644 --- a/system/gd/hci/facade/le_acl_manager_facade.cc +++ b/system/gd/hci/facade/le_acl_manager_facade.cc @@ -53,7 +53,7 @@ using acl_manager::LeConnectionManagementCallbacks; using namespace blueberry::facade::hci; class LeAclManagerFacadeService : public LeAclManagerFacade::Service, public LeConnectionCallbacks { - public: +public: LeAclManagerFacadeService(AclManager* acl_manager, ::bluetooth::os::Handler* facade_handler) : acl_manager_(acl_manager), facade_handler_(facade_handler) { acl_manager_->RegisterLeCallbacks(this, facade_handler_); @@ -69,67 +69,61 @@ class LeAclManagerFacadeService : public LeAclManagerFacade::Service, public LeC } } - ::grpc::Status CreateConnection( - ::grpc::ServerContext* context, - const CreateConnectionMsg* request, - ::grpc::ServerWriter* writer) override { - log::info( - "peer={}, type={}, id_direct={}", - request->peer_address().address().address(), - request->peer_address().type(), - request->is_direct()); + ::grpc::Status CreateConnection(::grpc::ServerContext* context, + const CreateConnectionMsg* request, + ::grpc::ServerWriter* writer) override { + log::info("peer={}, type={}, id_direct={}", request->peer_address().address().address(), + request->peer_address().type(), request->is_direct()); Address peer_address; log::assert_that( - Address::FromString(request->peer_address().address().address(), peer_address), - "assert failed: Address::FromString(request->peer_address().address().address(), " - "peer_address)"); + Address::FromString(request->peer_address().address().address(), peer_address), + "assert failed: Address::FromString(request->peer_address().address().address(), " + "peer_address)"); AddressWithType peer(peer_address, static_cast(request->peer_address().type())); bool is_direct = request->is_direct(); acl_manager_->CreateLeConnection(peer, is_direct); if (is_direct) { if (direct_connection_events_ != nullptr) { - return ::grpc::Status( - ::grpc::StatusCode::RESOURCE_EXHAUSTED, "Only one outstanding direct request is supported"); + return ::grpc::Status(::grpc::StatusCode::RESOURCE_EXHAUSTED, + "Only one outstanding direct request is supported"); } - direct_connection_events_ = std::make_shared<::bluetooth::grpc::GrpcEventQueue>( - std::string("direct connection attempt ") + peer.ToString()); + direct_connection_events_ = + std::make_shared<::bluetooth::grpc::GrpcEventQueue>( + std::string("direct connection attempt ") + peer.ToString()); direct_connection_address_ = peer; return direct_connection_events_->RunLoop(context, writer); } per_connection_events_.emplace( - peer, - std::make_unique<::bluetooth::grpc::GrpcEventQueue>( - std::string("connection attempt ") + peer.ToString())); + peer, std::make_unique<::bluetooth::grpc::GrpcEventQueue>( + std::string("connection attempt ") + peer.ToString())); return per_connection_events_[peer]->RunLoop(context, writer); } - ::grpc::Status CancelConnection( - ::grpc::ServerContext* /* context */, - const ::blueberry::facade::BluetoothAddressWithType* request, - google::protobuf::Empty* /* response */) override { + ::grpc::Status CancelConnection(::grpc::ServerContext* /* context */, + const ::blueberry::facade::BluetoothAddressWithType* request, + google::protobuf::Empty* /* response */) override { log::info("peer={}, type={}", request->address().address(), request->type()); Address peer_address; log::assert_that( - Address::FromString(request->address().address(), peer_address), - "assert failed: Address::FromString(request->address().address(), peer_address)"); + Address::FromString(request->address().address(), peer_address), + "assert failed: Address::FromString(request->address().address(), peer_address)"); AddressWithType peer(peer_address, static_cast(request->type())); if (peer == direct_connection_address_) { direct_connection_address_ = AddressWithType(); direct_connection_events_.reset(); } else { if (per_connection_events_.count(peer) == 0) { - return ::grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, "No matching outstanding connection"); + return ::grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, + "No matching outstanding connection"); } } acl_manager_->CancelLeConnect(peer); return ::grpc::Status::OK; } - ::grpc::Status Disconnect( - ::grpc::ServerContext* /* context */, - const LeHandleMsg* request, - ::google::protobuf::Empty* /* response */) override { + ::grpc::Status Disconnect(::grpc::ServerContext* /* context */, const LeHandleMsg* request, + ::google::protobuf::Empty* /* response */) override { log::info("handle={}", request->handle()); std::unique_lock lock(acl_connections_mutex_); auto connection = acl_connections_.find(request->handle()); @@ -137,7 +131,8 @@ class LeAclManagerFacadeService : public LeAclManagerFacade::Service, public LeC log::error("Invalid handle"); return ::grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, "Invalid handle"); } else { - connection->second.connection_->Disconnect(DisconnectReason::REMOTE_USER_TERMINATED_CONNECTION); + connection->second.connection_->Disconnect( + DisconnectReason::REMOTE_USER_TERMINATED_CONNECTION); return ::grpc::Status::OK; } } @@ -155,14 +150,13 @@ class LeAclManagerFacadeService : public LeAclManagerFacade::Service, public LeC } \ } while (0) - ::grpc::Status ConnectionCommand( - ::grpc::ServerContext* /* context */, - const LeConnectionCommandMsg* request, - ::google::protobuf::Empty* /* response */) override { + ::grpc::Status ConnectionCommand(::grpc::ServerContext* /* context */, + const LeConnectionCommandMsg* request, + ::google::protobuf::Empty* /* response */) override { log::info("size={}", request->packet().size()); - auto command_view = - ConnectionManagementCommandView::Create(AclCommandView::Create(CommandView::Create(PacketView( - std::make_shared>(request->packet().begin(), request->packet().end()))))); + auto command_view = ConnectionManagementCommandView::Create(AclCommandView::Create( + CommandView::Create(PacketView(std::make_shared>( + request->packet().begin(), request->packet().end()))))); if (!command_view.IsValid()) { return ::grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, "Invalid command packet"); } @@ -180,29 +174,28 @@ class LeAclManagerFacadeService : public LeAclManagerFacade::Service, public LeC } #undef GET_CONNECTION - ::grpc::Status FetchIncomingConnection( - ::grpc::ServerContext* context, - const google::protobuf::Empty* /* request */, - ::grpc::ServerWriter* writer) override { + ::grpc::Status FetchIncomingConnection(::grpc::ServerContext* context, + const google::protobuf::Empty* /* request */, + ::grpc::ServerWriter* writer) override { log::info("wait for one incoming connection"); if (incoming_connection_events_ != nullptr) { - return ::grpc::Status( - ::grpc::StatusCode::RESOURCE_EXHAUSTED, "Only one outstanding incoming connection is supported"); + return ::grpc::Status(::grpc::StatusCode::RESOURCE_EXHAUSTED, + "Only one outstanding incoming connection is supported"); } incoming_connection_events_ = - std::make_unique<::bluetooth::grpc::GrpcEventQueue>(std::string("incoming connection ")); + std::make_unique<::bluetooth::grpc::GrpcEventQueue>( + std::string("incoming connection ")); return incoming_connection_events_->RunLoop(context, writer); } - ::grpc::Status AddDeviceToResolvingList( - ::grpc::ServerContext* /* context */, - const IrkMsg* request, - ::google::protobuf::Empty* /* response */) override { + ::grpc::Status AddDeviceToResolvingList(::grpc::ServerContext* /* context */, + const IrkMsg* request, + ::google::protobuf::Empty* /* response */) override { log::info("peer={}, type={}", request->peer().address().address(), request->peer().type()); Address peer_address; - log::assert_that( - Address::FromString(request->peer().address().address(), peer_address), - "assert failed: Address::FromString(request->peer().address().address(), peer_address)"); + log::assert_that(Address::FromString(request->peer().address().address(), peer_address), + "assert failed: Address::FromString(request->peer().address().address(), " + "peer_address)"); AddressWithType peer(peer_address, static_cast(request->peer().type())); auto request_peer_irk_length = request->peer_irk().end() - request->peer_irk().begin(); @@ -229,10 +222,8 @@ class LeAclManagerFacadeService : public LeAclManagerFacade::Service, public LeC return ::grpc::Status::OK; } - ::grpc::Status SendAclData( - ::grpc::ServerContext* /* context */, - const LeAclData* request, - ::google::protobuf::Empty* /* response */) override { + ::grpc::Status SendAclData(::grpc::ServerContext* /* context */, const LeAclData* request, + ::google::protobuf::Empty* /* response */) override { log::info("handle={}, size={}", request->handle(), request->payload().size()); std::promise promise; auto future = promise.get_future(); @@ -243,12 +234,9 @@ class LeAclManagerFacadeService : public LeAclManagerFacade::Service, public LeC return ::grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, "Invalid handle"); } connection->second.connection_->GetAclQueueEnd()->RegisterEnqueue( - facade_handler_, - common::Bind( - &LeAclManagerFacadeService::enqueue_packet, - common::Unretained(this), - common::Unretained(request), - common::Passed(std::move(promise)))); + facade_handler_, + common::Bind(&LeAclManagerFacadeService::enqueue_packet, common::Unretained(this), + common::Unretained(request), common::Passed(std::move(promise)))); auto status = future.wait_for(std::chrono::milliseconds(1000)); if (status != std::future_status::ready) { return ::grpc::Status(::grpc::StatusCode::RESOURCE_EXHAUSTED, "Can't send packet"); @@ -257,18 +245,19 @@ class LeAclManagerFacadeService : public LeAclManagerFacade::Service, public LeC return ::grpc::Status::OK; } - std::unique_ptr enqueue_packet(const LeAclData* request, std::promise promise) { + std::unique_ptr enqueue_packet(const LeAclData* request, + std::promise promise) { auto connection = acl_connections_.find(request->handle()); log::assert_that(connection != acl_connections_.end(), "handle {}", request->handle()); connection->second.connection_->GetAclQueueEnd()->UnregisterEnqueue(); - std::unique_ptr packet = - std::make_unique(std::vector(request->payload().begin(), request->payload().end())); + std::unique_ptr packet = std::make_unique( + std::vector(request->payload().begin(), request->payload().end())); promise.set_value(); return packet; } - ::grpc::Status FetchAclData( - ::grpc::ServerContext* context, const LeHandleMsg* request, ::grpc::ServerWriter* writer) override { + ::grpc::Status FetchAclData(::grpc::ServerContext* context, const LeHandleMsg* request, + ::grpc::ServerWriter* writer) override { log::info("handle={}", request->handle()); auto connection = acl_connections_.find(request->handle()); if (connection == acl_connections_.end()) { @@ -295,16 +284,16 @@ class LeAclManagerFacadeService : public LeAclManagerFacade::Service, public LeC connection_tracker->second.pending_acl_data_.OnIncomingEvent(acl_data); } - void OnLeConnectSuccess(AddressWithType peer, std::unique_ptr connection) override { + void OnLeConnectSuccess(AddressWithType peer, + std::unique_ptr connection) override { log::info("handle={}, addr={}", connection->GetHandle(), peer); std::unique_lock lock(acl_connections_mutex_); std::shared_ptr shared_connection = std::move(connection); uint16_t handle = shared_connection->GetHandle(); auto role = shared_connection->GetRole(); if (role == Role::PERIPHERAL) { - log::assert_that( - incoming_connection_events_ != nullptr, - "assert failed: incoming_connection_events_ != nullptr"); + log::assert_that(incoming_connection_events_ != nullptr, + "assert failed: incoming_connection_events_ != nullptr"); if (per_connection_events_.find(peer) == per_connection_events_.end()) { per_connection_events_.emplace(peer, incoming_connection_events_); } else { @@ -316,24 +305,22 @@ class LeAclManagerFacadeService : public LeAclManagerFacade::Service, public LeC per_connection_events_.emplace(peer, direct_connection_events_); direct_connection_events_.reset(); } else { - log::assert_that( - per_connection_events_.count(peer) > 0, - "No connection request for {}", - ADDRESS_TO_LOGGABLE_CSTR(peer)); + log::assert_that(per_connection_events_.count(peer) > 0, "No connection request for {}", + ADDRESS_TO_LOGGABLE_CSTR(peer)); } acl_connections_.erase(handle); acl_connections_.emplace( - std::piecewise_construct, - std::forward_as_tuple(handle), - std::forward_as_tuple(handle, shared_connection, per_connection_events_[peer])); + std::piecewise_construct, std::forward_as_tuple(handle), + std::forward_as_tuple(handle, shared_connection, per_connection_events_[peer])); shared_connection->GetAclQueueEnd()->RegisterDequeue( - facade_handler_, - common::Bind(&LeAclManagerFacadeService::on_incoming_acl, common::Unretained(this), shared_connection, handle)); + facade_handler_, common::Bind(&LeAclManagerFacadeService::on_incoming_acl, + common::Unretained(this), shared_connection, handle)); auto callbacks = acl_connections_.find(handle)->second.GetCallbacks(); shared_connection->RegisterCallbacks(callbacks, facade_handler_); { std::unique_ptr builder = LeConnectionCompleteBuilder::Create( - ErrorCode::SUCCESS, handle, role, peer.GetAddressType(), peer.GetAddress(), 1, 2, 3, ClockAccuracy::PPM_20); + ErrorCode::SUCCESS, handle, role, peer.GetAddressType(), peer.GetAddress(), 1, 2, 3, + ClockAccuracy::PPM_20); LeConnectionEvent success; success.set_payload(builder_to_string(std::move(builder))); per_connection_events_[peer]->OnIncomingEvent(success); @@ -343,7 +330,8 @@ class LeAclManagerFacadeService : public LeAclManagerFacade::Service, public LeC void OnLeConnectFail(AddressWithType address, ErrorCode reason) override { log::info("addr={}, reason={}", address, ErrorCodeText(reason)); std::unique_ptr builder = LeConnectionCompleteBuilder::Create( - reason, 0, Role::CENTRAL, address.GetAddressType(), address.GetAddress(), 0, 0, 0, ClockAccuracy::PPM_20); + reason, 0, Role::CENTRAL, address.GetAddressType(), address.GetAddress(), 0, 0, 0, + ClockAccuracy::PPM_20); LeConnectionEvent fail; fail.set_payload(builder_to_string(std::move(builder))); if (address == direct_connection_address_) { @@ -355,82 +343,58 @@ class LeAclManagerFacadeService : public LeAclManagerFacade::Service, public LeC } class Connection : public LeConnectionManagementCallbacks { - public: - Connection( - uint16_t handle, - std::shared_ptr connection, - std::shared_ptr<::bluetooth::grpc::GrpcEventQueue> event_stream) - : handle_(handle), connection_(std::move(connection)), event_stream_(std::move(event_stream)) {} - void OnConnectionUpdate( - hci::ErrorCode /* hci_status */, - uint16_t connection_interval, - uint16_t connection_latency, - uint16_t supervision_timeout) override { - log::info( - "interval: 0x{:x}, latency: 0x{:x}, timeout 0x{:x}", - connection_interval, - connection_latency, - supervision_timeout); + public: + Connection(uint16_t handle, std::shared_ptr connection, + std::shared_ptr<::bluetooth::grpc::GrpcEventQueue> event_stream) + : handle_(handle), + connection_(std::move(connection)), + event_stream_(std::move(event_stream)) {} + void OnConnectionUpdate(hci::ErrorCode /* hci_status */, uint16_t connection_interval, + uint16_t connection_latency, uint16_t supervision_timeout) override { + log::info("interval: 0x{:x}, latency: 0x{:x}, timeout 0x{:x}", connection_interval, + connection_latency, supervision_timeout); } - void OnParameterUpdateRequest( - uint16_t interval_min, - uint16_t interval_max, - uint16_t latency, - uint16_t supervision_timeout) override { - log::info( - "interval_min: 0x{:x}, interval_max: 0x{:x}, latency: 0x{:x}, timeout 0x{:x}", - interval_min, - interval_max, - latency, - supervision_timeout); + void OnParameterUpdateRequest(uint16_t interval_min, uint16_t interval_max, uint16_t latency, + uint16_t supervision_timeout) override { + log::info("interval_min: 0x{:x}, interval_max: 0x{:x}, latency: 0x{:x}, timeout 0x{:x}", + interval_min, interval_max, latency, supervision_timeout); } - void OnDataLengthChange(uint16_t tx_octets, uint16_t tx_time, uint16_t rx_octets, uint16_t rx_time) override { - log::info( - "tx_octets: 0x{:x}, tx_time: 0x{:x}, rx_octets 0x{:x}, rx_time 0x{:x}", - tx_octets, - tx_time, - rx_octets, - rx_time); + void OnDataLengthChange(uint16_t tx_octets, uint16_t tx_time, uint16_t rx_octets, + uint16_t rx_time) override { + log::info("tx_octets: 0x{:x}, tx_time: 0x{:x}, rx_octets 0x{:x}, rx_time 0x{:x}", tx_octets, + tx_time, rx_octets, rx_time); } - void OnPhyUpdate( - hci::ErrorCode /* hci_status */, uint8_t /* tx_phy */, uint8_t /* rx_phy */) override {} + void OnPhyUpdate(hci::ErrorCode /* hci_status */, uint8_t /* tx_phy */, + uint8_t /* rx_phy */) override {} void OnDisconnection(ErrorCode reason) override { log::info("reason: {}", ErrorCodeText(reason)); std::unique_ptr builder = - DisconnectionCompleteBuilder::Create(ErrorCode::SUCCESS, handle_, reason); + DisconnectionCompleteBuilder::Create(ErrorCode::SUCCESS, handle_, reason); LeConnectionEvent disconnection; disconnection.set_payload(builder_to_string(std::move(builder))); event_stream_->OnIncomingEvent(disconnection); } - void OnReadRemoteVersionInformationComplete( - hci::ErrorCode /* hci_status */, - uint8_t /* lmp_version */, - uint16_t /* manufacturer_name */, - uint16_t /* sub_version */) override {} - void OnLeReadRemoteFeaturesComplete( - hci::ErrorCode /* hci_status */, uint64_t /* features */) override {} - - LeConnectionManagementCallbacks* GetCallbacks() { - return this; - } - void OnLeSubrateChange( - hci::ErrorCode hci_status, - uint16_t subrate_factor, - uint16_t peripheral_latency, - uint16_t continuation_number, - uint16_t supervision_timeout) override { + void OnReadRemoteVersionInformationComplete(hci::ErrorCode /* hci_status */, + uint8_t /* lmp_version */, + uint16_t /* manufacturer_name */, + uint16_t /* sub_version */) override {} + void OnLeReadRemoteFeaturesComplete(hci::ErrorCode /* hci_status */, + uint64_t /* features */) override {} + + LeConnectionManagementCallbacks* GetCallbacks() { return this; } + void OnLeSubrateChange(hci::ErrorCode hci_status, uint16_t subrate_factor, + uint16_t peripheral_latency, uint16_t continuation_number, + uint16_t supervision_timeout) override { log::info( - "hci_status: {}, subrate_factor: {:#x}, peripheral_latency: {:#x}, continuation_number: " - "{:#x}, supervision_timeout: {:#x}", - ErrorCodeText(hci_status), - subrate_factor, - peripheral_latency, - continuation_number, - supervision_timeout); + "hci_status: {}, subrate_factor: {:#x}, peripheral_latency: {:#x}, " + "continuation_number: " + "{:#x}, supervision_timeout: {:#x}", + ErrorCodeText(hci_status), subrate_factor, peripheral_latency, continuation_number, + supervision_timeout); } uint16_t handle_; @@ -440,15 +404,14 @@ class LeAclManagerFacadeService : public LeAclManagerFacade::Service, public LeC std::to_string(handle_)}; }; - ::grpc::Status IsOnBackgroundList( - ::grpc::ServerContext* /* context */, - const ::blueberry::facade::hci::BackgroundRequestMsg* request, - ::blueberry::facade::hci::BackgroundResultMsg* msg) { + ::grpc::Status IsOnBackgroundList(::grpc::ServerContext* /* context */, + const ::blueberry::facade::hci::BackgroundRequestMsg* request, + ::blueberry::facade::hci::BackgroundResultMsg* msg) { Address peer_address; log::assert_that( - Address::FromString(request->peer_address().address().address(), peer_address), - "assert failed: Address::FromString(request->peer_address().address().address(), " - "peer_address)"); + Address::FromString(request->peer_address().address().address(), peer_address), + "assert failed: Address::FromString(request->peer_address().address().address(), " + "peer_address)"); AddressWithType peer(peer_address, static_cast(request->peer_address().type())); std::promise promise; auto future = promise.get_future(); @@ -458,25 +421,26 @@ class LeAclManagerFacadeService : public LeAclManagerFacade::Service, public LeC } ::grpc::Status RemoveFromBackgroundList( - ::grpc::ServerContext* /* context */, - const ::blueberry::facade::hci::BackgroundRequestMsg* request, - ::google::protobuf::Empty* /* response */) { + ::grpc::ServerContext* /* context */, + const ::blueberry::facade::hci::BackgroundRequestMsg* request, + ::google::protobuf::Empty* /* response */) { Address peer_address; log::assert_that( - Address::FromString(request->peer_address().address().address(), peer_address), - "assert failed: Address::FromString(request->peer_address().address().address(), " - "peer_address)"); + Address::FromString(request->peer_address().address().address(), peer_address), + "assert failed: Address::FromString(request->peer_address().address().address(), " + "peer_address)"); AddressWithType peer(peer_address, static_cast(request->peer_address().type())); acl_manager_->RemoveFromBackgroundList(peer); return ::grpc::Status::OK; } - private: +private: AclManager* acl_manager_; ::bluetooth::os::Handler* facade_handler_; mutable std::mutex acl_connections_mutex_; - std::map>> - per_connection_events_; + std::map>> + per_connection_events_; std::shared_ptr<::bluetooth::grpc::GrpcEventQueue> direct_connection_events_; bluetooth::hci::AddressWithType direct_connection_address_; std::shared_ptr<::bluetooth::grpc::GrpcEventQueue> incoming_connection_events_; @@ -498,12 +462,10 @@ void LeAclManagerFacadeModule::Stop() { ::bluetooth::grpc::GrpcFacadeModule::Stop(); } -::grpc::Service* LeAclManagerFacadeModule::GetService() const { - return service_; -} +::grpc::Service* LeAclManagerFacadeModule::GetService() const { return service_; } const ModuleFactory LeAclManagerFacadeModule::Factory = - ::bluetooth::ModuleFactory([]() { return new LeAclManagerFacadeModule(); }); + ::bluetooth::ModuleFactory([]() { return new LeAclManagerFacadeModule(); }); } // namespace facade } // namespace hci diff --git a/system/gd/hci/facade/le_acl_manager_facade.h b/system/gd/hci/facade/le_acl_manager_facade.h index 45d35fe0aa0..931601c273c 100644 --- a/system/gd/hci/facade/le_acl_manager_facade.h +++ b/system/gd/hci/facade/le_acl_manager_facade.h @@ -28,7 +28,7 @@ namespace facade { class LeAclManagerFacadeService; class LeAclManagerFacadeModule : public ::bluetooth::grpc::GrpcFacadeModule { - public: +public: static const ModuleFactory Factory; void ListDependencies(ModuleList* list) const override; @@ -36,7 +36,7 @@ class LeAclManagerFacadeModule : public ::bluetooth::grpc::GrpcFacadeModule { void Stop() override; ::grpc::Service* GetService() const override; - private: +private: LeAclManagerFacadeService* service_; }; diff --git a/system/gd/hci/facade/le_advertising_manager_facade.cc b/system/gd/hci/facade/le_advertising_manager_facade.cc index 26e6147601f..88207dd242d 100644 --- a/system/gd/hci/facade/le_advertising_manager_facade.cc +++ b/system/gd/hci/facade/le_advertising_manager_facade.cc @@ -53,15 +53,16 @@ using ::blueberry::facade::hci::PeriodicAdvertisingParameters; hci::GapData GapDataFromProto(const GapDataMsg& gap_data_proto) { hci::GapData gap_data; - auto data_copy = std::make_shared>(gap_data_proto.data().begin(), gap_data_proto.data().end()); + auto data_copy = std::make_shared>(gap_data_proto.data().begin(), + gap_data_proto.data().end()); packet::PacketView packet(data_copy); auto after = hci::GapData::Parse(&gap_data, packet.begin()); log::assert_that(after != packet.begin(), "assert failed: after != packet.begin()"); return gap_data; } -bool AdvertisingConfigFromProto( - const AdvertisingConfig& config_proto, hci::AdvertisingConfig* config) { +bool AdvertisingConfigFromProto(const AdvertisingConfig& config_proto, + hci::AdvertisingConfig* config) { for (const auto& elem : config_proto.advertisement()) { config->advertisement.push_back(GapDataFromProto(elem)); } @@ -85,11 +86,12 @@ bool AdvertisingConfigFromProto( config->advertising_type = static_cast(config_proto.advertising_type()); config->requested_advertiser_address_type = - config_proto.own_address_type() == BluetoothOwnAddressTypeEnum::USE_PUBLIC_DEVICE_ADDRESS - ? AdvertiserAddressType::PUBLIC - : AdvertiserAddressType::RESOLVABLE_RANDOM; + config_proto.own_address_type() == BluetoothOwnAddressTypeEnum::USE_PUBLIC_DEVICE_ADDRESS + ? AdvertiserAddressType::PUBLIC + : AdvertiserAddressType::RESOLVABLE_RANDOM; - config->peer_address_type = static_cast<::bluetooth::hci::PeerAddressType>(config_proto.peer_address_type()); + config->peer_address_type = + static_cast<::bluetooth::hci::PeerAddressType>(config_proto.peer_address_type()); hci::Address::FromString(config_proto.peer_address().address(), config->peer_address); @@ -110,7 +112,8 @@ bool AdvertisingConfigFromProto( config->legacy_pdus = true; - auto advertising_type = static_cast<::bluetooth::hci::AdvertisingType>(config_proto.advertising_type()); + auto advertising_type = + static_cast<::bluetooth::hci::AdvertisingType>(config_proto.advertising_type()); switch (advertising_type) { case AdvertisingType::ADV_IND: { @@ -136,8 +139,8 @@ bool AdvertisingConfigFromProto( return true; } -bool ExtendedAdvertisingConfigFromProto( - const ExtendedAdvertisingConfig& config_proto, hci::AdvertisingConfig* config) { +bool ExtendedAdvertisingConfigFromProto(const ExtendedAdvertisingConfig& config_proto, + hci::AdvertisingConfig* config) { if (!AdvertisingConfigFromProto(config_proto.advertising_config(), config)) { log::warn("Error parsing advertising config"); return false; @@ -151,15 +154,16 @@ bool ExtendedAdvertisingConfigFromProto( config->include_tx_power = config_proto.include_tx_power(); config->use_le_coded_phy = config_proto.use_le_coded_phy(); config->secondary_max_skip = static_cast(config_proto.secondary_max_skip()); - config->secondary_advertising_phy = static_cast(config_proto.secondary_advertising_phy()); + config->secondary_advertising_phy = + static_cast(config_proto.secondary_advertising_phy()); config->sid = static_cast(config_proto.sid()); config->enable_scan_request_notifications = - static_cast(config_proto.enable_scan_request_notifications()); + static_cast(config_proto.enable_scan_request_notifications()); return true; } -bool PeriodicAdvertisingParametersFromProto( - const PeriodicAdvertisingParameters& config_proto, hci::PeriodicAdvertisingParameters* config) { +bool PeriodicAdvertisingParametersFromProto(const PeriodicAdvertisingParameters& config_proto, + hci::PeriodicAdvertisingParameters* config) { if (config_proto.min_interval() > UINT16_MAX || config_proto.min_interval() < 0) { log::warn("Bad interval_min: {}", config_proto.min_interval()); return false; @@ -170,28 +174,24 @@ bool PeriodicAdvertisingParametersFromProto( return false; } config->max_interval = static_cast(config_proto.max_interval()); - config->properties = - static_cast(config_proto.advertising_property()); + config->properties = static_cast( + config_proto.advertising_property()); return true; } class LeAdvertiser { - public: +public: LeAdvertiser(hci::AdvertisingConfig config) : config_(std::move(config)) {} void ScanCallback(Address /* address */, AddressType /* address_type */) {} void TerminatedCallback(ErrorCode /* error_code */, uint8_t, uint8_t) {} - hci::AdvertiserId GetAdvertiserId() { - return id_; - } + hci::AdvertiserId GetAdvertiserId() { return id_; } - void SetAdvertiserId(hci::AdvertiserId id) { - id_ = id; - } + void SetAdvertiserId(hci::AdvertiserId id) { id_ = id; } - private: +private: hci::AdvertiserId id_ = LeAdvertisingManager::kInvalidId; hci::AdvertisingConfig config_; }; @@ -215,39 +215,37 @@ using ::blueberry::facade::hci::SetParametersRequest; using ::blueberry::facade::hci::SetPeriodicDataRequest; using ::blueberry::facade::hci::SetPeriodicParametersRequest; -class LeAdvertisingManagerFacadeService : public LeAdvertisingManagerFacade::Service, AdvertisingCallback { - public: - LeAdvertisingManagerFacadeService(LeAdvertisingManager* le_advertising_manager, os::Handler* facade_handler) +class LeAdvertisingManagerFacadeService : public LeAdvertisingManagerFacade::Service, + AdvertisingCallback { +public: + LeAdvertisingManagerFacadeService(LeAdvertisingManager* le_advertising_manager, + os::Handler* facade_handler) : le_advertising_manager_(le_advertising_manager), facade_handler_(facade_handler) { - log::assert_that( - le_advertising_manager_ != nullptr, "assert failed: le_advertising_manager_ != nullptr"); + log::assert_that(le_advertising_manager_ != nullptr, + "assert failed: le_advertising_manager_ != nullptr"); log::assert_that(facade_handler_ != nullptr, "assert failed: facade_handler_ != nullptr"); le_advertising_manager_->RegisterAdvertisingCallback(this); } - ::grpc::Status CreateAdvertiser( - ::grpc::ServerContext* /* context */, - const CreateAdvertiserRequest* request, - CreateAdvertiserResponse* response) override { + ::grpc::Status CreateAdvertiser(::grpc::ServerContext* /* context */, + const CreateAdvertiserRequest* request, + CreateAdvertiserResponse* response) override { hci::AdvertisingConfig config = {}; if (!AdvertisingConfigFromProto(request->config(), &config)) { log::warn("Error parsing advertising config {}", request->SerializeAsString()); response->set_advertiser_id(LeAdvertisingManager::kInvalidId); - return ::grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, "Error while parsing advertising config"); + return ::grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, + "Error while parsing advertising config"); } LeAdvertiser le_advertiser(config); pending_advertiser_id_ = std::promise(); auto future = pending_advertiser_id_->get_future(); le_advertising_manager_->ExtendedCreateAdvertiser( - kAdvertiserClientIdJni, - 0, - config, - common::Bind(&LeAdvertiser::ScanCallback, common::Unretained(&le_advertiser)), - common::Bind(&LeAdvertiser::TerminatedCallback, common::Unretained(&le_advertiser)), - 0, - 0, - facade_handler_); + kAdvertiserClientIdJni, 0, config, + common::Bind(&LeAdvertiser::ScanCallback, common::Unretained(&le_advertiser)), + common::Bind(&LeAdvertiser::TerminatedCallback, common::Unretained(&le_advertiser)), 0, + 0, facade_handler_); auto advertiser_id = future.get(); if (advertiser_id != LeAdvertisingManager::kInvalidId) { @@ -260,28 +258,24 @@ class LeAdvertisingManagerFacadeService : public LeAdvertisingManagerFacade::Ser return ::grpc::Status::OK; } - ::grpc::Status ExtendedCreateAdvertiser( - ::grpc::ServerContext* /* context */, - const ExtendedCreateAdvertiserRequest* request, - ExtendedCreateAdvertiserResponse* response) override { + ::grpc::Status ExtendedCreateAdvertiser(::grpc::ServerContext* /* context */, + const ExtendedCreateAdvertiserRequest* request, + ExtendedCreateAdvertiserResponse* response) override { hci::AdvertisingConfig config = {}; if (!ExtendedAdvertisingConfigFromProto(request->config(), &config)) { log::warn("Error parsing advertising config {}", request->SerializeAsString()); response->set_advertiser_id(LeAdvertisingManager::kInvalidId); - return ::grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, "Error while parsing advertising config"); + return ::grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, + "Error while parsing advertising config"); } LeAdvertiser le_advertiser(config); pending_advertiser_id_ = std::promise(); auto future = pending_advertiser_id_->get_future(); le_advertising_manager_->ExtendedCreateAdvertiser( - kAdvertiserClientIdJni, - 0, - config, - common::Bind(&LeAdvertiser::ScanCallback, common::Unretained(&le_advertiser)), - common::Bind(&LeAdvertiser::TerminatedCallback, common::Unretained(&le_advertiser)), - 0, - 0, - facade_handler_); + kAdvertiserClientIdJni, 0, config, + common::Bind(&LeAdvertiser::ScanCallback, common::Unretained(&le_advertiser)), + common::Bind(&LeAdvertiser::TerminatedCallback, common::Unretained(&le_advertiser)), 0, + 0, facade_handler_); auto advertiser_id = future.get(); if (advertiser_id != LeAdvertisingManager::kInvalidId) { @@ -294,57 +288,53 @@ class LeAdvertisingManagerFacadeService : public LeAdvertisingManagerFacade::Ser return ::grpc::Status::OK; } - ::grpc::Status EnableAdvertiser( - ::grpc::ServerContext* /* context */, - const EnableAdvertiserRequest* request, - ::google::protobuf::Empty* /* response */) override { + ::grpc::Status EnableAdvertiser(::grpc::ServerContext* /* context */, + const EnableAdvertiserRequest* request, + ::google::protobuf::Empty* /* response */) override { le_advertising_manager_->EnableAdvertiser(request->advertiser_id(), request->enable(), 0, 0); return ::grpc::Status::OK; } - ::grpc::Status SetData( - ::grpc::ServerContext* /* context */, - const SetDataRequest* request, - ::google::protobuf::Empty* /* response */) override { + ::grpc::Status SetData(::grpc::ServerContext* /* context */, const SetDataRequest* request, + ::google::protobuf::Empty* /* response */) override { std::vector advertising_data = {}; for (const auto& elem : request->data()) { advertising_data.push_back(GapDataFromProto(elem)); } - le_advertising_manager_->SetData(request->advertiser_id(), request->set_scan_rsp(), advertising_data); + le_advertising_manager_->SetData(request->advertiser_id(), request->set_scan_rsp(), + advertising_data); return ::grpc::Status::OK; } - ::grpc::Status SetParameters( - ::grpc::ServerContext* /* context */, - const SetParametersRequest* request, - ::google::protobuf::Empty* /* response */) override { + ::grpc::Status SetParameters(::grpc::ServerContext* /* context */, + const SetParametersRequest* request, + ::google::protobuf::Empty* /* response */) override { hci::AdvertisingConfig config = {}; if (!AdvertisingConfigFromProto(request->config(), &config)) { log::warn("Error parsing advertising config {}", request->SerializeAsString()); - return ::grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, "Error while parsing advertising config"); + return ::grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, + "Error while parsing advertising config"); } le_advertising_manager_->SetParameters(request->advertiser_id(), config); return ::grpc::Status::OK; } - ::grpc::Status SetPeriodicParameters( - ::grpc::ServerContext* /* context */, - const SetPeriodicParametersRequest* request, - ::google::protobuf::Empty* /* response */) override { + ::grpc::Status SetPeriodicParameters(::grpc::ServerContext* /* context */, + const SetPeriodicParametersRequest* request, + ::google::protobuf::Empty* /* response */) override { hci::PeriodicAdvertisingParameters config = {}; if (!PeriodicAdvertisingParametersFromProto(request->config(), &config)) { log::warn("Error parsing periodic advertising parameters {}", request->SerializeAsString()); - return ::grpc::Status( - ::grpc::StatusCode::INVALID_ARGUMENT, "Error while parsing periodic advertising parameters"); + return ::grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, + "Error while parsing periodic advertising parameters"); } le_advertising_manager_->SetPeriodicParameters(request->advertiser_id(), config); return ::grpc::Status::OK; } - ::grpc::Status SetPeriodicData( - ::grpc::ServerContext* /* context */, - const SetPeriodicDataRequest* request, - ::google::protobuf::Empty* /* response */) override { + ::grpc::Status SetPeriodicData(::grpc::ServerContext* /* context */, + const SetPeriodicDataRequest* request, + ::google::protobuf::Empty* /* response */) override { std::vector advertising_data = {}; for (const auto& elem : request->data()) { advertising_data.push_back(GapDataFromProto(elem)); @@ -353,35 +343,32 @@ class LeAdvertisingManagerFacadeService : public LeAdvertisingManagerFacade::Ser return ::grpc::Status::OK; } - ::grpc::Status EnablePeriodicAdvertising( - ::grpc::ServerContext* /* context */, - const EnablePeriodicAdvertisingRequest* request, - ::google::protobuf::Empty* /* response */) override { - le_advertising_manager_->EnablePeriodicAdvertising( - request->advertiser_id(), request->enable(), request->include_adi()); + ::grpc::Status EnablePeriodicAdvertising(::grpc::ServerContext* /* context */, + const EnablePeriodicAdvertisingRequest* request, + ::google::protobuf::Empty* /* response */) override { + le_advertising_manager_->EnablePeriodicAdvertising(request->advertiser_id(), request->enable(), + request->include_adi()); return ::grpc::Status::OK; } - ::grpc::Status GetOwnAddress( - ::grpc::ServerContext* /* context */, - const GetOwnAddressRequest* request, - ::google::protobuf::Empty* /* response */) override { + ::grpc::Status GetOwnAddress(::grpc::ServerContext* /* context */, + const GetOwnAddressRequest* request, + ::google::protobuf::Empty* /* response */) override { le_advertising_manager_->GetOwnAddress(request->advertiser_id()); return ::grpc::Status::OK; } ::grpc::Status GetNumberOfAdvertisingInstances( - ::grpc::ServerContext* /* context */, - const ::google::protobuf::Empty* /* request */, - GetNumberOfAdvertisingInstancesResponse* response) override { - response->set_num_advertising_instances(le_advertising_manager_->GetNumberOfAdvertisingInstances()); + ::grpc::ServerContext* /* context */, const ::google::protobuf::Empty* /* request */, + GetNumberOfAdvertisingInstancesResponse* response) override { + response->set_num_advertising_instances( + le_advertising_manager_->GetNumberOfAdvertisingInstances()); return ::grpc::Status::OK; } - ::grpc::Status RemoveAdvertiser( - ::grpc::ServerContext* /* context */, - const RemoveAdvertiserRequest* request, - ::google::protobuf::Empty* /* response */) override { + ::grpc::Status RemoveAdvertiser(::grpc::ServerContext* /* context */, + const RemoveAdvertiserRequest* request, + ::google::protobuf::Empty* /* response */) override { if (request->advertiser_id() == LeAdvertisingManager::kInvalidId) { log::warn("Invalid advertiser ID {}", request->advertiser_id()); return ::grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, "Invlid advertiser ID received"); @@ -398,21 +385,19 @@ class LeAdvertisingManagerFacadeService : public LeAdvertisingManagerFacade::Ser } ::grpc::Status FetchCallbackEvents( - ::grpc::ServerContext* context, - const ::google::protobuf::Empty* /* request */, - ::grpc::ServerWriter* writer) override { + ::grpc::ServerContext* context, const ::google::protobuf::Empty* /* request */, + ::grpc::ServerWriter* writer) override { return callback_events_.RunLoop(context, writer); } - ::grpc::Status FetchAddressEvents( - ::grpc::ServerContext* context, - const ::google::protobuf::Empty* /* request */, - ::grpc::ServerWriter* writer) override { + ::grpc::Status FetchAddressEvents(::grpc::ServerContext* context, + const ::google::protobuf::Empty* /* request */, + ::grpc::ServerWriter* writer) override { return address_events_.RunLoop(context, writer); } - void OnAdvertisingSetStarted( - int reg_id, uint8_t advertiser_id, int8_t /* tx_power */, AdvertisingStatus status) { + void OnAdvertisingSetStarted(int reg_id, uint8_t advertiser_id, int8_t /* tx_power */, + AdvertisingStatus status) { if (pending_advertiser_id_.has_value()) { pending_advertiser_id_->set_value(advertiser_id); pending_advertiser_id_.reset(); @@ -423,7 +408,7 @@ class LeAdvertisingManagerFacadeService : public LeAdvertisingManagerFacade::Ser msg.set_status(static_cast(status)); msg.set_data(reg_id); callback_events_.OnIncomingEvent(msg); - }; + } void OnAdvertisingEnabled(uint8_t advertiser_id, bool enable, AdvertisingStatus status) { AdvertisingCallbackMsg msg; @@ -494,7 +479,7 @@ class LeAdvertisingManagerFacadeService : public LeAdvertisingManagerFacade::Ser facade_address.set_type(static_cast(address_type)); *msg.mutable_address() = facade_address; address_events_.OnIncomingEvent(msg); - }; + } std::vector le_advertisers_; LeAdvertisingManager* le_advertising_manager_; @@ -511,7 +496,8 @@ void LeAdvertisingManagerFacadeModule::ListDependencies(ModuleList* list) const void LeAdvertisingManagerFacadeModule::Start() { ::bluetooth::grpc::GrpcFacadeModule::Start(); - service_ = new LeAdvertisingManagerFacadeService(GetDependency(), GetHandler()); + service_ = new LeAdvertisingManagerFacadeService(GetDependency(), + GetHandler()); } void LeAdvertisingManagerFacadeModule::Stop() { @@ -519,12 +505,10 @@ void LeAdvertisingManagerFacadeModule::Stop() { ::bluetooth::grpc::GrpcFacadeModule::Stop(); } -::grpc::Service* LeAdvertisingManagerFacadeModule::GetService() const { - return service_; -} +::grpc::Service* LeAdvertisingManagerFacadeModule::GetService() const { return service_; } const ModuleFactory LeAdvertisingManagerFacadeModule::Factory = - ::bluetooth::ModuleFactory([]() { return new LeAdvertisingManagerFacadeModule(); }); + ::bluetooth::ModuleFactory([]() { return new LeAdvertisingManagerFacadeModule(); }); } // namespace facade } // namespace hci diff --git a/system/gd/hci/facade/le_advertising_manager_facade.h b/system/gd/hci/facade/le_advertising_manager_facade.h index d6af43e3455..99913f9a312 100644 --- a/system/gd/hci/facade/le_advertising_manager_facade.h +++ b/system/gd/hci/facade/le_advertising_manager_facade.h @@ -26,7 +26,7 @@ namespace facade { class LeAdvertisingManagerFacadeService; class LeAdvertisingManagerFacadeModule : public ::bluetooth::grpc::GrpcFacadeModule { - public: +public: static const ModuleFactory Factory; void ListDependencies(ModuleList* list) const override; @@ -35,7 +35,7 @@ class LeAdvertisingManagerFacadeModule : public ::bluetooth::grpc::GrpcFacadeMod ::grpc::Service* GetService() const override; - private: +private: LeAdvertisingManagerFacadeService* service_; }; diff --git a/system/gd/hci/facade/le_initiator_address_facade.cc b/system/gd/hci/facade/le_initiator_address_facade.cc index 4b53e426f63..dcc2da0e355 100644 --- a/system/gd/hci/facade/le_initiator_address_facade.cc +++ b/system/gd/hci/facade/le_initiator_address_facade.cc @@ -36,7 +36,7 @@ namespace facade { using namespace blueberry::facade::hci; class LeInitiatorAddressFacadeService : public LeInitiatorAddressFacade::Service { - public: +public: LeInitiatorAddressFacadeService(AclManager* acl_manager, ::bluetooth::os::Handler* facade_handler) : acl_manager_(acl_manager), address_manager_(acl_manager_->GetLeAddressManager()), @@ -45,19 +45,20 @@ class LeInitiatorAddressFacadeService : public LeInitiatorAddressFacade::Service } ::grpc::Status SetPrivacyPolicyForInitiatorAddress( - ::grpc::ServerContext* /* context */, - const PrivacyPolicy* request, - ::google::protobuf::Empty* /* writer */) override { + ::grpc::ServerContext* /* context */, const PrivacyPolicy* request, + ::google::protobuf::Empty* /* writer */) override { Address address = Address::kEmpty; LeAddressManager::AddressPolicy address_policy = - static_cast(request->address_policy()); + static_cast(request->address_policy()); if (address_policy == LeAddressManager::AddressPolicy::USE_STATIC_ADDRESS) { log::assert_that( - Address::FromString(request->address_with_type().address().address(), address), - "assert failed: Address::FromString(request->address_with_type().address().address(), " - "address)"); + Address::FromString(request->address_with_type().address().address(), address), + "assert failed: " + "Address::FromString(request->address_with_type().address().address(), " + "address)"); } - AddressWithType address_with_type(address, static_cast(request->address_with_type().type())); + AddressWithType address_with_type( + address, static_cast(request->address_with_type().type())); auto minimum_rotation_time = std::chrono::milliseconds(request->minimum_rotation_time()); auto maximum_rotation_time = std::chrono::milliseconds(request->maximum_rotation_time()); Octet16 irk = {}; @@ -66,40 +67,40 @@ class LeInitiatorAddressFacadeService : public LeInitiatorAddressFacade::Service std::vector irk_data(request->rotation_irk().begin(), request->rotation_irk().end()); std::copy_n(irk_data.begin(), kOctet16Length, irk.begin()); acl_manager_->SetPrivacyPolicyForInitiatorAddressForTest( - address_policy, address_with_type, irk, minimum_rotation_time, maximum_rotation_time); + address_policy, address_with_type, irk, minimum_rotation_time, maximum_rotation_time); } else { acl_manager_->SetPrivacyPolicyForInitiatorAddress( - address_policy, address_with_type, minimum_rotation_time, maximum_rotation_time); + address_policy, address_with_type, minimum_rotation_time, maximum_rotation_time); log::assert_that(request_irk_length == 0, "assert failed: request_irk_length == 0"); } return ::grpc::Status::OK; } ::grpc::Status GetCurrentInitiatorAddress( - ::grpc::ServerContext* /* context */, - const ::google::protobuf::Empty* /* request */, - ::blueberry::facade::BluetoothAddressWithType* response) override { + ::grpc::ServerContext* /* context */, const ::google::protobuf::Empty* /* request */, + ::blueberry::facade::BluetoothAddressWithType* response) override { AddressWithType current = address_manager_->GetInitiatorAddress(); auto bluetooth_address = new ::blueberry::facade::BluetoothAddress(); bluetooth_address->set_address(current.GetAddress().ToString()); - response->set_type(static_cast<::blueberry::facade::BluetoothAddressTypeEnum>(current.GetAddressType())); + response->set_type( + static_cast<::blueberry::facade::BluetoothAddressTypeEnum>(current.GetAddressType())); response->set_allocated_address(bluetooth_address); return ::grpc::Status::OK; } ::grpc::Status NewResolvableAddress( - ::grpc::ServerContext* /* context */, - const ::google::protobuf::Empty* /* request */, - ::blueberry::facade::BluetoothAddressWithType* response) override { + ::grpc::ServerContext* /* context */, const ::google::protobuf::Empty* /* request */, + ::blueberry::facade::BluetoothAddressWithType* response) override { AddressWithType another = address_manager_->NewResolvableAddress(); auto bluetooth_address = new ::blueberry::facade::BluetoothAddress(); bluetooth_address->set_address(another.GetAddress().ToString()); - response->set_type(static_cast<::blueberry::facade::BluetoothAddressTypeEnum>(another.GetAddressType())); + response->set_type( + static_cast<::blueberry::facade::BluetoothAddressTypeEnum>(another.GetAddressType())); response->set_allocated_address(bluetooth_address); return ::grpc::Status::OK; } - private: +private: AclManager* acl_manager_; LeAddressManager* address_manager_; ::bluetooth::os::Handler* facade_handler_; @@ -120,12 +121,10 @@ void LeInitiatorAddressFacadeModule::Stop() { ::bluetooth::grpc::GrpcFacadeModule::Stop(); } -::grpc::Service* LeInitiatorAddressFacadeModule::GetService() const { - return service_; -} +::grpc::Service* LeInitiatorAddressFacadeModule::GetService() const { return service_; } const ModuleFactory LeInitiatorAddressFacadeModule::Factory = - ::bluetooth::ModuleFactory([]() { return new LeInitiatorAddressFacadeModule(); }); + ::bluetooth::ModuleFactory([]() { return new LeInitiatorAddressFacadeModule(); }); } // namespace facade } // namespace hci diff --git a/system/gd/hci/facade/le_initiator_address_facade.h b/system/gd/hci/facade/le_initiator_address_facade.h index 28c8c64de82..3952b141468 100644 --- a/system/gd/hci/facade/le_initiator_address_facade.h +++ b/system/gd/hci/facade/le_initiator_address_facade.h @@ -28,7 +28,7 @@ namespace facade { class LeInitiatorAddressFacadeService; class LeInitiatorAddressFacadeModule : public ::bluetooth::grpc::GrpcFacadeModule { - public: +public: static const ModuleFactory Factory; void ListDependencies(ModuleList* list) const override; @@ -36,7 +36,7 @@ class LeInitiatorAddressFacadeModule : public ::bluetooth::grpc::GrpcFacadeModul void Stop() override; ::grpc::Service* GetService() const override; - private: +private: LeInitiatorAddressFacadeService* service_; }; diff --git a/system/gd/hci/facade/le_scanning_manager_facade.cc b/system/gd/hci/facade/le_scanning_manager_facade.cc index 32f1f426182..8a2e7f90eef 100644 --- a/system/gd/hci/facade/le_scanning_manager_facade.cc +++ b/system/gd/hci/facade/le_scanning_manager_facade.cc @@ -44,77 +44,67 @@ using ::grpc::Status; using namespace blueberry::facade::hci; class LeScanningManagerFacadeService : public LeScanningManagerFacade::Service, ScanningCallback { - public: - LeScanningManagerFacadeService(LeScanningManager* le_scanning_manager, os::Handler* facade_handler) +public: + LeScanningManagerFacadeService(LeScanningManager* le_scanning_manager, + os::Handler* facade_handler) : le_scanning_manager_(le_scanning_manager), facade_handler_(facade_handler) { - log::assert_that( - le_scanning_manager_ != nullptr, "assert failed: le_scanning_manager_ != nullptr"); + log::assert_that(le_scanning_manager_ != nullptr, + "assert failed: le_scanning_manager_ != nullptr"); log::assert_that(facade_handler_ != nullptr, "assert failed: facade_handler_ != nullptr"); le_scanning_manager_->RegisterScanningCallback(this); } - ::grpc::Status RegisterScanner( - ::grpc::ServerContext* /* context */, - const RegisterScannerRequest* request, - ::google::protobuf::Empty* /* response */) override { + ::grpc::Status RegisterScanner(::grpc::ServerContext* /* context */, + const RegisterScannerRequest* request, + ::google::protobuf::Empty* /* response */) override { uint32_t uuid_raw = request->uuid(); bluetooth::hci::Uuid uuid = bluetooth::hci::Uuid::From32Bit(uuid_raw); le_scanning_manager_->RegisterScanner(uuid); return ::grpc::Status::OK; } - ::grpc::Status Unregister( - ::grpc::ServerContext* /* context */, - const UnregisterRequest* request, - ::google::protobuf::Empty* /* response */) override { + ::grpc::Status Unregister(::grpc::ServerContext* /* context */, const UnregisterRequest* request, + ::google::protobuf::Empty* /* response */) override { le_scanning_manager_->Unregister(request->scanner_id()); return ::grpc::Status::OK; } - ::grpc::Status Scan( - ::grpc::ServerContext* /* context */, - const ScanRequest* request, - ::google::protobuf::Empty* /* response */) override { + ::grpc::Status Scan(::grpc::ServerContext* /* context */, const ScanRequest* request, + ::google::protobuf::Empty* /* response */) override { le_scanning_manager_->Scan(request->start()); return ::grpc::Status::OK; } - ::grpc::Status SetScanParameters( - ::grpc::ServerContext* /* context */, - const SetScanParametersRequest* request, - ::google::protobuf::Empty* /* response */) override { + ::grpc::Status SetScanParameters(::grpc::ServerContext* /* context */, + const SetScanParametersRequest* request, + ::google::protobuf::Empty* /* response */) override { auto scan_type = static_cast(request->scan_type()); - le_scanning_manager_->SetScanParameters( - request->scanner_id(), - scan_type, - request->scan_interval(), - request->scan_window(), - request->scan_phy()); + le_scanning_manager_->SetScanParameters(request->scanner_id(), scan_type, + request->scan_interval(), request->scan_window(), + request->scan_phy()); return ::grpc::Status::OK; } - ::grpc::Status FetchCallbackEvents( - ::grpc::ServerContext* context, - const ::google::protobuf::Empty* /* request */, - ::grpc::ServerWriter* writer) override { + ::grpc::Status FetchCallbackEvents(::grpc::ServerContext* context, + const ::google::protobuf::Empty* /* request */, + ::grpc::ServerWriter* writer) override { return callback_events_.RunLoop(context, writer); } ::grpc::Status FetchAdvertisingReports( - ::grpc::ServerContext* context, - const ::google::protobuf::Empty* /* request */, - ::grpc::ServerWriter* writer) override { + ::grpc::ServerContext* context, const ::google::protobuf::Empty* /* request */, + ::grpc::ServerWriter* writer) override { return advertising_reports_.RunLoop(context, writer); } - void OnScannerRegistered( - const bluetooth::hci::Uuid app_uuid, ScannerId /* scanner_id */, ScanningStatus status) { + void OnScannerRegistered(const bluetooth::hci::Uuid app_uuid, ScannerId /* scanner_id */, + ScanningStatus status) { ScanningCallbackMsg msg; msg.set_message_type(ScanningCallbackMsgType::SCANNER_REGISTERED); msg.set_status(static_cast(status)); msg.set_data(app_uuid.As32Bit()); callback_events_.OnIncomingEvent(msg); - }; + } void OnSetScannerParameterComplete(ScannerId scanner_id, ScanningStatus status) { ScanningCallbackMsg msg; @@ -122,19 +112,13 @@ class LeScanningManagerFacadeService : public LeScanningManagerFacade::Service, msg.set_status(static_cast(status)); msg.set_data(static_cast(scanner_id)); callback_events_.OnIncomingEvent(msg); - }; - - void OnScanResult( - uint16_t /* event_type */, - uint8_t address_type, - Address address, - uint8_t /* primary_phy */, - uint8_t /* secondary_phy */, - uint8_t /* advertising_sid */, - int8_t /* tx_power */, - int8_t rssi, - uint16_t /* periodic_advertising_interval */, - std::vector advertising_data) { + } + + void OnScanResult(uint16_t /* event_type */, uint8_t address_type, Address address, + uint8_t /* primary_phy */, uint8_t /* secondary_phy */, + uint8_t /* advertising_sid */, int8_t /* tx_power */, int8_t rssi, + uint16_t /* periodic_advertising_interval */, + std::vector advertising_data) { AdvertisingReportMsg advertising_report_msg; std::vector advertisements; LeExtendedAdvertisingResponseRaw le_extended_advertising_report; @@ -150,61 +134,46 @@ class LeScanningManagerFacadeService : public LeScanningManagerFacade::Service, builder->Serialize(bit_inserter); advertising_report_msg.set_event(std::string(bytes.begin(), bytes.end())); advertising_reports_.OnIncomingEvent(std::move(advertising_report_msg)); - }; + } void OnTrackAdvFoundLost(AdvertisingFilterOnFoundOnLostInfo /* on_found_on_lost_info */){}; - void OnBatchScanReports( - int /* client_if */, - int /* status */, - int /* report_format */, - int /* num_records */, - std::vector /* data */){}; - void OnBatchScanThresholdCrossed(int /* client_if */){}; - void OnTimeout(){}; - void OnFilterEnable(Enable /* enable */, uint8_t /* status */){}; - void OnFilterParamSetup( - uint8_t /* available_spaces */, ApcfAction /* action */, uint8_t /* status */){}; - void OnFilterConfigCallback( - ApcfFilterType /* filter_type */, - uint8_t /* available_spaces */, - ApcfAction /* action */, - uint8_t /* status */){}; - - void OnPeriodicSyncStarted( - int /* reg_id */, - uint8_t /* status */, - uint16_t /* sync_handle */, - uint8_t /* advertising_sid */, - AddressWithType /* address_with_type */, - uint8_t /* phy */, - uint16_t /* interval */) override { + void OnBatchScanReports(int /* client_if */, int /* status */, int /* report_format */, + int /* num_records */, std::vector /* data */) {} + void OnBatchScanThresholdCrossed(int /* client_if */) {} + void OnTimeout() {} + void OnFilterEnable(Enable /* enable */, uint8_t /* status */) {} + void OnFilterParamSetup(uint8_t /* available_spaces */, ApcfAction /* action */, + uint8_t /* status */) {} + void OnFilterConfigCallback(ApcfFilterType /* filter_type */, uint8_t /* available_spaces */, + ApcfAction /* action */, uint8_t /* status */) {} + + void OnPeriodicSyncStarted(int /* reg_id */, uint8_t /* status */, uint16_t /* sync_handle */, + uint8_t /* advertising_sid */, AddressWithType /* address_with_type */, + uint8_t /* phy */, uint16_t /* interval */) override { log::info("OnPeriodicSyncStarted in LeScanningManagerFacadeService"); - }; - - void OnPeriodicSyncReport( - uint16_t /* sync_handle */, - int8_t /* tx_power */, - int8_t /* rssi */, - uint8_t /* status */, - std::vector /* data */) override { + } + + void OnPeriodicSyncReport(uint16_t /* sync_handle */, int8_t /* tx_power */, int8_t /* rssi */, + uint8_t /* status */, std::vector /* data */) override { log::info("OnPeriodicSyncReport in LeScanningManagerFacadeService"); - }; + } void OnPeriodicSyncLost(uint16_t /* sync_handle */) override { log::info("OnPeriodicSyncLost in LeScanningManagerFacadeService"); - }; + } - void OnPeriodicSyncTransferred( - int /* pa_source */, uint8_t /* status */, Address /* address */) override { + void OnPeriodicSyncTransferred(int /* pa_source */, uint8_t /* status */, + Address /* address */) override { log::info("OnPeriodicSyncTransferred in LeScanningManagerFacadeService"); - }; + } void OnBigInfoReport(uint16_t /* sync_handle */, bool /* encrypted */) override { log::info("OnBigInfoReport in LeScanningManagerFacadeService"); - }; + } LeScanningManager* le_scanning_manager_; os::Handler* facade_handler_; - ::bluetooth::grpc::GrpcEventQueue advertising_reports_{"advertising reports"}; + ::bluetooth::grpc::GrpcEventQueue advertising_reports_{ + "advertising reports"}; ::bluetooth::grpc::GrpcEventQueue callback_events_{"callback events"}; }; @@ -215,7 +184,8 @@ void LeScanningManagerFacadeModule::ListDependencies(ModuleList* list) const { void LeScanningManagerFacadeModule::Start() { ::bluetooth::grpc::GrpcFacadeModule::Start(); - service_ = new LeScanningManagerFacadeService(GetDependency(), GetHandler()); + service_ = + new LeScanningManagerFacadeService(GetDependency(), GetHandler()); } void LeScanningManagerFacadeModule::Stop() { @@ -223,12 +193,10 @@ void LeScanningManagerFacadeModule::Stop() { ::bluetooth::grpc::GrpcFacadeModule::Stop(); } -::grpc::Service* LeScanningManagerFacadeModule::GetService() const { - return service_; -} +::grpc::Service* LeScanningManagerFacadeModule::GetService() const { return service_; } const ModuleFactory LeScanningManagerFacadeModule::Factory = - ::bluetooth::ModuleFactory([]() { return new LeScanningManagerFacadeModule(); }); + ::bluetooth::ModuleFactory([]() { return new LeScanningManagerFacadeModule(); }); } // namespace facade } // namespace hci diff --git a/system/gd/hci/facade/le_scanning_manager_facade.h b/system/gd/hci/facade/le_scanning_manager_facade.h index 95ec2cfa014..a3e68315d86 100644 --- a/system/gd/hci/facade/le_scanning_manager_facade.h +++ b/system/gd/hci/facade/le_scanning_manager_facade.h @@ -26,7 +26,7 @@ namespace facade { class LeScanningManagerFacadeService; class LeScanningManagerFacadeModule : public ::bluetooth::grpc::GrpcFacadeModule { - public: +public: static const ModuleFactory Factory; void ListDependencies(ModuleList* list) const override; @@ -35,7 +35,7 @@ class LeScanningManagerFacadeModule : public ::bluetooth::grpc::GrpcFacadeModule ::grpc::Service* GetService() const override; - private: +private: LeScanningManagerFacadeService* service_; }; diff --git a/system/gd/hci/fuzz/acl_manager_fuzz_test.cc b/system/gd/hci/fuzz/acl_manager_fuzz_test.cc index 26d99833d7a..53bf55d6f47 100644 --- a/system/gd/hci/fuzz/acl_manager_fuzz_test.cc +++ b/system/gd/hci/fuzz/acl_manager_fuzz_test.cc @@ -14,8 +14,10 @@ * limitations under the License. */ +#include #include #include + #include "fuzz/helpers.h" #include "hci/acl_manager.h" #include "hci/fuzz/fuzz_hci_layer.h" @@ -24,8 +26,6 @@ #include "os/fake_timer/fake_timerfd.h" #include "os/log.h" -#include - using bluetooth::FuzzTestModuleRegistry; using bluetooth::fuzz::GetArbitraryBytes; using bluetooth::hci::AclManager; @@ -57,7 +57,8 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { switch (action) { case 1: { - uint64_t advanceTime = dataProvider.ConsumeIntegralInRange(kMinTimeAdvanced, kMaxTotalTimeAdvanced); + uint64_t advanceTime = dataProvider.ConsumeIntegralInRange(kMinTimeAdvanced, + kMaxTotalTimeAdvanced); totalAdvanceTime += advanceTime; if (totalAdvanceTime < kMaxTotalTimeAdvanced) { fake_timerfd_advance(advanceTime); diff --git a/system/gd/hci/fuzz/fuzz_hci_layer.cc b/system/gd/hci/fuzz/fuzz_hci_layer.cc index cb3862cc702..64115ec253b 100644 --- a/system/gd/hci/fuzz/fuzz_hci_layer.cc +++ b/system/gd/hci/fuzz/fuzz_hci_layer.cc @@ -28,59 +28,51 @@ using bluetooth::fuzz::GetArbitraryBytes; using bluetooth::fuzz::InvokeIfValid; hci::SecurityInterface* FuzzHciLayer::GetSecurityInterface( - ContextualCallback /* event_handler */) { + ContextualCallback /* event_handler */) { return &security_interface_; } hci::LeSecurityInterface* FuzzHciLayer::GetLeSecurityInterface( - ContextualCallback /* event_handler */) { + ContextualCallback /* event_handler */) { return &le_security_interface_; } hci::AclConnectionInterface* FuzzHciLayer::GetAclConnectionInterface( - ContextualCallback /* event_handler */, - ContextualCallback /* on_disconnect */, - ContextualCallback /* on_connection_request */, - ContextualCallback - /* on_read_remote_version */) { + ContextualCallback /* event_handler */, + ContextualCallback /* on_disconnect */, + ContextualCallback /* on_connection_request */, + ContextualCallback + /* on_read_remote_version */) { return &acl_connection_interface_; } hci::LeAclConnectionInterface* FuzzHciLayer::GetLeAclConnectionInterface( - ContextualCallback /* event_handler */, - ContextualCallback /* on_disconnect */, - ContextualCallback - /* on_read_remote_version */) { + ContextualCallback /* event_handler */, + ContextualCallback /* on_disconnect */, + ContextualCallback + /* on_read_remote_version */) { return &le_acl_connection_interface_; } hci::LeAdvertisingInterface* FuzzHciLayer::GetLeAdvertisingInterface( - ContextualCallback /* event_handler */) { + ContextualCallback /* event_handler */) { return &le_advertising_interface_; } hci::LeScanningInterface* FuzzHciLayer::GetLeScanningInterface( - ContextualCallback /* event_handler */) { + ContextualCallback /* event_handler */) { return &le_scanning_interface_; } hci::LeIsoInterface* FuzzHciLayer::GetLeIsoInterface( - ContextualCallback /* event_handler */) { + ContextualCallback /* event_handler */) { return &le_iso_interface_; } hci::DistanceMeasurementInterface* FuzzHciLayer::GetDistanceMeasurementInterface( - ContextualCallback /* event_handler */) { + ContextualCallback /* event_handler */) { return &distance_measurement_interface_; } @@ -162,7 +154,8 @@ void FuzzHciLayer::injectEvent(FuzzedDataProvider& fdp) { } void FuzzHciLayer::injectLeEvent(FuzzedDataProvider& fdp) { - auto handler_pair = le_event_handlers_.find(static_cast(fdp.ConsumeIntegral())); + auto handler_pair = + le_event_handlers_.find(static_cast(fdp.ConsumeIntegral())); if (handler_pair != le_event_handlers_.end()) { InvokeIfValid(handler_pair->second, GetArbitraryBytes(&fdp)); } @@ -182,9 +175,8 @@ void FuzzHciLayer::injectAclEvent(std::vector data) { void FuzzHciLayer::injectAclDisconnect(FuzzedDataProvider& fdp) { if (acl_on_disconnect_) { - acl_on_disconnect_( - fdp.ConsumeIntegral(), - static_cast(fdp.ConsumeIntegral())); + acl_on_disconnect_(fdp.ConsumeIntegral(), + static_cast(fdp.ConsumeIntegral())); } } @@ -194,9 +186,8 @@ void FuzzHciLayer::injectLeAclEvent(std::vector data) { void FuzzHciLayer::injectLeAclDisconnect(FuzzedDataProvider& fdp) { if (le_acl_on_disconnect_) { - le_acl_on_disconnect_( - fdp.ConsumeIntegral(), - static_cast(fdp.ConsumeIntegral())); + le_acl_on_disconnect_(fdp.ConsumeIntegral(), + static_cast(fdp.ConsumeIntegral())); } } diff --git a/system/gd/hci/fuzz/fuzz_hci_layer.h b/system/gd/hci/fuzz/fuzz_hci_layer.h index 8ef87646871..07a58fdc74c 100644 --- a/system/gd/hci/fuzz/fuzz_hci_layer.h +++ b/system/gd/hci/fuzz/fuzz_hci_layer.h @@ -34,29 +34,26 @@ namespace fuzz { template class FuzzCommandInterface : public CommandInterface { - public: +public: void EnqueueCommand( - std::unique_ptr /* command */, - common::ContextualOnceCallback /* on_complete */) override {} + std::unique_ptr /* command */, + common::ContextualOnceCallback /* on_complete */) + override {} void EnqueueCommand( - std::unique_ptr /* command */, - common::ContextualOnceCallback /* on_status */) override {} + std::unique_ptr /* command */, + common::ContextualOnceCallback /* on_status */) override {} }; class FuzzHciLayer : public HciLayer { - public: - void TurnOnAutoReply(FuzzedDataProvider* fdp) { - auto_reply_fdp = fdp; - } +public: + void TurnOnAutoReply(FuzzedDataProvider* fdp) { auto_reply_fdp = fdp; } - void TurnOffAutoReply() { - auto_reply_fdp = nullptr; - } + void TurnOffAutoReply() { auto_reply_fdp = nullptr; } void EnqueueCommand( - std::unique_ptr /* command */, - common::ContextualOnceCallback on_complete) override { + std::unique_ptr /* command */, + common::ContextualOnceCallback on_complete) override { on_command_complete_ = std::move(on_complete); if (auto_reply_fdp != nullptr) { injectCommandComplete(bluetooth::fuzz::GetArbitraryBytes(auto_reply_fdp)); @@ -64,8 +61,8 @@ class FuzzHciLayer : public HciLayer { } void EnqueueCommand( - std::unique_ptr /* command */, - common::ContextualOnceCallback on_status) override { + std::unique_ptr /* command */, + common::ContextualOnceCallback on_status) override { on_command_status_ = std::move(on_status); if (auto_reply_fdp != nullptr) { injectCommandStatus(bluetooth::fuzz::GetArbitraryBytes(auto_reply_fdp)); @@ -84,7 +81,8 @@ class FuzzHciLayer : public HciLayer { return sco_queue_.GetUpEnd(); } - void RegisterEventHandler(hci::EventCode event, common::ContextualCallback handler) override { + void RegisterEventHandler(hci::EventCode event, + common::ContextualCallback handler) override { event_handlers_[event] = handler; } @@ -95,8 +93,9 @@ class FuzzHciLayer : public HciLayer { } } - void RegisterLeEventHandler(hci::SubeventCode event, - common::ContextualCallback handler) override { + void RegisterLeEventHandler( + hci::SubeventCode event, + common::ContextualCallback handler) override { le_event_handlers_[event] = handler; } @@ -107,52 +106,53 @@ class FuzzHciLayer : public HciLayer { } } - hci::SecurityInterface* GetSecurityInterface(common::ContextualCallback event_handler) override; + hci::SecurityInterface* GetSecurityInterface( + common::ContextualCallback event_handler) override; hci::LeSecurityInterface* GetLeSecurityInterface( - common::ContextualCallback event_handler) override; + common::ContextualCallback event_handler) override; hci::AclConnectionInterface* GetAclConnectionInterface( - common::ContextualCallback event_handler, - common::ContextualCallback on_disconnect, - common::ContextualCallback on_connection_request, - common::ContextualCallback on_read_remote_version) - override; + common::ContextualCallback event_handler, + common::ContextualCallback on_disconnect, + common::ContextualCallback on_connection_request, + common::ContextualCallback + on_read_remote_version) override; void PutAclConnectionInterface() override {} hci::LeAclConnectionInterface* GetLeAclConnectionInterface( - common::ContextualCallback event_handler, - common::ContextualCallback on_disconnect, - common::ContextualCallback - on_read_remote_version) override; + common::ContextualCallback event_handler, + common::ContextualCallback on_disconnect, + common::ContextualCallback + on_read_remote_version) override; void PutLeAclConnectionInterface() override {} hci::LeAdvertisingInterface* GetLeAdvertisingInterface( - common::ContextualCallback event_handler) override; + common::ContextualCallback event_handler) override; hci::LeScanningInterface* GetLeScanningInterface( - common::ContextualCallback event_handler) override; + common::ContextualCallback event_handler) override; - hci::LeIsoInterface* GetLeIsoInterface(common::ContextualCallback event_handler) override; + hci::LeIsoInterface* GetLeIsoInterface( + common::ContextualCallback event_handler) override; hci::DistanceMeasurementInterface* GetDistanceMeasurementInterface( - common::ContextualCallback event_handler) override; + common::ContextualCallback event_handler) override; void injectArbitrary(FuzzedDataProvider& fdp); - std::string ToString() const override { - return "FuzzHciLayer"; - } + std::string ToString() const override { return "FuzzHciLayer"; } static const ModuleFactory Factory; - protected: +protected: void ListDependencies(ModuleList* /* list */) const override {} void Start() override; void Stop() override; - private: +private: void injectAclData(std::vector data); void injectCommandComplete(std::vector data); @@ -195,7 +195,8 @@ class FuzzHciLayer : public HciLayer { common::ContextualOnceCallback on_command_status_; std::map> event_handlers_; - std::map> le_event_handlers_; + std::map> + le_event_handlers_; common::ContextualCallback security_event_handler_; common::ContextualCallback le_security_event_handler_; diff --git a/system/gd/hci/fuzz/hci_layer_fuzz_client.cc b/system/gd/hci/fuzz/hci_layer_fuzz_client.cc index 0a6dfa5b6da..6ca1b15f994 100644 --- a/system/gd/hci/fuzz/hci_layer_fuzz_client.cc +++ b/system/gd/hci/fuzz/hci_layer_fuzz_client.cc @@ -25,7 +25,8 @@ namespace fuzz { using bluetooth::fuzz::GetArbitraryBytes; using bluetooth::hci::AclView; -const ModuleFactory HciLayerFuzzClient::Factory = ModuleFactory([]() { return new HciLayerFuzzClient(); }); +const ModuleFactory HciLayerFuzzClient::Factory = + ModuleFactory([]() { return new HciLayerFuzzClient(); }); void HciLayerFuzzClient::Start() { hci_ = GetDependency(); @@ -33,22 +34,23 @@ void HciLayerFuzzClient::Start() { aclDevNull_->Start(); aclInject_ = new os::fuzz::FuzzInjectQueue(hci_->GetAclQueueEnd(), GetHandler()); - // Can't do security right now, due to the Encryption Change conflict between ACL manager & security - // security_interface_ = hci_->GetSecurityInterface(common::Bind([](EventView){}), GetHandler()); + // Can't do security right now, due to the Encryption Change conflict between ACL manager & + // security security_interface_ = hci_->GetSecurityInterface(common::Bind([](EventView){}), + // GetHandler()); le_security_interface_ = hci_->GetLeSecurityInterface(GetHandler()->Bind([](LeMetaEventView) {})); acl_connection_interface_ = hci_->GetAclConnectionInterface( - GetHandler()->Bind([](EventView) {}), - GetHandler()->Bind([](uint16_t, hci::ErrorCode) {}), - GetHandler()->Bind([](Address, ClassOfDevice) {}), - GetHandler()->Bind([](hci::ErrorCode, uint16_t, uint8_t, uint16_t, uint16_t) {})); + GetHandler()->Bind([](EventView) {}), GetHandler()->Bind([](uint16_t, hci::ErrorCode) {}), + GetHandler()->Bind([](Address, ClassOfDevice) {}), + GetHandler()->Bind([](hci::ErrorCode, uint16_t, uint8_t, uint16_t, uint16_t) {})); le_acl_connection_interface_ = hci_->GetLeAclConnectionInterface( - GetHandler()->Bind([](LeMetaEventView) {}), - GetHandler()->Bind([](uint16_t, hci::ErrorCode) {}), - GetHandler()->Bind([](hci::ErrorCode, uint16_t, uint8_t, uint16_t, uint16_t) {})); - le_advertising_interface_ = hci_->GetLeAdvertisingInterface(GetHandler()->Bind([](LeMetaEventView) {})); + GetHandler()->Bind([](LeMetaEventView) {}), + GetHandler()->Bind([](uint16_t, hci::ErrorCode) {}), + GetHandler()->Bind([](hci::ErrorCode, uint16_t, uint8_t, uint16_t, uint16_t) {})); + le_advertising_interface_ = + hci_->GetLeAdvertisingInterface(GetHandler()->Bind([](LeMetaEventView) {})); le_scanning_interface_ = hci_->GetLeScanningInterface(GetHandler()->Bind([](LeMetaEventView) {})); distance_measurement_interface_ = - hci_->GetDistanceMeasurementInterface(GetHandler()->Bind([](LeMetaEventView) {})); + hci_->GetDistanceMeasurementInterface(GetHandler()->Bind([](LeMetaEventView) {})); } void HciLayerFuzzClient::Stop() { @@ -117,7 +119,8 @@ void HciLayerFuzzClient::injectLeAclConnectionCommand(std::vector data) } void HciLayerFuzzClient::injectLeAdvertisingCommand(std::vector data) { - inject_command(data, le_advertising_interface_); + inject_command(data, + le_advertising_interface_); } void HciLayerFuzzClient::injectLeScanningCommand(std::vector data) { diff --git a/system/gd/hci/fuzz/hci_layer_fuzz_client.h b/system/gd/hci/fuzz/hci_layer_fuzz_client.h index 144f65063b9..3ec1ef34e82 100644 --- a/system/gd/hci/fuzz/hci_layer_fuzz_client.h +++ b/system/gd/hci/fuzz/hci_layer_fuzz_client.h @@ -34,7 +34,7 @@ namespace hci { namespace fuzz { class HciLayerFuzzClient : public Module { - public: +public: HciLayerFuzzClient() : Module() {} void Start() override; @@ -42,17 +42,13 @@ class HciLayerFuzzClient : public Module { void injectArbitrary(FuzzedDataProvider& fdp); - void ListDependencies(ModuleList* list) const override { - list->add(); - } + void ListDependencies(ModuleList* list) const override { list->add(); } static const ModuleFactory Factory; - std::string ToString() const override { - return "DevNullHci"; - } + std::string ToString() const override { return "DevNullHci"; } - private: +private: void injectAclData(std::vector data); void injectHciCommand(std::vector data); void injectSecurityCommand(std::vector data); @@ -70,13 +66,11 @@ class HciLayerFuzzClient : public Module { } if (uses_command_status(commandPacket.GetOpCode())) { - interface->EnqueueCommand( - TBUILDER::FromView(commandPacket), - GetHandler()->BindOnce([](CommandStatusView /* status */) {})); + interface->EnqueueCommand(TBUILDER::FromView(commandPacket), + GetHandler()->BindOnce([](CommandStatusView /* status */) {})); } else { - interface->EnqueueCommand( - TBUILDER::FromView(commandPacket), - GetHandler()->BindOnce([](CommandCompleteView /* status */) {})); + interface->EnqueueCommand(TBUILDER::FromView(commandPacket), + GetHandler()->BindOnce([](CommandCompleteView /* status */) {})); } } diff --git a/system/gd/hci/fuzz/hci_layer_fuzz_test.cc b/system/gd/hci/fuzz/hci_layer_fuzz_test.cc index 8288f628cda..2c46fa2a0fb 100644 --- a/system/gd/hci/fuzz/hci_layer_fuzz_test.cc +++ b/system/gd/hci/fuzz/hci_layer_fuzz_test.cc @@ -14,8 +14,10 @@ * limitations under the License. */ +#include #include #include + #include "fuzz/helpers.h" #include "hal/fuzz/fuzz_hci_hal.h" #include "hci/fuzz/hci_layer_fuzz_client.h" @@ -24,8 +26,6 @@ #include "os/fake_timer/fake_timerfd.h" #include "os/log.h" -#include - using bluetooth::FuzzTestModuleRegistry; using bluetooth::fuzz::GetArbitraryBytes; using bluetooth::hal::HciHal; diff --git a/system/gd/hci/fuzz/status_vs_complete_commands.cc b/system/gd/hci/fuzz/status_vs_complete_commands.cc index cf4a5ff5fdf..1bed8ff07ab 100644 --- a/system/gd/hci/fuzz/status_vs_complete_commands.cc +++ b/system/gd/hci/fuzz/status_vs_complete_commands.cc @@ -15,6 +15,7 @@ */ #include "hci/fuzz/status_vs_complete_commands.h" + #include namespace bluetooth { @@ -24,7 +25,7 @@ namespace fuzz { using ::bluetooth::hci::OpCode; constexpr OpCode StatusOpCodes[] = { - OpCode::RESET, + OpCode::RESET, }; static std::map commands_that_use_status; diff --git a/system/gd/hci/hci_interface.h b/system/gd/hci/hci_interface.h index 06315c3f4e2..135ee8093b6 100644 --- a/system/gd/hci/hci_interface.h +++ b/system/gd/hci/hci_interface.h @@ -37,17 +37,17 @@ namespace bluetooth { namespace hci { class HciInterface : public CommandInterface { - public: +public: HciInterface() = default; virtual ~HciInterface() = default; virtual void EnqueueCommand( - std::unique_ptr command, - common::ContextualOnceCallback on_complete) override = 0; + std::unique_ptr command, + common::ContextualOnceCallback on_complete) override = 0; virtual void EnqueueCommand( - std::unique_ptr command, - common::ContextualOnceCallback on_status) override = 0; + std::unique_ptr command, + common::ContextualOnceCallback on_status) override = 0; virtual common::BidiQueueEnd* GetAclQueueEnd() = 0; @@ -55,79 +55,79 @@ class HciInterface : public CommandInterface { virtual common::BidiQueueEnd* GetIsoQueueEnd() = 0; - virtual void RegisterEventHandler( - EventCode event_code, common::ContextualCallback event_handler) = 0; + virtual void RegisterEventHandler(EventCode event_code, + common::ContextualCallback event_handler) = 0; virtual void UnregisterEventHandler(EventCode event_code) = 0; virtual void RegisterLeEventHandler( - SubeventCode subevent_code, - common::ContextualCallback event_handler) = 0; + SubeventCode subevent_code, + common::ContextualCallback event_handler) = 0; virtual void UnregisterLeEventHandler(SubeventCode subevent_code) = 0; virtual void RegisterVendorSpecificEventHandler( - VseSubeventCode subevent_code, - common::ContextualCallback event_handler) = 0; + VseSubeventCode subevent_code, + common::ContextualCallback event_handler) = 0; virtual void UnregisterVendorSpecificEventHandler(VseSubeventCode subevent_code) = 0; virtual void RegisterForDisconnects( - common::ContextualCallback on_disconnect) = 0; + common::ContextualCallback on_disconnect) = 0; virtual SecurityInterface* GetSecurityInterface( - common::ContextualCallback event_handler) = 0; + common::ContextualCallback event_handler) = 0; virtual LeSecurityInterface* GetLeSecurityInterface( - common::ContextualCallback event_handler) = 0; + common::ContextualCallback event_handler) = 0; virtual AclConnectionInterface* GetAclConnectionInterface( - common::ContextualCallback event_handler, - common::ContextualCallback on_disconnect, - common::ContextualCallback on_connection_request, - common::ContextualCallback - on_read_remote_version_complete) = 0; + common::ContextualCallback event_handler, + common::ContextualCallback on_disconnect, + common::ContextualCallback on_connection_request, + common::ContextualCallback + on_read_remote_version_complete) = 0; virtual void PutAclConnectionInterface() = 0; virtual LeAclConnectionInterface* GetLeAclConnectionInterface( - common::ContextualCallback event_handler, - common::ContextualCallback on_disconnect, - common::ContextualCallback - on_read_remote_version_complete) = 0; + common::ContextualCallback event_handler, + common::ContextualCallback on_disconnect, + common::ContextualCallback + on_read_remote_version_complete) = 0; virtual void PutLeAclConnectionInterface() = 0; virtual LeAdvertisingInterface* GetLeAdvertisingInterface( - common::ContextualCallback event_handler) = 0; + common::ContextualCallback event_handler) = 0; virtual LeScanningInterface* GetLeScanningInterface( - common::ContextualCallback event_handler) = 0; + common::ContextualCallback event_handler) = 0; virtual void RegisterForScoConnectionRequests( - common::ContextualCallback - on_sco_connection_request) = 0; + common::ContextualCallback + on_sco_connection_request) = 0; virtual LeIsoInterface* GetLeIsoInterface( - common::ContextualCallback event_handler) = 0; + common::ContextualCallback event_handler) = 0; virtual DistanceMeasurementInterface* GetDistanceMeasurementInterface( - common::ContextualCallback event_handler) = 0; + common::ContextualCallback event_handler) = 0; - protected: +protected: template class CommandInterfaceImpl : public CommandInterface { - public: + public: explicit CommandInterfaceImpl(HciInterface& hci) : hci_(hci) {} virtual ~CommandInterfaceImpl() = default; void EnqueueCommand( - std::unique_ptr command, - common::ContextualOnceCallback on_complete) override { + std::unique_ptr command, + common::ContextualOnceCallback on_complete) override { hci_.EnqueueCommand(std::move(command), std::move(on_complete)); } void EnqueueCommand( - std::unique_ptr command, - common::ContextualOnceCallback on_status) override { + std::unique_ptr command, + common::ContextualOnceCallback on_status) override { hci_.EnqueueCommand(std::move(command), std::move(on_status)); } HciInterface& hci_; diff --git a/system/gd/hci/hci_layer.cc b/system/gd/hci/hci_layer.cc index a1ceedfb229..650ec35cf3f 100644 --- a/system/gd/hci/hci_layer.cc +++ b/system/gd/hci/hci_layer.cc @@ -60,14 +60,14 @@ using std::unique_ptr; static std::chrono::milliseconds getHciTimeoutMs() { static auto sHciTimeoutMs = std::chrono::milliseconds(bluetooth::os::GetSystemPropertyUint32Base( - "bluetooth.hci.timeout_milliseconds", HciLayer::kHciTimeoutMs.count())); + "bluetooth.hci.timeout_milliseconds", HciLayer::kHciTimeoutMs.count())); return sHciTimeoutMs; } static std::chrono::milliseconds getHciTimeoutRestartMs() { - static auto sRestartHciTimeoutMs = - std::chrono::milliseconds(bluetooth::os::GetSystemPropertyUint32Base( - "bluetooth.hci.restart_timeout_milliseconds", HciLayer::kHciTimeoutRestartMs.count())); + static auto sRestartHciTimeoutMs = std::chrono::milliseconds( + bluetooth::os::GetSystemPropertyUint32Base("bluetooth.hci.restart_timeout_milliseconds", + HciLayer::kHciTimeoutRestartMs.count())); return sRestartHciTimeoutMs; } @@ -75,30 +75,25 @@ static void fail_if_reset_complete_not_success(CommandCompleteView complete) { auto reset_complete = ResetCompleteView::Create(complete); log::assert_that(reset_complete.IsValid(), "assert failed: reset_complete.IsValid()"); log::debug("Reset completed with status: {}", ErrorCodeText(ErrorCode::SUCCESS)); - log::assert_that( - reset_complete.GetStatus() == ErrorCode::SUCCESS, - "assert failed: reset_complete.GetStatus() == ErrorCode::SUCCESS"); + log::assert_that(reset_complete.GetStatus() == ErrorCode::SUCCESS, + "assert failed: reset_complete.GetStatus() == ErrorCode::SUCCESS"); } static void abort_after_time_out(OpCode op_code) { - log::fatal( - "Done waiting for debug information after HCI timeout ({}) for {}ms", - OpCodeText(op_code), - getHciTimeoutRestartMs().count()); + log::fatal("Done waiting for debug information after HCI timeout ({}) for {}ms", + OpCodeText(op_code), getHciTimeoutRestartMs().count()); } class CommandQueueEntry { - public: - CommandQueueEntry( - unique_ptr command_packet, - ContextualOnceCallback on_complete_function) +public: + CommandQueueEntry(unique_ptr command_packet, + ContextualOnceCallback on_complete_function) : command(std::move(command_packet)), waiting_for_status_(false), on_complete(std::move(on_complete_function)) {} - CommandQueueEntry( - unique_ptr command_packet, - ContextualOnceCallback on_status_function) + CommandQueueEntry(unique_ptr command_packet, + ContextualOnceCallback on_status_function) : command(std::move(command_packet)), waiting_for_status_(true), on_status(std::move(on_status_function)) {} @@ -173,7 +168,8 @@ struct HciLayer::impl { } template - void enqueue_command(unique_ptr command, ContextualOnceCallback on_response) { + void enqueue_command(unique_ptr command, + ContextualOnceCallback on_response) { command_queue_.emplace_back(std::move(command), std::move(on_response)); send_next_command(); } @@ -184,10 +180,8 @@ struct HciLayer::impl { OpCode op_code = response_view.GetCommandOpCode(); ErrorCode status = response_view.GetStatus(); if (status != ErrorCode::SUCCESS) { - log::error( - "Received UNEXPECTED command status:{} opcode:{}", - ErrorCodeText(status), - OpCodeText(op_code)); + log::error("Received UNEXPECTED command status:{} opcode:{}", ErrorCodeText(status), + OpCodeText(op_code)); } handle_command_response(event, "status"); } @@ -208,21 +202,16 @@ struct HciLayer::impl { } bool is_status = logging_id == "status"; - log::assert_that( - !command_queue_.empty(), - "Unexpected {} event with OpCode {}", - logging_id, - OpCodeText(op_code)); - if (waiting_command_ == OpCode::CONTROLLER_DEBUG_INFO && op_code != OpCode::CONTROLLER_DEBUG_INFO) { + log::assert_that(!command_queue_.empty(), "Unexpected {} event with OpCode {}", logging_id, + OpCodeText(op_code)); + if (waiting_command_ == OpCode::CONTROLLER_DEBUG_INFO && + op_code != OpCode::CONTROLLER_DEBUG_INFO) { log::error("Discarding event that came after timeout {}", OpCodeText(op_code)); common::StopWatch::DumpStopWatchLog(); return; } - log::assert_that( - waiting_command_ == op_code, - "Waiting for {}, got {}", - OpCodeText(waiting_command_), - OpCodeText(op_code)); + log::assert_that(waiting_command_ == op_code, "Waiting for {}, got {}", + OpCodeText(waiting_command_), OpCodeText(op_code)); bool is_vendor_specific = static_cast(op_code) & (0x3f << 10); CommandStatusView status_view = CommandStatusView::Create(event); @@ -235,23 +224,19 @@ struct HciLayer::impl { auto payload = std::make_unique(); payload->AddOctets1(static_cast(status_view.GetStatus())); - auto complete_event_builder = CommandCompleteBuilder::Create( - status_view.GetNumHciCommandPackets(), - status_view.GetCommandOpCode(), - std::move(payload)); - auto complete = - std::make_shared>(complete_event_builder->SerializeToBytes()); + auto complete_event_builder = + CommandCompleteBuilder::Create(status_view.GetNumHciCommandPackets(), + status_view.GetCommandOpCode(), std::move(payload)); + auto complete = std::make_shared>( + complete_event_builder->SerializeToBytes()); CommandCompleteView command_complete_view = - CommandCompleteView::Create(EventView::Create(PacketView(complete))); - log::assert_that( - command_complete_view.IsValid(), "assert failed: command_complete_view.IsValid()"); + CommandCompleteView::Create(EventView::Create(PacketView(complete))); + log::assert_that(command_complete_view.IsValid(), + "assert failed: command_complete_view.IsValid()"); (*command_queue_.front().GetCallback())(command_complete_view); } else { - log::assert_that( - command_queue_.front().waiting_for_status_ == is_status, - "{} was not expecting {} event", - OpCodeText(op_code), - logging_id); + log::assert_that(command_queue_.front().waiting_for_status_ == is_status, + "{} was not expecting {} event", OpCodeText(op_code), logging_id); (*command_queue_.front().GetCallback())(std::move(response_view)); } @@ -266,7 +251,7 @@ struct HciLayer::impl { status_view.GetStatus() == ErrorCode::UNKNOWN_CONNECTION) { auto& command_view = *command_queue_.front().command_view; auto le_read_features_view = bluetooth::hci::LeReadRemoteFeaturesView::Create( - LeConnectionManagementCommandView::Create(AclCommandView::Create(command_view))); + LeConnectionManagementCommandView::Create(AclCommandView::Create(command_view))); if (le_read_features_view.IsValid()) { uint16_t handle = le_read_features_view.GetConnectionHandle(); module_.Disconnect(handle, ErrorCode::UNKNOWN_CONNECTION); @@ -294,7 +279,8 @@ struct HciLayer::impl { command_credits_ = 1; waiting_command_ = OpCode::NONE; // Ignore the response, since we don't know what might come back. - enqueue_command(ControllerDebugInfoBuilder::Create(), module_.GetHandler()->BindOnce([](CommandCompleteView) {})); + enqueue_command(ControllerDebugInfoBuilder::Create(), + module_.GetHandler()->BindOnce([](CommandCompleteView) {})); // Don't time out for this one; if (hci_timeout_alarm_ != nullptr) { hci_timeout_alarm_->Cancel(); @@ -303,8 +289,8 @@ struct HciLayer::impl { } if (hci_abort_alarm_ == nullptr) { hci_abort_alarm_ = new Alarm(module_.GetHandler()); - hci_abort_alarm_->Schedule( - BindOnce(&abort_after_time_out, op_code), getHciTimeoutRestartMs()); + hci_abort_alarm_->Schedule(BindOnce(&abort_after_time_out, op_code), + getHciTimeoutRestartMs()); } else { log::warn("Unable to schedul abort timer"); } @@ -331,43 +317,37 @@ struct HciLayer::impl { power_telemetry::GetInstance().LogHciCmdDetail(); command_queue_.front().command_view = std::make_unique(std::move(cmd_view)); log_link_layer_connection_command(command_queue_.front().command_view); - log_classic_pairing_command_status(command_queue_.front().command_view, ErrorCode::STATUS_UNKNOWN); + log_classic_pairing_command_status(command_queue_.front().command_view, + ErrorCode::STATUS_UNKNOWN); waiting_command_ = op_code; command_credits_ = 0; // Only allow one outstanding command if (hci_timeout_alarm_ != nullptr) { hci_timeout_alarm_->Schedule( - BindOnce(&impl::on_hci_timeout, common::Unretained(this), op_code), getHciTimeoutMs()); + BindOnce(&impl::on_hci_timeout, common::Unretained(this), op_code), + getHciTimeoutMs()); } else { log::warn("{} sent without an hci-timeout timer", OpCodeText(op_code)); } } void register_event(EventCode event, ContextualCallback handler) { - log::assert_that( - event != EventCode::LE_META_EVENT, - "Can not register handler for {}", - EventCodeText(EventCode::LE_META_EVENT)); + log::assert_that(event != EventCode::LE_META_EVENT, "Can not register handler for {}", + EventCodeText(EventCode::LE_META_EVENT)); // Allow GD Cert tests to register for CONNECTION_REQUEST if (event == EventCode::CONNECTION_REQUEST && !module_.on_acl_connection_request_) { log::info("Registering test for CONNECTION_REQUEST, since there's no ACL"); event_handlers_.erase(event); } - log::assert_that( - event_handlers_.count(event) == 0, - "Can not register a second handler for {}", - EventCodeText(event)); + log::assert_that(event_handlers_.count(event) == 0, "Can not register a second handler for {}", + EventCodeText(event)); event_handlers_[event] = handler; } - void unregister_event(EventCode event) { - event_handlers_.erase(event); - } + void unregister_event(EventCode event) { event_handlers_.erase(event); } void register_le_event(SubeventCode event, ContextualCallback handler) { - log::assert_that( - le_event_handlers_.count(event) == 0, - "Can not register a second handler for {}", - SubeventCodeText(event)); + log::assert_that(le_event_handlers_.count(event) == 0, + "Can not register a second handler for {}", SubeventCodeText(event)); le_event_handlers_[event] = handler; } @@ -375,12 +355,10 @@ struct HciLayer::impl { le_event_handlers_.erase(le_event_handlers_.find(event)); } - void register_vs_event( - VseSubeventCode event, ContextualCallback handler) { - log::assert_that( - vs_event_handlers_.count(event) == 0, - "Can not register a second handler for {}", - VseSubeventCodeText(event)); + void register_vs_event(VseSubeventCode event, + ContextualCallback handler) { + log::assert_that(vs_event_handlers_.count(event) == 0, + "Can not register a second handler for {}", VseSubeventCodeText(event)); vs_event_handlers_[event] = handler; } @@ -393,9 +371,8 @@ struct HciLayer::impl { } void handle_root_inflammation(uint8_t vse_error_reason) { - log::error( - "Received a Root Inflammation Event vendor reason 0x{:02x}, scheduling an abort", - vse_error_reason); + log::error("Received a Root Inflammation Event vendor reason 0x{:02x}, scheduling an abort", + vse_error_reason); bluetooth::os::LogMetricBluetoothHalCrashReason(Address::kEmpty, 0, vse_error_reason); // Add Logging for crash reason if (hci_timeout_alarm_ != nullptr) { @@ -405,8 +382,8 @@ struct HciLayer::impl { } if (hci_abort_alarm_ == nullptr) { hci_abort_alarm_ = new Alarm(module_.GetHandler()); - hci_abort_alarm_->Schedule( - BindOnce(&abort_after_root_inflammation, vse_error_reason), getHciTimeoutRestartMs()); + hci_abort_alarm_->Schedule(BindOnce(&abort_after_root_inflammation, vse_error_reason), + getHciTimeoutRestartMs()); } else { log::warn("Abort timer already scheduled"); } @@ -422,28 +399,25 @@ struct HciLayer::impl { auto view = CommandCompleteView::Create(event); log::assert_that(view.IsValid(), "assert failed: view.IsValid()"); auto op_code = view.GetCommandOpCode(); - log::assert_that( - op_code == OpCode::NONE, - "Received {} event with OpCode {} without a waiting command(is the HAL " - "sending commands, but not handling the events?)", - EventCodeText(event_code), - OpCodeText(op_code)); + log::assert_that(op_code == OpCode::NONE, + "Received {} event with OpCode {} without a waiting command(is the HAL " + "sending commands, but not handling the events?)", + EventCodeText(event_code), OpCodeText(op_code)); } if (event_code == EventCode::COMMAND_STATUS) { auto view = CommandStatusView::Create(event); log::assert_that(view.IsValid(), "assert failed: view.IsValid()"); auto op_code = view.GetCommandOpCode(); - log::assert_that( - op_code == OpCode::NONE, - "Received {} event with OpCode {} without a waiting command(is the HAL " - "sending commands, but not handling the events?)", - EventCodeText(event_code), - OpCodeText(op_code)); + log::assert_that(op_code == OpCode::NONE, + "Received {} event with OpCode {} without a waiting command(is the HAL " + "sending commands, but not handling the events?)", + EventCodeText(event_code), OpCodeText(op_code)); } std::unique_ptr no_waiting_command{nullptr}; log_hci_event(no_waiting_command, event, module_.GetDependency()); } else { - log_hci_event(command_queue_.front().command_view, event, module_.GetDependency()); + log_hci_event(command_queue_.front().command_view, event, + module_.GetDependency()); } power_telemetry::GetInstance().LogHciEvtDetail(); EventCode event_code = event.GetEventCode(); @@ -554,28 +528,29 @@ struct HciLayer::hal_callbacks : public hal::HciHalCallbacks { hal_callbacks(HciLayer& module) : module_(module) {} void hciEventReceived(hal::HciPacket event_bytes) override { - auto packet = packet::PacketView(std::make_shared>(event_bytes)); + auto packet = packet::PacketView( + std::make_shared>(event_bytes)); EventView event = EventView::Create(packet); module_.CallOn(module_.impl_, &impl::on_hci_event, std::move(event)); } void aclDataReceived(hal::HciPacket data_bytes) override { auto packet = packet::PacketView( - std::make_shared>(std::move(data_bytes))); + std::make_shared>(std::move(data_bytes))); auto acl = std::make_unique(AclView::Create(packet)); module_.impl_->incoming_acl_buffer_.Enqueue(std::move(acl), module_.GetHandler()); } void scoDataReceived(hal::HciPacket data_bytes) override { auto packet = packet::PacketView( - std::make_shared>(std::move(data_bytes))); + std::make_shared>(std::move(data_bytes))); auto sco = std::make_unique(ScoView::Create(packet)); module_.impl_->incoming_sco_buffer_.Enqueue(std::move(sco), module_.GetHandler()); } void isoDataReceived(hal::HciPacket data_bytes) override { auto packet = packet::PacketView( - std::make_shared>(std::move(data_bytes))); + std::make_shared>(std::move(data_bytes))); auto iso = std::make_unique(IsoView::Create(packet)); module_.impl_->incoming_iso_buffer_.Enqueue(std::move(iso), module_.GetHandler()); } @@ -599,19 +574,16 @@ common::BidiQueueEnd* HciLayer::GetIsoQueueEnd() { return impl_->iso_queue_.GetUpEnd(); } -void HciLayer::EnqueueCommand( - unique_ptr command, ContextualOnceCallback on_complete) { - CallOn( - impl_, - &impl::enqueue_command, - std::move(command), - std::move(on_complete)); +void HciLayer::EnqueueCommand(unique_ptr command, + ContextualOnceCallback on_complete) { + CallOn(impl_, &impl::enqueue_command, std::move(command), + std::move(on_complete)); } -void HciLayer::EnqueueCommand( - unique_ptr command, ContextualOnceCallback on_status) { - CallOn( - impl_, &impl::enqueue_command, std::move(command), std::move(on_status)); +void HciLayer::EnqueueCommand(unique_ptr command, + ContextualOnceCallback on_status) { + CallOn(impl_, &impl::enqueue_command, std::move(command), + std::move(on_status)); } void HciLayer::RegisterEventHandler(EventCode event, ContextualCallback handler) { @@ -622,7 +594,8 @@ void HciLayer::UnregisterEventHandler(EventCode event) { CallOn(impl_, &impl::unregister_event, event); } -void HciLayer::RegisterLeEventHandler(SubeventCode event, ContextualCallback handler) { +void HciLayer::RegisterLeEventHandler(SubeventCode event, + ContextualCallback handler) { CallOn(impl_, &impl::register_le_event, event, handler); } @@ -631,7 +604,7 @@ void HciLayer::UnregisterLeEventHandler(SubeventCode event) { } void HciLayer::RegisterVendorSpecificEventHandler( - VseSubeventCode event, ContextualCallback handler) { + VseSubeventCode event, ContextualCallback handler) { CallOn(impl_, &impl::register_vs_event, event, handler); } @@ -695,16 +668,12 @@ void HciLayer::RegisterForDisconnects(ContextualCallback lock(callback_handlers_guard_); for (auto callback : read_remote_version_handlers_) { callback(hci_status, handle, version, manufacturer_name, sub_version); @@ -712,15 +681,12 @@ void HciLayer::ReadRemoteVersion( } AclConnectionInterface* HciLayer::GetAclConnectionInterface( - ContextualCallback event_handler, - ContextualCallback on_disconnect, - ContextualCallback on_connection_request, - ContextualCallback on_read_remote_version) { + ContextualCallback event_handler, + ContextualCallback on_disconnect, + ContextualCallback on_connection_request, + ContextualCallback + on_read_remote_version) { { std::unique_lock lock(callback_handlers_guard_); disconnect_handlers_.push_back(on_disconnect); @@ -745,11 +711,11 @@ void HciLayer::PutAclConnectionInterface() { } LeAclConnectionInterface* HciLayer::GetLeAclConnectionInterface( - ContextualCallback event_handler, - ContextualCallback on_disconnect, - ContextualCallback< - void(hci::ErrorCode hci_status, uint16_t, uint8_t version, uint16_t manufacturer_name, uint16_t sub_version)> - on_read_remote_version) { + ContextualCallback event_handler, + ContextualCallback on_disconnect, + ContextualCallback + on_read_remote_version) { { std::unique_lock lock(callback_handlers_guard_); disconnect_handlers_.push_back(on_disconnect); @@ -773,41 +739,46 @@ void HciLayer::PutLeAclConnectionInterface() { } void HciLayer::RegisterForScoConnectionRequests( - common::ContextualCallback - on_sco_connection_request) { + common::ContextualCallback + on_sco_connection_request) { std::unique_lock lock(callback_handlers_guard_); on_sco_connection_request_ = on_sco_connection_request; } -SecurityInterface* HciLayer::GetSecurityInterface(ContextualCallback event_handler) { +SecurityInterface* HciLayer::GetSecurityInterface( + ContextualCallback event_handler) { for (const auto event : SecurityEvents) { RegisterEventHandler(event, event_handler); } return &security_interface; } -LeSecurityInterface* HciLayer::GetLeSecurityInterface(ContextualCallback event_handler) { +LeSecurityInterface* HciLayer::GetLeSecurityInterface( + ContextualCallback event_handler) { for (const auto subevent : LeSecurityEvents) { RegisterLeEventHandler(subevent, event_handler); } return &le_security_interface; } -LeAdvertisingInterface* HciLayer::GetLeAdvertisingInterface(ContextualCallback event_handler) { +LeAdvertisingInterface* HciLayer::GetLeAdvertisingInterface( + ContextualCallback event_handler) { for (const auto subevent : LeAdvertisingEvents) { RegisterLeEventHandler(subevent, event_handler); } return &le_advertising_interface; } -LeScanningInterface* HciLayer::GetLeScanningInterface(ContextualCallback event_handler) { +LeScanningInterface* HciLayer::GetLeScanningInterface( + ContextualCallback event_handler) { for (const auto subevent : LeScanningEvents) { RegisterLeEventHandler(subevent, event_handler); } return &le_scanning_interface; } -LeIsoInterface* HciLayer::GetLeIsoInterface(ContextualCallback event_handler) { +LeIsoInterface* HciLayer::GetLeIsoInterface( + ContextualCallback event_handler) { for (const auto subevent : LeIsoEvents) { RegisterLeEventHandler(subevent, event_handler); } @@ -815,7 +786,7 @@ LeIsoInterface* HciLayer::GetLeIsoInterface(ContextualCallback event_handler) { + ContextualCallback event_handler) { for (const auto subevent : DistanceMeasurementEvents) { RegisterLeEventHandler(subevent, event_handler); } @@ -835,10 +806,12 @@ void HciLayer::Start() { hal_callbacks_ = new hal_callbacks(*this); Handler* handler = GetHandler(); - impl_->acl_queue_.GetDownEnd()->RegisterDequeue(handler, BindOn(impl_, &impl::on_outbound_acl_ready)); - impl_->sco_queue_.GetDownEnd()->RegisterDequeue(handler, BindOn(impl_, &impl::on_outbound_sco_ready)); - impl_->iso_queue_.GetDownEnd()->RegisterDequeue( - handler, BindOn(impl_, &impl::on_outbound_iso_ready)); + impl_->acl_queue_.GetDownEnd()->RegisterDequeue(handler, + BindOn(impl_, &impl::on_outbound_acl_ready)); + impl_->sco_queue_.GetDownEnd()->RegisterDequeue(handler, + BindOn(impl_, &impl::on_outbound_sco_ready)); + impl_->iso_queue_.GetDownEnd()->RegisterDequeue(handler, + BindOn(impl_, &impl::on_outbound_iso_ready)); StartWithNoHalDependencies(handler); hal->registerIncomingPacketCallback(hal_callbacks_); EnqueueCommand(ResetBuilder::Create(), handler->BindOnce(&fail_if_reset_complete_not_success)); @@ -846,15 +819,15 @@ void HciLayer::Start() { // Initialize event handlers that don't depend on the HAL void HciLayer::StartWithNoHalDependencies(Handler* handler) { - RegisterEventHandler(EventCode::DISCONNECTION_COMPLETE, handler->BindOn(this, &HciLayer::on_disconnection_complete)); - RegisterEventHandler( - EventCode::READ_REMOTE_VERSION_INFORMATION_COMPLETE, - handler->BindOn(this, &HciLayer::on_read_remote_version_complete)); + RegisterEventHandler(EventCode::DISCONNECTION_COMPLETE, + handler->BindOn(this, &HciLayer::on_disconnection_complete)); + RegisterEventHandler(EventCode::READ_REMOTE_VERSION_INFORMATION_COMPLETE, + handler->BindOn(this, &HciLayer::on_read_remote_version_complete)); auto drop_packet = handler->BindOn(impl_, &impl::drop); RegisterEventHandler(EventCode::PAGE_SCAN_REPETITION_MODE_CHANGE, drop_packet); RegisterEventHandler(EventCode::MAX_SLOTS_CHANGE, drop_packet); - RegisterEventHandler( - EventCode::CONNECTION_REQUEST, handler->BindOn(this, &HciLayer::on_connection_request)); + RegisterEventHandler(EventCode::CONNECTION_REQUEST, + handler->BindOn(this, &HciLayer::on_connection_request)); } void HciLayer::Stop() { diff --git a/system/gd/hci/hci_layer.h b/system/gd/hci/hci_layer.h index 46a76f5857a..19694ed3200 100644 --- a/system/gd/hci/hci_layer.h +++ b/system/gd/hci/hci_layer.h @@ -43,7 +43,7 @@ namespace hci { class HciLayer : public Module, public HciInterface { // LINT.IfChange - public: +public: HciLayer(); HciLayer(const HciLayer&) = delete; HciLayer& operator=(const HciLayer&) = delete; @@ -51,12 +51,11 @@ class HciLayer : public Module, public HciInterface { virtual ~HciLayer(); void EnqueueCommand( - std::unique_ptr command, - common::ContextualOnceCallback on_complete) override; + std::unique_ptr command, + common::ContextualOnceCallback on_complete) override; - void EnqueueCommand( - std::unique_ptr command, - common::ContextualOnceCallback on_status) override; + void EnqueueCommand(std::unique_ptr command, + common::ContextualOnceCallback on_status) override; virtual common::BidiQueueEnd* GetAclQueueEnd(); @@ -64,66 +63,70 @@ class HciLayer : public Module, public HciInterface { virtual common::BidiQueueEnd* GetIsoQueueEnd(); - virtual void RegisterEventHandler(EventCode event_code, common::ContextualCallback event_handler); + virtual void RegisterEventHandler(EventCode event_code, + common::ContextualCallback event_handler); virtual void UnregisterEventHandler(EventCode event_code); - virtual void RegisterLeEventHandler(SubeventCode subevent_code, - common::ContextualCallback event_handler); + virtual void RegisterLeEventHandler( + SubeventCode subevent_code, + common::ContextualCallback event_handler); virtual void UnregisterLeEventHandler(SubeventCode subevent_code); virtual void RegisterVendorSpecificEventHandler( - VseSubeventCode event, common::ContextualCallback handler); + VseSubeventCode event, common::ContextualCallback handler); virtual void UnregisterVendorSpecificEventHandler(VseSubeventCode event); virtual void RegisterForDisconnects( - common::ContextualCallback on_disconnect); + common::ContextualCallback on_disconnect); - virtual SecurityInterface* GetSecurityInterface(common::ContextualCallback event_handler); + virtual SecurityInterface* GetSecurityInterface( + common::ContextualCallback event_handler); - virtual LeSecurityInterface* GetLeSecurityInterface(common::ContextualCallback event_handler); + virtual LeSecurityInterface* GetLeSecurityInterface( + common::ContextualCallback event_handler); virtual AclConnectionInterface* GetAclConnectionInterface( - common::ContextualCallback event_handler, - common::ContextualCallback on_disconnect, - common::ContextualCallback on_connection_request, - common::ContextualCallback - on_read_remote_version_complete); + common::ContextualCallback event_handler, + common::ContextualCallback on_disconnect, + common::ContextualCallback on_connection_request, + common::ContextualCallback + on_read_remote_version_complete); virtual void PutAclConnectionInterface(); virtual LeAclConnectionInterface* GetLeAclConnectionInterface( - common::ContextualCallback event_handler, - common::ContextualCallback on_disconnect, - common::ContextualCallback - on_read_remote_version_complete); + common::ContextualCallback event_handler, + common::ContextualCallback on_disconnect, + common::ContextualCallback + on_read_remote_version_complete); virtual void PutLeAclConnectionInterface(); virtual LeAdvertisingInterface* GetLeAdvertisingInterface( - common::ContextualCallback event_handler); + common::ContextualCallback event_handler); - virtual LeScanningInterface* GetLeScanningInterface(common::ContextualCallback event_handler); + virtual LeScanningInterface* GetLeScanningInterface( + common::ContextualCallback event_handler); virtual void RegisterForScoConnectionRequests( - common::ContextualCallback - on_sco_connection_request); + common::ContextualCallback + on_sco_connection_request); - virtual LeIsoInterface* GetLeIsoInterface(common::ContextualCallback event_handler); + virtual LeIsoInterface* GetLeIsoInterface( + common::ContextualCallback event_handler); virtual DistanceMeasurementInterface* GetDistanceMeasurementInterface( - common::ContextualCallback event_handler); + common::ContextualCallback event_handler); - std::string ToString() const override { - return "Hci Layer"; - } + std::string ToString() const override { return "Hci Layer"; } static constexpr std::chrono::milliseconds kHciTimeoutMs = std::chrono::milliseconds(2000); static constexpr std::chrono::milliseconds kHciTimeoutRestartMs = std::chrono::milliseconds(5000); static const ModuleFactory Factory; - protected: +protected: // LINT.ThenChange(fuzz/fuzz_hci_layer.h) void ListDependencies(ModuleList* list) const override; @@ -134,18 +137,14 @@ class HciLayer : public Module, public HciInterface { void Stop() override; virtual void Disconnect(uint16_t handle, ErrorCode reason); - virtual void ReadRemoteVersion( - hci::ErrorCode hci_status, - uint16_t handle, - uint8_t version, - uint16_t manufacturer_name, - uint16_t sub_version); + virtual void ReadRemoteVersion(hci::ErrorCode hci_status, uint16_t handle, uint8_t version, + uint16_t manufacturer_name, uint16_t sub_version); std::list> disconnect_handlers_; std::list> - read_remote_version_handlers_; + read_remote_version_handlers_; - private: +private: struct impl; struct hal_callbacks; impl* impl_; @@ -157,9 +156,9 @@ class HciLayer : public Module, public HciInterface { void on_read_remote_version_complete(EventView event_view); common::ContextualCallback on_acl_connection_request_{}; - common::ContextualCallback - on_sco_connection_request_{}; + common::ContextualCallback + on_sco_connection_request_{}; // Interfaces CommandInterfaceImpl acl_connection_manager_interface_{*this}; diff --git a/system/gd/hci/hci_layer_fake.cc b/system/gd/hci/hci_layer_fake.cc index e431df82300..eb350acc39b 100644 --- a/system/gd/hci/hci_layer_fake.cc +++ b/system/gd/hci/hci_layer_fake.cc @@ -58,8 +58,8 @@ static std::unique_ptr NextAclPacket(uint16_t handle) { } void HciLayerFake::EnqueueCommand( - std::unique_ptr command, - common::ContextualOnceCallback on_status) { + std::unique_ptr command, + common::ContextualOnceCallback on_status) { std::lock_guard lock(mutex_); command_queue_.push(std::move(command)); @@ -72,8 +72,8 @@ void HciLayerFake::EnqueueCommand( } void HciLayerFake::EnqueueCommand( - std::unique_ptr command, - common::ContextualOnceCallback on_complete) { + std::unique_ptr command, + common::ContextualOnceCallback on_complete) { std::lock_guard lock(mutex_); command_queue_.push(std::move(command)); @@ -116,12 +116,10 @@ CommandView HciLayerFake::GetCommand(OpCode op_code) { return next_command; } -void HciLayerFake::AssertNoQueuedCommand() { - EXPECT_TRUE(command_queue_.empty()); -} +void HciLayerFake::AssertNoQueuedCommand() { EXPECT_TRUE(command_queue_.empty()); } -void HciLayerFake::RegisterEventHandler( - EventCode event_code, common::ContextualCallback event_handler) { +void HciLayerFake::RegisterEventHandler(EventCode event_code, + common::ContextualCallback event_handler) { registered_events_[event_code] = event_handler; } @@ -130,7 +128,8 @@ void HciLayerFake::UnregisterEventHandler(EventCode event_code) { } void HciLayerFake::RegisterLeEventHandler( - SubeventCode subevent_code, common::ContextualCallback event_handler) { + SubeventCode subevent_code, + common::ContextualCallback event_handler) { registered_le_events_[subevent_code] = event_handler; } @@ -139,8 +138,8 @@ void HciLayerFake::UnregisterLeEventHandler(SubeventCode subevent_code) { } void HciLayerFake::RegisterVendorSpecificEventHandler( - VseSubeventCode subevent_code, - common::ContextualCallback event_handler) { + VseSubeventCode subevent_code, + common::ContextualCallback event_handler) { registered_vs_events_[subevent_code] = event_handler; } @@ -158,7 +157,8 @@ void HciLayerFake::IncomingEvent(std::unique_ptr event_builder) { } else if (event_code == EventCode::COMMAND_STATUS) { CommandStatusCallback(event); } else { - ASSERT_NE(registered_events_.find(event_code), registered_events_.end()) << EventCodeText(event_code); + ASSERT_NE(registered_events_.find(event_code), registered_events_.end()) + << EventCodeText(event_code); registered_events_[event_code](event); } } @@ -202,20 +202,14 @@ void HciLayerFake::IncomingAclData(uint16_t handle, std::unique_ptr auto packet = GetPacketView(std::move(acl_builder)); auto acl_view = AclView::Create(packet); queue_end->RegisterEnqueue( - hci_handler, - common::Bind( - [](decltype(queue_end) queue_end, - uint16_t /* handle */, - AclView acl2, - std::promise promise) { - queue_end->UnregisterEnqueue(); - promise.set_value(); - return std::make_unique(acl2); - }, - queue_end, - handle, - acl_view, - common::Passed(std::move(promise)))); + hci_handler, common::Bind( + [](decltype(queue_end) queue_end, uint16_t /* handle */, + AclView acl2, std::promise promise) { + queue_end->UnregisterEnqueue(); + promise.set_value(); + return std::make_unique(acl2); + }, + queue_end, handle, acl_view, common::Passed(std::move(promise)))); auto status = future.wait_for(std::chrono::milliseconds(1000)); ASSERT_EQ(status, std::future_status::ready); } @@ -239,13 +233,11 @@ PacketView HciLayerFake::OutgoingAclData() { return GetPacketView(std::move(received)); } -BidiQueueEnd* HciLayerFake::GetAclQueueEnd() { - return acl_queue_.GetUpEnd(); -} +BidiQueueEnd* HciLayerFake::GetAclQueueEnd() { return acl_queue_.GetUpEnd(); } void HciLayerFake::Disconnect(uint16_t handle, ErrorCode reason) { GetHandler()->Post( - common::BindOnce(&HciLayerFake::do_disconnect, common::Unretained(this), handle, reason)); + common::BindOnce(&HciLayerFake::do_disconnect, common::Unretained(this), handle, reason)); } void HciLayerFake::do_disconnect(uint16_t handle, ErrorCode reason) { diff --git a/system/gd/hci/hci_layer_fake.h b/system/gd/hci/hci_layer_fake.h index 645746014c1..a15bc0ec542 100644 --- a/system/gd/hci/hci_layer_fake.h +++ b/system/gd/hci/hci_layer_fake.h @@ -27,19 +27,18 @@ namespace bluetooth { namespace hci { packet::PacketView GetPacketView( - std::unique_ptr packet); + std::unique_ptr packet); std::unique_ptr NextPayload(uint16_t handle); class HciLayerFake : public HciLayer { - public: - void EnqueueCommand( - std::unique_ptr command, - common::ContextualOnceCallback on_status) override; +public: + void EnqueueCommand(std::unique_ptr command, + common::ContextualOnceCallback on_status) override; void EnqueueCommand( - std::unique_ptr command, - common::ContextualOnceCallback on_complete) override; + std::unique_ptr command, + common::ContextualOnceCallback on_complete) override; CommandView GetCommand(); @@ -47,18 +46,20 @@ class HciLayerFake : public HciLayer { void AssertNoQueuedCommand(); - void RegisterEventHandler(EventCode event_code, common::ContextualCallback event_handler) override; + void RegisterEventHandler(EventCode event_code, + common::ContextualCallback event_handler) override; void UnregisterEventHandler(EventCode event_code) override; void RegisterLeEventHandler( - SubeventCode subevent_code, common::ContextualCallback event_handler) override; + SubeventCode subevent_code, + common::ContextualCallback event_handler) override; void UnregisterLeEventHandler(SubeventCode subevent_code) override; void RegisterVendorSpecificEventHandler( - VseSubeventCode subevent_code, - common::ContextualCallback event_handler) override; + VseSubeventCode subevent_code, + common::ContextualCallback event_handler) override; void UnregisterVendorSpecificEventHandler(VseSubeventCode subevent_code) override; @@ -82,12 +83,12 @@ class HciLayerFake : public HciLayer { void Disconnect(uint16_t handle, ErrorCode reason) override; - protected: +protected: void ListDependencies(ModuleList* list) const override; void Start() override; void Stop() override; - private: +private: void InitEmptyCommand(); void do_disconnect(uint16_t handle, ErrorCode reason); @@ -97,7 +98,7 @@ class HciLayerFake : public HciLayer { std::map> registered_events_; std::map> registered_le_events_; std::map> - registered_vs_events_; + registered_vs_events_; // thread-safe common::BidiQueue acl_queue_{3 /* TODO: Set queue depth */}; @@ -116,10 +117,10 @@ class HciLayerFake : public HciLayer { // reset Command=Unset and set Consumed=Set. This way we emulate a blocking queue. std::promise command_promise_{}; // Set when at least one command is in the queue std::future command_future_ = - command_promise_.get_future(); // GetCommand() blocks until this is fulfilled + command_promise_.get_future(); // GetCommand() blocks until this is fulfilled CommandView empty_command_view_ = CommandView::Create( - PacketView(std::make_shared>())); + PacketView(std::make_shared>())); }; } // namespace hci diff --git a/system/gd/hci/hci_layer_mock.h b/system/gd/hci/hci_layer_mock.h index e3f39285e29..34bbcfc1852 100644 --- a/system/gd/hci/hci_layer_mock.h +++ b/system/gd/hci/hci_layer_mock.h @@ -30,105 +30,71 @@ namespace hci { namespace testing { class MockHciLayer : public HciInterface { - public: - MOCK_METHOD( - void, - EnqueueCommand, - (std::unique_ptr, common::ContextualOnceCallback), - (override)); - MOCK_METHOD( - void, - EnqueueCommand, - (std::unique_ptr, common::ContextualOnceCallback), - (override)); +public: + MOCK_METHOD(void, EnqueueCommand, + (std::unique_ptr, + common::ContextualOnceCallback), + (override)); + MOCK_METHOD(void, EnqueueCommand, + (std::unique_ptr, + common::ContextualOnceCallback), + (override)); MOCK_METHOD((common::BidiQueueEnd*), GetAclQueueEnd, (), (override)); MOCK_METHOD((common::BidiQueueEnd*), GetScoQueueEnd, (), (override)); MOCK_METHOD((common::BidiQueueEnd*), GetIsoQueueEnd, (), (override)); - MOCK_METHOD( - (void), - RegisterEventHandler, - (EventCode, common::ContextualCallback), - (override)); + MOCK_METHOD((void), RegisterEventHandler, + (EventCode, common::ContextualCallback), (override)); MOCK_METHOD((void), UnregisterEventHandler, (EventCode), (override)); - MOCK_METHOD( - (void), - RegisterLeEventHandler, - (SubeventCode, common::ContextualCallback), - (override)); + MOCK_METHOD((void), RegisterLeEventHandler, + (SubeventCode, common::ContextualCallback), (override)); MOCK_METHOD((void), UnregisterLeEventHandler, (SubeventCode), (override)); - MOCK_METHOD( - (void), - RegisterVendorSpecificEventHandler, - (VseSubeventCode, common::ContextualCallback), - (override)); + MOCK_METHOD((void), RegisterVendorSpecificEventHandler, + (VseSubeventCode, common::ContextualCallback), + (override)); MOCK_METHOD((void), UnregisterVendorSpecificEventHandler, (VseSubeventCode), (override)); - MOCK_METHOD( - (SecurityInterface*), - GetSecurityInterface, - (common::ContextualCallback event_handler), - (override)); + MOCK_METHOD((SecurityInterface*), GetSecurityInterface, + (common::ContextualCallback event_handler), (override)); - MOCK_METHOD( - (void), - RegisterForDisconnects, - (common::ContextualCallback on_disconnect)); + MOCK_METHOD((void), RegisterForDisconnects, + (common::ContextualCallback on_disconnect)); - MOCK_METHOD( - (LeSecurityInterface*), - GetLeSecurityInterface, - (common::ContextualCallback event_handler), - (override)); + MOCK_METHOD((LeSecurityInterface*), GetLeSecurityInterface, + (common::ContextualCallback event_handler), (override)); MOCK_METHOD( - (AclConnectionInterface*), - GetAclConnectionInterface, - (common::ContextualCallback event_handler, - common::ContextualCallback on_disconnect, - common::ContextualCallback on_connection_request, - common::ContextualCallback - on_read_remote_version_complete), - (override)); + (AclConnectionInterface*), GetAclConnectionInterface, + (common::ContextualCallback event_handler, + common::ContextualCallback on_disconnect, + common::ContextualCallback on_connection_request, + common::ContextualCallback + on_read_remote_version_complete), + (override)); MOCK_METHOD((void), PutAclConnectionInterface, (), (override)); MOCK_METHOD( - (LeAclConnectionInterface*), - GetLeAclConnectionInterface, - (common::ContextualCallback event_handler, - common::ContextualCallback on_disconnect, - common::ContextualCallback - on_read_remote_version_complete), - (override)); + (LeAclConnectionInterface*), GetLeAclConnectionInterface, + (common::ContextualCallback event_handler, + common::ContextualCallback on_disconnect, + common::ContextualCallback + on_read_remote_version_complete), + (override)); MOCK_METHOD((void), PutLeAclConnectionInterface, (), (override)); - MOCK_METHOD( - (LeAdvertisingInterface*), - GetLeAdvertisingInterface, - (common::ContextualCallback event_handler), - (override)); + MOCK_METHOD((LeAdvertisingInterface*), GetLeAdvertisingInterface, + (common::ContextualCallback event_handler), (override)); - MOCK_METHOD( - (LeScanningInterface*), - GetLeScanningInterface, - (common::ContextualCallback event_handler), - (override)); + MOCK_METHOD((LeScanningInterface*), GetLeScanningInterface, + (common::ContextualCallback event_handler), (override)); - MOCK_METHOD( - (LeIsoInterface*), - GetLeIsoInterface, - (common::ContextualCallback event_handler), - (override)); + MOCK_METHOD((LeIsoInterface*), GetLeIsoInterface, + (common::ContextualCallback event_handler), (override)); - MOCK_METHOD( - (DistanceMeasurementInterface*), - GetDistanceMeasurementInterface, - (common::ContextualCallback event_handler), - (override)); + MOCK_METHOD((DistanceMeasurementInterface*), GetDistanceMeasurementInterface, + (common::ContextualCallback event_handler), (override)); - MOCK_METHOD( - void, - RegisterForScoConnectionRequests, - (common::ContextualCallback - on_sco_connection_request)); + MOCK_METHOD(void, RegisterForScoConnectionRequests, + (common::ContextualCallback + on_sco_connection_request)); }; } // namespace testing diff --git a/system/gd/hci/hci_layer_test.cc b/system/gd/hci/hci_layer_test.cc index a4ad96c0d31..9f8d9ead3cb 100644 --- a/system/gd/hci/hci_layer_test.cc +++ b/system/gd/hci/hci_layer_test.cc @@ -36,20 +36,7 @@ using std::vector; namespace { vector information_request = { - 0xfe, - 0x2e, - 0x0a, - 0x00, - 0x06, - 0x00, - 0x01, - 0x00, - 0x0a, - 0x02, - 0x02, - 0x00, - 0x02, - 0x00, + 0xfe, 0x2e, 0x0a, 0x00, 0x06, 0x00, 0x01, 0x00, 0x0a, 0x02, 0x02, 0x00, 0x02, 0x00, }; // 0x00, 0x01, 0x02, 0x03, ... vector counting_bytes; @@ -66,47 +53,53 @@ namespace { constexpr std::chrono::milliseconds kTimeout = HciLayer::kHciTimeoutMs / 2; class DependsOnHci : public Module { - public: +public: DependsOnHci() : Module() {} void SendHciCommandExpectingStatus(std::unique_ptr command) { hci_->EnqueueCommand( - std::move(command), GetHandler()->BindOnceOn(this, &DependsOnHci::handle_event)); + std::move(command), + GetHandler()->BindOnceOn(this, &DependsOnHci::handle_event)); } void SendHciCommandExpectingComplete(std::unique_ptr command) { hci_->EnqueueCommand( - std::move(command), GetHandler()->BindOnceOn(this, &DependsOnHci::handle_event)); + std::move(command), + GetHandler()->BindOnceOn(this, &DependsOnHci::handle_event)); } void SendSecurityCommandExpectingComplete(std::unique_ptr command) { if (security_interface_ == nullptr) { - security_interface_ = - hci_->GetSecurityInterface(GetHandler()->BindOn(this, &DependsOnHci::handle_event)); + security_interface_ = hci_->GetSecurityInterface( + GetHandler()->BindOn(this, &DependsOnHci::handle_event)); } hci_->EnqueueCommand( - std::move(command), GetHandler()->BindOnceOn(this, &DependsOnHci::handle_event)); + std::move(command), + GetHandler()->BindOnceOn(this, &DependsOnHci::handle_event)); } void SendLeSecurityCommandExpectingComplete(std::unique_ptr command) { if (le_security_interface_ == nullptr) { - le_security_interface_ = - hci_->GetLeSecurityInterface(GetHandler()->BindOn(this, &DependsOnHci::handle_event)); + le_security_interface_ = hci_->GetLeSecurityInterface( + GetHandler()->BindOn(this, &DependsOnHci::handle_event)); } hci_->EnqueueCommand( - std::move(command), GetHandler()->BindOnceOn(this, &DependsOnHci::handle_event)); + std::move(command), + GetHandler()->BindOnceOn(this, &DependsOnHci::handle_event)); } void SendAclData(std::unique_ptr acl) { outgoing_acl_.push(std::move(acl)); auto queue_end = hci_->GetAclQueueEnd(); - queue_end->RegisterEnqueue(GetHandler(), common::Bind(&DependsOnHci::handle_enqueue, common::Unretained(this))); + queue_end->RegisterEnqueue( + GetHandler(), common::Bind(&DependsOnHci::handle_enqueue, common::Unretained(this))); } void SendIsoData(std::unique_ptr iso) { outgoing_iso_.push(std::move(iso)); auto queue_end = hci_->GetIsoQueueEnd(); - queue_end->RegisterEnqueue(GetHandler(), common::Bind(&DependsOnHci::handle_enqueue_iso, common::Unretained(this))); + queue_end->RegisterEnqueue(GetHandler(), common::Bind(&DependsOnHci::handle_enqueue_iso, + common::Unretained(this))); } std::optional GetReceivedEvent(std::chrono::milliseconds timeout = kTimeout) { @@ -119,7 +112,7 @@ class DependsOnHci : public Module { } std::optional GetReceivedAcl( - std::chrono::milliseconds timeout = std::chrono::seconds(1)) { + std::chrono::milliseconds timeout = std::chrono::seconds(1)) { if (!incoming_acl_.wait_to_take(timeout)) { return {}; } @@ -129,7 +122,7 @@ class DependsOnHci : public Module { } std::optional GetReceivedIso( - std::chrono::milliseconds timeout = std::chrono::seconds(1)) { + std::chrono::milliseconds timeout = std::chrono::seconds(1)) { if (!incoming_iso_.wait_to_take(timeout)) { return {}; } @@ -140,14 +133,15 @@ class DependsOnHci : public Module { void Start() { hci_ = GetDependency(); - hci_->RegisterEventHandler( - EventCode::CONNECTION_COMPLETE, GetHandler()->BindOn(this, &DependsOnHci::handle_event)); + hci_->RegisterEventHandler(EventCode::CONNECTION_COMPLETE, + GetHandler()->BindOn(this, &DependsOnHci::handle_event)); hci_->RegisterLeEventHandler( - SubeventCode::CONNECTION_COMPLETE, GetHandler()->BindOn(this, &DependsOnHci::handle_event)); + SubeventCode::CONNECTION_COMPLETE, + GetHandler()->BindOn(this, &DependsOnHci::handle_event)); hci_->GetAclQueueEnd()->RegisterDequeue( - GetHandler(), common::Bind(&DependsOnHci::handle_acl, common::Unretained(this))); + GetHandler(), common::Bind(&DependsOnHci::handle_acl, common::Unretained(this))); hci_->GetIsoQueueEnd()->RegisterDequeue( - GetHandler(), common::Bind(&DependsOnHci::handle_iso, common::Unretained(this))); + GetHandler(), common::Bind(&DependsOnHci::handle_iso, common::Unretained(this))); } void Stop() { @@ -155,17 +149,13 @@ class DependsOnHci : public Module { hci_->GetIsoQueueEnd()->UnregisterDequeue(); } - void ListDependencies(ModuleList* list) const { - list->add(); - } + void ListDependencies(ModuleList* list) const { list->add(); } - std::string ToString() const override { - return std::string("DependsOnHci"); - } + std::string ToString() const override { return std::string("DependsOnHci"); } static const ModuleFactory Factory; - private: +private: HciLayer* hci_ = nullptr; const SecurityInterface* security_interface_; const LeSecurityInterface* le_security_interface_; @@ -210,7 +200,7 @@ class DependsOnHci : public Module { const ModuleFactory DependsOnHci::Factory = ModuleFactory([]() { return new DependsOnHci(); }); class HciTest : public ::testing::Test { - public: +public: void SetUp() override { counting_bytes.reserve(count_size); counting_down_bytes.reserve(count_size); @@ -235,12 +225,11 @@ class HciTest : public ::testing::Test { // Send the response event uint8_t num_packets = 1; ErrorCode error_code = ErrorCode::SUCCESS; - hal->callbacks->hciEventReceived(GetPacketBytes(ResetCompleteBuilder::Create(num_packets, error_code))); + hal->callbacks->hciEventReceived( + GetPacketBytes(ResetCompleteBuilder::Create(num_packets, error_code))); } - void TearDown() override { - fake_registry_.StopAll(); - } + void TearDown() override { fake_registry_.StopAll(); } std::vector GetPacketBytes(std::unique_ptr packet) { std::vector bytes; @@ -270,21 +259,14 @@ TEST_F(HciTest, leMetaEvent) { uint16_t supervision_timeout = 0x0B05; ClockAccuracy central_clock_accuracy = ClockAccuracy::PPM_50; hal->callbacks->hciEventReceived(GetPacketBytes(LeConnectionCompleteBuilder::Create( - status, - handle, - role, - peer_address_type, - peer_address, - conn_interval, - conn_latency, - supervision_timeout, - central_clock_accuracy))); + status, handle, role, peer_address_type, peer_address, conn_interval, conn_latency, + supervision_timeout, central_clock_accuracy))); // Wait for the event auto event = upper->GetReceivedEvent(); ASSERT_TRUE(event.has_value()); ASSERT_TRUE(LeConnectionCompleteView::Create(LeMetaEventView::Create(EventView::Create(*event))) - .IsValid()); + .IsValid()); } TEST_F(HciTest, postEventsOnceOnHciHandler) { @@ -292,33 +274,29 @@ TEST_F(HciTest, postEventsOnceOnHciHandler) { Address addr; Address::FromString("01:02:03:04:05:06", addr); upper->SendHciCommandExpectingStatus(CreateConnectionBuilder::Create( - addr, - 0, - PageScanRepetitionMode::R0, - 0, - ClockOffsetValid::INVALID, - CreateConnectionRoleSwitch::ALLOW_ROLE_SWITCH)); + addr, 0, PageScanRepetitionMode::R0, 0, ClockOffsetValid::INVALID, + CreateConnectionRoleSwitch::ALLOW_ROLE_SWITCH)); // Validate the received command. auto sent_command = hal->GetSentCommand(); ASSERT_TRUE(sent_command.has_value()); auto command = CreateConnectionView::Create( - ConnectionManagementCommandView::Create(AclCommandView::Create(*sent_command))); + ConnectionManagementCommandView::Create(AclCommandView::Create(*sent_command))); ASSERT_TRUE(command.IsValid()); // Send a status and a connection complete at the same time. uint8_t num_packets = 1; hal->callbacks->hciEventReceived( - GetPacketBytes(CreateConnectionStatusBuilder::Create(ErrorCode::SUCCESS, num_packets))); + GetPacketBytes(CreateConnectionStatusBuilder::Create(ErrorCode::SUCCESS, num_packets))); hal->callbacks->hciEventReceived(GetPacketBytes(ConnectionCompleteBuilder::Create( - ErrorCode::SUCCESS, 0x123, addr, LinkType::ACL, Enable::DISABLED))); + ErrorCode::SUCCESS, 0x123, addr, LinkType::ACL, Enable::DISABLED))); // Make sure the status comes first. auto event = upper->GetReceivedEvent(); ASSERT_TRUE(event.has_value()); ASSERT_TRUE( - CreateConnectionStatusView::Create(CommandStatusView::Create(EventView::Create(*event))) - .IsValid()); + CreateConnectionStatusView::Create(CommandStatusView::Create(EventView::Create(*event))) + .IsValid()); } TEST_F(HciTest, DISABLED_hciTimeOut) { @@ -362,15 +340,16 @@ TEST_F(HciTest, noOpCredits) { local_version_information.lmp_version_ = LmpVersion::V_4_2; local_version_information.manufacturer_name_ = 0xBAD; local_version_information.lmp_subversion_ = 0x5678; - hal->callbacks->hciEventReceived(GetPacketBytes( - ReadLocalVersionInformationCompleteBuilder::Create(num_packets, error_code, local_version_information))); + hal->callbacks->hciEventReceived( + GetPacketBytes(ReadLocalVersionInformationCompleteBuilder::Create( + num_packets, error_code, local_version_information))); // Wait for the event auto event = upper->GetReceivedEvent(); ASSERT_TRUE(event.has_value()); ASSERT_TRUE(ReadLocalVersionInformationCompleteView::Create( - CommandCompleteView::Create(EventView::Create(*event))) - .IsValid()); + CommandCompleteView::Create(EventView::Create(*event))) + .IsValid()); } TEST_F(HciTest, creditsTest) { @@ -401,21 +380,22 @@ TEST_F(HciTest, creditsTest) { local_version_information.lmp_version_ = LmpVersion::V_4_2; local_version_information.manufacturer_name_ = 0xBAD; local_version_information.lmp_subversion_ = 0x5678; - hal->callbacks->hciEventReceived(GetPacketBytes( - ReadLocalVersionInformationCompleteBuilder::Create(num_packets, error_code, local_version_information))); + hal->callbacks->hciEventReceived( + GetPacketBytes(ReadLocalVersionInformationCompleteBuilder::Create( + num_packets, error_code, local_version_information))); // Wait for the event auto event = upper->GetReceivedEvent(); ASSERT_TRUE(event.has_value()); ASSERT_TRUE(ReadLocalVersionInformationCompleteView::Create( - CommandCompleteView::Create(EventView::Create(*event))) - .IsValid()); + CommandCompleteView::Create(EventView::Create(*event))) + .IsValid()); // Verify that the second one is sent sent_command = hal->GetSentCommand(); ASSERT_TRUE(sent_command.has_value()); auto supported_commands_view = - ReadLocalSupportedCommandsView::Create(CommandView::Create(*sent_command)); + ReadLocalSupportedCommandsView::Create(CommandView::Create(*sent_command)); ASSERT_TRUE(supported_commands_view.IsValid()); // Verify that only one was sent @@ -428,18 +408,18 @@ TEST_F(HciTest, creditsTest) { supported_commands[i] = i; } hal->callbacks->hciEventReceived(GetPacketBytes(ReadLocalSupportedCommandsCompleteBuilder::Create( - num_packets, error_code, supported_commands))); + num_packets, error_code, supported_commands))); // Wait for the event event = upper->GetReceivedEvent(); ASSERT_TRUE(event.has_value()); ASSERT_TRUE(ReadLocalSupportedCommandsCompleteView::Create(CommandCompleteView::Create(*event)) - .IsValid()); + .IsValid()); // Verify that the third one is sent sent_command = hal->GetSentCommand(); ASSERT_TRUE(sent_command.has_value()); auto supported_features_view = - ReadLocalSupportedFeaturesView::Create(CommandView::Create(*sent_command)); + ReadLocalSupportedFeaturesView::Create(CommandView::Create(*sent_command)); ASSERT_TRUE(supported_features_view.IsValid()); // Verify that only one was sent @@ -448,14 +428,14 @@ TEST_F(HciTest, creditsTest) { // Send the response event uint64_t lmp_features = 0x012345678abcdef; - hal->callbacks->hciEventReceived( - GetPacketBytes(ReadLocalSupportedFeaturesCompleteBuilder::Create(num_packets, error_code, lmp_features))); + hal->callbacks->hciEventReceived(GetPacketBytes(ReadLocalSupportedFeaturesCompleteBuilder::Create( + num_packets, error_code, lmp_features))); // Wait for the event event = upper->GetReceivedEvent(); ASSERT_TRUE(event.has_value()); ASSERT_TRUE(ReadLocalSupportedFeaturesCompleteView::Create(CommandCompleteView::Create(*event)) - .IsValid()); + .IsValid()); } TEST_F(HciTest, leSecurityInterfaceTest) { @@ -466,14 +446,15 @@ TEST_F(HciTest, leSecurityInterfaceTest) { auto sent_command = hal->GetSentCommand(); ASSERT_TRUE(sent_command.has_value()); LeRandView view = - LeRandView::Create(LeSecurityCommandView::Create(CommandView::Create(*sent_command))); + LeRandView::Create(LeSecurityCommandView::Create(CommandView::Create(*sent_command))); ASSERT_TRUE(view.IsValid()); // Send a Command Complete to the host uint8_t num_packets = 1; ErrorCode status = ErrorCode::SUCCESS; uint64_t rand = 0x0123456789abcdef; - hal->callbacks->hciEventReceived(GetPacketBytes(LeRandCompleteBuilder::Create(num_packets, status, rand))); + hal->callbacks->hciEventReceived( + GetPacketBytes(LeRandCompleteBuilder::Create(num_packets, status, rand))); // Verify the event auto event = upper->GetReceivedEvent(); @@ -490,19 +471,20 @@ TEST_F(HciTest, securityInterfacesTest) { auto sent_command = hal->GetSentCommand(); ASSERT_TRUE(sent_command.has_value()); auto view = WriteSimplePairingModeView::Create( - SecurityCommandView::Create(CommandView::Create(*sent_command))); + SecurityCommandView::Create(CommandView::Create(*sent_command))); ASSERT_TRUE(view.IsValid()); // Send a Command Complete to the host uint8_t num_packets = 1; ErrorCode status = ErrorCode::SUCCESS; - hal->callbacks->hciEventReceived(GetPacketBytes(WriteSimplePairingModeCompleteBuilder::Create(num_packets, status))); + hal->callbacks->hciEventReceived( + GetPacketBytes(WriteSimplePairingModeCompleteBuilder::Create(num_packets, status))); // Verify the event auto event = upper->GetReceivedEvent(); ASSERT_TRUE(event.has_value()); - ASSERT_TRUE( - WriteSimplePairingModeCompleteView::Create(CommandCompleteView::Create(*event)).IsValid()); + ASSERT_TRUE(WriteSimplePairingModeCompleteView::Create(CommandCompleteView::Create(*event)) + .IsValid()); } TEST_F(HciTest, createConnectionTest) { @@ -514,14 +496,15 @@ TEST_F(HciTest, createConnectionTest) { uint16_t clock_offset = 0x3456; ClockOffsetValid clock_offset_valid = ClockOffsetValid::VALID; CreateConnectionRoleSwitch allow_role_switch = CreateConnectionRoleSwitch::ALLOW_ROLE_SWITCH; - upper->SendHciCommandExpectingStatus(CreateConnectionBuilder::Create( - bd_addr, packet_type, page_scan_repetition_mode, clock_offset, clock_offset_valid, allow_role_switch)); + upper->SendHciCommandExpectingStatus( + CreateConnectionBuilder::Create(bd_addr, packet_type, page_scan_repetition_mode, + clock_offset, clock_offset_valid, allow_role_switch)); // Check the command auto sent_command = hal->GetSentCommand(); ASSERT_TRUE(sent_command.has_value()); CreateConnectionView view = CreateConnectionView::Create(ConnectionManagementCommandView::Create( - AclCommandView::Create(CommandView::Create(*sent_command)))); + AclCommandView::Create(CommandView::Create(*sent_command)))); ASSERT_TRUE(view.IsValid()); ASSERT_EQ(bd_addr, view.GetBdAddr()); ASSERT_EQ(packet_type, view.GetPacketType()); @@ -535,7 +518,8 @@ TEST_F(HciTest, createConnectionTest) { uint16_t handle = 0x123; LinkType link_type = LinkType::ACL; Enable encryption_enabled = Enable::DISABLED; - hal->callbacks->hciEventReceived(GetPacketBytes(CreateConnectionStatusBuilder::Create(ErrorCode::SUCCESS, 1))); + hal->callbacks->hciEventReceived( + GetPacketBytes(CreateConnectionStatusBuilder::Create(ErrorCode::SUCCESS, 1))); // Verify the event auto event = upper->GetReceivedEvent(); @@ -543,8 +527,8 @@ TEST_F(HciTest, createConnectionTest) { ASSERT_TRUE(CreateConnectionStatusView::Create(CommandStatusView::Create(*event)).IsValid()); // Send a ConnectionComplete to the host - hal->callbacks->hciEventReceived( - GetPacketBytes(ConnectionCompleteBuilder::Create(status, handle, bd_addr, link_type, encryption_enabled))); + hal->callbacks->hciEventReceived(GetPacketBytes(ConnectionCompleteBuilder::Create( + status, handle, bd_addr, link_type, encryption_enabled))); // Verify the event event = upper->GetReceivedEvent(); @@ -562,8 +546,8 @@ TEST_F(HciTest, createConnectionTest) { auto acl_payload = std::make_unique(); acl_payload->AddOctets(bd_addr.address); acl_payload->AddOctets2(handle); - hal->callbacks->aclDataReceived( - GetPacketBytes(AclBuilder::Create(handle, packet_boundary_flag, broadcast_flag, std::move(acl_payload)))); + hal->callbacks->aclDataReceived(GetPacketBytes(AclBuilder::Create( + handle, packet_boundary_flag, broadcast_flag, std::move(acl_payload)))); // Verify the ACL packet auto acl_view_result = upper->GetReceivedAcl(); @@ -581,7 +565,8 @@ TEST_F(HciTest, createConnectionTest) { auto acl_payload2 = std::make_unique(); acl_payload2->AddOctets2(handle); acl_payload2->AddOctets(bd_addr.address); - upper->SendAclData(AclBuilder::Create(handle, packet_boundary_flag2, broadcast_flag2, std::move(acl_payload2))); + upper->SendAclData(AclBuilder::Create(handle, packet_boundary_flag2, broadcast_flag2, + std::move(acl_payload2))); // Verify the ACL packet auto sent_acl = hal->GetSentAcl(); @@ -606,8 +591,8 @@ TEST_F(HciTest, receiveMultipleAclPackets) { acl_payload->AddOctets(bd_addr.address); acl_payload->AddOctets2(handle); acl_payload->AddOctets2(i); - hal->callbacks->aclDataReceived( - GetPacketBytes(AclBuilder::Create(handle, packet_boundary_flag, broadcast_flag, std::move(acl_payload)))); + hal->callbacks->aclDataReceived(GetPacketBytes(AclBuilder::Create( + handle, packet_boundary_flag, broadcast_flag, std::move(acl_payload)))); } for (uint16_t i = 0; i < num_packets; i++) { @@ -632,8 +617,8 @@ TEST_F(HciTest, receiveMultipleIsoPackets) { auto iso_payload = std::make_unique(); iso_payload->AddOctets2(handle); iso_payload->AddOctets2(i); - hal->callbacks->isoDataReceived( - GetPacketBytes(IsoBuilder::Create(handle, packet_boundary_flag, timestamp_flag, std::move(iso_payload)))); + hal->callbacks->isoDataReceived(GetPacketBytes(IsoBuilder::Create( + handle, packet_boundary_flag, timestamp_flag, std::move(iso_payload)))); } for (uint16_t i = 0; i < num_packets; i++) { auto iso_opt = upper->GetReceivedIso(); diff --git a/system/gd/hci/hci_layer_unittest.cc b/system/gd/hci/hci_layer_unittest.cc index e4de68cc63f..80cc4c9b59d 100644 --- a/system/gd/hci/hci_layer_unittest.cc +++ b/system/gd/hci/hci_layer_unittest.cc @@ -46,14 +46,19 @@ constexpr char kOurCommandStatusHandlerWasInvoked[] = "Our command status handle constexpr char kOurDisconnectHandlerWasInvoked[] = "Our disconnect handler was invoked."; constexpr char kOurEventHandlerWasInvoked[] = "Our event handler was invoked."; constexpr char kOurLeAclEventHandlerWasInvoked[] = "Our LE ACL event handler was invoked."; -constexpr char kOurLeAdvertisementEventHandlerWasInvoked[] = "Our LE advertisement event handler was invoked."; +constexpr char kOurLeAdvertisementEventHandlerWasInvoked[] = + "Our LE advertisement event handler was invoked."; constexpr char kOurLeDisconnectHandlerWasInvoked[] = "Our LE disconnect handler was invoked."; constexpr char kOurLeEventHandlerWasInvoked[] = "Our LE event handler was invoked."; constexpr char kOurLeIsoEventHandlerWasInvoked[] = "Our LE ISO event handler was invoked."; -constexpr char kOurLeReadRemoteVersionHandlerWasInvoked[] = "Our Read Remote Version complete handler was invoked."; -constexpr char kOurLeScanningEventHandlerWasInvoked[] = "Our LE scanning event handler was invoked."; -constexpr char kOurReadRemoteVersionHandlerWasInvoked[] = "Our Read Remote Version complete handler was invoked."; -constexpr char kOurLeSecurityEventHandlerWasInvoked[] = "Our LE security event handler was invoked."; +constexpr char kOurLeReadRemoteVersionHandlerWasInvoked[] = + "Our Read Remote Version complete handler was invoked."; +constexpr char kOurLeScanningEventHandlerWasInvoked[] = + "Our LE scanning event handler was invoked."; +constexpr char kOurReadRemoteVersionHandlerWasInvoked[] = + "Our Read Remote Version complete handler was invoked."; +constexpr char kOurLeSecurityEventHandlerWasInvoked[] = + "Our LE security event handler was invoked."; constexpr char kOurSecurityEventHandlerWasInvoked[] = "Our security event handler was invoked."; } // namespace @@ -78,19 +83,19 @@ std::vector GetPacketBytes(std::unique_ptr p static std::chrono::milliseconds getHciTimeoutMs() { static auto sHciTimeoutMs = std::chrono::milliseconds(bluetooth::os::GetSystemPropertyUint32Base( - "bluetooth.hci.timeout_milliseconds", HciLayer::kHciTimeoutMs.count())); + "bluetooth.hci.timeout_milliseconds", HciLayer::kHciTimeoutMs.count())); return sHciTimeoutMs; } static std::chrono::milliseconds getHciTimeoutRestartMs() { - static auto sRestartHciTimeoutMs = - std::chrono::milliseconds(bluetooth::os::GetSystemPropertyUint32Base( - "bluetooth.hci.restart_timeout_milliseconds", HciLayer::kHciTimeoutRestartMs.count())); + static auto sRestartHciTimeoutMs = std::chrono::milliseconds( + bluetooth::os::GetSystemPropertyUint32Base("bluetooth.hci.restart_timeout_milliseconds", + HciLayer::kHciTimeoutRestartMs.count())); return sRestartHciTimeoutMs; } class HciLayerTest : public ::testing::Test { - protected: +protected: void SetUp() override { hal_ = new hal::TestHciHal(); fake_registry_.InjectTestModule(&hal::HciHal::Factory, hal_); @@ -125,9 +130,8 @@ class HciLayerTest : public ::testing::Test { } void sync_handler() { - log::assert_that( - fake_registry_.GetTestThread().GetReactor()->WaitForIdle(2s), - "assert failed: fake_registry_.GetTestThread().GetReactor()->WaitForIdle(2s)"); + log::assert_that(fake_registry_.GetTestThread().GetReactor()->WaitForIdle(2s), + "assert failed: fake_registry_.GetTestThread().GetReactor()->WaitForIdle(2s)"); } hal::TestHciHal* hal_ = nullptr; @@ -140,9 +144,7 @@ class HciLayerDeathTest : public HciLayerTest {}; TEST_F(HciLayerTest, setup_teardown) {} -TEST_F(HciLayerTest, reset_command_sent_on_start) { - FailIfResetNotSent(); -} +TEST_F(HciLayerTest, reset_command_sent_on_start) { FailIfResetNotSent(); } TEST_F(HciLayerTest, controller_debug_info_requested_on_hci_timeout) { FailIfResetNotSent(); @@ -166,12 +168,12 @@ TEST_F(HciLayerDeathTest, abort_after_hci_restart_timeout) { ASSERT_TRUE(debug_info_view.IsValid()); ASSERT_DEATH( - { - sync_handler(); - FakeTimerAdvance(getHciTimeoutRestartMs().count()); - sync_handler(); - }, - ""); + { + sync_handler(); + FakeTimerAdvance(getHciTimeoutRestartMs().count()); + sync_handler(); + }, + ""); } TEST_F(HciLayerDeathTest, discard_event_after_hci_timeout) { @@ -188,37 +190,37 @@ TEST_F(HciLayerDeathTest, discard_event_after_hci_timeout) { sync_handler(); ASSERT_DEATH( - { - FakeTimerAdvance(getHciTimeoutRestartMs().count()); - sync_handler(); - }, - ""); + { + FakeTimerAdvance(getHciTimeoutRestartMs().count()); + sync_handler(); + }, + ""); } TEST_F(HciLayerDeathTest, abort_on_root_inflammation_event) { FailIfResetNotSent(); ASSERT_DEATH( - { - sync_handler(); - hal_->InjectEvent(BqrRootInflammationEventBuilder::Create( - 0x01, 0x01, std::make_unique())); - FakeTimerAdvance(getHciTimeoutRestartMs().count()); - sync_handler(); - }, - ""); + { + sync_handler(); + hal_->InjectEvent(BqrRootInflammationEventBuilder::Create( + 0x01, 0x01, std::make_unique())); + FakeTimerAdvance(getHciTimeoutRestartMs().count()); + sync_handler(); + }, + ""); } TEST_F(HciLayerDeathTest, abort_on_hardware_error) { FailIfResetNotSent(); ASSERT_DEATH( - { - sync_handler(); - hal_->InjectEvent(HardwareErrorBuilder::Create(0xbb)); - sync_handler(); - }, - ""); + { + sync_handler(); + hal_->InjectEvent(HardwareErrorBuilder::Create(0xbb)); + sync_handler(); + }, + ""); } TEST_F(HciLayerTest, successful_reset) { @@ -230,179 +232,159 @@ TEST_F(HciLayerTest, successful_reset) { TEST_F(HciLayerDeathTest, abort_if_reset_complete_returns_error) { FailIfResetNotSent(); ASSERT_DEATH( - { - hal_->InjectEvent(ResetCompleteBuilder::Create(1, ErrorCode::HARDWARE_FAILURE)); - sync_handler(); - }, - ""); + { + hal_->InjectEvent(ResetCompleteBuilder::Create(1, ErrorCode::HARDWARE_FAILURE)); + sync_handler(); + }, + ""); } TEST_F(HciLayerTest, event_handler_is_invoked) { FailIfResetNotSent(); - hci_->RegisterEventHandler( - EventCode::COMMAND_COMPLETE, hci_handler_->Bind([](EventView /* view */) { - log::debug("{}", kOurEventHandlerWasInvoked); - })); + hci_->RegisterEventHandler(EventCode::COMMAND_COMPLETE, + hci_handler_->Bind([](EventView /* view */) { + log::debug("{}", kOurEventHandlerWasInvoked); + })); hal_->InjectEvent(ResetCompleteBuilder::Create(1, ErrorCode::SUCCESS)); } TEST_F(HciLayerTest, le_event_handler_is_invoked) { FailIfResetNotSent(); - hci_->RegisterLeEventHandler( - SubeventCode::ENHANCED_CONNECTION_COMPLETE, - hci_handler_->Bind( - [](LeMetaEventView /* view */) { log::debug("{}", kOurLeEventHandlerWasInvoked); })); + hci_->RegisterLeEventHandler(SubeventCode::ENHANCED_CONNECTION_COMPLETE, + hci_handler_->Bind([](LeMetaEventView /* view */) { + log::debug("{}", kOurLeEventHandlerWasInvoked); + })); hci::Address remote_address; Address::FromString("D0:05:04:03:02:01", remote_address); hal_->InjectEvent(LeEnhancedConnectionCompleteBuilder::Create( - ErrorCode::SUCCESS, - 0x0041, - Role::PERIPHERAL, - AddressType::PUBLIC_DEVICE_ADDRESS, - remote_address, - Address::kEmpty, - Address::kEmpty, - 0x0024, - 0x0000, - 0x0011, - ClockAccuracy::PPM_30)); + ErrorCode::SUCCESS, 0x0041, Role::PERIPHERAL, AddressType::PUBLIC_DEVICE_ADDRESS, + remote_address, Address::kEmpty, Address::kEmpty, 0x0024, 0x0000, 0x0011, + ClockAccuracy::PPM_30)); } TEST_F(HciLayerDeathTest, abort_on_second_register_event_handler) { FailIfResetNotSent(); ASSERT_DEATH( - { - hci_->RegisterEventHandler( - EventCode::SIMPLE_PAIRING_COMPLETE, hci_handler_->Bind([](EventView /* view */) {})); - hci_->RegisterEventHandler( - EventCode::SIMPLE_PAIRING_COMPLETE, hci_handler_->Bind([](EventView /* view */) {})); - sync_handler(); - }, - ""); + { + hci_->RegisterEventHandler(EventCode::SIMPLE_PAIRING_COMPLETE, + hci_handler_->Bind([](EventView /* view */) {})); + hci_->RegisterEventHandler(EventCode::SIMPLE_PAIRING_COMPLETE, + hci_handler_->Bind([](EventView /* view */) {})); + sync_handler(); + }, + ""); } TEST_F(HciLayerDeathTest, abort_on_second_register_le_event_handler) { ASSERT_DEATH( - { - FailIfResetNotSent(); - hci_->RegisterLeEventHandler( - SubeventCode::ENHANCED_CONNECTION_COMPLETE, - hci_handler_->Bind([](LeMetaEventView /* view */) {})); - hci_->RegisterLeEventHandler( - SubeventCode::ENHANCED_CONNECTION_COMPLETE, - hci_handler_->Bind([](LeMetaEventView /* view */) {})); - sync_handler(); - }, - ""); + { + FailIfResetNotSent(); + hci_->RegisterLeEventHandler(SubeventCode::ENHANCED_CONNECTION_COMPLETE, + hci_handler_->Bind([](LeMetaEventView /* view */) {})); + hci_->RegisterLeEventHandler(SubeventCode::ENHANCED_CONNECTION_COMPLETE, + hci_handler_->Bind([](LeMetaEventView /* view */) {})); + sync_handler(); + }, + ""); } TEST_F(HciLayerTest, our_acl_event_callback_is_invoked) { FailIfResetNotSent(); hci_->GetAclConnectionInterface( - hci_handler_->Bind( - [](EventView /* view */) { log::debug("{}", kOurAclEventHandlerWasInvoked); }), - hci_handler_->Bind([](uint16_t /* handle */, ErrorCode /* reason */) {}), - hci_handler_->Bind([](Address /* bd_addr */, ClassOfDevice /* cod */) {}), - hci_handler_->Bind([](hci::ErrorCode /* hci_status */, - uint16_t /* handle */, - uint8_t /* version */, - uint16_t /* manufacturer_name */, - uint16_t /* sub_version */) {})); + hci_handler_->Bind( + [](EventView /* view */) { log::debug("{}", kOurAclEventHandlerWasInvoked); }), + hci_handler_->Bind([](uint16_t /* handle */, ErrorCode /* reason */) {}), + hci_handler_->Bind([](Address /* bd_addr */, ClassOfDevice /* cod */) {}), + hci_handler_->Bind([](hci::ErrorCode /* hci_status */, uint16_t /* handle */, + uint8_t /* version */, uint16_t /* manufacturer_name */, + uint16_t /* sub_version */) {})); hal_->InjectEvent(ReadClockOffsetCompleteBuilder::Create(ErrorCode::SUCCESS, 0x0001, 0x0123)); } TEST_F(HciLayerTest, our_disconnect_callback_is_invoked) { FailIfResetNotSent(); hci_->GetAclConnectionInterface( - hci_handler_->Bind([](EventView /* view */) {}), - hci_handler_->Bind([](uint16_t /* handle */, ErrorCode /* reason */) { - log::debug("{}", kOurDisconnectHandlerWasInvoked); - }), - hci_handler_->Bind([](Address /* bd_addr */, ClassOfDevice /* cod */) {}), - hci_handler_->Bind([](hci::ErrorCode /* hci_status */, - uint16_t /* handle */, - uint8_t /* version */, - uint16_t /* manufacturer_name */, - uint16_t /* sub_version */) {})); + hci_handler_->Bind([](EventView /* view */) {}), + hci_handler_->Bind([](uint16_t /* handle */, ErrorCode /* reason */) { + log::debug("{}", kOurDisconnectHandlerWasInvoked); + }), + hci_handler_->Bind([](Address /* bd_addr */, ClassOfDevice /* cod */) {}), + hci_handler_->Bind([](hci::ErrorCode /* hci_status */, uint16_t /* handle */, + uint8_t /* version */, uint16_t /* manufacturer_name */, + uint16_t /* sub_version */) {})); hal_->InjectEvent(DisconnectionCompleteBuilder::Create( - ErrorCode::SUCCESS, 0x0001, ErrorCode::REMOTE_USER_TERMINATED_CONNECTION)); + ErrorCode::SUCCESS, 0x0001, ErrorCode::REMOTE_USER_TERMINATED_CONNECTION)); } TEST_F(HciLayerTest, our_read_remote_version_callback_is_invoked) { FailIfResetNotSent(); hci_->GetAclConnectionInterface( - hci_handler_->Bind([](EventView /* view */) {}), - hci_handler_->Bind([](uint16_t /* handle */, ErrorCode /* reason */) {}), - hci_handler_->Bind([](Address /* bd_addr */, ClassOfDevice /* cod */) {}), - hci_handler_->Bind([](hci::ErrorCode /* hci_status */, - uint16_t /* handle */, - uint8_t /* version */, - uint16_t /* manufacturer_name */, - uint16_t /* sub_version */) { - log::debug("{}", kOurReadRemoteVersionHandlerWasInvoked); - })); - hal_->InjectEvent(ReadRemoteVersionInformationCompleteBuilder::Create( - ErrorCode::SUCCESS, 0x0001, 0x0b, 0x000f, 0x0000)); + hci_handler_->Bind([](EventView /* view */) {}), + hci_handler_->Bind([](uint16_t /* handle */, ErrorCode /* reason */) {}), + hci_handler_->Bind([](Address /* bd_addr */, ClassOfDevice /* cod */) {}), + hci_handler_->Bind([](hci::ErrorCode /* hci_status */, uint16_t /* handle */, + uint8_t /* version */, uint16_t /* manufacturer_name */, + uint16_t /* sub_version */) { + log::debug("{}", kOurReadRemoteVersionHandlerWasInvoked); + })); + hal_->InjectEvent(ReadRemoteVersionInformationCompleteBuilder::Create(ErrorCode::SUCCESS, 0x0001, + 0x0b, 0x000f, 0x0000)); } TEST_F(HciLayerTest, our_le_acl_event_callback_is_invoked) { FailIfResetNotSent(); hci_->GetLeAclConnectionInterface( - hci_handler_->Bind( - [](LeMetaEventView /* view */) { log::debug("{}", kOurLeAclEventHandlerWasInvoked); }), - hci_handler_->Bind([](uint16_t /* handle */, ErrorCode /* reason */) {}), - hci_handler_->Bind([](hci::ErrorCode /* hci_status */, - uint16_t /* handle */, - uint8_t /* version */, - uint16_t /* manufacturer_name */, - uint16_t /* sub_version */) {})); + hci_handler_->Bind([](LeMetaEventView /* view */) { + log::debug("{}", kOurLeAclEventHandlerWasInvoked); + }), + hci_handler_->Bind([](uint16_t /* handle */, ErrorCode /* reason */) {}), + hci_handler_->Bind([](hci::ErrorCode /* hci_status */, uint16_t /* handle */, + uint8_t /* version */, uint16_t /* manufacturer_name */, + uint16_t /* sub_version */) {})); hal_->InjectEvent(LeDataLengthChangeBuilder::Create(0x0001, 0x001B, 0x0148, 0x001B, 0x0148)); } TEST_F(HciLayerTest, our_le_disconnect_callback_is_invoked) { FailIfResetNotSent(); hci_->GetLeAclConnectionInterface( - hci_handler_->Bind([](LeMetaEventView /* view */) {}), - hci_handler_->Bind([](uint16_t /* handle */, ErrorCode /* reason */) { - log::debug("{}", kOurLeDisconnectHandlerWasInvoked); - }), - hci_handler_->Bind([](hci::ErrorCode /* hci_status */, - uint16_t /* handle */, - uint8_t /* version */, - uint16_t /* manufacturer_name */, - uint16_t /* sub_version */) {})); + hci_handler_->Bind([](LeMetaEventView /* view */) {}), + hci_handler_->Bind([](uint16_t /* handle */, ErrorCode /* reason */) { + log::debug("{}", kOurLeDisconnectHandlerWasInvoked); + }), + hci_handler_->Bind([](hci::ErrorCode /* hci_status */, uint16_t /* handle */, + uint8_t /* version */, uint16_t /* manufacturer_name */, + uint16_t /* sub_version */) {})); hal_->InjectEvent(DisconnectionCompleteBuilder::Create( - ErrorCode::SUCCESS, 0x0001, ErrorCode::REMOTE_USER_TERMINATED_CONNECTION)); + ErrorCode::SUCCESS, 0x0001, ErrorCode::REMOTE_USER_TERMINATED_CONNECTION)); } TEST_F(HciLayerTest, our_le_read_remote_version_callback_is_invoked) { FailIfResetNotSent(); hci_->GetLeAclConnectionInterface( - hci_handler_->Bind([](LeMetaEventView /* view */) {}), - hci_handler_->Bind([](uint16_t /* handle */, ErrorCode /* reason */) {}), - hci_handler_->Bind([](hci::ErrorCode /* hci_status */, - uint16_t /* handle */, - uint8_t /* version */, - uint16_t /* manufacturer_name */, - uint16_t /* sub_version */) { - log::debug("{}", kOurLeReadRemoteVersionHandlerWasInvoked); - })); - hal_->InjectEvent(ReadRemoteVersionInformationCompleteBuilder::Create( - ErrorCode::SUCCESS, 0x0001, 0x0b, 0x000f, 0x0000)); + hci_handler_->Bind([](LeMetaEventView /* view */) {}), + hci_handler_->Bind([](uint16_t /* handle */, ErrorCode /* reason */) {}), + hci_handler_->Bind([](hci::ErrorCode /* hci_status */, uint16_t /* handle */, + uint8_t /* version */, uint16_t /* manufacturer_name */, + uint16_t /* sub_version */) { + log::debug("{}", kOurLeReadRemoteVersionHandlerWasInvoked); + })); + hal_->InjectEvent(ReadRemoteVersionInformationCompleteBuilder::Create(ErrorCode::SUCCESS, 0x0001, + 0x0b, 0x000f, 0x0000)); } TEST_F(HciLayerTest, our_security_callback_is_invoked) { FailIfResetNotSent(); hci_->GetSecurityInterface(hci_handler_->Bind( - [](EventView /* view */) { log::debug("{}", kOurSecurityEventHandlerWasInvoked); })); - hal_->InjectEvent(EncryptionChangeBuilder::Create( - ErrorCode::SUCCESS, 0x0001, bluetooth::hci::EncryptionEnabled::ON)); + [](EventView /* view */) { log::debug("{}", kOurSecurityEventHandlerWasInvoked); })); + hal_->InjectEvent(EncryptionChangeBuilder::Create(ErrorCode::SUCCESS, 0x0001, + bluetooth::hci::EncryptionEnabled::ON)); } TEST_F(HciLayerTest, our_le_security_callback_is_invoked) { FailIfResetNotSent(); - hci_->GetLeSecurityInterface(hci_handler_->Bind( - [](LeMetaEventView /* view */) { log::debug("{}", kOurLeSecurityEventHandlerWasInvoked); })); + hci_->GetLeSecurityInterface(hci_handler_->Bind([](LeMetaEventView /* view */) { + log::debug("{}", kOurLeSecurityEventHandlerWasInvoked); + })); hal_->InjectEvent(LeLongTermKeyRequestBuilder::Create(0x0001, {0, 0, 0, 0, 0, 0, 0, 0}, 0)); } @@ -412,41 +394,41 @@ TEST_F(HciLayerTest, our_le_advertising_callback_is_invoked) { log::debug("{}", kOurLeAdvertisementEventHandlerWasInvoked); })); hal_->InjectEvent( - LeAdvertisingSetTerminatedBuilder::Create(ErrorCode::SUCCESS, 0x01, 0x001, 0x01)); + LeAdvertisingSetTerminatedBuilder::Create(ErrorCode::SUCCESS, 0x01, 0x001, 0x01)); } TEST_F(HciLayerTest, our_le_scanning_callback_is_invoked) { FailIfResetNotSent(); - hci_->GetLeScanningInterface(hci_handler_->Bind( - [](LeMetaEventView /* view */) { log::debug("{}", kOurLeScanningEventHandlerWasInvoked); })); + hci_->GetLeScanningInterface(hci_handler_->Bind([](LeMetaEventView /* view */) { + log::debug("{}", kOurLeScanningEventHandlerWasInvoked); + })); hal_->InjectEvent(LeScanTimeoutBuilder::Create()); } TEST_F(HciLayerTest, our_le_iso_callback_is_invoked) { FailIfResetNotSent(); hci_->GetLeIsoInterface(hci_handler_->Bind( - [](LeMetaEventView /* view */) { log::debug("{}", kOurLeIsoEventHandlerWasInvoked); })); + [](LeMetaEventView /* view */) { log::debug("{}", kOurLeIsoEventHandlerWasInvoked); })); hal_->InjectEvent(LeCisRequestBuilder::Create(0x0001, 0x0001, 0x01, 0x01)); } TEST_F(HciLayerTest, our_command_complete_callback_is_invoked) { FailIfResetNotSent(); hal_->InjectEvent(ResetCompleteBuilder::Create(1, ErrorCode::SUCCESS)); - hci_->EnqueueCommand( - ResetBuilder::Create(), hci_handler_->BindOnce([](CommandCompleteView /* view */) { - log::debug("{}", kOurCommandCompleteHandlerWasInvoked); - })); + hci_->EnqueueCommand(ResetBuilder::Create(), + hci_handler_->BindOnce([](CommandCompleteView /* view */) { + log::debug("{}", kOurCommandCompleteHandlerWasInvoked); + })); hal_->InjectEvent(ResetCompleteBuilder::Create(1, ErrorCode::SUCCESS)); } TEST_F(HciLayerTest, our_command_status_callback_is_invoked) { FailIfResetNotSent(); hal_->InjectEvent(ResetCompleteBuilder::Create(1, ErrorCode::SUCCESS)); - hci_->EnqueueCommand( - ReadClockOffsetBuilder::Create(0x001), - hci_handler_->BindOnce([](CommandStatusView /* view */) { - log::debug("{}", kOurCommandStatusHandlerWasInvoked); - })); + hci_->EnqueueCommand(ReadClockOffsetBuilder::Create(0x001), + hci_handler_->BindOnce([](CommandStatusView /* view */) { + log::debug("{}", kOurCommandStatusHandlerWasInvoked); + })); hal_->InjectEvent(ReadClockOffsetStatusBuilder::Create(ErrorCode::SUCCESS, 1)); } @@ -455,82 +437,74 @@ TEST_F(HciLayerTest, vendor_specific_status_instead_of_complete) { auto callback_future = callback_promise.get_future(); FailIfResetNotSent(); hal_->InjectEvent(ResetCompleteBuilder::Create(1, ErrorCode::SUCCESS)); - hci_->EnqueueCommand( - LeGetVendorCapabilitiesBuilder::Create(), - hci_handler_->BindOnce( - [](std::promise promise, CommandCompleteView view) { - ASSERT_TRUE(view.IsValid()); - promise.set_value(view.GetCommandOpCode()); - }, - std::move(callback_promise))); - hal_->InjectEvent(CommandStatusBuilder::Create( - ErrorCode::UNKNOWN_HCI_COMMAND, - 1, - OpCode::LE_GET_VENDOR_CAPABILITIES, - std::make_unique())); + hci_->EnqueueCommand(LeGetVendorCapabilitiesBuilder::Create(), + hci_handler_->BindOnce( + [](std::promise promise, CommandCompleteView view) { + ASSERT_TRUE(view.IsValid()); + promise.set_value(view.GetCommandOpCode()); + }, + std::move(callback_promise))); + hal_->InjectEvent(CommandStatusBuilder::Create(ErrorCode::UNKNOWN_HCI_COMMAND, 1, + OpCode::LE_GET_VENDOR_CAPABILITIES, + std::make_unique())); ASSERT_EQ(std::future_status::ready, callback_future.wait_for(std::chrono::seconds(1))); ASSERT_EQ(OpCode::LE_GET_VENDOR_CAPABILITIES, callback_future.get()); } -TEST_F( - HciLayerDeathTest, - command_complete_callback_is_invoked_with_an_opcode_that_does_not_match_command_queue) { +TEST_F(HciLayerDeathTest, + command_complete_callback_is_invoked_with_an_opcode_that_does_not_match_command_queue) { ASSERT_DEATH( - { - FailIfResetNotSent(); - hci_->EnqueueCommand( - ReadClockOffsetBuilder::Create(0x001), - hci_handler_->BindOnce([](CommandCompleteView /* view */) {})); - hal_->InjectEvent(ReadClockOffsetStatusBuilder::Create(ErrorCode::SUCCESS, 1)); - sync_handler(); - }, - ""); -} - -TEST_F( - HciLayerDeathTest, - command_status_callback_is_invoked_with_an_opcode_that_does_not_match_command_queue) { + { + FailIfResetNotSent(); + hci_->EnqueueCommand(ReadClockOffsetBuilder::Create(0x001), + hci_handler_->BindOnce([](CommandCompleteView /* view */) {})); + hal_->InjectEvent(ReadClockOffsetStatusBuilder::Create(ErrorCode::SUCCESS, 1)); + sync_handler(); + }, + ""); +} + +TEST_F(HciLayerDeathTest, + command_status_callback_is_invoked_with_an_opcode_that_does_not_match_command_queue) { ASSERT_DEATH( - { - FailIfResetNotSent(); - hci_->EnqueueCommand( - ReadClockOffsetBuilder::Create(0x001), - hci_handler_->BindOnce([](CommandStatusView /* view */) {})); - hal_->InjectEvent(ReadClockOffsetStatusBuilder::Create(ErrorCode::SUCCESS, 1)); - sync_handler(); - }, - ""); + { + FailIfResetNotSent(); + hci_->EnqueueCommand(ReadClockOffsetBuilder::Create(0x001), + hci_handler_->BindOnce([](CommandStatusView /* view */) {})); + hal_->InjectEvent(ReadClockOffsetStatusBuilder::Create(ErrorCode::SUCCESS, 1)); + sync_handler(); + }, + ""); } TEST_F(HciLayerDeathTest, command_complete_callback_is_invoked_but_command_queue_empty) { ASSERT_DEATH( - { - FailIfResetNotSent(); - hal_->InjectEvent(ResetCompleteBuilder::Create(1, ErrorCode::SUCCESS)); - hal_->InjectEvent(ResetCompleteBuilder::Create(1, ErrorCode::SUCCESS)); - sync_handler(); - }, - ""); + { + FailIfResetNotSent(); + hal_->InjectEvent(ResetCompleteBuilder::Create(1, ErrorCode::SUCCESS)); + hal_->InjectEvent(ResetCompleteBuilder::Create(1, ErrorCode::SUCCESS)); + sync_handler(); + }, + ""); } TEST_F(HciLayerDeathTest, command_status_callback_is_invoked_but_command_queue_empty) { ASSERT_DEATH( - { - FailIfResetNotSent(); - hal_->InjectEvent(ResetCompleteBuilder::Create(1, ErrorCode::SUCCESS)); - hal_->InjectEvent(ReadClockOffsetStatusBuilder::Create(ErrorCode::SUCCESS, 1)); - sync_handler(); - }, - ""); + { + FailIfResetNotSent(); + hal_->InjectEvent(ResetCompleteBuilder::Create(1, ErrorCode::SUCCESS)); + hal_->InjectEvent(ReadClockOffsetStatusBuilder::Create(ErrorCode::SUCCESS, 1)); + sync_handler(); + }, + ""); } TEST_F(HciLayerTest, command_status_callback_is_invoked_with_failure_status) { FailIfResetNotSent(); hal_->InjectEvent(ResetCompleteBuilder::Create(1, ErrorCode::SUCCESS)); - hci_->EnqueueCommand( - ReadClockOffsetBuilder::Create(0x001), - hci_handler_->BindOnce([](CommandStatusView /* view */) {})); + hci_->EnqueueCommand(ReadClockOffsetBuilder::Create(0x001), + hci_handler_->BindOnce([](CommandStatusView /* view */) {})); hal_->InjectEvent(ReadClockOffsetStatusBuilder::Create(ErrorCode::HARDWARE_FAILURE, 1)); sync_handler(); } diff --git a/system/gd/hci/hci_metrics_logging.cc b/system/gd/hci/hci_metrics_logging.cc index 961e33fc7c2..dfc8d6f4ad4 100644 --- a/system/gd/hci/hci_metrics_logging.cc +++ b/system/gd/hci/hci_metrics_logging.cc @@ -26,8 +26,8 @@ namespace bluetooth { namespace hci { -void log_hci_event( - std::unique_ptr& command_view, EventView event_view, storage::StorageModule* storage_module) { +void log_hci_event(std::unique_ptr& command_view, EventView event_view, + storage::StorageModule* storage_module) { log::assert_that(event_view.IsValid(), "assert failed: event_view.IsValid()"); EventCode event_code = event_view.GetEventCode(); switch (event_code) { @@ -82,15 +82,15 @@ void log_link_layer_connection_command(std::unique_ptr& command_vie // get ConnectionManagementCommandView ConnectionManagementCommandView connection_management_command_view = - ConnectionManagementCommandView::Create(AclCommandView::Create(*command_view)); - log::assert_that( - connection_management_command_view.IsValid(), - "assert failed: connection_management_command_view.IsValid()"); + ConnectionManagementCommandView::Create(AclCommandView::Create(*command_view)); + log::assert_that(connection_management_command_view.IsValid(), + "assert failed: connection_management_command_view.IsValid()"); switch (op_code) { case OpCode::CREATE_CONNECTION: { - auto create_connection_view = CreateConnectionView::Create(std::move(connection_management_command_view)); - log::assert_that( - create_connection_view.IsValid(), "assert failed: create_connection_view.IsValid()"); + auto create_connection_view = + CreateConnectionView::Create(std::move(connection_management_command_view)); + log::assert_that(create_connection_view.IsValid(), + "assert failed: create_connection_view.IsValid()"); address = create_connection_view.GetBdAddr(); direction = android::bluetooth::DIRECTION_OUTGOING; link_type = android::bluetooth::LINK_TYPE_ACL; @@ -98,10 +98,9 @@ void log_link_layer_connection_command(std::unique_ptr& command_vie } case OpCode::CREATE_CONNECTION_CANCEL: { auto create_connection_cancel_view = - CreateConnectionCancelView::Create(std::move(connection_management_command_view)); - log::assert_that( - create_connection_cancel_view.IsValid(), - "assert failed: create_connection_cancel_view.IsValid()"); + CreateConnectionCancelView::Create(std::move(connection_management_command_view)); + log::assert_that(create_connection_cancel_view.IsValid(), + "assert failed: create_connection_cancel_view.IsValid()"); address = create_connection_cancel_view.GetBdAddr(); direction = android::bluetooth::DIRECTION_OUTGOING; link_type = android::bluetooth::LINK_TYPE_ACL; @@ -116,60 +115,56 @@ void log_link_layer_connection_command(std::unique_ptr& command_vie } case OpCode::SETUP_SYNCHRONOUS_CONNECTION: { auto setup_synchronous_connection_view = SetupSynchronousConnectionView::Create( - ScoConnectionCommandView::Create(std::move(connection_management_command_view))); - log::assert_that( - setup_synchronous_connection_view.IsValid(), - "assert failed: setup_synchronous_connection_view.IsValid()"); + ScoConnectionCommandView::Create(std::move(connection_management_command_view))); + log::assert_that(setup_synchronous_connection_view.IsValid(), + "assert failed: setup_synchronous_connection_view.IsValid()"); connection_handle = setup_synchronous_connection_view.GetConnectionHandle(); direction = android::bluetooth::DIRECTION_OUTGOING; break; } case OpCode::ENHANCED_SETUP_SYNCHRONOUS_CONNECTION: { - auto enhanced_setup_synchronous_connection_view = EnhancedSetupSynchronousConnectionView::Create( - ScoConnectionCommandView::Create(std::move(connection_management_command_view))); - log::assert_that( - enhanced_setup_synchronous_connection_view.IsValid(), - "assert failed: enhanced_setup_synchronous_connection_view.IsValid()"); + auto enhanced_setup_synchronous_connection_view = + EnhancedSetupSynchronousConnectionView::Create(ScoConnectionCommandView::Create( + std::move(connection_management_command_view))); + log::assert_that(enhanced_setup_synchronous_connection_view.IsValid(), + "assert failed: enhanced_setup_synchronous_connection_view.IsValid()"); connection_handle = enhanced_setup_synchronous_connection_view.GetConnectionHandle(); direction = android::bluetooth::DIRECTION_OUTGOING; break; } case OpCode::ACCEPT_CONNECTION_REQUEST: { auto accept_connection_request_view = - AcceptConnectionRequestView::Create(std::move(connection_management_command_view)); - log::assert_that( - accept_connection_request_view.IsValid(), - "assert failed: accept_connection_request_view.IsValid()"); + AcceptConnectionRequestView::Create(std::move(connection_management_command_view)); + log::assert_that(accept_connection_request_view.IsValid(), + "assert failed: accept_connection_request_view.IsValid()"); address = accept_connection_request_view.GetBdAddr(); direction = android::bluetooth::DIRECTION_INCOMING; break; } case OpCode::ACCEPT_SYNCHRONOUS_CONNECTION: { auto accept_synchronous_connection_view = AcceptSynchronousConnectionView::Create( - ScoConnectionCommandView::Create(std::move(connection_management_command_view))); - log::assert_that( - accept_synchronous_connection_view.IsValid(), - "assert failed: accept_synchronous_connection_view.IsValid()"); + ScoConnectionCommandView::Create(std::move(connection_management_command_view))); + log::assert_that(accept_synchronous_connection_view.IsValid(), + "assert failed: accept_synchronous_connection_view.IsValid()"); address = accept_synchronous_connection_view.GetBdAddr(); direction = android::bluetooth::DIRECTION_INCOMING; break; } case OpCode::ENHANCED_ACCEPT_SYNCHRONOUS_CONNECTION: { - auto enhanced_accept_synchronous_connection_view = EnhancedAcceptSynchronousConnectionView::Create( - ScoConnectionCommandView::Create(std::move(connection_management_command_view))); - log::assert_that( - enhanced_accept_synchronous_connection_view.IsValid(), - "assert failed: enhanced_accept_synchronous_connection_view.IsValid()"); + auto enhanced_accept_synchronous_connection_view = + EnhancedAcceptSynchronousConnectionView::Create(ScoConnectionCommandView::Create( + std::move(connection_management_command_view))); + log::assert_that(enhanced_accept_synchronous_connection_view.IsValid(), + "assert failed: enhanced_accept_synchronous_connection_view.IsValid()"); address = enhanced_accept_synchronous_connection_view.GetBdAddr(); direction = android::bluetooth::DIRECTION_INCOMING; break; } case OpCode::REJECT_CONNECTION_REQUEST: { auto reject_connection_request_view = - RejectConnectionRequestView::Create(std::move(connection_management_command_view)); - log::assert_that( - reject_connection_request_view.IsValid(), - "assert failed: reject_connection_request_view.IsValid()"); + RejectConnectionRequestView::Create(std::move(connection_management_command_view)); + log::assert_that(reject_connection_request_view.IsValid(), + "assert failed: reject_connection_request_view.IsValid()"); address = reject_connection_request_view.GetBdAddr(); reason = static_cast(reject_connection_request_view.GetReason()); direction = android::bluetooth::DIRECTION_INCOMING; @@ -177,63 +172,62 @@ void log_link_layer_connection_command(std::unique_ptr& command_vie } case OpCode::REJECT_SYNCHRONOUS_CONNECTION: { auto reject_synchronous_connection_view = RejectSynchronousConnectionView::Create( - ScoConnectionCommandView::Create(std::move(connection_management_command_view))); - log::assert_that( - reject_synchronous_connection_view.IsValid(), - "assert failed: reject_synchronous_connection_view.IsValid()"); + ScoConnectionCommandView::Create(std::move(connection_management_command_view))); + log::assert_that(reject_synchronous_connection_view.IsValid(), + "assert failed: reject_synchronous_connection_view.IsValid()"); address = reject_synchronous_connection_view.GetBdAddr(); reason = static_cast(reject_synchronous_connection_view.GetReason()); direction = android::bluetooth::DIRECTION_INCOMING; break; } case OpCode::LE_CREATE_CONNECTION: { - auto le_create_connection_view = LeCreateConnectionView::Create( - LeConnectionManagementCommandView::Create(std::move(connection_management_command_view))); - log::assert_that( - le_create_connection_view.IsValid(), - "assert failed: le_create_connection_view.IsValid()"); + auto le_create_connection_view = + LeCreateConnectionView::Create(LeConnectionManagementCommandView::Create( + std::move(connection_management_command_view))); + log::assert_that(le_create_connection_view.IsValid(), + "assert failed: le_create_connection_view.IsValid()"); address = le_create_connection_view.GetPeerAddress(); direction = android::bluetooth::DIRECTION_INCOMING; link_type = android::bluetooth::LINK_TYPE_ACL; break; } case OpCode::LE_EXTENDED_CREATE_CONNECTION: { - auto le_extended_create_connection_view = LeExtendedCreateConnectionView::Create( - LeConnectionManagementCommandView::Create(std::move(connection_management_command_view))); - log::assert_that( - le_extended_create_connection_view.IsValid(), - "assert failed: le_extended_create_connection_view.IsValid()"); + auto le_extended_create_connection_view = + LeExtendedCreateConnectionView::Create(LeConnectionManagementCommandView::Create( + std::move(connection_management_command_view))); + log::assert_that(le_extended_create_connection_view.IsValid(), + "assert failed: le_extended_create_connection_view.IsValid()"); address = le_extended_create_connection_view.GetPeerAddress(); direction = android::bluetooth::DIRECTION_OUTGOING; link_type = android::bluetooth::LINK_TYPE_ACL; break; } case OpCode::LE_CREATE_CONNECTION_CANCEL: { - auto le_create_connection_cancel_view = LeCreateConnectionCancelView::Create( - LeConnectionManagementCommandView::Create(std::move(connection_management_command_view))); - log::assert_that( - le_create_connection_cancel_view.IsValid(), - "assert failed: le_create_connection_cancel_view.IsValid()"); + auto le_create_connection_cancel_view = + LeCreateConnectionCancelView::Create(LeConnectionManagementCommandView::Create( + std::move(connection_management_command_view))); + log::assert_that(le_create_connection_cancel_view.IsValid(), + "assert failed: le_create_connection_cancel_view.IsValid()"); direction = android::bluetooth::DIRECTION_OUTGOING; link_type = android::bluetooth::LINK_TYPE_ACL; break; } case OpCode::LE_CLEAR_FILTER_ACCEPT_LIST: { - auto le_clear_filter_accept_list_view = LeClearFilterAcceptListView::Create( - LeConnectionManagementCommandView::Create(std::move(connection_management_command_view))); - log::assert_that( - le_clear_filter_accept_list_view.IsValid(), - "assert failed: le_clear_filter_accept_list_view.IsValid()"); + auto le_clear_filter_accept_list_view = + LeClearFilterAcceptListView::Create(LeConnectionManagementCommandView::Create( + std::move(connection_management_command_view))); + log::assert_that(le_clear_filter_accept_list_view.IsValid(), + "assert failed: le_clear_filter_accept_list_view.IsValid()"); direction = android::bluetooth::DIRECTION_INCOMING; link_type = android::bluetooth::LINK_TYPE_ACL; break; } case OpCode::LE_ADD_DEVICE_TO_FILTER_ACCEPT_LIST: { - auto le_add_device_to_accept_list_view = LeAddDeviceToFilterAcceptListView::Create( - LeConnectionManagementCommandView::Create(std::move(connection_management_command_view))); - log::assert_that( - le_add_device_to_accept_list_view.IsValid(), - "assert failed: le_add_device_to_accept_list_view.IsValid()"); + auto le_add_device_to_accept_list_view = + LeAddDeviceToFilterAcceptListView::Create(LeConnectionManagementCommandView::Create( + std::move(connection_management_command_view))); + log::assert_that(le_add_device_to_accept_list_view.IsValid(), + "assert failed: le_add_device_to_accept_list_view.IsValid()"); address = le_add_device_to_accept_list_view.GetAddress(); direction = android::bluetooth::DIRECTION_INCOMING; link_type = android::bluetooth::LINK_TYPE_ACL; @@ -241,10 +235,10 @@ void log_link_layer_connection_command(std::unique_ptr& command_vie } case OpCode::LE_REMOVE_DEVICE_FROM_FILTER_ACCEPT_LIST: { auto le_remove_device_from_accept_list_view = LeRemoveDeviceFromFilterAcceptListView::Create( - LeConnectionManagementCommandView::Create(std::move(connection_management_command_view))); - log::assert_that( - le_remove_device_from_accept_list_view.IsValid(), - "assert failed: le_remove_device_from_accept_list_view.IsValid()"); + LeConnectionManagementCommandView::Create( + std::move(connection_management_command_view))); + log::assert_that(le_remove_device_from_accept_list_view.IsValid(), + "assert failed: le_remove_device_from_accept_list_view.IsValid()"); address = le_remove_device_from_accept_list_view.GetAddress(); direction = android::bluetooth::DIRECTION_INCOMING; link_type = android::bluetooth::LINK_TYPE_ACL; @@ -254,18 +248,12 @@ void log_link_layer_connection_command(std::unique_ptr& command_vie return; } os::LogMetricLinkLayerConnectionEvent( - &address, - connection_handle, - direction, - link_type, - static_cast(op_code), - static_cast(event_code), - kUnknownBleEvt, - status, - static_cast(reason)); + &address, connection_handle, direction, link_type, static_cast(op_code), + static_cast(event_code), kUnknownBleEvt, status, static_cast(reason)); } -void log_link_layer_connection_command_status(std::unique_ptr& command_view, ErrorCode status) { +void log_link_layer_connection_command_status(std::unique_ptr& command_view, + ErrorCode status) { // get op_code log::assert_that(command_view->IsValid(), "assert failed: command_view->IsValid()"); OpCode op_code = command_view->GetOpCode(); @@ -281,15 +269,15 @@ void log_link_layer_connection_command_status(std::unique_ptr& comm // get ConnectionManagementCommandView ConnectionManagementCommandView connection_management_command_view = - ConnectionManagementCommandView::Create(AclCommandView::Create(*command_view)); - log::assert_that( - connection_management_command_view.IsValid(), - "assert failed: connection_management_command_view.IsValid()"); + ConnectionManagementCommandView::Create(AclCommandView::Create(*command_view)); + log::assert_that(connection_management_command_view.IsValid(), + "assert failed: connection_management_command_view.IsValid()"); switch (op_code) { case OpCode::CREATE_CONNECTION: { - auto create_connection_view = CreateConnectionView::Create(std::move(connection_management_command_view)); - log::assert_that( - create_connection_view.IsValid(), "assert failed: create_connection_view.IsValid()"); + auto create_connection_view = + CreateConnectionView::Create(std::move(connection_management_command_view)); + log::assert_that(create_connection_view.IsValid(), + "assert failed: create_connection_view.IsValid()"); address = create_connection_view.GetBdAddr(); direction = android::bluetooth::DIRECTION_OUTGOING; link_type = android::bluetooth::LINK_TYPE_ACL; @@ -297,10 +285,9 @@ void log_link_layer_connection_command_status(std::unique_ptr& comm } case OpCode::CREATE_CONNECTION_CANCEL: { auto create_connection_cancel_view = - CreateConnectionCancelView::Create(std::move(connection_management_command_view)); - log::assert_that( - create_connection_cancel_view.IsValid(), - "assert failed: create_connection_cancel_view.IsValid()"); + CreateConnectionCancelView::Create(std::move(connection_management_command_view)); + log::assert_that(create_connection_cancel_view.IsValid(), + "assert failed: create_connection_cancel_view.IsValid()"); address = create_connection_cancel_view.GetBdAddr(); direction = android::bluetooth::DIRECTION_OUTGOING; link_type = android::bluetooth::LINK_TYPE_ACL; @@ -315,60 +302,56 @@ void log_link_layer_connection_command_status(std::unique_ptr& comm } case OpCode::SETUP_SYNCHRONOUS_CONNECTION: { auto setup_synchronous_connection_view = SetupSynchronousConnectionView::Create( - ScoConnectionCommandView::Create(std::move(connection_management_command_view))); - log::assert_that( - setup_synchronous_connection_view.IsValid(), - "assert failed: setup_synchronous_connection_view.IsValid()"); + ScoConnectionCommandView::Create(std::move(connection_management_command_view))); + log::assert_that(setup_synchronous_connection_view.IsValid(), + "assert failed: setup_synchronous_connection_view.IsValid()"); connection_handle = setup_synchronous_connection_view.GetConnectionHandle(); direction = android::bluetooth::DIRECTION_OUTGOING; break; } case OpCode::ENHANCED_SETUP_SYNCHRONOUS_CONNECTION: { - auto enhanced_setup_synchronous_connection_view = EnhancedSetupSynchronousConnectionView::Create( - ScoConnectionCommandView::Create(std::move(connection_management_command_view))); - log::assert_that( - enhanced_setup_synchronous_connection_view.IsValid(), - "assert failed: enhanced_setup_synchronous_connection_view.IsValid()"); + auto enhanced_setup_synchronous_connection_view = + EnhancedSetupSynchronousConnectionView::Create(ScoConnectionCommandView::Create( + std::move(connection_management_command_view))); + log::assert_that(enhanced_setup_synchronous_connection_view.IsValid(), + "assert failed: enhanced_setup_synchronous_connection_view.IsValid()"); connection_handle = enhanced_setup_synchronous_connection_view.GetConnectionHandle(); direction = android::bluetooth::DIRECTION_OUTGOING; break; } case OpCode::ACCEPT_CONNECTION_REQUEST: { auto accept_connection_request_view = - AcceptConnectionRequestView::Create(std::move(connection_management_command_view)); - log::assert_that( - accept_connection_request_view.IsValid(), - "assert failed: accept_connection_request_view.IsValid()"); + AcceptConnectionRequestView::Create(std::move(connection_management_command_view)); + log::assert_that(accept_connection_request_view.IsValid(), + "assert failed: accept_connection_request_view.IsValid()"); address = accept_connection_request_view.GetBdAddr(); direction = android::bluetooth::DIRECTION_INCOMING; break; } case OpCode::ACCEPT_SYNCHRONOUS_CONNECTION: { auto accept_synchronous_connection_view = AcceptSynchronousConnectionView::Create( - ScoConnectionCommandView::Create(std::move(connection_management_command_view))); - log::assert_that( - accept_synchronous_connection_view.IsValid(), - "assert failed: accept_synchronous_connection_view.IsValid()"); + ScoConnectionCommandView::Create(std::move(connection_management_command_view))); + log::assert_that(accept_synchronous_connection_view.IsValid(), + "assert failed: accept_synchronous_connection_view.IsValid()"); address = accept_synchronous_connection_view.GetBdAddr(); direction = android::bluetooth::DIRECTION_INCOMING; break; } case OpCode::ENHANCED_ACCEPT_SYNCHRONOUS_CONNECTION: { - auto enhanced_accept_synchronous_connection_view = EnhancedAcceptSynchronousConnectionView::Create( - ScoConnectionCommandView::Create(std::move(connection_management_command_view))); - log::assert_that( - enhanced_accept_synchronous_connection_view.IsValid(), - "assert failed: enhanced_accept_synchronous_connection_view.IsValid()"); + auto enhanced_accept_synchronous_connection_view = + EnhancedAcceptSynchronousConnectionView::Create(ScoConnectionCommandView::Create( + std::move(connection_management_command_view))); + log::assert_that(enhanced_accept_synchronous_connection_view.IsValid(), + "assert failed: enhanced_accept_synchronous_connection_view.IsValid()"); address = enhanced_accept_synchronous_connection_view.GetBdAddr(); direction = android::bluetooth::DIRECTION_INCOMING; break; } case OpCode::REJECT_CONNECTION_REQUEST: { auto reject_connection_request_view = - RejectConnectionRequestView::Create(std::move(connection_management_command_view)); - log::assert_that( - reject_connection_request_view.IsValid(), - "assert failed: reject_connection_request_view.IsValid()"); + RejectConnectionRequestView::Create(std::move(connection_management_command_view)); + log::assert_that(reject_connection_request_view.IsValid(), + "assert failed: reject_connection_request_view.IsValid()"); address = reject_connection_request_view.GetBdAddr(); reason = static_cast(reject_connection_request_view.GetReason()); direction = android::bluetooth::DIRECTION_INCOMING; @@ -376,22 +359,22 @@ void log_link_layer_connection_command_status(std::unique_ptr& comm } case OpCode::REJECT_SYNCHRONOUS_CONNECTION: { auto reject_synchronous_connection_view = RejectSynchronousConnectionView::Create( - ScoConnectionCommandView::Create(std::move(connection_management_command_view))); - log::assert_that( - reject_synchronous_connection_view.IsValid(), - "assert failed: reject_synchronous_connection_view.IsValid()"); + ScoConnectionCommandView::Create(std::move(connection_management_command_view))); + log::assert_that(reject_synchronous_connection_view.IsValid(), + "assert failed: reject_synchronous_connection_view.IsValid()"); address = reject_synchronous_connection_view.GetBdAddr(); reason = static_cast(reject_synchronous_connection_view.GetReason()); direction = android::bluetooth::DIRECTION_INCOMING; break; } case OpCode::LE_CREATE_CONNECTION: { - auto le_create_connection_view = LeCreateConnectionView::Create( - LeConnectionManagementCommandView::Create(std::move(connection_management_command_view))); - log::assert_that( - le_create_connection_view.IsValid(), - "assert failed: le_create_connection_view.IsValid()"); - uint8_t initiator_filter_policy = static_cast(le_create_connection_view.GetInitiatorFilterPolicy()); + auto le_create_connection_view = + LeCreateConnectionView::Create(LeConnectionManagementCommandView::Create( + std::move(connection_management_command_view))); + log::assert_that(le_create_connection_view.IsValid(), + "assert failed: le_create_connection_view.IsValid()"); + uint8_t initiator_filter_policy = + static_cast(le_create_connection_view.GetInitiatorFilterPolicy()); if (initiator_filter_policy != 0x00 && status == ErrorCode::SUCCESS) { return; } @@ -401,13 +384,13 @@ void log_link_layer_connection_command_status(std::unique_ptr& comm break; } case OpCode::LE_EXTENDED_CREATE_CONNECTION: { - auto le_extended_create_connection_view = LeExtendedCreateConnectionView::Create( - LeConnectionManagementCommandView::Create(std::move(connection_management_command_view))); - log::assert_that( - le_extended_create_connection_view.IsValid(), - "assert failed: le_extended_create_connection_view.IsValid()"); + auto le_extended_create_connection_view = + LeExtendedCreateConnectionView::Create(LeConnectionManagementCommandView::Create( + std::move(connection_management_command_view))); + log::assert_that(le_extended_create_connection_view.IsValid(), + "assert failed: le_extended_create_connection_view.IsValid()"); uint8_t initiator_filter_policy = - static_cast(le_extended_create_connection_view.GetInitiatorFilterPolicy()); + static_cast(le_extended_create_connection_view.GetInitiatorFilterPolicy()); if (initiator_filter_policy != 0x00 && status == ErrorCode::SUCCESS) { return; } @@ -417,11 +400,11 @@ void log_link_layer_connection_command_status(std::unique_ptr& comm break; } case OpCode::LE_CREATE_CONNECTION_CANCEL: { - auto le_create_connection_cancel_view = LeCreateConnectionCancelView::Create( - LeConnectionManagementCommandView::Create(std::move(connection_management_command_view))); - log::assert_that( - le_create_connection_cancel_view.IsValid(), - "assert failed: le_create_connection_cancel_view.IsValid()"); + auto le_create_connection_cancel_view = + LeCreateConnectionCancelView::Create(LeConnectionManagementCommandView::Create( + std::move(connection_management_command_view))); + log::assert_that(le_create_connection_cancel_view.IsValid(), + "assert failed: le_create_connection_cancel_view.IsValid()"); if (status == ErrorCode::SUCCESS) { return; } @@ -430,21 +413,21 @@ void log_link_layer_connection_command_status(std::unique_ptr& comm break; } case OpCode::LE_CLEAR_FILTER_ACCEPT_LIST: { - auto le_clear_filter_accept_list_view = LeClearFilterAcceptListView::Create( - LeConnectionManagementCommandView::Create(std::move(connection_management_command_view))); - log::assert_that( - le_clear_filter_accept_list_view.IsValid(), - "assert failed: le_clear_filter_accept_list_view.IsValid()"); + auto le_clear_filter_accept_list_view = + LeClearFilterAcceptListView::Create(LeConnectionManagementCommandView::Create( + std::move(connection_management_command_view))); + log::assert_that(le_clear_filter_accept_list_view.IsValid(), + "assert failed: le_clear_filter_accept_list_view.IsValid()"); direction = android::bluetooth::DIRECTION_INCOMING; link_type = android::bluetooth::LINK_TYPE_ACL; break; } case OpCode::LE_ADD_DEVICE_TO_FILTER_ACCEPT_LIST: { - auto le_add_device_to_accept_list_view = LeAddDeviceToFilterAcceptListView::Create( - LeConnectionManagementCommandView::Create(std::move(connection_management_command_view))); - log::assert_that( - le_add_device_to_accept_list_view.IsValid(), - "assert failed: le_add_device_to_accept_list_view.IsValid()"); + auto le_add_device_to_accept_list_view = + LeAddDeviceToFilterAcceptListView::Create(LeConnectionManagementCommandView::Create( + std::move(connection_management_command_view))); + log::assert_that(le_add_device_to_accept_list_view.IsValid(), + "assert failed: le_add_device_to_accept_list_view.IsValid()"); address = le_add_device_to_accept_list_view.GetAddress(); direction = android::bluetooth::DIRECTION_INCOMING; link_type = android::bluetooth::LINK_TYPE_ACL; @@ -452,10 +435,10 @@ void log_link_layer_connection_command_status(std::unique_ptr& comm } case OpCode::LE_REMOVE_DEVICE_FROM_FILTER_ACCEPT_LIST: { auto le_remove_device_from_accept_list_view = LeRemoveDeviceFromFilterAcceptListView::Create( - LeConnectionManagementCommandView::Create(std::move(connection_management_command_view))); - log::assert_that( - le_remove_device_from_accept_list_view.IsValid(), - "assert failed: le_remove_device_from_accept_list_view.IsValid()"); + LeConnectionManagementCommandView::Create( + std::move(connection_management_command_view))); + log::assert_that(le_remove_device_from_accept_list_view.IsValid(), + "assert failed: le_remove_device_from_accept_list_view.IsValid()"); address = le_remove_device_from_accept_list_view.GetAddress(); direction = android::bluetooth::DIRECTION_INCOMING; link_type = android::bluetooth::LINK_TYPE_ACL; @@ -465,21 +448,16 @@ void log_link_layer_connection_command_status(std::unique_ptr& comm return; } os::LogMetricLinkLayerConnectionEvent( - &address, - connection_handle, - direction, - link_type, - static_cast(op_code), - static_cast(event_code), - kUnknownBleEvt, - static_cast(status), - static_cast(reason)); + &address, connection_handle, direction, link_type, static_cast(op_code), + static_cast(event_code), kUnknownBleEvt, static_cast(status), + static_cast(reason)); } -void log_link_layer_connection_command_complete(EventView event_view, std::unique_ptr& command_view) { +void log_link_layer_connection_command_complete(EventView event_view, + std::unique_ptr& command_view) { CommandCompleteView command_complete_view = CommandCompleteView::Create(std::move(event_view)); - log::assert_that( - command_complete_view.IsValid(), "assert failed: command_complete_view.IsValid()"); + log::assert_that(command_complete_view.IsValid(), + "assert failed: command_complete_view.IsValid()"); OpCode op_code = command_complete_view.GetCommandOpCode(); // init parameters to log @@ -494,28 +472,27 @@ void log_link_layer_connection_command_complete(EventView event_view, std::uniqu // get ConnectionManagementCommandView ConnectionManagementCommandView connection_management_command_view = - ConnectionManagementCommandView::Create(AclCommandView::Create(*command_view)); - log::assert_that( - connection_management_command_view.IsValid(), - "assert failed: connection_management_command_view.IsValid()"); + ConnectionManagementCommandView::Create(AclCommandView::Create(*command_view)); + log::assert_that(connection_management_command_view.IsValid(), + "assert failed: connection_management_command_view.IsValid()"); switch (op_code) { case OpCode::LE_CLEAR_FILTER_ACCEPT_LIST: { - auto le_clear_filter_accept_list_view = LeClearFilterAcceptListView::Create( - LeConnectionManagementCommandView::Create(std::move(connection_management_command_view))); - log::assert_that( - le_clear_filter_accept_list_view.IsValid(), - "assert failed: le_clear_filter_accept_list_view.IsValid()"); + auto le_clear_filter_accept_list_view = + LeClearFilterAcceptListView::Create(LeConnectionManagementCommandView::Create( + std::move(connection_management_command_view))); + log::assert_that(le_clear_filter_accept_list_view.IsValid(), + "assert failed: le_clear_filter_accept_list_view.IsValid()"); direction = android::bluetooth::DIRECTION_INCOMING; link_type = android::bluetooth::LINK_TYPE_ACL; break; } case OpCode::LE_ADD_DEVICE_TO_FILTER_ACCEPT_LIST: { - auto le_add_device_to_accept_list_view = LeAddDeviceToFilterAcceptListView::Create( - LeConnectionManagementCommandView::Create(std::move(connection_management_command_view))); - log::assert_that( - le_add_device_to_accept_list_view.IsValid(), - "assert failed: le_add_device_to_accept_list_view.IsValid()"); + auto le_add_device_to_accept_list_view = + LeAddDeviceToFilterAcceptListView::Create(LeConnectionManagementCommandView::Create( + std::move(connection_management_command_view))); + log::assert_that(le_add_device_to_accept_list_view.IsValid(), + "assert failed: le_add_device_to_accept_list_view.IsValid()"); address = le_add_device_to_accept_list_view.GetAddress(); direction = android::bluetooth::DIRECTION_INCOMING; link_type = android::bluetooth::LINK_TYPE_ACL; @@ -523,10 +500,10 @@ void log_link_layer_connection_command_complete(EventView event_view, std::uniqu } case OpCode::LE_REMOVE_DEVICE_FROM_FILTER_ACCEPT_LIST: { auto le_remove_device_from_accept_list_view = LeRemoveDeviceFromFilterAcceptListView::Create( - LeConnectionManagementCommandView::Create(std::move(connection_management_command_view))); - log::assert_that( - le_remove_device_from_accept_list_view.IsValid(), - "assert failed: le_remove_device_from_accept_list_view.IsValid()"); + LeConnectionManagementCommandView::Create( + std::move(connection_management_command_view))); + log::assert_that(le_remove_device_from_accept_list_view.IsValid(), + "assert failed: le_remove_device_from_accept_list_view.IsValid()"); address = le_remove_device_from_accept_list_view.GetAddress(); direction = android::bluetooth::DIRECTION_INCOMING; link_type = android::bluetooth::LINK_TYPE_ACL; @@ -534,10 +511,9 @@ void log_link_layer_connection_command_complete(EventView event_view, std::uniqu } case OpCode::CREATE_CONNECTION_CANCEL: { auto create_connection_cancel_complete_view = - CreateConnectionCancelCompleteView::Create(std::move(command_complete_view)); - log::assert_that( - create_connection_cancel_complete_view.IsValid(), - "assert failed: create_connection_cancel_complete_view.IsValid()"); + CreateConnectionCancelCompleteView::Create(std::move(command_complete_view)); + log::assert_that(create_connection_cancel_complete_view.IsValid(), + "assert failed: create_connection_cancel_complete_view.IsValid()"); address = create_connection_cancel_complete_view.GetBdAddr(); direction = android::bluetooth::DIRECTION_OUTGOING; link_type = android::bluetooth::LINK_TYPE_ACL; @@ -546,10 +522,9 @@ void log_link_layer_connection_command_complete(EventView event_view, std::uniqu } case OpCode::LE_CREATE_CONNECTION_CANCEL: { auto le_create_connection_cancel_complete_view = - LeCreateConnectionCancelCompleteView::Create(std::move(command_complete_view)); - log::assert_that( - le_create_connection_cancel_complete_view.IsValid(), - "assert failed: le_create_connection_cancel_complete_view.IsValid()"); + LeCreateConnectionCancelCompleteView::Create(std::move(command_complete_view)); + log::assert_that(le_create_connection_cancel_complete_view.IsValid(), + "assert failed: le_create_connection_cancel_complete_view.IsValid()"); direction = android::bluetooth::DIRECTION_OUTGOING; link_type = android::bluetooth::LINK_TYPE_ACL; status = le_create_connection_cancel_complete_view.GetStatus(); @@ -559,18 +534,13 @@ void log_link_layer_connection_command_complete(EventView event_view, std::uniqu return; } os::LogMetricLinkLayerConnectionEvent( - &address, - connection_handle, - direction, - link_type, - static_cast(op_code), - static_cast(event_code), - kUnknownBleEvt, - static_cast(status), - static_cast(reason)); + &address, connection_handle, direction, link_type, static_cast(op_code), + static_cast(event_code), kUnknownBleEvt, static_cast(status), + static_cast(reason)); } -void log_link_layer_connection_other_hci_event(EventView packet, storage::StorageModule* storage_module) { +void log_link_layer_connection_other_hci_event(EventView packet, + storage::StorageModule* storage_module) { EventCode event_code = packet.GetEventCode(); Address address = Address::kEmpty; uint32_t connection_handle = bluetooth::os::kUnknownConnectionHandle; @@ -582,20 +552,16 @@ void log_link_layer_connection_other_hci_event(EventView packet, storage::Storag switch (event_code) { case EventCode::CONNECTION_COMPLETE: { auto connection_complete_view = ConnectionCompleteView::Create(std::move(packet)); - log::assert_that( - connection_complete_view.IsValid(), "assert failed: connection_complete_view.IsValid()"); + log::assert_that(connection_complete_view.IsValid(), + "assert failed: connection_complete_view.IsValid()"); address = connection_complete_view.GetBdAddr(); connection_handle = connection_complete_view.GetConnectionHandle(); link_type = static_cast(connection_complete_view.GetLinkType()); status = connection_complete_view.GetStatus(); // besides log link layer connection events, also log remote device manufacturer info - log_remote_device_information( - address, - android::bluetooth::ADDRESS_TYPE_PUBLIC, - connection_handle, - status, - storage_module); + log_remote_device_information(address, android::bluetooth::ADDRESS_TYPE_PUBLIC, + connection_handle, status, storage_module); if (status != ErrorCode::SUCCESS) { common::LogConnectionAdminAuditEvent("Connecting", address, status); @@ -604,8 +570,8 @@ void log_link_layer_connection_other_hci_event(EventView packet, storage::Storag } case EventCode::CONNECTION_REQUEST: { auto connection_request_view = ConnectionRequestView::Create(std::move(packet)); - log::assert_that( - connection_request_view.IsValid(), "assert failed: connection_request_view.IsValid()"); + log::assert_that(connection_request_view.IsValid(), + "assert failed: connection_request_view.IsValid()"); address = connection_request_view.GetBdAddr(); link_type = static_cast(connection_request_view.GetLinkType()); direction = android::bluetooth::DIRECTION_INCOMING; @@ -613,19 +579,18 @@ void log_link_layer_connection_other_hci_event(EventView packet, storage::Storag } case EventCode::DISCONNECTION_COMPLETE: { auto disconnection_complete_view = DisconnectionCompleteView::Create(std::move(packet)); - log::assert_that( - disconnection_complete_view.IsValid(), - "assert failed: disconnection_complete_view.IsValid()"); + log::assert_that(disconnection_complete_view.IsValid(), + "assert failed: disconnection_complete_view.IsValid()"); status = disconnection_complete_view.GetStatus(); connection_handle = disconnection_complete_view.GetConnectionHandle(); reason = disconnection_complete_view.GetReason(); break; } case EventCode::SYNCHRONOUS_CONNECTION_COMPLETE: { - auto synchronous_connection_complete_view = SynchronousConnectionCompleteView::Create(std::move(packet)); - log::assert_that( - synchronous_connection_complete_view.IsValid(), - "assert failed: synchronous_connection_complete_view.IsValid()"); + auto synchronous_connection_complete_view = + SynchronousConnectionCompleteView::Create(std::move(packet)); + log::assert_that(synchronous_connection_complete_view.IsValid(), + "assert failed: synchronous_connection_complete_view.IsValid()"); connection_handle = synchronous_connection_complete_view.GetConnectionHandle(); address = synchronous_connection_complete_view.GetBdAddr(); link_type = static_cast(synchronous_connection_complete_view.GetLinkType()); @@ -633,10 +598,10 @@ void log_link_layer_connection_other_hci_event(EventView packet, storage::Storag break; } case EventCode::SYNCHRONOUS_CONNECTION_CHANGED: { - auto synchronous_connection_changed_view = SynchronousConnectionChangedView::Create(std::move(packet)); - log::assert_that( - synchronous_connection_changed_view.IsValid(), - "assert failed: synchronous_connection_changed_view.IsValid()"); + auto synchronous_connection_changed_view = + SynchronousConnectionChangedView::Create(std::move(packet)); + log::assert_that(synchronous_connection_changed_view.IsValid(), + "assert failed: synchronous_connection_changed_view.IsValid()"); status = synchronous_connection_changed_view.GetStatus(); connection_handle = synchronous_connection_changed_view.GetConnectionHandle(); break; @@ -645,20 +610,15 @@ void log_link_layer_connection_other_hci_event(EventView packet, storage::Storag return; } os::LogMetricLinkLayerConnectionEvent( - &address, - connection_handle, - direction, - link_type, - static_cast(cmd), - static_cast(event_code), - android::bluetooth::hci::BLE_EVT_UNKNOWN, - static_cast(status), - static_cast(reason)); + &address, connection_handle, direction, link_type, static_cast(cmd), + static_cast(event_code), android::bluetooth::hci::BLE_EVT_UNKNOWN, + static_cast(status), static_cast(reason)); } void log_link_layer_connection_event_le_meta(LeMetaEventView le_meta_event_view) { SubeventCode leEvt = le_meta_event_view.GetSubeventCode(); - if (leEvt != SubeventCode::ENHANCED_CONNECTION_COMPLETE && leEvt != SubeventCode::CONNECTION_COMPLETE) { + if (leEvt != SubeventCode::ENHANCED_CONNECTION_COMPLETE && + leEvt != SubeventCode::CONNECTION_COMPLETE) { // function is called for all le meta events. Only need to process le connection complete. return; } @@ -673,18 +633,18 @@ void log_link_layer_connection_event_le_meta(LeMetaEventView le_meta_event_view) uint32_t cmd = android::bluetooth::hci::CMD_UNKNOWN; if (leEvt == SubeventCode::CONNECTION_COMPLETE) { - auto le_connection_complete_view = LeConnectionCompleteView::Create(std::move(le_meta_event_view)); - log::assert_that( - le_connection_complete_view.IsValid(), - "assert failed: le_connection_complete_view.IsValid()"); + auto le_connection_complete_view = + LeConnectionCompleteView::Create(std::move(le_meta_event_view)); + log::assert_that(le_connection_complete_view.IsValid(), + "assert failed: le_connection_complete_view.IsValid()"); address = le_connection_complete_view.GetPeerAddress(); connection_handle = le_connection_complete_view.GetConnectionHandle(); status = le_connection_complete_view.GetStatus(); } else if (leEvt == SubeventCode::ENHANCED_CONNECTION_COMPLETE) { - auto le_enhanced_connection_complete_view = LeEnhancedConnectionCompleteView::Create(std::move(le_meta_event_view)); - log::assert_that( - le_enhanced_connection_complete_view.IsValid(), - "assert failed: le_enhanced_connection_complete_view.IsValid()"); + auto le_enhanced_connection_complete_view = + LeEnhancedConnectionCompleteView::Create(std::move(le_meta_event_view)); + log::assert_that(le_enhanced_connection_complete_view.IsValid(), + "assert failed: le_enhanced_connection_complete_view.IsValid()"); address = le_enhanced_connection_complete_view.GetPeerAddress(); connection_handle = le_enhanced_connection_complete_view.GetConnectionHandle(); status = le_enhanced_connection_complete_view.GetStatus(); @@ -694,19 +654,13 @@ void log_link_layer_connection_event_le_meta(LeMetaEventView le_meta_event_view) } os::LogMetricLinkLayerConnectionEvent( - &address, - connection_handle, - direction, - link_type, - static_cast(cmd), - static_cast(event_code), - static_cast(leEvt), - static_cast(status), - static_cast(reason)); + &address, connection_handle, direction, link_type, static_cast(cmd), + static_cast(event_code), static_cast(leEvt), + static_cast(status), static_cast(reason)); if (status != ErrorCode::SUCCESS && status != ErrorCode::UNKNOWN_CONNECTION) { - // ERROR CODE 0x02, unknown connection identifier, means connection attempt was cancelled by host, so probably no - // need to log it. + // ERROR CODE 0x02, unknown connection identifier, means connection attempt was cancelled by + // host, so probably no need to log it. common::LogConnectionAdminAuditEvent("Connecting", address, status); } } @@ -722,70 +676,71 @@ void log_classic_pairing_other_hci_event(EventView packet) { switch (event_code) { case EventCode::IO_CAPABILITY_REQUEST: { - IoCapabilityRequestView io_capability_request_view = IoCapabilityRequestView::Create(std::move(packet)); - log::assert_that( - io_capability_request_view.IsValid(), - "assert failed: io_capability_request_view.IsValid()"); + IoCapabilityRequestView io_capability_request_view = + IoCapabilityRequestView::Create(std::move(packet)); + log::assert_that(io_capability_request_view.IsValid(), + "assert failed: io_capability_request_view.IsValid()"); address = io_capability_request_view.GetBdAddr(); break; } case EventCode::IO_CAPABILITY_RESPONSE: { - IoCapabilityResponseView io_capability_response_view = IoCapabilityResponseView::Create(std::move(packet)); - log::assert_that( - io_capability_response_view.IsValid(), - "assert failed: io_capability_response_view.IsValid()"); + IoCapabilityResponseView io_capability_response_view = + IoCapabilityResponseView::Create(std::move(packet)); + log::assert_that(io_capability_response_view.IsValid(), + "assert failed: io_capability_response_view.IsValid()"); address = io_capability_response_view.GetBdAddr(); break; } case EventCode::LINK_KEY_REQUEST: { LinkKeyRequestView link_key_request_view = LinkKeyRequestView::Create(std::move(packet)); - log::assert_that( - link_key_request_view.IsValid(), "assert failed: link_key_request_view.IsValid()"); + log::assert_that(link_key_request_view.IsValid(), + "assert failed: link_key_request_view.IsValid()"); address = link_key_request_view.GetBdAddr(); break; } case EventCode::LINK_KEY_NOTIFICATION: { - LinkKeyNotificationView link_key_notification_view = LinkKeyNotificationView::Create(std::move(packet)); - log::assert_that( - link_key_notification_view.IsValid(), - "assert failed: link_key_notification_view.IsValid()"); + LinkKeyNotificationView link_key_notification_view = + LinkKeyNotificationView::Create(std::move(packet)); + log::assert_that(link_key_notification_view.IsValid(), + "assert failed: link_key_notification_view.IsValid()"); address = link_key_notification_view.GetBdAddr(); break; } case EventCode::USER_PASSKEY_REQUEST: { - UserPasskeyRequestView user_passkey_request_view = UserPasskeyRequestView::Create(std::move(packet)); - log::assert_that( - user_passkey_request_view.IsValid(), - "assert failed: user_passkey_request_view.IsValid()"); + UserPasskeyRequestView user_passkey_request_view = + UserPasskeyRequestView::Create(std::move(packet)); + log::assert_that(user_passkey_request_view.IsValid(), + "assert failed: user_passkey_request_view.IsValid()"); address = user_passkey_request_view.GetBdAddr(); break; } case EventCode::USER_PASSKEY_NOTIFICATION: { - UserPasskeyNotificationView user_passkey_notification_view = UserPasskeyNotificationView::Create(std::move(packet)); - log::assert_that( - user_passkey_notification_view.IsValid(), - "assert failed: user_passkey_notification_view.IsValid()"); + UserPasskeyNotificationView user_passkey_notification_view = + UserPasskeyNotificationView::Create(std::move(packet)); + log::assert_that(user_passkey_notification_view.IsValid(), + "assert failed: user_passkey_notification_view.IsValid()"); address = user_passkey_notification_view.GetBdAddr(); break; } case EventCode::USER_CONFIRMATION_REQUEST: { - UserConfirmationRequestView user_confirmation_request_view = UserConfirmationRequestView::Create(std::move(packet)); - log::assert_that( - user_confirmation_request_view.IsValid(), - "assert failed: user_confirmation_request_view.IsValid()"); + UserConfirmationRequestView user_confirmation_request_view = + UserConfirmationRequestView::Create(std::move(packet)); + log::assert_that(user_confirmation_request_view.IsValid(), + "assert failed: user_confirmation_request_view.IsValid()"); address = user_confirmation_request_view.GetBdAddr(); break; } case EventCode::KEYPRESS_NOTIFICATION: { - KeypressNotificationView keypress_notification_view = KeypressNotificationView::Create(std::move(packet)); - log::assert_that( - keypress_notification_view.IsValid(), - "assert failed: keypress_notification_view.IsValid()"); + KeypressNotificationView keypress_notification_view = + KeypressNotificationView::Create(std::move(packet)); + log::assert_that(keypress_notification_view.IsValid(), + "assert failed: keypress_notification_view.IsValid()"); address = keypress_notification_view.GetBdAddr(); break; } case EventCode::REMOTE_OOB_DATA_REQUEST: { - RemoteOobDataRequestView remote_oob_data_request_view = RemoteOobDataRequestView::Create(std::move(packet)); + RemoteOobDataRequestView remote_oob_data_request_view = + RemoteOobDataRequestView::Create(std::move(packet)); if (!remote_oob_data_request_view.IsValid()) { log::warn("remote_oob_data_request_view not valid"); return; @@ -794,16 +749,17 @@ void log_classic_pairing_other_hci_event(EventView packet) { break; } case EventCode::SIMPLE_PAIRING_COMPLETE: { - SimplePairingCompleteView simple_pairing_complete_view = SimplePairingCompleteView::Create(std::move(packet)); - log::assert_that( - simple_pairing_complete_view.IsValid(), - "assert failed: simple_pairing_complete_view.IsValid()"); + SimplePairingCompleteView simple_pairing_complete_view = + SimplePairingCompleteView::Create(std::move(packet)); + log::assert_that(simple_pairing_complete_view.IsValid(), + "assert failed: simple_pairing_complete_view.IsValid()"); address = simple_pairing_complete_view.GetBdAddr(); status = simple_pairing_complete_view.GetStatus(); break; } case EventCode::REMOTE_NAME_REQUEST_COMPLETE: { - RemoteNameRequestCompleteView remote_name_request_complete_view = RemoteNameRequestCompleteView::Create(std::move(packet)); + RemoteNameRequestCompleteView remote_name_request_complete_view = + RemoteNameRequestCompleteView::Create(std::move(packet)); if (!remote_name_request_complete_view.IsValid()) { log::warn("remote_name_request_complete_view not valid"); return; @@ -813,18 +769,18 @@ void log_classic_pairing_other_hci_event(EventView packet) { break; } case EventCode::AUTHENTICATION_COMPLETE: { - AuthenticationCompleteView authentication_complete_view = AuthenticationCompleteView::Create(std::move(packet)); - log::assert_that( - authentication_complete_view.IsValid(), - "assert failed: authentication_complete_view.IsValid()"); + AuthenticationCompleteView authentication_complete_view = + AuthenticationCompleteView::Create(std::move(packet)); + log::assert_that(authentication_complete_view.IsValid(), + "assert failed: authentication_complete_view.IsValid()"); status = authentication_complete_view.GetStatus(); connection_handle = authentication_complete_view.GetConnectionHandle(); break; } case EventCode::ENCRYPTION_CHANGE: { EncryptionChangeView encryption_change_view = EncryptionChangeView::Create(std::move(packet)); - log::assert_that( - encryption_change_view.IsValid(), "assert failed: encryption_change_view.IsValid()"); + log::assert_that(encryption_change_view.IsValid(), + "assert failed: encryption_change_view.IsValid()"); status = encryption_change_view.GetStatus(); connection_handle = encryption_change_view.GetConnectionHandle(); value = static_cast(encryption_change_view.GetEncryptionEnabled()); @@ -833,17 +789,13 @@ void log_classic_pairing_other_hci_event(EventView packet) { default: return; } - os::LogMetricClassicPairingEvent( - address, - connection_handle, - static_cast(cmd), - static_cast(event_code), - static_cast(status), - static_cast(reason), - value); + os::LogMetricClassicPairingEvent(address, connection_handle, static_cast(cmd), + static_cast(event_code), static_cast(status), + static_cast(reason), value); } -void log_classic_pairing_command_status(std::unique_ptr& command_view, ErrorCode status) { +void log_classic_pairing_command_status(std::unique_ptr& command_view, + ErrorCode status) { // get op_code log::assert_that(command_view->IsValid(), "assert failed: command_view->IsValid()"); OpCode op_code = command_view->GetOpCode(); @@ -857,147 +809,137 @@ void log_classic_pairing_command_status(std::unique_ptr& command_vi // create SecurityCommandView SecurityCommandView security_command_view = SecurityCommandView::Create(*command_view); - log::assert_that( - security_command_view.IsValid(), "assert failed: security_command_view.IsValid()"); + log::assert_that(security_command_view.IsValid(), + "assert failed: security_command_view.IsValid()"); // create ConnectionManagementCommandView ConnectionManagementCommandView connection_management_command_view = - ConnectionManagementCommandView::Create(AclCommandView::Create(*command_view)); - log::assert_that( - connection_management_command_view.IsValid(), - "assert failed: connection_management_command_view.IsValid()"); + ConnectionManagementCommandView::Create(AclCommandView::Create(*command_view)); + log::assert_that(connection_management_command_view.IsValid(), + "assert failed: connection_management_command_view.IsValid()"); // create DiscoveryCommandView DiscoveryCommandView discovery_command_view = DiscoveryCommandView::Create(*command_view); - log::assert_that( - discovery_command_view.IsValid(), "assert failed: discovery_command_view.IsValid()"); + log::assert_that(discovery_command_view.IsValid(), + "assert failed: discovery_command_view.IsValid()"); switch (op_code) { case OpCode::READ_LOCAL_OOB_DATA: { - ReadLocalOobDataView read_local_oob_data_view = ReadLocalOobDataView::Create(std::move(security_command_view)); - log::assert_that( - read_local_oob_data_view.IsValid(), "assert failed: read_local_oob_data_view.IsValid()"); + ReadLocalOobDataView read_local_oob_data_view = + ReadLocalOobDataView::Create(std::move(security_command_view)); + log::assert_that(read_local_oob_data_view.IsValid(), + "assert failed: read_local_oob_data_view.IsValid()"); break; } case OpCode::WRITE_SIMPLE_PAIRING_MODE: { - WriteSimplePairingModeView write_simple_pairing_mode_view - = WriteSimplePairingModeView::Create(std::move(security_command_view)); - log::assert_that( - write_simple_pairing_mode_view.IsValid(), - "assert failed: write_simple_pairing_mode_view.IsValid()"); + WriteSimplePairingModeView write_simple_pairing_mode_view = + WriteSimplePairingModeView::Create(std::move(security_command_view)); + log::assert_that(write_simple_pairing_mode_view.IsValid(), + "assert failed: write_simple_pairing_mode_view.IsValid()"); value = static_cast(write_simple_pairing_mode_view.GetSimplePairingMode()); break; } case OpCode::WRITE_SECURE_CONNECTIONS_HOST_SUPPORT: { - WriteSecureConnectionsHostSupportView write_secure_connections_host_support_view - = WriteSecureConnectionsHostSupportView::Create(std::move(security_command_view)); - log::assert_that( - write_secure_connections_host_support_view.IsValid(), - "assert failed: write_secure_connections_host_support_view.IsValid()"); - value = static_cast(write_secure_connections_host_support_view.GetSecureConnectionsHostSupport()); + WriteSecureConnectionsHostSupportView write_secure_connections_host_support_view = + WriteSecureConnectionsHostSupportView::Create(std::move(security_command_view)); + log::assert_that(write_secure_connections_host_support_view.IsValid(), + "assert failed: write_secure_connections_host_support_view.IsValid()"); + value = static_cast( + write_secure_connections_host_support_view.GetSecureConnectionsHostSupport()); break; } case OpCode::AUTHENTICATION_REQUESTED: { - AuthenticationRequestedView authentication_requested_view - = AuthenticationRequestedView::Create(std::move(connection_management_command_view)); - log::assert_that( - authentication_requested_view.IsValid(), - "assert failed: authentication_requested_view.IsValid()"); + AuthenticationRequestedView authentication_requested_view = + AuthenticationRequestedView::Create(std::move(connection_management_command_view)); + log::assert_that(authentication_requested_view.IsValid(), + "assert failed: authentication_requested_view.IsValid()"); connection_handle = authentication_requested_view.GetConnectionHandle(); break; } case OpCode::SET_CONNECTION_ENCRYPTION: { - SetConnectionEncryptionView set_connection_encryption_view - = SetConnectionEncryptionView::Create(std::move(connection_management_command_view)); - log::assert_that( - set_connection_encryption_view.IsValid(), - "assert failed: set_connection_encryption_view.IsValid()"); + SetConnectionEncryptionView set_connection_encryption_view = + SetConnectionEncryptionView::Create(std::move(connection_management_command_view)); + log::assert_that(set_connection_encryption_view.IsValid(), + "assert failed: set_connection_encryption_view.IsValid()"); connection_handle = set_connection_encryption_view.GetConnectionHandle(); value = static_cast(set_connection_encryption_view.GetEncryptionEnable()); break; } case OpCode::REMOTE_NAME_REQUEST: { - RemoteNameRequestView remote_name_request_view = RemoteNameRequestView::Create(std::move(discovery_command_view)); - log::assert_that( - remote_name_request_view.IsValid(), "assert failed: remote_name_request_view.IsValid()"); + RemoteNameRequestView remote_name_request_view = + RemoteNameRequestView::Create(std::move(discovery_command_view)); + log::assert_that(remote_name_request_view.IsValid(), + "assert failed: remote_name_request_view.IsValid()"); address = remote_name_request_view.GetBdAddr(); break; } case OpCode::REMOTE_NAME_REQUEST_CANCEL: { - RemoteNameRequestCancelView remote_name_request_cancel_view - = RemoteNameRequestCancelView::Create(std::move(discovery_command_view)); - log::assert_that( - remote_name_request_cancel_view.IsValid(), - "assert failed: remote_name_request_cancel_view.IsValid()"); + RemoteNameRequestCancelView remote_name_request_cancel_view = + RemoteNameRequestCancelView::Create(std::move(discovery_command_view)); + log::assert_that(remote_name_request_cancel_view.IsValid(), + "assert failed: remote_name_request_cancel_view.IsValid()"); address = remote_name_request_cancel_view.GetBdAddr(); break; } case OpCode::LINK_KEY_REQUEST_REPLY: { - LinkKeyRequestReplyView link_key_request_reply_view - = LinkKeyRequestReplyView::Create(std::move(security_command_view)); - log::assert_that( - link_key_request_reply_view.IsValid(), - "assert failed: link_key_request_reply_view.IsValid()"); + LinkKeyRequestReplyView link_key_request_reply_view = + LinkKeyRequestReplyView::Create(std::move(security_command_view)); + log::assert_that(link_key_request_reply_view.IsValid(), + "assert failed: link_key_request_reply_view.IsValid()"); address = link_key_request_reply_view.GetBdAddr(); break; } case OpCode::LINK_KEY_REQUEST_NEGATIVE_REPLY: { - LinkKeyRequestNegativeReplyView link_key_request_negative_reply_view - = LinkKeyRequestNegativeReplyView::Create(std::move(security_command_view)); - log::assert_that( - link_key_request_negative_reply_view.IsValid(), - "assert failed: link_key_request_negative_reply_view.IsValid()"); + LinkKeyRequestNegativeReplyView link_key_request_negative_reply_view = + LinkKeyRequestNegativeReplyView::Create(std::move(security_command_view)); + log::assert_that(link_key_request_negative_reply_view.IsValid(), + "assert failed: link_key_request_negative_reply_view.IsValid()"); address = link_key_request_negative_reply_view.GetBdAddr(); break; } case OpCode::IO_CAPABILITY_REQUEST_REPLY: { - IoCapabilityRequestReplyView io_capability_request_reply_view - = IoCapabilityRequestReplyView::Create(std::move(security_command_view)); - log::assert_that( - io_capability_request_reply_view.IsValid(), - "assert failed: io_capability_request_reply_view.IsValid()"); + IoCapabilityRequestReplyView io_capability_request_reply_view = + IoCapabilityRequestReplyView::Create(std::move(security_command_view)); + log::assert_that(io_capability_request_reply_view.IsValid(), + "assert failed: io_capability_request_reply_view.IsValid()"); address = io_capability_request_reply_view.GetBdAddr(); break; } case OpCode::USER_CONFIRMATION_REQUEST_REPLY: { - UserConfirmationRequestReplyView user_confirmation_request_reply - = UserConfirmationRequestReplyView::Create(std::move(security_command_view)); - log::assert_that( - user_confirmation_request_reply.IsValid(), - "assert failed: user_confirmation_request_reply.IsValid()"); + UserConfirmationRequestReplyView user_confirmation_request_reply = + UserConfirmationRequestReplyView::Create(std::move(security_command_view)); + log::assert_that(user_confirmation_request_reply.IsValid(), + "assert failed: user_confirmation_request_reply.IsValid()"); address = user_confirmation_request_reply.GetBdAddr(); break; } case OpCode::USER_CONFIRMATION_REQUEST_NEGATIVE_REPLY: { - UserConfirmationRequestNegativeReplyView user_confirmation_request_negative_reply - = UserConfirmationRequestNegativeReplyView::Create(std::move(security_command_view)); - log::assert_that( - user_confirmation_request_negative_reply.IsValid(), - "assert failed: user_confirmation_request_negative_reply.IsValid()"); + UserConfirmationRequestNegativeReplyView user_confirmation_request_negative_reply = + UserConfirmationRequestNegativeReplyView::Create(std::move(security_command_view)); + log::assert_that(user_confirmation_request_negative_reply.IsValid(), + "assert failed: user_confirmation_request_negative_reply.IsValid()"); address = user_confirmation_request_negative_reply.GetBdAddr(); break; } case OpCode::USER_PASSKEY_REQUEST_REPLY: { - UserPasskeyRequestReplyView user_passkey_request_reply - = UserPasskeyRequestReplyView::Create(std::move(security_command_view)); - log::assert_that( - user_passkey_request_reply.IsValid(), - "assert failed: user_passkey_request_reply.IsValid()"); + UserPasskeyRequestReplyView user_passkey_request_reply = + UserPasskeyRequestReplyView::Create(std::move(security_command_view)); + log::assert_that(user_passkey_request_reply.IsValid(), + "assert failed: user_passkey_request_reply.IsValid()"); address = user_passkey_request_reply.GetBdAddr(); break; } case OpCode::USER_PASSKEY_REQUEST_NEGATIVE_REPLY: { - UserPasskeyRequestNegativeReplyView user_passkey_request_negative_reply - = UserPasskeyRequestNegativeReplyView::Create(std::move(security_command_view)); - log::assert_that( - user_passkey_request_negative_reply.IsValid(), - "assert failed: user_passkey_request_negative_reply.IsValid()"); + UserPasskeyRequestNegativeReplyView user_passkey_request_negative_reply = + UserPasskeyRequestNegativeReplyView::Create(std::move(security_command_view)); + log::assert_that(user_passkey_request_negative_reply.IsValid(), + "assert failed: user_passkey_request_negative_reply.IsValid()"); address = user_passkey_request_negative_reply.GetBdAddr(); break; } case OpCode::REMOTE_OOB_DATA_REQUEST_REPLY: { - RemoteOobDataRequestReplyView remote_oob_data_request_reply_view - = RemoteOobDataRequestReplyView::Create(std::move(security_command_view)); + RemoteOobDataRequestReplyView remote_oob_data_request_reply_view = + RemoteOobDataRequestReplyView::Create(std::move(security_command_view)); if (!remote_oob_data_request_reply_view.IsValid()) { log::warn("remote_oob_data_request_reply_view is not valid."); return; @@ -1006,8 +948,8 @@ void log_classic_pairing_command_status(std::unique_ptr& command_vi break; } case OpCode::REMOTE_OOB_DATA_REQUEST_NEGATIVE_REPLY: { - RemoteOobDataRequestNegativeReplyView remote_oob_data_request_negative_reply_view - = RemoteOobDataRequestNegativeReplyView::Create(std::move(security_command_view)); + RemoteOobDataRequestNegativeReplyView remote_oob_data_request_negative_reply_view = + RemoteOobDataRequestNegativeReplyView::Create(std::move(security_command_view)); if (!remote_oob_data_request_negative_reply_view.IsValid()) { log::warn("remote_oob_data_request_negative_reply_view is not valid."); return; @@ -1016,11 +958,10 @@ void log_classic_pairing_command_status(std::unique_ptr& command_vi break; } case OpCode::IO_CAPABILITY_REQUEST_NEGATIVE_REPLY: { - IoCapabilityRequestNegativeReplyView io_capability_request_negative_reply_view - = IoCapabilityRequestNegativeReplyView::Create(std::move(security_command_view)); - log::assert_that( - io_capability_request_negative_reply_view.IsValid(), - "assert failed: io_capability_request_negative_reply_view.IsValid()"); + IoCapabilityRequestNegativeReplyView io_capability_request_negative_reply_view = + IoCapabilityRequestNegativeReplyView::Create(std::move(security_command_view)); + log::assert_that(io_capability_request_negative_reply_view.IsValid(), + "assert failed: io_capability_request_negative_reply_view.IsValid()"); address = io_capability_request_negative_reply_view.GetBdAddr(); reason = io_capability_request_negative_reply_view.GetReason(); break; @@ -1028,22 +969,17 @@ void log_classic_pairing_command_status(std::unique_ptr& command_vi default: return; } - os::LogMetricClassicPairingEvent( - address, - connection_handle, - static_cast(op_code), - static_cast(event_code), - static_cast(status), - static_cast(reason), - value); + os::LogMetricClassicPairingEvent(address, connection_handle, static_cast(op_code), + static_cast(event_code), static_cast(status), + static_cast(reason), value); } -void log_classic_pairing_command_complete(EventView event_view, std::unique_ptr& command_view) { - +void log_classic_pairing_command_complete(EventView event_view, + std::unique_ptr& command_view) { // get op_code CommandCompleteView command_complete_view = CommandCompleteView::Create(std::move(event_view)); - log::assert_that( - command_complete_view.IsValid(), "assert failed: command_complete_view.IsValid()"); + log::assert_that(command_complete_view.IsValid(), + "assert failed: command_complete_view.IsValid()"); OpCode op_code = command_complete_view.GetCommandOpCode(); // init parameters @@ -1056,19 +992,19 @@ void log_classic_pairing_command_complete(EventView event_view, std::unique_ptr< // get ConnectionManagementCommandView ConnectionManagementCommandView connection_management_command_view = - ConnectionManagementCommandView::Create(AclCommandView::Create(*command_view)); - log::assert_that( - connection_management_command_view.IsValid(), - "assert failed: connection_management_command_view.IsValid()"); + ConnectionManagementCommandView::Create(AclCommandView::Create(*command_view)); + log::assert_that(connection_management_command_view.IsValid(), + "assert failed: connection_management_command_view.IsValid()"); // create SecurityCommandView SecurityCommandView security_command_view = SecurityCommandView::Create(*command_view); - log::assert_that( - security_command_view.IsValid(), "assert failed: security_command_view.IsValid()"); + log::assert_that(security_command_view.IsValid(), + "assert failed: security_command_view.IsValid()"); switch (op_code) { case OpCode::READ_LOCAL_OOB_DATA: { - auto read_local_oob_data_complete_view = ReadLocalOobDataCompleteView::Create(std::move(command_complete_view)); + auto read_local_oob_data_complete_view = + ReadLocalOobDataCompleteView::Create(std::move(command_complete_view)); if (!read_local_oob_data_complete_view.IsValid()) { log::warn("read_local_oob_data_complete_view is not valid."); return; @@ -1077,7 +1013,8 @@ void log_classic_pairing_command_complete(EventView event_view, std::unique_ptr< break; } case OpCode::WRITE_SIMPLE_PAIRING_MODE: { - auto write_simple_pairing_mode_complete_view = WriteSimplePairingModeCompleteView::Create(std::move(command_complete_view)); + auto write_simple_pairing_mode_complete_view = + WriteSimplePairingModeCompleteView::Create(std::move(command_complete_view)); if (!write_simple_pairing_mode_complete_view.IsValid()) { log::warn("write_simple_pairing_mode_complete_view is not valid."); return; @@ -1086,7 +1023,9 @@ void log_classic_pairing_command_complete(EventView event_view, std::unique_ptr< break; } case OpCode::WRITE_SECURE_CONNECTIONS_HOST_SUPPORT: { - auto write_secure_connections_host_support_complete_view = WriteSecureConnectionsHostSupportCompleteView::Create(std::move(command_complete_view)); + auto write_secure_connections_host_support_complete_view = + WriteSecureConnectionsHostSupportCompleteView::Create( + std::move(command_complete_view)); if (!write_secure_connections_host_support_complete_view.IsValid()) { log::warn("write_secure_connections_host_support_complete_view is not valid."); return; @@ -1095,7 +1034,8 @@ void log_classic_pairing_command_complete(EventView event_view, std::unique_ptr< break; } case OpCode::READ_ENCRYPTION_KEY_SIZE: { - auto read_encryption_key_size_complete_view = ReadEncryptionKeySizeCompleteView::Create(std::move(command_complete_view)); + auto read_encryption_key_size_complete_view = + ReadEncryptionKeySizeCompleteView::Create(std::move(command_complete_view)); if (!read_encryption_key_size_complete_view.IsValid()) { log::warn("read_encryption_key_size_complete_view is not valid."); return; @@ -1106,13 +1046,15 @@ void log_classic_pairing_command_complete(EventView event_view, std::unique_ptr< break; } case OpCode::LINK_KEY_REQUEST_REPLY: { - auto link_key_request_reply_complete_view = LinkKeyRequestReplyCompleteView::Create(std::move(command_complete_view)); + auto link_key_request_reply_complete_view = + LinkKeyRequestReplyCompleteView::Create(std::move(command_complete_view)); if (!link_key_request_reply_complete_view.IsValid()) { log::warn("link_key_request_reply_complete_view is not valid."); return; } status = link_key_request_reply_complete_view.GetStatus(); - auto link_key_request_reply_view = LinkKeyRequestReplyView::Create(std::move(security_command_view)); + auto link_key_request_reply_view = + LinkKeyRequestReplyView::Create(std::move(security_command_view)); if (!link_key_request_reply_view.IsValid()) { log::warn("link_key_request_reply_view is not valid."); return; @@ -1121,13 +1063,15 @@ void log_classic_pairing_command_complete(EventView event_view, std::unique_ptr< break; } case OpCode::LINK_KEY_REQUEST_NEGATIVE_REPLY: { - auto link_key_request_negative_reply_complete_view = LinkKeyRequestNegativeReplyCompleteView::Create(std::move(command_complete_view)); + auto link_key_request_negative_reply_complete_view = + LinkKeyRequestNegativeReplyCompleteView::Create(std::move(command_complete_view)); if (!link_key_request_negative_reply_complete_view.IsValid()) { log::warn("link_key_request_negative_reply_complete_view is not valid."); return; } status = link_key_request_negative_reply_complete_view.GetStatus(); - auto link_key_request_negative_reply_view = LinkKeyRequestNegativeReplyView::Create(std::move(security_command_view)); + auto link_key_request_negative_reply_view = + LinkKeyRequestNegativeReplyView::Create(std::move(security_command_view)); if (!link_key_request_negative_reply_view.IsValid()) { log::warn("link_key_request_negative_reply_view is not valid."); return; @@ -1136,13 +1080,15 @@ void log_classic_pairing_command_complete(EventView event_view, std::unique_ptr< break; } case OpCode::IO_CAPABILITY_REQUEST_REPLY: { - auto io_capability_request_reply_complete_view = IoCapabilityRequestReplyCompleteView::Create(std::move(command_complete_view)); + auto io_capability_request_reply_complete_view = + IoCapabilityRequestReplyCompleteView::Create(std::move(command_complete_view)); if (!io_capability_request_reply_complete_view.IsValid()) { log::warn("io_capability_request_reply_complete_view is not valid."); return; } status = io_capability_request_reply_complete_view.GetStatus(); - auto io_capability_request_reply_view = IoCapabilityRequestReplyView::Create(std::move(security_command_view)); + auto io_capability_request_reply_view = + IoCapabilityRequestReplyView::Create(std::move(security_command_view)); if (!io_capability_request_reply_view.IsValid()) { log::warn("io_capability_request_reply_view is not valid."); return; @@ -1151,13 +1097,16 @@ void log_classic_pairing_command_complete(EventView event_view, std::unique_ptr< break; } case OpCode::IO_CAPABILITY_REQUEST_NEGATIVE_REPLY: { - auto io_capability_request_negative_reply_complete_view = IoCapabilityRequestNegativeReplyCompleteView::Create(std::move(command_complete_view)); + auto io_capability_request_negative_reply_complete_view = + IoCapabilityRequestNegativeReplyCompleteView::Create( + std::move(command_complete_view)); if (!io_capability_request_negative_reply_complete_view.IsValid()) { log::warn("io_capability_request_negative_reply_complete_view is not valid."); return; } status = io_capability_request_negative_reply_complete_view.GetStatus(); - auto io_capability_request_negative_reply_view = IoCapabilityRequestNegativeReplyView::Create(std::move(security_command_view)); + auto io_capability_request_negative_reply_view = + IoCapabilityRequestNegativeReplyView::Create(std::move(security_command_view)); if (!io_capability_request_negative_reply_view.IsValid()) { log::warn("io_capability_request_negative_reply_view is not valid."); return; @@ -1166,13 +1115,15 @@ void log_classic_pairing_command_complete(EventView event_view, std::unique_ptr< break; } case OpCode::USER_CONFIRMATION_REQUEST_REPLY: { - auto user_confirmation_request_reply_complete_view = UserConfirmationRequestReplyCompleteView::Create(std::move(command_complete_view)); + auto user_confirmation_request_reply_complete_view = + UserConfirmationRequestReplyCompleteView::Create(std::move(command_complete_view)); if (!user_confirmation_request_reply_complete_view.IsValid()) { log::warn("user_confirmation_request_reply_complete_view is not valid."); return; } status = user_confirmation_request_reply_complete_view.GetStatus(); - auto user_confirmation_request_reply_view = UserConfirmationRequestReplyView::Create(std::move(security_command_view)); + auto user_confirmation_request_reply_view = + UserConfirmationRequestReplyView::Create(std::move(security_command_view)); if (!user_confirmation_request_reply_view.IsValid()) { log::warn("user_confirmation_request_reply_view is not valid."); return; @@ -1181,13 +1132,16 @@ void log_classic_pairing_command_complete(EventView event_view, std::unique_ptr< break; } case OpCode::USER_CONFIRMATION_REQUEST_NEGATIVE_REPLY: { - auto user_confirmation_request_negative_reply_complete_view = UserConfirmationRequestNegativeReplyCompleteView::Create(std::move(command_complete_view)); + auto user_confirmation_request_negative_reply_complete_view = + UserConfirmationRequestNegativeReplyCompleteView::Create( + std::move(command_complete_view)); if (!user_confirmation_request_negative_reply_complete_view.IsValid()) { log::warn("user_confirmation_request_negative_reply_complete_view is not valid."); return; } status = user_confirmation_request_negative_reply_complete_view.GetStatus(); - auto user_confirmation_request_negative_reply_view = UserConfirmationRequestNegativeReplyView::Create(std::move(security_command_view)); + auto user_confirmation_request_negative_reply_view = + UserConfirmationRequestNegativeReplyView::Create(std::move(security_command_view)); if (!user_confirmation_request_negative_reply_view.IsValid()) { log::warn("user_confirmation_request_negative_reply_view is not valid."); return; @@ -1196,13 +1150,15 @@ void log_classic_pairing_command_complete(EventView event_view, std::unique_ptr< break; } case OpCode::USER_PASSKEY_REQUEST_REPLY: { - auto user_passkey_request_reply_complete_view = UserPasskeyRequestReplyCompleteView::Create(std::move(command_complete_view)); + auto user_passkey_request_reply_complete_view = + UserPasskeyRequestReplyCompleteView::Create(std::move(command_complete_view)); if (!user_passkey_request_reply_complete_view.IsValid()) { log::warn("user_passkey_request_reply_complete_view is not valid."); return; } status = user_passkey_request_reply_complete_view.GetStatus(); - auto user_passkey_request_reply_view = UserPasskeyRequestReplyView::Create(std::move(security_command_view)); + auto user_passkey_request_reply_view = + UserPasskeyRequestReplyView::Create(std::move(security_command_view)); if (!user_passkey_request_reply_view.IsValid()) { log::warn("user_passkey_request_reply_view is not valid."); return; @@ -1211,13 +1167,15 @@ void log_classic_pairing_command_complete(EventView event_view, std::unique_ptr< break; } case OpCode::USER_PASSKEY_REQUEST_NEGATIVE_REPLY: { - auto user_passkey_request_negative_reply_complete_view = UserPasskeyRequestNegativeReplyCompleteView::Create(std::move(command_complete_view)); + auto user_passkey_request_negative_reply_complete_view = + UserPasskeyRequestNegativeReplyCompleteView::Create(std::move(command_complete_view)); if (!user_passkey_request_negative_reply_complete_view.IsValid()) { log::warn("user_passkey_request_negative_reply_complete_view is not valid."); return; } status = user_passkey_request_negative_reply_complete_view.GetStatus(); - auto user_passkey_request_negative_reply_view = UserPasskeyRequestNegativeReplyView::Create(std::move(security_command_view)); + auto user_passkey_request_negative_reply_view = + UserPasskeyRequestNegativeReplyView::Create(std::move(security_command_view)); if (!user_passkey_request_negative_reply_view.IsValid()) { log::warn("user_passkey_request_negative_reply_view is not valid."); return; @@ -1226,13 +1184,15 @@ void log_classic_pairing_command_complete(EventView event_view, std::unique_ptr< break; } case OpCode::REMOTE_OOB_DATA_REQUEST_REPLY: { - auto remote_oob_data_request_reply_complete_view = RemoteOobDataRequestReplyCompleteView::Create(std::move(command_complete_view)); + auto remote_oob_data_request_reply_complete_view = + RemoteOobDataRequestReplyCompleteView::Create(std::move(command_complete_view)); if (!remote_oob_data_request_reply_complete_view.IsValid()) { log::warn("remote_oob_data_request_reply_complete_view is not valid."); return; } status = remote_oob_data_request_reply_complete_view.GetStatus(); - auto remote_oob_data_request_reply_view = RemoteOobDataRequestReplyView::Create(std::move(security_command_view)); + auto remote_oob_data_request_reply_view = + RemoteOobDataRequestReplyView::Create(std::move(security_command_view)); if (!remote_oob_data_request_reply_view.IsValid()) { log::warn("remote_oob_data_request_reply_view is not valid."); return; @@ -1241,13 +1201,16 @@ void log_classic_pairing_command_complete(EventView event_view, std::unique_ptr< break; } case OpCode::REMOTE_OOB_DATA_REQUEST_NEGATIVE_REPLY: { - auto remote_oob_data_request_negative_reply_complete_view = RemoteOobDataRequestNegativeReplyCompleteView::Create(std::move(command_complete_view)); + auto remote_oob_data_request_negative_reply_complete_view = + RemoteOobDataRequestNegativeReplyCompleteView::Create( + std::move(command_complete_view)); if (!remote_oob_data_request_negative_reply_complete_view.IsValid()) { log::warn("remote_oob_data_request_negative_reply_complete_view is not valid."); return; } status = remote_oob_data_request_negative_reply_complete_view.GetStatus(); - auto remote_oob_data_request_negative_reply_view = RemoteOobDataRequestNegativeReplyView::Create(std::move(security_command_view)); + auto remote_oob_data_request_negative_reply_view = + RemoteOobDataRequestNegativeReplyView::Create(std::move(security_command_view)); if (!remote_oob_data_request_negative_reply_view.IsValid()) { log::warn("remote_oob_data_request_negative_reply_view is not valid."); return; @@ -1258,22 +1221,15 @@ void log_classic_pairing_command_complete(EventView event_view, std::unique_ptr< default: return; } - os::LogMetricClassicPairingEvent( - address, - connection_handle, - static_cast(op_code), - static_cast(event_code), - static_cast(status), - static_cast(reason), - value); + os::LogMetricClassicPairingEvent(address, connection_handle, static_cast(op_code), + static_cast(event_code), static_cast(status), + static_cast(reason), value); } -void log_remote_device_information( - const Address& address, - android::bluetooth::AddressTypeEnum address_type, - uint32_t connection_handle, - ErrorCode status, - storage::StorageModule* storage_module) { +void log_remote_device_information(const Address& address, + android::bluetooth::AddressTypeEnum address_type, + uint32_t connection_handle, ErrorCode status, + storage::StorageModule* storage_module) { if (address.IsEmpty()) { return; } @@ -1281,24 +1237,20 @@ void log_remote_device_information( // log ManufacturerInfo std::stringstream sdp_di_vendor_id_source; // [N - native]::SDP::[DIP - Device ID Profile] - sdp_di_vendor_id_source << "N:SDP::DIP::" << common::ToHexString(device.GetSdpDiVendorIdSource().value_or(0)).c_str(); + sdp_di_vendor_id_source + << "N:SDP::DIP::" + << common::ToHexString(device.GetSdpDiVendorIdSource().value_or(0)).c_str(); os::LogMetricManufacturerInfo( - address, - address_type, - android::bluetooth::DeviceInfoSrcEnum::DEVICE_INFO_INTERNAL, - sdp_di_vendor_id_source.str(), - common::ToHexString(device.GetSdpDiManufacturer().value_or(0)).c_str(), - common::ToHexString(device.GetSdpDiModel().value_or(0)).c_str(), - common::ToHexString(device.GetSdpDiHardwareVersion().value_or(0)).c_str(), - ""); + address, address_type, android::bluetooth::DeviceInfoSrcEnum::DEVICE_INFO_INTERNAL, + sdp_di_vendor_id_source.str(), + common::ToHexString(device.GetSdpDiManufacturer().value_or(0)).c_str(), + common::ToHexString(device.GetSdpDiModel().value_or(0)).c_str(), + common::ToHexString(device.GetSdpDiHardwareVersion().value_or(0)).c_str(), ""); // log RemoteVersionInfo os::LogMetricRemoteVersionInfo( - connection_handle, - static_cast(status), - device.GetLmpVersion().value_or(-1), - device.GetManufacturerCode().value_or(-1), - device.GetLmpSubVersion().value_or(-1)); + connection_handle, static_cast(status), device.GetLmpVersion().value_or(-1), + device.GetManufacturerCode().value_or(-1), device.GetLmpSubVersion().value_or(-1)); } } // namespace hci diff --git a/system/gd/hci/hci_metrics_logging.h b/system/gd/hci/hci_metrics_logging.h index 37a230aa7eb..ffa07fda501 100644 --- a/system/gd/hci/hci_metrics_logging.h +++ b/system/gd/hci/hci_metrics_logging.h @@ -22,23 +22,26 @@ namespace bluetooth { namespace hci { -void log_hci_event( - std::unique_ptr& command_view, EventView packet, storage::StorageModule* storage_module); +void log_hci_event(std::unique_ptr& command_view, EventView packet, + storage::StorageModule* storage_module); void log_link_layer_connection_command(std::unique_ptr& command_view); -void log_link_layer_connection_command_status(std::unique_ptr& command_view, ErrorCode status); -void log_link_layer_connection_command_complete(EventView event, std::unique_ptr& command_view); +void log_link_layer_connection_command_status(std::unique_ptr& command_view, + ErrorCode status); +void log_link_layer_connection_command_complete(EventView event, + std::unique_ptr& command_view); void log_link_layer_connection_event_le_meta(LeMetaEventView le_meta_event_view); -void log_link_layer_connection_other_hci_event(EventView packet, storage::StorageModule* storage_module); +void log_link_layer_connection_other_hci_event(EventView packet, + storage::StorageModule* storage_module); -void log_classic_pairing_command_status(std::unique_ptr& command_view, ErrorCode status); -void log_classic_pairing_command_complete(EventView event, std::unique_ptr& command_view); +void log_classic_pairing_command_status(std::unique_ptr& command_view, + ErrorCode status); +void log_classic_pairing_command_complete(EventView event, + std::unique_ptr& command_view); void log_classic_pairing_other_hci_event(EventView packet); -void log_remote_device_information( - const Address& address, - android::bluetooth::AddressTypeEnum address_type, - uint32_t connection_handle, - ErrorCode status, - storage::StorageModule* storage_module); +void log_remote_device_information(const Address& address, + android::bluetooth::AddressTypeEnum address_type, + uint32_t connection_handle, ErrorCode status, + storage::StorageModule* storage_module); } // namespace hci } // namespace bluetooth \ No newline at end of file diff --git a/system/gd/hci/hci_packets_fuzz_test.cc b/system/gd/hci/hci_packets_fuzz_test.cc index 57aa25b93d6..1388f1bbd86 100644 --- a/system/gd/hci/hci_packets_fuzz_test.cc +++ b/system/gd/hci/hci_packets_fuzz_test.cc @@ -15,10 +15,9 @@ */ #define PACKET_FUZZ_TESTING -#include "hci/hci_packets.h" - #include +#include "hci/hci_packets.h" #include "os/log.h" #include "packet/bit_inserter.h" #include "packet/raw_builder.h" @@ -70,7 +69,8 @@ DEFINE_AND_REGISTER_ReadLocalExtendedFeaturesCompleteReflectionFuzzTest(hci_pack DEFINE_AND_REGISTER_WriteSecureConnectionsHostSupportReflectionFuzzTest(hci_packet_fuzz_tests); -DEFINE_AND_REGISTER_WriteSecureConnectionsHostSupportCompleteReflectionFuzzTest(hci_packet_fuzz_tests); +DEFINE_AND_REGISTER_WriteSecureConnectionsHostSupportCompleteReflectionFuzzTest( + hci_packet_fuzz_tests); DEFINE_AND_REGISTER_LeReadFilterAcceptListSizeReflectionFuzzTest(hci_packet_fuzz_tests); @@ -128,7 +128,9 @@ DEFINE_AND_REGISTER_ExitPeriodicInquiryModeCompleteReflectionFuzzTest(hci_packet } // namespace bluetooth void RunHciPacketFuzzTest(const uint8_t* data, size_t size) { - if (data == nullptr) return; + if (data == nullptr) { + return; + } for (auto test_function : bluetooth::hci::hci_packet_fuzz_tests) { test_function(data, size); } diff --git a/system/gd/hci/hci_packets_test.cc b/system/gd/hci/hci_packets_test.cc index a7ccb1ff559..9df54187bba 100644 --- a/system/gd/hci/hci_packets_test.cc +++ b/system/gd/hci/hci_packets_test.cc @@ -15,11 +15,11 @@ */ #include + #include #define PACKET_TESTING // Instantiate the tests in the packet files #include "hci/hci_packets.h" - #include "os/log.h" #include "packet/bit_inserter.h" #include "packet/raw_builder.h" @@ -31,42 +31,51 @@ namespace bluetooth { namespace hci { std::vector pixel_3_xl_write_extended_inquiry_response{ - 0x52, 0x0c, 0xf1, 0x01, 0x0b, 0x09, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x20, 0x33, 0x20, 0x58, 0x4c, 0x19, 0x03, 0x05, - 0x11, 0x0a, 0x11, 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, - 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + 0x52, 0x0c, 0xf1, 0x01, 0x0b, 0x09, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x20, 0x33, 0x20, 0x58, + 0x4c, 0x19, 0x03, 0x05, 0x11, 0x0a, 0x11, 0x0c, 0x11, 0x0e, 0x11, 0x12, 0x11, 0x15, 0x11, + 0x16, 0x11, 0x1f, 0x11, 0x2d, 0x11, 0x2f, 0x11, 0x00, 0x12, 0x32, 0x11, 0x01, 0x05, 0x81, + 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00}; std::vector pixel_3_xl_write_extended_inquiry_response_no_uuids{ - 0x52, 0x0c, 0xf1, 0x01, 0x0b, 0x09, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x20, 0x33, 0x20, 0x58, 0x4c, 0x01, 0x03, 0x01, - 0x05, 0x81, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + 0x52, 0x0c, 0xf1, 0x01, 0x0b, 0x09, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x20, 0x33, 0x20, 0x58, + 0x4c, 0x01, 0x03, 0x01, 0x05, 0x81, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00}; std::vector pixel_3_xl_write_extended_inquiry_response_no_uuids_just_eir{ - pixel_3_xl_write_extended_inquiry_response_no_uuids.begin() + 4, // skip command, size, and fec_required - pixel_3_xl_write_extended_inquiry_response_no_uuids.end()}; + pixel_3_xl_write_extended_inquiry_response_no_uuids.begin() + + 4, // skip command, size, and fec_required + pixel_3_xl_write_extended_inquiry_response_no_uuids.end()}; TEST(HciPacketsTest, testWriteExtendedInquiryResponse) { std::shared_ptr> view_bytes = - std::make_shared>(pixel_3_xl_write_extended_inquiry_response); + std::make_shared>(pixel_3_xl_write_extended_inquiry_response); PacketView packet_bytes_view(view_bytes); auto view = WriteExtendedInquiryResponseView::Create(CommandView::Create(packet_bytes_view)); @@ -100,11 +109,13 @@ TEST(HciPacketsTest, testWriteExtendedInquiryResponse) { // pixel_3_xl_write_extended_inquiry_response_no_uuids); std::vector le_set_scan_parameters{ - 0x0b, 0x20, 0x07, 0x01, 0x12, 0x00, 0x12, 0x00, 0x01, 0x00, + 0x0b, 0x20, 0x07, 0x01, 0x12, 0x00, 0x12, 0x00, 0x01, 0x00, }; TEST(HciPacketsTest, testLeSetScanParameters) { - PacketView packet_bytes_view(std::make_shared>(le_set_scan_parameters)); - auto view = LeSetScanParametersView::Create(LeScanningCommandView::Create(CommandView::Create(packet_bytes_view))); + PacketView packet_bytes_view( + std::make_shared>(le_set_scan_parameters)); + auto view = LeSetScanParametersView::Create( + LeScanningCommandView::Create(CommandView::Create(packet_bytes_view))); ASSERT_TRUE(view.IsValid()); ASSERT_EQ(LeScanType::ACTIVE, view.GetLeScanType()); @@ -115,11 +126,13 @@ TEST(HciPacketsTest, testLeSetScanParameters) { } std::vector le_set_scan_enable{ - 0x0c, 0x20, 0x02, 0x01, 0x00, + 0x0c, 0x20, 0x02, 0x01, 0x00, }; TEST(HciPacketsTest, testLeSetScanEnable) { - PacketView packet_bytes_view(std::make_shared>(le_set_scan_enable)); - auto view = LeSetScanEnableView::Create(LeScanningCommandView::Create(CommandView::Create(packet_bytes_view))); + PacketView packet_bytes_view( + std::make_shared>(le_set_scan_enable)); + auto view = LeSetScanEnableView::Create( + LeScanningCommandView::Create(CommandView::Create(packet_bytes_view))); ASSERT_TRUE(view.IsValid()); ASSERT_EQ(Enable::ENABLED, view.GetLeScanEnable()); @@ -127,25 +140,27 @@ TEST(HciPacketsTest, testLeSetScanEnable) { } std::vector le_get_vendor_capabilities{ - 0x53, - 0xfd, - 0x00, + 0x53, + 0xfd, + 0x00, }; TEST(HciPacketsTest, testLeGetVendorCapabilities) { - PacketView packet_bytes_view(std::make_shared>(le_get_vendor_capabilities)); - auto view = LeGetVendorCapabilitiesView::Create(VendorCommandView::Create(CommandView::Create(packet_bytes_view))); + PacketView packet_bytes_view( + std::make_shared>(le_get_vendor_capabilities)); + auto view = LeGetVendorCapabilitiesView::Create( + VendorCommandView::Create(CommandView::Create(packet_bytes_view))); ASSERT_TRUE(view.IsValid()); } std::vector le_get_vendor_capabilities_complete{ - 0x0e, 0x0c, 0x01, 0x53, 0xfd, 0x00, 0x05, 0x01, 0x00, 0x04, 0x80, 0x01, 0x10, 0x01, + 0x0e, 0x0c, 0x01, 0x53, 0xfd, 0x00, 0x05, 0x01, 0x00, 0x04, 0x80, 0x01, 0x10, 0x01, }; TEST(HciPacketsTest, testLeGetVendorCapabilitiesComplete) { PacketView packet_bytes_view( - std::make_shared>(le_get_vendor_capabilities_complete)); - auto view = - LeGetVendorCapabilitiesCompleteView::Create(CommandCompleteView::Create(EventView::Create(packet_bytes_view))); + std::make_shared>(le_get_vendor_capabilities_complete)); + auto view = LeGetVendorCapabilitiesCompleteView::Create( + CommandCompleteView::Create(EventView::Create(packet_bytes_view))); ASSERT_TRUE(view.IsValid()); auto base_capabilities = view.GetBaseVendorCapabilities(); @@ -159,13 +174,14 @@ TEST(HciPacketsTest, testLeGetVendorCapabilitiesComplete) { } std::vector le_set_extended_scan_parameters{ - 0x41, 0x20, 0x08, 0x01, 0x00, 0x01, 0x01, 0x12, 0x00, 0x12, 0x00, + 0x41, 0x20, 0x08, 0x01, 0x00, 0x01, 0x01, 0x12, 0x00, 0x12, 0x00, }; TEST(HciPacketsTest, testLeSetExtendedScanParameters) { - PacketView packet_bytes_view(std::make_shared>(le_set_extended_scan_parameters)); - auto view = - LeSetExtendedScanParametersView::Create(LeScanningCommandView::Create(CommandView::Create(packet_bytes_view))); + PacketView packet_bytes_view( + std::make_shared>(le_set_extended_scan_parameters)); + auto view = LeSetExtendedScanParametersView::Create( + LeScanningCommandView::Create(CommandView::Create(packet_bytes_view))); ASSERT_TRUE(view.IsValid()); ASSERT_EQ(1, view.GetScanningPhys()); @@ -177,14 +193,14 @@ TEST(HciPacketsTest, testLeSetExtendedScanParameters) { } std::vector le_set_extended_scan_parameters_6553{ - 0x41, 0x20, 0x08, 0x01, 0x00, 0x01, 0x01, 0x99, 0x19, 0x99, 0x19, + 0x41, 0x20, 0x08, 0x01, 0x00, 0x01, 0x01, 0x99, 0x19, 0x99, 0x19, }; TEST(HciPacketsTest, testLeSetExtendedScanParameters_6553) { PacketView packet_bytes_view( - std::make_shared>(le_set_extended_scan_parameters_6553)); - auto view = - LeSetExtendedScanParametersView::Create(LeScanningCommandView::Create(CommandView::Create(packet_bytes_view))); + std::make_shared>(le_set_extended_scan_parameters_6553)); + auto view = LeSetExtendedScanParametersView::Create( + LeScanningCommandView::Create(CommandView::Create(packet_bytes_view))); ASSERT_TRUE(view.IsValid()); ASSERT_EQ(1, view.GetScanningPhys()); @@ -196,13 +212,14 @@ TEST(HciPacketsTest, testLeSetExtendedScanParameters_6553) { } std::vector le_set_extended_scan_enable{ - 0x42, 0x20, 0x06, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x42, 0x20, 0x06, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, }; TEST(HciPacketsTest, testLeSetExtendedScanEnable) { - PacketView packet_bytes_view(std::make_shared>(le_set_extended_scan_enable)); - auto view = - LeSetExtendedScanEnableView::Create(LeScanningCommandView::Create(CommandView::Create(packet_bytes_view))); + PacketView packet_bytes_view( + std::make_shared>(le_set_extended_scan_enable)); + auto view = LeSetExtendedScanEnableView::Create( + LeScanningCommandView::Create(CommandView::Create(packet_bytes_view))); ASSERT_TRUE(view.IsValid()); ASSERT_EQ(FilterDuplicates::DISABLED, view.GetFilterDuplicates()); @@ -212,14 +229,14 @@ TEST(HciPacketsTest, testLeSetExtendedScanEnable) { } std::vector le_set_extended_scan_enable_disable{ - 0x42, 0x20, 0x06, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, + 0x42, 0x20, 0x06, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, }; TEST(HciPacketsTest, testLeSetExtendedScanEnableDisable) { PacketView packet_bytes_view( - std::make_shared>(le_set_extended_scan_enable_disable)); - auto view = - LeSetExtendedScanEnableView::Create(LeScanningCommandView::Create(CommandView::Create(packet_bytes_view))); + std::make_shared>(le_set_extended_scan_enable_disable)); + auto view = LeSetExtendedScanEnableView::Create( + LeScanningCommandView::Create(CommandView::Create(packet_bytes_view))); ASSERT_TRUE(view.IsValid()); ASSERT_EQ(FilterDuplicates::ENABLED, view.GetFilterDuplicates()); @@ -229,29 +246,29 @@ TEST(HciPacketsTest, testLeSetExtendedScanEnableDisable) { } std::vector le_extended_create_connection = { - 0x43, 0x20, 0x2a, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x08, - 0x30, 0x00, 0x18, 0x00, 0x28, 0x00, 0x00, 0x00, 0xf4, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x08, 0x30, 0x00, 0x18, 0x00, 0x28, 0x00, 0x00, 0x00, 0xf4, 0x01, 0x00, 0x00, 0x00, 0x00}; + 0x43, 0x20, 0x2a, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x08, + 0x30, 0x00, 0x18, 0x00, 0x28, 0x00, 0x00, 0x00, 0xf4, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x08, 0x30, 0x00, 0x18, 0x00, 0x28, 0x00, 0x00, 0x00, 0xf4, 0x01, 0x00, 0x00, 0x00, 0x00}; TEST(HciPacketsTest, testLeExtendedCreateConnection) { std::shared_ptr> packet_bytes = - std::make_shared>(le_extended_create_connection); + std::make_shared>(le_extended_create_connection); PacketView packet_bytes_view(packet_bytes); - auto view = LeExtendedCreateConnectionView::Create( - LeConnectionManagementCommandView::Create(AclCommandView::Create(CommandView::Create(packet_bytes_view)))); + auto view = LeExtendedCreateConnectionView::Create(LeConnectionManagementCommandView::Create( + AclCommandView::Create(CommandView::Create(packet_bytes_view)))); ASSERT_TRUE(view.IsValid()); } std::vector le_set_extended_advertising_random_address = { - 0x35, 0x20, 0x07, 0x00, 0x77, 0x58, 0xeb, 0xd3, 0x1c, 0x6e, + 0x35, 0x20, 0x07, 0x00, 0x77, 0x58, 0xeb, 0xd3, 0x1c, 0x6e, }; TEST(HciPacketsTest, testLeSetAdvertisingSetRandomAddress) { std::shared_ptr> packet_bytes = - std::make_shared>(le_set_extended_advertising_random_address); + std::make_shared>(le_set_extended_advertising_random_address); PacketView packet_bytes_view(packet_bytes); auto view = LeSetAdvertisingSetRandomAddressView::Create( - LeAdvertisingCommandView::Create(CommandView::Create(packet_bytes_view))); + LeAdvertisingCommandView::Create(CommandView::Create(packet_bytes_view))); ASSERT_TRUE(view.IsValid()); uint8_t random_address_bytes[] = {0x77, 0x58, 0xeb, 0xd3, 0x1c, 0x6e}; ASSERT_EQ(0, view.GetAdvertisingHandle()); @@ -259,21 +276,21 @@ TEST(HciPacketsTest, testLeSetAdvertisingSetRandomAddress) { } std::vector le_set_extended_advertising_data{ - 0x37, 0x20, 0x12, 0x00, 0x03, 0x01, 0x0e, 0x02, 0x01, 0x02, 0x0a, - 0x09, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x20, 0x33, 0x20, 0x58, + 0x37, 0x20, 0x12, 0x00, 0x03, 0x01, 0x0e, 0x02, 0x01, 0x02, 0x0a, + 0x09, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x20, 0x33, 0x20, 0x58, }; TEST(HciPacketsTest, testLeSetExtendedAdvertisingData) { std::shared_ptr> packet_bytes = - std::make_shared>(le_set_extended_advertising_data); + std::make_shared>(le_set_extended_advertising_data); PacketView packet_bytes_view(packet_bytes); auto view = LeSetExtendedAdvertisingDataRawView::Create( - LeAdvertisingCommandView::Create(CommandView::Create(packet_bytes_view))); + LeAdvertisingCommandView::Create(CommandView::Create(packet_bytes_view))); ASSERT_TRUE(view.IsValid()); ASSERT_EQ(0, view.GetAdvertisingHandle()); ASSERT_EQ(Operation::COMPLETE_ADVERTISEMENT, view.GetOperation()); ASSERT_EQ(FragmentPreference::CONTROLLER_SHOULD_NOT, view.GetFragmentPreference()); std::vector advertising_data{ - 0x02, 0x01, 0x02, 0x0a, 0x09, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x20, 0x33, 0x20, 0x58, + 0x02, 0x01, 0x02, 0x0a, 0x09, 0x50, 0x69, 0x78, 0x65, 0x6c, 0x20, 0x33, 0x20, 0x58, }; auto payload = view.GetPayload(); std::vector payload_data(payload.begin(), payload.end()); @@ -281,15 +298,15 @@ TEST(HciPacketsTest, testLeSetExtendedAdvertisingData) { } std::vector le_set_extended_advertising_parameters_set_0{ - 0x36, 0x20, 0x19, 0x00, 0x13, 0x00, 0x90, 0x01, 0x00, 0xc2, 0x01, 0x00, 0x07, 0x01, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf9, 0x01, 0x00, 0x01, 0x01, 0x00, + 0x36, 0x20, 0x19, 0x00, 0x13, 0x00, 0x90, 0x01, 0x00, 0xc2, 0x01, 0x00, 0x07, 0x01, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf9, 0x01, 0x00, 0x01, 0x01, 0x00, }; TEST(HciPacketsTest, testLeSetExtendedAdvertisingParametersLegacySet0) { std::shared_ptr> packet_bytes = - std::make_shared>(le_set_extended_advertising_parameters_set_0); + std::make_shared>(le_set_extended_advertising_parameters_set_0); PacketView packet_bytes_view(packet_bytes); auto view = LeSetExtendedAdvertisingParametersLegacyView::Create( - LeAdvertisingCommandView::Create(CommandView::Create(packet_bytes_view))); + LeAdvertisingCommandView::Create(CommandView::Create(packet_bytes_view))); ASSERT_TRUE(view.IsValid()); ASSERT_EQ(0, view.GetAdvertisingHandle()); ASSERT_EQ(400ul, view.GetPrimaryAdvertisingIntervalMin()); @@ -304,15 +321,15 @@ TEST(HciPacketsTest, testLeSetExtendedAdvertisingParametersLegacySet0) { } std::vector le_set_extended_advertising_parameters_set_1{ - 0x36, 0x20, 0x19, 0x01, 0x13, 0x00, 0x90, 0x01, 0x00, 0xc2, 0x01, 0x00, 0x07, 0x01, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf9, 0x01, 0x00, 0x01, 0x01, 0x00, + 0x36, 0x20, 0x19, 0x01, 0x13, 0x00, 0x90, 0x01, 0x00, 0xc2, 0x01, 0x00, 0x07, 0x01, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf9, 0x01, 0x00, 0x01, 0x01, 0x00, }; TEST(HciPacketsTest, testLeSetExtendedAdvertisingParametersSet1) { std::shared_ptr> packet_bytes = - std::make_shared>(le_set_extended_advertising_parameters_set_1); + std::make_shared>(le_set_extended_advertising_parameters_set_1); PacketView packet_bytes_view(packet_bytes); auto view = LeSetExtendedAdvertisingParametersLegacyView::Create( - LeAdvertisingCommandView::Create(CommandView::Create(packet_bytes_view))); + LeAdvertisingCommandView::Create(CommandView::Create(packet_bytes_view))); ASSERT_TRUE(view.IsValid()); ASSERT_EQ(1, view.GetAdvertisingHandle()); ASSERT_EQ(400ul, view.GetPrimaryAdvertisingIntervalMin()); @@ -326,42 +343,43 @@ TEST(HciPacketsTest, testLeSetExtendedAdvertisingParametersSet1) { ASSERT_EQ(Enable::DISABLED, view.GetScanRequestNotificationEnable()); } -std::vector le_set_extended_advertising_parameters_complete{0x0e, 0x05, 0x01, 0x36, 0x20, 0x00, 0xf5}; +std::vector le_set_extended_advertising_parameters_complete{0x0e, 0x05, 0x01, 0x36, + 0x20, 0x00, 0xf5}; TEST(HciPacketsTest, testLeSetExtendedAdvertisingParametersComplete) { std::shared_ptr> packet_bytes = - std::make_shared>(le_set_extended_advertising_parameters_complete); + std::make_shared>(le_set_extended_advertising_parameters_complete); PacketView packet_bytes_view(packet_bytes); auto view = LeSetExtendedAdvertisingParametersCompleteView::Create( - CommandCompleteView::Create(EventView::Create(packet_bytes_view))); + CommandCompleteView::Create(EventView::Create(packet_bytes_view))); ASSERT_TRUE(view.IsValid()); ASSERT_EQ(static_cast(-11), view.GetSelectedTxPower()); } std::vector le_remove_advertising_set_1{ - 0x3c, - 0x20, - 0x01, - 0x01, + 0x3c, + 0x20, + 0x01, + 0x01, }; TEST(HciPacketsTest, testLeRemoveAdvertisingSet1) { std::shared_ptr> packet_bytes = - std::make_shared>(le_remove_advertising_set_1); + std::make_shared>(le_remove_advertising_set_1); PacketView packet_bytes_view(packet_bytes); - auto view = - LeRemoveAdvertisingSetView::Create(LeAdvertisingCommandView::Create(CommandView::Create(packet_bytes_view))); + auto view = LeRemoveAdvertisingSetView::Create( + LeAdvertisingCommandView::Create(CommandView::Create(packet_bytes_view))); ASSERT_TRUE(view.IsValid()); ASSERT_EQ(1, view.GetAdvertisingHandle()); } std::vector le_set_extended_advertising_disable_1{ - 0x39, 0x20, 0x06, 0x00, 0x01, 0x01, 0x00, 0x00, 0x00, + 0x39, 0x20, 0x06, 0x00, 0x01, 0x01, 0x00, 0x00, 0x00, }; TEST(HciPacketsTest, testLeSetExtendedAdvertisingDisable1) { std::shared_ptr> packet_bytes = - std::make_shared>(le_set_extended_advertising_disable_1); + std::make_shared>(le_set_extended_advertising_disable_1); PacketView packet_bytes_view(packet_bytes); auto view = LeSetExtendedAdvertisingDisableView::Create( - LeAdvertisingCommandView::Create(CommandView::Create(packet_bytes_view))); + LeAdvertisingCommandView::Create(CommandView::Create(packet_bytes_view))); ASSERT_TRUE(view.IsValid()); auto disabled_set = view.GetDisabledSets(); ASSERT_EQ(1ul, disabled_set.size()); @@ -373,13 +391,15 @@ TEST(HciPacketsTest, testLeSetAdvertisingDataBuilderLength) { gap_data.data_type_ = GapDataType::COMPLETE_LOCAL_NAME; gap_data.data_ = std::vector({'A', ' ', 'g', 'o', 'o', 'd', ' ', 'n', 'a', 'm', 'e'}); auto builder = LeSetAdvertisingDataBuilder::Create({gap_data}); - ASSERT_EQ(2ul /*opcode*/ + 1ul /* parameter size */ + 1ul /* data_length */ + 31ul /* data */, builder->size()); + ASSERT_EQ(2ul /*opcode*/ + 1ul /* parameter size */ + 1ul /* data_length */ + 31ul /* data */, + builder->size()); auto packet_bytes = std::make_shared>(); packet_bytes->reserve(builder->size()); BitInserter bit_inserter(*packet_bytes); builder->Serialize(bit_inserter); - auto command_view = LeAdvertisingCommandView::Create(CommandView::Create(PacketView(packet_bytes))); + auto command_view = LeAdvertisingCommandView::Create( + CommandView::Create(PacketView(packet_bytes))); ASSERT_TRUE(command_view.IsValid()); ASSERT_EQ(1ul /* data_length */ + 31ul /* data */, command_view.GetPayload().size()); auto view = LeSetAdvertisingDataView::Create(command_view); @@ -391,13 +411,15 @@ TEST(HciPacketsTest, testLeSetScanResponseDataBuilderLength) { gap_data.data_type_ = GapDataType::COMPLETE_LOCAL_NAME; gap_data.data_ = std::vector({'A', ' ', 'g', 'o', 'o', 'd', ' ', 'n', 'a', 'm', 'e'}); auto builder = LeSetScanResponseDataBuilder::Create({gap_data}); - ASSERT_EQ(2ul /*opcode*/ + 1ul /* parameter size */ + 1ul /*data_length */ + 31ul /* data */, builder->size()); + ASSERT_EQ(2ul /*opcode*/ + 1ul /* parameter size */ + 1ul /*data_length */ + 31ul /* data */, + builder->size()); auto packet_bytes = std::make_shared>(); packet_bytes->reserve(builder->size()); BitInserter bit_inserter(*packet_bytes); builder->Serialize(bit_inserter); - auto command_view = LeAdvertisingCommandView::Create(CommandView::Create(PacketView(packet_bytes))); + auto command_view = LeAdvertisingCommandView::Create( + CommandView::Create(PacketView(packet_bytes))); ASSERT_TRUE(command_view.IsValid()); ASSERT_EQ(1ul /* data_length */ + 31ul /* data */, command_view.GetPayload().size()); auto view = LeSetScanResponseDataView::Create(command_view); @@ -415,8 +437,9 @@ TEST(HciPacketsTest, testLeMultiAdvSetAdvertisingDataBuilderLength) { packet_bytes->reserve(builder->size()); BitInserter bit_inserter(*packet_bytes); builder->Serialize(bit_inserter); - auto command_view = LeMultiAdvtSetDataView::Create(LeMultiAdvtView::Create( - LeAdvertisingCommandView::Create(CommandView::Create(PacketView(packet_bytes))))); + auto command_view = + LeMultiAdvtSetDataView::Create(LeMultiAdvtView::Create(LeAdvertisingCommandView::Create( + CommandView::Create(PacketView(packet_bytes))))); ASSERT_TRUE(command_view.IsValid()); auto view = LeMultiAdvtSetDataView::Create(command_view); ASSERT_TRUE(view.IsValid()); @@ -436,8 +459,9 @@ TEST(HciPacketsTest, testLeMultiAdvSetScanResponseDataBuilderLength) { packet_bytes->reserve(builder->size()); BitInserter bit_inserter(*packet_bytes); builder->Serialize(bit_inserter); - auto command_view = LeMultiAdvtSetScanRespView::Create(LeMultiAdvtView::Create( - LeAdvertisingCommandView::Create(CommandView::Create(PacketView(packet_bytes))))); + auto command_view = LeMultiAdvtSetScanRespView::Create( + LeMultiAdvtView::Create(LeAdvertisingCommandView::Create( + CommandView::Create(PacketView(packet_bytes))))); ASSERT_TRUE(command_view.IsValid()); auto view = LeMultiAdvtSetScanRespView::Create(command_view); ASSERT_TRUE(view.IsValid()); @@ -457,10 +481,10 @@ TEST(HciPacketsTest, testMsftReadSupportedFeatures) { builder->Serialize(bit_inserter); std::vector expected_bytes{ - 0x01, // Vendor command opcode and MSFT base code. - 0xfc, - 0x01, // Packet length - 0x00, // Subcommand Opcode for Read Supported Features + 0x01, // Vendor command opcode and MSFT base code. + 0xfc, + 0x01, // Packet length + 0x00, // Subcommand Opcode for Read Supported Features }; ASSERT_EQ(expected_bytes, *packet_bytes); } @@ -470,12 +494,9 @@ TEST(HciPacketsTest, testMsftLeMonitorAdvUuid) { auto msft_opcode = static_cast(0xfc01); auto builder = MsftLeMonitorAdvConditionUuid2Builder::Create( - msft_opcode, - 0x10 /* RSSI threshold high */, - 0x11 /* RSSI threshold low */, - 0x12 /* RSSI threshold low timeout */, - 0x13 /* RSSI sampling period */, - std::array{0x71, 0x72} /* 16-bit UUID */); + msft_opcode, 0x10 /* RSSI threshold high */, 0x11 /* RSSI threshold low */, + 0x12 /* RSSI threshold low timeout */, 0x13 /* RSSI sampling period */, + std::array{0x71, 0x72} /* 16-bit UUID */); auto packet_bytes = std::make_shared>(); packet_bytes->reserve(builder->size()); @@ -483,18 +504,18 @@ TEST(HciPacketsTest, testMsftLeMonitorAdvUuid) { builder->Serialize(bit_inserter); std::vector expected_bytes{ - 0x01, // Vendor command opcode and MSFT base code. - 0xfc, - 0x09, // Packet length - 0x03, // Subcommand Opcode for LE Monitor Adv - 0x10, // RSSI threshold high - 0x11, // RSSI threshold low - 0x12, // RSSI threshold low timeout - 0x13, // RSSI sampling period - 0x02, // Condition type = UUID - 0x01, // UUID type = 16-bit UUID - 0x71, // UUID content - 0x72, + 0x01, // Vendor command opcode and MSFT base code. + 0xfc, + 0x09, // Packet length + 0x03, // Subcommand Opcode for LE Monitor Adv + 0x10, // RSSI threshold high + 0x11, // RSSI threshold low + 0x12, // RSSI threshold low timeout + 0x13, // RSSI sampling period + 0x02, // Condition type = UUID + 0x01, // UUID type = 16-bit UUID + 0x71, // UUID content + 0x72, }; ASSERT_EQ(expected_bytes, *packet_bytes); } @@ -506,12 +527,8 @@ TEST(HciPacketsTest, testMsftLeMonitorAdvPatternsEmpty) { std::vector patterns; auto builder = MsftLeMonitorAdvConditionPatternsBuilder::Create( - msft_opcode, - 0x10 /* RSSI threshold high */, - 0x11 /* RSSI threshold low */, - 0x12 /* RSSI threshold low timeout */, - 0x13 /* RSSI sampling period */, - patterns); + msft_opcode, 0x10 /* RSSI threshold high */, 0x11 /* RSSI threshold low */, + 0x12 /* RSSI threshold low timeout */, 0x13 /* RSSI sampling period */, patterns); auto packet_bytes = std::make_shared>(); packet_bytes->reserve(builder->size()); @@ -519,16 +536,16 @@ TEST(HciPacketsTest, testMsftLeMonitorAdvPatternsEmpty) { builder->Serialize(bit_inserter); std::vector expected_bytes{ - 0x01, // Vendor command opcode and MSFT base code. - 0xfc, - 0x07, // Packet length - 0x03, // Subcommand Opcode for LE Monitor Adv - 0x10, // RSSI threshold high - 0x11, // RSSI threshold low - 0x12, // RSSI threshold low timeout - 0x13, // RSSI sampling period - 0x01, // Condition type = Patterns - 0x00, // Number of patterns + 0x01, // Vendor command opcode and MSFT base code. + 0xfc, + 0x07, // Packet length + 0x03, // Subcommand Opcode for LE Monitor Adv + 0x10, // RSSI threshold high + 0x11, // RSSI threshold low + 0x12, // RSSI threshold low timeout + 0x13, // RSSI sampling period + 0x01, // Condition type = Patterns + 0x00, // Number of patterns }; ASSERT_EQ(expected_bytes, *packet_bytes); } @@ -550,12 +567,8 @@ TEST(HciPacketsTest, testMsftLeMonitorAdvPatterns) { std::vector patterns{pattern1, pattern2}; auto builder = MsftLeMonitorAdvConditionPatternsBuilder::Create( - msft_opcode, - 0x10 /* RSSI threshold high */, - 0x11 /* RSSI threshold low */, - 0x12 /* RSSI threshold low timeout */, - 0x13 /* RSSI sampling period */, - patterns); + msft_opcode, 0x10 /* RSSI threshold high */, 0x11 /* RSSI threshold low */, + 0x12 /* RSSI threshold low timeout */, 0x13 /* RSSI sampling period */, patterns); auto packet_bytes = std::make_shared>(); packet_bytes->reserve(builder->size()); @@ -563,58 +576,52 @@ TEST(HciPacketsTest, testMsftLeMonitorAdvPatterns) { builder->Serialize(bit_inserter); std::vector expected_bytes{ - 0x01, // Vendor command opcode and MSFT base code. - 0xfc, - 0x12, // Packet length - 0x03, // Subcommand Opcode for LE Monitor Adv - 0x10, // RSSI threshold high - 0x11, // RSSI threshold low - 0x12, // RSSI threshold low timeout - 0x13, // RSSI sampling period - 0x01, // Condition type = Patterns - 0x02, // Number of patterns - // Pattern 1 - 0x05, // Length - 0x03, // AD Type - 0x00, // Start of pattern - 0x01, // Pattern - 0x02, - 0x03, - // Pattern 2 - 0x04, // Length - 0x0f, // AD Type - 0x10, // Start of pattern - 0xa1, // Pattern - 0xa2, + 0x01, // Vendor command opcode and MSFT base code. + 0xfc, + 0x12, // Packet length + 0x03, // Subcommand Opcode for LE Monitor Adv + 0x10, // RSSI threshold high + 0x11, // RSSI threshold low + 0x12, // RSSI threshold low timeout + 0x13, // RSSI sampling period + 0x01, // Condition type = Patterns + 0x02, // Number of patterns + // Pattern 1 + 0x05, // Length + 0x03, // AD Type + 0x00, // Start of pattern + 0x01, // Pattern + 0x02, + 0x03, + // Pattern 2 + 0x04, // Length + 0x0f, // AD Type + 0x10, // Start of pattern + 0xa1, // Pattern + 0xa2, }; ASSERT_EQ(expected_bytes, *packet_bytes); } std::vector msft_read_supported_features_complete{ - 0x0e, // command complete event code - 0x10, // event size - 0x01, // num_hci_command_packets - 0x1e, - 0xfc, // vendor specific MSFT opcode assigned by Intel - 0x00, // status - 0x00, // MSFT subcommand opcode - 0x7f, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, // supported features - 0x02, // MSFT event prefix length - 0x87, - 0x80, // prefix: MSFT event prefix provided by Intel + 0x0e, // command complete event code + 0x10, // event size + 0x01, // num_hci_command_packets + 0x1e, + 0xfc, // vendor specific MSFT opcode assigned by Intel + 0x00, // status + 0x00, // MSFT subcommand opcode + 0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, // supported features + 0x02, // MSFT event prefix length + 0x87, + 0x80, // prefix: MSFT event prefix provided by Intel }; TEST(HciPacketsTest, testMsftReadSupportedFeaturesComplete) { PacketView packet_bytes_view( - std::make_shared>(msft_read_supported_features_complete)); - auto view = MsftReadSupportedFeaturesCommandCompleteView::Create( - MsftCommandCompleteView::Create(CommandCompleteView::Create(EventView::Create(packet_bytes_view)))); + std::make_shared>(msft_read_supported_features_complete)); + auto view = MsftReadSupportedFeaturesCommandCompleteView::Create(MsftCommandCompleteView::Create( + CommandCompleteView::Create(EventView::Create(packet_bytes_view)))); ASSERT_TRUE(view.IsValid()); ASSERT_EQ(ErrorCode::SUCCESS, view.GetStatus()); @@ -623,7 +630,9 @@ TEST(HciPacketsTest, testMsftReadSupportedFeaturesComplete) { ASSERT_EQ(2ul, view.GetPrefix().size()); uint16_t prefix = 0; - for (auto p : view.GetPrefix()) prefix = (prefix << 8) + p; + for (auto p : view.GetPrefix()) { + prefix = (prefix << 8) + p; + } ASSERT_EQ((uint16_t)0x8780, prefix); } diff --git a/system/gd/hci/le_acl_connection_interface.h b/system/gd/hci/le_acl_connection_interface.h index 71219ea2d3d..b3081e30b6f 100644 --- a/system/gd/hci/le_acl_connection_interface.h +++ b/system/gd/hci/le_acl_connection_interface.h @@ -23,15 +23,12 @@ namespace bluetooth { namespace hci { constexpr SubeventCode LeConnectionManagementEvents[] = { - SubeventCode::CONNECTION_COMPLETE, - SubeventCode::ENHANCED_CONNECTION_COMPLETE, - SubeventCode::CONNECTION_UPDATE_COMPLETE, - SubeventCode::PHY_UPDATE_COMPLETE, - SubeventCode::DATA_LENGTH_CHANGE, - SubeventCode::REMOTE_CONNECTION_PARAMETER_REQUEST, - SubeventCode::LE_SUBRATE_CHANGE, - // TODO implement callback for READ_REMOTE_FEATURES_COMPLETE - // SubeventCode::READ_REMOTE_FEATURES_COMPLETE + SubeventCode::CONNECTION_COMPLETE, SubeventCode::ENHANCED_CONNECTION_COMPLETE, + SubeventCode::CONNECTION_UPDATE_COMPLETE, SubeventCode::PHY_UPDATE_COMPLETE, + SubeventCode::DATA_LENGTH_CHANGE, SubeventCode::REMOTE_CONNECTION_PARAMETER_REQUEST, + SubeventCode::LE_SUBRATE_CHANGE, + // TODO implement callback for READ_REMOTE_FEATURES_COMPLETE + // SubeventCode::READ_REMOTE_FEATURES_COMPLETE }; typedef CommandInterface LeAclConnectionInterface; diff --git a/system/gd/hci/le_address_manager.cc b/system/gd/hci/le_address_manager.cc index dae1c9d5a02..682d9529240 100644 --- a/system/gd/hci/le_address_manager.cc +++ b/system/gd/hci/le_address_manager.cc @@ -58,16 +58,14 @@ std::string AddressPolicyText(const LeAddressManager::AddressPolicy policy) { } LeAddressManager::LeAddressManager( - common::Callback)> enqueue_command, - os::Handler* handler, - Address public_address, - uint8_t accept_list_size, - uint8_t resolving_list_size) + common::Callback)> enqueue_command, + os::Handler* handler, Address public_address, uint8_t accept_list_size, + uint8_t resolving_list_size) : enqueue_command_(enqueue_command), handler_(handler), public_address_(public_address), accept_list_size_(accept_list_size), - resolving_list_size_(resolving_list_size){}; + resolving_list_size_(resolving_list_size) {} LeAddressManager::~LeAddressManager() { if (address_rotation_alarm_ != nullptr) { @@ -78,32 +76,26 @@ LeAddressManager::~LeAddressManager() { // Called on initialization, and on IRK rotation void LeAddressManager::SetPrivacyPolicyForInitiatorAddress( - AddressPolicy address_policy, - AddressWithType fixed_address, - Octet16 rotation_irk, - bool supports_ble_privacy, - std::chrono::milliseconds minimum_rotation_time, - std::chrono::milliseconds maximum_rotation_time) { + AddressPolicy address_policy, AddressWithType fixed_address, Octet16 rotation_irk, + bool supports_ble_privacy, std::chrono::milliseconds minimum_rotation_time, + std::chrono::milliseconds maximum_rotation_time) { // Handle repeated calls to the function for IRK rotation if (address_policy_ != AddressPolicy::POLICY_NOT_SET) { // Need to update some parameteres like IRK if privacy is supported if (supports_ble_privacy) { log::info("Updating rotation parameters."); handler_->CallOn( - this, - &LeAddressManager::prepare_to_update_irk, - UpdateIRKCommand{rotation_irk, minimum_rotation_time, maximum_rotation_time}); + this, &LeAddressManager::prepare_to_update_irk, + UpdateIRKCommand{rotation_irk, minimum_rotation_time, maximum_rotation_time}); } return; } - log::assert_that( - address_policy_ == AddressPolicy::POLICY_NOT_SET, - "assert failed: address_policy_ == AddressPolicy::POLICY_NOT_SET"); - log::assert_that( - address_policy != AddressPolicy::POLICY_NOT_SET, - "assert failed: address_policy != AddressPolicy::POLICY_NOT_SET"); - log::assert_that( - registered_clients_.empty(), "Policy must be set before clients are registered."); + log::assert_that(address_policy_ == AddressPolicy::POLICY_NOT_SET, + "assert failed: address_policy_ == AddressPolicy::POLICY_NOT_SET"); + log::assert_that(address_policy != AddressPolicy::POLICY_NOT_SET, + "assert failed: address_policy != AddressPolicy::POLICY_NOT_SET"); + log::assert_that(registered_clients_.empty(), + "Policy must be set before clients are registered."); address_policy_ = address_policy; supports_ble_privacy_ = supports_ble_privacy; log::info("New policy: {}", AddressPolicyText(address_policy)); @@ -122,14 +114,13 @@ void LeAddressManager::SetPrivacyPolicyForInitiatorAddress( auto addr = fixed_address.GetAddress(); auto address = addr.address; // The two most significant bits of the static address shall be equal to 1 - log::assert_that( - (address[5] & BLE_ADDR_MASK) == BLE_ADDR_MASK, - "The two most significant bits shall be equal to 1"); + log::assert_that((address[5] & BLE_ADDR_MASK) == BLE_ADDR_MASK, + "The two most significant bits shall be equal to 1"); // Bits of the random part of the address shall not be all 1 or all 0 - if ((address[0] == 0x00 && address[1] == 0x00 && address[2] == 0x00 && address[3] == 0x00 && address[4] == 0x00 && - address[5] == BLE_ADDR_MASK) || - (address[0] == 0xFF && address[1] == 0xFF && address[2] == 0xFF && address[3] == 0xFF && address[4] == 0xFF && - address[5] == 0xFF)) { + if ((address[0] == 0x00 && address[1] == 0x00 && address[2] == 0x00 && address[3] == 0x00 && + address[4] == 0x00 && address[5] == BLE_ADDR_MASK) || + (address[0] == 0xFF && address[1] == 0xFF && address[2] == 0xFF && address[3] == 0xFF && + address[4] == 0xFF && address[5] == 0xFF)) { log::fatal("Bits of the random part of the address shall not be all 1 or all 0"); } le_address_ = fixed_address; @@ -154,16 +145,13 @@ void LeAddressManager::SetPrivacyPolicyForInitiatorAddress( // TODO(jpawlowski): remove once we have config file abstraction in cert tests void LeAddressManager::SetPrivacyPolicyForInitiatorAddressForTest( - AddressPolicy address_policy, - AddressWithType fixed_address, - Octet16 rotation_irk, - std::chrono::milliseconds minimum_rotation_time, - std::chrono::milliseconds maximum_rotation_time) { - log::assert_that( - address_policy != AddressPolicy::POLICY_NOT_SET, - "assert failed: address_policy != AddressPolicy::POLICY_NOT_SET"); - log::assert_that( - registered_clients_.empty(), "Policy must be set before clients are registered."); + AddressPolicy address_policy, AddressWithType fixed_address, Octet16 rotation_irk, + std::chrono::milliseconds minimum_rotation_time, + std::chrono::milliseconds maximum_rotation_time) { + log::assert_that(address_policy != AddressPolicy::POLICY_NOT_SET, + "assert failed: address_policy != AddressPolicy::POLICY_NOT_SET"); + log::assert_that(registered_clients_.empty(), + "Policy must be set before clients are registered."); address_policy_ = address_policy; switch (address_policy_) { @@ -174,14 +162,13 @@ void LeAddressManager::SetPrivacyPolicyForInitiatorAddressForTest( auto addr = fixed_address.GetAddress(); auto address = addr.address; // The two most significant bits of the static address shall be equal to 1 - log::assert_that( - (address[5] & BLE_ADDR_MASK) == BLE_ADDR_MASK, - "The two most significant bits shall be equal to 1"); + log::assert_that((address[5] & BLE_ADDR_MASK) == BLE_ADDR_MASK, + "The two most significant bits shall be equal to 1"); // Bits of the random part of the address shall not be all 1 or all 0 - if ((address[0] == 0x00 && address[1] == 0x00 && address[2] == 0x00 && address[3] == 0x00 && address[4] == 0x00 && - address[5] == BLE_ADDR_MASK) || - (address[0] == 0xFF && address[1] == 0xFF && address[2] == 0xFF && address[3] == 0xFF && address[4] == 0xFF && - address[5] == 0xFF)) { + if ((address[0] == 0x00 && address[1] == 0x00 && address[2] == 0x00 && address[3] == 0x00 && + address[4] == 0x00 && address[5] == BLE_ADDR_MASK) || + (address[0] == 0xFF && address[1] == 0xFF && address[2] == 0xFF && address[3] == 0xFF && + address[4] == 0xFF && address[5] == 0xFF)) { log::fatal("Bits of the random part of the address shall not be all 1 or all 0"); } le_address_ = fixed_address; @@ -200,9 +187,7 @@ void LeAddressManager::SetPrivacyPolicyForInitiatorAddressForTest( log::fatal("invalid parameters"); } } -LeAddressManager::AddressPolicy LeAddressManager::GetAddressPolicy() { - return address_policy_; -} +LeAddressManager::AddressPolicy LeAddressManager::GetAddressPolicy() { return address_policy_; } bool LeAddressManager::RotatingAddress() { return address_policy_ == AddressPolicy::USE_RESOLVABLE_ADDRESS || address_policy_ == AddressPolicy::USE_NON_RESOLVABLE_ADDRESS; @@ -213,18 +198,18 @@ LeAddressManager::AddressPolicy LeAddressManager::Register(LeAddressManagerCallb } void LeAddressManager::register_client(LeAddressManagerCallback* callback) { - registered_clients_.insert(std::pair(callback, ClientState::RESUMED)); + registered_clients_.insert( + std::pair(callback, ClientState::RESUMED)); if (address_policy_ == AddressPolicy::POLICY_NOT_SET) { log::info("address policy isn't set yet, pause clients and return"); pause_registered_clients(); return; - } else if ( - address_policy_ == AddressPolicy::USE_RESOLVABLE_ADDRESS || - address_policy_ == AddressPolicy::USE_NON_RESOLVABLE_ADDRESS) { - if (registered_clients_.size() == 1) { - schedule_rotate_random_address(); - log::info("Scheduled address rotation for first client registered"); - } + } else if (address_policy_ == AddressPolicy::USE_RESOLVABLE_ADDRESS || + address_policy_ == AddressPolicy::USE_NON_RESOLVABLE_ADDRESS) { + if (registered_clients_.size() == 1) { + schedule_rotate_random_address(); + log::info("Scheduled address rotation for first client registered"); + } } log::info("Client registered"); } @@ -249,7 +234,8 @@ void LeAddressManager::unregister_client(LeAddressManagerCallback* callback) { } } -bool LeAddressManager::UnregisterSync(LeAddressManagerCallback* callback, std::chrono::milliseconds timeout) { +bool LeAddressManager::UnregisterSync(LeAddressManagerCallback* callback, + std::chrono::milliseconds timeout) { handler_->BindOnceOn(this, &LeAddressManager::unregister_client, callback)(); std::promise promise; auto future = promise.get_future(); @@ -266,9 +252,8 @@ void LeAddressManager::AckResume(LeAddressManagerCallback* callback) { } AddressWithType LeAddressManager::GetInitiatorAddress() { - log::assert_that( - address_policy_ != AddressPolicy::POLICY_NOT_SET, - "assert failed: address_policy_ != AddressPolicy::POLICY_NOT_SET"); + log::assert_that(address_policy_ != AddressPolicy::POLICY_NOT_SET, + "assert failed: address_policy_ != AddressPolicy::POLICY_NOT_SET"); return le_address_; } @@ -370,8 +355,8 @@ void LeAddressManager::prepare_to_rotate() { void LeAddressManager::schedule_rotate_random_address() { address_rotation_alarm_->Schedule( - common::BindOnce(&LeAddressManager::prepare_to_rotate, common::Unretained(this)), - GetNextPrivateAddressIntervalMs()); + common::BindOnce(&LeAddressManager::prepare_to_rotate, common::Unretained(this)), + GetNextPrivateAddressIntervalMs()); } void LeAddressManager::set_random_address() { @@ -463,10 +448,10 @@ hci::Address LeAddressManager::generate_nrpa() { // Bits of the random part of the address shall not be all 1 or all 0 std::array random = os::GenerateRandom<6>(); random[5] &= ~BLE_ADDR_MASK; - if ((random[0] == 0x00 && random[1] == 0x00 && random[2] == 0x00 && random[3] == 0x00 && random[4] == 0x00 && - random[5] == 0x00) || - (random[0] == 0xFF && random[1] == 0xFF && random[2] == 0xFF && random[3] == 0xFF && random[4] == 0xFF && - random[5] == 0x3F)) { + if ((random[0] == 0x00 && random[1] == 0x00 && random[2] == 0x00 && random[3] == 0x00 && + random[4] == 0x00 && random[5] == 0x00) || + (random[0] == 0xFF && random[1] == 0xFF && random[2] == 0xFF && random[3] == 0xFF && + random[4] == 0xFF && random[5] == 0x3F)) { random[0] = (uint8_t)(os::GenerateRandom() % 0xFE + 1); } @@ -487,13 +472,9 @@ std::chrono::milliseconds LeAddressManager::GetNextPrivateAddressIntervalMs() { return minimum_rotation_time_ + random_ms; } -uint8_t LeAddressManager::GetFilterAcceptListSize() { - return accept_list_size_; -} +uint8_t LeAddressManager::GetFilterAcceptListSize() { return accept_list_size_; } -uint8_t LeAddressManager::GetResolvingListSize() { - return resolving_list_size_; -} +uint8_t LeAddressManager::GetResolvingListSize() { return resolving_list_size_; } void LeAddressManager::handle_next_command() { for (auto client : registered_clients_) { @@ -509,57 +490,60 @@ void LeAddressManager::handle_next_command() { cached_commands_.pop(); std::visit( - [this](auto&& command) { - using T = std::decay_t; - if constexpr (std::is_same_v) { - update_irk(command); - } else if constexpr (std::is_same_v) { - rotate_random_address(); - } else if constexpr (std::is_same_v) { - enqueue_command_.Run(std::move(command.command)); - } else { - static_assert(!sizeof(T*), "non-exhaustive visitor!"); - } - }, - command.contents); + [this](auto&& command) { + using T = std::decay_t; + if constexpr (std::is_same_v) { + update_irk(command); + } else if constexpr (std::is_same_v) { + rotate_random_address(); + } else if constexpr (std::is_same_v) { + enqueue_command_.Run(std::move(command.command)); + } else { + static_assert(!sizeof(T*), "non-exhaustive visitor!"); + } + }, + command.contents); } void LeAddressManager::AddDeviceToFilterAcceptList( - FilterAcceptListAddressType accept_list_address_type, bluetooth::hci::Address address) { - auto packet_builder = hci::LeAddDeviceToFilterAcceptListBuilder::Create(accept_list_address_type, address); + FilterAcceptListAddressType accept_list_address_type, bluetooth::hci::Address address) { + auto packet_builder = + hci::LeAddDeviceToFilterAcceptListBuilder::Create(accept_list_address_type, address); Command command = {CommandType::ADD_DEVICE_TO_ACCEPT_LIST, HCICommand{std::move(packet_builder)}}; handler_->BindOnceOn(this, &LeAddressManager::push_command, std::move(command))(); } -void LeAddressManager::AddDeviceToResolvingList( - PeerAddressType peer_identity_address_type, - Address peer_identity_address, - const std::array& peer_irk, - const std::array& local_irk) { +void LeAddressManager::AddDeviceToResolvingList(PeerAddressType peer_identity_address_type, + Address peer_identity_address, + const std::array& peer_irk, + const std::array& local_irk) { if (!supports_ble_privacy_) { return; } // Disable Address resolution auto disable_builder = hci::LeSetAddressResolutionEnableBuilder::Create(hci::Enable::DISABLED); - Command disable = {CommandType::SET_ADDRESS_RESOLUTION_ENABLE, HCICommand{std::move(disable_builder)}}; + Command disable = {CommandType::SET_ADDRESS_RESOLUTION_ENABLE, + HCICommand{std::move(disable_builder)}}; cached_commands_.push(std::move(disable)); auto packet_builder = hci::LeAddDeviceToResolvingListBuilder::Create( - peer_identity_address_type, peer_identity_address, peer_irk, local_irk); - Command command = {CommandType::ADD_DEVICE_TO_RESOLVING_LIST, HCICommand{std::move(packet_builder)}}; + peer_identity_address_type, peer_identity_address, peer_irk, local_irk); + Command command = {CommandType::ADD_DEVICE_TO_RESOLVING_LIST, + HCICommand{std::move(packet_builder)}}; cached_commands_.push(std::move(command)); if (supports_ble_privacy_) { - auto packet_builder = - hci::LeSetPrivacyModeBuilder::Create(peer_identity_address_type, peer_identity_address, PrivacyMode::DEVICE); + auto packet_builder = hci::LeSetPrivacyModeBuilder::Create( + peer_identity_address_type, peer_identity_address, PrivacyMode::DEVICE); Command command = {CommandType::LE_SET_PRIVACY_MODE, HCICommand{std::move(packet_builder)}}; cached_commands_.push(std::move(command)); } // Enable Address resolution auto enable_builder = hci::LeSetAddressResolutionEnableBuilder::Create(hci::Enable::ENABLED); - Command enable = {CommandType::SET_ADDRESS_RESOLUTION_ENABLE, HCICommand{std::move(enable_builder)}}; + Command enable = {CommandType::SET_ADDRESS_RESOLUTION_ENABLE, + HCICommand{std::move(enable_builder)}}; cached_commands_.push(std::move(enable)); if (registered_clients_.empty()) { @@ -570,31 +554,36 @@ void LeAddressManager::AddDeviceToResolvingList( } void LeAddressManager::RemoveDeviceFromFilterAcceptList( - FilterAcceptListAddressType accept_list_address_type, bluetooth::hci::Address address) { - auto packet_builder = hci::LeRemoveDeviceFromFilterAcceptListBuilder::Create(accept_list_address_type, address); - Command command = {CommandType::REMOVE_DEVICE_FROM_ACCEPT_LIST, HCICommand{std::move(packet_builder)}}; + FilterAcceptListAddressType accept_list_address_type, bluetooth::hci::Address address) { + auto packet_builder = + hci::LeRemoveDeviceFromFilterAcceptListBuilder::Create(accept_list_address_type, address); + Command command = {CommandType::REMOVE_DEVICE_FROM_ACCEPT_LIST, + HCICommand{std::move(packet_builder)}}; handler_->BindOnceOn(this, &LeAddressManager::push_command, std::move(command))(); } -void LeAddressManager::RemoveDeviceFromResolvingList( - PeerAddressType peer_identity_address_type, Address peer_identity_address) { +void LeAddressManager::RemoveDeviceFromResolvingList(PeerAddressType peer_identity_address_type, + Address peer_identity_address) { if (!supports_ble_privacy_) { return; } // Disable Address resolution auto disable_builder = hci::LeSetAddressResolutionEnableBuilder::Create(hci::Enable::DISABLED); - Command disable = {CommandType::SET_ADDRESS_RESOLUTION_ENABLE, HCICommand{std::move(disable_builder)}}; + Command disable = {CommandType::SET_ADDRESS_RESOLUTION_ENABLE, + HCICommand{std::move(disable_builder)}}; cached_commands_.push(std::move(disable)); - auto packet_builder = - hci::LeRemoveDeviceFromResolvingListBuilder::Create(peer_identity_address_type, peer_identity_address); - Command command = {CommandType::REMOVE_DEVICE_FROM_RESOLVING_LIST, HCICommand{std::move(packet_builder)}}; + auto packet_builder = hci::LeRemoveDeviceFromResolvingListBuilder::Create( + peer_identity_address_type, peer_identity_address); + Command command = {CommandType::REMOVE_DEVICE_FROM_RESOLVING_LIST, + HCICommand{std::move(packet_builder)}}; cached_commands_.push(std::move(command)); // Enable Address resolution auto enable_builder = hci::LeSetAddressResolutionEnableBuilder::Create(hci::Enable::ENABLED); - Command enable = {CommandType::SET_ADDRESS_RESOLUTION_ENABLE, HCICommand{std::move(enable_builder)}}; + Command enable = {CommandType::SET_ADDRESS_RESOLUTION_ENABLE, + HCICommand{std::move(enable_builder)}}; cached_commands_.push(std::move(enable)); if (registered_clients_.empty()) { @@ -617,7 +606,8 @@ void LeAddressManager::ClearResolvingList() { // Disable Address resolution auto disable_builder = hci::LeSetAddressResolutionEnableBuilder::Create(hci::Enable::DISABLED); - Command disable = {CommandType::SET_ADDRESS_RESOLUTION_ENABLE, HCICommand{std::move(disable_builder)}}; + Command disable = {CommandType::SET_ADDRESS_RESOLUTION_ENABLE, + HCICommand{std::move(disable_builder)}}; cached_commands_.push(std::move(disable)); auto packet_builder = hci::LeClearResolvingListBuilder::Create(); @@ -626,7 +616,8 @@ void LeAddressManager::ClearResolvingList() { // Enable Address resolution auto enable_builder = hci::LeSetAddressResolutionEnableBuilder::Create(hci::Enable::ENABLED); - Command enable = {CommandType::SET_ADDRESS_RESOLUTION_ENABLE, HCICommand{std::move(enable_builder)}}; + Command enable = {CommandType::SET_ADDRESS_RESOLUTION_ENABLE, + HCICommand{std::move(enable_builder)}}; cached_commands_.push(std::move(enable)); handler_->BindOnceOn(this, &LeAddressManager::pause_registered_clients)(); @@ -643,10 +634,8 @@ void LeAddressManager::on_command_complete(CommandCompleteView view) { } auto status = complete_view.GetStatus(); if (status != ErrorCode::SUCCESS) { - log::error( - "Received {} complete with status {}", - hci::OpCodeText(op_code), - ErrorCodeText(complete_view.GetStatus())); + log::error("Received {} complete with status {}", hci::OpCodeText(op_code), + ErrorCodeText(complete_view.GetStatus())); } } @@ -660,12 +649,12 @@ void LeAddressManager::OnCommandComplete(bluetooth::hci::CommandCompleteView vie switch (op_code) { case OpCode::LE_SET_RANDOM_ADDRESS: { - // The command was sent before any client registered, we can make sure all the clients paused when command - // complete. + // The command was sent before any client registered, we can make sure all the clients paused + // when command complete. if (address_policy_ == AddressPolicy::USE_STATIC_ADDRESS) { log::info( - "Received LE_SET_RANDOM_ADDRESS complete and Address policy is USE_STATIC_ADDRESS, " - "return"); + "Received LE_SET_RANDOM_ADDRESS complete and Address policy is USE_STATIC_ADDRESS, " + "return"); return; } auto complete_view = LeSetRandomAddressCompleteView::Create(view); @@ -673,9 +662,8 @@ void LeAddressManager::OnCommandComplete(bluetooth::hci::CommandCompleteView vie log::error("Received LE_SET_RANDOM_ADDRESS complete with invalid packet"); } else { if (complete_view.GetStatus() != ErrorCode::SUCCESS) { - log::error( - "Received LE_SET_RANDOM_ADDRESS complete with status {}", - ErrorCodeText(complete_view.GetStatus())); + log::error("Received LE_SET_RANDOM_ADDRESS complete with status {}", + ErrorCodeText(complete_view.GetStatus())); } else { log::info("update random address : {}", cached_address_.GetAddress()); le_address_ = cached_address_; diff --git a/system/gd/hci/le_address_manager.h b/system/gd/hci/le_address_manager.h index 74edad1f044..35032ca1f6b 100644 --- a/system/gd/hci/le_address_manager.h +++ b/system/gd/hci/le_address_manager.h @@ -31,21 +31,18 @@ namespace hci { constexpr std::chrono::milliseconds kUnregisterSyncTimeoutInMs = std::chrono::milliseconds(10); class LeAddressManagerCallback { - public: +public: virtual ~LeAddressManagerCallback() = default; virtual void OnPause() = 0; virtual void OnResume() = 0; - virtual void NotifyOnIRKChange(){}; + virtual void NotifyOnIRKChange() {} }; class LeAddressManager { - public: - LeAddressManager( - common::Callback)> enqueue_command, - os::Handler* handler, - Address public_address, - uint8_t accept_list_size, - uint8_t resolving_list_size); +public: + LeAddressManager(common::Callback)> enqueue_command, + os::Handler* handler, Address public_address, uint8_t accept_list_size, + uint8_t resolving_list_size); virtual ~LeAddressManager(); enum AddressPolicy { @@ -57,59 +54,55 @@ class LeAddressManager { }; // Aborts if called more than once - void SetPrivacyPolicyForInitiatorAddress( - AddressPolicy address_policy, - AddressWithType fixed_address, - Octet16 rotation_irk, - bool supports_ble_privacy, - std::chrono::milliseconds minimum_rotation_time, - std::chrono::milliseconds maximum_rotation_time); + void SetPrivacyPolicyForInitiatorAddress(AddressPolicy address_policy, + AddressWithType fixed_address, Octet16 rotation_irk, + bool supports_ble_privacy, + std::chrono::milliseconds minimum_rotation_time, + std::chrono::milliseconds maximum_rotation_time); // TODO(jpawlowski): remove once we have config file abstraction in cert tests - void SetPrivacyPolicyForInitiatorAddressForTest( - AddressPolicy address_policy, - AddressWithType fixed_address, - Octet16 rotation_irk, - std::chrono::milliseconds minimum_rotation_time, - std::chrono::milliseconds maximum_rotation_time); + void SetPrivacyPolicyForInitiatorAddressForTest(AddressPolicy address_policy, + AddressWithType fixed_address, + Octet16 rotation_irk, + std::chrono::milliseconds minimum_rotation_time, + std::chrono::milliseconds maximum_rotation_time); AddressPolicy GetAddressPolicy(); bool RotatingAddress(); virtual void AckPause(LeAddressManagerCallback* callback); virtual void AckResume(LeAddressManagerCallback* callback); virtual AddressPolicy Register(LeAddressManagerCallback* callback); virtual void Unregister(LeAddressManagerCallback* callback); - virtual bool UnregisterSync( - LeAddressManagerCallback* callback, - std::chrono::milliseconds timeout = kUnregisterSyncTimeoutInMs); + virtual bool UnregisterSync(LeAddressManagerCallback* callback, + std::chrono::milliseconds timeout = kUnregisterSyncTimeoutInMs); virtual AddressWithType GetInitiatorAddress(); // What was set in SetRandomAddress() virtual AddressWithType NewResolvableAddress(); // A new random address without rotating. virtual AddressWithType NewNonResolvableAddress(); // A new non-resolvable address uint8_t GetFilterAcceptListSize(); uint8_t GetResolvingListSize(); - void AddDeviceToFilterAcceptList(FilterAcceptListAddressType accept_list_address_type, Address address); - void AddDeviceToResolvingList( - PeerAddressType peer_identity_address_type, - Address peer_identity_address, - const std::array& peer_irk, - const std::array& local_irk); - void RemoveDeviceFromFilterAcceptList(FilterAcceptListAddressType accept_list_address_type, Address address); - void RemoveDeviceFromResolvingList(PeerAddressType peer_identity_address_type, Address peer_identity_address); + void AddDeviceToFilterAcceptList(FilterAcceptListAddressType accept_list_address_type, + Address address); + void AddDeviceToResolvingList(PeerAddressType peer_identity_address_type, + Address peer_identity_address, + const std::array& peer_irk, + const std::array& local_irk); + void RemoveDeviceFromFilterAcceptList(FilterAcceptListAddressType accept_list_address_type, + Address address); + void RemoveDeviceFromResolvingList(PeerAddressType peer_identity_address_type, + Address peer_identity_address); void ClearFilterAcceptList(); void ClearResolvingList(); void OnCommandComplete(CommandCompleteView view); std::chrono::milliseconds GetNextPrivateAddressIntervalMs(); // Unsynchronized check for testing purposes - size_t NumberCachedCommands() const { - return cached_commands_.size(); - } + size_t NumberCachedCommands() const { return cached_commands_.size(); } - protected: +protected: AddressPolicy address_policy_ = AddressPolicy::POLICY_NOT_SET; std::chrono::milliseconds minimum_rotation_time_; std::chrono::milliseconds maximum_rotation_time_; - private: +private: enum class ClientState; std::string ClientStateText(const ClientState cs); @@ -139,7 +132,8 @@ class LeAddressManager { }; struct Command { - CommandType command_type; // Note that this field is only intended for logging, not control flow + CommandType + command_type; // Note that this field is only intended for logging, not control flow std::variant contents; }; diff --git a/system/gd/hci/le_address_manager_test.cc b/system/gd/hci/le_address_manager_test.cc index 180f9194130..46e7c347846 100644 --- a/system/gd/hci/le_address_manager_test.cc +++ b/system/gd/hci/le_address_manager_test.cc @@ -38,8 +38,9 @@ using packet::PacketView; using packet::RawBuilder; class RotatorClient : public LeAddressManagerCallback { - public: - RotatorClient(LeAddressManager* le_address_manager, size_t id) : le_address_manager_(le_address_manager), id_(id){}; +public: + RotatorClient(LeAddressManager* le_address_manager, size_t id) + : le_address_manager_(le_address_manager), id_(id) {} void OnPause() { paused = true; @@ -72,14 +73,15 @@ class RotatorClient : public LeAddressManagerCallback { }; class LeAddressManagerTest : public ::testing::Test { - public: +public: void SetUp() override { thread_ = new Thread("thread", Thread::Priority::NORMAL); handler_ = new Handler(thread_); hci_layer_ = new HciLayerFake(); Address address({0x01, 0x02, 0x03, 0x04, 0x05, 0x06}); le_address_manager_ = new LeAddressManager( - common::Bind(&LeAddressManagerTest::enqueue_command, common::Unretained(this)), handler_, address, 0x3F, 0x3F); + common::Bind(&LeAddressManagerTest::enqueue_command, common::Unretained(this)), + handler_, address, 0x3F, 0x3F); AllocateClients(1); } @@ -108,10 +110,9 @@ class LeAddressManagerTest : public ::testing::Test { } void enqueue_command(std::unique_ptr command_packet) { - hci_layer_->EnqueueCommand( - std::move(command_packet), - handler_->BindOnce( - &LeAddressManager::OnCommandComplete, common::Unretained(le_address_manager_))); + hci_layer_->EnqueueCommand(std::move(command_packet), + handler_->BindOnce(&LeAddressManager::OnCommandComplete, + common::Unretained(le_address_manager_))); } Thread* thread_; @@ -131,17 +132,14 @@ TEST_F(LeAddressManagerTest, register_unregister_callback) { } TEST_F(LeAddressManagerTest, rotator_address_for_single_client) { - Octet16 irk = {0xec, 0x02, 0x34, 0xa3, 0x57, 0xc8, 0xad, 0x05, 0x34, 0x10, 0x10, 0xa6, 0x0a, 0x39, 0x7d, 0x9b}; + Octet16 irk = {0xec, 0x02, 0x34, 0xa3, 0x57, 0xc8, 0xad, 0x05, + 0x34, 0x10, 0x10, 0xa6, 0x0a, 0x39, 0x7d, 0x9b}; auto minimum_rotation_time = std::chrono::milliseconds(1000); auto maximum_rotation_time = std::chrono::milliseconds(3000); AddressWithType remote_address(Address::kEmpty, AddressType::RANDOM_DEVICE_ADDRESS); le_address_manager_->SetPrivacyPolicyForInitiatorAddress( - LeAddressManager::AddressPolicy::USE_RESOLVABLE_ADDRESS, - remote_address, - irk, - false, - minimum_rotation_time, - maximum_rotation_time); + LeAddressManager::AddressPolicy::USE_RESOLVABLE_ADDRESS, remote_address, irk, false, + minimum_rotation_time, maximum_rotation_time); le_address_manager_->Register(clients[0].get()); sync_handler(handler_); @@ -158,12 +156,8 @@ TEST_F(LeAddressManagerTest, rotator_non_resolvable_address_for_single_client) { auto maximum_rotation_time = std::chrono::milliseconds(3000); AddressWithType remote_address(Address::kEmpty, AddressType::RANDOM_DEVICE_ADDRESS); le_address_manager_->SetPrivacyPolicyForInitiatorAddress( - LeAddressManager::AddressPolicy::USE_NON_RESOLVABLE_ADDRESS, - remote_address, - irk, - false, - minimum_rotation_time, - maximum_rotation_time); + LeAddressManager::AddressPolicy::USE_NON_RESOLVABLE_ADDRESS, remote_address, irk, false, + minimum_rotation_time, maximum_rotation_time); le_address_manager_->Register(clients[0].get()); sync_handler(handler_); @@ -177,17 +171,14 @@ TEST_F(LeAddressManagerTest, rotator_non_resolvable_address_for_single_client) { // TODO handle the case "register during rotate_random_address" and enable this TEST_F(LeAddressManagerTest, DISABLED_rotator_address_for_multiple_clients) { AllocateClients(2); - Octet16 irk = {0xec, 0x02, 0x34, 0xa3, 0x57, 0xc8, 0xad, 0x05, 0x34, 0x10, 0x10, 0xa6, 0x0a, 0x39, 0x7d, 0x9b}; + Octet16 irk = {0xec, 0x02, 0x34, 0xa3, 0x57, 0xc8, 0xad, 0x05, + 0x34, 0x10, 0x10, 0xa6, 0x0a, 0x39, 0x7d, 0x9b}; auto minimum_rotation_time = std::chrono::milliseconds(1000); auto maximum_rotation_time = std::chrono::milliseconds(3000); AddressWithType remote_address(Address::kEmpty, AddressType::RANDOM_DEVICE_ADDRESS); le_address_manager_->SetPrivacyPolicyForInitiatorAddress( - LeAddressManager::AddressPolicy::USE_RESOLVABLE_ADDRESS, - remote_address, - irk, - false, - minimum_rotation_time, - maximum_rotation_time); + LeAddressManager::AddressPolicy::USE_RESOLVABLE_ADDRESS, remote_address, irk, false, + minimum_rotation_time, maximum_rotation_time); le_address_manager_->Register(clients[0].get()); le_address_manager_->Register(clients[1].get()); le_address_manager_->Register(clients[2].get()); @@ -200,7 +191,7 @@ TEST_F(LeAddressManagerTest, DISABLED_rotator_address_for_multiple_clients) { } class LeAddressManagerWithSingleClientTest : public LeAddressManagerTest { - public: +public: void SetUp() override { bluetooth::common::InitFlags::SetAllForTesting(); thread_ = new Thread("thread", Thread::Priority::NORMAL); @@ -208,24 +199,19 @@ class LeAddressManagerWithSingleClientTest : public LeAddressManagerTest { hci_layer_ = new HciLayerFake(); Address address({0x01, 0x02, 0x03, 0x04, 0x05, 0x06}); le_address_manager_ = new LeAddressManager( - common::Bind(&LeAddressManagerWithSingleClientTest::enqueue_command, common::Unretained(this)), - handler_, - address, - 0x3F, - 0x3F); + common::Bind(&LeAddressManagerWithSingleClientTest::enqueue_command, + common::Unretained(this)), + handler_, address, 0x3F, 0x3F); AllocateClients(1); - Octet16 irk = {0xec, 0x02, 0x34, 0xa3, 0x57, 0xc8, 0xad, 0x05, 0x34, 0x10, 0x10, 0xa6, 0x0a, 0x39, 0x7d, 0x9b}; + Octet16 irk = {0xec, 0x02, 0x34, 0xa3, 0x57, 0xc8, 0xad, 0x05, + 0x34, 0x10, 0x10, 0xa6, 0x0a, 0x39, 0x7d, 0x9b}; auto minimum_rotation_time = std::chrono::milliseconds(1000); auto maximum_rotation_time = std::chrono::milliseconds(3000); AddressWithType remote_address(Address::kEmpty, AddressType::RANDOM_DEVICE_ADDRESS); le_address_manager_->SetPrivacyPolicyForInitiatorAddress( - LeAddressManager::AddressPolicy::USE_RESOLVABLE_ADDRESS, - remote_address, - irk, - false, - minimum_rotation_time, - maximum_rotation_time); + LeAddressManager::AddressPolicy::USE_RESOLVABLE_ADDRESS, remote_address, irk, false, + minimum_rotation_time, maximum_rotation_time); le_address_manager_->Register(clients[0].get()); sync_handler(handler_); @@ -234,10 +220,9 @@ class LeAddressManagerWithSingleClientTest : public LeAddressManagerTest { } void enqueue_command(std::unique_ptr command_packet) { - hci_layer_->EnqueueCommand( - std::move(command_packet), - handler_->BindOnce( - &LeAddressManager::OnCommandComplete, common::Unretained(le_address_manager_))); + hci_layer_->EnqueueCommand(std::move(command_packet), + handler_->BindOnce(&LeAddressManager::OnCommandComplete, + common::Unretained(le_address_manager_))); } void TearDown() override { @@ -257,13 +242,13 @@ TEST_F(LeAddressManagerWithSingleClientTest, add_device_to_accept_list) { le_address_manager_->AddDeviceToFilterAcceptList(FilterAcceptListAddressType::RANDOM, address); auto packet = hci_layer_->GetCommand(OpCode::LE_ADD_DEVICE_TO_FILTER_ACCEPT_LIST); auto packet_view = LeAddDeviceToFilterAcceptListView::Create( - LeConnectionManagementCommandView::Create(AclCommandView::Create(packet))); + LeConnectionManagementCommandView::Create(AclCommandView::Create(packet))); ASSERT_TRUE(packet_view.IsValid()); ASSERT_EQ(FilterAcceptListAddressType::RANDOM, packet_view.GetAddressType()); ASSERT_EQ(address, packet_view.GetAddress()); hci_layer_->IncomingEvent( - LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); + LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); clients[0].get()->WaitForResume(); } @@ -273,17 +258,18 @@ TEST_F(LeAddressManagerWithSingleClientTest, remove_device_from_accept_list) { le_address_manager_->AddDeviceToFilterAcceptList(FilterAcceptListAddressType::RANDOM, address); hci_layer_->GetCommand(OpCode::LE_ADD_DEVICE_TO_FILTER_ACCEPT_LIST); hci_layer_->IncomingEvent( - LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); + LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); - le_address_manager_->RemoveDeviceFromFilterAcceptList(FilterAcceptListAddressType::RANDOM, address); + le_address_manager_->RemoveDeviceFromFilterAcceptList(FilterAcceptListAddressType::RANDOM, + address); auto packet = hci_layer_->GetCommand(OpCode::LE_REMOVE_DEVICE_FROM_FILTER_ACCEPT_LIST); auto packet_view = LeRemoveDeviceFromFilterAcceptListView::Create( - LeConnectionManagementCommandView::Create(AclCommandView::Create(packet))); + LeConnectionManagementCommandView::Create(AclCommandView::Create(packet))); ASSERT_TRUE(packet_view.IsValid()); ASSERT_EQ(FilterAcceptListAddressType::RANDOM, packet_view.GetAddressType()); ASSERT_EQ(address, packet_view.GetAddress()); hci_layer_->IncomingEvent( - LeRemoveDeviceFromFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); + LeRemoveDeviceFromFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); clients[0].get()->WaitForResume(); } @@ -293,12 +279,12 @@ TEST_F(LeAddressManagerWithSingleClientTest, clear_filter_accept_list) { le_address_manager_->AddDeviceToFilterAcceptList(FilterAcceptListAddressType::RANDOM, address); hci_layer_->GetCommand(OpCode::LE_ADD_DEVICE_TO_FILTER_ACCEPT_LIST); hci_layer_->IncomingEvent( - LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); + LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); le_address_manager_->ClearFilterAcceptList(); hci_layer_->GetCommand(OpCode::LE_CLEAR_FILTER_ACCEPT_LIST); hci_layer_->IncomingEvent( - LeClearFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); + LeClearFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); clients[0].get()->WaitForResume(); } @@ -306,37 +292,43 @@ TEST_F(LeAddressManagerWithSingleClientTest, clear_filter_accept_list) { TEST_F(LeAddressManagerWithSingleClientTest, DISABLED_add_device_to_resolving_list) { Address address; Address::FromString("01:02:03:04:05:06", address); - Octet16 peer_irk = {0xec, 0x02, 0x34, 0xa3, 0x57, 0xc8, 0xad, 0x05, 0x34, 0x10, 0x10, 0xa6, 0x0a, 0x39, 0x7d, 0x9b}; - Octet16 local_irk = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10}; + Octet16 peer_irk = {0xec, 0x02, 0x34, 0xa3, 0x57, 0xc8, 0xad, 0x05, + 0x34, 0x10, 0x10, 0xa6, 0x0a, 0x39, 0x7d, 0x9b}; + Octet16 local_irk = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, + 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10}; - le_address_manager_->AddDeviceToResolvingList( - PeerAddressType::RANDOM_DEVICE_OR_IDENTITY_ADDRESS, address, peer_irk, local_irk); + le_address_manager_->AddDeviceToResolvingList(PeerAddressType::RANDOM_DEVICE_OR_IDENTITY_ADDRESS, + address, peer_irk, local_irk); { auto packet = hci_layer_->GetCommand(OpCode::LE_SET_ADDRESS_RESOLUTION_ENABLE); - auto packet_view = LeSetAddressResolutionEnableView::Create(LeSecurityCommandView::Create(packet)); + auto packet_view = + LeSetAddressResolutionEnableView::Create(LeSecurityCommandView::Create(packet)); ASSERT_TRUE(packet_view.IsValid()); ASSERT_EQ(Enable::DISABLED, packet_view.GetAddressResolutionEnable()); hci_layer_->IncomingEvent( - LeSetAddressResolutionEnableCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); + LeSetAddressResolutionEnableCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); } { auto packet = hci_layer_->GetCommand(OpCode::LE_ADD_DEVICE_TO_RESOLVING_LIST); - auto packet_view = LeAddDeviceToResolvingListView::Create(LeSecurityCommandView::Create(packet)); + auto packet_view = + LeAddDeviceToResolvingListView::Create(LeSecurityCommandView::Create(packet)); ASSERT_TRUE(packet_view.IsValid()); - ASSERT_EQ(PeerAddressType::RANDOM_DEVICE_OR_IDENTITY_ADDRESS, packet_view.GetPeerIdentityAddressType()); + ASSERT_EQ(PeerAddressType::RANDOM_DEVICE_OR_IDENTITY_ADDRESS, + packet_view.GetPeerIdentityAddressType()); ASSERT_EQ(address, packet_view.GetPeerIdentityAddress()); ASSERT_EQ(peer_irk, packet_view.GetPeerIrk()); ASSERT_EQ(local_irk, packet_view.GetLocalIrk()); hci_layer_->IncomingEvent( - LeAddDeviceToResolvingListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); + LeAddDeviceToResolvingListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); } { auto packet = hci_layer_->GetCommand(OpCode::LE_SET_ADDRESS_RESOLUTION_ENABLE); - auto packet_view = LeSetAddressResolutionEnableView::Create(LeSecurityCommandView::Create(packet)); + auto packet_view = + LeSetAddressResolutionEnableView::Create(LeSecurityCommandView::Create(packet)); ASSERT_TRUE(packet_view.IsValid()); ASSERT_EQ(Enable::ENABLED, packet_view.GetAddressResolutionEnable()); hci_layer_->IncomingEvent( - LeSetAddressResolutionEnableCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); + LeSetAddressResolutionEnableCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); } clients[0].get()->WaitForResume(); } @@ -345,61 +337,52 @@ TEST_F(LeAddressManagerWithSingleClientTest, DISABLED_add_device_to_resolving_li TEST_F(LeAddressManagerWithSingleClientTest, DISABLED_remove_device_from_resolving_list) { Address address; Address::FromString("01:02:03:04:05:06", address); - Octet16 peer_irk = {0xec, 0x02, 0x34, 0xa3, 0x57, 0xc8, 0xad, 0x05, 0x34, 0x10, 0x10, 0xa6, 0x0a, 0x39, 0x7d, 0x9b}; - Octet16 local_irk = { - 0x01, - 0x02, - 0x03, - 0x04, - 0x05, - 0x06, - 0x07, - 0x08, - 0x09, - 0x0a, - 0x0b, - 0x0c, - 0x0d, - 0x0e, - 0x0f, - 0x10}; - le_address_manager_->AddDeviceToResolvingList( - PeerAddressType::RANDOM_DEVICE_OR_IDENTITY_ADDRESS, address, peer_irk, local_irk); + Octet16 peer_irk = {0xec, 0x02, 0x34, 0xa3, 0x57, 0xc8, 0xad, 0x05, + 0x34, 0x10, 0x10, 0xa6, 0x0a, 0x39, 0x7d, 0x9b}; + Octet16 local_irk = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, + 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10}; + le_address_manager_->AddDeviceToResolvingList(PeerAddressType::RANDOM_DEVICE_OR_IDENTITY_ADDRESS, + address, peer_irk, local_irk); hci_layer_->GetCommand(OpCode::LE_SET_ADDRESS_RESOLUTION_ENABLE); hci_layer_->IncomingEvent( - LeSetAddressResolutionEnableCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); + LeSetAddressResolutionEnableCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); hci_layer_->GetCommand(OpCode::LE_ADD_DEVICE_TO_RESOLVING_LIST); hci_layer_->IncomingEvent( - LeAddDeviceToResolvingListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); + LeAddDeviceToResolvingListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); hci_layer_->GetCommand(OpCode::LE_SET_ADDRESS_RESOLUTION_ENABLE); hci_layer_->IncomingEvent( - LeSetAddressResolutionEnableCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); + LeSetAddressResolutionEnableCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); - le_address_manager_->RemoveDeviceFromResolvingList(PeerAddressType::RANDOM_DEVICE_OR_IDENTITY_ADDRESS, address); + le_address_manager_->RemoveDeviceFromResolvingList( + PeerAddressType::RANDOM_DEVICE_OR_IDENTITY_ADDRESS, address); { auto packet = hci_layer_->GetCommand(OpCode::LE_SET_ADDRESS_RESOLUTION_ENABLE); - auto packet_view = LeSetAddressResolutionEnableView::Create(LeSecurityCommandView::Create(packet)); + auto packet_view = + LeSetAddressResolutionEnableView::Create(LeSecurityCommandView::Create(packet)); ASSERT_TRUE(packet_view.IsValid()); ASSERT_EQ(Enable::DISABLED, packet_view.GetAddressResolutionEnable()); hci_layer_->IncomingEvent( - LeSetAddressResolutionEnableCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); + LeSetAddressResolutionEnableCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); } { auto packet = hci_layer_->GetCommand(OpCode::LE_REMOVE_DEVICE_FROM_RESOLVING_LIST); - auto packet_view = LeRemoveDeviceFromResolvingListView::Create(LeSecurityCommandView::Create(packet)); + auto packet_view = + LeRemoveDeviceFromResolvingListView::Create(LeSecurityCommandView::Create(packet)); ASSERT_TRUE(packet_view.IsValid()); - ASSERT_EQ(PeerAddressType::RANDOM_DEVICE_OR_IDENTITY_ADDRESS, packet_view.GetPeerIdentityAddressType()); + ASSERT_EQ(PeerAddressType::RANDOM_DEVICE_OR_IDENTITY_ADDRESS, + packet_view.GetPeerIdentityAddressType()); ASSERT_EQ(address, packet_view.GetPeerIdentityAddress()); hci_layer_->IncomingEvent( - LeRemoveDeviceFromResolvingListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); + LeRemoveDeviceFromResolvingListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); } { auto packet = hci_layer_->GetCommand(OpCode::LE_SET_ADDRESS_RESOLUTION_ENABLE); - auto packet_view = LeSetAddressResolutionEnableView::Create(LeSecurityCommandView::Create(packet)); + auto packet_view = + LeSetAddressResolutionEnableView::Create(LeSecurityCommandView::Create(packet)); ASSERT_TRUE(packet_view.IsValid()); ASSERT_EQ(Enable::ENABLED, packet_view.GetAddressResolutionEnable()); hci_layer_->IncomingEvent( - LeSetAddressResolutionEnableCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); + LeSetAddressResolutionEnableCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); } clients[0].get()->WaitForResume(); } @@ -408,59 +391,47 @@ TEST_F(LeAddressManagerWithSingleClientTest, DISABLED_remove_device_from_resolvi TEST_F(LeAddressManagerWithSingleClientTest, DISABLED_clear_resolving_list) { Address address; Address::FromString("01:02:03:04:05:06", address); - Octet16 peer_irk = {0xec, 0x02, 0x34, 0xa3, 0x57, 0xc8, 0xad, 0x05, 0x34, 0x10, 0x10, 0xa6, 0x0a, 0x39, 0x7d, 0x9b}; - Octet16 local_irk = { - 0x01, - 0x02, - 0x03, - 0x04, - 0x05, - 0x06, - 0x07, - 0x08, - 0x09, - 0x0a, - 0x0b, - 0x0c, - 0x0d, - 0x0e, - 0x0f, - 0x10}; - le_address_manager_->AddDeviceToResolvingList( - PeerAddressType::RANDOM_DEVICE_OR_IDENTITY_ADDRESS, address, peer_irk, local_irk); + Octet16 peer_irk = {0xec, 0x02, 0x34, 0xa3, 0x57, 0xc8, 0xad, 0x05, + 0x34, 0x10, 0x10, 0xa6, 0x0a, 0x39, 0x7d, 0x9b}; + Octet16 local_irk = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, + 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10}; + le_address_manager_->AddDeviceToResolvingList(PeerAddressType::RANDOM_DEVICE_OR_IDENTITY_ADDRESS, + address, peer_irk, local_irk); hci_layer_->GetCommand(OpCode::LE_SET_ADDRESS_RESOLUTION_ENABLE); hci_layer_->IncomingEvent( - LeSetAddressResolutionEnableCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); + LeSetAddressResolutionEnableCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); hci_layer_->GetCommand(OpCode::LE_ADD_DEVICE_TO_RESOLVING_LIST); hci_layer_->IncomingEvent( - LeAddDeviceToResolvingListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); + LeAddDeviceToResolvingListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); hci_layer_->GetCommand(OpCode::LE_SET_ADDRESS_RESOLUTION_ENABLE); hci_layer_->IncomingEvent( - LeSetAddressResolutionEnableCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); + LeSetAddressResolutionEnableCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); le_address_manager_->ClearResolvingList(); { auto packet = hci_layer_->GetCommand(OpCode::LE_SET_ADDRESS_RESOLUTION_ENABLE); - auto packet_view = LeSetAddressResolutionEnableView::Create(LeSecurityCommandView::Create(packet)); + auto packet_view = + LeSetAddressResolutionEnableView::Create(LeSecurityCommandView::Create(packet)); ASSERT_TRUE(packet_view.IsValid()); ASSERT_EQ(Enable::DISABLED, packet_view.GetAddressResolutionEnable()); hci_layer_->IncomingEvent( - LeSetAddressResolutionEnableCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); + LeSetAddressResolutionEnableCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); } { auto packet = hci_layer_->GetCommand(OpCode::LE_CLEAR_RESOLVING_LIST); auto packet_view = LeClearResolvingListView::Create(LeSecurityCommandView::Create(packet)); ASSERT_TRUE(packet_view.IsValid()); hci_layer_->IncomingEvent( - LeClearResolvingListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); + LeClearResolvingListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); } { auto packet = hci_layer_->GetCommand(OpCode::LE_SET_ADDRESS_RESOLUTION_ENABLE); - auto packet_view = LeSetAddressResolutionEnableView::Create(LeSecurityCommandView::Create(packet)); + auto packet_view = + LeSetAddressResolutionEnableView::Create(LeSecurityCommandView::Create(packet)); ASSERT_TRUE(packet_view.IsValid()); ASSERT_EQ(Enable::ENABLED, packet_view.GetAddressResolutionEnable()); hci_layer_->IncomingEvent( - LeSetAddressResolutionEnableCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); + LeSetAddressResolutionEnableCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); } clients[0].get()->WaitForResume(); @@ -472,12 +443,12 @@ TEST_F(LeAddressManagerWithSingleClientTest, register_during_command_complete) { le_address_manager_->AddDeviceToFilterAcceptList(FilterAcceptListAddressType::RANDOM, address); auto packet = hci_layer_->GetCommand(OpCode::LE_ADD_DEVICE_TO_FILTER_ACCEPT_LIST); auto packet_view = LeAddDeviceToFilterAcceptListView::Create( - LeConnectionManagementCommandView::Create(AclCommandView::Create(packet))); + LeConnectionManagementCommandView::Create(AclCommandView::Create(packet))); ASSERT_TRUE(packet_view.IsValid()); ASSERT_EQ(FilterAcceptListAddressType::RANDOM, packet_view.GetAddressType()); ASSERT_EQ(address, packet_view.GetAddress()); hci_layer_->IncomingEvent( - LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); + LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS)); AllocateClients(1); le_address_manager_->Register(clients[1].get()); diff --git a/system/gd/hci/le_advertising_interface.h b/system/gd/hci/le_advertising_interface.h index c419c426864..5fcddc71236 100644 --- a/system/gd/hci/le_advertising_interface.h +++ b/system/gd/hci/le_advertising_interface.h @@ -23,8 +23,8 @@ namespace bluetooth { namespace hci { constexpr hci::SubeventCode LeAdvertisingEvents[] = { - hci::SubeventCode::SCAN_REQUEST_RECEIVED, - hci::SubeventCode::ADVERTISING_SET_TERMINATED, + hci::SubeventCode::SCAN_REQUEST_RECEIVED, + hci::SubeventCode::ADVERTISING_SET_TERMINATED, }; typedef CommandInterface LeAdvertisingInterface; diff --git a/system/gd/hci/le_advertising_manager.cc b/system/gd/hci/le_advertising_manager.cc index 24e86bfddb6..3cfb54ba400 100644 --- a/system/gd/hci/le_advertising_manager.cc +++ b/system/gd/hci/le_advertising_manager.cc @@ -38,7 +38,8 @@ namespace bluetooth { namespace hci { -const ModuleFactory LeAdvertisingManager::Factory = ModuleFactory([]() { return new LeAdvertisingManager(); }); +const ModuleFactory LeAdvertisingManager::Factory = + ModuleFactory([]() { return new LeAdvertisingManager(); }); constexpr int kIdLocal = 0xff; // Id for advertiser not register from Java layer constexpr uint16_t kLenOfFlags = 0x03; constexpr int64_t kLeAdvertisingTxPowerMin = -127; @@ -94,7 +95,8 @@ struct Advertiser { * (3) if the host supports RPAs, then the requested type will always be honored */ AdvertiserAddressType GetAdvertiserAddressTypeFromRequestedTypeAndPolicy( - AdvertiserAddressType requested_address_type, LeAddressManager::AddressPolicy address_policy) { + AdvertiserAddressType requested_address_type, + LeAddressManager::AddressPolicy address_policy) { switch (address_policy) { case LeAddressManager::AddressPolicy::USE_PUBLIC_ADDRESS: case LeAddressManager::AddressPolicy::USE_STATIC_ADDRESS: @@ -103,8 +105,8 @@ AdvertiserAddressType GetAdvertiserAddressTypeFromRequestedTypeAndPolicy( return requested_address_type; case LeAddressManager::AddressPolicy::USE_NON_RESOLVABLE_ADDRESS: return requested_address_type == AdvertiserAddressType::RESOLVABLE_RANDOM - ? AdvertiserAddressType::NONRESOLVABLE_RANDOM - : requested_address_type; + ? AdvertiserAddressType::NONRESOLVABLE_RANDOM + : requested_address_type; default: log::fatal("unreachable"); return AdvertiserAddressType::PUBLIC; @@ -118,16 +120,17 @@ AdvertiserAddressType GetAdvertiserAddressTypeFromRequestedTypeAndPolicy( * (2) in other cases, based on the requested type and the address manager policy. */ AdvertiserAddressType GetAdvertiserAddressTypeNonConnectable( - AdvertiserAddressType requested_address_type, LeAddressManager::AddressPolicy address_policy) { + AdvertiserAddressType requested_address_type, + LeAddressManager::AddressPolicy address_policy) { switch (address_policy) { case LeAddressManager::AddressPolicy::USE_PUBLIC_ADDRESS: case LeAddressManager::AddressPolicy::USE_STATIC_ADDRESS: return requested_address_type == AdvertiserAddressType::RESOLVABLE_RANDOM - ? AdvertiserAddressType::NONRESOLVABLE_RANDOM - : requested_address_type; + ? AdvertiserAddressType::NONRESOLVABLE_RANDOM + : requested_address_type; default: - return GetAdvertiserAddressTypeFromRequestedTypeAndPolicy( - requested_address_type, address_policy); + return GetAdvertiserAddressTypeFromRequestedTypeAndPolicy(requested_address_type, + address_policy); } } @@ -141,11 +144,8 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb advertising_sets_.clear(); } - void start( - os::Handler* handler, - hci::HciLayer* hci_layer, - hci::Controller* controller, - hci::AclManager* acl_manager) { + void start(os::Handler* handler, hci::HciLayer* hci_layer, hci::Controller* controller, + hci::AclManager* acl_manager) { module_handler_ = handler; hci_layer_ = hci_layer; controller_ = controller; @@ -154,11 +154,11 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb le_address_manager_ = acl_manager->GetLeAddressManager(); num_instances_ = controller_->GetLeNumberOfSupportedAdverisingSets(); - le_advertising_interface_ = - hci_layer_->GetLeAdvertisingInterface(module_handler_->BindOn(this, &LeAdvertisingManager::impl::handle_event)); + le_advertising_interface_ = hci_layer_->GetLeAdvertisingInterface( + module_handler_->BindOn(this, &LeAdvertisingManager::impl::handle_event)); hci_layer_->RegisterVendorSpecificEventHandler( - hci::VseSubeventCode::BLE_STCHANGE, - handler->BindOn(this, &LeAdvertisingManager::impl::multi_advertising_state_change)); + hci::VseSubeventCode::BLE_STCHANGE, + handler->BindOn(this, &LeAdvertisingManager::impl::multi_advertising_state_change)); if (controller_->SupportsBleExtendedAdvertising()) { advertising_api_type_ = AdvertisingApiType::EXTENDED; @@ -172,13 +172,13 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb int vendor_version = os::GetAndroidVendorReleaseVersion(); if (vendor_version != 0 && vendor_version <= 11 && os::IsRootCanalEnabled()) { log::info( - "LeReadAdvertisingPhysicalChannelTxPower is not supported on Android R RootCanal, " - "default to 0"); + "LeReadAdvertisingPhysicalChannelTxPower is not supported on Android R RootCanal, " + "default to 0"); le_physical_channel_tx_power_ = 0; } else { hci_layer_->EnqueueCommand( - LeReadAdvertisingPhysicalChannelTxPowerBuilder::Create(), - handler->BindOnceOn(this, &impl::on_read_advertising_physical_channel_tx_power)); + LeReadAdvertisingPhysicalChannelTxPowerBuilder::Create(), + handler->BindOnceOn(this, &impl::on_read_advertising_physical_channel_tx_power)); } } enabled_sets_ = std::vector(num_instances_); @@ -221,23 +221,16 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb return calibrated_tx_power; } - size_t GetNumberOfAdvertisingInstances() const { - return num_instances_; - } + size_t GetNumberOfAdvertisingInstances() const { return num_instances_; } size_t GetNumberOfAdvertisingInstancesInUse() const { - return std::count_if(advertising_sets_.begin(), advertising_sets_.end(), [](const auto& set) { - return set.second.in_use; - }); + return std::count_if(advertising_sets_.begin(), advertising_sets_.end(), + [](const auto& set) { return set.second.in_use; }); } - int get_advertiser_reg_id(AdvertiserId advertiser_id) { - return id_map_[advertiser_id]; - } + int get_advertiser_reg_id(AdvertiserId advertiser_id) { return id_map_[advertiser_id]; } - AdvertisingApiType get_advertising_api_type() const { - return advertising_api_type_; - } + AdvertisingApiType get_advertising_api_type() const { return advertising_api_type_; } void register_advertising_callback(AdvertisingCallback* advertising_callback) { advertising_callbacks_ = advertising_callback; @@ -249,20 +242,15 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb auto advertiser_id = view.GetAdvertisingInstance(); - log::info( - "Instance: 0x{:x} StateChangeReason: {} Handle: 0x{:x} Address: {}", - advertiser_id, - VseStateChangeReasonText(view.GetStateChangeReason()), - view.GetConnectionHandle(), - advertising_sets_[view.GetAdvertisingInstance()].current_address.ToString()); + log::info("Instance: 0x{:x} StateChangeReason: {} Handle: 0x{:x} Address: {}", advertiser_id, + VseStateChangeReasonText(view.GetStateChangeReason()), view.GetConnectionHandle(), + advertising_sets_[view.GetAdvertisingInstance()].current_address.ToString()); if (view.GetStateChangeReason() == VseStateChangeReason::CONNECTION_RECEIVED) { - acl_manager_->OnAdvertisingSetTerminated( - ErrorCode::SUCCESS, - view.GetConnectionHandle(), - advertiser_id, - advertising_sets_[advertiser_id].current_address, - advertising_sets_[advertiser_id].discoverable); + acl_manager_->OnAdvertisingSetTerminated(ErrorCode::SUCCESS, view.GetConnectionHandle(), + advertiser_id, + advertising_sets_[advertiser_id].current_address, + advertising_sets_[advertiser_id].discoverable); enabled_sets_[advertiser_id].advertising_handle_ = kInvalidHandle; @@ -292,8 +280,8 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb log::info("Dropping invalid scan request event"); return; } - registered_handler_->Post( - common::BindOnce(scan_callback_, event_view.GetScannerAddress(), event_view.GetScannerAddressType())); + registered_handler_->Post(common::BindOnce(scan_callback_, event_view.GetScannerAddress(), + event_view.GetScannerAddressType())); } void handle_set_terminated(LeAdvertisingSetTerminatedView event_view) { @@ -324,15 +312,12 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb } enabled_sets_[advertiser_id].advertising_handle_ = kInvalidHandle; - AddressWithType advertiser_address = advertising_sets_[event_view.GetAdvertisingHandle()].current_address; + AddressWithType advertiser_address = + advertising_sets_[event_view.GetAdvertisingHandle()].current_address; bool is_discoverable = advertising_sets_[event_view.GetAdvertisingHandle()].discoverable; - acl_manager_->OnAdvertisingSetTerminated( - status, - event_view.GetConnectionHandle(), - advertiser_id, - advertiser_address, - is_discoverable); + acl_manager_->OnAdvertisingSetTerminated(status, event_view.GetConnectionHandle(), + advertiser_id, advertiser_address, is_discoverable); if (status == ErrorCode::LIMIT_REACHED || status == ErrorCode::ADVERTISING_TIMEOUT) { if (id_map_[advertiser_id] == kIdLocal) { @@ -358,11 +343,12 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb advertising_sets_[advertiser_id].max_extended_advertising_events == 0) { log::info("Reenable advertising"); if (was_rotating_address) { - advertising_sets_[advertiser_id].address_rotation_alarm = std::make_unique(module_handler_); + advertising_sets_[advertiser_id].address_rotation_alarm = + std::make_unique(module_handler_); advertising_sets_[advertiser_id].address_rotation_alarm->Schedule( - common::BindOnce( - &impl::set_advertising_set_random_address_on_timer, common::Unretained(this), advertiser_id), - le_address_manager_->GetNextPrivateAddressIntervalMs()); + common::BindOnce(&impl::set_advertising_set_random_address_on_timer, + common::Unretained(this), advertiser_id), + le_address_manager_->GetNextPrivateAddressIntervalMs()); } enable_advertiser(advertiser_id, true, 0, 0); } @@ -391,8 +377,8 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb } if (advertising_api_type_ == AdvertisingApiType::EXTENDED) { le_advertising_interface_->EnqueueCommand( - hci::LeRemoveAdvertisingSetBuilder::Create(advertiser_id), - module_handler_->BindOnce(check_complete)); + hci::LeRemoveAdvertisingSetBuilder::Create(advertiser_id), + module_handler_->BindOnce(check_complete)); if (advertising_sets_[advertiser_id].address_rotation_alarm != nullptr) { advertising_sets_[advertiser_id].address_rotation_alarm->Cancel(); @@ -432,11 +418,10 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb } void create_advertiser( - int reg_id, - const AdvertisingConfig config, - common::Callback scan_callback, - common::Callback set_terminated_callback, - os::Handler* handler) { + int reg_id, const AdvertisingConfig config, + common::Callback scan_callback, + common::Callback set_terminated_callback, + os::Handler* handler) { AdvertiserId id = allocate_advertiser(); if (id == kInvalidId) { log::warn("Number of max instances reached"); @@ -448,17 +433,16 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb } void create_advertiser_with_id( - int reg_id, - AdvertiserId id, - const AdvertisingConfig config, - common::Callback scan_callback, - common::Callback set_terminated_callback, - os::Handler* handler) { + int reg_id, AdvertiserId id, const AdvertisingConfig config, + common::Callback scan_callback, + common::Callback set_terminated_callback, + os::Handler* handler) { // check advertising data is valid before start advertising if (!check_advertising_data(config.advertisement, config.connectable && config.discoverable) || !check_advertising_data(config.scan_response, false)) { advertising_callbacks_->OnAdvertisingSetStarted( - reg_id, id, le_physical_channel_tx_power_, AdvertisingCallback::AdvertisingStatus::DATA_TOO_LARGE); + reg_id, id, le_physical_channel_tx_power_, + AdvertisingCallback::AdvertisingStatus::DATA_TOO_LARGE); return; } @@ -474,10 +458,10 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb if (com::android::bluetooth::flags::nrpa_non_connectable_adv() && !config.connectable) { advertising_sets_[id].address_type = GetAdvertiserAddressTypeNonConnectable( - config.requested_advertiser_address_type, le_address_manager_->GetAddressPolicy()); + config.requested_advertiser_address_type, le_address_manager_->GetAddressPolicy()); } else { advertising_sets_[id].address_type = GetAdvertiserAddressTypeFromRequestedTypeAndPolicy( - config.requested_advertiser_address_type, le_address_manager_->GetAddressPolicy()); + config.requested_advertiser_address_type, le_address_manager_->GetAddressPolicy()); } advertising_sets_[id].current_address = new_advertiser_address(id); set_parameters(id, config); @@ -503,9 +487,9 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb set_data(id, false, config.advertisement); if (advertising_sets_[id].address_type != AdvertiserAddressType::PUBLIC) { le_advertising_interface_->EnqueueCommand( - hci::LeMultiAdvtSetRandomAddrBuilder::Create( - advertising_sets_[id].current_address.GetAddress(), id), - module_handler_->BindOnce(check_complete)); + hci::LeMultiAdvtSetRandomAddrBuilder::Create( + advertising_sets_[id].current_address.GetAddress(), id), + module_handler_->BindOnce(check_complete)); } if (!paused) { enable_advertiser(id, true, 0, 0); @@ -520,81 +504,56 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb } void start_advertising( - AdvertiserId id, - const AdvertisingConfig config, - uint16_t duration, - base::OnceCallback status_callback, - base::OnceCallback timeout_callback, - const common::Callback scan_callback, - const common::Callback set_terminated_callback, - os::Handler* handler) { + AdvertiserId id, const AdvertisingConfig config, uint16_t duration, + base::OnceCallback status_callback, + base::OnceCallback timeout_callback, + const common::Callback scan_callback, + const common::Callback set_terminated_callback, + os::Handler* handler) { advertising_sets_[id].status_callback = std::move(status_callback); advertising_sets_[id].timeout_callback = std::move(timeout_callback); // legacy start_advertising use default jni client id - create_extended_advertiser_with_id( - kAdvertiserClientIdJni, - kIdLocal, - id, - config, - scan_callback, - set_terminated_callback, - duration, - 0, - handler); + create_extended_advertiser_with_id(kAdvertiserClientIdJni, kIdLocal, id, config, scan_callback, + set_terminated_callback, duration, 0, handler); } void create_extended_advertiser( - uint8_t client_id, - int reg_id, - const AdvertisingConfig config, - common::Callback scan_callback, - common::Callback set_terminated_callback, - uint16_t duration, - uint8_t max_ext_adv_events, - os::Handler* handler) { + uint8_t client_id, int reg_id, const AdvertisingConfig config, + common::Callback scan_callback, + common::Callback set_terminated_callback, + uint16_t duration, uint8_t max_ext_adv_events, os::Handler* handler) { AdvertiserId id = allocate_advertiser(); if (id == kInvalidId) { log::warn("Number of max instances reached"); start_advertising_fail(reg_id, AdvertisingCallback::AdvertisingStatus::TOO_MANY_ADVERTISERS); return; } - create_extended_advertiser_with_id( - client_id, - reg_id, - id, - config, - scan_callback, - set_terminated_callback, - duration, - max_ext_adv_events, - handler); + create_extended_advertiser_with_id(client_id, reg_id, id, config, scan_callback, + set_terminated_callback, duration, max_ext_adv_events, + handler); } void create_extended_advertiser_with_id( - uint8_t client_id, - int reg_id, - AdvertiserId id, - const AdvertisingConfig config, - common::Callback scan_callback, - common::Callback set_terminated_callback, - uint16_t duration, - uint8_t max_ext_adv_events, - os::Handler* handler) { + uint8_t client_id, int reg_id, AdvertiserId id, const AdvertisingConfig config, + common::Callback scan_callback, + common::Callback set_terminated_callback, + uint16_t duration, uint8_t max_ext_adv_events, os::Handler* handler) { id_map_[id] = reg_id; if (advertising_api_type_ != AdvertisingApiType::EXTENDED) { - create_advertiser_with_id( - reg_id, id, config, scan_callback, set_terminated_callback, handler); + create_advertiser_with_id(reg_id, id, config, scan_callback, set_terminated_callback, + handler); return; } // check extended advertising data is valid before start advertising - if (!check_extended_advertising_data( - config.advertisement, config.connectable && config.discoverable) || + if (!check_extended_advertising_data(config.advertisement, + config.connectable && config.discoverable) || !check_extended_advertising_data(config.scan_response, false)) { advertising_callbacks_->OnAdvertisingSetStarted( - reg_id, id, le_physical_channel_tx_power_, AdvertisingCallback::AdvertisingStatus::DATA_TOO_LARGE); + reg_id, id, le_physical_channel_tx_power_, + AdvertisingCallback::AdvertisingStatus::DATA_TOO_LARGE); return; } @@ -610,10 +569,10 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb advertising_sets_[id].handler = handler; if (com::android::bluetooth::flags::nrpa_non_connectable_adv() && !config.connectable) { advertising_sets_[id].address_type = GetAdvertiserAddressTypeNonConnectable( - config.requested_advertiser_address_type, le_address_manager_->GetAddressPolicy()); + config.requested_advertiser_address_type, le_address_manager_->GetAddressPolicy()); } else { advertising_sets_[id].address_type = GetAdvertiserAddressTypeFromRequestedTypeAndPolicy( - config.requested_advertiser_address_type, le_address_manager_->GetAddressPolicy()); + config.requested_advertiser_address_type, le_address_manager_->GetAddressPolicy()); } advertising_sets_[id].current_address = new_advertiser_address(id); @@ -624,21 +583,18 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb // if we aren't using the public address type at the HCI level, we need to set the random // address le_advertising_interface_->EnqueueCommand( - hci::LeSetAdvertisingSetRandomAddressBuilder::Create( - id, advertising_sets_[id].current_address.GetAddress()), - module_handler_->BindOnceOn( - this, - &impl::on_set_advertising_set_random_address_complete< - LeSetAdvertisingSetRandomAddressCompleteView>, - id, - advertising_sets_[id].current_address)); + hci::LeSetAdvertisingSetRandomAddressBuilder::Create( + id, advertising_sets_[id].current_address.GetAddress()), + module_handler_->BindOnceOn(this, + &impl::on_set_advertising_set_random_address_complete< + LeSetAdvertisingSetRandomAddressCompleteView>, + id, advertising_sets_[id].current_address)); bool leaudio_requested_nrpa = false; if (client_id == kAdvertiserClientIdLeAudio && advertising_sets_[id].address_type == AdvertiserAddressType::NONRESOLVABLE_RANDOM) { - log::info( - "Advertiser started by le audio client with address type: {}", - advertising_sets_[id].address_type); + log::info("Advertiser started by le audio client with address type: {}", + advertising_sets_[id].address_type); leaudio_requested_nrpa = true; } @@ -649,9 +605,9 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb // start timer for random address advertising_sets_[id].address_rotation_alarm = std::make_unique(module_handler_); advertising_sets_[id].address_rotation_alarm->Schedule( - common::BindOnce( - &impl::set_advertising_set_random_address_on_timer, common::Unretained(this), id), - le_address_manager_->GetNextPrivateAddressIntervalMs()); + common::BindOnce(&impl::set_advertising_set_random_address_on_timer, + common::Unretained(this), id), + le_address_manager_->GetNextPrivateAddressIntervalMs()); } } if (config.advertising_type == AdvertisingType::ADV_IND || @@ -663,8 +619,8 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb if (!config.periodic_data.empty()) { set_periodic_parameter(id, config.periodic_advertising_parameters); set_periodic_data(id, config.periodic_data); - enable_periodic_advertising( - id, config.periodic_advertising_parameters.enable, config.periodic_advertising_parameters.include_adi); + enable_periodic_advertising(id, config.periodic_advertising_parameters.enable, + config.periodic_advertising_parameters.include_adi); } if (!paused) { @@ -695,18 +651,20 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb switch (advertising_api_type_) { case (AdvertisingApiType::LEGACY): le_advertising_interface_->EnqueueCommand( - hci::LeSetAdvertisingEnableBuilder::Create(Enable::DISABLED), - module_handler_->BindOnce(check_complete)); + hci::LeSetAdvertisingEnableBuilder::Create(Enable::DISABLED), + module_handler_->BindOnce(check_complete)); break; case (AdvertisingApiType::ANDROID_HCI): le_advertising_interface_->EnqueueCommand( - hci::LeMultiAdvtSetEnableBuilder::Create(Enable::DISABLED, advertiser_id), - module_handler_->BindOnce(check_complete)); + hci::LeMultiAdvtSetEnableBuilder::Create(Enable::DISABLED, advertiser_id), + module_handler_->BindOnce(check_complete)); break; case (AdvertisingApiType::EXTENDED): { le_advertising_interface_->EnqueueCommand( - hci::LeSetExtendedAdvertisingEnableBuilder::Create(Enable::DISABLED, enabled_vector), - module_handler_->BindOnce(check_complete)); + hci::LeSetExtendedAdvertisingEnableBuilder::Create(Enable::DISABLED, + enabled_vector), + module_handler_->BindOnce( + check_complete)); bool is_periodic = advertising_iter->second.is_periodic; log::debug("advertiser_id: {} is_periodic: {}", advertiser_id, is_periodic); @@ -714,9 +672,9 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb // Only set periodic advertising if supported. if (is_periodic && controller_->SupportsBlePeriodicAdvertising()) { le_advertising_interface_->EnqueueCommand( - hci::LeSetPeriodicAdvertisingEnableBuilder::Create(false, false, advertiser_id), - module_handler_->BindOnce( - check_complete)); + hci::LeSetPeriodicAdvertisingEnableBuilder::Create(false, false, advertiser_id), + module_handler_->BindOnce( + check_complete)); } } break; } @@ -729,12 +687,12 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb if (advertising_api_type_ == AdvertisingApiType::EXTENDED) { AddressWithType address_with_type = new_advertiser_address(advertiser_id); le_advertising_interface_->EnqueueCommand( - hci::LeSetAdvertisingSetRandomAddressBuilder::Create(advertiser_id, address_with_type.GetAddress()), - module_handler_->BindOnceOn( - this, - &impl::on_set_advertising_set_random_address_complete, - advertiser_id, - address_with_type)); + hci::LeSetAdvertisingSetRandomAddressBuilder::Create(advertiser_id, + address_with_type.GetAddress()), + module_handler_->BindOnceOn(this, + &impl::on_set_advertising_set_random_address_complete< + LeSetAdvertisingSetRandomAddressCompleteView>, + advertiser_id, address_with_type)); } } @@ -752,14 +710,16 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb EnabledSet curr_set; curr_set.advertising_handle_ = advertiser_id; curr_set.duration_ = advertising_sets_[advertiser_id].duration; - curr_set.max_extended_advertising_events_ = advertising_sets_[advertiser_id].max_extended_advertising_events; + curr_set.max_extended_advertising_events_ = + advertising_sets_[advertiser_id].max_extended_advertising_events; std::vector enabled_sets = {curr_set}; // For connectable advertising, we should disable it first if (advertising_sets_[advertiser_id].connectable) { le_advertising_interface_->EnqueueCommand( - hci::LeSetExtendedAdvertisingEnableBuilder::Create(Enable::DISABLED, enabled_sets), - module_handler_->BindOnce(check_complete)); + hci::LeSetExtendedAdvertisingEnableBuilder::Create(Enable::DISABLED, enabled_sets), + module_handler_->BindOnce( + check_complete)); } rotate_advertiser_address(advertiser_id); @@ -770,17 +730,20 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb // analogous check. if (advertising_sets_[advertiser_id].connectable && !paused) { le_advertising_interface_->EnqueueCommand( - hci::LeSetExtendedAdvertisingEnableBuilder::Create(Enable::ENABLED, enabled_sets), - module_handler_->BindOnce(check_complete)); + hci::LeSetExtendedAdvertisingEnableBuilder::Create(Enable::ENABLED, enabled_sets), + module_handler_->BindOnce( + check_complete)); } advertising_sets_[advertiser_id].address_rotation_alarm->Schedule( - common::BindOnce(&impl::set_advertising_set_random_address_on_timer, common::Unretained(this), advertiser_id), - le_address_manager_->GetNextPrivateAddressIntervalMs()); + common::BindOnce(&impl::set_advertising_set_random_address_on_timer, + common::Unretained(this), advertiser_id), + le_address_manager_->GetNextPrivateAddressIntervalMs()); } void register_advertiser( - common::ContextualOnceCallback callback) { + common::ContextualOnceCallback + callback) { AdvertiserId id = allocate_advertiser(); if (id == kInvalidId) { callback(kInvalidId, AdvertisingCallback::AdvertisingStatus::TOO_MANY_ADVERTISERS); @@ -795,8 +758,9 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb return; } auto current_address = advertising_sets_[advertiser_id].current_address; - advertising_callbacks_->OnOwnAddressRead( - advertiser_id, static_cast(current_address.GetAddressType()), current_address.GetAddress()); + advertising_callbacks_->OnOwnAddressRead(advertiser_id, + static_cast(current_address.GetAddressType()), + current_address.GetAddress()); } void set_parameters(AdvertiserId advertiser_id, AdvertisingConfig config) { @@ -810,42 +774,30 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb // based on logic in new_advertiser_address auto own_address_type = static_cast( - advertising_sets_[advertiser_id].current_address.GetAddressType()); + advertising_sets_[advertiser_id].current_address.GetAddressType()); switch (advertising_api_type_) { case (AdvertisingApiType::LEGACY): { le_advertising_interface_->EnqueueCommand( - hci::LeSetAdvertisingParametersBuilder::Create( - config.interval_min, - config.interval_max, - config.advertising_type, - own_address_type, - config.peer_address_type, - config.peer_address, - config.channel_map, - config.filter_policy), - module_handler_->BindOnceOn( - this, - &impl::check_status_with_id, - true, - advertiser_id)); + hci::LeSetAdvertisingParametersBuilder::Create( + config.interval_min, config.interval_max, config.advertising_type, + own_address_type, config.peer_address_type, config.peer_address, + config.channel_map, config.filter_policy), + module_handler_->BindOnceOn( + this, &impl::check_status_with_id, + true, advertiser_id)); } break; case (AdvertisingApiType::ANDROID_HCI): { le_advertising_interface_->EnqueueCommand( - hci::LeMultiAdvtParamBuilder::Create( - config.interval_min, - config.interval_max, - config.advertising_type, - own_address_type, - advertising_sets_[advertiser_id].current_address.GetAddress(), - config.peer_address_type, - config.peer_address, - config.channel_map, - config.filter_policy, - advertiser_id, - config.tx_power), - module_handler_->BindOnceOn( - this, &impl::check_status_with_id, true, advertiser_id)); + hci::LeMultiAdvtParamBuilder::Create( + config.interval_min, config.interval_max, config.advertising_type, + own_address_type, + advertising_sets_[advertiser_id].current_address.GetAddress(), + config.peer_address_type, config.peer_address, config.channel_map, + config.filter_policy, advertiser_id, config.tx_power), + module_handler_->BindOnceOn(this, + &impl::check_status_with_id, + true, advertiser_id)); } break; case (AdvertisingApiType::EXTENDED): { // sid must be in range 0x00 to 0x0F. Since no controller supports more than @@ -853,7 +805,8 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb config.sid = advertiser_id % kAdvertisingSetIdMask; if (config.legacy_pdus) { - LegacyAdvertisingEventProperties legacy_properties = LegacyAdvertisingEventProperties::ADV_IND; + LegacyAdvertisingEventProperties legacy_properties = + LegacyAdvertisingEventProperties::ADV_IND; if (config.connectable && config.directed) { if (config.high_duty_directed_connectable) { legacy_properties = LegacyAdvertisingEventProperties::ADV_DIRECT_IND_HIGH; @@ -869,24 +822,16 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb } le_advertising_interface_->EnqueueCommand( - LeSetExtendedAdvertisingParametersLegacyBuilder::Create( - advertiser_id, - legacy_properties, - config.interval_min, - config.interval_max, - config.channel_map, - own_address_type, - config.peer_address_type, - config.peer_address, - config.filter_policy, - config.tx_power, - config.sid, - config.enable_scan_request_notifications), - module_handler_->BindOnceOn( - this, - &impl::on_set_extended_advertising_parameters_complete< - LeSetExtendedAdvertisingParametersCompleteView>, - advertiser_id)); + LeSetExtendedAdvertisingParametersLegacyBuilder::Create( + advertiser_id, legacy_properties, config.interval_min, + config.interval_max, config.channel_map, own_address_type, + config.peer_address_type, config.peer_address, config.filter_policy, + config.tx_power, config.sid, config.enable_scan_request_notifications), + module_handler_->BindOnceOn( + this, + &impl::on_set_extended_advertising_parameters_complete< + LeSetExtendedAdvertisingParametersCompleteView>, + advertiser_id)); } else { AdvertisingEventProperties extended_properties; extended_properties.connectable_ = config.connectable; @@ -898,27 +843,20 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb extended_properties.tx_power_ = config.include_tx_power; le_advertising_interface_->EnqueueCommand( - hci::LeSetExtendedAdvertisingParametersBuilder::Create( - advertiser_id, - extended_properties, - config.interval_min, - config.interval_max, - config.channel_map, - own_address_type, - config.peer_address_type, - config.peer_address, - config.filter_policy, - config.tx_power, - (config.use_le_coded_phy ? PrimaryPhyType::LE_CODED : PrimaryPhyType::LE_1M), - config.secondary_max_skip, - config.secondary_advertising_phy, - config.sid, - config.enable_scan_request_notifications), - module_handler_->BindOnceOn( - this, - &impl::on_set_extended_advertising_parameters_complete< - LeSetExtendedAdvertisingParametersCompleteView>, - advertiser_id)); + hci::LeSetExtendedAdvertisingParametersBuilder::Create( + advertiser_id, extended_properties, config.interval_min, + config.interval_max, config.channel_map, own_address_type, + config.peer_address_type, config.peer_address, config.filter_policy, + config.tx_power, + (config.use_le_coded_phy ? PrimaryPhyType::LE_CODED + : PrimaryPhyType::LE_1M), + config.secondary_max_skip, config.secondary_advertising_phy, config.sid, + config.enable_scan_request_notifications), + module_handler_->BindOnceOn( + this, + &impl::on_set_extended_advertising_parameters_complete< + LeSetExtendedAdvertisingParametersCompleteView>, + advertiser_id)); } } break; } @@ -948,14 +886,12 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb } if (data_len > le_maximum_advertising_data_length_) { - log::warn( - "advertising data len {} exceeds le_maximum_advertising_data_length_ {}", - data_len, - le_maximum_advertising_data_length_); + log::warn("advertising data len {} exceeds le_maximum_advertising_data_length_ {}", data_len, + le_maximum_advertising_data_length_); return false; } return true; - }; + } bool check_extended_advertising_data(std::vector data, bool include_flag) { uint16_t data_len = 0; @@ -976,14 +912,12 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb } if (data_len > le_maximum_advertising_data_length_) { - log::warn( - "advertising data len {} exceeds le_maximum_advertising_data_length_ {}", - data_len, - le_maximum_advertising_data_length_); + log::warn("advertising data len {} exceeds le_maximum_advertising_data_length_ {}", data_len, + le_maximum_advertising_data_length_); return false; } return true; - }; + } void set_data(AdvertiserId advertiser_id, bool set_scan_rsp, std::vector data) { // The Flags data type shall be included when any of the Flag bits are non-zero and the @@ -1008,13 +942,14 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb } } - if (advertising_api_type_ != AdvertisingApiType::EXTENDED && !check_advertising_data(data, false)) { + if (advertising_api_type_ != AdvertisingApiType::EXTENDED && + !check_advertising_data(data, false)) { if (set_scan_rsp) { advertising_callbacks_->OnScanResponseDataSet( - advertiser_id, AdvertisingCallback::AdvertisingStatus::DATA_TOO_LARGE); + advertiser_id, AdvertisingCallback::AdvertisingStatus::DATA_TOO_LARGE); } else { advertising_callbacks_->OnAdvertisingDataSet( - advertiser_id, AdvertisingCallback::AdvertisingStatus::DATA_TOO_LARGE); + advertiser_id, AdvertisingCallback::AdvertisingStatus::DATA_TOO_LARGE); } return; } @@ -1023,33 +958,31 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb case (AdvertisingApiType::LEGACY): { if (set_scan_rsp) { le_advertising_interface_->EnqueueCommand( - hci::LeSetScanResponseDataBuilder::Create(data), - module_handler_->BindOnceOn( - this, - &impl::check_status_with_id, - true, - advertiser_id)); + hci::LeSetScanResponseDataBuilder::Create(data), + module_handler_->BindOnceOn( + this, &impl::check_status_with_id, + true, advertiser_id)); } else { le_advertising_interface_->EnqueueCommand( - hci::LeSetAdvertisingDataBuilder::Create(data), - module_handler_->BindOnceOn( - this, - &impl::check_status_with_id, - true, - advertiser_id)); + hci::LeSetAdvertisingDataBuilder::Create(data), + module_handler_->BindOnceOn( + this, &impl::check_status_with_id, true, + advertiser_id)); } } break; case (AdvertisingApiType::ANDROID_HCI): { if (set_scan_rsp) { le_advertising_interface_->EnqueueCommand( - hci::LeMultiAdvtSetScanRespBuilder::Create(data, advertiser_id), - module_handler_->BindOnceOn( - this, &impl::check_status_with_id, true, advertiser_id)); + hci::LeMultiAdvtSetScanRespBuilder::Create(data, advertiser_id), + module_handler_->BindOnceOn(this, + &impl::check_status_with_id, + true, advertiser_id)); } else { le_advertising_interface_->EnqueueCommand( - hci::LeMultiAdvtSetDataBuilder::Create(data, advertiser_id), - module_handler_->BindOnceOn( - this, &impl::check_status_with_id, true, advertiser_id)); + hci::LeMultiAdvtSetDataBuilder::Create(data, advertiser_id), + module_handler_->BindOnceOn(this, + &impl::check_status_with_id, + true, advertiser_id)); } } break; case (AdvertisingApiType::EXTENDED): { @@ -1061,10 +994,10 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb if (advertising_callbacks_ != nullptr) { if (set_scan_rsp) { advertising_callbacks_->OnScanResponseDataSet( - advertiser_id, AdvertisingCallback::AdvertisingStatus::INTERNAL_ERROR); + advertiser_id, AdvertisingCallback::AdvertisingStatus::INTERNAL_ERROR); } else { advertising_callbacks_->OnAdvertisingDataSet( - advertiser_id, AdvertisingCallback::AdvertisingStatus::INTERNAL_ERROR); + advertiser_id, AdvertisingCallback::AdvertisingStatus::INTERNAL_ERROR); } } return; @@ -1073,20 +1006,20 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb } int maxDataLength = - (com::android::bluetooth::flags::ble_check_data_length_on_legacy_advertising() && - advertising_sets_[advertiser_id].is_legacy) - ? kLeMaximumLegacyAdvertisingDataLength - : le_maximum_advertising_data_length_; + (com::android::bluetooth::flags::ble_check_data_length_on_legacy_advertising() && + advertising_sets_[advertiser_id].is_legacy) + ? kLeMaximumLegacyAdvertisingDataLength + : le_maximum_advertising_data_length_; if (data_len > maxDataLength) { log::warn("advertising data len {} exceeds maxDataLength {}", data_len, maxDataLength); if (advertising_callbacks_ != nullptr) { if (set_scan_rsp) { advertising_callbacks_->OnScanResponseDataSet( - advertiser_id, AdvertisingCallback::AdvertisingStatus::DATA_TOO_LARGE); + advertiser_id, AdvertisingCallback::AdvertisingStatus::DATA_TOO_LARGE); } else { advertising_callbacks_->OnAdvertisingDataSet( - advertiser_id, AdvertisingCallback::AdvertisingStatus::DATA_TOO_LARGE); + advertiser_id, AdvertisingCallback::AdvertisingStatus::DATA_TOO_LARGE); } } return; @@ -1099,8 +1032,8 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb Operation operation = Operation::FIRST_FRAGMENT; std::vector> fragments; - packet::FragmentingInserter it( - kLeMaximumFragmentLength, std::back_insert_iterator(fragments)); + packet::FragmentingInserter it(kLeMaximumFragmentLength, + std::back_insert_iterator(fragments)); for (auto gap_data : data) { gap_data.Serialize(it); } @@ -1108,10 +1041,8 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb for (size_t i = 0; i < fragments.size(); i++) { send_data_fragment_with_raw_builder( - advertiser_id, - set_scan_rsp, - std::move(fragments[i]), - (i == fragments.size() - 1) ? Operation::LAST_FRAGMENT : operation); + advertiser_id, set_scan_rsp, std::move(fragments[i]), + (i == fragments.size() - 1) ? Operation::LAST_FRAGMENT : operation); operation = Operation::INTERMEDIATE_FRAGMENT; } } @@ -1119,66 +1050,53 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb } } - void send_data_fragment( - AdvertiserId advertiser_id, - bool set_scan_rsp, - std::vector data, - Operation operation) { + void send_data_fragment(AdvertiserId advertiser_id, bool set_scan_rsp, std::vector data, + Operation operation) { // For first and intermediate fragment, do not trigger advertising_callbacks_. - bool send_callback = - (operation == Operation::COMPLETE_ADVERTISEMENT || operation == Operation::LAST_FRAGMENT); + bool send_callback = (operation == Operation::COMPLETE_ADVERTISEMENT || + operation == Operation::LAST_FRAGMENT); if (set_scan_rsp) { le_advertising_interface_->EnqueueCommand( - hci::LeSetExtendedScanResponseDataBuilder::Create( - advertiser_id, operation, kFragment_preference, data), - module_handler_->BindOnceOn( - this, - &impl::check_status_with_id, - send_callback, - advertiser_id)); + hci::LeSetExtendedScanResponseDataBuilder::Create(advertiser_id, operation, + kFragment_preference, data), + module_handler_->BindOnceOn( + this, &impl::check_status_with_id, + send_callback, advertiser_id)); } else { le_advertising_interface_->EnqueueCommand( - hci::LeSetExtendedAdvertisingDataBuilder::Create( - advertiser_id, operation, kFragment_preference, data), - module_handler_->BindOnceOn( - this, - &impl::check_status_with_id, - send_callback, - advertiser_id)); + hci::LeSetExtendedAdvertisingDataBuilder::Create(advertiser_id, operation, + kFragment_preference, data), + module_handler_->BindOnceOn( + this, &impl::check_status_with_id, + send_callback, advertiser_id)); } } - void send_data_fragment_with_raw_builder( - AdvertiserId advertiser_id, - bool set_scan_rsp, - std::unique_ptr data, - Operation operation) { + void send_data_fragment_with_raw_builder(AdvertiserId advertiser_id, bool set_scan_rsp, + std::unique_ptr data, + Operation operation) { // For first and intermediate fragment, do not trigger advertising_callbacks_. - bool send_callback = - (operation == Operation::COMPLETE_ADVERTISEMENT || operation == Operation::LAST_FRAGMENT); + bool send_callback = (operation == Operation::COMPLETE_ADVERTISEMENT || + operation == Operation::LAST_FRAGMENT); if (set_scan_rsp) { le_advertising_interface_->EnqueueCommand( - hci::LeSetExtendedScanResponseDataRawBuilder::Create( - advertiser_id, operation, kFragment_preference, std::move(data)), - module_handler_->BindOnceOn( - this, - &impl::check_status_with_id, - send_callback, - advertiser_id)); + hci::LeSetExtendedScanResponseDataRawBuilder::Create( + advertiser_id, operation, kFragment_preference, std::move(data)), + module_handler_->BindOnceOn( + this, &impl::check_status_with_id, + send_callback, advertiser_id)); } else { le_advertising_interface_->EnqueueCommand( - hci::LeSetExtendedAdvertisingDataRawBuilder::Create( - advertiser_id, operation, kFragment_preference, std::move(data)), - module_handler_->BindOnceOn( - this, - &impl::check_status_with_id, - send_callback, - advertiser_id)); + hci::LeSetExtendedAdvertisingDataRawBuilder::Create( + advertiser_id, operation, kFragment_preference, std::move(data)), + module_handler_->BindOnceOn( + this, &impl::check_status_with_id, + send_callback, advertiser_id)); } } - void enable_advertiser( - AdvertiserId advertiser_id, bool enable, uint16_t duration, uint8_t max_extended_advertising_events) { + void enable_advertiser(AdvertiserId advertiser_id, bool enable, uint16_t duration, + uint8_t max_extended_advertising_events) { EnabledSet curr_set; curr_set.advertising_handle_ = advertiser_id; curr_set.duration_ = duration; @@ -1194,34 +1112,26 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb switch (advertising_api_type_) { case (AdvertisingApiType::LEGACY): { le_advertising_interface_->EnqueueCommand( - hci::LeSetAdvertisingEnableBuilder::Create(enable_value), - module_handler_->BindOnceOn( - this, - &impl::on_set_advertising_enable_complete, - enable, - enabled_sets, - true /* trigger callbacks */)); + hci::LeSetAdvertisingEnableBuilder::Create(enable_value), + module_handler_->BindOnceOn(this, + &impl::on_set_advertising_enable_complete< + LeSetAdvertisingEnableCompleteView>, + enable, enabled_sets, true /* trigger callbacks */)); } break; case (AdvertisingApiType::ANDROID_HCI): { le_advertising_interface_->EnqueueCommand( - hci::LeMultiAdvtSetEnableBuilder::Create(enable_value, advertiser_id), - module_handler_->BindOnceOn( - this, - &impl::on_set_advertising_enable_complete, - enable, - enabled_sets, - true /* trigger callbacks */)); + hci::LeMultiAdvtSetEnableBuilder::Create(enable_value, advertiser_id), + module_handler_->BindOnceOn( + this, &impl::on_set_advertising_enable_complete, + enable, enabled_sets, true /* trigger callbacks */)); } break; case (AdvertisingApiType::EXTENDED): { le_advertising_interface_->EnqueueCommand( - hci::LeSetExtendedAdvertisingEnableBuilder::Create(enable_value, enabled_sets), - module_handler_->BindOnceOn( - this, - &impl::on_set_extended_advertising_enable_complete< - LeSetExtendedAdvertisingEnableCompleteView>, - enable, - enabled_sets, - true /* trigger callbacks */)); + hci::LeSetExtendedAdvertisingEnableBuilder::Create(enable_value, enabled_sets), + module_handler_->BindOnceOn(this, + &impl::on_set_extended_advertising_enable_complete< + LeSetExtendedAdvertisingEnableCompleteView>, + enable, enabled_sets, true /* trigger callbacks */)); } break; } @@ -1230,11 +1140,12 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb if (advertising_api_type_ == AdvertisingApiType::EXTENDED) { enabled_sets_[advertiser_id].duration_ = duration; enabled_sets_[advertiser_id].max_extended_advertising_events_ = - max_extended_advertising_events; + max_extended_advertising_events; } advertising_sets_[advertiser_id].duration = duration; - advertising_sets_[advertiser_id].max_extended_advertising_events = max_extended_advertising_events; + advertising_sets_[advertiser_id].max_extended_advertising_events = + max_extended_advertising_events; } else { enabled_sets_[advertiser_id].advertising_handle_ = kInvalidHandle; if (advertising_sets_[advertiser_id].address_rotation_alarm != nullptr) { @@ -1244,22 +1155,19 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb } } - void set_periodic_parameter( - AdvertiserId advertiser_id, PeriodicAdvertisingParameters periodic_advertising_parameters) { + void set_periodic_parameter(AdvertiserId advertiser_id, + PeriodicAdvertisingParameters periodic_advertising_parameters) { uint8_t include_tx_power = periodic_advertising_parameters.properties >> PeriodicAdvertisingParameters::AdvertisingProperty::INCLUDE_TX_POWER; le_advertising_interface_->EnqueueCommand( - hci::LeSetPeriodicAdvertisingParametersBuilder::Create( - advertiser_id, - periodic_advertising_parameters.min_interval, - periodic_advertising_parameters.max_interval, - include_tx_power), - module_handler_->BindOnceOn( - this, - &impl::check_status_with_id, - true, - advertiser_id)); + hci::LeSetPeriodicAdvertisingParametersBuilder::Create( + advertiser_id, periodic_advertising_parameters.min_interval, + periodic_advertising_parameters.max_interval, include_tx_power), + module_handler_->BindOnceOn( + this, + &impl::check_status_with_id, + true, advertiser_id)); } void set_periodic_data(AdvertiserId advertiser_id, std::vector data) { @@ -1270,7 +1178,7 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb log::warn("AD data len shall not greater than {}", kLeMaximumGapDataLength); if (advertising_callbacks_ != nullptr) { advertising_callbacks_->OnPeriodicAdvertisingDataSet( - advertiser_id, AdvertisingCallback::AdvertisingStatus::INTERNAL_ERROR); + advertiser_id, AdvertisingCallback::AdvertisingStatus::INTERNAL_ERROR); } return; } @@ -1278,12 +1186,11 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb } if (data_len > le_maximum_advertising_data_length_) { - log::warn( - "advertising data len exceeds le_maximum_advertising_data_length_ {}", - le_maximum_advertising_data_length_); + log::warn("advertising data len exceeds le_maximum_advertising_data_length_ {}", + le_maximum_advertising_data_length_); if (advertising_callbacks_ != nullptr) { advertising_callbacks_->OnPeriodicAdvertisingDataSet( - advertiser_id, AdvertisingCallback::AdvertisingStatus::DATA_TOO_LARGE); + advertiser_id, AdvertisingCallback::AdvertisingStatus::DATA_TOO_LARGE); } return; } @@ -1295,8 +1202,8 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb Operation operation = Operation::FIRST_FRAGMENT; std::vector> fragments; - packet::FragmentingInserter it( - kLeMaximumPeriodicDataFragmentLength, std::back_insert_iterator(fragments)); + packet::FragmentingInserter it(kLeMaximumPeriodicDataFragmentLength, + std::back_insert_iterator(fragments)); for (auto gap_data : data) { gap_data.Serialize(it); } @@ -1304,41 +1211,37 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb for (size_t i = 0; i < fragments.size(); i++) { send_periodic_data_fragment_with_raw_builder( - advertiser_id, - std::move(fragments[i]), - (i == fragments.size() - 1) ? Operation::LAST_FRAGMENT : operation); + advertiser_id, std::move(fragments[i]), + (i == fragments.size() - 1) ? Operation::LAST_FRAGMENT : operation); operation = Operation::INTERMEDIATE_FRAGMENT; } } } - void send_periodic_data_fragment( - AdvertiserId advertiser_id, std::vector data, Operation operation) { + void send_periodic_data_fragment(AdvertiserId advertiser_id, std::vector data, + Operation operation) { // For first and intermediate fragment, do not trigger advertising_callbacks_. - bool send_callback = - (operation == Operation::COMPLETE_ADVERTISEMENT || operation == Operation::LAST_FRAGMENT); + bool send_callback = (operation == Operation::COMPLETE_ADVERTISEMENT || + operation == Operation::LAST_FRAGMENT); le_advertising_interface_->EnqueueCommand( - hci::LeSetPeriodicAdvertisingDataBuilder::Create(advertiser_id, operation, data), - module_handler_->BindOnceOn( - this, - &impl::check_status_with_id, - send_callback, - advertiser_id)); + hci::LeSetPeriodicAdvertisingDataBuilder::Create(advertiser_id, operation, data), + module_handler_->BindOnceOn( + this, &impl::check_status_with_id, + send_callback, advertiser_id)); } - void send_periodic_data_fragment_with_raw_builder( - AdvertiserId advertiser_id, std::unique_ptr data, Operation operation) { + void send_periodic_data_fragment_with_raw_builder(AdvertiserId advertiser_id, + std::unique_ptr data, + Operation operation) { // For first and intermediate fragment, do not trigger advertising_callbacks_. - bool send_callback = - (operation == Operation::COMPLETE_ADVERTISEMENT || operation == Operation::LAST_FRAGMENT); + bool send_callback = (operation == Operation::COMPLETE_ADVERTISEMENT || + operation == Operation::LAST_FRAGMENT); le_advertising_interface_->EnqueueCommand( - hci::LeSetPeriodicAdvertisingDataRawBuilder::Create( - advertiser_id, operation, std::move(data)), - module_handler_->BindOnceOn( - this, - &impl::check_status_with_id, - send_callback, - advertiser_id)); + hci::LeSetPeriodicAdvertisingDataRawBuilder::Create(advertiser_id, operation, + std::move(data)), + module_handler_->BindOnceOn( + this, &impl::check_status_with_id, + send_callback, advertiser_id)); } void enable_periodic_advertising(AdvertiserId advertiser_id, bool enable, bool include_adi) { @@ -1350,12 +1253,11 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb include_adi = false; } le_advertising_interface_->EnqueueCommand( - hci::LeSetPeriodicAdvertisingEnableBuilder::Create(enable, include_adi, advertiser_id), - module_handler_->BindOnceOn( - this, - &impl::on_set_periodic_advertising_enable_complete, - enable, - advertiser_id)); + hci::LeSetPeriodicAdvertisingEnableBuilder::Create(enable, include_adi, advertiser_id), + module_handler_->BindOnceOn(this, + &impl::on_set_periodic_advertising_enable_complete< + LeSetPeriodicAdvertisingEnableCompleteView>, + enable, advertiser_id)); } void OnPause() override { @@ -1376,25 +1278,26 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb switch (advertising_api_type_) { case (AdvertisingApiType::LEGACY): { le_advertising_interface_->EnqueueCommand( - hci::LeSetAdvertisingEnableBuilder::Create(Enable::DISABLED), - module_handler_->BindOnce(check_complete)); + hci::LeSetAdvertisingEnableBuilder::Create(Enable::DISABLED), + module_handler_->BindOnce(check_complete)); } break; case (AdvertisingApiType::ANDROID_HCI): { for (size_t i = 0; i < enabled_sets_.size(); i++) { uint8_t id = enabled_sets_[i].advertising_handle_; if (id != kInvalidHandle) { le_advertising_interface_->EnqueueCommand( - hci::LeMultiAdvtSetEnableBuilder::Create(Enable::DISABLED, id), - module_handler_->BindOnce(check_complete)); + hci::LeMultiAdvtSetEnableBuilder::Create(Enable::DISABLED, id), + module_handler_->BindOnce(check_complete)); } } } break; case (AdvertisingApiType::EXTENDED): { if (enabled_sets.size() != 0) { le_advertising_interface_->EnqueueCommand( - hci::LeSetExtendedAdvertisingEnableBuilder::Create(Enable::DISABLED, enabled_sets), - module_handler_->BindOnce( - check_complete)); + hci::LeSetExtendedAdvertisingEnableBuilder::Create(Enable::DISABLED, + enabled_sets), + module_handler_->BindOnce( + check_complete)); } } break; } @@ -1420,40 +1323,34 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb switch (advertising_api_type_) { case (AdvertisingApiType::LEGACY): { le_advertising_interface_->EnqueueCommand( - hci::LeSetAdvertisingEnableBuilder::Create(Enable::ENABLED), - module_handler_->BindOnceOn( - this, - &impl::on_set_advertising_enable_complete, - true, - enabled_sets, - false /* trigger_callbacks */)); + hci::LeSetAdvertisingEnableBuilder::Create(Enable::ENABLED), + module_handler_->BindOnceOn(this, + &impl::on_set_advertising_enable_complete< + LeSetAdvertisingEnableCompleteView>, + true, enabled_sets, false /* trigger_callbacks */)); } break; case (AdvertisingApiType::ANDROID_HCI): { for (size_t i = 0; i < enabled_sets_.size(); i++) { uint8_t id = enabled_sets_[i].advertising_handle_; if (id != kInvalidHandle) { le_advertising_interface_->EnqueueCommand( - hci::LeMultiAdvtSetEnableBuilder::Create(Enable::ENABLED, id), - module_handler_->BindOnceOn( - this, - &impl::on_set_advertising_enable_complete, - true, - enabled_sets, - false /* trigger_callbacks */)); + hci::LeMultiAdvtSetEnableBuilder::Create(Enable::ENABLED, id), + module_handler_->BindOnceOn( + this, + &impl::on_set_advertising_enable_complete, + true, enabled_sets, false /* trigger_callbacks */)); } } } break; case (AdvertisingApiType::EXTENDED): { if (enabled_sets.size() != 0) { le_advertising_interface_->EnqueueCommand( - hci::LeSetExtendedAdvertisingEnableBuilder::Create(Enable::ENABLED, enabled_sets), - module_handler_->BindOnceOn( - this, - &impl::on_set_extended_advertising_enable_complete< - LeSetExtendedAdvertisingEnableCompleteView>, - true, - enabled_sets, - false /* trigger_callbacks */)); + hci::LeSetExtendedAdvertisingEnableBuilder::Create(Enable::ENABLED, + enabled_sets), + module_handler_->BindOnceOn(this, + &impl::on_set_extended_advertising_enable_complete< + LeSetExtendedAdvertisingEnableCompleteView>, + true, enabled_sets, false /* trigger_callbacks */)); } } break; } @@ -1463,12 +1360,13 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb // Note: this needs to be synchronous (i.e. NOT on a handler) for two reasons: // 1. For parity with OnPause() and OnResume() - // 2. If we don't enqueue our HCI commands SYNCHRONOUSLY, then it is possible that we OnResume() in addressManager - // before our commands complete. So then our commands reach the HCI layer *after* the resume commands from address - // manager, which is racey (even if it might not matter). + // 2. If we don't enqueue our HCI commands SYNCHRONOUSLY, then it is possible that we OnResume() + // in addressManager before our commands complete. So then our commands reach the HCI layer + // *after* the resume commands from address manager, which is racey (even if it might not matter). // - // If you are a future developer making this asynchronous, you need to add some kind of ->AckIRKChange() method to the - // address manager so we can defer resumption to after this completes. + // If you are a future developer making this asynchronous, you need to add some kind of + // ->AckIRKChange() method to the address manager so we can defer resumption to after this + // completes. void NotifyOnIRKChange() override { for (size_t i = 0; i < enabled_sets_.size(); i++) { if (enabled_sets_[i].advertising_handle_ != kInvalidHandle) { @@ -1478,7 +1376,8 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb } common::Callback scan_callback_; - common::ContextualCallback set_terminated_callback_{}; + common::ContextualCallback + set_terminated_callback_{}; AdvertisingCallback* advertising_callbacks_ = nullptr; os::Handler* registered_handler_{nullptr}; Module* module_; @@ -1507,7 +1406,8 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb auto complete_view = LeReadAdvertisingPhysicalChannelTxPowerCompleteView::Create(view); if (!complete_view.IsValid()) { auto payload = view.GetPayload(); - if (payload.size() == 1 && payload[0] == static_cast(ErrorCode::UNKNOWN_HCI_COMMAND)) { + if (payload.size() == 1 && + payload[0] == static_cast(ErrorCode::UNKNOWN_HCI_COMMAND)) { log::info("Unknown command, not setting tx power"); return; } @@ -1521,15 +1421,13 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb } template - void on_set_advertising_enable_complete( - bool enable, - std::vector enabled_sets, - bool trigger_callbacks, - CommandCompleteView view) { + void on_set_advertising_enable_complete(bool enable, std::vector enabled_sets, + bool trigger_callbacks, CommandCompleteView view) { log::assert_that(view.IsValid(), "assert failed: view.IsValid()"); auto complete_view = View::Create(view); log::assert_that(complete_view.IsValid(), "assert failed: complete_view.IsValid()"); - AdvertisingCallback::AdvertisingStatus advertising_status = AdvertisingCallback::AdvertisingStatus::SUCCESS; + AdvertisingCallback::AdvertisingStatus advertising_status = + AdvertisingCallback::AdvertisingStatus::SUCCESS; if (complete_view.GetStatus() != ErrorCode::SUCCESS) { log::info("Got a command complete with status {}", ErrorCodeText(complete_view.GetStatus())); } @@ -1547,7 +1445,8 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb int reg_id = id_map_[id]; if (reg_id == kIdLocal) { if (!advertising_sets_[enabled_set.advertising_handle_].status_callback.is_null()) { - std::move(advertising_sets_[enabled_set.advertising_handle_].status_callback).Run(advertising_status); + std::move(advertising_sets_[enabled_set.advertising_handle_].status_callback) + .Run(advertising_status); advertising_sets_[enabled_set.advertising_handle_].status_callback.Reset(); } continue; @@ -1559,21 +1458,22 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb } } else { advertising_sets_[enabled_set.advertising_handle_].started = true; - advertising_callbacks_->OnAdvertisingSetStarted(reg_id, id, le_physical_channel_tx_power_, advertising_status); + advertising_callbacks_->OnAdvertisingSetStarted(reg_id, id, le_physical_channel_tx_power_, + advertising_status); } } } template - void on_set_extended_advertising_enable_complete( - bool enable, - std::vector enabled_sets, - bool trigger_callbacks, - CommandCompleteView view) { + void on_set_extended_advertising_enable_complete(bool enable, + std::vector enabled_sets, + bool trigger_callbacks, + CommandCompleteView view) { log::assert_that(view.IsValid(), "assert failed: view.IsValid()"); auto complete_view = LeSetExtendedAdvertisingEnableCompleteView::Create(view); log::assert_that(complete_view.IsValid(), "assert failed: complete_view.IsValid()"); - AdvertisingCallback::AdvertisingStatus advertising_status = AdvertisingCallback::AdvertisingStatus::SUCCESS; + AdvertisingCallback::AdvertisingStatus advertising_status = + AdvertisingCallback::AdvertisingStatus::SUCCESS; if (complete_view.GetStatus() != ErrorCode::SUCCESS) { log::info("Got a command complete with status {}", ErrorCodeText(complete_view.GetStatus())); advertising_status = AdvertisingCallback::AdvertisingStatus::INTERNAL_ERROR; @@ -1594,7 +1494,8 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb int reg_id = id_map_[id]; if (reg_id == kIdLocal) { if (!advertising_sets_[enabled_set.advertising_handle_].status_callback.is_null()) { - std::move(advertising_sets_[enabled_set.advertising_handle_].status_callback).Run(advertising_status); + std::move(advertising_sets_[enabled_set.advertising_handle_].status_callback) + .Run(advertising_status); advertising_sets_[enabled_set.advertising_handle_].status_callback.Reset(); } continue; @@ -1616,7 +1517,8 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb log::assert_that(view.IsValid(), "assert failed: view.IsValid()"); auto complete_view = LeSetExtendedAdvertisingParametersCompleteView::Create(view); log::assert_that(complete_view.IsValid(), "assert failed: complete_view.IsValid()"); - AdvertisingCallback::AdvertisingStatus advertising_status = AdvertisingCallback::AdvertisingStatus::SUCCESS; + AdvertisingCallback::AdvertisingStatus advertising_status = + AdvertisingCallback::AdvertisingStatus::SUCCESS; if (complete_view.GetStatus() != ErrorCode::SUCCESS) { log::info("Got a command complete with status {}", ErrorCodeText(complete_view.GetStatus())); advertising_status = AdvertisingCallback::AdvertisingStatus::INTERNAL_ERROR; @@ -1624,22 +1526,26 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb advertising_sets_[id].tx_power = complete_view.GetSelectedTxPower(); if (advertising_sets_[id].started && id_map_[id] != kIdLocal) { - advertising_callbacks_->OnAdvertisingParametersUpdated(id, advertising_sets_[id].tx_power, advertising_status); + advertising_callbacks_->OnAdvertisingParametersUpdated(id, advertising_sets_[id].tx_power, + advertising_status); } } template - void on_set_periodic_advertising_enable_complete(bool enable, AdvertiserId id, CommandCompleteView view) { + void on_set_periodic_advertising_enable_complete(bool enable, AdvertiserId id, + CommandCompleteView view) { log::assert_that(view.IsValid(), "assert failed: view.IsValid()"); auto complete_view = LeSetPeriodicAdvertisingEnableCompleteView::Create(view); log::assert_that(complete_view.IsValid(), "assert failed: complete_view.IsValid()"); - AdvertisingCallback::AdvertisingStatus advertising_status = AdvertisingCallback::AdvertisingStatus::SUCCESS; + AdvertisingCallback::AdvertisingStatus advertising_status = + AdvertisingCallback::AdvertisingStatus::SUCCESS; if (complete_view.GetStatus() != ErrorCode::SUCCESS) { log::info("Got a command complete with status {}", ErrorCodeText(complete_view.GetStatus())); advertising_status = AdvertisingCallback::AdvertisingStatus::INTERNAL_ERROR; } - if (advertising_callbacks_ == nullptr || !advertising_sets_[id].started || id_map_[id] == kIdLocal) { + if (advertising_callbacks_ == nullptr || !advertising_sets_[id].started || + id_map_[id] == kIdLocal) { return; } @@ -1647,18 +1553,17 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb } template - void on_set_advertising_set_random_address_complete( - AdvertiserId advertiser_id, AddressWithType address_with_type, CommandCompleteView view) { + void on_set_advertising_set_random_address_complete(AdvertiserId advertiser_id, + AddressWithType address_with_type, + CommandCompleteView view) { log::assert_that(view.IsValid(), "assert failed: view.IsValid()"); auto complete_view = LeSetAdvertisingSetRandomAddressCompleteView::Create(view); log::assert_that(complete_view.IsValid(), "assert failed: complete_view.IsValid()"); if (complete_view.GetStatus() != ErrorCode::SUCCESS) { log::error("Got a command complete with status {}", ErrorCodeText(complete_view.GetStatus())); } else { - log::info( - "update random address for advertising set {} : {}", - advertiser_id, - address_with_type.GetAddress()); + log::info("update random address for advertising set {} : {}", advertiser_id, + address_with_type.GetAddress()); advertising_sets_[advertiser_id].current_address = address_with_type; } } @@ -1669,12 +1574,11 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb auto status_view = View::Create(view); log::assert_that(status_view.IsValid(), "assert failed: status_view.IsValid()"); if (status_view.GetStatus() != ErrorCode::SUCCESS) { - log::info( - "Got a Command complete {}, status {}", - OpCodeText(view.GetCommandOpCode()), - ErrorCodeText(status_view.GetStatus())); + log::info("Got a Command complete {}, status {}", OpCodeText(view.GetCommandOpCode()), + ErrorCodeText(status_view.GetStatus())); } - AdvertisingCallback::AdvertisingStatus advertising_status = AdvertisingCallback::AdvertisingStatus::SUCCESS; + AdvertisingCallback::AdvertisingStatus advertising_status = + AdvertisingCallback::AdvertisingStatus::SUCCESS; if (status_view.GetStatus() != ErrorCode::SUCCESS) { log::info("Got a command complete with status {}", ErrorCodeText(status_view.GetStatus())); advertising_status = AdvertisingCallback::AdvertisingStatus::INTERNAL_ERROR; @@ -1682,7 +1586,8 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb // Do not trigger callback if the advertiser not stated yet, or the advertiser is not register // from Java layer - if (advertising_callbacks_ == nullptr || !advertising_sets_[id].started || id_map_[id] == kIdLocal) { + if (advertising_callbacks_ == nullptr || !advertising_sets_[id].started || + id_map_[id] == kIdLocal) { return; } @@ -1695,7 +1600,8 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb switch (opcode) { case OpCode::LE_SET_ADVERTISING_PARAMETERS: - advertising_callbacks_->OnAdvertisingParametersUpdated(id, le_physical_channel_tx_power_, advertising_status); + advertising_callbacks_->OnAdvertisingParametersUpdated(id, le_physical_channel_tx_power_, + advertising_status); break; case OpCode::LE_SET_ADVERTISING_DATA: case OpCode::LE_SET_EXTENDED_ADVERTISING_DATA: @@ -1718,7 +1624,7 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb switch (sub_opcode) { case SubOcf::SET_PARAM: advertising_callbacks_->OnAdvertisingParametersUpdated( - id, le_physical_channel_tx_power_, advertising_status); + id, le_physical_channel_tx_power_, advertising_status); break; case SubOcf::SET_DATA: advertising_callbacks_->OnAdvertisingDataSet(id, advertising_status); @@ -1736,16 +1642,13 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb } void start_advertising_fail(int reg_id, AdvertisingCallback::AdvertisingStatus status) { - log::assert_that( - status != AdvertisingCallback::AdvertisingStatus::SUCCESS, - "assert failed: status != AdvertisingCallback::AdvertisingStatus::SUCCESS"); + log::assert_that(status != AdvertisingCallback::AdvertisingStatus::SUCCESS, + "assert failed: status != AdvertisingCallback::AdvertisingStatus::SUCCESS"); advertising_callbacks_->OnAdvertisingSetStarted(reg_id, kInvalidId, 0, status); } }; -LeAdvertisingManager::LeAdvertisingManager() { - pimpl_ = std::make_unique(this); -} +LeAdvertisingManager::LeAdvertisingManager() { pimpl_ = std::make_unique(this); } void LeAdvertisingManager::ListDependencies(ModuleList* list) const { list->add(); @@ -1754,20 +1657,13 @@ void LeAdvertisingManager::ListDependencies(ModuleList* list) const { } void LeAdvertisingManager::Start() { - pimpl_->start( - GetHandler(), - GetDependency(), - GetDependency(), - GetDependency()); + pimpl_->start(GetHandler(), GetDependency(), GetDependency(), + GetDependency()); } -void LeAdvertisingManager::Stop() { - pimpl_.reset(); -} +void LeAdvertisingManager::Stop() { pimpl_.reset(); } -std::string LeAdvertisingManager::ToString() const { - return "Le Advertising Manager"; -} +std::string LeAdvertisingManager::ToString() const { return "Le Advertising Manager"; } size_t LeAdvertisingManager::GetNumberOfAdvertisingInstances() const { return pimpl_->GetNumberOfAdvertisingInstances(); @@ -1782,36 +1678,24 @@ int LeAdvertisingManager::GetAdvertiserRegId(AdvertiserId advertiser_id) { } void LeAdvertisingManager::ExtendedCreateAdvertiser( - uint8_t client_id, - int reg_id, - const AdvertisingConfig config, - common::Callback scan_callback, - common::Callback set_terminated_callback, - uint16_t duration, - uint8_t max_extended_advertising_events, - os::Handler* handler) { + uint8_t client_id, int reg_id, const AdvertisingConfig config, + common::Callback scan_callback, + common::Callback set_terminated_callback, + uint16_t duration, uint8_t max_extended_advertising_events, os::Handler* handler) { AdvertisingApiType advertising_api_type = pimpl_->get_advertising_api_type(); if (advertising_api_type != AdvertisingApiType::EXTENDED) { if (config.peer_address == Address::kEmpty) { if (config.advertising_type == hci::AdvertisingType::ADV_DIRECT_IND_HIGH || config.advertising_type == hci::AdvertisingType::ADV_DIRECT_IND_LOW) { log::warn("Peer address can not be empty for directed advertising"); - CallOn( - pimpl_.get(), - &impl::start_advertising_fail, - reg_id, - AdvertisingCallback::AdvertisingStatus::INTERNAL_ERROR); + CallOn(pimpl_.get(), &impl::start_advertising_fail, reg_id, + AdvertisingCallback::AdvertisingStatus::INTERNAL_ERROR); return; } } - GetHandler()->Post(common::BindOnce( - &impl::create_advertiser, - common::Unretained(pimpl_.get()), - reg_id, - config, - scan_callback, - set_terminated_callback, - handler)); + GetHandler()->Post(common::BindOnce(&impl::create_advertiser, common::Unretained(pimpl_.get()), + reg_id, config, scan_callback, set_terminated_callback, + handler)); return; }; @@ -1819,74 +1703,58 @@ void LeAdvertisingManager::ExtendedCreateAdvertiser( if (config.directed) { if (config.peer_address == Address::kEmpty) { log::info("Peer address can not be empty for directed advertising"); - CallOn( - pimpl_.get(), &impl::start_advertising_fail, reg_id, AdvertisingCallback::AdvertisingStatus::INTERNAL_ERROR); + CallOn(pimpl_.get(), &impl::start_advertising_fail, reg_id, + AdvertisingCallback::AdvertisingStatus::INTERNAL_ERROR); return; } } if (config.channel_map == 0) { log::info("At least one channel must be set in the map"); - CallOn(pimpl_.get(), &impl::start_advertising_fail, reg_id, AdvertisingCallback::AdvertisingStatus::INTERNAL_ERROR); + CallOn(pimpl_.get(), &impl::start_advertising_fail, reg_id, + AdvertisingCallback::AdvertisingStatus::INTERNAL_ERROR); return; } if (!config.legacy_pdus) { if (config.connectable && config.scannable) { log::info("Extended advertising PDUs can not be connectable and scannable"); - CallOn( - pimpl_.get(), &impl::start_advertising_fail, reg_id, AdvertisingCallback::AdvertisingStatus::INTERNAL_ERROR); + CallOn(pimpl_.get(), &impl::start_advertising_fail, reg_id, + AdvertisingCallback::AdvertisingStatus::INTERNAL_ERROR); return; } if (config.high_duty_directed_connectable) { log::info("Extended advertising PDUs can not be high duty cycle"); - CallOn( - pimpl_.get(), &impl::start_advertising_fail, reg_id, AdvertisingCallback::AdvertisingStatus::INTERNAL_ERROR); + CallOn(pimpl_.get(), &impl::start_advertising_fail, reg_id, + AdvertisingCallback::AdvertisingStatus::INTERNAL_ERROR); return; } } if (config.interval_min > config.interval_max) { - log::info( - "Advertising interval: min ({}) > max ({})", config.interval_min, config.interval_max); - CallOn(pimpl_.get(), &impl::start_advertising_fail, reg_id, AdvertisingCallback::AdvertisingStatus::INTERNAL_ERROR); + log::info("Advertising interval: min ({}) > max ({})", config.interval_min, + config.interval_max); + CallOn(pimpl_.get(), &impl::start_advertising_fail, reg_id, + AdvertisingCallback::AdvertisingStatus::INTERNAL_ERROR); return; } - CallOn( - pimpl_.get(), - &impl::create_extended_advertiser, - client_id, - reg_id, - config, - scan_callback, - set_terminated_callback, - duration, - max_extended_advertising_events, - handler); + CallOn(pimpl_.get(), &impl::create_extended_advertiser, client_id, reg_id, config, scan_callback, + set_terminated_callback, duration, max_extended_advertising_events, handler); return; } void LeAdvertisingManager::StartAdvertising( - AdvertiserId advertiser_id, - const AdvertisingConfig config, - uint16_t duration, - base::OnceCallback status_callback, - base::OnceCallback timeout_callback, - common::Callback scan_callback, - common::Callback set_terminated_callback, - os::Handler* handler) { - CallOn( - pimpl_.get(), - &impl::start_advertising, - advertiser_id, - config, - duration, - std::move(status_callback), - std::move(timeout_callback), - scan_callback, - set_terminated_callback, - handler); + AdvertiserId advertiser_id, const AdvertisingConfig config, uint16_t duration, + base::OnceCallback status_callback, + base::OnceCallback timeout_callback, + common::Callback scan_callback, + common::Callback set_terminated_callback, + os::Handler* handler) { + CallOn(pimpl_.get(), &impl::start_advertising, advertiser_id, config, duration, + std::move(status_callback), std::move(timeout_callback), scan_callback, + set_terminated_callback, handler); } void LeAdvertisingManager::RegisterAdvertiser( - common::ContextualOnceCallback callback) { + common::ContextualOnceCallback + callback) { CallOn(pimpl_.get(), &impl::register_advertiser, std::move(callback)); } @@ -1898,25 +1766,30 @@ void LeAdvertisingManager::SetParameters(AdvertiserId advertiser_id, Advertising CallOn(pimpl_.get(), &impl::set_parameters, advertiser_id, config); } -void LeAdvertisingManager::SetData(AdvertiserId advertiser_id, bool set_scan_rsp, std::vector data) { +void LeAdvertisingManager::SetData(AdvertiserId advertiser_id, bool set_scan_rsp, + std::vector data) { CallOn(pimpl_.get(), &impl::set_data, advertiser_id, set_scan_rsp, data); } -void LeAdvertisingManager::EnableAdvertiser( - AdvertiserId advertiser_id, bool enable, uint16_t duration, uint8_t max_extended_advertising_events) { - CallOn(pimpl_.get(), &impl::enable_advertiser, advertiser_id, enable, duration, max_extended_advertising_events); +void LeAdvertisingManager::EnableAdvertiser(AdvertiserId advertiser_id, bool enable, + uint16_t duration, + uint8_t max_extended_advertising_events) { + CallOn(pimpl_.get(), &impl::enable_advertiser, advertiser_id, enable, duration, + max_extended_advertising_events); } void LeAdvertisingManager::SetPeriodicParameters( - AdvertiserId advertiser_id, PeriodicAdvertisingParameters periodic_advertising_parameters) { - CallOn(pimpl_.get(), &impl::set_periodic_parameter, advertiser_id, periodic_advertising_parameters); + AdvertiserId advertiser_id, PeriodicAdvertisingParameters periodic_advertising_parameters) { + CallOn(pimpl_.get(), &impl::set_periodic_parameter, advertiser_id, + periodic_advertising_parameters); } void LeAdvertisingManager::SetPeriodicData(AdvertiserId advertiser_id, std::vector data) { CallOn(pimpl_.get(), &impl::set_periodic_data, advertiser_id, data); } -void LeAdvertisingManager::EnablePeriodicAdvertising(AdvertiserId advertiser_id, bool enable, bool include_adi) { +void LeAdvertisingManager::EnablePeriodicAdvertising(AdvertiserId advertiser_id, bool enable, + bool include_adi) { CallOn(pimpl_.get(), &impl::enable_periodic_advertising, advertiser_id, enable, include_adi); } diff --git a/system/gd/hci/le_advertising_manager.h b/system/gd/hci/le_advertising_manager.h index 3f465ac6049..bffa6a9ee80 100644 --- a/system/gd/hci/le_advertising_manager.h +++ b/system/gd/hci/le_advertising_manager.h @@ -28,7 +28,7 @@ namespace bluetooth { namespace hci { class PeriodicAdvertisingParameters { - public: +public: bool enable; bool include_adi; uint16_t min_interval; @@ -44,7 +44,7 @@ enum class AdvertiserAddressType { }; class AdvertisingConfig { - public: +public: std::vector advertisement; std::vector scan_response; uint16_t interval_min; @@ -65,7 +65,8 @@ class AdvertisingConfig { bool anonymous = false; bool include_tx_power = false; bool use_le_coded_phy; // Primary advertisement PHY is LE Coded - uint8_t secondary_max_skip; // maximum advertising events to be skipped, 0x0 send AUX_ADV_IND prior ot the next event + uint8_t secondary_max_skip; // maximum advertising events to be skipped, 0x0 send AUX_ADV_IND + // prior ot the next event SecondaryPhyType secondary_advertising_phy; uint8_t sid = 0x00; Enable enable_scan_request_notifications = Enable::DISABLED; @@ -77,36 +78,36 @@ class AdvertisingConfig { using AdvertiserId = uint8_t; class AdvertisingCallback { - public: - enum AdvertisingStatus { - SUCCESS, - DATA_TOO_LARGE, - TOO_MANY_ADVERTISERS, - ALREADY_STARTED, - INTERNAL_ERROR, - FEATURE_UNSUPPORTED, - TIMEOUT - }; - - virtual ~AdvertisingCallback() = default; - virtual void OnAdvertisingSetStarted(int reg_id, uint8_t advertiser_id, int8_t tx_power, - AdvertisingStatus status) = 0; - virtual void OnAdvertisingEnabled(uint8_t advertiser_id, bool enable, - AdvertisingStatus status) = 0; - virtual void OnAdvertisingDataSet(uint8_t advertiser_id, AdvertisingStatus status) = 0; - virtual void OnScanResponseDataSet(uint8_t advertiser_id, AdvertisingStatus status) = 0; - virtual void OnAdvertisingParametersUpdated(uint8_t advertiser_id, int8_t tx_power, - AdvertisingStatus status) = 0; - virtual void OnPeriodicAdvertisingParametersUpdated(uint8_t advertiser_id, - AdvertisingStatus status) = 0; - virtual void OnPeriodicAdvertisingDataSet(uint8_t advertiser_id, AdvertisingStatus status) = 0; - virtual void OnPeriodicAdvertisingEnabled(uint8_t advertiser_id, bool enable, - AdvertisingStatus status) = 0; - virtual void OnOwnAddressRead(uint8_t advertiser_id, uint8_t address_type, Address address) = 0; +public: + enum AdvertisingStatus { + SUCCESS, + DATA_TOO_LARGE, + TOO_MANY_ADVERTISERS, + ALREADY_STARTED, + INTERNAL_ERROR, + FEATURE_UNSUPPORTED, + TIMEOUT + }; + + virtual ~AdvertisingCallback() = default; + virtual void OnAdvertisingSetStarted(int reg_id, uint8_t advertiser_id, int8_t tx_power, + AdvertisingStatus status) = 0; + virtual void OnAdvertisingEnabled(uint8_t advertiser_id, bool enable, + AdvertisingStatus status) = 0; + virtual void OnAdvertisingDataSet(uint8_t advertiser_id, AdvertisingStatus status) = 0; + virtual void OnScanResponseDataSet(uint8_t advertiser_id, AdvertisingStatus status) = 0; + virtual void OnAdvertisingParametersUpdated(uint8_t advertiser_id, int8_t tx_power, + AdvertisingStatus status) = 0; + virtual void OnPeriodicAdvertisingParametersUpdated(uint8_t advertiser_id, + AdvertisingStatus status) = 0; + virtual void OnPeriodicAdvertisingDataSet(uint8_t advertiser_id, AdvertisingStatus status) = 0; + virtual void OnPeriodicAdvertisingEnabled(uint8_t advertiser_id, bool enable, + AdvertisingStatus status) = 0; + virtual void OnOwnAddressRead(uint8_t advertiser_id, uint8_t address_type, Address address) = 0; }; class LeAdvertisingManager : public bluetooth::Module { - public: +public: static constexpr AdvertiserId kInvalidId = 0xFF; static constexpr uint8_t kInvalidHandle = 0xFF; static constexpr uint8_t kAdvertisingSetIdMask = 0x0F; @@ -114,7 +115,8 @@ class LeAdvertisingManager : public bluetooth::Module { static constexpr uint16_t kLeMaximumFragmentLength = 251; static constexpr uint16_t kLeMaximumPeriodicDataFragmentLength = 252; static constexpr uint16_t kLeMaximumGapDataLength = 255; - static constexpr FragmentPreference kFragment_preference = FragmentPreference::CONTROLLER_SHOULD_NOT; + static constexpr FragmentPreference kFragment_preference = + FragmentPreference::CONTROLLER_SHOULD_NOT; LeAdvertisingManager(); LeAdvertisingManager(const LeAdvertisingManager&) = delete; LeAdvertisingManager& operator=(const LeAdvertisingManager&) = delete; @@ -126,38 +128,34 @@ class LeAdvertisingManager : public bluetooth::Module { int GetAdvertiserRegId(AdvertiserId advertiser_id); void ExtendedCreateAdvertiser( - uint8_t client_id, - int reg_id, - const AdvertisingConfig config, - common::Callback scan_callback, - common::Callback set_terminated_callback, - uint16_t duration, - uint8_t max_extended_advertising_events, - os::Handler* handler); - - void StartAdvertising( - AdvertiserId advertiser_id, - const AdvertisingConfig config, - uint16_t duration, - base::OnceCallback status_callback, - base::OnceCallback timeout_callback, - common::Callback scan_callback, - common::Callback set_terminated_callback, - os::Handler* handler); + uint8_t client_id, int reg_id, const AdvertisingConfig config, + common::Callback scan_callback, + common::Callback set_terminated_callback, + uint16_t duration, uint8_t max_extended_advertising_events, os::Handler* handler); + + void StartAdvertising(AdvertiserId advertiser_id, const AdvertisingConfig config, + uint16_t duration, + base::OnceCallback status_callback, + base::OnceCallback timeout_callback, + common::Callback scan_callback, + common::Callback set_terminated_callback, + os::Handler* handler); void GetOwnAddress(uint8_t advertiser_id); void RegisterAdvertiser( - common::ContextualOnceCallback callback); + common::ContextualOnceCallback + callback); void SetParameters(AdvertiserId advertiser_id, AdvertisingConfig config); void SetData(AdvertiserId advertiser_id, bool set_scan_rsp, std::vector data); - void EnableAdvertiser( - AdvertiserId advertiser_id, bool enable, uint16_t duration, uint8_t max_extended_advertising_events); + void EnableAdvertiser(AdvertiserId advertiser_id, bool enable, uint16_t duration, + uint8_t max_extended_advertising_events); - void SetPeriodicParameters(AdvertiserId advertiser_id, PeriodicAdvertisingParameters periodic_advertising_parameters); + void SetPeriodicParameters(AdvertiserId advertiser_id, + PeriodicAdvertisingParameters periodic_advertising_parameters); void SetPeriodicData(AdvertiserId advertiser_id, std::vector data); @@ -169,7 +167,7 @@ class LeAdvertisingManager : public bluetooth::Module { static const ModuleFactory Factory; - protected: +protected: void ListDependencies(ModuleList* list) const override; void Start() override; @@ -178,7 +176,7 @@ class LeAdvertisingManager : public bluetooth::Module { std::string ToString() const override; - private: +private: struct impl; std::unique_ptr pimpl_; }; diff --git a/system/gd/hci/le_advertising_manager_mock.h b/system/gd/hci/le_advertising_manager_mock.h index d56e91de3a2..baf2e263f1e 100644 --- a/system/gd/hci/le_advertising_manager_mock.h +++ b/system/gd/hci/le_advertising_manager_mock.h @@ -15,10 +15,10 @@ */ #pragma once -#include "hci/le_advertising_manager.h" - #include +#include "hci/le_advertising_manager.h" + // Unit test interfaces namespace bluetooth { namespace hci { @@ -31,21 +31,14 @@ using hci::AdvertiserId; using hci::LeAdvertisingManager; class MockLeAdvertisingManager : public LeAdvertisingManager { - public: +public: MOCK_METHOD(size_t, GetNumberOfAdvertisingInstances, (), (const)); - MOCK_METHOD( - AdvertiserId, - ExtendedCreateAdvertiser, - (uint8_t client_id, - int regId, - const AdvertisingConfig, - const common::Callback&, - const common::Callback&, - uint16_t, - uint8_t, - os::Handler*)); + MOCK_METHOD(AdvertiserId, ExtendedCreateAdvertiser, + (uint8_t client_id, int regId, const AdvertisingConfig, + const common::Callback&, + const common::Callback&, uint16_t, uint8_t, + os::Handler*)); MOCK_METHOD(void, RemoveAdvertiser, (AdvertiserId)); - }; } // namespace testing diff --git a/system/gd/hci/le_advertising_manager_test.cc b/system/gd/hci/le_advertising_manager_test.cc index 6da2fdf6e99..c15798da1db 100644 --- a/system/gd/hci/le_advertising_manager_test.cc +++ b/system/gd/hci/le_advertising_manager_test.cc @@ -51,62 +51,45 @@ using testing::InSequence; using testing::SaveArg; class TestController : public Controller { - public: - bool IsSupported(OpCode op_code) const override { - return supported_opcodes_.count(op_code) == 1; - } +public: + bool IsSupported(OpCode op_code) const override { return supported_opcodes_.count(op_code) == 1; } - void AddSupported(OpCode op_code) { - supported_opcodes_.insert(op_code); - } + void AddSupported(OpCode op_code) { supported_opcodes_.insert(op_code); } - uint8_t GetLeNumberOfSupportedAdverisingSets() const override { - return num_advertisers_; - } + uint8_t GetLeNumberOfSupportedAdverisingSets() const override { return num_advertisers_; } - uint16_t GetLeMaximumAdvertisingDataLength() const override { - return 0x0672; - } + uint16_t GetLeMaximumAdvertisingDataLength() const override { return 0x0672; } - bool SupportsBlePeriodicAdvertising() const override { - return true; - } + bool SupportsBlePeriodicAdvertising() const override { return true; } - bool SupportsBleExtendedAdvertising() const override { - return support_ble_extended_advertising_; - } + bool SupportsBleExtendedAdvertising() const override { return support_ble_extended_advertising_; } void SetBleExtendedAdvertisingSupport(bool support) { support_ble_extended_advertising_ = support; } - VendorCapabilities GetVendorCapabilities() const override { - return vendor_capabilities_; - } + VendorCapabilities GetVendorCapabilities() const override { return vendor_capabilities_; } uint8_t num_advertisers_{0}; VendorCapabilities vendor_capabilities_; - protected: +protected: void Start() override {} void Stop() override {} void ListDependencies(ModuleList* /* list */) const {} - private: +private: std::set supported_opcodes_{}; bool support_ble_extended_advertising_ = false; }; class TestLeAddressManager : public LeAddressManager { - public: - TestLeAddressManager( - common::Callback)> enqueue_command, - os::Handler* handler, - Address public_address, - uint8_t accept_list_size, - uint8_t resolving_list_size) - : LeAddressManager( - enqueue_command, handler, public_address, accept_list_size, resolving_list_size) { +public: + TestLeAddressManager(common::Callback)> enqueue_command, + os::Handler* handler, Address public_address, uint8_t accept_list_size, + uint8_t resolving_list_size) + : LeAddressManager(enqueue_command, handler, public_address, accept_list_size, + resolving_list_size) { address_policy_ = AddressPolicy::USE_STATIC_ADDRESS; minimum_rotation_time_ = 0ms; maximum_rotation_time_ = 100ms; @@ -125,17 +108,13 @@ class TestLeAddressManager : public LeAddressManager { test_client_state_ = UNREGISTERED; } - void AckPause(LeAddressManagerCallback* /* callback */) override { - test_client_state_ = PAUSED; - } + void AckPause(LeAddressManagerCallback* /* callback */) override { test_client_state_ = PAUSED; } void AckResume(LeAddressManagerCallback* /* callback */) override { test_client_state_ = RESUMED; } - void SetAddressPolicy(AddressPolicy address_policy) { - address_policy_ = address_policy; - } + void SetAddressPolicy(AddressPolicy address_policy) { address_policy_ = address_policy; } LeAddressManagerCallback* client_; bool ignore_unregister_for_testing = false; @@ -148,22 +127,21 @@ class TestLeAddressManager : public LeAddressManager { }; class TestAclManager : public AclManager { - public: - LeAddressManager* GetLeAddressManager() override { - return test_le_address_manager_; - } +public: + LeAddressManager* GetLeAddressManager() override { return test_le_address_manager_; } void SetAddressPolicy(LeAddressManager::AddressPolicy address_policy) { test_le_address_manager_->SetAddressPolicy(address_policy); } - protected: +protected: void Start() override { thread_ = new os::Thread("thread", os::Thread::Priority::NORMAL); handler_ = new os::Handler(thread_); Address address({0x01, 0x02, 0x03, 0x04, 0x05, 0x06}); test_le_address_manager_ = new TestLeAddressManager( - common::Bind(&TestAclManager::enqueue_command, common::Unretained(this)), handler_, address, 0x3F, 0x3F); + common::Bind(&TestAclManager::enqueue_command, common::Unretained(this)), handler_, + address, 0x3F, 0x3F); } void Stop() override { @@ -185,7 +163,7 @@ class TestAclManager : public AclManager { }; class LeAdvertisingManagerTest : public ::testing::Test { - protected: +protected: void SetUp() override { test_hci_layer_ = new HciLayerFake; // Ownership is transferred to registry test_controller_ = new TestController; @@ -205,7 +183,8 @@ class LeAdvertisingManagerTest : public ::testing::Test { void TearDown() override { sync_client_handler(); - fake_registry_.SynchronizeModuleHandler(&LeAdvertisingManager::Factory, std::chrono::milliseconds(20)); + fake_registry_.SynchronizeModuleHandler(&LeAdvertisingManager::Factory, + std::chrono::milliseconds(20)); fake_registry_.StopAll(); } @@ -221,24 +200,23 @@ class LeAdvertisingManagerTest : public ::testing::Test { bool support_ble_extended_advertising_ = false; const common::Callback scan_callback = - common::Bind(&LeAdvertisingManagerTest::on_scan, common::Unretained(this)); + common::Bind(&LeAdvertisingManagerTest::on_scan, common::Unretained(this)); const common::Callback set_terminated_callback = - common::Bind(&LeAdvertisingManagerTest::on_set_terminated, common::Unretained(this)); + common::Bind(&LeAdvertisingManagerTest::on_set_terminated, common::Unretained(this)); void on_scan(Address /* address */, AddressType /* address_type */) {} void on_set_terminated(ErrorCode /* error_code */, uint8_t, uint8_t) {} void sync_client_handler() { - log::assert_that( - thread_.GetReactor()->WaitForIdle(2s), - "assert failed: thread_.GetReactor()->WaitForIdle(2s)"); + log::assert_that(thread_.GetReactor()->WaitForIdle(2s), + "assert failed: thread_.GetReactor()->WaitForIdle(2s)"); } class MockAdvertisingCallback : public AdvertisingCallback { - public: - MOCK_METHOD4( - OnAdvertisingSetStarted, void(int reg_id, uint8_t advertiser_id, int8_t tx_power, AdvertisingStatus status)); + public: + MOCK_METHOD4(OnAdvertisingSetStarted, void(int reg_id, uint8_t advertiser_id, int8_t tx_power, + AdvertisingStatus status)); MOCK_METHOD3(OnAdvertisingEnabled, void(uint8_t advertiser_id, bool enable, AdvertisingStatus status)); MOCK_METHOD2(OnAdvertisingDataSet, void(uint8_t advertiser_id, AdvertisingStatus status)); @@ -251,12 +229,13 @@ class LeAdvertisingManagerTest : public ::testing::Test { void(uint8_t advertiser_id, AdvertisingStatus status)); MOCK_METHOD3(OnPeriodicAdvertisingEnabled, void(uint8_t advertiser_id, bool enable, AdvertisingStatus status)); - MOCK_METHOD3(OnOwnAddressRead, void(uint8_t advertiser_id, uint8_t address_type, Address address)); + MOCK_METHOD3(OnOwnAddressRead, + void(uint8_t advertiser_id, uint8_t address_type, Address address)); } mock_advertising_callback_; }; class LeAdvertisingAPITest : public LeAdvertisingManagerTest { - protected: +protected: void SetUp() override { LeAdvertisingManagerTest::SetUp(); @@ -277,26 +256,20 @@ class LeAdvertisingAPITest : public LeAdvertisingManagerTest { advertising_config.channel_map = 1; EXPECT_CALL( - mock_advertising_callback_, - OnAdvertisingSetStarted(0x00, _, 0x00, AdvertisingCallback::AdvertisingStatus::SUCCESS)) - .WillOnce(SaveArg<1>(&advertiser_id_)); + mock_advertising_callback_, + OnAdvertisingSetStarted(0x00, _, 0x00, AdvertisingCallback::AdvertisingStatus::SUCCESS)) + .WillOnce(SaveArg<1>(&advertiser_id_)); le_advertising_manager_->ExtendedCreateAdvertiser( - kAdvertiserClientIdJni, - 0x00, - advertising_config, - scan_callback, - set_terminated_callback, - 0, - 0, - client_handler_); + kAdvertiserClientIdJni, 0x00, advertising_config, scan_callback, + set_terminated_callback, 0, 0, client_handler_); std::vector adv_opcodes = { - OpCode::LE_READ_ADVERTISING_PHYSICAL_CHANNEL_TX_POWER, - OpCode::LE_SET_ADVERTISING_PARAMETERS, - OpCode::LE_SET_SCAN_RESPONSE_DATA, - OpCode::LE_SET_ADVERTISING_DATA, - OpCode::LE_SET_ADVERTISING_ENABLE, + OpCode::LE_READ_ADVERTISING_PHYSICAL_CHANNEL_TX_POWER, + OpCode::LE_SET_ADVERTISING_PARAMETERS, + OpCode::LE_SET_SCAN_RESPONSE_DATA, + OpCode::LE_SET_ADVERTISING_DATA, + OpCode::LE_SET_ADVERTISING_ENABLE, }; std::vector success_vector{static_cast(ErrorCode::SUCCESS)}; @@ -304,10 +277,11 @@ class LeAdvertisingAPITest : public LeAdvertisingManagerTest { ASSERT_EQ(adv_opcodes[i], test_hci_layer_->GetCommand().GetOpCode()); if (adv_opcodes[i] == OpCode::LE_READ_ADVERTISING_PHYSICAL_CHANNEL_TX_POWER) { test_hci_layer_->IncomingEvent( - LeReadAdvertisingPhysicalChannelTxPowerCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS, 0x00)); + LeReadAdvertisingPhysicalChannelTxPowerCompleteBuilder::Create( + uint8_t{1}, ErrorCode::SUCCESS, 0x00)); } else { - test_hci_layer_->IncomingEvent( - CommandCompleteBuilder::Create(uint8_t{1}, adv_opcodes[i], std::make_unique(success_vector))); + test_hci_layer_->IncomingEvent(CommandCompleteBuilder::Create( + uint8_t{1}, adv_opcodes[i], std::make_unique(success_vector))); } } @@ -319,7 +293,7 @@ class LeAdvertisingAPITest : public LeAdvertisingManagerTest { }; class LeAndroidHciAdvertisingManagerTest : public LeAdvertisingManagerTest { - protected: +protected: void SetUp() override { param_opcode_ = OpCode::LE_MULTI_ADVT; LeAdvertisingManagerTest::SetUp(); @@ -328,7 +302,7 @@ class LeAndroidHciAdvertisingManagerTest : public LeAdvertisingManagerTest { }; class LeAndroidHciAdvertisingAPITest : public LeAndroidHciAdvertisingManagerTest { - protected: +protected: void SetUp() override { LeAndroidHciAdvertisingManagerTest::SetUp(); @@ -348,32 +322,27 @@ class LeAndroidHciAdvertisingAPITest : public LeAndroidHciAdvertisingManagerTest advertising_config.channel_map = 1; EXPECT_CALL( - mock_advertising_callback_, - OnAdvertisingSetStarted(0x00, _, 0x00, AdvertisingCallback::AdvertisingStatus::SUCCESS)) - .WillOnce(SaveArg<1>(&advertiser_id_)); + mock_advertising_callback_, + OnAdvertisingSetStarted(0x00, _, 0x00, AdvertisingCallback::AdvertisingStatus::SUCCESS)) + .WillOnce(SaveArg<1>(&advertiser_id_)); le_advertising_manager_->ExtendedCreateAdvertiser( - kAdvertiserClientIdJni, - 0x00, - advertising_config, - scan_callback, - set_terminated_callback, - 0, - 0, - client_handler_); + kAdvertiserClientIdJni, 0x00, advertising_config, scan_callback, + set_terminated_callback, 0, 0, client_handler_); std::vector sub_ocf = { - SubOcf::SET_PARAM, - SubOcf::SET_SCAN_RESP, - SubOcf::SET_DATA, - SubOcf::SET_ENABLE, + SubOcf::SET_PARAM, + SubOcf::SET_SCAN_RESP, + SubOcf::SET_DATA, + SubOcf::SET_ENABLE, }; for (size_t i = 0; i < sub_ocf.size(); i++) { auto packet = test_hci_layer_->GetCommand(); auto sub_packet = LeMultiAdvtView::Create(LeAdvertisingCommandView::Create(packet)); ASSERT_TRUE(sub_packet.IsValid()); ASSERT_EQ(sub_packet.GetSubCmd(), sub_ocf[i]); - test_hci_layer_->IncomingEvent(LeMultiAdvtCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS, sub_ocf[i])); + test_hci_layer_->IncomingEvent( + LeMultiAdvtCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS, sub_ocf[i])); } sync_client_handler(); @@ -384,7 +353,7 @@ class LeAndroidHciAdvertisingAPITest : public LeAndroidHciAdvertisingManagerTest }; class LeAndroidHciAdvertisingAPIPublicAddressTest : public LeAndroidHciAdvertisingManagerTest { - protected: +protected: void SetUp() override { LeAndroidHciAdvertisingManagerTest::SetUp(); @@ -406,32 +375,27 @@ class LeAndroidHciAdvertisingAPIPublicAddressTest : public LeAndroidHciAdvertisi test_acl_manager_->SetAddressPolicy(LeAddressManager::AddressPolicy::USE_PUBLIC_ADDRESS); EXPECT_CALL( - mock_advertising_callback_, - OnAdvertisingSetStarted(0x00, _, 0x00, AdvertisingCallback::AdvertisingStatus::SUCCESS)) - .WillOnce(SaveArg<1>(&advertiser_id_)); + mock_advertising_callback_, + OnAdvertisingSetStarted(0x00, _, 0x00, AdvertisingCallback::AdvertisingStatus::SUCCESS)) + .WillOnce(SaveArg<1>(&advertiser_id_)); le_advertising_manager_->ExtendedCreateAdvertiser( - kAdvertiserClientIdJni, - 0x00, - advertising_config, - scan_callback, - set_terminated_callback, - 0, - 0, - client_handler_); + kAdvertiserClientIdJni, 0x00, advertising_config, scan_callback, + set_terminated_callback, 0, 0, client_handler_); std::vector sub_ocf = { - SubOcf::SET_PARAM, - SubOcf::SET_SCAN_RESP, - SubOcf::SET_DATA, - SubOcf::SET_ENABLE, + SubOcf::SET_PARAM, + SubOcf::SET_SCAN_RESP, + SubOcf::SET_DATA, + SubOcf::SET_ENABLE, }; for (size_t i = 0; i < sub_ocf.size(); i++) { auto packet = test_hci_layer_->GetCommand(); auto sub_packet = LeMultiAdvtView::Create(LeAdvertisingCommandView::Create(packet)); ASSERT_TRUE(sub_packet.IsValid()); ASSERT_EQ(sub_packet.GetSubCmd(), sub_ocf[i]); - test_hci_layer_->IncomingEvent(LeMultiAdvtCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS, sub_ocf[i])); + test_hci_layer_->IncomingEvent( + LeMultiAdvtCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS, sub_ocf[i])); } sync_client_handler(); @@ -442,7 +406,7 @@ class LeAndroidHciAdvertisingAPIPublicAddressTest : public LeAndroidHciAdvertisi }; class LeExtendedAdvertisingManagerTest : public LeAdvertisingManagerTest { - protected: +protected: void SetUp() override { support_ble_extended_advertising_ = true; param_opcode_ = OpCode::LE_SET_EXTENDED_ADVERTISING_PARAMETERS; @@ -451,7 +415,7 @@ class LeExtendedAdvertisingManagerTest : public LeAdvertisingManagerTest { }; class LeExtendedAdvertisingAPITest : public LeExtendedAdvertisingManagerTest { - protected: +protected: void SetUp() override { LeExtendedAdvertisingManagerTest::SetUp(); @@ -473,35 +437,29 @@ class LeExtendedAdvertisingAPITest : public LeExtendedAdvertisingManagerTest { advertising_config.sid = 0x01; EXPECT_CALL( - mock_advertising_callback_, - OnAdvertisingSetStarted(0x00, _, -23, AdvertisingCallback::AdvertisingStatus::SUCCESS)) - .WillOnce(SaveArg<1>(&advertiser_id_)); + mock_advertising_callback_, + OnAdvertisingSetStarted(0x00, _, -23, AdvertisingCallback::AdvertisingStatus::SUCCESS)) + .WillOnce(SaveArg<1>(&advertiser_id_)); le_advertising_manager_->ExtendedCreateAdvertiser( - kAdvertiserClientIdJni, - 0x00, - advertising_config, - scan_callback, - set_terminated_callback, - 0, - 0, - client_handler_); + kAdvertiserClientIdJni, 0x00, advertising_config, scan_callback, + set_terminated_callback, 0, 0, client_handler_); std::vector adv_opcodes = { - OpCode::LE_SET_EXTENDED_ADVERTISING_PARAMETERS, - OpCode::LE_SET_EXTENDED_SCAN_RESPONSE_DATA, - OpCode::LE_SET_EXTENDED_ADVERTISING_DATA, - OpCode::LE_SET_EXTENDED_ADVERTISING_ENABLE, + OpCode::LE_SET_EXTENDED_ADVERTISING_PARAMETERS, + OpCode::LE_SET_EXTENDED_SCAN_RESPONSE_DATA, + OpCode::LE_SET_EXTENDED_ADVERTISING_DATA, + OpCode::LE_SET_EXTENDED_ADVERTISING_ENABLE, }; std::vector success_vector{static_cast(ErrorCode::SUCCESS)}; for (size_t i = 0; i < adv_opcodes.size(); i++) { ASSERT_EQ(adv_opcodes[i], test_hci_layer_->GetCommand().GetOpCode()); if (adv_opcodes[i] == OpCode::LE_SET_EXTENDED_ADVERTISING_PARAMETERS) { test_hci_layer_->IncomingEvent(LeSetExtendedAdvertisingParametersCompleteBuilder::Create( - uint8_t{1}, ErrorCode::SUCCESS, static_cast(-23))); + uint8_t{1}, ErrorCode::SUCCESS, static_cast(-23))); } else { - test_hci_layer_->IncomingEvent( - CommandCompleteBuilder::Create(uint8_t{1}, adv_opcodes[i], std::make_unique(success_vector))); + test_hci_layer_->IncomingEvent(CommandCompleteBuilder::Create( + uint8_t{1}, adv_opcodes[i], std::make_unique(success_vector))); } } @@ -534,38 +492,32 @@ TEST_F(LeAdvertisingManagerTest, create_advertiser_test) { advertising_config.scan_response = gap_data; advertising_config.channel_map = 1; - le_advertising_manager_->ExtendedCreateAdvertiser( - kAdvertiserClientIdJni, - 0x00, - advertising_config, - scan_callback, - set_terminated_callback, - 0, - 0, - client_handler_); + le_advertising_manager_->ExtendedCreateAdvertiser(kAdvertiserClientIdJni, 0x00, + advertising_config, scan_callback, + set_terminated_callback, 0, 0, client_handler_); std::vector adv_opcodes = { - OpCode::LE_READ_ADVERTISING_PHYSICAL_CHANNEL_TX_POWER, - OpCode::LE_SET_ADVERTISING_PARAMETERS, - OpCode::LE_SET_SCAN_RESPONSE_DATA, - OpCode::LE_SET_ADVERTISING_DATA, - OpCode::LE_SET_ADVERTISING_ENABLE, + OpCode::LE_READ_ADVERTISING_PHYSICAL_CHANNEL_TX_POWER, + OpCode::LE_SET_ADVERTISING_PARAMETERS, + OpCode::LE_SET_SCAN_RESPONSE_DATA, + OpCode::LE_SET_ADVERTISING_DATA, + OpCode::LE_SET_ADVERTISING_ENABLE, }; AdvertiserId id; EXPECT_CALL( - mock_advertising_callback_, - OnAdvertisingSetStarted(0x00, _, 0x00, AdvertisingCallback::AdvertisingStatus::SUCCESS)) - .WillOnce(SaveArg<1>(&id)); + mock_advertising_callback_, + OnAdvertisingSetStarted(0x00, _, 0x00, AdvertisingCallback::AdvertisingStatus::SUCCESS)) + .WillOnce(SaveArg<1>(&id)); std::vector success_vector{static_cast(ErrorCode::SUCCESS)}; for (size_t i = 0; i < adv_opcodes.size(); i++) { ASSERT_EQ(adv_opcodes[i], test_hci_layer_->GetCommand().GetOpCode()); if (adv_opcodes[i] == OpCode::LE_READ_ADVERTISING_PHYSICAL_CHANNEL_TX_POWER) { - test_hci_layer_->IncomingEvent( - LeReadAdvertisingPhysicalChannelTxPowerCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS, 0x00)); + test_hci_layer_->IncomingEvent(LeReadAdvertisingPhysicalChannelTxPowerCompleteBuilder::Create( + uint8_t{1}, ErrorCode::SUCCESS, 0x00)); } else { - test_hci_layer_->IncomingEvent( - CommandCompleteBuilder::Create(uint8_t{1}, adv_opcodes[i], std::make_unique(success_vector))); + test_hci_layer_->IncomingEvent(CommandCompleteBuilder::Create( + uint8_t{1}, adv_opcodes[i], std::make_unique(success_vector))); } } sync_client_handler(); @@ -593,33 +545,27 @@ TEST_F(LeAndroidHciAdvertisingManagerTest, create_advertiser_test) { advertising_config.channel_map = 1; AdvertiserId id; - EXPECT_CALL( - mock_advertising_callback_, - OnAdvertisingSetStarted(0, _, 0, AdvertisingCallback::AdvertisingStatus::SUCCESS)) - .WillOnce(SaveArg<1>(&id)); - - le_advertising_manager_->ExtendedCreateAdvertiser( - kAdvertiserClientIdJni, - 0x00, - advertising_config, - scan_callback, - set_terminated_callback, - 0, - 0, - client_handler_); + EXPECT_CALL(mock_advertising_callback_, + OnAdvertisingSetStarted(0, _, 0, AdvertisingCallback::AdvertisingStatus::SUCCESS)) + .WillOnce(SaveArg<1>(&id)); + + le_advertising_manager_->ExtendedCreateAdvertiser(kAdvertiserClientIdJni, 0x00, + advertising_config, scan_callback, + set_terminated_callback, 0, 0, client_handler_); std::vector sub_ocf = { - SubOcf::SET_PARAM, - SubOcf::SET_SCAN_RESP, - SubOcf::SET_DATA, - SubOcf::SET_ENABLE, + SubOcf::SET_PARAM, + SubOcf::SET_SCAN_RESP, + SubOcf::SET_DATA, + SubOcf::SET_ENABLE, }; for (size_t i = 0; i < sub_ocf.size(); i++) { auto packet = test_hci_layer_->GetCommand(); auto sub_packet = LeMultiAdvtView::Create(LeAdvertisingCommandView::Create(packet)); ASSERT_TRUE(sub_packet.IsValid()); ASSERT_EQ(sub_packet.GetSubCmd(), sub_ocf[i]); - test_hci_layer_->IncomingEvent(LeMultiAdvtCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS, sub_ocf[i])); + test_hci_layer_->IncomingEvent( + LeMultiAdvtCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS, sub_ocf[i])); } sync_client_handler(); @@ -627,7 +573,8 @@ TEST_F(LeAndroidHciAdvertisingManagerTest, create_advertiser_test) { ASSERT_NE(LeAdvertisingManager::kInvalidId, id); le_advertising_manager_->RemoveAdvertiser(id); ASSERT_EQ(OpCode::LE_MULTI_ADVT, test_hci_layer_->GetCommand().GetOpCode()); - test_hci_layer_->IncomingEvent(LeMultiAdvtSetEnableCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + test_hci_layer_->IncomingEvent( + LeMultiAdvtSetEnableCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); } TEST_F(LeAndroidHciAdvertisingManagerTest, create_advertiser_with_rpa_test) { @@ -637,26 +584,16 @@ TEST_F(LeAndroidHciAdvertisingManagerTest, create_advertiser_with_rpa_test) { advertising_config.channel_map = 1; AdvertiserId id; - EXPECT_CALL( - mock_advertising_callback_, - OnAdvertisingSetStarted(0, _, 0, AdvertisingCallback::AdvertisingStatus::SUCCESS)) - .WillOnce(SaveArg<1>(&id)); - - le_advertising_manager_->ExtendedCreateAdvertiser( - kAdvertiserClientIdJni, - 0x00, - advertising_config, - scan_callback, - set_terminated_callback, - 0, - 0, - client_handler_); + EXPECT_CALL(mock_advertising_callback_, + OnAdvertisingSetStarted(0, _, 0, AdvertisingCallback::AdvertisingStatus::SUCCESS)) + .WillOnce(SaveArg<1>(&id)); + + le_advertising_manager_->ExtendedCreateAdvertiser(kAdvertiserClientIdJni, 0x00, + advertising_config, scan_callback, + set_terminated_callback, 0, 0, client_handler_); std::vector sub_ocf = { - SubOcf::SET_PARAM, - SubOcf::SET_SCAN_RESP, - SubOcf::SET_DATA, - SubOcf::SET_RANDOM_ADDR, - SubOcf::SET_ENABLE, + SubOcf::SET_PARAM, SubOcf::SET_SCAN_RESP, SubOcf::SET_DATA, + SubOcf::SET_RANDOM_ADDR, SubOcf::SET_ENABLE, }; for (size_t i = 0; i < sub_ocf.size(); i++) { @@ -665,7 +602,7 @@ TEST_F(LeAndroidHciAdvertisingManagerTest, create_advertiser_with_rpa_test) { ASSERT_TRUE(sub_packet.IsValid()); ASSERT_EQ(sub_packet.GetSubCmd(), sub_ocf[i]); test_hci_layer_->IncomingEvent( - LeMultiAdvtCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS, sub_ocf[i])); + LeMultiAdvtCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS, sub_ocf[i])); } sync_client_handler(); @@ -690,36 +627,29 @@ TEST_F(LeExtendedAdvertisingManagerTest, create_advertiser_test) { advertising_config.sid = 0x01; AdvertiserId id; - EXPECT_CALL( - mock_advertising_callback_, - OnAdvertisingSetStarted(0, _, -23, AdvertisingCallback::AdvertisingStatus::SUCCESS)) - .WillOnce(SaveArg<1>(&id)); - - le_advertising_manager_->ExtendedCreateAdvertiser( - kAdvertiserClientIdJni, - 0x00, - advertising_config, - scan_callback, - set_terminated_callback, - 0, - 0, - client_handler_); + EXPECT_CALL(mock_advertising_callback_, + OnAdvertisingSetStarted(0, _, -23, AdvertisingCallback::AdvertisingStatus::SUCCESS)) + .WillOnce(SaveArg<1>(&id)); + + le_advertising_manager_->ExtendedCreateAdvertiser(kAdvertiserClientIdJni, 0x00, + advertising_config, scan_callback, + set_terminated_callback, 0, 0, client_handler_); std::vector adv_opcodes = { - OpCode::LE_SET_EXTENDED_ADVERTISING_PARAMETERS, - OpCode::LE_SET_EXTENDED_SCAN_RESPONSE_DATA, - OpCode::LE_SET_EXTENDED_ADVERTISING_DATA, - OpCode::LE_SET_EXTENDED_ADVERTISING_ENABLE, + OpCode::LE_SET_EXTENDED_ADVERTISING_PARAMETERS, + OpCode::LE_SET_EXTENDED_SCAN_RESPONSE_DATA, + OpCode::LE_SET_EXTENDED_ADVERTISING_DATA, + OpCode::LE_SET_EXTENDED_ADVERTISING_ENABLE, }; std::vector success_vector{static_cast(ErrorCode::SUCCESS)}; for (size_t i = 0; i < adv_opcodes.size(); i++) { ASSERT_EQ(adv_opcodes[i], test_hci_layer_->GetCommand().GetOpCode()); if (adv_opcodes[i] == OpCode::LE_SET_EXTENDED_ADVERTISING_PARAMETERS) { test_hci_layer_->IncomingEvent(LeSetExtendedAdvertisingParametersCompleteBuilder::Create( - uint8_t{1}, ErrorCode::SUCCESS, static_cast(-23))); + uint8_t{1}, ErrorCode::SUCCESS, static_cast(-23))); } else { - test_hci_layer_->IncomingEvent( - CommandCompleteBuilder::Create(uint8_t{1}, adv_opcodes[i], std::make_unique(success_vector))); + test_hci_layer_->IncomingEvent(CommandCompleteBuilder::Create( + uint8_t{1}, adv_opcodes[i], std::make_unique(success_vector))); } } sync_client_handler(); @@ -750,36 +680,29 @@ TEST_F(LeExtendedAdvertisingManagerTest, create_periodic_advertiser_test) { advertising_config.periodic_advertising_parameters.enable = true; AdvertiserId id; - EXPECT_CALL( - mock_advertising_callback_, - OnAdvertisingSetStarted(0, _, -23, AdvertisingCallback::AdvertisingStatus::SUCCESS)) - .WillOnce(SaveArg<1>(&id)); - - le_advertising_manager_->ExtendedCreateAdvertiser( - kAdvertiserClientIdJni, - 0x00, - advertising_config, - scan_callback, - set_terminated_callback, - 0, - 0, - client_handler_); + EXPECT_CALL(mock_advertising_callback_, + OnAdvertisingSetStarted(0, _, -23, AdvertisingCallback::AdvertisingStatus::SUCCESS)) + .WillOnce(SaveArg<1>(&id)); + + le_advertising_manager_->ExtendedCreateAdvertiser(kAdvertiserClientIdJni, 0x00, + advertising_config, scan_callback, + set_terminated_callback, 0, 0, client_handler_); std::vector adv_opcodes = { - OpCode::LE_SET_EXTENDED_ADVERTISING_PARAMETERS, - OpCode::LE_SET_EXTENDED_SCAN_RESPONSE_DATA, - OpCode::LE_SET_EXTENDED_ADVERTISING_DATA, - OpCode::LE_SET_EXTENDED_ADVERTISING_ENABLE, + OpCode::LE_SET_EXTENDED_ADVERTISING_PARAMETERS, + OpCode::LE_SET_EXTENDED_SCAN_RESPONSE_DATA, + OpCode::LE_SET_EXTENDED_ADVERTISING_DATA, + OpCode::LE_SET_EXTENDED_ADVERTISING_ENABLE, }; std::vector success_vector{static_cast(ErrorCode::SUCCESS)}; for (size_t i = 0; i < adv_opcodes.size(); i++) { ASSERT_EQ(adv_opcodes[i], test_hci_layer_->GetCommand().GetOpCode()); if (adv_opcodes[i] == OpCode::LE_SET_EXTENDED_ADVERTISING_PARAMETERS) { test_hci_layer_->IncomingEvent(LeSetExtendedAdvertisingParametersCompleteBuilder::Create( - uint8_t{1}, ErrorCode::SUCCESS, static_cast(-23))); + uint8_t{1}, ErrorCode::SUCCESS, static_cast(-23))); } else { test_hci_layer_->IncomingEvent(CommandCompleteBuilder::Create( - uint8_t{1}, adv_opcodes[i], std::make_unique(success_vector))); + uint8_t{1}, adv_opcodes[i], std::make_unique(success_vector))); } } sync_client_handler(); @@ -809,36 +732,29 @@ TEST_F(LeExtendedAdvertisingManagerTest, create_advertiser_valid_max_251_ad_data advertising_config.sid = 0x01; AdvertiserId id; - EXPECT_CALL( - mock_advertising_callback_, - OnAdvertisingSetStarted(0, _, -23, AdvertisingCallback::AdvertisingStatus::SUCCESS)) - .WillOnce(SaveArg<1>(&id)); - - le_advertising_manager_->ExtendedCreateAdvertiser( - kAdvertiserClientIdJni, - 0x00, - advertising_config, - scan_callback, - set_terminated_callback, - 0, - 0, - client_handler_); + EXPECT_CALL(mock_advertising_callback_, + OnAdvertisingSetStarted(0, _, -23, AdvertisingCallback::AdvertisingStatus::SUCCESS)) + .WillOnce(SaveArg<1>(&id)); + + le_advertising_manager_->ExtendedCreateAdvertiser(kAdvertiserClientIdJni, 0x00, + advertising_config, scan_callback, + set_terminated_callback, 0, 0, client_handler_); std::vector adv_opcodes = { - OpCode::LE_SET_EXTENDED_ADVERTISING_PARAMETERS, - OpCode::LE_SET_EXTENDED_SCAN_RESPONSE_DATA, - OpCode::LE_SET_EXTENDED_ADVERTISING_DATA, - OpCode::LE_SET_EXTENDED_ADVERTISING_ENABLE, + OpCode::LE_SET_EXTENDED_ADVERTISING_PARAMETERS, + OpCode::LE_SET_EXTENDED_SCAN_RESPONSE_DATA, + OpCode::LE_SET_EXTENDED_ADVERTISING_DATA, + OpCode::LE_SET_EXTENDED_ADVERTISING_ENABLE, }; std::vector success_vector{static_cast(ErrorCode::SUCCESS)}; for (size_t i = 0; i < adv_opcodes.size(); i++) { ASSERT_EQ(adv_opcodes[i], test_hci_layer_->GetCommand().GetOpCode()); if (adv_opcodes[i] == OpCode::LE_SET_EXTENDED_ADVERTISING_PARAMETERS) { test_hci_layer_->IncomingEvent(LeSetExtendedAdvertisingParametersCompleteBuilder::Create( - uint8_t{1}, ErrorCode::SUCCESS, static_cast(-23))); + uint8_t{1}, ErrorCode::SUCCESS, static_cast(-23))); } else { test_hci_layer_->IncomingEvent(CommandCompleteBuilder::Create( - uint8_t{1}, adv_opcodes[i], std::make_unique(success_vector))); + uint8_t{1}, adv_opcodes[i], std::make_unique(success_vector))); } } sync_client_handler(); @@ -850,9 +766,8 @@ TEST_F(LeExtendedAdvertisingManagerTest, create_advertiser_valid_max_251_ad_data ASSERT_EQ(OpCode::LE_REMOVE_ADVERTISING_SET, test_hci_layer_->GetCommand().GetOpCode()); } -TEST_F( - LeExtendedAdvertisingManagerTest, - create_advertiser_valid_max_252_ad_data_length_fragments_test) { +TEST_F(LeExtendedAdvertisingManagerTest, + create_advertiser_valid_max_252_ad_data_length_fragments_test) { AdvertisingConfig advertising_config{}; advertising_config.advertising_type = AdvertisingType::ADV_IND; advertising_config.requested_advertiser_address_type = AdvertiserAddressType::PUBLIC; @@ -869,44 +784,37 @@ TEST_F( advertising_config.sid = 0x01; AdvertiserId id; - EXPECT_CALL( - mock_advertising_callback_, - OnAdvertisingSetStarted(0, _, -23, AdvertisingCallback::AdvertisingStatus::SUCCESS)) - .WillOnce(SaveArg<1>(&id)); - - le_advertising_manager_->ExtendedCreateAdvertiser( - kAdvertiserClientIdJni, - 0x00, - advertising_config, - scan_callback, - set_terminated_callback, - 0, - 0, - client_handler_); + EXPECT_CALL(mock_advertising_callback_, + OnAdvertisingSetStarted(0, _, -23, AdvertisingCallback::AdvertisingStatus::SUCCESS)) + .WillOnce(SaveArg<1>(&id)); + + le_advertising_manager_->ExtendedCreateAdvertiser(kAdvertiserClientIdJni, 0x00, + advertising_config, scan_callback, + set_terminated_callback, 0, 0, client_handler_); std::vector adv_opcodes = { - OpCode::LE_SET_EXTENDED_ADVERTISING_PARAMETERS, - OpCode::LE_SET_EXTENDED_SCAN_RESPONSE_DATA, // 1st fragment - OpCode::LE_SET_EXTENDED_SCAN_RESPONSE_DATA, // 2nd fragment - OpCode::LE_SET_EXTENDED_ADVERTISING_DATA, // 1st fragment - OpCode::LE_SET_EXTENDED_ADVERTISING_DATA, // 2nd fragment - OpCode::LE_SET_EXTENDED_ADVERTISING_ENABLE, + OpCode::LE_SET_EXTENDED_ADVERTISING_PARAMETERS, + OpCode::LE_SET_EXTENDED_SCAN_RESPONSE_DATA, // 1st fragment + OpCode::LE_SET_EXTENDED_SCAN_RESPONSE_DATA, // 2nd fragment + OpCode::LE_SET_EXTENDED_ADVERTISING_DATA, // 1st fragment + OpCode::LE_SET_EXTENDED_ADVERTISING_DATA, // 2nd fragment + OpCode::LE_SET_EXTENDED_ADVERTISING_ENABLE, }; std::vector success_vector{static_cast(ErrorCode::SUCCESS)}; for (size_t i = 0; i < adv_opcodes.size(); i++) { ASSERT_EQ(adv_opcodes[i], test_hci_layer_->GetCommand().GetOpCode()); if (adv_opcodes[i] == OpCode::LE_SET_EXTENDED_ADVERTISING_PARAMETERS) { test_hci_layer_->IncomingEvent(LeSetExtendedAdvertisingParametersCompleteBuilder::Create( - uint8_t{1}, ErrorCode::SUCCESS, static_cast(-23))); + uint8_t{1}, ErrorCode::SUCCESS, static_cast(-23))); } else if (adv_opcodes[i] == OpCode::LE_SET_EXTENDED_SCAN_RESPONSE_DATA) { test_hci_layer_->IncomingEvent( - LeSetExtendedScanResponseDataCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + LeSetExtendedScanResponseDataCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); } else if (adv_opcodes[i] == OpCode::LE_SET_EXTENDED_ADVERTISING_DATA) { test_hci_layer_->IncomingEvent( - LeSetExtendedAdvertisingDataCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + LeSetExtendedAdvertisingDataCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); } else { test_hci_layer_->IncomingEvent(CommandCompleteBuilder::Create( - uint8_t{1}, adv_opcodes[i], std::make_unique(success_vector))); + uint8_t{1}, adv_opcodes[i], std::make_unique(success_vector))); } } sync_client_handler(); @@ -938,25 +846,20 @@ TEST_F(LeExtendedAdvertisingManagerTest, create_advertiser_test_invalid_256_ad_d AdvertiserId id; EXPECT_CALL( - mock_advertising_callback_, - OnAdvertisingSetStarted(0, _, _, AdvertisingCallback::AdvertisingStatus::DATA_TOO_LARGE)) - .WillOnce(SaveArg<1>(&id)); - - le_advertising_manager_->ExtendedCreateAdvertiser( - kAdvertiserClientIdJni, - 0x00, - advertising_config, - scan_callback, - set_terminated_callback, - 0, - 0, - client_handler_); + mock_advertising_callback_, + OnAdvertisingSetStarted(0, _, _, AdvertisingCallback::AdvertisingStatus::DATA_TOO_LARGE)) + .WillOnce(SaveArg<1>(&id)); + + le_advertising_manager_->ExtendedCreateAdvertiser(kAdvertiserClientIdJni, 0x00, + advertising_config, scan_callback, + set_terminated_callback, 0, 0, client_handler_); sync_client_handler(); } TEST_F(LeExtendedAdvertisingManagerTest, ignore_on_pause_on_resume_after_unregistered) { - TestLeAddressManager* test_le_address_manager = (TestLeAddressManager*)test_acl_manager_->GetLeAddressManager(); + TestLeAddressManager* test_le_address_manager = + (TestLeAddressManager*)test_acl_manager_->GetLeAddressManager(); test_le_address_manager->ignore_unregister_for_testing = true; // Register LeAddressManager vai ExtendedCreateAdvertiser @@ -977,36 +880,29 @@ TEST_F(LeExtendedAdvertisingManagerTest, ignore_on_pause_on_resume_after_unregis advertising_config.sid = 0x01; AdvertiserId id; - EXPECT_CALL( - mock_advertising_callback_, - OnAdvertisingSetStarted(0, _, -23, AdvertisingCallback::AdvertisingStatus::SUCCESS)) - .WillOnce(SaveArg<1>(&id)); - - le_advertising_manager_->ExtendedCreateAdvertiser( - kAdvertiserClientIdJni, - 0x00, - advertising_config, - scan_callback, - set_terminated_callback, - 0, - 0, - client_handler_); + EXPECT_CALL(mock_advertising_callback_, + OnAdvertisingSetStarted(0, _, -23, AdvertisingCallback::AdvertisingStatus::SUCCESS)) + .WillOnce(SaveArg<1>(&id)); + + le_advertising_manager_->ExtendedCreateAdvertiser(kAdvertiserClientIdJni, 0x00, + advertising_config, scan_callback, + set_terminated_callback, 0, 0, client_handler_); std::vector adv_opcodes = { - OpCode::LE_SET_EXTENDED_ADVERTISING_PARAMETERS, - OpCode::LE_SET_EXTENDED_SCAN_RESPONSE_DATA, - OpCode::LE_SET_EXTENDED_ADVERTISING_DATA, - OpCode::LE_SET_EXTENDED_ADVERTISING_ENABLE, + OpCode::LE_SET_EXTENDED_ADVERTISING_PARAMETERS, + OpCode::LE_SET_EXTENDED_SCAN_RESPONSE_DATA, + OpCode::LE_SET_EXTENDED_ADVERTISING_DATA, + OpCode::LE_SET_EXTENDED_ADVERTISING_ENABLE, }; std::vector success_vector{static_cast(ErrorCode::SUCCESS)}; for (size_t i = 0; i < adv_opcodes.size(); i++) { ASSERT_EQ(adv_opcodes[i], test_hci_layer_->GetCommand().GetOpCode()); if (adv_opcodes[i] == OpCode::LE_SET_EXTENDED_ADVERTISING_PARAMETERS) { test_hci_layer_->IncomingEvent(LeSetExtendedAdvertisingParametersCompleteBuilder::Create( - uint8_t{1}, ErrorCode::SUCCESS, static_cast(-23))); + uint8_t{1}, ErrorCode::SUCCESS, static_cast(-23))); } else { - test_hci_layer_->IncomingEvent( - CommandCompleteBuilder::Create(uint8_t{1}, adv_opcodes[i], std::make_unique(success_vector))); + test_hci_layer_->IncomingEvent(CommandCompleteBuilder::Create( + uint8_t{1}, adv_opcodes[i], std::make_unique(success_vector))); } } sync_client_handler(); @@ -1020,11 +916,14 @@ TEST_F(LeExtendedAdvertisingManagerTest, ignore_on_pause_on_resume_after_unregis // Unregistered client should ignore OnPause/OnResume ASSERT_NE(test_le_address_manager->client_, nullptr); - ASSERT_EQ(test_le_address_manager->test_client_state_, TestLeAddressManager::TestClientState::UNREGISTERED); + ASSERT_EQ(test_le_address_manager->test_client_state_, + TestLeAddressManager::TestClientState::UNREGISTERED); test_le_address_manager->client_->OnPause(); - ASSERT_EQ(test_le_address_manager->test_client_state_, TestLeAddressManager::TestClientState::UNREGISTERED); + ASSERT_EQ(test_le_address_manager->test_client_state_, + TestLeAddressManager::TestClientState::UNREGISTERED); test_le_address_manager->client_->OnResume(); - ASSERT_EQ(test_le_address_manager->test_client_state_, TestLeAddressManager::TestClientState::UNREGISTERED); + ASSERT_EQ(test_le_address_manager->test_client_state_, + TestLeAddressManager::TestClientState::UNREGISTERED); } TEST_F(LeAdvertisingAPITest, startup_teardown) {} @@ -1048,10 +947,11 @@ TEST_F(LeAdvertisingAPITest, set_parameter) { advertising_config.channel_map = 1; le_advertising_manager_->SetParameters(advertiser_id_, advertising_config); ASSERT_EQ(OpCode::LE_SET_ADVERTISING_PARAMETERS, test_hci_layer_->GetCommand().GetOpCode()); - EXPECT_CALL( - mock_advertising_callback_, - OnAdvertisingParametersUpdated(advertiser_id_, 0x00, AdvertisingCallback::AdvertisingStatus::SUCCESS)); - test_hci_layer_->IncomingEvent(LeSetAdvertisingParametersCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + EXPECT_CALL(mock_advertising_callback_, + OnAdvertisingParametersUpdated(advertiser_id_, 0x00, + AdvertisingCallback::AdvertisingStatus::SUCCESS)); + test_hci_layer_->IncomingEvent( + LeSetAdvertisingParametersCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); } TEST_F(LeAndroidHciAdvertisingAPITest, set_parameter) { @@ -1070,10 +970,11 @@ TEST_F(LeAndroidHciAdvertisingAPITest, set_parameter) { auto sub_packet = LeMultiAdvtView::Create(LeAdvertisingCommandView::Create(packet)); ASSERT_TRUE(sub_packet.IsValid()); ASSERT_EQ(sub_packet.GetSubCmd(), SubOcf::SET_PARAM); - EXPECT_CALL( - mock_advertising_callback_, - OnAdvertisingParametersUpdated(advertiser_id_, 0x00, AdvertisingCallback::AdvertisingStatus::SUCCESS)); - test_hci_layer_->IncomingEvent(LeMultiAdvtCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS, SubOcf::SET_PARAM)); + EXPECT_CALL(mock_advertising_callback_, + OnAdvertisingParametersUpdated(advertiser_id_, 0x00, + AdvertisingCallback::AdvertisingStatus::SUCCESS)); + test_hci_layer_->IncomingEvent( + LeMultiAdvtCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS, SubOcf::SET_PARAM)); } TEST_F(LeExtendedAdvertisingAPITest, set_parameter) { @@ -1090,12 +991,13 @@ TEST_F(LeExtendedAdvertisingAPITest, set_parameter) { advertising_config.sid = 0x01; advertising_config.tx_power = 0x08; le_advertising_manager_->SetParameters(advertiser_id_, advertising_config); - ASSERT_EQ(OpCode::LE_SET_EXTENDED_ADVERTISING_PARAMETERS, test_hci_layer_->GetCommand().GetOpCode()); - EXPECT_CALL( - mock_advertising_callback_, - OnAdvertisingParametersUpdated(advertiser_id_, 0x08, AdvertisingCallback::AdvertisingStatus::SUCCESS)); - test_hci_layer_->IncomingEvent( - LeSetExtendedAdvertisingParametersCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS, 0x08)); + ASSERT_EQ(OpCode::LE_SET_EXTENDED_ADVERTISING_PARAMETERS, + test_hci_layer_->GetCommand().GetOpCode()); + EXPECT_CALL(mock_advertising_callback_, + OnAdvertisingParametersUpdated(advertiser_id_, 0x08, + AdvertisingCallback::AdvertisingStatus::SUCCESS)); + test_hci_layer_->IncomingEvent(LeSetExtendedAdvertisingParametersCompleteBuilder::Create( + uint8_t{1}, ErrorCode::SUCCESS, 0x08)); } TEST_F(LeAdvertisingAPITest, set_data_test) { @@ -1108,9 +1010,10 @@ TEST_F(LeAdvertisingAPITest, set_data_test) { le_advertising_manager_->SetData(advertiser_id_, false, advertising_data); ASSERT_EQ(OpCode::LE_SET_ADVERTISING_DATA, test_hci_layer_->GetCommand().GetOpCode()); EXPECT_CALL( - mock_advertising_callback_, - OnAdvertisingDataSet(advertiser_id_, AdvertisingCallback::AdvertisingStatus::SUCCESS)); - test_hci_layer_->IncomingEvent(LeSetAdvertisingDataCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + mock_advertising_callback_, + OnAdvertisingDataSet(advertiser_id_, AdvertisingCallback::AdvertisingStatus::SUCCESS)); + test_hci_layer_->IncomingEvent( + LeSetAdvertisingDataCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); // Set scan response data std::vector response_data{}; @@ -1121,9 +1024,10 @@ TEST_F(LeAdvertisingAPITest, set_data_test) { le_advertising_manager_->SetData(advertiser_id_, true, response_data); ASSERT_EQ(OpCode::LE_SET_SCAN_RESPONSE_DATA, test_hci_layer_->GetCommand().GetOpCode()); EXPECT_CALL( - mock_advertising_callback_, - OnScanResponseDataSet(advertiser_id_, AdvertisingCallback::AdvertisingStatus::SUCCESS)); - test_hci_layer_->IncomingEvent(LeSetScanResponseDataCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + mock_advertising_callback_, + OnScanResponseDataSet(advertiser_id_, AdvertisingCallback::AdvertisingStatus::SUCCESS)); + test_hci_layer_->IncomingEvent( + LeSetScanResponseDataCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); } TEST_F(LeExtendedAdvertisingAPITest, set_data_test) { @@ -1136,9 +1040,10 @@ TEST_F(LeExtendedAdvertisingAPITest, set_data_test) { le_advertising_manager_->SetData(advertiser_id_, false, advertising_data); ASSERT_EQ(OpCode::LE_SET_EXTENDED_ADVERTISING_DATA, test_hci_layer_->GetCommand().GetOpCode()); EXPECT_CALL( - mock_advertising_callback_, - OnAdvertisingDataSet(advertiser_id_, AdvertisingCallback::AdvertisingStatus::SUCCESS)); - test_hci_layer_->IncomingEvent(LeSetExtendedAdvertisingDataCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + mock_advertising_callback_, + OnAdvertisingDataSet(advertiser_id_, AdvertisingCallback::AdvertisingStatus::SUCCESS)); + test_hci_layer_->IncomingEvent( + LeSetExtendedAdvertisingDataCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); // Set scan response data std::vector response_data{}; @@ -1149,9 +1054,10 @@ TEST_F(LeExtendedAdvertisingAPITest, set_data_test) { le_advertising_manager_->SetData(advertiser_id_, true, response_data); ASSERT_EQ(OpCode::LE_SET_EXTENDED_SCAN_RESPONSE_DATA, test_hci_layer_->GetCommand().GetOpCode()); EXPECT_CALL( - mock_advertising_callback_, - OnScanResponseDataSet(advertiser_id_, AdvertisingCallback::AdvertisingStatus::SUCCESS)); - test_hci_layer_->IncomingEvent(LeSetExtendedScanResponseDataCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + mock_advertising_callback_, + OnScanResponseDataSet(advertiser_id_, AdvertisingCallback::AdvertisingStatus::SUCCESS)); + test_hci_layer_->IncomingEvent( + LeSetExtendedScanResponseDataCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); } TEST_F(LeAndroidHciAdvertisingAPITest, set_data_test) { @@ -1167,9 +1073,10 @@ TEST_F(LeAndroidHciAdvertisingAPITest, set_data_test) { ASSERT_TRUE(sub_packet.IsValid()); ASSERT_EQ(sub_packet.GetSubCmd(), SubOcf::SET_DATA); EXPECT_CALL( - mock_advertising_callback_, - OnAdvertisingDataSet(advertiser_id_, AdvertisingCallback::AdvertisingStatus::SUCCESS)); - test_hci_layer_->IncomingEvent(LeMultiAdvtCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS, SubOcf::SET_DATA)); + mock_advertising_callback_, + OnAdvertisingDataSet(advertiser_id_, AdvertisingCallback::AdvertisingStatus::SUCCESS)); + test_hci_layer_->IncomingEvent( + LeMultiAdvtCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS, SubOcf::SET_DATA)); // Set scan response data std::vector response_data{}; @@ -1183,10 +1090,10 @@ TEST_F(LeAndroidHciAdvertisingAPITest, set_data_test) { ASSERT_TRUE(sub_packet.IsValid()); ASSERT_EQ(sub_packet.GetSubCmd(), SubOcf::SET_SCAN_RESP); EXPECT_CALL( - mock_advertising_callback_, - OnScanResponseDataSet(advertiser_id_, AdvertisingCallback::AdvertisingStatus::SUCCESS)); - test_hci_layer_->IncomingEvent( - LeMultiAdvtCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS, SubOcf::SET_SCAN_RESP)); + mock_advertising_callback_, + OnScanResponseDataSet(advertiser_id_, AdvertisingCallback::AdvertisingStatus::SUCCESS)); + test_hci_layer_->IncomingEvent(LeMultiAdvtCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS, + SubOcf::SET_SCAN_RESP)); } TEST_F(LeExtendedAdvertisingAPITest, set_data_fragments_test) { @@ -1196,7 +1103,8 @@ TEST_F(LeExtendedAdvertisingAPITest, set_data_fragments_test) { GapData data_item{}; data_item.data_.push_back(0xda); data_item.data_type_ = GapDataType::SERVICE_DATA_128_BIT_UUIDS; - uint8_t uuid[16] = {0xf0, 0x34, 0x9b, 0x5f, 0x80, 0x00, 0x00, 0x80, 0x00, 0x10, 0x00, 0x00, 0x00, 0x10, 0x00, i}; + uint8_t uuid[16] = {0xf0, 0x34, 0x9b, 0x5f, 0x80, 0x00, 0x00, 0x80, + 0x00, 0x10, 0x00, 0x00, 0x00, 0x10, 0x00, i}; std::copy_n(uuid, 16, std::back_inserter(data_item.data_)); uint8_t service_data[200]; std::copy_n(service_data, 200, std::back_inserter(data_item.data_)); @@ -1212,11 +1120,14 @@ TEST_F(LeExtendedAdvertisingAPITest, set_data_fragments_test) { ASSERT_EQ(OpCode::LE_SET_EXTENDED_ADVERTISING_DATA, test_hci_layer_->GetCommand().GetOpCode()); EXPECT_CALL( - mock_advertising_callback_, - OnAdvertisingDataSet(advertiser_id_, AdvertisingCallback::AdvertisingStatus::SUCCESS)); - test_hci_layer_->IncomingEvent(LeSetExtendedAdvertisingDataCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); - test_hci_layer_->IncomingEvent(LeSetExtendedAdvertisingDataCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); - test_hci_layer_->IncomingEvent(LeSetExtendedAdvertisingDataCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + mock_advertising_callback_, + OnAdvertisingDataSet(advertiser_id_, AdvertisingCallback::AdvertisingStatus::SUCCESS)); + test_hci_layer_->IncomingEvent( + LeSetExtendedAdvertisingDataCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + test_hci_layer_->IncomingEvent( + LeSetExtendedAdvertisingDataCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + test_hci_layer_->IncomingEvent( + LeSetExtendedAdvertisingDataCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); } TEST_F(LeExtendedAdvertisingAPITest, set_scan_response_fragments_test) { @@ -1226,7 +1137,8 @@ TEST_F(LeExtendedAdvertisingAPITest, set_scan_response_fragments_test) { GapData data_item{}; data_item.data_.push_back(0xfa); data_item.data_type_ = GapDataType::SERVICE_DATA_128_BIT_UUIDS; - uint8_t uuid[16] = {0xf0, 0x34, 0x9b, 0x5f, 0x80, 0x00, 0x00, 0x80, 0x00, 0x10, 0x00, 0x00, 0x00, 0x10, 0x00, i}; + uint8_t uuid[16] = {0xf0, 0x34, 0x9b, 0x5f, 0x80, 0x00, 0x00, 0x80, + 0x00, 0x10, 0x00, 0x00, 0x00, 0x10, 0x00, i}; std::copy_n(uuid, 16, std::back_inserter(data_item.data_)); uint8_t service_data[232]; std::copy_n(service_data, 232, std::back_inserter(data_item.data_)); @@ -1242,11 +1154,14 @@ TEST_F(LeExtendedAdvertisingAPITest, set_scan_response_fragments_test) { ASSERT_EQ(OpCode::LE_SET_EXTENDED_SCAN_RESPONSE_DATA, test_hci_layer_->GetCommand().GetOpCode()); EXPECT_CALL( - mock_advertising_callback_, - OnScanResponseDataSet(advertiser_id_, AdvertisingCallback::AdvertisingStatus::SUCCESS)); - test_hci_layer_->IncomingEvent(LeSetExtendedScanResponseDataCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); - test_hci_layer_->IncomingEvent(LeSetExtendedScanResponseDataCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); - test_hci_layer_->IncomingEvent(LeSetExtendedScanResponseDataCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + mock_advertising_callback_, + OnScanResponseDataSet(advertiser_id_, AdvertisingCallback::AdvertisingStatus::SUCCESS)); + test_hci_layer_->IncomingEvent( + LeSetExtendedScanResponseDataCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + test_hci_layer_->IncomingEvent( + LeSetExtendedScanResponseDataCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + test_hci_layer_->IncomingEvent( + LeSetExtendedScanResponseDataCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); } TEST_F(LeExtendedAdvertisingAPITest, set_data_with_invalid_length) { @@ -1256,21 +1171,22 @@ TEST_F(LeExtendedAdvertisingAPITest, set_data_with_invalid_length) { GapData data_item{}; data_item.data_.push_back(0xfb); data_item.data_type_ = GapDataType::SERVICE_DATA_128_BIT_UUIDS; - uint8_t uuid[16] = {0xf0, 0x34, 0x9b, 0x5f, 0x80, 0x00, 0x00, 0x80, 0x00, 0x10, 0x00, 0x00, 0x00, 0x10, 0x00, i}; + uint8_t uuid[16] = {0xf0, 0x34, 0x9b, 0x5f, 0x80, 0x00, 0x00, 0x80, + 0x00, 0x10, 0x00, 0x00, 0x00, 0x10, 0x00, i}; std::copy_n(uuid, 16, std::back_inserter(data_item.data_)); uint8_t service_data[200]; std::copy_n(service_data, 200, std::back_inserter(data_item.data_)); advertising_data.push_back(data_item); } - EXPECT_CALL( - mock_advertising_callback_, - OnAdvertisingDataSet(advertiser_id_, AdvertisingCallback::AdvertisingStatus::DATA_TOO_LARGE)); + EXPECT_CALL(mock_advertising_callback_, + OnAdvertisingDataSet(advertiser_id_, + AdvertisingCallback::AdvertisingStatus::DATA_TOO_LARGE)); le_advertising_manager_->SetData(advertiser_id_, false, advertising_data); - EXPECT_CALL( - mock_advertising_callback_, - OnScanResponseDataSet(advertiser_id_, AdvertisingCallback::AdvertisingStatus::DATA_TOO_LARGE)); + EXPECT_CALL(mock_advertising_callback_, + OnScanResponseDataSet(advertiser_id_, + AdvertisingCallback::AdvertisingStatus::DATA_TOO_LARGE)); le_advertising_manager_->SetData(advertiser_id_, true, advertising_data); sync_client_handler(); @@ -1289,10 +1205,10 @@ TEST_F(LeExtendedAdvertisingAPITest, set_data_valid_max_251_ad_data_length_test) le_advertising_manager_->SetData(advertiser_id_, false, advertising_data); ASSERT_EQ(OpCode::LE_SET_EXTENDED_ADVERTISING_DATA, test_hci_layer_->GetCommand().GetOpCode()); EXPECT_CALL( - mock_advertising_callback_, - OnAdvertisingDataSet(advertiser_id_, AdvertisingCallback::AdvertisingStatus::SUCCESS)); + mock_advertising_callback_, + OnAdvertisingDataSet(advertiser_id_, AdvertisingCallback::AdvertisingStatus::SUCCESS)); test_hci_layer_->IncomingEvent( - LeSetExtendedAdvertisingDataCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + LeSetExtendedAdvertisingDataCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); // Set scan response data std::vector response_data{}; @@ -1305,10 +1221,10 @@ TEST_F(LeExtendedAdvertisingAPITest, set_data_valid_max_251_ad_data_length_test) le_advertising_manager_->SetData(advertiser_id_, true, response_data); ASSERT_EQ(OpCode::LE_SET_EXTENDED_SCAN_RESPONSE_DATA, test_hci_layer_->GetCommand().GetOpCode()); EXPECT_CALL( - mock_advertising_callback_, - OnScanResponseDataSet(advertiser_id_, AdvertisingCallback::AdvertisingStatus::SUCCESS)); + mock_advertising_callback_, + OnScanResponseDataSet(advertiser_id_, AdvertisingCallback::AdvertisingStatus::SUCCESS)); test_hci_layer_->IncomingEvent( - LeSetExtendedScanResponseDataCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + LeSetExtendedScanResponseDataCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); } TEST_F(LeExtendedAdvertisingAPITest, set_data_valid_252_ad_data_length_fragments_test) { @@ -1326,26 +1242,24 @@ TEST_F(LeExtendedAdvertisingAPITest, set_data_valid_252_ad_data_length_fragments // First fragment auto command = test_hci_layer_->GetCommand(); ASSERT_EQ(command.GetOpCode(), OpCode::LE_SET_EXTENDED_ADVERTISING_DATA); - ASSERT_EQ( - 1ul /* Advertising_Handle */ + 1ul /* Operation */ + 1ul /* Fragment_Preference */ - + 1ul /*Advertising_Data_Length*/ + - 251ul /* Max data length 251 includes AD length and type */, - command.GetPayload().size()); + ASSERT_EQ(1ul /* Advertising_Handle */ + 1ul /* Operation */ + 1ul /* Fragment_Preference */ + + 1ul /*Advertising_Data_Length*/ + + 251ul /* Max data length 251 includes AD length and type */, + command.GetPayload().size()); // Second fragment auto command2 = test_hci_layer_->GetCommand(); ASSERT_EQ(command2.GetOpCode(), OpCode::LE_SET_EXTENDED_ADVERTISING_DATA); - ASSERT_EQ( - 1ul /* Advertising_Handle */ + 1ul /* Operation */ + 1ul /* Fragment_Preference */ - + 1ul /*Advertising_Data_Length*/ + 1ul /* Remaining 1 byte data */, - command2.GetPayload().size()); + ASSERT_EQ(1ul /* Advertising_Handle */ + 1ul /* Operation */ + 1ul /* Fragment_Preference */ + + 1ul /*Advertising_Data_Length*/ + 1ul /* Remaining 1 byte data */, + command2.GetPayload().size()); EXPECT_CALL( - mock_advertising_callback_, - OnAdvertisingDataSet(advertiser_id_, AdvertisingCallback::AdvertisingStatus::SUCCESS)); + mock_advertising_callback_, + OnAdvertisingDataSet(advertiser_id_, AdvertisingCallback::AdvertisingStatus::SUCCESS)); test_hci_layer_->IncomingEvent( - LeSetExtendedAdvertisingDataCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + LeSetExtendedAdvertisingDataCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); test_hci_layer_->IncomingEvent( - LeSetExtendedAdvertisingDataCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + LeSetExtendedAdvertisingDataCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); // Set scan response data std::vector response_data{}; @@ -1360,26 +1274,24 @@ TEST_F(LeExtendedAdvertisingAPITest, set_data_valid_252_ad_data_length_fragments // First fragment command = test_hci_layer_->GetCommand(); ASSERT_EQ(command.GetOpCode(), OpCode::LE_SET_EXTENDED_SCAN_RESPONSE_DATA); - ASSERT_EQ( - 1ul /* Advertising_Handle */ + 1ul /* Operation */ + 1ul /* Fragment_Preference */ - + 1ul /*Advertising_Data_Length*/ + - 251ul /* Max data length 251 includes AD length and type */, - command.GetPayload().size()); + ASSERT_EQ(1ul /* Advertising_Handle */ + 1ul /* Operation */ + 1ul /* Fragment_Preference */ + + 1ul /*Advertising_Data_Length*/ + + 251ul /* Max data length 251 includes AD length and type */, + command.GetPayload().size()); // Second fragment command2 = test_hci_layer_->GetCommand(); ASSERT_EQ(command2.GetOpCode(), OpCode::LE_SET_EXTENDED_SCAN_RESPONSE_DATA); - ASSERT_EQ( - 1ul /* Advertising_Handle */ + 1ul /* Operation */ + 1ul /* Fragment_Preference */ - + 1ul /*Advertising_Data_Length*/ + 1ul /* Remaining 1 byte data */, - command2.GetPayload().size()); + ASSERT_EQ(1ul /* Advertising_Handle */ + 1ul /* Operation */ + 1ul /* Fragment_Preference */ + + 1ul /*Advertising_Data_Length*/ + 1ul /* Remaining 1 byte data */, + command2.GetPayload().size()); EXPECT_CALL( - mock_advertising_callback_, - OnScanResponseDataSet(advertiser_id_, AdvertisingCallback::AdvertisingStatus::SUCCESS)); + mock_advertising_callback_, + OnScanResponseDataSet(advertiser_id_, AdvertisingCallback::AdvertisingStatus::SUCCESS)); test_hci_layer_->IncomingEvent( - LeSetExtendedScanResponseDataCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + LeSetExtendedScanResponseDataCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); test_hci_layer_->IncomingEvent( - LeSetExtendedScanResponseDataCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + LeSetExtendedScanResponseDataCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); } TEST_F(LeExtendedAdvertisingAPITest, set_data_with_invalid_256_ad_data_length_test) { @@ -1393,15 +1305,14 @@ TEST_F(LeExtendedAdvertisingAPITest, set_data_with_invalid_256_ad_data_length_te std::copy_n(service_data, 254, std::back_inserter(data_item.data_)); advertising_data.push_back(data_item); - EXPECT_CALL( - mock_advertising_callback_, - OnAdvertisingDataSet(advertiser_id_, AdvertisingCallback::AdvertisingStatus::INTERNAL_ERROR)); + EXPECT_CALL(mock_advertising_callback_, + OnAdvertisingDataSet(advertiser_id_, + AdvertisingCallback::AdvertisingStatus::INTERNAL_ERROR)); le_advertising_manager_->SetData(advertiser_id_, false, advertising_data); - EXPECT_CALL( - mock_advertising_callback_, - OnScanResponseDataSet( - advertiser_id_, AdvertisingCallback::AdvertisingStatus::INTERNAL_ERROR)); + EXPECT_CALL(mock_advertising_callback_, + OnScanResponseDataSet(advertiser_id_, + AdvertisingCallback::AdvertisingStatus::INTERNAL_ERROR)); le_advertising_manager_->SetData(advertiser_id_, true, advertising_data); sync_client_handler(); @@ -1411,19 +1322,21 @@ TEST_F(LeAdvertisingAPITest, disable_enable_advertiser_test) { // disable advertiser le_advertising_manager_->EnableAdvertiser(advertiser_id_, false, 0x00, 0x00); ASSERT_EQ(OpCode::LE_SET_ADVERTISING_ENABLE, test_hci_layer_->GetCommand().GetOpCode()); - EXPECT_CALL( - mock_advertising_callback_, - OnAdvertisingEnabled(advertiser_id_, false, AdvertisingCallback::AdvertisingStatus::SUCCESS)); - test_hci_layer_->IncomingEvent(LeSetAdvertisingEnableCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + EXPECT_CALL(mock_advertising_callback_, + OnAdvertisingEnabled(advertiser_id_, false, + AdvertisingCallback::AdvertisingStatus::SUCCESS)); + test_hci_layer_->IncomingEvent( + LeSetAdvertisingEnableCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); sync_client_handler(); // enable advertiser le_advertising_manager_->EnableAdvertiser(advertiser_id_, true, 0x00, 0x00); ASSERT_EQ(OpCode::LE_SET_ADVERTISING_ENABLE, test_hci_layer_->GetCommand().GetOpCode()); - EXPECT_CALL( - mock_advertising_callback_, - OnAdvertisingEnabled(advertiser_id_, true, AdvertisingCallback::AdvertisingStatus::SUCCESS)); - test_hci_layer_->IncomingEvent(LeSetAdvertisingEnableCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + EXPECT_CALL(mock_advertising_callback_, + OnAdvertisingEnabled(advertiser_id_, true, + AdvertisingCallback::AdvertisingStatus::SUCCESS)); + test_hci_layer_->IncomingEvent( + LeSetAdvertisingEnableCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); } TEST_F(LeAndroidHciAdvertisingAPITest, disable_enable_advertiser_test) { @@ -1433,11 +1346,11 @@ TEST_F(LeAndroidHciAdvertisingAPITest, disable_enable_advertiser_test) { auto sub_packet = LeMultiAdvtView::Create(LeAdvertisingCommandView::Create(packet)); ASSERT_TRUE(sub_packet.IsValid()); ASSERT_EQ(sub_packet.GetSubCmd(), SubOcf::SET_ENABLE); - EXPECT_CALL( - mock_advertising_callback_, - OnAdvertisingEnabled(advertiser_id_, false, AdvertisingCallback::AdvertisingStatus::SUCCESS)); + EXPECT_CALL(mock_advertising_callback_, + OnAdvertisingEnabled(advertiser_id_, false, + AdvertisingCallback::AdvertisingStatus::SUCCESS)); test_hci_layer_->IncomingEvent( - LeMultiAdvtCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS, SubOcf::SET_ENABLE)); + LeMultiAdvtCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS, SubOcf::SET_ENABLE)); sync_client_handler(); // enable advertiser @@ -1446,30 +1359,32 @@ TEST_F(LeAndroidHciAdvertisingAPITest, disable_enable_advertiser_test) { sub_packet = LeMultiAdvtView::Create(LeAdvertisingCommandView::Create(packet)); ASSERT_TRUE(sub_packet.IsValid()); ASSERT_EQ(sub_packet.GetSubCmd(), SubOcf::SET_ENABLE); - EXPECT_CALL( - mock_advertising_callback_, - OnAdvertisingEnabled(advertiser_id_, true, AdvertisingCallback::AdvertisingStatus::SUCCESS)); + EXPECT_CALL(mock_advertising_callback_, + OnAdvertisingEnabled(advertiser_id_, true, + AdvertisingCallback::AdvertisingStatus::SUCCESS)); test_hci_layer_->IncomingEvent( - LeMultiAdvtCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS, SubOcf::SET_ENABLE)); + LeMultiAdvtCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS, SubOcf::SET_ENABLE)); } TEST_F(LeExtendedAdvertisingAPITest, disable_enable_advertiser_test) { // disable advertiser le_advertising_manager_->EnableAdvertiser(advertiser_id_, false, 0x00, 0x00); ASSERT_EQ(OpCode::LE_SET_EXTENDED_ADVERTISING_ENABLE, test_hci_layer_->GetCommand().GetOpCode()); - EXPECT_CALL( - mock_advertising_callback_, - OnAdvertisingEnabled(advertiser_id_, false, AdvertisingCallback::AdvertisingStatus::SUCCESS)); - test_hci_layer_->IncomingEvent(LeSetExtendedAdvertisingEnableCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + EXPECT_CALL(mock_advertising_callback_, + OnAdvertisingEnabled(advertiser_id_, false, + AdvertisingCallback::AdvertisingStatus::SUCCESS)); + test_hci_layer_->IncomingEvent( + LeSetExtendedAdvertisingEnableCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); sync_client_handler(); // enable advertiser le_advertising_manager_->EnableAdvertiser(advertiser_id_, true, 0x00, 0x00); ASSERT_EQ(OpCode::LE_SET_EXTENDED_ADVERTISING_ENABLE, test_hci_layer_->GetCommand().GetOpCode()); - EXPECT_CALL( - mock_advertising_callback_, - OnAdvertisingEnabled(advertiser_id_, true, AdvertisingCallback::AdvertisingStatus::SUCCESS)); - test_hci_layer_->IncomingEvent(LeSetExtendedAdvertisingEnableCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + EXPECT_CALL(mock_advertising_callback_, + OnAdvertisingEnabled(advertiser_id_, true, + AdvertisingCallback::AdvertisingStatus::SUCCESS)); + test_hci_layer_->IncomingEvent( + LeSetExtendedAdvertisingEnableCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); } TEST_F(LeExtendedAdvertisingAPITest, disable_after_enable) { @@ -1490,25 +1405,25 @@ TEST_F(LeExtendedAdvertisingAPITest, disable_after_enable) { le_advertising_manager_->EnableAdvertiser(advertiser_id_, false, 0x00, 0x00); test_hci_layer_->GetCommand(); test_hci_layer_->IncomingEvent( - LeSetExtendedAdvertisingEnableCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + LeSetExtendedAdvertisingEnableCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); // enable le_advertising_manager_->EnableAdvertiser(advertiser_id_, true, 0x00, 0x00); test_hci_layer_->GetCommand(); test_hci_layer_->IncomingEvent( - LeSetExtendedAdvertisingEnableCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + LeSetExtendedAdvertisingEnableCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); // disable le_advertising_manager_->EnableAdvertiser(advertiser_id_, false, 0x00, 0x00); test_hci_layer_->GetCommand(); test_hci_layer_->IncomingEvent( - LeSetExtendedAdvertisingEnableCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + LeSetExtendedAdvertisingEnableCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); // enable le_advertising_manager_->EnableAdvertiser(advertiser_id_, true, 0x00, 0x00); test_hci_layer_->GetCommand(); test_hci_layer_->IncomingEvent( - LeSetExtendedAdvertisingEnableCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + LeSetExtendedAdvertisingEnableCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); sync_client_handler(); } @@ -1518,13 +1433,13 @@ TEST_F(LeExtendedAdvertisingAPITest, set_periodic_parameter) { advertising_config.max_interval = 0x1000; advertising_config.min_interval = 0x0006; le_advertising_manager_->SetPeriodicParameters(advertiser_id_, advertising_config); - ASSERT_EQ( - OpCode::LE_SET_PERIODIC_ADVERTISING_PARAMETERS, test_hci_layer_->GetCommand().GetOpCode()); - EXPECT_CALL( - mock_advertising_callback_, - OnPeriodicAdvertisingParametersUpdated(advertiser_id_, AdvertisingCallback::AdvertisingStatus::SUCCESS)); - test_hci_layer_->IncomingEvent( - LeSetPeriodicAdvertisingParametersCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + ASSERT_EQ(OpCode::LE_SET_PERIODIC_ADVERTISING_PARAMETERS, + test_hci_layer_->GetCommand().GetOpCode()); + EXPECT_CALL(mock_advertising_callback_, + OnPeriodicAdvertisingParametersUpdated( + advertiser_id_, AdvertisingCallback::AdvertisingStatus::SUCCESS)); + test_hci_layer_->IncomingEvent(LeSetPeriodicAdvertisingParametersCompleteBuilder::Create( + uint8_t{1}, ErrorCode::SUCCESS)); sync_client_handler(); } @@ -1537,10 +1452,11 @@ TEST_F(LeExtendedAdvertisingAPITest, set_periodic_data_test) { advertising_data.push_back(data_item); le_advertising_manager_->SetPeriodicData(advertiser_id_, advertising_data); ASSERT_EQ(OpCode::LE_SET_PERIODIC_ADVERTISING_DATA, test_hci_layer_->GetCommand().GetOpCode()); - EXPECT_CALL( - mock_advertising_callback_, - OnPeriodicAdvertisingDataSet(advertiser_id_, AdvertisingCallback::AdvertisingStatus::SUCCESS)); - test_hci_layer_->IncomingEvent(LeSetPeriodicAdvertisingDataCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + EXPECT_CALL(mock_advertising_callback_, + OnPeriodicAdvertisingDataSet(advertiser_id_, + AdvertisingCallback::AdvertisingStatus::SUCCESS)); + test_hci_layer_->IncomingEvent( + LeSetPeriodicAdvertisingDataCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); sync_client_handler(); } @@ -1551,7 +1467,8 @@ TEST_F(LeExtendedAdvertisingAPITest, set_periodic_data_fragments_test) { GapData data_item{}; data_item.data_.push_back(0xfa); data_item.data_type_ = GapDataType::SERVICE_DATA_128_BIT_UUIDS; - uint8_t uuid[16] = {0xf0, 0x34, 0x9b, 0x5f, 0x80, 0x00, 0x00, 0x80, 0x00, 0x10, 0x00, 0x00, 0x00, 0x10, 0x00, i}; + uint8_t uuid[16] = {0xf0, 0x34, 0x9b, 0x5f, 0x80, 0x00, 0x00, 0x80, + 0x00, 0x10, 0x00, 0x00, 0x00, 0x10, 0x00, i}; std::copy_n(uuid, 16, std::back_inserter(data_item.data_)); uint8_t service_data[232]; std::copy_n(service_data, 232, std::back_inserter(data_item.data_)); @@ -1566,12 +1483,15 @@ TEST_F(LeExtendedAdvertisingAPITest, set_periodic_data_fragments_test) { // Last fragment ASSERT_EQ(OpCode::LE_SET_PERIODIC_ADVERTISING_DATA, test_hci_layer_->GetCommand().GetOpCode()); - EXPECT_CALL( - mock_advertising_callback_, - OnPeriodicAdvertisingDataSet(advertiser_id_, AdvertisingCallback::AdvertisingStatus::SUCCESS)); - test_hci_layer_->IncomingEvent(LeSetPeriodicAdvertisingDataCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); - test_hci_layer_->IncomingEvent(LeSetPeriodicAdvertisingDataCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); - test_hci_layer_->IncomingEvent(LeSetPeriodicAdvertisingDataCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + EXPECT_CALL(mock_advertising_callback_, + OnPeriodicAdvertisingDataSet(advertiser_id_, + AdvertisingCallback::AdvertisingStatus::SUCCESS)); + test_hci_layer_->IncomingEvent( + LeSetPeriodicAdvertisingDataCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + test_hci_layer_->IncomingEvent( + LeSetPeriodicAdvertisingDataCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + test_hci_layer_->IncomingEvent( + LeSetPeriodicAdvertisingDataCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); } TEST_F(LeExtendedAdvertisingAPITest, set_periodic_data_valid_max_252_ad_data_length_test) { @@ -1588,12 +1508,11 @@ TEST_F(LeExtendedAdvertisingAPITest, set_periodic_data_valid_max_252_ad_data_len le_advertising_manager_->SetPeriodicData(advertiser_id_, advertising_data); ASSERT_EQ(OpCode::LE_SET_PERIODIC_ADVERTISING_DATA, test_hci_layer_->GetCommand().GetOpCode()); - EXPECT_CALL( - mock_advertising_callback_, - OnPeriodicAdvertisingDataSet( - advertiser_id_, AdvertisingCallback::AdvertisingStatus::SUCCESS)); + EXPECT_CALL(mock_advertising_callback_, + OnPeriodicAdvertisingDataSet(advertiser_id_, + AdvertisingCallback::AdvertisingStatus::SUCCESS)); test_hci_layer_->IncomingEvent( - LeSetPeriodicAdvertisingDataCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + LeSetPeriodicAdvertisingDataCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); sync_client_handler(); } @@ -1613,26 +1532,23 @@ TEST_F(LeExtendedAdvertisingAPITest, set_periodic_data_valid_253_ad_data_length_ // First fragment auto command = test_hci_layer_->GetCommand(); ASSERT_EQ(command.GetOpCode(), OpCode::LE_SET_PERIODIC_ADVERTISING_DATA); - ASSERT_EQ( - 1ul /* Advertising_Handle */ + 1ul /* Operation */ + 1ul /*Advertising_Data_Length*/ - + 252ul /* Max data length 252 includes AD length and type */, - command.GetPayload().size()); + ASSERT_EQ(1ul /* Advertising_Handle */ + 1ul /* Operation */ + 1ul /*Advertising_Data_Length*/ + + 252ul /* Max data length 252 includes AD length and type */, + command.GetPayload().size()); // Second fragment auto command2 = test_hci_layer_->GetCommand(); ASSERT_EQ(command2.GetOpCode(), OpCode::LE_SET_PERIODIC_ADVERTISING_DATA); - ASSERT_EQ( - 1ul /* Advertising_Handle */ + 1ul /* Operation */ + 1ul /*Advertising_Data_Length*/ - + 1ul /* Remaining 1 byte data */, - command2.GetPayload().size()); + ASSERT_EQ(1ul /* Advertising_Handle */ + 1ul /* Operation */ + 1ul /*Advertising_Data_Length*/ + + 1ul /* Remaining 1 byte data */, + command2.GetPayload().size()); - EXPECT_CALL( - mock_advertising_callback_, - OnPeriodicAdvertisingDataSet( - advertiser_id_, AdvertisingCallback::AdvertisingStatus::SUCCESS)); + EXPECT_CALL(mock_advertising_callback_, + OnPeriodicAdvertisingDataSet(advertiser_id_, + AdvertisingCallback::AdvertisingStatus::SUCCESS)); test_hci_layer_->IncomingEvent( - LeSetPeriodicAdvertisingDataCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + LeSetPeriodicAdvertisingDataCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); test_hci_layer_->IncomingEvent( - LeSetPeriodicAdvertisingDataCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + LeSetPeriodicAdvertisingDataCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); } TEST_F(LeExtendedAdvertisingAPITest, set_periodic_data_invalid_256_ad_data_length_test) { @@ -1646,10 +1562,9 @@ TEST_F(LeExtendedAdvertisingAPITest, set_periodic_data_invalid_256_ad_data_lengt std::copy_n(service_data, 254, std::back_inserter(data_item.data_)); advertising_data.push_back(data_item); - EXPECT_CALL( - mock_advertising_callback_, - OnPeriodicAdvertisingDataSet( - advertiser_id_, AdvertisingCallback::AdvertisingStatus::INTERNAL_ERROR)); + EXPECT_CALL(mock_advertising_callback_, + OnPeriodicAdvertisingDataSet(advertiser_id_, + AdvertisingCallback::AdvertisingStatus::INTERNAL_ERROR)); le_advertising_manager_->SetPeriodicData(advertiser_id_, advertising_data); sync_client_handler(); @@ -1662,16 +1577,17 @@ TEST_F(LeExtendedAdvertisingAPITest, set_perodic_data_with_invalid_length) { GapData data_item{}; data_item.data_.push_back(0xfb); data_item.data_type_ = GapDataType::SERVICE_DATA_128_BIT_UUIDS; - uint8_t uuid[16] = {0xf0, 0x34, 0x9b, 0x5f, 0x80, 0x00, 0x00, 0x80, 0x00, 0x10, 0x00, 0x00, 0x00, 0x10, 0x00, i}; + uint8_t uuid[16] = {0xf0, 0x34, 0x9b, 0x5f, 0x80, 0x00, 0x00, 0x80, + 0x00, 0x10, 0x00, 0x00, 0x00, 0x10, 0x00, i}; std::copy_n(uuid, 16, std::back_inserter(data_item.data_)); uint8_t service_data[200]; std::copy_n(service_data, 200, std::back_inserter(data_item.data_)); advertising_data.push_back(data_item); } - EXPECT_CALL( - mock_advertising_callback_, - OnPeriodicAdvertisingDataSet(advertiser_id_, AdvertisingCallback::AdvertisingStatus::DATA_TOO_LARGE)); + EXPECT_CALL(mock_advertising_callback_, + OnPeriodicAdvertisingDataSet(advertiser_id_, + AdvertisingCallback::AdvertisingStatus::DATA_TOO_LARGE)); le_advertising_manager_->SetPeriodicData(advertiser_id_, advertising_data); sync_client_handler(); @@ -1681,19 +1597,21 @@ TEST_F(LeExtendedAdvertisingAPITest, disable_enable_periodic_advertiser_test) { // disable advertiser le_advertising_manager_->EnablePeriodicAdvertising(advertiser_id_, false, false); ASSERT_EQ(OpCode::LE_SET_PERIODIC_ADVERTISING_ENABLE, test_hci_layer_->GetCommand().GetOpCode()); - EXPECT_CALL( - mock_advertising_callback_, - OnPeriodicAdvertisingEnabled(advertiser_id_, false, AdvertisingCallback::AdvertisingStatus::SUCCESS)); - test_hci_layer_->IncomingEvent(LeSetPeriodicAdvertisingEnableCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + EXPECT_CALL(mock_advertising_callback_, + OnPeriodicAdvertisingEnabled(advertiser_id_, false, + AdvertisingCallback::AdvertisingStatus::SUCCESS)); + test_hci_layer_->IncomingEvent( + LeSetPeriodicAdvertisingEnableCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); sync_client_handler(); // enable advertiser le_advertising_manager_->EnablePeriodicAdvertising(advertiser_id_, true, false); ASSERT_EQ(OpCode::LE_SET_PERIODIC_ADVERTISING_ENABLE, test_hci_layer_->GetCommand().GetOpCode()); - EXPECT_CALL( - mock_advertising_callback_, - OnPeriodicAdvertisingEnabled(advertiser_id_, true, AdvertisingCallback::AdvertisingStatus::SUCCESS)); - test_hci_layer_->IncomingEvent(LeSetPeriodicAdvertisingEnableCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + EXPECT_CALL(mock_advertising_callback_, + OnPeriodicAdvertisingEnabled(advertiser_id_, true, + AdvertisingCallback::AdvertisingStatus::SUCCESS)); + test_hci_layer_->IncomingEvent( + LeSetPeriodicAdvertisingEnableCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); sync_client_handler(); } @@ -1702,11 +1620,10 @@ TEST_F(LeExtendedAdvertisingAPITest, trigger_advertiser_callbacks_if_started_whi auto test_le_address_manager = (TestLeAddressManager*)test_acl_manager_->GetLeAddressManager(); auto id_promise = std::promise{}; auto id_future = id_promise.get_future(); - le_advertising_manager_->RegisterAdvertiser(client_handler_->BindOnce( - [](std::promise promise, uint8_t id, uint8_t /* _status */) { - promise.set_value(id); - }, - std::move(id_promise))); + le_advertising_manager_->RegisterAdvertiser( + client_handler_->BindOnce([](std::promise promise, uint8_t id, + uint8_t /* _status */) { promise.set_value(id); }, + std::move(id_promise))); sync_client_handler(); auto set_id = id_future.get(); @@ -1716,39 +1633,41 @@ TEST_F(LeExtendedAdvertisingAPITest, trigger_advertiser_callbacks_if_started_whi test_le_address_manager->client_->OnPause(); test_hci_layer_->GetCommand(); - test_hci_layer_->IncomingEvent(LeSetExtendedAdvertisingEnableCompleteBuilder::Create(1, ErrorCode::SUCCESS)); + test_hci_layer_->IncomingEvent( + LeSetExtendedAdvertisingEnableCompleteBuilder::Create(1, ErrorCode::SUCCESS)); sync_client_handler(); // act le_advertising_manager_->StartAdvertising( - set_id, - {}, - 0, - base::BindOnce( - [](std::promise promise, uint8_t status) { - promise.set_value((ErrorCode)status); - }, - std::move(status_promise)), - base::Bind([](uint8_t /* _status */) {}), - base::Bind([](Address /* _address */, AddressType /* _address_type */) {}), - base::Bind([](ErrorCode /* _status */, uint8_t /* _unused_1 */, uint8_t /* _unused_2 */) {}), - client_handler_); + set_id, {}, 0, + base::BindOnce([](std::promise promise, + uint8_t status) { promise.set_value((ErrorCode)status); }, + std::move(status_promise)), + base::Bind([](uint8_t /* _status */) {}), + base::Bind([](Address /* _address */, AddressType /* _address_type */) {}), + base::Bind( + [](ErrorCode /* _status */, uint8_t /* _unused_1 */, uint8_t /* _unused_2 */) {}), + client_handler_); test_hci_layer_->GetCommand(); - test_hci_layer_->IncomingEvent(LeSetExtendedAdvertisingParametersCompleteBuilder::Create(1, ErrorCode::SUCCESS, 0)); + test_hci_layer_->IncomingEvent( + LeSetExtendedAdvertisingParametersCompleteBuilder::Create(1, ErrorCode::SUCCESS, 0)); test_hci_layer_->GetCommand(); - test_hci_layer_->IncomingEvent(LeSetExtendedScanResponseDataCompleteBuilder::Create(1, ErrorCode::SUCCESS)); + test_hci_layer_->IncomingEvent( + LeSetExtendedScanResponseDataCompleteBuilder::Create(1, ErrorCode::SUCCESS)); test_hci_layer_->GetCommand(); - test_hci_layer_->IncomingEvent(LeSetExtendedAdvertisingDataCompleteBuilder::Create(1, ErrorCode::SUCCESS)); + test_hci_layer_->IncomingEvent( + LeSetExtendedAdvertisingDataCompleteBuilder::Create(1, ErrorCode::SUCCESS)); EXPECT_EQ(status_future.wait_for(std::chrono::milliseconds(100)), std::future_status::timeout); test_le_address_manager->client_->OnResume(); test_hci_layer_->GetCommand(); - test_hci_layer_->IncomingEvent(LeSetExtendedAdvertisingEnableCompleteBuilder::Create(1, ErrorCode::SUCCESS)); + test_hci_layer_->IncomingEvent( + LeSetExtendedAdvertisingEnableCompleteBuilder::Create(1, ErrorCode::SUCCESS)); // assert EXPECT_EQ(status_future.get(), ErrorCode::SUCCESS); @@ -1763,20 +1682,20 @@ TEST_F(LeExtendedAdvertisingAPITest, duration_maxevents_restored_on_resume) { uint8_t max_extended_advertising_events = 100; // enable advertiser - le_advertising_manager_->EnableAdvertiser( - advertiser_id_, true, duration, max_extended_advertising_events); + le_advertising_manager_->EnableAdvertiser(advertiser_id_, true, duration, + max_extended_advertising_events); ASSERT_EQ(OpCode::LE_SET_EXTENDED_ADVERTISING_ENABLE, test_hci_layer_->GetCommand().GetOpCode()); - EXPECT_CALL( - mock_advertising_callback_, - OnAdvertisingEnabled(advertiser_id_, true, AdvertisingCallback::AdvertisingStatus::SUCCESS)); + EXPECT_CALL(mock_advertising_callback_, + OnAdvertisingEnabled(advertiser_id_, true, + AdvertisingCallback::AdvertisingStatus::SUCCESS)); test_hci_layer_->IncomingEvent( - LeSetExtendedAdvertisingEnableCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + LeSetExtendedAdvertisingEnableCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); test_le_address_manager->client_->OnPause(); // verify advertising is disabled onPause ASSERT_EQ(OpCode::LE_SET_EXTENDED_ADVERTISING_ENABLE, test_hci_layer_->GetCommand().GetOpCode()); test_hci_layer_->IncomingEvent( - LeSetExtendedAdvertisingEnableCompleteBuilder::Create(1, ErrorCode::SUCCESS)); + LeSetExtendedAdvertisingEnableCompleteBuilder::Create(1, ErrorCode::SUCCESS)); sync_client_handler(); test_le_address_manager->client_->OnResume(); @@ -1784,7 +1703,7 @@ TEST_F(LeExtendedAdvertisingAPITest, duration_maxevents_restored_on_resume) { auto command = test_hci_layer_->GetCommand(); ASSERT_EQ(OpCode::LE_SET_EXTENDED_ADVERTISING_ENABLE, command.GetOpCode()); auto enable_command_view = - LeSetExtendedAdvertisingEnableView::Create(LeAdvertisingCommandView::Create(command)); + LeSetExtendedAdvertisingEnableView::Create(LeAdvertisingCommandView::Create(command)); ASSERT_TRUE(enable_command_view.IsValid()); ASSERT_EQ(bluetooth::hci::Enable::ENABLED, enable_command_view.GetEnable()); auto enabled_sets = enable_command_view.GetEnabledSets(); @@ -1792,7 +1711,7 @@ TEST_F(LeExtendedAdvertisingAPITest, duration_maxevents_restored_on_resume) { ASSERT_EQ(duration, enabled_sets[0].duration_); ASSERT_EQ(max_extended_advertising_events, enabled_sets[0].max_extended_advertising_events_); test_hci_layer_->IncomingEvent( - LeSetExtendedAdvertisingEnableCompleteBuilder::Create(1, ErrorCode::SUCCESS)); + LeSetExtendedAdvertisingEnableCompleteBuilder::Create(1, ErrorCode::SUCCESS)); sync_client_handler(); } @@ -1809,7 +1728,7 @@ TEST_F(LeExtendedAdvertisingAPITest, no_callbacks_on_pause) { test_le_address_manager->client_->OnPause(); test_hci_layer_->GetCommand(); test_hci_layer_->IncomingEvent( - LeSetExtendedAdvertisingEnableCompleteBuilder::Create(1, ErrorCode::SUCCESS)); + LeSetExtendedAdvertisingEnableCompleteBuilder::Create(1, ErrorCode::SUCCESS)); sync_client_handler(); } @@ -1820,7 +1739,7 @@ TEST_F(LeExtendedAdvertisingAPITest, no_callbacks_on_resume) { test_le_address_manager->client_->OnPause(); test_hci_layer_->GetCommand(); test_hci_layer_->IncomingEvent( - LeSetExtendedAdvertisingEnableCompleteBuilder::Create(1, ErrorCode::SUCCESS)); + LeSetExtendedAdvertisingEnableCompleteBuilder::Create(1, ErrorCode::SUCCESS)); sync_client_handler(); // expect @@ -1830,7 +1749,7 @@ TEST_F(LeExtendedAdvertisingAPITest, no_callbacks_on_resume) { test_le_address_manager->client_->OnResume(); test_hci_layer_->GetCommand(); test_hci_layer_->IncomingEvent( - LeSetExtendedAdvertisingEnableCompleteBuilder::Create(1, ErrorCode::SUCCESS)); + LeSetExtendedAdvertisingEnableCompleteBuilder::Create(1, ErrorCode::SUCCESS)); sync_client_handler(); } @@ -1844,15 +1763,9 @@ TEST_F(LeExtendedAdvertisingManagerTest, use_rpa) { config.requested_advertiser_address_type = AdvertiserAddressType::RESOLVABLE_RANDOM; config.channel_map = 1; - le_advertising_manager_->ExtendedCreateAdvertiser( - kAdvertiserClientIdJni, - 0x00, - config, - scan_callback, - set_terminated_callback, - 0, - 0, - client_handler_); + le_advertising_manager_->ExtendedCreateAdvertiser(kAdvertiserClientIdJni, 0x00, config, + scan_callback, set_terminated_callback, 0, 0, + client_handler_); auto command = LeAdvertisingCommandView::Create(test_hci_layer_->GetCommand()); // assert @@ -1860,7 +1773,7 @@ TEST_F(LeExtendedAdvertisingManagerTest, use_rpa) { EXPECT_EQ(command.GetOpCode(), OpCode::LE_SET_EXTENDED_ADVERTISING_PARAMETERS); auto set_parameters_command = - LeSetExtendedAdvertisingParametersView::Create(LeAdvertisingCommandView::Create(command)); + LeSetExtendedAdvertisingParametersView::Create(LeAdvertisingCommandView::Create(command)); ASSERT_TRUE(set_parameters_command.IsValid()); EXPECT_EQ(set_parameters_command.GetOwnAddressType(), OwnAddressType::RANDOM_DEVICE_ADDRESS); } @@ -1873,27 +1786,21 @@ TEST_F(LeExtendedAdvertisingManagerTest, use_non_resolvable_address) { config.requested_advertiser_address_type = AdvertiserAddressType::NONRESOLVABLE_RANDOM; config.channel_map = 1; - le_advertising_manager_->ExtendedCreateAdvertiser( - kAdvertiserClientIdJni, - 0x00, - config, - scan_callback, - set_terminated_callback, - 0, - 0, - client_handler_); - - ASSERT_EQ( - test_hci_layer_->GetCommand().GetOpCode(), OpCode::LE_SET_EXTENDED_ADVERTISING_PARAMETERS); + le_advertising_manager_->ExtendedCreateAdvertiser(kAdvertiserClientIdJni, 0x00, config, + scan_callback, set_terminated_callback, 0, 0, + client_handler_); + + ASSERT_EQ(test_hci_layer_->GetCommand().GetOpCode(), + OpCode::LE_SET_EXTENDED_ADVERTISING_PARAMETERS); test_hci_layer_->IncomingEvent(LeSetExtendedAdvertisingParametersCompleteBuilder::Create( - uint8_t{1}, ErrorCode::SUCCESS, static_cast(-23))); + uint8_t{1}, ErrorCode::SUCCESS, static_cast(-23))); auto command = LeAdvertisingCommandView::Create(test_hci_layer_->GetCommand()); ASSERT_TRUE(command.IsValid()); ASSERT_EQ(command.GetOpCode(), OpCode::LE_SET_ADVERTISING_SET_RANDOM_ADDRESS); auto set_address_command = - LeSetAdvertisingSetRandomAddressView::Create(LeAdvertisingCommandView::Create(command)); + LeSetAdvertisingSetRandomAddressView::Create(LeAdvertisingCommandView::Create(command)); ASSERT_TRUE(set_address_command.IsValid()); EXPECT_EQ(set_address_command.GetOpCode(), OpCode::LE_SET_ADVERTISING_SET_RANDOM_ADDRESS); @@ -1911,15 +1818,9 @@ TEST_F(LeExtendedAdvertisingManagerTest, use_public_address_type_if_public_addre config.requested_advertiser_address_type = AdvertiserAddressType::RESOLVABLE_RANDOM; config.channel_map = 1; - le_advertising_manager_->ExtendedCreateAdvertiser( - kAdvertiserClientIdJni, - 0x00, - config, - scan_callback, - set_terminated_callback, - 0, - 0, - client_handler_); + le_advertising_manager_->ExtendedCreateAdvertiser(kAdvertiserClientIdJni, 0x00, config, + scan_callback, set_terminated_callback, 0, 0, + client_handler_); auto command = LeAdvertisingCommandView::Create(test_hci_layer_->GetCommand()); // assert @@ -1927,15 +1828,14 @@ TEST_F(LeExtendedAdvertisingManagerTest, use_public_address_type_if_public_addre EXPECT_EQ(command.GetOpCode(), OpCode::LE_SET_EXTENDED_ADVERTISING_PARAMETERS); auto set_parameters_command = - LeSetExtendedAdvertisingParametersView::Create(LeAdvertisingCommandView::Create(command)); + LeSetExtendedAdvertisingParametersView::Create(LeAdvertisingCommandView::Create(command)); ASSERT_TRUE(set_parameters_command.IsValid()); EXPECT_EQ(set_parameters_command.GetOwnAddressType(), OwnAddressType::PUBLIC_DEVICE_ADDRESS); } -TEST_F_WITH_FLAGS( - LeExtendedAdvertisingManagerTest, - use_nrpa_if_public_address_policy_non_connectable, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, nrpa_non_connectable_adv))) { +TEST_F_WITH_FLAGS(LeExtendedAdvertisingManagerTest, + use_nrpa_if_public_address_policy_non_connectable, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, nrpa_non_connectable_adv))) { // arrange: use PUBLIC address policy test_acl_manager_->SetAddressPolicy(LeAddressManager::AddressPolicy::USE_PUBLIC_ADDRESS); @@ -1945,26 +1845,20 @@ TEST_F_WITH_FLAGS( config.channel_map = 1; config.connectable = false; - le_advertising_manager_->ExtendedCreateAdvertiser( - kAdvertiserClientIdJni, - 0x00, - config, - scan_callback, - set_terminated_callback, - 0, - 0, - client_handler_); - ASSERT_EQ( - test_hci_layer_->GetCommand().GetOpCode(), OpCode::LE_SET_EXTENDED_ADVERTISING_PARAMETERS); + le_advertising_manager_->ExtendedCreateAdvertiser(kAdvertiserClientIdJni, 0x00, config, + scan_callback, set_terminated_callback, 0, 0, + client_handler_); + ASSERT_EQ(test_hci_layer_->GetCommand().GetOpCode(), + OpCode::LE_SET_EXTENDED_ADVERTISING_PARAMETERS); test_hci_layer_->IncomingEvent(LeSetExtendedAdvertisingParametersCompleteBuilder::Create( - uint8_t{1}, ErrorCode::SUCCESS, static_cast(-23))); + uint8_t{1}, ErrorCode::SUCCESS, static_cast(-23))); auto command = LeAdvertisingCommandView::Create(test_hci_layer_->GetCommand()); ASSERT_TRUE(command.IsValid()); ASSERT_EQ(command.GetOpCode(), OpCode::LE_SET_ADVERTISING_SET_RANDOM_ADDRESS); auto set_address_command = - LeSetAdvertisingSetRandomAddressView::Create(LeAdvertisingCommandView::Create(command)); + LeSetAdvertisingSetRandomAddressView::Create(LeAdvertisingCommandView::Create(command)); ASSERT_TRUE(set_address_command.IsValid()); EXPECT_EQ(set_address_command.GetOpCode(), OpCode::LE_SET_ADVERTISING_SET_RANDOM_ADDRESS); @@ -1973,10 +1867,9 @@ TEST_F_WITH_FLAGS( EXPECT_EQ(address.data()[5] >> 6, 0b00); } -TEST_F_WITH_FLAGS( - LeExtendedAdvertisingManagerTest, - use_public_if_requested_with_public_address_policy_non_connectable, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, nrpa_non_connectable_adv))) { +TEST_F_WITH_FLAGS(LeExtendedAdvertisingManagerTest, + use_public_if_requested_with_public_address_policy_non_connectable, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, nrpa_non_connectable_adv))) { // arrange: use PUBLIC address policy test_acl_manager_->SetAddressPolicy(LeAddressManager::AddressPolicy::USE_PUBLIC_ADDRESS); @@ -1986,15 +1879,9 @@ TEST_F_WITH_FLAGS( config.channel_map = 1; config.connectable = false; - le_advertising_manager_->ExtendedCreateAdvertiser( - kAdvertiserClientIdJni, - 0x00, - config, - scan_callback, - set_terminated_callback, - 0, - 0, - client_handler_); + le_advertising_manager_->ExtendedCreateAdvertiser(kAdvertiserClientIdJni, 0x00, config, + scan_callback, set_terminated_callback, 0, 0, + client_handler_); auto command = LeAdvertisingCommandView::Create(test_hci_layer_->GetCommand()); // assert @@ -2002,7 +1889,7 @@ TEST_F_WITH_FLAGS( EXPECT_EQ(command.GetOpCode(), OpCode::LE_SET_EXTENDED_ADVERTISING_PARAMETERS); auto set_parameters_command = - LeSetExtendedAdvertisingParametersView::Create(LeAdvertisingCommandView::Create(command)); + LeSetExtendedAdvertisingParametersView::Create(LeAdvertisingCommandView::Create(command)); ASSERT_TRUE(set_parameters_command.IsValid()); EXPECT_EQ(set_parameters_command.GetOwnAddressType(), OwnAddressType::PUBLIC_DEVICE_ADDRESS); } diff --git a/system/gd/hci/le_iso_interface.h b/system/gd/hci/le_iso_interface.h index c02fbb3b216..33aa1c4461d 100644 --- a/system/gd/hci/le_iso_interface.h +++ b/system/gd/hci/le_iso_interface.h @@ -23,12 +23,9 @@ namespace bluetooth { namespace hci { constexpr hci::SubeventCode LeIsoEvents[] = { - hci::SubeventCode::CIS_ESTABLISHED, - hci::SubeventCode::CIS_REQUEST, - hci::SubeventCode::CREATE_BIG_COMPLETE, - hci::SubeventCode::TERMINATE_BIG_COMPLETE, - hci::SubeventCode::BIG_SYNC_ESTABLISHED, - hci::SubeventCode::BIG_SYNC_LOST, + hci::SubeventCode::CIS_ESTABLISHED, hci::SubeventCode::CIS_REQUEST, + hci::SubeventCode::CREATE_BIG_COMPLETE, hci::SubeventCode::TERMINATE_BIG_COMPLETE, + hci::SubeventCode::BIG_SYNC_ESTABLISHED, hci::SubeventCode::BIG_SYNC_LOST, }; typedef CommandInterface LeIsoInterface; diff --git a/system/gd/hci/le_periodic_sync_manager.h b/system/gd/hci/le_periodic_sync_manager.h index ff80291323e..dab7ff6c1a2 100644 --- a/system/gd/hci/le_periodic_sync_manager.h +++ b/system/gd/hci/le_periodic_sync_manager.h @@ -62,12 +62,8 @@ struct PeriodicSyncStates { }; struct PendingPeriodicSyncRequest { - PendingPeriodicSyncRequest( - uint8_t advertiser_sid, - AddressWithType address_with_type, - uint16_t skip, - uint16_t sync_timeout, - os::Handler* handler) + PendingPeriodicSyncRequest(uint8_t advertiser_sid, AddressWithType address_with_type, + uint16_t skip, uint16_t sync_timeout, os::Handler* handler) : advertiser_sid(advertiser_sid), address_with_type(std::move(address_with_type)), skip(skip), @@ -82,36 +78,35 @@ struct PendingPeriodicSyncRequest { }; class PeriodicSyncManager { - public: +public: explicit PeriodicSyncManager(ScanningCallback* callbacks) - : le_scanning_interface_(nullptr), handler_(nullptr), callbacks_(callbacks), sync_received_callback_id(0) {} + : le_scanning_interface_(nullptr), + handler_(nullptr), + callbacks_(callbacks), + sync_received_callback_id(0) {} void Init(hci::LeScanningInterface* le_scanning_interface, os::Handler* handler) { le_scanning_interface_ = le_scanning_interface; handler_ = handler; } - void SetScanningCallback(ScanningCallback* callbacks) { - callbacks_ = callbacks; - } + void SetScanningCallback(ScanningCallback* callbacks) { callbacks_ = callbacks; } void StartSync(const PeriodicSyncStates& request, uint16_t skip, uint16_t sync_timeout) { if (periodic_syncs_.size() >= kMaxSyncTransactions) { int status = static_cast(ErrorCode::CONNECTION_REJECTED_LIMITED_RESOURCES); - callbacks_->OnPeriodicSyncStarted( - request.request_id, status, 0, request.advertiser_sid, request.address_with_type, 0, 0); + callbacks_->OnPeriodicSyncStarted(request.request_id, status, 0, request.advertiser_sid, + request.address_with_type, 0, 0); return; } auto address_type = request.address_with_type.GetAddressType(); - log::assert_that( - (address_type == AddressType::PUBLIC_DEVICE_ADDRESS || - address_type == AddressType::RANDOM_DEVICE_ADDRESS), - "Invalid address type {}", - AddressTypeText(address_type)); + log::assert_that((address_type == AddressType::PUBLIC_DEVICE_ADDRESS || + address_type == AddressType::RANDOM_DEVICE_ADDRESS), + "Invalid address type {}", AddressTypeText(address_type)); periodic_syncs_.emplace_back(request); log::debug("address = {}, sid = {}", request.address_with_type, request.advertiser_sid); - pending_sync_requests_.emplace_back( - request.advertiser_sid, request.address_with_type, skip, sync_timeout, handler_); + pending_sync_requests_.emplace_back(request.advertiser_sid, request.address_with_type, skip, + sync_timeout, handler_); HandleNextRequest(); } @@ -121,14 +116,14 @@ class PeriodicSyncManager { if (periodic_sync == periodic_syncs_.end()) { log::error("[PSync]: invalid index for handle {}", handle); le_scanning_interface_->EnqueueCommand( - hci::LePeriodicAdvertisingTerminateSyncBuilder::Create(handle), - handler_->BindOnce(check_complete)); + hci::LePeriodicAdvertisingTerminateSyncBuilder::Create(handle), + handler_->BindOnce(check_complete)); return; }; periodic_syncs_.erase(periodic_sync); le_scanning_interface_->EnqueueCommand( - hci::LePeriodicAdvertisingTerminateSyncBuilder::Create(handle), - handler_->BindOnce(check_complete)); + hci::LePeriodicAdvertisingTerminateSyncBuilder::Create(handle), + handler_->BindOnce(check_complete)); } void CancelCreateSync(uint8_t adv_sid, Address address) { @@ -142,11 +137,10 @@ class PeriodicSyncManager { if (periodic_sync->sync_state == PERIODIC_SYNC_STATE_PENDING) { log::warn("[PSync]: Sync state is pending"); le_scanning_interface_->EnqueueCommand( - hci::LePeriodicAdvertisingCreateSyncCancelBuilder::Create(), - handler_->BindOnceOn( - this, - &PeriodicSyncManager::HandlePeriodicAdvertisingCreateSyncCancelStatus< - LePeriodicAdvertisingCreateSyncCancelCompleteView>)); + hci::LePeriodicAdvertisingCreateSyncCancelBuilder::Create(), + handler_->BindOnceOn( + this, &PeriodicSyncManager::HandlePeriodicAdvertisingCreateSyncCancelStatus< + LePeriodicAdvertisingCreateSyncCancelCompleteView>)); } else if (periodic_sync->sync_state == PERIODIC_SYNC_STATE_IDLE) { log::debug("[PSync]: Removing Sync request from queue"); CleanUpRequest(adv_sid, address); @@ -154,8 +148,8 @@ class PeriodicSyncManager { periodic_syncs_.erase(periodic_sync); } - void TransferSync( - const Address& address, uint16_t service_data, uint16_t sync_handle, int pa_source, uint16_t connection_handle) { + void TransferSync(const Address& address, uint16_t service_data, uint16_t sync_handle, + int pa_source, uint16_t connection_handle) { if (periodic_sync_transfers_.size() >= kMaxSyncTransactions) { int status = static_cast(ErrorCode::CONNECTION_REJECTED_LIMITED_RESOURCES); callbacks_->OnPeriodicSyncTransferred(pa_source, status, address); @@ -165,16 +159,17 @@ class PeriodicSyncManager { PeriodicSyncTransferStates request{pa_source, connection_handle, address}; periodic_sync_transfers_.emplace_back(request); le_scanning_interface_->EnqueueCommand( - hci::LePeriodicAdvertisingSyncTransferBuilder::Create(connection_handle, service_data, sync_handle), - handler_->BindOnceOn( - this, - &PeriodicSyncManager::HandlePeriodicAdvertisingSyncTransferComplete< - LePeriodicAdvertisingSyncTransferCompleteView>, - connection_handle)); + hci::LePeriodicAdvertisingSyncTransferBuilder::Create(connection_handle, service_data, + sync_handle), + handler_->BindOnceOn( + this, + &PeriodicSyncManager::HandlePeriodicAdvertisingSyncTransferComplete< + LePeriodicAdvertisingSyncTransferCompleteView>, + connection_handle)); } - void SyncSetInfo( - const Address& address, uint16_t service_data, uint8_t adv_handle, int pa_source, uint16_t connection_handle) { + void SyncSetInfo(const Address& address, uint16_t service_data, uint8_t adv_handle, int pa_source, + uint16_t connection_handle) { if (periodic_sync_transfers_.size() >= kMaxSyncTransactions) { int status = static_cast(ErrorCode::CONNECTION_REJECTED_LIMITED_RESOURCES); callbacks_->OnPeriodicSyncTransferred(pa_source, status, address); @@ -183,29 +178,32 @@ class PeriodicSyncManager { PeriodicSyncTransferStates request{pa_source, connection_handle, address}; periodic_sync_transfers_.emplace_back(request); le_scanning_interface_->EnqueueCommand( - hci::LePeriodicAdvertisingSetInfoTransferBuilder::Create(connection_handle, service_data, adv_handle), - handler_->BindOnceOn( - this, - &PeriodicSyncManager::HandlePeriodicAdvertisingSyncTransferComplete< - LePeriodicAdvertisingSetInfoTransferCompleteView>, - connection_handle)); + hci::LePeriodicAdvertisingSetInfoTransferBuilder::Create(connection_handle, + service_data, adv_handle), + handler_->BindOnceOn( + this, + &PeriodicSyncManager::HandlePeriodicAdvertisingSyncTransferComplete< + LePeriodicAdvertisingSetInfoTransferCompleteView>, + connection_handle)); } - void SyncTxParameters( - const Address& /* address */, uint8_t mode, uint16_t skip, uint16_t timeout, int reg_id) { + void SyncTxParameters(const Address& /* address */, uint8_t mode, uint16_t skip, uint16_t timeout, + int reg_id) { log::debug("[PAST]: mode={}, skip={}, timeout={}", mode, skip, timeout); auto sync_cte_type = static_cast( - static_cast(PeriodicSyncCteType::AVOID_AOA_CONSTANT_TONE_EXTENSION) | - static_cast(PeriodicSyncCteType::AVOID_AOD_CONSTANT_TONE_EXTENSION_WITH_ONE_US_SLOTS) | - static_cast(PeriodicSyncCteType::AVOID_AOD_CONSTANT_TONE_EXTENSION_WITH_TWO_US_SLOTS)); + static_cast(PeriodicSyncCteType::AVOID_AOA_CONSTANT_TONE_EXTENSION) | + static_cast( + PeriodicSyncCteType::AVOID_AOD_CONSTANT_TONE_EXTENSION_WITH_ONE_US_SLOTS) | + static_cast( + PeriodicSyncCteType::AVOID_AOD_CONSTANT_TONE_EXTENSION_WITH_TWO_US_SLOTS)); sync_received_callback_registered_ = true; sync_received_callback_id = reg_id; le_scanning_interface_->EnqueueCommand( - hci::LeSetDefaultPeriodicAdvertisingSyncTransferParametersBuilder::Create( - static_cast(mode), skip, timeout, sync_cte_type), - handler_->BindOnce( - check_complete)); + hci::LeSetDefaultPeriodicAdvertisingSyncTransferParametersBuilder::Create( + static_cast(mode), skip, timeout, sync_cte_type), + handler_->BindOnce(check_complete< + LeSetDefaultPeriodicAdvertisingSyncTransferParametersCompleteView>)); } template @@ -220,24 +218,15 @@ class PeriodicSyncManager { if (status != ErrorCode::SUCCESS) { auto& request = pending_sync_requests_.front(); request.sync_timeout_alarm.Cancel(); - log::warn( - "Got a Command status {}, status {}, SID={:04X}, bd_addr={}", - OpCodeText(view.GetCommandOpCode()), - ErrorCodeText(status), - request.advertiser_sid, - request.address_with_type); + log::warn("Got a Command status {}, status {}, SID={:04X}, bd_addr={}", + OpCodeText(view.GetCommandOpCode()), ErrorCodeText(status), request.advertiser_sid, + request.address_with_type); uint8_t adv_sid = request.advertiser_sid; AddressWithType address_with_type = request.address_with_type; auto sync = GetSyncFromAddressWithTypeAndSid(address_with_type, adv_sid); - callbacks_->OnPeriodicSyncStarted( - sync->request_id, - (uint8_t)status, - 0, - sync->advertiser_sid, - request.address_with_type, - 0, - 0); + callbacks_->OnPeriodicSyncStarted(sync->request_id, (uint8_t)status, 0, sync->advertiser_sid, + request.address_with_type, 0, 0); periodic_syncs_.erase(sync); AdvanceRequest(); } @@ -255,33 +244,27 @@ class PeriodicSyncManager { if (status != ErrorCode::SUCCESS) { auto& request = pending_sync_requests_.front(); request.sync_timeout_alarm.Cancel(); - log::warn( - "Got a Command complete {}, status {}, SID={:04X}, bd_addr={}", - OpCodeText(view.GetCommandOpCode()), - ErrorCodeText(status), - request.advertiser_sid, - request.address_with_type); + log::warn("Got a Command complete {}, status {}, SID={:04X}, bd_addr={}", + OpCodeText(view.GetCommandOpCode()), ErrorCodeText(status), request.advertiser_sid, + request.address_with_type); AdvanceRequest(); } } template - void HandlePeriodicAdvertisingSyncTransferComplete(uint16_t connection_handle, CommandCompleteView view) { + void HandlePeriodicAdvertisingSyncTransferComplete(uint16_t connection_handle, + CommandCompleteView view) { log::assert_that(view.IsValid(), "assert failed: view.IsValid()"); auto status_view = View::Create(view); log::assert_that(status_view.IsValid(), "assert failed: status_view.IsValid()"); if (status_view.GetStatus() != ErrorCode::SUCCESS) { - log::warn( - "Got a Command complete {}, status {}, connection_handle {}", - OpCodeText(view.GetCommandOpCode()), - ErrorCodeText(status_view.GetStatus()), - connection_handle); + log::warn("Got a Command complete {}, status {}, connection_handle {}", + OpCodeText(view.GetCommandOpCode()), ErrorCodeText(status_view.GetStatus()), + connection_handle); } else { - log::debug( - "Got a Command complete {}, status {}, connection_handle {}", - OpCodeText(view.GetCommandOpCode()), - ErrorCodeText(status_view.GetStatus()), - connection_handle); + log::debug("Got a Command complete {}, status {}, connection_handle {}", + OpCodeText(view.GetCommandOpCode()), ErrorCodeText(status_view.GetStatus()), + connection_handle); } auto periodic_sync_transfer = GetSyncTransferRequestFromConnectionHandle(connection_handle); @@ -290,32 +273,33 @@ class PeriodicSyncManager { return; }; - callbacks_->OnPeriodicSyncTransferred( - periodic_sync_transfer->pa_source, (uint16_t)status_view.GetStatus(), periodic_sync_transfer->addr); + callbacks_->OnPeriodicSyncTransferred(periodic_sync_transfer->pa_source, + (uint16_t)status_view.GetStatus(), + periodic_sync_transfer->addr); periodic_sync_transfers_.erase(periodic_sync_transfer); } - void HandleLePeriodicAdvertisingSyncEstablished(LePeriodicAdvertisingSyncEstablishedView event_view) { + void HandleLePeriodicAdvertisingSyncEstablished( + LePeriodicAdvertisingSyncEstablishedView event_view) { log::assert_that(event_view.IsValid(), "assert failed: event_view.IsValid()"); log::debug( - "[PSync]: status={}, sync_handle={}, address={}, s_id={}, address_type={}, adv_phy={}, " - "adv_interval={}, clock_acc={}", - (uint16_t)event_view.GetStatus(), - event_view.GetSyncHandle(), - AddressWithType(event_view.GetAdvertiserAddress(), event_view.GetAdvertiserAddressType()), - event_view.GetAdvertisingSid(), - (uint16_t)event_view.GetAdvertiserAddressType(), - (uint16_t)event_view.GetAdvertiserPhy(), - event_view.GetPeriodicAdvertisingInterval(), - (uint16_t)event_view.GetAdvertiserClockAccuracy()); - - auto pending_sync_request = - GetPendingSyncFromAddressAndSid(event_view.GetAdvertiserAddress(), event_view.GetAdvertisingSid()); + "[PSync]: status={}, sync_handle={}, address={}, s_id={}, address_type={}, adv_phy={}, " + "adv_interval={}, clock_acc={}", + (uint16_t)event_view.GetStatus(), event_view.GetSyncHandle(), + AddressWithType(event_view.GetAdvertiserAddress(), + event_view.GetAdvertiserAddressType()), + event_view.GetAdvertisingSid(), (uint16_t)event_view.GetAdvertiserAddressType(), + (uint16_t)event_view.GetAdvertiserPhy(), event_view.GetPeriodicAdvertisingInterval(), + (uint16_t)event_view.GetAdvertiserClockAccuracy()); + + auto pending_sync_request = GetPendingSyncFromAddressAndSid(event_view.GetAdvertiserAddress(), + event_view.GetAdvertisingSid()); if (pending_sync_request != pending_sync_requests_.end()) { pending_sync_request->sync_timeout_alarm.Cancel(); } - auto address_with_type = AddressWithType(event_view.GetAdvertiserAddress(), event_view.GetAdvertiserAddressType()); + auto address_with_type = AddressWithType(event_view.GetAdvertiserAddress(), + event_view.GetAdvertiserAddressType()); auto peer_address_type = address_with_type.GetAddressType(); AddressType temp_address_type; switch (peer_address_type) { @@ -330,28 +314,25 @@ class PeriodicSyncManager { } auto periodic_sync = GetSyncFromAddressWithTypeAndSid( - AddressWithType(event_view.GetAdvertiserAddress(), temp_address_type), event_view.GetAdvertisingSid()); + AddressWithType(event_view.GetAdvertiserAddress(), temp_address_type), + event_view.GetAdvertisingSid()); if (periodic_sync == periodic_syncs_.end()) { log::warn("[PSync]: Invalid address and sid for sync established"); if (event_view.GetStatus() == ErrorCode::SUCCESS) { log::warn("Terminate sync"); le_scanning_interface_->EnqueueCommand( - hci::LePeriodicAdvertisingTerminateSyncBuilder::Create(event_view.GetSyncHandle()), - handler_->BindOnce(check_complete)); + hci::LePeriodicAdvertisingTerminateSyncBuilder::Create(event_view.GetSyncHandle()), + handler_->BindOnce(check_complete)); } AdvanceRequest(); return; } periodic_sync->sync_handle = event_view.GetSyncHandle(); periodic_sync->sync_state = PERIODIC_SYNC_STATE_ESTABLISHED; - callbacks_->OnPeriodicSyncStarted( - periodic_sync->request_id, - (uint8_t)event_view.GetStatus(), - event_view.GetSyncHandle(), - event_view.GetAdvertisingSid(), - address_with_type, - (uint16_t)event_view.GetAdvertiserPhy(), - event_view.GetPeriodicAdvertisingInterval()); + callbacks_->OnPeriodicSyncStarted(periodic_sync->request_id, (uint8_t)event_view.GetStatus(), + event_view.GetSyncHandle(), event_view.GetAdvertisingSid(), + address_with_type, (uint16_t)event_view.GetAdvertiserPhy(), + event_view.GetPeriodicAdvertisingInterval()); if (com::android::bluetooth::flags::leaudio_broadcast_feature_support()) { if (event_view.GetStatus() != ErrorCode::SUCCESS) { @@ -365,14 +346,11 @@ class PeriodicSyncManager { void HandleLePeriodicAdvertisingReport(LePeriodicAdvertisingReportView event_view) { log::assert_that(event_view.IsValid(), "assert failed: event_view.IsValid()"); log::debug( - "[PSync]: sync_handle = {}, tx_power = {}, rssi = {},cte_type = {}, data_status = {}, " - "data_len = {}", - event_view.GetSyncHandle(), - event_view.GetTxPower(), - event_view.GetRssi(), - (uint16_t)event_view.GetCteType(), - (uint16_t)event_view.GetDataStatus(), - (uint16_t)event_view.GetData().size()); + "[PSync]: sync_handle = {}, tx_power = {}, rssi = {},cte_type = {}, data_status = {}, " + "data_len = {}", + event_view.GetSyncHandle(), event_view.GetTxPower(), event_view.GetRssi(), + (uint16_t)event_view.GetCteType(), (uint16_t)event_view.GetDataStatus(), + (uint16_t)event_view.GetData().size()); uint16_t sync_handle = event_view.GetSyncHandle(); auto periodic_sync = GetEstablishedSyncFromHandle(sync_handle); @@ -382,21 +360,19 @@ class PeriodicSyncManager { } auto complete_advertising_data = - com::android::bluetooth::flags::le_periodic_scanning_reassembler() - ? scanning_reassembler_.ProcessPeriodicAdvertisingReport( - sync_handle, DataStatus(event_view.GetDataStatus()), event_view.GetData()) - : event_view.GetData(); + com::android::bluetooth::flags::le_periodic_scanning_reassembler() + ? scanning_reassembler_.ProcessPeriodicAdvertisingReport( + sync_handle, DataStatus(event_view.GetDataStatus()), + event_view.GetData()) + : event_view.GetData(); if (!complete_advertising_data.has_value()) { return; } log::debug("{}", "[PSync]: invoking callback"); - callbacks_->OnPeriodicSyncReport( - sync_handle, - event_view.GetTxPower(), - event_view.GetRssi(), - (uint16_t)event_view.GetDataStatus(), - complete_advertising_data.value()); + callbacks_->OnPeriodicSyncReport(sync_handle, event_view.GetTxPower(), event_view.GetRssi(), + (uint16_t)event_view.GetDataStatus(), + complete_advertising_data.value()); } void HandleLePeriodicAdvertisingSyncLost(LePeriodicAdvertisingSyncLostView event_view) { @@ -412,74 +388,64 @@ class PeriodicSyncManager { periodic_syncs_.erase(periodic_sync); } - void HandleLePeriodicAdvertisingSyncTransferReceived(LePeriodicAdvertisingSyncTransferReceivedView event_view) { + void HandleLePeriodicAdvertisingSyncTransferReceived( + LePeriodicAdvertisingSyncTransferReceivedView event_view) { log::assert_that(event_view.IsValid(), "assert failed: event_view.IsValid()"); uint8_t status = (uint8_t)event_view.GetStatus(); uint8_t advertiser_phy = (uint8_t)event_view.GetAdvertiserPhy(); log::debug( - "[PAST]: status = {}, connection_handle = {}, service_data = {}, sync_handle = {}, adv_sid " - "= {}, address_type = {}, address = {}, advertiser_phy = {}, periodic_advertising_interval " - "= {}, clock_accuracy = {}", - status, - event_view.GetConnectionHandle(), - event_view.GetServiceData(), - event_view.GetSyncHandle(), - event_view.GetAdvertisingSid(), - (uint8_t)event_view.GetAdvertiserAddressType(), - event_view.GetAdvertiserAddress(), - advertiser_phy, - event_view.GetPeriodicAdvertisingInterval(), - (uint8_t)event_view.GetAdvertiserClockAccuracy()); + "[PAST]: status = {}, connection_handle = {}, service_data = {}, sync_handle = {}, " + "adv_sid " + "= {}, address_type = {}, address = {}, advertiser_phy = {}, " + "periodic_advertising_interval " + "= {}, clock_accuracy = {}", + status, event_view.GetConnectionHandle(), event_view.GetServiceData(), + event_view.GetSyncHandle(), event_view.GetAdvertisingSid(), + (uint8_t)event_view.GetAdvertiserAddressType(), event_view.GetAdvertiserAddress(), + advertiser_phy, event_view.GetPeriodicAdvertisingInterval(), + (uint8_t)event_view.GetAdvertiserClockAccuracy()); if (sync_received_callback_registered_) { - callbacks_->OnPeriodicSyncStarted( - sync_received_callback_id, - status, - event_view.GetSyncHandle(), - event_view.GetAdvertisingSid(), - AddressWithType(event_view.GetAdvertiserAddress(), event_view.GetAdvertiserAddressType()), - advertiser_phy, - event_view.GetPeriodicAdvertisingInterval()); + callbacks_->OnPeriodicSyncStarted(sync_received_callback_id, status, + event_view.GetSyncHandle(), event_view.GetAdvertisingSid(), + AddressWithType(event_view.GetAdvertiserAddress(), + event_view.GetAdvertiserAddressType()), + advertiser_phy, + event_view.GetPeriodicAdvertisingInterval()); } } void OnStartSyncTimeout() { auto& request = pending_sync_requests_.front(); - log::warn( - "sync timeout SID={:04X}, bd_addr={}", request.advertiser_sid, request.address_with_type); + log::warn("sync timeout SID={:04X}, bd_addr={}", request.advertiser_sid, + request.address_with_type); uint8_t adv_sid = request.advertiser_sid; AddressWithType address_with_type = request.address_with_type; auto sync = GetSyncFromAddressWithTypeAndSid(address_with_type, adv_sid); le_scanning_interface_->EnqueueCommand( - hci::LePeriodicAdvertisingCreateSyncCancelBuilder::Create(), - handler_->BindOnceOn( - this, - &PeriodicSyncManager::HandlePeriodicAdvertisingCreateSyncCancelStatus< - LePeriodicAdvertisingCreateSyncCancelCompleteView>)); + hci::LePeriodicAdvertisingCreateSyncCancelBuilder::Create(), + handler_->BindOnceOn( + this, &PeriodicSyncManager::HandlePeriodicAdvertisingCreateSyncCancelStatus< + LePeriodicAdvertisingCreateSyncCancelCompleteView>)); int status = static_cast(ErrorCode::ADVERTISING_TIMEOUT); - callbacks_->OnPeriodicSyncStarted( - sync->request_id, status, 0, sync->advertiser_sid, request.address_with_type, 0, 0); + callbacks_->OnPeriodicSyncStarted(sync->request_id, status, 0, sync->advertiser_sid, + request.address_with_type, 0, 0); periodic_syncs_.erase(sync); } void HandleLeBigInfoAdvertisingReport(LeBigInfoAdvertisingReportView event_view) { log::assert_that(event_view.IsValid(), "assert failed: event_view.IsValid()"); log::debug( - "[PAST]:sync_handle {}, num_bises = {}, nse = {},iso_interval = {}, bn = {}, pto = {}, irc " - "= {}, max_pdu = {} sdu_interval = {}, max_sdu = {}, phy = {}, framing = {}, encryption = " - "{}", - event_view.GetSyncHandle(), - event_view.GetNumBis(), - event_view.GetNse(), - event_view.GetIsoInterval(), - event_view.GetBn(), - event_view.GetPto(), - event_view.GetIrc(), - event_view.GetMaxPdu(), - event_view.GetSduInterval(), - event_view.GetMaxSdu(), - static_cast(event_view.GetPhy()), - static_cast(event_view.GetFraming()), - static_cast(event_view.GetEncryption())); + "[PAST]:sync_handle {}, num_bises = {}, nse = {},iso_interval = {}, bn = {}, pto = {}, " + "irc " + "= {}, max_pdu = {} sdu_interval = {}, max_sdu = {}, phy = {}, framing = {}, " + "encryption = " + "{}", + event_view.GetSyncHandle(), event_view.GetNumBis(), event_view.GetNse(), + event_view.GetIsoInterval(), event_view.GetBn(), event_view.GetPto(), + event_view.GetIrc(), event_view.GetMaxPdu(), event_view.GetSduInterval(), + event_view.GetMaxSdu(), static_cast(event_view.GetPhy()), + static_cast(event_view.GetFraming()), + static_cast(event_view.GetEncryption())); uint16_t sync_handle = event_view.GetSyncHandle(); auto periodic_sync = GetEstablishedSyncFromHandle(sync_handle); @@ -488,13 +454,15 @@ class PeriodicSyncManager { return; } log::debug("{}", "[PSync]: invoking callback"); - callbacks_->OnBigInfoReport(sync_handle, event_view.GetEncryption() == Enable::ENABLED ? true : false); + callbacks_->OnBigInfoReport(sync_handle, + event_view.GetEncryption() == Enable::ENABLED ? true : false); } - private: +private: std::list::iterator GetEstablishedSyncFromHandle(uint16_t handle) { for (auto it = periodic_syncs_.begin(); it != periodic_syncs_.end(); it++) { - if (it->sync_handle == handle && it->sync_state == PeriodicSyncState::PERIODIC_SYNC_STATE_ESTABLISHED) { + if (it->sync_handle == handle && + it->sync_state == PeriodicSyncState::PERIODIC_SYNC_STATE_ESTABLISHED) { return it; } } @@ -502,7 +470,7 @@ class PeriodicSyncManager { } std::list::iterator GetSyncFromAddressWithTypeAndSid( - const AddressWithType& address_with_type, uint8_t adv_sid) { + const AddressWithType& address_with_type, uint8_t adv_sid) { for (auto it = periodic_syncs_.begin(); it != periodic_syncs_.end(); it++) { if (it->advertiser_sid == adv_sid && it->address_with_type == address_with_type) { return it; @@ -511,7 +479,8 @@ class PeriodicSyncManager { return periodic_syncs_.end(); } - std::list::iterator GetSyncFromAddressAndSid(const Address& address, uint8_t adv_sid) { + std::list::iterator GetSyncFromAddressAndSid(const Address& address, + uint8_t adv_sid) { for (auto it = periodic_syncs_.begin(); it != periodic_syncs_.end(); it++) { if (it->advertiser_sid == adv_sid && it->address_with_type.GetAddress() == address) { return it; @@ -521,7 +490,7 @@ class PeriodicSyncManager { } std::list::iterator GetPendingSyncFromAddressAndSid( - const Address& address, uint8_t adv_sid) { + const Address& address, uint8_t adv_sid) { for (auto it = pending_sync_requests_.begin(); it != pending_sync_requests_.end(); it++) { if (it->advertiser_sid == adv_sid && it->address_with_type.GetAddress() == address) { return it; @@ -531,7 +500,7 @@ class PeriodicSyncManager { } std::list::iterator GetSyncTransferRequestFromConnectionHandle( - uint16_t connection_handle) { + uint16_t connection_handle) { for (auto it = periodic_sync_transfers_.begin(); it != periodic_sync_transfers_.end(); it++) { if (it->connection_handle == connection_handle) { return it; @@ -540,31 +509,26 @@ class PeriodicSyncManager { return periodic_sync_transfers_.end(); } - void HandleStartSyncRequest(uint8_t sid, const AddressWithType& address_with_type, uint16_t skip, uint16_t timeout) { + void HandleStartSyncRequest(uint8_t sid, const AddressWithType& address_with_type, uint16_t skip, + uint16_t timeout) { PeriodicAdvertisingOptions options; auto sync_cte_type = - static_cast(PeriodicSyncCteType::AVOID_AOA_CONSTANT_TONE_EXTENSION) | - static_cast( - PeriodicSyncCteType::AVOID_AOD_CONSTANT_TONE_EXTENSION_WITH_ONE_US_SLOTS) | - static_cast( - PeriodicSyncCteType::AVOID_AOD_CONSTANT_TONE_EXTENSION_WITH_TWO_US_SLOTS); + static_cast(PeriodicSyncCteType::AVOID_AOA_CONSTANT_TONE_EXTENSION) | + static_cast( + PeriodicSyncCteType::AVOID_AOD_CONSTANT_TONE_EXTENSION_WITH_ONE_US_SLOTS) | + static_cast( + PeriodicSyncCteType::AVOID_AOD_CONSTANT_TONE_EXTENSION_WITH_TWO_US_SLOTS); auto sync = GetSyncFromAddressWithTypeAndSid(address_with_type, sid); sync->sync_state = PERIODIC_SYNC_STATE_PENDING; AdvertisingAddressType advertisingAddressType = - static_cast(address_with_type.GetAddressType()); + static_cast(address_with_type.GetAddressType()); le_scanning_interface_->EnqueueCommand( - hci::LePeriodicAdvertisingCreateSyncBuilder::Create( - options, - sid, - advertisingAddressType, - address_with_type.GetAddress(), - skip, - timeout, - sync_cte_type), - handler_->BindOnceOn( - this, - &PeriodicSyncManager::HandlePeriodicAdvertisingCreateSyncStatus< - LePeriodicAdvertisingCreateSyncStatusView>)); + hci::LePeriodicAdvertisingCreateSyncBuilder::Create( + options, sid, advertisingAddressType, address_with_type.GetAddress(), skip, + timeout, sync_cte_type), + handler_->BindOnceOn(this, + &PeriodicSyncManager::HandlePeriodicAdvertisingCreateSyncStatus< + LePeriodicAdvertisingCreateSyncStatusView>)); } void HandleNextRequest() { @@ -573,19 +537,19 @@ class PeriodicSyncManager { return; } auto& request = pending_sync_requests_.front(); - log::info( - "executing sync request SID={:04X}, bd_addr={}", - request.advertiser_sid, - request.address_with_type); + log::info("executing sync request SID={:04X}, bd_addr={}", request.advertiser_sid, + request.address_with_type); if (request.busy) { log::info("Request is already busy"); return; } request.busy = true; request.sync_timeout_alarm.Cancel(); - HandleStartSyncRequest(request.advertiser_sid, request.address_with_type, request.skip, request.sync_timeout); + HandleStartSyncRequest(request.advertiser_sid, request.address_with_type, request.skip, + request.sync_timeout); request.sync_timeout_alarm.Schedule( - base::BindOnce(&PeriodicSyncManager::OnStartSyncTimeout, base::Unretained(this)), kPeriodicSyncTimeout); + base::BindOnce(&PeriodicSyncManager::OnStartSyncTimeout, base::Unretained(this)), + kPeriodicSyncTimeout); } void AdvanceRequest() { @@ -603,11 +567,8 @@ class PeriodicSyncManager { auto it = pending_sync_requests_.begin(); while (it != pending_sync_requests_.end()) { if (it->advertiser_sid == advertiser_sid && it->address_with_type.GetAddress() == address) { - log::info( - "removing connection request SID={:04X}, bd_addr={}, busy={}", - it->advertiser_sid, - it->address_with_type, - it->busy); + log::info("removing connection request SID={:04X}, bd_addr={}, busy={}", it->advertiser_sid, + it->address_with_type, it->busy); it = pending_sync_requests_.erase(it); } else { ++it; diff --git a/system/gd/hci/le_periodic_sync_manager_test.cc b/system/gd/hci/le_periodic_sync_manager_test.cc index ecf3248bc1c..d8003cd1b37 100644 --- a/system/gd/hci/le_periodic_sync_manager_test.cc +++ b/system/gd/hci/le_periodic_sync_manager_test.cc @@ -45,10 +45,10 @@ PacketView GetPacketView(std::unique_ptr command, - common::ContextualOnceCallback on_complete) override { + std::unique_ptr command, + common::ContextualOnceCallback on_complete) override { std::lock_guard lock(mutex_); command_queue_.push(std::move(command)); command_complete_callbacks.push_back(std::move(on_complete)); @@ -59,9 +59,8 @@ class TestLeScanningInterface : public LeScanningInterface { } } - void EnqueueCommand( - std::unique_ptr command, - common::ContextualOnceCallback on_status) override { + void EnqueueCommand(std::unique_ptr command, + common::ContextualOnceCallback on_status) override { command_queue_.push(std::move(command)); command_status_callbacks.push_back(std::move(on_status)); if (command_promise_ != nullptr) { @@ -79,7 +78,8 @@ class TestLeScanningInterface : public LeScanningInterface { CommandView GetLastCommand() { if (command_queue_.empty()) { - return CommandView::Create(PacketView(std::make_shared>())); + return CommandView::Create( + PacketView(std::make_shared>())); } auto last = std::move(command_queue_.front()); command_queue_.pop(); @@ -98,10 +98,8 @@ class TestLeScanningInterface : public LeScanningInterface { EXPECT_NE(std::future_status::timeout, result); } std::lock_guard lock(mutex_); - log::assert_that( - !command_queue_.empty(), - "Expecting command {} but command queue was empty", - OpCodeText(op_code)); + log::assert_that(!command_queue_.empty(), "Expecting command {} but command queue was empty", + OpCodeText(op_code)); CommandView command_packet_view = GetLastCommand(); EXPECT_TRUE(command_packet_view.IsValid()); EXPECT_EQ(command_packet_view.GetOpCode(), op_code); @@ -126,7 +124,7 @@ class TestLeScanningInterface : public LeScanningInterface { command_status_callbacks.pop_front(); } - private: +private: std::list> command_complete_callbacks; std::list> command_status_callbacks; std::queue> command_queue_; @@ -136,7 +134,7 @@ class TestLeScanningInterface : public LeScanningInterface { }; class PeriodicSyncManagerTest : public ::testing::Test { - protected: +protected: void SetUp() override { thread_ = new os::Thread("thread", os::Thread::Priority::NORMAL); handler_ = new os::Handler(thread_); @@ -159,54 +157,42 @@ class PeriodicSyncManagerTest : public ::testing::Test { void sync_handler() { log::assert_that(thread_ != nullptr, "assert failed: thread_ != nullptr"); - log::assert_that( - thread_->GetReactor()->WaitForIdle(2s), - "assert failed: thread_->GetReactor()->WaitForIdle(2s)"); + log::assert_that(thread_->GetReactor()->WaitForIdle(2s), + "assert failed: thread_->GetReactor()->WaitForIdle(2s)"); } class MockCallbacks : public bluetooth::hci::ScanningCallback { - public: - MOCK_METHOD( - void, - OnScannerRegistered, - (const bluetooth::hci::Uuid app_uuid, ScannerId scanner_id, ScanningStatus status), - (override)); - MOCK_METHOD(void, OnSetScannerParameterComplete, (ScannerId scanner_id, ScanningStatus status), (override)); - MOCK_METHOD( - void, - OnScanResult, - (uint16_t event_type, - uint8_t address_type, - Address address, - uint8_t primary_phy, - uint8_t secondary_phy, - uint8_t advertising_sid, - int8_t tx_power, - int8_t rssi, - uint16_t periodic_advertising_interval, - std::vector advertising_data), - (override)); - MOCK_METHOD( - void, - OnTrackAdvFoundLost, - (bluetooth::hci::AdvertisingFilterOnFoundOnLostInfo on_found_on_lost_info), - (override)); - MOCK_METHOD( - void, - OnBatchScanReports, - (int client_if, int status, int report_format, int num_records, std::vector data), - (override)); + public: + MOCK_METHOD(void, OnScannerRegistered, + (const bluetooth::hci::Uuid app_uuid, ScannerId scanner_id, ScanningStatus status), + (override)); + MOCK_METHOD(void, OnSetScannerParameterComplete, (ScannerId scanner_id, ScanningStatus status), + (override)); + MOCK_METHOD(void, OnScanResult, + (uint16_t event_type, uint8_t address_type, Address address, uint8_t primary_phy, + uint8_t secondary_phy, uint8_t advertising_sid, int8_t tx_power, int8_t rssi, + uint16_t periodic_advertising_interval, std::vector advertising_data), + (override)); + MOCK_METHOD(void, OnTrackAdvFoundLost, + (bluetooth::hci::AdvertisingFilterOnFoundOnLostInfo on_found_on_lost_info), + (override)); + MOCK_METHOD(void, OnBatchScanReports, + (int client_if, int status, int report_format, int num_records, + std::vector data), + (override)); MOCK_METHOD(void, OnBatchScanThresholdCrossed, (int client_if), (override)); MOCK_METHOD(void, OnTimeout, (), (override)); MOCK_METHOD(void, OnFilterEnable, (Enable enable, uint8_t status), (override)); - MOCK_METHOD(void, OnFilterParamSetup, (uint8_t available_spaces, ApcfAction action, uint8_t status), (override)); - MOCK_METHOD( - void, - OnFilterConfigCallback, - (ApcfFilterType filter_type, uint8_t available_spaces, ApcfAction action, uint8_t status), - (override)); - MOCK_METHOD(void, OnPeriodicSyncStarted, (int, uint8_t, uint16_t, uint8_t, AddressWithType, uint8_t, uint16_t)); - MOCK_METHOD(void, OnPeriodicSyncReport, (uint16_t, int8_t, int8_t, uint8_t, std::vector)); + MOCK_METHOD(void, OnFilterParamSetup, + (uint8_t available_spaces, ApcfAction action, uint8_t status), (override)); + MOCK_METHOD(void, OnFilterConfigCallback, + (ApcfFilterType filter_type, uint8_t available_spaces, ApcfAction action, + uint8_t status), + (override)); + MOCK_METHOD(void, OnPeriodicSyncStarted, + (int, uint8_t, uint16_t, uint8_t, AddressWithType, uint8_t, uint16_t)); + MOCK_METHOD(void, OnPeriodicSyncReport, + (uint16_t, int8_t, int8_t, uint8_t, std::vector)); MOCK_METHOD(void, OnPeriodicSyncLost, (uint16_t)); MOCK_METHOD(void, OnPeriodicSyncTransferred, (int, uint8_t, Address)); MOCK_METHOD(void, OnBigInfoReport, (uint16_t, bool)); @@ -228,23 +214,24 @@ TEST_F(PeriodicSyncManagerTest, start_sync_test) { AddressWithType address_with_type = AddressWithType(address, AddressType::PUBLIC_DEVICE_ADDRESS); uint16_t sync_handle = 0x03; PeriodicSyncStates request{ - .request_id = request_id, - .advertiser_sid = advertiser_sid, - .address_with_type = address_with_type, - .sync_handle = sync_handle, - .sync_state = PeriodicSyncState::PERIODIC_SYNC_STATE_IDLE, + .request_id = request_id, + .advertiser_sid = advertiser_sid, + .address_with_type = address_with_type, + .sync_handle = sync_handle, + .sync_state = PeriodicSyncState::PERIODIC_SYNC_STATE_IDLE, }; uint16_t skip = 0x04; uint16_t sync_timeout = 0x0A; ASSERT_NO_FATAL_FAILURE(test_le_scanning_interface_->SetCommandFuture()); periodic_sync_manager_->StartSync(request, skip, sync_timeout); - auto packet = test_le_scanning_interface_->GetCommand(OpCode::LE_PERIODIC_ADVERTISING_CREATE_SYNC); - auto packet_view = LePeriodicAdvertisingCreateSyncView::Create(LeScanningCommandView::Create(packet)); + auto packet = + test_le_scanning_interface_->GetCommand(OpCode::LE_PERIODIC_ADVERTISING_CREATE_SYNC); + auto packet_view = + LePeriodicAdvertisingCreateSyncView::Create(LeScanningCommandView::Create(packet)); ASSERT_TRUE(packet_view.IsValid()); ASSERT_EQ(advertiser_sid, packet_view.GetAdvertisingSid()); - ASSERT_EQ( - AdvertisingAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - packet_view.GetAdvertiserAddressType()); + ASSERT_EQ(AdvertisingAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, + packet_view.GetAdvertiserAddressType()); ASSERT_EQ(address, packet_view.GetAdvertiserAddress()); ASSERT_EQ(skip, packet_view.GetSkip()); ASSERT_EQ(sync_timeout, packet_view.GetSyncTimeout()); @@ -259,41 +246,38 @@ TEST_F(PeriodicSyncManagerTest, handle_advertising_sync_established_test) { Address::FromString("00:11:22:33:44:55", address); AddressWithType address_with_type = AddressWithType(address, AddressType::PUBLIC_DEVICE_ADDRESS); PeriodicSyncStates request{ - .request_id = 0x01, - .advertiser_sid = advertiser_sid, - .address_with_type = address_with_type, - .sync_handle = sync_handle, - .sync_state = PeriodicSyncState::PERIODIC_SYNC_STATE_IDLE, + .request_id = 0x01, + .advertiser_sid = advertiser_sid, + .address_with_type = address_with_type, + .sync_handle = sync_handle, + .sync_state = PeriodicSyncState::PERIODIC_SYNC_STATE_IDLE, }; ASSERT_NO_FATAL_FAILURE(test_le_scanning_interface_->SetCommandFuture()); periodic_sync_manager_->StartSync(request, 0x04, 0x0A); - auto packet = test_le_scanning_interface_->GetCommand(OpCode::LE_PERIODIC_ADVERTISING_CREATE_SYNC); - auto temp_view = LePeriodicAdvertisingCreateSyncView::Create(LeScanningCommandView::Create(packet)); + auto packet = + test_le_scanning_interface_->GetCommand(OpCode::LE_PERIODIC_ADVERTISING_CREATE_SYNC); + auto temp_view = + LePeriodicAdvertisingCreateSyncView::Create(LeScanningCommandView::Create(packet)); ASSERT_TRUE(temp_view.IsValid()); // Get command status test_le_scanning_interface_->CommandStatusCallback( - LePeriodicAdvertisingCreateSyncStatusBuilder::Create(ErrorCode::SUCCESS, 0x00)); + LePeriodicAdvertisingCreateSyncStatusBuilder::Create(ErrorCode::SUCCESS, 0x00)); EXPECT_CALL(mock_callbacks_, OnPeriodicSyncStarted); // Get LePeriodicAdvertisingSyncEstablished auto builder = LePeriodicAdvertisingSyncEstablishedBuilder::Create( - ErrorCode::SUCCESS, - sync_handle, - advertiser_sid, - address_with_type.GetAddressType(), - address_with_type.GetAddress(), - SecondaryPhyType::LE_1M, - 0xFF, - ClockAccuracy::PPM_250); + ErrorCode::SUCCESS, sync_handle, advertiser_sid, address_with_type.GetAddressType(), + address_with_type.GetAddress(), SecondaryPhyType::LE_1M, 0xFF, ClockAccuracy::PPM_250); auto event_view = LePeriodicAdvertisingSyncEstablishedView::Create( - LeMetaEventView::Create(EventView::Create(GetPacketView(std::move(builder))))); + LeMetaEventView::Create(EventView::Create(GetPacketView(std::move(builder))))); periodic_sync_manager_->HandleLePeriodicAdvertisingSyncEstablished(event_view); sync_handler(); } -TEST_F(PeriodicSyncManagerTest, handle_advertising_sync_established_with_public_identity_address_test) { +TEST_F(PeriodicSyncManagerTest, + handle_advertising_sync_established_with_public_identity_address_test) { uint16_t sync_handle = 0x12; uint8_t advertiser_sid = 0x02; // start scan @@ -301,36 +285,32 @@ TEST_F(PeriodicSyncManagerTest, handle_advertising_sync_established_with_public_ Address::FromString("00:11:22:33:44:55", address); AddressWithType address_with_type = AddressWithType(address, AddressType::PUBLIC_DEVICE_ADDRESS); PeriodicSyncStates request{ - .request_id = 0x01, - .advertiser_sid = advertiser_sid, - .address_with_type = address_with_type, - .sync_handle = sync_handle, - .sync_state = PeriodicSyncState::PERIODIC_SYNC_STATE_IDLE, + .request_id = 0x01, + .advertiser_sid = advertiser_sid, + .address_with_type = address_with_type, + .sync_handle = sync_handle, + .sync_state = PeriodicSyncState::PERIODIC_SYNC_STATE_IDLE, }; ASSERT_NO_FATAL_FAILURE(test_le_scanning_interface_->SetCommandFuture()); periodic_sync_manager_->StartSync(request, 0x04, 0x0A); - auto packet = test_le_scanning_interface_->GetCommand(OpCode::LE_PERIODIC_ADVERTISING_CREATE_SYNC); - auto temp_view = LePeriodicAdvertisingCreateSyncView::Create(LeScanningCommandView::Create(packet)); + auto packet = + test_le_scanning_interface_->GetCommand(OpCode::LE_PERIODIC_ADVERTISING_CREATE_SYNC); + auto temp_view = + LePeriodicAdvertisingCreateSyncView::Create(LeScanningCommandView::Create(packet)); ASSERT_TRUE(temp_view.IsValid()); // Get command status test_le_scanning_interface_->CommandStatusCallback( - LePeriodicAdvertisingCreateSyncStatusBuilder::Create(ErrorCode::SUCCESS, 0x00)); + LePeriodicAdvertisingCreateSyncStatusBuilder::Create(ErrorCode::SUCCESS, 0x00)); EXPECT_CALL(mock_callbacks_, OnPeriodicSyncStarted); // Get LePeriodicAdvertisingSyncEstablished with AddressType::PUBLIC_IDENTITY_ADDRESS auto builder = LePeriodicAdvertisingSyncEstablishedBuilder::Create( - ErrorCode::SUCCESS, - sync_handle, - advertiser_sid, - AddressType::PUBLIC_IDENTITY_ADDRESS, - address_with_type.GetAddress(), - SecondaryPhyType::LE_1M, - 0xFF, - ClockAccuracy::PPM_250); + ErrorCode::SUCCESS, sync_handle, advertiser_sid, AddressType::PUBLIC_IDENTITY_ADDRESS, + address_with_type.GetAddress(), SecondaryPhyType::LE_1M, 0xFF, ClockAccuracy::PPM_250); auto event_view = LePeriodicAdvertisingSyncEstablishedView::Create( - LeMetaEventView::Create(EventView::Create(GetPacketView(std::move(builder))))); + LeMetaEventView::Create(EventView::Create(GetPacketView(std::move(builder))))); periodic_sync_manager_->HandleLePeriodicAdvertisingSyncEstablished(event_view); sync_handler(); } @@ -343,44 +323,40 @@ TEST_F(PeriodicSyncManagerTest, stop_sync_test) { Address::FromString("00:11:22:33:44:55", address); AddressWithType address_with_type = AddressWithType(address, AddressType::PUBLIC_DEVICE_ADDRESS); PeriodicSyncStates request{ - .request_id = 0x01, - .advertiser_sid = advertiser_sid, - .address_with_type = address_with_type, - .sync_handle = sync_handle, - .sync_state = PeriodicSyncState::PERIODIC_SYNC_STATE_IDLE, + .request_id = 0x01, + .advertiser_sid = advertiser_sid, + .address_with_type = address_with_type, + .sync_handle = sync_handle, + .sync_state = PeriodicSyncState::PERIODIC_SYNC_STATE_IDLE, }; ASSERT_NO_FATAL_FAILURE(test_le_scanning_interface_->SetCommandFuture()); periodic_sync_manager_->StartSync(request, 0x04, 0x0A); - auto packet = test_le_scanning_interface_->GetCommand(OpCode::LE_PERIODIC_ADVERTISING_CREATE_SYNC); + auto packet = + test_le_scanning_interface_->GetCommand(OpCode::LE_PERIODIC_ADVERTISING_CREATE_SYNC); auto temp_view = - LePeriodicAdvertisingCreateSyncView::Create(LeScanningCommandView::Create(packet)); + LePeriodicAdvertisingCreateSyncView::Create(LeScanningCommandView::Create(packet)); ASSERT_TRUE(temp_view.IsValid()); // Get command status test_le_scanning_interface_->CommandStatusCallback( - LePeriodicAdvertisingCreateSyncStatusBuilder::Create(ErrorCode::SUCCESS, 0x00)); + LePeriodicAdvertisingCreateSyncStatusBuilder::Create(ErrorCode::SUCCESS, 0x00)); EXPECT_CALL(mock_callbacks_, OnPeriodicSyncStarted); // Get LePeriodicAdvertisingSyncEstablished auto builder = LePeriodicAdvertisingSyncEstablishedBuilder::Create( - ErrorCode::SUCCESS, - sync_handle, - advertiser_sid, - address_with_type.GetAddressType(), - address_with_type.GetAddress(), - SecondaryPhyType::LE_1M, - 0xFF, - ClockAccuracy::PPM_250); + ErrorCode::SUCCESS, sync_handle, advertiser_sid, address_with_type.GetAddressType(), + address_with_type.GetAddress(), SecondaryPhyType::LE_1M, 0xFF, ClockAccuracy::PPM_250); auto event_view = LePeriodicAdvertisingSyncEstablishedView::Create( - LeMetaEventView::Create(EventView::Create(GetPacketView(std::move(builder))))); + LeMetaEventView::Create(EventView::Create(GetPacketView(std::move(builder))))); periodic_sync_manager_->HandleLePeriodicAdvertisingSyncEstablished(event_view); // StopSync ASSERT_NO_FATAL_FAILURE(test_le_scanning_interface_->SetCommandFuture()); periodic_sync_manager_->StopSync(sync_handle); packet = test_le_scanning_interface_->GetCommand(OpCode::LE_PERIODIC_ADVERTISING_TERMINATE_SYNC); - auto packet_view = LePeriodicAdvertisingTerminateSyncView::Create(LeScanningCommandView::Create(packet)); + auto packet_view = + LePeriodicAdvertisingTerminateSyncView::Create(LeScanningCommandView::Create(packet)); ASSERT_TRUE(packet_view.IsValid()); ASSERT_EQ(sync_handle, packet_view.GetSyncHandle()); sync_handler(); @@ -394,28 +370,31 @@ TEST_F(PeriodicSyncManagerTest, cancel_create_sync_test) { Address::FromString("00:11:22:33:44:55", address); AddressWithType address_with_type = AddressWithType(address, AddressType::PUBLIC_DEVICE_ADDRESS); PeriodicSyncStates request{ - .request_id = 0x01, - .advertiser_sid = advertiser_sid, - .address_with_type = address_with_type, - .sync_handle = sync_handle, - .sync_state = PeriodicSyncState::PERIODIC_SYNC_STATE_IDLE, + .request_id = 0x01, + .advertiser_sid = advertiser_sid, + .address_with_type = address_with_type, + .sync_handle = sync_handle, + .sync_state = PeriodicSyncState::PERIODIC_SYNC_STATE_IDLE, }; ASSERT_NO_FATAL_FAILURE(test_le_scanning_interface_->SetCommandFuture()); periodic_sync_manager_->StartSync(request, 0x04, 0x0A); - auto packet = test_le_scanning_interface_->GetCommand(OpCode::LE_PERIODIC_ADVERTISING_CREATE_SYNC); + auto packet = + test_le_scanning_interface_->GetCommand(OpCode::LE_PERIODIC_ADVERTISING_CREATE_SYNC); auto temp_view = - LePeriodicAdvertisingCreateSyncView::Create(LeScanningCommandView::Create(packet)); + LePeriodicAdvertisingCreateSyncView::Create(LeScanningCommandView::Create(packet)); ASSERT_TRUE(temp_view.IsValid()); // Get command status test_le_scanning_interface_->CommandStatusCallback( - LePeriodicAdvertisingCreateSyncStatusBuilder::Create(ErrorCode::SUCCESS, 0x00)); + LePeriodicAdvertisingCreateSyncStatusBuilder::Create(ErrorCode::SUCCESS, 0x00)); // Cancel crate sync ASSERT_NO_FATAL_FAILURE(test_le_scanning_interface_->SetCommandFuture()); periodic_sync_manager_->CancelCreateSync(advertiser_sid, address_with_type.GetAddress()); - packet = test_le_scanning_interface_->GetCommand(OpCode::LE_PERIODIC_ADVERTISING_CREATE_SYNC_CANCEL); - auto packet_view = LePeriodicAdvertisingCreateSyncCancelView::Create(LeScanningCommandView::Create(packet)); + packet = test_le_scanning_interface_->GetCommand( + OpCode::LE_PERIODIC_ADVERTISING_CREATE_SYNC_CANCEL); + auto packet_view = + LePeriodicAdvertisingCreateSyncCancelView::Create(LeScanningCommandView::Create(packet)); ASSERT_TRUE(packet_view.IsValid()); sync_handler(); } @@ -428,9 +407,12 @@ TEST_F(PeriodicSyncManagerTest, transfer_sync_test) { uint16_t connection_handle = 0x12; int pa_source = 0x01; ASSERT_NO_FATAL_FAILURE(test_le_scanning_interface_->SetCommandFuture()); - periodic_sync_manager_->TransferSync(address, service_data, sync_handle, pa_source, connection_handle); - auto packet = test_le_scanning_interface_->GetCommand(OpCode::LE_PERIODIC_ADVERTISING_SYNC_TRANSFER); - auto packet_view = LePeriodicAdvertisingSyncTransferView::Create(LeScanningCommandView::Create(packet)); + periodic_sync_manager_->TransferSync(address, service_data, sync_handle, pa_source, + connection_handle); + auto packet = + test_le_scanning_interface_->GetCommand(OpCode::LE_PERIODIC_ADVERTISING_SYNC_TRANSFER); + auto packet_view = + LePeriodicAdvertisingSyncTransferView::Create(LeScanningCommandView::Create(packet)); ASSERT_TRUE(packet_view.IsValid()); ASSERT_EQ(connection_handle, packet_view.GetConnectionHandle()); ASSERT_EQ(service_data, packet_view.GetServiceData()); @@ -440,7 +422,8 @@ TEST_F(PeriodicSyncManagerTest, transfer_sync_test) { // Get command complete test_le_scanning_interface_->CommandCompleteCallback( - LePeriodicAdvertisingSyncTransferCompleteBuilder::Create(0x00, ErrorCode::SUCCESS, connection_handle)); + LePeriodicAdvertisingSyncTransferCompleteBuilder::Create(0x00, ErrorCode::SUCCESS, + connection_handle)); sync_handler(); } @@ -453,9 +436,12 @@ TEST_F(PeriodicSyncManagerTest, sync_set_info_test) { uint16_t connection_handle = 0x12; int pa_source = 0x01; ASSERT_NO_FATAL_FAILURE(test_le_scanning_interface_->SetCommandFuture()); - periodic_sync_manager_->SyncSetInfo(address, service_data, advertising_handle, pa_source, connection_handle); - auto packet = test_le_scanning_interface_->GetCommand(OpCode::LE_PERIODIC_ADVERTISING_SET_INFO_TRANSFER); - auto packet_view = LePeriodicAdvertisingSetInfoTransferView::Create(LeScanningCommandView::Create(packet)); + periodic_sync_manager_->SyncSetInfo(address, service_data, advertising_handle, pa_source, + connection_handle); + auto packet = test_le_scanning_interface_->GetCommand( + OpCode::LE_PERIODIC_ADVERTISING_SET_INFO_TRANSFER); + auto packet_view = + LePeriodicAdvertisingSetInfoTransferView::Create(LeScanningCommandView::Create(packet)); ASSERT_TRUE(packet_view.IsValid()); ASSERT_EQ(connection_handle, packet_view.GetConnectionHandle()); ASSERT_EQ(service_data, packet_view.GetServiceData()); @@ -465,7 +451,8 @@ TEST_F(PeriodicSyncManagerTest, sync_set_info_test) { // Get command complete test_le_scanning_interface_->CommandCompleteCallback( - LePeriodicAdvertisingSetInfoTransferCompleteBuilder::Create(0x00, ErrorCode::SUCCESS, connection_handle)); + LePeriodicAdvertisingSetInfoTransferCompleteBuilder::Create(0x00, ErrorCode::SUCCESS, + connection_handle)); sync_handler(); } @@ -475,19 +462,19 @@ TEST_F(PeriodicSyncManagerTest, sync_tx_parameters_test) { Address::FromString("00:11:22:33:44:55", address); uint8_t mode = 0x00; uint16_t skip = 0x11; - uint16_t timout = 0x12; + uint16_t timeout = 0x12; int reg_id = 0x01; ASSERT_NO_FATAL_FAILURE(test_le_scanning_interface_->SetCommandFuture()); - periodic_sync_manager_->SyncTxParameters(address, mode, skip, timout, reg_id); - auto packet = - test_le_scanning_interface_->GetCommand(OpCode::LE_SET_DEFAULT_PERIODIC_ADVERTISING_SYNC_TRANSFER_PARAMETERS); - auto packet_view = - LeSetDefaultPeriodicAdvertisingSyncTransferParametersView::Create(LeScanningCommandView::Create(packet)); + periodic_sync_manager_->SyncTxParameters(address, mode, skip, timeout, reg_id); + auto packet = test_le_scanning_interface_->GetCommand( + OpCode::LE_SET_DEFAULT_PERIODIC_ADVERTISING_SYNC_TRANSFER_PARAMETERS); + auto packet_view = LeSetDefaultPeriodicAdvertisingSyncTransferParametersView::Create( + LeScanningCommandView::Create(packet)); ASSERT_TRUE(packet_view.IsValid()); ASSERT_EQ(mode, (uint8_t)packet_view.GetMode()); ASSERT_EQ(skip, packet_view.GetSkip()); - ASSERT_EQ(timout, packet_view.GetSyncTimeout()); + ASSERT_EQ(timeout, packet_view.GetSyncTimeout()); sync_handler(); } @@ -500,37 +487,32 @@ TEST_F(PeriodicSyncManagerTest, handle_sync_lost_test) { Address::FromString("00:11:22:33:44:55", address); AddressWithType address_with_type = AddressWithType(address, AddressType::PUBLIC_DEVICE_ADDRESS); PeriodicSyncStates request{ - .request_id = 0x01, - .advertiser_sid = advertiser_sid, - .address_with_type = address_with_type, - .sync_handle = sync_handle, - .sync_state = PeriodicSyncState::PERIODIC_SYNC_STATE_IDLE, + .request_id = 0x01, + .advertiser_sid = advertiser_sid, + .address_with_type = address_with_type, + .sync_handle = sync_handle, + .sync_state = PeriodicSyncState::PERIODIC_SYNC_STATE_IDLE, }; ASSERT_NO_FATAL_FAILURE(test_le_scanning_interface_->SetCommandFuture()); periodic_sync_manager_->StartSync(request, 0x04, 0x0A); - auto packet = test_le_scanning_interface_->GetCommand(OpCode::LE_PERIODIC_ADVERTISING_CREATE_SYNC); + auto packet = + test_le_scanning_interface_->GetCommand(OpCode::LE_PERIODIC_ADVERTISING_CREATE_SYNC); auto temp_view = - LePeriodicAdvertisingCreateSyncView::Create(LeScanningCommandView::Create(packet)); + LePeriodicAdvertisingCreateSyncView::Create(LeScanningCommandView::Create(packet)); ASSERT_TRUE(temp_view.IsValid()); // Get command status test_le_scanning_interface_->CommandStatusCallback( - LePeriodicAdvertisingCreateSyncStatusBuilder::Create(ErrorCode::SUCCESS, 0x00)); + LePeriodicAdvertisingCreateSyncStatusBuilder::Create(ErrorCode::SUCCESS, 0x00)); EXPECT_CALL(mock_callbacks_, OnPeriodicSyncStarted); // Get LePeriodicAdvertisingSyncEstablished auto builder = LePeriodicAdvertisingSyncEstablishedBuilder::Create( - ErrorCode::SUCCESS, - sync_handle, - advertiser_sid, - address_with_type.GetAddressType(), - address_with_type.GetAddress(), - SecondaryPhyType::LE_1M, - 0xFF, - ClockAccuracy::PPM_250); + ErrorCode::SUCCESS, sync_handle, advertiser_sid, address_with_type.GetAddressType(), + address_with_type.GetAddress(), SecondaryPhyType::LE_1M, 0xFF, ClockAccuracy::PPM_250); auto event_view = LePeriodicAdvertisingSyncEstablishedView::Create( - LeMetaEventView::Create(EventView::Create(GetPacketView(std::move(builder))))); + LeMetaEventView::Create(EventView::Create(GetPacketView(std::move(builder))))); periodic_sync_manager_->HandleLePeriodicAdvertisingSyncEstablished(event_view); EXPECT_CALL(mock_callbacks_, OnPeriodicSyncLost); @@ -539,16 +521,15 @@ TEST_F(PeriodicSyncManagerTest, handle_sync_lost_test) { auto builder2 = LePeriodicAdvertisingSyncLostBuilder::Create(sync_handle); auto event_view2 = LePeriodicAdvertisingSyncLostView::Create( - LeMetaEventView::Create(EventView::Create(GetPacketView(std::move(builder2))))); + LeMetaEventView::Create(EventView::Create(GetPacketView(std::move(builder2))))); periodic_sync_manager_->HandleLePeriodicAdvertisingSyncLost(event_view2); sync_handler(); } -TEST_F_WITH_FLAGS( - PeriodicSyncManagerTest, - handle_advertising_sync_established_after_error_test, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, leaudio_broadcast_feature_support))) { +TEST_F_WITH_FLAGS(PeriodicSyncManagerTest, handle_advertising_sync_established_after_error_test, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, + leaudio_broadcast_feature_support))) { uint16_t sync_handle = 0x12; uint8_t advertiser_sid = 0x02; // start scan @@ -559,48 +540,38 @@ TEST_F_WITH_FLAGS( // First request which will finish with error int request_id_1 = 0x01; PeriodicSyncStates request{ - .request_id = request_id_1, - .advertiser_sid = advertiser_sid, - .address_with_type = address_with_type, - .sync_handle = sync_handle, - .sync_state = PeriodicSyncState::PERIODIC_SYNC_STATE_IDLE, + .request_id = request_id_1, + .advertiser_sid = advertiser_sid, + .address_with_type = address_with_type, + .sync_handle = sync_handle, + .sync_state = PeriodicSyncState::PERIODIC_SYNC_STATE_IDLE, }; ASSERT_NO_FATAL_FAILURE(test_le_scanning_interface_->SetCommandFuture()); periodic_sync_manager_->StartSync(request, 0x04, 0x0A); auto packet = - test_le_scanning_interface_->GetCommand(OpCode::LE_PERIODIC_ADVERTISING_CREATE_SYNC); + test_le_scanning_interface_->GetCommand(OpCode::LE_PERIODIC_ADVERTISING_CREATE_SYNC); auto temp_view = - LePeriodicAdvertisingCreateSyncView::Create(LeScanningCommandView::Create(packet)); + LePeriodicAdvertisingCreateSyncView::Create(LeScanningCommandView::Create(packet)); ASSERT_TRUE(temp_view.IsValid()); // Get command status test_le_scanning_interface_->CommandStatusCallback( - LePeriodicAdvertisingCreateSyncStatusBuilder::Create(ErrorCode::SUCCESS, 0x00)); + LePeriodicAdvertisingCreateSyncStatusBuilder::Create(ErrorCode::SUCCESS, 0x00)); EXPECT_CALL( - mock_callbacks_, - OnPeriodicSyncStarted( - request_id_1, - static_cast(ErrorCode::CONNECTION_FAILED_ESTABLISHMENT), - _, - _, - _, - _, - _)) - .Times(1); + mock_callbacks_, + OnPeriodicSyncStarted(request_id_1, + static_cast(ErrorCode::CONNECTION_FAILED_ESTABLISHMENT), _, + _, _, _, _)) + .Times(1); // Get LePeriodicAdvertisingSyncEstablished auto builder = LePeriodicAdvertisingSyncEstablishedBuilder::Create( - ErrorCode::CONNECTION_FAILED_ESTABLISHMENT, - sync_handle, - advertiser_sid, - address_with_type.GetAddressType(), - address_with_type.GetAddress(), - SecondaryPhyType::LE_1M, - 0xFF, - ClockAccuracy::PPM_250); + ErrorCode::CONNECTION_FAILED_ESTABLISHMENT, sync_handle, advertiser_sid, + address_with_type.GetAddressType(), address_with_type.GetAddress(), + SecondaryPhyType::LE_1M, 0xFF, ClockAccuracy::PPM_250); auto event_view = LePeriodicAdvertisingSyncEstablishedView::Create( - LeMetaEventView::Create(EventView::Create(GetPacketView(std::move(builder))))); + LeMetaEventView::Create(EventView::Create(GetPacketView(std::move(builder))))); periodic_sync_manager_->HandleLePeriodicAdvertisingSyncEstablished(event_view); // Second request with the same data but different id @@ -614,35 +585,28 @@ TEST_F_WITH_FLAGS( // Get command status test_le_scanning_interface_->CommandStatusCallback( - LePeriodicAdvertisingCreateSyncStatusBuilder::Create(ErrorCode::SUCCESS, 0x00)); + LePeriodicAdvertisingCreateSyncStatusBuilder::Create(ErrorCode::SUCCESS, 0x00)); - EXPECT_CALL( - mock_callbacks_, - OnPeriodicSyncStarted(request_id_2, static_cast(ErrorCode::SUCCESS), _, _, _, _, _)) - .Times(1); + EXPECT_CALL(mock_callbacks_, + OnPeriodicSyncStarted(request_id_2, static_cast(ErrorCode::SUCCESS), _, _, _, + _, _)) + .Times(1); // Get LePeriodicAdvertisingSyncEstablished auto builder2 = LePeriodicAdvertisingSyncEstablishedBuilder::Create( - ErrorCode::SUCCESS, - sync_handle, - advertiser_sid, - address_with_type.GetAddressType(), - address_with_type.GetAddress(), - SecondaryPhyType::LE_1M, - 0xFF, - ClockAccuracy::PPM_250); + ErrorCode::SUCCESS, sync_handle, advertiser_sid, address_with_type.GetAddressType(), + address_with_type.GetAddress(), SecondaryPhyType::LE_1M, 0xFF, ClockAccuracy::PPM_250); event_view = LePeriodicAdvertisingSyncEstablishedView::Create( - LeMetaEventView::Create(EventView::Create(GetPacketView(std::move(builder2))))); + LeMetaEventView::Create(EventView::Create(GetPacketView(std::move(builder2))))); periodic_sync_manager_->HandleLePeriodicAdvertisingSyncEstablished(event_view); sync_handler(); } -TEST_F_WITH_FLAGS( - PeriodicSyncManagerTest, - handle_advertising_sync_established_after_create_command_error_test, - REQUIRES_FLAGS_ENABLED( - ACONFIG_FLAG(TEST_BT, leaudio_broadcast_assistant_handle_command_statuses))) { +TEST_F_WITH_FLAGS(PeriodicSyncManagerTest, + handle_advertising_sync_established_after_create_command_error_test, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG( + TEST_BT, leaudio_broadcast_assistant_handle_command_statuses))) { uint16_t sync_handle = 0x12; Address address; Address::FromString("00:11:22:33:44:55", address); @@ -652,36 +616,30 @@ TEST_F_WITH_FLAGS( int request_id_1 = 0x01; uint8_t advertiser_sid_1 = 0x02; PeriodicSyncStates request{ - .request_id = request_id_1, - .advertiser_sid = advertiser_sid_1, - .address_with_type = address_with_type, - .sync_handle = sync_handle, - .sync_state = PeriodicSyncState::PERIODIC_SYNC_STATE_IDLE, + .request_id = request_id_1, + .advertiser_sid = advertiser_sid_1, + .address_with_type = address_with_type, + .sync_handle = sync_handle, + .sync_state = PeriodicSyncState::PERIODIC_SYNC_STATE_IDLE, }; ASSERT_NO_FATAL_FAILURE(test_le_scanning_interface_->SetCommandFuture()); periodic_sync_manager_->StartSync(request, 0x04, 0x0A); auto packet = - test_le_scanning_interface_->GetCommand(OpCode::LE_PERIODIC_ADVERTISING_CREATE_SYNC); + test_le_scanning_interface_->GetCommand(OpCode::LE_PERIODIC_ADVERTISING_CREATE_SYNC); auto temp_view = - LePeriodicAdvertisingCreateSyncView::Create(LeScanningCommandView::Create(packet)); + LePeriodicAdvertisingCreateSyncView::Create(LeScanningCommandView::Create(packet)); ASSERT_TRUE(temp_view.IsValid()); - EXPECT_CALL( - mock_callbacks_, - OnPeriodicSyncStarted( - request_id_1, - static_cast(ErrorCode::MEMORY_CAPACITY_EXCEEDED), - _, - advertiser_sid_1, - _, - _, - _)) - .Times(1); + EXPECT_CALL(mock_callbacks_, + OnPeriodicSyncStarted(request_id_1, + static_cast(ErrorCode::MEMORY_CAPACITY_EXCEEDED), _, + advertiser_sid_1, _, _, _)) + .Times(1); // Get command status test_le_scanning_interface_->CommandStatusCallback( - LePeriodicAdvertisingCreateSyncStatusBuilder::Create( - ErrorCode::MEMORY_CAPACITY_EXCEEDED, 0x00)); + LePeriodicAdvertisingCreateSyncStatusBuilder::Create(ErrorCode::MEMORY_CAPACITY_EXCEEDED, + 0x00)); // Second request int request_id_2 = 0x02; @@ -696,36 +654,28 @@ TEST_F_WITH_FLAGS( // Get command status test_le_scanning_interface_->CommandStatusCallback( - LePeriodicAdvertisingCreateSyncStatusBuilder::Create(ErrorCode::SUCCESS, 0x00)); + LePeriodicAdvertisingCreateSyncStatusBuilder::Create(ErrorCode::SUCCESS, 0x00)); - EXPECT_CALL( - mock_callbacks_, - OnPeriodicSyncStarted( - request_id_2, static_cast(ErrorCode::SUCCESS), _, advertiser_sid_2, _, _, _)) - .Times(1); + EXPECT_CALL(mock_callbacks_, + OnPeriodicSyncStarted(request_id_2, static_cast(ErrorCode::SUCCESS), _, + advertiser_sid_2, _, _, _)) + .Times(1); // Get LePeriodicAdvertisingSyncEstablished auto builder = LePeriodicAdvertisingSyncEstablishedBuilder::Create( - ErrorCode::SUCCESS, - sync_handle, - advertiser_sid_2, - address_with_type.GetAddressType(), - address_with_type.GetAddress(), - SecondaryPhyType::LE_1M, - 0xFF, - ClockAccuracy::PPM_250); + ErrorCode::SUCCESS, sync_handle, advertiser_sid_2, address_with_type.GetAddressType(), + address_with_type.GetAddress(), SecondaryPhyType::LE_1M, 0xFF, ClockAccuracy::PPM_250); auto event_view = LePeriodicAdvertisingSyncEstablishedView::Create( - LeMetaEventView::Create(EventView::Create(GetPacketView(std::move(builder))))); + LeMetaEventView::Create(EventView::Create(GetPacketView(std::move(builder))))); periodic_sync_manager_->HandleLePeriodicAdvertisingSyncEstablished(event_view); sync_handler(); } -TEST_F_WITH_FLAGS( - PeriodicSyncManagerTest, - handle_advertising_sync_established_after_cancel_command_error_test, - REQUIRES_FLAGS_ENABLED( - ACONFIG_FLAG(TEST_BT, leaudio_broadcast_assistant_handle_command_statuses))) { +TEST_F_WITH_FLAGS(PeriodicSyncManagerTest, + handle_advertising_sync_established_after_cancel_command_error_test, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG( + TEST_BT, leaudio_broadcast_assistant_handle_command_statuses))) { uint16_t sync_handle = 0x12; Address address; Address::FromString("00:11:22:33:44:55", address); @@ -735,48 +685,42 @@ TEST_F_WITH_FLAGS( uint8_t advertiser_sid_1 = 0x02; int request_id_1 = 0x01; PeriodicSyncStates request{ - .request_id = request_id_1, - .advertiser_sid = advertiser_sid_1, - .address_with_type = address_with_type, - .sync_handle = sync_handle, - .sync_state = PeriodicSyncState::PERIODIC_SYNC_STATE_IDLE, + .request_id = request_id_1, + .advertiser_sid = advertiser_sid_1, + .address_with_type = address_with_type, + .sync_handle = sync_handle, + .sync_state = PeriodicSyncState::PERIODIC_SYNC_STATE_IDLE, }; ASSERT_NO_FATAL_FAILURE(test_le_scanning_interface_->SetCommandFuture()); periodic_sync_manager_->StartSync(request, 0x04, 0x0A); auto packet = - test_le_scanning_interface_->GetCommand(OpCode::LE_PERIODIC_ADVERTISING_CREATE_SYNC); + test_le_scanning_interface_->GetCommand(OpCode::LE_PERIODIC_ADVERTISING_CREATE_SYNC); auto temp_view = - LePeriodicAdvertisingCreateSyncView::Create(LeScanningCommandView::Create(packet)); + LePeriodicAdvertisingCreateSyncView::Create(LeScanningCommandView::Create(packet)); ASSERT_TRUE(temp_view.IsValid()); // Get command status test_le_scanning_interface_->CommandStatusCallback( - LePeriodicAdvertisingCreateSyncStatusBuilder::Create(ErrorCode::SUCCESS, 0x00)); + LePeriodicAdvertisingCreateSyncStatusBuilder::Create(ErrorCode::SUCCESS, 0x00)); EXPECT_CALL( - mock_callbacks_, - OnPeriodicSyncStarted( - request_id_1, - static_cast(ErrorCode::ADVERTISING_TIMEOUT), - _, - advertiser_sid_1, - _, - _, - _)) - .Times(1); + mock_callbacks_, + OnPeriodicSyncStarted(request_id_1, static_cast(ErrorCode::ADVERTISING_TIMEOUT), + _, advertiser_sid_1, _, _, _)) + .Times(1); ASSERT_NO_FATAL_FAILURE(test_le_scanning_interface_->SetCommandFuture()); periodic_sync_manager_->OnStartSyncTimeout(); - packet = - test_le_scanning_interface_->GetCommand(OpCode::LE_PERIODIC_ADVERTISING_CREATE_SYNC_CANCEL); + packet = test_le_scanning_interface_->GetCommand( + OpCode::LE_PERIODIC_ADVERTISING_CREATE_SYNC_CANCEL); auto temp_view2 = - LePeriodicAdvertisingCreateSyncCancelView::Create(LeScanningCommandView::Create(packet)); + LePeriodicAdvertisingCreateSyncCancelView::Create(LeScanningCommandView::Create(packet)); ASSERT_TRUE(temp_view2.IsValid()); // Get command status test_le_scanning_interface_->CommandCompleteCallback( - LePeriodicAdvertisingCreateSyncCancelCompleteBuilder::Create( - 0x00, ErrorCode::COMMAND_DISALLOWED)); + LePeriodicAdvertisingCreateSyncCancelCompleteBuilder::Create( + 0x00, ErrorCode::COMMAND_DISALLOWED)); // Second request int request_id_2 = 0x02; @@ -791,26 +735,19 @@ TEST_F_WITH_FLAGS( // Get command status test_le_scanning_interface_->CommandStatusCallback( - LePeriodicAdvertisingCreateSyncStatusBuilder::Create(ErrorCode::SUCCESS, 0x00)); + LePeriodicAdvertisingCreateSyncStatusBuilder::Create(ErrorCode::SUCCESS, 0x00)); - EXPECT_CALL( - mock_callbacks_, - OnPeriodicSyncStarted( - request_id_2, static_cast(ErrorCode::SUCCESS), _, advertiser_sid_2, _, _, _)) - .Times(1); + EXPECT_CALL(mock_callbacks_, + OnPeriodicSyncStarted(request_id_2, static_cast(ErrorCode::SUCCESS), _, + advertiser_sid_2, _, _, _)) + .Times(1); // Get LePeriodicAdvertisingSyncEstablished auto builder2 = LePeriodicAdvertisingSyncEstablishedBuilder::Create( - ErrorCode::SUCCESS, - sync_handle, - advertiser_sid_2, - address_with_type.GetAddressType(), - address_with_type.GetAddress(), - SecondaryPhyType::LE_1M, - 0xFF, - ClockAccuracy::PPM_250); + ErrorCode::SUCCESS, sync_handle, advertiser_sid_2, address_with_type.GetAddressType(), + address_with_type.GetAddress(), SecondaryPhyType::LE_1M, 0xFF, ClockAccuracy::PPM_250); auto event_view = LePeriodicAdvertisingSyncEstablishedView::Create( - LeMetaEventView::Create(EventView::Create(GetPacketView(std::move(builder2))))); + LeMetaEventView::Create(EventView::Create(GetPacketView(std::move(builder2))))); periodic_sync_manager_->HandleLePeriodicAdvertisingSyncEstablished(event_view); sync_handler(); @@ -824,48 +761,44 @@ TEST_F(PeriodicSyncManagerTest, handle_periodic_advertising_report_test) { Address::FromString("00:11:22:33:44:55", address); AddressWithType address_with_type = AddressWithType(address, AddressType::PUBLIC_DEVICE_ADDRESS); PeriodicSyncStates request{ - .request_id = 0x01, - .advertiser_sid = advertiser_sid, - .address_with_type = address_with_type, - .sync_handle = sync_handle, - .sync_state = PeriodicSyncState::PERIODIC_SYNC_STATE_IDLE, + .request_id = 0x01, + .advertiser_sid = advertiser_sid, + .address_with_type = address_with_type, + .sync_handle = sync_handle, + .sync_state = PeriodicSyncState::PERIODIC_SYNC_STATE_IDLE, }; ASSERT_NO_FATAL_FAILURE(test_le_scanning_interface_->SetCommandFuture()); periodic_sync_manager_->StartSync(request, 0x04, 0x0A); - auto packet = test_le_scanning_interface_->GetCommand(OpCode::LE_PERIODIC_ADVERTISING_CREATE_SYNC); + auto packet = + test_le_scanning_interface_->GetCommand(OpCode::LE_PERIODIC_ADVERTISING_CREATE_SYNC); auto temp_view = - LePeriodicAdvertisingCreateSyncView::Create(LeScanningCommandView::Create(packet)); + LePeriodicAdvertisingCreateSyncView::Create(LeScanningCommandView::Create(packet)); ASSERT_TRUE(temp_view.IsValid()); // Get command status test_le_scanning_interface_->CommandStatusCallback( - LePeriodicAdvertisingCreateSyncStatusBuilder::Create(ErrorCode::SUCCESS, 0x00)); + LePeriodicAdvertisingCreateSyncStatusBuilder::Create(ErrorCode::SUCCESS, 0x00)); EXPECT_CALL(mock_callbacks_, OnPeriodicSyncStarted); // Get LePeriodicAdvertisingSyncEstablished auto builder = LePeriodicAdvertisingSyncEstablishedBuilder::Create( - ErrorCode::SUCCESS, - sync_handle, - advertiser_sid, - address_with_type.GetAddressType(), - address_with_type.GetAddress(), - SecondaryPhyType::LE_1M, - 0xFF, - ClockAccuracy::PPM_250); + ErrorCode::SUCCESS, sync_handle, advertiser_sid, address_with_type.GetAddressType(), + address_with_type.GetAddress(), SecondaryPhyType::LE_1M, 0xFF, ClockAccuracy::PPM_250); auto event_view = LePeriodicAdvertisingSyncEstablishedView::Create( - LeMetaEventView::Create(EventView::Create(GetPacketView(std::move(builder))))); + LeMetaEventView::Create(EventView::Create(GetPacketView(std::move(builder))))); periodic_sync_manager_->HandleLePeriodicAdvertisingSyncEstablished(event_view); EXPECT_CALL(mock_callbacks_, OnPeriodicSyncReport); // Get LePeriodicAdvertisingReport std::vector data = {0x01, 0x02, 0x03}; - auto builder2 = LePeriodicAdvertisingReportBuilder::Create( - sync_handle, 0x1a, 0x1a, CteType::AOA_CONSTANT_TONE_EXTENSION, DataStatus::COMPLETE, data); + auto builder2 = LePeriodicAdvertisingReportBuilder::Create(sync_handle, 0x1a, 0x1a, + CteType::AOA_CONSTANT_TONE_EXTENSION, + DataStatus::COMPLETE, data); auto event_view2 = LePeriodicAdvertisingReportView::Create( - LeMetaEventView::Create(EventView::Create(GetPacketView(std::move(builder2))))); + LeMetaEventView::Create(EventView::Create(GetPacketView(std::move(builder2))))); periodic_sync_manager_->HandleLePeriodicAdvertisingReport(event_view2); sync_handler(); @@ -874,53 +807,48 @@ TEST_F(PeriodicSyncManagerTest, handle_periodic_advertising_report_test) { TEST_F(PeriodicSyncManagerTest, handle_biginfo_advertising_report_test) { uint16_t sync_handle = 0x12; uint8_t advertiser_sid = 0x02; -// start scan + // start scan Address address; Address::FromString("00:11:22:33:44:55", address); AddressWithType address_with_type = AddressWithType(address, AddressType::PUBLIC_DEVICE_ADDRESS); PeriodicSyncStates request{ - .request_id = 0x01, - .advertiser_sid = advertiser_sid, - .address_with_type = address_with_type, - .sync_handle = sync_handle, - .sync_state = PeriodicSyncState::PERIODIC_SYNC_STATE_IDLE, + .request_id = 0x01, + .advertiser_sid = advertiser_sid, + .address_with_type = address_with_type, + .sync_handle = sync_handle, + .sync_state = PeriodicSyncState::PERIODIC_SYNC_STATE_IDLE, }; ASSERT_NO_FATAL_FAILURE(test_le_scanning_interface_->SetCommandFuture()); periodic_sync_manager_->StartSync(request, 0x04, 0x0A); - auto packet = test_le_scanning_interface_->GetCommand(OpCode::LE_PERIODIC_ADVERTISING_CREATE_SYNC); + auto packet = + test_le_scanning_interface_->GetCommand(OpCode::LE_PERIODIC_ADVERTISING_CREATE_SYNC); auto temp_view = - LePeriodicAdvertisingCreateSyncView::Create(LeScanningCommandView::Create(packet)); + LePeriodicAdvertisingCreateSyncView::Create(LeScanningCommandView::Create(packet)); ASSERT_TRUE(temp_view.IsValid()); // Get command status test_le_scanning_interface_->CommandStatusCallback( - LePeriodicAdvertisingCreateSyncStatusBuilder::Create(ErrorCode::SUCCESS, 0x00)); + LePeriodicAdvertisingCreateSyncStatusBuilder::Create(ErrorCode::SUCCESS, 0x00)); EXPECT_CALL(mock_callbacks_, OnPeriodicSyncStarted); // Get LePeriodicAdvertisingSyncEstablished auto builder = LePeriodicAdvertisingSyncEstablishedBuilder::Create( - ErrorCode::SUCCESS, - sync_handle, - advertiser_sid, - address_with_type.GetAddressType(), - address_with_type.GetAddress(), - SecondaryPhyType::LE_1M, - 0xFF, - ClockAccuracy::PPM_250); + ErrorCode::SUCCESS, sync_handle, advertiser_sid, address_with_type.GetAddressType(), + address_with_type.GetAddress(), SecondaryPhyType::LE_1M, 0xFF, ClockAccuracy::PPM_250); auto event_view = LePeriodicAdvertisingSyncEstablishedView::Create( - LeMetaEventView::Create(EventView::Create(GetPacketView(std::move(builder))))); + LeMetaEventView::Create(EventView::Create(GetPacketView(std::move(builder))))); periodic_sync_manager_->HandleLePeriodicAdvertisingSyncEstablished(event_view); EXPECT_CALL(mock_callbacks_, OnBigInfoReport); // Get LeBigInfoAdvertisingReport auto builder2 = LeBigInfoAdvertisingReportBuilder::Create( - sync_handle, 2, 9, 24, 3, 1, 2, 100, 10000, 100, static_cast(2), - static_cast (0), static_cast (1)); + sync_handle, 2, 9, 24, 3, 1, 2, 100, 10000, 100, static_cast(2), + static_cast(0), static_cast(1)); auto event_view2 = LeBigInfoAdvertisingReportView::Create( - LeMetaEventView::Create(EventView::Create(GetPacketView(std::move(builder2))))); + LeMetaEventView::Create(EventView::Create(GetPacketView(std::move(builder2))))); periodic_sync_manager_->HandleLeBigInfoAdvertisingReport(event_view2); sync_handler(); diff --git a/system/gd/hci/le_scanning_callback.h b/system/gd/hci/le_scanning_callback.h index ef509339644..4bd75dbbc4b 100644 --- a/system/gd/hci/le_scanning_callback.h +++ b/system/gd/hci/le_scanning_callback.h @@ -29,7 +29,7 @@ namespace hci { using ScannerId = uint8_t; class AdvertisingFilterOnFoundOnLostInfo { - public: +public: // For MSFT-based advertisement events, the monitor handle associates every event with the monitor // filter this event comes from. uint8_t monitor_handle; @@ -47,7 +47,7 @@ class AdvertisingFilterOnFoundOnLostInfo { }; class ScanningCallback { - public: +public: enum ScanningStatus { SUCCESS, NO_RESOURCES = 0x80, @@ -56,46 +56,34 @@ class ScanningCallback { }; virtual ~ScanningCallback() = default; - virtual void OnScannerRegistered( - const bluetooth::hci::Uuid app_uuid, ScannerId scanner_id, ScanningStatus status) = 0; + virtual void OnScannerRegistered(const bluetooth::hci::Uuid app_uuid, ScannerId scanner_id, + ScanningStatus status) = 0; virtual void OnSetScannerParameterComplete(ScannerId scanner_id, ScanningStatus status) = 0; - virtual void OnScanResult( - uint16_t event_type, - uint8_t address_type, - Address address, - uint8_t primary_phy, - uint8_t secondary_phy, - uint8_t advertising_sid, - int8_t tx_power, - int8_t rssi, - uint16_t periodic_advertising_interval, - std::vector advertising_data) = 0; + virtual void OnScanResult(uint16_t event_type, uint8_t address_type, Address address, + uint8_t primary_phy, uint8_t secondary_phy, uint8_t advertising_sid, + int8_t tx_power, int8_t rssi, uint16_t periodic_advertising_interval, + std::vector advertising_data) = 0; virtual void OnTrackAdvFoundLost(AdvertisingFilterOnFoundOnLostInfo on_found_on_lost_info) = 0; - virtual void OnBatchScanReports( - int client_if, int status, int report_format, int num_records, std::vector data) = 0; + virtual void OnBatchScanReports(int client_if, int status, int report_format, int num_records, + std::vector data) = 0; virtual void OnBatchScanThresholdCrossed(int client_if) = 0; virtual void OnTimeout() = 0; virtual void OnFilterEnable(Enable enable, uint8_t status) = 0; virtual void OnFilterParamSetup(uint8_t available_spaces, ApcfAction action, uint8_t status) = 0; - virtual void OnFilterConfigCallback( - ApcfFilterType filter_type, uint8_t available_spaces, ApcfAction action, uint8_t status) = 0; - virtual void OnPeriodicSyncStarted( - int request_id, - uint8_t status, - uint16_t sync_handle, - uint8_t advertising_sid, - AddressWithType address_with_type, - uint8_t phy, - uint16_t interval) = 0; - virtual void OnPeriodicSyncReport( - uint16_t sync_handle, int8_t tx_power, int8_t rssi, uint8_t status, std::vector data) = 0; + virtual void OnFilterConfigCallback(ApcfFilterType filter_type, uint8_t available_spaces, + ApcfAction action, uint8_t status) = 0; + virtual void OnPeriodicSyncStarted(int request_id, uint8_t status, uint16_t sync_handle, + uint8_t advertising_sid, AddressWithType address_with_type, + uint8_t phy, uint16_t interval) = 0; + virtual void OnPeriodicSyncReport(uint16_t sync_handle, int8_t tx_power, int8_t rssi, + uint8_t status, std::vector data) = 0; virtual void OnPeriodicSyncLost(uint16_t sync_handle) = 0; virtual void OnPeriodicSyncTransferred(int pa_source, uint8_t status, Address address) = 0; virtual void OnBigInfoReport(uint16_t sync_handle, bool encrypted) = 0; }; class AdvertisingPacketContentFilterCommand { - public: +public: ApcfFilterType filter_type; Address address; ApcfApplicationAddressType application_address_type; @@ -116,7 +104,7 @@ class AdvertisingPacketContentFilterCommand { }; class AdvertisingFilterParameter { - public: +public: uint16_t feature_selection; uint16_t list_logic_type; uint8_t filter_logic_type; diff --git a/system/gd/hci/le_scanning_interface.h b/system/gd/hci/le_scanning_interface.h index ad6e155e5d5..d26cf536040 100644 --- a/system/gd/hci/le_scanning_interface.h +++ b/system/gd/hci/le_scanning_interface.h @@ -23,15 +23,15 @@ namespace bluetooth { namespace hci { constexpr hci::SubeventCode LeScanningEvents[] = { - hci::SubeventCode::SCAN_TIMEOUT, - hci::SubeventCode::ADVERTISING_REPORT, - hci::SubeventCode::DIRECTED_ADVERTISING_REPORT, - hci::SubeventCode::EXTENDED_ADVERTISING_REPORT, - hci::SubeventCode::PERIODIC_ADVERTISING_REPORT, - hci::SubeventCode::PERIODIC_ADVERTISING_SYNC_ESTABLISHED, - hci::SubeventCode::PERIODIC_ADVERTISING_SYNC_LOST, - hci::SubeventCode::PERIODIC_ADVERTISING_SYNC_TRANSFER_RECEIVED, - hci::SubeventCode::BIG_INFO_ADVERTISING_REPORT, + hci::SubeventCode::SCAN_TIMEOUT, + hci::SubeventCode::ADVERTISING_REPORT, + hci::SubeventCode::DIRECTED_ADVERTISING_REPORT, + hci::SubeventCode::EXTENDED_ADVERTISING_REPORT, + hci::SubeventCode::PERIODIC_ADVERTISING_REPORT, + hci::SubeventCode::PERIODIC_ADVERTISING_SYNC_ESTABLISHED, + hci::SubeventCode::PERIODIC_ADVERTISING_SYNC_LOST, + hci::SubeventCode::PERIODIC_ADVERTISING_SYNC_TRANSFER_RECEIVED, + hci::SubeventCode::BIG_INFO_ADVERTISING_REPORT, }; typedef CommandInterface LeScanningInterface; diff --git a/system/gd/hci/le_scanning_manager.cc b/system/gd/hci/le_scanning_manager.cc index 922da0e1d46..4ade641f931 100644 --- a/system/gd/hci/le_scanning_manager.cc +++ b/system/gd/hci/le_scanning_manager.cc @@ -61,7 +61,8 @@ constexpr uint8_t kDataStatusBits = 5; // system properties const std::string kLeRxPathLossCompProperty = "bluetooth.hardware.radio.le_rx_path_loss_comp_db"; -const ModuleFactory LeScanningManager::Factory = ModuleFactory([]() { return new LeScanningManager(); }); +const ModuleFactory LeScanningManager::Factory = + ModuleFactory([]() { return new LeScanningManager(); }); enum class ScanApiType { LEGACY = 1, @@ -75,87 +76,63 @@ struct Scanner { }; class NullScanningCallback : public ScanningCallback { - void OnScannerRegistered( - const Uuid /* app_uuid */, ScannerId /* scanner_id */, ScanningStatus /* status */) override { + void OnScannerRegistered(const Uuid /* app_uuid */, ScannerId /* scanner_id */, + ScanningStatus /* status */) override { log::info("OnScannerRegistered in NullScanningCallback"); } - void OnSetScannerParameterComplete( - ScannerId /* scanner_id */, ScanningStatus /* status */) override { + void OnSetScannerParameterComplete(ScannerId /* scanner_id */, + ScanningStatus /* status */) override { log::info("OnSetScannerParameterComplete in NullScanningCallback"); } - void OnScanResult( - uint16_t /* event_type */, - uint8_t /* address_type */, - Address /* address */, - uint8_t /* primary_phy */, - uint8_t /* secondary_phy */, - uint8_t /* advertising_sid */, - int8_t /* tx_power */, - int8_t /* rssi */, - uint16_t /* periodic_advertising_interval */, - std::vector /* advertising_data */) override { + void OnScanResult(uint16_t /* event_type */, uint8_t /* address_type */, Address /* address */, + uint8_t /* primary_phy */, uint8_t /* secondary_phy */, + uint8_t /* advertising_sid */, int8_t /* tx_power */, int8_t /* rssi */, + uint16_t /* periodic_advertising_interval */, + std::vector /* advertising_data */) override { log::info("OnScanResult in NullScanningCallback"); } void OnTrackAdvFoundLost( - AdvertisingFilterOnFoundOnLostInfo /* on_found_on_lost_info */) override { + AdvertisingFilterOnFoundOnLostInfo /* on_found_on_lost_info */) override { log::info("OnTrackAdvFoundLost in NullScanningCallback"); } - void OnBatchScanReports( - int /* client_if */, - int /* status */, - int /* report_format */, - int /* num_records */, - std::vector /* data */) override { + void OnBatchScanReports(int /* client_if */, int /* status */, int /* report_format */, + int /* num_records */, std::vector /* data */) override { log::info("OnBatchScanReports in NullScanningCallback"); } void OnBatchScanThresholdCrossed(int /* client_if */) override { log::info("OnBatchScanThresholdCrossed in NullScanningCallback"); } - void OnTimeout() override { - log::info("OnTimeout in NullScanningCallback"); - } + void OnTimeout() override { log::info("OnTimeout in NullScanningCallback"); } void OnFilterEnable(Enable /* enable */, uint8_t /* status */) override { log::info("OnFilterEnable in NullScanningCallback"); } - void OnFilterParamSetup( - uint8_t /* available_spaces */, ApcfAction /* action */, uint8_t /* status */) override { + void OnFilterParamSetup(uint8_t /* available_spaces */, ApcfAction /* action */, + uint8_t /* status */) override { log::info("OnFilterParamSetup in NullScanningCallback"); } - void OnFilterConfigCallback( - ApcfFilterType /* filter_type */, - uint8_t /* available_spaces */, - ApcfAction /* action */, - uint8_t /* status */) override { + void OnFilterConfigCallback(ApcfFilterType /* filter_type */, uint8_t /* available_spaces */, + ApcfAction /* action */, uint8_t /* status */) override { log::info("OnFilterConfigCallback in NullScanningCallback"); } - void OnPeriodicSyncStarted( - int /* reg_id */, - uint8_t /* status */, - uint16_t /* sync_handle */, - uint8_t /* advertising_sid */, - AddressWithType /* address_with_type */, - uint8_t /* phy */, - uint16_t /* interval */) override { + void OnPeriodicSyncStarted(int /* reg_id */, uint8_t /* status */, uint16_t /* sync_handle */, + uint8_t /* advertising_sid */, AddressWithType /* address_with_type */, + uint8_t /* phy */, uint16_t /* interval */) override { log::info("OnPeriodicSyncStarted in NullScanningCallback"); - }; - void OnPeriodicSyncReport( - uint16_t /* sync_handle */, - int8_t /* tx_power */, - int8_t /* rssi */, - uint8_t /* status */, - std::vector /* data */) override { + } + void OnPeriodicSyncReport(uint16_t /* sync_handle */, int8_t /* tx_power */, int8_t /* rssi */, + uint8_t /* status */, std::vector /* data */) override { log::info("OnPeriodicSyncReport in NullScanningCallback"); - }; + } void OnPeriodicSyncLost(uint16_t /* sync_handle */) override { log::info("OnPeriodicSyncLost in NullScanningCallback"); - }; - void OnPeriodicSyncTransferred( - int /* pa_source */, uint8_t /* status */, Address /* address */) override { + } + void OnPeriodicSyncTransferred(int /* pa_source */, uint8_t /* status */, + Address /* address */) override { log::info("OnPeriodicSyncTransferred in NullScanningCallback"); - }; + } void OnBigInfoReport(uint16_t /* sync_handle */, bool /* encrypted */) { log::info("OnBigInfoReport in NullScanningCallback"); - }; + } }; enum class BatchScanState { @@ -189,12 +166,8 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { } } - void start( - os::Handler* handler, - HciLayer* hci_layer, - Controller* controller, - AclManager* acl_manager, - storage::StorageModule* storage_module) { + void start(os::Handler* handler, HciLayer* hci_layer, Controller* controller, + AclManager* acl_manager, storage::StorageModule* storage_module) { module_handler_ = handler; hci_layer_ = hci_layer; controller_ = controller; @@ -202,7 +175,7 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { storage_module_ = storage_module; le_address_manager_ = acl_manager->GetLeAddressManager(); le_scanning_interface_ = hci_layer_->GetLeScanningInterface( - module_handler_->BindOn(this, &LeScanningManager::impl::handle_scan_results)); + module_handler_->BindOn(this, &LeScanningManager::impl::handle_scan_results)); periodic_sync_manager_.Init(le_scanning_interface_, module_handler_); /* Check to see if the opcode is supported and C19 (support for extended advertising). */ if (controller_->IsSupported(OpCode::LE_SET_EXTENDED_SCAN_PARAMETERS) && @@ -219,20 +192,20 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { is_filter_supported_ = controller_->IsSupported(OpCode::LE_ADV_FILTER); if (is_filter_supported_) { le_scanning_interface_->EnqueueCommand( - LeAdvFilterReadExtendedFeaturesBuilder::Create(), - module_handler_->BindOnceOn(this, &impl::on_apcf_read_extended_features_complete)); + LeAdvFilterReadExtendedFeaturesBuilder::Create(), + module_handler_->BindOnceOn(this, &impl::on_apcf_read_extended_features_complete)); } is_batch_scan_supported_ = controller->IsSupported(OpCode::LE_BATCH_SCAN); is_periodic_advertising_sync_transfer_sender_supported_ = - controller_->SupportsBlePeriodicAdvertisingSyncTransferSender(); + controller_->SupportsBlePeriodicAdvertisingSyncTransferSender(); total_num_of_advt_tracked_ = controller->GetVendorCapabilities().total_num_of_advt_tracked_; if (is_batch_scan_supported_) { hci_layer_->RegisterVendorSpecificEventHandler( - VseSubeventCode::BLE_THRESHOLD, - handler->BindOn(this, &LeScanningManager::impl::on_storage_threshold_breach)); + VseSubeventCode::BLE_THRESHOLD, + handler->BindOn(this, &LeScanningManager::impl::on_storage_threshold_breach)); hci_layer_->RegisterVendorSpecificEventHandler( - VseSubeventCode::BLE_TRACKING, - handler->BindOn(this, &LeScanningManager::impl::on_advertisement_tracking)); + VseSubeventCode::BLE_TRACKING, + handler->BindOn(this, &LeScanningManager::impl::on_advertisement_tracking)); } scanners_ = std::vector(kMaxAppNum + 1); for (size_t i = 0; i < scanners_.size(); i++) { @@ -273,24 +246,26 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { case SubeventCode::PERIODIC_ADVERTISING_SYNC_ESTABLISHED: LePeriodicAdvertisingSyncEstablishedView::Create(event); periodic_sync_manager_.HandleLePeriodicAdvertisingSyncEstablished( - LePeriodicAdvertisingSyncEstablishedView::Create(event)); + LePeriodicAdvertisingSyncEstablishedView::Create(event)); break; case SubeventCode::PERIODIC_ADVERTISING_REPORT: - periodic_sync_manager_.HandleLePeriodicAdvertisingReport(LePeriodicAdvertisingReportView::Create(event)); + periodic_sync_manager_.HandleLePeriodicAdvertisingReport( + LePeriodicAdvertisingReportView::Create(event)); break; case SubeventCode::PERIODIC_ADVERTISING_SYNC_LOST: - periodic_sync_manager_.HandleLePeriodicAdvertisingSyncLost(LePeriodicAdvertisingSyncLostView::Create(event)); + periodic_sync_manager_.HandleLePeriodicAdvertisingSyncLost( + LePeriodicAdvertisingSyncLostView::Create(event)); break; case SubeventCode::PERIODIC_ADVERTISING_SYNC_TRANSFER_RECEIVED: periodic_sync_manager_.HandleLePeriodicAdvertisingSyncTransferReceived( - LePeriodicAdvertisingSyncTransferReceivedView::Create(event)); + LePeriodicAdvertisingSyncTransferReceivedView::Create(event)); break; case SubeventCode::SCAN_TIMEOUT: scanning_callbacks_->OnTimeout(); break; case SubeventCode::BIG_INFO_ADVERTISING_REPORT: periodic_sync_manager_.HandleLeBigInfoAdvertisingReport( - LeBigInfoAdvertisingReportView::Create(event)); + LeBigInfoAdvertisingReportView::Create(event)); break; default: log::fatal("Unknown advertising subevent {}", SubeventCodeText(event.GetSubeventCode())); @@ -362,15 +337,15 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { switch (report.event_type_) { case AdvertisingEventType::ADV_IND: extended_event_type = transform_to_extended_event_type( - {.connectable = true, .scannable = true, .legacy = true}); + {.connectable = true, .scannable = true, .legacy = true}); break; case AdvertisingEventType::ADV_DIRECT_IND: extended_event_type = transform_to_extended_event_type( - {.connectable = true, .directed = true, .legacy = true}); + {.connectable = true, .directed = true, .legacy = true}); break; case AdvertisingEventType::ADV_SCAN_IND: extended_event_type = - transform_to_extended_event_type({.scannable = true, .legacy = true}); + transform_to_extended_event_type({.scannable = true, .legacy = true}); break; case AdvertisingEventType::ADV_NONCONN_IND: extended_event_type = transform_to_extended_event_type({.legacy = true}); @@ -380,10 +355,12 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { // We don't know if the initial advertising report was connectable or not. // LeScanningReassembler fixes the connectable field. extended_event_type = transform_to_extended_event_type( - {.scannable = true, .scan_response = true, .legacy = true}); + {.scannable = true, .scan_response = true, .legacy = true}); } else { - extended_event_type = transform_to_extended_event_type( - {.connectable = true, .scannable = true, .scan_response = true, .legacy = true}); + extended_event_type = transform_to_extended_event_type({.connectable = true, + .scannable = true, + .scan_response = true, + .legacy = true}); } break; default: @@ -392,16 +369,10 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { } process_advertising_package_content( - extended_event_type, - (uint8_t)report.address_type_, - report.address_, - (uint8_t)PrimaryPhyType::LE_1M, - (uint8_t)SecondaryPhyType::NO_PACKETS, - kAdvertisingDataInfoNotPresent, - kTxPowerInformationNotPresent, - report.rssi_, - kNotPeriodicAdvertisement, - report.advertising_data_); + extended_event_type, (uint8_t)report.address_type_, report.address_, + (uint8_t)PrimaryPhyType::LE_1M, (uint8_t)SecondaryPhyType::NO_PACKETS, + kAdvertisingDataInfoNotPresent, kTxPowerInformationNotPresent, report.rssi_, + kNotPeriodicAdvertisement, report.advertising_data_); } } @@ -422,34 +393,24 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { } for (LeExtendedAdvertisingResponseRaw& report : reports) { - uint16_t event_type = report.connectable_ | (report.scannable_ << kScannableBit) | - (report.directed_ << kDirectedBit) | (report.scan_response_ << kScanResponseBit) | - (report.legacy_ << kLegacyBit) | ((uint16_t)report.data_status_ << kDataStatusBits); + uint16_t event_type = + report.connectable_ | (report.scannable_ << kScannableBit) | + (report.directed_ << kDirectedBit) | (report.scan_response_ << kScanResponseBit) | + (report.legacy_ << kLegacyBit) | ((uint16_t)report.data_status_ << kDataStatusBits); process_advertising_package_content( - event_type, - (uint8_t)report.address_type_, - report.address_, - (uint8_t)report.primary_phy_, - (uint8_t)report.secondary_phy_, - report.advertising_sid_, - report.tx_power_, - report.rssi_, - report.periodic_advertising_interval_, - report.advertising_data_); - } - } - - void process_advertising_package_content( - uint16_t event_type, - uint8_t address_type, - Address address, - uint8_t primary_phy, - uint8_t secondary_phy, - uint8_t advertising_sid, - int8_t tx_power, - int8_t rssi, - uint16_t periodic_advertising_interval, - const std::vector& advertising_data) { + event_type, (uint8_t)report.address_type_, report.address_, + (uint8_t)report.primary_phy_, (uint8_t)report.secondary_phy_, report.advertising_sid_, + report.tx_power_, report.rssi_, report.periodic_advertising_interval_, + report.advertising_data_); + } + } + + void process_advertising_package_content(uint16_t event_type, uint8_t address_type, + Address address, uint8_t primary_phy, + uint8_t secondary_phy, uint8_t advertising_sid, + int8_t tx_power, int8_t rssi, + uint16_t periodic_advertising_interval, + const std::vector& advertising_data) { // When using the vendor command Le Set Extended Params to // configure a filter accept list based e.g. on the service UUIDs // found in the report, we ignore the scan responses as we cannot be @@ -458,12 +419,12 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { // with hardware-filtering features should we ignore waiting for scan response, and make sure // scan responses are still reported too. scanning_reassembler_.SetIgnoreScanResponses( - le_scan_type_ == LeScanType::PASSIVE || - filter_policy_ == LeScanningFilterPolicy::FILTER_ACCEPT_LIST_ONLY); + le_scan_type_ == LeScanType::PASSIVE || + filter_policy_ == LeScanningFilterPolicy::FILTER_ACCEPT_LIST_ONLY); std::optional processed_report = - scanning_reassembler_.ProcessAdvertisingReport( - event_type, address_type, address, advertising_sid, advertising_data); + scanning_reassembler_.ProcessAdvertisingReport(event_type, address_type, address, + advertising_sid, advertising_data); if (processed_report.has_value()) { switch (address_type) { @@ -478,21 +439,14 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { } const uint16_t result_event_type = - com::android::bluetooth::flags::fix_nonconnectable_scannable_advertisement() - ? processed_report->extended_event_type - : event_type; + com::android::bluetooth::flags::fix_nonconnectable_scannable_advertisement() + ? processed_report->extended_event_type + : event_type; scanning_callbacks_->OnScanResult( - result_event_type, - address_type, - address, - primary_phy, - secondary_phy, - advertising_sid, - tx_power, - get_rssi_after_calibration(rssi), - periodic_advertising_interval, - std::move(processed_report->data)); + result_event_type, address_type, address, primary_phy, secondary_phy, advertising_sid, + tx_power, get_rssi_after_calibration(rssi), periodic_advertising_interval, + std::move(processed_report->data)); } } @@ -521,23 +475,23 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { switch (api_type_) { case ScanApiType::EXTENDED: le_scanning_interface_->EnqueueCommand( - LeSetExtendedScanParametersBuilder::Create( - own_address_type_, filter_policy_, phys_in_use, parameter_vector), - module_handler_->BindOnceOn(this, &impl::on_set_scan_parameter_complete)); + LeSetExtendedScanParametersBuilder::Create(own_address_type_, filter_policy_, + phys_in_use, parameter_vector), + module_handler_->BindOnceOn(this, &impl::on_set_scan_parameter_complete)); break; case ScanApiType::ANDROID_HCI: le_scanning_interface_->EnqueueCommand( - LeExtendedScanParamsBuilder::Create( - le_scan_type_, interval_ms_, window_ms_, own_address_type_, filter_policy_), - module_handler_->BindOnceOn(this, &impl::on_set_scan_parameter_complete)); + LeExtendedScanParamsBuilder::Create(le_scan_type_, interval_ms_, window_ms_, + own_address_type_, filter_policy_), + module_handler_->BindOnceOn(this, &impl::on_set_scan_parameter_complete)); break; case ScanApiType::LEGACY: le_scanning_interface_->EnqueueCommand( - LeSetScanParametersBuilder::Create( - le_scan_type_, interval_ms_, window_ms_, own_address_type_, filter_policy_), - module_handler_->BindOnceOn(this, &impl::on_set_scan_parameter_complete)); + LeSetScanParametersBuilder::Create(le_scan_type_, interval_ms_, window_ms_, + own_address_type_, filter_policy_), + module_handler_->BindOnceOn(this, &impl::on_set_scan_parameter_complete)); break; } } @@ -546,7 +500,8 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { for (uint8_t i = 1; i <= kMaxAppNum; i++) { if (scanners_[i].in_use && scanners_[i].app_uuid == app_uuid) { log::error("Application already registered {}", app_uuid.ToString()); - scanning_callbacks_->OnScannerRegistered(app_uuid, 0x00, ScanningCallback::ScanningStatus::INTERNAL_ERROR); + scanning_callbacks_->OnScannerRegistered(app_uuid, 0x00, + ScanningCallback::ScanningStatus::INTERNAL_ERROR); return; } } @@ -556,13 +511,15 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { if (!scanners_[i].in_use) { scanners_[i].app_uuid = app_uuid; scanners_[i].in_use = true; - scanning_callbacks_->OnScannerRegistered(app_uuid, i, ScanningCallback::ScanningStatus::SUCCESS); + scanning_callbacks_->OnScannerRegistered(app_uuid, i, + ScanningCallback::ScanningStatus::SUCCESS); return; } } log::error("Unable to register scanner, max client reached:{}", kMaxAppNum); - scanning_callbacks_->OnScannerRegistered(app_uuid, 0x00, ScanningCallback::ScanningStatus::NO_RESOURCES); + scanning_callbacks_->OnScannerRegistered(app_uuid, 0x00, + ScanningCallback::ScanningStatus::NO_RESOURCES); } void unregister_scanner(ScannerId scanner_id) { @@ -611,23 +568,22 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { switch (api_type_) { case ScanApiType::EXTENDED: le_scanning_interface_->EnqueueCommand( - LeSetExtendedScanEnableBuilder::Create( - Enable::ENABLED, + LeSetExtendedScanEnableBuilder::Create( + Enable::ENABLED, #if TARGET_FLOSS - FilterDuplicates::ENABLED /* filter duplicates */, + FilterDuplicates::ENABLED /* filter duplicates */, #else - FilterDuplicates::DISABLED /* filter duplicates */, + FilterDuplicates::DISABLED /* filter duplicates */, #endif - 0, - 0), - module_handler_->BindOnce(check_complete)); + 0, 0), + module_handler_->BindOnce(check_complete)); break; case ScanApiType::ANDROID_HCI: case ScanApiType::LEGACY: le_scanning_interface_->EnqueueCommand( - LeSetScanEnableBuilder::Create( - Enable::ENABLED, Enable::DISABLED /* filter duplicates */), - module_handler_->BindOnce(check_complete)); + LeSetScanEnableBuilder::Create(Enable::ENABLED, + Enable::DISABLED /* filter duplicates */), + module_handler_->BindOnce(check_complete)); break; } } @@ -642,33 +598,28 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { switch (api_type_) { case ScanApiType::EXTENDED: le_scanning_interface_->EnqueueCommand( - LeSetExtendedScanEnableBuilder::Create( - Enable::DISABLED, + LeSetExtendedScanEnableBuilder::Create( + Enable::DISABLED, #if TARGET_FLOSS - FilterDuplicates::ENABLED /* filter duplicates */, + FilterDuplicates::ENABLED /* filter duplicates */, #else - FilterDuplicates::DISABLED /* filter duplicates */, + FilterDuplicates::DISABLED /* filter duplicates */, #endif - 0, - 0), - module_handler_->BindOnce(check_complete)); + 0, 0), + module_handler_->BindOnce(check_complete)); break; case ScanApiType::ANDROID_HCI: case ScanApiType::LEGACY: le_scanning_interface_->EnqueueCommand( - LeSetScanEnableBuilder::Create( - Enable::DISABLED, Enable::DISABLED /* filter duplicates */), - module_handler_->BindOnce(check_complete)); + LeSetScanEnableBuilder::Create(Enable::DISABLED, + Enable::DISABLED /* filter duplicates */), + module_handler_->BindOnce(check_complete)); break; } } - void set_scan_parameters( - ScannerId scanner_id, - LeScanType scan_type, - uint16_t scan_interval, - uint16_t scan_window, - uint8_t scan_phy) { + void set_scan_parameters(ScannerId scanner_id, LeScanType scan_type, uint16_t scan_interval, + uint16_t scan_window, uint8_t scan_phy) { uint32_t max_scan_interval = kLeScanIntervalMax; uint32_t max_scan_window = kLeScanWindowMax; if (api_type_ == ScanApiType::EXTENDED) { @@ -679,25 +630,27 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { if (scan_type != LeScanType::ACTIVE && scan_type != LeScanType::PASSIVE) { log::error("Invalid scan type"); scanning_callbacks_->OnSetScannerParameterComplete( - scanner_id, ScanningCallback::ScanningStatus::ILLEGAL_PARAMETER); + scanner_id, ScanningCallback::ScanningStatus::ILLEGAL_PARAMETER); return; } if (scan_interval > max_scan_interval || scan_interval < kLeScanIntervalMin) { log::error("Invalid scan_interval {}", scan_interval); scanning_callbacks_->OnSetScannerParameterComplete( - scanner_id, ScanningCallback::ScanningStatus::ILLEGAL_PARAMETER); + scanner_id, ScanningCallback::ScanningStatus::ILLEGAL_PARAMETER); return; } if (scan_window > max_scan_window || scan_window < kLeScanWindowMin) { log::error("Invalid scan_window {}", scan_window); scanning_callbacks_->OnSetScannerParameterComplete( - scanner_id, ScanningCallback::ScanningStatus::ILLEGAL_PARAMETER); + scanner_id, ScanningCallback::ScanningStatus::ILLEGAL_PARAMETER); return; } le_scan_type_ = scan_type; interval_ms_ = scan_interval; window_ms_ = scan_window; - if (com::android::bluetooth::flags::phy_to_native()) phy_ = scan_phy; + if (com::android::bluetooth::flags::phy_to_native()) { + phy_ = scan_phy; + } scanning_callbacks_->OnSetScannerParameterComplete(scanner_id, ScanningCallback::SUCCESS); } @@ -713,8 +666,8 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { Enable apcf_enable = enable ? Enable::ENABLED : Enable::DISABLED; le_scanning_interface_->EnqueueCommand( - LeAdvFilterEnableBuilder::Create(apcf_enable), - module_handler_->BindOnceOn(this, &impl::on_advertising_filter_complete)); + LeAdvFilterEnableBuilder::Create(apcf_enable), + module_handler_->BindOnceOn(this, &impl::on_advertising_filter_complete)); } bool is_bonded(Address target_address) { @@ -728,8 +681,8 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { return false; } - void scan_filter_parameter_setup( - ApcfAction action, uint8_t filter_index, AdvertisingFilterParameter advertising_filter_parameter) { + void scan_filter_parameter_setup(ApcfAction action, uint8_t filter_index, + AdvertisingFilterParameter advertising_filter_parameter) { if (!is_filter_supported_) { log::warn("Advertising filter is not supported"); return; @@ -739,32 +692,32 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { switch (action) { case ApcfAction::ADD: le_scanning_interface_->EnqueueCommand( - LeAdvFilterAddFilteringParametersBuilder::Create( - filter_index, - advertising_filter_parameter.feature_selection, - advertising_filter_parameter.list_logic_type, - advertising_filter_parameter.filter_logic_type, - advertising_filter_parameter.rssi_high_thresh, - advertising_filter_parameter.delivery_mode, - advertising_filter_parameter.onfound_timeout, - advertising_filter_parameter.onfound_timeout_cnt, - advertising_filter_parameter.rssi_low_thresh, - advertising_filter_parameter.onlost_timeout, - advertising_filter_parameter.num_of_tracking_entries), - module_handler_->BindOnceOn(this, &impl::on_advertising_filter_complete)); + LeAdvFilterAddFilteringParametersBuilder::Create( + filter_index, advertising_filter_parameter.feature_selection, + advertising_filter_parameter.list_logic_type, + advertising_filter_parameter.filter_logic_type, + advertising_filter_parameter.rssi_high_thresh, + advertising_filter_parameter.delivery_mode, + advertising_filter_parameter.onfound_timeout, + advertising_filter_parameter.onfound_timeout_cnt, + advertising_filter_parameter.rssi_low_thresh, + advertising_filter_parameter.onlost_timeout, + advertising_filter_parameter.num_of_tracking_entries), + module_handler_->BindOnceOn(this, &impl::on_advertising_filter_complete)); break; case ApcfAction::DELETE: tracker_id_map_.erase(filter_index); le_scanning_interface_->EnqueueCommand( - LeAdvFilterDeleteFilteringParametersBuilder::Create(filter_index), - module_handler_->BindOnceOn(this, &impl::on_advertising_filter_complete)); + LeAdvFilterDeleteFilteringParametersBuilder::Create(filter_index), + module_handler_->BindOnceOn(this, &impl::on_advertising_filter_complete)); // IRK Scanning if (entry != remove_me_later_map_.end()) { // Don't want to remove for a bonded device if (!is_bonded(entry->second.GetAddress())) { le_address_manager_->RemoveDeviceFromResolvingList( - static_cast(entry->second.GetAddressType()), entry->second.GetAddress()); + static_cast(entry->second.GetAddressType()), + entry->second.GetAddress()); } remove_me_later_map_.erase(filter_index); } @@ -772,15 +725,16 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { break; case ApcfAction::CLEAR: le_scanning_interface_->EnqueueCommand( - LeAdvFilterClearFilteringParametersBuilder::Create(), - module_handler_->BindOnceOn(this, &impl::on_advertising_filter_complete)); + LeAdvFilterClearFilteringParametersBuilder::Create(), + module_handler_->BindOnceOn(this, &impl::on_advertising_filter_complete)); // IRK Scanning if (entry != remove_me_later_map_.end()) { // Don't want to remove for a bonded device if (!is_bonded(entry->second.GetAddress())) { le_address_manager_->RemoveDeviceFromResolvingList( - static_cast(entry->second.GetAddressType()), entry->second.GetAddress()); + static_cast(entry->second.GetAddressType()), + entry->second.GetAddress()); } remove_me_later_map_.erase(filter_index); } @@ -792,7 +746,8 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { } } - void scan_filter_add(uint8_t filter_index, std::vector filters) { + void scan_filter_add(uint8_t filter_index, + std::vector filters) { if (!is_filter_supported_) { log::warn("Advertising filter is not supported"); return; @@ -801,19 +756,22 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { ApcfAction apcf_action = ApcfAction::ADD; for (auto filter : filters) { /* If data is passed, both mask and data have to be the same length */ - if (filter.data.size() != filter.data_mask.size() && filter.data.size() != 0 && filter.data_mask.size() != 0) { + if (filter.data.size() != filter.data_mask.size() && filter.data.size() != 0 && + filter.data_mask.size() != 0) { log::error("data and data_mask are of different size"); continue; } switch (filter.filter_type) { case ApcfFilterType::BROADCASTER_ADDRESS: { - update_address_filter(apcf_action, filter_index, filter.address, filter.application_address_type, filter.irk); + update_address_filter(apcf_action, filter_index, filter.address, + filter.application_address_type, filter.irk); break; } case ApcfFilterType::SERVICE_UUID: case ApcfFilterType::SERVICE_SOLICITATION_UUID: { - update_uuid_filter(apcf_action, filter_index, filter.filter_type, filter.uuid, filter.uuid_mask); + update_uuid_filter(apcf_action, filter_index, filter.filter_type, filter.uuid, + filter.uuid_mask); break; } case ApcfFilterType::LOCAL_NAME: { @@ -821,8 +779,8 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { break; } case ApcfFilterType::MANUFACTURER_DATA: { - update_manufacturer_data_filter( - apcf_action, filter_index, filter.company, filter.company_mask, filter.data, filter.data_mask); + update_manufacturer_data_filter(apcf_action, filter_index, filter.company, + filter.company_mask, filter.data, filter.data_mask); break; } case ApcfFilterType::SERVICE_DATA: { @@ -831,19 +789,13 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { } case ApcfFilterType::TRANSPORT_DISCOVERY_DATA: { update_transport_discovery_data_filter( - apcf_action, - filter_index, - filter.org_id, - filter.tds_flags, - filter.tds_flags_mask, - filter.data, - filter.data_mask, - filter.meta_data_type, - filter.meta_data); + apcf_action, filter_index, filter.org_id, filter.tds_flags, filter.tds_flags_mask, + filter.data, filter.data_mask, filter.meta_data_type, filter.meta_data); break; } case ApcfFilterType::AD_TYPE: { - update_ad_type_filter(apcf_action, filter_index, filter.ad_type, filter.data, filter.data_mask); + update_ad_type_filter(apcf_action, filter_index, filter.ad_type, filter.data, + filter.data_mask); break; } default: @@ -855,12 +807,8 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { std::unordered_map remove_me_later_map_; - void update_address_filter( - ApcfAction action, - uint8_t filter_index, - Address address, - ApcfApplicationAddressType address_type, - std::array irk) { + void update_address_filter(ApcfAction action, uint8_t filter_index, Address address, + ApcfApplicationAddressType address_type, std::array irk) { if (action != ApcfAction::CLEAR) { /* * The vendor command (APCF Filtering 0x0157) takes Public (0) or Random (1) @@ -878,9 +826,9 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { * This should also cover if the RPA is derived from RANDOM STATIC. */ le_scanning_interface_->EnqueueCommand( - LeAdvFilterBroadcasterAddressBuilder::Create( - action, filter_index, address, ApcfApplicationAddressType::NOT_APPLICABLE), - module_handler_->BindOnceOn(this, &impl::on_advertising_filter_complete)); + LeAdvFilterBroadcasterAddressBuilder::Create( + action, filter_index, address, ApcfApplicationAddressType::NOT_APPLICABLE), + module_handler_->BindOnceOn(this, &impl::on_advertising_filter_complete)); if (!is_empty_128bit(irk)) { // If an entry exists for this filter index, replace data because the filter has been // updated. @@ -890,25 +838,28 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { // Don't want to remove for a bonded device if (!is_bonded(entry->second.GetAddress())) { le_address_manager_->RemoveDeviceFromResolvingList( - static_cast(entry->second.GetAddressType()), entry->second.GetAddress()); + static_cast(entry->second.GetAddressType()), + entry->second.GetAddress()); } remove_me_later_map_.erase(filter_index); } // Now replace it with a new one std::array empty_irk; - le_address_manager_->AddDeviceToResolvingList( - static_cast(address_type), address, irk, empty_irk); - remove_me_later_map_.emplace(filter_index, AddressWithType(address, static_cast(address_type))); + le_address_manager_->AddDeviceToResolvingList(static_cast(address_type), + address, irk, empty_irk); + remove_me_later_map_.emplace( + filter_index, AddressWithType(address, static_cast(address_type))); } } else { le_scanning_interface_->EnqueueCommand( - LeAdvFilterClearBroadcasterAddressBuilder::Create(filter_index), - module_handler_->BindOnceOn(this, &impl::on_advertising_filter_complete)); + LeAdvFilterClearBroadcasterAddressBuilder::Create(filter_index), + module_handler_->BindOnceOn(this, &impl::on_advertising_filter_complete)); auto entry = remove_me_later_map_.find(filter_index); if (entry != remove_me_later_map_.end()) { // TODO(optedoblivion): If not bonded - le_address_manager_->RemoveDeviceFromResolvingList(static_cast(address_type), address); + le_address_manager_->RemoveDeviceFromResolvingList( + static_cast(address_type), address); remove_me_later_map_.erase(filter_index); } } @@ -923,8 +874,8 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { return true; } - void update_uuid_filter( - ApcfAction action, uint8_t filter_index, ApcfFilterType filter_type, Uuid uuid, Uuid uuid_mask) { + void update_uuid_filter(ApcfAction action, uint8_t filter_index, ApcfFilterType filter_type, + Uuid uuid, Uuid uuid_mask) { std::vector combined_data = {}; if (action != ApcfAction::CLEAR) { uint8_t uuid_len = uuid.GetShortestRepresentationSize(); @@ -969,28 +920,25 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { if (filter_type == ApcfFilterType::SERVICE_UUID) { le_scanning_interface_->EnqueueCommand( - LeAdvFilterServiceUuidBuilder::Create(action, filter_index, combined_data), - module_handler_->BindOnceOn(this, &impl::on_advertising_filter_complete)); + LeAdvFilterServiceUuidBuilder::Create(action, filter_index, combined_data), + module_handler_->BindOnceOn(this, &impl::on_advertising_filter_complete)); } else { le_scanning_interface_->EnqueueCommand( - LeAdvFilterSolicitationUuidBuilder::Create(action, filter_index, combined_data), - module_handler_->BindOnceOn(this, &impl::on_advertising_filter_complete)); + LeAdvFilterSolicitationUuidBuilder::Create(action, filter_index, combined_data), + module_handler_->BindOnceOn(this, &impl::on_advertising_filter_complete)); } } - void update_local_name_filter(ApcfAction action, uint8_t filter_index, std::vector name) { + void update_local_name_filter(ApcfAction action, uint8_t filter_index, + std::vector name) { le_scanning_interface_->EnqueueCommand( - LeAdvFilterLocalNameBuilder::Create(action, filter_index, name), - module_handler_->BindOnceOn(this, &impl::on_advertising_filter_complete)); + LeAdvFilterLocalNameBuilder::Create(action, filter_index, name), + module_handler_->BindOnceOn(this, &impl::on_advertising_filter_complete)); } - void update_manufacturer_data_filter( - ApcfAction action, - uint8_t filter_index, - uint16_t company_id, - uint16_t company_id_mask, - std::vector data, - std::vector data_mask) { + void update_manufacturer_data_filter(ApcfAction action, uint8_t filter_index, uint16_t company_id, + uint16_t company_id_mask, std::vector data, + std::vector data_mask) { if (data.size() != data_mask.size()) { log::error("manufacturer data mask should have the same length as manufacturer data"); return; @@ -1015,12 +963,12 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { } le_scanning_interface_->EnqueueCommand( - LeAdvFilterManufacturerDataBuilder::Create(action, filter_index, combined_data), - module_handler_->BindOnceOn(this, &impl::on_advertising_filter_complete)); + LeAdvFilterManufacturerDataBuilder::Create(action, filter_index, combined_data), + module_handler_->BindOnceOn(this, &impl::on_advertising_filter_complete)); } - void update_service_data_filter( - ApcfAction action, uint8_t filter_index, std::vector data, std::vector data_mask) { + void update_service_data_filter(ApcfAction action, uint8_t filter_index, + std::vector data, std::vector data_mask) { if (data.size() != data_mask.size()) { log::error("service data mask should have the same length as service data"); return; @@ -1032,20 +980,17 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { } le_scanning_interface_->EnqueueCommand( - LeAdvFilterServiceDataBuilder::Create(action, filter_index, combined_data), - module_handler_->BindOnceOn(this, &impl::on_advertising_filter_complete)); - } - - void update_transport_discovery_data_filter( - ApcfAction action, - uint8_t filter_index, - uint8_t org_id, - uint8_t tds_flags, - uint8_t tds_flags_mask, - std::vector transport_data, - std::vector transport_data_mask, - ApcfMetaDataType meta_data_type, - std::vector meta_data) { + LeAdvFilterServiceDataBuilder::Create(action, filter_index, combined_data), + module_handler_->BindOnceOn(this, &impl::on_advertising_filter_complete)); + } + + void update_transport_discovery_data_filter(ApcfAction action, uint8_t filter_index, + uint8_t org_id, uint8_t tds_flags, + uint8_t tds_flags_mask, + std::vector transport_data, + std::vector transport_data_mask, + ApcfMetaDataType meta_data_type, + std::vector meta_data) { LocalVersionInformation local_version_information = controller_->GetLocalVersionInformation(); // In QTI controller, transport discovery data filter are supported by default. Check is added @@ -1057,15 +1002,10 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { } log::info( - "org id: {}, tds_flags: {}, tds_flags_mask: {}, transport_data size: {}, " - "transport_data_mask size: {}, meta_data_type: {}, meta_data size: {}", - org_id, - tds_flags, - tds_flags_mask, - transport_data.size(), - transport_data_mask.size(), - (uint8_t)meta_data_type, - meta_data.size()); + "org id: {}, tds_flags: {}, tds_flags_mask: {}, transport_data size: {}, " + "transport_data_mask size: {}, meta_data_type: {}, meta_data size: {}", + org_id, tds_flags, tds_flags_mask, transport_data.size(), transport_data_mask.size(), + (uint8_t)meta_data_type, meta_data.size()); // 0x02 Wi-Fi Alliance Neighbor Awareness Networking & meta_data_type is 0x01 for NAN Hash. if (org_id == 0x02) { @@ -1081,17 +1021,10 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { if (is_transport_discovery_data_filter_supported_) { le_scanning_interface_->EnqueueCommand( - LeAdvFilterTransportDiscoveryDataBuilder::Create( - action, - filter_index, - org_id, - tds_flags, - tds_flags_mask, - transport_data, - transport_data_mask, - meta_data_type, - meta_data), - module_handler_->BindOnceOn(this, &impl::on_advertising_filter_complete)); + LeAdvFilterTransportDiscoveryDataBuilder::Create( + action, filter_index, org_id, tds_flags, tds_flags_mask, transport_data, + transport_data_mask, meta_data_type, meta_data), + module_handler_->BindOnceOn(this, &impl::on_advertising_filter_complete)); } else { // In QTI controller, transport discovery data filter are supported by default. // keeping old version for backward compatibility @@ -1106,17 +1039,14 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { } } le_scanning_interface_->EnqueueCommand( - LeAdvFilterTransportDiscoveryDataOldBuilder::Create(action, filter_index, combined_data), - module_handler_->BindOnceOn(this, &impl::on_advertising_filter_complete)); + LeAdvFilterTransportDiscoveryDataOldBuilder::Create(action, filter_index, + combined_data), + module_handler_->BindOnceOn(this, &impl::on_advertising_filter_complete)); } } - void update_ad_type_filter( - ApcfAction action, - uint8_t filter_index, - uint8_t ad_type, - std::vector data, - std::vector data_mask) { + void update_ad_type_filter(ApcfAction action, uint8_t filter_index, uint8_t ad_type, + std::vector data, std::vector data_mask) { if (!is_ad_type_filter_supported_) { log::error("AD type filter isn't supported"); return; @@ -1137,15 +1067,13 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { } le_scanning_interface_->EnqueueCommand( - LeAdvFilterADTypeBuilder::Create(action, filter_index, combined_data), - module_handler_->BindOnceOn(this, &impl::on_advertising_filter_complete)); + LeAdvFilterADTypeBuilder::Create(action, filter_index, combined_data), + module_handler_->BindOnceOn(this, &impl::on_advertising_filter_complete)); } - void batch_scan_set_storage_parameter( - uint8_t batch_scan_full_max, - uint8_t batch_scan_truncated_max, - uint8_t batch_scan_notify_threshold, - ScannerId scanner_id) { + void batch_scan_set_storage_parameter(uint8_t batch_scan_full_max, + uint8_t batch_scan_truncated_max, + uint8_t batch_scan_notify_threshold, ScannerId scanner_id) { if (!is_batch_scan_supported_) { log::warn("Batch scan is not supported"); return; @@ -1158,21 +1086,19 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { batch_scan_config_.current_state == BatchScanState::DISABLE_CALLED) { batch_scan_config_.current_state = BatchScanState::ENABLE_CALLED; le_scanning_interface_->EnqueueCommand( - LeBatchScanEnableBuilder::Create(Enable::ENABLED), - module_handler_->BindOnceOn(this, &impl::on_batch_scan_enable_complete)); + LeBatchScanEnableBuilder::Create(Enable::ENABLED), + module_handler_->BindOnceOn(this, &impl::on_batch_scan_enable_complete)); } le_scanning_interface_->EnqueueCommand( - LeBatchScanSetStorageParametersBuilder::Create( - batch_scan_full_max, batch_scan_truncated_max, batch_scan_notify_threshold), - module_handler_->BindOnceOn(this, &impl::on_batch_scan_complete)); + LeBatchScanSetStorageParametersBuilder::Create( + batch_scan_full_max, batch_scan_truncated_max, batch_scan_notify_threshold), + module_handler_->BindOnceOn(this, &impl::on_batch_scan_complete)); } - void batch_scan_enable( - BatchScanMode scan_mode, - uint32_t duty_cycle_scan_window_slots, - uint32_t duty_cycle_scan_interval_slots, - BatchScanDiscardRule batch_scan_discard_rule) { + void batch_scan_enable(BatchScanMode scan_mode, uint32_t duty_cycle_scan_window_slots, + uint32_t duty_cycle_scan_interval_slots, + BatchScanDiscardRule batch_scan_discard_rule) { if (!is_batch_scan_supported_) { log::warn("Batch scan is not supported"); return; @@ -1183,8 +1109,8 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { batch_scan_config_.current_state == BatchScanState::DISABLE_CALLED) { batch_scan_config_.current_state = BatchScanState::ENABLE_CALLED; le_scanning_interface_->EnqueueCommand( - LeBatchScanEnableBuilder::Create(Enable::ENABLED), - module_handler_->BindOnceOn(this, &impl::on_batch_scan_enable_complete)); + LeBatchScanEnableBuilder::Create(Enable::ENABLED), + module_handler_->BindOnceOn(this, &impl::on_batch_scan_enable_complete)); } batch_scan_config_.scan_mode = scan_mode; @@ -1192,8 +1118,8 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { batch_scan_config_.scan_window = duty_cycle_scan_window_slots; batch_scan_config_.discard_rule = batch_scan_discard_rule; /* This command starts batch scanning, if enabled */ - batch_scan_set_scan_parameter( - scan_mode, duty_cycle_scan_window_slots, duty_cycle_scan_interval_slots, batch_scan_discard_rule); + batch_scan_set_scan_parameter(scan_mode, duty_cycle_scan_window_slots, + duty_cycle_scan_interval_slots, batch_scan_discard_rule); } void batch_scan_disable() { @@ -1202,18 +1128,14 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { return; } batch_scan_config_.current_state = BatchScanState::DISABLE_CALLED; - batch_scan_set_scan_parameter( - BatchScanMode::DISABLE, - batch_scan_config_.scan_window, - batch_scan_config_.scan_interval, - batch_scan_config_.discard_rule); - } - - void batch_scan_set_scan_parameter( - BatchScanMode scan_mode, - uint32_t duty_cycle_scan_window_slots, - uint32_t duty_cycle_scan_interval_slots, - BatchScanDiscardRule batch_scan_discard_rule) { + batch_scan_set_scan_parameter(BatchScanMode::DISABLE, batch_scan_config_.scan_window, + batch_scan_config_.scan_interval, + batch_scan_config_.discard_rule); + } + + void batch_scan_set_scan_parameter(BatchScanMode scan_mode, uint32_t duty_cycle_scan_window_slots, + uint32_t duty_cycle_scan_interval_slots, + BatchScanDiscardRule batch_scan_discard_rule) { if (!is_batch_scan_supported_) { log::warn("Batch scan is not supported"); return; @@ -1234,28 +1156,21 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { if (scan_mode == BatchScanMode::DISABLE) { le_scanning_interface_->EnqueueCommand( - LeBatchScanSetScanParametersBuilder::Create( - truncated_mode_enabled, - full_mode_enabled, - duty_cycle_scan_window_slots, - duty_cycle_scan_interval_slots, - own_address_type, - batch_scan_discard_rule), - module_handler_->BindOnceOn(this, &impl::on_batch_scan_disable_complete)); + LeBatchScanSetScanParametersBuilder::Create( + truncated_mode_enabled, full_mode_enabled, duty_cycle_scan_window_slots, + duty_cycle_scan_interval_slots, own_address_type, batch_scan_discard_rule), + module_handler_->BindOnceOn(this, &impl::on_batch_scan_disable_complete)); } else { le_scanning_interface_->EnqueueCommand( - LeBatchScanSetScanParametersBuilder::Create( - truncated_mode_enabled, - full_mode_enabled, - duty_cycle_scan_window_slots, - duty_cycle_scan_interval_slots, - own_address_type, - batch_scan_discard_rule), - module_handler_->BindOnceOn(this, &impl::on_batch_scan_complete)); + LeBatchScanSetScanParametersBuilder::Create( + truncated_mode_enabled, full_mode_enabled, duty_cycle_scan_window_slots, + duty_cycle_scan_interval_slots, own_address_type, batch_scan_discard_rule), + module_handler_->BindOnceOn(this, &impl::on_batch_scan_complete)); } } - void batch_scan_read_results(ScannerId scanner_id, uint16_t total_num_of_records, BatchScanMode scan_mode) { + void batch_scan_read_results(ScannerId scanner_id, uint16_t total_num_of_records, + BatchScanMode scan_mode) { if (!is_batch_scan_supported_) { log::warn("Batch scan is not supported"); int status = static_cast(ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); @@ -1276,24 +1191,27 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { } le_scanning_interface_->EnqueueCommand( - LeBatchScanReadResultParametersBuilder::Create(static_cast(scan_mode)), - module_handler_->BindOnceOn(this, &impl::on_batch_scan_read_result_complete, scanner_id, total_num_of_records)); + LeBatchScanReadResultParametersBuilder::Create( + static_cast(scan_mode)), + module_handler_->BindOnceOn(this, &impl::on_batch_scan_read_result_complete, scanner_id, + total_num_of_records)); } - void start_sync( - uint8_t sid, const AddressWithType& address_with_type, uint16_t skip, uint16_t timeout, int request_id) { + void start_sync(uint8_t sid, const AddressWithType& address_with_type, uint16_t skip, + uint16_t timeout, int request_id) { if (!is_periodic_advertising_sync_transfer_sender_supported_) { log::warn("PAST sender not supported on this device"); int status = static_cast(ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); - scanning_callbacks_->OnPeriodicSyncStarted(request_id, status, -1, sid, address_with_type, 0, 0); + scanning_callbacks_->OnPeriodicSyncStarted(request_id, status, -1, sid, address_with_type, 0, + 0); return; } PeriodicSyncStates request{ - .request_id = request_id, - .advertiser_sid = sid, - .address_with_type = address_with_type, - .sync_handle = 0, - .sync_state = PeriodicSyncState::PERIODIC_SYNC_STATE_IDLE, + .request_id = request_id, + .advertiser_sid = sid, + .address_with_type = address_with_type, + .sync_handle = 0, + .sync_state = PeriodicSyncState::PERIODIC_SYNC_STATE_IDLE, }; periodic_sync_manager_.StartSync(request, skip, timeout); } @@ -1314,12 +1232,8 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { periodic_sync_manager_.CancelCreateSync(sid, address); } - void transfer_sync( - const Address& address, - uint16_t connection_handle, - uint16_t service_data, - uint16_t sync_handle, - int pa_source) { + void transfer_sync(const Address& address, uint16_t connection_handle, uint16_t service_data, + uint16_t sync_handle, int pa_source) { if (!is_periodic_advertising_sync_transfer_sender_supported_) { log::warn("PAST sender not supported on this device"); int status = static_cast(ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); @@ -1332,15 +1246,12 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { scanning_callbacks_->OnPeriodicSyncTransferred(pa_source, status, address); return; } - periodic_sync_manager_.TransferSync(address, service_data, sync_handle, pa_source, connection_handle); + periodic_sync_manager_.TransferSync(address, service_data, sync_handle, pa_source, + connection_handle); } - void transfer_set_info( - const Address& address, - uint16_t connection_handle, - uint16_t service_data, - uint8_t adv_handle, - int pa_source) { + void transfer_set_info(const Address& address, uint16_t connection_handle, uint16_t service_data, + uint8_t adv_handle, int pa_source) { if (!is_periodic_advertising_sync_transfer_sender_supported_) { log::warn("PAST sender not supported on this device"); int status = static_cast(ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); @@ -1353,10 +1264,12 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { scanning_callbacks_->OnPeriodicSyncTransferred(pa_source, status, address); return; } - periodic_sync_manager_.SyncSetInfo(address, service_data, adv_handle, pa_source, connection_handle); + periodic_sync_manager_.SyncSetInfo(address, service_data, adv_handle, pa_source, + connection_handle); } - void sync_tx_parameters(const Address& address, uint8_t mode, uint16_t skip, uint16_t timeout, int reg_id) { + void sync_tx_parameters(const Address& address, uint8_t mode, uint16_t skip, uint16_t timeout, + int reg_id) { if (!is_periodic_advertising_sync_transfer_sender_supported_) { log::warn("PAST sender not supported on this device"); int status = static_cast(ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); @@ -1382,10 +1295,8 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { scanning_callbacks_->OnTrackAdvFoundLost(on_found_on_lost_info); return; } - log::info( - "track_advertiser scanner_id {}, filter_index {}", - (uint16_t)scanner_id, - (uint16_t)filter_index); + log::info("track_advertiser scanner_id {}, filter_index {}", (uint16_t)scanner_id, + (uint16_t)filter_index); tracker_id_map_[filter_index] = scanner_id; } @@ -1394,9 +1305,7 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { periodic_sync_manager_.SetScanningCallback(scanning_callbacks_); } - bool is_ad_type_filter_supported() { - return is_ad_type_filter_supported_; - } + bool is_ad_type_filter_supported() { return is_ad_type_filter_supported_; } void on_set_scan_parameter_complete(CommandCompleteView view) { switch (view.GetCommandOpCode()) { @@ -1404,27 +1313,24 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { auto status_view = LeSetScanParametersCompleteView::Create(view); log::assert_that(status_view.IsValid(), "assert failed: status_view.IsValid()"); if (status_view.GetStatus() != ErrorCode::SUCCESS) { - log::info( - "Receive set scan parameter complete with error code {}", - ErrorCodeText(status_view.GetStatus())); + log::info("Receive set scan parameter complete with error code {}", + ErrorCodeText(status_view.GetStatus())); } } break; case (OpCode::LE_EXTENDED_SCAN_PARAMS): { auto status_view = LeExtendedScanParamsCompleteView::Create(view); log::assert_that(status_view.IsValid(), "assert failed: status_view.IsValid()"); if (status_view.GetStatus() != ErrorCode::SUCCESS) { - log::info( - "Receive extended scan parameter complete with error code {}", - ErrorCodeText(status_view.GetStatus())); + log::info("Receive extended scan parameter complete with error code {}", + ErrorCodeText(status_view.GetStatus())); } } break; case (OpCode::LE_SET_EXTENDED_SCAN_PARAMETERS): { auto status_view = LeSetExtendedScanParametersCompleteView::Create(view); log::assert_that(status_view.IsValid(), "assert failed: status_view.IsValid()"); if (status_view.GetStatus() != ErrorCode::SUCCESS) { - log::info( - "Receive set extended scan parameter complete with error code {}", - ErrorCodeText(status_view.GetStatus())); + log::info("Receive set extended scan parameter complete with error code {}", + ErrorCodeText(status_view.GetStatus())); } } break; default: @@ -1437,10 +1343,8 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { auto status_view = LeAdvFilterCompleteView::Create(view); log::assert_that(status_view.IsValid(), "assert failed: status_view.IsValid()"); if (status_view.GetStatus() != ErrorCode::SUCCESS) { - log::info( - "Got a Command complete {}, status {}", - OpCodeText(view.GetCommandOpCode()), - ErrorCodeText(status_view.GetStatus())); + log::info("Got a Command complete {}, status {}", OpCodeText(view.GetCommandOpCode()), + ErrorCodeText(status_view.GetStatus())); } ApcfOpcode apcf_opcode = status_view.GetApcfOpcode(); @@ -1448,85 +1352,71 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { case ApcfOpcode::ENABLE: { auto complete_view = LeAdvFilterEnableCompleteView::Create(status_view); log::assert_that(complete_view.IsValid(), "assert failed: complete_view.IsValid()"); - scanning_callbacks_->OnFilterEnable(complete_view.GetApcfEnable(), (uint8_t)complete_view.GetStatus()); + scanning_callbacks_->OnFilterEnable(complete_view.GetApcfEnable(), + (uint8_t)complete_view.GetStatus()); } break; case ApcfOpcode::SET_FILTERING_PARAMETERS: { auto complete_view = LeAdvFilterSetFilteringParametersCompleteView::Create(status_view); log::assert_that(complete_view.IsValid(), "assert failed: complete_view.IsValid()"); - scanning_callbacks_->OnFilterParamSetup( - complete_view.GetApcfAvailableSpaces(), complete_view.GetApcfAction(), (uint8_t)complete_view.GetStatus()); + scanning_callbacks_->OnFilterParamSetup(complete_view.GetApcfAvailableSpaces(), + complete_view.GetApcfAction(), + (uint8_t)complete_view.GetStatus()); } break; case ApcfOpcode::BROADCASTER_ADDRESS: { auto complete_view = LeAdvFilterBroadcasterAddressCompleteView::Create(status_view); log::assert_that(complete_view.IsValid(), "assert failed: complete_view.IsValid()"); scanning_callbacks_->OnFilterConfigCallback( - ApcfFilterType::BROADCASTER_ADDRESS, - complete_view.GetApcfAvailableSpaces(), - complete_view.GetApcfAction(), - (uint8_t)complete_view.GetStatus()); + ApcfFilterType::BROADCASTER_ADDRESS, complete_view.GetApcfAvailableSpaces(), + complete_view.GetApcfAction(), (uint8_t)complete_view.GetStatus()); } break; case ApcfOpcode::SERVICE_UUID: { auto complete_view = LeAdvFilterServiceUuidCompleteView::Create(status_view); log::assert_that(complete_view.IsValid(), "assert failed: complete_view.IsValid()"); scanning_callbacks_->OnFilterConfigCallback( - ApcfFilterType::SERVICE_UUID, - complete_view.GetApcfAvailableSpaces(), - complete_view.GetApcfAction(), - (uint8_t)complete_view.GetStatus()); + ApcfFilterType::SERVICE_UUID, complete_view.GetApcfAvailableSpaces(), + complete_view.GetApcfAction(), (uint8_t)complete_view.GetStatus()); } break; case ApcfOpcode::SERVICE_SOLICITATION_UUID: { auto complete_view = LeAdvFilterSolicitationUuidCompleteView::Create(status_view); log::assert_that(complete_view.IsValid(), "assert failed: complete_view.IsValid()"); scanning_callbacks_->OnFilterConfigCallback( - ApcfFilterType::SERVICE_SOLICITATION_UUID, - complete_view.GetApcfAvailableSpaces(), - complete_view.GetApcfAction(), - (uint8_t)complete_view.GetStatus()); + ApcfFilterType::SERVICE_SOLICITATION_UUID, complete_view.GetApcfAvailableSpaces(), + complete_view.GetApcfAction(), (uint8_t)complete_view.GetStatus()); } break; case ApcfOpcode::LOCAL_NAME: { auto complete_view = LeAdvFilterLocalNameCompleteView::Create(status_view); log::assert_that(complete_view.IsValid(), "assert failed: complete_view.IsValid()"); scanning_callbacks_->OnFilterConfigCallback( - ApcfFilterType::LOCAL_NAME, - complete_view.GetApcfAvailableSpaces(), - complete_view.GetApcfAction(), - (uint8_t)complete_view.GetStatus()); + ApcfFilterType::LOCAL_NAME, complete_view.GetApcfAvailableSpaces(), + complete_view.GetApcfAction(), (uint8_t)complete_view.GetStatus()); } break; case ApcfOpcode::MANUFACTURER_DATA: { auto complete_view = LeAdvFilterManufacturerDataCompleteView::Create(status_view); log::assert_that(complete_view.IsValid(), "assert failed: complete_view.IsValid()"); scanning_callbacks_->OnFilterConfigCallback( - ApcfFilterType::MANUFACTURER_DATA, - complete_view.GetApcfAvailableSpaces(), - complete_view.GetApcfAction(), - (uint8_t)complete_view.GetStatus()); + ApcfFilterType::MANUFACTURER_DATA, complete_view.GetApcfAvailableSpaces(), + complete_view.GetApcfAction(), (uint8_t)complete_view.GetStatus()); } break; case ApcfOpcode::SERVICE_DATA: { auto complete_view = LeAdvFilterServiceDataCompleteView::Create(status_view); log::assert_that(complete_view.IsValid(), "assert failed: complete_view.IsValid()"); scanning_callbacks_->OnFilterConfigCallback( - ApcfFilterType::SERVICE_DATA, - complete_view.GetApcfAvailableSpaces(), - complete_view.GetApcfAction(), - (uint8_t)complete_view.GetStatus()); + ApcfFilterType::SERVICE_DATA, complete_view.GetApcfAvailableSpaces(), + complete_view.GetApcfAction(), (uint8_t)complete_view.GetStatus()); } break; case ApcfOpcode::TRANSPORT_DISCOVERY_DATA: { auto complete_view = LeAdvFilterTransportDiscoveryDataCompleteView::Create(status_view); log::assert_that(complete_view.IsValid(), "assert failed: complete_view.IsValid()"); scanning_callbacks_->OnFilterConfigCallback( - ApcfFilterType::TRANSPORT_DISCOVERY_DATA, - complete_view.GetApcfAvailableSpaces(), - complete_view.GetApcfAction(), - (uint8_t)complete_view.GetStatus()); + ApcfFilterType::TRANSPORT_DISCOVERY_DATA, complete_view.GetApcfAvailableSpaces(), + complete_view.GetApcfAction(), (uint8_t)complete_view.GetStatus()); } break; case ApcfOpcode::AD_TYPE: { auto complete_view = LeAdvFilterADTypeCompleteView::Create(status_view); log::assert_that(complete_view.IsValid(), "assert failed: complete_view.IsValid()"); scanning_callbacks_->OnFilterConfigCallback( - ApcfFilterType::AD_TYPE, - complete_view.GetApcfAvailableSpaces(), - complete_view.GetApcfAction(), - (uint8_t)complete_view.GetStatus()); + ApcfFilterType::AD_TYPE, complete_view.GetApcfAvailableSpaces(), + complete_view.GetApcfAction(), (uint8_t)complete_view.GetStatus()); } break; default: log::warn("Unexpected event type {}", OpCodeText(view.GetCommandOpCode())); @@ -1541,22 +1431,19 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { return; } if (status_view.GetStatus() != ErrorCode::SUCCESS) { - log::warn( - "Got a Command complete {}, status {}", - OpCodeText(view.GetCommandOpCode()), - ErrorCodeText(status_view.GetStatus())); + log::warn("Got a Command complete {}, status {}", OpCodeText(view.GetCommandOpCode()), + ErrorCodeText(status_view.GetStatus())); return; } auto complete_view = LeAdvFilterReadExtendedFeaturesCompleteView::Create(status_view); log::assert_that(complete_view.IsValid(), "assert failed: complete_view.IsValid()"); is_transport_discovery_data_filter_supported_ = - complete_view.GetTransportDiscoveryDataFilter() == 1; + complete_view.GetTransportDiscoveryDataFilter() == 1; is_ad_type_filter_supported_ = complete_view.GetAdTypeFilter() == 1; log::info( - "set is_ad_type_filter_supported_ to {} & is_transport_discovery_data_filter_supported_ to " - "{}", - is_ad_type_filter_supported_, - is_transport_discovery_data_filter_supported_); + "set is_ad_type_filter_supported_ to {} & " + "is_transport_discovery_data_filter_supported_ to {}", + is_ad_type_filter_supported_, is_transport_discovery_data_filter_supported_); } void on_batch_scan_complete(CommandCompleteView view) { @@ -1564,11 +1451,9 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { auto status_view = LeBatchScanCompleteView::Create(view); log::assert_that(status_view.IsValid(), "assert failed: status_view.IsValid()"); if (status_view.GetStatus() != ErrorCode::SUCCESS) { - log::info( - "Got a Command complete {}, status {}, batch_scan_opcode {}", - OpCodeText(view.GetCommandOpCode()), - ErrorCodeText(status_view.GetStatus()), - BatchScanOpcodeText(status_view.GetBatchScanOpcode())); + log::info("Got a Command complete {}, status {}, batch_scan_opcode {}", + OpCodeText(view.GetCommandOpCode()), ErrorCodeText(status_view.GetStatus()), + BatchScanOpcodeText(status_view.GetBatchScanOpcode())); } } @@ -1579,8 +1464,8 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { auto complete_view = LeBatchScanEnableCompleteView::Create(status_view); log::assert_that(complete_view.IsValid(), "assert failed: complete_view.IsValid()"); if (status_view.GetStatus() != ErrorCode::SUCCESS) { - log::info( - "Got batch scan enable complete, status {}", ErrorCodeText(status_view.GetStatus())); + log::info("Got batch scan enable complete, status {}", + ErrorCodeText(status_view.GetStatus())); batch_scan_config_.current_state = BatchScanState::ERROR_STATE; } else { batch_scan_config_.current_state = BatchScanState::ENABLED_STATE; @@ -1593,35 +1478,36 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { log::assert_that(status_view.IsValid(), "assert failed: status_view.IsValid()"); auto complete_view = LeBatchScanSetScanParametersCompleteView::Create(status_view); log::assert_that(complete_view.IsValid(), "assert failed: complete_view.IsValid()"); - log::assert_that( - status_view.GetStatus() == ErrorCode::SUCCESS, - "assert failed: status_view.GetStatus() == ErrorCode::SUCCESS"); + log::assert_that(status_view.GetStatus() == ErrorCode::SUCCESS, + "assert failed: status_view.GetStatus() == ErrorCode::SUCCESS"); batch_scan_config_.current_state = BatchScanState::DISABLED_STATE; } - void on_batch_scan_read_result_complete( - ScannerId scanner_id, uint16_t total_num_of_records, CommandCompleteView view) { + void on_batch_scan_read_result_complete(ScannerId scanner_id, uint16_t total_num_of_records, + CommandCompleteView view) { log::assert_that(view.IsValid(), "assert failed: view.IsValid()"); auto status_view = LeBatchScanCompleteView::Create(view); log::assert_that(status_view.IsValid(), "assert failed: status_view.IsValid()"); auto complete_view = LeBatchScanReadResultParametersCompleteRawView::Create(status_view); log::assert_that(complete_view.IsValid(), "assert failed: complete_view.IsValid()"); if (complete_view.GetStatus() != ErrorCode::SUCCESS) { - log::info( - "Got batch scan read result complete, status {}", ErrorCodeText(status_view.GetStatus())); + log::info("Got batch scan read result complete, status {}", + ErrorCodeText(status_view.GetStatus())); } uint8_t num_of_records = complete_view.GetNumOfRecords(); auto report_format = complete_view.GetBatchScanDataRead(); if (num_of_records == 0) { - scanning_callbacks_->OnBatchScanReports( - scanner_id, 0x00, (int)report_format, total_num_of_records, batch_scan_result_cache_[scanner_id]); + scanning_callbacks_->OnBatchScanReports(scanner_id, 0x00, (int)report_format, + total_num_of_records, + batch_scan_result_cache_[scanner_id]); batch_scan_result_cache_.erase(scanner_id); } else { auto raw_data = complete_view.GetRawData(); - batch_scan_result_cache_[scanner_id].insert( - batch_scan_result_cache_[scanner_id].end(), raw_data.begin(), raw_data.end()); + batch_scan_result_cache_[scanner_id].insert(batch_scan_result_cache_[scanner_id].end(), + raw_data.begin(), raw_data.end()); total_num_of_records += num_of_records; - batch_scan_read_results(scanner_id, total_num_of_records, static_cast(report_format)); + batch_scan_read_results(scanner_id, total_num_of_records, + static_cast(report_format)); } } @@ -1630,7 +1516,8 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { log::warn("storage threshold was not set !!"); return; } - scanning_callbacks_->OnBatchScanThresholdCrossed(static_cast(batch_scan_config_.ref_value)); + scanning_callbacks_->OnBatchScanThresholdCrossed( + static_cast(batch_scan_config_.ref_value)); } void on_advertisement_tracking(VendorSpecificEventView event) { @@ -1657,11 +1544,12 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { on_found_on_lost_info.time_stamp = info_view.GetTimestamp(); auto adv_data = info_view.GetAdvPacket(); on_found_on_lost_info.adv_packet.reserve(adv_data.size()); - on_found_on_lost_info.adv_packet.insert(on_found_on_lost_info.adv_packet.end(), adv_data.begin(), adv_data.end()); + on_found_on_lost_info.adv_packet.insert(on_found_on_lost_info.adv_packet.end(), + adv_data.begin(), adv_data.end()); auto scan_rsp_data = info_view.GetScanResponse(); on_found_on_lost_info.scan_response.reserve(scan_rsp_data.size()); - on_found_on_lost_info.scan_response.insert( - on_found_on_lost_info.scan_response.end(), scan_rsp_data.begin(), scan_rsp_data.end()); + on_found_on_lost_info.scan_response.insert(on_found_on_lost_info.scan_response.end(), + scan_rsp_data.begin(), scan_rsp_data.end()); } scanning_callbacks_->OnTrackAdvFoundLost(on_found_on_lost_info); } @@ -1677,9 +1565,7 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { ack_pause(); } - void ack_pause() { - le_address_manager_->AckPause(this); - } + void ack_pause() { le_address_manager_->AckPause(this); } void OnResume() override { if (!address_manager_registered_) { @@ -1732,9 +1618,7 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { int8_t le_rx_path_loss_comp_ = 0; }; -LeScanningManager::LeScanningManager() { - pimpl_ = std::make_unique(this); -} +LeScanningManager::LeScanningManager() { pimpl_ = std::make_unique(this); } void LeScanningManager::ListDependencies(ModuleList* list) const { list->add(); @@ -1744,12 +1628,8 @@ void LeScanningManager::ListDependencies(ModuleList* list) const { } void LeScanningManager::Start() { - pimpl_->start( - GetHandler(), - GetDependency(), - GetDependency(), - GetDependency(), - GetDependency()); + pimpl_->start(GetHandler(), GetDependency(), GetDependency(), + GetDependency(), GetDependency()); } void LeScanningManager::Stop() { @@ -1757,9 +1637,7 @@ void LeScanningManager::Stop() { pimpl_.reset(); } -std::string LeScanningManager::ToString() const { - return "Le Scanning Manager"; -} +std::string LeScanningManager::ToString() const { return "Le Scanning Manager"; } void LeScanningManager::RegisterScanner(Uuid app_uuid) { CallOn(pimpl_.get(), &impl::register_scanner, app_uuid); @@ -1769,24 +1647,13 @@ void LeScanningManager::Unregister(ScannerId scanner_id) { CallOn(pimpl_.get(), &impl::unregister_scanner, scanner_id); } -void LeScanningManager::Scan(bool start) { - CallOn(pimpl_.get(), &impl::scan, start); -} +void LeScanningManager::Scan(bool start) { CallOn(pimpl_.get(), &impl::scan, start); } -void LeScanningManager::SetScanParameters( - ScannerId scanner_id, - LeScanType scan_type, - uint16_t scan_interval, - uint16_t scan_window, - uint8_t scan_phy) { - CallOn( - pimpl_.get(), - &impl::set_scan_parameters, - scanner_id, - scan_type, - scan_interval, - scan_window, - scan_phy); +void LeScanningManager::SetScanParameters(ScannerId scanner_id, LeScanType scan_type, + uint16_t scan_interval, uint16_t scan_window, + uint8_t scan_phy) { + CallOn(pimpl_.get(), &impl::set_scan_parameters, scanner_id, scan_type, scan_interval, + scan_window, scan_phy); } void LeScanningManager::SetScanFilterPolicy(LeScanningFilterPolicy filter_policy) { @@ -1798,53 +1665,41 @@ void LeScanningManager::ScanFilterEnable(bool enable) { } void LeScanningManager::ScanFilterParameterSetup( - ApcfAction action, uint8_t filter_index, AdvertisingFilterParameter advertising_filter_parameter) { - CallOn(pimpl_.get(), &impl::scan_filter_parameter_setup, action, filter_index, advertising_filter_parameter); + ApcfAction action, uint8_t filter_index, + AdvertisingFilterParameter advertising_filter_parameter) { + CallOn(pimpl_.get(), &impl::scan_filter_parameter_setup, action, filter_index, + advertising_filter_parameter); } -void LeScanningManager::ScanFilterAdd( - uint8_t filter_index, std::vector filters) { +void LeScanningManager::ScanFilterAdd(uint8_t filter_index, + std::vector filters) { CallOn(pimpl_.get(), &impl::scan_filter_add, filter_index, filters); } -void LeScanningManager::BatchScanConifgStorage( - uint8_t batch_scan_full_max, - uint8_t batch_scan_truncated_max, - uint8_t batch_scan_notify_threshold, - ScannerId scanner_id) { - CallOn( - pimpl_.get(), - &impl::batch_scan_set_storage_parameter, - batch_scan_full_max, - batch_scan_truncated_max, - batch_scan_notify_threshold, - scanner_id); +void LeScanningManager::BatchScanConifgStorage(uint8_t batch_scan_full_max, + uint8_t batch_scan_truncated_max, + uint8_t batch_scan_notify_threshold, + ScannerId scanner_id) { + CallOn(pimpl_.get(), &impl::batch_scan_set_storage_parameter, batch_scan_full_max, + batch_scan_truncated_max, batch_scan_notify_threshold, scanner_id); } -void LeScanningManager::BatchScanEnable( - BatchScanMode scan_mode, - uint32_t duty_cycle_scan_window_slots, - uint32_t duty_cycle_scan_interval_slots, - BatchScanDiscardRule batch_scan_discard_rule) { - CallOn( - pimpl_.get(), - &impl::batch_scan_enable, - scan_mode, - duty_cycle_scan_window_slots, - duty_cycle_scan_interval_slots, - batch_scan_discard_rule); +void LeScanningManager::BatchScanEnable(BatchScanMode scan_mode, + uint32_t duty_cycle_scan_window_slots, + uint32_t duty_cycle_scan_interval_slots, + BatchScanDiscardRule batch_scan_discard_rule) { + CallOn(pimpl_.get(), &impl::batch_scan_enable, scan_mode, duty_cycle_scan_window_slots, + duty_cycle_scan_interval_slots, batch_scan_discard_rule); } -void LeScanningManager::BatchScanDisable() { - CallOn(pimpl_.get(), &impl::batch_scan_disable); -} +void LeScanningManager::BatchScanDisable() { CallOn(pimpl_.get(), &impl::batch_scan_disable); } void LeScanningManager::BatchScanReadReport(ScannerId scanner_id, BatchScanMode scan_mode) { CallOn(pimpl_.get(), &impl::batch_scan_read_results, scanner_id, 0, scan_mode); } -void LeScanningManager::StartSync( - uint8_t sid, const AddressWithType& address_with_type, uint16_t skip, uint16_t timeout, int reg_id) { +void LeScanningManager::StartSync(uint8_t sid, const AddressWithType& address_with_type, + uint16_t skip, uint16_t timeout, int reg_id) { CallOn(pimpl_.get(), &impl::start_sync, sid, address_with_type, skip, timeout, reg_id); } @@ -1856,27 +1711,19 @@ void LeScanningManager::CancelCreateSync(uint8_t sid, const Address& address) { CallOn(pimpl_.get(), &impl::cancel_create_sync, sid, address); } -void LeScanningManager::TransferSync( - const Address& address, - uint16_t handle, - uint16_t service_data, - uint16_t sync_handle, - int pa_source) { +void LeScanningManager::TransferSync(const Address& address, uint16_t handle, uint16_t service_data, + uint16_t sync_handle, int pa_source) { CallOn(pimpl_.get(), &impl::transfer_sync, address, handle, service_data, sync_handle, pa_source); } -void LeScanningManager::TransferSetInfo( - const Address& address, - uint16_t handle, - uint16_t service_data, - uint8_t adv_handle, - int pa_source) { - CallOn( - pimpl_.get(), &impl::transfer_set_info, address, handle, service_data, adv_handle, pa_source); +void LeScanningManager::TransferSetInfo(const Address& address, uint16_t handle, + uint16_t service_data, uint8_t adv_handle, int pa_source) { + CallOn(pimpl_.get(), &impl::transfer_set_info, address, handle, service_data, adv_handle, + pa_source); } -void LeScanningManager::SyncTxParameters( - const Address& address, uint8_t mode, uint16_t skip, uint16_t timeout, int reg_id) { +void LeScanningManager::SyncTxParameters(const Address& address, uint8_t mode, uint16_t skip, + uint16_t timeout, int reg_id) { CallOn(pimpl_.get(), &impl::sync_tx_parameters, address, mode, skip, timeout, reg_id); } diff --git a/system/gd/hci/le_scanning_manager.h b/system/gd/hci/le_scanning_manager.h index 5c9e4ffd7e2..f4842223102 100644 --- a/system/gd/hci/le_scanning_manager.h +++ b/system/gd/hci/le_scanning_manager.h @@ -36,7 +36,7 @@ enum class BatchScanMode : uint8_t { }; class LeScanningManager : public bluetooth::Module { - public: +public: static constexpr uint8_t kMaxAppNum = 32; static constexpr uint8_t kAdvertisingDataInfoNotPresent = 0xff; static constexpr uint8_t kTxPowerInformationNotPresent = 0x7f; @@ -52,58 +52,44 @@ class LeScanningManager : public bluetooth::Module { virtual void Scan(bool start); - virtual void SetScanParameters( - ScannerId scanner_id, - LeScanType scan_type, - uint16_t scan_interval, - uint16_t scan_window, - uint8_t scan_phy); + virtual void SetScanParameters(ScannerId scanner_id, LeScanType scan_type, uint16_t scan_interval, + uint16_t scan_window, uint8_t scan_phy); virtual void SetScanFilterPolicy(LeScanningFilterPolicy filter_policy); /* Scan filter */ virtual void ScanFilterEnable(bool enable); - virtual void ScanFilterParameterSetup( - ApcfAction action, uint8_t filter_index, AdvertisingFilterParameter advertising_filter_parameter); + virtual void ScanFilterParameterSetup(ApcfAction action, uint8_t filter_index, + AdvertisingFilterParameter advertising_filter_parameter); - virtual void ScanFilterAdd(uint8_t filter_index, std::vector filters); + virtual void ScanFilterAdd(uint8_t filter_index, + std::vector filters); /*Batch Scan*/ - virtual void BatchScanConifgStorage( - uint8_t batch_scan_full_max, - uint8_t batch_scan_truncated_max, - uint8_t batch_scan_notify_threshold, - ScannerId scanner_id); - virtual void BatchScanEnable( - BatchScanMode scan_mode, - uint32_t duty_cycle_scan_window_slots, - uint32_t duty_cycle_scan_interval_slots, - BatchScanDiscardRule batch_scan_discard_rule); + virtual void BatchScanConifgStorage(uint8_t batch_scan_full_max, uint8_t batch_scan_truncated_max, + uint8_t batch_scan_notify_threshold, ScannerId scanner_id); + virtual void BatchScanEnable(BatchScanMode scan_mode, uint32_t duty_cycle_scan_window_slots, + uint32_t duty_cycle_scan_interval_slots, + BatchScanDiscardRule batch_scan_discard_rule); virtual void BatchScanDisable(); virtual void BatchScanReadReport(ScannerId scanner_id, BatchScanMode scan_mode); - virtual void StartSync(uint8_t sid, const AddressWithType& address, uint16_t skip, uint16_t timeout, int reg_id); + virtual void StartSync(uint8_t sid, const AddressWithType& address, uint16_t skip, + uint16_t timeout, int reg_id); virtual void StopSync(uint16_t handle); virtual void CancelCreateSync(uint8_t sid, const Address& address); - virtual void TransferSync( - const Address& address, - uint16_t handle, - uint16_t service_data, - uint16_t sync_handle, - int pa_source); + virtual void TransferSync(const Address& address, uint16_t handle, uint16_t service_data, + uint16_t sync_handle, int pa_source); - virtual void TransferSetInfo( - const Address& address, - uint16_t handle, - uint16_t service_data, - uint8_t adv_handle, - int pa_source); + virtual void TransferSetInfo(const Address& address, uint16_t handle, uint16_t service_data, + uint8_t adv_handle, int pa_source); - virtual void SyncTxParameters(const Address& addr, uint8_t mode, uint16_t skip, uint16_t timeout, int reg_id); + virtual void SyncTxParameters(const Address& addr, uint8_t mode, uint16_t skip, uint16_t timeout, + int reg_id); virtual void TrackAdvertiser(uint8_t filter_index, ScannerId scanner_id); @@ -113,7 +99,7 @@ class LeScanningManager : public bluetooth::Module { static const ModuleFactory Factory; - protected: +protected: void ListDependencies(ModuleList* list) const override; void Start() override; @@ -122,7 +108,7 @@ class LeScanningManager : public bluetooth::Module { std::string ToString() const override; - private: +private: struct impl; std::unique_ptr pimpl_; }; diff --git a/system/gd/hci/le_scanning_manager_mock.h b/system/gd/hci/le_scanning_manager_mock.h index f6c7ea73466..49eff4b08d6 100644 --- a/system/gd/hci/le_scanning_manager_mock.h +++ b/system/gd/hci/le_scanning_manager_mock.h @@ -30,10 +30,9 @@ namespace testing { class MockScanningCallback : public ScanningCallback { MOCK_METHOD(void, OnScannerRegistered, (const bluetooth::hci::Uuid, ScannerId, ScanningStatus)); MOCK_METHOD(void, OnSetScannerParameterComplete, (ScannerId scanner_id, ScanningStatus status)); - MOCK_METHOD( - void, - OnScanResult, - (uint16_t, uint8_t, Address, uint8_t, uint8_t, uint8_t, int8_t, int8_t, uint16_t, std::vector)); + MOCK_METHOD(void, OnScanResult, + (uint16_t, uint8_t, Address, uint8_t, uint8_t, uint8_t, int8_t, int8_t, uint16_t, + std::vector)); MOCK_METHOD(void, OnTrackAdvFoundLost, (AdvertisingFilterOnFoundOnLostInfo)); MOCK_METHOD(void, OnBatchScanReports, (int, int, int, int, std::vector)); MOCK_METHOD(void, OnBatchScanThresholdCrossed, (int)); @@ -41,14 +40,16 @@ class MockScanningCallback : public ScanningCallback { MOCK_METHOD(void, OnFilterEnable, (Enable, uint8_t)); MOCK_METHOD(void, OnFilterParamSetup, (uint8_t, ApcfAction, uint8_t)); MOCK_METHOD(void, OnFilterConfigCallback, (ApcfFilterType, uint8_t, ApcfAction, uint8_t)); - MOCK_METHOD(void, OnPeriodicSyncStarted, (int, uint8_t, uint16_t, uint8_t, AddressWithType, uint8_t, uint16_t)); - MOCK_METHOD(void, OnPeriodicSyncReport, (uint16_t, int8_t, int8_t, uint8_t, std::vector)); + MOCK_METHOD(void, OnPeriodicSyncStarted, + (int, uint8_t, uint16_t, uint8_t, AddressWithType, uint8_t, uint16_t)); + MOCK_METHOD(void, OnPeriodicSyncReport, + (uint16_t, int8_t, int8_t, uint8_t, std::vector)); MOCK_METHOD(void, OnPeriodicSyncLost, (uint16_t)); MOCK_METHOD(void, OnPeriodicSyncTransferred, (int, uint8_t, Address)); }; class MockLeScanningManager : public LeScanningManager { - public: +public: MOCK_METHOD(void, RegisterScanner, (const Uuid)); MOCK_METHOD(void, Unregister, (ScannerId)); MOCK_METHOD(void, Scan, (bool)); @@ -65,18 +66,11 @@ class MockLeScanningManager : public LeScanningManager { MOCK_METHOD(void, StartSync, (uint8_t, const AddressWithType&, uint16_t, uint16_t, int)); MOCK_METHOD(void, StopSync, (uint16_t)); MOCK_METHOD(void, CancelCreateSync, (uint8_t, const Address&)); - MOCK_METHOD( - void, - TransferSync, - (const Address&, - uint16_t connection_handle, - uint16_t service_data, - uint16_t sync_handle, - int pa_source)); - MOCK_METHOD( - void, - TransferSetInfo, - (const Address&, uint16_t connection_handle, uint16_t service_data, uint8_t, int)); + MOCK_METHOD(void, TransferSync, + (const Address&, uint16_t connection_handle, uint16_t service_data, + uint16_t sync_handle, int pa_source)); + MOCK_METHOD(void, TransferSetInfo, + (const Address&, uint16_t connection_handle, uint16_t service_data, uint8_t, int)); MOCK_METHOD(void, SyncTxParameters, (const Address&, uint8_t, uint16_t, uint16_t, int)); }; diff --git a/system/gd/hci/le_scanning_manager_test.cc b/system/gd/hci/le_scanning_manager_test.cc index 6e5ef01e7d7..e52dcaa07ff 100644 --- a/system/gd/hci/le_scanning_manager_test.cc +++ b/system/gd/hci/le_scanning_manager_test.cc @@ -126,18 +126,12 @@ namespace hci { namespace { class TestController : public Controller { - public: - bool IsSupported(OpCode op_code) const override { - return supported_opcodes_.count(op_code) == 1; - } +public: + bool IsSupported(OpCode op_code) const override { return supported_opcodes_.count(op_code) == 1; } - void AddSupported(OpCode op_code) { - supported_opcodes_.insert(op_code); - } + void AddSupported(OpCode op_code) { supported_opcodes_.insert(op_code); } - bool SupportsBleExtendedAdvertising() const override { - return support_ble_extended_advertising_; - } + bool SupportsBleExtendedAdvertising() const override { return support_ble_extended_advertising_; } void SetBleExtendedAdvertisingSupport(bool support) { support_ble_extended_advertising_ = support; @@ -151,26 +145,24 @@ class TestController : public Controller { support_ble_periodic_advertising_sync_transfer_ = support; } - protected: +protected: void Start() override {} void Stop() override {} void ListDependencies(ModuleList* /* list */) const {} - private: +private: std::set supported_opcodes_{}; bool support_ble_extended_advertising_ = false; bool support_ble_periodic_advertising_sync_transfer_ = false; }; class TestLeAddressManager : public LeAddressManager { - public: - TestLeAddressManager( - common::Callback)> enqueue_command, - os::Handler* handler, - Address public_address, - uint8_t accept_list_size, - uint8_t resolving_list_size) - : LeAddressManager(enqueue_command, handler, public_address, accept_list_size, resolving_list_size) {} +public: + TestLeAddressManager(common::Callback)> enqueue_command, + os::Handler* handler, Address public_address, uint8_t accept_list_size, + uint8_t resolving_list_size) + : LeAddressManager(enqueue_command, handler, public_address, accept_list_size, + resolving_list_size) {} AddressPolicy Register(LeAddressManagerCallback* callback) override { client_ = callback; @@ -185,9 +177,7 @@ class TestLeAddressManager : public LeAddressManager { test_client_state_ = UNREGISTERED; } - void AckPause(LeAddressManagerCallback* /* callback */) override { - test_client_state_ = PAUSED; - } + void AckPause(LeAddressManagerCallback* /* callback */) override { test_client_state_ = PAUSED; } void AckResume(LeAddressManagerCallback* /* callback */) override { test_client_state_ = RESUMED; @@ -204,18 +194,17 @@ class TestLeAddressManager : public LeAddressManager { }; class TestAclManager : public AclManager { - public: - LeAddressManager* GetLeAddressManager() override { - return test_le_address_manager_; - } +public: + LeAddressManager* GetLeAddressManager() override { return test_le_address_manager_; } - protected: +protected: void Start() override { thread_ = new os::Thread("thread", os::Thread::Priority::NORMAL); handler_ = new os::Handler(thread_); Address address({0x01, 0x02, 0x03, 0x04, 0x05, 0x06}); test_le_address_manager_ = new TestLeAddressManager( - common::Bind(&TestAclManager::enqueue_command, common::Unretained(this)), handler_, address, 0x3F, 0x3F); + common::Bind(&TestAclManager::enqueue_command, common::Unretained(this)), handler_, + address, 0x3F, 0x3F); } void Stop() override { @@ -231,62 +220,51 @@ class TestAclManager : public AclManager { void enqueue_command(std::unique_ptr /* command_packet */){}; - private: +private: os::Thread* thread_; os::Handler* handler_; TestLeAddressManager* test_le_address_manager_; }; class MockCallbacks : public bluetooth::hci::ScanningCallback { - public: - MOCK_METHOD( - void, - OnScannerRegistered, - (const bluetooth::hci::Uuid app_uuid, ScannerId scanner_id, ScanningStatus status), - (override)); - MOCK_METHOD(void, OnSetScannerParameterComplete, (ScannerId scanner_id, ScanningStatus status), (override)); - MOCK_METHOD( - void, - OnScanResult, - (uint16_t event_type, - uint8_t address_type, - Address address, - uint8_t primary_phy, - uint8_t secondary_phy, - uint8_t advertising_sid, - int8_t tx_power, - int8_t rssi, - uint16_t periodic_advertising_interval, - std::vector advertising_data), - (override)); - MOCK_METHOD( - void, - OnTrackAdvFoundLost, - (bluetooth::hci::AdvertisingFilterOnFoundOnLostInfo on_found_on_lost_info), - (override)); - MOCK_METHOD( - void, - OnBatchScanReports, - (int client_if, int status, int report_format, int num_records, std::vector data), - (override)); +public: + MOCK_METHOD(void, OnScannerRegistered, + (const bluetooth::hci::Uuid app_uuid, ScannerId scanner_id, ScanningStatus status), + (override)); + MOCK_METHOD(void, OnSetScannerParameterComplete, (ScannerId scanner_id, ScanningStatus status), + (override)); + MOCK_METHOD(void, OnScanResult, + (uint16_t event_type, uint8_t address_type, Address address, uint8_t primary_phy, + uint8_t secondary_phy, uint8_t advertising_sid, int8_t tx_power, int8_t rssi, + uint16_t periodic_advertising_interval, std::vector advertising_data), + (override)); + MOCK_METHOD(void, OnTrackAdvFoundLost, + (bluetooth::hci::AdvertisingFilterOnFoundOnLostInfo on_found_on_lost_info), + (override)); + MOCK_METHOD(void, OnBatchScanReports, + (int client_if, int status, int report_format, int num_records, + std::vector data), + (override)); MOCK_METHOD(void, OnBatchScanThresholdCrossed, (int client_if), (override)); MOCK_METHOD(void, OnTimeout, (), (override)); MOCK_METHOD(void, OnFilterEnable, (Enable enable, uint8_t status), (override)); - MOCK_METHOD(void, OnFilterParamSetup, (uint8_t available_spaces, ApcfAction action, uint8_t status), (override)); - MOCK_METHOD( - void, - OnFilterConfigCallback, - (ApcfFilterType filter_type, uint8_t available_spaces, ApcfAction action, uint8_t status), - (override)); - MOCK_METHOD(void, OnPeriodicSyncStarted, (int, uint8_t, uint16_t, uint8_t, AddressWithType, uint8_t, uint16_t)); - MOCK_METHOD(void, OnPeriodicSyncReport, (uint16_t, int8_t, int8_t, uint8_t, std::vector)); + MOCK_METHOD(void, OnFilterParamSetup, + (uint8_t available_spaces, ApcfAction action, uint8_t status), (override)); + MOCK_METHOD(void, OnFilterConfigCallback, + (ApcfFilterType filter_type, uint8_t available_spaces, ApcfAction action, + uint8_t status), + (override)); + MOCK_METHOD(void, OnPeriodicSyncStarted, + (int, uint8_t, uint16_t, uint8_t, AddressWithType, uint8_t, uint16_t)); + MOCK_METHOD(void, OnPeriodicSyncReport, + (uint16_t, int8_t, int8_t, uint8_t, std::vector)); MOCK_METHOD(void, OnPeriodicSyncLost, (uint16_t)); MOCK_METHOD(void, OnPeriodicSyncTransferred, (int, uint8_t, Address)); MOCK_METHOD(void, OnBigInfoReport, (uint16_t, bool)); } mock_callbacks_; class LeScanningManagerTest : public ::testing::Test { - protected: +protected: void SetUp() override { test_hci_layer_ = new HciLayerFake; // Ownership is transferred to registry test_controller_ = new TestController; @@ -301,23 +279,23 @@ class LeScanningManagerTest : public ::testing::Test { void TearDown() override { sync_client_handler(); if (fake_registry_.IsStarted()) { - fake_registry_.SynchronizeModuleHandler(&LeScanningManager::Factory, std::chrono::milliseconds(20)); + fake_registry_.SynchronizeModuleHandler(&LeScanningManager::Factory, + std::chrono::milliseconds(20)); } fake_registry_.StopAll(); } void start_le_scanning_manager() { fake_registry_.Start(&thread_); - le_scanning_manager = - static_cast(fake_registry_.GetModuleUnderTest(&LeScanningManager::Factory)); + le_scanning_manager = static_cast( + fake_registry_.GetModuleUnderTest(&LeScanningManager::Factory)); le_scanning_manager->RegisterScanningCallback(&mock_callbacks_); sync_client_handler(); } void sync_client_handler() { - log::assert_that( - thread_.GetReactor()->WaitForIdle(std::chrono::seconds(2)), - "assert failed: thread_.GetReactor()->WaitForIdle(std::chrono::seconds(2))"); + log::assert_that(thread_.GetReactor()->WaitForIdle(std::chrono::seconds(2)), + "assert failed: thread_.GetReactor()->WaitForIdle(std::chrono::seconds(2))"); } TestModuleRegistry fake_registry_; @@ -332,7 +310,7 @@ class LeScanningManagerTest : public ::testing::Test { }; class LeScanningManagerAndroidHciTest : public LeScanningManagerTest { - protected: +protected: void SetUp() override { LeScanningManagerTest::SetUp(); test_controller_->AddSupported(OpCode::LE_EXTENDED_SCAN_PARAMS); @@ -342,19 +320,16 @@ class LeScanningManagerAndroidHciTest : public LeScanningManagerTest { start_le_scanning_manager(); ASSERT_TRUE(fake_registry_.IsStarted(&HciLayer::Factory)); - ASSERT_EQ(OpCode::LE_ADV_FILTER, test_hci_layer_->GetCommand().GetOpCode()); - test_hci_layer_->IncomingEvent( - LeAdvFilterReadExtendedFeaturesCompleteBuilder::Create(1, ErrorCode::SUCCESS, 0x01, 0x01)); + test_hci_layer_->IncomingEvent(LeAdvFilterReadExtendedFeaturesCompleteBuilder::Create( + 1, ErrorCode::SUCCESS, 0x01, 0x01)); } - void TearDown() override { - LeScanningManagerTest::TearDown(); - } + void TearDown() override { LeScanningManagerTest::TearDown(); } }; class LeScanningManagerExtendedTest : public LeScanningManagerTest { - protected: +protected: void SetUp() override { LeScanningManagerTest::SetUp(); test_controller_->AddSupported(OpCode::LE_SET_EXTENDED_SCAN_PARAMETERS); @@ -373,10 +348,10 @@ TEST_F(LeScanningManagerTest, start_scan_test) { le_scanning_manager->Scan(true); ASSERT_EQ(OpCode::LE_SET_SCAN_PARAMETERS, test_hci_layer_->GetCommand().GetOpCode()); test_hci_layer_->IncomingEvent( - LeSetScanParametersCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + LeSetScanParametersCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); ASSERT_EQ(OpCode::LE_SET_SCAN_ENABLE, test_hci_layer_->GetCommand().GetOpCode()); test_hci_layer_->IncomingEvent( - LeSetScanEnableCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + LeSetScanEnableCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); LeAdvertisingResponse report = make_advertising_report(); EXPECT_CALL(mock_callbacks_, OnScanResult); @@ -390,10 +365,10 @@ TEST_F(LeScanningManagerTest, legacy_adv_scan_ind_report_with_scan_response) { le_scanning_manager->Scan(true); ASSERT_EQ(OpCode::LE_SET_SCAN_PARAMETERS, test_hci_layer_->GetCommand().GetOpCode()); test_hci_layer_->IncomingEvent( - LeSetScanParametersCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + LeSetScanParametersCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); ASSERT_EQ(OpCode::LE_SET_SCAN_ENABLE, test_hci_layer_->GetCommand().GetOpCode()); test_hci_layer_->IncomingEvent( - LeSetScanEnableCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + LeSetScanEnableCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); LeAdvertisingResponse report = make_advertising_report(); // Scannable & not connectable! @@ -420,10 +395,10 @@ TEST_F(LeScanningManagerTest, legacy_adv_ind_report_with_scan_response) { le_scanning_manager->Scan(true); ASSERT_EQ(OpCode::LE_SET_SCAN_PARAMETERS, test_hci_layer_->GetCommand().GetOpCode()); test_hci_layer_->IncomingEvent( - LeSetScanParametersCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + LeSetScanParametersCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); ASSERT_EQ(OpCode::LE_SET_SCAN_ENABLE, test_hci_layer_->GetCommand().GetOpCode()); test_hci_layer_->IncomingEvent( - LeSetScanEnableCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + LeSetScanEnableCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); LeAdvertisingResponse report = make_advertising_report(); // Scannable & connectable! @@ -463,7 +438,7 @@ TEST_F(LeScanningManagerExtendedTest, is_nonstandard_phy_supported_test) { le_scanning_manager->Scan(true); auto command_view = LeSetExtendedScanParametersView::Create( - LeScanningCommandView::Create(test_hci_layer_->GetCommand())); + LeScanningCommandView::Create(test_hci_layer_->GetCommand())); ASSERT_TRUE(command_view.IsValid()); if (com::android::bluetooth::flags::phy_to_native()) { ASSERT_EQ(command_view.GetScanningPhys(), scan_phy); @@ -479,7 +454,7 @@ TEST_F(LeScanningManagerExtendedTest, is_multiple_phy_supported_test) { le_scanning_manager->Scan(true); auto command_view = LeSetExtendedScanParametersView::Create( - LeScanningCommandView::Create(test_hci_layer_->GetCommand())); + LeScanningCommandView::Create(test_hci_layer_->GetCommand())); ASSERT_TRUE(command_view.IsValid()); if (com::android::bluetooth::flags::phy_to_native()) { ASSERT_EQ(command_view.GetScanningPhys(), scan_phy); @@ -504,8 +479,10 @@ TEST_F(LeScanningManagerAndroidHciTest, start_scan_test) { TEST_F(LeScanningManagerAndroidHciTest, is_ad_type_filter_supported_true_test) { sync_client_handler(); client_handler_->Post(common::BindOnce( - [](LeScanningManager* le_scanning_manager) { ASSERT_TRUE(le_scanning_manager->IsAdTypeFilterSupported()); }, - le_scanning_manager)); + [](LeScanningManager* le_scanning_manager) { + ASSERT_TRUE(le_scanning_manager->IsAdTypeFilterSupported()); + }, + le_scanning_manager)); } TEST_F(LeScanningManagerAndroidHciTest, scan_filter_enable_test) { @@ -513,112 +490,107 @@ TEST_F(LeScanningManagerAndroidHciTest, scan_filter_enable_test) { sync_client_handler(); EXPECT_CALL(mock_callbacks_, OnFilterEnable); - test_hci_layer_->IncomingEvent( - LeAdvFilterEnableCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS, Enable::ENABLED)); + test_hci_layer_->IncomingEvent(LeAdvFilterEnableCompleteBuilder::Create( + uint8_t{1}, ErrorCode::SUCCESS, Enable::ENABLED)); sync_client_handler(); } TEST_F(LeScanningManagerAndroidHciTest, scan_filter_parameter_test) { - AdvertisingFilterParameter advertising_filter_parameter{}; advertising_filter_parameter.delivery_mode = DeliveryMode::IMMEDIATE; - le_scanning_manager->ScanFilterParameterSetup(ApcfAction::ADD, 0x01, advertising_filter_parameter); + le_scanning_manager->ScanFilterParameterSetup(ApcfAction::ADD, 0x01, + advertising_filter_parameter); auto commandView = test_hci_layer_->GetCommand(); ASSERT_EQ(OpCode::LE_ADV_FILTER, commandView.GetOpCode()); auto filter_command_view = LeAdvFilterSetFilteringParametersView::Create( - LeAdvFilterView::Create(LeScanningCommandView::Create(commandView))); + LeAdvFilterView::Create(LeScanningCommandView::Create(commandView))); ASSERT_TRUE(filter_command_view.IsValid()); ASSERT_EQ(filter_command_view.GetApcfOpcode(), ApcfOpcode::SET_FILTERING_PARAMETERS); EXPECT_CALL(mock_callbacks_, OnFilterParamSetup); - test_hci_layer_->IncomingEvent( - LeAdvFilterSetFilteringParametersCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS, ApcfAction::ADD, 0x0a)); + test_hci_layer_->IncomingEvent(LeAdvFilterSetFilteringParametersCompleteBuilder::Create( + uint8_t{1}, ErrorCode::SUCCESS, ApcfAction::ADD, 0x0a)); sync_client_handler(); } TEST_F(LeScanningManagerAndroidHciTest, scan_filter_add_broadcaster_address_test) { - std::vector filters = {}; filters.push_back(make_filter(ApcfFilterType::BROADCASTER_ADDRESS)); le_scanning_manager->ScanFilterAdd(0x01, filters); auto commandView = test_hci_layer_->GetCommand(); ASSERT_EQ(OpCode::LE_ADV_FILTER, commandView.GetOpCode()); - auto filter_command_view = - LeAdvFilterBroadcasterAddressView::Create(LeAdvFilterView::Create(LeScanningCommandView::Create(commandView))); + auto filter_command_view = LeAdvFilterBroadcasterAddressView::Create( + LeAdvFilterView::Create(LeScanningCommandView::Create(commandView))); ASSERT_TRUE(filter_command_view.IsValid()); ASSERT_EQ(filter_command_view.GetApcfOpcode(), ApcfOpcode::BROADCASTER_ADDRESS); EXPECT_CALL(mock_callbacks_, OnFilterConfigCallback); - test_hci_layer_->IncomingEvent( - LeAdvFilterBroadcasterAddressCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS, ApcfAction::ADD, 0x0a)); + test_hci_layer_->IncomingEvent(LeAdvFilterBroadcasterAddressCompleteBuilder::Create( + uint8_t{1}, ErrorCode::SUCCESS, ApcfAction::ADD, 0x0a)); } TEST_F(LeScanningManagerAndroidHciTest, scan_filter_add_service_uuid_test) { - std::vector filters = {}; filters.push_back(make_filter(ApcfFilterType::SERVICE_UUID)); le_scanning_manager->ScanFilterAdd(0x01, filters); auto commandView = test_hci_layer_->GetCommand(); ASSERT_EQ(OpCode::LE_ADV_FILTER, commandView.GetOpCode()); - auto filter_command_view = - LeAdvFilterServiceUuidView::Create(LeAdvFilterView::Create(LeScanningCommandView::Create(commandView))); + auto filter_command_view = LeAdvFilterServiceUuidView::Create( + LeAdvFilterView::Create(LeScanningCommandView::Create(commandView))); ASSERT_TRUE(filter_command_view.IsValid()); ASSERT_EQ(filter_command_view.GetApcfOpcode(), ApcfOpcode::SERVICE_UUID); EXPECT_CALL(mock_callbacks_, OnFilterConfigCallback); - test_hci_layer_->IncomingEvent( - LeAdvFilterServiceUuidCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS, ApcfAction::ADD, 0x0a)); + test_hci_layer_->IncomingEvent(LeAdvFilterServiceUuidCompleteBuilder::Create( + uint8_t{1}, ErrorCode::SUCCESS, ApcfAction::ADD, 0x0a)); } TEST_F(LeScanningManagerAndroidHciTest, scan_filter_add_local_name_test) { - std::vector filters = {}; filters.push_back(make_filter(ApcfFilterType::LOCAL_NAME)); le_scanning_manager->ScanFilterAdd(0x01, filters); auto commandView = test_hci_layer_->GetCommand(); ASSERT_EQ(OpCode::LE_ADV_FILTER, commandView.GetOpCode()); - auto filter_command_view = - LeAdvFilterLocalNameView::Create(LeAdvFilterView::Create(LeScanningCommandView::Create(commandView))); + auto filter_command_view = LeAdvFilterLocalNameView::Create( + LeAdvFilterView::Create(LeScanningCommandView::Create(commandView))); ASSERT_TRUE(filter_command_view.IsValid()); ASSERT_EQ(filter_command_view.GetApcfOpcode(), ApcfOpcode::LOCAL_NAME); EXPECT_CALL(mock_callbacks_, OnFilterConfigCallback); - test_hci_layer_->IncomingEvent( - LeAdvFilterLocalNameCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS, ApcfAction::ADD, 0x0a)); + test_hci_layer_->IncomingEvent(LeAdvFilterLocalNameCompleteBuilder::Create( + uint8_t{1}, ErrorCode::SUCCESS, ApcfAction::ADD, 0x0a)); } TEST_F(LeScanningManagerAndroidHciTest, scan_filter_add_manufacturer_data_test) { - std::vector filters = {}; filters.push_back(make_filter(ApcfFilterType::MANUFACTURER_DATA)); le_scanning_manager->ScanFilterAdd(0x01, filters); auto commandView = test_hci_layer_->GetCommand(); ASSERT_EQ(OpCode::LE_ADV_FILTER, commandView.GetOpCode()); - auto filter_command_view = - LeAdvFilterManufacturerDataView::Create(LeAdvFilterView::Create(LeScanningCommandView::Create(commandView))); + auto filter_command_view = LeAdvFilterManufacturerDataView::Create( + LeAdvFilterView::Create(LeScanningCommandView::Create(commandView))); ASSERT_TRUE(filter_command_view.IsValid()); ASSERT_EQ(filter_command_view.GetApcfOpcode(), ApcfOpcode::MANUFACTURER_DATA); EXPECT_CALL(mock_callbacks_, OnFilterConfigCallback); - test_hci_layer_->IncomingEvent( - LeAdvFilterManufacturerDataCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS, ApcfAction::ADD, 0x0a)); + test_hci_layer_->IncomingEvent(LeAdvFilterManufacturerDataCompleteBuilder::Create( + uint8_t{1}, ErrorCode::SUCCESS, ApcfAction::ADD, 0x0a)); } TEST_F(LeScanningManagerAndroidHciTest, scan_filter_add_service_data_test) { - std::vector filters = {}; filters.push_back(make_filter(hci::ApcfFilterType::SERVICE_DATA)); le_scanning_manager->ScanFilterAdd(0x01, filters); auto commandView = test_hci_layer_->GetCommand(); ASSERT_EQ(OpCode::LE_ADV_FILTER, commandView.GetOpCode()); - auto filter_command_view = - LeAdvFilterServiceDataView::Create(LeAdvFilterView::Create(LeScanningCommandView::Create(commandView))); + auto filter_command_view = LeAdvFilterServiceDataView::Create( + LeAdvFilterView::Create(LeScanningCommandView::Create(commandView))); ASSERT_TRUE(filter_command_view.IsValid()); ASSERT_EQ(filter_command_view.GetApcfOpcode(), ApcfOpcode::SERVICE_DATA); EXPECT_CALL(mock_callbacks_, OnFilterConfigCallback); - test_hci_layer_->IncomingEvent( - LeAdvFilterServiceDataCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS, ApcfAction::ADD, 0x0a)); + test_hci_layer_->IncomingEvent(LeAdvFilterServiceDataCompleteBuilder::Create( + uint8_t{1}, ErrorCode::SUCCESS, ApcfAction::ADD, 0x0a)); } TEST_F(LeScanningManagerAndroidHciTest, scan_filter_add_transport_discovery_data_test) { @@ -628,21 +600,23 @@ TEST_F(LeScanningManagerAndroidHciTest, scan_filter_add_transport_discovery_data auto commandView = test_hci_layer_->GetCommand(); ASSERT_EQ(OpCode::LE_ADV_FILTER, commandView.GetOpCode()); auto filter_command_view = LeAdvFilterTransportDiscoveryDataView::Create( - LeAdvFilterView::Create(LeScanningCommandView::Create(commandView))); + LeAdvFilterView::Create(LeScanningCommandView::Create(commandView))); ASSERT_TRUE(filter_command_view.IsValid()); ASSERT_EQ(filter_command_view.GetApcfOpcode(), ApcfOpcode::TRANSPORT_DISCOVERY_DATA); EXPECT_CALL(mock_callbacks_, OnFilterConfigCallback); test_hci_layer_->IncomingEvent(LeAdvFilterTransportDiscoveryDataCompleteBuilder::Create( - uint8_t{1}, ErrorCode::SUCCESS, ApcfAction::ADD, 0x0a)); + uint8_t{1}, ErrorCode::SUCCESS, ApcfAction::ADD, 0x0a)); } TEST_F(LeScanningManagerAndroidHciTest, scan_filter_add_ad_type_test) { sync_client_handler(); client_handler_->Post(common::BindOnce( - [](LeScanningManager* le_scanning_manager) { ASSERT_TRUE(le_scanning_manager->IsAdTypeFilterSupported()); }, - le_scanning_manager)); + [](LeScanningManager* le_scanning_manager) { + ASSERT_TRUE(le_scanning_manager->IsAdTypeFilterSupported()); + }, + le_scanning_manager)); std::vector filters = {}; hci::AdvertisingPacketContentFilterCommand filter = make_filter(hci::ApcfFilterType::AD_TYPE); @@ -651,24 +625,27 @@ TEST_F(LeScanningManagerAndroidHciTest, scan_filter_add_ad_type_test) { sync_client_handler(); EXPECT_CALL(mock_callbacks_, OnFilterConfigCallback); - test_hci_layer_->IncomingEvent( - LeAdvFilterADTypeCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS, ApcfAction::ADD, 0x0a)); + test_hci_layer_->IncomingEvent(LeAdvFilterADTypeCompleteBuilder::Create( + uint8_t{1}, ErrorCode::SUCCESS, ApcfAction::ADD, 0x0a)); } TEST_F(LeScanningManagerAndroidHciTest, read_batch_scan_result) { le_scanning_manager->BatchScanConifgStorage(100, 0, 95, 0x00); sync_client_handler(); ASSERT_EQ(OpCode::LE_BATCH_SCAN, test_hci_layer_->GetCommand().GetOpCode()); - test_hci_layer_->IncomingEvent(LeBatchScanEnableCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + test_hci_layer_->IncomingEvent( + LeBatchScanEnableCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); ASSERT_EQ(OpCode::LE_BATCH_SCAN, test_hci_layer_->GetCommand().GetOpCode()); test_hci_layer_->IncomingEvent( - LeBatchScanSetStorageParametersCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + LeBatchScanSetStorageParametersCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); // Enable batch scan - le_scanning_manager->BatchScanEnable(BatchScanMode::FULL, 2400, 2400, BatchScanDiscardRule::OLDEST); + le_scanning_manager->BatchScanEnable(BatchScanMode::FULL, 2400, 2400, + BatchScanDiscardRule::OLDEST); ASSERT_EQ(OpCode::LE_BATCH_SCAN, test_hci_layer_->GetCommand().GetOpCode()); - test_hci_layer_->IncomingEvent(LeBatchScanEnableCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + test_hci_layer_->IncomingEvent( + LeBatchScanEnableCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); // Read batch scan data @@ -676,17 +653,18 @@ TEST_F(LeScanningManagerAndroidHciTest, read_batch_scan_result) { ASSERT_EQ(OpCode::LE_BATCH_SCAN, test_hci_layer_->GetCommand().GetOpCode()); // We will send read command while num_of_record != 0 - std::vector raw_data = {0x5c, 0x1f, 0xa2, 0xc3, 0x63, 0x5d, 0x01, 0xf5, 0xb3, 0x5e, 0x00, 0x0c, 0x02, - 0x01, 0x02, 0x05, 0x09, 0x6d, 0x76, 0x38, 0x76, 0x02, 0x0a, 0xf5, 0x00}; + std::vector raw_data = {0x5c, 0x1f, 0xa2, 0xc3, 0x63, 0x5d, 0x01, 0xf5, 0xb3, + 0x5e, 0x00, 0x0c, 0x02, 0x01, 0x02, 0x05, 0x09, 0x6d, + 0x76, 0x38, 0x76, 0x02, 0x0a, 0xf5, 0x00}; test_hci_layer_->IncomingEvent(LeBatchScanReadResultParametersCompleteRawBuilder::Create( - uint8_t{1}, ErrorCode::SUCCESS, BatchScanDataRead::FULL_MODE_DATA, 1, raw_data)); + uint8_t{1}, ErrorCode::SUCCESS, BatchScanDataRead::FULL_MODE_DATA, 1, raw_data)); ASSERT_EQ(OpCode::LE_BATCH_SCAN, test_hci_layer_->GetCommand().GetOpCode()); // OnBatchScanReports will be trigger when num_of_record == 0 EXPECT_CALL(mock_callbacks_, OnBatchScanReports); test_hci_layer_->IncomingEvent(LeBatchScanReadResultParametersCompleteRawBuilder::Create( - uint8_t{1}, ErrorCode::SUCCESS, BatchScanDataRead::FULL_MODE_DATA, 0, {})); + uint8_t{1}, ErrorCode::SUCCESS, BatchScanDataRead::FULL_MODE_DATA, 0, {})); } TEST_F(LeScanningManagerAndroidHciTest, start_sync_test) { @@ -701,8 +679,8 @@ TEST_F(LeScanningManagerAndroidHciTest, start_sync_test) { le_scanning_manager->TransferSync(address, handle, service_data, sync_handle, pa_source); sync_client_handler(); - ASSERT_EQ( - OpCode::LE_PERIODIC_ADVERTISING_SYNC_TRANSFER, test_hci_layer_->GetCommand().GetOpCode()); + ASSERT_EQ(OpCode::LE_PERIODIC_ADVERTISING_SYNC_TRANSFER, + test_hci_layer_->GetCommand().GetOpCode()); } TEST_F(LeScanningManagerAndroidHciTest, start_sync_invalid_handle_test) { @@ -714,10 +692,9 @@ TEST_F(LeScanningManagerAndroidHciTest, start_sync_invalid_handle_test) { Address::FromString("12:34:56:78:9a:bc", address); - EXPECT_CALL( - mock_callbacks_, - OnPeriodicSyncTransferred( - pa_source, static_cast(ErrorCode::UNKNOWN_CONNECTION), address)); + EXPECT_CALL(mock_callbacks_, + OnPeriodicSyncTransferred(pa_source, static_cast(ErrorCode::UNKNOWN_CONNECTION), + address)); le_scanning_manager->TransferSync(address, handle, service_data, sync_handle, pa_source); sync_client_handler(); } @@ -734,8 +711,8 @@ TEST_F(LeScanningManagerAndroidHciTest, set_info_test) { le_scanning_manager->TransferSetInfo(address, handle, service_data, sync_handle, pa_source); sync_client_handler(); - ASSERT_EQ( - OpCode::LE_PERIODIC_ADVERTISING_SET_INFO_TRANSFER, test_hci_layer_->GetCommand().GetOpCode()); + ASSERT_EQ(OpCode::LE_PERIODIC_ADVERTISING_SET_INFO_TRANSFER, + test_hci_layer_->GetCommand().GetOpCode()); } TEST_F(LeScanningManagerAndroidHciTest, set_info_invalid_handle_test) { @@ -747,10 +724,9 @@ TEST_F(LeScanningManagerAndroidHciTest, set_info_invalid_handle_test) { Address::FromString("12:34:56:78:9a:bc", address); - EXPECT_CALL( - mock_callbacks_, - OnPeriodicSyncTransferred( - pa_source, static_cast(ErrorCode::UNKNOWN_CONNECTION), address)); + EXPECT_CALL(mock_callbacks_, + OnPeriodicSyncTransferred(pa_source, static_cast(ErrorCode::UNKNOWN_CONNECTION), + address)); le_scanning_manager->TransferSetInfo(address, handle, service_data, sync_handle, pa_source); sync_client_handler(); } @@ -761,9 +737,11 @@ TEST_F(LeScanningManagerExtendedTest, start_scan_test) { // Enable scan le_scanning_manager->Scan(true); ASSERT_EQ(OpCode::LE_SET_EXTENDED_SCAN_PARAMETERS, test_hci_layer_->GetCommand().GetOpCode()); - test_hci_layer_->IncomingEvent(LeSetExtendedScanParametersCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + test_hci_layer_->IncomingEvent( + LeSetExtendedScanParametersCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); ASSERT_EQ(OpCode::LE_SET_EXTENDED_SCAN_ENABLE, test_hci_layer_->GetCommand().GetOpCode()); - test_hci_layer_->IncomingEvent(LeSetExtendedScanEnableCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + test_hci_layer_->IncomingEvent( + LeSetExtendedScanEnableCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); LeExtendedAdvertisingResponse report{}; report.connectable_ = 1; report.scannable_ = 0; @@ -789,23 +767,23 @@ TEST_F(LeScanningManagerExtendedTest, start_scan_test) { TEST_F(LeScanningManagerExtendedTest, start_scan_on_resume_conflict_test) { TestLeAddressManager* test_le_address_manager = - (TestLeAddressManager*)test_acl_manager_->GetLeAddressManager(); + (TestLeAddressManager*)test_acl_manager_->GetLeAddressManager(); // Enable scan le_scanning_manager->Scan(true); ASSERT_EQ(OpCode::LE_SET_EXTENDED_SCAN_PARAMETERS, test_hci_layer_->GetCommand().GetOpCode()); test_hci_layer_->IncomingEvent( - LeSetExtendedScanParametersCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + LeSetExtendedScanParametersCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); ASSERT_EQ(OpCode::LE_SET_EXTENDED_SCAN_ENABLE, test_hci_layer_->GetCommand().GetOpCode()); test_hci_layer_->IncomingEvent( - LeSetExtendedScanEnableCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + LeSetExtendedScanEnableCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); sync_client_handler(); // Pause scan test_le_address_manager->client_->OnPause(); ASSERT_EQ(OpCode::LE_SET_EXTENDED_SCAN_ENABLE, test_hci_layer_->GetCommand().GetOpCode()); test_hci_layer_->IncomingEvent( - LeSetExtendedScanEnableCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + LeSetExtendedScanEnableCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); // Disable scan le_scanning_manager->Scan(false); @@ -815,10 +793,10 @@ TEST_F(LeScanningManagerExtendedTest, start_scan_on_resume_conflict_test) { le_scanning_manager->Scan(true); ASSERT_EQ(OpCode::LE_SET_EXTENDED_SCAN_PARAMETERS, test_hci_layer_->GetCommand().GetOpCode()); test_hci_layer_->IncomingEvent( - LeSetExtendedScanParametersCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + LeSetExtendedScanParametersCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); ASSERT_EQ(OpCode::LE_SET_EXTENDED_SCAN_ENABLE, test_hci_layer_->GetCommand().GetOpCode()); test_hci_layer_->IncomingEvent( - LeSetExtendedScanEnableCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + LeSetExtendedScanEnableCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); // Ensure there is no double enable commands on resume test_le_address_manager->client_->OnResume(); @@ -828,65 +806,74 @@ TEST_F(LeScanningManagerExtendedTest, start_scan_on_resume_conflict_test) { TEST_F(LeScanningManagerExtendedTest, on_pause_on_resume_test) { TestLeAddressManager* test_le_address_manager = - (TestLeAddressManager*)test_acl_manager_->GetLeAddressManager(); + (TestLeAddressManager*)test_acl_manager_->GetLeAddressManager(); // Enable scan le_scanning_manager->Scan(true); ASSERT_EQ(OpCode::LE_SET_EXTENDED_SCAN_PARAMETERS, test_hci_layer_->GetCommand().GetOpCode()); test_hci_layer_->IncomingEvent( - LeSetExtendedScanParametersCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + LeSetExtendedScanParametersCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); ASSERT_EQ(OpCode::LE_SET_EXTENDED_SCAN_ENABLE, test_hci_layer_->GetCommand().GetOpCode()); test_hci_layer_->IncomingEvent( - LeSetExtendedScanEnableCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + LeSetExtendedScanEnableCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); sync_client_handler(); // Pause scan test_le_address_manager->client_->OnPause(); ASSERT_EQ(OpCode::LE_SET_EXTENDED_SCAN_ENABLE, test_hci_layer_->GetCommand().GetOpCode()); test_hci_layer_->IncomingEvent( - LeSetExtendedScanEnableCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + LeSetExtendedScanEnableCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); // Ensure scan is resumed (enabled) test_le_address_manager->client_->OnResume(); ASSERT_EQ(OpCode::LE_SET_EXTENDED_SCAN_ENABLE, test_hci_layer_->GetCommand().GetOpCode()); test_hci_layer_->IncomingEvent( - LeSetExtendedScanEnableCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + LeSetExtendedScanEnableCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); } TEST_F(LeScanningManagerExtendedTest, ignore_on_pause_on_resume_after_unregistered) { - TestLeAddressManager* test_le_address_manager = (TestLeAddressManager*)test_acl_manager_->GetLeAddressManager(); + TestLeAddressManager* test_le_address_manager = + (TestLeAddressManager*)test_acl_manager_->GetLeAddressManager(); test_le_address_manager->ignore_unregister_for_testing = true; // Register LeAddressManager le_scanning_manager->Scan(true); ASSERT_EQ(OpCode::LE_SET_EXTENDED_SCAN_PARAMETERS, test_hci_layer_->GetCommand().GetOpCode()); - test_hci_layer_->IncomingEvent(LeSetExtendedScanParametersCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + test_hci_layer_->IncomingEvent( + LeSetExtendedScanParametersCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); ASSERT_EQ(OpCode::LE_SET_EXTENDED_SCAN_ENABLE, test_hci_layer_->GetCommand().GetOpCode()); - test_hci_layer_->IncomingEvent(LeSetExtendedScanEnableCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + test_hci_layer_->IncomingEvent( + LeSetExtendedScanEnableCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); sync_client_handler(); // Unregister LeAddressManager le_scanning_manager->Scan(false); ASSERT_EQ(OpCode::LE_SET_EXTENDED_SCAN_ENABLE, test_hci_layer_->GetCommand().GetOpCode()); - test_hci_layer_->IncomingEvent(LeSetExtendedScanEnableCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + test_hci_layer_->IncomingEvent( + LeSetExtendedScanEnableCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); sync_client_handler(); // Unregistered client should ignore OnPause/OnResume ASSERT_NE(test_le_address_manager->client_, nullptr); - ASSERT_EQ(test_le_address_manager->test_client_state_, TestLeAddressManager::TestClientState::UNREGISTERED); + ASSERT_EQ(test_le_address_manager->test_client_state_, + TestLeAddressManager::TestClientState::UNREGISTERED); test_le_address_manager->client_->OnPause(); - ASSERT_EQ(test_le_address_manager->test_client_state_, TestLeAddressManager::TestClientState::UNREGISTERED); + ASSERT_EQ(test_le_address_manager->test_client_state_, + TestLeAddressManager::TestClientState::UNREGISTERED); test_le_address_manager->client_->OnResume(); - ASSERT_EQ(test_le_address_manager->test_client_state_, TestLeAddressManager::TestClientState::UNREGISTERED); + ASSERT_EQ(test_le_address_manager->test_client_state_, + TestLeAddressManager::TestClientState::UNREGISTERED); } TEST_F(LeScanningManagerExtendedTest, drop_insignificant_bytes_test) { // Enable scan le_scanning_manager->Scan(true); ASSERT_EQ(OpCode::LE_SET_EXTENDED_SCAN_PARAMETERS, test_hci_layer_->GetCommand().GetOpCode()); - test_hci_layer_->IncomingEvent(LeSetExtendedScanParametersCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + test_hci_layer_->IncomingEvent( + LeSetExtendedScanParametersCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); ASSERT_EQ(OpCode::LE_SET_EXTENDED_SCAN_ENABLE, test_hci_layer_->GetCommand().GetOpCode()); - test_hci_layer_->IncomingEvent(LeSetExtendedScanEnableCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); + test_hci_layer_->IncomingEvent( + LeSetExtendedScanEnableCompleteBuilder::Create(uint8_t{1}, ErrorCode::SUCCESS)); // Prepare advertisement report LeExtendedAdvertisingResponse advertisement_report{}; @@ -933,8 +920,10 @@ TEST_F(LeScanningManagerExtendedTest, drop_insignificant_bytes_test) { EXPECT_CALL(mock_callbacks_, OnScanResult(_, _, _, _, _, _, _, _, _, result)); // Send both reports - test_hci_layer_->IncomingLeMetaEvent(LeExtendedAdvertisingReportBuilder::Create({advertisement_report})); - test_hci_layer_->IncomingLeMetaEvent(LeExtendedAdvertisingReportBuilder::Create({scan_response_report})); + test_hci_layer_->IncomingLeMetaEvent( + LeExtendedAdvertisingReportBuilder::Create({advertisement_report})); + test_hci_layer_->IncomingLeMetaEvent( + LeExtendedAdvertisingReportBuilder::Create({scan_response_report})); } } // namespace diff --git a/system/gd/hci/le_scanning_reassembler.cc b/system/gd/hci/le_scanning_reassembler.cc index d174a44d755..383b2bc4aea 100644 --- a/system/gd/hci/le_scanning_reassembler.cc +++ b/system/gd/hci/le_scanning_reassembler.cc @@ -34,12 +34,9 @@ namespace bluetooth::hci { std::optional -LeScanningReassembler::ProcessAdvertisingReport( - uint16_t event_type, - uint8_t address_type, - Address address, - uint8_t advertising_sid, - const std::vector& advertising_data) { +LeScanningReassembler::ProcessAdvertisingReport(uint16_t event_type, uint8_t address_type, + Address address, uint8_t advertising_sid, + const std::vector& advertising_data) { bool is_scannable = event_type & (1 << kScannableBit); bool is_scan_response = event_type & (1 << kScanResponseBit); bool is_legacy = event_type & (1 << kLegacyBit); @@ -69,7 +66,7 @@ LeScanningReassembler::ProcessAdvertisingReport( // Concatenate the data with existing fragments. std::list::iterator advertising_fragment = - AppendFragment(key, event_type, advertising_data); + AppendFragment(key, event_type, advertising_data); // Trim the advertising data when the complete payload is received. if (data_status != DataStatus::CONTINUING) { @@ -91,18 +88,18 @@ LeScanningReassembler::ProcessAdvertisingReport( // Otherwise the full advertising report has been reassembled, // removed the cache entry and return the complete advertising data. - CompleteAdvertisingData result{ - .extended_event_type = advertising_fragment->extended_event_type, - .data = std::move(advertising_fragment->data)}; + CompleteAdvertisingData result{.extended_event_type = advertising_fragment->extended_event_type, + .data = std::move(advertising_fragment->data)}; cache_.erase(advertising_fragment); return result; } std::optional> LeScanningReassembler::ProcessPeriodicAdvertisingReport( - uint16_t sync_handle, DataStatus data_status, const std::vector& advertising_data) { + uint16_t sync_handle, DataStatus data_status, + const std::vector& advertising_data) { // Concatenate the data with existing fragments. std::list::iterator advertising_fragment = - AppendPeriodicFragment(sync_handle, advertising_data); + AppendPeriodicFragment(sync_handle, advertising_data); // Return and wait for additional fragments if the data is marked as // incomplete. @@ -120,7 +117,7 @@ std::optional> LeScanningReassembler::ProcessPeriodicAdvert /// Trim the advertising data by removing empty or overflowing /// GAP Data entries. std::vector LeScanningReassembler::TrimAdvertisingData( - const std::vector& advertising_data) { + const std::vector& advertising_data) { // Remove empty and overflowing entries from the advertising data. std::vector significant_advertising_data; for (size_t offset = 0; offset < advertising_data.size();) { @@ -129,10 +126,9 @@ std::vector LeScanningReassembler::TrimAdvertisingData( if (entry_size != 0 && entry_size < remaining_size) { significant_advertising_data.push_back(entry_size); - significant_advertising_data.insert( - significant_advertising_data.end(), - advertising_data.begin() + offset + 1, - advertising_data.begin() + offset + 1 + entry_size); + significant_advertising_data.insert(significant_advertising_data.end(), + advertising_data.begin() + offset + 1, + advertising_data.begin() + offset + 1 + entry_size); } offset += entry_size + 1; @@ -141,8 +137,9 @@ std::vector LeScanningReassembler::TrimAdvertisingData( return significant_advertising_data; } -LeScanningReassembler::AdvertisingKey::AdvertisingKey( - Address address, DirectAdvertisingAddressType address_type, uint8_t sid) +LeScanningReassembler::AdvertisingKey::AdvertisingKey(Address address, + DirectAdvertisingAddressType address_type, + uint8_t sid) : address(), sid() { // The address type is NO_ADDRESS_PROVIDED for anonymous advertising. if (address_type != DirectAdvertisingAddressType::NO_ADDRESS_PROVIDED) { @@ -163,8 +160,8 @@ bool LeScanningReassembler::AdvertisingKey::operator==(const AdvertisingKey& oth /// If the advertiser is unknown a new entry is added, optionally by /// dropping the oldest advertiser. std::list::iterator -LeScanningReassembler::AppendFragment( - const AdvertisingKey& key, uint16_t extended_event_type, const std::vector& data) { +LeScanningReassembler::AppendFragment(const AdvertisingKey& key, uint16_t extended_event_type, + const std::vector& data) { auto it = FindFragment(key); if (it != cache_.end()) { // Legacy scan responses don't contain a 'connectable' bit, so this adds the @@ -172,7 +169,7 @@ LeScanningReassembler::AppendFragment( if ((extended_event_type & (1 << kLegacyBit)) && (extended_event_type & (1 << kScanResponseBit))) { it->extended_event_type = - extended_event_type | (it->extended_event_type & (1 << kConnectableBit)); + extended_event_type | (it->extended_event_type & (1 << kConnectableBit)); } else { it->extended_event_type = extended_event_type; } @@ -200,7 +197,7 @@ bool LeScanningReassembler::ContainsFragment(const AdvertisingKey& key) { } std::list::iterator LeScanningReassembler::FindFragment( - const AdvertisingKey& key) { + const AdvertisingKey& key) { for (auto it = cache_.begin(); it != cache_.end(); it++) { if (it->key == key) { return it; @@ -213,8 +210,8 @@ std::list::iterator LeScanningReasse /// If the advertiser is unknown a new entry is added, optionally by /// dropping the oldest advertiser. std::list::iterator -LeScanningReassembler::AppendPeriodicFragment( - uint16_t sync_handle, const std::vector& data) { +LeScanningReassembler::AppendPeriodicFragment(uint16_t sync_handle, + const std::vector& data) { auto it = FindPeriodicFragment(sync_handle); if (it != periodic_cache_.end()) { it->data.insert(it->data.end(), data.cbegin(), data.cend()); diff --git a/system/gd/hci/le_scanning_reassembler.h b/system/gd/hci/le_scanning_reassembler.h index e5e416e1f8e..afc4b9b303f 100644 --- a/system/gd/hci/le_scanning_reassembler.h +++ b/system/gd/hci/le_scanning_reassembler.h @@ -34,13 +34,13 @@ namespace bluetooth::hci { /// matching advertising data. class LeScanningReassembler { - public: +public: struct CompleteAdvertisingData { uint16_t extended_event_type; std::vector data; }; - LeScanningReassembler(){}; + LeScanningReassembler() {} LeScanningReassembler(const LeScanningReassembler&) = delete; @@ -52,18 +52,15 @@ class LeScanningReassembler { /// Returns the completed advertising data if the event was complete, or the /// completion of a fragmented advertising event. std::optional ProcessAdvertisingReport( - uint16_t event_type, - uint8_t address_type, - Address address, - uint8_t advertising_sid, - const std::vector& advertising_data); + uint16_t event_type, uint8_t address_type, Address address, uint8_t advertising_sid, + const std::vector& advertising_data); /// Process an incoming periodic advertising report, extracted from the /// HCI LE Periodic Advertising Report events. /// Returns the completed advertising data if the event was complete, /// or the completion of a fragmented advertising event. std::optional> ProcessPeriodicAdvertisingReport( - uint16_t sync_handle, DataStatus status, const std::vector& advertising_data); + uint16_t sync_handle, DataStatus status, const std::vector& advertising_data); /// Configure the scan response filter. /// If true all scan responses are ignored. @@ -71,7 +68,7 @@ class LeScanningReassembler { ignore_scan_responses_ = ignore_scan_responses; } - private: +private: /// Determine if scan responses should be processed or ignored. bool ignore_scan_responses_{false}; @@ -107,8 +104,8 @@ class LeScanningReassembler { uint16_t extended_event_type; std::vector data; - AdvertisingFragment( - const AdvertisingKey& key, uint16_t extended_event_type, const std::vector& data) + AdvertisingFragment(const AdvertisingKey& key, uint16_t extended_event_type, + const std::vector& data) : key(key), extended_event_type(extended_event_type), data(data.begin(), data.end()) {} }; @@ -130,8 +127,9 @@ class LeScanningReassembler { std::list cache_; /// Advertising cache management methods. - std::list::iterator AppendFragment( - const AdvertisingKey& key, uint16_t extended_event_type, const std::vector& data); + std::list::iterator AppendFragment(const AdvertisingKey& key, + uint16_t extended_event_type, + const std::vector& data); void RemoveFragment(const AdvertisingKey& key); @@ -144,7 +142,7 @@ class LeScanningReassembler { std::list periodic_cache_; std::list::iterator AppendPeriodicFragment( - uint16_t sync_handle, const std::vector& data); + uint16_t sync_handle, const std::vector& data); std::list::iterator FindPeriodicFragment(uint16_t sync_handle); diff --git a/system/gd/hci/le_scanning_reassembler_test.cc b/system/gd/hci/le_scanning_reassembler_test.cc index 828699fb78b..d2461391f98 100644 --- a/system/gd/hci/le_scanning_reassembler_test.cc +++ b/system/gd/hci/le_scanning_reassembler_test.cc @@ -47,60 +47,48 @@ static const uint16_t kTestSyncHandle1 = 0x4242; static const uint16_t kTestSyncHandle2 = 0x4243; class LeScanningReassemblerTest : public ::testing::Test { - public: +public: LeScanningReassembler reassembler_; }; TEST_F(LeScanningReassemblerTest, trim_advertising_data) { // TrimAdvertisingData should filter out empty entries. - ASSERT_EQ( - LeScanningReassembler::TrimAdvertisingData({0x1, 0x2, 0x0, 0x0, 0x3, 0x4, 0x5, 0x6}), - std::vector({0x1, 0x2, 0x3, 0x4, 0x5, 0x6})); + ASSERT_EQ(LeScanningReassembler::TrimAdvertisingData({0x1, 0x2, 0x0, 0x0, 0x3, 0x4, 0x5, 0x6}), + std::vector({0x1, 0x2, 0x3, 0x4, 0x5, 0x6})); // TrimAdvertisingData should remove trailing zeros. - ASSERT_EQ( - LeScanningReassembler::TrimAdvertisingData({0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x0, 0x0}), - std::vector({0x1, 0x2, 0x3, 0x4, 0x5, 0x6})); + ASSERT_EQ(LeScanningReassembler::TrimAdvertisingData({0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x0, 0x0}), + std::vector({0x1, 0x2, 0x3, 0x4, 0x5, 0x6})); // TrimAdvertisingData should remove overflowing entries. - ASSERT_EQ( - LeScanningReassembler::TrimAdvertisingData({0x1, 0x2, 0x3, 0x4, 0x5}), - std::vector({0x1, 0x2})); + ASSERT_EQ(LeScanningReassembler::TrimAdvertisingData({0x1, 0x2, 0x3, 0x4, 0x5}), + std::vector({0x1, 0x2})); } TEST_F(LeScanningReassemblerTest, non_scannable_legacy_advertising) { // Test non scannable legacy advertising. - ASSERT_EQ( - reassembler_ - .ProcessAdvertisingReport( - kLegacy | kComplete, - (uint8_t)AddressType::PUBLIC_DEVICE_ADDRESS, - kTestAddress, - kSidNotPresent, - {0x1, 0x2}) - .value() - .data, - std::vector({0x1, 0x2})); + ASSERT_EQ(reassembler_ + .ProcessAdvertisingReport(kLegacy | kComplete, + (uint8_t)AddressType::PUBLIC_DEVICE_ADDRESS, + kTestAddress, kSidNotPresent, {0x1, 0x2}) + .value() + .data, + std::vector({0x1, 0x2})); } TEST_F(LeScanningReassemblerTest, scannable_non_connectable_legacy_advertising) { // Test scannable legacy advertising with well formed advertising and // scan response payload. ASSERT_FALSE(reassembler_ - .ProcessAdvertisingReport( - kLegacy | kScannable | kComplete, - (uint8_t)AddressType::PUBLIC_DEVICE_ADDRESS, - kTestAddress, - kSidNotPresent, - {0x1, 0x2}) - .has_value()); - - auto processed_report = reassembler_.ProcessAdvertisingReport( - kLegacy | kScannable | kScanResponse | kComplete, - (uint8_t)AddressType::PUBLIC_DEVICE_ADDRESS, - kTestAddress, - kSidNotPresent, - {0x3, 0x4, 0x5, 0x6}); + .ProcessAdvertisingReport(kLegacy | kScannable | kComplete, + (uint8_t)AddressType::PUBLIC_DEVICE_ADDRESS, + kTestAddress, kSidNotPresent, {0x1, 0x2}) + .has_value()); + + auto processed_report = + reassembler_.ProcessAdvertisingReport(kLegacy | kScannable | kScanResponse | kComplete, + (uint8_t)AddressType::PUBLIC_DEVICE_ADDRESS, + kTestAddress, kSidNotPresent, {0x3, 0x4, 0x5, 0x6}); ASSERT_TRUE(processed_report.has_value()); ASSERT_EQ(processed_report.value().extended_event_type, kLegacy | kScannable | kScanResponse); ASSERT_EQ(processed_report.value().data, std::vector({0x1, 0x2, 0x3, 0x4, 0x5, 0x6})); @@ -108,47 +96,34 @@ TEST_F(LeScanningReassemblerTest, scannable_non_connectable_legacy_advertising) // Test scannable legacy advertising with padding after the // advertising and scan response data. ASSERT_FALSE(reassembler_ - .ProcessAdvertisingReport( - kLegacy | kScannable | kComplete, - (uint8_t)AddressType::PUBLIC_DEVICE_ADDRESS, - kTestAddress, - kSidNotPresent, - {0x1, 0x2, 0x0, 0x0}) - .has_value()); - - ASSERT_EQ( - reassembler_ - .ProcessAdvertisingReport( - kLegacy | kScannable | kScanResponse | kComplete, - (uint8_t)AddressType::PUBLIC_DEVICE_ADDRESS, - kTestAddress, - kSidNotPresent, - {0x3, 0x4, 0x5, 0x6, 0x0, 0x0}) - .value() - .data, - std::vector({0x1, 0x2, 0x3, 0x4, 0x5, 0x6})); + .ProcessAdvertisingReport(kLegacy | kScannable | kComplete, + (uint8_t)AddressType::PUBLIC_DEVICE_ADDRESS, + kTestAddress, kSidNotPresent, {0x1, 0x2, 0x0, 0x0}) + .has_value()); + + ASSERT_EQ(reassembler_ + .ProcessAdvertisingReport(kLegacy | kScannable | kScanResponse | kComplete, + (uint8_t)AddressType::PUBLIC_DEVICE_ADDRESS, + kTestAddress, kSidNotPresent, + {0x3, 0x4, 0x5, 0x6, 0x0, 0x0}) + .value() + .data, + std::vector({0x1, 0x2, 0x3, 0x4, 0x5, 0x6})); } TEST_F(LeScanningReassemblerTest, scannable_connectable_legacy_advertising) { ASSERT_FALSE(reassembler_ - .ProcessAdvertisingReport( - kLegacy | kScannable | kConnectable, - (uint8_t)AddressType::PUBLIC_DEVICE_ADDRESS, - kTestAddress, - kSidNotPresent, - {0x1, 0x2}) - .has_value()); + .ProcessAdvertisingReport(kLegacy | kScannable | kConnectable, + (uint8_t)AddressType::PUBLIC_DEVICE_ADDRESS, + kTestAddress, kSidNotPresent, {0x1, 0x2}) + .has_value()); auto processed_report = reassembler_.ProcessAdvertisingReport( - kLegacy | kScannable | kScanResponse, - (uint8_t)AddressType::PUBLIC_DEVICE_ADDRESS, - kTestAddress, - kSidNotPresent, - {0x3, 0x4, 0x5, 0x6}); + kLegacy | kScannable | kScanResponse, (uint8_t)AddressType::PUBLIC_DEVICE_ADDRESS, + kTestAddress, kSidNotPresent, {0x3, 0x4, 0x5, 0x6}); ASSERT_TRUE(processed_report.has_value()); - ASSERT_EQ( - processed_report.value().extended_event_type, - kLegacy | kScannable | kScanResponse | kConnectable); + ASSERT_EQ(processed_report.value().extended_event_type, + kLegacy | kScannable | kScanResponse | kConnectable); ASSERT_EQ(processed_report.value().data, std::vector({0x1, 0x2, 0x3, 0x4, 0x5, 0x6})); } @@ -156,20 +131,14 @@ TEST_F(LeScanningReassemblerTest, non_scannable_extended_advertising) { // Test fragmented non scannable extended advertising. // The split may occur in the middle of a GAP entry. ASSERT_FALSE(reassembler_ - .ProcessAdvertisingReport( - kContinuation, - (uint8_t)AddressType::PUBLIC_DEVICE_ADDRESS, - kTestAddress, - kSidNotPresent, - {0x1, 0x2, 0x3}) - .has_value()); + .ProcessAdvertisingReport(kContinuation, + (uint8_t)AddressType::PUBLIC_DEVICE_ADDRESS, + kTestAddress, kSidNotPresent, {0x1, 0x2, 0x3}) + .has_value()); auto processed_report = reassembler_.ProcessAdvertisingReport( - kComplete, - (uint8_t)AddressType::PUBLIC_DEVICE_ADDRESS, - kTestAddress, - kSidNotPresent, - {0x4, 0x5, 0x6}); + kComplete, (uint8_t)AddressType::PUBLIC_DEVICE_ADDRESS, kTestAddress, kSidNotPresent, + {0x4, 0x5, 0x6}); ASSERT_TRUE(processed_report.has_value()); ASSERT_EQ(processed_report.value().extended_event_type, kComplete); ASSERT_EQ(processed_report.value().data, std::vector({0x1, 0x2, 0x3, 0x4, 0x5, 0x6})); @@ -177,48 +146,35 @@ TEST_F(LeScanningReassemblerTest, non_scannable_extended_advertising) { // Test fragmented and truncated non scannable extended advertising. // The split may occur in the middle of a GAP entry. ASSERT_FALSE(reassembler_ - .ProcessAdvertisingReport( - kContinuation, - (uint8_t)AddressType::PUBLIC_DEVICE_ADDRESS, - kTestAddress, - kSidNotPresent, - {0x1, 0x2, 0x3}) - .has_value()); + .ProcessAdvertisingReport(kContinuation, + (uint8_t)AddressType::PUBLIC_DEVICE_ADDRESS, + kTestAddress, kSidNotPresent, {0x1, 0x2, 0x3}) + .has_value()); ASSERT_EQ( - reassembler_ - .ProcessAdvertisingReport( - kTruncated, - (uint8_t)AddressType::PUBLIC_DEVICE_ADDRESS, - kTestAddress, - kSidNotPresent, - {0x4, 0x5, 0x6, 0x7}) - .value() - .data, - std::vector({0x1, 0x2, 0x3, 0x4, 0x5, 0x6})); + reassembler_ + .ProcessAdvertisingReport(kTruncated, (uint8_t)AddressType::PUBLIC_DEVICE_ADDRESS, + kTestAddress, kSidNotPresent, {0x4, 0x5, 0x6, 0x7}) + .value() + .data, + std::vector({0x1, 0x2, 0x3, 0x4, 0x5, 0x6})); // Test fragmented and truncated anonymous, non scannable // extended advertising. The split may occur in the middle of a GAP entry. ASSERT_FALSE(reassembler_ - .ProcessAdvertisingReport( - kContinuation, - (uint8_t)DirectAdvertisingAddressType::NO_ADDRESS_PROVIDED, - Address::kEmpty, - kSidNotPresent, - {0x1, 0x2, 0x3}) - .has_value()); - - ASSERT_EQ( - reassembler_ - .ProcessAdvertisingReport( - kTruncated, - (uint8_t)DirectAdvertisingAddressType::NO_ADDRESS_PROVIDED, - Address::kEmpty, - kSidNotPresent, - {0x4, 0x5, 0x6, 0x7}) - .value() - .data, - std::vector({0x1, 0x2, 0x3, 0x4, 0x5, 0x6})); + .ProcessAdvertisingReport( + kContinuation, + (uint8_t)DirectAdvertisingAddressType::NO_ADDRESS_PROVIDED, + Address::kEmpty, kSidNotPresent, {0x1, 0x2, 0x3}) + .has_value()); + + ASSERT_EQ(reassembler_ + .ProcessAdvertisingReport( + kTruncated, (uint8_t)DirectAdvertisingAddressType::NO_ADDRESS_PROVIDED, + Address::kEmpty, kSidNotPresent, {0x4, 0x5, 0x6, 0x7}) + .value() + .data, + std::vector({0x1, 0x2, 0x3, 0x4, 0x5, 0x6})); } TEST_F(LeScanningReassemblerTest, scannable_extended_advertising) { @@ -226,183 +182,137 @@ TEST_F(LeScanningReassemblerTest, scannable_extended_advertising) { // The split may occur in the middle of a GAP entry. // Padding may occur at the end of the advertising data. ASSERT_FALSE(reassembler_ - .ProcessAdvertisingReport( - kScannable | kContinuation, - (uint8_t)AddressType::PUBLIC_DEVICE_ADDRESS, - kTestAddress, - kSidNotPresent, - {0x1, 0x2, 0x3}) - .has_value()); + .ProcessAdvertisingReport(kScannable | kContinuation, + (uint8_t)AddressType::PUBLIC_DEVICE_ADDRESS, + kTestAddress, kSidNotPresent, {0x1, 0x2, 0x3}) + .has_value()); ASSERT_FALSE(reassembler_ - .ProcessAdvertisingReport( - kScannable | kComplete, - (uint8_t)AddressType::PUBLIC_DEVICE_ADDRESS, - kTestAddress, - kSidNotPresent, - {0x4, 0x5, 0x6, 0x0, 0x0}) - .has_value()); + .ProcessAdvertisingReport( + kScannable | kComplete, (uint8_t)AddressType::PUBLIC_DEVICE_ADDRESS, + kTestAddress, kSidNotPresent, {0x4, 0x5, 0x6, 0x0, 0x0}) + .has_value()); ASSERT_FALSE(reassembler_ - .ProcessAdvertisingReport( - kContinuation, - (uint8_t)AddressType::PUBLIC_DEVICE_ADDRESS, - kTestAddress, - kSidNotPresent, - {0x7, 0x8, 0x9, 0xa}) - .has_value()); + .ProcessAdvertisingReport(kContinuation, + (uint8_t)AddressType::PUBLIC_DEVICE_ADDRESS, + kTestAddress, kSidNotPresent, {0x7, 0x8, 0x9, 0xa}) + .has_value()); ASSERT_EQ( - reassembler_ - .ProcessAdvertisingReport( - kTruncated, - (uint8_t)AddressType::PUBLIC_DEVICE_ADDRESS, - kTestAddress, - kSidNotPresent, - {0xb, 0xc, 0xd, 0xe, 0x0}) - .value() - .data, - std::vector({0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe})); + reassembler_ + .ProcessAdvertisingReport(kTruncated, (uint8_t)AddressType::PUBLIC_DEVICE_ADDRESS, + kTestAddress, kSidNotPresent, {0xb, 0xc, 0xd, 0xe, 0x0}) + .value() + .data, + std::vector( + {0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe})); } TEST_F(LeScanningReassemblerTest, ignore_scan_responses) { // Scan response without advertising data are ignored. ASSERT_FALSE(reassembler_ - .ProcessAdvertisingReport( - kScannable | kScanResponse | kComplete, - (uint8_t)AddressType::PUBLIC_DEVICE_ADDRESS, - kTestAddress, - kSidNotPresent, - {0x1, 0x2}) - .has_value()); + .ProcessAdvertisingReport(kScannable | kScanResponse | kComplete, + (uint8_t)AddressType::PUBLIC_DEVICE_ADDRESS, + kTestAddress, kSidNotPresent, {0x1, 0x2}) + .has_value()); ASSERT_EQ( - reassembler_ - .ProcessAdvertisingReport( - kComplete, - (uint8_t)AddressType::PUBLIC_DEVICE_ADDRESS, - kTestAddress, - kSidNotPresent, - {0x1, 0x2}) - .value() - .data, - std::vector({0x1, 0x2})); + reassembler_ + .ProcessAdvertisingReport(kComplete, (uint8_t)AddressType::PUBLIC_DEVICE_ADDRESS, + kTestAddress, kSidNotPresent, {0x1, 0x2}) + .value() + .data, + std::vector({0x1, 0x2})); // The option ignore_scan_responses forces scan responses to be dropped. reassembler_.SetIgnoreScanResponses(true); - ASSERT_EQ( - reassembler_ - .ProcessAdvertisingReport( - kScannable | kComplete, - (uint8_t)AddressType::PUBLIC_DEVICE_ADDRESS, - kTestAddress, - kSidNotPresent, - {0x1, 0x2}) - .value() - .data, - std::vector({0x1, 0x2})); + ASSERT_EQ(reassembler_ + .ProcessAdvertisingReport(kScannable | kComplete, + (uint8_t)AddressType::PUBLIC_DEVICE_ADDRESS, + kTestAddress, kSidNotPresent, {0x1, 0x2}) + .value() + .data, + std::vector({0x1, 0x2})); } TEST_F(LeScanningReassemblerTest, interleaved_advertising) { // The reassembler must disambiguate advertising events by address, // address type, and SID. ASSERT_FALSE(reassembler_ - .ProcessAdvertisingReport( - kContinuation, - (uint8_t)AddressType::PUBLIC_DEVICE_ADDRESS, - kTestAddress, - kSidNotPresent, - {0x2, 0x0}) - .has_value()); + .ProcessAdvertisingReport(kContinuation, + (uint8_t)AddressType::PUBLIC_DEVICE_ADDRESS, + kTestAddress, kSidNotPresent, {0x2, 0x0}) + .has_value()); ASSERT_FALSE(reassembler_ - .ProcessAdvertisingReport( - kContinuation, - (uint8_t)AddressType::RANDOM_DEVICE_ADDRESS, - kTestAddress, - kSidNotPresent, - {0x2, 0x1}) - .has_value()); + .ProcessAdvertisingReport(kContinuation, + (uint8_t)AddressType::RANDOM_DEVICE_ADDRESS, + kTestAddress, kSidNotPresent, {0x2, 0x1}) + .has_value()); ASSERT_FALSE(reassembler_ - .ProcessAdvertisingReport( - kContinuation, - (uint8_t)AddressType::PUBLIC_DEVICE_ADDRESS, - kTestAddress, - 0x1, - {0x2, 0x2}) - .has_value()); + .ProcessAdvertisingReport(kContinuation, + (uint8_t)AddressType::PUBLIC_DEVICE_ADDRESS, + kTestAddress, 0x1, {0x2, 0x2}) + .has_value()); ASSERT_FALSE(reassembler_ - .ProcessAdvertisingReport( - kContinuation, - (uint8_t)DirectAdvertisingAddressType::NO_ADDRESS_PROVIDED, - Address::kEmpty, - 0x1, - {0x2, 0x3}) - .has_value()); - - ASSERT_EQ( - reassembler_ - .ProcessAdvertisingReport( - kComplete, - (uint8_t)AddressType::PUBLIC_DEVICE_ADDRESS, - kTestAddress, - kSidNotPresent, - {0x0}) - .value() - .data, - std::vector({0x2, 0x0, 0x0})); + .ProcessAdvertisingReport( + kContinuation, + (uint8_t)DirectAdvertisingAddressType::NO_ADDRESS_PROVIDED, + Address::kEmpty, 0x1, {0x2, 0x3}) + .has_value()); ASSERT_EQ( - reassembler_ - .ProcessAdvertisingReport( - kComplete, - (uint8_t)AddressType::RANDOM_DEVICE_ADDRESS, - kTestAddress, - kSidNotPresent, - {0x1}) - .value() - .data, - std::vector({0x2, 0x1, 0x1})); + reassembler_ + .ProcessAdvertisingReport(kComplete, (uint8_t)AddressType::PUBLIC_DEVICE_ADDRESS, + kTestAddress, kSidNotPresent, {0x0}) + .value() + .data, + std::vector({0x2, 0x0, 0x0})); ASSERT_EQ( - reassembler_ - .ProcessAdvertisingReport( - kComplete, (uint8_t)AddressType::PUBLIC_DEVICE_ADDRESS, kTestAddress, 0x1, {0x2}) - .value() - .data, - std::vector({0x2, 0x2, 0x2})); + reassembler_ + .ProcessAdvertisingReport(kComplete, (uint8_t)AddressType::RANDOM_DEVICE_ADDRESS, + kTestAddress, kSidNotPresent, {0x1}) + .value() + .data, + std::vector({0x2, 0x1, 0x1})); ASSERT_EQ( - reassembler_ - .ProcessAdvertisingReport( - kComplete, - (uint8_t)DirectAdvertisingAddressType::NO_ADDRESS_PROVIDED, - Address::kEmpty, - 0x1, - {0x3}) - .value() - .data, - std::vector({0x2, 0x3, 0x3})); + reassembler_ + .ProcessAdvertisingReport(kComplete, (uint8_t)AddressType::PUBLIC_DEVICE_ADDRESS, + kTestAddress, 0x1, {0x2}) + .value() + .data, + std::vector({0x2, 0x2, 0x2})); + + ASSERT_EQ(reassembler_ + .ProcessAdvertisingReport( + kComplete, (uint8_t)DirectAdvertisingAddressType::NO_ADDRESS_PROVIDED, + Address::kEmpty, 0x1, {0x3}) + .value() + .data, + std::vector({0x2, 0x3, 0x3})); } TEST_F(LeScanningReassemblerTest, periodic_advertising) { // Test periodic advertising. - ASSERT_FALSE( - reassembler_ - .ProcessPeriodicAdvertisingReport(kTestSyncHandle1, DataStatus::CONTINUING, {0x1, 0x2}) - .has_value()); + ASSERT_FALSE(reassembler_ + .ProcessPeriodicAdvertisingReport(kTestSyncHandle1, DataStatus::CONTINUING, + {0x1, 0x2}) + .has_value()); auto processed_report = reassembler_.ProcessPeriodicAdvertisingReport( - kTestSyncHandle1, DataStatus::COMPLETE, {0x3, 0x4, 0x5, 0x6}); + kTestSyncHandle1, DataStatus::COMPLETE, {0x3, 0x4, 0x5, 0x6}); ASSERT_TRUE(processed_report.has_value()); ASSERT_EQ(processed_report.value(), std::vector({0x1, 0x2, 0x3, 0x4, 0x5, 0x6})); // Test periodic advertising with the same handle // to validate that the context was cleared. processed_report = reassembler_.ProcessPeriodicAdvertisingReport( - kTestSyncHandle1, DataStatus::COMPLETE, {0x4, 0xa0, 0xb0, 0xc0, 0xd0}); + kTestSyncHandle1, DataStatus::COMPLETE, {0x4, 0xa0, 0xb0, 0xc0, 0xd0}); ASSERT_TRUE(processed_report.has_value()); ASSERT_EQ(processed_report.value(), std::vector({0x4, 0xa0, 0xb0, 0xc0, 0xd0})); } @@ -410,25 +320,25 @@ TEST_F(LeScanningReassemblerTest, periodic_advertising) { TEST_F(LeScanningReassemblerTest, interleaved_periodic_advertising) { // The reassembler must disambiguate advertising events by address, // address type, and SID. - ASSERT_FALSE( - reassembler_ - .ProcessPeriodicAdvertisingReport(kTestSyncHandle1, DataStatus::CONTINUING, {0x2, 0x0}) - .has_value()); - - ASSERT_FALSE( - reassembler_ - .ProcessPeriodicAdvertisingReport(kTestSyncHandle2, DataStatus::CONTINUING, {0x2, 0x1}) - .has_value()); - - ASSERT_EQ( - reassembler_.ProcessPeriodicAdvertisingReport(kTestSyncHandle1, DataStatus::COMPLETE, {0x0}) - .value(), - std::vector({0x2, 0x0, 0x0})); + ASSERT_FALSE(reassembler_ + .ProcessPeriodicAdvertisingReport(kTestSyncHandle1, DataStatus::CONTINUING, + {0x2, 0x0}) + .has_value()); - ASSERT_EQ( - reassembler_.ProcessPeriodicAdvertisingReport(kTestSyncHandle2, DataStatus::COMPLETE, {0x1}) - .value(), - std::vector({0x2, 0x1, 0x1})); + ASSERT_FALSE(reassembler_ + .ProcessPeriodicAdvertisingReport(kTestSyncHandle2, DataStatus::CONTINUING, + {0x2, 0x1}) + .has_value()); + + ASSERT_EQ(reassembler_ + .ProcessPeriodicAdvertisingReport(kTestSyncHandle1, DataStatus::COMPLETE, {0x0}) + .value(), + std::vector({0x2, 0x0, 0x0})); + + ASSERT_EQ(reassembler_ + .ProcessPeriodicAdvertisingReport(kTestSyncHandle2, DataStatus::COMPLETE, {0x1}) + .value(), + std::vector({0x2, 0x1, 0x1})); } } // namespace bluetooth::hci diff --git a/system/gd/hci/le_security_interface.h b/system/gd/hci/le_security_interface.h index da1e62d7b1e..93a2122d8f3 100644 --- a/system/gd/hci/le_security_interface.h +++ b/system/gd/hci/le_security_interface.h @@ -23,9 +23,9 @@ namespace bluetooth { namespace hci { constexpr hci::SubeventCode LeSecurityEvents[] = { - hci::SubeventCode::LONG_TERM_KEY_REQUEST, - hci::SubeventCode::READ_LOCAL_P256_PUBLIC_KEY_COMPLETE, - hci::SubeventCode::GENERATE_DHKEY_COMPLETE, + hci::SubeventCode::LONG_TERM_KEY_REQUEST, + hci::SubeventCode::READ_LOCAL_P256_PUBLIC_KEY_COMPLETE, + hci::SubeventCode::GENERATE_DHKEY_COMPLETE, }; typedef CommandInterface LeSecurityInterface; diff --git a/system/gd/hci/link_key.cc b/system/gd/hci/link_key.cc index 98074bbb170..2a9204f6901 100644 --- a/system/gd/hci/link_key.cc +++ b/system/gd/hci/link_key.cc @@ -19,7 +19,7 @@ namespace bluetooth { namespace hci { -const LinkKey kExampleLinkKey{ - {0x4C, 0x68, 0x38, 0x41, 0x39, 0xf5, 0x74, 0xd8, 0x36, 0xbc, 0xf3, 0x4e, 0x9d, 0xfb, 0x01, 0xbf}}; +const LinkKey kExampleLinkKey{{0x4C, 0x68, 0x38, 0x41, 0x39, 0xf5, 0x74, 0xd8, 0x36, 0xbc, 0xf3, + 0x4e, 0x9d, 0xfb, 0x01, 0xbf}}; } } // namespace bluetooth \ No newline at end of file diff --git a/system/gd/hci/msft.cc b/system/gd/hci/msft.cc index 167bbf463e1..e663438952e 100644 --- a/system/gd/hci/msft.cc +++ b/system/gd/hci/msft.cc @@ -38,10 +38,11 @@ struct Msft { std::vector prefix; }; -const ModuleFactory MsftExtensionManager::Factory = ModuleFactory([]() { return new MsftExtensionManager(); }); +const ModuleFactory MsftExtensionManager::Factory = + ModuleFactory([]() { return new MsftExtensionManager(); }); struct MsftExtensionManager::impl { - impl(Module* module) : module_(module){}; + impl(Module* module) : module_(module) {} ~impl() {} @@ -67,13 +68,11 @@ struct MsftExtensionManager::impl { * derive the vendor prefix as well as other supported features. */ hci_layer_->EnqueueCommand( - MsftReadSupportedFeaturesBuilder::Create(static_cast(msft_.opcode.value())), - module_handler_->BindOnceOn(this, &impl::on_msft_read_supported_features_complete)); + MsftReadSupportedFeaturesBuilder::Create(static_cast(msft_.opcode.value())), + module_handler_->BindOnceOn(this, &impl::on_msft_read_supported_features_complete)); } - void stop() { - log::info("MsftExtensionManager stop()"); - } + void stop() { log::info("MsftExtensionManager stop()"); } void handle_rssi_event(MsftRssiEventPayloadView /* view */) { log::warn("The Microsoft MSFT_RSSI_EVENT is not supported yet."); @@ -106,7 +105,7 @@ struct MsftExtensionManager::impl { } auto msft_view = MsftEventPayloadView::Create( - payload.GetLittleEndianSubview(msft_.prefix.size() - 1, payload.size())); + payload.GetLittleEndianSubview(msft_.prefix.size() - 1, payload.size())); log::assert_that(msft_view.IsValid(), "assert failed: msft_view.IsValid()"); MsftEventCode ev_code = msft_view.GetMsftEventCode(); @@ -124,10 +123,14 @@ struct MsftExtensionManager::impl { } bool supports_msft_extensions() { - if (msft_.opcode.has_value()) return true; + if (msft_.opcode.has_value()) { + return true; + } uint16_t opcode = hal_->getMsftOpcode(); - if (opcode == 0) return false; + if (opcode == 0) { + return false; + } msft_.opcode = opcode; log::info("MSFT opcode 0x{:04x}", msft_.opcode.value()); @@ -152,15 +155,11 @@ struct MsftExtensionManager::impl { Address addr; Address::FromString(monitor.addr_info.bd_addr.ToString(), addr); hci_layer_->EnqueueCommand( - MsftLeMonitorAdvConditionAddressBuilder::Create( - static_cast(msft_.opcode.value()), - monitor.rssi_threshold_high, - monitor.rssi_threshold_low, - monitor.rssi_threshold_low_time_interval, - monitor.rssi_sampling_period, - monitor.addr_info.addr_type, - addr), - module_handler_->BindOnceOn(this, &impl::on_msft_adv_monitor_add_complete)); + MsftLeMonitorAdvConditionAddressBuilder::Create( + static_cast(msft_.opcode.value()), monitor.rssi_threshold_high, + monitor.rssi_threshold_low, monitor.rssi_threshold_low_time_interval, + monitor.rssi_sampling_period, monitor.addr_info.addr_type, addr), + module_handler_->BindOnceOn(this, &impl::on_msft_adv_monitor_add_complete)); return; } } @@ -184,14 +183,11 @@ struct MsftExtensionManager::impl { msft_adv_monitor_add_cb_ = cb; hci_layer_->EnqueueCommand( - MsftLeMonitorAdvConditionPatternsBuilder::Create( - static_cast(msft_.opcode.value()), - monitor.rssi_threshold_high, - monitor.rssi_threshold_low, - monitor.rssi_threshold_low_time_interval, - monitor.rssi_sampling_period, - patterns), - module_handler_->BindOnceOn(this, &impl::on_msft_adv_monitor_add_complete)); + MsftLeMonitorAdvConditionPatternsBuilder::Create( + static_cast(msft_.opcode.value()), monitor.rssi_threshold_high, + monitor.rssi_threshold_low, monitor.rssi_threshold_low_time_interval, + monitor.rssi_sampling_period, patterns), + module_handler_->BindOnceOn(this, &impl::on_msft_adv_monitor_add_complete)); } void msft_adv_monitor_remove(uint8_t monitor_handle, MsftAdvMonitorRemoveCallback cb) { @@ -202,9 +198,9 @@ struct MsftExtensionManager::impl { msft_adv_monitor_remove_cb_ = cb; hci_layer_->EnqueueCommand( - MsftLeCancelMonitorAdvBuilder::Create( - static_cast(msft_.opcode.value()), monitor_handle), - module_handler_->BindOnceOn(this, &impl::on_msft_adv_monitor_remove_complete)); + MsftLeCancelMonitorAdvBuilder::Create(static_cast(msft_.opcode.value()), + monitor_handle), + module_handler_->BindOnceOn(this, &impl::on_msft_adv_monitor_remove_complete)); } void msft_adv_monitor_enable(bool enable, MsftAdvMonitorEnableCallback cb) { @@ -215,13 +211,12 @@ struct MsftExtensionManager::impl { msft_adv_monitor_enable_cb_ = cb; hci_layer_->EnqueueCommand( - MsftLeSetAdvFilterEnableBuilder::Create(static_cast(msft_.opcode.value()), enable), - module_handler_->BindOnceOn(this, &impl::on_msft_adv_monitor_enable_complete)); + MsftLeSetAdvFilterEnableBuilder::Create(static_cast(msft_.opcode.value()), + enable), + module_handler_->BindOnceOn(this, &impl::on_msft_adv_monitor_enable_complete)); } - void set_scanning_callback(ScanningCallback* callbacks) { - scanning_callbacks_ = callbacks; - } + void set_scanning_callback(ScanningCallback* callbacks) { scanning_callbacks_ = callbacks; } /* * Get the event prefix from the packet for configuring MSFT's @@ -229,7 +224,8 @@ struct MsftExtensionManager::impl { */ void on_msft_read_supported_features_complete(CommandCompleteView view) { log::assert_that(view.IsValid(), "assert failed: view.IsValid()"); - auto status_view = MsftReadSupportedFeaturesCommandCompleteView::Create(MsftCommandCompleteView::Create(view)); + auto status_view = MsftReadSupportedFeaturesCommandCompleteView::Create( + MsftCommandCompleteView::Create(view)); log::assert_that(status_view.IsValid(), "assert failed: status_view.IsValid()"); if (status_view.GetStatus() != ErrorCode::SUCCESS) { @@ -249,8 +245,9 @@ struct MsftExtensionManager::impl { auto prefix = status_view.GetPrefix(); msft_.prefix.assign(prefix.begin(), prefix.end()); - if (prefix.size() > kMsftEventPrefixLengthMax) + if (prefix.size() > kMsftEventPrefixLengthMax) { log::warn("The MSFT prefix length {} is too large", (unsigned int)prefix.size()); + } log::info("MSFT features 0x{:016x} prefix length {}", msft_.features, prefix.size()); @@ -261,14 +258,14 @@ struct MsftExtensionManager::impl { // because each vendor controller should ensure that the first octet // is unique within the vendor's events. hci_layer_->RegisterVendorSpecificEventHandler( - static_cast(msft_.prefix[0]), - module_handler_->BindOn(this, &impl::handle_msft_events)); + static_cast(msft_.prefix[0]), + module_handler_->BindOn(this, &impl::handle_msft_events)); } void on_msft_adv_monitor_add_complete(CommandCompleteView view) { log::assert_that(view.IsValid(), "assert failed: view.IsValid()"); auto status_view = - MsftLeMonitorAdvCommandCompleteView::Create(MsftCommandCompleteView::Create(view)); + MsftLeMonitorAdvCommandCompleteView::Create(MsftCommandCompleteView::Create(view)); log::assert_that(status_view.IsValid(), "assert failed: status_view.IsValid()"); MsftSubcommandOpcode sub_opcode = status_view.GetSubcommandOpcode(); @@ -282,8 +279,8 @@ struct MsftExtensionManager::impl { void on_msft_adv_monitor_remove_complete(CommandCompleteView view) { log::assert_that(view.IsValid(), "assert failed: view.IsValid()"); - auto status_view = - MsftLeCancelMonitorAdvCommandCompleteView::Create(MsftCommandCompleteView::Create(view)); + auto status_view = MsftLeCancelMonitorAdvCommandCompleteView::Create( + MsftCommandCompleteView::Create(view)); log::assert_that(status_view.IsValid(), "assert failed: status_view.IsValid()"); MsftSubcommandOpcode sub_opcode = status_view.GetSubcommandOpcode(); @@ -297,8 +294,8 @@ struct MsftExtensionManager::impl { void on_msft_adv_monitor_enable_complete(CommandCompleteView view) { log::assert_that(view.IsValid(), "assert failed: view.IsValid()"); - auto status_view = - MsftLeSetAdvFilterEnableCommandCompleteView::Create(MsftCommandCompleteView::Create(view)); + auto status_view = MsftLeSetAdvFilterEnableCommandCompleteView::Create( + MsftCommandCompleteView::Create(view)); log::assert_that(status_view.IsValid(), "assert failed: status_view.IsValid()"); MsftSubcommandOpcode sub_opcode = status_view.GetSubcommandOpcode(); @@ -335,25 +332,19 @@ void MsftExtensionManager::Start() { pimpl_->start(GetHandler(), GetDependency(), GetDependency()); } -void MsftExtensionManager::Stop() { - pimpl_->stop(); -} +void MsftExtensionManager::Stop() { pimpl_->stop(); } -std::string MsftExtensionManager::ToString() const { - return "Microsoft Extension Manager"; -} +std::string MsftExtensionManager::ToString() const { return "Microsoft Extension Manager"; } -bool MsftExtensionManager::SupportsMsftExtensions() { - return pimpl_->supports_msft_extensions(); -} +bool MsftExtensionManager::SupportsMsftExtensions() { return pimpl_->supports_msft_extensions(); } -void MsftExtensionManager::MsftAdvMonitorAdd( - const MsftAdvMonitor& monitor, MsftAdvMonitorAddCallback cb) { +void MsftExtensionManager::MsftAdvMonitorAdd(const MsftAdvMonitor& monitor, + MsftAdvMonitorAddCallback cb) { CallOn(pimpl_.get(), &impl::msft_adv_monitor_add, monitor, cb); } -void MsftExtensionManager::MsftAdvMonitorRemove( - uint8_t monitor_handle, MsftAdvMonitorRemoveCallback cb) { +void MsftExtensionManager::MsftAdvMonitorRemove(uint8_t monitor_handle, + MsftAdvMonitorRemoveCallback cb) { CallOn(pimpl_.get(), &impl::msft_adv_monitor_remove, monitor_handle, cb); } diff --git a/system/gd/hci/msft.h b/system/gd/hci/msft.h index 7debd274b0c..5e31a6b345a 100644 --- a/system/gd/hci/msft.h +++ b/system/gd/hci/msft.h @@ -26,14 +26,14 @@ namespace bluetooth { namespace hci { class MsftExtensionManager : public bluetooth::Module { - public: +public: MsftExtensionManager(); MsftExtensionManager(const MsftExtensionManager&) = delete; MsftExtensionManager& operator=(const MsftExtensionManager&) = delete; using MsftAdvMonitorAddCallback = - base::Callback; + base::Callback; using MsftAdvMonitorRemoveCallback = base::Callback; using MsftAdvMonitorEnableCallback = base::Callback; @@ -45,7 +45,7 @@ class MsftExtensionManager : public bluetooth::Module { static const ModuleFactory Factory; - protected: +protected: void ListDependencies(ModuleList* list) const override; void Start() override; @@ -54,7 +54,7 @@ class MsftExtensionManager : public bluetooth::Module { std::string ToString() const override; - private: +private: struct impl; std::unique_ptr pimpl_; }; diff --git a/system/gd/hci/remote_name_request.cc b/system/gd/hci/remote_name_request.cc index 3df4ae3268b..2f703feca96 100644 --- a/system/gd/hci/remote_name_request.cc +++ b/system/gd/hci/remote_name_request.cc @@ -27,7 +27,7 @@ namespace bluetooth { namespace hci { struct RemoteNameRequestModule::impl { - public: +public: impl(const RemoteNameRequestModule& module) : module_(module) {} void Start() { @@ -37,12 +37,13 @@ struct RemoteNameRequestModule::impl { handler_ = module_.GetHandler(); hci_layer_->RegisterEventHandler( - EventCode::REMOTE_HOST_SUPPORTED_FEATURES_NOTIFICATION, - handler_->BindOn( - this, &RemoteNameRequestModule::impl::on_remote_host_supported_features_notification)); + EventCode::REMOTE_HOST_SUPPORTED_FEATURES_NOTIFICATION, + handler_->BindOn(this, &RemoteNameRequestModule::impl:: + on_remote_host_supported_features_notification)); hci_layer_->RegisterEventHandler( - EventCode::REMOTE_NAME_REQUEST_COMPLETE, - handler_->BindOn(this, &RemoteNameRequestModule::impl::on_remote_name_request_complete)); + EventCode::REMOTE_NAME_REQUEST_COMPLETE, + handler_->BindOn(this, + &RemoteNameRequestModule::impl::on_remote_name_request_complete)); } void Stop() { @@ -52,83 +53,78 @@ struct RemoteNameRequestModule::impl { } void StartRemoteNameRequest( - Address address, - std::unique_ptr request, - CompletionCallback on_completion, - RemoteHostSupportedFeaturesCallback on_remote_host_supported_features_notification, - RemoteNameCallback on_remote_name_complete) { + Address address, std::unique_ptr request, + CompletionCallback on_completion, + RemoteHostSupportedFeaturesCallback on_remote_host_supported_features_notification, + RemoteNameCallback on_remote_name_complete) { log::info("Enqueuing remote name request to {}", address.ToRedactedStringForLogging()); // This callback needs to be shared between the *start* callback and the *cancel_completed* // callback, so we refcount it for safety. But since the scheduler guarantees that exactly one // of these callbacks will be invokes, this is safe. auto on_remote_name_complete_ptr = - std::make_shared(std::move(on_remote_name_complete)); + std::make_shared(std::move(on_remote_name_complete)); acl_scheduler_->EnqueueRemoteNameRequest( - address, - handler_->BindOnceOn( - this, - &impl::actually_start_remote_name_request, address, - std::move(request), - std::move(on_completion), - std::move(on_remote_host_supported_features_notification), - on_remote_name_complete_ptr), - handler_->BindOnce( - [&](Address address, std::shared_ptr on_remote_name_complete_ptr) { - log::info( - "Dequeued remote name request to {} since it was cancelled", - address.ToRedactedStringForLogging()); - (*on_remote_name_complete_ptr)(ErrorCode::PAGE_TIMEOUT, {}); - }, - address, - on_remote_name_complete_ptr)); + handler_->BindOnceOn(this, &impl::actually_start_remote_name_request, address, + std::move(request), std::move(on_completion), + std::move(on_remote_host_supported_features_notification), + on_remote_name_complete_ptr), + handler_->BindOnce( + [&](Address address, + std::shared_ptr on_remote_name_complete_ptr) { + log::info("Dequeued remote name request to {} since it was cancelled", + address.ToRedactedStringForLogging()); + (*on_remote_name_complete_ptr)(ErrorCode::PAGE_TIMEOUT, {}); + }, + address, on_remote_name_complete_ptr)); } void CancelRemoteNameRequest(Address address) { - log::info( - "Enqueuing cancel of remote name request to {}", address.ToRedactedStringForLogging()); + log::info("Enqueuing cancel of remote name request to {}", + address.ToRedactedStringForLogging()); acl_scheduler_->CancelRemoteNameRequest( - address, handler_->BindOnceOn(this, &impl::actually_cancel_remote_name_request, address)); + address, + handler_->BindOnceOn(this, &impl::actually_cancel_remote_name_request, address)); } void ReportRemoteNameRequestCancellation(Address address) { if (pending_) { log::info( - "Received CONNECTION_COMPLETE (corresponding INCORRECTLY to an RNR cancellation) from {}", - address.ToRedactedStringForLogging()); + "Received CONNECTION_COMPLETE (corresponding INCORRECTLY to an RNR cancellation) " + "from {}", + address.ToRedactedStringForLogging()); pending_ = false; on_remote_name_complete_(ErrorCode::UNKNOWN_CONNECTION, {}); acl_scheduler_->ReportRemoteNameRequestCompletion(address); } else { log::error( - "Received unexpected CONNECTION_COMPLETE when no Remote Name Request OR ACL connection " - "is outstanding"); + "Received unexpected CONNECTION_COMPLETE when no Remote Name Request OR ACL " + "connection is outstanding"); } } - private: +private: void actually_start_remote_name_request( - Address address, - std::unique_ptr request, - CompletionCallback on_completion, - RemoteHostSupportedFeaturesCallback on_remote_host_supported_features_notification, - std::shared_ptr on_remote_name_complete_ptr) { + Address address, std::unique_ptr request, + CompletionCallback on_completion, + RemoteHostSupportedFeaturesCallback on_remote_host_supported_features_notification, + std::shared_ptr on_remote_name_complete_ptr) { log::info("Starting remote name request to {}", address.ToRedactedStringForLogging()); log::assert_that(pending_ == false, "assert failed: pending_ == false"); pending_ = true; on_remote_host_supported_features_notification_ = - std::move(on_remote_host_supported_features_notification); + std::move(on_remote_host_supported_features_notification); on_remote_name_complete_ = std::move(*on_remote_name_complete_ptr.get()); hci_layer_->EnqueueCommand( - std::move(request), - handler_->BindOnceOn( - this, &impl::on_start_remote_name_request_status, address, std::move(on_completion))); + std::move(request), + handler_->BindOnceOn(this, &impl::on_start_remote_name_request_status, address, + std::move(on_completion))); } - void on_start_remote_name_request_status( - Address address, CompletionCallback on_completion, CommandStatusView status) { + void on_start_remote_name_request_status(Address address, CompletionCallback on_completion, + CommandStatusView status) { // TODO(b/294961421): Remove the ifdef when firmware fix in place. Realtek controllers // unexpectedly sent a Remote Name Req Complete HCI event without the corresponding HCI command. #ifndef TARGET_FLOSS @@ -139,13 +135,10 @@ struct RemoteNameRequestModule::impl { return; } #endif - log::assert_that( - status.GetCommandOpCode() == OpCode::REMOTE_NAME_REQUEST, - "assert failed: status.GetCommandOpCode() == OpCode::REMOTE_NAME_REQUEST"); - log::info( - "Started remote name request peer:{} status:{}", - address.ToRedactedStringForLogging(), - ErrorCodeText(status.GetStatus())); + log::assert_that(status.GetCommandOpCode() == OpCode::REMOTE_NAME_REQUEST, + "assert failed: status.GetCommandOpCode() == OpCode::REMOTE_NAME_REQUEST"); + log::info("Started remote name request peer:{} status:{}", address.ToRedactedStringForLogging(), + ErrorCodeText(status.GetStatus())); on_completion(status.GetStatus()); if (status.GetStatus() != ErrorCode::SUCCESS /* pending */) { pending_ = false; @@ -156,13 +149,11 @@ struct RemoteNameRequestModule::impl { void actually_cancel_remote_name_request(Address address) { if (pending_) { log::info("Cancelling remote name request to {}", address.ToRedactedStringForLogging()); - hci_layer_->EnqueueCommand( - RemoteNameRequestCancelBuilder::Create(address), - handler_->BindOnceOn(this, &impl::check_cancel_status, address)); + hci_layer_->EnqueueCommand(RemoteNameRequestCancelBuilder::Create(address), + handler_->BindOnceOn(this, &impl::check_cancel_status, address)); } else { - log::info( - "Ignoring cancel RNR as RNR event already received to {}", - address.ToRedactedStringForLogging()); + log::info("Ignoring cancel RNR as RNR event already received to {}", + address.ToRedactedStringForLogging()); } } @@ -170,37 +161,32 @@ struct RemoteNameRequestModule::impl { auto packet = RemoteHostSupportedFeaturesNotificationView::Create(view); log::assert_that(packet.IsValid(), "assert failed: packet.IsValid()"); if (pending_ && on_remote_host_supported_features_notification_) { - log::info( - "Received REMOTE_HOST_SUPPORTED_FEATURES_NOTIFICATION from {}", - packet.GetBdAddr().ToRedactedStringForLogging()); + log::info("Received REMOTE_HOST_SUPPORTED_FEATURES_NOTIFICATION from {}", + packet.GetBdAddr().ToRedactedStringForLogging()); on_remote_host_supported_features_notification_(packet.GetHostSupportedFeatures()); // Remove the callback so that we won't call it again. on_remote_host_supported_features_notification_ = RemoteHostSupportedFeaturesCallback(); } else if (!pending_) { log::error( - "Received unexpected REMOTE_HOST_SUPPORTED_FEATURES_NOTIFICATION when no Remote Name " - "Request is outstanding"); + "Received unexpected REMOTE_HOST_SUPPORTED_FEATURES_NOTIFICATION when no Remote Name " + "Request is outstanding"); } else { // callback is not set, which indicates we have processed the feature notification. log::error( - "Received more than one REMOTE_HOST_SUPPORTED_FEATURES_NOTIFICATION during Remote Name " - "Request"); + "Received more than one REMOTE_HOST_SUPPORTED_FEATURES_NOTIFICATION during Remote " + "Name Request"); } } void completed(ErrorCode status, std::array name, Address address) { if (pending_) { - log::info( - "Received REMOTE_NAME_REQUEST_COMPLETE from {} with status {}", - address.ToRedactedStringForLogging(), - ErrorCodeText(status)); + log::info("Received REMOTE_NAME_REQUEST_COMPLETE from {} with status {}", + address.ToRedactedStringForLogging(), ErrorCodeText(status)); pending_ = false; on_remote_name_complete_(status, name); acl_scheduler_->ReportRemoteNameRequestCompletion(address); } else { - log::error( - "Received unexpected REMOTE_NAME_REQUEST_COMPLETE from {} with status {}", - address.ToRedactedStringForLogging(), - ErrorCodeText(status)); + log::error("Received unexpected REMOTE_NAME_REQUEST_COMPLETE from {} with status {}", + address.ToRedactedStringForLogging(), ErrorCodeText(status)); } } @@ -233,25 +219,19 @@ struct RemoteNameRequestModule::impl { }; const ModuleFactory RemoteNameRequestModule::Factory = - ModuleFactory([]() { return new RemoteNameRequestModule(); }); + ModuleFactory([]() { return new RemoteNameRequestModule(); }); -RemoteNameRequestModule::RemoteNameRequestModule() : pimpl_(std::make_unique(*this)){}; +RemoteNameRequestModule::RemoteNameRequestModule() : pimpl_(std::make_unique(*this)) {} RemoteNameRequestModule::~RemoteNameRequestModule() = default; void RemoteNameRequestModule::StartRemoteNameRequest( - Address address, - std::unique_ptr request, - CompletionCallback on_completion, - RemoteHostSupportedFeaturesCallback on_remote_host_supported_features_notification, - RemoteNameCallback on_remote_name_complete) { - CallOn( - pimpl_.get(), - &impl::StartRemoteNameRequest, - address, - std::move(request), - std::move(on_completion), - std::move(on_remote_host_supported_features_notification), - std::move(on_remote_name_complete)); + Address address, std::unique_ptr request, + CompletionCallback on_completion, + RemoteHostSupportedFeaturesCallback on_remote_host_supported_features_notification, + RemoteNameCallback on_remote_name_complete) { + CallOn(pimpl_.get(), &impl::StartRemoteNameRequest, address, std::move(request), + std::move(on_completion), std::move(on_remote_host_supported_features_notification), + std::move(on_remote_name_complete)); } void RemoteNameRequestModule::CancelRemoteNameRequest(Address address) { @@ -267,13 +247,9 @@ void RemoteNameRequestModule::ListDependencies(ModuleList* list) const { list->add(); } -void RemoteNameRequestModule::Start() { - pimpl_->Start(); -} +void RemoteNameRequestModule::Start() { pimpl_->Start(); } -void RemoteNameRequestModule::Stop() { - pimpl_->Stop(); -} +void RemoteNameRequestModule::Stop() { pimpl_->Stop(); } } // namespace hci } // namespace bluetooth diff --git a/system/gd/hci/remote_name_request.h b/system/gd/hci/remote_name_request.h index 9150d15d665..d8018d28412 100644 --- a/system/gd/hci/remote_name_request.h +++ b/system/gd/hci/remote_name_request.h @@ -33,21 +33,20 @@ namespace hci { using CompletionCallback = common::ContextualOnceCallback; using RemoteHostSupportedFeaturesCallback = common::ContextualOnceCallback; using RemoteNameCallback = - common::ContextualOnceCallback)>; + common::ContextualOnceCallback)>; // Historical note: This class is intended to provide a shim at the *HCI* layer, so legacy Remote // Name Requests can interoperate with the GD ACL scheduler. Thus, we intentionally do not merge // identical requests, cache responses, or handle request timeouts - we leave this to our callers. // When GD clients start to use this module, richer functionality should be added. class RemoteNameRequestModule : public bluetooth::Module { - public: +public: // Dispatch a Remote Name Request void StartRemoteNameRequest( - Address address, - std::unique_ptr request, - CompletionCallback on_completion, - RemoteHostSupportedFeaturesCallback on_remote_host_supported_features_notification, - RemoteNameCallback on_remote_name_complete); + Address address, std::unique_ptr request, + CompletionCallback on_completion, + RemoteHostSupportedFeaturesCallback on_remote_host_supported_features_notification, + RemoteNameCallback on_remote_name_complete); // Cancel a Remote Name Request void CancelRemoteNameRequest(Address address); @@ -57,19 +56,17 @@ class RemoteNameRequestModule : public bluetooth::Module { // happens, since we don't get the appropriate HCI event. void ReportRemoteNameRequestCancellation(Address address); - private: +private: struct impl; std::unique_ptr pimpl_; - protected: +protected: void ListDependencies(ModuleList* list) const override; void Start() override; void Stop() override; - std::string ToString() const override { - return std::string("RemoteNameRequestModule"); - } + std::string ToString() const override { return std::string("RemoteNameRequestModule"); } - public: +public: static const ModuleFactory Factory; RemoteNameRequestModule(); ~RemoteNameRequestModule(); diff --git a/system/gd/hci/remote_name_request_test.cc b/system/gd/hci/remote_name_request_test.cc index 2d7726995a8..a90ff2eb47d 100644 --- a/system/gd/hci/remote_name_request_test.cc +++ b/system/gd/hci/remote_name_request_test.cc @@ -62,7 +62,7 @@ MATCHER_P(IsSetWithValue, matcher, "Future is not set with value") { } class RemoteNameRequestModuleTest : public ::testing::Test { - protected: +protected: void SetUp() override { test_hci_layer_ = new HciLayerFake; fake_registry_.InjectTestModule(&HciLayer::Factory, test_hci_layer_); @@ -74,7 +74,7 @@ class RemoteNameRequestModuleTest : public ::testing::Test { ASSERT_NE(client_handler_, nullptr); remote_name_request_module_ = static_cast( - fake_registry_.GetModuleUnderTest(&RemoteNameRequestModule::Factory)); + fake_registry_.GetModuleUnderTest(&RemoteNameRequestModule::Factory)); ::testing::FLAGS_gtest_death_test_style = "threadsafe"; } @@ -97,24 +97,22 @@ class RemoteNameRequestModuleTest : public ::testing::Test { template common::ContextualOnceCallback promiseCallback(std::promise promise) { return client_handler_->BindOnce( - [](std::promise promise, T... /* args */) { promise.set_value(); }, - std::move(promise)); + [](std::promise promise, T... /* args */) { promise.set_value(); }, + std::move(promise)); } template common::ContextualOnceCallback capturingPromiseCallback( - std::promise> promise) { - return client_handler_->BindOnce( - [](std::promise> promise, T... args) { - promise.set_value(std::make_tuple(args...)); - }, - std::move(promise)); + std::promise> promise) { + return client_handler_->BindOnce([](std::promise> promise, + T... args) { promise.set_value(std::make_tuple(args...)); }, + std::move(promise)); } template common::ContextualOnceCallback capturingPromiseCallback(std::promise promise) { - return client_handler_->BindOnce( - [](std::promise promise, T arg) { promise.set_value(arg); }, std::move(promise)); + return client_handler_->BindOnce([](std::promise promise, T arg) { promise.set_value(arg); }, + std::move(promise)); } TestModuleRegistry fake_registry_; @@ -127,12 +125,11 @@ class RemoteNameRequestModuleTest : public ::testing::Test { TEST_F(RemoteNameRequestModuleTest, CorrectCommandSent) { // start a remote name request remote_name_request_module_->StartRemoteNameRequest( - address1, - RemoteNameRequestBuilder::Create( - address1, PageScanRepetitionMode::R0, 3, ClockOffsetValid::INVALID), - impossibleCallback(), - impossibleCallback(), - impossibleCallback>()); + address1, + RemoteNameRequestBuilder::Create(address1, PageScanRepetitionMode::R0, 3, + ClockOffsetValid::INVALID), + impossibleCallback(), impossibleCallback(), + impossibleCallback>()); // verify that the correct HCI command was sent auto command = test_hci_layer_->GetCommand(); @@ -152,16 +149,15 @@ TEST_F(RemoteNameRequestModuleTest, FailToSendCommand) { // start a remote name request remote_name_request_module_->StartRemoteNameRequest( - address1, - RemoteNameRequestBuilder::Create( - address1, PageScanRepetitionMode::R0, 3, ClockOffsetValid::INVALID), - capturingPromiseCallback(std::move(promise)), - impossibleCallback(), - impossibleCallback>()); + address1, + RemoteNameRequestBuilder::Create(address1, PageScanRepetitionMode::R0, 3, + ClockOffsetValid::INVALID), + capturingPromiseCallback(std::move(promise)), impossibleCallback(), + impossibleCallback>()); // on the command, return a failure HCI status test_hci_layer_->GetCommand(); test_hci_layer_->IncomingEvent( - RemoteNameRequestStatusBuilder::Create(ErrorCode::STATUS_UNKNOWN, 1)); + RemoteNameRequestStatusBuilder::Create(ErrorCode::STATUS_UNKNOWN, 1)); // the completion callback should be immediately invoked with the failing status EXPECT_THAT(future, IsSetWithValue(Eq(ErrorCode::STATUS_UNKNOWN))); @@ -173,12 +169,11 @@ TEST_F(RemoteNameRequestModuleTest, SendCommandSuccessfully) { // start a remote name request remote_name_request_module_->StartRemoteNameRequest( - address1, - RemoteNameRequestBuilder::Create( - address1, PageScanRepetitionMode::R0, 3, ClockOffsetValid::INVALID), - capturingPromiseCallback(std::move(promise)), - impossibleCallback(), - impossibleCallback>()); + address1, + RemoteNameRequestBuilder::Create(address1, PageScanRepetitionMode::R0, 3, + ClockOffsetValid::INVALID), + capturingPromiseCallback(std::move(promise)), impossibleCallback(), + impossibleCallback>()); // the command receives a successful reply, so it successfully starts test_hci_layer_->GetCommand(); test_hci_layer_->IncomingEvent(RemoteNameRequestStatusBuilder::Create(ErrorCode::SUCCESS, 1)); @@ -193,12 +188,11 @@ TEST_F(RemoteNameRequestModuleTest, SendCommandThenCancelIt) { // start a remote name request remote_name_request_module_->StartRemoteNameRequest( - address1, - RemoteNameRequestBuilder::Create( - address1, PageScanRepetitionMode::R0, 3, ClockOffsetValid::INVALID), - emptyCallback(), - impossibleCallback(), - impossibleCallback>()); + address1, + RemoteNameRequestBuilder::Create(address1, PageScanRepetitionMode::R0, 3, + ClockOffsetValid::INVALID), + emptyCallback(), impossibleCallback(), + impossibleCallback>()); // we successfully start test_hci_layer_->GetCommand(); @@ -212,7 +206,7 @@ TEST_F(RemoteNameRequestModuleTest, SendCommandThenCancelIt) { auto discovery_command = DiscoveryCommandView::Create(command); ASSERT_TRUE(discovery_command.IsValid()); auto cancel_command = - RemoteNameRequestCancelView::Create(DiscoveryCommandView::Create(discovery_command)); + RemoteNameRequestCancelView::Create(DiscoveryCommandView::Create(discovery_command)); ASSERT_TRUE(cancel_command.IsValid()); EXPECT_EQ(cancel_command.GetBdAddr(), address1); } @@ -223,12 +217,11 @@ TEST_F(RemoteNameRequestModuleTest, SendCommandThenCancelItCallback) { // start a remote name request remote_name_request_module_->StartRemoteNameRequest( - address1, - RemoteNameRequestBuilder::Create( - address1, PageScanRepetitionMode::R0, 3, ClockOffsetValid::INVALID), - emptyCallback(), - impossibleCallback(), - capturingPromiseCallback>(std::move(promise))); + address1, + RemoteNameRequestBuilder::Create(address1, PageScanRepetitionMode::R0, 3, + ClockOffsetValid::INVALID), + emptyCallback(), impossibleCallback(), + capturingPromiseCallback>(std::move(promise))); // we successfully start test_hci_layer_->GetCommand(); @@ -238,7 +231,7 @@ TEST_F(RemoteNameRequestModuleTest, SendCommandThenCancelItCallback) { remote_name_request_module_->CancelRemoteNameRequest(address1); test_hci_layer_->GetCommand(); test_hci_layer_->IncomingEvent( - RemoteNameRequestCancelCompleteBuilder::Create(1, ErrorCode::SUCCESS, address1)); + RemoteNameRequestCancelCompleteBuilder::Create(1, ErrorCode::SUCCESS, address1)); // verify that the completion has NOT yet been invoked (we need to wait for the RNR itself to // complete) @@ -246,11 +239,11 @@ TEST_F(RemoteNameRequestModuleTest, SendCommandThenCancelItCallback) { // let the RNR complete with a failure test_hci_layer_->IncomingEvent(RemoteNameRequestCompleteBuilder::Create( - ErrorCode::UNKNOWN_CONNECTION, address1, remote_name1)); + ErrorCode::UNKNOWN_CONNECTION, address1, remote_name1)); // only now should the name callback be invoked - EXPECT_THAT( - future, IsSetWithValue(Eq(std::make_tuple(ErrorCode::UNKNOWN_CONNECTION, remote_name1)))); + EXPECT_THAT(future, + IsSetWithValue(Eq(std::make_tuple(ErrorCode::UNKNOWN_CONNECTION, remote_name1)))); } // TODO(aryarahul) - unify HciLayerFake so this test can be run @@ -264,12 +257,11 @@ TEST_F(RemoteNameRequestModuleTest, DISABLED_SendCommandThenCancelItCallbackInte // start a remote name request remote_name_request_module_->StartRemoteNameRequest( - address1, - RemoteNameRequestBuilder::Create( - address1, PageScanRepetitionMode::R0, 3, ClockOffsetValid::INVALID), - emptyCallback(), - impossibleCallback(), - capturingPromiseCallback>(std::move(promise))); + address1, + RemoteNameRequestBuilder::Create(address1, PageScanRepetitionMode::R0, 3, + ClockOffsetValid::INVALID), + emptyCallback(), impossibleCallback(), + capturingPromiseCallback>(std::move(promise))); // we successfully start test_hci_layer_->GetCommand(); @@ -279,17 +271,15 @@ TEST_F(RemoteNameRequestModuleTest, DISABLED_SendCommandThenCancelItCallbackInte remote_name_request_module_->CancelRemoteNameRequest(address1); test_hci_layer_->GetCommand(); test_hci_layer_->IncomingEvent( - RemoteNameRequestCancelCompleteBuilder::Create(1, ErrorCode::SUCCESS, address1)); + RemoteNameRequestCancelCompleteBuilder::Create(1, ErrorCode::SUCCESS, address1)); // get the INCORRECT ACL connection complete event test_hci_layer_->IncomingEvent(ConnectionCompleteBuilder::Create( - ErrorCode::UNKNOWN_CONNECTION, 0, address1, LinkType::ACL, Enable::DISABLED)); + ErrorCode::UNKNOWN_CONNECTION, 0, address1, LinkType::ACL, Enable::DISABLED)); // we expect the name callback to be invoked nonetheless - EXPECT_THAT( - future, - IsSetWithValue( - Eq(std::make_tuple(ErrorCode::UNKNOWN_CONNECTION, std::array{})))); + EXPECT_THAT(future, IsSetWithValue(Eq(std::make_tuple(ErrorCode::UNKNOWN_CONNECTION, + std::array{})))); } // This test should be replaced with the above one, so we test the integration of AclManager and @@ -300,12 +290,11 @@ TEST_F(RemoteNameRequestModuleTest, SendCommandThenCancelItCallbackInteropWorkar // start a remote name request remote_name_request_module_->StartRemoteNameRequest( - address1, - RemoteNameRequestBuilder::Create( - address1, PageScanRepetitionMode::R0, 3, ClockOffsetValid::INVALID), - emptyCallback(), - impossibleCallback(), - capturingPromiseCallback>(std::move(promise))); + address1, + RemoteNameRequestBuilder::Create(address1, PageScanRepetitionMode::R0, 3, + ClockOffsetValid::INVALID), + emptyCallback(), impossibleCallback(), + capturingPromiseCallback>(std::move(promise))); // we successfully start test_hci_layer_->GetCommand(); @@ -315,16 +304,14 @@ TEST_F(RemoteNameRequestModuleTest, SendCommandThenCancelItCallbackInteropWorkar remote_name_request_module_->CancelRemoteNameRequest(address1); test_hci_layer_->GetCommand(); test_hci_layer_->IncomingEvent( - RemoteNameRequestCancelCompleteBuilder::Create(1, ErrorCode::SUCCESS, address1)); + RemoteNameRequestCancelCompleteBuilder::Create(1, ErrorCode::SUCCESS, address1)); // the INCORRECT ACL connection complete event will, from ACLManager, trigger this event remote_name_request_module_->ReportRemoteNameRequestCancellation(address1); // we expect the name callback to be invoked nonetheless - EXPECT_THAT( - future, - IsSetWithValue( - Eq(std::make_tuple(ErrorCode::UNKNOWN_CONNECTION, std::array{})))); + EXPECT_THAT(future, IsSetWithValue(Eq(std::make_tuple(ErrorCode::UNKNOWN_CONNECTION, + std::array{})))); } TEST_F(RemoteNameRequestModuleTest, SendCommandThenCancelItCancelFails) { @@ -333,12 +320,11 @@ TEST_F(RemoteNameRequestModuleTest, SendCommandThenCancelItCancelFails) { // start a remote name request remote_name_request_module_->StartRemoteNameRequest( - address1, - RemoteNameRequestBuilder::Create( - address1, PageScanRepetitionMode::R0, 3, ClockOffsetValid::INVALID), - emptyCallback(), - impossibleCallback(), - capturingPromiseCallback>(std::move(promise))); + address1, + RemoteNameRequestBuilder::Create(address1, PageScanRepetitionMode::R0, 3, + ClockOffsetValid::INVALID), + emptyCallback(), impossibleCallback(), + capturingPromiseCallback>(std::move(promise))); // we successfully start test_hci_layer_->GetCommand(); @@ -348,13 +334,11 @@ TEST_F(RemoteNameRequestModuleTest, SendCommandThenCancelItCancelFails) { remote_name_request_module_->CancelRemoteNameRequest(address1); test_hci_layer_->GetCommand(); test_hci_layer_->IncomingEvent(RemoteNameRequestCancelCompleteBuilder::Create( - 1, ErrorCode::INVALID_HCI_COMMAND_PARAMETERS, address1)); + 1, ErrorCode::INVALID_HCI_COMMAND_PARAMETERS, address1)); // we expect the name callback to be invoked nonetheless - EXPECT_THAT( - future, - IsSetWithValue(Eq( - std::make_tuple(ErrorCode::INVALID_HCI_COMMAND_PARAMETERS, std::array{})))); + EXPECT_THAT(future, IsSetWithValue(Eq(std::make_tuple(ErrorCode::INVALID_HCI_COMMAND_PARAMETERS, + std::array{})))); } TEST_F(RemoteNameRequestModuleTest, HostSupportedEvents) { @@ -363,12 +347,11 @@ TEST_F(RemoteNameRequestModuleTest, HostSupportedEvents) { // start a remote name request remote_name_request_module_->StartRemoteNameRequest( - address1, - RemoteNameRequestBuilder::Create( - address1, PageScanRepetitionMode::R0, 3, ClockOffsetValid::INVALID), - emptyCallback(), - capturingPromiseCallback(std::move(promise)), - impossibleCallback>()); + address1, + RemoteNameRequestBuilder::Create(address1, PageScanRepetitionMode::R0, 3, + ClockOffsetValid::INVALID), + emptyCallback(), capturingPromiseCallback(std::move(promise)), + impossibleCallback>()); test_hci_layer_->GetCommand(); test_hci_layer_->IncomingEvent(RemoteNameRequestStatusBuilder::Create(ErrorCode::SUCCESS, 1)); @@ -378,7 +361,7 @@ TEST_F(RemoteNameRequestModuleTest, HostSupportedEvents) { // report host supported events test_hci_layer_->IncomingEvent( - RemoteHostSupportedFeaturesNotificationBuilder::Create(address1, 1234)); + RemoteHostSupportedFeaturesNotificationBuilder::Create(address1, 1234)); // verify that we got the features EXPECT_THAT(future, IsSetWithValue(Eq((uint64_t)1234))); @@ -390,12 +373,11 @@ TEST_F(RemoteNameRequestModuleTest, CompletedRemoteNameRequest) { // start a remote name request remote_name_request_module_->StartRemoteNameRequest( - address1, - RemoteNameRequestBuilder::Create( - address1, PageScanRepetitionMode::R0, 3, ClockOffsetValid::INVALID), - emptyCallback(), - impossibleCallback(), - capturingPromiseCallback>(std::move(promise))); + address1, + RemoteNameRequestBuilder::Create(address1, PageScanRepetitionMode::R0, 3, + ClockOffsetValid::INVALID), + emptyCallback(), impossibleCallback(), + capturingPromiseCallback>(std::move(promise))); test_hci_layer_->GetCommand(); test_hci_layer_->IncomingEvent(RemoteNameRequestStatusBuilder::Create(ErrorCode::SUCCESS, 1)); @@ -404,8 +386,8 @@ TEST_F(RemoteNameRequestModuleTest, CompletedRemoteNameRequest) { EXPECT_THAT(future.wait_for(timeout), std::future_status::timeout); // report remote name (with some random status that should be passed through) - test_hci_layer_->IncomingEvent( - RemoteNameRequestCompleteBuilder::Create(ErrorCode::STATUS_UNKNOWN, address1, remote_name1)); + test_hci_layer_->IncomingEvent(RemoteNameRequestCompleteBuilder::Create(ErrorCode::STATUS_UNKNOWN, + address1, remote_name1)); // verify that the callback was invoked with the same status EXPECT_THAT(future, IsSetWithValue(Eq(std::make_tuple(ErrorCode::STATUS_UNKNOWN, remote_name1)))); @@ -419,29 +401,27 @@ TEST_F(RemoteNameRequestModuleTest, QueuingRemoteNameRequestsSecondOneStarts) { // start a remote name request remote_name_request_module_->StartRemoteNameRequest( - address1, - RemoteNameRequestBuilder::Create( - address1, PageScanRepetitionMode::R0, 3, ClockOffsetValid::INVALID), - emptyCallback(), - impossibleCallback(), - promiseCallback>(std::move(promise1))); + address1, + RemoteNameRequestBuilder::Create(address1, PageScanRepetitionMode::R0, 3, + ClockOffsetValid::INVALID), + emptyCallback(), impossibleCallback(), + promiseCallback>(std::move(promise1))); // enqueue a second one remote_name_request_module_->StartRemoteNameRequest( - address2, - RemoteNameRequestBuilder::Create( - address2, PageScanRepetitionMode::R1, 4, ClockOffsetValid::VALID), - emptyCallback(), - impossibleCallback(), - capturingPromiseCallback>(std::move(promise2))); + address2, + RemoteNameRequestBuilder::Create(address2, PageScanRepetitionMode::R1, 4, + ClockOffsetValid::VALID), + emptyCallback(), impossibleCallback(), + capturingPromiseCallback>(std::move(promise2))); // acknowledge that the first one has started test_hci_layer_->GetCommand(); test_hci_layer_->IncomingEvent(RemoteNameRequestStatusBuilder::Create(ErrorCode::SUCCESS, 1)); // report remote name for the first one - test_hci_layer_->IncomingEvent( - RemoteNameRequestCompleteBuilder::Create(ErrorCode::STATUS_UNKNOWN, address1, remote_name1)); + test_hci_layer_->IncomingEvent(RemoteNameRequestCompleteBuilder::Create(ErrorCode::STATUS_UNKNOWN, + address1, remote_name1)); // verify that the first callback was invoked EXPECT_THAT(future1, IsSet()); @@ -465,21 +445,19 @@ TEST_F(RemoteNameRequestModuleTest, QueuingRemoteNameRequestsSecondOneCancelledW // start a remote name request remote_name_request_module_->StartRemoteNameRequest( - address1, - RemoteNameRequestBuilder::Create( - address1, PageScanRepetitionMode::R0, 3, ClockOffsetValid::INVALID), - emptyCallback(), - impossibleCallback(), - emptyCallback>()); + address1, + RemoteNameRequestBuilder::Create(address1, PageScanRepetitionMode::R0, 3, + ClockOffsetValid::INVALID), + emptyCallback(), impossibleCallback(), + emptyCallback>()); // enqueue a second one remote_name_request_module_->StartRemoteNameRequest( - address2, - RemoteNameRequestBuilder::Create( - address2, PageScanRepetitionMode::R1, 4, ClockOffsetValid::VALID), - emptyCallback(), - impossibleCallback(), - capturingPromiseCallback>(std::move(promise))); + address2, + RemoteNameRequestBuilder::Create(address2, PageScanRepetitionMode::R1, 4, + ClockOffsetValid::VALID), + emptyCallback(), impossibleCallback(), + capturingPromiseCallback>(std::move(promise))); // acknowledge that the first one has started test_hci_layer_->GetCommand(); @@ -490,8 +468,8 @@ TEST_F(RemoteNameRequestModuleTest, QueuingRemoteNameRequestsSecondOneCancelledW // verify that the cancellation callback was properly invoked immediately EXPECT_THAT( - future, - IsSetWithValue(Eq(std::make_tuple(ErrorCode::PAGE_TIMEOUT, std::array{})))); + future, + IsSetWithValue(Eq(std::make_tuple(ErrorCode::PAGE_TIMEOUT, std::array{})))); } TEST_F(RemoteNameRequestModuleTest, QueuingRemoteNameRequestsCancelFirst) { @@ -502,21 +480,19 @@ TEST_F(RemoteNameRequestModuleTest, QueuingRemoteNameRequestsCancelFirst) { // start a remote name request remote_name_request_module_->StartRemoteNameRequest( - address1, - RemoteNameRequestBuilder::Create( - address1, PageScanRepetitionMode::R0, 3, ClockOffsetValid::INVALID), - emptyCallback(), - impossibleCallback(), - promiseCallback>(std::move(promise1))); + address1, + RemoteNameRequestBuilder::Create(address1, PageScanRepetitionMode::R0, 3, + ClockOffsetValid::INVALID), + emptyCallback(), impossibleCallback(), + promiseCallback>(std::move(promise1))); // enqueue a second one remote_name_request_module_->StartRemoteNameRequest( - address2, - RemoteNameRequestBuilder::Create( - address2, PageScanRepetitionMode::R1, 4, ClockOffsetValid::VALID), - emptyCallback(), - impossibleCallback(), - capturingPromiseCallback>(std::move(promise2))); + address2, + RemoteNameRequestBuilder::Create(address2, PageScanRepetitionMode::R1, 4, + ClockOffsetValid::VALID), + emptyCallback(), impossibleCallback(), + capturingPromiseCallback>(std::move(promise2))); // acknowledge that the first one has started test_hci_layer_->GetCommand(); @@ -528,9 +504,9 @@ TEST_F(RemoteNameRequestModuleTest, QueuingRemoteNameRequestsCancelFirst) { // let the cancel complete test_hci_layer_->GetCommand(); test_hci_layer_->IncomingEvent( - RemoteNameRequestCancelCompleteBuilder::Create(1, ErrorCode::SUCCESS, address1)); + RemoteNameRequestCancelCompleteBuilder::Create(1, ErrorCode::SUCCESS, address1)); test_hci_layer_->IncomingEvent(RemoteNameRequestCompleteBuilder::Create( - ErrorCode::UNKNOWN_CONNECTION, address1, remote_name1)); + ErrorCode::UNKNOWN_CONNECTION, address1, remote_name1)); // verify that the second request has now started auto command = test_hci_layer_->GetCommand(); @@ -549,21 +525,19 @@ TEST_F(RemoteNameRequestModuleTest, QueuingRemoteNameRequestsCancelFirstWithBugg // start a remote name request remote_name_request_module_->StartRemoteNameRequest( - address1, - RemoteNameRequestBuilder::Create( - address1, PageScanRepetitionMode::R0, 3, ClockOffsetValid::INVALID), - emptyCallback(), - impossibleCallback(), - promiseCallback>(std::move(promise1))); + address1, + RemoteNameRequestBuilder::Create(address1, PageScanRepetitionMode::R0, 3, + ClockOffsetValid::INVALID), + emptyCallback(), impossibleCallback(), + promiseCallback>(std::move(promise1))); // enqueue a second one remote_name_request_module_->StartRemoteNameRequest( - address2, - RemoteNameRequestBuilder::Create( - address2, PageScanRepetitionMode::R1, 4, ClockOffsetValid::VALID), - emptyCallback(), - impossibleCallback(), - capturingPromiseCallback>(std::move(promise2))); + address2, + RemoteNameRequestBuilder::Create(address2, PageScanRepetitionMode::R1, 4, + ClockOffsetValid::VALID), + emptyCallback(), impossibleCallback(), + capturingPromiseCallback>(std::move(promise2))); // acknowledge that the first one has started test_hci_layer_->GetCommand(); @@ -575,7 +549,7 @@ TEST_F(RemoteNameRequestModuleTest, QueuingRemoteNameRequestsCancelFirstWithBugg // let the cancel complete test_hci_layer_->GetCommand(); test_hci_layer_->IncomingEvent( - RemoteNameRequestCancelCompleteBuilder::Create(1, ErrorCode::SUCCESS, address1)); + RemoteNameRequestCancelCompleteBuilder::Create(1, ErrorCode::SUCCESS, address1)); // send the INCORRECT response that we tolerate for interop reasons remote_name_request_module_->ReportRemoteNameRequestCancellation(address1); @@ -594,25 +568,23 @@ TEST_F(RemoteNameRequestModuleTest, FailToSendCommandThenSendNext) { // start a remote name request remote_name_request_module_->StartRemoteNameRequest( - address1, - RemoteNameRequestBuilder::Create( - address1, PageScanRepetitionMode::R0, 3, ClockOffsetValid::INVALID), - capturingPromiseCallback(std::move(promise)), - impossibleCallback(), - impossibleCallback>()); + address1, + RemoteNameRequestBuilder::Create(address1, PageScanRepetitionMode::R0, 3, + ClockOffsetValid::INVALID), + capturingPromiseCallback(std::move(promise)), impossibleCallback(), + impossibleCallback>()); // on the command, return a failure HCI status test_hci_layer_->GetCommand(); test_hci_layer_->IncomingEvent( - RemoteNameRequestStatusBuilder::Create(ErrorCode::STATUS_UNKNOWN, 1)); + RemoteNameRequestStatusBuilder::Create(ErrorCode::STATUS_UNKNOWN, 1)); // start a second request remote_name_request_module_->StartRemoteNameRequest( - address2, - RemoteNameRequestBuilder::Create( - address2, PageScanRepetitionMode::R1, 4, ClockOffsetValid::VALID), - emptyCallback(), - impossibleCallback(), - impossibleCallback>()); + address2, + RemoteNameRequestBuilder::Create(address2, PageScanRepetitionMode::R1, 4, + ClockOffsetValid::VALID), + emptyCallback(), impossibleCallback(), + impossibleCallback>()); // verify that it started auto command = test_hci_layer_->GetCommand(); @@ -629,26 +601,24 @@ TEST_F(RemoteNameRequestModuleTest, FailToSendCommandThenDequeueNext) { // start a remote name request remote_name_request_module_->StartRemoteNameRequest( - address1, - RemoteNameRequestBuilder::Create( - address1, PageScanRepetitionMode::R0, 3, ClockOffsetValid::INVALID), - emptyCallback(), - impossibleCallback(), - impossibleCallback>()); + address1, + RemoteNameRequestBuilder::Create(address1, PageScanRepetitionMode::R0, 3, + ClockOffsetValid::INVALID), + emptyCallback(), impossibleCallback(), + impossibleCallback>()); // enqueue a second one remote_name_request_module_->StartRemoteNameRequest( - address2, - RemoteNameRequestBuilder::Create( - address2, PageScanRepetitionMode::R1, 4, ClockOffsetValid::VALID), - impossibleCallback(), - impossibleCallback(), - impossibleCallback>()); + address2, + RemoteNameRequestBuilder::Create(address2, PageScanRepetitionMode::R1, 4, + ClockOffsetValid::VALID), + impossibleCallback(), impossibleCallback(), + impossibleCallback>()); // for the first, return a failure HCI status test_hci_layer_->GetCommand(); test_hci_layer_->IncomingEvent( - RemoteNameRequestStatusBuilder::Create(ErrorCode::STATUS_UNKNOWN, 1)); + RemoteNameRequestStatusBuilder::Create(ErrorCode::STATUS_UNKNOWN, 1)); // verify that the second one started auto command = test_hci_layer_->GetCommand(); @@ -665,12 +635,11 @@ TEST_F(RemoteNameRequestModuleTest, CancelJustWhenRNREventReturns) { // start a remote name request remote_name_request_module_->StartRemoteNameRequest( - address1, - RemoteNameRequestBuilder::Create( - address1, PageScanRepetitionMode::R0, 3, ClockOffsetValid::INVALID), - emptyCallback(), - impossibleCallback(), - capturingPromiseCallback>(std::move(promise))); + address1, + RemoteNameRequestBuilder::Create(address1, PageScanRepetitionMode::R0, 3, + ClockOffsetValid::INVALID), + emptyCallback(), impossibleCallback(), + capturingPromiseCallback>(std::move(promise))); // we successfully start test_hci_layer_->GetCommand(); @@ -678,21 +647,18 @@ TEST_F(RemoteNameRequestModuleTest, CancelJustWhenRNREventReturns) { auto promise2 = std::promise(); auto future2 = promise2.get_future(); client_handler_->Post(base::BindOnce( - [](RemoteNameRequestModule* remote_name_request_module, - HciLayerFake* test_hci_layer, - std::promise promise2) { - // but then the request is cancelled successfully (the status doesn't matter) - remote_name_request_module->CancelRemoteNameRequest(address1); - - // Send an rnr event completed with page timeout status - test_hci_layer->IncomingEvent( - RemoteNameRequestStatusBuilder::Create(ErrorCode::PAGE_TIMEOUT, 1)); - - promise2.set_value(); - }, - remote_name_request_module_, - test_hci_layer_, - std::move(promise2))); + [](RemoteNameRequestModule* remote_name_request_module, HciLayerFake* test_hci_layer, + std::promise promise2) { + // but then the request is cancelled successfully (the status doesn't matter) + remote_name_request_module->CancelRemoteNameRequest(address1); + + // Send an rnr event completed with page timeout status + test_hci_layer->IncomingEvent( + RemoteNameRequestStatusBuilder::Create(ErrorCode::PAGE_TIMEOUT, 1)); + + promise2.set_value(); + }, + remote_name_request_module_, test_hci_layer_, std::move(promise2))); future2.wait(); } diff --git a/system/gd/hci/security_interface.h b/system/gd/hci/security_interface.h index e14e060c3f6..d1126bd4ab0 100644 --- a/system/gd/hci/security_interface.h +++ b/system/gd/hci/security_interface.h @@ -23,22 +23,22 @@ namespace bluetooth { namespace hci { constexpr hci::EventCode SecurityEvents[] = { - hci::EventCode::ENCRYPTION_CHANGE, - hci::EventCode::CHANGE_CONNECTION_LINK_KEY_COMPLETE, - hci::EventCode::CENTRAL_LINK_KEY_COMPLETE, - hci::EventCode::RETURN_LINK_KEYS, - hci::EventCode::PIN_CODE_REQUEST, - hci::EventCode::LINK_KEY_REQUEST, - hci::EventCode::LINK_KEY_NOTIFICATION, - hci::EventCode::ENCRYPTION_KEY_REFRESH_COMPLETE, - hci::EventCode::IO_CAPABILITY_REQUEST, - hci::EventCode::IO_CAPABILITY_RESPONSE, - hci::EventCode::REMOTE_OOB_DATA_REQUEST, - hci::EventCode::SIMPLE_PAIRING_COMPLETE, - hci::EventCode::USER_PASSKEY_NOTIFICATION, - hci::EventCode::KEYPRESS_NOTIFICATION, - hci::EventCode::USER_CONFIRMATION_REQUEST, - hci::EventCode::USER_PASSKEY_REQUEST, + hci::EventCode::ENCRYPTION_CHANGE, + hci::EventCode::CHANGE_CONNECTION_LINK_KEY_COMPLETE, + hci::EventCode::CENTRAL_LINK_KEY_COMPLETE, + hci::EventCode::RETURN_LINK_KEYS, + hci::EventCode::PIN_CODE_REQUEST, + hci::EventCode::LINK_KEY_REQUEST, + hci::EventCode::LINK_KEY_NOTIFICATION, + hci::EventCode::ENCRYPTION_KEY_REFRESH_COMPLETE, + hci::EventCode::IO_CAPABILITY_REQUEST, + hci::EventCode::IO_CAPABILITY_RESPONSE, + hci::EventCode::REMOTE_OOB_DATA_REQUEST, + hci::EventCode::SIMPLE_PAIRING_COMPLETE, + hci::EventCode::USER_PASSKEY_NOTIFICATION, + hci::EventCode::KEYPRESS_NOTIFICATION, + hci::EventCode::USER_CONFIRMATION_REQUEST, + hci::EventCode::USER_PASSKEY_REQUEST, }; typedef CommandInterface SecurityInterface; diff --git a/system/gd/hci/uuid.cc b/system/gd/hci/uuid.cc index c1a44175b0c..4074d9f750b 100644 --- a/system/gd/hci/uuid.cc +++ b/system/gd/hci/uuid.cc @@ -19,8 +19,8 @@ #include "hci/uuid.h" #include - #include + #include namespace bluetooth { @@ -31,12 +31,13 @@ using UUID128Bit = Uuid::UUID128Bit; const Uuid Uuid::kEmpty = Uuid::From128BitBE(UUID128Bit{{0x00}}); namespace { -Uuid kBase = Uuid::From128BitBE( - UUID128Bit{{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, 0x5f, 0x9b, 0x34, 0xfb}}); +Uuid kBase = Uuid::From128BitBE(UUID128Bit{{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, + 0x00, 0x00, 0x80, 0x5f, 0x9b, 0x34, 0xfb}}); } // namespace size_t Uuid::GetShortestRepresentationSize() const { - if (memcmp(uu.data() + kNumBytes32, kBase.uu.data() + kNumBytes32, kNumBytes128 - kNumBytes32) != 0) { + if (memcmp(uu.data() + kNumBytes32, kBase.uu.data() + kNumBytes32, kNumBytes128 - kNumBytes32) != + 0) { return kNumBytes128; } @@ -47,13 +48,9 @@ size_t Uuid::GetShortestRepresentationSize() const { return kNumBytes32; } -bool Uuid::Is16Bit() const { - return GetShortestRepresentationSize() == kNumBytes16; -} +bool Uuid::Is16Bit() const { return GetShortestRepresentationSize() == kNumBytes16; } -uint16_t Uuid::As16Bit() const { - return (((uint16_t)uu[2]) << 8) + uu[3]; -} +uint16_t Uuid::As16Bit() const { return (((uint16_t)uu[2]) << 8) + uu[3]; } uint32_t Uuid::As32Bit() const { return (((uint32_t)uu[0]) << 24) + (((uint32_t)uu[1]) << 16) + (((uint32_t)uu[2]) << 8) + uu[3]; @@ -72,27 +69,11 @@ std::optional Uuid::FromString(const std::string& uuid) { } int c; - int rc = sscanf( - uuid.c_str(), - "%02hhx%02hhx%02hhx%02hhx-%02hhx%02hhx-%02hhx%02hhx" - "-%02hhx%02hhx-%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%n", - &p[0], - &p[1], - &p[2], - &p[3], - &p[4], - &p[5], - &p[6], - &p[7], - &p[8], - &p[9], - &p[10], - &p[11], - &p[12], - &p[13], - &p[14], - &p[15], - &c); + int rc = sscanf(uuid.c_str(), + "%02hhx%02hhx%02hhx%02hhx-%02hhx%02hhx-%02hhx%02hhx" + "-%02hhx%02hhx-%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%n", + &p[0], &p[1], &p[2], &p[3], &p[4], &p[5], &p[6], &p[7], &p[8], &p[9], &p[10], + &p[11], &p[12], &p[13], &p[14], &p[15], &c); if (rc != 16) { return std::nullopt; } @@ -172,54 +153,28 @@ UUID128Bit Uuid::To128BitLE() const { return le; } -const UUID128Bit& Uuid::To128BitBE() const { - return uu; -} +const UUID128Bit& Uuid::To128BitBE() const { return uu; } -bool Uuid::IsEmpty() const { - return *this == kEmpty; -} +bool Uuid::IsEmpty() const { return *this == kEmpty; } bool Uuid::operator<(const Uuid& rhs) const { return std::lexicographical_compare(uu.begin(), uu.end(), rhs.uu.begin(), rhs.uu.end()); } -bool Uuid::operator==(const Uuid& rhs) const { - return uu == rhs.uu; -} +bool Uuid::operator==(const Uuid& rhs) const { return uu == rhs.uu; } -bool Uuid::operator!=(const Uuid& rhs) const { - return uu != rhs.uu; -} +bool Uuid::operator!=(const Uuid& rhs) const { return uu != rhs.uu; } std::string Uuid::ToString() const { char buf[kString128BitLen + 1] = {}; - std::snprintf( - buf, - sizeof(buf), - "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x", - uu[0], - uu[1], - uu[2], - uu[3], - uu[4], - uu[5], - uu[6], - uu[7], - uu[8], - uu[9], - uu[10], - uu[11], - uu[12], - uu[13], - uu[14], - uu[15]); + std::snprintf(buf, sizeof(buf), + "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x", uu[0], + uu[1], uu[2], uu[3], uu[4], uu[5], uu[6], uu[7], uu[8], uu[9], uu[10], uu[11], + uu[12], uu[13], uu[14], uu[15]); return std::string(buf); } -std::string Uuid::ToLegacyConfigString() const { - return ToString(); -} +std::string Uuid::ToLegacyConfigString() const { return ToString(); } } // namespace hci } // namespace bluetooth diff --git a/system/gd/hci/uuid.h b/system/gd/hci/uuid.h index 77f4d7d26c9..ab0ad6db6bc 100644 --- a/system/gd/hci/uuid.h +++ b/system/gd/hci/uuid.h @@ -36,7 +36,7 @@ namespace hci { // 3. Bytes representing UUID coming from lower layer, HCI packets, are Little Endian. // 4. UUID in storage is always string. class Uuid final : public storage::Serializable { - public: +public: static constexpr size_t kNumBytes128 = 16; static constexpr size_t kNumBytes32 = 4; static constexpr size_t kNumBytes16 = 2; @@ -49,13 +49,9 @@ class Uuid final : public storage::Serializable { Uuid() = default; - inline uint8_t* data() { - return uu.data(); - } + inline uint8_t* data() { return uu.data(); } - inline const uint8_t* data() const { - return uu.data(); - } + inline const uint8_t* data() const { return uu.data(); } // storage::Serializable methods // Converts string representing 128, 32, or 16 bit UUID in @@ -119,8 +115,8 @@ class Uuid final : public storage::Serializable { bool operator==(const Uuid& rhs) const; bool operator!=(const Uuid& rhs) const; - private: - constexpr Uuid(const UUID128Bit& val) : uu{val} {}; +private: + constexpr Uuid(const UUID128Bit& val) : uu{val} {} // Network-byte-ordered ID (Big Endian). UUID128Bit uu = {}; @@ -143,7 +139,8 @@ struct hash { std::size_t operator()(const bluetooth::hci::Uuid& key) const { const auto& uuid_bytes = key.To128BitBE(); std::hash hash_fn; - return hash_fn(std::string(reinterpret_cast(uuid_bytes.data()), uuid_bytes.size())); + return hash_fn( + std::string(reinterpret_cast(uuid_bytes.data()), uuid_bytes.size())); } }; diff --git a/system/gd/hci/uuid_unittest.cc b/system/gd/hci/uuid_unittest.cc index 159e5f3e159..36abbba0f7b 100644 --- a/system/gd/hci/uuid_unittest.cc +++ b/system/gd/hci/uuid_unittest.cc @@ -23,32 +23,21 @@ namespace testing { using bluetooth::hci::Uuid; -static const Uuid ONES = Uuid::From128BitBE( - Uuid::UUID128Bit{{0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11}}); - -static const Uuid SEQUENTIAL = Uuid::From128BitBE( - Uuid::UUID128Bit{{0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89}}); - -static const Uuid kBase = Uuid::From128BitBE( - Uuid::UUID128Bit{{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, 0x5f, 0x9b, 0x34, 0xfb}}); - -static const Uuid kBaseLe = Uuid::From128BitLE(Uuid::UUID128Bit{ - {0xfb, - 0x34, - 0x9b, - 0x5f, - 0x80, - 0x00, - 0x00, - 0x80, - 0x00, - 0x10, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00}}); +static const Uuid ONES = + Uuid::From128BitBE(Uuid::UUID128Bit{{0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, + 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11}}); + +static const Uuid SEQUENTIAL = + Uuid::From128BitBE(Uuid::UUID128Bit{{0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xab, + 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89}}); + +static const Uuid kBase = + Uuid::From128BitBE(Uuid::UUID128Bit{{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, + 0x00, 0x00, 0x80, 0x5f, 0x9b, 0x34, 0xfb}}); + +static const Uuid kBaseLe = + Uuid::From128BitLE(Uuid::UUID128Bit{{0xfb, 0x34, 0x9b, 0x5f, 0x80, 0x00, 0x00, 0x80, 0x00, + 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}); TEST(UuidTest, IsEmpty) { ASSERT_TRUE(Uuid::kEmpty.IsEmpty()); @@ -88,15 +77,18 @@ TEST(UuidTest, Is16Bit) { TEST(UuidTest, From16Bit) { ASSERT_EQ(Uuid::From16Bit(0x0000), kBase); - const uint8_t u2[] = {0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, 0x5f, 0x9b, 0x34, 0xfb}; + const uint8_t u2[] = {0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x10, 0x00, + 0x80, 0x00, 0x00, 0x80, 0x5f, 0x9b, 0x34, 0xfb}; Uuid uuid = Uuid::From16Bit(0x0001); ASSERT_TRUE(memcmp(uuid.data(), u2, sizeof(u2)) == 0); - const uint8_t u3[] = {0x00, 0x00, 0x55, 0x3e, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, 0x5f, 0x9b, 0x34, 0xfb}; + const uint8_t u3[] = {0x00, 0x00, 0x55, 0x3e, 0x00, 0x00, 0x10, 0x00, + 0x80, 0x00, 0x00, 0x80, 0x5f, 0x9b, 0x34, 0xfb}; uuid = Uuid::From16Bit(0x553e); ASSERT_TRUE(memcmp(uuid.data(), u3, sizeof(u3)) == 0); - const uint8_t u4[] = {0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, 0x5f, 0x9b, 0x34, 0xfb}; + const uint8_t u4[] = {0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0x10, 0x00, + 0x80, 0x00, 0x00, 0x80, 0x5f, 0x9b, 0x34, 0xfb}; uuid = Uuid::From16Bit(0xffff); ASSERT_TRUE(memcmp(uuid.data(), u4, sizeof(u4)) == 0); } @@ -104,15 +96,18 @@ TEST(UuidTest, From16Bit) { TEST(UuidTest, From32Bit) { ASSERT_EQ(Uuid::From32Bit(0x00000000), kBase); - const uint8_t u2[] = {0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, 0x5f, 0x9b, 0x34, 0xfb}; + const uint8_t u2[] = {0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x10, 0x00, + 0x80, 0x00, 0x00, 0x80, 0x5f, 0x9b, 0x34, 0xfb}; Uuid uuid = Uuid::From32Bit(0x00000001); ASSERT_TRUE(memcmp(uuid.data(), u2, sizeof(u2)) == 0); - const uint8_t u3[] = {0x33, 0x44, 0x55, 0x3e, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, 0x5f, 0x9b, 0x34, 0xfb}; + const uint8_t u3[] = {0x33, 0x44, 0x55, 0x3e, 0x00, 0x00, 0x10, 0x00, + 0x80, 0x00, 0x00, 0x80, 0x5f, 0x9b, 0x34, 0xfb}; uuid = Uuid::From32Bit(0x3344553e); ASSERT_TRUE(memcmp(uuid.data(), u3, sizeof(u3)) == 0); - const uint8_t u4[] = {0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, 0x5f, 0x9b, 0x34, 0xfb}; + const uint8_t u4[] = {0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x10, 0x00, + 0x80, 0x00, 0x00, 0x80, 0x5f, 0x9b, 0x34, 0xfb}; uuid = Uuid::From32Bit(0xffffffff); ASSERT_TRUE(memcmp(uuid.data(), u4, sizeof(u4)) == 0); } @@ -133,17 +128,20 @@ TEST(UuidTest, ToString) { } TEST(UuidTest, test_string_to_uuid) { - const uint8_t u1[] = {0xe3, 0x9c, 0x62, 0x85, 0x86, 0x7f, 0x4b, 0x1d, 0x9d, 0xb0, 0x35, 0xfb, 0xd9, 0xae, 0xbf, 0x22}; + const uint8_t u1[] = {0xe3, 0x9c, 0x62, 0x85, 0x86, 0x7f, 0x4b, 0x1d, + 0x9d, 0xb0, 0x35, 0xfb, 0xd9, 0xae, 0xbf, 0x22}; auto uuid = Uuid::FromString("e39c6285-867f-4b1d-9db0-35fbd9aebf22"); ASSERT_TRUE(uuid); ASSERT_TRUE(memcmp(uuid->data(), u1, sizeof(u1)) == 0); - const uint8_t u2[] = {0x00, 0x00, 0x1a, 0xe8, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, 0x5f, 0x9b, 0x34, 0xfb}; + const uint8_t u2[] = {0x00, 0x00, 0x1a, 0xe8, 0x00, 0x00, 0x10, 0x00, + 0x80, 0x00, 0x00, 0x80, 0x5f, 0x9b, 0x34, 0xfb}; uuid = Uuid::FromString("1Ae8"); ASSERT_TRUE(uuid); ASSERT_TRUE(memcmp(uuid->data(), u2, sizeof(u2)) == 0); - const uint8_t u3[] = {0x12, 0x34, 0x11, 0x28, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, 0x5f, 0x9b, 0x34, 0xfb}; + const uint8_t u3[] = {0x12, 0x34, 0x11, 0x28, 0x00, 0x00, 0x10, 0x00, + 0x80, 0x00, 0x00, 0x80, 0x5f, 0x9b, 0x34, 0xfb}; uuid = Uuid::FromString("12341128"); ASSERT_TRUE(uuid); ASSERT_TRUE(memcmp(uuid->data(), u3, sizeof(u3)) == 0); diff --git a/system/gd/l2cap/classic/dynamic_channel_configuration_option.h b/system/gd/l2cap/classic/dynamic_channel_configuration_option.h index 2d8de291332..27bfe5fed2d 100644 --- a/system/gd/l2cap/classic/dynamic_channel_configuration_option.h +++ b/system/gd/l2cap/classic/dynamic_channel_configuration_option.h @@ -23,8 +23,8 @@ namespace l2cap { namespace classic { /** - * Configuration Option specified by L2CAP Channel user on a dynamic channel. L2CAP module will configure the channel - * based on user provided option. + * Configuration Option specified by L2CAP Channel user on a dynamic channel. L2CAP module will + * configure the channel based on user provided option. */ struct DynamicChannelConfigurationOption { enum class RetransmissionAndFlowControlMode { @@ -34,7 +34,8 @@ struct DynamicChannelConfigurationOption { }; /** * Retransmission and flow control mode. Currently L2CAP_BASIC and ENHANCED_RETRANSMISSION. - * If the remote doesn't support a mode, it might fall back to basic, as this is a negotiable option. + * If the remote doesn't support a mode, it might fall back to basic, as this is a negotiable + * option. */ RetransmissionAndFlowControlMode channel_mode = RetransmissionAndFlowControlMode::L2CAP_BASIC; diff --git a/system/gd/l2cap/classic/dynamic_channel_manager.cc b/system/gd/l2cap/classic/dynamic_channel_manager.cc index 8620086bba7..005074c7ef5 100644 --- a/system/gd/l2cap/classic/dynamic_channel_manager.cc +++ b/system/gd/l2cap/classic/dynamic_channel_manager.cc @@ -15,6 +15,7 @@ */ #include "l2cap/classic/dynamic_channel_manager.h" + #include "l2cap/classic/internal/dynamic_channel_service_impl.h" #include "l2cap/classic/internal/dynamic_channel_service_manager_impl.h" #include "l2cap/classic/internal/link.h" @@ -24,35 +25,33 @@ namespace bluetooth { namespace l2cap { namespace classic { -void DynamicChannelManager::ConnectChannel( - hci::Address device, - DynamicChannelConfigurationOption configuration_option, - Psm psm, - OnConnectionOpenCallback on_connection_open, - OnConnectionFailureCallback on_fail_callback) { +void DynamicChannelManager::ConnectChannel(hci::Address device, + DynamicChannelConfigurationOption configuration_option, + Psm psm, OnConnectionOpenCallback on_connection_open, + OnConnectionFailureCallback on_fail_callback) { internal::Link::PendingDynamicChannelConnection pending_connection{ - .on_open_callback_ = std::move(on_connection_open), - .on_fail_callback_ = std::move(on_fail_callback), - .configuration_ = configuration_option, + .on_open_callback_ = std::move(on_connection_open), + .on_fail_callback_ = std::move(on_fail_callback), + .configuration_ = configuration_option, }; - l2cap_layer_handler_->CallOn( - link_manager_, &internal::LinkManager::ConnectDynamicChannelServices, device, std::move(pending_connection), psm); + l2cap_layer_handler_->CallOn(link_manager_, &internal::LinkManager::ConnectDynamicChannelServices, + device, std::move(pending_connection), psm); } -void DynamicChannelManager::RegisterService( - Psm psm, - DynamicChannelConfigurationOption configuration_option, - const classic::SecurityPolicy& security_policy, - OnRegistrationCompleteCallback on_registration_complete, - OnConnectionOpenCallback on_connection_open) { +void DynamicChannelManager::RegisterService(Psm psm, + DynamicChannelConfigurationOption configuration_option, + const classic::SecurityPolicy& security_policy, + OnRegistrationCompleteCallback on_registration_complete, + OnConnectionOpenCallback on_connection_open) { internal::DynamicChannelServiceImpl::PendingRegistration pending_registration{ - .security_policy_ = security_policy, - .on_registration_complete_callback_ = std::move(on_registration_complete), - .on_connection_open_callback_ = std::move(on_connection_open), - .configuration_ = configuration_option, + .security_policy_ = security_policy, + .on_registration_complete_callback_ = std::move(on_registration_complete), + .on_connection_open_callback_ = std::move(on_connection_open), + .configuration_ = configuration_option, }; - l2cap_layer_handler_->CallOn( - service_manager_, &internal::DynamicChannelServiceManagerImpl::Register, psm, std::move(pending_registration)); + l2cap_layer_handler_->CallOn(service_manager_, + &internal::DynamicChannelServiceManagerImpl::Register, psm, + std::move(pending_registration)); } } // namespace classic diff --git a/system/gd/l2cap/classic/dynamic_channel_manager.h b/system/gd/l2cap/classic/dynamic_channel_manager.h index 9dbcd017e4c..a5cf9834573 100644 --- a/system/gd/l2cap/classic/dynamic_channel_manager.h +++ b/system/gd/l2cap/classic/dynamic_channel_manager.h @@ -40,14 +40,14 @@ class DynamicChannelServiceManagerImpl; } // namespace internal class DynamicChannelManager { - public: +public: enum class ConnectionResultCode { SUCCESS = 0, FAIL_NO_SERVICE_REGISTERED = 1, // No service is registered FAIL_HCI_ERROR = 2, // See hci_error FAIL_L2CAP_ERROR = 3, // See l2cap_connection_response_result - FAIL_REMOTE_NOT_SUPPORT = 4, // Remote not support required retansmission and flow control mode - FAIL_SECURITY_BLOCK = 5, // Cannot enhance required security level + FAIL_REMOTE_NOT_SUPPORT = 4, // Remote not support required retansmission and flow control mode + FAIL_SECURITY_BLOCK = 5, // Cannot enhance required security level }; struct ConnectionResult { @@ -58,7 +58,8 @@ class DynamicChannelManager { using OnConnectionFailureCallback = common::ContextualOnceCallback; - using OnConnectionOpenCallback = common::ContextualCallback)>; + using OnConnectionOpenCallback = + common::ContextualCallback)>; enum class RegistrationResult { SUCCESS = 0, @@ -66,8 +67,8 @@ class DynamicChannelManager { FAIL_INVALID_SERVICE = 2, // Invalid PSM }; - using OnRegistrationCompleteCallback = - common::ContextualOnceCallback)>; + using OnRegistrationCompleteCallback = common::ContextualOnceCallback)>; /** * Connect to a Dynamic channel on a remote device @@ -77,48 +78,48 @@ class DynamicChannelManager { * - When true is returned, method caller should wait for on_fail_callback or on_open_callback * - If an ACL connection does not exist, this method will create an ACL connection * - If HCI connection failed, on_fail_callback will be triggered with FAIL_HCI_ERROR - * - If Dynamic channel on a remote device is already reported as connected via on_open_callback, it won't be - * reported again + * - If Dynamic channel on a remote device is already reported as connected via on_open_callback, + * it won't be reported again * * @param device: Remote device to make this connection. * @param psm: Service PSM to connect. PSM is defined in Core spec Vol 3 Part A 4.2. - * @param on_open_callback: A callback to indicate success of a connection initiated from a remote device. + * @param on_open_callback: A callback to indicate success of a connection initiated from a remote + * device. * @param on_fail_callback: A callback to indicate connection failure along with a status code. * @param configuration_option: The configuration options for this channel */ - virtual void ConnectChannel( - hci::Address device, - DynamicChannelConfigurationOption configuration_option, - Psm psm, - OnConnectionOpenCallback on_connection_open, - OnConnectionFailureCallback on_fail_callback); + virtual void ConnectChannel(hci::Address device, + DynamicChannelConfigurationOption configuration_option, Psm psm, + OnConnectionOpenCallback on_connection_open, + OnConnectionFailureCallback on_fail_callback); /** * Register a service to receive incoming connections bound to a specific channel. * * - This method is asynchronous. * - When false is returned, the registration fails immediately. - * - When true is returned, method caller should wait for on_service_registered callback that contains a - * DynamicChannelService object. The registered service can be managed from that object. - * - If a PSM is already registered or some other error happens, on_registration_complete will be triggered with a - * non-SUCCESS value - * - After a service is registered, a DynamicChannel is delivered through on_open_callback when the remote - * initiates a channel open and channel is opened successfully + * - When true is returned, method caller should wait for on_service_registered callback that + * contains a DynamicChannelService object. The registered service can be managed from that + * object. + * - If a PSM is already registered or some other error happens, on_registration_complete will be + * triggered with a non-SUCCESS value + * - After a service is registered, a DynamicChannel is delivered through on_open_callback when + * the remote initiates a channel open and channel is opened successfully * - on_open_callback, will only be triggered after on_service_registered callback * * @param security_policy: The security policy used for the connection. * @param psm: Service PSM to register. PSM is defined in Core spec Vol 3 Part A 4.2. - * @param on_registration_complete: A callback to indicate the service setup has completed. If the return status is - * not SUCCESS, it means service is not registered due to reasons like PSM already take - * @param on_open_callback: A callback to indicate success of a connection initiated from a remote device. + * @param on_registration_complete: A callback to indicate the service setup has completed. If the + * return status is not SUCCESS, it means service is not registered due to reasons like PSM + * already take + * @param on_open_callback: A callback to indicate success of a connection initiated from a remote + * device. * @param configuration_option: The configuration options for this channel */ - virtual void RegisterService( - Psm psm, - DynamicChannelConfigurationOption configuration_option, - const SecurityPolicy& security_policy, - OnRegistrationCompleteCallback on_registration_complete, - OnConnectionOpenCallback on_connection_open); + virtual void RegisterService(Psm psm, DynamicChannelConfigurationOption configuration_option, + const SecurityPolicy& security_policy, + OnRegistrationCompleteCallback on_registration_complete, + OnConnectionOpenCallback on_connection_open); friend class L2capClassicModule; @@ -127,18 +128,20 @@ class DynamicChannelManager { virtual ~DynamicChannelManager() = default; - protected: +protected: DynamicChannelManager() = default; - private: +private: // The constructor is not to be used by user code DynamicChannelManager(internal::DynamicChannelServiceManagerImpl* service_manager, internal::LinkManager* link_manager, os::Handler* l2cap_layer_handler) - : service_manager_(service_manager), link_manager_(link_manager), l2cap_layer_handler_(l2cap_layer_handler) { + : service_manager_(service_manager), + link_manager_(link_manager), + l2cap_layer_handler_(l2cap_layer_handler) { log::assert_that(service_manager_ != nullptr, "assert failed: service_manager_ != nullptr"); log::assert_that(link_manager_ != nullptr, "assert failed: link_manager_ != nullptr"); - log::assert_that( - l2cap_layer_handler_ != nullptr, "assert failed: l2cap_layer_handler_ != nullptr"); + log::assert_that(l2cap_layer_handler_ != nullptr, + "assert failed: l2cap_layer_handler_ != nullptr"); } internal::DynamicChannelServiceManagerImpl* service_manager_ = nullptr; internal::LinkManager* link_manager_ = nullptr; diff --git a/system/gd/l2cap/classic/dynamic_channel_service.cc b/system/gd/l2cap/classic/dynamic_channel_service.cc index e9deb3822f0..748f6788cc1 100644 --- a/system/gd/l2cap/classic/dynamic_channel_service.cc +++ b/system/gd/l2cap/classic/dynamic_channel_service.cc @@ -15,6 +15,7 @@ */ #include "l2cap/classic/dynamic_channel_service.h" + #include "common/bind.h" #include "l2cap/classic/internal/dynamic_channel_service_manager_impl.h" @@ -24,13 +25,11 @@ namespace classic { void DynamicChannelService::Unregister(OnUnregisteredCallback on_unregistered) { log::assert_that(manager_ != nullptr, "this service is invalid"); - l2cap_layer_handler_->CallOn( - manager_, &internal::DynamicChannelServiceManagerImpl::Unregister, psm_, std::move(on_unregistered)); + l2cap_layer_handler_->CallOn(manager_, &internal::DynamicChannelServiceManagerImpl::Unregister, + psm_, std::move(on_unregistered)); } -Psm DynamicChannelService::GetPsm() const { - return psm_; -} +Psm DynamicChannelService::GetPsm() const { return psm_; } } // namespace classic } // namespace l2cap diff --git a/system/gd/l2cap/classic/dynamic_channel_service.h b/system/gd/l2cap/classic/dynamic_channel_service.h index 4760e92b824..87be835304f 100644 --- a/system/gd/l2cap/classic/dynamic_channel_service.h +++ b/system/gd/l2cap/classic/dynamic_channel_service.h @@ -32,7 +32,7 @@ class DynamicChannelServiceManagerImpl; } class DynamicChannelService { - public: +public: DynamicChannelService() = default; DynamicChannelService(const DynamicChannelService&) = delete; DynamicChannelService& operator=(const DynamicChannelService&) = delete; @@ -51,16 +51,17 @@ class DynamicChannelService { Psm GetPsm() const; - protected: - DynamicChannelService(Psm psm, internal::DynamicChannelServiceManagerImpl* manager, os::Handler* handler) +protected: + DynamicChannelService(Psm psm, internal::DynamicChannelServiceManagerImpl* manager, + os::Handler* handler) : psm_(psm), manager_(manager), l2cap_layer_handler_(handler) { log::assert_that(IsPsmValid(psm), "assert failed: IsPsmValid(psm)"); log::assert_that(manager_ != nullptr, "assert failed: manager_ != nullptr"); - log::assert_that( - l2cap_layer_handler_ != nullptr, "assert failed: l2cap_layer_handler_ != nullptr"); + log::assert_that(l2cap_layer_handler_ != nullptr, + "assert failed: l2cap_layer_handler_ != nullptr"); } - private: +private: Psm psm_ = kDefaultPsm; internal::DynamicChannelServiceManagerImpl* manager_ = nullptr; os::Handler* l2cap_layer_handler_; diff --git a/system/gd/l2cap/classic/facade.cc b/system/gd/l2cap/classic/facade.cc index ae0d76e20fe..b4c9b7916ed 100644 --- a/system/gd/l2cap/classic/facade.cc +++ b/system/gd/l2cap/classic/facade.cc @@ -44,8 +44,9 @@ namespace classic { using namespace blueberry::facade::l2cap::classic; -class L2capClassicModuleFacadeService : public L2capClassicModuleFacade::Service, public LinkSecurityInterfaceListener { - public: +class L2capClassicModuleFacadeService : public L2capClassicModuleFacade::Service, + public LinkSecurityInterfaceListener { +public: L2capClassicModuleFacadeService(L2capClassicModule* l2cap_layer, os::Handler* facade_handler) : l2cap_layer_(l2cap_layer), facade_handler_(facade_handler), security_interface_(nullptr) { log::assert_that(l2cap_layer_ != nullptr, "assert failed: l2cap_layer_ != nullptr"); @@ -53,23 +54,20 @@ class L2capClassicModuleFacadeService : public L2capClassicModuleFacade::Service } ::grpc::Status FetchConnectionComplete( - ::grpc::ServerContext* context, - const ::google::protobuf::Empty* /* request */, - ::grpc::ServerWriter* writer) override { + ::grpc::ServerContext* context, const ::google::protobuf::Empty* /* request */, + ::grpc::ServerWriter* writer) override { return pending_connection_complete_.RunLoop(context, writer); } ::grpc::Status FetchConnectionClose( - ::grpc::ServerContext* context, - const ::google::protobuf::Empty* /* request */, - ::grpc::ServerWriter* writer) override { + ::grpc::ServerContext* context, const ::google::protobuf::Empty* /* request */, + ::grpc::ServerWriter* writer) override { return pending_connection_close_.RunLoop(context, writer); } - ::grpc::Status SendDynamicChannelPacket( - ::grpc::ServerContext* /* context */, - const DynamicChannelPacket* request, - ::google::protobuf::Empty* /* response */) override { + ::grpc::Status SendDynamicChannelPacket(::grpc::ServerContext* /* context */, + const DynamicChannelPacket* request, + ::google::protobuf::Empty* /* response */) override { std::unique_lock lock(channel_map_mutex_); if (dynamic_channel_helper_map_.find(request->psm()) == dynamic_channel_helper_map_.end()) { return ::grpc::Status(::grpc::StatusCode::FAILED_PRECONDITION, "Psm not registered"); @@ -81,26 +79,23 @@ class L2capClassicModuleFacadeService : public L2capClassicModuleFacade::Service return ::grpc::Status::OK; } - ::grpc::Status OpenChannel( - ::grpc::ServerContext* /* context */, - const ::bluetooth::l2cap::classic::OpenChannelRequest* request, - ::google::protobuf::Empty* /* response */) override { + ::grpc::Status OpenChannel(::grpc::ServerContext* /* context */, + const ::bluetooth::l2cap::classic::OpenChannelRequest* request, + ::google::protobuf::Empty* /* response */) override { auto service_helper = dynamic_channel_helper_map_.find(request->psm()); if (service_helper == dynamic_channel_helper_map_.end()) { return ::grpc::Status(::grpc::StatusCode::FAILED_PRECONDITION, "Psm not registered"); } hci::Address peer; - log::assert_that( - hci::Address::FromString(request->remote().address(), peer), - "assert failed: hci::Address::FromString(request->remote().address(), peer)"); + log::assert_that(hci::Address::FromString(request->remote().address(), peer), + "assert failed: hci::Address::FromString(request->remote().address(), peer)"); dynamic_channel_helper_map_[request->psm()]->Connect(peer); return ::grpc::Status::OK; } - ::grpc::Status CloseChannel( - ::grpc::ServerContext* /* context */, - const ::bluetooth::l2cap::classic::CloseChannelRequest* request, - ::google::protobuf::Empty* /* response */) override { + ::grpc::Status CloseChannel(::grpc::ServerContext* /* context */, + const ::bluetooth::l2cap::classic::CloseChannelRequest* request, + ::google::protobuf::Empty* /* response */) override { auto psm = request->psm(); if (dynamic_channel_helper_map_.find(request->psm()) == dynamic_channel_helper_map_.end()) { return ::grpc::Status(::grpc::StatusCode::FAILED_PRECONDITION, "Psm not registered"); @@ -109,29 +104,27 @@ class L2capClassicModuleFacadeService : public L2capClassicModuleFacade::Service return ::grpc::Status::OK; } - ::grpc::Status FetchL2capData( - ::grpc::ServerContext* context, - const ::google::protobuf::Empty* /* request */, - ::grpc::ServerWriter* writer) override { + ::grpc::Status FetchL2capData(::grpc::ServerContext* context, + const ::google::protobuf::Empty* /* request */, + ::grpc::ServerWriter* writer) override { auto status = pending_l2cap_data_.RunLoop(context, writer); return status; } - ::grpc::Status SetDynamicChannel( - ::grpc::ServerContext* /* context */, - const SetEnableDynamicChannelRequest* request, - google::protobuf::Empty* /* response */) override { - dynamic_channel_helper_map_.emplace( - request->psm(), std::make_unique(this, l2cap_layer_, facade_handler_, request->psm(), - request->retransmission_mode())); + ::grpc::Status SetDynamicChannel(::grpc::ServerContext* /* context */, + const SetEnableDynamicChannelRequest* request, + google::protobuf::Empty* /* response */) override { + dynamic_channel_helper_map_.emplace(request->psm(), + std::make_unique( + this, l2cap_layer_, facade_handler_, request->psm(), + request->retransmission_mode())); return ::grpc::Status::OK; } - ::grpc::Status SetTrafficPaused( - ::grpc::ServerContext* /* context */, - const SetTrafficPausedRequest* request, - ::google::protobuf::Empty* /* response */) override { + ::grpc::Status SetTrafficPaused(::grpc::ServerContext* /* context */, + const SetTrafficPausedRequest* request, + ::google::protobuf::Empty* /* response */) override { auto psm = request->psm(); if (dynamic_channel_helper_map_.find(request->psm()) == dynamic_channel_helper_map_.end()) { return ::grpc::Status(::grpc::StatusCode::FAILED_PRECONDITION, "Psm not registered"); @@ -144,32 +137,27 @@ class L2capClassicModuleFacadeService : public L2capClassicModuleFacade::Service return ::grpc::Status::OK; } - ::grpc::Status GetChannelQueueDepth( - ::grpc::ServerContext* /* context */, - const ::google::protobuf::Empty* /* request */, - GetChannelQueueDepthResponse* response) override { + ::grpc::Status GetChannelQueueDepth(::grpc::ServerContext* /* context */, + const ::google::protobuf::Empty* /* request */, + GetChannelQueueDepthResponse* response) override { // Use the value kChannelQueueSize (5) in internal/dynamic_channel_impl.h response->set_size(5); return ::grpc::Status::OK; } - ::grpc::Status InitiateConnectionForSecurity( - ::grpc::ServerContext* /* context */, - const blueberry::facade::BluetoothAddress* request, - ::google::protobuf::Empty* /* response */) override { + ::grpc::Status InitiateConnectionForSecurity(::grpc::ServerContext* /* context */, + const blueberry::facade::BluetoothAddress* request, + ::google::protobuf::Empty* /* response */) override { hci::Address peer; - log::assert_that( - hci::Address::FromString(request->address(), peer), - "assert failed: hci::Address::FromString(request->address(), peer)"); + log::assert_that(hci::Address::FromString(request->address(), peer), + "assert failed: hci::Address::FromString(request->address(), peer)"); outgoing_pairing_remote_devices_.insert(peer); security_interface_->InitiateConnectionForSecurity(peer); return ::grpc::Status::OK; } - void SecurityConnectionEventOccurred( - hci::ErrorCode /* hci_status */, - hci::Address remote, - LinkSecurityInterfaceCallbackEventType event_type) { + void SecurityConnectionEventOccurred(hci::ErrorCode /* hci_status */, hci::Address remote, + LinkSecurityInterfaceCallbackEventType event_type) { LinkSecurityInterfaceCallbackEvent msg; msg.mutable_address()->set_address(remote.ToString()); msg.set_event_type(event_type); @@ -177,21 +165,18 @@ class L2capClassicModuleFacadeService : public L2capClassicModuleFacade::Service } ::grpc::Status FetchSecurityConnectionEvents( - ::grpc::ServerContext* context, - const ::google::protobuf::Empty* /* request */, - ::grpc::ServerWriter* writer) override { + ::grpc::ServerContext* context, const ::google::protobuf::Empty* /* request */, + ::grpc::ServerWriter* writer) override { security_interface_ = l2cap_layer_->GetSecurityInterface(facade_handler_, this); return security_connection_events_.RunLoop(context, writer); } - ::grpc::Status SecurityLinkHold( - ::grpc::ServerContext* /* context */, - const blueberry::facade::BluetoothAddress* request, - ::google::protobuf::Empty* /* response */) override { + ::grpc::Status SecurityLinkHold(::grpc::ServerContext* /* context */, + const blueberry::facade::BluetoothAddress* request, + ::google::protobuf::Empty* /* response */) override { hci::Address peer; - log::assert_that( - hci::Address::FromString(request->address(), peer), - "assert failed: hci::Address::FromString(request->address(), peer)"); + log::assert_that(hci::Address::FromString(request->address(), peer), + "assert failed: hci::Address::FromString(request->address(), peer)"); auto entry = security_link_map_.find(peer); if (entry == security_link_map_.end()) { log::warn("Unknown address '{}'", peer); @@ -202,13 +187,11 @@ class L2capClassicModuleFacadeService : public L2capClassicModuleFacade::Service } ::grpc::Status SecurityLinkEnsureAuthenticated( - ::grpc::ServerContext* /* context */, - const blueberry::facade::BluetoothAddress* request, - ::google::protobuf::Empty* /* response */) override { + ::grpc::ServerContext* /* context */, const blueberry::facade::BluetoothAddress* request, + ::google::protobuf::Empty* /* response */) override { hci::Address peer; - log::assert_that( - hci::Address::FromString(request->address(), peer), - "assert failed: hci::Address::FromString(request->address(), peer)"); + log::assert_that(hci::Address::FromString(request->address(), peer), + "assert failed: hci::Address::FromString(request->address(), peer)"); auto entry = security_link_map_.find(peer); if (entry == security_link_map_.end()) { log::warn("Unknown address '{}'", peer); @@ -218,14 +201,12 @@ class L2capClassicModuleFacadeService : public L2capClassicModuleFacade::Service return ::grpc::Status::OK; } - ::grpc::Status SecurityLinkRelease( - ::grpc::ServerContext* /* context */, - const blueberry::facade::BluetoothAddress* request, - ::google::protobuf::Empty* /* response */) override { + ::grpc::Status SecurityLinkRelease(::grpc::ServerContext* /* context */, + const blueberry::facade::BluetoothAddress* request, + ::google::protobuf::Empty* /* response */) override { hci::Address peer; - log::assert_that( - hci::Address::FromString(request->address(), peer), - "assert failed: hci::Address::FromString(request->address(), peer)"); + log::assert_that(hci::Address::FromString(request->address(), peer), + "assert failed: hci::Address::FromString(request->address(), peer)"); outgoing_pairing_remote_devices_.erase(peer); auto entry = security_link_map_.find(peer); if (entry == security_link_map_.end()) { @@ -236,14 +217,12 @@ class L2capClassicModuleFacadeService : public L2capClassicModuleFacade::Service return ::grpc::Status::OK; } - ::grpc::Status SecurityLinkDisconnect( - ::grpc::ServerContext* /* context */, - const blueberry::facade::BluetoothAddress* request, - ::google::protobuf::Empty* /* response */) override { + ::grpc::Status SecurityLinkDisconnect(::grpc::ServerContext* /* context */, + const blueberry::facade::BluetoothAddress* request, + ::google::protobuf::Empty* /* response */) override { hci::Address peer; - log::assert_that( - hci::Address::FromString(request->address(), peer), - "assert failed: hci::Address::FromString(request->address(), peer)"); + log::assert_that(hci::Address::FromString(request->address(), peer), + "assert failed: hci::Address::FromString(request->address(), peer)"); outgoing_pairing_remote_devices_.erase(peer); auto entry = security_link_map_.find(peer); if (entry == security_link_map_.end()) { @@ -262,8 +241,8 @@ class L2capClassicModuleFacadeService : public L2capClassicModuleFacade::Service outgoing_pairing_remote_devices_.erase(remote); } security_link_map_.emplace(remote, std::move(link)); - SecurityConnectionEventOccurred( - hci::ErrorCode::SUCCESS, remote, LinkSecurityInterfaceCallbackEventType::ON_CONNECTED); + SecurityConnectionEventOccurred(hci::ErrorCode::SUCCESS, remote, + LinkSecurityInterfaceCallbackEventType::ON_CONNECTED); } void OnLinkDisconnected(hci::Address remote) override { @@ -274,8 +253,8 @@ class L2capClassicModuleFacadeService : public L2capClassicModuleFacade::Service } entry->second.reset(); security_link_map_.erase(entry); - SecurityConnectionEventOccurred( - hci::ErrorCode::SUCCESS, remote, LinkSecurityInterfaceCallbackEventType::ON_DISCONNECTED); + SecurityConnectionEventOccurred(hci::ErrorCode::SUCCESS, remote, + LinkSecurityInterfaceCallbackEventType::ON_DISCONNECTED); } void OnAuthenticationComplete(hci::ErrorCode hci_status, hci::Address remote) override { @@ -285,28 +264,34 @@ class L2capClassicModuleFacadeService : public L2capClassicModuleFacade::Service return; } SecurityConnectionEventOccurred( - hci_status, remote, LinkSecurityInterfaceCallbackEventType::ON_AUTHENTICATION_COMPLETE); + hci_status, remote, LinkSecurityInterfaceCallbackEventType::ON_AUTHENTICATION_COMPLETE); } void OnEncryptionChange(hci::Address remote, bool /* encrypted */) override { - SecurityConnectionEventOccurred( - hci::ErrorCode::SUCCESS, remote, LinkSecurityInterfaceCallbackEventType::ON_ENCRYPTION_CHANGE); + SecurityConnectionEventOccurred(hci::ErrorCode::SUCCESS, remote, + LinkSecurityInterfaceCallbackEventType::ON_ENCRYPTION_CHANGE); } class L2capDynamicChannelHelper { - public: - L2capDynamicChannelHelper(L2capClassicModuleFacadeService* service, L2capClassicModule* l2cap_layer, - os::Handler* handler, Psm psm, RetransmissionFlowControlMode mode) - : facade_service_(service), l2cap_layer_(l2cap_layer), handler_(handler), psm_(psm), mode_(mode) { + public: + L2capDynamicChannelHelper(L2capClassicModuleFacadeService* service, + L2capClassicModule* l2cap_layer, os::Handler* handler, Psm psm, + RetransmissionFlowControlMode mode) + : facade_service_(service), + l2cap_layer_(l2cap_layer), + handler_(handler), + psm_(psm), + mode_(mode) { dynamic_channel_manager_ = l2cap_layer_->GetDynamicChannelManager(); DynamicChannelConfigurationOption configuration_option = {}; - configuration_option.channel_mode = (DynamicChannelConfigurationOption::RetransmissionAndFlowControlMode)mode; + configuration_option.channel_mode = + (DynamicChannelConfigurationOption::RetransmissionAndFlowControlMode)mode; dynamic_channel_manager_->RegisterService( - psm, - configuration_option, - SecurityPolicy::_SDP_ONLY_NO_SECURITY_WHATSOEVER_PLAINTEXT_TRANSPORT_OK, - handler_->BindOnceOn(this, &L2capDynamicChannelHelper::on_l2cap_service_registration_complete), - handler_->BindOn(this, &L2capDynamicChannelHelper::on_connection_open)); + psm, configuration_option, + SecurityPolicy::_SDP_ONLY_NO_SECURITY_WHATSOEVER_PLAINTEXT_TRANSPORT_OK, + handler_->BindOnceOn( + this, &L2capDynamicChannelHelper::on_l2cap_service_registration_complete), + handler_->BindOn(this, &L2capDynamicChannelHelper::on_connection_open)); } ~L2capDynamicChannelHelper() { @@ -318,17 +303,18 @@ class L2capClassicModuleFacadeService : public L2capClassicModuleFacade::Service } void Connect(hci::Address address) { - DynamicChannelConfigurationOption configuration_option = l2cap::classic::DynamicChannelConfigurationOption(); - configuration_option.channel_mode = (DynamicChannelConfigurationOption::RetransmissionAndFlowControlMode)mode_; + DynamicChannelConfigurationOption configuration_option = + l2cap::classic::DynamicChannelConfigurationOption(); + configuration_option.channel_mode = + (DynamicChannelConfigurationOption::RetransmissionAndFlowControlMode)mode_; dynamic_channel_manager_->ConnectChannel( - address, - configuration_option, - psm_, - handler_->BindOn(this, &L2capDynamicChannelHelper::on_connection_open), - handler_->BindOnceOn(this, &L2capDynamicChannelHelper::on_connect_fail)); + address, configuration_option, psm_, + handler_->BindOn(this, &L2capDynamicChannelHelper::on_connection_open), + handler_->BindOnceOn(this, &L2capDynamicChannelHelper::on_connect_fail)); std::unique_lock lock(channel_open_cv_mutex_); - if (!channel_open_cv_.wait_for(lock, std::chrono::seconds(2), [this] { return channel_ != nullptr; })) { + if (!channel_open_cv_.wait_for(lock, std::chrono::seconds(2), + [this] { return channel_ != nullptr; })) { log::warn("Channel is not open for psm {}", psm_); } } @@ -336,7 +322,8 @@ class L2capClassicModuleFacadeService : public L2capClassicModuleFacade::Service void Disconnect() { if (channel_ == nullptr) { std::unique_lock lock(channel_open_cv_mutex_); - if (!channel_open_cv_.wait_for(lock, std::chrono::seconds(2), [this] { return channel_ != nullptr; })) { + if (!channel_open_cv_.wait_for(lock, std::chrono::seconds(2), + [this] { return channel_ != nullptr; })) { log::warn("Channel is not open for psm {}", psm_); return; } @@ -345,8 +332,8 @@ class L2capClassicModuleFacadeService : public L2capClassicModuleFacade::Service } void on_l2cap_service_registration_complete( - DynamicChannelManager::RegistrationResult /* registration_result */, - std::unique_ptr /* service */) {} + DynamicChannelManager::RegistrationResult /* registration_result */, + std::unique_ptr /* service */) {} // invoked from Facade Handler void on_connection_open(std::unique_ptr channel) { @@ -356,15 +343,17 @@ class L2capClassicModuleFacadeService : public L2capClassicModuleFacade::Service { std::unique_lock lock(channel_open_cv_mutex_); channel_ = std::move(channel); - enqueue_buffer_ = std::make_unique>(channel_->GetQueueUpEnd()); + enqueue_buffer_ = + std::make_unique>(channel_->GetQueueUpEnd()); } channel_open_cv_.notify_all(); - channel_->RegisterOnCloseCallback( - facade_service_->facade_handler_->BindOnceOn(this, &L2capDynamicChannelHelper::on_close_callback)); + channel_->RegisterOnCloseCallback(facade_service_->facade_handler_->BindOnceOn( + this, &L2capDynamicChannelHelper::on_close_callback)); dequeue_registered_ = true; channel_->GetQueueUpEnd()->RegisterDequeue( - facade_service_->facade_handler_, - common::Bind(&L2capDynamicChannelHelper::on_incoming_packet, common::Unretained(this))); + facade_service_->facade_handler_, + common::Bind(&L2capDynamicChannelHelper::on_incoming_packet, + common::Unretained(this))); } void on_close_callback(hci::ErrorCode error_code) { @@ -391,8 +380,9 @@ class L2capClassicModuleFacadeService : public L2capClassicModuleFacade::Service void ResumeDequeue() { if (!dequeue_registered_.exchange(true)) { channel_->GetQueueUpEnd()->RegisterDequeue( - facade_service_->facade_handler_, - common::Bind(&L2capDynamicChannelHelper::on_incoming_packet, common::Unretained(this))); + facade_service_->facade_handler_, + common::Bind(&L2capDynamicChannelHelper::on_incoming_packet, + common::Unretained(this))); } } @@ -410,7 +400,8 @@ class L2capClassicModuleFacadeService : public L2capClassicModuleFacade::Service bool SendPacket(std::vector packet) { if (channel_ == nullptr) { std::unique_lock lock(channel_open_cv_mutex_); - if (!channel_open_cv_.wait_for(lock, std::chrono::seconds(2), [this] { return channel_ != nullptr; })) { + if (!channel_open_cv_.wait_for(lock, std::chrono::seconds(2), + [this] { return channel_ != nullptr; })) { log::warn("Channel is not open"); return false; } @@ -439,13 +430,15 @@ class L2capClassicModuleFacadeService : public L2capClassicModuleFacade::Service std::mutex channel_map_mutex_; std::map> dynamic_channel_helper_map_; ::bluetooth::grpc::GrpcEventQueue pending_connection_complete_{ - "FetchConnectionComplete"}; - ::bluetooth::grpc::GrpcEventQueue pending_connection_close_{"FetchConnectionClose"}; + "FetchConnectionComplete"}; + ::bluetooth::grpc::GrpcEventQueue pending_connection_close_{ + "FetchConnectionClose"}; ::bluetooth::grpc::GrpcEventQueue pending_l2cap_data_{"FetchL2capData"}; ::bluetooth::grpc::GrpcEventQueue security_connection_events_{ - "Security Connection Events"}; + "Security Connection Events"}; SecurityInterface* security_interface_; - std::unordered_map> security_link_map_; + std::unordered_map> + security_link_map_; std::set outgoing_pairing_remote_devices_; }; @@ -456,7 +449,8 @@ void L2capClassicModuleFacadeModule::ListDependencies(ModuleList* list) const { void L2capClassicModuleFacadeModule::Start() { ::bluetooth::grpc::GrpcFacadeModule::Start(); - service_ = new L2capClassicModuleFacadeService(GetDependency(), GetHandler()); + service_ = new L2capClassicModuleFacadeService( + GetDependency(), GetHandler()); } void L2capClassicModuleFacadeModule::Stop() { @@ -464,12 +458,10 @@ void L2capClassicModuleFacadeModule::Stop() { ::bluetooth::grpc::GrpcFacadeModule::Stop(); } -::grpc::Service* L2capClassicModuleFacadeModule::GetService() const { - return service_; -} +::grpc::Service* L2capClassicModuleFacadeModule::GetService() const { return service_; } const ModuleFactory L2capClassicModuleFacadeModule::Factory = - ::bluetooth::ModuleFactory([]() { return new L2capClassicModuleFacadeModule(); }); + ::bluetooth::ModuleFactory([]() { return new L2capClassicModuleFacadeModule(); }); } // namespace classic } // namespace l2cap diff --git a/system/gd/l2cap/classic/facade.h b/system/gd/l2cap/classic/facade.h index f699d1ef7d6..9d4a6c8aff9 100644 --- a/system/gd/l2cap/classic/facade.h +++ b/system/gd/l2cap/classic/facade.h @@ -26,7 +26,7 @@ namespace classic { class L2capClassicModuleFacadeService; class L2capClassicModuleFacadeModule : public ::bluetooth::grpc::GrpcFacadeModule { - public: +public: static const ModuleFactory Factory; void ListDependencies(ModuleList* list) const override; @@ -35,7 +35,7 @@ class L2capClassicModuleFacadeModule : public ::bluetooth::grpc::GrpcFacadeModul ::grpc::Service* GetService() const override; - private: +private: L2capClassicModuleFacadeService* service_; }; diff --git a/system/gd/l2cap/classic/fixed_channel.cc b/system/gd/l2cap/classic/fixed_channel.cc index a90d1198aba..20a117d3d6a 100644 --- a/system/gd/l2cap/classic/fixed_channel.cc +++ b/system/gd/l2cap/classic/fixed_channel.cc @@ -15,6 +15,7 @@ */ #include "l2cap/classic/fixed_channel.h" + #include "common/bind.h" #include "l2cap/classic/internal/fixed_channel_impl.h" @@ -22,13 +23,12 @@ namespace bluetooth { namespace l2cap { namespace classic { -hci::Address FixedChannel::GetDevice() const { - return impl_->GetDevice(); -} +hci::Address FixedChannel::GetDevice() const { return impl_->GetDevice(); } -void FixedChannel::RegisterOnCloseCallback(os::Handler* user_handler, FixedChannel::OnCloseCallback on_close_callback) { - l2cap_handler_->Post(common::BindOnce(&internal::FixedChannelImpl::RegisterOnCloseCallback, impl_, user_handler, - std::move(on_close_callback))); +void FixedChannel::RegisterOnCloseCallback(os::Handler* user_handler, + FixedChannel::OnCloseCallback on_close_callback) { + l2cap_handler_->Post(common::BindOnce(&internal::FixedChannelImpl::RegisterOnCloseCallback, impl_, + user_handler, std::move(on_close_callback))); } void FixedChannel::Acquire() { diff --git a/system/gd/l2cap/classic/fixed_channel.h b/system/gd/l2cap/classic/fixed_channel.h index adec45ba0b9..4e8bdf17259 100644 --- a/system/gd/l2cap/classic/fixed_channel.h +++ b/system/gd/l2cap/classic/fixed_channel.h @@ -38,7 +38,7 @@ class FixedChannelImpl; * */ class FixedChannel { - public: +public: // Should only be constructed by modules that have access to LinkManager FixedChannel(std::shared_ptr impl, os::Handler* l2cap_handler) : impl_(std::move(impl)), l2cap_handler_(l2cap_handler) { @@ -49,9 +49,10 @@ class FixedChannel { hci::Address GetDevice() const; /** - * Register close callback. If close callback is registered, when a channel is closed, the channel's resource will - * only be freed after on_close callback is invoked. Otherwise, if no on_close callback is registered, the channel's - * resource will be freed immediately after closing. + * Register close callback. If close callback is registered, when a channel is closed, the + * channel's resource will only be freed after on_close callback is invoked. Otherwise, if no + * on_close callback is registered, the channel's resource will be freed immediately after + * closing. * * @param user_handler The handler used to invoke the callback on * @param on_close_callback The callback invoked upon channel closing. @@ -60,14 +61,16 @@ class FixedChannel { void RegisterOnCloseCallback(os::Handler* user_handler, OnCloseCallback on_close_callback); /** - * Indicate that this Fixed Channel is being used. This will prevent ACL connection from being disconnected. + * Indicate that this Fixed Channel is being used. This will prevent ACL connection from being + * disconnected. */ void Acquire(); /** - * Indicate that this Fixed Channel is no longer being used. ACL connection will be disconnected after - * kLinkIdleDisconnectTimeout if no other DynamicChannel is connected or no other Fixed Channel is using this - * ACL connection. However a module can still receive data on this channel as long as it remains open. + * Indicate that this Fixed Channel is no longer being used. ACL connection will be disconnected + * after kLinkIdleDisconnectTimeout if no other DynamicChannel is connected or no other Fixed + * Channel is using this ACL connection. However a module can still receive data on this channel + * as long as it remains open. */ void Release(); @@ -78,9 +81,10 @@ class FixedChannel { * * @return The upper end of a bi-directional queue. */ - common::BidiQueueEnd>* GetQueueUpEnd() const; + common::BidiQueueEnd>* + GetQueueUpEnd() const; - private: +private: std::shared_ptr impl_; os::Handler* l2cap_handler_; }; diff --git a/system/gd/l2cap/classic/fixed_channel_manager.cc b/system/gd/l2cap/classic/fixed_channel_manager.cc index 24e78bd9f42..aabfbdfff51 100644 --- a/system/gd/l2cap/classic/fixed_channel_manager.cc +++ b/system/gd/l2cap/classic/fixed_channel_manager.cc @@ -15,6 +15,7 @@ */ #include "l2cap/classic/fixed_channel_manager.h" + #include "l2cap/classic/internal/fixed_channel_service_impl.h" #include "l2cap/classic/internal/fixed_channel_service_manager_impl.h" #include "l2cap/classic/internal/link_manager.h" @@ -23,11 +24,12 @@ namespace bluetooth { namespace l2cap { namespace classic { -bool FixedChannelManager::ConnectServices(hci::Address device, OnConnectionFailureCallback on_fail_callback, +bool FixedChannelManager::ConnectServices(hci::Address device, + OnConnectionFailureCallback on_fail_callback, os::Handler* handler) { internal::LinkManager::PendingFixedChannelConnection pending_fixed_channel_connection{ - .handler_ = handler, - .on_fail_callback_ = std::move(on_fail_callback), + .handler_ = handler, + .on_fail_callback_ = std::move(on_fail_callback), }; l2cap_layer_handler_->Post(common::BindOnce(&internal::LinkManager::ConnectFixedChannelServices, common::Unretained(link_manager_), device, @@ -35,12 +37,14 @@ bool FixedChannelManager::ConnectServices(hci::Address device, OnConnectionFailu return true; } -bool FixedChannelManager::RegisterService(Cid cid, OnRegistrationCompleteCallback on_registration_complete, - OnConnectionOpenCallback on_connection_open, os::Handler* handler) { +bool FixedChannelManager::RegisterService(Cid cid, + OnRegistrationCompleteCallback on_registration_complete, + OnConnectionOpenCallback on_connection_open, + os::Handler* handler) { internal::FixedChannelServiceImpl::PendingRegistration pending_registration{ - .user_handler_ = handler, - .on_registration_complete_callback_ = std::move(on_registration_complete), - .on_connection_open_callback_ = std::move(on_connection_open)}; + .user_handler_ = handler, + .on_registration_complete_callback_ = std::move(on_registration_complete), + .on_connection_open_callback_ = std::move(on_connection_open)}; l2cap_layer_handler_->Post(common::BindOnce(&internal::FixedChannelServiceManagerImpl::Register, common::Unretained(service_manager_), cid, std::move(pending_registration))); diff --git a/system/gd/l2cap/classic/fixed_channel_manager.h b/system/gd/l2cap/classic/fixed_channel_manager.h index 9c40bd1e545..eb032ad3437 100644 --- a/system/gd/l2cap/classic/fixed_channel_manager.h +++ b/system/gd/l2cap/classic/fixed_channel_manager.h @@ -40,7 +40,7 @@ class FixedChannelServiceManagerImpl; } // namespace internal class FixedChannelManager { - public: +public: enum class ConnectionResultCode { SUCCESS = 0, FAIL_NO_SERVICE_REGISTERED = 1, // No service is registered @@ -72,29 +72,32 @@ class FixedChannelManager { * OnRegistrationFailureCallback(RegistrationResult result, FixedChannelService service); */ using OnRegistrationCompleteCallback = - common::OnceCallback)>; + common::OnceCallback)>; /** * Connect to ALL fixed channels on a remote device * * - This method is asynchronous * - When false is returned, the connection fails immediately - * - When true is returned, method caller should wait for on_fail_callback or on_open_callback registered through - * RegisterService() API. - * - If an ACL connection does not exist, this method will create an ACL connection. As a result, on_open_callback - * supplied through RegisterService() will be triggered to provide the actual FixedChannel objects + * - When true is returned, method caller should wait for on_fail_callback or on_open_callback + * registered through RegisterService() API. + * - If an ACL connection does not exist, this method will create an ACL connection. As a result, + * on_open_callback supplied through RegisterService() will be triggered to provide the actual + * FixedChannel objects * - If HCI connection failed, on_fail_callback will be triggered with FAIL_HCI_ERROR - * - If fixed channel on a remote device is already reported as connected via on_open_callback and has been acquired - * via FixedChannel#Acquire() API, it won't be reported again - * - If no service is registered, on_fail_callback will be triggered with FAIL_NO_SERVICE_REGISTERED - * - If there is an ACL connection and channels for each service is allocated, on_fail_callback will be triggered with - * FAIL_ALL_SERVICES_HAVE_CHANNEL + * - If fixed channel on a remote device is already reported as connected via on_open_callback and + * has been acquired via FixedChannel#Acquire() API, it won't be reported again + * - If no service is registered, on_fail_callback will be triggered with + * FAIL_NO_SERVICE_REGISTERED + * - If there is an ACL connection and channels for each service is allocated, on_fail_callback + * will be triggered with FAIL_ALL_SERVICES_HAVE_CHANNEL * * NOTE: * This call will initiate an effort to connect all fixed channel services on a remote device. - * Due to the connectionless nature of fixed channels, all fixed channels will be connected together. - * If a fixed channel service does not need a particular fixed channel. It should release the received - * channel immediately after receiving on_open_callback via FixedChannel#Release() + * Due to the connectionless nature of fixed channels, all fixed channels will be connected + * together. If a fixed channel service does not need a particular fixed channel. It should + * release the received channel immediately after receiving on_open_callback via + * FixedChannel#Release() * * A module calling ConnectServices() must have called RegisterService() before. * The callback will come back from on_open_callback in the service that is registered @@ -105,25 +108,28 @@ class FixedChannelManager { * * Returns: true if connection was able to be initiated, false otherwise. */ - virtual bool ConnectServices(hci::Address device, OnConnectionFailureCallback on_fail_callback, os::Handler* handler); + virtual bool ConnectServices(hci::Address device, OnConnectionFailureCallback on_fail_callback, + os::Handler* handler); /** * Register a service to receive incoming connections bound to a specific channel. * * - This method is asynchronous. * - When false is returned, the registration fails immediately. - * - When true is returned, method caller should wait for on_service_registered callback that contains a - * FixedChannelService object. The registered service can be managed from that object. - * - If a CID is already registered or some other error happens, on_registration_complete will be triggered with a - * non-SUCCESS value - * - After a service is registered, any classic ACL connection will create a FixedChannel object that is - * delivered through on_open_callback + * - When true is returned, method caller should wait for on_service_registered callback that + * contains a FixedChannelService object. The registered service can be managed from that object. + * - If a CID is already registered or some other error happens, on_registration_complete will be + * triggered with a non-SUCCESS value + * - After a service is registered, any classic ACL connection will create a FixedChannel object + * that is delivered through on_open_callback * - on_open_callback, will only be triggered after on_service_registered callback * * @param cid: cid used to receive incoming connections - * @param on_registration_complete: A callback to indicate the service setup has completed. If the return status is - * not SUCCESS, it means service is not registered due to reasons like CID already take - * @param on_open_callback: A callback to indicate success of a connection initiated from a remote device. + * @param on_registration_complete: A callback to indicate the service setup has completed. If the + * return status is not SUCCESS, it means service is not registered due to reasons like CID + * already take + * @param on_open_callback: A callback to indicate success of a connection initiated from a remote + * device. * @param handler: The handler context in which to execute the @callback parameter. */ virtual bool RegisterService(Cid cid, OnRegistrationCompleteCallback on_registration_complete, @@ -137,11 +143,13 @@ class FixedChannelManager { friend class L2capClassicModule; friend class testing::MockFixedChannelManager; - private: +private: // The constructor is not to be used by user code - FixedChannelManager(internal::FixedChannelServiceManagerImpl* service_manager, internal::LinkManager* link_manager, - os::Handler* l2cap_layer_handler) - : service_manager_(service_manager), link_manager_(link_manager), l2cap_layer_handler_(l2cap_layer_handler) {} + FixedChannelManager(internal::FixedChannelServiceManagerImpl* service_manager, + internal::LinkManager* link_manager, os::Handler* l2cap_layer_handler) + : service_manager_(service_manager), + link_manager_(link_manager), + l2cap_layer_handler_(l2cap_layer_handler) {} internal::FixedChannelServiceManagerImpl* service_manager_ = nullptr; internal::LinkManager* link_manager_ = nullptr; diff --git a/system/gd/l2cap/classic/fixed_channel_manager_mock.h b/system/gd/l2cap/classic/fixed_channel_manager_mock.h index 513213e67bf..bfaec3be456 100644 --- a/system/gd/l2cap/classic/fixed_channel_manager_mock.h +++ b/system/gd/l2cap/classic/fixed_channel_manager_mock.h @@ -15,10 +15,10 @@ */ #pragma once -#include "l2cap/classic/fixed_channel_manager.h" - #include +#include "l2cap/classic/fixed_channel_manager.h" + // Unit test interfaces namespace bluetooth { namespace l2cap { @@ -26,10 +26,12 @@ namespace classic { namespace testing { class MockFixedChannelManager : public FixedChannelManager { - public: - MockFixedChannelManager() : FixedChannelManager(nullptr, nullptr, nullptr){}; +public: + MockFixedChannelManager() : FixedChannelManager(nullptr, nullptr, nullptr) {} MOCK_METHOD(bool, ConnectServices, - (hci::Address device, OnConnectionFailureCallback on_fail_callback, os::Handler* handler), (override)); + (hci::Address device, OnConnectionFailureCallback on_fail_callback, + os::Handler* handler), + (override)); MOCK_METHOD(bool, RegisterService, (Cid cid, OnRegistrationCompleteCallback on_registration_complete, OnConnectionOpenCallback on_connection_open, os::Handler* handler), diff --git a/system/gd/l2cap/classic/fixed_channel_mock.h b/system/gd/l2cap/classic/fixed_channel_mock.h index 417e776adac..82fb1725f4d 100644 --- a/system/gd/l2cap/classic/fixed_channel_mock.h +++ b/system/gd/l2cap/classic/fixed_channel_mock.h @@ -15,14 +15,14 @@ */ #pragma once -#include "l2cap/classic/fixed_channel.h" -#include "l2cap/classic/internal/fixed_channel_impl_mock.h" -#include "os/handler.h" - #include #include +#include "l2cap/classic/fixed_channel.h" +#include "l2cap/classic/internal/fixed_channel_impl_mock.h" +#include "os/handler.h" + // Unit test interfaces namespace bluetooth { namespace l2cap { @@ -30,11 +30,12 @@ namespace classic { namespace testing { class MockFixedChannel : public FixedChannel { - public: - MockFixedChannel() : FixedChannel(nullptr, nullptr){}; +public: + MockFixedChannel() : FixedChannel(nullptr, nullptr) {} MOCK_METHOD(void, Acquire, ()); MOCK_METHOD(void, Release, ()); - MOCK_METHOD(void, RegisterOnCloseCallback, (os::Handler * handler, OnCloseCallback on_close_callback)); + MOCK_METHOD(void, RegisterOnCloseCallback, + (os::Handler * handler, OnCloseCallback on_close_callback)); }; } // namespace testing diff --git a/system/gd/l2cap/classic/fixed_channel_service.cc b/system/gd/l2cap/classic/fixed_channel_service.cc index 13e4fc1c69b..3a87a1b780b 100644 --- a/system/gd/l2cap/classic/fixed_channel_service.cc +++ b/system/gd/l2cap/classic/fixed_channel_service.cc @@ -15,6 +15,7 @@ */ #include "l2cap/classic/fixed_channel_service.h" + #include "common/bind.h" #include "l2cap/classic/internal/fixed_channel_service_manager_impl.h" @@ -22,11 +23,12 @@ namespace bluetooth { namespace l2cap { namespace classic { -void FixedChannelService::Unregister(OnUnregisteredCallback on_unregistered, os::Handler* on_unregistered_handler) { +void FixedChannelService::Unregister(OnUnregisteredCallback on_unregistered, + os::Handler* on_unregistered_handler) { log::assert_that(manager_ != nullptr, "this service is invalid"); l2cap_layer_handler_->Post(common::BindOnce(&internal::FixedChannelServiceManagerImpl::Unregister, - common::Unretained(manager_), cid_, std::move(on_unregistered), - on_unregistered_handler)); + common::Unretained(manager_), cid_, + std::move(on_unregistered), on_unregistered_handler)); } } // namespace classic diff --git a/system/gd/l2cap/classic/fixed_channel_service.h b/system/gd/l2cap/classic/fixed_channel_service.h index 447d3a80bde..29ac93a4a5e 100644 --- a/system/gd/l2cap/classic/fixed_channel_service.h +++ b/system/gd/l2cap/classic/fixed_channel_service.h @@ -30,7 +30,7 @@ class FixedChannelServiceManagerImpl; } // namespace internal class FixedChannelService { - public: +public: FixedChannelService() = default; FixedChannelService(const FixedChannelService&) = delete; FixedChannelService& operator=(const FixedChannelService&) = delete; @@ -47,8 +47,9 @@ class FixedChannelService { friend internal::FixedChannelServiceManagerImpl; - private: - FixedChannelService(Cid cid, internal::FixedChannelServiceManagerImpl* manager, os::Handler* handler) +private: + FixedChannelService(Cid cid, internal::FixedChannelServiceManagerImpl* manager, + os::Handler* handler) : cid_(cid), manager_(manager), l2cap_layer_handler_(handler) {} Cid cid_ = kInvalidCid; internal::FixedChannelServiceManagerImpl* manager_ = nullptr; diff --git a/system/gd/l2cap/classic/fixed_channel_service_mock.h b/system/gd/l2cap/classic/fixed_channel_service_mock.h index 6695cd1b20f..f6997ce0e12 100644 --- a/system/gd/l2cap/classic/fixed_channel_service_mock.h +++ b/system/gd/l2cap/classic/fixed_channel_service_mock.h @@ -15,10 +15,10 @@ */ #pragma once -#include "l2cap/classic/fixed_channel_service.h" - #include +#include "l2cap/classic/fixed_channel_service.h" + // Unit test interfaces namespace bluetooth { namespace l2cap { @@ -26,9 +26,10 @@ namespace classic { namespace testing { class MockFixedChannelService : public FixedChannelService { - public: - MockFixedChannelService() : FixedChannelService(){}; - MOCK_METHOD(void, Unregister, (OnUnregisteredCallback on_unregistered, os::Handler* on_unregistered_handler)); +public: + MockFixedChannelService() : FixedChannelService() {} + MOCK_METHOD(void, Unregister, + (OnUnregisteredCallback on_unregistered, os::Handler* on_unregistered_handler)); }; } // namespace testing diff --git a/system/gd/l2cap/classic/internal/channel_configuration_state.h b/system/gd/l2cap/classic/internal/channel_configuration_state.h index cee905ed4d7..2ebc2f20939 100644 --- a/system/gd/l2cap/classic/internal/channel_configuration_state.h +++ b/system/gd/l2cap/classic/internal/channel_configuration_state.h @@ -25,21 +25,22 @@ namespace classic { namespace internal { struct ChannelConfigurationState { - public: +public: enum State { /** - * for the initiator path, a request has been sent but a positive response has not yet been received, and for the - * acceptor path, a request with acceptable options has not yet been received. + * for the initiator path, a request has been sent but a positive response has not yet been + * received, and for the acceptor path, a request with acceptable options has not yet been + * received. */ WAIT_CONFIG_REQ_RSP, /** - * the acceptor path is complete after having responded to acceptable options, but for the initiator path, a - * positive response on the recent request has not yet been received. + * the acceptor path is complete after having responded to acceptable options, but for the + * initiator path, a positive response on the recent request has not yet been received. */ WAIT_CONFIG_RSP, /** - * the initiator path is complete after having received a positive response, but for the acceptor path, a request - * with acceptable options has not yet been received. + * the initiator path is complete after having received a positive response, but for the + * acceptor path, a request with acceptable options has not yet been received. */ WAIT_CONFIG_REQ, /** diff --git a/system/gd/l2cap/classic/internal/dumpsys_helper.cc b/system/gd/l2cap/classic/internal/dumpsys_helper.cc index d69d690d82c..c107bd6af98 100644 --- a/system/gd/l2cap/classic/internal/dumpsys_helper.cc +++ b/system/gd/l2cap/classic/internal/dumpsys_helper.cc @@ -14,9 +14,10 @@ * limitations under the License. */ +#include "l2cap/classic/internal/dumpsys_helper.h" + #include -#include "l2cap/classic/internal/dumpsys_helper.h" #include "l2cap/classic/internal/fixed_channel_impl.h" #include "l2cap/classic/internal/link.h" #include "l2cap/classic/internal/link_manager.h" @@ -29,11 +30,12 @@ bluetooth::l2cap::classic::internal::DumpsysHelper::DumpsysHelper(const LinkMana std::vector> bluetooth::l2cap::classic::internal::DumpsysHelper::DumpActiveDynamicChannels( - flatbuffers::FlatBufferBuilder* fb_builder, - const l2cap::internal::DynamicChannelAllocator& channel_allocator) const { + flatbuffers::FlatBufferBuilder* fb_builder, + const l2cap::internal::DynamicChannelAllocator& channel_allocator) const { std::vector> channel_offsets; - for (auto it = channel_allocator.channels_.cbegin(); it != channel_allocator.channels_.cend(); ++it) { + for (auto it = channel_allocator.channels_.cbegin(); it != channel_allocator.channels_.cend(); + ++it) { ChannelDataBuilder builder(*fb_builder); builder.add_cid(it->first); channel_offsets.push_back(builder.Finish()); @@ -43,13 +45,14 @@ bluetooth::l2cap::classic::internal::DumpsysHelper::DumpActiveDynamicChannels( std::vector> bluetooth::l2cap::classic::internal::DumpsysHelper::DumpActiveFixedChannels( - flatbuffers::FlatBufferBuilder* fb_builder, - const bluetooth::l2cap::internal::FixedChannelAllocator< - bluetooth::l2cap::classic::internal::FixedChannelImpl, - bluetooth::l2cap::classic::internal::Link>& channel_allocator) const { + flatbuffers::FlatBufferBuilder* fb_builder, + const bluetooth::l2cap::internal::FixedChannelAllocator< + bluetooth::l2cap::classic::internal::FixedChannelImpl, + bluetooth::l2cap::classic::internal::Link>& channel_allocator) const { std::vector> channel_offsets; - for (auto it = channel_allocator.channels_.cbegin(); it != channel_allocator.channels_.cend(); ++it) { + for (auto it = channel_allocator.channels_.cbegin(); it != channel_allocator.channels_.cend(); + ++it) { ChannelDataBuilder builder(*fb_builder); builder.add_cid(it->first); channel_offsets.push_back(builder.Finish()); @@ -58,17 +61,20 @@ bluetooth::l2cap::classic::internal::DumpsysHelper::DumpActiveFixedChannels( } std::vector> -bluetooth::l2cap::classic::internal::DumpsysHelper::DumpActiveLinks(flatbuffers::FlatBufferBuilder* fb_builder) const { +bluetooth::l2cap::classic::internal::DumpsysHelper::DumpActiveLinks( + flatbuffers::FlatBufferBuilder* fb_builder) const { const std::unordered_map* links = &link_manager_.links_; std::vector> link_offsets; for (auto it = links->cbegin(); it != links->cend(); ++it) { auto link_address = fb_builder->CreateString(it->second.ToString()); - auto dynamic_channel_offsets = DumpActiveDynamicChannels(fb_builder, it->second.dynamic_channel_allocator_); + auto dynamic_channel_offsets = + DumpActiveDynamicChannels(fb_builder, it->second.dynamic_channel_allocator_); auto dynamic_channels = fb_builder->CreateVector(dynamic_channel_offsets); - auto fixed_channel_offsets = DumpActiveFixedChannels(fb_builder, it->second.fixed_channel_allocator_); + auto fixed_channel_offsets = + DumpActiveFixedChannels(fb_builder, it->second.fixed_channel_allocator_); auto fixed_channels = fb_builder->CreateVector(fixed_channel_offsets); LinkDataBuilder builder(*fb_builder); diff --git a/system/gd/l2cap/classic/internal/dumpsys_helper.h b/system/gd/l2cap/classic/internal/dumpsys_helper.h index 134917bbd79..7fb3377d2e2 100644 --- a/system/gd/l2cap/classic/internal/dumpsys_helper.h +++ b/system/gd/l2cap/classic/internal/dumpsys_helper.h @@ -29,18 +29,20 @@ namespace classic { namespace internal { class DumpsysHelper { - public: +public: DumpsysHelper(const LinkManager& link_manager); std::vector> DumpActiveDynamicChannels( - flatbuffers::FlatBufferBuilder* fb_builder, - const l2cap::internal::DynamicChannelAllocator& channel_allocator) const; + flatbuffers::FlatBufferBuilder* fb_builder, + const l2cap::internal::DynamicChannelAllocator& channel_allocator) const; std::vector> DumpActiveFixedChannels( - flatbuffers::FlatBufferBuilder* fb_builder, - const l2cap::internal::FixedChannelAllocator& channel_allocator) const; - std::vector> DumpActiveLinks(flatbuffers::FlatBufferBuilder* fb_builder) const; + flatbuffers::FlatBufferBuilder* fb_builder, + const l2cap::internal::FixedChannelAllocator& channel_allocator) + const; + std::vector> DumpActiveLinks( + flatbuffers::FlatBufferBuilder* fb_builder) const; - private: +private: const LinkManager& link_manager_; }; diff --git a/system/gd/l2cap/classic/internal/dynamic_channel_service_impl.h b/system/gd/l2cap/classic/internal/dynamic_channel_service_impl.h index 15aaff0583e..dc2133e4466 100644 --- a/system/gd/l2cap/classic/internal/dynamic_channel_service_impl.h +++ b/system/gd/l2cap/classic/internal/dynamic_channel_service_impl.h @@ -27,7 +27,7 @@ namespace l2cap { namespace classic { namespace internal { class DynamicChannelServiceImpl { - public: +public: virtual ~DynamicChannelServiceImpl() = default; struct PendingRegistration { @@ -42,27 +42,23 @@ class DynamicChannelServiceImpl { on_connection_open_callback_(std::move(channel)); } - virtual DynamicChannelConfigurationOption GetConfigOption() const { - return config_option_; - } + virtual DynamicChannelConfigurationOption GetConfigOption() const { return config_option_; } - virtual SecurityPolicy GetSecurityPolicy() const { - return security_policy_; - } + virtual SecurityPolicy GetSecurityPolicy() const { return security_policy_; } friend class DynamicChannelServiceManagerImpl; - protected: +protected: // protected access for mocking DynamicChannelServiceImpl( - classic::SecurityPolicy security_policy, - DynamicChannelManager::OnConnectionOpenCallback on_connection_open_callback, - DynamicChannelConfigurationOption config_option) + classic::SecurityPolicy security_policy, + DynamicChannelManager::OnConnectionOpenCallback on_connection_open_callback, + DynamicChannelConfigurationOption config_option) : security_policy_(security_policy), on_connection_open_callback_(std::move(on_connection_open_callback)), config_option_(config_option) {} - private: +private: classic::SecurityPolicy security_policy_; DynamicChannelManager::OnConnectionOpenCallback on_connection_open_callback_; DynamicChannelConfigurationOption config_option_; diff --git a/system/gd/l2cap/classic/internal/dynamic_channel_service_impl_mock.h b/system/gd/l2cap/classic/internal/dynamic_channel_service_impl_mock.h index 299841e9c30..6176ed65c74 100644 --- a/system/gd/l2cap/classic/internal/dynamic_channel_service_impl_mock.h +++ b/system/gd/l2cap/classic/internal/dynamic_channel_service_impl_mock.h @@ -15,10 +15,10 @@ */ #pragma once -#include "l2cap/classic/internal/dynamic_channel_service_impl.h" - #include +#include "l2cap/classic/internal/dynamic_channel_service_impl.h" + // Unit test interfaces namespace bluetooth { namespace l2cap { @@ -27,7 +27,7 @@ namespace internal { namespace testing { class MockDynamicChannelServiceImpl : public DynamicChannelServiceImpl { - public: +public: MockDynamicChannelServiceImpl() : DynamicChannelServiceImpl({}, {}, {}) {} MOCK_METHOD(SecurityPolicy, GetSecurityPolicy, (), (const, override)); }; diff --git a/system/gd/l2cap/classic/internal/dynamic_channel_service_manager_impl.cc b/system/gd/l2cap/classic/internal/dynamic_channel_service_manager_impl.cc index 3dfb0e185fc..1b7ceeca4f4 100644 --- a/system/gd/l2cap/classic/internal/dynamic_channel_service_manager_impl.cc +++ b/system/gd/l2cap/classic/internal/dynamic_channel_service_manager_impl.cc @@ -27,32 +27,33 @@ namespace l2cap { namespace classic { namespace internal { -void DynamicChannelServiceManagerImpl::Register(Psm psm, - DynamicChannelServiceImpl::PendingRegistration pending_registration) { +void DynamicChannelServiceManagerImpl::Register( + Psm psm, DynamicChannelServiceImpl::PendingRegistration pending_registration) { if (!IsPsmValid(psm)) { std::unique_ptr invalid_service(new DynamicChannelService()); pending_registration.on_registration_complete_callback_( - DynamicChannelManager::RegistrationResult::FAIL_INVALID_SERVICE, - std::move(invalid_service)); + DynamicChannelManager::RegistrationResult::FAIL_INVALID_SERVICE, + std::move(invalid_service)); } else if (IsServiceRegistered(psm)) { std::unique_ptr invalid_service(new DynamicChannelService()); pending_registration.on_registration_complete_callback_( - DynamicChannelManager::RegistrationResult::FAIL_DUPLICATE_SERVICE, - std::move(invalid_service)); + DynamicChannelManager::RegistrationResult::FAIL_DUPLICATE_SERVICE, + std::move(invalid_service)); } else { service_map_.try_emplace( - psm, - DynamicChannelServiceImpl( - pending_registration.security_policy_, - std::move(pending_registration.on_connection_open_callback_), - pending_registration.configuration_)); - std::unique_ptr user_service(new DynamicChannelService(psm, this, l2cap_layer_handler_)); + psm, + DynamicChannelServiceImpl(pending_registration.security_policy_, + std::move(pending_registration.on_connection_open_callback_), + pending_registration.configuration_)); + std::unique_ptr user_service( + new DynamicChannelService(psm, this, l2cap_layer_handler_)); pending_registration.on_registration_complete_callback_( - DynamicChannelManager::RegistrationResult::SUCCESS, std::move(user_service)); + DynamicChannelManager::RegistrationResult::SUCCESS, std::move(user_service)); } } -void DynamicChannelServiceManagerImpl::Unregister(Psm psm, DynamicChannelService::OnUnregisteredCallback callback) { +void DynamicChannelServiceManagerImpl::Unregister( + Psm psm, DynamicChannelService::OnUnregisteredCallback callback) { if (IsServiceRegistered(psm)) { service_map_.erase(psm); callback(); @@ -70,7 +71,8 @@ DynamicChannelServiceImpl* DynamicChannelServiceManagerImpl::GetService(Psm psm) return &service_map_.find(psm)->second; } -std::vector> DynamicChannelServiceManagerImpl::GetRegisteredServices() { +std::vector> +DynamicChannelServiceManagerImpl::GetRegisteredServices() { std::vector> results; for (auto& elem : service_map_) { results.emplace_back(elem.first, &elem.second); diff --git a/system/gd/l2cap/classic/internal/dynamic_channel_service_manager_impl.h b/system/gd/l2cap/classic/internal/dynamic_channel_service_manager_impl.h index 724d70a02c0..97df099e2bc 100644 --- a/system/gd/l2cap/classic/internal/dynamic_channel_service_manager_impl.h +++ b/system/gd/l2cap/classic/internal/dynamic_channel_service_manager_impl.h @@ -31,7 +31,7 @@ namespace classic { namespace internal { class DynamicChannelServiceManagerImpl { - public: +public: explicit DynamicChannelServiceManagerImpl(os::Handler* l2cap_layer_handler) : l2cap_layer_handler_(l2cap_layer_handler) {} @@ -39,7 +39,8 @@ class DynamicChannelServiceManagerImpl { // // All APIs must be invoked in L2CAP layer handler // - virtual void Register(Psm psm, DynamicChannelServiceImpl::PendingRegistration pending_registration); + virtual void Register(Psm psm, + DynamicChannelServiceImpl::PendingRegistration pending_registration); virtual void Unregister(Psm psm, DynamicChannelService::OnUnregisteredCallback callback); virtual bool IsServiceRegistered(Psm psm) const; virtual DynamicChannelServiceImpl* GetService(Psm psm); @@ -55,7 +56,7 @@ class DynamicChannelServiceManagerImpl { return security_enforcement_interface_; } - private: +private: os::Handler* l2cap_layer_handler_ = nullptr; std::unordered_map service_map_; SecurityEnforcementInterface* security_enforcement_interface_ = nullptr; diff --git a/system/gd/l2cap/classic/internal/dynamic_channel_service_manager_impl_mock.h b/system/gd/l2cap/classic/internal/dynamic_channel_service_manager_impl_mock.h index eb25d292fc6..1990c86e6c6 100644 --- a/system/gd/l2cap/classic/internal/dynamic_channel_service_manager_impl_mock.h +++ b/system/gd/l2cap/classic/internal/dynamic_channel_service_manager_impl_mock.h @@ -15,12 +15,12 @@ */ #pragma once +#include + #include "l2cap/classic/internal/dynamic_channel_service_manager_impl.h" #include "l2cap/classic/security_enforcement_interface.h" #include "l2cap/internal/dynamic_channel_impl.h" -#include - // Unit test interfaces namespace bluetooth { namespace l2cap { @@ -29,14 +29,17 @@ namespace internal { namespace testing { class MockDynamicChannelServiceManagerImpl : public DynamicChannelServiceManagerImpl { - public: +public: MockDynamicChannelServiceManagerImpl() : DynamicChannelServiceManagerImpl(nullptr) {} - MOCK_METHOD(void, Register, (Psm psm, DynamicChannelServiceImpl::PendingRegistration pending_registration), + MOCK_METHOD(void, Register, + (Psm psm, DynamicChannelServiceImpl::PendingRegistration pending_registration), + (override)); + MOCK_METHOD(void, Unregister, (Psm psm, DynamicChannelService::OnUnregisteredCallback callback), (override)); - MOCK_METHOD(void, Unregister, (Psm psm, DynamicChannelService::OnUnregisteredCallback callback), (override)); MOCK_METHOD(bool, IsServiceRegistered, (Psm psm), (const, override)); MOCK_METHOD(DynamicChannelServiceImpl*, GetService, (Psm psm), (override)); - MOCK_METHOD((std::vector>), GetRegisteredServices, (), (override)); + MOCK_METHOD((std::vector>), GetRegisteredServices, (), + (override)); MOCK_METHOD(SecurityEnforcementInterface*, GetSecurityEnforcementInterface, (), (override)); }; diff --git a/system/gd/l2cap/classic/internal/dynamic_channel_service_manager_test.cc b/system/gd/l2cap/classic/internal/dynamic_channel_service_manager_test.cc index 5decd300586..bc03b563b26 100644 --- a/system/gd/l2cap/classic/internal/dynamic_channel_service_manager_test.cc +++ b/system/gd/l2cap/classic/internal/dynamic_channel_service_manager_test.cc @@ -14,10 +14,10 @@ * limitations under the License. */ -#include - #include +#include + #include "common/bind.h" #include "l2cap/cid.h" #include "l2cap/classic/dynamic_channel_manager.h" @@ -33,7 +33,7 @@ namespace internal { namespace { class L2capDynamicServiceManagerTest : public ::testing::Test { - public: +public: ~L2capDynamicServiceManagerTest() = default; void OnServiceRegistered(bool expect_success, DynamicChannelManager::RegistrationResult result, @@ -42,7 +42,7 @@ class L2capDynamicServiceManagerTest : public ::testing::Test { service_registered_ = expect_success; } - protected: +protected: void SetUp() override { thread_ = new os::Thread("test_thread", os::Thread::Priority::NORMAL); user_handler_ = new os::Handler(thread_); @@ -77,10 +77,11 @@ class L2capDynamicServiceManagerTest : public ::testing::Test { TEST_F(L2capDynamicServiceManagerTest, register_and_unregister_classic_dynamic_channel) { DynamicChannelServiceImpl::PendingRegistration pending_registration{ - .user_handler_ = user_handler_, - .security_policy_ = SecurityPolicy::_SDP_ONLY_NO_SECURITY_WHATSOEVER_PLAINTEXT_TRANSPORT_OK, - .on_registration_complete_callback_ = - user_handler_->BindOnceOn(this, &L2capDynamicServiceManagerTest::OnServiceRegistered, true)}; + .user_handler_ = user_handler_, + .security_policy_ = + SecurityPolicy::_SDP_ONLY_NO_SECURITY_WHATSOEVER_PLAINTEXT_TRANSPORT_OK, + .on_registration_complete_callback_ = user_handler_->BindOnceOn( + this, &L2capDynamicServiceManagerTest::OnServiceRegistered, true)}; Cid cid = kSmpBrCid; EXPECT_FALSE(manager_->IsServiceRegistered(cid)); manager_->Register(cid, std::move(pending_registration)); @@ -93,9 +94,10 @@ TEST_F(L2capDynamicServiceManagerTest, register_and_unregister_classic_dynamic_c TEST_F(L2capDynamicServiceManagerTest, register_classic_dynamic_channel_bad_cid) { DynamicChannelServiceImpl::PendingRegistration pending_registration{ - .security_policy_ = SecurityPolicy::_SDP_ONLY_NO_SECURITY_WHATSOEVER_PLAINTEXT_TRANSPORT_OK, - .on_registration_complete_callback_ = - user_handler_->BindOnceOn(this, &L2capDynamicServiceManagerTest::OnServiceRegistered, false)}; + .security_policy_ = + SecurityPolicy::_SDP_ONLY_NO_SECURITY_WHATSOEVER_PLAINTEXT_TRANSPORT_OK, + .on_registration_complete_callback_ = user_handler_->BindOnceOn( + this, &L2capDynamicServiceManagerTest::OnServiceRegistered, false)}; Cid cid = 0x1000; EXPECT_FALSE(manager_->IsServiceRegistered(cid)); manager_->Register(cid, std::move(pending_registration)); diff --git a/system/gd/l2cap/classic/internal/fixed_channel_impl.cc b/system/gd/l2cap/classic/internal/fixed_channel_impl.cc index bc2ffe13118..f3040127ae7 100644 --- a/system/gd/l2cap/classic/internal/fixed_channel_impl.cc +++ b/system/gd/l2cap/classic/internal/fixed_channel_impl.cc @@ -32,8 +32,8 @@ namespace internal { FixedChannelImpl::FixedChannelImpl(Cid cid, Link* link, os::Handler* l2cap_handler) : cid_(cid), device_(link->GetDevice()), link_(link), l2cap_handler_(l2cap_handler) { - log::assert_that( - cid_ >= kFirstFixedChannel && cid_ <= kLastFixedChannel, "Invalid cid: {}", cid_); + log::assert_that(cid_ >= kFirstFixedChannel && cid_ <= kLastFixedChannel, "Invalid cid: {}", + cid_); log::assert_that(link_ != nullptr, "assert failed: link_ != nullptr"); log::assert_that(l2cap_handler_ != nullptr, "assert failed: l2cap_handler_ != nullptr"); } @@ -51,13 +51,10 @@ void FixedChannelImpl::RegisterOnCloseCallback(os::Handler* user_handler, } void FixedChannelImpl::OnClosed(hci::ErrorCode status) { - log::assert_that( - !closed_, - "Device {} Cid 0x{:x} closed twice, old status 0x{:x}, new status 0x{:x}", - ADDRESS_TO_LOGGABLE_CSTR(device_), - cid_, - static_cast(close_reason_), - static_cast(status)); + log::assert_that(!closed_, + "Device {} Cid 0x{:x} closed twice, old status 0x{:x}, new status 0x{:x}", + ADDRESS_TO_LOGGABLE_CSTR(device_), cid_, static_cast(close_reason_), + static_cast(status)); closed_ = true; close_reason_ = status; acquired_ = false; @@ -73,8 +70,8 @@ void FixedChannelImpl::OnClosed(hci::ErrorCode status) { } void FixedChannelImpl::Acquire() { - log::assert_that( - user_handler_ != nullptr, "Must register OnCloseCallback before calling any methods"); + log::assert_that(user_handler_ != nullptr, + "Must register OnCloseCallback before calling any methods"); if (closed_) { log::warn("{} is already closed", ToLoggableStr(*this)); log::assert_that(!acquired_, "assert failed: !acquired_"); @@ -89,8 +86,8 @@ void FixedChannelImpl::Acquire() { } void FixedChannelImpl::Release() { - log::assert_that( - user_handler_ != nullptr, "Must register OnCloseCallback before calling any methods"); + log::assert_that(user_handler_ != nullptr, + "Must register OnCloseCallback before calling any methods"); if (closed_) { log::warn("{} is already closed", ToLoggableStr(*this)); log::assert_that(!acquired_, "assert failed: !acquired_"); diff --git a/system/gd/l2cap/classic/internal/fixed_channel_impl.h b/system/gd/l2cap/classic/internal/fixed_channel_impl.h index 4c9394a68e2..6ce00a48c3b 100644 --- a/system/gd/l2cap/classic/internal/fixed_channel_impl.h +++ b/system/gd/l2cap/classic/internal/fixed_channel_impl.h @@ -34,7 +34,7 @@ class Link; class FixedChannelImpl : public l2cap::internal::ChannelImpl, public bluetooth::common::IRedactableLoggable { - public: +public: FixedChannelImpl(Cid cid, Link* link, os::Handler* l2cap_handler); FixedChannelImpl(const FixedChannelImpl&) = delete; @@ -42,19 +42,16 @@ class FixedChannelImpl : public l2cap::internal::ChannelImpl, virtual ~FixedChannelImpl() = default; - hci::Address GetDevice() const { - return device_.GetAddress(); - } + hci::Address GetDevice() const { return device_.GetAddress(); } - virtual void RegisterOnCloseCallback(os::Handler* user_handler, FixedChannel::OnCloseCallback on_close_callback); + virtual void RegisterOnCloseCallback(os::Handler* user_handler, + FixedChannel::OnCloseCallback on_close_callback); virtual void Acquire(); virtual void Release(); - virtual bool IsAcquired() const { - return acquired_; - } + virtual bool IsAcquired() const { return acquired_; } virtual void OnClosed(hci::ErrorCode status); @@ -70,23 +67,21 @@ class FixedChannelImpl : public l2cap::internal::ChannelImpl, return ss.str(); } - common::BidiQueueEnd>* GetQueueUpEnd() { + common::BidiQueueEnd>* + GetQueueUpEnd() { return channel_queue_.GetUpEnd(); } - common::BidiQueueEnd, packet::BasePacketBuilder>* GetQueueDownEnd() { + common::BidiQueueEnd, packet::BasePacketBuilder>* + GetQueueDownEnd() { return channel_queue_.GetDownEnd(); } - Cid GetCid() const { - return cid_; - } + Cid GetCid() const { return cid_; } - Cid GetRemoteCid() const { - return cid_; - } + Cid GetRemoteCid() const { return cid_; } - private: +private: // Constructor states // For logging purpose only const Cid cid_; @@ -105,8 +100,8 @@ class FixedChannelImpl : public l2cap::internal::ChannelImpl, bool closed_ = false; hci::ErrorCode close_reason_ = hci::ErrorCode::SUCCESS; static constexpr size_t kChannelQueueSize = 10; - common::BidiQueue, packet::BasePacketBuilder> channel_queue_{ - kChannelQueueSize}; + common::BidiQueue, packet::BasePacketBuilder> + channel_queue_{kChannelQueueSize}; }; } // namespace internal diff --git a/system/gd/l2cap/classic/internal/fixed_channel_impl_mock.h b/system/gd/l2cap/classic/internal/fixed_channel_impl_mock.h index 680bf515cc8..d5eaee180b4 100644 --- a/system/gd/l2cap/classic/internal/fixed_channel_impl_mock.h +++ b/system/gd/l2cap/classic/internal/fixed_channel_impl_mock.h @@ -15,10 +15,10 @@ */ #pragma once -#include "l2cap/classic/internal/fixed_channel_impl.h" - #include +#include "l2cap/classic/internal/fixed_channel_impl.h" + // Unit test interfaces namespace bluetooth { namespace l2cap { @@ -27,10 +27,12 @@ namespace internal { namespace testing { class MockFixedChannelImpl : public FixedChannelImpl { - public: - MockFixedChannelImpl(Cid cid, Link* link, os::Handler* l2cap_handler) : FixedChannelImpl(cid, link, l2cap_handler) {} +public: + MockFixedChannelImpl(Cid cid, Link* link, os::Handler* l2cap_handler) + : FixedChannelImpl(cid, link, l2cap_handler) {} MOCK_METHOD(void, RegisterOnCloseCallback, - (os::Handler * user_handler, FixedChannel::OnCloseCallback on_close_callback), (override)); + (os::Handler * user_handler, FixedChannel::OnCloseCallback on_close_callback), + (override)); MOCK_METHOD(void, Acquire, (), (override)); MOCK_METHOD(void, Release, (), (override)); MOCK_METHOD(bool, IsAcquired, (), (override, const)); diff --git a/system/gd/l2cap/classic/internal/fixed_channel_impl_test.cc b/system/gd/l2cap/classic/internal/fixed_channel_impl_test.cc index efd379894d3..d22ff62d074 100644 --- a/system/gd/l2cap/classic/internal/fixed_channel_impl_test.cc +++ b/system/gd/l2cap/classic/internal/fixed_channel_impl_test.cc @@ -15,15 +15,15 @@ */ #include "l2cap/classic/internal/fixed_channel_impl.h" +#include +#include + #include "common/testing/bind_test_util.h" #include "l2cap/cid.h" #include "l2cap/classic/internal/link_mock.h" #include "l2cap/internal/parameter_provider_mock.h" #include "os/handler.h" -#include -#include - namespace bluetooth { namespace l2cap { namespace classic { @@ -35,7 +35,7 @@ using testing::MockLink; using ::testing::Return; class L2capClassicFixedChannelImplTest : public ::testing::Test { - public: +public: static void SyncHandler(os::Handler* handler) { std::promise promise; auto future = promise.get_future(); @@ -43,7 +43,7 @@ class L2capClassicFixedChannelImplTest : public ::testing::Test { future.wait_for(std::chrono::seconds(1)); } - protected: +protected: void SetUp() override { thread_ = new os::Thread("test_thread", os::Thread::Priority::NORMAL); l2cap_handler_ = new os::Handler(thread_); @@ -62,13 +62,14 @@ class L2capClassicFixedChannelImplTest : public ::testing::Test { TEST_F(L2capClassicFixedChannelImplTest, get_device) { MockParameterProvider mock_parameter_provider; EXPECT_CALL(mock_parameter_provider, GetClassicLinkIdleDisconnectTimeout()) - .WillRepeatedly(Return(std::chrono::seconds(5))); + .WillRepeatedly(Return(std::chrono::seconds(5))); testing::MockClassicAclConnection* mock_acl_connection = new testing::MockClassicAclConnection(); EXPECT_CALL(*mock_acl_connection, GetAddress()).Times(1); EXPECT_CALL(*mock_acl_connection, RegisterCallbacks(_, l2cap_handler_)).Times(1); - MockLink mock_classic_link(l2cap_handler_, &mock_parameter_provider, - std::unique_ptr(mock_acl_connection), - nullptr /* LinkManager */); + MockLink mock_classic_link( + l2cap_handler_, &mock_parameter_provider, + std::unique_ptr(mock_acl_connection), + nullptr /* LinkManager */); hci::AddressWithType device{hci::Address{{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}, hci::AddressType::PUBLIC_IDENTITY_ADDRESS}; EXPECT_CALL(mock_classic_link, GetDevice()).WillRepeatedly(Return(device)); @@ -79,13 +80,14 @@ TEST_F(L2capClassicFixedChannelImplTest, get_device) { TEST_F(L2capClassicFixedChannelImplTest, close_triggers_callback) { MockParameterProvider mock_parameter_provider; EXPECT_CALL(mock_parameter_provider, GetClassicLinkIdleDisconnectTimeout()) - .WillRepeatedly(Return(std::chrono::seconds(5))); + .WillRepeatedly(Return(std::chrono::seconds(5))); testing::MockClassicAclConnection* mock_acl_connection = new testing::MockClassicAclConnection(); EXPECT_CALL(*mock_acl_connection, GetAddress()).Times(1); EXPECT_CALL(*mock_acl_connection, RegisterCallbacks(_, l2cap_handler_)).Times(1); - MockLink mock_classic_link(l2cap_handler_, &mock_parameter_provider, - std::unique_ptr(mock_acl_connection), - nullptr /* LinkManager */); + MockLink mock_classic_link( + l2cap_handler_, &mock_parameter_provider, + std::unique_ptr(mock_acl_connection), + nullptr /* LinkManager */); hci::AddressWithType device{hci::Address{{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}, hci::AddressType::PUBLIC_IDENTITY_ADDRESS}; EXPECT_CALL(mock_classic_link, GetDevice()).WillRepeatedly(Return(device)); @@ -95,7 +97,8 @@ TEST_F(L2capClassicFixedChannelImplTest, close_triggers_callback) { auto user_handler = std::make_unique(thread_); hci::ErrorCode my_status = hci::ErrorCode::SUCCESS; fixed_channel_impl.RegisterOnCloseCallback( - user_handler.get(), common::testing::BindLambdaForTesting([&](hci::ErrorCode status) { my_status = status; })); + user_handler.get(), common::testing::BindLambdaForTesting( + [&](hci::ErrorCode status) { my_status = status; })); // Channel closure should trigger such callback fixed_channel_impl.OnClosed(hci::ErrorCode::REMOTE_USER_TERMINATED_CONNECTION); @@ -108,13 +111,14 @@ TEST_F(L2capClassicFixedChannelImplTest, close_triggers_callback) { TEST_F(L2capClassicFixedChannelImplTest, register_callback_after_close_should_call_immediately) { MockParameterProvider mock_parameter_provider; EXPECT_CALL(mock_parameter_provider, GetClassicLinkIdleDisconnectTimeout()) - .WillRepeatedly(Return(std::chrono::seconds(5))); + .WillRepeatedly(Return(std::chrono::seconds(5))); testing::MockClassicAclConnection* mock_acl_connection = new testing::MockClassicAclConnection(); EXPECT_CALL(*mock_acl_connection, GetAddress()).Times(1); EXPECT_CALL(*mock_acl_connection, RegisterCallbacks(_, l2cap_handler_)).Times(1); - MockLink mock_classic_link(l2cap_handler_, &mock_parameter_provider, - std::unique_ptr(mock_acl_connection), - nullptr /* LinkManager */); + MockLink mock_classic_link( + l2cap_handler_, &mock_parameter_provider, + std::unique_ptr(mock_acl_connection), + nullptr /* LinkManager */); hci::AddressWithType device{hci::Address{{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}, hci::AddressType::PUBLIC_IDENTITY_ADDRESS}; EXPECT_CALL(mock_classic_link, GetDevice()).WillRepeatedly(Return(device)); @@ -127,7 +131,8 @@ TEST_F(L2capClassicFixedChannelImplTest, register_callback_after_close_should_ca auto user_handler = std::make_unique(thread_); hci::ErrorCode my_status = hci::ErrorCode::SUCCESS; fixed_channel_impl.RegisterOnCloseCallback( - user_handler.get(), common::testing::BindLambdaForTesting([&](hci::ErrorCode status) { my_status = status; })); + user_handler.get(), common::testing::BindLambdaForTesting( + [&](hci::ErrorCode status) { my_status = status; })); SyncHandler(user_handler.get()); EXPECT_EQ(hci::ErrorCode::REMOTE_USER_TERMINATED_CONNECTION, my_status); @@ -138,13 +143,14 @@ TEST_F(L2capClassicFixedChannelImplTest, close_twice_should_fail) { ::testing::FLAGS_gtest_death_test_style = "threadsafe"; MockParameterProvider mock_parameter_provider; EXPECT_CALL(mock_parameter_provider, GetClassicLinkIdleDisconnectTimeout()) - .WillRepeatedly(Return(std::chrono::seconds(5))); + .WillRepeatedly(Return(std::chrono::seconds(5))); testing::MockClassicAclConnection* mock_acl_connection = new testing::MockClassicAclConnection(); EXPECT_CALL(*mock_acl_connection, GetAddress()).Times(1); EXPECT_CALL(*mock_acl_connection, RegisterCallbacks(_, l2cap_handler_)).Times(1); - MockLink mock_classic_link(l2cap_handler_, &mock_parameter_provider, - std::unique_ptr(mock_acl_connection), - nullptr /* LinkManager */); + MockLink mock_classic_link( + l2cap_handler_, &mock_parameter_provider, + std::unique_ptr(mock_acl_connection), + nullptr /* LinkManager */); hci::AddressWithType device{hci::Address{{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}, hci::AddressType::PUBLIC_IDENTITY_ADDRESS}; EXPECT_CALL(mock_classic_link, GetDevice()).WillRepeatedly(Return(device)); @@ -154,7 +160,8 @@ TEST_F(L2capClassicFixedChannelImplTest, close_twice_should_fail) { auto user_handler = std::make_unique(thread_); hci::ErrorCode my_status = hci::ErrorCode::SUCCESS; fixed_channel_impl.RegisterOnCloseCallback( - user_handler.get(), common::testing::BindLambdaForTesting([&](hci::ErrorCode status) { my_status = status; })); + user_handler.get(), common::testing::BindLambdaForTesting( + [&](hci::ErrorCode status) { my_status = status; })); // Channel closure should trigger such callback fixed_channel_impl.OnClosed(hci::ErrorCode::REMOTE_USER_TERMINATED_CONNECTION); @@ -162,7 +169,8 @@ TEST_F(L2capClassicFixedChannelImplTest, close_twice_should_fail) { EXPECT_EQ(hci::ErrorCode::REMOTE_USER_TERMINATED_CONNECTION, my_status); // 2nd OnClose() callback should fail - EXPECT_DEATH(fixed_channel_impl.OnClosed(hci::ErrorCode::PAGE_TIMEOUT), ".*assertion \'!closed_\' failed.*"); + EXPECT_DEATH(fixed_channel_impl.OnClosed(hci::ErrorCode::PAGE_TIMEOUT), + ".*assertion \'!closed_\' failed.*"); user_handler->Clear(); } @@ -171,13 +179,14 @@ TEST_F(L2capClassicFixedChannelImplTest, multiple_registration_should_fail) { ::testing::FLAGS_gtest_death_test_style = "threadsafe"; MockParameterProvider mock_parameter_provider; EXPECT_CALL(mock_parameter_provider, GetClassicLinkIdleDisconnectTimeout()) - .WillRepeatedly(Return(std::chrono::seconds(5))); + .WillRepeatedly(Return(std::chrono::seconds(5))); testing::MockClassicAclConnection* mock_acl_connection = new testing::MockClassicAclConnection(); EXPECT_CALL(*mock_acl_connection, GetAddress()).Times(1); EXPECT_CALL(*mock_acl_connection, RegisterCallbacks(_, l2cap_handler_)).Times(1); - MockLink mock_classic_link(l2cap_handler_, &mock_parameter_provider, - std::unique_ptr(mock_acl_connection), - nullptr /* LinkManager */); + MockLink mock_classic_link( + l2cap_handler_, &mock_parameter_provider, + std::unique_ptr(mock_acl_connection), + nullptr /* LinkManager */); hci::AddressWithType device{hci::Address{{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}, hci::AddressType::PUBLIC_IDENTITY_ADDRESS}; EXPECT_CALL(mock_classic_link, GetDevice()).WillRepeatedly(Return(device)); @@ -187,10 +196,11 @@ TEST_F(L2capClassicFixedChannelImplTest, multiple_registration_should_fail) { auto user_handler = std::make_unique(thread_); hci::ErrorCode my_status = hci::ErrorCode::SUCCESS; fixed_channel_impl.RegisterOnCloseCallback( - user_handler.get(), common::testing::BindLambdaForTesting([&](hci::ErrorCode status) { my_status = status; })); + user_handler.get(), common::testing::BindLambdaForTesting( + [&](hci::ErrorCode status) { my_status = status; })); - EXPECT_DEATH(fixed_channel_impl.RegisterOnCloseCallback(user_handler.get(), - common::BindOnce([](hci::ErrorCode status) { FAIL(); })), + EXPECT_DEATH(fixed_channel_impl.RegisterOnCloseCallback( + user_handler.get(), common::BindOnce([](hci::ErrorCode status) { FAIL(); })), ".*OnCloseCallback can only be registered once.*"); user_handler->Clear(); @@ -200,50 +210,55 @@ TEST_F(L2capClassicFixedChannelImplTest, call_acquire_before_registration_should ::testing::FLAGS_gtest_death_test_style = "threadsafe"; MockParameterProvider mock_parameter_provider; EXPECT_CALL(mock_parameter_provider, GetClassicLinkIdleDisconnectTimeout()) - .WillRepeatedly(Return(std::chrono::seconds(5))); + .WillRepeatedly(Return(std::chrono::seconds(5))); testing::MockClassicAclConnection* mock_acl_connection = new testing::MockClassicAclConnection(); EXPECT_CALL(*mock_acl_connection, GetAddress()).Times(1); EXPECT_CALL(*mock_acl_connection, RegisterCallbacks(_, l2cap_handler_)).Times(1); - MockLink mock_classic_link(l2cap_handler_, &mock_parameter_provider, - std::unique_ptr(mock_acl_connection), - nullptr /* LinkManager */); + MockLink mock_classic_link( + l2cap_handler_, &mock_parameter_provider, + std::unique_ptr(mock_acl_connection), + nullptr /* LinkManager */); hci::AddressWithType device{hci::Address{{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}, hci::AddressType::PUBLIC_IDENTITY_ADDRESS}; EXPECT_CALL(mock_classic_link, GetDevice()).WillRepeatedly(Return(device)); FixedChannelImpl fixed_channel_impl(kSmpBrCid, &mock_classic_link, l2cap_handler_); - EXPECT_DEATH(fixed_channel_impl.Acquire(), ".*Must register OnCloseCallback before calling any methods.*"); + EXPECT_DEATH(fixed_channel_impl.Acquire(), + ".*Must register OnCloseCallback before calling any methods.*"); } TEST_F(L2capClassicFixedChannelImplTest, call_release_before_registration_should_fail) { ::testing::FLAGS_gtest_death_test_style = "threadsafe"; MockParameterProvider mock_parameter_provider; EXPECT_CALL(mock_parameter_provider, GetClassicLinkIdleDisconnectTimeout()) - .WillRepeatedly(Return(std::chrono::seconds(5))); + .WillRepeatedly(Return(std::chrono::seconds(5))); testing::MockClassicAclConnection* mock_acl_connection = new testing::MockClassicAclConnection(); EXPECT_CALL(*mock_acl_connection, GetAddress()).Times(1); EXPECT_CALL(*mock_acl_connection, RegisterCallbacks(_, l2cap_handler_)).Times(1); - MockLink mock_classic_link(l2cap_handler_, &mock_parameter_provider, - std::unique_ptr(mock_acl_connection), - nullptr /* LinkManager */); + MockLink mock_classic_link( + l2cap_handler_, &mock_parameter_provider, + std::unique_ptr(mock_acl_connection), + nullptr /* LinkManager */); hci::AddressWithType device{hci::Address{{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}, hci::AddressType::PUBLIC_IDENTITY_ADDRESS}; EXPECT_CALL(mock_classic_link, GetDevice()).WillRepeatedly(Return(device)); FixedChannelImpl fixed_channel_impl(kSmpBrCid, &mock_classic_link, l2cap_handler_); - EXPECT_DEATH(fixed_channel_impl.Release(), ".*Must register OnCloseCallback before calling any methods.*"); + EXPECT_DEATH(fixed_channel_impl.Release(), + ".*Must register OnCloseCallback before calling any methods.*"); } TEST_F(L2capClassicFixedChannelImplTest, test_acquire_release_channel) { MockParameterProvider mock_parameter_provider; EXPECT_CALL(mock_parameter_provider, GetClassicLinkIdleDisconnectTimeout()) - .WillRepeatedly(Return(std::chrono::seconds(5))); + .WillRepeatedly(Return(std::chrono::seconds(5))); EXPECT_CALL(mock_parameter_provider, GetClassicLinkIdleDisconnectTimeout()) - .WillRepeatedly(Return(std::chrono::seconds(5))); + .WillRepeatedly(Return(std::chrono::seconds(5))); testing::MockClassicAclConnection* mock_acl_connection = new testing::MockClassicAclConnection(); EXPECT_CALL(*mock_acl_connection, GetAddress()).Times(1); EXPECT_CALL(*mock_acl_connection, RegisterCallbacks(_, l2cap_handler_)).Times(1); - MockLink mock_classic_link(l2cap_handler_, &mock_parameter_provider, - std::unique_ptr(mock_acl_connection), - nullptr /* LinkManager */); + MockLink mock_classic_link( + l2cap_handler_, &mock_parameter_provider, + std::unique_ptr(mock_acl_connection), + nullptr /* LinkManager */); hci::AddressWithType device{hci::Address{{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}, hci::AddressType::PUBLIC_IDENTITY_ADDRESS}; EXPECT_CALL(mock_classic_link, GetDevice()).WillRepeatedly(Return(device)); @@ -253,8 +268,8 @@ TEST_F(L2capClassicFixedChannelImplTest, test_acquire_release_channel) { auto user_handler = std::make_unique(thread_); hci::ErrorCode my_status = hci::ErrorCode::SUCCESS; fixed_channel_impl.RegisterOnCloseCallback( - user_handler.get(), - common::testing::BindLambdaForTesting([&my_status](hci::ErrorCode status) { my_status = status; })); + user_handler.get(), common::testing::BindLambdaForTesting( + [&my_status](hci::ErrorCode status) { my_status = status; })); // Default should be false EXPECT_FALSE(fixed_channel_impl.IsAcquired()); @@ -275,13 +290,14 @@ TEST_F(L2capClassicFixedChannelImplTest, test_acquire_after_close) { ::testing::FLAGS_gtest_death_test_style = "threadsafe"; MockParameterProvider mock_parameter_provider; EXPECT_CALL(mock_parameter_provider, GetClassicLinkIdleDisconnectTimeout()) - .WillRepeatedly(Return(std::chrono::seconds(5))); + .WillRepeatedly(Return(std::chrono::seconds(5))); testing::MockClassicAclConnection* mock_acl_connection = new testing::MockClassicAclConnection(); EXPECT_CALL(*mock_acl_connection, GetAddress()).Times(1); EXPECT_CALL(*mock_acl_connection, RegisterCallbacks(_, l2cap_handler_)).Times(1); - MockLink mock_classic_link(l2cap_handler_, &mock_parameter_provider, - std::unique_ptr(mock_acl_connection), - nullptr /* LinkManager */); + MockLink mock_classic_link( + l2cap_handler_, &mock_parameter_provider, + std::unique_ptr(mock_acl_connection), + nullptr /* LinkManager */); hci::AddressWithType device{hci::Address{{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}, hci::AddressType::PUBLIC_IDENTITY_ADDRESS}; EXPECT_CALL(mock_classic_link, GetDevice()).WillRepeatedly(Return(device)); @@ -292,11 +308,11 @@ TEST_F(L2capClassicFixedChannelImplTest, test_acquire_after_close) { hci::ErrorCode my_status = hci::ErrorCode::SUCCESS; std::promise promise; auto future = promise.get_future(); - fixed_channel_impl.RegisterOnCloseCallback(user_handler.get(), - common::testing::BindLambdaForTesting([&](hci::ErrorCode status) { - my_status = status; - promise.set_value(); - })); + fixed_channel_impl.RegisterOnCloseCallback( + user_handler.get(), common::testing::BindLambdaForTesting([&](hci::ErrorCode status) { + my_status = status; + promise.set_value(); + })); // Channel closure should trigger such callback fixed_channel_impl.OnClosed(hci::ErrorCode::REMOTE_USER_TERMINATED_CONNECTION); @@ -308,7 +324,8 @@ TEST_F(L2capClassicFixedChannelImplTest, test_acquire_after_close) { // Release or Acquire after closing should crash EXPECT_CALL(mock_classic_link, RefreshRefCount()).Times(0); EXPECT_FALSE(fixed_channel_impl.IsAcquired()); - EXPECT_DEATH(fixed_channel_impl.Acquire(), ".*Must register OnCloseCallback before calling any methods.*"); + EXPECT_DEATH(fixed_channel_impl.Acquire(), + ".*Must register OnCloseCallback before calling any methods.*"); user_handler->Clear(); } diff --git a/system/gd/l2cap/classic/internal/fixed_channel_service_impl.h b/system/gd/l2cap/classic/internal/fixed_channel_service_impl.h index b06983f3fc6..087f800b46c 100644 --- a/system/gd/l2cap/classic/internal/fixed_channel_service_impl.h +++ b/system/gd/l2cap/classic/internal/fixed_channel_service_impl.h @@ -26,7 +26,7 @@ namespace classic { namespace internal { class FixedChannelServiceImpl { - public: +public: virtual ~FixedChannelServiceImpl() = default; struct PendingRegistration { @@ -41,13 +41,14 @@ class FixedChannelServiceImpl { friend class FixedChannelServiceManagerImpl; - protected: +protected: // protected access for mocking FixedChannelServiceImpl(os::Handler* user_handler, FixedChannelManager::OnConnectionOpenCallback on_connection_open_callback) - : user_handler_(user_handler), on_connection_open_callback_(std::move(on_connection_open_callback)) {} + : user_handler_(user_handler), + on_connection_open_callback_(std::move(on_connection_open_callback)) {} - private: +private: os::Handler* user_handler_ = nullptr; FixedChannelManager::OnConnectionOpenCallback on_connection_open_callback_; }; diff --git a/system/gd/l2cap/classic/internal/fixed_channel_service_impl_mock.h b/system/gd/l2cap/classic/internal/fixed_channel_service_impl_mock.h index 7aeb094934a..9eebacfb4c8 100644 --- a/system/gd/l2cap/classic/internal/fixed_channel_service_impl_mock.h +++ b/system/gd/l2cap/classic/internal/fixed_channel_service_impl_mock.h @@ -15,11 +15,11 @@ */ #pragma once +#include + #include "l2cap/classic/internal/fixed_channel_impl.h" #include "l2cap/classic/internal/fixed_channel_service_manager_impl.h" -#include - // Unit test interfaces namespace bluetooth { namespace l2cap { @@ -28,8 +28,9 @@ namespace internal { namespace testing { class MockFixedChannelServiceImpl : public FixedChannelServiceImpl { - public: - MockFixedChannelServiceImpl() : FixedChannelServiceImpl(nullptr, FixedChannelManager::OnConnectionOpenCallback()) {} +public: + MockFixedChannelServiceImpl() + : FixedChannelServiceImpl(nullptr, FixedChannelManager::OnConnectionOpenCallback()) {} MOCK_METHOD(void, NotifyChannelCreation, (std::unique_ptr channel), (override)); }; diff --git a/system/gd/l2cap/classic/internal/fixed_channel_service_manager_impl.cc b/system/gd/l2cap/classic/internal/fixed_channel_service_manager_impl.cc index 0e9b6b9469a..169b55b06ad 100644 --- a/system/gd/l2cap/classic/internal/fixed_channel_service_manager_impl.cc +++ b/system/gd/l2cap/classic/internal/fixed_channel_service_manager_impl.cc @@ -28,31 +28,35 @@ namespace l2cap { namespace classic { namespace internal { -void FixedChannelServiceManagerImpl::Register(Cid cid, - FixedChannelServiceImpl::PendingRegistration pending_registration) { +void FixedChannelServiceManagerImpl::Register( + Cid cid, FixedChannelServiceImpl::PendingRegistration pending_registration) { if (cid < kFirstFixedChannel || cid > kLastFixedChannel || cid == kClassicSignallingCid) { std::unique_ptr invalid_service(new FixedChannelService()); pending_registration.user_handler_->Post( - common::BindOnce(std::move(pending_registration.on_registration_complete_callback_), - FixedChannelManager::RegistrationResult::FAIL_INVALID_SERVICE, std::move(invalid_service))); + common::BindOnce(std::move(pending_registration.on_registration_complete_callback_), + FixedChannelManager::RegistrationResult::FAIL_INVALID_SERVICE, + std::move(invalid_service))); } else if (IsServiceRegistered(cid)) { std::unique_ptr invalid_service(new FixedChannelService()); pending_registration.user_handler_->Post( - common::BindOnce(std::move(pending_registration.on_registration_complete_callback_), - FixedChannelManager::RegistrationResult::FAIL_DUPLICATE_SERVICE, std::move(invalid_service))); + common::BindOnce(std::move(pending_registration.on_registration_complete_callback_), + FixedChannelManager::RegistrationResult::FAIL_DUPLICATE_SERVICE, + std::move(invalid_service))); } else { - service_map_.try_emplace(cid, - FixedChannelServiceImpl(pending_registration.user_handler_, - std::move(pending_registration.on_connection_open_callback_))); - std::unique_ptr user_service(new FixedChannelService(cid, this, l2cap_layer_handler_)); - pending_registration.user_handler_->Post( - common::BindOnce(std::move(pending_registration.on_registration_complete_callback_), - FixedChannelManager::RegistrationResult::SUCCESS, std::move(user_service))); + service_map_.try_emplace( + cid, + FixedChannelServiceImpl(pending_registration.user_handler_, + std::move(pending_registration.on_connection_open_callback_))); + std::unique_ptr user_service( + new FixedChannelService(cid, this, l2cap_layer_handler_)); + pending_registration.user_handler_->Post(common::BindOnce( + std::move(pending_registration.on_registration_complete_callback_), + FixedChannelManager::RegistrationResult::SUCCESS, std::move(user_service))); } } -void FixedChannelServiceManagerImpl::Unregister(Cid cid, FixedChannelService::OnUnregisteredCallback callback, - os::Handler* handler) { +void FixedChannelServiceManagerImpl::Unregister( + Cid cid, FixedChannelService::OnUnregisteredCallback callback, os::Handler* handler) { if (IsServiceRegistered(cid)) { service_map_.erase(cid); handler->Post(std::move(callback)); @@ -70,7 +74,8 @@ FixedChannelServiceImpl* FixedChannelServiceManagerImpl::GetService(Cid cid) { return &service_map_.find(cid)->second; } -std::vector> FixedChannelServiceManagerImpl::GetRegisteredServices() { +std::vector> +FixedChannelServiceManagerImpl::GetRegisteredServices() { std::vector> results; for (auto& elem : service_map_) { results.emplace_back(elem.first, &elem.second); diff --git a/system/gd/l2cap/classic/internal/fixed_channel_service_manager_impl.h b/system/gd/l2cap/classic/internal/fixed_channel_service_manager_impl.h index 1e1d21deb92..24edbcf2c1c 100644 --- a/system/gd/l2cap/classic/internal/fixed_channel_service_manager_impl.h +++ b/system/gd/l2cap/classic/internal/fixed_channel_service_manager_impl.h @@ -29,7 +29,7 @@ namespace classic { namespace internal { class FixedChannelServiceManagerImpl { - public: +public: explicit FixedChannelServiceManagerImpl(os::Handler* l2cap_layer_handler) : l2cap_layer_handler_(l2cap_layer_handler) {} virtual ~FixedChannelServiceManagerImpl() = default; @@ -37,13 +37,14 @@ class FixedChannelServiceManagerImpl { // All APIs must be invoked in L2CAP layer handler virtual void Register(Cid cid, FixedChannelServiceImpl::PendingRegistration pending_registration); - virtual void Unregister(Cid cid, FixedChannelService::OnUnregisteredCallback callback, os::Handler* handler); + virtual void Unregister(Cid cid, FixedChannelService::OnUnregisteredCallback callback, + os::Handler* handler); virtual bool IsServiceRegistered(Cid cid) const; virtual FixedChannelServiceImpl* GetService(Cid cid); virtual std::vector> GetRegisteredServices(); virtual uint64_t GetSupportedFixedChannelMask(); - private: +private: os::Handler* l2cap_layer_handler_ = nullptr; std::unordered_map service_map_; }; diff --git a/system/gd/l2cap/classic/internal/fixed_channel_service_manager_impl_mock.h b/system/gd/l2cap/classic/internal/fixed_channel_service_manager_impl_mock.h index 55aa4cfc21a..49acdf6157d 100644 --- a/system/gd/l2cap/classic/internal/fixed_channel_service_manager_impl_mock.h +++ b/system/gd/l2cap/classic/internal/fixed_channel_service_manager_impl_mock.h @@ -15,11 +15,11 @@ */ #pragma once +#include + #include "l2cap/classic/internal/fixed_channel_impl.h" #include "l2cap/classic/internal/fixed_channel_service_manager_impl.h" -#include - // Unit test interfaces namespace bluetooth { namespace l2cap { @@ -28,14 +28,18 @@ namespace internal { namespace testing { class MockFixedChannelServiceManagerImpl : public FixedChannelServiceManagerImpl { - public: +public: MockFixedChannelServiceManagerImpl() : FixedChannelServiceManagerImpl(nullptr) {} - MOCK_METHOD(void, Register, (Cid cid, FixedChannelServiceImpl::PendingRegistration pending_registration), (override)); - MOCK_METHOD(void, Unregister, (Cid cid, FixedChannelService::OnUnregisteredCallback callback, os::Handler* handler), + MOCK_METHOD(void, Register, + (Cid cid, FixedChannelServiceImpl::PendingRegistration pending_registration), + (override)); + MOCK_METHOD(void, Unregister, + (Cid cid, FixedChannelService::OnUnregisteredCallback callback, os::Handler* handler), (override)); MOCK_METHOD(bool, IsServiceRegistered, (Cid cid), (const, override)); MOCK_METHOD(FixedChannelServiceImpl*, GetService, (Cid cid), (override)); - MOCK_METHOD((std::vector>), GetRegisteredServices, (), (override)); + MOCK_METHOD((std::vector>), GetRegisteredServices, (), + (override)); }; } // namespace testing diff --git a/system/gd/l2cap/classic/internal/fixed_channel_service_manager_test.cc b/system/gd/l2cap/classic/internal/fixed_channel_service_manager_test.cc index 7d5d8afdf01..ea1dc1227a9 100644 --- a/system/gd/l2cap/classic/internal/fixed_channel_service_manager_test.cc +++ b/system/gd/l2cap/classic/internal/fixed_channel_service_manager_test.cc @@ -14,7 +14,7 @@ * limitations under the License. */ -#include "l2cap/classic/internal/fixed_channel_service_manager_impl.h" +#include #include @@ -22,18 +22,17 @@ #include "l2cap/cid.h" #include "l2cap/classic/fixed_channel_manager.h" #include "l2cap/classic/fixed_channel_service.h" +#include "l2cap/classic/internal/fixed_channel_service_manager_impl.h" #include "os/handler.h" #include "os/thread.h" -#include - namespace bluetooth { namespace l2cap { namespace classic { namespace internal { class L2capClassicFixedServiceManagerTest : public ::testing::Test { - public: +public: ~L2capClassicFixedServiceManagerTest() = default; void OnServiceRegistered(bool expect_success, FixedChannelManager::RegistrationResult result, @@ -42,7 +41,7 @@ class L2capClassicFixedServiceManagerTest : public ::testing::Test { service_registered_ = expect_success; } - protected: +protected: void SetUp() override { manager_ = new FixedChannelServiceManagerImpl{nullptr}; thread_ = new os::Thread("test_thread", os::Thread::Priority::NORMAL); @@ -59,7 +58,8 @@ class L2capClassicFixedServiceManagerTest : public ::testing::Test { void sync_user_handler() { std::promise promise; auto future = promise.get_future(); - user_handler_->Post(common::BindOnce(&std::promise::set_value, common::Unretained(&promise))); + user_handler_->Post( + common::BindOnce(&std::promise::set_value, common::Unretained(&promise))); future.wait_for(std::chrono::milliseconds(3)); } @@ -72,9 +72,10 @@ class L2capClassicFixedServiceManagerTest : public ::testing::Test { TEST_F(L2capClassicFixedServiceManagerTest, register_and_unregister_classic_fixed_channel) { FixedChannelServiceImpl::PendingRegistration pending_registration{ - .user_handler_ = user_handler_, - .on_registration_complete_callback_ = - common::BindOnce(&L2capClassicFixedServiceManagerTest::OnServiceRegistered, common::Unretained(this), true)}; + .user_handler_ = user_handler_, + .on_registration_complete_callback_ = + common::BindOnce(&L2capClassicFixedServiceManagerTest::OnServiceRegistered, + common::Unretained(this), true)}; Cid cid = kSmpBrCid; EXPECT_FALSE(manager_->IsServiceRegistered(cid)); manager_->Register(cid, std::move(pending_registration)); @@ -87,9 +88,10 @@ TEST_F(L2capClassicFixedServiceManagerTest, register_and_unregister_classic_fixe TEST_F(L2capClassicFixedServiceManagerTest, register_classic_fixed_channel_bad_cid) { FixedChannelServiceImpl::PendingRegistration pending_registration{ - .user_handler_ = user_handler_, - .on_registration_complete_callback_ = - common::BindOnce(&L2capClassicFixedServiceManagerTest::OnServiceRegistered, common::Unretained(this), false)}; + .user_handler_ = user_handler_, + .on_registration_complete_callback_ = + common::BindOnce(&L2capClassicFixedServiceManagerTest::OnServiceRegistered, + common::Unretained(this), false)}; Cid cid = 0x1000; EXPECT_FALSE(manager_->IsServiceRegistered(cid)); manager_->Register(cid, std::move(pending_registration)); diff --git a/system/gd/l2cap/classic/internal/link.cc b/system/gd/l2cap/classic/internal/link.cc index 0e0d48ab942..11711558578 100644 --- a/system/gd/l2cap/classic/internal/link.cc +++ b/system/gd/l2cap/classic/internal/link.cc @@ -34,17 +34,16 @@ namespace l2cap { namespace classic { namespace internal { -using RetransmissionAndFlowControlMode = DynamicChannelConfigurationOption::RetransmissionAndFlowControlMode; +using RetransmissionAndFlowControlMode = + DynamicChannelConfigurationOption::RetransmissionAndFlowControlMode; using ConnectionResult = DynamicChannelManager::ConnectionResult; using ConnectionResultCode = DynamicChannelManager::ConnectionResultCode; -Link::Link( - os::Handler* l2cap_handler, - std::unique_ptr acl_connection, - l2cap::internal::ParameterProvider* parameter_provider, - DynamicChannelServiceManagerImpl* dynamic_service_manager, - FixedChannelServiceManagerImpl* fixed_service_manager, - LinkManager* link_manager) +Link::Link(os::Handler* l2cap_handler, + std::unique_ptr acl_connection, + l2cap::internal::ParameterProvider* parameter_provider, + DynamicChannelServiceManagerImpl* dynamic_service_manager, + FixedChannelServiceManagerImpl* fixed_service_manager, LinkManager* link_manager) : l2cap_handler_(l2cap_handler), acl_connection_(std::move(acl_connection)), data_pipeline_manager_(l2cap_handler, this, acl_connection_->GetAclQueueEnd()), @@ -52,19 +51,15 @@ Link::Link( dynamic_service_manager_(dynamic_service_manager), fixed_service_manager_(fixed_service_manager), link_manager_(link_manager), - signalling_manager_( - l2cap_handler_, - this, - &data_pipeline_manager_, - dynamic_service_manager_, - &dynamic_channel_allocator_, - fixed_service_manager_), + signalling_manager_(l2cap_handler_, this, &data_pipeline_manager_, dynamic_service_manager_, + &dynamic_channel_allocator_, fixed_service_manager_), acl_handle_(acl_connection_->GetHandle()) { log::assert_that(l2cap_handler_ != nullptr, "assert failed: l2cap_handler_ != nullptr"); log::assert_that(acl_connection_ != nullptr, "assert failed: acl_connection_ != nullptr"); log::assert_that(parameter_provider_ != nullptr, "assert failed: parameter_provider_ != nullptr"); - link_idle_disconnect_alarm_.Schedule(common::BindOnce(&Link::Disconnect, common::Unretained(this)), - parameter_provider_->GetClassicLinkIdleDisconnectTimeout()); + link_idle_disconnect_alarm_.Schedule( + common::BindOnce(&Link::Disconnect, common::Unretained(this)), + parameter_provider_->GetClassicLinkIdleDisconnectTimeout()); acl_connection_->RegisterCallbacks(this, l2cap_handler_); } @@ -73,9 +68,9 @@ void Link::OnAclDisconnected(hci::ErrorCode status) { fixed_channel_allocator_.OnAclDisconnected(status); dynamic_channel_allocator_.OnAclDisconnected(status); ConnectionResult result{ - .connection_result_code = ConnectionResultCode::FAIL_HCI_ERROR, - .hci_error = status, - .l2cap_connection_response_result = ConnectionResponseResult::SUCCESS, + .connection_result_code = ConnectionResultCode::FAIL_HCI_ERROR, + .hci_error = status, + .l2cap_connection_response_result = ConnectionResponseResult::SUCCESS, }; while (!local_cid_to_pending_dynamic_channel_connection_map_.empty()) { auto entry = local_cid_to_pending_dynamic_channel_connection_map_.begin(); @@ -100,25 +95,17 @@ void Link::Authenticate() { } } -bool Link::IsAuthenticated() const { - return encryption_enabled_ != hci::EncryptionEnabled::OFF; -} +bool Link::IsAuthenticated() const { return encryption_enabled_ != hci::EncryptionEnabled::OFF; } -void Link::ReadRemoteVersionInformation() { - acl_connection_->ReadRemoteVersionInformation(); -} +void Link::ReadRemoteVersionInformation() { acl_connection_->ReadRemoteVersionInformation(); } -void Link::ReadRemoteSupportedFeatures() { - acl_connection_->ReadRemoteSupportedFeatures(); -} +void Link::ReadRemoteSupportedFeatures() { acl_connection_->ReadRemoteSupportedFeatures(); } void Link::ReadRemoteExtendedFeatures(uint8_t page_number) { acl_connection_->ReadRemoteExtendedFeatures(page_number); } -void Link::ReadClockOffset() { - acl_connection_->ReadClockOffset(); -} +void Link::ReadClockOffset() { acl_connection_->ReadClockOffset(); } void Link::AcquireSecurityHold() { used_by_security_module_ = true; @@ -131,7 +118,8 @@ void Link::ReleaseSecurityHold() { std::shared_ptr Link::AllocateFixedChannel(Cid cid) { auto channel = fixed_channel_allocator_.AllocateChannel(cid); - data_pipeline_manager_.AttachChannel(cid, channel, l2cap::internal::DataPipelineManager::ChannelMode::BASIC); + data_pipeline_manager_.AttachChannel(cid, channel, + l2cap::internal::DataPipelineManager::ChannelMode::BASIC); return channel; } @@ -139,18 +127,17 @@ bool Link::IsFixedChannelAllocated(Cid cid) { return fixed_channel_allocator_.IsChannelAllocated(cid); } -Cid Link::ReserveDynamicChannel() { - return dynamic_channel_allocator_.ReserveChannel(); -} +Cid Link::ReserveDynamicChannel() { return dynamic_channel_allocator_.ReserveChannel(); } void Link::SendConnectionRequest(Psm psm, Cid local_cid) { signalling_manager_.SendConnectionRequest(psm, local_cid); } -void Link::SendConnectionRequest(Psm psm, Cid local_cid, - PendingDynamicChannelConnection pending_dynamic_channel_connection) { +void Link::SendConnectionRequest( + Psm psm, Cid local_cid, + PendingDynamicChannelConnection pending_dynamic_channel_connection) { if (pending_dynamic_channel_connection.configuration_.channel_mode == - RetransmissionAndFlowControlMode::ENHANCED_RETRANSMISSION && + RetransmissionAndFlowControlMode::ENHANCED_RETRANSMISSION && !remote_extended_feature_received_) { pending_dynamic_psm_list_.push_back(psm); pending_dynamic_channel_callback_list_.push_back(std::move(pending_dynamic_channel_connection)); @@ -158,17 +145,18 @@ void Link::SendConnectionRequest(Psm psm, Cid local_cid, dynamic_channel_allocator_.FreeChannel(local_cid); return; } else if (pending_dynamic_channel_connection.configuration_.channel_mode == - RetransmissionAndFlowControlMode::ENHANCED_RETRANSMISSION && + RetransmissionAndFlowControlMode::ENHANCED_RETRANSMISSION && !GetRemoteSupportsErtm()) { log::warn("Remote doesn't support ERTM. Dropping connection request"); ConnectionResult result{ - .connection_result_code = ConnectionResultCode::FAIL_REMOTE_NOT_SUPPORT, + .connection_result_code = ConnectionResultCode::FAIL_REMOTE_NOT_SUPPORT, }; pending_dynamic_channel_connection.on_fail_callback_(result); dynamic_channel_allocator_.FreeChannel(local_cid); return; } else { - local_cid_to_pending_dynamic_channel_connection_map_[local_cid] = std::move(pending_dynamic_channel_connection); + local_cid_to_pending_dynamic_channel_connection_map_[local_cid] = + std::move(pending_dynamic_channel_connection); signalling_manager_.SendConnectionRequest(psm, local_cid); } } @@ -177,11 +165,10 @@ void Link::SetChannelTxPriority(Cid local_cid, bool high_priority) { data_pipeline_manager_.SetChannelTxPriority(local_cid, high_priority); } -void Link::SetPendingDynamicChannels(std::list psm_list, - std::list callback_list) { - log::assert_that( - psm_list.size() == callback_list.size(), - "assert failed: psm_list.size() == callback_list.size()"); +void Link::SetPendingDynamicChannels( + std::list psm_list, std::list callback_list) { + log::assert_that(psm_list.size() == callback_list.size(), + "assert failed: psm_list.size() == callback_list.size()"); pending_dynamic_psm_list_ = std::move(psm_list); pending_dynamic_channel_callback_list_ = std::move(callback_list); } @@ -227,7 +214,8 @@ void Link::SendInformationRequest(InformationRequestInfoType type) { signalling_manager_.SendInformationRequest(type); } -std::shared_ptr Link::AllocateDynamicChannel(Psm psm, Cid remote_cid) { +std::shared_ptr Link::AllocateDynamicChannel(Psm psm, + Cid remote_cid) { auto channel = dynamic_channel_allocator_.AllocateChannel(psm, remote_cid); if (channel != nullptr) { RefreshRefCount(); @@ -236,8 +224,8 @@ std::shared_ptr Link::AllocateDynamicChanne return channel; } -std::shared_ptr Link::AllocateReservedDynamicChannel(Cid reserved_cid, Psm psm, - Cid remote_cid) { +std::shared_ptr Link::AllocateReservedDynamicChannel( + Cid reserved_cid, Psm psm, Cid remote_cid) { auto channel = dynamic_channel_allocator_.AllocateReservedChannel(reserved_cid, psm, remote_cid); if (channel != nullptr) { RefreshRefCount(); @@ -248,10 +236,10 @@ std::shared_ptr Link::AllocateReservedDynam classic::DynamicChannelConfigurationOption Link::GetConfigurationForInitialConfiguration(Cid cid) { log::assert_that( - local_cid_to_pending_dynamic_channel_connection_map_.find(cid) != - local_cid_to_pending_dynamic_channel_connection_map_.end(), - "assert failed: local_cid_to_pending_dynamic_channel_connection_map_.find(cid) != " - "local_cid_to_pending_dynamic_channel_connection_map_.end()"); + local_cid_to_pending_dynamic_channel_connection_map_.find(cid) != + local_cid_to_pending_dynamic_channel_connection_map_.end(), + "assert failed: local_cid_to_pending_dynamic_channel_connection_map_.find(cid) != " + "local_cid_to_pending_dynamic_channel_connection_map_.end()"); return local_cid_to_pending_dynamic_channel_connection_map_[cid].configuration_; } @@ -274,48 +262,43 @@ void Link::RefreshRefCount() { if (ref_count > 0) { link_idle_disconnect_alarm_.Cancel(); } else { - link_idle_disconnect_alarm_.Schedule(common::BindOnce(&Link::Disconnect, common::Unretained(this)), - parameter_provider_->GetClassicLinkIdleDisconnectTimeout()); + link_idle_disconnect_alarm_.Schedule( + common::BindOnce(&Link::Disconnect, common::Unretained(this)), + parameter_provider_->GetClassicLinkIdleDisconnectTimeout()); } } void Link::NotifyChannelCreation(Cid cid, std::unique_ptr user_channel) { log::assert_that( - local_cid_to_pending_dynamic_channel_connection_map_.find(cid) != - local_cid_to_pending_dynamic_channel_connection_map_.end(), - "assert failed: local_cid_to_pending_dynamic_channel_connection_map_.find(cid) != " - "local_cid_to_pending_dynamic_channel_connection_map_.end()"); - auto& pending_dynamic_channel_connection = local_cid_to_pending_dynamic_channel_connection_map_[cid]; + local_cid_to_pending_dynamic_channel_connection_map_.find(cid) != + local_cid_to_pending_dynamic_channel_connection_map_.end(), + "assert failed: local_cid_to_pending_dynamic_channel_connection_map_.find(cid) != " + "local_cid_to_pending_dynamic_channel_connection_map_.end()"); + auto& pending_dynamic_channel_connection = + local_cid_to_pending_dynamic_channel_connection_map_[cid]; pending_dynamic_channel_connection.on_open_callback_(std::move(user_channel)); local_cid_to_pending_dynamic_channel_connection_map_.erase(cid); } void Link::NotifyChannelFail(Cid cid, ConnectionResult result) { log::assert_that( - local_cid_to_pending_dynamic_channel_connection_map_.find(cid) != - local_cid_to_pending_dynamic_channel_connection_map_.end(), - "assert failed: local_cid_to_pending_dynamic_channel_connection_map_.find(cid) != " - "local_cid_to_pending_dynamic_channel_connection_map_.end()"); - auto& pending_dynamic_channel_connection = local_cid_to_pending_dynamic_channel_connection_map_[cid]; + local_cid_to_pending_dynamic_channel_connection_map_.find(cid) != + local_cid_to_pending_dynamic_channel_connection_map_.end(), + "assert failed: local_cid_to_pending_dynamic_channel_connection_map_.find(cid) != " + "local_cid_to_pending_dynamic_channel_connection_map_.end()"); + auto& pending_dynamic_channel_connection = + local_cid_to_pending_dynamic_channel_connection_map_[cid]; pending_dynamic_channel_connection.on_fail_callback_(result); local_cid_to_pending_dynamic_channel_connection_map_.erase(cid); } -void Link::SetRemoteConnectionlessMtu(Mtu mtu) { - remote_connectionless_mtu_ = mtu; -} +void Link::SetRemoteConnectionlessMtu(Mtu mtu) { remote_connectionless_mtu_ = mtu; } -Mtu Link::GetRemoteConnectionlessMtu() const { - return remote_connectionless_mtu_; -} +Mtu Link::GetRemoteConnectionlessMtu() const { return remote_connectionless_mtu_; } -bool Link::GetRemoteSupportsErtm() const { - return remote_supports_ertm_; -} +bool Link::GetRemoteSupportsErtm() const { return remote_supports_ertm_; } -bool Link::GetRemoteSupportsFcs() const { - return remote_supports_fcs_; -} +bool Link::GetRemoteSupportsFcs() const { return remote_supports_fcs_; } void Link::OnRemoteExtendedFeatureReceived(bool ertm_supported, bool fcs_supported) { remote_supports_ertm_ = ertm_supported; @@ -338,16 +321,12 @@ void Link::OnEncryptionChange(hci::EncryptionEnabled enabled) { link_manager_->OnEncryptionChange(GetDevice().GetAddress(), enabled); for (auto& listener : encryption_change_listener_) { signalling_manager_.on_security_result_for_outgoing( - ClassicSignallingManager::SecurityEnforcementType::ENCRYPTION, - listener.psm, - listener.cid, - enabled != hci::EncryptionEnabled::OFF); + ClassicSignallingManager::SecurityEnforcementType::ENCRYPTION, listener.psm, + listener.cid, enabled != hci::EncryptionEnabled::OFF); } } -void Link::OnChangeConnectionLinkKeyComplete() { - log::info("UNIMPLEMENTED"); -} +void Link::OnChangeConnectionLinkKeyComplete() { log::info("UNIMPLEMENTED"); } void Link::OnReadClockOffsetComplete(uint16_t clock_offset) { link_manager_->OnReadClockOffset(GetDevice().GetAddress(), clock_offset); @@ -357,51 +336,33 @@ void Link::OnModeChange(hci::ErrorCode status, hci::Mode current_mode, uint16_t link_manager_->OnModeChange(status, GetDevice().GetAddress(), current_mode, interval); } -void Link::OnSniffSubrating( - hci::ErrorCode hci_status, - uint16_t maximum_transmit_latency, - uint16_t maximum_receive_latency, - uint16_t minimum_remote_timeout, - uint16_t minimum_local_timeout) { - link_manager_->OnSniffSubrating( - hci_status, - GetDevice().GetAddress(), - maximum_transmit_latency, - maximum_receive_latency, - minimum_remote_timeout, - minimum_local_timeout); +void Link::OnSniffSubrating(hci::ErrorCode hci_status, uint16_t maximum_transmit_latency, + uint16_t maximum_receive_latency, uint16_t minimum_remote_timeout, + uint16_t minimum_local_timeout) { + link_manager_->OnSniffSubrating(hci_status, GetDevice().GetAddress(), maximum_transmit_latency, + maximum_receive_latency, minimum_remote_timeout, + minimum_local_timeout); } -void Link::OnQosSetupComplete(hci::ServiceType service_type, uint32_t token_rate, uint32_t peak_bandwidth, - uint32_t latency, uint32_t delay_variation) { +void Link::OnQosSetupComplete(hci::ServiceType service_type, uint32_t token_rate, + uint32_t peak_bandwidth, uint32_t latency, uint32_t delay_variation) { log::info( - "UNIMPLEMENTED service_type:{} token_rate:{} peak_bandwidth:{} latency:{} " - "delay_varitation:{}", - hci::ServiceTypeText(service_type), - token_rate, - peak_bandwidth, - latency, - delay_variation); -} -void Link::OnFlowSpecificationComplete(hci::FlowDirection flow_direction, hci::ServiceType service_type, - uint32_t token_rate, uint32_t token_bucket_size, uint32_t peak_bandwidth, + "UNIMPLEMENTED service_type:{} token_rate:{} peak_bandwidth:{} latency:{} " + "delay_varitation:{}", + hci::ServiceTypeText(service_type), token_rate, peak_bandwidth, latency, delay_variation); +} +void Link::OnFlowSpecificationComplete(hci::FlowDirection flow_direction, + hci::ServiceType service_type, uint32_t token_rate, + uint32_t token_bucket_size, uint32_t peak_bandwidth, uint32_t access_latency) { log::info( - "UNIMPLEMENTED flow_direction:{} service_type:{} token_rate:{} token_bucket_size:{} " - "peak_bandwidth:{} access_latency:{}", - hci::FlowDirectionText(flow_direction), - hci::ServiceTypeText(service_type), - token_rate, - token_bucket_size, - peak_bandwidth, - access_latency); -} -void Link::OnFlushOccurred() { - log::info("UNIMPLEMENTED"); -} -void Link::OnRoleDiscoveryComplete(hci::Role current_role) { - role_ = current_role; + "UNIMPLEMENTED flow_direction:{} service_type:{} token_rate:{} token_bucket_size:{} " + "peak_bandwidth:{} access_latency:{}", + hci::FlowDirectionText(flow_direction), hci::ServiceTypeText(service_type), token_rate, + token_bucket_size, peak_bandwidth, access_latency); } +void Link::OnFlushOccurred() { log::info("UNIMPLEMENTED"); } +void Link::OnRoleDiscoveryComplete(hci::Role current_role) { role_ = current_role; } void Link::OnReadLinkPolicySettingsComplete(uint16_t link_policy_settings) { log::info("UNIMPLEMENTED link_policy_settings:0x{:x}", link_policy_settings); } @@ -420,13 +381,11 @@ void Link::OnReadFailedContactCounterComplete(uint16_t failed_contact_counter) { void Link::OnReadLinkQualityComplete(uint8_t link_quality) { log::info("UNIMPLEMENTED link_quality:{}", link_quality); } -void Link::OnReadAfhChannelMapComplete( - hci::AfhMode afh_mode, std::array /* afh_channel_map */) { +void Link::OnReadAfhChannelMapComplete(hci::AfhMode afh_mode, + std::array /* afh_channel_map */) { log::info("UNIMPLEMENTED afh_mode:{}", hci::AfhModeText(afh_mode)); } -void Link::OnReadRssiComplete(uint8_t rssi) { - log::info("UNIMPLEMENTED rssi:{}", rssi); -} +void Link::OnReadRssiComplete(uint8_t rssi) { log::info("UNIMPLEMENTED rssi:{}", rssi); } void Link::OnReadClockComplete(uint32_t clock, uint16_t accuracy) { log::info("UNIMPLEMENTED clock:{} accuracy:{}", clock, accuracy); } @@ -441,32 +400,26 @@ void Link::OnDisconnection(hci::ErrorCode reason) { OnAclDisconnected(reason); link_manager_->OnDisconnect(GetDevice().GetAddress(), reason); } -void Link::OnReadRemoteVersionInformationComplete( - hci::ErrorCode hci_status, uint8_t lmp_version, uint16_t manufacturer_name, uint16_t sub_version) { - log::info( - "UNIMPLEMENTED hci_status:{} lmp_version:{} manufacturer_name:{} sub_version:{}", - ErrorCodeText(hci_status), - lmp_version, - manufacturer_name, - sub_version); - link_manager_->OnReadRemoteVersionInformation( - hci_status, GetDevice().GetAddress(), lmp_version, manufacturer_name, sub_version); +void Link::OnReadRemoteVersionInformationComplete(hci::ErrorCode hci_status, uint8_t lmp_version, + uint16_t manufacturer_name, + uint16_t sub_version) { + log::info("UNIMPLEMENTED hci_status:{} lmp_version:{} manufacturer_name:{} sub_version:{}", + ErrorCodeText(hci_status), lmp_version, manufacturer_name, sub_version); + link_manager_->OnReadRemoteVersionInformation(hci_status, GetDevice().GetAddress(), lmp_version, + manufacturer_name, sub_version); } void Link::OnReadRemoteSupportedFeaturesComplete(uint64_t features) { - log::info( - "page_number:{} features:0x{:x}", - static_cast(0), - static_cast(features)); + log::info("page_number:{} features:0x{:x}", static_cast(0), + static_cast(features)); link_manager_->OnReadRemoteSupportedFeatures(GetDevice().GetAddress(), features); } -void Link::OnReadRemoteExtendedFeaturesComplete(uint8_t page_number, uint8_t max_page_number, uint64_t features) { - log::info( - "page_number:{} max_page_number:{} features:0x{:x}", - page_number, - max_page_number, - static_cast(features)); - link_manager_->OnReadRemoteExtendedFeatures(GetDevice().GetAddress(), page_number, max_page_number, features); +void Link::OnReadRemoteExtendedFeaturesComplete(uint8_t page_number, uint8_t max_page_number, + uint64_t features) { + log::info("page_number:{} max_page_number:{} features:0x{:x}", page_number, max_page_number, + static_cast(features)); + link_manager_->OnReadRemoteExtendedFeatures(GetDevice().GetAddress(), page_number, + max_page_number, features); } void Link::AddEncryptionChangeListener(EncryptionChangeListener listener) { diff --git a/system/gd/l2cap/classic/internal/link.h b/system/gd/l2cap/classic/internal/link.h index 37e100763ab..5077eb7b890 100644 --- a/system/gd/l2cap/classic/internal/link.h +++ b/system/gd/l2cap/classic/internal/link.h @@ -48,11 +48,12 @@ class DumpsysHelper; class Link : public l2cap::internal::ILink, public hci::acl_manager::ConnectionManagementCallbacks, public bluetooth::common::IRedactableLoggable { - public: - Link(os::Handler* l2cap_handler, std::unique_ptr acl_connection, +public: + Link(os::Handler* l2cap_handler, + std::unique_ptr acl_connection, l2cap::internal::ParameterProvider* parameter_provider, - DynamicChannelServiceManagerImpl* dynamic_service_manager, FixedChannelServiceManagerImpl* fixed_service_manager, - LinkManager* link_manager); + DynamicChannelServiceManagerImpl* dynamic_service_manager, + FixedChannelServiceManagerImpl* fixed_service_manager, LinkManager* link_manager); Link(const Link&) = delete; Link& operator=(const Link&) = delete; @@ -94,7 +95,8 @@ class Link : public l2cap::internal::ILink, virtual void ReadClockOffset(); - // Increase the link usage refcount to ensure the link won't be disconnected when SecurityModule needs it + // Increase the link usage refcount to ensure the link won't be disconnected when SecurityModule + // needs it virtual void AcquireSecurityHold(); // Decrease the link usage refcount when SecurityModule no longer needs it @@ -111,16 +113,19 @@ class Link : public l2cap::internal::ILink, virtual Cid ReserveDynamicChannel(); virtual void SendConnectionRequest(Psm psm, Cid local_cid); - virtual void SendConnectionRequest(Psm psm, Cid local_cid, - PendingDynamicChannelConnection pending_dynamic_channel_connection); + virtual void SendConnectionRequest( + Psm psm, Cid local_cid, + PendingDynamicChannelConnection pending_dynamic_channel_connection); void SetChannelTxPriority(Cid local_cid, bool high_priority) override; // When a Link is established, LinkManager notifies pending dynamic channels to connect - virtual void SetPendingDynamicChannels(std::list psm_list, - std::list callback_list); + virtual void SetPendingDynamicChannels( + std::list psm_list, std::list callback_list); - // Invoked by signalling manager to indicate an outgoing connection request failed and link shall free resources - virtual void OnOutgoingConnectionRequestFail(Cid local_cid, DynamicChannelManager::ConnectionResult result); + // Invoked by signalling manager to indicate an outgoing connection request failed and link shall + // free resources + virtual void OnOutgoingConnectionRequestFail(Cid local_cid, + DynamicChannelManager::ConnectionResult result); virtual void SendInitialConfigRequestOrQueue(Cid local_cid); @@ -128,16 +133,19 @@ class Link : public l2cap::internal::ILink, virtual void SendDisconnectionRequest(Cid local_cid, Cid remote_cid) override; - virtual std::shared_ptr AllocateDynamicChannel(Psm psm, Cid remote_cid); + virtual std::shared_ptr AllocateDynamicChannel( + Psm psm, Cid remote_cid); - virtual std::shared_ptr AllocateReservedDynamicChannel(Cid reserved_cid, Psm psm, - Cid remote_cid); + virtual std::shared_ptr AllocateReservedDynamicChannel( + Cid reserved_cid, Psm psm, Cid remote_cid); - virtual classic::DynamicChannelConfigurationOption GetConfigurationForInitialConfiguration(Cid cid); + virtual classic::DynamicChannelConfigurationOption GetConfigurationForInitialConfiguration( + Cid cid); virtual void FreeDynamicChannel(Cid cid); - // Check how many channels are acquired or in use, if zero, start tear down timer, if non-zero, cancel tear down timer + // Check how many channels are acquired or in use, if zero, start tear down timer, if non-zero, + // cancel tear down timer virtual void RefreshRefCount(); virtual void NotifyChannelCreation(Cid cid, std::unique_ptr channel); @@ -150,13 +158,9 @@ class Link : public l2cap::internal::ILink, virtual bool GetRemoteSupportsFcs() const; virtual void OnRemoteExtendedFeatureReceived(bool ertm_supported, bool fcs_supported); - virtual std::string ToString() const { - return GetDevice().ToString(); - } + virtual std::string ToString() const { return GetDevice().ToString(); } - std::string ToStringForLogging() const override { - return GetDevice().ToStringForLogging(); - } + std::string ToStringForLogging() const override { return GetDevice().ToStringForLogging(); } std::string ToRedactedStringForLogging() const override { return GetDevice().ToRedactedStringForLogging(); @@ -171,17 +175,15 @@ class Link : public l2cap::internal::ILink, void OnChangeConnectionLinkKeyComplete() override; void OnReadClockOffsetComplete(uint16_t clock_offset) override; void OnModeChange(hci::ErrorCode status, hci::Mode current_mode, uint16_t interval) override; - void OnSniffSubrating( - hci::ErrorCode hci_status, - uint16_t maximum_transmit_latency, - uint16_t maximum_receive_latency, - uint16_t minimum_remote_timeout, - uint16_t minimum_local_timeout) override; - void OnQosSetupComplete(hci::ServiceType service_type, uint32_t token_rate, uint32_t peak_bandwidth, uint32_t latency, + void OnSniffSubrating(hci::ErrorCode hci_status, uint16_t maximum_transmit_latency, + uint16_t maximum_receive_latency, uint16_t minimum_remote_timeout, + uint16_t minimum_local_timeout) override; + void OnQosSetupComplete(hci::ServiceType service_type, uint32_t token_rate, + uint32_t peak_bandwidth, uint32_t latency, uint32_t delay_variation) override; void OnFlowSpecificationComplete(hci::FlowDirection flow_direction, hci::ServiceType service_type, - uint32_t token_rate, uint32_t token_bucket_size, uint32_t peak_bandwidth, - uint32_t access_latency) override; + uint32_t token_rate, uint32_t token_bucket_size, + uint32_t peak_bandwidth, uint32_t access_latency) override; void OnFlushOccurred() override; void OnRoleDiscoveryComplete(hci::Role current_role) override; void OnReadLinkPolicySettingsComplete(uint16_t link_policy_settings) override; @@ -190,16 +192,18 @@ class Link : public l2cap::internal::ILink, void OnReadLinkSupervisionTimeoutComplete(uint16_t link_supervision_timeout) override; void OnReadFailedContactCounterComplete(uint16_t failed_contact_counter) override; void OnReadLinkQualityComplete(uint8_t link_quality) override; - void OnReadAfhChannelMapComplete(hci::AfhMode afh_mode, std::array afh_channel_map) override; + void OnReadAfhChannelMapComplete(hci::AfhMode afh_mode, + std::array afh_channel_map) override; void OnReadRssiComplete(uint8_t rssi) override; void OnReadClockComplete(uint32_t clock, uint16_t accuracy) override; void OnCentralLinkKeyComplete(hci::KeyFlag key_flag) override; void OnRoleChange(hci::ErrorCode hci_status, hci::Role new_role) override; void OnDisconnection(hci::ErrorCode reason) override; - void OnReadRemoteVersionInformationComplete( - hci::ErrorCode hci_status, uint8_t lmp_version, uint16_t manufacturer_name, uint16_t sub_version); + void OnReadRemoteVersionInformationComplete(hci::ErrorCode hci_status, uint8_t lmp_version, + uint16_t manufacturer_name, uint16_t sub_version); void OnReadRemoteSupportedFeaturesComplete(uint64_t features); - void OnReadRemoteExtendedFeaturesComplete(uint8_t page_number, uint8_t max_page_number, uint64_t features); + void OnReadRemoteExtendedFeaturesComplete(uint8_t page_number, uint8_t max_page_number, + uint64_t features); struct EncryptionChangeListener { Cid cid; @@ -207,23 +211,20 @@ class Link : public l2cap::internal::ILink, }; void AddEncryptionChangeListener(EncryptionChangeListener); - uint16_t GetAclHandle() const { - return acl_handle_; - } + uint16_t GetAclHandle() const { return acl_handle_; } - hci::Role GetRole() const { - return role_; - } + hci::Role GetRole() const { return role_; } void OnPendingPacketChange(Cid local_cid, bool has_packet) override; - private: +private: friend class DumpsysHelper; void connect_to_pending_dynamic_channels(); void send_pending_configuration_requests(); os::Handler* l2cap_handler_; - l2cap::internal::FixedChannelAllocator fixed_channel_allocator_{this, l2cap_handler_}; + l2cap::internal::FixedChannelAllocator fixed_channel_allocator_{ + this, l2cap_handler_}; l2cap::internal::DynamicChannelAllocator dynamic_channel_allocator_{this, l2cap_handler_}; std::unique_ptr acl_connection_; l2cap::internal::DataPipelineManager data_pipeline_manager_; @@ -231,7 +232,8 @@ class Link : public l2cap::internal::ILink, DynamicChannelServiceManagerImpl* dynamic_service_manager_; FixedChannelServiceManagerImpl* fixed_service_manager_; LinkManager* link_manager_; - std::unordered_map local_cid_to_pending_dynamic_channel_connection_map_; + std::unordered_map + local_cid_to_pending_dynamic_channel_connection_map_; os::Alarm link_idle_disconnect_alarm_{l2cap_handler_}; ClassicSignallingManager signalling_manager_; uint16_t acl_handle_; diff --git a/system/gd/l2cap/classic/internal/link_manager.cc b/system/gd/l2cap/classic/internal/link_manager.cc index 6ce3188a71f..967598eed73 100644 --- a/system/gd/l2cap/classic/internal/link_manager.cc +++ b/system/gd/l2cap/classic/internal/link_manager.cc @@ -32,23 +32,25 @@ namespace l2cap { namespace classic { namespace internal { -void LinkManager::ConnectFixedChannelServices(hci::Address device, - PendingFixedChannelConnection pending_fixed_channel_connection) { +void LinkManager::ConnectFixedChannelServices( + hci::Address device, PendingFixedChannelConnection pending_fixed_channel_connection) { // Check if there is any service registered auto fixed_channel_services = fixed_channel_service_manager_->GetRegisteredServices(); if (fixed_channel_services.empty()) { // If so, return error - pending_fixed_channel_connection.handler_->Post(common::BindOnce( - std::move(pending_fixed_channel_connection.on_fail_callback_), - FixedChannelManager::ConnectionResult{ - .connection_result_code = FixedChannelManager::ConnectionResultCode::FAIL_NO_SERVICE_REGISTERED})); + pending_fixed_channel_connection.handler_->Post( + common::BindOnce(std::move(pending_fixed_channel_connection.on_fail_callback_), + FixedChannelManager::ConnectionResult{ + .connection_result_code = FixedChannelManager:: + ConnectionResultCode::FAIL_NO_SERVICE_REGISTERED})); return; } // Otherwise, check if device has an ACL connection auto* link = GetLink(device); if (link != nullptr) { // If device already have an ACL connection - // Check if all registered services have an allocated channel and allocate one if not already allocated + // Check if all registered services have an allocated channel and allocate one if not already + // allocated int num_new_channels = 0; for (auto& fixed_channel_service : fixed_channel_services) { if (link->IsFixedChannelAllocated(fixed_channel_service.first)) { @@ -58,15 +60,16 @@ void LinkManager::ConnectFixedChannelServices(hci::Address device, // Allocate channel for newly registered fixed channels auto fixed_channel_impl = link->AllocateFixedChannel(fixed_channel_service.first); fixed_channel_service.second->NotifyChannelCreation( - std::make_unique(fixed_channel_impl, l2cap_handler_)); + std::make_unique(fixed_channel_impl, l2cap_handler_)); num_new_channels++; } // Declare connection failure if no new channels are created if (num_new_channels == 0) { pending_fixed_channel_connection.handler_->Post(common::BindOnce( - std::move(pending_fixed_channel_connection.on_fail_callback_), - FixedChannelManager::ConnectionResult{ - .connection_result_code = FixedChannelManager::ConnectionResultCode::FAIL_ALL_SERVICES_HAVE_CHANNEL})); + std::move(pending_fixed_channel_connection.on_fail_callback_), + FixedChannelManager::ConnectionResult{ + .connection_result_code = FixedChannelManager::ConnectionResultCode:: + FAIL_ALL_SERVICES_HAVE_CHANNEL})); } // No need to create ACL connection, return without saving any pending connections return; @@ -79,13 +82,15 @@ void LinkManager::ConnectFixedChannelServices(hci::Address device, pending_links_.try_emplace(device); pending_link = pending_links_.find(device); } - pending_link->second.pending_fixed_channel_connections_.push_back(std::move(pending_fixed_channel_connection)); + pending_link->second.pending_fixed_channel_connections_.push_back( + std::move(pending_fixed_channel_connection)); // Then create new ACL connection acl_manager_->CreateConnection(device); } void LinkManager::ConnectDynamicChannelServices( - hci::Address device, Link::PendingDynamicChannelConnection pending_dynamic_channel_connection, Psm psm) { + hci::Address device, + Link::PendingDynamicChannelConnection pending_dynamic_channel_connection, Psm psm) { if (!IsPsmValid(psm)) { return; } @@ -94,14 +99,17 @@ void LinkManager::ConnectDynamicChannelServices( acl_manager_->CreateConnection(device); if (pending_dynamic_channels_.find(device) != pending_dynamic_channels_.end()) { pending_dynamic_channels_[device].push_back(psm); - pending_dynamic_channels_callbacks_[device].push_back(std::move(pending_dynamic_channel_connection)); + pending_dynamic_channels_callbacks_[device].push_back( + std::move(pending_dynamic_channel_connection)); } else { pending_dynamic_channels_[device] = {psm}; - pending_dynamic_channels_callbacks_[device].push_back(std::move(pending_dynamic_channel_connection)); + pending_dynamic_channels_callbacks_[device].push_back( + std::move(pending_dynamic_channel_connection)); } return; } - link->SendConnectionRequest(psm, link->ReserveDynamicChannel(), std::move(pending_dynamic_channel_connection)); + link->SendConnectionRequest(psm, link->ReserveDynamicChannel(), + std::move(pending_dynamic_channel_connection)); } void LinkManager::InitiateConnectionForSecurity(hci::Address remote) { @@ -112,7 +120,8 @@ void LinkManager::InitiateConnectionForSecurity(hci::Address remote) { acl_manager_->CreateConnection(remote); } -void LinkManager::RegisterLinkSecurityInterfaceListener(os::Handler* handler, LinkSecurityInterfaceListener* listener) { +void LinkManager::RegisterLinkSecurityInterfaceListener(os::Handler* handler, + LinkSecurityInterfaceListener* listener) { link_security_interface_listener_handler_ = handler; link_security_interface_listener_ = listener; } @@ -121,7 +130,8 @@ LinkSecurityInterfaceListener* LinkManager::GetLinkSecurityInterfaceListener() { return link_security_interface_listener_; } -void LinkManager::RegisterLinkPropertyListener(os::Handler* handler, LinkPropertyListener* listener) { +void LinkManager::RegisterLinkPropertyListener(os::Handler* handler, + LinkPropertyListener* listener) { link_property_callback_handler_ = handler; link_property_listener_ = listener; } @@ -190,20 +200,19 @@ void LinkManager::handle_link_security_ensure_encrypted(hci::Address remote) { } /** - * The implementation for LinkSecurityInterface, which allows the SecurityModule to access some link functionalities. - * Note: All public methods implementing this interface are invoked from external context. + * The implementation for LinkSecurityInterface, which allows the SecurityModule to access some link + * functionalities. Note: All public methods implementing this interface are invoked from external + * context. */ class LinkSecurityInterfaceImpl : public LinkSecurityInterface { - public: +public: LinkSecurityInterfaceImpl(os::Handler* handler, LinkManager* link_manager, Link* link) : handler_(handler), link_manager_(link_manager), remote_(link->GetDevice().GetAddress()), acl_handle_(link->GetAclHandle()) {} - hci::Address GetRemoteAddress() override { - return remote_; - } + hci::Address GetRemoteAddress() override { return remote_; } void Hold() override { handler_->CallOn(link_manager_, &LinkManager::handle_link_security_hold, remote_); @@ -218,20 +227,17 @@ class LinkSecurityInterfaceImpl : public LinkSecurityInterface { } void EnsureAuthenticated() override { - handler_->CallOn(link_manager_, &LinkManager::handle_link_security_ensure_authenticated, remote_); + handler_->CallOn(link_manager_, &LinkManager::handle_link_security_ensure_authenticated, + remote_); } void EnsureEncrypted() override { handler_->CallOn(link_manager_, &LinkManager::handle_link_security_ensure_encrypted, remote_); } - uint16_t GetAclHandle() override { - return acl_handle_; - } + uint16_t GetAclHandle() override { return acl_handle_; } - hci::Role GetRole() override { - return link_manager_->GetLink(remote_)->GetRole(); - } + hci::Role GetRole() override { return link_manager_->GetLink(remote_)->GetRole(); } os::Handler* handler_; LinkManager* link_manager_; @@ -239,13 +245,12 @@ class LinkSecurityInterfaceImpl : public LinkSecurityInterface { uint16_t acl_handle_; }; -void LinkManager::OnConnectSuccess(std::unique_ptr acl_connection) { +void LinkManager::OnConnectSuccess( + std::unique_ptr acl_connection) { // Same link should not be connected twice hci::Address device = acl_connection->GetAddress(); - log::assert_that( - GetLink(device) == nullptr, - "{} is connected twice without disconnection", - ADDRESS_TO_LOGGABLE_CSTR(acl_connection->GetAddress())); + log::assert_that(GetLink(device) == nullptr, "{} is connected twice without disconnection", + ADDRESS_TO_LOGGABLE_CSTR(acl_connection->GetAddress())); links_.try_emplace(device, l2cap_handler_, std::move(acl_connection), parameter_provider_, dynamic_channel_service_manager_, fixed_channel_service_manager_, this); auto* link = GetLink(device); @@ -261,7 +266,7 @@ void LinkManager::OnConnectSuccess(std::unique_ptrAllocateFixedChannel(fixed_channel_service.first); fixed_channel_service.second->NotifyChannelCreation( - std::make_unique(fixed_channel_impl, l2cap_handler_)); + std::make_unique(fixed_channel_impl, l2cap_handler_)); } if (pending_dynamic_channels_.find(device) != pending_dynamic_channels_.end()) { auto psm_list = pending_dynamic_channels_[device]; @@ -272,16 +277,16 @@ void LinkManager::OnConnectSuccess(std::unique_ptrCallOn( - link_property_listener_, &LinkPropertyListener::OnLinkConnected, device, link->GetAclHandle()); + link_property_callback_handler_->CallOn(link_property_listener_, + &LinkPropertyListener::OnLinkConnected, device, + link->GetAclHandle()); } // Notify security manager if (link_security_interface_listener_handler_ != nullptr) { link_security_interface_listener_handler_->CallOn( - link_security_interface_listener_, - &LinkSecurityInterfaceListener::OnLinkConnected, - std::make_unique(l2cap_handler_, this, link)); + link_security_interface_listener_, &LinkSecurityInterfaceListener::OnLinkConnected, + std::make_unique(l2cap_handler_, this, link)); } // Remove device from pending links list, if any @@ -297,14 +302,14 @@ void LinkManager::OnConnectFail(hci::Address device, hci::ErrorCode reason, bool auto pending_link = pending_links_.find(device); if (pending_link == pending_links_.end()) { // There is no pending link, exit - log::info( - "Connection to {} failed without a pending link; reason: {}", - device, - hci::ErrorCodeText(reason)); - if (pending_dynamic_channels_callbacks_.find(device) != pending_dynamic_channels_callbacks_.end()) { - for (Link::PendingDynamicChannelConnection& callbacks : pending_dynamic_channels_callbacks_[device]) { + log::info("Connection to {} failed without a pending link; reason: {}", device, + hci::ErrorCodeText(reason)); + if (pending_dynamic_channels_callbacks_.find(device) != + pending_dynamic_channels_callbacks_.end()) { + for (Link::PendingDynamicChannelConnection& callbacks : + pending_dynamic_channels_callbacks_[device]) { callbacks.on_fail_callback_(DynamicChannelManager::ConnectionResult{ - .hci_error = hci::ErrorCode::CONNECTION_TIMEOUT, + .hci_error = hci::ErrorCode::CONNECTION_TIMEOUT, }); } pending_dynamic_channels_.erase(device); @@ -312,11 +317,14 @@ void LinkManager::OnConnectFail(hci::Address device, hci::ErrorCode reason, bool } return; } - for (auto& pending_fixed_channel_connection : pending_link->second.pending_fixed_channel_connections_) { + for (auto& pending_fixed_channel_connection : + pending_link->second.pending_fixed_channel_connections_) { pending_fixed_channel_connection.handler_->Post(common::BindOnce( - std::move(pending_fixed_channel_connection.on_fail_callback_), - FixedChannelManager::ConnectionResult{ - .connection_result_code = FixedChannelManager::ConnectionResultCode::FAIL_HCI_ERROR, .hci_error = reason})); + std::move(pending_fixed_channel_connection.on_fail_callback_), + FixedChannelManager::ConnectionResult{ + .connection_result_code = + FixedChannelManager::ConnectionResultCode::FAIL_HCI_ERROR, + .hci_error = reason})); } // Remove entry in pending link list pending_links_.erase(pending_link); @@ -324,17 +332,17 @@ void LinkManager::OnConnectFail(hci::Address device, hci::ErrorCode reason, bool void LinkManager::OnDisconnect(hci::Address device, hci::ErrorCode status) { auto* link = GetLink(device); - log::assert_that( - link != nullptr, - "Device {} is disconnected with reason 0x{:x}, but not in local database", - ADDRESS_TO_LOGGABLE_CSTR(device), - static_cast(status)); + log::assert_that(link != nullptr, + "Device {} is disconnected with reason 0x{:x}, but not in local database", + ADDRESS_TO_LOGGABLE_CSTR(device), static_cast(status)); if (link_security_interface_listener_handler_ != nullptr) { link_security_interface_listener_handler_->CallOn( - link_security_interface_listener_, &LinkSecurityInterfaceListener::OnLinkDisconnected, device); + link_security_interface_listener_, &LinkSecurityInterfaceListener::OnLinkDisconnected, + device); } if (link_property_callback_handler_ != nullptr) { - link_property_callback_handler_->CallOn(link_property_listener_, &LinkPropertyListener::OnLinkDisconnected, device); + link_property_callback_handler_->CallOn(link_property_listener_, + &LinkPropertyListener::OnLinkDisconnected, device); } if (links_with_pending_packets_.count(device) != 0) { @@ -347,99 +355,79 @@ void LinkManager::OnDisconnect(hci::Address device, hci::ErrorCode status) { void LinkManager::OnAuthenticationComplete(hci::ErrorCode hci_status, hci::Address device) { if (link_security_interface_listener_handler_ != nullptr) { link_security_interface_listener_handler_->CallOn( - link_security_interface_listener_, - &LinkSecurityInterfaceListener::OnAuthenticationComplete, - hci_status, - device); + link_security_interface_listener_, + &LinkSecurityInterfaceListener::OnAuthenticationComplete, hci_status, device); } } void LinkManager::OnEncryptionChange(hci::Address device, hci::EncryptionEnabled enabled) { if (link_security_interface_listener_handler_ != nullptr) { link_security_interface_listener_handler_->CallOn( - link_security_interface_listener_, - &LinkSecurityInterfaceListener::OnEncryptionChange, - device, - enabled == hci::EncryptionEnabled::ON || enabled == hci::EncryptionEnabled::BR_EDR_AES_CCM); + link_security_interface_listener_, &LinkSecurityInterfaceListener::OnEncryptionChange, + device, + enabled == hci::EncryptionEnabled::ON || + enabled == hci::EncryptionEnabled::BR_EDR_AES_CCM); } } -void LinkManager::OnReadRemoteVersionInformation( - hci::ErrorCode hci_status, - hci::Address device, - uint8_t lmp_version, - uint16_t manufacturer_name, - uint16_t sub_version) { +void LinkManager::OnReadRemoteVersionInformation(hci::ErrorCode hci_status, hci::Address device, + uint8_t lmp_version, uint16_t manufacturer_name, + uint16_t sub_version) { if (link_property_callback_handler_ != nullptr) { link_property_callback_handler_->CallOn( - link_property_listener_, - &LinkPropertyListener::OnReadRemoteVersionInformation, - hci_status, - device, - lmp_version, - manufacturer_name, - sub_version); + link_property_listener_, &LinkPropertyListener::OnReadRemoteVersionInformation, + hci_status, device, lmp_version, manufacturer_name, sub_version); } } void LinkManager::OnReadRemoteSupportedFeatures(hci::Address device, uint64_t features) { if (link_property_callback_handler_ != nullptr) { - link_property_callback_handler_->CallOn( - link_property_listener_, &LinkPropertyListener::OnReadRemoteSupportedFeatures, device, features); + link_property_callback_handler_->CallOn(link_property_listener_, + &LinkPropertyListener::OnReadRemoteSupportedFeatures, + device, features); } } -void LinkManager::OnReadRemoteExtendedFeatures( - hci::Address device, uint8_t page_number, uint8_t max_page_number, uint64_t features) { +void LinkManager::OnReadRemoteExtendedFeatures(hci::Address device, uint8_t page_number, + uint8_t max_page_number, uint64_t features) { if (link_property_callback_handler_ != nullptr) { - link_property_callback_handler_->CallOn( - link_property_listener_, - &LinkPropertyListener::OnReadRemoteExtendedFeatures, - device, - page_number, - max_page_number, - features); + link_property_callback_handler_->CallOn(link_property_listener_, + &LinkPropertyListener::OnReadRemoteExtendedFeatures, + device, page_number, max_page_number, features); } } void LinkManager::OnRoleChange(hci::ErrorCode hci_status, hci::Address remote, hci::Role role) { if (link_property_callback_handler_ != nullptr) { link_property_callback_handler_->CallOn( - link_property_listener_, &LinkPropertyListener::OnRoleChange, hci_status, remote, role); + link_property_listener_, &LinkPropertyListener::OnRoleChange, hci_status, remote, role); } } void LinkManager::OnReadClockOffset(hci::Address remote, uint16_t clock_offset) { if (link_property_callback_handler_ != nullptr) { - link_property_callback_handler_->CallOn( - link_property_listener_, &LinkPropertyListener::OnReadClockOffset, remote, clock_offset); + link_property_callback_handler_->CallOn(link_property_listener_, + &LinkPropertyListener::OnReadClockOffset, remote, + clock_offset); } } -void LinkManager::OnModeChange(hci::ErrorCode hci_status, hci::Address remote, hci::Mode mode, uint16_t interval) { +void LinkManager::OnModeChange(hci::ErrorCode hci_status, hci::Address remote, hci::Mode mode, + uint16_t interval) { if (link_property_callback_handler_ != nullptr) { - link_property_callback_handler_->CallOn( - link_property_listener_, &LinkPropertyListener::OnModeChange, hci_status, remote, mode, interval); + link_property_callback_handler_->CallOn(link_property_listener_, + &LinkPropertyListener::OnModeChange, hci_status, remote, + mode, interval); } } -void LinkManager::OnSniffSubrating( - hci::ErrorCode hci_status, - hci::Address remote, - uint16_t max_tx_lat, - uint16_t max_rx_lat, - uint16_t min_remote_timeout, - uint16_t min_local_timeout) { +void LinkManager::OnSniffSubrating(hci::ErrorCode hci_status, hci::Address remote, + uint16_t max_tx_lat, uint16_t max_rx_lat, + uint16_t min_remote_timeout, uint16_t min_local_timeout) { if (link_property_callback_handler_ != nullptr) { link_property_callback_handler_->CallOn( - link_property_listener_, - &LinkPropertyListener::OnSniffSubrating, - hci_status, - remote, - max_tx_lat, - max_rx_lat, - min_remote_timeout, - min_local_timeout); + link_property_listener_, &LinkPropertyListener::OnSniffSubrating, hci_status, remote, + max_tx_lat, max_rx_lat, min_remote_timeout, min_local_timeout); } } diff --git a/system/gd/l2cap/classic/internal/link_manager.h b/system/gd/l2cap/classic/internal/link_manager.h index 482c07c6f0e..1f719fa57b6 100644 --- a/system/gd/l2cap/classic/internal/link_manager.h +++ b/system/gd/l2cap/classic/internal/link_manager.h @@ -42,14 +42,16 @@ namespace internal { class DumpsysHelper; class LinkManager : public hci::acl_manager::ConnectionCallbacks { - public: +public: LinkManager(os::Handler* l2cap_handler, hci::AclManager* acl_manager, FixedChannelServiceManagerImpl* fixed_channel_service_manager, DynamicChannelServiceManagerImpl* dynamic_channel_service_manager, l2cap::internal::ParameterProvider* parameter_provider) - : l2cap_handler_(l2cap_handler), acl_manager_(acl_manager), + : l2cap_handler_(l2cap_handler), + acl_manager_(acl_manager), fixed_channel_service_manager_(fixed_channel_service_manager), - dynamic_channel_service_manager_(dynamic_channel_service_manager), parameter_provider_(parameter_provider) { + dynamic_channel_service_manager_(dynamic_channel_service_manager), + parameter_provider_(parameter_provider) { acl_manager_->RegisterCallbacks(this, l2cap_handler_); } @@ -68,47 +70,46 @@ class LinkManager : public hci::acl_manager::ConnectionCallbacks { // ACL methods Link* GetLink(hci::Address device); - void OnConnectSuccess(std::unique_ptr acl_connection) override; + void OnConnectSuccess( + std::unique_ptr acl_connection) override; void OnConnectRequest(hci::Address, hci::ClassOfDevice) override; void OnConnectFail(hci::Address device, hci::ErrorCode reason, bool locally_initiated) override; virtual void OnDisconnect(hci::Address device, hci::ErrorCode status); void OnAuthenticationComplete(hci::ErrorCode hci_status, hci::Address device); void OnEncryptionChange(hci::Address device, hci::EncryptionEnabled enabled); - void OnReadRemoteVersionInformation( - hci::ErrorCode hci_status, - hci::Address device, - uint8_t lmp_version, - uint16_t manufacturer_name, - uint16_t sub_version); + void OnReadRemoteVersionInformation(hci::ErrorCode hci_status, hci::Address device, + uint8_t lmp_version, uint16_t manufacturer_name, + uint16_t sub_version); void OnReadRemoteSupportedFeatures(hci::Address device, uint64_t features); - void OnReadRemoteExtendedFeatures( - hci::Address device, uint8_t page_number, uint8_t max_page_number, uint64_t features); + void OnReadRemoteExtendedFeatures(hci::Address device, uint8_t page_number, + uint8_t max_page_number, uint64_t features); void OnRoleChange(hci::ErrorCode hci_status, hci::Address remote, hci::Role role); void OnReadClockOffset(hci::Address remote, uint16_t clock_offset); - void OnModeChange(hci::ErrorCode hci_status, hci::Address remote, hci::Mode mode, uint16_t interval); - void OnSniffSubrating( - hci::ErrorCode hci_status, - hci::Address remote, - uint16_t max_tx_lat, - uint16_t max_rx_lat, - uint16_t min_remote_timeout, - uint16_t min_local_timeout); + void OnModeChange(hci::ErrorCode hci_status, hci::Address remote, hci::Mode mode, + uint16_t interval); + void OnSniffSubrating(hci::ErrorCode hci_status, hci::Address remote, uint16_t max_tx_lat, + uint16_t max_rx_lat, uint16_t min_remote_timeout, + uint16_t min_local_timeout); // FixedChannelManager methods - void ConnectFixedChannelServices(hci::Address device, PendingFixedChannelConnection pending_fixed_channel_connection); + void ConnectFixedChannelServices(hci::Address device, + PendingFixedChannelConnection pending_fixed_channel_connection); // DynamicChannelManager methods - void ConnectDynamicChannelServices( - hci::Address device, Link::PendingDynamicChannelConnection pending_connection, Psm psm); + void ConnectDynamicChannelServices(hci::Address device, + Link::PendingDynamicChannelConnection pending_connection, + Psm psm); // For SecurityModule to initiate an ACL link void InitiateConnectionForSecurity(hci::Address remote); - // LinkManager will handle sending OnLinkConnected() callback and construct a LinkSecurityInterface proxy. - void RegisterLinkSecurityInterfaceListener(os::Handler* handler, LinkSecurityInterfaceListener* listener); + // LinkManager will handle sending OnLinkConnected() callback and construct a + // LinkSecurityInterface proxy. + void RegisterLinkSecurityInterfaceListener(os::Handler* handler, + LinkSecurityInterfaceListener* listener); // For the link to get LinkSecurityInterfaceListener LinkSecurityInterfaceListener* GetLinkSecurityInterfaceListener(); @@ -120,7 +121,7 @@ class LinkManager : public hci::acl_manager::ConnectionCallbacks { // If there is anything outstanding, don't delete link void OnPendingPacketChange(hci::Address remote, int num_packets); - private: +private: // Handles requests from LinkSecurityInterface friend class LinkSecurityInterfaceImpl; friend class DumpsysHelper; @@ -142,7 +143,7 @@ class LinkManager : public hci::acl_manager::ConnectionCallbacks { std::unordered_map links_; std::unordered_map> pending_dynamic_channels_; std::unordered_map> - pending_dynamic_channels_callbacks_; + pending_dynamic_channels_callbacks_; os::Handler* link_security_interface_listener_handler_ = nullptr; LinkSecurityInterfaceListener* link_security_interface_listener_ = nullptr; LinkPropertyListener* link_property_listener_ = nullptr; diff --git a/system/gd/l2cap/classic/internal/link_manager_test.cc b/system/gd/l2cap/classic/internal/link_manager_test.cc index b48cd8a894b..ad2928ff06d 100644 --- a/system/gd/l2cap/classic/internal/link_manager_test.cc +++ b/system/gd/l2cap/classic/internal/link_manager_test.cc @@ -16,6 +16,9 @@ #include "l2cap/classic/internal/link_manager.h" +#include +#include + #include #include @@ -33,9 +36,6 @@ #include "os/handler.h" #include "os/thread.h" -#include -#include - namespace bluetooth { namespace l2cap { namespace classic { @@ -59,7 +59,7 @@ constexpr static auto kTestIdleDisconnectTimeoutLong = std::chrono::milliseconds constexpr static auto kTestIdleDisconnectTimeoutShort = std::chrono::milliseconds(1000); class L2capClassicLinkManagerTest : public ::testing::Test { - public: +public: static void SyncHandler(os::Handler* handler) { std::promise promise; auto future = promise.get_future(); @@ -67,13 +67,13 @@ class L2capClassicLinkManagerTest : public ::testing::Test { future.wait_for(std::chrono::milliseconds(3)); } - protected: +protected: void SetUp() override { thread_ = new os::Thread("test_thread", os::Thread::Priority::NORMAL); l2cap_handler_ = new os::Handler(thread_); mock_parameter_provider_ = new MockParameterProvider; EXPECT_CALL(*mock_parameter_provider_, GetClassicLinkIdleDisconnectTimeout) - .WillRepeatedly(Return(kTestIdleDisconnectTimeoutLong)); + .WillRepeatedly(Return(kTestIdleDisconnectTimeoutLong)); } void TearDown() override { @@ -94,10 +94,11 @@ TEST_F(L2capClassicLinkManagerTest, connect_fixed_channel_service_without_acl) { SecurityEnforcementRejectAllImpl security_module_impl; MockDynamicChannelServiceImpl service; ON_CALL(service, GetSecurityPolicy()) - .WillByDefault(Return(SecurityPolicy::_SDP_ONLY_NO_SECURITY_WHATSOEVER_PLAINTEXT_TRANSPORT_OK)); + .WillByDefault( + Return(SecurityPolicy::_SDP_ONLY_NO_SECURITY_WHATSOEVER_PLAINTEXT_TRANSPORT_OK)); ON_CALL(mock_classic_dynamic_channel_service_manager, GetSecurityEnforcementInterface()) - .WillByDefault(Return(&security_module_impl)); + .WillByDefault(Return(&security_module_impl)); MockAclManager mock_acl_manager; hci::Address device{{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}; auto user_handler = std::make_unique(thread_); @@ -106,10 +107,13 @@ TEST_F(L2capClassicLinkManagerTest, connect_fixed_channel_service_without_acl) { hci::acl_manager::ConnectionCallbacks* hci_connection_callbacks = nullptr; os::Handler* hci_callback_handler = nullptr; EXPECT_CALL(mock_acl_manager, RegisterCallbacks(_, _)) - .WillOnce(DoAll(SaveArg<0>(&hci_connection_callbacks), SaveArg<1>(&hci_callback_handler))); - ON_CALL(mock_classic_dynamic_channel_service_manager, GetService(_)).WillByDefault(Return(&service)); - LinkManager classic_link_manager(l2cap_handler_, &mock_acl_manager, &mock_classic_fixed_channel_service_manager, - &mock_classic_dynamic_channel_service_manager, mock_parameter_provider_); + .WillOnce( + DoAll(SaveArg<0>(&hci_connection_callbacks), SaveArg<1>(&hci_callback_handler))); + ON_CALL(mock_classic_dynamic_channel_service_manager, GetService(_)) + .WillByDefault(Return(&service)); + LinkManager classic_link_manager( + l2cap_handler_, &mock_acl_manager, &mock_classic_fixed_channel_service_manager, + &mock_classic_dynamic_channel_service_manager, mock_parameter_provider_); EXPECT_EQ(hci_connection_callbacks, &classic_link_manager); EXPECT_EQ(hci_callback_handler, l2cap_handler_); @@ -118,18 +122,23 @@ TEST_F(L2capClassicLinkManagerTest, connect_fixed_channel_service_without_acl) { std::vector> results; results.emplace_back(kSmpBrCid, &mock_service_1); results.emplace_back(kConnectionlessCid, &mock_service_2); - EXPECT_CALL(mock_classic_fixed_channel_service_manager, GetRegisteredServices()).WillRepeatedly(Return(results)); + EXPECT_CALL(mock_classic_fixed_channel_service_manager, GetRegisteredServices()) + .WillRepeatedly(Return(results)); // Step 2: Connect to fixed channel without ACL connection should trigger ACL connection process EXPECT_CALL(mock_acl_manager, CreateConnection(device)).Times(1); LinkManager::PendingFixedChannelConnection pending_fixed_channel_connection{ - .handler_ = user_handler.get(), - .on_fail_callback_ = common::BindOnce([](FixedChannelManager::ConnectionResult result) { FAIL(); })}; - classic_link_manager.ConnectFixedChannelServices(device, std::move(pending_fixed_channel_connection)); + .handler_ = user_handler.get(), + .on_fail_callback_ = + common::BindOnce([](FixedChannelManager::ConnectionResult result) { FAIL(); })}; + classic_link_manager.ConnectFixedChannelServices(device, + std::move(pending_fixed_channel_connection)); - // Step 3: ACL connection success event should trigger channel creation for all registered services + // Step 3: ACL connection success event should trigger channel creation for all registered + // services - std::unique_ptr acl_connection = std::make_unique(); + std::unique_ptr acl_connection = + std::make_unique(); EXPECT_CALL(*acl_connection, GetAddress()).WillRepeatedly(Return(device)); EXPECT_CALL(*acl_connection, RegisterCallbacks(_, l2cap_handler_)).Times(1); std::unique_ptr channel_1, channel_2; @@ -137,17 +146,18 @@ TEST_F(L2capClassicLinkManagerTest, connect_fixed_channel_service_without_acl) { auto future_1 = promise_1.get_future(); auto future_2 = promise_2.get_future(); EXPECT_CALL(mock_service_1, NotifyChannelCreation(_)) - .WillOnce([&channel_1, &promise_1](std::unique_ptr channel) { - channel_1 = std::move(channel); - promise_1.set_value(); - }); + .WillOnce([&channel_1, &promise_1](std::unique_ptr channel) { + channel_1 = std::move(channel); + promise_1.set_value(); + }); EXPECT_CALL(mock_service_2, NotifyChannelCreation(_)) - .WillOnce([&channel_2, &promise_2](std::unique_ptr channel) { - channel_2 = std::move(channel); - promise_2.set_value(); - }); - hci_callback_handler->Post(common::BindOnce(&hci::acl_manager::ConnectionCallbacks::OnConnectSuccess, - common::Unretained(hci_connection_callbacks), std::move(acl_connection))); + .WillOnce([&channel_2, &promise_2](std::unique_ptr channel) { + channel_2 = std::move(channel); + promise_2.set_value(); + }); + hci_callback_handler->Post(common::BindOnce( + &hci::acl_manager::ConnectionCallbacks::OnConnectSuccess, + common::Unretained(hci_connection_callbacks), std::move(acl_connection))); SyncHandler(hci_callback_handler); auto future_1_status = future_1.wait_for(kTestIdleDisconnectTimeoutShort); EXPECT_EQ(future_1_status, std::future_status::ready); @@ -159,10 +169,13 @@ TEST_F(L2capClassicLinkManagerTest, connect_fixed_channel_service_without_acl) { // Step 4: Calling ConnectServices() to the same device will no trigger another connection attempt FixedChannelManager::ConnectionResult my_result; LinkManager::PendingFixedChannelConnection pending_fixed_channel_connection_2{ - .handler_ = user_handler.get(), - .on_fail_callback_ = common::testing::BindLambdaForTesting( - [&my_result](FixedChannelManager::ConnectionResult result) { my_result = result; })}; - classic_link_manager.ConnectFixedChannelServices(device, std::move(pending_fixed_channel_connection_2)); + .handler_ = user_handler.get(), + .on_fail_callback_ = common::testing::BindLambdaForTesting( + [&my_result](FixedChannelManager::ConnectionResult result) { + my_result = result; + })}; + classic_link_manager.ConnectFixedChannelServices(device, + std::move(pending_fixed_channel_connection_2)); SyncHandler(user_handler.get()); EXPECT_EQ(my_result.connection_result_code, FixedChannelManager::ConnectionResultCode::FAIL_ALL_SERVICES_HAVE_CHANNEL); @@ -170,15 +183,19 @@ TEST_F(L2capClassicLinkManagerTest, connect_fixed_channel_service_without_acl) { // Step 5: Register new service will cause new channels to be created during ConnectServices() MockFixedChannelServiceImpl mock_service_3; results.emplace_back(kSmpBrCid + 1, &mock_service_3); - EXPECT_CALL(mock_classic_fixed_channel_service_manager, GetRegisteredServices()).WillRepeatedly(Return(results)); + EXPECT_CALL(mock_classic_fixed_channel_service_manager, GetRegisteredServices()) + .WillRepeatedly(Return(results)); LinkManager::PendingFixedChannelConnection pending_fixed_channel_connection_3{ - .handler_ = user_handler.get(), - .on_fail_callback_ = common::BindOnce([](FixedChannelManager::ConnectionResult result) { FAIL(); })}; + .handler_ = user_handler.get(), + .on_fail_callback_ = + common::BindOnce([](FixedChannelManager::ConnectionResult result) { FAIL(); })}; std::unique_ptr channel_3; - EXPECT_CALL(mock_service_3, NotifyChannelCreation(_)).WillOnce([&channel_3](std::unique_ptr channel) { - channel_3 = std::move(channel); - }); - classic_link_manager.ConnectFixedChannelServices(device, std::move(pending_fixed_channel_connection_3)); + EXPECT_CALL(mock_service_3, NotifyChannelCreation(_)) + .WillOnce([&channel_3](std::unique_ptr channel) { + channel_3 = std::move(channel); + }); + classic_link_manager.ConnectFixedChannelServices(device, + std::move(pending_fixed_channel_connection_3)); EXPECT_NE(channel_3, nullptr); user_handler->Clear(); @@ -196,26 +213,33 @@ TEST_F(L2capClassicLinkManagerTest, connect_fixed_channel_service_without_acl_wi hci::acl_manager::ConnectionCallbacks* hci_connection_callbacks = nullptr; os::Handler* hci_callback_handler = nullptr; EXPECT_CALL(mock_acl_manager, RegisterCallbacks(_, _)) - .WillOnce(DoAll(SaveArg<0>(&hci_connection_callbacks), SaveArg<1>(&hci_callback_handler))); - LinkManager classic_link_manager(l2cap_handler_, &mock_acl_manager, &mock_classic_fixed_channel_service_manager, - nullptr, mock_parameter_provider_); + .WillOnce( + DoAll(SaveArg<0>(&hci_connection_callbacks), SaveArg<1>(&hci_callback_handler))); + LinkManager classic_link_manager(l2cap_handler_, &mock_acl_manager, + &mock_classic_fixed_channel_service_manager, nullptr, + mock_parameter_provider_); EXPECT_EQ(hci_connection_callbacks, &classic_link_manager); EXPECT_EQ(hci_callback_handler, l2cap_handler_); // Make sure no service is registered std::vector> results; - EXPECT_CALL(mock_classic_fixed_channel_service_manager, GetRegisteredServices()).WillRepeatedly(Return(results)); + EXPECT_CALL(mock_classic_fixed_channel_service_manager, GetRegisteredServices()) + .WillRepeatedly(Return(results)); // Step 2: Connect to fixed channel without any service registered will result in failure EXPECT_CALL(mock_acl_manager, CreateConnection(device)).Times(0); FixedChannelManager::ConnectionResult my_result; LinkManager::PendingFixedChannelConnection pending_fixed_channel_connection{ - .handler_ = user_handler.get(), - .on_fail_callback_ = common::testing::BindLambdaForTesting( - [&my_result](FixedChannelManager::ConnectionResult result) { my_result = result; })}; - classic_link_manager.ConnectFixedChannelServices(device, std::move(pending_fixed_channel_connection)); + .handler_ = user_handler.get(), + .on_fail_callback_ = common::testing::BindLambdaForTesting( + [&my_result](FixedChannelManager::ConnectionResult result) { + my_result = result; + })}; + classic_link_manager.ConnectFixedChannelServices(device, + std::move(pending_fixed_channel_connection)); SyncHandler(user_handler.get()); - EXPECT_EQ(my_result.connection_result_code, FixedChannelManager::ConnectionResultCode::FAIL_NO_SERVICE_REGISTERED); + EXPECT_EQ(my_result.connection_result_code, + FixedChannelManager::ConnectionResultCode::FAIL_NO_SERVICE_REGISTERED); user_handler->Clear(); } @@ -230,9 +254,11 @@ TEST_F(L2capClassicLinkManagerTest, connect_fixed_channel_service_without_acl_wi hci::acl_manager::ConnectionCallbacks* hci_connection_callbacks = nullptr; os::Handler* hci_callback_handler = nullptr; EXPECT_CALL(mock_acl_manager, RegisterCallbacks(_, _)) - .WillOnce(DoAll(SaveArg<0>(&hci_connection_callbacks), SaveArg<1>(&hci_callback_handler))); - LinkManager classic_link_manager(l2cap_handler_, &mock_acl_manager, &mock_classic_fixed_channel_service_manager, - nullptr, mock_parameter_provider_); + .WillOnce( + DoAll(SaveArg<0>(&hci_connection_callbacks), SaveArg<1>(&hci_callback_handler))); + LinkManager classic_link_manager(l2cap_handler_, &mock_acl_manager, + &mock_classic_fixed_channel_service_manager, nullptr, + mock_parameter_provider_); EXPECT_EQ(hci_connection_callbacks, &classic_link_manager); EXPECT_EQ(hci_callback_handler, l2cap_handler_); @@ -240,28 +266,31 @@ TEST_F(L2capClassicLinkManagerTest, connect_fixed_channel_service_without_acl_wi MockFixedChannelServiceImpl mock_service_1; std::vector> results; results.emplace_back(kSmpBrCid, &mock_service_1); - EXPECT_CALL(mock_classic_fixed_channel_service_manager, GetRegisteredServices()).WillRepeatedly(Return(results)); + EXPECT_CALL(mock_classic_fixed_channel_service_manager, GetRegisteredServices()) + .WillRepeatedly(Return(results)); // Step 2: Connect to fixed channel without ACL connection should trigger ACL connection process EXPECT_CALL(mock_acl_manager, CreateConnection(device)).Times(1); FixedChannelManager::ConnectionResult my_result; LinkManager::PendingFixedChannelConnection pending_fixed_channel_connection{ - .handler_ = user_handler.get(), - .on_fail_callback_ = common::testing::BindLambdaForTesting( - [&my_result](FixedChannelManager::ConnectionResult result) { my_result = result; })}; - classic_link_manager.ConnectFixedChannelServices(device, std::move(pending_fixed_channel_connection)); + .handler_ = user_handler.get(), + .on_fail_callback_ = common::testing::BindLambdaForTesting( + [&my_result](FixedChannelManager::ConnectionResult result) { + my_result = result; + })}; + classic_link_manager.ConnectFixedChannelServices(device, + std::move(pending_fixed_channel_connection)); // Step 3: ACL connection failure event should trigger connection failure callback EXPECT_CALL(mock_service_1, NotifyChannelCreation(_)).Times(0); - hci_callback_handler->Post(common::BindOnce( - &hci::acl_manager::ConnectionCallbacks::OnConnectFail, - common::Unretained(hci_connection_callbacks), - device, - hci::ErrorCode::PAGE_TIMEOUT, - true /* locally_initiated */)); + hci_callback_handler->Post(common::BindOnce(&hci::acl_manager::ConnectionCallbacks::OnConnectFail, + common::Unretained(hci_connection_callbacks), device, + hci::ErrorCode::PAGE_TIMEOUT, + true /* locally_initiated */)); SyncHandler(hci_callback_handler); SyncHandler(user_handler.get()); - EXPECT_EQ(my_result.connection_result_code, FixedChannelManager::ConnectionResultCode::FAIL_HCI_ERROR); + EXPECT_EQ(my_result.connection_result_code, + FixedChannelManager::ConnectionResultCode::FAIL_HCI_ERROR); EXPECT_EQ(my_result.hci_error, hci::ErrorCode::PAGE_TIMEOUT); user_handler->Clear(); @@ -269,7 +298,7 @@ TEST_F(L2capClassicLinkManagerTest, connect_fixed_channel_service_without_acl_wi TEST_F(L2capClassicLinkManagerTest, not_acquiring_channels_should_disconnect_acl_after_timeout) { EXPECT_CALL(*mock_parameter_provider_, GetClassicLinkIdleDisconnectTimeout) - .WillRepeatedly(Return(kTestIdleDisconnectTimeoutShort)); + .WillRepeatedly(Return(kTestIdleDisconnectTimeoutShort)); MockFixedChannelServiceManagerImpl mock_classic_fixed_channel_service_manager; MockAclManager mock_acl_manager; hci::Address device{{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}; @@ -279,9 +308,11 @@ TEST_F(L2capClassicLinkManagerTest, not_acquiring_channels_should_disconnect_acl hci::acl_manager::ConnectionCallbacks* hci_connection_callbacks = nullptr; os::Handler* hci_callback_handler = nullptr; EXPECT_CALL(mock_acl_manager, RegisterCallbacks(_, _)) - .WillOnce(DoAll(SaveArg<0>(&hci_connection_callbacks), SaveArg<1>(&hci_callback_handler))); - LinkManager classic_link_manager(l2cap_handler_, &mock_acl_manager, &mock_classic_fixed_channel_service_manager, - nullptr, mock_parameter_provider_); + .WillOnce( + DoAll(SaveArg<0>(&hci_connection_callbacks), SaveArg<1>(&hci_callback_handler))); + LinkManager classic_link_manager(l2cap_handler_, &mock_acl_manager, + &mock_classic_fixed_channel_service_manager, nullptr, + mock_parameter_provider_); EXPECT_EQ(hci_connection_callbacks, &classic_link_manager); EXPECT_EQ(hci_callback_handler, l2cap_handler_); @@ -290,16 +321,20 @@ TEST_F(L2capClassicLinkManagerTest, not_acquiring_channels_should_disconnect_acl std::vector> results; results.emplace_back(kSmpBrCid, &mock_service_1); results.emplace_back(kConnectionlessCid, &mock_service_2); - EXPECT_CALL(mock_classic_fixed_channel_service_manager, GetRegisteredServices()).WillRepeatedly(Return(results)); + EXPECT_CALL(mock_classic_fixed_channel_service_manager, GetRegisteredServices()) + .WillRepeatedly(Return(results)); // Step 2: Connect to fixed channel without ACL connection should trigger ACL connection process EXPECT_CALL(mock_acl_manager, CreateConnection(device)).Times(1); LinkManager::PendingFixedChannelConnection pending_fixed_channel_connection{ - .handler_ = user_handler.get(), - .on_fail_callback_ = common::BindOnce([](FixedChannelManager::ConnectionResult result) { FAIL(); })}; - classic_link_manager.ConnectFixedChannelServices(device, std::move(pending_fixed_channel_connection)); - - // Step 3: ACL connection success event should trigger channel creation for all registered services + .handler_ = user_handler.get(), + .on_fail_callback_ = + common::BindOnce([](FixedChannelManager::ConnectionResult result) { FAIL(); })}; + classic_link_manager.ConnectFixedChannelServices(device, + std::move(pending_fixed_channel_connection)); + + // Step 3: ACL connection success event should trigger channel creation for all registered + // services auto* raw_acl_connection = new MockClassicAclConnection(); std::unique_ptr acl_connection(raw_acl_connection); EXPECT_CALL(*acl_connection, GetAddress()).WillRepeatedly(Return(device)); @@ -309,17 +344,18 @@ TEST_F(L2capClassicLinkManagerTest, not_acquiring_channels_should_disconnect_acl auto future_1 = promise_1.get_future(); auto future_2 = promise_2.get_future(); EXPECT_CALL(mock_service_1, NotifyChannelCreation(_)) - .WillOnce([&channel_1, &promise_1](std::unique_ptr channel) { - channel_1 = std::move(channel); - promise_1.set_value(); - }); + .WillOnce([&channel_1, &promise_1](std::unique_ptr channel) { + channel_1 = std::move(channel); + promise_1.set_value(); + }); EXPECT_CALL(mock_service_2, NotifyChannelCreation(_)) - .WillOnce([&channel_2, &promise_2](std::unique_ptr channel) { - channel_2 = std::move(channel); - promise_2.set_value(); - }); - hci_callback_handler->Post(common::BindOnce(&hci::acl_manager::ConnectionCallbacks::OnConnectSuccess, - common::Unretained(hci_connection_callbacks), std::move(acl_connection))); + .WillOnce([&channel_2, &promise_2](std::unique_ptr channel) { + channel_2 = std::move(channel); + promise_2.set_value(); + }); + hci_callback_handler->Post(common::BindOnce( + &hci::acl_manager::ConnectionCallbacks::OnConnectSuccess, + common::Unretained(hci_connection_callbacks), std::move(acl_connection))); SyncHandler(hci_callback_handler); auto future_1_status = future_1.wait_for(kTestIdleDisconnectTimeoutShort); EXPECT_EQ(future_1_status, std::future_status::ready); @@ -329,13 +365,17 @@ TEST_F(L2capClassicLinkManagerTest, not_acquiring_channels_should_disconnect_acl EXPECT_NE(channel_2, nullptr); hci::ErrorCode status_1 = hci::ErrorCode::SUCCESS; channel_1->RegisterOnCloseCallback( - user_handler.get(), common::testing::BindLambdaForTesting([&](hci::ErrorCode status) { status_1 = status; })); + user_handler.get(), + common::testing::BindLambdaForTesting([&](hci::ErrorCode status) { status_1 = status; })); hci::ErrorCode status_2 = hci::ErrorCode::SUCCESS; channel_2->RegisterOnCloseCallback( - user_handler.get(), common::testing::BindLambdaForTesting([&](hci::ErrorCode status) { status_2 = status; })); + user_handler.get(), + common::testing::BindLambdaForTesting([&](hci::ErrorCode status) { status_2 = status; })); // Step 4: Leave channel IDLE long enough, they will disconnect - EXPECT_CALL(*raw_acl_connection, Disconnect(hci::DisconnectReason::REMOTE_USER_TERMINATED_CONNECTION)).Times(1); + EXPECT_CALL(*raw_acl_connection, + Disconnect(hci::DisconnectReason::REMOTE_USER_TERMINATED_CONNECTION)) + .Times(1); std::this_thread::sleep_for(kTestIdleDisconnectTimeoutShort * 1.2); user_handler->Clear(); @@ -343,7 +383,7 @@ TEST_F(L2capClassicLinkManagerTest, not_acquiring_channels_should_disconnect_acl TEST_F(L2capClassicLinkManagerTest, acquiring_channels_should_not_disconnect_acl_after_timeout) { EXPECT_CALL(*mock_parameter_provider_, GetClassicLinkIdleDisconnectTimeout) - .WillRepeatedly(Return(kTestIdleDisconnectTimeoutShort)); + .WillRepeatedly(Return(kTestIdleDisconnectTimeoutShort)); MockFixedChannelServiceManagerImpl mock_classic_fixed_channel_service_manager; MockAclManager mock_acl_manager; hci::Address device{{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}; @@ -353,9 +393,11 @@ TEST_F(L2capClassicLinkManagerTest, acquiring_channels_should_not_disconnect_acl hci::acl_manager::ConnectionCallbacks* hci_connection_callbacks = nullptr; os::Handler* hci_callback_handler = nullptr; EXPECT_CALL(mock_acl_manager, RegisterCallbacks(_, _)) - .WillOnce(DoAll(SaveArg<0>(&hci_connection_callbacks), SaveArg<1>(&hci_callback_handler))); - LinkManager classic_link_manager(l2cap_handler_, &mock_acl_manager, &mock_classic_fixed_channel_service_manager, - nullptr, mock_parameter_provider_); + .WillOnce( + DoAll(SaveArg<0>(&hci_connection_callbacks), SaveArg<1>(&hci_callback_handler))); + LinkManager classic_link_manager(l2cap_handler_, &mock_acl_manager, + &mock_classic_fixed_channel_service_manager, nullptr, + mock_parameter_provider_); EXPECT_EQ(hci_connection_callbacks, &classic_link_manager); EXPECT_EQ(hci_callback_handler, l2cap_handler_); @@ -364,16 +406,20 @@ TEST_F(L2capClassicLinkManagerTest, acquiring_channels_should_not_disconnect_acl std::vector> results; results.emplace_back(kSmpBrCid, &mock_service_1); results.emplace_back(kConnectionlessCid, &mock_service_2); - EXPECT_CALL(mock_classic_fixed_channel_service_manager, GetRegisteredServices()).WillRepeatedly(Return(results)); + EXPECT_CALL(mock_classic_fixed_channel_service_manager, GetRegisteredServices()) + .WillRepeatedly(Return(results)); // Step 2: Connect to fixed channel without ACL connection should trigger ACL connection process EXPECT_CALL(mock_acl_manager, CreateConnection(device)).Times(1); LinkManager::PendingFixedChannelConnection pending_fixed_channel_connection{ - .handler_ = user_handler.get(), - .on_fail_callback_ = common::BindOnce([](FixedChannelManager::ConnectionResult result) { FAIL(); })}; - classic_link_manager.ConnectFixedChannelServices(device, std::move(pending_fixed_channel_connection)); - - // Step 3: ACL connection success event should trigger channel creation for all registered services + .handler_ = user_handler.get(), + .on_fail_callback_ = + common::BindOnce([](FixedChannelManager::ConnectionResult result) { FAIL(); })}; + classic_link_manager.ConnectFixedChannelServices(device, + std::move(pending_fixed_channel_connection)); + + // Step 3: ACL connection success event should trigger channel creation for all registered + // services auto* raw_acl_connection = new MockClassicAclConnection(); std::unique_ptr acl_connection(raw_acl_connection); EXPECT_CALL(*acl_connection, GetAddress()).WillRepeatedly(Return(device)); @@ -383,17 +429,18 @@ TEST_F(L2capClassicLinkManagerTest, acquiring_channels_should_not_disconnect_acl auto future_1 = promise_1.get_future(); auto future_2 = promise_2.get_future(); EXPECT_CALL(mock_service_1, NotifyChannelCreation(_)) - .WillOnce([&channel_1, &promise_1](std::unique_ptr channel) { - channel_1 = std::move(channel); - promise_1.set_value(); - }); + .WillOnce([&channel_1, &promise_1](std::unique_ptr channel) { + channel_1 = std::move(channel); + promise_1.set_value(); + }); EXPECT_CALL(mock_service_2, NotifyChannelCreation(_)) - .WillOnce([&channel_2, &promise_2](std::unique_ptr channel) { - channel_2 = std::move(channel); - promise_2.set_value(); - }); - hci_callback_handler->Post(common::BindOnce(&hci::acl_manager::ConnectionCallbacks::OnConnectSuccess, - common::Unretained(hci_connection_callbacks), std::move(acl_connection))); + .WillOnce([&channel_2, &promise_2](std::unique_ptr channel) { + channel_2 = std::move(channel); + promise_2.set_value(); + }); + hci_callback_handler->Post(common::BindOnce( + &hci::acl_manager::ConnectionCallbacks::OnConnectSuccess, + common::Unretained(hci_connection_callbacks), std::move(acl_connection))); SyncHandler(hci_callback_handler); auto future_1_status = future_1.wait_for(kTestIdleDisconnectTimeoutShort); EXPECT_EQ(future_1_status, std::future_status::ready); @@ -403,23 +450,28 @@ TEST_F(L2capClassicLinkManagerTest, acquiring_channels_should_not_disconnect_acl EXPECT_NE(channel_2, nullptr); hci::ErrorCode status_1 = hci::ErrorCode::SUCCESS; channel_1->RegisterOnCloseCallback( - user_handler.get(), common::testing::BindLambdaForTesting([&](hci::ErrorCode status) { status_1 = status; })); + user_handler.get(), + common::testing::BindLambdaForTesting([&](hci::ErrorCode status) { status_1 = status; })); hci::ErrorCode status_2 = hci::ErrorCode::SUCCESS; channel_2->RegisterOnCloseCallback( - user_handler.get(), common::testing::BindLambdaForTesting([&](hci::ErrorCode status) { status_2 = status; })); + user_handler.get(), + common::testing::BindLambdaForTesting([&](hci::ErrorCode status) { status_2 = status; })); channel_1->Acquire(); // Step 4: Leave channel IDLE, it won't disconnect to due acquired channel 1 - EXPECT_CALL(*raw_acl_connection, Disconnect(hci::DisconnectReason::REMOTE_USER_TERMINATED_CONNECTION)).Times(0); + EXPECT_CALL(*raw_acl_connection, + Disconnect(hci::DisconnectReason::REMOTE_USER_TERMINATED_CONNECTION)) + .Times(0); std::this_thread::sleep_for(kTestIdleDisconnectTimeoutShort * 2); user_handler->Clear(); } -TEST_F(L2capClassicLinkManagerTest, acquiring_and_releasing_channels_should_eventually_disconnect_acl) { +TEST_F(L2capClassicLinkManagerTest, + acquiring_and_releasing_channels_should_eventually_disconnect_acl) { EXPECT_CALL(*mock_parameter_provider_, GetClassicLinkIdleDisconnectTimeout) - .WillRepeatedly(Return(kTestIdleDisconnectTimeoutShort)); + .WillRepeatedly(Return(kTestIdleDisconnectTimeoutShort)); MockFixedChannelServiceManagerImpl mock_classic_fixed_channel_service_manager; MockAclManager mock_acl_manager; hci::Address device{{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}; @@ -429,9 +481,11 @@ TEST_F(L2capClassicLinkManagerTest, acquiring_and_releasing_channels_should_even hci::acl_manager::ConnectionCallbacks* hci_connection_callbacks = nullptr; os::Handler* hci_callback_handler = nullptr; EXPECT_CALL(mock_acl_manager, RegisterCallbacks(_, _)) - .WillOnce(DoAll(SaveArg<0>(&hci_connection_callbacks), SaveArg<1>(&hci_callback_handler))); - LinkManager classic_link_manager(l2cap_handler_, &mock_acl_manager, &mock_classic_fixed_channel_service_manager, - nullptr, mock_parameter_provider_); + .WillOnce( + DoAll(SaveArg<0>(&hci_connection_callbacks), SaveArg<1>(&hci_callback_handler))); + LinkManager classic_link_manager(l2cap_handler_, &mock_acl_manager, + &mock_classic_fixed_channel_service_manager, nullptr, + mock_parameter_provider_); EXPECT_EQ(hci_connection_callbacks, &classic_link_manager); EXPECT_EQ(hci_callback_handler, l2cap_handler_); @@ -440,16 +494,20 @@ TEST_F(L2capClassicLinkManagerTest, acquiring_and_releasing_channels_should_even std::vector> results; results.emplace_back(kSmpBrCid, &mock_service_1); results.emplace_back(kConnectionlessCid, &mock_service_2); - EXPECT_CALL(mock_classic_fixed_channel_service_manager, GetRegisteredServices()).WillRepeatedly(Return(results)); + EXPECT_CALL(mock_classic_fixed_channel_service_manager, GetRegisteredServices()) + .WillRepeatedly(Return(results)); // Step 2: Connect to fixed channel without ACL connection should trigger ACL connection process EXPECT_CALL(mock_acl_manager, CreateConnection(device)).Times(1); LinkManager::PendingFixedChannelConnection pending_fixed_channel_connection{ - .handler_ = user_handler.get(), - .on_fail_callback_ = common::BindOnce([](FixedChannelManager::ConnectionResult result) { FAIL(); })}; - classic_link_manager.ConnectFixedChannelServices(device, std::move(pending_fixed_channel_connection)); - - // Step 3: ACL connection success event should trigger channel creation for all registered services + .handler_ = user_handler.get(), + .on_fail_callback_ = + common::BindOnce([](FixedChannelManager::ConnectionResult result) { FAIL(); })}; + classic_link_manager.ConnectFixedChannelServices(device, + std::move(pending_fixed_channel_connection)); + + // Step 3: ACL connection success event should trigger channel creation for all registered + // services auto* raw_acl_connection = new MockClassicAclConnection(); std::unique_ptr acl_connection(raw_acl_connection); EXPECT_CALL(*acl_connection, GetAddress()).WillRepeatedly(Return(device)); @@ -459,17 +517,18 @@ TEST_F(L2capClassicLinkManagerTest, acquiring_and_releasing_channels_should_even auto future_1 = promise_1.get_future(); auto future_2 = promise_2.get_future(); EXPECT_CALL(mock_service_1, NotifyChannelCreation(_)) - .WillOnce([&channel_1, &promise_1](std::unique_ptr channel) { - channel_1 = std::move(channel); - promise_1.set_value(); - }); + .WillOnce([&channel_1, &promise_1](std::unique_ptr channel) { + channel_1 = std::move(channel); + promise_1.set_value(); + }); EXPECT_CALL(mock_service_2, NotifyChannelCreation(_)) - .WillOnce([&channel_2, &promise_2](std::unique_ptr channel) { - channel_2 = std::move(channel); - promise_2.set_value(); - }); - hci_callback_handler->Post(common::BindOnce(&hci::acl_manager::ConnectionCallbacks::OnConnectSuccess, - common::Unretained(hci_connection_callbacks), std::move(acl_connection))); + .WillOnce([&channel_2, &promise_2](std::unique_ptr channel) { + channel_2 = std::move(channel); + promise_2.set_value(); + }); + hci_callback_handler->Post(common::BindOnce( + &hci::acl_manager::ConnectionCallbacks::OnConnectSuccess, + common::Unretained(hci_connection_callbacks), std::move(acl_connection))); SyncHandler(hci_callback_handler); auto future_1_status = future_1.wait_for(kTestIdleDisconnectTimeoutShort); EXPECT_EQ(future_1_status, std::future_status::ready); @@ -479,20 +538,26 @@ TEST_F(L2capClassicLinkManagerTest, acquiring_and_releasing_channels_should_even EXPECT_NE(channel_2, nullptr); hci::ErrorCode status_1 = hci::ErrorCode::SUCCESS; channel_1->RegisterOnCloseCallback( - user_handler.get(), common::testing::BindLambdaForTesting([&](hci::ErrorCode status) { status_1 = status; })); + user_handler.get(), + common::testing::BindLambdaForTesting([&](hci::ErrorCode status) { status_1 = status; })); hci::ErrorCode status_2 = hci::ErrorCode::SUCCESS; channel_2->RegisterOnCloseCallback( - user_handler.get(), common::testing::BindLambdaForTesting([&](hci::ErrorCode status) { status_2 = status; })); + user_handler.get(), + common::testing::BindLambdaForTesting([&](hci::ErrorCode status) { status_2 = status; })); channel_1->Acquire(); // Step 4: Leave channel IDLE, it won't disconnect to due acquired channel 1 - EXPECT_CALL(*raw_acl_connection, Disconnect(hci::DisconnectReason::REMOTE_USER_TERMINATED_CONNECTION)).Times(0); + EXPECT_CALL(*raw_acl_connection, + Disconnect(hci::DisconnectReason::REMOTE_USER_TERMINATED_CONNECTION)) + .Times(0); std::this_thread::sleep_for(kTestIdleDisconnectTimeoutShort * 2); // Step 5: Leave channel IDLE long enough, they will disconnect channel_1->Release(); - EXPECT_CALL(*raw_acl_connection, Disconnect(hci::DisconnectReason::REMOTE_USER_TERMINATED_CONNECTION)).Times(1); + EXPECT_CALL(*raw_acl_connection, + Disconnect(hci::DisconnectReason::REMOTE_USER_TERMINATED_CONNECTION)) + .Times(1); std::this_thread::sleep_for(kTestIdleDisconnectTimeoutShort * 1.2); user_handler->Clear(); diff --git a/system/gd/l2cap/classic/internal/link_mock.h b/system/gd/l2cap/classic/internal/link_mock.h index 54f8fb9f5f1..c55649117f9 100644 --- a/system/gd/l2cap/classic/internal/link_mock.h +++ b/system/gd/l2cap/classic/internal/link_mock.h @@ -15,13 +15,13 @@ */ #pragma once +#include + #include "hci/acl_manager_mock.h" #include "hci/address.h" #include "l2cap/classic/internal/link.h" #include "l2cap/internal/scheduler_mock.h" -#include - // Unit test interfaces namespace bluetooth { namespace l2cap { @@ -32,20 +32,19 @@ namespace testing { using hci::testing::MockClassicAclConnection; class MockLink : public Link { - public: +public: explicit MockLink(os::Handler* handler, l2cap::internal::ParameterProvider* parameter_provider) - : Link(handler, std::make_unique(), parameter_provider, nullptr, nullptr, nullptr){}; - explicit MockLink( - os::Handler* handler, - l2cap::internal::ParameterProvider* parameter_provider, - std::unique_ptr acl_connection, - LinkManager* /* link_manager */) - : Link(handler, std::move(acl_connection), parameter_provider, nullptr, nullptr, nullptr){}; + : Link(handler, std::make_unique(), parameter_provider, nullptr, + nullptr, nullptr) {} + explicit MockLink(os::Handler* handler, l2cap::internal::ParameterProvider* parameter_provider, + std::unique_ptr acl_connection, + LinkManager* /* link_manager */) + : Link(handler, std::move(acl_connection), parameter_provider, nullptr, nullptr, nullptr) {} MOCK_METHOD(hci::AddressWithType, GetDevice, (), (const, override)); MOCK_METHOD(void, OnAclDisconnected, (hci::ErrorCode status), (override)); MOCK_METHOD(void, Disconnect, (), (override)); - MOCK_METHOD(std::shared_ptr, AllocateDynamicChannel, (Psm psm, Cid cid), - (override)); + MOCK_METHOD(std::shared_ptr, AllocateDynamicChannel, + (Psm psm, Cid cid), (override)); MOCK_METHOD(bool, IsFixedChannelAllocated, (Cid cid), (override)); MOCK_METHOD(void, RefreshRefCount, (), (override)); diff --git a/system/gd/l2cap/classic/internal/link_test.cc b/system/gd/l2cap/classic/internal/link_test.cc index 89d6dc75d57..c6a0addccb7 100644 --- a/system/gd/l2cap/classic/internal/link_test.cc +++ b/system/gd/l2cap/classic/internal/link_test.cc @@ -16,6 +16,10 @@ #include "l2cap/classic/internal/link.h" +#include +#include +#include + #include "hci/acl_manager_mock.h" #include "hci/address.h" #include "l2cap/classic/internal/dynamic_channel_service_impl_mock.h" @@ -23,10 +27,6 @@ #include "l2cap/classic/internal/fixed_channel_service_manager_impl_mock.h" #include "l2cap/internal/parameter_provider_mock.h" -#include -#include -#include - using ::testing::NiceMock; namespace bluetooth { @@ -45,17 +45,14 @@ using l2cap::internal::testing::MockParameterProvider; using testing::MockFixedChannelServiceManagerImpl; class L2capClassicLinkTest : public ::testing::Test { - public: - void OnOpen(std::unique_ptr channel) { - on_open_promise_.set_value(); - } +public: + void OnOpen(std::unique_ptr channel) { on_open_promise_.set_value(); } - void OnFail(DynamicChannelManager::ConnectionResult result) { - on_fail_promise_.set_value(); - } + void OnFail(DynamicChannelManager::ConnectionResult result) { on_fail_promise_.set_value(); } void OnDequeueCallbackForTest() { - std::unique_ptr data = raw_acl_connection_->acl_queue_.GetDownEnd()->TryDequeue(); + std::unique_ptr data = + raw_acl_connection_->acl_queue_.GetDownEnd()->TryDequeue(); if (data != nullptr) { dequeue_promise_.set_value(); } @@ -63,21 +60,21 @@ class L2capClassicLinkTest : public ::testing::Test { void EnqueueCallbackForTest() { raw_acl_connection_->acl_queue_.GetDownEnd()->RegisterDequeue( - handler_, common::Bind(&L2capClassicLinkTest::OnDequeueCallbackForTest, common::Unretained(this))); + handler_, common::Bind(&L2capClassicLinkTest::OnDequeueCallbackForTest, + common::Unretained(this))); } - void DequeueCallback() { - raw_acl_connection_->acl_queue_.GetDownEnd()->UnregisterDequeue(); - } + void DequeueCallback() { raw_acl_connection_->acl_queue_.GetDownEnd()->UnregisterDequeue(); } - protected: +protected: void SetUp() override { thread_ = new os::Thread("test_thread", os::Thread::Priority::NORMAL); handler_ = new os::Handler(thread_); signalling_handler_ = new os::Handler(thread_); raw_acl_connection_ = new NiceMock(); - link_ = new Link(signalling_handler_, std::unique_ptr(raw_acl_connection_), + link_ = new Link(signalling_handler_, + std::unique_ptr(raw_acl_connection_), &mock_parameter_provider_, &mock_classic_dynamic_channel_service_manager_, &mock_classic_fixed_channel_service_manager_, nullptr); } @@ -117,20 +114,21 @@ TEST_F(L2capClassicLinkTest, pending_channels_get_notified_on_acl_disconnect) { EnqueueCallbackForTest(); Link::PendingDynamicChannelConnection pending_dynamic_channel_connection{ - .on_open_callback_ = handler_->BindOn(this, &L2capClassicLinkTest::OnOpen), - .on_fail_callback_ = handler_->BindOnceOn(this, &L2capClassicLinkTest::OnFail), - .configuration_ = DynamicChannelConfigurationOption(), + .on_open_callback_ = handler_->BindOn(this, &L2capClassicLinkTest::OnOpen), + .on_fail_callback_ = handler_->BindOnceOn(this, &L2capClassicLinkTest::OnFail), + .configuration_ = DynamicChannelConfigurationOption(), }; auto future = on_fail_promise_.get_future(); MockDynamicChannelServiceImpl service; ON_CALL(service, GetSecurityPolicy()) - .WillByDefault(::testing::Return(SecurityPolicy::_SDP_ONLY_NO_SECURITY_WHATSOEVER_PLAINTEXT_TRANSPORT_OK)); + .WillByDefault(::testing::Return( + SecurityPolicy::_SDP_ONLY_NO_SECURITY_WHATSOEVER_PLAINTEXT_TRANSPORT_OK)); EXPECT_CALL(mock_classic_dynamic_channel_service_manager_, GetSecurityEnforcementInterface()) - .WillOnce(::testing::Return(&security_module_impl_)); + .WillOnce(::testing::Return(&security_module_impl_)); EXPECT_CALL(mock_classic_dynamic_channel_service_manager_, GetService(::testing::_)) - .WillRepeatedly(::testing::Return(&service)); + .WillRepeatedly(::testing::Return(&service)); link_->SendConnectionRequest(kPsm, kCid, std::move(pending_dynamic_channel_connection)); link_->OnAclDisconnected(hci::ErrorCode::UNKNOWN_HCI_COMMAND); diff --git a/system/gd/l2cap/classic/internal/signalling_manager.cc b/system/gd/l2cap/classic/internal/signalling_manager.cc index 34a72f708d4..b26b194472f 100644 --- a/system/gd/l2cap/classic/internal/signalling_manager.cc +++ b/system/gd/l2cap/classic/internal/signalling_manager.cc @@ -50,21 +50,27 @@ static std::vector GetCommandsFromPacketView(PacketViewAllocateFixedChannel(kClassicSignallingCid); signalling_channel_->GetQueueUpEnd()->RegisterDequeue( - handler_, common::Bind(&ClassicSignallingManager::on_incoming_packet, common::Unretained(this))); - enqueue_buffer_ = - std::make_unique>(signalling_channel_->GetQueueUpEnd()); + handler_, + common::Bind(&ClassicSignallingManager::on_incoming_packet, common::Unretained(this))); + enqueue_buffer_ = std::make_unique>( + signalling_channel_->GetQueueUpEnd()); } ClassicSignallingManager::~ClassicSignallingManager() { @@ -92,18 +98,14 @@ void ClassicSignallingManager::OnCommandReject(CommandRejectView command_reject_ void ClassicSignallingManager::SendConnectionRequest(Psm psm, Cid local_cid) { dynamic_service_manager_->GetSecurityEnforcementInterface()->Enforce( - link_->GetDevice(), - dynamic_service_manager_->GetService(psm)->GetSecurityPolicy(), - handler_->BindOnceOn( - this, - &ClassicSignallingManager::on_security_result_for_outgoing, - SecurityEnforcementType::LINK_KEY, - psm, - local_cid)); + link_->GetDevice(), dynamic_service_manager_->GetService(psm)->GetSecurityPolicy(), + handler_->BindOnceOn(this, &ClassicSignallingManager::on_security_result_for_outgoing, + SecurityEnforcementType::LINK_KEY, psm, local_cid)); } -void ClassicSignallingManager::on_security_result_for_outgoing( - SecurityEnforcementType type, Psm psm, Cid local_cid, bool result) { +void ClassicSignallingManager::on_security_result_for_outgoing(SecurityEnforcementType type, + Psm psm, Cid local_cid, + bool result) { if (enqueue_buffer_.get() == nullptr) { log::error("Got security result callback after deletion"); return; @@ -111,21 +113,24 @@ void ClassicSignallingManager::on_security_result_for_outgoing( if (!result) { log::warn("Security requirement can't be satisfied. Dropping connection request"); DynamicChannelManager::ConnectionResult connection_result{ - .connection_result_code = DynamicChannelManager::ConnectionResultCode::FAIL_SECURITY_BLOCK, - .hci_error = hci::ErrorCode::SUCCESS, - .l2cap_connection_response_result = ConnectionResponseResult::NO_RESOURCES_AVAILABLE, + .connection_result_code = + DynamicChannelManager::ConnectionResultCode::FAIL_SECURITY_BLOCK, + .hci_error = hci::ErrorCode::SUCCESS, + .l2cap_connection_response_result = ConnectionResponseResult::NO_RESOURCES_AVAILABLE, }; link_->OnOutgoingConnectionRequestFail(local_cid, connection_result); return; } if (type == SecurityEnforcementType::LINK_KEY && !link_->IsAuthenticated() && dynamic_service_manager_->GetService(psm)->GetSecurityPolicy() != - SecurityPolicy::_SDP_ONLY_NO_SECURITY_WHATSOEVER_PLAINTEXT_TRANSPORT_OK) { + SecurityPolicy::_SDP_ONLY_NO_SECURITY_WHATSOEVER_PLAINTEXT_TRANSPORT_OK) { link_->Encrypt(); - // TODO(b/171253721): If we can receive ENCRYPTION_CHANGE event, we can send command after callback is received. + // TODO(b/171253721): If we can receive ENCRYPTION_CHANGE event, we can send command after + // callback is received. } - PendingCommand pending_command = {next_signal_id_, CommandCode::CONNECTION_REQUEST, psm, local_cid, {}, {}, {}}; + PendingCommand pending_command = { + next_signal_id_, CommandCode::CONNECTION_REQUEST, psm, local_cid, {}, {}, {}}; next_signal_id_++; pending_commands_.push(std::move(pending_command)); if (command_just_sent_.signal_id_ == kInvalidSignalId) { @@ -133,10 +138,11 @@ void ClassicSignallingManager::on_security_result_for_outgoing( } } -void ClassicSignallingManager::send_configuration_request(Cid remote_cid, - std::vector> config) { - PendingCommand pending_command = {next_signal_id_, CommandCode::CONFIGURATION_REQUEST, {}, {}, remote_cid, {}, - std::move(config)}; +void ClassicSignallingManager::send_configuration_request( + Cid remote_cid, std::vector> config) { + PendingCommand pending_command = { + next_signal_id_, CommandCode::CONFIGURATION_REQUEST, {}, {}, remote_cid, {}, + std::move(config)}; next_signal_id_++; pending_commands_.push(std::move(pending_command)); if (command_just_sent_.signal_id_ == kInvalidSignalId) { @@ -146,7 +152,7 @@ void ClassicSignallingManager::send_configuration_request(Cid remote_cid, void ClassicSignallingManager::SendDisconnectionRequest(Cid local_cid, Cid remote_cid) { PendingCommand pending_command = { - next_signal_id_, CommandCode::DISCONNECTION_REQUEST, {}, local_cid, remote_cid, {}, {}}; + next_signal_id_, CommandCode::DISCONNECTION_REQUEST, {}, local_cid, remote_cid, {}, {}}; next_signal_id_++; pending_commands_.push(std::move(pending_command)); if (command_just_sent_.signal_id_ == kInvalidSignalId) { @@ -155,7 +161,8 @@ void ClassicSignallingManager::SendDisconnectionRequest(Cid local_cid, Cid remot } void ClassicSignallingManager::SendInformationRequest(InformationRequestInfoType type) { - PendingCommand pending_command = {next_signal_id_, CommandCode::INFORMATION_REQUEST, {}, {}, {}, type, {}}; + PendingCommand pending_command = { + next_signal_id_, CommandCode::INFORMATION_REQUEST, {}, {}, {}, type, {}}; next_signal_id_++; pending_commands_.push(std::move(pending_command)); if (command_just_sent_.signal_id_ == kInvalidSignalId) { @@ -167,21 +174,21 @@ void ClassicSignallingManager::SendEchoRequest(std::unique_ptrIsServiceRegistered(psm)) { log::info("Service for this psm ({}) is not registered", psm); - send_connection_response(signal_id, remote_cid, kInvalidCid, ConnectionResponseResult::PSM_NOT_SUPPORTED, + send_connection_response(signal_id, remote_cid, kInvalidCid, + ConnectionResponseResult::PSM_NOT_SUPPORTED, ConnectionResponseStatus::NO_FURTHER_INFORMATION_AVAILABLE); return; } dynamic_service_manager_->GetSecurityEnforcementInterface()->Enforce( - link_->GetDevice(), - dynamic_service_manager_->GetService(psm)->GetSecurityPolicy(), - handler_->BindOnceOn( - this, &ClassicSignallingManager::on_security_result_for_incoming, psm, remote_cid, signal_id)); + link_->GetDevice(), dynamic_service_manager_->GetService(psm)->GetSecurityPolicy(), + handler_->BindOnceOn(this, &ClassicSignallingManager::on_security_result_for_incoming, + psm, remote_cid, signal_id)); } -void ClassicSignallingManager::on_security_result_for_incoming( - Psm psm, Cid remote_cid, SignalId signal_id, bool result) { +void ClassicSignallingManager::on_security_result_for_incoming(Psm psm, Cid remote_cid, + SignalId signal_id, bool result) { if (enqueue_buffer_.get() == nullptr) { log::error("Got security result callback after deletion"); return; } if (!result) { - send_connection_response( - signal_id, - remote_cid, - 0, - ConnectionResponseResult::SECURITY_BLOCK, - ConnectionResponseStatus::NO_FURTHER_INFORMATION_AVAILABLE); + send_connection_response(signal_id, remote_cid, 0, ConnectionResponseResult::SECURITY_BLOCK, + ConnectionResponseStatus::NO_FURTHER_INFORMATION_AVAILABLE); DynamicChannelManager::ConnectionResult connection_result{ - .connection_result_code = DynamicChannelManager::ConnectionResultCode::FAIL_SECURITY_BLOCK, - .hci_error = hci::ErrorCode::SUCCESS, - .l2cap_connection_response_result = ConnectionResponseResult::NO_RESOURCES_AVAILABLE, + .connection_result_code = + DynamicChannelManager::ConnectionResultCode::FAIL_SECURITY_BLOCK, + .hci_error = hci::ErrorCode::SUCCESS, + .l2cap_connection_response_result = ConnectionResponseResult::NO_RESOURCES_AVAILABLE, }; link_->OnOutgoingConnectionRequestFail(0, connection_result); } @@ -235,29 +239,21 @@ void ClassicSignallingManager::on_security_result_for_incoming( log::warn("Can't allocate dynamic channel"); return; } - send_connection_response( - signal_id, - remote_cid, - new_channel->GetCid(), - ConnectionResponseResult::SUCCESS, - ConnectionResponseStatus::NO_FURTHER_INFORMATION_AVAILABLE); + send_connection_response(signal_id, remote_cid, new_channel->GetCid(), + ConnectionResponseResult::SUCCESS, + ConnectionResponseStatus::NO_FURTHER_INFORMATION_AVAILABLE); link_->SendInitialConfigRequestOrQueue(new_channel->GetCid()); } -void ClassicSignallingManager::OnConnectionResponse( - SignalId signal_id, - Cid remote_cid, - Cid cid, - ConnectionResponseResult result, - ConnectionResponseStatus /* status */) { +void ClassicSignallingManager::OnConnectionResponse(SignalId signal_id, Cid remote_cid, Cid cid, + ConnectionResponseResult result, + ConnectionResponseStatus /* status */) { if (command_just_sent_.signal_id_ != signal_id || command_just_sent_.command_code_ != CommandCode::CONNECTION_REQUEST) { - log::warn( - "Unexpected response: no pending request. Expected signal id {} type {}, got {}", - command_just_sent_.signal_id_.Value(), - CommandCodeText(command_just_sent_.command_code_).data(), - signal_id.Value()); + log::warn("Unexpected response: no pending request. Expected signal id {} type {}, got {}", + command_just_sent_.signal_id_.Value(), + CommandCodeText(command_just_sent_.command_code_).data(), signal_id.Value()); return; } if (command_just_sent_.source_cid_ != cid) { @@ -266,7 +262,8 @@ void ClassicSignallingManager::OnConnectionResponse( return; } if (result == ConnectionResponseResult::PENDING) { - alarm_.Schedule(common::BindOnce(&ClassicSignallingManager::on_command_timeout, common::Unretained(this)), + alarm_.Schedule(common::BindOnce(&ClassicSignallingManager::on_command_timeout, + common::Unretained(this)), kTimeout); return; } @@ -275,9 +272,9 @@ void ClassicSignallingManager::OnConnectionResponse( alarm_.Cancel(); if (result != ConnectionResponseResult::SUCCESS) { DynamicChannelManager::ConnectionResult connection_result{ - .connection_result_code = DynamicChannelManager::ConnectionResultCode::FAIL_L2CAP_ERROR, - .hci_error = hci::ErrorCode::SUCCESS, - .l2cap_connection_response_result = result, + .connection_result_code = DynamicChannelManager::ConnectionResultCode::FAIL_L2CAP_ERROR, + .hci_error = hci::ErrorCode::SUCCESS, + .l2cap_connection_response_result = result, }; link_->OnOutgoingConnectionRequestFail(cid, connection_result); handle_send_next_command(); @@ -288,9 +285,9 @@ void ClassicSignallingManager::OnConnectionResponse( if (new_channel == nullptr) { log::warn("Can't allocate dynamic channel"); DynamicChannelManager::ConnectionResult connection_result{ - .connection_result_code = DynamicChannelManager::ConnectionResultCode::FAIL_L2CAP_ERROR, - .hci_error = hci::ErrorCode::SUCCESS, - .l2cap_connection_response_result = ConnectionResponseResult::NO_RESOURCES_AVAILABLE, + .connection_result_code = DynamicChannelManager::ConnectionResultCode::FAIL_L2CAP_ERROR, + .hci_error = hci::ErrorCode::SUCCESS, + .l2cap_connection_response_result = ConnectionResponseResult::NO_RESOURCES_AVAILABLE, }; link_->OnOutgoingConnectionRequestFail(cid, connection_result); handle_send_next_command(); @@ -300,8 +297,9 @@ void ClassicSignallingManager::OnConnectionResponse( link_->SendInitialConfigRequestOrQueue(cid); } -void ClassicSignallingManager::OnConfigurationRequest(SignalId signal_id, Cid cid, Continuation is_continuation, - std::vector> options) { +void ClassicSignallingManager::OnConfigurationRequest( + SignalId signal_id, Cid cid, Continuation is_continuation, + std::vector> options) { auto channel = channel_allocator_->FindChannelByCid(cid); if (channel == nullptr) { log::warn("Configuration request for an unknown channel"); @@ -313,7 +311,8 @@ void ClassicSignallingManager::OnConfigurationRequest(SignalId signal_id, Cid ci ConfigurationResponseResult result = ConfigurationResponseResult::SUCCESS; auto remote_rfc_mode = RetransmissionAndFlowControlModeOption::L2CAP_BASIC; - auto initial_config_option = dynamic_service_manager_->GetService(channel->GetPsm())->GetConfigOption(); + auto initial_config_option = + dynamic_service_manager_->GetService(channel->GetPsm())->GetConfigOption(); for (auto& option : options) { switch (option->type_) { @@ -345,7 +344,8 @@ void ClassicSignallingManager::OnConfigurationRequest(SignalId signal_id, Cid ci } configuration_state.remote_retransmission_and_flow_control_ = *config; configuration_state.retransmission_and_flow_control_mode_ = config->mode_; - rsp_options.emplace_back(std::make_unique(*config)); + rsp_options.emplace_back( + std::make_unique(*config)); break; } case ConfigurationOptionType::FRAME_CHECK_SEQUENCE: { @@ -354,12 +354,11 @@ void ClassicSignallingManager::OnConfigurationRequest(SignalId signal_id, Cid ci } default: if (option->is_hint_ != ConfigurationOptionIsHint::OPTION_IS_A_HINT) { - log::warn( - "Received some unsupported configuration option: {}", - static_cast(option->type_)); - auto response = - ConfigurationResponseBuilder::Create(signal_id.Value(), channel->GetRemoteCid(), is_continuation, - ConfigurationResponseResult::UNKNOWN_OPTIONS, {}); + log::warn("Received some unsupported configuration option: {}", + static_cast(option->type_)); + auto response = ConfigurationResponseBuilder::Create( + signal_id.Value(), channel->GetRemoteCid(), is_continuation, + ConfigurationResponseResult::UNKNOWN_OPTIONS, {}); enqueue_buffer_->Enqueue(std::move(response), handler_); return; } @@ -369,28 +368,33 @@ void ClassicSignallingManager::OnConfigurationRequest(SignalId signal_id, Cid ci if (remote_rfc_mode == RetransmissionAndFlowControlModeOption::L2CAP_BASIC && initial_config_option.channel_mode == - DynamicChannelConfigurationOption::RetransmissionAndFlowControlMode::ENHANCED_RETRANSMISSION) { + DynamicChannelConfigurationOption::RetransmissionAndFlowControlMode:: + ENHANCED_RETRANSMISSION) { log::warn("ERTM mandatory not allow mode configuration, disconnect channel."); SendDisconnectionRequest(channel->GetCid(), channel->GetRemoteCid()); return; } if (configuration_state.state_ == ChannelConfigurationState::State::WAIT_CONFIG_REQ) { - std::unique_ptr user_channel = std::make_unique(channel, handler_); + std::unique_ptr user_channel = + std::make_unique(channel, handler_); if (channel->local_initiated_) { link_->NotifyChannelCreation(cid, std::move(user_channel)); } else { - dynamic_service_manager_->GetService(channel->GetPsm())->NotifyChannelCreation(std::move(user_channel)); + dynamic_service_manager_->GetService(channel->GetPsm()) + ->NotifyChannelCreation(std::move(user_channel)); } configuration_state.state_ = ChannelConfigurationState::State::CONFIGURED; - data_pipeline_manager_->AttachChannel(cid, channel, l2cap::internal::DataPipelineManager::ChannelMode::BASIC); + data_pipeline_manager_->AttachChannel(cid, channel, + l2cap::internal::DataPipelineManager::ChannelMode::BASIC); data_pipeline_manager_->UpdateClassicConfiguration(cid, configuration_state); } else if (configuration_state.state_ == ChannelConfigurationState::State::WAIT_CONFIG_REQ_RSP) { configuration_state.state_ = ChannelConfigurationState::State::WAIT_CONFIG_RSP; } - auto response = ConfigurationResponseBuilder::Create(signal_id.Value(), channel->GetRemoteCid(), is_continuation, - result, std::move(rsp_options)); + auto response = + ConfigurationResponseBuilder::Create(signal_id.Value(), channel->GetRemoteCid(), + is_continuation, result, std::move(rsp_options)); enqueue_buffer_->Enqueue(std::move(response), handler_); } @@ -412,18 +416,23 @@ void ClassicSignallingManager::SendInitialConfigRequest(Cid local_cid) { configuration_state.fcs_type_ = FcsType::DEFAULT; } - auto retransmission_flow_control_configuration = std::make_unique(); + auto retransmission_flow_control_configuration = + std::make_unique(); switch (initial_config.channel_mode) { case DynamicChannelConfigurationOption::RetransmissionAndFlowControlMode::L2CAP_BASIC: - retransmission_flow_control_configuration->mode_ = RetransmissionAndFlowControlModeOption::L2CAP_BASIC; - configuration_state.retransmission_and_flow_control_mode_ = RetransmissionAndFlowControlModeOption::L2CAP_BASIC; + retransmission_flow_control_configuration->mode_ = + RetransmissionAndFlowControlModeOption::L2CAP_BASIC; + configuration_state.retransmission_and_flow_control_mode_ = + RetransmissionAndFlowControlModeOption::L2CAP_BASIC; break; - case DynamicChannelConfigurationOption::RetransmissionAndFlowControlMode::ENHANCED_RETRANSMISSION: - case DynamicChannelConfigurationOption::RetransmissionAndFlowControlMode::ENHANCED_RETRANSMISSION_OPTIONAL: + case DynamicChannelConfigurationOption::RetransmissionAndFlowControlMode:: + ENHANCED_RETRANSMISSION: + case DynamicChannelConfigurationOption::RetransmissionAndFlowControlMode:: + ENHANCED_RETRANSMISSION_OPTIONAL: retransmission_flow_control_configuration->mode_ = - RetransmissionAndFlowControlModeOption::ENHANCED_RETRANSMISSION; + RetransmissionAndFlowControlModeOption::ENHANCED_RETRANSMISSION; configuration_state.retransmission_and_flow_control_mode_ = - RetransmissionAndFlowControlModeOption::ENHANCED_RETRANSMISSION; + RetransmissionAndFlowControlModeOption::ENHANCED_RETRANSMISSION; // TODO: Decide where to put initial values retransmission_flow_control_configuration->tx_window_size_ = 10; retransmission_flow_control_configuration->max_transmit_ = 20; @@ -432,11 +441,13 @@ void ClassicSignallingManager::SendInitialConfigRequest(Cid local_cid) { retransmission_flow_control_configuration->maximum_pdu_size_ = 1010; break; } - configuration_state.local_retransmission_and_flow_control_ = *retransmission_flow_control_configuration; + configuration_state.local_retransmission_and_flow_control_ = + *retransmission_flow_control_configuration; std::vector> config; config.emplace_back(std::move(mtu_configuration)); - if (initial_config.channel_mode != DynamicChannelConfigurationOption::RetransmissionAndFlowControlMode::L2CAP_BASIC) { + if (initial_config.channel_mode != + DynamicChannelConfigurationOption::RetransmissionAndFlowControlMode::L2CAP_BASIC) { config.emplace_back(std::move(retransmission_flow_control_configuration)); config.emplace_back(std::move(fcs_option)); } @@ -444,7 +455,7 @@ void ClassicSignallingManager::SendInitialConfigRequest(Cid local_cid) { } void ClassicSignallingManager::negotiate_configuration( - Cid cid, Continuation, std::vector> options) { + Cid cid, Continuation, std::vector> options) { auto channel = channel_allocator_->FindChannelByCid(cid); auto& configuration_state = channel_configuration_[channel->GetCid()]; std::vector> negotiation_config; @@ -470,19 +481,24 @@ void ClassicSignallingManager::negotiate_configuration( if (config->mode_ == RetransmissionAndFlowControlModeOption::ENHANCED_RETRANSMISSION) { configuration_state.retransmission_and_flow_control_mode_ = config->mode_; configuration_state.local_retransmission_and_flow_control_ = *config; - negotiation_config.emplace_back(std::make_unique(*config)); + negotiation_config.emplace_back( + std::make_unique(*config)); } else if (config->mode_ == RetransmissionAndFlowControlModeOption::L2CAP_BASIC) { - auto initial_config_option = dynamic_service_manager_->GetService(channel->GetPsm())->GetConfigOption(); + auto initial_config_option = + dynamic_service_manager_->GetService(channel->GetPsm())->GetConfigOption(); if (initial_config_option.channel_mode == - DynamicChannelConfigurationOption::RetransmissionAndFlowControlMode::ENHANCED_RETRANSMISSION) { - // ERTM mandatory is not allow negotiating of retransmission and flow control mode, disconnect channel + DynamicChannelConfigurationOption::RetransmissionAndFlowControlMode:: + ENHANCED_RETRANSMISSION) { + // ERTM mandatory is not allow negotiating of retransmission and flow control mode, + // disconnect channel SendDisconnectionRequest(channel->GetCid(), channel->GetRemoteCid()); return; } else if (initial_config_option.channel_mode == DynamicChannelConfigurationOption::RetransmissionAndFlowControlMode:: - ENHANCED_RETRANSMISSION_OPTIONAL) { + ENHANCED_RETRANSMISSION_OPTIONAL) { can_negotiate = true; - negotiation_config.emplace_back(std::make_unique(*config)); + negotiation_config.emplace_back( + std::make_unique(*config)); } } else { // Not support other retransmission and flow control mode, disconnect channel. @@ -492,8 +508,8 @@ void ClassicSignallingManager::negotiate_configuration( break; } default: - log::warn( - "Received some unsupported configuration option: {}", static_cast(option->type_)); + log::warn("Received some unsupported configuration option: {}", + static_cast(option->type_)); return; } } @@ -504,16 +520,15 @@ void ClassicSignallingManager::negotiate_configuration( } } -void ClassicSignallingManager::OnConfigurationResponse(SignalId signal_id, Cid cid, Continuation is_continuation, - ConfigurationResponseResult result, - std::vector> options) { +void ClassicSignallingManager::OnConfigurationResponse( + SignalId signal_id, Cid cid, Continuation is_continuation, + ConfigurationResponseResult result, + std::vector> options) { if (command_just_sent_.signal_id_ != signal_id || command_just_sent_.command_code_ != CommandCode::CONFIGURATION_REQUEST) { - log::warn( - "Unexpected response: no pending request. Expected signal id {} type {}, got {}", - command_just_sent_.signal_id_.Value(), - CommandCodeText(command_just_sent_.command_code_).data(), - signal_id.Value()); + log::warn("Unexpected response: no pending request. Expected signal id {} type {}, got {}", + command_just_sent_.signal_id_.Value(), + CommandCodeText(command_just_sent_.command_code_).data(), signal_id.Value()); return; } @@ -535,7 +550,8 @@ void ClassicSignallingManager::OnConfigurationResponse(SignalId signal_id, Cid c return; case ConfigurationResponseResult::PENDING: - alarm_.Schedule(common::BindOnce(&ClassicSignallingManager::on_command_timeout, common::Unretained(this)), + alarm_.Schedule(common::BindOnce(&ClassicSignallingManager::on_command_timeout, + common::Unretained(this)), kTimeout); return; @@ -572,12 +588,13 @@ void ClassicSignallingManager::OnConfigurationResponse(SignalId signal_id, Cid c break; } case ConfigurationOptionType::FRAME_CHECK_SEQUENCE: { - configuration_state.fcs_type_ = FrameCheckSequenceOption::Specialize(option.get())->fcs_type_; + configuration_state.fcs_type_ = + FrameCheckSequenceOption::Specialize(option.get())->fcs_type_; break; } default: - log::warn( - "Received some unsupported configuration option: {}", static_cast(option->type_)); + log::warn("Received some unsupported configuration option: {}", + static_cast(option->type_)); alarm_.Cancel(); handle_send_next_command(); return; @@ -585,14 +602,17 @@ void ClassicSignallingManager::OnConfigurationResponse(SignalId signal_id, Cid c } if (configuration_state.state_ == ChannelConfigurationState::State::WAIT_CONFIG_RSP) { - std::unique_ptr user_channel = std::make_unique(channel, handler_); + std::unique_ptr user_channel = + std::make_unique(channel, handler_); if (channel->local_initiated_) { link_->NotifyChannelCreation(cid, std::move(user_channel)); } else { - dynamic_service_manager_->GetService(channel->GetPsm())->NotifyChannelCreation(std::move(user_channel)); + dynamic_service_manager_->GetService(channel->GetPsm()) + ->NotifyChannelCreation(std::move(user_channel)); } configuration_state.state_ = ChannelConfigurationState::State::CONFIGURED; - data_pipeline_manager_->AttachChannel(cid, channel, l2cap::internal::DataPipelineManager::ChannelMode::BASIC); + data_pipeline_manager_->AttachChannel(cid, channel, + l2cap::internal::DataPipelineManager::ChannelMode::BASIC); data_pipeline_manager_->UpdateClassicConfiguration(cid, configuration_state); } else if (configuration_state.state_ == ChannelConfigurationState::State::WAIT_CONFIG_REQ_RSP) { configuration_state.state_ = ChannelConfigurationState::State::WAIT_CONFIG_REQ; @@ -620,15 +640,13 @@ void ClassicSignallingManager::OnDisconnectionRequest(SignalId signal_id, Cid ci channel_configuration_.erase(cid); } -void ClassicSignallingManager::OnDisconnectionResponse( - SignalId signal_id, Cid /* remote_cid */, Cid cid) { +void ClassicSignallingManager::OnDisconnectionResponse(SignalId signal_id, Cid /* remote_cid */, + Cid cid) { if (command_just_sent_.signal_id_ != signal_id || command_just_sent_.command_code_ != CommandCode::DISCONNECTION_REQUEST) { - log::warn( - "Unexpected response: no pending request. Expected signal id {} type {}, got {}", - command_just_sent_.signal_id_.Value(), - CommandCodeText(command_just_sent_.command_code_).data(), - signal_id.Value()); + log::warn("Unexpected response: no pending request. Expected signal id {} type {}, got {}", + command_just_sent_.signal_id_.Value(), + CommandCodeText(command_just_sent_.command_code_).data(), signal_id.Value()); return; } @@ -651,7 +669,8 @@ void ClassicSignallingManager::OnDisconnectionResponse( channel_configuration_.erase(cid); } -void ClassicSignallingManager::OnEchoRequest(SignalId signal_id, const PacketView& packet) { +void ClassicSignallingManager::OnEchoRequest(SignalId signal_id, + const PacketView& packet) { std::vector packet_vector{packet.begin(), packet.end()}; auto raw_builder = std::make_unique(); raw_builder->AddOctets(packet_vector); @@ -659,14 +678,13 @@ void ClassicSignallingManager::OnEchoRequest(SignalId signal_id, const PacketVie enqueue_buffer_->Enqueue(std::move(builder), handler_); } -void ClassicSignallingManager::OnEchoResponse( - SignalId signal_id, const PacketView& /* packet */) { - if (command_just_sent_.signal_id_ != signal_id || command_just_sent_.command_code_ != CommandCode::ECHO_REQUEST) { - log::warn( - "Unexpected response: no pending request. Expected signal id {} type {}, got {}", - command_just_sent_.signal_id_.Value(), - CommandCodeText(command_just_sent_.command_code_).data(), - signal_id.Value()); +void ClassicSignallingManager::OnEchoResponse(SignalId signal_id, + const PacketView& /* packet */) { + if (command_just_sent_.signal_id_ != signal_id || + command_just_sent_.command_code_ != CommandCode::ECHO_REQUEST) { + log::warn("Unexpected response: no pending request. Expected signal id {} type {}, got {}", + command_just_sent_.signal_id_.Value(), + CommandCodeText(command_just_sent_.command_code_).data(), signal_id.Value()); return; } log::info("Echo response received"); @@ -674,38 +692,39 @@ void ClassicSignallingManager::OnEchoResponse( handle_send_next_command(); } -void ClassicSignallingManager::OnInformationRequest(SignalId signal_id, InformationRequestInfoType type) { +void ClassicSignallingManager::OnInformationRequest(SignalId signal_id, + InformationRequestInfoType type) { switch (type) { case InformationRequestInfoType::CONNECTIONLESS_MTU: { auto response = InformationResponseConnectionlessMtuBuilder::Create( - signal_id.Value(), InformationRequestResult::SUCCESS, kDefaultClassicMtu); + signal_id.Value(), InformationRequestResult::SUCCESS, kDefaultClassicMtu); enqueue_buffer_->Enqueue(std::move(response), handler_); break; } case InformationRequestInfoType::EXTENDED_FEATURES_SUPPORTED: { auto response = InformationResponseExtendedFeaturesBuilder::Create( - signal_id.Value(), InformationRequestResult::SUCCESS, 0, 0, 0, 1 /* ERTM */, 0 /* Streaming mode */, - 1 /* FCS */, 0, 1 /* Fixed Channels */, 0, 0, 0 /* COC */); + signal_id.Value(), InformationRequestResult::SUCCESS, 0, 0, 0, 1 /* ERTM */, + 0 /* Streaming mode */, 1 /* FCS */, 0, 1 /* Fixed Channels */, 0, 0, 0 /* COC */); enqueue_buffer_->Enqueue(std::move(response), handler_); break; } case InformationRequestInfoType::FIXED_CHANNELS_SUPPORTED: { auto response = InformationResponseFixedChannelsBuilder::Create( - signal_id.Value(), InformationRequestResult::SUCCESS, fixed_service_manager_->GetSupportedFixedChannelMask()); + signal_id.Value(), InformationRequestResult::SUCCESS, + fixed_service_manager_->GetSupportedFixedChannelMask()); enqueue_buffer_->Enqueue(std::move(response), handler_); break; } } } -void ClassicSignallingManager::OnInformationResponse(SignalId signal_id, const InformationResponseView& response) { +void ClassicSignallingManager::OnInformationResponse(SignalId signal_id, + const InformationResponseView& response) { if (command_just_sent_.signal_id_ != signal_id || command_just_sent_.command_code_ != CommandCode::INFORMATION_REQUEST) { - log::warn( - "Unexpected response: no pending request. Expected signal id {} type {}, got {}", - command_just_sent_.signal_id_.Value(), - CommandCodeText(command_just_sent_.command_code_).data(), - signal_id.Value()); + log::warn("Unexpected response: no pending request. Expected signal id {} type {}, got {}", + command_just_sent_.signal_id_.Value(), + CommandCodeText(command_just_sent_.command_code_).data(), signal_id.Value()); return; } @@ -726,7 +745,8 @@ void ClassicSignallingManager::OnInformationResponse(SignalId signal_id, const I log::warn("Invalid InformationResponseExtendedFeatures received"); return; } - link_->OnRemoteExtendedFeatureReceived(view.GetEnhancedRetransmissionMode(), view.GetFcsOption()); + link_->OnRemoteExtendedFeatureReceived(view.GetEnhancedRetransmissionMode(), + view.GetFcsOption()); // We don't care about other parameters break; } @@ -769,7 +789,8 @@ void ClassicSignallingManager::handle_one_command(ControlView control_packet_vie return; } case CommandCode::CONNECTION_REQUEST: { - ConnectionRequestView connection_request_view = ConnectionRequestView::Create(control_packet_view); + ConnectionRequestView connection_request_view = + ConnectionRequestView::Create(control_packet_view); if (!connection_request_view.IsValid()) { return; } @@ -778,45 +799,56 @@ void ClassicSignallingManager::handle_one_command(ControlView control_packet_vie return; } case CommandCode::CONNECTION_RESPONSE: { - ConnectionResponseView connection_response_view = ConnectionResponseView::Create(control_packet_view); + ConnectionResponseView connection_response_view = + ConnectionResponseView::Create(control_packet_view); if (!connection_response_view.IsValid()) { return; } - OnConnectionResponse(connection_response_view.GetIdentifier(), connection_response_view.GetDestinationCid(), - connection_response_view.GetSourceCid(), connection_response_view.GetResult(), - connection_response_view.GetStatus()); + OnConnectionResponse( + connection_response_view.GetIdentifier(), + connection_response_view.GetDestinationCid(), connection_response_view.GetSourceCid(), + connection_response_view.GetResult(), connection_response_view.GetStatus()); return; } case CommandCode::CONFIGURATION_REQUEST: { - ConfigurationRequestView configuration_request_view = ConfigurationRequestView::Create(control_packet_view); + ConfigurationRequestView configuration_request_view = + ConfigurationRequestView::Create(control_packet_view); if (!configuration_request_view.IsValid()) { return; } - OnConfigurationRequest(configuration_request_view.GetIdentifier(), configuration_request_view.GetDestinationCid(), - configuration_request_view.GetContinuation(), configuration_request_view.GetConfig()); + OnConfigurationRequest(configuration_request_view.GetIdentifier(), + configuration_request_view.GetDestinationCid(), + configuration_request_view.GetContinuation(), + configuration_request_view.GetConfig()); return; } case CommandCode::CONFIGURATION_RESPONSE: { - ConfigurationResponseView configuration_response_view = ConfigurationResponseView::Create(control_packet_view); + ConfigurationResponseView configuration_response_view = + ConfigurationResponseView::Create(control_packet_view); if (!configuration_response_view.IsValid()) { return; } - OnConfigurationResponse(configuration_response_view.GetIdentifier(), configuration_response_view.GetSourceCid(), - configuration_response_view.GetContinuation(), configuration_response_view.GetResult(), + OnConfigurationResponse(configuration_response_view.GetIdentifier(), + configuration_response_view.GetSourceCid(), + configuration_response_view.GetContinuation(), + configuration_response_view.GetResult(), configuration_response_view.GetConfig()); return; } case CommandCode::DISCONNECTION_REQUEST: { - DisconnectionRequestView disconnection_request_view = DisconnectionRequestView::Create(control_packet_view); + DisconnectionRequestView disconnection_request_view = + DisconnectionRequestView::Create(control_packet_view); if (!disconnection_request_view.IsValid()) { return; } - OnDisconnectionRequest(disconnection_request_view.GetIdentifier(), disconnection_request_view.GetDestinationCid(), + OnDisconnectionRequest(disconnection_request_view.GetIdentifier(), + disconnection_request_view.GetDestinationCid(), disconnection_request_view.GetSourceCid()); return; } case CommandCode::DISCONNECTION_RESPONSE: { - DisconnectionResponseView disconnection_response_view = DisconnectionResponseView::Create(control_packet_view); + DisconnectionResponseView disconnection_response_view = + DisconnectionResponseView::Create(control_packet_view); if (!disconnection_response_view.IsValid()) { return; } @@ -842,15 +874,18 @@ void ClassicSignallingManager::handle_one_command(ControlView control_packet_vie return; } case CommandCode::INFORMATION_REQUEST: { - InformationRequestView information_request_view = InformationRequestView::Create(control_packet_view); + InformationRequestView information_request_view = + InformationRequestView::Create(control_packet_view); if (!information_request_view.IsValid()) { return; } - OnInformationRequest(information_request_view.GetIdentifier(), information_request_view.GetInfoType()); + OnInformationRequest(information_request_view.GetIdentifier(), + information_request_view.GetInfoType()); return; } case CommandCode::INFORMATION_RESPONSE: { - InformationResponseView information_response_view = InformationResponseView::Create(control_packet_view); + InformationResponseView information_response_view = + InformationResponseView::Create(control_packet_view); if (!information_response_view.IsValid()) { return; } @@ -858,21 +893,24 @@ void ClassicSignallingManager::handle_one_command(ControlView control_packet_vie return; } case CommandCode::CREDIT_BASED_CONNECTION_REQUEST: { - CreditBasedConnectionRequestView request_view = CreditBasedConnectionRequestView::Create(control_packet_view); + CreditBasedConnectionRequestView request_view = + CreditBasedConnectionRequestView::Create(control_packet_view); if (!request_view.IsValid()) { return; } return; } case CommandCode::CREDIT_BASED_CONNECTION_RESPONSE: { - CreditBasedConnectionResponseView response_view = CreditBasedConnectionResponseView::Create(control_packet_view); + CreditBasedConnectionResponseView response_view = + CreditBasedConnectionResponseView::Create(control_packet_view); if (!response_view.IsValid()) { return; } return; } case CommandCode::CREDIT_BASED_RECONFIGURE_REQUEST: { - CreditBasedReconfigureRequestView request_view = CreditBasedReconfigureRequestView::Create(control_packet_view); + CreditBasedReconfigureRequestView request_view = + CreditBasedReconfigureRequestView::Create(control_packet_view); if (!request_view.IsValid()) { return; } @@ -880,7 +918,7 @@ void ClassicSignallingManager::handle_one_command(ControlView control_packet_vie } case CommandCode::CREDIT_BASED_RECONFIGURE_RESPONSE: { CreditBasedReconfigureResponseView response_view = - CreditBasedReconfigureResponseView::Create(control_packet_view); + CreditBasedReconfigureResponseView::Create(control_packet_view); if (!response_view.IsValid()) { return; } @@ -901,10 +939,12 @@ void ClassicSignallingManager::handle_one_command(ControlView control_packet_vie } } -void ClassicSignallingManager::send_connection_response(SignalId signal_id, Cid remote_cid, Cid local_cid, +void ClassicSignallingManager::send_connection_response(SignalId signal_id, Cid remote_cid, + Cid local_cid, ConnectionResponseResult result, ConnectionResponseStatus status) { - auto builder = ConnectionResponseBuilder::Create(signal_id.Value(), local_cid, remote_cid, result, status); + auto builder = ConnectionResponseBuilder::Create(signal_id.Value(), local_cid, remote_cid, result, + status); enqueue_buffer_->Enqueue(std::move(builder), handler_); } @@ -918,20 +958,23 @@ void ClassicSignallingManager::on_command_timeout() { switch (command_just_sent_.command_code_) { case CommandCode::CONNECTION_REQUEST: { DynamicChannelManager::ConnectionResult connection_result{ - .connection_result_code = DynamicChannelManager::ConnectionResultCode::FAIL_L2CAP_ERROR, - .hci_error = hci::ErrorCode::SUCCESS, - .l2cap_connection_response_result = ConnectionResponseResult::NO_RESOURCES_AVAILABLE, + .connection_result_code = + DynamicChannelManager::ConnectionResultCode::FAIL_L2CAP_ERROR, + .hci_error = hci::ErrorCode::SUCCESS, + .l2cap_connection_response_result = ConnectionResponseResult::NO_RESOURCES_AVAILABLE, }; link_->OnOutgoingConnectionRequestFail(command_just_sent_.source_cid_, connection_result); break; } case CommandCode::CONFIGURATION_REQUEST: { - auto channel = channel_allocator_->FindChannelByRemoteCid(command_just_sent_.destination_cid_); + auto channel = + channel_allocator_->FindChannelByRemoteCid(command_just_sent_.destination_cid_); SendDisconnectionRequest(channel->GetCid(), channel->GetRemoteCid()); return; } case CommandCode::INFORMATION_REQUEST: { - if (command_just_sent_.info_type_ == InformationRequestInfoType::EXTENDED_FEATURES_SUPPORTED) { + if (command_just_sent_.info_type_ == + InformationRequestInfoType::EXTENDED_FEATURES_SUPPORTED) { link_->OnRemoteExtendedFeatureReceived(false, false); } break; @@ -960,35 +1003,40 @@ void ClassicSignallingManager::handle_send_next_command() { case CommandCode::CONNECTION_REQUEST: { auto builder = ConnectionRequestBuilder::Create(signal_id.Value(), psm, source_cid); enqueue_buffer_->Enqueue(std::move(builder), handler_); - alarm_.Schedule(common::BindOnce(&ClassicSignallingManager::on_command_timeout, common::Unretained(this)), + alarm_.Schedule(common::BindOnce(&ClassicSignallingManager::on_command_timeout, + common::Unretained(this)), kTimeout); break; } case CommandCode::CONFIGURATION_REQUEST: { - auto builder = - ConfigurationRequestBuilder::Create(signal_id.Value(), destination_cid, Continuation::END, std::move(config)); + auto builder = ConfigurationRequestBuilder::Create(signal_id.Value(), destination_cid, + Continuation::END, std::move(config)); enqueue_buffer_->Enqueue(std::move(builder), handler_); - alarm_.Schedule(common::BindOnce(&ClassicSignallingManager::on_command_timeout, common::Unretained(this)), + alarm_.Schedule(common::BindOnce(&ClassicSignallingManager::on_command_timeout, + common::Unretained(this)), kTimeout); break; } case CommandCode::DISCONNECTION_REQUEST: { - auto builder = DisconnectionRequestBuilder::Create(signal_id.Value(), destination_cid, source_cid); + auto builder = + DisconnectionRequestBuilder::Create(signal_id.Value(), destination_cid, source_cid); enqueue_buffer_->Enqueue(std::move(builder), handler_); - alarm_.Schedule(common::BindOnce(&ClassicSignallingManager::on_command_timeout, common::Unretained(this)), + alarm_.Schedule(common::BindOnce(&ClassicSignallingManager::on_command_timeout, + common::Unretained(this)), kTimeout); break; } case CommandCode::INFORMATION_REQUEST: { auto builder = InformationRequestBuilder::Create(signal_id.Value(), info_type); enqueue_buffer_->Enqueue(std::move(builder), handler_); - alarm_.Schedule(common::BindOnce(&ClassicSignallingManager::on_command_timeout, common::Unretained(this)), + alarm_.Schedule(common::BindOnce(&ClassicSignallingManager::on_command_timeout, + common::Unretained(this)), kTimeout); break; } default: - log::warn( - "Unsupported command code 0x{:x}", static_cast(command_just_sent_.command_code_)); + log::warn("Unsupported command code 0x{:x}", + static_cast(command_just_sent_.command_code_)); } } diff --git a/system/gd/l2cap/classic/internal/signalling_manager.h b/system/gd/l2cap/classic/internal/signalling_manager.h index 76637ae56b4..aa3f2c77ef9 100644 --- a/system/gd/l2cap/classic/internal/signalling_manager.h +++ b/system/gd/l2cap/classic/internal/signalling_manager.h @@ -53,12 +53,13 @@ struct PendingCommand { class Link; class ClassicSignallingManager { - public: - ClassicSignallingManager(os::Handler* handler, Link* link, - l2cap::internal::DataPipelineManager* data_pipeline_manager, - classic::internal::DynamicChannelServiceManagerImpl* dynamic_service_manager, - l2cap::internal::DynamicChannelAllocator* channel_allocator, - classic::internal::FixedChannelServiceManagerImpl* fixed_service_manager); +public: + ClassicSignallingManager( + os::Handler* handler, Link* link, + l2cap::internal::DataPipelineManager* data_pipeline_manager, + classic::internal::DynamicChannelServiceManagerImpl* dynamic_service_manager, + l2cap::internal::DynamicChannelAllocator* channel_allocator, + classic::internal::FixedChannelServiceManagerImpl* fixed_service_manager); virtual ~ClassicSignallingManager(); @@ -78,8 +79,8 @@ class ClassicSignallingManager { void OnConnectionRequest(SignalId signal_id, Psm psm, Cid remote_cid); - void OnConnectionResponse(SignalId signal_id, Cid remote_cid, Cid cid, ConnectionResponseResult result, - ConnectionResponseStatus status); + void OnConnectionResponse(SignalId signal_id, Cid remote_cid, Cid cid, + ConnectionResponseResult result, ConnectionResponseStatus status); void OnDisconnectionRequest(SignalId signal_id, Cid cid, Cid remote_cid); @@ -89,7 +90,8 @@ class ClassicSignallingManager { std::vector>); void OnConfigurationResponse(SignalId signal_id, Cid cid, Continuation is_continuation, - ConfigurationResponseResult result, std::vector>); + ConfigurationResponseResult result, + std::vector>); void OnEchoRequest(SignalId signal_id, const PacketView& packet); @@ -103,20 +105,22 @@ class ClassicSignallingManager { LINK_KEY, ENCRYPTION, }; - void on_security_result_for_outgoing(SecurityEnforcementType type, Psm psm, Cid local_cid, bool result); + void on_security_result_for_outgoing(SecurityEnforcementType type, Psm psm, Cid local_cid, + bool result); - private: +private: void on_incoming_packet(); void handle_one_command(ControlView control_view); - void send_connection_response(SignalId signal_id, Cid remote_cid, Cid local_cid, ConnectionResponseResult result, - ConnectionResponseStatus status); + void send_connection_response(SignalId signal_id, Cid remote_cid, Cid local_cid, + ConnectionResponseResult result, ConnectionResponseStatus status); void on_command_timeout(); void handle_send_next_command(); void negotiate_configuration(Cid cid, Continuation is_continuation, std::vector>); - void send_configuration_request(Cid remote_cid, std::vector> config); + void send_configuration_request(Cid remote_cid, + std::vector> config); void on_security_result_for_incoming(Psm psm, Cid remote_cid, SignalId signal_id, bool result); os::Handler* handler_; diff --git a/system/gd/l2cap/classic/internal/signalling_manager_test.cc b/system/gd/l2cap/classic/internal/signalling_manager_test.cc index a89b4451e69..f28a2886c87 100644 --- a/system/gd/l2cap/classic/internal/signalling_manager_test.cc +++ b/system/gd/l2cap/classic/internal/signalling_manager_test.cc @@ -16,14 +16,14 @@ #include "l2cap/classic/internal/signalling_manager.h" +#include +#include + #include "l2cap/classic/internal/dynamic_channel_service_manager_impl_mock.h" #include "l2cap/classic/internal/fixed_channel_service_manager_impl_mock.h" #include "l2cap/classic/internal/link_mock.h" #include "l2cap/internal/parameter_provider_mock.h" -#include -#include - using ::testing::_; using ::testing::Return; @@ -34,7 +34,7 @@ namespace internal { namespace { class L2capClassicSignallingManagerTest : public ::testing::Test { - public: +public: static void SyncHandler(os::Handler* handler) { std::promise promise; auto future = promise.get_future(); @@ -42,7 +42,7 @@ class L2capClassicSignallingManagerTest : public ::testing::Test { future.wait_for(std::chrono::milliseconds(3)); } - protected: +protected: void SetUp() override { thread_ = new os::Thread("test_thread", os::Thread::Priority::NORMAL); l2cap_handler_ = new os::Handler(thread_); diff --git a/system/gd/l2cap/classic/l2cap_classic_module.cc b/system/gd/l2cap/classic/l2cap_classic_module.cc index 42442ff3e04..afb0f4ef8f6 100644 --- a/system/gd/l2cap/classic/l2cap_classic_module.cc +++ b/system/gd/l2cap/classic/l2cap_classic_module.cc @@ -37,14 +37,16 @@ namespace bluetooth { namespace l2cap { namespace classic { -const ModuleFactory L2capClassicModule::Factory = ModuleFactory([]() { return new L2capClassicModule(); }); +const ModuleFactory L2capClassicModule::Factory = + ModuleFactory([]() { return new L2capClassicModule(); }); static SecurityEnforcementRejectAllImpl default_security_module_impl_; struct L2capClassicModule::impl { impl(os::Handler* l2cap_handler, hci::AclManager* acl_manager) : l2cap_handler_(l2cap_handler), acl_manager_(acl_manager) { - dynamic_channel_service_manager_impl_.SetSecurityEnforcementInterface(&default_security_module_impl_); + dynamic_channel_service_manager_impl_.SetSecurityEnforcementInterface( + &default_security_module_impl_); dumpsys_helper_ = std::make_unique(link_manager_); } os::Handler* l2cap_handler_; @@ -52,14 +54,16 @@ struct L2capClassicModule::impl { l2cap::internal::ParameterProvider parameter_provider_; internal::FixedChannelServiceManagerImpl fixed_channel_service_manager_impl_{l2cap_handler_}; internal::DynamicChannelServiceManagerImpl dynamic_channel_service_manager_impl_{l2cap_handler_}; - internal::LinkManager link_manager_{l2cap_handler_, acl_manager_, &fixed_channel_service_manager_impl_, + internal::LinkManager link_manager_{l2cap_handler_, acl_manager_, + &fixed_channel_service_manager_impl_, &dynamic_channel_service_manager_impl_, ¶meter_provider_}; std::unique_ptr dumpsys_helper_; struct SecurityInterfaceImpl : public SecurityInterface { SecurityInterfaceImpl(impl* module_impl) : module_impl_(module_impl) {} - void RegisterLinkSecurityInterfaceListener(os::Handler* handler, LinkSecurityInterfaceListener* listener) { + void RegisterLinkSecurityInterfaceListener(os::Handler* handler, + LinkSecurityInterfaceListener* listener) { log::assert_that(!registered_, "assert failed: !registered_"); module_impl_->link_manager_.RegisterLinkSecurityInterfaceListener(handler, listener); registered_ = true; @@ -79,67 +83,65 @@ struct L2capClassicModule::impl { bool registered_ = false; } security_interface_impl_{this}; - void Dump( - std::promise> promise, - flatbuffers::FlatBufferBuilder* fb_builder) const; + void Dump(std::promise> promise, + flatbuffers::FlatBufferBuilder* fb_builder) const; }; L2capClassicModule::L2capClassicModule() {} L2capClassicModule::~L2capClassicModule() {} -void L2capClassicModule::ListDependencies(ModuleList* list) const { - list->add(); -} +void L2capClassicModule::ListDependencies(ModuleList* list) const { list->add(); } void L2capClassicModule::Start() { pimpl_ = std::make_unique(GetHandler(), GetDependency()); } -void L2capClassicModule::Stop() { - pimpl_.reset(); -} +void L2capClassicModule::Stop() { pimpl_.reset(); } -std::string L2capClassicModule::ToString() const { - return "L2cap Classic Module"; -} +std::string L2capClassicModule::ToString() const { return "L2cap Classic Module"; } std::unique_ptr L2capClassicModule::GetFixedChannelManager() { - return std::unique_ptr(new FixedChannelManager(&pimpl_->fixed_channel_service_manager_impl_, - &pimpl_->link_manager_, pimpl_->l2cap_handler_)); + return std::unique_ptr( + new FixedChannelManager(&pimpl_->fixed_channel_service_manager_impl_, + &pimpl_->link_manager_, pimpl_->l2cap_handler_)); } std::unique_ptr L2capClassicModule::GetDynamicChannelManager() { - return std::unique_ptr(new DynamicChannelManager( - &pimpl_->dynamic_channel_service_manager_impl_, &pimpl_->link_manager_, pimpl_->l2cap_handler_)); + return std::unique_ptr( + new DynamicChannelManager(&pimpl_->dynamic_channel_service_manager_impl_, + &pimpl_->link_manager_, pimpl_->l2cap_handler_)); } void L2capClassicModule::InjectSecurityEnforcementInterface( - SecurityEnforcementInterface* security_enforcement_interface) { + SecurityEnforcementInterface* security_enforcement_interface) { if (security_enforcement_interface != nullptr) { - pimpl_->dynamic_channel_service_manager_impl_.SetSecurityEnforcementInterface(security_enforcement_interface); + pimpl_->dynamic_channel_service_manager_impl_.SetSecurityEnforcementInterface( + security_enforcement_interface); } else { - pimpl_->dynamic_channel_service_manager_impl_.SetSecurityEnforcementInterface(&default_security_module_impl_); + pimpl_->dynamic_channel_service_manager_impl_.SetSecurityEnforcementInterface( + &default_security_module_impl_); } } SecurityInterface* L2capClassicModule::GetSecurityInterface( - os::Handler* handler, LinkSecurityInterfaceListener* listener) { + os::Handler* handler, LinkSecurityInterfaceListener* listener) { pimpl_->security_interface_impl_.RegisterLinkSecurityInterfaceListener(handler, listener); return &pimpl_->security_interface_impl_; } -void L2capClassicModule::SetLinkPropertyListener(os::Handler* handler, LinkPropertyListener* listener) { +void L2capClassicModule::SetLinkPropertyListener(os::Handler* handler, + LinkPropertyListener* listener) { pimpl_->link_manager_.RegisterLinkPropertyListener(handler, listener); } void L2capClassicModule::impl::Dump( - std::promise> promise, - flatbuffers::FlatBufferBuilder* fb_builder) const { + std::promise> promise, + flatbuffers::FlatBufferBuilder* fb_builder) const { auto title = fb_builder->CreateString("----- L2cap Classic Dumpsys -----"); std::vector> link_offsets = - dumpsys_helper_->DumpActiveLinks(fb_builder); + dumpsys_helper_->DumpActiveLinks(fb_builder); auto active_links = fb_builder->CreateVector(link_offsets); @@ -151,7 +153,8 @@ void L2capClassicModule::impl::Dump( promise.set_value(dumpsys_data); } -DumpsysDataFinisher L2capClassicModule::GetDumpsysData(flatbuffers::FlatBufferBuilder* fb_builder) const { +DumpsysDataFinisher L2capClassicModule::GetDumpsysData( + flatbuffers::FlatBufferBuilder* fb_builder) const { log::assert_that(fb_builder != nullptr, "assert failed: fb_builder != nullptr"); std::promise> promise; diff --git a/system/gd/l2cap/classic/l2cap_classic_module.h b/system/gd/l2cap/classic/l2cap_classic_module.h index 407de38dc42..3c21625ca79 100644 --- a/system/gd/l2cap/classic/l2cap_classic_module.h +++ b/system/gd/l2cap/classic/l2cap_classic_module.h @@ -34,7 +34,7 @@ namespace l2cap { namespace classic { class L2capClassicModule : public bluetooth::Module { - public: +public: L2capClassicModule(); L2capClassicModule(const L2capClassicModule&) = delete; L2capClassicModule& operator=(const L2capClassicModule&) = delete; @@ -53,19 +53,21 @@ class L2capClassicModule : public bluetooth::Module { static const ModuleFactory Factory; /** - * Only for the classic security module to inject functionality to enforce security level for a connection. When - * classic security module is stopping, inject nullptr. Note: We expect this only to be called during stack startup. - * This is not synchronized. + * Only for the classic security module to inject functionality to enforce security level for a + * connection. When classic security module is stopping, inject nullptr. Note: We expect this only + * to be called during stack startup. This is not synchronized. */ - virtual void InjectSecurityEnforcementInterface(SecurityEnforcementInterface* security_enforcement_interface); + virtual void InjectSecurityEnforcementInterface( + SecurityEnforcementInterface* security_enforcement_interface); /** * Get the interface for Security Module to access link function. - * Security Module needs to register the callback for ACL link connected and disconnected. When connected, either by - * incoming or by outgoing connection request, Security Module receives a LinkSecurityInterface proxy, which can be - * used to access some link functionlities. + * Security Module needs to register the callback for ACL link connected and disconnected. When + * connected, either by incoming or by outgoing connection request, Security Module receives a + * LinkSecurityInterface proxy, which can be used to access some link functionlities. */ - virtual SecurityInterface* GetSecurityInterface(os::Handler* handler, LinkSecurityInterfaceListener* listener); + virtual SecurityInterface* GetSecurityInterface(os::Handler* handler, + LinkSecurityInterfaceListener* listener); friend security::SecurityModule; @@ -75,7 +77,7 @@ class L2capClassicModule : public bluetooth::Module { */ virtual void SetLinkPropertyListener(os::Handler* handler, LinkPropertyListener* listener); - protected: +protected: void ListDependencies(ModuleList* list) const override; void Start() override; @@ -84,9 +86,10 @@ class L2capClassicModule : public bluetooth::Module { std::string ToString() const override; - DumpsysDataFinisher GetDumpsysData(flatbuffers::FlatBufferBuilder* builder) const override; // Module + DumpsysDataFinisher GetDumpsysData( + flatbuffers::FlatBufferBuilder* builder) const override; // Module - private: +private: struct impl; std::unique_ptr pimpl_; }; diff --git a/system/gd/l2cap/classic/l2cap_classic_module_mock.h b/system/gd/l2cap/classic/l2cap_classic_module_mock.h index 125285424e4..d8e894422b5 100644 --- a/system/gd/l2cap/classic/l2cap_classic_module_mock.h +++ b/system/gd/l2cap/classic/l2cap_classic_module_mock.h @@ -15,10 +15,10 @@ */ #pragma once -#include "l2cap/classic/l2cap_classic_module.h" - #include +#include "l2cap/classic/l2cap_classic_module.h" + // Unit test interfaces namespace bluetooth { namespace l2cap { @@ -26,7 +26,7 @@ namespace classic { namespace testing { class MockL2capClassicModule : public L2capClassicModule { - public: +public: MOCK_METHOD(std::unique_ptr, GetFixedChannelManager, (), (override)); MOCK_METHOD(std::unique_ptr, GetDynamicChannelManager, (), (override)); }; diff --git a/system/gd/l2cap/classic/link_property_listener.h b/system/gd/l2cap/classic/link_property_listener.h index 052530f333a..cbee2a3ad71 100644 --- a/system/gd/l2cap/classic/link_property_listener.h +++ b/system/gd/l2cap/classic/link_property_listener.h @@ -29,7 +29,7 @@ namespace classic { * This is the listener interface for link property callbacks. */ class LinkPropertyListener { - public: +public: virtual ~LinkPropertyListener() = default; /** @@ -45,12 +45,10 @@ class LinkPropertyListener { /** * Invoked when received remote version information for a given link */ - virtual void OnReadRemoteVersionInformation( - hci::ErrorCode /* hci_status */, - hci::Address /* remote */, - uint8_t /* lmp_version */, - uint16_t /* manufacturer_name */, - uint16_t /* sub_version */) {} + virtual void OnReadRemoteVersionInformation(hci::ErrorCode /* hci_status */, + hci::Address /* remote */, uint8_t /* lmp_version */, + uint16_t /* manufacturer_name */, + uint16_t /* sub_version */) {} /** * Invoked when received remote features and remote supported features for a @@ -62,17 +60,15 @@ class LinkPropertyListener { * Invoked when received remote features and remote extended features for a * given link */ - virtual void OnReadRemoteExtendedFeatures( - hci::Address /* remote */, - uint8_t /* page_number */, - uint8_t /* max_page_number */, - uint64_t /* features */) {} + virtual void OnReadRemoteExtendedFeatures(hci::Address /* remote */, uint8_t /* page_number */, + uint8_t /* max_page_number */, + uint64_t /* features */) {} /** * Invoked when received role change */ - virtual void OnRoleChange( - hci::ErrorCode /* status */, hci::Address /* remote */, hci::Role /* role */) {} + virtual void OnRoleChange(hci::ErrorCode /* status */, hci::Address /* remote */, + hci::Role /* role */) {} /** * Invoked when received clock offset @@ -82,22 +78,16 @@ class LinkPropertyListener { /** * Invoked when received mode change */ - virtual void OnModeChange( - hci::ErrorCode /* hci_status */, - hci::Address /* remote */, - hci::Mode /* mode */, - uint16_t /* interval */) {} + virtual void OnModeChange(hci::ErrorCode /* hci_status */, hci::Address /* remote */, + hci::Mode /* mode */, uint16_t /* interval */) {} /** * Invoked when received sniff subrating */ - virtual void OnSniffSubrating( - hci::ErrorCode /* hci_status */, - hci::Address /* remote */, - uint16_t /* max_tx_lat */, - uint16_t /* max_rx_lat */, - uint16_t /* min_remote_timeout */, - uint16_t /* min_local_timeout */) {} + virtual void OnSniffSubrating(hci::ErrorCode /* hci_status */, hci::Address /* remote */, + uint16_t /* max_tx_lat */, uint16_t /* max_rx_lat */, + uint16_t /* min_remote_timeout */, + uint16_t /* min_local_timeout */) {} }; } // namespace classic diff --git a/system/gd/l2cap/classic/link_security_interface.h b/system/gd/l2cap/classic/link_security_interface.h index 38b3be0ef1a..edb6da28662 100644 --- a/system/gd/l2cap/classic/link_security_interface.h +++ b/system/gd/l2cap/classic/link_security_interface.h @@ -29,12 +29,13 @@ namespace classic { * This is a proxy for Security Module to unregister itself, or to initiate link connection. */ class SecurityInterface { - public: +public: virtual ~SecurityInterface() = default; /** - * Page a remote device for ACL connection, when Security Module needs it for pairing. When the remote device is - * connected, Security Module will receive a callback through LinkSecurityInterfaceListener. + * Page a remote device for ACL connection, when Security Module needs it for pairing. When the + * remote device is connected, Security Module will receive a callback through + * LinkSecurityInterfaceListener. */ virtual void InitiateConnectionForSecurity(hci::Address remote) = 0; @@ -45,11 +46,11 @@ class SecurityInterface { }; /** - * This is a proxy for Security Module to access some link function. This object is passed to Security Module when a - * link is established. + * This is a proxy for Security Module to access some link function. This object is passed to + * Security Module when a link is established. */ class LinkSecurityInterface { - public: +public: virtual ~LinkSecurityInterface() = default; virtual hci::Address GetRemoteAddress() = 0; @@ -60,8 +61,8 @@ class LinkSecurityInterface { virtual void Hold() = 0; /** - * Release the ACL link connection. This doesn't guarantee link disconnection, if other L2cap services are using the - * link. + * Release the ACL link connection. This doesn't guarantee link disconnection, if other L2cap + * services are using the link. */ virtual void Release() = 0; @@ -82,24 +83,22 @@ class LinkSecurityInterface { virtual uint16_t GetAclHandle() = 0; - virtual hci::Role GetRole() { - return hci::Role::CENTRAL; - } + virtual hci::Role GetRole() { return hci::Role::CENTRAL; } }; class LinkSecurityInterfaceListener { - public: +public: virtual ~LinkSecurityInterfaceListener() = default; /** - * Each time when an ACL link is connected, security manager receives this callback to use LinkSecurityInterface - * functions. + * Each time when an ACL link is connected, security manager receives this callback to use + * LinkSecurityInterface functions. */ virtual void OnLinkConnected(std::unique_ptr) {} /** - * When an ACL link is disconnected, security manager receives this callback. The corresponding LinkSecurityInterface - * is invalidated then. + * When an ACL link is disconnected, security manager receives this callback. The corresponding + * LinkSecurityInterface is invalidated then. * @param remote */ virtual void OnLinkDisconnected(hci::Address /* remote */) {} @@ -107,8 +106,8 @@ class LinkSecurityInterfaceListener { /** * Invoked when AuthenticationComplete event is received for a given link */ - virtual void OnAuthenticationComplete( - hci::ErrorCode /* hci_status */, hci::Address /* remote */) {} + virtual void OnAuthenticationComplete(hci::ErrorCode /* hci_status */, + hci::Address /* remote */) {} /** * Invoked when EncryptionChange event is received for a given link diff --git a/system/gd/l2cap/classic/security_enforcement_interface.h b/system/gd/l2cap/classic/security_enforcement_interface.h index f951760b524..ecb2a243ec2 100644 --- a/system/gd/l2cap/classic/security_enforcement_interface.h +++ b/system/gd/l2cap/classic/security_enforcement_interface.h @@ -28,16 +28,18 @@ namespace classic { * The interface for Security Module to implement. */ class SecurityEnforcementInterface { - public: +public: virtual ~SecurityEnforcementInterface() = default; using ResultCallback = common::ContextualOnceCallback; /** - * Invoked when L2CAP needs to open a channel with given security requirement. When the Security Module satisfies the - * required security level, or cannot satisfy at all, invoke the result_callback. + * Invoked when L2CAP needs to open a channel with given security requirement. When the Security + * Module satisfies the required security level, or cannot satisfy at all, invoke the + * result_callback. */ - virtual void Enforce(hci::AddressWithType remote, SecurityPolicy policy, ResultCallback result_callback) = 0; + virtual void Enforce(hci::AddressWithType remote, SecurityPolicy policy, + ResultCallback result_callback) = 0; }; /** @@ -45,11 +47,9 @@ class SecurityEnforcementInterface { * _SDP_ONLY_NO_SECURITY_WHATSOEVER_PLAINTEXT_TRANSPORT_OK. */ class SecurityEnforcementRejectAllImpl : public SecurityEnforcementInterface { - public: - void Enforce( - hci::AddressWithType /* remote */, - SecurityPolicy policy, - ResultCallback result_callback) override { +public: + void Enforce(hci::AddressWithType /* remote */, SecurityPolicy policy, + ResultCallback result_callback) override { if (policy == SecurityPolicy::_SDP_ONLY_NO_SECURITY_WHATSOEVER_PLAINTEXT_TRANSPORT_OK) { result_callback(true); } else { diff --git a/system/gd/l2cap/dynamic_channel.cc b/system/gd/l2cap/dynamic_channel.cc index a49aed7636e..2266857b322 100644 --- a/system/gd/l2cap/dynamic_channel.cc +++ b/system/gd/l2cap/dynamic_channel.cc @@ -15,19 +15,18 @@ */ #include "l2cap/dynamic_channel.h" + #include "common/bind.h" #include "l2cap/internal/dynamic_channel_impl.h" namespace bluetooth { namespace l2cap { -hci::AddressWithType DynamicChannel::GetDevice() const { - return impl_->GetDevice(); -} +hci::AddressWithType DynamicChannel::GetDevice() const { return impl_->GetDevice(); } void DynamicChannel::RegisterOnCloseCallback(DynamicChannel::OnCloseCallback on_close_callback) { - l2cap_handler_->CallOn( - impl_.get(), &l2cap::internal::DynamicChannelImpl::RegisterOnCloseCallback, std::move(on_close_callback)); + l2cap_handler_->CallOn(impl_.get(), &l2cap::internal::DynamicChannelImpl::RegisterOnCloseCallback, + std::move(on_close_callback)); } void DynamicChannel::Close() { @@ -39,9 +38,7 @@ DynamicChannel::GetQueueUpEnd() const { return impl_->GetQueueUpEnd(); } -Cid DynamicChannel::HACK_GetRemoteCid() { - return impl_->GetRemoteCid(); -} +Cid DynamicChannel::HACK_GetRemoteCid() { return impl_->GetRemoteCid(); } void DynamicChannel::HACK_SetChannelTxPriority(bool high_priority) { return impl_->SetChannelTxPriority(high_priority); diff --git a/system/gd/l2cap/dynamic_channel.h b/system/gd/l2cap/dynamic_channel.h index 281be0d60db..1af21f15436 100644 --- a/system/gd/l2cap/dynamic_channel.h +++ b/system/gd/l2cap/dynamic_channel.h @@ -31,13 +31,14 @@ class DynamicChannelImpl; } // namespace internal /** - * L2CAP Dynamic channel object. User needs to call Close() when user no longer wants to use it. Otherwise the link - * won't be disconnected. + * L2CAP Dynamic channel object. User needs to call Close() when user no longer wants to use it. + * Otherwise the link won't be disconnected. */ class DynamicChannel { - public: +public: // Should only be constructed by modules that have access to LinkManager - DynamicChannel(std::shared_ptr impl, os::Handler* l2cap_handler) + DynamicChannel(std::shared_ptr impl, + os::Handler* l2cap_handler) : impl_(std::move(impl)), l2cap_handler_(l2cap_handler) { log::assert_that(impl_ != nullptr, "assert failed: impl_ != nullptr"); log::assert_that(l2cap_handler_ != nullptr, "assert failed: l2cap_handler_ != nullptr"); @@ -46,9 +47,10 @@ class DynamicChannel { hci::AddressWithType GetDevice() const; /** - * Register close callback. If close callback is registered, when a channel is closed, the channel's resource will - * only be freed after on_close callback is invoked. Otherwise, if no on_close callback is registered, the channel's - * resource will be freed immediately after closing. + * Register close callback. If close callback is registered, when a channel is closed, the + * channel's resource will only be freed after on_close callback is invoked. Otherwise, if no + * on_close callback is registered, the channel's resource will be freed immediately after + * closing. * * @param on_close_callback The callback invoked upon channel closing. */ @@ -56,8 +58,9 @@ class DynamicChannel { void RegisterOnCloseCallback(OnCloseCallback on_close_callback); /** - * Indicate that this Dynamic Channel should be closed. OnCloseCallback will be invoked when channel close is done. - * L2cay layer may terminate this ACL connection to free the resource after channel is closed. + * Indicate that this Dynamic Channel should be closed. OnCloseCallback will be invoked when + * channel close is done. L2cay layer may terminate this ACL connection to free the resource after + * channel is closed. */ void Close(); @@ -68,7 +71,8 @@ class DynamicChannel { * * @return The upper end of a bi-directional queue. */ - common::BidiQueueEnd>* GetQueueUpEnd() const; + common::BidiQueueEnd>* + GetQueueUpEnd() const; Cid HACK_GetRemoteCid(); @@ -78,7 +82,7 @@ class DynamicChannel { */ void HACK_SetChannelTxPriority(bool high_priority); - private: +private: std::shared_ptr impl_; os::Handler* l2cap_handler_; }; diff --git a/system/gd/l2cap/fcs.cc b/system/gd/l2cap/fcs.cc index 3ad78ccb688..d1b6e1584d9 100644 --- a/system/gd/l2cap/fcs.cc +++ b/system/gd/l2cap/fcs.cc @@ -19,42 +19,41 @@ namespace { // Table for optimizing the CRC calculation, which is a bitwise operation. static const uint16_t crctab[256] = { - 0x0000, 0xc0c1, 0xc181, 0x0140, 0xc301, 0x03c0, 0x0280, 0xc241, 0xc601, 0x06c0, 0x0780, 0xc741, 0x0500, 0xc5c1, - 0xc481, 0x0440, 0xcc01, 0x0cc0, 0x0d80, 0xcd41, 0x0f00, 0xcfc1, 0xce81, 0x0e40, 0x0a00, 0xcac1, 0xcb81, 0x0b40, - 0xc901, 0x09c0, 0x0880, 0xc841, 0xd801, 0x18c0, 0x1980, 0xd941, 0x1b00, 0xdbc1, 0xda81, 0x1a40, 0x1e00, 0xdec1, - 0xdf81, 0x1f40, 0xdd01, 0x1dc0, 0x1c80, 0xdc41, 0x1400, 0xd4c1, 0xd581, 0x1540, 0xd701, 0x17c0, 0x1680, 0xd641, - 0xd201, 0x12c0, 0x1380, 0xd341, 0x1100, 0xd1c1, 0xd081, 0x1040, 0xf001, 0x30c0, 0x3180, 0xf141, 0x3300, 0xf3c1, - 0xf281, 0x3240, 0x3600, 0xf6c1, 0xf781, 0x3740, 0xf501, 0x35c0, 0x3480, 0xf441, 0x3c00, 0xfcc1, 0xfd81, 0x3d40, - 0xff01, 0x3fc0, 0x3e80, 0xfe41, 0xfa01, 0x3ac0, 0x3b80, 0xfb41, 0x3900, 0xf9c1, 0xf881, 0x3840, 0x2800, 0xe8c1, - 0xe981, 0x2940, 0xeb01, 0x2bc0, 0x2a80, 0xea41, 0xee01, 0x2ec0, 0x2f80, 0xef41, 0x2d00, 0xedc1, 0xec81, 0x2c40, - 0xe401, 0x24c0, 0x2580, 0xe541, 0x2700, 0xe7c1, 0xe681, 0x2640, 0x2200, 0xe2c1, 0xe381, 0x2340, 0xe101, 0x21c0, - 0x2080, 0xe041, 0xa001, 0x60c0, 0x6180, 0xa141, 0x6300, 0xa3c1, 0xa281, 0x6240, 0x6600, 0xa6c1, 0xa781, 0x6740, - 0xa501, 0x65c0, 0x6480, 0xa441, 0x6c00, 0xacc1, 0xad81, 0x6d40, 0xaf01, 0x6fc0, 0x6e80, 0xae41, 0xaa01, 0x6ac0, - 0x6b80, 0xab41, 0x6900, 0xa9c1, 0xa881, 0x6840, 0x7800, 0xb8c1, 0xb981, 0x7940, 0xbb01, 0x7bc0, 0x7a80, 0xba41, - 0xbe01, 0x7ec0, 0x7f80, 0xbf41, 0x7d00, 0xbdc1, 0xbc81, 0x7c40, 0xb401, 0x74c0, 0x7580, 0xb541, 0x7700, 0xb7c1, - 0xb681, 0x7640, 0x7200, 0xb2c1, 0xb381, 0x7340, 0xb101, 0x71c0, 0x7080, 0xb041, 0x5000, 0x90c1, 0x9181, 0x5140, - 0x9301, 0x53c0, 0x5280, 0x9241, 0x9601, 0x56c0, 0x5780, 0x9741, 0x5500, 0x95c1, 0x9481, 0x5440, 0x9c01, 0x5cc0, - 0x5d80, 0x9d41, 0x5f00, 0x9fc1, 0x9e81, 0x5e40, 0x5a00, 0x9ac1, 0x9b81, 0x5b40, 0x9901, 0x59c0, 0x5880, 0x9841, - 0x8801, 0x48c0, 0x4980, 0x8941, 0x4b00, 0x8bc1, 0x8a81, 0x4a40, 0x4e00, 0x8ec1, 0x8f81, 0x4f40, 0x8d01, 0x4dc0, - 0x4c80, 0x8c41, 0x4400, 0x84c1, 0x8581, 0x4540, 0x8701, 0x47c0, 0x4680, 0x8641, 0x8201, 0x42c0, 0x4380, 0x8341, - 0x4100, 0x81c1, 0x8081, 0x4040, + 0x0000, 0xc0c1, 0xc181, 0x0140, 0xc301, 0x03c0, 0x0280, 0xc241, 0xc601, 0x06c0, 0x0780, + 0xc741, 0x0500, 0xc5c1, 0xc481, 0x0440, 0xcc01, 0x0cc0, 0x0d80, 0xcd41, 0x0f00, 0xcfc1, + 0xce81, 0x0e40, 0x0a00, 0xcac1, 0xcb81, 0x0b40, 0xc901, 0x09c0, 0x0880, 0xc841, 0xd801, + 0x18c0, 0x1980, 0xd941, 0x1b00, 0xdbc1, 0xda81, 0x1a40, 0x1e00, 0xdec1, 0xdf81, 0x1f40, + 0xdd01, 0x1dc0, 0x1c80, 0xdc41, 0x1400, 0xd4c1, 0xd581, 0x1540, 0xd701, 0x17c0, 0x1680, + 0xd641, 0xd201, 0x12c0, 0x1380, 0xd341, 0x1100, 0xd1c1, 0xd081, 0x1040, 0xf001, 0x30c0, + 0x3180, 0xf141, 0x3300, 0xf3c1, 0xf281, 0x3240, 0x3600, 0xf6c1, 0xf781, 0x3740, 0xf501, + 0x35c0, 0x3480, 0xf441, 0x3c00, 0xfcc1, 0xfd81, 0x3d40, 0xff01, 0x3fc0, 0x3e80, 0xfe41, + 0xfa01, 0x3ac0, 0x3b80, 0xfb41, 0x3900, 0xf9c1, 0xf881, 0x3840, 0x2800, 0xe8c1, 0xe981, + 0x2940, 0xeb01, 0x2bc0, 0x2a80, 0xea41, 0xee01, 0x2ec0, 0x2f80, 0xef41, 0x2d00, 0xedc1, + 0xec81, 0x2c40, 0xe401, 0x24c0, 0x2580, 0xe541, 0x2700, 0xe7c1, 0xe681, 0x2640, 0x2200, + 0xe2c1, 0xe381, 0x2340, 0xe101, 0x21c0, 0x2080, 0xe041, 0xa001, 0x60c0, 0x6180, 0xa141, + 0x6300, 0xa3c1, 0xa281, 0x6240, 0x6600, 0xa6c1, 0xa781, 0x6740, 0xa501, 0x65c0, 0x6480, + 0xa441, 0x6c00, 0xacc1, 0xad81, 0x6d40, 0xaf01, 0x6fc0, 0x6e80, 0xae41, 0xaa01, 0x6ac0, + 0x6b80, 0xab41, 0x6900, 0xa9c1, 0xa881, 0x6840, 0x7800, 0xb8c1, 0xb981, 0x7940, 0xbb01, + 0x7bc0, 0x7a80, 0xba41, 0xbe01, 0x7ec0, 0x7f80, 0xbf41, 0x7d00, 0xbdc1, 0xbc81, 0x7c40, + 0xb401, 0x74c0, 0x7580, 0xb541, 0x7700, 0xb7c1, 0xb681, 0x7640, 0x7200, 0xb2c1, 0xb381, + 0x7340, 0xb101, 0x71c0, 0x7080, 0xb041, 0x5000, 0x90c1, 0x9181, 0x5140, 0x9301, 0x53c0, + 0x5280, 0x9241, 0x9601, 0x56c0, 0x5780, 0x9741, 0x5500, 0x95c1, 0x9481, 0x5440, 0x9c01, + 0x5cc0, 0x5d80, 0x9d41, 0x5f00, 0x9fc1, 0x9e81, 0x5e40, 0x5a00, 0x9ac1, 0x9b81, 0x5b40, + 0x9901, 0x59c0, 0x5880, 0x9841, 0x8801, 0x48c0, 0x4980, 0x8941, 0x4b00, 0x8bc1, 0x8a81, + 0x4a40, 0x4e00, 0x8ec1, 0x8f81, 0x4f40, 0x8d01, 0x4dc0, 0x4c80, 0x8c41, 0x4400, 0x84c1, + 0x8581, 0x4540, 0x8701, 0x47c0, 0x4680, 0x8641, 0x8201, 0x42c0, 0x4380, 0x8341, 0x4100, + 0x81c1, 0x8081, 0x4040, }; } // namespace namespace bluetooth { namespace l2cap { -void Fcs::Initialize() { - crc = 0; -} +void Fcs::Initialize() { crc = 0; } -void Fcs::AddByte(uint8_t byte) { - crc = ((crc >> 8) & 0x00ff) ^ crctab[(crc & 0x00ff) ^ byte]; -} +void Fcs::AddByte(uint8_t byte) { crc = ((crc >> 8) & 0x00ff) ^ crctab[(crc & 0x00ff) ^ byte]; } -uint16_t Fcs::GetChecksum() const { - return crc; -} +uint16_t Fcs::GetChecksum() const { return crc; } } // namespace l2cap } // namespace bluetooth diff --git a/system/gd/l2cap/fcs.h b/system/gd/l2cap/fcs.h index 127fa9df21d..e1f6c50a854 100644 --- a/system/gd/l2cap/fcs.h +++ b/system/gd/l2cap/fcs.h @@ -23,14 +23,14 @@ namespace l2cap { // Frame Check Sequence from the L2CAP spec. class Fcs { - public: +public: void Initialize(); void AddByte(uint8_t byte); uint16_t GetChecksum() const; - private: +private: uint16_t crc; }; diff --git a/system/gd/l2cap/fuzz/channel_fuzz_controller.cc b/system/gd/l2cap/fuzz/channel_fuzz_controller.cc index 41738ccbf4e..cf83082f013 100644 --- a/system/gd/l2cap/fuzz/channel_fuzz_controller.cc +++ b/system/gd/l2cap/fuzz/channel_fuzz_controller.cc @@ -23,12 +23,14 @@ using l2cap::classic::internal::FixedChannelImpl; using l2cap::internal::DynamicChannelImpl; using os::Handler; -ChannelFuzzController::ChannelFuzzController(Handler* l2cap_handler, std::shared_ptr chan) { +ChannelFuzzController::ChannelFuzzController(Handler* l2cap_handler, + std::shared_ptr chan) { EnqueueType* queue = reinterpret_cast(chan->GetQueueUpEnd()); channelInject_ = std::make_shared(queue, l2cap_handler); } -ChannelFuzzController::ChannelFuzzController(Handler* l2cap_handler, std::shared_ptr chan) { +ChannelFuzzController::ChannelFuzzController(Handler* l2cap_handler, + std::shared_ptr chan) { EnqueueType* queue = reinterpret_cast(chan->GetQueueUpEnd()); channelInject_ = std::make_shared(queue, l2cap_handler); } diff --git a/system/gd/l2cap/fuzz/channel_fuzz_controller.h b/system/gd/l2cap/fuzz/channel_fuzz_controller.h index a6128204d35..7336dc941a3 100644 --- a/system/gd/l2cap/fuzz/channel_fuzz_controller.h +++ b/system/gd/l2cap/fuzz/channel_fuzz_controller.h @@ -34,16 +34,18 @@ typedef os::IQueueEnqueue> EnqueueType typedef os::fuzz::FuzzInjectQueue> ChannelFuzzQueueType; class ChannelFuzzController { - public: - ChannelFuzzController(os::Handler* l2cap_handler, std::shared_ptr chan); +public: + ChannelFuzzController(os::Handler* l2cap_handler, + std::shared_ptr chan); - ChannelFuzzController(os::Handler* l2cap_handler, std::shared_ptr chan); + ChannelFuzzController(os::Handler* l2cap_handler, + std::shared_ptr chan); void injectPacketData(std::vector data); void injectFrame(std::vector data); - private: +private: std::shared_ptr channelInject_; }; } // namespace bluetooth diff --git a/system/gd/l2cap/fuzz/fuzz_dynamic_channel_manager.h b/system/gd/l2cap/fuzz/fuzz_dynamic_channel_manager.h index ce9c6bd8b67..e8651d3783f 100644 --- a/system/gd/l2cap/fuzz/fuzz_dynamic_channel_manager.h +++ b/system/gd/l2cap/fuzz/fuzz_dynamic_channel_manager.h @@ -29,24 +29,26 @@ namespace bluetooth { namespace shim { namespace { class FuzzDynamicChannelManager : public l2cap::classic::DynamicChannelManager { - public: +public: void ConnectChannel( - hci::Address device, - l2cap::classic::DynamicChannelConfigurationOption configuration_option, - l2cap::Psm psm, - l2cap::classic::DynamicChannelManager::OnConnectionOpenCallback on_open_callback, - l2cap::classic::DynamicChannelManager::OnConnectionFailureCallback on_fail_callback) override { - impl_.ConnectChannel(device, configuration_option, psm, std::move(on_open_callback), std::move(on_fail_callback)); + hci::Address device, + l2cap::classic::DynamicChannelConfigurationOption configuration_option, l2cap::Psm psm, + l2cap::classic::DynamicChannelManager::OnConnectionOpenCallback on_open_callback, + l2cap::classic::DynamicChannelManager::OnConnectionFailureCallback on_fail_callback) + override { + impl_.ConnectChannel(device, configuration_option, psm, std::move(on_open_callback), + std::move(on_fail_callback)); } - void RegisterService( - l2cap::Psm psm, - l2cap::classic::DynamicChannelConfigurationOption configuration_option, - const l2cap::classic::SecurityPolicy& security_policy, - l2cap::classic::DynamicChannelManager::OnRegistrationCompleteCallback on_registration_complete, - l2cap::classic::DynamicChannelManager::OnConnectionOpenCallback on_open_callback) override { - impl_.RegisterService( - psm, configuration_option, security_policy, std::move(on_registration_complete), std::move(on_open_callback)); + void RegisterService(l2cap::Psm psm, + l2cap::classic::DynamicChannelConfigurationOption configuration_option, + const l2cap::classic::SecurityPolicy& security_policy, + l2cap::classic::DynamicChannelManager::OnRegistrationCompleteCallback + on_registration_complete, + l2cap::classic::DynamicChannelManager::OnConnectionOpenCallback + on_open_callback) override { + impl_.RegisterService(psm, configuration_option, security_policy, + std::move(on_registration_complete), std::move(on_open_callback)); } FuzzDynamicChannelManager(FuzzDynamicChannelManagerImpl& impl) : impl_(impl) {} FuzzDynamicChannelManagerImpl& impl_; diff --git a/system/gd/l2cap/fuzz/fuzz_dynamic_channel_manager_impl.h b/system/gd/l2cap/fuzz/fuzz_dynamic_channel_manager_impl.h index bf8adb7f026..b64606f4f38 100644 --- a/system/gd/l2cap/fuzz/fuzz_dynamic_channel_manager_impl.h +++ b/system/gd/l2cap/fuzz/fuzz_dynamic_channel_manager_impl.h @@ -31,13 +31,12 @@ namespace bluetooth { namespace shim { namespace { class FuzzDynamicChannelManagerImpl { - public: +public: void ConnectChannel( - hci::Address device, - l2cap::classic::DynamicChannelConfigurationOption configuration_option, - l2cap::Psm, - l2cap::classic::DynamicChannelManager::OnConnectionOpenCallback on_open_callback, - l2cap::classic::DynamicChannelManager::OnConnectionFailureCallback on_fail_callback) { + hci::Address device, + l2cap::classic::DynamicChannelConfigurationOption configuration_option, l2cap::Psm, + l2cap::classic::DynamicChannelManager::OnConnectionOpenCallback on_open_callback, + l2cap::classic::DynamicChannelManager::OnConnectionFailureCallback on_fail_callback) { connections_++; on_open_callback_ = std::move(on_open_callback); on_fail_callback_ = std::move(on_fail_callback); @@ -47,11 +46,11 @@ class FuzzDynamicChannelManagerImpl { int connections_{0}; void RegisterService( - l2cap::Psm, - l2cap::classic::DynamicChannelConfigurationOption, - const l2cap::classic::SecurityPolicy&, - l2cap::classic::DynamicChannelManager::OnRegistrationCompleteCallback on_registration_complete, - l2cap::classic::DynamicChannelManager::OnConnectionOpenCallback on_open_callback) { + l2cap::Psm, l2cap::classic::DynamicChannelConfigurationOption, + const l2cap::classic::SecurityPolicy&, + l2cap::classic::DynamicChannelManager::OnRegistrationCompleteCallback + on_registration_complete, + l2cap::classic::DynamicChannelManager::OnConnectionOpenCallback on_open_callback) { services_++; on_registration_complete_ = std::move(on_registration_complete); on_open_callback_ = std::move(on_open_callback); @@ -60,30 +59,28 @@ class FuzzDynamicChannelManagerImpl { } int services_{0}; - void SetConnectionFuture() { - connected_promise_ = std::promise(); - } + void SetConnectionFuture() { connected_promise_ = std::promise(); } void WaitConnectionFuture() { connected_future_ = connected_promise_.get_future(); connected_future_.wait(); } - void SetRegistrationFuture() { - register_promise_ = std::promise(); - } + void SetRegistrationFuture() { register_promise_ = std::promise(); } void WaitRegistrationFuture() { register_future_ = register_promise_.get_future(); register_future_.wait(); } - void SetConnectionOnFail(l2cap::classic::DynamicChannelManager::ConnectionResult result, std::promise promise) { + void SetConnectionOnFail(l2cap::classic::DynamicChannelManager::ConnectionResult result, + std::promise promise) { std::move(on_fail_callback_)(result); promise.set_value(); } - void SetConnectionOnOpen(std::unique_ptr channel, std::promise promise) { + void SetConnectionOnOpen(std::unique_ptr channel, + std::promise promise) { std::move(on_open_callback_)(std::move(channel)); promise.set_value(); } @@ -95,7 +92,7 @@ class FuzzDynamicChannelManagerImpl { FuzzDynamicChannelManagerImpl() = default; ~FuzzDynamicChannelManagerImpl() = default; - private: +private: std::promise connected_promise_; std::future connected_future_; diff --git a/system/gd/l2cap/fuzz/fuzz_l2cap.cc b/system/gd/l2cap/fuzz/fuzz_l2cap.cc index caebe0cce87..354e15bfa91 100644 --- a/system/gd/l2cap/fuzz/fuzz_l2cap.cc +++ b/system/gd/l2cap/fuzz/fuzz_l2cap.cc @@ -18,10 +18,10 @@ #include #include -#include "l2cap/psm.h" -#include "os/log.h" #include "channel_fuzz_controller.h" +#include "l2cap/psm.h" +#include "os/log.h" #include "shim_l2cap.h" namespace bluetooth { @@ -36,14 +36,14 @@ using l2cap::classic::internal::Link; using shim::ShimL2capFuzz; class FakeCommandInterface : public hci::CommandInterface { - public: +public: virtual void EnqueueCommand( - std::unique_ptr command, - common::ContextualOnceCallback on_complete) {} + std::unique_ptr command, + common::ContextualOnceCallback on_complete) {} virtual void EnqueueCommand( - std::unique_ptr command, - common::ContextualOnceCallback on_status) {} + std::unique_ptr command, + common::ContextualOnceCallback on_status) {} } fake_command_interface; extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { @@ -58,12 +58,13 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { } Address myAddress; myAddress.FromOctets(addressVals.data()); - hci::AddressWithType addressWithType = hci::AddressWithType(myAddress, AddressType::PUBLIC_DEVICE_ADDRESS); + hci::AddressWithType addressWithType = + hci::AddressWithType(myAddress, AddressType::PUBLIC_DEVICE_ADDRESS); // Associate a ClassicAclConnection so that we can grab a link. auto throwaway_queue = std::make_shared(10); l2shim.link_manager->OnConnectSuccess(std::unique_ptr( - new ClassicAclConnection(throwaway_queue, &fake_command_interface, 0, myAddress))); + new ClassicAclConnection(throwaway_queue, &fake_command_interface, 0, myAddress))); Link* link = l2shim.link_manager->GetLink(myAddress); // 0x0001-0x007F Fixed, 0x0080-0x00FF Dynamic @@ -77,11 +78,13 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { // Fixed channels must be acquired. auto fixedChannel = link->AllocateFixedChannel(fixedCid); - fixedChannel->RegisterOnCloseCallback(l2shim.handler_.get(), common::BindOnce([](hci::ErrorCode) {})); + fixedChannel->RegisterOnCloseCallback(l2shim.handler_.get(), + common::BindOnce([](hci::ErrorCode) {})); fixedChannel->Acquire(); ChannelFuzzController fixedChannelController(l2shim.handler_.get(), fixedChannel); // Generate a valid dynamic channel ID - Cid dynamicCid = fdp.ConsumeIntegralInRange(l2cap::kFirstDynamicChannel, l2cap::kLastDynamicChannel); + Cid dynamicCid = fdp.ConsumeIntegralInRange(l2cap::kFirstDynamicChannel, + l2cap::kLastDynamicChannel); auto dynamicChannel = link->AllocateDynamicChannel(dynamicPsm, dynamicCid); ChannelFuzzController dynamicChannelController(l2shim.handler_.get(), dynamicChannel); @@ -90,8 +93,8 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { bool dynamic = fdp.ConsumeBool(); // Consume at most UINT16_MAX or remaining_bytes, whatever is smaller. - uint16_t packetSize = - static_cast(std::min(static_cast(fdp.ConsumeIntegral()), fdp.remaining_bytes())); + uint16_t packetSize = static_cast( + std::min(static_cast(fdp.ConsumeIntegral()), fdp.remaining_bytes())); std::vector data = fdp.ConsumeBytes(packetSize); if (dynamic) { dynamicChannelController.injectFrame(data); diff --git a/system/gd/l2cap/fuzz/fuzz_l2cap_classic_module.h b/system/gd/l2cap/fuzz/fuzz_l2cap_classic_module.h index c0fe7468c03..4a8df5b54d3 100644 --- a/system/gd/l2cap/fuzz/fuzz_l2cap_classic_module.h +++ b/system/gd/l2cap/fuzz/fuzz_l2cap_classic_module.h @@ -20,17 +20,16 @@ #include -#include "l2cap/classic/dynamic_channel_manager.h" -#include "l2cap/classic/l2cap_classic_module.h" - #include "fuzz_dynamic_channel_manager.h" #include "fuzz_dynamic_channel_manager_impl.h" +#include "l2cap/classic/dynamic_channel_manager.h" +#include "l2cap/classic/l2cap_classic_module.h" namespace bluetooth { namespace shim { namespace { class FuzzL2capClassicModule : public l2cap::classic::L2capClassicModule { - public: +public: std::unique_ptr GetDynamicChannelManager() override { return std::make_unique(*impl_); } @@ -42,13 +41,9 @@ class FuzzL2capClassicModule : public l2cap::classic::L2capClassicModule { std::unique_ptr impl_; }; -void FuzzL2capClassicModule::Start() { - impl_ = std::make_unique(); -} +void FuzzL2capClassicModule::Start() { impl_ = std::make_unique(); } -void FuzzL2capClassicModule::Stop() { - impl_.reset(); -} +void FuzzL2capClassicModule::Stop() { impl_.reset(); } } // namespace } // namespace shim } // namespace bluetooth diff --git a/system/gd/l2cap/fuzz/shim_l2cap.h b/system/gd/l2cap/fuzz/shim_l2cap.h index 2bd27d5c542..2636fcd0078 100644 --- a/system/gd/l2cap/fuzz/shim_l2cap.h +++ b/system/gd/l2cap/fuzz/shim_l2cap.h @@ -37,17 +37,14 @@ namespace bluetooth { namespace shim { namespace { class ShimL2capFuzz { - public: +public: uint16_t CreateConnection(uint16_t psm, hci::Address device_address) { std::promise promise; auto future = promise.get_future(); fuzz_l2cap_classic_module_->GetDynamicChannelManager()->ConnectChannel( - device_address, - {}, - psm, - handler_->BindOn(this, &ShimL2capFuzz::OnConnectionComplete), - handler_->BindOnceOn(this, &ShimL2capFuzz::OnConnectionFail)); + device_address, {}, psm, handler_->BindOn(this, &ShimL2capFuzz::OnConnectionComplete), + handler_->BindOnceOn(this, &ShimL2capFuzz::OnConnectionFail)); return future.get(); } @@ -57,9 +54,11 @@ class ShimL2capFuzz { void OnConnectionFail(l2cap::classic::DynamicChannelManager::ConnectionResult result) {} ShimL2capFuzz(FuzzedDataProvider* fdp) { - hci::fuzz::FuzzHciLayer* fuzzHci = fake_registry_.Inject(&hci::HciLayer::Factory); + hci::fuzz::FuzzHciLayer* fuzzHci = + fake_registry_.Inject(&hci::HciLayer::Factory); fuzz_l2cap_classic_module_ = new FuzzL2capClassicModule(); - fake_registry_.InjectTestModule(&l2cap::classic::L2capClassicModule::Factory, fuzz_l2cap_classic_module_); + fake_registry_.InjectTestModule(&l2cap::classic::L2capClassicModule::Factory, + fuzz_l2cap_classic_module_); fake_registry_.Start(); // The autoreply is needed to prevent it from hanging. @@ -69,22 +68,22 @@ class ShimL2capFuzz { // Create the LinkManager handler_ = std::unique_ptr(new os::Handler(&thread_)); - dynamic_channel_impl = std::unique_ptr( - new l2cap::classic::internal::DynamicChannelServiceManagerImpl(handler_.get())); + dynamic_channel_impl = + std::unique_ptr( + new l2cap::classic::internal::DynamicChannelServiceManagerImpl(handler_.get())); fixed_channel_impl = std::unique_ptr( - new l2cap::classic::internal::FixedChannelServiceManagerImpl(handler_.get())); - parameter_provider = std::unique_ptr(new l2cap::internal::ParameterProvider()); - link_manager = std::unique_ptr(new l2cap::classic::internal::LinkManager( - handler_.get(), acl_manager_, fixed_channel_impl.get(), dynamic_channel_impl.get(), parameter_provider.get())); + new l2cap::classic::internal::FixedChannelServiceManagerImpl(handler_.get())); + parameter_provider = std::unique_ptr( + new l2cap::internal::ParameterProvider()); + link_manager = std::unique_ptr( + new l2cap::classic::internal::LinkManager( + handler_.get(), acl_manager_, fixed_channel_impl.get(), + dynamic_channel_impl.get(), parameter_provider.get())); } - ~ShimL2capFuzz() { - handler_->Clear(); - } + ~ShimL2capFuzz() { handler_->Clear(); } - void stopRegistry() { - fake_registry_.WaitForIdleAndStopAll(); - } + void stopRegistry() { fake_registry_.WaitForIdleAndStopAll(); } std::promise connection_complete_promise_; @@ -97,7 +96,7 @@ class ShimL2capFuzz { std::unique_ptr link_manager; std::unique_ptr parameter_provider; - private: +private: FuzzTestModuleRegistry fake_registry_; os::Thread& thread_ = fake_registry_.GetTestThread(); }; diff --git a/system/gd/l2cap/internal/basic_mode_channel_data_controller.cc b/system/gd/l2cap/internal/basic_mode_channel_data_controller.cc index 922607a9f8a..a8a4b358191 100644 --- a/system/gd/l2cap/internal/basic_mode_channel_data_controller.cc +++ b/system/gd/l2cap/internal/basic_mode_channel_data_controller.cc @@ -24,14 +24,16 @@ namespace bluetooth { namespace l2cap { namespace internal { -BasicModeDataController::BasicModeDataController(Cid cid, Cid remote_cid, UpperQueueDownEnd* channel_queue_end, +BasicModeDataController::BasicModeDataController(Cid cid, Cid remote_cid, + UpperQueueDownEnd* channel_queue_end, os::Handler* handler, Scheduler* scheduler) - : cid_(cid), remote_cid_(remote_cid), enqueue_buffer_(channel_queue_end), handler_(handler), scheduler_(scheduler) { -} + : cid_(cid), + remote_cid_(remote_cid), + enqueue_buffer_(channel_queue_end), + handler_(handler), + scheduler_(scheduler) {} -BasicModeDataController::~BasicModeDataController() { - enqueue_buffer_.Clear(); -} +BasicModeDataController::~BasicModeDataController() { enqueue_buffer_.Clear(); } void BasicModeDataController::OnSdu(std::unique_ptr sdu) { auto l2cap_information = BasicFrameBuilder::Create(remote_cid_, std::move(sdu)); @@ -45,7 +47,8 @@ void BasicModeDataController::OnPdu(packet::PacketView pdu) { log::warn("Received invalid frame"); return; } - enqueue_buffer_.Enqueue(std::make_unique>(basic_frame_view.GetPayload()), handler_); + enqueue_buffer_.Enqueue( + std::make_unique>(basic_frame_view.GetPayload()), handler_); } std::unique_ptr BasicModeDataController::GetNextPacket() { diff --git a/system/gd/l2cap/internal/basic_mode_channel_data_controller.h b/system/gd/l2cap/internal/basic_mode_channel_data_controller.h index 66c171c0d1c..a8a730654c9 100644 --- a/system/gd/l2cap/internal/basic_mode_channel_data_controller.h +++ b/system/gd/l2cap/internal/basic_mode_channel_data_controller.h @@ -37,12 +37,12 @@ namespace l2cap { namespace internal { class BasicModeDataController : public DataController { - public: +public: using UpperEnqueue = packet::PacketView; using UpperDequeue = packet::BasePacketBuilder; using UpperQueueDownEnd = common::BidiQueueEnd; - BasicModeDataController(Cid cid, Cid remote_cid, UpperQueueDownEnd* channel_queue_end, os::Handler* handler, - Scheduler* scheduler); + BasicModeDataController(Cid cid, Cid remote_cid, UpperQueueDownEnd* channel_queue_end, + os::Handler* handler, Scheduler* scheduler); ~BasicModeDataController(); @@ -54,9 +54,9 @@ class BasicModeDataController : public DataController { void EnableFcs(bool /* enabled */) override {} void SetRetransmissionAndFlowControlOptions( - const RetransmissionAndFlowControlConfigurationOption& /* option */) override {} + const RetransmissionAndFlowControlConfigurationOption& /* option */) override {} - private: +private: Cid cid_; Cid remote_cid_; os::EnqueueBuffer enqueue_buffer_; diff --git a/system/gd/l2cap/internal/basic_mode_channel_data_controller_test.cc b/system/gd/l2cap/internal/basic_mode_channel_data_controller_test.cc index c4cc56d74df..cc7082105ac 100644 --- a/system/gd/l2cap/internal/basic_mode_channel_data_controller_test.cc +++ b/system/gd/l2cap/internal/basic_mode_channel_data_controller_test.cc @@ -49,7 +49,7 @@ void sync_handler(os::Handler* handler) { } class BasicModeDataControllerTest : public ::testing::Test { - protected: +protected: void SetUp() override { thread_ = new os::Thread("test_thread", os::Thread::Priority::NORMAL); user_handler_ = new os::Handler(thread_); diff --git a/system/gd/l2cap/internal/channel_impl.h b/system/gd/l2cap/internal/channel_impl.h index 427a15f5e27..04503b1e1b7 100644 --- a/system/gd/l2cap/internal/channel_impl.h +++ b/system/gd/l2cap/internal/channel_impl.h @@ -29,19 +29,21 @@ class Sender; * Common interface for internal channel implementation */ class ChannelImpl { - public: +public: virtual ~ChannelImpl() = default; /** * Return the queue end for upper layer (L2CAP user) */ - virtual common::BidiQueueEnd>* + virtual common::BidiQueueEnd>* GetQueueUpEnd() = 0; /** * Return the queue end for lower layer (sender and receiver) */ - virtual common::BidiQueueEnd, packet::BasePacketBuilder>* + virtual common::BidiQueueEnd, + packet::BasePacketBuilder>* GetQueueDownEnd() = 0; virtual Cid GetCid() const = 0; diff --git a/system/gd/l2cap/internal/channel_impl_mock.h b/system/gd/l2cap/internal/channel_impl_mock.h index 443048761f1..67e66ad1ab3 100644 --- a/system/gd/l2cap/internal/channel_impl_mock.h +++ b/system/gd/l2cap/internal/channel_impl_mock.h @@ -16,10 +16,10 @@ #pragma once -#include "l2cap/internal/channel_impl.h" - #include +#include "l2cap/internal/channel_impl.h" + // Unit test interfaces namespace bluetooth { namespace l2cap { @@ -27,10 +27,12 @@ namespace internal { namespace testing { class MockChannelImpl : public ChannelImpl { - public: - MOCK_METHOD((common::BidiQueueEnd>*), +public: + MOCK_METHOD((common::BidiQueueEnd>*), GetQueueUpEnd, (), (override)); - MOCK_METHOD((common::BidiQueueEnd, packet::BasePacketBuilder>*), + MOCK_METHOD((common::BidiQueueEnd, + packet::BasePacketBuilder>*), GetQueueDownEnd, (), (override)); MOCK_METHOD(Cid, GetCid, (), (const, override)); MOCK_METHOD(Cid, GetRemoteCid, (), (const, override)); diff --git a/system/gd/l2cap/internal/data_controller.h b/system/gd/l2cap/internal/data_controller.h index bc7c2e57cae..8efb57cc161 100644 --- a/system/gd/l2cap/internal/data_controller.h +++ b/system/gd/l2cap/internal/data_controller.h @@ -27,7 +27,7 @@ namespace l2cap { namespace internal { class DataController { - public: +public: virtual ~DataController() = default; // SDU -> PDUs and notify Scheduler @@ -42,10 +42,10 @@ class DataController { // Set FCS mode. This only applies to some modes (ERTM). virtual void EnableFcs(bool enabled) = 0; - // Set retransmission and flow control. Ignore the mode option because each DataController only handles one mode. - // This only applies to some modes (ERTM). + // Set retransmission and flow control. Ignore the mode option because each DataController only + // handles one mode. This only applies to some modes (ERTM). virtual void SetRetransmissionAndFlowControlOptions( - const RetransmissionAndFlowControlConfigurationOption& option) = 0; + const RetransmissionAndFlowControlConfigurationOption& option) = 0; }; } // namespace internal diff --git a/system/gd/l2cap/internal/data_controller_mock.h b/system/gd/l2cap/internal/data_controller_mock.h index d071c68f36f..92876d8d161 100644 --- a/system/gd/l2cap/internal/data_controller_mock.h +++ b/system/gd/l2cap/internal/data_controller_mock.h @@ -16,10 +16,10 @@ #pragma once -#include "l2cap/internal/data_controller.h" - #include +#include "l2cap/internal/data_controller.h" + // Unit test interfaces namespace bluetooth { namespace l2cap { @@ -27,13 +27,13 @@ namespace internal { namespace testing { class MockDataController : public DataController { - public: +public: MOCK_METHOD(void, OnSdu, (std::unique_ptr), (override)); MOCK_METHOD(void, OnPdu, (packet::PacketView), (override)); MOCK_METHOD(std::unique_ptr, GetNextPacket, (), (override)); MOCK_METHOD(void, EnableFcs, (bool), (override)); - MOCK_METHOD(void, SetRetransmissionAndFlowControlOptions, (const RetransmissionAndFlowControlConfigurationOption&), - (override)); + MOCK_METHOD(void, SetRetransmissionAndFlowControlOptions, + (const RetransmissionAndFlowControlConfigurationOption&), (override)); }; } // namespace testing diff --git a/system/gd/l2cap/internal/data_pipeline_manager.cc b/system/gd/l2cap/internal/data_pipeline_manager.cc index 95fa83ea2bd..e2ce918beb1 100644 --- a/system/gd/l2cap/internal/data_pipeline_manager.cc +++ b/system/gd/l2cap/internal/data_pipeline_manager.cc @@ -14,12 +14,13 @@ * limitations under the License. */ +#include "l2cap/internal/data_pipeline_manager.h" + #include #include "l2cap/cid.h" #include "l2cap/internal/channel_impl.h" #include "l2cap/internal/data_controller.h" -#include "l2cap/internal/data_pipeline_manager.h" #include "l2cap/internal/sender.h" #include "os/log.h" @@ -27,18 +28,17 @@ namespace bluetooth { namespace l2cap { namespace internal { -void DataPipelineManager::AttachChannel(Cid cid, std::shared_ptr channel, ChannelMode mode) { - log::assert_that( - sender_map_.find(cid) == sender_map_.end(), - "assert failed: sender_map_.find(cid) == sender_map_.end()"); +void DataPipelineManager::AttachChannel(Cid cid, std::shared_ptr channel, + ChannelMode mode) { + log::assert_that(sender_map_.find(cid) == sender_map_.end(), + "assert failed: sender_map_.find(cid) == sender_map_.end()"); sender_map_.emplace(std::piecewise_construct, std::forward_as_tuple(cid), std::forward_as_tuple(handler_, link_, scheduler_.get(), channel, mode)); } void DataPipelineManager::DetachChannel(Cid cid) { - log::assert_that( - sender_map_.find(cid) != sender_map_.end(), - "assert failed: sender_map_.find(cid) != sender_map_.end()"); + log::assert_that(sender_map_.find(cid) != sender_map_.end(), + "assert failed: sender_map_.find(cid) != sender_map_.end()"); sender_map_.erase(cid); scheduler_->RemoveChannel(cid); scheduler_->SetChannelTxPriority(cid, false); @@ -52,23 +52,21 @@ DataController* DataPipelineManager::GetDataController(Cid cid) { } void DataPipelineManager::OnPacketSent(Cid cid) { - log::assert_that( - sender_map_.find(cid) != sender_map_.end(), - "assert failed: sender_map_.find(cid) != sender_map_.end()"); + log::assert_that(sender_map_.find(cid) != sender_map_.end(), + "assert failed: sender_map_.find(cid) != sender_map_.end()"); sender_map_.find(cid)->second.OnPacketSent(); } -void DataPipelineManager::UpdateClassicConfiguration(Cid cid, classic::internal::ChannelConfigurationState config) { - log::assert_that( - sender_map_.find(cid) != sender_map_.end(), - "assert failed: sender_map_.find(cid) != sender_map_.end()"); +void DataPipelineManager::UpdateClassicConfiguration( + Cid cid, classic::internal::ChannelConfigurationState config) { + log::assert_that(sender_map_.find(cid) != sender_map_.end(), + "assert failed: sender_map_.find(cid) != sender_map_.end()"); sender_map_.find(cid)->second.UpdateClassicConfiguration(config); } void DataPipelineManager::SetChannelTxPriority(Cid cid, bool high_priority) { - log::assert_that( - sender_map_.find(cid) != sender_map_.end(), - "assert failed: sender_map_.find(cid) != sender_map_.end()"); + log::assert_that(sender_map_.find(cid) != sender_map_.end(), + "assert failed: sender_map_.find(cid) != sender_map_.end()"); scheduler_->SetChannelTxPriority(cid, high_priority); } diff --git a/system/gd/l2cap/internal/data_pipeline_manager.h b/system/gd/l2cap/internal/data_pipeline_manager.h index 104f49ec76e..4f9a27311db 100644 --- a/system/gd/l2cap/internal/data_pipeline_manager.h +++ b/system/gd/l2cap/internal/data_pipeline_manager.h @@ -47,7 +47,7 @@ class ILink; * Contains a Sender and its corresponding DataController per attached channel. */ class DataPipelineManager { - public: +public: using UpperEnqueue = packet::PacketView; using UpperDequeue = packet::BasePacketBuilder; using UpperQueueDownEnd = common::BidiQueueEnd; @@ -56,7 +56,9 @@ class DataPipelineManager { using LowerQueueUpEnd = common::BidiQueueEnd; DataPipelineManager(os::Handler* handler, ILink* link, LowerQueueUpEnd* link_queue_up_end) - : handler_(handler), link_(link), scheduler_(std::make_unique(this, link_queue_up_end, handler)), + : handler_(handler), + link_(link), + scheduler_(std::make_unique(this, link_queue_up_end, handler)), receiver_(link_queue_up_end, handler, this) {} using ChannelMode = Sender::ChannelMode; @@ -65,11 +67,12 @@ class DataPipelineManager { virtual void DetachChannel(Cid cid); virtual DataController* GetDataController(Cid cid); virtual void OnPacketSent(Cid cid); - virtual void UpdateClassicConfiguration(Cid cid, classic::internal::ChannelConfigurationState config); + virtual void UpdateClassicConfiguration(Cid cid, + classic::internal::ChannelConfigurationState config); virtual void SetChannelTxPriority(Cid cid, bool high_priority); virtual ~DataPipelineManager() = default; - private: +private: os::Handler* handler_; ILink* link_; std::unordered_map sender_map_; diff --git a/system/gd/l2cap/internal/data_pipeline_manager_mock.h b/system/gd/l2cap/internal/data_pipeline_manager_mock.h index 01fb926d4a2..900f0d49c68 100644 --- a/system/gd/l2cap/internal/data_pipeline_manager_mock.h +++ b/system/gd/l2cap/internal/data_pipeline_manager_mock.h @@ -16,12 +16,11 @@ #pragma once -#include "l2cap/internal/data_pipeline_manager.h" +#include #include "l2cap/internal/channel_impl.h" #include "l2cap/internal/data_controller.h" - -#include +#include "l2cap/internal/data_pipeline_manager.h" // Unit test interfaces namespace bluetooth { @@ -30,7 +29,7 @@ namespace internal { namespace testing { class MockDataPipelineManager : public DataPipelineManager { - public: +public: MockDataPipelineManager(os::Handler* handler, LowerQueueUpEnd* link_queue_up_end) : DataPipelineManager(handler, nullptr, link_queue_up_end) {} MOCK_METHOD(void, AttachChannel, (Cid, std::shared_ptr, ChannelMode), (override)); diff --git a/system/gd/l2cap/internal/dynamic_channel_allocator.cc b/system/gd/l2cap/internal/dynamic_channel_allocator.cc index 3dd7d0a40a0..bb59311e772 100644 --- a/system/gd/l2cap/internal/dynamic_channel_allocator.cc +++ b/system/gd/l2cap/internal/dynamic_channel_allocator.cc @@ -30,45 +30,43 @@ namespace bluetooth { namespace l2cap { namespace internal { -std::shared_ptr DynamicChannelAllocator::AllocateChannel(Psm psm, Cid remote_cid) { +std::shared_ptr DynamicChannelAllocator::AllocateChannel(Psm psm, + Cid remote_cid) { if (used_remote_cid_.find(remote_cid) != used_remote_cid_.end()) { log::info("Remote cid 0x{:x} is used", remote_cid); return nullptr; } Cid cid = kFirstDynamicChannel; for (; cid <= kLastDynamicChannel; cid++) { - if (used_cid_.find(cid) == used_cid_.end()) break; + if (used_cid_.find(cid) == used_cid_.end()) { + break; + } } if (cid > kLastDynamicChannel) { log::warn("All cid are used"); return nullptr; } - auto elem = - channels_.try_emplace(cid, std::make_shared(psm, cid, remote_cid, link_, l2cap_handler_)); - log::assert_that( - elem.second, - "Failed to create channel for psm 0x{:x} device {}", - psm, - ADDRESS_TO_LOGGABLE_CSTR(link_->GetDevice())); + auto elem = channels_.try_emplace( + cid, std::make_shared(psm, cid, remote_cid, link_, l2cap_handler_)); + log::assert_that(elem.second, "Failed to create channel for psm 0x{:x} device {}", psm, + ADDRESS_TO_LOGGABLE_CSTR(link_->GetDevice())); log::assert_that(elem.first->second != nullptr, "assert failed: elem.first->second != nullptr"); used_remote_cid_.insert(remote_cid); used_cid_.insert(cid); return elem.first->second; } -std::shared_ptr DynamicChannelAllocator::AllocateReservedChannel(Cid reserved_cid, Psm psm, - Cid remote_cid) { +std::shared_ptr DynamicChannelAllocator::AllocateReservedChannel( + Cid reserved_cid, Psm psm, Cid remote_cid) { if (used_remote_cid_.find(remote_cid) != used_remote_cid_.end()) { log::info("Remote cid 0x{:x} is used", remote_cid); return nullptr; } auto elem = channels_.try_emplace( - reserved_cid, std::make_shared(psm, reserved_cid, remote_cid, link_, l2cap_handler_)); - log::assert_that( - elem.second, - "Failed to create channel for psm 0x{:x} device {}", - psm, - ADDRESS_TO_LOGGABLE_CSTR(link_->GetDevice())); + reserved_cid, std::make_shared(psm, reserved_cid, remote_cid, link_, + l2cap_handler_)); + log::assert_that(elem.second, "Failed to create channel for psm 0x{:x} device {}", psm, + ADDRESS_TO_LOGGABLE_CSTR(link_->GetDevice())); log::assert_that(elem.first->second != nullptr, "assert failed: elem.first->second != nullptr"); used_remote_cid_.insert(remote_cid); return elem.first->second; @@ -77,7 +75,9 @@ std::shared_ptr DynamicChannelAllocator::AllocateReservedCha Cid DynamicChannelAllocator::ReserveChannel() { Cid cid = kFirstDynamicChannel; for (; cid <= kLastDynamicChannel; cid++) { - if (used_cid_.find(cid) == used_cid_.end()) break; + if (used_cid_.find(cid) == used_cid_.end()) { + break; + } } if (cid > kLastDynamicChannel) { log::warn("All cid are used"); @@ -115,7 +115,8 @@ std::shared_ptr DynamicChannelAllocator::FindChannelByCid(Ci return channels_.find(cid)->second; } -std::shared_ptr DynamicChannelAllocator::FindChannelByRemoteCid(Cid remote_cid) { +std::shared_ptr DynamicChannelAllocator::FindChannelByRemoteCid( + Cid remote_cid) { for (auto& channel : channels_) { if (channel.second->GetRemoteCid() == remote_cid) { return channel.second; @@ -124,9 +125,7 @@ std::shared_ptr DynamicChannelAllocator::FindChannelByRemote return nullptr; } -size_t DynamicChannelAllocator::NumberOfChannels() const { - return channels_.size(); -} +size_t DynamicChannelAllocator::NumberOfChannels() const { return channels_.size(); } void DynamicChannelAllocator::OnAclDisconnected(hci::ErrorCode reason) { for (auto& elem : channels_) { diff --git a/system/gd/l2cap/internal/dynamic_channel_allocator.h b/system/gd/l2cap/internal/dynamic_channel_allocator.h index 947ae45ef70..9f760ebfe34 100644 --- a/system/gd/l2cap/internal/dynamic_channel_allocator.h +++ b/system/gd/l2cap/internal/dynamic_channel_allocator.h @@ -40,10 +40,10 @@ namespace internal { class DynamicChannelImpl; -// Helper class for keeping channels in a Link. It allocates and frees Channel object, and supports querying whether a -// channel is in use +// Helper class for keeping channels in a Link. It allocates and frees Channel object, and supports +// querying whether a channel is in use class DynamicChannelAllocator { - public: +public: DynamicChannelAllocator(l2cap::internal::ILink* link, os::Handler* l2cap_handler) : link_(link), l2cap_handler_(l2cap_handler) { log::assert_that(link_ != nullptr, "assert failed: link_ != nullptr"); @@ -51,13 +51,15 @@ class DynamicChannelAllocator { } // Allocates a channel. If psm is used, OR the remote cid already exists, return nullptr. - // NOTE: The returned DynamicChannelImpl object is still owned by the channel allocator, NOT the client. + // NOTE: The returned DynamicChannelImpl object is still owned by the channel allocator, NOT the + // client. std::shared_ptr AllocateChannel(Psm psm, Cid remote_cid); - std::shared_ptr AllocateReservedChannel(Cid reserved_cid, Psm psm, Cid remote_cid); + std::shared_ptr AllocateReservedChannel(Cid reserved_cid, Psm psm, + Cid remote_cid); - // Gives an unused Cid to be used for opening a channel. If a channel is used, call AllocateReservedChannel. If no - // longer needed, use FreeChannel. + // Gives an unused Cid to be used for opening a channel. If a channel is used, call + // AllocateReservedChannel. If no longer needed, use FreeChannel. Cid ReserveChannel(); // Frees a channel (existing or reserved) @@ -73,7 +75,7 @@ class DynamicChannelAllocator { void OnAclDisconnected(hci::ErrorCode hci_status); - private: +private: friend class bluetooth::l2cap::classic::internal::DumpsysHelper; l2cap::internal::ILink* link_; os::Handler* l2cap_handler_; diff --git a/system/gd/l2cap/internal/dynamic_channel_allocator_fuzz_test.cc b/system/gd/l2cap/internal/dynamic_channel_allocator_fuzz_test.cc index be46086a8e2..2c1f50f22f7 100644 --- a/system/gd/l2cap/internal/dynamic_channel_allocator_fuzz_test.cc +++ b/system/gd/l2cap/internal/dynamic_channel_allocator_fuzz_test.cc @@ -14,12 +14,12 @@ * limitations under the License. */ +#include + #include "l2cap/classic/internal/link_mock.h" #include "l2cap/internal/dynamic_channel_allocator.h" #include "l2cap/internal/parameter_provider_mock.h" -#include - namespace bluetooth { namespace l2cap { namespace internal { @@ -31,23 +31,25 @@ using l2cap::internal::testing::MockScheduler; using ::testing::NiceMock; using ::testing::Return; -const hci::AddressWithType device{{{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}, hci::AddressType::PUBLIC_IDENTITY_ADDRESS}; +const hci::AddressWithType device{{{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}, + hci::AddressType::PUBLIC_IDENTITY_ADDRESS}; class L2capClassicDynamicChannelAllocatorFuzzTest { - public: +public: void RunTests(const uint8_t* data, size_t size) { SetUp(); TestPrecondition(data, size); TearDown(); } - private: +private: void SetUp() { thread_ = new os::Thread("test_thread", os::Thread::Priority::NORMAL); handler_ = new os::Handler(thread_); mock_parameter_provider_ = new NiceMock(); - mock_classic_link_ = new NiceMock(handler_, mock_parameter_provider_, - std::make_unique>(), nullptr); + mock_classic_link_ = + new NiceMock(handler_, mock_parameter_provider_, + std::make_unique>(), nullptr); EXPECT_CALL(*mock_classic_link_, GetDevice()).WillRepeatedly(Return(device)); channel_allocator_ = std::make_unique(mock_classic_link_, handler_); } diff --git a/system/gd/l2cap/internal/dynamic_channel_allocator_test.cc b/system/gd/l2cap/internal/dynamic_channel_allocator_test.cc index 566e2c406cb..5cfebf666bc 100644 --- a/system/gd/l2cap/internal/dynamic_channel_allocator_test.cc +++ b/system/gd/l2cap/internal/dynamic_channel_allocator_test.cc @@ -15,12 +15,13 @@ */ #include "l2cap/internal/dynamic_channel_allocator.h" -#include "l2cap/classic/internal/link_mock.h" -#include "l2cap/internal/parameter_provider_mock.h" #include #include +#include "l2cap/classic/internal/link_mock.h" +#include "l2cap/internal/parameter_provider_mock.h" + namespace bluetooth { namespace l2cap { namespace internal { @@ -29,10 +30,11 @@ using classic::internal::testing::MockLink; using l2cap::internal::testing::MockParameterProvider; using ::testing::Return; -const hci::AddressWithType device{{{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}, hci::AddressType::PUBLIC_IDENTITY_ADDRESS}; +const hci::AddressWithType device{{{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}, + hci::AddressType::PUBLIC_IDENTITY_ADDRESS}; class L2capClassicDynamicChannelAllocatorTest : public ::testing::Test { - protected: +protected: void SetUp() override { thread_ = new os::Thread("test_thread", os::Thread::Priority::NORMAL); handler_ = new os::Handler(thread_); diff --git a/system/gd/l2cap/internal/dynamic_channel_impl.cc b/system/gd/l2cap/internal/dynamic_channel_impl.cc index dfd2bc335e9..ff47c283c74 100644 --- a/system/gd/l2cap/internal/dynamic_channel_impl.cc +++ b/system/gd/l2cap/internal/dynamic_channel_impl.cc @@ -32,9 +32,13 @@ namespace bluetooth { namespace l2cap { namespace internal { -DynamicChannelImpl::DynamicChannelImpl(Psm psm, Cid cid, Cid remote_cid, l2cap::internal::ILink* link, - os::Handler* l2cap_handler) - : psm_(psm), cid_(cid), remote_cid_(remote_cid), link_(link), l2cap_handler_(l2cap_handler), +DynamicChannelImpl::DynamicChannelImpl(Psm psm, Cid cid, Cid remote_cid, + l2cap::internal::ILink* link, os::Handler* l2cap_handler) + : psm_(psm), + cid_(cid), + remote_cid_(remote_cid), + link_(link), + l2cap_handler_(l2cap_handler), device_(link->GetDevice()) { log::assert_that(cid_ > 0, "assert failed: cid_ > 0"); log::assert_that(remote_cid_ > 0, "assert failed: remote_cid_ > 0"); @@ -42,11 +46,10 @@ DynamicChannelImpl::DynamicChannelImpl(Psm psm, Cid cid, Cid remote_cid, l2cap:: log::assert_that(l2cap_handler_ != nullptr, "assert failed: l2cap_handler_ != nullptr"); } -hci::AddressWithType DynamicChannelImpl::GetDevice() const { - return device_; -} +hci::AddressWithType DynamicChannelImpl::GetDevice() const { return device_; } -void DynamicChannelImpl::RegisterOnCloseCallback(DynamicChannel::OnCloseCallback on_close_callback) { +void DynamicChannelImpl::RegisterOnCloseCallback( + DynamicChannel::OnCloseCallback on_close_callback) { log::assert_that(!on_close_callback_, "OnCloseCallback can only be registered once"); // If channel is already closed, call the callback immediately without saving it if (closed_) { @@ -65,13 +68,10 @@ void DynamicChannelImpl::Close() { } void DynamicChannelImpl::OnClosed(hci::ErrorCode status) { - log::assert_that( - !closed_, - "Device {} Cid 0x{:x} closed twice, old status 0x{:x}, new status 0x{:x}", - ADDRESS_TO_LOGGABLE_CSTR(device_), - cid_, - static_cast(close_reason_), - static_cast(status)); + log::assert_that(!closed_, + "Device {} Cid 0x{:x} closed twice, old status 0x{:x}, new status 0x{:x}", + ADDRESS_TO_LOGGABLE_CSTR(device_), cid_, static_cast(close_reason_), + static_cast(status)); closed_ = true; close_reason_ = status; link_ = nullptr; diff --git a/system/gd/l2cap/internal/dynamic_channel_impl.h b/system/gd/l2cap/internal/dynamic_channel_impl.h index 7f34551a86c..c2eccfba6f8 100644 --- a/system/gd/l2cap/internal/dynamic_channel_impl.h +++ b/system/gd/l2cap/internal/dynamic_channel_impl.h @@ -33,8 +33,9 @@ namespace l2cap { namespace internal { class DynamicChannelImpl : public l2cap::internal::ChannelImpl { - public: - DynamicChannelImpl(Psm psm, Cid cid, Cid remote_cid, l2cap::internal::ILink* link, os::Handler* l2cap_handler); +public: + DynamicChannelImpl(Psm psm, Cid cid, Cid remote_cid, l2cap::internal::ILink* link, + os::Handler* l2cap_handler); DynamicChannelImpl(const DynamicChannelImpl&) = delete; DynamicChannelImpl& operator=(const DynamicChannelImpl&) = delete; @@ -48,25 +49,21 @@ class DynamicChannelImpl : public l2cap::internal::ChannelImpl { virtual void Close(); virtual void OnClosed(hci::ErrorCode status); - common::BidiQueueEnd>* GetQueueUpEnd() { + common::BidiQueueEnd>* + GetQueueUpEnd() { return channel_queue_.GetUpEnd(); } - common::BidiQueueEnd, packet::BasePacketBuilder>* GetQueueDownEnd() { + common::BidiQueueEnd, packet::BasePacketBuilder>* + GetQueueDownEnd() { return channel_queue_.GetDownEnd(); } - virtual Cid GetCid() const { - return cid_; - } + virtual Cid GetCid() const { return cid_; } - virtual Cid GetRemoteCid() const { - return remote_cid_; - } + virtual Cid GetRemoteCid() const { return remote_cid_; } - virtual Psm GetPsm() const { - return psm_; - } + virtual Psm GetPsm() const { return psm_; } virtual void SetChannelTxPriority(bool high_priority) { link_->SetChannelTxPriority(cid_, high_priority); @@ -75,7 +72,7 @@ class DynamicChannelImpl : public l2cap::internal::ChannelImpl { // TODO(cmanton) Do something a little bit better than this bool local_initiated_{false}; - private: +private: const Psm psm_; const Cid cid_; const Cid remote_cid_; @@ -90,8 +87,8 @@ class DynamicChannelImpl : public l2cap::internal::ChannelImpl { bool closed_ = false; hci::ErrorCode close_reason_ = hci::ErrorCode::SUCCESS; static constexpr size_t kChannelQueueSize = 5; - common::BidiQueue, packet::BasePacketBuilder> channel_queue_{ - kChannelQueueSize}; + common::BidiQueue, packet::BasePacketBuilder> + channel_queue_{kChannelQueueSize}; }; } // namespace internal diff --git a/system/gd/l2cap/internal/dynamic_channel_impl_test.cc b/system/gd/l2cap/internal/dynamic_channel_impl_test.cc index 7469869b911..e356a587c84 100644 --- a/system/gd/l2cap/internal/dynamic_channel_impl_test.cc +++ b/system/gd/l2cap/internal/dynamic_channel_impl_test.cc @@ -16,15 +16,15 @@ #include "l2cap/internal/dynamic_channel_impl.h" +#include +#include + #include "common/testing/bind_test_util.h" #include "l2cap/cid.h" #include "l2cap/classic/internal/link_mock.h" #include "l2cap/internal/parameter_provider_mock.h" #include "os/handler.h" -#include -#include - namespace bluetooth { namespace l2cap { namespace internal { @@ -34,7 +34,7 @@ using l2cap::internal::testing::MockParameterProvider; using ::testing::Return; class L2capClassicDynamicChannelImplTest : public ::testing::Test { - public: +public: static void SyncHandler(os::Handler* handler) { std::promise promise; auto future = promise.get_future(); @@ -42,7 +42,7 @@ class L2capClassicDynamicChannelImplTest : public ::testing::Test { future.wait_for(std::chrono::milliseconds(3)); } - protected: +protected: void SetUp() override { thread_ = new os::Thread("test_thread", os::Thread::Priority::NORMAL); l2cap_handler_ = new os::Handler(thread_); @@ -59,35 +59,36 @@ class L2capClassicDynamicChannelImplTest : public ::testing::Test { }; class StatusCapture { - public: +public: hci::ErrorCode value = hci::ErrorCode::SUCCESS; - void capture(hci::ErrorCode status) { - value = status; - } + void capture(hci::ErrorCode status) { value = status; } }; TEST_F(L2capClassicDynamicChannelImplTest, get_device) { MockParameterProvider mock_parameter_provider; MockLink mock_classic_link(l2cap_handler_, &mock_parameter_provider); - const hci::AddressWithType device{{{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}, hci::AddressType::PUBLIC_IDENTITY_ADDRESS}; + const hci::AddressWithType device{{{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}, + hci::AddressType::PUBLIC_IDENTITY_ADDRESS}; EXPECT_CALL(mock_classic_link, GetDevice()).WillRepeatedly(Return(device)); - DynamicChannelImpl dynamic_channel_impl(0x01, kFirstDynamicChannel, kFirstDynamicChannel, &mock_classic_link, - l2cap_handler_); + DynamicChannelImpl dynamic_channel_impl(0x01, kFirstDynamicChannel, kFirstDynamicChannel, + &mock_classic_link, l2cap_handler_); EXPECT_EQ(device, dynamic_channel_impl.GetDevice()); } TEST_F(L2capClassicDynamicChannelImplTest, close_triggers_callback) { MockParameterProvider mock_parameter_provider; MockLink mock_classic_link(l2cap_handler_, &mock_parameter_provider); - const hci::AddressWithType device{{{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}, hci::AddressType::PUBLIC_IDENTITY_ADDRESS}; + const hci::AddressWithType device{{{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}, + hci::AddressType::PUBLIC_IDENTITY_ADDRESS}; EXPECT_CALL(mock_classic_link, GetDevice()).WillRepeatedly(Return(device)); - DynamicChannelImpl dynamic_channel_impl(0x01, kFirstDynamicChannel, kFirstDynamicChannel, &mock_classic_link, - l2cap_handler_); + DynamicChannelImpl dynamic_channel_impl(0x01, kFirstDynamicChannel, kFirstDynamicChannel, + &mock_classic_link, l2cap_handler_); // Register on close callback auto user_handler = std::make_unique(thread_); StatusCapture* my_status = new StatusCapture(); - dynamic_channel_impl.RegisterOnCloseCallback(user_handler->BindOnceOn(my_status, &StatusCapture::capture)); + dynamic_channel_impl.RegisterOnCloseCallback( + user_handler->BindOnceOn(my_status, &StatusCapture::capture)); // Channel closure should trigger such callback dynamic_channel_impl.OnClosed(hci::ErrorCode::REMOTE_USER_TERMINATED_CONNECTION); @@ -101,10 +102,11 @@ TEST_F(L2capClassicDynamicChannelImplTest, close_triggers_callback) { TEST_F(L2capClassicDynamicChannelImplTest, register_callback_after_close_should_call_immediately) { MockParameterProvider mock_parameter_provider; MockLink mock_classic_link(l2cap_handler_, &mock_parameter_provider); - const hci::AddressWithType device{{{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}, hci::AddressType::PUBLIC_IDENTITY_ADDRESS}; + const hci::AddressWithType device{{{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}, + hci::AddressType::PUBLIC_IDENTITY_ADDRESS}; EXPECT_CALL(mock_classic_link, GetDevice()).WillRepeatedly(Return(device)); - DynamicChannelImpl dynamic_channel_impl(0x01, kFirstDynamicChannel, kFirstDynamicChannel, &mock_classic_link, - l2cap_handler_); + DynamicChannelImpl dynamic_channel_impl(0x01, kFirstDynamicChannel, kFirstDynamicChannel, + &mock_classic_link, l2cap_handler_); // Channel closure should do nothing dynamic_channel_impl.OnClosed(hci::ErrorCode::REMOTE_USER_TERMINATED_CONNECTION); @@ -112,7 +114,8 @@ TEST_F(L2capClassicDynamicChannelImplTest, register_callback_after_close_should_ // Register on close callback should trigger callback immediately auto user_handler = std::make_unique(thread_); StatusCapture* my_status = new StatusCapture(); - dynamic_channel_impl.RegisterOnCloseCallback(user_handler->BindOnceOn(my_status, &StatusCapture::capture)); + dynamic_channel_impl.RegisterOnCloseCallback( + user_handler->BindOnceOn(my_status, &StatusCapture::capture)); SyncHandler(user_handler.get()); EXPECT_EQ(hci::ErrorCode::REMOTE_USER_TERMINATED_CONNECTION, my_status->value); @@ -124,15 +127,17 @@ TEST_F(L2capClassicDynamicChannelImplTest, register_callback_after_close_should_ TEST_F(L2capClassicDynamicChannelImplTest, close_twice_should_fail) { MockParameterProvider mock_parameter_provider; MockLink mock_classic_link(l2cap_handler_, &mock_parameter_provider); - const hci::AddressWithType device{{{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}, hci::AddressType::PUBLIC_IDENTITY_ADDRESS}; + const hci::AddressWithType device{{{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}, + hci::AddressType::PUBLIC_IDENTITY_ADDRESS}; EXPECT_CALL(mock_classic_link, GetDevice()).WillRepeatedly(Return(device)); - DynamicChannelImpl dynamic_channel_impl(0x01, kFirstDynamicChannel, kFirstDynamicChannel, &mock_classic_link, - l2cap_handler_); + DynamicChannelImpl dynamic_channel_impl(0x01, kFirstDynamicChannel, kFirstDynamicChannel, + &mock_classic_link, l2cap_handler_); // Register on close callback auto user_handler = std::make_unique(thread_); StatusCapture* my_status = new StatusCapture(); - dynamic_channel_impl.RegisterOnCloseCallback(user_handler->BindOnceOn(my_status, &StatusCapture::capture)); + dynamic_channel_impl.RegisterOnCloseCallback( + user_handler->BindOnceOn(my_status, &StatusCapture::capture)); // Channel closure should trigger such callback dynamic_channel_impl.OnClosed(hci::ErrorCode::REMOTE_USER_TERMINATED_CONNECTION); @@ -149,19 +154,21 @@ TEST_F(L2capClassicDynamicChannelImplTest, close_twice_should_fail) { TEST_F(L2capClassicDynamicChannelImplTest, multiple_registeration_should_fail) { MockParameterProvider mock_parameter_provider; MockLink mock_classic_link(l2cap_handler_, &mock_parameter_provider); - const hci::AddressWithType device{{{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}, hci::AddressType::PUBLIC_IDENTITY_ADDRESS}; + const hci::AddressWithType device{{{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}, + hci::AddressType::PUBLIC_IDENTITY_ADDRESS}; EXPECT_CALL(mock_classic_link, GetDevice()).WillRepeatedly(Return(device)); - DynamicChannelImpl dynamic_channel_impl(0x01, kFirstDynamicChannel, kFirstDynamicChannel, &mock_classic_link, - l2cap_handler_); + DynamicChannelImpl dynamic_channel_impl(0x01, kFirstDynamicChannel, kFirstDynamicChannel, + &mock_classic_link, l2cap_handler_); // Register on close callback auto user_handler = std::make_unique(thread_); StatusCapture* my_status = new StatusCapture(); - dynamic_channel_impl.RegisterOnCloseCallback(user_handler->BindOnceOn(my_status, &StatusCapture::capture)); + dynamic_channel_impl.RegisterOnCloseCallback( + user_handler->BindOnceOn(my_status, &StatusCapture::capture)); - EXPECT_DEATH( - dynamic_channel_impl.RegisterOnCloseCallback(user_handler->BindOnce([](hci::ErrorCode status) { FAIL(); })), - ".*RegisterOnCloseCallback.*"); + EXPECT_DEATH(dynamic_channel_impl.RegisterOnCloseCallback( + user_handler->BindOnce([](hci::ErrorCode status) { FAIL(); })), + ".*RegisterOnCloseCallback.*"); user_handler->Clear(); delete my_status; diff --git a/system/gd/l2cap/internal/enhanced_retransmission_mode_channel_data_controller.cc b/system/gd/l2cap/internal/enhanced_retransmission_mode_channel_data_controller.cc index 2e3e3ba48a6..201ab32f5cf 100644 --- a/system/gd/l2cap/internal/enhanced_retransmission_mode_channel_data_controller.cc +++ b/system/gd/l2cap/internal/enhanced_retransmission_mode_channel_data_controller.cc @@ -31,18 +31,25 @@ namespace bluetooth { namespace l2cap { namespace internal { -ErtmController::ErtmController(ILink* link, Cid cid, Cid remote_cid, UpperQueueDownEnd* channel_queue_end, - os::Handler* handler, Scheduler* scheduler) - : link_(link), cid_(cid), remote_cid_(remote_cid), enqueue_buffer_(channel_queue_end), handler_(handler), - scheduler_(scheduler), pimpl_(std::make_unique(this, handler)) {} - -ErtmController::~ErtmController() { - enqueue_buffer_.Clear(); -} +ErtmController::ErtmController(ILink* link, Cid cid, Cid remote_cid, + UpperQueueDownEnd* channel_queue_end, os::Handler* handler, + Scheduler* scheduler) + : link_(link), + cid_(cid), + remote_cid_(remote_cid), + enqueue_buffer_(channel_queue_end), + handler_(handler), + scheduler_(scheduler), + pimpl_(std::make_unique(this, handler)) {} + +ErtmController::~ErtmController() { enqueue_buffer_.Clear(); } struct ErtmController::impl { impl(ErtmController* controller, os::Handler* handler) - : controller_(controller), handler_(handler), retrans_timer_(handler), monitor_timer_(handler) {} + : controller_(controller), + handler_(handler), + retrans_timer_(handler), + monitor_timer_(handler) {} ErtmController* controller_; os::Handler* handler_; @@ -82,9 +89,12 @@ struct ErtmController::impl { int unacked_frames_ = 0; // TODO: Instead of having a map, we may consider about a better data structure // Map from TxSeq to (SAR, SDU size for START packet, information payload) - std::map>> unacked_list_; + std::map>> + unacked_list_; // Stores (SAR, SDU size for START packet, information payload) - std::queue>> pending_frames_; + std::queue>> + pending_frames_; int retry_count_ = 0; std::map retry_i_frames_; bool rnr_sent_ = false; @@ -99,7 +109,8 @@ struct ErtmController::impl { // Events (@see 8.6.5.4) - void data_request(SegmentationAndReassembly sar, std::unique_ptr pdu, uint16_t sdu_size = 0) { + void data_request(SegmentationAndReassembly sar, std::unique_ptr pdu, + uint16_t sdu_size = 0) { // Note: sdu_size only applies to START packet if (tx_state_ == TxState::XMIT && !remote_busy() && rem_window_not_full()) { send_data(sar, sdu_size, std::move(pdu)); @@ -110,9 +121,7 @@ struct ErtmController::impl { } } - void local_busy_detected() { - local_busy_ = true; - } + void local_busy_detected() { local_busy_ = true; } void local_busy_clear() { if (tx_state_ == TxState::XMIT && rnr_sent()) { @@ -174,17 +183,17 @@ struct ErtmController::impl { } } - void recv_i_frame(Final f, uint8_t tx_seq, uint8_t req_seq, SegmentationAndReassembly sar, uint16_t sdu_size, - const packet::PacketView& payload) { + void recv_i_frame(Final f, uint8_t tx_seq, uint8_t req_seq, SegmentationAndReassembly sar, + uint16_t sdu_size, const packet::PacketView& payload) { if (rx_state_ == RxState::RECV) { - if (f == Final::NOT_SET && with_expected_tx_seq(tx_seq) && with_valid_req_seq(req_seq) && with_valid_f_bit(f) && - !local_busy()) { + if (f == Final::NOT_SET && with_expected_tx_seq(tx_seq) && with_valid_req_seq(req_seq) && + with_valid_f_bit(f) && !local_busy()) { increment_expected_tx_seq(); pass_to_tx(req_seq, f); data_indication(sar, sdu_size, payload); send_ack(Final::NOT_SET); - } else if (f == Final::POLL_RESPONSE && with_expected_tx_seq(tx_seq) && with_valid_req_seq(req_seq) && - with_valid_f_bit(f) && !local_busy()) { + } else if (f == Final::POLL_RESPONSE && with_expected_tx_seq(tx_seq) && + with_valid_req_seq(req_seq) && with_valid_f_bit(f) && !local_busy()) { increment_expected_tx_seq(); pass_to_tx(req_seq, f); data_indication(sar, sdu_size, payload); @@ -195,10 +204,11 @@ struct ErtmController::impl { rej_actioned_ = false; } send_ack(Final::NOT_SET); - } else if (with_duplicate_tx_seq(tx_seq) && with_valid_req_seq(req_seq) && with_valid_f_bit(f) && !local_busy()) { + } else if (with_duplicate_tx_seq(tx_seq) && with_valid_req_seq(req_seq) && + with_valid_f_bit(f) && !local_busy()) { pass_to_tx(req_seq, f); - } else if (with_unexpected_tx_seq(tx_seq) && with_valid_req_seq(req_seq) && with_valid_f_bit(f) && - !local_busy()) { + } else if (with_unexpected_tx_seq(tx_seq) && with_valid_req_seq(req_seq) && + with_valid_f_bit(f) && !local_busy()) { if constexpr (kSendSrej) { // We don't support sending SREJ } else { @@ -206,11 +216,12 @@ struct ErtmController::impl { send_rej(); rx_state_ = RxState::REJ_SENT; } - } else if (with_expected_tx_seq(tx_seq) && with_valid_req_seq(req_seq) && with_valid_f_bit(f) && local_busy()) { + } else if (with_expected_tx_seq(tx_seq) && with_valid_req_seq(req_seq) && + with_valid_f_bit(f) && local_busy()) { pass_to_tx(req_seq, f); store_or_ignore(); - } else if (with_valid_req_seq(req_seq) && not_with_expected_tx_seq(tx_seq) && with_valid_f_bit(f) && - local_busy()) { + } else if (with_valid_req_seq(req_seq) && not_with_expected_tx_seq(tx_seq) && + with_valid_f_bit(f) && local_busy()) { pass_to_tx(req_seq, f); } else if ((with_invalid_tx_seq(tx_seq) && controller_->local_tx_window_ > kMaxTxWin / 2) || with_invalid_req_seq(req_seq)) { @@ -219,14 +230,15 @@ struct ErtmController::impl { // We decided to ignore } } else if (rx_state_ == RxState::REJ_SENT) { - if (f == Final::NOT_SET && with_expected_tx_seq(tx_seq) && with_valid_req_seq(req_seq) && with_valid_f_bit(f)) { + if (f == Final::NOT_SET && with_expected_tx_seq(tx_seq) && with_valid_req_seq(req_seq) && + with_valid_f_bit(f)) { increment_expected_tx_seq(); pass_to_tx(req_seq, f); data_indication(sar, sdu_size, payload); send_ack(Final::NOT_SET); rx_state_ = RxState::RECV; - } else if (f == Final::POLL_RESPONSE && with_expected_tx_seq(tx_seq) && with_valid_req_seq(req_seq) && - with_valid_f_bit(f)) { + } else if (f == Final::POLL_RESPONSE && with_expected_tx_seq(tx_seq) && + with_valid_req_seq(req_seq) && with_valid_f_bit(f)) { increment_expected_tx_seq(); pass_to_tx(req_seq, f); data_indication(sar, sdu_size, payload); @@ -238,7 +250,8 @@ struct ErtmController::impl { } send_ack(Final::NOT_SET); rx_state_ = RxState::RECV; - } else if (with_unexpected_tx_seq(tx_seq) && with_valid_req_seq(req_seq) && with_valid_f_bit(f)) { + } else if (with_unexpected_tx_seq(tx_seq) && with_valid_req_seq(req_seq) && + with_valid_f_bit(f)) { pass_to_tx(req_seq, f); } } else if (rx_state_ == RxState::SREJ_SENT) { @@ -248,7 +261,8 @@ struct ErtmController::impl { void recv_rr(uint8_t req_seq, Poll p = Poll::NOT_SET, Final f = Final::NOT_SET) { if (rx_state_ == RxState::RECV) { - if (p == Poll::NOT_SET && f == Final::NOT_SET && with_valid_req_seq(req_seq) && with_valid_f_bit(f)) { + if (p == Poll::NOT_SET && f == Final::NOT_SET && with_valid_req_seq(req_seq) && + with_valid_f_bit(f)) { pass_to_tx(req_seq, f); if (remote_busy() && unacked_frames_ > 0) { start_retrans_timer(); @@ -280,7 +294,8 @@ struct ErtmController::impl { rej_actioned_ = false; } send_pending_i_frames(); - } else if (p == Poll::NOT_SET && f == Final::NOT_SET && with_valid_req_seq(req_seq) && with_valid_f_bit(f)) { + } else if (p == Poll::NOT_SET && f == Final::NOT_SET && with_valid_req_seq(req_seq) && + with_valid_f_bit(f)) { pass_to_tx(req_seq, f); if (remote_busy() && unacked_frames_ > 0) { start_retrans_timer(); @@ -323,7 +338,8 @@ struct ErtmController::impl { rej_actioned_ = false; } send_pending_i_frames(); - } else if (with_valid_req_seq_retrans(req_seq) && !retry_i_frames_less_than_max_transmit(req_seq)) { + } else if (with_valid_req_seq_retrans(req_seq) && + !retry_i_frames_less_than_max_transmit(req_seq)) { CloseChannel(); } else if (with_invalid_req_seq_retrans(req_seq)) { CloseChannel(); @@ -348,7 +364,8 @@ struct ErtmController::impl { rej_actioned_ = false; } send_pending_i_frames(); - } else if (with_valid_req_seq_retrans(req_seq) && !retry_i_frames_less_than_max_transmit(req_seq)) { + } else if (with_valid_req_seq_retrans(req_seq) && + !retry_i_frames_less_than_max_transmit(req_seq)) { CloseChannel(); } else if (with_invalid_req_seq_retrans(req_seq)) { CloseChannel(); @@ -419,7 +436,8 @@ struct ErtmController::impl { srej_actioned_ = true; srej_save_req_seq_ = req_seq; } - } else if (with_valid_req_seq_retrans(req_seq) && !retry_i_frames_less_than_max_transmit(req_seq)) { + } else if (with_valid_req_seq_retrans(req_seq) && + !retry_i_frames_less_than_max_transmit(req_seq)) { CloseChannel(); } else if (with_invalid_req_seq_retrans(req_seq)) { CloseChannel(); @@ -453,7 +471,8 @@ struct ErtmController::impl { srej_actioned_ = true; srej_save_req_seq_ = req_seq; } - } else if (with_valid_req_seq_retrans(req_seq) && !retry_i_frames_less_than_max_transmit(req_seq)) { + } else if (with_valid_req_seq_retrans(req_seq) && + !retry_i_frames_less_than_max_transmit(req_seq)) { CloseChannel(); } else if (with_invalid_req_seq_retrans(req_seq)) { CloseChannel(); @@ -464,25 +483,15 @@ struct ErtmController::impl { } // Conditions (@see 8.6.5.5) - bool remote_busy() { - return remote_busy_; - } + bool remote_busy() { return remote_busy_; } - bool local_busy() { - return local_busy_; - } + bool local_busy() { return local_busy_; } - bool rem_window_not_full() { - return unacked_frames_ < controller_->remote_tx_window_; - } + bool rem_window_not_full() { return unacked_frames_ < controller_->remote_tx_window_; } - bool rem_window_full() { - return unacked_frames_ == controller_->remote_tx_window_; - } + bool rem_window_full() { return unacked_frames_ == controller_->remote_tx_window_; } - bool rnr_sent() { - return rnr_sent_; - } + bool rnr_sent() { return rnr_sent_; } bool retry_i_frames_less_than_max_transmit(uint8_t req_seq) { return retry_i_frames_[req_seq] < controller_->local_max_transmit_; @@ -494,19 +503,19 @@ struct ErtmController::impl { // Compares two sequence numbers (tx_seq or rx_seq) bool sequence_less_than(uint8_t x, uint8_t y) { - // Assuming the maximum overflow of sequence number is the same as local_tx_window_ (10 by default). + // Assuming the maximum overflow of sequence number is the same as local_tx_window_ (10 by + // default). return x < y || kMaxTxWin - (x - y) < controller_->local_tx_window_; } // Compares two sequence numbers (tx_seq or rx_seq) bool sequence_less_than_or_equal(uint8_t x, uint8_t y) { - // Assuming the maximum overflow of sequence number is the same as local_tx_window_ (10 by default). + // Assuming the maximum overflow of sequence number is the same as local_tx_window_ (10 by + // default). return x <= y || kMaxTxWin - (x - y) <= controller_->local_tx_window_; } - bool with_expected_tx_seq(uint8_t tx_seq) { - return tx_seq == expected_tx_seq_; - } + bool with_expected_tx_seq(uint8_t tx_seq) { return tx_seq == expected_tx_seq_; } bool with_valid_req_seq(uint8_t req_seq) { return sequence_less_than_or_equal(expected_ack_seq_, req_seq) && @@ -518,9 +527,7 @@ struct ErtmController::impl { sequence_less_than_or_equal(req_seq, next_tx_seq_); } - bool with_valid_f_bit(Final f) { - return f == Final::NOT_SET ^ tx_state_ == TxState::WAIT_F; - } + bool with_valid_f_bit(Final f) { return f == Final::NOT_SET ^ tx_state_ == TxState::WAIT_F; } bool with_unexpected_tx_seq(uint8_t tx_seq) { return sequence_less_than(expected_tx_seq_, tx_seq) && @@ -538,11 +545,13 @@ struct ErtmController::impl { } bool with_invalid_req_seq(uint8_t req_seq) { - return sequence_less_than(req_seq, expected_ack_seq_) || sequence_less_than(next_tx_seq_, req_seq); + return sequence_less_than(req_seq, expected_ack_seq_) || + sequence_less_than(next_tx_seq_, req_seq); } bool with_invalid_req_seq_retrans(uint8_t req_seq) { - return sequence_less_than(req_seq, expected_ack_seq_) || sequence_less_than(next_tx_seq_, req_seq); + return sequence_less_than(req_seq, expected_ack_seq_) || + sequence_less_than(next_tx_seq_, req_seq); } bool not_with_expected_tx_seq(uint8_t tx_seq) { @@ -576,37 +585,39 @@ struct ErtmController::impl { // Actions (@see 8.6.5.6) - void _send_i_frame(SegmentationAndReassembly sar, std::unique_ptr segment, uint8_t req_seq, - uint8_t tx_seq, uint16_t sdu_size = 0, Final f = Final::NOT_SET) { + void _send_i_frame(SegmentationAndReassembly sar, std::unique_ptr segment, + uint8_t req_seq, uint8_t tx_seq, uint16_t sdu_size = 0, + Final f = Final::NOT_SET) { std::unique_ptr builder; if (sar == SegmentationAndReassembly::START) { if (controller_->fcs_enabled_) { - builder = EnhancedInformationStartFrameWithFcsBuilder::Create(controller_->remote_cid_, tx_seq, f, req_seq, - sdu_size, std::move(segment)); + builder = EnhancedInformationStartFrameWithFcsBuilder::Create( + controller_->remote_cid_, tx_seq, f, req_seq, sdu_size, std::move(segment)); } else { - builder = EnhancedInformationStartFrameBuilder::Create(controller_->remote_cid_, tx_seq, f, req_seq, sdu_size, - std::move(segment)); + builder = EnhancedInformationStartFrameBuilder::Create( + controller_->remote_cid_, tx_seq, f, req_seq, sdu_size, std::move(segment)); } } else { if (controller_->fcs_enabled_) { - builder = EnhancedInformationFrameWithFcsBuilder::Create(controller_->remote_cid_, tx_seq, f, req_seq, sar, - std::move(segment)); + builder = EnhancedInformationFrameWithFcsBuilder::Create( + controller_->remote_cid_, tx_seq, f, req_seq, sar, std::move(segment)); } else { - builder = EnhancedInformationFrameBuilder::Create(controller_->remote_cid_, tx_seq, f, req_seq, sar, - std::move(segment)); + builder = EnhancedInformationFrameBuilder::Create(controller_->remote_cid_, tx_seq, f, + req_seq, sar, std::move(segment)); } } controller_->send_pdu(std::move(builder)); } - void send_data(SegmentationAndReassembly sar, uint16_t sdu_size, std::unique_ptr segment, - Final f = Final::NOT_SET) { + void send_data(SegmentationAndReassembly sar, uint16_t sdu_size, + std::unique_ptr segment, Final f = Final::NOT_SET) { std::shared_ptr shared_segment(segment.release()); unacked_list_.emplace(std::piecewise_construct, std::forward_as_tuple(next_tx_seq_), std::forward_as_tuple(sar, sdu_size, shared_segment)); std::unique_ptr copyable_packet_builder = - std::make_unique(std::get<2>(unacked_list_.find(next_tx_seq_)->second)); + std::make_unique( + std::get<2>(unacked_list_.find(next_tx_seq_)->second)); _send_i_frame(sar, std::move(copyable_packet_builder), buffer_seq_, next_tx_seq_, sdu_size, f); unacked_frames_++; frames_sent_++; @@ -615,7 +626,8 @@ struct ErtmController::impl { start_retrans_timer(); } - void pend_data(SegmentationAndReassembly sar, uint16_t sdu_size, std::unique_ptr data) { + void pend_data(SegmentationAndReassembly sar, uint16_t sdu_size, + std::unique_ptr data) { pending_frames_.emplace(std::make_tuple(sar, sdu_size, std::move(data))); } @@ -634,7 +646,8 @@ struct ErtmController::impl { void _send_s_frame(SupervisoryFunction s, uint8_t req_seq, Poll p, Final f) { std::unique_ptr builder; if (controller_->fcs_enabled_) { - builder = EnhancedSupervisoryFrameWithFcsBuilder::Create(controller_->remote_cid_, s, p, f, req_seq); + builder = EnhancedSupervisoryFrameWithFcsBuilder::Create(controller_->remote_cid_, s, p, f, + req_seq); } else { builder = EnhancedSupervisoryFrameBuilder::Create(controller_->remote_cid_, s, p, f, req_seq); } @@ -690,39 +703,32 @@ struct ErtmController::impl { } void start_retrans_timer() { - retrans_timer_.Schedule(common::BindOnce(&impl::retrans_timer_expires, common::Unretained(this)), - std::chrono::milliseconds(controller_->local_retransmit_timeout_ms_)); + retrans_timer_.Schedule( + common::BindOnce(&impl::retrans_timer_expires, common::Unretained(this)), + std::chrono::milliseconds(controller_->local_retransmit_timeout_ms_)); } void start_monitor_timer() { - monitor_timer_.Schedule(common::BindOnce(&impl::monitor_timer_expires, common::Unretained(this)), - std::chrono::milliseconds(controller_->local_monitor_timeout_ms_)); + monitor_timer_.Schedule( + common::BindOnce(&impl::monitor_timer_expires, common::Unretained(this)), + std::chrono::milliseconds(controller_->local_monitor_timeout_ms_)); } - void pass_to_tx(uint8_t req_seq, Final f) { - recv_req_seq_and_f_bit(req_seq, f); - } + void pass_to_tx(uint8_t req_seq, Final f) { recv_req_seq_and_f_bit(req_seq, f); } - void pass_to_tx_f_bit(Final f) { - recv_f_bit(f); - } + void pass_to_tx_f_bit(Final f) { recv_f_bit(f); } - void data_indication(SegmentationAndReassembly sar, uint16_t sdu_size, const packet::PacketView& segment) { + void data_indication(SegmentationAndReassembly sar, uint16_t sdu_size, + const packet::PacketView& segment) { controller_->stage_for_reassembly(sar, sdu_size, segment); buffer_seq_ = (buffer_seq_ + 1) % kMaxTxWin; } - void increment_expected_tx_seq() { - expected_tx_seq_ = (expected_tx_seq_ + 1) % kMaxTxWin; - } + void increment_expected_tx_seq() { expected_tx_seq_ = (expected_tx_seq_ + 1) % kMaxTxWin; } - void stop_retrans_timer() { - retrans_timer_.Cancel(); - } + void stop_retrans_timer() { retrans_timer_.Cancel(); } - void stop_monitor_timer() { - monitor_timer_.Cancel(); - } + void stop_monitor_timer() { monitor_timer_.Cancel(); } void send_ack(Final f = Final::NOT_SET) { if (local_busy()) { @@ -746,9 +752,7 @@ struct ErtmController::impl { // We choose to ignore. } - bool p_bit_outstanding() { - return tx_state_ == TxState::WAIT_F; - } + bool p_bit_outstanding() { return tx_state_ == TxState::WAIT_F; } void retransmit_i_frames(uint8_t req_seq, Poll p = Poll::NOT_SET) { uint8_t i = req_seq; @@ -759,9 +763,9 @@ struct ErtmController::impl { return; } std::unique_ptr copyable_packet_builder = - std::make_unique(std::get<2>(unacked_list_.find(i)->second)); - _send_i_frame(std::get<0>(unacked_list_.find(i)->second), std::move(copyable_packet_builder), buffer_seq_, i, - std::get<1>(unacked_list_.find(i)->second), f); + std::make_unique(std::get<2>(unacked_list_.find(i)->second)); + _send_i_frame(std::get<0>(unacked_list_.find(i)->second), std::move(copyable_packet_builder), + buffer_seq_, i, std::get<1>(unacked_list_.find(i)->second), f); retry_i_frames_[i]++; frames_sent_++; f = Final::NOT_SET; @@ -779,9 +783,11 @@ struct ErtmController::impl { return; } std::unique_ptr copyable_packet_builder = - std::make_unique(std::get<2>(unacked_list_.find(req_seq)->second)); - _send_i_frame(std::get<0>(unacked_list_.find(req_seq)->second), std::move(copyable_packet_builder), buffer_seq_, - req_seq, std::get<1>(unacked_list_.find(req_seq)->second), f); + std::make_unique( + std::get<2>(unacked_list_.find(req_seq)->second)); + _send_i_frame(std::get<0>(unacked_list_.find(req_seq)->second), + std::move(copyable_packet_builder), buffer_seq_, req_seq, + std::get<1>(unacked_list_.find(req_seq)->second), f); retry_i_frames_[req_seq]++; start_retrans_timer(); } @@ -798,9 +804,7 @@ struct ErtmController::impl { } } - void CloseChannel() { - controller_->close_channel(); - } + void CloseChannel() { controller_->close_channel(); } void pop_srej_list() { // We don't support sending SREJ @@ -815,9 +819,10 @@ struct ErtmController::impl { void ErtmController::OnSdu(std::unique_ptr sdu) { auto sdu_size = sdu->size(); std::vector> segments; - auto size_each_packet = (remote_mps_ - 4 /* basic L2CAP header */ - 2 /* SDU length */ - 2 /* Enhanced control */ - - (fcs_enabled_ ? 2 : 0)); - packet::FragmentingInserter fragmenting_inserter(size_each_packet, std::back_insert_iterator(segments)); + auto size_each_packet = (remote_mps_ - 4 /* basic L2CAP header */ - 2 /* SDU length */ - + 2 /* Enhanced control */ - (fcs_enabled_ ? 2 : 0)); + packet::FragmentingInserter fragmenting_inserter(size_each_packet, + std::back_insert_iterator(segments)); sdu->Serialize(fragmenting_inserter); fragmenting_inserter.finalize(); if (segments.size() == 1) { @@ -977,10 +982,12 @@ void ErtmController::stage_for_reassembly(SegmentationAndReassembly sar, uint16_ return; } // TODO: Enforce MTU - enqueue_buffer_.Enqueue(std::make_unique>(payload), handler_); + enqueue_buffer_.Enqueue(std::make_unique>(payload), + handler_); if (enqueue_buffer_.Size() == kEnqueueBufferBusyThreshold) { pimpl_->local_busy_detected(); - enqueue_buffer_.NotifyOnEmpty(common::BindOnce(&impl::local_busy_clear, common::Unretained(pimpl_.get()))); + enqueue_buffer_.NotifyOnEmpty( + common::BindOnce(&impl::local_busy_clear, common::Unretained(pimpl_.get()))); } break; case SegmentationAndReassembly::START: @@ -1013,25 +1020,25 @@ void ErtmController::stage_for_reassembly(SegmentationAndReassembly sar, uint16_ remaining_sdu_continuation_packet_size_ -= payload.size(); if (remaining_sdu_continuation_packet_size_ != 0) { log::warn("Received invalid END I-Frame"); - reassembly_stage_ = - PacketViewForReassembly(PacketView(std::make_shared>())); + reassembly_stage_ = PacketViewForReassembly( + PacketView(std::make_shared>())); remaining_sdu_continuation_packet_size_ = 0; close_channel(); return; } reassembly_stage_.AppendPacketView(payload); - enqueue_buffer_.Enqueue(std::make_unique>(reassembly_stage_), handler_); + enqueue_buffer_.Enqueue( + std::make_unique>(reassembly_stage_), handler_); if (enqueue_buffer_.Size() == kEnqueueBufferBusyThreshold) { pimpl_->local_busy_detected(); - enqueue_buffer_.NotifyOnEmpty(common::BindOnce(&impl::local_busy_clear, common::Unretained(pimpl_.get()))); + enqueue_buffer_.NotifyOnEmpty( + common::BindOnce(&impl::local_busy_clear, common::Unretained(pimpl_.get()))); } break; } } -void ErtmController::EnableFcs(bool enabled) { - fcs_enabled_ = enabled; -} +void ErtmController::EnableFcs(bool enabled) { fcs_enabled_ = enabled; } void ErtmController::send_pdu(std::unique_ptr pdu) { pdu_queue_.emplace(std::move(pdu)); @@ -1039,7 +1046,7 @@ void ErtmController::send_pdu(std::unique_ptr pdu) { } void ErtmController::SetRetransmissionAndFlowControlOptions( - const RetransmissionAndFlowControlConfigurationOption& option) { + const RetransmissionAndFlowControlConfigurationOption& option) { remote_tx_window_ = option.tx_window_size_; local_max_transmit_ = option.max_transmit_; local_retransmit_timeout_ms_ = option.retransmission_time_out_; @@ -1047,13 +1054,9 @@ void ErtmController::SetRetransmissionAndFlowControlOptions( remote_mps_ = option.maximum_pdu_size_; } -void ErtmController::close_channel() { - link_->SendDisconnectionRequest(cid_, remote_cid_); -} +void ErtmController::close_channel() { link_->SendDisconnectionRequest(cid_, remote_cid_); } -size_t ErtmController::CopyablePacketBuilder::size() const { - return builder_->size(); -} +size_t ErtmController::CopyablePacketBuilder::size() const { return builder_->size(); } void ErtmController::CopyablePacketBuilder::Serialize(BitInserter& it) const { builder_->Serialize(it); diff --git a/system/gd/l2cap/internal/enhanced_retransmission_mode_channel_data_controller.h b/system/gd/l2cap/internal/enhanced_retransmission_mode_channel_data_controller.h index 1a0c3627086..4d9be3b213b 100644 --- a/system/gd/l2cap/internal/enhanced_retransmission_mode_channel_data_controller.h +++ b/system/gd/l2cap/internal/enhanced_retransmission_mode_channel_data_controller.h @@ -39,21 +39,22 @@ namespace internal { class ILink; class ErtmController : public DataController { - public: +public: using UpperEnqueue = packet::PacketView; using UpperDequeue = packet::BasePacketBuilder; using UpperQueueDownEnd = common::BidiQueueEnd; - ErtmController(ILink* link, Cid cid, Cid remote_cid, UpperQueueDownEnd* channel_queue_end, os::Handler* handler, - Scheduler* scheduler); + ErtmController(ILink* link, Cid cid, Cid remote_cid, UpperQueueDownEnd* channel_queue_end, + os::Handler* handler, Scheduler* scheduler); ~ErtmController(); // Segmentation is handled here void OnSdu(std::unique_ptr sdu) override; void OnPdu(packet::PacketView pdu) override; std::unique_ptr GetNextPacket() override; void EnableFcs(bool enabled) override; - void SetRetransmissionAndFlowControlOptions(const RetransmissionAndFlowControlConfigurationOption& option) override; + void SetRetransmissionAndFlowControlOptions( + const RetransmissionAndFlowControlConfigurationOption& option) override; - private: +private: ILink* link_; Cid cid_; Cid remote_cid_; @@ -73,26 +74,26 @@ class ErtmController : public DataController { uint16_t remote_mps_ = 1010; class PacketViewForReassembly : public packet::PacketView { - public: + public: PacketViewForReassembly(const PacketView& packetView) : PacketView(packetView) {} - void AppendPacketView(packet::PacketView to_append) { - Append(to_append); - } + void AppendPacketView(packet::PacketView to_append) { Append(to_append); } }; class CopyablePacketBuilder : public packet::BasePacketBuilder { - public: - CopyablePacketBuilder(std::shared_ptr builder) : builder_(std::move(builder)) {} + public: + CopyablePacketBuilder(std::shared_ptr builder) + : builder_(std::move(builder)) {} void Serialize(BitInserter& it) const override; size_t size() const override; - private: + private: std::shared_ptr builder_; }; - PacketViewForReassembly reassembly_stage_{PacketView(std::make_shared>())}; + PacketViewForReassembly reassembly_stage_{ + PacketView(std::make_shared>())}; SegmentationAndReassembly sar_state_ = SegmentationAndReassembly::END; uint16_t remaining_sdu_continuation_packet_size_ = 0; diff --git a/system/gd/l2cap/internal/enhanced_retransmission_mode_channel_data_controller_test.cc b/system/gd/l2cap/internal/enhanced_retransmission_mode_channel_data_controller_test.cc index f8138983982..10b63823097 100644 --- a/system/gd/l2cap/internal/enhanced_retransmission_mode_channel_data_controller_test.cc +++ b/system/gd/l2cap/internal/enhanced_retransmission_mode_channel_data_controller_test.cc @@ -51,7 +51,7 @@ void sync_handler(os::Handler* handler) { } class ErtmDataControllerTest : public ::testing::Test { - protected: +protected: void SetUp() override { thread_ = new os::Thread("test_thread", os::Thread::Priority::NORMAL); user_handler_ = new os::Handler(thread_); @@ -100,8 +100,8 @@ TEST_F(ErtmDataControllerTest, receive_no_fcs) { testing::MockILink link; ErtmController controller{&link, 1, 1, channel_queue.GetDownEnd(), queue_handler_, &scheduler}; auto segment = CreateSdu({'a', 'b', 'c', 'd'}); - auto builder = EnhancedInformationFrameBuilder::Create(1, 0, Final::NOT_SET, 0, - SegmentationAndReassembly::UNSEGMENTED, std::move(segment)); + auto builder = EnhancedInformationFrameBuilder::Create( + 1, 0, Final::NOT_SET, 0, SegmentationAndReassembly::UNSEGMENTED, std::move(segment)); auto base_view = GetPacketView(std::move(builder)); controller.OnPdu(base_view); sync_handler(queue_handler_); @@ -119,15 +119,16 @@ TEST_F(ErtmDataControllerTest, reassemble_valid_sdu) { auto segment1 = CreateSdu({'a'}); auto segment2 = CreateSdu({'b', 'c'}); auto segment3 = CreateSdu({'d', 'e', 'f'}); - auto builder1 = EnhancedInformationStartFrameBuilder::Create(1, 0, Final::NOT_SET, 0, 6, std::move(segment1)); + auto builder1 = EnhancedInformationStartFrameBuilder::Create(1, 0, Final::NOT_SET, 0, 6, + std::move(segment1)); auto base_view = GetPacketView(std::move(builder1)); controller.OnPdu(base_view); - auto builder2 = EnhancedInformationFrameBuilder::Create(1, 1, Final::NOT_SET, 0, - SegmentationAndReassembly::CONTINUATION, std::move(segment2)); + auto builder2 = EnhancedInformationFrameBuilder::Create( + 1, 1, Final::NOT_SET, 0, SegmentationAndReassembly::CONTINUATION, std::move(segment2)); base_view = GetPacketView(std::move(builder2)); controller.OnPdu(base_view); - auto builder3 = EnhancedInformationFrameBuilder::Create(1, 2, Final::NOT_SET, 0, SegmentationAndReassembly::END, - std::move(segment3)); + auto builder3 = EnhancedInformationFrameBuilder::Create( + 1, 2, Final::NOT_SET, 0, SegmentationAndReassembly::END, std::move(segment3)); base_view = GetPacketView(std::move(builder3)); controller.OnPdu(base_view); sync_handler(queue_handler_); @@ -145,15 +146,16 @@ TEST_F(ErtmDataControllerTest, reassemble_invalid_sdu_size_in_start_frame_will_d auto segment1 = CreateSdu({'a'}); auto segment2 = CreateSdu({'b', 'c'}); auto segment3 = CreateSdu({'d', 'e', 'f'}); - auto builder1 = EnhancedInformationStartFrameBuilder::Create(1, 0, Final::NOT_SET, 0, 10, std::move(segment1)); + auto builder1 = EnhancedInformationStartFrameBuilder::Create(1, 0, Final::NOT_SET, 0, 10, + std::move(segment1)); auto base_view = GetPacketView(std::move(builder1)); controller.OnPdu(base_view); - auto builder2 = EnhancedInformationFrameBuilder::Create(1, 1, Final::NOT_SET, 0, - SegmentationAndReassembly::CONTINUATION, std::move(segment2)); + auto builder2 = EnhancedInformationFrameBuilder::Create( + 1, 1, Final::NOT_SET, 0, SegmentationAndReassembly::CONTINUATION, std::move(segment2)); base_view = GetPacketView(std::move(builder2)); controller.OnPdu(base_view); - auto builder3 = EnhancedInformationFrameBuilder::Create(1, 2, Final::NOT_SET, 0, SegmentationAndReassembly::END, - std::move(segment3)); + auto builder3 = EnhancedInformationFrameBuilder::Create( + 1, 2, Final::NOT_SET, 0, SegmentationAndReassembly::END, std::move(segment3)); base_view = GetPacketView(std::move(builder3)); EXPECT_CALL(link, SendDisconnectionRequest(1, 1)); controller.OnPdu(base_view); @@ -194,7 +196,7 @@ TEST_F(ErtmDataControllerTest, receive_packet_with_fcs) { controller.EnableFcs(true); auto segment = CreateSdu({'a', 'b', 'c', 'd'}); auto builder = EnhancedInformationFrameWithFcsBuilder::Create( - 1, 0, Final::NOT_SET, 0, SegmentationAndReassembly::UNSEGMENTED, std::move(segment)); + 1, 0, Final::NOT_SET, 0, SegmentationAndReassembly::UNSEGMENTED, std::move(segment)); auto base_view = GetPacketView(std::move(builder)); controller.OnPdu(base_view); sync_handler(queue_handler_); diff --git a/system/gd/l2cap/internal/fixed_channel_allocator.h b/system/gd/l2cap/internal/fixed_channel_allocator.h index e5cea2fb90d..498d9242ad0 100644 --- a/system/gd/l2cap/internal/fixed_channel_allocator.h +++ b/system/gd/l2cap/internal/fixed_channel_allocator.h @@ -35,67 +35,53 @@ class DumpsysHelper; namespace internal { -// Helper class for keeping channels in a Link. It allocates and frees Channel object, and supports querying whether a -// channel is in use +// Helper class for keeping channels in a Link. It allocates and frees Channel object, and supports +// querying whether a channel is in use template class FixedChannelAllocator { - public: - FixedChannelAllocator(LinkType* link, os::Handler* l2cap_handler) : link_(link), l2cap_handler_(l2cap_handler) { +public: + FixedChannelAllocator(LinkType* link, os::Handler* l2cap_handler) + : link_(link), l2cap_handler_(l2cap_handler) { log::assert_that(link_ != nullptr, "assert failed: link_ != nullptr"); log::assert_that(l2cap_handler_ != nullptr, "assert failed: l2cap_handler_ != nullptr"); } virtual ~FixedChannelAllocator() = default; - // Allocates a channel. If cid is used, return nullptr. NOTE: The returned BaseFixedChannelImpl object is still - // owned by the channel allocator, NOT the client. + // Allocates a channel. If cid is used, return nullptr. NOTE: The returned BaseFixedChannelImpl + // object is still owned by the channel allocator, NOT the client. virtual std::shared_ptr AllocateChannel(Cid cid) { - log::assert_that( - !IsChannelAllocated(cid), - "Cid 0x{:x} for link {} is already in use", - cid, - ToLoggableStr(*link_)); - - log::assert_that( - cid >= kFirstFixedChannel && cid <= kLastFixedChannel, "Cid {} out of bound", cid); - auto elem = channels_.try_emplace(cid, std::make_shared(cid, link_, l2cap_handler_)); - log::assert_that( - elem.second, - "Failed to create channel for cid 0x{:x} link {}", - cid, - ToLoggableStr(*link_)); // TODO RENAME ADDRESS_TO_LOGGABLE_CSTR + log::assert_that(!IsChannelAllocated(cid), "Cid 0x{:x} for link {} is already in use", cid, + ToLoggableStr(*link_)); + + log::assert_that(cid >= kFirstFixedChannel && cid <= kLastFixedChannel, "Cid {} out of bound", + cid); + auto elem = channels_.try_emplace( + cid, std::make_shared(cid, link_, l2cap_handler_)); + log::assert_that(elem.second, "Failed to create channel for cid 0x{:x} link {}", cid, + ToLoggableStr(*link_)); // TODO RENAME ADDRESS_TO_LOGGABLE_CSTR log::assert_that(elem.first->second != nullptr, "assert failed: elem.first->second != nullptr"); return elem.first->second; } // Frees a channel. If cid doesn't exist, it will crash virtual void FreeChannel(Cid cid) { - log::assert_that( - IsChannelAllocated(cid), - "Channel is not in use: cid {}, link {}", - cid, - ToLoggableStr(*link_)); + log::assert_that(IsChannelAllocated(cid), "Channel is not in use: cid {}, link {}", cid, + ToLoggableStr(*link_)); channels_.erase(cid); } - virtual bool IsChannelAllocated(Cid cid) const { - return channels_.find(cid) != channels_.end(); - } + virtual bool IsChannelAllocated(Cid cid) const { return channels_.find(cid) != channels_.end(); } virtual std::shared_ptr FindChannel(Cid cid) { - log::assert_that( - IsChannelAllocated(cid), - "Channel is not in use: cid {}, link {}", - cid, - ToLoggableStr(*link_)); + log::assert_that(IsChannelAllocated(cid), "Channel is not in use: cid {}, link {}", cid, + ToLoggableStr(*link_)); return channels_.find(cid)->second; } - virtual size_t NumberOfChannels() const { - return channels_.size(); - } + virtual size_t NumberOfChannels() const { return channels_.size(); } virtual void OnAclDisconnected(hci::ErrorCode hci_status) { for (auto& elem : channels_) { @@ -113,7 +99,7 @@ class FixedChannelAllocator { return ref_count; } - private: +private: friend class bluetooth::l2cap::classic::internal::DumpsysHelper; LinkType* link_; os::Handler* l2cap_handler_; diff --git a/system/gd/l2cap/internal/fixed_channel_allocator_test.cc b/system/gd/l2cap/internal/fixed_channel_allocator_test.cc index 5295cc733b0..49416bf3687 100644 --- a/system/gd/l2cap/internal/fixed_channel_allocator_test.cc +++ b/system/gd/l2cap/internal/fixed_channel_allocator_test.cc @@ -15,13 +15,14 @@ */ #include "l2cap/internal/fixed_channel_allocator.h" -#include "l2cap/classic/internal/fixed_channel_impl_mock.h" -#include "l2cap/classic/internal/link_mock.h" -#include "l2cap/internal/parameter_provider_mock.h" #include #include +#include "l2cap/classic/internal/fixed_channel_impl_mock.h" +#include "l2cap/classic/internal/link_mock.h" +#include "l2cap/internal/parameter_provider_mock.h" + namespace bluetooth { namespace l2cap { namespace internal { @@ -31,10 +32,11 @@ using l2cap::classic::internal::testing::MockLink; using testing::MockParameterProvider; using ::testing::Return; -const hci::AddressWithType device{{{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}, hci::AddressType::PUBLIC_IDENTITY_ADDRESS}; +const hci::AddressWithType device{{{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}, + hci::AddressType::PUBLIC_IDENTITY_ADDRESS}; class L2capFixedChannelAllocatorTest : public ::testing::Test { - protected: +protected: void SetUp() override { thread_ = new os::Thread("test_thread", os::Thread::Priority::NORMAL); handler_ = new os::Handler(thread_); @@ -42,8 +44,8 @@ class L2capFixedChannelAllocatorTest : public ::testing::Test { mock_classic_link_ = new MockLink(handler_, mock_parameter_provider_); EXPECT_CALL(*mock_classic_link_, GetDevice()).WillRepeatedly(Return(device)); // Use classic as a place holder - channel_allocator_ = - std::make_unique>(mock_classic_link_, handler_); + channel_allocator_ = std::make_unique>( + mock_classic_link_, handler_); } void TearDown() override { diff --git a/system/gd/l2cap/internal/ilink.h b/system/gd/l2cap/internal/ilink.h index bc978c86d57..245847f70df 100644 --- a/system/gd/l2cap/internal/ilink.h +++ b/system/gd/l2cap/internal/ilink.h @@ -27,7 +27,7 @@ namespace internal { * Common interface for link (Classic ACL and LE) */ class ILink { - public: +public: virtual ~ILink() = default; virtual void SendDisconnectionRequest(Cid local_cid, Cid remote_cid) = 0; virtual hci::AddressWithType GetDevice() const = 0; diff --git a/system/gd/l2cap/internal/ilink_mock.h b/system/gd/l2cap/internal/ilink_mock.h index 29250f598b5..8343d17f180 100644 --- a/system/gd/l2cap/internal/ilink_mock.h +++ b/system/gd/l2cap/internal/ilink_mock.h @@ -16,10 +16,10 @@ #pragma once -#include "l2cap/internal/ilink.h" - #include +#include "l2cap/internal/ilink.h" + // Unit test interfaces namespace bluetooth { namespace l2cap { @@ -27,7 +27,7 @@ namespace internal { namespace testing { class MockILink : public ILink { - public: +public: MOCK_METHOD(hci::AddressWithType, GetDevice, (), (const, override)); MOCK_METHOD(void, SendDisconnectionRequest, (Cid, Cid), (override)); MOCK_METHOD(void, SendLeCredit, (Cid, uint16_t), (override)); diff --git a/system/gd/l2cap/internal/le_credit_based_channel_data_controller.cc b/system/gd/l2cap/internal/le_credit_based_channel_data_controller.cc index 35aab4085b5..d8f3cd03d2a 100644 --- a/system/gd/l2cap/internal/le_credit_based_channel_data_controller.cc +++ b/system/gd/l2cap/internal/le_credit_based_channel_data_controller.cc @@ -28,9 +28,13 @@ namespace l2cap { namespace internal { LeCreditBasedDataController::LeCreditBasedDataController(ILink* link, Cid cid, Cid remote_cid, - UpperQueueDownEnd* channel_queue_end, os::Handler* handler, - Scheduler* scheduler) - : cid_(cid), remote_cid_(remote_cid), enqueue_buffer_(channel_queue_end), handler_(handler), scheduler_(scheduler), + UpperQueueDownEnd* channel_queue_end, + os::Handler* handler, Scheduler* scheduler) + : cid_(cid), + remote_cid_(remote_cid), + enqueue_buffer_(channel_queue_end), + handler_(handler), + scheduler_(scheduler), link_(link) {} void LeCreditBasedDataController::OnSdu(std::unique_ptr sdu) { @@ -73,10 +77,8 @@ void LeCreditBasedDataController::OnPdu(packet::PacketView pdu) { return; } if (basic_frame_view.size() > mps_) { - log::warn( - "Received frame size {} > mps {}, dropping the packet", - static_cast(basic_frame_view.size()), - mps_); + log::warn("Received frame size {} > mps {}, dropping the packet", + static_cast(basic_frame_view.size()), mps_); return; } if (remaining_sdu_continuation_packet_size_ == 0) { @@ -95,10 +97,12 @@ void LeCreditBasedDataController::OnPdu(packet::PacketView pdu) { reassembly_stage_.AppendPacketView(payload); } if (remaining_sdu_continuation_packet_size_ == 0) { - enqueue_buffer_.Enqueue(std::make_unique>(reassembly_stage_), handler_); + enqueue_buffer_.Enqueue(std::make_unique>(reassembly_stage_), + handler_); } else if (remaining_sdu_continuation_packet_size_ < 0 || reassembly_stage_.size() > mtu_) { log::warn("Received larger SDU size than expected"); - reassembly_stage_ = PacketViewForReassembly(PacketView(std::make_shared>())); + reassembly_stage_ = PacketViewForReassembly( + PacketView(std::make_shared>())); remaining_sdu_continuation_packet_size_ = 0; link_->SendDisconnectionRequest(cid_, remote_cid_); } @@ -113,13 +117,9 @@ std::unique_ptr LeCreditBasedDataController::GetNextP return next; } -void LeCreditBasedDataController::SetMtu(Mtu mtu) { - mtu_ = mtu; -} +void LeCreditBasedDataController::SetMtu(Mtu mtu) { mtu_ = mtu; } -void LeCreditBasedDataController::SetMps(uint16_t mps) { - mps_ = mps; -} +void LeCreditBasedDataController::SetMps(uint16_t mps) { mps_ = mps; } void LeCreditBasedDataController::OnCredit(uint16_t credits) { int total_credits = credits_ + credits; diff --git a/system/gd/l2cap/internal/le_credit_based_channel_data_controller.h b/system/gd/l2cap/internal/le_credit_based_channel_data_controller.h index b9e510f1431..aa10b0fb7d9 100644 --- a/system/gd/l2cap/internal/le_credit_based_channel_data_controller.h +++ b/system/gd/l2cap/internal/le_credit_based_channel_data_controller.h @@ -38,12 +38,13 @@ namespace l2cap { namespace internal { class LeCreditBasedDataController : public DataController { - public: +public: using UpperEnqueue = packet::PacketView; using UpperDequeue = packet::BasePacketBuilder; using UpperQueueDownEnd = common::BidiQueueEnd; - LeCreditBasedDataController(ILink* link, Cid cid, Cid remote_cid, UpperQueueDownEnd* channel_queue_end, - os::Handler* handler, Scheduler* scheduler); + LeCreditBasedDataController(ILink* link, Cid cid, Cid remote_cid, + UpperQueueDownEnd* channel_queue_end, os::Handler* handler, + Scheduler* scheduler); void OnSdu(std::unique_ptr sdu) override; void OnPdu(packet::PacketView pdu) override; @@ -51,7 +52,7 @@ class LeCreditBasedDataController : public DataController { void EnableFcs(bool /* enabled */) override {} void SetRetransmissionAndFlowControlOptions( - const RetransmissionAndFlowControlConfigurationOption& /* option */) override {} + const RetransmissionAndFlowControlConfigurationOption& /* option */) override {} // TODO: Set MTU and MPS from signalling channel void SetMtu(Mtu mtu); @@ -59,7 +60,7 @@ class LeCreditBasedDataController : public DataController { // TODO: Handle credits void OnCredit(uint16_t credits); - private: +private: Cid cid_; Cid remote_cid_; os::EnqueueBuffer enqueue_buffer_; @@ -73,13 +74,12 @@ class LeCreditBasedDataController : public DataController { uint16_t pending_frames_count_ = 0; class PacketViewForReassembly : public packet::PacketView { - public: + public: PacketViewForReassembly(const PacketView& packetView) : PacketView(packetView) {} - void AppendPacketView(packet::PacketView to_append) { - Append(to_append); - } + void AppendPacketView(packet::PacketView to_append) { Append(to_append); } }; - PacketViewForReassembly reassembly_stage_{PacketView(std::make_shared>())}; + PacketViewForReassembly reassembly_stage_{ + PacketView(std::make_shared>())}; uint16_t remaining_sdu_continuation_packet_size_ = 0; }; diff --git a/system/gd/l2cap/internal/le_credit_based_channel_data_controller_test.cc b/system/gd/l2cap/internal/le_credit_based_channel_data_controller_test.cc index ab23dd219ad..b561fe31918 100644 --- a/system/gd/l2cap/internal/le_credit_based_channel_data_controller_test.cc +++ b/system/gd/l2cap/internal/le_credit_based_channel_data_controller_test.cc @@ -49,7 +49,7 @@ void sync_handler(os::Handler* handler) { } class LeCreditBasedDataControllerTest : public ::testing::Test { - protected: +protected: void SetUp() override { thread_ = new os::Thread("test_thread", os::Thread::Priority::NORMAL); user_handler_ = new os::Handler(thread_); @@ -73,7 +73,8 @@ TEST_F(LeCreditBasedDataControllerTest, transmit_unsegmented) { common::BidiQueue channel_queue{10}; testing::MockScheduler scheduler; testing::MockILink link; - LeCreditBasedDataController controller{&link, 0x41, 0x41, channel_queue.GetDownEnd(), queue_handler_, &scheduler}; + LeCreditBasedDataController controller{ + &link, 0x41, 0x41, channel_queue.GetDownEnd(), queue_handler_, &scheduler}; controller.OnCredit(10); EXPECT_CALL(scheduler, OnPacketsReady(0x41, 1)); controller.OnSdu(CreateSdu({'a', 'b', 'c', 'd'})); @@ -93,7 +94,8 @@ TEST_F(LeCreditBasedDataControllerTest, transmit_segmented) { common::BidiQueue channel_queue{10}; testing::MockScheduler scheduler; testing::MockILink link; - LeCreditBasedDataController controller{&link, 0x41, 0x41, channel_queue.GetDownEnd(), queue_handler_, &scheduler}; + LeCreditBasedDataController controller{ + &link, 0x41, 0x41, channel_queue.GetDownEnd(), queue_handler_, &scheduler}; controller.OnCredit(10); controller.SetMps(4); EXPECT_CALL(scheduler, OnPacketsReady(0x41, 2)); @@ -125,7 +127,8 @@ TEST_F(LeCreditBasedDataControllerTest, receive_unsegmented) { common::BidiQueue channel_queue{10}; testing::MockScheduler scheduler; testing::MockILink link; - LeCreditBasedDataController controller{&link, 0x41, 0x41, channel_queue.GetDownEnd(), queue_handler_, &scheduler}; + LeCreditBasedDataController controller{ + &link, 0x41, 0x41, channel_queue.GetDownEnd(), queue_handler_, &scheduler}; controller.OnCredit(10); auto segment = CreateSdu({'a', 'b', 'c', 'd'}); auto builder = FirstLeInformationFrameBuilder::Create(0x41, 4, std::move(segment)); @@ -142,7 +145,8 @@ TEST_F(LeCreditBasedDataControllerTest, receive_segmented) { common::BidiQueue channel_queue{10}; testing::MockScheduler scheduler; testing::MockILink link; - LeCreditBasedDataController controller{&link, 0x41, 0x41, channel_queue.GetDownEnd(), queue_handler_, &scheduler}; + LeCreditBasedDataController controller{ + &link, 0x41, 0x41, channel_queue.GetDownEnd(), queue_handler_, &scheduler}; controller.OnCredit(10); auto segment1 = CreateSdu({'a', 'b', 'c', 'd'}); auto builder1 = FirstLeInformationFrameBuilder::Create(0x41, 7, std::move(segment1)); @@ -164,7 +168,8 @@ TEST_F(LeCreditBasedDataControllerTest, receive_segmented_with_wrong_sdu_length) common::BidiQueue channel_queue{10}; testing::MockScheduler scheduler; testing::MockILink link; - LeCreditBasedDataController controller{&link, 0x41, 0x41, channel_queue.GetDownEnd(), queue_handler_, &scheduler}; + LeCreditBasedDataController controller{ + &link, 0x41, 0x41, channel_queue.GetDownEnd(), queue_handler_, &scheduler}; controller.OnCredit(10); auto segment1 = CreateSdu({'a', 'b', 'c', 'd'}); auto builder1 = FirstLeInformationFrameBuilder::Create(0x41, 5, std::move(segment1)); diff --git a/system/gd/l2cap/internal/parameter_provider.h b/system/gd/l2cap/internal/parameter_provider.h index bec0322481e..bb9cb37f7a2 100644 --- a/system/gd/l2cap/internal/parameter_provider.h +++ b/system/gd/l2cap/internal/parameter_provider.h @@ -28,7 +28,7 @@ namespace internal { * All methods are virtual so that they can be override in unit tests */ class ParameterProvider { - public: +public: virtual ~ParameterProvider() = default; virtual std::chrono::milliseconds GetClassicLinkIdleDisconnectTimeout() { return std::chrono::seconds(20); @@ -36,12 +36,8 @@ class ParameterProvider { virtual std::chrono::milliseconds GetLeLinkIdleDisconnectTimeout() { return std::chrono::seconds(1); } - virtual uint16_t GetLeMps() { - return 251; - } - virtual uint16_t GetLeInitialCredit() { - return 100; - } + virtual uint16_t GetLeMps() { return 251; } + virtual uint16_t GetLeInitialCredit() { return 100; } }; } // namespace internal diff --git a/system/gd/l2cap/internal/parameter_provider_mock.h b/system/gd/l2cap/internal/parameter_provider_mock.h index 823cf8afe94..218464c7402 100644 --- a/system/gd/l2cap/internal/parameter_provider_mock.h +++ b/system/gd/l2cap/internal/parameter_provider_mock.h @@ -15,10 +15,10 @@ */ #pragma once -#include "l2cap/internal/parameter_provider.h" - #include +#include "l2cap/internal/parameter_provider.h" + // Unit test interfaces namespace bluetooth { namespace l2cap { @@ -26,7 +26,7 @@ namespace internal { namespace testing { class MockParameterProvider : public ParameterProvider { - public: +public: MOCK_METHOD(std::chrono::milliseconds, GetClassicLinkIdleDisconnectTimeout, (), (override)); MOCK_METHOD(std::chrono::milliseconds, GetLeLinkIdleDisconnectTimeout, (), (override)); }; diff --git a/system/gd/l2cap/internal/receiver.cc b/system/gd/l2cap/internal/receiver.cc index 28da903b35c..db5bc7b2086 100644 --- a/system/gd/l2cap/internal/receiver.cc +++ b/system/gd/l2cap/internal/receiver.cc @@ -27,23 +27,20 @@ namespace bluetooth { namespace l2cap { namespace internal { -Receiver::Receiver( - LowerQueueUpEnd* link_queue_up_end, os::Handler* handler, DataPipelineManager* data_pipeline_manager_) +Receiver::Receiver(LowerQueueUpEnd* link_queue_up_end, os::Handler* handler, + DataPipelineManager* data_pipeline_manager_) : link_queue_up_end_(link_queue_up_end), handler_(handler), buffer_timer_(handler), data_pipeline_manager_(data_pipeline_manager_) { - log::assert_that( - link_queue_up_end_ != nullptr && handler_ != nullptr, - "assert failed: link_queue_up_end_ != nullptr && handler_ != nullptr"); - link_queue_up_end_->RegisterDequeue(handler_, - common::Bind(&Receiver::link_queue_dequeue_callback, common::Unretained(this))); + log::assert_that(link_queue_up_end_ != nullptr && handler_ != nullptr, + "assert failed: link_queue_up_end_ != nullptr && handler_ != nullptr"); + link_queue_up_end_->RegisterDequeue( + handler_, common::Bind(&Receiver::link_queue_dequeue_callback, common::Unretained(this))); } // Invoked from external handler/thread (ModuleRegistry) -Receiver::~Receiver() { - link_queue_up_end_->UnregisterDequeue(); -} +Receiver::~Receiver() { link_queue_up_end_->UnregisterDequeue(); } // Invoked from external (Queue Reactable) void Receiver::link_queue_dequeue_callback() { @@ -61,7 +58,8 @@ void Receiver::link_queue_dequeue_callback() { buffered_packets_.emplace(*packet); log::warn("Enqueued the unexpected packet. Current queue size: {}", buffered_packets_.size()); buffer_timer_.Schedule( - common::BindOnce(&Receiver::check_buffered_packets, common::Unretained(this)), std::chrono::milliseconds(500)); + common::BindOnce(&Receiver::check_buffered_packets, common::Unretained(this)), + std::chrono::milliseconds(500)); return; } diff --git a/system/gd/l2cap/internal/receiver.h b/system/gd/l2cap/internal/receiver.h index a3977dc207d..45681d21d02 100644 --- a/system/gd/l2cap/internal/receiver.h +++ b/system/gd/l2cap/internal/receiver.h @@ -39,15 +39,15 @@ namespace internal { class DataPipelineManager; /** - * Handle receiving L2CAP PDUs from link queue and distribute them into into channel data controllers. - * Dequeue incoming packets from LinkQueueUpEnd, and enqueue it to ChannelQueueDownEnd. Note: If a channel - * cannot dequeue from ChannelQueueDownEnd so that the buffer for incoming packet is full, further incoming packets will - * be dropped. - * The Reassembler keeps the reference to ChannelImpl objects, because it needs to check channel mode and parameters. - * The Reassembler also keeps the reference to Scheduler, to get Segmenter and send signals (Tx, Rx seq) to it. + * Handle receiving L2CAP PDUs from link queue and distribute them into into channel data + * controllers. Dequeue incoming packets from LinkQueueUpEnd, and enqueue it to ChannelQueueDownEnd. + * Note: If a channel cannot dequeue from ChannelQueueDownEnd so that the buffer for incoming packet + * is full, further incoming packets will be dropped. The Reassembler keeps the reference to + * ChannelImpl objects, because it needs to check channel mode and parameters. The Reassembler also + * keeps the reference to Scheduler, to get Segmenter and send signals (Tx, Rx seq) to it. */ class Receiver { - public: +public: using UpperEnqueue = packet::PacketView; using UpperDequeue = packet::BasePacketBuilder; using UpperQueueDownEnd = common::BidiQueueEnd; @@ -55,10 +55,11 @@ class Receiver { using LowerDequeue = UpperEnqueue; using LowerQueueUpEnd = common::BidiQueueEnd; - Receiver(LowerQueueUpEnd* link_queue_up_end, os::Handler* handler, DataPipelineManager* data_pipeline_manager); + Receiver(LowerQueueUpEnd* link_queue_up_end, os::Handler* handler, + DataPipelineManager* data_pipeline_manager); ~Receiver(); - private: +private: LowerQueueUpEnd* link_queue_up_end_; os::Handler* handler_; os::Alarm buffer_timer_; diff --git a/system/gd/l2cap/internal/scheduler.h b/system/gd/l2cap/internal/scheduler.h index a0a242dc939..56586216be6 100644 --- a/system/gd/l2cap/internal/scheduler.h +++ b/system/gd/l2cap/internal/scheduler.h @@ -41,7 +41,7 @@ namespace internal { * for incoming packet is full, further incoming packets will be dropped. */ class Scheduler { - public: +public: using UpperEnqueue = packet::PacketView; using UpperDequeue = packet::BasePacketBuilder; using UpperQueueDownEnd = common::BidiQueueEnd; diff --git a/system/gd/l2cap/internal/scheduler_fifo.cc b/system/gd/l2cap/internal/scheduler_fifo.cc index ee29ec85ba3..732799bd9b0 100644 --- a/system/gd/l2cap/internal/scheduler_fifo.cc +++ b/system/gd/l2cap/internal/scheduler_fifo.cc @@ -25,11 +25,13 @@ namespace bluetooth { namespace l2cap { namespace internal { -Fifo::Fifo(DataPipelineManager* data_pipeline_manager, LowerQueueUpEnd* link_queue_up_end, os::Handler* handler) - : data_pipeline_manager_(data_pipeline_manager), link_queue_up_end_(link_queue_up_end), handler_(handler) { - log::assert_that( - link_queue_up_end_ != nullptr && handler_ != nullptr, - "assert failed: link_queue_up_end_ != nullptr && handler_ != nullptr"); +Fifo::Fifo(DataPipelineManager* data_pipeline_manager, LowerQueueUpEnd* link_queue_up_end, + os::Handler* handler) + : data_pipeline_manager_(data_pipeline_manager), + link_queue_up_end_(link_queue_up_end), + handler_(handler) { + log::assert_that(link_queue_up_end_ != nullptr && handler_ != nullptr, + "assert failed: link_queue_up_end_ != nullptr && handler_ != nullptr"); } // Invoked from some external Handler context @@ -74,9 +76,8 @@ void Fifo::RemoveChannel(Cid cid) { // Invoked from some external Queue Reactable context std::unique_ptr Fifo::link_queue_enqueue_callback() { - log::assert_that( - !next_to_dequeue_and_num_packets.empty(), - "assert failed: !next_to_dequeue_and_num_packets.empty()"); + log::assert_that(!next_to_dequeue_and_num_packets.empty(), + "assert failed: !next_to_dequeue_and_num_packets.empty()"); auto& channel_id_and_number_packets = next_to_dequeue_and_num_packets.front(); auto channel_id = channel_id_and_number_packets.first; channel_id_and_number_packets.second--; @@ -96,8 +97,8 @@ void Fifo::try_register_link_queue_enqueue() { if (link_queue_enqueue_registered_.exchange(true)) { return; } - link_queue_up_end_->RegisterEnqueue(handler_, - common::Bind(&Fifo::link_queue_enqueue_callback, common::Unretained(this))); + link_queue_up_end_->RegisterEnqueue( + handler_, common::Bind(&Fifo::link_queue_enqueue_callback, common::Unretained(this))); } } // namespace internal diff --git a/system/gd/l2cap/internal/scheduler_fifo.h b/system/gd/l2cap/internal/scheduler_fifo.h index 23a292c6c21..dec737e1e20 100644 --- a/system/gd/l2cap/internal/scheduler_fifo.h +++ b/system/gd/l2cap/internal/scheduler_fifo.h @@ -37,14 +37,15 @@ namespace internal { class DataPipelineManager; class Fifo : public Scheduler { - public: - Fifo(DataPipelineManager* data_pipeline_manager, LowerQueueUpEnd* link_queue_up_end, os::Handler* handler); +public: + Fifo(DataPipelineManager* data_pipeline_manager, LowerQueueUpEnd* link_queue_up_end, + os::Handler* handler); ~Fifo(); void OnPacketsReady(Cid cid, int number_packets) override; void SetChannelTxPriority(Cid cid, bool high_priority) override; void RemoveChannel(Cid cid) override; - private: +private: DataPipelineManager* data_pipeline_manager_; LowerQueueUpEnd* link_queue_up_end_; os::Handler* handler_; diff --git a/system/gd/l2cap/internal/scheduler_fifo_test.cc b/system/gd/l2cap/internal/scheduler_fifo_test.cc index 9a0579f148d..a7a430cb18c 100644 --- a/system/gd/l2cap/internal/scheduler_fifo_test.cc +++ b/system/gd/l2cap/internal/scheduler_fifo_test.cc @@ -50,7 +50,7 @@ PacketView GetPacketView(std::unique_ptr GetNextPacket() override { auto next = std::move(next_packets.front()); next_packets.pop(); @@ -61,7 +61,7 @@ class MyDataController : public testing::MockDataController { }; class L2capSchedulerFifoTest : public ::testing::Test { - protected: +protected: void SetUp() override { thread_ = new os::Thread("test_thread", os::Thread::Priority::NORMAL); queue_handler_ = new os::Handler(thread_); @@ -81,7 +81,8 @@ class L2capSchedulerFifoTest : public ::testing::Test { os::Handler* queue_handler_ = nullptr; os::MockIQueueDequeue dequeue_; os::MockIQueueEnqueue enqueue_; - common::BidiQueueEnd queue_end_{&enqueue_, &dequeue_}; + common::BidiQueueEnd queue_end_{&enqueue_, + &dequeue_}; testing::MockDataPipelineManager* mock_data_pipeline_manager_ = nullptr; MyDataController data_controller_1_; MyDataController data_controller_2_; @@ -91,7 +92,8 @@ class L2capSchedulerFifoTest : public ::testing::Test { TEST_F(L2capSchedulerFifoTest, send_packet) { auto frame = BasicFrameBuilder::Create(1, CreateSdu({'a', 'b', 'c'})); data_controller_1_.next_packets.push(std::move(frame)); - EXPECT_CALL(*mock_data_pipeline_manager_, GetDataController(_)).WillOnce(Return(&data_controller_1_)); + EXPECT_CALL(*mock_data_pipeline_manager_, GetDataController(_)) + .WillOnce(Return(&data_controller_1_)); EXPECT_CALL(*mock_data_pipeline_manager_, OnPacketSent(1)); fifo_->OnPacketsReady(1, 1); enqueue_.run_enqueue(); @@ -111,8 +113,10 @@ TEST_F(L2capSchedulerFifoTest, prioritize_channel) { frame = BasicFrameBuilder::Create(2, CreateSdu({'d', 'e', 'f'})); data_controller_2_.next_packets.push(std::move(frame)); - EXPECT_CALL(*mock_data_pipeline_manager_, GetDataController(1)).WillRepeatedly(Return(&data_controller_1_)); - EXPECT_CALL(*mock_data_pipeline_manager_, GetDataController(2)).WillRepeatedly(Return(&data_controller_2_)); + EXPECT_CALL(*mock_data_pipeline_manager_, GetDataController(1)) + .WillRepeatedly(Return(&data_controller_1_)); + EXPECT_CALL(*mock_data_pipeline_manager_, GetDataController(2)) + .WillRepeatedly(Return(&data_controller_2_)); EXPECT_CALL(*mock_data_pipeline_manager_, OnPacketSent(1)); EXPECT_CALL(*mock_data_pipeline_manager_, OnPacketSent(2)); fifo_->SetChannelTxPriority(1, true); @@ -144,8 +148,10 @@ TEST_F(L2capSchedulerFifoTest, remove_channel) { frame = BasicFrameBuilder::Create(2, CreateSdu({'d', 'e', 'f'})); data_controller_2_.next_packets.push(std::move(frame)); - EXPECT_CALL(*mock_data_pipeline_manager_, GetDataController(1)).WillRepeatedly(Return(&data_controller_1_)); - EXPECT_CALL(*mock_data_pipeline_manager_, GetDataController(2)).WillRepeatedly(Return(&data_controller_2_)); + EXPECT_CALL(*mock_data_pipeline_manager_, GetDataController(1)) + .WillRepeatedly(Return(&data_controller_1_)); + EXPECT_CALL(*mock_data_pipeline_manager_, GetDataController(2)) + .WillRepeatedly(Return(&data_controller_2_)); EXPECT_CALL(*mock_data_pipeline_manager_, OnPacketSent(2)); fifo_->OnPacketsReady(1, 1); fifo_->OnPacketsReady(2, 1); diff --git a/system/gd/l2cap/internal/scheduler_mock.h b/system/gd/l2cap/internal/scheduler_mock.h index c0ac4d7596d..0ec527b7418 100644 --- a/system/gd/l2cap/internal/scheduler_mock.h +++ b/system/gd/l2cap/internal/scheduler_mock.h @@ -15,11 +15,11 @@ */ #pragma once +#include + #include "l2cap/internal/channel_impl.h" #include "l2cap/internal/scheduler.h" -#include - // Unit test interfaces namespace bluetooth { namespace l2cap { @@ -27,7 +27,7 @@ namespace internal { namespace testing { class MockScheduler : public Scheduler { - public: +public: MOCK_METHOD(void, OnPacketsReady, (Cid cid, int number_packet), (override)); }; diff --git a/system/gd/l2cap/internal/sender.cc b/system/gd/l2cap/internal/sender.cc index e9e6ea6bc53..c03a30b2c25 100644 --- a/system/gd/l2cap/internal/sender.cc +++ b/system/gd/l2cap/internal/sender.cc @@ -14,6 +14,8 @@ * limitations under the License. */ +#include "l2cap/internal/sender.h" + #include #include "common/bind.h" @@ -21,7 +23,6 @@ #include "l2cap/internal/enhanced_retransmission_mode_channel_data_controller.h" #include "l2cap/internal/le_credit_based_channel_data_controller.h" #include "l2cap/internal/scheduler.h" -#include "l2cap/internal/sender.h" #include "os/handler.h" #include "os/log.h" @@ -29,27 +30,36 @@ namespace bluetooth { namespace l2cap { namespace internal { -Sender::Sender(os::Handler* handler, ILink* link, Scheduler* scheduler, std::shared_ptr channel) - : handler_(handler), link_(link), queue_end_(channel->GetQueueDownEnd()), scheduler_(scheduler), - channel_id_(channel->GetCid()), remote_channel_id_(channel->GetRemoteCid()), - data_controller_(std::make_unique(channel_id_, remote_channel_id_, queue_end_, handler_, - scheduler_)) { +Sender::Sender(os::Handler* handler, ILink* link, Scheduler* scheduler, + std::shared_ptr channel) + : handler_(handler), + link_(link), + queue_end_(channel->GetQueueDownEnd()), + scheduler_(scheduler), + channel_id_(channel->GetCid()), + remote_channel_id_(channel->GetRemoteCid()), + data_controller_(std::make_unique( + channel_id_, remote_channel_id_, queue_end_, handler_, scheduler_)) { try_register_dequeue(); } -Sender::Sender(os::Handler* handler, ILink* link, Scheduler* scheduler, std::shared_ptr channel, - ChannelMode mode) - : handler_(handler), link_(link), queue_end_(channel->GetQueueDownEnd()), scheduler_(scheduler), - channel_id_(channel->GetCid()), remote_channel_id_(channel->GetRemoteCid()) { +Sender::Sender(os::Handler* handler, ILink* link, Scheduler* scheduler, + std::shared_ptr channel, ChannelMode mode) + : handler_(handler), + link_(link), + queue_end_(channel->GetQueueDownEnd()), + scheduler_(scheduler), + channel_id_(channel->GetCid()), + remote_channel_id_(channel->GetRemoteCid()) { if (mode == ChannelMode::BASIC) { - data_controller_ = - std::make_unique(channel_id_, remote_channel_id_, queue_end_, handler_, scheduler_); + data_controller_ = std::make_unique(channel_id_, remote_channel_id_, + queue_end_, handler_, scheduler_); } else if (mode == ChannelMode::ERTM) { - data_controller_ = - std::make_unique(link_, channel_id_, remote_channel_id_, queue_end_, handler_, scheduler_); + data_controller_ = std::make_unique(link_, channel_id_, remote_channel_id_, + queue_end_, handler_, scheduler_); } else if (mode == ChannelMode::LE_CREDIT_BASED) { - data_controller_ = std::make_unique(link_, channel_id_, remote_channel_id_, queue_end_, - handler_, scheduler_); + data_controller_ = std::make_unique( + link_, channel_id_, remote_channel_id_, queue_end_, handler_, scheduler_); } try_register_dequeue(); } @@ -69,23 +79,22 @@ std::unique_ptr Sender::GetNextPacket() { return data_controller_->GetNextPacket(); } -DataController* Sender::GetDataController() { - return data_controller_.get(); -} +DataController* Sender::GetDataController() { return data_controller_.get(); } void Sender::try_register_dequeue() { if (is_dequeue_registered_.exchange(true)) { return; } - queue_end_->RegisterDequeue(handler_, common::Bind(&Sender::dequeue_callback, common::Unretained(this))); + queue_end_->RegisterDequeue(handler_, + common::Bind(&Sender::dequeue_callback, common::Unretained(this))); } // From external context void Sender::dequeue_callback() { auto packet = queue_end_->TryDequeue(); log::assert_that(packet != nullptr, "assert failed: packet != nullptr"); - handler_->Post( - common::BindOnce(&DataController::OnSdu, common::Unretained(data_controller_.get()), std::move(packet))); + handler_->Post(common::BindOnce(&DataController::OnSdu, + common::Unretained(data_controller_.get()), std::move(packet))); if (is_dequeue_registered_.exchange(false)) { queue_end_->UnregisterDequeue(); } @@ -98,14 +107,15 @@ void Sender::UpdateClassicConfiguration(classic::internal::ChannelConfigurationS return; } if (mode == RetransmissionAndFlowControlModeOption::L2CAP_BASIC) { - data_controller_ = - std::make_unique(channel_id_, remote_channel_id_, queue_end_, handler_, scheduler_); + data_controller_ = std::make_unique(channel_id_, remote_channel_id_, + queue_end_, handler_, scheduler_); return; } if (mode == RetransmissionAndFlowControlModeOption::ENHANCED_RETRANSMISSION) { - data_controller_ = - std::make_unique(link_, channel_id_, remote_channel_id_, queue_end_, handler_, scheduler_); - RetransmissionAndFlowControlConfigurationOption option = config.local_retransmission_and_flow_control_; + data_controller_ = std::make_unique(link_, channel_id_, remote_channel_id_, + queue_end_, handler_, scheduler_); + RetransmissionAndFlowControlConfigurationOption option = + config.local_retransmission_and_flow_control_; option.tx_window_size_ = config.remote_retransmission_and_flow_control_.tx_window_size_; data_controller_->SetRetransmissionAndFlowControlOptions(option); data_controller_->EnableFcs(config.fcs_type_ == FcsType::DEFAULT); diff --git a/system/gd/l2cap/internal/sender.h b/system/gd/l2cap/internal/sender.h index 3e541a96b47..5e39d228c1b 100644 --- a/system/gd/l2cap/internal/sender.h +++ b/system/gd/l2cap/internal/sender.h @@ -42,10 +42,11 @@ class ILink; /** * A middle layer between L2CAP channel and outgoing packet scheduler. - * Fetches data (SDU) from an L2CAP channel queue end, handles L2CAP segmentation, and gives data to L2CAP scheduler. + * Fetches data (SDU) from an L2CAP channel queue end, handles L2CAP segmentation, and gives data to + * L2CAP scheduler. */ class Sender { - public: +public: using UpperEnqueue = packet::PacketView; using UpperDequeue = packet::BasePacketBuilder; using UpperQueueDownEnd = common::BidiQueueEnd; @@ -56,14 +57,15 @@ class Sender { LE_CREDIT_BASED = 10, }; - Sender(os::Handler* handler, ILink* link, Scheduler* scheduler, std::shared_ptr channel); - Sender(os::Handler* handler, ILink* link, Scheduler* scheduler, std::shared_ptr channel, - ChannelMode mode); + Sender(os::Handler* handler, ILink* link, Scheduler* scheduler, + std::shared_ptr channel); + Sender(os::Handler* handler, ILink* link, Scheduler* scheduler, + std::shared_ptr channel, ChannelMode mode); ~Sender(); /** - * Callback from scheduler to indicate that scheduler already dequeued a packet from sender's queue. - * Segmenter can continue dequeuing from channel queue end. + * Callback from scheduler to indicate that scheduler already dequeued a packet from sender's + * queue. Segmenter can continue dequeuing from channel queue end. */ void OnPacketSent(); @@ -75,7 +77,7 @@ class Sender { void UpdateClassicConfiguration(classic::internal::ChannelConfigurationState config); DataController* GetDataController(); - private: +private: os::Handler* handler_; ILink* link_; UpperQueueDownEnd* queue_end_; @@ -83,7 +85,8 @@ class Sender { const Cid channel_id_; const Cid remote_channel_id_; std::atomic_bool is_dequeue_registered_ = false; - RetransmissionAndFlowControlModeOption mode_ = RetransmissionAndFlowControlModeOption::L2CAP_BASIC; + RetransmissionAndFlowControlModeOption mode_ = + RetransmissionAndFlowControlModeOption::L2CAP_BASIC; std::unique_ptr data_controller_; void try_register_dequeue(); diff --git a/system/gd/l2cap/internal/sender_test.cc b/system/gd/l2cap/internal/sender_test.cc index 99a9b31d3fd..92a02d0ce14 100644 --- a/system/gd/l2cap/internal/sender_test.cc +++ b/system/gd/l2cap/internal/sender_test.cc @@ -18,6 +18,7 @@ #include #include + #include #include "l2cap/internal/channel_impl_mock.h" @@ -50,7 +51,7 @@ PacketView GetPacketView(std::unique_ptr enqueue_callback() { auto packet_one = CreateSdu({'a', 'b', 'c'}); channel_queue_.GetUpEnd()->UnregisterEnqueue(); return packet_one; } - protected: +protected: void SetUp() override { thread_ = new os::Thread("test_thread", os::Thread::Priority::NORMAL); user_handler_ = new os::Handler(thread_); queue_handler_ = new os::Handler(thread_); mock_channel_ = std::make_shared(); - EXPECT_CALL(*mock_channel_, GetQueueDownEnd()).WillRepeatedly(Return(channel_queue_.GetDownEnd())); + EXPECT_CALL(*mock_channel_, GetQueueDownEnd()) + .WillRepeatedly(Return(channel_queue_.GetDownEnd())); EXPECT_CALL(*mock_channel_, GetCid()).WillRepeatedly(Return(cid_)); EXPECT_CALL(*mock_channel_, GetRemoteCid()).WillRepeatedly(Return(cid_)); sender_ = new Sender(queue_handler_, &link_, &scheduler_, mock_channel_); @@ -106,7 +108,8 @@ TEST_F(L2capSenderTest, send_packet) { auto future = promise.get_future(); scheduler_.SetOnPacketsReady([&promise](Cid cid, int number_packets) { promise.set_value(); }); channel_queue_.GetUpEnd()->RegisterEnqueue( - queue_handler_, common::Bind(&L2capSenderTest::enqueue_callback, common::Unretained(this))); + queue_handler_, + common::Bind(&L2capSenderTest::enqueue_callback, common::Unretained(this))); auto status = future.wait_for(std::chrono::milliseconds(3)); EXPECT_EQ(status, std::future_status::ready); auto packet = sender_->GetNextPacket(); diff --git a/system/gd/l2cap/l2cap_packet_fuzz_test.cc b/system/gd/l2cap/l2cap_packet_fuzz_test.cc index 90bd9653dad..f4fe81e7194 100644 --- a/system/gd/l2cap/l2cap_packet_fuzz_test.cc +++ b/system/gd/l2cap/l2cap_packet_fuzz_test.cc @@ -15,10 +15,9 @@ */ #define PACKET_FUZZ_TESTING -#include "l2cap/l2cap_packets.h" - #include +#include "l2cap/l2cap_packets.h" #include "os/log.h" #include "packet/bit_inserter.h" #include "packet/raw_builder.h" @@ -46,7 +45,9 @@ DEFINE_AND_REGISTER_ConfigurationRequestReflectionFuzzTest(l2cap_packet_fuzz_tes } // namespace bluetooth void RunL2capPacketFuzzTest(const uint8_t* data, size_t size) { - if (data == nullptr || size > 65536 /* Max ACL packet size */) return; + if (data == nullptr || size > 65536 /* Max ACL packet size */) { + return; + } for (auto test_function : bluetooth::l2cap::l2cap_packet_fuzz_tests) { test_function(data, size); } diff --git a/system/gd/l2cap/l2cap_packet_test.cc b/system/gd/l2cap/l2cap_packet_test.cc index add7d8d5c0e..0e87e806dd2 100644 --- a/system/gd/l2cap/l2cap_packet_test.cc +++ b/system/gd/l2cap/l2cap_packet_test.cc @@ -15,12 +15,12 @@ */ #define PACKET_TESTING -#include "l2cap/l2cap_packets.h" - #include + #include #include +#include "l2cap/l2cap_packets.h" #include "os/log.h" #include "packet/bit_inserter.h" #include "packet/raw_builder.h" @@ -33,21 +33,22 @@ namespace bluetooth { namespace l2cap { std::vector extended_information_start_frame = { - 0x0B, /* First size byte */ - 0x00, /* Second size byte */ - 0xc1, /* First ChannelId byte */ - 0xc2, /**/ - 0x4A, /* 0x12 ReqSeq, Final, IFrame */ - 0xD0, /* 0x13 ReqSeq */ - 0x89, /* 0x21 TxSeq sar = START */ - 0x8C, /* 0x23 TxSeq */ - 0x10, /* first length byte */ - 0x11, /**/ - 0x01, /* first payload byte */ - 0x02, 0x03, 0x04, 0x05, + 0x0B, /* First size byte */ + 0x00, /* Second size byte */ + 0xc1, /* First ChannelId byte */ + 0xc2, /**/ + 0x4A, /* 0x12 ReqSeq, Final, IFrame */ + 0xD0, /* 0x13 ReqSeq */ + 0x89, /* 0x21 TxSeq sar = START */ + 0x8C, /* 0x23 TxSeq */ + 0x10, /* first length byte */ + 0x11, /**/ + 0x01, /* first payload byte */ + 0x02, 0x03, 0x04, 0x05, }; -DEFINE_AND_INSTANTIATE_ExtendedInformationStartFrameReflectionTest(extended_information_start_frame); +DEFINE_AND_INSTANTIATE_ExtendedInformationStartFrameReflectionTest( + extended_information_start_frame); std::vector i_frame_with_fcs = {0x0E, 0x00, 0x40, 0x00, 0x02, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x38, 0x61}; @@ -59,23 +60,27 @@ DEFINE_AND_INSTANTIATE_StandardSupervisoryFrameWithFcsReflectionTest(rr_frame_wi std::vector g_frame = {0x03, 0x00, 0x02, 0x00, 0x01, 0x02, 0x03}; DEFINE_AND_INSTANTIATE_GroupFrameReflectionTest(g_frame); -std::vector config_mtu_request = {0x04, 0x05, 0x08, 0x00, 0x41, 0x00, 0x00, 0x00, 0x01, 0x02, 0xa0, 0x02}; +std::vector config_mtu_request = {0x04, 0x05, 0x08, 0x00, 0x41, 0x00, + 0x00, 0x00, 0x01, 0x02, 0xa0, 0x02}; DEFINE_AND_INSTANTIATE_ConfigurationRequestReflectionTest(config_mtu_request); std::vector config_request_one_defined_option = {0x04, 0x05, 0x08, 0x00, 0x41, 0x00, 0x00, 0x00, 0x01, 0x02, 0x12, 0x34}; -std::vector config_request_two_defined_options = {0x04, 0x05, 0x0c, 0x00, 0x41, 0x00, 0x00, 0x00, - 0x01, 0x02, 0x12, 0x34, 0x02, 0x02, 0x56, 0x78}; -std::vector config_request_two_undefined_options = {0x04, 0x05, 0x0e, 0x00, 0x41, 0x00, 0x00, 0x00, 0x7f, - 0x02, 0x01, 0x00, 0x7e, 0x04, 0x11, 0x11, 0x00, 0x00}; +std::vector config_request_two_defined_options = {0x04, 0x05, 0x0c, 0x00, 0x41, 0x00, + 0x00, 0x00, 0x01, 0x02, 0x12, 0x34, + 0x02, 0x02, 0x56, 0x78}; +std::vector config_request_two_undefined_options = {0x04, 0x05, 0x0e, 0x00, 0x41, 0x00, + 0x00, 0x00, 0x7f, 0x02, 0x01, 0x00, + 0x7e, 0x04, 0x11, 0x11, 0x00, 0x00}; std::vector config_request_hint_one_defined_option = {0x04, 0x05, 0x08, 0x00, 0x41, 0x00, 0x00, 0x00, 0x81, 0x02, 0x12, 0x34}; -std::vector config_request_hint_two_undefined_options = {0x04, 0x05, 0x0c, 0x00, 0x41, 0x00, 0x00, 0x00, - 0x90, 0x02, 0x01, 0x00, 0x91, 0x02, 0x11, 0x11}; +std::vector config_request_hint_two_undefined_options = { + 0x04, 0x05, 0x0c, 0x00, 0x41, 0x00, 0x00, 0x00, + 0x90, 0x02, 0x01, 0x00, 0x91, 0x02, 0x11, 0x11}; TEST(L2capPacketsTest, testConfigRequestOptions) { { std::shared_ptr> view_bytes = - std::make_shared>(config_request_one_defined_option); + std::make_shared>(config_request_one_defined_option); PacketView packet_bytes_view(view_bytes); auto view = ConfigurationRequestView::Create(ControlView::Create(packet_bytes_view)); @@ -85,7 +90,7 @@ TEST(L2capPacketsTest, testConfigRequestOptions) { { std::shared_ptr> view_bytes = - std::make_shared>(config_request_two_defined_options); + std::make_shared>(config_request_two_defined_options); PacketView packet_bytes_view(view_bytes); auto view = ConfigurationRequestView::Create(ControlView::Create(packet_bytes_view)); @@ -95,7 +100,7 @@ TEST(L2capPacketsTest, testConfigRequestOptions) { { std::shared_ptr> view_bytes = - std::make_shared>(config_request_two_undefined_options); + std::make_shared>(config_request_two_undefined_options); PacketView packet_bytes_view(view_bytes); auto view = ConfigurationRequestView::Create(ControlView::Create(packet_bytes_view)); @@ -105,7 +110,7 @@ TEST(L2capPacketsTest, testConfigRequestOptions) { { std::shared_ptr> view_bytes = - std::make_shared>(config_request_hint_one_defined_option); + std::make_shared>(config_request_hint_one_defined_option); PacketView packet_bytes_view(view_bytes); auto view = ConfigurationRequestView::Create(ControlView::Create(packet_bytes_view)); @@ -115,7 +120,7 @@ TEST(L2capPacketsTest, testConfigRequestOptions) { { std::shared_ptr> view_bytes = - std::make_shared>(config_request_hint_two_undefined_options); + std::make_shared>(config_request_hint_two_undefined_options); PacketView packet_bytes_view(view_bytes); auto view = ConfigurationRequestView::Create(ControlView::Create(packet_bytes_view)); @@ -128,7 +133,7 @@ DEFINE_ConfigurationRequestReflectionFuzzTest(); TEST(L2capFuzzRegressions, ConfigurationRequestFuzz_5691566077247488) { uint8_t bluetooth_gd_fuzz_test_5691566077247488[] = { - 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; RunConfigurationRequestReflectionFuzzTest(bluetooth_gd_fuzz_test_5691566077247488, sizeof(bluetooth_gd_fuzz_test_5691566077247488)); @@ -136,7 +141,7 @@ TEST(L2capFuzzRegressions, ConfigurationRequestFuzz_5691566077247488) { TEST(L2capFuzzRegressions, ConfigurationRequestFuzz_5747922062802944) { uint8_t bluetooth_gd_fuzz_test_5747922062802944[] = { - 0x04, 0x02, 0x02, 0x7f, 0x3f, 0x7f, 0x3f, 0x7e, 0x7f, + 0x04, 0x02, 0x02, 0x7f, 0x3f, 0x7f, 0x3f, 0x7e, 0x7f, }; RunConfigurationRequestReflectionFuzzTest(bluetooth_gd_fuzz_test_5747922062802944, sizeof(bluetooth_gd_fuzz_test_5747922062802944)); @@ -144,7 +149,7 @@ TEST(L2capFuzzRegressions, ConfigurationRequestFuzz_5747922062802944) { TEST(L2capFuzzRegressions, ConfigurationRequestFuzz_5202709231697920) { uint8_t bluetooth_gd_fuzz_test_5747922062802944[] = { - 0x04, 0x01, 0x45, 0x45, 0x05, 0x01, 0x01, 0x45, 0x05, 0x01, + 0x04, 0x01, 0x45, 0x45, 0x05, 0x01, 0x01, 0x45, 0x05, 0x01, }; RunConfigurationRequestReflectionFuzzTest(bluetooth_gd_fuzz_test_5747922062802944, diff --git a/system/gd/l2cap/le/dynamic_channel.cc b/system/gd/l2cap/le/dynamic_channel.cc index 108b65f97e0..5005348aa99 100644 --- a/system/gd/l2cap/le/dynamic_channel.cc +++ b/system/gd/l2cap/le/dynamic_channel.cc @@ -15,18 +15,15 @@ */ #include "l2cap/le/dynamic_channel.h" + #include "l2cap/le/internal/link.h" namespace bluetooth { namespace l2cap { namespace le { -LinkOptions* DynamicChannel::GetLinkOptions() { - return link_->GetLinkOptions(); -} +LinkOptions* DynamicChannel::GetLinkOptions() { return link_->GetLinkOptions(); } -Mtu DynamicChannel::GetMtu() const { - return mtu_; -} +Mtu DynamicChannel::GetMtu() const { return mtu_; } } // namespace le } // namespace l2cap diff --git a/system/gd/l2cap/le/dynamic_channel.h b/system/gd/l2cap/le/dynamic_channel.h index 988d12aefb0..42a9a3b6fbd 100644 --- a/system/gd/l2cap/le/dynamic_channel.h +++ b/system/gd/l2cap/le/dynamic_channel.h @@ -28,12 +28,9 @@ class Link; } class DynamicChannel : public l2cap::DynamicChannel { - public: - DynamicChannel( - std::shared_ptr impl, - os::Handler* l2cap_handler, - internal::Link* link, - Mtu mtu) +public: + DynamicChannel(std::shared_ptr impl, + os::Handler* l2cap_handler, internal::Link* link, Mtu mtu) : l2cap::DynamicChannel(impl, l2cap_handler), link_(link), mtu_(mtu) {} /** @@ -45,7 +42,7 @@ class DynamicChannel : public l2cap::DynamicChannel { Mtu GetMtu() const; - private: +private: internal::Link* link_; Mtu mtu_; }; diff --git a/system/gd/l2cap/le/dynamic_channel_configuration_option.h b/system/gd/l2cap/le/dynamic_channel_configuration_option.h index a70b60d721d..60d98b00f09 100644 --- a/system/gd/l2cap/le/dynamic_channel_configuration_option.h +++ b/system/gd/l2cap/le/dynamic_channel_configuration_option.h @@ -23,13 +23,13 @@ namespace l2cap { namespace le { /** - * Configuration Option specified by L2CAP Channel user on a dynamic channel. L2CAP module will configure the channel - * based on user provided option. + * Configuration Option specified by L2CAP Channel user on a dynamic channel. L2CAP module will + * configure the channel based on user provided option. */ struct DynamicChannelConfigurationOption { /** - * Maximum SDU size that the L2CAP Channel user is able to receive or send. When the channel is created, the actual - * MTU is the minimum of the suggested MTU between two devices. + * Maximum SDU size that the L2CAP Channel user is able to receive or send. When the channel is + * created, the actual MTU is the minimum of the suggested MTU between two devices. */ Mtu mtu = kDefaultClassicMtu; }; diff --git a/system/gd/l2cap/le/dynamic_channel_manager.cc b/system/gd/l2cap/le/dynamic_channel_manager.cc index 677e92c6f78..72ae165bc08 100644 --- a/system/gd/l2cap/le/dynamic_channel_manager.cc +++ b/system/gd/l2cap/le/dynamic_channel_manager.cc @@ -15,6 +15,7 @@ */ #include "l2cap/le/dynamic_channel_manager.h" + #include "l2cap/le/internal/dynamic_channel_service_impl.h" #include "l2cap/le/internal/dynamic_channel_service_manager_impl.h" #include "l2cap/le/internal/link.h" @@ -25,14 +26,15 @@ namespace l2cap { namespace le { bool DynamicChannelManager::ConnectChannel(hci::AddressWithType device, - DynamicChannelConfigurationOption configuration_option, Psm psm, - OnConnectionOpenCallback on_connection_open, - OnConnectionFailureCallback on_fail_callback, os::Handler* handler) { + DynamicChannelConfigurationOption configuration_option, + Psm psm, OnConnectionOpenCallback on_connection_open, + OnConnectionFailureCallback on_fail_callback, + os::Handler* handler) { internal::Link::PendingDynamicChannelConnection pending_dynamic_channel_connection{ - .handler_ = handler, - .on_open_callback_ = std::move(on_connection_open), - .on_fail_callback_ = std::move(on_fail_callback), - .configuration_ = configuration_option, + .handler_ = handler, + .on_open_callback_ = std::move(on_connection_open), + .on_fail_callback_ = std::move(on_fail_callback), + .configuration_ = configuration_option, }; l2cap_layer_handler_->Post(common::BindOnce(&internal::LinkManager::ConnectDynamicChannelServices, common::Unretained(link_manager_), device, @@ -41,16 +43,18 @@ bool DynamicChannelManager::ConnectChannel(hci::AddressWithType device, return true; } -bool DynamicChannelManager::RegisterService(Psm psm, DynamicChannelConfigurationOption configuration_option, +bool DynamicChannelManager::RegisterService(Psm psm, + DynamicChannelConfigurationOption configuration_option, const SecurityPolicy& security_policy, OnRegistrationCompleteCallback on_registration_complete, - OnConnectionOpenCallback on_connection_open, os::Handler* handler) { + OnConnectionOpenCallback on_connection_open, + os::Handler* handler) { internal::DynamicChannelServiceImpl::PendingRegistration pending_registration{ - .user_handler_ = handler, - .security_policy_ = security_policy, - .on_registration_complete_callback_ = std::move(on_registration_complete), - .on_connection_open_callback_ = std::move(on_connection_open), - .configuration_ = configuration_option, + .user_handler_ = handler, + .security_policy_ = security_policy, + .on_registration_complete_callback_ = std::move(on_registration_complete), + .on_connection_open_callback_ = std::move(on_connection_open), + .configuration_ = configuration_option, }; l2cap_layer_handler_->Post(common::BindOnce(&internal::DynamicChannelServiceManagerImpl::Register, common::Unretained(service_manager_), psm, diff --git a/system/gd/l2cap/le/dynamic_channel_manager.h b/system/gd/l2cap/le/dynamic_channel_manager.h index ae9eb4624a7..2cef583843d 100644 --- a/system/gd/l2cap/le/dynamic_channel_manager.h +++ b/system/gd/l2cap/le/dynamic_channel_manager.h @@ -39,7 +39,7 @@ class DynamicChannelServiceManagerImpl; } // namespace internal class DynamicChannelManager { - public: +public: DynamicChannelManager(const DynamicChannelManager&) = delete; DynamicChannelManager& operator=(const DynamicChannelManager&) = delete; @@ -54,7 +54,7 @@ class DynamicChannelManager { ConnectionResultCode connection_result_code = ConnectionResultCode::SUCCESS; hci::ErrorCode hci_error = hci::ErrorCode::SUCCESS; LeCreditBasedConnectionResponseResult l2cap_connection_response_result = - LeCreditBasedConnectionResponseResult::SUCCESS; + LeCreditBasedConnectionResponseResult::SUCCESS; }; /** * OnConnectionFailureCallback(std::string failure_reason); @@ -76,7 +76,7 @@ class DynamicChannelManager { * OnRegistrationFailureCallback(RegistrationResult result, DynamicChannelService service); */ using OnRegistrationCompleteCallback = - common::OnceCallback)>; + common::OnceCallback)>; /** * Connect to a Dynamic channel on a remote device @@ -86,58 +86,66 @@ class DynamicChannelManager { * - When true is returned, method caller should wait for on_fail_callback or on_open_callback * - If an LE connection does not exist, this method will create an LE connection * - If HCI connection failed, on_fail_callback will be triggered with FAIL_HCI_ERROR - * - If Dynamic channel on a remote device is already reported as connected via on_open_callback, it won't be - * reported again + * - If Dynamic channel on a remote device is already reported as connected via on_open_callback, + * it won't be reported again * * @param device: Remote device to make this connection. * @param psm: Service PSM to connect. PSM is defined in Core spec Vol 3 Part A 4.2. - * @param on_open_callback: A callback to indicate success of a connection initiated from a remote device. + * @param on_open_callback: A callback to indicate success of a connection initiated from a remote + * device. * @param on_fail_callback: A callback to indicate connection failure along with a status code. * @param handler: The handler context in which to execute the @callback parameters. * @param configuration_option: The configuration options for this channel * * Returns: true if connection was able to be initiated, false otherwise. */ - bool ConnectChannel(hci::AddressWithType device, DynamicChannelConfigurationOption configuration_option, Psm psm, - OnConnectionOpenCallback on_connection_open, OnConnectionFailureCallback on_fail_callback, - os::Handler* handler); + bool ConnectChannel(hci::AddressWithType device, + DynamicChannelConfigurationOption configuration_option, Psm psm, + OnConnectionOpenCallback on_connection_open, + OnConnectionFailureCallback on_fail_callback, os::Handler* handler); /** * Register a service to receive incoming connections bound to a specific channel. * * - This method is asynchronous. * - When false is returned, the registration fails immediately. - * - When true is returned, method caller should wait for on_service_registered callback that contains a - * DynamicChannelService object. The registered service can be managed from that object. - * - If a PSM is already registered or some other error happens, on_registration_complete will be triggered with a - * non-SUCCESS value - * - After a service is registered, a DynamicChannel is delivered through on_open_callback when the remote - * initiates a channel open and channel is opened successfully + * - When true is returned, method caller should wait for on_service_registered callback that + * contains a DynamicChannelService object. The registered service can be managed from that + * object. + * - If a PSM is already registered or some other error happens, on_registration_complete will be + * triggered with a non-SUCCESS value + * - After a service is registered, a DynamicChannel is delivered through on_open_callback when + * the remote initiates a channel open and channel is opened successfully * - on_open_callback, will only be triggered after on_service_registered callback * * @param security_policy: The security policy used for the connection. * @param psm: Service PSM to register. PSM is defined in Core spec Vol 3 Part A 4.2. - * @param on_registration_complete: A callback to indicate the service setup has completed. If the return status is - * not SUCCESS, it means service is not registered due to reasons like PSM already take - * @param on_open_callback: A callback to indicate success of a connection initiated from a remote device. + * @param on_registration_complete: A callback to indicate the service setup has completed. If the + * return status is not SUCCESS, it means service is not registered due to reasons like PSM + * already take + * @param on_open_callback: A callback to indicate success of a connection initiated from a remote + * device. * @param handler: The handler context in which to execute the @callback parameter. * @param configuration_option: The configuration options for this channel */ bool RegisterService(Psm psm, DynamicChannelConfigurationOption configuration_option, - const SecurityPolicy& security_policy, OnRegistrationCompleteCallback on_registration_complete, + const SecurityPolicy& security_policy, + OnRegistrationCompleteCallback on_registration_complete, OnConnectionOpenCallback on_connection_open, os::Handler* handler); friend class L2capLeModule; - private: +private: // The constructor is not to be used by user code DynamicChannelManager(internal::DynamicChannelServiceManagerImpl* service_manager, internal::LinkManager* link_manager, os::Handler* l2cap_layer_handler) - : service_manager_(service_manager), link_manager_(link_manager), l2cap_layer_handler_(l2cap_layer_handler) { + : service_manager_(service_manager), + link_manager_(link_manager), + l2cap_layer_handler_(l2cap_layer_handler) { log::assert_that(service_manager_ != nullptr, "assert failed: service_manager_ != nullptr"); log::assert_that(link_manager_ != nullptr, "assert failed: link_manager_ != nullptr"); - log::assert_that( - l2cap_layer_handler_ != nullptr, "assert failed: l2cap_layer_handler_ != nullptr"); + log::assert_that(l2cap_layer_handler_ != nullptr, + "assert failed: l2cap_layer_handler_ != nullptr"); } internal::DynamicChannelServiceManagerImpl* service_manager_ = nullptr; internal::LinkManager* link_manager_ = nullptr; diff --git a/system/gd/l2cap/le/dynamic_channel_service.cc b/system/gd/l2cap/le/dynamic_channel_service.cc index 323bd9b0663..d4f4db62e6b 100644 --- a/system/gd/l2cap/le/dynamic_channel_service.cc +++ b/system/gd/l2cap/le/dynamic_channel_service.cc @@ -24,16 +24,15 @@ namespace bluetooth { namespace l2cap { namespace le { -void DynamicChannelService::Unregister(OnUnregisteredCallback on_unregistered, os::Handler* on_unregistered_handler) { +void DynamicChannelService::Unregister(OnUnregisteredCallback on_unregistered, + os::Handler* on_unregistered_handler) { log::assert_that(manager_ != nullptr, "this service is invalid"); - l2cap_layer_handler_->Post(common::BindOnce(&internal::DynamicChannelServiceManagerImpl::Unregister, - common::Unretained(manager_), psm_, std::move(on_unregistered), - on_unregistered_handler)); + l2cap_layer_handler_->Post(common::BindOnce( + &internal::DynamicChannelServiceManagerImpl::Unregister, common::Unretained(manager_), + psm_, std::move(on_unregistered), on_unregistered_handler)); } -Psm DynamicChannelService::GetPsm() const { - return psm_; -} +Psm DynamicChannelService::GetPsm() const { return psm_; } } // namespace le } // namespace l2cap diff --git a/system/gd/l2cap/le/dynamic_channel_service.h b/system/gd/l2cap/le/dynamic_channel_service.h index 487f37bbf73..867b57a5197 100644 --- a/system/gd/l2cap/le/dynamic_channel_service.h +++ b/system/gd/l2cap/le/dynamic_channel_service.h @@ -32,7 +32,7 @@ class DynamicChannelServiceManagerImpl; } class DynamicChannelService { - public: +public: DynamicChannelService() = default; DynamicChannelService(const DynamicChannelService&) = delete; DynamicChannelService& operator=(const DynamicChannelService&) = delete; @@ -51,15 +51,16 @@ class DynamicChannelService { Psm GetPsm() const; - protected: - DynamicChannelService(Psm psm, internal::DynamicChannelServiceManagerImpl* manager, os::Handler* handler) +protected: + DynamicChannelService(Psm psm, internal::DynamicChannelServiceManagerImpl* manager, + os::Handler* handler) : psm_(psm), manager_(manager), l2cap_layer_handler_(handler) { log::assert_that(manager_ != nullptr, "assert failed: manager_ != nullptr"); - log::assert_that( - l2cap_layer_handler_ != nullptr, "assert failed: l2cap_layer_handler_ != nullptr"); + log::assert_that(l2cap_layer_handler_ != nullptr, + "assert failed: l2cap_layer_handler_ != nullptr"); } - private: +private: Psm psm_ = kDefaultPsm; internal::DynamicChannelServiceManagerImpl* manager_ = nullptr; os::Handler* l2cap_layer_handler_; diff --git a/system/gd/l2cap/le/facade.cc b/system/gd/l2cap/le/facade.cc index 3680323284e..2ce76039aa8 100644 --- a/system/gd/l2cap/le/facade.cc +++ b/system/gd/l2cap/le/facade.cc @@ -54,7 +54,7 @@ SecurityPolicy SecurityLevelToPolicy(SecurityLevel level) { static constexpr auto kChannelOpenTimeout = std::chrono::seconds(4); class L2capLeModuleFacadeService : public L2capLeModuleFacade::Service { - public: +public: L2capLeModuleFacadeService(L2capLeModule* l2cap_layer, os::Handler* facade_handler) : l2cap_layer_(l2cap_layer), facade_handler_(facade_handler) { log::assert_that(l2cap_layer_ != nullptr, "assert failed: l2cap_layer_ != nullptr"); @@ -62,37 +62,34 @@ class L2capLeModuleFacadeService : public L2capLeModuleFacade::Service { } ::grpc::Status FetchL2capData( - ::grpc::ServerContext* context, - const ::google::protobuf::Empty* /* request */, - ::grpc::ServerWriter<::bluetooth::l2cap::le::L2capPacket>* writer) override { + ::grpc::ServerContext* context, const ::google::protobuf::Empty* /* request */, + ::grpc::ServerWriter<::bluetooth::l2cap::le::L2capPacket>* writer) override { return pending_l2cap_data_.RunLoop(context, writer); } - ::grpc::Status OpenDynamicChannel( - ::grpc::ServerContext* /* context */, - const OpenDynamicChannelRequest* request, - OpenDynamicChannelResponse* response) override { + ::grpc::Status OpenDynamicChannel(::grpc::ServerContext* /* context */, + const OpenDynamicChannelRequest* request, + OpenDynamicChannelResponse* response) override { auto service_helper = dynamic_channel_helper_map_.find(request->psm()); if (service_helper == dynamic_channel_helper_map_.end()) { return ::grpc::Status(::grpc::StatusCode::FAILED_PRECONDITION, "Psm not registered"); } hci::Address peer_address; log::assert_that( - hci::Address::FromString(request->remote().address().address(), peer_address), - "assert failed: hci::Address::FromString(request->remote().address().address(), " - "peer_address)"); + hci::Address::FromString(request->remote().address().address(), peer_address), + "assert failed: hci::Address::FromString(request->remote().address().address(), " + "peer_address)"); // TODO: Support different address type hci::AddressWithType peer(peer_address, hci::AddressType::RANDOM_DEVICE_ADDRESS); service_helper->second->Connect(peer); - response->set_status( - static_cast(service_helper->second->channel_open_fail_reason_.l2cap_connection_response_result)); + response->set_status(static_cast( + service_helper->second->channel_open_fail_reason_.l2cap_connection_response_result)); return ::grpc::Status::OK; } - ::grpc::Status CloseDynamicChannel( - ::grpc::ServerContext* /* context */, - const CloseDynamicChannelRequest* request, - ::google::protobuf::Empty* /* response */) override { + ::grpc::Status CloseDynamicChannel(::grpc::ServerContext* /* context */, + const CloseDynamicChannelRequest* request, + ::google::protobuf::Empty* /* response */) override { auto service_helper = dynamic_channel_helper_map_.find(request->psm()); if (service_helper == dynamic_channel_helper_map_.end()) { return ::grpc::Status(::grpc::StatusCode::FAILED_PRECONDITION, "Psm not registered"); @@ -103,24 +100,26 @@ class L2capLeModuleFacadeService : public L2capLeModuleFacade::Service { auto address = service_helper->second->channel_->GetDevice().GetAddress(); hci::Address peer_address; log::assert_that( - hci::Address::FromString(request->remote().address().address(), peer_address), - "assert failed: hci::Address::FromString(request->remote().address().address(), " - "peer_address)"); + hci::Address::FromString(request->remote().address().address(), peer_address), + "assert failed: hci::Address::FromString(request->remote().address().address(), " + "peer_address)"); if (address != peer_address) { - return ::grpc::Status(::grpc::StatusCode::FAILED_PRECONDITION, "Remote address doesn't match"); + return ::grpc::Status(::grpc::StatusCode::FAILED_PRECONDITION, + "Remote address doesn't match"); } service_helper->second->channel_->Close(); return ::grpc::Status::OK; } ::grpc::Status SetDynamicChannel( - ::grpc::ServerContext* /* context */, - const ::bluetooth::l2cap::le::SetEnableDynamicChannelRequest* request, - ::google::protobuf::Empty* /* response */) override { + ::grpc::ServerContext* /* context */, + const ::bluetooth::l2cap::le::SetEnableDynamicChannelRequest* request, + ::google::protobuf::Empty* /* response */) override { if (request->enable()) { - dynamic_channel_helper_map_.emplace(request->psm(), std::make_unique( - this, l2cap_layer_, facade_handler_, request->psm(), - SecurityLevelToPolicy(request->security_level()))); + dynamic_channel_helper_map_.emplace( + request->psm(), std::make_unique( + this, l2cap_layer_, facade_handler_, request->psm(), + SecurityLevelToPolicy(request->security_level()))); return ::grpc::Status::OK; } else { auto service_helper = dynamic_channel_helper_map_.find(request->psm()); @@ -133,9 +132,9 @@ class L2capLeModuleFacadeService : public L2capLeModuleFacade::Service { } ::grpc::Status SendDynamicChannelPacket( - ::grpc::ServerContext* /* context */, - const ::bluetooth::l2cap::le::DynamicChannelPacket* request, - ::google::protobuf::Empty* /* response */) override { + ::grpc::ServerContext* /* context */, + const ::bluetooth::l2cap::le::DynamicChannelPacket* request, + ::google::protobuf::Empty* /* response */) override { std::unique_lock lock(channel_map_mutex_); if (dynamic_channel_helper_map_.find(request->psm()) == dynamic_channel_helper_map_.end()) { return ::grpc::Status(::grpc::StatusCode::FAILED_PRECONDITION, "Psm not registered"); @@ -148,16 +147,18 @@ class L2capLeModuleFacadeService : public L2capLeModuleFacade::Service { } class L2capDynamicChannelHelper { - public: - L2capDynamicChannelHelper(L2capLeModuleFacadeService* service, L2capLeModule* l2cap_layer, os::Handler* handler, - Psm psm, SecurityPolicy security_policy) + public: + L2capDynamicChannelHelper(L2capLeModuleFacadeService* service, L2capLeModule* l2cap_layer, + os::Handler* handler, Psm psm, SecurityPolicy security_policy) : facade_service_(service), l2cap_layer_(l2cap_layer), handler_(handler), psm_(psm) { dynamic_channel_manager_ = l2cap_layer_->GetDynamicChannelManager(); dynamic_channel_manager_->RegisterService( - psm, {}, security_policy, - common::BindOnce(&L2capDynamicChannelHelper::on_l2cap_service_registration_complete, + psm, {}, security_policy, + common::BindOnce(&L2capDynamicChannelHelper::on_l2cap_service_registration_complete, + common::Unretained(this)), + common::Bind(&L2capDynamicChannelHelper::on_connection_open, common::Unretained(this)), - common::Bind(&L2capDynamicChannelHelper::on_connection_open, common::Unretained(this)), handler_); + handler_); } ~L2capDynamicChannelHelper() { @@ -169,16 +170,21 @@ class L2capLeModuleFacadeService : public L2capLeModuleFacade::Service { void Connect(hci::AddressWithType address) { dynamic_channel_manager_->ConnectChannel( - address, {}, psm_, common::Bind(&L2capDynamicChannelHelper::on_connection_open, common::Unretained(this)), - common::Bind(&L2capDynamicChannelHelper::on_connect_fail, common::Unretained(this)), handler_); + address, {}, psm_, + common::Bind(&L2capDynamicChannelHelper::on_connection_open, + common::Unretained(this)), + common::Bind(&L2capDynamicChannelHelper::on_connect_fail, common::Unretained(this)), + handler_); std::unique_lock lock(channel_open_cv_mutex_); - if (!channel_open_cv_.wait_for(lock, kChannelOpenTimeout, [this] { return channel_ != nullptr; })) { + if (!channel_open_cv_.wait_for(lock, kChannelOpenTimeout, + [this] { return channel_ != nullptr; })) { log::warn("Channel is not open for psm {}", psm_); } } - void on_l2cap_service_registration_complete(DynamicChannelManager::RegistrationResult registration_result, - std::unique_ptr service) { + void on_l2cap_service_registration_complete( + DynamicChannelManager::RegistrationResult registration_result, + std::unique_ptr service) { if (registration_result != DynamicChannelManager::RegistrationResult::SUCCESS) { log::error("Service registration failed"); } else { @@ -193,11 +199,12 @@ class L2capLeModuleFacadeService : public L2capLeModuleFacade::Service { channel_ = std::move(channel); } channel_open_cv_.notify_all(); - channel_->RegisterOnCloseCallback( - facade_service_->facade_handler_->BindOnceOn(this, &L2capDynamicChannelHelper::on_close_callback)); + channel_->RegisterOnCloseCallback(facade_service_->facade_handler_->BindOnceOn( + this, &L2capDynamicChannelHelper::on_close_callback)); channel_->GetQueueUpEnd()->RegisterDequeue( - facade_service_->facade_handler_, - common::Bind(&L2capDynamicChannelHelper::on_incoming_packet, common::Unretained(this))); + facade_service_->facade_handler_, + common::Bind(&L2capDynamicChannelHelper::on_incoming_packet, + common::Unretained(this))); } void on_close_callback(hci::ErrorCode /* error_code */) { @@ -229,7 +236,8 @@ class L2capLeModuleFacadeService : public L2capLeModuleFacade::Service { bool SendPacket(std::vector packet) { if (channel_ == nullptr) { std::unique_lock lock(channel_open_cv_mutex_); - if (!channel_open_cv_.wait_for(lock, kChannelOpenTimeout, [this] { return channel_ != nullptr; })) { + if (!channel_open_cv_.wait_for(lock, kChannelOpenTimeout, + [this] { return channel_ != nullptr; })) { log::warn("Channel is not open for psm {}", psm_); return false; } @@ -237,8 +245,9 @@ class L2capLeModuleFacadeService : public L2capLeModuleFacade::Service { std::promise promise; auto future = promise.get_future(); channel_->GetQueueUpEnd()->RegisterEnqueue( - handler_, common::Bind(&L2capDynamicChannelHelper::enqueue_callback, common::Unretained(this), packet, - common::Passed(std::move(promise)))); + handler_, + common::Bind(&L2capDynamicChannelHelper::enqueue_callback, common::Unretained(this), + packet, common::Passed(std::move(promise)))); auto status = future.wait_for(std::chrono::milliseconds(500)); if (status != std::future_status::ready) { log::error("Can't send packet because the previous packet wasn't sent yet"); @@ -268,13 +277,13 @@ class L2capLeModuleFacadeService : public L2capLeModuleFacade::Service { std::mutex channel_open_cv_mutex_; }; - ::grpc::Status SetFixedChannel( - ::grpc::ServerContext* /* context */, - const SetEnableFixedChannelRequest* request, - ::google::protobuf::Empty* /* response */) override { + ::grpc::Status SetFixedChannel(::grpc::ServerContext* /* context */, + const SetEnableFixedChannelRequest* request, + ::google::protobuf::Empty* /* response */) override { if (request->enable()) { - fixed_channel_helper_map_.emplace(request->cid(), std::make_unique( - this, l2cap_layer_, facade_handler_, request->cid())); + fixed_channel_helper_map_.emplace( + request->cid(), std::make_unique( + this, l2cap_layer_, facade_handler_, request->cid())); return ::grpc::Status::OK; } else { auto service_helper = fixed_channel_helper_map_.find(request->cid()); @@ -287,10 +296,9 @@ class L2capLeModuleFacadeService : public L2capLeModuleFacade::Service { } } - ::grpc::Status SendFixedChannelPacket( - ::grpc::ServerContext* /* context */, - const FixedChannelPacket* request, - ::google::protobuf::Empty* /* response */) override { + ::grpc::Status SendFixedChannelPacket(::grpc::ServerContext* /* context */, + const FixedChannelPacket* request, + ::google::protobuf::Empty* /* response */) override { std::unique_lock lock(channel_map_mutex_); if (fixed_channel_helper_map_.find(request->cid()) == fixed_channel_helper_map_.end()) { return ::grpc::Status(::grpc::StatusCode::FAILED_PRECONDITION, "Cid not registered"); @@ -303,15 +311,17 @@ class L2capLeModuleFacadeService : public L2capLeModuleFacade::Service { } class L2capFixedChannelHelper { - public: - L2capFixedChannelHelper(L2capLeModuleFacadeService* service, L2capLeModule* l2cap_layer, os::Handler* handler, - Cid cid) + public: + L2capFixedChannelHelper(L2capLeModuleFacadeService* service, L2capLeModule* l2cap_layer, + os::Handler* handler, Cid cid) : facade_service_(service), l2cap_layer_(l2cap_layer), handler_(handler), cid_(cid) { fixed_channel_manager_ = l2cap_layer_->GetFixedChannelManager(); fixed_channel_manager_->RegisterService( - cid_, - common::BindOnce(&L2capFixedChannelHelper::on_l2cap_service_registration_complete, common::Unretained(this)), - common::Bind(&L2capFixedChannelHelper::on_connection_open, common::Unretained(this)), handler_); + cid_, + common::BindOnce(&L2capFixedChannelHelper::on_l2cap_service_registration_complete, + common::Unretained(this)), + common::Bind(&L2capFixedChannelHelper::on_connection_open, common::Unretained(this)), + handler_); } ~L2capFixedChannelHelper() { @@ -324,15 +334,19 @@ class L2capLeModuleFacadeService : public L2capLeModuleFacade::Service { void Connect(hci::AddressWithType address) { fixed_channel_manager_->ConnectServices( - address, common::BindOnce(&L2capFixedChannelHelper::on_connect_fail, common::Unretained(this)), handler_); + address, + common::BindOnce(&L2capFixedChannelHelper::on_connect_fail, common::Unretained(this)), + handler_); std::unique_lock lock(channel_open_cv_mutex_); - if (!channel_open_cv_.wait_for(lock, kChannelOpenTimeout, [this] { return channel_ != nullptr; })) { + if (!channel_open_cv_.wait_for(lock, kChannelOpenTimeout, + [this] { return channel_ != nullptr; })) { log::warn("Channel is not open for cid {}", cid_); } } - void on_l2cap_service_registration_complete(FixedChannelManager::RegistrationResult registration_result, - std::unique_ptr service) { + void on_l2cap_service_registration_complete( + FixedChannelManager::RegistrationResult registration_result, + std::unique_ptr service) { if (registration_result != FixedChannelManager::RegistrationResult::SUCCESS) { log::error("Service registration failed"); } else { @@ -346,13 +360,14 @@ class L2capLeModuleFacadeService : public L2capLeModuleFacade::Service { std::unique_lock lock(channel_open_cv_mutex_); channel_ = std::move(channel); channel_->RegisterOnCloseCallback( - handler_, common::BindOnce(&L2capFixedChannelHelper::on_close_callback, common::Unretained(this))); + handler_, common::BindOnce(&L2capFixedChannelHelper::on_close_callback, + common::Unretained(this))); channel_->Acquire(); } channel_open_cv_.notify_all(); channel_->GetQueueUpEnd()->RegisterDequeue( - facade_service_->facade_handler_, - common::Bind(&L2capFixedChannelHelper::on_incoming_packet, common::Unretained(this))); + facade_service_->facade_handler_, + common::Bind(&L2capFixedChannelHelper::on_incoming_packet, common::Unretained(this))); } void on_close_callback(hci::ErrorCode /* error_code */) { @@ -383,7 +398,8 @@ class L2capLeModuleFacadeService : public L2capLeModuleFacade::Service { bool SendPacket(std::vector packet) { if (channel_ == nullptr) { std::unique_lock lock(channel_open_cv_mutex_); - if (!channel_open_cv_.wait_for(lock, kChannelOpenTimeout, [this] { return channel_ != nullptr; })) { + if (!channel_open_cv_.wait_for(lock, kChannelOpenTimeout, + [this] { return channel_ != nullptr; })) { log::warn("Channel is not open for cid {}", cid_); return false; } @@ -391,8 +407,9 @@ class L2capLeModuleFacadeService : public L2capLeModuleFacade::Service { std::promise promise; auto future = promise.get_future(); channel_->GetQueueUpEnd()->RegisterEnqueue( - handler_, common::Bind(&L2capFixedChannelHelper::enqueue_callback, common::Unretained(this), packet, - common::Passed(std::move(promise)))); + handler_, + common::Bind(&L2capFixedChannelHelper::enqueue_callback, common::Unretained(this), + packet, common::Passed(std::move(promise)))); auto status = future.wait_for(std::chrono::milliseconds(500)); if (status != std::future_status::ready) { log::error("Can't send packet because the previous packet wasn't sent yet"); @@ -421,17 +438,17 @@ class L2capLeModuleFacadeService : public L2capLeModuleFacade::Service { std::mutex channel_open_cv_mutex_; }; - ::grpc::Status SendConnectionParameterUpdate( - ::grpc::ServerContext* /* context */, - const ConnectionParameter* request, - ::google::protobuf::Empty* /* response */) override { + ::grpc::Status SendConnectionParameterUpdate(::grpc::ServerContext* /* context */, + const ConnectionParameter* request, + ::google::protobuf::Empty* /* response */) override { if (dynamic_channel_helper_map_.empty()) { - return ::grpc::Status(::grpc::StatusCode::FAILED_PRECONDITION, "Need to open at least one dynamic channel first"); + return ::grpc::Status(::grpc::StatusCode::FAILED_PRECONDITION, + "Need to open at least one dynamic channel first"); } auto& dynamic_channel_helper = dynamic_channel_helper_map_.begin()->second; dynamic_channel_helper->channel_->GetLinkOptions()->UpdateConnectionParameter( - request->conn_interval_min(), request->conn_interval_max(), request->conn_latency(), - request->supervision_timeout(), request->min_ce_length(), request->max_ce_length()); + request->conn_interval_min(), request->conn_interval_max(), request->conn_latency(), + request->supervision_timeout(), request->min_ce_length(), request->max_ce_length()); return ::grpc::Status::OK; } @@ -451,7 +468,8 @@ void L2capLeModuleFacadeModule::ListDependencies(ModuleList* list) const { void L2capLeModuleFacadeModule::Start() { ::bluetooth::grpc::GrpcFacadeModule::Start(); - service_ = new L2capLeModuleFacadeService(GetDependency(), GetHandler()); + service_ = + new L2capLeModuleFacadeService(GetDependency(), GetHandler()); } void L2capLeModuleFacadeModule::Stop() { @@ -459,12 +477,10 @@ void L2capLeModuleFacadeModule::Stop() { ::bluetooth::grpc::GrpcFacadeModule::Stop(); } -::grpc::Service* L2capLeModuleFacadeModule::GetService() const { - return service_; -} +::grpc::Service* L2capLeModuleFacadeModule::GetService() const { return service_; } const ModuleFactory L2capLeModuleFacadeModule::Factory = - ::bluetooth::ModuleFactory([]() { return new L2capLeModuleFacadeModule(); }); + ::bluetooth::ModuleFactory([]() { return new L2capLeModuleFacadeModule(); }); } // namespace le } // namespace l2cap diff --git a/system/gd/l2cap/le/facade.h b/system/gd/l2cap/le/facade.h index 8af68c0a2ca..da12934de76 100644 --- a/system/gd/l2cap/le/facade.h +++ b/system/gd/l2cap/le/facade.h @@ -26,7 +26,7 @@ namespace le { class L2capLeModuleFacadeService; class L2capLeModuleFacadeModule : public ::bluetooth::grpc::GrpcFacadeModule { - public: +public: static const ModuleFactory Factory; void ListDependencies(ModuleList* list) const override; @@ -37,7 +37,7 @@ class L2capLeModuleFacadeModule : public ::bluetooth::grpc::GrpcFacadeModule { ::grpc::Service* GetService() const override; - private: +private: L2capLeModuleFacadeService* service_; }; diff --git a/system/gd/l2cap/le/fixed_channel.cc b/system/gd/l2cap/le/fixed_channel.cc index fb3fd4c2d8f..d1a071aa398 100644 --- a/system/gd/l2cap/le/fixed_channel.cc +++ b/system/gd/l2cap/le/fixed_channel.cc @@ -15,6 +15,7 @@ */ #include "l2cap/le/fixed_channel.h" + #include "common/bind.h" #include "l2cap/le/internal/fixed_channel_impl.h" @@ -22,13 +23,12 @@ namespace bluetooth { namespace l2cap { namespace le { -hci::AddressWithType FixedChannel::GetDevice() const { - return impl_->GetDevice(); -} +hci::AddressWithType FixedChannel::GetDevice() const { return impl_->GetDevice(); } -void FixedChannel::RegisterOnCloseCallback(os::Handler* user_handler, FixedChannel::OnCloseCallback on_close_callback) { - l2cap_handler_->Post(common::BindOnce(&internal::FixedChannelImpl::RegisterOnCloseCallback, impl_, user_handler, - std::move(on_close_callback))); +void FixedChannel::RegisterOnCloseCallback(os::Handler* user_handler, + FixedChannel::OnCloseCallback on_close_callback) { + l2cap_handler_->Post(common::BindOnce(&internal::FixedChannelImpl::RegisterOnCloseCallback, impl_, + user_handler, std::move(on_close_callback))); } void FixedChannel::Acquire() { @@ -44,9 +44,7 @@ FixedChannel::GetQueueUpEnd() const { return impl_->GetQueueUpEnd(); } -LinkOptions* FixedChannel::GetLinkOptions() { - return impl_->GetLinkOptions(); -} +LinkOptions* FixedChannel::GetLinkOptions() { return impl_->GetLinkOptions(); } } // namespace le } // namespace l2cap diff --git a/system/gd/l2cap/le/fixed_channel.h b/system/gd/l2cap/le/fixed_channel.h index f97039d5f5e..ec8b92c6a2e 100644 --- a/system/gd/l2cap/le/fixed_channel.h +++ b/system/gd/l2cap/le/fixed_channel.h @@ -39,7 +39,7 @@ class FixedChannelImpl; * */ class FixedChannel { - public: +public: // Should only be constructed by modules that have access to LinkManager FixedChannel(std::shared_ptr impl, os::Handler* l2cap_handler) : impl_(std::move(impl)), l2cap_handler_(l2cap_handler) { @@ -50,9 +50,10 @@ class FixedChannel { hci::AddressWithType GetDevice() const; /** - * Register close callback. If close callback is registered, when a channel is closed, the channel's resource will - * only be freed after on_close callback is invoked. Otherwise, if no on_close callback is registered, the channel's - * resource will be freed immediately after closing. + * Register close callback. If close callback is registered, when a channel is closed, the + * channel's resource will only be freed after on_close callback is invoked. Otherwise, if no + * on_close callback is registered, the channel's resource will be freed immediately after + * closing. * * @param user_handler The handler used to invoke the callback on * @param on_close_callback The callback invoked upon channel closing. @@ -61,14 +62,16 @@ class FixedChannel { void RegisterOnCloseCallback(os::Handler* user_handler, OnCloseCallback on_close_callback); /** - * Indicate that this Fixed Channel is being used. This will prevent ACL connection from being disconnected. + * Indicate that this Fixed Channel is being used. This will prevent ACL connection from being + * disconnected. */ void Acquire(); /** - * Indicate that this Fixed Channel is no longer being used. ACL connection will be disconnected after - * kLinkIdleDisconnectTimeout if no other DynamicChannel is connected or no other Fixed Channel is using this - * ACL connection. However a module can still receive data on this channel as long as it remains open. + * Indicate that this Fixed Channel is no longer being used. ACL connection will be disconnected + * after kLinkIdleDisconnectTimeout if no other DynamicChannel is connected or no other Fixed + * Channel is using this ACL connection. However a module can still receive data on this channel + * as long as it remains open. */ void Release(); @@ -79,7 +82,8 @@ class FixedChannel { * * @return The upper end of a bi-directional queue. */ - common::BidiQueueEnd>* GetQueueUpEnd() const; + common::BidiQueueEnd>* + GetQueueUpEnd() const; /** * Get the Proxy for L2CAP Link Options. @@ -88,7 +92,7 @@ class FixedChannel { */ LinkOptions* GetLinkOptions(); - private: +private: std::shared_ptr impl_; os::Handler* l2cap_handler_; }; diff --git a/system/gd/l2cap/le/fixed_channel_manager.cc b/system/gd/l2cap/le/fixed_channel_manager.cc index c3c47638088..29ae1c6b6cb 100644 --- a/system/gd/l2cap/le/fixed_channel_manager.cc +++ b/system/gd/l2cap/le/fixed_channel_manager.cc @@ -15,6 +15,7 @@ */ #include "l2cap/le/fixed_channel_manager.h" + #include "l2cap/le/internal/fixed_channel_service_impl.h" #include "l2cap/le/internal/fixed_channel_service_manager_impl.h" #include "l2cap/le/internal/link_manager.h" @@ -24,10 +25,11 @@ namespace l2cap { namespace le { bool FixedChannelManager::ConnectServices(hci::AddressWithType address_with_type, - OnConnectionFailureCallback on_fail_callback, os::Handler* handler) { + OnConnectionFailureCallback on_fail_callback, + os::Handler* handler) { internal::LinkManager::PendingFixedChannelConnection pending_fixed_channel_connection{ - .handler_ = handler, - .on_fail_callback_ = std::move(on_fail_callback), + .handler_ = handler, + .on_fail_callback_ = std::move(on_fail_callback), }; l2cap_layer_handler_->Post(common::BindOnce(&internal::LinkManager::ConnectFixedChannelServices, common::Unretained(link_manager_), address_with_type, @@ -35,12 +37,14 @@ bool FixedChannelManager::ConnectServices(hci::AddressWithType address_with_type return true; } -bool FixedChannelManager::RegisterService(Cid cid, OnRegistrationCompleteCallback on_registration_complete, - OnConnectionOpenCallback on_connection_open, os::Handler* handler) { +bool FixedChannelManager::RegisterService(Cid cid, + OnRegistrationCompleteCallback on_registration_complete, + OnConnectionOpenCallback on_connection_open, + os::Handler* handler) { internal::FixedChannelServiceImpl::PendingRegistration pending_registration{ - .user_handler_ = handler, - .on_registration_complete_callback_ = std::move(on_registration_complete), - .on_connection_open_callback_ = std::move(on_connection_open)}; + .user_handler_ = handler, + .on_registration_complete_callback_ = std::move(on_registration_complete), + .on_connection_open_callback_ = std::move(on_connection_open)}; l2cap_layer_handler_->Post(common::BindOnce(&internal::FixedChannelServiceManagerImpl::Register, common::Unretained(service_manager_), cid, std::move(pending_registration))); diff --git a/system/gd/l2cap/le/fixed_channel_manager.h b/system/gd/l2cap/le/fixed_channel_manager.h index 9bd2c70cd82..9c7c893305c 100644 --- a/system/gd/l2cap/le/fixed_channel_manager.h +++ b/system/gd/l2cap/le/fixed_channel_manager.h @@ -35,7 +35,7 @@ class FixedChannelServiceManagerImpl; } // namespace internal class FixedChannelManager { - public: +public: FixedChannelManager(const FixedChannelManager&) = delete; FixedChannelManager& operator=(const FixedChannelManager&) = delete; @@ -70,29 +70,32 @@ class FixedChannelManager { * OnRegistrationFailureCallback(RegistrationResult result, FixedChannelService service); */ using OnRegistrationCompleteCallback = - common::OnceCallback)>; + common::OnceCallback)>; /** * Connect to ALL fixed channels on a remote device * * - This method is asynchronous * - When false is returned, the connection fails immediately - * - When true is returned, method caller should wait for on_fail_callback or on_open_callback registered through - * RegisterService() API. - * - If an ACL connection does not exist, this method will create an ACL connection. As a result, on_open_callback - * supplied through RegisterService() will be triggered to provide the actual FixedChannel objects + * - When true is returned, method caller should wait for on_fail_callback or on_open_callback + * registered through RegisterService() API. + * - If an ACL connection does not exist, this method will create an ACL connection. As a result, + * on_open_callback supplied through RegisterService() will be triggered to provide the actual + * FixedChannel objects * - If HCI connection failed, on_fail_callback will be triggered with FAIL_HCI_ERROR - * - If fixed channel on a remote device is already reported as connected via on_open_callback and has been acquired - * via FixedChannel#Acquire() API, it won't be reported again - * - If no service is registered, on_fail_callback will be triggered with FAIL_NO_SERVICE_REGISTERED - * - If there is an ACL connection and channels for each service is allocated, on_fail_callback will be triggered with - * FAIL_ALL_SERVICES_HAVE_CHANNEL + * - If fixed channel on a remote device is already reported as connected via on_open_callback and + * has been acquired via FixedChannel#Acquire() API, it won't be reported again + * - If no service is registered, on_fail_callback will be triggered with + * FAIL_NO_SERVICE_REGISTERED + * - If there is an ACL connection and channels for each service is allocated, on_fail_callback + * will be triggered with FAIL_ALL_SERVICES_HAVE_CHANNEL * * NOTE: * This call will initiate an effort to connect all fixed channel services on a remote device. - * Due to the connectionless nature of fixed channels, all fixed channels will be connected together. - * If a fixed channel service does not need a particular fixed channel. It should release the received - * channel immediately after receiving on_open_callback via FixedChannel#Release() + * Due to the connectionless nature of fixed channels, all fixed channels will be connected + * together. If a fixed channel service does not need a particular fixed channel. It should + * release the received channel immediately after receiving on_open_callback via + * FixedChannel#Release() * * A module calling ConnectServices() must have called RegisterService() before. * The callback will come back from on_open_callback in the service that is registered @@ -104,26 +107,28 @@ class FixedChannelManager { * * Returns: true if connection was able to be initiated, false otherwise. */ - bool ConnectServices(hci::AddressWithType address_with_type, OnConnectionFailureCallback on_fail_callback, - os::Handler* handler); + bool ConnectServices(hci::AddressWithType address_with_type, + OnConnectionFailureCallback on_fail_callback, os::Handler* handler); /** * Register a service to receive incoming connections bound to a specific channel. * * - This method is asynchronous. * - When false is returned, the registration fails immediately. - * - When true is returned, method caller should wait for on_service_registered callback that contains a - * FixedChannelService object. The registered service can be managed from that object. - * - If a CID is already registered or some other error happens, on_registration_complete will be triggered with a - * non-SUCCESS value - * - After a service is registered, any LE ACL connection will create a FixedChannel object that is - * delivered through on_open_callback + * - When true is returned, method caller should wait for on_service_registered callback that + * contains a FixedChannelService object. The registered service can be managed from that object. + * - If a CID is already registered or some other error happens, on_registration_complete will be + * triggered with a non-SUCCESS value + * - After a service is registered, any LE ACL connection will create a FixedChannel object that + * is delivered through on_open_callback * - on_open_callback, will only be triggered after on_service_registered callback * * @param cid: cid used to receive incoming connections - * @param on_registration_complete: A callback to indicate the service setup has completed. If the return status is - * not SUCCESS, it means service is not registered due to reasons like CID already take - * @param on_open_callback: A callback to indicate success of a connection initiated from a remote device. + * @param on_registration_complete: A callback to indicate the service setup has completed. If the + * return status is not SUCCESS, it means service is not registered due to reasons like CID + * already take + * @param on_open_callback: A callback to indicate success of a connection initiated from a remote + * device. * @param handler: The handler context in which to execute the @callback parameter. */ bool RegisterService(Cid cid, OnRegistrationCompleteCallback on_registration_complete, @@ -131,11 +136,13 @@ class FixedChannelManager { friend class L2capLeModule; - private: +private: // The constructor is not to be used by user code - FixedChannelManager(internal::FixedChannelServiceManagerImpl* service_manager, internal::LinkManager* link_manager, - os::Handler* l2cap_layer_handler) - : service_manager_(service_manager), link_manager_(link_manager), l2cap_layer_handler_(l2cap_layer_handler) {} + FixedChannelManager(internal::FixedChannelServiceManagerImpl* service_manager, + internal::LinkManager* link_manager, os::Handler* l2cap_layer_handler) + : service_manager_(service_manager), + link_manager_(link_manager), + l2cap_layer_handler_(l2cap_layer_handler) {} internal::FixedChannelServiceManagerImpl* service_manager_ = nullptr; internal::LinkManager* link_manager_ = nullptr; os::Handler* l2cap_layer_handler_ = nullptr; diff --git a/system/gd/l2cap/le/fixed_channel_service.cc b/system/gd/l2cap/le/fixed_channel_service.cc index c0bbb3ade43..ad7de59b0c1 100644 --- a/system/gd/l2cap/le/fixed_channel_service.cc +++ b/system/gd/l2cap/le/fixed_channel_service.cc @@ -15,17 +15,19 @@ */ #include "l2cap/le/fixed_channel_service.h" + #include "l2cap/le/internal/fixed_channel_service_manager_impl.h" namespace bluetooth { namespace l2cap { namespace le { -void FixedChannelService::Unregister(OnUnregisteredCallback on_unregistered, os::Handler* on_unregistered_handler) { +void FixedChannelService::Unregister(OnUnregisteredCallback on_unregistered, + os::Handler* on_unregistered_handler) { log::assert_that(manager_ != nullptr, "this service is invalid"); l2cap_layer_handler_->Post(common::BindOnce(&internal::FixedChannelServiceManagerImpl::Unregister, - common::Unretained(manager_), cid_, std::move(on_unregistered), - on_unregistered_handler)); + common::Unretained(manager_), cid_, + std::move(on_unregistered), on_unregistered_handler)); } } // namespace le diff --git a/system/gd/l2cap/le/fixed_channel_service.h b/system/gd/l2cap/le/fixed_channel_service.h index 7660e31ec52..fbee65fd74b 100644 --- a/system/gd/l2cap/le/fixed_channel_service.h +++ b/system/gd/l2cap/le/fixed_channel_service.h @@ -30,7 +30,7 @@ class FixedChannelServiceManagerImpl; } class FixedChannelService { - public: +public: FixedChannelService() = default; FixedChannelService(const FixedChannelService&) = delete; FixedChannelService& operator=(const FixedChannelService&) = delete; @@ -47,8 +47,9 @@ class FixedChannelService { friend internal::FixedChannelServiceManagerImpl; - private: - FixedChannelService(Cid cid, internal::FixedChannelServiceManagerImpl* manager, os::Handler* handler) +private: + FixedChannelService(Cid cid, internal::FixedChannelServiceManagerImpl* manager, + os::Handler* handler) : cid_(cid), manager_(manager), l2cap_layer_handler_(handler) {} Cid cid_ = kInvalidCid; internal::FixedChannelServiceManagerImpl* manager_ = nullptr; diff --git a/system/gd/l2cap/le/internal/dynamic_channel_service_impl.h b/system/gd/l2cap/le/internal/dynamic_channel_service_impl.h index 25af09428af..16e9a2005cf 100644 --- a/system/gd/l2cap/le/internal/dynamic_channel_service_impl.h +++ b/system/gd/l2cap/le/internal/dynamic_channel_service_impl.h @@ -17,7 +17,6 @@ #pragma once #include "common/bind.h" - #include "l2cap/le/dynamic_channel.h" #include "l2cap/le/dynamic_channel_configuration_option.h" #include "l2cap/le/dynamic_channel_manager.h" @@ -29,7 +28,7 @@ namespace l2cap { namespace le { namespace internal { class DynamicChannelServiceImpl { - public: +public: virtual ~DynamicChannelServiceImpl() = default; struct PendingRegistration { @@ -44,25 +43,24 @@ class DynamicChannelServiceImpl { user_handler_->Post(common::BindOnce(on_connection_open_callback_, std::move(channel))); } - DynamicChannelConfigurationOption GetConfigOption() const { - return config_option_; - } + DynamicChannelConfigurationOption GetConfigOption() const { return config_option_; } - SecurityPolicy GetSecurityPolicy() { - return security_policy_; - } + SecurityPolicy GetSecurityPolicy() { return security_policy_; } friend class DynamicChannelServiceManagerImpl; - protected: +protected: // protected access for mocking - DynamicChannelServiceImpl(os::Handler* user_handler, - DynamicChannelManager::OnConnectionOpenCallback on_connection_open_callback, - DynamicChannelConfigurationOption config_option, SecurityPolicy security_policy) - : user_handler_(user_handler), on_connection_open_callback_(std::move(on_connection_open_callback)), - config_option_(config_option), security_policy_(security_policy) {} + DynamicChannelServiceImpl( + os::Handler* user_handler, + DynamicChannelManager::OnConnectionOpenCallback on_connection_open_callback, + DynamicChannelConfigurationOption config_option, SecurityPolicy security_policy) + : user_handler_(user_handler), + on_connection_open_callback_(std::move(on_connection_open_callback)), + config_option_(config_option), + security_policy_(security_policy) {} - private: +private: os::Handler* user_handler_ = nullptr; DynamicChannelManager::OnConnectionOpenCallback on_connection_open_callback_; DynamicChannelConfigurationOption config_option_; diff --git a/system/gd/l2cap/le/internal/dynamic_channel_service_impl_mock.h b/system/gd/l2cap/le/internal/dynamic_channel_service_impl_mock.h index 4edfee86431..c4573e990ad 100644 --- a/system/gd/l2cap/le/internal/dynamic_channel_service_impl_mock.h +++ b/system/gd/l2cap/le/internal/dynamic_channel_service_impl_mock.h @@ -15,10 +15,10 @@ */ #pragma once -#include "l2cap/le/internal/dynamic_channel_service_impl.h" - #include +#include "l2cap/le/internal/dynamic_channel_service_impl.h" + // Unit test interfaces namespace bluetooth { namespace l2cap { @@ -27,7 +27,7 @@ namespace internal { namespace testing { class MockDynamicChannelServiceImpl : public DynamicChannelServiceImpl { - public: +public: MOCK_METHOD(SecurityPolicy, GetSecurityPolicy, (), (const, override)); }; diff --git a/system/gd/l2cap/le/internal/dynamic_channel_service_manager_impl.cc b/system/gd/l2cap/le/internal/dynamic_channel_service_manager_impl.cc index 92424187e28..80be1b39fdf 100644 --- a/system/gd/l2cap/le/internal/dynamic_channel_service_manager_impl.cc +++ b/system/gd/l2cap/le/internal/dynamic_channel_service_manager_impl.cc @@ -28,27 +28,31 @@ namespace l2cap { namespace le { namespace internal { -void DynamicChannelServiceManagerImpl::Register(Psm psm, - DynamicChannelServiceImpl::PendingRegistration pending_registration) { +void DynamicChannelServiceManagerImpl::Register( + Psm psm, DynamicChannelServiceImpl::PendingRegistration pending_registration) { if (IsServiceRegistered(psm)) { std::unique_ptr invalid_service(new DynamicChannelService()); - pending_registration.user_handler_->Post(common::BindOnce( - std::move(pending_registration.on_registration_complete_callback_), - DynamicChannelManager::RegistrationResult::FAIL_DUPLICATE_SERVICE, std::move(invalid_service))); + pending_registration.user_handler_->Post( + common::BindOnce(std::move(pending_registration.on_registration_complete_callback_), + DynamicChannelManager::RegistrationResult::FAIL_DUPLICATE_SERVICE, + std::move(invalid_service))); } else { service_map_.try_emplace( - psm, DynamicChannelServiceImpl(pending_registration.user_handler_, - std::move(pending_registration.on_connection_open_callback_), - pending_registration.configuration_, pending_registration.security_policy_)); - std::unique_ptr user_service(new DynamicChannelService(psm, this, l2cap_layer_handler_)); - pending_registration.user_handler_->Post( - common::BindOnce(std::move(pending_registration.on_registration_complete_callback_), - DynamicChannelManager::RegistrationResult::SUCCESS, std::move(user_service))); + psm, + DynamicChannelServiceImpl(pending_registration.user_handler_, + std::move(pending_registration.on_connection_open_callback_), + pending_registration.configuration_, + pending_registration.security_policy_)); + std::unique_ptr user_service( + new DynamicChannelService(psm, this, l2cap_layer_handler_)); + pending_registration.user_handler_->Post(common::BindOnce( + std::move(pending_registration.on_registration_complete_callback_), + DynamicChannelManager::RegistrationResult::SUCCESS, std::move(user_service))); } } -void DynamicChannelServiceManagerImpl::Unregister(Psm psm, DynamicChannelService::OnUnregisteredCallback callback, - os::Handler* handler) { +void DynamicChannelServiceManagerImpl::Unregister( + Psm psm, DynamicChannelService::OnUnregisteredCallback callback, os::Handler* handler) { if (IsServiceRegistered(psm)) { service_map_.erase(psm); handler->Post(std::move(callback)); @@ -66,7 +70,8 @@ DynamicChannelServiceImpl* DynamicChannelServiceManagerImpl::GetService(Psm psm) return &service_map_.find(psm)->second; } -std::vector> DynamicChannelServiceManagerImpl::GetRegisteredServices() { +std::vector> +DynamicChannelServiceManagerImpl::GetRegisteredServices() { std::vector> results; for (auto& elem : service_map_) { results.emplace_back(elem.first, &elem.second); diff --git a/system/gd/l2cap/le/internal/dynamic_channel_service_manager_impl.h b/system/gd/l2cap/le/internal/dynamic_channel_service_manager_impl.h index 169853f44a0..28a4f9830fb 100644 --- a/system/gd/l2cap/le/internal/dynamic_channel_service_manager_impl.h +++ b/system/gd/l2cap/le/internal/dynamic_channel_service_manager_impl.h @@ -30,7 +30,7 @@ namespace le { namespace internal { class DynamicChannelServiceManagerImpl { - public: +public: explicit DynamicChannelServiceManagerImpl(os::Handler* l2cap_layer_handler) : l2cap_layer_handler_(l2cap_layer_handler) {} @@ -38,8 +38,10 @@ class DynamicChannelServiceManagerImpl { // // All APIs must be invoked in L2CAP layer handler // - virtual void Register(Psm psm, DynamicChannelServiceImpl::PendingRegistration pending_registration); - virtual void Unregister(Psm psm, DynamicChannelService::OnUnregisteredCallback callback, os::Handler* handler); + virtual void Register(Psm psm, + DynamicChannelServiceImpl::PendingRegistration pending_registration); + virtual void Unregister(Psm psm, DynamicChannelService::OnUnregisteredCallback callback, + os::Handler* handler); virtual bool IsServiceRegistered(Psm psm) const; virtual DynamicChannelServiceImpl* GetService(Psm psm); @@ -54,7 +56,7 @@ class DynamicChannelServiceManagerImpl { return security_enforcement_interface_; } - private: +private: os::Handler* l2cap_layer_handler_ = nullptr; std::unordered_map service_map_; SecurityEnforcementInterface* security_enforcement_interface_; diff --git a/system/gd/l2cap/le/internal/dynamic_channel_service_manager_test.cc b/system/gd/l2cap/le/internal/dynamic_channel_service_manager_test.cc index d1f16561d3b..87a5153bca0 100644 --- a/system/gd/l2cap/le/internal/dynamic_channel_service_manager_test.cc +++ b/system/gd/l2cap/le/internal/dynamic_channel_service_manager_test.cc @@ -14,10 +14,10 @@ * limitations under the License. */ -#include - #include +#include + #include "common/bind.h" #include "l2cap/cid.h" #include "l2cap/le/dynamic_channel_manager.h" @@ -32,7 +32,7 @@ namespace le { namespace internal { class L2capLeDynamicServiceManagerTest : public ::testing::Test { - public: +public: ~L2capLeDynamicServiceManagerTest() = default; void OnServiceRegistered(bool expect_success, DynamicChannelManager::RegistrationResult result, @@ -41,7 +41,7 @@ class L2capLeDynamicServiceManagerTest : public ::testing::Test { service_registered_ = expect_success; } - protected: +protected: void SetUp() override { thread_ = new os::Thread("test_thread", os::Thread::Priority::NORMAL); user_handler_ = new os::Handler(thread_); @@ -61,7 +61,8 @@ class L2capLeDynamicServiceManagerTest : public ::testing::Test { void sync_user_handler() { std::promise promise; auto future = promise.get_future(); - user_handler_->Post(common::BindOnce(&std::promise::set_value, common::Unretained(&promise))); + user_handler_->Post( + common::BindOnce(&std::promise::set_value, common::Unretained(&promise))); future.wait_for(std::chrono::milliseconds(3)); } @@ -75,10 +76,11 @@ class L2capLeDynamicServiceManagerTest : public ::testing::Test { TEST_F(L2capLeDynamicServiceManagerTest, register_and_unregister_le_dynamic_channel) { DynamicChannelServiceImpl::PendingRegistration pending_registration{ - .user_handler_ = user_handler_, - .security_policy_ = SecurityPolicy::NO_SECURITY_WHATSOEVER_PLAINTEXT_TRANSPORT_OK, - .on_registration_complete_callback_ = - common::BindOnce(&L2capLeDynamicServiceManagerTest::OnServiceRegistered, common::Unretained(this), true)}; + .user_handler_ = user_handler_, + .security_policy_ = SecurityPolicy::NO_SECURITY_WHATSOEVER_PLAINTEXT_TRANSPORT_OK, + .on_registration_complete_callback_ = + common::BindOnce(&L2capLeDynamicServiceManagerTest::OnServiceRegistered, + common::Unretained(this), true)}; Psm psm = 0x41; EXPECT_FALSE(manager_->IsServiceRegistered(psm)); manager_->Register(psm, std::move(pending_registration)); @@ -91,10 +93,11 @@ TEST_F(L2capLeDynamicServiceManagerTest, register_and_unregister_le_dynamic_chan TEST_F(L2capLeDynamicServiceManagerTest, register_le_dynamic_channel_even_number_psm) { DynamicChannelServiceImpl::PendingRegistration pending_registration{ - .user_handler_ = user_handler_, - .security_policy_ = SecurityPolicy::NO_SECURITY_WHATSOEVER_PLAINTEXT_TRANSPORT_OK, - .on_registration_complete_callback_ = - common::BindOnce(&L2capLeDynamicServiceManagerTest::OnServiceRegistered, common::Unretained(this), true)}; + .user_handler_ = user_handler_, + .security_policy_ = SecurityPolicy::NO_SECURITY_WHATSOEVER_PLAINTEXT_TRANSPORT_OK, + .on_registration_complete_callback_ = + common::BindOnce(&L2capLeDynamicServiceManagerTest::OnServiceRegistered, + common::Unretained(this), true)}; Psm psm = 0x0100; EXPECT_FALSE(manager_->IsServiceRegistered(psm)); manager_->Register(psm, std::move(pending_registration)); diff --git a/system/gd/l2cap/le/internal/fixed_channel_impl.cc b/system/gd/l2cap/le/internal/fixed_channel_impl.cc index 22b90451507..dd8e45b889e 100644 --- a/system/gd/l2cap/le/internal/fixed_channel_impl.cc +++ b/system/gd/l2cap/le/internal/fixed_channel_impl.cc @@ -31,9 +31,7 @@ namespace l2cap { namespace le { namespace internal { -hci::Role FixedChannelImpl::GetRole() const { - return link_->GetRole(); -} +hci::Role FixedChannelImpl::GetRole() const { return link_->GetRole(); } hci::acl_manager::LeAclConnection* FixedChannelImpl::GetAclConnection() const { return link_->GetAclConnection(); @@ -41,8 +39,8 @@ hci::acl_manager::LeAclConnection* FixedChannelImpl::GetAclConnection() const { FixedChannelImpl::FixedChannelImpl(Cid cid, Link* link, os::Handler* l2cap_handler) : cid_(cid), device_(link->GetDevice()), link_(link), l2cap_handler_(l2cap_handler) { - log::assert_that( - cid_ >= kFirstFixedChannel && cid_ <= kLastFixedChannel, "Invalid cid: {}", cid_); + log::assert_that(cid_ >= kFirstFixedChannel && cid_ <= kLastFixedChannel, "Invalid cid: {}", + cid_); log::assert_that(link_ != nullptr, "assert failed: link_ != nullptr"); log::assert_that(l2cap_handler_ != nullptr, "assert failed: l2cap_handler_ != nullptr"); } @@ -60,13 +58,10 @@ void FixedChannelImpl::RegisterOnCloseCallback(os::Handler* user_handler, } void FixedChannelImpl::OnClosed(hci::ErrorCode status) { - log::assert_that( - !closed_, - "Device {} Cid 0x{:x} closed twice, old status 0x{:x}, new status 0x{:x}", - ADDRESS_TO_LOGGABLE_CSTR(device_), - cid_, - static_cast(close_reason_), - static_cast(status)); + log::assert_that(!closed_, + "Device {} Cid 0x{:x} closed twice, old status 0x{:x}, new status 0x{:x}", + ADDRESS_TO_LOGGABLE_CSTR(device_), cid_, static_cast(close_reason_), + static_cast(status)); closed_ = true; close_reason_ = status; acquired_ = false; @@ -82,8 +77,8 @@ void FixedChannelImpl::OnClosed(hci::ErrorCode status) { } void FixedChannelImpl::Acquire() { - log::assert_that( - user_handler_ != nullptr, "Must register OnCloseCallback before calling any methods"); + log::assert_that(user_handler_ != nullptr, + "Must register OnCloseCallback before calling any methods"); if (closed_) { log::warn("{} is already closed", ToLoggableStr(*this)); log::assert_that(!acquired_, "assert failed: !acquired_"); @@ -98,8 +93,8 @@ void FixedChannelImpl::Acquire() { } void FixedChannelImpl::Release() { - log::assert_that( - user_handler_ != nullptr, "Must register OnCloseCallback before calling any methods"); + log::assert_that(user_handler_ != nullptr, + "Must register OnCloseCallback before calling any methods"); if (closed_) { log::warn("{} is already closed", ToLoggableStr(*this)); log::assert_that(!acquired_, "assert failed: !acquired_"); @@ -113,17 +108,11 @@ void FixedChannelImpl::Release() { link_->RefreshRefCount(); } -Cid FixedChannelImpl::GetCid() const { - return cid_; -} +Cid FixedChannelImpl::GetCid() const { return cid_; } -Cid FixedChannelImpl::GetRemoteCid() const { - return cid_; -} +Cid FixedChannelImpl::GetRemoteCid() const { return cid_; } -LinkOptions* FixedChannelImpl::GetLinkOptions() { - return link_->GetLinkOptions(); -} +LinkOptions* FixedChannelImpl::GetLinkOptions() { return link_->GetLinkOptions(); } } // namespace internal } // namespace le diff --git a/system/gd/l2cap/le/internal/fixed_channel_impl.h b/system/gd/l2cap/le/internal/fixed_channel_impl.h index 12ce4a670b2..12948d14c57 100644 --- a/system/gd/l2cap/le/internal/fixed_channel_impl.h +++ b/system/gd/l2cap/le/internal/fixed_channel_impl.h @@ -34,7 +34,7 @@ class Link; class FixedChannelImpl : public l2cap::internal::ChannelImpl, public bluetooth::common::IRedactableLoggable { - public: +public: FixedChannelImpl(Cid cid, Link* link, os::Handler* l2cap_handler); FixedChannelImpl(const FixedChannelImpl&) = delete; @@ -42,24 +42,21 @@ class FixedChannelImpl : public l2cap::internal::ChannelImpl, virtual ~FixedChannelImpl() = default; - hci::AddressWithType GetDevice() const { - return device_; - } + hci::AddressWithType GetDevice() const { return device_; } /* Return the role we have in the associated link */ virtual hci::Role GetRole() const; virtual hci::acl_manager::LeAclConnection* GetAclConnection() const; - virtual void RegisterOnCloseCallback(os::Handler* user_handler, FixedChannel::OnCloseCallback on_close_callback); + virtual void RegisterOnCloseCallback(os::Handler* user_handler, + FixedChannel::OnCloseCallback on_close_callback); virtual void Acquire(); virtual void Release(); - virtual bool IsAcquired() const { - return acquired_; - } + virtual bool IsAcquired() const { return acquired_; } Cid GetCid() const override; Cid GetRemoteCid() const override; @@ -83,17 +80,19 @@ class FixedChannelImpl : public l2cap::internal::ChannelImpl, return ss.str(); } - common::BidiQueueEnd>* GetQueueUpEnd() { + common::BidiQueueEnd>* + GetQueueUpEnd() { return channel_queue_.GetUpEnd(); } - common::BidiQueueEnd, packet::BasePacketBuilder>* GetQueueDownEnd() { + common::BidiQueueEnd, packet::BasePacketBuilder>* + GetQueueDownEnd() { return channel_queue_.GetDownEnd(); } LinkOptions* GetLinkOptions(); - private: +private: // Constructor states // For logging purpose only const Cid cid_; @@ -112,8 +111,8 @@ class FixedChannelImpl : public l2cap::internal::ChannelImpl, bool closed_ = false; hci::ErrorCode close_reason_ = hci::ErrorCode::SUCCESS; static constexpr size_t kChannelQueueSize = 10; - common::BidiQueue, packet::BasePacketBuilder> channel_queue_{ - kChannelQueueSize}; + common::BidiQueue, packet::BasePacketBuilder> + channel_queue_{kChannelQueueSize}; }; } // namespace internal diff --git a/system/gd/l2cap/le/internal/fixed_channel_impl_mock.h b/system/gd/l2cap/le/internal/fixed_channel_impl_mock.h index 5baa7e5045b..084e657b367 100644 --- a/system/gd/l2cap/le/internal/fixed_channel_impl_mock.h +++ b/system/gd/l2cap/le/internal/fixed_channel_impl_mock.h @@ -15,10 +15,10 @@ */ #pragma once -#include "l2cap/le/internal/fixed_channel_impl.h" - #include +#include "l2cap/le/internal/fixed_channel_impl.h" + // Unit test interfaces namespace bluetooth { namespace l2cap { @@ -27,9 +27,10 @@ namespace internal { namespace testing { class MockFixedChannelImpl : public FixedChannelImpl { - public: +public: MOCK_METHOD(void, RegisterOnCloseCallback, - (os::Handler * user_handler, FixedChannel::OnCloseCallback on_close_callback), (override)); + (os::Handler * user_handler, FixedChannel::OnCloseCallback on_close_callback), + (override)); MOCK_METHOD(void, Acquire, (), (override)); MOCK_METHOD(void, Release, (), (override)); MOCK_METHOD(bool, IsAcquired, (), (override, const)); diff --git a/system/gd/l2cap/le/internal/fixed_channel_impl_test.cc b/system/gd/l2cap/le/internal/fixed_channel_impl_test.cc index f8466c51d7f..761b7742f17 100644 --- a/system/gd/l2cap/le/internal/fixed_channel_impl_test.cc +++ b/system/gd/l2cap/le/internal/fixed_channel_impl_test.cc @@ -38,7 +38,7 @@ using testing::MockLink; using ::testing::Return; class L2capLeFixedChannelImplTest : public ::testing::Test { - public: +public: static void SyncHandler(os::Handler* handler) { std::promise promise; auto future = promise.get_future(); @@ -46,7 +46,7 @@ class L2capLeFixedChannelImplTest : public ::testing::Test { future.wait_for(std::chrono::milliseconds(3)); } - protected: +protected: void SetUp() override { thread_ = new os::Thread("test_thread", os::Thread::Priority::NORMAL); l2cap_handler_ = new os::Handler(thread_); @@ -68,8 +68,10 @@ TEST_F(L2capLeFixedChannelImplTest, get_device) { testing::MockLeAclConnection* mock_acl_connection = new testing::MockLeAclConnection(); EXPECT_CALL(*mock_acl_connection, GetRemoteAddress()).Times(1); MockLink mock_le_link(l2cap_handler_, &mock_parameter_provider, - std::unique_ptr(mock_acl_connection), nullptr /* LinkManager* */); - AddressWithType device{{{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}, hci::AddressType::PUBLIC_DEVICE_ADDRESS}; + std::unique_ptr(mock_acl_connection), + nullptr /* LinkManager* */); + AddressWithType device{{{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}, + hci::AddressType::PUBLIC_DEVICE_ADDRESS}; EXPECT_CALL(mock_le_link, GetDevice()).WillRepeatedly(Return(device)); log::info("------------------"); FixedChannelImpl fixed_channel_impl(kSmpBrCid, &mock_le_link, l2cap_handler_); @@ -82,8 +84,10 @@ TEST_F(L2capLeFixedChannelImplTest, close_triggers_callback) { testing::MockLeAclConnection* mock_acl_connection = new testing::MockLeAclConnection(); EXPECT_CALL(*mock_acl_connection, GetRemoteAddress()).Times(1); MockLink mock_le_link(l2cap_handler_, &mock_parameter_provider, - std::unique_ptr(mock_acl_connection), nullptr /* LinkManager* */); - AddressWithType device{{{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}, hci::AddressType::PUBLIC_DEVICE_ADDRESS}; + std::unique_ptr(mock_acl_connection), + nullptr /* LinkManager* */); + AddressWithType device{{{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}, + hci::AddressType::PUBLIC_DEVICE_ADDRESS}; EXPECT_CALL(mock_le_link, GetDevice()).WillRepeatedly(Return(device)); FixedChannelImpl fixed_channel_impl(kSmpBrCid, &mock_le_link, l2cap_handler_); @@ -91,7 +95,8 @@ TEST_F(L2capLeFixedChannelImplTest, close_triggers_callback) { auto user_handler = std::make_unique(thread_); hci::ErrorCode my_status = hci::ErrorCode::SUCCESS; fixed_channel_impl.RegisterOnCloseCallback( - user_handler.get(), common::testing::BindLambdaForTesting([&](hci::ErrorCode status) { my_status = status; })); + user_handler.get(), common::testing::BindLambdaForTesting( + [&](hci::ErrorCode status) { my_status = status; })); // Channel closure should trigger such callback fixed_channel_impl.OnClosed(hci::ErrorCode::REMOTE_USER_TERMINATED_CONNECTION); @@ -107,8 +112,10 @@ TEST_F(L2capLeFixedChannelImplTest, register_callback_after_close_should_call_im testing::MockLeAclConnection* mock_acl_connection = new testing::MockLeAclConnection(); EXPECT_CALL(*mock_acl_connection, GetRemoteAddress()).Times(1); MockLink mock_le_link(l2cap_handler_, &mock_parameter_provider, - std::unique_ptr(mock_acl_connection), nullptr /* LinkManager* */); - AddressWithType device{{{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}, hci::AddressType::PUBLIC_DEVICE_ADDRESS}; + std::unique_ptr(mock_acl_connection), + nullptr /* LinkManager* */); + AddressWithType device{{{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}, + hci::AddressType::PUBLIC_DEVICE_ADDRESS}; EXPECT_CALL(mock_le_link, GetDevice()).WillRepeatedly(Return(device)); FixedChannelImpl fixed_channel_impl(kSmpBrCid, &mock_le_link, l2cap_handler_); @@ -119,7 +126,8 @@ TEST_F(L2capLeFixedChannelImplTest, register_callback_after_close_should_call_im auto user_handler = std::make_unique(thread_); hci::ErrorCode my_status = hci::ErrorCode::SUCCESS; fixed_channel_impl.RegisterOnCloseCallback( - user_handler.get(), common::testing::BindLambdaForTesting([&](hci::ErrorCode status) { my_status = status; })); + user_handler.get(), common::testing::BindLambdaForTesting( + [&](hci::ErrorCode status) { my_status = status; })); SyncHandler(user_handler.get()); EXPECT_EQ(hci::ErrorCode::REMOTE_USER_TERMINATED_CONNECTION, my_status); @@ -132,8 +140,10 @@ TEST_F(L2capLeFixedChannelImplTest, close_twice_should_fail) { testing::MockLeAclConnection* mock_acl_connection = new testing::MockLeAclConnection(); EXPECT_CALL(*mock_acl_connection, GetRemoteAddress()).Times(1); MockLink mock_le_link(l2cap_handler_, &mock_parameter_provider, - std::unique_ptr(mock_acl_connection), nullptr /* LinkManager* */); - AddressWithType device{{{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}, hci::AddressType::PUBLIC_DEVICE_ADDRESS}; + std::unique_ptr(mock_acl_connection), + nullptr /* LinkManager* */); + AddressWithType device{{{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}, + hci::AddressType::PUBLIC_DEVICE_ADDRESS}; EXPECT_CALL(mock_le_link, GetDevice()).WillRepeatedly(Return(device)); FixedChannelImpl fixed_channel_impl(kSmpBrCid, &mock_le_link, l2cap_handler_); @@ -141,7 +151,8 @@ TEST_F(L2capLeFixedChannelImplTest, close_twice_should_fail) { auto user_handler = std::make_unique(thread_); hci::ErrorCode my_status = hci::ErrorCode::SUCCESS; fixed_channel_impl.RegisterOnCloseCallback( - user_handler.get(), common::testing::BindLambdaForTesting([&](hci::ErrorCode status) { my_status = status; })); + user_handler.get(), common::testing::BindLambdaForTesting( + [&](hci::ErrorCode status) { my_status = status; })); // Channel closure should trigger such callback fixed_channel_impl.OnClosed(hci::ErrorCode::REMOTE_USER_TERMINATED_CONNECTION); @@ -160,8 +171,10 @@ TEST_F(L2capLeFixedChannelImplTest, multiple_registeration_should_fail) { testing::MockLeAclConnection* mock_acl_connection = new testing::MockLeAclConnection(); EXPECT_CALL(*mock_acl_connection, GetRemoteAddress()).Times(1); MockLink mock_le_link(l2cap_handler_, &mock_parameter_provider, - std::unique_ptr(mock_acl_connection), nullptr /* LinkManager* */); - AddressWithType device{{{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}, hci::AddressType::PUBLIC_DEVICE_ADDRESS}; + std::unique_ptr(mock_acl_connection), + nullptr /* LinkManager* */); + AddressWithType device{{{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}, + hci::AddressType::PUBLIC_DEVICE_ADDRESS}; EXPECT_CALL(mock_le_link, GetDevice()).WillRepeatedly(Return(device)); FixedChannelImpl fixed_channel_impl(kSmpBrCid, &mock_le_link, l2cap_handler_); @@ -169,10 +182,11 @@ TEST_F(L2capLeFixedChannelImplTest, multiple_registeration_should_fail) { auto user_handler = std::make_unique(thread_); hci::ErrorCode my_status = hci::ErrorCode::SUCCESS; fixed_channel_impl.RegisterOnCloseCallback( - user_handler.get(), common::testing::BindLambdaForTesting([&](hci::ErrorCode status) { my_status = status; })); + user_handler.get(), common::testing::BindLambdaForTesting( + [&](hci::ErrorCode status) { my_status = status; })); - EXPECT_DEATH(fixed_channel_impl.RegisterOnCloseCallback(user_handler.get(), - common::BindOnce([](hci::ErrorCode status) { FAIL(); })), + EXPECT_DEATH(fixed_channel_impl.RegisterOnCloseCallback( + user_handler.get(), common::BindOnce([](hci::ErrorCode status) { FAIL(); })), ".*RegisterOnCloseCallback.*"); user_handler->Clear(); @@ -184,8 +198,10 @@ TEST_F(L2capLeFixedChannelImplTest, call_acquire_before_registeration_should_fai testing::MockLeAclConnection* mock_acl_connection = new testing::MockLeAclConnection(); EXPECT_CALL(*mock_acl_connection, GetRemoteAddress()).Times(1); MockLink mock_le_link(l2cap_handler_, &mock_parameter_provider, - std::unique_ptr(mock_acl_connection), nullptr /* LinkManager* */); - AddressWithType device{{{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}, hci::AddressType::PUBLIC_DEVICE_ADDRESS}; + std::unique_ptr(mock_acl_connection), + nullptr /* LinkManager* */); + AddressWithType device{{{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}, + hci::AddressType::PUBLIC_DEVICE_ADDRESS}; EXPECT_CALL(mock_le_link, GetDevice()).WillRepeatedly(Return(device)); FixedChannelImpl fixed_channel_impl(kSmpBrCid, &mock_le_link, l2cap_handler_); EXPECT_DEATH(fixed_channel_impl.Acquire(), ".*Acquire.*"); @@ -197,8 +213,10 @@ TEST_F(L2capLeFixedChannelImplTest, call_release_before_registeration_should_fai testing::MockLeAclConnection* mock_acl_connection = new testing::MockLeAclConnection(); EXPECT_CALL(*mock_acl_connection, GetRemoteAddress()).Times(1); MockLink mock_le_link(l2cap_handler_, &mock_parameter_provider, - std::unique_ptr(mock_acl_connection), nullptr /* LinkManager* */); - AddressWithType device{{{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}, hci::AddressType::PUBLIC_DEVICE_ADDRESS}; + std::unique_ptr(mock_acl_connection), + nullptr /* LinkManager* */); + AddressWithType device{{{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}, + hci::AddressType::PUBLIC_DEVICE_ADDRESS}; EXPECT_CALL(mock_le_link, GetDevice()).WillRepeatedly(Return(device)); FixedChannelImpl fixed_channel_impl(kSmpBrCid, &mock_le_link, l2cap_handler_); EXPECT_DEATH(fixed_channel_impl.Release(), ".*Release.*"); @@ -210,8 +228,10 @@ TEST_F(L2capLeFixedChannelImplTest, test_acquire_release_channel) { testing::MockLeAclConnection* mock_acl_connection = new testing::MockLeAclConnection(); EXPECT_CALL(*mock_acl_connection, GetRemoteAddress()).Times(1); MockLink mock_le_link(l2cap_handler_, &mock_parameter_provider, - std::unique_ptr(mock_acl_connection), nullptr /* LinkManager* */); - AddressWithType device{{{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}, hci::AddressType::PUBLIC_DEVICE_ADDRESS}; + std::unique_ptr(mock_acl_connection), + nullptr /* LinkManager* */); + AddressWithType device{{{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}, + hci::AddressType::PUBLIC_DEVICE_ADDRESS}; EXPECT_CALL(mock_le_link, GetDevice()).WillRepeatedly(Return(device)); FixedChannelImpl fixed_channel_impl(kSmpBrCid, &mock_le_link, l2cap_handler_); @@ -219,7 +239,8 @@ TEST_F(L2capLeFixedChannelImplTest, test_acquire_release_channel) { auto user_handler = std::make_unique(thread_); hci::ErrorCode my_status = hci::ErrorCode::SUCCESS; fixed_channel_impl.RegisterOnCloseCallback( - user_handler.get(), common::testing::BindLambdaForTesting([&](hci::ErrorCode status) { my_status = status; })); + user_handler.get(), common::testing::BindLambdaForTesting( + [&](hci::ErrorCode status) { my_status = status; })); // Default should be false EXPECT_FALSE(fixed_channel_impl.IsAcquired()); @@ -242,8 +263,10 @@ TEST_F(L2capLeFixedChannelImplTest, test_acquire_after_close) { testing::MockLeAclConnection* mock_acl_connection = new testing::MockLeAclConnection(); EXPECT_CALL(*mock_acl_connection, GetRemoteAddress()).Times(1); MockLink mock_le_link(l2cap_handler_, &mock_parameter_provider, - std::unique_ptr(mock_acl_connection), nullptr /* LinkManager* */); - AddressWithType device{{{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}, hci::AddressType::PUBLIC_DEVICE_ADDRESS}; + std::unique_ptr(mock_acl_connection), + nullptr /* LinkManager* */); + AddressWithType device{{{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}, + hci::AddressType::PUBLIC_DEVICE_ADDRESS}; EXPECT_CALL(mock_le_link, GetDevice()).WillRepeatedly(Return(device)); FixedChannelImpl fixed_channel_impl(kSmpBrCid, &mock_le_link, l2cap_handler_); @@ -251,7 +274,8 @@ TEST_F(L2capLeFixedChannelImplTest, test_acquire_after_close) { auto user_handler = std::make_unique(thread_); hci::ErrorCode my_status = hci::ErrorCode::SUCCESS; fixed_channel_impl.RegisterOnCloseCallback( - user_handler.get(), common::testing::BindLambdaForTesting([&](hci::ErrorCode status) { my_status = status; })); + user_handler.get(), common::testing::BindLambdaForTesting( + [&](hci::ErrorCode status) { my_status = status; })); // Channel closure should trigger such callback fixed_channel_impl.OnClosed(hci::ErrorCode::REMOTE_USER_TERMINATED_CONNECTION); diff --git a/system/gd/l2cap/le/internal/fixed_channel_service_impl.h b/system/gd/l2cap/le/internal/fixed_channel_service_impl.h index 5eed7777d43..8e70214543e 100644 --- a/system/gd/l2cap/le/internal/fixed_channel_service_impl.h +++ b/system/gd/l2cap/le/internal/fixed_channel_service_impl.h @@ -26,7 +26,7 @@ namespace le { namespace internal { class FixedChannelServiceImpl { - public: +public: virtual ~FixedChannelServiceImpl() = default; struct PendingRegistration { @@ -41,13 +41,14 @@ class FixedChannelServiceImpl { friend class FixedChannelServiceManagerImpl; - protected: +protected: // protected access for mocking FixedChannelServiceImpl(os::Handler* user_handler, FixedChannelManager::OnConnectionOpenCallback on_connection_open_callback) - : user_handler_(user_handler), on_connection_open_callback_(std::move(on_connection_open_callback)) {} + : user_handler_(user_handler), + on_connection_open_callback_(std::move(on_connection_open_callback)) {} - private: +private: os::Handler* user_handler_ = nullptr; FixedChannelManager::OnConnectionOpenCallback on_connection_open_callback_; }; diff --git a/system/gd/l2cap/le/internal/fixed_channel_service_impl_mock.h b/system/gd/l2cap/le/internal/fixed_channel_service_impl_mock.h index 5a1b65d224f..f85437102ce 100644 --- a/system/gd/l2cap/le/internal/fixed_channel_service_impl_mock.h +++ b/system/gd/l2cap/le/internal/fixed_channel_service_impl_mock.h @@ -15,11 +15,11 @@ */ #pragma once +#include + #include "l2cap/le/internal/fixed_channel_impl.h" #include "l2cap/le/internal/fixed_channel_service_manager_impl.h" -#include - // Unit test interfaces namespace bluetooth { namespace l2cap { @@ -28,8 +28,9 @@ namespace internal { namespace testing { class MockFixedChannelServiceImpl : public FixedChannelServiceImpl { - public: - MockFixedChannelServiceImpl() : FixedChannelServiceImpl(nullptr, FixedChannelManager::OnConnectionOpenCallback()) {} +public: + MockFixedChannelServiceImpl() + : FixedChannelServiceImpl(nullptr, FixedChannelManager::OnConnectionOpenCallback()) {} MOCK_METHOD(void, NotifyChannelCreation, (std::unique_ptr channel), (override)); }; diff --git a/system/gd/l2cap/le/internal/fixed_channel_service_manager_impl.cc b/system/gd/l2cap/le/internal/fixed_channel_service_manager_impl.cc index f8ace1ca20b..dcd0398cee9 100644 --- a/system/gd/l2cap/le/internal/fixed_channel_service_manager_impl.cc +++ b/system/gd/l2cap/le/internal/fixed_channel_service_manager_impl.cc @@ -28,31 +28,35 @@ namespace l2cap { namespace le { namespace internal { -void FixedChannelServiceManagerImpl::Register(Cid cid, - FixedChannelServiceImpl::PendingRegistration pending_registration) { +void FixedChannelServiceManagerImpl::Register( + Cid cid, FixedChannelServiceImpl::PendingRegistration pending_registration) { if (cid < kFirstFixedChannel || cid > kLastFixedChannel || cid == kLeSignallingCid) { std::unique_ptr invalid_service(new FixedChannelService()); pending_registration.user_handler_->Post( - common::BindOnce(std::move(pending_registration.on_registration_complete_callback_), - FixedChannelManager::RegistrationResult::FAIL_INVALID_SERVICE, std::move(invalid_service))); + common::BindOnce(std::move(pending_registration.on_registration_complete_callback_), + FixedChannelManager::RegistrationResult::FAIL_INVALID_SERVICE, + std::move(invalid_service))); } else if (IsServiceRegistered(cid)) { std::unique_ptr invalid_service(new FixedChannelService()); pending_registration.user_handler_->Post( - common::BindOnce(std::move(pending_registration.on_registration_complete_callback_), - FixedChannelManager::RegistrationResult::FAIL_DUPLICATE_SERVICE, std::move(invalid_service))); + common::BindOnce(std::move(pending_registration.on_registration_complete_callback_), + FixedChannelManager::RegistrationResult::FAIL_DUPLICATE_SERVICE, + std::move(invalid_service))); } else { - service_map_.try_emplace(cid, - FixedChannelServiceImpl(pending_registration.user_handler_, - std::move(pending_registration.on_connection_open_callback_))); - std::unique_ptr user_service(new FixedChannelService(cid, this, l2cap_layer_handler_)); - pending_registration.user_handler_->Post( - common::BindOnce(std::move(pending_registration.on_registration_complete_callback_), - FixedChannelManager::RegistrationResult::SUCCESS, std::move(user_service))); + service_map_.try_emplace( + cid, + FixedChannelServiceImpl(pending_registration.user_handler_, + std::move(pending_registration.on_connection_open_callback_))); + std::unique_ptr user_service( + new FixedChannelService(cid, this, l2cap_layer_handler_)); + pending_registration.user_handler_->Post(common::BindOnce( + std::move(pending_registration.on_registration_complete_callback_), + FixedChannelManager::RegistrationResult::SUCCESS, std::move(user_service))); } } -void FixedChannelServiceManagerImpl::Unregister(Cid cid, FixedChannelService::OnUnregisteredCallback callback, - os::Handler* handler) { +void FixedChannelServiceManagerImpl::Unregister( + Cid cid, FixedChannelService::OnUnregisteredCallback callback, os::Handler* handler) { if (IsServiceRegistered(cid)) { service_map_.erase(cid); handler->Post(std::move(callback)); @@ -70,7 +74,8 @@ FixedChannelServiceImpl* FixedChannelServiceManagerImpl::GetService(Cid cid) { return &service_map_.find(cid)->second; } -std::vector> FixedChannelServiceManagerImpl::GetRegisteredServices() { +std::vector> +FixedChannelServiceManagerImpl::GetRegisteredServices() { std::vector> results; for (auto& elem : service_map_) { results.emplace_back(elem.first, &elem.second); diff --git a/system/gd/l2cap/le/internal/fixed_channel_service_manager_impl.h b/system/gd/l2cap/le/internal/fixed_channel_service_manager_impl.h index d57c19246f2..b49a4f4f357 100644 --- a/system/gd/l2cap/le/internal/fixed_channel_service_manager_impl.h +++ b/system/gd/l2cap/le/internal/fixed_channel_service_manager_impl.h @@ -29,7 +29,7 @@ namespace le { namespace internal { class FixedChannelServiceManagerImpl { - public: +public: explicit FixedChannelServiceManagerImpl(os::Handler* l2cap_layer_handler) : l2cap_layer_handler_(l2cap_layer_handler) {} virtual ~FixedChannelServiceManagerImpl() = default; @@ -37,12 +37,13 @@ class FixedChannelServiceManagerImpl { // All APIs must be invoked in L2CAP layer handler virtual void Register(Cid cid, FixedChannelServiceImpl::PendingRegistration pending_registration); - virtual void Unregister(Cid cid, FixedChannelService::OnUnregisteredCallback callback, os::Handler* handler); + virtual void Unregister(Cid cid, FixedChannelService::OnUnregisteredCallback callback, + os::Handler* handler); virtual bool IsServiceRegistered(Cid cid) const; virtual FixedChannelServiceImpl* GetService(Cid cid); virtual std::vector> GetRegisteredServices(); - private: +private: os::Handler* l2cap_layer_handler_ = nullptr; std::unordered_map service_map_; }; diff --git a/system/gd/l2cap/le/internal/fixed_channel_service_manager_impl_mock.h b/system/gd/l2cap/le/internal/fixed_channel_service_manager_impl_mock.h index 068599b14de..f8e51f53ffc 100644 --- a/system/gd/l2cap/le/internal/fixed_channel_service_manager_impl_mock.h +++ b/system/gd/l2cap/le/internal/fixed_channel_service_manager_impl_mock.h @@ -15,11 +15,11 @@ */ #pragma once +#include + #include "l2cap/le/internal/fixed_channel_impl.h" #include "l2cap/le/internal/fixed_channel_service_manager_impl.h" -#include - // Unit test interfaces namespace bluetooth { namespace l2cap { @@ -28,14 +28,18 @@ namespace internal { namespace testing { class MockFixedChannelServiceManagerImpl : public FixedChannelServiceManagerImpl { - public: +public: MockFixedChannelServiceManagerImpl() : FixedChannelServiceManagerImpl(nullptr) {} - MOCK_METHOD(void, Register, (Cid cid, FixedChannelServiceImpl::PendingRegistration pending_registration), (override)); - MOCK_METHOD(void, Unregister, (Cid cid, FixedChannelService::OnUnregisteredCallback callback, os::Handler* handler), + MOCK_METHOD(void, Register, + (Cid cid, FixedChannelServiceImpl::PendingRegistration pending_registration), + (override)); + MOCK_METHOD(void, Unregister, + (Cid cid, FixedChannelService::OnUnregisteredCallback callback, os::Handler* handler), (override)); MOCK_METHOD(bool, IsServiceRegistered, (Cid cid), (const, override)); MOCK_METHOD(FixedChannelServiceImpl*, GetService, (Cid cid), (override)); - MOCK_METHOD((std::vector>), GetRegisteredServices, (), (override)); + MOCK_METHOD((std::vector>), GetRegisteredServices, (), + (override)); }; } // namespace testing diff --git a/system/gd/l2cap/le/internal/fixed_channel_service_manager_test.cc b/system/gd/l2cap/le/internal/fixed_channel_service_manager_test.cc index efacf9dbdbd..645b30ba71f 100644 --- a/system/gd/l2cap/le/internal/fixed_channel_service_manager_test.cc +++ b/system/gd/l2cap/le/internal/fixed_channel_service_manager_test.cc @@ -14,7 +14,7 @@ * limitations under the License. */ -#include "l2cap/le/internal/fixed_channel_service_manager_impl.h" +#include #include @@ -22,18 +22,17 @@ #include "l2cap/cid.h" #include "l2cap/le/fixed_channel_manager.h" #include "l2cap/le/fixed_channel_service.h" +#include "l2cap/le/internal/fixed_channel_service_manager_impl.h" #include "os/handler.h" #include "os/thread.h" -#include - namespace bluetooth { namespace l2cap { namespace le { namespace internal { class L2capLeServiceManagerTest : public ::testing::Test { - public: +public: ~L2capLeServiceManagerTest() = default; void OnServiceRegistered(bool expect_success, FixedChannelManager::RegistrationResult result, @@ -42,7 +41,7 @@ class L2capLeServiceManagerTest : public ::testing::Test { service_registered_ = expect_success; } - protected: +protected: void SetUp() override { manager_ = new FixedChannelServiceManagerImpl{nullptr}; thread_ = new os::Thread("test_thread", os::Thread::Priority::NORMAL); @@ -59,7 +58,8 @@ class L2capLeServiceManagerTest : public ::testing::Test { void sync_user_handler() { std::promise promise; auto future = promise.get_future(); - user_handler_->Post(common::BindOnce(&std::promise::set_value, common::Unretained(&promise))); + user_handler_->Post( + common::BindOnce(&std::promise::set_value, common::Unretained(&promise))); future.wait_for(std::chrono::milliseconds(3)); } @@ -72,9 +72,9 @@ class L2capLeServiceManagerTest : public ::testing::Test { TEST_F(L2capLeServiceManagerTest, register_and_unregister_le_fixed_channel) { FixedChannelServiceImpl::PendingRegistration pending_registration{ - .user_handler_ = user_handler_, - .on_registration_complete_callback_ = - common::BindOnce(&L2capLeServiceManagerTest::OnServiceRegistered, common::Unretained(this), true)}; + .user_handler_ = user_handler_, + .on_registration_complete_callback_ = common::BindOnce( + &L2capLeServiceManagerTest::OnServiceRegistered, common::Unretained(this), true)}; Cid cid = kSmpBrCid; EXPECT_FALSE(manager_->IsServiceRegistered(cid)); manager_->Register(cid, std::move(pending_registration)); @@ -87,9 +87,10 @@ TEST_F(L2capLeServiceManagerTest, register_and_unregister_le_fixed_channel) { TEST_F(L2capLeServiceManagerTest, register_le_fixed_channel_bad_cid) { FixedChannelServiceImpl::PendingRegistration pending_registration{ - .user_handler_ = user_handler_, - .on_registration_complete_callback_ = - common::BindOnce(&L2capLeServiceManagerTest::OnServiceRegistered, common::Unretained(this), false)}; + .user_handler_ = user_handler_, + .on_registration_complete_callback_ = + common::BindOnce(&L2capLeServiceManagerTest::OnServiceRegistered, + common::Unretained(this), false)}; Cid cid = 0x1000; EXPECT_FALSE(manager_->IsServiceRegistered(cid)); manager_->Register(cid, std::move(pending_registration)); diff --git a/system/gd/l2cap/le/internal/link.cc b/system/gd/l2cap/le/internal/link.cc index e219294e6b8..8143a9cf451 100644 --- a/system/gd/l2cap/le/internal/link.cc +++ b/system/gd/l2cap/le/internal/link.cc @@ -37,30 +37,25 @@ namespace internal { static constexpr uint16_t kDefaultMinimumCeLength = 0x0002; static constexpr uint16_t kDefaultMaximumCeLength = 0x0C00; -Link::Link( - os::Handler* l2cap_handler, - std::unique_ptr acl_connection, - l2cap::internal::ParameterProvider* parameter_provider, - DynamicChannelServiceManagerImpl* dynamic_service_manager, - FixedChannelServiceManagerImpl* /* fixed_service_manager */, - LinkManager* link_manager) +Link::Link(os::Handler* l2cap_handler, + std::unique_ptr acl_connection, + l2cap::internal::ParameterProvider* parameter_provider, + DynamicChannelServiceManagerImpl* dynamic_service_manager, + FixedChannelServiceManagerImpl* /* fixed_service_manager */, LinkManager* link_manager) : l2cap_handler_(l2cap_handler), acl_connection_(std::move(acl_connection)), data_pipeline_manager_(l2cap_handler, this, acl_connection_->GetAclQueueEnd()), parameter_provider_(parameter_provider), dynamic_service_manager_(dynamic_service_manager), - signalling_manager_( - l2cap_handler_, - this, - &data_pipeline_manager_, - dynamic_service_manager_, - &dynamic_channel_allocator_), + signalling_manager_(l2cap_handler_, this, &data_pipeline_manager_, dynamic_service_manager_, + &dynamic_channel_allocator_), link_manager_(link_manager) { log::assert_that(l2cap_handler_ != nullptr, "assert failed: l2cap_handler_ != nullptr"); log::assert_that(acl_connection_ != nullptr, "assert failed: acl_connection_ != nullptr"); log::assert_that(parameter_provider_ != nullptr, "assert failed: parameter_provider_ != nullptr"); - link_idle_disconnect_alarm_.Schedule(common::BindOnce(&Link::Disconnect, common::Unretained(this)), - parameter_provider_->GetLeLinkIdleDisconnectTimeout()); + link_idle_disconnect_alarm_.Schedule( + common::BindOnce(&Link::Disconnect, common::Unretained(this)), + parameter_provider_->GetLeLinkIdleDisconnectTimeout()); acl_connection_->RegisterCallbacks(this, l2cap_handler_); } @@ -75,26 +70,23 @@ void Link::OnDisconnection(hci::ErrorCode status) { link_manager_->OnDisconnect(GetAclConnection()->GetRemoteAddress()); } -void Link::OnConnectionUpdate( - hci::ErrorCode /* hci_status */, - uint16_t connection_interval, - uint16_t connection_latency, - uint16_t supervision_timeout) { - log::info( - "interval {:x} latency {:x} supervision_timeout {:x}", - connection_interval, - connection_latency, - supervision_timeout); +void Link::OnConnectionUpdate(hci::ErrorCode /* hci_status */, uint16_t connection_interval, + uint16_t connection_latency, uint16_t supervision_timeout) { + log::info("interval {:x} latency {:x} supervision_timeout {:x}", connection_interval, + connection_latency, supervision_timeout); if (update_request_signal_id_ != kInvalidSignalId) { hci::ErrorCode result = hci::ErrorCode::SUCCESS; - if (connection_interval > update_request_interval_max_ || connection_interval < update_request_interval_min_ || - connection_latency != update_request_latency_ || supervision_timeout != update_request_supervision_timeout_) { + if (connection_interval > update_request_interval_max_ || + connection_interval < update_request_interval_min_ || + connection_latency != update_request_latency_ || + supervision_timeout != update_request_supervision_timeout_) { log::info( - "Received connection update complete with different parameters that provided by the " - "Host"); + "Received connection update complete with different parameters that provided by the " + "Host"); } - if (!CheckConnectionParameters(connection_interval, connection_interval, connection_latency, supervision_timeout)) { + if (!CheckConnectionParameters(connection_interval, connection_interval, connection_latency, + supervision_timeout)) { result = hci::ErrorCode::UNSPECIFIED_ERROR; } @@ -103,21 +95,17 @@ void Link::OnConnectionUpdate( } } -void Link::OnParameterUpdateRequest( - uint16_t interval_min, uint16_t interval_max, uint16_t latency, uint16_t supervision_timeout) { - log::info( - "interval_min {:x} interval_max {:x} latency {:x} supervision_timeout {:x}", - interval_min, - interval_max, - latency, - supervision_timeout); +void Link::OnParameterUpdateRequest(uint16_t interval_min, uint16_t interval_max, uint16_t latency, + uint16_t supervision_timeout) { + log::info("interval_min {:x} interval_max {:x} latency {:x} supervision_timeout {:x}", + interval_min, interval_max, latency, supervision_timeout); hci::ErrorCode result = hci::ErrorCode::SUCCESS; if (interval_max > update_request_interval_max_ || interval_min < update_request_interval_min_ || latency != update_request_latency_ || supervision_timeout != update_request_supervision_timeout_) { log::info( - "Received connection update complete with different parameters that provided by the " - "Host"); + "Received connection update complete with different parameters that provided by the " + "Host"); } if (!CheckConnectionParameters(interval_min, interval_max, latency, supervision_timeout)) { @@ -127,46 +115,35 @@ void Link::OnParameterUpdateRequest( } } -void Link::OnDataLengthChange(uint16_t tx_octets, uint16_t tx_time, uint16_t rx_octets, uint16_t rx_time) { - log::info( - "tx_octets {:x} tx_time {:x} rx_octets {:x} rx_time {:x}", - tx_octets, - tx_time, - rx_octets, - rx_time); +void Link::OnDataLengthChange(uint16_t tx_octets, uint16_t tx_time, uint16_t rx_octets, + uint16_t rx_time) { + log::info("tx_octets {:x} tx_time {:x} rx_octets {:x} rx_time {:x}", tx_octets, tx_time, + rx_octets, rx_time); } -void Link::OnReadRemoteVersionInformationComplete( - hci::ErrorCode hci_status, uint8_t lmp_version, uint16_t manufacturer_name, uint16_t sub_version) { - log::info( - "lmp_version:{} manufacturer_name:{} sub_version:{}", - lmp_version, - manufacturer_name, - sub_version); - link_manager_->OnReadRemoteVersionInformationComplete( - hci_status, GetDevice(), lmp_version, manufacturer_name, sub_version); +void Link::OnReadRemoteVersionInformationComplete(hci::ErrorCode hci_status, uint8_t lmp_version, + uint16_t manufacturer_name, + uint16_t sub_version) { + log::info("lmp_version:{} manufacturer_name:{} sub_version:{}", lmp_version, manufacturer_name, + sub_version); + link_manager_->OnReadRemoteVersionInformationComplete(hci_status, GetDevice(), lmp_version, + manufacturer_name, sub_version); } void Link::OnLeReadRemoteFeaturesComplete(hci::ErrorCode /* hci_status*/, uint64_t /* features */) { } -void Link::OnPhyUpdate( - hci::ErrorCode /* hci_status */, uint8_t /* tx_phy */, uint8_t /* rx_phy */) {} +void Link::OnPhyUpdate(hci::ErrorCode /* hci_status */, uint8_t /* tx_phy */, + uint8_t /* rx_phy */) {} -void Link::OnLeSubrateChange( - hci::ErrorCode hci_status, - uint16_t subrate_factor, - uint16_t peripheral_latency, - uint16_t continuation_number, - uint16_t supervision_timeout) { +void Link::OnLeSubrateChange(hci::ErrorCode hci_status, uint16_t subrate_factor, + uint16_t peripheral_latency, uint16_t continuation_number, + uint16_t supervision_timeout) { log::info( - "hci_status: {}, subrate_factor: {:#x}, peripheral_latency: {:#x}, continuation_number: " - "{:#x}, supervision_timeout: {:#x}", - ErrorCodeText(hci_status), - subrate_factor, - peripheral_latency, - continuation_number, - supervision_timeout); + "hci_status: {}, subrate_factor: {:#x}, peripheral_latency: {:#x}, continuation_number: " + "{:#x}, supervision_timeout: {:#x}", + ErrorCodeText(hci_status), subrate_factor, peripheral_latency, continuation_number, + supervision_timeout); } void Link::Disconnect() { @@ -176,8 +153,9 @@ void Link::Disconnect() { void Link::UpdateConnectionParameterFromRemote(SignalId signal_id, uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout) { - acl_connection_->LeConnectionUpdate(conn_interval_min, conn_interval_max, conn_latency, supervision_timeout, - kDefaultMinimumCeLength, kDefaultMaximumCeLength); + acl_connection_->LeConnectionUpdate(conn_interval_min, conn_interval_max, conn_latency, + supervision_timeout, kDefaultMinimumCeLength, + kDefaultMaximumCeLength); update_request_signal_id_ = signal_id; update_request_interval_min_ = conn_interval_min; update_request_interval_max_ = conn_interval_max; @@ -185,8 +163,8 @@ void Link::UpdateConnectionParameterFromRemote(SignalId signal_id, uint16_t conn update_request_supervision_timeout_ = supervision_timeout; } -bool Link::CheckConnectionParameters( - uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout) { +bool Link::CheckConnectionParameters(uint16_t conn_interval_min, uint16_t conn_interval_max, + uint16_t conn_latency, uint16_t supervision_timeout) { if (conn_interval_min < 0x0006 || conn_interval_min > 0x0C80 || conn_interval_max < 0x0006 || conn_interval_max > 0x0C80 || conn_latency > 0x01F3 || supervision_timeout < 0x000A || supervision_timeout > 0x0C80) { @@ -196,8 +174,8 @@ bool Link::CheckConnectionParameters( // The Maximum interval in milliseconds will be conn_interval_max * 1.25 ms // The Timeout in milliseconds will be expected_supervision_timeout * 10 ms - // The Timeout in milliseconds shall be larger than (1 + Latency) * Interval_Max * 2, where Interval_Max is given in - // milliseconds. + // The Timeout in milliseconds shall be larger than (1 + Latency) * Interval_Max * 2, where + // Interval_Max is given in milliseconds. uint32_t supervision_timeout_min = (uint32_t)(1 + conn_latency) * conn_interval_max * 2 + 1; if (supervision_timeout * 8 < supervision_timeout_min || conn_interval_max < conn_interval_min) { log::error("Invalid parameter"); @@ -207,23 +185,25 @@ bool Link::CheckConnectionParameters( return true; } -void Link::SendConnectionParameterUpdate(uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency, - uint16_t supervision_timeout, uint16_t min_ce_length, uint16_t max_ce_length) { +void Link::SendConnectionParameterUpdate(uint16_t conn_interval_min, uint16_t conn_interval_max, + uint16_t conn_latency, uint16_t supervision_timeout, + uint16_t min_ce_length, uint16_t max_ce_length) { if (acl_connection_->GetRole() == hci::Role::PERIPHERAL) { // TODO: If both LL central and peripheral support 4.1, use HCI command directly - signalling_manager_.SendConnectionParameterUpdateRequest(conn_interval_min, conn_interval_max, conn_latency, - supervision_timeout); + signalling_manager_.SendConnectionParameterUpdateRequest(conn_interval_min, conn_interval_max, + conn_latency, supervision_timeout); return; } - acl_connection_->LeConnectionUpdate(conn_interval_min, conn_interval_max, conn_latency, supervision_timeout, - min_ce_length, max_ce_length); + acl_connection_->LeConnectionUpdate(conn_interval_min, conn_interval_max, conn_latency, + supervision_timeout, min_ce_length, max_ce_length); update_request_signal_id_ = kInvalidSignalId; } -std::shared_ptr Link::AllocateFixedChannel( - Cid cid, SecurityPolicy /* security_policy */) { +std::shared_ptr Link::AllocateFixedChannel(Cid cid, + SecurityPolicy /* security_policy */) { auto channel = fixed_channel_allocator_.AllocateChannel(cid); - data_pipeline_manager_.AttachChannel(cid, channel, l2cap::internal::DataPipelineManager::ChannelMode::BASIC); + data_pipeline_manager_.AttachChannel(cid, channel, + l2cap::internal::DataPipelineManager::ChannelMode::BASIC); return channel; } @@ -231,18 +211,18 @@ bool Link::IsFixedChannelAllocated(Cid cid) { return fixed_channel_allocator_.IsChannelAllocated(cid); } -Cid Link::ReserveDynamicChannel() { - return dynamic_channel_allocator_.ReserveChannel(); -} +Cid Link::ReserveDynamicChannel() { return dynamic_channel_allocator_.ReserveChannel(); } -void Link::SendConnectionRequest(Psm psm, PendingDynamicChannelConnection pending_dynamic_channel_connection) { +void Link::SendConnectionRequest( + Psm psm, PendingDynamicChannelConnection pending_dynamic_channel_connection) { if (dynamic_channel_allocator_.IsPsmUsed(psm)) { log::info("Psm {} is already connected", psm); return; } auto reserved_cid = ReserveDynamicChannel(); auto mtu = pending_dynamic_channel_connection.configuration_.mtu; - local_cid_to_pending_dynamic_channel_connection_map_[reserved_cid] = std::move(pending_dynamic_channel_connection); + local_cid_to_pending_dynamic_channel_connection_map_[reserved_cid] = + std::move(pending_dynamic_channel_connection); signalling_manager_.SendConnectionRequest(psm, reserved_cid, mtu); } @@ -254,38 +234,43 @@ void Link::SendDisconnectionRequest(Cid local_cid, Cid remote_cid) { signalling_manager_.SendDisconnectRequest(local_cid, remote_cid); } -void Link::OnOutgoingConnectionRequestFail(Cid local_cid, LeCreditBasedConnectionResponseResult response_result) { +void Link::OnOutgoingConnectionRequestFail(Cid local_cid, + LeCreditBasedConnectionResponseResult response_result) { if (local_cid_to_pending_dynamic_channel_connection_map_.find(local_cid) != local_cid_to_pending_dynamic_channel_connection_map_.end()) { - // TODO(hsz): Currently we only notify the client when the remote didn't send connection response SUCCESS. + // TODO(hsz): Currently we only notify the client when the remote didn't send connection + // response SUCCESS. // Should we notify the client when the link failed to establish? DynamicChannelManager::ConnectionResult result{ - .connection_result_code = DynamicChannelManager::ConnectionResultCode::FAIL_L2CAP_ERROR, - .hci_error = hci::ErrorCode::SUCCESS, - .l2cap_connection_response_result = response_result, + .connection_result_code = DynamicChannelManager::ConnectionResultCode::FAIL_L2CAP_ERROR, + .hci_error = hci::ErrorCode::SUCCESS, + .l2cap_connection_response_result = response_result, }; NotifyChannelFail(local_cid, result); } dynamic_channel_allocator_.FreeChannel(local_cid); } -std::shared_ptr Link::AllocateDynamicChannel(Psm psm, Cid remote_cid) { +std::shared_ptr Link::AllocateDynamicChannel(Psm psm, + Cid remote_cid) { auto channel = dynamic_channel_allocator_.AllocateChannel(psm, remote_cid); if (channel != nullptr) { - data_pipeline_manager_.AttachChannel(channel->GetCid(), channel, - l2cap::internal::DataPipelineManager::ChannelMode::LE_CREDIT_BASED); + data_pipeline_manager_.AttachChannel( + channel->GetCid(), channel, + l2cap::internal::DataPipelineManager::ChannelMode::LE_CREDIT_BASED); RefreshRefCount(); channel->local_initiated_ = false; } return channel; } -std::shared_ptr Link::AllocateReservedDynamicChannel(Cid reserved_cid, Psm psm, - Cid remote_cid) { +std::shared_ptr Link::AllocateReservedDynamicChannel( + Cid reserved_cid, Psm psm, Cid remote_cid) { auto channel = dynamic_channel_allocator_.AllocateReservedChannel(reserved_cid, psm, remote_cid); if (channel != nullptr) { - data_pipeline_manager_.AttachChannel(channel->GetCid(), channel, - l2cap::internal::DataPipelineManager::ChannelMode::LE_CREDIT_BASED); + data_pipeline_manager_.AttachChannel( + channel->GetCid(), channel, + l2cap::internal::DataPipelineManager::ChannelMode::LE_CREDIT_BASED); RefreshRefCount(); channel->local_initiated_ = true; } @@ -309,60 +294,59 @@ void Link::RefreshRefCount() { if (ref_count > 0) { link_idle_disconnect_alarm_.Cancel(); } else { - link_idle_disconnect_alarm_.Schedule(common::BindOnce(&Link::Disconnect, common::Unretained(this)), - parameter_provider_->GetLeLinkIdleDisconnectTimeout()); + link_idle_disconnect_alarm_.Schedule( + common::BindOnce(&Link::Disconnect, common::Unretained(this)), + parameter_provider_->GetLeLinkIdleDisconnectTimeout()); } } void Link::NotifyChannelCreation(Cid cid, std::unique_ptr user_channel) { log::assert_that( - local_cid_to_pending_dynamic_channel_connection_map_.find(cid) != - local_cid_to_pending_dynamic_channel_connection_map_.end(), - "assert failed: local_cid_to_pending_dynamic_channel_connection_map_.find(cid) != " - "local_cid_to_pending_dynamic_channel_connection_map_.end()"); - auto& pending_dynamic_channel_connection = local_cid_to_pending_dynamic_channel_connection_map_[cid]; + local_cid_to_pending_dynamic_channel_connection_map_.find(cid) != + local_cid_to_pending_dynamic_channel_connection_map_.end(), + "assert failed: local_cid_to_pending_dynamic_channel_connection_map_.find(cid) != " + "local_cid_to_pending_dynamic_channel_connection_map_.end()"); + auto& pending_dynamic_channel_connection = + local_cid_to_pending_dynamic_channel_connection_map_[cid]; pending_dynamic_channel_connection.handler_->Post( - common::BindOnce(std::move(pending_dynamic_channel_connection.on_open_callback_), std::move(user_channel))); + common::BindOnce(std::move(pending_dynamic_channel_connection.on_open_callback_), + std::move(user_channel))); local_cid_to_pending_dynamic_channel_connection_map_.erase(cid); } void Link::NotifyChannelFail(Cid cid, DynamicChannelManager::ConnectionResult result) { log::assert_that( - local_cid_to_pending_dynamic_channel_connection_map_.find(cid) != - local_cid_to_pending_dynamic_channel_connection_map_.end(), - "assert failed: local_cid_to_pending_dynamic_channel_connection_map_.find(cid) != " - "local_cid_to_pending_dynamic_channel_connection_map_.end()"); - auto& pending_dynamic_channel_connection = local_cid_to_pending_dynamic_channel_connection_map_[cid]; + local_cid_to_pending_dynamic_channel_connection_map_.find(cid) != + local_cid_to_pending_dynamic_channel_connection_map_.end(), + "assert failed: local_cid_to_pending_dynamic_channel_connection_map_.find(cid) != " + "local_cid_to_pending_dynamic_channel_connection_map_.end()"); + auto& pending_dynamic_channel_connection = + local_cid_to_pending_dynamic_channel_connection_map_[cid]; // TODO(cmanton) Pass proper connection falure result to user - pending_dynamic_channel_connection.handler_->Post( - common::BindOnce(std::move(pending_dynamic_channel_connection.on_fail_callback_), result)); + pending_dynamic_channel_connection.handler_->Post(common::BindOnce( + std::move(pending_dynamic_channel_connection.on_fail_callback_), result)); local_cid_to_pending_dynamic_channel_connection_map_.erase(cid); } -uint16_t Link::GetMps() const { - return parameter_provider_->GetLeMps(); -} +uint16_t Link::GetMps() const { return parameter_provider_->GetLeMps(); } -uint16_t Link::GetInitialCredit() const { - return parameter_provider_->GetLeInitialCredit(); -} +uint16_t Link::GetInitialCredit() const { return parameter_provider_->GetLeInitialCredit(); } void Link::SendLeCredit(Cid local_cid, uint16_t credit) { signalling_manager_.SendCredit(local_cid, credit); } -void Link::ReadRemoteVersionInformation() { - acl_connection_->ReadRemoteVersionInformation(); -} +void Link::ReadRemoteVersionInformation() { acl_connection_->ReadRemoteVersionInformation(); } void Link::on_connection_update_complete(SignalId signal_id, hci::ErrorCode error_code) { if (!signal_id.IsValid()) { log::info("Invalid signal_id"); return; } - ConnectionParameterUpdateResponseResult result = (error_code == hci::ErrorCode::SUCCESS) - ? ConnectionParameterUpdateResponseResult::ACCEPTED - : ConnectionParameterUpdateResponseResult::REJECTED; + ConnectionParameterUpdateResponseResult result = + (error_code == hci::ErrorCode::SUCCESS) + ? ConnectionParameterUpdateResponseResult::ACCEPTED + : ConnectionParameterUpdateResponseResult::REJECTED; signalling_manager_.SendConnectionParameterUpdateResponse(SignalId(), result); } diff --git a/system/gd/l2cap/le/internal/link.h b/system/gd/l2cap/le/internal/link.h index a9f57bafb84..fa8c06ea71f 100644 --- a/system/gd/l2cap/le/internal/link.h +++ b/system/gd/l2cap/le/internal/link.h @@ -46,11 +46,12 @@ class LinkManager; class Link : public l2cap::internal::ILink, public hci::acl_manager::LeConnectionManagementCallbacks, public bluetooth::common::IRedactableLoggable { - public: - Link(os::Handler* l2cap_handler, std::unique_ptr acl_connection, +public: + Link(os::Handler* l2cap_handler, + std::unique_ptr acl_connection, l2cap::internal::ParameterProvider* parameter_provider, - DynamicChannelServiceManagerImpl* dynamic_service_manager, FixedChannelServiceManagerImpl* fixed_service_manager, - LinkManager* link_manager); + DynamicChannelServiceManagerImpl* dynamic_service_manager, + FixedChannelServiceManagerImpl* fixed_service_manager, LinkManager* link_manager); Link(const Link&) = delete; Link& operator=(const Link&) = delete; @@ -68,9 +69,7 @@ class Link : public l2cap::internal::ILink, le::DynamicChannelConfigurationOption configuration_; }; - inline virtual hci::Role GetRole() { - return acl_connection_->GetRole(); - } + inline virtual hci::Role GetRole() { return acl_connection_->GetRole(); } inline virtual hci::acl_manager::LeAclConnection* GetAclConnection() { return acl_connection_.get(); @@ -82,42 +81,36 @@ class Link : public l2cap::internal::ILink, void OnDisconnection(hci::ErrorCode reason) override; - void OnConnectionUpdate( - hci::ErrorCode hci_status, - uint16_t connection_interval, - uint16_t connection_latency, - uint16_t supervision_timeout) override; + void OnConnectionUpdate(hci::ErrorCode hci_status, uint16_t connection_interval, + uint16_t connection_latency, uint16_t supervision_timeout) override; - void OnParameterUpdateRequest( - uint16_t interval_min, - uint16_t interval_max, - uint16_t latency, - uint16_t supervision_timeout) override; + void OnParameterUpdateRequest(uint16_t interval_min, uint16_t interval_max, uint16_t latency, + uint16_t supervision_timeout) override; - void OnDataLengthChange(uint16_t tx_octets, uint16_t tx_time, uint16_t rx_octets, uint16_t rx_time) override; + void OnDataLengthChange(uint16_t tx_octets, uint16_t tx_time, uint16_t rx_octets, + uint16_t rx_time) override; - void OnReadRemoteVersionInformationComplete( - hci::ErrorCode hci_status, uint8_t lmp_version, uint16_t manufacturer_name, uint16_t sub_version) override; + void OnReadRemoteVersionInformationComplete(hci::ErrorCode hci_status, uint8_t lmp_version, + uint16_t manufacturer_name, + uint16_t sub_version) override; void OnLeReadRemoteFeaturesComplete(hci::ErrorCode hci_status, uint64_t features) override; void OnPhyUpdate(hci::ErrorCode hci_status, uint8_t tx_phy, uint8_t rx_phy) override; - void OnLeSubrateChange( - hci::ErrorCode hci_status, - uint16_t subrate_factor, - uint16_t peripheral_latency, - uint16_t continuation_number, - uint16_t supervision_timeout) override; + void OnLeSubrateChange(hci::ErrorCode hci_status, uint16_t subrate_factor, + uint16_t peripheral_latency, uint16_t continuation_number, + uint16_t supervision_timeout) override; virtual void Disconnect(); // Handles connection parameter update request from remote virtual void UpdateConnectionParameterFromRemote(SignalId signal_id, uint16_t conn_interval_min, - uint16_t conn_interval_max, uint16_t conn_latency, + uint16_t conn_interval_max, + uint16_t conn_latency, uint16_t supervision_timeout); - virtual bool CheckConnectionParameters( - uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout); + virtual bool CheckConnectionParameters(uint16_t conn_interval_min, uint16_t conn_interval_max, + uint16_t conn_latency, uint16_t supervision_timeout); virtual void SendConnectionParameterUpdate(uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout, @@ -125,7 +118,8 @@ class Link : public l2cap::internal::ILink, // FixedChannel methods - virtual std::shared_ptr AllocateFixedChannel(Cid cid, SecurityPolicy security_policy); + virtual std::shared_ptr AllocateFixedChannel(Cid cid, + SecurityPolicy security_policy); virtual bool IsFixedChannelAllocated(Cid cid); @@ -133,33 +127,34 @@ class Link : public l2cap::internal::ILink, virtual Cid ReserveDynamicChannel(); - virtual void SendConnectionRequest(Psm psm, PendingDynamicChannelConnection pending_dynamic_channel_connection); + virtual void SendConnectionRequest( + Psm psm, PendingDynamicChannelConnection pending_dynamic_channel_connection); void SendDisconnectionRequest(Cid local_cid, Cid remote_cid) override; - // Invoked by signalling manager to indicate an outgoing connection request failed and link shall free resources - virtual void OnOutgoingConnectionRequestFail(Cid local_cid, LeCreditBasedConnectionResponseResult result); + // Invoked by signalling manager to indicate an outgoing connection request failed and link shall + // free resources + virtual void OnOutgoingConnectionRequestFail(Cid local_cid, + LeCreditBasedConnectionResponseResult result); - virtual std::shared_ptr AllocateDynamicChannel(Psm psm, Cid remote_cid); + virtual std::shared_ptr AllocateDynamicChannel( + Psm psm, Cid remote_cid); - virtual std::shared_ptr AllocateReservedDynamicChannel(Cid reserved_cid, Psm psm, - Cid remote_cid); + virtual std::shared_ptr AllocateReservedDynamicChannel( + Cid reserved_cid, Psm psm, Cid remote_cid); virtual void FreeDynamicChannel(Cid cid); - // Check how many channels are acquired or in use, if zero, start tear down timer, if non-zero, cancel tear down timer + // Check how many channels are acquired or in use, if zero, start tear down timer, if non-zero, + // cancel tear down timer virtual void RefreshRefCount(); void NotifyChannelCreation(Cid cid, std::unique_ptr user_channel); void NotifyChannelFail(Cid cid, DynamicChannelManager::ConnectionResult result); - virtual std::string ToString() { - return GetDevice().ToString(); - } + virtual std::string ToString() { return GetDevice().ToString(); } - std::string ToStringForLogging() const override { - return GetDevice().ToStringForLogging(); - } + std::string ToStringForLogging() const override { return GetDevice().ToStringForLogging(); } std::string ToRedactedStringForLogging() const override { return GetDevice().ToRedactedStringForLogging(); @@ -171,24 +166,24 @@ class Link : public l2cap::internal::ILink, void SendLeCredit(Cid local_cid, uint16_t credit) override; - LinkOptions* GetLinkOptions() { - return &link_options_; - } + LinkOptions* GetLinkOptions() { return &link_options_; } void ReadRemoteVersionInformation(); void OnPendingPacketChange(Cid local_cid, bool has_packet) override; - private: +private: os::Handler* l2cap_handler_; - l2cap::internal::FixedChannelAllocator fixed_channel_allocator_{this, l2cap_handler_}; + l2cap::internal::FixedChannelAllocator fixed_channel_allocator_{ + this, l2cap_handler_}; l2cap::internal::DynamicChannelAllocator dynamic_channel_allocator_{this, l2cap_handler_}; std::unique_ptr acl_connection_; l2cap::internal::DataPipelineManager data_pipeline_manager_; l2cap::internal::ParameterProvider* parameter_provider_; DynamicChannelServiceManagerImpl* dynamic_service_manager_; LeSignallingManager signalling_manager_; - std::unordered_map local_cid_to_pending_dynamic_channel_connection_map_; + std::unordered_map + local_cid_to_pending_dynamic_channel_connection_map_; os::Alarm link_idle_disconnect_alarm_{l2cap_handler_}; LinkOptions link_options_{acl_connection_.get(), this, l2cap_handler_}; LinkManager* link_manager_; @@ -199,9 +194,9 @@ class Link : public l2cap::internal::ILink, uint16_t update_request_supervision_timeout_; std::atomic_int remaining_packets_to_be_sent_ = 0; - // Received connection update complete from ACL manager. SignalId is bound to a valid number when we need to send a - // response to remote. If SignalId is bound to an invalid number, we don't send a response to remote, because the - // connection update request is not from remote LL peripheral. + // Received connection update complete from ACL manager. SignalId is bound to a valid number when + // we need to send a response to remote. If SignalId is bound to an invalid number, we don't send + // a response to remote, because the connection update request is not from remote LL peripheral. void on_connection_update_complete(SignalId signal_id, hci::ErrorCode error_code); }; diff --git a/system/gd/l2cap/le/internal/link_manager.cc b/system/gd/l2cap/le/internal/link_manager.cc index 71392f37a82..ba0782be49c 100644 --- a/system/gd/l2cap/le/internal/link_manager.cc +++ b/system/gd/l2cap/le/internal/link_manager.cc @@ -32,23 +32,26 @@ namespace l2cap { namespace le { namespace internal { -void LinkManager::ConnectFixedChannelServices(hci::AddressWithType address_with_type, - PendingFixedChannelConnection pending_fixed_channel_connection) { +void LinkManager::ConnectFixedChannelServices( + hci::AddressWithType address_with_type, + PendingFixedChannelConnection pending_fixed_channel_connection) { // Check if there is any service registered auto fixed_channel_services = fixed_channel_service_manager_->GetRegisteredServices(); if (fixed_channel_services.empty()) { // If so, return error - pending_fixed_channel_connection.handler_->Post(common::BindOnce( - std::move(pending_fixed_channel_connection.on_fail_callback_), - FixedChannelManager::ConnectionResult{ - .connection_result_code = FixedChannelManager::ConnectionResultCode::FAIL_NO_SERVICE_REGISTERED})); + pending_fixed_channel_connection.handler_->Post( + common::BindOnce(std::move(pending_fixed_channel_connection.on_fail_callback_), + FixedChannelManager::ConnectionResult{ + .connection_result_code = FixedChannelManager:: + ConnectionResultCode::FAIL_NO_SERVICE_REGISTERED})); return; } // Otherwise, check if device has an ACL connection auto* link = GetLink(address_with_type); if (link != nullptr) { // If device already have an ACL connection - // Check if all registered services have an allocated channel and allocate one if not already allocated + // Check if all registered services have an allocated channel and allocate one if not already + // allocated int num_new_channels = 0; for (auto& fixed_channel_service : fixed_channel_services) { if (link->IsFixedChannelAllocated(fixed_channel_service.first)) { @@ -57,17 +60,19 @@ void LinkManager::ConnectFixedChannelServices(hci::AddressWithType address_with_ } // Allocate channel for newly registered fixed channels auto fixed_channel_impl = link->AllocateFixedChannel( - fixed_channel_service.first, SecurityPolicy::NO_SECURITY_WHATSOEVER_PLAINTEXT_TRANSPORT_OK); + fixed_channel_service.first, + SecurityPolicy::NO_SECURITY_WHATSOEVER_PLAINTEXT_TRANSPORT_OK); fixed_channel_service.second->NotifyChannelCreation( - std::make_unique(fixed_channel_impl, l2cap_handler_)); + std::make_unique(fixed_channel_impl, l2cap_handler_)); num_new_channels++; } // Declare connection failure if no new channels are created if (num_new_channels == 0) { pending_fixed_channel_connection.handler_->Post(common::BindOnce( - std::move(pending_fixed_channel_connection.on_fail_callback_), - FixedChannelManager::ConnectionResult{ - .connection_result_code = FixedChannelManager::ConnectionResultCode::FAIL_ALL_SERVICES_HAVE_CHANNEL})); + std::move(pending_fixed_channel_connection.on_fail_callback_), + FixedChannelManager::ConnectionResult{ + .connection_result_code = FixedChannelManager::ConnectionResultCode:: + FAIL_ALL_SERVICES_HAVE_CHANNEL})); } // No need to create ACL connection, return without saving any pending connections return; @@ -80,17 +85,20 @@ void LinkManager::ConnectFixedChannelServices(hci::AddressWithType address_with_ pending_links_.try_emplace(address_with_type); pending_link = pending_links_.find(address_with_type); } - pending_link->second.pending_fixed_channel_connections_.push_back(std::move(pending_fixed_channel_connection)); + pending_link->second.pending_fixed_channel_connections_.push_back( + std::move(pending_fixed_channel_connection)); // Then create new ACL connection acl_manager_->CreateLeConnection(address_with_type, /* is_direct */ true); } void LinkManager::ConnectDynamicChannelServices( - hci::AddressWithType device, Link::PendingDynamicChannelConnection pending_dynamic_channel_connection, Psm psm) { + hci::AddressWithType device, + Link::PendingDynamicChannelConnection pending_dynamic_channel_connection, Psm psm) { auto* link = GetLink(device); if (link == nullptr) { acl_manager_->CreateLeConnection(device, /* is_direct */ true); - pending_dynamic_channels_[device].push_back(std::make_pair(psm, std::move(pending_dynamic_channel_connection))); + pending_dynamic_channels_[device].push_back( + std::make_pair(psm, std::move(pending_dynamic_channel_connection))); return; } link->SendConnectionRequest(psm, std::move(pending_dynamic_channel_connection)); @@ -103,26 +111,24 @@ Link* LinkManager::GetLink(hci::AddressWithType address_with_type) { return &links_.find(address_with_type)->second; } -void LinkManager::OnLeConnectSuccess(hci::AddressWithType connecting_address_with_type, - std::unique_ptr acl_connection) { +void LinkManager::OnLeConnectSuccess( + hci::AddressWithType connecting_address_with_type, + std::unique_ptr acl_connection) { // Same link should not be connected twice hci::AddressWithType connected_address_with_type = acl_connection->GetRemoteAddress(); uint16_t handle = acl_connection->GetHandle(); - log::assert_that( - GetLink(connected_address_with_type) == nullptr, - "{} is connected twice without disconnection", - ADDRESS_TO_LOGGABLE_CSTR(acl_connection->GetRemoteAddress())); - links_.try_emplace(connected_address_with_type, l2cap_handler_, std::move(acl_connection), parameter_provider_, - dynamic_channel_service_manager_, fixed_channel_service_manager_, this); + log::assert_that(GetLink(connected_address_with_type) == nullptr, + "{} is connected twice without disconnection", + ADDRESS_TO_LOGGABLE_CSTR(acl_connection->GetRemoteAddress())); + links_.try_emplace(connected_address_with_type, l2cap_handler_, std::move(acl_connection), + parameter_provider_, dynamic_channel_service_manager_, + fixed_channel_service_manager_, this); auto* link = GetLink(connected_address_with_type); if (link_property_callback_handler_ != nullptr) { - link_property_callback_handler_->CallOn( - link_property_listener_, - &LinkPropertyListener::OnLinkConnected, - connected_address_with_type, - handle, - link->GetRole()); + link_property_callback_handler_->CallOn(link_property_listener_, + &LinkPropertyListener::OnLinkConnected, + connected_address_with_type, handle, link->GetRole()); } // Remove device from pending links list, if any @@ -139,11 +145,14 @@ void LinkManager::OnLeConnectFail(hci::AddressWithType address_with_type, hci::E log::info("Connection to {} failed without a pending link", address_with_type); return; } - for (auto& pending_fixed_channel_connection : pending_link->second.pending_fixed_channel_connections_) { + for (auto& pending_fixed_channel_connection : + pending_link->second.pending_fixed_channel_connections_) { pending_fixed_channel_connection.handler_->Post(common::BindOnce( - std::move(pending_fixed_channel_connection.on_fail_callback_), - FixedChannelManager::ConnectionResult{ - .connection_result_code = FixedChannelManager::ConnectionResultCode::FAIL_HCI_ERROR, .hci_error = reason})); + std::move(pending_fixed_channel_connection.on_fail_callback_), + FixedChannelManager::ConnectionResult{ + .connection_result_code = + FixedChannelManager::ConnectionResultCode::FAIL_HCI_ERROR, + .hci_error = reason})); } // Remove entry in pending link list pending_links_.erase(pending_link); @@ -151,10 +160,8 @@ void LinkManager::OnLeConnectFail(hci::AddressWithType address_with_type, hci::E void LinkManager::OnDisconnect(bluetooth::hci::AddressWithType address_with_type) { auto* link = GetLink(address_with_type); - log::assert_that( - link != nullptr, - "Device {} is disconnected but not in local database", - ADDRESS_TO_LOGGABLE_CSTR(address_with_type)); + log::assert_that(link != nullptr, "Device {} is disconnected but not in local database", + ADDRESS_TO_LOGGABLE_CSTR(address_with_type)); if (links_with_pending_packets_.count(address_with_type) != 0) { disconnected_links_.emplace(address_with_type); } else { @@ -163,30 +170,25 @@ void LinkManager::OnDisconnect(bluetooth::hci::AddressWithType address_with_type if (link_property_callback_handler_ != nullptr) { link_property_callback_handler_->CallOn( - link_property_listener_, &LinkPropertyListener::OnLinkDisconnected, address_with_type); + link_property_listener_, &LinkPropertyListener::OnLinkDisconnected, address_with_type); } } -void LinkManager::RegisterLinkPropertyListener(os::Handler* handler, LinkPropertyListener* listener) { +void LinkManager::RegisterLinkPropertyListener(os::Handler* handler, + LinkPropertyListener* listener) { link_property_callback_handler_ = handler; link_property_listener_ = listener; } -void LinkManager::OnReadRemoteVersionInformationComplete( - hci::ErrorCode hci_status, - hci::AddressWithType address_with_type, - uint8_t lmp_version, - uint16_t manufacturer_name, - uint16_t sub_version) { +void LinkManager::OnReadRemoteVersionInformationComplete(hci::ErrorCode hci_status, + hci::AddressWithType address_with_type, + uint8_t lmp_version, + uint16_t manufacturer_name, + uint16_t sub_version) { if (link_property_callback_handler_ != nullptr) { link_property_callback_handler_->CallOn( - link_property_listener_, - &LinkPropertyListener::OnReadRemoteVersionInformation, - hci_status, - address_with_type, - lmp_version, - manufacturer_name, - sub_version); + link_property_listener_, &LinkPropertyListener::OnReadRemoteVersionInformation, + hci_status, address_with_type, lmp_version, manufacturer_name, sub_version); } auto* link = GetLink(address_with_type); @@ -194,9 +196,10 @@ void LinkManager::OnReadRemoteVersionInformationComplete( auto fixed_channel_services = fixed_channel_service_manager_->GetRegisteredServices(); for (auto& fixed_channel_service : fixed_channel_services) { auto fixed_channel_impl = link->AllocateFixedChannel( - fixed_channel_service.first, SecurityPolicy::NO_SECURITY_WHATSOEVER_PLAINTEXT_TRANSPORT_OK); + fixed_channel_service.first, + SecurityPolicy::NO_SECURITY_WHATSOEVER_PLAINTEXT_TRANSPORT_OK); fixed_channel_service.second->NotifyChannelCreation( - std::make_unique(fixed_channel_impl, l2cap_handler_)); + std::make_unique(fixed_channel_impl, l2cap_handler_)); } if (pending_dynamic_channels_.find(address_with_type) != pending_dynamic_channels_.end()) { for (auto& psm_callback : pending_dynamic_channels_[address_with_type]) { diff --git a/system/gd/l2cap/le/internal/link_manager.h b/system/gd/l2cap/le/internal/link_manager.h index 3a981437563..4453d11c18e 100644 --- a/system/gd/l2cap/le/internal/link_manager.h +++ b/system/gd/l2cap/le/internal/link_manager.h @@ -41,13 +41,11 @@ namespace le { namespace internal { class LinkManager : public hci::acl_manager::LeConnectionCallbacks { - public: - LinkManager( - os::Handler* l2cap_handler, - hci::AclManager* acl_manager, - FixedChannelServiceManagerImpl* service_manager, - DynamicChannelServiceManagerImpl* dynamic_service_manager, - l2cap::internal::ParameterProvider* parameter_provider) +public: + LinkManager(os::Handler* l2cap_handler, hci::AclManager* acl_manager, + FixedChannelServiceManagerImpl* service_manager, + DynamicChannelServiceManagerImpl* dynamic_service_manager, + l2cap::internal::ParameterProvider* parameter_provider) : l2cap_handler_(l2cap_handler), acl_manager_(acl_manager), fixed_channel_service_manager_(service_manager), @@ -71,8 +69,9 @@ class LinkManager : public hci::acl_manager::LeConnectionCallbacks { // ACL methods Link* GetLink(hci::AddressWithType address_with_type); - void OnLeConnectSuccess(hci::AddressWithType connecting_address_with_type, - std::unique_ptr acl_connection) override; + void OnLeConnectSuccess( + hci::AddressWithType connecting_address_with_type, + std::unique_ptr acl_connection) override; void OnLeConnectFail(hci::AddressWithType address_with_type, hci::ErrorCode reason) override; // FixedChannelManager methods @@ -82,8 +81,9 @@ class LinkManager : public hci::acl_manager::LeConnectionCallbacks { // DynamicChannelManager methods - void ConnectDynamicChannelServices(hci::AddressWithType device, - Link::PendingDynamicChannelConnection pending_dynamic_channel_connection, Psm psm); + void ConnectDynamicChannelServices( + hci::AddressWithType device, + Link::PendingDynamicChannelConnection pending_dynamic_channel_connection, Psm psm); void OnDisconnect(hci::AddressWithType address_with_type); @@ -91,18 +91,16 @@ class LinkManager : public hci::acl_manager::LeConnectionCallbacks { void RegisterLinkPropertyListener(os::Handler* handler, LinkPropertyListener* listener); - void OnReadRemoteVersionInformationComplete( - hci::ErrorCode hci_status, - hci::AddressWithType address_with_type, - uint8_t lmp_version, - uint16_t manufacturer_name, - uint16_t sub_version); + void OnReadRemoteVersionInformationComplete(hci::ErrorCode hci_status, + hci::AddressWithType address_with_type, + uint8_t lmp_version, uint16_t manufacturer_name, + uint16_t sub_version); // Reported by link to indicate how many pending packets are remaining to be set. // If there is anything outstanding, don't delete link void OnPendingPacketChange(hci::AddressWithType remote, int num_packets); - private: +private: // Dependencies os::Handler* l2cap_handler_; hci::AclManager* acl_manager_; @@ -113,8 +111,9 @@ class LinkManager : public hci::acl_manager::LeConnectionCallbacks { // Internal states std::unordered_map pending_links_; std::unordered_map links_; - std::unordered_map>> - pending_dynamic_channels_; + std::unordered_map>> + pending_dynamic_channels_; os::Handler* link_property_callback_handler_ = nullptr; LinkPropertyListener* link_property_listener_ = nullptr; std::unordered_set disconnected_links_; diff --git a/system/gd/l2cap/le/internal/link_manager_test.cc b/system/gd/l2cap/le/internal/link_manager_test.cc index 3d90abf2b77..bfdaf518382 100644 --- a/system/gd/l2cap/le/internal/link_manager_test.cc +++ b/system/gd/l2cap/le/internal/link_manager_test.cc @@ -16,6 +16,9 @@ #include "l2cap/le/internal/link_manager.h" +#include +#include + #include #include @@ -31,9 +34,6 @@ #include "os/handler.h" #include "os/thread.h" -#include -#include - namespace bluetooth { namespace l2cap { namespace le { @@ -55,7 +55,7 @@ constexpr static auto kTestIdleDisconnectTimeoutLong = std::chrono::milliseconds constexpr static auto kTestIdleDisconnectTimeoutShort = std::chrono::milliseconds(1000); class L2capLeLinkManagerTest : public ::testing::Test { - public: +public: static void SyncHandler(os::Handler* handler) { std::promise promise; auto future = promise.get_future(); @@ -63,14 +63,14 @@ class L2capLeLinkManagerTest : public ::testing::Test { future.wait_for(std::chrono::milliseconds(3)); } - protected: +protected: void SetUp() override { thread_ = new os::Thread("test_thread", os::Thread::Priority::NORMAL); l2cap_handler_ = new os::Handler(thread_); user_handler_ = new os::Handler(thread_); mock_parameter_provider_ = new MockParameterProvider; EXPECT_CALL(*mock_parameter_provider_, GetLeLinkIdleDisconnectTimeout) - .WillRepeatedly(Return(kTestIdleDisconnectTimeoutLong)); + .WillRepeatedly(Return(kTestIdleDisconnectTimeoutLong)); } void TearDown() override { @@ -98,13 +98,11 @@ TEST_F(L2capLeLinkManagerTest, connect_fixed_channel_service_without_acl) { hci::acl_manager::LeConnectionCallbacks* hci_le_connection_callbacks = nullptr; os::Handler* hci_callback_handler = nullptr; EXPECT_CALL(mock_acl_manager, RegisterLeCallbacks(_, _)) - .WillOnce(DoAll(SaveArg<0>(&hci_le_connection_callbacks), SaveArg<1>(&hci_callback_handler))); - LinkManager le_link_manager( - l2cap_handler_, - &mock_acl_manager, - &mock_le_fixed_channel_service_manager, - nullptr, - mock_parameter_provider_); + .WillOnce(DoAll(SaveArg<0>(&hci_le_connection_callbacks), + SaveArg<1>(&hci_callback_handler))); + LinkManager le_link_manager(l2cap_handler_, &mock_acl_manager, + &mock_le_fixed_channel_service_manager, nullptr, + mock_parameter_provider_); EXPECT_EQ(hci_le_connection_callbacks, &le_link_manager); EXPECT_EQ(hci_callback_handler, l2cap_handler_); @@ -113,47 +111,50 @@ TEST_F(L2capLeLinkManagerTest, connect_fixed_channel_service_without_acl) { std::vector> results; results.emplace_back(kSmpBrCid, &mock_service_1); results.emplace_back(kConnectionlessCid, &mock_service_2); - EXPECT_CALL(mock_le_fixed_channel_service_manager, GetRegisteredServices()).WillRepeatedly(Return(results)); + EXPECT_CALL(mock_le_fixed_channel_service_manager, GetRegisteredServices()) + .WillRepeatedly(Return(results)); // Step 2: Connect to fixed channel without ACL connection should trigger ACL connection process EXPECT_CALL(mock_acl_manager, CreateLeConnection(address_with_type, true)).Times(1); LinkManager::PendingFixedChannelConnection pending_fixed_channel_connection{ - .handler_ = user_handler_, - .on_fail_callback_ = common::BindOnce([](FixedChannelManager::ConnectionResult result) { FAIL(); })}; - le_link_manager.ConnectFixedChannelServices(address_with_type, std::move(pending_fixed_channel_connection)); - - // Step 3: ACL connection success event should trigger channel creation for all registered services + .handler_ = user_handler_, + .on_fail_callback_ = + common::BindOnce([](FixedChannelManager::ConnectionResult result) { FAIL(); })}; + le_link_manager.ConnectFixedChannelServices(address_with_type, + std::move(pending_fixed_channel_connection)); + + // Step 3: ACL connection success event should trigger channel creation for all registered + // services std::unique_ptr acl_connection = std::make_unique(); EXPECT_CALL(*acl_connection, GetRemoteAddress()).WillRepeatedly(Return(address_with_type)); hci::acl_manager::LeConnectionManagementCallbacks* connection_management_callbacks = nullptr; os::Handler* connection_management_handler = nullptr; EXPECT_CALL(*acl_connection, RegisterCallbacks(_, _)) - .WillOnce(DoAll(SaveArg<0>(&connection_management_callbacks), SaveArg<1>(&connection_management_handler))); + .WillOnce(DoAll(SaveArg<0>(&connection_management_callbacks), + SaveArg<1>(&connection_management_handler))); std::unique_ptr channel_1, channel_2; std::promise promise_1, promise_2; auto future_1 = promise_1.get_future(); auto future_2 = promise_2.get_future(); EXPECT_CALL(mock_service_1, NotifyChannelCreation(_)) - .WillOnce([&channel_1, &promise_1](std::unique_ptr channel) { - channel_1 = std::move(channel); - promise_1.set_value(); - }); + .WillOnce([&channel_1, &promise_1](std::unique_ptr channel) { + channel_1 = std::move(channel); + promise_1.set_value(); + }); EXPECT_CALL(mock_service_2, NotifyChannelCreation(_)) - .WillOnce([&channel_2, &promise_2](std::unique_ptr channel) { - channel_2 = std::move(channel); - promise_2.set_value(); - }); - hci_callback_handler->Post(common::BindOnce(&hci::acl_manager::LeConnectionCallbacks::OnLeConnectSuccess, - common::Unretained(hci_le_connection_callbacks), address_with_type, - std::move(acl_connection))); + .WillOnce([&channel_2, &promise_2](std::unique_ptr channel) { + channel_2 = std::move(channel); + promise_2.set_value(); + }); + hci_callback_handler->Post( + common::BindOnce(&hci::acl_manager::LeConnectionCallbacks::OnLeConnectSuccess, + common::Unretained(hci_le_connection_callbacks), address_with_type, + std::move(acl_connection))); SyncHandler(hci_callback_handler); connection_management_handler->Post(common::BindOnce( - &hci::acl_manager::LeConnectionManagementCallbacks::OnReadRemoteVersionInformationComplete, - common::Unretained(connection_management_callbacks), - hci::ErrorCode::SUCCESS, - 0, - 0, - 0)); + &hci::acl_manager::LeConnectionManagementCallbacks:: + OnReadRemoteVersionInformationComplete, + common::Unretained(connection_management_callbacks), hci::ErrorCode::SUCCESS, 0, 0, 0)); auto future_1_status = future_1.wait_for(kTestIdleDisconnectTimeoutShort); EXPECT_EQ(future_1_status, std::future_status::ready); auto future_2_status = future_2.wait_for(kTestIdleDisconnectTimeoutShort); @@ -161,13 +162,17 @@ TEST_F(L2capLeLinkManagerTest, connect_fixed_channel_service_without_acl) { ASSERT_NE(channel_1, nullptr); ASSERT_NE(channel_2, nullptr); - // Step 4: Calling ConnectServices() to the same device will not trigger another connection attempt + // Step 4: Calling ConnectServices() to the same device will not trigger another connection + // attempt FixedChannelManager::ConnectionResult my_result; LinkManager::PendingFixedChannelConnection pending_fixed_channel_connection_2{ - .handler_ = user_handler_, - .on_fail_callback_ = common::testing::BindLambdaForTesting( - [&my_result](FixedChannelManager::ConnectionResult result) { my_result = result; })}; - le_link_manager.ConnectFixedChannelServices(address_with_type, std::move(pending_fixed_channel_connection_2)); + .handler_ = user_handler_, + .on_fail_callback_ = common::testing::BindLambdaForTesting( + [&my_result](FixedChannelManager::ConnectionResult result) { + my_result = result; + })}; + le_link_manager.ConnectFixedChannelServices(address_with_type, + std::move(pending_fixed_channel_connection_2)); SyncHandler(user_handler_); EXPECT_EQ(my_result.connection_result_code, FixedChannelManager::ConnectionResultCode::FAIL_ALL_SERVICES_HAVE_CHANNEL); @@ -175,26 +180,30 @@ TEST_F(L2capLeLinkManagerTest, connect_fixed_channel_service_without_acl) { // Step 5: Register new service will cause new channels to be created during ConnectServices() MockFixedChannelServiceImpl mock_service_3; results.emplace_back(kSmpBrCid + 1, &mock_service_3); - EXPECT_CALL(mock_le_fixed_channel_service_manager, GetRegisteredServices()).WillRepeatedly(Return(results)); + EXPECT_CALL(mock_le_fixed_channel_service_manager, GetRegisteredServices()) + .WillRepeatedly(Return(results)); LinkManager::PendingFixedChannelConnection pending_fixed_channel_connection_3{ - .handler_ = user_handler_, - .on_fail_callback_ = common::BindOnce([](FixedChannelManager::ConnectionResult result) { FAIL(); })}; + .handler_ = user_handler_, + .on_fail_callback_ = + common::BindOnce([](FixedChannelManager::ConnectionResult result) { FAIL(); })}; std::unique_ptr channel_3; std::promise promise_3; auto future_3 = promise_3.get_future(); EXPECT_CALL(mock_service_3, NotifyChannelCreation(_)) - .WillOnce([&channel_3, &promise_3](std::unique_ptr channel) { - channel_3 = std::move(channel); - promise_3.set_value(); - }); - le_link_manager.ConnectFixedChannelServices(address_with_type, std::move(pending_fixed_channel_connection_3)); + .WillOnce([&channel_3, &promise_3](std::unique_ptr channel) { + channel_3 = std::move(channel); + promise_3.set_value(); + }); + le_link_manager.ConnectFixedChannelServices(address_with_type, + std::move(pending_fixed_channel_connection_3)); auto future_3_status = future_3.wait_for(kTestIdleDisconnectTimeoutShort); EXPECT_EQ(future_3_status, std::future_status::ready); EXPECT_NE(channel_3, nullptr); - connection_management_handler->Post(common::BindOnce( - &hci::acl_manager::LeConnectionManagementCallbacks::OnDisconnection, - common::Unretained(connection_management_callbacks), hci::ErrorCode::REMOTE_USER_TERMINATED_CONNECTION)); + connection_management_handler->Post( + common::BindOnce(&hci::acl_manager::LeConnectionManagementCallbacks::OnDisconnection, + common::Unretained(connection_management_callbacks), + hci::ErrorCode::REMOTE_USER_TERMINATED_CONNECTION)); SyncHandler(connection_management_handler); } @@ -208,31 +217,33 @@ TEST_F(L2capLeLinkManagerTest, connect_fixed_channel_service_without_acl_with_no hci::acl_manager::LeConnectionCallbacks* hci_le_connection_callbacks = nullptr; os::Handler* hci_callback_handler = nullptr; EXPECT_CALL(mock_acl_manager, RegisterLeCallbacks(_, _)) - .WillOnce(DoAll(SaveArg<0>(&hci_le_connection_callbacks), SaveArg<1>(&hci_callback_handler))); - LinkManager le_link_manager( - l2cap_handler_, - &mock_acl_manager, - &mock_le_fixed_channel_service_manager, - nullptr, - mock_parameter_provider_); + .WillOnce(DoAll(SaveArg<0>(&hci_le_connection_callbacks), + SaveArg<1>(&hci_callback_handler))); + LinkManager le_link_manager(l2cap_handler_, &mock_acl_manager, + &mock_le_fixed_channel_service_manager, nullptr, + mock_parameter_provider_); EXPECT_EQ(hci_le_connection_callbacks, &le_link_manager); EXPECT_EQ(hci_callback_handler, l2cap_handler_); // Make sure no service is registered std::vector> results; - EXPECT_CALL(mock_le_fixed_channel_service_manager, GetRegisteredServices()).WillRepeatedly(Return(results)); + EXPECT_CALL(mock_le_fixed_channel_service_manager, GetRegisteredServices()) + .WillRepeatedly(Return(results)); // Step 2: Connect to fixed channel without any service registered will result in failure EXPECT_CALL(mock_acl_manager, CreateLeConnection(address_with_type, true)).Times(0); FixedChannelManager::ConnectionResult my_result; LinkManager::PendingFixedChannelConnection pending_fixed_channel_connection{ - .handler_ = user_handler_, - .on_fail_callback_ = common::testing::BindLambdaForTesting( - [&my_result](FixedChannelManager::ConnectionResult result) { my_result = result; })}; - le_link_manager.ConnectFixedChannelServices(address_with_type, std::move(pending_fixed_channel_connection)); + .handler_ = user_handler_, + .on_fail_callback_ = common::testing::BindLambdaForTesting( + [&my_result](FixedChannelManager::ConnectionResult result) { + my_result = result; + })}; + le_link_manager.ConnectFixedChannelServices(address_with_type, + std::move(pending_fixed_channel_connection)); SyncHandler(user_handler_); - EXPECT_EQ(my_result.connection_result_code, FixedChannelManager::ConnectionResultCode::FAIL_NO_SERVICE_REGISTERED); - + EXPECT_EQ(my_result.connection_result_code, + FixedChannelManager::ConnectionResultCode::FAIL_NO_SERVICE_REGISTERED); } TEST_F(L2capLeLinkManagerTest, connect_fixed_channel_service_without_acl_with_hci_failure) { @@ -245,13 +256,11 @@ TEST_F(L2capLeLinkManagerTest, connect_fixed_channel_service_without_acl_with_hc hci::acl_manager::LeConnectionCallbacks* hci_le_connection_callbacks = nullptr; os::Handler* hci_callback_handler = nullptr; EXPECT_CALL(mock_acl_manager, RegisterLeCallbacks(_, _)) - .WillOnce(DoAll(SaveArg<0>(&hci_le_connection_callbacks), SaveArg<1>(&hci_callback_handler))); - LinkManager le_link_manager( - l2cap_handler_, - &mock_acl_manager, - &mock_le_fixed_channel_service_manager, - nullptr, - mock_parameter_provider_); + .WillOnce(DoAll(SaveArg<0>(&hci_le_connection_callbacks), + SaveArg<1>(&hci_callback_handler))); + LinkManager le_link_manager(l2cap_handler_, &mock_acl_manager, + &mock_le_fixed_channel_service_manager, nullptr, + mock_parameter_provider_); EXPECT_EQ(hci_le_connection_callbacks, &le_link_manager); EXPECT_EQ(hci_callback_handler, l2cap_handler_); @@ -259,33 +268,37 @@ TEST_F(L2capLeLinkManagerTest, connect_fixed_channel_service_without_acl_with_hc MockFixedChannelServiceImpl mock_service_1; std::vector> results; results.emplace_back(kSmpBrCid, &mock_service_1); - EXPECT_CALL(mock_le_fixed_channel_service_manager, GetRegisteredServices()).WillRepeatedly(Return(results)); + EXPECT_CALL(mock_le_fixed_channel_service_manager, GetRegisteredServices()) + .WillRepeatedly(Return(results)); // Step 2: Connect to fixed channel without ACL connection should trigger ACL connection process EXPECT_CALL(mock_acl_manager, CreateLeConnection(address_with_type, true)).Times(1); FixedChannelManager::ConnectionResult my_result; LinkManager::PendingFixedChannelConnection pending_fixed_channel_connection{ - .handler_ = user_handler_, - .on_fail_callback_ = common::testing::BindLambdaForTesting( - [&my_result](FixedChannelManager::ConnectionResult result) { my_result = result; })}; - le_link_manager.ConnectFixedChannelServices(address_with_type, std::move(pending_fixed_channel_connection)); + .handler_ = user_handler_, + .on_fail_callback_ = common::testing::BindLambdaForTesting( + [&my_result](FixedChannelManager::ConnectionResult result) { + my_result = result; + })}; + le_link_manager.ConnectFixedChannelServices(address_with_type, + std::move(pending_fixed_channel_connection)); // Step 3: ACL connection failure event should trigger connection failure callback EXPECT_CALL(mock_service_1, NotifyChannelCreation(_)).Times(0); - hci_callback_handler->Post(common::BindOnce( - &hci::acl_manager::LeConnectionCallbacks::OnLeConnectFail, - common::Unretained(hci_le_connection_callbacks), - address_with_type, - hci::ErrorCode::PAGE_TIMEOUT)); + hci_callback_handler->Post( + common::BindOnce(&hci::acl_manager::LeConnectionCallbacks::OnLeConnectFail, + common::Unretained(hci_le_connection_callbacks), address_with_type, + hci::ErrorCode::PAGE_TIMEOUT)); SyncHandler(hci_callback_handler); SyncHandler(user_handler_); - EXPECT_EQ(my_result.connection_result_code, FixedChannelManager::ConnectionResultCode::FAIL_HCI_ERROR); + EXPECT_EQ(my_result.connection_result_code, + FixedChannelManager::ConnectionResultCode::FAIL_HCI_ERROR); EXPECT_EQ(my_result.hci_error, hci::ErrorCode::PAGE_TIMEOUT); } TEST_F(L2capLeLinkManagerTest, not_acquiring_channels_should_disconnect_acl_after_timeout) { EXPECT_CALL(*mock_parameter_provider_, GetLeLinkIdleDisconnectTimeout) - .WillRepeatedly(Return(kTestIdleDisconnectTimeoutShort)); + .WillRepeatedly(Return(kTestIdleDisconnectTimeoutShort)); MockFixedChannelServiceManagerImpl mock_le_fixed_channel_service_manager; MockAclManager mock_acl_manager; hci::AddressWithType address_with_type({{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}, @@ -295,13 +308,11 @@ TEST_F(L2capLeLinkManagerTest, not_acquiring_channels_should_disconnect_acl_afte hci::acl_manager::LeConnectionCallbacks* hci_le_connection_callbacks = nullptr; os::Handler* hci_callback_handler = nullptr; EXPECT_CALL(mock_acl_manager, RegisterLeCallbacks(_, _)) - .WillOnce(DoAll(SaveArg<0>(&hci_le_connection_callbacks), SaveArg<1>(&hci_callback_handler))); - LinkManager le_link_manager( - l2cap_handler_, - &mock_acl_manager, - &mock_le_fixed_channel_service_manager, - nullptr, - mock_parameter_provider_); + .WillOnce(DoAll(SaveArg<0>(&hci_le_connection_callbacks), + SaveArg<1>(&hci_callback_handler))); + LinkManager le_link_manager(l2cap_handler_, &mock_acl_manager, + &mock_le_fixed_channel_service_manager, nullptr, + mock_parameter_provider_); EXPECT_EQ(hci_le_connection_callbacks, &le_link_manager); EXPECT_EQ(hci_callback_handler, l2cap_handler_); @@ -310,48 +321,51 @@ TEST_F(L2capLeLinkManagerTest, not_acquiring_channels_should_disconnect_acl_afte std::vector> results; results.emplace_back(kSmpBrCid, &mock_service_1); results.emplace_back(kConnectionlessCid, &mock_service_2); - EXPECT_CALL(mock_le_fixed_channel_service_manager, GetRegisteredServices()).WillRepeatedly(Return(results)); + EXPECT_CALL(mock_le_fixed_channel_service_manager, GetRegisteredServices()) + .WillRepeatedly(Return(results)); // Step 2: Connect to fixed channel without ACL connection should trigger ACL connection process EXPECT_CALL(mock_acl_manager, CreateLeConnection(address_with_type, true)).Times(1); LinkManager::PendingFixedChannelConnection pending_fixed_channel_connection{ - .handler_ = user_handler_, - .on_fail_callback_ = common::BindOnce([](FixedChannelManager::ConnectionResult result) { FAIL(); })}; - le_link_manager.ConnectFixedChannelServices(address_with_type, std::move(pending_fixed_channel_connection)); - - // Step 3: ACL connection success event should trigger channel creation for all registered services + .handler_ = user_handler_, + .on_fail_callback_ = + common::BindOnce([](FixedChannelManager::ConnectionResult result) { FAIL(); })}; + le_link_manager.ConnectFixedChannelServices(address_with_type, + std::move(pending_fixed_channel_connection)); + + // Step 3: ACL connection success event should trigger channel creation for all registered + // services auto* raw_acl_connection = new MockLeAclConnection(); std::unique_ptr acl_connection(raw_acl_connection); EXPECT_CALL(*acl_connection, GetRemoteAddress()).WillRepeatedly(Return(address_with_type)); hci::acl_manager::LeConnectionManagementCallbacks* connection_management_callbacks = nullptr; os::Handler* connection_management_handler = nullptr; EXPECT_CALL(*acl_connection, RegisterCallbacks(_, _)) - .WillOnce(DoAll(SaveArg<0>(&connection_management_callbacks), SaveArg<1>(&connection_management_handler))); + .WillOnce(DoAll(SaveArg<0>(&connection_management_callbacks), + SaveArg<1>(&connection_management_handler))); std::unique_ptr channel_1, channel_2; std::promise promise_1, promise_2; auto future_1 = promise_1.get_future(); auto future_2 = promise_2.get_future(); EXPECT_CALL(mock_service_1, NotifyChannelCreation(_)) - .WillOnce([&channel_1, &promise_1](std::unique_ptr channel) { - channel_1 = std::move(channel); - promise_1.set_value(); - }); + .WillOnce([&channel_1, &promise_1](std::unique_ptr channel) { + channel_1 = std::move(channel); + promise_1.set_value(); + }); EXPECT_CALL(mock_service_2, NotifyChannelCreation(_)) - .WillOnce([&channel_2, &promise_2](std::unique_ptr channel) { - channel_2 = std::move(channel); - promise_2.set_value(); - }); - hci_callback_handler->Post(common::BindOnce(&hci::acl_manager::LeConnectionCallbacks::OnLeConnectSuccess, - common::Unretained(hci_le_connection_callbacks), address_with_type, - std::move(acl_connection))); + .WillOnce([&channel_2, &promise_2](std::unique_ptr channel) { + channel_2 = std::move(channel); + promise_2.set_value(); + }); + hci_callback_handler->Post( + common::BindOnce(&hci::acl_manager::LeConnectionCallbacks::OnLeConnectSuccess, + common::Unretained(hci_le_connection_callbacks), address_with_type, + std::move(acl_connection))); SyncHandler(hci_callback_handler); connection_management_handler->Post(common::BindOnce( - &hci::acl_manager::LeConnectionManagementCallbacks::OnReadRemoteVersionInformationComplete, - common::Unretained(connection_management_callbacks), - hci::ErrorCode::SUCCESS, - 0, - 0, - 0)); + &hci::acl_manager::LeConnectionManagementCallbacks:: + OnReadRemoteVersionInformationComplete, + common::Unretained(connection_management_callbacks), hci::ErrorCode::SUCCESS, 0, 0, 0)); auto future_1_status = future_1.wait_for(kTestIdleDisconnectTimeoutShort); EXPECT_EQ(future_1_status, std::future_status::ready); EXPECT_NE(channel_1, nullptr); @@ -360,17 +374,22 @@ TEST_F(L2capLeLinkManagerTest, not_acquiring_channels_should_disconnect_acl_afte EXPECT_NE(channel_2, nullptr); hci::ErrorCode status_1 = hci::ErrorCode::SUCCESS; channel_1->RegisterOnCloseCallback( - user_handler_, common::testing::BindLambdaForTesting([&](hci::ErrorCode status) { status_1 = status; })); + user_handler_, + common::testing::BindLambdaForTesting([&](hci::ErrorCode status) { status_1 = status; })); hci::ErrorCode status_2 = hci::ErrorCode::SUCCESS; channel_2->RegisterOnCloseCallback( - user_handler_, common::testing::BindLambdaForTesting([&](hci::ErrorCode status) { status_2 = status; })); + user_handler_, + common::testing::BindLambdaForTesting([&](hci::ErrorCode status) { status_2 = status; })); // Step 4: Leave channel IDLE long enough, they will disconnect - EXPECT_CALL(*raw_acl_connection, Disconnect(hci::DisconnectReason::REMOTE_USER_TERMINATED_CONNECTION)).Times(1); + EXPECT_CALL(*raw_acl_connection, + Disconnect(hci::DisconnectReason::REMOTE_USER_TERMINATED_CONNECTION)) + .Times(1); std::this_thread::sleep_for(kTestIdleDisconnectTimeoutShort * 1.2); - connection_management_handler->Post(common::BindOnce( - &hci::acl_manager::LeConnectionManagementCallbacks::OnDisconnection, - common::Unretained(connection_management_callbacks), hci::ErrorCode::CONNECTION_TERMINATED_BY_LOCAL_HOST)); + connection_management_handler->Post( + common::BindOnce(&hci::acl_manager::LeConnectionManagementCallbacks::OnDisconnection, + common::Unretained(connection_management_callbacks), + hci::ErrorCode::CONNECTION_TERMINATED_BY_LOCAL_HOST)); SyncHandler(connection_management_handler); // Step 5: Link disconnect will trigger all callbacks @@ -381,7 +400,7 @@ TEST_F(L2capLeLinkManagerTest, not_acquiring_channels_should_disconnect_acl_afte TEST_F(L2capLeLinkManagerTest, acquiring_channels_should_not_disconnect_acl_after_timeout) { EXPECT_CALL(*mock_parameter_provider_, GetLeLinkIdleDisconnectTimeout) - .WillRepeatedly(Return(kTestIdleDisconnectTimeoutShort)); + .WillRepeatedly(Return(kTestIdleDisconnectTimeoutShort)); MockFixedChannelServiceManagerImpl mock_le_fixed_channel_service_manager; MockAclManager mock_acl_manager; hci::AddressWithType address_with_type({{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}, @@ -391,13 +410,11 @@ TEST_F(L2capLeLinkManagerTest, acquiring_channels_should_not_disconnect_acl_afte hci::acl_manager::LeConnectionCallbacks* hci_le_connection_callbacks = nullptr; os::Handler* hci_callback_handler = nullptr; EXPECT_CALL(mock_acl_manager, RegisterLeCallbacks(_, _)) - .WillOnce(DoAll(SaveArg<0>(&hci_le_connection_callbacks), SaveArg<1>(&hci_callback_handler))); - LinkManager le_link_manager( - l2cap_handler_, - &mock_acl_manager, - &mock_le_fixed_channel_service_manager, - nullptr, - mock_parameter_provider_); + .WillOnce(DoAll(SaveArg<0>(&hci_le_connection_callbacks), + SaveArg<1>(&hci_callback_handler))); + LinkManager le_link_manager(l2cap_handler_, &mock_acl_manager, + &mock_le_fixed_channel_service_manager, nullptr, + mock_parameter_provider_); EXPECT_EQ(hci_le_connection_callbacks, &le_link_manager); EXPECT_EQ(hci_callback_handler, l2cap_handler_); @@ -406,48 +423,51 @@ TEST_F(L2capLeLinkManagerTest, acquiring_channels_should_not_disconnect_acl_afte std::vector> results; results.emplace_back(kSmpBrCid, &mock_service_1); results.emplace_back(kConnectionlessCid, &mock_service_2); - EXPECT_CALL(mock_le_fixed_channel_service_manager, GetRegisteredServices()).WillRepeatedly(Return(results)); + EXPECT_CALL(mock_le_fixed_channel_service_manager, GetRegisteredServices()) + .WillRepeatedly(Return(results)); // Step 2: Connect to fixed channel without ACL connection should trigger ACL connection process EXPECT_CALL(mock_acl_manager, CreateLeConnection(address_with_type, true)).Times(1); LinkManager::PendingFixedChannelConnection pending_fixed_channel_connection{ - .handler_ = user_handler_, - .on_fail_callback_ = common::BindOnce([](FixedChannelManager::ConnectionResult result) { FAIL(); })}; - le_link_manager.ConnectFixedChannelServices(address_with_type, std::move(pending_fixed_channel_connection)); - - // Step 3: ACL connection success event should trigger channel creation for all registered services + .handler_ = user_handler_, + .on_fail_callback_ = + common::BindOnce([](FixedChannelManager::ConnectionResult result) { FAIL(); })}; + le_link_manager.ConnectFixedChannelServices(address_with_type, + std::move(pending_fixed_channel_connection)); + + // Step 3: ACL connection success event should trigger channel creation for all registered + // services auto* raw_acl_connection = new MockLeAclConnection(); std::unique_ptr acl_connection(raw_acl_connection); EXPECT_CALL(*acl_connection, GetRemoteAddress()).WillRepeatedly(Return(address_with_type)); hci::acl_manager::LeConnectionManagementCallbacks* connection_management_callbacks = nullptr; os::Handler* connection_management_handler = nullptr; EXPECT_CALL(*acl_connection, RegisterCallbacks(_, _)) - .WillOnce(DoAll(SaveArg<0>(&connection_management_callbacks), SaveArg<1>(&connection_management_handler))); + .WillOnce(DoAll(SaveArg<0>(&connection_management_callbacks), + SaveArg<1>(&connection_management_handler))); std::unique_ptr channel_1, channel_2; std::promise promise_1, promise_2; auto future_1 = promise_1.get_future(); auto future_2 = promise_2.get_future(); EXPECT_CALL(mock_service_1, NotifyChannelCreation(_)) - .WillOnce([&channel_1, &promise_1](std::unique_ptr channel) { - channel_1 = std::move(channel); - promise_1.set_value(); - }); + .WillOnce([&channel_1, &promise_1](std::unique_ptr channel) { + channel_1 = std::move(channel); + promise_1.set_value(); + }); EXPECT_CALL(mock_service_2, NotifyChannelCreation(_)) - .WillOnce([&channel_2, &promise_2](std::unique_ptr channel) { - channel_2 = std::move(channel); - promise_2.set_value(); - }); - hci_callback_handler->Post(common::BindOnce(&hci::acl_manager::LeConnectionCallbacks::OnLeConnectSuccess, - common::Unretained(hci_le_connection_callbacks), address_with_type, - std::move(acl_connection))); + .WillOnce([&channel_2, &promise_2](std::unique_ptr channel) { + channel_2 = std::move(channel); + promise_2.set_value(); + }); + hci_callback_handler->Post( + common::BindOnce(&hci::acl_manager::LeConnectionCallbacks::OnLeConnectSuccess, + common::Unretained(hci_le_connection_callbacks), address_with_type, + std::move(acl_connection))); SyncHandler(hci_callback_handler); connection_management_handler->Post(common::BindOnce( - &hci::acl_manager::LeConnectionManagementCallbacks::OnReadRemoteVersionInformationComplete, - common::Unretained(connection_management_callbacks), - hci::ErrorCode::SUCCESS, - 0, - 0, - 0)); + &hci::acl_manager::LeConnectionManagementCallbacks:: + OnReadRemoteVersionInformationComplete, + common::Unretained(connection_management_callbacks), hci::ErrorCode::SUCCESS, 0, 0, 0)); auto future_1_status = future_1.wait_for(kTestIdleDisconnectTimeoutShort); EXPECT_EQ(future_1_status, std::future_status::ready); EXPECT_NE(channel_1, nullptr); @@ -456,21 +476,26 @@ TEST_F(L2capLeLinkManagerTest, acquiring_channels_should_not_disconnect_acl_afte EXPECT_NE(channel_2, nullptr); hci::ErrorCode status_1 = hci::ErrorCode::SUCCESS; channel_1->RegisterOnCloseCallback( - user_handler_, common::testing::BindLambdaForTesting([&](hci::ErrorCode status) { status_1 = status; })); + user_handler_, + common::testing::BindLambdaForTesting([&](hci::ErrorCode status) { status_1 = status; })); hci::ErrorCode status_2 = hci::ErrorCode::SUCCESS; channel_2->RegisterOnCloseCallback( - user_handler_, common::testing::BindLambdaForTesting([&](hci::ErrorCode status) { status_2 = status; })); + user_handler_, + common::testing::BindLambdaForTesting([&](hci::ErrorCode status) { status_2 = status; })); channel_1->Acquire(); // Step 4: ave channel IDLE, it won't disconnect to due acquired channel 1 - EXPECT_CALL(*raw_acl_connection, Disconnect(hci::DisconnectReason::REMOTE_USER_TERMINATED_CONNECTION)).Times(0); + EXPECT_CALL(*raw_acl_connection, + Disconnect(hci::DisconnectReason::REMOTE_USER_TERMINATED_CONNECTION)) + .Times(0); std::this_thread::sleep_for(kTestIdleDisconnectTimeoutShort * 2); // Step 5: Link disconnect will trigger all callbacks - connection_management_handler->Post(common::BindOnce( - &hci::acl_manager::LeConnectionManagementCallbacks::OnDisconnection, - common::Unretained(connection_management_callbacks), hci::ErrorCode::CONNECTION_TERMINATED_BY_LOCAL_HOST)); + connection_management_handler->Post( + common::BindOnce(&hci::acl_manager::LeConnectionManagementCallbacks::OnDisconnection, + common::Unretained(connection_management_callbacks), + hci::ErrorCode::CONNECTION_TERMINATED_BY_LOCAL_HOST)); SyncHandler(connection_management_handler); SyncHandler(user_handler_); EXPECT_EQ(hci::ErrorCode::CONNECTION_TERMINATED_BY_LOCAL_HOST, status_1); @@ -479,7 +504,7 @@ TEST_F(L2capLeLinkManagerTest, acquiring_channels_should_not_disconnect_acl_afte TEST_F(L2capLeLinkManagerTest, acquiring_and_releasing_channels_should_eventually_disconnect_acl) { EXPECT_CALL(*mock_parameter_provider_, GetLeLinkIdleDisconnectTimeout) - .WillRepeatedly(Return(kTestIdleDisconnectTimeoutShort)); + .WillRepeatedly(Return(kTestIdleDisconnectTimeoutShort)); MockFixedChannelServiceManagerImpl mock_le_fixed_channel_service_manager; MockAclManager mock_acl_manager; hci::AddressWithType address_with_type({{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}, @@ -489,13 +514,11 @@ TEST_F(L2capLeLinkManagerTest, acquiring_and_releasing_channels_should_eventuall hci::acl_manager::LeConnectionCallbacks* hci_le_connection_callbacks = nullptr; os::Handler* hci_callback_handler = nullptr; EXPECT_CALL(mock_acl_manager, RegisterLeCallbacks(_, _)) - .WillOnce(DoAll(SaveArg<0>(&hci_le_connection_callbacks), SaveArg<1>(&hci_callback_handler))); - LinkManager le_link_manager( - l2cap_handler_, - &mock_acl_manager, - &mock_le_fixed_channel_service_manager, - nullptr, - mock_parameter_provider_); + .WillOnce(DoAll(SaveArg<0>(&hci_le_connection_callbacks), + SaveArg<1>(&hci_callback_handler))); + LinkManager le_link_manager(l2cap_handler_, &mock_acl_manager, + &mock_le_fixed_channel_service_manager, nullptr, + mock_parameter_provider_); EXPECT_EQ(hci_le_connection_callbacks, &le_link_manager); EXPECT_EQ(hci_callback_handler, l2cap_handler_); @@ -504,48 +527,51 @@ TEST_F(L2capLeLinkManagerTest, acquiring_and_releasing_channels_should_eventuall std::vector> results; results.emplace_back(kSmpBrCid, &mock_service_1); results.emplace_back(kConnectionlessCid, &mock_service_2); - EXPECT_CALL(mock_le_fixed_channel_service_manager, GetRegisteredServices()).WillRepeatedly(Return(results)); + EXPECT_CALL(mock_le_fixed_channel_service_manager, GetRegisteredServices()) + .WillRepeatedly(Return(results)); // Step 2: Connect to fixed channel without ACL connection should trigger ACL connection process EXPECT_CALL(mock_acl_manager, CreateLeConnection(address_with_type, true)).Times(1); LinkManager::PendingFixedChannelConnection pending_fixed_channel_connection{ - .handler_ = user_handler_, - .on_fail_callback_ = common::BindOnce([](FixedChannelManager::ConnectionResult result) { FAIL(); })}; - le_link_manager.ConnectFixedChannelServices(address_with_type, std::move(pending_fixed_channel_connection)); - - // Step 3: ACL connection success event should trigger channel creation for all registered services + .handler_ = user_handler_, + .on_fail_callback_ = + common::BindOnce([](FixedChannelManager::ConnectionResult result) { FAIL(); })}; + le_link_manager.ConnectFixedChannelServices(address_with_type, + std::move(pending_fixed_channel_connection)); + + // Step 3: ACL connection success event should trigger channel creation for all registered + // services auto* raw_acl_connection = new MockLeAclConnection(); std::unique_ptr acl_connection(raw_acl_connection); EXPECT_CALL(*acl_connection, GetRemoteAddress()).WillRepeatedly(Return(address_with_type)); hci::acl_manager::LeConnectionManagementCallbacks* connection_management_callbacks = nullptr; os::Handler* connection_management_handler = nullptr; EXPECT_CALL(*acl_connection, RegisterCallbacks(_, _)) - .WillOnce(DoAll(SaveArg<0>(&connection_management_callbacks), SaveArg<1>(&connection_management_handler))); + .WillOnce(DoAll(SaveArg<0>(&connection_management_callbacks), + SaveArg<1>(&connection_management_handler))); std::unique_ptr channel_1, channel_2; std::promise promise_1, promise_2; auto future_1 = promise_1.get_future(); auto future_2 = promise_2.get_future(); EXPECT_CALL(mock_service_1, NotifyChannelCreation(_)) - .WillOnce([&channel_1, &promise_1](std::unique_ptr channel) { - channel_1 = std::move(channel); - promise_1.set_value(); - }); + .WillOnce([&channel_1, &promise_1](std::unique_ptr channel) { + channel_1 = std::move(channel); + promise_1.set_value(); + }); EXPECT_CALL(mock_service_2, NotifyChannelCreation(_)) - .WillOnce([&channel_2, &promise_2](std::unique_ptr channel) { - channel_2 = std::move(channel); - promise_2.set_value(); - }); - hci_callback_handler->Post(common::BindOnce(&hci::acl_manager::LeConnectionCallbacks::OnLeConnectSuccess, - common::Unretained(hci_le_connection_callbacks), address_with_type, - std::move(acl_connection))); + .WillOnce([&channel_2, &promise_2](std::unique_ptr channel) { + channel_2 = std::move(channel); + promise_2.set_value(); + }); + hci_callback_handler->Post( + common::BindOnce(&hci::acl_manager::LeConnectionCallbacks::OnLeConnectSuccess, + common::Unretained(hci_le_connection_callbacks), address_with_type, + std::move(acl_connection))); SyncHandler(hci_callback_handler); connection_management_handler->Post(common::BindOnce( - &hci::acl_manager::LeConnectionManagementCallbacks::OnReadRemoteVersionInformationComplete, - common::Unretained(connection_management_callbacks), - hci::ErrorCode::SUCCESS, - 0, - 0, - 0)); + &hci::acl_manager::LeConnectionManagementCallbacks:: + OnReadRemoteVersionInformationComplete, + common::Unretained(connection_management_callbacks), hci::ErrorCode::SUCCESS, 0, 0, 0)); auto future_1_status = future_1.wait_for(kTestIdleDisconnectTimeoutShort); EXPECT_EQ(future_1_status, std::future_status::ready); EXPECT_NE(channel_1, nullptr); @@ -554,26 +580,33 @@ TEST_F(L2capLeLinkManagerTest, acquiring_and_releasing_channels_should_eventuall EXPECT_NE(channel_2, nullptr); hci::ErrorCode status_1 = hci::ErrorCode::SUCCESS; channel_1->RegisterOnCloseCallback( - user_handler_, common::testing::BindLambdaForTesting([&](hci::ErrorCode status) { status_1 = status; })); + user_handler_, + common::testing::BindLambdaForTesting([&](hci::ErrorCode status) { status_1 = status; })); hci::ErrorCode status_2 = hci::ErrorCode::SUCCESS; channel_2->RegisterOnCloseCallback( - user_handler_, common::testing::BindLambdaForTesting([&](hci::ErrorCode status) { status_2 = status; })); + user_handler_, + common::testing::BindLambdaForTesting([&](hci::ErrorCode status) { status_2 = status; })); channel_1->Acquire(); // Step 4: ave channel IDLE, it won't disconnect to due acquired channel 1 - EXPECT_CALL(*raw_acl_connection, Disconnect(hci::DisconnectReason::REMOTE_USER_TERMINATED_CONNECTION)).Times(0); + EXPECT_CALL(*raw_acl_connection, + Disconnect(hci::DisconnectReason::REMOTE_USER_TERMINATED_CONNECTION)) + .Times(0); std::this_thread::sleep_for(kTestIdleDisconnectTimeoutShort * 2); // Step 5: ave channel IDLE long enough, they will disconnect channel_1->Release(); - EXPECT_CALL(*raw_acl_connection, Disconnect(hci::DisconnectReason::REMOTE_USER_TERMINATED_CONNECTION)).Times(1); + EXPECT_CALL(*raw_acl_connection, + Disconnect(hci::DisconnectReason::REMOTE_USER_TERMINATED_CONNECTION)) + .Times(1); std::this_thread::sleep_for(kTestIdleDisconnectTimeoutShort * 1.2); // Step 6: Link disconnect will trigger all callbacks - connection_management_handler->Post(common::BindOnce( - &hci::acl_manager::LeConnectionManagementCallbacks::OnDisconnection, - common::Unretained(connection_management_callbacks), hci::ErrorCode::CONNECTION_TERMINATED_BY_LOCAL_HOST)); + connection_management_handler->Post( + common::BindOnce(&hci::acl_manager::LeConnectionManagementCallbacks::OnDisconnection, + common::Unretained(connection_management_callbacks), + hci::ErrorCode::CONNECTION_TERMINATED_BY_LOCAL_HOST)); SyncHandler(connection_management_handler); SyncHandler(user_handler_); EXPECT_EQ(hci::ErrorCode::CONNECTION_TERMINATED_BY_LOCAL_HOST, status_1); diff --git a/system/gd/l2cap/le/internal/link_mock.h b/system/gd/l2cap/le/internal/link_mock.h index 98f74ddec6c..3caac2ac382 100644 --- a/system/gd/l2cap/le/internal/link_mock.h +++ b/system/gd/l2cap/le/internal/link_mock.h @@ -15,13 +15,13 @@ */ #pragma once +#include + #include "hci/acl_manager_mock.h" #include "hci/address_with_type.h" #include "l2cap/internal/scheduler_mock.h" #include "l2cap/le/internal/link.h" -#include - // Unit test interfaces namespace bluetooth { namespace l2cap { @@ -32,17 +32,19 @@ namespace testing { using hci::testing::MockLeAclConnection; class MockLink : public Link { - public: +public: explicit MockLink(os::Handler* handler, l2cap::internal::ParameterProvider* parameter_provider, - std::unique_ptr mock_acl_connection, LinkManager* link_manager) - : Link(handler, std::move(mock_acl_connection), parameter_provider, nullptr, nullptr, link_manager) {} + std::unique_ptr mock_acl_connection, + LinkManager* link_manager) + : Link(handler, std::move(mock_acl_connection), parameter_provider, nullptr, nullptr, + link_manager) {} MOCK_METHOD(hci::AddressWithType, GetDevice, (), (const, override)); MOCK_METHOD(hci::Role, GetRole, (), (override)); MOCK_METHOD(void, OnAclDisconnected, (hci::ErrorCode status), (override)); MOCK_METHOD(void, Disconnect, (), (override)); - MOCK_METHOD(std::shared_ptr, AllocateFixedChannel, (Cid cid, SecurityPolicy security_policy), - (override)); + MOCK_METHOD(std::shared_ptr, AllocateFixedChannel, + (Cid cid, SecurityPolicy security_policy), (override)); MOCK_METHOD(bool, IsFixedChannelAllocated, (Cid cid), (override)); MOCK_METHOD(void, RefreshRefCount, (), (override)); }; diff --git a/system/gd/l2cap/le/internal/signalling_manager.cc b/system/gd/l2cap/le/internal/signalling_manager.cc index dae7d381ad1..e1b480935d1 100644 --- a/system/gd/l2cap/le/internal/signalling_manager.cc +++ b/system/gd/l2cap/le/internal/signalling_manager.cc @@ -36,20 +36,26 @@ namespace internal { static constexpr auto kTimeout = std::chrono::seconds(3); -LeSignallingManager::LeSignallingManager(os::Handler* handler, Link* link, - l2cap::internal::DataPipelineManager* data_pipeline_manager, - DynamicChannelServiceManagerImpl* dynamic_service_manager, - l2cap::internal::DynamicChannelAllocator* channel_allocator) - : handler_(handler), link_(link), data_pipeline_manager_(data_pipeline_manager), - dynamic_service_manager_(dynamic_service_manager), channel_allocator_(channel_allocator), alarm_(handler) { +LeSignallingManager::LeSignallingManager( + os::Handler* handler, Link* link, + l2cap::internal::DataPipelineManager* data_pipeline_manager, + DynamicChannelServiceManagerImpl* dynamic_service_manager, + l2cap::internal::DynamicChannelAllocator* channel_allocator) + : handler_(handler), + link_(link), + data_pipeline_manager_(data_pipeline_manager), + dynamic_service_manager_(dynamic_service_manager), + channel_allocator_(channel_allocator), + alarm_(handler) { log::assert_that(handler_ != nullptr, "assert failed: handler_ != nullptr"); log::assert_that(link_ != nullptr, "assert failed: link_ != nullptr"); - signalling_channel_ = - link_->AllocateFixedChannel(kLeSignallingCid, SecurityPolicy::NO_SECURITY_WHATSOEVER_PLAINTEXT_TRANSPORT_OK); + signalling_channel_ = link_->AllocateFixedChannel( + kLeSignallingCid, SecurityPolicy::NO_SECURITY_WHATSOEVER_PLAINTEXT_TRANSPORT_OK); signalling_channel_->GetQueueUpEnd()->RegisterDequeue( - handler_, common::Bind(&LeSignallingManager::on_incoming_packet, common::Unretained(this))); - enqueue_buffer_ = - std::make_unique>(signalling_channel_->GetQueueUpEnd()); + handler_, + common::Bind(&LeSignallingManager::on_incoming_packet, common::Unretained(this))); + enqueue_buffer_ = std::make_unique>( + signalling_channel_->GetQueueUpEnd()); } LeSignallingManager::~LeSignallingManager() { @@ -60,19 +66,20 @@ LeSignallingManager::~LeSignallingManager() { void LeSignallingManager::SendConnectionRequest(Psm psm, Cid local_cid, Mtu mtu) { dynamic_service_manager_->GetSecurityEnforcementInterface()->Enforce( - link_->GetDevice(), - dynamic_service_manager_->GetService(psm)->GetSecurityPolicy(), - handler_->BindOnceOn(this, &LeSignallingManager::on_security_result_for_outgoing, psm, local_cid, mtu)); + link_->GetDevice(), dynamic_service_manager_->GetService(psm)->GetSecurityPolicy(), + handler_->BindOnceOn(this, &LeSignallingManager::on_security_result_for_outgoing, psm, + local_cid, mtu)); } -void LeSignallingManager::on_security_result_for_outgoing(Psm psm, Cid local_cid, Mtu mtu, bool result) { +void LeSignallingManager::on_security_result_for_outgoing(Psm psm, Cid local_cid, Mtu mtu, + bool result) { if (!result) { log::warn("Security requirement can't be satisfied. Dropping connection request"); return; } PendingCommand pending_command = PendingCommand::CreditBasedConnectionRequest( - next_signal_id_, psm, local_cid, mtu, link_->GetMps(), link_->GetInitialCredit()); + next_signal_id_, psm, local_cid, mtu, link_->GetMps(), link_->GetInitialCredit()); next_signal_id_++; pending_commands_.push(pending_command); if (pending_commands_.size() == 1) { @@ -81,7 +88,8 @@ void LeSignallingManager::on_security_result_for_outgoing(Psm psm, Cid local_cid } void LeSignallingManager::SendDisconnectRequest(Cid scid, Cid dcid) { - PendingCommand pending_command = PendingCommand::DisconnectionRequest(next_signal_id_, scid, dcid); + PendingCommand pending_command = + PendingCommand::DisconnectionRequest(next_signal_id_, scid, dcid); next_signal_id_++; pending_commands_.push(pending_command); if (pending_commands_.size() == 1) { @@ -89,10 +97,12 @@ void LeSignallingManager::SendDisconnectRequest(Cid scid, Cid dcid) { } } -void LeSignallingManager::SendConnectionParameterUpdateRequest( - uint16_t interval_min, uint16_t interval_max, uint16_t peripheral_latency, uint16_t timeout_multiplier) { +void LeSignallingManager::SendConnectionParameterUpdateRequest(uint16_t interval_min, + uint16_t interval_max, + uint16_t peripheral_latency, + uint16_t timeout_multiplier) { PendingCommand pending_command = PendingCommand::ConnectionParameterUpdate( - next_signal_id_, interval_min, interval_max, peripheral_latency, timeout_multiplier); + next_signal_id_, interval_min, interval_max, peripheral_latency, timeout_multiplier); next_signal_id_++; pending_commands_.push(pending_command); if (pending_commands_.size() == 1) { @@ -100,8 +110,8 @@ void LeSignallingManager::SendConnectionParameterUpdateRequest( } } -void LeSignallingManager::SendConnectionParameterUpdateResponse(SignalId signal_id, - ConnectionParameterUpdateResponseResult result) { +void LeSignallingManager::SendConnectionParameterUpdateResponse( + SignalId signal_id, ConnectionParameterUpdateResponseResult result) { auto builder = ConnectionParameterUpdateResponseBuilder::Create(signal_id.Value(), result); enqueue_buffer_->Enqueue(std::move(builder), handler_); } @@ -112,15 +122,14 @@ void LeSignallingManager::SendCredit(Cid local_cid, uint16_t credits) { enqueue_buffer_->Enqueue(std::move(builder), handler_); } -void LeSignallingManager::SendEnhancedConnectionRequest( - Psm /* psm */, std::vector /* local_cid */, Mtu /* mtu */) {} +void LeSignallingManager::SendEnhancedConnectionRequest(Psm /* psm */, + std::vector /* local_cid */, + Mtu /* mtu */) {} -void LeSignallingManager::SendEnhancedReconfigureRequest( - std::vector /* local_cid */, Mtu /* mtu */) {} +void LeSignallingManager::SendEnhancedReconfigureRequest(std::vector /* local_cid */, + Mtu /* mtu */) {} -void LeSignallingManager::CancelAlarm() { - alarm_.Cancel(); -} +void LeSignallingManager::CancelAlarm() { alarm_.Cancel(); } void LeSignallingManager::OnCommandReject(LeCommandRejectView command_reject_view) { auto signal_id = command_reject_view.GetIdentifier(); @@ -130,20 +139,20 @@ void LeSignallingManager::OnCommandReject(LeCommandRejectView command_reject_vie } alarm_.Cancel(); if (command_just_sent_.command_code_ == LeCommandCode::LE_CREDIT_BASED_CONNECTION_REQUEST) { - link_->OnOutgoingConnectionRequestFail(command_just_sent_.source_cid_, - LeCreditBasedConnectionResponseResult::NO_RESOURCES_AVAILABLE); + link_->OnOutgoingConnectionRequestFail( + command_just_sent_.source_cid_, + LeCreditBasedConnectionResponseResult::NO_RESOURCES_AVAILABLE); } handle_send_next_command(); log::warn("Command rejected"); } -void LeSignallingManager::OnConnectionParameterUpdateRequest( - SignalId signal_id, - uint16_t interval_min, - uint16_t interval_max, - uint16_t peripheral_latency, - uint16_t timeout_multiplier) { +void LeSignallingManager::OnConnectionParameterUpdateRequest(SignalId signal_id, + uint16_t interval_min, + uint16_t interval_max, + uint16_t peripheral_latency, + uint16_t timeout_multiplier) { if (link_->GetRole() == hci::Role::PERIPHERAL) { log::warn("Received request from LL central"); auto builder = LeCommandRejectNotUnderstoodBuilder::Create(signal_id.Value()); @@ -151,19 +160,20 @@ void LeSignallingManager::OnConnectionParameterUpdateRequest( return; } - if (!link_->CheckConnectionParameters(interval_min, interval_max, peripheral_latency, timeout_multiplier)) { + if (!link_->CheckConnectionParameters(interval_min, interval_max, peripheral_latency, + timeout_multiplier)) { log::warn("Received invalid connection parameter update request from LL central"); - auto builder = ConnectionParameterUpdateResponseBuilder::Create(signal_id.Value(), - ConnectionParameterUpdateResponseResult::REJECTED); + auto builder = ConnectionParameterUpdateResponseBuilder::Create( + signal_id.Value(), ConnectionParameterUpdateResponseResult::REJECTED); enqueue_buffer_->Enqueue(std::move(builder), handler_); return; } - link_->UpdateConnectionParameterFromRemote( - signal_id, interval_min, interval_max, peripheral_latency, timeout_multiplier); + link_->UpdateConnectionParameterFromRemote(signal_id, interval_min, interval_max, + peripheral_latency, timeout_multiplier); } -void LeSignallingManager::OnConnectionParameterUpdateResponse(SignalId signal_id, - ConnectionParameterUpdateResponseResult result) { +void LeSignallingManager::OnConnectionParameterUpdateResponse( + SignalId signal_id, ConnectionParameterUpdateResponseResult result) { if (signal_id != command_just_sent_.signal_id_) { log::warn("Unexpected response: no pending request"); return; @@ -179,8 +189,8 @@ void LeSignallingManager::OnConnectionParameterUpdateResponse(SignalId signal_id } } -void LeSignallingManager::OnConnectionRequest(SignalId signal_id, Psm psm, Cid remote_cid, Mtu mtu, uint16_t mps, - uint16_t initial_credits) { +void LeSignallingManager::OnConnectionRequest(SignalId signal_id, Psm psm, Cid remote_cid, Mtu mtu, + uint16_t mps, uint16_t initial_credits) { if (remote_cid == kInvalidCid) { log::warn("Invalid remote cid received from remote psm:{} remote_cid:{}", psm, remote_cid); send_connection_response(signal_id, kInvalidCid, 0, 0, 0, @@ -203,19 +213,20 @@ void LeSignallingManager::OnConnectionRequest(SignalId signal_id, Psm psm, Cid r } PendingConnection pending{ - .remote_cid = remote_cid, - .mtu = mtu, - .max_pdu_size = mps, - .initial_credits = initial_credits, - .incoming_signal_id = signal_id, + .remote_cid = remote_cid, + .mtu = mtu, + .max_pdu_size = mps, + .initial_credits = initial_credits, + .incoming_signal_id = signal_id, }; dynamic_service_manager_->GetSecurityEnforcementInterface()->Enforce( - link_->GetDevice(), - dynamic_service_manager_->GetService(psm)->GetSecurityPolicy(), - handler_->BindOnceOn(this, &LeSignallingManager::on_security_result_for_incoming, psm, pending)); + link_->GetDevice(), dynamic_service_manager_->GetService(psm)->GetSecurityPolicy(), + handler_->BindOnceOn(this, &LeSignallingManager::on_security_result_for_incoming, psm, + pending)); } -void LeSignallingManager::on_security_result_for_incoming(Psm psm, PendingConnection request, bool result) { +void LeSignallingManager::on_security_result_for_incoming(Psm psm, PendingConnection request, + bool result) { auto signal_id = request.incoming_signal_id; auto* service = dynamic_service_manager_->GetService(psm); if (!result) { @@ -225,17 +236,20 @@ void LeSignallingManager::on_security_result_for_incoming(Psm psm, PendingConnec log::error("If no security requirement, we should never fail"); break; case SecurityPolicy::ENCRYPTED_TRANSPORT: - send_connection_response(signal_id, kInvalidCid, 0, 0, 0, - LeCreditBasedConnectionResponseResult::INSUFFICIENT_AUTHENTICATION); + send_connection_response( + signal_id, kInvalidCid, 0, 0, 0, + LeCreditBasedConnectionResponseResult::INSUFFICIENT_AUTHENTICATION); return; case SecurityPolicy::AUTHENTICATED_ENCRYPTED_TRANSPORT: case SecurityPolicy::BEST: - send_connection_response(signal_id, kInvalidCid, 0, 0, 0, - LeCreditBasedConnectionResponseResult::INSUFFICIENT_AUTHENTICATION); + send_connection_response( + signal_id, kInvalidCid, 0, 0, 0, + LeCreditBasedConnectionResponseResult::INSUFFICIENT_AUTHENTICATION); return; case SecurityPolicy::_NOT_FOR_YOU__AUTHENTICATED_PAIRING_WITH_128_BIT_KEY: - send_connection_response(signal_id, kInvalidCid, 0, 0, 0, - LeCreditBasedConnectionResponseResult::INSUFFICIENT_ENCRYPTION_KEY_SIZE); + send_connection_response( + signal_id, kInvalidCid, 0, 0, 0, + LeCreditBasedConnectionResponseResult::INSUFFICIENT_ENCRYPTION_KEY_SIZE); return; case SecurityPolicy::_NOT_FOR_YOU__AUTHORIZATION: send_connection_response(signal_id, kInvalidCid, 0, 0, 0, @@ -256,10 +270,11 @@ void LeSignallingManager::on_security_result_for_incoming(Psm psm, PendingConnec return; } - send_connection_response(signal_id, new_channel->GetCid(), local_mtu, local_mps, link_->GetInitialCredit(), + send_connection_response(signal_id, new_channel->GetCid(), local_mtu, local_mps, + link_->GetInitialCredit(), LeCreditBasedConnectionResponseResult::SUCCESS); auto* data_controller = reinterpret_cast( - data_pipeline_manager_->GetDataController(new_channel->GetCid())); + data_pipeline_manager_->GetDataController(new_channel->GetCid())); auto actual_mtu = std::min(request.mtu, local_mtu); data_controller->SetMtu(actual_mtu); data_controller->SetMps(std::min(request.max_pdu_size, local_mps)); @@ -268,8 +283,9 @@ void LeSignallingManager::on_security_result_for_incoming(Psm psm, PendingConnec dynamic_service_manager_->GetService(psm)->NotifyChannelCreation(std::move(user_channel)); } -void LeSignallingManager::OnConnectionResponse(SignalId signal_id, Cid remote_cid, Mtu mtu, uint16_t mps, - uint16_t initial_credits, LeCreditBasedConnectionResponseResult result) { +void LeSignallingManager::OnConnectionResponse(SignalId signal_id, Cid remote_cid, Mtu mtu, + uint16_t mps, uint16_t initial_credits, + LeCreditBasedConnectionResponseResult result) { if (signal_id != command_just_sent_.signal_id_) { log::warn("Unexpected response: no pending request"); return; @@ -286,23 +302,24 @@ void LeSignallingManager::OnConnectionResponse(SignalId signal_id, Cid remote_ci handle_send_next_command(); return; } - auto new_channel = - link_->AllocateReservedDynamicChannel(command_just_sent_.source_cid_, command_just_sent_.psm_, remote_cid); + auto new_channel = link_->AllocateReservedDynamicChannel(command_just_sent_.source_cid_, + command_just_sent_.psm_, remote_cid); if (new_channel == nullptr) { log::warn("Can't allocate dynamic channel"); - link_->OnOutgoingConnectionRequestFail(command_just_sent_.source_cid_, - LeCreditBasedConnectionResponseResult::NO_RESOURCES_AVAILABLE); + link_->OnOutgoingConnectionRequestFail( + command_just_sent_.source_cid_, + LeCreditBasedConnectionResponseResult::NO_RESOURCES_AVAILABLE); handle_send_next_command(); return; } auto* data_controller = reinterpret_cast( - data_pipeline_manager_->GetDataController(new_channel->GetCid())); + data_pipeline_manager_->GetDataController(new_channel->GetCid())); auto actual_mtu = std::min(mtu, command_just_sent_.mtu_); data_controller->SetMtu(actual_mtu); data_controller->SetMps(std::min(mps, command_just_sent_.mps_)); data_controller->OnCredit(initial_credits); std::unique_ptr user_channel = - std::make_unique(new_channel, handler_, link_, actual_mtu); + std::make_unique(new_channel, handler_, link_, actual_mtu); link_->NotifyChannelCreation(new_channel->GetCid(), std::move(user_channel)); } @@ -330,11 +347,8 @@ void LeSignallingManager::OnDisconnectionResponse(SignalId signal_id, Cid remote } if (command_just_sent_.source_cid_ != cid || command_just_sent_.destination_cid_ != remote_cid) { log::warn( - "Unexpected response: cid doesn't match. Expected scid {} dcid {}, got scid {} dcid {}", - command_just_sent_.source_cid_, - command_just_sent_.destination_cid_, - cid, - remote_cid); + "Unexpected response: cid doesn't match. Expected scid {} dcid {}, got scid {} dcid {}", + command_just_sent_.source_cid_, command_just_sent_.destination_cid_, cid, remote_cid); handle_send_next_command(); return; } @@ -359,7 +373,7 @@ void LeSignallingManager::OnCredit(Cid remote_cid, uint16_t credits) { return; } auto* data_controller = reinterpret_cast( - data_pipeline_manager_->GetDataController(channel->GetCid())); + data_pipeline_manager_->GetDataController(channel->GetCid())); data_controller->OnCredit(credits); } @@ -383,21 +397,20 @@ void LeSignallingManager::on_incoming_packet() { case LeCommandCode::CONNECTION_PARAMETER_UPDATE_REQUEST: { ConnectionParameterUpdateRequestView parameter_update_req_view = - ConnectionParameterUpdateRequestView::Create(control_packet_view); + ConnectionParameterUpdateRequestView::Create(control_packet_view); if (!parameter_update_req_view.IsValid()) { return; } - OnConnectionParameterUpdateRequest( - parameter_update_req_view.GetIdentifier(), - parameter_update_req_view.GetIntervalMin(), - parameter_update_req_view.GetIntervalMax(), - parameter_update_req_view.GetPeripheralLatency(), - parameter_update_req_view.GetTimeoutMultiplier()); + OnConnectionParameterUpdateRequest(parameter_update_req_view.GetIdentifier(), + parameter_update_req_view.GetIntervalMin(), + parameter_update_req_view.GetIntervalMax(), + parameter_update_req_view.GetPeripheralLatency(), + parameter_update_req_view.GetTimeoutMultiplier()); return; } case LeCommandCode::CONNECTION_PARAMETER_UPDATE_RESPONSE: { ConnectionParameterUpdateResponseView parameter_update_rsp_view = - ConnectionParameterUpdateResponseView::Create(control_packet_view); + ConnectionParameterUpdateResponseView::Create(control_packet_view); if (!parameter_update_rsp_view.IsValid()) { return; } @@ -407,24 +420,27 @@ void LeSignallingManager::on_incoming_packet() { } case LeCommandCode::LE_CREDIT_BASED_CONNECTION_REQUEST: { LeCreditBasedConnectionRequestView connection_request_view = - LeCreditBasedConnectionRequestView::Create(control_packet_view); + LeCreditBasedConnectionRequestView::Create(control_packet_view); if (!connection_request_view.IsValid()) { return; } - OnConnectionRequest(connection_request_view.GetIdentifier(), connection_request_view.GetLePsm(), - connection_request_view.GetSourceCid(), connection_request_view.GetMtu(), - connection_request_view.GetMps(), connection_request_view.GetInitialCredits()); + OnConnectionRequest( + connection_request_view.GetIdentifier(), connection_request_view.GetLePsm(), + connection_request_view.GetSourceCid(), connection_request_view.GetMtu(), + connection_request_view.GetMps(), connection_request_view.GetInitialCredits()); return; } case LeCommandCode::LE_CREDIT_BASED_CONNECTION_RESPONSE: { LeCreditBasedConnectionResponseView connection_response_view = - LeCreditBasedConnectionResponseView::Create(control_packet_view); + LeCreditBasedConnectionResponseView::Create(control_packet_view); if (!connection_response_view.IsValid()) { return; } - OnConnectionResponse(connection_response_view.GetIdentifier(), connection_response_view.GetDestinationCid(), + OnConnectionResponse(connection_response_view.GetIdentifier(), + connection_response_view.GetDestinationCid(), connection_response_view.GetMtu(), connection_response_view.GetMps(), - connection_response_view.GetInitialCredits(), connection_response_view.GetResult()); + connection_response_view.GetInitialCredits(), + connection_response_view.GetResult()); return; } case LeCommandCode::LE_FLOW_CONTROL_CREDIT: { @@ -436,17 +452,19 @@ void LeSignallingManager::on_incoming_packet() { return; } case LeCommandCode::DISCONNECTION_REQUEST: { - LeDisconnectionRequestView disconnection_request_view = LeDisconnectionRequestView::Create(control_packet_view); + LeDisconnectionRequestView disconnection_request_view = + LeDisconnectionRequestView::Create(control_packet_view); if (!disconnection_request_view.IsValid()) { return; } - OnDisconnectionRequest(disconnection_request_view.GetIdentifier(), disconnection_request_view.GetDestinationCid(), + OnDisconnectionRequest(disconnection_request_view.GetIdentifier(), + disconnection_request_view.GetDestinationCid(), disconnection_request_view.GetSourceCid()); return; } case LeCommandCode::DISCONNECTION_RESPONSE: { LeDisconnectionResponseView disconnection_response_view = - LeDisconnectionResponseView::Create(control_packet_view); + LeDisconnectionResponseView::Create(control_packet_view); if (!disconnection_response_view.IsValid()) { return; } @@ -457,7 +475,7 @@ void LeSignallingManager::on_incoming_packet() { } case LeCommandCode::CREDIT_BASED_CONNECTION_REQUEST: { LeEnhancedCreditBasedConnectionRequestView request_view = - LeEnhancedCreditBasedConnectionRequestView::Create(control_packet_view); + LeEnhancedCreditBasedConnectionRequestView::Create(control_packet_view); if (!request_view.IsValid()) { return; } @@ -465,7 +483,7 @@ void LeSignallingManager::on_incoming_packet() { } case LeCommandCode::CREDIT_BASED_CONNECTION_RESPONSE: { LeEnhancedCreditBasedConnectionResponseView response_view = - LeEnhancedCreditBasedConnectionResponseView::Create(control_packet_view); + LeEnhancedCreditBasedConnectionResponseView::Create(control_packet_view); if (!response_view.IsValid()) { return; } @@ -473,7 +491,7 @@ void LeSignallingManager::on_incoming_packet() { } case LeCommandCode::CREDIT_BASED_RECONFIGURE_REQUEST: { LeEnhancedCreditBasedReconfigureRequestView request_view = - LeEnhancedCreditBasedReconfigureRequestView::Create(control_packet_view); + LeEnhancedCreditBasedReconfigureRequestView::Create(control_packet_view); if (!request_view.IsValid()) { return; } @@ -481,7 +499,7 @@ void LeSignallingManager::on_incoming_packet() { } case LeCommandCode::CREDIT_BASED_RECONFIGURE_RESPONSE: { LeEnhancedCreditBasedReconfigureResponseView response_view = - LeEnhancedCreditBasedReconfigureResponseView::Create(control_packet_view); + LeEnhancedCreditBasedReconfigureResponseView::Create(control_packet_view); if (!response_view.IsValid()) { return; } @@ -489,17 +507,18 @@ void LeSignallingManager::on_incoming_packet() { } default: log::warn("Unhandled event 0x{:x}", static_cast(code)); - auto builder = LeCommandRejectNotUnderstoodBuilder::Create(control_packet_view.GetIdentifier()); + auto builder = + LeCommandRejectNotUnderstoodBuilder::Create(control_packet_view.GetIdentifier()); enqueue_buffer_->Enqueue(std::move(builder), handler_); return; } } -void LeSignallingManager::send_connection_response(SignalId signal_id, Cid local_cid, Mtu mtu, uint16_t mps, - uint16_t initial_credit, +void LeSignallingManager::send_connection_response(SignalId signal_id, Cid local_cid, Mtu mtu, + uint16_t mps, uint16_t initial_credit, LeCreditBasedConnectionResponseResult result) { - auto builder = - LeCreditBasedConnectionResponseBuilder::Create(signal_id.Value(), local_cid, mtu, mps, initial_credit, result); + auto builder = LeCreditBasedConnectionResponseBuilder::Create(signal_id.Value(), local_cid, mtu, + mps, initial_credit, result); enqueue_buffer_->Enqueue(std::move(builder), handler_); } @@ -511,8 +530,9 @@ void LeSignallingManager::on_command_timeout() { } switch (command_just_sent_.command_code_) { case LeCommandCode::CONNECTION_PARAMETER_UPDATE_REQUEST: { - link_->OnOutgoingConnectionRequestFail(command_just_sent_.source_cid_, - LeCreditBasedConnectionResponseResult::NO_RESOURCES_AVAILABLE); + link_->OnOutgoingConnectionRequestFail( + command_just_sent_.source_cid_, + LeCreditBasedConnectionResponseResult::NO_RESOURCES_AVAILABLE); break; } default: @@ -532,33 +552,39 @@ void LeSignallingManager::handle_send_next_command() { switch (command_just_sent_.command_code_) { case LeCommandCode::LE_CREDIT_BASED_CONNECTION_REQUEST: { auto builder = LeCreditBasedConnectionRequestBuilder::Create( - command_just_sent_.signal_id_.Value(), command_just_sent_.psm_, command_just_sent_.source_cid_, - command_just_sent_.mtu_, command_just_sent_.mps_, command_just_sent_.credits_); + command_just_sent_.signal_id_.Value(), command_just_sent_.psm_, + command_just_sent_.source_cid_, command_just_sent_.mtu_, command_just_sent_.mps_, + command_just_sent_.credits_); enqueue_buffer_->Enqueue(std::move(builder), handler_); - alarm_.Schedule(common::BindOnce(&LeSignallingManager::on_command_timeout, common::Unretained(this)), kTimeout); + alarm_.Schedule( + common::BindOnce(&LeSignallingManager::on_command_timeout, common::Unretained(this)), + kTimeout); break; } case LeCommandCode::DISCONNECTION_REQUEST: { - auto builder = LeDisconnectionRequestBuilder::Create( - command_just_sent_.signal_id_.Value(), command_just_sent_.destination_cid_, command_just_sent_.source_cid_); + auto builder = LeDisconnectionRequestBuilder::Create(command_just_sent_.signal_id_.Value(), + command_just_sent_.destination_cid_, + command_just_sent_.source_cid_); enqueue_buffer_->Enqueue(std::move(builder), handler_); - alarm_.Schedule(common::BindOnce(&LeSignallingManager::on_command_timeout, common::Unretained(this)), kTimeout); + alarm_.Schedule( + common::BindOnce(&LeSignallingManager::on_command_timeout, common::Unretained(this)), + kTimeout); break; } case LeCommandCode::CONNECTION_PARAMETER_UPDATE_REQUEST: { auto builder = ConnectionParameterUpdateRequestBuilder::Create( - command_just_sent_.signal_id_.Value(), - command_just_sent_.interval_min_, - command_just_sent_.interval_max_, - command_just_sent_.peripheral_latency_, - command_just_sent_.timeout_multiplier_); + command_just_sent_.signal_id_.Value(), command_just_sent_.interval_min_, + command_just_sent_.interval_max_, command_just_sent_.peripheral_latency_, + command_just_sent_.timeout_multiplier_); enqueue_buffer_->Enqueue(std::move(builder), handler_); - alarm_.Schedule(common::BindOnce(&LeSignallingManager::on_command_timeout, common::Unretained(this)), kTimeout); + alarm_.Schedule( + common::BindOnce(&LeSignallingManager::on_command_timeout, common::Unretained(this)), + kTimeout); break; } default: { - log::warn( - "Unsupported command code 0x{:x}", static_cast(command_just_sent_.command_code_)); + log::warn("Unsupported command code 0x{:x}", + static_cast(command_just_sent_.command_code_)); } } } diff --git a/system/gd/l2cap/le/internal/signalling_manager.h b/system/gd/l2cap/le/internal/signalling_manager.h index c4a3e32e56e..0fa6a992f46 100644 --- a/system/gd/l2cap/le/internal/signalling_manager.h +++ b/system/gd/l2cap/le/internal/signalling_manager.h @@ -54,8 +54,8 @@ struct PendingCommand { uint16_t peripheral_latency_; uint16_t timeout_multiplier_; - static PendingCommand CreditBasedConnectionRequest(SignalId signal_id, Psm psm, Cid scid, Mtu mtu, uint16_t mps, - uint16_t initial_credits) { + static PendingCommand CreditBasedConnectionRequest(SignalId signal_id, Psm psm, Cid scid, Mtu mtu, + uint16_t mps, uint16_t initial_credits) { PendingCommand pending_command; pending_command.signal_id_ = signal_id; pending_command.command_code_ = LeCommandCode::LE_CREDIT_BASED_CONNECTION_REQUEST; @@ -76,12 +76,10 @@ struct PendingCommand { return pending_command; } - static PendingCommand ConnectionParameterUpdate( - SignalId signal_id, - uint16_t interval_min, - uint16_t interval_max, - uint16_t peripheral_latency, - uint16_t timeout_multiplier) { + static PendingCommand ConnectionParameterUpdate(SignalId signal_id, uint16_t interval_min, + uint16_t interval_max, + uint16_t peripheral_latency, + uint16_t timeout_multiplier) { PendingCommand pending_command; pending_command.signal_id_ = signal_id; pending_command.command_code_ = LeCommandCode::CONNECTION_PARAMETER_UPDATE_REQUEST; @@ -96,8 +94,9 @@ struct PendingCommand { class Link; class LeSignallingManager { - public: - LeSignallingManager(os::Handler* handler, Link* link, l2cap::internal::DataPipelineManager* data_pipeline_manager, +public: + LeSignallingManager(os::Handler* handler, Link* link, + l2cap::internal::DataPipelineManager* data_pipeline_manager, DynamicChannelServiceManagerImpl* dynamic_service_manager, l2cap::internal::DynamicChannelAllocator* channel_allocator); @@ -108,10 +107,12 @@ class LeSignallingManager { void SendDisconnectRequest(Cid local_cid, Cid remote_cid); // Note: Since Core 4.1, LL peripheral can send this through HCI command. - void SendConnectionParameterUpdateRequest( - uint16_t interval_min, uint16_t interval_max, uint16_t peripheral_latency, uint16_t timeout_multiplier); + void SendConnectionParameterUpdateRequest(uint16_t interval_min, uint16_t interval_max, + uint16_t peripheral_latency, + uint16_t timeout_multiplier); - void SendConnectionParameterUpdateResponse(SignalId signal_id, ConnectionParameterUpdateResponseResult result); + void SendConnectionParameterUpdateResponse(SignalId signal_id, + ConnectionParameterUpdateResponseResult result); void SendCredit(Cid local_cid, uint16_t credits); @@ -123,19 +124,17 @@ class LeSignallingManager { void OnCommandReject(LeCommandRejectView command_reject_view); - void OnConnectionParameterUpdateRequest( - SignalId signal_id, - uint16_t interval_min, - uint16_t interval_max, - uint16_t peripheral_latency, - uint16_t timeout_multiplier); - void OnConnectionParameterUpdateResponse(SignalId signal_id, ConnectionParameterUpdateResponseResult result); + void OnConnectionParameterUpdateRequest(SignalId signal_id, uint16_t interval_min, + uint16_t interval_max, uint16_t peripheral_latency, + uint16_t timeout_multiplier); + void OnConnectionParameterUpdateResponse(SignalId signal_id, + ConnectionParameterUpdateResponseResult result); void OnConnectionRequest(SignalId signal_id, Psm psm, Cid remote_cid, Mtu mtu, uint16_t mps, uint16_t initial_credits); - void OnConnectionResponse(SignalId signal_id, Cid remote_cid, Mtu mtu, uint16_t mps, uint16_t initial_credits, - LeCreditBasedConnectionResponseResult result); + void OnConnectionResponse(SignalId signal_id, Cid remote_cid, Mtu mtu, uint16_t mps, + uint16_t initial_credits, LeCreditBasedConnectionResponseResult result); void OnDisconnectionRequest(SignalId signal_id, Cid cid, Cid remote_cid); @@ -143,7 +142,7 @@ class LeSignallingManager { void OnCredit(Cid remote_cid, uint16_t credits); - private: +private: struct PendingConnection { Cid remote_cid; Mtu mtu; @@ -153,7 +152,8 @@ class LeSignallingManager { }; void on_incoming_packet(); - void send_connection_response(SignalId signal_id, Cid local_cid, Mtu mtu, uint16_t mps, uint16_t initial_credit, + void send_connection_response(SignalId signal_id, Cid local_cid, Mtu mtu, uint16_t mps, + uint16_t initial_credit, LeCreditBasedConnectionResponseResult result); void on_command_timeout(); void handle_send_next_command(); diff --git a/system/gd/l2cap/le/l2cap_le_module.cc b/system/gd/l2cap/le/l2cap_le_module.cc index f4f1daee56b..a6f5462b08b 100644 --- a/system/gd/l2cap/le/l2cap_le_module.cc +++ b/system/gd/l2cap/le/l2cap_le_module.cc @@ -14,6 +14,8 @@ * limitations under the License. */ +#include "l2cap/le/l2cap_le_module.h" + #include #include "hci/acl_manager.h" @@ -25,8 +27,6 @@ #include "module.h" #include "os/handler.h" -#include "l2cap/le/l2cap_le_module.h" - namespace bluetooth { namespace l2cap { namespace le { @@ -38,11 +38,9 @@ const ModuleFactory L2capLeModule::Factory = ModuleFactory([]() { return new L2c * NO_SECURITY_WHATSOEVER_PLAINTEXT_TRANSPORT_OK. */ class SecurityEnforcementRejectAllImpl : public SecurityEnforcementInterface { - public: - void Enforce( - hci::AddressWithType /* remote */, - SecurityPolicy policy, - ResultCallback result_callback) override { +public: + void Enforce(hci::AddressWithType /* remote */, SecurityPolicy policy, + ResultCallback result_callback) override { if (policy == SecurityPolicy::NO_SECURITY_WHATSOEVER_PLAINTEXT_TRANSPORT_OK) { result_callback(true); } else { @@ -55,54 +53,52 @@ static SecurityEnforcementRejectAllImpl default_security_module_impl_; struct L2capLeModule::impl { impl(os::Handler* l2cap_handler, hci::AclManager* acl_manager) : l2cap_handler_(l2cap_handler), acl_manager_(acl_manager) { - dynamic_channel_service_manager_impl_.SetSecurityEnforcementInterface(&default_security_module_impl_); + dynamic_channel_service_manager_impl_.SetSecurityEnforcementInterface( + &default_security_module_impl_); } os::Handler* l2cap_handler_; hci::AclManager* acl_manager_; l2cap::internal::ParameterProvider parameter_provider_; internal::FixedChannelServiceManagerImpl fixed_channel_service_manager_impl_{l2cap_handler_}; internal::DynamicChannelServiceManagerImpl dynamic_channel_service_manager_impl_{l2cap_handler_}; - internal::LinkManager link_manager_{l2cap_handler_, - acl_manager_, + internal::LinkManager link_manager_{l2cap_handler_, acl_manager_, &fixed_channel_service_manager_impl_, - &dynamic_channel_service_manager_impl_, - ¶meter_provider_}; + &dynamic_channel_service_manager_impl_, ¶meter_provider_}; }; L2capLeModule::L2capLeModule() {} L2capLeModule::~L2capLeModule() {} -void L2capLeModule::ListDependencies(ModuleList* list) const { - list->add(); -} +void L2capLeModule::ListDependencies(ModuleList* list) const { list->add(); } void L2capLeModule::Start() { pimpl_ = std::make_unique(GetHandler(), GetDependency()); } -void L2capLeModule::Stop() { - pimpl_.reset(); -} +void L2capLeModule::Stop() { pimpl_.reset(); } -std::string L2capLeModule::ToString() const { - return "L2cap Le Module"; -} +std::string L2capLeModule::ToString() const { return "L2cap Le Module"; } std::unique_ptr L2capLeModule::GetFixedChannelManager() { - return std::unique_ptr(new FixedChannelManager(&pimpl_->fixed_channel_service_manager_impl_, - &pimpl_->link_manager_, pimpl_->l2cap_handler_)); + return std::unique_ptr( + new FixedChannelManager(&pimpl_->fixed_channel_service_manager_impl_, + &pimpl_->link_manager_, pimpl_->l2cap_handler_)); } std::unique_ptr L2capLeModule::GetDynamicChannelManager() { - return std::unique_ptr(new DynamicChannelManager( - &pimpl_->dynamic_channel_service_manager_impl_, &pimpl_->link_manager_, pimpl_->l2cap_handler_)); + return std::unique_ptr( + new DynamicChannelManager(&pimpl_->dynamic_channel_service_manager_impl_, + &pimpl_->link_manager_, pimpl_->l2cap_handler_)); } -void L2capLeModule::InjectSecurityEnforcementInterface(SecurityEnforcementInterface* security_enforcement_interface) { +void L2capLeModule::InjectSecurityEnforcementInterface( + SecurityEnforcementInterface* security_enforcement_interface) { if (security_enforcement_interface != nullptr) { - pimpl_->dynamic_channel_service_manager_impl_.SetSecurityEnforcementInterface(security_enforcement_interface); + pimpl_->dynamic_channel_service_manager_impl_.SetSecurityEnforcementInterface( + security_enforcement_interface); } else { - pimpl_->dynamic_channel_service_manager_impl_.SetSecurityEnforcementInterface(&default_security_module_impl_); + pimpl_->dynamic_channel_service_manager_impl_.SetSecurityEnforcementInterface( + &default_security_module_impl_); } } diff --git a/system/gd/l2cap/le/l2cap_le_module.h b/system/gd/l2cap/le/l2cap_le_module.h index 999f1dfad15..816538345d9 100644 --- a/system/gd/l2cap/le/l2cap_le_module.h +++ b/system/gd/l2cap/le/l2cap_le_module.h @@ -33,7 +33,7 @@ namespace l2cap { namespace le { class L2capLeModule : public bluetooth::Module { - public: +public: L2capLeModule(); L2capLeModule(const L2capLeModule&) = delete; L2capLeModule& operator=(const L2capLeModule&) = delete; @@ -52,7 +52,7 @@ class L2capLeModule : public bluetooth::Module { static const ModuleFactory Factory; - protected: +protected: void ListDependencies(ModuleList* list) const override; void Start() override; @@ -61,18 +61,19 @@ class L2capLeModule : public bluetooth::Module { std::string ToString() const override; - private: +private: struct impl; std::unique_ptr pimpl_; friend security::SecurityModule; /** - * Only for the LE security module to inject functionality to enforce security level for a connection. When LE - * security module is stopping, inject nullptr. Note: We expect this only to be called during stack startup. This is - * not synchronized. + * Only for the LE security module to inject functionality to enforce security level for a + * connection. When LE security module is stopping, inject nullptr. Note: We expect this only to + * be called during stack startup. This is not synchronized. */ - virtual void InjectSecurityEnforcementInterface(SecurityEnforcementInterface* security_enforcement_interface); + virtual void InjectSecurityEnforcementInterface( + SecurityEnforcementInterface* security_enforcement_interface); /** * Set the link property listener. diff --git a/system/gd/l2cap/le/l2cap_le_module_mock.h b/system/gd/l2cap/le/l2cap_le_module_mock.h index 897ddb0f637..0585546eaf9 100644 --- a/system/gd/l2cap/le/l2cap_le_module_mock.h +++ b/system/gd/l2cap/le/l2cap_le_module_mock.h @@ -15,10 +15,10 @@ */ #pragma once -#include "l2cap/le/l2cap_le_module.h" - #include +#include "l2cap/le/l2cap_le_module.h" + // Unit test interfaces namespace bluetooth { namespace l2cap { @@ -26,7 +26,7 @@ namespace le { namespace testing { class MockL2capLeModule : public L2capLeModule { - public: +public: MOCK_METHOD(std::unique_ptr, GetFixedChannelManager, (), (override)); }; diff --git a/system/gd/l2cap/le/link_options.cc b/system/gd/l2cap/le/link_options.cc index 152c4c2295d..9cf5a04419e 100644 --- a/system/gd/l2cap/le/link_options.cc +++ b/system/gd/l2cap/le/link_options.cc @@ -31,21 +31,17 @@ LinkOptions::LinkOptions(hci::acl_manager::LeAclConnection* acl_connection, inte os::Handler* l2cap_handler) : acl_connection_(acl_connection), link_(link), l2cap_handler_(l2cap_handler) {} -hci::Role LinkOptions::GetRole() const { - return acl_connection_->GetRole(); -} +hci::Role LinkOptions::GetRole() const { return acl_connection_->GetRole(); } -uint16_t LinkOptions::GetHandle() const { - return acl_connection_->GetHandle(); -} +uint16_t LinkOptions::GetHandle() const { return acl_connection_->GetHandle(); } hci::AddressWithType LinkOptions::GetLocalAddress() const { return acl_connection_->GetLocalAddress(); } bool LinkOptions::UpdateConnectionParameter(uint16_t conn_interval_min, uint16_t conn_interval_max, - uint16_t conn_latency, uint16_t supervision_timeout, uint16_t min_ce_length, - uint16_t max_ce_length) { + uint16_t conn_latency, uint16_t supervision_timeout, + uint16_t min_ce_length, uint16_t max_ce_length) { if (conn_interval_min < 0x0006 || conn_interval_min > 0x0C80 || conn_interval_max < 0x0006 || conn_interval_max > 0x0C80 || conn_latency > 0x01F3 || supervision_timeout < 0x000A || supervision_timeout > 0x0C80) { @@ -53,18 +49,16 @@ bool LinkOptions::UpdateConnectionParameter(uint16_t conn_interval_min, uint16_t return false; } - l2cap_handler_->Post(common::BindOnce(&internal::Link::SendConnectionParameterUpdate, common::Unretained(link_), - conn_interval_min, conn_interval_max, conn_latency, supervision_timeout, + l2cap_handler_->Post(common::BindOnce(&internal::Link::SendConnectionParameterUpdate, + common::Unretained(link_), conn_interval_min, + conn_interval_max, conn_latency, supervision_timeout, min_ce_length, max_ce_length)); return true; } -bool LinkOptions::SetPhy( - uint8_t /* all_phys */, - uint8_t /* tx_phys */, - uint8_t /* rx_phys */, - uint16_t /* phy_options */) { +bool LinkOptions::SetPhy(uint8_t /* all_phys */, uint8_t /* tx_phys */, uint8_t /* rx_phys */, + uint16_t /* phy_options */) { log::error("Not implemented"); return false; } diff --git a/system/gd/l2cap/le/link_options.h b/system/gd/l2cap/le/link_options.h index d7326df5e42..a001519ad5d 100644 --- a/system/gd/l2cap/le/link_options.h +++ b/system/gd/l2cap/le/link_options.h @@ -30,13 +30,13 @@ class Link; } /** - * Proxy for L2CAP user to get some link layer properties (connection handle, role), and set link layer options - * (connection parameter update, set PHY). Only few special L2CAP users need to use it, including Security Manager, - * Hearing Aid Profile, HID Profile, and Java API. - * Note: Setting link layer options applies to the LINK, not single CHANNEL. + * Proxy for L2CAP user to get some link layer properties (connection handle, role), and set link + * layer options (connection parameter update, set PHY). Only few special L2CAP users need to use + * it, including Security Manager, Hearing Aid Profile, HID Profile, and Java API. Note: Setting + * link layer options applies to the LINK, not single CHANNEL. */ class LinkOptions { - public: +public: /** * Get LL Role. Most applications should NOT know its LL role. */ @@ -54,15 +54,16 @@ class LinkOptions { /** * Update the LE link layer connection parameters. - * Depending on the link role and supported features, may directly send HCI command to update link, or send L2CAP - * request to advise the remote. The updated connection parameters are still determined by controller. It's a link - * layer change for performance tuning, and no host layer change should be observable by user. - * Parameters are defined in Core spec HCI 7.8.18. + * Depending on the link role and supported features, may directly send HCI command to update + * link, or send L2CAP request to advise the remote. The updated connection parameters are still + * determined by controller. It's a link layer change for performance tuning, and no host layer + * change should be observable by user. Parameters are defined in Core spec HCI 7.8.18. * @return true iff the request is sent to controller through HCI or remote through L2CAP * (Use it only if you know what you are doing!) */ - bool UpdateConnectionParameter(uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency, - uint16_t supervision_timeout, uint16_t min_ce_length, uint16_t max_ce_length); + bool UpdateConnectionParameter(uint16_t conn_interval_min, uint16_t conn_interval_max, + uint16_t conn_latency, uint16_t supervision_timeout, + uint16_t min_ce_length, uint16_t max_ce_length); /** * Set PHY preference. The PHY is determined by the controller. @@ -73,9 +74,10 @@ class LinkOptions { */ bool SetPhy(uint8_t all_phys, uint8_t tx_phys, uint8_t rx_phys, uint16_t phy_options); - LinkOptions(hci::acl_manager::LeAclConnection* acl_connection, internal::Link* link, os::Handler* l2cap_handler); + LinkOptions(hci::acl_manager::LeAclConnection* acl_connection, internal::Link* link, + os::Handler* l2cap_handler); - private: +private: hci::acl_manager::LeAclConnection* acl_connection_ = nullptr; internal::Link* link_ = nullptr; os::Handler* l2cap_handler_ = nullptr; diff --git a/system/gd/l2cap/le/link_property_listener.h b/system/gd/l2cap/le/link_property_listener.h index 9960dab952f..11ae0d7ca91 100644 --- a/system/gd/l2cap/le/link_property_listener.h +++ b/system/gd/l2cap/le/link_property_listener.h @@ -29,14 +29,14 @@ namespace le { * This is the listener interface for link property callbacks. */ class LinkPropertyListener { - public: +public: virtual ~LinkPropertyListener() = default; /** * Invoked when an ACL link is connected. */ - virtual void OnLinkConnected( - hci::AddressWithType /* remote */, uint16_t /* handle */, hci::Role /* my_role */) {} + virtual void OnLinkConnected(hci::AddressWithType /* remote */, uint16_t /* handle */, + hci::Role /* my_role */) {} /** * Invoked when an ACL link is disconnected. @@ -46,37 +46,32 @@ class LinkPropertyListener { /** * Invoked when received remote version information for a given link */ - virtual void OnReadRemoteVersionInformation( - hci::ErrorCode /* hci_status */, - hci::AddressWithType /* remote */, - uint8_t /* lmp_version */, - uint16_t /* manufacturer_name */, - uint16_t /* sub_version */) {} + virtual void OnReadRemoteVersionInformation(hci::ErrorCode /* hci_status */, + hci::AddressWithType /* remote */, + uint8_t /* lmp_version */, + uint16_t /* manufacturer_name */, + uint16_t /* sub_version */) {} /** * Invoked when received connection update for a given link */ - virtual void OnConnectionUpdate( - hci::AddressWithType /* remote */, - uint16_t /* connection_interval */, - uint16_t /* connection_latency */, - uint16_t /* supervision_timeout */) {} + virtual void OnConnectionUpdate(hci::AddressWithType /* remote */, + uint16_t /* connection_interval */, + uint16_t /* connection_latency */, + uint16_t /* supervision_timeout */) {} /** * Invoked when received PHY update for a given link */ - virtual void OnPhyUpdate( - hci::AddressWithType /* remote */, uint8_t /* tx_phy */, uint8_t /* rx_phy */) {} + virtual void OnPhyUpdate(hci::AddressWithType /* remote */, uint8_t /* tx_phy */, + uint8_t /* rx_phy */) {} /** * Invoked when received data length exchange for a given link */ - virtual void OnDataLengthChange( - hci::AddressWithType /* remote */, - uint16_t /* tx_octets */, - uint16_t /* tx_time */, - uint16_t /* rx_octets */, - uint16_t /* rx_time */) {} + virtual void OnDataLengthChange(hci::AddressWithType /* remote */, uint16_t /* tx_octets */, + uint16_t /* tx_time */, uint16_t /* rx_octets */, + uint16_t /* rx_time */) {} }; } // namespace le diff --git a/system/gd/l2cap/le/security_enforcement_interface.h b/system/gd/l2cap/le/security_enforcement_interface.h index d3bc0d73dd7..ccbd9b91c42 100644 --- a/system/gd/l2cap/le/security_enforcement_interface.h +++ b/system/gd/l2cap/le/security_enforcement_interface.h @@ -28,16 +28,18 @@ namespace le { * The interface for Security Module to implement. */ class SecurityEnforcementInterface { - public: +public: virtual ~SecurityEnforcementInterface() = default; using ResultCallback = common::ContextualOnceCallback; /** - * Invoked when L2CAP needs to open a channel with given security requirement. When the Security Module satisfies the - * required security level, or cannot satisfy at all, invoke the result_callback. + * Invoked when L2CAP needs to open a channel with given security requirement. When the Security + * Module satisfies the required security level, or cannot satisfy at all, invoke the + * result_callback. */ - virtual void Enforce(hci::AddressWithType remote, SecurityPolicy policy, ResultCallback result_callback) = 0; + virtual void Enforce(hci::AddressWithType remote, SecurityPolicy policy, + ResultCallback result_callback) = 0; }; } // namespace le diff --git a/system/gd/l2cap/signal_id.h b/system/gd/l2cap/signal_id.h index 24372b17eb4..15227d36e5c 100644 --- a/system/gd/l2cap/signal_id.h +++ b/system/gd/l2cap/signal_id.h @@ -22,18 +22,14 @@ namespace bluetooth { namespace l2cap { struct SignalId { - public: +public: constexpr SignalId(uint8_t value) : value_(value) {} constexpr SignalId() : value_(1) {} ~SignalId() = default; - uint8_t Value() const { - return value_; - } + uint8_t Value() const { return value_; } - bool IsValid() const { - return value_ != 0; - } + bool IsValid() const { return value_ != 0; } friend bool operator==(const SignalId& lhs, const SignalId& rhs); friend bool operator!=(const SignalId& lhs, const SignalId& rhs); @@ -43,7 +39,7 @@ struct SignalId { struct SignalId& operator--(); // Prefix decrement operator. struct SignalId operator--(int); // Postfix decrement operator. - private: +private: uint8_t value_; }; @@ -54,13 +50,13 @@ inline bool operator==(const SignalId& lhs, const SignalId& rhs) { return lhs.value_ == rhs.value_; } -inline bool operator!=(const SignalId& lhs, const SignalId& rhs) { - return !(lhs == rhs); -} +inline bool operator!=(const SignalId& lhs, const SignalId& rhs) { return !(lhs == rhs); } inline struct SignalId& SignalId::operator++() { value_++; - if (value_ == 0) value_++; + if (value_ == 0) { + value_++; + } return *this; } @@ -72,7 +68,9 @@ inline struct SignalId SignalId::operator++(int) { inline struct SignalId& SignalId::operator--() { value_--; - if (value_ == 0) value_ = 0xff; + if (value_ == 0) { + value_ = 0xff; + } return *this; } diff --git a/system/gd/l2cap/signal_id_test.cc b/system/gd/l2cap/signal_id_test.cc index cd9542583d6..5060a88de82 100644 --- a/system/gd/l2cap/signal_id_test.cc +++ b/system/gd/l2cap/signal_id_test.cc @@ -14,10 +14,11 @@ * limitations under the License. */ +#include "l2cap/signal_id.h" + #include -#include -#include "l2cap/signal_id.h" +#include namespace bluetooth { namespace l2cap { diff --git a/system/gd/metrics/chromeos/metrics.cc b/system/gd/metrics/chromeos/metrics.cc index 6aacbbb3fa7..fbe7afcba33 100644 --- a/system/gd/metrics/chromeos/metrics.cc +++ b/system/gd/metrics/chromeos/metrics.cc @@ -39,7 +39,9 @@ void LogMetricsAdapterStateChanged(uint32_t state) { int64_t boot_time; std::string boot_id; - if (!GetBootId(&boot_id)) return; + if (!GetBootId(&boot_id)) { + return; + } adapter_state = (int64_t)ToAdapterState(state); boot_time = bluetooth::common::time_get_os_boottime_us(); @@ -47,11 +49,11 @@ void LogMetricsAdapterStateChanged(uint32_t state) { log::debug("AdapterStateChanged: {}, {}, {}", boot_id, boot_time, adapter_state); ::metrics::structured::events::bluetooth::BluetoothAdapterStateChanged() - .SetBootId(boot_id) - .SetSystemTime(boot_time) - .SetIsFloss(true) - .SetAdapterState(adapter_state) - .Record(); + .SetBootId(boot_id) + .SetSystemTime(boot_time) + .SetIsFloss(true) + .SetAdapterState(adapter_state) + .Record(); LogMetricsChipsetInfoReport(); } @@ -62,38 +64,37 @@ void LogMetricsBondCreateAttempt(RawAddress* addr, uint32_t device_type) { std::string addr_string; std::string boot_id; - if (!GetBootId(&boot_id)) return; + if (!GetBootId(&boot_id)) { + return; + } addr_string = addr->ToString(); boot_time = bluetooth::common::time_get_os_boottime_us(); connection_type = ToPairingDeviceType(addr_string, device_type); - log::debug( - "PairingStateChanged: {}, {}, {}, {}, {}", - boot_id, - (int)boot_time, - *addr, - (int)connection_type, - (int)PairingState::PAIR_STARTING); + log::debug("PairingStateChanged: {}, {}, {}, {}, {}", boot_id, (int)boot_time, *addr, + (int)connection_type, (int)PairingState::PAIR_STARTING); ::metrics::structured::events::bluetooth::BluetoothPairingStateChanged() - .SetBootId(boot_id) - .SetSystemTime(boot_time) - .SetDeviceId(addr_string) - .SetDeviceType((int64_t)connection_type) - .SetPairingState((int64_t)PairingState::PAIR_STARTING) - .Record(); + .SetBootId(boot_id) + .SetSystemTime(boot_time) + .SetDeviceId(addr_string) + .SetDeviceType((int64_t)connection_type) + .SetPairingState((int64_t)PairingState::PAIR_STARTING) + .Record(); } -void LogMetricsBondStateChanged( - RawAddress* addr, uint32_t device_type, uint32_t status, uint32_t bond_state, int32_t fail_reason) { +void LogMetricsBondStateChanged(RawAddress* addr, uint32_t device_type, uint32_t status, + uint32_t bond_state, int32_t fail_reason) { ConnectionType connection_type; int64_t boot_time; PairingState pairing_state; std::string addr_string; std::string boot_id; - if (!GetBootId(&boot_id)) return; + if (!GetBootId(&boot_id)) { + return; + } addr_string = addr->ToString(); boot_time = bluetooth::common::time_get_os_boottime_us(); @@ -101,44 +102,39 @@ void LogMetricsBondStateChanged( pairing_state = ToPairingState(status, bond_state, fail_reason); // Ignore the start of pairing event as its logged separated above. - if (pairing_state == PairingState::PAIR_STARTING) return; + if (pairing_state == PairingState::PAIR_STARTING) { + return; + } // Ignore absurd state. - if (pairing_state == PairingState::PAIR_FAIL_END) return; + if (pairing_state == PairingState::PAIR_FAIL_END) { + return; + } - log::debug( - "PairingStateChanged: {}, {}, {}, {}, {}", - boot_id, - (int)boot_time, - *addr, - (int)connection_type, - (int)pairing_state); + log::debug("PairingStateChanged: {}, {}, {}, {}, {}", boot_id, (int)boot_time, *addr, + (int)connection_type, (int)pairing_state); ::metrics::structured::events::bluetooth::BluetoothPairingStateChanged() - .SetBootId(boot_id) - .SetSystemTime(boot_time) - .SetDeviceId(addr_string) - .SetDeviceType((int64_t)connection_type) - .SetPairingState((int64_t)pairing_state) - .Record(); + .SetBootId(boot_id) + .SetSystemTime(boot_time) + .SetDeviceId(addr_string) + .SetDeviceType((int64_t)connection_type) + .SetPairingState((int64_t)pairing_state) + .Record(); } -void LogMetricsDeviceInfoReport( - RawAddress* addr, - uint32_t device_type, - uint32_t class_of_device, - uint32_t appearance, - uint32_t vendor_id, - uint32_t vendor_id_src, - uint32_t product_id, - uint32_t version) { +void LogMetricsDeviceInfoReport(RawAddress* addr, uint32_t device_type, uint32_t class_of_device, + uint32_t appearance, uint32_t vendor_id, uint32_t vendor_id_src, + uint32_t product_id, uint32_t version) { int64_t boot_time; std::string addr_string; std::string boot_id; uint32_t major_class; uint32_t category; - if (!GetBootId(&boot_id)) return; + if (!GetBootId(&boot_id)) { + return; + } addr_string = addr->ToString(); boot_time = bluetooth::common::time_get_os_boottime_us(); @@ -146,18 +142,9 @@ void LogMetricsDeviceInfoReport( major_class = (class_of_device & DEVICE_MAJOR_CLASS_MASK) >> DEVICE_MAJOR_CLASS_BIT_OFFSET; category = (appearance & DEVICE_CATEGORY_MASK) >> DEVICE_CATEGORY_BIT_OFFSET; - log::debug( - "DeviceInfoReport {} {} {} {} {} {} {} {} {} {}", - boot_id, - (int)boot_time, - *addr, - (int)device_type, - (int)major_class, - (int)category, - (int)vendor_id, - (int)vendor_id_src, - (int)product_id, - (int)version); + log::debug("DeviceInfoReport {} {} {} {} {} {} {} {} {} {}", boot_id, (int)boot_time, *addr, + (int)device_type, (int)major_class, (int)category, (int)vendor_id, (int)vendor_id_src, + (int)product_id, (int)version); if (!IsDeviceInfoInAllowlist(vendor_id_src, vendor_id, product_id)) { vendor_id_src = 0; @@ -167,50 +154,49 @@ void LogMetricsDeviceInfoReport( } ::metrics::structured::events::bluetooth::BluetoothDeviceInfoReport() - .SetBootId(boot_id) - .SetSystemTime(boot_time) - .SetDeviceId(addr_string) - .SetDeviceType(device_type) - .SetDeviceClass(major_class) - .SetDeviceCategory(category) - .SetVendorId(vendor_id) - .SetVendorIdSource(vendor_id_src) - .SetProductId(product_id) - .SetProductVersion(version) - .Record(); + .SetBootId(boot_id) + .SetSystemTime(boot_time) + .SetDeviceId(addr_string) + .SetDeviceType(device_type) + .SetDeviceClass(major_class) + .SetDeviceCategory(category) + .SetVendorId(vendor_id) + .SetVendorIdSource(vendor_id_src) + .SetProductId(product_id) + .SetProductVersion(version) + .Record(); } -void LogMetricsProfileConnectionStateChanged(RawAddress* addr, uint32_t profile, uint32_t status, uint32_t state) { +void LogMetricsProfileConnectionStateChanged(RawAddress* addr, uint32_t profile, uint32_t status, + uint32_t state) { int64_t boot_time; std::string addr_string; std::string boot_id; - if (!GetBootId(&boot_id)) return; + if (!GetBootId(&boot_id)) { + return; + } addr_string = addr->ToString(); boot_time = bluetooth::common::time_get_os_boottime_us(); ProfileConnectionEvent event = ToProfileConnectionEvent(addr_string, profile, status, state); - if (Profile::UNKNOWN == (Profile)event.profile) return; + if (Profile::UNKNOWN == (Profile)event.profile) { + return; + } - log::debug( - "ProfileConnectionStateChanged: {}, {}, {}, {}, {}, {}", - boot_id, - (int)boot_time, - *addr, - (int)event.type, - (int)event.profile, - (int)event.state); + log::debug("ProfileConnectionStateChanged: {}, {}, {}, {}, {}, {}", boot_id, (int)boot_time, + *addr, (int)event.type, (int)event.profile, (int)event.state); ::metrics::structured::events::bluetooth::BluetoothProfileConnectionStateChanged() - .SetBootId(boot_id) - .SetSystemTime(boot_time) - .SetDeviceId(addr_string) - .SetStateChangeType((int64_t)event.type) - .SetProfile((int64_t)event.profile) - .SetProfileConnectionState((int64_t)event.state) - .Record(); + .SetBootId(boot_id) + .SetSystemTime(boot_time) + .SetDeviceId(addr_string) + .SetStateChangeType((int64_t)event.type) + .SetProfile((int64_t)event.profile) + .SetProfileConnectionState((int64_t)event.state) + .Record(); } void LogMetricsAclConnectAttempt(RawAddress* addr, uint32_t acl_state) { @@ -221,13 +207,9 @@ void LogMetricsAclConnectAttempt(RawAddress* addr, uint32_t acl_state) { PendingAclConnectAttemptEvent(addr_string, boot_time, acl_state); } -void LogMetricsAclConnectionStateChanged( - RawAddress* addr, - uint32_t transport, - uint32_t acl_status, - uint32_t acl_state, - uint32_t direction, - uint32_t hci_reason) { +void LogMetricsAclConnectionStateChanged(RawAddress* addr, uint32_t transport, uint32_t acl_status, + uint32_t acl_state, uint32_t direction, + uint32_t hci_reason) { int64_t boot_time; std::string addr_string; std::string boot_id; @@ -237,57 +219,44 @@ void LogMetricsAclConnectionStateChanged( boot_time = bluetooth::common::time_get_os_boottime_us(); addr_string = addr->ToString(); - event = ToAclConnectionEvent(addr_string, boot_time, acl_status, acl_state, direction, hci_reason); + event = ToAclConnectionEvent(addr_string, boot_time, acl_status, acl_state, direction, + hci_reason); if (!GetBootId(&boot_id)) { return; } - log::debug( - "AclConnectionStateChanged: {}, {}, {}, {}, {}, {}, {}, {}", - boot_id, - (int)event.start_time, - *addr, - (int)transport, - (int)event.direction, - (int)event.initiator, - (int)event.state, - (int)event.start_status); + log::debug("AclConnectionStateChanged: {}, {}, {}, {}, {}, {}, {}, {}", boot_id, + (int)event.start_time, *addr, (int)transport, (int)event.direction, + (int)event.initiator, (int)event.state, (int)event.start_status); ::metrics::structured::events::bluetooth::BluetoothAclConnectionStateChanged() - .SetBootId(boot_id) - .SetSystemTime(event.start_time) - .SetIsFloss(true) - .SetDeviceId(addr_string) - .SetDeviceType(transport) - .SetConnectionDirection(event.direction) - .SetConnectionInitiator(event.initiator) - .SetStateChangeType(event.state) - .SetAclConnectionState(event.start_status) - .Record(); - - log::debug( - "AclConnectionStateChanged: {}, {}, {}, {}, {}, {}, {}, {}", - boot_id, - (int)boot_time, - *addr, - (int)transport, - (int)event.direction, - (int)event.initiator, - (int)event.state, - (int)event.status); + .SetBootId(boot_id) + .SetSystemTime(event.start_time) + .SetIsFloss(true) + .SetDeviceId(addr_string) + .SetDeviceType(transport) + .SetConnectionDirection(event.direction) + .SetConnectionInitiator(event.initiator) + .SetStateChangeType(event.state) + .SetAclConnectionState(event.start_status) + .Record(); + + log::debug("AclConnectionStateChanged: {}, {}, {}, {}, {}, {}, {}, {}", boot_id, (int)boot_time, + *addr, (int)transport, (int)event.direction, (int)event.initiator, (int)event.state, + (int)event.status); ::metrics::structured::events::bluetooth::BluetoothAclConnectionStateChanged() - .SetBootId(boot_id) - .SetSystemTime(boot_time) - .SetIsFloss(true) - .SetDeviceId(addr_string) - .SetDeviceType(transport) - .SetConnectionDirection(event.direction) - .SetConnectionInitiator(event.initiator) - .SetStateChangeType(event.state) - .SetAclConnectionState(event.status) - .Record(); + .SetBootId(boot_id) + .SetSystemTime(boot_time) + .SetIsFloss(true) + .SetDeviceId(addr_string) + .SetDeviceType(transport) + .SetConnectionDirection(event.direction) + .SetConnectionInitiator(event.initiator) + .SetStateChangeType(event.state) + .SetAclConnectionState(event.status) + .Record(); LogMetricsChipsetInfoReport(); } @@ -306,21 +275,17 @@ void LogMetricsChipsetInfoReport() { return; } - log::debug( - "ChipsetInfoReport: 0x{:x} 0x{:x} {} {}", - info->vid, - info->pid, - info->transport, - info->chipset_string); + log::debug("ChipsetInfoReport: 0x{:x} 0x{:x} {} {}", info->vid, info->pid, info->transport, + info->chipset_string); - if (IsChipsetInfoInAllowList( - info->vid, info->pid, info->transport, info->chipset_string.c_str(), &chipset_string_hval)) { + if (IsChipsetInfoInAllowList(info->vid, info->pid, info->transport, info->chipset_string.c_str(), + &chipset_string_hval)) { ::metrics::structured::events::bluetooth::BluetoothChipsetInfoReport() - .SetBootId(boot_id.c_str()) - .SetVendorId(info->vid) - .SetProductId(info->pid) - .SetTransport(info->transport) - .SetChipsetStringHashValue(chipset_string_hval); + .SetBootId(boot_id.c_str()) + .SetVendorId(info->vid) + .SetProductId(info->pid) + .SetTransport(info->transport) + .SetChipsetStringHashValue(chipset_string_hval); } } @@ -329,7 +294,9 @@ void LogMetricsSuspendIdState(uint32_t state) { int64_t boot_time; std::string boot_id; - if (!GetBootId(&boot_id)) return; + if (!GetBootId(&boot_id)) { + return; + } boot_time = bluetooth::common::time_get_os_boottime_us(); @@ -337,10 +304,10 @@ void LogMetricsSuspendIdState(uint32_t state) { log::debug("SuspendIdState: {}, {}, {}", boot_id, boot_time, suspend_id_state); ::metrics::structured::events::bluetooth::BluetoothSuspendIdStateChanged() - .SetBootId(boot_id) - .SetSystemTime(boot_time) - .SetSuspendIdState(suspend_id_state) - .Record(); + .SetBootId(boot_id) + .SetSystemTime(boot_time) + .SetSuspendIdState(suspend_id_state) + .Record(); } } // namespace metrics diff --git a/system/gd/metrics/chromeos/metrics_allowlist.cc b/system/gd/metrics/chromeos/metrics_allowlist.cc index ef77650d492..47cec3af454 100644 --- a/system/gd/metrics/chromeos/metrics_allowlist.cc +++ b/system/gd/metrics/chromeos/metrics_allowlist.cc @@ -25,163 +25,163 @@ namespace metrics { namespace { static constexpr int device_info_allow_list_sig[][2] = { - /* Ericsson Technology Licensing */ - {0, 52}, - /* Motorola */ - {8, 11905}, - /* Qualcomm Technologies International, Ltd. (QTIL) */ - {10, 65535}, - /* Texas Instruments Inc. */ - {13, 0}, - /* Broadcom Corporation. */ - {15, 4608}, - /* Qualcomm */ - {29, 4608}, - /* Integrated System Solution Corp. */ - {57, 5028}, - {57, 5506}, - /* MediaTek, Inc. */ - {70, 4608}, - /* Apple, Inc. */ - {76, 8194}, - {76, 8198}, - {76, 8201}, - {76, 8203}, - {76, 8204}, - {76, 8206}, - {76, 8207}, - {76, 8208}, - {76, 8211}, - /* Harman International Industries, Inc. */ - {87, 35}, - {87, 7977}, - /* Realtek Semiconductor Corporation */ - {93, 8763}, - /* Samsung Electronics Co. Ltd. */ - {117, 256}, - {117, 40977}, - {117, 40978}, - {117, 40979}, - /* Airoha Technology Corp. */ - {148, 4}, - {148, 291}, - /* LG Electronics​ */ - {196, 5025}, - /* Google */ - {224, 0}, - {224, 4608}, - {224, 12288}, - {224, 12289}, - {224, 12290}, - {224, 12291}, - {224, 12292}, - {224, 12544}, - {224, 50181}, - /* Amazon.com Services, LLC */ - {369, 384}, - /* Bestechnic(Shanghai),Ltd */ - {688, 0}, - /* LEGO System A/S */ - {919, 1}, - /* Actions (Zhuhai) Technology Co., Limited */ - {992, 12298}, - /* STABILO International */ - {1256, 32896}, - /* GoerTek Dynaudio Co., Ltd. */ - {1452, 544}, - /* Zhuhai Jieli technology Co.,Ltd */ - {1494, 10}}; + /* Ericsson Technology Licensing */ + {0, 52}, + /* Motorola */ + {8, 11905}, + /* Qualcomm Technologies International, Ltd. (QTIL) */ + {10, 65535}, + /* Texas Instruments Inc. */ + {13, 0}, + /* Broadcom Corporation. */ + {15, 4608}, + /* Qualcomm */ + {29, 4608}, + /* Integrated System Solution Corp. */ + {57, 5028}, + {57, 5506}, + /* MediaTek, Inc. */ + {70, 4608}, + /* Apple, Inc. */ + {76, 8194}, + {76, 8198}, + {76, 8201}, + {76, 8203}, + {76, 8204}, + {76, 8206}, + {76, 8207}, + {76, 8208}, + {76, 8211}, + /* Harman International Industries, Inc. */ + {87, 35}, + {87, 7977}, + /* Realtek Semiconductor Corporation */ + {93, 8763}, + /* Samsung Electronics Co. Ltd. */ + {117, 256}, + {117, 40977}, + {117, 40978}, + {117, 40979}, + /* Airoha Technology Corp. */ + {148, 4}, + {148, 291}, + /* LG Electronics​ */ + {196, 5025}, + /* Google */ + {224, 0}, + {224, 4608}, + {224, 12288}, + {224, 12289}, + {224, 12290}, + {224, 12291}, + {224, 12292}, + {224, 12544}, + {224, 50181}, + /* Amazon.com Services, LLC */ + {369, 384}, + /* Bestechnic(Shanghai),Ltd */ + {688, 0}, + /* LEGO System A/S */ + {919, 1}, + /* Actions (Zhuhai) Technology Co., Limited */ + {992, 12298}, + /* STABILO International */ + {1256, 32896}, + /* GoerTek Dynaudio Co., Ltd. */ + {1452, 544}, + /* Zhuhai Jieli technology Co.,Ltd */ + {1494, 10}}; static constexpr int device_info_allow_list_usb[][2] = { - /* Unknown */ - {14, 13330}, - /* Unknown */ - {97, 1}, - /* Unknown */ - {125, 628}, - /* HP, Inc */ - {1008, 2124}, - {1008, 588}, - /* Unknown */ - {1014, 40961}, - /* Microsoft Corp. */ - {1118, 736}, - {1118, 765}, - {1118, 1954}, - {1118, 2053}, - {1118, 2054}, - {1118, 2087}, - {1118, 2095}, - {1118, 2326}, - {1118, 2354}, - {1118, 2397}, - {1118, 2835}, - {1118, 2848}, - /* Primax Electronics, Ltd */ - {1121, 20206}, - {1121, 20207}, - /* Logitech, Inc. */ - {1133, 45072}, - {1133, 45076}, - {1133, 45077}, - {1133, 45078}, - {1133, 45081}, - {1133, 45082}, - {1133, 45083}, - {1133, 45089}, - {1133, 45091}, - {1133, 45093}, - {1133, 45094}, - {1133, 45095}, - {1133, 45883}, - {1133, 45885}, - {1133, 45890}, - {1133, 45901}, - {1133, 45915}, - {1133, 45917}, - {1133, 45890}, - /* Samsung Electronics Co., Ltd */ - {1256, 28705}, - /* Sony Corp. */ - {1356, 1476}, - {1356, 2508}, - {1356, 3302}, - /* Wacom Co., Ltd */ - {1386, 887}, - /* Nintendo Co., Ltd */ - {1406, 8198}, - {1406, 8199}, - {1406, 8201}, - /* Apple, Inc. */ - {1452, 544}, - {1452, 556}, - {1452, 569}, - {1452, 591}, - {1452, 597}, - {1452, 781}, - {1452, 12850}, - /* Zippy Technology Corp. */ - {2458, 1280}, - /* Broadcom Corp. */ - {2652, 1}, - {2652, 17667}, - {2652, 63369}, - /* Microdia */ - {3141, 32270}, - /* Focusrite-Novation */ - {4661, 43554}, - /* Razer USA, Ltd */ - {5426, 130}, - /* Nordic Semiconductor ASA */ - {6421, 64}, - /* Lab126, Inc. */ - {6473, 1026}, - /* Anker Innovations Limited */ - {10522, 34050}, - /* Unknown */ - {12994, 1}, - /* Fuji Yusoki Kogyo Co., Ltd. */ - {44580, 34328}, + /* Unknown */ + {14, 13330}, + /* Unknown */ + {97, 1}, + /* Unknown */ + {125, 628}, + /* HP, Inc */ + {1008, 2124}, + {1008, 588}, + /* Unknown */ + {1014, 40961}, + /* Microsoft Corp. */ + {1118, 736}, + {1118, 765}, + {1118, 1954}, + {1118, 2053}, + {1118, 2054}, + {1118, 2087}, + {1118, 2095}, + {1118, 2326}, + {1118, 2354}, + {1118, 2397}, + {1118, 2835}, + {1118, 2848}, + /* Primax Electronics, Ltd */ + {1121, 20206}, + {1121, 20207}, + /* Logitech, Inc. */ + {1133, 45072}, + {1133, 45076}, + {1133, 45077}, + {1133, 45078}, + {1133, 45081}, + {1133, 45082}, + {1133, 45083}, + {1133, 45089}, + {1133, 45091}, + {1133, 45093}, + {1133, 45094}, + {1133, 45095}, + {1133, 45883}, + {1133, 45885}, + {1133, 45890}, + {1133, 45901}, + {1133, 45915}, + {1133, 45917}, + {1133, 45890}, + /* Samsung Electronics Co., Ltd */ + {1256, 28705}, + /* Sony Corp. */ + {1356, 1476}, + {1356, 2508}, + {1356, 3302}, + /* Wacom Co., Ltd */ + {1386, 887}, + /* Nintendo Co., Ltd */ + {1406, 8198}, + {1406, 8199}, + {1406, 8201}, + /* Apple, Inc. */ + {1452, 544}, + {1452, 556}, + {1452, 569}, + {1452, 591}, + {1452, 597}, + {1452, 781}, + {1452, 12850}, + /* Zippy Technology Corp. */ + {2458, 1280}, + /* Broadcom Corp. */ + {2652, 1}, + {2652, 17667}, + {2652, 63369}, + /* Microdia */ + {3141, 32270}, + /* Focusrite-Novation */ + {4661, 43554}, + /* Razer USA, Ltd */ + {5426, 130}, + /* Nordic Semiconductor ASA */ + {6421, 64}, + /* Lab126, Inc. */ + {6473, 1026}, + /* Anker Innovations Limited */ + {10522, 34050}, + /* Unknown */ + {12994, 1}, + /* Fuji Yusoki Kogyo Co., Ltd. */ + {44580, 34328}, }; @@ -197,71 +197,71 @@ enum Transport { * go/cros-chipset-info-0512 */ static constexpr int chipset_info_allow_list_vidpid[][3] = { - /* Intel */ - {USB, 0x8086, 0x095a}, // INTEL-AC7265 - {USB, 0x8086, 0x31dc}, // INTEL-AC9560 - {USB, 0x8086, 0x4df0}, // INTEL-AX201 - {USB, 0x8086, 0x095b}, // INTEL-AC7265 - {USB, 0x8086, 0x02f0}, // INTEL-AX201 - {USB, 0x8086, 0x51f0}, - {USB, 0x8086, 0xa0f0}, // INTEL-AX201 - {USB, 0x8086, 0x2526}, // INTEL-AC9260 - {USB, 0x8086, 0x3165}, - {USB, 0x8086, 0x2723}, // INTEL-AX200 - {USB, 0x8086, 0x08b1}, // INTEL-AC7260 - {USB, 0x8086, 0x24fd}, - {USB, 0x8086, 0x9df0}, // INTEL-AC9560 - {USB, 0x8086, 0x08b3}, - {USB, 0x8086, 0x24fb}, - {USB, 0x8086, 0x3166}, - {USB, 0x8086, 0x24f3}, - {USB, 0x8086, 0x08b2}, // INTEL-AC7260 - {USB, 0x8086, 0x08b4}, - {USB, 0x8086, 0x0887}, - {USB, 0x8086, 0x4232}, - {USB, 0x8086, 0x088e}, - {USB, 0x8086, 0x0085}, - {USB, 0x8086, 0x0082}, - {USB, 0x8086, 0x4239}, - {USB, 0x8086, 0x4238}, - {USB, 0x8086, 0x4222}, - {USB, 0x8086, 0x008a}, - {USB, 0x8086, 0xa370}, - {USB, 0x8086, 0x54f0}, - {USB, 0x8086, 0x422c}, - {USB, 0x8086, 0x4237}, - {USB, 0x8086, 0x4229}, - /* Qualcomm */ - {USB, 0x168c, 0x003e}, // QCA-6174A-5 - {UART, 0x0271, 0x050a}, // QCA-6174A-3 - {USB, 0x168c, 0x0042}, - {USB, 0x168c, 0x0036}, - {USB, 0x168c, 0x0032}, - {USB, 0x168c, 0x002b}, - {USB, 0x168c, 0x0034}, - {USB, 0x168c, 0x002a}, - {USB, 0x168c, 0x0030}, - /* Realtek */ - {USB, 0x10ec, 0xc822}, // Realtek-RTL8822C-USB - {USB, 0x10ec, 0xb723}, - {USB, 0x10ec, 0xc821}, - {USB, 0x10ec, 0x8821}, - {USB, 0x10ec, 0xb822}, - {USB, 0x10ec, 0x8852}, // Realtek-RTL8852A-USB - {USB, 0x10ec, 0x8723}, - {USB, 0x10ec, 0x8176}, - {UART, 0x10ec, 0xc822}, // Realtek-RTL8822C-UART - {USB, 0x10ec, 0xc82f}, - /* Marvell */ - {SDIO, 0x02df, 0x912d}, // MVL-8897 - {USB, 0x1b4b, 0x2b42}, // MVL-8997 - /* Unknown */ - {USB, 0x14e4, 0x4365}, - {USB, 0x14e4, 0x43a0}, - {USB, 0x1814, 0x3090}, - /* MediaTek */ - {USB, 0x14c3, 0x7961}, // Mediatek-MTK7921-USB - {SDIO, 0x037a, 0x7901}, // Mediatek-MTK7921-SDIO + /* Intel */ + {USB, 0x8086, 0x095a}, // INTEL-AC7265 + {USB, 0x8086, 0x31dc}, // INTEL-AC9560 + {USB, 0x8086, 0x4df0}, // INTEL-AX201 + {USB, 0x8086, 0x095b}, // INTEL-AC7265 + {USB, 0x8086, 0x02f0}, // INTEL-AX201 + {USB, 0x8086, 0x51f0}, + {USB, 0x8086, 0xa0f0}, // INTEL-AX201 + {USB, 0x8086, 0x2526}, // INTEL-AC9260 + {USB, 0x8086, 0x3165}, + {USB, 0x8086, 0x2723}, // INTEL-AX200 + {USB, 0x8086, 0x08b1}, // INTEL-AC7260 + {USB, 0x8086, 0x24fd}, + {USB, 0x8086, 0x9df0}, // INTEL-AC9560 + {USB, 0x8086, 0x08b3}, + {USB, 0x8086, 0x24fb}, + {USB, 0x8086, 0x3166}, + {USB, 0x8086, 0x24f3}, + {USB, 0x8086, 0x08b2}, // INTEL-AC7260 + {USB, 0x8086, 0x08b4}, + {USB, 0x8086, 0x0887}, + {USB, 0x8086, 0x4232}, + {USB, 0x8086, 0x088e}, + {USB, 0x8086, 0x0085}, + {USB, 0x8086, 0x0082}, + {USB, 0x8086, 0x4239}, + {USB, 0x8086, 0x4238}, + {USB, 0x8086, 0x4222}, + {USB, 0x8086, 0x008a}, + {USB, 0x8086, 0xa370}, + {USB, 0x8086, 0x54f0}, + {USB, 0x8086, 0x422c}, + {USB, 0x8086, 0x4237}, + {USB, 0x8086, 0x4229}, + /* Qualcomm */ + {USB, 0x168c, 0x003e}, // QCA-6174A-5 + {UART, 0x0271, 0x050a}, // QCA-6174A-3 + {USB, 0x168c, 0x0042}, + {USB, 0x168c, 0x0036}, + {USB, 0x168c, 0x0032}, + {USB, 0x168c, 0x002b}, + {USB, 0x168c, 0x0034}, + {USB, 0x168c, 0x002a}, + {USB, 0x168c, 0x0030}, + /* Realtek */ + {USB, 0x10ec, 0xc822}, // Realtek-RTL8822C-USB + {USB, 0x10ec, 0xb723}, + {USB, 0x10ec, 0xc821}, + {USB, 0x10ec, 0x8821}, + {USB, 0x10ec, 0xb822}, + {USB, 0x10ec, 0x8852}, // Realtek-RTL8852A-USB + {USB, 0x10ec, 0x8723}, + {USB, 0x10ec, 0x8176}, + {UART, 0x10ec, 0xc822}, // Realtek-RTL8822C-UART + {USB, 0x10ec, 0xc82f}, + /* Marvell */ + {SDIO, 0x02df, 0x912d}, // MVL-8897 + {USB, 0x1b4b, 0x2b42}, // MVL-8997 + /* Unknown */ + {USB, 0x14e4, 0x4365}, + {USB, 0x14e4, 0x43a0}, + {USB, 0x1814, 0x3090}, + /* MediaTek */ + {USB, 0x14c3, 0x7961}, // Mediatek-MTK7921-USB + {SDIO, 0x037a, 0x7901}, // Mediatek-MTK7921-SDIO }; static constexpr struct chipstr_transport { @@ -269,41 +269,45 @@ static constexpr struct chipstr_transport { uint64_t hash_value; const char* str; } chipset_info_allow_list_str[] = { - {USB, 0x676651522ac38489ULL, "usb:v8087p0AAAd0002dcE0dsc01dp01icE0isc01ip01in00"}, - {UART, 0x0f7029c4e4bee5c2ULL, "of:NbluetoothT(null)Cqcom,wcn3991-bt"}, - {USB, 0xc87adddb3473cef2ULL, "usb:v8087p0033d0000dcE0dsc01dp01icE0isc01ip01in00"}, - {USB, 0xd4af1ceff203aa54ULL, "usb:v8087p0A2Ad0003dcE0dsc01dp01icE0isc01ip01in00"}, - {USB, 0x67ff2e0860c6088cULL, "usb:v8087p0026d0002dcE0dsc01dp01icE0isc01ip01in00"}, - {USB, 0x5ea49b43333b6757ULL, "usb:v0BDApB009d0200dcE0dsc01dp01icE0isc01ip01in00"}, - {USB, 0xae4252633a7fc378ULL, "usb:v0A12p0001d8891dcE0dsc01dp01icE0isc01ip01in00"}, - {USB, 0xe8b1d7dcab4a9180ULL, "usb:v05ACp821Fd0156dcFFdsc01dp01icFFisc01ip01in00"}, - {USB, 0xf2fc524b34906492ULL, "usb:v413Cp8160d0173dcE0dsc01dp01icE0isc01ip01in00"}, - {USB, 0xa16695ffe3ebcf8eULL, "usb:v0BDApB00Cd0000dcE0dsc01dp01icE0isc01ip01in00"}, - {USB, 0x45fa5f31f455c161ULL, "usb:v05ACp821Ad0042dcFFdsc01dp01icFFisc01ip01in00"}, - {USB, 0xed0707b5f055458dULL, "usb:v05ACp821Dd0156dcFFdsc01dp01icFFisc01ip01in00"}, - {UART, 0x645c8874e1a27038ULL, "of:NbluetoothT(null)Cqcom,wcn6750-bt"}, - {USB, 0xf8feae883f843f61ULL, "usb:v0A5Cp21BCd0761dcE0dsc01dp01icE0isc01ip01in00"}, - {USB, 0x3db1b39b76523e6fULL, "usb:v0A5Cp219Cd0628dcE0dsc01dp01icE0isc01ip01in00"}, - {USB, 0xa4fec7094cdb7bedULL, "usb:v05ACp8205d1965dcE0dsc01dp01icE0isc01ip01in00"}, - {USB, 0x952ae80214a19dd9ULL, "usb:v05ACp828Ad0150dcFFdsc01dp01icFFisc01ip01in00"}, - {USB, 0x40e84e9cf6844c32ULL, "usb:v8087p0025d0002dcE0dsc01dp01icE0isc01ip01in00"}, - {USB, 0x6b037999f75bc6ceULL, "usb:v0A5Cp21F1d0112dcFFdsc01dp01icFFisc01ip01in00"}, - {USB, 0x91be30aba4f17b7eULL, "usb:v8087p0A2Ad0001dcE0dsc01dp01icE0isc01ip01in00"}, - {USB, 0xd393d6690ca2c212ULL, "usb:v0BDApB720d0200dcEFdsc02dp01icE0isc01ip01in00"}, + {USB, 0x676651522ac38489ULL, "usb:v8087p0AAAd0002dcE0dsc01dp01icE0isc01ip01in00"}, + {UART, 0x0f7029c4e4bee5c2ULL, "of:NbluetoothT(null)Cqcom,wcn3991-bt"}, + {USB, 0xc87adddb3473cef2ULL, "usb:v8087p0033d0000dcE0dsc01dp01icE0isc01ip01in00"}, + {USB, 0xd4af1ceff203aa54ULL, "usb:v8087p0A2Ad0003dcE0dsc01dp01icE0isc01ip01in00"}, + {USB, 0x67ff2e0860c6088cULL, "usb:v8087p0026d0002dcE0dsc01dp01icE0isc01ip01in00"}, + {USB, 0x5ea49b43333b6757ULL, "usb:v0BDApB009d0200dcE0dsc01dp01icE0isc01ip01in00"}, + {USB, 0xae4252633a7fc378ULL, "usb:v0A12p0001d8891dcE0dsc01dp01icE0isc01ip01in00"}, + {USB, 0xe8b1d7dcab4a9180ULL, "usb:v05ACp821Fd0156dcFFdsc01dp01icFFisc01ip01in00"}, + {USB, 0xf2fc524b34906492ULL, "usb:v413Cp8160d0173dcE0dsc01dp01icE0isc01ip01in00"}, + {USB, 0xa16695ffe3ebcf8eULL, "usb:v0BDApB00Cd0000dcE0dsc01dp01icE0isc01ip01in00"}, + {USB, 0x45fa5f31f455c161ULL, "usb:v05ACp821Ad0042dcFFdsc01dp01icFFisc01ip01in00"}, + {USB, 0xed0707b5f055458dULL, "usb:v05ACp821Dd0156dcFFdsc01dp01icFFisc01ip01in00"}, + {UART, 0x645c8874e1a27038ULL, "of:NbluetoothT(null)Cqcom,wcn6750-bt"}, + {USB, 0xf8feae883f843f61ULL, "usb:v0A5Cp21BCd0761dcE0dsc01dp01icE0isc01ip01in00"}, + {USB, 0x3db1b39b76523e6fULL, "usb:v0A5Cp219Cd0628dcE0dsc01dp01icE0isc01ip01in00"}, + {USB, 0xa4fec7094cdb7bedULL, "usb:v05ACp8205d1965dcE0dsc01dp01icE0isc01ip01in00"}, + {USB, 0x952ae80214a19dd9ULL, "usb:v05ACp828Ad0150dcFFdsc01dp01icFFisc01ip01in00"}, + {USB, 0x40e84e9cf6844c32ULL, "usb:v8087p0025d0002dcE0dsc01dp01icE0isc01ip01in00"}, + {USB, 0x6b037999f75bc6ceULL, "usb:v0A5Cp21F1d0112dcFFdsc01dp01icFFisc01ip01in00"}, + {USB, 0x91be30aba4f17b7eULL, "usb:v8087p0A2Ad0001dcE0dsc01dp01icE0isc01ip01in00"}, + {USB, 0xd393d6690ca2c212ULL, "usb:v0BDApB720d0200dcEFdsc02dp01icE0isc01ip01in00"}, }; } // namespace bool IsDeviceInfoInAllowlist(int vendor_id_source, int vendor_id, int product_id) { if (vendor_id_source == 1) { - for (int i = 0; i < sizeof(device_info_allow_list_sig) / sizeof(device_info_allow_list_sig[0]); i++) { - if (vendor_id == device_info_allow_list_sig[i][0] && product_id == device_info_allow_list_sig[i][1]) { + for (int i = 0; i < sizeof(device_info_allow_list_sig) / sizeof(device_info_allow_list_sig[0]); + i++) { + if (vendor_id == device_info_allow_list_sig[i][0] && + product_id == device_info_allow_list_sig[i][1]) { return true; } } } else if (vendor_id_source == 2) { - for (int i = 0; i < sizeof(device_info_allow_list_usb) / sizeof(device_info_allow_list_usb[0]); i++) { - if (vendor_id == device_info_allow_list_usb[i][0] && product_id == device_info_allow_list_usb[i][1]) { + for (int i = 0; i < sizeof(device_info_allow_list_usb) / sizeof(device_info_allow_list_usb[0]); + i++) { + if (vendor_id == device_info_allow_list_usb[i][0] && + product_id == device_info_allow_list_usb[i][1]) { return true; } } @@ -312,10 +316,12 @@ bool IsDeviceInfoInAllowlist(int vendor_id_source, int vendor_id, int product_id return false; } -bool IsChipsetInfoInAllowList( - int vendor_id, int product_id, int transport, const char* chipset_string, uint64_t* hval) { +bool IsChipsetInfoInAllowList(int vendor_id, int product_id, int transport, + const char* chipset_string, uint64_t* hval) { if (vendor_id != 0 && product_id != 0) { - for (int i = 0; i < sizeof(chipset_info_allow_list_vidpid) / sizeof(chipset_info_allow_list_vidpid[0]); i++) { + for (int i = 0; + i < sizeof(chipset_info_allow_list_vidpid) / sizeof(chipset_info_allow_list_vidpid[0]); + i++) { const int* record = chipset_info_allow_list_vidpid[i]; if (transport == record[0] && vendor_id == record[1] && product_id == record[2]) { @@ -323,7 +329,8 @@ bool IsChipsetInfoInAllowList( } } } else if (!!chipset_string && !!strlen(chipset_string)) { - for (int i = 0; i < sizeof(chipset_info_allow_list_str) / sizeof(chipset_info_allow_list_str[0]); i++) { + for (int i = 0; + i < sizeof(chipset_info_allow_list_str) / sizeof(chipset_info_allow_list_str[0]); i++) { const struct chipstr_transport* record = &chipset_info_allow_list_str[i]; if (strcmp(chipset_string, record->str) == 0 && transport == record->transport) { diff --git a/system/gd/metrics/chromeos/metrics_allowlist.h b/system/gd/metrics/chromeos/metrics_allowlist.h index 5f3377cef2c..07e00a05090 100644 --- a/system/gd/metrics/chromeos/metrics_allowlist.h +++ b/system/gd/metrics/chromeos/metrics_allowlist.h @@ -21,7 +21,8 @@ namespace bluetooth { namespace metrics { bool IsDeviceInfoInAllowlist(int vendor_id_source, int vendor_id, int product_id); -bool IsChipsetInfoInAllowList(int vendor_id, int product_id, int transport, const char* chipset_string, uint64_t* hval); +bool IsChipsetInfoInAllowList(int vendor_id, int product_id, int transport, + const char* chipset_string, uint64_t* hval); } // namespace metrics } // namespace bluetooth \ No newline at end of file diff --git a/system/gd/metrics/chromeos/metrics_event.cc b/system/gd/metrics/chromeos/metrics_event.cc index cc8bb056212..dff91408f0a 100644 --- a/system/gd/metrics/chromeos/metrics_event.cc +++ b/system/gd/metrics/chromeos/metrics_event.cc @@ -54,9 +54,11 @@ typedef bt_conn_direction_t BtConnectionDirection; typedef bt_status_t BtStatus; // topshim::profile::a2dp::BtavConnectionState is a copy of hardware/bt_av.h:btav_connection_state_t typedef btav_connection_state_t BtavConnectionState; -// topshim::profile::hid_host::BthhConnectionState is a copy of hardware/bt_hh.h:bthh_connection_state_t +// topshim::profile::hid_host::BthhConnectionState is a copy of +// hardware/bt_hh.h:bthh_connection_state_t typedef bthh_connection_state_t BthhConnectionState; -// topshim::profile::hid_host::BthfConnectionState is a copy of hardware/bt_hh.h:bthf_connection_state_t +// topshim::profile::hid_host::BthfConnectionState is a copy of +// hardware/bt_hh.h:bthf_connection_state_t typedef headset::bthf_connection_state_t BthfConnectionState; // A copy of topshim::btif::BtDeviceType @@ -265,10 +267,14 @@ ConnectionType ToPairingDeviceType(std::string addr, uint32_t device_type) { PairingState ToPairingState(uint32_t status, uint32_t bond_state, int32_t fail_reason) { PairingState pairing_state = PairingState::PAIR_FAIL_UNKNOWN; - // The Bonding is a transitional state during the pairing process. Ignore it by returning the starting again. - if ((BtBondState)bond_state == BtBondState::BT_BOND_STATE_BONDING) return PairingState::PAIR_STARTING; + // The Bonding is a transitional state during the pairing process. Ignore it by returning the + // starting again. + if ((BtBondState)bond_state == BtBondState::BT_BOND_STATE_BONDING) { + return PairingState::PAIR_STARTING; + } - if ((BtStatus)status == BtStatus::BT_STATUS_SUCCESS && (hci::ErrorCode)fail_reason == hci::ErrorCode::SUCCESS) { + if ((BtStatus)status == BtStatus::BT_STATUS_SUCCESS && + (hci::ErrorCode)fail_reason == hci::ErrorCode::SUCCESS) { if ((BtBondState)bond_state == BtBondState::BT_BOND_STATE_BONDED) { return PairingState::PAIR_SUCCEED; } else { // must be BtBondState::BT_BOND_STATE_NONE as BT_BOND_STATE_BONDING case has been @@ -281,10 +287,15 @@ PairingState ToPairingState(uint32_t status, uint32_t bond_state, int32_t fail_r // TODO(b/287392029): Translate cases of bond cancelled into PairingState:PAIR_FAIL_CANCELLED - // When both status and fail reason are provided and disagree with each other, overwrite status with the fail reason - // as fail reason is generated closer to the HCI and provides a more accurate description. - if (status) pairing_state = StatusToPairingState(status); - if (fail_reason) pairing_state = FailReasonToPairingState(fail_reason); + // When both status and fail reason are provided and disagree with each other, overwrite status + // with the fail reason as fail reason is generated closer to the HCI and provides a more accurate + // description. + if (status) { + pairing_state = StatusToPairingState(status); + } + if (fail_reason) { + pairing_state = FailReasonToPairingState(fail_reason); + } return pairing_state; } @@ -332,7 +343,8 @@ int64_t StatusToProfileConnectionState(uint32_t status, StateChangeType type) { state = (int64_t)MetricProfileDisconnectionStatus::PROFILE_DISCONN_STATE_BUSY_DISCONNECTING; break; case BtStatus::BT_STATUS_DONE: - state = (int64_t)MetricProfileDisconnectionStatus::PROFILE_DISCONN_STATE_ALREADY_DISCONNECTED; + state = (int64_t) + MetricProfileDisconnectionStatus::PROFILE_DISCONN_STATE_ALREADY_DISCONNECTED; break; case BtStatus::BT_STATUS_UNSUPPORTED: state = (int64_t)MetricProfileDisconnectionStatus::PROFILE_DISCONN_STATE_UNKNOWN_ERROR; @@ -341,13 +353,15 @@ int64_t StatusToProfileConnectionState(uint32_t status, StateChangeType type) { state = (int64_t)MetricProfileDisconnectionStatus::PROFILE_DISCONN_STATE_INVALID_PARAMS; break; case BtStatus::BT_STATUS_AUTH_FAILURE: - state = (int64_t)MetricProfileDisconnectionStatus::PROFILE_DISCONN_STATE_DISCONNECTION_REFUSED; + state = (int64_t) + MetricProfileDisconnectionStatus::PROFILE_DISCONN_STATE_DISCONNECTION_REFUSED; break; case BtStatus::BT_STATUS_RMT_DEV_DOWN: state = (int64_t)MetricProfileDisconnectionStatus::PROFILE_DISCONN_STATE_UNKNOWN_ERROR; break; case BtStatus::BT_STATUS_AUTH_REJECTED: - state = (int64_t)MetricProfileDisconnectionStatus::PROFILE_DISCONN_STATE_DISCONNECTION_REFUSED; + state = (int64_t) + MetricProfileDisconnectionStatus::PROFILE_DISCONN_STATE_DISCONNECTION_REFUSED; break; case BtStatus::BT_STATUS_FAIL: case BtStatus::BT_STATUS_NOT_READY: @@ -483,10 +497,11 @@ static std::pair ToProfileConnectionState(uint32_t profile, return output; } -ProfileConnectionEvent ToProfileConnectionEvent(std::string addr, uint32_t profile, uint32_t status, uint32_t state) { +ProfileConnectionEvent ToProfileConnectionEvent(std::string addr, uint32_t profile, uint32_t status, + uint32_t state) { ProfileConnectionEvent event; - // A map stores the pending StateChangeType used to match a (dis)connection event with unknown type. - // map, type> + // A map stores the pending StateChangeType used to match a (dis)connection event with unknown + // type. map, type> static std::map, StateChangeType> pending_type; auto profile_state_pair = ToProfileConnectionState(profile, state); @@ -506,10 +521,10 @@ ProfileConnectionEvent ToProfileConnectionEvent(std::string addr, uint32_t profi break; case ProfilesConnectionState::DISCONNECTED: event.type = pending_type.find(key) != pending_type.end() - ? (int64_t)pending_type[key] - : (int64_t)StateChangeType::STATE_CHANGE_TYPE_DISCONNECT; - // If the profile successfully disconnected for a connect intent, i.e., a connection is attempted but received a - // disconnection state update. Report this as an unknown error. + ? (int64_t)pending_type[key] + : (int64_t)StateChangeType::STATE_CHANGE_TYPE_DISCONNECT; + // If the profile successfully disconnected for a connect intent, i.e., a connection is + // attempted but received a disconnection state update. Report this as an unknown error. if (StateChangeType::STATE_CHANGE_TYPE_CONNECT == (StateChangeType)event.type && BtStatus::BT_STATUS_SUCCESS == (BtStatus)status) { event.state = (int64_t)MetricProfileConnectionStatus::PROFILE_CONN_STATE_UNKNOWN_ERROR; @@ -600,8 +615,9 @@ void PendingAclConnectAttemptEvent(std::string addr, int64_t time, uint32_t acl_ pending_acl_events[addr] = std::make_pair(acl_state, time); } -AclConnectionEvent ToAclConnectionEvent( - std::string addr, int64_t time, uint32_t acl_status, uint32_t acl_state, uint32_t direction, uint32_t hci_reason) { +AclConnectionEvent ToAclConnectionEvent(std::string addr, int64_t time, uint32_t acl_status, + uint32_t acl_state, uint32_t direction, + uint32_t hci_reason) { AclConnectionEvent event; if (pending_acl_events.find(addr) == pending_acl_events.end()) { @@ -680,12 +696,13 @@ static MetricTransportType GetChipsetInfoTransport(void) { } module_name = module_realpath.BaseName().value(); - if (base::MatchPattern(module_name, "*usb*")) + if (base::MatchPattern(module_name, "*usb*")) { transport = MetricTransportType::TRANSPORT_TYPE_USB; - else if (base::MatchPattern(module_name, "*uart*")) + } else if (base::MatchPattern(module_name, "*uart*")) { transport = MetricTransportType::TRANSPORT_TYPE_UART; - else if (base::MatchPattern(module_name, "*sdio*")) + } else if (base::MatchPattern(module_name, "*sdio*")) { transport = MetricTransportType::TRANSPORT_TYPE_SDIO; + } return transport; } diff --git a/system/gd/metrics/chromeos/metrics_event.h b/system/gd/metrics/chromeos/metrics_event.h index b67ee2c7114..039cf84944b 100644 --- a/system/gd/metrics/chromeos/metrics_event.h +++ b/system/gd/metrics/chromeos/metrics_event.h @@ -26,9 +26,9 @@ namespace metrics { enum class AdapterState : int64_t { OFF = 0, ON = 1 }; // ENUM definition for device/connection type that in sync with ChromeOS structured metrics -// BluetoothPairingStateChanged/DeviceType and BlueZ metrics_conn_type. Note this is a non-optimal ENUM design that -// mixed the connection transport type with the device type. The connection can only be LE or Classic, but the device -// type can also be Dual. +// BluetoothPairingStateChanged/DeviceType and BlueZ metrics_conn_type. Note this is a non-optimal +// ENUM design that mixed the connection transport type with the device type. The connection can +// only be LE or Classic, but the device type can also be Dual. enum class ConnectionType : int64_t { CONN_TYPE_UNKNOWN = 0, CONN_TYPE_BREDR = 1, @@ -167,8 +167,12 @@ enum class MetricAclDisconnectionStatus : int64_t { ACL_DISCONN_STATE_UNKNOWN = 6, }; -// A binary ENUM defines the metrics event is logged for: either for an attempt to connect or to disconnect. -enum class StateChangeType : int64_t { STATE_CHANGE_TYPE_DISCONNECT = 0, STATE_CHANGE_TYPE_CONNECT = 1 }; +// A binary ENUM defines the metrics event is logged for: either for an attempt to connect or to +// disconnect. +enum class StateChangeType : int64_t { + STATE_CHANGE_TYPE_DISCONNECT = 0, + STATE_CHANGE_TYPE_CONNECT = 1 +}; // ENUM definition for ACL disconnection status that in sync with ChromeOS structured metrics // MetricAclConnectionDirection and BlueZ's metrics_acl_connection_direction. @@ -215,11 +219,13 @@ SuspendIdState ToSuspendIdState(uint32_t state); // Convert topshim::btif::BtDeviceType to ConnectionType ConnectionType ToPairingDeviceType(std::string addr, uint32_t device_type); -// Convert topshim::btif::bond_state info (status, addr, bond_state, and fail_reason) to PairingState +// Convert topshim::btif::bond_state info (status, addr, bond_state, and fail_reason) to +// PairingState PairingState ToPairingState(uint32_t status, uint32_t bond_state, int32_t fail_reason); // Convert Floss profile connection info to ProfileConnectionEvent -ProfileConnectionEvent ToProfileConnectionEvent(std::string addr, uint32_t profile, uint32_t status, uint32_t state); +ProfileConnectionEvent ToProfileConnectionEvent(std::string addr, uint32_t profile, uint32_t status, + uint32_t state); // A struct holds the parsed ACL connection event. struct AclConnectionEvent { @@ -235,8 +241,9 @@ struct AclConnectionEvent { void PendingAclConnectAttemptEvent(std::string addr, int64_t time, uint32_t acl_state); // Convert Floss ACL connection info to AclConnectionEvent. -AclConnectionEvent ToAclConnectionEvent( - std::string addr, int64_t time, uint32_t acl_status, uint32_t acl_state, uint32_t direction, uint32_t hci_reason); +AclConnectionEvent ToAclConnectionEvent(std::string addr, int64_t time, uint32_t acl_status, + uint32_t acl_state, uint32_t direction, + uint32_t hci_reason); // A struct to hold the chipset info. struct MetricsChipsetInfo { diff --git a/system/gd/metrics/counter_metrics.cc b/system/gd/metrics/counter_metrics.cc index 5b82b099b50..0155eb1bd09 100644 --- a/system/gd/metrics/counter_metrics.cc +++ b/system/gd/metrics/counter_metrics.cc @@ -26,7 +26,7 @@ namespace bluetooth { namespace metrics { -const int COUNTER_METRICS_PERDIOD_MINUTES = 360; // Drain counters every 6 hours +const int COUNTER_METRICS_PERDIOD_MINUTES = 360; // Drain counters every 6 hours const ModuleFactory CounterMetrics::Factory = ModuleFactory([]() { return new CounterMetrics(); }); @@ -35,9 +35,8 @@ void CounterMetrics::ListDependencies(ModuleList* /* list */) const {} void CounterMetrics::Start() { alarm_ = std::make_unique(GetHandler()); alarm_->Schedule( - common::Bind(&CounterMetrics::DrainBufferedCounters, - bluetooth::common::Unretained(this)), - std::chrono::minutes(COUNTER_METRICS_PERDIOD_MINUTES)); + common::Bind(&CounterMetrics::DrainBufferedCounters, bluetooth::common::Unretained(this)), + std::chrono::minutes(COUNTER_METRICS_PERDIOD_MINUTES)); log::info("Counter metrics initialized"); initialized_ = true; } @@ -89,7 +88,7 @@ bool CounterMetrics::Count(int32_t key, int64_t count) { void CounterMetrics::DrainBufferedCounters() { if (!IsInitialized()) { log::warn("Counter metrics isn't initialized"); - return ; + return; } std::lock_guard lock(mutex_); log::info("Draining buffered counters"); diff --git a/system/gd/metrics/counter_metrics.h b/system/gd/metrics/counter_metrics.h index 8148e63e6d7..69dd5df043a 100644 --- a/system/gd/metrics/counter_metrics.h +++ b/system/gd/metrics/counter_metrics.h @@ -24,28 +24,24 @@ namespace bluetooth { namespace metrics { class CounterMetrics : public bluetooth::Module { - public: +public: bool CacheCount(int32_t key, int64_t value); virtual bool Count(int32_t key, int64_t count); void Stop() override; static const ModuleFactory Factory; - protected: +protected: void ListDependencies(ModuleList* list) const override; void Start() override; - std::string ToString() const override { - return std::string("BluetoothCounterMetrics"); - } + std::string ToString() const override { return std::string("BluetoothCounterMetrics"); } void DrainBufferedCounters(); - virtual bool IsInitialized() { - return initialized_; - } + virtual bool IsInitialized() { return initialized_; } - private: +private: std::unordered_map counters_; mutable std::mutex mutex_; std::unique_ptr alarm_; - bool initialized_ {false}; + bool initialized_{false}; }; } // namespace metrics diff --git a/system/gd/metrics/counter_metrics_unittest.cc b/system/gd/metrics/counter_metrics_unittest.cc index f09a6d9e906..cbaf7f00721 100644 --- a/system/gd/metrics/counter_metrics_unittest.cc +++ b/system/gd/metrics/counter_metrics_unittest.cc @@ -25,21 +25,18 @@ namespace metrics { namespace { class CounterMetricsTest : public ::testing::Test { - public: +public: class TestableCounterMetrics : public CounterMetrics { - public: - void DrainBuffer() { - DrainBufferedCounters(); - } + public: + void DrainBuffer() { DrainBufferedCounters(); } std::unordered_map test_counters_; - private: + + private: bool Count(int32_t key, int64_t count) override { test_counters_[key] = count; return true; } - bool IsInitialized() override { - return true; - } + bool IsInitialized() override { return true; } }; TestableCounterMetrics testable_counter_metrics_; }; diff --git a/system/gd/metrics/linux/metrics.cc b/system/gd/metrics/linux/metrics.cc index 9792edf7e43..450d7bc8c28 100644 --- a/system/gd/metrics/linux/metrics.cc +++ b/system/gd/metrics/linux/metrics.cc @@ -24,34 +24,25 @@ void LogMetricsAdapterStateChanged(uint32_t state) {} void LogMetricsBondCreateAttempt(RawAddress* addr, uint32_t device_type) {} -void LogMetricsBondStateChanged( - RawAddress* addr, uint32_t device_type, uint32_t status, uint32_t bond_state, int32_t fail_reason) {} +void LogMetricsBondStateChanged(RawAddress* addr, uint32_t device_type, uint32_t status, + uint32_t bond_state, int32_t fail_reason) {} -void LogMetricsDeviceInfoReport( - RawAddress* addr, - uint32_t device_type, - uint32_t class_of_device, - uint32_t appearance, - uint32_t vendor_id, - uint32_t vendor_id_src, - uint32_t product_id, - uint32_t version) {} +void LogMetricsDeviceInfoReport(RawAddress* addr, uint32_t device_type, uint32_t class_of_device, + uint32_t appearance, uint32_t vendor_id, uint32_t vendor_id_src, + uint32_t product_id, uint32_t version) {} -void LogMetricsProfileConnectionStateChanged(RawAddress* addr, uint32_t profile, uint32_t status, uint32_t state) {} +void LogMetricsProfileConnectionStateChanged(RawAddress* addr, uint32_t profile, uint32_t status, + uint32_t state) {} void LogMetricsAclConnectAttempt(RawAddress* addr, uint32_t acl_state) {} -void LogMetricsAclConnectionStateChanged( - RawAddress* addr, - uint32_t transport, - uint32_t status, - uint32_t acl_state, - uint32_t direction, - uint32_t hci_reason) {} +void LogMetricsAclConnectionStateChanged(RawAddress* addr, uint32_t transport, uint32_t status, + uint32_t acl_state, uint32_t direction, + uint32_t hci_reason) {} void LogMetricsChipsetInfoReport() {} -void LogMetricsSuspendIdState(uint32_t state){}; +void LogMetricsSuspendIdState(uint32_t state) {} } // namespace metrics } // namespace bluetooth diff --git a/system/gd/metrics/metrics.h b/system/gd/metrics/metrics.h index 16b95a1c655..6b2dda8c988 100644 --- a/system/gd/metrics/metrics.h +++ b/system/gd/metrics/metrics.h @@ -16,6 +16,7 @@ #pragma once #include + #include "types/raw_address.h" namespace bluetooth { @@ -23,21 +24,17 @@ namespace metrics { void LogMetricsAdapterStateChanged(uint32_t state); void LogMetricsBondCreateAttempt(RawAddress* addr, uint32_t device_type); -void LogMetricsBondStateChanged( - RawAddress* addr, uint32_t device_type, uint32_t status, uint32_t bond_state, int32_t fail_reason); -void LogMetricsDeviceInfoReport( - RawAddress* addr, - uint32_t device_type, - uint32_t class_of_device, - uint32_t appearance, - uint32_t vendor_id, - uint32_t vendor_id_src, - uint32_t product_id, - uint32_t version); -void LogMetricsProfileConnectionStateChanged(RawAddress* addr, uint32_t profile, uint32_t status, uint32_t state); +void LogMetricsBondStateChanged(RawAddress* addr, uint32_t device_type, uint32_t status, + uint32_t bond_state, int32_t fail_reason); +void LogMetricsDeviceInfoReport(RawAddress* addr, uint32_t device_type, uint32_t class_of_device, + uint32_t appearance, uint32_t vendor_id, uint32_t vendor_id_src, + uint32_t product_id, uint32_t version); +void LogMetricsProfileConnectionStateChanged(RawAddress* addr, uint32_t profile, uint32_t status, + uint32_t state); void LogMetricsAclConnectAttempt(RawAddress* addr, uint32_t acl_state); -void LogMetricsAclConnectionStateChanged( - RawAddress* addr, uint32_t transport, uint32_t status, uint32_t acl_state, uint32_t direction, uint32_t hci_reason); +void LogMetricsAclConnectionStateChanged(RawAddress* addr, uint32_t transport, uint32_t status, + uint32_t acl_state, uint32_t direction, + uint32_t hci_reason); void LogMetricsChipsetInfoReport(); void LogMetricsSuspendIdState(uint32_t state); diff --git a/system/gd/metrics/metrics_state.cc b/system/gd/metrics/metrics_state.cc index afe25296af6..ba68114f019 100644 --- a/system/gd/metrics/metrics_state.cc +++ b/system/gd/metrics/metrics_state.cc @@ -47,11 +47,9 @@ using android::bluetooth::le::LeConnectionType; * */ void LEConnectionMetricState::AddStateChangedEvent( - LeConnectionOriginType origin_type, - LeConnectionType connection_type, - LeConnectionState transaction_state, - std::vector> argument_list) { - + LeConnectionOriginType origin_type, LeConnectionType connection_type, + LeConnectionState transaction_state, + std::vector> argument_list) { ClockTimePoint current_timestamp = std::chrono::high_resolution_clock::now(); state = transaction_state; @@ -83,7 +81,7 @@ void LEConnectionMetricState::AddStateChangedEvent( } case LeConnectionState::STATE_LE_ACL_END: { int acl_status_code_from_args = - GetArgumentTypeFromList(argument_list, os::ArgumentType::ACL_STATUS_CODE); + GetArgumentTypeFromList(argument_list, os::ArgumentType::ACL_STATUS_CODE); acl_status_code = static_cast(acl_status_code_from_args); acl_state = LeAclConnectionState::LE_ACL_SUCCESS; @@ -94,7 +92,7 @@ void LEConnectionMetricState::AddStateChangedEvent( } case LeConnectionState::STATE_LE_ACL_TIMEOUT: { int acl_status_code_from_args = - GetArgumentTypeFromList(argument_list, os::ArgumentType::ACL_STATUS_CODE); + GetArgumentTypeFromList(argument_list, os::ArgumentType::ACL_STATUS_CODE); acl_status_code = static_cast(acl_status_code_from_args); acl_state = LeAclConnectionState::LE_ACL_FAILED; break; @@ -116,13 +114,9 @@ bool LEConnectionMetricState::IsEnded() { acl_state == LeAclConnectionState::LE_ACL_FAILED; } -bool LEConnectionMetricState::IsStarted() { - return state == LeConnectionState::STATE_LE_ACL_START; -} +bool LEConnectionMetricState::IsStarted() { return state == LeConnectionState::STATE_LE_ACL_START; } -bool LEConnectionMetricState::IsCancelled() { - return is_cancelled; -} +bool LEConnectionMetricState::IsCancelled() { return is_cancelled; } // Initialize the LEConnectionMetricsRemoteDevice LEConnectionMetricsRemoteDevice::LEConnectionMetricsRemoteDevice() { @@ -130,7 +124,7 @@ LEConnectionMetricsRemoteDevice::LEConnectionMetricsRemoteDevice() { } LEConnectionMetricsRemoteDevice::LEConnectionMetricsRemoteDevice( - BaseMetricsLoggerModule* baseMetricsLoggerModule) { + BaseMetricsLoggerModule* baseMetricsLoggerModule) { metrics_logger_module = baseMetricsLoggerModule; } @@ -142,8 +136,8 @@ void LEConnectionMetricsRemoteDevice::UploadLEConnectionSession(const hci::Addre session_options.acl_connection_state = it->second->acl_state; session_options.origin_type = it->second->connection_origin_type; session_options.transaction_type = it->second->input_connection_type; - session_options.latency = bluetooth::metrics::get_timedelta_nanos( - it->second->start_timepoint, it->second->end_timepoint); + session_options.latency = bluetooth::metrics::get_timedelta_nanos(it->second->start_timepoint, + it->second->end_timepoint); session_options.remote_address = address; session_options.status = it->second->acl_status_code; // TODO: keep the acl latency the same as the overall latency for now @@ -158,39 +152,35 @@ void LEConnectionMetricsRemoteDevice::UploadLEConnectionSession(const hci::Addre // Implementation of metrics per remote device void LEConnectionMetricsRemoteDevice::AddStateChangedEvent( - const hci::Address& address, - LeConnectionOriginType origin_type, - LeConnectionType connection_type, - LeConnectionState transaction_state, - std::vector> argument_list) { + const hci::Address& address, LeConnectionOriginType origin_type, + LeConnectionType connection_type, LeConnectionState transaction_state, + std::vector> argument_list) { log::info( - "LEConnectionMetricsRemoteDevice: Transaction State {}, Connection Type {}, Origin Type {}", - common::ToHexString(transaction_state), - common::ToHexString(connection_type), - common::ToHexString(origin_type)); + "LEConnectionMetricsRemoteDevice: Transaction State {}, Connection Type {}, Origin Type " + "{}", + common::ToHexString(transaction_state), common::ToHexString(connection_type), + common::ToHexString(origin_type)); std::unique_lock lock(le_connection_metrics_remote_device_guard); if (address.IsEmpty()) { - log::info( - "LEConnectionMetricsRemoteDevice: Empty Address Cancellation {}, {}, {}", - common::ToHexString(transaction_state), - common::ToHexString(connection_type), - common::ToHexString(transaction_state)); + log::info("LEConnectionMetricsRemoteDevice: Empty Address Cancellation {}, {}, {}", + common::ToHexString(transaction_state), common::ToHexString(connection_type), + common::ToHexString(transaction_state)); for (auto& device_metric : device_metrics) { if (device_metric->IsStarted() && transaction_state == LeConnectionState::STATE_LE_ACL_CANCEL) { log::info("LEConnectionMetricsRemoteDevice: Cancellation Begin"); // cancel the connection - device_metric->AddStateChangedEvent( - origin_type, connection_type, transaction_state, argument_list); + device_metric->AddStateChangedEvent(origin_type, connection_type, transaction_state, + argument_list); continue; } if (device_metric->IsCancelled() && transaction_state == LeConnectionState::STATE_LE_ACL_END) { // complete the connection - device_metric->AddStateChangedEvent( - origin_type, connection_type, transaction_state, argument_list); + device_metric->AddStateChangedEvent(origin_type, connection_type, transaction_state, + argument_list); UploadLEConnectionSession(address); continue; } @@ -212,16 +202,15 @@ void LEConnectionMetricsRemoteDevice::AddStateChangedEvent( } } - // MetricsLoggerModule class void MetricsLoggerModule::LogMetricBluetoothLESession( - os::LEConnectionSessionOptions session_options) { + os::LEConnectionSessionOptions session_options) { os::LogMetricBluetoothLEConnection(session_options); } // Instance of Metrics Collector for LEConnectionMetricsRemoteDeviceImpl LEConnectionMetricsRemoteDevice* MetricsCollector::le_connection_metrics_remote_device = - new LEConnectionMetricsRemoteDevice(); + new LEConnectionMetricsRemoteDevice(); LEConnectionMetricsRemoteDevice* MetricsCollector::GetLEConnectionMetricsCollector() { return MetricsCollector::le_connection_metrics_remote_device; diff --git a/system/gd/metrics/metrics_state.h b/system/gd/metrics/metrics_state.h index d8fb9e8be03..60c16066e55 100644 --- a/system/gd/metrics/metrics_state.h +++ b/system/gd/metrics/metrics_state.h @@ -50,21 +50,21 @@ inline int64_t get_timedelta_nanos(const ClockTimePoint& t1, const ClockTimePoin } class BaseMetricsLoggerModule { - public: +public: BaseMetricsLoggerModule() {} virtual void LogMetricBluetoothLESession(os::LEConnectionSessionOptions session_options) = 0; virtual ~BaseMetricsLoggerModule() {} }; class MetricsLoggerModule : public BaseMetricsLoggerModule { - public: +public: MetricsLoggerModule() {} void LogMetricBluetoothLESession(os::LEConnectionSessionOptions session_options); virtual ~MetricsLoggerModule() {} }; class LEConnectionMetricState { - public: +public: hci::Address address; LEConnectionMetricState(const hci::Address address) : address(address) {} LeConnectionState state; @@ -80,30 +80,24 @@ class LEConnectionMetricState { bool IsEnded(); bool IsCancelled(); - void AddStateChangedEvent( - LeConnectionOriginType origin_type, - LeConnectionType connection_type, - LeConnectionState transaction_state, - std::vector> argument_list); - + void AddStateChangedEvent(LeConnectionOriginType origin_type, LeConnectionType connection_type, + LeConnectionState transaction_state, + std::vector> argument_list); }; class LEConnectionMetricsRemoteDevice { - public: +public: LEConnectionMetricsRemoteDevice(); LEConnectionMetricsRemoteDevice(BaseMetricsLoggerModule* baseMetricsLoggerModule); - void AddStateChangedEvent( - const hci::Address& address, - LeConnectionOriginType origin_type, - LeConnectionType connection_type, - LeConnectionState transaction_state, - std::vector> argument_list); + void AddStateChangedEvent(const hci::Address& address, LeConnectionOriginType origin_type, + LeConnectionType connection_type, LeConnectionState transaction_state, + std::vector> argument_list); void UploadLEConnectionSession(const hci::Address& address); - private: +private: mutable std::mutex le_connection_metrics_remote_device_guard; std::vector> device_metrics; std::unordered_map opened_devices; @@ -111,11 +105,11 @@ class LEConnectionMetricsRemoteDevice { }; class MetricsCollector { - public: +public: // getting the LE Connection Metrics Collector static LEConnectionMetricsRemoteDevice* GetLEConnectionMetricsCollector(); - private: +private: static LEConnectionMetricsRemoteDevice* le_connection_metrics_remote_device; }; diff --git a/system/gd/metrics/metrics_state_unittest.cc b/system/gd/metrics/metrics_state_unittest.cc index 435e5c09bb7..4d9876e52bc 100644 --- a/system/gd/metrics/metrics_state_unittest.cc +++ b/system/gd/metrics/metrics_state_unittest.cc @@ -33,14 +33,14 @@ const hci::Address address1 = hci::Address({0x11, 0x22, 0x33, 0x44, 0x55, 0x66}) const hci::Address empty_address = hci::Address::kEmpty; class TestMetricsLoggerModule : public BaseMetricsLoggerModule { - public: +public: TestMetricsLoggerModule() {} void LogMetricBluetoothLESession(os::LEConnectionSessionOptions session_options); virtual ~TestMetricsLoggerModule() {} }; void TestMetricsLoggerModule::LogMetricBluetoothLESession( - os::LEConnectionSessionOptions session_options) { + os::LEConnectionSessionOptions session_options) { le_acl_state = session_options.acl_connection_state; origin_type = session_options.origin_type; connection_type = session_options.transaction_type; @@ -50,16 +50,14 @@ void TestMetricsLoggerModule::LogMetricBluetoothLESession( } class MockMetricsCollector { - public: +public: static LEConnectionMetricsRemoteDevice* GetLEConnectionMetricsCollector(); static LEConnectionMetricsRemoteDevice* le_connection_metrics_remote_device; }; - - LEConnectionMetricsRemoteDevice* MockMetricsCollector::le_connection_metrics_remote_device = - new LEConnectionMetricsRemoteDevice(new TestMetricsLoggerModule()); + new LEConnectionMetricsRemoteDevice(new TestMetricsLoggerModule()); LEConnectionMetricsRemoteDevice* MockMetricsCollector::GetLEConnectionMetricsCollector() { return MockMetricsCollector::le_connection_metrics_remote_device; @@ -69,29 +67,21 @@ namespace { class LEConnectionMetricsRemoteDeviceTest : public ::testing::Test {}; -TEST(LEConnectionMetricsRemoteDeviceTest, Initialize) { - ASSERT_EQ(0, 0); -} +TEST(LEConnectionMetricsRemoteDeviceTest, Initialize) { ASSERT_EQ(0, 0); } TEST(LEConnectionMetricsRemoteDeviceTest, ConnectionSuccess) { auto argument_list = std::vector>(); - argument_list.push_back(std::make_pair( - os::ArgumentType::ACL_STATUS_CODE, - static_cast(android::bluetooth::hci::StatusEnum::STATUS_SUCCESS))); + argument_list.push_back( + std::make_pair(os::ArgumentType::ACL_STATUS_CODE, + static_cast(android::bluetooth::hci::StatusEnum::STATUS_SUCCESS))); MockMetricsCollector::GetLEConnectionMetricsCollector()->AddStateChangedEvent( - address1, - LeConnectionOriginType::ORIGIN_NATIVE, - LeConnectionType::CONNECTION_TYPE_LE_ACL, - LeConnectionState::STATE_LE_ACL_START, - argument_list); + address1, LeConnectionOriginType::ORIGIN_NATIVE, LeConnectionType::CONNECTION_TYPE_LE_ACL, + LeConnectionState::STATE_LE_ACL_START, argument_list); MockMetricsCollector::GetLEConnectionMetricsCollector()->AddStateChangedEvent( - address1, - LeConnectionOriginType::ORIGIN_NATIVE, - LeConnectionType::CONNECTION_TYPE_LE_ACL, - LeConnectionState::STATE_LE_ACL_END, - argument_list); + address1, LeConnectionOriginType::ORIGIN_NATIVE, LeConnectionType::CONNECTION_TYPE_LE_ACL, + LeConnectionState::STATE_LE_ACL_END, argument_list); // assert that these are equal ASSERT_EQ(le_acl_state, LeAclConnectionState::LE_ACL_SUCCESS); ASSERT_EQ(origin_type, LeConnectionOriginType::ORIGIN_NATIVE); @@ -103,22 +93,16 @@ TEST(LEConnectionMetricsRemoteDeviceTest, ConnectionSuccess) { TEST(LEConnectionMetricsRemoteDeviceTest, ConnectionFailed) { auto argument_list = std::vector>(); argument_list.push_back(std::make_pair( - os::ArgumentType::ACL_STATUS_CODE, - static_cast(android::bluetooth::hci::StatusEnum::STATUS_NO_CONNECTION))); + os::ArgumentType::ACL_STATUS_CODE, + static_cast(android::bluetooth::hci::StatusEnum::STATUS_NO_CONNECTION))); MockMetricsCollector::GetLEConnectionMetricsCollector()->AddStateChangedEvent( - address1, - LeConnectionOriginType::ORIGIN_NATIVE, - LeConnectionType::CONNECTION_TYPE_LE_ACL, - LeConnectionState::STATE_LE_ACL_START, - argument_list); + address1, LeConnectionOriginType::ORIGIN_NATIVE, LeConnectionType::CONNECTION_TYPE_LE_ACL, + LeConnectionState::STATE_LE_ACL_START, argument_list); MockMetricsCollector::GetLEConnectionMetricsCollector()->AddStateChangedEvent( - address1, - LeConnectionOriginType::ORIGIN_NATIVE, - LeConnectionType::CONNECTION_TYPE_LE_ACL, - LeConnectionState::STATE_LE_ACL_END, - argument_list); + address1, LeConnectionOriginType::ORIGIN_NATIVE, LeConnectionType::CONNECTION_TYPE_LE_ACL, + LeConnectionState::STATE_LE_ACL_END, argument_list); // assert that these are equal ASSERT_EQ(le_acl_state, LeAclConnectionState::LE_ACL_FAILED); ASSERT_EQ(origin_type, LeConnectionOriginType::ORIGIN_NATIVE); @@ -131,32 +115,24 @@ TEST(LEConnectionMetricsRemoteDeviceTest, Cancellation) { auto argument_list = std::vector>(); auto no_connection_argument_list = std::vector>(); no_connection_argument_list.push_back(std::make_pair( - os::ArgumentType::ACL_STATUS_CODE, - static_cast(android::bluetooth::hci::StatusEnum::STATUS_NO_CONNECTION))); + os::ArgumentType::ACL_STATUS_CODE, + static_cast(android::bluetooth::hci::StatusEnum::STATUS_NO_CONNECTION))); // Start of the LE-ACL Connection MockMetricsCollector::GetLEConnectionMetricsCollector()->AddStateChangedEvent( - address1, - LeConnectionOriginType::ORIGIN_NATIVE, - LeConnectionType::CONNECTION_TYPE_LE_ACL, - LeConnectionState::STATE_LE_ACL_START, - argument_list); + address1, LeConnectionOriginType::ORIGIN_NATIVE, LeConnectionType::CONNECTION_TYPE_LE_ACL, + LeConnectionState::STATE_LE_ACL_START, argument_list); // Cancellation of the LE-ACL Connection MockMetricsCollector::GetLEConnectionMetricsCollector()->AddStateChangedEvent( - empty_address, - LeConnectionOriginType::ORIGIN_NATIVE, - LeConnectionType::CONNECTION_TYPE_LE_ACL, - LeConnectionState::STATE_LE_ACL_CANCEL, - argument_list); + empty_address, LeConnectionOriginType::ORIGIN_NATIVE, + LeConnectionType::CONNECTION_TYPE_LE_ACL, LeConnectionState::STATE_LE_ACL_CANCEL, + argument_list); // Ending of the LE-ACL Connection MockMetricsCollector::GetLEConnectionMetricsCollector()->AddStateChangedEvent( - address1, - LeConnectionOriginType::ORIGIN_NATIVE, - LeConnectionType::CONNECTION_TYPE_LE_ACL, - LeConnectionState::STATE_LE_ACL_END, - no_connection_argument_list); + address1, LeConnectionOriginType::ORIGIN_NATIVE, LeConnectionType::CONNECTION_TYPE_LE_ACL, + LeConnectionState::STATE_LE_ACL_END, no_connection_argument_list); ASSERT_EQ(le_acl_state, LeAclConnectionState::LE_ACL_FAILED); ASSERT_EQ(origin_type, LeConnectionOriginType::ORIGIN_NATIVE); @@ -170,19 +146,13 @@ TEST(LEConnectionMetricsRemoteDeviceTest, Timeout) { // Start of the LE-ACL Connection MockMetricsCollector::GetLEConnectionMetricsCollector()->AddStateChangedEvent( - address1, - LeConnectionOriginType::ORIGIN_NATIVE, - LeConnectionType::CONNECTION_TYPE_LE_ACL, - LeConnectionState::STATE_LE_ACL_START, - argument_list); + address1, LeConnectionOriginType::ORIGIN_NATIVE, LeConnectionType::CONNECTION_TYPE_LE_ACL, + LeConnectionState::STATE_LE_ACL_START, argument_list); // Timeout of the LE-ACL Connection MockMetricsCollector::GetLEConnectionMetricsCollector()->AddStateChangedEvent( - address1, - LeConnectionOriginType::ORIGIN_NATIVE, - LeConnectionType::CONNECTION_TYPE_LE_ACL, - LeConnectionState::STATE_LE_ACL_TIMEOUT, - argument_list); + address1, LeConnectionOriginType::ORIGIN_NATIVE, LeConnectionType::CONNECTION_TYPE_LE_ACL, + LeConnectionState::STATE_LE_ACL_TIMEOUT, argument_list); ASSERT_EQ(le_acl_state, LeAclConnectionState::LE_ACL_FAILED); ASSERT_EQ(origin_type, LeConnectionOriginType::ORIGIN_NATIVE); diff --git a/system/gd/metrics/utils.cc b/system/gd/metrics/utils.cc index bf970ce8c0b..77e7df37881 100644 --- a/system/gd/metrics/utils.cc +++ b/system/gd/metrics/utils.cc @@ -35,8 +35,8 @@ bool GetBootId(std::string* boot_id) { return true; } -int GetArgumentTypeFromList( - std::vector>& argument_list, os::ArgumentType argumentType) { +int GetArgumentTypeFromList(std::vector>& argument_list, + os::ArgumentType argumentType) { for (std::pair argumentPair : argument_list) { if (argumentPair.first == argumentType) { return argumentPair.second; @@ -46,7 +46,7 @@ int GetArgumentTypeFromList( } os::LeConnectionType GetLeConnectionTypeFromCID(int fixed_cid) { - switch(fixed_cid) { + switch (fixed_cid) { case 3: { return os::LeConnectionType::CONNECTION_TYPE_L2CAP_FIXED_CHNL_AMP; } @@ -68,7 +68,5 @@ os::LeConnectionType GetLeConnectionTypeFromCID(int fixed_cid) { } } - - } // namespace metrics } // namespace bluetooth diff --git a/system/gd/metrics/utils.h b/system/gd/metrics/utils.h index 03a645c245f..cb686c533ec 100644 --- a/system/gd/metrics/utils.h +++ b/system/gd/metrics/utils.h @@ -25,8 +25,8 @@ namespace bluetooth { namespace metrics { bool GetBootId(std::string* boot_id); -int GetArgumentTypeFromList( - std::vector>& argument_list, os::ArgumentType argumentType); - os::LeConnectionType GetLeConnectionTypeFromCID(int fixed_cid); +int GetArgumentTypeFromList(std::vector>& argument_list, + os::ArgumentType argumentType); +os::LeConnectionType GetLeConnectionTypeFromCID(int fixed_cid); } // namespace metrics } // namespace bluetooth diff --git a/system/gd/module.cc b/system/gd/module.cc index ed8575babeb..1545f596e2c 100644 --- a/system/gd/module.cc +++ b/system/gd/module.cc @@ -28,17 +28,14 @@ namespace bluetooth { constexpr std::chrono::milliseconds kModuleStopTimeout = std::chrono::milliseconds(2000); -ModuleFactory::ModuleFactory(std::function ctor) : ctor_(ctor) { -} +ModuleFactory::ModuleFactory(std::function ctor) : ctor_(ctor) {} Handler* Module::GetHandler() const { log::assert_that(handler_ != nullptr, "Can't get handler when it's not started"); return handler_; } -const ModuleRegistry* Module::GetModuleRegistry() const { - return registry_; -} +const ModuleRegistry* Module::GetModuleRegistry() const { return registry_; } Module* Module::GetDependency(const ModuleFactory* module) const { for (auto& dependency : dependencies_.list_) { @@ -51,7 +48,7 @@ Module* Module::GetDependency(const ModuleFactory* module) const { } bluetooth::DumpsysDataFinisher EmptyDumpsysDataFinisher = - [](bluetooth::DumpsysDataBuilder* /* dumpsys_data_builder */) {}; + [](bluetooth::DumpsysDataBuilder* /* dumpsys_data_builder */) {}; DumpsysDataFinisher Module::GetDumpsysData(flatbuffers::FlatBufferBuilder* /* builder */) const { return EmptyDumpsysDataFinisher; @@ -59,9 +56,8 @@ DumpsysDataFinisher Module::GetDumpsysData(flatbuffers::FlatBufferBuilder* /* bu Module* ModuleRegistry::Get(const ModuleFactory* module) const { auto instance = started_modules_.find(module); - log::assert_that( - instance != started_modules_.end(), - "Request for module not started up, maybe not in Start(ModuleList)?"); + log::assert_that(instance != started_modules_.end(), + "Request for module not started up, maybe not in Start(ModuleList)?"); return instance->second; } @@ -105,11 +101,12 @@ Module* ModuleRegistry::Start(const ModuleFactory* module, Thread* thread) { } void ModuleRegistry::StopAll() { - // Since modules were brought up in dependency order, it is safe to tear down by going in reverse order. + // Since modules were brought up in dependency order, it is safe to tear down by going in reverse + // order. for (auto it = start_order_.rbegin(); it != start_order_.rend(); it++) { auto instance = started_modules_.find(*it); - log::assert_that( - instance != started_modules_.end(), "assert failed: instance != started_modules_.end()"); + log::assert_that(instance != started_modules_.end(), + "assert failed: instance != started_modules_.end()"); last_instance_ = "stopping " + instance->second->ToString(); // Clear the handler before stopping the module to allow it to shut down gracefully. @@ -121,8 +118,8 @@ void ModuleRegistry::StopAll() { } for (auto it = start_order_.rbegin(); it != start_order_.rend(); it++) { auto instance = started_modules_.find(*it); - log::assert_that( - instance != started_modules_.end(), "assert failed: instance != started_modules_.end()"); + log::assert_that(instance != started_modules_.end(), + "assert failed: instance != started_modules_.end()"); delete instance->second->handler_; delete instance->second; started_modules_.erase(instance); diff --git a/system/gd/module.h b/system/gd/module.h index 8101f8fdd75..14c81ccaf4d 100644 --- a/system/gd/module.h +++ b/system/gd/module.h @@ -42,32 +42,30 @@ class TestModuleRegistry; class FuzzTestModuleRegistry; class ModuleFactory { - friend ModuleRegistry; - friend FuzzTestModuleRegistry; + friend ModuleRegistry; + friend FuzzTestModuleRegistry; public: - ModuleFactory(std::function ctor); + ModuleFactory(std::function ctor); private: - std::function ctor_; + std::function ctor_; }; class ModuleList { - friend Module; - friend ModuleRegistry; + friend Module; + friend ModuleRegistry; public: - template - void add() { - list_.push_back(&T::Factory); - } + template + void add() { + list_.push_back(&T::Factory); + } - // Return the number of modules in this list - size_t NumModules() const { - return list_.size(); - } + // Return the number of modules in this list + size_t NumModules() const { return list_.size(); } - private: +private: std::vector list_; }; @@ -88,10 +86,10 @@ class Module { friend ModuleRegistry; friend TestModuleRegistry; - public: +public: virtual ~Module() = default; - protected: +protected: // Populate the provided list with modules that must start before yours virtual void ListDependencies(ModuleList* list) const = 0; @@ -125,7 +123,7 @@ class Module { virtual DumpsysDataFinisher GetDumpsysData(flatbuffers::FlatBufferBuilder* builder) const; - private: +private: Module* GetDependency(const ModuleFactory* module) const; ::bluetooth::os::Handler* handler_ = nullptr; @@ -134,10 +132,11 @@ class Module { }; class ModuleRegistry { - friend Module; - friend ModuleDumper; - friend class StackManager; - public: + friend Module; + friend ModuleDumper; + friend class StackManager; + +public: template bool IsStarted() const { return IsStarted(&T::Factory); @@ -159,7 +158,7 @@ class ModuleRegistry { // Stop all running modules in reverse order of start void StopAll(); - protected: +protected: Module* Get(const ModuleFactory* module) const; void set_registry_and_handler(Module* instance, ::bluetooth::os::Thread* thread) const; @@ -172,7 +171,7 @@ class ModuleRegistry { }; class TestModuleRegistry : public ModuleRegistry { - public: +public: void InjectTestModule(const ModuleFactory* module, Module* instance) { start_order_.push_back(module); started_modules_[module] = instance; @@ -180,9 +179,7 @@ class TestModuleRegistry : public ModuleRegistry { instance->Start(); } - Module* GetModuleUnderTest(const ModuleFactory* module) const { - return Get(module); - } + Module* GetModuleUnderTest(const ModuleFactory* module) const { return Get(module); } template T* GetModuleUnderTest() const { @@ -193,11 +190,10 @@ class TestModuleRegistry : public ModuleRegistry { return GetModuleHandler(module); } - os::Thread& GetTestThread() { - return test_thread; - } + os::Thread& GetTestThread() { return test_thread; } - bool SynchronizeModuleHandler(const ModuleFactory* module, std::chrono::milliseconds timeout) const { + bool SynchronizeModuleHandler(const ModuleFactory* module, + std::chrono::milliseconds timeout) const { return SynchronizeHandler(GetTestModuleHandler(module), timeout); } @@ -208,12 +204,12 @@ class TestModuleRegistry : public ModuleRegistry { return future.wait_for(timeout) == std::future_status::ready; } - private: +private: os::Thread test_thread{"test_thread", os::Thread::Priority::NORMAL}; }; class FuzzTestModuleRegistry : public TestModuleRegistry { - public: +public: template T* Inject(const ModuleFactory* overriding) { Module* instance = T::Factory.ctor_(); diff --git a/system/gd/module_dumper.cc b/system/gd/module_dumper.cc index 7cff2189550..9e133dfe90c 100644 --- a/system/gd/module_dumper.cc +++ b/system/gd/module_dumper.cc @@ -38,10 +38,9 @@ void ModuleDumper::DumpState(std::string* output, std::ostringstream& /*oss*/) c init_flags_builder.add_title(builder.CreateString("----- Init Flags -----")); std::vector> flags; for (const auto& flag : common::init_flags::dump()) { - flags.push_back(common::CreateInitFlagValue( - builder, - builder.CreateString(std::string(flag.flag)), - builder.CreateString(std::string(flag.value)))); + flags.push_back(common::CreateInitFlagValue(builder, + builder.CreateString(std::string(flag.flag)), + builder.CreateString(std::string(flag.value)))); } init_flags_builder.add_values(builder.CreateVector(flags)); auto init_flags_offset = init_flags_builder.Finish(); @@ -52,9 +51,8 @@ void ModuleDumper::DumpState(std::string* output, std::ostringstream& /*oss*/) c for (auto it = module_registry_.start_order_.rbegin(); it != module_registry_.start_order_.rend(); it++) { auto instance = module_registry_.started_modules_.find(*it); - log::assert_that( - instance != module_registry_.started_modules_.end(), - "assert failed: instance != module_registry_.started_modules_.end()"); + log::assert_that(instance != module_registry_.started_modules_.end(), + "assert failed: instance != module_registry_.started_modules_.end()"); log::verbose("Starting dumpsys module:{}", instance->second->ToString()); queue.push(instance->second->GetDumpsysData(&builder)); log::verbose("Finished dumpsys module:{}", instance->second->ToString()); diff --git a/system/gd/module_dumper.h b/system/gd/module_dumper.h index 44dc84c321b..d1953a224da 100644 --- a/system/gd/module_dumper.h +++ b/system/gd/module_dumper.h @@ -26,12 +26,12 @@ namespace bluetooth { class ModuleRegistry; class ModuleDumper { - public: +public: ModuleDumper(int /*fd*/, const ModuleRegistry& module_registry, const char* title) : module_registry_(module_registry), title_(title) {} void DumpState(std::string* output, std::ostringstream& oss) const; - private: +private: const ModuleRegistry& module_registry_; const std::string title_; }; diff --git a/system/gd/module_gdx_unittest.cc b/system/gd/module_gdx_unittest.cc index 7e7cf46f12b..76eefd86100 100644 --- a/system/gd/module_gdx_unittest.cc +++ b/system/gd/module_gdx_unittest.cc @@ -60,18 +60,18 @@ struct TestGdxModule::PrivateImpl : public ModuleMainloop, public ModuleJniloop private_impl_promise.set_value(base::PlatformThread::CurrentId()); } - void privateCallableRepostOnMainMethod( - std::shared_ptr ptr, int a, double b, char c) { + void privateCallableRepostOnMainMethod(std::shared_ptr ptr, int a, + double b, char c) { PostMethodOnMain(ptr, &PrivateImpl::repostMethodTest, a, b, c); } - void privateCallableRepostOnJniMethod( - std::shared_ptr ptr, int a, double b, char c) { + void privateCallableRepostOnJniMethod(std::shared_ptr ptr, int a, + double b, char c) { PostMethodOnJni(ptr, &PrivateImpl::repostMethodTest, a, b, c); } - void privateCallableRecursiveOnMainMethod( - std::shared_ptr ptr, int depth, double b, char c) { + void privateCallableRecursiveOnMainMethod(std::shared_ptr ptr, + int depth, double b, char c) { if (depth > kMaxTestGdxModuleRecurseDepth) { private_impl_promise.set_value(base::PlatformThread::CurrentId()); return; @@ -79,8 +79,8 @@ struct TestGdxModule::PrivateImpl : public ModuleMainloop, public ModuleJniloop PostMethodOnMain(ptr, &PrivateImpl::privateCallableRecursiveOnMainMethod, ptr, depth + 1, b, c); } - void privateCallableRecursiveOnJniMethod( - std::shared_ptr ptr, int depth, double b, char c) { + void privateCallableRecursiveOnJniMethod(std::shared_ptr ptr, + int depth, double b, char c) { if (depth > kMaxTestGdxModuleRecurseDepth) { private_impl_promise.set_value(base::PlatformThread::CurrentId()); return; @@ -120,8 +120,8 @@ void TestGdxModule::call_on_main(int loop_tid, int a, int b, int c) { void TestGdxModule::call_on_main_repost(int loop_tid, int a, int b, int c) { private_impl_promise = std::promise(); auto future = private_impl_promise.get_future(); - PostMethodOnMain( - pimpl_, &TestGdxModule::PrivateImpl::privateCallableRepostOnMainMethod, pimpl_, a, b, c); + PostMethodOnMain(pimpl_, &TestGdxModule::PrivateImpl::privateCallableRepostOnMainMethod, pimpl_, + a, b, c); ASSERT_EQ(future.wait_for(std::chrono::seconds(3)), std::future_status::ready); ASSERT_EQ(future.get(), loop_tid); } @@ -130,13 +130,8 @@ void TestGdxModule::call_on_main_repost(int loop_tid, int a, int b, int c) { void TestGdxModule::call_on_main_recurse(int loop_tid, int depth, int b, int c) { private_impl_promise = std::promise(); auto future = private_impl_promise.get_future(); - PostMethodOnMain( - pimpl_, - &TestGdxModule::PrivateImpl::privateCallableRecursiveOnMainMethod, - pimpl_, - depth, - b, - c); + PostMethodOnMain(pimpl_, &TestGdxModule::PrivateImpl::privateCallableRecursiveOnMainMethod, + pimpl_, depth, b, c); ASSERT_EQ(future.wait_for(std::chrono::seconds(3)), std::future_status::ready); ASSERT_EQ(future.get(), loop_tid); } @@ -163,8 +158,8 @@ void TestGdxModule::call_on_jni(int loop_tid, int a, int b, int c) { void TestGdxModule::call_on_jni_repost(int loop_tid, int a, int b, int c) { private_impl_promise = std::promise(); auto future = private_impl_promise.get_future(); - PostMethodOnJni( - pimpl_, &TestGdxModule::PrivateImpl::privateCallableRepostOnJniMethod, pimpl_, a, b, c); + PostMethodOnJni(pimpl_, &TestGdxModule::PrivateImpl::privateCallableRepostOnJniMethod, pimpl_, a, + b, c); ASSERT_EQ(future.wait_for(std::chrono::seconds(3)), std::future_status::ready); ASSERT_EQ(future.get(), loop_tid); } @@ -173,13 +168,8 @@ void TestGdxModule::call_on_jni_repost(int loop_tid, int a, int b, int c) { void TestGdxModule::call_on_jni_recurse(int loop_tid, int depth, int b, int c) { private_impl_promise = std::promise(); auto future = private_impl_promise.get_future(); - PostMethodOnJni( - pimpl_, - &TestGdxModule::PrivateImpl::privateCallableRecursiveOnJniMethod, - pimpl_, - depth, - b, - c); + PostMethodOnJni(pimpl_, &TestGdxModule::PrivateImpl::privateCallableRecursiveOnJniMethod, pimpl_, + depth, b, c); ASSERT_EQ(future.wait_for(std::chrono::seconds(3)), std::future_status::ready); ASSERT_EQ(future.get(), loop_tid); } @@ -187,9 +177,7 @@ void TestGdxModule::protected_method(int /* a */, int /* b */, int /* c */) { protected_method_promise.set_value(base::PlatformThread::CurrentId()); } -bool TestGdxModule::IsStarted() const { - return pimpl_ != nullptr; -} +bool TestGdxModule::IsStarted() const { return pimpl_ != nullptr; } void TestGdxModule::Start() { ASSERT_FALSE(IsStarted()); @@ -201,12 +189,10 @@ void TestGdxModule::Stop() { pimpl_.reset(); } -std::string TestGdxModule::ToString() const { - return "TestGdxModule"; -} +std::string TestGdxModule::ToString() const { return "TestGdxModule"; } const bluetooth::ModuleFactory TestGdxModule::Factory = - bluetooth::ModuleFactory([]() { return new TestGdxModule(); }); + bluetooth::ModuleFactory([]() { return new TestGdxModule(); }); void TestGdxModule::set_callback(common::ContextualCallback callback) { call_many_ = callback; @@ -217,21 +203,15 @@ void TestGdxModule::set_once_callback(common::ContextualOnceCallbackPost(common::BindOnce( - [](common::ContextualCallback callback, std::string message) { - callback(message); - }, - call_many_, - message)); + GetHandler()->Post(common::BindOnce([](common::ContextualCallback callback, + std::string message) { callback(message); }, + call_many_, message)); } void TestGdxModule::call_once_callback_on_handler(std::string message) { - GetHandler()->Post(common::BindOnce( - [](common::ContextualOnceCallback callback, std::string message) { - callback(message); - }, - std::move(call_once_), - message)); + GetHandler()->Post(common::BindOnce([](common::ContextualOnceCallback callback, + std::string message) { callback(message); }, + std::move(call_once_), message)); } void TestGdxModule::call_callback_on_main(std::string message) { @@ -254,7 +234,7 @@ void TestGdxModule::call_once_callback_on_jni(std::string message) { // Module GDx Testing Below // class ModuleGdxTest : public ::testing::Test { - protected: +protected: void SetUp() override { test_framework_tid_ = base::PlatformThread::CurrentId(); module_ = new TestGdxModule(); @@ -276,14 +256,14 @@ class ModuleGdxTest : public ::testing::Test { std::future future = promise.get_future(); post_on_bt_main([&promise]() { promise.set_value(); }); future.wait_for(std::chrono::milliseconds(sync_timeout_in_ms)); - }; + } void sync_jni_handler() { std::promise promise = std::promise(); std::future future = promise.get_future(); post_on_bt_jni([&promise]() { promise.set_value(); }); future.wait_for(std::chrono::milliseconds(sync_timeout_in_ms)); - }; + } static pid_t get_mainloop_tid() { std::promise pid_promise = std::promise(); @@ -307,7 +287,7 @@ class ModuleGdxTest : public ::testing::Test { }; class ModuleGdxWithStackTest : public ModuleGdxTest { - protected: +protected: void SetUp() override { ModuleGdxTest::SetUp(); module_registry_.InjectTestModule(&TestGdxModule::Factory, module_ /* pass ownership */); @@ -319,8 +299,10 @@ class ModuleGdxWithStackTest : public ModuleGdxTest { std::promise handler_tid_promise = std::promise(); std::future future = handler_tid_promise.get_future(); handler->Post(common::BindOnce( - [](std::promise promise) { promise.set_value(base::PlatformThread::CurrentId()); }, - std::move(handler_tid_promise))); + [](std::promise promise) { + promise.set_value(base::PlatformThread::CurrentId()); + }, + std::move(handler_tid_promise))); return future.get(); } @@ -329,9 +311,7 @@ class ModuleGdxWithStackTest : public ModuleGdxTest { ModuleGdxTest::TearDown(); } - TestGdxModule* Mod() { - return module_registry_.GetModuleUnderTest(); - } + TestGdxModule* Mod() { return module_registry_.GetModuleUnderTest(); } pid_t handler_tid_{-1}; }; @@ -340,7 +320,7 @@ TEST_F(ModuleGdxTest, nop) {} TEST_F(ModuleGdxTest, lifecycle) { ::bluetooth::os::Thread* thread = - new bluetooth::os::Thread("Name", bluetooth::os::Thread::Priority::REAL_TIME); + new bluetooth::os::Thread("Name", bluetooth::os::Thread::Priority::REAL_TIME); ASSERT_FALSE(module_registry_.IsStarted()); module_registry_.Start(thread); ASSERT_TRUE(module_registry_.IsStarted()); @@ -354,9 +334,7 @@ TEST_F(ModuleGdxWithStackTest, call_on_handler_protected_method) { Mod()->call_on_handler_protected_method(handler_tid_, 1, 2, 3); } -TEST_F(ModuleGdxWithStackTest, test_call_on_main) { - Mod()->call_on_main(mainloop_tid_, 1, 2, 3); -} +TEST_F(ModuleGdxWithStackTest, test_call_on_main) { Mod()->call_on_main(mainloop_tid_, 1, 2, 3); } TEST_F(ModuleGdxWithStackTest, test_call_gdx_external_function_on_main) { Mod()->call_on_main_external_function(mainloop_tid_, 1, 2.3, 'c'); @@ -370,9 +348,7 @@ TEST_F(ModuleGdxWithStackTest, test_call_on_main_recurse) { Mod()->call_on_main_recurse(mainloop_tid_, 1, 2, 3); } -TEST_F(ModuleGdxWithStackTest, test_call_on_jni) { - Mod()->call_on_jni(jniloop_tid_, 1, 2, 3); -} +TEST_F(ModuleGdxWithStackTest, test_call_on_jni) { Mod()->call_on_jni(jniloop_tid_, 1, 2, 3); } TEST_F(ModuleGdxWithStackTest, test_call_gdx_external_function_on_jni) { Mod()->call_on_jni_external_function(jniloop_tid_, 1, 2.3, 'c'); @@ -387,18 +363,14 @@ TEST_F(ModuleGdxWithStackTest, test_call_on_jni_recurse) { } class ModuleGdxWithInstrumentedCallback : public ModuleGdxWithStackTest { - protected: - void SetUp() override { - ModuleGdxWithStackTest::SetUp(); - } +protected: + void SetUp() override { ModuleGdxWithStackTest::SetUp(); } - void TearDown() override { - ModuleGdxWithStackTest::TearDown(); - } + void TearDown() override { ModuleGdxWithStackTest::TearDown(); } // A helper class to promise/future for synchronization class Promises { - public: + public: std::promise result; std::future result_future = result.get_future(); std::promise blocking; @@ -408,13 +380,13 @@ class ModuleGdxWithInstrumentedCallback : public ModuleGdxWithStackTest { }; class InstrumentedCallback { - public: + public: Promises promises; common::ContextualCallback callback; }; class InstrumentedOnceCallback { - public: + public: Promises promises; common::ContextualOnceCallback callback; }; @@ -422,21 +394,18 @@ class ModuleGdxWithInstrumentedCallback : public ModuleGdxWithStackTest { std::unique_ptr GetNewCallbackOnMain() { auto to_return = std::make_unique(); to_return->callback = get_main()->Bind( - [](std::promise* promise_ptr, - std::promise* blocking, - std::future* unblock, - std::string result) { - // Tell the test that this callback is running (and blocking) - blocking->set_value(); - // Block until the test is ready to continue - ASSERT_EQ(std::future_status::ready, unblock->wait_for(std::chrono::seconds(1))); - // Send the result back to the test - promise_ptr->set_value(result); - log::info("set_value {}", result); - }, - &to_return->promises.result, - &to_return->promises.blocking, - &to_return->promises.unblock_future); + [](std::promise* promise_ptr, std::promise* blocking, + std::future* unblock, std::string result) { + // Tell the test that this callback is running (and blocking) + blocking->set_value(); + // Block until the test is ready to continue + ASSERT_EQ(std::future_status::ready, unblock->wait_for(std::chrono::seconds(1))); + // Send the result back to the test + promise_ptr->set_value(result); + log::info("set_value {}", result); + }, + &to_return->promises.result, &to_return->promises.blocking, + &to_return->promises.unblock_future); return to_return; } @@ -444,18 +413,15 @@ class ModuleGdxWithInstrumentedCallback : public ModuleGdxWithStackTest { std::unique_ptr GetNewOnceCallbackOnMain() { auto to_return = std::make_unique(); to_return->callback = get_main()->BindOnce( - [](std::promise* promise_ptr, - std::promise* blocking, - std::future* unblock, - std::string result) { - blocking->set_value(); - ASSERT_EQ(std::future_status::ready, unblock->wait_for(std::chrono::seconds(1))); - promise_ptr->set_value(result); - log::info("set_value {}", result); - }, - &to_return->promises.result, - &to_return->promises.blocking, - &to_return->promises.unblock_future); + [](std::promise* promise_ptr, std::promise* blocking, + std::future* unblock, std::string result) { + blocking->set_value(); + ASSERT_EQ(std::future_status::ready, unblock->wait_for(std::chrono::seconds(1))); + promise_ptr->set_value(result); + log::info("set_value {}", result); + }, + &to_return->promises.result, &to_return->promises.blocking, + &to_return->promises.unblock_future); return to_return; } @@ -468,29 +434,25 @@ TEST_F(ModuleGdxWithInstrumentedCallback, test_call_callback_on_handler) { // Enqueue the callback and wait for it to block on main thread std::string result = "This was called on the handler"; Mod()->call_callback_on_handler(result); - ASSERT_EQ( - std::future_status::ready, - instrumented->promises.blocking_future.wait_for(std::chrono::seconds(1))); + ASSERT_EQ(std::future_status::ready, + instrumented->promises.blocking_future.wait_for(std::chrono::seconds(1))); log::info("Waiting"); // Enqueue something else on the main thread and verify that it hasn't run static auto second_task_promise = std::promise(); auto final_future = second_task_promise.get_future(); - do_in_main_thread( - FROM_HERE, - common::BindOnce( - [](std::promise promise) { - promise.set_value(); - log::info("Finally"); - }, - std::move(second_task_promise))); + do_in_main_thread(FROM_HERE, common::BindOnce( + [](std::promise promise) { + promise.set_value(); + log::info("Finally"); + }, + std::move(second_task_promise))); ASSERT_EQ(std::future_status::timeout, final_future.wait_for(std::chrono::milliseconds(1))); // Let the callback start instrumented->promises.unblock.set_value(); - ASSERT_EQ( - std::future_status::ready, - instrumented->promises.result_future.wait_for(std::chrono::seconds(1))); + ASSERT_EQ(std::future_status::ready, + instrumented->promises.result_future.wait_for(std::chrono::seconds(1))); ASSERT_EQ(result, instrumented->promises.result_future.get()); // Let the second task finish @@ -504,29 +466,25 @@ TEST_F(ModuleGdxWithInstrumentedCallback, test_call_once_callback_on_handler) { // Enqueue the callback and wait for it to block on main thread std::string result = "This was called on the handler"; Mod()->call_once_callback_on_handler(result); - ASSERT_EQ( - std::future_status::ready, - instrumented->promises.blocking_future.wait_for(std::chrono::seconds(1))); + ASSERT_EQ(std::future_status::ready, + instrumented->promises.blocking_future.wait_for(std::chrono::seconds(1))); log::info("Waiting"); // Enqueue something else on the main thread and verify that it hasn't run static auto second_task_promise = std::promise(); auto final_future = second_task_promise.get_future(); - do_in_main_thread( - FROM_HERE, - common::BindOnce( - [](std::promise promise) { - promise.set_value(); - log::info("Finally"); - }, - std::move(second_task_promise))); + do_in_main_thread(FROM_HERE, common::BindOnce( + [](std::promise promise) { + promise.set_value(); + log::info("Finally"); + }, + std::move(second_task_promise))); ASSERT_EQ(std::future_status::timeout, final_future.wait_for(std::chrono::milliseconds(1))); // Let the callback start instrumented->promises.unblock.set_value(); - ASSERT_EQ( - std::future_status::ready, - instrumented->promises.result_future.wait_for(std::chrono::seconds(1))); + ASSERT_EQ(std::future_status::ready, + instrumented->promises.result_future.wait_for(std::chrono::seconds(1))); ASSERT_EQ(result, instrumented->promises.result_future.get()); // Let the second task finish @@ -540,29 +498,25 @@ TEST_F(ModuleGdxWithInstrumentedCallback, test_call_callback_on_main) { // Enqueue the callback and wait for it to block on main thread std::string result = "This was called on the main"; Mod()->call_callback_on_main(result); - ASSERT_EQ( - std::future_status::ready, - instrumented->promises.blocking_future.wait_for(std::chrono::seconds(1))); + ASSERT_EQ(std::future_status::ready, + instrumented->promises.blocking_future.wait_for(std::chrono::seconds(1))); log::info("Waiting"); // Enqueue something else on the main thread and verify that it hasn't run static auto second_task_promise = std::promise(); auto final_future = second_task_promise.get_future(); - do_in_main_thread( - FROM_HERE, - common::BindOnce( - [](std::promise promise) { - promise.set_value(); - log::info("Finally"); - }, - std::move(second_task_promise))); + do_in_main_thread(FROM_HERE, common::BindOnce( + [](std::promise promise) { + promise.set_value(); + log::info("Finally"); + }, + std::move(second_task_promise))); ASSERT_EQ(std::future_status::timeout, final_future.wait_for(std::chrono::milliseconds(1))); // Let the callback start instrumented->promises.unblock.set_value(); - ASSERT_EQ( - std::future_status::ready, - instrumented->promises.result_future.wait_for(std::chrono::seconds(1))); + ASSERT_EQ(std::future_status::ready, + instrumented->promises.result_future.wait_for(std::chrono::seconds(1))); ASSERT_EQ(result, instrumented->promises.result_future.get()); // Let the second task finish @@ -576,29 +530,25 @@ TEST_F(ModuleGdxWithInstrumentedCallback, test_call_once_callback_on_main) { // Enqueue the callback and wait for it to block on main thread std::string result = "This was called on the main"; Mod()->call_once_callback_on_main(result); - ASSERT_EQ( - std::future_status::ready, - instrumented->promises.blocking_future.wait_for(std::chrono::seconds(1))); + ASSERT_EQ(std::future_status::ready, + instrumented->promises.blocking_future.wait_for(std::chrono::seconds(1))); log::info("Waiting"); // Enqueue something else on the main thread and verify that it hasn't run static auto second_task_promise = std::promise(); auto final_future = second_task_promise.get_future(); - do_in_main_thread( - FROM_HERE, - common::BindOnce( - [](std::promise promise) { - promise.set_value(); - log::info("Finally"); - }, - std::move(second_task_promise))); + do_in_main_thread(FROM_HERE, common::BindOnce( + [](std::promise promise) { + promise.set_value(); + log::info("Finally"); + }, + std::move(second_task_promise))); ASSERT_EQ(std::future_status::timeout, final_future.wait_for(std::chrono::milliseconds(1))); // Let the callback start instrumented->promises.unblock.set_value(); - ASSERT_EQ( - std::future_status::ready, - instrumented->promises.result_future.wait_for(std::chrono::seconds(1))); + ASSERT_EQ(std::future_status::ready, + instrumented->promises.result_future.wait_for(std::chrono::seconds(1))); ASSERT_EQ(result, instrumented->promises.result_future.get()); // Let the second task finish @@ -612,29 +562,25 @@ TEST_F(ModuleGdxWithInstrumentedCallback, test_call_callback_on_jni) { // Enqueue the callback and wait for it to block on main thread std::string result = "This was called on the jni"; Mod()->call_callback_on_jni(result); - ASSERT_EQ( - std::future_status::ready, - instrumented->promises.blocking_future.wait_for(std::chrono::seconds(1))); + ASSERT_EQ(std::future_status::ready, + instrumented->promises.blocking_future.wait_for(std::chrono::seconds(1))); log::info("Waiting"); // Enqueue something else on the main thread and verify that it hasn't run static auto second_task_promise = std::promise(); auto final_future = second_task_promise.get_future(); - do_in_main_thread( - FROM_HERE, - common::BindOnce( - [](std::promise promise) { - promise.set_value(); - log::info("Finally"); - }, - std::move(second_task_promise))); + do_in_main_thread(FROM_HERE, common::BindOnce( + [](std::promise promise) { + promise.set_value(); + log::info("Finally"); + }, + std::move(second_task_promise))); ASSERT_EQ(std::future_status::timeout, final_future.wait_for(std::chrono::milliseconds(1))); // Let the callback start instrumented->promises.unblock.set_value(); - ASSERT_EQ( - std::future_status::ready, - instrumented->promises.result_future.wait_for(std::chrono::seconds(1))); + ASSERT_EQ(std::future_status::ready, + instrumented->promises.result_future.wait_for(std::chrono::seconds(1))); ASSERT_EQ(result, instrumented->promises.result_future.get()); // Let the second task finish @@ -648,29 +594,25 @@ TEST_F(ModuleGdxWithInstrumentedCallback, test_call_once_callback_on_jni) { // Enqueue the callback and wait for it to block on main thread std::string result = "This was called on the jni"; Mod()->call_once_callback_on_jni(result); - ASSERT_EQ( - std::future_status::ready, - instrumented->promises.blocking_future.wait_for(std::chrono::seconds(1))); + ASSERT_EQ(std::future_status::ready, + instrumented->promises.blocking_future.wait_for(std::chrono::seconds(1))); log::info("Waiting"); // Enqueue something else on the main thread and verify that it hasn't run static auto second_task_promise = std::promise(); auto final_future = second_task_promise.get_future(); - do_in_main_thread( - FROM_HERE, - common::BindOnce( - [](std::promise promise) { - promise.set_value(); - log::info("Finally"); - }, - std::move(second_task_promise))); + do_in_main_thread(FROM_HERE, common::BindOnce( + [](std::promise promise) { + promise.set_value(); + log::info("Finally"); + }, + std::move(second_task_promise))); ASSERT_EQ(std::future_status::timeout, final_future.wait_for(std::chrono::milliseconds(1))); // Let the callback start instrumented->promises.unblock.set_value(); - ASSERT_EQ( - std::future_status::ready, - instrumented->promises.result_future.wait_for(std::chrono::seconds(1))); + ASSERT_EQ(std::future_status::ready, + instrumented->promises.result_future.wait_for(std::chrono::seconds(1))); ASSERT_EQ(result, instrumented->promises.result_future.get()); // Let the second task finish diff --git a/system/gd/module_gdx_unittest.h b/system/gd/module_gdx_unittest.h index 1a49d3483f9..6765be025e5 100644 --- a/system/gd/module_gdx_unittest.h +++ b/system/gd/module_gdx_unittest.h @@ -30,7 +30,7 @@ using namespace bluetooth; void external_function(int /* a */, double /* b */, char /* c */); class TestGdxModule : public Module, public ModuleMainloop, public ModuleJniloop { - public: +public: void call_on_handler_protected_method(pid_t tid, int a, int b, int c); void call_on_main_external_function(pid_t tid, int a, double b, char c); void call_on_main(pid_t tid, int a, int b, int c); @@ -54,7 +54,7 @@ class TestGdxModule : public Module, public ModuleMainloop, public ModuleJniloop static const bluetooth::ModuleFactory Factory; - protected: +protected: void protected_method(int a, int b, int c); void call_on_main_internal(int a, int b, int c); void call_on_jni_internal(int a, int b, int c); @@ -65,7 +65,7 @@ class TestGdxModule : public Module, public ModuleMainloop, public ModuleJniloop void Stop() override; std::string ToString() const override; - private: +private: struct PrivateImpl; std::shared_ptr pimpl_; diff --git a/system/gd/module_jniloop.h b/system/gd/module_jniloop.h index 159a0e3db17..b77aa6e322a 100644 --- a/system/gd/module_jniloop.h +++ b/system/gd/module_jniloop.h @@ -25,7 +25,7 @@ namespace bluetooth { class ModuleJniloop { - protected: +protected: ModuleJniloop() noexcept = default; virtual ~ModuleJniloop() = default; ModuleJniloop(const ModuleJniloop& mod) = delete; @@ -40,14 +40,13 @@ class ModuleJniloop { template void PostMethodOnJni(std::shared_ptr ref, Functor&& functor, Args... args) const { do_in_jni_thread(base::BindOnce( - [](std::weak_ptr ref, Functor&& functor, Args&&... args) { - if (std::shared_ptr spt = ref.lock()) { - base::BindOnce(std::forward(functor), spt, std::forward(args)...).Run(); - } - }, - std::weak_ptr(ref), - std::forward(functor), - std::forward(args)...)); + [](std::weak_ptr ref, Functor&& functor, Args&&... args) { + if (std::shared_ptr spt = ref.lock()) { + base::BindOnce(std::forward(functor), spt, std::forward(args)...) + .Run(); + } + }, + std::weak_ptr(ref), std::forward(functor), std::forward(args)...)); } }; diff --git a/system/gd/module_jniloop_unittest.cc b/system/gd/module_jniloop_unittest.cc index 58842104651..1ce47036b43 100644 --- a/system/gd/module_jniloop_unittest.cc +++ b/system/gd/module_jniloop_unittest.cc @@ -58,13 +58,13 @@ struct TestJniModule::PrivateImpl : public ModuleJniloop { private_impl_promise.set_value(base::PlatformThread::CurrentId()); } - void privateCallableRepostMethod( - std::shared_ptr ptr, int a, double b, char c) { + void privateCallableRepostMethod(std::shared_ptr ptr, int a, double b, + char c) { PostMethodOnJni(ptr, &PrivateImpl::repostMethodTest, a, b, c); } - void privateCallableRecursiveMethod( - std::shared_ptr ptr, int depth, double b, char c) { + void privateCallableRecursiveMethod(std::shared_ptr ptr, int depth, + double b, char c) { if (depth > kMaxTestModuleRecurseDepth) { private_impl_promise.set_value(base::PlatformThread::CurrentId()); return; @@ -104,8 +104,8 @@ void TestJniModule::call_on_jni(int loop_tid, int a, int b, int c) { void TestJniModule::call_on_jni_repost(int loop_tid, int a, int b, int c) { private_impl_promise = std::promise(); auto future = private_impl_promise.get_future(); - PostMethodOnJni( - pimpl_, &TestJniModule::PrivateImpl::privateCallableRepostMethod, pimpl_, a, b, c); + PostMethodOnJni(pimpl_, &TestJniModule::PrivateImpl::privateCallableRepostMethod, pimpl_, a, b, + c); ASSERT_EQ(future.wait_for(std::chrono::seconds(3)), std::future_status::ready); ASSERT_EQ(future.get(), loop_tid); } @@ -114,8 +114,8 @@ void TestJniModule::call_on_jni_repost(int loop_tid, int a, int b, int c) { void TestJniModule::call_on_jni_recurse(int loop_tid, int depth, int b, int c) { private_impl_promise = std::promise(); auto future = private_impl_promise.get_future(); - PostMethodOnJni( - pimpl_, &TestJniModule::PrivateImpl::privateCallableRecursiveMethod, pimpl_, depth, b, c); + PostMethodOnJni(pimpl_, &TestJniModule::PrivateImpl::privateCallableRecursiveMethod, pimpl_, + depth, b, c); ASSERT_EQ(future.wait_for(std::chrono::seconds(3)), std::future_status::ready); ASSERT_EQ(future.get(), loop_tid); } @@ -124,9 +124,7 @@ void TestJniModule::protected_method(int /* a */, int /* b */, int /* c */) { protected_method_promise.set_value(base::PlatformThread::CurrentId()); } -bool TestJniModule::IsStarted() const { - return pimpl_ != nullptr; -} +bool TestJniModule::IsStarted() const { return pimpl_ != nullptr; } void TestJniModule::Start() { ASSERT_FALSE(IsStarted()); @@ -138,18 +136,16 @@ void TestJniModule::Stop() { pimpl_.reset(); } -std::string TestJniModule::ToString() const { - return std::string(__func__); -} +std::string TestJniModule::ToString() const { return std::string(__func__); } const bluetooth::ModuleFactory TestJniModule::Factory = - bluetooth::ModuleFactory([]() { return new TestJniModule(); }); + bluetooth::ModuleFactory([]() { return new TestJniModule(); }); // // Module GDx Testing Below // class ModuleGdxJniTest : public ::testing::Test { - protected: +protected: void SetUp() override { test_framework_tid_ = base::PlatformThread::CurrentId(); module_ = new TestJniModule(); @@ -168,7 +164,7 @@ class ModuleGdxJniTest : public ::testing::Test { std::future future = promise.get_future(); post_on_bt_jni([&promise]() { promise.set_value(); }); future.wait_for(std::chrono::milliseconds(sync_timeout_in_ms)); - }; + } static pid_t get_jniloop_tid() { std::promise pid_promise = std::promise(); @@ -184,7 +180,7 @@ class ModuleGdxJniTest : public ::testing::Test { }; class ModuleGdxWithJniStackTest : public ModuleGdxJniTest { - protected: +protected: void SetUp() override { ModuleGdxJniTest::SetUp(); module_registry_.InjectTestModule(&TestJniModule::Factory, module_ /* pass ownership */); @@ -196,8 +192,10 @@ class ModuleGdxWithJniStackTest : public ModuleGdxJniTest { std::promise handler_tid_promise = std::promise(); std::future future = handler_tid_promise.get_future(); handler->Post(common::BindOnce( - [](std::promise promise) { promise.set_value(base::PlatformThread::CurrentId()); }, - std::move(handler_tid_promise))); + [](std::promise promise) { + promise.set_value(base::PlatformThread::CurrentId()); + }, + std::move(handler_tid_promise))); return future.get(); } @@ -206,9 +204,7 @@ class ModuleGdxWithJniStackTest : public ModuleGdxJniTest { ModuleGdxJniTest::TearDown(); } - TestJniModule* Mod() { - return module_registry_.GetModuleUnderTest(); - } + TestJniModule* Mod() { return module_registry_.GetModuleUnderTest(); } pid_t handler_tid_{-1}; }; @@ -217,7 +213,7 @@ TEST_F(ModuleGdxJniTest, nop) {} TEST_F(ModuleGdxJniTest, lifecycle) { ::bluetooth::os::Thread* thread = - new bluetooth::os::Thread("Name", bluetooth::os::Thread::Priority::REAL_TIME); + new bluetooth::os::Thread("Name", bluetooth::os::Thread::Priority::REAL_TIME); ASSERT_FALSE(module_registry_.IsStarted()); module_registry_.Start(thread); ASSERT_TRUE(module_registry_.IsStarted()); @@ -230,9 +226,7 @@ TEST_F(ModuleGdxWithJniStackTest, call_on_handler_protected_method) { Mod()->call_on_handler_protected_method(handler_tid_, 1, 2, 3); } -TEST_F(ModuleGdxWithJniStackTest, test_call_on_jni) { - Mod()->call_on_jni(jniloop_tid_, 1, 2, 3); -} +TEST_F(ModuleGdxWithJniStackTest, test_call_on_jni) { Mod()->call_on_jni(jniloop_tid_, 1, 2, 3); } TEST_F(ModuleGdxWithJniStackTest, test_call_external_function) { Mod()->call_on_jni_external_function(jniloop_tid_, 1, 2.3, 'c'); diff --git a/system/gd/module_jniloop_unittest.h b/system/gd/module_jniloop_unittest.h index 52a4c28e7e4..032606251e1 100644 --- a/system/gd/module_jniloop_unittest.h +++ b/system/gd/module_jniloop_unittest.h @@ -28,7 +28,7 @@ using namespace bluetooth; void external_function(int /* a */, double /* b */, char /* c */); class TestJniModule : public Module, public ModuleJniloop { - public: +public: void call_on_handler_protected_method(pid_t tid, int a, int b, int c); void call_on_jni_external_function(pid_t tid, int a, double b, char c); void call_on_jni(pid_t tid, int a, int b, int c); @@ -37,7 +37,7 @@ class TestJniModule : public Module, public ModuleJniloop { static const bluetooth::ModuleFactory Factory; - protected: +protected: void protected_method(int a, int b, int c); void call_on_jni_internal(int a, int b, int c); bool IsStarted() const; @@ -47,7 +47,7 @@ class TestJniModule : public Module, public ModuleJniloop { void Stop() override; std::string ToString() const override; - private: +private: struct PrivateImpl; std::shared_ptr pimpl_; diff --git a/system/gd/module_mainloop.h b/system/gd/module_mainloop.h index 41ba42f8683..ce6ed8c1cbc 100644 --- a/system/gd/module_mainloop.h +++ b/system/gd/module_mainloop.h @@ -25,7 +25,7 @@ namespace bluetooth { class ModuleMainloop { - protected: +protected: ModuleMainloop() noexcept = default; virtual ~ModuleMainloop() = default; ModuleMainloop(const ModuleMainloop& mod) = delete; @@ -33,25 +33,24 @@ class ModuleMainloop { // Threadsafe post onto mainloop a function with copyable arguments template void PostFunctionOnMain(Functor&& functor, Args&&... args) const { - do_in_main_thread( - FROM_HERE, base::BindOnce(std::forward(functor), std::forward(args)...)); + do_in_main_thread(FROM_HERE, + base::BindOnce(std::forward(functor), std::forward(args)...)); } // Threadsafe post onto mainloop a method and context with copyable arguments template void PostMethodOnMain(std::shared_ptr ref, Functor&& functor, Args... args) const { - do_in_main_thread( - FROM_HERE, - base::BindOnce( - [](std::weak_ptr ref, Functor&& functor, Args&&... args) { - if (std::shared_ptr spt = ref.lock()) { - base::BindOnce(std::forward(functor), spt, std::forward(args)...) - .Run(); - } - }, - std::weak_ptr(ref), - std::forward(functor), - std::forward(args)...)); + do_in_main_thread(FROM_HERE, + base::BindOnce( + [](std::weak_ptr ref, Functor&& functor, Args&&... args) { + if (std::shared_ptr spt = ref.lock()) { + base::BindOnce(std::forward(functor), spt, + std::forward(args)...) + .Run(); + } + }, + std::weak_ptr(ref), std::forward(functor), + std::forward(args)...)); } }; diff --git a/system/gd/module_mainloop_unittest.cc b/system/gd/module_mainloop_unittest.cc index e59b6623d46..f9e9ce3419d 100644 --- a/system/gd/module_mainloop_unittest.cc +++ b/system/gd/module_mainloop_unittest.cc @@ -58,13 +58,13 @@ struct TestModule::PrivateImpl : public ModuleMainloop { private_impl_promise.set_value(base::PlatformThread::CurrentId()); } - void privateCallableRepostMethod( - std::shared_ptr ptr, int a, double b, char c) { + void privateCallableRepostMethod(std::shared_ptr ptr, int a, double b, + char c) { PostMethodOnMain(ptr, &PrivateImpl::repostMethodTest, a, b, c); } - void privateCallableRecursiveMethod( - std::shared_ptr ptr, int depth, double b, char c) { + void privateCallableRecursiveMethod(std::shared_ptr ptr, int depth, + double b, char c) { if (depth > kMaxTestModuleRecurseDepth) { private_impl_promise.set_value(base::PlatformThread::CurrentId()); return; @@ -113,8 +113,8 @@ void TestModule::call_on_main_repost(int loop_tid, int a, int b, int c) { void TestModule::call_on_main_recurse(int loop_tid, int depth, int b, int c) { private_impl_promise = std::promise(); auto future = private_impl_promise.get_future(); - PostMethodOnMain( - pimpl_, &TestModule::PrivateImpl::privateCallableRecursiveMethod, pimpl_, depth, b, c); + PostMethodOnMain(pimpl_, &TestModule::PrivateImpl::privateCallableRecursiveMethod, pimpl_, depth, + b, c); ASSERT_EQ(future.wait_for(std::chrono::seconds(3)), std::future_status::ready); ASSERT_EQ(future.get(), loop_tid); } @@ -123,9 +123,7 @@ void TestModule::protected_method(int /* a */, int /* b */, int /* c */) { protected_method_promise.set_value(base::PlatformThread::CurrentId()); } -bool TestModule::IsStarted() const { - return pimpl_ != nullptr; -} +bool TestModule::IsStarted() const { return pimpl_ != nullptr; } void TestModule::Start() { ASSERT_FALSE(IsStarted()); @@ -137,18 +135,16 @@ void TestModule::Stop() { pimpl_.reset(); } -std::string TestModule::ToString() const { - return std::string(__func__); -} +std::string TestModule::ToString() const { return std::string(__func__); } const bluetooth::ModuleFactory TestModule::Factory = - bluetooth::ModuleFactory([]() { return new TestModule(); }); + bluetooth::ModuleFactory([]() { return new TestModule(); }); // // Module GDx Testing Below // class ModuleMainGdxTest : public ::testing::Test { - protected: +protected: void SetUp() override { test_framework_tid_ = base::PlatformThread::CurrentId(); module_ = new TestModule(); @@ -167,7 +163,7 @@ class ModuleMainGdxTest : public ::testing::Test { std::future future = promise.get_future(); post_on_bt_main([&promise]() { promise.set_value(); }); future.wait_for(std::chrono::milliseconds(sync_timeout_in_ms)); - }; + } static pid_t get_mainloop_tid() { std::promise pid_promise = std::promise(); @@ -183,7 +179,7 @@ class ModuleMainGdxTest : public ::testing::Test { }; class ModuleMainGdxWithStackTest : public ModuleMainGdxTest { - protected: +protected: void SetUp() override { ModuleMainGdxTest::SetUp(); module_registry_.InjectTestModule(&TestModule::Factory, module_ /* pass ownership */); @@ -195,8 +191,10 @@ class ModuleMainGdxWithStackTest : public ModuleMainGdxTest { std::promise handler_tid_promise = std::promise(); std::future future = handler_tid_promise.get_future(); handler->Post(common::BindOnce( - [](std::promise promise) { promise.set_value(base::PlatformThread::CurrentId()); }, - std::move(handler_tid_promise))); + [](std::promise promise) { + promise.set_value(base::PlatformThread::CurrentId()); + }, + std::move(handler_tid_promise))); return future.get(); } @@ -205,9 +203,7 @@ class ModuleMainGdxWithStackTest : public ModuleMainGdxTest { ModuleMainGdxTest::TearDown(); } - TestModule* Mod() { - return module_registry_.GetModuleUnderTest(); - } + TestModule* Mod() { return module_registry_.GetModuleUnderTest(); } pid_t handler_tid_{-1}; }; @@ -216,7 +212,7 @@ TEST_F(ModuleMainGdxTest, nop) {} TEST_F(ModuleMainGdxTest, lifecycle) { ::bluetooth::os::Thread* thread = - new bluetooth::os::Thread("Name", bluetooth::os::Thread::Priority::REAL_TIME); + new bluetooth::os::Thread("Name", bluetooth::os::Thread::Priority::REAL_TIME); ASSERT_FALSE(module_registry_.IsStarted()); module_registry_.Start(thread); ASSERT_TRUE(module_registry_.IsStarted()); diff --git a/system/gd/module_mainloop_unittest.h b/system/gd/module_mainloop_unittest.h index bafc44e6060..8e864f33d75 100644 --- a/system/gd/module_mainloop_unittest.h +++ b/system/gd/module_mainloop_unittest.h @@ -28,7 +28,7 @@ using namespace bluetooth; void external_function(int /* a */, double /* b */, char /* c */); class TestModule : public Module, public ModuleMainloop { - public: +public: void call_on_handler_protected_method(pid_t tid, int a, int b, int c); void call_on_main_external_function(pid_t tid, int a, double b, char c); void call_on_main(pid_t tid, int a, int b, int c); @@ -37,7 +37,7 @@ class TestModule : public Module, public ModuleMainloop { static const bluetooth::ModuleFactory Factory; - protected: +protected: void protected_method(int a, int b, int c); void call_on_main_internal(int a, int b, int c); bool IsStarted() const; @@ -47,7 +47,7 @@ class TestModule : public Module, public ModuleMainloop { void Stop() override; std::string ToString() const override; - private: +private: struct PrivateImpl; std::shared_ptr pimpl_; diff --git a/system/gd/module_state_dumper_unittest.cc b/system/gd/module_state_dumper_unittest.cc index 935429802e1..2bb3e92addf 100644 --- a/system/gd/module_state_dumper_unittest.cc +++ b/system/gd/module_state_dumper_unittest.cc @@ -44,9 +44,7 @@ constexpr char title[] = "module_state_dumper_test"; // Module private implementation that is inaccessible externally struct StateDumperTestModule::PrivateImpl : public ModuleMainloop {}; -bool StateDumperTestModule::IsStarted() const { - return pimpl_ != nullptr; -} +bool StateDumperTestModule::IsStarted() const { return pimpl_ != nullptr; } void StateDumperTestModule::Start() { ASSERT_FALSE(IsStarted()); @@ -58,15 +56,13 @@ void StateDumperTestModule::Stop() { pimpl_.reset(); } -std::string StateDumperTestModule::ToString() const { - return std::string(__func__); -} +std::string StateDumperTestModule::ToString() const { return std::string(__func__); } const bluetooth::ModuleFactory StateDumperTestModule::Factory = - bluetooth::ModuleFactory([]() { return new StateDumperTestModule(); }); + bluetooth::ModuleFactory([]() { return new StateDumperTestModule(); }); DumpsysDataFinisher StateDumperTestModule::GetDumpsysData( - flatbuffers::FlatBufferBuilder* /* builder */) const { + flatbuffers::FlatBufferBuilder* /* builder */) const { log::info("flatbuffers"); return EmptyDumpsysDataFinisher; } @@ -75,7 +71,7 @@ DumpsysDataFinisher StateDumperTestModule::GetDumpsysData( // Module GDx Testing Below // class ModuleStateDumperTest : public ::testing::Test { - protected: +protected: void SetUp() override { test_framework_tid_ = base::PlatformThread::CurrentId(); module_ = new StateDumperTestModule(); @@ -94,7 +90,7 @@ class ModuleStateDumperTest : public ::testing::Test { std::future future = promise.get_future(); post_on_bt_main([&promise]() { promise.set_value(); }); future.wait_for(std::chrono::milliseconds(sync_timeout_in_ms)); - }; + } static pid_t get_mainloop_tid() { std::promise pid_promise = std::promise(); @@ -110,11 +106,11 @@ class ModuleStateDumperTest : public ::testing::Test { }; class ModuleStateDumperWithStackTest : public ModuleStateDumperTest { - protected: +protected: void SetUp() override { ModuleStateDumperTest::SetUp(); - module_registry_.InjectTestModule( - &StateDumperTestModule::Factory, module_ /* pass ownership */); + module_registry_.InjectTestModule(&StateDumperTestModule::Factory, + module_ /* pass ownership */); module_ = nullptr; // ownership is passed } @@ -122,8 +118,10 @@ class ModuleStateDumperWithStackTest : public ModuleStateDumperTest { std::promise handler_tid_promise = std::promise(); std::future future = handler_tid_promise.get_future(); handler->Post(common::BindOnce( - [](std::promise promise) { promise.set_value(base::PlatformThread::CurrentId()); }, - std::move(handler_tid_promise))); + [](std::promise promise) { + promise.set_value(base::PlatformThread::CurrentId()); + }, + std::move(handler_tid_promise))); return future.get(); } @@ -141,7 +139,7 @@ class ModuleStateDumperWithStackTest : public ModuleStateDumperTest { TEST_F(ModuleStateDumperTest, lifecycle) { ::bluetooth::os::Thread* thread = - new bluetooth::os::Thread("Name", bluetooth::os::Thread::Priority::REAL_TIME); + new bluetooth::os::Thread("Name", bluetooth::os::Thread::Priority::REAL_TIME); ASSERT_FALSE(module_registry_.IsStarted()); module_registry_.Start(thread); ASSERT_TRUE(module_registry_.IsStarted()); diff --git a/system/gd/module_state_dumper_unittest.h b/system/gd/module_state_dumper_unittest.h index c6ee7479681..7c2a1e6f1c6 100644 --- a/system/gd/module_state_dumper_unittest.h +++ b/system/gd/module_state_dumper_unittest.h @@ -23,10 +23,10 @@ using namespace bluetooth; class StateDumperTestModule : public Module, public ModuleMainloop { - public: +public: static const bluetooth::ModuleFactory Factory; - protected: +protected: bool IsStarted() const; void ListDependencies(bluetooth::ModuleList* /* list */) const override {} @@ -36,7 +36,7 @@ class StateDumperTestModule : public Module, public ModuleMainloop { DumpsysDataFinisher GetDumpsysData(flatbuffers::FlatBufferBuilder* builder) const override; - private: +private: struct PrivateImpl; std::shared_ptr pimpl_; diff --git a/system/gd/module_unittest.cc b/system/gd/module_unittest.cc index f8cdd30b6fc..123cd3e4696 100644 --- a/system/gd/module_unittest.cc +++ b/system/gd/module_unittest.cc @@ -35,7 +35,7 @@ namespace bluetooth { namespace { class ModuleTest : public ::testing::Test { - protected: +protected: void SetUp() override { thread_ = new Thread("test_thread", Thread::Priority::NORMAL); registry_ = new ModuleRegistry(); @@ -53,10 +53,10 @@ class ModuleTest : public ::testing::Test { os::Handler* test_module_no_dependency_handler = nullptr; class TestModuleNoDependency : public Module { - public: +public: static const ModuleFactory Factory; - protected: +protected: void ListDependencies(ModuleList* /* list */) const {} void Start() override { @@ -70,25 +70,20 @@ class TestModuleNoDependency : public Module { EXPECT_TRUE(GetModuleRegistry()->IsStarted()); } - std::string ToString() const override { - return std::string("TestModuleNoDependency"); - } + std::string ToString() const override { return std::string("TestModuleNoDependency"); } }; -const ModuleFactory TestModuleNoDependency::Factory = ModuleFactory([]() { - return new TestModuleNoDependency(); -}); +const ModuleFactory TestModuleNoDependency::Factory = + ModuleFactory([]() { return new TestModuleNoDependency(); }); os::Handler* test_module_one_dependency_handler = nullptr; class TestModuleOneDependency : public Module { - public: +public: static const ModuleFactory Factory; - protected: - void ListDependencies(ModuleList* list) const { - list->add(); - } +protected: + void ListDependencies(ModuleList* list) const { list->add(); } void Start() override { EXPECT_TRUE(GetModuleRegistry()->IsStarted()); @@ -105,21 +100,17 @@ class TestModuleOneDependency : public Module { EXPECT_TRUE(GetModuleRegistry()->IsStarted()); } - std::string ToString() const override { - return std::string("TestModuleOneDependency"); - } + std::string ToString() const override { return std::string("TestModuleOneDependency"); } }; -const ModuleFactory TestModuleOneDependency::Factory = ModuleFactory([]() { - return new TestModuleOneDependency(); -}); - +const ModuleFactory TestModuleOneDependency::Factory = + ModuleFactory([]() { return new TestModuleOneDependency(); }); class TestModuleNoDependencyTwo : public Module { - public: +public: static const ModuleFactory Factory; - protected: +protected: void ListDependencies(ModuleList* /* list */) const {} void Start() override { @@ -132,20 +123,17 @@ class TestModuleNoDependencyTwo : public Module { EXPECT_TRUE(GetModuleRegistry()->IsStarted()); } - std::string ToString() const override { - return std::string("TestModuleNoDependencyTwo"); - } + std::string ToString() const override { return std::string("TestModuleNoDependencyTwo"); } }; -const ModuleFactory TestModuleNoDependencyTwo::Factory = ModuleFactory([]() { - return new TestModuleNoDependencyTwo(); -}); +const ModuleFactory TestModuleNoDependencyTwo::Factory = + ModuleFactory([]() { return new TestModuleNoDependencyTwo(); }); class TestModuleTwoDependencies : public Module { - public: +public: static const ModuleFactory Factory; - protected: +protected: void ListDependencies(ModuleList* list) const { list->add(); list->add(); @@ -167,27 +155,22 @@ class TestModuleTwoDependencies : public Module { EXPECT_TRUE(GetModuleRegistry()->IsStarted()); } - std::string ToString() const override { - return std::string("TestModuleTwoDependencies"); - } + std::string ToString() const override { return std::string("TestModuleTwoDependencies"); } }; -const ModuleFactory TestModuleTwoDependencies::Factory = ModuleFactory([]() { - return new TestModuleTwoDependencies(); -}); +const ModuleFactory TestModuleTwoDependencies::Factory = + ModuleFactory([]() { return new TestModuleTwoDependencies(); }); // To generate module unittest flatbuffer headers: // $ flatc --cpp module_unittest.fbs class TestModuleDumpState : public Module { - public: +public: static const ModuleFactory Factory; std::string test_string_{"Initial Test String"}; - protected: - void ListDependencies(ModuleList* list) const { - list->add(); - } +protected: + void ListDependencies(ModuleList* list) const { list->add(); } void Start() override { EXPECT_TRUE(GetModuleRegistry()->IsStarted()); @@ -204,9 +187,7 @@ class TestModuleDumpState : public Module { EXPECT_TRUE(GetModuleRegistry()->IsStarted()); } - std::string ToString() const override { - return std::string("TestModuleDumpState"); - } + std::string ToString() const override { return std::string("TestModuleDumpState"); } DumpsysDataFinisher GetDumpsysData(flatbuffers::FlatBufferBuilder* fb_builder) const override { auto string = fb_builder->CreateString(test_string_.c_str()); @@ -219,7 +200,8 @@ class TestModuleDumpState : public Module { } }; -const ModuleFactory TestModuleDumpState::Factory = ModuleFactory([]() { return new TestModuleDumpState(); }); +const ModuleFactory TestModuleDumpState::Factory = + ModuleFactory([]() { return new TestModuleDumpState(); }); TEST_F(ModuleTest, no_dependency) { ModuleList list; @@ -306,8 +288,8 @@ TEST_F(ModuleTest, dump_state) { auto test_data = data->module_unittest_data(); EXPECT_STREQ("Initial Test String", test_data->title()->c_str()); - TestModuleDumpState* test_module = - static_cast(registry_->Start(&TestModuleDumpState::Factory, nullptr)); + TestModuleDumpState* test_module = static_cast( + registry_->Start(&TestModuleDumpState::Factory, nullptr)); test_module->test_string_ = "A Second Test String"; oss.clear(); diff --git a/system/gd/module_unittest_generated.h b/system/gd/module_unittest_generated.h index 3c9fd362c1d..1176e5cbc9a 100644 --- a/system/gd/module_unittest_generated.h +++ b/system/gd/module_unittest_generated.h @@ -17,8 +17,8 @@ struct ModuleUnitTestData FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table { return GetPointer(VT_TITLE); } bool Verify(flatbuffers::Verifier& verifier) const { - return VerifyTableStart(verifier) && VerifyOffset(verifier, VT_TITLE) && verifier.VerifyString(title()) && - verifier.EndTable(); + return VerifyTableStart(verifier) && VerifyOffset(verifier, VT_TITLE) && + verifier.VerifyString(title()) && verifier.EndTable(); } }; @@ -41,14 +41,14 @@ struct ModuleUnitTestDataBuilder { }; inline flatbuffers::Offset CreateModuleUnitTestData( - flatbuffers::FlatBufferBuilder& _fbb, flatbuffers::Offset title = 0) { + flatbuffers::FlatBufferBuilder& _fbb, flatbuffers::Offset title = 0) { ModuleUnitTestDataBuilder builder_(_fbb); builder_.add_title(title); return builder_.Finish(); } inline flatbuffers::Offset CreateModuleUnitTestDataDirect( - flatbuffers::FlatBufferBuilder& _fbb, const char* title = nullptr) { + flatbuffers::FlatBufferBuilder& _fbb, const char* title = nullptr) { auto title__ = title ? _fbb.CreateString(title) : 0; return bluetooth::CreateModuleUnitTestData(_fbb, title__); } @@ -70,12 +70,14 @@ inline bool VerifySizePrefixedModuleUnitTestDataBuffer(flatbuffers::Verifier& ve } inline void FinishModuleUnitTestDataBuffer( - flatbuffers::FlatBufferBuilder& fbb, flatbuffers::Offset root) { + flatbuffers::FlatBufferBuilder& fbb, + flatbuffers::Offset root) { fbb.Finish(root); } inline void FinishSizePrefixedModuleUnitTestDataBuffer( - flatbuffers::FlatBufferBuilder& fbb, flatbuffers::Offset root) { + flatbuffers::FlatBufferBuilder& fbb, + flatbuffers::Offset root) { fbb.FinishSizePrefixed(root); } diff --git a/system/gd/neighbor/facade/facade.cc b/system/gd/neighbor/facade/facade.cc index 3f34e3f310a..b3df4a876b2 100644 --- a/system/gd/neighbor/facade/facade.cc +++ b/system/gd/neighbor/facade/facade.cc @@ -33,15 +33,11 @@ namespace facade { using namespace blueberry::facade::neighbor; class NeighborFacadeService : public NeighborFacade::Service { - public: - NeighborFacadeService( - ScanModule* scan_module) - : scan_module_(scan_module) {} - - ::grpc::Status EnablePageScan( - ::grpc::ServerContext* /* context */, - const EnableMsg* request, - ::google::protobuf::Empty* /* response */) override { +public: + NeighborFacadeService(ScanModule* scan_module) : scan_module_(scan_module) {} + + ::grpc::Status EnablePageScan(::grpc::ServerContext* /* context */, const EnableMsg* request, + ::google::protobuf::Empty* /* response */) override { if (request->enabled()) { scan_module_->SetPageScan(); } else { @@ -50,7 +46,7 @@ class NeighborFacadeService : public NeighborFacade::Service { return ::grpc::Status::OK; } - private: +private: ScanModule* scan_module_; }; @@ -69,12 +65,10 @@ void NeighborFacadeModule::Stop() { ::bluetooth::grpc::GrpcFacadeModule::Stop(); } -::grpc::Service* NeighborFacadeModule::GetService() const { - return service_; -} +::grpc::Service* NeighborFacadeModule::GetService() const { return service_; } const ModuleFactory NeighborFacadeModule::Factory = - ::bluetooth::ModuleFactory([]() { return new NeighborFacadeModule(); }); + ::bluetooth::ModuleFactory([]() { return new NeighborFacadeModule(); }); } // namespace facade } // namespace neighbor diff --git a/system/gd/neighbor/facade/facade.h b/system/gd/neighbor/facade/facade.h index 7d50a895c56..92432ed5300 100644 --- a/system/gd/neighbor/facade/facade.h +++ b/system/gd/neighbor/facade/facade.h @@ -28,7 +28,7 @@ namespace facade { class NeighborFacadeService; class NeighborFacadeModule : public ::bluetooth::grpc::GrpcFacadeModule { - public: +public: static const ModuleFactory Factory; void ListDependencies(ModuleList* list) const override; @@ -36,7 +36,7 @@ class NeighborFacadeModule : public ::bluetooth::grpc::GrpcFacadeModule { void Stop() override; ::grpc::Service* GetService() const override; - private: +private: NeighborFacadeService* service_; }; diff --git a/system/gd/neighbor/name_db.cc b/system/gd/neighbor/name_db.cc index 747bb2e9172..99eca8d0e12 100644 --- a/system/gd/neighbor/name_db.cc +++ b/system/gd/neighbor/name_db.cc @@ -41,8 +41,8 @@ struct PendingRemoteNameRead { } // namespace struct NameDbModule::impl { - void ReadRemoteNameRequest( - hci::Address address, ReadRemoteNameDbCallback callback, os::Handler* handler); + void ReadRemoteNameRequest(hci::Address address, ReadRemoteNameDbCallback callback, + os::Handler* handler); bool IsNameCached(hci::Address address) const; RemoteName ReadCachedRemoteName(hci::Address address) const; @@ -52,7 +52,7 @@ struct NameDbModule::impl { void Start(); void Stop(); - private: +private: std::unordered_map> address_to_pending_read_map_; std::unordered_map address_to_name_map_; @@ -65,12 +65,13 @@ struct NameDbModule::impl { }; const ModuleFactory neighbor::NameDbModule::Factory = - ModuleFactory([]() { return new neighbor::NameDbModule(); }); + ModuleFactory([]() { return new neighbor::NameDbModule(); }); neighbor::NameDbModule::impl::impl(const neighbor::NameDbModule& module) : module_(module) {} -void neighbor::NameDbModule::impl::ReadRemoteNameRequest( - hci::Address address, ReadRemoteNameDbCallback callback, os::Handler* handler) { +void neighbor::NameDbModule::impl::ReadRemoteNameRequest(hci::Address address, + ReadRemoteNameDbCallback callback, + os::Handler* handler) { if (address_to_pending_read_map_.find(address) != address_to_pending_read_map_.end()) { log::warn("Already have remote read db in progress; adding callback to callback list"); address_to_pending_read_map_[address].push_back({std::move(callback), handler}); @@ -86,22 +87,21 @@ void neighbor::NameDbModule::impl::ReadRemoteNameRequest( uint16_t clock_offset = 0; hci::ClockOffsetValid clock_offset_valid = hci::ClockOffsetValid::INVALID; name_module_->StartRemoteNameRequest( - address, - hci::RemoteNameRequestBuilder::Create( - address, page_scan_repetition_mode, clock_offset, clock_offset_valid), - handler_->BindOnce([](hci::ErrorCode /* status */) {}), - handler_->BindOnce([&](uint64_t /* features */) { - log::warn("UNIMPLEMENTED: ignoring host supported features"); - }), - handler_->BindOnceOn(this, &NameDbModule::impl::OnRemoteNameResponse, address)); + address, + hci::RemoteNameRequestBuilder::Create(address, page_scan_repetition_mode, clock_offset, + clock_offset_valid), + handler_->BindOnce([](hci::ErrorCode /* status */) {}), + handler_->BindOnce([&](uint64_t /* features */) { + log::warn("UNIMPLEMENTED: ignoring host supported features"); + }), + handler_->BindOnceOn(this, &NameDbModule::impl::OnRemoteNameResponse, address)); } -void neighbor::NameDbModule::impl::OnRemoteNameResponse( - hci::Address address, hci::ErrorCode status, RemoteName name) { - log::assert_that( - address_to_pending_read_map_.find(address) != address_to_pending_read_map_.end(), - "assert failed: address_to_pending_read_map_.find(address) != " - "address_to_pending_read_map_.end()"); +void neighbor::NameDbModule::impl::OnRemoteNameResponse(hci::Address address, hci::ErrorCode status, + RemoteName name) { + log::assert_that(address_to_pending_read_map_.find(address) != address_to_pending_read_map_.end(), + "assert failed: address_to_pending_read_map_.find(address) != " + "address_to_pending_read_map_.end()"); if (status == hci::ErrorCode::SUCCESS) { address_to_name_map_[address] = name; } @@ -126,18 +126,14 @@ RemoteName neighbor::NameDbModule::impl::ReadCachedRemoteName(hci::Address addre */ neighbor::NameDbModule::NameDbModule() : pimpl_(std::make_unique(*this)) {} -neighbor::NameDbModule::~NameDbModule() { - pimpl_.reset(); -} +neighbor::NameDbModule::~NameDbModule() { pimpl_.reset(); } -void neighbor::NameDbModule::ReadRemoteNameRequest( - hci::Address address, ReadRemoteNameDbCallback callback, os::Handler* handler) { - GetHandler()->Post(common::BindOnce( - &NameDbModule::impl::ReadRemoteNameRequest, - common::Unretained(pimpl_.get()), - address, - std::move(callback), - handler)); +void neighbor::NameDbModule::ReadRemoteNameRequest(hci::Address address, + ReadRemoteNameDbCallback callback, + os::Handler* handler) { + GetHandler()->Post(common::BindOnce(&NameDbModule::impl::ReadRemoteNameRequest, + common::Unretained(pimpl_.get()), address, + std::move(callback), handler)); } bool neighbor::NameDbModule::IsNameCached(hci::Address address) const { @@ -162,13 +158,9 @@ void neighbor::NameDbModule::ListDependencies(ModuleList* list) const { list->add(); } -void neighbor::NameDbModule::Start() { - pimpl_->Start(); -} +void neighbor::NameDbModule::Start() { pimpl_->Start(); } -void neighbor::NameDbModule::Stop() { - pimpl_->Stop(); -} +void neighbor::NameDbModule::Stop() { pimpl_->Stop(); } } // namespace neighbor } // namespace bluetooth diff --git a/system/gd/neighbor/name_db.h b/system/gd/neighbor/name_db.h index e15ffd5d8a8..f2201420795 100644 --- a/system/gd/neighbor/name_db.h +++ b/system/gd/neighbor/name_db.h @@ -31,8 +31,9 @@ using RemoteName = std::array; using ReadRemoteNameDbCallback = common::OnceCallback; class NameDbModule : public bluetooth::Module { - public: - virtual void ReadRemoteNameRequest(hci::Address address, ReadRemoteNameDbCallback callback, os::Handler* handler); +public: + virtual void ReadRemoteNameRequest(hci::Address address, ReadRemoteNameDbCallback callback, + os::Handler* handler); bool IsNameCached(hci::Address address) const; RemoteName ReadCachedRemoteName(hci::Address address) const; @@ -45,15 +46,13 @@ class NameDbModule : public bluetooth::Module { ~NameDbModule(); - protected: +protected: void ListDependencies(ModuleList* list) const override; void Start() override; void Stop() override; - std::string ToString() const override { - return std::string("NameDb"); - } + std::string ToString() const override { return std::string("NameDb"); } - private: +private: struct impl; std::unique_ptr pimpl_; }; diff --git a/system/gd/neighbor/scan.cc b/system/gd/neighbor/scan.cc index 7bce75fe934..fafb316b33e 100644 --- a/system/gd/neighbor/scan.cc +++ b/system/gd/neighbor/scan.cc @@ -42,7 +42,7 @@ struct ScanModule::impl { void Start(); void Stop(); - private: +private: ScanModule& module_; bool inquiry_scan_enabled_; @@ -57,7 +57,8 @@ struct ScanModule::impl { os::Handler* handler_; }; -const ModuleFactory neighbor::ScanModule::Factory = ModuleFactory([]() { return new neighbor::ScanModule(); }); +const ModuleFactory neighbor::ScanModule::Factory = + ModuleFactory([]() { return new neighbor::ScanModule(); }); neighbor::ScanModule::impl::impl(neighbor::ScanModule& module) : module_(module), inquiry_scan_enabled_(false), page_scan_enabled_(false) {} @@ -67,18 +68,16 @@ void neighbor::ScanModule::impl::OnCommandComplete(hci::CommandCompleteView view case hci::OpCode::READ_SCAN_ENABLE: { auto packet = hci::ReadScanEnableCompleteView::Create(view); log::assert_that(packet.IsValid(), "assert failed: packet.IsValid()"); - log::assert_that( - packet.GetStatus() == hci::ErrorCode::SUCCESS, - "assert failed: packet.GetStatus() == hci::ErrorCode::SUCCESS"); + log::assert_that(packet.GetStatus() == hci::ErrorCode::SUCCESS, + "assert failed: packet.GetStatus() == hci::ErrorCode::SUCCESS"); ReadScanEnable(packet.GetScanEnable()); } break; case hci::OpCode::WRITE_SCAN_ENABLE: { auto packet = hci::WriteScanEnableCompleteView::Create(view); log::assert_that(packet.IsValid(), "assert failed: packet.IsValid()"); - log::assert_that( - packet.GetStatus() == hci::ErrorCode::SUCCESS, - "assert failed: packet.GetStatus() == hci::ErrorCode::SUCCESS"); + log::assert_that(packet.GetStatus() == hci::ErrorCode::SUCCESS, + "assert failed: packet.GetStatus() == hci::ErrorCode::SUCCESS"); } break; default: @@ -101,13 +100,16 @@ void neighbor::ScanModule::impl::WriteScanEnable() { } { - std::unique_ptr packet = hci::WriteScanEnableBuilder::Create(scan_enable); - hci_layer_->EnqueueCommand(std::move(packet), handler_->BindOnceOn(this, &impl::OnCommandComplete)); + std::unique_ptr packet = + hci::WriteScanEnableBuilder::Create(scan_enable); + hci_layer_->EnqueueCommand(std::move(packet), + handler_->BindOnceOn(this, &impl::OnCommandComplete)); } { std::unique_ptr packet = hci::ReadScanEnableBuilder::Create(); - hci_layer_->EnqueueCommand(std::move(packet), handler_->BindOnceOn(this, &impl::OnCommandComplete)); + hci_layer_->EnqueueCommand(std::move(packet), + handler_->BindOnceOn(this, &impl::OnCommandComplete)); } } @@ -145,68 +147,45 @@ void neighbor::ScanModule::impl::SetPageScan(bool enabled) { WriteScanEnable(); } -bool neighbor::ScanModule::impl::IsInquiryEnabled() const { - return inquiry_scan_enabled_; -} +bool neighbor::ScanModule::impl::IsInquiryEnabled() const { return inquiry_scan_enabled_; } -bool neighbor::ScanModule::impl::IsPageEnabled() const { - return page_scan_enabled_; -} +bool neighbor::ScanModule::impl::IsPageEnabled() const { return page_scan_enabled_; } void neighbor::ScanModule::impl::Start() { hci_layer_ = module_.GetDependency(); handler_ = module_.GetHandler(); std::unique_ptr packet = hci::ReadScanEnableBuilder::Create(); - hci_layer_->EnqueueCommand(std::move(packet), handler_->BindOnceOn(this, &impl::OnCommandComplete)); + hci_layer_->EnqueueCommand(std::move(packet), + handler_->BindOnceOn(this, &impl::OnCommandComplete)); } void neighbor::ScanModule::impl::Stop() { - log::info( - "inquiry scan enabled:{} page scan enabled:{}", inquiry_scan_enabled_, page_scan_enabled_); + log::info("inquiry scan enabled:{} page scan enabled:{}", inquiry_scan_enabled_, + page_scan_enabled_); } neighbor::ScanModule::ScanModule() : pimpl_(std::make_unique(*this)) {} -neighbor::ScanModule::~ScanModule() { - pimpl_.reset(); -} +neighbor::ScanModule::~ScanModule() { pimpl_.reset(); } -void neighbor::ScanModule::SetInquiryScan() { - pimpl_->SetInquiryScan(true); -} +void neighbor::ScanModule::SetInquiryScan() { pimpl_->SetInquiryScan(true); } -void neighbor::ScanModule::ClearInquiryScan() { - pimpl_->SetInquiryScan(false); -} +void neighbor::ScanModule::ClearInquiryScan() { pimpl_->SetInquiryScan(false); } -void neighbor::ScanModule::SetPageScan() { - pimpl_->SetPageScan(true); -} +void neighbor::ScanModule::SetPageScan() { pimpl_->SetPageScan(true); } -void neighbor::ScanModule::ClearPageScan() { - pimpl_->SetPageScan(false); -} +void neighbor::ScanModule::ClearPageScan() { pimpl_->SetPageScan(false); } -bool neighbor::ScanModule::IsInquiryEnabled() const { - return pimpl_->IsInquiryEnabled(); -} +bool neighbor::ScanModule::IsInquiryEnabled() const { return pimpl_->IsInquiryEnabled(); } -bool neighbor::ScanModule::IsPageEnabled() const { - return pimpl_->IsPageEnabled(); -} +bool neighbor::ScanModule::IsPageEnabled() const { return pimpl_->IsPageEnabled(); } -void neighbor::ScanModule::ListDependencies(ModuleList* list) const { - list->add(); -} +void neighbor::ScanModule::ListDependencies(ModuleList* list) const { list->add(); } -void neighbor::ScanModule::Start() { - pimpl_->Start(); -} +void neighbor::ScanModule::Start() { pimpl_->Start(); } -void neighbor::ScanModule::Stop() { - pimpl_->Stop(); -} +void neighbor::ScanModule::Stop() { pimpl_->Stop(); } } // namespace neighbor } // namespace bluetooth diff --git a/system/gd/neighbor/scan.h b/system/gd/neighbor/scan.h index 6cea59595d4..0a5d29b6a7b 100644 --- a/system/gd/neighbor/scan.h +++ b/system/gd/neighbor/scan.h @@ -23,7 +23,7 @@ namespace bluetooth { namespace neighbor { class ScanModule : public bluetooth::Module { - public: +public: ScanModule(); ScanModule(const ScanModule&) = delete; ScanModule& operator=(const ScanModule&) = delete; @@ -40,15 +40,13 @@ class ScanModule : public bluetooth::Module { static const ModuleFactory Factory; - protected: +protected: void ListDependencies(ModuleList* list) const override; void Start() override; void Stop() override; - std::string ToString() const override { - return std::string("Scan"); - } + std::string ToString() const override { return std::string("Scan"); } - private: +private: struct impl; std::unique_ptr pimpl_; }; diff --git a/system/gd/os/alarm.h b/system/gd/os/alarm.h index 4a689da48b3..c65bece8287 100644 --- a/system/gd/os/alarm.h +++ b/system/gd/os/alarm.h @@ -29,10 +29,10 @@ namespace bluetooth { namespace os { // A single-shot alarm for reactor-based thread, implemented by Linux timerfd. -// When it's constructed, it will register a reactable on the specified thread; when it's destroyed, it will unregister -// itself from the thread. +// When it's constructed, it will register a reactable on the specified thread; when it's destroyed, +// it will unregister itself from the thread. class Alarm { - public: +public: // Create and register a single-shot alarm on a given handler explicit Alarm(Handler* handler); @@ -48,7 +48,7 @@ class Alarm { // Cancel the alarm. No-op if it's not armed. void Cancel(); - private: +private: common::OnceClosure task_; Handler* handler_; int fd_ = 0; diff --git a/system/gd/os/alarm_benchmark.cc b/system/gd/os/alarm_benchmark.cc index 286ae4e1487..cfe3c3db806 100644 --- a/system/gd/os/alarm_benchmark.cc +++ b/system/gd/os/alarm_benchmark.cc @@ -32,7 +32,7 @@ using ::bluetooth::os::RepeatingAlarm; using ::bluetooth::os::Thread; class BM_ReactableAlarm : public ::benchmark::Fixture { - protected: +protected: void SetUp(State& st) override { ::benchmark::Fixture::SetUp(st); thread_ = std::make_unique("timer_benchmark", Thread::Priority::REAL_TIME); @@ -58,7 +58,8 @@ class BM_ReactableAlarm : public ::benchmark::Fixture { void AlarmSleepAndCountDelayedTime() { auto end_time = std::chrono::steady_clock::now(); - auto duration_since_start = std::chrono::duration_cast(end_time - start_time_); + auto duration_since_start = + std::chrono::duration_cast(end_time - start_time_); task_counter_++; map_[duration_since_start.count() - task_counter_ * task_interval_]++; std::this_thread::sleep_for(std::chrono::milliseconds(task_length_)); @@ -67,9 +68,7 @@ class BM_ReactableAlarm : public ::benchmark::Fixture { } } - void TimerFire() { - promise_.set_value(); - } + void TimerFire() { promise_.set_value(); } int64_t scheduled_tasks_; int64_t task_length_; @@ -88,27 +87,28 @@ BENCHMARK_DEFINE_F(BM_ReactableAlarm, timer_performance_ms)(State& state) { auto milliseconds = static_cast(state.range(0)); for (auto _ : state) { auto start_time_point = std::chrono::steady_clock::now(); - alarm_->Schedule( - Bind(&BM_ReactableAlarm_timer_performance_ms_Benchmark::TimerFire, bluetooth::common::Unretained(this)), - std::chrono::milliseconds(milliseconds)); + alarm_->Schedule(Bind(&BM_ReactableAlarm_timer_performance_ms_Benchmark::TimerFire, + bluetooth::common::Unretained(this)), + std::chrono::milliseconds(milliseconds)); promise_.get_future().get(); auto end_time_point = std::chrono::steady_clock::now(); - auto duration = std::chrono::duration_cast(end_time_point - start_time_point); + auto duration = + std::chrono::duration_cast(end_time_point - start_time_point); state.SetIterationTime(static_cast(duration.count()) * 1e-6); alarm_->Cancel(); } -}; +} BENCHMARK_REGISTER_F(BM_ReactableAlarm, timer_performance_ms) - ->Arg(1) - ->Arg(5) - ->Arg(10) - ->Arg(20) - ->Arg(100) - ->Arg(1000) - ->Arg(2000) - ->Iterations(1) - ->UseRealTime(); + ->Arg(1) + ->Arg(5) + ->Arg(10) + ->Arg(20) + ->Arg(100) + ->Arg(1000) + ->Arg(2000) + ->Iterations(1) + ->UseRealTime(); BENCHMARK_DEFINE_F(BM_ReactableAlarm, periodic_accuracy)(State& state) { for (auto _ : state) { @@ -117,26 +117,25 @@ BENCHMARK_DEFINE_F(BM_ReactableAlarm, periodic_accuracy)(State& state) { task_interval_ = state.range(2); start_time_ = std::chrono::steady_clock::now(); repeating_alarm_->Schedule( - Bind( - &BM_ReactableAlarm_periodic_accuracy_Benchmark::AlarmSleepAndCountDelayedTime, - bluetooth::common::Unretained(this)), - std::chrono::milliseconds(task_interval_)); + Bind(&BM_ReactableAlarm_periodic_accuracy_Benchmark::AlarmSleepAndCountDelayedTime, + bluetooth::common::Unretained(this)), + std::chrono::milliseconds(task_interval_)); promise_.get_future().get(); repeating_alarm_->Cancel(); } for (const auto& delay : map_) { state.counters[std::to_string(delay.first)] = delay.second; } -}; +} BENCHMARK_REGISTER_F(BM_ReactableAlarm, periodic_accuracy) - ->Args({2000, 1, 5}) - ->Args({2000, 3, 5}) - ->Args({2000, 1, 7}) - ->Args({2000, 3, 7}) - ->Args({2000, 1, 20}) - ->Args({2000, 5, 20}) - ->Args({2000, 10, 20}) - ->Args({2000, 15, 20}) - ->Iterations(1) - ->UseRealTime(); + ->Args({2000, 1, 5}) + ->Args({2000, 3, 5}) + ->Args({2000, 1, 7}) + ->Args({2000, 3, 7}) + ->Args({2000, 1, 20}) + ->Args({2000, 5, 20}) + ->Args({2000, 10, 20}) + ->Args({2000, 15, 20}) + ->Iterations(1) + ->UseRealTime(); diff --git a/system/gd/os/android/metrics.cc b/system/gd/os/android/metrics.cc index 0223b42df9c..216ae9b7a13 100644 --- a/system/gd/os/android/metrics.cc +++ b/system/gd/os/android/metrics.cc @@ -63,45 +63,28 @@ using bluetooth::hci::EventCode; */ static const BytesField byteField(nullptr, 0); -void LogMetricLinkLayerConnectionEvent( - const Address* address, - uint32_t connection_handle, - android::bluetooth::DirectionEnum direction, - uint16_t link_type, - uint32_t hci_cmd, - uint16_t hci_event, - uint16_t hci_ble_event, - uint16_t cmd_status, - uint16_t reason_code) { +void LogMetricLinkLayerConnectionEvent(const Address* address, uint32_t connection_handle, + android::bluetooth::DirectionEnum direction, + uint16_t link_type, uint32_t hci_cmd, uint16_t hci_event, + uint16_t hci_ble_event, uint16_t cmd_status, + uint16_t reason_code) { int metric_id = 0; if (address != nullptr) { metric_id = MetricIdManager::GetInstance().AllocateId(*address); } - int ret = stats_write( - BLUETOOTH_LINK_LAYER_CONNECTION_EVENT, - byteField, - connection_handle, - direction, - link_type, - hci_cmd, - hci_event, - hci_ble_event, - cmd_status, - reason_code, - metric_id); + int ret = stats_write(BLUETOOTH_LINK_LAYER_CONNECTION_EVENT, byteField, connection_handle, + direction, link_type, hci_cmd, hci_event, hci_ble_event, cmd_status, + reason_code, metric_id); if (ret < 0) { log::warn( - "Failed to log status {} , reason {}, from cmd {}, event {}, ble_event {}, for {}, handle " - "{}, type {}, error {}", - common::ToHexString(cmd_status), - common::ToHexString(reason_code), - common::ToHexString(hci_cmd), - common::ToHexString(hci_event), - common::ToHexString(hci_ble_event), - address ? ADDRESS_TO_LOGGABLE_CSTR(*address) : "(NULL)", - connection_handle, - common::ToHexString(link_type), - ret); + "Failed to log status {} , reason {}, from cmd {}, event {}, ble_event {}, for {}, " + "handle " + "{}, type {}, error {}", + common::ToHexString(cmd_status), common::ToHexString(reason_code), + common::ToHexString(hci_cmd), common::ToHexString(hci_event), + common::ToHexString(hci_ble_event), + address ? ADDRESS_TO_LOGGABLE_CSTR(*address) : "(NULL)", connection_handle, + common::ToHexString(link_type), ret); } } @@ -112,71 +95,53 @@ void LogMetricHciTimeoutEvent(uint32_t hci_cmd) { } } -void LogMetricRemoteVersionInfo( - uint16_t handle, uint8_t status, uint8_t version, uint16_t manufacturer_name, uint16_t subversion) { - int ret = stats_write(BLUETOOTH_REMOTE_VERSION_INFO_REPORTED, handle, status, version, manufacturer_name, subversion); +void LogMetricRemoteVersionInfo(uint16_t handle, uint8_t status, uint8_t version, + uint16_t manufacturer_name, uint16_t subversion) { + int ret = stats_write(BLUETOOTH_REMOTE_VERSION_INFO_REPORTED, handle, status, version, + manufacturer_name, subversion); if (ret < 0) { log::warn( - "Failed for handle {}, status {}, version {}, manufacturer_name {}, subversion {}, error " - "{}", - handle, - common::ToHexString(status), - common::ToHexString(version), - common::ToHexString(manufacturer_name), - common::ToHexString(subversion), - ret); + "Failed for handle {}, status {}, version {}, manufacturer_name {}, subversion {}, " + "error " + "{}", + handle, common::ToHexString(status), common::ToHexString(version), + common::ToHexString(manufacturer_name), common::ToHexString(subversion), ret); } } -void LogMetricA2dpAudioUnderrunEvent( - const Address& address, uint64_t encoding_interval_millis, int num_missing_pcm_bytes) { +void LogMetricA2dpAudioUnderrunEvent(const Address& address, uint64_t encoding_interval_millis, + int num_missing_pcm_bytes) { int metric_id = 0; if (!address.IsEmpty()) { metric_id = MetricIdManager::GetInstance().AllocateId(address); } int64_t encoding_interval_nanos = encoding_interval_millis * 1000000; - int ret = stats_write( - BLUETOOTH_A2DP_AUDIO_UNDERRUN_REPORTED, byteField, encoding_interval_nanos, num_missing_pcm_bytes, metric_id); + int ret = stats_write(BLUETOOTH_A2DP_AUDIO_UNDERRUN_REPORTED, byteField, encoding_interval_nanos, + num_missing_pcm_bytes, metric_id); if (ret < 0) { - log::warn( - "Failed for {}, encoding_interval_nanos {}, num_missing_pcm_bytes {}, error {}", - address, - encoding_interval_nanos, - num_missing_pcm_bytes, - ret); + log::warn("Failed for {}, encoding_interval_nanos {}, num_missing_pcm_bytes {}, error {}", + address, encoding_interval_nanos, num_missing_pcm_bytes, ret); } } -void LogMetricA2dpAudioOverrunEvent( - const Address& address, - uint64_t encoding_interval_millis, - int num_dropped_buffers, - int num_dropped_encoded_frames, - int num_dropped_encoded_bytes) { +void LogMetricA2dpAudioOverrunEvent(const Address& address, uint64_t encoding_interval_millis, + int num_dropped_buffers, int num_dropped_encoded_frames, + int num_dropped_encoded_bytes) { int metric_id = 0; if (!address.IsEmpty()) { metric_id = MetricIdManager::GetInstance().AllocateId(address); } int64_t encoding_interval_nanos = encoding_interval_millis * 1000000; - int ret = stats_write( - BLUETOOTH_A2DP_AUDIO_OVERRUN_REPORTED, - byteField, - encoding_interval_nanos, - num_dropped_buffers, - num_dropped_encoded_frames, - num_dropped_encoded_bytes, - metric_id); + int ret = stats_write(BLUETOOTH_A2DP_AUDIO_OVERRUN_REPORTED, byteField, encoding_interval_nanos, + num_dropped_buffers, num_dropped_encoded_frames, num_dropped_encoded_bytes, + metric_id); if (ret < 0) { log::warn( - "Failed to log for {}, encoding_interval_nanos {}, num_dropped_buffers {}, " - "num_dropped_encoded_frames {}, num_dropped_encoded_bytes {}, error {}", - address, - encoding_interval_nanos, - num_dropped_buffers, - num_dropped_encoded_frames, - num_dropped_encoded_bytes, - ret); + "Failed to log for {}, encoding_interval_nanos {}, num_dropped_buffers {}, " + "num_dropped_encoded_frames {}, num_dropped_encoded_bytes {}, error {}", + address, encoding_interval_nanos, num_dropped_buffers, num_dropped_encoded_frames, + num_dropped_encoded_bytes, ret); } } @@ -186,30 +151,20 @@ void LogMetricA2dpPlaybackEvent(const Address& address, int playback_state, int metric_id = MetricIdManager::GetInstance().AllocateId(address); } - int ret = stats_write(BLUETOOTH_A2DP_PLAYBACK_STATE_CHANGED, byteField, playback_state, audio_coding_mode, metric_id); + int ret = stats_write(BLUETOOTH_A2DP_PLAYBACK_STATE_CHANGED, byteField, playback_state, + audio_coding_mode, metric_id); if (ret < 0) { - log::warn( - "Failed to log for {}, playback_state {}, audio_coding_mode {},error {}", - address, - playback_state, - audio_coding_mode, - ret); + log::warn("Failed to log for {}, playback_state {}, audio_coding_mode {},error {}", address, + playback_state, audio_coding_mode, ret); } } void LogMetricA2dpSessionMetricsEvent( - const hci::Address& /* address */, - int64_t /* audio_duration_ms */, - int /* media_timer_min_ms */, - int /* media_timer_max_ms */, - int /* media_timer_avg_ms */, - int /* total_scheduling_count */, - int /* buffer_overruns_max_count */, - int /* buffer_overruns_total */, - float /* buffer_underruns_average */, - int /* buffer_underruns_count */, - int64_t codec_index, - bool /* is_a2dp_offload */) { + const hci::Address& /* address */, int64_t /* audio_duration_ms */, + int /* media_timer_min_ms */, int /* media_timer_max_ms */, int /* media_timer_avg_ms */, + int /* total_scheduling_count */, int /* buffer_overruns_max_count */, + int /* buffer_overruns_total */, float /* buffer_underruns_average */, + int /* buffer_underruns_count */, int64_t codec_index, bool /* is_a2dp_offload */) { char const* metric_id = nullptr; switch (codec_index) { case BTAV_A2DP_CODEC_INDEX_SOURCE_SBC: @@ -237,131 +192,85 @@ void LogMetricA2dpSessionMetricsEvent( android::expresslog::Counter::logIncrement(metric_id); } -void LogMetricHfpPacketLossStats( - const Address& /* address */, - int /* num_decoded_frames */, - double /* packet_loss_ratio */, - uint16_t /* codec_type */) {} +void LogMetricHfpPacketLossStats(const Address& /* address */, int /* num_decoded_frames */, + double /* packet_loss_ratio */, uint16_t /* codec_type */) {} -void LogMetricMmcTranscodeRttStats( - int /*maximum_rtt*/, - double /*mean_rtt*/, - int /*num_requests*/, - int /*codec_type*/) {} +void LogMetricMmcTranscodeRttStats(int /*maximum_rtt*/, double /*mean_rtt*/, int /*num_requests*/, + int /*codec_type*/) {} -void LogMetricReadRssiResult(const Address& address, uint16_t handle, uint32_t cmd_status, int8_t rssi) { +void LogMetricReadRssiResult(const Address& address, uint16_t handle, uint32_t cmd_status, + int8_t rssi) { int metric_id = 0; if (!address.IsEmpty()) { metric_id = MetricIdManager::GetInstance().AllocateId(address); } - int ret = stats_write(BLUETOOTH_DEVICE_RSSI_REPORTED, byteField, handle, cmd_status, rssi, metric_id); + int ret = stats_write(BLUETOOTH_DEVICE_RSSI_REPORTED, byteField, handle, cmd_status, rssi, + metric_id); if (ret < 0) { - log::warn( - "Failed for {}, handle {}, status {}, rssi {} dBm, error {}", - address, - handle, - common::ToHexString(cmd_status), - rssi, - ret); + log::warn("Failed for {}, handle {}, status {}, rssi {} dBm, error {}", address, handle, + common::ToHexString(cmd_status), rssi, ret); } } -void LogMetricReadFailedContactCounterResult( - const Address& address, uint16_t handle, uint32_t cmd_status, int32_t failed_contact_counter) { +void LogMetricReadFailedContactCounterResult(const Address& address, uint16_t handle, + uint32_t cmd_status, int32_t failed_contact_counter) { int metric_id = 0; if (!address.IsEmpty()) { metric_id = MetricIdManager::GetInstance().AllocateId(address); } - int ret = stats_write( - BLUETOOTH_DEVICE_FAILED_CONTACT_COUNTER_REPORTED, - byteField, - handle, - cmd_status, - failed_contact_counter, - metric_id); + int ret = stats_write(BLUETOOTH_DEVICE_FAILED_CONTACT_COUNTER_REPORTED, byteField, handle, + cmd_status, failed_contact_counter, metric_id); if (ret < 0) { - log::warn( - "Failed for {}, handle {}, status {}, failed_contact_counter {} packets, error {}", - address, - handle, - common::ToHexString(cmd_status), - failed_contact_counter, - ret); + log::warn("Failed for {}, handle {}, status {}, failed_contact_counter {} packets, error {}", + address, handle, common::ToHexString(cmd_status), failed_contact_counter, ret); } } -void LogMetricReadTxPowerLevelResult( - const Address& address, uint16_t handle, uint32_t cmd_status, int32_t transmit_power_level) { +void LogMetricReadTxPowerLevelResult(const Address& address, uint16_t handle, uint32_t cmd_status, + int32_t transmit_power_level) { int metric_id = 0; if (!address.IsEmpty()) { metric_id = MetricIdManager::GetInstance().AllocateId(address); } - int ret = stats_write( - BLUETOOTH_DEVICE_TX_POWER_LEVEL_REPORTED, byteField, handle, cmd_status, transmit_power_level, metric_id); + int ret = stats_write(BLUETOOTH_DEVICE_TX_POWER_LEVEL_REPORTED, byteField, handle, cmd_status, + transmit_power_level, metric_id); if (ret < 0) { - log::warn( - "Failed for {}, handle {}, status {}, transmit_power_level {} packets, error {}", - address, - handle, - common::ToHexString(cmd_status), - transmit_power_level, - ret); + log::warn("Failed for {}, handle {}, status {}, transmit_power_level {} packets, error {}", + address, handle, common::ToHexString(cmd_status), transmit_power_level, ret); } } -void LogMetricSmpPairingEvent( - const Address& address, uint16_t smp_cmd, android::bluetooth::DirectionEnum direction, uint16_t smp_fail_reason) { +void LogMetricSmpPairingEvent(const Address& address, uint16_t smp_cmd, + android::bluetooth::DirectionEnum direction, + uint16_t smp_fail_reason) { int metric_id = 0; if (!address.IsEmpty()) { metric_id = MetricIdManager::GetInstance().AllocateId(address); } - int ret = - stats_write(BLUETOOTH_SMP_PAIRING_EVENT_REPORTED, byteField, smp_cmd, direction, smp_fail_reason, metric_id); + int ret = stats_write(BLUETOOTH_SMP_PAIRING_EVENT_REPORTED, byteField, smp_cmd, direction, + smp_fail_reason, metric_id); if (ret < 0) { - log::warn( - "Failed for {}, smp_cmd {}, direction {}, smp_fail_reason {}, error {}", - address, - common::ToHexString(smp_cmd), - direction, - common::ToHexString(smp_fail_reason), - ret); + log::warn("Failed for {}, smp_cmd {}, direction {}, smp_fail_reason {}, error {}", address, + common::ToHexString(smp_cmd), direction, common::ToHexString(smp_fail_reason), ret); } } -void LogMetricClassicPairingEvent( - const Address& address, - uint16_t handle, - uint32_t hci_cmd, - uint16_t hci_event, - uint16_t cmd_status, - uint16_t reason_code, - int64_t event_value) { +void LogMetricClassicPairingEvent(const Address& address, uint16_t handle, uint32_t hci_cmd, + uint16_t hci_event, uint16_t cmd_status, uint16_t reason_code, + int64_t event_value) { int metric_id = 0; if (!address.IsEmpty()) { metric_id = MetricIdManager::GetInstance().AllocateId(address); } - int ret = stats_write( - BLUETOOTH_CLASSIC_PAIRING_EVENT_REPORTED, - byteField, - handle, - hci_cmd, - hci_event, - cmd_status, - reason_code, - event_value, - metric_id); + int ret = stats_write(BLUETOOTH_CLASSIC_PAIRING_EVENT_REPORTED, byteField, handle, hci_cmd, + hci_event, cmd_status, reason_code, event_value, metric_id); if (ret < 0) { log::warn( - "Failed for {}, handle {}, hci_cmd {}, hci_event {}, cmd_status {}, reason {}, event_value " - "{}, error {}", - address, - handle, - common::ToHexString(hci_cmd), - common::ToHexString(hci_event), - common::ToHexString(cmd_status), - common::ToHexString(reason_code), - event_value, - ret); + "Failed for {}, handle {}, hci_cmd {}, hci_event {}, cmd_status {}, reason {}, " + "event_value " + "{}, error {}", + address, handle, common::ToHexString(hci_cmd), common::ToHexString(hci_event), + common::ToHexString(cmd_status), common::ToHexString(reason_code), event_value, ret); } if (static_cast(hci_event) == EventCode::SIMPLE_PAIRING_COMPLETE) { @@ -369,212 +278,134 @@ void LogMetricClassicPairingEvent( } } -void LogMetricSdpAttribute( - const Address& address, - uint16_t protocol_uuid, - uint16_t attribute_id, - size_t attribute_size, - const char* attribute_value) { +void LogMetricSdpAttribute(const Address& address, uint16_t protocol_uuid, uint16_t attribute_id, + size_t attribute_size, const char* attribute_value) { int metric_id = 0; if (!address.IsEmpty()) { metric_id = MetricIdManager::GetInstance().AllocateId(address); } BytesField attribute_field(attribute_value, attribute_size); - int ret = - stats_write(BLUETOOTH_SDP_ATTRIBUTE_REPORTED, byteField, protocol_uuid, attribute_id, attribute_field, metric_id); + int ret = stats_write(BLUETOOTH_SDP_ATTRIBUTE_REPORTED, byteField, protocol_uuid, attribute_id, + attribute_field, metric_id); if (ret < 0) { - log::warn( - "Failed for {}, protocol_uuid {}, attribute_id {}, error {}", - address, - common::ToHexString(protocol_uuid), - common::ToHexString(attribute_id), - ret); + log::warn("Failed for {}, protocol_uuid {}, attribute_id {}, error {}", address, + common::ToHexString(protocol_uuid), common::ToHexString(attribute_id), ret); } } -void LogMetricSocketConnectionState( - const Address& address, - int port, - int type, - android::bluetooth::SocketConnectionstateEnum connection_state, - int64_t tx_bytes, - int64_t rx_bytes, - int uid, - int server_port, - android::bluetooth::SocketRoleEnum socket_role) { +void LogMetricSocketConnectionState(const Address& address, int port, int type, + android::bluetooth::SocketConnectionstateEnum connection_state, + int64_t tx_bytes, int64_t rx_bytes, int uid, int server_port, + android::bluetooth::SocketRoleEnum socket_role) { int metric_id = 0; if (!address.IsEmpty()) { metric_id = MetricIdManager::GetInstance().AllocateId(address); } - int ret = stats_write( - BLUETOOTH_SOCKET_CONNECTION_STATE_CHANGED, - byteField, - port, - type, - connection_state, - tx_bytes, - rx_bytes, - uid, - server_port, - socket_role, - metric_id); + int ret = stats_write(BLUETOOTH_SOCKET_CONNECTION_STATE_CHANGED, byteField, port, type, + connection_state, tx_bytes, rx_bytes, uid, server_port, socket_role, + metric_id); if (ret < 0) { log::warn( - "Failed for {}, port {}, type {}, state {}, tx_bytes {}, rx_bytes {}, uid {}, server_port " - "{}, socket_role {}, error {}", - address, - port, - type, - connection_state, - tx_bytes, - rx_bytes, - uid, - server_port, - socket_role, - ret); + "Failed for {}, port {}, type {}, state {}, tx_bytes {}, rx_bytes {}, uid {}, " + "server_port " + "{}, socket_role {}, error {}", + address, port, type, connection_state, tx_bytes, rx_bytes, uid, server_port, + socket_role, ret); } } -void LogMetricManufacturerInfo( - const Address& address, - android::bluetooth::AddressTypeEnum address_type, - android::bluetooth::DeviceInfoSrcEnum source_type, - const std::string& source_name, - const std::string& manufacturer, - const std::string& model, - const std::string& hardware_version, - const std::string& software_version) { +void LogMetricManufacturerInfo(const Address& address, + android::bluetooth::AddressTypeEnum address_type, + android::bluetooth::DeviceInfoSrcEnum source_type, + const std::string& source_name, const std::string& manufacturer, + const std::string& model, const std::string& hardware_version, + const std::string& software_version) { int metric_id = 0; if (!address.IsEmpty()) { metric_id = MetricIdManager::GetInstance().AllocateId(address); } - int ret = stats_write( - BLUETOOTH_DEVICE_INFO_REPORTED, - byteField, - source_type, - source_name.c_str(), - manufacturer.c_str(), - model.c_str(), - hardware_version.c_str(), - software_version.c_str(), - metric_id, - address_type, - address.address[5], - address.address[4], - address.address[3]); + int ret = stats_write(BLUETOOTH_DEVICE_INFO_REPORTED, byteField, source_type, source_name.c_str(), + manufacturer.c_str(), model.c_str(), hardware_version.c_str(), + software_version.c_str(), metric_id, address_type, address.address[5], + address.address[4], address.address[3]); if (ret < 0) { log::warn( - "Failed for {}, source_type {}, source_name {}, manufacturer {}, model {}, " - "hardware_version {}, software_version {}, MAC address type {} MAC address prefix {} {} " - "{}, error {}", - address, - source_type, - source_name, - manufacturer, - model, - hardware_version, - software_version, - address_type, - address.address[5], - address.address[4], - address.address[3], - ret); + "Failed for {}, source_type {}, source_name {}, manufacturer {}, model {}, " + "hardware_version {}, software_version {}, MAC address type {} MAC address prefix {} " + "{} " + "{}, error {}", + address, source_type, source_name, manufacturer, model, hardware_version, + software_version, address_type, address.address[5], address.address[4], + address.address[3], ret); } } -void LogMetricBluetoothHalCrashReason( - const Address& address, - uint32_t error_code, - uint32_t vendor_error_code) { - int ret = - stats_write(BLUETOOTH_HAL_CRASH_REASON_REPORTED, 0 /* metric_id */, byteField, error_code, vendor_error_code); +void LogMetricBluetoothHalCrashReason(const Address& address, uint32_t error_code, + uint32_t vendor_error_code) { + int ret = stats_write(BLUETOOTH_HAL_CRASH_REASON_REPORTED, 0 /* metric_id */, byteField, + error_code, vendor_error_code); if (ret < 0) { - log::warn( - "Failed for {}, error_code {}, vendor_error_code {}, error {}", - address, - common::ToHexString(error_code), - common::ToHexString(vendor_error_code), - ret); + log::warn("Failed for {}, error_code {}, vendor_error_code {}, error {}", address, + common::ToHexString(error_code), common::ToHexString(vendor_error_code), ret); } } void LogMetricBluetoothLocalSupportedFeatures(uint32_t page_num, uint64_t features) { - int ret = stats_write( - BLUETOOTH_LOCAL_SUPPORTED_FEATURES_REPORTED, page_num, static_cast(features)); + int ret = stats_write(BLUETOOTH_LOCAL_SUPPORTED_FEATURES_REPORTED, page_num, + static_cast(features)); if (ret < 0) { log::warn( - "Failed for LogMetricBluetoothLocalSupportedFeatures, page_num {}, features {}, error {}", - page_num, - features, - ret); + "Failed for LogMetricBluetoothLocalSupportedFeatures, page_num {}, features {}, error " + "{}", + page_num, features, ret); } } -void LogMetricBluetoothLocalVersions( - uint32_t lmp_manufacturer_name, - uint8_t lmp_version, - uint32_t lmp_subversion, - uint8_t hci_version, - uint32_t hci_revision) { - int ret = stats_write( - BLUETOOTH_LOCAL_VERSIONS_REPORTED, - static_cast(lmp_manufacturer_name), - static_cast(lmp_version), - static_cast(lmp_subversion), - static_cast(hci_version), - static_cast(hci_revision)); +void LogMetricBluetoothLocalVersions(uint32_t lmp_manufacturer_name, uint8_t lmp_version, + uint32_t lmp_subversion, uint8_t hci_version, + uint32_t hci_revision) { + int ret = stats_write(BLUETOOTH_LOCAL_VERSIONS_REPORTED, + static_cast(lmp_manufacturer_name), + static_cast(lmp_version), static_cast(lmp_subversion), + static_cast(hci_version), static_cast(hci_revision)); if (ret < 0) { log::warn( - "Failed for LogMetricBluetoothLocalVersions, lmp_manufacturer_name {}, lmp_version {}, " - "lmp_subversion {}, hci_version {}, hci_revision {}, error {}", - lmp_manufacturer_name, - lmp_version, - lmp_subversion, - hci_version, - hci_revision, - ret); + "Failed for LogMetricBluetoothLocalVersions, lmp_manufacturer_name {}, lmp_version {}, " + "lmp_subversion {}, hci_version {}, hci_revision {}, error {}", + lmp_manufacturer_name, lmp_version, lmp_subversion, hci_version, hci_revision, ret); } } -void LogMetricBluetoothDisconnectionReasonReported( - uint32_t reason, const Address& address, uint32_t connection_handle) { +void LogMetricBluetoothDisconnectionReasonReported(uint32_t reason, const Address& address, + uint32_t connection_handle) { int metric_id = 0; if (!address.IsEmpty()) { metric_id = MetricIdManager::GetInstance().AllocateId(address); } - int ret = stats_write(BLUETOOTH_DISCONNECTION_REASON_REPORTED, reason, metric_id, connection_handle); + int ret = stats_write(BLUETOOTH_DISCONNECTION_REASON_REPORTED, reason, metric_id, + connection_handle); if (ret < 0) { log::warn( - "Failed for LogMetricBluetoothDisconnectionReasonReported, reason {}, metric_id {}, " - "connection_handle {}, error {}", - reason, - metric_id, - connection_handle, - ret); + "Failed for LogMetricBluetoothDisconnectionReasonReported, reason {}, metric_id {}, " + "connection_handle {}, error {}", + reason, metric_id, connection_handle, ret); } } -void LogMetricBluetoothRemoteSupportedFeatures( - const Address& address, uint32_t page, uint64_t features, uint32_t connection_handle) { +void LogMetricBluetoothRemoteSupportedFeatures(const Address& address, uint32_t page, + uint64_t features, uint32_t connection_handle) { int metric_id = 0; if (!address.IsEmpty()) { metric_id = MetricIdManager::GetInstance().AllocateId(address); } - int ret = stats_write( - BLUETOOTH_REMOTE_SUPPORTED_FEATURES_REPORTED, - metric_id, - page, - static_cast(features), - connection_handle); + int ret = stats_write(BLUETOOTH_REMOTE_SUPPORTED_FEATURES_REPORTED, metric_id, page, + static_cast(features), connection_handle); if (ret < 0) { log::warn( - "Failed for LogMetricBluetoothRemoteSupportedFeatures, metric_id {}, page {}, features {}, " - "connection_handle {}, error {}", - metric_id, - page, - features, - connection_handle, - ret); + "Failed for LogMetricBluetoothRemoteSupportedFeatures, metric_id {}, page {}, features " + "{}, " + "connection_handle {}, error {}", + metric_id, page, features, connection_handle, ret); } } @@ -586,13 +417,12 @@ void LogMetricBluetoothCodePathCounterMetrics(int32_t key, int64_t count) { } void LogMetricBluetoothLEConnectionMetricEvent( - const Address& address, - android::bluetooth::le::LeConnectionOriginType origin_type, - android::bluetooth::le::LeConnectionType connection_type, - android::bluetooth::le::LeConnectionState transaction_state, - std::vector>& argument_list) { + const Address& address, android::bluetooth::le::LeConnectionOriginType origin_type, + android::bluetooth::le::LeConnectionType connection_type, + android::bluetooth::le::LeConnectionState transaction_state, + std::vector>& argument_list) { bluetooth::metrics::MetricsCollector::GetLEConnectionMetricsCollector()->AddStateChangedEvent( - address, origin_type, connection_type, transaction_state, argument_list); + address, origin_type, connection_type, transaction_state, argument_list); } void LogMetricBluetoothLEConnection(os::LEConnectionSessionOptions session_options) { @@ -600,26 +430,20 @@ void LogMetricBluetoothLEConnection(os::LEConnectionSessionOptions session_optio if (!session_options.remote_address.IsEmpty()) { metric_id = MetricIdManager::GetInstance().AllocateId(session_options.remote_address); } - int ret = stats_write( - BLUETOOTH_LE_SESSION_CONNECTED, - session_options.acl_connection_state, - session_options.origin_type, - session_options.transaction_type, - session_options.transaction_state, - session_options.latency, - metric_id, - session_options.app_uid, - session_options.acl_latency, - session_options.status, - session_options.is_cancelled); + int ret = stats_write(BLUETOOTH_LE_SESSION_CONNECTED, session_options.acl_connection_state, + session_options.origin_type, session_options.transaction_type, + session_options.transaction_state, session_options.latency, metric_id, + session_options.app_uid, session_options.acl_latency, + session_options.status, session_options.is_cancelled); if (ret < 0) { log::warn( - "Failed BluetoothLeSessionConnected - Address: {}, ACL Connection State: {}, Origin Type: " - "{}", - session_options.remote_address, - common::ToHexString(session_options.acl_connection_state), - common::ToHexString(session_options.origin_type)); + "Failed BluetoothLeSessionConnected - Address: {}, ACL Connection State: {}, Origin " + "Type: " + "{}", + session_options.remote_address, + common::ToHexString(session_options.acl_connection_state), + common::ToHexString(session_options.origin_type)); } } diff --git a/system/gd/os/android/parameter_provider.cc b/system/gd/os/android/parameter_provider.cc index f4d4751cf80..5f137a02529 100644 --- a/system/gd/os/android/parameter_provider.cc +++ b/system/gd/os/android/parameter_provider.cc @@ -83,16 +83,15 @@ void ParameterProvider::OverrideSnoozLogFilePath(const std::string& path) { } // Android doesn't have a need for the sysprops module -std::string ParameterProvider::SyspropsFilePath() { - return ""; -} +std::string ParameterProvider::SyspropsFilePath() { return ""; } bluetooth_keystore::BluetoothKeystoreInterface* ParameterProvider::GetBtKeystoreInterface() { std::lock_guard lock(parameter_mutex); return bt_keystore_interface; } -void ParameterProvider::SetBtKeystoreInterface(bluetooth_keystore::BluetoothKeystoreInterface* bt_keystore) { +void ParameterProvider::SetBtKeystoreInterface( + bluetooth_keystore::BluetoothKeystoreInterface* bt_keystore) { std::lock_guard lock(parameter_mutex); bt_keystore_interface = bt_keystore; } diff --git a/system/gd/os/android/system_properties.cc b/system/gd/os/android/system_properties.cc index 4796932a4b9..d7dc9e918af 100644 --- a/system/gd/os/android/system_properties.cc +++ b/system/gd/os/android/system_properties.cc @@ -39,10 +39,8 @@ std::optional GetSystemProperty(const std::string& property) { bool SetSystemProperty(const std::string& property, const std::string& value) { if (value.size() >= PROPERTY_VALUE_MAX) { - log::error( - "Property value's maximum size is {}, but {} chars were given", - PROPERTY_VALUE_MAX - 1, - value.size()); + log::error("Property value's maximum size is {}, but {} chars were given", + PROPERTY_VALUE_MAX - 1, value.size()); return false; } auto ret = property_set(property.c_str(), value.c_str()); @@ -75,10 +73,8 @@ int GetAndroidVendorReleaseVersion() { log::info("ro.vendor.build.version.release_or_codename does not exist"); return 0; } - log::info( - "ro.vendor.build.version.release_or_codename='{}', length={}", - value->c_str(), - value->length()); + log::info("ro.vendor.build.version.release_or_codename='{}', length={}", value->c_str(), + value->length()); auto int_value = common::Int64FromString(*value); if (int_value) { return static_cast(*int_value); @@ -107,9 +103,7 @@ int GetAndroidVendorReleaseVersion() { } } -bool ClearSystemPropertiesForHost() { - return false; -} +bool ClearSystemPropertiesForHost() { return false; } } // namespace os } // namespace bluetooth diff --git a/system/gd/os/android/wakelock_native.cc b/system/gd/os/android/wakelock_native.cc index 58713e6fba2..d34fa94cabb 100644 --- a/system/gd/os/android/wakelock_native.cc +++ b/system/gd/os/android/wakelock_native.cc @@ -80,12 +80,10 @@ void WakelockNative::Initialize() { log::info("Initializing native wake locks"); const std::string suspendInstance = std::string() + ISystemSuspend::descriptor + "/default"; pimpl_->suspend_service = ISystemSuspend::fromBinder( - ndk::SpAIBinder(AServiceManager_waitForService(suspendInstance.c_str()))); + ndk::SpAIBinder(AServiceManager_waitForService(suspendInstance.c_str()))); log::assert_that(pimpl_->suspend_service != nullptr, "Cannot get ISystemSuspend service"); - AIBinder_linkToDeath( - pimpl_->suspend_service->asBinder().get(), - pimpl_->suspend_death_recipient.get(), - static_cast(&pimpl_->onDeath)); + AIBinder_linkToDeath(pimpl_->suspend_service->asBinder().get(), + pimpl_->suspend_death_recipient.get(), static_cast(&pimpl_->onDeath)); } WakelockNative::StatusCode WakelockNative::Acquire(const std::string& lock_name) { @@ -99,8 +97,8 @@ WakelockNative::StatusCode WakelockNative::Acquire(const std::string& lock_name) return StatusCode::SUCCESS; } - auto status = pimpl_->suspend_service->acquireWakeLock( - WakeLockType::PARTIAL, lock_name, &pimpl_->current_wakelock); + auto status = pimpl_->suspend_service->acquireWakeLock(WakeLockType::PARTIAL, lock_name, + &pimpl_->current_wakelock); if (!pimpl_->current_wakelock) { log::error("wake lock not acquired: {}", status.getDescription()); return StatusCode::NATIVE_API_ERROR; @@ -128,10 +126,9 @@ void WakelockNative::CleanUp() { } if (pimpl_->suspend_service) { log::info("Unlink death recipient"); - AIBinder_unlinkToDeath( - pimpl_->suspend_service->asBinder().get(), - pimpl_->suspend_death_recipient.get(), - static_cast(&pimpl_->onDeath)); + AIBinder_unlinkToDeath(pimpl_->suspend_service->asBinder().get(), + pimpl_->suspend_death_recipient.get(), + static_cast(&pimpl_->onDeath)); pimpl_->suspend_service = nullptr; } } diff --git a/system/gd/os/android/wakelock_native_test.cc b/system/gd/os/android/wakelock_native_test.cc index 66c2204e306..ad17fa67773 100644 --- a/system/gd/os/android/wakelock_native_test.cc +++ b/system/gd/os/android/wakelock_native_test.cc @@ -49,7 +49,7 @@ static std::unique_ptr> acquire_promise = nullptr; static std::unique_ptr> release_promise = nullptr; class PromiseFutureContext { - public: +public: static void FulfilPromise(std::unique_ptr>& promise) { std::lock_guard lock_guard(mutex); if (promise != nullptr) { @@ -59,7 +59,8 @@ class PromiseFutureContext { } } - explicit PromiseFutureContext(std::unique_ptr>& promise, bool expect_fulfillment) + explicit PromiseFutureContext(std::unique_ptr>& promise, + bool expect_fulfillment) : promise_(promise), expect_fulfillment_(expect_fulfillment) { std::lock_guard lock_guard(mutex); EXPECT_EQ(promise_, nullptr); @@ -78,14 +79,14 @@ class PromiseFutureContext { promise_ = nullptr; } - private: +private: std::unique_ptr>& promise_; bool expect_fulfillment_ = true; std::future future_; }; class WakelockCallback : public BnWakelockCallback { - public: +public: ScopedAStatus notifyAcquired() override { std::lock_guard lock_guard(mutex); net_acquired_count++; @@ -105,9 +106,9 @@ class WakelockCallback : public BnWakelockCallback { }; class SuspendCallback : public BnSuspendCallback { - public: - ScopedAStatus notifyWakeup( - bool /* success */, const std::vector& /* wakeup_reasons */) override { +public: + ScopedAStatus notifyWakeup(bool /* success */, + const std::vector& /* wakeup_reasons */) override { std::lock_guard lock_guard(mutex); fprintf(stderr, "notifyWakeup\n"); return ScopedAStatus::ok(); @@ -120,7 +121,7 @@ static std::shared_ptr suspend_callback = nullptr; static std::shared_ptr control_callback = nullptr; class WakelockNativeTest : public Test { - protected: +protected: void SetUp() override { ABinderProcess_setThreadPoolMaxThreadCount(1); ABinderProcess_startThreadPool(); @@ -147,8 +148,8 @@ class WakelockNativeTest : public Test { if (control_callback == nullptr) { control_callback = SharedRefBase::make(); bool is_registered = false; - ScopedAStatus status = - control_service_->registerWakelockCallback(control_callback, kTestWakelockName, &is_registered); + ScopedAStatus status = control_service_->registerWakelockCallback( + control_callback, kTestWakelockName, &is_registered); if (!is_registered || !status.isOk()) { FAIL() << "Fail to register wakeup callback"; } diff --git a/system/gd/os/chromeos/metrics.cc b/system/gd/os/chromeos/metrics.cc index 9e2116eac2d..8182d811e6b 100644 --- a/system/gd/os/chromeos/metrics.cc +++ b/system/gd/os/chromeos/metrics.cc @@ -29,244 +29,184 @@ namespace os { using bluetooth::hci::Address; -void LogMetricClassicPairingEvent( - const Address& address, - uint16_t handle, - uint32_t hci_cmd, - uint16_t hci_event, - uint16_t cmd_status, - uint16_t reason_code, - int64_t event_value) {} - -void LogMetricSocketConnectionState( - const Address& address, - int port, - int type, - android::bluetooth::SocketConnectionstateEnum connection_state, - int64_t tx_bytes, - int64_t rx_bytes, - int uid, - int server_port, - android::bluetooth::SocketRoleEnum socket_role) {} +void LogMetricClassicPairingEvent(const Address& address, uint16_t handle, uint32_t hci_cmd, + uint16_t hci_event, uint16_t cmd_status, uint16_t reason_code, + int64_t event_value) {} + +void LogMetricSocketConnectionState(const Address& address, int port, int type, + android::bluetooth::SocketConnectionstateEnum connection_state, + int64_t tx_bytes, int64_t rx_bytes, int uid, int server_port, + android::bluetooth::SocketRoleEnum socket_role) {} void LogMetricHciTimeoutEvent(uint32_t hci_cmd) {} -void LogMetricA2dpAudioUnderrunEvent( - const Address& address, uint64_t encoding_interval_millis, int num_missing_pcm_bytes) {} +void LogMetricA2dpAudioUnderrunEvent(const Address& address, uint64_t encoding_interval_millis, + int num_missing_pcm_bytes) {} -void LogMetricA2dpAudioOverrunEvent( - const Address& address, - uint64_t encoding_interval_millis, - int num_dropped_buffers, - int num_dropped_encoded_frames, - int num_dropped_encoded_bytes) { +void LogMetricA2dpAudioOverrunEvent(const Address& address, uint64_t encoding_interval_millis, + int num_dropped_buffers, int num_dropped_encoded_frames, + int num_dropped_encoded_bytes) { std::string boot_id; std::string addr_string; - if (!metrics::GetBootId(&boot_id)) return; + if (!metrics::GetBootId(&boot_id)) { + return; + } addr_string = address.ToString(); - log::debug( - "A2dpAudioOverrun: {}, {}, {}, {}, {}, {}", - boot_id, - address, - (long long unsigned)encoding_interval_millis, - num_dropped_buffers, - num_dropped_encoded_bytes, - num_dropped_encoded_bytes); + log::debug("A2dpAudioOverrun: {}, {}, {}, {}, {}, {}", boot_id, address, + (long long unsigned)encoding_interval_millis, num_dropped_buffers, + num_dropped_encoded_bytes, num_dropped_encoded_bytes); ::metrics::structured::events::bluetooth::BluetoothA2dpAudioOverrun() - .SetBootId(boot_id) - .SetDeviceId(addr_string) - .SetEncodingInterval(encoding_interval_millis) - .SetDroppedBuffers(num_dropped_buffers) - .SetDroppedFrames(num_dropped_encoded_frames) - .SetDroppedBytes(num_dropped_encoded_bytes) - .Record(); + .SetBootId(boot_id) + .SetDeviceId(addr_string) + .SetEncodingInterval(encoding_interval_millis) + .SetDroppedBuffers(num_dropped_buffers) + .SetDroppedFrames(num_dropped_encoded_frames) + .SetDroppedBytes(num_dropped_encoded_bytes) + .Record(); } -void LogMetricHfpPacketLossStats( - const Address& address, int num_decoded_frames, double packet_loss_ratio, uint16_t codec_type) { +void LogMetricHfpPacketLossStats(const Address& address, int num_decoded_frames, + double packet_loss_ratio, uint16_t codec_type) { std::string boot_id; std::string addr_string; - if (!metrics::GetBootId(&boot_id)) return; + if (!metrics::GetBootId(&boot_id)) { + return; + } addr_string = address.ToString(); - log::debug( - "HfpPacketLoss: {}, {}, {}, {:f}, {}", - boot_id, - address, - num_decoded_frames, - packet_loss_ratio, - codec_type); + log::debug("HfpPacketLoss: {}, {}, {}, {:f}, {}", boot_id, address, num_decoded_frames, + packet_loss_ratio, codec_type); ::metrics::structured::events::bluetooth::BluetoothHfpPacketLoss() - .SetBootId(boot_id) - .SetDeviceId(addr_string) - .SetDecodedFrames(num_decoded_frames) - .SetPacketLossRatio(packet_loss_ratio) - .SetCodecType(codec_type) - .Record(); + .SetBootId(boot_id) + .SetDeviceId(addr_string) + .SetDecodedFrames(num_decoded_frames) + .SetPacketLossRatio(packet_loss_ratio) + .SetCodecType(codec_type) + .Record(); } -void LogMetricMmcTranscodeRttStats( - int maximum_rtt, double mean_rtt, int num_requests, int codec_type) { +void LogMetricMmcTranscodeRttStats(int maximum_rtt, double mean_rtt, int num_requests, + int codec_type) { std::string boot_id; - if (!metrics::GetBootId(&boot_id)) return; + if (!metrics::GetBootId(&boot_id)) { + return; + } - log::debug( - "MmcTranscodeRttStats: {}, {}, {:f}, {}, {}", - boot_id, - maximum_rtt, - mean_rtt, - num_requests, - codec_type); + log::debug("MmcTranscodeRttStats: {}, {}, {:f}, {}, {}", boot_id, maximum_rtt, mean_rtt, + num_requests, codec_type); ::metrics::structured::events::bluetooth::BluetoothMmcTranscodeRtt() - .SetBootId(boot_id) - .SetMaximumRtt(maximum_rtt) - .SetMeanRtt(mean_rtt) - .SetNumRequests(num_requests) - .SetCodecType(codec_type) - .Record(); + .SetBootId(boot_id) + .SetMaximumRtt(maximum_rtt) + .SetMeanRtt(mean_rtt) + .SetNumRequests(num_requests) + .SetCodecType(codec_type) + .Record(); } -void LogMetricReadRssiResult( - const Address& address, uint16_t handle, uint32_t cmd_status, int8_t rssi) {} - -void LogMetricReadFailedContactCounterResult( - const Address& address, uint16_t handle, uint32_t cmd_status, int32_t failed_contact_counter) {} - -void LogMetricReadTxPowerLevelResult( - const Address& address, uint16_t handle, uint32_t cmd_status, int32_t transmit_power_level) {} - -void LogMetricRemoteVersionInfo( - uint16_t handle, - uint8_t status, - uint8_t version, - uint16_t manufacturer_name, - uint16_t subversion) {} - -void LogMetricLinkLayerConnectionEvent( - const Address* address, - uint32_t connection_handle, - android::bluetooth::DirectionEnum direction, - uint16_t link_type, - uint32_t hci_cmd, - uint16_t hci_event, - uint16_t hci_ble_event, - uint16_t cmd_status, - uint16_t reason_code) {} - -void LogMetricManufacturerInfo( - const Address& address, - android::bluetooth::AddressTypeEnum address_type, - android::bluetooth::DeviceInfoSrcEnum source_type, - const std::string& source_name, - const std::string& manufacturer, - const std::string& model, - const std::string& hardware_version, - const std::string& software_version) {} - -void LogMetricSdpAttribute( - const Address& address, - uint16_t protocol_uuid, - uint16_t attribute_id, - size_t attribute_size, - const char* attribute_value) {} - -void LogMetricSmpPairingEvent( - const Address& address, - uint16_t smp_cmd, - android::bluetooth::DirectionEnum direction, - uint16_t smp_fail_reason) {} +void LogMetricReadRssiResult(const Address& address, uint16_t handle, uint32_t cmd_status, + int8_t rssi) {} + +void LogMetricReadFailedContactCounterResult(const Address& address, uint16_t handle, + uint32_t cmd_status, int32_t failed_contact_counter) {} + +void LogMetricReadTxPowerLevelResult(const Address& address, uint16_t handle, uint32_t cmd_status, + int32_t transmit_power_level) {} + +void LogMetricRemoteVersionInfo(uint16_t handle, uint8_t status, uint8_t version, + uint16_t manufacturer_name, uint16_t subversion) {} + +void LogMetricLinkLayerConnectionEvent(const Address* address, uint32_t connection_handle, + android::bluetooth::DirectionEnum direction, + uint16_t link_type, uint32_t hci_cmd, uint16_t hci_event, + uint16_t hci_ble_event, uint16_t cmd_status, + uint16_t reason_code) {} + +void LogMetricManufacturerInfo(const Address& address, + android::bluetooth::AddressTypeEnum address_type, + android::bluetooth::DeviceInfoSrcEnum source_type, + const std::string& source_name, const std::string& manufacturer, + const std::string& model, const std::string& hardware_version, + const std::string& software_version) {} + +void LogMetricSdpAttribute(const Address& address, uint16_t protocol_uuid, uint16_t attribute_id, + size_t attribute_size, const char* attribute_value) {} + +void LogMetricSmpPairingEvent(const Address& address, uint16_t smp_cmd, + android::bluetooth::DirectionEnum direction, + uint16_t smp_fail_reason) {} void LogMetricA2dpPlaybackEvent(const Address& address, int playback_state, int audio_coding_mode) { } -void LogMetricA2dpSessionMetricsEvent( - const hci::Address& address, - int64_t audio_duration_ms, - int media_timer_min_ms, - int media_timer_max_ms, - int media_timer_avg_ms, - int total_scheduling_count, - int buffer_overruns_max_count, - int buffer_overruns_total, - float buffer_underruns_average, - int buffer_underruns_count, - int64_t codec_index, - bool is_a2dp_offload) { +void LogMetricA2dpSessionMetricsEvent(const hci::Address& address, int64_t audio_duration_ms, + int media_timer_min_ms, int media_timer_max_ms, + int media_timer_avg_ms, int total_scheduling_count, + int buffer_overruns_max_count, int buffer_overruns_total, + float buffer_underruns_average, int buffer_underruns_count, + int64_t codec_index, bool is_a2dp_offload) { std::string boot_id; std::string addr_string; - if (!metrics::GetBootId(&boot_id)) return; + if (!metrics::GetBootId(&boot_id)) { + return; + } addr_string = address.ToString(); - log::debug( - "A2dpSessionMetrics: {}, {}, {}, {}, {}, {}, {}, {}, {}, {:f}, {}, {}, {}", - boot_id, - address, - (long long int)audio_duration_ms, - media_timer_min_ms, - media_timer_max_ms, - media_timer_avg_ms, - total_scheduling_count, - buffer_overruns_max_count, - buffer_overruns_total, - buffer_underruns_average, - buffer_underruns_count, - codec_index, - is_a2dp_offload); + log::debug("A2dpSessionMetrics: {}, {}, {}, {}, {}, {}, {}, {}, {}, {:f}, {}, {}, {}", boot_id, + address, (long long int)audio_duration_ms, media_timer_min_ms, media_timer_max_ms, + media_timer_avg_ms, total_scheduling_count, buffer_overruns_max_count, + buffer_overruns_total, buffer_underruns_average, buffer_underruns_count, codec_index, + is_a2dp_offload); ::metrics::structured::events::bluetooth::BluetoothA2dpSession() - .SetBootId(boot_id) - .SetDeviceId(addr_string) - .SetAudioDuration(audio_duration_ms) - .SetMediaTimerMin(media_timer_min_ms) - .SetMediaTimerMax(media_timer_max_ms) - .SetMediaTimerAvg(media_timer_avg_ms) - .SetTotalSchedulingCount(total_scheduling_count) - .SetBufferOverrunsMaxCount(buffer_overruns_max_count) - .SetBufferOverrunsTotal(buffer_overruns_total) - .SetBufferUnderrunsAvg(buffer_underruns_average) - .SetBufferUnderrunsCount(buffer_underruns_count) - .SetCodecIndex(codec_index) - .SetIsA2dpOffload(is_a2dp_offload) - .Record(); + .SetBootId(boot_id) + .SetDeviceId(addr_string) + .SetAudioDuration(audio_duration_ms) + .SetMediaTimerMin(media_timer_min_ms) + .SetMediaTimerMax(media_timer_max_ms) + .SetMediaTimerAvg(media_timer_avg_ms) + .SetTotalSchedulingCount(total_scheduling_count) + .SetBufferOverrunsMaxCount(buffer_overruns_max_count) + .SetBufferOverrunsTotal(buffer_overruns_total) + .SetBufferUnderrunsAvg(buffer_underruns_average) + .SetBufferUnderrunsCount(buffer_underruns_count) + .SetCodecIndex(codec_index) + .SetIsA2dpOffload(is_a2dp_offload) + .Record(); } -void LogMetricBluetoothHalCrashReason( - const Address& address, uint32_t error_code, uint32_t vendor_error_code) {} +void LogMetricBluetoothHalCrashReason(const Address& address, uint32_t error_code, + uint32_t vendor_error_code) {} void LogMetricBluetoothLocalSupportedFeatures(uint32_t page_num, uint64_t features) {} -void LogMetricBluetoothLocalVersions( - uint32_t lmp_manufacturer_name, - uint8_t lmp_version, - uint32_t lmp_subversion, - uint8_t hci_version, - uint32_t hci_revision) {} +void LogMetricBluetoothLocalVersions(uint32_t lmp_manufacturer_name, uint8_t lmp_version, + uint32_t lmp_subversion, uint8_t hci_version, + uint32_t hci_revision) {} -void LogMetricBluetoothDisconnectionReasonReported( - uint32_t reason, const Address& address, uint32_t connection_handle) {} +void LogMetricBluetoothDisconnectionReasonReported(uint32_t reason, const Address& address, + uint32_t connection_handle) {} -void LogMetricBluetoothRemoteSupportedFeatures( - const Address& address, uint32_t page, uint64_t features, uint32_t connection_handle) {} +void LogMetricBluetoothRemoteSupportedFeatures(const Address& address, uint32_t page, + uint64_t features, uint32_t connection_handle) {} void LogMetricBluetoothCodePathCounterMetrics(int32_t key, int64_t count) {} void LogMetricBluetoothLEConnectionMetricEvent( - const Address& raw_address, - android::bluetooth::le::LeConnectionOriginType origin_type, - android::bluetooth::le::LeConnectionType connection_type, - android::bluetooth::le::LeConnectionState transaction_state, - std::vector>& argument_list) {} + const Address& raw_address, android::bluetooth::le::LeConnectionOriginType origin_type, + android::bluetooth::le::LeConnectionType connection_type, + android::bluetooth::le::LeConnectionState transaction_state, + std::vector>& argument_list) {} void LogMetricBluetoothLEConnection(os::LEConnectionSessionOptions /* session_options */) {} } // namespace os diff --git a/system/gd/os/chromeos/parameter_provider.cc b/system/gd/os/chromeos/parameter_provider.cc index 6d720329906..2302a68e119 100644 --- a/system/gd/os/chromeos/parameter_provider.cc +++ b/system/gd/os/chromeos/parameter_provider.cc @@ -97,17 +97,13 @@ bluetooth_keystore::BluetoothKeystoreInterface* ParameterProvider::GetBtKeystore } void ParameterProvider::SetBtKeystoreInterface( - bluetooth_keystore::BluetoothKeystoreInterface* bt_keystore) {} + bluetooth_keystore::BluetoothKeystoreInterface* bt_keystore) {} -bool ParameterProvider::IsCommonCriteriaMode() { - return false; -} +bool ParameterProvider::IsCommonCriteriaMode() { return false; } void ParameterProvider::SetCommonCriteriaMode(bool enable) {} -int ParameterProvider::GetCommonCriteriaConfigCompareResult() { - return 0b11; -} +int ParameterProvider::GetCommonCriteriaConfigCompareResult() { return 0b11; } void ParameterProvider::SetCommonCriteriaConfigCompareResult(int result) {} diff --git a/system/gd/os/chromeos/system_properties.cc b/system/gd/os/chromeos/system_properties.cc index c9d719f06f7..aef6dadcc11 100644 --- a/system/gd/os/chromeos/system_properties.cc +++ b/system/gd/os/chromeos/system_properties.cc @@ -28,7 +28,7 @@ std::mutex properties_mutex; // Properties set along with some default values for Floss. std::unordered_map properties = { - {"bluetooth.profile.avrcp.target.enabled", "true"}, + {"bluetooth.profile.avrcp.target.enabled", "true"}, }; } // namespace @@ -53,13 +53,9 @@ bool ClearSystemPropertiesForHost() { return true; } -bool IsRootCanalEnabled() { - return false; -} +bool IsRootCanalEnabled() { return false; } -int GetAndroidVendorReleaseVersion() { - return 0; -} +int GetAndroidVendorReleaseVersion() { return 0; } } // namespace os } // namespace bluetooth diff --git a/system/gd/os/chromeos/wakelock_native.cc b/system/gd/os/chromeos/wakelock_native.cc index d312938f5fd..8cf7f71fde4 100644 --- a/system/gd/os/chromeos/wakelock_native.cc +++ b/system/gd/os/chromeos/wakelock_native.cc @@ -30,9 +30,7 @@ namespace internal { struct WakelockNative::Impl {}; -void WakelockNative::Initialize() { - log::info("Linux native wakelock is not implemented"); -} +void WakelockNative::Initialize() { log::info("Linux native wakelock is not implemented"); } WakelockNative::StatusCode WakelockNative::Acquire(const std::string& lock_name) { log::info("Linux native wakelock is not implemented"); @@ -43,9 +41,7 @@ WakelockNative::StatusCode WakelockNative::Release(const std::string& lock_name) log::info("Linux native wakelock is not implemented"); return StatusCode::SUCCESS; } -void WakelockNative::CleanUp() { - log::info("Linux native wakelock is not implemented"); -} +void WakelockNative::CleanUp() { log::info("Linux native wakelock is not implemented"); } WakelockNative::WakelockNative() : pimpl_(std::make_unique()) {} diff --git a/system/gd/os/fake_timer/fake_timerfd.cc b/system/gd/os/fake_timer/fake_timerfd.cc index 54785b3d940..ea6dbabb242 100644 --- a/system/gd/os/fake_timer/fake_timerfd.cc +++ b/system/gd/os/fake_timer/fake_timerfd.cc @@ -26,7 +26,7 @@ namespace os { namespace fake_timer { class FakeTimerFd { - public: +public: int fd; bool active; uint64_t trigger_ms; @@ -53,11 +53,8 @@ int fake_timerfd_create(int /* clockid */, int /* flags */) { return fd; } -int fake_timerfd_settime( - int fd, - int /* flags */, - const struct itimerspec* new_value, - struct itimerspec* /* old_value */) { +int fake_timerfd_settime(int fd, int /* flags */, const struct itimerspec* new_value, + struct itimerspec* /* old_value */) { if (fake_timers.find(fd) == fake_timers.end()) { return -1; } @@ -134,13 +131,9 @@ void fake_timerfd_advance(uint64_t ms) { clock = new_clock; } -void fake_timerfd_cap_at(uint64_t ms) { - max_clock = ms; -} +void fake_timerfd_cap_at(uint64_t ms) { max_clock = ms; } -uint64_t fake_timerfd_get_clock() { - return clock; -} +uint64_t fake_timerfd_get_clock() { return clock; } } // namespace fake_timer } // namespace os diff --git a/system/gd/os/fake_timer/fake_timerfd.h b/system/gd/os/fake_timer/fake_timerfd.h index fc7940d8bcb..31a698aec96 100644 --- a/system/gd/os/fake_timer/fake_timerfd.h +++ b/system/gd/os/fake_timer/fake_timerfd.h @@ -26,7 +26,8 @@ namespace fake_timer { int fake_timerfd_create(int clockid, int flags); -int fake_timerfd_settime(int fd, int flags, const struct itimerspec* new_value, struct itimerspec* old_value); +int fake_timerfd_settime(int fd, int flags, const struct itimerspec* new_value, + struct itimerspec* old_value); int fake_timerfd_close(int fd); diff --git a/system/gd/os/files.h b/system/gd/os/files.h index 5802aa1e674..e10d792f621 100644 --- a/system/gd/os/files.h +++ b/system/gd/os/files.h @@ -29,26 +29,28 @@ bool FileExists(const std::string& path); // Rename file from |from| to |to| bool RenameFile(const std::string& from, const std::string& to); -// Implement ability to read a whole file from |path| into a C++ string, return std::nullopt on failure +// Implement ability to read a whole file from |path| into a C++ string, return std::nullopt on +// failure // // Do not use this with large files std::optional ReadSmallFile(const std::string& path); -// Implement ability to safely write to a file. This function is needed because of deficiencies in existing C++ file -// libraries, namely: +// Implement ability to safely write to a file. This function is needed because of deficiencies in +// existing C++ file libraries, namely: // - The ability to open and sync directories with storage media // - The ability to block and sync file to storage media // Return true on success, false on failure bool WriteToFile(const std::string& path, const std::string& data); // Remove file and print error message if failed -// Print error log when file is failed to be removed, hence user should make sure file exists before calling this -// Return true on success, false on failure (e.g. file not exist, failed to remove, etc) +// Print error log when file is failed to be removed, hence user should make sure file exists before +// calling this Return true on success, false on failure (e.g. file not exist, failed to remove, +// etc) bool RemoveFile(const std::string& path); // Returns created time_point of given file, return std::nullopt on failure -std::optional> FileCreatedTime( - const std::string& path); +std::optional> +FileCreatedTime(const std::string& path); } // namespace os } // namespace bluetooth \ No newline at end of file diff --git a/system/gd/os/fuzz/dev_null_queue.h b/system/gd/os/fuzz/dev_null_queue.h index 0b2d7c550a3..46f88d3fc4b 100644 --- a/system/gd/os/fuzz/dev_null_queue.h +++ b/system/gd/os/fuzz/dev_null_queue.h @@ -25,7 +25,7 @@ namespace fuzz { // Drops stuff you send it, and banishes it into the void. template class DevNullQueue { - public: +public: DevNullQueue(IQueueDequeue* queue, Handler* handler) : queue_(queue), handler_(handler) {} ~DevNullQueue() {} @@ -33,15 +33,11 @@ class DevNullQueue { queue_->RegisterDequeue(handler_, common::Bind(&DevNullQueue::Dump, common::Unretained(this))); } - void Stop() { - queue_->UnregisterDequeue(); - } + void Stop() { queue_->UnregisterDequeue(); } - void Dump() { - queue_->TryDequeue(); - } + void Dump() { queue_->TryDequeue(); } - private: +private: IQueueDequeue* queue_; Handler* handler_; }; diff --git a/system/gd/os/fuzz/fuzz_inject_queue.h b/system/gd/os/fuzz/fuzz_inject_queue.h index 2b9ebae966d..322faa0d573 100644 --- a/system/gd/os/fuzz/fuzz_inject_queue.h +++ b/system/gd/os/fuzz/fuzz_inject_queue.h @@ -24,19 +24,15 @@ namespace fuzz { template class FuzzInjectQueue { - public: +public: FuzzInjectQueue(IQueueEnqueue* queue, Handler* handler) : handler_(handler) { buffer_ = new EnqueueBuffer(queue); } - ~FuzzInjectQueue() { - delete buffer_; - } + ~FuzzInjectQueue() { delete buffer_; } - void Inject(std::unique_ptr data) { - buffer_->Enqueue(std::move(data), handler_); - } + void Inject(std::unique_ptr data) { buffer_->Enqueue(std::move(data), handler_); } - private: +private: EnqueueBuffer* buffer_; Handler* handler_; }; diff --git a/system/gd/os/handler.cc b/system/gd/os/handler.cc index 45446362464..f49236fde30 100644 --- a/system/gd/os/handler.cc +++ b/system/gd/os/handler.cc @@ -30,7 +30,8 @@ using common::OnceClosure; Handler::Handler(Thread* thread) : tasks_(new std::queue()), thread_(thread) { event_ = thread_->GetReactor()->NewEvent(); reactable_ = thread_->GetReactor()->Register( - event_->Id(), common::Bind(&Handler::handle_next_event, common::Unretained(this)), common::Closure()); + event_->Id(), common::Bind(&Handler::handle_next_event, common::Unretained(this)), + common::Closure()); } Handler::~Handler() { @@ -70,9 +71,8 @@ void Handler::Clear() { void Handler::WaitUntilStopped(std::chrono::milliseconds timeout) { log::assert_that(reactable_ == nullptr, "assert failed: reactable_ == nullptr"); - log::assert_that( - thread_->GetReactor()->WaitForUnregisteredReactable(timeout), - "assert failed: thread_->GetReactor()->WaitForUnregisteredReactable(timeout)"); + log::assert_that(thread_->GetReactor()->WaitForUnregisteredReactable(timeout), + "assert failed: thread_->GetReactor()->WaitForUnregisteredReactable(timeout)"); } void Handler::handle_next_event() { diff --git a/system/gd/os/handler.h b/system/gd/os/handler.h index 03f65e5d370..4bb75b86f4f 100644 --- a/system/gd/os/handler.h +++ b/system/gd/os/handler.h @@ -28,18 +28,19 @@ namespace bluetooth { namespace os { -// A message-queue style handler for reactor-based thread to handle incoming events from different threads. When it's -// constructed, it will register a reactable on the specified thread; when it's destroyed, it will unregister itself -// from the thread. +// A message-queue style handler for reactor-based thread to handle incoming events from different +// threads. When it's constructed, it will register a reactable on the specified thread; when it's +// destroyed, it will unregister itself from the thread. class Handler : public common::PostableContext { - public: +public: // Create and register a handler on given thread explicit Handler(Thread* thread); Handler(const Handler&) = delete; Handler& operator=(const Handler&) = delete; - // Unregister this handler from the thread and release resource. Unhandled events will be discarded and not executed. + // Unregister this handler from the thread and release resource. Unhandled events will be + // discarded and not executed. virtual ~Handler(); // Enqueue a closure to the queue of this handler @@ -58,7 +59,8 @@ class Handler : public common::PostableContext { template void CallOn(T* obj, Functor&& functor, Args&&... args) { - Post(common::BindOnce(std::forward(functor), common::Unretained(obj), std::forward(args)...)); + Post(common::BindOnce(std::forward(functor), common::Unretained(obj), + std::forward(args)...)); } template @@ -68,10 +70,8 @@ class Handler : public common::PostableContext { friend class RepeatingAlarm; - private: - inline bool was_cleared() const { - return tasks_ == nullptr; - }; +private: + inline bool was_cleared() const { return tasks_ == nullptr; } std::queue* tasks_; Thread* thread_; std::unique_ptr event_; diff --git a/system/gd/os/handler_unittest.cc b/system/gd/os/handler_unittest.cc index 04f634765be..0a06699c391 100644 --- a/system/gd/os/handler_unittest.cc +++ b/system/gd/os/handler_unittest.cc @@ -29,7 +29,7 @@ namespace os { namespace { class HandlerTest : public ::testing::Test { - protected: +protected: void SetUp() override { thread_ = new Thread("test_thread", Thread::Priority::NORMAL); handler_ = new Handler(thread_); @@ -43,21 +43,18 @@ class HandlerTest : public ::testing::Test { Thread* thread_; }; -TEST_F(HandlerTest, empty) { - handler_->Clear(); -} +TEST_F(HandlerTest, empty) { handler_->Clear(); } TEST_F(HandlerTest, post_task_invoked) { int val = 0; std::promise closure_ran; auto future = closure_ran.get_future(); common::OnceClosure closure = common::BindOnce( - [](int* val, std::promise closure_ran) { - *val = *val + 1; - closure_ran.set_value(); - }, - common::Unretained(&val), - std::move(closure_ran)); + [](int* val, std::promise closure_ran) { + *val = *val + 1; + closure_ran.set_value(); + }, + common::Unretained(&val), std::move(closure_ran)); handler_->Post(std::move(closure)); future.wait(); ASSERT_EQ(val, 1); @@ -73,20 +70,16 @@ TEST_F(HandlerTest, post_task_cleared) { std::promise closure_finished; auto closure_finished_future = closure_finished.get_future(); handler_->Post(common::BindOnce( - [](int* val, - std::promise closure_started, - std::future can_continue_future, - std::promise closure_finished) { - closure_started.set_value(); - *val = *val + 1; - can_continue_future.wait(); - closure_finished.set_value(); - }, - common::Unretained(&val), - std::move(closure_started), - std::move(can_continue_future), - std::move(closure_finished))); - handler_->Post(common::BindOnce([]() { ASSERT_TRUE(false); })); + [](int* val, std::promise closure_started, std::future can_continue_future, + std::promise closure_finished) { + closure_started.set_value(); + *val = *val + 1; + can_continue_future.wait(); + closure_finished.set_value(); + }, + common::Unretained(&val), std::move(closure_started), std::move(can_continue_future), + std::move(closure_finished))); + handler_->Post(common::BindOnce([]() { FAIL(); })); closure_started_future.wait(); handler_->Clear(); closure_can_continue.set_value(); @@ -110,7 +103,8 @@ TEST_F(HandlerTest, once_callback) { TEST_F(HandlerTest, callback_with_promise) { std::promise promise; auto future = promise.get_future(); - auto once_callback = common::BindOnce(&std::promise::set_value, common::Unretained(&promise)); + auto once_callback = + common::BindOnce(&std::promise::set_value, common::Unretained(&promise)); std::move(once_callback).Run(); future.wait(); handler_->Clear(); @@ -118,7 +112,7 @@ TEST_F(HandlerTest, callback_with_promise) { // For Death tests, all the threading needs to be done in the ASSERT_DEATH call class HandlerDeathTest : public ::testing::Test { - protected: +protected: void ThreadSetUp() { thread_ = new Thread("test_thread", Thread::Priority::NORMAL); handler_ = new Handler(thread_); diff --git a/system/gd/os/host/metrics.cc b/system/gd/os/host/metrics.cc index 29caef103d8..574598875a0 100644 --- a/system/gd/os/host/metrics.cc +++ b/system/gd/os/host/metrics.cc @@ -17,6 +17,7 @@ ******************************************************************************/ #include "os/metrics.h" + #include "os/log.h" namespace bluetooth { @@ -24,154 +25,108 @@ namespace os { using bluetooth::hci::Address; -void LogMetricClassicPairingEvent( - const Address& /* address */, - uint16_t /* handle */, - uint32_t /* hci_cmd */, - uint16_t /* hci_event */, - uint16_t /* cmd_status */, - uint16_t /* reason_code */, - int64_t /* event_value */) {} +void LogMetricClassicPairingEvent(const Address& /* address */, uint16_t /* handle */, + uint32_t /* hci_cmd */, uint16_t /* hci_event */, + uint16_t /* cmd_status */, uint16_t /* reason_code */, + int64_t /* event_value */) {} void LogMetricSocketConnectionState( - const Address& /* address */, - int /* port */, - int /* type */, - android::bluetooth::SocketConnectionstateEnum /* connection_state */, - int64_t /* tx_bytes */, - int64_t /* rx_bytes */, - int /* uid */, - int /* server_port */, - android::bluetooth::SocketRoleEnum /* socket_role */) {} + const Address& /* address */, int /* port */, int /* type */, + android::bluetooth::SocketConnectionstateEnum /* connection_state */, + int64_t /* tx_bytes */, int64_t /* rx_bytes */, int /* uid */, int /* server_port */, + android::bluetooth::SocketRoleEnum /* socket_role */) {} void LogMetricHciTimeoutEvent(uint32_t /* hci_cmd */) {} -void LogMetricA2dpAudioUnderrunEvent( - const Address& /* address */, - uint64_t /* encoding_interval_millis */, - int /* num_missing_pcm_bytes */) {} - -void LogMetricA2dpAudioOverrunEvent( - const Address& /* address */, - uint64_t /* encoding_interval_millis */, - int /* num_dropped_buffers */, - int /* num_dropped_encoded_frames */, - int /* num_dropped_encoded_bytes */) {} - -void LogMetricHfpPacketLossStats( - const Address& /* address */, - int /* num_decoded_frames */, - double /* packet_loss_ratio */, - uint16_t /* codec_type */) {} - -void LogMetricMmcTranscodeRttStats( - int /* maximum_rtt */, double /* mean_rtt */, int /* num_requests */, int /* codec_type */) {} - -void LogMetricReadRssiResult( - const Address& /* address */, - uint16_t /* handle */, - uint32_t /* cmd_status */, - int8_t /* rssi */) {} - -void LogMetricReadFailedContactCounterResult( - const Address& /* address */, - uint16_t /* handle */, - uint32_t /* cmd_status */, - int32_t /* failed_contact_counter */) {} - -void LogMetricReadTxPowerLevelResult( - const Address& /* address */, - uint16_t /* handle */, - uint32_t /* cmd_status */, - int32_t /* transmit_power_level */) {} - -void LogMetricRemoteVersionInfo( - uint16_t /* handle */, - uint8_t /* status */, - uint8_t /* version */, - uint16_t /* manufacturer_name */, - uint16_t /* subversion */) {} - -void LogMetricLinkLayerConnectionEvent( - const Address* /* address */, - uint32_t /* connection_handle */, - android::bluetooth::DirectionEnum /* direction */, - uint16_t /* link_type */, - uint32_t /* hci_cmd */, - uint16_t /* hci_event */, - uint16_t /* hci_ble_event */, - uint16_t /* cmd_status */, - uint16_t /* reason_code */) {} - -void LogMetricManufacturerInfo( - const Address& /* address */, - android::bluetooth::AddressTypeEnum /* address_type */, - android::bluetooth::DeviceInfoSrcEnum /* source_type */, - const std::string& /* source_name */, - const std::string& /* manufacturer */, - const std::string& /* model */, - const std::string& /* hardware_version */, - const std::string& /* software_version */) {} - -void LogMetricSdpAttribute( - const Address& /* address */, - uint16_t /* protocol_uuid */, - uint16_t /* attribute_id */, - size_t /* attribute_size */, - const char* /* attribute_value */) {} - -void LogMetricSmpPairingEvent( - const Address& /* address */, - uint16_t /* smp_cmd */, - android::bluetooth::DirectionEnum /* direction */, - uint16_t /* smp_fail_reason */) {} - -void LogMetricA2dpPlaybackEvent( - const Address& /* address */, int /* playback_state */, int /* audio_coding_mode */) {} +void LogMetricA2dpAudioUnderrunEvent(const Address& /* address */, + uint64_t /* encoding_interval_millis */, + int /* num_missing_pcm_bytes */) {} + +void LogMetricA2dpAudioOverrunEvent(const Address& /* address */, + uint64_t /* encoding_interval_millis */, + int /* num_dropped_buffers */, + int /* num_dropped_encoded_frames */, + int /* num_dropped_encoded_bytes */) {} + +void LogMetricHfpPacketLossStats(const Address& /* address */, int /* num_decoded_frames */, + double /* packet_loss_ratio */, uint16_t /* codec_type */) {} + +void LogMetricMmcTranscodeRttStats(int /* maximum_rtt */, double /* mean_rtt */, + int /* num_requests */, int /* codec_type */) {} + +void LogMetricReadRssiResult(const Address& /* address */, uint16_t /* handle */, + uint32_t /* cmd_status */, int8_t /* rssi */) {} + +void LogMetricReadFailedContactCounterResult(const Address& /* address */, uint16_t /* handle */, + uint32_t /* cmd_status */, + int32_t /* failed_contact_counter */) {} + +void LogMetricReadTxPowerLevelResult(const Address& /* address */, uint16_t /* handle */, + uint32_t /* cmd_status */, + int32_t /* transmit_power_level */) {} + +void LogMetricRemoteVersionInfo(uint16_t /* handle */, uint8_t /* status */, uint8_t /* version */, + uint16_t /* manufacturer_name */, uint16_t /* subversion */) {} + +void LogMetricLinkLayerConnectionEvent(const Address* /* address */, + uint32_t /* connection_handle */, + android::bluetooth::DirectionEnum /* direction */, + uint16_t /* link_type */, uint32_t /* hci_cmd */, + uint16_t /* hci_event */, uint16_t /* hci_ble_event */, + uint16_t /* cmd_status */, uint16_t /* reason_code */) {} + +void LogMetricManufacturerInfo(const Address& /* address */, + android::bluetooth::AddressTypeEnum /* address_type */, + android::bluetooth::DeviceInfoSrcEnum /* source_type */, + const std::string& /* source_name */, + const std::string& /* manufacturer */, + const std::string& /* model */, + const std::string& /* hardware_version */, + const std::string& /* software_version */) {} + +void LogMetricSdpAttribute(const Address& /* address */, uint16_t /* protocol_uuid */, + uint16_t /* attribute_id */, size_t /* attribute_size */, + const char* /* attribute_value */) {} + +void LogMetricSmpPairingEvent(const Address& /* address */, uint16_t /* smp_cmd */, + android::bluetooth::DirectionEnum /* direction */, + uint16_t /* smp_fail_reason */) {} + +void LogMetricA2dpPlaybackEvent(const Address& /* address */, int /* playback_state */, + int /* audio_coding_mode */) {} void LogMetricA2dpSessionMetricsEvent( - const Address& /* address */, - int64_t /* audio_duration_ms */, - int /* media_timer_min_ms */, - int /* media_timer_max_ms */, - int /* media_timer_avg_ms */, - int /* total_scheduling_count */, - int /* buffer_overruns_max_count */, - int /* buffer_overruns_total */, - float /* buffer_underruns_average */, - int /* buffer_underruns_count */, - int64_t /* codec_index */, - bool /* is_a2dp_offload */) {} - -void LogMetricBluetoothHalCrashReason( - const Address& /* address */, uint32_t /* error_code */, uint32_t /* vendor_error_code */) {} + const Address& /* address */, int64_t /* audio_duration_ms */, int /* media_timer_min_ms */, + int /* media_timer_max_ms */, int /* media_timer_avg_ms */, + int /* total_scheduling_count */, int /* buffer_overruns_max_count */, + int /* buffer_overruns_total */, float /* buffer_underruns_average */, + int /* buffer_underruns_count */, int64_t /* codec_index */, bool /* is_a2dp_offload */) {} + +void LogMetricBluetoothHalCrashReason(const Address& /* address */, uint32_t /* error_code */, + uint32_t /* vendor_error_code */) {} void LogMetricBluetoothLocalSupportedFeatures(uint32_t /* page_num */, uint64_t /* features */) {} -void LogMetricBluetoothLocalVersions( - uint32_t /* lmp_manufacturer_name */, - uint8_t /* lmp_version */, - uint32_t /* lmp_subversion */, - uint8_t /* hci_version */, - uint32_t /* hci_reversion */) {} +void LogMetricBluetoothLocalVersions(uint32_t /* lmp_manufacturer_name */, + uint8_t /* lmp_version */, uint32_t /* lmp_subversion */, + uint8_t /* hci_version */, uint32_t /* hci_reversion */) {} -void LogMetricBluetoothDisconnectionReasonReported( - uint32_t /* reason */, const Address& /* address */, uint32_t /* connection_handle */) {} +void LogMetricBluetoothDisconnectionReasonReported(uint32_t /* reason */, + const Address& /* address */, + uint32_t /* connection_handle */) {} -void LogMetricBluetoothRemoteSupportedFeatures( - const Address& /* address */, - uint32_t /* page */, - uint64_t /* features */, - uint32_t /* connection_handle */) {} +void LogMetricBluetoothRemoteSupportedFeatures(const Address& /* address */, uint32_t /* page */, + uint64_t /* features */, + uint32_t /* connection_handle */) {} void LogMetricBluetoothCodePathCounterMetrics(int32_t /* key */, int64_t /* count */) {} void LogMetricBluetoothLEConnectionMetricEvent( - const Address& /* address */, - android::bluetooth::le::LeConnectionOriginType /* origin_type */, - android::bluetooth::le::LeConnectionType /* connection_type */, - android::bluetooth::le::LeConnectionState /* transaction_state */, - std::vector>& /* argument_list */) {} + const Address& /* address */, + android::bluetooth::le::LeConnectionOriginType /* origin_type */, + android::bluetooth::le::LeConnectionType /* connection_type */, + android::bluetooth::le::LeConnectionState /* transaction_state */, + std::vector>& /* argument_list */) {} void LogMetricBluetoothLEConnection(os::LEConnectionSessionOptions /* session_options */) {} diff --git a/system/gd/os/host/parameter_provider.cc b/system/gd/os/host/parameter_provider.cc index 61776c7d866..37d6232ebe8 100644 --- a/system/gd/os/host/parameter_provider.cc +++ b/system/gd/os/host/parameter_provider.cc @@ -46,9 +46,8 @@ std::string ParameterProvider::ConfigFilePath() { } char cwd[PATH_MAX] = {}; if (getcwd(cwd, sizeof(cwd)) == nullptr) { - log::error( - "Failed to get current working directory due to \"{}\", returning default", - strerror(errno)); + log::error("Failed to get current working directory due to \"{}\", returning default", + strerror(errno)); return "bt_config.conf"; } return std::string(cwd) + "/bt_config.conf"; @@ -68,9 +67,8 @@ std::string ParameterProvider::SnoopLogFilePath() { } char cwd[PATH_MAX] = {}; if (getcwd(cwd, sizeof(cwd)) == nullptr) { - log::error( - "Failed to get current working directory due to \"{}\", returning default", - strerror(errno)); + log::error("Failed to get current working directory due to \"{}\", returning default", + strerror(errno)); return "btsnoop_hci.log"; } return std::string(cwd) + "/btsnoop_hci.log"; @@ -91,9 +89,8 @@ std::string ParameterProvider::SnoozLogFilePath() { } char cwd[PATH_MAX] = {}; if (getcwd(cwd, sizeof(cwd)) == nullptr) { - log::error( - "Failed to get current working directory due to \"{}\", returning default", - strerror(errno)); + log::error("Failed to get current working directory due to \"{}\", returning default", + strerror(errno)); return "bt_config.conf"; } return std::string(cwd) + "/btsnooz_hci.log"; @@ -119,17 +116,13 @@ bluetooth_keystore::BluetoothKeystoreInterface* ParameterProvider::GetBtKeystore } void ParameterProvider::SetBtKeystoreInterface( - bluetooth_keystore::BluetoothKeystoreInterface* /* bt_keystore */) {} + bluetooth_keystore::BluetoothKeystoreInterface* /* bt_keystore */) {} -bool ParameterProvider::IsCommonCriteriaMode() { - return false; -} +bool ParameterProvider::IsCommonCriteriaMode() { return false; } void ParameterProvider::SetCommonCriteriaMode(bool /* enable */) {} -int ParameterProvider::GetCommonCriteriaConfigCompareResult() { - return 0b11; -} +int ParameterProvider::GetCommonCriteriaConfigCompareResult() { return 0b11; } void ParameterProvider::SetCommonCriteriaConfigCompareResult(int /* result */) {} diff --git a/system/gd/os/host/system_properties.cc b/system/gd/os/host/system_properties.cc index d0e8d8c71d2..7918aae2ce0 100644 --- a/system/gd/os/host/system_properties.cc +++ b/system/gd/os/host/system_properties.cc @@ -49,13 +49,9 @@ bool ClearSystemPropertiesForHost() { return true; } -bool IsRootCanalEnabled() { - return false; -} +bool IsRootCanalEnabled() { return false; } -int GetAndroidVendorReleaseVersion() { - return 0; -} +int GetAndroidVendorReleaseVersion() { return 0; } } // namespace os } // namespace bluetooth \ No newline at end of file diff --git a/system/gd/os/host/wakelock_native.cc b/system/gd/os/host/wakelock_native.cc index 928a6f793bb..d09d91fbf3d 100644 --- a/system/gd/os/host/wakelock_native.cc +++ b/system/gd/os/host/wakelock_native.cc @@ -30,9 +30,7 @@ namespace internal { struct WakelockNative::Impl {}; -void WakelockNative::Initialize() { - log::info("Host native wakelock is not implemented"); -} +void WakelockNative::Initialize() { log::info("Host native wakelock is not implemented"); } WakelockNative::StatusCode WakelockNative::Acquire(const std::string& /* lock_name */) { log::info("Host native wakelock is not implemented"); @@ -43,9 +41,7 @@ WakelockNative::StatusCode WakelockNative::Release(const std::string& /* lock_na log::info("Host native wakelock is not implemented"); return StatusCode::SUCCESS; } -void WakelockNative::CleanUp() { - log::info("Host native wakelock is not implemented"); -} +void WakelockNative::CleanUp() { log::info("Host native wakelock is not implemented"); } WakelockNative::WakelockNative() : pimpl_(std::make_unique()) {} diff --git a/system/gd/os/internal/wakelock_native.h b/system/gd/os/internal/wakelock_native.h index 0cde6bd3854..82c7069f575 100644 --- a/system/gd/os/internal/wakelock_native.h +++ b/system/gd/os/internal/wakelock_native.h @@ -29,7 +29,7 @@ namespace internal { // DO NOT USE OUTSIDE os/ // Native wakelock APIs implemented by each architecture, not public APIs class WakelockNative { - public: +public: static WakelockNative& Get() { static WakelockNative instance; return instance; @@ -42,7 +42,7 @@ class WakelockNative { ~WakelockNative(); - private: +private: WakelockNative(); struct Impl; std::unique_ptr pimpl_; diff --git a/system/gd/os/linux/metrics.cc b/system/gd/os/linux/metrics.cc index 62f7b9392d7..0b267c24e23 100644 --- a/system/gd/os/linux/metrics.cc +++ b/system/gd/os/linux/metrics.cc @@ -17,6 +17,7 @@ ******************************************************************************/ #include "os/metrics.h" + #include "os/log.h" namespace bluetooth { @@ -24,129 +25,94 @@ namespace os { using bluetooth::hci::Address; -void LogMetricClassicPairingEvent( - const Address& address, - uint16_t handle, - uint32_t hci_cmd, - uint16_t hci_event, - uint16_t cmd_status, - uint16_t reason_code, - int64_t event_value) {} - -void LogMetricSocketConnectionState( - const Address& address, - int port, - int type, - android::bluetooth::SocketConnectionstateEnum connection_state, - int64_t tx_bytes, - int64_t rx_bytes, - int uid, - int server_port, - android::bluetooth::SocketRoleEnum socket_role) {} +void LogMetricClassicPairingEvent(const Address& address, uint16_t handle, uint32_t hci_cmd, + uint16_t hci_event, uint16_t cmd_status, uint16_t reason_code, + int64_t event_value) {} + +void LogMetricSocketConnectionState(const Address& address, int port, int type, + android::bluetooth::SocketConnectionstateEnum connection_state, + int64_t tx_bytes, int64_t rx_bytes, int uid, int server_port, + android::bluetooth::SocketRoleEnum socket_role) {} void LogMetricHciTimeoutEvent(uint32_t hci_cmd) {} -void LogMetricA2dpAudioUnderrunEvent( - const Address& address, uint64_t encoding_interval_millis, int num_missing_pcm_bytes) {} - -void LogMetricA2dpAudioOverrunEvent( - const Address& address, - uint64_t encoding_interval_millis, - int num_dropped_buffers, - int num_dropped_encoded_frames, - int num_dropped_encoded_bytes) {} - -void LogMetricReadRssiResult(const Address& address, uint16_t handle, uint32_t cmd_status, int8_t rssi) {} - -void LogMetricReadFailedContactCounterResult( - const Address& address, uint16_t handle, uint32_t cmd_status, int32_t failed_contact_counter) {} - -void LogMetricReadTxPowerLevelResult( - const Address& address, uint16_t handle, uint32_t cmd_status, int32_t transmit_power_level) {} - -void LogMetricRemoteVersionInfo( - uint16_t handle, uint8_t status, uint8_t version, uint16_t manufacturer_name, uint16_t subversion) {} - -void LogMetricLinkLayerConnectionEvent( - const Address* address, - uint32_t connection_handle, - android::bluetooth::DirectionEnum direction, - uint16_t link_type, - uint32_t hci_cmd, - uint16_t hci_event, - uint16_t hci_ble_event, - uint16_t cmd_status, - uint16_t reason_code) {} - -void LogMetricManufacturerInfo( - const Address& address, - android::bluetooth::AddressTypeEnum address_type, - android::bluetooth::DeviceInfoSrcEnum source_type, - const std::string& source_name, - const std::string& manufacturer, - const std::string& model, - const std::string& hardware_version, - const std::string& software_version) {} - -void LogMetricSdpAttribute( - const Address& address, - uint16_t protocol_uuid, - uint16_t attribute_id, - size_t attribute_size, - const char* attribute_value) {} - -void LogMetricSmpPairingEvent( - const Address& address, uint16_t smp_cmd, android::bluetooth::DirectionEnum direction, uint16_t smp_fail_reason) {} - -void LogMetricA2dpPlaybackEvent(const Address& address, int playback_state, int audio_coding_mode) {} - -void LogMetricA2dpSessionMetricsEvent( - const Address& address, - int64_t audio_duration_ms, - int media_timer_min_ms, - int media_timer_max_ms, - int media_timer_avg_ms, - int total_scheduling_count, - int buffer_overruns_max_count, - int buffer_overruns_total, - float buffer_underruns_average, - int buffer_underruns_count, - int64_t codec_index, - bool is_a2dp_offload) {} - -void LogMetricHfpPacketLossStats( - const Address& address, int num_decoded_frames, double packet_loss_ratio, uint16_t codec_type) { +void LogMetricA2dpAudioUnderrunEvent(const Address& address, uint64_t encoding_interval_millis, + int num_missing_pcm_bytes) {} + +void LogMetricA2dpAudioOverrunEvent(const Address& address, uint64_t encoding_interval_millis, + int num_dropped_buffers, int num_dropped_encoded_frames, + int num_dropped_encoded_bytes) {} + +void LogMetricReadRssiResult(const Address& address, uint16_t handle, uint32_t cmd_status, + int8_t rssi) {} + +void LogMetricReadFailedContactCounterResult(const Address& address, uint16_t handle, + uint32_t cmd_status, int32_t failed_contact_counter) {} + +void LogMetricReadTxPowerLevelResult(const Address& address, uint16_t handle, uint32_t cmd_status, + int32_t transmit_power_level) {} + +void LogMetricRemoteVersionInfo(uint16_t handle, uint8_t status, uint8_t version, + uint16_t manufacturer_name, uint16_t subversion) {} + +void LogMetricLinkLayerConnectionEvent(const Address* address, uint32_t connection_handle, + android::bluetooth::DirectionEnum direction, + uint16_t link_type, uint32_t hci_cmd, uint16_t hci_event, + uint16_t hci_ble_event, uint16_t cmd_status, + uint16_t reason_code) {} + +void LogMetricManufacturerInfo(const Address& address, + android::bluetooth::AddressTypeEnum address_type, + android::bluetooth::DeviceInfoSrcEnum source_type, + const std::string& source_name, const std::string& manufacturer, + const std::string& model, const std::string& hardware_version, + const std::string& software_version) {} + +void LogMetricSdpAttribute(const Address& address, uint16_t protocol_uuid, uint16_t attribute_id, + size_t attribute_size, const char* attribute_value) {} + +void LogMetricSmpPairingEvent(const Address& address, uint16_t smp_cmd, + android::bluetooth::DirectionEnum direction, + uint16_t smp_fail_reason) {} + +void LogMetricA2dpPlaybackEvent(const Address& address, int playback_state, int audio_coding_mode) { } -void LogMetricMmcTranscodeRttStats( - int maximum_rtt, double mean_rtt, int num_requests, int codec_type) {} +void LogMetricA2dpSessionMetricsEvent(const Address& address, int64_t audio_duration_ms, + int media_timer_min_ms, int media_timer_max_ms, + int media_timer_avg_ms, int total_scheduling_count, + int buffer_overruns_max_count, int buffer_overruns_total, + float buffer_underruns_average, int buffer_underruns_count, + int64_t codec_index, bool is_a2dp_offload) {} + +void LogMetricHfpPacketLossStats(const Address& address, int num_decoded_frames, + double packet_loss_ratio, uint16_t codec_type) {} + +void LogMetricMmcTranscodeRttStats(int maximum_rtt, double mean_rtt, int num_requests, + int codec_type) {} -void LogMetricBluetoothHalCrashReason( - const Address& address, uint32_t error_code, uint32_t vendor_error_code) {} +void LogMetricBluetoothHalCrashReason(const Address& address, uint32_t error_code, + uint32_t vendor_error_code) {} void LogMetricBluetoothLocalSupportedFeatures(uint32_t page_num, uint64_t features) {} -void LogMetricBluetoothLocalVersions( - uint32_t lmp_manufacturer_name, - uint8_t lmp_version, - uint32_t lmp_subversion, - uint8_t hci_version, - uint32_t hci_revision) {} +void LogMetricBluetoothLocalVersions(uint32_t lmp_manufacturer_name, uint8_t lmp_version, + uint32_t lmp_subversion, uint8_t hci_version, + uint32_t hci_revision) {} -void LogMetricBluetoothDisconnectionReasonReported( - uint32_t reason, const Address& address, uint32_t connection_handle) {} +void LogMetricBluetoothDisconnectionReasonReported(uint32_t reason, const Address& address, + uint32_t connection_handle) {} -void LogMetricBluetoothRemoteSupportedFeatures( - const Address& address, uint32_t page, uint64_t features, uint32_t connection_handle) {} +void LogMetricBluetoothRemoteSupportedFeatures(const Address& address, uint32_t page, + uint64_t features, uint32_t connection_handle) {} void LogMetricBluetoothCodePathCounterMetrics(int32_t key, int64_t count) {} void LogMetricBluetoothLEConnectionMetricEvent( - const Address& address, - android::bluetooth::le::LeConnectionOriginType origin_type, - android::bluetooth::le::LeConnectionType connection_type, - android::bluetooth::le::LeConnectionState transaction_state, - std::vector>& argument_list) {} + const Address& address, android::bluetooth::le::LeConnectionOriginType origin_type, + android::bluetooth::le::LeConnectionType connection_type, + android::bluetooth::le::LeConnectionState transaction_state, + std::vector>& argument_list) {} void LogMetricBluetoothLEConnection(os::LEConnectionSessionOptions /* session_options */) {} } // namespace os diff --git a/system/gd/os/linux/parameter_provider.cc b/system/gd/os/linux/parameter_provider.cc index f754a7fa48a..2302a68e119 100644 --- a/system/gd/os/linux/parameter_provider.cc +++ b/system/gd/os/linux/parameter_provider.cc @@ -96,17 +96,14 @@ bluetooth_keystore::BluetoothKeystoreInterface* ParameterProvider::GetBtKeystore return nullptr; } -void ParameterProvider::SetBtKeystoreInterface(bluetooth_keystore::BluetoothKeystoreInterface* bt_keystore) {} +void ParameterProvider::SetBtKeystoreInterface( + bluetooth_keystore::BluetoothKeystoreInterface* bt_keystore) {} -bool ParameterProvider::IsCommonCriteriaMode() { - return false; -} +bool ParameterProvider::IsCommonCriteriaMode() { return false; } void ParameterProvider::SetCommonCriteriaMode(bool enable) {} -int ParameterProvider::GetCommonCriteriaConfigCompareResult() { - return 0b11; -} +int ParameterProvider::GetCommonCriteriaConfigCompareResult() { return 0b11; } void ParameterProvider::SetCommonCriteriaConfigCompareResult(int result) {} diff --git a/system/gd/os/linux/system_properties.cc b/system/gd/os/linux/system_properties.cc index c9d719f06f7..aef6dadcc11 100644 --- a/system/gd/os/linux/system_properties.cc +++ b/system/gd/os/linux/system_properties.cc @@ -28,7 +28,7 @@ std::mutex properties_mutex; // Properties set along with some default values for Floss. std::unordered_map properties = { - {"bluetooth.profile.avrcp.target.enabled", "true"}, + {"bluetooth.profile.avrcp.target.enabled", "true"}, }; } // namespace @@ -53,13 +53,9 @@ bool ClearSystemPropertiesForHost() { return true; } -bool IsRootCanalEnabled() { - return false; -} +bool IsRootCanalEnabled() { return false; } -int GetAndroidVendorReleaseVersion() { - return 0; -} +int GetAndroidVendorReleaseVersion() { return 0; } } // namespace os } // namespace bluetooth diff --git a/system/gd/os/linux/wakelock_native.cc b/system/gd/os/linux/wakelock_native.cc index d312938f5fd..8cf7f71fde4 100644 --- a/system/gd/os/linux/wakelock_native.cc +++ b/system/gd/os/linux/wakelock_native.cc @@ -30,9 +30,7 @@ namespace internal { struct WakelockNative::Impl {}; -void WakelockNative::Initialize() { - log::info("Linux native wakelock is not implemented"); -} +void WakelockNative::Initialize() { log::info("Linux native wakelock is not implemented"); } WakelockNative::StatusCode WakelockNative::Acquire(const std::string& lock_name) { log::info("Linux native wakelock is not implemented"); @@ -43,9 +41,7 @@ WakelockNative::StatusCode WakelockNative::Release(const std::string& lock_name) log::info("Linux native wakelock is not implemented"); return StatusCode::SUCCESS; } -void WakelockNative::CleanUp() { - log::info("Linux native wakelock is not implemented"); -} +void WakelockNative::CleanUp() { log::info("Linux native wakelock is not implemented"); } WakelockNative::WakelockNative() : pimpl_(std::make_unique()) {} diff --git a/system/gd/os/linux_generic/alarm.cc b/system/gd/os/linux_generic/alarm.cc index e6d831645c2..6cb2d191fd9 100644 --- a/system/gd/os/linux_generic/alarm.cc +++ b/system/gd/os/linux_generic/alarm.cc @@ -42,7 +42,7 @@ Alarm::Alarm(Handler* handler) : handler_(handler), fd_(TIMERFD_CREATE(ALARM_CLO log::assert_that(fd_ != -1, "cannot create timerfd: {}", strerror(errno)); token_ = handler_->thread_->GetReactor()->Register( - fd_, common::Bind(&Alarm::on_fire, common::Unretained(this)), Closure()); + fd_, common::Bind(&Alarm::on_fire, common::Unretained(this)), Closure()); } Alarm::~Alarm() { @@ -56,7 +56,8 @@ Alarm::~Alarm() { void Alarm::Schedule(OnceClosure task, std::chrono::milliseconds delay) { std::lock_guard lock(mutex_); long delay_ms = delay.count(); - itimerspec timer_itimerspec{{/* interval for periodic timer */}, {delay_ms / 1000, delay_ms % 1000 * 1000000}}; + itimerspec timer_itimerspec{{/* interval for periodic timer */}, + {delay_ms / 1000, delay_ms % 1000 * 1000000}}; int result = TIMERFD_SETTIME(fd_, 0, &timer_itimerspec, nullptr); log::assert_that(result == 0, "assert failed: result == 0"); @@ -76,14 +77,10 @@ void Alarm::on_fire() { uint64_t times_invoked; auto bytes_read = read(fd_, ×_invoked, sizeof(uint64_t)); lock.unlock(); - log::assert_that( - bytes_read == static_cast(sizeof(uint64_t)), - "assert failed: bytes_read == static_cast(sizeof(uint64_t))"); - log::assert_that( - times_invoked == static_cast(1), - "Invoked number of times:{} fd:{}", - (unsigned long)times_invoked, - fd_); + log::assert_that(bytes_read == static_cast(sizeof(uint64_t)), + "assert failed: bytes_read == static_cast(sizeof(uint64_t))"); + log::assert_that(times_invoked == static_cast(1), "Invoked number of times:{} fd:{}", + (unsigned long)times_invoked, fd_); std::move(task).Run(); } diff --git a/system/gd/os/linux_generic/alarm_timerfd_unittest.cc b/system/gd/os/linux_generic/alarm_timerfd_unittest.cc index c2e3952b292..b79cca8fedc 100644 --- a/system/gd/os/linux_generic/alarm_timerfd_unittest.cc +++ b/system/gd/os/linux_generic/alarm_timerfd_unittest.cc @@ -14,8 +14,6 @@ * limitations under the License. */ -#include "os/alarm.h" - #include #include #include @@ -23,14 +21,12 @@ #include "common/bind.h" #include "gtest/gtest.h" - +#include "os/alarm.h" namespace bluetooth::common { struct IsSpace { - bool operator()(std::string::value_type v) { - return isspace(static_cast(v)); - } + bool operator()(std::string::value_type v) { return isspace(static_cast(v)); } }; std::string StringTrim(std::string str) { @@ -50,7 +46,7 @@ static constexpr seconds kForever = seconds(1); static constexpr milliseconds kShortWait = milliseconds(10); class AlarmOnTimerFdTest : public ::testing::Test { - protected: +protected: void SetUp() override { thread_ = new Thread("test_thread", Thread::Priority::NORMAL); handler_ = new Handler(thread_); @@ -64,20 +60,16 @@ class AlarmOnTimerFdTest : public ::testing::Test { delete thread_; } - std::shared_ptr get_new_alarm() { - return std::make_shared(handler_); - } + std::shared_ptr get_new_alarm() { return std::make_shared(handler_); } std::shared_ptr alarm_; - private: +private: Handler* handler_; Thread* thread_; }; -TEST_F(AlarmOnTimerFdTest, cancel_while_not_armed) { - alarm_->Cancel(); -} +TEST_F(AlarmOnTimerFdTest, cancel_while_not_armed) { alarm_->Cancel(); } TEST_F(AlarmOnTimerFdTest, schedule) { auto promise = std::make_unique>(); @@ -97,16 +89,14 @@ TEST_F(AlarmOnTimerFdTest, cancel_alarm) { TEST_F(AlarmOnTimerFdTest, cancel_alarm_from_callback) { auto promise = std::promise(); auto future = promise.get_future(); - alarm_->Schedule( - BindOnce( - [](std::shared_ptr alarm, std::promise promise) { - alarm->Cancel(); - alarm.reset(); // Allow alarm to be freed by Teardown - promise.set_value(); - }, - alarm_, - std::move(promise)), - kShortWait); + alarm_->Schedule(BindOnce( + [](std::shared_ptr alarm, std::promise promise) { + alarm->Cancel(); + alarm.reset(); // Allow alarm to be freed by Teardown + promise.set_value(); + }, + alarm_, std::move(promise)), + kShortWait); ASSERT_EQ(std::future_status::ready, future.wait_for(kForever)); } @@ -127,7 +117,7 @@ TEST_F(AlarmOnTimerFdTest, delete_while_alarm_armed) { } class TwoAlarmOnTimerFdTest : public AlarmOnTimerFdTest { - protected: +protected: void SetUp() override { AlarmOnTimerFdTest::SetUp(); alarm2 = get_new_alarm(); @@ -145,14 +135,13 @@ TEST_F(TwoAlarmOnTimerFdTest, schedule_from_alarm) { auto promise = std::make_unique>(); auto future = promise->get_future(); alarm_->Schedule( - BindOnce( - [](std::shared_ptr alarm2, std::unique_ptr> promise) { - alarm2->Schedule( - BindOnce(&std::promise::set_value, std::move(promise)), kShortWait); - }, - alarm2, - std::move(promise)), - kShortWait); + BindOnce( + [](std::shared_ptr alarm2, std::unique_ptr> promise) { + alarm2->Schedule(BindOnce(&std::promise::set_value, std::move(promise)), + kShortWait); + }, + alarm2, std::move(promise)), + kShortWait); EXPECT_EQ(std::future_status::ready, future.wait_for(kForever)); } diff --git a/system/gd/os/linux_generic/alarm_unittest.cc b/system/gd/os/linux_generic/alarm_unittest.cc index d3b07beb890..5dad6dc2b3f 100644 --- a/system/gd/os/linux_generic/alarm_unittest.cc +++ b/system/gd/os/linux_generic/alarm_unittest.cc @@ -32,7 +32,7 @@ using fake_timer::fake_timerfd_advance; using fake_timer::fake_timerfd_reset; class AlarmTest : public ::testing::Test { - protected: +protected: void SetUp() override { thread_ = new Thread("test_thread", Thread::Priority::NORMAL); handler_ = new Handler(thread_); @@ -51,34 +51,30 @@ class AlarmTest : public ::testing::Test { handler_->Post(common::BindOnce(fake_timerfd_advance, ms)); } - std::shared_ptr get_new_alarm() { - return std::make_shared(handler_); - } + std::shared_ptr get_new_alarm() { return std::make_shared(handler_); } std::shared_ptr alarm_; - private: +private: Handler* handler_; Thread* thread_; }; -TEST_F(AlarmTest, cancel_while_not_armed) { - alarm_->Cancel(); -} +TEST_F(AlarmTest, cancel_while_not_armed) { alarm_->Cancel(); } TEST_F(AlarmTest, schedule) { std::promise promise; auto future = promise.get_future(); int delay_ms = 10; - alarm_->Schedule( - BindOnce(&std::promise::set_value, common::Unretained(&promise)), std::chrono::milliseconds(delay_ms)); + alarm_->Schedule(BindOnce(&std::promise::set_value, common::Unretained(&promise)), + std::chrono::milliseconds(delay_ms)); fake_timer_advance(10); future.get(); ASSERT_FALSE(future.valid()); } TEST_F(AlarmTest, cancel_alarm) { - alarm_->Schedule(BindOnce([]() { ASSERT_TRUE(false) << "Should not happen"; }), std::chrono::milliseconds(3)); + alarm_->Schedule(BindOnce([]() { FAIL() << "Should not happen"; }), std::chrono::milliseconds(3)); alarm_->Cancel(); std::this_thread::sleep_for(std::chrono::milliseconds(5)); } @@ -86,39 +82,37 @@ TEST_F(AlarmTest, cancel_alarm) { TEST_F(AlarmTest, cancel_alarm_from_callback) { std::promise promise; auto future = promise.get_future(); - alarm_->Schedule( - BindOnce( - [](std::shared_ptr alarm, std::promise promise) { - alarm->Cancel(); - alarm.reset(); // Allow alarm to be freed by Teardown - promise.set_value(); - }, - alarm_, - std::move(promise)), - std::chrono::milliseconds(1)); + alarm_->Schedule(BindOnce( + [](std::shared_ptr alarm, std::promise promise) { + alarm->Cancel(); + alarm.reset(); // Allow alarm to be freed by Teardown + promise.set_value(); + }, + alarm_, std::move(promise)), + std::chrono::milliseconds(1)); fake_timer_advance(10); ASSERT_EQ(std::future_status::ready, future.wait_for(std::chrono::seconds(1))); ASSERT_EQ(alarm_.use_count(), 1); } TEST_F(AlarmTest, schedule_while_alarm_armed) { - alarm_->Schedule(BindOnce([]() { ASSERT_TRUE(false) << "Should not happen"; }), std::chrono::milliseconds(1)); + alarm_->Schedule(BindOnce([]() { FAIL() << "Should not happen"; }), std::chrono::milliseconds(1)); std::promise promise; auto future = promise.get_future(); - alarm_->Schedule( - BindOnce(&std::promise::set_value, common::Unretained(&promise)), std::chrono::milliseconds(10)); + alarm_->Schedule(BindOnce(&std::promise::set_value, common::Unretained(&promise)), + std::chrono::milliseconds(10)); fake_timer_advance(10); future.get(); } TEST_F(AlarmTest, delete_while_alarm_armed) { - alarm_->Schedule(BindOnce([]() { ASSERT_TRUE(false) << "Should not happen"; }), std::chrono::milliseconds(1)); + alarm_->Schedule(BindOnce([]() { FAIL() << "Should not happen"; }), std::chrono::milliseconds(1)); alarm_.reset(); std::this_thread::sleep_for(std::chrono::milliseconds(10)); } class TwoAlarmTest : public AlarmTest { - protected: +protected: void SetUp() override { AlarmTest::SetUp(); alarm2 = get_new_alarm(); @@ -138,19 +132,15 @@ TEST_F(TwoAlarmTest, schedule_from_alarm_long) { auto promise2 = std::make_unique>(); auto future2 = promise2->get_future(); alarm_->Schedule( - BindOnce( - [](std::shared_ptr alarm2, - std::unique_ptr> promise, - std::unique_ptr> promise2) { - promise->set_value(); - alarm2->Schedule( - BindOnce(&std::promise::set_value, std::move(promise2)), - std::chrono::milliseconds(10)); - }, - alarm2, - std::move(promise), - std::move(promise2)), - std::chrono::milliseconds(1)); + BindOnce( + [](std::shared_ptr alarm2, std::unique_ptr> promise, + std::unique_ptr> promise2) { + promise->set_value(); + alarm2->Schedule(BindOnce(&std::promise::set_value, std::move(promise2)), + std::chrono::milliseconds(10)); + }, + alarm2, std::move(promise), std::move(promise2)), + std::chrono::milliseconds(1)); fake_timer_advance(10); EXPECT_EQ(std::future_status::ready, future.wait_for(std::chrono::milliseconds(20))); fake_timer_advance(10); diff --git a/system/gd/os/linux_generic/files.cc b/system/gd/os/linux_generic/files.cc index 83ba0d63818..38896cccc79 100644 --- a/system/gd/os/linux_generic/files.cc +++ b/system/gd/os/linux_generic/files.cc @@ -100,7 +100,8 @@ bool WriteToFile(const std::string& path, const std::string& data) { // 5) Sync directory that has the conf file with fsync(). // This ensures directory entries are up-to-date. // - // We are using traditional C type file methods because C++ std::filesystem and std::ofstream do not support: + // We are using traditional C type file methods because C++ std::filesystem and std::ofstream do + // not support: // - Operation on directories // - fsync() to ensure content is written to disk @@ -111,8 +112,9 @@ bool WriteToFile(const std::string& path, const std::string& data) { // TODO: switch to std::filesystem::path::parent_path std::string directory_path; { - // Make a temporary variable as inputs to dirname() will be modified and return value points to input char array - // temp_path_for_dir must not be destroyed until results from dirname is appended to directory_path + // Make a temporary variable as inputs to dirname() will be modified and return value points to + // input char array temp_path_for_dir must not be destroyed until results from dirname is + // appended to directory_path std::string temp_path_for_dir(path); directory_path.append(dirname(temp_path_for_dir.data())); } @@ -189,8 +191,8 @@ bool WriteToFile(const std::string& path, const std::string& data) { // Rename written temp file to the actual config file. if (std::rename(temp_path.c_str(), path.c_str()) != 0) { - log::error( - "unable to commit file from '{}' to '{}', error: {}", temp_path, path, strerror(errno)); + log::error("unable to commit file from '{}' to '{}', error: {}", temp_path, path, + strerror(errno)); HandleError(temp_path, &dir_fd, &fp); return false; } @@ -216,8 +218,8 @@ bool RemoveFile(const std::string& path) { return true; } -std::optional> FileCreatedTime( - const std::string& path) { +std::optional> +FileCreatedTime(const std::string& path) { struct stat file_info; if (stat(path.c_str(), &file_info) != 0) { log::error("unable to read '{}' file metadata, error: {}", path, strerror(errno)); diff --git a/system/gd/os/linux_generic/files_test.cc b/system/gd/os/linux_generic/files_test.cc index 383083c454d..ee58ae5c475 100644 --- a/system/gd/os/linux_generic/files_test.cc +++ b/system/gd/os/linux_generic/files_test.cc @@ -82,8 +82,6 @@ TEST(FilesTest, write_read_empty_string_test) { EXPECT_TRUE(std::filesystem::remove(temp_file)); } -TEST(FilesTest, read_non_existing_file_test) { - EXPECT_FALSE(ReadSmallFile("/woof")); -} +TEST(FilesTest, read_non_existing_file_test) { EXPECT_FALSE(ReadSmallFile("/woof")); } } // namespace testing \ No newline at end of file diff --git a/system/gd/os/linux_generic/queue_unittest.cc b/system/gd/os/linux_generic/queue_unittest.cc index 2d96630af9a..0e23454c611 100644 --- a/system/gd/os/linux_generic/queue_unittest.cc +++ b/system/gd/os/linux_generic/queue_unittest.cc @@ -39,7 +39,7 @@ constexpr int kDoubleOfQueueSize = kQueueSize * 2; constexpr int kQueueSizeOne = 1; class QueueTest : public ::testing::Test { - protected: +protected: void SetUp() override { enqueue_thread_ = new Thread("enqueue_thread", Thread::Priority::NORMAL); enqueue_handler_ = new Handler(enqueue_thread_); @@ -66,14 +66,13 @@ class QueueTest : public ::testing::Test { void sync_enqueue_handler() { log::assert_that(enqueue_thread_ != nullptr, "assert failed: enqueue_thread_ != nullptr"); - log::assert_that( - enqueue_thread_->GetReactor()->WaitForIdle(2s), - "assert failed: enqueue_thread_->GetReactor()->WaitForIdle(2s)"); + log::assert_that(enqueue_thread_->GetReactor()->WaitForIdle(2s), + "assert failed: enqueue_thread_->GetReactor()->WaitForIdle(2s)"); } }; class TestEnqueueEnd { - public: +public: explicit TestEnqueueEnd(Queue* queue, Handler* handler) : count(0), handler_(handler), queue_(queue), delay_(0) {} @@ -81,15 +80,16 @@ class TestEnqueueEnd { void RegisterEnqueue(std::unordered_map>* promise_map) { promise_map_ = promise_map; - handler_->Post(common::BindOnce(&TestEnqueueEnd::handle_register_enqueue, common::Unretained(this))); + handler_->Post( + common::BindOnce(&TestEnqueueEnd::handle_register_enqueue, common::Unretained(this))); } void UnregisterEnqueue() { std::promise promise; auto future = promise.get_future(); - handler_->Post( - common::BindOnce(&TestEnqueueEnd::handle_unregister_enqueue, common::Unretained(this), std::move(promise))); + handler_->Post(common::BindOnce(&TestEnqueueEnd::handle_unregister_enqueue, + common::Unretained(this), std::move(promise))); future.wait(); } @@ -115,21 +115,20 @@ class TestEnqueueEnd { return data; } - void setDelay(int value) { - delay_ = value; - } + void setDelay(int value) { delay_ = value; } std::queue> buffer_; int count; - private: +private: Handler* handler_; Queue* queue_; std::unordered_map>* promise_map_; int delay_; void handle_register_enqueue() { - queue_->RegisterEnqueue(handler_, common::Bind(&TestEnqueueEnd::EnqueueCallbackForTest, common::Unretained(this))); + queue_->RegisterEnqueue(handler_, common::Bind(&TestEnqueueEnd::EnqueueCallbackForTest, + common::Unretained(this))); } void handle_unregister_enqueue(std::promise promise) { @@ -139,7 +138,7 @@ class TestEnqueueEnd { }; class TestDequeueEnd { - public: +public: explicit TestDequeueEnd(Queue* queue, Handler* handler, int capacity) : count(0), handler_(handler), queue_(queue), capacity_(capacity), delay_(0) {} @@ -147,15 +146,16 @@ class TestDequeueEnd { void RegisterDequeue(std::unordered_map>* promise_map) { promise_map_ = promise_map; - handler_->Post(common::BindOnce(&TestDequeueEnd::handle_register_dequeue, common::Unretained(this))); + handler_->Post( + common::BindOnce(&TestDequeueEnd::handle_register_dequeue, common::Unretained(this))); } void UnregisterDequeue() { std::promise promise; auto future = promise.get_future(); - handler_->Post( - common::BindOnce(&TestDequeueEnd::handle_unregister_dequeue, common::Unretained(this), std::move(promise))); + handler_->Post(common::BindOnce(&TestDequeueEnd::handle_unregister_dequeue, + common::Unretained(this), std::move(promise))); future.wait(); } @@ -179,14 +179,12 @@ class TestDequeueEnd { } } - void setDelay(int value) { - delay_ = value; - } + void setDelay(int value) { delay_ = value; } std::queue> buffer_; int count; - private: +private: Handler* handler_; Queue* queue_; std::unordered_map>* promise_map_; @@ -194,7 +192,8 @@ class TestDequeueEnd { int delay_; void handle_register_dequeue() { - queue_->RegisterDequeue(handler_, common::Bind(&TestDequeueEnd::DequeueCallbackForTest, common::Unretained(this))); + queue_->RegisterDequeue(handler_, common::Bind(&TestDequeueEnd::DequeueCallbackForTest, + common::Unretained(this))); } void handle_unregister_dequeue(std::promise promise) { @@ -224,7 +223,8 @@ TEST_F(QueueTest, register_enqueue_with_empty_queue) { // Register enqueue and expect data move to Queue std::unordered_map> enqueue_promise_map; - enqueue_promise_map.emplace(std::piecewise_construct, std::forward_as_tuple(0), std::forward_as_tuple()); + enqueue_promise_map.emplace(std::piecewise_construct, std::forward_as_tuple(0), + std::forward_as_tuple()); auto enqueue_future = enqueue_promise_map[0].get_future(); test_enqueue_end.RegisterEnqueue(&enqueue_promise_map); enqueue_future.wait(); @@ -263,7 +263,8 @@ TEST_F(QueueTest, register_enqueue_with_full_queue) { test_enqueue_end.buffer_.push(std::move(data)); } std::unordered_map> enqueue_promise_map; - enqueue_promise_map.emplace(std::piecewise_construct, std::forward_as_tuple(0), std::forward_as_tuple()); + enqueue_promise_map.emplace(std::piecewise_construct, std::forward_as_tuple(0), + std::forward_as_tuple()); auto enqueue_future = enqueue_promise_map[0].get_future(); test_enqueue_end.RegisterEnqueue(&enqueue_promise_map); enqueue_future.wait(); @@ -298,7 +299,8 @@ TEST_F(QueueTest, register_dequeue_with_full_queue) { test_enqueue_end.buffer_.push(std::move(data)); } std::unordered_map> enqueue_promise_map; - enqueue_promise_map.emplace(std::piecewise_construct, std::forward_as_tuple(0), std::forward_as_tuple()); + enqueue_promise_map.emplace(std::piecewise_construct, std::forward_as_tuple(0), + std::forward_as_tuple()); auto enqueue_future = enqueue_promise_map[0].get_future(); test_enqueue_end.RegisterEnqueue(&enqueue_promise_map); enqueue_future.wait(); @@ -306,7 +308,8 @@ TEST_F(QueueTest, register_dequeue_with_full_queue) { // Register dequeue and expect data move to dequeue end buffer std::unordered_map> dequeue_promise_map; - dequeue_promise_map.emplace(std::piecewise_construct, std::forward_as_tuple(kQueueSize), std::forward_as_tuple()); + dequeue_promise_map.emplace(std::piecewise_construct, std::forward_as_tuple(kQueueSize), + std::forward_as_tuple()); auto dequeue_future = dequeue_promise_map[kQueueSize].get_future(); test_dequeue_end.RegisterDequeue(&dequeue_promise_map); dequeue_future.wait(); @@ -330,7 +333,8 @@ TEST_F(QueueTest, register_enqueue_with_half_empty_queue) { test_enqueue_end.buffer_.push(std::move(data)); } std::unordered_map> enqueue_promise_map; - enqueue_promise_map.emplace(std::piecewise_construct, std::forward_as_tuple(0), std::forward_as_tuple()); + enqueue_promise_map.emplace(std::piecewise_construct, std::forward_as_tuple(0), + std::forward_as_tuple()); auto enqueue_future = enqueue_promise_map[0].get_future(); test_enqueue_end.RegisterEnqueue(&enqueue_promise_map); enqueue_future.wait(); @@ -343,7 +347,8 @@ TEST_F(QueueTest, register_enqueue_with_half_empty_queue) { } // Register enqueue and expect data move to Queue - enqueue_promise_map.emplace(std::piecewise_construct, std::forward_as_tuple(0), std::forward_as_tuple()); + enqueue_promise_map.emplace(std::piecewise_construct, std::forward_as_tuple(0), + std::forward_as_tuple()); enqueue_future = enqueue_promise_map[0].get_future(); test_enqueue_end.RegisterEnqueue(&enqueue_promise_map); enqueue_future.wait(); @@ -365,7 +370,8 @@ TEST_F(QueueTest, register_dequeue_with_half_empty_queue) { test_enqueue_end.buffer_.push(std::move(data)); } std::unordered_map> enqueue_promise_map; - enqueue_promise_map.emplace(std::piecewise_construct, std::forward_as_tuple(0), std::forward_as_tuple()); + enqueue_promise_map.emplace(std::piecewise_construct, std::forward_as_tuple(0), + std::forward_as_tuple()); auto enqueue_future = enqueue_promise_map[0].get_future(); test_enqueue_end.RegisterEnqueue(&enqueue_promise_map); enqueue_future.wait(); @@ -373,8 +379,8 @@ TEST_F(QueueTest, register_dequeue_with_half_empty_queue) { // Register dequeue and expect data move to dequeue end buffer std::unordered_map> dequeue_promise_map; - dequeue_promise_map.emplace( - std::piecewise_construct, std::forward_as_tuple(kHalfOfQueueSize), std::forward_as_tuple()); + dequeue_promise_map.emplace(std::piecewise_construct, std::forward_as_tuple(kHalfOfQueueSize), + std::forward_as_tuple()); auto dequeue_future = dequeue_promise_map[kHalfOfQueueSize].get_future(); test_dequeue_end.RegisterDequeue(&dequeue_promise_map); dequeue_future.wait(); @@ -402,7 +408,8 @@ TEST_F(QueueTest, queue_becomes_full_enqueue_callback_only) { // Register enqueue and expect kQueueSize data move to Queue std::unordered_map> enqueue_promise_map; - enqueue_promise_map.emplace(std::piecewise_construct, std::forward_as_tuple(kQueueSize), std::forward_as_tuple()); + enqueue_promise_map.emplace(std::piecewise_construct, std::forward_as_tuple(kQueueSize), + std::forward_as_tuple()); auto enqueue_future = enqueue_promise_map[kQueueSize].get_future(); test_enqueue_end.RegisterEnqueue(&enqueue_promise_map); enqueue_future.wait(); @@ -432,15 +439,15 @@ TEST_F(QueueTest, queue_becomes_full_dequeue_callback_unregister) { // Register dequeue std::unordered_map> dequeue_promise_map; - dequeue_promise_map.emplace( - std::piecewise_construct, std::forward_as_tuple(kHalfOfQueueSize), std::forward_as_tuple()); + dequeue_promise_map.emplace(std::piecewise_construct, std::forward_as_tuple(kHalfOfQueueSize), + std::forward_as_tuple()); auto dequeue_future = dequeue_promise_map[kHalfOfQueueSize].get_future(); test_dequeue_end.RegisterDequeue(&dequeue_promise_map); // Register enqueue std::unordered_map> enqueue_promise_map; - enqueue_promise_map.emplace( - std::piecewise_construct, std::forward_as_tuple(kHalfOfQueueSize), std::forward_as_tuple()); + enqueue_promise_map.emplace(std::piecewise_construct, std::forward_as_tuple(kHalfOfQueueSize), + std::forward_as_tuple()); auto enqueue_future = enqueue_promise_map[kHalfOfQueueSize].get_future(); test_enqueue_end.RegisterEnqueue(&enqueue_promise_map); @@ -480,7 +487,8 @@ TEST_F(QueueTest, queue_becomes_full_dequeue_callback_slower) { // Register enqueue std::unordered_map> enqueue_promise_map; - enqueue_promise_map.emplace(std::piecewise_construct, std::forward_as_tuple(0), std::forward_as_tuple()); + enqueue_promise_map.emplace(std::piecewise_construct, std::forward_as_tuple(0), + std::forward_as_tuple()); auto enqueue_future = enqueue_promise_map[0].get_future(); test_enqueue_end.RegisterEnqueue(&enqueue_promise_map); @@ -508,7 +516,8 @@ TEST_F(QueueTest, queue_becomes_full_and_non_empty_at_same_time) { // Register dequeue std::unordered_map> dequeue_promise_map; - dequeue_promise_map.emplace(std::piecewise_construct, std::forward_as_tuple(kQueueSize), std::forward_as_tuple()); + dequeue_promise_map.emplace(std::piecewise_construct, std::forward_as_tuple(kQueueSize), + std::forward_as_tuple()); auto dequeue_future = dequeue_promise_map[kQueueSize].get_future(); test_dequeue_end.RegisterDequeue(&dequeue_promise_map); @@ -538,8 +547,10 @@ TEST_F(QueueTest, queue_becomes_non_full_during_test) { test_enqueue_end.buffer_.push(std::move(data)); } std::unordered_map> enqueue_promise_map; - enqueue_promise_map.emplace(std::piecewise_construct, std::forward_as_tuple(kQueueSize), std::forward_as_tuple()); - enqueue_promise_map.emplace(std::piecewise_construct, std::forward_as_tuple(0), std::forward_as_tuple()); + enqueue_promise_map.emplace(std::piecewise_construct, std::forward_as_tuple(kQueueSize), + std::forward_as_tuple()); + enqueue_promise_map.emplace(std::piecewise_construct, std::forward_as_tuple(0), + std::forward_as_tuple()); auto enqueue_future = enqueue_promise_map[kQueueSize].get_future(); test_enqueue_end.RegisterEnqueue(&enqueue_promise_map); enqueue_future.wait(); @@ -577,7 +588,8 @@ TEST_F(QueueTest, queue_becomes_non_full_and_empty_at_same_time) { // Register dequeue std::unordered_map> dequeue_promise_map; - dequeue_promise_map.emplace(std::piecewise_construct, std::forward_as_tuple(kQueueSize), std::forward_as_tuple()); + dequeue_promise_map.emplace(std::piecewise_construct, std::forward_as_tuple(kQueueSize), + std::forward_as_tuple()); auto dequeue_future = dequeue_promise_map[kQueueSize].get_future(); test_dequeue_end.RegisterDequeue(&dequeue_promise_map); @@ -609,7 +621,8 @@ TEST_F(QueueTest, queue_becomes_empty_dequeue_callback_only) { test_enqueue_end.buffer_.push(std::move(data)); } std::unordered_map> enqueue_promise_map; - enqueue_promise_map.emplace(std::piecewise_construct, std::forward_as_tuple(0), std::forward_as_tuple()); + enqueue_promise_map.emplace(std::piecewise_construct, std::forward_as_tuple(0), + std::forward_as_tuple()); auto enqueue_future = enqueue_promise_map[0].get_future(); test_enqueue_end.RegisterEnqueue(&enqueue_promise_map); enqueue_future.wait(); @@ -617,8 +630,8 @@ TEST_F(QueueTest, queue_becomes_empty_dequeue_callback_only) { // Register dequeue, expect kHalfOfQueueSize data move to dequeue end buffer std::unordered_map> dequeue_promise_map; - dequeue_promise_map.emplace( - std::piecewise_construct, std::forward_as_tuple(kHalfOfQueueSize), std::forward_as_tuple()); + dequeue_promise_map.emplace(std::piecewise_construct, std::forward_as_tuple(kHalfOfQueueSize), + std::forward_as_tuple()); auto dequeue_future = dequeue_promise_map[kHalfOfQueueSize].get_future(); test_dequeue_end.RegisterDequeue(&dequeue_promise_map); dequeue_future.wait(); @@ -643,7 +656,8 @@ TEST_F(QueueTest, queue_becomes_empty_enqueue_callback_unregister) { test_enqueue_end.buffer_.push(std::move(data)); } std::unordered_map> enqueue_promise_map; - enqueue_promise_map.emplace(std::piecewise_construct, std::forward_as_tuple(0), std::forward_as_tuple()); + enqueue_promise_map.emplace(std::piecewise_construct, std::forward_as_tuple(0), + std::forward_as_tuple()); auto enqueue_future = enqueue_promise_map[0].get_future(); test_enqueue_end.RegisterEnqueue(&enqueue_promise_map); enqueue_future.wait(); @@ -658,7 +672,8 @@ TEST_F(QueueTest, queue_becomes_empty_enqueue_callback_unregister) { // Register dequeue, expect kQueueSize move to dequeue end buffer std::unordered_map> dequeue_promise_map; - dequeue_promise_map.emplace(std::piecewise_construct, std::forward_as_tuple(kQueueSize), std::forward_as_tuple()); + dequeue_promise_map.emplace(std::piecewise_construct, std::forward_as_tuple(kQueueSize), + std::forward_as_tuple()); auto dequeue_future = dequeue_promise_map[kQueueSize].get_future(); test_dequeue_end.RegisterDequeue(&dequeue_promise_map); dequeue_future.wait(); @@ -679,7 +694,8 @@ TEST_F(QueueTest, queue_becomes_non_empty_during_test) { // Register dequeue std::unordered_map> dequeue_promise_map; - dequeue_promise_map.emplace(std::piecewise_construct, std::forward_as_tuple(kQueueSize), std::forward_as_tuple()); + dequeue_promise_map.emplace(std::piecewise_construct, std::forward_as_tuple(kQueueSize), + std::forward_as_tuple()); test_dequeue_end.RegisterDequeue(&dequeue_promise_map); // push kQueueSize data to enqueue end buffer and register enqueue @@ -702,45 +718,39 @@ TEST_F(QueueTest, pass_smart_pointer_and_unregister) { // Enqueue a string std::string valid = "Valid String"; std::shared_ptr shared = std::make_shared(valid); - queue->RegisterEnqueue( - enqueue_handler_, - common::Bind( - [](Queue* queue, std::shared_ptr shared) { - queue->UnregisterEnqueue(); - return std::make_unique(*shared); - }, - common::Unretained(queue), - shared)); + queue->RegisterEnqueue(enqueue_handler_, common::Bind( + [](Queue* queue, + std::shared_ptr shared) { + queue->UnregisterEnqueue(); + return std::make_unique(*shared); + }, + common::Unretained(queue), shared)); // Dequeue the string - queue->RegisterDequeue( - dequeue_handler_, - common::Bind( - [](Queue* queue, std::string valid) { - queue->UnregisterDequeue(); - auto answer = *queue->TryDequeue(); - ASSERT_EQ(answer, valid); - }, - common::Unretained(queue), - valid)); + queue->RegisterDequeue(dequeue_handler_, + common::Bind( + [](Queue* queue, std::string valid) { + queue->UnregisterDequeue(); + auto answer = *queue->TryDequeue(); + ASSERT_EQ(answer, valid); + }, + common::Unretained(queue), valid)); // Wait for both handlers to finish and delete the Queue std::promise promise; auto future = promise.get_future(); enqueue_handler_->Post(common::BindOnce( - [](os::Handler* dequeue_handler, Queue* queue, std::promise* promise) { - dequeue_handler->Post(common::BindOnce( - [](Queue* queue, std::promise* promise) { - delete queue; - promise->set_value(); - }, - common::Unretained(queue), - common::Unretained(promise))); - }, - common::Unretained(dequeue_handler_), - common::Unretained(queue), - common::Unretained(&promise))); + [](os::Handler* dequeue_handler, Queue* queue, std::promise* promise) { + dequeue_handler->Post(common::BindOnce( + [](Queue* queue, std::promise* promise) { + delete queue; + promise->set_value(); + }, + common::Unretained(queue), common::Unretained(promise))); + }, + common::Unretained(dequeue_handler_), common::Unretained(queue), + common::Unretained(&promise))); future.wait(); } @@ -753,7 +763,8 @@ std::unique_ptr sleep_and_enqueue_callback(int* to_increase) { TEST_F(QueueTest, unregister_enqueue_and_wait) { Queue queue(10); int* indicator = new int(100); - queue.RegisterEnqueue(enqueue_handler_, common::Bind(&sleep_and_enqueue_callback, common::Unretained(indicator))); + queue.RegisterEnqueue(enqueue_handler_, + common::Bind(&sleep_and_enqueue_callback, common::Unretained(indicator))); std::this_thread::sleep_for(std::chrono::milliseconds(50)); queue.UnregisterEnqueue(); EXPECT_EQ(*indicator, 101); @@ -761,7 +772,7 @@ TEST_F(QueueTest, unregister_enqueue_and_wait) { } std::unique_ptr sleep_and_enqueue_callback_and_unregister( - int* to_increase, Queue* queue, std::atomic_bool* is_registered) { + int* to_increase, Queue* queue, std::atomic_bool* is_registered) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); (*to_increase)++; if (is_registered->exchange(false)) { @@ -775,12 +786,9 @@ TEST_F(QueueTest, unregister_enqueue_and_wait_maybe_unregistered) { int* indicator = new int(100); std::atomic_bool is_registered = true; queue.RegisterEnqueue( - enqueue_handler_, - common::Bind( - &sleep_and_enqueue_callback_and_unregister, - common::Unretained(indicator), - common::Unretained(&queue), - common::Unretained(&is_registered))); + enqueue_handler_, + common::Bind(&sleep_and_enqueue_callback_and_unregister, common::Unretained(indicator), + common::Unretained(&queue), common::Unretained(&is_registered))); std::this_thread::sleep_for(std::chrono::milliseconds(50)); if (is_registered.exchange(false)) { queue.UnregisterEnqueue(); @@ -797,15 +805,14 @@ void sleep_and_dequeue_callback(int* to_increase) { TEST_F(QueueTest, unregister_dequeue_and_wait) { int* indicator = new int(100); Queue queue(10); - queue.RegisterEnqueue( - enqueue_handler_, - common::Bind( - [](Queue* queue) { - queue->UnregisterEnqueue(); - return std::make_unique("Hello"); - }, - common::Unretained(&queue))); - queue.RegisterDequeue(enqueue_handler_, common::Bind(&sleep_and_dequeue_callback, common::Unretained(indicator))); + queue.RegisterEnqueue(enqueue_handler_, common::Bind( + [](Queue* queue) { + queue->UnregisterEnqueue(); + return std::make_unique("Hello"); + }, + common::Unretained(&queue))); + queue.RegisterDequeue(enqueue_handler_, + common::Bind(&sleep_and_dequeue_callback, common::Unretained(indicator))); std::this_thread::sleep_for(std::chrono::milliseconds(50)); queue.UnregisterDequeue(); EXPECT_EQ(*indicator, 101); @@ -814,13 +821,14 @@ TEST_F(QueueTest, unregister_dequeue_and_wait) { // Create all threads for death tests in the function that dies class QueueDeathTest : public ::testing::Test { - public: +public: void RegisterEnqueueAndDelete() { Thread* enqueue_thread = new Thread("enqueue_thread", Thread::Priority::NORMAL); Handler* enqueue_handler = new Handler(enqueue_thread); Queue* queue = new Queue(kQueueSizeOne); - queue->RegisterEnqueue( - enqueue_handler, common::Bind([]() { return std::make_unique("A string to fill the queue"); })); + queue->RegisterEnqueue(enqueue_handler, common::Bind([]() { + return std::make_unique("A string to fill the queue"); + })); delete queue; } @@ -828,9 +836,9 @@ class QueueDeathTest : public ::testing::Test { Thread* dequeue_thread = new Thread("dequeue_thread", Thread::Priority::NORMAL); Handler* dequeue_handler = new Handler(dequeue_thread); Queue* queue = new Queue(kQueueSizeOne); - queue->RegisterDequeue( - dequeue_handler, - common::Bind([](Queue* queue) { queue->TryDequeue(); }, common::Unretained(queue))); + queue->RegisterDequeue(dequeue_handler, + common::Bind([](Queue* queue) { queue->TryDequeue(); }, + common::Unretained(queue))); delete queue; } }; @@ -844,11 +852,12 @@ TEST_F(QueueDeathTest, die_if_dequeue_not_unregistered) { } class MockIQueueEnqueue : public IQueueEnqueue { - public: +public: void RegisterEnqueue(Handler* handler, EnqueueCallback callback) override { EXPECT_FALSE(registered_); registered_ = true; - handler->Post(common::BindOnce(&MockIQueueEnqueue::handle_register_enqueue, common::Unretained(this), callback)); + handler->Post(common::BindOnce(&MockIQueueEnqueue::handle_register_enqueue, + common::Unretained(this), callback)); } void handle_register_enqueue(EnqueueCallback callback) { @@ -872,7 +881,7 @@ class MockIQueueEnqueue : public IQueueEnqueue { }; class EnqueueBufferTest : public ::testing::Test { - protected: +protected: void SetUp() override { thread_ = new Thread("test_thread", Thread::Priority::NORMAL); handler_ = new Handler(thread_); @@ -887,7 +896,8 @@ class EnqueueBufferTest : public ::testing::Test { void SynchronizeHandler() { std::promise promise; auto future = promise.get_future(); - handler_->Post(common::BindOnce([](std::promise promise) { promise.set_value(); }, std::move(promise))); + handler_->Post(common::BindOnce([](std::promise promise) { promise.set_value(); }, + std::move(promise))); future.wait(); } diff --git a/system/gd/os/linux_generic/reactive_semaphore.cc b/system/gd/os/linux_generic/reactive_semaphore.cc index 0f0e9e73371..47d1ee9406c 100644 --- a/system/gd/os/linux_generic/reactive_semaphore.cc +++ b/system/gd/os/linux_generic/reactive_semaphore.cc @@ -29,7 +29,8 @@ namespace bluetooth { namespace os { -ReactiveSemaphore::ReactiveSemaphore(unsigned int value) : fd_(eventfd(value, EFD_SEMAPHORE | EFD_NONBLOCK)) { +ReactiveSemaphore::ReactiveSemaphore(unsigned int value) + : fd_(eventfd(value, EFD_SEMAPHORE | EFD_NONBLOCK)) { log::assert_that(fd_ != -1, "assert failed: fd_ != -1"); } @@ -51,9 +52,7 @@ void ReactiveSemaphore::Increase() { log::assert_that(write_result != -1, "increase failed: {}", strerror(errno)); } -int ReactiveSemaphore::GetFd() { - return fd_; -} +int ReactiveSemaphore::GetFd() { return fd_; } } // namespace os } // namespace bluetooth diff --git a/system/gd/os/linux_generic/reactive_semaphore.h b/system/gd/os/linux_generic/reactive_semaphore.h index dd54b1a9dcb..ac10d761439 100644 --- a/system/gd/os/linux_generic/reactive_semaphore.h +++ b/system/gd/os/linux_generic/reactive_semaphore.h @@ -23,7 +23,7 @@ namespace os { // A event_fd work in non-blocking and Semaphore mode class ReactiveSemaphore { - public: +public: // Creates a new ReactiveSemaphore with an initial value of |value|. explicit ReactiveSemaphore(unsigned int value); @@ -37,7 +37,7 @@ class ReactiveSemaphore { void Increase(); int GetFd(); - private: +private: int fd_; }; diff --git a/system/gd/os/linux_generic/reactor.cc b/system/gd/os/linux_generic/reactor.cc index 90186e0897a..36574330d5d 100644 --- a/system/gd/os/linux_generic/reactor.cc +++ b/system/gd/os/linux_generic/reactor.cc @@ -56,17 +56,13 @@ struct Reactor::Event::impl { }; Reactor::Event::Event() : pimpl_(new impl()) {} -Reactor::Event::~Event() { - delete pimpl_; -} +Reactor::Event::~Event() { delete pimpl_; } bool Reactor::Event::Read() { uint64_t val = 0; return eventfd_read(pimpl_->fd_, &val) == 0; } -int Reactor::Event::Id() const { - return pimpl_->fd_; -} +int Reactor::Event::Id() const { return pimpl_->fd_; } void Reactor::Event::Clear() { uint64_t val; while (eventfd_read(pimpl_->fd_, &val) == 0) { @@ -84,7 +80,7 @@ void Reactor::Event::Notify() { } class Reactor::Reactable { - public: +public: Reactable(int fd, Closure on_read_ready, Closure on_write_ready) : fd_(fd), on_read_ready_(std::move(on_read_ready)), @@ -172,7 +168,8 @@ void Reactor::Run() { std::unique_lock lock(mutex_); executing_reactable_finished_ = nullptr; // See if this reactable has been removed in the meantime. - if (std::find(invalidation_list_.begin(), invalidation_list_.end(), reactable) != invalidation_list_.end()) { + if (std::find(invalidation_list_.begin(), invalidation_list_.end(), reactable) != + invalidation_list_.end()) { continue; } @@ -181,7 +178,8 @@ void Reactor::Run() { lock.unlock(); reactable->is_executing_ = true; } - if (event.events & (EPOLLIN | EPOLLHUP | EPOLLRDHUP | EPOLLERR) && !reactable->on_read_ready_.is_null()) { + if (event.events & (EPOLLIN | EPOLLHUP | EPOLLRDHUP | EPOLLERR) && + !reactable->on_read_ready_.is_null()) { reactable->on_read_ready_.Run(); } if (event.events & EPOLLOUT && !reactable->on_write_ready_.is_null()) { @@ -222,8 +220,8 @@ Reactor::Reactable* Reactor::Register(int fd, Closure on_read_ready, Closure on_ } auto* reactable = new Reactable(fd, on_read_ready, on_write_ready); epoll_event event = { - .events = poll_event_type, - .data = {.ptr = reactable}, + .events = poll_event_type, + .data = {.ptr = reactable}, }; int register_fd; RUN_NO_INTR(register_fd = epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, fd, &event)); @@ -248,12 +246,14 @@ void Reactor::Unregister(Reactor::Reactable* reactable) { log::assert_that(result != -1, "could not unregister epoll fd: {}", strerror(errno)); } - // If we are unregistering during the callback event from this reactable, we delete it after the callback is - // executed. reactable->is_executing_ is protected by reactable->mutex_, so it's thread safe. + // If we are unregistering during the callback event from this reactable, we delete it after the + // callback is executed. reactable->is_executing_ is protected by reactable->mutex_, so it's + // thread safe. if (reactable->is_executing_) { reactable->removed_ = true; reactable->finished_promise_ = std::make_unique>(); - executing_reactable_finished_ = std::make_shared>(reactable->finished_promise_->get_future()); + executing_reactable_finished_ = + std::make_shared>(reactable->finished_promise_->get_future()); delaying_delete_until_callback_finished = true; } } @@ -301,8 +301,8 @@ void Reactor::ModifyRegistration(Reactor::Reactable* reactable, ReactOn react_on poll_event_type |= EPOLLOUT; } epoll_event event = { - .events = poll_event_type, - .data = {.ptr = reactable}, + .events = poll_event_type, + .data = {.ptr = reactable}, }; int modify_fd; RUN_NO_INTR(modify_fd = epoll_ctl(epoll_fd_, EPOLL_CTL_MOD, reactable->fd_, &event)); diff --git a/system/gd/os/linux_generic/reactor_unittest.cc b/system/gd/os/linux_generic/reactor_unittest.cc index 7893f55f92c..de6b829a678 100644 --- a/system/gd/os/linux_generic/reactor_unittest.cc +++ b/system/gd/os/linux_generic/reactor_unittest.cc @@ -39,7 +39,7 @@ using common::Bind; std::promise* g_promise; class ReactorTest : public ::testing::Test { - protected: +protected: void SetUp() override { g_promise = new std::promise; reactor_ = new Reactor; @@ -56,14 +56,10 @@ class ReactorTest : public ::testing::Test { }; class SampleReactable { - public: - SampleReactable() : fd_(eventfd(0, EFD_NONBLOCK)) { - EXPECT_NE(fd_, -1); - } +public: + SampleReactable() : fd_(eventfd(0, EFD_NONBLOCK)) { EXPECT_NE(fd_, -1); } - ~SampleReactable() { - close(fd_); - } + ~SampleReactable() { close(fd_); } void OnReadReady() {} @@ -73,24 +69,18 @@ class SampleReactable { }; class FakeReactable { - public: +public: enum EventFdValue { kSetPromise = 1, kRegisterSampleReactable, kUnregisterSampleReactable, kSampleOutputValue, }; - FakeReactable() : fd_(eventfd(0, 0)), reactor_(nullptr) { - EXPECT_NE(fd_, -1); - } + FakeReactable() : fd_(eventfd(0, 0)), reactor_(nullptr) { EXPECT_NE(fd_, -1); } - FakeReactable(Reactor* reactor) : fd_(eventfd(0, 0)), reactor_(reactor) { - EXPECT_NE(fd_, -1); - } + FakeReactable(Reactor* reactor) : fd_(eventfd(0, 0)), reactor_(reactor) { EXPECT_NE(fd_, -1); } - ~FakeReactable() { - close(fd_); - } + ~FakeReactable() { close(fd_); } void OnReadReady() { log::info(""); @@ -103,9 +93,8 @@ class FakeReactable { } if (value == kRegisterSampleReactable) { reactable_ = reactor_->Register( - sample_reactable_.fd_, - Bind(&FakeReactable::OnReadReady, common::Unretained(this)), - Bind(&FakeReactable::OnWriteReadyNoOp, common::Unretained(this))); + sample_reactable_.fd_, Bind(&FakeReactable::OnReadReady, common::Unretained(this)), + Bind(&FakeReactable::OnWriteReadyNoOp, common::Unretained(this))); g_promise->set_value(kReadReadyValue); } if (value == kUnregisterSampleReactable) { @@ -134,20 +123,16 @@ class FakeReactable { Reactor::Reactable* reactable_ = nullptr; int fd_; - private: +private: Reactor* reactor_; uint64_t output_data_ = kSampleOutputValue; }; class FakeRunningReactable { - public: - FakeRunningReactable() : fd_(eventfd(0, 0)) { - EXPECT_NE(fd_, -1); - } +public: + FakeRunningReactable() : fd_(eventfd(0, 0)) { EXPECT_NE(fd_, -1); } - ~FakeRunningReactable() { - close(fd_); - } + ~FakeRunningReactable() { close(fd_); } void OnReadReady() { uint64_t value = 0; @@ -189,16 +174,20 @@ TEST_F(ReactorTest, stop_multi_times) { TEST_F(ReactorTest, cold_register_only) { FakeReactable fake_reactable; - auto* reactable = reactor_->Register( - fake_reactable.fd_, Bind(&FakeReactable::OnReadReady, common::Unretained(&fake_reactable)), common::Closure()); + auto* reactable = + reactor_->Register(fake_reactable.fd_, + Bind(&FakeReactable::OnReadReady, common::Unretained(&fake_reactable)), + common::Closure()); reactor_->Unregister(reactable); } TEST_F(ReactorTest, cold_register) { FakeReactable fake_reactable; - auto* reactable = reactor_->Register( - fake_reactable.fd_, Bind(&FakeReactable::OnReadReady, common::Unretained(&fake_reactable)), common::Closure()); + auto* reactable = + reactor_->Register(fake_reactable.fd_, + Bind(&FakeReactable::OnReadReady, common::Unretained(&fake_reactable)), + common::Closure()); auto reactor_thread = std::thread(&Reactor::Run, reactor_); auto future = g_promise->get_future(); @@ -215,8 +204,10 @@ TEST_F(ReactorTest, hot_register_from_different_thread) { auto future = g_promise->get_future(); FakeReactable fake_reactable; - auto* reactable = reactor_->Register( - fake_reactable.fd_, Bind(&FakeReactable::OnReadReady, common::Unretained(&fake_reactable)), common::Closure()); + auto* reactable = + reactor_->Register(fake_reactable.fd_, + Bind(&FakeReactable::OnReadReady, common::Unretained(&fake_reactable)), + common::Closure()); auto write_result = eventfd_write(fake_reactable.fd_, FakeReactable::kSetPromise); EXPECT_EQ(write_result, 0); EXPECT_EQ(future.get(), kReadReadyValue); @@ -229,9 +220,9 @@ TEST_F(ReactorTest, hot_register_from_different_thread) { TEST_F(ReactorTest, unregister_from_different_thread_while_task_is_executing_) { FakeRunningReactable fake_reactable; auto* reactable = reactor_->Register( - fake_reactable.fd_, - Bind(&FakeRunningReactable::OnReadReady, common::Unretained(&fake_reactable)), - common::Closure()); + fake_reactable.fd_, + Bind(&FakeRunningReactable::OnReadReady, common::Unretained(&fake_reactable)), + common::Closure()); auto reactor_thread = std::thread(&Reactor::Run, reactor_); auto write_result = eventfd_write(fake_reactable.fd_, 1); ASSERT_EQ(write_result, 0); @@ -247,9 +238,9 @@ TEST_F(ReactorTest, unregister_from_different_thread_while_task_is_executing_) { TEST_F(ReactorTest, unregister_from_different_thread_while_task_is_executing_wait_fails) { FakeRunningReactable fake_reactable; auto* reactable = reactor_->Register( - fake_reactable.fd_, - common::Bind(&FakeRunningReactable::OnReadReady, common::Unretained(&fake_reactable)), - common::Closure()); + fake_reactable.fd_, + common::Bind(&FakeRunningReactable::OnReadReady, common::Unretained(&fake_reactable)), + common::Closure()); auto reactor_thread = std::thread(&Reactor::Run, reactor_); auto write_result = eventfd_write(fake_reactable.fd_, 1); ASSERT_EQ(write_result, 0); @@ -266,9 +257,9 @@ TEST_F(ReactorTest, unregister_from_different_thread_while_task_is_executing_wai TEST_F(ReactorTest, unregister_from_different_thread_while_task_is_executing_wait_succeeds) { FakeRunningReactable fake_reactable; auto* reactable = reactor_->Register( - fake_reactable.fd_, - common::Bind(&FakeRunningReactable::OnReadReady, common::Unretained(&fake_reactable)), - common::Closure()); + fake_reactable.fd_, + common::Bind(&FakeRunningReactable::OnReadReady, common::Unretained(&fake_reactable)), + common::Closure()); auto reactor_thread = std::thread(&Reactor::Run, reactor_); auto write_result = eventfd_write(fake_reactable.fd_, 1); ASSERT_EQ(write_result, 0); @@ -284,8 +275,10 @@ TEST_F(ReactorTest, unregister_from_different_thread_while_task_is_executing_wai TEST_F(ReactorTest, hot_unregister_from_different_thread) { FakeReactable fake_reactable; - auto* reactable = reactor_->Register( - fake_reactable.fd_, Bind(&FakeReactable::OnReadReady, common::Unretained(&fake_reactable)), common::Closure()); + auto* reactable = + reactor_->Register(fake_reactable.fd_, + Bind(&FakeReactable::OnReadReady, common::Unretained(&fake_reactable)), + common::Closure()); auto reactor_thread = std::thread(&Reactor::Run, reactor_); reactor_->Unregister(reactable); auto future = g_promise->get_future(); @@ -304,8 +297,10 @@ TEST_F(ReactorTest, hot_register_from_same_thread) { auto future = g_promise->get_future(); FakeReactable fake_reactable(reactor_); - auto* reactable = reactor_->Register( - fake_reactable.fd_, Bind(&FakeReactable::OnReadReady, common::Unretained(&fake_reactable)), common::Closure()); + auto* reactable = + reactor_->Register(fake_reactable.fd_, + Bind(&FakeReactable::OnReadReady, common::Unretained(&fake_reactable)), + common::Closure()); auto write_result = eventfd_write(fake_reactable.fd_, FakeReactable::kRegisterSampleReactable); EXPECT_EQ(write_result, 0); EXPECT_EQ(future.get(), kReadReadyValue); @@ -325,8 +320,10 @@ TEST_F(ReactorTest, hot_unregister_from_same_thread) { auto future = g_promise->get_future(); FakeReactable fake_reactable(reactor_); - auto* reactable = reactor_->Register( - fake_reactable.fd_, Bind(&FakeReactable::OnReadReady, common::Unretained(&fake_reactable)), common::Closure()); + auto* reactable = + reactor_->Register(fake_reactable.fd_, + Bind(&FakeReactable::OnReadReady, common::Unretained(&fake_reactable)), + common::Closure()); auto write_result = eventfd_write(fake_reactable.fd_, FakeReactable::kRegisterSampleReactable); EXPECT_EQ(write_result, 0); EXPECT_EQ(future.get(), kReadReadyValue); @@ -349,13 +346,15 @@ TEST_F(ReactorTest, hot_unregister_from_callback) { FakeReactable fake_reactable1(reactor_); auto* reactable1 = reactor_->Register( - fake_reactable1.fd_, Bind(&FakeReactable::OnReadReady, common::Unretained(&fake_reactable1)), common::Closure()); + fake_reactable1.fd_, + Bind(&FakeReactable::OnReadReady, common::Unretained(&fake_reactable1)), + common::Closure()); FakeReactable fake_reactable2(reactor_); auto* reactable2 = reactor_->Register( - fake_reactable2.fd_, - Bind(&FakeReactable::UnregisterInCallback, common::Unretained(&fake_reactable2)), - common::Closure()); + fake_reactable2.fd_, + Bind(&FakeReactable::UnregisterInCallback, common::Unretained(&fake_reactable2)), + common::Closure()); fake_reactable2.reactable_ = reactable2; auto write_result = eventfd_write(fake_reactable2.fd_, 1); EXPECT_EQ(write_result, 0); @@ -371,13 +370,15 @@ TEST_F(ReactorTest, hot_unregister_during_unregister_from_callback) { FakeReactable fake_reactable1(reactor_); auto* reactable1 = reactor_->Register( - fake_reactable1.fd_, Bind(&FakeReactable::OnReadReady, common::Unretained(&fake_reactable1)), common::Closure()); + fake_reactable1.fd_, + Bind(&FakeReactable::OnReadReady, common::Unretained(&fake_reactable1)), + common::Closure()); FakeReactable fake_reactable2(reactor_); auto* reactable2 = reactor_->Register( - fake_reactable2.fd_, - Bind(&FakeReactable::UnregisterInCallback, common::Unretained(&fake_reactable2)), - common::Closure()); + fake_reactable2.fd_, + Bind(&FakeReactable::UnregisterInCallback, common::Unretained(&fake_reactable2)), + common::Closure()); fake_reactable2.reactable_ = reactable2; auto write_result = eventfd_write(fake_reactable2.fd_, 1); EXPECT_EQ(write_result, 0); @@ -402,7 +403,8 @@ TEST_F(ReactorTest, start_and_stop_multi_times) { TEST_F(ReactorTest, on_write_ready) { FakeReactable fake_reactable; auto* reactable = reactor_->Register( - fake_reactable.fd_, common::Closure(), Bind(&FakeReactable::OnWriteReady, common::Unretained(&fake_reactable))); + fake_reactable.fd_, common::Closure(), + Bind(&FakeReactable::OnWriteReady, common::Unretained(&fake_reactable))); auto reactor_thread = std::thread(&Reactor::Run, reactor_); uint64_t value = 0; auto read_result = eventfd_read(fake_reactable.fd_, &value); @@ -418,9 +420,9 @@ TEST_F(ReactorTest, on_write_ready) { TEST_F(ReactorTest, modify_registration) { FakeReactable fake_reactable; auto* reactable = reactor_->Register( - fake_reactable.fd_, - Bind(&FakeReactable::OnReadReady, common::Unretained(&fake_reactable)), - Bind(&FakeReactable::OnWriteReady, common::Unretained(&fake_reactable))); + fake_reactable.fd_, + Bind(&FakeReactable::OnReadReady, common::Unretained(&fake_reactable)), + Bind(&FakeReactable::OnWriteReady, common::Unretained(&fake_reactable))); auto reactor_thread = std::thread(&Reactor::Run, reactor_); diff --git a/system/gd/os/linux_generic/repeating_alarm.cc b/system/gd/os/linux_generic/repeating_alarm.cc index 36fdddbd6ef..f62de8be652 100644 --- a/system/gd/os/linux_generic/repeating_alarm.cc +++ b/system/gd/os/linux_generic/repeating_alarm.cc @@ -37,11 +37,12 @@ namespace bluetooth { namespace os { using common::Closure; -RepeatingAlarm::RepeatingAlarm(Handler* handler) : handler_(handler), fd_(TIMERFD_CREATE(ALARM_CLOCK, 0)) { +RepeatingAlarm::RepeatingAlarm(Handler* handler) + : handler_(handler), fd_(TIMERFD_CREATE(ALARM_CLOCK, 0)) { log::assert_that(fd_ != -1, "assert failed: fd_ != -1"); token_ = handler_->thread_->GetReactor()->Register( - fd_, common::Bind(&RepeatingAlarm::on_fire, common::Unretained(this)), common::Closure()); + fd_, common::Bind(&RepeatingAlarm::on_fire, common::Unretained(this)), common::Closure()); } RepeatingAlarm::~RepeatingAlarm() { @@ -77,9 +78,8 @@ void RepeatingAlarm::on_fire() { auto bytes_read = read(fd_, ×_invoked, sizeof(uint64_t)); lock.unlock(); task.Run(); - log::assert_that( - bytes_read == static_cast(sizeof(uint64_t)), - "assert failed: bytes_read == static_cast(sizeof(uint64_t))"); + log::assert_that(bytes_read == static_cast(sizeof(uint64_t)), + "assert failed: bytes_read == static_cast(sizeof(uint64_t))"); } } // namespace os diff --git a/system/gd/os/linux_generic/repeating_alarm_unittest.cc b/system/gd/os/linux_generic/repeating_alarm_unittest.cc index a1329845f55..f101f505c95 100644 --- a/system/gd/os/linux_generic/repeating_alarm_unittest.cc +++ b/system/gd/os/linux_generic/repeating_alarm_unittest.cc @@ -31,7 +31,7 @@ using fake_timer::fake_timerfd_advance; using fake_timer::fake_timerfd_reset; class RepeatingAlarmTest : public ::testing::Test { - protected: +protected: void SetUp() override { thread_ = new Thread("test_thread", Thread::Priority::NORMAL); handler_ = new Handler(thread_); @@ -46,34 +46,25 @@ class RepeatingAlarmTest : public ::testing::Test { fake_timerfd_reset(); } - void VerifyMultipleDelayedTasks(int scheduled_tasks, int task_length_ms, int interval_between_tasks_ms) { + void VerifyMultipleDelayedTasks(int scheduled_tasks, int task_length_ms, + int interval_between_tasks_ms) { std::promise promise; auto future = promise.get_future(); auto start_time = std::chrono::steady_clock::now(); int counter = 0; alarm_->Schedule( - common::Bind( - &RepeatingAlarmTest::verify_delayed_tasks, - common::Unretained(this), - common::Unretained(&counter), - start_time, - scheduled_tasks, - common::Unretained(&promise), - task_length_ms, - interval_between_tasks_ms), - std::chrono::milliseconds(interval_between_tasks_ms)); + common::Bind(&RepeatingAlarmTest::verify_delayed_tasks, common::Unretained(this), + common::Unretained(&counter), start_time, scheduled_tasks, + common::Unretained(&promise), task_length_ms, interval_between_tasks_ms), + std::chrono::milliseconds(interval_between_tasks_ms)); fake_timer_advance(interval_between_tasks_ms * scheduled_tasks); future.get(); alarm_->Cancel(); } - void verify_delayed_tasks( - int* counter, - std::chrono::steady_clock::time_point /* start_time */, - int scheduled_tasks, - std::promise* promise, - int /* task_length_ms */, - int /* interval_between_tasks_ms */) { + void verify_delayed_tasks(int* counter, std::chrono::steady_clock::time_point /* start_time */, + int scheduled_tasks, std::promise* promise, + int /* task_length_ms */, int /* interval_between_tasks_ms */) { *counter = *counter + 1; if (*counter == scheduled_tasks) { promise->set_value(); @@ -88,21 +79,19 @@ class RepeatingAlarmTest : public ::testing::Test { common::Closure should_not_happen_ = common::Bind([]() { FAIL(); }); - private: +private: Thread* thread_; Handler* handler_; }; -TEST_F(RepeatingAlarmTest, cancel_while_not_armed) { - alarm_->Cancel(); -} +TEST_F(RepeatingAlarmTest, cancel_while_not_armed) { alarm_->Cancel(); } TEST_F(RepeatingAlarmTest, schedule) { std::promise promise; auto future = promise.get_future(); int period_ms = 10; - alarm_->Schedule( - common::Bind(&std::promise::set_value, common::Unretained(&promise)), std::chrono::milliseconds(period_ms)); + alarm_->Schedule(common::Bind(&std::promise::set_value, common::Unretained(&promise)), + std::chrono::milliseconds(period_ms)); fake_timer_advance(period_ms); future.get(); alarm_->Cancel(); @@ -118,15 +107,13 @@ TEST_F(RepeatingAlarmTest, cancel_alarm) { TEST_F(RepeatingAlarmTest, cancel_alarm_from_callback) { std::promise promise; auto future = promise.get_future(); - alarm_->Schedule( - common::Bind( - [](RepeatingAlarm* alarm, std::promise* promise) { - alarm->Cancel(); - promise->set_value(); - }, - common::Unretained(this->alarm_), - common::Unretained(&promise)), - std::chrono::milliseconds(1)); + alarm_->Schedule(common::Bind( + [](RepeatingAlarm* alarm, std::promise* promise) { + alarm->Cancel(); + promise->set_value(); + }, + common::Unretained(this->alarm_), common::Unretained(&promise)), + std::chrono::milliseconds(1)); fake_timer_advance(1); ASSERT_EQ(std::future_status::ready, future.wait_for(std::chrono::seconds(1))); } @@ -135,8 +122,8 @@ TEST_F(RepeatingAlarmTest, schedule_while_alarm_armed) { alarm_->Schedule(should_not_happen_, std::chrono::milliseconds(1)); std::promise promise; auto future = promise.get_future(); - alarm_->Schedule( - common::Bind(&std::promise::set_value, common::Unretained(&promise)), std::chrono::milliseconds(10)); + alarm_->Schedule(common::Bind(&std::promise::set_value, common::Unretained(&promise)), + std::chrono::milliseconds(10)); fake_timer_advance(10); ASSERT_EQ(std::future_status::ready, future.wait_for(std::chrono::seconds(1))); alarm_->Cancel(); @@ -149,13 +136,9 @@ TEST_F(RepeatingAlarmTest, delete_while_alarm_armed) { fake_timer_advance(10); } -TEST_F(RepeatingAlarmTest, verify_small) { - VerifyMultipleDelayedTasks(100, 1, 10); -} +TEST_F(RepeatingAlarmTest, verify_small) { VerifyMultipleDelayedTasks(100, 1, 10); } -TEST_F(RepeatingAlarmTest, verify_large) { - VerifyMultipleDelayedTasks(100, 3, 10); -} +TEST_F(RepeatingAlarmTest, verify_large) { VerifyMultipleDelayedTasks(100, 3, 10); } } // namespace } // namespace os diff --git a/system/gd/os/linux_generic/thread.cc b/system/gd/os/linux_generic/thread.cc index 3483d5cdfcd..9bc2e496b1b 100644 --- a/system/gd/os/linux_generic/thread.cc +++ b/system/gd/os/linux_generic/thread.cc @@ -49,15 +49,12 @@ void Thread::run(Priority priority) { reactor_.Run(); } -Thread::~Thread() { - Stop(); -} +Thread::~Thread() { Stop(); } bool Thread::Stop() { std::lock_guard lock(mutex_); - log::assert_that( - std::this_thread::get_id() != running_thread_.get_id(), - "assert failed: std::this_thread::get_id() != running_thread_.get_id()"); + log::assert_that(std::this_thread::get_id() != running_thread_.get_id(), + "assert failed: std::this_thread::get_id() != running_thread_.get_id()"); if (!running_thread_.joinable()) { return false; @@ -67,21 +64,13 @@ bool Thread::Stop() { return true; } -bool Thread::IsSameThread() const { - return std::this_thread::get_id() == running_thread_.get_id(); -} +bool Thread::IsSameThread() const { return std::this_thread::get_id() == running_thread_.get_id(); } -Reactor* Thread::GetReactor() const { - return &reactor_; -} +Reactor* Thread::GetReactor() const { return &reactor_; } -std::string Thread::GetThreadName() const { - return name_; -} +std::string Thread::GetThreadName() const { return name_; } -std::string Thread::ToString() const { - return "Thread " + name_; -} +std::string Thread::ToString() const { return "Thread " + name_; } } // namespace os } // namespace bluetooth diff --git a/system/gd/os/linux_generic/thread_unittest.cc b/system/gd/os/linux_generic/thread_unittest.cc index 811b6c2a8f3..90579348459 100644 --- a/system/gd/os/linux_generic/thread_unittest.cc +++ b/system/gd/os/linux_generic/thread_unittest.cc @@ -29,14 +29,13 @@ namespace { constexpr int kCheckIsSameThread = 1; class SampleReactable { - public: - explicit SampleReactable(Thread* thread) : thread_(thread), fd_(eventfd(0, 0)), is_same_thread_checked_(false) { +public: + explicit SampleReactable(Thread* thread) + : thread_(thread), fd_(eventfd(0, 0)), is_same_thread_checked_(false) { EXPECT_NE(fd_, 0); } - ~SampleReactable() { - close(fd_); - } + ~SampleReactable() { close(fd_); } void OnReadReady() { EXPECT_TRUE(thread_->IsSameThread()); @@ -45,9 +44,7 @@ class SampleReactable { eventfd_read(fd_, &val); } - bool IsSameThreadCheckDone() { - return is_same_thread_checked_; - } + bool IsSameThreadCheckDone() { return is_same_thread_checked_; } Thread* thread_; int fd_; @@ -55,44 +52,36 @@ class SampleReactable { }; class ThreadTest : public ::testing::Test { - protected: - void SetUp() override { - thread = new Thread("test", Thread::Priority::NORMAL); - } +protected: + void SetUp() override { thread = new Thread("test", Thread::Priority::NORMAL); } - void TearDown() override { - delete thread; - } + void TearDown() override { delete thread; } Thread* thread = nullptr; }; -TEST_F(ThreadTest, just_stop_no_op) { - thread->Stop(); -} +TEST_F(ThreadTest, just_stop_no_op) { thread->Stop(); } -TEST_F(ThreadTest, thread_name) { - EXPECT_EQ(thread->GetThreadName(), "test"); -} +TEST_F(ThreadTest, thread_name) { EXPECT_EQ(thread->GetThreadName(), "test"); } TEST_F(ThreadTest, thread_to_string) { EXPECT_NE(thread->ToString().find("test"), std::string::npos); } -TEST_F(ThreadTest, not_same_thread) { - EXPECT_FALSE(thread->IsSameThread()); -} +TEST_F(ThreadTest, not_same_thread) { EXPECT_FALSE(thread->IsSameThread()); } TEST_F(ThreadTest, same_thread) { Reactor* reactor = thread->GetReactor(); SampleReactable sample_reactable(thread); auto* reactable = reactor->Register( - sample_reactable.fd_, - common::Bind(&SampleReactable::OnReadReady, common::Unretained(&sample_reactable)), - common::Closure()); + sample_reactable.fd_, + common::Bind(&SampleReactable::OnReadReady, common::Unretained(&sample_reactable)), + common::Closure()); int fd = sample_reactable.fd_; int write_result = eventfd_write(fd, kCheckIsSameThread); EXPECT_EQ(write_result, 0); - while (!sample_reactable.IsSameThreadCheckDone()) std::this_thread::yield(); + while (!sample_reactable.IsSameThreadCheckDone()) { + std::this_thread::yield(); + } reactor->Unregister(reactable); } diff --git a/system/gd/os/linux_generic/wakelock_manager.cc b/system/gd/os/linux_generic/wakelock_manager.cc index 9972fe0ddd2..a5b65ac35b3 100644 --- a/system/gd/os/linux_generic/wakelock_manager.cc +++ b/system/gd/os/linux_generic/wakelock_manager.cc @@ -133,7 +133,7 @@ struct WakelockManager::Stats { } flatbuffers::Offset GetDumpsysData( - flatbuffers::FlatBufferBuilder* fb_builder, bool is_native) const { + flatbuffers::FlatBufferBuilder* fb_builder, bool is_native) const { const uint64_t just_now_ms = now_ms(); // Compute the last acquired interval if the wakelock is still acquired uint64_t delta_ms = 0; @@ -189,8 +189,8 @@ void WakelockManager::SetOsCallouts(OsCallouts* callouts, Handler* handler) { os_callouts_handler_ = handler; is_native_ = (os_callouts_ == nullptr); if (is_native_) { - log::assert_that( - os_callouts_handler_ != nullptr, "handler must not be null when callout is not null"); + log::assert_that(os_callouts_handler_ != nullptr, + "handler must not be null when callout is not null"); } log::info("set to {}", is_native_ ? "native" : "non-native"); } @@ -264,7 +264,8 @@ void WakelockManager::CleanUp() { initialized_ = false; } -flatbuffers::Offset WakelockManager::GetDumpsysData(flatbuffers::FlatBufferBuilder* fb_builder) { +flatbuffers::Offset WakelockManager::GetDumpsysData( + flatbuffers::FlatBufferBuilder* fb_builder) { std::lock_guard lock_guard(mutex_); return pstats_->GetDumpsysData(fb_builder, is_native_); } diff --git a/system/gd/os/linux_generic/wakelock_manager_unittest.cc b/system/gd/os/linux_generic/wakelock_manager_unittest.cc index 4359371902a..e070d24fb58 100644 --- a/system/gd/os/linux_generic/wakelock_manager_unittest.cc +++ b/system/gd/os/linux_generic/wakelock_manager_unittest.cc @@ -15,18 +15,18 @@ * limitations under the License. * ******************************************************************************/ -#include -#include +#include "os/wakelock_manager.h" #include #include -#include "flatbuffers/flatbuffers.h" +#include +#include #include "common/bind.h" +#include "flatbuffers/flatbuffers.h" #include "os/handler.h" #include "os/thread.h" -#include "os/wakelock_manager.h" #include "wakelock_manager_generated.h" namespace testing { @@ -40,7 +40,7 @@ using bluetooth::os::WakelockManagerData; using bluetooth::os::WakelockManagerDataBuilder; class TestOsCallouts : public WakelockManager::OsCallouts { - public: +public: void AcquireCallout(const std::string& lock_name) override { auto iter = acquired_lock_counts.find(lock_name); if (iter == acquired_lock_counts.end()) { @@ -70,7 +70,7 @@ class TestOsCallouts : public WakelockManager::OsCallouts { }; class WakelockManagerTest : public Test { - protected: +protected: void SetUp() override { thread_ = new Thread("test_thread", Thread::Priority::NORMAL); handler_ = new Handler(thread_); @@ -84,8 +84,8 @@ class WakelockManagerTest : public Test { void SyncHandler() { std::promise promise; auto future = promise.get_future(); - handler_->Post( - bluetooth::common::BindOnce(&std::promise::set_value, bluetooth::common::Unretained(&promise))); + handler_->Post(bluetooth::common::BindOnce(&std::promise::set_value, + bluetooth::common::Unretained(&promise))); auto future_status = future.wait_for(std::chrono::seconds(1)); ASSERT_EQ(future_status, std::future_status::ready); } diff --git a/system/gd/os/logging/log_adapter.h b/system/gd/os/logging/log_adapter.h index 4a33a0b0ac3..63edbebca47 100644 --- a/system/gd/os/logging/log_adapter.h +++ b/system/gd/os/logging/log_adapter.h @@ -38,13 +38,9 @@ std::string ToLoggableStr(const Loggable& loggable) { #define ADDRESS_TO_LOGGABLE_STR(addr) ToLoggableStr(addr) #define ADDRESS_TO_LOGGABLE_CSTR(addr) ADDRESS_TO_LOGGABLE_STR(addr).c_str() -#define PRIVATE_CELL(number) \ - (number \ - .replace( \ - 0, \ - (number.size() > 2) ? number.size() - 2 : 0, \ - (number.size() > 2) ? number.size() - 2 : 0, \ - '*') \ - .c_str()) +#define PRIVATE_CELL(number) \ + (number.replace(0, (number.size() > 2) ? number.size() - 2 : 0, \ + (number.size() > 2) ? number.size() - 2 : 0, '*') \ + .c_str()) #define PRIVATE_NAME(name) (name) diff --git a/system/gd/os/logging/log_redaction.cc b/system/gd/os/logging/log_redaction.cc index 50f32eee8b8..9997cfc5d3d 100644 --- a/system/gd/os/logging/log_redaction.cc +++ b/system/gd/os/logging/log_redaction.cc @@ -25,9 +25,7 @@ namespace os { using bluetooth::common::init_flags::redact_log_is_enabled; -bool should_log_be_redacted() { - return redact_log_is_enabled(); -} +bool should_log_be_redacted() { return redact_log_is_enabled(); } } // namespace os } // namespace bluetooth diff --git a/system/gd/os/metrics.h b/system/gd/os/metrics.h index 2b6883d4fed..df110cf4ed5 100644 --- a/system/gd/os/metrics.h +++ b/system/gd/os/metrics.h @@ -49,16 +49,11 @@ static const uint32_t kUnknownConnectionHandle = 0xFFFF; * @param cmd_status Command status associated with this event, if any * @param reason_code Reason code associated with this event, if any */ -void LogMetricLinkLayerConnectionEvent( - const hci::Address* address, - uint32_t connection_handle, - android::bluetooth::DirectionEnum direction, - uint16_t link_type, - uint32_t hci_cmd, - uint16_t hci_event, - uint16_t hci_ble_event, - uint16_t cmd_status, - uint16_t reason_code); +void LogMetricLinkLayerConnectionEvent(const hci::Address* address, uint32_t connection_handle, + android::bluetooth::DirectionEnum direction, + uint16_t link_type, uint32_t hci_cmd, uint16_t hci_event, + uint16_t hci_ble_event, uint16_t cmd_status, + uint16_t reason_code); /** * Logs when Bluetooth controller failed to reply with command status within @@ -82,8 +77,8 @@ void LogMetricHciTimeoutEvent(uint32_t hci_cmd); * event * @param subversion subversion code from read remote version complete event */ -void LogMetricRemoteVersionInfo( - uint16_t handle, uint8_t status, uint8_t version, uint16_t manufacturer_name, uint16_t subversion); +void LogMetricRemoteVersionInfo(uint16_t handle, uint8_t status, uint8_t version, + uint16_t manufacturer_name, uint16_t subversion); /** * Log A2DP audio buffer underrun event @@ -93,8 +88,8 @@ void LogMetricRemoteVersionInfo( * @param num_missing_pcm_bytes number of PCM bytes that cannot be read from * the source */ -void LogMetricA2dpAudioUnderrunEvent( - const hci::Address& address, uint64_t encoding_interval_millis, int num_missing_pcm_bytes); +void LogMetricA2dpAudioUnderrunEvent(const hci::Address& address, uint64_t encoding_interval_millis, + int num_missing_pcm_bytes); /** * Log A2DP audio buffer overrun event @@ -107,12 +102,9 @@ void LogMetricA2dpAudioUnderrunEvent( * @param num_dropped_encoded_bytes number of encoded bytes dropped from Tx * queue */ -void LogMetricA2dpAudioOverrunEvent( - const hci::Address& address, - uint64_t encoding_interval_millis, - int num_dropped_buffers, - int num_dropped_encoded_frames, - int num_dropped_encoded_bytes); +void LogMetricA2dpAudioOverrunEvent(const hci::Address& address, uint64_t encoding_interval_millis, + int num_dropped_buffers, int num_dropped_encoded_frames, + int num_dropped_encoded_bytes); /** * Log A2DP audio playback state changed event @@ -121,8 +113,8 @@ void LogMetricA2dpAudioOverrunEvent( * @param playback_state A2DP audio playback state, on/off * @param audio_coding_mode A2DP audio codec encoding mode, hw/sw */ -void LogMetricA2dpPlaybackEvent( - const hci::Address& address, int playback_state, int audio_coding_mode); +void LogMetricA2dpPlaybackEvent(const hci::Address& address, int playback_state, + int audio_coding_mode); /** * Log A2DP audio session metrics @@ -143,19 +135,12 @@ void LogMetricA2dpPlaybackEvent( * @param codec_index A2DP codec index (SBC=0, AAC=1, etc...) * @param is_a2dp_offload if A2DP is offload */ -void LogMetricA2dpSessionMetricsEvent( - const hci::Address& address, - int64_t audio_duration_ms, - int media_timer_min_ms, - int media_timer_max_ms, - int media_timer_avg_ms, - int total_scheduling_count, - int buffer_overruns_max_count, - int buffer_overruns_total, - float buffer_underruns_average, - int buffer_underruns_count, - int64_t codec_index, - bool is_a2dp_offload); +void LogMetricA2dpSessionMetricsEvent(const hci::Address& address, int64_t audio_duration_ms, + int media_timer_min_ms, int media_timer_max_ms, + int media_timer_avg_ms, int total_scheduling_count, + int buffer_overruns_max_count, int buffer_overruns_total, + float buffer_underruns_average, int buffer_underruns_count, + int64_t codec_index, bool is_a2dp_offload); /** * Log HFP audio capture packet loss statistics @@ -165,11 +150,8 @@ void LogMetricA2dpSessionMetricsEvent( * @param packet_loss_ratio ratio of packet loss frames * @param codec_id codec ID of the packet (mSBC=2, LC3=3) */ -void LogMetricHfpPacketLossStats( - const hci::Address& address, - int num_decoded_frames, - double packet_loss_ratio, - uint16_t codec_id); +void LogMetricHfpPacketLossStats(const hci::Address& address, int num_decoded_frames, + double packet_loss_ratio, uint16_t codec_id); /** * Log Mmc transcode round-trip time statistics @@ -179,8 +161,8 @@ void LogMetricHfpPacketLossStats( * @param num_requests the number of transcoding requests in the session * @param codec_type codec type used in this session */ -void LogMetricMmcTranscodeRttStats( - int maximum_rtt, double mean_rtt, int num_requests, int codec_type); +void LogMetricMmcTranscodeRttStats(int maximum_rtt, double mean_rtt, int num_requests, + int codec_type); /** * Log read RSSI result @@ -191,7 +173,8 @@ void LogMetricMmcTranscodeRttStats( * @param cmd_status command status from read RSSI command * @param rssi rssi value in dBm */ -void LogMetricReadRssiResult(const hci::Address& address, uint16_t handle, uint32_t cmd_status, int8_t rssi); +void LogMetricReadRssiResult(const hci::Address& address, uint16_t handle, uint32_t cmd_status, + int8_t rssi); /** * Log failed contact counter report @@ -203,8 +186,8 @@ void LogMetricReadRssiResult(const hci::Address& address, uint16_t handle, uint3 * @param failed_contact_counter Number of consecutive failed contacts for a * connection corresponding to the Handle */ -void LogMetricReadFailedContactCounterResult( - const hci::Address& address, uint16_t handle, uint32_t cmd_status, int32_t failed_contact_counter); +void LogMetricReadFailedContactCounterResult(const hci::Address& address, uint16_t handle, + uint32_t cmd_status, int32_t failed_contact_counter); /** * Log transmit power level for a particular device after read @@ -216,8 +199,8 @@ void LogMetricReadFailedContactCounterResult( * @param transmit_power_level transmit power level for connection to this * device */ -void LogMetricReadTxPowerLevelResult( - const hci::Address& address, uint16_t handle, uint32_t cmd_status, int32_t transmit_power_level); +void LogMetricReadTxPowerLevelResult(const hci::Address& address, uint16_t handle, + uint32_t cmd_status, int32_t transmit_power_level); /** * Logs when there is an event related to Bluetooth Security Manager Protocol @@ -227,11 +210,9 @@ void LogMetricReadTxPowerLevelResult( * @param direction direction of this SMP command * @param smp_fail_reason SMP pairing failure reason code from SMP spec */ -void LogMetricSmpPairingEvent( - const hci::Address& address, - uint16_t smp_cmd, - android::bluetooth::DirectionEnum direction, - uint16_t smp_fail_reason); +void LogMetricSmpPairingEvent(const hci::Address& address, uint16_t smp_cmd, + android::bluetooth::DirectionEnum direction, + uint16_t smp_fail_reason); /** * Logs there is an event related Bluetooth classic pairing @@ -245,14 +226,9 @@ void LogMetricSmpPairingEvent( * @param reason_code Reason code associated with this event * @param event_value A status value related to this specific event */ -void LogMetricClassicPairingEvent( - const hci::Address& address, - uint16_t handle, - uint32_t hci_cmd, - uint16_t hci_event, - uint16_t cmd_status, - uint16_t reason_code, - int64_t event_value); +void LogMetricClassicPairingEvent(const hci::Address& address, uint16_t handle, uint32_t hci_cmd, + uint16_t hci_event, uint16_t cmd_status, uint16_t reason_code, + int64_t event_value); /** * Logs when certain Bluetooth SDP attributes are discovered @@ -264,12 +240,9 @@ void LogMetricClassicPairingEvent( * @param attribute_value pointer to the attribute data, must be larger than * attribute_size */ -void LogMetricSdpAttribute( - const hci::Address& address, - uint16_t protocol_uuid, - uint16_t attribute_id, - size_t attribute_size, - const char* attribute_value); +void LogMetricSdpAttribute(const hci::Address& address, uint16_t protocol_uuid, + uint16_t attribute_id, size_t attribute_size, + const char* attribute_value); /** * Logs when there is a change in Bluetooth socket connection state @@ -286,16 +259,10 @@ void LogMetricSdpAttribute( * @param socket_role role of this socket, server or connection * @param uid socket owner's uid */ -void LogMetricSocketConnectionState( - const hci::Address& address, - int port, - int type, - android::bluetooth::SocketConnectionstateEnum connection_state, - int64_t tx_bytes, - int64_t rx_bytes, - int uid, - int server_port, - android::bluetooth::SocketRoleEnum socket_role); +void LogMetricSocketConnectionState(const hci::Address& address, int port, int type, + android::bluetooth::SocketConnectionstateEnum connection_state, + int64_t tx_bytes, int64_t rx_bytes, int uid, int server_port, + android::bluetooth::SocketRoleEnum socket_role); /** * Logs when a Bluetooth device's manufacturer information is learnt @@ -308,15 +275,12 @@ void LogMetricSocketConnectionState( * @param hardware_version hardware version of this device * @param software_version software version of this device */ -void LogMetricManufacturerInfo( - const hci::Address& address, - android::bluetooth::AddressTypeEnum address_type, - android::bluetooth::DeviceInfoSrcEnum source_type, - const std::string& source_name, - const std::string& manufacturer, - const std::string& model, - const std::string& hardware_version, - const std::string& software_version); +void LogMetricManufacturerInfo(const hci::Address& address, + android::bluetooth::AddressTypeEnum address_type, + android::bluetooth::DeviceInfoSrcEnum source_type, + const std::string& source_name, const std::string& manufacturer, + const std::string& model, const std::string& hardware_version, + const std::string& software_version); /** * Logs when received Bluetooth HAL crash reason report. @@ -325,32 +289,27 @@ void LogMetricManufacturerInfo( * @param error_code the crash reason from bluetooth hal * @param vendor_error_code the vendor crash reason from bluetooth firmware */ -void LogMetricBluetoothHalCrashReason( - const hci::Address& address, - uint32_t error_code, - uint32_t vendor_error_code); +void LogMetricBluetoothHalCrashReason(const hci::Address& address, uint32_t error_code, + uint32_t vendor_error_code); void LogMetricBluetoothLocalSupportedFeatures(uint32_t page_num, uint64_t features); -void LogMetricBluetoothLocalVersions( - uint32_t lmp_manufacturer_name, - uint8_t lmp_version, - uint32_t lmp_subversion, - uint8_t hci_version, - uint32_t hci_revision); +void LogMetricBluetoothLocalVersions(uint32_t lmp_manufacturer_name, uint8_t lmp_version, + uint32_t lmp_subversion, uint8_t hci_version, + uint32_t hci_revision); -void LogMetricBluetoothDisconnectionReasonReported( - uint32_t reason, const hci::Address& address, uint32_t connection_handle); +void LogMetricBluetoothDisconnectionReasonReported(uint32_t reason, const hci::Address& address, + uint32_t connection_handle); -void LogMetricBluetoothRemoteSupportedFeatures( - const hci::Address& address, uint32_t page, uint64_t features, uint32_t connection_handle); +void LogMetricBluetoothRemoteSupportedFeatures(const hci::Address& address, uint32_t page, + uint64_t features, uint32_t connection_handle); void LogMetricBluetoothCodePathCounterMetrics(int32_t key, int64_t count); using android::bluetooth::le::LeAclConnectionState; using android::bluetooth::le::LeConnectionOriginType; -using android::bluetooth::le::LeConnectionType; using android::bluetooth::le::LeConnectionState; +using android::bluetooth::le::LeConnectionType; // Adding options struct LEConnectionSessionOptions { // Contains the state of the LE-ACL Connection @@ -378,11 +337,9 @@ struct LEConnectionSessionOptions { // Argument Type enum ArgumentType { GATT_IF, L2CAP_PSM, L2CAP_CID, APP_UID, ACL_STATUS_CODE }; void LogMetricBluetoothLEConnectionMetricEvent( - const hci::Address& address, - LeConnectionOriginType origin_type, - LeConnectionType connection_type, - LeConnectionState transaction_state, - std::vector>& argument_list); + const hci::Address& address, LeConnectionOriginType origin_type, + LeConnectionType connection_type, LeConnectionState transaction_state, + std::vector>& argument_list); // Upload LE Session void LogMetricBluetoothLEConnection(os::LEConnectionSessionOptions session_options); diff --git a/system/gd/os/mock_queue.h b/system/gd/os/mock_queue.h index 470068e4f18..41aa743e9c0 100644 --- a/system/gd/os/mock_queue.h +++ b/system/gd/os/mock_queue.h @@ -34,7 +34,7 @@ namespace os { template class MockIQueueEnqueue : public IQueueEnqueue { - public: +public: using EnqueueCallback = common::Callback()>; virtual void RegisterEnqueue(Handler* handler, EnqueueCallback callback) { @@ -63,7 +63,7 @@ class MockIQueueEnqueue : public IQueueEnqueue { template class MockIQueueDequeue : public IQueueDequeue { - public: +public: using DequeueCallback = common::Callback; virtual void RegisterDequeue(Handler* handler, DequeueCallback callback) { diff --git a/system/gd/os/parameter_provider.h b/system/gd/os/parameter_provider.h index da33270c29f..cdb9d3f9f16 100644 --- a/system/gd/os/parameter_provider.h +++ b/system/gd/os/parameter_provider.h @@ -24,7 +24,7 @@ namespace bluetooth { namespace os { class ParameterProvider { - public: +public: // Return the path to config file for storage module static std::string ConfigFilePath(); diff --git a/system/gd/os/queue.h b/system/gd/os/queue.h index 23c6cba3084..3063c35a649 100644 --- a/system/gd/os/queue.h +++ b/system/gd/os/queue.h @@ -35,7 +35,7 @@ namespace os { // See documentation for |Queue| template class IQueueEnqueue { - public: +public: using EnqueueCallback = common::Callback()>; virtual ~IQueueEnqueue() = default; virtual void RegisterEnqueue(Handler* handler, EnqueueCallback callback) = 0; @@ -45,7 +45,7 @@ class IQueueEnqueue { // See documentation for |Queue| template class IQueueDequeue { - public: +public: using DequeueCallback = common::Callback; virtual ~IQueueDequeue() = default; virtual void RegisterDequeue(Handler* handler, DequeueCallback callback) = 0; @@ -55,31 +55,36 @@ class IQueueDequeue { template class Queue : public IQueueEnqueue, public IQueueDequeue { - public: - // A function moving data from enqueue end buffer to queue, it will be continually be invoked until queue - // is full. Enqueue end should make sure buffer isn't empty and UnregisterEnqueue when buffer become empty. +public: + // A function moving data from enqueue end buffer to queue, it will be continually be invoked + // until queue is full. Enqueue end should make sure buffer isn't empty and UnregisterEnqueue when + // buffer become empty. using EnqueueCallback = common::Callback()>; - // A function moving data form queue to dequeue end buffer, it will be continually be invoked until queue - // is empty. TryDequeue should be use in this function to get data from queue. + // A function moving data form queue to dequeue end buffer, it will be continually be invoked + // until queue is empty. TryDequeue should be use in this function to get data from queue. using DequeueCallback = common::Callback; // Create a queue with |capacity| is the maximum number of messages a queue can contain explicit Queue(size_t capacity); ~Queue(); - // Register |callback| that will be called on |handler| when the queue is able to enqueue one piece of data. - // This will cause a crash if handler or callback has already been registered before. + // Register |callback| that will be called on |handler| when the queue is able to enqueue one + // piece of data. This will cause a crash if handler or callback has already been registered + // before. void RegisterEnqueue(Handler* handler, EnqueueCallback callback) override; - // Unregister current EnqueueCallback from this queue, this will cause a crash if not registered yet. + // Unregister current EnqueueCallback from this queue, this will cause a crash if not registered + // yet. void UnregisterEnqueue() override; - // Register |callback| that will be called on |handler| when the queue has at least one piece of data ready - // for dequeue. This will cause a crash if handler or callback has already been registered before. + // Register |callback| that will be called on |handler| when the queue has at least one piece of + // data ready for dequeue. This will cause a crash if handler or callback has already been + // registered before. void RegisterDequeue(Handler* handler, DequeueCallback callback) override; - // Unregister current DequeueCallback from this queue, this will cause a crash if not registered yet. + // Unregister current DequeueCallback from this queue, this will cause a crash if not registered + // yet. void UnregisterDequeue() override; // Try to dequeue an item from this queue. Return nullptr when there is nothing in the queue. std::unique_ptr TryDequeue() override; - private: +private: void EnqueueCallbackInternal(EnqueueCallback callback); // An internal queue that holds at most |capacity| pieces of data std::queue> queue_; @@ -87,7 +92,7 @@ class Queue : public IQueueEnqueue, public IQueueDequeue { std::mutex mutex_; class QueueEndpoint { - public: + public: explicit QueueEndpoint(unsigned int initial_value) : reactive_semaphore_(initial_value), handler_(nullptr), reactable_(nullptr) {} ReactiveSemaphore reactive_semaphore_; @@ -101,7 +106,7 @@ class Queue : public IQueueEnqueue, public IQueueDequeue { template class EnqueueBuffer { - public: +public: EnqueueBuffer(IQueueEnqueue* queue) : queue_(queue) {} ~EnqueueBuffer() { @@ -114,7 +119,8 @@ class EnqueueBuffer { std::lock_guard lock(mutex_); buffer_.push(std::move(t)); if (!enqueue_registered_.exchange(true)) { - queue_->RegisterEnqueue(handler, common::Bind(&EnqueueBuffer::enqueue_callback, common::Unretained(this))); + queue_->RegisterEnqueue( + handler, common::Bind(&EnqueueBuffer::enqueue_callback, common::Unretained(this))); } } @@ -127,9 +133,7 @@ class EnqueueBuffer { } } - auto Size() const { - return buffer_.size(); - } + auto Size() const { return buffer_.size(); } void NotifyOnEmpty(common::OnceClosure callback) { std::lock_guard lock(mutex_); @@ -137,7 +141,7 @@ class EnqueueBuffer { callback_on_empty_ = std::move(callback); } - private: +private: std::unique_ptr enqueue_callback() { std::lock_guard lock(mutex_); std::unique_ptr enqueued_t = std::move(buffer_.front()); @@ -165,7 +169,7 @@ template Queue::~Queue() { log::assert_that(enqueue_.handler_ == nullptr, "Enqueue is not unregistered"); log::assert_that(dequeue_.handler_ == nullptr, "Dequeue is not unregistered"); -}; +} template void Queue::RegisterEnqueue(Handler* handler, EnqueueCallback callback) { @@ -174,9 +178,10 @@ void Queue::RegisterEnqueue(Handler* handler, EnqueueCallback callback) { log::assert_that(enqueue_.reactable_ == nullptr, "assert failed: enqueue_.reactable_ == nullptr"); enqueue_.handler_ = handler; enqueue_.reactable_ = enqueue_.handler_->thread_->GetReactor()->Register( - enqueue_.reactive_semaphore_.GetFd(), - base::Bind(&Queue::EnqueueCallbackInternal, base::Unretained(this), std::move(callback)), - base::Closure()); + enqueue_.reactive_semaphore_.GetFd(), + base::Bind(&Queue::EnqueueCallbackInternal, base::Unretained(this), + std::move(callback)), + base::Closure()); } template @@ -186,8 +191,8 @@ void Queue::UnregisterEnqueue() { bool wait_for_unregister = false; { std::lock_guard lock(mutex_); - log::assert_that( - enqueue_.reactable_ != nullptr, "assert failed: enqueue_.reactable_ != nullptr"); + log::assert_that(enqueue_.reactable_ != nullptr, + "assert failed: enqueue_.reactable_ != nullptr"); reactor = enqueue_.handler_->thread_->GetReactor(); wait_for_unregister = (!enqueue_.handler_->thread_->IsSameThread()); to_unregister = enqueue_.reactable_; @@ -207,7 +212,7 @@ void Queue::RegisterDequeue(Handler* handler, DequeueCallback callback) { log::assert_that(dequeue_.reactable_ == nullptr, "assert failed: dequeue_.reactable_ == nullptr"); dequeue_.handler_ = handler; dequeue_.reactable_ = dequeue_.handler_->thread_->GetReactor()->Register( - dequeue_.reactive_semaphore_.GetFd(), callback, base::Closure()); + dequeue_.reactive_semaphore_.GetFd(), callback, base::Closure()); } template @@ -217,8 +222,8 @@ void Queue::UnregisterDequeue() { bool wait_for_unregister = false; { std::lock_guard lock(mutex_); - log::assert_that( - dequeue_.reactable_ != nullptr, "assert failed: dequeue_.reactable_ != nullptr"); + log::assert_that(dequeue_.reactable_ != nullptr, + "assert failed: dequeue_.reactable_ != nullptr"); reactor = dequeue_.handler_->thread_->GetReactor(); wait_for_unregister = (!dequeue_.handler_->thread_->IsSameThread()); to_unregister = dequeue_.reactable_; diff --git a/system/gd/os/queue_benchmark.cc b/system/gd/os/queue_benchmark.cc index 2066aeaa7af..b4c442e7dd4 100644 --- a/system/gd/os/queue_benchmark.cc +++ b/system/gd/os/queue_benchmark.cc @@ -27,7 +27,7 @@ namespace bluetooth { namespace os { class BM_QueuePerformance : public ::benchmark::Fixture { - protected: +protected: void SetUp(State& st) override { ::benchmark::Fixture::SetUp(st); enqueue_thread_ = new Thread("enqueue_thread", Thread::Priority::NORMAL); @@ -55,12 +55,14 @@ class BM_QueuePerformance : public ::benchmark::Fixture { }; class TestEnqueueEnd { - public: - explicit TestEnqueueEnd(int64_t count, Queue* queue, Handler* handler, std::promise* promise) +public: + explicit TestEnqueueEnd(int64_t count, Queue* queue, Handler* handler, + std::promise* promise) : count_(count), handler_(handler), queue_(queue), promise_(promise) {} void RegisterEnqueue() { - handler_->Post(common::BindOnce(&TestEnqueueEnd::handle_register_enqueue, common::Unretained(this))); + handler_->Post( + common::BindOnce(&TestEnqueueEnd::handle_register_enqueue, common::Unretained(this))); } void push(std::string data) { @@ -93,24 +95,27 @@ class TestEnqueueEnd { std::queue buffer_; int64_t count_; - private: +private: Handler* handler_; Queue* queue_; std::promise* promise_; std::mutex mutex_; void handle_register_enqueue() { - queue_->RegisterEnqueue(handler_, common::Bind(&TestEnqueueEnd::EnqueueCallbackForTest, common::Unretained(this))); + queue_->RegisterEnqueue(handler_, common::Bind(&TestEnqueueEnd::EnqueueCallbackForTest, + common::Unretained(this))); } }; class TestDequeueEnd { - public: - explicit TestDequeueEnd(int64_t count, Queue* queue, Handler* handler, std::promise* promise) +public: + explicit TestDequeueEnd(int64_t count, Queue* queue, Handler* handler, + std::promise* promise) : count_(count), handler_(handler), queue_(queue), promise_(promise) {} void RegisterDequeue() { - handler_->Post(common::BindOnce(&TestDequeueEnd::handle_register_dequeue, common::Unretained(this))); + handler_->Post( + common::BindOnce(&TestDequeueEnd::handle_register_dequeue, common::Unretained(this))); } void DequeueCallbackForTest() { @@ -127,13 +132,14 @@ class TestDequeueEnd { std::queue buffer_; int64_t count_; - private: +private: Handler* handler_; Queue* queue_; std::promise* promise_; void handle_register_dequeue() { - queue_->RegisterDequeue(handler_, common::Bind(&TestDequeueEnd::DequeueCallbackForTest, common::Unretained(this))); + queue_->RegisterDequeue(handler_, common::Bind(&TestDequeueEnd::DequeueCallbackForTest, + common::Unretained(this))); } }; @@ -159,16 +165,16 @@ BENCHMARK_DEFINE_F(BM_QueuePerformance, send_packet_vary_by_packet_num)(State& s } state.SetBytesProcessed(static_cast(state.iterations()) * state.range(0)); -}; +} BENCHMARK_REGISTER_F(BM_QueuePerformance, send_packet_vary_by_packet_num) - ->Arg(10) - ->Arg(100) - ->Arg(1000) - ->Arg(10000) - ->Arg(100000) - ->Iterations(100) - ->UseRealTime(); + ->Arg(10) + ->Arg(100) + ->Arg(1000) + ->Arg(10000) + ->Arg(100000) + ->Iterations(100) + ->UseRealTime(); BENCHMARK_DEFINE_F(BM_QueuePerformance, send_10000_packet_vary_by_packet_size)(State& state) { for (auto _ : state) { @@ -193,14 +199,14 @@ BENCHMARK_DEFINE_F(BM_QueuePerformance, send_10000_packet_vary_by_packet_size)(S } state.SetBytesProcessed(static_cast(state.iterations()) * state.range(0) * 10000); -}; +} BENCHMARK_REGISTER_F(BM_QueuePerformance, send_10000_packet_vary_by_packet_size) - ->Arg(10) - ->Arg(100) - ->Arg(1000) - ->Iterations(100) - ->UseRealTime(); + ->Arg(10) + ->Arg(100) + ->Arg(1000) + ->Iterations(100) + ->UseRealTime(); } // namespace os } // namespace bluetooth diff --git a/system/gd/os/rand.h b/system/gd/os/rand.h index 35e297374fa..edda493b31a 100644 --- a/system/gd/os/rand.h +++ b/system/gd/os/rand.h @@ -30,17 +30,15 @@ namespace os { template std::array GenerateRandom() { std::array ret; - log::assert_that( - RAND_bytes(ret.data(), ret.size()) == 1, - "assert failed: RAND_bytes(ret.data(), ret.size()) == 1"); + log::assert_that(RAND_bytes(ret.data(), ret.size()) == 1, + "assert failed: RAND_bytes(ret.data(), ret.size()) == 1"); return ret; } inline uint32_t GenerateRandom() { uint32_t ret{}; - log::assert_that( - RAND_bytes((uint8_t*)(&ret), sizeof(uint32_t)) == 1, - "assert failed: RAND_bytes((uint8_t*)(&ret), sizeof(uint32_t)) == 1"); + log::assert_that(RAND_bytes((uint8_t*)(&ret), sizeof(uint32_t)) == 1, + "assert failed: RAND_bytes((uint8_t*)(&ret), sizeof(uint32_t)) == 1"); return ret; } diff --git a/system/gd/os/reactor.h b/system/gd/os/reactor.h index 23febf93fbd..ef286fbb608 100644 --- a/system/gd/os/reactor.h +++ b/system/gd/os/reactor.h @@ -33,11 +33,11 @@ namespace bluetooth { namespace os { // A simple implementation of reactor-style looper. -// When a reactor is running, the main loop is polling and blocked until at least one registered reactable is ready to -// read or write. It will invoke on_read_ready() or on_write_ready(), which is registered with the reactor. Then, it -// blocks again until ready event. +// When a reactor is running, the main loop is polling and blocked until at least one registered +// reactable is ready to read or write. It will invoke on_read_ready() or on_write_ready(), which is +// registered with the reactor. Then, it blocks again until ready event. class Reactor { - public: +public: // An object used for Unregister() and ModifyRegistration() class Reactable; @@ -53,12 +53,14 @@ class Reactor { // Start the reactor. The current thread will be blocked until Stop() is invoked and handled. void Run(); - // Stop the reactor. Must be invoked from a different thread. Note: all registered reactables will not be unregistered - // by Stop(). If the reactor is not running, it will be stopped once it's started. + // Stop the reactor. Must be invoked from a different thread. Note: all registered reactables will + // not be unregistered by Stop(). If the reactor is not running, it will be stopped once it's + // started. void Stop(); - // Register a reactable fd to this reactor. Returns a pointer to a Reactable. Caller must use this object to - // unregister or modify registration. Ownership of the memory space is NOT transferred to user. + // Register a reactable fd to this reactor. Returns a pointer to a Reactable. Caller must use this + // object to unregister or modify registration. Ownership of the memory space is NOT transferred + // to user. Reactable* Register(int fd, common::Closure on_read_ready, common::Closure on_write_ready); // Unregister a reactable from this reactor @@ -80,7 +82,7 @@ class Reactor { void ModifyRegistration(Reactable* reactable, ReactOn react_on); class Event { - public: + public: Event(); ~Event(); bool Read(); @@ -89,14 +91,14 @@ class Reactor { void Close(); void Notify(); - private: + private: Event(const Event& handler) = default; struct impl; impl* pimpl_{nullptr}; }; std::unique_ptr NewEvent() const; - private: +private: mutable std::mutex mutex_; int epoll_fd_; int control_fd_; diff --git a/system/gd/os/repeating_alarm.h b/system/gd/os/repeating_alarm.h index b261b5e7fd5..d38e5374d05 100644 --- a/system/gd/os/repeating_alarm.h +++ b/system/gd/os/repeating_alarm.h @@ -29,10 +29,10 @@ namespace bluetooth { namespace os { // A repeating alarm for reactor-based thread, implemented by Linux timerfd. -// When it's constructed, it will register a reactable on the specified thread; when it's destroyed, it will unregister -// itself from the thread. +// When it's constructed, it will register a reactable on the specified thread; when it's destroyed, +// it will unregister itself from the thread. class RepeatingAlarm { - public: +public: // Create and register a repeating alarm on a given handler explicit RepeatingAlarm(Handler* handler); @@ -48,7 +48,7 @@ class RepeatingAlarm { // Cancel the alarm. No-op if it's not armed. void Cancel(); - private: +private: common::Closure task_; Handler* handler_; int fd_ = 0; diff --git a/system/gd/os/system_properties.h b/system/gd/os/system_properties.h index cbad2dc9568..db317084803 100644 --- a/system/gd/os/system_properties.h +++ b/system/gd/os/system_properties.h @@ -27,29 +27,29 @@ namespace os { /* System Property to indicate if the dual mode audio feature is enabled */ static const std::string kIsDualModeAudioEnabledProperty = - "persist.bluetooth.enable_dual_mode_audio"; + "persist.bluetooth.enable_dual_mode_audio"; -// Get |property| keyed system property from supported platform, return std::nullopt if the property does not exist -// or if the platform does not support system property +// Get |property| keyed system property from supported platform, return std::nullopt if the property +// does not exist or if the platform does not support system property std::optional GetSystemProperty(const std::string& property); -// Get |property| keyed system property as uint32_t from supported platform, return |default_value| if the property -// does not exist or if the platform does not support system property +// Get |property| keyed system property as uint32_t from supported platform, return |default_value| +// if the property does not exist or if the platform does not support system property uint32_t GetSystemPropertyUint32(const std::string& property, uint32_t default_value); // Get |property| keyed system property as uint32_t from supported platform, return |default_value| // if the property does not exist or if the platform does not support system property if property is // found it will call stoul with |base| -uint32_t GetSystemPropertyUint32Base( - const std::string& property, uint32_t default_value, int base = 0); +uint32_t GetSystemPropertyUint32Base(const std::string& property, uint32_t default_value, + int base = 0); // Get |property| keyed property as bool from supported platform, return // |default_value| if the property does not exist or if the platform // does not support system property bool GetSystemPropertyBool(const std::string& property, bool default_value); -// Set |property| keyed system property to |value|, return true if the set was successful and false if the set failed -// Replace existing value if property already exists +// Set |property| keyed system property to |value|, return true if the set was successful and false +// if the set failed Replace existing value if property already exists bool SetSystemProperty(const std::string& property, const std::string& value); // Clear system properties for host only return true on success @@ -58,8 +58,8 @@ bool ClearSystemPropertiesForHost(); // Check if the vendor image is using root canal simulated Bluetooth stack bool IsRootCanalEnabled(); -// Get Android Vendor Image release version in numeric value (e.g. Android R is 11), return 0 if not on Android or -// version not available +// Get Android Vendor Image release version in numeric value (e.g. Android R is 11), return 0 if not +// on Android or version not available int GetAndroidVendorReleaseVersion(); } // namespace os diff --git a/system/gd/os/system_properties_common.cc b/system/gd/os/system_properties_common.cc index f59560c8f25..9dfed10da6e 100644 --- a/system/gd/os/system_properties_common.cc +++ b/system/gd/os/system_properties_common.cc @@ -26,8 +26,8 @@ uint32_t GetSystemPropertyUint32(const std::string& property, uint32_t default_v return GetSystemPropertyUint32Base(property, default_value, 10); } -uint32_t GetSystemPropertyUint32Base( - const std::string& property, uint32_t default_value, int base) { +uint32_t GetSystemPropertyUint32Base(const std::string& property, uint32_t default_value, + int base) { std::optional result = GetSystemProperty(property); if (result.has_value()) { return static_cast(std::stoul(*result, nullptr, base)); diff --git a/system/gd/os/thread.h b/system/gd/os/thread.h index 4be792d3ccb..ccab6113ccb 100644 --- a/system/gd/os/thread.h +++ b/system/gd/os/thread.h @@ -26,14 +26,14 @@ namespace bluetooth { namespace os { -// Reactor-based looper thread implementation. The thread runs immediately after it is constructed, and stops after -// Stop() is invoked. To assign task to this thread, user needs to register a reactable object to the underlying -// reactor. +// Reactor-based looper thread implementation. The thread runs immediately after it is constructed, +// and stops after Stop() is invoked. To assign task to this thread, user needs to register a +// reactable object to the underlying reactor. class Thread { - public: - // Used by thread constructor. Suggest the priority to the kernel scheduler. Use REAL_TIME if we need (soft) real-time - // scheduling guarantee for this thread; use NORMAL if no real-time guarantee is needed to save CPU time slice for - // other threads +public: + // Used by thread constructor. Suggest the priority to the kernel scheduler. Use REAL_TIME if we + // need (soft) real-time scheduling guarantee for this thread; use NORMAL if no real-time + // guarantee is needed to save CPU time slice for other threads enum class Priority { REAL_TIME, NORMAL, @@ -49,7 +49,8 @@ class Thread { // Stop and destroy this thread ~Thread(); - // Stop this thread. Must be invoked from another thread. After this thread is stopped, it cannot be started again. + // Stop this thread. Must be invoked from another thread. After this thread is stopped, it cannot + // be started again. bool Stop(); // Return true if this function is invoked from this thread @@ -64,7 +65,7 @@ class Thread { // Return the pointer of underlying reactor. The ownership is NOT transferred. Reactor* GetReactor() const; - private: +private: void run(Priority priority); mutable std::mutex mutex_; const std::string name_; diff --git a/system/gd/os/thread_benchmark.cc b/system/gd/os/thread_benchmark.cc index 7a0e1407b55..529eb8a6622 100644 --- a/system/gd/os/thread_benchmark.cc +++ b/system/gd/os/thread_benchmark.cc @@ -31,15 +31,13 @@ using ::bluetooth::os::Thread; #define NUM_MESSAGES_TO_SEND 100000 class BM_ThreadPerformance : public ::benchmark::Fixture { - protected: +protected: void SetUp(State& st) override { benchmark::Fixture::SetUp(st); counter_promise_ = std::promise(); counter_ = 0; } - void TearDown(State& st) override { - benchmark::Fixture::TearDown(st); - } + void TearDown(State& st) override { benchmark::Fixture::TearDown(st); } void callback_batch() { counter_++; if (counter_ >= num_messages_to_send_) { @@ -47,9 +45,7 @@ class BM_ThreadPerformance : public ::benchmark::Fixture { } } - void callback() { - counter_promise_.set_value(); - } + void callback() { counter_promise_.set_value(); } int64_t num_messages_to_send_; int64_t counter_; @@ -57,7 +53,7 @@ class BM_ThreadPerformance : public ::benchmark::Fixture { }; class BM_ReactorThread : public BM_ThreadPerformance { - protected: +protected: void SetUp(State& st) override { BM_ThreadPerformance::SetUp(st); thread_ = std::make_unique("BM_ReactorThread thread", Thread::Priority::NORMAL); @@ -80,20 +76,20 @@ BENCHMARK_DEFINE_F(BM_ReactorThread, batch_enque_dequeue)(State& state) { counter_promise_ = std::promise(); std::future counter_future = counter_promise_.get_future(); for (int i = 0; i < num_messages_to_send_; i++) { - handler_->Post(BindOnce( - &BM_ReactorThread_batch_enque_dequeue_Benchmark::callback_batch, bluetooth::common::Unretained(this))); + handler_->Post(BindOnce(&BM_ReactorThread_batch_enque_dequeue_Benchmark::callback_batch, + bluetooth::common::Unretained(this))); } counter_future.wait(); } -}; +} BENCHMARK_REGISTER_F(BM_ReactorThread, batch_enque_dequeue) - ->Arg(10) - ->Arg(1000) - ->Arg(10000) - ->Arg(100000) - ->Iterations(1) - ->UseRealTime(); + ->Arg(10) + ->Arg(1000) + ->Arg(10000) + ->Arg(100000) + ->Iterations(1) + ->UseRealTime(); BENCHMARK_DEFINE_F(BM_ReactorThread, sequential_execution)(State& state) { for (auto _ : state) { @@ -101,17 +97,17 @@ BENCHMARK_DEFINE_F(BM_ReactorThread, sequential_execution)(State& state) { for (int i = 0; i < num_messages_to_send_; i++) { counter_promise_ = std::promise(); std::future counter_future = counter_promise_.get_future(); - handler_->Post( - BindOnce(&BM_ReactorThread_sequential_execution_Benchmark::callback, bluetooth::common::Unretained(this))); + handler_->Post(BindOnce(&BM_ReactorThread_sequential_execution_Benchmark::callback, + bluetooth::common::Unretained(this))); counter_future.wait(); } } -}; +} BENCHMARK_REGISTER_F(BM_ReactorThread, sequential_execution) - ->Arg(10) - ->Arg(1000) - ->Arg(10000) - ->Arg(100000) - ->Iterations(1) - ->UseRealTime(); + ->Arg(10) + ->Arg(1000) + ->Arg(10000) + ->Arg(100000) + ->Iterations(1) + ->UseRealTime(); diff --git a/system/gd/os/wakelock_manager.h b/system/gd/os/wakelock_manager.h index 77645c3a71d..7f598955026 100644 --- a/system/gd/os/wakelock_manager.h +++ b/system/gd/os/wakelock_manager.h @@ -18,12 +18,12 @@ #pragma once +#include + #include #include #include -#include - #include "handler.h" #include "wakelock_manager_generated.h" @@ -31,7 +31,7 @@ namespace bluetooth { namespace os { class WakelockManager { - public: +public: static const std::string kBtWakelockId; static WakelockManager& Get() { @@ -39,10 +39,10 @@ class WakelockManager { return instance; } - // The set of functions required by GD to grab wake locks. A caller with a custom wakelock implementation should - // implement this class and passed into the stack through SetCallouts() + // The set of functions required by GD to grab wake locks. A caller with a custom wakelock + // implementation should implement this class and passed into the stack through SetCallouts() class OsCallouts { - public: + public: virtual ~OsCallouts() = default; virtual void AcquireCallout(const std::string& lock_name) = 0; virtual void ReleaseCallout(const std::string& lock_name) = 0; @@ -51,9 +51,10 @@ class WakelockManager { // Set the Bluetooth OS callouts to |callouts|. // // This function should be called when native kernel wakelock are not used directly. - // If this function is not called, or |callouts| is nullptr, then native kernel wakelock will be used. - // When |callouts| are used, the callbacks are going to be invoked asynchronously to avoid being blocked by upper - // layer delays. Therefore, a handler is needed and the callout result will be ignored. + // If this function is not called, or |callouts| is nullptr, then native kernel wakelock will be + // used. When |callouts| are used, the callbacks are going to be invoked asynchronously to avoid + // being blocked by upper layer delays. Therefore, a handler is needed and the callout result will + // be ignored. // // This method must be called before calling Acquire() or Release() void SetOsCallouts(OsCallouts* callouts, Handler* handler); @@ -73,11 +74,12 @@ class WakelockManager { void CleanUp(); // Dump wakelock-related debug info to a flat buffer defined in wakelock_manager.fbs - flatbuffers::Offset GetDumpsysData(flatbuffers::FlatBufferBuilder* fb_builder); + flatbuffers::Offset GetDumpsysData( + flatbuffers::FlatBufferBuilder* fb_builder); ~WakelockManager(); - private: +private: WakelockManager(); std::recursive_mutex mutex_; diff --git a/system/gd/packet/base_packet_builder.h b/system/gd/packet/base_packet_builder.h index cf24dc1db5e..766e896f9dc 100644 --- a/system/gd/packet/base_packet_builder.h +++ b/system/gd/packet/base_packet_builder.h @@ -30,7 +30,7 @@ namespace packet { // A little-endian PacketBuilder can contain a big-endian PacketBuilder, // so BasePacketBuilder provides a common base class. class BasePacketBuilder { - public: +public: virtual ~BasePacketBuilder() = default; virtual size_t size() const = 0; @@ -38,17 +38,13 @@ class BasePacketBuilder { // Write to the vector with the given iterator. virtual void Serialize(BitInserter& it) const = 0; - void SetFlushable(bool is_flushable) { - is_flushable_ = is_flushable; - } - bool IsFlushable() const { - return is_flushable_; - } + void SetFlushable(bool is_flushable) { is_flushable_ = is_flushable; } + bool IsFlushable() const { return is_flushable_; } - protected: +protected: BasePacketBuilder() = default; - private: +private: bool is_flushable_{false}; }; diff --git a/system/gd/packet/base_struct.h b/system/gd/packet/base_struct.h index 99832292512..f0461f9ff5c 100644 --- a/system/gd/packet/base_struct.h +++ b/system/gd/packet/base_struct.h @@ -29,7 +29,7 @@ namespace packet { // A base struct to provide Serialize() and size() to be overridden. class BaseStruct { - public: +public: virtual ~BaseStruct() = default; virtual size_t size() const = 0; @@ -37,7 +37,7 @@ class BaseStruct { // Write to the vector with the given iterator. virtual void Serialize(BitInserter& it) const = 0; - protected: +protected: BaseStruct() = default; }; diff --git a/system/gd/packet/bit_inserter.cc b/system/gd/packet/bit_inserter.cc index 8f694ac3081..d02e1deecf7 100644 --- a/system/gd/packet/bit_inserter.cc +++ b/system/gd/packet/bit_inserter.cc @@ -24,13 +24,12 @@ namespace packet { BitInserter::BitInserter(std::vector& vector) : ByteInserter(vector) {} -BitInserter::~BitInserter() { - assert(num_saved_bits_ == 0); -} +BitInserter::~BitInserter() { assert(num_saved_bits_ == 0); } void BitInserter::insert_bits(uint8_t byte, size_t num_bits) { size_t total_bits = num_bits + num_saved_bits_; - uint16_t new_value = static_cast(saved_bits_) | (static_cast(byte) << num_saved_bits_); + uint16_t new_value = + static_cast(saved_bits_) | (static_cast(byte) << num_saved_bits_); if (total_bits >= 8) { ByteInserter::insert_byte(static_cast(new_value)); total_bits -= 8; @@ -41,9 +40,7 @@ void BitInserter::insert_bits(uint8_t byte, size_t num_bits) { saved_bits_ = static_cast(new_value) & mask; } -void BitInserter::insert_byte(uint8_t byte) { - insert_bits(byte, 8); -} +void BitInserter::insert_byte(uint8_t byte) { insert_bits(byte, 8); } } // namespace packet } // namespace bluetooth diff --git a/system/gd/packet/bit_inserter.h b/system/gd/packet/bit_inserter.h index 29d8408153a..f7749d62c61 100644 --- a/system/gd/packet/bit_inserter.h +++ b/system/gd/packet/bit_inserter.h @@ -27,7 +27,7 @@ namespace bluetooth { namespace packet { class BitInserter : public ByteInserter { - public: +public: explicit BitInserter(std::vector& vector); ~BitInserter(); @@ -35,7 +35,7 @@ class BitInserter : public ByteInserter { void insert_byte(uint8_t byte) override; - protected: +protected: size_t num_saved_bits_{0}; uint8_t saved_bits_{0}; }; diff --git a/system/gd/packet/bit_inserter_unittest.cc b/system/gd/packet/bit_inserter_unittest.cc index fae19f8abba..5c78db51ffd 100644 --- a/system/gd/packet/bit_inserter_unittest.cc +++ b/system/gd/packet/bit_inserter_unittest.cc @@ -17,6 +17,7 @@ #include "packet/bit_inserter.h" #include + #include #include "os/log.h" @@ -35,8 +36,8 @@ TEST(BitInserterTest, addMoreBits) { it.insert_bits(static_cast(i), i); } it.insert_bits(static_cast(0b1010), 4); - std::vector result = {0b00011101 /* 3 2 1 */, 0b00010101 /* 5 4 */, 0b11100011 /* 7 6 */, 0b10000000 /* 8 */, - 0b10100000 /* filled with 1010 */}; + std::vector result = {0b00011101 /* 3 2 1 */, 0b00010101 /* 5 4 */, 0b11100011 /* 7 6 */, + 0b10000000 /* 8 */, 0b10100000 /* filled with 1010 */}; ASSERT_EQ(result.size(), bytes.size()); for (size_t i = 0; i < bytes.size(); i++) { @@ -50,14 +51,15 @@ TEST(BitInserterTest, observerTest) { std::vector copy; uint64_t checksum = 0x0123456789abcdef; - it.RegisterObserver(ByteObserver([©](uint8_t byte) { copy.push_back(byte); }, [checksum]() { return checksum; })); + it.RegisterObserver(ByteObserver([©](uint8_t byte) { copy.push_back(byte); }, + [checksum]() { return checksum; })); for (size_t i = 0; i < 9; i++) { it.insert_bits(static_cast(i), i); } it.insert_bits(static_cast(0b1010), 4); - std::vector result = {0b00011101 /* 3 2 1 */, 0b00010101 /* 5 4 */, 0b11100011 /* 7 6 */, 0b10000000 /* 8 */, - 0b10100000 /* filled with 1010 */}; + std::vector result = {0b00011101 /* 3 2 1 */, 0b00010101 /* 5 4 */, 0b11100011 /* 7 6 */, + 0b10000000 /* 8 */, 0b10100000 /* filled with 1010 */}; ASSERT_EQ(result.size(), bytes.size()); for (size_t i = 0; i < bytes.size(); i++) { diff --git a/system/gd/packet/byte_inserter.cc b/system/gd/packet/byte_inserter.cc index 0cfcd8716b1..a821477a850 100644 --- a/system/gd/packet/byte_inserter.cc +++ b/system/gd/packet/byte_inserter.cc @@ -22,11 +22,10 @@ namespace bluetooth { namespace packet { -ByteInserter::ByteInserter(std::vector& vector) : std::back_insert_iterator>(vector) {} +ByteInserter::ByteInserter(std::vector& vector) + : std::back_insert_iterator>(vector) {} -ByteInserter::~ByteInserter() { - assert(registered_observers_.empty()); -} +ByteInserter::~ByteInserter() { assert(registered_observers_.empty()); } void ByteInserter::RegisterObserver(const ByteObserver& observer) { registered_observers_.push_back(observer); diff --git a/system/gd/packet/byte_inserter.h b/system/gd/packet/byte_inserter.h index 00787d60348..9cb71b2e367 100644 --- a/system/gd/packet/byte_inserter.h +++ b/system/gd/packet/byte_inserter.h @@ -27,7 +27,7 @@ namespace bluetooth { namespace packet { class ByteInserter : public std::back_insert_iterator> { - public: +public: explicit ByteInserter(std::vector& vector); virtual ~ByteInserter(); @@ -37,10 +37,10 @@ class ByteInserter : public std::back_insert_iterator> { ByteObserver UnregisterObserver(); - protected: +protected: void on_byte(uint8_t); - private: +private: std::vector registered_observers_; }; diff --git a/system/gd/packet/byte_observer.cc b/system/gd/packet/byte_observer.cc index 358a230b5f3..1b294b4bcc2 100644 --- a/system/gd/packet/byte_observer.cc +++ b/system/gd/packet/byte_observer.cc @@ -19,16 +19,13 @@ namespace bluetooth { namespace packet { -ByteObserver::ByteObserver(const std::function& on_byte, const std::function& get_value) +ByteObserver::ByteObserver(const std::function& on_byte, + const std::function& get_value) : on_byte_(on_byte), get_value_(get_value) {} -void ByteObserver::OnByte(uint8_t byte) { - on_byte_(byte); -} +void ByteObserver::OnByte(uint8_t byte) { on_byte_(byte); } -uint64_t ByteObserver::GetValue() { - return get_value_(); -} +uint64_t ByteObserver::GetValue() { return get_value_(); } } // namespace packet } // namespace bluetooth diff --git a/system/gd/packet/byte_observer.h b/system/gd/packet/byte_observer.h index adfcfc1bb38..f5c32f3d661 100644 --- a/system/gd/packet/byte_observer.h +++ b/system/gd/packet/byte_observer.h @@ -23,14 +23,15 @@ namespace bluetooth { namespace packet { class ByteObserver { - public: - ByteObserver(const std::function& on_byte_, const std::function& get_value_); +public: + ByteObserver(const std::function& on_byte_, + const std::function& get_value_); void OnByte(uint8_t byte); uint64_t GetValue(); - private: +private: std::function on_byte_; std::function get_value_; }; diff --git a/system/gd/packet/checksum_type_checker.h b/system/gd/packet/checksum_type_checker.h index 65c8ca7fdb6..380c4d32405 100644 --- a/system/gd/packet/checksum_type_checker.h +++ b/system/gd/packet/checksum_type_checker.h @@ -27,7 +27,7 @@ namespace parser { // C and CRET are the substituted types for T and TRET template class ChecksumTypeChecker { - public: +public: template struct InitializeChecker {}; @@ -39,10 +39,8 @@ class ChecksumTypeChecker { // If all the methods are defined, this one matches template - static int Test( - InitializeChecker*, - AddByteChecker*, - GetChecksumChecker*); + static int Test(InitializeChecker*, AddByteChecker*, + GetChecksumChecker*); // This one matches everything else template diff --git a/system/gd/packet/custom_field_fixed_size_interface.h b/system/gd/packet/custom_field_fixed_size_interface.h index c342bc92b9d..76cdcaf1381 100644 --- a/system/gd/packet/custom_field_fixed_size_interface.h +++ b/system/gd/packet/custom_field_fixed_size_interface.h @@ -23,7 +23,7 @@ namespace packet { template class CustomFieldFixedSizeInterface { - public: +public: virtual ~CustomFieldFixedSizeInterface() = default; // Get a pointer to a modifiable and readable continuous array of data virtual uint8_t* data() = 0; @@ -31,11 +31,11 @@ class CustomFieldFixedSizeInterface { // Get the length of underlying data array, data() + length() would be invalid // subclass T must have kLength variable defined static constexpr size_t length() { - static_assert( - std::is_same_v, "T::kLength must be const size_t or constexpr size_t"); + static_assert(std::is_same_v, + "T::kLength must be const size_t or constexpr size_t"); static_assert(std::is_const_v, "T::kLength must be const"); return T::kLength; - }; + } }; } // namespace packet diff --git a/system/gd/packet/custom_type_checker.h b/system/gd/packet/custom_type_checker.h index dc6c8f08ecf..ea1b59f8013 100644 --- a/system/gd/packet/custom_type_checker.h +++ b/system/gd/packet/custom_type_checker.h @@ -27,25 +27,23 @@ namespace packet { // Checks a custom type has all the necessary functions with the correct signatures. template class CustomTypeChecker { - public: +public: template struct SerializeChecker {}; template struct SizeChecker {}; - template > (*)(C* vec, Iterator it)> + template > (*)(C* vec, Iterator it)> struct ParseChecker {}; template struct ToStringChecker {}; template - static int Test( - SerializeChecker*, - SizeChecker*, - ParseChecker*, - ToStringChecker*); + static int Test(SerializeChecker*, SizeChecker*, + ParseChecker*, ToStringChecker*); template static char Test(...); diff --git a/system/gd/packet/endian_inserter.h b/system/gd/packet/endian_inserter.h index d63b17fd362..6490ed257c0 100644 --- a/system/gd/packet/endian_inserter.h +++ b/system/gd/packet/endian_inserter.h @@ -33,11 +33,11 @@ namespace packet { // The template parameter little_endian controls the generation of insert(). template class EndianInserter { - public: +public: EndianInserter() = default; virtual ~EndianInserter() = default; - protected: +protected: // Write sizeof(T) bytes using the iterator template ::value, int>::type = 0> void insert(T value, BitInserter& it) const { @@ -52,9 +52,9 @@ class EndianInserter { } // Write sizeof(FixedWidthCustomType) bytes using the iterator - template < - typename T, - typename std::enable_if, T>::value, int>::type = 0> + template , T>::value, + int>::type = 0> void insert(const T& value, BitInserter& it) const { auto* raw_bytes = value.data(); for (size_t i = 0; i < CustomFieldFixedSizeInterface::length(); i++) { @@ -75,11 +75,13 @@ class EndianInserter { if (little_endian == true) { it.insert_byte(static_cast(static_cast(value) >> (i * 8))); } else { - it.insert_byte(static_cast(static_cast(value) >> (((num_bits / 8) - i - 1) * 8))); + it.insert_byte(static_cast(static_cast(value) >> + (((num_bits / 8) - i - 1) * 8))); } } if (num_bits % 8) { - it.insert_bits(static_cast(static_cast(value) >> ((num_bits / 8) * 8)), num_bits % 8); + it.insert_bits(static_cast(static_cast(value) >> ((num_bits / 8) * 8)), + num_bits % 8); } } @@ -87,16 +89,16 @@ class EndianInserter { template , int>::type = 0> inline void insert(Enum value, BitInserter& it) const { using enum_type = typename std::underlying_type_t; - static_assert(std::is_unsigned_v, "Enum type is signed. Did you forget to specify the enum size?"); + static_assert(std::is_unsigned_v, + "Enum type is signed. Did you forget to specify the enum size?"); insert(static_cast(value), it); } // Write a vector of T using the iterator template ::value, int>::type = 0> void insert_vector(const std::vector& vec, BitInserter& it) const { - static_assert( - std::is_trivial::value, - "EndianInserter::insert requires a vector with elements of a fixed-size."); + static_assert(std::is_trivial::value, + "EndianInserter::insert requires a vector with elements of a fixed-size."); for (const auto& element : vec) { insert(element, it); } diff --git a/system/gd/packet/fragmenting_inserter.cc b/system/gd/packet/fragmenting_inserter.cc index 3950fec6066..a0230c52187 100644 --- a/system/gd/packet/fragmenting_inserter.cc +++ b/system/gd/packet/fragmenting_inserter.cc @@ -22,15 +22,18 @@ namespace bluetooth { namespace packet { -FragmentingInserter::FragmentingInserter(size_t mtu, - std::back_insert_iterator>> iterator) - : BitInserter(to_construct_bit_inserter_), mtu_(mtu), curr_packet_(std::make_unique(mtu)), +FragmentingInserter::FragmentingInserter( + size_t mtu, std::back_insert_iterator>> iterator) + : BitInserter(to_construct_bit_inserter_), + mtu_(mtu), + curr_packet_(std::make_unique(mtu)), iterator_(iterator) {} void FragmentingInserter::insert_bits(uint8_t byte, size_t num_bits) { assert(curr_packet_ != nullptr); size_t total_bits = num_bits + num_saved_bits_; - uint16_t new_value = static_cast(saved_bits_) | (static_cast(byte) << num_saved_bits_); + uint16_t new_value = + static_cast(saved_bits_) | (static_cast(byte) << num_saved_bits_); if (total_bits >= 8) { uint8_t new_byte = static_cast(new_value); on_byte(new_byte); diff --git a/system/gd/packet/fragmenting_inserter.h b/system/gd/packet/fragmenting_inserter.h index ff23a09b756..282b6cc2288 100644 --- a/system/gd/packet/fragmenting_inserter.h +++ b/system/gd/packet/fragmenting_inserter.h @@ -28,14 +28,15 @@ namespace bluetooth { namespace packet { class FragmentingInserter : public BitInserter { - public: - FragmentingInserter(size_t mtu, std::back_insert_iterator>> iterator); +public: + FragmentingInserter(size_t mtu, + std::back_insert_iterator>> iterator); void insert_bits(uint8_t byte, size_t num_bits) override; void finalize(); - protected: +protected: std::vector to_construct_bit_inserter_; size_t mtu_; std::unique_ptr curr_packet_; diff --git a/system/gd/packet/fragmenting_inserter_unittest.cc b/system/gd/packet/fragmenting_inserter_unittest.cc index ab833194fdf..dee70a615cb 100644 --- a/system/gd/packet/fragmenting_inserter_unittest.cc +++ b/system/gd/packet/fragmenting_inserter_unittest.cc @@ -17,6 +17,7 @@ #include "packet/fragmenting_inserter.h" #include + #include #include "os/log.h" @@ -28,8 +29,8 @@ namespace bluetooth { namespace packet { TEST(FragmentingInserterTest, addMoreBits) { - std::vector result = {0b00011101 /* 3 2 1 */, 0b00010101 /* 5 4 */, 0b11100011 /* 7 6 */, 0b10000000 /* 8 */, - 0b10100000 /* filled with 1010 */}; + std::vector result = {0b00011101 /* 3 2 1 */, 0b00010101 /* 5 4 */, 0b11100011 /* 7 6 */, + 0b10000000 /* 8 */, 0b10100000 /* filled with 1010 */}; std::vector> fragments; FragmentingInserter it(result.size(), std::back_insert_iterator(fragments)); @@ -54,8 +55,8 @@ TEST(FragmentingInserterTest, addMoreBits) { } TEST(FragmentingInserterTest, observerTest) { - std::vector result = {0b00011101 /* 3 2 1 */, 0b00010101 /* 5 4 */, 0b11100011 /* 7 6 */, 0b10000000 /* 8 */, - 0b10100000 /* filled with 1010 */}; + std::vector result = {0b00011101 /* 3 2 1 */, 0b00010101 /* 5 4 */, 0b11100011 /* 7 6 */, + 0b10000000 /* 8 */, 0b10100000 /* filled with 1010 */}; std::vector> fragments; FragmentingInserter it(result.size() + 1, std::back_insert_iterator(fragments)); @@ -63,7 +64,8 @@ TEST(FragmentingInserterTest, observerTest) { std::vector copy; uint64_t checksum = 0x0123456789abcdef; - it.RegisterObserver(ByteObserver([©](uint8_t byte) { copy.push_back(byte); }, [checksum]() { return checksum; })); + it.RegisterObserver(ByteObserver([©](uint8_t byte) { copy.push_back(byte); }, + [checksum]() { return checksum; })); for (size_t i = 0; i < 9; i++) { it.insert_bits(static_cast(i), i); @@ -123,16 +125,14 @@ TEST(FragmentingInserterTest, testMtuBoundaries) { constexpr size_t kPacketSize = 128; class FragmentingTest : public ::testing::TestWithParam { - public: +public: void StartUp() { counts_.reserve(kPacketSize); for (size_t i = 0; i < kPacketSize; i++) { counts_.push_back(static_cast(i)); } } - void ShutDown() { - counts_.clear(); - } + void ShutDown() { counts_.clear(); } std::vector counts_; }; diff --git a/system/gd/packet/iterator.h b/system/gd/packet/iterator.h index 52ab47f43ac..d1ea14b6870 100644 --- a/system/gd/packet/iterator.h +++ b/system/gd/packet/iterator.h @@ -44,7 +44,7 @@ struct IteratorTraits : public std::iterator class Iterator : public IteratorTraits { - public: +public: Iterator(const std::forward_list& data, size_t offset); Iterator(std::shared_ptr> data); Iterator(const Iterator& itr) = default; @@ -92,7 +92,9 @@ class Iterator : public IteratorTraits { return extracted_value; } - template , T>, int>::type = 0> + template , T>, + int>::type = 0> T extract() { T extracted_value{}; for (size_t i = 0; i < CustomFieldFixedSizeInterface::length(); i++) { @@ -103,7 +105,7 @@ class Iterator : public IteratorTraits { return extracted_value; } - private: +private: std::forward_list data_; size_t index_; size_t begin_; diff --git a/system/gd/packet/packet_builder.h b/system/gd/packet/packet_builder.h index e1b60675c9c..e86af5289da 100644 --- a/system/gd/packet/packet_builder.h +++ b/system/gd/packet/packet_builder.h @@ -34,7 +34,7 @@ namespace packet { // The template parameter little_endian controls the generation of insert(). template class PacketBuilder : public BasePacketBuilder, protected EndianInserter { - public: +public: PacketBuilder() = default; virtual ~PacketBuilder() = default; diff --git a/system/gd/packet/packet_builder_unittest.cc b/system/gd/packet/packet_builder_unittest.cc index 46647a32a8c..edb978d7de3 100644 --- a/system/gd/packet/packet_builder_unittest.cc +++ b/system/gd/packet/packet_builder_unittest.cc @@ -17,6 +17,7 @@ #include "packet/packet_builder.h" #include + #include #include @@ -27,22 +28,24 @@ using std::vector; namespace { vector count_all = { - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, - 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, + 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, + 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, }; vector count_1 = { - 0x00, - 0x01, - 0x02, + 0x00, + 0x01, + 0x02, }; vector count_2 = { - 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, + 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, }; vector count_3 = { - 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, + 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, + 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, }; } // namespace @@ -51,13 +54,14 @@ namespace packet { template class EndianBuilder : public PacketBuilder { - public: +public: EndianBuilder(uint8_t byte, uint16_t two_bytes, uint32_t four_bytes, uint64_t eight_bytes) : byte_(byte), two_bytes_(two_bytes), four_bytes_(four_bytes), eight_bytes_(eight_bytes) {} ~EndianBuilder() = default; virtual size_t size() const override { - return sizeof(signature_) + sizeof(byte_) + sizeof(two_bytes_) + sizeof(four_bytes_) + sizeof(eight_bytes_); + return sizeof(signature_) + sizeof(byte_) + sizeof(two_bytes_) + sizeof(four_bytes_) + + sizeof(eight_bytes_); } virtual const std::unique_ptr> FinalPacket() { @@ -76,7 +80,7 @@ class EndianBuilder : public PacketBuilder { PacketBuilder::insert(eight_bytes_, it); } - private: +private: uint32_t signature_{(little_endian ? 0x03020100 : 0x00010203)}; uint8_t byte_; uint16_t two_bytes_; @@ -85,7 +89,7 @@ class EndianBuilder : public PacketBuilder { }; class PacketBuilderEndianTest : public ::testing::Test { - public: +public: PacketBuilderEndianTest() = default; ~PacketBuilderEndianTest() = default; }; @@ -98,7 +102,7 @@ TEST(PacketBuilderEndianTest, insertTest) { template class VectorBuilder : public PacketBuilder { - public: +public: VectorBuilder(const std::vector vect) { for (uint64_t element : vect) { vect_.push_back(static_cast(element)); @@ -106,9 +110,7 @@ class VectorBuilder : public PacketBuilder { } ~VectorBuilder() = default; - virtual size_t size() const override { - return vect_.size() * sizeof(T); - } + virtual size_t size() const override { return vect_.size() * sizeof(T); } virtual const std::unique_ptr> FinalPacket() { std::unique_ptr> packet = std::make_unique>(); @@ -122,13 +124,13 @@ class VectorBuilder : public PacketBuilder { PacketBuilder::insert_vector(vect_, it); } - private: +private: std::vector vect_; }; template class InsertElementsBuilder : public PacketBuilder { - public: +public: InsertElementsBuilder(const std::vector vect) { for (uint64_t element : vect) { vect_.push_back(static_cast(element)); @@ -136,9 +138,7 @@ class InsertElementsBuilder : public PacketBuilder { } virtual ~InsertElementsBuilder() = default; - virtual size_t size() const override { - return vect_.size() * sizeof(T); - } + virtual size_t size() const override { return vect_.size() * sizeof(T); } virtual const std::unique_ptr> FinalPacket() { std::unique_ptr> packet = std::make_unique>(); @@ -154,24 +154,26 @@ class InsertElementsBuilder : public PacketBuilder { } } - private: +private: std::vector vect_; }; std::vector vector_data{ - 0x7060504030201000, 0x7161514131211101, 0x7262524232221202, 0x7363534333231303, 0x7464544434241404, - 0x7565554535251505, 0x7666564636261606, 0x7767574737271707, 0x7868584838281808, + 0x7060504030201000, 0x7161514131211101, 0x7262524232221202, + 0x7363534333231303, 0x7464544434241404, 0x7565554535251505, + 0x7666564636261606, 0x7767574737271707, 0x7868584838281808, }; template class VectorBuilderTest : public ::testing::Test { - public: +public: VectorBuilderTest() = default; ~VectorBuilderTest() = default; void SetUp() { packet_1_ = std::shared_ptr>(new VectorBuilder(vector_data)); - packet_2_ = std::shared_ptr>(new InsertElementsBuilder(vector_data)); + packet_2_ = + std::shared_ptr>(new InsertElementsBuilder(vector_data)); } void TearDown() { @@ -183,7 +185,8 @@ class VectorBuilderTest : public ::testing::Test { std::shared_ptr> packet_2_; }; -using VectorBaseTypes = ::testing::Types; +using VectorBaseTypes = + ::testing::Types; TYPED_TEST_CASE(VectorBuilderTest, VectorBaseTypes); TYPED_TEST(VectorBuilderTest, insertVectorTest) { @@ -191,7 +194,7 @@ TYPED_TEST(VectorBuilderTest, insertVectorTest) { } class NestedBuilder : public PacketBuilder { - public: +public: ~NestedBuilder() = default; virtual size_t size() const override { @@ -203,7 +206,8 @@ class NestedBuilder : public PacketBuilder { return std::unique_ptr(new NestedBuilder(level)); } - static std::unique_ptr CreateNested(std::unique_ptr payload, uint8_t level) { + static std::unique_ptr CreateNested(std::unique_ptr payload, + uint8_t level) { return std::unique_ptr(new NestedBuilder(std::move(payload), level)); } @@ -222,11 +226,12 @@ class NestedBuilder : public PacketBuilder { } } - private: +private: std::unique_ptr payload_; uint8_t level_; - NestedBuilder(std::unique_ptr inner, uint8_t level) : payload_(std::move(inner)), level_(level) {} + NestedBuilder(std::unique_ptr inner, uint8_t level) + : payload_(std::move(inner)), level_(level) {} NestedBuilder(uint8_t level) : level_(level) {} }; @@ -234,7 +239,8 @@ class BuilderBuilderTest : public ::testing::Test {}; TEST(BuilderBuilderTest, nestingTest) { std::unique_ptr innermost = NestedBuilder::Create(0); - std::unique_ptr number_1 = NestedBuilder::CreateNested(std::move(innermost), 1); + std::unique_ptr number_1 = + NestedBuilder::CreateNested(std::move(innermost), 1); std::unique_ptr number_2 = NestedBuilder::CreateNested(std::move(number_1), 2); std::unique_ptr number_3 = NestedBuilder::CreateNested(std::move(number_2), 3); std::unique_ptr number_4 = NestedBuilder::CreateNested(std::move(number_3), 4); diff --git a/system/gd/packet/packet_struct.h b/system/gd/packet/packet_struct.h index 19bb0e526ab..92e3200f35e 100644 --- a/system/gd/packet/packet_struct.h +++ b/system/gd/packet/packet_struct.h @@ -34,7 +34,7 @@ namespace packet { // The template parameter little_endian controls the generation of insert(). template class PacketStruct : public BaseStruct, protected EndianInserter { - public: +public: PacketStruct() = default; virtual ~PacketStruct() = default; }; diff --git a/system/gd/packet/packet_view.h b/system/gd/packet/packet_view.h index b822fdfbfbb..3c495f37559 100644 --- a/system/gd/packet/packet_view.h +++ b/system/gd/packet/packet_view.h @@ -33,7 +33,7 @@ static const bool kLittleEndian = true; // The template parameter little_endian controls the generation of extract(). template class PacketView { - public: +public: explicit PacketView(std::forward_list fragments); explicit PacketView(std::shared_ptr> packet); PacketView(const PacketView& PacketView) = default; @@ -51,10 +51,10 @@ class PacketView { PacketView GetLittleEndianSubview(size_t begin, size_t end) const; PacketView GetBigEndianSubview(size_t begin, size_t end) const; - protected: +protected: void Append(PacketView to_add); - private: +private: std::forward_list fragments_; size_t length_; diff --git a/system/gd/packet/packet_view_unittest.cc b/system/gd/packet/packet_view_unittest.cc index 1e1fd8a2829..108275f94ac 100644 --- a/system/gd/packet/packet_view_unittest.cc +++ b/system/gd/packet/packet_view_unittest.cc @@ -31,22 +31,24 @@ using std::vector; namespace { vector count_all = { - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, - 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, + 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, + 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, }; vector count_1 = { - 0x00, - 0x01, - 0x02, + 0x00, + 0x01, + 0x02, }; vector count_2 = { - 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, + 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, }; vector count_3 = { - 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, + 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, + 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, }; } // namespace @@ -55,17 +57,16 @@ namespace packet { template class IteratorTest : public ::testing::Test { - public: +public: IteratorTest() = default; ~IteratorTest() override = default; void SetUp() override { - packet = std::shared_ptr(new T({View(std::make_shared>(count_all), 0, count_all.size())})); + packet = std::shared_ptr( + new T({View(std::make_shared>(count_all), 0, count_all.size())})); } - void TearDown() override { - packet.reset(); - } + void TearDown() override { packet.reset(); } std::shared_ptr packet; }; @@ -74,14 +75,14 @@ using PacketViewTypes = ::testing::Types, PacketView>; TYPED_TEST_CASE(IteratorTest, PacketViewTypes); class IteratorExtractTest : public ::testing::Test { - public: +public: IteratorExtractTest() = default; ~IteratorExtractTest() override = default; }; template class PacketViewTest : public IteratorTest { - public: +public: PacketViewTest() = default; ~PacketViewTest() = default; }; @@ -90,26 +91,26 @@ using PacketViewTypes = ::testing::Types, PacketView>; TYPED_TEST_CASE(PacketViewTest, PacketViewTypes); class PacketViewMultiViewTest : public ::testing::Test { - public: +public: PacketViewMultiViewTest() = default; ~PacketViewMultiViewTest() override = default; - const PacketView single_view = - PacketView({View(std::make_shared>(count_all), 0, count_all.size())}); + const PacketView single_view = PacketView( + {View(std::make_shared>(count_all), 0, count_all.size())}); const PacketView multi_view = PacketView({ - View(std::make_shared>(count_1), 0, count_1.size()), - View(std::make_shared>(count_2), 0, count_2.size()), - View(std::make_shared>(count_3), 0, count_3.size()), + View(std::make_shared>(count_1), 0, count_1.size()), + View(std::make_shared>(count_2), 0, count_2.size()), + View(std::make_shared>(count_3), 0, count_3.size()), }); }; class PacketViewMultiViewAppendTest : public ::testing::Test { - public: +public: PacketViewMultiViewAppendTest() = default; ~PacketViewMultiViewAppendTest() override = default; class AppendedPacketView : public PacketView { - public: + public: AppendedPacketView(PacketView first, std::forward_list> to_append) : PacketView(first) { for (const auto& packet_view : to_append) { @@ -117,22 +118,26 @@ class PacketViewMultiViewAppendTest : public ::testing::Test { } } }; - const PacketView single_view = - PacketView({View(std::make_shared>(count_all), 0, count_all.size())}); + const PacketView single_view = PacketView( + {View(std::make_shared>(count_all), 0, count_all.size())}); const PacketView multi_view = AppendedPacketView( - PacketView({View(std::make_shared>(count_1), 0, count_1.size())}), - {PacketView({View(std::make_shared>(count_2), 0, count_2.size())}), - PacketView({View(std::make_shared>(count_3), 0, count_3.size())})}); + PacketView( + {View(std::make_shared>(count_1), 0, count_1.size())}), + {PacketView( + {View(std::make_shared>(count_2), 0, count_2.size())}), + PacketView( + {View(std::make_shared>(count_3), 0, count_3.size())})}); }; class ViewTest : public ::testing::Test { - public: +public: ViewTest() = default; ~ViewTest() override = default; }; TEST(IteratorExtractTest, extractLeTest) { - PacketView packet({View(std::make_shared>(count_all), 0, count_all.size())}); + PacketView packet( + {View(std::make_shared>(count_all), 0, count_all.size())}); auto general_case = packet.begin(); ASSERT_EQ(0x00, general_case.extract()); @@ -146,7 +151,8 @@ TEST(IteratorExtractTest, extractLeTest) { } TEST(IteratorExtractTest, extractBeTest) { - PacketView packet({View(std::make_shared>(count_all), 0, count_all.size())}); + PacketView packet( + {View(std::make_shared>(count_all), 0, count_all.size())}); auto general_case = packet.begin(); ASSERT_EQ(0x00, general_case.extract()); @@ -178,7 +184,8 @@ TYPED_TEST(IteratorTest, dereferenceDeathTest) { TYPED_TEST(IteratorTest, plusEqTest) { auto plus_eq = this->packet->begin(); for (size_t i = 0; i < count_all.size(); i += 2) { - ASSERT_EQ(count_all[i], *plus_eq) << "+= test: Dereferenced iterator does not equal expected at index " << i; + ASSERT_EQ(count_all[i], *plus_eq) + << "+= test: Dereferenced iterator does not equal expected at index " << i; plus_eq += 2; } } @@ -186,8 +193,9 @@ TYPED_TEST(IteratorTest, plusEqTest) { TYPED_TEST(IteratorTest, preIncrementTest) { auto plus_plus = this->packet->begin(); for (size_t i = 0; i < count_all.size() - 1; i++) { - ASSERT_EQ(count_all[i + 1], *(++plus_plus)) << "Pre-increment test: Dereferenced iterator does not equal expected " - << "at index " << i; + ASSERT_EQ(count_all[i + 1], *(++plus_plus)) + << "Pre-increment test: Dereferenced iterator does not equal expected " << "at index " + << i; } } @@ -195,8 +203,8 @@ TYPED_TEST(IteratorTest, postIncrementTest) { auto plus_plus = this->packet->begin(); for (size_t i = 0; i < count_all.size(); i++) { ASSERT_EQ(count_all[i], plus_plus.operator*()) - << "Post-increment test: Dereferenced iterator does not equal expected " - << "at index " << i; + << "Post-increment test: Dereferenced iterator does not equal expected " << "at index " + << i; plus_plus.operator++(); } } @@ -204,7 +212,8 @@ TYPED_TEST(IteratorTest, postIncrementTest) { TYPED_TEST(IteratorTest, additionTest) { auto plus = this->packet->begin(); for (size_t i = 0; i < count_all.size(); i++) { - ASSERT_EQ(count_all[i], *plus) << "+ test: Dereferenced iterator does not equal expected at index " << i; + ASSERT_EQ(count_all[i], *plus) + << "+ test: Dereferenced iterator does not equal expected at index " << i; plus = plus + 1; } } @@ -215,7 +224,7 @@ TYPED_TEST(IteratorTest, minusEqTest) { size_t index = count_all.size() - 1; for (size_t i = 0; index > i; i++) { ASSERT_EQ(count_all[index], *minus_eq) - << "-= test: Dereferenced iterator does not equal expected at index " << index; + << "-= test: Dereferenced iterator does not equal expected at index " << index; index -= i; minus_eq -= i; } @@ -225,8 +234,8 @@ TYPED_TEST(IteratorTest, preDecrementTest) { auto minus_minus = this->packet->end(); for (size_t i = count_all.size(); i > 0; i--) { ASSERT_EQ(count_all[i - 1], *(--minus_minus)) - << "Pre-decrement test: Dereferenced iterator does not equal expected " - << "at index " << i; + << "Pre-decrement test: Dereferenced iterator does not equal expected " << "at index " + << i; } } @@ -235,8 +244,8 @@ TYPED_TEST(IteratorTest, postDecrementTest) { minus_minus.operator--(); for (size_t i = count_all.size() - 1; i > 0; i--) { ASSERT_EQ(count_all[i], minus_minus.operator*()) - << "Post-decrement test: Dereferenced iterator does not equal expected " - << "at index " << i; + << "Post-decrement test: Dereferenced iterator does not equal expected " << "at index " + << i; minus_minus.operator--(); } } @@ -245,7 +254,8 @@ TYPED_TEST(IteratorTest, subtractionTest) { auto minus = this->packet->end(); minus = minus - 1; for (size_t i = count_all.size() - 1; i > 0; i--) { - ASSERT_EQ(count_all[i], *minus) << "- test: Dereferenced iterator does not equal expected at index " << i; + ASSERT_EQ(count_all[i], *minus) + << "- test: Dereferenced iterator does not equal expected at index " << i; minus = minus - 1; } } @@ -412,9 +422,9 @@ TYPED_TEST(IteratorTest, constructor_from_shared_vector_test) { using SubviewTestParam = std::pair; class SubviewBaseTest : public ::testing::TestWithParam { - public: +public: class SubPacketView : public PacketView { - public: + public: using PacketView::PacketView; PacketView Slice(size_t header, size_t tail) { return PacketView::GetLittleEndianSubview(header, tail); @@ -427,11 +437,12 @@ class SubviewPassTest : public SubviewBaseTest {}; TEST_P(SubviewPassTest, subviewTest) { auto header = GetParam().first; auto tail = GetParam().second; - SubPacketView single_view({View(std::make_shared>(count_all), 0, count_all.size())}); + SubPacketView single_view( + {View(std::make_shared>(count_all), 0, count_all.size())}); SubPacketView multi_view({ - View(std::make_shared>(count_1), 0, count_1.size()), - View(std::make_shared>(count_2), 0, count_2.size()), - View(std::make_shared>(count_3), 0, count_3.size()), + View(std::make_shared>(count_1), 0, count_1.size()), + View(std::make_shared>(count_2), 0, count_2.size()), + View(std::make_shared>(count_3), 0, count_3.size()), }); auto single_slice = single_view.Slice(header, tail); @@ -448,31 +459,40 @@ static const size_t boundary_1 = count_1.size(); static const size_t boundary_2 = count_1.size() + count_2.size(); INSTANTIATE_TEST_CASE_P( - chopomatic, SubviewPassTest, - ::testing::Values( - // {begin, end} pairs for subsets into the PacketView - SubviewTestParam{0, 0}, SubviewTestParam{0, boundary_1}, SubviewTestParam{0, boundary_1 + 1}, - SubviewTestParam{0, boundary_2}, SubviewTestParam{0, boundary_2 + 1}, SubviewTestParam{0, count_all.size()}, - SubviewTestParam{boundary_1 - 1, boundary_1}, SubviewTestParam{boundary_1 - 1, boundary_1 + 1}, - SubviewTestParam{boundary_1 - 1, boundary_2}, SubviewTestParam{boundary_1 - 1, boundary_2 + 1}, - SubviewTestParam{boundary_1 - 1, count_all.size()}, SubviewTestParam{boundary_1, boundary_1}, - SubviewTestParam{boundary_1, boundary_2}, SubviewTestParam{boundary_1, boundary_2 + 1}, - SubviewTestParam{boundary_1, count_all.size()}, SubviewTestParam{boundary_2 - 1, boundary_2}, - SubviewTestParam{boundary_2 - 1, boundary_2 + 1}, SubviewTestParam{boundary_2 - 1, count_all.size()}, - SubviewTestParam{boundary_2, boundary_2}, SubviewTestParam{boundary_2, boundary_2 + 1}, - SubviewTestParam{boundary_2, count_all.size()}, SubviewTestParam{count_all.size() - 1, count_all.size()}, - SubviewTestParam{count_all.size(), count_all.size()})); + chopomatic, SubviewPassTest, + ::testing::Values( + // {begin, end} pairs for subsets into the PacketView + SubviewTestParam{0, 0}, SubviewTestParam{0, boundary_1}, + SubviewTestParam{0, boundary_1 + 1}, SubviewTestParam{0, boundary_2}, + SubviewTestParam{0, boundary_2 + 1}, SubviewTestParam{0, count_all.size()}, + SubviewTestParam{boundary_1 - 1, boundary_1}, + SubviewTestParam{boundary_1 - 1, boundary_1 + 1}, + SubviewTestParam{boundary_1 - 1, boundary_2}, + SubviewTestParam{boundary_1 - 1, boundary_2 + 1}, + SubviewTestParam{boundary_1 - 1, count_all.size()}, + SubviewTestParam{boundary_1, boundary_1}, SubviewTestParam{boundary_1, boundary_2}, + SubviewTestParam{boundary_1, boundary_2 + 1}, + SubviewTestParam{boundary_1, count_all.size()}, + SubviewTestParam{boundary_2 - 1, boundary_2}, + SubviewTestParam{boundary_2 - 1, boundary_2 + 1}, + SubviewTestParam{boundary_2 - 1, count_all.size()}, + SubviewTestParam{boundary_2, boundary_2}, + SubviewTestParam{boundary_2, boundary_2 + 1}, + SubviewTestParam{boundary_2, count_all.size()}, + SubviewTestParam{count_all.size() - 1, count_all.size()}, + SubviewTestParam{count_all.size(), count_all.size()})); class SubviewDeathTest : public SubviewBaseTest {}; TEST_P(SubviewDeathTest, subviewDeathTest) { auto header = GetParam().first; auto tail = GetParam().second; - SubPacketView single_view({View(std::make_shared>(count_all), 0, count_all.size())}); + SubPacketView single_view( + {View(std::make_shared>(count_all), 0, count_all.size())}); SubPacketView multi_view({ - View(std::make_shared>(count_1), 0, count_1.size()), - View(std::make_shared>(count_2), 0, count_2.size()), - View(std::make_shared>(count_3), 0, count_3.size()), + View(std::make_shared>(count_1), 0, count_1.size()), + View(std::make_shared>(count_2), 0, count_2.size()), + View(std::make_shared>(count_3), 0, count_3.size()), }); ASSERT_DEATH(auto single_slice = single_view.Slice(header, tail), ""); @@ -481,12 +501,14 @@ TEST_P(SubviewDeathTest, subviewDeathTest) { INSTANTIATE_TEST_CASE_P(chopomaticDeath, SubviewDeathTest, ::testing::Values( - // {begin, end} pairs for subsets into the PacketView - SubviewTestParam{1, 0}, SubviewTestParam{count_all.size(), count_all.size() - 1}, - SubviewTestParam{count_all.size(), count_all.size() + 1})); + // {begin, end} pairs for subsets into the PacketView + SubviewTestParam{1, 0}, + SubviewTestParam{count_all.size(), count_all.size() - 1}, + SubviewTestParam{count_all.size(), count_all.size() + 1})); TEST(SubviewTest, simpleSubviewTest) { - PacketView view({View(std::make_shared>(count_all), 0, count_all.size())}); + PacketView view( + {View(std::make_shared>(count_all), 0, count_all.size())}); PacketView sub_1_view = view.GetLittleEndianSubview(0, view.size()); PacketView sub_2_view = sub_1_view.GetLittleEndianSubview(0, sub_1_view.size()); PacketView sub_3_view = sub_2_view.GetLittleEndianSubview(0, sub_2_view.size()); @@ -498,7 +520,8 @@ TEST(SubviewTest, simpleSubviewTest) { } TEST(SubviewTest, realSubviewTest) { - PacketView view({View(std::make_shared>(count_all), 0, count_all.size())}); + PacketView view( + {View(std::make_shared>(count_all), 0, count_all.size())}); std::vector> sub_views{view}; for (size_t i = 1; i < 6; i++) { size_t parent_size = sub_views[i - 1].size(); @@ -509,11 +532,12 @@ TEST(SubviewTest, realSubviewTest) { } TEST(SubviewTest, subSubviewTest) { - PacketView single_view({View(std::make_shared>(count_all), 0, count_all.size())}); + PacketView single_view( + {View(std::make_shared>(count_all), 0, count_all.size())}); PacketView multi_view({ - View(std::make_shared>(count_1), 0, count_1.size()), - View(std::make_shared>(count_2), 0, count_2.size()), - View(std::make_shared>(count_3), 0, count_3.size()), + View(std::make_shared>(count_1), 0, count_1.size()), + View(std::make_shared>(count_2), 0, count_2.size()), + View(std::make_shared>(count_3), 0, count_3.size()), }); ASSERT_EQ(single_view.size(), multi_view.size()); for (size_t i = 0; i < count_all.size() / 2; i++) { @@ -522,17 +546,17 @@ TEST(SubviewTest, subSubviewTest) { ASSERT_EQ(count_all.size() - 2 * i, sub_single_view.size()); ASSERT_EQ(sub_single_view.size(), sub_multi_view.size()); for (size_t j = 0; j < sub_single_view.size() / 2; j++) { - PacketView sub_sub_single_view = sub_single_view.GetLittleEndianSubview(j, sub_single_view.size() - j); - PacketView sub_sub_multi_view = sub_multi_view.GetLittleEndianSubview(j, sub_multi_view.size() - j); + PacketView sub_sub_single_view = + sub_single_view.GetLittleEndianSubview(j, sub_single_view.size() - j); + PacketView sub_sub_multi_view = + sub_multi_view.GetLittleEndianSubview(j, sub_multi_view.size() - j); ASSERT_EQ(sub_single_view.size() - 2 * j, sub_sub_single_view.size()); ASSERT_EQ(sub_sub_single_view.size(), sub_sub_multi_view.size()); } } } -TEST_F(PacketViewMultiViewTest, sizeTest) { - ASSERT_EQ(single_view.size(), multi_view.size()); -} +TEST_F(PacketViewMultiViewTest, sizeTest) { ASSERT_EQ(single_view.size(), multi_view.size()); } TEST_F(PacketViewMultiViewTest, dereferenceTestLittleEndian) { auto single_itr = single_view.begin(); @@ -606,7 +630,8 @@ TEST(ViewTest, arrayOperatorTest) { size_t header_size = 2; size_t tail_size = 3; - View view_subset(std::make_shared>(count_all), header_size, count_all.size() - tail_size); + View view_subset(std::make_shared>(count_all), header_size, + count_all.size() - tail_size); View view_subset2(view_all, header_size, count_all.size() - tail_size); size_t subset_length = view_subset.size(); for (size_t i = 0; i < subset_length; i++) { diff --git a/system/gd/packet/parser/checksum_def.cc b/system/gd/packet/parser/checksum_def.cc index 39a44c43267..0ad6ec6f906 100644 --- a/system/gd/packet/parser/checksum_def.cc +++ b/system/gd/packet/parser/checksum_def.cc @@ -19,17 +19,17 @@ #include "fields/checksum_field.h" #include "util.h" -ChecksumDef::ChecksumDef(std::string name, std::string include, int size) : CustomFieldDef(name, include, size) {} +ChecksumDef::ChecksumDef(std::string name, std::string include, int size) + : CustomFieldDef(name, include, size) {} PacketField* ChecksumDef::GetNewField(const std::string& name, ParseLocation loc) const { return new ChecksumField(name, name_, size_, loc); } -TypeDef::Type ChecksumDef::GetDefinitionType() const { - return TypeDef::Type::CHECKSUM; -} +TypeDef::Type ChecksumDef::GetDefinitionType() const { return TypeDef::Type::CHECKSUM; } void ChecksumDef::GenChecksumCheck(std::ostream& s) const { - s << "static_assert(ChecksumTypeChecker<" << name_ << "," << util::GetTypeForSize(size_) << ">::value, \""; + s << "static_assert(ChecksumTypeChecker<" << name_ << "," << util::GetTypeForSize(size_) + << ">::value, \""; s << name_ << " is not a valid checksum type. Please see README for more details.\");"; } diff --git a/system/gd/packet/parser/checksum_def.h b/system/gd/packet/parser/checksum_def.h index f82b8c36f84..ee8ea1b9099 100644 --- a/system/gd/packet/parser/checksum_def.h +++ b/system/gd/packet/parser/checksum_def.h @@ -24,7 +24,7 @@ #include "type_def.h" class ChecksumDef : public CustomFieldDef { - public: +public: ChecksumDef(std::string name, std::string include, int size); virtual PacketField* GetNewField(const std::string& name, ParseLocation loc) const override; diff --git a/system/gd/packet/parser/custom_field_def.cc b/system/gd/packet/parser/custom_field_def.cc index b950ca11f03..1ffde0522e9 100644 --- a/system/gd/packet/parser/custom_field_def.cc +++ b/system/gd/packet/parser/custom_field_def.cc @@ -18,7 +18,8 @@ #include "util.h" -CustomFieldDef::CustomFieldDef(std::string name, std::string include) : TypeDef(name), include_(include) {} +CustomFieldDef::CustomFieldDef(std::string name, std::string include) + : TypeDef(name), include_(include) {} CustomFieldDef::CustomFieldDef(std::string name, std::string include, int size) : TypeDef(name, size), include_(include) { @@ -35,9 +36,7 @@ PacketField* CustomFieldDef::GetNewField(const std::string& name, ParseLocation } } -TypeDef::Type CustomFieldDef::GetDefinitionType() const { - return TypeDef::Type::CUSTOM; -} +TypeDef::Type CustomFieldDef::GetDefinitionType() const { return TypeDef::Type::CUSTOM; } void CustomFieldDef::GenInclude(std::ostream& s) const { s << "#include \"" << include_ << util::CamelCaseToUnderScore(GetTypeName()) << ".h\"\n"; @@ -58,11 +57,13 @@ void CustomFieldDef::GenUsing(std::ostream& s) const { } void CustomFieldDef::GenFixedSizeCustomFieldCheck(std::ostream& s) const { - s << "static_assert(std::is_base_of_v, " << name_ << ">, \""; - s << name_ << " is not a valid fixed size custom field type. Please see README for more details.\");"; + s << "static_assert(std::is_base_of_v, " << name_ + << ">, \""; + s << name_ + << " is not a valid fixed size custom field type. Please see README for more details.\");"; s << "static_assert(CustomFieldFixedSizeInterface<" << name_ << ">::length() * 8 == " << size_ - << ", \"CustomFieldFixedSizeInterface<" << name_ << ">::length * 8 should match PDL defined size (in bits) " - << size_ << "\");"; + << ", \"CustomFieldFixedSizeInterface<" << name_ + << ">::length * 8 should match PDL defined size (in bits) " << size_ << "\");"; } void CustomFieldDef::GenCustomFieldCheck(std::ostream& s, bool little_endian) const { diff --git a/system/gd/packet/parser/custom_field_def.h b/system/gd/packet/parser/custom_field_def.h index 24b28304524..f605fe559bf 100644 --- a/system/gd/packet/parser/custom_field_def.h +++ b/system/gd/packet/parser/custom_field_def.h @@ -24,7 +24,7 @@ #include "type_def.h" class CustomFieldDef : public TypeDef { - public: +public: CustomFieldDef(std::string name, std::string include); CustomFieldDef(std::string name, std::string include, int size); diff --git a/system/gd/packet/parser/declarations.h b/system/gd/packet/parser/declarations.h index 6d892765f6b..ff89d8aaf16 100644 --- a/system/gd/packet/parser/declarations.h +++ b/system/gd/packet/parser/declarations.h @@ -28,7 +28,7 @@ #include "struct_def.h" class Declarations { - public: +public: void AddTypeDef(std::string name, TypeDef* def) { auto it = type_defs_.find(name); if (it != type_defs_.end()) { diff --git a/system/gd/packet/parser/enum_def.cc b/system/gd/packet/parser/enum_def.cc index f87ed8a5d2e..8b36572b3a4 100644 --- a/system/gd/packet/parser/enum_def.cc +++ b/system/gd/packet/parser/enum_def.cc @@ -26,11 +26,13 @@ EnumDef::EnumDef(std::string name, int size) : TypeDef(name, size) {} void EnumDef::AddEntry(std::string name, uint64_t value) { if (!util::IsEnumCase(name)) { - ERROR() << __func__ << ": Enum " << name << "(" << value << ") should be all uppercase with underscores"; + ERROR() << __func__ << ": Enum " << name << "(" << value + << ") should be all uppercase with underscores"; } if (value > util::GetMaxValueForBits(size_)) { - ERROR() << __func__ << ": Value of " << name << "(" << value << ") is greater than the max possible value for enum " - << name_ << "(" << util::GetMaxValueForBits(size_) << ")\n"; + ERROR() << __func__ << ": Value of " << name << "(" << value + << ") is greater than the max possible value for enum " << name_ << "(" + << util::GetMaxValueForBits(size_) << ")\n"; } constants_.insert(std::pair(value, name)); @@ -41,10 +43,6 @@ PacketField* EnumDef::GetNewField(const std::string& name, ParseLocation loc) co return new EnumField(name, *this, "What is this for", loc); } -bool EnumDef::HasEntry(std::string name) const { - return entries_.count(name) != 0; -} +bool EnumDef::HasEntry(std::string name) const { return entries_.count(name) != 0; } -TypeDef::Type EnumDef::GetDefinitionType() const { - return TypeDef::Type::ENUM; -} +TypeDef::Type EnumDef::GetDefinitionType() const { return TypeDef::Type::ENUM; } diff --git a/system/gd/packet/parser/enum_def.h b/system/gd/packet/parser/enum_def.h index b17f1b1bb5b..1150da86c7d 100644 --- a/system/gd/packet/parser/enum_def.h +++ b/system/gd/packet/parser/enum_def.h @@ -26,7 +26,7 @@ // Holds the definition of an enum. class EnumDef : public TypeDef { - public: +public: EnumDef(std::string name, int size); virtual PacketField* GetNewField(const std::string& name, ParseLocation loc) const; diff --git a/system/gd/packet/parser/enum_gen.h b/system/gd/packet/parser/enum_gen.h index be165598511..7dcb7b76a3e 100644 --- a/system/gd/packet/parser/enum_gen.h +++ b/system/gd/packet/parser/enum_gen.h @@ -22,7 +22,7 @@ // Generates the C++ code for an enum. class EnumGen { - public: +public: EnumGen(EnumDef e); void GenDefinition(std::ostream& stream); diff --git a/system/gd/packet/parser/field_list.h b/system/gd/packet/parser/field_list.h index 81fc0d76a2e..2eaeffa1cbf 100644 --- a/system/gd/packet/parser/field_list.h +++ b/system/gd/packet/parser/field_list.h @@ -27,7 +27,7 @@ using FieldListIterator = std::vector::const_iterator; using ReverseFieldListIterator = std::vector::const_reverse_iterator; class FieldList { - public: +public: FieldList() = default; FieldList(std::vector fields) { @@ -44,9 +44,7 @@ class FieldList { } } - PacketField* operator[](int index) const { - return field_list_[index]; - } + PacketField* operator[](int index) const { return field_list_[index]; } PacketField* GetField(std::string field_name) const { auto it = field_map_.find(field_name); @@ -71,7 +69,8 @@ class FieldList { FieldList ret; for (auto it = begin(); it != end(); it++) { const auto& field = *it; - if (field->GetFieldType() == PayloadField::kFieldType || field->GetFieldType() == BodyField::kFieldType) { + if (field->GetFieldType() == PayloadField::kFieldType || + field->GetFieldType() == BodyField::kFieldType) { break; } ret.AppendField(*it); @@ -84,7 +83,8 @@ class FieldList { FieldListIterator it; for (it = begin(); it != end(); it++) { const auto& field = *it; - if (field->GetFieldType() == PayloadField::kFieldType || field->GetFieldType() == BodyField::kFieldType) { + if (field->GetFieldType() == PayloadField::kFieldType || + field->GetFieldType() == BodyField::kFieldType) { // Increment it once to get first field after payload/body. it++; break; @@ -148,39 +148,23 @@ class FieldList { return ret; } - bool HasPayloadOrBody() const { - return has_payload_ || has_body_; - } + bool HasPayloadOrBody() const { return has_payload_ || has_body_; } - bool HasPayload() const { - return has_payload_; - } + bool HasPayload() const { return has_payload_; } - bool HasBody() const { - return has_body_; - } + bool HasBody() const { return has_body_; } - FieldListIterator begin() const { - return field_list_.begin(); - } + FieldListIterator begin() const { return field_list_.begin(); } - FieldListIterator end() const { - return field_list_.end(); - } + FieldListIterator end() const { return field_list_.end(); } - ReverseFieldListIterator rbegin() const { - return field_list_.rbegin(); - } + ReverseFieldListIterator rbegin() const { return field_list_.rbegin(); } - ReverseFieldListIterator rend() const { - return field_list_.rend(); - } + ReverseFieldListIterator rend() const { return field_list_.rend(); } - size_t size() const { - return field_list_.size(); - } + size_t size() const { return field_list_.size(); } - private: +private: void AddField(PacketField* field) { if (field_map_.find(field->GetName()) != field_map_.end()) { ERROR(field) << "Field with name \"" << field->GetName() << "\" was previously defined.\n"; diff --git a/system/gd/packet/parser/fields/array_field.cc b/system/gd/packet/parser/fields/array_field.cc index 27719d0864c..b3612a089bd 100644 --- a/system/gd/packet/parser/fields/array_field.cc +++ b/system/gd/packet/parser/fields/array_field.cc @@ -23,26 +23,31 @@ const std::string ArrayField::kFieldType = "ArrayField"; ArrayField::ArrayField(std::string name, int element_size, int array_size, ParseLocation loc) - : PacketField(name, loc), element_field_(new ScalarField("val", element_size, loc)), element_size_(element_size), + : PacketField(name, loc), + element_field_(new ScalarField("val", element_size, loc)), + element_size_(element_size), array_size_(array_size) { - if (element_size > 64 || element_size < 0) + if (element_size > 64 || element_size < 0) { ERROR(this) << __func__ << ": Not implemented for element size = " << element_size; + } if (element_size % 8 != 0) { - ERROR(this) << "Can only have arrays with elements that are byte aligned (" << element_size << ")"; + ERROR(this) << "Can only have arrays with elements that are byte aligned (" << element_size + << ")"; } } ArrayField::ArrayField(std::string name, TypeDef* type_def, int array_size, ParseLocation loc) - : PacketField(name, loc), element_field_(type_def->GetNewField("val", loc)), - element_size_(element_field_->GetSize()), array_size_(array_size) { + : PacketField(name, loc), + element_field_(type_def->GetNewField("val", loc)), + element_size_(element_field_->GetSize()), + array_size_(array_size) { if (!element_size_.empty() && element_size_.bits() % 8 != 0) { - ERROR(this) << "Can only have arrays with elements that are byte aligned (" << element_size_ << ")"; + ERROR(this) << "Can only have arrays with elements that are byte aligned (" << element_size_ + << ")"; } } -const std::string& ArrayField::GetFieldType() const { - return ArrayField::kFieldType; -} +const std::string& ArrayField::GetFieldType() const { return ArrayField::kFieldType; } Size ArrayField::GetSize() const { if (!element_size_.empty() && !element_size_.has_dynamic()) { @@ -87,7 +92,8 @@ void ArrayField::GenExtractor(std::ostream& s, int num_leading_bits, bool for_st s << GetDataType() << "::iterator ret_it = " << GetName() << "_ptr->begin();"; s << "auto " << element_field_->GetName() << "_it = " << GetName() << "_it;"; if (!element_size_.empty()) { - s << "while (" << element_field_->GetName() << "_it.NumBytesRemaining() >= " << element_size_.bytes(); + s << "while (" << element_field_->GetName() + << "_it.NumBytesRemaining() >= " << element_size_.bytes(); s << " && ret_it < " << GetName() << "_ptr->end()) {"; } else { s << "while (" << element_field_->GetName() << "_it.NumBytesRemaining() > 0 "; @@ -146,9 +152,7 @@ bool ArrayField::GenBuilderMember(std::ostream& s) const { return true; } -bool ArrayField::HasParameterValidator() const { - return false; -} +bool ArrayField::HasParameterValidator() const { return false; } void ArrayField::GenParameterValidator(std::ostream&) const { // Array length is validated by the compiler @@ -161,20 +165,16 @@ void ArrayField::GenInserter(std::ostream& s) const { } void ArrayField::GenValidator(std::ostream&) const { - // NOTE: We could check if the element size divides cleanly into the array size, but we decided to forgo that - // in favor of just returning as many elements as possible in a best effort style. + // NOTE: We could check if the element size divides cleanly into the array size, but we decided to + // forgo that in favor of just returning as many elements as possible in a best effort style. // - // Other than that there is nothing that arrays need to be validated on other than length so nothing needs to - // be done here. + // Other than that there is nothing that arrays need to be validated on other than length so + // nothing needs to be done here. } -bool ArrayField::IsContainerField() const { - return true; -} +bool ArrayField::IsContainerField() const { return true; } -const PacketField* ArrayField::GetElementField() const { - return element_field_; -} +const PacketField* ArrayField::GetElementField() const { return element_field_; } void ArrayField::GenStringRepresentation(std::ostream& s, std::string accessor) const { s << "\"ARRAY[\";"; diff --git a/system/gd/packet/parser/fields/array_field.h b/system/gd/packet/parser/fields/array_field.h index e31e8de006a..80c08e3b97d 100644 --- a/system/gd/packet/parser/fields/array_field.h +++ b/system/gd/packet/parser/fields/array_field.h @@ -21,7 +21,7 @@ #include "type_def.h" class ArrayField : public PacketField { - public: +public: ArrayField(std::string name, int element_size, int fixed_size, ParseLocation loc); ArrayField(std::string name, TypeDef* type_def, int fixed_size, ParseLocation loc); diff --git a/system/gd/packet/parser/fields/body_field.cc b/system/gd/packet/parser/fields/body_field.cc index cab1af529d9..b0a093d7d43 100644 --- a/system/gd/packet/parser/fields/body_field.cc +++ b/system/gd/packet/parser/fields/body_field.cc @@ -22,14 +22,13 @@ BodyField::BodyField(ParseLocation loc) : PacketField("body", loc) {} void BodyField::SetSizeField(const SizeField* size_field) { if (size_field_ != nullptr) { - ERROR(this, size_field_, size_field) << "The size field for the body has already been assigned."; + ERROR(this, size_field_, size_field) + << "The size field for the body has already been assigned."; } size_field_ = size_field; } -const std::string& BodyField::GetFieldType() const { - return BodyField::kFieldType; -} +const std::string& BodyField::GetFieldType() const { return BodyField::kFieldType; } Size BodyField::GetSize() const { if (size_field_ == nullptr) { @@ -46,19 +45,13 @@ std::string BodyField::GetDataType() const { void BodyField::GenExtractor(std::ostream&, int, bool) const {} -std::string BodyField::GetGetterFunctionName() const { - return ""; -} +std::string BodyField::GetGetterFunctionName() const { return ""; } void BodyField::GenGetter(std::ostream&, Size, Size) const {} -std::string BodyField::GetBuilderParameterType() const { - return ""; -} +std::string BodyField::GetBuilderParameterType() const { return ""; } -bool BodyField::HasParameterValidator() const { - return false; -} +bool BodyField::HasParameterValidator() const { return false; } void BodyField::GenParameterValidator(std::ostream&) const { // There is no validation needed for a payload diff --git a/system/gd/packet/parser/fields/body_field.h b/system/gd/packet/parser/fields/body_field.h index d8c4ee0b390..7f44d001e14 100644 --- a/system/gd/packet/parser/fields/body_field.h +++ b/system/gd/packet/parser/fields/body_field.h @@ -21,7 +21,7 @@ #include "parse_location.h" class BodyField : public PacketField { - public: +public: BodyField(ParseLocation loc); static const std::string kFieldType; diff --git a/system/gd/packet/parser/fields/checksum_field.cc b/system/gd/packet/parser/fields/checksum_field.cc index 67863c26d71..729266ae9de 100644 --- a/system/gd/packet/parser/fields/checksum_field.cc +++ b/system/gd/packet/parser/fields/checksum_field.cc @@ -15,6 +15,7 @@ */ #include "fields/checksum_field.h" + #include "util.h" const std::string ChecksumField::kFieldType = "ChecksumField"; @@ -22,29 +23,19 @@ const std::string ChecksumField::kFieldType = "ChecksumField"; ChecksumField::ChecksumField(std::string name, std::string type_name, int size, ParseLocation loc) : ScalarField(name, size, loc), type_name_(type_name) {} -const std::string& ChecksumField::GetFieldType() const { - return ChecksumField::kFieldType; -} +const std::string& ChecksumField::GetFieldType() const { return ChecksumField::kFieldType; } -std::string ChecksumField::GetDataType() const { - return type_name_; -} +std::string ChecksumField::GetDataType() const { return type_name_; } void ChecksumField::GenExtractor(std::ostream&, int, bool) const {} -std::string ChecksumField::GetGetterFunctionName() const { - return ""; -} +std::string ChecksumField::GetGetterFunctionName() const { return ""; } void ChecksumField::GenGetter(std::ostream&, Size, Size) const {} -bool ChecksumField::GenBuilderParameter(std::ostream&) const { - return false; -} +bool ChecksumField::GenBuilderParameter(std::ostream&) const { return false; } -bool ChecksumField::HasParameterValidator() const { - return false; -} +bool ChecksumField::HasParameterValidator() const { return false; } void ChecksumField::GenParameterValidator(std::ostream&) const { // Do nothing. @@ -52,7 +43,8 @@ void ChecksumField::GenParameterValidator(std::ostream&) const { void ChecksumField::GenInserter(std::ostream& s) const { s << "packet::ByteObserver observer = i.UnregisterObserver();"; - s << "insert(static_cast<" << util::GetTypeForSize(GetSize().bits()) << ">(observer.GetValue()), i);"; + s << "insert(static_cast<" << util::GetTypeForSize(GetSize().bits()) + << ">(observer.GetValue()), i);"; } void ChecksumField::GenValidator(std::ostream&) const { diff --git a/system/gd/packet/parser/fields/checksum_field.h b/system/gd/packet/parser/fields/checksum_field.h index 0e0a4c2ec2a..c54439b3437 100644 --- a/system/gd/packet/parser/fields/checksum_field.h +++ b/system/gd/packet/parser/fields/checksum_field.h @@ -21,7 +21,7 @@ #include "parse_location.h" class ChecksumField : public ScalarField { - public: +public: ChecksumField(std::string name, std::string type_name, int size, ParseLocation loc); static const std::string kFieldType; @@ -48,6 +48,6 @@ class ChecksumField : public ScalarField { virtual void GenStringRepresentation(std::ostream& s, std::string accessor) const override; - private: +private: std::string type_name_; }; diff --git a/system/gd/packet/parser/fields/checksum_start_field.cc b/system/gd/packet/parser/fields/checksum_start_field.cc index 3f87db252f9..3634b45c0fa 100644 --- a/system/gd/packet/parser/fields/checksum_start_field.cc +++ b/system/gd/packet/parser/fields/checksum_start_field.cc @@ -15,6 +15,7 @@ */ #include "fields/checksum_start_field.h" + #include "util.h" const std::string ChecksumStartField::kFieldType = "ChecksumStartField"; @@ -26,9 +27,7 @@ const std::string& ChecksumStartField::GetFieldType() const { return ChecksumStartField::kFieldType; } -Size ChecksumStartField::GetSize() const { - return Size(0); -} +Size ChecksumStartField::GetSize() const { return Size(0); } std::string ChecksumStartField::GetDataType() const { return "There's no type for Checksum Start fields"; @@ -36,19 +35,13 @@ std::string ChecksumStartField::GetDataType() const { void ChecksumStartField::GenExtractor(std::ostream&, int, bool) const {} -std::string ChecksumStartField::GetGetterFunctionName() const { - return ""; -} +std::string ChecksumStartField::GetGetterFunctionName() const { return ""; } void ChecksumStartField::GenGetter(std::ostream&, Size, Size) const {} -std::string ChecksumStartField::GetBuilderParameterType() const { - return ""; -} +std::string ChecksumStartField::GetBuilderParameterType() const { return ""; } -bool ChecksumStartField::HasParameterValidator() const { - return false; -} +bool ChecksumStartField::HasParameterValidator() const { return false; } void ChecksumStartField::GenParameterValidator(std::ostream&) const {} @@ -58,9 +51,7 @@ void ChecksumStartField::GenInserter(std::ostream&) const { void ChecksumStartField::GenValidator(std::ostream&) const {} -std::string ChecksumStartField::GetStartedFieldName() const { - return started_field_name_; -} +std::string ChecksumStartField::GetStartedFieldName() const { return started_field_name_; } void ChecksumStartField::GenStringRepresentation(std::ostream&, std::string) const { // Print nothing for checksum start diff --git a/system/gd/packet/parser/fields/checksum_start_field.h b/system/gd/packet/parser/fields/checksum_start_field.h index 8c61a8219ca..d0d29ca517c 100644 --- a/system/gd/packet/parser/fields/checksum_start_field.h +++ b/system/gd/packet/parser/fields/checksum_start_field.h @@ -20,7 +20,7 @@ #include "parse_location.h" class ChecksumStartField : public PacketField { - public: +public: ChecksumStartField(std::string name, ParseLocation loc); static const std::string kFieldType; @@ -53,6 +53,6 @@ class ChecksumStartField : public PacketField { virtual void GenStringRepresentation(std::ostream& s, std::string accessor) const override; - private: +private: std::string started_field_name_; }; diff --git a/system/gd/packet/parser/fields/count_field.cc b/system/gd/packet/parser/fields/count_field.cc index 8e1cf090b64..0c5c1ace855 100644 --- a/system/gd/packet/parser/fields/count_field.cc +++ b/system/gd/packet/parser/fields/count_field.cc @@ -15,6 +15,7 @@ */ #include "fields/count_field.h" + #include "util.h" const std::string CountField::kFieldType = "CountField"; @@ -22,9 +23,7 @@ const std::string CountField::kFieldType = "CountField"; CountField::CountField(std::string name, int size, ParseLocation loc) : ScalarField(name + "_count", size, loc), sized_field_name_(name) {} -const std::string& CountField::GetFieldType() const { - return CountField::kFieldType; -} +const std::string& CountField::GetFieldType() const { return CountField::kFieldType; } void CountField::GenGetter(std::ostream& s, Size start_offset, Size end_offset) const { s << "protected:"; @@ -37,9 +36,7 @@ bool CountField::GenBuilderParameter(std::ostream&) const { return false; } -bool CountField::HasParameterValidator() const { - return false; -} +bool CountField::HasParameterValidator() const { return false; } void CountField::GenParameterValidator(std::ostream&) const { // There is no builder parameter for a size field @@ -54,6 +51,4 @@ void CountField::GenValidator(std::ostream&) const { // Do nothing since the fixed count fields will be handled specially. } -std::string CountField::GetSizedFieldName() const { - return sized_field_name_; -} +std::string CountField::GetSizedFieldName() const { return sized_field_name_; } diff --git a/system/gd/packet/parser/fields/count_field.h b/system/gd/packet/parser/fields/count_field.h index c9cb6739fc5..d5e3927e958 100644 --- a/system/gd/packet/parser/fields/count_field.h +++ b/system/gd/packet/parser/fields/count_field.h @@ -21,7 +21,7 @@ #include "parse_location.h" class CountField : public ScalarField { - public: +public: CountField(std::string name, int size, ParseLocation loc); static const std::string kFieldType; @@ -44,7 +44,7 @@ class CountField : public ScalarField { virtual std::string GetSizedFieldName() const; - private: +private: int size_; std::string sized_field_name_; }; diff --git a/system/gd/packet/parser/fields/custom_field.cc b/system/gd/packet/parser/fields/custom_field.cc index 6c5900df13b..c01d5a15eb1 100644 --- a/system/gd/packet/parser/fields/custom_field.cc +++ b/system/gd/packet/parser/fields/custom_field.cc @@ -15,6 +15,7 @@ */ #include "fields/custom_field.h" + #include "util.h" const std::string CustomField::kFieldType = "CustomField"; @@ -22,22 +23,16 @@ const std::string CustomField::kFieldType = "CustomField"; CustomField::CustomField(std::string name, std::string type_name, ParseLocation loc) : PacketField(name, loc), type_name_(type_name) {} -const std::string& CustomField::GetFieldType() const { - return CustomField::kFieldType; -} +const std::string& CustomField::GetFieldType() const { return CustomField::kFieldType; } -Size CustomField::GetSize() const { - return Size(); -} +Size CustomField::GetSize() const { return Size(); } Size CustomField::GetBuilderSize() const { std::string ret = "(" + GetName() + "_.size() * 8) "; return ret; } -std::string CustomField::GetDataType() const { - return type_name_; -} +std::string CustomField::GetDataType() const { return type_name_; } void CustomField::GenExtractor(std::ostream& s, int, bool) const { s << "auto optional_it = "; @@ -72,21 +67,15 @@ void CustomField::GenGetter(std::ostream& s, Size start_offset, Size end_offset) s << "}\n"; } -std::string CustomField::GetBuilderParameterType() const { - return GetDataType(); -} +std::string CustomField::GetBuilderParameterType() const { return GetDataType(); } -bool CustomField::HasParameterValidator() const { - return false; -} +bool CustomField::HasParameterValidator() const { return false; } void CustomField::GenParameterValidator(std::ostream&) const { // Do nothing. } -void CustomField::GenInserter(std::ostream& s) const { - s << GetName() << "_.Serialize(i);"; -} +void CustomField::GenInserter(std::ostream& s) const { s << GetName() << "_.Serialize(i);"; } void CustomField::GenValidator(std::ostream&) const { // Do nothing. diff --git a/system/gd/packet/parser/fields/custom_field.h b/system/gd/packet/parser/fields/custom_field.h index 8e4ae8a3ff4..9a10479e69d 100644 --- a/system/gd/packet/parser/fields/custom_field.h +++ b/system/gd/packet/parser/fields/custom_field.h @@ -20,7 +20,7 @@ #include "parse_location.h" class CustomField : public PacketField { - public: +public: CustomField(std::string name, std::string type_name, ParseLocation loc); static const std::string kFieldType; @@ -53,6 +53,6 @@ class CustomField : public PacketField { virtual void GenBuilderParameterFromView(std::ostream& s) const override; - private: +private: std::string type_name_; }; diff --git a/system/gd/packet/parser/fields/custom_field_fixed_size.cc b/system/gd/packet/parser/fields/custom_field_fixed_size.cc index c296438c0d6..84cffa79861 100644 --- a/system/gd/packet/parser/fields/custom_field_fixed_size.cc +++ b/system/gd/packet/parser/fields/custom_field_fixed_size.cc @@ -20,24 +20,25 @@ const std::string CustomFieldFixedSize::kFieldType = "CustomField"; -CustomFieldFixedSize::CustomFieldFixedSize(std::string name, std::string type_name, int size, ParseLocation loc) +CustomFieldFixedSize::CustomFieldFixedSize(std::string name, std::string type_name, int size, + ParseLocation loc) : ScalarField(name, size, loc), type_name_(type_name) {} const std::string& CustomFieldFixedSize::GetFieldType() const { return CustomFieldFixedSize::kFieldType; } -std::string CustomFieldFixedSize::GetDataType() const { - return type_name_; -} +std::string CustomFieldFixedSize::GetDataType() const { return type_name_; } -int CustomFieldFixedSize::GenBounds(std::ostream& s, Size start_offset, Size end_offset, Size size) const { +int CustomFieldFixedSize::GenBounds(std::ostream& s, Size start_offset, Size end_offset, + Size size) const { if (!start_offset.empty()) { // Default to start if available. s << "auto " << GetName() << "_it = to_bound + (" << start_offset << ") / 8;"; } else if (!end_offset.empty()) { Size byte_offset = size + end_offset; - s << "auto " << GetName() << "_it = to_bound (+ to_bound.NumBytesRemaining() - (" << byte_offset << ") / 8);"; + s << "auto " << GetName() << "_it = to_bound (+ to_bound.NumBytesRemaining() - (" << byte_offset + << ") / 8);"; } else { ERROR(this) << "Ambiguous offset for field."; } @@ -48,9 +49,7 @@ void CustomFieldFixedSize::GenExtractor(std::ostream& s, int, bool) const { s << "*" << GetName() << "_ptr = " << GetName() << "_it.extract<" << GetDataType() << ">();"; } -bool CustomFieldFixedSize::HasParameterValidator() const { - return false; -} +bool CustomFieldFixedSize::HasParameterValidator() const { return false; } void CustomFieldFixedSize::GenParameterValidator(std::ostream&) const { // Do nothing. diff --git a/system/gd/packet/parser/fields/custom_field_fixed_size.h b/system/gd/packet/parser/fields/custom_field_fixed_size.h index c53f0b0aede..a5f728286ec 100644 --- a/system/gd/packet/parser/fields/custom_field_fixed_size.h +++ b/system/gd/packet/parser/fields/custom_field_fixed_size.h @@ -20,7 +20,7 @@ #include "parse_location.h" class CustomFieldFixedSize : public ScalarField { - public: +public: CustomFieldFixedSize(std::string name, std::string type_name, int size, ParseLocation loc); static const std::string kFieldType; @@ -29,7 +29,8 @@ class CustomFieldFixedSize : public ScalarField { virtual std::string GetDataType() const override; - virtual int GenBounds(std::ostream& s, Size start_offset, Size end_offset, Size size) const override; + virtual int GenBounds(std::ostream& s, Size start_offset, Size end_offset, + Size size) const override; virtual void GenExtractor(std::ostream& s, int num_leading_bits, bool for_struct) const override; diff --git a/system/gd/packet/parser/fields/enum_field.cc b/system/gd/packet/parser/fields/enum_field.cc index 8fe56c2ff17..675232d5689 100644 --- a/system/gd/packet/parser/fields/enum_field.cc +++ b/system/gd/packet/parser/fields/enum_field.cc @@ -23,21 +23,13 @@ const std::string EnumField::kFieldType = "EnumField"; EnumField::EnumField(std::string name, EnumDef enum_def, std::string value, ParseLocation loc) : ScalarField(name, enum_def.size_, loc), enum_def_(enum_def), value_(value) {} -const std::string& EnumField::GetFieldType() const { - return EnumField::kFieldType; -} +const std::string& EnumField::GetFieldType() const { return EnumField::kFieldType; } -EnumDef EnumField::GetEnumDef() { - return enum_def_; -} +EnumDef EnumField::GetEnumDef() { return enum_def_; } -std::string EnumField::GetDataType() const { - return enum_def_.name_; -} +std::string EnumField::GetDataType() const { return enum_def_.name_; } -bool EnumField::HasParameterValidator() const { - return false; -} +bool EnumField::HasParameterValidator() const { return false; } void EnumField::GenParameterValidator(std::ostream&) const { // Validated at compile time. diff --git a/system/gd/packet/parser/fields/enum_field.h b/system/gd/packet/parser/fields/enum_field.h index f413553a912..ea1a48f3ee3 100644 --- a/system/gd/packet/parser/fields/enum_field.h +++ b/system/gd/packet/parser/fields/enum_field.h @@ -22,7 +22,7 @@ #include "parse_location.h" class EnumField : public ScalarField { - public: +public: EnumField(std::string name, EnumDef enum_def, std::string value, ParseLocation loc); EnumDef GetEnumDef(); @@ -43,7 +43,7 @@ class EnumField : public ScalarField { virtual void GenStringRepresentation(std::ostream& s, std::string accessor) const override; - private: +private: EnumDef enum_def_; std::string value_; }; diff --git a/system/gd/packet/parser/fields/fixed_enum_field.cc b/system/gd/packet/parser/fields/fixed_enum_field.cc index 0cc35c0dff6..642c46fd4ad 100644 --- a/system/gd/packet/parser/fields/fixed_enum_field.cc +++ b/system/gd/packet/parser/fields/fixed_enum_field.cc @@ -15,6 +15,7 @@ */ #include "fields/fixed_enum_field.h" + #include "util.h" const std::string FixedEnumField::kFieldType = "FixedEnumField"; @@ -22,14 +23,8 @@ const std::string FixedEnumField::kFieldType = "FixedEnumField"; FixedEnumField::FixedEnumField(EnumDef* enum_def, std::string value, ParseLocation loc) : FixedField("fixed_enum", enum_def->size_, loc), enum_(enum_def), value_(value) {} -const std::string& FixedEnumField::GetFieldType() const { - return FixedEnumField::kFieldType; -} +const std::string& FixedEnumField::GetFieldType() const { return FixedEnumField::kFieldType; } -std::string FixedEnumField::GetDataType() const { - return enum_->name_; -} +std::string FixedEnumField::GetDataType() const { return enum_->name_; } -void FixedEnumField::GenValue(std::ostream& s) const { - s << enum_->name_ << "::" << value_; -} +void FixedEnumField::GenValue(std::ostream& s) const { s << enum_->name_ << "::" << value_; } diff --git a/system/gd/packet/parser/fields/fixed_enum_field.h b/system/gd/packet/parser/fields/fixed_enum_field.h index 2c6c3f3b8ff..4ea33db12ba 100644 --- a/system/gd/packet/parser/fields/fixed_enum_field.h +++ b/system/gd/packet/parser/fields/fixed_enum_field.h @@ -24,7 +24,7 @@ #include "parse_location.h" class FixedEnumField : public FixedField { - public: +public: FixedEnumField(EnumDef* enum_def, std::string value, ParseLocation loc); static const std::string kFieldType; @@ -35,7 +35,7 @@ class FixedEnumField : public FixedField { static const std::string field_type; - private: +private: void GenValue(std::ostream& s) const; EnumDef* enum_; diff --git a/system/gd/packet/parser/fields/fixed_field.cc b/system/gd/packet/parser/fields/fixed_field.cc index a30765390ab..a5dcd372faa 100644 --- a/system/gd/packet/parser/fields/fixed_field.cc +++ b/system/gd/packet/parser/fields/fixed_field.cc @@ -15,6 +15,7 @@ */ #include "fields/fixed_field.h" + #include "util.h" int FixedField::unique_id_ = 0; @@ -28,18 +29,14 @@ void FixedField::GenGetter(std::ostream& s, Size start_offset, Size end_offset) s << "public:\n"; } -std::string FixedField::GetBuilderParameterType() const { - return ""; -} +std::string FixedField::GetBuilderParameterType() const { return ""; } bool FixedField::GenBuilderParameter(std::ostream&) const { // No parameter needed for a fixed field. return false; } -bool FixedField::HasParameterValidator() const { - return false; -} +bool FixedField::HasParameterValidator() const { return false; } void FixedField::GenParameterValidator(std::ostream&) const { // No parameter validator needed for a fixed field. diff --git a/system/gd/packet/parser/fields/fixed_field.h b/system/gd/packet/parser/fields/fixed_field.h index c2b2b7bd7f2..da67daf4e60 100644 --- a/system/gd/packet/parser/fields/fixed_field.h +++ b/system/gd/packet/parser/fields/fixed_field.h @@ -24,7 +24,7 @@ #include "parse_location.h" class FixedField : public ScalarField { - public: +public: FixedField(std::string name, int size, ParseLocation loc); static const std::string kFieldType; @@ -45,7 +45,7 @@ class FixedField : public ScalarField { virtual void GenValidator(std::ostream& s) const override; - private: +private: virtual void GenValue(std::ostream& s) const = 0; static int unique_id_; diff --git a/system/gd/packet/parser/fields/fixed_scalar_field.cc b/system/gd/packet/parser/fields/fixed_scalar_field.cc index a0a83004bae..4f66ddb4b70 100644 --- a/system/gd/packet/parser/fields/fixed_scalar_field.cc +++ b/system/gd/packet/parser/fields/fixed_scalar_field.cc @@ -15,6 +15,7 @@ */ #include "fields/fixed_scalar_field.h" + #include "util.h" const std::string FixedScalarField::kFieldType = "FixedScalarField"; @@ -22,18 +23,10 @@ const std::string FixedScalarField::kFieldType = "FixedScalarField"; FixedScalarField::FixedScalarField(int size, int64_t value, ParseLocation loc) : FixedField("fixed_scalar", size, loc), value_(value) {} -const std::string& FixedScalarField::GetFieldType() const { - return FixedScalarField::kFieldType; -} +const std::string& FixedScalarField::GetFieldType() const { return FixedScalarField::kFieldType; } -std::string FixedScalarField::GetDataType() const { - return util::GetTypeForSize(GetSize().bits()); -} +std::string FixedScalarField::GetDataType() const { return util::GetTypeForSize(GetSize().bits()); } -void FixedScalarField::GenValue(std::ostream& s) const { - s << value_; -} +void FixedScalarField::GenValue(std::ostream& s) const { s << value_; } -void FixedScalarField::GenStringRepresentation(std::ostream& s, std::string) const { - s << value_; -} +void FixedScalarField::GenStringRepresentation(std::ostream& s, std::string) const { s << value_; } diff --git a/system/gd/packet/parser/fields/fixed_scalar_field.h b/system/gd/packet/parser/fields/fixed_scalar_field.h index 44a0fa58c30..fc6603ad378 100644 --- a/system/gd/packet/parser/fields/fixed_scalar_field.h +++ b/system/gd/packet/parser/fields/fixed_scalar_field.h @@ -24,7 +24,7 @@ #include "parse_location.h" class FixedScalarField : public FixedField { - public: +public: FixedScalarField(int size, int64_t value, ParseLocation loc); static const std::string kFieldType; @@ -39,7 +39,6 @@ class FixedScalarField : public FixedField { static const std::string field_type; - private: - +private: const int64_t value_; }; diff --git a/system/gd/packet/parser/fields/group_field.cc b/system/gd/packet/parser/fields/group_field.cc index 6c9ade976ac..1440d23293f 100644 --- a/system/gd/packet/parser/fields/group_field.cc +++ b/system/gd/packet/parser/fields/group_field.cc @@ -19,9 +19,7 @@ GroupField::GroupField(ParseLocation loc, std::list* fields) : PacketField("Groups have no name", loc), fields_(fields) {} -GroupField::~GroupField() { - delete fields_; -} +GroupField::~GroupField() { delete fields_; } const std::string GroupField::kFieldType = "GroupField"; @@ -30,9 +28,7 @@ std::string GroupField::GetName() const { return ""; } -const std::string& GroupField::GetFieldType() const { - return GroupField::kFieldType; -} +const std::string& GroupField::GetFieldType() const { return GroupField::kFieldType; } Size GroupField::GetSize() const { ERROR(this) << "GetSize should never be called."; @@ -67,9 +63,7 @@ bool GroupField::HasParameterValidator() const { return false; } -void GroupField::GenParameterValidator(std::ostream&) const { - ERROR(this) << "Not implemented"; -} +void GroupField::GenParameterValidator(std::ostream&) const { ERROR(this) << "Not implemented"; } void GroupField::GenInserter(std::ostream&) const { ERROR(this) << "GenInserter should never be called."; @@ -79,6 +73,4 @@ void GroupField::GenValidator(std::ostream&) const { ERROR(this) << "GenValidator should never be called."; } -const std::list* GroupField::GetFields() const { - return fields_; -} +const std::list* GroupField::GetFields() const { return fields_; } diff --git a/system/gd/packet/parser/fields/group_field.h b/system/gd/packet/parser/fields/group_field.h index 57e01651de8..d1f0bee5c55 100644 --- a/system/gd/packet/parser/fields/group_field.h +++ b/system/gd/packet/parser/fields/group_field.h @@ -22,7 +22,7 @@ #include "parse_location.h" class GroupField : public PacketField { - public: +public: GroupField(ParseLocation loc, std::list* fields); ~GroupField(); @@ -55,6 +55,6 @@ class GroupField : public PacketField { const std::list* GetFields() const; - private: +private: std::list* fields_; }; diff --git a/system/gd/packet/parser/fields/packet_field.cc b/system/gd/packet/parser/fields/packet_field.cc index b51999fdf6b..04239ade660 100644 --- a/system/gd/packet/parser/fields/packet_field.cc +++ b/system/gd/packet/parser/fields/packet_field.cc @@ -24,31 +24,25 @@ std::string PacketField::GetDebugName() const { return "Field{Type:" + GetFieldType() + ", Name:" + GetName() + "}"; } -ParseLocation PacketField::GetLocation() const { - return loc_; -} +ParseLocation PacketField::GetLocation() const { return loc_; } -std::string PacketField::GetName() const { - return name_; -} +std::string PacketField::GetName() const { return name_; } -Size PacketField::GetBuilderSize() const { - return GetSize(); -} +Size PacketField::GetBuilderSize() const { return GetSize(); } -Size PacketField::GetStructSize() const { - return GetSize(); -} +Size PacketField::GetStructSize() const { return GetSize(); } int PacketField::GenBounds(std::ostream& s, Size start_offset, Size end_offset, Size size) const { // In order to find field_begin and field_end, we must have two of the three Sizes. if ((start_offset.empty() && size.empty()) || (start_offset.empty() && end_offset.empty()) || (end_offset.empty() && size.empty())) { - ERROR(this) << "GenBounds called without enough information. " << start_offset << end_offset << size; + ERROR(this) << "GenBounds called without enough information. " << start_offset << end_offset + << size; } if (start_offset.bits() % 8 != 0 || end_offset.bits() % 8 != 0) { - ERROR(this) << "Can not find the bounds of a field at a non byte-aligned offset." << start_offset << end_offset; + ERROR(this) << "Can not find the bounds of a field at a non byte-aligned offset." + << start_offset << end_offset; } if (!start_offset.empty()) { @@ -81,25 +75,17 @@ bool PacketField::GenBuilderParameter(std::ostream& s) const { return true; } -bool PacketField::BuilderParameterMustBeMoved() const { - return false; -} +bool PacketField::BuilderParameterMustBeMoved() const { return false; } -bool PacketField::GenBuilderMember(std::ostream& s) const { - return GenBuilderParameter(s); -} +bool PacketField::GenBuilderMember(std::ostream& s) const { return GenBuilderParameter(s); } void PacketField::GenBuilderParameterFromView(std::ostream& s) const { s << "view.Get" << util::UnderscoreToCamelCase(GetName()) << "()"; } -bool PacketField::IsContainerField() const { - return false; -} +bool PacketField::IsContainerField() const { return false; } -const PacketField* PacketField::GetElementField() const { - return nullptr; -} +const PacketField* PacketField::GetElementField() const { return nullptr; } void PacketField::GenStringRepresentation(std::ostream& s, std::string accessor) const { s << "\"REPRESENTATION_UNIMPLEMENTED " << GetFieldType() << " " << accessor << "\""; diff --git a/system/gd/packet/parser/fields/packet_field.h b/system/gd/packet/parser/fields/packet_field.h index 44be3b14c95..4e25c9017e8 100644 --- a/system/gd/packet/parser/fields/packet_field.h +++ b/system/gd/packet/parser/fields/packet_field.h @@ -25,7 +25,7 @@ // The base field that every packet needs to inherit from. class PacketField : public Loggable { - public: +public: virtual ~PacketField() = default; PacketField(std::string name, ParseLocation loc); @@ -50,7 +50,8 @@ class PacketField : public Loggable { // Given an iterator {name}_it, extract the type. virtual void GenExtractor(std::ostream& s, int num_leading_bits, bool for_struct) const = 0; - // Calculate field_begin and field_end using the given offsets and size, return the number of leading bits + // Calculate field_begin and field_end using the given offsets and size, return the number of + // leading bits virtual int GenBounds(std::ostream& s, Size start_offset, Size end_offset, Size size) const; // Get the name of the getter function, return empty string if there is a getter function @@ -62,7 +63,8 @@ class PacketField : public Loggable { // calculate the offset. virtual void GenGetter(std::ostream& s, Size start_offset, Size end_offset) const = 0; - // Get the type of parameter used in Create(), return empty string if a parameter type was NOT generated + // Get the type of parameter used in Create(), return empty string if a parameter type was NOT + // generated virtual std::string GetBuilderParameterType() const = 0; // Generate the parameter for Create(), return true if a parameter was added. @@ -106,7 +108,8 @@ class PacketField : public Loggable { // Get field of nested elements if this is a container field, nullptr if none virtual const PacketField* GetElementField() const; - // Return string representation of this field, that can be displayed for debugging or logging purposes + // Return string representation of this field, that can be displayed for debugging or logging + // purposes virtual void GenStringRepresentation(std::ostream& s, std::string accessor) const; std::string GetDebugName() const override; @@ -115,11 +118,9 @@ class PacketField : public Loggable { virtual std::string GetName() const; - virtual bool GetterIsByRef() const { - return true; - } + virtual bool GetterIsByRef() const { return true; } - private: +private: ParseLocation loc_; std::string name_; }; diff --git a/system/gd/packet/parser/fields/padding_field.cc b/system/gd/packet/parser/fields/padding_field.cc index 5f438f88e9c..d38148eb920 100644 --- a/system/gd/packet/parser/fields/padding_field.cc +++ b/system/gd/packet/parser/fields/padding_field.cc @@ -15,6 +15,7 @@ */ #include "fields/padding_field.h" + #include "util.h" const std::string PaddingField::kFieldType = "PaddingField"; @@ -22,37 +23,23 @@ const std::string PaddingField::kFieldType = "PaddingField"; PaddingField::PaddingField(int size, ParseLocation loc) : PacketField("padding_" + std::to_string(size * 8), loc), size_(size * 8) {} -const std::string& PaddingField::GetFieldType() const { - return PaddingField::kFieldType; -} +const std::string& PaddingField::GetFieldType() const { return PaddingField::kFieldType; } -Size PaddingField::GetSize() const { - return size_; -} +Size PaddingField::GetSize() const { return size_; } -Size PaddingField::GetBuilderSize() const { - return 0; -} +Size PaddingField::GetBuilderSize() const { return 0; } -std::string PaddingField::GetDataType() const { - return "There's no type for Padding fields"; -} +std::string PaddingField::GetDataType() const { return "There's no type for Padding fields"; } void PaddingField::GenExtractor(std::ostream&, int, bool) const {} -std::string PaddingField::GetGetterFunctionName() const { - return ""; -} +std::string PaddingField::GetGetterFunctionName() const { return ""; } void PaddingField::GenGetter(std::ostream&, Size, Size) const {} -std::string PaddingField::GetBuilderParameterType() const { - return ""; -} +std::string PaddingField::GetBuilderParameterType() const { return ""; } -bool PaddingField::HasParameterValidator() const { - return false; -} +bool PaddingField::HasParameterValidator() const { return false; } void PaddingField::GenParameterValidator(std::ostream&) const {} diff --git a/system/gd/packet/parser/fields/padding_field.h b/system/gd/packet/parser/fields/padding_field.h index bb99d42a0bd..b9c5449a045 100644 --- a/system/gd/packet/parser/fields/padding_field.h +++ b/system/gd/packet/parser/fields/padding_field.h @@ -20,7 +20,7 @@ #include "parse_location.h" class PaddingField : public PacketField { - public: +public: PaddingField(int size, ParseLocation loc); static const std::string kFieldType; @@ -51,6 +51,6 @@ class PaddingField : public PacketField { virtual void GenValidator(std::ostream&) const override; - private: +private: Size size_; }; diff --git a/system/gd/packet/parser/fields/payload_field.cc b/system/gd/packet/parser/fields/payload_field.cc index 6779dade3c5..85d17b81b74 100644 --- a/system/gd/packet/parser/fields/payload_field.cc +++ b/system/gd/packet/parser/fields/payload_field.cc @@ -15,6 +15,7 @@ */ #include "fields/payload_field.h" + #include "util.h" const std::string PayloadField::kFieldType = "PayloadField"; @@ -24,15 +25,14 @@ PayloadField::PayloadField(std::string modifier, ParseLocation loc) void PayloadField::SetSizeField(const SizeField* size_field) { if (size_field_ != nullptr) { - ERROR(this, size_field_, size_field) << "The size field for the payload has already been assigned."; + ERROR(this, size_field_, size_field) + << "The size field for the payload has already been assigned."; } size_field_ = size_field; } -const std::string& PayloadField::GetFieldType() const { - return PayloadField::kFieldType; -} +const std::string& PayloadField::GetFieldType() const { return PayloadField::kFieldType; } Size PayloadField::GetSize() const { if (size_field_ == nullptr) { @@ -42,7 +42,8 @@ Size PayloadField::GetSize() const { return Size(); } - std::string dynamic_size = "(Get" + util::UnderscoreToCamelCase(size_field_->GetName()) + "() * 8)"; + std::string dynamic_size = + "(Get" + util::UnderscoreToCamelCase(size_field_->GetName()) + "() * 8)"; if (!size_modifier_.empty()) { dynamic_size += "- (" + size_modifier_.substr(1) + " * 8)"; } @@ -50,17 +51,13 @@ Size PayloadField::GetSize() const { return dynamic_size; } -std::string PayloadField::GetDataType() const { - return "PacketView"; -} +std::string PayloadField::GetDataType() const { return "PacketView"; } void PayloadField::GenExtractor(std::ostream&, int, bool) const { ERROR(this) << __func__ << " should never be called. "; } -std::string PayloadField::GetGetterFunctionName() const { - return "GetPayload"; -} +std::string PayloadField::GetGetterFunctionName() const { return "GetPayload"; } void PayloadField::GenGetter(std::ostream& s, Size start_offset, Size end_offset) const { s << "PacketView " << GetGetterFunctionName() << "() const {"; @@ -76,17 +73,14 @@ std::string PayloadField::GetBuilderParameterType() const { return "std::unique_ptr"; } -bool PayloadField::BuilderParameterMustBeMoved() const { - return true; -} +bool PayloadField::BuilderParameterMustBeMoved() const { return true; } void PayloadField::GenBuilderParameterFromView(std::ostream& s) const { - s << "std::make_unique(std::vector(view.GetPayload().begin(), view.GetPayload().end()))"; + s << "std::make_unique(std::vector(view.GetPayload().begin(), " + "view.GetPayload().end()))"; } -bool PayloadField::HasParameterValidator() const { - return false; -} +bool PayloadField::HasParameterValidator() const { return false; } void PayloadField::GenParameterValidator(std::ostream&) const { // There is no validation needed for a payload diff --git a/system/gd/packet/parser/fields/payload_field.h b/system/gd/packet/parser/fields/payload_field.h index b4ead5bb1fd..6ef419d863c 100644 --- a/system/gd/packet/parser/fields/payload_field.h +++ b/system/gd/packet/parser/fields/payload_field.h @@ -21,7 +21,7 @@ #include "parse_location.h" class PayloadField : public PacketField { - public: +public: PayloadField(std::string modifier, ParseLocation loc); static const std::string kFieldType; diff --git a/system/gd/packet/parser/fields/reserved_field.cc b/system/gd/packet/parser/fields/reserved_field.cc index 0acf7b720c9..72b7f25601c 100644 --- a/system/gd/packet/parser/fields/reserved_field.cc +++ b/system/gd/packet/parser/fields/reserved_field.cc @@ -15,6 +15,7 @@ */ #include "fields/reserved_field.h" + #include "util.h" int ReservedField::unique_id_ = 0; @@ -24,23 +25,15 @@ const std::string ReservedField::kFieldType = "ReservedField"; ReservedField::ReservedField(int size, ParseLocation loc) : PacketField("ReservedScalar" + std::to_string(unique_id_++), loc), size_(size) {} -const std::string& ReservedField::GetFieldType() const { - return ReservedField::kFieldType; -} +const std::string& ReservedField::GetFieldType() const { return ReservedField::kFieldType; } -Size ReservedField::GetSize() const { - return size_; -} +Size ReservedField::GetSize() const { return size_; } -std::string ReservedField::GetDataType() const { - return util::GetTypeForSize(size_); -} +std::string ReservedField::GetDataType() const { return util::GetTypeForSize(size_); } void ReservedField::GenExtractor(std::ostream&, int, bool) const {} -std::string ReservedField::GetGetterFunctionName() const { - return ""; -} +std::string ReservedField::GetGetterFunctionName() const { return ""; } void ReservedField::GenGetter(std::ostream&, Size, Size) const { // There is no Getter for a reserved field @@ -51,17 +44,15 @@ std::string ReservedField::GetBuilderParameterType() const { return ""; } -bool ReservedField::HasParameterValidator() const { - return false; -} +bool ReservedField::HasParameterValidator() const { return false; } void ReservedField::GenParameterValidator(std::ostream&) const { // There is no builder parameter for a reserved field } void ReservedField::GenInserter(std::ostream& s) const { - s << "insert(static_cast<" << util::GetTypeForSize(GetSize().bits()) << ">(0) /* Reserved */, i, " << GetSize().bits() - << " );\n"; + s << "insert(static_cast<" << util::GetTypeForSize(GetSize().bits()) << ">(0) /* Reserved */, i, " + << GetSize().bits() << " );\n"; } void ReservedField::GenValidator(std::ostream&) const { diff --git a/system/gd/packet/parser/fields/reserved_field.h b/system/gd/packet/parser/fields/reserved_field.h index 7d363528a35..258ce234aff 100644 --- a/system/gd/packet/parser/fields/reserved_field.h +++ b/system/gd/packet/parser/fields/reserved_field.h @@ -20,7 +20,7 @@ #include "parse_location.h" class ReservedField : public PacketField { - public: +public: ReservedField(int size, ParseLocation loc); static const std::string kFieldType; @@ -47,7 +47,7 @@ class ReservedField : public PacketField { virtual void GenValidator(std::ostream&) const override; - private: +private: std::string name_; int size_; static int unique_id_; diff --git a/system/gd/packet/parser/fields/scalar_field.cc b/system/gd/packet/parser/fields/scalar_field.cc index 725fd3be198..f916329cc1a 100644 --- a/system/gd/packet/parser/fields/scalar_field.cc +++ b/system/gd/packet/parser/fields/scalar_field.cc @@ -22,23 +22,18 @@ const std::string ScalarField::kFieldType = "ScalarField"; -ScalarField::ScalarField(std::string name, int size, ParseLocation loc) : PacketField(name, loc), size_(size) { +ScalarField::ScalarField(std::string name, int size, ParseLocation loc) + : PacketField(name, loc), size_(size) { if (size_ > 64 || size_ < 0) { ERROR(this) << "Not implemented for size_ = " << size_; } } -const std::string& ScalarField::GetFieldType() const { - return ScalarField::kFieldType; -} +const std::string& ScalarField::GetFieldType() const { return ScalarField::kFieldType; } -Size ScalarField::GetSize() const { - return size_; -} +Size ScalarField::GetSize() const { return size_; } -std::string ScalarField::GetDataType() const { - return util::GetTypeForSize(size_); -} +std::string ScalarField::GetDataType() const { return util::GetTypeForSize(size_); } int GetShiftBits(int i) { int bits_past_byte_boundary = i % 8; @@ -59,7 +54,8 @@ int ScalarField::GenBounds(std::ostream& s, Size start_offset, Size end_offset, } else if (!end_offset.empty()) { num_leading_bits = GetShiftBits(end_offset.bits() + size.bits()); Size byte_offset = Size(num_leading_bits + size.bits()) + end_offset; - s << "auto " << GetName() << "_it = to_bound + (to_bound.NumBytesRemaining() - (" << byte_offset << ") / 8);"; + s << "auto " << GetName() << "_it = to_bound + (to_bound.NumBytesRemaining() - (" << byte_offset + << ") / 8);"; } else { ERROR(this) << "Ambiguous offset for field."; } @@ -108,9 +104,7 @@ void ScalarField::GenGetter(std::ostream& s, Size start_offset, Size end_offset) s << "}"; } -std::string ScalarField::GetBuilderParameterType() const { - return GetDataType(); -} +std::string ScalarField::GetBuilderParameterType() const { return GetDataType(); } bool ScalarField::HasParameterValidator() const { return util::RoundSizeUp(GetSize().bits()) != GetSize().bits(); diff --git a/system/gd/packet/parser/fields/scalar_field.h b/system/gd/packet/parser/fields/scalar_field.h index a55417b9801..a63d46dd21d 100644 --- a/system/gd/packet/parser/fields/scalar_field.h +++ b/system/gd/packet/parser/fields/scalar_field.h @@ -20,7 +20,7 @@ #include "parse_location.h" class ScalarField : public PacketField { - public: +public: ScalarField(std::string name, int size, ParseLocation loc); static const std::string kFieldType; @@ -31,7 +31,8 @@ class ScalarField : public PacketField { virtual std::string GetDataType() const override; - virtual int GenBounds(std::ostream& s, Size start_offset, Size end_offset, Size size) const override; + virtual int GenBounds(std::ostream& s, Size start_offset, Size end_offset, + Size size) const override; virtual void GenExtractor(std::ostream& s, int num_leading_bits, bool for_struct) const override; @@ -51,10 +52,8 @@ class ScalarField : public PacketField { virtual void GenStringRepresentation(std::ostream& s, std::string accessor) const override; - virtual bool GetterIsByRef() const override { - return false; - } + virtual bool GetterIsByRef() const override { return false; } - private: +private: const int size_; }; diff --git a/system/gd/packet/parser/fields/size_field.cc b/system/gd/packet/parser/fields/size_field.cc index ce2c899d9e6..6c0fbb53604 100644 --- a/system/gd/packet/parser/fields/size_field.cc +++ b/system/gd/packet/parser/fields/size_field.cc @@ -15,6 +15,7 @@ */ #include "fields/size_field.h" + #include "util.h" const std::string SizeField::kFieldType = "SizeField"; @@ -22,9 +23,7 @@ const std::string SizeField::kFieldType = "SizeField"; SizeField::SizeField(std::string name, int size, ParseLocation loc) : ScalarField(name + "_size", size, loc), sized_field_name_(name) {} -const std::string& SizeField::GetFieldType() const { - return SizeField::kFieldType; -} +const std::string& SizeField::GetFieldType() const { return SizeField::kFieldType; } void SizeField::GenGetter(std::ostream& s, Size start_offset, Size end_offset) const { s << "protected:"; @@ -32,18 +31,14 @@ void SizeField::GenGetter(std::ostream& s, Size start_offset, Size end_offset) c s << "public:\n"; } -std::string SizeField::GetBuilderParameterType() const { - return ""; -} +std::string SizeField::GetBuilderParameterType() const { return ""; } bool SizeField::GenBuilderParameter(std::ostream&) const { // There is no builder parameter for a size field return false; } -bool SizeField::HasParameterValidator() const { - return false; -} +bool SizeField::HasParameterValidator() const { return false; } void SizeField::GenParameterValidator(std::ostream&) const { // There is no builder parameter for a size field @@ -58,9 +53,7 @@ void SizeField::GenValidator(std::ostream&) const { // Do nothing since the fixed size fields will be handled specially. } -std::string SizeField::GetSizedFieldName() const { - return sized_field_name_; -} +std::string SizeField::GetSizedFieldName() const { return sized_field_name_; } void SizeField::GenStringRepresentation(std::ostream& s, std::string accessor) const { s << accessor; diff --git a/system/gd/packet/parser/fields/size_field.h b/system/gd/packet/parser/fields/size_field.h index 2d40c42ebc6..9258a457529 100644 --- a/system/gd/packet/parser/fields/size_field.h +++ b/system/gd/packet/parser/fields/size_field.h @@ -21,7 +21,7 @@ #include "parse_location.h" class SizeField : public ScalarField { - public: +public: SizeField(std::string name, int size, ParseLocation loc); static const std::string kFieldType; @@ -48,7 +48,7 @@ class SizeField : public ScalarField { virtual void GenStringRepresentation(std::ostream& s, std::string accessor) const override; - private: +private: int size_; std::string sized_field_name_; }; diff --git a/system/gd/packet/parser/fields/struct_field.cc b/system/gd/packet/parser/fields/struct_field.cc index 8013a7890ea..50762045e30 100644 --- a/system/gd/packet/parser/fields/struct_field.cc +++ b/system/gd/packet/parser/fields/struct_field.cc @@ -15,6 +15,7 @@ */ #include "fields/struct_field.h" + #include "util.h" const std::string StructField::kFieldType = "StructField"; @@ -22,22 +23,16 @@ const std::string StructField::kFieldType = "StructField"; StructField::StructField(std::string name, std::string type_name, Size size, ParseLocation loc) : PacketField(name, loc), type_name_(type_name), size_(size) {} -const std::string& StructField::GetFieldType() const { - return StructField::kFieldType; -} +const std::string& StructField::GetFieldType() const { return StructField::kFieldType; } -Size StructField::GetSize() const { - return size_; -} +Size StructField::GetSize() const { return size_; } Size StructField::GetBuilderSize() const { std::string ret = "(" + GetName() + "_.size() * 8)"; return ret; } -std::string StructField::GetDataType() const { - return type_name_; -} +std::string StructField::GetDataType() const { return type_name_; } void StructField::GenExtractor(std::ostream& s, int, bool) const { s << GetName() << "_it = "; @@ -64,21 +59,15 @@ void StructField::GenGetter(std::ostream& s, Size start_offset, Size end_offset) s << "}\n"; } -std::string StructField::GetBuilderParameterType() const { - return GetDataType(); -} +std::string StructField::GetBuilderParameterType() const { return GetDataType(); } -bool StructField::HasParameterValidator() const { - return false; -} +bool StructField::HasParameterValidator() const { return false; } void StructField::GenParameterValidator(std::ostream&) const { // Validated at compile time. } -void StructField::GenInserter(std::ostream& s) const { - s << GetName() << "_.Serialize(i);"; -} +void StructField::GenInserter(std::ostream& s) const { s << GetName() << "_.Serialize(i);"; } void StructField::GenValidator(std::ostream&) const { // Do nothing diff --git a/system/gd/packet/parser/fields/struct_field.h b/system/gd/packet/parser/fields/struct_field.h index 9d1d463b4d4..cb05169c285 100644 --- a/system/gd/packet/parser/fields/struct_field.h +++ b/system/gd/packet/parser/fields/struct_field.h @@ -20,7 +20,7 @@ #include "parse_location.h" class StructField : public PacketField { - public: +public: StructField(std::string name, std::string type_name, Size size, ParseLocation loc); static const std::string kFieldType; @@ -51,9 +51,9 @@ class StructField : public PacketField { virtual void GenStringRepresentation(std::ostream& s, std::string accessor) const override; - private: +private: std::string type_name_; - public: +public: const Size size_{}; }; diff --git a/system/gd/packet/parser/fields/variable_length_struct_field.cc b/system/gd/packet/parser/fields/variable_length_struct_field.cc index 35f2f54cdd2..0ba48e8800f 100644 --- a/system/gd/packet/parser/fields/variable_length_struct_field.cc +++ b/system/gd/packet/parser/fields/variable_length_struct_field.cc @@ -15,20 +15,20 @@ */ #include "fields/variable_length_struct_field.h" + #include "util.h" const std::string VariableLengthStructField::kFieldType = "VariableLengthStructField"; -VariableLengthStructField::VariableLengthStructField(std::string name, std::string type_name, ParseLocation loc) +VariableLengthStructField::VariableLengthStructField(std::string name, std::string type_name, + ParseLocation loc) : PacketField(name, loc), type_name_(type_name) {} const std::string& VariableLengthStructField::GetFieldType() const { return VariableLengthStructField::kFieldType; } -Size VariableLengthStructField::GetSize() const { - return Size(); -} +Size VariableLengthStructField::GetSize() const { return Size(); } Size VariableLengthStructField::GetBuilderSize() const { std::string ret = "(" + GetName() + "_->size() * 8) "; @@ -55,7 +55,8 @@ std::string VariableLengthStructField::GetGetterFunctionName() const { return ss.str(); } -void VariableLengthStructField::GenGetter(std::ostream& s, Size start_offset, Size end_offset) const { +void VariableLengthStructField::GenGetter(std::ostream& s, Size start_offset, + Size end_offset) const { s << GetDataType() << " " << GetGetterFunctionName() << "() const {"; s << "ASSERT(was_validated_);"; s << "size_t end_index = size();"; @@ -67,17 +68,11 @@ void VariableLengthStructField::GenGetter(std::ostream& s, Size start_offset, Si s << "}\n"; } -std::string VariableLengthStructField::GetBuilderParameterType() const { - return GetDataType(); -} +std::string VariableLengthStructField::GetBuilderParameterType() const { return GetDataType(); } -bool VariableLengthStructField::BuilderParameterMustBeMoved() const { - return true; -} +bool VariableLengthStructField::BuilderParameterMustBeMoved() const { return true; } -bool VariableLengthStructField::HasParameterValidator() const { - return false; -} +bool VariableLengthStructField::HasParameterValidator() const { return false; } void VariableLengthStructField::GenParameterValidator(std::ostream&) const { // Validated at compile time. diff --git a/system/gd/packet/parser/fields/variable_length_struct_field.h b/system/gd/packet/parser/fields/variable_length_struct_field.h index 0b1b97f6627..361b7fdca8f 100644 --- a/system/gd/packet/parser/fields/variable_length_struct_field.h +++ b/system/gd/packet/parser/fields/variable_length_struct_field.h @@ -20,7 +20,7 @@ #include "parse_location.h" class VariableLengthStructField : public PacketField { - public: +public: VariableLengthStructField(std::string name, std::string type_name, ParseLocation loc); static const std::string kFieldType; @@ -51,6 +51,6 @@ class VariableLengthStructField : public PacketField { virtual void GenValidator(std::ostream&) const override; - private: +private: std::string type_name_; }; diff --git a/system/gd/packet/parser/fields/vector_field.cc b/system/gd/packet/parser/fields/vector_field.cc index 295f7b612a2..741bcff32fa 100644 --- a/system/gd/packet/parser/fields/vector_field.cc +++ b/system/gd/packet/parser/fields/vector_field.cc @@ -22,27 +22,34 @@ const std::string VectorField::kFieldType = "VectorField"; -VectorField::VectorField(std::string name, int element_size, std::string size_modifier, ParseLocation loc) - : PacketField(name, loc), element_field_(new ScalarField("val", element_size, loc)), element_size_(element_size), +VectorField::VectorField(std::string name, int element_size, std::string size_modifier, + ParseLocation loc) + : PacketField(name, loc), + element_field_(new ScalarField("val", element_size, loc)), + element_size_(element_size), size_modifier_(size_modifier) { - if (element_size > 64 || element_size < 0) + if (element_size > 64 || element_size < 0) { ERROR(this) << __func__ << ": Not implemented for element size = " << element_size; + } if (element_size % 8 != 0) { - ERROR(this) << "Can only have arrays with elements that are byte aligned (" << element_size << ")"; + ERROR(this) << "Can only have arrays with elements that are byte aligned (" << element_size + << ")"; } } -VectorField::VectorField(std::string name, TypeDef* type_def, std::string size_modifier, ParseLocation loc) - : PacketField(name, loc), element_field_(type_def->GetNewField("val", loc)), - element_size_(element_field_->GetSize()), size_modifier_(size_modifier) { +VectorField::VectorField(std::string name, TypeDef* type_def, std::string size_modifier, + ParseLocation loc) + : PacketField(name, loc), + element_field_(type_def->GetNewField("val", loc)), + element_size_(element_field_->GetSize()), + size_modifier_(size_modifier) { if (!element_size_.empty() && element_size_.bits() % 8 != 0) { - ERROR(this) << "Can only have arrays with elements that are byte aligned (" << element_size_ << ")"; + ERROR(this) << "Can only have arrays with elements that are byte aligned (" << element_size_ + << ")"; } } -const std::string& VectorField::GetFieldType() const { - return VectorField::kFieldType; -} +const std::string& VectorField::GetFieldType() const { return VectorField::kFieldType; } Size VectorField::GetSize() const { // If there is no size field, then it is of unknown size. @@ -52,15 +59,18 @@ Size VectorField::GetSize() const { // size_field_ is of type SIZE if (size_field_->GetFieldType() == SizeField::kFieldType) { - std::string ret = "(static_cast(Get" + util::UnderscoreToCamelCase(size_field_->GetName()) + "()) * 8)"; - if (!size_modifier_.empty()) ret += "+ (" + size_modifier_.substr(1) + " * 8)"; + std::string ret = "(static_cast(Get" + + util::UnderscoreToCamelCase(size_field_->GetName()) + "()) * 8)"; + if (!size_modifier_.empty()) { + ret += "+ (" + size_modifier_.substr(1) + " * 8)"; + } return ret; } // size_field_ is of type COUNT and elements have a fixed size if (!element_size_.empty() && !element_size_.has_dynamic()) { - return "(static_cast(Get" + util::UnderscoreToCamelCase(size_field_->GetName()) + "()) * " + - std::to_string(element_size_.bits()) + ")"; + return "(static_cast(Get" + util::UnderscoreToCamelCase(size_field_->GetName()) + + "()) * " + std::to_string(element_size_.bits()) + ")"; } return Size(); @@ -68,7 +78,8 @@ Size VectorField::GetSize() const { Size VectorField::GetBuilderSize() const { if (!element_size_.empty() && !element_size_.has_dynamic()) { - std::string ret = "(static_cast(" + GetName() + "_.size()) * " + std::to_string(element_size_.bits()) + ")"; + std::string ret = "(static_cast(" + GetName() + "_.size()) * " + + std::to_string(element_size_.bits()) + ")"; return ret; } else if (element_field_->BuilderParameterMustBeMoved()) { std::string ret = "[this](){ size_t length = 0; for (const auto& elem : " + GetName() + @@ -89,8 +100,11 @@ Size VectorField::GetStructSize() const { // size_field_ is of type SIZE if (size_field_->GetFieldType() == SizeField::kFieldType) { - std::string ret = "(static_cast(to_fill->" + size_field_->GetName() + "_extracted_) * 8)"; - if (!size_modifier_.empty()) ret += "- (" + size_modifier_.substr(1) + " * 8)"; + std::string ret = + "(static_cast(to_fill->" + size_field_->GetName() + "_extracted_) * 8)"; + if (!size_modifier_.empty()) { + ret += "- (" + size_modifier_.substr(1) + " * 8)"; + } return ret; } @@ -123,7 +137,8 @@ void VectorField::GenExtractor(std::ostream& s, int num_leading_bits, bool for_s s << "(" << element_field_->GetName() << "_count-- > 0) && "; } if (!element_size_.empty()) { - s << element_field_->GetName() << "_it.NumBytesRemaining() >= " << element_size_.bytes() << ") {"; + s << element_field_->GetName() << "_it.NumBytesRemaining() >= " << element_size_.bytes() + << ") {"; } else { s << element_field_->GetName() << "_it.NumBytesRemaining() > 0) {"; } @@ -131,8 +146,8 @@ void VectorField::GenExtractor(std::ostream& s, int num_leading_bits, bool for_s s << element_field_->GetDataType() << " " << element_field_->GetName() << "_ptr;"; } else { s << element_field_->GetDataType() << " " << element_field_->GetName() << "_value;"; - s << element_field_->GetDataType() << "* " << element_field_->GetName() << "_ptr = &" << element_field_->GetName() - << "_value;"; + s << element_field_->GetDataType() << "* " << element_field_->GetName() << "_ptr = &" + << element_field_->GetName() << "_value;"; } element_field_->GenExtractor(s, num_leading_bits, for_struct); s << "if (" << element_field_->GetName() << "_ptr != nullptr) { "; @@ -193,7 +208,8 @@ bool VectorField::HasParameterValidator() const { void VectorField::GenParameterValidator(std::ostream&) const { // No Parameter validator if its dynamically size. - // TODO: Maybe add a validator to ensure that the size isn't larger than what the size field can hold. + // TODO: Maybe add a validator to ensure that the size isn't larger than what the size field can + // hold. return; } @@ -204,11 +220,11 @@ void VectorField::GenInserter(std::ostream& s) const { } void VectorField::GenValidator(std::ostream&) const { - // NOTE: We could check if the element size divides cleanly into the array size, but we decided to forgo that - // in favor of just returning as many elements as possible in a best effort style. + // NOTE: We could check if the element size divides cleanly into the array size, but we decided to + // forgo that in favor of just returning as many elements as possible in a best effort style. // - // Other than that there is nothing that arrays need to be validated on other than length so nothing needs to - // be done here. + // Other than that there is nothing that arrays need to be validated on other than length so + // nothing needs to be done here. } void VectorField::SetSizeField(const SizeField* size_field) { @@ -220,17 +236,11 @@ void VectorField::SetSizeField(const SizeField* size_field) { size_field_ = size_field; } -const std::string& VectorField::GetSizeModifier() const { - return size_modifier_; -} +const std::string& VectorField::GetSizeModifier() const { return size_modifier_; } -bool VectorField::IsContainerField() const { - return true; -} +bool VectorField::IsContainerField() const { return true; } -const PacketField* VectorField::GetElementField() const { - return element_field_; -} +const PacketField* VectorField::GetElementField() const { return element_field_; } void VectorField::GenStringRepresentation(std::ostream& s, std::string accessor) const { s << "\"VECTOR[\";"; diff --git a/system/gd/packet/parser/fields/vector_field.h b/system/gd/packet/parser/fields/vector_field.h index 827f71882e4..8ef11555407 100644 --- a/system/gd/packet/parser/fields/vector_field.h +++ b/system/gd/packet/parser/fields/vector_field.h @@ -22,7 +22,7 @@ #include "type_def.h" class VectorField : public PacketField { - public: +public: VectorField(std::string name, int element_size, std::string size_modifier, ParseLocation loc); VectorField(std::string name, TypeDef* type_def, std::string size_modifier, ParseLocation loc); diff --git a/system/gd/packet/parser/gen_cpp.cc b/system/gd/packet/parser/gen_cpp.cc index 7e089ebb0e3..199624f6e3a 100644 --- a/system/gd/packet/parser/gen_cpp.cc +++ b/system/gd/packet/parser/gen_cpp.cc @@ -15,6 +15,7 @@ */ #include + #include #include #include @@ -28,10 +29,9 @@ #include "declarations.h" #include "struct_parser_generator.h" -void parse_namespace( - const std::string& root_namespace, - const std::filesystem::path& input_file_relative_path, - std::vector* token) { +void parse_namespace(const std::string& root_namespace, + const std::filesystem::path& input_file_relative_path, + std::vector* token) { std::filesystem::path gen_namespace = root_namespace / input_file_relative_path; for (auto it = gen_namespace.begin(); it != gen_namespace.end(); ++it) { token->push_back(it->string()); @@ -50,17 +50,15 @@ void generate_namespace_close(const std::vector& token, std::ostrea } } -bool generate_cpp_headers_one_file( - const Declarations& decls, - bool generate_fuzzing, - bool generate_tests, - const std::filesystem::path& input_file, - const std::filesystem::path& include_dir, - const std::filesystem::path& out_dir, - const std::string& root_namespace) { +bool generate_cpp_headers_one_file(const Declarations& decls, bool generate_fuzzing, + bool generate_tests, const std::filesystem::path& input_file, + const std::filesystem::path& include_dir, + const std::filesystem::path& out_dir, + const std::string& root_namespace) { auto gen_relative_path = input_file.lexically_relative(include_dir).parent_path(); - auto input_filename = input_file.filename().string().substr(0, input_file.filename().string().find(".pdl")); + auto input_filename = + input_file.filename().string().substr(0, input_file.filename().string().find(".pdl")); auto gen_path = out_dir / gen_relative_path; std::filesystem::create_directories(gen_path); @@ -77,7 +75,7 @@ bool generate_cpp_headers_one_file( } out_file << - R"( + R"( #pragma once #include @@ -117,7 +115,7 @@ bool generate_cpp_headers_one_file( if (generate_fuzzing || generate_tests) { out_file << - R"( + R"( #if defined(PACKET_FUZZ_TESTING) || defined(PACKET_TESTING) || defined(FUZZ_TARGET) #include "packet/raw_builder.h" @@ -146,7 +144,7 @@ bool generate_cpp_headers_one_file( } out_file << - R"( + R"( using ::bluetooth::packet::BasePacketBuilder; using ::bluetooth::packet::BitInserter; @@ -162,7 +160,7 @@ using ::bluetooth::packet::parser::ChecksumTypeChecker; if (generate_fuzzing || generate_tests) { out_file << - R"( + R"( #if defined(PACKET_FUZZ_TESTING) || defined(PACKET_TESTING) || defined(FUZZ_TARGET) using ::bluetooth::packet::RawBuilder; #endif @@ -292,7 +290,8 @@ using ::bluetooth::packet::RawBuilder; } // Get the out_file shard at a symbol_count -std::ofstream& get_out_file(size_t symbol_count, size_t symbol_total, std::vector* out_files) { +std::ofstream& get_out_file(size_t symbol_count, size_t symbol_total, + std::vector* out_files) { auto symbols_per_shard = symbol_total / out_files->size(); auto file_index = std::min(symbol_count / symbols_per_shard, out_files->size() - 1); return out_files->at(file_index); diff --git a/system/gd/packet/parser/logging.h b/system/gd/packet/parser/logging.h index a2939ef56c7..0f1f6f14289 100644 --- a/system/gd/packet/parser/logging.h +++ b/system/gd/packet/parser/logging.h @@ -24,20 +24,21 @@ #include "parse_location.h" class Loggable { - public: +public: virtual ~Loggable() = default; virtual std::string GetDebugName() const = 0; virtual ParseLocation GetLocation() const = 0; }; class LogMessage { - public: +public: LogMessage(ParseLocation loc, std::initializer_list tokens) : debug_(false), loc_(loc), tokens_(tokens) { Init(); } - LogMessage(bool debug, std::initializer_list tokens) : debug_(debug), tokens_(tokens) { + LogMessage(bool debug, std::initializer_list tokens) + : debug_(debug), tokens_(tokens) { Init(); } @@ -58,7 +59,9 @@ class LogMessage { } ~LogMessage() { - if (debug_ && suppress_debug_) return; + if (debug_ && suppress_debug_) { + return; + } std::cerr << stream_.str() << "\n"; for (const auto& token : tokens_) { @@ -74,11 +77,9 @@ class LogMessage { } } - std::ostream& stream() { - return stream_; - } + std::ostream& stream() { return stream_; } - private: +private: std::ostringstream stream_; bool debug_; bool suppress_debug_{true}; @@ -87,7 +88,8 @@ class LogMessage { }; // Error Log stream. Aborts the program after the message is printed. -// The arguments to the macro is a list of Loggable objects that are printed when the error is printed. +// The arguments to the macro is a list of Loggable objects that are printed when the error is +// printed. #define ERROR(...) LogMessage(false, {__VA_ARGS__}).stream() // ParseLocation error log, the first argument is a location. diff --git a/system/gd/packet/parser/main.cc b/system/gd/packet/parser/main.cc index bf79504cce9..4426f748f87 100644 --- a/system/gd/packet/parser/main.cc +++ b/system/gd/packet/parser/main.cc @@ -37,16 +37,14 @@ int yylex_destroy(void*); void yyset_debug(int, void*); void yyset_in(FILE*, void*); -bool generate_cpp_headers_one_file( - const Declarations& decls, - bool generate_fuzzing, - bool generate_tests, - const std::filesystem::path& input_file, - const std::filesystem::path& include_dir, - const std::filesystem::path& out_dir, - const std::string& root_namespace); - -bool parse_declarations_one_file(const std::filesystem::path& input_file, Declarations* declarations) { +bool generate_cpp_headers_one_file(const Declarations& decls, bool generate_fuzzing, + bool generate_tests, const std::filesystem::path& input_file, + const std::filesystem::path& include_dir, + const std::filesystem::path& out_dir, + const std::string& root_namespace); + +bool parse_declarations_one_file(const std::filesystem::path& input_file, + Declarations* declarations) { void* scanner; yylex_init(&scanner); @@ -87,9 +85,7 @@ bool parse_declarations_one_file(const std::filesystem::path& input_file, Declar } // TODO(b/141583809): stop leaks -extern "C" const char* __asan_default_options() { - return "detect_leaks=0"; -} +extern "C" const char* __asan_default_options() { return "detect_leaks=0"; } void usage(const char* prog) { auto& ofs = std::cerr; @@ -168,14 +164,8 @@ int main(int argc, const char** argv) { return 2; } std::cout << "generating c++" << std::endl; - if (!generate_cpp_headers_one_file( - declarations, - generate_fuzzing, - generate_tests, - input_files.front(), - include_dir, - out_dir, - root_namespace)) { + if (!generate_cpp_headers_one_file(declarations, generate_fuzzing, generate_tests, + input_files.front(), include_dir, out_dir, root_namespace)) { std::cerr << "Didn't generate cpp headers for " << input_files.front() << std::endl; return 3; } diff --git a/system/gd/packet/parser/packet_def.cc b/system/gd/packet/parser/packet_def.cc index d91ab2d4f4a..7753d375477 100644 --- a/system/gd/packet/parser/packet_def.cc +++ b/system/gd/packet/parser/packet_def.cc @@ -25,13 +25,15 @@ #include "util.h" PacketDef::PacketDef(std::string name, FieldList fields) : ParentDef(name, fields, nullptr) {} -PacketDef::PacketDef(std::string name, FieldList fields, PacketDef* parent) : ParentDef(name, fields, parent) {} +PacketDef::PacketDef(std::string name, FieldList fields, PacketDef* parent) + : ParentDef(name, fields, parent) {} PacketField* PacketDef::GetNewField(const std::string&, ParseLocation) const { return nullptr; // Packets can't be fields } -void PacketDef::GenParserDefinition(std::ostream& s, bool generate_fuzzing, bool generate_tests) const { +void PacketDef::GenParserDefinition(std::ostream& s, bool generate_fuzzing, + bool generate_tests) const { s << "class " << name_ << "View"; if (parent_ != nullptr) { s << " : public " << parent_->name_ << "View {"; @@ -67,8 +69,8 @@ void PacketDef::GenParserDefinition(std::ostream& s, bool generate_fuzzing, bool } std::set fixed_types = { - FixedScalarField::kFieldType, - FixedEnumField::kFieldType, + FixedScalarField::kFieldType, + FixedEnumField::kFieldType, }; // Print all of the public fields which are all the fields minus the fixed fields. @@ -91,8 +93,10 @@ void PacketDef::GenParserDefinition(std::ostream& s, bool generate_fuzzing, bool s << "explicit " << name_ << "View(" << parent_->name_ << "View parent)"; s << " : " << parent_->name_ << "View(std::move(parent)) { was_validated_ = false; }"; } else { - s << "explicit " << name_ << "View(PacketView<" << (is_little_endian_ ? "" : "!") << "kLittleEndian> packet) "; - s << " : PacketView<" << (is_little_endian_ ? "" : "!") << "kLittleEndian>(packet) { was_validated_ = false;}"; + s << "explicit " << name_ << "View(PacketView<" << (is_little_endian_ ? "" : "!") + << "kLittleEndian> packet) "; + s << " : PacketView<" << (is_little_endian_ ? "" : "!") + << "kLittleEndian>(packet) { was_validated_ = false;}"; } // Print the private fields which are the fixed fields. @@ -141,7 +145,8 @@ void PacketDef::GenParserDefinitionPybind11(std::ostream& s) const { if (parent_ != nullptr) { s << ".def(py::init([](" << parent_->name_ << "View parent) {"; } else { - s << ".def(py::init([](PacketView<" << (is_little_endian_ ? "" : "!") << "kLittleEndian> parent) {"; + s << ".def(py::init([](PacketView<" << (is_little_endian_ ? "" : "!") + << "kLittleEndian> parent) {"; } s << "auto view =" << name_ << "View::Create(std::move(parent));"; s << "if (!view.IsValid()) { throw std::invalid_argument(\"Bad packet view\"); }"; @@ -149,10 +154,10 @@ void PacketDef::GenParserDefinitionPybind11(std::ostream& s) const { s << ".def(py::init(&" << name_ << "View::Create))"; std::set protected_field_types = { - FixedScalarField::kFieldType, - FixedEnumField::kFieldType, - SizeField::kFieldType, - CountField::kFieldType, + FixedScalarField::kFieldType, + FixedEnumField::kFieldType, + SizeField::kFieldType, + CountField::kFieldType, }; const auto& public_fields = fields_.GetFieldsWithoutTypes(protected_field_types); for (const auto& field : public_fields) { @@ -179,9 +184,7 @@ void PacketDef::GenParserFieldGetter(std::ostream& s, const PacketField* field) field->GenGetter(s, start_field_offset, end_field_offset); } -TypeDef::Type PacketDef::GetDefinitionType() const { - return TypeDef::Type::PACKET; -} +TypeDef::Type PacketDef::GetDefinitionType() const { return TypeDef::Type::PACKET; } void PacketDef::GenValidator(std::ostream& s) const { // Get the static offset for all of our fields. @@ -251,8 +254,8 @@ void PacketDef::GenValidator(std::ostream& s) const { const auto& field_name = ((ChecksumStartField*)field)->GetStartedFieldName(); const auto& started_field = fields_.GetField(field_name); if (started_field == nullptr) { - ERROR(field) << __func__ << ": Can't find checksum field named " << field_name << "(" << field->GetName() - << ")"; + ERROR(field) << __func__ << ": Can't find checksum field named " << field_name << "(" + << field->GetName() << ")"; } auto end_offset = GetOffsetForField(started_field->GetName(), false); if (!end_offset.empty()) { @@ -262,7 +265,8 @@ void PacketDef::GenValidator(std::ostream& s) const { if (end_offset.empty()) { ERROR(started_field) << "Checksum Field end_offset can not be determined."; } - s << "size_t end_sum_index = size() - (" << started_field->GetSize() << " - " << end_offset << ") / 8;"; + s << "size_t end_sum_index = size() - (" << started_field->GetSize() << " - " << end_offset + << ") / 8;"; } s << "if (end_sum_index >= size()) { return false; }"; if (is_little_endian_) { @@ -355,9 +359,11 @@ void PacketDef::GenParserToString(std::ostream& s) const { s << "ss << \"\" "; bool firstfield = true; for (const auto& field : fields_) { - if (field->GetFieldType() == ReservedField::kFieldType || field->GetFieldType() == FixedScalarField::kFieldType || - field->GetFieldType() == ChecksumStartField::kFieldType) + if (field->GetFieldType() == ReservedField::kFieldType || + field->GetFieldType() == FixedScalarField::kFieldType || + field->GetFieldType() == ChecksumStartField::kFieldType) { continue; + } s << (firstfield ? " << \"" : " << \", ") << field->GetName() << " = \" << "; @@ -375,7 +381,8 @@ void PacketDef::GenParserToString(std::ostream& s) const { s << "}\n"; } -void PacketDef::GenBuilderDefinition(std::ostream& s, bool generate_fuzzing, bool generate_tests) const { +void PacketDef::GenBuilderDefinition(std::ostream& s, bool generate_fuzzing, + bool generate_tests) const { s << "class " << name_ << "Builder"; if (parent_ != nullptr) { s << " : public " << parent_->name_ << "Builder"; @@ -439,7 +446,7 @@ void PacketDef::GenTestingFromView(std::ostream& s) const { s << "if (!view.IsValid()) return nullptr;"; s << "return " << name_ << "Builder::Create("; FieldList params = GetParamList().GetFieldsWithoutTypes({ - BodyField::kFieldType, + BodyField::kFieldType, }); for (std::size_t i = 0; i < params.size(); i++) { params[i]->GenBuilderParameterFromView(s); @@ -480,7 +487,8 @@ void PacketDef::GenBuilderDefinitionPybind11(std::ostream& s) const { void PacketDef::GenTestDefine(std::ostream& s) const { s << "#ifdef PACKET_TESTING\n"; s << "#define DEFINE_AND_INSTANTIATE_" << name_ << "ReflectionTest(...)"; - s << "class " << name_ << "ReflectionTest : public testing::TestWithParam> { "; + s << "class " << name_ + << "ReflectionTest : public testing::TestWithParam> { "; s << "public: "; s << "void CompareBytes(std::vector captured_packet) {"; s << name_ << "View view = " << name_ << "View::FromBytes(captured_packet);"; @@ -489,7 +497,8 @@ void PacketDef::GenTestDefine(std::ostream& s) const { "i)); }}"; s << "ASSERT_TRUE(view.IsValid());"; s << "auto packet = " << name_ << "Builder::FromView(view);"; - s << "std::shared_ptr> packet_bytes = std::make_shared>();"; + s << "std::shared_ptr> packet_bytes = " + "std::make_shared>();"; s << "packet_bytes->reserve(packet->size());"; s << "BitInserter it(*packet_bytes);"; s << "packet->Serialize(it);"; @@ -532,7 +541,8 @@ void PacketDef::GenReflectTestDefine(std::ostream& s) const { s << name_ << "View view = " << name_ << "View::FromBytes(vec);"; s << "if (!view.IsValid()) { return; }"; s << "auto packet = " << name_ << "Builder::FromView(view);"; - s << "std::shared_ptr> packet_bytes = std::make_shared>();"; + s << "std::shared_ptr> packet_bytes = " + "std::make_shared>();"; s << "packet_bytes->reserve(packet->size());"; s << "BitInserter it(*packet_bytes);"; s << "packet->Serialize(it);"; @@ -547,10 +557,12 @@ void PacketDef::GenFuzzTestDefine(std::ostream& s) const { s << " class " << name_ << "ReflectionFuzzTestRegistrant {"; s << "public: "; s << "explicit " << name_ - << "ReflectionFuzzTestRegistrant(std::vector& fuzz_test_registry) {"; + << "ReflectionFuzzTestRegistrant(std::vector& " + "fuzz_test_registry) {"; s << "fuzz_test_registry.push_back(Run" << name_ << "ReflectionFuzzTest);"; s << "}}; "; - s << name_ << "ReflectionFuzzTestRegistrant " << name_ << "_reflection_fuzz_test_registrant(REGISTRY);"; + s << name_ << "ReflectionFuzzTestRegistrant " << name_ + << "_reflection_fuzz_test_registrant(REGISTRY);"; s << "\n#endif"; } @@ -580,8 +592,8 @@ void PacketDef::GenBuilderCreate(std::ostream& s) const { s << "auto builder = std::unique_ptr<" << name_ << "Builder>(new " << name_ << "Builder("; params = params.GetFieldsWithoutTypes({ - PayloadField::kFieldType, - BodyField::kFieldType, + PayloadField::kFieldType, + BodyField::kFieldType, }); // Add the parameters. for (std::size_t i = 0; i < params.size(); i++) { @@ -646,7 +658,8 @@ void PacketDef::GenBuilderCreatePybind11(std::ostream& s) const { s << "BitInserter " << param->GetName() + "_bi(*" << param->GetName() << "_bytes);"; s << param->GetName() << "[i]->Serialize(" << param->GetName() << "_bi);"; // Parse it again - s << "auto " << param->GetName() << "_view = PacketView(" << param->GetName() << "_bytes);"; + s << "auto " << param->GetName() << "_view = PacketView(" << param->GetName() + << "_bytes);"; s << param->GetElementField()->GetDataType() << " " << param->GetName() << "_reparsed = "; s << "Parse" << struct_type << "(" << param->GetName() + "_view.begin());"; // Push it into a new container @@ -718,8 +731,8 @@ void PacketDef::GenBuilderConstructor(std::ostream& s) const { // Generate the constructor parameters. auto params = GetParamList().GetFieldsWithoutTypes({ - PayloadField::kFieldType, - BodyField::kFieldType, + PayloadField::kFieldType, + BodyField::kFieldType, }); for (std::size_t i = 0; i < params.size(); i++) { params[i]->GenBuilderParameter(s); @@ -739,8 +752,8 @@ void PacketDef::GenBuilderConstructor(std::ostream& s) const { // Pass parameters to the parent constructor s << parent_->name_ << "Builder("; parent_params = parent_->GetParamList().GetFieldsWithoutTypes({ - PayloadField::kFieldType, - BodyField::kFieldType, + PayloadField::kFieldType, + BodyField::kFieldType, }); // Go through all the fields and replace constrained fields with fixed values diff --git a/system/gd/packet/parser/packet_def.h b/system/gd/packet/parser/packet_def.h index 91fd85f020f..2ca40975ff8 100644 --- a/system/gd/packet/parser/packet_def.h +++ b/system/gd/packet/parser/packet_def.h @@ -25,7 +25,7 @@ #include "parent_def.h" class PacketDef : public ParentDef { - public: +public: PacketDef(std::string name, FieldList fields); PacketDef(std::string name, FieldList fields, PacketDef* parent); diff --git a/system/gd/packet/parser/packet_dependency.cc b/system/gd/packet/parser/packet_dependency.cc index 3bda393bd70..01000ea1ae0 100644 --- a/system/gd/packet/parser/packet_dependency.cc +++ b/system/gd/packet/parser/packet_dependency.cc @@ -32,13 +32,13 @@ std::vector& PacketDependency::GetDependencies(const std::string& p } std::vector& PacketDependency::GetChildrenDependencies( - const std::string& packet_name) { + const std::string& packet_name) { return children_dependencies[packet_name]; } std::set PacketDependency::CollectInitialParseAndMatchFields( - const ParentDef* parent, - std::map>& initial_parse_and_match_fields) const { + const ParentDef* parent, + std::map>& initial_parse_and_match_fields) const { // Case Leaf Packet: Return all of its constraints if (parent->children_.empty()) { auto constraints = parent->GetAllConstraints(); @@ -85,9 +85,9 @@ std::set PacketDependency::CollectInitialParseAndMatchFields( } void PacketDependency::FinalizeParseAndMatchFields( - const ParentDef* parent, - std::map>& initial_parse_and_match_fields, - std::vector& available_fields) { + const ParentDef* parent, + std::map>& initial_parse_and_match_fields, + std::vector& available_fields) { // Root does not have any constraints on anything if (parent->parent_ == nullptr) { dependencies[parent->name_] = std::vector{}; diff --git a/system/gd/packet/parser/packet_dependency.h b/system/gd/packet/parser/packet_dependency.h index e550775c350..ad2a5aa024c 100644 --- a/system/gd/packet/parser/packet_dependency.h +++ b/system/gd/packet/parser/packet_dependency.h @@ -22,19 +22,19 @@ #include "parent_def.h" class PacketDependency { - private: +private: std::map> dependencies; std::map> children_dependencies; std::set CollectInitialParseAndMatchFields( - const ParentDef* parent, - std::map>& initial_parse_and_match_fields) const; + const ParentDef* parent, + std::map>& initial_parse_and_match_fields) const; void FinalizeParseAndMatchFields( - const ParentDef* parent, - std::map>& initial_parse_and_match_fields, - std::vector& available_fields); + const ParentDef* parent, + std::map>& initial_parse_and_match_fields, + std::vector& available_fields); - public: +public: PacketDependency(const ParentDef* root); std::vector& GetDependencies(const std::string& packet_name); std::vector& GetChildrenDependencies(const std::string& packet_name); diff --git a/system/gd/packet/parser/parent_def.cc b/system/gd/packet/parser/parent_def.cc index 0c63482ffaa..18fd9a98bae 100644 --- a/system/gd/packet/parser/parent_def.cc +++ b/system/gd/packet/parser/parent_def.cc @@ -23,7 +23,8 @@ ParentDef::ParentDef(std::string name, FieldList fields) : ParentDef(name, field ParentDef::ParentDef(std::string name, FieldList fields, ParentDef* parent) : TypeDef(name), fields_(fields), parent_(parent) {} -void ParentDef::AddParentConstraint(std::string field_name, std::variant value) { +void ParentDef::AddParentConstraint(std::string field_name, + std::variant value) { // NOTE: This could end up being very slow if there are a lot of constraints. const auto& parent_params = parent_->GetParamList(); const auto& constrained_field = parent_params.GetField(field_name); @@ -34,11 +35,13 @@ void ParentDef::AddParentConstraint(std::string field_name, std::variantGetFieldType() == ScalarField::kFieldType) { if (!std::holds_alternative(value)) { - ERROR(constrained_field) << "Attempting to constrain a scalar field to an enum value in " << parent_->name_; + ERROR(constrained_field) << "Attempting to constrain a scalar field to an enum value in " + << parent_->name_; } } else if (constrained_field->GetFieldType() == EnumField::kFieldType) { if (!std::holds_alternative(value)) { - ERROR(constrained_field) << "Attempting to constrain an enum field to a scalar value in " << parent_->name_; + ERROR(constrained_field) << "Attempting to constrain an enum field to a scalar value in " + << parent_->name_; } const auto& enum_def = static_cast(constrained_field)->GetEnumDef(); if (!enum_def.HasEntry(std::get(value))) { @@ -49,7 +52,8 @@ void ParentDef::AddParentConstraint(std::string field_name, std::variant(value); } else { - ERROR(constrained_field) << "Field in parent " << parent_->name_ << " is not viable for constraining."; + ERROR(constrained_field) << "Field in parent " << parent_->name_ + << " is not viable for constraining."; } parent_constraints_.insert(std::pair(field_name, value)); @@ -68,7 +72,8 @@ void ParentDef::AssignSizeFields() { for (const auto& field : fields_) { DEBUG() << "field name: " << field->GetName(); - if (field->GetFieldType() != SizeField::kFieldType && field->GetFieldType() != CountField::kFieldType) { + if (field->GetFieldType() != SizeField::kFieldType && + field->GetFieldType() != CountField::kFieldType) { continue; } @@ -84,7 +89,8 @@ void ParentDef::AssignSizeFields() { for (auto it = fields_.begin(); *it != size_field; it++) { DEBUG() << "field name: " << (*it)->GetName(); if (*it == var_len_field) { - ERROR(var_len_field, size_field) << "Size/count field must come before the variable length field it describes."; + ERROR(var_len_field, size_field) + << "Size/count field must come before the variable length field it describes."; } } @@ -112,17 +118,16 @@ void ParentDef::AssignSizeFields() { } } -void ParentDef::SetEndianness(bool is_little_endian) { - is_little_endian_ = is_little_endian; -} +void ParentDef::SetEndianness(bool is_little_endian) { is_little_endian_ = is_little_endian; } -// Get the size. You scan specify without_payload in order to exclude payload fields as children will be overriding it. +// Get the size. You scan specify without_payload in order to exclude payload fields as children +// will be overriding it. Size ParentDef::GetSize(bool without_payload) const { auto size = Size(0); for (const auto& field : fields_) { - if (without_payload && - (field->GetFieldType() == PayloadField::kFieldType || field->GetFieldType() == BodyField::kFieldType)) { + if (without_payload && (field->GetFieldType() == PayloadField::kFieldType || + field->GetFieldType() == BodyField::kFieldType)) { continue; } @@ -144,8 +149,12 @@ Size ParentDef::GetSize(bool without_payload) const { if (offset.bits() % 8 != 0) { ERROR(field) << "Custom fields must be byte aligned."; } - if (offset.has_bits()) custom_field_size << " + " << offset.bits() / 8; - if (offset.has_dynamic()) custom_field_size << " + " << offset.dynamic_string(); + if (offset.has_bits()) { + custom_field_size << " + " << offset.bits() / 8; + } + if (offset.has_dynamic()) { + custom_field_size << " + " << offset.dynamic_string(); + } custom_field_size << ")"; size += custom_field_size.str(); @@ -169,7 +178,8 @@ Size ParentDef::GetSize(bool without_payload) const { Size ParentDef::GetOffsetForField(std::string field_name, bool from_end) const { // Check first if the field exists. if (fields_.GetField(field_name) == nullptr) { - ERROR() << "Can't find a field offset for nonexistent field named: " << field_name << " in " << name_; + ERROR() << "Can't find a field offset for nonexistent field named: " << field_name << " in " + << name_; } PacketField* padded_field = nullptr; @@ -189,7 +199,9 @@ Size ParentDef::GetOffsetForField(std::string field_name, bool from_end) const { auto size = Size(0); for (auto it = from; it != to; it++) { // We've reached the field, end the loop. - if ((*it)->GetName() == field_name) break; + if ((*it)->GetName() == field_name) { + break; + } const auto& field = *it; // If there is a field with an unknown size before the field, return an empty Size. if (field->GetSize().empty() && padded_field != field) { @@ -206,24 +218,29 @@ Size ParentDef::GetOffsetForField(std::string field_name, bool from_end) const { // Change iteration direction based on from_end. auto size = Size(); - if (from_end) + if (from_end) { size = size_lambda(fields_.rbegin(), fields_.rend()); - else + } else { size = size_lambda(fields_.begin(), fields_.end()); - if (size.empty()) return size; + } + if (size.empty()) { + return size; + } // We need the offset until a payload or body field. if (parent_ != nullptr) { if (parent_->fields_.HasPayload()) { auto parent_payload_offset = parent_->GetOffsetForField("payload", from_end); if (parent_payload_offset.empty()) { - ERROR() << "Empty offset for payload in " << parent_->name_ << " finding the offset for field: " << field_name; + ERROR() << "Empty offset for payload in " << parent_->name_ + << " finding the offset for field: " << field_name; } size += parent_payload_offset; } else { auto parent_body_offset = parent_->GetOffsetForField("body", from_end); if (parent_body_offset.empty()) { - ERROR() << "Empty offset for body in " << parent_->name_ << " finding the offset for field: " << field_name; + ERROR() << "Empty offset for body in " << parent_->name_ + << " finding the offset for field: " << field_name; } size += parent_body_offset; } @@ -236,14 +253,14 @@ FieldList ParentDef::GetParamList() const { FieldList params; std::set param_types = { - ScalarField::kFieldType, - EnumField::kFieldType, - ArrayField::kFieldType, - VectorField::kFieldType, - CustomField::kFieldType, - StructField::kFieldType, - VariableLengthStructField::kFieldType, - PayloadField::kFieldType, + ScalarField::kFieldType, + EnumField::kFieldType, + ArrayField::kFieldType, + VectorField::kFieldType, + CustomField::kFieldType, + StructField::kFieldType, + VariableLengthStructField::kFieldType, + PayloadField::kFieldType, }; if (parent_ != nullptr) { @@ -400,15 +417,18 @@ void ParentDef::GenSerialize(std::ostream& s) const { if (modifier != "") { s << "payload_bytes = payload_bytes + " << modifier.substr(1) << ";"; } - s << "ASSERT(payload_bytes < (static_cast(1) << " << field->GetSize().bits() << "));"; - s << "insert(static_cast<" << field->GetDataType() << ">(payload_bytes), i," << field->GetSize().bits() << ");"; + s << "ASSERT(payload_bytes < (static_cast(1) << " << field->GetSize().bits() + << "));"; + s << "insert(static_cast<" << field->GetDataType() << ">(payload_bytes), i," + << field->GetSize().bits() << ");"; } else if (sized_field->GetFieldType() == BodyField::kFieldType) { s << field->GetName() << "_extracted_ = 0;"; s << "size_t local_size = " << name_ << "::size();"; - s << "ASSERT((size() - local_size) < (static_cast(1) << " << field->GetSize().bits() << "));"; - s << "insert(static_cast<" << field->GetDataType() << ">(size() - local_size), i," << field->GetSize().bits() - << ");"; + s << "ASSERT((size() - local_size) < (static_cast(1) << " << field->GetSize().bits() + << "));"; + s << "insert(static_cast<" << field->GetDataType() << ">(size() - local_size), i," + << field->GetSize().bits() << ");"; } else { if (sized_field->GetFieldType() != VectorField::kFieldType) { ERROR(field) << __func__ << ": Unhandled sized field type for " << field_name; @@ -436,14 +456,15 @@ void ParentDef::GenSerialize(std::ostream& s) const { const auto& field_name = ((ChecksumStartField*)field)->GetStartedFieldName(); const auto& started_field = fields_.GetField(field_name); if (started_field == nullptr) { - ERROR(field) << __func__ << ": Can't find checksum field named " << field_name << "(" << field->GetName() - << ")"; + ERROR(field) << __func__ << ": Can't find checksum field named " << field_name << "(" + << field->GetName() << ")"; } s << "auto shared_checksum_ptr = std::make_shared<" << started_field->GetDataType() << ">();"; s << "shared_checksum_ptr->Initialize();"; s << "i.RegisterObserver(packet::ByteObserver("; s << "[shared_checksum_ptr](uint8_t byte){ shared_checksum_ptr->AddByte(byte);},"; - s << "[shared_checksum_ptr](){ return static_cast(shared_checksum_ptr->GetChecksum());}));"; + s << "[shared_checksum_ptr](){ return " + "static_cast(shared_checksum_ptr->GetChecksum());}));"; } else if (field->GetFieldType() == PaddingField::kFieldType) { s << "ASSERT(unpadded_size <= " << field->GetSize().bytes() << ");"; s << "size_t padding_bytes = "; @@ -495,8 +516,8 @@ void ParentDef::GenInstanceOf(std::ostream& s) const { s << "static bool IsInstance(const " << parent_->name_ << "& parent) {"; // Get the list of parent params. FieldList parent_params = parent_->GetParamList().GetFieldsWithoutTypes({ - PayloadField::kFieldType, - BodyField::kFieldType, + PayloadField::kFieldType, + BodyField::kFieldType, }); // Check if constrained parent fields are set to their correct values. @@ -570,8 +591,7 @@ std::string ParentDef::FindConstraintField() const { } std::map> - ParentDef::FindDescendantsWithConstraint( - std::string constraint_name) const { +ParentDef::FindDescendantsWithConstraint(std::string constraint_name) const { std::map> res; for (auto const& child : children_) { @@ -602,6 +622,4 @@ std::vector ParentDef::FindPathToDescendant(std::string descen return res; } -bool ParentDef::HasChildEnums() const { - return !children_.empty() || fields_.HasPayload(); -} +bool ParentDef::HasChildEnums() const { return !children_.empty() || fields_.HasPayload(); } diff --git a/system/gd/packet/parser/parent_def.h b/system/gd/packet/parser/parent_def.h index f9e29dbd5c5..c7816da45b1 100644 --- a/system/gd/packet/parser/parent_def.h +++ b/system/gd/packet/parser/parent_def.h @@ -30,7 +30,7 @@ #include "type_def.h" class ParentDef : public TypeDef { - public: +public: ParentDef(std::string name, FieldList fields); ParentDef(std::string name, FieldList fields, ParentDef* parent); @@ -47,7 +47,8 @@ class ParentDef : public TypeDef { void SetEndianness(bool is_little_endian); - // Get the size. You scan specify without_payload to exclude payload and body fields as children override them. + // Get the size. You scan specify without_payload to exclude payload and body fields as children + // override them. Size GetSize(bool without_payload = false) const; // Get the offset until the field is reached, if there is no field @@ -77,7 +78,7 @@ class ParentDef : public TypeDef { std::string FindConstraintField() const; std::map> - FindDescendantsWithConstraint(std::string constraint_name) const; + FindDescendantsWithConstraint(std::string constraint_name) const; std::vector FindPathToDescendant(std::string descendant) const; FieldList fields_; diff --git a/system/gd/packet/parser/parse_location.h b/system/gd/packet/parser/parse_location.h index 80bdc729a24..ee2b747888f 100644 --- a/system/gd/packet/parser/parse_location.h +++ b/system/gd/packet/parser/parse_location.h @@ -17,15 +17,13 @@ #pragma once class ParseLocation { - public: +public: ParseLocation() : line_(-1) {} ParseLocation(int line) : line_(line) {} - int GetLine() { - return line_; - } + int GetLine() { return line_; } - private: +private: int line_; }; diff --git a/system/gd/packet/parser/size.h b/system/gd/packet/parser/size.h index fed3c519f80..f863639e36c 100644 --- a/system/gd/packet/parser/size.h +++ b/system/gd/packet/parser/size.h @@ -22,7 +22,7 @@ #include class Size { - public: +public: Size() {} Size(int bits) { @@ -48,44 +48,35 @@ class Size { } std::string dynamic_string() const { - if (dynamic_.empty()) return "0"; + if (dynamic_.empty()) { + return "0"; + } std::stringstream result; // Print everything but the last element then append it manually to avoid // the trailing "+" operator. - std::copy(dynamic_.begin(), dynamic_.end() - 1, std::ostream_iterator(result, " + ")); + std::copy(dynamic_.begin(), dynamic_.end() - 1, + std::ostream_iterator(result, " + ")); result << dynamic_.back(); return result.str(); } - std::vector dynamic_string_list() { - return dynamic_; - } + std::vector dynamic_string_list() { return dynamic_; } - bool empty() const { - return !is_valid_; - } + bool empty() const { return !is_valid_; } - bool has_bits() const { - return bits_ != 0; - } + bool has_bits() const { return bits_ != 0; } - bool has_dynamic() const { - return !dynamic_.empty(); - } + bool has_dynamic() const { return !dynamic_.empty(); } - int bits() const { - return bits_; - } + int bits() const { return bits_; } int bytes() const { // Round up to the nearest byte return (bits_ + 7) / 8; } - Size operator+(int rhs) { - return Size(bits_ + rhs); - } + Size operator+(int rhs) { return Size(bits_ + rhs); } Size operator+(std::string rhs) { auto ret = Size(); @@ -135,7 +126,7 @@ class Size { return os << rhs.ToString(); } - private: +private: bool is_valid_ = false; int bits_ = 0; std::vector dynamic_; diff --git a/system/gd/packet/parser/struct_def.cc b/system/gd/packet/parser/struct_def.cc index 691a4429dca..b611bc89573 100644 --- a/system/gd/packet/parser/struct_def.cc +++ b/system/gd/packet/parser/struct_def.cc @@ -31,9 +31,7 @@ PacketField* StructDef::GetNewField(const std::string& name, ParseLocation loc) } } -TypeDef::Type StructDef::GetDefinitionType() const { - return TypeDef::Type::STRUCT; -} +TypeDef::Type StructDef::GetDefinitionType() const { return TypeDef::Type::STRUCT; } void StructDef::GenSpecialize(std::ostream& s) const { if (parent_ == nullptr) { @@ -56,9 +54,11 @@ void StructDef::GenToString(std::ostream& s) const { for (const auto& field : fields_) { if (field->GetFieldType() == ReservedField::kFieldType || field->GetFieldType() == ChecksumStartField::kFieldType || - field->GetFieldType() == FixedScalarField::kFieldType || field->GetFieldType() == CountField::kFieldType || - field->GetFieldType() == SizeField::kFieldType) + field->GetFieldType() == FixedScalarField::kFieldType || + field->GetFieldType() == CountField::kFieldType || + field->GetFieldType() == SizeField::kFieldType) { continue; + } s << (firstfield ? " << \"" : " << \", ") << field->GetName() << " = \" << "; @@ -77,7 +77,8 @@ void StructDef::GenToString(std::ostream& s) const { } void StructDef::GenParse(std::ostream& s) const { - std::string iterator = (is_little_endian_ ? "Iterator" : "Iterator"); + std::string iterator = + (is_little_endian_ ? "Iterator" : "Iterator"); if (fields_.HasBody()) { s << "static std::optional<" << iterator << ">"; @@ -98,7 +99,8 @@ void StructDef::GenParse(std::ostream& s) const { s << "if (fill_parent) {"; std::string parent_param = (parent_->parent_ == nullptr ? "" : ", true"); if (parent_->fields_.HasBody()) { - s << "auto parent_optional_it = " << parent_->name_ << "::Parse(to_fill, to_bound" << parent_param << ");"; + s << "auto parent_optional_it = " << parent_->name_ << "::Parse(to_fill, to_bound" + << parent_param << ");"; if (fields_.HasBody()) { s << "if (!parent_optional_it) { return {}; }"; } else { @@ -118,9 +120,11 @@ void StructDef::GenParse(std::ostream& s) const { Size total_bits{0}; for (const auto& field : fields_) { - if (field->GetFieldType() != ReservedField::kFieldType && field->GetFieldType() != BodyField::kFieldType && + if (field->GetFieldType() != ReservedField::kFieldType && + field->GetFieldType() != BodyField::kFieldType && field->GetFieldType() != FixedScalarField::kFieldType && - field->GetFieldType() != ChecksumStartField::kFieldType && field->GetFieldType() != ChecksumField::kFieldType && + field->GetFieldType() != ChecksumStartField::kFieldType && + field->GetFieldType() != ChecksumField::kFieldType && field->GetFieldType() != CountField::kFieldType) { total_bits += field->GetSize().bits(); } @@ -134,21 +138,25 @@ void StructDef::GenParse(std::ostream& s) const { } s << "}"; for (const auto& field : fields_) { - if (field->GetFieldType() != ReservedField::kFieldType && field->GetFieldType() != BodyField::kFieldType && - field->GetFieldType() != FixedScalarField::kFieldType && field->GetFieldType() != SizeField::kFieldType && - field->GetFieldType() != ChecksumStartField::kFieldType && field->GetFieldType() != ChecksumField::kFieldType && + if (field->GetFieldType() != ReservedField::kFieldType && + field->GetFieldType() != BodyField::kFieldType && + field->GetFieldType() != FixedScalarField::kFieldType && + field->GetFieldType() != SizeField::kFieldType && + field->GetFieldType() != ChecksumStartField::kFieldType && + field->GetFieldType() != ChecksumField::kFieldType && field->GetFieldType() != CountField::kFieldType) { s << "{"; - int num_leading_bits = - field->GenBounds(s, GetStructOffsetForField(field->GetName()), Size(), field->GetStructSize()); + int num_leading_bits = field->GenBounds(s, GetStructOffsetForField(field->GetName()), Size(), + field->GetStructSize()); s << "auto " << field->GetName() << "_ptr = &to_fill->" << field->GetName() << "_;"; field->GenExtractor(s, num_leading_bits, true); s << "}"; } - if (field->GetFieldType() == CountField::kFieldType || field->GetFieldType() == SizeField::kFieldType) { + if (field->GetFieldType() == CountField::kFieldType || + field->GetFieldType() == SizeField::kFieldType) { s << "{"; - int num_leading_bits = - field->GenBounds(s, GetStructOffsetForField(field->GetName()), Size(), field->GetStructSize()); + int num_leading_bits = field->GenBounds(s, GetStructOffsetForField(field->GetName()), Size(), + field->GetStructSize()); s << "auto " << field->GetName() << "_ptr = &to_fill->" << field->GetName() << "_extracted_;"; field->GenExtractor(s, num_leading_bits, true); s << "}"; @@ -208,7 +216,8 @@ void StructDef::GenDefinition(std::ostream& s) const { GenMembers(s); for (const auto& field : fields_) { - if (field->GetFieldType() == CountField::kFieldType || field->GetFieldType() == SizeField::kFieldType) { + if (field->GetFieldType() == CountField::kFieldType || + field->GetFieldType() == SizeField::kFieldType) { s << "\n private:\n"; s << " mutable " << field->GetDataType() << " " << field->GetName() << "_extracted_{0};"; } @@ -246,7 +255,8 @@ void StructDef::GenDefinitionPybind11(std::ostream& s) const { if (field->GetBuilderParameterType().empty()) { continue; } - s << ".def_readwrite(\"" << field->GetName() << "\", &" << name_ << "::" << field->GetName() << "_)"; + s << ".def_readwrite(\"" << field->GetName() << "\", &" << name_ << "::" << field->GetName() + << "_)"; } s << ";\n"; } @@ -264,8 +274,8 @@ void StructDef::GenDefaultConstructor(std::ostream& s) const { FieldList parent_params; if (parent_ != nullptr) { parent_params = parent_->GetParamList().GetFieldsWithoutTypes({ - PayloadField::kFieldType, - BodyField::kFieldType, + PayloadField::kFieldType, + BodyField::kFieldType, }); // Set constrained parent fields to their correct values. @@ -294,14 +304,14 @@ void StructDef::GenConstructor(std::ostream& s) const { // have a constrained value. FieldList parent_params; FieldList params = GetParamList().GetFieldsWithoutTypes({ - PayloadField::kFieldType, - BodyField::kFieldType, + PayloadField::kFieldType, + BodyField::kFieldType, }); if (parent_ != nullptr) { parent_params = parent_->GetParamList().GetFieldsWithoutTypes({ - PayloadField::kFieldType, - BodyField::kFieldType, + PayloadField::kFieldType, + BodyField::kFieldType, }); } @@ -381,11 +391,14 @@ Size StructDef::GetStructOffsetForField(std::string field_name) const { auto size = Size(0); for (auto it = fields_.begin(); it != fields_.end(); it++) { // We've reached the field, end the loop. - if ((*it)->GetName() == field_name) break; + if ((*it)->GetName() == field_name) { + break; + } const auto& field = *it; // When we need to parse this field, all previous fields should already be parsed. if (field->GetStructSize().empty()) { - ERROR() << "Empty size for field " << (*it)->GetName() << " finding the offset for field: " << field_name; + ERROR() << "Empty size for field " << (*it)->GetName() + << " finding the offset for field: " << field_name; } size += field->GetStructSize(); } @@ -394,7 +407,8 @@ Size StructDef::GetStructOffsetForField(std::string field_name) const { if (parent_ != nullptr) { auto parent_body_offset = static_cast(parent_)->GetStructOffsetForField("body"); if (parent_body_offset.empty()) { - ERROR() << "Empty offset for body in " << parent_->name_ << " finding the offset for field: " << field_name; + ERROR() << "Empty offset for body in " << parent_->name_ + << " finding the offset for field: " << field_name; } size += parent_body_offset; } diff --git a/system/gd/packet/parser/struct_def.h b/system/gd/packet/parser/struct_def.h index c5b81250ef9..82bba3446ef 100644 --- a/system/gd/packet/parser/struct_def.h +++ b/system/gd/packet/parser/struct_def.h @@ -26,7 +26,7 @@ #include "type_def.h" class StructDef : public ParentDef { - public: +public: StructDef(std::string name, FieldList fields); StructDef(std::string name, FieldList fields, StructDef* parent); @@ -51,6 +51,6 @@ class StructDef : public ParentDef { Size GetStructOffsetForField(std::string field_name) const; - private: +private: Size total_size_; }; diff --git a/system/gd/packet/parser/struct_parser_generator.cc b/system/gd/packet/parser/struct_parser_generator.cc index 7caf6792d85..cd66b31da61 100644 --- a/system/gd/packet/parser/struct_parser_generator.cc +++ b/system/gd/packet/parser/struct_parser_generator.cc @@ -44,17 +44,20 @@ void StructParserGenerator::explore_children(const TreeNode& node, std::ostream& s << "if (!" << field->GetName() << "_child_found && "; s << child->struct_def_->name_ << "::IsInstance(*" << field->GetName() << "_value.get())) {"; s << field->GetName() << "_child_found = true;"; - s << "std::unique_ptr<" << child->struct_def_->name_ << "> " << child->packet_field_->GetName() << "_value;"; + s << "std::unique_ptr<" << child->struct_def_->name_ << "> " << child->packet_field_->GetName() + << "_value;"; s << child->packet_field_->GetName() << "_value.reset(new "; s << child->struct_def_->name_ << "(*" << field->GetName() << "_value));"; if (child->struct_def_->fields_.HasBody()) { s << "auto optional_it = "; - s << child->struct_def_->name_ << "::Parse( " << child->packet_field_->GetName() << "_value.get(), "; + s << child->struct_def_->name_ << "::Parse( " << child->packet_field_->GetName() + << "_value.get(), "; s << "to_bound, false);"; s << "if (optional_it) {"; s << "} else { return " << field->GetName() << "_value;}"; } else { - s << child->struct_def_->name_ << "::Parse( " << child->packet_field_->GetName() << "_value.get(), "; + s << child->struct_def_->name_ << "::Parse( " << child->packet_field_->GetName() + << "_value.get(), "; s << "to_bound, false);"; } explore_children(*child, s); @@ -70,7 +73,8 @@ void StructParserGenerator::Generate(std::ostream& s) const { continue; } auto field = node.packet_field_; - s << "inline std::unique_ptr<" << node.struct_def_->name_ << "> Parse" << node.struct_def_->name_; + s << "inline std::unique_ptr<" << node.struct_def_->name_ << "> Parse" + << node.struct_def_->name_; if (is_little_endian) { s << "(Iterator to_bound) {"; } else { diff --git a/system/gd/packet/parser/struct_parser_generator.h b/system/gd/packet/parser/struct_parser_generator.h index 03154602ffa..1f5f9b1fcdf 100644 --- a/system/gd/packet/parser/struct_parser_generator.h +++ b/system/gd/packet/parser/struct_parser_generator.h @@ -23,14 +23,14 @@ #include "parse_location.h" class StructParserGenerator { - public: +public: explicit StructParserGenerator(const Declarations& declarations); void Generate(std::ostream& s) const; - private: +private: class TreeNode { - public: + public: explicit TreeNode(const StructDef* s) : struct_def_(s), packet_field_(s->GetNewField(s->name_ + "_parse", ParseLocation())) {} const StructDef* struct_def_; diff --git a/system/gd/packet/parser/test/generated_packet_test.cc b/system/gd/packet/parser/test/generated_packet_test.cc index a3ce2542cf4..66ca1fb7ccb 100644 --- a/system/gd/packet/parser/test/generated_packet_test.cc +++ b/system/gd/packet/parser/test/generated_packet_test.cc @@ -15,6 +15,7 @@ */ #include + #include #include @@ -34,27 +35,31 @@ using std::vector; namespace { vector child_two_two_three = { - 0x20 /* Reserved : 4, FourBits::TWO */, - 0x03 /* FourBits::THREE, Reserved : 4 */, + 0x20 /* Reserved : 4, FourBits::TWO */, + 0x03 /* FourBits::THREE, Reserved : 4 */, }; vector child = { - 0x12 /* fixed */, 0x02 /* Size of the payload */, 0xa1 /* First byte of the payload */, 0xa2, 0xb1 /* footer */, + 0x12 /* fixed */, + 0x02 /* Size of the payload */, + 0xa1 /* First byte of the payload */, + 0xa2, + 0xb1 /* footer */, }; vector child_with_six_bytes = { - 0x34 /* TwoBytes */, - 0x12, - 0xa1 /* First byte of the six_bytes */, - 0xa2, - 0xa3, - 0xa4, - 0xa5, - 0xa6, - 0xb1 /* Second six_bytes*/, - 0xb2, - 0xb3, - 0xb4, - 0xb5, - 0xb6, + 0x34 /* TwoBytes */, + 0x12, + 0xa1 /* First byte of the six_bytes */, + 0xa2, + 0xa3, + 0xa4, + 0xa5, + 0xa6, + 0xb1 /* Second six_bytes*/, + 0xb2, + 0xb3, + 0xb4, + 0xb5, + 0xb6, }; } // namespace @@ -128,33 +133,38 @@ TEST(GeneratedPacketTest, testChild) { TEST(GeneratedPacketTest, testValidateWayTooSmall) { std::vector too_small_bytes = {0x34}; - auto too_small = std::make_shared>(too_small_bytes.begin(), too_small_bytes.end()); + auto too_small = + std::make_shared>(too_small_bytes.begin(), too_small_bytes.end()); - ParentWithSixBytesView invalid_parent = ParentWithSixBytesView::Create(PacketView(too_small)); + ParentWithSixBytesView invalid_parent = + ParentWithSixBytesView::Create(PacketView(too_small)); ASSERT_FALSE(invalid_parent.IsValid()); - ChildWithSixBytesView invalid = - ChildWithSixBytesView::Create(ParentWithSixBytesView::Create(PacketView(too_small))); + ChildWithSixBytesView invalid = ChildWithSixBytesView::Create( + ParentWithSixBytesView::Create(PacketView(too_small))); ASSERT_FALSE(invalid.IsValid()); } TEST(GeneratedPacketTest, testValidateTooSmall) { std::vector too_small_bytes = {0x34, 0x12, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x11}; - auto too_small = std::make_shared>(too_small_bytes.begin(), too_small_bytes.end()); + auto too_small = + std::make_shared>(too_small_bytes.begin(), too_small_bytes.end()); - ParentWithSixBytesView valid_parent = ParentWithSixBytesView::Create(PacketView(too_small)); + ParentWithSixBytesView valid_parent = + ParentWithSixBytesView::Create(PacketView(too_small)); ASSERT_TRUE(valid_parent.IsValid()); - ChildWithSixBytesView invalid = - ChildWithSixBytesView::Create(ParentWithSixBytesView::Create(PacketView(too_small))); + ChildWithSixBytesView invalid = ChildWithSixBytesView::Create( + ParentWithSixBytesView::Create(PacketView(too_small))); ASSERT_FALSE(invalid.IsValid()); } TEST(GeneratedPacketTest, testValidateJustRight) { std::vector just_right_bytes = {0x34, 0x12, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16}; - auto just_right = std::make_shared>(just_right_bytes.begin(), just_right_bytes.end()); + auto just_right = + std::make_shared>(just_right_bytes.begin(), just_right_bytes.end()); - ChildWithSixBytesView valid = - ChildWithSixBytesView::Create(ParentWithSixBytesView::Create(PacketView(just_right))); + ChildWithSixBytesView valid = ChildWithSixBytesView::Create( + ParentWithSixBytesView::Create(PacketView(just_right))); ASSERT_TRUE(valid.IsValid()); } @@ -163,8 +173,8 @@ TEST(GeneratedPacketTest, testValidateTooBig) { 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x20}; auto too_big = std::make_shared>(too_big_bytes.begin(), too_big_bytes.end()); - ChildWithSixBytesView lenient = - ChildWithSixBytesView::Create(ParentWithSixBytesView::Create(PacketView(too_big))); + ChildWithSixBytesView lenient = ChildWithSixBytesView::Create( + ParentWithSixBytesView::Create(PacketView(too_big))); ASSERT_TRUE(lenient.IsValid()); } @@ -218,8 +228,8 @@ TEST(GeneratedPacketTest, testValidatedParentDeath) { } vector middle_four_bits = { - 0x95, // low_two = ONE, next_four = FIVE, straddle = TEN - 0x8a, // straddle = TEN, four_more = TWO, high_two = TWO + 0x95, // low_two = ONE, next_four = FIVE, straddle = TEN + 0x8a, // straddle = TEN, four_more = TWO, high_two = TWO }; TEST(GeneratedPacketTest, testMiddleFourBitsPacket) { @@ -283,7 +293,12 @@ TEST(GeneratedPacketTest, testChildWithSixBytes) { namespace { vector parent_with_sum = { - 0x11 /* TwoBytes */, 0x12, 0x21 /* Sum Bytes */, 0x22, 0x43 /* Sum, excluding TwoBytes */, 0x00, + 0x11 /* TwoBytes */, + 0x12, + 0x21 /* Sum Bytes */, + 0x22, + 0x43 /* Sum, excluding TwoBytes */, + 0x00, }; } // namespace @@ -291,7 +306,8 @@ vector parent_with_sum = { TEST(GeneratedPacketTest, testParentWithSum) { uint16_t two_bytes = 0x1211; uint16_t sum_bytes = 0x2221; - auto packet = ParentWithSumBuilder::Create(two_bytes, sum_bytes, std::make_unique()); + auto packet = ParentWithSumBuilder::Create(two_bytes, sum_bytes, + std::make_unique()); ASSERT_EQ(parent_with_sum.size(), packet->size()); @@ -318,18 +334,18 @@ TEST(GeneratedPacketTest, testParentWithSum) { namespace { vector child_with_nested_sum = { - 0x11 /* TwoBytes */, - 0x12, - 0x21 /* Sum Bytes */, - 0x22, - 0x31 /* More Bytes */, - 0x32, - 0x33, - 0x34, - 0xca /* Nested Sum */, - 0x00, - 0xd7 /* Sum, excluding TwoBytes */, - 0x01, + 0x11 /* TwoBytes */, + 0x12, + 0x21 /* Sum Bytes */, + 0x22, + 0x31 /* More Bytes */, + 0x32, + 0x33, + 0x34, + 0xca /* Nested Sum */, + 0x00, + 0xd7 /* Sum, excluding TwoBytes */, + 0x01, }; } // namespace @@ -374,9 +390,9 @@ TEST(GeneratedPacketTest, testSizedWithSumBadSize) { namespace { vector parent_size_modifier = { - 0x02 /* Size */, - 0x11 /* TwoBytes */, - 0x12, + 0x02 /* Size */, + 0x11 /* TwoBytes */, + 0x12, }; } // namespace @@ -404,13 +420,13 @@ TEST(GeneratedPacketTest, testParentSizeModifier) { namespace { vector child_size_modifier = { - 0x06 /* PayloadSize (TwoBytes + MoreBytes)*/, - 0x31 /* MoreBytes */, - 0x32, - 0x33, - 0x34, - 0x11 /* TwoBytes = 0x1211 */, - 0x12, + 0x06 /* PayloadSize (TwoBytes + MoreBytes)*/, + 0x31 /* MoreBytes */, + 0x32, + 0x33, + 0x34, + 0x11 /* TwoBytes = 0x1211 */, + 0x12, }; } // namespace @@ -444,22 +460,22 @@ TEST(GeneratedPacketTest, testChildSizeModifier) { namespace { vector fixed_array_enum{ - 0x01, // ONE - 0x00, - 0x02, // TWO - 0x00, - 0x01, // ONE_TWO - 0x02, - 0x02, // TWO_THREE - 0x03, - 0xff, // FFFF - 0xff, + 0x01, // ONE + 0x00, + 0x02, // TWO + 0x00, + 0x01, // ONE_TWO + 0x02, + 0x02, // TWO_THREE + 0x03, + 0xff, // FFFF + 0xff, }; } TEST(GeneratedPacketTest, testFixedArrayEnum) { - std::array fixed_array{ - {ForArrays::ONE, ForArrays::TWO, ForArrays::ONE_TWO, ForArrays::TWO_THREE, ForArrays::FFFF}}; + std::array fixed_array{{ForArrays::ONE, ForArrays::TWO, ForArrays::ONE_TWO, + ForArrays::TWO_THREE, ForArrays::FFFF}}; auto packet = FixedArrayEnumBuilder::Create(fixed_array); ASSERT_EQ(fixed_array_enum.size(), packet->size()); @@ -488,24 +504,24 @@ TEST(GeneratedPacketTest, testFixedArrayEnum) { namespace { vector sized_array_enum{ - 0x0a, // _size_ - 0x00, - 0x01, // ONE - 0x00, - 0x02, // TWO - 0x00, - 0x01, // ONE_TWO - 0x02, - 0x02, // TWO_THREE - 0x03, - 0xff, // FFFF - 0xff, + 0x0a, // _size_ + 0x00, + 0x01, // ONE + 0x00, + 0x02, // TWO + 0x00, + 0x01, // ONE_TWO + 0x02, + 0x02, // TWO_THREE + 0x03, + 0xff, // FFFF + 0xff, }; } TEST(GeneratedPacketTest, testSizedArrayEnum) { - std::vector sized_array{ - {ForArrays::ONE, ForArrays::TWO, ForArrays::ONE_TWO, ForArrays::TWO_THREE, ForArrays::FFFF}}; + std::vector sized_array{{ForArrays::ONE, ForArrays::TWO, ForArrays::ONE_TWO, + ForArrays::TWO_THREE, ForArrays::FFFF}}; auto packet = SizedArrayEnumBuilder::Create(sized_array); ASSERT_EQ(sized_array_enum.size(), packet->size()); @@ -534,13 +550,13 @@ TEST(GeneratedPacketTest, testSizedArrayEnum) { namespace { vector count_array_enum{ - 0x03, // _count_ - 0x01, // ONE - 0x00, - 0x02, // TWO_THREE - 0x03, - 0xff, // FFFF - 0xff, + 0x03, // _count_ + 0x01, // ONE + 0x00, + 0x02, // TWO_THREE + 0x03, + 0xff, // FFFF + 0xff, }; } @@ -571,11 +587,15 @@ TEST(GeneratedPacketTest, testCountArrayEnum) { TEST(GeneratedPacketTest, testFixedSizeByteArray) { constexpr std::size_t byte_array_size = 32; std::array byte_array; - for (uint8_t i = 0; i < byte_array_size; i++) byte_array[i] = i; + for (uint8_t i = 0; i < byte_array_size; i++) { + byte_array[i] = i; + } constexpr int word_array_size = 8; std::array word_array; - for (uint32_t i = 0; i < word_array_size; i++) word_array[i] = i; + for (uint32_t i = 0; i < word_array_size; i++) { + word_array[i] = i; + } auto packet = PacketWithFixedArraysOfBytesBuilder::Create(byte_array, word_array); ASSERT_EQ((size_t)(2 * (256 / 8)), packet->size()); @@ -607,7 +627,7 @@ TEST(GeneratedPacketTest, testFixedSizeByteArray) { } vector one_variable{ - 0x03, 'o', 'n', 'e', // "one" + 0x03, 'o', 'n', 'e', // "one" }; TEST(GeneratedPacketTest, testOneVariableField) { @@ -633,11 +653,12 @@ TEST(GeneratedPacketTest, testOneVariableField) { } vector fou_variable{ - 0x04, 'f', 'o', 'u', // too short + 0x04, 'f', 'o', 'u', // too short }; TEST(GeneratedPacketTest, testOneVariableFieldTooShort) { - std::shared_ptr> packet_bytes = std::make_shared>(fou_variable); + std::shared_ptr> packet_bytes = + std::make_shared>(fou_variable); PacketView packet_bytes_view(packet_bytes); auto view = OneVariableView::Create(packet_bytes_view); ASSERT_TRUE(view.IsValid()); @@ -646,10 +667,10 @@ TEST(GeneratedPacketTest, testOneVariableFieldTooShort) { } vector sized_array_variable{ - 0x0e, // _size_ - 0x03, 'o', 'n', 'e', // "one" - 0x03, 't', 'w', 'o', // "two" - 0x05, 't', 'h', 'r', 'e', 'e', // "three" + 0x0e, // _size_ + 0x03, 'o', 'n', 'e', // "one" + 0x03, 't', 'w', 'o', // "two" + 0x05, 't', 'h', 'r', 'e', 'e', // "three" }; TEST(GeneratedPacketTest, testSizedArrayVariableLength) { @@ -681,10 +702,10 @@ TEST(GeneratedPacketTest, testSizedArrayVariableLength) { } vector sized_array_variable_too_short{ - 0x0e, // _size_ - 0x03, 'o', 'n', 'e', // "one" - 0x03, 't', 'w', 'o', // "two" - 0x06, 't', 'h', 'r', 'e', 'e', // "three" needs another letter to be length 6 + 0x0e, // _size_ + 0x03, 'o', 'n', 'e', // "one" + 0x03, 't', 'w', 'o', // "two" + 0x06, 't', 'h', 'r', 'e', 'e', // "three" needs another letter to be length 6 }; TEST(GeneratedPacketTest, testSizedArrayVariableLengthLastBad) { @@ -693,7 +714,7 @@ TEST(GeneratedPacketTest, testSizedArrayVariableLengthLastBad) { sized_array.emplace_back("two"); std::shared_ptr> packet_bytes = - std::make_shared>(sized_array_variable_too_short); + std::make_shared>(sized_array_variable_too_short); PacketView packet_bytes_view(packet_bytes); auto view = SizedArrayVariableView::Create(packet_bytes_view); @@ -706,10 +727,10 @@ TEST(GeneratedPacketTest, testSizedArrayVariableLengthLastBad) { } vector sized_array_variable_first_too_short{ - 0x0e, // _size_ - 0x02, 'o', 'n', 'e', // "on" - 0x03, 't', 'w', 'o', // "two" - 0x05, 't', 'h', 'r', 'e', 'e', // "three" + 0x0e, // _size_ + 0x02, 'o', 'n', 'e', // "on" + 0x03, 't', 'w', 'o', // "two" + 0x05, 't', 'h', 'r', 'e', 'e', // "three" }; TEST(GeneratedPacketTest, testSizedArrayVariableLengthFirstBad) { @@ -717,7 +738,7 @@ TEST(GeneratedPacketTest, testSizedArrayVariableLengthFirstBad) { sized_array.emplace_back("on"); std::shared_ptr> packet_bytes = - std::make_shared>(sized_array_variable_first_too_short); + std::make_shared>(sized_array_variable_first_too_short); PacketView packet_bytes_view(packet_bytes); auto view = SizedArrayVariableView::Create(packet_bytes_view); @@ -730,16 +751,16 @@ TEST(GeneratedPacketTest, testSizedArrayVariableLengthFirstBad) { } vector fixed_array_variable{ - 0x03, 'o', 'n', 'e', // "one" - 0x03, 't', 'w', 'o', // "two" - 0x05, 't', 'h', 'r', 'e', 'e', // "three" - 0x04, 'f', 'o', 'u', 'r', // "four" - 0x04, 'f', 'i', 'v', 'e', // "five" + 0x03, 'o', 'n', 'e', // "one" + 0x03, 't', 'w', 'o', // "two" + 0x05, 't', 'h', 'r', 'e', 'e', // "three" + 0x04, 'f', 'o', 'u', 'r', // "four" + 0x04, 'f', 'i', 'v', 'e', // "five" }; TEST(GeneratedPacketTest, testFixedArrayVariableLength) { - std::array fixed_array{std::string("one"), std::string("two"), std::string("three"), std::string("four"), - std::string("five")}; + std::array fixed_array{std::string("one"), std::string("two"), std::string("three"), + std::string("four"), std::string("five")}; auto packet = FixedArrayVariableBuilder::Create(fixed_array); ASSERT_EQ(fixed_array_variable.size(), packet->size()); @@ -764,11 +785,11 @@ TEST(GeneratedPacketTest, testFixedArrayVariableLength) { } vector fixed_array_variable_too_short{ - 0x03, 'o', 'n', 'e', // "one" - 0x03, 't', 'w', 'o', // "two" - 0x05, 't', 'h', 'r', 'e', 'e', // "three" - 0x04, 'f', 'o', 'u', 'r', // "four" - 0x05, 'f', 'i', 'v', 'e', // "five" + 0x03, 'o', 'n', 'e', // "one" + 0x03, 't', 'w', 'o', // "two" + 0x05, 't', 'h', 'r', 'e', 'e', // "three" + 0x04, 'f', 'o', 'u', 'r', // "four" + 0x05, 'f', 'i', 'v', 'e', // "five" }; TEST(GeneratedPacketTest, testFixedArrayVariableLengthTooShort) { @@ -776,7 +797,7 @@ TEST(GeneratedPacketTest, testFixedArrayVariableLengthTooShort) { std::string("four")}; std::shared_ptr> packet_bytes = - std::make_shared>(fixed_array_variable_too_short); + std::make_shared>(fixed_array_variable_too_short); PacketView packet_bytes_view(packet_bytes); auto view = FixedArrayVariableView::Create(packet_bytes_view); @@ -789,11 +810,11 @@ TEST(GeneratedPacketTest, testFixedArrayVariableLengthTooShort) { } vector count_array_variable{ - 0x04, // _count_ - 0x03, 'o', 'n', 'e', // "one" - 0x03, 't', 'w', 'o', // "two" - 0x05, 't', 'h', 'r', 'e', 'e', // "three" - 0x04, 'f', 'o', 'u', 'r', // "four" + 0x04, // _count_ + 0x03, 'o', 'n', 'e', // "one" + 0x03, 't', 'w', 'o', // "two" + 0x05, 't', 'h', 'r', 'e', 'e', // "three" + 0x04, 'f', 'o', 'u', 'r', // "four" }; TEST(GeneratedPacketTest, testCountArrayVariableLength) { @@ -826,12 +847,12 @@ TEST(GeneratedPacketTest, testCountArrayVariableLength) { } vector count_array_variable_extra{ - 0x04, // _count_ - 0x03, 'o', 'n', 'e', // "one" - 0x03, 't', 'w', 'o', // "two" - 0x05, 't', 'h', 'r', 'e', 'e', // "three" - 0x04, 'f', 'o', 'u', 'r', // "four" - 0x04, 'x', 't', 'r', 'a', // "xtra" + 0x04, // _count_ + 0x03, 'o', 'n', 'e', // "one" + 0x03, 't', 'w', 'o', // "two" + 0x05, 't', 'h', 'r', 'e', 'e', // "three" + 0x04, 'f', 'o', 'u', 'r', // "four" + 0x04, 'x', 't', 'r', 'a', // "xtra" }; TEST(GeneratedPacketTest, testCountArrayVariableLengthExtraData) { @@ -842,7 +863,7 @@ TEST(GeneratedPacketTest, testCountArrayVariableLengthExtraData) { count_array.emplace_back("four"); std::shared_ptr> packet_bytes = - std::make_shared>(count_array_variable_extra); + std::make_shared>(count_array_variable_extra); PacketView packet_bytes_view(packet_bytes); auto view = CountArrayVariableView::Create(packet_bytes_view); @@ -855,10 +876,10 @@ TEST(GeneratedPacketTest, testCountArrayVariableLengthExtraData) { } vector count_array_variable_too_few{ - 0x04, // _count_ - 0x03, 'o', 'n', 'e', // "one" - 0x03, 't', 'w', 'o', // "two" - 0x05, 't', 'h', 'r', 'e', 'e', // "three" + 0x04, // _count_ + 0x03, 'o', 'n', 'e', // "one" + 0x03, 't', 'w', 'o', // "two" + 0x05, 't', 'h', 'r', 'e', 'e', // "three" }; TEST(GeneratedPacketTest, testCountArrayVariableLengthMissingData) { @@ -868,7 +889,7 @@ TEST(GeneratedPacketTest, testCountArrayVariableLengthMissingData) { count_array.emplace_back("three"); std::shared_ptr> packet_bytes = - std::make_shared>(count_array_variable_too_few); + std::make_shared>(count_array_variable_too_few); PacketView packet_bytes_view(packet_bytes); auto view = CountArrayVariableView::Create(packet_bytes_view); @@ -881,7 +902,7 @@ TEST(GeneratedPacketTest, testCountArrayVariableLengthMissingData) { } vector one_struct{ - 0x01, 0x02, 0x03, // id = 0x01, count = 0x0302 + 0x01, 0x02, 0x03, // id = 0x01, count = 0x0302 }; TEST(GeneratedPacketTest, testOneStruct) { @@ -914,8 +935,8 @@ TEST(GeneratedPacketTest, testOneStruct) { } vector two_structs{ - 0x01, 0x01, 0x02, // id, id * 0x0201 - 0x02, 0x02, 0x04, + 0x01, 0x01, 0x02, // id, id * 0x0201 + 0x02, 0x02, 0x04, }; TEST(GeneratedPacketTest, testTwoStructs) { @@ -951,9 +972,9 @@ TEST(GeneratedPacketTest, testTwoStructs) { } vector array_or_vector_of_struct{ - 0x04, // _count_ - 0x01, 0x01, 0x02, // id, id * 0x0201 - 0x02, 0x02, 0x04, 0x03, 0x03, 0x06, 0x04, 0x04, 0x08, + 0x04, // _count_ + 0x01, 0x01, 0x02, // id, id * 0x0201 + 0x02, 0x02, 0x04, 0x03, 0x03, 0x06, 0x04, 0x04, 0x08, }; TEST(GeneratedPacketTest, testVectorOfStruct) { @@ -1035,12 +1056,12 @@ TEST(GeneratedPacketTest, testArrayOfStruct) { } vector one_fixed_types_struct{ - 0x05, // four_bits = FIVE, reserved - 0xf3, // _fixed_ - 0x0d, // id = 0x0d - 0x01, 0x02, 0x03, // array = { 1, 2, 3} - 0x06, 0x01, // example_checksum - 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, // six_bytes + 0x05, // four_bits = FIVE, reserved + 0xf3, // _fixed_ + 0x0d, // id = 0x0d + 0x01, 0x02, 0x03, // array = { 1, 2, 3} + 0x06, 0x01, // example_checksum + 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, // six_bytes }; TEST(GeneratedPacketTest, testOneFixedTypesStruct) { @@ -1073,11 +1094,11 @@ TEST(GeneratedPacketTest, testOneFixedTypesStruct) { } vector array_of_struct_and_another{ - 0x03, // _count_ - 0x01, 0x01, 0x02, // id, id * 0x0201 - 0x02, 0x02, 0x04, // 2 - 0x03, 0x03, 0x06, // 3 - 0x04, 0x04, 0x08, // Another + 0x03, // _count_ + 0x01, 0x01, 0x02, // id, id * 0x0201 + 0x02, 0x02, 0x04, // 2 + 0x03, 0x03, 0x06, // 3 + 0x04, 0x04, 0x08, // Another }; TEST(GeneratedPacketTest, testArrayOfStructAndAnother) { @@ -1122,7 +1143,7 @@ DEFINE_AND_INSTANTIATE_OneArrayOfStructAndAnotherStructReflectionTest(array_of_s TEST(GeneratedPacketTest, testOneArrayOfStructAndAnotherStruct) { std::shared_ptr> packet_bytes = - std::make_shared>(array_of_struct_and_another); + std::make_shared>(array_of_struct_and_another); PacketView packet_bytes_view(packet_bytes); auto view = OneArrayOfStructAndAnotherStructView::Create(packet_bytes_view); @@ -1134,19 +1155,20 @@ TEST(GeneratedPacketTest, testOneArrayOfStructAndAnotherStruct) { } vector sized_array_of_struct_and_another{ - 0x09, // _size_ - 0x01, 0x01, 0x02, // id, id * 0x0201 - 0x02, 0x02, 0x04, // 2 - 0x03, 0x03, 0x06, // 3 - 0x04, 0x04, 0x08, // Another + 0x09, // _size_ + 0x01, 0x01, 0x02, // id, id * 0x0201 + 0x02, 0x02, 0x04, // 2 + 0x03, 0x03, 0x06, // 3 + 0x04, 0x04, 0x08, // Another }; -DEFINE_AND_INSTANTIATE_OneSizedArrayOfStructAndAnotherStructReflectionTest(sized_array_of_struct_and_another); +DEFINE_AND_INSTANTIATE_OneSizedArrayOfStructAndAnotherStructReflectionTest( + sized_array_of_struct_and_another); vector bit_field_group_packet{ - // seven_bits_ = 0x77, straddle_ = 0x5, five_bits_ = 0x15 - 0xf7, // 0x77 | (0x5 & 0x1) << 7 - 0xaa, // 0x15 << 3 | (0x5 >> 1) + // seven_bits_ = 0x77, straddle_ = 0x5, five_bits_ = 0x15 + 0xf7, // 0x77 | (0x5 & 0x1) << 7 + 0xaa, // 0x15 << 3 | (0x5 >> 1) }; TEST(GeneratedPacketTest, testBitFieldGroupPacket) { @@ -1175,9 +1197,9 @@ TEST(GeneratedPacketTest, testBitFieldGroupPacket) { } vector bit_field_packet{ - // seven_bits_ = 0x77, straddle_ = 0x5, five_bits_ = 0x15 - 0xf7, // 0x77 | (0x5 & 0x1) << 7 - 0xaa, // 0x15 << 3 | (0x5 >> 1) + // seven_bits_ = 0x77, straddle_ = 0x5, five_bits_ = 0x15 + 0xf7, // 0x77 | (0x5 & 0x1) << 7 + 0xaa, // 0x15 << 3 | (0x5 >> 1) }; TEST(GeneratedPacketTest, testBitFieldPacket) { @@ -1208,10 +1230,10 @@ TEST(GeneratedPacketTest, testBitFieldPacket) { } vector bit_field_group_after_unsized_array_packet{ - 0x01, 0x02, 0x03, 0x04, // byte array - // seven_bits_ = 0x77, straddle_ = 0x5, five_bits_ = 0x15 - 0xf7, // 0x77 | (0x5 & 0x1) << 7 - 0xaa, // 0x15 << 3 | (0x5 >> 1) + 0x01, 0x02, 0x03, 0x04, // byte array + // seven_bits_ = 0x77, straddle_ = 0x5, five_bits_ = 0x15 + 0xf7, // 0x77 | (0x5 & 0x1) << 7 + 0xaa, // 0x15 << 3 | (0x5 >> 1) }; TEST(GeneratedPacketTest, testBitFieldGroupAfterUnsizedArrayPacket) { @@ -1223,7 +1245,8 @@ TEST(GeneratedPacketTest, testBitFieldGroupAfterUnsizedArrayPacket) { uint8_t straddle = 0x5; uint8_t five_bits = 0x15; - auto packet = BitFieldGroupAfterUnsizedArrayPacketBuilder::Create(count_array, seven_bits, straddle, five_bits); + auto packet = BitFieldGroupAfterUnsizedArrayPacketBuilder::Create(count_array, seven_bits, + straddle, five_bits); ASSERT_EQ(bit_field_group_after_unsized_array_packet.size(), packet->size()); std::shared_ptr> packet_bytes = std::make_shared>(); @@ -1255,10 +1278,10 @@ TEST(GeneratedPacketTest, testBitFieldGroupAfterUnsizedArrayPacket) { } vector bit_field_after_unsized_array_packet{ - 0x01, 0x02, 0x03, 0x04, // byte array - // seven_bits_ = 0x77, straddle_ = 0x5, five_bits_ = 0x15 - 0xf7, // 0x77 | (0x5 & 0x1) << 7 - 0xaa, // 0x15 << 3 | (0x5 >> 1) + 0x01, 0x02, 0x03, 0x04, // byte array + // seven_bits_ = 0x77, straddle_ = 0x5, five_bits_ = 0x15 + 0xf7, // 0x77 | (0x5 & 0x1) << 7 + 0xaa, // 0x15 << 3 | (0x5 >> 1) }; TEST(GeneratedPacketTest, testBitFieldAfterUnsizedArrayPacket) { @@ -1305,18 +1328,18 @@ TEST(GeneratedPacketTest, testBitFieldAfterUnsizedArrayPacket) { } vector bit_field_array_packet{ - 0x06, // _size_(array) - // seven_bits_ = 0x77, straddle_ = 0x5, five_bits_ = 0x15 - 0xf7, // 0x77 | (0x5 & 0x1) << 7 - 0xaa, // 0x15 << 3 | (0x5 >> 1) - - // seven_bits_ = 0x78, straddle_ = 0x6, five_bits_ = 0x16 - 0x78, // 0x78 | (0x6 & 0x1) << 7 - 0xb3, // 0x16 << 3 | (0x6 >> 1) - - // seven_bits_ = 0x79, straddle_ = 0x7, five_bits_ = 0x17 - 0xf9, // 0x79 | (0x7 & 0x1) << 7 - 0xbb, // 0x17 << 3 | (0x7 >> 1) + 0x06, // _size_(array) + // seven_bits_ = 0x77, straddle_ = 0x5, five_bits_ = 0x15 + 0xf7, // 0x77 | (0x5 & 0x1) << 7 + 0xaa, // 0x15 << 3 | (0x5 >> 1) + + // seven_bits_ = 0x78, straddle_ = 0x6, five_bits_ = 0x16 + 0x78, // 0x78 | (0x6 & 0x1) << 7 + 0xb3, // 0x16 << 3 | (0x6 >> 1) + + // seven_bits_ = 0x79, straddle_ = 0x7, five_bits_ = 0x17 + 0xf9, // 0x79 | (0x7 & 0x1) << 7 + 0xbb, // 0x17 << 3 | (0x7 >> 1) }; TEST(GeneratedPacketTest, testBitFieldArrayPacket) { @@ -1354,7 +1377,8 @@ TEST(GeneratedPacketTest, testBitFieldArrayPacket) { } TEST(GeneratedPacketTest, testNewBitFieldArrayPacket) { - PacketView packet_bytes_view(std::make_shared>(bit_field_array_packet)); + PacketView packet_bytes_view( + std::make_shared>(bit_field_array_packet)); auto view = BitFieldArrayPacketView::Create(packet_bytes_view); ASSERT_TRUE(view.IsValid()); @@ -1372,9 +1396,11 @@ std::vector child_two_two_two_ = {0x20, 0x02}; std::vector child_two_two_three_ = {0x20, 0x03}; std::vector child_two_two_four_ = {0x20, 0x04}; -DEFINE_AND_INSTANTIATE_ParentTwoReflectionTest(child_two_two_two_, child_two_two_three_, child_two_two_four_); +DEFINE_AND_INSTANTIATE_ParentTwoReflectionTest(child_two_two_two_, child_two_two_three_, + child_two_two_four_); -DEFINE_AND_INSTANTIATE_ChildTwoTwoReflectionTest(child_two_two_two_, child_two_two_three_, child_two_two_four_); +DEFINE_AND_INSTANTIATE_ChildTwoTwoReflectionTest(child_two_two_two_, child_two_two_three_, + child_two_two_four_); DEFINE_AND_INSTANTIATE_ChildTwoTwoThreeReflectionTest(child_two_two_three_); @@ -1393,7 +1419,7 @@ DEFINE_AND_INSTANTIATE_OneVersionOneStructPacketReflectionTest(one_version_one_s DEFINE_AND_INSTANTIATE_OneVersionTwoStructPacketReflectionTest(one_version_two_struct_packet); vector one_struct_be{ - 0x01, 0x02, 0x03, // id = 0x01, count = 0x0203 + 0x01, 0x02, 0x03, // id = 0x01, count = 0x0203 }; TEST(GeneratedPacketTest, testOneStructBe) { @@ -1422,8 +1448,8 @@ TEST(GeneratedPacketTest, testOneStructBe) { } vector two_structs_be{ - 0x01, 0x01, 0x02, // id, id * 0x0102 - 0x02, 0x02, 0x04, + 0x01, 0x01, 0x02, // id, id * 0x0102 + 0x02, 0x02, 0x04, }; TEST(GeneratedPacketTest, testTwoStructsBe) { @@ -1459,9 +1485,9 @@ TEST(GeneratedPacketTest, testTwoStructsBe) { } vector array_of_struct_be{ - 0x04, // _count_ - 0x01, 0x01, 0x02, // id, id * 0x0102 - 0x02, 0x02, 0x04, 0x03, 0x03, 0x06, 0x04, 0x04, 0x08, + 0x04, // _count_ + 0x01, 0x01, 0x02, // id, id * 0x0102 + 0x02, 0x02, 0x04, 0x03, 0x03, 0x06, 0x04, 0x04, 0x08, }; TEST(GeneratedPacketTest, testArrayOfStructBe) { @@ -1498,8 +1524,8 @@ TEST(GeneratedPacketTest, testArrayOfStructBe) { } vector one_four_byte_struct{ - 0x04, // struct_type_ = FourByte - 0xd1, 0xd2, 0xd3, 0xd4, // four_bytes_ + 0x04, // struct_type_ = FourByte + 0xd1, 0xd2, 0xd3, 0xd4, // four_bytes_ }; TEST(GeneratedPacketTest, testOneFourByteStruct) { @@ -1525,13 +1551,14 @@ TEST(GeneratedPacketTest, testOneFourByteStruct) { } vector generic_struct_two{ - 0x02, // struct_type_ = TwoByte - 0x01, 0x02, // two_bytes_ + 0x02, // struct_type_ = TwoByte + 0x01, 0x02, // two_bytes_ }; TEST(GeneratedPacketTest, testOneGenericStructTwo) { TwoByteStruct two_byte_struct(0x0201); - std::unique_ptr two_byte_struct_ptr = std::make_unique(two_byte_struct); + std::unique_ptr two_byte_struct_ptr = + std::make_unique(two_byte_struct); auto packet = OneGenericStructBuilder::Create(std::move(two_byte_struct_ptr)); ASSERT_EQ(generic_struct_two.size(), packet->size()); @@ -1561,13 +1588,14 @@ TEST(GeneratedPacketTest, testOneGenericStructTwo) { } vector generic_struct_four{ - 0x04, // struct_type_ = FourByte - 0x01, 0x02, 0x03, 0x04, // four_bytes_ + 0x04, // struct_type_ = FourByte + 0x01, 0x02, 0x03, 0x04, // four_bytes_ }; TEST(GeneratedPacketTest, testOneGenericStructFour) { FourByteStruct four_byte_struct(0x04030201); - std::unique_ptr four_byte_struct_p = std::make_unique(four_byte_struct); + std::unique_ptr four_byte_struct_p = + std::make_unique(four_byte_struct); ASSERT_EQ(four_byte_struct.four_bytes_, four_byte_struct_p->four_bytes_); auto packet = OneGenericStructBuilder::Create(std::move(four_byte_struct_p)); @@ -1592,14 +1620,14 @@ TEST(GeneratedPacketTest, testOneGenericStructFour) { } vector one_struct_array{ - 0x04, // struct_type_ = FourByte - 0xa1, 0xa2, 0xa3, 0xa4, // four_bytes_ - 0x04, // struct_type_ = FourByte - 0xb2, 0xb2, 0xb3, 0xb4, // four_bytes_ - 0x02, // struct_type_ = TwoByte - 0xc3, 0xc2, // two_bytes_ - 0x04, // struct_type_ = TwoByte - 0xd4, 0xd2, 0xd3, 0xd4, // four_bytes_ + 0x04, // struct_type_ = FourByte + 0xa1, 0xa2, 0xa3, 0xa4, // four_bytes_ + 0x04, // struct_type_ = FourByte + 0xb2, 0xb2, 0xb3, 0xb4, // four_bytes_ + 0x02, // struct_type_ = TwoByte + 0xc3, 0xc2, // two_bytes_ + 0x04, // struct_type_ = TwoByte + 0xd4, 0xd2, 0xd3, 0xd4, // four_bytes_ }; TEST(GeneratedPacketTest, testOneGenericStructArray) { @@ -1711,31 +1739,31 @@ TEST(GeneratedPacketTest, testOneGenericStructFourArray) { } vector one_struct_array_after_fixed{ - 0x01, 0x02, // two_bytes = 0x0201 - 0x04, // struct_type_ = FourByte - 0xa1, 0xa2, 0xa3, 0xa4, // four_bytes_ - 0x04, // struct_type_ = FourByte - 0xb2, 0xb2, 0xb3, 0xb4, // four_bytes_ - 0x02, // struct_type_ = TwoByte - 0xc3, 0xc2, // two_bytes_ - 0x04, // struct_type_ = TwoByte - 0xd4, 0xd2, 0xd3, 0xd4, // four_bytes_ + 0x01, 0x02, // two_bytes = 0x0201 + 0x04, // struct_type_ = FourByte + 0xa1, 0xa2, 0xa3, 0xa4, // four_bytes_ + 0x04, // struct_type_ = FourByte + 0xb2, 0xb2, 0xb3, 0xb4, // four_bytes_ + 0x02, // struct_type_ = TwoByte + 0xc3, 0xc2, // two_bytes_ + 0x04, // struct_type_ = TwoByte + 0xd4, 0xd2, 0xd3, 0xd4, // four_bytes_ }; DEFINE_AND_INSTANTIATE_OneGenericStructArrayAfterFixedReflectionTest(one_struct_array_after_fixed); vector one_length_type_value_struct{ - // _size_(value):16 type value - 0x04, 0x00, 0x01, 'o', 'n', 'e', // ONE - 0x04, 0x00, 0x02, 't', 'w', 'o', // TWO - 0x06, 0x00, 0x03, 't', 'h', 'r', 'e', 'e', // THREE + // _size_(value):16 type value + 0x04, 0x00, 0x01, 'o', 'n', 'e', // ONE + 0x04, 0x00, 0x02, 't', 'w', 'o', // TWO + 0x06, 0x00, 0x03, 't', 'h', 'r', 'e', 'e', // THREE }; DEFINE_AND_INSTANTIATE_OneLengthTypeValueStructReflectionTest(one_length_type_value_struct); TEST(GeneratedPacketTest, testOneLengthTypeValueStruct) { std::shared_ptr> packet_bytes = - std::make_shared>(one_length_type_value_struct); + std::make_shared>(one_length_type_value_struct); PacketView packet_bytes_view(packet_bytes); auto view = OneLengthTypeValueStructView::Create(packet_bytes_view); @@ -1763,23 +1791,23 @@ TEST(GeneratedPacketTest, testOneLengthTypeValueStruct) { } vector one_length_type_value_struct_padded_10{ - 0x20, // _size_(payload), - 0x14, // valid bytes - 0x04, 0x00, 0x01, 'o', 'n', 'e', // ONE - 0x04, 0x00, 0x02, 't', 'w', 'o', // TWO - 0x06, 0x00, 0x03, 't', 'h', 'r', 'e', 'e', // THREE - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // padding to 30 - 0x20, // after padding + 0x20, // _size_(payload), + 0x14, // valid bytes + 0x04, 0x00, 0x01, 'o', 'n', 'e', // ONE + 0x04, 0x00, 0x02, 't', 'w', 'o', // TWO + 0x06, 0x00, 0x03, 't', 'h', 'r', 'e', 'e', // THREE + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // padding to 30 + 0x20, // after padding }; vector one_length_type_value_struct_padded_18{ - 0x20, // _size_(payload), - 0x0C, // valid bytes - 0x04, 0x00, 0x01, 'o', 'n', 'e', // ONE - 0x04, 0x00, 0x02, 't', 'w', 'o', // TWO - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // padding to 20 - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // padding to 30 - 0x20, // after padding + 0x20, // _size_(payload), + 0x0C, // valid bytes + 0x04, 0x00, 0x01, 'o', 'n', 'e', // ONE + 0x04, 0x00, 0x02, 't', 'w', 'o', // TWO + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // padding to 20 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // padding to 30 + 0x20, // after padding }; // TODO: Revisit LTV parsing. Right now, the padding bytes are parsed @@ -1791,16 +1819,16 @@ TEST(GeneratedPacketTest, testOneLengthTypeValueStructPaddedGeneration) { LengthTypeValueStruct ltv; ltv.type_ = DataType::ONE; ltv.value_ = { - 'o', - 'n', - 'e', + 'o', + 'n', + 'e', }; ltv_vector.push_back(ltv); ltv.type_ = DataType::TWO; ltv.value_ = { - 't', - 'w', - 'o', + 't', + 'w', + 'o', }; ltv_vector.push_back(ltv); uint8_t after_padding = 0x20; @@ -1818,7 +1846,8 @@ TEST(GeneratedPacketTest, testOneLengthTypeValueStructPaddedGeneration) { } PacketView packet_bytes_view(packet_bytes); - auto view = OneLengthTypeValueStructPaddedView::Create(SizedParentView::Create(packet_bytes_view)); + auto view = + OneLengthTypeValueStructPaddedView::Create(SizedParentView::Create(packet_bytes_view)); ASSERT_TRUE(view.IsValid()); auto an_array = view.GetOneArray(); // TODO: Revisit LTV parsing. Right now, the padding bytes are parsed @@ -1831,30 +1860,30 @@ TEST(GeneratedPacketTest, testOneLengthTypeValueStructPaddedGeneration) { } vector byte_sized{ - 0x11, // 1 - 0x21, 0x22, // 2 - 0x31, 0x32, 0x33, // 3 - 0x41, 0x42, 0x43, 0x44, // 4 - 0x51, 0x52, 0x53, 0x54, 0x55, // 5 - 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, // 6 - 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, // 7 - 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, // 8 + 0x11, // 1 + 0x21, 0x22, // 2 + 0x31, 0x32, 0x33, // 3 + 0x41, 0x42, 0x43, 0x44, // 4 + 0x51, 0x52, 0x53, 0x54, 0x55, // 5 + 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, // 6 + 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, // 7 + 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, // 8 }; TEST(GeneratedPacketTest, testByteSizedFields) { uint64_t array[9]{ - 0xbadbadbad, - 0x11, // 1 - 0x2221, // 2 - 0x333231, // 3 - 0x44434241, // 4 - 0x5554535251, // 5 - 0x666564636261, // 6 - 0x77767574737271, // 7 - 0x8887868584838281, // 8 + 0xbadbadbad, + 0x11, // 1 + 0x2221, // 2 + 0x333231, // 3 + 0x44434241, // 4 + 0x5554535251, // 5 + 0x666564636261, // 6 + 0x77767574737271, // 7 + 0x8887868584838281, // 8 }; - auto packet = - ByteSizedFieldsBuilder::Create(array[1], array[2], array[3], array[4], array[5], array[6], array[7], array[8]); + auto packet = ByteSizedFieldsBuilder::Create(array[1], array[2], array[3], array[4], array[5], + array[6], array[7], array[8]); ASSERT_EQ(byte_sized.size(), packet->size()); std::shared_ptr> packet_bytes = std::make_shared>(); @@ -1893,9 +1922,9 @@ TEST(GeneratedPacketTest, testOneGenericStructArrayNoZeroEmpty) { } std::vector a_two_byte_struct = { - static_cast(StructTypeNoZero::TWO_BYTE), - 0x01, - 0x02, + static_cast(StructTypeNoZero::TWO_BYTE), + 0x01, + 0x02, }; too_few_bytes = std::make_shared>(a_two_byte_struct); view = OneGenericStructArrayNoZeroView::Create(PacketView(too_few_bytes)); @@ -1930,10 +1959,12 @@ TEST(GeneratedPacketTest, testToStringOutput) { ASSERT_TRUE(view.IsValid()); ASSERT_EQ( - "ArrayOfStructBe { array_count = 0x4, array = VECTOR[TwoRelatedNumbersBe { id = 0x1, count = 0x102 }, " - "TwoRelatedNumbersBe { id = 0x2, count = 0x204 }, TwoRelatedNumbersBe { id = 0x3, count = 0x306 }, " - "TwoRelatedNumbersBe { id = 0x4, count = 0x408 }] }", - view.ToString()); + "ArrayOfStructBe { array_count = 0x4, array = VECTOR[TwoRelatedNumbersBe { id = 0x1, " + "count = 0x102 }, " + "TwoRelatedNumbersBe { id = 0x2, count = 0x204 }, TwoRelatedNumbersBe { id = 0x3, count " + "= 0x306 }, " + "TwoRelatedNumbersBe { id = 0x4, count = 0x408 }] }", + view.ToString()); } TEST(GeneratedPacketTest, testEnumText) { @@ -1967,9 +1998,9 @@ TEST(GeneratedPacketTest, testToStringOneFixedTypesStruct) { ASSERT_TRUE(view.IsValid()); ASSERT_EQ( - "OneFixedTypesStruct { one = StructWithFixedTypes { four_bits = FIVE(0x5), id = 0xd, " - "array = ARRAY[0x1, 0x2, 0x3], example_checksum = CHECKSUM, six_bytes = SixBytes } }", - view.ToString()); + "OneFixedTypesStruct { one = StructWithFixedTypes { four_bits = FIVE(0x5), id = 0xd, " + "array = ARRAY[0x1, 0x2, 0x3], example_checksum = CHECKSUM, six_bytes = SixBytes } }", + view.ToString()); } TEST(GeneratedPacketTest, testCreateOptional) { diff --git a/system/gd/packet/parser/test/simple_sum.h b/system/gd/packet/parser/test/simple_sum.h index 95c4888f43f..aea94488039 100644 --- a/system/gd/packet/parser/test/simple_sum.h +++ b/system/gd/packet/parser/test/simple_sum.h @@ -24,20 +24,14 @@ namespace parser { namespace test { class SimpleSum { - public: - void Initialize() { - sum = 0; - } +public: + void Initialize() { sum = 0; } - void AddByte(uint8_t byte) { - sum += byte; - } + void AddByte(uint8_t byte) { sum += byte; } - uint16_t GetChecksum() const { - return sum; - } + uint16_t GetChecksum() const { return sum; } - private: +private: uint16_t sum; }; diff --git a/system/gd/packet/parser/test/six_bytes.cc b/system/gd/packet/parser/test/six_bytes.cc index e3b4b81187f..51228683185 100644 --- a/system/gd/packet/parser/test/six_bytes.cc +++ b/system/gd/packet/parser/test/six_bytes.cc @@ -23,9 +23,7 @@ namespace packet { namespace parser { namespace test { -SixBytes::SixBytes(const uint8_t (&six)[6]) { - std::copy(six, six + kLength, six_bytes); -}; +SixBytes::SixBytes(const uint8_t (&six)[6]) { std::copy(six, six + kLength, six_bytes); } } // namespace test } // namespace parser diff --git a/system/gd/packet/parser/test/six_bytes.h b/system/gd/packet/parser/test/six_bytes.h index 510ea757fd6..c8b3ea82934 100644 --- a/system/gd/packet/parser/test/six_bytes.h +++ b/system/gd/packet/parser/test/six_bytes.h @@ -19,6 +19,7 @@ #pragma once #include + #include #include "packet/custom_field_fixed_size_interface.h" @@ -29,7 +30,7 @@ namespace parser { namespace test { class SixBytes final : public packet::CustomFieldFixedSizeInterface { - public: +public: static constexpr size_t kLength = 6; uint8_t six_bytes[kLength] = {}; @@ -37,35 +38,21 @@ class SixBytes final : public packet::CustomFieldFixedSizeInterface { SixBytes() = default; SixBytes(const uint8_t (&addr)[6]); - inline uint8_t* data() override { - return six_bytes; - } + inline uint8_t* data() override { return six_bytes; } - inline const uint8_t* data() const override { - return six_bytes; - } + inline const uint8_t* data() const override { return six_bytes; } bool operator<(const SixBytes& rhs) const { - return (std::memcmp(six_bytes, rhs.six_bytes, sizeof(six_bytes)) < 0); + return std::memcmp(six_bytes, rhs.six_bytes, sizeof(six_bytes)) < 0; } bool operator==(const SixBytes& rhs) const { - return (std::memcmp(six_bytes, rhs.six_bytes, sizeof(six_bytes)) == 0); - } - bool operator>(const SixBytes& rhs) const { - return (rhs < *this); - } - bool operator<=(const SixBytes& rhs) const { - return !(*this > rhs); - } - bool operator>=(const SixBytes& rhs) const { - return !(*this < rhs); - } - bool operator!=(const SixBytes& rhs) const { - return !(*this == rhs); - } - std::string ToString() const { - return "SixBytes"; + return std::memcmp(six_bytes, rhs.six_bytes, sizeof(six_bytes)) == 0; } + bool operator>(const SixBytes& rhs) const { return rhs < *this; } + bool operator<=(const SixBytes& rhs) const { return !(*this > rhs); } + bool operator>=(const SixBytes& rhs) const { return !(*this < rhs); } + bool operator!=(const SixBytes& rhs) const { return !(*this == rhs); } + std::string ToString() const { return "SixBytes"; } }; } // namespace test diff --git a/system/gd/packet/parser/test/variable.cc b/system/gd/packet/parser/test/variable.cc index aba8aae74cb..727d33a3926 100644 --- a/system/gd/packet/parser/test/variable.cc +++ b/system/gd/packet/parser/test/variable.cc @@ -38,9 +38,7 @@ void Variable::Serialize(BitInserter& bi) const { } } -size_t Variable::size() const { - return data.size() + 1; -} +size_t Variable::size() const { return data.size() + 1; } } // namespace test } // namespace parser } // namespace packet diff --git a/system/gd/packet/parser/test/variable.h b/system/gd/packet/parser/test/variable.h index 920c14fd1c9..febd3e63f76 100644 --- a/system/gd/packet/parser/test/variable.h +++ b/system/gd/packet/parser/test/variable.h @@ -19,6 +19,7 @@ #pragma once #include + #include #include #include @@ -32,7 +33,7 @@ namespace parser { namespace test { class Variable final { - public: +public: std::string data; Variable() = default; @@ -44,7 +45,8 @@ class Variable final { size_t size() const; template - static std::optional> Parse(Variable* instance, Iterator it) { + static std::optional> Parse(Variable* instance, + Iterator it) { if (it.NumBytesRemaining() < 1) { return {}; } @@ -63,9 +65,7 @@ class Variable final { return it; } - std::string ToString() const { - return data; - } + std::string ToString() const { return data; } }; } // namespace test diff --git a/system/gd/packet/parser/type_def.h b/system/gd/packet/parser/type_def.h index 811dca89ea1..9aa5c29731b 100644 --- a/system/gd/packet/parser/type_def.h +++ b/system/gd/packet/parser/type_def.h @@ -21,16 +21,14 @@ #include "fields/packet_field.h" class TypeDef { - public: +public: TypeDef(std::string name) : name_(name) {} TypeDef(std::string name, int size) : name_(name), size_(size) {} virtual ~TypeDef() = default; - std::string GetTypeName() const { - return name_; - } + std::string GetTypeName() const { return name_; } enum class Type { INVALID, diff --git a/system/gd/packet/parser/util.h b/system/gd/packet/parser/util.h index 918c0d43ca4..c65a5dc493a 100644 --- a/system/gd/packet/parser/util.h +++ b/system/gd/packet/parser/util.h @@ -32,11 +32,17 @@ inline std::string GetTypeForSize(int size) { ERROR() << __func__ << ": Cannot use a type larger than 64 bits. (" << size << ")\n"; } - if (size <= 8) return "uint8_t"; + if (size <= 8) { + return "uint8_t"; + } - if (size <= 16) return "uint16_t"; + if (size <= 16) { + return "uint16_t"; + } - if (size <= 32) return "uint32_t"; + if (size <= 32) { + return "uint32_t"; + } return "uint64_t"; } @@ -46,9 +52,15 @@ inline int RoundSizeUp(int size) { ERROR() << __func__ << ": Cannot use a type larger than 64 bits. (" << size << ")\n"; } - if (size <= 8) return 8; - if (size <= 16) return 16; - if (size <= 32) return 32; + if (size <= 8) { + return 8; + } + if (size <= 16) { + return 16; + } + if (size <= 32) { + return 32; + } return 64; } @@ -77,7 +89,8 @@ inline std::string CamelCaseToUnderScore(std::string value) { value.pop_back(); // Convert all characters to lowercase. - std::transform(value.begin(), value.end(), value.begin(), [](unsigned char c) { return std::tolower(c); }); + std::transform(value.begin(), value.end(), value.begin(), + [](unsigned char c) { return std::tolower(c); }); return value; } @@ -152,7 +165,8 @@ inline std::string StringJoin(const std::string& delimiter, const std::vector { - public: +public: RawBuilder() = default; explicit RawBuilder(size_t max_bytes); explicit RawBuilder(std::vector vec); @@ -66,7 +66,7 @@ class RawBuilder : public PacketBuilder { bool AddOctets6(uint64_t value); bool AddOctets8(uint64_t value); - private: +private: // Add |octets| bytes to the payload. Return true if: // - the value of |value| fits in |octets| bytes and // - the new size of the payload is still <= |max_bytes_| diff --git a/system/gd/packet/raw_builder_unittest.cc b/system/gd/packet/raw_builder_unittest.cc index 189c9f472e4..07beca80c41 100644 --- a/system/gd/packet/raw_builder_unittest.cc +++ b/system/gd/packet/raw_builder_unittest.cc @@ -17,6 +17,7 @@ #include "packet/raw_builder.h" #include + #include #include @@ -25,8 +26,9 @@ using std::vector; namespace { vector count = { - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, - 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, + 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, + 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, }; } // namespace @@ -35,7 +37,7 @@ namespace bluetooth { namespace packet { class RawBuilderTest : public ::testing::Test { - public: +public: RawBuilderTest() = default; ~RawBuilderTest() = default; }; diff --git a/system/gd/packet/view.cc b/system/gd/packet/view.cc index 73fc19ccde4..672d2f7769d 100644 --- a/system/gd/packet/view.cc +++ b/system/gd/packet/view.cc @@ -23,7 +23,8 @@ namespace bluetooth { namespace packet { View::View(std::shared_ptr> data, size_t begin, size_t end) - : data_(data), begin_(begin < data_->size() ? begin : data_->size()), + : data_(data), + begin_(begin < data_->size() ? begin : data_->size()), end_(end < data_->size() ? end : data_->size()) {} View::View(const View& view, size_t begin, size_t end) : data_(view.data_) { @@ -38,8 +39,6 @@ uint8_t View::operator[](size_t i) const { return data_->operator[](i + begin_); } -size_t View::size() const { - return end_ - begin_; -} +size_t View::size() const { return end_ - begin_; } } // namespace packet } // namespace bluetooth diff --git a/system/gd/packet/view.h b/system/gd/packet/view.h index 3b8b6793126..9ec8c4b1b19 100644 --- a/system/gd/packet/view.h +++ b/system/gd/packet/view.h @@ -25,7 +25,7 @@ namespace packet { // Base class that holds a shared pointer to data with bounds. class View { - public: +public: View(std::shared_ptr> data, size_t begin, size_t end); View(const View& view, size_t begin, size_t end); View(const View& view) = default; @@ -35,7 +35,7 @@ class View { size_t size() const; - private: +private: std::shared_ptr> data_; size_t begin_; size_t end_; diff --git a/system/gd/rust/topshim/btav/btav_shim.cc b/system/gd/rust/topshim/btav/btav_shim.cc index d4806c1d050..eb17f6ab618 100644 --- a/system/gd/rust/topshim/btav/btav_shim.cc +++ b/system/gd/rust/topshim/btav/btav_shim.cc @@ -32,100 +32,105 @@ namespace rusty = ::bluetooth::topshim::rust; namespace bluetooth::avrcp { class AvrcpMediaInterfaceImpl : public MediaInterface { - public: +public: void SendKeyEvent(uint8_t key, KeyState state) { rusty::avrcp_send_key_event(key, state == KeyState::PUSHED); } - void GetSongInfo(SongInfoCallback cb) override { - cb.Run(songInfo_); - } + void GetSongInfo(SongInfoCallback cb) override { cb.Run(songInfo_); } - void GetPlayStatus(PlayStatusCallback cb) override { - cb.Run(playStatus_); - } + void GetPlayStatus(PlayStatusCallback cb) override { cb.Run(playStatus_); } void GetNowPlayingList(NowPlayingCallback cb) override { cb.Run(currentSongId_, nowPlayingList_); } - void GetMediaPlayerList(MediaListCallback cb) override { - cb.Run(currentPlayer_, playerList_); - } + void GetMediaPlayerList(MediaListCallback cb) override { cb.Run(currentPlayer_, playerList_); } - void GetFolderItems( - [[maybe_unused]] uint16_t player_id, - [[maybe_unused]] std::string media_id, - [[maybe_unused]] FolderItemsCallback folder_cb) override {} + void GetFolderItems([[maybe_unused]] uint16_t player_id, [[maybe_unused]] std::string media_id, + [[maybe_unused]] FolderItemsCallback folder_cb) override {} - void SetBrowsedPlayer( - [[maybe_unused]] uint16_t player_id, [[maybe_unused]] SetBrowsedPlayerCallback browse_cb) override {} + void SetBrowsedPlayer([[maybe_unused]] uint16_t player_id, + [[maybe_unused]] SetBrowsedPlayerCallback browse_cb) override {} - void RegisterUpdateCallback(MediaCallbacks* callback) override { - mediaCb_ = callback; - } + void RegisterUpdateCallback(MediaCallbacks* callback) override { mediaCb_ = callback; } void UnregisterUpdateCallback([[maybe_unused]] MediaCallbacks* callback) override { mediaCb_ = nullptr; } - void PlayItem( - [[maybe_unused]] uint16_t player_id, - [[maybe_unused]] bool now_playing, - [[maybe_unused]] std::string media_id) override {} + void PlayItem([[maybe_unused]] uint16_t player_id, [[maybe_unused]] bool now_playing, + [[maybe_unused]] std::string media_id) override {} - void SetActiveDevice(const RawAddress& addr) override { - rusty::avrcp_set_active_device(addr); - } + void SetActiveDevice(const RawAddress& addr) override { rusty::avrcp_set_active_device(addr); } void SetPlaybackStatus(const PlayState& state) { playStatus_.state = state; - if (mediaCb_) mediaCb_->SendMediaUpdate(/*track_changed*/ false, /*play_state*/ true, /*queuefalse*/ false); + if (mediaCb_) { + mediaCb_->SendMediaUpdate(/*track_changed*/ false, /*play_state*/ true, /*queuefalse*/ false); + } } void SetPosition(int64_t position_us) { // Unit conversion from microsecond to millisecond. playStatus_.position = position_us / 1000; - if (mediaCb_) mediaCb_->SendMediaUpdate(/*track_changed*/ false, /*play_state*/ true, /*queuefalse*/ false); + if (mediaCb_) { + mediaCb_->SendMediaUpdate(/*track_changed*/ false, /*play_state*/ true, /*queuefalse*/ false); + } } - void SetMetadata(const std::string& title, const std::string& artist, const std::string& album, int64_t length_us) { + void SetMetadata(const std::string& title, const std::string& artist, const std::string& album, + int64_t length_us) { if (title.length() || artist.length() || album.length()) { songInfo_.attributes.clear(); // Reuse title for media_id, ideally this should be a shorter UID. songInfo_.media_id = title; - if (title.length()) songInfo_.attributes.emplace(avrcp::AttributeEntry(avrcp::Attribute::TITLE, title)); - if (artist.length()) songInfo_.attributes.emplace(avrcp::AttributeEntry(avrcp::Attribute::ARTIST_NAME, artist)); - if (album.length()) songInfo_.attributes.emplace(avrcp::AttributeEntry(avrcp::Attribute::ALBUM_NAME, album)); - // Floss's media implementation does not fully support the "Now Playing List," as Floss does not receive - // additional media information other than the current playing one. However, not all peripherals request metadata - // through the "Get Element Attributes" request. Instead, many get such information through the "Track Changed - // Notification." Hence, fill the playlist with one item here and have the Current Song ID always point to the - // only entry to support the track changed notification. + if (title.length()) { + songInfo_.attributes.emplace(avrcp::AttributeEntry(avrcp::Attribute::TITLE, title)); + } + if (artist.length()) { + songInfo_.attributes.emplace(avrcp::AttributeEntry(avrcp::Attribute::ARTIST_NAME, artist)); + } + if (album.length()) { + songInfo_.attributes.emplace(avrcp::AttributeEntry(avrcp::Attribute::ALBUM_NAME, album)); + } + // Floss's media implementation does not fully support the "Now Playing List," as Floss does + // not receive additional media information other than the current playing one. However, not + // all peripherals request metadata through the "Get Element Attributes" request. Instead, + // many get such information through the "Track Changed Notification." Hence, fill the + // playlist with one item here and have the Current Song ID always point to the only entry to + // support the track changed notification. nowPlayingList_.clear(); nowPlayingList_.emplace_back(songInfo_); currentSongId_ = songInfo_.media_id; - if (mediaCb_) mediaCb_->SendMediaUpdate(/*track_changed*/ true, /*play_state*/ false, /*queuefalse*/ false); + if (mediaCb_) { + mediaCb_->SendMediaUpdate(/*track_changed*/ true, /*play_state*/ false, + /*queuefalse*/ false); + } } if (length_us) { // Unit conversion from microsecond to millisecond. playStatus_.duration = length_us / 1000; - if (mediaCb_) mediaCb_->SendMediaUpdate(/*track_changed*/ false, /*play_state*/ true, /*queuefalse*/ false); + if (mediaCb_) { + mediaCb_->SendMediaUpdate(/*track_changed*/ false, /*play_state*/ true, + /*queuefalse*/ false); + } } } uint16_t AddPlayer(std::string name, bool browsing_supported) { playerList_.push_back(MediaPlayerInfo{player_id_, name, browsing_supported}); - if (mediaCb_) + if (mediaCb_) { mediaCb_->SendFolderUpdate( - /*available_players*/ true, /*addressed_players*/ true, /*uids_changed*/ false); + /*available_players*/ true, /*addressed_players*/ true, /*uids_changed*/ false); + } return player_id_++; } - private: +private: MediaCallbacks* mediaCb_; PlayStatus playStatus_; @@ -139,7 +144,7 @@ class AvrcpMediaInterfaceImpl : public MediaInterface { }; class VolumeInterfaceImpl : public VolumeInterface { - public: +public: void DeviceConnected(const RawAddress& addr) override { rusty::avrcp_device_connected(addr, /*absolute_volume_enabled=*/false); } @@ -156,19 +161,23 @@ class VolumeInterfaceImpl : public VolumeInterface { // Set TG's (Android, ChromeOS) volume. void SetVolume(int8_t volume) override { - if (volume < 0) return; + if (volume < 0) { + return; + } rusty::avrcp_absolute_volume_update(volume); } // Set CT's (headsets, speakers) volume. void SetDeviceVolume(int8_t volume) { - if (!volumeCb || volume < 0) return; + if (!volumeCb || volume < 0) { + return; + } volumeCb.Run(volume); } - private: +private: VolumeInterface::VolumeChangedCb volumeCb; }; @@ -182,35 +191,36 @@ static A2dpIntf* g_a2dpif; static AvrcpIntf* g_avrcpif; static A2dpCodecConfig to_rust_codec_config(const btav_a2dp_codec_config_t& config) { - A2dpCodecConfig rconfig = { - .codec_type = static_cast(config.codec_type), - .codec_priority = config.codec_priority, - .sample_rate = static_cast(config.sample_rate), - .bits_per_sample = static_cast(config.bits_per_sample), - .channel_mode = static_cast(config.channel_mode), - .codec_specific_1 = config.codec_specific_1, - .codec_specific_2 = config.codec_specific_2, - .codec_specific_3 = config.codec_specific_3, - .codec_specific_4 = config.codec_specific_4}; + A2dpCodecConfig rconfig = {.codec_type = static_cast(config.codec_type), + .codec_priority = config.codec_priority, + .sample_rate = static_cast(config.sample_rate), + .bits_per_sample = static_cast(config.bits_per_sample), + .channel_mode = static_cast(config.channel_mode), + .codec_specific_1 = config.codec_specific_1, + .codec_specific_2 = config.codec_specific_2, + .codec_specific_3 = config.codec_specific_3, + .codec_specific_4 = config.codec_specific_4}; return rconfig; } static btav_a2dp_codec_config_t from_rust_codec_config(const A2dpCodecConfig& rconfig) { btav_a2dp_codec_config_t config = { - .codec_type = static_cast(rconfig.codec_type), - .codec_priority = static_cast(rconfig.codec_priority), - .sample_rate = static_cast(rconfig.sample_rate), - .bits_per_sample = static_cast(rconfig.bits_per_sample), - .channel_mode = static_cast(rconfig.channel_mode), - .codec_specific_1 = rconfig.codec_specific_1, - .codec_specific_2 = rconfig.codec_specific_2, - .codec_specific_3 = rconfig.codec_specific_3, - .codec_specific_4 = rconfig.codec_specific_4, + .codec_type = static_cast(rconfig.codec_type), + .codec_priority = static_cast(rconfig.codec_priority), + .sample_rate = static_cast(rconfig.sample_rate), + .bits_per_sample = + static_cast(rconfig.bits_per_sample), + .channel_mode = static_cast(rconfig.channel_mode), + .codec_specific_1 = rconfig.codec_specific_1, + .codec_specific_2 = rconfig.codec_specific_2, + .codec_specific_3 = rconfig.codec_specific_3, + .codec_specific_4 = rconfig.codec_specific_4, }; return config; } -static ::rust::Vec to_rust_codec_config_vec(const std::vector& configs) { +static ::rust::Vec to_rust_codec_config_vec( + const std::vector& configs) { ::rust::Vec rconfigs; for (btav_a2dp_codec_config_t c : configs) { @@ -221,25 +231,24 @@ static ::rust::Vec to_rust_codec_config_vec(const std::vector codecs_local_capabilities, - std::vector codecs_selectable_capabilities) { +static void audio_config_cb(const RawAddress& addr, btav_a2dp_codec_config_t codec_config, + std::vector codecs_local_capabilities, + std::vector codecs_selectable_capabilities) { A2dpCodecConfig cfg = to_rust_codec_config(codec_config); ::rust::Vec lcaps = to_rust_codec_config_vec(codecs_local_capabilities); ::rust::Vec scaps = to_rust_codec_config_vec(codecs_selectable_capabilities); @@ -251,11 +260,8 @@ static bool mandatory_codec_preferred_cb(const RawAddress& addr) { } btav_source_callbacks_t g_callbacks = { - sizeof(btav_source_callbacks_t), - connection_state_cb, - audio_state_cb, - audio_config_cb, - mandatory_codec_preferred_cb, + sizeof(btav_source_callbacks_t), connection_state_cb, audio_state_cb, audio_config_cb, + mandatory_codec_preferred_cb, }; } // namespace internal @@ -264,7 +270,9 @@ A2dpIntf::~A2dpIntf() { } std::unique_ptr GetA2dpProfile(const unsigned char* btif) { - if (internal::g_a2dpif) std::abort(); + if (internal::g_a2dpif) { + std::abort(); + } const bt_interface_t* btif_ = reinterpret_cast(btif); @@ -280,12 +288,8 @@ int A2dpIntf::init() const { return btif_av_source_init(&internal::g_callbacks, 1, a, b, &c); } -uint32_t A2dpIntf::connect(RawAddress addr) const { - return btif_av_source_connect(addr); -} -uint32_t A2dpIntf::disconnect(RawAddress addr) const { - return btif_av_source_disconnect(addr); -} +uint32_t A2dpIntf::connect(RawAddress addr) const { return btif_av_source_connect(addr); } +uint32_t A2dpIntf::disconnect(RawAddress addr) const { return btif_av_source_disconnect(addr); } int A2dpIntf::set_silence_device(RawAddress addr, bool silent) const { return btif_av_source_set_silence_device(addr, silent); } @@ -300,33 +304,27 @@ int A2dpIntf::config_codec(RawAddress addr, ::rust::Vec codec_p return btif_av_source_set_codec_config_preference(addr, prefs); } -void A2dpIntf::cleanup() const { - btif_av_source_cleanup(); -} +void A2dpIntf::cleanup() const { btif_av_source_cleanup(); } bool A2dpIntf::set_audio_config(A2dpCodecConfig rconfig) const { bluetooth::audio::a2dp::AudioConfig config = { - .sample_rate = static_cast(rconfig.sample_rate), - .bits_per_sample = static_cast(rconfig.bits_per_sample), - .channel_mode = static_cast(rconfig.channel_mode), + .sample_rate = static_cast(rconfig.sample_rate), + .bits_per_sample = + static_cast(rconfig.bits_per_sample), + .channel_mode = static_cast(rconfig.channel_mode), }; return bluetooth::audio::a2dp::SetAudioConfig(config); } -bool A2dpIntf::start_audio_request() const { - return bluetooth::audio::a2dp::StartRequest(); -} -bool A2dpIntf::stop_audio_request() const { - return bluetooth::audio::a2dp::StopRequest(); -} -bool A2dpIntf::suspend_audio_request() const { - return bluetooth::audio::a2dp::SuspendRequest(); -} +bool A2dpIntf::start_audio_request() const { return bluetooth::audio::a2dp::StartRequest(); } +bool A2dpIntf::stop_audio_request() const { return bluetooth::audio::a2dp::StopRequest(); } +bool A2dpIntf::suspend_audio_request() const { return bluetooth::audio::a2dp::SuspendRequest(); } RustPresentationPosition A2dpIntf::get_presentation_position() const { - bluetooth::audio::a2dp::PresentationPosition p = bluetooth::audio::a2dp::GetPresentationPosition(); + bluetooth::audio::a2dp::PresentationPosition p = + bluetooth::audio::a2dp::GetPresentationPosition(); RustPresentationPosition rposition = { - .remote_delay_report_ns = p.remote_delay_report_ns, - .total_bytes_read = p.total_bytes_read, - .data_position_sec = p.data_position.tv_sec, - .data_position_nsec = static_cast(p.data_position.tv_nsec), + .remote_delay_report_ns = p.remote_delay_report_ns, + .total_bytes_read = p.total_bytes_read, + .data_position_sec = p.data_position.tv_sec, + .data_position_nsec = static_cast(p.data_position.tv_nsec), }; return rposition; } @@ -337,53 +335,51 @@ static bluetooth::avrcp::AvrcpMediaInterfaceImpl mAvrcpInterface; static bluetooth::avrcp::VolumeInterfaceImpl mVolumeInterface; std::unique_ptr GetAvrcpProfile(const unsigned char* btif) { - if (internal::g_avrcpif) std::abort(); + if (internal::g_avrcpif) { + std::abort(); + } const bt_interface_t* btif_ = reinterpret_cast(btif); - auto avrcpif = std::make_unique(reinterpret_cast(btif_->get_avrcp_service())); + auto avrcpif = std::make_unique( + reinterpret_cast(btif_->get_avrcp_service())); internal::g_avrcpif = avrcpif.get(); return avrcpif; } AvrcpIntf::~AvrcpIntf() {} -void AvrcpIntf::init() { - intf_->Init(&mAvrcpInterface, &mVolumeInterface, nullptr); -} +void AvrcpIntf::init() { intf_->Init(&mAvrcpInterface, &mVolumeInterface, nullptr); } -void AvrcpIntf::cleanup() { - intf_->Cleanup(); -} +void AvrcpIntf::cleanup() { intf_->Cleanup(); } -uint32_t AvrcpIntf::connect(RawAddress addr) { - return intf_->ConnectDevice(addr); -} -uint32_t AvrcpIntf::disconnect(RawAddress addr) { - return intf_->DisconnectDevice(addr); -} +uint32_t AvrcpIntf::connect(RawAddress addr) { return intf_->ConnectDevice(addr); } +uint32_t AvrcpIntf::disconnect(RawAddress addr) { return intf_->DisconnectDevice(addr); } -void AvrcpIntf::set_volume(int8_t volume) { - return mVolumeInterface.SetDeviceVolume(volume); -} +void AvrcpIntf::set_volume(int8_t volume) { return mVolumeInterface.SetDeviceVolume(volume); } void AvrcpIntf::set_playback_status(const ::rust::String& status) { avrcp::PlayState state = avrcp::PlayState::STOPPED; - if (status == "stopped") state = avrcp::PlayState::STOPPED; - if (status == "playing") state = avrcp::PlayState::PLAYING; - if (status == "paused") state = avrcp::PlayState::PAUSED; + if (status == "stopped") { + state = avrcp::PlayState::STOPPED; + } + if (status == "playing") { + state = avrcp::PlayState::PLAYING; + } + if (status == "paused") { + state = avrcp::PlayState::PAUSED; + } mAvrcpInterface.SetPlaybackStatus(state); } -void AvrcpIntf::set_position(int64_t position) { - mAvrcpInterface.SetPosition(position); -} +void AvrcpIntf::set_position(int64_t position) { mAvrcpInterface.SetPosition(position); } -void AvrcpIntf::set_metadata( - const ::rust::String& title, const ::rust::String& artist, const ::rust::String& album, int64_t length_us) { - mAvrcpInterface.SetMetadata(std::string(title), std::string(artist), std::string(album), length_us); +void AvrcpIntf::set_metadata(const ::rust::String& title, const ::rust::String& artist, + const ::rust::String& album, int64_t length_us) { + mAvrcpInterface.SetMetadata(std::string(title), std::string(artist), std::string(album), + length_us); } uint16_t AvrcpIntf::add_player(const ::rust::String& name, bool browsing_supported) { diff --git a/system/gd/rust/topshim/btav/btav_shim.h b/system/gd/rust/topshim/btav/btav_shim.h index 16b0e008a4a..6482bca94f9 100644 --- a/system/gd/rust/topshim/btav/btav_shim.h +++ b/system/gd/rust/topshim/btav/btav_shim.h @@ -33,7 +33,7 @@ struct RustPresentationPosition; struct RustPlayStatus; class A2dpIntf { - public: +public: A2dpIntf() {} ~A2dpIntf(); @@ -57,7 +57,7 @@ class A2dpIntf { std::unique_ptr GetA2dpProfile(const unsigned char* btif); class AvrcpIntf { - public: +public: AvrcpIntf(bluetooth::avrcp::ServiceInterface* intf) : intf_(intf) {} ~AvrcpIntf(); @@ -71,12 +71,12 @@ class AvrcpIntf { void set_playback_status(const ::rust::String& status); void set_position(int64_t position_us); - void set_metadata( - const ::rust::String& title, const ::rust::String& artist, const ::rust::String& album, int64_t length_us); + void set_metadata(const ::rust::String& title, const ::rust::String& artist, + const ::rust::String& album, int64_t length_us); // Used by qualification uint16_t add_player(const ::rust::String& name, bool browsing_supported); - private: +private: bluetooth::avrcp::ServiceInterface* intf_; }; diff --git a/system/gd/rust/topshim/btav_sink/btav_sink_shim.cc b/system/gd/rust/topshim/btav_sink/btav_sink_shim.cc index 5c1103d12ce..8b38b9b15a4 100644 --- a/system/gd/rust/topshim/btav_sink/btav_sink_shim.cc +++ b/system/gd/rust/topshim/btav_sink/btav_sink_shim.cc @@ -34,15 +34,15 @@ static A2dpSinkIntf* g_a2dp_sink_if; static A2dpError to_rust_error(const btav_error_t& error) { A2dpError a2dp_error = { - .status = error.status, - .error_code = error.error_code, - .error_msg = error.error_msg.value_or(""), + .status = error.status, + .error_code = error.error_code, + .error_msg = error.error_msg.value_or(""), }; return a2dp_error; } -static void connection_state_cb( - const RawAddress& addr, btav_connection_state_t state, const btav_error_t& error) { +static void connection_state_cb(const RawAddress& addr, btav_connection_state_t state, + const btav_error_t& error) { A2dpError a2dp_error = to_rust_error(error); rusty::sink_connection_state_callback(addr, state, a2dp_error); } @@ -54,10 +54,10 @@ static void audio_config_cb(const RawAddress& addr, uint32_t sample_rate, uint8_ } btav_sink_callbacks_t g_a2dp_sink_callbacks = { - sizeof(btav_sink_callbacks_t), - connection_state_cb, - audio_state_cb, - audio_config_cb, + sizeof(btav_sink_callbacks_t), + connection_state_cb, + audio_state_cb, + audio_config_cb, }; } // namespace internal @@ -66,7 +66,9 @@ A2dpSinkIntf::~A2dpSinkIntf() { } std::unique_ptr GetA2dpSinkProfile(const unsigned char* btif) { - if (internal::g_a2dp_sink_if) std::abort(); + if (internal::g_a2dp_sink_if) { + std::abort(); + } const bt_interface_t* btif_ = reinterpret_cast(btif); @@ -75,17 +77,11 @@ std::unique_ptr GetA2dpSinkProfile(const unsigned char* btif) { return a2dp_sink; } -int A2dpSinkIntf::init() const { - return btif_av_sink_init(&internal::g_a2dp_sink_callbacks, 1); -} +int A2dpSinkIntf::init() const { return btif_av_sink_init(&internal::g_a2dp_sink_callbacks, 1); } -int A2dpSinkIntf::connect(RawAddress addr) const { - return btif_av_sink_connect(addr); -} +int A2dpSinkIntf::connect(RawAddress addr) const { return btif_av_sink_connect(addr); } -int A2dpSinkIntf::disconnect(RawAddress addr) const { - return btif_av_sink_disconnect(addr); -} +int A2dpSinkIntf::disconnect(RawAddress addr) const { return btif_av_sink_disconnect(addr); } int A2dpSinkIntf::set_active_device(RawAddress addr) const { return btif_av_sink_set_active_device(addr); diff --git a/system/gd/rust/topshim/btav_sink/btav_sink_shim.h b/system/gd/rust/topshim/btav_sink/btav_sink_shim.h index a74445e3f15..58c09371ec8 100644 --- a/system/gd/rust/topshim/btav_sink/btav_sink_shim.h +++ b/system/gd/rust/topshim/btav_sink/btav_sink_shim.h @@ -28,8 +28,8 @@ namespace topshim { namespace rust { class A2dpSinkIntf { - public: - A2dpSinkIntf(){}; +public: + A2dpSinkIntf() {} ~A2dpSinkIntf(); // interface for Settings diff --git a/system/gd/rust/topshim/btif/btif_shim.cc b/system/gd/rust/topshim/btif/btif_shim.cc index 82cb32ea199..ed31a15e9a5 100644 --- a/system/gd/rust/topshim/btif/btif_shim.cc +++ b/system/gd/rust/topshim/btif/btif_shim.cc @@ -43,7 +43,9 @@ void InitFlags::Convert(::rust::Vec<::rust::String>& initFlags) { // Allocate number of flags + 1 (last entry must be null to signify end) // Must be calloc so our cleanup correctly frees everything flags_ = static_cast(std::calloc(initFlags.size() + 1, sizeof(char*))); - if (!flags_) return; + if (!flags_) { + return; + } for (size_t i = 0; i < initFlags.size(); ++i) { flags_[i] = strndup(initFlags[i].data(), initFlags[i].size()); diff --git a/system/gd/rust/topshim/btif/btif_shim.h b/system/gd/rust/topshim/btif/btif_shim.h index c1a268439aa..b04baf871f0 100644 --- a/system/gd/rust/topshim/btif/btif_shim.h +++ b/system/gd/rust/topshim/btif/btif_shim.h @@ -25,16 +25,14 @@ namespace topshim { namespace rust { class InitFlags { - public: +public: InitFlags(); ~InitFlags(); void Convert(::rust::Vec<::rust::String>& flags); - const char** GetFlagsPtr() const { - return flags_; - } + const char** GetFlagsPtr() const { return flags_; } - private: +private: const char** flags_; }; diff --git a/system/gd/rust/topshim/controller/controller_shim.cc b/system/gd/rust/topshim/controller/controller_shim.cc index 86b33ebf102..b47065f4401 100644 --- a/system/gd/rust/topshim/controller/controller_shim.cc +++ b/system/gd/rust/topshim/controller/controller_shim.cc @@ -33,24 +33,32 @@ static ControllerIntf* g_controller_intf; ControllerIntf::~ControllerIntf() {} std::unique_ptr GetControllerInterface() { - if (internal::g_controller_intf) std::abort(); + if (internal::g_controller_intf) { + std::abort(); + } auto controller_intf = std::make_unique(); internal::g_controller_intf = controller_intf.get(); return controller_intf; } RawAddress ControllerIntf::read_local_addr() const { - if (!controller_) std::abort(); + if (!controller_) { + std::abort(); + } return ToRawAddress(controller_->GetMacAddress()); } uint64_t ControllerIntf::get_ble_supported_states() const { - if (!controller_) std::abort(); + if (!controller_) { + std::abort(); + } return controller_->GetLeSupportedStates(); } uint64_t ControllerIntf::get_ble_local_supported_features() const { - if (!controller_) std::abort(); + if (!controller_) { + std::abort(); + } return controller_->GetControllerLeLocalSupportedFeatures(); } diff --git a/system/gd/rust/topshim/controller/controller_shim.h b/system/gd/rust/topshim/controller/controller_shim.h index cc794deed94..0d6e6a93608 100644 --- a/system/gd/rust/topshim/controller/controller_shim.h +++ b/system/gd/rust/topshim/controller/controller_shim.h @@ -28,7 +28,7 @@ namespace topshim { namespace rust { class ControllerIntf { - public: +public: ControllerIntf() : controller_(shim::GetController()) {} ~ControllerIntf(); @@ -36,7 +36,7 @@ class ControllerIntf { uint64_t get_ble_supported_states() const; uint64_t get_ble_local_supported_features() const; - private: +private: const hci::ControllerInterface* controller_; }; diff --git a/system/gd/rust/topshim/csis/csis_shim.cc b/system/gd/rust/topshim/csis/csis_shim.cc index cfc5b86cff3..371d4976f59 100644 --- a/system/gd/rust/topshim/csis/csis_shim.cc +++ b/system/gd/rust/topshim/csis/csis_shim.cc @@ -77,8 +77,8 @@ static void connection_state_cb(const RawAddress& addr, csis::ConnectionState st csis_connection_state_callback(addr, to_rust_btcsis_connection_state(state)); } -static void device_available_cb( - const RawAddress& addr, int group_id, int group_size, int rank, const bluetooth::Uuid& uuid) { +static void device_available_cb(const RawAddress& addr, int group_id, int group_size, int rank, + const bluetooth::Uuid& uuid) { csis_device_available_callback(addr, group_id, group_size, rank, uuid); } @@ -92,31 +92,23 @@ static void group_lock_changed_cb(int group_id, bool locked, csis::CsisGroupLock } // namespace internal class DBusCsisClientCallbacks : public csis::CsisClientCallbacks { - public: +public: static csis::CsisClientCallbacks* GetInstance() { static auto instance = new DBusCsisClientCallbacks(); return instance; } - DBusCsisClientCallbacks(){}; + DBusCsisClientCallbacks() {} void OnConnectionState(const RawAddress& addr, csis::ConnectionState state) override { log::info("addr={}, state={}", ADDRESS_TO_LOGGABLE_CSTR(addr), static_cast(state)); topshim::rust::internal::connection_state_cb(addr, state); } - void OnDeviceAvailable( - const RawAddress& addr, - int group_id, - int group_size, - int rank, - const bluetooth::Uuid& uuid) override { - log::info( - "addr={}, group_id={}, group_size={}, rank={}", - ADDRESS_TO_LOGGABLE_CSTR(addr), - group_id, - group_size, - rank); + void OnDeviceAvailable(const RawAddress& addr, int group_id, int group_size, int rank, + const bluetooth::Uuid& uuid) override { + log::info("addr={}, group_id={}, group_size={}, rank={}", ADDRESS_TO_LOGGABLE_CSTR(addr), + group_id, group_size, rank); topshim::rust::internal::device_available_cb(addr, group_id, group_size, rank, uuid); } @@ -131,13 +123,15 @@ class DBusCsisClientCallbacks : public csis::CsisClientCallbacks { }; std::unique_ptr GetCsisClientProfile(const unsigned char* btif) { - if (internal::g_csis_if) std::abort(); + if (internal::g_csis_if) { + std::abort(); + } const bt_interface_t* btif_ = reinterpret_cast(btif); auto csis_if = std::make_unique( - const_cast(reinterpret_cast( - btif_->get_profile_interface("csis_client")))); + const_cast(reinterpret_cast( + btif_->get_profile_interface("csis_client")))); internal::g_csis_if = csis_if.get(); @@ -148,25 +142,17 @@ void CsisClientIntf::init(/*CsisClientCallbacks* callbacks*/) { return intf_->Init(DBusCsisClientCallbacks::GetInstance()); } -void CsisClientIntf::connect(RawAddress addr) { - return intf_->Connect(addr); -} +void CsisClientIntf::connect(RawAddress addr) { return intf_->Connect(addr); } -void CsisClientIntf::disconnect(RawAddress addr) { - return intf_->Disconnect(addr); -} +void CsisClientIntf::disconnect(RawAddress addr) { return intf_->Disconnect(addr); } void CsisClientIntf::lock_group(int group_id, bool lock) { return intf_->LockGroup(group_id, lock); } -void CsisClientIntf::remove_device(RawAddress addr) { - return intf_->RemoveDevice(addr); -} +void CsisClientIntf::remove_device(RawAddress addr) { return intf_->RemoveDevice(addr); } -void CsisClientIntf::cleanup() { - return intf_->Cleanup(); -} +void CsisClientIntf::cleanup() { return intf_->Cleanup(); } } // namespace rust } // namespace topshim } // namespace bluetooth diff --git a/system/gd/rust/topshim/csis/csis_shim.h b/system/gd/rust/topshim/csis/csis_shim.h index 48d33fc9a48..30a66d72e89 100644 --- a/system/gd/rust/topshim/csis/csis_shim.h +++ b/system/gd/rust/topshim/csis/csis_shim.h @@ -27,8 +27,8 @@ namespace topshim { namespace rust { class CsisClientIntf { - public: - CsisClientIntf(csis::CsisClientInterface* intf) : intf_(intf){}; +public: + CsisClientIntf(csis::CsisClientInterface* intf) : intf_(intf) {} void init(/*CsisClientCallbacks* callbacks*/); void connect(RawAddress addr); @@ -37,7 +37,7 @@ class CsisClientIntf { void remove_device(RawAddress addr); void cleanup(); - private: +private: csis::CsisClientInterface* intf_; }; diff --git a/system/gd/rust/topshim/gatt/gatt_ble_advertiser_shim.cc b/system/gd/rust/topshim/gatt/gatt_ble_advertiser_shim.cc index ff77bc26a13..a863f70e500 100644 --- a/system/gd/rust/topshim/gatt/gatt_ble_advertiser_shim.cc +++ b/system/gd/rust/topshim/gatt/gatt_ble_advertiser_shim.cc @@ -39,7 +39,8 @@ namespace rusty = ::bluetooth::topshim::rust; // AdvertisingCallbacks implementations -void BleAdvertiserIntf::OnAdvertisingSetStarted(int reg_id, uint8_t advertiser_id, int8_t tx_power, uint8_t status) { +void BleAdvertiserIntf::OnAdvertisingSetStarted(int reg_id, uint8_t advertiser_id, int8_t tx_power, + uint8_t status) { rusty::gdadv_on_advertising_set_started(reg_id, advertiser_id, tx_power, status); } void BleAdvertiserIntf::OnAdvertisingEnabled(uint8_t advertiser_id, bool enable, uint8_t status) { @@ -51,42 +52,44 @@ void BleAdvertiserIntf::OnAdvertisingDataSet(uint8_t advertiser_id, uint8_t stat void BleAdvertiserIntf::OnScanResponseDataSet(uint8_t advertiser_id, uint8_t status) { rusty::gdadv_on_scan_response_data_set(advertiser_id, status); } -void BleAdvertiserIntf::OnAdvertisingParametersUpdated(uint8_t advertiser_id, int8_t tx_power, uint8_t status) { +void BleAdvertiserIntf::OnAdvertisingParametersUpdated(uint8_t advertiser_id, int8_t tx_power, + uint8_t status) { rusty::gdadv_on_advertising_parameters_updated(advertiser_id, tx_power, status); } -void BleAdvertiserIntf::OnPeriodicAdvertisingParametersUpdated(uint8_t advertiser_id, uint8_t status) { +void BleAdvertiserIntf::OnPeriodicAdvertisingParametersUpdated(uint8_t advertiser_id, + uint8_t status) { rusty::gdadv_on_periodic_advertising_parameters_updated(advertiser_id, status); } void BleAdvertiserIntf::OnPeriodicAdvertisingDataSet(uint8_t advertiser_id, uint8_t status) { rusty::gdadv_on_periodic_advertising_data_set(advertiser_id, status); } -void BleAdvertiserIntf::OnPeriodicAdvertisingEnabled(uint8_t advertiser_id, bool enable, uint8_t status) { +void BleAdvertiserIntf::OnPeriodicAdvertisingEnabled(uint8_t advertiser_id, bool enable, + uint8_t status) { rusty::gdadv_on_periodic_advertising_enabled(advertiser_id, enable, status); } -void BleAdvertiserIntf::OnOwnAddressRead(uint8_t advertiser_id, uint8_t address_type, RawAddress addr) { +void BleAdvertiserIntf::OnOwnAddressRead(uint8_t advertiser_id, uint8_t address_type, + RawAddress addr) { rusty::gdadv_on_own_address_read(advertiser_id, address_type, &addr); } // BleAdvertiserInterface implementations void BleAdvertiserIntf::RegisterAdvertiser() { - adv_intf_->RegisterAdvertiser(base::Bind(&BleAdvertiserIntf::OnIdStatusCallback, base::Unretained(this))); + adv_intf_->RegisterAdvertiser( + base::Bind(&BleAdvertiserIntf::OnIdStatusCallback, base::Unretained(this))); } -void BleAdvertiserIntf::Unregister(uint8_t adv_id) { - adv_intf_->Unregister(adv_id); -} +void BleAdvertiserIntf::Unregister(uint8_t adv_id) { adv_intf_->Unregister(adv_id); } void BleAdvertiserIntf::GetOwnAddress(uint8_t adv_id) { - adv_intf_->GetOwnAddress( - adv_id, base::Bind(&BleAdvertiserIntf::OnGetAddressCallback, base::Unretained(this), adv_id)); + adv_intf_->GetOwnAddress(adv_id, base::Bind(&BleAdvertiserIntf::OnGetAddressCallback, + base::Unretained(this), adv_id)); } void BleAdvertiserIntf::SetParameters(uint8_t adv_id, AdvertiseParameters params) { adv_intf_->SetParameters( - adv_id, - params, - base::Bind(&BleAdvertiserIntf::OnParametersCallback, base::Unretained(this), adv_id)); + adv_id, params, + base::Bind(&BleAdvertiserIntf::OnParametersCallback, base::Unretained(this), adv_id)); } void BleAdvertiserIntf::SetData(uint8_t adv_id, bool set_scan_rsp, ::rust::Vec data) { @@ -94,76 +97,61 @@ void BleAdvertiserIntf::SetData(uint8_t adv_id, bool set_scan_rsp, ::rust::VecSetData( - adv_id, - set_scan_rsp, - converted, - base::Bind(&BleAdvertiserIntf::OnIdStatusCallback, base::Unretained(this), adv_id)); + adv_id, set_scan_rsp, converted, + base::Bind(&BleAdvertiserIntf::OnIdStatusCallback, base::Unretained(this), adv_id)); } -void BleAdvertiserIntf::Enable(uint8_t adv_id, bool enable, uint16_t duration, uint8_t max_ext_adv_events) { +void BleAdvertiserIntf::Enable(uint8_t adv_id, bool enable, uint16_t duration, + uint8_t max_ext_adv_events) { adv_intf_->Enable( - adv_id, - enable, - base::Bind(&BleAdvertiserIntf::OnIdStatusCallback, base::Unretained(this), adv_id), - duration, - max_ext_adv_events, - base::Bind(&BleAdvertiserIntf::OnIdStatusCallback, base::Unretained(this), adv_id)); -} - -void BleAdvertiserIntf::StartAdvertising( - uint8_t adv_id, - AdvertiseParameters params, - ::rust::Vec advertise_data, - ::rust::Vec scan_response_data, - int32_t timeout_in_sec) { + adv_id, enable, + base::Bind(&BleAdvertiserIntf::OnIdStatusCallback, base::Unretained(this), adv_id), + duration, max_ext_adv_events, + base::Bind(&BleAdvertiserIntf::OnIdStatusCallback, base::Unretained(this), adv_id)); +} + +void BleAdvertiserIntf::StartAdvertising(uint8_t adv_id, AdvertiseParameters params, + ::rust::Vec advertise_data, + ::rust::Vec scan_response_data, + int32_t timeout_in_sec) { std::vector converted_adv_data, converted_scan_rsp_data; std::copy(advertise_data.begin(), advertise_data.end(), std::back_inserter(converted_adv_data)); - std::copy(scan_response_data.begin(), scan_response_data.end(), std::back_inserter(converted_scan_rsp_data)); + std::copy(scan_response_data.begin(), scan_response_data.end(), + std::back_inserter(converted_scan_rsp_data)); adv_intf_->StartAdvertising( - adv_id, - base::Bind(&BleAdvertiserIntf::OnIdStatusCallback, base::Unretained(this), adv_id), - params, - converted_adv_data, - converted_scan_rsp_data, - timeout_in_sec, - base::Bind(&BleAdvertiserIntf::OnIdStatusCallback, base::Unretained(this), adv_id)); -} - -void BleAdvertiserIntf::StartAdvertisingSet( - int32_t reg_id, - AdvertiseParameters params, - ::rust::Vec advertise_data, - ::rust::Vec scan_response_data, - PeriodicAdvertisingParameters periodic_params, - ::rust::Vec periodic_data, - uint16_t duration, - uint8_t max_ext_adv_events) { + adv_id, + base::Bind(&BleAdvertiserIntf::OnIdStatusCallback, base::Unretained(this), adv_id), + params, converted_adv_data, converted_scan_rsp_data, timeout_in_sec, + base::Bind(&BleAdvertiserIntf::OnIdStatusCallback, base::Unretained(this), adv_id)); +} + +void BleAdvertiserIntf::StartAdvertisingSet(int32_t reg_id, AdvertiseParameters params, + ::rust::Vec advertise_data, + ::rust::Vec scan_response_data, + PeriodicAdvertisingParameters periodic_params, + ::rust::Vec periodic_data, uint16_t duration, + uint8_t max_ext_adv_events) { std::vector converted_adv_data, converted_scan_rsp_data, converted_periodic_data; std::copy(advertise_data.begin(), advertise_data.end(), std::back_inserter(converted_adv_data)); - std::copy(scan_response_data.begin(), scan_response_data.end(), std::back_inserter(converted_scan_rsp_data)); - std::copy(periodic_data.begin(), periodic_data.end(), std::back_inserter(converted_periodic_data)); + std::copy(scan_response_data.begin(), scan_response_data.end(), + std::back_inserter(converted_scan_rsp_data)); + std::copy(periodic_data.begin(), periodic_data.end(), + std::back_inserter(converted_periodic_data)); adv_intf_->StartAdvertisingSet( - kAdvertiserClientIdJni, - reg_id, - base::Bind(&BleAdvertiserIntf::OnIdTxPowerStatusCallback, base::Unretained(this)), - params, - converted_adv_data, - converted_scan_rsp_data, - periodic_params, - converted_periodic_data, - duration, - max_ext_adv_events, - base::Bind(&BleAdvertiserIntf::OnIdStatusCallback, base::Unretained(this))); -} - -void BleAdvertiserIntf::SetPeriodicAdvertisingParameters( - uint8_t adv_id, PeriodicAdvertisingParameters params) { + kAdvertiserClientIdJni, reg_id, + base::Bind(&BleAdvertiserIntf::OnIdTxPowerStatusCallback, base::Unretained(this)), params, + converted_adv_data, converted_scan_rsp_data, periodic_params, converted_periodic_data, + duration, max_ext_adv_events, + base::Bind(&BleAdvertiserIntf::OnIdStatusCallback, base::Unretained(this))); +} + +void BleAdvertiserIntf::SetPeriodicAdvertisingParameters(uint8_t adv_id, + PeriodicAdvertisingParameters params) { adv_intf_->SetPeriodicAdvertisingParameters( - adv_id, - params, - base::Bind(&BleAdvertiserIntf::OnIdStatusCallback, base::Unretained(this), adv_id)); + adv_id, params, + base::Bind(&BleAdvertiserIntf::OnIdStatusCallback, base::Unretained(this), adv_id)); } void BleAdvertiserIntf::SetPeriodicAdvertisingData(uint8_t adv_id, ::rust::Vec data) { @@ -171,17 +159,18 @@ void BleAdvertiserIntf::SetPeriodicAdvertisingData(uint8_t adv_id, ::rust::VecSetPeriodicAdvertisingData( - adv_id, converted, base::Bind(&BleAdvertiserIntf::OnIdStatusCallback, base::Unretained(this), adv_id)); + adv_id, converted, + base::Bind(&BleAdvertiserIntf::OnIdStatusCallback, base::Unretained(this), adv_id)); } -void BleAdvertiserIntf::SetPeriodicAdvertisingEnable(uint8_t adv_id, bool enable, bool include_adi) { +void BleAdvertiserIntf::SetPeriodicAdvertisingEnable(uint8_t adv_id, bool enable, + bool include_adi) { adv_intf_->SetPeriodicAdvertisingEnable( - adv_id, enable, include_adi, base::Bind(&BleAdvertiserIntf::OnIdStatusCallback, base::Unretained(this), adv_id)); + adv_id, enable, include_adi, + base::Bind(&BleAdvertiserIntf::OnIdStatusCallback, base::Unretained(this), adv_id)); } -void BleAdvertiserIntf::RegisterCallbacks() { - adv_intf_->RegisterCallbacks(this); -} +void BleAdvertiserIntf::RegisterCallbacks() { adv_intf_->RegisterCallbacks(this); } // Inband callbacks @@ -199,7 +188,8 @@ void BleAdvertiserIntf::OnGetAddressCallback(uint8_t adv_id, uint8_t addr_type, } std::unique_ptr GetBleAdvertiserIntf(const unsigned char* gatt_intf) { - return std::make_unique(reinterpret_cast(gatt_intf)->advertiser); + return std::make_unique( + reinterpret_cast(gatt_intf)->advertiser); } } // namespace rust diff --git a/system/gd/rust/topshim/gatt/gatt_ble_advertiser_shim.h b/system/gd/rust/topshim/gatt/gatt_ble_advertiser_shim.h index fe8b515965a..5caa8dca677 100644 --- a/system/gd/rust/topshim/gatt/gatt_ble_advertiser_shim.h +++ b/system/gd/rust/topshim/gatt/gatt_ble_advertiser_shim.h @@ -30,16 +30,18 @@ namespace rust { // This shim implementation just calls the underlying interface and binds the // local callbacks in order to dispatch the Rust callbacks. class BleAdvertiserIntf : public AdvertisingCallbacks { - public: - BleAdvertiserIntf(BleAdvertiserInterface* adv_intf) : adv_intf_(adv_intf){}; +public: + BleAdvertiserIntf(BleAdvertiserInterface* adv_intf) : adv_intf_(adv_intf) {} ~BleAdvertiserIntf() = default; // AdvertisingCallbacks overrides - void OnAdvertisingSetStarted(int reg_id, uint8_t advertiser_id, int8_t tx_power, uint8_t status) override; + void OnAdvertisingSetStarted(int reg_id, uint8_t advertiser_id, int8_t tx_power, + uint8_t status) override; void OnAdvertisingEnabled(uint8_t advertiser_id, bool enable, uint8_t status) override; void OnAdvertisingDataSet(uint8_t advertiser_id, uint8_t status) override; void OnScanResponseDataSet(uint8_t advertiser_id, uint8_t status) override; - void OnAdvertisingParametersUpdated(uint8_t advertiser_id, int8_t tx_power, uint8_t status) override; + void OnAdvertisingParametersUpdated(uint8_t advertiser_id, int8_t tx_power, + uint8_t status) override; void OnPeriodicAdvertisingParametersUpdated(uint8_t advertiser_id, uint8_t status) override; void OnPeriodicAdvertisingDataSet(uint8_t advertiser_id, uint8_t status) override; void OnPeriodicAdvertisingEnabled(uint8_t advertiser_id, bool enable, uint8_t status) override; @@ -54,28 +56,22 @@ class BleAdvertiserIntf : public AdvertisingCallbacks { void SetParameters(uint8_t adv_id, AdvertiseParameters params); void SetData(uint8_t adv_id, bool set_scan_rsp, ::rust::Vec data); void Enable(uint8_t adv_id, bool enable, uint16_t duration, uint8_t max_ext_adv_events); - void StartAdvertising( - uint8_t adv_id, - AdvertiseParameters params, - ::rust::Vec advertise_data, - ::rust::Vec scan_response_data, - int32_t timeout_in_sec); - void StartAdvertisingSet( - int32_t reg_id, - AdvertiseParameters params, - ::rust::Vec advertise_data, - ::rust::Vec scan_response_data, - PeriodicAdvertisingParameters periodic_params, - ::rust::Vec periodic_data, - uint16_t duration, - uint8_t max_ext_adv_events); + void StartAdvertising(uint8_t adv_id, AdvertiseParameters params, + ::rust::Vec advertise_data, + ::rust::Vec scan_response_data, int32_t timeout_in_sec); + void StartAdvertisingSet(int32_t reg_id, AdvertiseParameters params, + ::rust::Vec advertise_data, + ::rust::Vec scan_response_data, + PeriodicAdvertisingParameters periodic_params, + ::rust::Vec periodic_data, uint16_t duration, + uint8_t max_ext_adv_events); void SetPeriodicAdvertisingParameters(uint8_t adv_id, PeriodicAdvertisingParameters params); void SetPeriodicAdvertisingData(uint8_t adv_id, ::rust::Vec data); void SetPeriodicAdvertisingEnable(uint8_t adv_id, bool enable, bool include_adi); void RegisterCallbacks(); - private: +private: // In-band callbacks will get binded to these and sent to Rust via static // callbacks. void OnIdStatusCallback(uint8_t adv_id, uint8_t status); diff --git a/system/gd/rust/topshim/gatt/gatt_ble_scanner_shim.cc b/system/gd/rust/topshim/gatt/gatt_ble_scanner_shim.cc index 6b46bb6b1e3..2884da572c6 100644 --- a/system/gd/rust/topshim/gatt/gatt_ble_scanner_shim.cc +++ b/system/gd/rust/topshim/gatt/gatt_ble_scanner_shim.cc @@ -48,23 +48,23 @@ ApcfCommand ConvertApcfFromRust(const RustApcfCommand& command) { std::copy(command.meta_data.begin(), command.meta_data.end(), std::back_inserter(meta_data)); ApcfCommand converted = { - .type = command.type_, - .address = command.address, - .addr_type = command.addr_type, - .uuid = command.uuid, - .uuid_mask = command.uuid_mask, - .name = name, - .company = command.company, - .company_mask = command.company_mask, - .org_id = command.org_id, - .tds_flags = command.tds_flags, - .tds_flags_mask = command.tds_flags_mask, - .meta_data_type = command.meta_data_type, - .meta_data = meta_data, - .ad_type = command.ad_type, - .data = data, - .data_mask = data_mask, - .irk = irk, + .type = command.type_, + .address = command.address, + .addr_type = command.addr_type, + .uuid = command.uuid, + .uuid_mask = command.uuid_mask, + .name = name, + .company = command.company, + .company_mask = command.company_mask, + .org_id = command.org_id, + .tds_flags = command.tds_flags, + .tds_flags_mask = command.tds_flags_mask, + .meta_data_type = command.meta_data_type, + .meta_data = meta_data, + .ad_type = command.ad_type, + .data = data, + .data_mask = data_mask, + .irk = irk, }; return converted; @@ -90,15 +90,16 @@ std::vector ConvertRustByteArray(const ::rust::Vec& bytes) { MsftAdvMonitorPattern ConvertAdvMonitorPattern(const RustMsftAdvMonitorPattern& pattern) { MsftAdvMonitorPattern converted = { - .ad_type = pattern.ad_type, - .start_byte = pattern.start_byte, - .pattern = ConvertRustByteArray(pattern.pattern), + .ad_type = pattern.ad_type, + .start_byte = pattern.start_byte, + .pattern = ConvertRustByteArray(pattern.pattern), }; return converted; } -std::vector ConvertAdvMonitorPatterns(const ::rust::Vec& patterns) { +std::vector ConvertAdvMonitorPatterns( + const ::rust::Vec& patterns) { std::vector converted; for (const auto& pattern : patterns) { @@ -117,13 +118,13 @@ MsftAdvMonitorAddress ConvertAdvMonitorAddress(RustMsftAdvMonitorAddress rust_ad MsftAdvMonitor ConvertAdvMonitor(const RustMsftAdvMonitor& monitor) { MsftAdvMonitor converted = { - .rssi_threshold_high = monitor.rssi_high_threshold, - .rssi_threshold_low = monitor.rssi_low_threshold, - .rssi_threshold_low_time_interval = monitor.rssi_low_timeout, - .rssi_sampling_period = monitor.rssi_sampling_period, - .condition_type = monitor.condition_type, - .patterns = ConvertAdvMonitorPatterns(monitor.patterns), - .addr_info = ConvertAdvMonitorAddress(monitor.addr_info), + .rssi_threshold_high = monitor.rssi_high_threshold, + .rssi_threshold_low = monitor.rssi_low_threshold, + .rssi_threshold_low_time_interval = monitor.rssi_low_timeout, + .rssi_sampling_period = monitor.rssi_sampling_period, + .condition_type = monitor.condition_type, + .patterns = ConvertAdvMonitorPatterns(monitor.patterns), + .addr_info = ConvertAdvMonitorAddress(monitor.addr_info), }; return converted; } @@ -131,66 +132,55 @@ MsftAdvMonitor ConvertAdvMonitor(const RustMsftAdvMonitor& monitor) { // ScanningCallbacks implementations -void BleScannerIntf::OnScannerRegistered(const bluetooth::Uuid app_uuid, uint8_t scannerId, uint8_t status) { - rusty::gdscan_on_scanner_registered(reinterpret_cast(&app_uuid), scannerId, status); +void BleScannerIntf::OnScannerRegistered(const bluetooth::Uuid app_uuid, uint8_t scannerId, + uint8_t status) { + rusty::gdscan_on_scanner_registered(reinterpret_cast(&app_uuid), scannerId, + status); } void BleScannerIntf::OnSetScannerParameterComplete(uint8_t scannerId, uint8_t status) { rusty::gdscan_on_set_scanner_parameter_complete(scannerId, status); } -void BleScannerIntf::OnScanResult( - uint16_t event_type, - uint8_t addr_type, - RawAddress addr, - uint8_t primary_phy, - uint8_t secondary_phy, - uint8_t advertising_sid, - int8_t tx_power, - int8_t rssi, - uint16_t periodic_adv_int, - std::vector adv_data) { - rusty::gdscan_on_scan_result( - event_type, - addr_type, - &addr, - primary_phy, - secondary_phy, - advertising_sid, - tx_power, - rssi, - periodic_adv_int, - adv_data.data(), - adv_data.size()); +void BleScannerIntf::OnScanResult(uint16_t event_type, uint8_t addr_type, RawAddress addr, + uint8_t primary_phy, uint8_t secondary_phy, + uint8_t advertising_sid, int8_t tx_power, int8_t rssi, + uint16_t periodic_adv_int, std::vector adv_data) { + rusty::gdscan_on_scan_result(event_type, addr_type, &addr, primary_phy, secondary_phy, + advertising_sid, tx_power, rssi, periodic_adv_int, adv_data.data(), + adv_data.size()); } void BleScannerIntf::OnTrackAdvFoundLost(AdvertisingTrackInfo ati) { rusty::RustAdvertisingTrackInfo rust_info = { - .monitor_handle = ati.monitor_handle, - .scanner_id = ati.scanner_id, - .filter_index = ati.filter_index, - .advertiser_state = ati.advertiser_state, - .advertiser_info_present = ati.advertiser_info_present, - .advertiser_address = ati.advertiser_address, - .advertiser_address_type = ati.advertiser_address_type, - .tx_power = ati.tx_power, - .rssi = ati.rssi, - .timestamp = ati.time_stamp, - .adv_packet_len = ati.adv_packet_len, - // .adv_packet is copied below - .scan_response_len = ati.scan_response_len, - // .scan_response is copied below + .monitor_handle = ati.monitor_handle, + .scanner_id = ati.scanner_id, + .filter_index = ati.filter_index, + .advertiser_state = ati.advertiser_state, + .advertiser_info_present = ati.advertiser_info_present, + .advertiser_address = ati.advertiser_address, + .advertiser_address_type = ati.advertiser_address_type, + .tx_power = ati.tx_power, + .rssi = ati.rssi, + .timestamp = ati.time_stamp, + .adv_packet_len = ati.adv_packet_len, + // .adv_packet is copied below + .scan_response_len = ati.scan_response_len, + // .scan_response is copied below }; - std::copy(rust_info.adv_packet.begin(), rust_info.adv_packet.end(), std::back_inserter(ati.adv_packet)); - std::copy(rust_info.scan_response.begin(), rust_info.scan_response.end(), std::back_inserter(ati.scan_response)); + std::copy(rust_info.adv_packet.begin(), rust_info.adv_packet.end(), + std::back_inserter(ati.adv_packet)); + std::copy(rust_info.scan_response.begin(), rust_info.scan_response.end(), + std::back_inserter(ati.scan_response)); rusty::gdscan_on_track_adv_found_lost(rust_info); } -void BleScannerIntf::OnBatchScanReports( - int client_if, int status, int report_format, int num_records, std::vector data) { - rusty::gdscan_on_batch_scan_reports(client_if, status, report_format, num_records, data.data(), data.size()); +void BleScannerIntf::OnBatchScanReports(int client_if, int status, int report_format, + int num_records, std::vector data) { + rusty::gdscan_on_batch_scan_reports(client_if, status, report_format, num_records, data.data(), + data.size()); } void BleScannerIntf::OnBatchScanThresholdCrossed(int client_if) { @@ -201,123 +191,97 @@ void BleScannerIntf::OnBatchScanThresholdCrossed(int client_if) { void BleScannerIntf::RegisterScanner(Uuid uuid) { scanner_intf_->RegisterScanner( - uuid, base::Bind(&BleScannerIntf::OnRegisterCallback, base::Unretained(this), uuid)); + uuid, base::Bind(&BleScannerIntf::OnRegisterCallback, base::Unretained(this), uuid)); } -void BleScannerIntf::Unregister(uint8_t scanner_id) { - scanner_intf_->Unregister(scanner_id); -} +void BleScannerIntf::Unregister(uint8_t scanner_id) { scanner_intf_->Unregister(scanner_id); } -void BleScannerIntf::Scan(bool start) { - scanner_intf_->Scan(start); -} +void BleScannerIntf::Scan(bool start) { scanner_intf_->Scan(start); } -void BleScannerIntf::ScanFilterParamSetup( - uint8_t scanner_id, - uint8_t action, - uint8_t filter_index, - btgatt_filt_param_setup_t filter_param) { +void BleScannerIntf::ScanFilterParamSetup(uint8_t scanner_id, uint8_t action, uint8_t filter_index, + btgatt_filt_param_setup_t filter_param) { auto converted = std::make_unique<::btgatt_filt_param_setup_t>(std::move(filter_param)); - scanner_intf_->ScanFilterParamSetup( - scanner_id, - action, - filter_index, - std::move(converted), - base::Bind(&BleScannerIntf::OnFilterParamSetupCallback, base::Unretained(this), scanner_id)); + scanner_intf_->ScanFilterParamSetup(scanner_id, action, filter_index, std::move(converted), + base::Bind(&BleScannerIntf::OnFilterParamSetupCallback, + base::Unretained(this), scanner_id)); } void BleScannerIntf::ScanFilterAdd(uint8_t filter_index, ::rust::Vec filters) { auto converted = internal::ConvertApcfVec(filters); - scanner_intf_->ScanFilterAdd( - filter_index, - converted, - base::Bind(&BleScannerIntf::OnFilterConfigCallback, base::Unretained(this), filter_index)); + scanner_intf_->ScanFilterAdd(filter_index, converted, + base::Bind(&BleScannerIntf::OnFilterConfigCallback, + base::Unretained(this), filter_index)); } void BleScannerIntf::ScanFilterClear(uint8_t filter_index) { - scanner_intf_->ScanFilterClear( - filter_index, base::Bind(&BleScannerIntf::OnFilterConfigCallback, base::Unretained(this), filter_index)); + scanner_intf_->ScanFilterClear(filter_index, base::Bind(&BleScannerIntf::OnFilterConfigCallback, + base::Unretained(this), filter_index)); } void BleScannerIntf::ScanFilterEnable(bool enable) { - scanner_intf_->ScanFilterEnable(enable, base::Bind(&BleScannerIntf::OnEnableCallback, base::Unretained(this))); + scanner_intf_->ScanFilterEnable( + enable, base::Bind(&BleScannerIntf::OnEnableCallback, base::Unretained(this))); } #if TARGET_FLOSS -bool BleScannerIntf::IsMsftSupported() { - return scanner_intf_->IsMsftSupported(); -} +bool BleScannerIntf::IsMsftSupported() { return scanner_intf_->IsMsftSupported(); } void BleScannerIntf::MsftAdvMonitorAdd(uint32_t call_id, const RustMsftAdvMonitor& monitor) { - scanner_intf_->MsftAdvMonitorAdd( - internal::ConvertAdvMonitor(monitor), - base::Bind(&BleScannerIntf::OnMsftAdvMonitorAddCallback, base::Unretained(this), call_id)); + scanner_intf_->MsftAdvMonitorAdd(internal::ConvertAdvMonitor(monitor), + base::Bind(&BleScannerIntf::OnMsftAdvMonitorAddCallback, + base::Unretained(this), call_id)); } void BleScannerIntf::MsftAdvMonitorRemove(uint32_t call_id, uint8_t monitor_handle) { - scanner_intf_->MsftAdvMonitorRemove( - monitor_handle, base::Bind(&BleScannerIntf::OnMsftAdvMonitorRemoveCallback, base::Unretained(this), call_id)); + scanner_intf_->MsftAdvMonitorRemove(monitor_handle, + base::Bind(&BleScannerIntf::OnMsftAdvMonitorRemoveCallback, + base::Unretained(this), call_id)); } void BleScannerIntf::MsftAdvMonitorEnable(uint32_t call_id, bool enable) { - scanner_intf_->MsftAdvMonitorEnable( - enable, base::Bind(&BleScannerIntf::OnMsftAdvMonitorEnableCallback, base::Unretained(this), call_id)); + scanner_intf_->MsftAdvMonitorEnable(enable, + base::Bind(&BleScannerIntf::OnMsftAdvMonitorEnableCallback, + base::Unretained(this), call_id)); } #else -bool BleScannerIntf::IsMsftSupported() { - return false; -} +bool BleScannerIntf::IsMsftSupported() { return false; } void BleScannerIntf::MsftAdvMonitorAdd(uint32_t, const RustMsftAdvMonitor&) {} void BleScannerIntf::MsftAdvMonitorRemove(uint32_t, uint8_t) {} void BleScannerIntf::MsftAdvMonitorEnable(uint32_t, bool) {} #endif -void BleScannerIntf::SetScanParameters( - uint8_t scanner_id, - uint8_t scan_type, - uint16_t scan_interval, - uint16_t scan_window, - uint8_t scan_phy) { +void BleScannerIntf::SetScanParameters(uint8_t scanner_id, uint8_t scan_type, + uint16_t scan_interval, uint16_t scan_window, + uint8_t scan_phy) { scanner_intf_->SetScanParameters( - scanner_id, - scan_type, - scan_interval, - scan_window, - scan_phy, - base::Bind(&BleScannerIntf::OnStatusCallback, base::Unretained(this), scanner_id)); -} - -void BleScannerIntf::BatchscanConfigStorage( - uint8_t scanner_id, - int32_t batch_scan_full_max, - int32_t batch_scan_trunc_max, - int32_t batch_scan_notify_threshold) { + scanner_id, scan_type, scan_interval, scan_window, scan_phy, + base::Bind(&BleScannerIntf::OnStatusCallback, base::Unretained(this), scanner_id)); +} + +void BleScannerIntf::BatchscanConfigStorage(uint8_t scanner_id, int32_t batch_scan_full_max, + int32_t batch_scan_trunc_max, + int32_t batch_scan_notify_threshold) { scanner_intf_->BatchscanConfigStorage( - scanner_id, - batch_scan_full_max, - batch_scan_trunc_max, - batch_scan_notify_threshold, - base::Bind(&BleScannerIntf::OnStatusCallback, base::Unretained(this), scanner_id)); + scanner_id, batch_scan_full_max, batch_scan_trunc_max, batch_scan_notify_threshold, + base::Bind(&BleScannerIntf::OnStatusCallback, base::Unretained(this), scanner_id)); } -void BleScannerIntf::BatchscanEnable( - int32_t scan_mode, uint16_t scan_interval, uint16_t scan_window, int32_t addr_type, int32_t discard_rule) { +void BleScannerIntf::BatchscanEnable(int32_t scan_mode, uint16_t scan_interval, + uint16_t scan_window, int32_t addr_type, + int32_t discard_rule) { scanner_intf_->BatchscanEnable( - scan_mode, - scan_interval, - scan_window, - addr_type, - discard_rule, - base::Bind(&BleScannerIntf::OnStatusCallback, base::Unretained(this), 0)); + scan_mode, scan_interval, scan_window, addr_type, discard_rule, + base::Bind(&BleScannerIntf::OnStatusCallback, base::Unretained(this), 0)); } void BleScannerIntf::BatchscanDisable() { - scanner_intf_->BatchscanDisable(base::Bind(&BleScannerIntf::OnStatusCallback, base::Unretained(this), 0)); + scanner_intf_->BatchscanDisable( + base::Bind(&BleScannerIntf::OnStatusCallback, base::Unretained(this), 0)); } void BleScannerIntf::BatchscanReadReports(uint8_t scanner_id, int32_t scan_mode) { @@ -328,9 +292,7 @@ void BleScannerIntf::StartSync(uint8_t sid, RawAddress addr, uint16_t skip, uint scanner_intf_->StartSync(sid, addr, skip, timeout, 0 /* place holder */); } -void BleScannerIntf::StopSync(uint16_t handle) { - scanner_intf_->StopSync(handle); -} +void BleScannerIntf::StopSync(uint16_t handle) { scanner_intf_->StopSync(handle); } void BleScannerIntf::CancelCreateSync(uint8_t sid, RawAddress addr) { scanner_intf_->CancelCreateSync(sid, addr); @@ -344,7 +306,8 @@ void BleScannerIntf::TransferSetInfo(RawAddress addr, uint16_t service_data, uin scanner_intf_->TransferSetInfo(addr, service_data, adv_handle, 0 /* place holder */); } -void BleScannerIntf::SyncTxParameters(RawAddress addr, uint8_t mode, uint16_t skip, uint16_t timeout) { +void BleScannerIntf::SyncTxParameters(RawAddress addr, uint8_t mode, uint16_t skip, + uint16_t timeout) { scanner_intf_->SyncTxParameters(addr, mode, skip, timeout, 0 /* place holder */); } @@ -360,18 +323,20 @@ void BleScannerIntf::OnEnableCallback(uint8_t action, uint8_t btm_status) { rusty::gdscan_enable_callback(action, btm_status); } -void BleScannerIntf::OnFilterParamSetupCallback( - uint8_t scanner_id, uint8_t avbl_space, uint8_t action_type, uint8_t btm_status) { +void BleScannerIntf::OnFilterParamSetupCallback(uint8_t scanner_id, uint8_t avbl_space, + uint8_t action_type, uint8_t btm_status) { rusty::gdscan_filter_param_setup_callback(scanner_id, avbl_space, action_type, btm_status); } -void BleScannerIntf::OnFilterConfigCallback( - uint8_t filter_index, uint8_t filt_type, uint8_t avbl_space, uint8_t action, uint8_t btm_status) { +void BleScannerIntf::OnFilterConfigCallback(uint8_t filter_index, uint8_t filt_type, + uint8_t avbl_space, uint8_t action, + uint8_t btm_status) { rusty::gdscan_filter_config_callback(filter_index, filt_type, avbl_space, action, btm_status); } #if TARGET_FLOSS -void BleScannerIntf::OnMsftAdvMonitorAddCallback(uint32_t call_id, uint8_t monitor_handle, uint8_t status) { +void BleScannerIntf::OnMsftAdvMonitorAddCallback(uint32_t call_id, uint8_t monitor_handle, + uint8_t status) { rusty::gdscan_msft_adv_monitor_add_callback(call_id, monitor_handle, status); } @@ -384,20 +349,15 @@ void BleScannerIntf::OnMsftAdvMonitorEnableCallback(uint32_t call_id, uint8_t st } #endif -void BleScannerIntf::OnPeriodicSyncStarted( - int, - uint8_t status, - uint16_t sync_handle, - uint8_t advertising_sid, - uint8_t address_type, - RawAddress addr, - uint8_t phy, - uint16_t interval) { - rusty::gdscan_start_sync_callback(status, sync_handle, advertising_sid, address_type, &addr, phy, interval); +void BleScannerIntf::OnPeriodicSyncStarted(int, uint8_t status, uint16_t sync_handle, + uint8_t advertising_sid, uint8_t address_type, + RawAddress addr, uint8_t phy, uint16_t interval) { + rusty::gdscan_start_sync_callback(status, sync_handle, advertising_sid, address_type, &addr, phy, + interval); } -void BleScannerIntf::OnPeriodicSyncReport( - uint16_t sync_handle, int8_t tx_power, int8_t rssi, uint8_t status, std::vector data) { +void BleScannerIntf::OnPeriodicSyncReport(uint16_t sync_handle, int8_t tx_power, int8_t rssi, + uint8_t status, std::vector data) { rusty::gdscan_sync_report_callback(sync_handle, tx_power, rssi, status, data.data(), data.size()); } @@ -420,7 +380,8 @@ void BleScannerIntf::RegisterCallbacks() { // ScanningCallbacks overrides std::unique_ptr GetBleScannerIntf(const unsigned char* gatt_intf) { - return std::make_unique(reinterpret_cast(gatt_intf)->scanner); + return std::make_unique( + reinterpret_cast(gatt_intf)->scanner); } } // namespace rust diff --git a/system/gd/rust/topshim/gatt/gatt_ble_scanner_shim.h b/system/gd/rust/topshim/gatt/gatt_ble_scanner_shim.h index 5712a973c28..14c5d480ab8 100644 --- a/system/gd/rust/topshim/gatt/gatt_ble_scanner_shim.h +++ b/system/gd/rust/topshim/gatt/gatt_ble_scanner_shim.h @@ -29,45 +29,32 @@ struct RustApcfCommand; struct RustMsftAdvMonitor; class BleScannerIntf : public ScanningCallbacks { - public: - BleScannerIntf(BleScannerInterface* scanner_intf) : scanner_intf_(scanner_intf){}; +public: + BleScannerIntf(BleScannerInterface* scanner_intf) : scanner_intf_(scanner_intf) {} ~BleScannerIntf() = default; // ScanningCallbacks overrides - void OnScannerRegistered(const bluetooth::Uuid app_uuid, uint8_t scannerId, uint8_t status) override; + void OnScannerRegistered(const bluetooth::Uuid app_uuid, uint8_t scannerId, + uint8_t status) override; void OnSetScannerParameterComplete(uint8_t scannerId, uint8_t status) override; - void OnScanResult( - uint16_t event_type, - uint8_t addr_type, - RawAddress bda, - uint8_t primary_phy, - uint8_t secondary_phy, - uint8_t advertising_sid, - int8_t tx_power, - int8_t rssi, - uint16_t periodic_adv_int, - std::vector adv_data) override; + void OnScanResult(uint16_t event_type, uint8_t addr_type, RawAddress bda, uint8_t primary_phy, + uint8_t secondary_phy, uint8_t advertising_sid, int8_t tx_power, int8_t rssi, + uint16_t periodic_adv_int, std::vector adv_data) override; void OnTrackAdvFoundLost(AdvertisingTrackInfo advertising_track_info) override; - void OnBatchScanReports( - int client_if, int status, int report_format, int num_records, std::vector data) override; + void OnBatchScanReports(int client_if, int status, int report_format, int num_records, + std::vector data) override; void OnBatchScanThresholdCrossed(int client_if) override; - void OnPeriodicSyncStarted( - int reg_id, - uint8_t status, - uint16_t sync_handle, - uint8_t advertising_sid, - uint8_t address_type, - RawAddress address, - uint8_t phy, - uint16_t interval) override; - void OnPeriodicSyncReport( - uint16_t sync_handle, int8_t tx_power, int8_t rssi, uint8_t status, std::vector data) override; + void OnPeriodicSyncStarted(int reg_id, uint8_t status, uint16_t sync_handle, + uint8_t advertising_sid, uint8_t address_type, RawAddress address, + uint8_t phy, uint16_t interval) override; + void OnPeriodicSyncReport(uint16_t sync_handle, int8_t tx_power, int8_t rssi, uint8_t status, + std::vector data) override; void OnPeriodicSyncLost(uint16_t sync_handle) override; void OnPeriodicSyncTransferred(int pa_source, uint8_t status, RawAddress address) override; void OnBigInfoReport(uint16_t sync_handle, bool encrypted) override; @@ -88,11 +75,8 @@ class BleScannerIntf : public ScanningCallbacks { // Setup scan filter parameters. Get responses via // |OnFilterParamSetupCallback|. - void ScanFilterParamSetup( - uint8_t scanner_id, - uint8_t action, - uint8_t filter_index, - btgatt_filt_param_setup_t filter_param); + void ScanFilterParamSetup(uint8_t scanner_id, uint8_t action, uint8_t filter_index, + btgatt_filt_param_setup_t filter_param); // Adds filters to given filter index. Gets responses via // |OnFilterConfigCallback|. @@ -118,24 +102,17 @@ class BleScannerIntf : public ScanningCallbacks { // Sets the LE scan interval and window in units of N * 0.625 msec. The result // of this action is returned via |OnStatusCallback|. - void SetScanParameters( - uint8_t scanner_id, - uint8_t scan_type, - uint16_t scan_interval, - uint16_t scan_window, - uint8_t scan_phy); + void SetScanParameters(uint8_t scanner_id, uint8_t scan_type, uint16_t scan_interval, + uint16_t scan_window, uint8_t scan_phy); // Configure the batchscan storage and get a response via |OnStatusCallback|. - void BatchscanConfigStorage( - uint8_t scanner_id, - int32_t batch_scan_full_max, - int32_t batch_scan_trunc_max, - int32_t batch_scan_notify_threshold); + void BatchscanConfigStorage(uint8_t scanner_id, int32_t batch_scan_full_max, + int32_t batch_scan_trunc_max, int32_t batch_scan_notify_threshold); // Enable batchscan. Gets responses via |OnStatusCallback| with scanner id // = 0 (since multiple scanners can be registered). - void BatchscanEnable( - int32_t scan_mode, uint16_t scan_interval, uint16_t scan_window, int32_t addr_type, int32_t discard_rule); + void BatchscanEnable(int32_t scan_mode, uint16_t scan_interval, uint16_t scan_window, + int32_t addr_type, int32_t discard_rule); // Disable batchscan. Gets responses via |OnStatusCallback| with a scanner id // = 0 (since multiple scanners can be registered). @@ -169,7 +146,7 @@ class BleScannerIntf : public ScanningCallbacks { // methods. void RegisterCallbacks(); - private: +private: // The callback functions below will get base::Bind to the apis that need it // and will call the same Rust function with all the parameters. Some of these // callbacks don't have all the parameters coming back in the original @@ -178,9 +155,10 @@ class BleScannerIntf : public ScanningCallbacks { void OnRegisterCallback(bluetooth::Uuid uuid, uint8_t scanner_id, uint8_t btm_status); void OnStatusCallback(uint8_t scanner_id, uint8_t btm_status); void OnEnableCallback(uint8_t action, uint8_t btm_status); - void OnFilterParamSetupCallback(uint8_t scanner_id, uint8_t avbl_space, uint8_t action_type, uint8_t btm_status); - void OnFilterConfigCallback( - uint8_t filt_index, uint8_t filt_type, uint8_t avbl_space, uint8_t action, uint8_t btm_status); + void OnFilterParamSetupCallback(uint8_t scanner_id, uint8_t avbl_space, uint8_t action_type, + uint8_t btm_status); + void OnFilterConfigCallback(uint8_t filt_index, uint8_t filt_type, uint8_t avbl_space, + uint8_t action, uint8_t btm_status); #if TARGET_FLOSS void OnMsftAdvMonitorAddCallback(uint32_t call_id, uint8_t monitor_handle, uint8_t status); void OnMsftAdvMonitorRemoveCallback(uint32_t call_id, uint8_t status); diff --git a/system/gd/rust/topshim/gatt/gatt_shim.cc b/system/gd/rust/topshim/gatt/gatt_shim.cc index 4438f90fcf1..3ddc3c54ac2 100644 --- a/system/gd/rust/topshim/gatt/gatt_shim.cc +++ b/system/gd/rust/topshim/gatt/gatt_shim.cc @@ -25,12 +25,13 @@ namespace rust { namespace internal { -void ReadPhyCallback(int client_if, RawAddress addr, uint8_t tx_phy, uint8_t rx_phy, uint8_t status) { +void ReadPhyCallback(int client_if, RawAddress addr, uint8_t tx_phy, uint8_t rx_phy, + uint8_t status) { bluetooth::topshim::rust::read_phy_callback(client_if, addr, tx_phy, rx_phy, status); } -void ServerReadPhyCallback( - int server_if, RawAddress addr, uint8_t tx_phy, uint8_t rx_phy, uint8_t status) { +void ServerReadPhyCallback(int server_if, RawAddress addr, uint8_t tx_phy, uint8_t rx_phy, + uint8_t status) { bluetooth::topshim::rust::server_read_phy_callback(server_if, addr, tx_phy, rx_phy, status); } @@ -41,17 +42,18 @@ int GattClientIntf::read_phy(int client_if, RawAddress addr) { } std::unique_ptr GetGattClientProfile(const unsigned char* gatt_intf) { - return std::make_unique(reinterpret_cast(gatt_intf)->client); + return std::make_unique( + reinterpret_cast(gatt_intf)->client); } int GattServerIntf::server_read_phy(int server_if, RawAddress addr) { - return server_intf_->read_phy( - addr, base::Bind(&internal::ServerReadPhyCallback, server_if, addr)); + return server_intf_->read_phy(addr, + base::Bind(&internal::ServerReadPhyCallback, server_if, addr)); } std::unique_ptr GetGattServerProfile(const unsigned char* gatt_intf) { return std::make_unique( - reinterpret_cast(gatt_intf)->server); + reinterpret_cast(gatt_intf)->server); } } // namespace rust diff --git a/system/gd/rust/topshim/gatt/gatt_shim.h b/system/gd/rust/topshim/gatt/gatt_shim.h index 7140536b5dc..b76a772cd91 100644 --- a/system/gd/rust/topshim/gatt/gatt_shim.h +++ b/system/gd/rust/topshim/gatt/gatt_shim.h @@ -19,7 +19,6 @@ #include #include "include/hardware/bt_gatt.h" - #include "rust/cxx.h" namespace bluetooth { @@ -27,26 +26,26 @@ namespace topshim { namespace rust { class GattClientIntf { - public: - GattClientIntf(const btgatt_client_interface_t* client_intf) : client_intf_(client_intf){}; +public: + GattClientIntf(const btgatt_client_interface_t* client_intf) : client_intf_(client_intf) {} ~GattClientIntf() = default; int read_phy(int client_if, RawAddress bt_addr); - private: +private: const btgatt_client_interface_t* client_intf_; }; std::unique_ptr GetGattClientProfile(const unsigned char* gatt_intf); class GattServerIntf { - public: - GattServerIntf(const btgatt_server_interface_t* server_intf) : server_intf_(server_intf){}; +public: + GattServerIntf(const btgatt_server_interface_t* server_intf) : server_intf_(server_intf) {} ~GattServerIntf() = default; int server_read_phy(int server_if, RawAddress bt_addr); - private: +private: const btgatt_server_interface_t* server_intf_; }; diff --git a/system/gd/rust/topshim/hfp/hfp_shim.cc b/system/gd/rust/topshim/hfp/hfp_shim.cc index 45db60ef6a8..12c338e535e 100644 --- a/system/gd/rust/topshim/hfp/hfp_shim.cc +++ b/system/gd/rust/topshim/hfp/hfp_shim.cc @@ -34,7 +34,8 @@ namespace rust { namespace internal { static HfpIntf* g_hfpif; -static void connection_state_cb(bluetooth::headset::bthf_connection_state_t state, RawAddress* addr) { +static void connection_state_cb(bluetooth::headset::bthf_connection_state_t state, + RawAddress* addr) { rusty::hfp_connection_state_callback(state, *addr); } @@ -58,21 +59,15 @@ static void battery_level_update_cb(uint8_t battery_level, RawAddress* addr) { rusty::hfp_battery_level_update_callback(battery_level, *addr); } -static void indicator_query_cb(RawAddress* addr) { - rusty::hfp_indicator_query_callback(*addr); -} +static void indicator_query_cb(RawAddress* addr) { rusty::hfp_indicator_query_callback(*addr); } static void current_calls_query_cb(RawAddress* addr) { rusty::hfp_current_calls_query_callback(*addr); } -static void answer_call_cb(RawAddress* addr) { - rusty::hfp_answer_call_callback(*addr); -} +static void answer_call_cb(RawAddress* addr) { rusty::hfp_answer_call_callback(*addr); } -static void hangup_call_cb(RawAddress* addr) { - rusty::hfp_hangup_call_callback(*addr); -} +static void hangup_call_cb(RawAddress* addr) { rusty::hfp_hangup_call_callback(*addr); } static void dial_call_cb(char* number, RawAddress* addr) { rusty::hfp_dial_call_callback(::rust::String{number}, *addr); @@ -118,38 +113,27 @@ static headset::bthf_call_state_t from_rust_call_state(rusty::CallState state) { } } -static void debug_dump_cb( - bool active, - uint16_t codec_id, - int total_num_decoded_frames, - double packet_loss_ratio, - uint64_t begin_ts, - uint64_t end_ts, - const char* pkt_status_in_hex, - const char* pkt_status_in_binary) { - rusty::hfp_debug_dump_callback( - active, - codec_id, - total_num_decoded_frames, - packet_loss_ratio, - begin_ts, - end_ts, - ::rust::String{pkt_status_in_hex}, - ::rust::String{pkt_status_in_binary}); +static void debug_dump_cb(bool active, uint16_t codec_id, int total_num_decoded_frames, + double packet_loss_ratio, uint64_t begin_ts, uint64_t end_ts, + const char* pkt_status_in_hex, const char* pkt_status_in_binary) { + rusty::hfp_debug_dump_callback(active, codec_id, total_num_decoded_frames, packet_loss_ratio, + begin_ts, end_ts, ::rust::String{pkt_status_in_hex}, + ::rust::String{pkt_status_in_binary}); } } // namespace internal class DBusHeadsetCallbacks : public headset::Callbacks { - public: +public: static Callbacks* GetInstance(headset::Interface* headset) { static Callbacks* instance = new DBusHeadsetCallbacks(headset); return instance; } - DBusHeadsetCallbacks(headset::Interface* headset) : headset_(headset){}; + DBusHeadsetCallbacks(headset::Interface* headset) : headset_(headset) {} // headset::Callbacks - void ConnectionStateCallback(headset::bthf_connection_state_t state, RawAddress* bd_addr) override { + void ConnectionStateCallback(headset::bthf_connection_state_t state, + RawAddress* bd_addr) override { log::info("ConnectionStateCallback from {}", *bd_addr); topshim::rust::internal::connection_state_cb(state, bd_addr); } @@ -159,8 +143,8 @@ class DBusHeadsetCallbacks : public headset::Callbacks { topshim::rust::internal::audio_state_cb(state, bd_addr); } - void VoiceRecognitionCallback( - [[maybe_unused]] headset::bthf_vr_state_t state, [[maybe_unused]] RawAddress* bd_addr) override {} + void VoiceRecognitionCallback([[maybe_unused]] headset::bthf_vr_state_t state, + [[maybe_unused]] RawAddress* bd_addr) override {} void AnswerCallCallback(RawAddress* bd_addr) override { topshim::rust::internal::answer_call_cb(bd_addr); @@ -170,9 +154,14 @@ class DBusHeadsetCallbacks : public headset::Callbacks { topshim::rust::internal::hangup_call_cb(bd_addr); } - void VolumeControlCallback(headset::bthf_volume_type_t type, int volume, RawAddress* bd_addr) override { - if (volume < 0) return; - if (volume > 15) volume = 15; + void VolumeControlCallback(headset::bthf_volume_type_t type, int volume, + RawAddress* bd_addr) override { + if (volume < 0) { + return; + } + if (volume > 15) { + volume = 15; + } if (type == headset::bthf_volume_type_t::BTHF_VOLUME_TYPE_SPK) { log::info("VolumeControlCallback (Spk) {} from {}", volume, *bd_addr); topshim::rust::internal::volume_update_cb(volume, bd_addr); @@ -188,19 +177,19 @@ class DBusHeadsetCallbacks : public headset::Callbacks { void DtmfCmdCallback([[maybe_unused]] char tone, [[maybe_unused]] RawAddress* bd_addr) override {} - void NoiseReductionCallback( - [[maybe_unused]] headset::bthf_nrec_t nrec, [[maybe_unused]] RawAddress* bd_addr) override {} + void NoiseReductionCallback([[maybe_unused]] headset::bthf_nrec_t nrec, + [[maybe_unused]] RawAddress* bd_addr) override {} void WbsCallback(headset::bthf_wbs_config_t wbs, RawAddress* addr) override { log::info("WbsCallback {} from {}", wbs, *addr); rusty::hfp_wbs_caps_update_callback(wbs == headset::BTHF_WBS_YES, *addr); } - void SwbCallback( - headset::bthf_swb_codec_t codec, headset::bthf_swb_config_t swb, RawAddress* addr) override { + void SwbCallback(headset::bthf_swb_codec_t codec, headset::bthf_swb_config_t swb, + RawAddress* addr) override { log::info("SwbCallback codec:{}, swb:{} from {}", codec, swb, *addr); rusty::hfp_swb_caps_update_callback( - (codec == headset::BTHF_SWB_CODEC_LC3 && swb == headset::BTHF_SWB_YES), *addr); + (codec == headset::BTHF_SWB_CODEC_LC3 && swb == headset::BTHF_SWB_YES), *addr); } void AtChldCallback(headset::bthf_chld_type_t chld, RawAddress* bd_addr) override { @@ -253,11 +242,12 @@ class DBusHeadsetCallbacks : public headset::Callbacks { void KeyPressedCallback([[maybe_unused]] RawAddress* bd_addr) override {} void AtBindCallback(char* at_string, RawAddress* bd_addr) override { - log::warn( - "AT+BIND {} from addr {}: Bluetooth HF Indicators is not supported.", at_string, *bd_addr); + log::warn("AT+BIND {} from addr {}: Bluetooth HF Indicators is not supported.", at_string, + *bd_addr); } - void AtBievCallback(headset::bthf_hf_ind_type_t ind_id, int ind_value, RawAddress* bd_addr) override { + void AtBievCallback(headset::bthf_hf_ind_type_t ind_id, int ind_value, + RawAddress* bd_addr) override { switch (ind_id) { case headset::bthf_hf_ind_type_t::BTHF_HF_IND_ENHANCED_DRIVER_SAFETY: // We don't do anything with this but we do know what it is, send OK. @@ -273,60 +263,36 @@ class DBusHeadsetCallbacks : public headset::Callbacks { } } - void AtBiaCallback(bool service, bool roam, bool signal, bool battery, RawAddress* bd_addr) override { + void AtBiaCallback(bool service, bool roam, bool signal, bool battery, + RawAddress* bd_addr) override { log::warn("AT+BIA=,,{},{},{},{},from addr {}", service, signal, roam, battery, *bd_addr); } - void DebugDumpCallback( - bool active, - uint16_t codec_id, - int total_num_decoded_frames, - double packet_loss_ratio, - uint64_t begin_ts, - uint64_t end_ts, - const char* pkt_status_in_hex, - const char* pkt_status_in_binary) override { - log::warn( - "DebugDumpCallback {} {} {} {:f} {} {} {} {}", - active, - codec_id, - total_num_decoded_frames, - packet_loss_ratio, - (unsigned long long)begin_ts, - (unsigned long long)end_ts, - pkt_status_in_hex, - pkt_status_in_binary); - topshim::rust::internal::debug_dump_cb( - active, - codec_id, - total_num_decoded_frames, - packet_loss_ratio, - begin_ts, - end_ts, - pkt_status_in_hex, - pkt_status_in_binary); + void DebugDumpCallback(bool active, uint16_t codec_id, int total_num_decoded_frames, + double packet_loss_ratio, uint64_t begin_ts, uint64_t end_ts, + const char* pkt_status_in_hex, const char* pkt_status_in_binary) override { + log::warn("DebugDumpCallback {} {} {} {:f} {} {} {} {}", active, codec_id, + total_num_decoded_frames, packet_loss_ratio, (unsigned long long)begin_ts, + (unsigned long long)end_ts, pkt_status_in_hex, pkt_status_in_binary); + topshim::rust::internal::debug_dump_cb(active, codec_id, total_num_decoded_frames, + packet_loss_ratio, begin_ts, end_ts, pkt_status_in_hex, + pkt_status_in_binary); } - private: +private: headset::Interface* headset_; }; -int HfpIntf::init() { - return intf_->Init(DBusHeadsetCallbacks::GetInstance(intf_), 1, false); -} +int HfpIntf::init() { return intf_->Init(DBusHeadsetCallbacks::GetInstance(intf_), 1, false); } -uint32_t HfpIntf::connect(RawAddress addr) { - return intf_->Connect(&addr); -} +uint32_t HfpIntf::connect(RawAddress addr) { return intf_->Connect(&addr); } int HfpIntf::connect_audio(RawAddress addr, bool sco_offload, int disabled_codecs) { intf_->SetScoOffloadEnabled(sco_offload); return intf_->ConnectAudio(&addr, disabled_codecs); } -int HfpIntf::set_active_device(RawAddress addr) { - return intf_->SetActiveDevice(&addr); -} +int HfpIntf::set_active_device(RawAddress addr) { return intf_->SetActiveDevice(&addr); } int HfpIntf::set_volume(int8_t volume, RawAddress addr) { return intf_->VolumeControl(headset::bthf_volume_type_t::BTHF_VOLUME_TYPE_SPK, volume, &addr); @@ -336,96 +302,79 @@ uint32_t HfpIntf::set_mic_volume(int8_t volume, RawAddress addr) { return intf_->VolumeControl(headset::bthf_volume_type_t::BTHF_VOLUME_TYPE_MIC, volume, &addr); } -uint32_t HfpIntf::disconnect(RawAddress addr) { - return intf_->Disconnect(&addr); -} +uint32_t HfpIntf::disconnect(RawAddress addr) { return intf_->Disconnect(&addr); } -int HfpIntf::disconnect_audio(RawAddress addr) { - return intf_->DisconnectAudio(&addr); -} +int HfpIntf::disconnect_audio(RawAddress addr) { return intf_->DisconnectAudio(&addr); } uint32_t HfpIntf::device_status_notification(TelephonyDeviceStatus status, RawAddress addr) { return intf_->DeviceStatusNotification( - status.network_available ? headset::BTHF_NETWORK_STATE_AVAILABLE - : headset::BTHF_NETWORK_STATE_NOT_AVAILABLE, - status.roaming ? headset::BTHF_SERVICE_TYPE_ROAMING : headset::BTHF_SERVICE_TYPE_HOME, - status.signal_strength, - status.battery_level, - &addr); + status.network_available ? headset::BTHF_NETWORK_STATE_AVAILABLE + : headset::BTHF_NETWORK_STATE_NOT_AVAILABLE, + status.roaming ? headset::BTHF_SERVICE_TYPE_ROAMING : headset::BTHF_SERVICE_TYPE_HOME, + status.signal_strength, status.battery_level, &addr); } -uint32_t HfpIntf::indicator_query_response( - TelephonyDeviceStatus device_status, PhoneState phone_state, RawAddress addr) { - return intf_->CindResponse( - device_status.network_available ? 1 : 0, - phone_state.num_active, - phone_state.num_held, - topshim::rust::internal::from_rust_call_state(phone_state.state), - device_status.signal_strength, - device_status.roaming ? 1 : 0, - device_status.battery_level, - &addr); +uint32_t HfpIntf::indicator_query_response(TelephonyDeviceStatus device_status, + PhoneState phone_state, RawAddress addr) { + return intf_->CindResponse(device_status.network_available ? 1 : 0, phone_state.num_active, + phone_state.num_held, + topshim::rust::internal::from_rust_call_state(phone_state.state), + device_status.signal_strength, device_status.roaming ? 1 : 0, + device_status.battery_level, &addr); } -uint32_t HfpIntf::current_calls_query_response( - const ::rust::Vec& call_list, RawAddress addr) { +uint32_t HfpIntf::current_calls_query_response(const ::rust::Vec& call_list, + RawAddress addr) { for (const auto& c : call_list) { std::string number{c.number}; - intf_->ClccResponse( - c.index, - c.dir_incoming ? headset::BTHF_CALL_DIRECTION_INCOMING - : headset::BTHF_CALL_DIRECTION_OUTGOING, - topshim::rust::internal::from_rust_call_state(c.state), - /*mode=*/headset::BTHF_CALL_TYPE_VOICE, - /*multi_party=*/headset::BTHF_CALL_MPTY_TYPE_SINGLE, - number.c_str(), - /*type=*/headset::BTHF_CALL_ADDRTYPE_UNKNOWN, - &addr); + intf_->ClccResponse(c.index, + c.dir_incoming ? headset::BTHF_CALL_DIRECTION_INCOMING + : headset::BTHF_CALL_DIRECTION_OUTGOING, + topshim::rust::internal::from_rust_call_state(c.state), + /*mode=*/headset::BTHF_CALL_TYPE_VOICE, + /*multi_party=*/headset::BTHF_CALL_MPTY_TYPE_SINGLE, number.c_str(), + /*type=*/headset::BTHF_CALL_ADDRTYPE_UNKNOWN, &addr); } // NULL termination (Completes response) return intf_->ClccResponse( - /*index=*/0, - /*dir=*/(headset::bthf_call_direction_t)0, - /*state=*/(headset::bthf_call_state_t)0, - /*mode=*/(headset::bthf_call_mode_t)0, - /*multi_party=*/(headset::bthf_call_mpty_type_t)0, - /*number=*/"", - /*type=*/(headset::bthf_call_addrtype_t)0, - &addr); + /*index=*/0, + /*dir=*/(headset::bthf_call_direction_t)0, + /*state=*/(headset::bthf_call_state_t)0, + /*mode=*/(headset::bthf_call_mode_t)0, + /*multi_party=*/(headset::bthf_call_mpty_type_t)0, + /*number=*/"", + /*type=*/(headset::bthf_call_addrtype_t)0, &addr); } -uint32_t HfpIntf::phone_state_change( - PhoneState phone_state, const ::rust::String& number_rs, RawAddress addr) { +uint32_t HfpIntf::phone_state_change(PhoneState phone_state, const ::rust::String& number_rs, + RawAddress addr) { std::string number{number_rs}; - return intf_->PhoneStateChange( - phone_state.num_active, - phone_state.num_held, - topshim::rust::internal::from_rust_call_state(phone_state.state), - number.c_str(), - /*type=*/(headset::bthf_call_addrtype_t)0, - /*name=*/"", - &addr); + return intf_->PhoneStateChange(phone_state.num_active, phone_state.num_held, + topshim::rust::internal::from_rust_call_state(phone_state.state), + number.c_str(), + /*type=*/(headset::bthf_call_addrtype_t)0, + /*name=*/"", &addr); } uint32_t HfpIntf::simple_at_response(bool ok, RawAddress addr) { - return intf_->AtResponse( - (ok ? headset::BTHF_AT_RESPONSE_OK : headset::BTHF_AT_RESPONSE_ERROR), 0, &addr); + return intf_->AtResponse((ok ? headset::BTHF_AT_RESPONSE_OK : headset::BTHF_AT_RESPONSE_ERROR), 0, + &addr); } -void HfpIntf::debug_dump() { - intf_->DebugDump(); -} +void HfpIntf::debug_dump() { intf_->DebugDump(); } void HfpIntf::cleanup() {} std::unique_ptr GetHfpProfile(const unsigned char* btif) { - if (internal::g_hfpif) std::abort(); + if (internal::g_hfpif) { + std::abort(); + } const bt_interface_t* btif_ = reinterpret_cast(btif); auto hfpif = std::make_unique(const_cast( - reinterpret_cast(btif_->get_profile_interface("handsfree")))); + reinterpret_cast(btif_->get_profile_interface("handsfree")))); internal::g_hfpif = hfpif.get(); return hfpif; diff --git a/system/gd/rust/topshim/hfp/hfp_shim.h b/system/gd/rust/topshim/hfp/hfp_shim.h index f17aec9c536..0b769e98ced 100644 --- a/system/gd/rust/topshim/hfp/hfp_shim.h +++ b/system/gd/rust/topshim/hfp/hfp_shim.h @@ -32,8 +32,8 @@ struct CallInfo; struct PhoneState; class HfpIntf { - public: - HfpIntf(headset::Interface* intf) : intf_(intf){}; +public: + HfpIntf(headset::Interface* intf) : intf_(intf) {} int init(); uint32_t connect(RawAddress addr); @@ -44,16 +44,16 @@ class HfpIntf { uint32_t disconnect(RawAddress addr); int disconnect_audio(RawAddress addr); uint32_t device_status_notification(TelephonyDeviceStatus status, RawAddress addr); - uint32_t indicator_query_response( - TelephonyDeviceStatus device_status, PhoneState phone_state, RawAddress addr); + uint32_t indicator_query_response(TelephonyDeviceStatus device_status, PhoneState phone_state, + RawAddress addr); uint32_t current_calls_query_response(const ::rust::Vec& call_list, RawAddress addr); - uint32_t phone_state_change( - PhoneState phone_state, const ::rust::String& number, RawAddress addr); + uint32_t phone_state_change(PhoneState phone_state, const ::rust::String& number, + RawAddress addr); uint32_t simple_at_response(bool ok, RawAddress addr); void debug_dump(); void cleanup(); - private: +private: headset::Interface* intf_; }; diff --git a/system/gd/rust/topshim/le_audio/le_audio_shim.cc b/system/gd/rust/topshim/le_audio/le_audio_shim.cc index 87a3d35bdd2..bb70fc37d08 100644 --- a/system/gd/rust/topshim/le_audio/le_audio_shim.cc +++ b/system/gd/rust/topshim/le_audio/le_audio_shim.cc @@ -50,11 +50,11 @@ static uint8_t from_rust_btle_audio_direction(BtLeAudioDirection direction) { } static le_audio::btle_audio_codec_config_t from_rust_btle_audio_codec_config( - BtLeAudioCodecConfig codec_config) { + BtLeAudioCodecConfig codec_config) { switch (codec_config.codec_type) { case static_cast(BtLeAudioCodecIndex::SrcLc3): return le_audio::btle_audio_codec_config_t{ - .codec_type = le_audio::btle_audio_codec_index_t::LE_AUDIO_CODEC_INDEX_SOURCE_LC3}; + .codec_type = le_audio::btle_audio_codec_index_t::LE_AUDIO_CODEC_INDEX_SOURCE_LC3}; default: log::assert_that(false, "Unhandled enum value from C++"); } @@ -62,7 +62,7 @@ static le_audio::btle_audio_codec_config_t from_rust_btle_audio_codec_config( } static BtLeAudioCodecConfig to_rust_btle_audio_codec_config( - le_audio::btle_audio_codec_config_t codec_config) { + le_audio::btle_audio_codec_config_t codec_config) { switch (codec_config.codec_type) { case le_audio::btle_audio_codec_index_t::LE_AUDIO_CODEC_INDEX_SOURCE_LC3: return BtLeAudioCodecConfig{.codec_type = static_cast(BtLeAudioCodecIndex::SrcLc3)}; @@ -73,7 +73,7 @@ static BtLeAudioCodecConfig to_rust_btle_audio_codec_config( } static ::rust::vec to_rust_btle_audio_codec_config_vec( - std::vector codec_configs) { + std::vector codec_configs) { ::rust::vec rconfigs; for (auto c : codec_configs) { rconfigs.push_back(to_rust_btle_audio_codec_config(c)); @@ -82,7 +82,7 @@ static ::rust::vec to_rust_btle_audio_codec_config_vec( } static BtLeAudioConnectionState to_rust_btle_audio_connection_state( - le_audio::ConnectionState state) { + le_audio::ConnectionState state) { switch (state) { case le_audio::ConnectionState::DISCONNECTED: return BtLeAudioConnectionState::Disconnected; @@ -113,7 +113,7 @@ static BtLeAudioGroupStatus to_rust_btle_audio_group_status(le_audio::GroupStatu } static BtLeAudioGroupNodeStatus to_rust_btle_audio_group_node_status( - le_audio::GroupNodeStatus status) { + le_audio::GroupNodeStatus status) { switch (status) { case le_audio::GroupNodeStatus::ADDED: return BtLeAudioGroupNodeStatus::Added; @@ -126,7 +126,7 @@ static BtLeAudioGroupNodeStatus to_rust_btle_audio_group_node_status( } static BtLeAudioUnicastMonitorModeStatus to_rust_btle_audio_unicast_monitor_mode_status( - le_audio::UnicastMonitorModeStatus status) { + le_audio::UnicastMonitorModeStatus status) { switch (status) { case le_audio::UnicastMonitorModeStatus::STREAMING_REQUESTED: return BtLeAudioUnicastMonitorModeStatus::StreamingRequested; @@ -155,7 +155,7 @@ static BtLeAudioDirection to_rust_btle_audio_direction(uint8_t direction) { } static BtLeAudioGroupStreamStatus to_rust_btle_audio_group_stream_status( - le_audio::GroupStreamStatus status) { + le_audio::GroupStreamStatus status) { switch (status) { case le_audio::GroupStreamStatus::IDLE: return BtLeAudioGroupStreamStatus::Idle; @@ -179,9 +179,7 @@ static BtLeAudioGroupStreamStatus to_rust_btle_audio_group_stream_status( return BtLeAudioGroupStreamStatus{}; } -static void initialized_cb() { - le_audio_initialized_callback(); -} +static void initialized_cb() { le_audio_initialized_callback(); } static void connection_state_cb(le_audio::ConnectionState state, const RawAddress& address) { le_audio_connection_state_callback(to_rust_btle_audio_connection_state(state), address); @@ -191,69 +189,63 @@ static void group_status_cb(int group_id, le_audio::GroupStatus group_status) { le_audio_group_status_callback(group_id, to_rust_btle_audio_group_status(group_status)); } -static void group_node_status_cb( - const RawAddress& bd_addr, int group_id, le_audio::GroupNodeStatus node_status) { - le_audio_group_node_status_callback( - bd_addr, group_id, to_rust_btle_audio_group_node_status(node_status)); +static void group_node_status_cb(const RawAddress& bd_addr, int group_id, + le_audio::GroupNodeStatus node_status) { + le_audio_group_node_status_callback(bd_addr, group_id, + to_rust_btle_audio_group_node_status(node_status)); } -static void unicast_monitor_mode_status_cb( - uint8_t direction, le_audio::UnicastMonitorModeStatus status) { +static void unicast_monitor_mode_status_cb(uint8_t direction, + le_audio::UnicastMonitorModeStatus status) { le_audio_unicast_monitor_mode_status_callback( - to_rust_btle_audio_direction(direction), - to_rust_btle_audio_unicast_monitor_mode_status(status)); + to_rust_btle_audio_direction(direction), + to_rust_btle_audio_unicast_monitor_mode_status(status)); } static void group_stream_status_cb(int group_id, le_audio::GroupStreamStatus status) { le_audio_group_stream_status_callback(group_id, to_rust_btle_audio_group_stream_status(status)); } -static void audio_conf_cb( - uint8_t direction, - int group_id, - uint32_t snk_audio_location, - uint32_t src_audio_location, - uint16_t avail_cont) { - le_audio_audio_conf_callback( - direction, group_id, snk_audio_location, src_audio_location, avail_cont); +static void audio_conf_cb(uint8_t direction, int group_id, uint32_t snk_audio_location, + uint32_t src_audio_location, uint16_t avail_cont) { + le_audio_audio_conf_callback(direction, group_id, snk_audio_location, src_audio_location, + avail_cont); } -static void sink_audio_location_available_cb( - const RawAddress& address, uint32_t snk_audio_locations) { +static void sink_audio_location_available_cb(const RawAddress& address, + uint32_t snk_audio_locations) { le_audio_sink_audio_location_available_callback(address, snk_audio_locations); } static void audio_local_codec_capabilities_cb( - std::vector local_input_capa_codec_conf, - std::vector local_output_capa_codec_conf) { + std::vector local_input_capa_codec_conf, + std::vector local_output_capa_codec_conf) { le_audio_audio_local_codec_capabilities_callback( - to_rust_btle_audio_codec_config_vec(local_input_capa_codec_conf), - to_rust_btle_audio_codec_config_vec(local_output_capa_codec_conf)); + to_rust_btle_audio_codec_config_vec(local_input_capa_codec_conf), + to_rust_btle_audio_codec_config_vec(local_output_capa_codec_conf)); } static void audio_group_codec_conf_cb( - int group_id, - le_audio::btle_audio_codec_config_t input_codec_conf, - le_audio::btle_audio_codec_config_t output_codec_conf, - std::vector input_selectable_codec_conf, - std::vector output_selectable_codec_conf) { + int group_id, le_audio::btle_audio_codec_config_t input_codec_conf, + le_audio::btle_audio_codec_config_t output_codec_conf, + std::vector input_selectable_codec_conf, + std::vector output_selectable_codec_conf) { le_audio_audio_group_codec_conf_callback( - group_id, - to_rust_btle_audio_codec_config(input_codec_conf), - to_rust_btle_audio_codec_config(output_codec_conf), - to_rust_btle_audio_codec_config_vec(input_selectable_codec_conf), - to_rust_btle_audio_codec_config_vec(output_selectable_codec_conf)); + group_id, to_rust_btle_audio_codec_config(input_codec_conf), + to_rust_btle_audio_codec_config(output_codec_conf), + to_rust_btle_audio_codec_config_vec(input_selectable_codec_conf), + to_rust_btle_audio_codec_config_vec(output_selectable_codec_conf)); } } // namespace internal class DBusLeAudioClientCallbacks : public le_audio::LeAudioClientCallbacks { - public: +public: static le_audio::LeAudioClientCallbacks* GetInstance() { static auto instance = new DBusLeAudioClientCallbacks(); return instance; } - DBusLeAudioClientCallbacks(){}; + DBusLeAudioClientCallbacks() {} void OnInitialized() override { log::info(""); @@ -270,93 +262,72 @@ class DBusLeAudioClientCallbacks : public le_audio::LeAudioClientCallbacks { topshim::rust::internal::group_status_cb(group_id, group_status); } - void OnGroupNodeStatus( - const RawAddress& bd_addr, int group_id, le_audio::GroupNodeStatus node_status) { - log::info( - "bd_addr={}, group_id={}, node_status={}", - ADDRESS_TO_LOGGABLE_CSTR(bd_addr), - group_id, - static_cast(node_status)); + void OnGroupNodeStatus(const RawAddress& bd_addr, int group_id, + le_audio::GroupNodeStatus node_status) { + log::info("bd_addr={}, group_id={}, node_status={}", ADDRESS_TO_LOGGABLE_CSTR(bd_addr), + group_id, static_cast(node_status)); topshim::rust::internal::group_node_status_cb(bd_addr, group_id, node_status); } - void OnAudioConf( - uint8_t direction, - int group_id, - uint32_t snk_audio_location, - uint32_t src_audio_location, - uint16_t avail_cont) { + void OnAudioConf(uint8_t direction, int group_id, uint32_t snk_audio_location, + uint32_t src_audio_location, uint16_t avail_cont) { log::info( - "direction={}, group_id={}, snk_audio_location={}, src_audio_location={}, avail_cont={}", - direction, - group_id, - snk_audio_location, - src_audio_location, - avail_cont); - topshim::rust::internal::audio_conf_cb( - direction, group_id, snk_audio_location, src_audio_location, avail_cont); + "direction={}, group_id={}, snk_audio_location={}, src_audio_location={}, " + "avail_cont={}", + direction, group_id, snk_audio_location, src_audio_location, avail_cont); + topshim::rust::internal::audio_conf_cb(direction, group_id, snk_audio_location, + src_audio_location, avail_cont); } void OnSinkAudioLocationAvailable(const RawAddress& address, uint32_t snk_audio_locations) { - log::info( - "address={}, snk_audio_locations={}", - ADDRESS_TO_LOGGABLE_CSTR(address), - snk_audio_locations); + log::info("address={}, snk_audio_locations={}", ADDRESS_TO_LOGGABLE_CSTR(address), + snk_audio_locations); topshim::rust::internal::sink_audio_location_available_cb(address, snk_audio_locations); } void OnAudioLocalCodecCapabilities( - std::vector local_input_capa_codec_conf, - std::vector local_output_capa_codec_conf) { + std::vector local_input_capa_codec_conf, + std::vector local_output_capa_codec_conf) { log::info(""); - topshim::rust::internal::audio_local_codec_capabilities_cb( - local_input_capa_codec_conf, local_output_capa_codec_conf); + topshim::rust::internal::audio_local_codec_capabilities_cb(local_input_capa_codec_conf, + local_output_capa_codec_conf); } void OnAudioGroupCodecConf( - int group_id, - le_audio::btle_audio_codec_config_t input_codec_conf, - le_audio::btle_audio_codec_config_t output_codec_conf, - std::vector input_selectable_codec_conf, - std::vector output_selectable_codec_conf) { + int group_id, le_audio::btle_audio_codec_config_t input_codec_conf, + le_audio::btle_audio_codec_config_t output_codec_conf, + std::vector input_selectable_codec_conf, + std::vector output_selectable_codec_conf) { log::info("group_id={}", group_id); topshim::rust::internal::audio_group_codec_conf_cb( - group_id, - input_codec_conf, - output_codec_conf, - input_selectable_codec_conf, - output_selectable_codec_conf); + group_id, input_codec_conf, output_codec_conf, input_selectable_codec_conf, + output_selectable_codec_conf); } - void OnAudioGroupCurrentCodecConf( - int group_id, - le_audio::btle_audio_codec_config_t input_codec_conf, - le_audio::btle_audio_codec_config_t output_codec_conf) { - log::info( - "group_id={}, input_codec_conf={}, output_codec_conf={}", - group_id, - input_codec_conf.ToString(), - output_codec_conf.ToString()); + void OnAudioGroupCurrentCodecConf(int group_id, + le_audio::btle_audio_codec_config_t input_codec_conf, + le_audio::btle_audio_codec_config_t output_codec_conf) { + log::info("group_id={}, input_codec_conf={}, output_codec_conf={}", group_id, + input_codec_conf.ToString(), output_codec_conf.ToString()); } void OnAudioGroupSelectableCodecConf( - int group_id, - std::vector input_selectable_codec_conf, - std::vector output_selectable_codec_conf) { + int group_id, + std::vector input_selectable_codec_conf, + std::vector output_selectable_codec_conf) { log::info( - "group_id={}, input_selectable_codec_conf.size={}, output_selectable_codec_conf.size={}", - group_id, - input_selectable_codec_conf.size(), - output_selectable_codec_conf.size()); + "group_id={}, input_selectable_codec_conf.size={}, " + "output_selectable_codec_conf.size={}", + group_id, input_selectable_codec_conf.size(), output_selectable_codec_conf.size()); } - void OnHealthBasedRecommendationAction( - const RawAddress& address, le_audio::LeAudioHealthBasedAction action) { + void OnHealthBasedRecommendationAction(const RawAddress& address, + le_audio::LeAudioHealthBasedAction action) { log::info("address={}, action={}", ADDRESS_TO_LOGGABLE_CSTR(address), static_cast(action)); } - void OnHealthBasedGroupRecommendationAction( - int group_id, le_audio::LeAudioHealthBasedAction action) { + void OnHealthBasedGroupRecommendationAction(int group_id, + le_audio::LeAudioHealthBasedAction action) { log::info("group_id={}, action={}", group_id, static_cast(action)); } @@ -377,25 +348,17 @@ void LeAudioClientIntf::init(/* return intf_->Initialize(DBusLeAudioClientCallbacks::GetInstance(), {}); } -void LeAudioClientIntf::connect(RawAddress addr) { - return intf_->Connect(addr); -} +void LeAudioClientIntf::connect(RawAddress addr) { return intf_->Connect(addr); } -void LeAudioClientIntf::disconnect(RawAddress addr) { - return intf_->Disconnect(addr); -} +void LeAudioClientIntf::disconnect(RawAddress addr) { return intf_->Disconnect(addr); } void LeAudioClientIntf::set_enable_state(RawAddress addr, bool enabled) { return intf_->SetEnableState(addr, enabled); } -void LeAudioClientIntf::cleanup() { - return intf_->Cleanup(); -} +void LeAudioClientIntf::cleanup() { return intf_->Cleanup(); } -void LeAudioClientIntf::remove_device(RawAddress addr) { - return intf_->RemoveDevice(addr); -} +void LeAudioClientIntf::remove_device(RawAddress addr) { return intf_->RemoveDevice(addr); } void LeAudioClientIntf::group_add_node(int group_id, RawAddress addr) { return intf_->GroupAddNode(group_id, addr); @@ -405,32 +368,27 @@ void LeAudioClientIntf::group_remove_node(int group_id, RawAddress addr) { return intf_->GroupRemoveNode(group_id, addr); } -void LeAudioClientIntf::group_set_active(int group_id) { - return intf_->GroupSetActive(group_id); -} +void LeAudioClientIntf::group_set_active(int group_id) { return intf_->GroupSetActive(group_id); } -void LeAudioClientIntf::set_codec_config_preference( - int group_id, - BtLeAudioCodecConfig input_codec_config, - BtLeAudioCodecConfig output_codec_config) { +void LeAudioClientIntf::set_codec_config_preference(int group_id, + BtLeAudioCodecConfig input_codec_config, + BtLeAudioCodecConfig output_codec_config) { return intf_->SetCodecConfigPreference( - group_id, - internal::from_rust_btle_audio_codec_config(input_codec_config), - internal::from_rust_btle_audio_codec_config(output_codec_config)); + group_id, internal::from_rust_btle_audio_codec_config(input_codec_config), + internal::from_rust_btle_audio_codec_config(output_codec_config)); } void LeAudioClientIntf::set_ccid_information(int ccid, int context_type) { return intf_->SetCcidInformation(ccid, context_type); } -void LeAudioClientIntf::set_in_call(bool in_call) { - return intf_->SetInCall(in_call); -} +void LeAudioClientIntf::set_in_call(bool in_call) { return intf_->SetInCall(in_call); } -void LeAudioClientIntf::send_audio_profile_preferences( - int group_id, bool is_output_preference_le_audio, bool is_duplex_preference_le_audio) { - return intf_->SendAudioProfilePreferences( - group_id, is_output_preference_le_audio, is_duplex_preference_le_audio); +void LeAudioClientIntf::send_audio_profile_preferences(int group_id, + bool is_output_preference_le_audio, + bool is_duplex_preference_le_audio) { + return intf_->SendAudioProfilePreferences(group_id, is_output_preference_le_audio, + is_duplex_preference_le_audio); } void LeAudioClientIntf::set_unicast_monitor_mode(BtLeAudioDirection direction, bool enable) { @@ -438,14 +396,16 @@ void LeAudioClientIntf::set_unicast_monitor_mode(BtLeAudioDirection direction, b } std::unique_ptr GetLeAudioClientProfile(const unsigned char* btif) { - if (internal::g_lea_client_if) std::abort(); + if (internal::g_lea_client_if) { + std::abort(); + } const bt_interface_t* btif_ = reinterpret_cast(btif); auto lea_client_if = - std::make_unique(const_cast( - reinterpret_cast( - btif_->get_profile_interface("le_audio")))); + std::make_unique(const_cast( + reinterpret_cast( + btif_->get_profile_interface("le_audio")))); internal::g_lea_client_if = lea_client_if.get(); @@ -470,10 +430,10 @@ void LeAudioClientIntf::peer_stop_audio_request() { static BtLePcmConfig to_rust_btle_pcm_params(audio::le_audio::btle_pcm_parameters pcm_params) { return BtLePcmConfig{ - .data_interval_us = pcm_params.data_interval_us, - .sample_rate = pcm_params.sample_rate, - .bits_per_sample = pcm_params.bits_per_sample, - .channels_count = pcm_params.channels_count, + .data_interval_us = pcm_params.data_interval_us, + .sample_rate = pcm_params.sample_rate, + .bits_per_sample = pcm_params.bits_per_sample, + .channels_count = pcm_params.channels_count, }; } @@ -486,7 +446,7 @@ BtLePcmConfig LeAudioClientIntf::get_peer_pcm_config() { } static BtLeStreamStartedStatus to_rust_btle_stream_started_status( - audio::le_audio::btle_stream_started_status status) { + audio::le_audio::btle_stream_started_status status) { switch (status) { case audio::le_audio::btle_stream_started_status::CANCELED: return BtLeStreamStartedStatus::Canceled; @@ -520,22 +480,22 @@ void LeAudioClientIntf::source_metadata_changed(::rust::Vec meta tracks.reserve(metadata.size()); for (auto m : metadata) { struct playback_track_metadata_v7 track = { - .base = - { - .usage = static_cast(m.usage), - .content_type = static_cast(m.content_type), - .gain = static_cast(m.gain), - }, - .channel_mask = AUDIO_CHANNEL_NONE, // unused - .tags = "", + .base = + { + .usage = static_cast(m.usage), + .content_type = static_cast(m.content_type), + .gain = static_cast(m.gain), + }, + .channel_mask = AUDIO_CHANNEL_NONE, // unused + .tags = "", }; tracks.push_back(track); } source_metadata_v7_t data = { - .track_count = tracks.size(), - .tracks = tracks.data(), + .track_count = tracks.size(), + .tracks = tracks.data(), }; ::bluetooth::audio::le_audio::SourceMetadataChanged(data); @@ -553,23 +513,23 @@ void LeAudioClientIntf::sink_metadata_changed(::rust::Vec metadata tracks.reserve(metadata.size()); for (auto m : metadata) { struct record_track_metadata_v7 track = { - .base = - { - .source = static_cast(m.source), - .gain = static_cast(m.gain), - .dest_device = AUDIO_DEVICE_IN_DEFAULT, - .dest_device_address = "", // unused - }, - .channel_mask = AUDIO_CHANNEL_NONE, // unused - .tags = "", + .base = + { + .source = static_cast(m.source), + .gain = static_cast(m.gain), + .dest_device = AUDIO_DEVICE_IN_DEFAULT, + .dest_device_address = "", // unused + }, + .channel_mask = AUDIO_CHANNEL_NONE, // unused + .tags = "", }; tracks.push_back(track); } const sink_metadata_v7_t data = { - .track_count = tracks.size(), - .tracks = tracks.data(), + .track_count = tracks.size(), + .tracks = tracks.data(), }; ::bluetooth::audio::le_audio::SinkMetadataChanged(data); diff --git a/system/gd/rust/topshim/le_audio/le_audio_shim.h b/system/gd/rust/topshim/le_audio/le_audio_shim.h index 99d5d805e57..1dbe122ccdb 100644 --- a/system/gd/rust/topshim/le_audio/le_audio_shim.h +++ b/system/gd/rust/topshim/le_audio/le_audio_shim.h @@ -35,8 +35,8 @@ struct SourceMetadata; struct SinkMetadata; class LeAudioClientIntf { - public: - LeAudioClientIntf(le_audio::LeAudioClientInterface* intf) : intf_(intf){}; +public: + LeAudioClientIntf(le_audio::LeAudioClientInterface* intf) : intf_(intf) {} void init( /* @@ -51,14 +51,12 @@ const std::vector& offloading_preference void group_add_node(int group_id, RawAddress addr); void group_remove_node(int group_id, RawAddress addr); void group_set_active(int group_id); - void set_codec_config_preference( - int group_id, - BtLeAudioCodecConfig input_codec_config, - BtLeAudioCodecConfig output_codec_config); + void set_codec_config_preference(int group_id, BtLeAudioCodecConfig input_codec_config, + BtLeAudioCodecConfig output_codec_config); void set_ccid_information(int ccid, int context_type); void set_in_call(bool in_call); - void send_audio_profile_preferences( - int group_id, bool is_output_preference_le_audio, bool is_duplex_preference_le_audio); + void send_audio_profile_preferences(int group_id, bool is_output_preference_le_audio, + bool is_duplex_preference_le_audio); void set_unicast_monitor_mode(BtLeAudioDirection direction, bool enable); // interface for audio server @@ -73,7 +71,7 @@ const std::vector& offloading_preference void source_metadata_changed(::rust::Vec metadata); void sink_metadata_changed(::rust::Vec metadata); - private: +private: le_audio::LeAudioClientInterface* intf_; }; diff --git a/system/gd/rust/topshim/metrics/metrics_shim.cc b/system/gd/rust/topshim/metrics/metrics_shim.cc index 2e9b01944e8..9829242bf85 100644 --- a/system/gd/rust/topshim/metrics/metrics_shim.cc +++ b/system/gd/rust/topshim/metrics/metrics_shim.cc @@ -26,33 +26,26 @@ namespace bluetooth { namespace topshim { namespace rust { -void adapter_state_changed(uint32_t state) { - metrics::LogMetricsAdapterStateChanged(state); -} +void adapter_state_changed(uint32_t state) { metrics::LogMetricsAdapterStateChanged(state); } void bond_create_attempt(RawAddress addr, uint32_t device_type) { metrics::LogMetricsBondCreateAttempt(&addr, device_type); } -void bond_state_changed( - RawAddress addr, uint32_t device_type, uint32_t status, uint32_t bond_state, int32_t fail_reason) { +void bond_state_changed(RawAddress addr, uint32_t device_type, uint32_t status, uint32_t bond_state, + int32_t fail_reason) { metrics::LogMetricsBondStateChanged(&addr, device_type, status, bond_state, fail_reason); } -void device_info_report( - RawAddress addr, - uint32_t device_type, - uint32_t class_of_device, - uint32_t appearance, - uint32_t vendor_id, - uint32_t vendor_id_src, - uint32_t product_id, - uint32_t version) { - metrics::LogMetricsDeviceInfoReport( - &addr, device_type, class_of_device, appearance, vendor_id, vendor_id_src, product_id, version); +void device_info_report(RawAddress addr, uint32_t device_type, uint32_t class_of_device, + uint32_t appearance, uint32_t vendor_id, uint32_t vendor_id_src, + uint32_t product_id, uint32_t version) { + metrics::LogMetricsDeviceInfoReport(&addr, device_type, class_of_device, appearance, vendor_id, + vendor_id_src, product_id, version); } -void profile_connection_state_changed(RawAddress addr, uint32_t profile, uint32_t status, uint32_t state) { +void profile_connection_state_changed(RawAddress addr, uint32_t profile, uint32_t status, + uint32_t state) { metrics::LogMetricsProfileConnectionStateChanged(&addr, profile, status, state); } @@ -60,14 +53,13 @@ void acl_connect_attempt(RawAddress addr, uint32_t acl_state) { metrics::LogMetricsAclConnectAttempt(&addr, acl_state); } -void acl_connection_state_changed( - RawAddress addr, uint32_t transport, uint32_t status, uint32_t acl_state, uint32_t direction, uint32_t hci_reason) { - metrics::LogMetricsAclConnectionStateChanged(&addr, transport, status, acl_state, direction, hci_reason); +void acl_connection_state_changed(RawAddress addr, uint32_t transport, uint32_t status, + uint32_t acl_state, uint32_t direction, uint32_t hci_reason) { + metrics::LogMetricsAclConnectionStateChanged(&addr, transport, status, acl_state, direction, + hci_reason); } -void suspend_complete_state(uint32_t state) { - metrics::LogMetricsSuspendIdState(state); -} +void suspend_complete_state(uint32_t state) { metrics::LogMetricsSuspendIdState(state); } } // namespace rust } // namespace topshim diff --git a/system/gd/rust/topshim/metrics/metrics_shim.h b/system/gd/rust/topshim/metrics/metrics_shim.h index d2e8fb9e557..0572d306ac4 100644 --- a/system/gd/rust/topshim/metrics/metrics_shim.h +++ b/system/gd/rust/topshim/metrics/metrics_shim.h @@ -26,22 +26,17 @@ namespace topshim { namespace rust { void adapter_state_changed(uint32_t state); -void bond_state_changed( - RawAddress addr, uint32_t device_type, uint32_t status, uint32_t bond_state, int32_t fail_reason); +void bond_state_changed(RawAddress addr, uint32_t device_type, uint32_t status, uint32_t bond_state, + int32_t fail_reason); void bond_create_attempt(RawAddress addr, uint32_t device_type); -void device_info_report( - RawAddress addr, - uint32_t device_type, - uint32_t class_of_device, - uint32_t appearance, - uint32_t vendor_id, - uint32_t vendor_id_src, - uint32_t product_id, - uint32_t version); -void profile_connection_state_changed(RawAddress addr, uint32_t profile, uint32_t status, uint32_t state); +void device_info_report(RawAddress addr, uint32_t device_type, uint32_t class_of_device, + uint32_t appearance, uint32_t vendor_id, uint32_t vendor_id_src, + uint32_t product_id, uint32_t version); +void profile_connection_state_changed(RawAddress addr, uint32_t profile, uint32_t status, + uint32_t state); void acl_connect_attempt(RawAddress addr, uint32_t acl_state); -void acl_connection_state_changed( - RawAddress addr, uint32_t transport, uint32_t status, uint32_t acl_state, uint32_t direction, uint32_t hci_reason); +void acl_connection_state_changed(RawAddress addr, uint32_t transport, uint32_t status, + uint32_t acl_state, uint32_t direction, uint32_t hci_reason); void suspend_complete_state(uint32_t state); } // namespace rust diff --git a/system/gd/rust/topshim/vc/vc_shim.cc b/system/gd/rust/topshim/vc/vc_shim.cc index 8c11cc475e8..4f17a168301 100644 --- a/system/gd/rust/topshim/vc/vc_shim.cc +++ b/system/gd/rust/topshim/vc/vc_shim.cc @@ -54,8 +54,8 @@ static void connection_state_cb(vc::ConnectionState state, const RawAddress& add vc_connection_state_callback(to_rust_btvc_connection_state(state), address); } -static void volume_state_cb( - const RawAddress& address, uint8_t volume, bool mute, bool is_autonomous) { +static void volume_state_cb(const RawAddress& address, uint8_t volume, bool mute, + bool is_autonomous) { vc_volume_state_callback(address, volume, mute, is_autonomous); } @@ -67,52 +67,48 @@ static void device_available_cb(const RawAddress& address, uint8_t num_offset) { vc_device_available_callback(address, num_offset); } -static void ext_audio_out_volume_offset_cb( - const RawAddress& address, uint8_t ext_output_id, int16_t offset) { +static void ext_audio_out_volume_offset_cb(const RawAddress& address, uint8_t ext_output_id, + int16_t offset) { vc_ext_audio_out_volume_offset_callback(address, ext_output_id, offset); } -static void ext_audio_out_location_cb( - const RawAddress& address, uint8_t ext_output_id, uint32_t location) { +static void ext_audio_out_location_cb(const RawAddress& address, uint8_t ext_output_id, + uint32_t location) { vc_ext_audio_out_location_callback(address, ext_output_id, location); } -static void ext_audio_out_description_cb( - const RawAddress& address, uint8_t ext_output_id, std::string descr) { +static void ext_audio_out_description_cb(const RawAddress& address, uint8_t ext_output_id, + std::string descr) { vc_ext_audio_out_description_callback(address, ext_output_id, descr); } } // namespace internal class DBusVolumeControlCallbacks : public vc::VolumeControlCallbacks { - public: +public: static vc::VolumeControlCallbacks* GetInstance() { static auto instance = new DBusVolumeControlCallbacks(); return instance; } - DBusVolumeControlCallbacks(){}; + DBusVolumeControlCallbacks() {} void OnConnectionState(vc::ConnectionState state, const RawAddress& address) override { log::info("state={}, address={}", static_cast(state), ADDRESS_TO_LOGGABLE_CSTR(address)); topshim::rust::internal::connection_state_cb(state, address); } - void OnVolumeStateChanged( - const RawAddress& address, uint8_t volume, bool mute, bool is_autonomous) override { - log::info( - "address={}, volume={}, mute={}, is_autonomous={}", - ADDRESS_TO_LOGGABLE_CSTR(address), - volume, - mute, - is_autonomous); + void OnVolumeStateChanged(const RawAddress& address, uint8_t volume, bool mute, + bool is_autonomous) override { + log::info("address={}, volume={}, mute={}, is_autonomous={}", ADDRESS_TO_LOGGABLE_CSTR(address), + volume, mute, is_autonomous); topshim::rust::internal::volume_state_cb(address, volume, mute, is_autonomous); } - void OnGroupVolumeStateChanged( - int group_id, uint8_t volume, bool mute, bool is_autonomous) override { - log::info( - "group_id={}, volume={}, mute={}, is_autonomous={}", group_id, volume, mute, is_autonomous); + void OnGroupVolumeStateChanged(int group_id, uint8_t volume, bool mute, + bool is_autonomous) override { + log::info("group_id={}, volume={}, mute={}, is_autonomous={}", group_id, volume, mute, + is_autonomous); topshim::rust::internal::group_volume_state_cb(group_id, volume, mute, is_autonomous); } @@ -121,45 +117,38 @@ class DBusVolumeControlCallbacks : public vc::VolumeControlCallbacks { topshim::rust::internal::device_available_cb(address, num_offset); } - void OnExtAudioOutVolumeOffsetChanged( - const RawAddress& address, uint8_t ext_output_id, int16_t offset) override { - log::info( - "address={}, ext_output_id={}, offset={}", - ADDRESS_TO_LOGGABLE_CSTR(address), - ext_output_id, - offset); + void OnExtAudioOutVolumeOffsetChanged(const RawAddress& address, uint8_t ext_output_id, + int16_t offset) override { + log::info("address={}, ext_output_id={}, offset={}", ADDRESS_TO_LOGGABLE_CSTR(address), + ext_output_id, offset); topshim::rust::internal::ext_audio_out_volume_offset_cb(address, ext_output_id, offset); } - void OnExtAudioOutLocationChanged( - const RawAddress& address, uint8_t ext_output_id, uint32_t location) override { - log::info( - "address={}, ext_output_id, location={}", - ADDRESS_TO_LOGGABLE_CSTR(address), - ext_output_id, - location); + void OnExtAudioOutLocationChanged(const RawAddress& address, uint8_t ext_output_id, + uint32_t location) override { + log::info("address={}, ext_output_id, location={}", ADDRESS_TO_LOGGABLE_CSTR(address), + ext_output_id, location); topshim::rust::internal::ext_audio_out_location_cb(address, ext_output_id, location); } - void OnExtAudioOutDescriptionChanged( - const RawAddress& address, uint8_t ext_output_id, std::string descr) override { - log::info( - "address={}, ext_output_id={}, descr={}", - ADDRESS_TO_LOGGABLE_CSTR(address), - ext_output_id, - descr.c_str()); + void OnExtAudioOutDescriptionChanged(const RawAddress& address, uint8_t ext_output_id, + std::string descr) override { + log::info("address={}, ext_output_id={}, descr={}", ADDRESS_TO_LOGGABLE_CSTR(address), + ext_output_id, descr.c_str()); topshim::rust::internal::ext_audio_out_description_cb(address, ext_output_id, descr); } }; std::unique_ptr GetVolumeControlProfile(const unsigned char* btif) { - if (internal::g_vc_if) std::abort(); + if (internal::g_vc_if) { + std::abort(); + } const bt_interface_t* btif_ = reinterpret_cast(btif); - auto vc_if = std::make_unique( - const_cast(reinterpret_cast( - btif_->get_profile_interface("volume_control")))); + auto vc_if = std::make_unique(const_cast( + reinterpret_cast( + btif_->get_profile_interface("volume_control")))); internal::g_vc_if = vc_if.get(); @@ -170,40 +159,28 @@ void VolumeControlIntf::init(/*VolumeControlCallbacks* callbacks*/) { return intf_->Init(DBusVolumeControlCallbacks::GetInstance()); } -void VolumeControlIntf::cleanup() { - return intf_->Cleanup(); -} +void VolumeControlIntf::cleanup() { return intf_->Cleanup(); } -void VolumeControlIntf::connect(RawAddress addr) { - return intf_->Connect(addr); -} +void VolumeControlIntf::connect(RawAddress addr) { return intf_->Connect(addr); } -void VolumeControlIntf::disconnect(RawAddress addr) { - return intf_->Disconnect(addr); -} +void VolumeControlIntf::disconnect(RawAddress addr) { return intf_->Disconnect(addr); } -void VolumeControlIntf::remove_device(RawAddress addr) { - return intf_->RemoveDevice(addr); -} +void VolumeControlIntf::remove_device(RawAddress addr) { return intf_->RemoveDevice(addr); } void VolumeControlIntf::set_volume(int group_id, uint8_t volume) { return intf_->SetVolume(group_id, volume); } -void VolumeControlIntf::mute(RawAddress addr) { - return intf_->Mute(addr); -} +void VolumeControlIntf::mute(RawAddress addr) { return intf_->Mute(addr); } -void VolumeControlIntf::unmute(RawAddress addr) { - return intf_->Unmute(addr); -} +void VolumeControlIntf::unmute(RawAddress addr) { return intf_->Unmute(addr); } void VolumeControlIntf::get_ext_audio_out_volume_offset(RawAddress addr, uint8_t ext_output_id) { return intf_->GetExtAudioOutVolumeOffset(addr, ext_output_id); } -void VolumeControlIntf::set_ext_audio_out_volume_offset( - RawAddress addr, uint8_t ext_output_id, int16_t offset_val) { +void VolumeControlIntf::set_ext_audio_out_volume_offset(RawAddress addr, uint8_t ext_output_id, + int16_t offset_val) { return intf_->SetExtAudioOutVolumeOffset(addr, ext_output_id, offset_val); } @@ -211,8 +188,8 @@ void VolumeControlIntf::get_ext_audio_out_location(RawAddress addr, uint8_t ext_ return intf_->GetExtAudioOutLocation(addr, ext_output_id); } -void VolumeControlIntf::set_ext_audio_out_location( - RawAddress addr, uint8_t ext_output_id, uint32_t location) { +void VolumeControlIntf::set_ext_audio_out_location(RawAddress addr, uint8_t ext_output_id, + uint32_t location) { return intf_->SetExtAudioOutLocation(addr, ext_output_id, location); } @@ -220,8 +197,8 @@ void VolumeControlIntf::get_ext_audio_out_description(RawAddress addr, uint8_t e return intf_->GetExtAudioOutDescription(addr, ext_output_id); } -void VolumeControlIntf::set_ext_audio_out_description( - RawAddress addr, uint8_t ext_output_id, const char* descr) { +void VolumeControlIntf::set_ext_audio_out_description(RawAddress addr, uint8_t ext_output_id, + const char* descr) { return intf_->SetExtAudioOutDescription(addr, ext_output_id, std::string(descr)); } } // namespace rust diff --git a/system/gd/rust/topshim/vc/vc_shim.h b/system/gd/rust/topshim/vc/vc_shim.h index eb0d68b20f0..38b066db4e3 100644 --- a/system/gd/rust/topshim/vc/vc_shim.h +++ b/system/gd/rust/topshim/vc/vc_shim.h @@ -27,8 +27,8 @@ namespace topshim { namespace rust { class VolumeControlIntf { - public: - VolumeControlIntf(vc::VolumeControlInterface* intf) : intf_(intf){}; +public: + VolumeControlIntf(vc::VolumeControlInterface* intf) : intf_(intf) {} void init(/*VolumeControlCallbacks* callbacks*/); void cleanup(); @@ -45,7 +45,7 @@ class VolumeControlIntf { void get_ext_audio_out_description(RawAddress addr, uint8_t ext_output_id); void set_ext_audio_out_description(RawAddress addr, uint8_t ext_output_id, const char* descr); - private: +private: vc::VolumeControlInterface* intf_; }; diff --git a/system/gd/security/channel/security_manager_channel.cc b/system/gd/security/channel/security_manager_channel.cc index 5a4bf01e4c5..c4cf1780cdc 100644 --- a/system/gd/security/channel/security_manager_channel.cc +++ b/system/gd/security/channel/security_manager_channel.cc @@ -30,8 +30,8 @@ namespace channel { */ SecurityManagerChannel::SecurityManagerChannel(os::Handler* handler, hci::HciLayer* hci_layer) : listener_(nullptr), - hci_security_interface_( - hci_layer->GetSecurityInterface(handler->BindOn(this, &SecurityManagerChannel::OnHciEventReceived))), + hci_security_interface_(hci_layer->GetSecurityInterface( + handler->BindOn(this, &SecurityManagerChannel::OnHciEventReceived))), handler_(handler), l2cap_security_interface_(nullptr) {} @@ -77,13 +77,15 @@ void SecurityManagerChannel::OnCommandComplete(hci::CommandCompleteView packet) } void SecurityManagerChannel::SendCommand(std::unique_ptr command) { - hci_security_interface_->EnqueueCommand(std::move(command), - handler_->BindOnceOn(this, &SecurityManagerChannel::OnCommandComplete)); + hci_security_interface_->EnqueueCommand( + std::move(command), + handler_->BindOnceOn(this, &SecurityManagerChannel::OnCommandComplete)); } -void SecurityManagerChannel::SendCommand( - std::unique_ptr command, SecurityCommandStatusCallback callback) { - hci_security_interface_->EnqueueCommand(std::move(command), std::forward(callback)); +void SecurityManagerChannel::SendCommand(std::unique_ptr command, + SecurityCommandStatusCallback callback) { + hci_security_interface_->EnqueueCommand(std::move(command), + std::forward(callback)); } void SecurityManagerChannel::OnHciEventReceived(hci::EventView packet) { @@ -92,7 +94,8 @@ void SecurityManagerChannel::OnHciEventReceived(hci::EventView packet) { listener_->OnHciEventReceived(packet); } -void SecurityManagerChannel::OnLinkConnected(std::unique_ptr link) { +void SecurityManagerChannel::OnLinkConnected( + std::unique_ptr link) { // Multiple links possible? auto remote = link->GetRemoteAddress(); if (outgoing_pairing_remote_devices_.count(remote) == 1) { @@ -115,8 +118,8 @@ void SecurityManagerChannel::OnLinkDisconnected(hci::Address address) { listener_->OnConnectionClosed(address); } -void SecurityManagerChannel::OnAuthenticationComplete( - hci::ErrorCode /* hci_status */, hci::Address remote) { +void SecurityManagerChannel::OnAuthenticationComplete(hci::ErrorCode /* hci_status */, + hci::Address remote) { log::assert_that(l2cap_security_interface_ != nullptr, "L2cap Security Interface is null!"); auto entry = link_map_.find(remote); if (entry != link_map_.end()) { diff --git a/system/gd/security/channel/security_manager_channel.h b/system/gd/security/channel/security_manager_channel.h index f1b0a8ebdc4..9a59e7ad783 100644 --- a/system/gd/security/channel/security_manager_channel.h +++ b/system/gd/security/channel/security_manager_channel.h @@ -30,13 +30,14 @@ namespace bluetooth { namespace security { namespace channel { -using SecurityCommandStatusCallback = common::ContextualOnceCallback; +using SecurityCommandStatusCallback = + common::ContextualOnceCallback; /** * Interface for listening to the channel for SMP commands. */ class ISecurityManagerChannelListener { - public: +public: virtual ~ISecurityManagerChannelListener() = default; virtual void OnHciEventReceived(hci::EventView packet) = 0; virtual void OnConnectionClosed(hci::Address) = 0; @@ -46,7 +47,7 @@ class ISecurityManagerChannelListener { * Channel for consolidating traffic and making the transport agnostic. */ class SecurityManagerChannel : public l2cap::classic::LinkSecurityInterfaceListener { - public: +public: SecurityManagerChannel(os::Handler* handler, hci::HciLayer* hci_layer); virtual ~SecurityManagerChannel(); @@ -89,16 +90,15 @@ class SecurityManagerChannel : public l2cap::classic::LinkSecurityInterfaceListe * @param command smp command to send * @param callback listener to call when command status complete */ - void SendCommand(std::unique_ptr command, SecurityCommandStatusCallback callback); + void SendCommand(std::unique_ptr command, + SecurityCommandStatusCallback callback); /** * Sets the listener to listen for channel events * * @param listener the caller interested in events */ - void SetChannelListener(ISecurityManagerChannelListener* listener) { - listener_ = listener; - } + void SetChannelListener(ISecurityManagerChannelListener* listener) { listener_ = listener; } void SetSecurityInterface(l2cap::classic::SecurityInterface* security_interface) { l2cap_security_interface_ = security_interface; @@ -124,12 +124,13 @@ class SecurityManagerChannel : public l2cap::classic::LinkSecurityInterfaceListe void OnAuthenticationComplete(hci::ErrorCode hci_status, hci::Address remote) override; void OnEncryptionChange(hci::Address, bool encrypted) override; - private: +private: ISecurityManagerChannelListener* listener_{nullptr}; hci::SecurityInterface* hci_security_interface_{nullptr}; os::Handler* handler_{nullptr}; l2cap::classic::SecurityInterface* l2cap_security_interface_{nullptr}; - std::unordered_map> link_map_; + std::unordered_map> + link_map_; std::set outgoing_pairing_remote_devices_; }; diff --git a/system/gd/security/channel/security_manager_channel_unittest.cc b/system/gd/security/channel/security_manager_channel_unittest.cc index b715c44ad3b..b3feb5d4999 100644 --- a/system/gd/security/channel/security_manager_channel_unittest.cc +++ b/system/gd/security/channel/security_manager_channel_unittest.cc @@ -47,7 +47,7 @@ static bool on_link_connected_called = false; static bool on_link_disconnected_called = false; class FakeSecurityManagerChannel : public SecurityManagerChannel { - public: +public: FakeSecurityManagerChannel(os::Handler* handler, hci::HciLayer* hci_layer) : SecurityManagerChannel(handler, hci_layer) {} ~FakeSecurityManagerChannel() {} @@ -56,9 +56,7 @@ class FakeSecurityManagerChannel : public SecurityManagerChannel { on_link_connected_called = true; } - void OnLinkDisconnected(hci::Address address) { - on_link_disconnected_called = true; - } + void OnLinkDisconnected(hci::Address address) { on_link_disconnected_called = true; } void OnAuthenticationComplete(hci::ErrorCode hci_status, hci::Address remote) override {} @@ -66,7 +64,7 @@ class FakeSecurityManagerChannel : public SecurityManagerChannel { }; class SecurityManagerChannelCallback : public ISecurityManagerChannelListener { - public: +public: // HCI bool receivedChangeConnectionLinkKeyComplete = false; bool receivedCentralLinkKeyComplete = false; @@ -209,13 +207,11 @@ class SecurityManagerChannelCallback : public ISecurityManagerChannelListener { } } - void OnConnectionClosed(hci::Address address) override { - log::info("Called"); - } + void OnConnectionClosed(hci::Address address) override { log::info("Called"); } }; class SecurityManagerChannelTest : public ::testing::Test { - protected: +protected: void SetUp() override { hci::Address address; hci::Address::FromString("01:23:45:67:89:AB:CD", address); @@ -271,8 +267,8 @@ TEST_F(SecurityManagerChannelTest, send_io_cap_request_reply) { hci::IoCapability io_capability = (hci::IoCapability)0x00; OobDataPresent oob_present = (OobDataPresent)0x00; AuthenticationRequirements authentication_requirements = (AuthenticationRequirements)0x00; - auto packet = hci::IoCapabilityRequestReplyBuilder::Create(device_.GetAddress(), io_capability, oob_present, - authentication_requirements); + auto packet = hci::IoCapabilityRequestReplyBuilder::Create( + device_.GetAddress(), io_capability, oob_present, authentication_requirements); // Act channel_->SendCommand(std::move(packet)); @@ -287,8 +283,8 @@ TEST_F(SecurityManagerChannelTest, send_io_cap_request_reply) { TEST_F(SecurityManagerChannelTest, send_io_cap_request_neg_reply) { // Arrange - auto packet = - hci::IoCapabilityRequestNegativeReplyBuilder::Create(device_.GetAddress(), hci::ErrorCode::COMMAND_DISALLOWED); + auto packet = hci::IoCapabilityRequestNegativeReplyBuilder::Create( + device_.GetAddress(), hci::ErrorCode::COMMAND_DISALLOWED); // Act channel_->SendCommand(std::move(packet)); @@ -305,8 +301,8 @@ TEST_F(SecurityManagerChannelTest, recv_io_cap_response) { hci::IoCapability io_capability = (hci::IoCapability)0x00; OobDataPresent oob_present = (OobDataPresent)0x00; AuthenticationRequirements authentication_requirements = (AuthenticationRequirements)0x00; - hci_layer_->IncomingEvent(hci::IoCapabilityResponseBuilder::Create(device_.GetAddress(), io_capability, oob_present, - authentication_requirements)); + hci_layer_->IncomingEvent(hci::IoCapabilityResponseBuilder::Create( + device_.GetAddress(), io_capability, oob_present, authentication_requirements)); synchronize(); ASSERT_TRUE(callback_->receivedIoCapabilityResponse); } @@ -321,7 +317,8 @@ TEST_F(SecurityManagerChannelTest, send_pin_code_request_reply) { // Arrange uint8_t pin_code_length = 6; std::array pin_code = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5}; - auto packet = hci::PinCodeRequestReplyBuilder::Create(device_.GetAddress(), pin_code_length, pin_code); + auto packet = + hci::PinCodeRequestReplyBuilder::Create(device_.GetAddress(), pin_code_length, pin_code); // Act channel_->SendCommand(std::move(packet)); @@ -351,14 +348,16 @@ TEST_F(SecurityManagerChannelTest, send_pin_code_request_neg_reply) { TEST_F(SecurityManagerChannelTest, recv_user_passkey_notification) { uint32_t passkey = 0x00; - hci_layer_->IncomingEvent(hci::UserPasskeyNotificationBuilder::Create(device_.GetAddress(), passkey)); + hci_layer_->IncomingEvent( + hci::UserPasskeyNotificationBuilder::Create(device_.GetAddress(), passkey)); synchronize(); ASSERT_TRUE(callback_->receivedUserPasskeyNotification); } TEST_F(SecurityManagerChannelTest, recv_user_confirmation_request) { uint32_t numeric_value = 0x0; - hci_layer_->IncomingEvent(hci::UserConfirmationRequestBuilder::Create(device_.GetAddress(), numeric_value)); + hci_layer_->IncomingEvent( + hci::UserConfirmationRequestBuilder::Create(device_.GetAddress(), numeric_value)); synchronize(); ASSERT_TRUE(callback_->receivedUserConfirmationRequest); } @@ -469,24 +468,24 @@ TEST_F(SecurityManagerChannelTest, recv_link_key_request) { TEST_F(SecurityManagerChannelTest, recv_link_key_notification) { std::array link_key = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5}; - hci_layer_->IncomingEvent( - hci::LinkKeyNotificationBuilder::Create(device_.GetAddress(), link_key, hci::KeyType::DEBUG_COMBINATION)); + hci_layer_->IncomingEvent(hci::LinkKeyNotificationBuilder::Create( + device_.GetAddress(), link_key, hci::KeyType::DEBUG_COMBINATION)); synchronize(); ASSERT_TRUE(callback_->receivedLinkKeyNotification); } TEST_F(SecurityManagerChannelTest, recv_central_link_key_complete) { uint16_t connection_handle = 0x0; - hci_layer_->IncomingEvent( - hci::CentralLinkKeyCompleteBuilder::Create(hci::ErrorCode::SUCCESS, connection_handle, hci::KeyFlag::TEMPORARY)); + hci_layer_->IncomingEvent(hci::CentralLinkKeyCompleteBuilder::Create( + hci::ErrorCode::SUCCESS, connection_handle, hci::KeyFlag::TEMPORARY)); synchronize(); ASSERT_TRUE(callback_->receivedCentralLinkKeyComplete); } TEST_F(SecurityManagerChannelTest, recv_change_connection_link_key_complete) { uint16_t connection_handle = 0x0; - hci_layer_->IncomingEvent( - hci::ChangeConnectionLinkKeyCompleteBuilder::Create(hci::ErrorCode::SUCCESS, connection_handle)); + hci_layer_->IncomingEvent(hci::ChangeConnectionLinkKeyCompleteBuilder::Create( + hci::ErrorCode::SUCCESS, connection_handle)); synchronize(); ASSERT_TRUE(callback_->receivedChangeConnectionLinkKeyComplete); } @@ -531,7 +530,8 @@ TEST_F(SecurityManagerChannelTest, send_link_key_request_neg_reply) { TEST_F(SecurityManagerChannelTest, send_read_stored_link_key) { // Arrange - auto packet = hci::ReadStoredLinkKeyBuilder::Create(device_.GetAddress(), hci::ReadStoredLinkKeyReadAllFlag::ALL); + auto packet = hci::ReadStoredLinkKeyBuilder::Create(device_.GetAddress(), + hci::ReadStoredLinkKeyReadAllFlag::ALL); // Act channel_->SendCommand(std::move(packet)); @@ -562,8 +562,8 @@ TEST_F(SecurityManagerChannelTest, send_write_stored_link_key) { TEST_F(SecurityManagerChannelTest, send_delete_stored_link_key) { // Arrange - auto packet = - hci::DeleteStoredLinkKeyBuilder::Create(device_.GetAddress(), hci::DeleteStoredLinkKeyDeleteAllFlag::ALL); + auto packet = hci::DeleteStoredLinkKeyBuilder::Create(device_.GetAddress(), + hci::DeleteStoredLinkKeyDeleteAllFlag::ALL); // Act channel_->SendCommand(std::move(packet)); @@ -578,16 +578,16 @@ TEST_F(SecurityManagerChannelTest, send_delete_stored_link_key) { TEST_F(SecurityManagerChannelTest, recv_encryption_change) { uint16_t connection_handle = 0x0; - hci_layer_->IncomingEvent( - hci::EncryptionChangeBuilder::Create(hci::ErrorCode::SUCCESS, connection_handle, hci::EncryptionEnabled::ON)); + hci_layer_->IncomingEvent(hci::EncryptionChangeBuilder::Create( + hci::ErrorCode::SUCCESS, connection_handle, hci::EncryptionEnabled::ON)); synchronize(); ASSERT_TRUE(callback_->receivedEncryptionChange); } TEST_F(SecurityManagerChannelTest, recv_encryption_key_refresh) { uint16_t connection_handle = 0x0; - hci_layer_->IncomingEvent( - hci::EncryptionKeyRefreshCompleteBuilder::Create(hci::ErrorCode::SUCCESS, connection_handle)); + hci_layer_->IncomingEvent(hci::EncryptionKeyRefreshCompleteBuilder::Create( + hci::ErrorCode::SUCCESS, connection_handle)); synchronize(); ASSERT_TRUE(callback_->receivedEncryptionKeyRefreshComplete); } @@ -625,7 +625,8 @@ TEST_F(SecurityManagerChannelTest, send_read_encryption_key_size) { } TEST_F(SecurityManagerChannelTest, recv_simple_pairing_complete) { - hci_layer_->IncomingEvent(hci::SimplePairingCompleteBuilder::Create(hci::ErrorCode::SUCCESS, device_.GetAddress())); + hci_layer_->IncomingEvent( + hci::SimplePairingCompleteBuilder::Create(hci::ErrorCode::SUCCESS, device_.GetAddress())); synchronize(); ASSERT_TRUE(callback_->receivedSimplePairingComplete); } @@ -661,16 +662,16 @@ TEST_F(SecurityManagerChannelTest, send_write_simple_pairing_mode) { } TEST_F(SecurityManagerChannelTest, recv_keypress_notification) { - hci_layer_->IncomingEvent( - hci::KeypressNotificationBuilder::Create(device_.GetAddress(), hci::KeypressNotificationType::ENTRY_COMPLETED)); + hci_layer_->IncomingEvent(hci::KeypressNotificationBuilder::Create( + device_.GetAddress(), hci::KeypressNotificationType::ENTRY_COMPLETED)); synchronize(); ASSERT_TRUE(callback_->receivedKeypressNotification); } TEST_F(SecurityManagerChannelTest, send_keypress_notification) { // Arrange - auto packet = - hci::SendKeypressNotificationBuilder::Create(device_.GetAddress(), hci::KeypressNotificationType::ENTRY_STARTED); + auto packet = hci::SendKeypressNotificationBuilder::Create( + device_.GetAddress(), hci::KeypressNotificationType::ENTRY_STARTED); // Act channel_->SendCommand(std::move(packet)); diff --git a/system/gd/security/ecc/multprecision.cc b/system/gd/security/ecc/multprecision.cc index 86ef0d80024..9f5153ed47e 100644 --- a/system/gd/security/ecc/multprecision.cc +++ b/system/gd/security/ecc/multprecision.cc @@ -33,50 +33,70 @@ namespace ecc { #define DWORD_BITS_SHIFT 5 void multiprecision_init(uint32_t* c) { - for (uint32_t i = 0; i < KEY_LENGTH_DWORDS_P256; i++) c[i] = 0; + for (uint32_t i = 0; i < KEY_LENGTH_DWORDS_P256; i++) { + c[i] = 0; + } } void multiprecision_copy(uint32_t* c, const uint32_t* a) { - for (uint32_t i = 0; i < KEY_LENGTH_DWORDS_P256; i++) c[i] = a[i]; + for (uint32_t i = 0; i < KEY_LENGTH_DWORDS_P256; i++) { + c[i] = a[i]; + } } int multiprecision_compare(const uint32_t* a, const uint32_t* b) { for (int i = KEY_LENGTH_DWORDS_P256 - 1; i >= 0; i--) { - if (a[i] > b[i]) return 1; - if (a[i] < b[i]) return -1; + if (a[i] > b[i]) { + return 1; + } + if (a[i] < b[i]) { + return -1; + } } return 0; } int multiprecision_iszero(const uint32_t* a) { - for (uint32_t i = 0; i < KEY_LENGTH_DWORDS_P256; i++) - if (a[i]) return 0; + for (uint32_t i = 0; i < KEY_LENGTH_DWORDS_P256; i++) { + if (a[i]) { + return 0; + } + } return 1; } uint32_t multiprecision_dword_bits(uint32_t a) { uint32_t i; - for (i = 0; i < DWORD_BITS; i++, a >>= 1) - if (a == 0) break; + for (i = 0; i < DWORD_BITS; i++, a >>= 1) { + if (a == 0) { + break; + } + } return i; } uint32_t multiprecision_most_signdwords(const uint32_t* a) { int i; - for (i = KEY_LENGTH_DWORDS_P256 - 1; i >= 0; i--) - if (a[i]) break; - return (i + 1); + for (i = KEY_LENGTH_DWORDS_P256 - 1; i >= 0; i--) { + if (a[i]) { + break; + } + } + return i + 1; } uint32_t multiprecision_most_signbits(const uint32_t* a) { int aMostSignDWORDs; aMostSignDWORDs = multiprecision_most_signdwords(a); - if (aMostSignDWORDs == 0) return 0; + if (aMostSignDWORDs == 0) { + return 0; + } - return (((aMostSignDWORDs - 1) << DWORD_BITS_SHIFT) + multiprecision_dword_bits(a[aMostSignDWORDs - 1])); + return ((aMostSignDWORDs - 1) << DWORD_BITS_SHIFT) + + multiprecision_dword_bits(a[aMostSignDWORDs - 1]); } uint32_t multiprecision_add(uint32_t* c, const uint32_t* a, const uint32_t* b) { @@ -139,7 +159,8 @@ void multiprecision_rshift(uint32_t* c, const uint32_t* a) { // Curve specific optimization when p is a pseudo-Mersenns prime, // p=2^(KEY_LENGTH_BITS)-omega -void multiprecision_mersenns_mult_mod(uint32_t* c, const uint32_t* a, const uint32_t* b, const uint32_t* modp) { +void multiprecision_mersenns_mult_mod(uint32_t* c, const uint32_t* a, const uint32_t* b, + const uint32_t* modp) { uint32_t cc[2 * KEY_LENGTH_DWORDS_P256]; multiprecision_mult(cc, a, b); @@ -152,7 +173,8 @@ void multiprecision_mersenns_squa_mod(uint32_t* c, const uint32_t* a, const uint } // c=(a+b) mod p, b= 0) multiprecision_sub(c, c, modp); + if (multiprecision_compare(c, modp) >= 0) { + multiprecision_sub(c, c, modp); + } } void multiprecision_inv_mod(uint32_t* aminus, uint32_t* u, const uint32_t* modp) { @@ -461,9 +488,9 @@ void multiprecision_inv_mod(uint32_t* aminus, uint32_t* u, const uint32_t* modp) while (!(u[0] & 0x01)) // u is even { multiprecision_rshift(u, u); - if (!(A[0] & 0x01)) // A is even + if (!(A[0] & 0x01)) { // A is even multiprecision_rshift(A, A); - else { + } else { A[KEY_LENGTH_DWORDS_P256] = multiprecision_add(A, A, modp); // A =A+p multiprecision_rshift(A, A); A[KEY_LENGTH_DWORDS_P256 - 1] |= (A[KEY_LENGTH_DWORDS_P256] << 31); @@ -492,10 +519,11 @@ void multiprecision_inv_mod(uint32_t* aminus, uint32_t* u, const uint32_t* modp) } } - if (multiprecision_compare(C, modp) >= 0) + if (multiprecision_compare(C, modp) >= 0) { multiprecision_sub(aminus, C, modp); - else + } else { multiprecision_copy(aminus, C); + } } } // namespace ecc diff --git a/system/gd/security/ecc/multprecision.h b/system/gd/security/ecc/multprecision.h index ad149cd89e9..7bb3f2de406 100644 --- a/system/gd/security/ecc/multprecision.h +++ b/system/gd/security/ecc/multprecision.h @@ -40,14 +40,18 @@ uint32_t multiprecision_most_signdwords(const uint32_t* a); uint32_t multiprecision_most_signbits(const uint32_t* a); void multiprecision_inv_mod(uint32_t* aminus, uint32_t* a, const uint32_t* modp); uint32_t multiprecision_add(uint32_t* c, const uint32_t* a, const uint32_t* b); // c=a+b -void multiprecision_add_mod(uint32_t* c, const uint32_t* a, const uint32_t* b, const uint32_t* modp); +void multiprecision_add_mod(uint32_t* c, const uint32_t* a, const uint32_t* b, + const uint32_t* modp); uint32_t multiprecision_sub(uint32_t* c, const uint32_t* a, const uint32_t* b); // c=a-b -void multiprecision_sub_mod(uint32_t* c, const uint32_t* a, const uint32_t* b, const uint32_t* modp); -void multiprecision_rshift(uint32_t* c, const uint32_t* a); // c=a>>1, return carrier -void multiprecision_lshift_mod(uint32_t* c, const uint32_t* a, const uint32_t* modp); // c=a<>1, return carrier +void multiprecision_lshift_mod(uint32_t* c, const uint32_t* a, + const uint32_t* modp); // c=a< GenerateRandom() { } std::array r; - for (size_t i = 0; i < SIZE; i++) r[i] = std::rand(); + for (size_t i = 0; i < SIZE; i++) { + r[i] = std::rand(); + } return r; } } // namespace @@ -64,7 +66,8 @@ std::pair, EcdhPublicKey> GenerateECDHKeyPair() { memcpy(pk.y.data(), public_key.y, 32); /* private_key, public key pair */ - return std::make_pair, EcdhPublicKey>(std::move(private_key), std::move(pk)); + return std::make_pair, EcdhPublicKey>(std::move(private_key), + std::move(pk)); } bool ValidateECDHPoint(EcdhPublicKey pk) { @@ -75,7 +78,8 @@ bool ValidateECDHPoint(EcdhPublicKey pk) { return ECC_ValidatePoint(public_key); } -std::array ComputeDHKey(std::array my_private_key, EcdhPublicKey remote_public_key) { +std::array ComputeDHKey(std::array my_private_key, + EcdhPublicKey remote_public_key) { ecc::Point peer_publ_key, new_publ_key; uint32_t private_key[8]; memcpy(private_key, my_private_key.data(), 32); diff --git a/system/gd/security/ecdh_keys.h b/system/gd/security/ecdh_keys.h index f9c43023ba9..64ef63be0ef 100644 --- a/system/gd/security/ecdh_keys.h +++ b/system/gd/security/ecdh_keys.h @@ -18,6 +18,7 @@ #pragma once #include + #include namespace bluetooth { @@ -35,7 +36,8 @@ std::pair, EcdhPublicKey> GenerateECDHKeyPair(); * Bluetooth curve */ bool ValidateECDHPoint(EcdhPublicKey pk); -std::array ComputeDHKey(std::array my_private_key, EcdhPublicKey remote_public_key); +std::array ComputeDHKey(std::array my_private_key, + EcdhPublicKey remote_public_key); } // namespace security } // namespace bluetooth diff --git a/system/gd/security/facade.cc b/system/gd/security/facade.cc index 57cc33fe473..a83af4d486e 100644 --- a/system/gd/security/facade.cc +++ b/system/gd/security/facade.cc @@ -62,12 +62,10 @@ class SecurityModuleFacadeService : public SecurityModuleFacade::Service, public ISecurityManagerListener, public UI, public hci::AdvertisingCallback { - public: - SecurityModuleFacadeService( - SecurityModule* security_module, - L2capLeModule* l2cap_le_module, - ::bluetooth::os::Handler* security_handler, - hci::LeAdvertisingManager* le_advertising_manager) +public: + SecurityModuleFacadeService(SecurityModule* security_module, L2capLeModule* l2cap_le_module, + ::bluetooth::os::Handler* security_handler, + hci::LeAdvertisingManager* le_advertising_manager) : security_module_(security_module), l2cap_le_module_(l2cap_le_module), security_handler_(security_handler), @@ -77,25 +75,26 @@ class SecurityModuleFacadeService : public SecurityModuleFacade::Service, /* In order to receive connect/disconenct event, we must register service */ l2cap_le_module_->GetFixedChannelManager()->RegisterService( - bluetooth::l2cap::kLastFixedChannel - 2, - common::BindOnce(&SecurityModuleFacadeService::OnL2capRegistrationCompleteLe, common::Unretained(this)), - common::Bind(&SecurityModuleFacadeService::OnConnectionOpenLe, common::Unretained(this)), - security_handler_); + bluetooth::l2cap::kLastFixedChannel - 2, + common::BindOnce(&SecurityModuleFacadeService::OnL2capRegistrationCompleteLe, + common::Unretained(this)), + common::Bind(&SecurityModuleFacadeService::OnConnectionOpenLe, + common::Unretained(this)), + security_handler_); } void OnL2capRegistrationCompleteLe( - l2cap::le::FixedChannelManager::RegistrationResult result, - std::unique_ptr /* le_smp_service */) { + l2cap::le::FixedChannelManager::RegistrationResult result, + std::unique_ptr /* le_smp_service */) { log::assert_that( - result == bluetooth::l2cap::le::FixedChannelManager::RegistrationResult::SUCCESS, - "Failed to register to LE SMP Fixed Channel Service"); + result == bluetooth::l2cap::le::FixedChannelManager::RegistrationResult::SUCCESS, + "Failed to register to LE SMP Fixed Channel Service"); } void OnConnectionOpenLe(std::unique_ptr channel) { channel->RegisterOnCloseCallback( - security_handler_, - common::BindOnce( - &SecurityModuleFacadeService::OnConnectionClosedLe, common::Unretained(this), channel->GetDevice())); + security_handler_, common::BindOnce(&SecurityModuleFacadeService::OnConnectionClosedLe, + common::Unretained(this), channel->GetDevice())); } void OnConnectionClosedLe(hci::AddressWithType address, hci::ErrorCode /* error_code */) { @@ -105,137 +104,121 @@ class SecurityModuleFacadeService : public SecurityModuleFacade::Service, helper_events_.OnIncomingEvent(disconnected); } - ::grpc::Status CreateBond( - ::grpc::ServerContext* /* context */, - const blueberry::facade::BluetoothAddressWithType* request, - ::google::protobuf::Empty* /* response */) override { + ::grpc::Status CreateBond(::grpc::ServerContext* /* context */, + const blueberry::facade::BluetoothAddressWithType* request, + ::google::protobuf::Empty* /* response */) override { hci::Address peer; - log::assert_that( - hci::Address::FromString(request->address().address(), peer), - "assert failed: hci::Address::FromString(request->address().address(), peer)"); + log::assert_that(hci::Address::FromString(request->address().address(), peer), + "assert failed: hci::Address::FromString(request->address().address(), peer)"); hci::AddressType peer_type = static_cast(request->type()); security_module_->GetSecurityManager()->CreateBond(hci::AddressWithType(peer, peer_type)); return ::grpc::Status::OK; } - ::grpc::Status CreateBondOutOfBand( - ::grpc::ServerContext* /* context */, - const OobDataBondMessage* request, - ::google::protobuf::Empty* /* response */) override { + ::grpc::Status CreateBondOutOfBand(::grpc::ServerContext* /* context */, + const OobDataBondMessage* request, + ::google::protobuf::Empty* /* response */) override { hci::Address peer; - log::assert_that( - hci::Address::FromString(request->address().address().address(), peer), - "assert failed: hci::Address::FromString(request->address().address().address(), peer)"); + log::assert_that(hci::Address::FromString(request->address().address().address(), peer), + "assert failed: " + "hci::Address::FromString(request->address().address().address(), peer)"); hci::AddressType peer_type = static_cast(request->address().type()); pairing::SimplePairingHash c; pairing::SimplePairingRandomizer r; - std::copy( - std::begin(request->p192_data().confirmation_value()), - std::end(request->p192_data().confirmation_value()), - c.data()); - std::copy(std::begin(request->p192_data().random_value()), std::end(request->p192_data().random_value()), r.data()); + std::copy(std::begin(request->p192_data().confirmation_value()), + std::end(request->p192_data().confirmation_value()), c.data()); + std::copy(std::begin(request->p192_data().random_value()), + std::end(request->p192_data().random_value()), r.data()); pairing::OobData p192_data(c, r); - std::copy( - std::begin(request->p256_data().confirmation_value()), - std::end(request->p256_data().confirmation_value()), - c.data()); - std::copy(std::begin(request->p256_data().random_value()), std::end(request->p256_data().random_value()), r.data()); + std::copy(std::begin(request->p256_data().confirmation_value()), + std::end(request->p256_data().confirmation_value()), c.data()); + std::copy(std::begin(request->p256_data().random_value()), + std::end(request->p256_data().random_value()), r.data()); pairing::OobData p256_data(c, r); security_module_->GetSecurityManager()->CreateBondOutOfBand( - hci::AddressWithType(peer, peer_type), p192_data, p256_data); + hci::AddressWithType(peer, peer_type), p192_data, p256_data); return ::grpc::Status::OK; } - ::grpc::Status GetOutOfBandData( - ::grpc::ServerContext* /* context */, - const ::google::protobuf::Empty* /* request */, - ::google::protobuf::Empty* /* response */) override { - security_module_->GetSecurityManager()->GetOutOfBandData( - security_handler_->BindOnceOn(this, &SecurityModuleFacadeService::OobDataEventOccurred)); + ::grpc::Status GetOutOfBandData(::grpc::ServerContext* /* context */, + const ::google::protobuf::Empty* /* request */, + ::google::protobuf::Empty* /* response */) override { + security_module_->GetSecurityManager()->GetOutOfBandData(security_handler_->BindOnceOn( + this, &SecurityModuleFacadeService::OobDataEventOccurred)); return ::grpc::Status::OK; } ::grpc::Status FetchGetOutOfBandDataEvents( - ::grpc::ServerContext* context, - const ::google::protobuf::Empty* /* request */, - ::grpc::ServerWriter* writer) override { + ::grpc::ServerContext* context, const ::google::protobuf::Empty* /* request */, + ::grpc::ServerWriter* writer) override { return oob_events_.RunLoop(context, writer); } - ::grpc::Status CreateBondLe( - ::grpc::ServerContext* /* context */, - const blueberry::facade::BluetoothAddressWithType* request, - ::google::protobuf::Empty* /* response */) override { + ::grpc::Status CreateBondLe(::grpc::ServerContext* /* context */, + const blueberry::facade::BluetoothAddressWithType* request, + ::google::protobuf::Empty* /* response */) override { hci::Address peer; - log::assert_that( - hci::Address::FromString(request->address().address(), peer), - "assert failed: hci::Address::FromString(request->address().address(), peer)"); + log::assert_that(hci::Address::FromString(request->address().address(), peer), + "assert failed: hci::Address::FromString(request->address().address(), peer)"); hci::AddressType peer_type = static_cast(request->type()); security_module_->GetSecurityManager()->CreateBondLe(hci::AddressWithType(peer, peer_type)); return ::grpc::Status::OK; } - ::grpc::Status CancelBond( - ::grpc::ServerContext* /* context */, - const blueberry::facade::BluetoothAddressWithType* request, - ::google::protobuf::Empty* /* response */) override { + ::grpc::Status CancelBond(::grpc::ServerContext* /* context */, + const blueberry::facade::BluetoothAddressWithType* request, + ::google::protobuf::Empty* /* response */) override { hci::Address peer; - log::assert_that( - hci::Address::FromString(request->address().address(), peer), - "assert failed: hci::Address::FromString(request->address().address(), peer)"); + log::assert_that(hci::Address::FromString(request->address().address(), peer), + "assert failed: hci::Address::FromString(request->address().address(), peer)"); hci::AddressType peer_type = hci::AddressType::PUBLIC_DEVICE_ADDRESS; security_module_->GetSecurityManager()->CancelBond(hci::AddressWithType(peer, peer_type)); return ::grpc::Status::OK; } - ::grpc::Status RemoveBond( - ::grpc::ServerContext* /* context */, - const blueberry::facade::BluetoothAddressWithType* request, - ::google::protobuf::Empty* /* response */) override { + ::grpc::Status RemoveBond(::grpc::ServerContext* /* context */, + const blueberry::facade::BluetoothAddressWithType* request, + ::google::protobuf::Empty* /* response */) override { hci::Address peer; - log::assert_that( - hci::Address::FromString(request->address().address(), peer), - "assert failed: hci::Address::FromString(request->address().address(), peer)"); + log::assert_that(hci::Address::FromString(request->address().address(), peer), + "assert failed: hci::Address::FromString(request->address().address(), peer)"); hci::AddressType peer_type = hci::AddressType::PUBLIC_DEVICE_ADDRESS; security_module_->GetSecurityManager()->RemoveBond(hci::AddressWithType(peer, peer_type)); return ::grpc::Status::OK; } - ::grpc::Status FetchUiEvents( - ::grpc::ServerContext* context, - const ::google::protobuf::Empty* /* request */, - ::grpc::ServerWriter* writer) override { + ::grpc::Status FetchUiEvents(::grpc::ServerContext* context, + const ::google::protobuf::Empty* /* request */, + ::grpc::ServerWriter* writer) override { return ui_events_.RunLoop(context, writer); } - ::grpc::Status SendUiCallback( - ::grpc::ServerContext* /* context */, - const UiCallbackMsg* request, - ::google::protobuf::Empty* /* response */) override { + ::grpc::Status SendUiCallback(::grpc::ServerContext* /* context */, const UiCallbackMsg* request, + ::google::protobuf::Empty* /* response */) override { hci::Address peer; - log::assert_that( - hci::Address::FromString(request->address().address().address(), peer), - "assert failed: hci::Address::FromString(request->address().address().address(), peer)"); + log::assert_that(hci::Address::FromString(request->address().address().address(), peer), + "assert failed: " + "hci::Address::FromString(request->address().address().address(), peer)"); hci::AddressType remote_type = static_cast(request->address().type()); switch (request->message_type()) { case UiCallbackType::PASSKEY: security_module_->GetSecurityManager()->OnPasskeyEntry( - hci::AddressWithType(peer, remote_type), request->numeric_value()); + hci::AddressWithType(peer, remote_type), request->numeric_value()); break; case UiCallbackType::YES_NO: - security_module_->GetSecurityManager()->OnConfirmYesNo(hci::AddressWithType(peer, remote_type), - request->boolean()); + security_module_->GetSecurityManager()->OnConfirmYesNo( + hci::AddressWithType(peer, remote_type), request->boolean()); break; case UiCallbackType::PAIRING_PROMPT: security_module_->GetSecurityManager()->OnPairingPromptAccepted( - hci::AddressWithType(peer, remote_type), request->boolean()); + hci::AddressWithType(peer, remote_type), request->boolean()); break; case UiCallbackType::PIN: log::info("PIN Callback"); security_module_->GetSecurityManager()->OnPinEntry( - hci::AddressWithType(peer, remote_type), - std::vector(request->pin().cbegin(), request->pin().cend())); + hci::AddressWithType(peer, remote_type), + std::vector(request->pin().cbegin(), request->pin().cend())); break; default: log::error("Unknown UiCallbackType {}", static_cast(request->message_type())); @@ -244,33 +227,27 @@ class SecurityModuleFacadeService : public SecurityModuleFacade::Service, return ::grpc::Status::OK; } - ::grpc::Status FetchBondEvents( - ::grpc::ServerContext* context, - const ::google::protobuf::Empty* /* request */, - ::grpc::ServerWriter* writer) override { + ::grpc::Status FetchBondEvents(::grpc::ServerContext* context, + const ::google::protobuf::Empty* /* request */, + ::grpc::ServerWriter* writer) override { return bond_events_.RunLoop(context, writer); } - ::grpc::Status FetchHelperEvents( - ::grpc::ServerContext* context, - const ::google::protobuf::Empty* /* request */, - ::grpc::ServerWriter* writer) override { + ::grpc::Status FetchHelperEvents(::grpc::ServerContext* context, + const ::google::protobuf::Empty* /* request */, + ::grpc::ServerWriter* writer) override { return helper_events_.RunLoop(context, writer); } ::grpc::Status FetchAdvertisingCallbackEvents( - ::grpc::ServerContext* context, - const ::google::protobuf::Empty* /* request */, - ::grpc::ServerWriter* writer) override { + ::grpc::ServerContext* context, const ::google::protobuf::Empty* /* request */, + ::grpc::ServerWriter* writer) override { le_advertising_manager_->RegisterAdvertisingCallback(this); return advertising_callback_events_.RunLoop(context, writer); } - void OnAdvertisingSetStarted( - int /* reg_id */, - uint8_t advertiser_id, - int8_t /* tx_power */, - AdvertisingStatus /* status */) { + void OnAdvertisingSetStarted(int /* reg_id */, uint8_t advertiser_id, int8_t /* tx_power */, + AdvertisingStatus /* status */) { AdvertisingCallbackMsg advertising_set_started; advertising_set_started.set_message_type(AdvertisingCallbackMsgType::ADVERTISING_SET_STARTED); advertising_set_started.set_advertising_started(AdvertisingSetStarted::STARTED); @@ -317,82 +294,87 @@ class SecurityModuleFacadeService : public SecurityModuleFacade::Service, advertising_callback_events_.OnIncomingEvent(get_own_address); } - ::grpc::Status SetIoCapability( - ::grpc::ServerContext* /* context */, - const IoCapabilityMessage* request, - ::google::protobuf::Empty* /* response */) override { + ::grpc::Status SetIoCapability(::grpc::ServerContext* /* context */, + const IoCapabilityMessage* request, + ::google::protobuf::Empty* /* response */) override { security_module_->GetFacadeConfigurationApi()->SetIoCapability( - static_cast(request->capability())); + static_cast(request->capability())); return ::grpc::Status::OK; } - ::grpc::Status SetLeIoCapability( - ::grpc::ServerContext* /* context */, - const LeIoCapabilityMessage* request, - ::google::protobuf::Empty* /* response */) override { + ::grpc::Status SetLeIoCapability(::grpc::ServerContext* /* context */, + const LeIoCapabilityMessage* request, + ::google::protobuf::Empty* /* response */) override { security_module_->GetFacadeConfigurationApi()->SetLeIoCapability( - static_cast(request->capabilities())); + static_cast(request->capabilities())); return ::grpc::Status::OK; } - ::grpc::Status SetAuthenticationRequirements( - ::grpc::ServerContext* /* context */, - const AuthenticationRequirementsMessage* request, - ::google::protobuf::Empty* /* response */) override { + ::grpc::Status SetAuthenticationRequirements(::grpc::ServerContext* /* context */, + const AuthenticationRequirementsMessage* request, + ::google::protobuf::Empty* /* response */) override { security_module_->GetFacadeConfigurationApi()->SetAuthenticationRequirements( - static_cast(request->requirement())); + static_cast(request->requirement())); return ::grpc::Status::OK; } - ::grpc::Status SetLeAuthRequirements( - ::grpc::ServerContext* /* context */, - const LeAuthRequirementsMessage* request, - ::google::protobuf::Empty* /* response */) override { + ::grpc::Status SetLeAuthRequirements(::grpc::ServerContext* /* context */, + const LeAuthRequirementsMessage* request, + ::google::protobuf::Empty* /* response */) override { uint8_t auth_req = request->bond() ? AUTH_REQ_BOND : AUTH_REQ_NO_BOND; - if (request->mitm()) auth_req |= AUTH_REQ_MITM_MASK; - if (request->secure_connections()) auth_req |= AUTH_REQ_SECURE_CONNECTIONS_MASK; - if (request->keypress()) auth_req |= AUTH_REQ_KEYPRESS_MASK; - if (request->ct2()) auth_req |= AUTH_REQ_CT2_MASK; - if (request->reserved_bits()) auth_req |= (((request->reserved_bits()) << 6) & AUTH_REQ_RFU_MASK); + if (request->mitm()) { + auth_req |= AUTH_REQ_MITM_MASK; + } + if (request->secure_connections()) { + auth_req |= AUTH_REQ_SECURE_CONNECTIONS_MASK; + } + if (request->keypress()) { + auth_req |= AUTH_REQ_KEYPRESS_MASK; + } + if (request->ct2()) { + auth_req |= AUTH_REQ_CT2_MASK; + } + if (request->reserved_bits()) { + auth_req |= (((request->reserved_bits()) << 6) & AUTH_REQ_RFU_MASK); + } security_module_->GetFacadeConfigurationApi()->SetLeAuthRequirements(auth_req); return ::grpc::Status::OK; } - ::grpc::Status SetLeMaximumEncryptionKeySize( - ::grpc::ServerContext* /* context */, - const LeMaximumEncryptionKeySizeMessage* request, - ::google::protobuf::Empty* /* response */) override { + ::grpc::Status SetLeMaximumEncryptionKeySize(::grpc::ServerContext* /* context */, + const LeMaximumEncryptionKeySizeMessage* request, + ::google::protobuf::Empty* /* response */) override { security_module_->GetFacadeConfigurationApi()->SetLeMaximumEncryptionKeySize( - request->maximum_encryption_key_size()); + request->maximum_encryption_key_size()); return ::grpc::Status::OK; } - ::grpc::Status SetLeOobDataPresent( - ::grpc::ServerContext* /* context */, - const LeOobDataPresentMessage* request, - ::google::protobuf::Empty* /* response */) override { + ::grpc::Status SetLeOobDataPresent(::grpc::ServerContext* /* context */, + const LeOobDataPresentMessage* request, + ::google::protobuf::Empty* /* response */) override { security_module_->GetFacadeConfigurationApi()->SetLeOobDataPresent( - static_cast(request->data_present())); + static_cast(request->data_present())); return ::grpc::Status::OK; } - ::grpc::Status SetLeInitiatorAddressPolicy( - ::grpc::ServerContext* /* context */, - const blueberry::facade::hci::PrivacyPolicy* request, - ::google::protobuf::Empty* /* response */) override { + ::grpc::Status SetLeInitiatorAddressPolicy(::grpc::ServerContext* /* context */, + const blueberry::facade::hci::PrivacyPolicy* request, + ::google::protobuf::Empty* /* response */) override { Address address = Address::kEmpty; hci::LeAddressManager::AddressPolicy address_policy = - static_cast(request->address_policy()); + static_cast(request->address_policy()); if (address_policy == hci::LeAddressManager::AddressPolicy::USE_STATIC_ADDRESS || address_policy == hci::LeAddressManager::AddressPolicy::USE_PUBLIC_ADDRESS) { log::assert_that( - Address::FromString(request->address_with_type().address().address(), address), - "assert failed: Address::FromString(request->address_with_type().address().address(), " - "address)"); + Address::FromString(request->address_with_type().address().address(), address), + "assert failed: " + "Address::FromString(request->address_with_type().address().address(), " + "address)"); } - hci::AddressWithType address_with_type(address, static_cast(request->address_with_type().type())); + hci::AddressWithType address_with_type( + address, static_cast(request->address_with_type().type())); hci::Octet16 irk = {}; auto request_irk_length = request->rotation_irk().end() - request->rotation_irk().begin(); if (request_irk_length == hci::kOctet16Length) { @@ -404,38 +386,37 @@ class SecurityModuleFacadeService : public SecurityModuleFacade::Service, auto minimum_rotation_time = std::chrono::milliseconds(request->minimum_rotation_time()); auto maximum_rotation_time = std::chrono::milliseconds(request->maximum_rotation_time()); security_module_->GetSecurityManager()->SetLeInitiatorAddressPolicyForTest( - address_policy, address_with_type, irk, minimum_rotation_time, maximum_rotation_time); + address_policy, address_with_type, irk, minimum_rotation_time, maximum_rotation_time); return ::grpc::Status::OK; } ::grpc::Status FetchEnforceSecurityPolicyEvents( - ::grpc::ServerContext* context, - const ::google::protobuf::Empty* /* request */, - ::grpc::ServerWriter* writer) override { + ::grpc::ServerContext* context, const ::google::protobuf::Empty* /* request */, + ::grpc::ServerWriter* writer) override { return enforce_security_policy_events_.RunLoop(context, writer); } - ::grpc::Status EnforceSecurityPolicy( - ::grpc::ServerContext* /* context */, - const SecurityPolicyMessage* request, - ::google::protobuf::Empty* /* response */) override { + ::grpc::Status EnforceSecurityPolicy(::grpc::ServerContext* /* context */, + const SecurityPolicyMessage* request, + ::google::protobuf::Empty* /* response */) override { hci::Address peer; - log::assert_that( - hci::Address::FromString(request->address().address().address(), peer), - "assert failed: hci::Address::FromString(request->address().address().address(), peer)"); + log::assert_that(hci::Address::FromString(request->address().address().address(), peer), + "assert failed: " + "hci::Address::FromString(request->address().address().address(), peer)"); hci::AddressType peer_type = static_cast(request->address().type()); hci::AddressWithType peer_with_type(peer, peer_type); l2cap::classic::SecurityEnforcementInterface::ResultCallback callback = - security_handler_->BindOnceOn(this, &SecurityModuleFacadeService::EnforceSecurityPolicyEvent); + security_handler_->BindOnceOn(this, + &SecurityModuleFacadeService::EnforceSecurityPolicyEvent); security_module_->GetFacadeConfigurationApi()->EnforceSecurityPolicy( - peer_with_type, static_cast(request->policy()), std::move(callback)); + peer_with_type, static_cast(request->policy()), + std::move(callback)); return ::grpc::Status::OK; } - ::grpc::Status GetLeOutOfBandData( - ::grpc::ServerContext* /* context */, - const ::google::protobuf::Empty* /* request */, - OobDataMessage* response) override { + ::grpc::Status GetLeOutOfBandData(::grpc::ServerContext* /* context */, + const ::google::protobuf::Empty* /* request */, + OobDataMessage* response) override { std::array le_sc_c; std::array le_sc_r; security_module_->GetFacadeConfigurationApi()->GetLeOutOfBandData(&le_sc_c, &le_sc_r); @@ -451,19 +432,18 @@ class SecurityModuleFacadeService : public SecurityModuleFacade::Service, return ::grpc::Status::OK; } - ::grpc::Status SetOutOfBandData( - ::grpc::ServerContext* /* context */, - const OobDataMessage* request, - ::google::protobuf::Empty* /* response */) override { + ::grpc::Status SetOutOfBandData(::grpc::ServerContext* /* context */, + const OobDataMessage* request, + ::google::protobuf::Empty* /* response */) override { hci::Address peer; - log::assert_that( - hci::Address::FromString(request->address().address().address(), peer), - "assert failed: hci::Address::FromString(request->address().address().address(), peer)"); + log::assert_that(hci::Address::FromString(request->address().address().address(), peer), + "assert failed: " + "hci::Address::FromString(request->address().address().address(), peer)"); hci::AddressType peer_type = static_cast(request->address().type()); hci::AddressWithType peer_with_type(peer, peer_type); - // We can't simply iterate till end of string, because we have an empty byte added at the end. We know confirm and - // random are fixed size, 16 bytes + // We can't simply iterate till end of string, because we have an empty byte added at the end. + // We know confirm and random are fixed size, 16 bytes std::array le_sc_c; auto req_le_sc_c = request->confirmation_value(); std::copy(req_le_sc_c.begin(), req_le_sc_c.begin() + 16, le_sc_c.data()); @@ -472,16 +452,16 @@ class SecurityModuleFacadeService : public SecurityModuleFacade::Service, auto req_le_sc_r = request->random_value(); std::copy(req_le_sc_r.begin(), req_le_sc_r.begin() + 16, le_sc_r.data()); - security_module_->GetFacadeConfigurationApi()->SetOutOfBandData(peer_with_type, le_sc_c, le_sc_r); + security_module_->GetFacadeConfigurationApi()->SetOutOfBandData(peer_with_type, le_sc_c, + le_sc_r); return ::grpc::Status::OK; } - ::grpc::Status FetchDisconnectEvents( - ::grpc::ServerContext* context, - const ::google::protobuf::Empty* /* request */, - ::grpc::ServerWriter* writer) override { - security_module_->GetFacadeConfigurationApi()->SetDisconnectCallback( - common::Bind(&SecurityModuleFacadeService::DisconnectEventOccurred, common::Unretained(this))); + ::grpc::Status FetchDisconnectEvents(::grpc::ServerContext* context, + const ::google::protobuf::Empty* /* request */, + ::grpc::ServerWriter* writer) override { + security_module_->GetFacadeConfigurationApi()->SetDisconnectCallback(common::Bind( + &SecurityModuleFacadeService::DisconnectEventOccurred, common::Unretained(this))); return disconnect_events_.RunLoop(context, writer); } @@ -635,19 +615,21 @@ class SecurityModuleFacadeService : public SecurityModuleFacade::Service, enforce_security_policy_events_.OnIncomingEvent(msg); } - private: +private: SecurityModule* security_module_; L2capLeModule* l2cap_le_module_; ::bluetooth::os::Handler* security_handler_; hci::LeAdvertisingManager* le_advertising_manager_; ::bluetooth::grpc::GrpcEventQueue ui_events_{"UI events"}; ::bluetooth::grpc::GrpcEventQueue bond_events_{"Bond events"}; - ::bluetooth::grpc::GrpcEventQueue helper_events_{"Events that don't fit any other category"}; + ::bluetooth::grpc::GrpcEventQueue helper_events_{ + "Events that don't fit any other category"}; ::bluetooth::grpc::GrpcEventQueue enforce_security_policy_events_{ - "Enforce Security Policy Events"}; + "Enforce Security Policy Events"}; ::bluetooth::grpc::GrpcEventQueue disconnect_events_{"Disconnect events"}; ::bluetooth::grpc::GrpcEventQueue oob_events_{"OOB Data events"}; - ::bluetooth::grpc::GrpcEventQueue advertising_callback_events_{"Advertising callback events"}; + ::bluetooth::grpc::GrpcEventQueue advertising_callback_events_{ + "Advertising callback events"}; uint32_t unique_id{1}; std::map> user_yes_no_callbacks_; std::map> user_passkey_callbacks_; @@ -662,11 +644,9 @@ void SecurityModuleFacadeModule::ListDependencies(ModuleList* list) const { void SecurityModuleFacadeModule::Start() { ::bluetooth::grpc::GrpcFacadeModule::Start(); - service_ = new SecurityModuleFacadeService( - GetDependency(), - GetDependency(), - GetHandler(), - GetDependency()); + service_ = new SecurityModuleFacadeService(GetDependency(), + GetDependency(), GetHandler(), + GetDependency()); } void SecurityModuleFacadeModule::Stop() { @@ -674,12 +654,10 @@ void SecurityModuleFacadeModule::Stop() { ::bluetooth::grpc::GrpcFacadeModule::Stop(); } -::grpc::Service* SecurityModuleFacadeModule::GetService() const { - return service_; -} +::grpc::Service* SecurityModuleFacadeModule::GetService() const { return service_; } const ModuleFactory SecurityModuleFacadeModule::Factory = - ::bluetooth::ModuleFactory([]() { return new SecurityModuleFacadeModule(); }); + ::bluetooth::ModuleFactory([]() { return new SecurityModuleFacadeModule(); }); } // namespace security } // namespace bluetooth diff --git a/system/gd/security/facade.h b/system/gd/security/facade.h index 207ad423cb5..d25245170cd 100644 --- a/system/gd/security/facade.h +++ b/system/gd/security/facade.h @@ -25,7 +25,7 @@ namespace security { class SecurityModuleFacadeService; class SecurityModuleFacadeModule : public ::bluetooth::grpc::GrpcFacadeModule { - public: +public: static const ModuleFactory Factory; void ListDependencies(ModuleList* list) const override; @@ -33,7 +33,7 @@ class SecurityModuleFacadeModule : public ::bluetooth::grpc::GrpcFacadeModule { void Stop() override; ::grpc::Service* GetService() const override; - private: +private: SecurityModuleFacadeService* service_; }; diff --git a/system/gd/security/facade_configuration_api.cc b/system/gd/security/facade_configuration_api.cc index c96f567e702..f9ea395a336 100644 --- a/system/gd/security/facade_configuration_api.cc +++ b/system/gd/security/facade_configuration_api.cc @@ -24,67 +24,64 @@ namespace bluetooth { namespace security { -void FacadeConfigurationApi::SetDisconnectCallback(internal::SecurityManagerImpl::FacadeDisconnectCallback callback) { - security_handler_->CallOn(security_manager_impl_, &internal::SecurityManagerImpl::SetDisconnectCallback, callback); +void FacadeConfigurationApi::SetDisconnectCallback( + internal::SecurityManagerImpl::FacadeDisconnectCallback callback) { + security_handler_->CallOn(security_manager_impl_, + &internal::SecurityManagerImpl::SetDisconnectCallback, callback); } void FacadeConfigurationApi::SetIoCapability(hci::IoCapability io_capability) { - security_handler_->CallOn(security_manager_impl_, &internal::SecurityManagerImpl::SetIoCapability, io_capability); + security_handler_->CallOn(security_manager_impl_, &internal::SecurityManagerImpl::SetIoCapability, + io_capability); } -void FacadeConfigurationApi::SetAuthenticationRequirements(hci::AuthenticationRequirements authentication_requirement) { - security_handler_->CallOn( - security_manager_impl_, - &internal::SecurityManagerImpl::SetAuthenticationRequirements, - authentication_requirement); +void FacadeConfigurationApi::SetAuthenticationRequirements( + hci::AuthenticationRequirements authentication_requirement) { + security_handler_->CallOn(security_manager_impl_, + &internal::SecurityManagerImpl::SetAuthenticationRequirements, + authentication_requirement); } void FacadeConfigurationApi::SetLeIoCapability(security::IoCapability io_capability) { - security_handler_->CallOn(security_manager_impl_, &internal::SecurityManagerImpl::SetLeIoCapability, io_capability); + security_handler_->CallOn(security_manager_impl_, + &internal::SecurityManagerImpl::SetLeIoCapability, io_capability); } void FacadeConfigurationApi::SetLeAuthRequirements(uint8_t auth_req) { - security_handler_->CallOn(security_manager_impl_, &internal::SecurityManagerImpl::SetLeAuthRequirements, auth_req); + security_handler_->CallOn(security_manager_impl_, + &internal::SecurityManagerImpl::SetLeAuthRequirements, auth_req); } void FacadeConfigurationApi::SetLeMaximumEncryptionKeySize(uint8_t maximum_encryption_key_size) { - security_handler_->CallOn( - security_manager_impl_, - &internal::SecurityManagerImpl::SetLeMaximumEncryptionKeySize, - maximum_encryption_key_size); + security_handler_->CallOn(security_manager_impl_, + &internal::SecurityManagerImpl::SetLeMaximumEncryptionKeySize, + maximum_encryption_key_size); } void FacadeConfigurationApi::SetLeOobDataPresent(OobDataFlag oob_present) { - security_handler_->CallOn(security_manager_impl_, &internal::SecurityManagerImpl::SetLeOobDataPresent, oob_present); + security_handler_->CallOn(security_manager_impl_, + &internal::SecurityManagerImpl::SetLeOobDataPresent, oob_present); } -void FacadeConfigurationApi::GetLeOutOfBandData( - std::array* confirmation_value, std::array* random_value) { +void FacadeConfigurationApi::GetLeOutOfBandData(std::array* confirmation_value, + std::array* random_value) { security_manager_impl_->GetLeOutOfBandData(confirmation_value, random_value); } -void FacadeConfigurationApi::SetOutOfBandData( - hci::AddressWithType remote_address, - std::array confirmation_value, - std::array random_value) { - security_handler_->CallOn( - security_manager_impl_, - &internal::SecurityManagerImpl::SetOutOfBandData, - remote_address, - confirmation_value, - random_value); +void FacadeConfigurationApi::SetOutOfBandData(hci::AddressWithType remote_address, + std::array confirmation_value, + std::array random_value) { + security_handler_->CallOn(security_manager_impl_, + &internal::SecurityManagerImpl::SetOutOfBandData, remote_address, + confirmation_value, random_value); } void FacadeConfigurationApi::EnforceSecurityPolicy( - hci::AddressWithType remote, - l2cap::classic::SecurityPolicy policy, - l2cap::classic::SecurityEnforcementInterface::ResultCallback callback) { - security_handler_->CallOn( - security_manager_impl_, - &internal::SecurityManagerImpl::EnforceSecurityPolicy, - remote, - policy, - std::move(callback)); + hci::AddressWithType remote, l2cap::classic::SecurityPolicy policy, + l2cap::classic::SecurityEnforcementInterface::ResultCallback callback) { + security_handler_->CallOn(security_manager_impl_, + &internal::SecurityManagerImpl::EnforceSecurityPolicy, remote, policy, + std::move(callback)); } } // namespace security diff --git a/system/gd/security/facade_configuration_api.h b/system/gd/security/facade_configuration_api.h index 660b8178e66..b3da40557f3 100644 --- a/system/gd/security/facade_configuration_api.h +++ b/system/gd/security/facade_configuration_api.h @@ -31,7 +31,7 @@ namespace security { * encryption/decryption of communications. */ class FacadeConfigurationApi { - public: +public: FacadeConfigurationApi(const FacadeConfigurationApi&) = delete; FacadeConfigurationApi& operator=(const FacadeConfigurationApi&) = delete; @@ -41,26 +41,25 @@ class FacadeConfigurationApi { void SetDisconnectCallback(internal::SecurityManagerImpl::FacadeDisconnectCallback callback); void SetIoCapability(hci::IoCapability io_capability); void SetAuthenticationRequirements(hci::AuthenticationRequirements authentication_requirement); - void EnforceSecurityPolicy( - hci::AddressWithType remote, - l2cap::classic::SecurityPolicy policy, - l2cap::classic::SecurityEnforcementInterface::ResultCallback callback); + void EnforceSecurityPolicy(hci::AddressWithType remote, l2cap::classic::SecurityPolicy policy, + l2cap::classic::SecurityEnforcementInterface::ResultCallback callback); void SetLeIoCapability(security::IoCapability io_capability); void SetLeAuthRequirements(uint8_t auth_req); void SetLeMaximumEncryptionKeySize(uint8_t maximum_encryption_key_size); void SetLeOobDataPresent(OobDataFlag oob_present); - void GetLeOutOfBandData(std::array* confirmation_value, std::array* random_value); - void SetOutOfBandData( - hci::AddressWithType remote_address, - std::array confirmation_value, - std::array random_value); + void GetLeOutOfBandData(std::array* confirmation_value, + std::array* random_value); + void SetOutOfBandData(hci::AddressWithType remote_address, + std::array confirmation_value, + std::array random_value); - protected: - FacadeConfigurationApi(os::Handler* security_handler, internal::SecurityManagerImpl* security_manager_impl) +protected: + FacadeConfigurationApi(os::Handler* security_handler, + internal::SecurityManagerImpl* security_manager_impl) : security_handler_(security_handler), security_manager_impl_(security_manager_impl) {} - private: +private: os::Handler* security_handler_ = nullptr; internal::SecurityManagerImpl* security_manager_impl_; }; diff --git a/system/gd/security/initial_informations.h b/system/gd/security/initial_informations.h index 65540a52e5e..46c2af559b6 100644 --- a/system/gd/security/initial_informations.h +++ b/system/gd/security/initial_informations.h @@ -70,7 +70,8 @@ struct MyOobData { hci::Octet16 r; }; -/* This structure is filled and send to PairingHandlerLe to initiate the Pairing process with remote device */ +/* This structure is filled and send to PairingHandlerLe to initiate the Pairing process with remote + * device */ struct InitialInformations { hci::Role my_role; hci::AddressWithType my_connection_address; diff --git a/system/gd/security/internal/security_manager_impl.cc b/system/gd/security/internal/security_manager_impl.cc index 566f991f342..4a90031e12b 100644 --- a/system/gd/security/internal/security_manager_impl.cc +++ b/system/gd/security/internal/security_manager_impl.cc @@ -36,15 +36,14 @@ namespace bluetooth { namespace security { namespace internal { -void SecurityManagerImpl::DispatchPairingHandler( - std::shared_ptr record, - bool locally_initiated, - hci::IoCapability io_capability, - hci::AuthenticationRequirements auth_requirements, - pairing::OobData remote_p192_oob_data, - pairing::OobData remote_p256_oob_data) { - common::OnceCallback callback = - common::BindOnce(&SecurityManagerImpl::OnPairingHandlerComplete, common::Unretained(this)); +void SecurityManagerImpl::DispatchPairingHandler(std::shared_ptr record, + bool locally_initiated, + hci::IoCapability io_capability, + hci::AuthenticationRequirements auth_requirements, + pairing::OobData remote_p192_oob_data, + pairing::OobData remote_p256_oob_data) { + common::OnceCallback callback = common::BindOnce( + &SecurityManagerImpl::OnPairingHandlerComplete, common::Unretained(this)); auto entry = pairing_handler_map_.find(record->GetPseudoAddress()->GetAddress()); if (entry != pairing_handler_map_.end()) { log::warn("Device already has a pairing handler, and is in the middle of pairing!"); @@ -54,64 +53,61 @@ void SecurityManagerImpl::DispatchPairingHandler( switch (record->GetPseudoAddress()->GetAddressType()) { case hci::AddressType::PUBLIC_DEVICE_ADDRESS: { pairing_handler = std::make_shared( - security_manager_channel_, - record, - security_handler_, - std::move(callback), - user_interface_, - user_interface_handler_, - record->GetPseudoAddress()->ToString(), - name_db_module_); + security_manager_channel_, record, security_handler_, std::move(callback), + user_interface_, user_interface_handler_, record->GetPseudoAddress()->ToString(), + name_db_module_); break; } default: - log::fatal( - "Pairing type {} not implemented!", - (uint8_t)record->GetPseudoAddress()->GetAddressType()); + log::fatal("Pairing type {} not implemented!", + (uint8_t)record->GetPseudoAddress()->GetAddressType()); } auto new_entry = std::pair>( - record->GetPseudoAddress()->GetAddress(), pairing_handler); + record->GetPseudoAddress()->GetAddress(), pairing_handler); pairing_handler_map_.insert(std::move(new_entry)); - pairing_handler->Initiate( - locally_initiated, io_capability, auth_requirements, remote_p192_oob_data, remote_p256_oob_data); + pairing_handler->Initiate(locally_initiated, io_capability, auth_requirements, + remote_p192_oob_data, remote_p256_oob_data); } void SecurityManagerImpl::Init() { security_manager_channel_->SetChannelListener(this); - security_manager_channel_->SendCommand(hci::WriteSimplePairingModeBuilder::Create(hci::Enable::ENABLED)); - security_manager_channel_->SendCommand(hci::WriteSecureConnectionsHostSupportBuilder::Create(hci::Enable::ENABLED)); + security_manager_channel_->SendCommand( + hci::WriteSimplePairingModeBuilder::Create(hci::Enable::ENABLED)); + security_manager_channel_->SendCommand( + hci::WriteSecureConnectionsHostSupportBuilder::Create(hci::Enable::ENABLED)); log::assert_that(storage_module_ != nullptr, "Storage module must not be null!"); security_database_.LoadRecordsFromStorage(); auto irk_prop = - storage_module_->GetBin(BTIF_STORAGE_SECTION_ADAPTER, BTIF_STORAGE_KEY_LE_LOCAL_KEY_IRK); + storage_module_->GetBin(BTIF_STORAGE_SECTION_ADAPTER, BTIF_STORAGE_KEY_LE_LOCAL_KEY_IRK); if (!irk_prop.has_value()) { auto rand16 = bluetooth::os::GenerateRandom<16>(); std::vector new_irk{rand16.begin(), rand16.end()}; - storage_module_->SetBin( - BTIF_STORAGE_SECTION_ADAPTER, BTIF_STORAGE_KEY_LE_LOCAL_KEY_IRK, new_irk); - irk_prop = - storage_module_->GetBin(BTIF_STORAGE_SECTION_ADAPTER, BTIF_STORAGE_KEY_LE_LOCAL_KEY_IRK); + storage_module_->SetBin(BTIF_STORAGE_SECTION_ADAPTER, BTIF_STORAGE_KEY_LE_LOCAL_KEY_IRK, + new_irk); + irk_prop = storage_module_->GetBin(BTIF_STORAGE_SECTION_ADAPTER, + BTIF_STORAGE_KEY_LE_LOCAL_KEY_IRK); } Address controllerAddress = controller_->GetMacAddress(); auto address_prop = - storage_module_->GetProperty(BTIF_STORAGE_SECTION_ADAPTER, BTIF_STORAGE_KEY_ADDRESS); + storage_module_->GetProperty(BTIF_STORAGE_SECTION_ADAPTER, BTIF_STORAGE_KEY_ADDRESS); if (!address_prop || address_prop.value() != controllerAddress.ToString()) { - storage_module_->SetProperty( - BTIF_STORAGE_SECTION_ADAPTER, BTIF_STORAGE_KEY_ADDRESS, controllerAddress.ToString()); + storage_module_->SetProperty(BTIF_STORAGE_SECTION_ADAPTER, BTIF_STORAGE_KEY_ADDRESS, + controllerAddress.ToString()); } local_identity_address_ = - hci::AddressWithType(controllerAddress, hci::AddressType::PUBLIC_DEVICE_ADDRESS); + hci::AddressWithType(controllerAddress, hci::AddressType::PUBLIC_DEVICE_ADDRESS); irk_prop = - storage_module_->GetBin(BTIF_STORAGE_SECTION_ADAPTER, BTIF_STORAGE_KEY_LE_LOCAL_KEY_IRK); + storage_module_->GetBin(BTIF_STORAGE_SECTION_ADAPTER, BTIF_STORAGE_KEY_LE_LOCAL_KEY_IRK); log::assert_that(irk_prop.has_value(), "Irk not found in storage"); log::assert_that(irk_prop->size() == 16, "Irk corrupted in storage"); std::copy(irk_prop->begin(), irk_prop->end(), local_identity_resolving_key_.data()); - hci::LeAddressManager::AddressPolicy address_policy = hci::LeAddressManager::AddressPolicy::USE_RESOLVABLE_ADDRESS; + hci::LeAddressManager::AddressPolicy address_policy = + hci::LeAddressManager::AddressPolicy::USE_RESOLVABLE_ADDRESS; hci::AddressWithType address_with_type(hci::Address{}, hci::AddressType::RANDOM_DEVICE_ADDRESS); /* Default to 7 minutes minimum, 15 minutes maximum for random address refreshing; @@ -121,16 +117,17 @@ void SecurityManagerImpl::Init() { auto maximum_rotation_time = std::chrono::minutes( android::sysprop::bluetooth::Ble::random_address_rotation_interval_max().value_or(15)); - acl_manager_->SetPrivacyPolicyForInitiatorAddress( - address_policy, address_with_type, minimum_rotation_time, maximum_rotation_time); + acl_manager_->SetPrivacyPolicyForInitiatorAddress(address_policy, address_with_type, + minimum_rotation_time, maximum_rotation_time); } void SecurityManagerImpl::CreateBond(hci::AddressWithType device) { this->CreateBondOutOfBand(device, pairing::OobData(), pairing::OobData()); } -void SecurityManagerImpl::CreateBondOutOfBand( - hci::AddressWithType device, pairing::OobData remote_p192_oob_data, pairing::OobData remote_p256_oob_data) { +void SecurityManagerImpl::CreateBondOutOfBand(hci::AddressWithType device, + pairing::OobData remote_p192_oob_data, + pairing::OobData remote_p256_oob_data) { auto record = security_database_.FindOrCreate(device); if (record->IsPaired()) { // Bonded means we saved it, but the caller doesn't care @@ -140,13 +137,9 @@ void SecurityManagerImpl::CreateBondOutOfBand( if (!record->IsPairing()) { // Dispatch pairing handler, if we are calling create we are the initiator log::warn("Dispatch #1"); - DispatchPairingHandler( - record, - true, - this->local_io_capability_, - this->local_authentication_requirements_, - remote_p192_oob_data, - remote_p256_oob_data); + DispatchPairingHandler(record, true, this->local_io_capability_, + this->local_authentication_requirements_, remote_p192_oob_data, + remote_p256_oob_data); } } } @@ -168,8 +161,9 @@ void SecurityManagerImpl::CreateBondLe(hci::AddressWithType address) { } l2cap_manager_le_->ConnectServices( - address, common::BindOnce(&SecurityManagerImpl::OnConnectionFailureLe, common::Unretained(this)), - security_handler_); + address, + common::BindOnce(&SecurityManagerImpl::OnConnectionFailureLe, common::Unretained(this)), + security_handler_); } void SecurityManagerImpl::CancelBond(hci::AddressWithType device) { @@ -191,7 +185,7 @@ void SecurityManagerImpl::RemoveBond(hci::AddressWithType device) { security_manager_channel_->Disconnect(device.GetAddress()); security_database_.Remove(device); security_manager_channel_->SendCommand(hci::DeleteStoredLinkKeyBuilder::Create( - device.GetAddress(), hci::DeleteStoredLinkKeyDeleteAllFlag::SPECIFIED_BD_ADDR)); + device.GetAddress(), hci::DeleteStoredLinkKeyDeleteAllFlag::SPECIFIED_BD_ADDR)); NotifyDeviceUnbonded(device); } @@ -205,16 +199,16 @@ void SecurityManagerImpl::SetUserInterfaceHandler(UI* user_interface, os::Handle // TODO(jpawlowski): remove once we have config file abstraction in cert tests void SecurityManagerImpl::SetLeInitiatorAddressPolicyForTest( - hci::LeAddressManager::AddressPolicy address_policy, - hci::AddressWithType fixed_address, - hci::Octet16 rotation_irk, - std::chrono::milliseconds minimum_rotation_time, - std::chrono::milliseconds maximum_rotation_time) { - acl_manager_->SetPrivacyPolicyForInitiatorAddressForTest( - address_policy, fixed_address, rotation_irk, minimum_rotation_time, maximum_rotation_time); + hci::LeAddressManager::AddressPolicy address_policy, hci::AddressWithType fixed_address, + hci::Octet16 rotation_irk, std::chrono::milliseconds minimum_rotation_time, + std::chrono::milliseconds maximum_rotation_time) { + acl_manager_->SetPrivacyPolicyForInitiatorAddressForTest(address_policy, fixed_address, + rotation_irk, minimum_rotation_time, + maximum_rotation_time); } -void SecurityManagerImpl::RegisterCallbackListener(ISecurityManagerListener* listener, os::Handler* handler) { +void SecurityManagerImpl::RegisterCallbackListener(ISecurityManagerListener* listener, + os::Handler* handler) { for (auto it = listeners_.begin(); it != listeners_.end(); ++it) { if (it->first == listener) { log::fatal("Listener has already been registered!"); @@ -237,29 +231,32 @@ void SecurityManagerImpl::UnregisterCallbackListener(ISecurityManagerListener* l void SecurityManagerImpl::NotifyDeviceBonded(hci::AddressWithType device) { for (auto& iter : listeners_) { - iter.second->Post(common::Bind(&ISecurityManagerListener::OnDeviceBonded, common::Unretained(iter.first), device)); + iter.second->Post(common::Bind(&ISecurityManagerListener::OnDeviceBonded, + common::Unretained(iter.first), device)); } } -void SecurityManagerImpl::NotifyDeviceBondFailed(hci::AddressWithType device, PairingFailure status) { +void SecurityManagerImpl::NotifyDeviceBondFailed(hci::AddressWithType device, + PairingFailure status) { for (auto& iter : listeners_) { - iter.second->Post( - common::Bind(&ISecurityManagerListener::OnDeviceBondFailed, common::Unretained(iter.first), device, status)); + iter.second->Post(common::Bind(&ISecurityManagerListener::OnDeviceBondFailed, + common::Unretained(iter.first), device, status)); } } void SecurityManagerImpl::NotifyDeviceUnbonded(hci::AddressWithType device) { for (auto& iter : listeners_) { - iter.second->Post( - common::Bind(&ISecurityManagerListener::OnDeviceUnbonded, common::Unretained(iter.first), device)); + iter.second->Post(common::Bind(&ISecurityManagerListener::OnDeviceUnbonded, + common::Unretained(iter.first), device)); } acl_manager_->CancelLeConnect(device); } -void SecurityManagerImpl::NotifyEncryptionStateChanged(hci::EncryptionChangeView encryption_change_view) { +void SecurityManagerImpl::NotifyEncryptionStateChanged( + hci::EncryptionChangeView encryption_change_view) { for (auto& iter : listeners_) { - iter.second->Post(common::Bind(&ISecurityManagerListener::OnEncryptionStateChanged, common::Unretained(iter.first), - encryption_change_view)); + iter.second->Post(common::Bind(&ISecurityManagerListener::OnEncryptionStateChanged, + common::Unretained(iter.first), encryption_change_view)); } } @@ -272,27 +269,22 @@ void SecurityManagerImpl::HandleEvent(T packet) { auto bd_addr = packet.GetBdAddr(); auto event_code = packet.GetEventCode(); - if (event_code != hci::EventCode::LINK_KEY_REQUEST && event_code != hci::EventCode::PIN_CODE_REQUEST && + if (event_code != hci::EventCode::LINK_KEY_REQUEST && + event_code != hci::EventCode::PIN_CODE_REQUEST && event_code != hci::EventCode::IO_CAPABILITY_RESPONSE) { - log::error( - "No classic pairing handler for device '{}' ready for command {}", - bd_addr, - hci::EventCodeText(event_code)); + log::error("No classic pairing handler for device '{}' ready for command {}", bd_addr, + hci::EventCodeText(event_code)); return; } auto device = storage_module_->GetDeviceByClassicMacAddress(bd_addr); - auto record = - security_database_.FindOrCreate(hci::AddressWithType{bd_addr, hci::AddressType::PUBLIC_DEVICE_ADDRESS}); + auto record = security_database_.FindOrCreate( + hci::AddressWithType{bd_addr, hci::AddressType::PUBLIC_DEVICE_ADDRESS}); log::warn("Dispatch #2"); - DispatchPairingHandler( - record, - false, - this->local_io_capability_, - this->local_authentication_requirements_, - pairing::OobData(), - pairing::OobData()); + DispatchPairingHandler(record, false, this->local_io_capability_, + this->local_authentication_requirements_, pairing::OobData(), + pairing::OobData()); entry = pairing_handler_map_.find(bd_addr); } entry->second->OnReceive(packet); @@ -363,13 +355,16 @@ void SecurityManagerImpl::OnConnectionClosed(hci::Address address) { log::info("Cancelling pairing handler for '{}'", address); entry->second->Cancel(); } - auto record = security_database_.FindOrCreate(hci::AddressWithType(address, hci::AddressType::PUBLIC_DEVICE_ADDRESS)); + auto record = security_database_.FindOrCreate( + hci::AddressWithType(address, hci::AddressType::PUBLIC_DEVICE_ADDRESS)); if (record->IsTemporary()) { - security_database_.Remove(hci::AddressWithType(address, hci::AddressType::PUBLIC_DEVICE_ADDRESS)); + security_database_.Remove( + hci::AddressWithType(address, hci::AddressType::PUBLIC_DEVICE_ADDRESS)); } if (this->facade_disconnect_callback_) { this->security_handler_->Call( - *this->facade_disconnect_callback_, hci::AddressWithType(address, hci::AddressType::PUBLIC_DEVICE_ADDRESS)); + *this->facade_disconnect_callback_, + hci::AddressWithType(address, hci::AddressType::PUBLIC_DEVICE_ADDRESS)); } } @@ -377,13 +372,15 @@ void SecurityManagerImpl::OnHciLeEvent(hci::LeMetaEventView event) { hci::SubeventCode code = event.GetSubeventCode(); if (code == hci::SubeventCode::LONG_TERM_KEY_REQUEST) { - hci::LeLongTermKeyRequestView le_long_term_key_request_view = hci::LeLongTermKeyRequestView::Create(event); + hci::LeLongTermKeyRequestView le_long_term_key_request_view = + hci::LeLongTermKeyRequestView::Create(event); if (!le_long_term_key_request_view.IsValid()) { log::error("Invalid LeLongTermKeyRequestView packet received"); return; } - if (le_long_term_key_request_view.GetConnectionHandle() == pending_le_pairing_.connection_handle_) { + if (le_long_term_key_request_view.GetConnectionHandle() == + pending_le_pairing_.connection_handle_) { pending_le_pairing_.handler_->OnHciLeEvent(event); return; } @@ -397,29 +394,34 @@ void SecurityManagerImpl::OnHciLeEvent(hci::LeMetaEventView event) { log::error("Unhandled HCI LE security event, code {}", hci::SubeventCodeText(code)); } -void SecurityManagerImpl::OnPairingPromptAccepted(const bluetooth::hci::AddressWithType& address, bool confirmed) { +void SecurityManagerImpl::OnPairingPromptAccepted(const bluetooth::hci::AddressWithType& address, + bool confirmed) { auto entry = pairing_handler_map_.find(address.GetAddress()); if (entry != pairing_handler_map_.end()) { entry->second->OnPairingPromptAccepted(address, confirmed); } else { if (pending_le_pairing_.address_ == address) { - pending_le_pairing_.handler_->OnUiAction(PairingEvent::UI_ACTION_TYPE::PAIRING_ACCEPTED, confirmed); + pending_le_pairing_.handler_->OnUiAction(PairingEvent::UI_ACTION_TYPE::PAIRING_ACCEPTED, + confirmed); } } } -void SecurityManagerImpl::OnConfirmYesNo(const bluetooth::hci::AddressWithType& address, bool confirmed) { +void SecurityManagerImpl::OnConfirmYesNo(const bluetooth::hci::AddressWithType& address, + bool confirmed) { auto entry = pairing_handler_map_.find(address.GetAddress()); if (entry != pairing_handler_map_.end()) { entry->second->OnConfirmYesNo(address, confirmed); } else { if (pending_le_pairing_.address_ == address) { - pending_le_pairing_.handler_->OnUiAction(PairingEvent::UI_ACTION_TYPE::CONFIRM_YESNO, confirmed); + pending_le_pairing_.handler_->OnUiAction(PairingEvent::UI_ACTION_TYPE::CONFIRM_YESNO, + confirmed); } } } -void SecurityManagerImpl::OnPasskeyEntry(const bluetooth::hci::AddressWithType& address, uint32_t passkey) { +void SecurityManagerImpl::OnPasskeyEntry(const bluetooth::hci::AddressWithType& address, + uint32_t passkey) { auto entry = pairing_handler_map_.find(address.GetAddress()); if (entry != pairing_handler_map_.end()) { entry->second->OnPasskeyEntry(address, passkey); @@ -430,7 +432,8 @@ void SecurityManagerImpl::OnPasskeyEntry(const bluetooth::hci::AddressWithType& } } -void SecurityManagerImpl::OnPinEntry(const bluetooth::hci::AddressWithType& address, std::vector pin) { +void SecurityManagerImpl::OnPinEntry(const bluetooth::hci::AddressWithType& address, + std::vector pin) { auto entry = pairing_handler_map_.find(address.GetAddress()); if (entry != pairing_handler_map_.end()) { log::info("PIN for {}", address); @@ -441,7 +444,8 @@ void SecurityManagerImpl::OnPinEntry(const bluetooth::hci::AddressWithType& addr } } -void SecurityManagerImpl::OnPairingHandlerComplete(hci::Address address, PairingResultOrFailure status) { +void SecurityManagerImpl::OnPairingHandlerComplete(hci::Address address, + PairingResultOrFailure status) { auto entry = pairing_handler_map_.find(address); if (entry != pairing_handler_map_.end()) { pairing_handler_map_.erase(entry); @@ -464,11 +468,10 @@ void SecurityManagerImpl::OnPairingHandlerComplete(hci::Address address, Pairing } void SecurityManagerImpl::OnL2capRegistrationCompleteLe( - l2cap::le::FixedChannelManager::RegistrationResult result, - [[maybe_unused]] std::unique_ptr le_smp_service) { - log::assert_that( - result == bluetooth::l2cap::le::FixedChannelManager::RegistrationResult::SUCCESS, - "Failed to register to LE SMP Fixed Channel Service"); + l2cap::le::FixedChannelManager::RegistrationResult result, + [[maybe_unused]] std::unique_ptr le_smp_service) { + log::assert_that(result == bluetooth::l2cap::le::FixedChannelManager::RegistrationResult::SUCCESS, + "Failed to register to LE SMP Fixed Channel Service"); } LeFixedChannelEntry* SecurityManagerImpl::FindStoredLeChannel(const hci::AddressWithType& device) { @@ -536,64 +539,71 @@ void SecurityManagerImpl::OnSmpCommandLe(hci::AddressWithType device) { auto& enqueue_buffer = stored_chan->enqueue_buffer_; std::optional remote_oob_data = std::nullopt; - if (remote_oob_data_address_.has_value() && remote_oob_data_address_.value() == channel->GetDevice()) - remote_oob_data = InitialInformations::out_of_band_data{.le_sc_c = remote_oob_data_le_sc_c_.value(), - .le_sc_r = remote_oob_data_le_sc_r_.value()}; + if (remote_oob_data_address_.has_value() && + remote_oob_data_address_.value() == channel->GetDevice()) { + remote_oob_data = + InitialInformations::out_of_band_data{.le_sc_c = remote_oob_data_le_sc_c_.value(), + .le_sc_r = remote_oob_data_le_sc_r_.value()}; + } - // TODO: this doesn't have to be a unique ptr, if there is a way to properly std::move it into place where it's - // stored + // TODO: this doesn't have to be a unique ptr, if there is a way to properly std::move it into + // place where it's stored pending_le_pairing_.connection_handle_ = channel->GetLinkOptions()->GetHandle(); InitialInformations initial_informations{ - .my_role = my_role, - .my_connection_address = channel->GetLinkOptions()->GetLocalAddress(), - .my_identity_address = local_identity_address_, - .my_identity_resolving_key = local_identity_resolving_key_, - /*TODO: properly obtain capabilities from device-specific storage*/ - .myPairingCapabilities = {.io_capability = local_le_io_capability_, - .oob_data_flag = local_le_oob_data_present_, - .auth_req = local_le_auth_req_, - .maximum_encryption_key_size = local_maximum_encryption_key_size_, - .initiator_key_distribution = 0x07, - .responder_key_distribution = 0x07}, - .remotely_initiated = true, - .connection_handle = channel->GetLinkOptions()->GetHandle(), - .remote_connection_address = channel->GetDevice(), - .remote_name = "TODO: grab proper device name in sec mgr", - /* contains pairing request, if the pairing was remotely initiated */ - .pairing_request = pairing_request, - .remote_oob_data = remote_oob_data, - .my_oob_data = local_le_oob_data_, - /* Used by Pairing Handler to present user with requests*/ - .user_interface = user_interface_, - .user_interface_handler = user_interface_handler_, - - /* HCI interface to use */ - .le_security_interface = hci_security_interface_le_, - .proper_l2cap_interface = enqueue_buffer.get(), - .l2cap_handler = security_handler_, - /* Callback to execute once the Pairing process is finished */ - // TODO: make it an common::OnceCallback ? - .OnPairingFinished = std::bind(&SecurityManagerImpl::OnPairingFinished, this, std::placeholders::_1), + .my_role = my_role, + .my_connection_address = channel->GetLinkOptions()->GetLocalAddress(), + .my_identity_address = local_identity_address_, + .my_identity_resolving_key = local_identity_resolving_key_, + /*TODO: properly obtain capabilities from device-specific storage*/ + .myPairingCapabilities = {.io_capability = local_le_io_capability_, + .oob_data_flag = local_le_oob_data_present_, + .auth_req = local_le_auth_req_, + .maximum_encryption_key_size = + local_maximum_encryption_key_size_, + .initiator_key_distribution = 0x07, + .responder_key_distribution = 0x07}, + .remotely_initiated = true, + .connection_handle = channel->GetLinkOptions()->GetHandle(), + .remote_connection_address = channel->GetDevice(), + .remote_name = "TODO: grab proper device name in sec mgr", + /* contains pairing request, if the pairing was remotely initiated */ + .pairing_request = pairing_request, + .remote_oob_data = remote_oob_data, + .my_oob_data = local_le_oob_data_, + /* Used by Pairing Handler to present user with requests*/ + .user_interface = user_interface_, + .user_interface_handler = user_interface_handler_, + + /* HCI interface to use */ + .le_security_interface = hci_security_interface_le_, + .proper_l2cap_interface = enqueue_buffer.get(), + .l2cap_handler = security_handler_, + /* Callback to execute once the Pairing process is finished */ + // TODO: make it a common::OnceCallback ? + .OnPairingFinished = + std::bind(&SecurityManagerImpl::OnPairingFinished, this, std::placeholders::_1), }; pending_le_pairing_.address_ = device; - pending_le_pairing_.handler_ = std::make_unique(PairingHandlerLe::PHASE1, initial_informations); + pending_le_pairing_.handler_ = + std::make_unique(PairingHandlerLe::PHASE1, initial_informations); } } -void SecurityManagerImpl::OnConnectionOpenLe(std::unique_ptr channel_param) { - auto enqueue_buffer_temp = - std::make_unique>(channel_param->GetQueueUpEnd()); +void SecurityManagerImpl::OnConnectionOpenLe( + std::unique_ptr channel_param) { + auto enqueue_buffer_temp = std::make_unique>( + channel_param->GetQueueUpEnd()); all_channels_.push_back({std::move(channel_param), std::move(enqueue_buffer_temp)}); auto& stored_channel = all_channels_.back(); auto& channel = stored_channel.channel_; channel->RegisterOnCloseCallback( - security_handler_, - common::BindOnce(&SecurityManagerImpl::OnConnectionClosedLe, common::Unretained(this), channel->GetDevice())); + security_handler_, common::BindOnce(&SecurityManagerImpl::OnConnectionClosedLe, + common::Unretained(this), channel->GetDevice())); channel->GetQueueUpEnd()->RegisterDequeue( - security_handler_, - common::Bind(&SecurityManagerImpl::OnSmpCommandLe, common::Unretained(this), channel->GetDevice())); + security_handler_, common::Bind(&SecurityManagerImpl::OnSmpCommandLe, + common::Unretained(this), channel->GetDevice())); if (pending_le_pairing_.address_ != channel->GetDevice()) { return; @@ -609,49 +619,57 @@ void SecurityManagerImpl::ConnectionIsReadyStartPairing(LeFixedChannelEntry* sto stored_channel->channel_->Acquire(); std::optional remote_oob_data = std::nullopt; - if (remote_oob_data_address_.has_value() && remote_oob_data_address_.value() == channel->GetDevice()) - remote_oob_data = InitialInformations::out_of_band_data{.le_sc_c = remote_oob_data_le_sc_c_.value(), - .le_sc_r = remote_oob_data_le_sc_r_.value()}; + if (remote_oob_data_address_.has_value() && + remote_oob_data_address_.value() == channel->GetDevice()) { + remote_oob_data = + InitialInformations::out_of_band_data{.le_sc_c = remote_oob_data_le_sc_c_.value(), + .le_sc_r = remote_oob_data_le_sc_r_.value()}; + } - // TODO: this doesn't have to be a unique ptr, if there is a way to properly std::move it into place where it's stored + // TODO: this doesn't have to be a unique ptr, if there is a way to properly std::move it into + // place where it's stored pending_le_pairing_.connection_handle_ = channel->GetLinkOptions()->GetHandle(); InitialInformations initial_informations{ - .my_role = channel->GetLinkOptions()->GetRole(), - .my_connection_address = channel->GetLinkOptions()->GetLocalAddress(), - .my_identity_address = local_identity_address_, - .my_identity_resolving_key = local_identity_resolving_key_, - /*TODO: properly obtain capabilities from device-specific storage*/ - .myPairingCapabilities = {.io_capability = local_le_io_capability_, - .oob_data_flag = local_le_oob_data_present_, - .auth_req = local_le_auth_req_, - .maximum_encryption_key_size = local_maximum_encryption_key_size_, - .initiator_key_distribution = 0x07, - .responder_key_distribution = 0x07}, - .remotely_initiated = false, - .connection_handle = channel->GetLinkOptions()->GetHandle(), - .remote_connection_address = channel->GetDevice(), - .remote_name = "TODO: grab proper device name in sec mgr", - /* contains pairing request, if the pairing was remotely initiated */ - .pairing_request = std::nullopt, // TODO: handle remotely initiated pairing in SecurityManager properly - .remote_oob_data = remote_oob_data, - .my_oob_data = local_le_oob_data_, - /* Used by Pairing Handler to present user with requests*/ - .user_interface = user_interface_, - .user_interface_handler = user_interface_handler_, - - /* HCI interface to use */ - .le_security_interface = hci_security_interface_le_, - .proper_l2cap_interface = enqueue_buffer.get(), - .l2cap_handler = security_handler_, - /* Callback to execute once the Pairing process is finished */ - // TODO: make it an common::OnceCallback ? - .OnPairingFinished = std::bind(&SecurityManagerImpl::OnPairingFinished, this, std::placeholders::_1), + .my_role = channel->GetLinkOptions()->GetRole(), + .my_connection_address = channel->GetLinkOptions()->GetLocalAddress(), + .my_identity_address = local_identity_address_, + .my_identity_resolving_key = local_identity_resolving_key_, + /*TODO: properly obtain capabilities from device-specific storage*/ + .myPairingCapabilities = {.io_capability = local_le_io_capability_, + .oob_data_flag = local_le_oob_data_present_, + .auth_req = local_le_auth_req_, + .maximum_encryption_key_size = + local_maximum_encryption_key_size_, + .initiator_key_distribution = 0x07, + .responder_key_distribution = 0x07}, + .remotely_initiated = false, + .connection_handle = channel->GetLinkOptions()->GetHandle(), + .remote_connection_address = channel->GetDevice(), + .remote_name = "TODO: grab proper device name in sec mgr", + /* contains pairing request, if the pairing was remotely initiated */ + .pairing_request = std::nullopt, // TODO: handle remotely initiated pairing in + // SecurityManager properly + .remote_oob_data = remote_oob_data, + .my_oob_data = local_le_oob_data_, + /* Used by Pairing Handler to present user with requests*/ + .user_interface = user_interface_, + .user_interface_handler = user_interface_handler_, + + /* HCI interface to use */ + .le_security_interface = hci_security_interface_le_, + .proper_l2cap_interface = enqueue_buffer.get(), + .l2cap_handler = security_handler_, + /* Callback to execute once the Pairing process is finished */ + // TODO: make it a common::OnceCallback ? + .OnPairingFinished = + std::bind(&SecurityManagerImpl::OnPairingFinished, this, std::placeholders::_1), }; - pending_le_pairing_.handler_ = std::make_unique(PairingHandlerLe::PHASE1, initial_informations); + pending_le_pairing_.handler_ = + std::make_unique(PairingHandlerLe::PHASE1, initial_informations); } -void SecurityManagerImpl::OnConnectionClosedLe( - hci::AddressWithType address, hci::ErrorCode /* error_code */) { +void SecurityManagerImpl::OnConnectionClosedLe(hci::AddressWithType address, + hci::ErrorCode /* error_code */) { if (pending_le_pairing_.address_ != address) { LeFixedChannelEntry* stored_chan = FindStoredLeChannel(address); if (!stored_chan) { @@ -667,30 +685,31 @@ void SecurityManagerImpl::OnConnectionClosedLe( NotifyDeviceBondFailed(address, PairingFailure("Connection closed")); } -void SecurityManagerImpl::OnConnectionFailureLe(bluetooth::l2cap::le::FixedChannelManager::ConnectionResult result) { +void SecurityManagerImpl::OnConnectionFailureLe( + bluetooth::l2cap::le::FixedChannelManager::ConnectionResult result) { if (result.connection_result_code == - bluetooth::l2cap::le::FixedChannelManager::ConnectionResultCode::FAIL_ALL_SERVICES_HAVE_CHANNEL) { + bluetooth::l2cap::le::FixedChannelManager::ConnectionResultCode:: + FAIL_ALL_SERVICES_HAVE_CHANNEL) { // TODO: already connected } // This callback is invoked only for devices we attempted to connect to. - NotifyDeviceBondFailed(pending_le_pairing_.address_, PairingFailure("Connection establishment failed")); -} - -SecurityManagerImpl::SecurityManagerImpl( - os::Handler* security_handler, - l2cap::le::L2capLeModule* l2cap_le_module, - channel::SecurityManagerChannel* security_manager_channel, - hci::HciLayer* hci_layer, - hci::AclManager* acl_manager, - hci::Controller* controller, - storage::StorageModule* storage_module, - neighbor::NameDbModule* name_db_module) + NotifyDeviceBondFailed(pending_le_pairing_.address_, + PairingFailure("Connection establishment failed")); +} + +SecurityManagerImpl::SecurityManagerImpl(os::Handler* security_handler, + l2cap::le::L2capLeModule* l2cap_le_module, + channel::SecurityManagerChannel* security_manager_channel, + hci::HciLayer* hci_layer, hci::AclManager* acl_manager, + hci::Controller* controller, + storage::StorageModule* storage_module, + neighbor::NameDbModule* name_db_module) : security_handler_(security_handler), l2cap_le_module_(l2cap_le_module), l2cap_manager_le_(l2cap_le_module_->GetFixedChannelManager()), - hci_security_interface_le_( - hci_layer->GetLeSecurityInterface(security_handler_->BindOn(this, &SecurityManagerImpl::OnHciLeEvent))), + hci_security_interface_le_(hci_layer->GetLeSecurityInterface( + security_handler_->BindOn(this, &SecurityManagerImpl::OnHciLeEvent))), security_manager_channel_(security_manager_channel), acl_manager_(acl_manager), controller_(controller), @@ -701,15 +720,17 @@ SecurityManagerImpl::SecurityManagerImpl( Init(); l2cap_manager_le_->RegisterService( - bluetooth::l2cap::kSmpCid, - common::BindOnce(&SecurityManagerImpl::OnL2capRegistrationCompleteLe, common::Unretained(this)), - common::Bind(&SecurityManagerImpl::OnConnectionOpenLe, common::Unretained(this)), security_handler_); + bluetooth::l2cap::kSmpCid, + common::BindOnce(&SecurityManagerImpl::OnL2capRegistrationCompleteLe, + common::Unretained(this)), + common::Bind(&SecurityManagerImpl::OnConnectionOpenLe, common::Unretained(this)), + security_handler_); } void SecurityManagerImpl::OnPairingFinished(security::PairingResultOrFailure pairing_result) { log::info( - "■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ Received " - "pairing result"); + "■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ Received " + "pairing result"); LeFixedChannelEntry* stored_chan = FindStoredLeChannel(pending_le_pairing_.address_); if (stored_chan) { @@ -719,9 +740,9 @@ void SecurityManagerImpl::OnPairingFinished(security::PairingResultOrFailure pai if (std::holds_alternative(pairing_result)) { PairingFailure failure = std::get(pairing_result); log::info( - "■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ failure " - "message: {}", - failure.message); + "■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ failure " + "message: {}", + failure.message); if (stored_chan) { NotifyDeviceBondFailed(stored_chan->channel_->GetDevice(), failure); } @@ -741,14 +762,16 @@ void SecurityManagerImpl::OnPairingFinished(security::PairingResultOrFailure pai record->remote_rand = result.distributed_keys.remote_rand; record->remote_irk = result.distributed_keys.remote_irk; record->remote_signature_key = result.distributed_keys.remote_signature_key; - if (result.distributed_keys.remote_link_key) + if (result.distributed_keys.remote_link_key) { record->SetLinkKey(*result.distributed_keys.remote_link_key, hci::KeyType::AUTHENTICATED_P256); + } security_database_.SaveRecordsToStorage(); NotifyDeviceBonded(result.connection_address); // We also notify bond complete using identity address. That's what old stack used to do. - if (result.distributed_keys.remote_identity_address) + if (result.distributed_keys.remote_identity_address) { NotifyDeviceBonded(*result.distributed_keys.remote_identity_address); + } security_handler_->CallOn(this, &SecurityManagerImpl::WipeLePairingHandler); } @@ -786,33 +809,33 @@ void SecurityManagerImpl::SetLeOobDataPresent(OobDataFlag data_present) { void SecurityManagerImpl::GetOutOfBandData(channel::SecurityCommandStatusCallback callback) { this->security_manager_channel_->SendCommand( - hci::ReadLocalOobDataBuilder::Create(), std::forward(callback)); + hci::ReadLocalOobDataBuilder::Create(), + std::forward(callback)); } -void SecurityManagerImpl::GetLeOutOfBandData( - std::array* confirmation_value, std::array* random_value) { +void SecurityManagerImpl::GetLeOutOfBandData(std::array* confirmation_value, + std::array* random_value) { local_le_oob_data_ = std::make_optional(PairingHandlerLe::GenerateOobData()); *confirmation_value = local_le_oob_data_.value().c; *random_value = local_le_oob_data_.value().r; } -void SecurityManagerImpl::SetOutOfBandData( - hci::AddressWithType remote_address, - std::array confirmation_value, - std::array random_value) { +void SecurityManagerImpl::SetOutOfBandData(hci::AddressWithType remote_address, + std::array confirmation_value, + std::array random_value) { remote_oob_data_address_ = remote_address; remote_oob_data_le_sc_c_ = confirmation_value; remote_oob_data_le_sc_r_ = random_value; } -void SecurityManagerImpl::SetAuthenticationRequirements(hci::AuthenticationRequirements authentication_requirements) { +void SecurityManagerImpl::SetAuthenticationRequirements( + hci::AuthenticationRequirements authentication_requirements) { this->local_authentication_requirements_ = authentication_requirements; } void SecurityManagerImpl::InternalEnforceSecurityPolicy( - hci::AddressWithType remote, - l2cap::classic::SecurityPolicy policy, - l2cap::classic::SecurityEnforcementInterface::ResultCallback result_callback) { + hci::AddressWithType remote, l2cap::classic::SecurityPolicy policy, + l2cap::classic::SecurityEnforcementInterface::ResultCallback result_callback) { if (IsSecurityRequirementSatisfied(remote, policy)) { // Notify client immediately if already satisfied std::move(result_callback)(true); @@ -828,7 +851,8 @@ void SecurityManagerImpl::InternalEnforceSecurityPolicy( case l2cap::classic::SecurityPolicy::BEST: case l2cap::classic::SecurityPolicy::AUTHENTICATED_ENCRYPTED_TRANSPORT: // Force MITM requirement locally - authentication_requirements = hci::AuthenticationRequirements::GENERAL_BONDING_MITM_PROTECTION; + authentication_requirements = + hci::AuthenticationRequirements::GENERAL_BONDING_MITM_PROTECTION; break; case l2cap::classic::SecurityPolicy::ENCRYPTED_TRANSPORT: authentication_requirements = hci::AuthenticationRequirements::GENERAL_BONDING; @@ -840,13 +864,9 @@ void SecurityManagerImpl::InternalEnforceSecurityPolicy( } log::warn("Dispatch #3"); - DispatchPairingHandler( - record, - true, - this->local_io_capability_, - std::as_const(authentication_requirements), - pairing::OobData(), - pairing::OobData()); + DispatchPairingHandler(record, true, this->local_io_capability_, + std::as_const(authentication_requirements), pairing::OobData(), + pairing::OobData()); } void SecurityManagerImpl::UpdateLinkSecurityCondition(hci::AddressWithType remote) { @@ -859,13 +879,13 @@ void SecurityManagerImpl::UpdateLinkSecurityCondition(hci::AddressWithType remot enforce_security_policy_callback_map_.erase(entry); } -bool SecurityManagerImpl::IsSecurityRequirementSatisfied( - hci::AddressWithType remote, l2cap::classic::SecurityPolicy policy) { +bool SecurityManagerImpl::IsSecurityRequirementSatisfied(hci::AddressWithType remote, + l2cap::classic::SecurityPolicy policy) { auto record = security_database_.FindOrCreate(remote); switch (policy) { case l2cap::classic::SecurityPolicy::BEST: case l2cap::classic::SecurityPolicy::AUTHENTICATED_ENCRYPTED_TRANSPORT: - return (record->IsPaired() && record->IsAuthenticated()); + return record->IsPaired() && record->IsAuthenticated(); case l2cap::classic::SecurityPolicy::ENCRYPTED_TRANSPORT: return record->IsPaired(); default: @@ -874,9 +894,8 @@ bool SecurityManagerImpl::IsSecurityRequirementSatisfied( } void SecurityManagerImpl::EnforceSecurityPolicy( - hci::AddressWithType remote, - l2cap::classic::SecurityPolicy policy, - l2cap::classic::SecurityEnforcementInterface::ResultCallback result_callback) { + hci::AddressWithType remote, l2cap::classic::SecurityPolicy policy, + l2cap::classic::SecurityEnforcementInterface::ResultCallback result_callback) { log::info("Attempting to enforce security policy"); auto record = security_database_.FindOrCreate(remote); if (!record->IsPairing()) { @@ -885,9 +904,8 @@ void SecurityManagerImpl::EnforceSecurityPolicy( } void SecurityManagerImpl::EnforceLeSecurityPolicy( - hci::AddressWithType /* remote */, - l2cap::le::SecurityPolicy policy, - l2cap::le::SecurityEnforcementInterface::ResultCallback result_callback) { + hci::AddressWithType /* remote */, l2cap::le::SecurityPolicy policy, + l2cap::le::SecurityEnforcementInterface::ResultCallback result_callback) { bool result = false; // TODO(jpawlowski): Implement for LE switch (policy) { diff --git a/system/gd/security/internal/security_manager_impl.h b/system/gd/security/internal/security_manager_impl.h index 97e5957bfa6..e5a9cb81c64 100644 --- a/system/gd/security/internal/security_manager_impl.h +++ b/system/gd/security/internal/security_manager_impl.h @@ -45,7 +45,7 @@ class ISecurityManagerListener; static constexpr hci::IoCapability kDefaultIoCapability = hci::IoCapability::DISPLAY_YES_NO; static constexpr hci::AuthenticationRequirements kDefaultAuthenticationRequirements = - hci::AuthenticationRequirements::GENERAL_BONDING; + hci::AuthenticationRequirements::GENERAL_BONDING; namespace internal { @@ -57,20 +57,17 @@ struct LeFixedChannelEntry { }; class SecurityManagerImpl : public channel::ISecurityManagerChannelListener, public UICallbacks { - public: - explicit SecurityManagerImpl( - os::Handler* security_handler, - l2cap::le::L2capLeModule* l2cap_le_module, - channel::SecurityManagerChannel* security_manager_channel, - hci::HciLayer* hci_layer, - hci::AclManager* acl_manager, - hci::Controller* controller, - storage::StorageModule* storage_module, - neighbor::NameDbModule* name_db_module); +public: + explicit SecurityManagerImpl(os::Handler* security_handler, + l2cap::le::L2capLeModule* l2cap_le_module, + channel::SecurityManagerChannel* security_manager_channel, + hci::HciLayer* hci_layer, hci::AclManager* acl_manager, + hci::Controller* controller, storage::StorageModule* storage_module, + neighbor::NameDbModule* name_db_module); ~SecurityManagerImpl() { - /* L2CAP layer doesn't guarantee to send the registered OnCloseCallback during shutdown. Cleanup the remaining - * queues to prevent crashes */ + /* L2CAP layer doesn't guarantee to send the registered OnCloseCallback during shutdown. Cleanup + * the remaining queues to prevent crashes */ for (auto& stored_chan : all_channels_) { stored_chan.channel_->GetQueueUpEnd()->UnregisterDequeue(); stored_chan.enqueue_buffer_.reset(); @@ -100,8 +97,8 @@ class SecurityManagerImpl : public channel::ISecurityManagerChannelListener, pub * @param remote_p192_oob_data P192 data given to the stack * @param remote_p256_oob_data P256 data given to the stack */ - void CreateBondOutOfBand( - hci::AddressWithType address, pairing::OobData remote_p192_oob_data, pairing::OobData remote_p256_oob_data); + void CreateBondOutOfBand(hci::AddressWithType address, pairing::OobData remote_p192_oob_data, + pairing::OobData remote_p256_oob_data); /** * Initiates bond over Low Energy transport with device, if not bonded yet. @@ -139,12 +136,11 @@ class SecurityManagerImpl : public channel::ISecurityManagerChannelListener, pub /** * Specify the initiator address policy used for LE transport. Can only be called once. */ - void SetLeInitiatorAddressPolicyForTest( - hci::LeAddressManager::AddressPolicy address_policy, - hci::AddressWithType fixed_address, - hci::Octet16 rotation_irk, - std::chrono::milliseconds minimum_rotation_time, - std::chrono::milliseconds maximum_rotation_time); + void SetLeInitiatorAddressPolicyForTest(hci::LeAddressManager::AddressPolicy address_policy, + hci::AddressWithType fixed_address, + hci::Octet16 rotation_irk, + std::chrono::milliseconds minimum_rotation_time, + std::chrono::milliseconds maximum_rotation_time); /** * Register to listen for callback events from SecurityManager @@ -183,10 +179,12 @@ class SecurityManagerImpl : public channel::ISecurityManagerChannelListener, pub void OnPairingHandlerComplete(hci::Address address, PairingResultOrFailure status); // UICallbacks implementation - void OnPairingPromptAccepted(const bluetooth::hci::AddressWithType& address, bool confirmed) override; + void OnPairingPromptAccepted(const bluetooth::hci::AddressWithType& address, + bool confirmed) override; void OnConfirmYesNo(const bluetooth::hci::AddressWithType& address, bool confirmed) override; void OnPasskeyEntry(const bluetooth::hci::AddressWithType& address, uint32_t passkey) override; - void OnPinEntry(const bluetooth::hci::AddressWithType& address, std::vector pin) override; + void OnPinEntry(const bluetooth::hci::AddressWithType& address, + std::vector pin) override; // Facade Configuration API functions using FacadeDisconnectCallback = common::Callback; @@ -198,17 +196,20 @@ class SecurityManagerImpl : public channel::ISecurityManagerChannelListener, pub void SetLeAuthRequirements(uint8_t auth_req); void SetLeMaximumEncryptionKeySize(uint8_t maximum_encryption_key_size); void SetLeOobDataPresent(OobDataFlag data_present); - void GetLeOutOfBandData(std::array* confirmation_value, std::array* random_value); - void SetOutOfBandData( - hci::AddressWithType remote_address, - std::array confirmation_value, - std::array random_value); - - void EnforceSecurityPolicy(hci::AddressWithType remote, l2cap::classic::SecurityPolicy policy, - l2cap::classic::SecurityEnforcementInterface::ResultCallback result_callback); - void EnforceLeSecurityPolicy(hci::AddressWithType remote, l2cap::le::SecurityPolicy policy, - l2cap::le::SecurityEnforcementInterface::ResultCallback result_callback); - protected: + void GetLeOutOfBandData(std::array* confirmation_value, + std::array* random_value); + void SetOutOfBandData(hci::AddressWithType remote_address, + std::array confirmation_value, + std::array random_value); + + void EnforceSecurityPolicy( + hci::AddressWithType remote, l2cap::classic::SecurityPolicy policy, + l2cap::classic::SecurityEnforcementInterface::ResultCallback result_callback); + void EnforceLeSecurityPolicy( + hci::AddressWithType remote, l2cap::le::SecurityPolicy policy, + l2cap::le::SecurityEnforcementInterface::ResultCallback result_callback); + +protected: std::vector> listeners_; UI* user_interface_ = nullptr; os::Handler* user_interface_handler_ = nullptr; @@ -218,19 +219,18 @@ class SecurityManagerImpl : public channel::ISecurityManagerChannelListener, pub void NotifyDeviceUnbonded(hci::AddressWithType device); void NotifyEncryptionStateChanged(hci::EncryptionChangeView encryption_change_view); - private: +private: template void HandleEvent(T packet); - void DispatchPairingHandler( - std::shared_ptr record, - bool locally_initiated, - hci::IoCapability io_capability, - hci::AuthenticationRequirements auth_requirements, - pairing::OobData remote_p192_oob_data_, - pairing::OobData remote_p256_oob_data_); - void OnL2capRegistrationCompleteLe(l2cap::le::FixedChannelManager::RegistrationResult result, - std::unique_ptr le_smp_service); + void DispatchPairingHandler(std::shared_ptr record, + bool locally_initiated, hci::IoCapability io_capability, + hci::AuthenticationRequirements auth_requirements, + pairing::OobData remote_p192_oob_data_, + pairing::OobData remote_p256_oob_data_); + void OnL2capRegistrationCompleteLe( + l2cap::le::FixedChannelManager::RegistrationResult result, + std::unique_ptr le_smp_service); void OnSmpCommandLe(hci::AddressWithType device); void OnConnectionOpenLe(std::unique_ptr channel); void OnConnectionClosedLe(hci::AddressWithType address, hci::ErrorCode error_code); @@ -241,11 +241,11 @@ class SecurityManagerImpl : public channel::ISecurityManagerChannelListener, pub LeFixedChannelEntry* FindStoredLeChannel(uint8_t connection_handle); bool EraseStoredLeChannel(const hci::AddressWithType& device); void InternalEnforceSecurityPolicy( - hci::AddressWithType remote, - l2cap::classic::SecurityPolicy policy, - l2cap::classic::SecurityEnforcementInterface::ResultCallback result_callback); + hci::AddressWithType remote, l2cap::classic::SecurityPolicy policy, + l2cap::classic::SecurityEnforcementInterface::ResultCallback result_callback); void UpdateLinkSecurityCondition(hci::AddressWithType remote); - bool IsSecurityRequirementSatisfied(hci::AddressWithType remote, l2cap::classic::SecurityPolicy policy); + bool IsSecurityRequirementSatisfied(hci::AddressWithType remote, + l2cap::classic::SecurityPolicy policy); void ConnectionIsReadyStartPairing(LeFixedChannelEntry* stored_channel); void WipeLePairingHandler(); @@ -262,7 +262,8 @@ class SecurityManagerImpl : public channel::ISecurityManagerChannelListener, pub neighbor::NameDbModule* name_db_module_; std::unordered_map> pairing_handler_map_; hci::IoCapability local_io_capability_ = kDefaultIoCapability; - hci::AuthenticationRequirements local_authentication_requirements_ = kDefaultAuthenticationRequirements; + hci::AuthenticationRequirements local_authentication_requirements_ = + kDefaultAuthenticationRequirements; security::IoCapability local_le_io_capability_ = security::IoCapability::KEYBOARD_DISPLAY; uint8_t local_le_auth_req_ = AuthReqMaskBondingFlag | AuthReqMaskMitm | AuthReqMaskSc; uint8_t local_maximum_encryption_key_size_ = 0x10; @@ -279,7 +280,8 @@ class SecurityManagerImpl : public channel::ISecurityManagerChannelListener, pub l2cap::classic::SecurityPolicy policy_; l2cap::classic::SecurityEnforcementInterface::ResultCallback callback_; }; - std::unordered_map enforce_security_policy_callback_map_; + std::unordered_map + enforce_security_policy_callback_map_; struct { hci::AddressWithType address_; diff --git a/system/gd/security/l2cap_security_module_interface.cc b/system/gd/security/l2cap_security_module_interface.cc index 939d06b5f84..ce28388c398 100644 --- a/system/gd/security/l2cap_security_module_interface.cc +++ b/system/gd/security/l2cap_security_module_interface.cc @@ -14,30 +14,35 @@ * limitations under the License. */ #include "security/l2cap_security_module_interface.h" + #include "common/bind.h" namespace bluetooth { namespace security { -L2capSecurityModuleInterface::L2capSecurityModuleInterface(internal::SecurityManagerImpl* security_manager_impl, - os::Handler* security_handler) +L2capSecurityModuleInterface::L2capSecurityModuleInterface( + internal::SecurityManagerImpl* security_manager_impl, os::Handler* security_handler) : security_manager_impl_(security_manager_impl), security_handler_(security_handler) {} void L2capSecurityModuleInterface::Enforce( - hci::AddressWithType remote, l2cap::classic::SecurityPolicy policy, - l2cap::classic::SecurityEnforcementInterface::ResultCallback result_callback) { + hci::AddressWithType remote, l2cap::classic::SecurityPolicy policy, + l2cap::classic::SecurityEnforcementInterface::ResultCallback result_callback) { this->security_handler_->Post(common::BindOnce( - &internal::SecurityManagerImpl::EnforceSecurityPolicy, common::Unretained(security_manager_impl_), - std::forward(remote), std::forward(policy), - std::forward(result_callback))); + &internal::SecurityManagerImpl::EnforceSecurityPolicy, + common::Unretained(security_manager_impl_), std::forward(remote), + std::forward(policy), + std::forward( + result_callback))); } -void L2capSecurityModuleInterface::Enforce(hci::AddressWithType remote, l2cap::le::SecurityPolicy policy, - l2cap::le::SecurityEnforcementInterface::ResultCallback result_callback) { +void L2capSecurityModuleInterface::Enforce( + hci::AddressWithType remote, l2cap::le::SecurityPolicy policy, + l2cap::le::SecurityEnforcementInterface::ResultCallback result_callback) { this->security_handler_->Post(common::BindOnce( - &internal::SecurityManagerImpl::EnforceLeSecurityPolicy, common::Unretained(security_manager_impl_), - std::forward(remote), std::forward(policy), - std::forward(result_callback))); + &internal::SecurityManagerImpl::EnforceLeSecurityPolicy, + common::Unretained(security_manager_impl_), std::forward(remote), + std::forward(policy), + std::forward(result_callback))); } } // namespace security diff --git a/system/gd/security/l2cap_security_module_interface.h b/system/gd/security/l2cap_security_module_interface.h index 9a8fc8e9721..a199c22890f 100644 --- a/system/gd/security/l2cap_security_module_interface.h +++ b/system/gd/security/l2cap_security_module_interface.h @@ -24,14 +24,16 @@ namespace bluetooth { namespace security { class L2capSecurityModuleInterface : public l2cap::classic::SecurityEnforcementInterface, public l2cap::le::SecurityEnforcementInterface { - public: - L2capSecurityModuleInterface(internal::SecurityManagerImpl* security_manager_impl, os::Handler* security_handler); - void Enforce(hci::AddressWithType remote, l2cap::classic::SecurityPolicy policy, - l2cap::classic::SecurityEnforcementInterface::ResultCallback result_callback) override; +public: + L2capSecurityModuleInterface(internal::SecurityManagerImpl* security_manager_impl, + os::Handler* security_handler); + void Enforce( + hci::AddressWithType remote, l2cap::classic::SecurityPolicy policy, + l2cap::classic::SecurityEnforcementInterface::ResultCallback result_callback) override; void Enforce(hci::AddressWithType remote, l2cap::le::SecurityPolicy policy, l2cap::le::SecurityEnforcementInterface::ResultCallback result_callback) override; - private: +private: internal::SecurityManagerImpl* security_manager_impl_; os::Handler* security_handler_ = nullptr; }; diff --git a/system/gd/security/pairing/classic_pairing_handler.cc b/system/gd/security/pairing/classic_pairing_handler.cc index 96cb7913039..a4a73909db5 100644 --- a/system/gd/security/pairing/classic_pairing_handler.cc +++ b/system/gd/security/pairing/classic_pairing_handler.cc @@ -26,8 +26,8 @@ namespace security { namespace pairing { void ClassicPairingHandler::NotifyUiDisplayYesNo(uint32_t numeric_value) { - log::assert_that( - user_interface_handler_ != nullptr, "assert failed: user_interface_handler_ != nullptr"); + log::assert_that(user_interface_handler_ != nullptr, + "assert failed: user_interface_handler_ != nullptr"); ConfirmationData data(*GetRecord()->GetPseudoAddress(), device_name_, numeric_value); data.SetRemoteIoCaps(remote_io_capability_); data.SetRemoteAuthReqs(remote_authentication_requirements_); @@ -36,8 +36,8 @@ void ClassicPairingHandler::NotifyUiDisplayYesNo(uint32_t numeric_value) { } void ClassicPairingHandler::NotifyUiDisplayYesNo() { - log::assert_that( - user_interface_handler_ != nullptr, "assert failed: user_interface_handler_ != nullptr"); + log::assert_that(user_interface_handler_ != nullptr, + "assert failed: user_interface_handler_ != nullptr"); ConfirmationData data(*GetRecord()->GetPseudoAddress(), device_name_); data.SetRemoteIoCaps(remote_io_capability_); data.SetRemoteAuthReqs(remote_authentication_requirements_); @@ -46,8 +46,8 @@ void ClassicPairingHandler::NotifyUiDisplayYesNo() { } void ClassicPairingHandler::NotifyUiDisplayPasskey(uint32_t passkey) { - log::assert_that( - user_interface_handler_ != nullptr, "assert failed: user_interface_handler_ != nullptr"); + log::assert_that(user_interface_handler_ != nullptr, + "assert failed: user_interface_handler_ != nullptr"); ConfirmationData data(*GetRecord()->GetPseudoAddress(), device_name_, passkey); data.SetRemoteIoCaps(remote_io_capability_); data.SetRemoteAuthReqs(remote_authentication_requirements_); @@ -56,8 +56,8 @@ void ClassicPairingHandler::NotifyUiDisplayPasskey(uint32_t passkey) { } void ClassicPairingHandler::NotifyUiDisplayPasskeyInput() { - log::assert_that( - user_interface_handler_ != nullptr, "assert failed: user_interface_handler_ != nullptr"); + log::assert_that(user_interface_handler_ != nullptr, + "assert failed: user_interface_handler_ != nullptr"); ConfirmationData data(*GetRecord()->GetPseudoAddress(), device_name_); data.SetRemoteIoCaps(remote_io_capability_); data.SetRemoteAuthReqs(remote_authentication_requirements_); @@ -66,8 +66,8 @@ void ClassicPairingHandler::NotifyUiDisplayPasskeyInput() { } void ClassicPairingHandler::NotifyUiDisplayPinCodeInput() { - log::assert_that( - user_interface_handler_ != nullptr, "assert failed: user_interface_handler_ != nullptr"); + log::assert_that(user_interface_handler_ != nullptr, + "assert failed: user_interface_handler_ != nullptr"); ConfirmationData data(*GetRecord()->GetPseudoAddress(), device_name_); data.SetRemoteIoCaps(remote_io_capability_); data.SetRemoteAuthReqs(remote_authentication_requirements_); @@ -76,47 +76,48 @@ void ClassicPairingHandler::NotifyUiDisplayPinCodeInput() { } void ClassicPairingHandler::NotifyUiDisplayCancel() { - log::assert_that( - user_interface_handler_ != nullptr, "assert failed: user_interface_handler_ != nullptr"); + log::assert_that(user_interface_handler_ != nullptr, + "assert failed: user_interface_handler_ != nullptr"); user_interface_handler_->CallOn(user_interface_, &UI::Cancel, *GetRecord()->GetPseudoAddress()); } void ClassicPairingHandler::OnPairingPromptAccepted( - const bluetooth::hci::AddressWithType& /* address */, bool /* confirmed */) { + const bluetooth::hci::AddressWithType& /* address */, bool /* confirmed */) { // NOTE: This is not used by Classic, only by LE log::fatal("This is not supported by Classic Pairing Handler, only LE"); } -void ClassicPairingHandler::OnConfirmYesNo( - const bluetooth::hci::AddressWithType& /* address */, bool confirmed) { +void ClassicPairingHandler::OnConfirmYesNo(const bluetooth::hci::AddressWithType& /* address */, + bool confirmed) { if (confirmed) { - GetChannel()->SendCommand( - hci::UserConfirmationRequestReplyBuilder::Create(GetRecord()->GetPseudoAddress()->GetAddress())); + GetChannel()->SendCommand(hci::UserConfirmationRequestReplyBuilder::Create( + GetRecord()->GetPseudoAddress()->GetAddress())); } else { - GetChannel()->SendCommand( - hci::UserConfirmationRequestNegativeReplyBuilder::Create(GetRecord()->GetPseudoAddress()->GetAddress())); + GetChannel()->SendCommand(hci::UserConfirmationRequestNegativeReplyBuilder::Create( + GetRecord()->GetPseudoAddress()->GetAddress())); } } -void ClassicPairingHandler::OnPasskeyEntry(const bluetooth::hci::AddressWithType& address, uint32_t passkey) { - GetChannel()->SendCommand(hci::UserPasskeyRequestReplyBuilder::Create(address.GetAddress(), passkey)); +void ClassicPairingHandler::OnPasskeyEntry(const bluetooth::hci::AddressWithType& address, + uint32_t passkey) { + GetChannel()->SendCommand( + hci::UserPasskeyRequestReplyBuilder::Create(address.GetAddress(), passkey)); } -void ClassicPairingHandler::OnPinEntry(const bluetooth::hci::AddressWithType& address, std::vector pin) { +void ClassicPairingHandler::OnPinEntry(const bluetooth::hci::AddressWithType& address, + std::vector pin) { std::array padded_pin; for (size_t i = 0; i < 16 && i < pin.size(); i++) { padded_pin[i] = pin[i]; } log::info("{}", address.GetAddress()); - GetChannel()->SendCommand(hci::PinCodeRequestReplyBuilder::Create(address.GetAddress(), pin.size(), padded_pin)); + GetChannel()->SendCommand( + hci::PinCodeRequestReplyBuilder::Create(address.GetAddress(), pin.size(), padded_pin)); } -void ClassicPairingHandler::Initiate( - bool locally_initiated, - hci::IoCapability io_capability, - hci::AuthenticationRequirements auth_requirements, - OobData remote_p192_oob_data, - OobData remote_p256_oob_data) { +void ClassicPairingHandler::Initiate(bool locally_initiated, hci::IoCapability io_capability, + hci::AuthenticationRequirements auth_requirements, + OobData remote_p192_oob_data, OobData remote_p256_oob_data) { log::info("Initiate"); locally_initiated_ = locally_initiated; local_io_capability_ = io_capability; @@ -167,7 +168,9 @@ void ClassicPairingHandler::OnNameRequestComplete(hci::Address address, bool /* } void ClassicPairingHandler::Cancel() { - if (is_cancelled_) return; + if (is_cancelled_) { + return; + } is_cancelled_ = true; PairingResultOrFailure result = PairingResult(); if (last_status_ != hci::ErrorCode::SUCCESS) { @@ -189,13 +192,13 @@ void ClassicPairingHandler::OnReceive(hci::CentralLinkKeyCompleteView packet) { void ClassicPairingHandler::OnReceive(hci::PinCodeRequestView packet) { log::assert_that(packet.IsValid(), "assert failed: packet.IsValid()"); log::info("Received: {}", hci::EventCodeText(packet.GetEventCode())); - log::assert_that( - GetRecord()->GetPseudoAddress()->GetAddress() == packet.GetBdAddr(), "Address mismatch"); + log::assert_that(GetRecord()->GetPseudoAddress()->GetAddress() == packet.GetBdAddr(), + "Address mismatch"); is_legacy_pin_code_ = true; GetNameDbModule()->ReadRemoteNameRequest( - GetRecord()->GetPseudoAddress()->GetAddress(), - common::BindOnce(&ClassicPairingHandler::OnNameRequestComplete, common::Unretained(this)), - security_handler_); + GetRecord()->GetPseudoAddress()->GetAddress(), + common::BindOnce(&ClassicPairingHandler::OnNameRequestComplete, common::Unretained(this)), + security_handler_); } void ClassicPairingHandler::OnReceive(hci::LinkKeyRequestView packet) { @@ -206,26 +209,26 @@ void ClassicPairingHandler::OnReceive(hci::LinkKeyRequestView packet) { } already_link_key_replied_ = true; log::info("Received: {}", hci::EventCodeText(packet.GetEventCode())); - log::assert_that( - GetRecord()->GetPseudoAddress()->GetAddress() == packet.GetBdAddr(), "Address mismatch"); + log::assert_that(GetRecord()->GetPseudoAddress()->GetAddress() == packet.GetBdAddr(), + "Address mismatch"); if (GetRecord()->IsPaired()) { log::info("Sending: LINK_KEY_REQUEST_REPLY"); this->GetChannel()->SendCommand(hci::LinkKeyRequestReplyBuilder::Create( - GetRecord()->GetPseudoAddress()->GetAddress(), GetRecord()->GetLinkKey())); + GetRecord()->GetPseudoAddress()->GetAddress(), GetRecord()->GetLinkKey())); last_status_ = hci::ErrorCode::SUCCESS; Cancel(); } else { log::info("Sending: LINK_KEY_REQUEST_NEGATIVE_REPLY"); - this->GetChannel()->SendCommand( - hci::LinkKeyRequestNegativeReplyBuilder::Create(GetRecord()->GetPseudoAddress()->GetAddress())); + this->GetChannel()->SendCommand(hci::LinkKeyRequestNegativeReplyBuilder::Create( + GetRecord()->GetPseudoAddress()->GetAddress())); } } void ClassicPairingHandler::OnReceive(hci::LinkKeyNotificationView packet) { log::assert_that(packet.IsValid(), "assert failed: packet.IsValid()"); log::info("Received: {}", hci::EventCodeText(packet.GetEventCode())); - log::assert_that( - GetRecord()->GetPseudoAddress()->GetAddress() == packet.GetBdAddr(), "Address mismatch"); + log::assert_that(GetRecord()->GetPseudoAddress()->GetAddress() == packet.GetBdAddr(), + "Address mismatch"); GetRecord()->SetLinkKey(packet.GetLinkKey(), packet.GetKeyType()); if (!has_gotten_name_response_) { link_key_notification_ = std::make_optional(packet); @@ -240,25 +243,26 @@ void ClassicPairingHandler::OnReceive(hci::LinkKeyNotificationView packet) { void ClassicPairingHandler::OnReceive(hci::IoCapabilityRequestView packet) { log::assert_that(packet.IsValid(), "assert failed: packet.IsValid()"); log::info("Received: {}", hci::EventCodeText(packet.GetEventCode())); - log::assert_that( - GetRecord()->GetPseudoAddress()->GetAddress() == packet.GetBdAddr(), "Address mismatch"); + log::assert_that(GetRecord()->GetPseudoAddress()->GetAddress() == packet.GetBdAddr(), + "Address mismatch"); hci::IoCapability io_capability = local_io_capability_; hci::OobDataPresent oob_present = remote_oob_present_; hci::AuthenticationRequirements authentication_requirements = local_authentication_requirements_; auto reply_packet = hci::IoCapabilityRequestReplyBuilder::Create( - GetRecord()->GetPseudoAddress()->GetAddress(), io_capability, oob_present, authentication_requirements); + GetRecord()->GetPseudoAddress()->GetAddress(), io_capability, oob_present, + authentication_requirements); this->GetChannel()->SendCommand(std::move(reply_packet)); GetNameDbModule()->ReadRemoteNameRequest( - GetRecord()->GetPseudoAddress()->GetAddress(), - common::BindOnce(&ClassicPairingHandler::OnNameRequestComplete, common::Unretained(this)), - security_handler_); + GetRecord()->GetPseudoAddress()->GetAddress(), + common::BindOnce(&ClassicPairingHandler::OnNameRequestComplete, common::Unretained(this)), + security_handler_); } void ClassicPairingHandler::OnReceive(hci::IoCapabilityResponseView packet) { log::assert_that(packet.IsValid(), "assert failed: packet.IsValid()"); log::info("Received: {}", hci::EventCodeText(packet.GetEventCode())); - log::assert_that( - GetRecord()->GetPseudoAddress()->GetAddress() == packet.GetBdAddr(), "Address mismatch"); + log::assert_that(GetRecord()->GetPseudoAddress()->GetAddress() == packet.GetBdAddr(), + "Address mismatch"); remote_io_capability_ = packet.GetIoCapability(); remote_authentication_requirements_ = packet.GetAuthenticationRequirements(); @@ -266,32 +270,42 @@ void ClassicPairingHandler::OnReceive(hci::IoCapabilityResponseView packet) { switch (remote_authentication_requirements_) { case hci::AuthenticationRequirements::NO_BONDING: GetRecord()->SetIsEncryptionRequired( - local_authentication_requirements_ != hci::AuthenticationRequirements::NO_BONDING || - local_authentication_requirements_ != hci::AuthenticationRequirements::NO_BONDING_MITM_PROTECTION); + local_authentication_requirements_ != hci::AuthenticationRequirements::NO_BONDING || + local_authentication_requirements_ != + hci::AuthenticationRequirements::NO_BONDING_MITM_PROTECTION); GetRecord()->SetRequiresMitmProtection( - local_authentication_requirements_ == hci::AuthenticationRequirements::DEDICATED_BONDING_MITM_PROTECTION || - local_authentication_requirements_ == hci::AuthenticationRequirements::GENERAL_BONDING_MITM_PROTECTION || - local_authentication_requirements_ == hci::AuthenticationRequirements::NO_BONDING_MITM_PROTECTION); + local_authentication_requirements_ == + hci::AuthenticationRequirements::DEDICATED_BONDING_MITM_PROTECTION || + local_authentication_requirements_ == + hci::AuthenticationRequirements::GENERAL_BONDING_MITM_PROTECTION || + local_authentication_requirements_ == + hci::AuthenticationRequirements::NO_BONDING_MITM_PROTECTION); // TODO(optedoblivion): check for HID device (CoD) and if HID don't make temporary GetRecord()->SetIsTemporary( - local_authentication_requirements_ == hci::AuthenticationRequirements::NO_BONDING || - local_authentication_requirements_ == hci::AuthenticationRequirements::NO_BONDING_MITM_PROTECTION); + local_authentication_requirements_ == hci::AuthenticationRequirements::NO_BONDING || + local_authentication_requirements_ == + hci::AuthenticationRequirements::NO_BONDING_MITM_PROTECTION); break; case hci::AuthenticationRequirements::NO_BONDING_MITM_PROTECTION: GetRecord()->SetIsEncryptionRequired( - local_authentication_requirements_ != hci::AuthenticationRequirements::NO_BONDING || - local_authentication_requirements_ != hci::AuthenticationRequirements::NO_BONDING_MITM_PROTECTION); + local_authentication_requirements_ != hci::AuthenticationRequirements::NO_BONDING || + local_authentication_requirements_ != + hci::AuthenticationRequirements::NO_BONDING_MITM_PROTECTION); GetRecord()->SetRequiresMitmProtection(true); GetRecord()->SetIsTemporary( - local_authentication_requirements_ == hci::AuthenticationRequirements::NO_BONDING || - local_authentication_requirements_ == hci::AuthenticationRequirements::NO_BONDING_MITM_PROTECTION); + local_authentication_requirements_ == hci::AuthenticationRequirements::NO_BONDING || + local_authentication_requirements_ == + hci::AuthenticationRequirements::NO_BONDING_MITM_PROTECTION); break; case hci::AuthenticationRequirements::DEDICATED_BONDING: GetRecord()->SetIsEncryptionRequired(true); GetRecord()->SetRequiresMitmProtection( - local_authentication_requirements_ == hci::AuthenticationRequirements::DEDICATED_BONDING_MITM_PROTECTION || - local_authentication_requirements_ == hci::AuthenticationRequirements::GENERAL_BONDING_MITM_PROTECTION || - local_authentication_requirements_ == hci::AuthenticationRequirements::NO_BONDING_MITM_PROTECTION); + local_authentication_requirements_ == + hci::AuthenticationRequirements::DEDICATED_BONDING_MITM_PROTECTION || + local_authentication_requirements_ == + hci::AuthenticationRequirements::GENERAL_BONDING_MITM_PROTECTION || + local_authentication_requirements_ == + hci::AuthenticationRequirements::NO_BONDING_MITM_PROTECTION); break; case hci::AuthenticationRequirements::DEDICATED_BONDING_MITM_PROTECTION: GetRecord()->SetIsEncryptionRequired(true); @@ -300,9 +314,12 @@ void ClassicPairingHandler::OnReceive(hci::IoCapabilityResponseView packet) { case hci::AuthenticationRequirements::GENERAL_BONDING: GetRecord()->SetIsEncryptionRequired(true); GetRecord()->SetRequiresMitmProtection( - local_authentication_requirements_ == hci::AuthenticationRequirements::DEDICATED_BONDING_MITM_PROTECTION || - local_authentication_requirements_ == hci::AuthenticationRequirements::GENERAL_BONDING_MITM_PROTECTION || - local_authentication_requirements_ == hci::AuthenticationRequirements::NO_BONDING_MITM_PROTECTION); + local_authentication_requirements_ == + hci::AuthenticationRequirements::DEDICATED_BONDING_MITM_PROTECTION || + local_authentication_requirements_ == + hci::AuthenticationRequirements::GENERAL_BONDING_MITM_PROTECTION || + local_authentication_requirements_ == + hci::AuthenticationRequirements::NO_BONDING_MITM_PROTECTION); break; case hci::AuthenticationRequirements::GENERAL_BONDING_MITM_PROTECTION: GetRecord()->SetIsEncryptionRequired(true); @@ -323,8 +340,8 @@ void ClassicPairingHandler::OnReceive(hci::IoCapabilityResponseView packet) { void ClassicPairingHandler::OnReceive(hci::SimplePairingCompleteView packet) { log::assert_that(packet.IsValid(), "assert failed: packet.IsValid()"); log::info("Received: {}", hci::EventCodeText(packet.GetEventCode())); - log::assert_that( - GetRecord()->GetPseudoAddress()->GetAddress() == packet.GetBdAddr(), "Address mismatch"); + log::assert_that(GetRecord()->GetPseudoAddress()->GetAddress() == packet.GetBdAddr(), + "Address mismatch"); last_status_ = packet.GetStatus(); if (last_status_ != hci::ErrorCode::SUCCESS) { log::info("Failed SimplePairingComplete: {}", hci::ErrorCodeText(last_status_)); @@ -351,15 +368,15 @@ void ClassicPairingHandler::OnReceive(hci::EncryptionKeyRefreshCompleteView pack void ClassicPairingHandler::OnReceive(hci::RemoteOobDataRequestView packet) { log::assert_that(packet.IsValid(), "assert failed: packet.IsValid()"); log::info("Received: {}", hci::EventCodeText(packet.GetEventCode())); - log::assert_that( - GetRecord()->GetPseudoAddress()->GetAddress() == packet.GetBdAddr(), "Address mismatch"); + log::assert_that(GetRecord()->GetPseudoAddress()->GetAddress() == packet.GetBdAddr(), + "Address mismatch"); // Corev5.2 V2PF switch (remote_oob_present_) { case hci::OobDataPresent::NOT_PRESENT: log::warn("Missing remote OOB data"); - GetChannel()->SendCommand( - hci::RemoteOobDataRequestNegativeReplyBuilder::Create(GetRecord()->GetPseudoAddress()->GetAddress())); + GetChannel()->SendCommand(hci::RemoteOobDataRequestNegativeReplyBuilder::Create( + GetRecord()->GetPseudoAddress()->GetAddress())); break; case hci::OobDataPresent::P_192_PRESENT: log::info("P192 Present"); @@ -367,35 +384,28 @@ void ClassicPairingHandler::OnReceive(hci::RemoteOobDataRequestView packet) { secure_connections_enabled_ = false; if (secure_connections_enabled_) { GetChannel()->SendCommand(hci::RemoteOobExtendedDataRequestReplyBuilder::Create( - GetRecord()->GetPseudoAddress()->GetAddress(), - this->remote_p192_oob_data_.GetC(), - this->remote_p192_oob_data_.GetR(), - this->remote_p256_oob_data_.GetC(), - this->remote_p256_oob_data_.GetR())); + GetRecord()->GetPseudoAddress()->GetAddress(), this->remote_p192_oob_data_.GetC(), + this->remote_p192_oob_data_.GetR(), this->remote_p256_oob_data_.GetC(), + this->remote_p256_oob_data_.GetR())); } else { GetChannel()->SendCommand(hci::RemoteOobDataRequestReplyBuilder::Create( - GetRecord()->GetPseudoAddress()->GetAddress(), - this->remote_p192_oob_data_.GetC(), - this->remote_p192_oob_data_.GetR())); + GetRecord()->GetPseudoAddress()->GetAddress(), this->remote_p192_oob_data_.GetC(), + this->remote_p192_oob_data_.GetR())); } break; case hci::OobDataPresent::P_256_PRESENT: log::info("P256 Present"); GetChannel()->SendCommand(hci::RemoteOobExtendedDataRequestReplyBuilder::Create( - GetRecord()->GetPseudoAddress()->GetAddress(), - this->remote_p192_oob_data_.GetC(), - this->remote_p192_oob_data_.GetR(), - this->remote_p256_oob_data_.GetC(), - this->remote_p256_oob_data_.GetR())); + GetRecord()->GetPseudoAddress()->GetAddress(), this->remote_p192_oob_data_.GetC(), + this->remote_p192_oob_data_.GetR(), this->remote_p256_oob_data_.GetC(), + this->remote_p256_oob_data_.GetR())); break; case hci::OobDataPresent::P_192_AND_256_PRESENT: log::info("P192 and P256 Present"); GetChannel()->SendCommand(hci::RemoteOobExtendedDataRequestReplyBuilder::Create( - GetRecord()->GetPseudoAddress()->GetAddress(), - this->remote_p192_oob_data_.GetC(), - this->remote_p192_oob_data_.GetR(), - this->remote_p256_oob_data_.GetC(), - this->remote_p256_oob_data_.GetR())); + GetRecord()->GetPseudoAddress()->GetAddress(), this->remote_p192_oob_data_.GetC(), + this->remote_p192_oob_data_.GetR(), this->remote_p256_oob_data_.GetC(), + this->remote_p256_oob_data_.GetR())); break; } } @@ -403,16 +413,16 @@ void ClassicPairingHandler::OnReceive(hci::RemoteOobDataRequestView packet) { void ClassicPairingHandler::OnReceive(hci::UserPasskeyNotificationView packet) { log::assert_that(packet.IsValid(), "assert failed: packet.IsValid()"); log::info("Received: {}", hci::EventCodeText(packet.GetEventCode())); - log::assert_that( - GetRecord()->GetPseudoAddress()->GetAddress() == packet.GetBdAddr(), "Address mismatch"); + log::assert_that(GetRecord()->GetPseudoAddress()->GetAddress() == packet.GetBdAddr(), + "Address mismatch"); NotifyUiDisplayPasskey(packet.GetPasskey()); } void ClassicPairingHandler::OnReceive(hci::KeypressNotificationView packet) { log::assert_that(packet.IsValid(), "assert failed: packet.IsValid()"); log::info("Received: {}", hci::EventCodeText(packet.GetEventCode())); - log::info( - "Notification Type: {}", hci::KeypressNotificationTypeText(packet.GetNotificationType())); + log::info("Notification Type: {}", + hci::KeypressNotificationTypeText(packet.GetNotificationType())); switch (packet.GetNotificationType()) { case hci::KeypressNotificationType::ENTRY_STARTED: // Tell the UI to highlight the first digit @@ -447,11 +457,13 @@ void ClassicPairingHandler::OnReceive(hci::UserConfirmationRequestView packet) { } log::assert_that(packet.IsValid(), "assert failed: packet.IsValid()"); log::info("Received: {}", hci::EventCodeText(packet.GetEventCode())); - log::assert_that( - GetRecord()->GetPseudoAddress()->GetAddress() == packet.GetBdAddr(), "Address mismatch"); + log::assert_that(GetRecord()->GetPseudoAddress()->GetAddress() == packet.GetBdAddr(), + "Address mismatch"); // if locally_initialized, use default, otherwise us remote io caps - hci::IoCapability initiator_io_capability = (locally_initiated_) ? local_io_capability_ : remote_io_capability_; - hci::IoCapability responder_io_capability = (!locally_initiated_) ? local_io_capability_ : remote_io_capability_; + hci::IoCapability initiator_io_capability = + (locally_initiated_) ? local_io_capability_ : remote_io_capability_; + hci::IoCapability responder_io_capability = + (!locally_initiated_) ? local_io_capability_ : remote_io_capability_; switch (initiator_io_capability) { case hci::IoCapability::DISPLAY_ONLY: switch (responder_io_capability) { @@ -459,8 +471,8 @@ void ClassicPairingHandler::OnReceive(hci::UserConfirmationRequestView packet) { // NumericComparison, Both auto confirm log::info("Numeric Comparison: A and B auto confirm"); if (!GetRecord()->RequiresMitmProtection()) { - GetChannel()->SendCommand( - hci::UserConfirmationRequestReplyBuilder::Create(GetRecord()->GetPseudoAddress()->GetAddress())); + GetChannel()->SendCommand(hci::UserConfirmationRequestReplyBuilder::Create( + GetRecord()->GetPseudoAddress()->GetAddress())); // NOTE(optedoblivion) BTA needs a callback for when auto accepting JustWorks // If we auto accept from the ClassicPairingHandler in GD then we won't // get a callback to this shim function. @@ -469,7 +481,7 @@ void ClassicPairingHandler::OnReceive(hci::UserConfirmationRequestView packet) { NotifyUiDisplayYesNo(); } else { GetChannel()->SendCommand(hci::UserConfirmationRequestNegativeReplyBuilder::Create( - GetRecord()->GetPseudoAddress()->GetAddress())); + GetRecord()->GetPseudoAddress()->GetAddress())); } // Unauthenticated GetRecord()->SetAuthenticated(false); @@ -477,13 +489,13 @@ void ClassicPairingHandler::OnReceive(hci::UserConfirmationRequestView packet) { case hci::IoCapability::DISPLAY_YES_NO: // NumericComparison, Initiator auto confirm, Responder display if (!GetRecord()->RequiresMitmProtection()) { - GetChannel()->SendCommand( - hci::UserConfirmationRequestReplyBuilder::Create(GetRecord()->GetPseudoAddress()->GetAddress())); + GetChannel()->SendCommand(hci::UserConfirmationRequestReplyBuilder::Create( + GetRecord()->GetPseudoAddress()->GetAddress())); // TODO(optedoblivion): REMOVE WHEN SHIM LEAVES NotifyUiDisplayYesNo(); } else { GetChannel()->SendCommand(hci::UserConfirmationRequestNegativeReplyBuilder::Create( - GetRecord()->GetPseudoAddress()->GetAddress())); + GetRecord()->GetPseudoAddress()->GetAddress())); } log::info("Numeric Comparison: A auto confirm"); // Unauthenticated @@ -500,13 +512,13 @@ void ClassicPairingHandler::OnReceive(hci::UserConfirmationRequestView packet) { // NumericComparison, Both auto confirm log::info("Numeric Comparison: A and B auto confirm"); if (!GetRecord()->RequiresMitmProtection()) { - GetChannel()->SendCommand( - hci::UserConfirmationRequestReplyBuilder::Create(GetRecord()->GetPseudoAddress()->GetAddress())); + GetChannel()->SendCommand(hci::UserConfirmationRequestReplyBuilder::Create( + GetRecord()->GetPseudoAddress()->GetAddress())); // TODO(optedoblivion): REMOVE WHEN SHIM LEAVES NotifyUiDisplayYesNo(); } else { GetChannel()->SendCommand(hci::UserConfirmationRequestNegativeReplyBuilder::Create( - GetRecord()->GetPseudoAddress()->GetAddress())); + GetRecord()->GetPseudoAddress()->GetAddress())); } // Unauthenticated GetRecord()->SetAuthenticated(true); @@ -537,7 +549,8 @@ void ClassicPairingHandler::OnReceive(hci::UserConfirmationRequestView packet) { GetRecord()->SetAuthenticated(true); break; case hci::IoCapability::NO_INPUT_NO_OUTPUT: - // NumericComparison, auto confirm Responder, Yes/No confirm Initiator. Don't show confirmation value + // NumericComparison, auto confirm Responder, Yes/No confirm Initiator. Don't show + // confirmation value log::info("Numeric Comparison: A DisplayYesNo, B auto confirm, no show value"); NotifyUiDisplayYesNo(); // Unauthenticated @@ -572,13 +585,13 @@ void ClassicPairingHandler::OnReceive(hci::UserConfirmationRequestView packet) { // NumericComparison, both auto confirm log::info("Numeric Comparison: A and B auto confirm"); if (!GetRecord()->RequiresMitmProtection()) { - GetChannel()->SendCommand( - hci::UserConfirmationRequestReplyBuilder::Create(GetRecord()->GetPseudoAddress()->GetAddress())); + GetChannel()->SendCommand(hci::UserConfirmationRequestReplyBuilder::Create( + GetRecord()->GetPseudoAddress()->GetAddress())); // TODO(optedoblivion): REMOVE WHEN SHIM LEAVES NotifyUiDisplayYesNo(); } else { GetChannel()->SendCommand(hci::UserConfirmationRequestNegativeReplyBuilder::Create( - GetRecord()->GetPseudoAddress()->GetAddress())); + GetRecord()->GetPseudoAddress()->GetAddress())); } // Unauthenticated GetRecord()->SetAuthenticated(false); @@ -591,13 +604,13 @@ void ClassicPairingHandler::OnReceive(hci::UserConfirmationRequestView packet) { // NumericComparison, both auto confirm log::info("Numeric Comparison: A and B auto confirm"); if (!GetRecord()->RequiresMitmProtection()) { - GetChannel()->SendCommand( - hci::UserConfirmationRequestReplyBuilder::Create(GetRecord()->GetPseudoAddress()->GetAddress())); + GetChannel()->SendCommand(hci::UserConfirmationRequestReplyBuilder::Create( + GetRecord()->GetPseudoAddress()->GetAddress())); // TODO(optedoblivion): REMOVE WHEN SHIM LEAVES NotifyUiDisplayYesNo(); } else { GetChannel()->SendCommand(hci::UserConfirmationRequestNegativeReplyBuilder::Create( - GetRecord()->GetPseudoAddress()->GetAddress())); + GetRecord()->GetPseudoAddress()->GetAddress())); } // Unauthenticated GetRecord()->SetAuthenticated(false); @@ -606,13 +619,13 @@ void ClassicPairingHandler::OnReceive(hci::UserConfirmationRequestView packet) { // NumericComparison, Initiator auto confirm, Responder Yes/No confirm, no show conf val log::info("Numeric Comparison: A auto confirm"); if (!GetRecord()->RequiresMitmProtection()) { - GetChannel()->SendCommand( - hci::UserConfirmationRequestReplyBuilder::Create(GetRecord()->GetPseudoAddress()->GetAddress())); + GetChannel()->SendCommand(hci::UserConfirmationRequestReplyBuilder::Create( + GetRecord()->GetPseudoAddress()->GetAddress())); // TODO(optedoblivion): REMOVE WHEN SHIM LEAVES NotifyUiDisplayYesNo(); } else { GetChannel()->SendCommand(hci::UserConfirmationRequestNegativeReplyBuilder::Create( - GetRecord()->GetPseudoAddress()->GetAddress())); + GetRecord()->GetPseudoAddress()->GetAddress())); } // Unauthenticated GetRecord()->SetAuthenticated(false); @@ -621,13 +634,13 @@ void ClassicPairingHandler::OnReceive(hci::UserConfirmationRequestView packet) { // NumericComparison, both auto confirm log::info("Numeric Comparison: A and B auto confirm"); if (!GetRecord()->RequiresMitmProtection()) { - GetChannel()->SendCommand( - hci::UserConfirmationRequestReplyBuilder::Create(GetRecord()->GetPseudoAddress()->GetAddress())); + GetChannel()->SendCommand(hci::UserConfirmationRequestReplyBuilder::Create( + GetRecord()->GetPseudoAddress()->GetAddress())); // TODO(optedoblivion): REMOVE WHEN SHIM LEAVES NotifyUiDisplayYesNo(); } else { GetChannel()->SendCommand(hci::UserConfirmationRequestNegativeReplyBuilder::Create( - GetRecord()->GetPseudoAddress()->GetAddress())); + GetRecord()->GetPseudoAddress()->GetAddress())); } // Unauthenticated GetRecord()->SetAuthenticated(false); @@ -636,13 +649,13 @@ void ClassicPairingHandler::OnReceive(hci::UserConfirmationRequestView packet) { // NumericComparison, both auto confirm log::info("Numeric Comparison: A and B auto confirm"); if (!GetRecord()->RequiresMitmProtection()) { - GetChannel()->SendCommand( - hci::UserConfirmationRequestReplyBuilder::Create(GetRecord()->GetPseudoAddress()->GetAddress())); + GetChannel()->SendCommand(hci::UserConfirmationRequestReplyBuilder::Create( + GetRecord()->GetPseudoAddress()->GetAddress())); // TODO(optedoblivion): REMOVE WHEN SHIM LEAVES NotifyUiDisplayYesNo(); } else { GetChannel()->SendCommand(hci::UserConfirmationRequestNegativeReplyBuilder::Create( - GetRecord()->GetPseudoAddress()->GetAddress())); + GetRecord()->GetPseudoAddress()->GetAddress())); } // Unauthenticated GetRecord()->SetAuthenticated(false); @@ -654,8 +667,8 @@ void ClassicPairingHandler::OnReceive(hci::UserConfirmationRequestView packet) { void ClassicPairingHandler::OnReceive(hci::UserPasskeyRequestView packet) { log::assert_that(packet.IsValid(), "assert failed: packet.IsValid()"); - log::assert_that( - GetRecord()->GetPseudoAddress()->GetAddress() == packet.GetBdAddr(), "Address mismatch"); + log::assert_that(GetRecord()->GetPseudoAddress()->GetAddress() == packet.GetBdAddr(), + "Address mismatch"); } void ClassicPairingHandler::OnUserInput(bool user_input) { @@ -667,18 +680,16 @@ void ClassicPairingHandler::OnUserInput(bool user_input) { } void ClassicPairingHandler::UserClickedYes() { - GetChannel()->SendCommand( - hci::UserConfirmationRequestReplyBuilder::Create(GetRecord()->GetPseudoAddress()->GetAddress())); + GetChannel()->SendCommand(hci::UserConfirmationRequestReplyBuilder::Create( + GetRecord()->GetPseudoAddress()->GetAddress())); } void ClassicPairingHandler::UserClickedNo() { - GetChannel()->SendCommand( - hci::UserConfirmationRequestNegativeReplyBuilder::Create(GetRecord()->GetPseudoAddress()->GetAddress())); + GetChannel()->SendCommand(hci::UserConfirmationRequestNegativeReplyBuilder::Create( + GetRecord()->GetPseudoAddress()->GetAddress())); } -void ClassicPairingHandler::OnPasskeyInput(uint32_t passkey) { - passkey_ = passkey; -} +void ClassicPairingHandler::OnPasskeyInput(uint32_t passkey) { passkey_ = passkey; } } // namespace pairing } // namespace security diff --git a/system/gd/security/pairing/classic_pairing_handler.h b/system/gd/security/pairing/classic_pairing_handler.h index 0df839d2572..f3af782c502 100644 --- a/system/gd/security/pairing/classic_pairing_handler.h +++ b/system/gd/security/pairing/classic_pairing_handler.h @@ -31,24 +31,23 @@ class ISecurityManagerListener; namespace pairing { class ClassicPairingHandler : public PairingHandler { - public: +public: ClassicPairingHandler( - channel::SecurityManagerChannel* security_manager_channel, - std::shared_ptr record, - os::Handler* security_handler, - common::OnceCallback complete_callback, - UI* user_interface, - os::Handler* user_interface_handler, - std::string device_name, - neighbor::NameDbModule* name_db_module) + channel::SecurityManagerChannel* security_manager_channel, + std::shared_ptr record, os::Handler* security_handler, + common::OnceCallback complete_callback, + UI* user_interface, os::Handler* user_interface_handler, std::string device_name, + neighbor::NameDbModule* name_db_module) : PairingHandler(security_manager_channel, std::move(record), name_db_module), security_handler_(security_handler), remote_io_capability_(hci::IoCapability::DISPLAY_YES_NO), remote_oob_present_(hci::OobDataPresent::NOT_PRESENT), - remote_authentication_requirements_(hci::AuthenticationRequirements::DEDICATED_BONDING_MITM_PROTECTION), + remote_authentication_requirements_( + hci::AuthenticationRequirements::DEDICATED_BONDING_MITM_PROTECTION), local_io_capability_(hci::IoCapability::DISPLAY_YES_NO), local_oob_present_(hci::OobDataPresent::NOT_PRESENT), - local_authentication_requirements_(hci::AuthenticationRequirements::DEDICATED_BONDING_MITM_PROTECTION), + local_authentication_requirements_( + hci::AuthenticationRequirements::DEDICATED_BONDING_MITM_PROTECTION), complete_callback_(std::move(complete_callback)), user_interface_(user_interface), user_interface_handler_(user_interface_handler), @@ -56,12 +55,9 @@ class ClassicPairingHandler : public PairingHandler { ~ClassicPairingHandler() = default; - void Initiate( - bool locally_initiated, - hci::IoCapability io_capability, - hci::AuthenticationRequirements auth_requirements, - OobData remote_p192_oob_data, - OobData remote_p256_oob_data) override; + void Initiate(bool locally_initiated, hci::IoCapability io_capability, + hci::AuthenticationRequirements auth_requirements, OobData remote_p192_oob_data, + OobData remote_p256_oob_data) override; void Cancel() override; void OnReceive(hci::ChangeConnectionLinkKeyCompleteView packet) override; @@ -81,14 +77,16 @@ class ClassicPairingHandler : public PairingHandler { void OnReceive(hci::UserConfirmationRequestView packet) override; void OnReceive(hci::UserPasskeyRequestView packet) override; - void OnPairingPromptAccepted(const bluetooth::hci::AddressWithType& address, bool confirmed) override; + void OnPairingPromptAccepted(const bluetooth::hci::AddressWithType& address, + bool confirmed) override; void OnConfirmYesNo(const bluetooth::hci::AddressWithType& address, bool confirmed) override; void OnPasskeyEntry(const bluetooth::hci::AddressWithType& address, uint32_t passkey) override; - void OnPinEntry(const bluetooth::hci::AddressWithType& address, std::vector pin) override; + void OnPinEntry(const bluetooth::hci::AddressWithType& address, + std::vector pin) override; void OnNameRequestComplete(hci::Address address, bool success); - private: +private: void OnUserInput(bool user_input); void OnPasskeyInput(uint32_t passkey); void NotifyUiDisplayYesNo(uint32_t numeric_value); diff --git a/system/gd/security/pairing/classic_pairing_handler_unittest.cc b/system/gd/security/pairing/classic_pairing_handler_unittest.cc index a9d49529974..d61c20eb62a 100644 --- a/system/gd/security/pairing/classic_pairing_handler_unittest.cc +++ b/system/gd/security/pairing/classic_pairing_handler_unittest.cc @@ -49,7 +49,7 @@ using os::Thread; using packet::RawBuilder; class FakeSecurityManagerChannel : public channel::SecurityManagerChannel { - public: +public: FakeSecurityManagerChannel(os::Handler* handler, hci::HciLayer* hci_layer) : channel::SecurityManagerChannel(handler, hci_layer) {} ~FakeSecurityManagerChannel() {} @@ -58,13 +58,9 @@ class FakeSecurityManagerChannel : public channel::SecurityManagerChannel { log::error("CALLED"); } - void OnLinkDisconnected(hci::Address address) override { - log::error("CALLED"); - } + void OnLinkDisconnected(hci::Address address) override { log::error("CALLED"); } - void OnEncryptionChange(hci::Address address, bool encrypted) override { - log::error("CALLED"); - } + void OnEncryptionChange(hci::Address address, bool encrypted) override { log::error("CALLED"); } void OnAuthenticationComplete(hci::ErrorCode hci_status, hci::Address remote) override { log::error("CALLED"); @@ -72,7 +68,7 @@ class FakeSecurityManagerChannel : public channel::SecurityManagerChannel { }; class TestUI : public UI { - public: +public: ~TestUI() = default; void DisplayPairingPrompt(const hci::AddressWithType& address, std::string name) override {} void Cancel(const hci::AddressWithType& address) override {} @@ -84,7 +80,7 @@ class TestUI : public UI { }; class SecurityManagerChannelCallback : public channel::ISecurityManagerChannelListener { - public: +public: explicit SecurityManagerChannelCallback(pairing::ClassicPairingHandler* pairing_handler) : pairing_handler_(pairing_handler) {} void OnHciEventReceived(hci::EventView packet) override { @@ -134,17 +130,16 @@ class SecurityManagerChannelCallback : public channel::ISecurityManagerChannelLi } } - void OnConnectionClosed(hci::Address address) override { - log::info("Called"); - } + void OnConnectionClosed(hci::Address address) override { log::info("Called"); } - private: +private: pairing::ClassicPairingHandler* pairing_handler_ = nullptr; }; bool expect_success_ = true; -static void pairing_complete_callback(bluetooth::hci::Address address, PairingResultOrFailure status) { +static void pairing_complete_callback(bluetooth::hci::Address address, + PairingResultOrFailure status) { if (expect_success_) { ASSERT_TRUE(std::holds_alternative(status)); } else { @@ -153,7 +148,7 @@ static void pairing_complete_callback(bluetooth::hci::Address address, PairingRe } class ClassicPairingHandlerTest : public ::testing::Test { - protected: +protected: void SetUp() override { expect_success_ = true; hci_layer_ = new FakeHciLayer(); @@ -166,14 +161,8 @@ class ClassicPairingHandlerTest : public ::testing::Test { user_interface_ = new TestUI(); user_interface_handler_ = handler_; pairing_handler_ = new pairing::ClassicPairingHandler( - channel_, - security_record_, - handler_, - common::Bind(&pairing_complete_callback), - user_interface_, - user_interface_handler_, - "Fake name", - name_db_module_); + channel_, security_record_, handler_, common::Bind(&pairing_complete_callback), + user_interface_, user_interface_handler_, "Fake name", name_db_module_); channel_callback_ = new SecurityManagerChannelCallback(pairing_handler_); channel_->SetChannelListener(channel_callback_); security_interface_ = new FakeSecurityInterface(handler_, channel_); @@ -193,7 +182,8 @@ class ClassicPairingHandlerTest : public ::testing::Test { void synchronize() { fake_registry_.SynchronizeModuleHandler(&FakeHciLayer::Factory, std::chrono::milliseconds(20)); - fake_registry_.SynchronizeModuleHandler(&FakeNameDbModule::Factory, std::chrono::milliseconds(20)); + fake_registry_.SynchronizeModuleHandler(&FakeNameDbModule::Factory, + std::chrono::milliseconds(20)); } void ReceiveLinkKeyRequest(hci::AddressWithType device) { @@ -207,9 +197,10 @@ class ClassicPairingHandlerTest : public ::testing::Test { } void ReceiveIoCapabilityResponse(hci::AddressWithType device, hci::IoCapability io_cap, - hci::OobDataPresent oob_present, hci::AuthenticationRequirements auth_reqs) { - hci_layer_->IncomingEvent( - hci::IoCapabilityResponseBuilder::Create(device.GetAddress(), io_cap, oob_present, auth_reqs)); + hci::OobDataPresent oob_present, + hci::AuthenticationRequirements auth_reqs) { + hci_layer_->IncomingEvent(hci::IoCapabilityResponseBuilder::Create(device.GetAddress(), io_cap, + oob_present, auth_reqs)); synchronize(); } @@ -219,18 +210,21 @@ class ClassicPairingHandlerTest : public ::testing::Test { } void ReceiveUserConfirmationRequest(hci::AddressWithType device, uint32_t numeric_value) { - hci_layer_->IncomingEvent(hci::UserConfirmationRequestBuilder::Create(device.GetAddress(), numeric_value)); + hci_layer_->IncomingEvent( + hci::UserConfirmationRequestBuilder::Create(device.GetAddress(), numeric_value)); synchronize(); } void ReceiveSimplePairingComplete(hci::ErrorCode status, hci::AddressWithType device) { - hci_layer_->IncomingEvent(hci::SimplePairingCompleteBuilder::Create(status, device.GetAddress())); + hci_layer_->IncomingEvent( + hci::SimplePairingCompleteBuilder::Create(status, device.GetAddress())); synchronize(); } void ReceiveLinkKeyNotification(hci::AddressWithType device, std::array link_key, hci::KeyType key_type) { - hci_layer_->IncomingEvent(hci::LinkKeyNotificationBuilder::Create(device.GetAddress(), link_key, key_type)); + hci_layer_->IncomingEvent( + hci::LinkKeyNotificationBuilder::Create(device.GetAddress(), link_key, key_type)); synchronize(); } @@ -290,9 +284,10 @@ TEST_F(ClassicPairingHandlerTest, setup_teardown) {} // Needs dialog as per security a bug unless pairing is temporary TEST_F(ClassicPairingHandlerTest, locally_initiatied_display_only_display_only_temp) { hci::IoCapability injected_io_capability = hci::IoCapability::DISPLAY_ONLY; - hci::AuthenticationRequirements injected_authentication_requirements = hci::AuthenticationRequirements::NO_BONDING; - pairing_handler_->Initiate( - true, injected_io_capability, injected_authentication_requirements, pairing::OobData(), pairing::OobData()); + hci::AuthenticationRequirements injected_authentication_requirements = + hci::AuthenticationRequirements::NO_BONDING; + pairing_handler_->Initiate(true, injected_io_capability, injected_authentication_requirements, + pairing::OobData(), pairing::OobData()); ReceiveLinkKeyRequest(device_); auto security_command_view = GetLastCommand(hci_layer_); auto link_key_neg_reply = hci::LinkKeyRequestNegativeReplyView::Create(security_command_view); @@ -305,14 +300,17 @@ TEST_F(ClassicPairingHandlerTest, locally_initiatied_display_only_display_only_t ASSERT_TRUE(io_cap_request_reply.IsValid()); ASSERT_EQ(injected_io_capability, io_cap_request_reply.GetIoCapability()); ASSERT_EQ(hci::OobDataPresent::NOT_PRESENT, io_cap_request_reply.GetOobPresent()); - ASSERT_EQ(injected_authentication_requirements, io_cap_request_reply.GetAuthenticationRequirements()); - ReceiveIoCapabilityResponse(device_, hci::IoCapability::DISPLAY_ONLY, hci::OobDataPresent::NOT_PRESENT, + ASSERT_EQ(injected_authentication_requirements, + io_cap_request_reply.GetAuthenticationRequirements()); + ReceiveIoCapabilityResponse(device_, hci::IoCapability::DISPLAY_ONLY, + hci::OobDataPresent::NOT_PRESENT, hci::AuthenticationRequirements::NO_BONDING); uint32_t numeric_value = 0x123; ReceiveUserConfirmationRequest(device_, numeric_value); security_command_view = GetLastCommand(hci_layer_); ASSERT_EQ(OpCode::USER_CONFIRMATION_REQUEST_REPLY, security_command_view.GetOpCode()); - auto user_conf_request_reply = hci::UserConfirmationRequestReplyView::Create(security_command_view); + auto user_conf_request_reply = + hci::UserConfirmationRequestReplyView::Create(security_command_view); ASSERT_TRUE(user_conf_request_reply.IsValid()); ReceiveSimplePairingComplete(hci::ErrorCode::SUCCESS, device_); std::array link_key = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5}; @@ -328,9 +326,10 @@ TEST_F(ClassicPairingHandlerTest, locally_initiatied_display_only_display_only_t // Needs dialog as per security a bug unless pairing is temporary TEST_F(ClassicPairingHandlerTest, locally_initiatied_display_only_display_yes_no_temp) { hci::IoCapability injected_io_capability = hci::IoCapability::DISPLAY_ONLY; - hci::AuthenticationRequirements injected_authentication_requirements = hci::AuthenticationRequirements::NO_BONDING; - pairing_handler_->Initiate( - true, injected_io_capability, injected_authentication_requirements, pairing::OobData(), pairing::OobData()); + hci::AuthenticationRequirements injected_authentication_requirements = + hci::AuthenticationRequirements::NO_BONDING; + pairing_handler_->Initiate(true, injected_io_capability, injected_authentication_requirements, + pairing::OobData(), pairing::OobData()); ReceiveLinkKeyRequest(device_); auto security_command_view = GetLastCommand(hci_layer_); auto link_key_neg_reply = hci::LinkKeyRequestNegativeReplyView::Create(security_command_view); @@ -343,14 +342,17 @@ TEST_F(ClassicPairingHandlerTest, locally_initiatied_display_only_display_yes_no ASSERT_TRUE(io_cap_request_reply.IsValid()); ASSERT_EQ(injected_io_capability, io_cap_request_reply.GetIoCapability()); ASSERT_EQ(hci::OobDataPresent::NOT_PRESENT, io_cap_request_reply.GetOobPresent()); - ASSERT_EQ(injected_authentication_requirements, io_cap_request_reply.GetAuthenticationRequirements()); - ReceiveIoCapabilityResponse(device_, hci::IoCapability::DISPLAY_YES_NO, hci::OobDataPresent::NOT_PRESENT, + ASSERT_EQ(injected_authentication_requirements, + io_cap_request_reply.GetAuthenticationRequirements()); + ReceiveIoCapabilityResponse(device_, hci::IoCapability::DISPLAY_YES_NO, + hci::OobDataPresent::NOT_PRESENT, hci::AuthenticationRequirements::NO_BONDING); uint32_t numeric_value = 0x123; ReceiveUserConfirmationRequest(device_, numeric_value); security_command_view = GetLastCommand(hci_layer_); ASSERT_EQ(OpCode::USER_CONFIRMATION_REQUEST_REPLY, security_command_view.GetOpCode()); - auto user_conf_request_reply = hci::UserConfirmationRequestReplyView::Create(security_command_view); + auto user_conf_request_reply = + hci::UserConfirmationRequestReplyView::Create(security_command_view); ASSERT_TRUE(user_conf_request_reply.IsValid()); ReceiveSimplePairingComplete(hci::ErrorCode::SUCCESS, device_); std::array link_key = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5}; @@ -366,9 +368,10 @@ TEST_F(ClassicPairingHandlerTest, locally_initiatied_display_only_display_yes_no // Needs dialog as per security a bug unless pairing is temporary TEST_F(ClassicPairingHandlerTest, locally_initiatied_display_only_no_input_no_output_temp) { hci::IoCapability injected_io_capability = hci::IoCapability::DISPLAY_ONLY; - hci::AuthenticationRequirements injected_authentication_requirements = hci::AuthenticationRequirements::NO_BONDING; - pairing_handler_->Initiate( - true, injected_io_capability, injected_authentication_requirements, pairing::OobData(), pairing::OobData()); + hci::AuthenticationRequirements injected_authentication_requirements = + hci::AuthenticationRequirements::NO_BONDING; + pairing_handler_->Initiate(true, injected_io_capability, injected_authentication_requirements, + pairing::OobData(), pairing::OobData()); ReceiveLinkKeyRequest(device_); auto security_command_view = GetLastCommand(hci_layer_); auto link_key_neg_reply = hci::LinkKeyRequestNegativeReplyView::Create(security_command_view); @@ -381,14 +384,17 @@ TEST_F(ClassicPairingHandlerTest, locally_initiatied_display_only_no_input_no_ou ASSERT_TRUE(io_cap_request_reply.IsValid()); ASSERT_EQ(injected_io_capability, io_cap_request_reply.GetIoCapability()); ASSERT_EQ(hci::OobDataPresent::NOT_PRESENT, io_cap_request_reply.GetOobPresent()); - ASSERT_EQ(injected_authentication_requirements, io_cap_request_reply.GetAuthenticationRequirements()); - ReceiveIoCapabilityResponse(device_, hci::IoCapability::NO_INPUT_NO_OUTPUT, hci::OobDataPresent::NOT_PRESENT, + ASSERT_EQ(injected_authentication_requirements, + io_cap_request_reply.GetAuthenticationRequirements()); + ReceiveIoCapabilityResponse(device_, hci::IoCapability::NO_INPUT_NO_OUTPUT, + hci::OobDataPresent::NOT_PRESENT, hci::AuthenticationRequirements::NO_BONDING); uint32_t numeric_value = 0x123; ReceiveUserConfirmationRequest(device_, numeric_value); security_command_view = GetLastCommand(hci_layer_); ASSERT_EQ(OpCode::USER_CONFIRMATION_REQUEST_REPLY, security_command_view.GetOpCode()); - auto user_conf_request_reply = hci::UserConfirmationRequestReplyView::Create(security_command_view); + auto user_conf_request_reply = + hci::UserConfirmationRequestReplyView::Create(security_command_view); ASSERT_TRUE(user_conf_request_reply.IsValid()); ReceiveSimplePairingComplete(hci::ErrorCode::SUCCESS, device_); std::array link_key = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5}; @@ -404,9 +410,10 @@ TEST_F(ClassicPairingHandlerTest, locally_initiatied_display_only_no_input_no_ou // Needs dialog as per security a bug unless pairing is temporary TEST_F(ClassicPairingHandlerTest, locally_initiatied_keyboard_only_no_input_no_output_temp) { hci::IoCapability injected_io_capability = hci::IoCapability::KEYBOARD_ONLY; - hci::AuthenticationRequirements injected_authentication_requirements = hci::AuthenticationRequirements::NO_BONDING; - pairing_handler_->Initiate( - true, injected_io_capability, injected_authentication_requirements, pairing::OobData(), pairing::OobData()); + hci::AuthenticationRequirements injected_authentication_requirements = + hci::AuthenticationRequirements::NO_BONDING; + pairing_handler_->Initiate(true, injected_io_capability, injected_authentication_requirements, + pairing::OobData(), pairing::OobData()); ReceiveLinkKeyRequest(device_); auto security_command_view = GetLastCommand(hci_layer_); auto link_key_neg_reply = hci::LinkKeyRequestNegativeReplyView::Create(security_command_view); @@ -419,14 +426,17 @@ TEST_F(ClassicPairingHandlerTest, locally_initiatied_keyboard_only_no_input_no_o ASSERT_TRUE(io_cap_request_reply.IsValid()); ASSERT_EQ(injected_io_capability, io_cap_request_reply.GetIoCapability()); ASSERT_EQ(hci::OobDataPresent::NOT_PRESENT, io_cap_request_reply.GetOobPresent()); - ASSERT_EQ(injected_authentication_requirements, io_cap_request_reply.GetAuthenticationRequirements()); - ReceiveIoCapabilityResponse(device_, hci::IoCapability::NO_INPUT_NO_OUTPUT, hci::OobDataPresent::NOT_PRESENT, + ASSERT_EQ(injected_authentication_requirements, + io_cap_request_reply.GetAuthenticationRequirements()); + ReceiveIoCapabilityResponse(device_, hci::IoCapability::NO_INPUT_NO_OUTPUT, + hci::OobDataPresent::NOT_PRESENT, hci::AuthenticationRequirements::NO_BONDING); uint32_t numeric_value = 0x123; ReceiveUserConfirmationRequest(device_, numeric_value); security_command_view = GetLastCommand(hci_layer_); ASSERT_EQ(OpCode::USER_CONFIRMATION_REQUEST_REPLY, security_command_view.GetOpCode()); - auto user_conf_request_reply = hci::UserConfirmationRequestReplyView::Create(security_command_view); + auto user_conf_request_reply = + hci::UserConfirmationRequestReplyView::Create(security_command_view); ASSERT_TRUE(user_conf_request_reply.IsValid()); ReceiveSimplePairingComplete(hci::ErrorCode::SUCCESS, device_); std::array link_key = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5}; @@ -442,9 +452,10 @@ TEST_F(ClassicPairingHandlerTest, locally_initiatied_keyboard_only_no_input_no_o // Needs dialog as per security a bug unless pairing is temporary TEST_F(ClassicPairingHandlerTest, locally_initiatied_no_input_no_output_display_only_temp) { hci::IoCapability injected_io_capability = hci::IoCapability::NO_INPUT_NO_OUTPUT; - hci::AuthenticationRequirements injected_authentication_requirements = hci::AuthenticationRequirements::NO_BONDING; - pairing_handler_->Initiate( - true, injected_io_capability, injected_authentication_requirements, pairing::OobData(), pairing::OobData()); + hci::AuthenticationRequirements injected_authentication_requirements = + hci::AuthenticationRequirements::NO_BONDING; + pairing_handler_->Initiate(true, injected_io_capability, injected_authentication_requirements, + pairing::OobData(), pairing::OobData()); ReceiveLinkKeyRequest(device_); auto security_command_view = GetLastCommand(hci_layer_); auto link_key_neg_reply = hci::LinkKeyRequestNegativeReplyView::Create(security_command_view); @@ -457,14 +468,17 @@ TEST_F(ClassicPairingHandlerTest, locally_initiatied_no_input_no_output_display_ ASSERT_TRUE(io_cap_request_reply.IsValid()); ASSERT_EQ(injected_io_capability, io_cap_request_reply.GetIoCapability()); ASSERT_EQ(hci::OobDataPresent::NOT_PRESENT, io_cap_request_reply.GetOobPresent()); - ASSERT_EQ(injected_authentication_requirements, io_cap_request_reply.GetAuthenticationRequirements()); - ReceiveIoCapabilityResponse(device_, hci::IoCapability::DISPLAY_ONLY, hci::OobDataPresent::NOT_PRESENT, + ASSERT_EQ(injected_authentication_requirements, + io_cap_request_reply.GetAuthenticationRequirements()); + ReceiveIoCapabilityResponse(device_, hci::IoCapability::DISPLAY_ONLY, + hci::OobDataPresent::NOT_PRESENT, hci::AuthenticationRequirements::NO_BONDING); uint32_t numeric_value = 0x123; ReceiveUserConfirmationRequest(device_, numeric_value); security_command_view = GetLastCommand(hci_layer_); ASSERT_EQ(OpCode::USER_CONFIRMATION_REQUEST_REPLY, security_command_view.GetOpCode()); - auto user_conf_request_reply = hci::UserConfirmationRequestReplyView::Create(security_command_view); + auto user_conf_request_reply = + hci::UserConfirmationRequestReplyView::Create(security_command_view); ASSERT_TRUE(user_conf_request_reply.IsValid()); ReceiveSimplePairingComplete(hci::ErrorCode::SUCCESS, device_); std::array link_key = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5}; @@ -480,9 +494,10 @@ TEST_F(ClassicPairingHandlerTest, locally_initiatied_no_input_no_output_display_ // Needs dialog as per security a bug unless pairing is temporary TEST_F(ClassicPairingHandlerTest, locally_initiatied_no_input_no_output_display_yes_no_temp) { hci::IoCapability injected_io_capability = hci::IoCapability::NO_INPUT_NO_OUTPUT; - hci::AuthenticationRequirements injected_authentication_requirements = hci::AuthenticationRequirements::NO_BONDING; - pairing_handler_->Initiate( - true, injected_io_capability, injected_authentication_requirements, pairing::OobData(), pairing::OobData()); + hci::AuthenticationRequirements injected_authentication_requirements = + hci::AuthenticationRequirements::NO_BONDING; + pairing_handler_->Initiate(true, injected_io_capability, injected_authentication_requirements, + pairing::OobData(), pairing::OobData()); ReceiveLinkKeyRequest(device_); auto security_command_view = GetLastCommand(hci_layer_); auto link_key_neg_reply = hci::LinkKeyRequestNegativeReplyView::Create(security_command_view); @@ -495,14 +510,17 @@ TEST_F(ClassicPairingHandlerTest, locally_initiatied_no_input_no_output_display_ ASSERT_TRUE(io_cap_request_reply.IsValid()); ASSERT_EQ(injected_io_capability, io_cap_request_reply.GetIoCapability()); ASSERT_EQ(hci::OobDataPresent::NOT_PRESENT, io_cap_request_reply.GetOobPresent()); - ASSERT_EQ(injected_authentication_requirements, io_cap_request_reply.GetAuthenticationRequirements()); - ReceiveIoCapabilityResponse(device_, hci::IoCapability::DISPLAY_YES_NO, hci::OobDataPresent::NOT_PRESENT, + ASSERT_EQ(injected_authentication_requirements, + io_cap_request_reply.GetAuthenticationRequirements()); + ReceiveIoCapabilityResponse(device_, hci::IoCapability::DISPLAY_YES_NO, + hci::OobDataPresent::NOT_PRESENT, hci::AuthenticationRequirements::NO_BONDING); uint32_t numeric_value = 0x123; ReceiveUserConfirmationRequest(device_, numeric_value); security_command_view = GetLastCommand(hci_layer_); ASSERT_EQ(OpCode::USER_CONFIRMATION_REQUEST_REPLY, security_command_view.GetOpCode()); - auto user_conf_request_reply = hci::UserConfirmationRequestReplyView::Create(security_command_view); + auto user_conf_request_reply = + hci::UserConfirmationRequestReplyView::Create(security_command_view); ASSERT_TRUE(user_conf_request_reply.IsValid()); ReceiveSimplePairingComplete(hci::ErrorCode::SUCCESS, device_); std::array link_key = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5}; @@ -518,9 +536,10 @@ TEST_F(ClassicPairingHandlerTest, locally_initiatied_no_input_no_output_display_ // Needs dialog as per security a bug unless pairing is temporary TEST_F(ClassicPairingHandlerTest, locally_initiatied_no_input_no_output_keyboard_only_temp) { hci::IoCapability injected_io_capability = hci::IoCapability::NO_INPUT_NO_OUTPUT; - hci::AuthenticationRequirements injected_authentication_requirements = hci::AuthenticationRequirements::NO_BONDING; - pairing_handler_->Initiate( - true, injected_io_capability, injected_authentication_requirements, pairing::OobData(), pairing::OobData()); + hci::AuthenticationRequirements injected_authentication_requirements = + hci::AuthenticationRequirements::NO_BONDING; + pairing_handler_->Initiate(true, injected_io_capability, injected_authentication_requirements, + pairing::OobData(), pairing::OobData()); ReceiveLinkKeyRequest(device_); auto security_command_view = GetLastCommand(hci_layer_); auto link_key_neg_reply = hci::LinkKeyRequestNegativeReplyView::Create(security_command_view); @@ -533,14 +552,17 @@ TEST_F(ClassicPairingHandlerTest, locally_initiatied_no_input_no_output_keyboard ASSERT_TRUE(io_cap_request_reply.IsValid()); ASSERT_EQ(injected_io_capability, io_cap_request_reply.GetIoCapability()); ASSERT_EQ(hci::OobDataPresent::NOT_PRESENT, io_cap_request_reply.GetOobPresent()); - ASSERT_EQ(injected_authentication_requirements, io_cap_request_reply.GetAuthenticationRequirements()); - ReceiveIoCapabilityResponse(device_, hci::IoCapability::KEYBOARD_ONLY, hci::OobDataPresent::NOT_PRESENT, + ASSERT_EQ(injected_authentication_requirements, + io_cap_request_reply.GetAuthenticationRequirements()); + ReceiveIoCapabilityResponse(device_, hci::IoCapability::KEYBOARD_ONLY, + hci::OobDataPresent::NOT_PRESENT, hci::AuthenticationRequirements::NO_BONDING); uint32_t numeric_value = 0x123; ReceiveUserConfirmationRequest(device_, numeric_value); security_command_view = GetLastCommand(hci_layer_); ASSERT_EQ(OpCode::USER_CONFIRMATION_REQUEST_REPLY, security_command_view.GetOpCode()); - auto user_conf_request_reply = hci::UserConfirmationRequestReplyView::Create(security_command_view); + auto user_conf_request_reply = + hci::UserConfirmationRequestReplyView::Create(security_command_view); ASSERT_TRUE(user_conf_request_reply.IsValid()); ReceiveSimplePairingComplete(hci::ErrorCode::SUCCESS, device_); std::array link_key = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5}; @@ -556,9 +578,10 @@ TEST_F(ClassicPairingHandlerTest, locally_initiatied_no_input_no_output_keyboard // Needs dialog as per security a bug unless pairing is temporary TEST_F(ClassicPairingHandlerTest, locally_initiatied_no_input_no_output_no_input_no_output_temp) { hci::IoCapability injected_io_capability = hci::IoCapability::NO_INPUT_NO_OUTPUT; - hci::AuthenticationRequirements injected_authentication_requirements = hci::AuthenticationRequirements::NO_BONDING; - pairing_handler_->Initiate( - true, injected_io_capability, injected_authentication_requirements, pairing::OobData(), pairing::OobData()); + hci::AuthenticationRequirements injected_authentication_requirements = + hci::AuthenticationRequirements::NO_BONDING; + pairing_handler_->Initiate(true, injected_io_capability, injected_authentication_requirements, + pairing::OobData(), pairing::OobData()); ReceiveLinkKeyRequest(device_); auto security_command_view = GetLastCommand(hci_layer_); auto link_key_neg_reply = hci::LinkKeyRequestNegativeReplyView::Create(security_command_view); @@ -571,14 +594,17 @@ TEST_F(ClassicPairingHandlerTest, locally_initiatied_no_input_no_output_no_input ASSERT_TRUE(io_cap_request_reply.IsValid()); ASSERT_EQ(injected_io_capability, io_cap_request_reply.GetIoCapability()); ASSERT_EQ(hci::OobDataPresent::NOT_PRESENT, io_cap_request_reply.GetOobPresent()); - ASSERT_EQ(injected_authentication_requirements, io_cap_request_reply.GetAuthenticationRequirements()); - ReceiveIoCapabilityResponse(device_, hci::IoCapability::NO_INPUT_NO_OUTPUT, hci::OobDataPresent::NOT_PRESENT, + ASSERT_EQ(injected_authentication_requirements, + io_cap_request_reply.GetAuthenticationRequirements()); + ReceiveIoCapabilityResponse(device_, hci::IoCapability::NO_INPUT_NO_OUTPUT, + hci::OobDataPresent::NOT_PRESENT, hci::AuthenticationRequirements::NO_BONDING); uint32_t numeric_value = 0x123; ReceiveUserConfirmationRequest(device_, numeric_value); security_command_view = GetLastCommand(hci_layer_); ASSERT_EQ(OpCode::USER_CONFIRMATION_REQUEST_REPLY, security_command_view.GetOpCode()); - auto user_conf_request_reply = hci::UserConfirmationRequestReplyView::Create(security_command_view); + auto user_conf_request_reply = + hci::UserConfirmationRequestReplyView::Create(security_command_view); ASSERT_TRUE(user_conf_request_reply.IsValid()); ReceiveSimplePairingComplete(hci::ErrorCode::SUCCESS, device_); std::array link_key = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5}; @@ -590,15 +616,18 @@ TEST_F(ClassicPairingHandlerTest, locally_initiatied_no_input_no_output_no_input ASSERT_FALSE(security_record_->RequiresMitmProtection()); } -TEST_F(ClassicPairingHandlerTest, remote_initiatied_no_input_no_output_no_input_no_output_with_missing_oob_data) {} +TEST_F(ClassicPairingHandlerTest, + remote_initiatied_no_input_no_output_no_input_no_output_with_missing_oob_data) {} // CreateBondOutOfBand no_input_no_output + no_input_no_output OOB Data missing when asked -TEST_F(ClassicPairingHandlerTest, locally_initiatied_no_input_no_output_no_input_no_output_with_missing_oob_data) { +TEST_F(ClassicPairingHandlerTest, + locally_initiatied_no_input_no_output_no_input_no_output_with_missing_oob_data) { expect_success_ = false; hci::IoCapability injected_io_capability = hci::IoCapability::NO_INPUT_NO_OUTPUT; - hci::AuthenticationRequirements injected_authentication_requirements = hci::AuthenticationRequirements::NO_BONDING; - pairing_handler_->Initiate( - true, injected_io_capability, injected_authentication_requirements, pairing::OobData(), pairing::OobData()); + hci::AuthenticationRequirements injected_authentication_requirements = + hci::AuthenticationRequirements::NO_BONDING; + pairing_handler_->Initiate(true, injected_io_capability, injected_authentication_requirements, + pairing::OobData(), pairing::OobData()); ReceiveLinkKeyRequest(device_); auto security_command_view = GetLastCommand(hci_layer_); @@ -612,29 +641,31 @@ TEST_F(ClassicPairingHandlerTest, locally_initiatied_no_input_no_output_no_input ASSERT_TRUE(io_cap_request_reply.IsValid()); ASSERT_EQ(injected_io_capability, io_cap_request_reply.GetIoCapability()); ASSERT_EQ(hci::OobDataPresent::NOT_PRESENT, io_cap_request_reply.GetOobPresent()); - ASSERT_EQ(injected_authentication_requirements, io_cap_request_reply.GetAuthenticationRequirements()); - ReceiveIoCapabilityResponse( - device_, - hci::IoCapability::NO_INPUT_NO_OUTPUT, - hci::OobDataPresent::NOT_PRESENT, - hci::AuthenticationRequirements::NO_BONDING); + ASSERT_EQ(injected_authentication_requirements, + io_cap_request_reply.GetAuthenticationRequirements()); + ReceiveIoCapabilityResponse(device_, hci::IoCapability::NO_INPUT_NO_OUTPUT, + hci::OobDataPresent::NOT_PRESENT, + hci::AuthenticationRequirements::NO_BONDING); // At this point the pairing handler thinks it has NOT_PRESENT ReceiveOobDataRequest(device_); security_command_view = GetLastCommand(hci_layer_); - auto oob_data_req_neg_reply = hci::RemoteOobDataRequestNegativeReplyView::Create(security_command_view); + auto oob_data_req_neg_reply = + hci::RemoteOobDataRequestNegativeReplyView::Create(security_command_view); ASSERT_TRUE(oob_data_req_neg_reply.IsValid()); ASSERT_EQ(OpCode::REMOTE_OOB_DATA_REQUEST_NEGATIVE_REPLY, oob_data_req_neg_reply.GetOpCode()); ReceiveSimplePairingComplete(hci::ErrorCode::AUTHENTICATION_FAILURE, device_); } // CreateBondOutOfBand no_input_no_output + no_input_no_output OOB Data P192 -TEST_F(ClassicPairingHandlerTest, locally_initiatied_no_input_no_output_no_input_no_output_p192_oob_data) { +TEST_F(ClassicPairingHandlerTest, + locally_initiatied_no_input_no_output_no_input_no_output_p192_oob_data) { hci::IoCapability injected_io_capability = hci::IoCapability::NO_INPUT_NO_OUTPUT; - hci::AuthenticationRequirements injected_authentication_requirements = hci::AuthenticationRequirements::NO_BONDING; - pairing::OobData oob_data( - {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}); - pairing_handler_->Initiate( - true, injected_io_capability, injected_authentication_requirements, oob_data, pairing::OobData()); + hci::AuthenticationRequirements injected_authentication_requirements = + hci::AuthenticationRequirements::NO_BONDING; + pairing::OobData oob_data({1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, + {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}); + pairing_handler_->Initiate(true, injected_io_capability, injected_authentication_requirements, + oob_data, pairing::OobData()); ReceiveLinkKeyRequest(device_); auto security_command_view = GetLastCommand(hci_layer_); @@ -648,12 +679,11 @@ TEST_F(ClassicPairingHandlerTest, locally_initiatied_no_input_no_output_no_input ASSERT_TRUE(io_cap_request_reply.IsValid()); ASSERT_EQ(injected_io_capability, io_cap_request_reply.GetIoCapability()); ASSERT_EQ(hci::OobDataPresent::P_192_PRESENT, io_cap_request_reply.GetOobPresent()); - ASSERT_EQ(injected_authentication_requirements, io_cap_request_reply.GetAuthenticationRequirements()); - ReceiveIoCapabilityResponse( - device_, - hci::IoCapability::NO_INPUT_NO_OUTPUT, - hci::OobDataPresent::NOT_PRESENT, - hci::AuthenticationRequirements::NO_BONDING); + ASSERT_EQ(injected_authentication_requirements, + io_cap_request_reply.GetAuthenticationRequirements()); + ReceiveIoCapabilityResponse(device_, hci::IoCapability::NO_INPUT_NO_OUTPUT, + hci::OobDataPresent::NOT_PRESENT, + hci::AuthenticationRequirements::NO_BONDING); // At this point the pairing handler thinks it has NOT_PRESENT ReceiveOobDataRequest(device_); security_command_view = GetLastCommand(hci_layer_); @@ -673,13 +703,15 @@ TEST_F(ClassicPairingHandlerTest, locally_initiatied_no_input_no_output_no_input } // CreateBondOutOfBand no_input_no_output + no_input_no_output OOB Data P256 -TEST_F(ClassicPairingHandlerTest, locally_initiatied_no_input_no_output_no_input_no_output_p256_oob_data) { +TEST_F(ClassicPairingHandlerTest, + locally_initiatied_no_input_no_output_no_input_no_output_p256_oob_data) { hci::IoCapability injected_io_capability = hci::IoCapability::NO_INPUT_NO_OUTPUT; - hci::AuthenticationRequirements injected_authentication_requirements = hci::AuthenticationRequirements::NO_BONDING; - pairing::OobData oob_data( - {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}); - pairing_handler_->Initiate( - true, injected_io_capability, injected_authentication_requirements, pairing::OobData(), oob_data); + hci::AuthenticationRequirements injected_authentication_requirements = + hci::AuthenticationRequirements::NO_BONDING; + pairing::OobData oob_data({1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, + {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}); + pairing_handler_->Initiate(true, injected_io_capability, injected_authentication_requirements, + pairing::OobData(), oob_data); ReceiveLinkKeyRequest(device_); auto security_command_view = GetLastCommand(hci_layer_); auto link_key_neg_reply = hci::LinkKeyRequestNegativeReplyView::Create(security_command_view); @@ -692,16 +724,16 @@ TEST_F(ClassicPairingHandlerTest, locally_initiatied_no_input_no_output_no_input ASSERT_TRUE(io_cap_request_reply.IsValid()); ASSERT_EQ(injected_io_capability, io_cap_request_reply.GetIoCapability()); ASSERT_EQ(hci::OobDataPresent::P_256_PRESENT, io_cap_request_reply.GetOobPresent()); - ASSERT_EQ(injected_authentication_requirements, io_cap_request_reply.GetAuthenticationRequirements()); - ReceiveIoCapabilityResponse( - device_, - hci::IoCapability::NO_INPUT_NO_OUTPUT, - hci::OobDataPresent::NOT_PRESENT, - hci::AuthenticationRequirements::NO_BONDING); + ASSERT_EQ(injected_authentication_requirements, + io_cap_request_reply.GetAuthenticationRequirements()); + ReceiveIoCapabilityResponse(device_, hci::IoCapability::NO_INPUT_NO_OUTPUT, + hci::OobDataPresent::NOT_PRESENT, + hci::AuthenticationRequirements::NO_BONDING); // At this point the pairing handler thinks it has NOT_PRESENT ReceiveOobDataRequest(device_); security_command_view = GetLastCommand(hci_layer_); - auto oob_data_req_reply = hci::RemoteOobExtendedDataRequestReplyView::Create(security_command_view); + auto oob_data_req_reply = + hci::RemoteOobExtendedDataRequestReplyView::Create(security_command_view); ASSERT_TRUE(oob_data_req_reply.IsValid()); ASSERT_EQ(OpCode::REMOTE_OOB_EXTENDED_DATA_REQUEST_REPLY, oob_data_req_reply.GetOpCode()); ReceiveSimplePairingComplete(hci::ErrorCode::SUCCESS, device_); @@ -715,12 +747,15 @@ TEST_F(ClassicPairingHandlerTest, locally_initiatied_no_input_no_output_no_input } // CreateBondOutOfBand no_input_no_output + no_input_no_output OOB Data P192 and 256 -TEST_F(ClassicPairingHandlerTest, locally_initiatied_no_input_no_output_no_input_no_output_p192_and_256_oob_data) { +TEST_F(ClassicPairingHandlerTest, + locally_initiatied_no_input_no_output_no_input_no_output_p192_and_256_oob_data) { hci::IoCapability injected_io_capability = hci::IoCapability::NO_INPUT_NO_OUTPUT; - hci::AuthenticationRequirements injected_authentication_requirements = hci::AuthenticationRequirements::NO_BONDING; - pairing::OobData oob_data( - {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}); - pairing_handler_->Initiate(true, injected_io_capability, injected_authentication_requirements, oob_data, oob_data); + hci::AuthenticationRequirements injected_authentication_requirements = + hci::AuthenticationRequirements::NO_BONDING; + pairing::OobData oob_data({1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, + {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}); + pairing_handler_->Initiate(true, injected_io_capability, injected_authentication_requirements, + oob_data, oob_data); ReceiveLinkKeyRequest(device_); auto security_command_view = GetLastCommand(hci_layer_); auto link_key_neg_reply = hci::LinkKeyRequestNegativeReplyView::Create(security_command_view); @@ -733,16 +768,16 @@ TEST_F(ClassicPairingHandlerTest, locally_initiatied_no_input_no_output_no_input ASSERT_TRUE(io_cap_request_reply.IsValid()); ASSERT_EQ(injected_io_capability, io_cap_request_reply.GetIoCapability()); ASSERT_EQ(hci::OobDataPresent::P_192_AND_256_PRESENT, io_cap_request_reply.GetOobPresent()); - ASSERT_EQ(injected_authentication_requirements, io_cap_request_reply.GetAuthenticationRequirements()); - ReceiveIoCapabilityResponse( - device_, - hci::IoCapability::NO_INPUT_NO_OUTPUT, - hci::OobDataPresent::NOT_PRESENT, - hci::AuthenticationRequirements::NO_BONDING); + ASSERT_EQ(injected_authentication_requirements, + io_cap_request_reply.GetAuthenticationRequirements()); + ReceiveIoCapabilityResponse(device_, hci::IoCapability::NO_INPUT_NO_OUTPUT, + hci::OobDataPresent::NOT_PRESENT, + hci::AuthenticationRequirements::NO_BONDING); // At this point the pairing handler thinks it has NOT_PRESENT ReceiveOobDataRequest(device_); security_command_view = GetLastCommand(hci_layer_); - auto oob_data_req_reply = hci::RemoteOobExtendedDataRequestReplyView::Create(security_command_view); + auto oob_data_req_reply = + hci::RemoteOobExtendedDataRequestReplyView::Create(security_command_view); ASSERT_TRUE(oob_data_req_reply.IsValid()); ASSERT_EQ(OpCode::REMOTE_OOB_EXTENDED_DATA_REQUEST_REPLY, oob_data_req_reply.GetOpCode()); ReceiveSimplePairingComplete(hci::ErrorCode::SUCCESS, device_); diff --git a/system/gd/security/pairing/oob_data.h b/system/gd/security/pairing/oob_data.h index 3d75196d806..bd75e59c0e9 100644 --- a/system/gd/security/pairing/oob_data.h +++ b/system/gd/security/pairing/oob_data.h @@ -28,24 +28,20 @@ using SimplePairingHash = std::array; using SimplePairingRandomizer = std::array; class OobData { - public: +public: OobData() {} OobData(SimplePairingHash C, SimplePairingRandomizer R) : C_(C), R_(R) {} - SimplePairingHash GetC() { - return C_; - } + SimplePairingHash GetC() { return C_; } - SimplePairingRandomizer GetR() { - return R_; - } + SimplePairingRandomizer GetR() { return R_; } bool IsValid() { return !std::all_of(C_.begin(), C_.end(), [](uint8_t b) { return b == 0; }) && !std::all_of(R_.begin(), R_.end(), [](uint8_t b) { return b == 0; }); } - private: +private: SimplePairingHash C_ = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; SimplePairingRandomizer R_ = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; }; diff --git a/system/gd/security/pairing/pairing_handler.h b/system/gd/security/pairing/pairing_handler.h index b3e4eb6c036..795d11f1dd1 100644 --- a/system/gd/security/pairing/pairing_handler.h +++ b/system/gd/security/pairing/pairing_handler.h @@ -40,23 +40,19 @@ namespace pairing { *

Extend this class in order to implement a new style of pairing. */ class PairingHandler : public UICallbacks { - public: - PairingHandler( - channel::SecurityManagerChannel* security_manager_channel, - std::shared_ptr record, - neighbor::NameDbModule* name_db_module) +public: + PairingHandler(channel::SecurityManagerChannel* security_manager_channel, + std::shared_ptr record, + neighbor::NameDbModule* name_db_module) : security_manager_channel_(security_manager_channel), record_(std::move(record)), name_db_module_(name_db_module) {} ~PairingHandler() = default; // Classic - virtual void Initiate( - bool locally_initiated, - hci::IoCapability io_capability, - hci::AuthenticationRequirements auth_requirements, - OobData local_p192_oob_data, - OobData local_p256_oob_data) = 0; + virtual void Initiate(bool locally_initiated, hci::IoCapability io_capability, + hci::AuthenticationRequirements auth_requirements, + OobData local_p192_oob_data, OobData local_p256_oob_data) = 0; virtual void Cancel() = 0; virtual void OnReceive(hci::ChangeConnectionLinkKeyCompleteView packet) = 0; virtual void OnReceive(hci::CentralLinkKeyCompleteView packet) = 0; @@ -75,23 +71,19 @@ class PairingHandler : public UICallbacks { virtual void OnReceive(hci::UserConfirmationRequestView packet) = 0; virtual void OnReceive(hci::UserPasskeyRequestView packet) = 0; - virtual void OnPairingPromptAccepted(const bluetooth::hci::AddressWithType& address, bool confirmed) = 0; + virtual void OnPairingPromptAccepted(const bluetooth::hci::AddressWithType& address, + bool confirmed) = 0; virtual void OnConfirmYesNo(const bluetooth::hci::AddressWithType& address, bool confirmed) = 0; virtual void OnPasskeyEntry(const bluetooth::hci::AddressWithType& address, uint32_t passkey) = 0; - virtual void OnPinEntry(const bluetooth::hci::AddressWithType& address, std::vector pin) override = 0; + virtual void OnPinEntry(const bluetooth::hci::AddressWithType& address, + std::vector pin) override = 0; - protected: - std::shared_ptr GetRecord() { - return record_; - } - channel::SecurityManagerChannel* GetChannel() { - return security_manager_channel_; - } - neighbor::NameDbModule* GetNameDbModule() { - return name_db_module_; - } +protected: + std::shared_ptr GetRecord() { return record_; } + channel::SecurityManagerChannel* GetChannel() { return security_manager_channel_; } + neighbor::NameDbModule* GetNameDbModule() { return name_db_module_; } - private: +private: channel::SecurityManagerChannel* security_manager_channel_ __attribute__((unused)); std::shared_ptr record_ __attribute__((unused)); neighbor::NameDbModule* name_db_module_; diff --git a/system/gd/security/pairing_failure.h b/system/gd/security/pairing_failure.h index fc1a4f9091e..1b671d91cee 100644 --- a/system/gd/security/pairing_failure.h +++ b/system/gd/security/pairing_failure.h @@ -27,9 +27,10 @@ namespace security { /* This structure holds the information about the failure in case of airing failure */ struct PairingFailure { - /* A place in code that triggered this failure. It can be modified by functions that pass the error to a location that - * better reflect the current state of flow. i.e. instead of generic location responsible for waiting for packet, - * replace it with location of receiving specific packet in a specific flow */ + /* A place in code that triggered this failure. It can be modified by functions that pass the + * error to a location that better reflect the current state of flow. i.e. instead of generic + * location responsible for waiting for packet, replace it with location of receiving specific + * packet in a specific flow */ // base::Location location; /* This is the failure message, that will be passed, either into upper layers, @@ -46,10 +47,12 @@ struct PairingFailure { PairingFailure(/*const base::Location& location, */ const std::string& message) : /*location(location), */ message(message) {} - PairingFailure(/*const base::Location& location, */ const std::string& message, Code received_code) + PairingFailure(/*const base::Location& location, */ const std::string& message, + Code received_code) : /*location(location), */ message(message), received_code_(received_code) {} - PairingFailure(/*const base::Location& location, */ const std::string& message, PairingFailedReason reason) + PairingFailure(/*const base::Location& location, */ const std::string& message, + PairingFailedReason reason) : /*location(location),*/ message(message), reason(reason) {} }; diff --git a/system/gd/security/pairing_handler_le.cc b/system/gd/security/pairing_handler_le.cc index 5af44657a05..8bb11eb6480 100644 --- a/system/gd/security/pairing_handler_le.cc +++ b/system/gd/security/pairing_handler_le.cc @@ -42,7 +42,8 @@ void PairingHandlerLe::PairingMain(InitialInformations i) { if (i.remotely_initiated) { log::info("Was remotely initiated, presenting user with the accept prompt"); - i.user_interface_handler->Post(common::BindOnce(&UI::DisplayPairingPrompt, common::Unretained(i.user_interface), + i.user_interface_handler->Post(common::BindOnce(&UI::DisplayPairingPrompt, + common::Unretained(i.user_interface), i.remote_connection_address, i.remote_name)); // If pairing was initiated by remote device, wait for the user to accept @@ -53,19 +54,22 @@ void PairingHandlerLe::PairingMain(InitialInformations i) { log::info("User either did not accept the remote pairing, or the prompt timed out"); // TODO: Uncomment this one once we find a way to attempt to send packet when the link is down // SendL2capPacket(i, PairingFailedBuilder::Create(PairingFailedReason::UNSPECIFIED_REASON)); - i.OnPairingFinished(PairingFailure("User either did not accept the remote pairing, or the prompt timed out")); + i.OnPairingFinished(PairingFailure( + "User either did not accept the remote pairing, or the prompt timed out")); return; } log::info("Pairing prompt accepted"); } - /************************************************ PHASE 1 *********************************************************/ + /************************************************ PHASE 1 + * *********************************************************/ Phase1ResultOrFailure phase_1_result = ExchangePairingFeature(i); if (std::holds_alternative(phase_1_result)) { log::warn("Pairing failed in phase 1"); - // We already send pairing fialed in lower layer. Which one should do that ? how about disconneciton? - // SendL2capPacket(i, PairingFailedBuilder::Create(PairingFailedReason::UNSPECIFIED_REASON)); + // We already send pairing fialed in lower layer. Which one should do that ? how about + // disconneciton? SendL2capPacket(i, + // PairingFailedBuilder::Create(PairingFailedReason::UNSPECIFIED_REASON)); // TODO: disconnect? i.OnPairingFinished(std::get(phase_1_result)); return; @@ -73,20 +77,23 @@ void PairingHandlerLe::PairingMain(InitialInformations i) { auto [pairing_request, pairing_response] = std::get(phase_1_result); - uint8_t key_size = - std::min(pairing_request.GetMaximumEncryptionKeySize(), pairing_response.GetMaximumEncryptionKeySize()); + uint8_t key_size = std::min(pairing_request.GetMaximumEncryptionKeySize(), + pairing_response.GetMaximumEncryptionKeySize()); if (key_size < 7 || key_size > 16) { log::warn("Resulting key size is bad {}", key_size); SendL2capPacket(i, PairingFailedBuilder::Create(PairingFailedReason::ENCRYPTION_KEY_SIZE)); - i.OnPairingFinished(PairingFailure("Resulting key size is bad", PairingFailedReason::ENCRYPTION_KEY_SIZE)); + i.OnPairingFinished( + PairingFailure("Resulting key size is bad", PairingFailedReason::ENCRYPTION_KEY_SIZE)); return; } if (key_size != 16) { log::warn("Resulting key size is less than 16 octets!"); } - /************************************************ PHASE 2 *********************************************************/ - bool isSecureConnections = pairing_request.GetAuthReq() & pairing_response.GetAuthReq() & AuthReqMaskSc; + /************************************************ PHASE 2 + * *********************************************************/ + bool isSecureConnections = + pairing_request.GetAuthReq() & pairing_response.GetAuthReq() & AuthReqMaskSc; if (isSecureConnections) { // 2.3.5.6 LE Secure Connections pairing phase 2 log::info("Pairing Phase 2 LE Secure connections Started"); @@ -101,7 +108,7 @@ void PairingHandlerLe::PairingMain(InitialInformations i) { */ OobDataFlag remote_have_oob_data = - IAmCentral(i) ? pairing_response.GetOobDataFlag() : pairing_request.GetOobDataFlag(); + IAmCentral(i) ? pairing_response.GetOobDataFlag() : pairing_request.GetOobDataFlag(); auto key_exchange_result = ExchangePublicKeys(i, remote_have_oob_data); if (std::holds_alternative(key_exchange_result)) { @@ -113,14 +120,16 @@ void PairingHandlerLe::PairingMain(InitialInformations i) { // Public key exchange finished, Diffie-Hellman key computed. - Stage1ResultOrFailure stage1result = DoSecureConnectionsStage1(i, PKa, PKb, pairing_request, pairing_response); + Stage1ResultOrFailure stage1result = + DoSecureConnectionsStage1(i, PKa, PKb, pairing_request, pairing_response); if (std::holds_alternative(stage1result)) { i.OnPairingFinished(std::get(stage1result)); return; } - Stage2ResultOrFailure stage_2_result = DoSecureConnectionsStage2(i, PKa, PKb, pairing_request, pairing_response, - std::get(stage1result), dhkey); + Stage2ResultOrFailure stage_2_result = + DoSecureConnectionsStage2(i, PKa, PKb, pairing_request, pairing_response, + std::get(stage1result), dhkey); if (std::holds_alternative(stage_2_result)) { i.OnPairingFinished(std::get(stage_2_result)); return; @@ -168,14 +177,16 @@ void PairingHandlerLe::PairingMain(InitialInformations i) { } } - /************************************************ PHASE 3 *********************************************************/ + /************************************************ PHASE 3 + * *********************************************************/ log::info("Waiting for encryption changed"); auto encryption_change_result = WaitEncryptionChanged(); if (std::holds_alternative(encryption_change_result)) { i.OnPairingFinished(std::get(encryption_change_result)); return; } else if (std::holds_alternative(encryption_change_result)) { - EncryptionChangeView encryption_changed = std::get(encryption_change_result); + EncryptionChangeView encryption_changed = + std::get(encryption_change_result); if (encryption_changed.GetStatus() != hci::ErrorCode::SUCCESS || encryption_changed.GetEncryptionEnabled() != hci::EncryptionEnabled::ON) { i.OnPairingFinished(PairingFailure("Encryption change failed")); @@ -183,7 +194,7 @@ void PairingHandlerLe::PairingMain(InitialInformations i) { } } else if (std::holds_alternative(encryption_change_result)) { EncryptionKeyRefreshCompleteView encryption_changed = - std::get(encryption_change_result); + std::get(encryption_change_result); if (encryption_changed.GetStatus() != hci::ErrorCode::SUCCESS) { i.OnPairingFinished(PairingFailure("Encryption key refresh failed")); return; @@ -194,7 +205,8 @@ void PairingHandlerLe::PairingMain(InitialInformations i) { } log::info("Encryption change finished successfully"); - DistributedKeysOrFailure keyExchangeStatus = DistributeKeys(i, pairing_response, isSecureConnections); + DistributedKeysOrFailure keyExchangeStatus = + DistributeKeys(i, pairing_response, isSecureConnections); if (std::holds_alternative(keyExchangeStatus)) { i.OnPairingFinished(std::get(keyExchangeStatus)); log::error("Key exchange failed"); @@ -209,12 +221,13 @@ void PairingHandlerLe::PairingMain(InitialInformations i) { distributed_keys.remote_link_key = link_key; } - // bool bonding = pairing_request.GetAuthReq() & pairing_response.GetAuthReq() & AuthReqMaskBondingFlag; + // bool bonding = pairing_request.GetAuthReq() & pairing_response.GetAuthReq() & + // AuthReqMaskBondingFlag; i.OnPairingFinished(PairingResult{ - .connection_address = i.remote_connection_address, - .distributed_keys = distributed_keys, - .key_size = key_size, + .connection_address = i.remote_connection_address, + .distributed_keys = distributed_keys, + .key_size = key_size, }); log::info("Pairing finished successfully."); @@ -226,9 +239,9 @@ Phase1ResultOrFailure PairingHandlerLe::ExchangePairingFeature(const InitialInfo if (IAmCentral(i)) { // Send Pairing Request const auto& x = i.myPairingCapabilities; - auto pairing_request_builder = - PairingRequestBuilder::Create(x.io_capability, x.oob_data_flag, x.auth_req, x.maximum_encryption_key_size, - x.initiator_key_distribution, x.responder_key_distribution); + auto pairing_request_builder = PairingRequestBuilder::Create( + x.io_capability, x.oob_data_flag, x.auth_req, x.maximum_encryption_key_size, + x.initiator_key_distribution, x.responder_key_distribution); // basically pairing_request = myPairingCapabilities; // Convert builder to view @@ -246,8 +259,8 @@ Phase1ResultOrFailure PairingHandlerLe::ExchangePairingFeature(const InitialInfo log::info("Waiting for Pairing Response"); auto response = WaitPairingResponse(); - /* There is a potential collision where the peripheral initiates the pairing at the same time we initiate it, by - * sending security request. */ + /* There is a potential collision where the peripheral initiates the pairing at the same time we + * initiate it, by sending security request. */ if (std::holds_alternative(response) && std::get(response).received_code_ == Code::SECURITY_REQUEST) { log::info("Received security request, waiting for Pairing Response again..."); @@ -271,12 +284,15 @@ Phase1ResultOrFailure PairingHandlerLe::ExchangePairingFeature(const InitialInfo if (i.remotely_initiated) { if (!i.pairing_request.has_value()) { - return PairingFailure("You must pass PairingRequest as a initial information to peripheral!"); + return PairingFailure( + "You must pass PairingRequest as a initial information to peripheral!"); } pairing_request = i.pairing_request.value(); - if (!pairing_request->IsValid()) return PairingFailure("Malformed PairingRequest"); + if (!pairing_request->IsValid()) { + return PairingFailure("Malformed PairingRequest"); + } } else { SendL2capPacket(i, SecurityRequestBuilder::Create(i.myPairingCapabilities.auth_req)); @@ -301,12 +317,12 @@ Phase1ResultOrFailure PairingHandlerLe::ExchangePairingFeature(const InitialInfo // Send Pairing Request const auto& x = i.myPairingCapabilities; // basically pairing_response_builder = my_first_packet; - // We are not allowed to enable bits that the remote did not allow us to set in initiator_key_dist and - // responder_key_distribution - auto pairing_response_builder = - PairingResponseBuilder::Create(x.io_capability, x.oob_data_flag, x.auth_req, x.maximum_encryption_key_size, - x.initiator_key_distribution & pairing_request->GetInitiatorKeyDistribution(), - x.responder_key_distribution & pairing_request->GetResponderKeyDistribution()); + // We are not allowed to enable bits that the remote did not allow us to set in + // initiator_key_dist and responder_key_distribution + auto pairing_response_builder = PairingResponseBuilder::Create( + x.io_capability, x.oob_data_flag, x.auth_req, x.maximum_encryption_key_size, + x.initiator_key_distribution & pairing_request->GetInitiatorKeyDistribution(), + x.responder_key_distribution & pairing_request->GetResponderKeyDistribution()); // Convert builder to view std::shared_ptr> packet_bytes = std::make_shared>(); @@ -325,13 +341,13 @@ Phase1ResultOrFailure PairingHandlerLe::ExchangePairingFeature(const InitialInfo } } -DistributedKeysOrFailure PairingHandlerLe::DistributeKeys(const InitialInformations& i, - const PairingResponseView& pairing_response, - bool isSecureConnections) { - uint8_t keys_i_receive = - IAmCentral(i) ? pairing_response.GetResponderKeyDistribution() : pairing_response.GetInitiatorKeyDistribution(); - uint8_t keys_i_send = - IAmCentral(i) ? pairing_response.GetInitiatorKeyDistribution() : pairing_response.GetResponderKeyDistribution(); +DistributedKeysOrFailure PairingHandlerLe::DistributeKeys( + const InitialInformations& i, const PairingResponseView& pairing_response, + bool isSecureConnections) { + uint8_t keys_i_receive = IAmCentral(i) ? pairing_response.GetResponderKeyDistribution() + : pairing_response.GetInitiatorKeyDistribution(); + uint8_t keys_i_send = IAmCentral(i) ? pairing_response.GetInitiatorKeyDistribution() + : pairing_response.GetResponderKeyDistribution(); // In Secure Connections on the LE Transport, the EncKey field shall be ignored if (isSecureConnections) { @@ -339,10 +355,8 @@ DistributedKeysOrFailure PairingHandlerLe::DistributeKeys(const InitialInformati keys_i_receive = (~KeyMaskEnc) & keys_i_receive; } - log::info( - "Key distribution start, keys_i_send=0x{:02x}, keys_i_receive=0x{:02x}", - keys_i_send, - keys_i_receive); + log::info("Key distribution start, keys_i_send=0x{:02x}, keys_i_receive=0x{:02x}", keys_i_send, + keys_i_receive); // TODO: obtain actual values, and apply key_size to the LTK Octet16 my_ltk = bluetooth::os::GenerateRandom<16>(); @@ -352,7 +366,7 @@ DistributedKeysOrFailure PairingHandlerLe::DistributeKeys(const InitialInformati Octet16 my_irk = i.my_identity_resolving_key; Address my_identity_address = i.my_identity_address.GetAddress(); AddrType my_identity_address_type = - static_cast(i.my_identity_address.GetAddressType()); + static_cast(i.my_identity_address.GetAddressType()); Octet16 my_signature_key{0}; if (IAmCentral(i)) { @@ -362,8 +376,8 @@ DistributedKeysOrFailure PairingHandlerLe::DistributeKeys(const InitialInformati return keys; } - SendKeys(i, keys_i_send, my_ltk, my_ediv, my_rand, my_irk, my_identity_address, my_identity_address_type, - my_signature_key); + SendKeys(i, keys_i_send, my_ltk, my_ediv, my_rand, my_irk, my_identity_address, + my_identity_address_type, my_signature_key); std::get(keys).local_ltk = my_ltk; std::get(keys).local_ediv = my_ediv; @@ -371,8 +385,8 @@ DistributedKeysOrFailure PairingHandlerLe::DistributeKeys(const InitialInformati log::info("Key distribution finish"); return keys; } else { - SendKeys(i, keys_i_send, my_ltk, my_ediv, my_rand, my_irk, my_identity_address, my_identity_address_type, - my_signature_key); + SendKeys(i, keys_i_send, my_ltk, my_ediv, my_rand, my_irk, my_identity_address, + my_identity_address_type, my_signature_key); DistributedKeysOrFailure keys = ReceiveKeys(keys_i_receive); if (std::holds_alternative(keys)) { @@ -433,9 +447,10 @@ DistributedKeysOrFailure PairingHandlerLe::ReceiveKeys(const uint8_t& keys_i_rec } log::info("Received Identity Address Information"); auto iapacketview = std::get(iapacket); - identity_address = hci::AddressWithType(iapacketview.GetBdAddr(), iapacketview.GetAddrType() == AddrType::PUBLIC - ? hci::AddressType::PUBLIC_DEVICE_ADDRESS - : hci::AddressType::RANDOM_DEVICE_ADDRESS); + identity_address = hci::AddressWithType(iapacketview.GetBdAddr(), + iapacketview.GetAddrType() == AddrType::PUBLIC + ? hci::AddressType::PUBLIC_DEVICE_ADDRESS + : hci::AddressType::RANDOM_DEVICE_ADDRESS); } if (keys_i_receive & KeyMaskSign) { @@ -457,8 +472,9 @@ DistributedKeysOrFailure PairingHandlerLe::ReceiveKeys(const uint8_t& keys_i_rec .remote_signature_key = signature_key}; } -void PairingHandlerLe::SendKeys(const InitialInformations& i, const uint8_t& keys_i_send, Octet16 ltk, uint16_t ediv, - std::array rand, Octet16 irk, Address identity_address, +void PairingHandlerLe::SendKeys(const InitialInformations& i, const uint8_t& keys_i_send, + Octet16 ltk, uint16_t ediv, std::array rand, + Octet16 irk, Address identity_address, AddrType identity_addres_type, Octet16 signature_key) { if (keys_i_send & KeyMaskEnc) { log::info("Sending Encryption Information"); @@ -471,7 +487,8 @@ void PairingHandlerLe::SendKeys(const InitialInformations& i, const uint8_t& key log::info("Sending Identity Information"); SendL2capPacket(i, IdentityInformationBuilder::Create(irk)); log::info("Sending Identity Address Information"); - SendL2capPacket(i, IdentityAddressInformationBuilder::Create(identity_addres_type, identity_address)); + SendL2capPacket( + i, IdentityAddressInformationBuilder::Create(identity_addres_type, identity_address)); } if (keys_i_send & KeyMaskSign) { diff --git a/system/gd/security/pairing_handler_le.h b/system/gd/security/pairing_handler_le.h index d62dba8402e..753e43678e8 100644 --- a/system/gd/security/pairing_handler_le.h +++ b/system/gd/security/pairing_handler_le.h @@ -58,7 +58,7 @@ namespace security { /* This class represents an event send from other subsystems into SMP Pairing Handler, * i.e. user request from the UI, L2CAP or HCI interaction */ class PairingEvent { - public: +public: enum TYPE { EXIT, L2CAP, HCI_EVENT, UI }; TYPE type; @@ -72,17 +72,19 @@ class PairingEvent { PairingEvent(TYPE type) : type(type) {} PairingEvent(CommandView l2cap_packet) : type(L2CAP), l2cap_packet(l2cap_packet) {} - PairingEvent(UI_ACTION_TYPE ui_action, uint32_t ui_value) : type(UI), ui_action(ui_action), ui_value(ui_value) {} + PairingEvent(UI_ACTION_TYPE ui_action, uint32_t ui_value) + : type(UI), ui_action(ui_action), ui_value(ui_value) {} PairingEvent(hci::EventView hci_event) : type(HCI_EVENT), hci_event(hci_event) {} }; constexpr int SMP_TIMEOUT = 30; using CommandViewOrFailure = std::variant; -using Phase1Result = std::pair; +using Phase1Result = std::pair; using Phase1ResultOrFailure = std::variant; -using KeyExchangeResult = - std::tuple /*dhkey*/>; +using KeyExchangeResult = std::tuple /*dhkey*/>; using Stage1Result = std::tuple; using Stage1ResultOrFailure = std::variant; using Stage2ResultOrFailure = std::variant; @@ -100,7 +102,7 @@ using StkOrFailure = std::variant; * phases. */ class PairingHandlerLe { - public: +public: // This is the phase of pairing as defined in BT Spec (with exception of // accept prompt) // * ACCEPT_PROMPT - we're waiting for the user to accept remotely initiated pairing @@ -118,45 +120,51 @@ class PairingHandlerLe { SendExitSignal(); // we need ot check if thread is joinable, because tests call join form // within WaitUntilPairingFinished - if (thread_.joinable()) thread_.join(); + if (thread_.joinable()) { + thread_.join(); + } } void PairingMain(InitialInformations i); Phase1ResultOrFailure ExchangePairingFeature(const InitialInformations& i); - void SendL2capPacket(const InitialInformations& i, std::unique_ptr command) { + void SendL2capPacket(const InitialInformations& i, + std::unique_ptr command) { i.proper_l2cap_interface->Enqueue(std::move(command), i.l2cap_handler); } - void SendHciLeStartEncryption( - const InitialInformations& i, - uint16_t conn_handle, - const std::array& rand, - const uint16_t& ediv, - const hci::Octet16& ltk) { - i.le_security_interface->EnqueueCommand(hci::LeStartEncryptionBuilder::Create(conn_handle, rand, ediv, ltk), - i.l2cap_handler->BindOnce([](hci::CommandStatusView) { - // TODO: handle command status. It's important - can show we are not - // connected any more. - - // TODO: if anything useful must be done there, use some sort of proper - // handler, wait/notify, and execute on the handler thread - })); + void SendHciLeStartEncryption(const InitialInformations& i, uint16_t conn_handle, + const std::array& rand, const uint16_t& ediv, + const hci::Octet16& ltk) { + i.le_security_interface->EnqueueCommand( + hci::LeStartEncryptionBuilder::Create(conn_handle, rand, ediv, ltk), + i.l2cap_handler->BindOnce([](hci::CommandStatusView) { + // TODO: handle command status. It's important - can show we are not + // connected any more. + + // TODO: if anything useful must be done there, use some sort of proper + // handler, wait/notify, and execute on the handler thread + })); } - void SendHciLeLongTermKeyReply( - const InitialInformations& i, uint16_t conn_handle, const hci::Octet16& ltk) { + void SendHciLeLongTermKeyReply(const InitialInformations& i, uint16_t conn_handle, + const hci::Octet16& ltk) { i.le_security_interface->EnqueueCommand( - hci::LeLongTermKeyRequestReplyBuilder::Create(conn_handle, ltk), - i.l2cap_handler->BindOnce([](hci::CommandCompleteView) {})); + hci::LeLongTermKeyRequestReplyBuilder::Create(conn_handle, ltk), + i.l2cap_handler->BindOnce([](hci::CommandCompleteView) {})); } - std::variant WaitEncryptionChanged() { + std::variant + WaitEncryptionChanged() { PairingEvent e = WaitForEvent(); - if (e.type != PairingEvent::HCI_EVENT) return PairingFailure("Was expecting HCI event but received something else"); + if (e.type != PairingEvent::HCI_EVENT) { + return PairingFailure("Was expecting HCI event but received something else"); + } - if (!e.hci_event->IsValid()) return PairingFailure("Received invalid HCI event"); + if (!e.hci_event->IsValid()) { + return PairingFailure("Received invalid HCI event"); + } if (e.hci_event->GetEventCode() == hci::EventCode::ENCRYPTION_CHANGE) { EncryptionChangeView enc_chg_packet = EncryptionChangeView::Create(*e.hci_event); @@ -167,23 +175,31 @@ class PairingHandlerLe { } if (e.hci_event->GetEventCode() == hci::EventCode::ENCRYPTION_KEY_REFRESH_COMPLETE) { - hci::EncryptionKeyRefreshCompleteView enc_packet = EncryptionKeyRefreshCompleteView::Create(*e.hci_event); + hci::EncryptionKeyRefreshCompleteView enc_packet = + EncryptionKeyRefreshCompleteView::Create(*e.hci_event); if (!enc_packet.IsValid()) { return PairingFailure("Invalid Key Refresh packet received"); } return enc_packet; } - return PairingFailure("Was expecting Encryption Change or Key Refresh Complete but received something else"); + return PairingFailure( + "Was expecting Encryption Change or Key Refresh Complete but received something else"); } std::variant WaitLeLongTermKeyRequest() { PairingEvent e = WaitForEvent(); - if (e.type != PairingEvent::HCI_EVENT) return PairingFailure("Was expecting HCI event but received something else"); + if (e.type != PairingEvent::HCI_EVENT) { + return PairingFailure("Was expecting HCI event but received something else"); + } - if (!e.hci_event->IsValid()) return PairingFailure("Received invalid HCI event"); + if (!e.hci_event->IsValid()) { + return PairingFailure("Received invalid HCI event"); + } - if (e.hci_event->GetEventCode() != hci::EventCode::LE_META_EVENT) return PairingFailure("Was expecting LE event"); + if (e.hci_event->GetEventCode() != hci::EventCode::LE_META_EVENT) { + return PairingFailure("Was expecting LE event"); + } hci::LeMetaEventView le_event = hci::LeMetaEventView::Create(*e.hci_event); if (!le_event.IsValid()) { @@ -202,68 +218,68 @@ class PairingHandlerLe { return ltk_req_packet; } - inline bool IAmCentral(const InitialInformations& i) { - return i.my_role == hci::Role::CENTRAL; - } + inline bool IAmCentral(const InitialInformations& i) { return i.my_role == hci::Role::CENTRAL; } /* This function generates data that should be passed to remote device, except the private key. */ static MyOobData GenerateOobData(); - std::variant ExchangePublicKeys(const InitialInformations& i, - OobDataFlag remote_have_oob_data); + std::variant ExchangePublicKeys( + const InitialInformations& i, OobDataFlag remote_have_oob_data); - Stage1ResultOrFailure DoSecureConnectionsStage1(const InitialInformations& i, const EcdhPublicKey& PKa, - const EcdhPublicKey& PKb, const PairingRequestView& pairing_request, + Stage1ResultOrFailure DoSecureConnectionsStage1(const InitialInformations& i, + const EcdhPublicKey& PKa, + const EcdhPublicKey& PKb, + const PairingRequestView& pairing_request, const PairingResponseView& pairing_response); - Stage1ResultOrFailure SecureConnectionsNumericComparison(const InitialInformations& i, const EcdhPublicKey& PKa, + Stage1ResultOrFailure SecureConnectionsNumericComparison(const InitialInformations& i, + const EcdhPublicKey& PKa, const EcdhPublicKey& PKb); - Stage1ResultOrFailure SecureConnectionsJustWorks(const InitialInformations& i, const EcdhPublicKey& PKa, + Stage1ResultOrFailure SecureConnectionsJustWorks(const InitialInformations& i, + const EcdhPublicKey& PKa, const EcdhPublicKey& PKb); - Stage1ResultOrFailure SecureConnectionsPasskeyEntry(const InitialInformations& i, const EcdhPublicKey& PKa, - const EcdhPublicKey& PKb, IoCapability my_iocaps, + Stage1ResultOrFailure SecureConnectionsPasskeyEntry(const InitialInformations& i, + const EcdhPublicKey& PKa, + const EcdhPublicKey& PKb, + IoCapability my_iocaps, IoCapability remote_iocaps); - Stage1ResultOrFailure SecureConnectionsOutOfBand(const InitialInformations& i, const EcdhPublicKey& Pka, - const EcdhPublicKey& Pkb, OobDataFlag my_oob_flag, + Stage1ResultOrFailure SecureConnectionsOutOfBand(const InitialInformations& i, + const EcdhPublicKey& Pka, + const EcdhPublicKey& Pkb, + OobDataFlag my_oob_flag, OobDataFlag remote_oob_flag); - Stage2ResultOrFailure DoSecureConnectionsStage2(const InitialInformations& i, const EcdhPublicKey& PKa, - const EcdhPublicKey& PKb, const PairingRequestView& pairing_request, - const PairingResponseView& pairing_response, - const Stage1Result stage1result, - const std::array& dhkey); + Stage2ResultOrFailure DoSecureConnectionsStage2( + const InitialInformations& i, const EcdhPublicKey& PKa, const EcdhPublicKey& PKb, + const PairingRequestView& pairing_request, const PairingResponseView& pairing_response, + const Stage1Result stage1result, const std::array& dhkey); - DistributedKeysOrFailure DistributeKeys(const InitialInformations& i, const PairingResponseView& pairing_response, + DistributedKeysOrFailure DistributeKeys(const InitialInformations& i, + const PairingResponseView& pairing_response, bool isSecureConnections); DistributedKeysOrFailure ReceiveKeys(const uint8_t& keys_i_receive); - LegacyStage1ResultOrFailure DoLegacyStage1(const InitialInformations& i, const PairingRequestView& pairing_request, + LegacyStage1ResultOrFailure DoLegacyStage1(const InitialInformations& i, + const PairingRequestView& pairing_request, const PairingResponseView& pairing_response); LegacyStage1ResultOrFailure LegacyOutOfBand(const InitialInformations& i); LegacyStage1ResultOrFailure LegacyJustWorks(); - LegacyStage1ResultOrFailure LegacyPasskeyEntry(const InitialInformations& i, const IoCapability& my_iocaps, + LegacyStage1ResultOrFailure LegacyPasskeyEntry(const InitialInformations& i, + const IoCapability& my_iocaps, const IoCapability& remote_iocaps); - StkOrFailure DoLegacyStage2( - const InitialInformations& i, - const PairingRequestView& pairing_request, - const PairingResponseView& pairing_response, - const hci::Octet16& tk); - - void SendKeys( - const InitialInformations& i, - const uint8_t& keys_i_send, - hci::Octet16 ltk, - uint16_t ediv, - std::array rand, - hci::Octet16 irk, - Address identity_address, - AddrType identity_addres_type, - hci::Octet16 signature_key); + StkOrFailure DoLegacyStage2(const InitialInformations& i, + const PairingRequestView& pairing_request, + const PairingResponseView& pairing_response, const hci::Octet16& tk); + + void SendKeys(const InitialInformations& i, const uint8_t& keys_i_send, hci::Octet16 ltk, + uint16_t ediv, std::array rand, hci::Octet16 irk, + Address identity_address, AddrType identity_addres_type, + hci::Octet16 signature_key); /* This can be called from any thread to immediately finish the pairing in progress. */ void SendExitSignal() { @@ -320,7 +336,8 @@ class PairingHandlerLe { return e; } // This releases the lock while blocking. - if (pairing_thread_blocker_.wait_for(lock, std::chrono::seconds(SMP_TIMEOUT)) == std::cv_status::timeout) { + if (pairing_thread_blocker_.wait_for(lock, std::chrono::seconds(SMP_TIMEOUT)) == + std::cv_status::timeout) { return PairingEvent(PairingEvent::EXIT); } @@ -329,8 +346,7 @@ class PairingHandlerLe { std::optional WaitUiPairingAccept() { PairingEvent e = WaitForEvent(); - if (e.type == PairingEvent::UI && - e.ui_action == PairingEvent::PAIRING_ACCEPTED) { + if (e.type == PairingEvent::UI && e.ui_action == PairingEvent::PAIRING_ACCEPTED) { return e; } else { return std::nullopt; @@ -339,8 +355,7 @@ class PairingHandlerLe { std::optional WaitUiConfirmYesNo() { PairingEvent e = WaitForEvent(); - if (e.type == PairingEvent::UI && - e.ui_action == PairingEvent::CONFIRM_YESNO) { + if (e.type == PairingEvent::UI && e.ui_action == PairingEvent::CONFIRM_YESNO) { return e; } else { return std::nullopt; @@ -375,8 +390,7 @@ class PairingHandlerLe { e = WaitForEvent(); } - if (e.type == PairingEvent::UI && - e.ui_action == PairingEvent::PASSKEY) { + if (e.type == PairingEvent::UI && e.ui_action == PairingEvent::PASSKEY) { return e; } else { return std::nullopt; @@ -448,15 +462,18 @@ class PairingHandlerLe { switch (e.type) { case PairingEvent::EXIT: return PairingFailure( - /*FROM_HERE,*/ "Was expecting L2CAP Packet " + CodeText(CODE) + ", but received EXIT instead"); + /*FROM_HERE,*/ "Was expecting L2CAP Packet " + CodeText(CODE) + + ", but received EXIT instead"); case PairingEvent::HCI_EVENT: return PairingFailure( - /*FROM_HERE,*/ "Was expecting L2CAP Packet " + CodeText(CODE) + ", but received HCI_EVENT instead"); + /*FROM_HERE,*/ "Was expecting L2CAP Packet " + CodeText(CODE) + + ", but received HCI_EVENT instead"); case PairingEvent::UI: return PairingFailure( - /*FROM_HERE,*/ "Was expecting L2CAP Packet " + CodeText(CODE) + ", but received UI instead"); + /*FROM_HERE,*/ "Was expecting L2CAP Packet " + CodeText(CODE) + + ", but received UI instead"); case PairingEvent::L2CAP: { auto l2cap_packet = e.l2cap_packet.value(); @@ -468,34 +485,36 @@ class PairingHandlerLe { if (received_code != CODE) { if (received_code == Code::PAIRING_FAILED) { auto pkt = PairingFailedView::Create(l2cap_packet); - if (!pkt.IsValid()) return PairingFailure("Malformed " + CodeText(CODE) + " packet"); + if (!pkt.IsValid()) { + return PairingFailure("Malformed " + CodeText(CODE) + " packet"); + } return PairingFailure(/*FROM_HERE,*/ - "Was expecting " + CodeText(CODE) + ", but received PAIRING_FAILED instead", + "Was expecting " + CodeText(CODE) + + ", but received PAIRING_FAILED instead", pkt.GetReason()); } return PairingFailure(/*FROM_HERE,*/ - "Was expecting " + CodeText(CODE) + ", but received " + CodeText(received_code) + - " instead", + "Was expecting " + CodeText(CODE) + ", but received " + + CodeText(received_code) + " instead", received_code); } auto pkt = CodeToPacketView::type::Create(l2cap_packet); - if (!pkt.IsValid()) return PairingFailure("Malformed " + CodeText(CODE) + " packet"); + if (!pkt.IsValid()) { + return PairingFailure("Malformed " + CodeText(CODE) + " packet"); + } return pkt; } } } - auto WaitPairingRequest() { - return WaitPacket(); - } + auto WaitPairingRequest() { return WaitPacket(); } - auto WaitPairingResponse() { - return WaitPacket(); - } + auto WaitPairingResponse() { return WaitPacket(); } - std::variant WaitPairingConfirm() { + std::variant + WaitPairingConfirm() { if (cached_pariring_confirm_view) { PairingConfirmView pkt = *cached_pariring_confirm_view; cached_pariring_confirm_view.release(); @@ -504,48 +523,28 @@ class PairingHandlerLe { return WaitPacket(); } - auto WaitPairingRandom() { - return WaitPacket(); - } + auto WaitPairingRandom() { return WaitPacket(); } - auto WaitPairingPublicKey() { - return WaitPacket(); - } + auto WaitPairingPublicKey() { return WaitPacket(); } - auto WaitPairingDHKeyCheck() { - return WaitPacket(); - } + auto WaitPairingDHKeyCheck() { return WaitPacket(); } - auto WaitEncryptionInformationRequest() { - return WaitPacket(); - } + auto WaitEncryptionInformationRequest() { return WaitPacket(); } - auto WaitEncryptionInformation() { - return WaitPacket(); - } + auto WaitEncryptionInformation() { return WaitPacket(); } - auto WaitCentralIdentification() { - return WaitPacket(); - } + auto WaitCentralIdentification() { return WaitPacket(); } - auto WaitIdentityInformation() { - return WaitPacket(); - } + auto WaitIdentityInformation() { return WaitPacket(); } - auto WaitIdentityAddressInformation() { - return WaitPacket(); - } + auto WaitIdentityAddressInformation() { return WaitPacket(); } - auto WaitSigningInformation() { - return WaitPacket(); - } + auto WaitSigningInformation() { return WaitPacket(); } /* This is just for test, never use in production code! */ - void WaitUntilPairingFinished() { - thread_.join(); - } + void WaitUntilPairingFinished() { thread_.join(); } - private: +private: std::condition_variable pairing_thread_blocker_; std::mutex queue_guard; diff --git a/system/gd/security/pairing_handler_le_legacy.cc b/system/gd/security/pairing_handler_le_legacy.cc index 9e28ce6a116..da35d83b81f 100644 --- a/system/gd/security/pairing_handler_le_legacy.cc +++ b/system/gd/security/pairing_handler_le_legacy.cc @@ -29,9 +29,9 @@ namespace security { using hci::Octet16; -LegacyStage1ResultOrFailure PairingHandlerLe::DoLegacyStage1(const InitialInformations& i, - const PairingRequestView& pairing_request, - const PairingResponseView& pairing_response) { +LegacyStage1ResultOrFailure PairingHandlerLe::DoLegacyStage1( + const InitialInformations& i, const PairingRequestView& pairing_request, + const PairingResponseView& pairing_response) { if (((pairing_request.GetAuthReq() | pairing_response.GetAuthReq()) & AuthReqMaskMitm) == 0) { // If both devices have not set MITM option, Just Works shall be used return LegacyJustWorks(); @@ -40,8 +40,8 @@ LegacyStage1ResultOrFailure PairingHandlerLe::DoLegacyStage1(const InitialInform if (pairing_request.GetOobDataFlag() == OobDataFlag::PRESENT && pairing_response.GetOobDataFlag() == OobDataFlag::PRESENT) { // OobDataFlag remote_oob_flag = IAmCentral(i) ? pairing_response.GetOobDataFlag() : - // pairing_request.GetOobDataFlag(); OobDataFlag my_oob_flag = IAmCentral(i) ? pairing_request.GetOobDataFlag() : - // pairing_response.GetOobDataFlag(); + // pairing_request.GetOobDataFlag(); OobDataFlag my_oob_flag = IAmCentral(i) ? + // pairing_request.GetOobDataFlag() : pairing_response.GetOobDataFlag(); return LegacyOutOfBand(i); } @@ -75,16 +75,17 @@ LegacyStage1ResultOrFailure PairingHandlerLe::LegacyJustWorks() { return Octet16{0}; } -LegacyStage1ResultOrFailure PairingHandlerLe::LegacyPasskeyEntry(const InitialInformations& i, - const IoCapability& my_iocaps, - const IoCapability& remote_iocaps) { +LegacyStage1ResultOrFailure PairingHandlerLe::LegacyPasskeyEntry( + const InitialInformations& i, const IoCapability& my_iocaps, + const IoCapability& remote_iocaps) { bool i_am_displaying = false; if (my_iocaps == IoCapability::DISPLAY_ONLY || my_iocaps == IoCapability::DISPLAY_YES_NO) { i_am_displaying = true; - } else if ( - IAmCentral(i) && remote_iocaps == IoCapability::KEYBOARD_DISPLAY && my_iocaps == IoCapability::KEYBOARD_DISPLAY) { + } else if (IAmCentral(i) && remote_iocaps == IoCapability::KEYBOARD_DISPLAY && + my_iocaps == IoCapability::KEYBOARD_DISPLAY) { i_am_displaying = true; - } else if (my_iocaps == IoCapability::KEYBOARD_DISPLAY && remote_iocaps == IoCapability::KEYBOARD_ONLY) { + } else if (my_iocaps == IoCapability::KEYBOARD_DISPLAY && + remote_iocaps == IoCapability::KEYBOARD_ONLY) { i_am_displaying = true; } @@ -96,17 +97,21 @@ LegacyStage1ResultOrFailure PairingHandlerLe::LegacyPasskeyEntry(const InitialIn passkey = GenerateRandom(); passkey &= 0x0fffff; /* maximum 20 significant bits */ constexpr uint32_t PASSKEY_MAX = 999999; - if (passkey > PASSKEY_MAX) passkey >>= 1; + if (passkey > PASSKEY_MAX) { + passkey >>= 1; + } ConfirmationData data(i.remote_connection_address, i.remote_name, passkey); i.user_interface_handler->Post( - common::BindOnce(&UI::DisplayConfirmValue, common::Unretained(i.user_interface), data)); + common::BindOnce(&UI::DisplayConfirmValue, common::Unretained(i.user_interface), data)); } else { ConfirmationData data(i.remote_connection_address, i.remote_name); - i.user_interface_handler->Post( - common::BindOnce(&UI::DisplayEnterPasskeyDialog, common::Unretained(i.user_interface), data)); + i.user_interface_handler->Post(common::BindOnce(&UI::DisplayEnterPasskeyDialog, + common::Unretained(i.user_interface), data)); std::optional response = WaitUiPasskey(); - if (!response) return PairingFailure("Passkey did not arrive!"); + if (!response) { + return PairingFailure("Passkey did not arrive!"); + } passkey = response->ui_value; } @@ -125,8 +130,10 @@ LegacyStage1ResultOrFailure PairingHandlerLe::LegacyOutOfBand(const InitialInfor return i.remote_oob_data->security_manager_tk_value; } -StkOrFailure PairingHandlerLe::DoLegacyStage2(const InitialInformations& i, const PairingRequestView& pairing_request, - const PairingResponseView& pairing_response, const Octet16& tk) { +StkOrFailure PairingHandlerLe::DoLegacyStage2(const InitialInformations& i, + const PairingRequestView& pairing_request, + const PairingResponseView& pairing_response, + const Octet16& tk) { log::info("Legacy Step 2 start"); std::vector preq(pairing_request.begin(), pairing_request.end()); std::vector pres(pairing_response.begin(), pairing_response.end()); @@ -140,15 +147,11 @@ StkOrFailure PairingHandlerLe::DoLegacyStage2(const InitialInformations& i, cons // log::info("{} pres = {}", IAmCentral(i), base::HexEncode(pres.data(), pres.size())); // log::info("{} preq = {}", IAmCentral(i), base::HexEncode(preq.data(), preq.size())); - Octet16 mconfirm = crypto_toolbox::c1( - tk, - mrand, - preq.data(), - pres.data(), - (uint8_t)i.my_connection_address.GetAddressType(), - i.my_connection_address.GetAddress().data(), - (uint8_t)i.remote_connection_address.GetAddressType(), - i.remote_connection_address.GetAddress().data()); + Octet16 mconfirm = crypto_toolbox::c1(tk, mrand, preq.data(), pres.data(), + (uint8_t)i.my_connection_address.GetAddressType(), + i.my_connection_address.GetAddress().data(), + (uint8_t)i.remote_connection_address.GetAddressType(), + i.remote_connection_address.GetAddress().data()); // log::info("{} mconfirm = {}", IAmCentral(i), base::HexEncode(mconfirm.data(), // mconfirm.size())); @@ -176,14 +179,10 @@ StkOrFailure PairingHandlerLe::DoLegacyStage2(const InitialInformations& i, cons // log::info("{} srand = {}", IAmCentral(i), base::HexEncode(srand.data(), srand.size())); Octet16 sconfirm_generated = crypto_toolbox::c1( - tk, - srand, - preq.data(), - pres.data(), - (uint8_t)i.my_connection_address.GetAddressType(), - i.my_connection_address.GetAddress().data(), - (uint8_t)i.remote_connection_address.GetAddressType(), - i.remote_connection_address.GetAddress().data()); + tk, srand, preq.data(), pres.data(), (uint8_t)i.my_connection_address.GetAddressType(), + i.my_connection_address.GetAddress().data(), + (uint8_t)i.remote_connection_address.GetAddressType(), + i.remote_connection_address.GetAddress().data()); if (sconfirm != sconfirm_generated) { log::info("sconfirm does not match generated value"); @@ -197,15 +196,11 @@ StkOrFailure PairingHandlerLe::DoLegacyStage2(const InitialInformations& i, cons std::vector preq(pairing_request.begin(), pairing_request.end()); std::vector pres(pairing_response.begin(), pairing_response.end()); - Octet16 sconfirm = crypto_toolbox::c1( - tk, - srand, - preq.data(), - pres.data(), - (uint8_t)i.remote_connection_address.GetAddressType(), - i.remote_connection_address.GetAddress().data(), - (uint8_t)i.my_connection_address.GetAddressType(), - i.my_connection_address.GetAddress().data()); + Octet16 sconfirm = crypto_toolbox::c1(tk, srand, preq.data(), pres.data(), + (uint8_t)i.remote_connection_address.GetAddressType(), + i.remote_connection_address.GetAddress().data(), + (uint8_t)i.my_connection_address.GetAddressType(), + i.my_connection_address.GetAddress().data()); log::info("Peripheral waits for the Mconfirm"); auto mconfirm_pkt = WaitPairingConfirm(); @@ -224,15 +219,12 @@ StkOrFailure PairingHandlerLe::DoLegacyStage2(const InitialInformations& i, cons } mrand = std::get(random_pkt).GetRandomValue(); - Octet16 mconfirm_generated = crypto_toolbox::c1( - tk, - mrand, - preq.data(), - pres.data(), - (uint8_t)i.remote_connection_address.GetAddressType(), - i.remote_connection_address.GetAddress().data(), - (uint8_t)i.my_connection_address.GetAddressType(), - i.my_connection_address.GetAddress().data()); + Octet16 mconfirm_generated = + crypto_toolbox::c1(tk, mrand, preq.data(), pres.data(), + (uint8_t)i.remote_connection_address.GetAddressType(), + i.remote_connection_address.GetAddress().data(), + (uint8_t)i.my_connection_address.GetAddressType(), + i.my_connection_address.GetAddress().data()); if (mconfirm != mconfirm_generated) { log::info("mconfirm does not match generated value"); diff --git a/system/gd/security/pairing_handler_le_secure_connections.cc b/system/gd/security/pairing_handler_le_secure_connections.cc index c3d1ef2ef56..a4ff418ce11 100644 --- a/system/gd/security/pairing_handler_le_secure_connections.cc +++ b/system/gd/security/pairing_handler_le_secure_connections.cc @@ -29,15 +29,17 @@ namespace bluetooth { namespace security { using hci::Octet16; -std::variant PairingHandlerLe::ExchangePublicKeys(const InitialInformations& i, - OobDataFlag remote_have_oob_data) { +std::variant PairingHandlerLe::ExchangePublicKeys( + const InitialInformations& i, OobDataFlag remote_have_oob_data) { // Generate ECDH, or use one that was used for OOB data - const auto [private_key, public_key] = (remote_have_oob_data == OobDataFlag::NOT_PRESENT || !i.my_oob_data) - ? GenerateECDHKeyPair() - : std::make_pair(i.my_oob_data->private_key, i.my_oob_data->public_key); + const auto [private_key, public_key] = + (remote_have_oob_data == OobDataFlag::NOT_PRESENT || !i.my_oob_data) + ? GenerateECDHKeyPair() + : std::make_pair(i.my_oob_data->private_key, i.my_oob_data->public_key); log::info("Public key exchange start"); - std::unique_ptr myPublicKey = PairingPublicKeyBuilder::Create(public_key.x, public_key.y); + std::unique_ptr myPublicKey = + PairingPublicKeyBuilder::Create(public_key.x, public_key.y); if (!ValidateECDHPoint(public_key)) { log::error("Can't validate my own public key!!!"); @@ -94,10 +96,9 @@ std::variant PairingHandlerLe::ExchangePublic return KeyExchangeResult{PKa, PKb, dhkey}; } -Stage1ResultOrFailure PairingHandlerLe::DoSecureConnectionsStage1(const InitialInformations& i, - const EcdhPublicKey& PKa, const EcdhPublicKey& PKb, - const PairingRequestView& pairing_request, - const PairingResponseView& pairing_response) { +Stage1ResultOrFailure PairingHandlerLe::DoSecureConnectionsStage1( + const InitialInformations& i, const EcdhPublicKey& PKa, const EcdhPublicKey& PKb, + const PairingRequestView& pairing_request, const PairingResponseView& pairing_response) { if (((pairing_request.GetAuthReq() & AuthReqMaskMitm) == 0) && ((pairing_response.GetAuthReq() & AuthReqMaskMitm) == 0)) { // If both devices have not set MITM option, Just Works shall be used @@ -106,8 +107,10 @@ Stage1ResultOrFailure PairingHandlerLe::DoSecureConnectionsStage1(const InitialI if (pairing_request.GetOobDataFlag() == OobDataFlag::PRESENT || pairing_response.GetOobDataFlag() == OobDataFlag::PRESENT) { - OobDataFlag remote_oob_flag = IAmCentral(i) ? pairing_response.GetOobDataFlag() : pairing_request.GetOobDataFlag(); - OobDataFlag my_oob_flag = IAmCentral(i) ? pairing_request.GetOobDataFlag() : pairing_response.GetOobDataFlag(); + OobDataFlag remote_oob_flag = + IAmCentral(i) ? pairing_response.GetOobDataFlag() : pairing_request.GetOobDataFlag(); + OobDataFlag my_oob_flag = + IAmCentral(i) ? pairing_request.GetOobDataFlag() : pairing_response.GetOobDataFlag(); return SecureConnectionsOutOfBand(i, PKa, PKb, my_oob_flag, remote_oob_flag); } @@ -134,13 +137,10 @@ Stage1ResultOrFailure PairingHandlerLe::DoSecureConnectionsStage1(const InitialI } Stage2ResultOrFailure PairingHandlerLe::DoSecureConnectionsStage2( - const InitialInformations& i, - const EcdhPublicKey& /* PKa */, - const EcdhPublicKey& /* PKb */, - const PairingRequestView& pairing_request, - const PairingResponseView& pairing_response, - const Stage1Result stage1result, - const std::array& dhkey) { + const InitialInformations& i, const EcdhPublicKey& /* PKa */, + const EcdhPublicKey& /* PKb */, const PairingRequestView& pairing_request, + const PairingResponseView& pairing_response, const Stage1Result stage1result, + const std::array& dhkey) { log::info("Authentication stage 2 started"); auto [Na, Nb, ra, rb] = stage1result; @@ -167,9 +167,11 @@ Stage2ResultOrFailure PairingHandlerLe::DoSecureConnectionsStage2( // DHKey exchange and check std::array iocapA{static_cast(pairing_request.GetIoCapability()), - static_cast(pairing_request.GetOobDataFlag()), pairing_request.GetAuthReq()}; + static_cast(pairing_request.GetOobDataFlag()), + pairing_request.GetAuthReq()}; std::array iocapB{static_cast(pairing_response.GetIoCapability()), - static_cast(pairing_response.GetOobDataFlag()), pairing_response.GetAuthReq()}; + static_cast(pairing_response.GetOobDataFlag()), + pairing_response.GetAuthReq()}; // log::info("{} LTK = {}", IAmCentral(i), base::HexEncode(ltk.data(), ltk.size())); // log::info("{} MAC_KEY = {}", IAmCentral(i), base::HexEncode(mac_key.data(), mac_key.size())); @@ -221,16 +223,19 @@ Stage2ResultOrFailure PairingHandlerLe::DoSecureConnectionsStage2( } Stage1ResultOrFailure PairingHandlerLe::SecureConnectionsOutOfBand(const InitialInformations& i, - const EcdhPublicKey& Pka, const EcdhPublicKey& Pkb, + const EcdhPublicKey& Pka, + const EcdhPublicKey& Pkb, OobDataFlag my_oob_flag, OobDataFlag remote_oob_flag) { log::info("Out Of Band start"); Octet16 zeros{0}; - Octet16 localR = (remote_oob_flag == OobDataFlag::PRESENT && i.my_oob_data) ? i.my_oob_data->r : zeros; + Octet16 localR = + (remote_oob_flag == OobDataFlag::PRESENT && i.my_oob_data) ? i.my_oob_data->r : zeros; Octet16 remoteR; - if (my_oob_flag == OobDataFlag::NOT_PRESENT || (my_oob_flag == OobDataFlag::PRESENT && !i.remote_oob_data)) { + if (my_oob_flag == OobDataFlag::NOT_PRESENT || + (my_oob_flag == OobDataFlag::PRESENT && !i.remote_oob_data)) { /* we have send the OOB data, but not received them. remote will check if * C value is correct */ remoteR = zeros; @@ -285,7 +290,8 @@ Stage1ResultOrFailure PairingHandlerLe::SecureConnectionsOutOfBand(const Initial Stage1ResultOrFailure PairingHandlerLe::SecureConnectionsPasskeyEntry(const InitialInformations& i, const EcdhPublicKey& PKa, - const EcdhPublicKey& PKb, IoCapability my_iocaps, + const EcdhPublicKey& PKb, + IoCapability my_iocaps, IoCapability remote_iocaps) { log::info("Passkey Entry start"); Octet16 Na, Nb, ra{0}, rb{0}; @@ -297,17 +303,23 @@ Stage1ResultOrFailure PairingHandlerLe::SecureConnectionsPasskeyEntry(const Init passkey = GenerateRandom(); passkey &= 0x0fffff; /* maximum 20 significant bytes */ constexpr uint32_t PASSKEY_MAX = 999999; - while (passkey > PASSKEY_MAX) passkey >>= 1; + while (passkey > PASSKEY_MAX) { + passkey >>= 1; + } ConfirmationData data(i.remote_connection_address, i.remote_name, passkey); - i.user_interface_handler->Post(common::BindOnce(&UI::DisplayPasskey, common::Unretained(i.user_interface), data)); + i.user_interface_handler->Post( + common::BindOnce(&UI::DisplayPasskey, common::Unretained(i.user_interface), data)); - } else if (my_iocaps == IoCapability::KEYBOARD_ONLY || remote_iocaps == IoCapability::DISPLAY_ONLY) { + } else if (my_iocaps == IoCapability::KEYBOARD_ONLY || + remote_iocaps == IoCapability::DISPLAY_ONLY) { ConfirmationData data(i.remote_connection_address, i.remote_name); - i.user_interface_handler->Post( - common::BindOnce(&UI::DisplayEnterPasskeyDialog, common::Unretained(i.user_interface), data)); + i.user_interface_handler->Post(common::BindOnce(&UI::DisplayEnterPasskeyDialog, + common::Unretained(i.user_interface), data)); std::optional response = WaitUiPasskey(); - if (!response) return PairingFailure("Passkey did not arrive!"); + if (!response) { + return PairingFailure("Passkey did not arrive!"); + } passkey = response->ui_value; @@ -407,9 +419,8 @@ Stage1ResultOrFailure PairingHandlerLe::SecureConnectionsPasskeyEntry(const Init return Stage1Result{Na, Nb, ra, rb}; } -Stage1ResultOrFailure PairingHandlerLe::SecureConnectionsNumericComparison(const InitialInformations& i, - const EcdhPublicKey& PKa, - const EcdhPublicKey& PKb) { +Stage1ResultOrFailure PairingHandlerLe::SecureConnectionsNumericComparison( + const InitialInformations& i, const EcdhPublicKey& PKa, const EcdhPublicKey& PKb) { log::info("Numeric Comparison start"); Stage1ResultOrFailure result = SecureConnectionsJustWorks(i, PKa, PKb); if (std::holds_alternative(result)) { @@ -418,11 +429,12 @@ Stage1ResultOrFailure PairingHandlerLe::SecureConnectionsNumericComparison(const const auto [Na, Nb, ra, rb] = std::get(result); - uint32_t number_to_display = crypto_toolbox::g2((uint8_t*)PKa.x.data(), (uint8_t*)PKb.x.data(), Na, Nb); + uint32_t number_to_display = + crypto_toolbox::g2((uint8_t*)PKa.x.data(), (uint8_t*)PKb.x.data(), Na, Nb); ConfirmationData data(i.remote_connection_address, i.remote_name, number_to_display); i.user_interface_handler->Post( - common::BindOnce(&UI::DisplayConfirmValue, common::Unretained(i.user_interface), data)); + common::BindOnce(&UI::DisplayConfirmValue, common::Unretained(i.user_interface), data)); std::optional confirmyesno = WaitUiConfirmYesNo(); if (!confirmyesno || confirmyesno->ui_value == 0) { @@ -434,7 +446,8 @@ Stage1ResultOrFailure PairingHandlerLe::SecureConnectionsNumericComparison(const } Stage1ResultOrFailure PairingHandlerLe::SecureConnectionsJustWorks(const InitialInformations& i, - const EcdhPublicKey& PKa, const EcdhPublicKey& PKb) { + const EcdhPublicKey& PKa, + const EcdhPublicKey& PKb) { Octet16 Cb, Na, Nb, ra, rb; ra = rb = {0}; diff --git a/system/gd/security/pairing_handler_le_unittest.cc b/system/gd/security/pairing_handler_le_unittest.cc index af82af6b182..44ea7d511e8 100644 --- a/system/gd/security/pairing_handler_le_unittest.cc +++ b/system/gd/security/pairing_handler_le_unittest.cc @@ -50,7 +50,7 @@ CommandView BuilderToView(std::unique_ptr builder) { } class PairingResultHandlerMock { - public: +public: MOCK_CONST_METHOD1(OnPairingFinished, void(PairingResultOrFailure)); }; @@ -60,8 +60,8 @@ UIMock uiMock; void OnPairingFinished(PairingResultOrFailure r) { if (std::holds_alternative(r)) { - log::info( - "pairing with {} finished successfully!", std::get(r).connection_address); + log::info("pairing with {} finished successfully!", + std::get(r).connection_address); } else { log::info("pairing with ... failed!"); } @@ -70,17 +70,19 @@ void OnPairingFinished(PairingResultOrFailure r) { } // namespace class PairingHandlerUnitTest : public testing::Test { - protected: +protected: void SetUp() { thread_ = new os::Thread("test_thread", os::Thread::Priority::NORMAL); handler_ = new os::Handler(thread_); - bidi_queue_ = - std::make_unique, packet::BasePacketBuilder>>(10); - up_buffer_ = std::make_unique>(bidi_queue_->GetUpEnd()); + bidi_queue_ = std::make_unique, + packet::BasePacketBuilder>>(10); + up_buffer_ = + std::make_unique>(bidi_queue_->GetUpEnd()); bidi_queue_->GetDownEnd()->RegisterDequeue( - handler_, common::Bind(&PairingHandlerUnitTest::L2CAP_SendSmp, common::Unretained(this))); + handler_, + common::Bind(&PairingHandlerUnitTest::L2CAP_SendSmp, common::Unretained(this))); pairingResult.reset(new PairingResultHandlerMock); } @@ -108,7 +110,8 @@ class PairingHandlerUnitTest : public testing::Test { std::mutex mutex; std::unique_lock lock(mutex); - // It is possible that we lost wakeup from condition_variable, check if data is already waiting to be processed + // It is possible that we lost wakeup from condition_variable, check if data is already waiting + // to be processed if (outgoing_l2cap_packet_ != std::nullopt) { std::optional tmp = std::nullopt; outgoing_l2cap_packet_.swap(tmp); @@ -116,7 +119,8 @@ class PairingHandlerUnitTest : public testing::Test { } // Data not ready yet, wait for it. - if (outgoing_l2cap_blocker_.wait_for(lock, std::chrono::seconds(5)) == std::cv_status::timeout) { + if (outgoing_l2cap_blocker_.wait_for(lock, std::chrono::seconds(5)) == + std::cv_status::timeout) { return std::nullopt; } @@ -125,34 +129,37 @@ class PairingHandlerUnitTest : public testing::Test { return tmp; } - public: +public: os::Thread* thread_; os::Handler* handler_; - std::unique_ptr, packet::BasePacketBuilder>> bidi_queue_; + std::unique_ptr< + common::BidiQueue, packet::BasePacketBuilder>> + bidi_queue_; std::unique_ptr> up_buffer_; std::condition_variable outgoing_l2cap_blocker_; std::optional outgoing_l2cap_packet_ = std::nullopt; }; InitialInformations initial_informations{ - .my_role = hci::Role::CENTRAL, - .my_connection_address = {{}, hci::AddressType::PUBLIC_DEVICE_ADDRESS}, - .my_identity_address = {{}, hci::AddressType::PUBLIC_DEVICE_ADDRESS}, - .my_identity_resolving_key = - {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f}, - - .myPairingCapabilities = {.io_capability = IoCapability::NO_INPUT_NO_OUTPUT, - .oob_data_flag = OobDataFlag::NOT_PRESENT, - .auth_req = AuthReqMaskBondingFlag | AuthReqMaskMitm | AuthReqMaskSc, - .maximum_encryption_key_size = 16, - .initiator_key_distribution = 0x03, - .responder_key_distribution = 0x03}, - - .remotely_initiated = false, - .remote_connection_address = {{}, hci::AddressType::RANDOM_DEVICE_ADDRESS}, - .user_interface = &uiMock, - .le_security_interface = &leSecurityMock, - .OnPairingFinished = OnPairingFinished, + .my_role = hci::Role::CENTRAL, + .my_connection_address = {{}, hci::AddressType::PUBLIC_DEVICE_ADDRESS}, + .my_identity_address = {{}, hci::AddressType::PUBLIC_DEVICE_ADDRESS}, + .my_identity_resolving_key = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, + 0x0b, 0x0c, 0x0d, 0x0e, 0x0f}, + + .myPairingCapabilities = {.io_capability = IoCapability::NO_INPUT_NO_OUTPUT, + .oob_data_flag = OobDataFlag::NOT_PRESENT, + .auth_req = + AuthReqMaskBondingFlag | AuthReqMaskMitm | AuthReqMaskSc, + .maximum_encryption_key_size = 16, + .initiator_key_distribution = 0x03, + .responder_key_distribution = 0x03}, + + .remotely_initiated = false, + .remote_connection_address = {{}, hci::AddressType::RANDOM_DEVICE_ADDRESS}, + .user_interface = &uiMock, + .le_security_interface = &leSecurityMock, + .OnPairingFinished = OnPairingFinished, }; TEST_F(PairingHandlerUnitTest, test_phase_1_failure) { @@ -161,7 +168,7 @@ TEST_F(PairingHandlerUnitTest, test_phase_1_failure) { initial_informations.user_interface_handler = handler_; std::unique_ptr pairing_handler = - std::make_unique(PairingHandlerLe::PHASE1, initial_informations); + std::make_unique(PairingHandlerLe::PHASE1, initial_informations); std::optional pairing_request = WaitForOutgoingL2capPacket(); EXPECT_TRUE(pairing_request.has_value()); @@ -187,16 +194,17 @@ TEST_F(PairingHandlerUnitTest, test_secure_connections_just_works) { // we keep the pairing_handler as unique_ptr to better mimick how it's used // in the real world std::unique_ptr pairing_handler = - std::make_unique(PairingHandlerLe::PHASE1, initial_informations); + std::make_unique(PairingHandlerLe::PHASE1, initial_informations); - std::optional pairing_request_pkt = WaitForOutgoingL2capPacket(); + std::optional pairing_request_pkt = + WaitForOutgoingL2capPacket(); EXPECT_TRUE(pairing_request_pkt.has_value()); EXPECT_EQ(pairing_request_pkt->GetCode(), Code::PAIRING_REQUEST); CommandView pairing_request = pairing_request_pkt.value(); - auto pairing_response = BuilderToView( - PairingResponseBuilder::Create(IoCapability::KEYBOARD_DISPLAY, OobDataFlag::NOT_PRESENT, - AuthReqMaskBondingFlag | AuthReqMaskMitm | AuthReqMaskSc, 16, 0x03, 0x03)); + auto pairing_response = BuilderToView(PairingResponseBuilder::Create( + IoCapability::KEYBOARD_DISPLAY, OobDataFlag::NOT_PRESENT, + AuthReqMaskBondingFlag | AuthReqMaskMitm | AuthReqMaskSc, 16, 0x03, 0x03)); pairing_handler->OnCommandView(pairing_response); // Phase 1 finished. @@ -212,7 +220,8 @@ TEST_F(PairingHandlerUnitTest, test_secure_connections_just_works) { const auto [private_key, public_key] = GenerateECDHKeyPair(); - pairing_handler->OnCommandView(BuilderToView(PairingPublicKeyBuilder::Create(public_key.x, public_key.y))); + pairing_handler->OnCommandView( + BuilderToView(PairingPublicKeyBuilder::Create(public_key.x, public_key.y))); // DHKey exchange finished std::array dhkey = ComputeDHKey(private_key, my_public_key); @@ -223,7 +232,8 @@ TEST_F(PairingHandlerUnitTest, test_secure_connections_just_works) { Octet16 Nb = GenerateRandom<16>(); // Compute confirm - Octet16 Cb = crypto_toolbox::f4((uint8_t*)public_key.x.data(), (uint8_t*)my_public_key.x.data(), Nb, 0); + Octet16 Cb = crypto_toolbox::f4((uint8_t*)public_key.x.data(), (uint8_t*)my_public_key.x.data(), + Nb, 0); pairing_handler->OnCommandView(BuilderToView(PairingConfirmBuilder::Create(Cb))); @@ -240,7 +250,8 @@ TEST_F(PairingHandlerUnitTest, test_secure_connections_just_works) { // Start of authentication stage 2 uint8_t a[7]; uint8_t b[7]; - memcpy(b, initial_informations.remote_connection_address.GetAddress().data(), hci::Address::kLength); + memcpy(b, initial_informations.remote_connection_address.GetAddress().data(), + hci::Address::kLength); b[6] = (uint8_t)initial_informations.remote_connection_address.GetAddressType(); memcpy(a, initial_informations.my_connection_address.GetAddress().data(), hci::Address::kLength); a[6] = (uint8_t)initial_informations.my_connection_address.GetAddressType(); @@ -275,24 +286,25 @@ TEST_F(PairingHandlerUnitTest, test_secure_connections_just_works) { } InitialInformations initial_informations_trsi{ - .my_role = hci::Role::CENTRAL, - .my_connection_address = hci::AddressWithType(), - .my_identity_address = {{}, hci::AddressType::PUBLIC_DEVICE_ADDRESS}, - .my_identity_resolving_key = - {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f}, - - .myPairingCapabilities = {.io_capability = IoCapability::NO_INPUT_NO_OUTPUT, - .oob_data_flag = OobDataFlag::NOT_PRESENT, - .auth_req = AuthReqMaskBondingFlag | AuthReqMaskMitm | AuthReqMaskSc, - .maximum_encryption_key_size = 16, - .initiator_key_distribution = 0x03, - .responder_key_distribution = 0x03}, - - .remotely_initiated = true, - .remote_connection_address = hci::AddressWithType(), - .user_interface = &uiMock, - .le_security_interface = &leSecurityMock, - .OnPairingFinished = OnPairingFinished, + .my_role = hci::Role::CENTRAL, + .my_connection_address = hci::AddressWithType(), + .my_identity_address = {{}, hci::AddressType::PUBLIC_DEVICE_ADDRESS}, + .my_identity_resolving_key = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, + 0x0b, 0x0c, 0x0d, 0x0e, 0x0f}, + + .myPairingCapabilities = {.io_capability = IoCapability::NO_INPUT_NO_OUTPUT, + .oob_data_flag = OobDataFlag::NOT_PRESENT, + .auth_req = + AuthReqMaskBondingFlag | AuthReqMaskMitm | AuthReqMaskSc, + .maximum_encryption_key_size = 16, + .initiator_key_distribution = 0x03, + .responder_key_distribution = 0x03}, + + .remotely_initiated = true, + .remote_connection_address = hci::AddressWithType(), + .user_interface = &uiMock, + .le_security_interface = &leSecurityMock, + .OnPairingFinished = OnPairingFinished, }; /* This test verifies that when remote peripheral device sends security request , and user @@ -302,13 +314,15 @@ TEST_F(PairingHandlerUnitTest, test_remote_peripheral_initiating) { initial_informations_trsi.l2cap_handler = handler_; initial_informations_trsi.user_interface_handler = handler_; - std::unique_ptr pairing_handler = - std::make_unique(PairingHandlerLe::ACCEPT_PROMPT, initial_informations_trsi); + std::unique_ptr pairing_handler = std::make_unique( + PairingHandlerLe::ACCEPT_PROMPT, initial_informations_trsi); // Simulate user accepting the pairing in UI - pairing_handler->OnUiAction(PairingEvent::PAIRING_ACCEPTED, 0x01 /* Non-zero value means success */); + pairing_handler->OnUiAction(PairingEvent::PAIRING_ACCEPTED, + 0x01 /* Non-zero value means success */); - std::optional pairing_request_pkt = WaitForOutgoingL2capPacket(); + std::optional pairing_request_pkt = + WaitForOutgoingL2capPacket(); EXPECT_TRUE(pairing_request_pkt.has_value()); EXPECT_EQ(Code::PAIRING_REQUEST, pairing_request_pkt->GetCode()); @@ -317,48 +331,47 @@ TEST_F(PairingHandlerUnitTest, test_remote_peripheral_initiating) { } InitialInformations initial_informations_trmi{ - .my_role = hci::Role::PERIPHERAL, - .my_connection_address = hci::AddressWithType(), - .my_identity_address = {{}, hci::AddressType::PUBLIC_DEVICE_ADDRESS}, - .my_identity_resolving_key = - {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f}, - - .myPairingCapabilities = {.io_capability = IoCapability::NO_INPUT_NO_OUTPUT, - .oob_data_flag = OobDataFlag::NOT_PRESENT, - .auth_req = AuthReqMaskBondingFlag | AuthReqMaskMitm | AuthReqMaskSc, - .maximum_encryption_key_size = 16, - .initiator_key_distribution = 0x03, - .responder_key_distribution = 0x03}, - - .remotely_initiated = true, - .remote_connection_address = hci::AddressWithType(), - .pairing_request = PairingRequestView::Create(BuilderToView(PairingRequestBuilder::Create( - IoCapability::NO_INPUT_NO_OUTPUT, - OobDataFlag::NOT_PRESENT, - AuthReqMaskBondingFlag | AuthReqMaskMitm | AuthReqMaskSc, - 16, - 0x03, - 0x03))), - .user_interface = &uiMock, - .le_security_interface = &leSecurityMock, - - .OnPairingFinished = OnPairingFinished, + .my_role = hci::Role::PERIPHERAL, + .my_connection_address = hci::AddressWithType(), + .my_identity_address = {{}, hci::AddressType::PUBLIC_DEVICE_ADDRESS}, + .my_identity_resolving_key = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, + 0x0b, 0x0c, 0x0d, 0x0e, 0x0f}, + + .myPairingCapabilities = {.io_capability = IoCapability::NO_INPUT_NO_OUTPUT, + .oob_data_flag = OobDataFlag::NOT_PRESENT, + .auth_req = + AuthReqMaskBondingFlag | AuthReqMaskMitm | AuthReqMaskSc, + .maximum_encryption_key_size = 16, + .initiator_key_distribution = 0x03, + .responder_key_distribution = 0x03}, + + .remotely_initiated = true, + .remote_connection_address = hci::AddressWithType(), + .pairing_request = PairingRequestView::Create(BuilderToView(PairingRequestBuilder::Create( + IoCapability::NO_INPUT_NO_OUTPUT, OobDataFlag::NOT_PRESENT, + AuthReqMaskBondingFlag | AuthReqMaskMitm | AuthReqMaskSc, 16, 0x03, 0x03))), + .user_interface = &uiMock, + .le_security_interface = &leSecurityMock, + + .OnPairingFinished = OnPairingFinished, }; -/* This test verifies that when remote device sends pairing request, and user does accept the prompt, we do send proper - * reply back */ +/* This test verifies that when remote device sends pairing request, and user does accept the + * prompt, we do send proper reply back */ TEST_F(PairingHandlerUnitTest, test_remote_central_initiating) { initial_informations_trmi.proper_l2cap_interface = up_buffer_.get(); initial_informations_trmi.l2cap_handler = handler_; initial_informations_trmi.user_interface_handler = handler_; - std::unique_ptr pairing_handler = - std::make_unique(PairingHandlerLe::ACCEPT_PROMPT, initial_informations_trmi); + std::unique_ptr pairing_handler = std::make_unique( + PairingHandlerLe::ACCEPT_PROMPT, initial_informations_trmi); // Simulate user accepting the pairing in UI - pairing_handler->OnUiAction(PairingEvent::PAIRING_ACCEPTED, 0x01 /* Non-zero value means success */); + pairing_handler->OnUiAction(PairingEvent::PAIRING_ACCEPTED, + 0x01 /* Non-zero value means success */); - std::optional pairing_response_pkt = WaitForOutgoingL2capPacket(); + std::optional pairing_response_pkt = + WaitForOutgoingL2capPacket(); EXPECT_TRUE(pairing_response_pkt.has_value()); EXPECT_EQ(Code::PAIRING_RESPONSE, pairing_response_pkt->GetCode()); // Phase 1 finished. diff --git a/system/gd/security/record/security_record.h b/system/gd/security/record/security_record.h index 83547ac5022..8b7d31023c5 100644 --- a/system/gd/security/record/security_record.h +++ b/system/gd/security/record/security_record.h @@ -26,7 +26,7 @@ namespace security { namespace record { class SecurityRecord { - public: +public: explicit SecurityRecord(hci::AddressWithType address) : pseudo_address_(address) {} SecurityRecord& operator=(const SecurityRecord& other) = default; @@ -34,14 +34,10 @@ class SecurityRecord { /** * Returns true if a device is currently pairing to another device */ - bool IsPairing() const { - return pairing_; - } + bool IsPairing() const { return pairing_; } /* Link key has been exchanged, but not stored */ - bool IsPaired() const { - return IsClassicLinkKeyValid(); - } + bool IsPaired() const { return IsClassicLinkKeyValid(); } void SetLinkKey(std::array link_key, hci::KeyType key_type) { link_key_ = link_key; @@ -49,9 +45,7 @@ class SecurityRecord { CancelPairing(); } - void CancelPairing() { - pairing_ = false; - } + void CancelPairing() { pairing_ = false; } std::array GetLinkKey() { log::assert_that(IsClassicLinkKeyValid(), "assert failed: IsClassicLinkKeyValid()"); @@ -63,48 +57,33 @@ class SecurityRecord { return key_type_; } - std::optional GetPseudoAddress() { - return pseudo_address_; - } + std::optional GetPseudoAddress() { return pseudo_address_; } - void SetAuthenticated(bool is_authenticated) { - this->is_authenticated_ = is_authenticated; - } + void SetAuthenticated(bool is_authenticated) { this->is_authenticated_ = is_authenticated; } - bool IsAuthenticated() { - return this->is_authenticated_; - } + bool IsAuthenticated() { return this->is_authenticated_; } void SetRequiresMitmProtection(bool requires_mitm_protection) { this->requires_mitm_protection_ = requires_mitm_protection; } - bool RequiresMitmProtection() { - return this->requires_mitm_protection_; - } + bool RequiresMitmProtection() { return this->requires_mitm_protection_; } void SetIsEncryptionRequired(bool is_encryption_required) { this->is_encryption_required_ = is_encryption_required; } - bool IsEncryptionRequired() { - return this->is_encryption_required_; - } + bool IsEncryptionRequired() { return this->is_encryption_required_; } bool IsClassicLinkKeyValid() const { return !std::all_of(link_key_.begin(), link_key_.end(), [](uint8_t b) { return b == 0; }); } - void SetIsTemporary(bool is_temp) { - this->is_temporary_ = is_temp; - } - - bool IsTemporary() { - return this->is_temporary_; - } + void SetIsTemporary(bool is_temp) { this->is_temporary_ = is_temp; } - private: + bool IsTemporary() { return this->is_temporary_; } +private: std::array link_key_ = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; hci::KeyType key_type_ = hci::KeyType::DEBUG_COMBINATION; @@ -114,7 +93,7 @@ class SecurityRecord { bool requires_mitm_protection_ = false; bool is_encryption_required_ = false; - public: +public: /* First address we have ever seen this device with, that we used to create bond */ std::optional pseudo_address_; diff --git a/system/gd/security/record/security_record_database.h b/system/gd/security/record/security_record_database.h index 0541c5358e9..e8309e27b16 100644 --- a/system/gd/security/record/security_record_database.h +++ b/system/gd/security/record/security_record_database.h @@ -27,7 +27,7 @@ namespace security { namespace record { class SecurityRecordDatabase { - public: +public: SecurityRecordDatabase(record::SecurityRecordStorage security_record_storage) : security_record_storage_(security_record_storage) {} @@ -36,7 +36,9 @@ class SecurityRecordDatabase { std::shared_ptr FindOrCreate(hci::AddressWithType address) { auto it = Find(address); // Security record check - if (it != records_.end()) return *it; + if (it != records_.end()) { + return *it; + } // No security record, create one auto record_ptr = std::make_shared(address); @@ -48,7 +50,9 @@ class SecurityRecordDatabase { auto it = Find(address); // No record exists - if (it == records_.end()) return; + if (it == records_.end()) { + return; + } records_.erase(it); security_record_storage_.RemoveDevice(address); @@ -57,20 +61,23 @@ class SecurityRecordDatabase { iterator Find(hci::AddressWithType address) { for (auto it = records_.begin(); it != records_.end(); ++it) { std::shared_ptr record = *it; - if (record->identity_address_.has_value() && record->identity_address_.value() == address) return it; - if (record->GetPseudoAddress() == address) return it; - if (record->remote_irk.has_value() && address.IsRpaThatMatchesIrk(record->remote_irk.value())) return it; + if (record->identity_address_.has_value() && record->identity_address_.value() == address) { + return it; + } + if (record->GetPseudoAddress() == address) { + return it; + } + if (record->remote_irk.has_value() && + address.IsRpaThatMatchesIrk(record->remote_irk.value())) { + return it; + } } return records_.end(); } - void LoadRecordsFromStorage() { - security_record_storage_.LoadSecurityRecords(&records_); - } + void LoadRecordsFromStorage() { security_record_storage_.LoadSecurityRecords(&records_); } - void SaveRecordsToStorage() { - security_record_storage_.SaveSecurityRecords(&records_); - } + void SaveRecordsToStorage() { security_record_storage_.SaveSecurityRecords(&records_); } std::set> records_; record::SecurityRecordStorage security_record_storage_; diff --git a/system/gd/security/record/security_record_storage.cc b/system/gd/security/record/security_record_storage.cc index 244762ff4de..6a7bb881ca9 100644 --- a/system/gd/security/record/security_record_storage.cc +++ b/system/gd/security/record/security_record_storage.cc @@ -28,8 +28,8 @@ namespace security { namespace record { namespace { -void SetClassicData( - storage::Mutation& mutation, std::shared_ptr record, storage::Device& device) { +void SetClassicData(storage::Mutation& mutation, std::shared_ptr record, + storage::Device& device) { if (*device.GetDeviceType() == hci::DeviceType::LE) { return; } @@ -40,7 +40,8 @@ void SetClassicData( } } -void SetLeData(storage::Mutation& mutation, std::shared_ptr record, storage::Device& device) { +void SetLeData(storage::Mutation& mutation, std::shared_ptr record, + storage::Device& device) { if (*device.GetDeviceType() == hci::DeviceType::BR_EDR) { return; } @@ -87,7 +88,8 @@ void SetLeData(storage::Mutation& mutation, std::shared_ptrremote_signature_key->data(), record->remote_signature_key->size(), psrk_keys.data() + 4); + std::copy_n(record->remote_signature_key->data(), record->remote_signature_key->size(), + psrk_keys.data() + 4); *(psrk_keys.data() + 20) = record->security_level; common::ByteArray<21> byte_array(psrk_keys); @@ -95,23 +97,27 @@ void SetLeData(storage::Mutation& mutation, std::shared_ptr record, - storage::Device& device) { - device.SetIsAuthenticated((record->IsAuthenticated() ? 1 : 0)); - device.SetIsEncryptionRequired((record->IsEncryptionRequired() ? 1 : 0)); +void SetAuthenticationData(storage::Mutation& /* mutation */, + std::shared_ptr record, + storage::Device& device) { + device.SetIsAuthenticated(record->IsAuthenticated() ? 1 : 0); + device.SetIsEncryptionRequired(record->IsEncryptionRequired() ? 1 : 0); device.SetRequiresMitmProtection(record->RequiresMitmProtection() ? 1 : 0); } } // namespace -SecurityRecordStorage::SecurityRecordStorage(storage::StorageModule* storage_module, os::Handler* handler) +SecurityRecordStorage::SecurityRecordStorage(storage::StorageModule* storage_module, + os::Handler* handler) : storage_module_(storage_module), handler_(handler) {} -void SecurityRecordStorage::SaveSecurityRecords(std::set>* records) { +void SecurityRecordStorage::SaveSecurityRecords( + std::set>* records) { for (auto record : *records) { - if (record->IsTemporary()) continue; - storage::Device device = storage_module_->GetDeviceByClassicMacAddress(record->GetPseudoAddress()->GetAddress()); + if (record->IsTemporary()) { + continue; + } + storage::Device device = + storage_module_->GetDeviceByClassicMacAddress(record->GetPseudoAddress()->GetAddress()); auto mutation = storage_module_->Modify(); if (record->IsClassicLinkKeyValid() && !record->identity_address_) { @@ -122,9 +128,8 @@ void SecurityRecordStorage::SaveSecurityRecords(std::setGetPseudoAddress()); + log::warn("Cannot determine device type from security record for '{}'; defaulting to LE", + *record->GetPseudoAddress()); } mutation.Commit(); SetClassicData(mutation, record, device); @@ -134,10 +139,12 @@ void SecurityRecordStorage::SaveSecurityRecords(std::set>* records) { +void SecurityRecordStorage::LoadSecurityRecords( + std::set>* records) { for (auto device : storage_module_->GetBondedDevices()) { - auto address_type = (device.GetDeviceType() == hci::DeviceType::BR_EDR) ? hci::AddressType::PUBLIC_DEVICE_ADDRESS - : device.Le().GetAddressType(); + auto address_type = (device.GetDeviceType() == hci::DeviceType::BR_EDR) + ? hci::AddressType::PUBLIC_DEVICE_ADDRESS + : device.Le().GetAddressType(); auto address_with_type = hci::AddressWithType(device.GetAddress(), *address_type); auto record = std::make_shared(address_with_type); @@ -146,7 +153,7 @@ void SecurityRecordStorage::LoadSecurityRecords(std::setpseudo_address_ = std::make_optional( - *device.Le().GetLegacyPseudoAddress(), *device.Le().GetAddressType()); + *device.Le().GetLegacyPseudoAddress(), *device.Le().GetAddressType()); if (device.Le().GetPeerId()) { auto peerid = common::ByteArray<23>::FromString(*device.Le().GetPeerId()); @@ -157,12 +164,13 @@ void SecurityRecordStorage::LoadSecurityRecords(std::setdata() + 16, 1, &idaddress_type); std::copy_n(peerid->data() + 17, 6, idaddress.data()); - record->identity_address_ = - std::make_optional(idaddress, static_cast(idaddress_type)); + record->identity_address_ = std::make_optional( + idaddress, static_cast(idaddress_type)); } if (device.Le().GetPeerEncryptionKeys()) { - auto peer_encryption_keys = common::ByteArray<28>::FromString(*device.Le().GetPeerEncryptionKeys()); + auto peer_encryption_keys = + common::ByteArray<28>::FromString(*device.Le().GetPeerEncryptionKeys()); record->remote_ltk = std::make_optional>(); record->remote_rand = std::make_optional>(); record->remote_ediv = std::make_optional(0); @@ -176,10 +184,11 @@ void SecurityRecordStorage::LoadSecurityRecords(std::set::FromString(*device.Le().GetPeerSignatureResolvingKeys()); + common::ByteArray<21>::FromString(*device.Le().GetPeerSignatureResolvingKeys()); record->remote_signature_key = std::make_optional>(); - std::copy_n(peer_signature_resolving_keys->data() + 4, 16, record->remote_signature_key->data()); + std::copy_n(peer_signature_resolving_keys->data() + 4, 16, + record->remote_signature_key->data()); record->security_level = peer_signature_resolving_keys->data()[20]; } } diff --git a/system/gd/security/record/security_record_storage.h b/system/gd/security/record/security_record_storage.h index a3ed24b785b..97f478b2a3e 100644 --- a/system/gd/security/record/security_record_storage.h +++ b/system/gd/security/record/security_record_storage.h @@ -34,7 +34,7 @@ static const char* CONFIG_FILE_PATH = "bt_config.conf"; #endif // __ANDROID__ class SecurityRecordStorage { - public: +public: SecurityRecordStorage(storage::StorageModule* storage_module, os::Handler* handler); /** @@ -62,7 +62,7 @@ class SecurityRecordStorage { */ void RemoveDevice(hci::AddressWithType address); - private: +private: storage::StorageModule* storage_module_ __attribute__((unused)); os::Handler* handler_ __attribute__((unused)); }; diff --git a/system/gd/security/record/security_record_storage_test.cc b/system/gd/security/record/security_record_storage_test.cc index 5b2d6fdf81b..9b327755b86 100644 --- a/system/gd/security/record/security_record_storage_test.cc +++ b/system/gd/security/record/security_record_storage_test.cc @@ -30,11 +30,11 @@ static const std::chrono::milliseconds kTestConfigSaveDelay = std::chrono::milli using storage::StorageModule; class DISABLED_SecurityRecordStorageTest : public ::testing::Test { - protected: +protected: void SetUp() override { // Make storage module storage_module_ = - new StorageModule("/tmp/temp_config.txt", kTestConfigSaveDelay, 100, false, false); + new StorageModule("/tmp/temp_config.txt", kTestConfigSaveDelay, 100, false, false); // Inject fake_registry_.InjectTestModule(&StorageModule::Factory, storage_module_); @@ -63,10 +63,10 @@ class DISABLED_SecurityRecordStorageTest : public ::testing::Test { TEST_F(DISABLED_SecurityRecordStorageTest, setup_teardown) {} TEST_F(DISABLED_SecurityRecordStorageTest, store_security_record) { - hci::AddressWithType remote( - hci::Address({0x01, 0x02, 0x03, 0x04, 0x05, 0x06}), hci::AddressType::PUBLIC_DEVICE_ADDRESS); - std::array link_key = { - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0}; + hci::AddressWithType remote(hci::Address({0x01, 0x02, 0x03, 0x04, 0x05, 0x06}), + hci::AddressType::PUBLIC_DEVICE_ADDRESS); + std::array link_key = {0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0}; std::shared_ptr record = std::make_shared(remote); record->SetLinkKey(link_key, hci::KeyType::DEBUG_COMBINATION); @@ -84,17 +84,18 @@ TEST_F(DISABLED_SecurityRecordStorageTest, store_security_record) { } TEST_F(DISABLED_SecurityRecordStorageTest, store_le_security_record) { - hci::AddressWithType identity_address( - hci::Address({0x01, 0x02, 0x03, 0x04, 0x05, 0x06}), hci::AddressType::RANDOM_DEVICE_ADDRESS); - std::array remote_ltk{ - 0x07, 0x0c, 0x0e, 0x16, 0x18, 0x55, 0xc6, 0x72, 0x64, 0x5a, 0xd8, 0xb1, 0xf6, 0x93, 0x94, 0xa7}; + hci::AddressWithType identity_address(hci::Address({0x01, 0x02, 0x03, 0x04, 0x05, 0x06}), + hci::AddressType::RANDOM_DEVICE_ADDRESS); + std::array remote_ltk{0x07, 0x0c, 0x0e, 0x16, 0x18, 0x55, 0xc6, 0x72, + 0x64, 0x5a, 0xd8, 0xb1, 0xf6, 0x93, 0x94, 0xa7}; uint16_t remote_ediv = 0x28; std::array remote_rand{0x48, 0xac, 0x91, 0xf4, 0xef, 0x6d, 0x41, 0x10}; - std::array remote_irk{ - 0x66, 0x90, 0x40, 0x76, 0x27, 0x69, 0x57, 0x71, 0x0d, 0x39, 0xf7, 0x80, 0x9e, 0x2f, 0x49, 0xcf}; - std::array remote_signature_key{ - 0x08, 0x83, 0xae, 0x44, 0xd6, 0x77, 0x9e, 0x90, 0x1d, 0x25, 0xcd, 0xd7, 0xb6, 0xf4, 0x57, 0x85}; - std::shared_ptr record = std::make_shared(identity_address); + std::array remote_irk{0x66, 0x90, 0x40, 0x76, 0x27, 0x69, 0x57, 0x71, + 0x0d, 0x39, 0xf7, 0x80, 0x9e, 0x2f, 0x49, 0xcf}; + std::array remote_signature_key{0x08, 0x83, 0xae, 0x44, 0xd6, 0x77, 0x9e, 0x90, + 0x1d, 0x25, 0xcd, 0xd7, 0xb6, 0xf4, 0x57, 0x85}; + std::shared_ptr record = + std::make_shared(identity_address); record->identity_address_ = identity_address; record->remote_ltk = remote_ltk; @@ -117,17 +118,19 @@ TEST_F(DISABLED_SecurityRecordStorageTest, store_le_security_record) { ASSERT_EQ(*device.Le().GetPeerId(), "66904076276957710d39f7809e2f49cf01010203040506"); // LTK, RAND, EDIV and sec level glued together - ASSERT_EQ(*device.Le().GetPeerEncryptionKeys(), "070c0e161855c672645ad8b1f69394a748ac91f4ef6d411028000210"); + ASSERT_EQ(*device.Le().GetPeerEncryptionKeys(), + "070c0e161855c672645ad8b1f69394a748ac91f4ef6d411028000210"); // Counter, signature key, and security level glued together - ASSERT_EQ(device.Le().GetPeerSignatureResolvingKeys(), "000000000883ae44d6779e901d25cdd7b6f4578502"); + ASSERT_EQ(device.Le().GetPeerSignatureResolvingKeys(), + "000000000883ae44d6779e901d25cdd7b6f4578502"); } TEST_F(DISABLED_SecurityRecordStorageTest, load_security_record) { - hci::AddressWithType remote( - hci::Address({0x01, 0x02, 0x03, 0x04, 0x05, 0x06}), hci::AddressType::PUBLIC_DEVICE_ADDRESS); - std::array link_key = { - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0}; + hci::AddressWithType remote(hci::Address({0x01, 0x02, 0x03, 0x04, 0x05, 0x06}), + hci::AddressType::PUBLIC_DEVICE_ADDRESS); + std::array link_key = {0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0}; std::shared_ptr record = std::make_shared(remote); record->SetLinkKey(link_key, hci::KeyType::DEBUG_COMBINATION); @@ -157,10 +160,10 @@ TEST_F(DISABLED_SecurityRecordStorageTest, load_security_record) { } TEST_F(DISABLED_SecurityRecordStorageTest, dont_save_temporary_records) { - hci::AddressWithType remote( - hci::Address({0x01, 0x02, 0x03, 0x04, 0x05, 0x06}), hci::AddressType::PUBLIC_DEVICE_ADDRESS); - std::array link_key = { - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0}; + hci::AddressWithType remote(hci::Address({0x01, 0x02, 0x03, 0x04, 0x05, 0x06}), + hci::AddressType::PUBLIC_DEVICE_ADDRESS); + std::array link_key = {0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0}; std::shared_ptr record = std::make_shared(remote); record->SetLinkKey(link_key, hci::KeyType::DEBUG_COMBINATION); @@ -178,10 +181,10 @@ TEST_F(DISABLED_SecurityRecordStorageTest, dont_save_temporary_records) { } TEST_F(DISABLED_SecurityRecordStorageTest, test_remove) { - hci::AddressWithType remote( - hci::Address({0x01, 0x02, 0x03, 0x04, 0x05, 0x06}), hci::AddressType::PUBLIC_DEVICE_ADDRESS); - std::array link_key = { - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0}; + hci::AddressWithType remote(hci::Address({0x01, 0x02, 0x03, 0x04, 0x05, 0x06}), + hci::AddressType::PUBLIC_DEVICE_ADDRESS); + std::array link_key = {0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0}; std::shared_ptr record = std::make_shared(remote); record->SetLinkKey(link_key, hci::KeyType::DEBUG_COMBINATION); diff --git a/system/gd/security/security_manager.cc b/system/gd/security/security_manager.cc index ed3b91fa208..5d7164fe22c 100644 --- a/system/gd/security/security_manager.cc +++ b/system/gd/security/security_manager.cc @@ -26,8 +26,8 @@ namespace security { ISecurityManagerListener::~ISecurityManagerListener() {} void SecurityManager::Init() { - security_handler_->Post( - common::BindOnce(&internal::SecurityManagerImpl::Init, common::Unretained(security_manager_impl_))); + security_handler_->Post(common::BindOnce(&internal::SecurityManagerImpl::Init, + common::Unretained(security_manager_impl_))); } void SecurityManager::CreateBond(hci::AddressWithType device) { @@ -36,21 +36,20 @@ void SecurityManager::CreateBond(hci::AddressWithType device) { std::forward(device))); } -void SecurityManager::CreateBondOutOfBand( - hci::AddressWithType device, pairing::OobData remote_p192_oob_data, pairing::OobData remote_p256_oob_data) { - security_handler_->Post(common::BindOnce( - &internal::SecurityManagerImpl::CreateBondOutOfBand, - common::Unretained(security_manager_impl_), - std::forward(device), - remote_p192_oob_data, - remote_p256_oob_data)); +void SecurityManager::CreateBondOutOfBand(hci::AddressWithType device, + pairing::OobData remote_p192_oob_data, + pairing::OobData remote_p256_oob_data) { + security_handler_->Post(common::BindOnce(&internal::SecurityManagerImpl::CreateBondOutOfBand, + common::Unretained(security_manager_impl_), + std::forward(device), + remote_p192_oob_data, remote_p256_oob_data)); } void SecurityManager::GetOutOfBandData(channel::SecurityCommandStatusCallback callback) { - security_handler_->Post(common::BindOnce( - &internal::SecurityManagerImpl::GetOutOfBandData, - common::Unretained(security_manager_impl_), - std::forward(callback))); + security_handler_->Post( + common::BindOnce(&internal::SecurityManagerImpl::GetOutOfBandData, + common::Unretained(security_manager_impl_), + std::forward(callback))); } void SecurityManager::CreateBondLe(hci::AddressWithType device) { @@ -73,54 +72,60 @@ void SecurityManager::RemoveBond(hci::AddressWithType device) { void SecurityManager::SetUserInterfaceHandler(UI* user_interface, os::Handler* handler) { security_handler_->Post(common::BindOnce(&internal::SecurityManagerImpl::SetUserInterfaceHandler, - common::Unretained(security_manager_impl_), user_interface, handler)); + common::Unretained(security_manager_impl_), + user_interface, handler)); } // TODO(jpawlowski): remove once we have config file abstraction in cert tests void SecurityManager::SetLeInitiatorAddressPolicyForTest( - hci::LeAddressManager::AddressPolicy address_policy, - hci::AddressWithType fixed_address, - hci::Octet16 rotation_irk, - std::chrono::milliseconds minimum_rotation_time, - std::chrono::milliseconds maximum_rotation_time) { + hci::LeAddressManager::AddressPolicy address_policy, hci::AddressWithType fixed_address, + hci::Octet16 rotation_irk, std::chrono::milliseconds minimum_rotation_time, + std::chrono::milliseconds maximum_rotation_time) { security_handler_->Post(common::BindOnce( - &internal::SecurityManagerImpl::SetLeInitiatorAddressPolicyForTest, - common::Unretained(security_manager_impl_), - address_policy, - fixed_address, - rotation_irk, - minimum_rotation_time, - maximum_rotation_time)); + &internal::SecurityManagerImpl::SetLeInitiatorAddressPolicyForTest, + common::Unretained(security_manager_impl_), address_policy, fixed_address, rotation_irk, + minimum_rotation_time, maximum_rotation_time)); } -void SecurityManager::RegisterCallbackListener(ISecurityManagerListener* listener, os::Handler* handler) { +void SecurityManager::RegisterCallbackListener(ISecurityManagerListener* listener, + os::Handler* handler) { security_handler_->Post(common::BindOnce(&internal::SecurityManagerImpl::RegisterCallbackListener, - common::Unretained(security_manager_impl_), listener, handler)); + common::Unretained(security_manager_impl_), listener, + handler)); } void SecurityManager::UnregisterCallbackListener(ISecurityManagerListener* listener) { - security_handler_->Post(common::BindOnce(&internal::SecurityManagerImpl::UnregisterCallbackListener, - common::Unretained(security_manager_impl_), listener)); + security_handler_->Post( + common::BindOnce(&internal::SecurityManagerImpl::UnregisterCallbackListener, + common::Unretained(security_manager_impl_), listener)); } -void SecurityManager::OnPairingPromptAccepted(const bluetooth::hci::AddressWithType& address, bool confirmed) { +void SecurityManager::OnPairingPromptAccepted(const bluetooth::hci::AddressWithType& address, + bool confirmed) { security_handler_->Post(common::BindOnce(&internal::SecurityManagerImpl::OnPairingPromptAccepted, - common::Unretained(security_manager_impl_), address, confirmed)); + common::Unretained(security_manager_impl_), address, + confirmed)); } -void SecurityManager::OnConfirmYesNo(const bluetooth::hci::AddressWithType& address, bool confirmed) { +void SecurityManager::OnConfirmYesNo(const bluetooth::hci::AddressWithType& address, + bool confirmed) { security_handler_->Post(common::BindOnce(&internal::SecurityManagerImpl::OnConfirmYesNo, - common::Unretained(security_manager_impl_), address, confirmed)); + common::Unretained(security_manager_impl_), address, + confirmed)); } -void SecurityManager::OnPasskeyEntry(const bluetooth::hci::AddressWithType& address, uint32_t passkey) { +void SecurityManager::OnPasskeyEntry(const bluetooth::hci::AddressWithType& address, + uint32_t passkey) { security_handler_->Post(common::BindOnce(&internal::SecurityManagerImpl::OnPasskeyEntry, - common::Unretained(security_manager_impl_), address, passkey)); + common::Unretained(security_manager_impl_), address, + passkey)); } -void SecurityManager::OnPinEntry(const bluetooth::hci::AddressWithType& address, std::vector pin) { - security_handler_->Post(common::BindOnce( - &internal::SecurityManagerImpl::OnPinEntry, common::Unretained(security_manager_impl_), address, std::move(pin))); +void SecurityManager::OnPinEntry(const bluetooth::hci::AddressWithType& address, + std::vector pin) { + security_handler_->Post(common::BindOnce(&internal::SecurityManagerImpl::OnPinEntry, + common::Unretained(security_manager_impl_), address, + std::move(pin))); } } // namespace security diff --git a/system/gd/security/security_manager.h b/system/gd/security/security_manager.h index 469bff0ca8a..b4ac6e620b4 100644 --- a/system/gd/security/security_manager.h +++ b/system/gd/security/security_manager.h @@ -34,7 +34,7 @@ namespace security { * encryption/decryption of communications. */ class SecurityManager : public UICallbacks { - public: +public: SecurityManager(const SecurityManager&) = delete; SecurityManager& operator=(const SecurityManager&) = delete; @@ -63,8 +63,8 @@ class SecurityManager : public UICallbacks { * @param remote_p192_oob_data comparison and random for p192 * @param remote_p256_oob_data comparison and random for p256 */ - void CreateBondOutOfBand( - hci::AddressWithType address, pairing::OobData remote_p192_oob_data, pairing::OobData remote_p256_oob_data); + void CreateBondOutOfBand(hci::AddressWithType address, pairing::OobData remote_p192_oob_data, + pairing::OobData remote_p256_oob_data); /** * Get the out of band data from the controller to send to another device @@ -102,12 +102,11 @@ class SecurityManager : public UICallbacks { /** * Specify the initiator address policy used for LE transport. Can only be called once. */ - void SetLeInitiatorAddressPolicyForTest( - hci::LeAddressManager::AddressPolicy address_policy, - hci::AddressWithType fixed_address, - hci::Octet16 rotation_irk, - std::chrono::milliseconds minimum_rotation_time, - std::chrono::milliseconds maximum_rotation_time); + void SetLeInitiatorAddressPolicyForTest(hci::LeAddressManager::AddressPolicy address_policy, + hci::AddressWithType fixed_address, + hci::Octet16 rotation_irk, + std::chrono::milliseconds minimum_rotation_time, + std::chrono::milliseconds maximum_rotation_time); /** * Register to listen for callback events from SecurityManager @@ -123,16 +122,19 @@ class SecurityManager : public UICallbacks { */ void UnregisterCallbackListener(ISecurityManagerListener* listener); - void OnPairingPromptAccepted(const bluetooth::hci::AddressWithType& address, bool confirmed) override; + void OnPairingPromptAccepted(const bluetooth::hci::AddressWithType& address, + bool confirmed) override; void OnConfirmYesNo(const bluetooth::hci::AddressWithType& address, bool confirmed) override; void OnPasskeyEntry(const bluetooth::hci::AddressWithType& address, uint32_t passkey) override; - void OnPinEntry(const bluetooth::hci::AddressWithType& address, std::vector pin) override; + void OnPinEntry(const bluetooth::hci::AddressWithType& address, + std::vector pin) override; - protected: - SecurityManager(os::Handler* security_handler, internal::SecurityManagerImpl* security_manager_impl) +protected: + SecurityManager(os::Handler* security_handler, + internal::SecurityManagerImpl* security_manager_impl) : security_handler_(security_handler), security_manager_impl_(security_manager_impl) {} - private: +private: os::Handler* security_handler_ = nullptr; internal::SecurityManagerImpl* security_manager_impl_; }; diff --git a/system/gd/security/security_manager_listener.h b/system/gd/security/security_manager_listener.h index c854575f13c..d3ea55155c9 100644 --- a/system/gd/security/security_manager_listener.h +++ b/system/gd/security/security_manager_listener.h @@ -27,7 +27,7 @@ namespace security { * Callback interface from SecurityManager. */ class ISecurityManagerListener { - public: +public: virtual ~ISecurityManagerListener() = 0; /** @@ -49,7 +49,8 @@ class ISecurityManagerListener { * * @param address of the device that failed to bond */ - virtual void OnDeviceBondFailed(bluetooth::hci::AddressWithType device, PairingFailure status) = 0; + virtual void OnDeviceBondFailed(bluetooth::hci::AddressWithType device, + PairingFailure status) = 0; /** * Called as a result of a failure during the bonding process. diff --git a/system/gd/security/security_module.cc b/system/gd/security/security_module.cc index 9f9299d56f0..2a953633ad9 100644 --- a/system/gd/security/security_module.cc +++ b/system/gd/security/security_module.cc @@ -39,19 +39,15 @@ namespace security { const ModuleFactory SecurityModule::Factory = ModuleFactory([]() { return new SecurityModule(); }); struct SecurityModule::impl { - impl( - os::Handler* security_handler, - l2cap::le::L2capLeModule* l2cap_le_module, - l2cap::classic::L2capClassicModule* l2cap_classic_module, - hci::HciLayer* hci_layer, - hci::AclManager* acl_manager, - hci::Controller* controller, - storage::StorageModule* storage_module, - neighbor::NameDbModule* name_db_module) + impl(os::Handler* security_handler, l2cap::le::L2capLeModule* l2cap_le_module, + l2cap::classic::L2capClassicModule* l2cap_classic_module, hci::HciLayer* hci_layer, + hci::AclManager* acl_manager, hci::Controller* controller, + storage::StorageModule* storage_module, neighbor::NameDbModule* name_db_module) : security_handler_(security_handler), l2cap_classic_module_(l2cap_classic_module), l2cap_le_module_(l2cap_le_module), - security_manager_channel_(new channel::SecurityManagerChannel(security_handler_, hci_layer)), + security_manager_channel_( + new channel::SecurityManagerChannel(security_handler_, hci_layer)), hci_layer_(hci_layer), acl_manager_(acl_manager), controller_(controller), @@ -60,8 +56,8 @@ struct SecurityModule::impl { name_db_module_(name_db_module) { l2cap_classic_module->InjectSecurityEnforcementInterface(&l2cap_security_interface_); l2cap_le_module->InjectSecurityEnforcementInterface(&l2cap_security_interface_); - security_manager_channel_->SetSecurityInterface( - l2cap_classic_module->GetSecurityInterface(security_handler_, security_manager_channel_)); + security_manager_channel_->SetSecurityInterface(l2cap_classic_module->GetSecurityInterface( + security_handler_, security_manager_channel_)); } os::Handler* security_handler_; @@ -75,14 +71,9 @@ struct SecurityModule::impl { L2capSecurityModuleInterface l2cap_security_interface_; neighbor::NameDbModule* name_db_module_; - internal::SecurityManagerImpl security_manager_impl{security_handler_, - l2cap_le_module_, - security_manager_channel_, - hci_layer_, - acl_manager_, - controller_, - storage_module_, - name_db_module_}; + internal::SecurityManagerImpl security_manager_impl{ + security_handler_, l2cap_le_module_, security_manager_channel_, hci_layer_, + acl_manager_, controller_, storage_module_, name_db_module_}; ~impl() { delete security_manager_channel_; @@ -103,32 +94,24 @@ void SecurityModule::ListDependencies(ModuleList* list) const { void SecurityModule::Start() { pimpl_ = std::make_unique( - GetHandler(), - GetDependency(), - GetDependency(), - GetDependency(), - GetDependency(), - GetDependency(), - GetDependency(), - GetDependency()); + GetHandler(), GetDependency(), + GetDependency(), GetDependency(), + GetDependency(), GetDependency(), + GetDependency(), GetDependency()); } -void SecurityModule::Stop() { - pimpl_.reset(); -} +void SecurityModule::Stop() { pimpl_.reset(); } -std::string SecurityModule::ToString() const { - return "Security Module"; -} +std::string SecurityModule::ToString() const { return "Security Module"; } std::unique_ptr SecurityModule::GetSecurityManager() { return std::unique_ptr( - new SecurityManager(pimpl_->security_handler_, &pimpl_->security_manager_impl)); + new SecurityManager(pimpl_->security_handler_, &pimpl_->security_manager_impl)); } std::unique_ptr SecurityModule::GetFacadeConfigurationApi() { return std::unique_ptr( - new FacadeConfigurationApi(pimpl_->security_handler_, &pimpl_->security_manager_impl)); + new FacadeConfigurationApi(pimpl_->security_handler_, &pimpl_->security_manager_impl)); } } // namespace security diff --git a/system/gd/security/security_module.h b/system/gd/security/security_module.h index 68ba2dacd1b..3caa8921a9f 100644 --- a/system/gd/security/security_module.h +++ b/system/gd/security/security_module.h @@ -25,7 +25,7 @@ namespace bluetooth { namespace security { class SecurityModule : public bluetooth::Module { - public: +public: SecurityModule() = default; SecurityModule(const SecurityModule&) = delete; SecurityModule& operator=(const SecurityModule&) = delete; @@ -40,13 +40,14 @@ class SecurityModule : public bluetooth::Module { /** * Facade configuration API. * - *

This allows you to set thins like IO Capabilities, Authentication Requirements, and OOB Data. + *

This allows you to set thins like IO Capabilities, Authentication Requirements, and OOB + * Data. */ std::unique_ptr GetFacadeConfigurationApi(); static const ModuleFactory Factory; - protected: +protected: void ListDependencies(ModuleList* list) const override; void Start() override; @@ -55,7 +56,7 @@ class SecurityModule : public bluetooth::Module { std::string ToString() const override; - private: +private: struct impl; std::unique_ptr pimpl_; }; diff --git a/system/gd/security/test/ecdh_keys_test.cc b/system/gd/security/test/ecdh_keys_test.cc index 11d59c511f1..3927e7f8cec 100644 --- a/system/gd/security/test/ecdh_keys_test.cc +++ b/system/gd/security/test/ecdh_keys_test.cc @@ -36,15 +36,16 @@ namespace bluetooth { namespace security { class EcdhKeysTest : public testing::Test { - protected: +protected: void SetUp() {} void TearDown() {} - public: +public: }; -/* This test generates two pairs of keys, computes the Diffie–Hellman key using both, and verifies that they match */ +/* This test generates two pairs of keys, computes the Diffie–Hellman key using both, and verifies + * that they match */ TEST_F(EcdhKeysTest, test_generated) { std::srand(std::time(nullptr)); @@ -58,47 +59,53 @@ TEST_F(EcdhKeysTest, test_generated) { if (dhkeya != dhkeyb) { log::error("private key a : {}", base::HexEncode(private_key_a.data(), private_key_a.size())); - log::error( - "public key a.x : {}", base::HexEncode(public_key_a.x.data(), public_key_a.x.size())); - log::error( - "public key a.y : {}", base::HexEncode(public_key_a.y.data(), public_key_a.y.size())); + log::error("public key a.x : {}", + base::HexEncode(public_key_a.x.data(), public_key_a.x.size())); + log::error("public key a.y : {}", + base::HexEncode(public_key_a.y.data(), public_key_a.y.size())); log::error("private key b : {}", base::HexEncode(private_key_b.data(), private_key_b.size())); - log::error( - "public key b.x : {}", base::HexEncode(public_key_b.x.data(), public_key_b.x.size())); - log::error( - "public key b.y : {}", base::HexEncode(public_key_b.y.data(), public_key_b.y.size())); + log::error("public key b.x : {}", + base::HexEncode(public_key_b.x.data(), public_key_b.x.size())); + log::error("public key b.y : {}", + base::HexEncode(public_key_b.y.data(), public_key_b.y.size())); log::error("dhkeya : {}", base::HexEncode(dhkeya.data(), dhkeya.size())); log::error("dhkeyb : {}", base::HexEncode(dhkeyb.data(), dhkeyb.size())); } } -/* This test uses two fixed pairs of keys, computes the Diffie–Hellman key using both, and verifies that they match -precomputed value. +/* This test uses two fixed pairs of keys, computes the Diffie–Hellman key using both, and verifies +that they match precomputed value. -This code is also useful during debuging - one can replace fixed values with values from failed exchagne to verify which -side did bad computation. */ +This code is also useful during debugging - one can replace fixed values with values from failed +exchange to verify which side did bad computation. */ TEST_F(EcdhKeysTest, test_static) { - std::array private_key_a = {0x3E, 0xC8, 0x2A, 0x32, 0xB3, 0x75, 0x76, 0xBA, 0x7D, 0xB8, 0xB4, - 0x7B, 0xA0, 0x8A, 0xA3, 0xC3, 0xF2, 0x03, 0x1A, 0x53, 0xF6, 0x52, - 0x26, 0x32, 0xB6, 0xAE, 0x57, 0x3F, 0x13, 0x15, 0x29, 0x51}; + std::array private_key_a = {0x3E, 0xC8, 0x2A, 0x32, 0xB3, 0x75, 0x76, 0xBA, + 0x7D, 0xB8, 0xB4, 0x7B, 0xA0, 0x8A, 0xA3, 0xC3, + 0xF2, 0x03, 0x1A, 0x53, 0xF6, 0x52, 0x26, 0x32, + 0xB6, 0xAE, 0x57, 0x3F, 0x13, 0x15, 0x29, 0x51}; bluetooth::security::EcdhPublicKey public_key_a; - uint8_t ax[32] = {0xDC, 0x88, 0xD0, 0xE5, 0x59, 0x73, 0xF2, 0x41, 0x88, 0x6C, 0xB4, 0x45, 0x8B, 0x61, 0x3B, 0x10, - 0xF5, 0xD4, 0xD2, 0x5B, 0x4E, 0xA1, 0x7F, 0x94, 0xE3, 0xA9, 0x38, 0xF8, 0x84, 0xD4, 0x98, 0x10}; - uint8_t ay[32] = {0x3D, 0x13, 0x76, 0x4F, 0xD1, 0x29, 0x6E, 0xEC, 0x8D, 0xF6, 0x70, 0x33, 0x8B, 0xA7, 0x18, 0xEA, - 0x84, 0x15, 0xE8, 0x8C, 0x4A, 0xC8, 0x76, 0x45, 0x90, 0x98, 0xBA, 0x52, 0x8B, 0x00, 0x69, 0xAF}; + uint8_t ax[32] = {0xDC, 0x88, 0xD0, 0xE5, 0x59, 0x73, 0xF2, 0x41, 0x88, 0x6C, 0xB4, + 0x45, 0x8B, 0x61, 0x3B, 0x10, 0xF5, 0xD4, 0xD2, 0x5B, 0x4E, 0xA1, + 0x7F, 0x94, 0xE3, 0xA9, 0x38, 0xF8, 0x84, 0xD4, 0x98, 0x10}; + uint8_t ay[32] = {0x3D, 0x13, 0x76, 0x4F, 0xD1, 0x29, 0x6E, 0xEC, 0x8D, 0xF6, 0x70, + 0x33, 0x8B, 0xA7, 0x18, 0xEA, 0x84, 0x15, 0xE8, 0x8C, 0x4A, 0xC8, + 0x76, 0x45, 0x90, 0x98, 0xBA, 0x52, 0x8B, 0x00, 0x69, 0xAF}; memcpy(public_key_a.x.data(), ax, 32); memcpy(public_key_a.y.data(), ay, 32); - std::array private_key_b = {0xDD, 0x53, 0x84, 0x91, 0xC8, 0xFA, 0x4B, 0x45, 0xB2, 0xFF, 0xC0, - 0x53, 0x89, 0x64, 0x16, 0x7B, 0x67, 0x30, 0xCE, 0x5D, 0x82, 0xF4, - 0x8F, 0x38, 0xA2, 0xE6, 0x78, 0xB6, 0xFB, 0xA1, 0x07, 0xD8}; + std::array private_key_b = {0xDD, 0x53, 0x84, 0x91, 0xC8, 0xFA, 0x4B, 0x45, + 0xB2, 0xFF, 0xC0, 0x53, 0x89, 0x64, 0x16, 0x7B, + 0x67, 0x30, 0xCE, 0x5D, 0x82, 0xF4, 0x8F, 0x38, + 0xA2, 0xE6, 0x78, 0xB6, 0xFB, 0xA1, 0x07, 0xD8}; bluetooth::security::EcdhPublicKey public_key_b; - uint8_t bx[32] = {0x23, 0x1A, 0xEC, 0xFE, 0x7D, 0xC1, 0x20, 0x2F, 0x03, 0x3E, 0x9A, 0xAA, 0x99, 0x55, 0x78, 0x86, - 0x58, 0xCB, 0x37, 0x68, 0x7D, 0xE1, 0xFF, 0x19, 0x33, 0xF8, 0xCB, 0x7A, 0x17, 0xAB, 0x0B, 0x73}; - uint8_t by[32] = {0x4C, 0x25, 0xE2, 0x42, 0x3C, 0x69, 0x0E, 0x3B, 0xC0, 0xEF, 0x94, 0x09, 0x4D, 0x3F, 0x96, 0xBB, - 0x18, 0xF2, 0x55, 0x81, 0x71, 0x5A, 0xDE, 0xC4, 0x3E, 0xF9, 0x6F, 0xA9, 0xAF, 0x04, 0x4E, 0x86}; + uint8_t bx[32] = {0x23, 0x1A, 0xEC, 0xFE, 0x7D, 0xC1, 0x20, 0x2F, 0x03, 0x3E, 0x9A, + 0xAA, 0x99, 0x55, 0x78, 0x86, 0x58, 0xCB, 0x37, 0x68, 0x7D, 0xE1, + 0xFF, 0x19, 0x33, 0xF8, 0xCB, 0x7A, 0x17, 0xAB, 0x0B, 0x73}; + uint8_t by[32] = {0x4C, 0x25, 0xE2, 0x42, 0x3C, 0x69, 0x0E, 0x3B, 0xC0, 0xEF, 0x94, + 0x09, 0x4D, 0x3F, 0x96, 0xBB, 0x18, 0xF2, 0x55, 0x81, 0x71, 0x5A, + 0xDE, 0xC4, 0x3E, 0xF9, 0x6F, 0xA9, 0xAF, 0x04, 0x4E, 0x86}; memcpy(public_key_b.x.data(), bx, 32); memcpy(public_key_b.y.data(), by, 32); diff --git a/system/gd/security/test/fake_hci_layer.h b/system/gd/security/test/fake_hci_layer.h index 4c0b11a7589..70b6facb05f 100644 --- a/system/gd/security/test/fake_hci_layer.h +++ b/system/gd/security/test/fake_hci_layer.h @@ -45,16 +45,18 @@ PacketView GetPacketView(std::unique_ptr command_packet, - ContextualOnceCallback on_complete_function) - : command(std::move(command_packet)), waiting_for_status_(false), on_complete(std::move(on_complete_function)) {} - - CommandQueueEntry( - std::unique_ptr command_packet, - ContextualOnceCallback on_status_function) - : command(std::move(command_packet)), waiting_for_status_(true), on_status(std::move(on_status_function)) {} +public: + CommandQueueEntry(std::unique_ptr command_packet, + ContextualOnceCallback on_complete_function) + : command(std::move(command_packet)), + waiting_for_status_(false), + on_complete(std::move(on_complete_function)) {} + + CommandQueueEntry(std::unique_ptr command_packet, + ContextualOnceCallback on_status_function) + : command(std::move(command_packet)), + waiting_for_status_(true), + on_status(std::move(on_status_function)) {} std::unique_ptr command; bool waiting_for_status_; @@ -65,18 +67,18 @@ class CommandQueueEntry { } // namespace class FakeHciLayer : public HciLayer { - public: - void EnqueueCommand( - std::unique_ptr command, - ContextualOnceCallback on_status) override { - auto command_queue_entry = std::make_unique(std::move(command), std::move(on_status)); +public: + void EnqueueCommand(std::unique_ptr command, + ContextualOnceCallback on_status) override { + auto command_queue_entry = + std::make_unique(std::move(command), std::move(on_status)); command_queue_.push(std::move(command_queue_entry)); } - void EnqueueCommand( - std::unique_ptr command, - ContextualOnceCallback on_complete) override { - auto command_queue_entry = std::make_unique(std::move(command), std::move(on_complete)); + void EnqueueCommand(std::unique_ptr command, + ContextualOnceCallback on_complete) override { + auto command_queue_entry = + std::make_unique(std::move(command), std::move(on_complete)); command_queue_.push(std::move(command_queue_entry)); } @@ -87,7 +89,8 @@ class FakeHciLayer : public HciLayer { return last; } - void RegisterEventHandler(EventCode event_code, common::ContextualCallback event_handler) override { + void RegisterEventHandler(EventCode event_code, + common::ContextualCallback event_handler) override { registered_events_[event_code] = event_handler; } @@ -108,7 +111,7 @@ class FakeHciLayer : public HciLayer { void Start() override {} void Stop() override {} - private: +private: std::map> registered_events_; std::queue> command_queue_; }; diff --git a/system/gd/security/test/fake_l2cap_test.cc b/system/gd/security/test/fake_l2cap_test.cc index 1cdb9905ecc..9da40644761 100644 --- a/system/gd/security/test/fake_l2cap_test.cc +++ b/system/gd/security/test/fake_l2cap_test.cc @@ -70,30 +70,31 @@ void sync_handler(os::Handler* handler) { } // namespace class FakeL2capTest : public testing::Test { - protected: +protected: void SetUp() {} void TearDown() {} - public: +public: }; -void my_enqueue_callback() { - log::info("packet ready for dequeue!"); -} +void my_enqueue_callback() { log::info("packet ready for dequeue!"); } /* This test verifies that Just Works pairing flow works. - * Both simulated devices specify capabilities as NO_INPUT_NO_OUTPUT, and secure connecitons support */ + * Both simulated devices specify capabilities as NO_INPUT_NO_OUTPUT, and secure connections support + */ TEST_F(FakeL2capTest, test_bidi_queue_example) { os::Thread* thread_ = new os::Thread("test_thread", os::Thread::Priority::NORMAL); os::Handler* handler_ = new os::Handler(thread_); - common::BidiQueue> bidi_queue{10}; + common::BidiQueue> + bidi_queue{10}; os::EnqueueBuffer enqueue_buffer{bidi_queue.GetDownEnd()}; // This is test packet we are sending down the queue to the other end; - auto test_packet = EncryptionChangeBuilder::Create(ErrorCode::SUCCESS, 0x0020, EncryptionEnabled::ON); + auto test_packet = + EncryptionChangeBuilder::Create(ErrorCode::SUCCESS, 0x0020, EncryptionEnabled::ON); // send the packet through the queue enqueue_buffer.Enqueue(std::move(test_packet), handler_); @@ -107,14 +108,16 @@ TEST_F(FakeL2capTest, test_bidi_queue_example) { EXPECT_TRUE(test_packet_from_other_end != nullptr); // This is how we receive data - os::EnqueueBuffer> up_end_enqueue_buffer{bidi_queue.GetUpEnd()}; + os::EnqueueBuffer> up_end_enqueue_buffer{ + bidi_queue.GetUpEnd()}; bidi_queue.GetDownEnd()->RegisterDequeue(handler_, common::Bind(&my_enqueue_callback)); auto packet_one = std::make_unique(); packet_one->AddOctets({1, 2, 3}); - up_end_enqueue_buffer.Enqueue(std::make_unique>(GetPacketView(std::move(packet_one))), - handler_); + up_end_enqueue_buffer.Enqueue( + std::make_unique>(GetPacketView(std::move(packet_one))), + handler_); sync_handler(handler_); diff --git a/system/gd/security/test/fake_name_db.h b/system/gd/security/test/fake_name_db.h index 704dc4083d6..30e1a6ba4fb 100644 --- a/system/gd/security/test/fake_name_db.h +++ b/system/gd/security/test/fake_name_db.h @@ -22,24 +22,20 @@ namespace bluetooth { namespace security { class FakeNameDbModule : public neighbor::NameDbModule { - public: +public: FakeNameDbModule() {} void ListDependencies(ModuleList* /* list */) const override {} void Start() override {} void Stop() override {} - std::string ToString() const override { - return std::string("FakeNameDbModule"); - } + std::string ToString() const override { return std::string("FakeNameDbModule"); } - void ReadRemoteNameRequest( - hci::Address address, neighbor::ReadRemoteNameDbCallback callback, os::Handler* handler) override { + void ReadRemoteNameRequest(hci::Address address, neighbor::ReadRemoteNameDbCallback callback, + os::Handler* handler) override { handler->Call(std::move(callback), address, true); } - bool IsNameCached(hci::Address /* address */) const { - return true; - } + bool IsNameCached(hci::Address /* address */) const { return true; } neighbor::RemoteName ReadCachedRemoteName(hci::Address /* address */) const { neighbor::RemoteName name = {'t', 'e', 's', 't'}; diff --git a/system/gd/security/test/fake_security_interface.h b/system/gd/security/test/fake_security_interface.h index 2066abf0001..4d29a8f182b 100644 --- a/system/gd/security/test/fake_security_interface.h +++ b/system/gd/security/test/fake_security_interface.h @@ -22,15 +22,14 @@ namespace bluetooth { namespace security { class FakeLinkSecurityInterface : public l2cap::classic::LinkSecurityInterface { - public: - FakeLinkSecurityInterface(l2cap::classic::LinkSecurityInterfaceListener* listener, hci::Address address) +public: + FakeLinkSecurityInterface(l2cap::classic::LinkSecurityInterfaceListener* listener, + hci::Address address) : listener_(listener), address_(address) {} - hci::Address GetRemoteAddress() { - return address_; - } + hci::Address GetRemoteAddress() { return address_; } void Hold() override {} - void EnsureAuthenticated() override{}; + void EnsureAuthenticated() override {} void EnsureEncrypted() override {} @@ -38,29 +37,26 @@ class FakeLinkSecurityInterface : public l2cap::classic::LinkSecurityInterface { // TODO(optedoblivion): Simulate the delay listener_->OnLinkDisconnected(address_); } - void Disconnect() override { - listener_->OnLinkDisconnected(address_); - } - uint16_t GetAclHandle() override { - return 0; - } + void Disconnect() override { listener_->OnLinkDisconnected(address_); } + uint16_t GetAclHandle() override { return 0; } - private: +private: l2cap::classic::LinkSecurityInterfaceListener* listener_ = nullptr; hci::Address address_; }; class FakeSecurityInterface : public l2cap::classic::SecurityInterface { - public: - FakeSecurityInterface(os::Handler* handler, l2cap::classic::LinkSecurityInterfaceListener* listener) +public: + FakeSecurityInterface(os::Handler* handler, + l2cap::classic::LinkSecurityInterfaceListener* listener) : handler_(handler), listener_(listener) {} ~FakeSecurityInterface() {} void InitiateConnectionForSecurity(hci::Address remote) override { listener_->OnLinkConnected(std::make_unique(listener_, remote)); - }; + } void Unregister() override {} - private: +private: os::Handler* handler_ __attribute__((unused)); l2cap::classic::LinkSecurityInterfaceListener* listener_ __attribute__((unused)); }; diff --git a/system/gd/security/test/mocks.h b/system/gd/security/test/mocks.h index 324cb6abea9..dcf4e291896 100644 --- a/system/gd/security/test/mocks.h +++ b/system/gd/security/test/mocks.h @@ -28,7 +28,7 @@ namespace bluetooth { namespace security { class UIMock : public UI { - public: +public: UIMock() = default; UIMock(const UIMock&) = delete; UIMock& operator=(const UIMock&) = delete; @@ -36,7 +36,8 @@ class UIMock : public UI { ~UIMock() = default; // Convert these to accept ConfirmationData - MOCK_METHOD2(DisplayPairingPrompt, void(const bluetooth::hci::AddressWithType& address, std::string name)); + MOCK_METHOD2(DisplayPairingPrompt, + void(const bluetooth::hci::AddressWithType& address, std::string name)); MOCK_METHOD1(Cancel, void(const bluetooth::hci::AddressWithType& address)); MOCK_METHOD1(DisplayConfirmValue, void(ConfirmationData)); MOCK_METHOD1(DisplayYesNoDialog, void(ConfirmationData)); @@ -46,11 +47,13 @@ class UIMock : public UI { }; class LeSecurityInterfaceMock : public hci::LeSecurityInterface { - public: - MOCK_METHOD2(EnqueueCommand, void(std::unique_ptr command, - common::ContextualOnceCallback on_complete)); - MOCK_METHOD2(EnqueueCommand, void(std::unique_ptr command, - common::ContextualOnceCallback on_status)); +public: + MOCK_METHOD2(EnqueueCommand, + void(std::unique_ptr command, + common::ContextualOnceCallback on_complete)); + MOCK_METHOD2(EnqueueCommand, + void(std::unique_ptr command, + common::ContextualOnceCallback on_status)); }; } // namespace security diff --git a/system/gd/security/test/pairing_handler_le_pair_test.cc b/system/gd/security/test/pairing_handler_le_pair_test.cc index 8e240e2fc68..96d13517333 100644 --- a/system/gd/security/test/pairing_handler_le_pair_test.cc +++ b/system/gd/security/test/pairing_handler_le_pair_test.cc @@ -49,7 +49,8 @@ using bluetooth::hci::LeSecurityCommandBuilder; // run: // out/host/linux-x86/nativetest/bluetooth_test_gd/bluetooth_test_gd --gtest_filter=Pairing* -// adb shell /data/nativetest/bluetooth_test_gd/bluetooth_test_gd --gtest_filter=PairingHandlerPairTest.* +// adb shell /data/nativetest/bluetooth_test_gd/bluetooth_test_gd +// --gtest_filter=PairingHandlerPairTest.* // --gtest_repeat=10 --gtest_shuffle namespace bluetooth { @@ -89,15 +90,15 @@ Address ADDRESS_CENTRAL{{0x26, 0x64, 0x76, 0x86, 0xab, 0xba}}; AddressType ADDRESS_TYPE_CENTRAL = AddressType::RANDOM_DEVICE_ADDRESS; Address IDENTITY_ADDRESS_CENTRAL{{0x12, 0x34, 0x56, 0x78, 0x90, 0xaa}}; AddressType IDENTITY_ADDRESS_TYPE_CENTRAL = AddressType::PUBLIC_DEVICE_ADDRESS; -hci::Octet16 IRK_CENTRAL = { - 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f}; +hci::Octet16 IRK_CENTRAL = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, + 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f}; Address ADDRESS_PERIPHERAL{{0x33, 0x58, 0x24, 0x76, 0x11, 0x89}}; AddressType ADDRESS_TYPE_PERIPHERAL = AddressType::RANDOM_DEVICE_ADDRESS; Address IDENTITY_ADDRESS_PERIPHERAL{{0x21, 0x43, 0x65, 0x87, 0x09, 0x44}}; AddressType IDENTITY_ADDRESS_TYPE_PERIPHERAL = AddressType::PUBLIC_DEVICE_ADDRESS; -hci::Octet16 IRK_PERIPHERAL = { - 0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01}; +hci::Octet16 IRK_PERIPHERAL = {0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08, + 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01}; std::optional pairing_result_central; std::optional pairing_result_peripheral; @@ -105,8 +106,8 @@ std::optional pairing_result_peripheral; void OnPairingFinishedCentral(PairingResultOrFailure r) { pairing_result_central = r; if (std::holds_alternative(r)) { - log::info( - "pairing finished successfully with {}", std::get(r).connection_address); + log::info("pairing finished successfully with {}", + std::get(r).connection_address); } else { log::info("pairing with ... failed: {}", std::get(r).message); } @@ -115,8 +116,8 @@ void OnPairingFinishedCentral(PairingResultOrFailure r) { void OnPairingFinishedPeripheral(PairingResultOrFailure r) { pairing_result_peripheral = r; if (std::holds_alternative(r)) { - log::info( - "pairing finished successfully with {}", std::get(r).connection_address); + log::info("pairing finished successfully with {}", + std::get(r).connection_address); } else { log::info("pairing with ... failed: {}", std::get(r).message); } @@ -124,13 +125,16 @@ void OnPairingFinishedPeripheral(PairingResultOrFailure r) { }; // namespace -// We obtain this mutex when we start initializing the handlers, and relese it when both handlers are initialized +// We obtain this mutex when we start initializing the handlers, and relese it when both handlers +// are initialized std::mutex handlers_initialization_guard; class PairingHandlerPairTest : public testing::Test { void dequeue_callback_central() { auto packet_bytes_view = l2cap_->GetQueueAUpEnd()->TryDequeue(); - if (!packet_bytes_view) log::error("Received dequeue, but no data ready..."); + if (!packet_bytes_view) { + log::error("Received dequeue, but no data ready..."); + } auto temp_cmd_view = CommandView::Create(*packet_bytes_view); if (!first_command_sent) { @@ -139,14 +143,18 @@ class PairingHandlerPairTest : public testing::Test { return; } - if (!pairing_handler_a) log::fatal("Peripheral handler not initlized yet!"); + if (!pairing_handler_a) { + log::fatal("Peripheral handler not initialized yet!"); + } pairing_handler_a->OnCommandView(CommandView::Create(temp_cmd_view)); } void dequeue_callback_peripheral() { auto packet_bytes_view = l2cap_->GetQueueBUpEnd()->TryDequeue(); - if (!packet_bytes_view) log::error("Received dequeue, but no data ready..."); + if (!packet_bytes_view) { + log::error("Received dequeue, but no data ready..."); + } auto temp_cmd_view = CommandView::Create(*packet_bytes_view); if (!first_command_sent) { @@ -155,12 +163,14 @@ class PairingHandlerPairTest : public testing::Test { return; } - if (!pairing_handler_b) log::fatal("Central handler not initlized yet!"); + if (!pairing_handler_b) { + log::fatal("Central handler not initialized yet!"); + } pairing_handler_b->OnCommandView(CommandView::Create(temp_cmd_view)); } - protected: +protected: void SetUp() { thread_ = new os::Thread("test_thread", os::Thread::Priority::NORMAL); handler_ = new os::Handler(thread_); @@ -169,59 +179,65 @@ class PairingHandlerPairTest : public testing::Test { // central sends it's packet into l2cap->down_buffer_b_ // peripheral sends it's packet into l2cap->down_buffer_a_ l2cap_->GetQueueAUpEnd()->RegisterDequeue( - handler_, common::Bind(&PairingHandlerPairTest::dequeue_callback_central, common::Unretained(this))); + handler_, common::Bind(&PairingHandlerPairTest::dequeue_callback_central, + common::Unretained(this))); l2cap_->GetQueueBUpEnd()->RegisterDequeue( - handler_, common::Bind(&PairingHandlerPairTest::dequeue_callback_peripheral, common::Unretained(this))); + handler_, common::Bind(&PairingHandlerPairTest::dequeue_callback_peripheral, + common::Unretained(this))); - up_buffer_a_ = std::make_unique>(l2cap_->GetQueueAUpEnd()); - up_buffer_b_ = std::make_unique>(l2cap_->GetQueueBUpEnd()); + up_buffer_a_ = std::make_unique>( + l2cap_->GetQueueAUpEnd()); + up_buffer_b_ = std::make_unique>( + l2cap_->GetQueueBUpEnd()); central_setup = { - .my_role = hci::Role::CENTRAL, - .my_connection_address = {ADDRESS_CENTRAL, ADDRESS_TYPE_CENTRAL}, - .my_identity_address = {IDENTITY_ADDRESS_CENTRAL, IDENTITY_ADDRESS_TYPE_CENTRAL}, - .my_identity_resolving_key = IRK_CENTRAL, - - .myPairingCapabilities = {.io_capability = IoCapability::NO_INPUT_NO_OUTPUT, - .oob_data_flag = OobDataFlag::NOT_PRESENT, - .auth_req = AuthReqMaskBondingFlag | AuthReqMaskMitm | AuthReqMaskSc, - .maximum_encryption_key_size = 16, - .initiator_key_distribution = KeyMaskId | KeyMaskSign, - .responder_key_distribution = KeyMaskId | KeyMaskSign}, - - .remotely_initiated = false, - .connection_handle = CONN_HANDLE_CENTRAL, - .remote_connection_address = {ADDRESS_PERIPHERAL, ADDRESS_TYPE_PERIPHERAL}, - .user_interface = ¢ral_user_interface, - .user_interface_handler = handler_, - .le_security_interface = ¢ral_le_security_mock, - .proper_l2cap_interface = up_buffer_a_.get(), - .l2cap_handler = handler_, - .OnPairingFinished = OnPairingFinishedCentral, + .my_role = hci::Role::CENTRAL, + .my_connection_address = {ADDRESS_CENTRAL, ADDRESS_TYPE_CENTRAL}, + .my_identity_address = {IDENTITY_ADDRESS_CENTRAL, IDENTITY_ADDRESS_TYPE_CENTRAL}, + .my_identity_resolving_key = IRK_CENTRAL, + + .myPairingCapabilities = {.io_capability = IoCapability::NO_INPUT_NO_OUTPUT, + .oob_data_flag = OobDataFlag::NOT_PRESENT, + .auth_req = AuthReqMaskBondingFlag | AuthReqMaskMitm | + AuthReqMaskSc, + .maximum_encryption_key_size = 16, + .initiator_key_distribution = KeyMaskId | KeyMaskSign, + .responder_key_distribution = KeyMaskId | KeyMaskSign}, + + .remotely_initiated = false, + .connection_handle = CONN_HANDLE_CENTRAL, + .remote_connection_address = {ADDRESS_PERIPHERAL, ADDRESS_TYPE_PERIPHERAL}, + .user_interface = ¢ral_user_interface, + .user_interface_handler = handler_, + .le_security_interface = ¢ral_le_security_mock, + .proper_l2cap_interface = up_buffer_a_.get(), + .l2cap_handler = handler_, + .OnPairingFinished = OnPairingFinishedCentral, }; peripheral_setup = { - .my_role = hci::Role::PERIPHERAL, - - .my_connection_address = {ADDRESS_PERIPHERAL, ADDRESS_TYPE_PERIPHERAL}, - .my_identity_address = {IDENTITY_ADDRESS_PERIPHERAL, IDENTITY_ADDRESS_TYPE_PERIPHERAL}, - .my_identity_resolving_key = IRK_PERIPHERAL, - - .myPairingCapabilities = {.io_capability = IoCapability::NO_INPUT_NO_OUTPUT, - .oob_data_flag = OobDataFlag::NOT_PRESENT, - .auth_req = AuthReqMaskBondingFlag | AuthReqMaskMitm | AuthReqMaskSc, - .maximum_encryption_key_size = 16, - .initiator_key_distribution = KeyMaskId | KeyMaskSign, - .responder_key_distribution = KeyMaskId | KeyMaskSign}, - .remotely_initiated = true, - .connection_handle = CONN_HANDLE_PERIPHERAL, - .remote_connection_address = {ADDRESS_CENTRAL, ADDRESS_TYPE_CENTRAL}, - .user_interface = &peripheral_user_interface, - .user_interface_handler = handler_, - .le_security_interface = &peripheral_le_security_mock, - .proper_l2cap_interface = up_buffer_b_.get(), - .l2cap_handler = handler_, - .OnPairingFinished = OnPairingFinishedPeripheral, + .my_role = hci::Role::PERIPHERAL, + + .my_connection_address = {ADDRESS_PERIPHERAL, ADDRESS_TYPE_PERIPHERAL}, + .my_identity_address = {IDENTITY_ADDRESS_PERIPHERAL, IDENTITY_ADDRESS_TYPE_PERIPHERAL}, + .my_identity_resolving_key = IRK_PERIPHERAL, + + .myPairingCapabilities = {.io_capability = IoCapability::NO_INPUT_NO_OUTPUT, + .oob_data_flag = OobDataFlag::NOT_PRESENT, + .auth_req = AuthReqMaskBondingFlag | AuthReqMaskMitm | + AuthReqMaskSc, + .maximum_encryption_key_size = 16, + .initiator_key_distribution = KeyMaskId | KeyMaskSign, + .responder_key_distribution = KeyMaskId | KeyMaskSign}, + .remotely_initiated = true, + .connection_handle = CONN_HANDLE_PERIPHERAL, + .remote_connection_address = {ADDRESS_CENTRAL, ADDRESS_TYPE_CENTRAL}, + .user_interface = &peripheral_user_interface, + .user_interface_handler = handler_, + .le_security_interface = &peripheral_le_security_mock, + .proper_l2cap_interface = up_buffer_b_.get(), + .l2cap_handler = handler_, + .OnPairingFinished = OnPairingFinishedPeripheral, }; RecordSuccessfulEncryptionComplete(); @@ -252,45 +268,49 @@ class PairingHandlerPairTest : public testing::Test { void RecordPairingPromptHandling(UIMock& ui_mock, std::unique_ptr* handler) { EXPECT_CALL(ui_mock, DisplayPairingPrompt(_, _)) - .Times(1) - .WillOnce(InvokeWithoutArgs([handler]() { - log::info("UI mock received pairing prompt"); - - { - // By grabbing the lock, we ensure initialization of both pairing handlers is finished. - std::lock_guard lock(handlers_initialization_guard); - } - - if (!(*handler)) log::fatal("handler not initalized yet!"); - // Simulate user accepting the pairing in UI - (*handler)->OnUiAction( - PairingEvent::PAIRING_ACCEPTED, 0x01 /* Non-zero value means success */); - })); + .Times(1) + .WillOnce(InvokeWithoutArgs([handler]() { + log::info("UI mock received pairing prompt"); + + { + // By grabbing the lock, we ensure initialization of both pairing handlers is + // finished. + std::lock_guard lock(handlers_initialization_guard); + } + + if (!(*handler)) { + log::fatal("handler not initialized yet!"); + } + // Simulate user accepting the pairing in UI + (*handler)->OnUiAction(PairingEvent::PAIRING_ACCEPTED, + 0x01 /* Non-zero value means success */); + })); } void RecordSuccessfulEncryptionComplete() { // For now, all tests are succeeding to go through Encryption. Record that in the setup. // Once we test failure cases, move this to each test EXPECT_CALL( - central_le_security_mock, - EnqueueCommand(_, Matcher>(_))) - .Times(1) - .WillOnce([](std::unique_ptr command, - common::ContextualOnceCallback on_status) { - // TODO: on_status.Run(); - - pairing_handler_a->OnHciEvent(EventBuilderToView( - EncryptionChangeBuilder::Create(ErrorCode::SUCCESS, CONN_HANDLE_CENTRAL, EncryptionEnabled::ON))); - - pairing_handler_b->OnHciEvent(EventBuilderToView( - hci::LeLongTermKeyRequestBuilder::Create(CONN_HANDLE_PERIPHERAL, {0, 0, 0, 0, 0, 0, 0, 0}, 0))); - - pairing_handler_b->OnHciEvent(EventBuilderToView( - EncryptionChangeBuilder::Create(ErrorCode::SUCCESS, CONN_HANDLE_PERIPHERAL, EncryptionEnabled::ON))); - }); + central_le_security_mock, + EnqueueCommand(_, Matcher>(_))) + .Times(1) + .WillOnce([](std::unique_ptr command, + common::ContextualOnceCallback on_status) { + // TODO: on_status.Run(); + + pairing_handler_a->OnHciEvent(EventBuilderToView(EncryptionChangeBuilder::Create( + ErrorCode::SUCCESS, CONN_HANDLE_CENTRAL, EncryptionEnabled::ON))); + + pairing_handler_b->OnHciEvent( + EventBuilderToView(hci::LeLongTermKeyRequestBuilder::Create( + CONN_HANDLE_PERIPHERAL, {0, 0, 0, 0, 0, 0, 0, 0}, 0))); + + pairing_handler_b->OnHciEvent(EventBuilderToView(EncryptionChangeBuilder::Create( + ErrorCode::SUCCESS, CONN_HANDLE_PERIPHERAL, EncryptionEnabled::ON))); + }); } - public: +public: std::unique_ptr WaitFirstL2capCommand() { while (!first_command_sent) { std::this_thread::sleep_for(1ms); @@ -319,7 +339,8 @@ class PairingHandlerPairTest : public testing::Test { }; /* This test verifies that Just Works pairing flow works. - * Both simulated devices specify capabilities as NO_INPUT_NO_OUTPUT, and secure connecitons support */ + * Both simulated devices specify capabilities as NO_INPUT_NO_OUTPUT, and secure connections support + */ TEST_F(PairingHandlerPairTest, test_secure_connections_just_works) { central_setup.myPairingCapabilities.io_capability = IoCapability::NO_INPUT_NO_OUTPUT; central_setup.myPairingCapabilities.oob_data_flag = OobDataFlag::NOT_PRESENT; @@ -335,23 +356,27 @@ TEST_F(PairingHandlerPairTest, test_secure_connections_just_works) { peripheral_setup.pairing_request = PairingRequestView::Create(*first_pkt); EXPECT_CALL(peripheral_user_interface, DisplayPairingPrompt(_, _)) - .Times(1) - .WillOnce(InvokeWithoutArgs([] { - log::info("UI mock received pairing prompt"); - - { - // By grabbing the lock, we ensure initialization of both pairing handlers is finished. - std::lock_guard lock(handlers_initialization_guard); - } - - if (!pairing_handler_b) log::fatal("handler not initalized yet!"); - - // Simulate user accepting the pairing in UI - pairing_handler_b->OnUiAction( - PairingEvent::PAIRING_ACCEPTED, 0x01 /* Non-zero value means success */); - })); - - pairing_handler_b = std::make_unique(PairingHandlerLe::PHASE1, peripheral_setup); + .Times(1) + .WillOnce(InvokeWithoutArgs([] { + log::info("UI mock received pairing prompt"); + + { + // By grabbing the lock, we ensure initialization of both pairing handlers is + // finished. + std::lock_guard lock(handlers_initialization_guard); + } + + if (!pairing_handler_b) { + log::fatal("handler not initialized yet!"); + } + + // Simulate user accepting the pairing in UI + pairing_handler_b->OnUiAction(PairingEvent::PAIRING_ACCEPTED, + 0x01 /* Non-zero value means success */); + })); + + pairing_handler_b = + std::make_unique(PairingHandlerLe::PHASE1, peripheral_setup); } pairing_handler_a->WaitUntilPairingFinished(); @@ -361,88 +386,97 @@ TEST_F(PairingHandlerPairTest, test_secure_connections_just_works) { EXPECT_TRUE(std::holds_alternative(pairing_result_peripheral.value())); auto central_result = std::get(pairing_result_central.value()); - ASSERT_EQ(central_result.distributed_keys.remote_identity_address->GetAddress(), IDENTITY_ADDRESS_PERIPHERAL); - ASSERT_EQ( - central_result.distributed_keys.remote_identity_address->GetAddressType(), IDENTITY_ADDRESS_TYPE_PERIPHERAL); + ASSERT_EQ(central_result.distributed_keys.remote_identity_address->GetAddress(), + IDENTITY_ADDRESS_PERIPHERAL); + ASSERT_EQ(central_result.distributed_keys.remote_identity_address->GetAddressType(), + IDENTITY_ADDRESS_TYPE_PERIPHERAL); ASSERT_EQ(*central_result.distributed_keys.remote_irk, IRK_PERIPHERAL); auto peripheral_result = std::get(pairing_result_peripheral.value()); - ASSERT_EQ(peripheral_result.distributed_keys.remote_identity_address->GetAddress(), IDENTITY_ADDRESS_CENTRAL); - ASSERT_EQ( - peripheral_result.distributed_keys.remote_identity_address->GetAddressType(), IDENTITY_ADDRESS_TYPE_CENTRAL); + ASSERT_EQ(peripheral_result.distributed_keys.remote_identity_address->GetAddress(), + IDENTITY_ADDRESS_CENTRAL); + ASSERT_EQ(peripheral_result.distributed_keys.remote_identity_address->GetAddressType(), + IDENTITY_ADDRESS_TYPE_CENTRAL); ASSERT_EQ(*peripheral_result.distributed_keys.remote_irk, IRK_CENTRAL); } TEST_F(PairingHandlerPairTest, test_secure_connections_just_works_peripheral_initiated) { central_setup = { - .my_role = hci::Role::CENTRAL, - .my_connection_address = {ADDRESS_CENTRAL, ADDRESS_TYPE_CENTRAL}, - .my_identity_address = {IDENTITY_ADDRESS_CENTRAL, IDENTITY_ADDRESS_TYPE_CENTRAL}, - .my_identity_resolving_key = IRK_CENTRAL, - .myPairingCapabilities = {.io_capability = IoCapability::NO_INPUT_NO_OUTPUT, - .oob_data_flag = OobDataFlag::NOT_PRESENT, - .auth_req = AuthReqMaskBondingFlag | AuthReqMaskMitm | AuthReqMaskSc, - .maximum_encryption_key_size = 16, - .initiator_key_distribution = KeyMaskId | KeyMaskSign, - .responder_key_distribution = KeyMaskId | KeyMaskSign}, - .remotely_initiated = true, - .connection_handle = CONN_HANDLE_CENTRAL, - .remote_connection_address = {ADDRESS_PERIPHERAL, ADDRESS_TYPE_PERIPHERAL}, - .user_interface = ¢ral_user_interface, - .user_interface_handler = handler_, - .le_security_interface = ¢ral_le_security_mock, - .proper_l2cap_interface = up_buffer_a_.get(), - .l2cap_handler = handler_, - .OnPairingFinished = OnPairingFinishedCentral, + .my_role = hci::Role::CENTRAL, + .my_connection_address = {ADDRESS_CENTRAL, ADDRESS_TYPE_CENTRAL}, + .my_identity_address = {IDENTITY_ADDRESS_CENTRAL, IDENTITY_ADDRESS_TYPE_CENTRAL}, + .my_identity_resolving_key = IRK_CENTRAL, + .myPairingCapabilities = {.io_capability = IoCapability::NO_INPUT_NO_OUTPUT, + .oob_data_flag = OobDataFlag::NOT_PRESENT, + .auth_req = AuthReqMaskBondingFlag | AuthReqMaskMitm | + AuthReqMaskSc, + .maximum_encryption_key_size = 16, + .initiator_key_distribution = KeyMaskId | KeyMaskSign, + .responder_key_distribution = KeyMaskId | KeyMaskSign}, + .remotely_initiated = true, + .connection_handle = CONN_HANDLE_CENTRAL, + .remote_connection_address = {ADDRESS_PERIPHERAL, ADDRESS_TYPE_PERIPHERAL}, + .user_interface = ¢ral_user_interface, + .user_interface_handler = handler_, + .le_security_interface = ¢ral_le_security_mock, + .proper_l2cap_interface = up_buffer_a_.get(), + .l2cap_handler = handler_, + .OnPairingFinished = OnPairingFinishedCentral, }; peripheral_setup = { - .my_role = hci::Role::PERIPHERAL, - .my_connection_address = {ADDRESS_PERIPHERAL, ADDRESS_TYPE_PERIPHERAL}, - .my_identity_address = {IDENTITY_ADDRESS_PERIPHERAL, IDENTITY_ADDRESS_TYPE_PERIPHERAL}, - .my_identity_resolving_key = IRK_PERIPHERAL, - .myPairingCapabilities = {.io_capability = IoCapability::NO_INPUT_NO_OUTPUT, - .oob_data_flag = OobDataFlag::NOT_PRESENT, - .auth_req = AuthReqMaskBondingFlag | AuthReqMaskMitm | AuthReqMaskSc, - .maximum_encryption_key_size = 16, - .initiator_key_distribution = KeyMaskId | KeyMaskSign, - .responder_key_distribution = KeyMaskId | KeyMaskSign}, - .remotely_initiated = false, - .connection_handle = CONN_HANDLE_PERIPHERAL, - .remote_connection_address = {ADDRESS_CENTRAL, ADDRESS_TYPE_CENTRAL}, - .user_interface = &peripheral_user_interface, - .user_interface_handler = handler_, - .le_security_interface = &peripheral_le_security_mock, - .proper_l2cap_interface = up_buffer_b_.get(), - .l2cap_handler = handler_, - .OnPairingFinished = OnPairingFinishedPeripheral, + .my_role = hci::Role::PERIPHERAL, + .my_connection_address = {ADDRESS_PERIPHERAL, ADDRESS_TYPE_PERIPHERAL}, + .my_identity_address = {IDENTITY_ADDRESS_PERIPHERAL, IDENTITY_ADDRESS_TYPE_PERIPHERAL}, + .my_identity_resolving_key = IRK_PERIPHERAL, + .myPairingCapabilities = {.io_capability = IoCapability::NO_INPUT_NO_OUTPUT, + .oob_data_flag = OobDataFlag::NOT_PRESENT, + .auth_req = AuthReqMaskBondingFlag | AuthReqMaskMitm | + AuthReqMaskSc, + .maximum_encryption_key_size = 16, + .initiator_key_distribution = KeyMaskId | KeyMaskSign, + .responder_key_distribution = KeyMaskId | KeyMaskSign}, + .remotely_initiated = false, + .connection_handle = CONN_HANDLE_PERIPHERAL, + .remote_connection_address = {ADDRESS_CENTRAL, ADDRESS_TYPE_CENTRAL}, + .user_interface = &peripheral_user_interface, + .user_interface_handler = handler_, + .le_security_interface = &peripheral_le_security_mock, + .proper_l2cap_interface = up_buffer_b_.get(), + .l2cap_handler = handler_, + .OnPairingFinished = OnPairingFinishedPeripheral, }; std::unique_ptr first_pkt; { std::unique_lock lock(handlers_initialization_guard); - pairing_handler_b = std::make_unique(PairingHandlerLe::PHASE1, peripheral_setup); + pairing_handler_b = + std::make_unique(PairingHandlerLe::PHASE1, peripheral_setup); first_pkt = WaitFirstL2capCommand(); EXPECT_CALL(central_user_interface, DisplayPairingPrompt(_, _)) - .Times(1) - .WillOnce(InvokeWithoutArgs([&first_pkt, this] { - log::info("UI mock received pairing prompt"); - - { - // By grabbing the lock, we ensure initialization of both pairing handlers is finished. - std::lock_guard lock(handlers_initialization_guard); - } - if (!pairing_handler_a) log::fatal("handler not initalized yet!"); - // Simulate user accepting the pairing in UI - pairing_handler_a->OnUiAction(PairingEvent::PAIRING_ACCEPTED, 0x01 /* Non-zero value means success */); - - // Send the first packet from the peripheral to central - auto view_to_packet = std::make_unique(); - view_to_packet->AddOctets(std::vector(first_pkt->begin(), first_pkt->end())); - up_buffer_b_->Enqueue(std::move(view_to_packet), handler_); - })); + .Times(1) + .WillOnce(InvokeWithoutArgs([&first_pkt, this] { + log::info("UI mock received pairing prompt"); + + { + // By grabbing the lock, we ensure initialization of both pairing handlers is + // finished. + std::lock_guard lock(handlers_initialization_guard); + } + if (!pairing_handler_a) { + log::fatal("handler not initialized yet!"); + } + // Simulate user accepting the pairing in UI + pairing_handler_a->OnUiAction(PairingEvent::PAIRING_ACCEPTED, + 0x01 /* Non-zero value means success */); + + // Send the first packet from the peripheral to central + auto view_to_packet = std::make_unique(); + view_to_packet->AddOctets(std::vector(first_pkt->begin(), first_pkt->end())); + up_buffer_b_->Enqueue(std::move(view_to_packet), handler_); + })); pairing_handler_a = std::make_unique(PairingHandlerLe::PHASE1, central_setup); } @@ -456,11 +490,13 @@ TEST_F(PairingHandlerPairTest, test_secure_connections_just_works_peripheral_ini TEST_F(PairingHandlerPairTest, test_secure_connections_numeric_comparison) { central_setup.myPairingCapabilities.io_capability = IoCapability::DISPLAY_YES_NO; central_setup.myPairingCapabilities.oob_data_flag = OobDataFlag::NOT_PRESENT; - central_setup.myPairingCapabilities.auth_req = AuthReqMaskBondingFlag | AuthReqMaskMitm | AuthReqMaskSc; + central_setup.myPairingCapabilities.auth_req = + AuthReqMaskBondingFlag | AuthReqMaskMitm | AuthReqMaskSc; peripheral_setup.myPairingCapabilities.io_capability = IoCapability::DISPLAY_YES_NO; peripheral_setup.myPairingCapabilities.oob_data_flag = OobDataFlag::NOT_PRESENT; - peripheral_setup.myPairingCapabilities.auth_req = AuthReqMaskBondingFlag | AuthReqMaskMitm | AuthReqMaskSc; + peripheral_setup.myPairingCapabilities.auth_req = + AuthReqMaskBondingFlag | AuthReqMaskMitm | AuthReqMaskSc; ConfirmationData data_peripheral; { @@ -476,16 +512,19 @@ TEST_F(PairingHandlerPairTest, test_secure_connections_numeric_comparison) { RecordPairingPromptHandling(peripheral_user_interface, &pairing_handler_b); - EXPECT_CALL(peripheral_user_interface, DisplayConfirmValue(_)).WillOnce(SaveArg<0>(&data_peripheral)); - EXPECT_CALL(central_user_interface, DisplayConfirmValue(_)).WillOnce(Invoke([&](ConfirmationData data) { - EXPECT_EQ(data_peripheral.GetNumericValue(), data.GetNumericValue()); - if (data_peripheral.GetNumericValue() == data.GetNumericValue()) { - pairing_handler_a->OnUiAction(PairingEvent::CONFIRM_YESNO, 0x01); - pairing_handler_b->OnUiAction(PairingEvent::CONFIRM_YESNO, 0x01); - } - })); - - pairing_handler_b = std::make_unique(PairingHandlerLe::PHASE1, peripheral_setup); + EXPECT_CALL(peripheral_user_interface, DisplayConfirmValue(_)) + .WillOnce(SaveArg<0>(&data_peripheral)); + EXPECT_CALL(central_user_interface, DisplayConfirmValue(_)) + .WillOnce(Invoke([&](ConfirmationData data) { + EXPECT_EQ(data_peripheral.GetNumericValue(), data.GetNumericValue()); + if (data_peripheral.GetNumericValue() == data.GetNumericValue()) { + pairing_handler_a->OnUiAction(PairingEvent::CONFIRM_YESNO, 0x01); + pairing_handler_b->OnUiAction(PairingEvent::CONFIRM_YESNO, 0x01); + } + })); + + pairing_handler_b = + std::make_unique(PairingHandlerLe::PHASE1, peripheral_setup); } pairing_handler_a->WaitUntilPairingFinished(); pairing_handler_b->WaitUntilPairingFinished(); @@ -497,14 +536,17 @@ TEST_F(PairingHandlerPairTest, test_secure_connections_numeric_comparison) { TEST_F(PairingHandlerPairTest, test_secure_connections_passkey_entry) { central_setup.myPairingCapabilities.io_capability = IoCapability::KEYBOARD_ONLY; central_setup.myPairingCapabilities.oob_data_flag = OobDataFlag::NOT_PRESENT; - central_setup.myPairingCapabilities.auth_req = AuthReqMaskBondingFlag | AuthReqMaskMitm | AuthReqMaskSc; + central_setup.myPairingCapabilities.auth_req = + AuthReqMaskBondingFlag | AuthReqMaskMitm | AuthReqMaskSc; peripheral_setup.myPairingCapabilities.io_capability = IoCapability::DISPLAY_ONLY; peripheral_setup.myPairingCapabilities.oob_data_flag = OobDataFlag::NOT_PRESENT; - peripheral_setup.myPairingCapabilities.auth_req = AuthReqMaskBondingFlag | AuthReqMaskMitm | AuthReqMaskSc; + peripheral_setup.myPairingCapabilities.auth_req = + AuthReqMaskBondingFlag | AuthReqMaskMitm | AuthReqMaskSc; - // In this test either central or peripheral display the UI prompt first. This variable makes sure both prompts are - // displayed before passkey is confirmed. Since both UI handlers are same thread, it's safe. + // In this test either central or peripheral display the UI prompt first. This variable makes sure + // both prompts are displayed before passkey is confirmed. Since both UI handlers are same thread, + // it's safe. int ui_prompts_count = 0; uint32_t passkey_ = std::numeric_limits::max(); { @@ -519,22 +561,25 @@ TEST_F(PairingHandlerPairTest, test_secure_connections_passkey_entry) { RecordPairingPromptHandling(peripheral_user_interface, &pairing_handler_b); - EXPECT_CALL(peripheral_user_interface, DisplayPasskey(_)).WillOnce(Invoke([&](ConfirmationData data) { - passkey_ = data.GetNumericValue(); - ui_prompts_count++; - if (ui_prompts_count == 2) { - pairing_handler_a->OnUiAction(PairingEvent::PASSKEY, passkey_); - } - })); - - EXPECT_CALL(central_user_interface, DisplayEnterPasskeyDialog(_)).WillOnce(Invoke([&](ConfirmationData data) { - ui_prompts_count++; - if (ui_prompts_count == 2) { - pairing_handler_a->OnUiAction(PairingEvent::PASSKEY, passkey_); - } - })); - - pairing_handler_b = std::make_unique(PairingHandlerLe::PHASE1, peripheral_setup); + EXPECT_CALL(peripheral_user_interface, DisplayPasskey(_)) + .WillOnce(Invoke([&](ConfirmationData data) { + passkey_ = data.GetNumericValue(); + ui_prompts_count++; + if (ui_prompts_count == 2) { + pairing_handler_a->OnUiAction(PairingEvent::PASSKEY, passkey_); + } + })); + + EXPECT_CALL(central_user_interface, DisplayEnterPasskeyDialog(_)) + .WillOnce(Invoke([&](ConfirmationData data) { + ui_prompts_count++; + if (ui_prompts_count == 2) { + pairing_handler_a->OnUiAction(PairingEvent::PASSKEY, passkey_); + } + })); + + pairing_handler_b = + std::make_unique(PairingHandlerLe::PHASE1, peripheral_setup); } // Initiator must be initialized after the responder. pairing_handler_a->WaitUntilPairingFinished(); @@ -547,18 +592,20 @@ TEST_F(PairingHandlerPairTest, test_secure_connections_passkey_entry) { TEST_F(PairingHandlerPairTest, test_secure_connections_out_of_band) { central_setup.myPairingCapabilities.io_capability = IoCapability::KEYBOARD_ONLY; central_setup.myPairingCapabilities.oob_data_flag = OobDataFlag::NOT_PRESENT; - central_setup.myPairingCapabilities.auth_req = AuthReqMaskBondingFlag | AuthReqMaskMitm | AuthReqMaskSc, + central_setup.myPairingCapabilities.auth_req = + AuthReqMaskBondingFlag | AuthReqMaskMitm | AuthReqMaskSc, peripheral_setup.myPairingCapabilities.io_capability = IoCapability::DISPLAY_ONLY; peripheral_setup.myPairingCapabilities.oob_data_flag = OobDataFlag::PRESENT; - peripheral_setup.myPairingCapabilities.auth_req = AuthReqMaskBondingFlag | AuthReqMaskMitm | AuthReqMaskSc, + peripheral_setup.myPairingCapabilities.auth_req = + AuthReqMaskBondingFlag | AuthReqMaskMitm | AuthReqMaskSc, central_setup.my_oob_data = std::make_optional(PairingHandlerLe::GenerateOobData()); - peripheral_setup.remote_oob_data = - std::make_optional(InitialInformations::out_of_band_data{ - .le_sc_c = central_setup.my_oob_data->c, - .le_sc_r = central_setup.my_oob_data->r, - }); + peripheral_setup.remote_oob_data = std::make_optional( + InitialInformations::out_of_band_data{ + .le_sc_c = central_setup.my_oob_data->c, + .le_sc_r = central_setup.my_oob_data->r, + }); { std::unique_lock lock(handlers_initialization_guard); @@ -571,7 +618,8 @@ TEST_F(PairingHandlerPairTest, test_secure_connections_out_of_band) { RecordPairingPromptHandling(peripheral_user_interface, &pairing_handler_b); - pairing_handler_b = std::make_unique(PairingHandlerLe::PHASE1, peripheral_setup); + pairing_handler_b = + std::make_unique(PairingHandlerLe::PHASE1, peripheral_setup); } pairing_handler_a->WaitUntilPairingFinished(); pairing_handler_b->WaitUntilPairingFinished(); @@ -583,25 +631,27 @@ TEST_F(PairingHandlerPairTest, test_secure_connections_out_of_band) { TEST_F(PairingHandlerPairTest, test_secure_connections_out_of_band_two_way) { central_setup.myPairingCapabilities.io_capability = IoCapability::KEYBOARD_ONLY; central_setup.myPairingCapabilities.oob_data_flag = OobDataFlag::PRESENT; - central_setup.myPairingCapabilities.auth_req = AuthReqMaskBondingFlag | AuthReqMaskMitm | AuthReqMaskSc, + central_setup.myPairingCapabilities.auth_req = + AuthReqMaskBondingFlag | AuthReqMaskMitm | AuthReqMaskSc, peripheral_setup.myPairingCapabilities.io_capability = IoCapability::DISPLAY_ONLY; peripheral_setup.myPairingCapabilities.oob_data_flag = OobDataFlag::PRESENT; - peripheral_setup.myPairingCapabilities.auth_req = AuthReqMaskBondingFlag | AuthReqMaskMitm | AuthReqMaskSc, + peripheral_setup.myPairingCapabilities.auth_req = + AuthReqMaskBondingFlag | AuthReqMaskMitm | AuthReqMaskSc, central_setup.my_oob_data = std::make_optional(PairingHandlerLe::GenerateOobData()); - peripheral_setup.remote_oob_data = - std::make_optional(InitialInformations::out_of_band_data{ - .le_sc_c = central_setup.my_oob_data->c, - .le_sc_r = central_setup.my_oob_data->r, - }); + peripheral_setup.remote_oob_data = std::make_optional( + InitialInformations::out_of_band_data{ + .le_sc_c = central_setup.my_oob_data->c, + .le_sc_r = central_setup.my_oob_data->r, + }); peripheral_setup.my_oob_data = std::make_optional(PairingHandlerLe::GenerateOobData()); - central_setup.remote_oob_data = - std::make_optional(InitialInformations::out_of_band_data{ - .le_sc_c = peripheral_setup.my_oob_data->c, - .le_sc_r = peripheral_setup.my_oob_data->r, - }); + central_setup.remote_oob_data = std::make_optional( + InitialInformations::out_of_band_data{ + .le_sc_c = peripheral_setup.my_oob_data->c, + .le_sc_r = peripheral_setup.my_oob_data->r, + }); { std::unique_lock lock(handlers_initialization_guard); @@ -614,7 +664,8 @@ TEST_F(PairingHandlerPairTest, test_secure_connections_out_of_band_two_way) { RecordPairingPromptHandling(peripheral_user_interface, &pairing_handler_b); - pairing_handler_b = std::make_unique(PairingHandlerLe::PHASE1, peripheral_setup); + pairing_handler_b = + std::make_unique(PairingHandlerLe::PHASE1, peripheral_setup); } pairing_handler_a->WaitUntilPairingFinished(); pairing_handler_b->WaitUntilPairingFinished(); @@ -643,7 +694,8 @@ TEST_F(PairingHandlerPairTest, test_legacy_just_works) { RecordPairingPromptHandling(peripheral_user_interface, &pairing_handler_b); - pairing_handler_b = std::make_unique(PairingHandlerLe::PHASE1, peripheral_setup); + pairing_handler_b = + std::make_unique(PairingHandlerLe::PHASE1, peripheral_setup); } pairing_handler_a->WaitUntilPairingFinished(); pairing_handler_b->WaitUntilPairingFinished(); @@ -674,15 +726,17 @@ TEST_F(PairingHandlerPairTest, test_legacy_passkey_entry) { EXPECT_CALL(peripheral_user_interface, DisplayEnterPasskeyDialog(_)); EXPECT_CALL(central_user_interface, DisplayConfirmValue(_)) - .WillOnce(Invoke([&](ConfirmationData data) { - log::info("Passkey prompt displayed entering passkey: {:08x}", data.GetNumericValue()); - std::this_thread::sleep_for(1ms); + .WillOnce(Invoke([&](ConfirmationData data) { + log::info("Passkey prompt displayed entering passkey: {:08x}", + data.GetNumericValue()); + std::this_thread::sleep_for(1ms); - // TODO: handle case where prompts are displayed in different order in the test! - pairing_handler_b->OnUiAction(PairingEvent::PASSKEY, data.GetNumericValue()); - })); + // TODO: handle case where prompts are displayed in different order in the test! + pairing_handler_b->OnUiAction(PairingEvent::PASSKEY, data.GetNumericValue()); + })); - pairing_handler_b = std::make_unique(PairingHandlerLe::PHASE1, peripheral_setup); + pairing_handler_b = + std::make_unique(PairingHandlerLe::PHASE1, peripheral_setup); } pairing_handler_a->WaitUntilPairingFinished(); pairing_handler_b->WaitUntilPairingFinished(); diff --git a/system/gd/security/ui.h b/system/gd/security/ui.h index a9519b6ed8b..0b2b286773a 100644 --- a/system/gd/security/ui.h +++ b/system/gd/security/ui.h @@ -27,57 +27,40 @@ namespace bluetooth { namespace security { class ConfirmationData { - public: +public: ConfirmationData() : address_with_type_(hci::AddressWithType()), name_("No name set") {} ConfirmationData(bluetooth::hci::AddressWithType address_with_type, std::string name) : address_with_type_(address_with_type), name_(name) {} - ConfirmationData(bluetooth::hci::AddressWithType address_with_type, std::string name, uint32_t numeric_value) + ConfirmationData(bluetooth::hci::AddressWithType address_with_type, std::string name, + uint32_t numeric_value) : address_with_type_(address_with_type), name_(name), numeric_value_(numeric_value) {} - const bluetooth::hci::AddressWithType& GetAddressWithType() { - return address_with_type_; - } + const bluetooth::hci::AddressWithType& GetAddressWithType() { return address_with_type_; } - std::string GetName() { - return name_; - } + std::string GetName() { return name_; } - uint32_t GetNumericValue() { - return numeric_value_; - } + uint32_t GetNumericValue() { return numeric_value_; } - hci::IoCapability GetRemoteIoCaps() const { - return remote_io_caps_; - } - void SetRemoteIoCaps(hci::IoCapability remote_io_caps) { - remote_io_caps_ = remote_io_caps; - } + hci::IoCapability GetRemoteIoCaps() const { return remote_io_caps_; } + void SetRemoteIoCaps(hci::IoCapability remote_io_caps) { remote_io_caps_ = remote_io_caps; } - hci::AuthenticationRequirements GetRemoteAuthReqs() const { - return remote_auth_reqs_; - } + hci::AuthenticationRequirements GetRemoteAuthReqs() const { return remote_auth_reqs_; } void SetRemoteAuthReqs(hci::AuthenticationRequirements remote_auth_reqs) { remote_auth_reqs_ = remote_auth_reqs; } - hci::OobDataPresent GetRemoteOobDataPresent() const { - return remote_oob_data_present_; - } + hci::OobDataPresent GetRemoteOobDataPresent() const { return remote_oob_data_present_; } void SetRemoteOobDataPresent(hci::OobDataPresent remote_oob_data_present) { remote_oob_data_present_ = remote_oob_data_present; } - bool IsJustWorks() const { - return just_works_; - } + bool IsJustWorks() const { return just_works_; } - void SetJustWorks(bool just_works) { - just_works_ = just_works; - } + void SetJustWorks(bool just_works) { just_works_ = just_works; } - private: +private: bluetooth::hci::AddressWithType address_with_type_; std::string name_; // Can either be the confirmation value or the passkey @@ -86,21 +69,23 @@ class ConfirmationData { // TODO(optedoblivion): Revisit after shim/BTA layer is gone // Extra data is a hack to get data from the module to the shim hci::IoCapability remote_io_caps_ = hci::IoCapability::DISPLAY_YES_NO; - hci::AuthenticationRequirements remote_auth_reqs_ = hci::AuthenticationRequirements::DEDICATED_BONDING; + hci::AuthenticationRequirements remote_auth_reqs_ = + hci::AuthenticationRequirements::DEDICATED_BONDING; hci::OobDataPresent remote_oob_data_present_ = hci::OobDataPresent::NOT_PRESENT; bool just_works_ = false; }; // Through this interface we talk to the user, asking for confirmations/acceptance. class UI { - public: +public: virtual ~UI() = default; /* Remote LE device tries to initiate pairing, ask user to confirm */ - virtual void DisplayPairingPrompt(const bluetooth::hci::AddressWithType& address, std::string name) = 0; + virtual void DisplayPairingPrompt(const bluetooth::hci::AddressWithType& address, + std::string name) = 0; - /* Remove the pairing prompt from DisplayPairingPrompt, i.e. remote device disconnected, or some application requested - * bond with this device */ + /* Remove the pairing prompt from DisplayPairingPrompt, i.e. remote device disconnected, or some + * application requested bond with this device */ virtual void Cancel(const bluetooth::hci::AddressWithType& address) = 0; /* Display value for Comparison, user responds yes/no */ @@ -121,20 +106,23 @@ class UI { /* Through this interface, UI provides us with user choices. */ class UICallbacks { - public: +public: virtual ~UICallbacks() = default; /* User accepted pairing prompt */ - virtual void OnPairingPromptAccepted(const bluetooth::hci::AddressWithType& address, bool confirmed) = 0; + virtual void OnPairingPromptAccepted(const bluetooth::hci::AddressWithType& address, + bool confirmed) = 0; /* User confirmed that displayed value matches the value on the other device */ virtual void OnConfirmYesNo(const bluetooth::hci::AddressWithType& address, bool confirmed) = 0; - /* User typed the value displayed on the other device. This is either Passkey or the Confirm value */ + /* User typed the value displayed on the other device. This is either Passkey or the Confirm value + */ virtual void OnPasskeyEntry(const bluetooth::hci::AddressWithType& address, uint32_t passkey) = 0; /* User typed the PIN for the other device. */ - virtual void OnPinEntry(const bluetooth::hci::AddressWithType& address, std::vector pin) = 0; + virtual void OnPinEntry(const bluetooth::hci::AddressWithType& address, + std::vector pin) = 0; }; } // namespace security diff --git a/system/gd/shim/dumpsys.cc b/system/gd/shim/dumpsys.cc index 3f6c87c9bed..25a47b2bf8f 100644 --- a/system/gd/shim/dumpsys.cc +++ b/system/gd/shim/dumpsys.cc @@ -46,20 +46,20 @@ constexpr char kDumpsysTitle[] = "----- Gd Dumpsys ------"; } // namespace struct Dumpsys::impl { - public: +public: void DumpWithArgsSync(int fd, const char** args, std::promise promise); int GetNumberOfBundledSchemas() const; impl(const Dumpsys& dumpsys_module, const dumpsys::ReflectionSchema& reflection_schema); ~impl() = default; - protected: +protected: void FilterSchema(std::string* dumpsys_data) const; std::string PrintAsJson(std::string* dumpsys_data) const; bool IsDebuggable() const; - private: +private: void DumpWithArgsAsync(int fd, const char** args) const; const Dumpsys& dumpsys_module_; @@ -67,9 +67,10 @@ struct Dumpsys::impl { }; const ModuleFactory Dumpsys::Factory = - ModuleFactory([]() { return new Dumpsys(bluetooth::dumpsys::GetBundledSchemaData()); }); + ModuleFactory([]() { return new Dumpsys(bluetooth::dumpsys::GetBundledSchemaData()); }); -Dumpsys::impl::impl(const Dumpsys& dumpsys_module, const dumpsys::ReflectionSchema& reflection_schema) +Dumpsys::impl::impl(const Dumpsys& dumpsys_module, + const dumpsys::ReflectionSchema& reflection_schema) : dumpsys_module_(dumpsys_module), reflection_schema_(std::move(reflection_schema)) {} int Dumpsys::impl::GetNumberOfBundledSchemas() const { @@ -77,7 +78,7 @@ int Dumpsys::impl::GetNumberOfBundledSchemas() const { } bool Dumpsys::impl::IsDebuggable() const { - return (os::GetSystemProperty(kReadOnlyDebuggableProperty) == "1"); + return os::GetSystemProperty(kReadOnlyDebuggableProperty) == "1"; } void Dumpsys::impl::FilterSchema(std::string* dumpsys_data) const { @@ -109,7 +110,8 @@ std::string Dumpsys::impl::PrintAsJson(std::string* dumpsys_data) const { flatbuffers::Parser parser{options}; if (!parser.Deserialize(schema)) { char buf[255]; - snprintf(buf, sizeof(buf), "ERROR: Unable to deserialize bundle root name:%s\n", root_name.c_str()); + snprintf(buf, sizeof(buf), "ERROR: Unable to deserialize bundle root name:%s\n", + root_name.c_str()); log::warn("{}", buf); return std::string(buf); } @@ -117,10 +119,10 @@ std::string Dumpsys::impl::PrintAsJson(std::string* dumpsys_data) const { std::string jsongen; // GenerateText was renamed to GenText in 23.5.26 because the return behavior was changed. // https://github.com/google/flatbuffers/commit/950a71ab893e96147c30dd91735af6db73f72ae0 -#if FLATBUFFERS_VERSION_MAJOR < 23 || \ - (FLATBUFFERS_VERSION_MAJOR == 23 && \ - (FLATBUFFERS_VERSION_MINOR < 5 || \ - (FLATBUFFERS_VERSION_MINOR == 5 && FLATBUFFERS_VERSION_REVISION < 26))) +#if FLATBUFFERS_VERSION_MAJOR < 23 || \ + (FLATBUFFERS_VERSION_MAJOR == 23 && \ + (FLATBUFFERS_VERSION_MINOR < 5 || \ + (FLATBUFFERS_VERSION_MINOR == 5 && FLATBUFFERS_VERSION_REVISION < 26))) flatbuffers::GenerateText(parser, dumpsys_data->data(), &jsongen); #else const char* error = flatbuffers::GenText(parser, dumpsys_data->data(), &jsongen); @@ -185,22 +187,16 @@ void Dumpsys::Dump(int fd, const char** args, std::promise promise) { CallOn(pimpl_.get(), &Dumpsys::impl::DumpWithArgsSync, fd, args, std::move(promise)); } -os::Handler* Dumpsys::GetGdShimHandler() { - return GetHandler(); -} +os::Handler* Dumpsys::GetGdShimHandler() { return GetHandler(); } /** * Module methods */ void Dumpsys::ListDependencies(ModuleList* /* list */) const {} -void Dumpsys::Start() { - pimpl_ = std::make_unique(*this, reflection_schema_); -} +void Dumpsys::Start() { pimpl_ = std::make_unique(*this, reflection_schema_); } -void Dumpsys::Stop() { - pimpl_.reset(); -} +void Dumpsys::Stop() { pimpl_.reset(); } DumpsysDataFinisher Dumpsys::GetDumpsysData(flatbuffers::FlatBufferBuilder* fb_builder) const { auto name = fb_builder->CreateString("----- Shim Dumpsys -----"); @@ -210,12 +206,12 @@ DumpsysDataFinisher Dumpsys::GetDumpsysData(flatbuffers::FlatBufferBuilder* fb_b builder.add_number_of_bundled_schemas(pimpl_->GetNumberOfBundledSchemas()); auto dumpsys_data = builder.Finish(); - return [dumpsys_data](DumpsysDataBuilder* builder) { builder->add_shim_dumpsys_data(dumpsys_data); }; + return [dumpsys_data](DumpsysDataBuilder* builder) { + builder->add_shim_dumpsys_data(dumpsys_data); + }; } -std::string Dumpsys::ToString() const { - return kModuleName; -} +std::string Dumpsys::ToString() const { return kModuleName; } } // namespace shim } // namespace bluetooth diff --git a/system/gd/shim/dumpsys.h b/system/gd/shim/dumpsys.h index 04be0627937..5b463fd193a 100644 --- a/system/gd/shim/dumpsys.h +++ b/system/gd/shim/dumpsys.h @@ -28,7 +28,7 @@ namespace shim { constexpr char kArgumentDeveloper[] = "--dev"; class Dumpsys : public bluetooth::Module { - public: +public: void Dump(int fd, const char** args); void Dump(int fd, const char** args, std::promise promise); @@ -44,14 +44,15 @@ class Dumpsys : public bluetooth::Module { static const ModuleFactory Factory; - protected: +protected: void ListDependencies(ModuleList* list) const override; // Module - void Start() override; // Module - void Stop() override; // Module - std::string ToString() const override; // Module - DumpsysDataFinisher GetDumpsysData(flatbuffers::FlatBufferBuilder* builder) const override; // Module + void Start() override; // Module + void Stop() override; // Module + std::string ToString() const override; // Module + DumpsysDataFinisher GetDumpsysData( + flatbuffers::FlatBufferBuilder* builder) const override; // Module - private: +private: struct impl; std::unique_ptr pimpl_; const dumpsys::ReflectionSchema reflection_schema_; diff --git a/system/gd/shim/dumpsys_args.cc b/system/gd/shim/dumpsys_args.cc index c196ed129b6..3813a53c13e 100644 --- a/system/gd/shim/dumpsys_args.cc +++ b/system/gd/shim/dumpsys_args.cc @@ -15,14 +15,17 @@ */ #include "shim/dumpsys_args.h" -#include "shim/dumpsys.h" #include +#include "shim/dumpsys.h" + using namespace bluetooth; shim::ParsedDumpsysArgs::ParsedDumpsysArgs(const char** args) { - if (args == nullptr) return; + if (args == nullptr) { + return; + } const char* p = *args; while (p != nullptr) { num_args_++; @@ -31,11 +34,11 @@ shim::ParsedDumpsysArgs::ParsedDumpsysArgs(const char** args) { } else { // silently ignore unexpected option } - if (++args == nullptr) break; + if (++args == nullptr) { + break; + } p = *args; } } -bool shim::ParsedDumpsysArgs::IsDeveloper() const { - return dev_arg_; -} +bool shim::ParsedDumpsysArgs::IsDeveloper() const { return dev_arg_; } diff --git a/system/gd/shim/dumpsys_args.h b/system/gd/shim/dumpsys_args.h index 0979799a1d1..38e8bc58551 100644 --- a/system/gd/shim/dumpsys_args.h +++ b/system/gd/shim/dumpsys_args.h @@ -20,11 +20,11 @@ namespace bluetooth { namespace shim { class ParsedDumpsysArgs { - public: +public: ParsedDumpsysArgs(const char** args); bool IsDeveloper() const; - private: +private: unsigned num_args_{0}; bool dev_arg_{false}; }; diff --git a/system/gd/shim/dumpsys_args_test.cc b/system/gd/shim/dumpsys_args_test.cc index db98bacce32..68af56846ee 100644 --- a/system/gd/shim/dumpsys_args_test.cc +++ b/system/gd/shim/dumpsys_args_test.cc @@ -15,10 +15,11 @@ */ #include "shim/dumpsys_args.h" -#include "shim/dumpsys.h" #include +#include "shim/dumpsys.h" + using namespace bluetooth; namespace testing { @@ -30,7 +31,7 @@ TEST(DumpsysArgsTest, no_args) { TEST(DumpsysArgsTest, parsed_args_without_dev) { const char* args[]{ - nullptr, + nullptr, }; shim::ParsedDumpsysArgs parsed_dumpsys_args(args); ASSERT_FALSE(parsed_dumpsys_args.IsDeveloper()); @@ -38,8 +39,8 @@ TEST(DumpsysArgsTest, parsed_args_without_dev) { TEST(DumpsysArgsTest, parsed_args_with_dev) { const char* args[]{ - bluetooth::shim::kArgumentDeveloper, - nullptr, + bluetooth::shim::kArgumentDeveloper, + nullptr, }; shim::ParsedDumpsysArgs parsed_dumpsys_args(args); ASSERT_TRUE(parsed_dumpsys_args.IsDeveloper()); diff --git a/system/gd/shim/dumpsys_test.cc b/system/gd/shim/dumpsys_test.cc index 0df58ce0a45..bc368f7b77c 100644 --- a/system/gd/shim/dumpsys_test.cc +++ b/system/gd/shim/dumpsys_test.cc @@ -14,6 +14,8 @@ * limitations under the License. */ +#include "shim/dumpsys.h" + #include #include #include @@ -22,7 +24,6 @@ #include "module.h" #include "os/thread.h" -#include "shim/dumpsys.h" #include "shim/dumpsys_args.h" #include "test_data/dumpsys_test_data_bin.h" @@ -64,23 +65,19 @@ bool SimpleJsonValidator(int fd, int* dumpsys_byte_cnt) { // To create dumpsys_test_header_bin.h: // make bluetooth_flatbuffer_bundler -// ${ANDROID_BUILD_TOP}/out/host/linux-x86/bin/bluetooth_flatbuffer_bundler -w -m bluetooth.DumpsysData -f -// test_gen/dumpsys_test_data_bin -n bluetooth::test test_gen/* +// ${ANDROID_BUILD_TOP}/out/host/linux-x86/bin/bluetooth_flatbuffer_bundler -w -m +// bluetooth.DumpsysData -f test_gen/dumpsys_test_data_bin -n bluetooth::test test_gen/* class DumpsysTest : public Test { - protected: +protected: void SetUp() override { dumpsys_module_ = new bluetooth::shim::Dumpsys(bluetooth::test::GetBundledSchemaData()); fake_registry_.InjectTestModule(&shim::Dumpsys::Factory, dumpsys_module_); } - void TearDown() override { - fake_registry_.StopAll(); - } + void TearDown() override { fake_registry_.StopAll(); } - void Print() { - dumpsys_module_->Dump(0, nullptr); - } + void Print() { dumpsys_module_->Dump(0, nullptr); } int GetSocketBufferSize(int sockfd) { int socket_buffer_size; @@ -91,7 +88,8 @@ class DumpsysTest : public Test { void SetSocketBufferSize(int sockfd, int socket_buffer_size) { socklen_t optlen = sizeof(socket_buffer_size); - ASSERT_EQ(0, setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, (const void*)&socket_buffer_size, optlen)); + ASSERT_EQ(0, + setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, (const void*)&socket_buffer_size, optlen)); } TestModuleRegistry fake_registry_; diff --git a/system/gd/shim/test_data/dumpsys_test_data_bin.h b/system/gd/shim/test_data/dumpsys_test_data_bin.h index 7759049f1a3..d1f118d0fa5 100644 --- a/system/gd/shim/test_data/dumpsys_test_data_bin.h +++ b/system/gd/shim/test_data/dumpsys_test_data_bin.h @@ -1,6 +1,7 @@ // Generated file by bluetooth_flatbuffer bundler #pragma once #include + #include namespace bluetooth { namespace test { @@ -10,56 +11,66 @@ const std::string& GetBundledSchemaData(); } // namespace test } // namespace bluetooth const unsigned char data_[] = { - 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x10, 0x00, 0x04, 0x00, 0x08, 0x00, 0x0c, 0x00, 0x0a, 0x00, 0x00, - 0x00, 0x30, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x44, 0x00, - 0x00, 0x00, 0x15, 0x00, 0x00, 0x00, 0x62, 0x6c, 0x75, 0x65, 0x74, 0x6f, 0x6f, 0x74, 0x68, 0x2e, 0x44, 0x75, 0x6d, - 0x70, 0x73, 0x79, 0x73, 0x44, 0x61, 0x74, 0x61, 0x00, 0x00, 0x00, 0x15, 0x00, 0x00, 0x00, 0x42, 0x75, 0x6e, 0x64, - 0x6c, 0x65, 0x64, 0x20, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x20, 0x74, 0x61, 0x62, 0x6c, 0x65, 0x73, 0x00, 0x00, - 0x00, 0x08, 0x00, 0x0c, 0x00, 0x04, 0x00, 0x08, 0x00, 0x08, 0x00, 0x00, 0x00, 0xec, 0x02, 0x00, 0x00, 0x04, 0x00, - 0x00, 0x00, 0xe0, 0x02, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x42, 0x46, 0x42, 0x53, 0x10, 0x00, 0x1c, 0x00, 0x04, - 0x00, 0x08, 0x00, 0x0c, 0x00, 0x10, 0x00, 0x14, 0x00, 0x18, 0x00, 0x10, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, - 0x28, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0xd8, 0x01, 0x00, 0x00, 0x38, - 0x01, 0x00, 0x00, 0x3c, 0xfe, 0xff, 0xff, 0x1c, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, - 0x03, 0x00, 0x00, 0x00, 0x34, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0xf4, 0x00, 0x00, 0x00, 0x15, 0x00, 0x00, - 0x00, 0x62, 0x6c, 0x75, 0x65, 0x74, 0x6f, 0x6f, 0x74, 0x68, 0x2e, 0x44, 0x75, 0x6d, 0x70, 0x73, 0x79, 0x73, 0x44, - 0x61, 0x74, 0x61, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x10, 0x00, 0x08, 0x00, 0x0c, 0x00, 0x04, 0x00, 0x06, 0x00, 0x0c, - 0x00, 0x00, 0x00, 0x02, 0x00, 0x08, 0x00, 0x14, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x82, 0xff, 0xff, 0xff, - 0x00, 0x00, 0x00, 0x0f, 0x01, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x6d, 0x6f, 0x64, 0x75, 0x6c, 0x65, 0x5f, - 0x75, 0x6e, 0x69, 0x74, 0x74, 0x65, 0x73, 0x74, 0x5f, 0x64, 0x61, 0x74, 0x61, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, - 0x14, 0x00, 0x08, 0x00, 0x0c, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x10, 0x00, 0x18, 0x00, 0x00, 0x00, 0x01, 0x00, 0x06, 0x00, 0x4c, 0x00, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x00, - 0x04, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x74, 0xfe, 0xff, 0xff, 0x10, 0x00, 0x00, - 0x00, 0x04, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x41, 0x6e, 0x79, 0x00, 0x07, 0x00, 0x00, 0x00, 0x70, 0x72, - 0x69, 0x76, 0x61, 0x63, 0x79, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x0c, 0x00, 0x07, 0x00, 0x00, 0x00, 0x08, 0x00, 0x0a, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0x02, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, 0x73, 0x68, 0x69, 0x6d, - 0x5f, 0x64, 0x75, 0x6d, 0x70, 0x73, 0x79, 0x73, 0x5f, 0x64, 0x61, 0x74, 0x61, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x10, - 0x00, 0x08, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x06, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x10, 0x00, - 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0xb6, 0xfe, 0xff, 0xff, 0x00, 0x00, 0x00, 0x0d, 0x05, 0x00, 0x00, 0x00, 0x74, - 0x69, 0x74, 0x6c, 0x65, 0x00, 0x00, 0x00, 0x70, 0xff, 0xff, 0xff, 0x14, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, - 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x62, 0x6c, 0x75, - 0x65, 0x74, 0x6f, 0x6f, 0x74, 0x68, 0x2e, 0x73, 0x68, 0x69, 0x6d, 0x2e, 0x44, 0x75, 0x6d, 0x70, 0x73, 0x79, 0x73, - 0x4d, 0x6f, 0x64, 0x75, 0x6c, 0x65, 0x44, 0x61, 0x74, 0x61, 0x00, 0x00, 0x00, 0x00, 0x68, 0xff, 0xff, 0xff, 0x00, - 0x00, 0x04, 0x00, 0x3c, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, - 0x04, 0x00, 0x00, 0x00, 0x50, 0xff, 0xff, 0xff, 0x10, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, - 0x00, 0x41, 0x6e, 0x79, 0x00, 0x07, 0x00, 0x00, 0x00, 0x70, 0x72, 0x69, 0x76, 0x61, 0x63, 0x79, 0x00, 0x46, 0xff, - 0xff, 0xff, 0x00, 0x00, 0x00, 0x0d, 0x05, 0x00, 0x00, 0x00, 0x74, 0x69, 0x74, 0x6c, 0x65, 0x00, 0x00, 0x00, 0x0c, - 0x00, 0x10, 0x00, 0x04, 0x00, 0x08, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, - 0x08, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, - 0x00, 0x62, 0x6c, 0x75, 0x65, 0x74, 0x6f, 0x6f, 0x74, 0x68, 0x2e, 0x4d, 0x6f, 0x64, 0x75, 0x6c, 0x65, 0x55, 0x6e, - 0x69, 0x74, 0x54, 0x65, 0x73, 0x74, 0x44, 0x61, 0x74, 0x61, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x14, 0x00, 0x08, - 0x00, 0x0c, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, - 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x4c, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, - 0x00, 0x01, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x08, 0x00, 0x0c, 0x00, 0x04, 0x00, 0x08, 0x00, 0x08, 0x00, - 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x41, 0x6e, 0x79, 0x00, 0x07, - 0x00, 0x00, 0x00, 0x70, 0x72, 0x69, 0x76, 0x61, 0x63, 0x79, 0x00, 0x00, 0x00, 0x06, 0x00, 0x08, 0x00, 0x07, 0x00, - 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0d, 0x05, 0x00, 0x00, 0x00, 0x74, 0x69, 0x74, 0x6c, 0x65, 0x00, 0x00, - 0x00, 0x15, 0x00, 0x00, 0x00, 0x62, 0x6c, 0x75, 0x65, 0x74, 0x6f, 0x6f, 0x74, 0x68, 0x2e, 0x44, 0x75, 0x6d, 0x70, - 0x73, 0x79, 0x73, 0x44, 0x61, 0x74, 0x61, 0x00, 0x00, 0x00}; + 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x10, 0x00, 0x04, 0x00, 0x08, 0x00, 0x0c, + 0x00, 0x0a, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x04, 0x00, + 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x44, 0x00, 0x00, 0x00, 0x15, 0x00, 0x00, 0x00, 0x62, + 0x6c, 0x75, 0x65, 0x74, 0x6f, 0x6f, 0x74, 0x68, 0x2e, 0x44, 0x75, 0x6d, 0x70, 0x73, 0x79, + 0x73, 0x44, 0x61, 0x74, 0x61, 0x00, 0x00, 0x00, 0x15, 0x00, 0x00, 0x00, 0x42, 0x75, 0x6e, + 0x64, 0x6c, 0x65, 0x64, 0x20, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x20, 0x74, 0x61, 0x62, + 0x6c, 0x65, 0x73, 0x00, 0x00, 0x00, 0x08, 0x00, 0x0c, 0x00, 0x04, 0x00, 0x08, 0x00, 0x08, + 0x00, 0x00, 0x00, 0xec, 0x02, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0xe0, 0x02, 0x00, 0x00, + 0x18, 0x00, 0x00, 0x00, 0x42, 0x46, 0x42, 0x53, 0x10, 0x00, 0x1c, 0x00, 0x04, 0x00, 0x08, + 0x00, 0x0c, 0x00, 0x10, 0x00, 0x14, 0x00, 0x18, 0x00, 0x10, 0x00, 0x00, 0x00, 0x30, 0x00, + 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x30, + 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x03, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0xd8, 0x01, 0x00, 0x00, 0x38, 0x01, + 0x00, 0x00, 0x3c, 0xfe, 0xff, 0xff, 0x1c, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01, + 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x34, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, + 0xf4, 0x00, 0x00, 0x00, 0x15, 0x00, 0x00, 0x00, 0x62, 0x6c, 0x75, 0x65, 0x74, 0x6f, 0x6f, + 0x74, 0x68, 0x2e, 0x44, 0x75, 0x6d, 0x70, 0x73, 0x79, 0x73, 0x44, 0x61, 0x74, 0x61, 0x00, + 0x00, 0x00, 0x0c, 0x00, 0x10, 0x00, 0x08, 0x00, 0x0c, 0x00, 0x04, 0x00, 0x06, 0x00, 0x0c, + 0x00, 0x00, 0x00, 0x02, 0x00, 0x08, 0x00, 0x14, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, + 0x82, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x0f, 0x01, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, + 0x00, 0x6d, 0x6f, 0x64, 0x75, 0x6c, 0x65, 0x5f, 0x75, 0x6e, 0x69, 0x74, 0x74, 0x65, 0x73, + 0x74, 0x5f, 0x64, 0x61, 0x74, 0x61, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x14, 0x00, 0x08, + 0x00, 0x0c, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x10, 0x00, 0x18, 0x00, 0x00, 0x00, 0x01, 0x00, 0x06, 0x00, 0x4c, 0x00, 0x00, + 0x00, 0x3c, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04, 0x00, + 0x00, 0x00, 0x74, 0xfe, 0xff, 0xff, 0x10, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x03, + 0x00, 0x00, 0x00, 0x41, 0x6e, 0x79, 0x00, 0x07, 0x00, 0x00, 0x00, 0x70, 0x72, 0x69, 0x76, + 0x61, 0x63, 0x79, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x0c, 0x00, 0x07, 0x00, 0x00, 0x00, 0x08, + 0x00, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0x02, 0x00, 0x00, 0x00, 0x11, 0x00, + 0x00, 0x00, 0x73, 0x68, 0x69, 0x6d, 0x5f, 0x64, 0x75, 0x6d, 0x70, 0x73, 0x79, 0x73, 0x5f, + 0x64, 0x61, 0x74, 0x61, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x10, 0x00, 0x08, 0x00, 0x0c, 0x00, + 0x00, 0x00, 0x06, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x10, 0x00, 0x00, + 0x00, 0x04, 0x00, 0x00, 0x00, 0xb6, 0xfe, 0xff, 0xff, 0x00, 0x00, 0x00, 0x0d, 0x05, 0x00, + 0x00, 0x00, 0x74, 0x69, 0x74, 0x6c, 0x65, 0x00, 0x00, 0x00, 0x70, 0xff, 0xff, 0xff, 0x14, + 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, + 0x2c, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x62, 0x6c, 0x75, 0x65, 0x74, 0x6f, 0x6f, + 0x74, 0x68, 0x2e, 0x73, 0x68, 0x69, 0x6d, 0x2e, 0x44, 0x75, 0x6d, 0x70, 0x73, 0x79, 0x73, + 0x4d, 0x6f, 0x64, 0x75, 0x6c, 0x65, 0x44, 0x61, 0x74, 0x61, 0x00, 0x00, 0x00, 0x00, 0x68, + 0xff, 0xff, 0xff, 0x00, 0x00, 0x04, 0x00, 0x3c, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, + 0x04, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x50, 0xff, 0xff, + 0xff, 0x10, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x41, 0x6e, + 0x79, 0x00, 0x07, 0x00, 0x00, 0x00, 0x70, 0x72, 0x69, 0x76, 0x61, 0x63, 0x79, 0x00, 0x46, + 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x0d, 0x05, 0x00, 0x00, 0x00, 0x74, 0x69, 0x74, 0x6c, + 0x65, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x10, 0x00, 0x04, 0x00, 0x08, 0x00, 0x00, 0x00, 0x0c, + 0x00, 0x0c, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01, 0x00, + 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x62, + 0x6c, 0x75, 0x65, 0x74, 0x6f, 0x6f, 0x74, 0x68, 0x2e, 0x4d, 0x6f, 0x64, 0x75, 0x6c, 0x65, + 0x55, 0x6e, 0x69, 0x74, 0x54, 0x65, 0x73, 0x74, 0x44, 0x61, 0x74, 0x61, 0x00, 0x00, 0x00, + 0x00, 0x18, 0x00, 0x14, 0x00, 0x08, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x04, 0x00, 0x4c, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, + 0x01, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x08, 0x00, 0x0c, 0x00, 0x04, 0x00, 0x08, + 0x00, 0x08, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x03, 0x00, + 0x00, 0x00, 0x41, 0x6e, 0x79, 0x00, 0x07, 0x00, 0x00, 0x00, 0x70, 0x72, 0x69, 0x76, 0x61, + 0x63, 0x79, 0x00, 0x00, 0x00, 0x06, 0x00, 0x08, 0x00, 0x07, 0x00, 0x06, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x0d, 0x05, 0x00, 0x00, 0x00, 0x74, 0x69, 0x74, 0x6c, 0x65, 0x00, 0x00, + 0x00, 0x15, 0x00, 0x00, 0x00, 0x62, 0x6c, 0x75, 0x65, 0x74, 0x6f, 0x6f, 0x74, 0x68, 0x2e, + 0x44, 0x75, 0x6d, 0x70, 0x73, 0x79, 0x73, 0x44, 0x61, 0x74, 0x61, 0x00, 0x00, 0x00}; const std::string string_data_(data_, data_ + sizeof(data_)); const unsigned char* bluetooth::test::data = data_; const size_t bluetooth::test::data_size = 884; -const std::string& bluetooth::test::GetBundledSchemaData() { - return string_data_; -} +const std::string& bluetooth::test::GetBundledSchemaData() { return string_data_; } diff --git a/system/gd/stack_manager.cc b/system/gd/stack_manager.cc index 764d07b8434..d62507400cc 100644 --- a/system/gd/stack_manager.cc +++ b/system/gd/stack_manager.cc @@ -44,25 +44,24 @@ void StackManager::StartUp(ModuleList* modules, Thread* stack_thread) { std::promise promise; auto future = promise.get_future(); - handler_->Post(common::BindOnce(&StackManager::handle_start_up, common::Unretained(this), modules, stack_thread, - std::move(promise))); + handler_->Post(common::BindOnce(&StackManager::handle_start_up, common::Unretained(this), modules, + stack_thread, std::move(promise))); - auto init_status = future.wait_for(std::chrono::milliseconds( - get_gd_stack_timeout_ms(/* is_start = */ true))); + auto init_status = future.wait_for( + std::chrono::milliseconds(get_gd_stack_timeout_ms(/* is_start = */ true))); WakelockManager::Get().Release(); log::info("init_status == {}", int(init_status)); - log::assert_that( - init_status == std::future_status::ready, - "Can't start stack, last instance: {}", - registry_.last_instance_); + log::assert_that(init_status == std::future_status::ready, "Can't start stack, last instance: {}", + registry_.last_instance_); log::info("init complete"); } -void StackManager::handle_start_up(ModuleList* modules, Thread* stack_thread, std::promise promise) { +void StackManager::handle_start_up(ModuleList* modules, Thread* stack_thread, + std::promise promise) { registry_.Start(modules, stack_thread); promise.set_value(); } @@ -72,18 +71,17 @@ void StackManager::ShutDown() { std::promise promise; auto future = promise.get_future(); - handler_->Post(common::BindOnce(&StackManager::handle_shut_down, common::Unretained(this), std::move(promise))); + handler_->Post(common::BindOnce(&StackManager::handle_shut_down, common::Unretained(this), + std::move(promise))); - auto stop_status = future.wait_for(std::chrono::milliseconds( - get_gd_stack_timeout_ms(/* is_start = */ false))); + auto stop_status = future.wait_for( + std::chrono::milliseconds(get_gd_stack_timeout_ms(/* is_start = */ false))); WakelockManager::Get().Release(); WakelockManager::Get().CleanUp(); - log::assert_that( - stop_status == std::future_status::ready, - "Can't stop stack, last instance: {}", - registry_.last_instance_); + log::assert_that(stop_status == std::future_status::ready, "Can't stop stack, last instance: {}", + registry_.last_instance_); handler_->Clear(); handler_->WaitUntilStopped(std::chrono::milliseconds(2000)); @@ -98,11 +96,11 @@ void StackManager::handle_shut_down(std::promise promise) { std::chrono::milliseconds StackManager::get_gd_stack_timeout_ms(bool is_start) { auto gd_timeout = os::GetSystemPropertyUint32( - is_start ? "bluetooth.gd.start_timeout" : "bluetooth.gd.stop_timeout", - /* default_value = */ is_start ? 3000 : 5000); - return std::chrono::milliseconds( - gd_timeout * os::GetSystemPropertyUint32("ro.hw_timeout_multiplier", - /* default_value = */ 1)); + is_start ? "bluetooth.gd.start_timeout" : "bluetooth.gd.stop_timeout", + /* default_value = */ is_start ? 3000 : 5000); + return std::chrono::milliseconds(gd_timeout * + os::GetSystemPropertyUint32("ro.hw_timeout_multiplier", + /* default_value = */ 1)); } } // namespace bluetooth diff --git a/system/gd/stack_manager.h b/system/gd/stack_manager.h index 85b0721ea70..892efc3c3bb 100644 --- a/system/gd/stack_manager.h +++ b/system/gd/stack_manager.h @@ -17,14 +17,14 @@ #pragma once #include "module.h" -#include "os/thread.h" #include "os/handler.h" +#include "os/thread.h" namespace bluetooth { class StackManager { - public: - void StartUp(ModuleList *modules, os::Thread* stack_thread); +public: + void StartUp(ModuleList* modules, os::Thread* stack_thread); void ShutDown(); template @@ -37,7 +37,7 @@ class StackManager { return registry_.IsStarted(&T::Factory); } - private: +private: os::Thread* management_thread_ = nullptr; os::Handler* handler_ = nullptr; ModuleRegistry registry_; diff --git a/system/gd/stack_manager_unittest.cc b/system/gd/stack_manager_unittest.cc index 282313d39b9..f3fb3b5c821 100644 --- a/system/gd/stack_manager_unittest.cc +++ b/system/gd/stack_manager_unittest.cc @@ -31,19 +31,18 @@ TEST(StackManagerTest, DISABLED_start_and_shutdown_no_module) { } class TestModuleNoDependency : public Module { - public: +public: static const ModuleFactory Factory; - protected: +protected: void ListDependencies(ModuleList* /* list */) const {} void Start() override {} void Stop() override {} - std::string ToString() const override { - return std::string("TestModuleDep"); - } + std::string ToString() const override { return std::string("TestModuleDep"); } }; -const ModuleFactory TestModuleNoDependency::Factory = ModuleFactory([]() { return new TestModuleNoDependency(); }); +const ModuleFactory TestModuleNoDependency::Factory = + ModuleFactory([]() { return new TestModuleNoDependency(); }); TEST(StackManagerTest, DISABLED_get_module_instance) { StackManager stack_manager; diff --git a/system/gd/storage/classic_device.cc b/system/gd/storage/classic_device.cc index e46ef20a1f8..0a204e5d5c8 100644 --- a/system/gd/storage/classic_device.cc +++ b/system/gd/storage/classic_device.cc @@ -25,16 +25,13 @@ namespace storage { const std::unordered_set ClassicDevice::kLinkKeyProperties = {"LinkKey"}; -ClassicDevice::ClassicDevice(ConfigCache* config, ConfigCache* memory_only_config, std::string section) +ClassicDevice::ClassicDevice(ConfigCache* config, ConfigCache* memory_only_config, + std::string section) : config_(config), memory_only_config_(memory_only_config), section_(std::move(section)) {} -Device ClassicDevice::Parent() { - return Device(config_, memory_only_config_, section_); -} +Device ClassicDevice::Parent() { return Device(config_, memory_only_config_, section_); } -std::string ClassicDevice::ToLogString() const { - return section_; -} +std::string ClassicDevice::ToLogString() const { return section_; } hci::Address ClassicDevice::GetAddress() const { // section name of a classic device is its MAC address diff --git a/system/gd/storage/classic_device.h b/system/gd/storage/classic_device.h index d18d25c6d70..155b44d8d87 100644 --- a/system/gd/storage/classic_device.h +++ b/system/gd/storage/classic_device.h @@ -29,7 +29,7 @@ namespace bluetooth { namespace storage { class ClassicDevice { - public: +public: ClassicDevice(ConfigCache* config, ConfigCache* memory_only_config, std::string section); // for move @@ -42,11 +42,10 @@ class ClassicDevice { // operators bool operator==(const ClassicDevice& other) const { - return config_ == other.config_ && memory_only_config_ == other.memory_only_config_ && section_ == other.section_; - } - bool operator!=(const ClassicDevice& other) const { - return !(*this == other); + return config_ == other.config_ && memory_only_config_ == other.memory_only_config_ && + section_ == other.section_; } + bool operator!=(const ClassicDevice& other) const { return !(*this == other); } bool operator<(const ClassicDevice& other) const { if (config_ != other.config_) { return config_ < other.config_; @@ -56,15 +55,9 @@ class ClassicDevice { } return section_ < other.section_; } - bool operator>(const ClassicDevice& rhs) const { - return (rhs < *this); - } - bool operator<=(const ClassicDevice& rhs) const { - return !(*this > rhs); - } - bool operator>=(const ClassicDevice& rhs) const { - return !(*this < rhs); - } + bool operator>(const ClassicDevice& rhs) const { return rhs < *this; } + bool operator<=(const ClassicDevice& rhs) const { return !(*this > rhs); } + bool operator>=(const ClassicDevice& rhs) const { return !(*this < rhs); } // Get the parent device Device Parent(); @@ -81,13 +74,13 @@ class ClassicDevice { // Property names that correspond to a link key used in Bluetooth classic device static const std::unordered_set kLinkKeyProperties; - private: +private: ConfigCache* config_; ConfigCache* memory_only_config_; std::string section_; friend std::hash; - public: +public: GENERATE_PROPERTY_GETTER_SETTER_REMOVER(LinkKey, hci::LinkKey, "LinkKey"); GENERATE_PROPERTY_GETTER_SETTER_REMOVER(LinkKeyType, hci::KeyType, "LinkKeyType"); GENERATE_PROPERTY_GETTER_SETTER_REMOVER(SdpDiManufacturer, uint16_t, "SdpDiManufacturer"); diff --git a/system/gd/storage/classic_device_test.cc b/system/gd/storage/classic_device_test.cc index fd5654aa933..ae26587d7a2 100644 --- a/system/gd/storage/classic_device_test.cc +++ b/system/gd/storage/classic_device_test.cc @@ -14,12 +14,13 @@ * limitations under the License. */ +#include "storage/classic_device.h" + #include #include #include "common/byte_array.h" #include "hci/link_key.h" -#include "storage/classic_device.h" #include "storage/mutation.h" using bluetooth::common::ByteArray; @@ -90,74 +91,98 @@ TEST(ClassicDeviceTest, operator_less_than) { bluetooth::hci::Address larger_address = {{0x01, 0x02, 0x03, 0x04, 0x05, 0x07}}; { - ClassicDevice device1(smaller_config_ptr, smaller_memory_only_config_ptr, smaller_address.ToString()); - ClassicDevice device2(larger_config_ptr, larger_memory_only_config_ptr, larger_address.ToString()); + ClassicDevice device1(smaller_config_ptr, smaller_memory_only_config_ptr, + smaller_address.ToString()); + ClassicDevice device2(larger_config_ptr, larger_memory_only_config_ptr, + larger_address.ToString()); ASSERT_TRUE(device1 < device2); } { - ClassicDevice device1(larger_config_ptr, smaller_memory_only_config_ptr, smaller_address.ToString()); - ClassicDevice device2(smaller_config_ptr, larger_memory_only_config_ptr, larger_address.ToString()); + ClassicDevice device1(larger_config_ptr, smaller_memory_only_config_ptr, + smaller_address.ToString()); + ClassicDevice device2(smaller_config_ptr, larger_memory_only_config_ptr, + larger_address.ToString()); ASSERT_FALSE(device1 < device2); } { - ClassicDevice device1(smaller_config_ptr, larger_memory_only_config_ptr, smaller_address.ToString()); - ClassicDevice device2(larger_config_ptr, smaller_memory_only_config_ptr, larger_address.ToString()); + ClassicDevice device1(smaller_config_ptr, larger_memory_only_config_ptr, + smaller_address.ToString()); + ClassicDevice device2(larger_config_ptr, smaller_memory_only_config_ptr, + larger_address.ToString()); ASSERT_TRUE(device1 < device2); } { - ClassicDevice device1(smaller_config_ptr, smaller_memory_only_config_ptr, larger_address.ToString()); - ClassicDevice device2(larger_config_ptr, larger_memory_only_config_ptr, smaller_address.ToString()); + ClassicDevice device1(smaller_config_ptr, smaller_memory_only_config_ptr, + larger_address.ToString()); + ClassicDevice device2(larger_config_ptr, larger_memory_only_config_ptr, + smaller_address.ToString()); ASSERT_TRUE(device1 < device2); } { - ClassicDevice device1(larger_config_ptr, larger_memory_only_config_ptr, smaller_address.ToString()); - ClassicDevice device2(smaller_config_ptr, smaller_memory_only_config_ptr, larger_address.ToString()); + ClassicDevice device1(larger_config_ptr, larger_memory_only_config_ptr, + smaller_address.ToString()); + ClassicDevice device2(smaller_config_ptr, smaller_memory_only_config_ptr, + larger_address.ToString()); ASSERT_FALSE(device1 < device2); } { - ClassicDevice device1(larger_config_ptr, larger_memory_only_config_ptr, larger_address.ToString()); - ClassicDevice device2(smaller_config_ptr, smaller_memory_only_config_ptr, smaller_address.ToString()); + ClassicDevice device1(larger_config_ptr, larger_memory_only_config_ptr, + larger_address.ToString()); + ClassicDevice device2(smaller_config_ptr, smaller_memory_only_config_ptr, + smaller_address.ToString()); ASSERT_FALSE(device1 < device2); } { - ClassicDevice device1(smaller_config_ptr, larger_memory_only_config_ptr, larger_address.ToString()); - ClassicDevice device2(larger_config_ptr, smaller_memory_only_config_ptr, smaller_address.ToString()); + ClassicDevice device1(smaller_config_ptr, larger_memory_only_config_ptr, + larger_address.ToString()); + ClassicDevice device2(larger_config_ptr, smaller_memory_only_config_ptr, + smaller_address.ToString()); ASSERT_TRUE(device1 < device2); } { - ClassicDevice device1(larger_config_ptr, smaller_memory_only_config_ptr, larger_address.ToString()); - ClassicDevice device2(smaller_config_ptr, larger_memory_only_config_ptr, smaller_address.ToString()); + ClassicDevice device1(larger_config_ptr, smaller_memory_only_config_ptr, + larger_address.ToString()); + ClassicDevice device2(smaller_config_ptr, larger_memory_only_config_ptr, + smaller_address.ToString()); ASSERT_FALSE(device1 < device2); } { - ClassicDevice device1(smaller_config_ptr, smaller_memory_only_config_ptr, smaller_address.ToString()); - ClassicDevice device2(smaller_config_ptr, larger_memory_only_config_ptr, smaller_address.ToString()); + ClassicDevice device1(smaller_config_ptr, smaller_memory_only_config_ptr, + smaller_address.ToString()); + ClassicDevice device2(smaller_config_ptr, larger_memory_only_config_ptr, + smaller_address.ToString()); ASSERT_TRUE(device1 < device2); } { - ClassicDevice device1(smaller_config_ptr, smaller_memory_only_config_ptr, smaller_address.ToString()); - ClassicDevice device2(smaller_config_ptr, smaller_memory_only_config_ptr, larger_address.ToString()); + ClassicDevice device1(smaller_config_ptr, smaller_memory_only_config_ptr, + smaller_address.ToString()); + ClassicDevice device2(smaller_config_ptr, smaller_memory_only_config_ptr, + larger_address.ToString()); ASSERT_TRUE(device1 < device2); } { - ClassicDevice device1(smaller_config_ptr, smaller_memory_only_config_ptr, smaller_address.ToString()); - ClassicDevice device2(larger_config_ptr, smaller_memory_only_config_ptr, smaller_address.ToString()); + ClassicDevice device1(smaller_config_ptr, smaller_memory_only_config_ptr, + smaller_address.ToString()); + ClassicDevice device2(larger_config_ptr, smaller_memory_only_config_ptr, + smaller_address.ToString()); ASSERT_TRUE(device1 < device2); } { - ClassicDevice device1(smaller_config_ptr, smaller_memory_only_config_ptr, smaller_address.ToString()); - ClassicDevice device2(smaller_config_ptr, larger_memory_only_config_ptr, larger_address.ToString()); + ClassicDevice device1(smaller_config_ptr, smaller_memory_only_config_ptr, + smaller_address.ToString()); + ClassicDevice device2(smaller_config_ptr, larger_memory_only_config_ptr, + larger_address.ToString()); ASSERT_TRUE(device1 < device2); } } diff --git a/system/gd/storage/config_cache.cc b/system/gd/storage/config_cache.cc index df101720b22..f2517be128e 100644 --- a/system/gd/storage/config_cache.cc +++ b/system/gd/storage/config_cache.cc @@ -29,7 +29,8 @@ namespace { const std::unordered_set kEncryptKeyNameList = { - "LinkKey", "LE_KEY_PENC", "LE_KEY_PID", "LE_KEY_LID", "LE_KEY_PCSRK", "LE_KEY_LENC", "LE_KEY_LCSRK"}; + "LinkKey", "LE_KEY_PENC", "LE_KEY_PID", "LE_KEY_LID", + "LE_KEY_PCSRK", "LE_KEY_LENC", "LE_KEY_LCSRK"}; bool TrimAfterNewLine(std::string& value) { std::string value_no_newline; @@ -51,22 +52,24 @@ namespace bluetooth { namespace storage { const std::unordered_set kLePropertyNames = { - "LE_KEY_PENC", "LE_KEY_PID", "LE_KEY_PCSRK", "LE_KEY_LENC", "LE_KEY_LCSRK"}; + "LE_KEY_PENC", "LE_KEY_PID", "LE_KEY_PCSRK", "LE_KEY_LENC", "LE_KEY_LCSRK"}; const std::unordered_set kClassicPropertyNames = { - "LinkKey", "SdpDiMaufacturer", "SdpDiModel", "SdpDiHardwareVersion", "SdpDiVendorSource"}; + "LinkKey", "SdpDiMaufacturer", "SdpDiModel", "SdpDiHardwareVersion", "SdpDiVendorSource"}; const std::string ConfigCache::kDefaultSectionName = "Global"; std::string kEncryptedStr = "encrypted"; -ConfigCache::ConfigCache(size_t temp_device_capacity, std::unordered_set persistent_property_names) +ConfigCache::ConfigCache(size_t temp_device_capacity, + std::unordered_set persistent_property_names) : persistent_property_names_(std::move(persistent_property_names)), information_sections_(), persistent_devices_(), temporary_devices_(temp_device_capacity) {} -void ConfigCache::SetPersistentConfigChangedCallback(std::function persistent_config_changed_callback) { +void ConfigCache::SetPersistentConfigChangedCallback( + std::function persistent_config_changed_callback) { std::lock_guard lock(mutex_); persistent_config_changed_callback_ = std::move(persistent_config_changed_callback); } @@ -77,9 +80,8 @@ ConfigCache::ConfigCache(ConfigCache&& other) noexcept information_sections_(std::move(other.information_sections_)), persistent_devices_(std::move(other.persistent_devices_)), temporary_devices_(std::move(other.temporary_devices_)) { - log::assert_that( - other.persistent_config_changed_callback_ == nullptr, - "Can't assign after setting the callback"); + log::assert_that(other.persistent_config_changed_callback_ == nullptr, + "Can't assign after setting the callback"); } ConfigCache& ConfigCache::operator=(ConfigCache&& other) noexcept { @@ -88,9 +90,8 @@ ConfigCache& ConfigCache::operator=(ConfigCache&& other) noexcept { } std::lock_guard my_lock(mutex_); std::lock_guard others_lock(other.mutex_); - log::assert_that( - other.persistent_config_changed_callback_ == nullptr, - "Can't assign after setting the callback"); + log::assert_that(other.persistent_config_changed_callback_ == nullptr, + "Can't assign after setting the callback"); persistent_config_changed_callback_ = {}; persistent_property_names_ = std::move(other.persistent_property_names_); information_sections_ = std::move(other.information_sections_); @@ -103,13 +104,12 @@ bool ConfigCache::operator==(const ConfigCache& rhs) const { std::lock_guard my_lock(mutex_); std::lock_guard others_lock(rhs.mutex_); return persistent_property_names_ == rhs.persistent_property_names_ && - information_sections_ == rhs.information_sections_ && persistent_devices_ == rhs.persistent_devices_ && + information_sections_ == rhs.information_sections_ && + persistent_devices_ == rhs.persistent_devices_ && temporary_devices_ == rhs.temporary_devices_; } -bool ConfigCache::operator!=(const ConfigCache& rhs) const { - return !(*this == rhs); -} +bool ConfigCache::operator!=(const ConfigCache& rhs) const { return !(*this == rhs); } void ConfigCache::Clear() { std::lock_guard lock(mutex_); @@ -149,7 +149,8 @@ bool ConfigCache::HasProperty(const std::string& section, const std::string& pro return false; } -std::optional ConfigCache::GetProperty(const std::string& section, const std::string& property) const { +std::optional ConfigCache::GetProperty(const std::string& section, + const std::string& property) const { std::lock_guard lock(mutex_); auto section_iter = information_sections_.find(section); if (section_iter != information_sections_.end()) { @@ -189,7 +190,9 @@ void ConfigCache::SetProperty(std::string section, std::string property, std::st if (!IsDeviceSection(section)) { auto section_iter = information_sections_.find(section); if (section_iter == information_sections_.end()) { - section_iter = information_sections_.try_emplace_back(section, common::ListMap{}).first; + section_iter = information_sections_ + .try_emplace_back(section, common::ListMap{}) + .first; } section_iter->second.insert_or_assign(property, std::move(value)); PersistentConfigChangedCallback(); @@ -200,17 +203,22 @@ void ConfigCache::SetProperty(std::string section, std::string property, std::st // move paired devices or create new paired device when a link key is set auto section_properties = temporary_devices_.extract(section); if (section_properties) { - section_iter = persistent_devices_.try_emplace_back(section, std::move(section_properties->second)).first; + section_iter = + persistent_devices_.try_emplace_back(section, std::move(section_properties->second)) + .first; } else { - section_iter = persistent_devices_.try_emplace_back(section, common::ListMap{}).first; + section_iter = persistent_devices_ + .try_emplace_back(section, common::ListMap{}) + .first; } } if (section_iter != persistent_devices_.end()) { bool is_encrypted = value == kEncryptedStr; if ((!value.empty()) && os::ParameterProvider::GetBtKeystoreInterface() != nullptr && - os::ParameterProvider::IsCommonCriteriaMode() && InEncryptKeyNameList(property) && !is_encrypted) { + os::ParameterProvider::IsCommonCriteriaMode() && InEncryptKeyNameList(property) && + !is_encrypted) { if (os::ParameterProvider::GetBtKeystoreInterface()->set_encrypt_key_or_remove_key( - section + "-" + property, value)) { + section + "-" + property, value)) { value = kEncryptedStr; } } @@ -220,7 +228,8 @@ void ConfigCache::SetProperty(std::string section, std::string property, std::st } section_iter = temporary_devices_.find(section); if (section_iter == temporary_devices_.end()) { - auto triple = temporary_devices_.try_emplace(section, common::ListMap{}); + auto triple = + temporary_devices_.try_emplace(section, common::ListMap{}); section_iter = std::get<0>(triple); } section_iter->second.insert_or_assign(property, std::move(value)); @@ -266,9 +275,10 @@ bool ConfigCache::RemoveProperty(const std::string& section, const std::string& } if (value.has_value()) { PersistentConfigChangedCallback(); - if (os::ParameterProvider::GetBtKeystoreInterface() != nullptr && os::ParameterProvider::IsCommonCriteriaMode() && - InEncryptKeyNameList(property)) { - os::ParameterProvider::GetBtKeystoreInterface()->set_encrypt_key_or_remove_key(section + "-" + property, ""); + if (os::ParameterProvider::GetBtKeystoreInterface() != nullptr && + os::ParameterProvider::IsCommonCriteriaMode() && InEncryptKeyNameList(property)) { + os::ParameterProvider::GetBtKeystoreInterface()->set_encrypt_key_or_remove_key( + section + "-" + property, ""); } return true; } else { @@ -296,16 +306,17 @@ void ConfigCache::ConvertEncryptOrDecryptKeyIfNeeded() { auto property_iter = section_iter->second.find(std::string(property)); if (property_iter != section_iter->second.end()) { bool is_encrypted = property_iter->second == kEncryptedStr; - if ((!property_iter->second.empty()) && os::ParameterProvider::GetBtKeystoreInterface() != nullptr && + if ((!property_iter->second.empty()) && + os::ParameterProvider::GetBtKeystoreInterface() != nullptr && os::ParameterProvider::IsCommonCriteriaMode() && !is_encrypted) { if (os::ParameterProvider::GetBtKeystoreInterface()->set_encrypt_key_or_remove_key( - section + "-" + std::string(property), property_iter->second)) { + section + "-" + std::string(property), property_iter->second)) { SetProperty(section, std::string(property), kEncryptedStr); } } if (os::ParameterProvider::GetBtKeystoreInterface() != nullptr && is_encrypted) { - std::string value_str = - os::ParameterProvider::GetBtKeystoreInterface()->get_key(section + "-" + std::string(property)); + std::string value_str = os::ParameterProvider::GetBtKeystoreInterface()->get_key( + section + "-" + std::string(property)); if (!os::ParameterProvider::IsCommonCriteriaMode()) { SetProperty(section, std::string(property), value_str); } @@ -375,7 +386,8 @@ void ConfigCache::Commit(std::queue& mutation_entries) { case MutationEntry::EntryType::REMOVE_SECTION: RemoveSection(entry.section); break; - // do not write a default case so that when a new enum is defined, compilation would fail automatically + // do not write a default case so that when a new enum is defined, compilation would fail + // automatically } } } @@ -396,7 +408,7 @@ std::string ConfigCache::SerializeToLegacyFormat() const { } std::vector ConfigCache::GetSectionNamesWithProperty( - const std::string& property) const { + const std::string& property) const { std::lock_guard lock(mutex_); std::vector result; for (auto* config_section : {&information_sections_, &persistent_devices_}) { @@ -447,7 +459,8 @@ std::vector ConfigCache::GetPropertyNames(const std::string& sectio namespace { bool FixDeviceTypeInconsistencyInSection( - const std::string& section_name, common::ListMap& device_section_entries) { + const std::string& section_name, + common::ListMap& device_section_entries) { if (!hci::Address::IsValidAddress(section_name)) { return false; } @@ -518,7 +531,8 @@ bool ConfigCache::FixDeviceTypeInconsistencies() { } bool ConfigCache::HasAtLeastOneMatchingPropertiesInSection( - const std::string& section, const std::unordered_set& property_names) const { + const std::string& section, + const std::unordered_set& property_names) const { std::lock_guard lock(mutex_); const common::ListMap* section_ptr; if (!IsDeviceSection(section)) { diff --git a/system/gd/storage/config_cache.h b/system/gd/storage/config_cache.h index 9c9c5b1e6e4..238660170c1 100644 --- a/system/gd/storage/config_cache.h +++ b/system/gd/storage/config_cache.h @@ -39,19 +39,22 @@ class Mutation; // A memory operated section-key-value structured config // -// A section can be either persistent or temporary. When a section becomes persistent, all its properties are -// written to disk. +// A section can be either persistent or temporary. When a section becomes persistent, all its +// properties are written to disk. // -// A section becomes persistent when a property that is part of persistent_property_names_ is written to config cache; -// A section becomes temporary when all properties that are part of persistent_property_names_ is removed +// A section becomes persistent when a property that is part of persistent_property_names_ is +// written to config cache; A section becomes temporary when all properties that are part of +// persistent_property_names_ is removed // -// The definition of persistent sections is up to the user and is defined through the |persistent_property_names| -// argument. When these properties are link key properties, then persistent sections is equal to bonded devices +// The definition of persistent sections is up to the user and is defined through the +// |persistent_property_names| argument. When these properties are link key properties, then +// persistent sections is equal to bonded devices // // This class is thread safe class ConfigCache { - public: - ConfigCache(size_t temp_device_capacity, std::unordered_set persistent_property_names); +public: + ConfigCache(size_t temp_device_capacity, + std::unordered_set persistent_property_names); ConfigCache(const ConfigCache&) = delete; ConfigCache& operator=(const ConfigCache&) = delete; @@ -72,14 +75,16 @@ class ConfigCache { virtual bool HasSection(const std::string& section) const; virtual bool HasProperty(const std::string& section, const std::string& property) const; // Get property, return std::nullopt if section or property does not exist - virtual std::optional GetProperty(const std::string& section, const std::string& property) const; + virtual std::optional GetProperty(const std::string& section, + const std::string& property) const; // Returns a copy of persistent device MAC addresses virtual std::vector GetPersistentSections() const; // Return true if a section is persistent virtual bool IsPersistentSection(const std::string& section) const; // Return true if a section has one of the properties in |property_names| virtual bool HasAtLeastOneMatchingPropertiesInSection( - const std::string& section, const std::unordered_set& property_names) const; + const std::string& section, + const std::unordered_set& property_names) const; // Return true if a property is part of persistent_property_names_ virtual bool IsPersistentProperty(const std::string& property) const; // Serialize to legacy config format @@ -91,11 +96,10 @@ class ConfigCache { bool operator==(const SectionAndPropertyValue& rhs) const { return section == rhs.section && property == rhs.property; } - bool operator!=(const SectionAndPropertyValue& rhs) const { - return !(*this == rhs); - } + bool operator!=(const SectionAndPropertyValue& rhs) const { return !(*this == rhs); } }; - virtual std::vector GetSectionNamesWithProperty(const std::string& property) const; + virtual std::vector GetSectionNamesWithProperty( + const std::string& property) const; // Returns all property names in the specific section. virtual std::vector GetPropertyNames(const std::string& section) const; @@ -112,11 +116,13 @@ class ConfigCache { // remove all content in this config cache, restore it to the state after the explicit constructor virtual void Clear(); // Set a callback to notify interested party that a persistent config change has just happened - virtual void SetPersistentConfigChangedCallback(std::function persistent_config_changed_callback); + virtual void SetPersistentConfigChangedCallback( + std::function persistent_config_changed_callback); // Device config specific methods - // TODO: methods here should be moved to a device specific config cache if this config cache is supposed to be generic - // Legacy stack has device type inconsistencies, this method is trying to fix it + // TODO: methods here should be moved to a device specific config cache if this config cache is + // supposed to be generic Legacy stack has device type inconsistencies, this method is trying to + // fix it virtual bool FixDeviceTypeInconsistencies(); // static methods @@ -126,19 +132,20 @@ class ConfigCache { // constants static const std::string kDefaultSectionName; - private: +private: mutable std::recursive_mutex mutex_; - // A callback to notify interested party that a persistent config change has just happened, empty by default + // A callback to notify interested party that a persistent config change has just happened, empty + // by default std::function persistent_config_changed_callback_; - // A set of property names that if set would make a section persistent and if non of these properties are set, a - // section would become temporary again + // A set of property names that if set would make a section persistent and if non of these + // properties are set, a section would become temporary again std::unordered_set persistent_property_names_; // Common section that does not relate to remote device, will be written to disk common::ListMap> information_sections_; // Information about persistent devices, normally paired, will be written to disk common::ListMap> persistent_devices_; - // Information about temporary devices, normally unpaired, will not be written to disk, will be evicted automatically - // if capacity exceeds given value during initialization + // Information about temporary devices, normally unpaired, will not be written to disk, will be + // evicted automatically if capacity exceeds given value during initialization common::LruCache> temporary_devices_; // Convenience method to check if the callback is valid before calling it diff --git a/system/gd/storage/config_cache_helper.cc b/system/gd/storage/config_cache_helper.cc index 5fb583188aa..485ed61508c 100644 --- a/system/gd/storage/config_cache_helper.cc +++ b/system/gd/storage/config_cache_helper.cc @@ -24,11 +24,13 @@ namespace bluetooth { namespace storage { -void ConfigCacheHelper::SetBool(const std::string& section, const std::string& property, bool value) { +void ConfigCacheHelper::SetBool(const std::string& section, const std::string& property, + bool value) { config_cache_.SetProperty(section, property, value ? "true" : "false"); } -std::optional ConfigCacheHelper::GetBool(const std::string& section, const std::string& property) const { +std::optional ConfigCacheHelper::GetBool(const std::string& section, + const std::string& property) const { auto value_str = config_cache_.GetProperty(section, property); if (!value_str) { return std::nullopt; @@ -42,11 +44,13 @@ std::optional ConfigCacheHelper::GetBool(const std::string& section, const } } -void ConfigCacheHelper::SetUint64(const std::string& section, const std::string& property, uint64_t value) { +void ConfigCacheHelper::SetUint64(const std::string& section, const std::string& property, + uint64_t value) { config_cache_.SetProperty(section, property, std::to_string(value)); } -std::optional ConfigCacheHelper::GetUint64(const std::string& section, const std::string& property) const { +std::optional ConfigCacheHelper::GetUint64(const std::string& section, + const std::string& property) const { auto value_str = config_cache_.GetProperty(section, property); if (!value_str) { return std::nullopt; @@ -54,11 +58,13 @@ std::optional ConfigCacheHelper::GetUint64(const std::string& section, return common::Uint64FromString(*value_str); } -void ConfigCacheHelper::SetUint32(const std::string& section, const std::string& property, uint32_t value) { +void ConfigCacheHelper::SetUint32(const std::string& section, const std::string& property, + uint32_t value) { config_cache_.SetProperty(section, property, std::to_string(value)); } -std::optional ConfigCacheHelper::GetUint32(const std::string& section, const std::string& property) const { +std::optional ConfigCacheHelper::GetUint32(const std::string& section, + const std::string& property) const { auto value_str = config_cache_.GetProperty(section, property); if (!value_str) { return std::nullopt; @@ -73,11 +79,13 @@ std::optional ConfigCacheHelper::GetUint32(const std::string& section, return static_cast(*large_value); } -void ConfigCacheHelper::SetInt64(const std::string& section, const std::string& property, int64_t value) { +void ConfigCacheHelper::SetInt64(const std::string& section, const std::string& property, + int64_t value) { config_cache_.SetProperty(section, property, std::to_string(value)); } -std::optional ConfigCacheHelper::GetInt64(const std::string& section, const std::string& property) const { +std::optional ConfigCacheHelper::GetInt64(const std::string& section, + const std::string& property) const { auto value_str = config_cache_.GetProperty(section, property); if (!value_str) { return std::nullopt; @@ -89,7 +97,8 @@ void ConfigCacheHelper::SetInt(const std::string& section, const std::string& pr config_cache_.SetProperty(section, property, std::to_string(value)); } -std::optional ConfigCacheHelper::GetInt(const std::string& section, const std::string& property) const { +std::optional ConfigCacheHelper::GetInt(const std::string& section, + const std::string& property) const { auto value_str = config_cache_.GetProperty(section, property); if (!value_str) { return std::nullopt; @@ -104,13 +113,13 @@ std::optional ConfigCacheHelper::GetInt(const std::string& section, const s return static_cast(*large_value); } -void ConfigCacheHelper::SetBin( - const std::string& section, const std::string& property, const std::vector& value) { +void ConfigCacheHelper::SetBin(const std::string& section, const std::string& property, + const std::vector& value) { config_cache_.SetProperty(section, property, common::ToHexString(value)); } -std::optional> ConfigCacheHelper::GetBin( - const std::string& section, const std::string& property) const { +std::optional> ConfigCacheHelper::GetBin(const std::string& section, + const std::string& property) const { auto value_str = config_cache_.GetProperty(section, property); if (!value_str) { return std::nullopt; diff --git a/system/gd/storage/config_cache_helper.h b/system/gd/storage/config_cache_helper.h index 87e0dfd3f69..e4f5c23a57a 100644 --- a/system/gd/storage/config_cache_helper.h +++ b/system/gd/storage/config_cache_helper.h @@ -34,28 +34,36 @@ namespace storage { // A thin wrapper around ConfigCache and implement more type supports other than std::string // // - all SetX methods accept value as copy and std::move() in encouraged -// - all GetX methods return std::optional and std::nullopt if not exist. std::optional<> can be treated as bool +// - all GetX methods return std::optional and std::nullopt if not exist. std::optional<> can be +// treated as bool class ConfigCacheHelper { - public: +public: static ConfigCacheHelper FromConfigCache(ConfigCache& config_cache) { return ConfigCacheHelper(config_cache); } explicit ConfigCacheHelper(ConfigCache& config_cache) : config_cache_(config_cache) {} virtual ~ConfigCacheHelper() = default; virtual void SetBool(const std::string& section, const std::string& property, bool value); - virtual std::optional GetBool(const std::string& section, const std::string& property) const; + virtual std::optional GetBool(const std::string& section, + const std::string& property) const; virtual void SetUint64(const std::string& section, const std::string& property, uint64_t value); - virtual std::optional GetUint64(const std::string& section, const std::string& property) const; + virtual std::optional GetUint64(const std::string& section, + const std::string& property) const; virtual void SetUint32(const std::string& section, const std::string& property, uint32_t value); - virtual std::optional GetUint32(const std::string& section, const std::string& property) const; + virtual std::optional GetUint32(const std::string& section, + const std::string& property) const; virtual void SetInt64(const std::string& section, const std::string& property, int64_t value); - virtual std::optional GetInt64(const std::string& section, const std::string& property) const; + virtual std::optional GetInt64(const std::string& section, + const std::string& property) const; virtual void SetInt(const std::string& section, const std::string& property, int value); virtual std::optional GetInt(const std::string& section, const std::string& property) const; - virtual void SetBin(const std::string& section, const std::string& property, const std::vector& value); - virtual std::optional> GetBin(const std::string& section, const std::string& property) const; + virtual void SetBin(const std::string& section, const std::string& property, + const std::vector& value); + virtual std::optional> GetBin(const std::string& section, + const std::string& property) const; - template && std::is_integral_v, int>::type = 0> + template && std::is_integral_v, int>::type = 0> std::optional Get(const std::string& section, const std::string& property) { auto value = GetInt64(section, property); if (!value) { @@ -67,7 +75,8 @@ class ConfigCacheHelper { return static_cast(*value); } - template && std::is_integral_v, int>::type = 0> + template && std::is_integral_v, int>::type = 0> std::optional Get(const std::string& section, const std::string& property) { auto value = GetUint64(section, property); if (!value) { @@ -84,7 +93,8 @@ class ConfigCacheHelper { return config_cache_.GetProperty(section, property); } - template >, int>::type = 0> + template >, int>::type = 0> std::optional Get(const std::string& section, const std::string& property) { return GetBin(section, property); } @@ -94,7 +104,8 @@ class ConfigCacheHelper { return GetBool(section, property); } - template , T>, int>::type = 0> + template , T>, int>::type = 0> std::optional Get(const std::string& section, const std::string& property) { auto value = config_cache_.GetProperty(section, property); if (!value) { @@ -112,12 +123,11 @@ class ConfigCacheHelper { return bluetooth::FromLegacyConfigString(*value); } - template < - typename T, - typename std::enable_if< - bluetooth::common::is_specialization_of::value && - std::is_base_of_v, typename T::value_type>, - int>::type = 0> + template ::value && + std::is_base_of_v, + typename T::value_type>, + int>::type = 0> std::optional Get(const std::string& section, const std::string& property) { auto value = config_cache_.GetProperty(section, property); if (!value) { @@ -136,7 +146,7 @@ class ConfigCacheHelper { return result; } - private: +private: ConfigCache& config_cache_; }; diff --git a/system/gd/storage/config_cache_helper_test.cc b/system/gd/storage/config_cache_helper_test.cc index 73e3b8dee76..1627023d1c8 100644 --- a/system/gd/storage/config_cache_helper_test.cc +++ b/system/gd/storage/config_cache_helper_test.cc @@ -52,7 +52,8 @@ TEST(ConfigCacheHelperTest, set_get_uint64_test) { uint64_t num = std::numeric_limits::max(); num = num * 10; ConfigCacheHelper(config).SetUint64("A", "B", num); - ASSERT_THAT(config.GetProperty("A", "B"), Optional(StrEq(std::to_string(std::numeric_limits::max()) + "0"))); + ASSERT_THAT(config.GetProperty("A", "B"), + Optional(StrEq(std::to_string(std::numeric_limits::max()) + "0"))); ASSERT_THAT(ConfigCacheHelper(config).GetUint64("A", "B"), Optional(Eq(num))); // zero ConfigCacheHelper(config).SetUint64("A", "B", 0); @@ -70,8 +71,8 @@ TEST(ConfigCacheHelperTest, set_get_uint32_test) { uint64_t num = std::numeric_limits::max(); num *= 10; ConfigCacheHelper(config).SetUint64("A", "B", num); - ASSERT_THAT( - config.GetProperty("A", "B"), Optional(StrEq(std::to_string(std::numeric_limits::max()) + "0"))); + ASSERT_THAT(config.GetProperty("A", "B"), + Optional(StrEq(std::to_string(std::numeric_limits::max()) + "0"))); ASSERT_FALSE(ConfigCacheHelper(config).GetUint32("A", "B")); // zero ConfigCacheHelper(config).SetUint32("A", "B", 0); @@ -85,12 +86,13 @@ TEST(ConfigCacheHelperTest, set_get_int64_test) { int64_t num = std::numeric_limits::max(); num *= 10; ConfigCacheHelper(config).SetInt64("A", "B", num); - ASSERT_THAT(config.GetProperty("A", "B"), Optional(StrEq(std::to_string(std::numeric_limits::max()) + "0"))); + ASSERT_THAT(config.GetProperty("A", "B"), + Optional(StrEq(std::to_string(std::numeric_limits::max()) + "0"))); ASSERT_THAT(ConfigCacheHelper(config).GetInt64("A", "B"), Optional(Eq(int64_t(num)))); // negative ConfigCacheHelper(config).SetInt64("A", "B", -1 * num); - ASSERT_THAT( - config.GetProperty("A", "B"), Optional(StrEq("-" + std::to_string(std::numeric_limits::max()) + "0"))); + ASSERT_THAT(config.GetProperty("A", "B"), + Optional(StrEq("-" + std::to_string(std::numeric_limits::max()) + "0"))); ASSERT_THAT(ConfigCacheHelper(config).GetInt64("A", "B"), Optional(Eq(-1 * num))); // zero ConfigCacheHelper(config).SetInt("A", "B", 0); diff --git a/system/gd/storage/config_cache_test.cc b/system/gd/storage/config_cache_test.cc index 13d0a90c74e..c129e8841bb 100644 --- a/system/gd/storage/config_cache_test.cc +++ b/system/gd/storage/config_cache_test.cc @@ -213,7 +213,8 @@ TEST(ConfigCacheTest, get_persistent_devices_test) { ASSERT_TRUE(config.HasProperty("CC:DD:EE:FF:00:11", BTIF_STORAGE_KEY_LINK_KEY)); ASSERT_THAT(config.GetPersistentSections(), ElementsAre("CC:DD:EE:FF:00:11")); config.SetProperty("AA:BB:CC:DD:EE:FF", BTIF_STORAGE_KEY_LINK_KEY, "DEERDEERDEER"); - ASSERT_THAT(config.GetPersistentSections(), ElementsAre("CC:DD:EE:FF:00:11", "AA:BB:CC:DD:EE:FF")); + ASSERT_THAT(config.GetPersistentSections(), + ElementsAre("CC:DD:EE:FF:00:11", "AA:BB:CC:DD:EE:FF")); ASSERT_TRUE(config.RemoveProperty("CC:DD:EE:FF:00:11", BTIF_STORAGE_KEY_LINK_KEY)); ASSERT_THAT(config.GetPersistentSections(), ElementsAre("AA:BB:CC:DD:EE:FF")); } @@ -230,21 +231,19 @@ TEST(ConfigCacheTest, appoaching_temporary_config_limit_test) { if (i % 2 == 0) { ASSERT_TRUE(config.HasSection(GetTestAddress(i))); ASSERT_TRUE(config.HasProperty(GetTestAddress(i), BTIF_STORAGE_KEY_LINK_KEY)); - ASSERT_THAT( - config.GetProperty(GetTestAddress(i), BTIF_STORAGE_KEY_NAME), - Optional(StrEq("Hello" + std::to_string(i)))); + ASSERT_THAT(config.GetProperty(GetTestAddress(i), BTIF_STORAGE_KEY_NAME), + Optional(StrEq("Hello" + std::to_string(i)))); } else if (i >= 7) { ASSERT_TRUE(config.HasSection(GetTestAddress(i))); - ASSERT_THAT( - config.GetProperty(GetTestAddress(i), BTIF_STORAGE_KEY_NAME), - Optional(StrEq("Hello" + std::to_string(i)))); + ASSERT_THAT(config.GetProperty(GetTestAddress(i), BTIF_STORAGE_KEY_NAME), + Optional(StrEq("Hello" + std::to_string(i)))); } else { ASSERT_FALSE(config.HasSection(GetTestAddress(i))); } } - ASSERT_THAT( - config.GetPersistentSections(), - ElementsAre(GetTestAddress(0), GetTestAddress(2), GetTestAddress(4), GetTestAddress(6), GetTestAddress(8))); + ASSERT_THAT(config.GetPersistentSections(), + ElementsAre(GetTestAddress(0), GetTestAddress(2), GetTestAddress(4), + GetTestAddress(6), GetTestAddress(8))); } TEST(ConfigCacheTest, remove_section_with_property_test) { @@ -289,9 +288,8 @@ TEST(ConfigCacheTest, fix_device_type_inconsistency_missing_devtype_no_keys_test auto hadInconsistencies = config.FixDeviceTypeInconsistencies(); ASSERT_TRUE(hadInconsistencies); - ASSERT_THAT( - config.GetProperty("AA:BB:CC:DD:EE:FF", BTIF_STORAGE_KEY_DEV_TYPE), - Optional(StrEq(std::to_string(bluetooth::hci::DeviceType::BR_EDR)))); + ASSERT_THAT(config.GetProperty("AA:BB:CC:DD:EE:FF", BTIF_STORAGE_KEY_DEV_TYPE), + Optional(StrEq(std::to_string(bluetooth::hci::DeviceType::BR_EDR)))); } TEST(ConfigCacheTest, fix_device_type_inconsistency_consistent_devtype_test) { @@ -300,16 +298,12 @@ TEST(ConfigCacheTest, fix_device_type_inconsistency_consistent_devtype_test) { config.SetProperty("A", "B", "C"); config.SetProperty("AA:BB:CC:DD:EE:FF", "B", "C"); config.SetProperty("AA:BB:CC:DD:EE:FF", "C", "D"); - config.SetProperty( - "AA:BB:CC:DD:EE:FF", - BTIF_STORAGE_KEY_DEV_TYPE, - std::to_string(bluetooth::hci::DeviceType::BR_EDR)); + config.SetProperty("AA:BB:CC:DD:EE:FF", BTIF_STORAGE_KEY_DEV_TYPE, + std::to_string(bluetooth::hci::DeviceType::BR_EDR)); config.SetProperty("CC:DD:EE:FF:00:11", "B", "AABBAABBCCDDEE"); - config.SetProperty( - "CC:DD:EE:FF:00:11", - BTIF_STORAGE_KEY_DEV_TYPE, - std::to_string(bluetooth::hci::DeviceType::BR_EDR)); + config.SetProperty("CC:DD:EE:FF:00:11", BTIF_STORAGE_KEY_DEV_TYPE, + std::to_string(bluetooth::hci::DeviceType::BR_EDR)); config.SetProperty("CC:DD:EE:FF:00:11", BTIF_STORAGE_KEY_LINK_KEY, "AABBAABBCCDDEE"); // act @@ -317,9 +311,8 @@ TEST(ConfigCacheTest, fix_device_type_inconsistency_consistent_devtype_test) { // assert ASSERT_FALSE(hadInconsistencies); - ASSERT_THAT( - config.GetProperty("CC:DD:EE:FF:00:11", BTIF_STORAGE_KEY_DEV_TYPE), - Optional(StrEq(std::to_string(bluetooth::hci::DeviceType::BR_EDR)))); + ASSERT_THAT(config.GetProperty("CC:DD:EE:FF:00:11", BTIF_STORAGE_KEY_DEV_TYPE), + Optional(StrEq(std::to_string(bluetooth::hci::DeviceType::BR_EDR)))); } TEST(ConfigCacheTest, fix_device_type_inconsistency_devtype_should_be_dual_test) { @@ -328,16 +321,12 @@ TEST(ConfigCacheTest, fix_device_type_inconsistency_devtype_should_be_dual_test) config.SetProperty("A", "B", "C"); config.SetProperty("AA:BB:CC:DD:EE:FF", "B", "C"); config.SetProperty("AA:BB:CC:DD:EE:FF", "C", "D"); - config.SetProperty( - "AA:BB:CC:DD:EE:FF", - BTIF_STORAGE_KEY_DEV_TYPE, - std::to_string(bluetooth::hci::DeviceType::BR_EDR)); + config.SetProperty("AA:BB:CC:DD:EE:FF", BTIF_STORAGE_KEY_DEV_TYPE, + std::to_string(bluetooth::hci::DeviceType::BR_EDR)); config.SetProperty("CC:DD:EE:FF:00:11", "B", "AABBAABBCCDDEE"); - config.SetProperty( - "CC:DD:EE:FF:00:11", - BTIF_STORAGE_KEY_DEV_TYPE, - std::to_string(bluetooth::hci::DeviceType::BR_EDR)); + config.SetProperty("CC:DD:EE:FF:00:11", BTIF_STORAGE_KEY_DEV_TYPE, + std::to_string(bluetooth::hci::DeviceType::BR_EDR)); config.SetProperty("CC:DD:EE:FF:00:11", BTIF_STORAGE_KEY_LINK_KEY, "AABBAABBCCDDEE"); config.SetProperty("CC:DD:EE:FF:00:11", BTIF_STORAGE_KEY_LE_KEY_PENC, "AABBAABBCCDDEE"); @@ -346,9 +335,8 @@ TEST(ConfigCacheTest, fix_device_type_inconsistency_devtype_should_be_dual_test) // assert ASSERT_TRUE(hadInconsistencies); - ASSERT_THAT( - config.GetProperty("CC:DD:EE:FF:00:11", BTIF_STORAGE_KEY_DEV_TYPE), - Optional(StrEq(std::to_string(bluetooth::hci::DeviceType::DUAL)))); + ASSERT_THAT(config.GetProperty("CC:DD:EE:FF:00:11", BTIF_STORAGE_KEY_DEV_TYPE), + Optional(StrEq(std::to_string(bluetooth::hci::DeviceType::DUAL)))); } TEST(ConfigCacheTest, fix_device_type_inconsistency_devtype_should_be_le_not_classic_test) { @@ -357,16 +345,12 @@ TEST(ConfigCacheTest, fix_device_type_inconsistency_devtype_should_be_le_not_cla config.SetProperty("A", "B", "C"); config.SetProperty("AA:BB:CC:DD:EE:FF", "B", "C"); config.SetProperty("AA:BB:CC:DD:EE:FF", "C", "D"); - config.SetProperty( - "AA:BB:CC:DD:EE:FF", - BTIF_STORAGE_KEY_DEV_TYPE, - std::to_string(bluetooth::hci::DeviceType::BR_EDR)); + config.SetProperty("AA:BB:CC:DD:EE:FF", BTIF_STORAGE_KEY_DEV_TYPE, + std::to_string(bluetooth::hci::DeviceType::BR_EDR)); config.SetProperty("CC:DD:EE:FF:00:11", "B", "AABBAABBCCDDEE"); - config.SetProperty( - "CC:DD:EE:FF:00:11", - BTIF_STORAGE_KEY_DEV_TYPE, - std::to_string(bluetooth::hci::DeviceType::BR_EDR)); + config.SetProperty("CC:DD:EE:FF:00:11", BTIF_STORAGE_KEY_DEV_TYPE, + std::to_string(bluetooth::hci::DeviceType::BR_EDR)); config.SetProperty("CC:DD:EE:FF:00:11", BTIF_STORAGE_KEY_LE_KEY_PENC, "AABBAABBCCDDEE"); // act @@ -374,9 +358,8 @@ TEST(ConfigCacheTest, fix_device_type_inconsistency_devtype_should_be_le_not_cla // assert ASSERT_TRUE(hadInconsistencies); - ASSERT_THAT( - config.GetProperty("CC:DD:EE:FF:00:11", BTIF_STORAGE_KEY_DEV_TYPE), - Optional(StrEq(std::to_string(bluetooth::hci::DeviceType::LE)))); + ASSERT_THAT(config.GetProperty("CC:DD:EE:FF:00:11", BTIF_STORAGE_KEY_DEV_TYPE), + Optional(StrEq(std::to_string(bluetooth::hci::DeviceType::LE)))); } TEST(ConfigCacheTest, fix_device_type_inconsistency_devtype_dont_override_dual_test) { @@ -385,16 +368,12 @@ TEST(ConfigCacheTest, fix_device_type_inconsistency_devtype_dont_override_dual_t config.SetProperty("A", "B", "C"); config.SetProperty("AA:BB:CC:DD:EE:FF", "B", "C"); config.SetProperty("AA:BB:CC:DD:EE:FF", "C", "D"); - config.SetProperty( - "AA:BB:CC:DD:EE:FF", - BTIF_STORAGE_KEY_DEV_TYPE, - std::to_string(bluetooth::hci::DeviceType::BR_EDR)); + config.SetProperty("AA:BB:CC:DD:EE:FF", BTIF_STORAGE_KEY_DEV_TYPE, + std::to_string(bluetooth::hci::DeviceType::BR_EDR)); config.SetProperty("CC:DD:EE:FF:00:11", "B", "AABBAABBCCDDEE"); - config.SetProperty( - "CC:DD:EE:FF:00:11", - BTIF_STORAGE_KEY_DEV_TYPE, - std::to_string(bluetooth::hci::DeviceType::DUAL)); + config.SetProperty("CC:DD:EE:FF:00:11", BTIF_STORAGE_KEY_DEV_TYPE, + std::to_string(bluetooth::hci::DeviceType::DUAL)); config.SetProperty("CC:DD:EE:FF:00:11", BTIF_STORAGE_KEY_LINK_KEY, "AABBAABBCCDDEE"); config.SetProperty("CC:DD:EE:FF:00:11", BTIF_STORAGE_KEY_LE_KEY_PENC, "AABBAABBCCDDEE"); @@ -403,9 +382,8 @@ TEST(ConfigCacheTest, fix_device_type_inconsistency_devtype_dont_override_dual_t // assert ASSERT_FALSE(hadInconsistencies); - ASSERT_THAT( - config.GetProperty("CC:DD:EE:FF:00:11", BTIF_STORAGE_KEY_DEV_TYPE), - Optional(StrEq(std::to_string(bluetooth::hci::DeviceType::DUAL)))); + ASSERT_THAT(config.GetProperty("CC:DD:EE:FF:00:11", BTIF_STORAGE_KEY_DEV_TYPE), + Optional(StrEq(std::to_string(bluetooth::hci::DeviceType::DUAL)))); } TEST(ConfigCacheTest, test_get_section_with_property) { @@ -414,10 +392,9 @@ TEST(ConfigCacheTest, test_get_section_with_property) { config.SetProperty("AA:BB:CC:DD:EE:FF", "B", "C"); config.SetProperty("AA:BB:CC:DD:EE:EF", "C", "D"); ASSERT_THAT( - config.GetSectionNamesWithProperty("B"), - ElementsAre( - SectionAndPropertyValue{.section = "A", .property = "C"}, - SectionAndPropertyValue{.section = "AA:BB:CC:DD:EE:FF", .property = "C"})); + config.GetSectionNamesWithProperty("B"), + ElementsAre(SectionAndPropertyValue{.section = "A", .property = "C"}, + SectionAndPropertyValue{.section = "AA:BB:CC:DD:EE:FF", .property = "C"})); } TEST(ConfigCacheTest, test_get_sections_matching_at_least_one_property) { @@ -425,7 +402,8 @@ TEST(ConfigCacheTest, test_get_sections_matching_at_least_one_property) { config.SetProperty("A", "B", "C"); config.SetProperty("AA:BB:CC:DD:EE:FF", "B", "C"); config.SetProperty("AA:BB:CC:DD:EE:EF", "C", "D"); - ASSERT_TRUE(config.HasAtLeastOneMatchingPropertiesInSection("AA:BB:CC:DD:EE:FF", {"B", "C", "D"})); + ASSERT_TRUE( + config.HasAtLeastOneMatchingPropertiesInSection("AA:BB:CC:DD:EE:FF", {"B", "C", "D"})); ASSERT_TRUE(config.HasAtLeastOneMatchingPropertiesInSection("A", {"B", "C", "D"})); ASSERT_FALSE(config.HasAtLeastOneMatchingPropertiesInSection("AA:BB:CC:DD:EE:FF", {"BC", "D"})); } @@ -436,7 +414,8 @@ TEST(ConfigCacheTest, test_empty_persistent_properties) { config.SetProperty("AA:BB:CC:DD:EE:FF", "B", "C"); config.SetProperty("AA:BB:CC:DD:EE:EF", "C", "D"); config.SetProperty("AA:BB:CC:DD:EE:EF", BTIF_STORAGE_KEY_LINK_KEY, "D"); - ASSERT_TRUE(config.HasAtLeastOneMatchingPropertiesInSection("AA:BB:CC:DD:EE:FF", {"B", "C", "D"})); + ASSERT_TRUE( + config.HasAtLeastOneMatchingPropertiesInSection("AA:BB:CC:DD:EE:FF", {"B", "C", "D"})); ASSERT_TRUE(config.HasAtLeastOneMatchingPropertiesInSection("A", {"B", "C", "D"})); ASSERT_FALSE(config.HasAtLeastOneMatchingPropertiesInSection("AA:BB:CC:DD:EE:FF", {"BC", "D"})); ASSERT_THAT(config.GetPersistentSections(), ElementsAre()); diff --git a/system/gd/storage/device.cc b/system/gd/storage/device.cc index a48ffe73c6f..50d973bdc51 100644 --- a/system/gd/storage/device.cc +++ b/system/gd/storage/device.cc @@ -36,8 +36,8 @@ namespace { const std::string kLeIdentityAddressKey = "LeIdentityAddr"; const std::string kLeLegacyPseudoAddr = "LeLegacyPseudoAddr"; -std::string GetConfigSection( - ConfigCache* config, const hci::Address& key_address, Device::ConfigKeyAddressType key_address_type) { +std::string GetConfigSection(ConfigCache* config, const hci::Address& key_address, + Device::ConfigKeyAddressType key_address_type) { log::assert_that(config != nullptr, "config cannot be null"); log::assert_that(!key_address.IsEmpty(), "key_address cannot be empty"); // assume lower case @@ -47,14 +47,16 @@ std::string GetConfigSection( case Device::ConfigKeyAddressType::CLASSIC_ADDRESS: return key_address_string; case Device::ConfigKeyAddressType::LE_IDENTITY_ADDRESS: - for (const auto& section_and_property : config->GetSectionNamesWithProperty(kLeIdentityAddressKey)) { + for (const auto& section_and_property : + config->GetSectionNamesWithProperty(kLeIdentityAddressKey)) { if (section_and_property.property == key_address_string) { return section_and_property.section; } } return key_address_string; case Device::ConfigKeyAddressType::LE_LEGACY_PSEUDO_ADDRESS: - for (const auto& section_and_property : config->GetSectionNamesWithProperty(kLeLegacyPseudoAddr)) { + for (const auto& section_and_property : + config->GetSectionNamesWithProperty(kLeLegacyPseudoAddr)) { if (section_and_property.property == key_address_string) { return section_and_property.section; } @@ -70,21 +72,16 @@ std::string GetConfigSection( } // namespace const std::unordered_set Device::kLinkKeyProperties = { - "LinkKey", "LE_KEY_PENC", "LE_KEY_PID", "LE_KEY_PCSRK", "LE_KEY_LENC", "LE_KEY_LCSRK"}; + "LinkKey", "LE_KEY_PENC", "LE_KEY_PID", "LE_KEY_PCSRK", "LE_KEY_LENC", "LE_KEY_LCSRK"}; -Device::Device( - ConfigCache* config, - ConfigCache* memory_only_config, - const hci::Address& key_address, - ConfigKeyAddressType key_address_type) +Device::Device(ConfigCache* config, ConfigCache* memory_only_config, + const hci::Address& key_address, ConfigKeyAddressType key_address_type) : Device(config, memory_only_config, GetConfigSection(config, key_address, key_address_type)) {} Device::Device(ConfigCache* config, ConfigCache* memory_only_config, std::string section) : config_(config), memory_only_config_(memory_only_config), section_(std::move(section)) {} -bool Device::Exists() { - return config_->HasSection(section_); -} +bool Device::Exists() { return config_->HasSection(section_); } MutationEntry Device::RemoveFromConfig() { return MutationEntry::Remove(MutationEntry::PropertyType::NORMAL, section_); @@ -98,8 +95,8 @@ LeDevice Device::Le() { auto device_type = GetDeviceType(); log::assert_that(device_type.has_value(), "assert failed: device_type.has_value()"); log::assert_that( - device_type == DeviceType::LE || device_type == DeviceType::DUAL, - "assert failed: device_type == DeviceType::LE || device_type == DeviceType::DUAL"); + device_type == DeviceType::LE || device_type == DeviceType::DUAL, + "assert failed: device_type == DeviceType::LE || device_type == DeviceType::DUAL"); return LeDevice(config_, memory_only_config_, section_); } @@ -107,8 +104,8 @@ ClassicDevice Device::Classic() { auto device_type = GetDeviceType(); log::assert_that(device_type.has_value(), "assert failed: device_type.has_value()"); log::assert_that( - device_type == DeviceType::BR_EDR || device_type == DeviceType::DUAL, - "assert failed: device_type == DeviceType::BR_EDR || device_type == DeviceType::DUAL"); + device_type == DeviceType::BR_EDR || device_type == DeviceType::DUAL, + "assert failed: device_type == DeviceType::BR_EDR || device_type == DeviceType::DUAL"); return ClassicDevice(config_, memory_only_config_, section_); } @@ -119,9 +116,7 @@ hci::Address Device::GetAddress() const { return addr.value(); } -std::string Device::ToLogString() const { - return section_; -} +std::string Device::ToLogString() const { return section_; } } // namespace storage } // namespace bluetooth diff --git a/system/gd/storage/device.h b/system/gd/storage/device.h index 96c6a7dcd2d..03311d1504f 100644 --- a/system/gd/storage/device.h +++ b/system/gd/storage/device.h @@ -42,80 +42,94 @@ class ClassicDevice; // Make sure our macro is used #ifdef GENERATE_PROPERTY_GETTER_SETTER_REMOVER -static_assert(false, "GENERATE_PROPERTY_GETTER_SETTER_REMOVER() must be uniquely defined once in this file"); +static_assert( + false, + "GENERATE_PROPERTY_GETTER_SETTER_REMOVER() must be uniquely defined once in this file"); #endif -#define GENERATE_PROPERTY_GETTER_SETTER_REMOVER(NAME, RETURN_TYPE, PROPERTY_KEY) \ - public: \ - std::optional Get##NAME() const { \ - return ConfigCacheHelper(*config_).Get(section_, PROPERTY_KEY); \ - } \ - MutationEntry Set##NAME(const RETURN_TYPE& value) { \ - return MutationEntry::Set(MutationEntry::PropertyType::NORMAL, section_, PROPERTY_KEY, value); \ - } \ - MutationEntry Remove##NAME() { \ - return MutationEntry::Remove(MutationEntry::PropertyType::NORMAL, section_, PROPERTY_KEY); \ +#define GENERATE_PROPERTY_GETTER_SETTER_REMOVER(NAME, RETURN_TYPE, PROPERTY_KEY) \ +public: \ + std::optional Get##NAME() const { \ + return ConfigCacheHelper(*config_).Get(section_, PROPERTY_KEY); \ + } \ + MutationEntry Set##NAME(const RETURN_TYPE& value) { \ + return MutationEntry::Set(MutationEntry::PropertyType::NORMAL, section_, \ + PROPERTY_KEY, value); \ + } \ + MutationEntry Remove##NAME() { \ + return MutationEntry::Remove(MutationEntry::PropertyType::NORMAL, section_, PROPERTY_KEY); \ } // Make sure our macro is used #ifdef GENERATE_PROPERTY_GETTER_SETTER_REMOVER_WITH_CUSTOM_SETTER -static_assert( - false, "GENERATE_PROPERTY_GETTER_SETTER_REMOVER_WITH_CUSTOM_SETTER() must be uniquely defined once in this file"); +static_assert(false, + "GENERATE_PROPERTY_GETTER_SETTER_REMOVER_WITH_CUSTOM_SETTER() must be uniquely " + "defined once in this file"); #endif -// FUNC is bracketed function definition that takes a const RETURN_TYPE& value and return RETURN_TYPE -// e.g. { return value + 1; } -#define GENERATE_PROPERTY_GETTER_SETTER_REMOVER_WITH_CUSTOM_SETTER(NAME, RETURN_TYPE, PROPERTY_KEY, FUNC) \ - public: \ - std::optional Get##NAME() const { \ - return ConfigCacheHelper(*config_).Get(section_, PROPERTY_KEY); \ - } \ - MutationEntry Set##NAME(const RETURN_TYPE& value) { \ - auto new_value = [this](const RETURN_TYPE& value) -> RETURN_TYPE FUNC(value); \ - return MutationEntry::Set(MutationEntry::PropertyType::NORMAL, section_, PROPERTY_KEY, new_value); \ - } \ - MutationEntry Remove##NAME() { \ - return MutationEntry::Remove(MutationEntry::PropertyType::NORMAL, section_, PROPERTY_KEY); \ +// FUNC is bracketed function definition that takes a const RETURN_TYPE& value and return +// RETURN_TYPE e.g. { return value + 1; } +#define GENERATE_PROPERTY_GETTER_SETTER_REMOVER_WITH_CUSTOM_SETTER(NAME, RETURN_TYPE, \ + PROPERTY_KEY, FUNC) \ +public: \ + std::optional Get##NAME() const { \ + return ConfigCacheHelper(*config_).Get(section_, PROPERTY_KEY); \ + } \ + MutationEntry Set##NAME(const RETURN_TYPE& value) { \ + auto new_value = [this](const RETURN_TYPE& value) -> RETURN_TYPE FUNC(value); \ + return MutationEntry::Set(MutationEntry::PropertyType::NORMAL, section_, \ + PROPERTY_KEY, new_value); \ + } \ + MutationEntry Remove##NAME() { \ + return MutationEntry::Remove(MutationEntry::PropertyType::NORMAL, section_, PROPERTY_KEY); \ } // Make sure our macro is used #ifdef GENERATE_TEMP_PROPERTY_GETTER_SETTER_REMOVER -static_assert(false, "GENERATE_TEMP_PROPERTY_GETTER_SETTER_REMOVER() must be uniquely defined once in this file"); +static_assert(false, + "GENERATE_TEMP_PROPERTY_GETTER_SETTER_REMOVER() must be uniquely defined once in " + "this file"); #endif // Macro to generate tempoarary property that exists in memory only // It is subjected to a limit of 10,000 devices // It will be cleared when the stack is restarted -#define GENERATE_TEMP_PROPERTY_GETTER_SETTER_REMOVER(NAME, RETURN_TYPE, PROPERTY_KEY) \ - public: \ - std::optional GetTemp##NAME() const { \ - return ConfigCacheHelper(*memory_only_config_).Get(section_, PROPERTY_KEY); \ - } \ - MutationEntry SetTemp##NAME(const RETURN_TYPE& value) { \ - return MutationEntry::Set(MutationEntry::PropertyType::MEMORY_ONLY, section_, PROPERTY_KEY, value); \ - } \ - MutationEntry RemoveTemp##NAME() { \ - return MutationEntry::Remove(MutationEntry::PropertyType::MEMORY_ONLY, section_, PROPERTY_KEY); \ +#define GENERATE_TEMP_PROPERTY_GETTER_SETTER_REMOVER(NAME, RETURN_TYPE, PROPERTY_KEY) \ +public: \ + std::optional GetTemp##NAME() const { \ + return ConfigCacheHelper(*memory_only_config_).Get(section_, PROPERTY_KEY); \ + } \ + MutationEntry SetTemp##NAME(const RETURN_TYPE& value) { \ + return MutationEntry::Set(MutationEntry::PropertyType::MEMORY_ONLY, section_, \ + PROPERTY_KEY, value); \ + } \ + MutationEntry RemoveTemp##NAME() { \ + return MutationEntry::Remove(MutationEntry::PropertyType::MEMORY_ONLY, section_, \ + PROPERTY_KEY); \ } -// A think wrapper of device in ConfigCache, allowing easy access to various predefined properties of a Bluetooth device +// A think wrapper of device in ConfigCache, allowing easy access to various predefined properties +// of a Bluetooth device // // Device, LeDevice, and Classic device objects are fully copyable, comparable hashable // -// A newly created device does not have any DeviceType information and user can only read or write the values in this -// common Device abstraction layer. +// A newly created device does not have any DeviceType information and user can only read or write +// the values in this common Device abstraction layer. // -// As soon as a user determines the type of device, they should call SetDeviceType() to assign device to a type -// After that, Classic() or Le() will return interfaces that allows access to deeper layer properties +// As soon as a user determines the type of device, they should call SetDeviceType() to assign +// device to a type After that, Classic() or Le() will return interfaces that allows access to +// deeper layer properties class Device { - public: - enum ConfigKeyAddressType { LEGACY_KEY_ADDRESS, CLASSIC_ADDRESS, LE_IDENTITY_ADDRESS, LE_LEGACY_PSEUDO_ADDRESS }; - - Device( - ConfigCache* config, - ConfigCache* memory_only_config, - const hci::Address& key_address, - ConfigKeyAddressType key_address_type); +public: + enum ConfigKeyAddressType { + LEGACY_KEY_ADDRESS, + CLASSIC_ADDRESS, + LE_IDENTITY_ADDRESS, + LE_LEGACY_PSEUDO_ADDRESS + }; + + Device(ConfigCache* config, ConfigCache* memory_only_config, const hci::Address& key_address, + ConfigKeyAddressType key_address_type); Device(ConfigCache* config, ConfigCache* memory_only_config, std::string section); // for move @@ -128,11 +142,10 @@ class Device { // operators bool operator==(const Device& other) const { - return config_ == other.config_ && memory_only_config_ == other.memory_only_config_ && section_ == other.section_; - } - bool operator!=(const Device& other) const { - return !(*this == other); + return config_ == other.config_ && memory_only_config_ == other.memory_only_config_ && + section_ == other.section_; } + bool operator!=(const Device& other) const { return !(*this == other); } bool operator<(const Device& other) const { if (config_ != other.config_) { return config_ < other.config_; @@ -142,23 +155,19 @@ class Device { } return section_ < other.section_; } - bool operator>(const Device& rhs) const { - return (rhs < *this); - } - bool operator<=(const Device& rhs) const { - return !(*this > rhs); - } - bool operator>=(const Device& rhs) const { - return !(*this < rhs); - } + bool operator>(const Device& rhs) const { return rhs < *this; } + bool operator<=(const Device& rhs) const { return !(*this > rhs); } + bool operator>=(const Device& rhs) const { return !(*this < rhs); } - // A newly created Device object may not be backed by any properties in the ConfigCache, where Exists() will return - // false. As soon as a property value is added to the device. Exists() will become true. + // A newly created Device object may not be backed by any properties in the ConfigCache, where + // Exists() will return false. As soon as a property value is added to the device. Exists() will + // become true. bool Exists(); // Remove device and all its properties from config and memory-only temp config MutationEntry RemoveFromConfig(); - // Remove device and all its properties from memory-only temp config, but keep items in normal config + // Remove device and all its properties from memory-only temp config, but keep items in normal + // config MutationEntry RemoveFromTempConfig(); // Only works when GetDeviceType() returns BR_EDR or DUAL, will crash otherwise @@ -177,24 +186,24 @@ class Device { // Property names that correspond to a link key used in Bluetooth Classic and LE device static const std::unordered_set kLinkKeyProperties; - private: +private: ConfigCache* config_; ConfigCache* memory_only_config_; std::string section_; friend std::hash; - public: +public: // Macro generate getters, setters and removers GENERATE_PROPERTY_GETTER_SETTER_REMOVER(Name, std::string, BTIF_STORAGE_KEY_NAME); - GENERATE_PROPERTY_GETTER_SETTER_REMOVER( - ClassOfDevice, hci::ClassOfDevice, BTIF_STORAGE_KEY_DEV_CLASS); + GENERATE_PROPERTY_GETTER_SETTER_REMOVER(ClassOfDevice, hci::ClassOfDevice, + BTIF_STORAGE_KEY_DEV_CLASS); GENERATE_PROPERTY_GETTER_SETTER_REMOVER_WITH_CUSTOM_SETTER( - DeviceType, hci::DeviceType, BTIF_STORAGE_KEY_DEV_TYPE, { - return static_cast( - value | GetDeviceType().value_or(hci::DeviceType::UNKNOWN)); - }); - GENERATE_PROPERTY_GETTER_SETTER_REMOVER( - ServiceUuids, std::vector, BTIF_STORAGE_KEY_REMOTE_SERVICE); + DeviceType, hci::DeviceType, BTIF_STORAGE_KEY_DEV_TYPE, { + return static_cast(value | + GetDeviceType().value_or(hci::DeviceType::UNKNOWN)); + }); + GENERATE_PROPERTY_GETTER_SETTER_REMOVER(ServiceUuids, std::vector, + BTIF_STORAGE_KEY_REMOTE_SERVICE); GENERATE_PROPERTY_GETTER_SETTER_REMOVER(ManufacturerCode, uint16_t, "Manufacturer"); GENERATE_PROPERTY_GETTER_SETTER_REMOVER(LmpVersion, uint8_t, "LmpVer"); GENERATE_PROPERTY_GETTER_SETTER_REMOVER(LmpSubVersion, uint16_t, "LmpSubVer"); diff --git a/system/gd/storage/device_test.cc b/system/gd/storage/device_test.cc index 307f403e977..01754cfd7ee 100644 --- a/system/gd/storage/device_test.cc +++ b/system/gd/storage/device_test.cc @@ -40,20 +40,23 @@ TEST(DeviceTest, create_new_device_using_legacy_key_address) { // A new device Address address = {{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}; - Device device(&config, &memory_only_config, address, Device::ConfigKeyAddressType::LEGACY_KEY_ADDRESS); + Device device(&config, &memory_only_config, address, + Device::ConfigKeyAddressType::LEGACY_KEY_ADDRESS); ASSERT_FALSE(device.Exists()); ASSERT_FALSE(device.GetClassOfDevice()); // An existing device Address address2 = {{0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff}}; config.SetProperty(address2.ToString(), "Name", "hello"); - Device device2(&config, &memory_only_config, address2, Device::ConfigKeyAddressType::LEGACY_KEY_ADDRESS); + Device device2(&config, &memory_only_config, address2, + Device::ConfigKeyAddressType::LEGACY_KEY_ADDRESS); ASSERT_TRUE(device2.Exists()); ASSERT_THAT(device2.GetName(), Optional(StrEq("hello"))); // devices with the same key address and config pointer are the same Address address3 = {{0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff}}; - Device device3(&config, &memory_only_config, address3, Device::ConfigKeyAddressType::LEGACY_KEY_ADDRESS); + Device device3(&config, &memory_only_config, address3, + Device::ConfigKeyAddressType::LEGACY_KEY_ADDRESS); ASSERT_EQ(device2, device3); ASSERT_TRUE(device3.Exists()); ASSERT_THAT(device3.GetName(), Optional(StrEq("hello"))); @@ -65,20 +68,23 @@ TEST(DeviceTest, create_new_device_using_classic_address) { // A new device Address address = {{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}; - Device device(&config, &memory_only_config, address, Device::ConfigKeyAddressType::CLASSIC_ADDRESS); + Device device(&config, &memory_only_config, address, + Device::ConfigKeyAddressType::CLASSIC_ADDRESS); ASSERT_FALSE(device.Exists()); ASSERT_FALSE(device.GetClassOfDevice()); // An existing device Address address2 = {{0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff}}; config.SetProperty(address2.ToString(), "Name", "hello"); - Device device2(&config, &memory_only_config, address2, Device::ConfigKeyAddressType::CLASSIC_ADDRESS); + Device device2(&config, &memory_only_config, address2, + Device::ConfigKeyAddressType::CLASSIC_ADDRESS); ASSERT_TRUE(device2.Exists()); ASSERT_THAT(device2.GetName(), Optional(StrEq("hello"))); // devices with the same key address and config pointer are the same Address address3 = {{0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff}}; - Device device3(&config, &memory_only_config, address3, Device::ConfigKeyAddressType::CLASSIC_ADDRESS); + Device device3(&config, &memory_only_config, address3, + Device::ConfigKeyAddressType::CLASSIC_ADDRESS); ASSERT_EQ(device2, device3); ASSERT_TRUE(device3.Exists()); ASSERT_THAT(device3.GetName(), Optional(StrEq("hello"))); @@ -90,7 +96,8 @@ TEST(DeviceTest, create_new_device_using_le_identity_address) { // A new device Address address = {{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}; - Device device(&config, &memory_only_config, address, Device::ConfigKeyAddressType::LE_IDENTITY_ADDRESS); + Device device(&config, &memory_only_config, address, + Device::ConfigKeyAddressType::LE_IDENTITY_ADDRESS); ASSERT_FALSE(device.Exists()); ASSERT_FALSE(device.GetClassOfDevice()); @@ -99,9 +106,11 @@ TEST(DeviceTest, create_new_device_using_le_identity_address) { Address le_identity_address = {{0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff}}; // first seen address used as key config.SetProperty(pseudo_first_seen_address.ToString(), "Name", "hello"); - config.SetProperty(pseudo_first_seen_address.ToString(), "LeIdentityAddr", le_identity_address.ToString()); + config.SetProperty(pseudo_first_seen_address.ToString(), "LeIdentityAddr", + le_identity_address.ToString()); config.SetProperty(address.ToString(), "Name", "world"); - Device device2(&config, &memory_only_config, le_identity_address, Device::ConfigKeyAddressType::LE_IDENTITY_ADDRESS); + Device device2(&config, &memory_only_config, le_identity_address, + Device::ConfigKeyAddressType::LE_IDENTITY_ADDRESS); ASSERT_TRUE(device2.Exists()); ASSERT_THAT(device2.GetName(), Optional(StrEq("hello"))); } @@ -110,7 +119,8 @@ TEST(DeviceTest, set_property) { ConfigCache config(10, Device::kLinkKeyProperties); ConfigCache memory_only_config(10, {}); Address address = {{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}; - Device device(&config, &memory_only_config, address, Device::ConfigKeyAddressType::LEGACY_KEY_ADDRESS); + Device device(&config, &memory_only_config, address, + Device::ConfigKeyAddressType::LEGACY_KEY_ADDRESS); ASSERT_FALSE(device.Exists()); ASSERT_FALSE(device.GetName()); Mutation mutation(&config, &memory_only_config); @@ -124,7 +134,8 @@ TEST(DeviceTest, set_device_type) { ConfigCache config(10, Device::kLinkKeyProperties); ConfigCache memory_only_config(10, {}); Address address = {{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}; - Device device(&config, &memory_only_config, address, Device::ConfigKeyAddressType::LEGACY_KEY_ADDRESS); + Device device(&config, &memory_only_config, address, + Device::ConfigKeyAddressType::LEGACY_KEY_ADDRESS); ASSERT_FALSE(device.Exists()); ASSERT_FALSE(device.GetName()); { @@ -145,7 +156,8 @@ TEST(DeviceTest, get_le_and_bredr) { ConfigCache config(10, Device::kLinkKeyProperties); ConfigCache memory_only_config(10, {}); Address address = {{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}; - Device device(&config, &memory_only_config, address, Device::ConfigKeyAddressType::LEGACY_KEY_ADDRESS); + Device device(&config, &memory_only_config, address, + Device::ConfigKeyAddressType::LEGACY_KEY_ADDRESS); ASSERT_FALSE(device.GetDeviceType()); ASSERT_DEATH({ device.Le(); }, MatchesRegex(".*")); ASSERT_DEATH({ device.Classic(); }, MatchesRegex(".*")); @@ -199,19 +211,23 @@ TEST(DeviceTest, equality_test) { ConfigCache config(10, Device::kLinkKeyProperties); ConfigCache memory_only_config(10, {}); Address address = {{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}}; - Device device1(&config, &memory_only_config, address, Device::ConfigKeyAddressType::LEGACY_KEY_ADDRESS); - Device device2(&config, &memory_only_config, address, Device::ConfigKeyAddressType::LEGACY_KEY_ADDRESS); + Device device1(&config, &memory_only_config, address, + Device::ConfigKeyAddressType::LEGACY_KEY_ADDRESS); + Device device2(&config, &memory_only_config, address, + Device::ConfigKeyAddressType::LEGACY_KEY_ADDRESS); ASSERT_EQ(device1, device2); // different config cache ConfigCache config_alt(10, Device::kLinkKeyProperties); ConfigCache memory_only_config_alt(10, {}); - Device device3(&config_alt, &memory_only_config_alt, address, Device::ConfigKeyAddressType::LEGACY_KEY_ADDRESS); + Device device3(&config_alt, &memory_only_config_alt, address, + Device::ConfigKeyAddressType::LEGACY_KEY_ADDRESS); ASSERT_NE(device1, device3); // different address Address address_alt = {{0x01, 0x02, 0x03, 0x04, 0x05, 0x07}}; - Device device4(&config, &memory_only_config, address_alt, Device::ConfigKeyAddressType::LEGACY_KEY_ADDRESS); + Device device4(&config, &memory_only_config, address_alt, + Device::ConfigKeyAddressType::LEGACY_KEY_ADDRESS); ASSERT_NE(device1, device4); Device device5 = std::move(device2); @@ -227,7 +243,8 @@ TEST(DeviceTest, remove_config_test) { ConfigCache memory_only_config(10, {}); Address address = {{0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff}}; config.SetProperty(address.ToString(), "Name", "hello"); - Device device(&config, &memory_only_config, address, Device::ConfigKeyAddressType::LEGACY_KEY_ADDRESS); + Device device(&config, &memory_only_config, address, + Device::ConfigKeyAddressType::LEGACY_KEY_ADDRESS); ASSERT_TRUE(device.Exists()); ASSERT_THAT(device.GetName(), Optional(StrEq("hello"))); Mutation mutation(&config, &memory_only_config); diff --git a/system/gd/storage/le_device.cc b/system/gd/storage/le_device.cc index d26a50344d9..4abf3c470cd 100644 --- a/system/gd/storage/le_device.cc +++ b/system/gd/storage/le_device.cc @@ -31,18 +31,14 @@ const std::string kLeIdentityAddressKey = "LeIdentityAddr"; } // namespace const std::unordered_set LeDevice::kLinkKeyProperties = { - "LE_KEY_PENC", "LE_KEY_PID", "LE_KEY_PCSRK", "LE_KEY_LENC", "LE_KEY_LCSRK"}; + "LE_KEY_PENC", "LE_KEY_PID", "LE_KEY_PCSRK", "LE_KEY_LENC", "LE_KEY_LCSRK"}; LeDevice::LeDevice(ConfigCache* config, ConfigCache* memory_only_config, std::string section) : config_(config), memory_only_config_(memory_only_config), section_(std::move(section)) {} -Device LeDevice::Parent() { - return Device(config_, memory_only_config_, section_); -} +Device LeDevice::Parent() { return Device(config_, memory_only_config_, section_); } -std::string LeDevice::ToLogString() const { - return section_; -} +std::string LeDevice::ToLogString() const { return section_; } bool LeDevice::IsPaired() const { // This first check is here only to speed up the checking process diff --git a/system/gd/storage/le_device.h b/system/gd/storage/le_device.h index e855e37e04f..9d5dd0132bf 100644 --- a/system/gd/storage/le_device.h +++ b/system/gd/storage/le_device.h @@ -27,7 +27,7 @@ namespace bluetooth { namespace storage { class LeDevice { - public: +public: LeDevice(ConfigCache* config, ConfigCache* memory_only_config, std::string section); // for move @@ -40,11 +40,10 @@ class LeDevice { // operators bool operator==(const LeDevice& other) const { - return config_ == other.config_ && memory_only_config_ == other.memory_only_config_ && section_ == other.section_; - } - bool operator!=(const LeDevice& other) const { - return !(*this == other); + return config_ == other.config_ && memory_only_config_ == other.memory_only_config_ && + section_ == other.section_; } + bool operator!=(const LeDevice& other) const { return !(*this == other); } bool operator<(const LeDevice& other) const { if (config_ != other.config_) { return config_ < other.config_; @@ -54,15 +53,9 @@ class LeDevice { } return section_ < other.section_; } - bool operator>(const LeDevice& rhs) const { - return (rhs < *this); - } - bool operator<=(const LeDevice& rhs) const { - return !(*this > rhs); - } - bool operator>=(const LeDevice& rhs) const { - return !(*this < rhs); - } + bool operator>(const LeDevice& rhs) const { return rhs < *this; } + bool operator<=(const LeDevice& rhs) const { return !(*this > rhs); } + bool operator>=(const LeDevice& rhs) const { return !(*this < rhs); } // Get the parent device Device Parent(); @@ -76,24 +69,24 @@ class LeDevice { // Property names that correspond to a link key used in Bluetooth LE device static const std::unordered_set kLinkKeyProperties; - private: +private: ConfigCache* config_; ConfigCache* memory_only_config_; std::string section_; friend std::hash; - public: +public: // Get LE address type of the key address - GENERATE_PROPERTY_GETTER_SETTER_REMOVER( - AddressType, hci::AddressType, BTIF_STORAGE_KEY_ADDR_TYPE); + GENERATE_PROPERTY_GETTER_SETTER_REMOVER(AddressType, hci::AddressType, + BTIF_STORAGE_KEY_ADDR_TYPE); // IRK + Identity Address Type + Identity Address GENERATE_PROPERTY_GETTER_SETTER_REMOVER(PeerId, std::string, BTIF_STORAGE_KEY_LE_KEY_PID); // LTK + RAND + EDIV + Security Level + Key Length - GENERATE_PROPERTY_GETTER_SETTER_REMOVER( - PeerEncryptionKeys, std::string, BTIF_STORAGE_KEY_LE_KEY_PENC); + GENERATE_PROPERTY_GETTER_SETTER_REMOVER(PeerEncryptionKeys, std::string, + BTIF_STORAGE_KEY_LE_KEY_PENC); // counter + CSRK (connection signature resolving key) + security level - GENERATE_PROPERTY_GETTER_SETTER_REMOVER( - PeerSignatureResolvingKeys, std::string, BTIF_STORAGE_KEY_LE_KEY_PCSRK); + GENERATE_PROPERTY_GETTER_SETTER_REMOVER(PeerSignatureResolvingKeys, std::string, + BTIF_STORAGE_KEY_LE_KEY_PCSRK); GENERATE_PROPERTY_GETTER_SETTER_REMOVER(LegacyPseudoAddress, hci::Address, "LeLegacyPseudoAddr"); }; diff --git a/system/gd/storage/le_device_test.cc b/system/gd/storage/le_device_test.cc index 26413568e71..b18b4e2fb74 100644 --- a/system/gd/storage/le_device_test.cc +++ b/system/gd/storage/le_device_test.cc @@ -14,13 +14,13 @@ * limitations under the License. */ -#include "storage/device.h" +#include "storage/le_device.h" #include #include #include "storage/classic_device.h" -#include "storage/le_device.h" +#include "storage/device.h" #include "storage/mutation.h" using bluetooth::hci::Address; @@ -90,7 +90,8 @@ TEST(LeDeviceTest, operator_less_than) { bluetooth::hci::Address larger_address = {{0x01, 0x02, 0x03, 0x04, 0x05, 0x07}}; { - LeDevice device1(smaller_config_ptr, smaller_memory_only_config_ptr, smaller_address.ToString()); + LeDevice device1(smaller_config_ptr, smaller_memory_only_config_ptr, + smaller_address.ToString()); LeDevice device2(larger_config_ptr, larger_memory_only_config_ptr, larger_address.ToString()); ASSERT_TRUE(device1 < device2); } @@ -121,7 +122,8 @@ TEST(LeDeviceTest, operator_less_than) { { LeDevice device1(larger_config_ptr, larger_memory_only_config_ptr, larger_address.ToString()); - LeDevice device2(smaller_config_ptr, smaller_memory_only_config_ptr, smaller_address.ToString()); + LeDevice device2(smaller_config_ptr, smaller_memory_only_config_ptr, + smaller_address.ToString()); ASSERT_FALSE(device1 < device2); } @@ -138,25 +140,29 @@ TEST(LeDeviceTest, operator_less_than) { } { - LeDevice device1(smaller_config_ptr, smaller_memory_only_config_ptr, smaller_address.ToString()); + LeDevice device1(smaller_config_ptr, smaller_memory_only_config_ptr, + smaller_address.ToString()); LeDevice device2(smaller_config_ptr, larger_memory_only_config_ptr, smaller_address.ToString()); ASSERT_TRUE(device1 < device2); } { - LeDevice device1(smaller_config_ptr, smaller_memory_only_config_ptr, smaller_address.ToString()); + LeDevice device1(smaller_config_ptr, smaller_memory_only_config_ptr, + smaller_address.ToString()); LeDevice device2(smaller_config_ptr, smaller_memory_only_config_ptr, larger_address.ToString()); ASSERT_TRUE(device1 < device2); } { - LeDevice device1(smaller_config_ptr, smaller_memory_only_config_ptr, smaller_address.ToString()); + LeDevice device1(smaller_config_ptr, smaller_memory_only_config_ptr, + smaller_address.ToString()); LeDevice device2(larger_config_ptr, smaller_memory_only_config_ptr, smaller_address.ToString()); ASSERT_TRUE(device1 < device2); } { - LeDevice device1(smaller_config_ptr, smaller_memory_only_config_ptr, smaller_address.ToString()); + LeDevice device1(smaller_config_ptr, smaller_memory_only_config_ptr, + smaller_address.ToString()); LeDevice device2(smaller_config_ptr, larger_memory_only_config_ptr, larger_address.ToString()); ASSERT_TRUE(device1 < device2); } diff --git a/system/gd/storage/legacy_config_file.cc b/system/gd/storage/legacy_config_file.cc index e5663610833..a64be377ea2 100644 --- a/system/gd/storage/legacy_config_file.cc +++ b/system/gd/storage/legacy_config_file.cc @@ -32,7 +32,7 @@ namespace storage { LegacyConfigFile::LegacyConfigFile(std::string path) : path_(std::move(path)) { log::assert_that(!path_.empty(), "assert failed: !path_.empty()"); -}; +} std::optional LegacyConfigFile::Read(size_t temp_devices_capacity) { log::assert_that(!path_.empty(), "assert failed: !path_.empty()"); diff --git a/system/gd/storage/legacy_config_file.h b/system/gd/storage/legacy_config_file.h index 2a319c93b92..38375a03f34 100644 --- a/system/gd/storage/legacy_config_file.h +++ b/system/gd/storage/legacy_config_file.h @@ -25,16 +25,14 @@ namespace storage { // similar to INI class LegacyConfigFile { - public: - static LegacyConfigFile FromPath(std::string path) { - return LegacyConfigFile(std::move(path)); - } +public: + static LegacyConfigFile FromPath(std::string path) { return LegacyConfigFile(std::move(path)); } explicit LegacyConfigFile(std::string path); std::optional Read(size_t temp_devices_capacity); bool Write(const ConfigCache& cache); bool Delete(); - private: +private: std::string path_; }; diff --git a/system/gd/storage/legacy_config_file_test.cc b/system/gd/storage/legacy_config_file_test.cc index 430dbd403d9..6cec332d5c3 100644 --- a/system/gd/storage/legacy_config_file_test.cc +++ b/system/gd/storage/legacy_config_file_test.cc @@ -53,31 +53,32 @@ TEST(LegacyConfigFileTest, write_and_read_loop_back_test) { EXPECT_EQ(config, *config_read); EXPECT_THAT(config_read->GetPersistentSections(), ElementsAre("CC:DD:EE:FF:00:11")); EXPECT_THAT(config_read->GetProperty("A", "B"), Optional(StrEq("C"))); - EXPECT_THAT(config_read->GetProperty("CC:DD:EE:FF:00:11", "LinkKey"), Optional(StrEq("AABBAABBCCDDEE"))); + EXPECT_THAT(config_read->GetProperty("CC:DD:EE:FF:00:11", "LinkKey"), + Optional(StrEq("AABBAABBCCDDEE"))); EXPECT_TRUE(std::filesystem::remove(temp_config)); } static const std::string kReadTestConfig = - "[Info]\n" - "FileSource = Empty\n" - "TimeCreated = 2020-05-20 01:20:56\n" - "\n" - "[Metrics]\n" - "Salt256Bit = 1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef\n" - "\n" - "[Adapter]\n" - "Address = 01:02:03:ab:cd:ef\n" - "LE_LOCAL_KEY_IRK = fedcba0987654321fedcba0987654321\n" - "LE_LOCAL_KEY_IR = fedcba0987654321fedcba0987654322\n" - "LE_LOCAL_KEY_DHK = fedcba0987654321fedcba0987654323\n" - "LE_LOCAL_KEY_ER = fedcba0987654321fedcba0987654324\n" - "ScanMode = 2\n" - "DiscoveryTimeout = 120\n" - "\n" - "[01:02:03:ab:cd:ea]\n" - "name = hello world\n" - "LinkKey = fedcba0987654321fedcba0987654328\n"; + "[Info]\n" + "FileSource = Empty\n" + "TimeCreated = 2020-05-20 01:20:56\n" + "\n" + "[Metrics]\n" + "Salt256Bit = 1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef\n" + "\n" + "[Adapter]\n" + "Address = 01:02:03:ab:cd:ef\n" + "LE_LOCAL_KEY_IRK = fedcba0987654321fedcba0987654321\n" + "LE_LOCAL_KEY_IR = fedcba0987654321fedcba0987654322\n" + "LE_LOCAL_KEY_DHK = fedcba0987654321fedcba0987654323\n" + "LE_LOCAL_KEY_ER = fedcba0987654321fedcba0987654324\n" + "ScanMode = 2\n" + "DiscoveryTimeout = 120\n" + "\n" + "[01:02:03:ab:cd:ea]\n" + "name = hello world\n" + "LinkKey = fedcba0987654321fedcba0987654328\n"; TEST(LegacyConfigFileTest, read_test) { auto temp_dir = std::filesystem::temp_directory_path(); @@ -89,24 +90,24 @@ TEST(LegacyConfigFileTest, read_test) { EXPECT_THAT(config_read->GetPersistentSections(), ElementsAre("01:02:03:ab:cd:ea")); EXPECT_THAT(config_read->GetProperty("Info", "FileSource"), Optional(StrEq("Empty"))); EXPECT_THAT(config_read->GetProperty("Info", "FileSource"), Optional(StrEq("Empty"))); - EXPECT_THAT( - config_read->GetProperty("01:02:03:ab:cd:ea", "LinkKey"), Optional(StrEq("fedcba0987654321fedcba0987654328"))); + EXPECT_THAT(config_read->GetProperty("01:02:03:ab:cd:ea", "LinkKey"), + Optional(StrEq("fedcba0987654321fedcba0987654328"))); EXPECT_TRUE(std::filesystem::remove(temp_config)); } static const std::string kWriteTestConfig = - "[Info]\n" - "FileSource = Empty\n" - "TimeCreated = \n" - "\n" - "[Adapter]\n" - "Address = 01:02:03:ab:cd:ef\n" - "\n" - "[01:02:03:ab:cd:ea]\n" - "Name = hello world\n" - "LinkKey = fedcba0987654321fedcba0987654328\n" - "\n"; + "[Info]\n" + "FileSource = Empty\n" + "TimeCreated = \n" + "\n" + "[Adapter]\n" + "Address = 01:02:03:ab:cd:ef\n" + "\n" + "[01:02:03:ab:cd:ea]\n" + "Name = hello world\n" + "LinkKey = fedcba0987654321fedcba0987654328\n" + "\n"; TEST(LegacyConfigFileTest, write_test) { auto temp_dir = std::filesystem::temp_directory_path(); @@ -117,8 +118,8 @@ TEST(LegacyConfigFileTest, write_test) { config.SetProperty("Info", "TimeCreated", ""); config.SetProperty(BTIF_STORAGE_SECTION_ADAPTER, BTIF_STORAGE_KEY_ADDRESS, "01:02:03:ab:cd:ef"); config.SetProperty("01:02:03:ab:cd:ea", BTIF_STORAGE_KEY_NAME, "hello world"); - config.SetProperty( - "01:02:03:ab:cd:ea", BTIF_STORAGE_KEY_LINK_KEY, "fedcba0987654321fedcba0987654328"); + config.SetProperty("01:02:03:ab:cd:ea", BTIF_STORAGE_KEY_LINK_KEY, + "fedcba0987654321fedcba0987654328"); EXPECT_TRUE(LegacyConfigFile::FromPath(temp_config.string()).Write(config)); EXPECT_THAT(ReadSmallFile(temp_config.string()), Optional(StrEq(kWriteTestConfig))); @@ -127,7 +128,7 @@ TEST(LegacyConfigFileTest, write_test) { } static const std::string kConfigWithDuplicateSectionAndKey = - " \n\ + " \n\ first_key=value \n\ \n\ # Device ID (DID) configuration \n\ @@ -177,7 +178,8 @@ TEST(LegacyConfigFileTest, duplicate_section_and_key_test) { auto config_read = LegacyConfigFile::FromPath(temp_config.string()).Read(100); ASSERT_TRUE(config_read); - EXPECT_THAT(config_read->GetProperty(ConfigCache::kDefaultSectionName, "first_key"), Optional(StrEq("value"))); + EXPECT_THAT(config_read->GetProperty(ConfigCache::kDefaultSectionName, "first_key"), + Optional(StrEq("value"))); // All sections with the same name merge into the same key-value pair EXPECT_THAT(config_read->GetProperty("DID", "primaryRecord"), Optional(StrEq("true"))); // When keys are repeated, the later one wins diff --git a/system/gd/storage/mutation.cc b/system/gd/storage/mutation.cc index c8b3260fa91..c0dacdcc802 100644 --- a/system/gd/storage/mutation.cc +++ b/system/gd/storage/mutation.cc @@ -39,7 +39,8 @@ void Mutation::Add(MutationEntry entry) { case MutationEntry::PropertyType::MEMORY_ONLY: memory_only_config_entries_.emplace(std::move(entry)); break; - // do not write a default case so that when a new enum is defined, compilation would fail automatically + // do not write a default case so that when a new enum is defined, compilation would fail + // automatically } } diff --git a/system/gd/storage/mutation.h b/system/gd/storage/mutation.h index b2072f910e2..ddaf5804f27 100644 --- a/system/gd/storage/mutation.h +++ b/system/gd/storage/mutation.h @@ -25,13 +25,13 @@ namespace bluetooth { namespace storage { class Mutation { - public: +public: Mutation(ConfigCache* config, ConfigCache* memory_only_config); void Add(MutationEntry entry); void Commit(); friend ConfigCache; - private: +private: ConfigCache* config_; ConfigCache* memory_only_config_; std::queue normal_config_entries_; diff --git a/system/gd/storage/mutation_entry.cc b/system/gd/storage/mutation_entry.cc index 14f71edcc45..6d078d60a88 100644 --- a/system/gd/storage/mutation_entry.cc +++ b/system/gd/storage/mutation_entry.cc @@ -21,12 +21,9 @@ namespace bluetooth { namespace storage { -MutationEntry::MutationEntry( - EntryType entry_type_param, - PropertyType property_type_param, - std::string section_param, - std::string property_param, - std::string value_param) +MutationEntry::MutationEntry(EntryType entry_type_param, PropertyType property_type_param, + std::string section_param, std::string property_param, + std::string value_param) : entry_type(entry_type_param), property_type(property_type_param), section(std::move(section_param)), @@ -40,13 +37,14 @@ MutationEntry::MutationEntry( break; case EntryType::REMOVE_PROPERTY: log::assert_that(!section.empty(), "section cannot be empty for EntryType::REMOVE_PROPERTY"); - log::assert_that( - !property.empty(), "property cannot be empty for EntryType::REMOVE_PROPERTY"); + log::assert_that(!property.empty(), + "property cannot be empty for EntryType::REMOVE_PROPERTY"); break; case EntryType::REMOVE_SECTION: log::assert_that(!section.empty(), "section cannot be empty for EntryType::REMOVE_SECTION"); break; - // do not write a default case so that when a new enum is defined, compilation would fail automatically + // do not write a default case so that when a new enum is defined, compilation would fail + // automatically } } diff --git a/system/gd/storage/mutation_entry.h b/system/gd/storage/mutation_entry.h index fcb902c77fd..120b99ea20d 100644 --- a/system/gd/storage/mutation_entry.h +++ b/system/gd/storage/mutation_entry.h @@ -26,92 +26,88 @@ namespace bluetooth { namespace storage { class MutationEntry { - public: +public: enum EntryType { SET, REMOVE_PROPERTY, REMOVE_SECTION }; enum PropertyType { NORMAL, MEMORY_ONLY }; template , int>::type = 0> - static MutationEntry Set( - PropertyType property_type, std::string section_param, std::string property_param, T value_param) { - return MutationEntry::Set( - property_type, std::move(section_param), std::move(property_param), std::to_string(value_param)); + static MutationEntry Set(PropertyType property_type, std::string section_param, + std::string property_param, T value_param) { + return MutationEntry::Set(property_type, std::move(section_param), std::move(property_param), + std::to_string(value_param)); } template , int>::type = 0> - static MutationEntry Set( - PropertyType property_type, std::string section_param, std::string property_param, T value_param) { + static MutationEntry Set(PropertyType property_type, std::string section_param, + std::string property_param, T value_param) { using EnumUnderlyingType = typename std::underlying_type_t; - return MutationEntry::Set( - property_type, - std::move(section_param), - std::move(property_param), - static_cast(value_param)); + return MutationEntry::Set(property_type, std::move(section_param), + std::move(property_param), + static_cast(value_param)); } template , int>::type = 0> - static MutationEntry Set( - PropertyType property_type, std::string section_param, std::string property_param, T value_param) { - return MutationEntry::Set( - property_type, std::move(section_param), std::move(property_param), common::ToString(value_param)); + static MutationEntry Set(PropertyType property_type, std::string section_param, + std::string property_param, T value_param) { + return MutationEntry::Set(property_type, std::move(section_param), std::move(property_param), + common::ToString(value_param)); } template , int>::type = 0> - static MutationEntry Set( - PropertyType property_type, std::string section_param, std::string property_param, T value_param) { - return MutationEntry::Set( - property_type, std::move(section_param), std::move(property_param), std::move(value_param)); + static MutationEntry Set(PropertyType property_type, std::string section_param, + std::string property_param, T value_param) { + return MutationEntry::Set(property_type, std::move(section_param), std::move(property_param), + std::move(value_param)); } - template , T>, int>::type = 0> - static MutationEntry Set( - PropertyType property_type, std::string section_param, std::string property_param, const T& value_param) { - return MutationEntry::Set( - property_type, std::move(section_param), std::move(property_param), value_param.ToLegacyConfigString()); + template , T>, int>::type = 0> + static MutationEntry Set(PropertyType property_type, std::string section_param, + std::string property_param, const T& value_param) { + return MutationEntry::Set(property_type, std::move(section_param), std::move(property_param), + value_param.ToLegacyConfigString()); } - template < - typename T, - typename std::enable_if< - bluetooth::common::is_specialization_of::value && - std::is_base_of_v, typename T::value_type>, - int>::type = 0> - static MutationEntry Set( - PropertyType property_type, std::string section_param, std::string property_param, const T& value_param) { + template ::value && + std::is_base_of_v, + typename T::value_type>, + int>::type = 0> + static MutationEntry Set(PropertyType property_type, std::string section_param, + std::string property_param, const T& value_param) { std::vector str_values; str_values.reserve(value_param.size()); for (const auto& v : value_param) { str_values.push_back(v.ToLegacyConfigString()); } - return MutationEntry::Set( - property_type, std::move(section_param), std::move(property_param), common::StringJoin(str_values, " ")); + return MutationEntry::Set(property_type, std::move(section_param), std::move(property_param), + common::StringJoin(str_values, " ")); } - static MutationEntry Set( - PropertyType property_type, std::string section_param, std::string property_param, std::string value_param) { - return MutationEntry( - EntryType::SET, property_type, std::move(section_param), std::move(property_param), std::move(value_param)); + static MutationEntry Set(PropertyType property_type, std::string section_param, + std::string property_param, std::string value_param) { + return MutationEntry(EntryType::SET, property_type, std::move(section_param), + std::move(property_param), std::move(value_param)); } static MutationEntry Remove(PropertyType property_type, std::string section_param) { return MutationEntry(EntryType::REMOVE_SECTION, property_type, std::move(section_param)); } - static MutationEntry Remove(PropertyType property_type, std::string section_param, std::string property_param) { - return MutationEntry( - EntryType::REMOVE_PROPERTY, property_type, std::move(section_param), std::move(property_param)); + static MutationEntry Remove(PropertyType property_type, std::string section_param, + std::string property_param) { + return MutationEntry(EntryType::REMOVE_PROPERTY, property_type, std::move(section_param), + std::move(property_param)); } - private: +private: friend class ConfigCache; friend class Mutation; - MutationEntry( - EntryType entry_type_param, - PropertyType property_type_param, - std::string section_param, - std::string property_param = "", - std::string value_param = ""); + MutationEntry(EntryType entry_type_param, PropertyType property_type_param, + std::string section_param, std::string property_param = "", + std::string value_param = ""); EntryType entry_type; PropertyType property_type; diff --git a/system/gd/storage/mutation_test.cc b/system/gd/storage/mutation_test.cc index cd72c59b184..9a0dada7908 100644 --- a/system/gd/storage/mutation_test.cc +++ b/system/gd/storage/mutation_test.cc @@ -37,14 +37,18 @@ TEST(MutationTest, simple_sequence_test) { config.SetProperty("AA:BB:CC:DD:EE:FF", "C", "D"); config.SetProperty("CC:DD:EE:FF:00:11", "LinkKey", "AABBAABBCCDDEE"); Mutation mutation(&config, &memory_only_config); - mutation.Add(MutationEntry::Set(MutationEntry::PropertyType::NORMAL, "AA:BB:CC:DD:EE:FF", "LinkKey", "CCDDEEFFGG")); - mutation.Add(MutationEntry::Remove(MutationEntry::PropertyType::NORMAL, "AA:BB:CC:DD:EE:FF", "LinkKey")); + mutation.Add(MutationEntry::Set(MutationEntry::PropertyType::NORMAL, "AA:BB:CC:DD:EE:FF", + "LinkKey", "CCDDEEFFGG")); + mutation.Add(MutationEntry::Remove(MutationEntry::PropertyType::NORMAL, "AA:BB:CC:DD:EE:FF", + "LinkKey")); mutation.Commit(); ASSERT_THAT(config.GetPersistentSections(), ElementsAre("CC:DD:EE:FF:00:11")); Mutation mutation2(&config, &memory_only_config); - mutation2.Add(MutationEntry::Set(MutationEntry::PropertyType::NORMAL, "AA:BB:CC:DD:EE:FF", "LinkKey", "CCDDEEFFGG")); + mutation2.Add(MutationEntry::Set(MutationEntry::PropertyType::NORMAL, "AA:BB:CC:DD:EE:FF", + "LinkKey", "CCDDEEFFGG")); mutation2.Commit(); - ASSERT_THAT(config.GetPersistentSections(), ElementsAre("CC:DD:EE:FF:00:11", "AA:BB:CC:DD:EE:FF")); + ASSERT_THAT(config.GetPersistentSections(), + ElementsAre("CC:DD:EE:FF:00:11", "AA:BB:CC:DD:EE:FF")); } TEST(MutationTest, remove_property_and_section) { diff --git a/system/gd/storage/serializable.h b/system/gd/storage/serializable.h index 3a7dd93e4cb..263539d822e 100644 --- a/system/gd/storage/serializable.h +++ b/system/gd/storage/serializable.h @@ -26,7 +26,7 @@ namespace storage { // A config serializable module template class Serializable { - public: +public: Serializable() = default; virtual ~Serializable() = default; @@ -36,9 +36,7 @@ class Serializable { virtual std::string ToString() const = 0; // T must implement FromString(const std::string&), otherwise, it will fail to compile // Parse string from GD stack - static std::optional FromString(const std::string& str) { - return T::FromString(str); - } + static std::optional FromString(const std::string& str) { return T::FromString(str); } // Legacy handling diff --git a/system/gd/storage/storage_module.cc b/system/gd/storage/storage_module.cc index 00f26b6b42a..9e5c3ecaf01 100644 --- a/system/gd/storage/storage_module.cc +++ b/system/gd/storage/storage_module.cc @@ -45,7 +45,8 @@ using os::Handler; static const std::string kFactoryResetProperty = "persist.bluetooth.factoryreset"; static const size_t kDefaultTempDeviceCapacity = 10000; -// Save config whenever there is a change, but delay it by this value so that burst config change won't overwhelm disk +// Save config whenever there is a change, but delay it by this value so that burst config change +// won't overwhelm disk static const std::chrono::milliseconds kDefaultConfigSaveDelay = std::chrono::milliseconds(3000); // Writing a config to disk takes a minimum 10 ms on a decent x86_64 machine // The config saving delay must be bigger than this value to avoid overwhelming the disk @@ -61,24 +62,21 @@ const std::string StorageModule::kTimeCreatedFormat = "%Y-%m-%d %H:%M:%S"; const std::string StorageModule::kAdapterSection = BTIF_STORAGE_SECTION_ADAPTER; -StorageModule::StorageModule( - std::string config_file_path, - std::chrono::milliseconds config_save_delay, - size_t temp_devices_capacity, - bool is_restricted_mode, - bool is_single_user_mode) +StorageModule::StorageModule(std::string config_file_path, + std::chrono::milliseconds config_save_delay, + size_t temp_devices_capacity, bool is_restricted_mode, + bool is_single_user_mode) : config_file_path_(std::move(config_file_path)), config_save_delay_(config_save_delay), temp_devices_capacity_(temp_devices_capacity), is_restricted_mode_(is_restricted_mode), is_single_user_mode_(is_single_user_mode) { - log::assert_that( - config_save_delay > kMinConfigSaveDelay, - "Config save delay of {} ms is not enough, must be at least {} ms to avoid overwhelming the " - "disk", - config_save_delay_.count(), - kMinConfigSaveDelay.count()); -}; + log::assert_that(config_save_delay > kMinConfigSaveDelay, + "Config save delay of {} ms is not enough, must be at least {} ms to avoid " + "overwhelming the " + "disk", + config_save_delay_.count(), kMinConfigSaveDelay.count()); +} StorageModule::~StorageModule() { std::lock_guard lock(mutex_); @@ -86,13 +84,15 @@ StorageModule::~StorageModule() { } const ModuleFactory StorageModule::Factory = ModuleFactory([]() { - return new StorageModule( - os::ParameterProvider::ConfigFilePath(), kDefaultConfigSaveDelay, kDefaultTempDeviceCapacity, false, false); + return new StorageModule(os::ParameterProvider::ConfigFilePath(), kDefaultConfigSaveDelay, + kDefaultTempDeviceCapacity, false, false); }); struct StorageModule::impl { explicit impl(Handler* handler, ConfigCache cache, size_t in_memory_cache_size_limit) - : config_save_alarm_(handler), cache_(std::move(cache)), memory_only_cache_(in_memory_cache_size_limit, {}) {} + : config_save_alarm_(handler), + cache_(std::move(cache)), + memory_only_cache_(in_memory_cache_size_limit, {}) {} Alarm config_save_alarm_; ConfigCache cache_; ConfigCache memory_only_cache_; @@ -110,7 +110,8 @@ void StorageModule::SaveDelayed() { return; } pimpl_->config_save_alarm_.Schedule( - common::BindOnce(&StorageModule::SaveImmediately, common::Unretained(this)), config_save_delay_); + common::BindOnce(&StorageModule::SaveImmediately, common::Unretained(this)), + config_save_delay_); pimpl_->has_pending_config_save_ = true; } @@ -122,8 +123,8 @@ void StorageModule::SaveImmediately() { } #ifndef TARGET_FLOSS log::assert_that( - LegacyConfigFile::FromPath(config_file_path_).Write(pimpl_->cache_), - "assert failed: LegacyConfigFile::FromPath(config_file_path_).Write(pimpl_->cache_)"); + LegacyConfigFile::FromPath(config_file_path_).Write(pimpl_->cache_), + "assert failed: LegacyConfigFile::FromPath(config_file_path_).Write(pimpl_->cache_)"); #else if (!LegacyConfigFile::FromPath(config_file_path_).Write(pimpl_->cache_)) { log::error("Unable to write config file to disk"); @@ -133,7 +134,7 @@ void StorageModule::SaveImmediately() { if (bluetooth::os::ParameterProvider::GetBtKeystoreInterface() != nullptr && bluetooth::os::ParameterProvider::IsCommonCriteriaMode()) { bluetooth::os::ParameterProvider::GetBtKeystoreInterface()->set_encrypt_key_or_remove_key( - kConfigFilePrefix, kConfigFileHash); + kConfigFilePrefix, kConfigFileHash); } } @@ -143,7 +144,7 @@ void StorageModule::Clear() { } void StorageModule::ListDependencies(ModuleList* list) const { - list->add(); + list->add(); } void StorageModule::Start() { @@ -172,7 +173,7 @@ void StorageModule::Start() { } pimpl_ = std::make_unique(GetHandler(), std::move(config.value()), temp_devices_capacity_); pimpl_->cache_.SetPersistentConfigChangedCallback( - [this] { this->CallOn(this, &StorageModule::SaveDelayed); }); + [this] { this->CallOn(this, &StorageModule::SaveDelayed); }); // Cleanup temporary pairings if we have left guest mode if (!is_restricted_mode_) { @@ -181,7 +182,8 @@ void StorageModule::Start() { config->FixDeviceTypeInconsistencies(); if (bluetooth::os::ParameterProvider::GetBtKeystoreInterface() != nullptr) { - bluetooth::os::ParameterProvider::GetBtKeystoreInterface()->ConvertEncryptOrDecryptKeyIfNeeded(); + bluetooth::os::ParameterProvider::GetBtKeystoreInterface() + ->ConvertEncryptOrDecryptKeyIfNeeded(); } if (save_needed) { @@ -201,35 +203,24 @@ void StorageModule::Stop() { pimpl_.reset(); } -std::string StorageModule::ToString() const { - return "Storage Module"; -} +std::string StorageModule::ToString() const { return "Storage Module"; } Device StorageModule::GetDeviceByLegacyKey(hci::Address legacy_key_address) { std::lock_guard lock(mutex_); - return Device( - &pimpl_->cache_, - &pimpl_->memory_only_cache_, - std::move(legacy_key_address), - Device::ConfigKeyAddressType::LEGACY_KEY_ADDRESS); + return Device(&pimpl_->cache_, &pimpl_->memory_only_cache_, std::move(legacy_key_address), + Device::ConfigKeyAddressType::LEGACY_KEY_ADDRESS); } Device StorageModule::GetDeviceByClassicMacAddress(hci::Address classic_address) { std::lock_guard lock(mutex_); - return Device( - &pimpl_->cache_, - &pimpl_->memory_only_cache_, - std::move(classic_address), - Device::ConfigKeyAddressType::CLASSIC_ADDRESS); + return Device(&pimpl_->cache_, &pimpl_->memory_only_cache_, std::move(classic_address), + Device::ConfigKeyAddressType::CLASSIC_ADDRESS); } Device StorageModule::GetDeviceByLeIdentityAddress(hci::Address le_identity_address) { std::lock_guard lock(mutex_); - return Device( - &pimpl_->cache_, - &pimpl_->memory_only_cache_, - std::move(le_identity_address), - Device::ConfigKeyAddressType::LE_IDENTITY_ADDRESS); + return Device(&pimpl_->cache_, &pimpl_->memory_only_cache_, std::move(le_identity_address), + Device::ConfigKeyAddressType::LE_IDENTITY_ADDRESS); } std::vector StorageModule::GetBondedDevices() { @@ -244,7 +235,7 @@ std::vector StorageModule::GetBondedDevices() { } bool StorageModule::is_config_checksum_pass(int check_bit) { - return ((os::ParameterProvider::GetCommonCriteriaConfigCompareResult() & check_bit) == check_bit); + return (os::ParameterProvider::GetCommonCriteriaConfigCompareResult() & check_bit) == check_bit; } bool StorageModule::HasSection(const std::string& section) const { @@ -257,8 +248,8 @@ bool StorageModule::HasProperty(const std::string& section, const std::string& p return pimpl_->cache_.HasProperty(section, property); } -std::optional StorageModule::GetProperty( - const std::string& section, const std::string& property) const { +std::optional StorageModule::GetProperty(const std::string& section, + const std::string& property) const { std::lock_guard lock(mutex_); return pimpl_->cache_.GetProperty(section, property); } @@ -298,42 +289,42 @@ void StorageModule::SetBool(const std::string& section, const std::string& prope ConfigCacheHelper::FromConfigCache(pimpl_->cache_).SetBool(section, property, value); } -std::optional StorageModule::GetBool( - const std::string& section, const std::string& property) const { +std::optional StorageModule::GetBool(const std::string& section, + const std::string& property) const { std::lock_guard lock(mutex_); return ConfigCacheHelper::FromConfigCache(pimpl_->cache_).GetBool(section, property); } -void StorageModule::SetUint64( - const std::string& section, const std::string& property, uint64_t value) { +void StorageModule::SetUint64(const std::string& section, const std::string& property, + uint64_t value) { std::lock_guard lock(mutex_); ConfigCacheHelper::FromConfigCache(pimpl_->cache_).SetUint64(section, property, value); } -std::optional StorageModule::GetUint64( - const std::string& section, const std::string& property) const { +std::optional StorageModule::GetUint64(const std::string& section, + const std::string& property) const { std::lock_guard lock(mutex_); return ConfigCacheHelper::FromConfigCache(pimpl_->cache_).GetUint64(section, property); } -void StorageModule::SetUint32( - const std::string& section, const std::string& property, uint32_t value) { +void StorageModule::SetUint32(const std::string& section, const std::string& property, + uint32_t value) { std::lock_guard lock(mutex_); ConfigCacheHelper::FromConfigCache(pimpl_->cache_).SetUint32(section, property, value); } -std::optional StorageModule::GetUint32( - const std::string& section, const std::string& property) const { +std::optional StorageModule::GetUint32(const std::string& section, + const std::string& property) const { std::lock_guard lock(mutex_); return ConfigCacheHelper::FromConfigCache(pimpl_->cache_).GetUint32(section, property); } -void StorageModule::SetInt64( - const std::string& section, const std::string& property, int64_t value) { +void StorageModule::SetInt64(const std::string& section, const std::string& property, + int64_t value) { std::lock_guard lock(mutex_); ConfigCacheHelper::FromConfigCache(pimpl_->cache_).SetInt64(section, property, value); } -std::optional StorageModule::GetInt64( - const std::string& section, const std::string& property) const { +std::optional StorageModule::GetInt64(const std::string& section, + const std::string& property) const { std::lock_guard lock(mutex_); return ConfigCacheHelper::FromConfigCache(pimpl_->cache_).GetInt64(section, property); } @@ -343,20 +334,20 @@ void StorageModule::SetInt(const std::string& section, const std::string& proper ConfigCacheHelper::FromConfigCache(pimpl_->cache_).SetInt(section, property, value); } -std::optional StorageModule::GetInt( - const std::string& section, const std::string& property) const { +std::optional StorageModule::GetInt(const std::string& section, + const std::string& property) const { std::lock_guard lock(mutex_); return ConfigCacheHelper::FromConfigCache(pimpl_->cache_).GetInt(section, property); } -void StorageModule::SetBin( - const std::string& section, const std::string& property, const std::vector& value) { +void StorageModule::SetBin(const std::string& section, const std::string& property, + const std::vector& value) { std::lock_guard lock(mutex_); ConfigCacheHelper::FromConfigCache(pimpl_->cache_).SetBin(section, property, value); } -std::optional> StorageModule::GetBin( - const std::string& section, const std::string& property) const { +std::optional> StorageModule::GetBin(const std::string& section, + const std::string& property) const { std::lock_guard lock(mutex_); return ConfigCacheHelper::FromConfigCache(pimpl_->cache_).GetBin(section, property); } diff --git a/system/gd/storage/storage_module.h b/system/gd/storage/storage_module.h index 3d08700c8b2..12f57501960 100644 --- a/system/gd/storage/storage_module.h +++ b/system/gd/storage/storage_module.h @@ -47,7 +47,7 @@ class AclManager; namespace storage { class StorageModule : public bluetooth::Module { - public: +public: static const std::string kInfoSection; static const std::string kFileSourceProperty; static const std::string kTimeCreatedProperty; @@ -62,8 +62,10 @@ class StorageModule : public bluetooth::Module { static const ModuleFactory Factory; // Methods to access the storage layer via Device abstraction - // - Devices will be lazily created when methods below are called. Hence, no std::optional<> nor nullptr is used in - // the return type. User of the API can use the Device object's API to find out if the device has existed before + // - Devices will be lazily created when methods below are called. Hence, no std::optional<> nor + // nullptr is used in + // the return type. User of the API can use the Device object's API to find out if the device + // has existed before // - Devices with no config values will not be saved to config cache // - Devices that are not paired will also be discarded when stack shutdown @@ -79,41 +81,45 @@ class StorageModule : public bluetooth::Module { // -> Random Address: randomly generated, does not begin with IEEE assigned OUI number // -> Static: static random address do not change // -> Private/Variable: private random address changes once so often - // -> Resolvable: this address can be resolved into a static address using identity resolving key (IRK) + // -> Resolvable: this address can be resolved into a static address using identity + // resolving key (IRK) // -> Non-resolvable: this address is for temporary use only, do not save this address // // MAC addresses are six bytes only and hence are only regionally unique - // Get a device object using the |legacy_key_address|. In legacy config, each device's config is stored in a config - // section keyed by a single MAC address. For BR/EDR device, this is straightforward as a BR/EDR device has only a - // single public static MAC address. However, for LE devices using private addresses, we only learn its real static - // address after pairing. Since we still need to store that device's information prior to pairing, we use the - // first-seen address of that device, no matter random private or static public, as a "key" to store that device's - // config. This method gives you a device object using this legacy key. If the key does not exist, the device will - // be lazily created in the config + // Get a device object using the |legacy_key_address|. In legacy config, each device's config is + // stored in a config section keyed by a single MAC address. For BR/EDR device, this is + // straightforward as a BR/EDR device has only a single public static MAC address. However, for LE + // devices using private addresses, we only learn its real static address after pairing. Since we + // still need to store that device's information prior to pairing, we use the first-seen address + // of that device, no matter random private or static public, as a "key" to store that device's + // config. This method gives you a device object using this legacy key. If the key does not exist, + // the device will be lazily created in the config Device GetDeviceByLegacyKey(hci::Address legacy_key_address); - // A classic (BR/EDR) or dual mode device can be uniquely located by its classic (BR/EDR) MAC address + // A classic (BR/EDR) or dual mode device can be uniquely located by its classic (BR/EDR) MAC + // address Device GetDeviceByClassicMacAddress(hci::Address classic_address); // A LE or dual mode device can be uniquely located by its identity address that is either: // -> Public static address // -> Random static address - // If remote device uses LE random private resolvable address, user of this API must resolve its identity address - // before calling this method to get the device object + // If remote device uses LE random private resolvable address, user of this API must resolve its + // identity address before calling this method to get the device object // - // Note: A dual mode device's identity address is normally the same as its BR/EDR address, but they can also be - // different. Hence, please don't make such assumption and don't use GetDeviceByBrEdrMacAddress() interchangeably + // Note: A dual mode device's identity address is normally the same as its BR/EDR address, but + // they can also be different. Hence, please don't make such assumption and don't use + // GetDeviceByBrEdrMacAddress() interchangeably Device GetDeviceByLeIdentityAddress(hci::Address le_identity_address); // Get a list of bonded devices from config std::vector GetBondedDevices(); - // Modify the underlying config by starting a mutation. All entries in the mutation will be applied atomically when - // Commit() is called. User should never touch ConfigCache() directly. + // Modify the underlying config by starting a mutation. All entries in the mutation will be + // applied atomically when Commit() is called. User should never touch ConfigCache() directly. Mutation Modify(); - protected: +protected: void ListDependencies(ModuleList* list) const override; void Start() override; void Stop() override; @@ -124,11 +130,12 @@ class StorageModule : public bluetooth::Module { friend security::internal::SecurityManagerImpl; // For unit test only ConfigCache* GetMemoryOnlyConfigCache(); - // Normally, underlying config will be saved at most 3 seconds after the first config change in a series of changes - // This method triggers the delayed saving automatically, the delay is equal to |config_save_delay_| + // Normally, underlying config will be saved at most 3 seconds after the first config change in a + // series of changes This method triggers the delayed saving automatically, the delay is equal to + // |config_save_delay_| void SaveDelayed(); - // In some cases, one may want to save the config immediately to disk. Call this method with caution as it runs - // immediately on the calling thread + // In some cases, one may want to save the config immediately to disk. Call this method with + // caution as it runs immediately on the calling thread void SaveImmediately(); // remove all content in this config cache, restore it to the state after the explicit constructor void Clear(); @@ -140,18 +147,14 @@ class StorageModule : public bluetooth::Module { // - temp_devices_capacity is the number of temporary, typically unpaired devices to hold in a // memory based LRU // - is_restricted_mode and is_single_user_mode are flags from upper layer - StorageModule( - std::string config_file_path, - std::chrono::milliseconds config_save_delay, - size_t temp_devices_capacity, - bool is_restricted_mode, - bool is_single_user_mode); + StorageModule(std::string config_file_path, std::chrono::milliseconds config_save_delay, + size_t temp_devices_capacity, bool is_restricted_mode, bool is_single_user_mode); bool HasSection(const std::string& section) const; bool HasProperty(const std::string& section, const std::string& property) const; - std::optional GetProperty( - const std::string& section, const std::string& property) const; + std::optional GetProperty(const std::string& section, + const std::string& property) const; void SetProperty(std::string section, std::string property, std::string value); std::vector GetPersistentSections() const; @@ -172,12 +175,12 @@ class StorageModule : public bluetooth::Module { std::optional GetInt64(const std::string& section, const std::string& property) const; void SetInt(const std::string& section, const std::string& property, int value); std::optional GetInt(const std::string& section, const std::string& property) const; - void SetBin( - const std::string& section, const std::string& property, const std::vector& value); - std::optional> GetBin( - const std::string& section, const std::string& property) const; + void SetBin(const std::string& section, const std::string& property, + const std::vector& value); + std::optional> GetBin(const std::string& section, + const std::string& property) const; - private: +private: struct impl; mutable std::recursive_mutex mutex_; std::unique_ptr pimpl_; diff --git a/system/gd/storage/storage_module_test.cc b/system/gd/storage/storage_module_test.cc index caa4b30307b..07163922fe1 100644 --- a/system/gd/storage/storage_module_test.cc +++ b/system/gd/storage/storage_module_test.cc @@ -50,18 +50,11 @@ static const std::chrono::milliseconds kTestConfigSaveDelay = std::chrono::milli static const size_t kTestTempDevicesCapacity = 10; class TestStorageModule : public StorageModule { - public: - TestStorageModule( - std::string config_file_path, - std::chrono::milliseconds config_save_delay, - bool is_restricted_mode, - bool is_single_user_mode) - : StorageModule( - std::move(config_file_path), - config_save_delay, - kTestTempDevicesCapacity, - is_restricted_mode, - is_single_user_mode) {} +public: + TestStorageModule(std::string config_file_path, std::chrono::milliseconds config_save_delay, + bool is_restricted_mode, bool is_single_user_mode) + : StorageModule(std::move(config_file_path), config_save_delay, kTestTempDevicesCapacity, + is_restricted_mode, is_single_user_mode) {} ConfigCache* GetMemoryOnlyConfigCachePublic() { return StorageModule::GetMemoryOnlyConfigCache(); @@ -74,37 +67,31 @@ class TestStorageModule : public StorageModule { return HasProperty(section, property); } - std::optional GetPropertyPublic( - const std::string& section, const std::string& property) const { + std::optional GetPropertyPublic(const std::string& section, + const std::string& property) const { return GetProperty(section, property); } void SetPropertyPublic(std::string section, std::string property, std::string value) { return SetProperty(section, property, value); } - std::vector GetPersistentSectionsPublic() const { - return GetPersistentSections(); - } + std::vector GetPersistentSectionsPublic() const { return GetPersistentSections(); } bool RemovePropertyPublic(const std::string& section, const std::string& property) { return RemoveProperty(section, property); } - void ConvertEncryptOrDecryptKeyIfNeededPublic() { - return ConvertEncryptOrDecryptKeyIfNeeded(); - } + void ConvertEncryptOrDecryptKeyIfNeededPublic() { return ConvertEncryptOrDecryptKeyIfNeeded(); } void RemoveSectionWithPropertyPublic(const std::string& property) { return RemoveSectionWithProperty(property); } - void RemoveSectionPublic(const std::string& section) { - return RemoveSection(section); - } + void RemoveSectionPublic(const std::string& section) { return RemoveSection(section); } }; class StorageModuleTest : public Test { - protected: +protected: void SetUp() override { temp_dir_ = std::filesystem::temp_directory_path(); temp_config_ = temp_dir_ / "temp_config.txt"; @@ -130,7 +117,7 @@ class StorageModuleTest : public Test { bool WaitForReactorIdle(std::chrono::milliseconds time) { bool stopped = - test_registry_.GetTestThread().GetReactor()->WaitForIdle(std::chrono::seconds(2)); + test_registry_.GetTestThread().GetReactor()->WaitForIdle(std::chrono::seconds(2)); if (!stopped) { return false; } @@ -163,25 +150,25 @@ TEST_F(StorageModuleTest, empty_config_no_op_test) { } static const std::string kReadTestConfig = - "[Info]\n" - "TimeCreated = 2020-05-20 01:20:56\n" - "\n" - "[Metrics]\n" - "Salt256Bit = 1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef\n" - "\n" - "[Adapter]\n" - "Address = 01:02:03:ab:cd:ef\n" - "LE_LOCAL_KEY_IRK = fedcba0987654321fedcba0987654321\n" - "LE_LOCAL_KEY_IR = fedcba0987654321fedcba0987654322\n" - "LE_LOCAL_KEY_DHK = fedcba0987654321fedcba0987654323\n" - "LE_LOCAL_KEY_ER = fedcba0987654321fedcba0987654324\n" - "ScanMode = 2\n" - "DiscoveryTimeout = 120\n" - "\n" - "[01:02:03:ab:cd:ea]\n" - "Name = hello world\n" - "LinkKey = fedcba0987654321fedcba0987654328\n" - "\n"; + "[Info]\n" + "TimeCreated = 2020-05-20 01:20:56\n" + "\n" + "[Metrics]\n" + "Salt256Bit = 1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef\n" + "\n" + "[Adapter]\n" + "Address = 01:02:03:ab:cd:ef\n" + "LE_LOCAL_KEY_IRK = fedcba0987654321fedcba0987654321\n" + "LE_LOCAL_KEY_IR = fedcba0987654321fedcba0987654322\n" + "LE_LOCAL_KEY_DHK = fedcba0987654321fedcba0987654323\n" + "LE_LOCAL_KEY_ER = fedcba0987654321fedcba0987654324\n" + "ScanMode = 2\n" + "DiscoveryTimeout = 120\n" + "\n" + "[01:02:03:ab:cd:ea]\n" + "Name = hello world\n" + "LinkKey = fedcba0987654321fedcba0987654328\n" + "\n"; TEST_F(StorageModuleTest, read_existing_config_test) { ASSERT_TRUE(bluetooth::os::WriteToFile(temp_config_.string(), kReadTestConfig)); @@ -194,9 +181,8 @@ TEST_F(StorageModuleTest, read_existing_config_test) { // Test ASSERT_TRUE(storage->HasSectionPublic("Metrics")); ASSERT_THAT(storage->GetPersistentSectionsPublic(), ElementsAre("01:02:03:ab:cd:ea")); - ASSERT_THAT( - storage->GetPropertyPublic(StorageModule::kAdapterSection, BTIF_STORAGE_KEY_ADDRESS), - Optional(StrEq("01:02:03:ab:cd:ef"))); + ASSERT_THAT(storage->GetPropertyPublic(StorageModule::kAdapterSection, BTIF_STORAGE_KEY_ADDRESS), + Optional(StrEq("01:02:03:ab:cd:ef"))); // Tear down test_registry_.StopAll(); @@ -220,19 +206,17 @@ TEST_F(StorageModuleTest, save_config_test) { // Test // Change a property - ASSERT_THAT( - storage->GetPropertyPublic("01:02:03:ab:cd:ea", BTIF_STORAGE_KEY_NAME), - Optional(StrEq("hello world"))); + ASSERT_THAT(storage->GetPropertyPublic("01:02:03:ab:cd:ea", BTIF_STORAGE_KEY_NAME), + Optional(StrEq("hello world"))); storage->SetPropertyPublic("01:02:03:ab:cd:ea", BTIF_STORAGE_KEY_NAME, "foo"); - ASSERT_THAT( - storage->GetPropertyPublic("01:02:03:ab:cd:ea", BTIF_STORAGE_KEY_NAME), - Optional(StrEq("foo"))); + ASSERT_THAT(storage->GetPropertyPublic("01:02:03:ab:cd:ea", BTIF_STORAGE_KEY_NAME), + Optional(StrEq("foo"))); ASSERT_TRUE(WaitForReactorIdle(kTestConfigSaveDelay)); auto config = LegacyConfigFile::FromPath(temp_config_.string()).Read(kTestTempDevicesCapacity); ASSERT_TRUE(config); - ASSERT_THAT( - config->GetProperty("01:02:03:ab:cd:ea", BTIF_STORAGE_KEY_NAME), Optional(StrEq("foo"))); + ASSERT_THAT(config->GetProperty("01:02:03:ab:cd:ea", BTIF_STORAGE_KEY_NAME), + Optional(StrEq("foo"))); // Remove a property storage->RemovePropertyPublic("01:02:03:ab:cd:ea", BTIF_STORAGE_KEY_NAME); diff --git a/system/gd/sysprops/sysprops_module.cc b/system/gd/sysprops/sysprops_module.cc index 64b9e19fe07..c86a260ef06 100644 --- a/system/gd/sysprops/sysprops_module.cc +++ b/system/gd/sysprops/sysprops_module.cc @@ -32,9 +32,7 @@ static const char* kAflagSection = "Aflags"; static const char* kAflagPrefix = "persist.device_config.aconfig_flags.bluetooth."; SyspropsModule::SyspropsModule() {} -SyspropsModule::~SyspropsModule() { - pimpl_.reset(); -} +SyspropsModule::~SyspropsModule() { pimpl_.reset(); } const ModuleFactory SyspropsModule::Factory = ModuleFactory([]() { return new SyspropsModule(); }); @@ -62,71 +60,67 @@ void SyspropsModule::Start() { pimpl_ = std::make_unique(GetHandler()); } -void SyspropsModule::Stop() { - pimpl_.reset(); -} +void SyspropsModule::Stop() { pimpl_.reset(); } -std::string SyspropsModule::ToString() const { - return "Sysprops Module"; -} +std::string SyspropsModule::ToString() const { return "Sysprops Module"; } void SyspropsModule::parse_config(std::string file_path) { const std::list supported_sysprops = { - // General - "bluetooth.btm.sec.delay_auth_ms.value", - "bluetooth.device.default_name", - "bluetooth.core.gap.le.privacy.enabled", - "bluetooth.core.gap.le.privacy.own_address_type.enabled", - "bluetooth.core.gap.le.conn.only_init_1m_phy.enabled", - "bluetooth.device.class_of_device", - "bluetooth.device_id.product_id", - "bluetooth.device_id.product_version", - "bluetooth.device_id.vendor_id", - "bluetooth.device_id.vendor_id_source", - "persist.bluetooth.inq_by_rssi", - // BR/EDR - "bluetooth.core.classic.page_scan_type", - "bluetooth.core.classic.page_scan_interval", - "bluetooth.core.classic.page_scan_window", - "bluetooth.core.classic.inq_scan_type", - "bluetooth.core.classic.inq_scan_interval", - "bluetooth.core.classic.inq_scan_window", - "bluetooth.core.classic.inq_length", - "bluetooth.core.acl.link_supervision_timeout", - "bluetooth.core.classic.page_timeout", - "bluetooth.core.classic.sniff_max_intervals", - "bluetooth.core.classic.sniff_min_intervals", - "bluetooth.core.classic.sniff_attempts", - "bluetooth.core.classic.sniff_timeouts", - // LE - "bluetooth.core.le.min_connection_interval", - "bluetooth.core.le.max_connection_interval", - "bluetooth.core.le.connection_latency", - "bluetooth.core.le.connection_supervision_timeout", - "bluetooth.core.le.direct_connection_timeout", - "bluetooth.core.le.connection_scan_interval_fast", - "bluetooth.core.le.connection_scan_window_fast", - "bluetooth.core.le.connection_scan_window_2m_fast", - "bluetooth.core.le.connection_scan_window_coded_fast", - "bluetooth.core.le.connection_scan_interval_slow", - "bluetooth.core.le.connection_scan_window_slow", - "bluetooth.core.le.connection_scan_interval_system_suspend", - "bluetooth.core.le.connection_scan_window_system_suspend", - "bluetooth.core.le.inquiry_scan_interval", - "bluetooth.core.le.inquiry_scan_window", - "bluetooth.core.le.adv_mon_scan_interval", - "bluetooth.core.le.adv_mon_scan_window", - "bluetooth.core.le.adv_mon_rtl_quirk", - "bluetooth.core.le.adv_mon_qca_quirk", - "bluetooth.core.le.vendor_capabilities.enabled", - // LE Audio - "bluetooth.le_audio.enable_le_audio_only", - "bluetooth.leaudio.dual_bidirection_swb.supported", - // SCO - "bluetooth.sco.disable_enhanced_connection", - "bluetooth.sco.swb_supported", - // Profile - "persist.bluetooth.avrcpcontrolversion", + // General + "bluetooth.btm.sec.delay_auth_ms.value", + "bluetooth.device.default_name", + "bluetooth.core.gap.le.privacy.enabled", + "bluetooth.core.gap.le.privacy.own_address_type.enabled", + "bluetooth.core.gap.le.conn.only_init_1m_phy.enabled", + "bluetooth.device.class_of_device", + "bluetooth.device_id.product_id", + "bluetooth.device_id.product_version", + "bluetooth.device_id.vendor_id", + "bluetooth.device_id.vendor_id_source", + "persist.bluetooth.inq_by_rssi", + // BR/EDR + "bluetooth.core.classic.page_scan_type", + "bluetooth.core.classic.page_scan_interval", + "bluetooth.core.classic.page_scan_window", + "bluetooth.core.classic.inq_scan_type", + "bluetooth.core.classic.inq_scan_interval", + "bluetooth.core.classic.inq_scan_window", + "bluetooth.core.classic.inq_length", + "bluetooth.core.acl.link_supervision_timeout", + "bluetooth.core.classic.page_timeout", + "bluetooth.core.classic.sniff_max_intervals", + "bluetooth.core.classic.sniff_min_intervals", + "bluetooth.core.classic.sniff_attempts", + "bluetooth.core.classic.sniff_timeouts", + // LE + "bluetooth.core.le.min_connection_interval", + "bluetooth.core.le.max_connection_interval", + "bluetooth.core.le.connection_latency", + "bluetooth.core.le.connection_supervision_timeout", + "bluetooth.core.le.direct_connection_timeout", + "bluetooth.core.le.connection_scan_interval_fast", + "bluetooth.core.le.connection_scan_window_fast", + "bluetooth.core.le.connection_scan_window_2m_fast", + "bluetooth.core.le.connection_scan_window_coded_fast", + "bluetooth.core.le.connection_scan_interval_slow", + "bluetooth.core.le.connection_scan_window_slow", + "bluetooth.core.le.connection_scan_interval_system_suspend", + "bluetooth.core.le.connection_scan_window_system_suspend", + "bluetooth.core.le.inquiry_scan_interval", + "bluetooth.core.le.inquiry_scan_window", + "bluetooth.core.le.adv_mon_scan_interval", + "bluetooth.core.le.adv_mon_scan_window", + "bluetooth.core.le.adv_mon_rtl_quirk", + "bluetooth.core.le.adv_mon_qca_quirk", + "bluetooth.core.le.vendor_capabilities.enabled", + // LE Audio + "bluetooth.le_audio.enable_le_audio_only", + "bluetooth.leaudio.dual_bidirection_swb.supported", + // SCO + "bluetooth.sco.disable_enhanced_connection", + "bluetooth.sco.swb_supported", + // Profile + "persist.bluetooth.avrcpcontrolversion", }; auto config = storage::LegacyConfigFile::FromPath(file_path).Read(kDefaultCapacity); diff --git a/system/gd/sysprops/sysprops_module.h b/system/gd/sysprops/sysprops_module.h index f643b95303d..d1050bd660d 100644 --- a/system/gd/sysprops/sysprops_module.h +++ b/system/gd/sysprops/sysprops_module.h @@ -25,7 +25,7 @@ namespace bluetooth { namespace sysprops { class SyspropsModule : public bluetooth::Module { - public: +public: SyspropsModule(); SyspropsModule(const SyspropsModule&) = delete; SyspropsModule& operator=(const SyspropsModule&) = delete; @@ -34,7 +34,7 @@ class SyspropsModule : public bluetooth::Module { static const ModuleFactory Factory; - protected: +protected: void ListDependencies(ModuleList* list) const override; void Start() override; @@ -43,7 +43,7 @@ class SyspropsModule : public bluetooth::Module { std::string ToString() const override; - private: +private: struct impl; std::unique_ptr pimpl_; void parse_config(std::string file_path); diff --git a/system/gd/sysprops/sysprops_module_test.cc b/system/gd/sysprops/sysprops_module_test.cc index 545780dcfe1..e427db3831f 100644 --- a/system/gd/sysprops/sysprops_module_test.cc +++ b/system/gd/sysprops/sysprops_module_test.cc @@ -28,7 +28,7 @@ namespace testing { class SyspropsModuleTest : public Test { - protected: +protected: void SetUp() override { EXPECT_TRUE(bluetooth::os::ClearSystemPropertiesForHost()); temp_config_ = std::filesystem::temp_directory_path() / "temp_sysprops.conf"; @@ -62,16 +62,16 @@ static const std::string kSupportedSyspropName = "bluetooth.device.class_of_devi static const std::string kSupportedSyspropValue = "0,1,4"; static const std::string kUnsupportedSyspropName = "i.am.an.unsupported.sysprop"; static const std::string kCorrectPrefixAflagName = - "persist.device_config.aconfig_flags.bluetooth.com.android.bluetooth.flags.msft_addr_tracking_" - "quirk"; + "persist.device_config.aconfig_flags.bluetooth.com.android.bluetooth.flags.msft_addr_" + "tracking_quirk"; static const std::string kCorrectPrefixAflagValue = "true"; static const std::string kIncorrectPrefixAflagName = - "persist.device_config.aconfig_flags.not_bluetooth.testing_flag"; + "persist.device_config.aconfig_flags.not_bluetooth.testing_flag"; static const std::string kParseConfigTestConfig = - "[Sysprops]\n" + kSupportedSyspropName + "=" + kSupportedSyspropValue + "\n" + - kUnsupportedSyspropName + "=true\n" + "\n" + "[Aflags]\n" + kCorrectPrefixAflagName + "=" + - kCorrectPrefixAflagValue + "\n" + kIncorrectPrefixAflagName + "=true\n"; + "[Sysprops]\n" + kSupportedSyspropName + "=" + kSupportedSyspropValue + "\n" + + kUnsupportedSyspropName + "=true\n" + "\n" + "[Aflags]\n" + kCorrectPrefixAflagName + "=" + + kCorrectPrefixAflagValue + "\n" + kIncorrectPrefixAflagName + "=true\n"; TEST_F(SyspropsModuleTest, parse_config_test) { // Verify the state before test @@ -84,13 +84,11 @@ TEST_F(SyspropsModuleTest, parse_config_test) { auto* sysprops_module = new bluetooth::sysprops::SyspropsModule(); test_registry_.InjectTestModule(&bluetooth::sysprops::SyspropsModule::Factory, sysprops_module); - EXPECT_THAT( - bluetooth::os::GetSystemProperty(kSupportedSyspropName), - Optional(StrEq(kSupportedSyspropValue))); + EXPECT_THAT(bluetooth::os::GetSystemProperty(kSupportedSyspropName), + Optional(StrEq(kSupportedSyspropValue))); EXPECT_THAT(bluetooth::os::GetSystemProperty(kUnsupportedSyspropName), std::nullopt); - EXPECT_THAT( - bluetooth::os::GetSystemProperty(kCorrectPrefixAflagName), - Optional(StrEq(kCorrectPrefixAflagValue))); + EXPECT_THAT(bluetooth::os::GetSystemProperty(kCorrectPrefixAflagName), + Optional(StrEq(kCorrectPrefixAflagValue))); EXPECT_THAT(bluetooth::os::GetSystemProperty(kIncorrectPrefixAflagName), std::nullopt); } diff --git a/system/hci/include/bt_vendor_lib.h b/system/hci/include/bt_vendor_lib.h index a274af77768..c666fc13bff 100644 --- a/system/hci/include/bt_vendor_lib.h +++ b/system/hci/include/bt_vendor_lib.h @@ -317,8 +317,7 @@ typedef void (*tINT_CMD_CBACK)(void* p_mem); * HCI Command packet. For example, opcode = 0x0c03 for the HCI_RESET command * packet. */ -typedef uint8_t (*cmd_xmit_cb)(uint16_t opcode, void* p_buf, - tINT_CMD_CBACK p_cback); +typedef uint8_t (*cmd_xmit_cb)(uint16_t opcode, void* p_buf, tINT_CMD_CBACK p_cback); typedef void (*cfg_a2dp_cb)(bt_vendor_op_result_t result, bt_vendor_opcode_t op, uint8_t bta_av_handle); diff --git a/system/hci/include/btsnoop.h b/system/hci/include/btsnoop.h index e574c98bcaa..5993438b186 100644 --- a/system/hci/include/btsnoop.h +++ b/system/hci/include/btsnoop.h @@ -19,6 +19,7 @@ #pragma once #include + #include #include "stack/include/bt_hdr.h" @@ -33,8 +34,7 @@ typedef struct btsnoop_t { // Set a L2CAP channel as allowlisted, allowing packets with that L2CAP CID // to show up in the snoop logs. - void (*allowlist_l2c_channel)(uint16_t conn_handle, uint16_t local_cid, - uint16_t remote_cid); + void (*allowlist_l2c_channel)(uint16_t conn_handle, uint16_t local_cid, uint16_t remote_cid); // Set a RFCOMM dlci as allowlisted, allowing packets with that RFCOMM CID // to show up in the snoop logs. The local_cid is used to associate it with @@ -46,12 +46,10 @@ typedef struct btsnoop_t { // Indicate that the provided L2CAP channel is being used for RFCOMM. // If packets with the provided L2CAP CID are encountered, they will be // filtered on RFCOMM based on channels provided to |filter_rfc_channel|. - void (*add_rfc_l2c_channel)(uint16_t conn_handle, uint16_t local_cid, - uint16_t remote_cid); + void (*add_rfc_l2c_channel)(uint16_t conn_handle, uint16_t local_cid, uint16_t remote_cid); // Clear an L2CAP channel from being filtered. - void (*clear_l2cap_allowlist)(uint16_t conn_handle, uint16_t local_cid, - uint16_t remote_cid); + void (*clear_l2cap_allowlist)(uint16_t conn_handle, uint16_t local_cid, uint16_t remote_cid); } btsnoop_t; const btsnoop_t* btsnoop_get_interface(void); diff --git a/system/hci/include/btsnoop_mem.h b/system/hci/include/btsnoop_mem.h index 660678e9a8c..8bffc3ec1f7 100644 --- a/system/hci/include/btsnoop_mem.h +++ b/system/hci/include/btsnoop_mem.h @@ -24,8 +24,8 @@ // Callback invoked for each HCI packet. // Highlander mode - there can be only one... -typedef void (*btsnoop_data_cb)(const uint16_t type, const uint8_t* p_data, - const size_t len, const uint64_t timestamp_us); +typedef void (*btsnoop_data_cb)(const uint16_t type, const uint8_t* p_data, const size_t len, + const uint64_t timestamp_us); // This call sets the (one and only) callback that will // be invoked once for each HCI packet/event. diff --git a/system/hci/include/hci_layer.h b/system/hci/include/hci_layer.h index 03fcf58e480..ab8b0430ce4 100644 --- a/system/hci/include/hci_layer.h +++ b/system/hci/include/hci_layer.h @@ -31,9 +31,9 @@ #define MSG_SUB_EVT_MASK 0x00FF /* eq. BT_SUB_EVT_MASK */ /* Message event ID passed from Host/Controller lib to stack */ -#define MSG_HC_TO_STACK_HCI_ERR 0x1300 /* eq. BT_EVT_TO_BTU_HCIT_ERR */ -#define MSG_HC_TO_STACK_HCI_ISO 0x1700 /* eq. BT_EVT_TO_BTU_HCI_ISO */ -#define MSG_HC_TO_STACK_HCI_EVT 0x1000 /* eq. BT_EVT_TO_BTU_HCI_EVT */ +#define MSG_HC_TO_STACK_HCI_ERR 0x1300 /* eq. BT_EVT_TO_BTU_HCIT_ERR */ +#define MSG_HC_TO_STACK_HCI_ISO 0x1700 /* eq. BT_EVT_TO_BTU_HCI_ISO */ +#define MSG_HC_TO_STACK_HCI_EVT 0x1000 /* eq. BT_EVT_TO_BTU_HCI_EVT */ /* Message event ID passed from stack to vendor lib */ #define MSG_STACK_TO_HC_HCI_ISO 0x2d00 /* eq. BT_EVT_TO_LM_HCI_ISO */ @@ -47,17 +47,14 @@ typedef struct packet_fragmenter_t packet_fragmenter_t; typedef uint16_t command_opcode_t; typedef void (*command_complete_cb)(BT_HDR* response, void* context); -typedef void (*command_status_cb)(uint8_t status, BT_HDR* command, - void* context); +typedef void (*command_status_cb)(uint8_t status, BT_HDR* command, void* context); typedef struct hci_t { // Set the callback that the HCI layer uses to send data upwards - void (*set_data_cb)( - base::Callback send_data_cb); + void (*set_data_cb)(base::Callback send_data_cb); // Send a command through the HCI layer - void (*transmit_command)(const BT_HDR* command, - command_complete_cb complete_callback, + void (*transmit_command)(const BT_HDR* command, command_complete_cb complete_callback, command_status_cb status_cb, void* context); // Send some data downward through the HCI layer diff --git a/system/hci/include/packet_fragmenter.h b/system/hci/include/packet_fragmenter.h index e3b5f3f2534..1e59ce51525 100644 --- a/system/hci/include/packet_fragmenter.h +++ b/system/hci/include/packet_fragmenter.h @@ -22,8 +22,7 @@ #include "stack/include/bt_hdr.h" typedef void (*packet_reassembled_cb)(BT_HDR* packet); -typedef void (*packet_fragmented_cb)(BT_HDR* packet, - bool send_transmit_finished); +typedef void (*packet_fragmented_cb)(BT_HDR* packet, bool send_transmit_finished); typedef struct { // Called for every packet fragment. diff --git a/system/hci/src/packet_fragmenter.cc b/system/hci/src/packet_fragmenter.cc index c546a7bf721..9ecb6bd7b5a 100644 --- a/system/hci/src/packet_fragmenter.cc +++ b/system/hci/src/packet_fragmenter.cc @@ -45,25 +45,21 @@ // 2 bytes for handle, 2 bytes for data length (Volume 2, Part E, 5.4.5) #define HCI_ISO_PREAMBLE_SIZE 4 -#define HCI_ISO_HEADER_LEN_WITHOUT_TS \ - (HCI_ISO_HEADER_ISO_LEN_SIZE + HCI_ISO_HEADER_PACKET_SEQ_SIZE) -#define HCI_ISO_HEADER_LEN_WITH_TS \ - (HCI_ISO_HEADER_LEN_WITHOUT_TS + HCI_ISO_HEADER_TIMESTAMP_SIZE) +#define HCI_ISO_HEADER_LEN_WITHOUT_TS (HCI_ISO_HEADER_ISO_LEN_SIZE + HCI_ISO_HEADER_PACKET_SEQ_SIZE) +#define HCI_ISO_HEADER_LEN_WITH_TS (HCI_ISO_HEADER_LEN_WITHOUT_TS + HCI_ISO_HEADER_TIMESTAMP_SIZE) -#define HCI_ISO_SET_CONTINUATION_FLAG(handle) \ - (((handle)&0x4FFF) | (0x0001 << 12)) -#define HCI_ISO_SET_COMPLETE_FLAG(handle) (((handle)&0x4FFF) | (0x0002 << 12)) -#define HCI_ISO_SET_END_FRAG_FLAG(handle) (((handle)&0x4FFF) | (0x0003 << 12)) -#define HCI_ISO_SET_TIMESTAMP_FLAG(handle) (((handle)&0x3FFF) | (0x0001 << 14)) +#define HCI_ISO_SET_CONTINUATION_FLAG(handle) (((handle) & 0x4FFF) | (0x0001 << 12)) +#define HCI_ISO_SET_COMPLETE_FLAG(handle) (((handle) & 0x4FFF) | (0x0002 << 12)) +#define HCI_ISO_SET_END_FRAG_FLAG(handle) (((handle) & 0x4FFF) | (0x0003 << 12)) +#define HCI_ISO_SET_TIMESTAMP_FLAG(handle) (((handle) & 0x3FFF) | (0x0001 << 14)) #define HCI_ISO_GET_TS_FLAG(handle) (((handle) >> 14) & 0x0001) -#define HCI_ISO_GET_PACKET_STATUS_FLAGS(iso_sdu_length) \ - (iso_sdu_length & 0xC000) +#define HCI_ISO_GET_PACKET_STATUS_FLAGS(iso_sdu_length) (iso_sdu_length & 0xC000) #define HCI_ISO_SDU_LENGTH_MASK 0x0FFF -#define APPLY_CONTINUATION_FLAG(handle) (((handle)&0xCFFF) | 0x1000) -#define APPLY_START_FLAG(handle) (((handle)&0xCFFF) | 0x2000) -#define SUB_EVENT(event) ((event)&MSG_SUB_EVT_MASK) +#define APPLY_CONTINUATION_FLAG(handle) (((handle) & 0xCFFF) | 0x1000) +#define APPLY_START_FLAG(handle) (((handle) & 0xCFFF) | 0x2000) +#define SUB_EVENT(event) ((event) & MSG_SUB_EVT_MASK) #define GET_BOUNDARY_FLAG(handle) (((handle) >> 12) & 0x0003) #define GET_BROADCAST_FLAG(handle) (((handle) >> 14) & 0x0003) @@ -129,11 +125,9 @@ static void fragment_and_dispatch(BT_HDR* packet, uint16_t max_data_size) { // Write the ISO header for the next fragment stream = packet->data + packet->offset; if (remaining_length > max_packet_size) { - UINT16_TO_STREAM(stream, - HCI_ISO_SET_CONTINUATION_FLAG(handle & HANDLE_MASK)); + UINT16_TO_STREAM(stream, HCI_ISO_SET_CONTINUATION_FLAG(handle & HANDLE_MASK)); } else { - UINT16_TO_STREAM(stream, - HCI_ISO_SET_END_FRAG_FLAG(handle & HANDLE_MASK)); + UINT16_TO_STREAM(stream, HCI_ISO_SET_END_FRAG_FLAG(handle & HANDLE_MASK)); } UINT16_TO_STREAM(stream, remaining_length - HCI_ISO_PREAMBLE_SIZE); } @@ -158,9 +152,8 @@ static void reassemble_and_dispatch(BT_HDR* packet) { // last 2 bits is RFU iso_length = iso_length & 0x3FFF; - log::assert_that( - iso_length == packet->len - HCI_ISO_PREAMBLE_SIZE, - "assert failed: iso_length == packet->len - HCI_ISO_PREAMBLE_SIZE"); + log::assert_that(iso_length == packet->len - HCI_ISO_PREAMBLE_SIZE, + "assert failed: iso_length == packet->len - HCI_ISO_PREAMBLE_SIZE"); uint8_t boundary_flag = GET_BOUNDARY_FLAG(handle); uint8_t ts_flag = HCI_ISO_GET_TS_FLAG(handle); @@ -176,8 +169,8 @@ static void reassemble_and_dispatch(BT_HDR* packet) { if (map_iter != partial_iso_packets.end()) { log::warn( - "found unfinished packet for the iso handle with start packet. " - "Dropping old."); + "found unfinished packet for the iso handle with start packet. " + "Dropping old."); BT_HDR* hdl = map_iter->second; partial_iso_packets.erase(map_iter); buffer_allocator->free(hdl); @@ -191,8 +184,7 @@ static void reassemble_and_dispatch(BT_HDR* packet) { } if (iso_length < iso_hdr_len) { - log::warn("ISO packet too small ({} < {}). Dropping it.", packet->len, - iso_hdr_len); + log::warn("ISO packet too small ({} < {}). Dropping it.", packet->len, iso_hdr_len); buffer_allocator->free(packet); return; } @@ -210,19 +202,18 @@ static void reassemble_and_dispatch(BT_HDR* packet) { packet_status_flags = HCI_ISO_GET_PACKET_STATUS_FLAGS(iso_sdu_length); iso_sdu_length = iso_sdu_length & HCI_ISO_SDU_LENGTH_MASK; - if (packet_status_flags) + if (packet_status_flags) { log::error("packet status flags: 0x{:02x}", packet_status_flags); + } iso_full_len = iso_sdu_length + iso_hdr_len + HCI_ISO_PREAMBLE_SIZE; if ((iso_full_len + sizeof(BT_HDR)) > BT_DEFAULT_BUFFER_SIZE) { - log::error("Dropping ISO packet with invalid length ({}).", - iso_sdu_length); + log::error("Dropping ISO packet with invalid length ({}).", iso_sdu_length); buffer_allocator->free(packet); return; } - if (((boundary_flag == HCI_ISO_BF_COMPLETE_PACKET) && - (iso_full_len != packet->len)) || + if (((boundary_flag == HCI_ISO_BF_COMPLETE_PACKET) && (iso_full_len != packet->len)) || ((boundary_flag == HCI_ISO_BF_FIRST_FRAGMENTED_PACKET) && (iso_full_len <= packet->len))) { log::error("corrupted ISO frame"); @@ -230,8 +221,7 @@ static void reassemble_and_dispatch(BT_HDR* packet) { return; } - partial_packet = - (BT_HDR*)buffer_allocator->alloc(iso_full_len + sizeof(BT_HDR)); + partial_packet = (BT_HDR*)buffer_allocator->alloc(iso_full_len + sizeof(BT_HDR)); if (!partial_packet) { log::error("cannot allocate partial packet"); buffer_allocator->free(packet); @@ -271,20 +261,18 @@ static void reassemble_and_dispatch(BT_HDR* packet) { } partial_packet = map_iter->second; - if (partial_packet->len < - (partial_packet->offset + packet->len - HCI_ISO_PREAMBLE_SIZE)) { + if (partial_packet->len < (partial_packet->offset + packet->len - HCI_ISO_PREAMBLE_SIZE)) { log::error( - "got packet which would exceed expected length of {}. dropping " - "full packet", - partial_packet->len); + "got packet which would exceed expected length of {}. dropping " + "full packet", + partial_packet->len); buffer_allocator->free(packet); partial_iso_packets.erase(map_iter); buffer_allocator->free(partial_packet); return; } - memcpy(partial_packet->data + partial_packet->offset, - packet->data + HCI_ISO_PREAMBLE_SIZE, + memcpy(partial_packet->data + partial_packet->offset, packet->data + HCI_ISO_PREAMBLE_SIZE, packet->len - HCI_ISO_PREAMBLE_SIZE); if (boundary_flag == HCI_ISO_BF_CONTINUATION_FRAGMENT_PACKET) { @@ -293,12 +281,11 @@ static void reassemble_and_dispatch(BT_HDR* packet) { return; } - if (partial_packet->len != - partial_packet->offset + packet->len - HCI_ISO_PREAMBLE_SIZE) { + if (partial_packet->len != partial_packet->offset + packet->len - HCI_ISO_PREAMBLE_SIZE) { log::error( - "got last fragment, but it doesn't fill up the whole packet of " - "size {}", - partial_packet->len); + "got last fragment, but it doesn't fill up the whole packet of " + "size {}", + partial_packet->len); buffer_allocator->free(packet); partial_iso_packets.erase(map_iter); buffer_allocator->free(partial_packet); @@ -307,10 +294,11 @@ static void reassemble_and_dispatch(BT_HDR* packet) { partial_packet->layer_specific |= BT_ISO_HDR_OFFSET_POINTS_DATA; partial_packet->offset = HCI_ISO_PREAMBLE_SIZE; - if (partial_packet->layer_specific & BT_ISO_HDR_CONTAINS_TS) + if (partial_packet->layer_specific & BT_ISO_HDR_CONTAINS_TS) { partial_packet->offset += HCI_ISO_HEADER_LEN_WITH_TS; - else + } else { partial_packet->offset += HCI_ISO_HEADER_LEN_WITHOUT_TS; + } buffer_allocator->free(packet); @@ -327,8 +315,7 @@ static void reassemble_and_dispatch(BT_HDR* packet) { static const packet_fragmenter_t interface = {init, cleanup, - fragment_and_dispatch, - reassemble_and_dispatch}; + fragment_and_dispatch, reassemble_and_dispatch}; const packet_fragmenter_t* packet_fragmenter_get_interface() { buffer_allocator = buffer_allocator_get_interface(); diff --git a/system/hci/test/packet_fragmenter_test.cc b/system/hci/test/packet_fragmenter_test.cc index f85450f2713..03e134382f9 100644 --- a/system/hci/test/packet_fragmenter_test.cc +++ b/system/hci/test/packet_fragmenter_test.cc @@ -38,28 +38,25 @@ DECLARE_TEST_MODES(init, iso_no_reassembly, iso_reassembly, iso_fragmentation, #define LOCAL_BLE_CONTROLLER_ID 1 static const char* sample_data = - "At this point they came in sight of thirty forty windmills that there are " - "on plain, and " - "as soon as Don Quixote saw them he said to his squire, \"Fortune is " - "arranging matters " - "for us better than we could have shaped our desires ourselves, for look " - "there, friend " - "Sancho Panza, where thirty or more monstrous giants present themselves, " - "all of whom I " - "mean to engage in battle and slay, and with whose spoils we shall begin " - "to make our " - "fortunes; for this is righteous warfare, and it is God's good service to " - "sweep so evil " - "a breed from off the face of the earth.\""; + "At this point they came in sight of thirty forty windmills that there are " + "on plain, and " + "as soon as Don Quixote saw them he said to his squire, \"Fortune is " + "arranging matters " + "for us better than we could have shaped our desires ourselves, for look " + "there, friend " + "Sancho Panza, where thirty or more monstrous giants present themselves, " + "all of whom I " + "mean to engage in battle and slay, and with whose spoils we shall begin " + "to make our " + "fortunes; for this is righteous warfare, and it is God's good service to " + "sweep so evil " + "a breed from off the face of the earth.\""; static const char* small_sample_data = "\"What giants?\" said Sancho Panza."; -static const uint16_t test_iso_handle_complete_with_ts = - (0x0666 | (0x0002 << 12) | (0x0001 << 14)); -static const uint16_t test_iso_handle_complete_without_ts = - (0x0666 | (0x0002 << 12)); +static const uint16_t test_iso_handle_complete_with_ts = (0x0666 | (0x0002 << 12) | (0x0001 << 14)); +static const uint16_t test_iso_handle_complete_without_ts = (0x0666 | (0x0002 << 12)); static const uint16_t test_iso_handle_start_with_ts = (0x0666 | (0x0001 << 14)); -static const uint16_t test_iso_handle_start_without_ts = - (0x0666); // Also base handle +static const uint16_t test_iso_handle_start_without_ts = (0x0666); // Also base handle static const uint16_t test_iso_handle_continuation = (0x0666 | (0x0001 << 12)); static const uint16_t test_iso_handle_end = (0x0666 | (0x0003 << 12)); @@ -72,8 +69,7 @@ static uint32_t iso_timestamp = 0x32122321; static uint16_t iso_packet_seq = 0x1291; static bool iso_has_ts = true; -static BT_HDR* manufacture_packet_for_fragmentation(uint16_t event, - const char* data) { +static BT_HDR* manufacture_packet_for_fragmentation(uint16_t event, const char* data) { uint16_t data_length = strlen(data); uint16_t size = data_length; if (event == MSG_STACK_TO_HC_HCI_ISO) { @@ -108,9 +104,8 @@ static BT_HDR* manufacture_packet_for_fragmentation(uint16_t event, return packet; } -static void expect_packet_fragmented(uint16_t event, int max_acl_data_size, - BT_HDR* packet, const char* expected_data, - bool send_complete) { +static void expect_packet_fragmented(uint16_t event, int max_acl_data_size, BT_HDR* packet, + const char* expected_data, bool send_complete) { uint8_t* data = packet->data + packet->offset; int expected_data_offset; int length_to_check; @@ -133,15 +128,17 @@ static void expect_packet_fragmented(uint16_t event, int max_acl_data_size, STREAM_TO_UINT32(timestamp, data); ASSERT_EQ(timestamp, iso_timestamp); - if (send_complete) + if (send_complete) { ASSERT_EQ(test_iso_handle_complete_with_ts, handle); - else + } else { ASSERT_EQ(test_iso_handle_start_with_ts, handle); + } } else { - if (send_complete) + if (send_complete) { ASSERT_EQ(test_iso_handle_complete_without_ts, handle); - else + } else { ASSERT_EQ(test_iso_handle_start_without_ts, handle); + } hdr_size -= 4; } @@ -156,16 +153,18 @@ static void expect_packet_fragmented(uint16_t event, int max_acl_data_size, length_to_check = packet_data_length - hdr_size; } else { - if (!send_complete) + if (!send_complete) { ASSERT_EQ(test_iso_handle_continuation, handle); - else + } else { ASSERT_EQ(test_iso_handle_end, handle); + } length_to_check = packet_data_length; } - if (length_remaining > max_acl_data_size) + if (length_remaining > max_acl_data_size) { ASSERT_EQ(max_acl_data_size, packet_data_length); + } expected_data_offset = packet_index * max_acl_data_size; if (expected_data_offset > 0) { @@ -186,14 +185,16 @@ static void expect_packet_fragmented(uint16_t event, int max_acl_data_size, data_size_sum++; } - if (event == MSG_STACK_TO_HC_HCI_ISO) + if (event == MSG_STACK_TO_HC_HCI_ISO) { EXPECT_TRUE(send_complete == (data_size_sum == strlen(expected_data))); + } - if (send_complete) osi_free(packet); + if (send_complete) { + osi_free(packet); + } } -static void manufacture_iso_packet_and_then_reassemble(uint16_t event, - uint16_t iso_size, +static void manufacture_iso_packet_and_then_reassemble(uint16_t event, uint16_t iso_size, const char* data) { uint16_t data_length = strlen(data); uint16_t total_length; @@ -205,12 +206,14 @@ static void manufacture_iso_packet_and_then_reassemble(uint16_t event, // ISO length (2), packet seq (2), optional timestamp (4) total_length = data_length + 4; - if (iso_has_ts) total_length += 4; + if (iso_has_ts) { + total_length += 4; + } do { int length_to_send = (length_sent + (iso_size - 4) < total_length) - ? (iso_size - 4) - : (total_length - length_sent); + ? (iso_size - 4) + : (total_length - length_sent); packet = (BT_HDR*)osi_malloc(length_to_send + 4 + sizeof(BT_HDR)); packet_data = packet->data; @@ -261,8 +264,7 @@ static void manufacture_iso_packet_and_then_reassemble(uint16_t event, } while (length_sent < total_length); } -static void manufacture_packet_and_then_reassemble(uint16_t event, - uint16_t packet_size, +static void manufacture_packet_and_then_reassemble(uint16_t event, uint16_t packet_size, const char* data) { uint16_t data_length = strlen(data); @@ -280,10 +282,8 @@ static void manufacture_packet_and_then_reassemble(uint16_t event, } } -static void expect_packet_reassembled_iso(uint16_t event, BT_HDR* packet, - const char* expected_data, - uint32_t expected_timestamp, - uint16_t expected_packet_seq, +static void expect_packet_reassembled_iso(uint16_t event, BT_HDR* packet, const char* expected_data, + uint32_t expected_timestamp, uint16_t expected_packet_seq, bool is_complete = false) { uint16_t expected_data_length = strlen(expected_data); uint8_t* data = packet->data; @@ -302,13 +302,11 @@ static void expect_packet_reassembled_iso(uint16_t event, BT_HDR* packet, STREAM_TO_UINT32(timestamp, data); ASSERT_TRUE((packet->layer_specific & BT_ISO_HDR_CONTAINS_TS) != 0); ASSERT_EQ(timestamp, expected_timestamp); - ASSERT_EQ(is_complete ? test_iso_handle_complete_with_ts - : test_iso_handle_start_with_ts, + ASSERT_EQ(is_complete ? test_iso_handle_complete_with_ts : test_iso_handle_start_with_ts, handle); } else { ASSERT_TRUE((packet->layer_specific & BT_ISO_HDR_CONTAINS_TS) == 0); - ASSERT_EQ(is_complete ? test_iso_handle_complete_without_ts - : test_iso_handle_start_without_ts, + ASSERT_EQ(is_complete ? test_iso_handle_complete_without_ts : test_iso_handle_start_without_ts, handle); hdr_size -= 4; } @@ -331,14 +329,12 @@ static void expect_packet_reassembled_iso(uint16_t event, BT_HDR* packet, STUB_FUNCTION(void, fragmented_callback, (BT_HDR * packet, bool send_complete)) DURING(iso_fragmentation) { - expect_packet_fragmented(MSG_STACK_TO_HC_HCI_ISO, 10, packet, sample_data, - send_complete); + expect_packet_fragmented(MSG_STACK_TO_HC_HCI_ISO, 10, packet, sample_data, send_complete); return; } DURING(iso_no_fragmentation) { - expect_packet_fragmented(MSG_STACK_TO_HC_HCI_ISO, 42, packet, - small_sample_data, send_complete); + expect_packet_fragmented(MSG_STACK_TO_HC_HCI_ISO, 42, packet, small_sample_data, send_complete); return; } @@ -347,14 +343,13 @@ UNEXPECTED_CALL; STUB_FUNCTION(void, reassembled_callback, (BT_HDR * packet)) DURING(iso_reassembly) AT_CALL(0) { - expect_packet_reassembled_iso(MSG_HC_TO_STACK_HCI_ISO, packet, sample_data, - iso_timestamp, iso_packet_seq); + expect_packet_reassembled_iso(MSG_HC_TO_STACK_HCI_ISO, packet, sample_data, iso_timestamp, + iso_packet_seq); return; } DURING(iso_no_reassembly) AT_CALL(0) { - expect_packet_reassembled_iso(MSG_HC_TO_STACK_HCI_ISO, packet, - small_sample_data, iso_timestamp, + expect_packet_reassembled_iso(MSG_HC_TO_STACK_HCI_ISO, packet, small_sample_data, iso_timestamp, iso_packet_seq, true); return; } @@ -377,7 +372,7 @@ static void reset_for(TEST_MODES_T next) { } class PacketFragmenterTest : public ::testing::Test { - protected: +protected: void SetUp() override { fragmenter = packet_fragmenter_get_interface(); @@ -399,8 +394,7 @@ TEST_F(PacketFragmenterTest, test_iso_fragment_necessary) { reset_for(iso_fragmentation); iso_has_ts = true; - BT_HDR* packet = manufacture_packet_for_fragmentation(MSG_STACK_TO_HC_HCI_ISO, - sample_data); + BT_HDR* packet = manufacture_packet_for_fragmentation(MSG_STACK_TO_HC_HCI_ISO, sample_data); packet->event |= LOCAL_BLE_CONTROLLER_ID; fragmenter->fragment_and_dispatch(packet, get_iso_data_size()); @@ -411,8 +405,7 @@ TEST_F(PacketFragmenterTest, test_iso_no_fragment_necessary) { reset_for(iso_no_fragmentation); iso_has_ts = true; - BT_HDR* packet = manufacture_packet_for_fragmentation(MSG_STACK_TO_HC_HCI_ISO, - small_sample_data); + BT_HDR* packet = manufacture_packet_for_fragmentation(MSG_STACK_TO_HC_HCI_ISO, small_sample_data); packet->event |= LOCAL_BLE_CONTROLLER_ID; fragmenter->fragment_and_dispatch(packet, get_iso_data_size()); @@ -422,8 +415,7 @@ TEST_F(PacketFragmenterTest, test_iso_no_fragment_necessary) { TEST_F(PacketFragmenterTest, test_iso_fragment_necessary_no_ts) { reset_for(iso_fragmentation); iso_has_ts = false; - BT_HDR* packet = manufacture_packet_for_fragmentation(MSG_STACK_TO_HC_HCI_ISO, - sample_data); + BT_HDR* packet = manufacture_packet_for_fragmentation(MSG_STACK_TO_HC_HCI_ISO, sample_data); packet->event |= LOCAL_BLE_CONTROLLER_ID; fragmenter->fragment_and_dispatch(packet, get_iso_data_size()); @@ -433,8 +425,7 @@ TEST_F(PacketFragmenterTest, test_iso_fragment_necessary_no_ts) { TEST_F(PacketFragmenterTest, test_iso_no_fragment_necessary_no_ts) { reset_for(iso_no_fragmentation); iso_has_ts = false; - BT_HDR* packet = manufacture_packet_for_fragmentation(MSG_STACK_TO_HC_HCI_ISO, - small_sample_data); + BT_HDR* packet = manufacture_packet_for_fragmentation(MSG_STACK_TO_HC_HCI_ISO, small_sample_data); packet->event |= LOCAL_BLE_CONTROLLER_ID; fragmenter->fragment_and_dispatch(packet, get_iso_data_size()); @@ -444,8 +435,7 @@ TEST_F(PacketFragmenterTest, test_iso_no_fragment_necessary_no_ts) { TEST_F(PacketFragmenterTest, test_iso_no_reassembly_necessary) { reset_for(iso_no_reassembly); iso_has_ts = true; - manufacture_packet_and_then_reassemble(MSG_HC_TO_STACK_HCI_ISO, 50, - small_sample_data); + manufacture_packet_and_then_reassemble(MSG_HC_TO_STACK_HCI_ISO, 50, small_sample_data); ASSERT_EQ(strlen(small_sample_data), data_size_sum); EXPECT_CALL_COUNT(reassembled_callback, 1); @@ -454,8 +444,7 @@ TEST_F(PacketFragmenterTest, test_iso_no_reassembly_necessary) { TEST_F(PacketFragmenterTest, test_iso_reassembly_necessary) { reset_for(iso_reassembly); iso_has_ts = true; - manufacture_packet_and_then_reassemble(MSG_HC_TO_STACK_HCI_ISO, 42, - sample_data); + manufacture_packet_and_then_reassemble(MSG_HC_TO_STACK_HCI_ISO, 42, sample_data); ASSERT_EQ(strlen(sample_data), data_size_sum); EXPECT_CALL_COUNT(reassembled_callback, 1); @@ -464,8 +453,7 @@ TEST_F(PacketFragmenterTest, test_iso_reassembly_necessary) { TEST_F(PacketFragmenterTest, test_iso_no_reassembly_necessary_no_ts) { reset_for(iso_no_reassembly); iso_has_ts = false; - manufacture_packet_and_then_reassemble(MSG_HC_TO_STACK_HCI_ISO, (42 + 4), - small_sample_data); + manufacture_packet_and_then_reassemble(MSG_HC_TO_STACK_HCI_ISO, (42 + 4), small_sample_data); ASSERT_EQ(strlen(small_sample_data), data_size_sum); EXPECT_CALL_COUNT(reassembled_callback, 1); @@ -474,8 +462,7 @@ TEST_F(PacketFragmenterTest, test_iso_no_reassembly_necessary_no_ts) { TEST_F(PacketFragmenterTest, test_iso_reassembly_necessary_no_ts) { reset_for(iso_reassembly); iso_has_ts = false; - manufacture_packet_and_then_reassemble(MSG_HC_TO_STACK_HCI_ISO, 42, - sample_data); + manufacture_packet_and_then_reassemble(MSG_HC_TO_STACK_HCI_ISO, 42, sample_data); ASSERT_EQ(strlen(sample_data), data_size_sum); EXPECT_CALL_COUNT(reassembled_callback, 1); diff --git a/system/include/abstract_message_loop.h b/system/include/abstract_message_loop.h index 4e04c259145..5162da0f711 100644 --- a/system/include/abstract_message_loop.h +++ b/system/include/abstract_message_loop.h @@ -41,24 +41,22 @@ namespace btbase { #if defined(BASE_VER) && BASE_VER > 780000 class AbstractMessageLoop : public base::SingleThreadTaskExecutor { - public: +public: static scoped_refptr current_task_runner() { return base::SingleThreadTaskRunner::GetCurrentDefault(); } }; class AbstractTestMessageLoop : public base::test::TaskEnvironment { - public: +public: static scoped_refptr current_task_runner() { return base::SingleThreadTaskRunner::GetCurrentDefault(); } }; // Initialize the test task environment -#define DEFINE_TEST_TASK_ENV(var) \ - base::AbstractTestMessageLoop var { \ - base::test::TaskEnvironment::ThreadingMode::MAIN_THREAD_ONLY \ - } +#define DEFINE_TEST_TASK_ENV(var) \ + base::AbstractTestMessageLoop var { base::test::TaskEnvironment::ThreadingMode::MAIN_THREAD_ONLY } inline void set_message_loop_type_IO(base::Thread::Options& options) { options.message_pump_type = base::MessagePumpType::IO; @@ -66,7 +64,7 @@ inline void set_message_loop_type_IO(base::Thread::Options& options) { #else class AbstractMessageLoop : public base::MessageLoop { - public: +public: static scoped_refptr current_task_runner() { return base::MessageLoop::current()->task_runner(); } diff --git a/system/include/abstract_observer_list.h b/system/include/abstract_observer_list.h index 0f882599ec6..a3ab99d1ada 100644 --- a/system/include/abstract_observer_list.h +++ b/system/include/abstract_observer_list.h @@ -24,8 +24,7 @@ namespace btbase { // Checked Observers aren't supported in the older libchrome so use unchecked // ones instead to preserve behavior. template -class AbstractObserverList - : public base::ObserverList::Unchecked {}; +class AbstractObserverList : public base::ObserverList::Unchecked {}; #else diff --git a/system/include/hardware/avrcp/avrcp.h b/system/include/hardware/avrcp/avrcp.h index 9ba033ad0e1..32a3b7f3a44 100644 --- a/system/include/hardware/avrcp/avrcp.h +++ b/system/include/hardware/avrcp/avrcp.h @@ -72,15 +72,14 @@ struct ListItem { }; class MediaCallbacks { - public: - virtual void SendMediaUpdate(bool track_changed, bool play_state, - bool queue) = 0; +public: + virtual void SendMediaUpdate(bool track_changed, bool play_state, bool queue) = 0; virtual void SendFolderUpdate(bool available_players, bool addressed_players, bool uids_changed) = 0; virtual void SendActiveDeviceChanged(const RawAddress& address) = 0; - virtual void SendPlayerSettingsChanged( - std::vector attributes, std::vector values) = 0; + virtual void SendPlayerSettingsChanged(std::vector attributes, + std::vector values) = 0; virtual ~MediaCallbacks() = default; }; @@ -105,7 +104,7 @@ class MediaCallbacks { // allowing the threading model to be totally encapsulated and allow correct // behavior in case the threading model changes on either side. class MediaInterface { - public: +public: virtual void SendKeyEvent(uint8_t key, KeyState state) = 0; using SongInfoCallback = base::Callback; @@ -116,28 +115,25 @@ class MediaInterface { // Contains the current queue and the media ID of the currently playing item // in the queue - using NowPlayingCallback = - base::Callback)>; + using NowPlayingCallback = base::Callback)>; virtual void GetNowPlayingList(NowPlayingCallback now_playing_cb) = 0; // TODO (apanicke): Use a map with the ID as the key instead of vector // in follow up cleanup patches. This allows simplification of the // MediaPlayerInfo object using MediaListCallback = - base::Callback)>; + base::Callback)>; virtual void GetMediaPlayerList(MediaListCallback list_cb) = 0; using FolderItemsCallback = base::Callback)>; virtual void GetFolderItems(uint16_t player_id, std::string media_id, FolderItemsCallback folder_cb) = 0; - using SetBrowsedPlayerCallback = base::Callback; - virtual void SetBrowsedPlayer(uint16_t player_id, - SetBrowsedPlayerCallback browse_cb) = 0; + using SetBrowsedPlayerCallback = + base::Callback; + virtual void SetBrowsedPlayer(uint16_t player_id, SetBrowsedPlayerCallback browse_cb) = 0; - virtual void PlayItem(uint16_t player_id, bool now_playing, - std::string media_id) = 0; + virtual void PlayItem(uint16_t player_id, bool now_playing, std::string media_id) = 0; virtual void SetActiveDevice(const RawAddress& address) = 0; @@ -150,7 +146,7 @@ class MediaInterface { }; class VolumeInterface { - public: +public: // TODO (apanicke): Investigate the best value type for volume. Right now it // is a value from 0-127 because thats what AVRCP uses. using VolumeChangedCb = base::Callback; @@ -162,8 +158,7 @@ class VolumeInterface { // Indicate that a device has been connected that does support absolute // volume. The callback will be immediately called with the current volume // which will be sent to the device. - virtual void DeviceConnected(const RawAddress& bdaddr, - VolumeChangedCb cb) = 0; + virtual void DeviceConnected(const RawAddress& bdaddr, VolumeChangedCb cb) = 0; // Indicate that a device has been disconnected from AVRCP. Will unregister // any callbacks if absolute volume is supported. @@ -175,36 +170,32 @@ class VolumeInterface { }; class PlayerSettingsInterface { - public: - using ListPlayerSettingsCallback = - base::Callback attributes)>; +public: + using ListPlayerSettingsCallback = base::Callback attributes)>; virtual void ListPlayerSettings(ListPlayerSettingsCallback cb) = 0; - using ListPlayerSettingValuesCallback = base::Callback values)>; + using ListPlayerSettingValuesCallback = + base::Callback values)>; virtual void ListPlayerSettingValues(PlayerAttribute setting, ListPlayerSettingValuesCallback cb) = 0; using GetCurrentPlayerSettingValueCallback = base::Callback attributes, std::vector values)>; - virtual void GetCurrentPlayerSettingValue( - std::vector attributes, - GetCurrentPlayerSettingValueCallback cb) = 0; + std::vector attributes, std::vector values)>; + virtual void GetCurrentPlayerSettingValue(std::vector attributes, + GetCurrentPlayerSettingValueCallback cb) = 0; using SetPlayerSettingValueCallback = base::Callback; virtual void SetPlayerSettings(std::vector attributes, - std::vector values, - SetPlayerSettingValueCallback cb) = 0; + std::vector values, SetPlayerSettingValueCallback cb) = 0; virtual ~PlayerSettingsInterface() = default; }; class ServiceInterface { - public: +public: // mediaInterface can not be null. If volumeInterface is null then Absolute // Volume is disabled. - virtual void Init(MediaInterface* mediaInterface, - VolumeInterface* volumeInterface, + virtual void Init(MediaInterface* mediaInterface, VolumeInterface* volumeInterface, PlayerSettingsInterface* player_settings_interface) = 0; virtual void RegisterBipServer(int psm) = 0; virtual void UnregisterBipServer() = 0; @@ -213,7 +204,7 @@ class ServiceInterface { virtual void SetBipClientStatus(const RawAddress& bdaddr, bool connected) = 0; virtual bool Cleanup() = 0; - protected: +protected: virtual ~ServiceInterface() = default; }; diff --git a/system/include/hardware/avrcp/avrcp_common.h b/system/include/hardware/avrcp/avrcp_common.h index 1c6eb4f636b..8c46efd6483 100644 --- a/system/include/hardware/avrcp/avrcp_common.h +++ b/system/include/hardware/avrcp/avrcp_common.h @@ -16,10 +16,10 @@ #pragma once -#include - #include +#include + namespace bluetooth { namespace avrcp { @@ -168,7 +168,7 @@ enum class PlayerShuffleValue : uint8_t { }; class AttributeEntry { - public: +public: AttributeEntry(const Attribute& attribute, const std::string& value) : attribute_(attribute), value_(value) {} @@ -199,11 +199,9 @@ class AttributeEntry { bool empty() { return value_.empty(); } - bool operator<(const AttributeEntry& rhs) const { - return attribute_ < rhs.attribute_; - } + bool operator<(const AttributeEntry& rhs) const { return attribute_ < rhs.attribute_; } - private: +private: Attribute attribute_; std::string value_; }; @@ -247,12 +245,8 @@ struct FolderItem { bool is_playable_; std::string name_; - FolderItem(uint64_t uid, uint8_t folder_type, bool is_playable, - const std::string& name) - : uid_(uid), - folder_type_(folder_type), - is_playable_(is_playable), - name_(name) { + FolderItem(uint64_t uid, uint8_t folder_type, bool is_playable, const std::string& name) + : uid_(uid), folder_type_(folder_type), is_playable_(is_playable), name_(name) { if (name_.size() > MAX_FIELD_LEN) { name_.resize(MAX_FIELD_LEN); } @@ -283,8 +277,7 @@ struct MediaElementItem { // Truncate the name and attribute fields so that we don't have a single item // that can exceed the Browsing MTU - MediaElementItem(uint64_t uid, const std::string& name, - std::set attributes) + MediaElementItem(uint64_t uid, const std::string& name, std::set attributes) : uid_(uid), name_(name) { if (name_.size() > MAX_FIELD_LEN) { name_.resize(MAX_FIELD_LEN); diff --git a/system/include/hardware/avrcp/avrcp_logging_helper.h b/system/include/hardware/avrcp/avrcp_logging_helper.h index 79792eafc57..d5a798ce9f4 100644 --- a/system/include/hardware/avrcp/avrcp_logging_helper.h +++ b/system/include/hardware/avrcp/avrcp_logging_helper.h @@ -211,9 +211,7 @@ inline std::string ScopeText(const Scope& scope) { } } -inline std::ostream& operator<<(std::ostream& os, const Scope& pdu) { - return os << ScopeText(pdu); -} +inline std::ostream& operator<<(std::ostream& os, const Scope& pdu) { return os << ScopeText(pdu); } inline std::string DirectionText(const Direction& dir) { switch (dir) { @@ -265,8 +263,7 @@ inline std::string PlayerRepeatValueText(const PlayerRepeatValue& val) { return "Unknown Player Repeat Value: " + loghex((uint8_t)val); } -inline std::ostream& operator<<(std::ostream& os, - const PlayerRepeatValue& val) { +inline std::ostream& operator<<(std::ostream& os, const PlayerRepeatValue& val) { return os << PlayerRepeatValueText(val); } @@ -279,8 +276,7 @@ inline std::string PlayerShuffleValueText(const PlayerShuffleValue& val) { return "Unknown Player Shuffle Value: " + loghex((uint8_t)val); } -inline std::ostream& operator<<(std::ostream& os, - const PlayerShuffleValue& val) { +inline std::ostream& operator<<(std::ostream& os, const PlayerShuffleValue& val) { return os << PlayerShuffleValueText(val); } diff --git a/system/include/hardware/ble_advertiser.h b/system/include/hardware/ble_advertiser.h index 69d8eff8117..11a753e92ae 100644 --- a/system/include/hardware/ble_advertiser.h +++ b/system/include/hardware/ble_advertiser.h @@ -54,46 +54,38 @@ struct PeriodicAdvertisingParameters { * All callbacks are invoked on the JNI thread */ class AdvertisingCallbacks { - public: +public: virtual ~AdvertisingCallbacks() = default; - virtual void OnAdvertisingSetStarted(int reg_id, uint8_t advertiser_id, - int8_t tx_power, uint8_t status) = 0; - virtual void OnAdvertisingEnabled(uint8_t advertiser_id, bool enable, - uint8_t status) = 0; + virtual void OnAdvertisingSetStarted(int reg_id, uint8_t advertiser_id, int8_t tx_power, + uint8_t status) = 0; + virtual void OnAdvertisingEnabled(uint8_t advertiser_id, bool enable, uint8_t status) = 0; virtual void OnAdvertisingDataSet(uint8_t advertiser_id, uint8_t status) = 0; virtual void OnScanResponseDataSet(uint8_t advertiser_id, uint8_t status) = 0; - virtual void OnAdvertisingParametersUpdated(uint8_t advertiser_id, - int8_t tx_power, + virtual void OnAdvertisingParametersUpdated(uint8_t advertiser_id, int8_t tx_power, uint8_t status) = 0; - virtual void OnPeriodicAdvertisingParametersUpdated(uint8_t advertiser_id, - uint8_t status) = 0; - virtual void OnPeriodicAdvertisingDataSet(uint8_t advertiser_id, - uint8_t status) = 0; - virtual void OnPeriodicAdvertisingEnabled(uint8_t advertiser_id, bool enable, - uint8_t status) = 0; + virtual void OnPeriodicAdvertisingParametersUpdated(uint8_t advertiser_id, uint8_t status) = 0; + virtual void OnPeriodicAdvertisingDataSet(uint8_t advertiser_id, uint8_t status) = 0; + virtual void OnPeriodicAdvertisingEnabled(uint8_t advertiser_id, bool enable, uint8_t status) = 0; virtual void OnOwnAddressRead(uint8_t advertiser_id, uint8_t address_type, RawAddress address) = 0; }; class BleAdvertiserInterface { - public: +public: virtual ~BleAdvertiserInterface() = default; /** Callback invoked when multi-adv operation has completed */ using StatusCallback = base::Callback; - using IdStatusCallback = - base::Callback; - using IdTxPowerStatusCallback = - base::Callback; - using ParametersCallback = - base::Callback; + using IdStatusCallback = base::Callback; + using IdTxPowerStatusCallback = base::Callback; + using ParametersCallback = base::Callback; /** Registers an advertiser with the stack */ virtual void RegisterAdvertiser(IdStatusCallback) = 0; using GetAddressCallback = - base::Callback; + base::Callback; virtual void GetOwnAddress(uint8_t advertiser_id, GetAddressCallback cb) = 0; /* Set the parameters as per spec, user manual specified values */ @@ -101,22 +93,20 @@ class BleAdvertiserInterface { ParametersCallback cb) = 0; /* Setup the data */ - virtual void SetData(int advertiser_id, bool set_scan_rsp, - std::vector data, StatusCallback cb) = 0; + virtual void SetData(int advertiser_id, bool set_scan_rsp, std::vector data, + StatusCallback cb) = 0; /* Enable the advertising instance */ - virtual void Enable(uint8_t advertiser_id, bool enable, StatusCallback cb, - uint16_t duration, uint8_t maxExtAdvEvents, - StatusCallback timeout_cb) = 0; + virtual void Enable(uint8_t advertiser_id, bool enable, StatusCallback cb, uint16_t duration, + uint8_t maxExtAdvEvents, StatusCallback timeout_cb) = 0; /* Unregisters an advertiser */ virtual void Unregister(uint8_t advertiser_id) = 0; virtual void StartAdvertising(uint8_t advertiser_id, StatusCallback cb, - AdvertiseParameters params, - std::vector advertise_data, - std::vector scan_response_data, - int timeout_s, StatusCallback timeout_cb) = 0; + AdvertiseParameters params, std::vector advertise_data, + std::vector scan_response_data, int timeout_s, + StatusCallback timeout_cb) = 0; /** Start the advertising set. This include registering, setting all * parameters and data, and enabling it. |register_cb| is called when the set @@ -124,28 +114,25 @@ class BleAdvertiserInterface { * |reg_id| is the callback id assigned from upper or native layer. * |client_id| is the callbacks client id for jni or native layer. */ - virtual void StartAdvertisingSet( - uint8_t client_id, int reg_id, IdTxPowerStatusCallback register_cb, - AdvertiseParameters params, std::vector advertise_data, - std::vector scan_response_data, - PeriodicAdvertisingParameters periodic_params, - std::vector periodic_data, uint16_t duration, - uint8_t maxExtAdvEvents, IdStatusCallback timeout_cb) = 0; - - virtual void SetPeriodicAdvertisingParameters( - int advertiser_id, PeriodicAdvertisingParameters parameters, - StatusCallback cb) = 0; - - virtual void SetPeriodicAdvertisingData(int advertiser_id, - std::vector data, + virtual void StartAdvertisingSet(uint8_t client_id, int reg_id, + IdTxPowerStatusCallback register_cb, AdvertiseParameters params, + std::vector advertise_data, + std::vector scan_response_data, + PeriodicAdvertisingParameters periodic_params, + std::vector periodic_data, uint16_t duration, + uint8_t maxExtAdvEvents, IdStatusCallback timeout_cb) = 0; + + virtual void SetPeriodicAdvertisingParameters(int advertiser_id, + PeriodicAdvertisingParameters parameters, + StatusCallback cb) = 0; + + virtual void SetPeriodicAdvertisingData(int advertiser_id, std::vector data, StatusCallback cb) = 0; - virtual void SetPeriodicAdvertisingEnable(int advertiser_id, bool enable, - bool include_adi, + virtual void SetPeriodicAdvertisingEnable(int advertiser_id, bool enable, bool include_adi, StatusCallback cb) = 0; virtual void RegisterCallbacks(AdvertisingCallbacks* callbacks) = 0; - virtual void RegisterCallbacksNative(AdvertisingCallbacks* callbacks, - uint8_t client_id) = 0; + virtual void RegisterCallbacksNative(AdvertisingCallbacks* callbacks, uint8_t client_id) = 0; }; #endif /* ANDROID_INCLUDE_BLE_ADVERTISER_H */ diff --git a/system/include/hardware/ble_scanner.h b/system/include/hardware/ble_scanner.h index f01194896a0..4e42d68fc5f 100644 --- a/system/include/hardware/ble_scanner.h +++ b/system/include/hardware/ble_scanner.h @@ -29,24 +29,20 @@ #include "bt_gatt_types.h" /** Callback invoked when batchscan reports are obtained */ -typedef void (*batchscan_reports_callback)(int client_if, int status, - int report_format, int num_records, - std::vector data); +typedef void (*batchscan_reports_callback)(int client_if, int status, int report_format, + int num_records, std::vector data); /** Callback invoked when batchscan storage threshold limit is crossed */ typedef void (*batchscan_threshold_callback)(int client_if); /** Track ADV VSE callback invoked when tracked device is found or lost */ -typedef void (*track_adv_event_callback)( - btgatt_track_adv_info_t* p_track_adv_info); +typedef void (*track_adv_event_callback)(btgatt_track_adv_info_t* p_track_adv_info); /** Callback for scan results */ -typedef void (*scan_result_callback)(uint16_t event_type, uint8_t addr_type, - RawAddress* bda, uint8_t primary_phy, - uint8_t secondary_phy, - uint8_t advertising_sid, int8_t tx_power, - int8_t rssi, uint16_t periodic_adv_int, - std::vector adv_data, +typedef void (*scan_result_callback)(uint16_t event_type, uint8_t addr_type, RawAddress* bda, + uint8_t primary_phy, uint8_t secondary_phy, + uint8_t advertising_sid, int8_t tx_power, int8_t rssi, + uint16_t periodic_adv_int, std::vector adv_data, RawAddress* original_bda); typedef struct { @@ -57,7 +53,7 @@ typedef struct { } btgatt_scanner_callbacks_t; class AdvertisingTrackInfo { - public: +public: // For MSFT-based advertisement monitor. uint8_t monitor_handle; uint8_t scanner_id; @@ -80,72 +76,57 @@ class AdvertisingTrackInfo { * All callbacks are invoked on the JNI thread */ class ScanningCallbacks { - public: +public: virtual ~ScanningCallbacks() = default; - virtual void OnScannerRegistered(const bluetooth::Uuid app_uuid, - uint8_t scannerId, uint8_t status) = 0; - virtual void OnSetScannerParameterComplete(uint8_t scannerId, - uint8_t status) = 0; - virtual void OnScanResult(uint16_t event_type, uint8_t addr_type, - RawAddress bda, uint8_t primary_phy, - uint8_t secondary_phy, uint8_t advertising_sid, - int8_t tx_power, int8_t rssi, - uint16_t periodic_adv_int, + virtual void OnScannerRegistered(const bluetooth::Uuid app_uuid, uint8_t scannerId, + uint8_t status) = 0; + virtual void OnSetScannerParameterComplete(uint8_t scannerId, uint8_t status) = 0; + virtual void OnScanResult(uint16_t event_type, uint8_t addr_type, RawAddress bda, + uint8_t primary_phy, uint8_t secondary_phy, uint8_t advertising_sid, + int8_t tx_power, int8_t rssi, uint16_t periodic_adv_int, std::vector adv_data) = 0; - virtual void OnTrackAdvFoundLost( - AdvertisingTrackInfo advertising_track_info) = 0; - virtual void OnBatchScanReports(int client_if, int status, int report_format, - int num_records, + virtual void OnTrackAdvFoundLost(AdvertisingTrackInfo advertising_track_info) = 0; + virtual void OnBatchScanReports(int client_if, int status, int report_format, int num_records, std::vector data) = 0; virtual void OnBatchScanThresholdCrossed(int client_if) = 0; - virtual void OnPeriodicSyncStarted(int reg_id, uint8_t status, - uint16_t sync_handle, - uint8_t advertising_sid, - uint8_t address_type, RawAddress address, - uint8_t phy, uint16_t interval) = 0; - virtual void OnPeriodicSyncReport(uint16_t sync_handle, int8_t tx_power, - int8_t rssi, uint8_t status, - std::vector data) = 0; + virtual void OnPeriodicSyncStarted(int reg_id, uint8_t status, uint16_t sync_handle, + uint8_t advertising_sid, uint8_t address_type, + RawAddress address, uint8_t phy, uint16_t interval) = 0; + virtual void OnPeriodicSyncReport(uint16_t sync_handle, int8_t tx_power, int8_t rssi, + uint8_t status, std::vector data) = 0; virtual void OnPeriodicSyncLost(uint16_t sync_handle) = 0; - virtual void OnPeriodicSyncTransferred(int pa_source, uint8_t status, - RawAddress address) = 0; + virtual void OnPeriodicSyncTransferred(int pa_source, uint8_t status, RawAddress address) = 0; virtual void OnBigInfoReport(uint16_t sync_handle, bool encrypted) = 0; }; class BleScannerInterface { - public: +public: virtual ~BleScannerInterface() = default; - using RegisterCallback = - base::Callback; + using RegisterCallback = base::Callback; using Callback = base::Callback; - using EnableCallback = - base::Callback; + using EnableCallback = base::Callback; - using FilterParamSetupCallback = - base::Callback; + using FilterParamSetupCallback = base::Callback; using FilterConfigCallback = - base::Callback; + base::Callback; #if TARGET_FLOSS using MsftAdvMonitorAddCallback = - base::Callback; + base::Callback; - using MsftAdvMonitorRemoveCallback = - base::Callback; + using MsftAdvMonitorRemoveCallback = base::Callback; - using MsftAdvMonitorEnableCallback = - base::Callback; + using MsftAdvMonitorEnableCallback = base::Callback; #endif /** Registers a scanner with the stack */ - virtual void RegisterScanner(const bluetooth::Uuid& app_uuid, - RegisterCallback) = 0; + virtual void RegisterScanner(const bluetooth::Uuid& app_uuid, RegisterCallback) = 0; /** Unregister a scanner from the stack */ virtual void Unregister(int scanner_id) = 0; @@ -154,10 +135,9 @@ class BleScannerInterface { virtual void Scan(bool start) = 0; /** Setup scan filter params */ - virtual void ScanFilterParamSetup( - uint8_t client_if, uint8_t action, uint8_t filt_index, - std::unique_ptr filt_param, - FilterParamSetupCallback cb) = 0; + virtual void ScanFilterParamSetup(uint8_t client_if, uint8_t action, uint8_t filt_index, + std::unique_ptr filt_param, + FilterParamSetupCallback cb) = 0; /** Configure a scan filter condition */ virtual void ScanFilterAdd(int filter_index, std::vector filters, @@ -174,33 +154,27 @@ class BleScannerInterface { virtual bool IsMsftSupported() = 0; /** Configures MSFT scan filter (advertisement monitor) */ - virtual void MsftAdvMonitorAdd(MsftAdvMonitor monitor, - MsftAdvMonitorAddCallback cb) = 0; + virtual void MsftAdvMonitorAdd(MsftAdvMonitor monitor, MsftAdvMonitorAddCallback cb) = 0; /** Removes previously added MSFT scan filter */ - virtual void MsftAdvMonitorRemove(uint8_t monitor_handle, - MsftAdvMonitorRemoveCallback cb) = 0; + virtual void MsftAdvMonitorRemove(uint8_t monitor_handle, MsftAdvMonitorRemoveCallback cb) = 0; /** Enable / disable MSFT scan filter feature */ - virtual void MsftAdvMonitorEnable(bool enable, - MsftAdvMonitorEnableCallback cb) = 0; + virtual void MsftAdvMonitorEnable(bool enable, MsftAdvMonitorEnableCallback cb) = 0; #endif /** Sets the LE scan interval and window in units of N*0.625 msec */ - virtual void SetScanParameters(int scanner_id, uint8_t scan_type, - int scan_interval, int scan_window, - int scan_phy, Callback cb) = 0; + virtual void SetScanParameters(int scanner_id, uint8_t scan_type, int scan_interval, + int scan_window, int scan_phy, Callback cb) = 0; /* Configure the batchscan storage */ virtual void BatchscanConfigStorage(int client_if, int batch_scan_full_max, - int batch_scan_trunc_max, - int batch_scan_notify_threshold, + int batch_scan_trunc_max, int batch_scan_notify_threshold, Callback cb) = 0; /* Enable batchscan */ - virtual void BatchscanEnable(int scan_mode, int scan_interval, - int scan_window, int addr_type, int discard_rule, - Callback cb) = 0; + virtual void BatchscanEnable(int scan_mode, int scan_interval, int scan_window, int addr_type, + int discard_rule, Callback cb) = 0; /* Disable batchscan */ virtual void BatchscanDisable(Callback cb) = 0; @@ -208,20 +182,20 @@ class BleScannerInterface { /* Read out batchscan reports */ virtual void BatchscanReadReports(int client_if, int scan_mode) = 0; - virtual void StartSync(uint8_t sid, RawAddress address, uint16_t skip, - uint16_t timeout, int reg_id) = 0; + virtual void StartSync(uint8_t sid, RawAddress address, uint16_t skip, uint16_t timeout, + int reg_id) = 0; virtual void StopSync(uint16_t handle) = 0; virtual void RegisterCallbacks(ScanningCallbacks* callbacks) = 0; virtual void CancelCreateSync(uint8_t sid, RawAddress address) = 0; - virtual void TransferSync(RawAddress address, uint16_t service_data, - uint16_t sync_handle, int pa_source) = 0; - virtual void TransferSetInfo(RawAddress address, uint16_t service_data, - uint8_t adv_handle, int pa_source) = 0; - virtual void SyncTxParameters(RawAddress addr, uint8_t mode, uint16_t skip, - uint16_t timeout, int reg_id) = 0; + virtual void TransferSync(RawAddress address, uint16_t service_data, uint16_t sync_handle, + int pa_source) = 0; + virtual void TransferSetInfo(RawAddress address, uint16_t service_data, uint8_t adv_handle, + int pa_source) = 0; + virtual void SyncTxParameters(RawAddress addr, uint8_t mode, uint16_t skip, uint16_t timeout, + int reg_id) = 0; }; #endif /* ANDROID_INCLUDE_BLE_SCANNER_H */ diff --git a/system/include/hardware/bluetooth.h b/system/include/hardware/bluetooth.h index 05088f0a14a..31041f1d388 100644 --- a/system/include/hardware/bluetooth.h +++ b/system/include/hardware/bluetooth.h @@ -63,7 +63,9 @@ #define BT_BQR_ID "bqr" /** Bluetooth Device Name */ -typedef struct { uint8_t name[249]; } __attribute__((packed)) bt_bdname_t; +typedef struct { + uint8_t name[249]; +} __attribute__((packed)) bt_bdname_t; /** Bluetooth Adapter Visibility Modes*/ typedef enum { @@ -163,7 +165,9 @@ inline std::string bt_status_text(const bt_status_t& status) { typedef uint8_t bt_hci_error_code_t; /** Bluetooth PinKey Code */ -typedef struct { uint8_t pin[16]; } __attribute__((packed)) bt_pin_code_t; +typedef struct { + uint8_t pin[16]; +} __attribute__((packed)) bt_pin_code_t; typedef struct { uint8_t status; @@ -181,16 +185,10 @@ typedef struct { } __attribute__((packed)) bt_uid_traffic_t; /** Bluetooth Adapter Discovery state */ -typedef enum { - BT_DISCOVERY_STOPPED, - BT_DISCOVERY_STARTED -} bt_discovery_state_t; +typedef enum { BT_DISCOVERY_STOPPED, BT_DISCOVERY_STARTED } bt_discovery_state_t; /** Bluetooth ACL connection state */ -typedef enum { - BT_ACL_STATE_CONNECTED, - BT_ACL_STATE_DISCONNECTED -} bt_acl_state_t; +typedef enum { BT_ACL_STATE_CONNECTED, BT_ACL_STATE_DISCONNECTED } bt_acl_state_t; /** Bluetooth ACL connection direction */ typedef enum { @@ -446,19 +444,19 @@ typedef struct bt_oob_data_s { // Both bool is_valid = false; /* Default to invalid data; force caller to verify */ uint8_t address[OOB_ADDRESS_SIZE]; - uint8_t c[OOB_C_SIZE]; /* Simple Pairing Hash C-192/256 (Classic or LE) */ - uint8_t r[OOB_R_SIZE]; /* Simple Pairing Randomizer R-192/256 (Classic or LE) */ + uint8_t c[OOB_C_SIZE]; /* Simple Pairing Hash C-192/256 (Classic or LE) */ + uint8_t r[OOB_R_SIZE]; /* Simple Pairing Randomizer R-192/256 (Classic or LE) */ uint8_t device_name[OOB_NAME_MAX_SIZE]; /* Name of the device */ // Classic uint8_t oob_data_length[OOB_DATA_LEN_SIZE]; /* Classic only data Length. Value includes this in length */ - uint8_t class_of_device[OOB_COD_SIZE]; /* Class of Device (Classic or LE) */ + uint8_t class_of_device[OOB_COD_SIZE]; /* Class of Device (Classic or LE) */ // LE - uint8_t le_device_role; /* Supported and preferred role of device */ - uint8_t sm_tk[OOB_TK_SIZE]; /* Security Manager TK Value (LE Only) */ - uint8_t le_flags; /* LE Flags for discoverability and features */ + uint8_t le_device_role; /* Supported and preferred role of device */ + uint8_t sm_tk[OOB_TK_SIZE]; /* Security Manager TK Value (LE Only) */ + uint8_t le_flags; /* LE Flags for discoverability and features */ uint8_t le_appearance[OOB_LE_APPEARANCE_SIZE]; /* For the appearance of the device */ } bt_oob_data_t; @@ -470,11 +468,7 @@ typedef enum { } bt_device_type_t; /** Bluetooth Bond state */ -typedef enum { - BT_BOND_STATE_NONE, - BT_BOND_STATE_BONDING, - BT_BOND_STATE_BONDED -} bt_bond_state_t; +typedef enum { BT_BOND_STATE_NONE, BT_BOND_STATE_BONDING, BT_BOND_STATE_BONDED } bt_bond_state_t; /** Bluetooth SSP Bonding Variant */ typedef enum { @@ -500,31 +494,26 @@ typedef void (*adapter_state_changed_callback)(bt_state_t state); * If this is going to be handled in the Java framework, then we do not need * to manage sessions here. */ -typedef void (*adapter_properties_callback)(bt_status_t status, - int num_properties, +typedef void (*adapter_properties_callback)(bt_status_t status, int num_properties, bt_property_t* properties); /** GET/SET Remote Device Properties callback */ /** TODO: For remote device properties, do not see a need to get/set * multiple properties - num_properties shall be 1 */ -typedef void (*remote_device_properties_callback)(bt_status_t status, - RawAddress* bd_addr, - int num_properties, - bt_property_t* properties); +typedef void (*remote_device_properties_callback)(bt_status_t status, RawAddress* bd_addr, + int num_properties, bt_property_t* properties); /** New device discovered callback */ /** If EIR data is not present, then BD_NAME and RSSI shall be NULL and -1 * respectively */ -typedef void (*device_found_callback)(int num_properties, - bt_property_t* properties); +typedef void (*device_found_callback)(int num_properties, bt_property_t* properties); /** Discovery state changed callback */ typedef void (*discovery_state_changed_callback)(bt_discovery_state_t state); /** Bluetooth Legacy PinKey Request callback */ -typedef void (*pin_request_callback)(RawAddress* remote_bd_addr, - bt_bdname_t* bd_name, uint32_t cod, +typedef void (*pin_request_callback)(RawAddress* remote_bd_addr, bt_bdname_t* bd_name, uint32_t cod, bool min_16_digit); /** Bluetooth SSP Request callback - Just Works & Numeric Comparison*/ @@ -532,16 +521,13 @@ typedef void (*pin_request_callback)(RawAddress* remote_bd_addr, * BT_SSP_PAIRING_PASSKEY_ENTRY */ /* TODO: Passkey request callback shall not be needed for devices with display * capability. We still need support this in the stack for completeness */ -typedef void (*ssp_request_callback)(RawAddress* remote_bd_addr, - bt_ssp_variant_t pairing_variant, +typedef void (*ssp_request_callback)(RawAddress* remote_bd_addr, bt_ssp_variant_t pairing_variant, uint32_t pass_key); /** Bluetooth Bond state changed callback */ /* Invoked in response to create_bond, cancel_bond or remove_bond */ -typedef void (*bond_state_changed_callback)(bt_status_t status, - RawAddress* remote_bd_addr, - bt_bond_state_t state, - int fail_reason); +typedef void (*bond_state_changed_callback)(bt_status_t status, RawAddress* remote_bd_addr, + bt_bond_state_t state, int fail_reason); /** Bluetooth Address consolidate callback */ /* Callback to inform upper layer that these two addresses come from same @@ -556,16 +542,16 @@ typedef void (*le_address_associate_callback)(RawAddress* main_bd_addr, RawAddress* secondary_bd_addr); /** Bluetooth ACL connection state changed callback */ -typedef void (*acl_state_changed_callback)( - bt_status_t status, RawAddress* remote_bd_addr, bt_acl_state_t state, - int transport_link_type, bt_hci_error_code_t hci_reason, - bt_conn_direction_t direction, uint16_t acl_handle); +typedef void (*acl_state_changed_callback)(bt_status_t status, RawAddress* remote_bd_addr, + bt_acl_state_t state, int transport_link_type, + bt_hci_error_code_t hci_reason, + bt_conn_direction_t direction, uint16_t acl_handle); /** Bluetooth link quality report callback */ -typedef void (*link_quality_report_callback)( - uint64_t timestamp, int report_id, int rssi, int snr, - int retransmission_count, int packets_not_receive_count, - int negative_acknowledgement_count); +typedef void (*link_quality_report_callback)(uint64_t timestamp, int report_id, int rssi, int snr, + int retransmission_count, + int packets_not_receive_count, + int negative_acknowledgement_count); /** Switch the buffer size callback */ typedef void (*switch_buffer_size_callback)(bool is_low_latency_buffer_size); @@ -585,8 +571,7 @@ typedef void (*callback_thread_event)(bt_cb_thread_evt evt); /** Bluetooth Test Mode Callback */ /* Receive any HCI event from controller. Must be in DUT Mode for this callback * to be received */ -typedef void (*dut_mode_recv_callback)(uint16_t opcode, uint8_t* buf, - uint8_t len); +typedef void (*dut_mode_recv_callback)(uint16_t opcode, uint8_t* buf, uint8_t len); /* LE Test mode callbacks * This callback shall be invoked whenever the le_tx_test, le_rx_test or @@ -606,8 +591,7 @@ typedef void (*energy_info_callback)(bt_activity_energy_info* energy_info, bt_uid_traffic_t* uid_data); /** Callback invoked when OOB data is returned from the controller */ -typedef void (*generate_local_oob_data_callback)(tBT_TRANSPORT transport, - bt_oob_data_t oob_data); +typedef void (*generate_local_oob_data_callback)(tBT_TRANSPORT transport, bt_oob_data_t oob_data); typedef void (*key_missing_callback)(const RawAddress bd_addr); @@ -691,9 +675,8 @@ typedef struct { * that cannot change during run. The |is_atv| flag indicates whether the * local device is an Android TV */ - int (*init)(bt_callbacks_t* callbacks, bool guest_mode, - bool is_common_criteria_mode, int config_compare_result, - const char** init_flags, bool is_atv, + int (*init)(bt_callbacks_t* callbacks, bool guest_mode, bool is_common_criteria_mode, + int config_compare_result, const char** init_flags, bool is_atv, const char* user_data_directory); /** Enable Bluetooth. */ @@ -729,16 +712,13 @@ typedef struct { int (*get_remote_device_properties)(RawAddress* remote_addr); /** Get Remote Device property of 'type' */ - int (*get_remote_device_property)(RawAddress* remote_addr, - bt_property_type_t type); + int (*get_remote_device_property)(RawAddress* remote_addr, bt_property_type_t type); /** Set Remote Device property of 'type' */ - int (*set_remote_device_property)(RawAddress* remote_addr, - const bt_property_t* property); + int (*set_remote_device_property)(RawAddress* remote_addr, const bt_property_t* property); /** Get Remote Device's service record for the given UUID */ - int (*get_remote_service_record)(const RawAddress& remote_addr, - const bluetooth::Uuid& uuid); + int (*get_remote_service_record)(const RawAddress& remote_addr, const bluetooth::Uuid& uuid); /** Start service discovery with transport to get remote services */ int (*get_remote_services)(RawAddress* remote_addr, int transport); @@ -757,8 +737,7 @@ typedef struct { /** Create Bluetooth Bond using out of band data */ int (*create_bond_out_of_band)(const RawAddress* bd_addr, int transport, - const bt_oob_data_t* p192_data, - const bt_oob_data_t* p256_data); + const bt_oob_data_t* p192_data, const bt_oob_data_t* p256_data); /** Remove Bond */ int (*remove_bond)(const RawAddress* bd_addr); @@ -785,8 +764,8 @@ typedef struct { * BT_SSP_VARIANT_CONSENT * For BT_SSP_VARIANT_PASSKEY_ENTRY, if accept==FALSE, then passkey * shall be zero */ - int (*ssp_reply)(const RawAddress* bd_addr, bt_ssp_variant_t variant, - uint8_t accept, uint32_t passkey); + int (*ssp_reply)(const RawAddress* bd_addr, bt_ssp_variant_t variant, uint8_t accept, + uint32_t passkey); /** Get Bluetooth profile interface */ const void* (*get_profile_interface)(const char* profile_id); @@ -846,8 +825,7 @@ typedef struct { * NOTE: |feature| has to match an item defined in interop_feature_t * (interop.h). */ - void (*interop_database_add)(uint16_t feature, const RawAddress* addr, - size_t len); + void (*interop_database_add)(uint16_t feature, const RawAddress* addr, size_t len); /** * Get the AvrcpTarget Service interface to interact with the Avrcp Service @@ -978,8 +956,7 @@ typedef struct { * @param key Metadata key * @param value Metadata value */ - void (*metadata_changed)(const RawAddress& remote_bd_addr, int key, - std::vector value); + void (*metadata_changed)(const RawAddress& remote_bd_addr, int key, std::vector value); /** interop match address */ bool (*interop_match_addr)(const char* feature_name, const RawAddress* addr); @@ -988,18 +965,14 @@ typedef struct { bool (*interop_match_name)(const char* feature_name, const char* name); /** interop match address or name */ - bool (*interop_match_addr_or_name)(const char* feature_name, - const RawAddress* addr); + bool (*interop_match_addr_or_name)(const char* feature_name, const RawAddress* addr); /** add or remove address entry to interop database */ - void (*interop_database_add_remove_addr)(bool do_add, - const char* feature_name, + void (*interop_database_add_remove_addr)(bool do_add, const char* feature_name, const RawAddress* addr, int length); /** add or remove name entry to interop database */ - void (*interop_database_add_remove_name)(bool do_add, - const char* feature_name, - const char* name); + void (*interop_database_add_remove_name)(bool do_add, const char* feature_name, const char* name); /** get remote Pbap PCE version*/ int (*get_remote_pbap_pce_version)(const RawAddress* bd_addr); diff --git a/system/include/hardware/bluetooth_headset_callbacks.h b/system/include/hardware/bluetooth_headset_callbacks.h index 36ea13431d7..3ef500322bc 100644 --- a/system/include/hardware/bluetooth_headset_callbacks.h +++ b/system/include/hardware/bluetooth_headset_callbacks.h @@ -28,7 +28,7 @@ namespace headset { * All callbacks are invoked on the JNI thread */ class Callbacks { - public: +public: virtual ~Callbacks() = default; /** * Callback for connection state change. @@ -36,8 +36,7 @@ class Callbacks { * @param state one of the values from bthf_connection_state_t * @param bd_addr remote device address */ - virtual void ConnectionStateCallback(bthf_connection_state_t state, - RawAddress* bd_addr) = 0; + virtual void ConnectionStateCallback(bthf_connection_state_t state, RawAddress* bd_addr) = 0; /** * Callback for audio connection state change. @@ -45,8 +44,7 @@ class Callbacks { * @param state one of the values from bthf_audio_state_t * @param bd_addr remote device address */ - virtual void AudioStateCallback(bthf_audio_state_t state, - RawAddress* bd_addr) = 0; + virtual void AudioStateCallback(bthf_audio_state_t state, RawAddress* bd_addr) = 0; /** * Callback for VR connection state change. @@ -54,8 +52,7 @@ class Callbacks { * @param state one of the values from bthf_vr_state_t * @param bd_addr */ - virtual void VoiceRecognitionCallback(bthf_vr_state_t state, - RawAddress* bd_addr) = 0; + virtual void VoiceRecognitionCallback(bthf_vr_state_t state, RawAddress* bd_addr) = 0; /** * Callback for answer incoming call (ATA) @@ -78,8 +75,7 @@ class Callbacks { * @param volume volume value 0 to 15, p69, HFP 1.7.1 spec * @param bd_addr remote device address */ - virtual void VolumeControlCallback(bthf_volume_type_t type, int volume, - RawAddress* bd_addr) = 0; + virtual void VolumeControlCallback(bthf_volume_type_t type, int volume, RawAddress* bd_addr) = 0; /** * Callback for dialing an outgoing call @@ -103,8 +99,7 @@ class Callbacks { * @param nrec 1 to enable, 0 to disable * @param bd_addr remote device address */ - virtual void NoiseReductionCallback(bthf_nrec_t nrec, - RawAddress* bd_addr) = 0; + virtual void NoiseReductionCallback(bthf_nrec_t nrec, RawAddress* bd_addr) = 0; /** * Callback for AT+BCS and event from BAC @@ -121,8 +116,7 @@ class Callbacks { * @param swb SWB enable, SWB disable * @param bd_addr remote device address */ - virtual void SwbCallback(bthf_swb_codec_t codec, bthf_swb_config_t swb, - RawAddress* bd_addr) = 0; + virtual void SwbCallback(bthf_swb_codec_t codec, bthf_swb_config_t swb, RawAddress* bd_addr) = 0; /** * Callback for call hold handling (AT+CHLD) @@ -190,8 +184,7 @@ class Callbacks { * @param ind_value HF indicator value * @param bd_addr remote device address */ - virtual void AtBievCallback(bthf_hf_ind_type_t ind_id, int ind_value, - RawAddress* bd_addr) = 0; + virtual void AtBievCallback(bthf_hf_ind_type_t ind_id, int ind_value, RawAddress* bd_addr) = 0; /** * Callback for BIA. Pass the change in AG indicator activation. @@ -219,10 +212,9 @@ class Callbacks { * @param pkt_status_in_hex recorded packets' status in hex string. * @param pkt_status_in_binary recorde packets' status in binary string. */ - virtual void DebugDumpCallback(bool active, uint16_t codec_id, - int total_num_decoded_frames, - double pkt_loss_ratio, uint64_t begin_ts, - uint64_t end_ts, const char* pkt_status_in_hex, + virtual void DebugDumpCallback(bool active, uint16_t codec_id, int total_num_decoded_frames, + double pkt_loss_ratio, uint64_t begin_ts, uint64_t end_ts, + const char* pkt_status_in_hex, const char* pkt_status_in_binary) = 0; }; diff --git a/system/include/hardware/bluetooth_headset_interface.h b/system/include/hardware/bluetooth_headset_interface.h index 164110ac0d4..aac8acabc20 100644 --- a/system/include/hardware/bluetooth_headset_interface.h +++ b/system/include/hardware/bluetooth_headset_interface.h @@ -30,7 +30,7 @@ namespace headset { * Thread-safe */ class Interface { - public: +public: virtual ~Interface() = default; /** * Register the BtHf callbacks @@ -66,8 +66,7 @@ class Interface { * @param disabled_codecs bitset of disabled BTM_SCO_CODECs * @return BT_STATUS_SUCCESS on success */ - virtual bt_status_t ConnectAudio(RawAddress* bd_addr, - int disabled_codecs) = 0; + virtual bt_status_t ConnectAudio(RawAddress* bd_addr, int disabled_codecs) = 0; /** * Close the audio connection @@ -119,8 +118,7 @@ class Interface { * @param bd_addr remote device address * @return BT_STATUS_SUCCESS on success */ - virtual bt_status_t VolumeControl(bthf_volume_type_t type, int volume, - RawAddress* bd_addr) = 0; + virtual bt_status_t VolumeControl(bthf_volume_type_t type, int volume, RawAddress* bd_addr) = 0; /** * Combined device status change notification @@ -133,9 +131,8 @@ class Interface { * @return BT_STATUS_SUCCESS on success */ virtual bt_status_t DeviceStatusNotification(bthf_network_state_t ntk_state, - bthf_service_type_t svc_type, - int signal, int batt_chg, - RawAddress* bd_addr) = 0; + bthf_service_type_t svc_type, int signal, + int batt_chg, RawAddress* bd_addr) = 0; /** * Response for COPS (Query Operator Selection) command @@ -160,9 +157,8 @@ class Interface { * @return BT_STATUS_SUCCESS on success */ virtual bt_status_t CindResponse(int svc, int num_active, int num_held, - bthf_call_state_t call_setup_state, - int signal, int roam, int batt_chg, - RawAddress* bd_addr) = 0; + bthf_call_state_t call_setup_state, int signal, int roam, + int batt_chg, RawAddress* bd_addr) = 0; /** * Pre-formatted AT response, typically in response to unknown AT cmd @@ -171,8 +167,7 @@ class Interface { * @param bd_addr remote device address * @return BT_STATUS_SUCCESS on success */ - virtual bt_status_t FormattedAtResponse(const char* rsp, - RawAddress* bd_addr) = 0; + virtual bt_status_t FormattedAtResponse(const char* rsp, RawAddress* bd_addr) = 0; /** * ok/error response to AT commands @@ -182,8 +177,8 @@ class Interface { * @param bd_addr remote device address * @return BT_STATUS_SUCCESS on success */ - virtual bt_status_t AtResponse(bthf_at_response_t response_code, - int error_code, RawAddress* bd_addr) = 0; + virtual bt_status_t AtResponse(bthf_at_response_t response_code, int error_code, + RawAddress* bd_addr) = 0; /** * Response for CLCC (Current List of Calls) command. @@ -200,10 +195,10 @@ class Interface { * @param bd_addr remote device address * @return BT_STATUS_SUCCESS on success */ - virtual bt_status_t ClccResponse( - int index, bthf_call_direction_t dir, bthf_call_state_t state, - bthf_call_mode_t mode, bthf_call_mpty_type_t mpty, const char* number, - bthf_call_addrtype_t type, RawAddress* bd_addr) = 0; + virtual bt_status_t ClccResponse(int index, bthf_call_direction_t dir, bthf_call_state_t state, + bthf_call_mode_t mode, bthf_call_mpty_type_t mpty, + const char* number, bthf_call_addrtype_t type, + RawAddress* bd_addr) = 0; /** * Notify of a call state change @@ -223,10 +218,8 @@ class Interface { * @return BT_STATUS_SUCCESS on success */ virtual bt_status_t PhoneStateChange(int num_active, int num_held, - bthf_call_state_t call_setup_state, - const char* number, - bthf_call_addrtype_t type, - const char* name, + bthf_call_state_t call_setup_state, const char* number, + bthf_call_addrtype_t type, const char* name, RawAddress* bd_addr) = 0; /** @@ -237,8 +230,7 @@ class Interface { * @param bd_addr remote device address * @return BT_STATUS_SUCCESS on success */ - virtual bt_status_t EnableSwb(bthf_swb_codec_t swbCodec, bool enable, - RawAddress* bd_addr) = 0; + virtual bt_status_t EnableSwb(bthf_swb_codec_t swbCodec, bool enable, RawAddress* bd_addr) = 0; /** * Closes the interface. diff --git a/system/include/hardware/bt_av.h b/system/include/hardware/bt_av.h index 867e659037c..befbfb45300 100644 --- a/system/include/hardware/bt_av.h +++ b/system/include/hardware/bt_av.h @@ -66,8 +66,7 @@ typedef enum { // Indexes in this range will be allocated for offloaded codecs // that the stack does not recognize. BTAV_A2DP_CODEC_INDEX_SOURCE_EXT_MIN = BTAV_A2DP_CODEC_INDEX_SOURCE_MAX, - BTAV_A2DP_CODEC_INDEX_SOURCE_EXT_MAX = - BTAV_A2DP_CODEC_INDEX_SOURCE_EXT_MIN + 4, + BTAV_A2DP_CODEC_INDEX_SOURCE_EXT_MAX = BTAV_A2DP_CODEC_INDEX_SOURCE_EXT_MIN + 4, BTAV_A2DP_CODEC_INDEX_SINK_MIN = BTAV_A2DP_CODEC_INDEX_SOURCE_EXT_MAX, @@ -155,11 +154,10 @@ typedef enum { */ struct btav_a2dp_codec_config_t { btav_a2dp_codec_index_t codec_type; - btav_a2dp_codec_priority_t - codec_priority; // Codec selection priority - // relative to other codecs: larger value - // means higher priority. If 0, reset to - // default. + btav_a2dp_codec_priority_t codec_priority; // Codec selection priority + // relative to other codecs: larger value + // means higher priority. If 0, reset to + // default. btav_a2dp_codec_sample_rate_t sample_rate; btav_a2dp_codec_bits_per_sample_t bits_per_sample; btav_a2dp_codec_channel_mode_t channel_mode; @@ -203,62 +201,34 @@ struct btav_a2dp_codec_config_t { std::string ToString() const { std::string sample_rate_str; - AppendCapability(sample_rate_str, - (sample_rate == BTAV_A2DP_CODEC_SAMPLE_RATE_NONE), "NONE"); - AppendCapability(sample_rate_str, - (sample_rate & BTAV_A2DP_CODEC_SAMPLE_RATE_44100), - "44100"); - AppendCapability(sample_rate_str, - (sample_rate & BTAV_A2DP_CODEC_SAMPLE_RATE_48000), - "48000"); - AppendCapability(sample_rate_str, - (sample_rate & BTAV_A2DP_CODEC_SAMPLE_RATE_88200), - "88200"); - AppendCapability(sample_rate_str, - (sample_rate & BTAV_A2DP_CODEC_SAMPLE_RATE_96000), - "96000"); - AppendCapability(sample_rate_str, - (sample_rate & BTAV_A2DP_CODEC_SAMPLE_RATE_176400), - "176400"); - AppendCapability(sample_rate_str, - (sample_rate & BTAV_A2DP_CODEC_SAMPLE_RATE_192000), - "192000"); - AppendCapability(sample_rate_str, - (sample_rate & BTAV_A2DP_CODEC_SAMPLE_RATE_16000), - "16000"); - AppendCapability(sample_rate_str, - (sample_rate & BTAV_A2DP_CODEC_SAMPLE_RATE_24000), - "24000"); + AppendCapability(sample_rate_str, (sample_rate == BTAV_A2DP_CODEC_SAMPLE_RATE_NONE), "NONE"); + AppendCapability(sample_rate_str, (sample_rate & BTAV_A2DP_CODEC_SAMPLE_RATE_44100), "44100"); + AppendCapability(sample_rate_str, (sample_rate & BTAV_A2DP_CODEC_SAMPLE_RATE_48000), "48000"); + AppendCapability(sample_rate_str, (sample_rate & BTAV_A2DP_CODEC_SAMPLE_RATE_88200), "88200"); + AppendCapability(sample_rate_str, (sample_rate & BTAV_A2DP_CODEC_SAMPLE_RATE_96000), "96000"); + AppendCapability(sample_rate_str, (sample_rate & BTAV_A2DP_CODEC_SAMPLE_RATE_176400), "176400"); + AppendCapability(sample_rate_str, (sample_rate & BTAV_A2DP_CODEC_SAMPLE_RATE_192000), "192000"); + AppendCapability(sample_rate_str, (sample_rate & BTAV_A2DP_CODEC_SAMPLE_RATE_16000), "16000"); + AppendCapability(sample_rate_str, (sample_rate & BTAV_A2DP_CODEC_SAMPLE_RATE_24000), "24000"); std::string bits_per_sample_str; - AppendCapability(bits_per_sample_str, - (bits_per_sample == BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE), + AppendCapability(bits_per_sample_str, (bits_per_sample == BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE), "NONE"); - AppendCapability(bits_per_sample_str, - (bits_per_sample & BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16), + AppendCapability(bits_per_sample_str, (bits_per_sample & BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16), "16"); - AppendCapability(bits_per_sample_str, - (bits_per_sample & BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24), + AppendCapability(bits_per_sample_str, (bits_per_sample & BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24), "24"); - AppendCapability(bits_per_sample_str, - (bits_per_sample & BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32), + AppendCapability(bits_per_sample_str, (bits_per_sample & BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32), "32"); std::string channel_mode_str; - AppendCapability(channel_mode_str, - (channel_mode == BTAV_A2DP_CODEC_CHANNEL_MODE_NONE), - "NONE"); - AppendCapability(channel_mode_str, - (channel_mode & BTAV_A2DP_CODEC_CHANNEL_MODE_MONO), - "MONO"); - AppendCapability(channel_mode_str, - (channel_mode & BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO), + AppendCapability(channel_mode_str, (channel_mode == BTAV_A2DP_CODEC_CHANNEL_MODE_NONE), "NONE"); + AppendCapability(channel_mode_str, (channel_mode & BTAV_A2DP_CODEC_CHANNEL_MODE_MONO), "MONO"); + AppendCapability(channel_mode_str, (channel_mode & BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO), "STEREO"); - return "codec: " + CodecNameStr() + - " priority: " + std::to_string(codec_priority) + - " sample_rate: " + sample_rate_str + - " bits_per_sample: " + bits_per_sample_str + + return "codec: " + CodecNameStr() + " priority: " + std::to_string(codec_priority) + + " sample_rate: " + sample_rate_str + " bits_per_sample: " + bits_per_sample_str + " channel_mode: " + channel_mode_str + " codec_specific_1: " + std::to_string(codec_specific_1) + " codec_specific_2: " + std::to_string(codec_specific_2) + @@ -278,11 +248,14 @@ struct btav_a2dp_codec_config_t { return oss.str(); } - private: - static std::string AppendCapability(std::string& result, bool append, - const std::string& name) { - if (!append) return result; - if (!result.empty()) result += "|"; +private: + static std::string AppendCapability(std::string& result, bool append, const std::string& name) { + if (!append) { + return result; + } + if (!result.empty()) { + result += "|"; + } result += name; return result; } @@ -309,32 +282,29 @@ typedef void (*btav_connection_state_callback)(const RawAddress& bd_addr, /** Callback for audiopath state change. * state will have one of the values from btav_audio_state_t */ -typedef void (*btav_audio_state_callback)(const RawAddress& bd_addr, - btav_audio_state_t state); +typedef void (*btav_audio_state_callback)(const RawAddress& bd_addr, btav_audio_state_t state); /** Callback for audio configuration change. * Used only for the A2DP Source interface. */ typedef void (*btav_audio_source_config_callback)( - const RawAddress& bd_addr, btav_a2dp_codec_config_t codec_config, - std::vector codecs_local_capabilities, - std::vector codecs_selectable_capabilities); + const RawAddress& bd_addr, btav_a2dp_codec_config_t codec_config, + std::vector codecs_local_capabilities, + std::vector codecs_selectable_capabilities); /** Callback for audio configuration change. * Used only for the A2DP Sink interface. * sample_rate: sample rate in Hz * channel_count: number of channels (1 for mono, 2 for stereo) */ -typedef void (*btav_audio_sink_config_callback)(const RawAddress& bd_addr, - uint32_t sample_rate, +typedef void (*btav_audio_sink_config_callback)(const RawAddress& bd_addr, uint32_t sample_rate, uint8_t channel_count); /** Callback for querying whether the mandatory codec is more preferred. * Used only for the A2DP Source interface. * Return true if optional codecs are not preferred. */ -typedef bool (*btav_mandatory_codec_preferred_callback)( - const RawAddress& bd_addr); +typedef bool (*btav_mandatory_codec_preferred_callback)(const RawAddress& bd_addr); /** BT-AV A2DP Source callback structure. */ typedef struct { @@ -370,25 +340,21 @@ __END_DECLS namespace fmt { template <> -struct formatter - : enum_formatter {}; +struct formatter : enum_formatter {}; template <> struct formatter : enum_formatter {}; template <> struct formatter : enum_formatter {}; template <> -struct formatter - : enum_formatter {}; +struct formatter : enum_formatter {}; template <> -struct formatter - : enum_formatter {}; +struct formatter : enum_formatter {}; template <> -struct formatter - : enum_formatter {}; +struct formatter : enum_formatter {}; template <> -struct formatter - : enum_formatter {}; +struct formatter : enum_formatter { +}; template <> struct formatter : enum_formatter {}; diff --git a/system/include/hardware/bt_bqr.h b/system/include/hardware/bt_bqr.h index a00af21849a..470cb5aff7e 100644 --- a/system/include/hardware/bt_bqr.h +++ b/system/include/hardware/bt_bqr.h @@ -26,26 +26,24 @@ namespace bluetooth { namespace bqr { class BluetoothQualityReportCallbacks { - public: +public: virtual ~BluetoothQualityReportCallbacks() = default; /** Callback for BQR delivery to app level. */ - virtual void bqr_delivery_callback(const RawAddress remote_bd_addr, - uint8_t lmp_ver, uint16_t lmp_subver, - uint16_t manufacturer_id, + virtual void bqr_delivery_callback(const RawAddress remote_bd_addr, uint8_t lmp_ver, + uint16_t lmp_subver, uint16_t manufacturer_id, std::vector bqr_raw_data) = 0; }; class BluetoothQualityReportInterface { - public: +public: virtual ~BluetoothQualityReportInterface() = default; /** Register the bluetooth keystore callbacks */ virtual void init(BluetoothQualityReportCallbacks* callbacks) = 0; /** Event for BQR delivery to app level. */ - virtual void bqr_delivery_event(const RawAddress& bd_addr, - const uint8_t* bqr_raw_data, + virtual void bqr_delivery_event(const RawAddress& bd_addr, const uint8_t* bqr_raw_data, uint32_t bqr_raw_data_len) = 0; }; diff --git a/system/include/hardware/bt_common_types.h b/system/include/hardware/bt_common_types.h index ff694924c7a..a394ed6e3e6 100644 --- a/system/include/hardware/bt_common_types.h +++ b/system/include/hardware/bt_common_types.h @@ -153,8 +153,7 @@ struct MsftAdvMonitor { namespace fmt { template <> -struct formatter - : enum_formatter {}; +struct formatter : enum_formatter {}; } // namespace fmt #endif // __has_include() diff --git a/system/include/hardware/bt_csis.h b/system/include/hardware/bt_csis.h index e9240972cde..e68f3f0a3cc 100644 --- a/system/include/hardware/bt_csis.h +++ b/system/include/hardware/bt_csis.h @@ -49,29 +49,25 @@ enum class CsisGroupLockStatus { static constexpr uint8_t CSIS_RANK_INVALID = 0x00; class CsisClientCallbacks { - public: +public: virtual ~CsisClientCallbacks() = default; /** Callback for profile connection state change */ - virtual void OnConnectionState(const RawAddress& addr, - ConnectionState state) = 0; + virtual void OnConnectionState(const RawAddress& addr, ConnectionState state) = 0; /** Callback for the new available device */ - virtual void OnDeviceAvailable(const RawAddress& addr, int group_id, - int group_size, int rank, + virtual void OnDeviceAvailable(const RawAddress& addr, int group_id, int group_size, int rank, const bluetooth::Uuid& uuid) = 0; /* Callback for available set member*/ - virtual void OnSetMemberAvailable(const RawAddress& address, - int group_id) = 0; + virtual void OnSetMemberAvailable(const RawAddress& address, int group_id) = 0; /* Callback for lock changed in the group */ - virtual void OnGroupLockChanged(int group_id, bool locked, - CsisGroupLockStatus status) = 0; + virtual void OnGroupLockChanged(int group_id, bool locked, CsisGroupLockStatus status) = 0; }; class CsisClientInterface { - public: +public: virtual ~CsisClientInterface() = default; /** Register the Csis Client profile callbacks */ diff --git a/system/include/hardware/bt_gatt_client.h b/system/include/hardware/bt_gatt_client.h index 7ddcbb5568e..200c00a36ba 100644 --- a/system/include/hardware/bt_gatt_client.h +++ b/system/include/hardware/bt_gatt_client.h @@ -69,22 +69,22 @@ typedef struct { /* BT GATT client error codes */ typedef enum { - BT_GATTC_COMMAND_SUCCESS = 0, /* 0 Command succeeded */ - BT_GATTC_COMMAND_STARTED, /* 1 Command started OK. */ - BT_GATTC_COMMAND_BUSY, /* 2 Device busy with another command */ - BT_GATTC_COMMAND_STORED, /* 3 request is stored in control block */ - BT_GATTC_NO_RESOURCES, /* 4 No resources to issue command */ - BT_GATTC_MODE_UNSUPPORTED, /* 5 Request for 1 or more unsupported modes */ - BT_GATTC_ILLEGAL_VALUE, /* 6 Illegal command /parameter value */ - BT_GATTC_INCORRECT_STATE, /* 7 Device in wrong state for request */ - BT_GATTC_UNKNOWN_ADDR, /* 8 Unknown remote BD address */ - BT_GATTC_DEVICE_TIMEOUT, /* 9 Device timeout */ + BT_GATTC_COMMAND_SUCCESS = 0, /* 0 Command succeeded */ + BT_GATTC_COMMAND_STARTED, /* 1 Command started OK. */ + BT_GATTC_COMMAND_BUSY, /* 2 Device busy with another command */ + BT_GATTC_COMMAND_STORED, /* 3 request is stored in control block */ + BT_GATTC_NO_RESOURCES, /* 4 No resources to issue command */ + BT_GATTC_MODE_UNSUPPORTED, /* 5 Request for 1 or more unsupported modes */ + BT_GATTC_ILLEGAL_VALUE, /* 6 Illegal command /parameter value */ + BT_GATTC_INCORRECT_STATE, /* 7 Device in wrong state for request */ + BT_GATTC_UNKNOWN_ADDR, /* 8 Unknown remote BD address */ + BT_GATTC_DEVICE_TIMEOUT, /* 9 Device timeout */ BT_GATTC_INVALID_CONTROLLER_OUTPUT, /* 10 An incorrect value was received from HCI */ - BT_GATTC_SECURITY_ERROR, /* 11 Authorization or security failure or not - authorized */ - BT_GATTC_DELAYED_ENCRYPTION_CHECK, /*12 Delayed encryption check */ - BT_GATTC_ERR_PROCESSING /* 12 Generic error */ + BT_GATTC_SECURITY_ERROR, /* 11 Authorization or security failure or not + authorized */ + BT_GATTC_DELAYED_ENCRYPTION_CHECK, /*12 Delayed encryption check */ + BT_GATTC_ERR_PROCESSING /* 12 Generic error */ } btgattc_error_t; /** BT-GATT Client callback structure. */ @@ -94,12 +94,10 @@ typedef void (*register_client_callback)(int status, int client_if, const bluetooth::Uuid& app_uuid); /** GATT open callback invoked in response to open */ -typedef void (*connect_callback)(int conn_id, int status, int client_if, - const RawAddress& bda); +typedef void (*connect_callback)(int conn_id, int status, int client_if, const RawAddress& bda); /** Callback invoked in response to close */ -typedef void (*disconnect_callback)(int conn_id, int status, int client_if, - const RawAddress& bda); +typedef void (*disconnect_callback)(int conn_id, int status, int client_if, const RawAddress& bda); /** * Invoked in response to search_service when the GATT service search @@ -108,24 +106,22 @@ typedef void (*disconnect_callback)(int conn_id, int status, int client_if, typedef void (*search_complete_callback)(int conn_id, int status); /** Callback invoked in response to (de)register_for_notification */ -typedef void (*register_for_notification_callback)(int conn_id, int registered, - int status, uint16_t handle); +typedef void (*register_for_notification_callback)(int conn_id, int registered, int status, + uint16_t handle); /** * Remote device notification callback, invoked when a remote device sends * a notification or indication that a client has registered for. */ -typedef void (*notify_callback)(int conn_id, - const btgatt_notify_params_t& p_data); +typedef void (*notify_callback)(int conn_id, const btgatt_notify_params_t& p_data); /** Reports result of a GATT read operation */ -typedef void (*read_characteristic_callback)( - int conn_id, int status, const btgatt_read_params_t& p_data); +typedef void (*read_characteristic_callback)(int conn_id, int status, + const btgatt_read_params_t& p_data); /** GATT write characteristic operation callback */ -typedef void (*write_characteristic_callback)(int conn_id, int status, - uint16_t handle, uint16_t len, - const uint8_t* value); +typedef void (*write_characteristic_callback)(int conn_id, int status, uint16_t handle, + uint16_t len, const uint8_t* value); /** GATT execute prepared write callback */ typedef void (*execute_write_callback)(int conn_id, int status); @@ -135,13 +131,12 @@ typedef void (*read_descriptor_callback)(int conn_id, int status, const btgatt_read_params_t& p_data); /** Callback invoked in response to write_descriptor */ -typedef void (*write_descriptor_callback)(int conn_id, int status, - uint16_t handle, uint16_t len, +typedef void (*write_descriptor_callback)(int conn_id, int status, uint16_t handle, uint16_t len, const uint8_t* value); /** Callback triggered in response to read_remote_rssi */ -typedef void (*read_remote_rssi_callback)(int client_if, const RawAddress& bda, - int rssi, int status); +typedef void (*read_remote_rssi_callback)(int client_if, const RawAddress& bda, int rssi, + int status); /** Callback invoked when the MTU for a given connection changes */ typedef void (*configure_mtu_callback)(int conn_id, int status, int mtu); @@ -155,36 +150,30 @@ typedef void (*configure_mtu_callback)(int conn_id, int status, int mtu); typedef void (*congestion_callback)(int conn_id, bool congested); /** GATT get database callback */ -typedef void (*get_gatt_db_callback)(int conn_id, const btgatt_db_element_t* db, - int count); +typedef void (*get_gatt_db_callback)(int conn_id, const btgatt_db_element_t* db, int count); /** GATT services between start_handle and end_handle were removed */ -typedef void (*services_removed_callback)(int conn_id, uint16_t start_handle, - uint16_t end_handle); +typedef void (*services_removed_callback)(int conn_id, uint16_t start_handle, uint16_t end_handle); /** GATT services were added */ -typedef void (*services_added_callback)(int conn_id, - const btgatt_db_element_t& added, +typedef void (*services_added_callback)(int conn_id, const btgatt_db_element_t& added, int added_count); /** Callback invoked when the PHY for a given connection changes */ -typedef void (*phy_updated_callback)(int conn_id, uint8_t tx_phy, - uint8_t rx_phy, uint8_t status); +typedef void (*phy_updated_callback)(int conn_id, uint8_t tx_phy, uint8_t rx_phy, uint8_t status); /** Callback invoked when the connection parameters for a given connection * changes */ -typedef void (*conn_updated_callback)(int conn_id, uint16_t interval, - uint16_t latency, uint16_t timeout, - uint8_t status); +typedef void (*conn_updated_callback)(int conn_id, uint16_t interval, uint16_t latency, + uint16_t timeout, uint8_t status); /** Callback when services are changed */ typedef void (*service_changed_callback)(int conn_id); /** Callback invoked when the subrate change event for a given connection * is received */ -typedef void (*subrate_change_callback)(int conn_id, uint16_t subrate_factor, - uint16_t latency, uint16_t cont_num, - uint16_t timeout, uint8_t status); +typedef void (*subrate_change_callback)(int conn_id, uint16_t subrate_factor, uint16_t latency, + uint16_t cont_num, uint16_t timeout, uint8_t status); typedef struct { register_client_callback register_client_cb; @@ -214,20 +203,17 @@ typedef struct { typedef struct { /** Registers a GATT client application with the stack */ - bt_status_t (*register_client)(const bluetooth::Uuid& uuid, - bool eatt_support); + bt_status_t (*register_client)(const bluetooth::Uuid& uuid, bool eatt_support); /** Unregister a client application from the stack */ bt_status_t (*unregister_client)(int client_if); /** Create a connection to a remote LE or dual-mode device */ - bt_status_t (*connect)(int client_if, const RawAddress& bd_addr, - uint8_t addr_type, bool is_direct, int transport, - bool opportunistic, int initiating_phys); + bt_status_t (*connect)(int client_if, const RawAddress& bd_addr, uint8_t addr_type, + bool is_direct, int transport, bool opportunistic, int initiating_phys); /** Disconnect a remote device or cancel a pending connection */ - bt_status_t (*disconnect)(int client_if, const RawAddress& bd_addr, - int conn_id); + bt_status_t (*disconnect)(int client_if, const RawAddress& bd_addr, int conn_id); /** Clear the attribute cache for a given device */ bt_status_t (*refresh)(int client_if, const RawAddress& bd_addr); @@ -236,37 +222,30 @@ typedef struct { * Enumerate all GATT services on a connected device. * Optionally, the results can be filtered for a given UUID. */ - bt_status_t (*search_service)(int conn_id, - const bluetooth::Uuid* filter_uuid); + bt_status_t (*search_service)(int conn_id, const bluetooth::Uuid* filter_uuid); /** * Sead "Find service by UUID" request. Used only for PTS tests. */ - void (*btif_gattc_discover_service_by_uuid)(int conn_id, - const bluetooth::Uuid& uuid); + void (*btif_gattc_discover_service_by_uuid)(int conn_id, const bluetooth::Uuid& uuid); /** Read a characteristic on a remote device */ - bt_status_t (*read_characteristic)(int conn_id, uint16_t handle, - int auth_req); + bt_status_t (*read_characteristic)(int conn_id, uint16_t handle, int auth_req); /** Read a characteristic on a remote device */ - bt_status_t (*read_using_characteristic_uuid)(int conn_id, - const bluetooth::Uuid& uuid, - uint16_t s_handle, - uint16_t e_handle, - int auth_req); + bt_status_t (*read_using_characteristic_uuid)(int conn_id, const bluetooth::Uuid& uuid, + uint16_t s_handle, uint16_t e_handle, int auth_req); /** Write a remote characteristic */ - bt_status_t (*write_characteristic)(int conn_id, uint16_t handle, - int write_type, int auth_req, + bt_status_t (*write_characteristic)(int conn_id, uint16_t handle, int write_type, int auth_req, const uint8_t* value, size_t length); /** Read the descriptor for a given characteristic */ bt_status_t (*read_descriptor)(int conn_id, uint16_t handle, int auth_req); /** Write a remote descriptor for a given characteristic */ - bt_status_t (*write_descriptor)(int conn_id, uint16_t handle, int auth_req, - const uint8_t* value, size_t length); + bt_status_t (*write_descriptor)(int conn_id, uint16_t handle, int auth_req, const uint8_t* value, + size_t length); /** Execute a prepared write operation */ bt_status_t (*execute_write)(int conn_id, int execute); @@ -275,13 +254,11 @@ typedef struct { * Register to receive notifications or indications for a given * characteristic */ - bt_status_t (*register_for_notification)(int client_if, - const RawAddress& bd_addr, + bt_status_t (*register_for_notification)(int client_if, const RawAddress& bd_addr, uint16_t handle); /** Deregister a previous request for notifications/indications */ - bt_status_t (*deregister_for_notification)(int client_if, - const RawAddress& bd_addr, + bt_status_t (*deregister_for_notification)(int client_if, const RawAddress& bd_addr, uint16_t handle); /** Request RSSI for a given remote device */ @@ -294,18 +271,15 @@ typedef struct { bt_status_t (*configure_mtu)(int conn_id, int mtu); /** Request a connection parameter update */ - bt_status_t (*conn_parameter_update)(const RawAddress& bd_addr, - int min_interval, int max_interval, - int latency, int timeout, - uint16_t min_ce_len, - uint16_t max_ce_len); + bt_status_t (*conn_parameter_update)(const RawAddress& bd_addr, int min_interval, + int max_interval, int latency, int timeout, + uint16_t min_ce_len, uint16_t max_ce_len); - bt_status_t (*set_preferred_phy)(const RawAddress& bd_addr, uint8_t tx_phy, - uint8_t rx_phy, uint16_t phy_options); + bt_status_t (*set_preferred_phy)(const RawAddress& bd_addr, uint8_t tx_phy, uint8_t rx_phy, + uint16_t phy_options); - bt_status_t (*read_phy)( - const RawAddress& bd_addr, - base::Callback cb); + bt_status_t (*read_phy)(const RawAddress& bd_addr, + base::Callback cb); /** Test mode interface */ bt_status_t (*test_command)(int command, const btgatt_test_params_t& params); @@ -314,9 +288,8 @@ typedef struct { bt_status_t (*get_gatt_db)(int conn_id); /** Request a BLE subrate request procedure */ - bt_status_t (*subrate_request)(const RawAddress& bd_addr, int subrate_min, - int subrate_max, int max_latency, int cont_num, - int timeout); + bt_status_t (*subrate_request)(const RawAddress& bd_addr, int subrate_min, int subrate_max, + int max_latency, int cont_num, int timeout); } btgatt_client_interface_t; diff --git a/system/include/hardware/bt_gatt_server.h b/system/include/hardware/bt_gatt_server.h index 29f4f450555..c83b2c9a4b5 100644 --- a/system/include/hardware/bt_gatt_server.h +++ b/system/include/hardware/bt_gatt_server.h @@ -52,37 +52,31 @@ typedef void (*connection_callback)(int conn_id, int server_if, int connected, /** Callback invoked in response to create_service */ typedef void (*service_added_callback)(int status, int server_if, - const btgatt_db_element_t* service, - size_t service_count); + const btgatt_db_element_t* service, size_t service_count); /** Callback invoked in response to stop_service */ -typedef void (*service_stopped_callback)(int status, int server_if, - int srvc_handle); +typedef void (*service_stopped_callback)(int status, int server_if, int srvc_handle); /** Callback triggered when a service has been deleted */ -typedef void (*service_deleted_callback)(int status, int server_if, - int srvc_handle); +typedef void (*service_deleted_callback)(int status, int server_if, int srvc_handle); /** * Callback invoked when a remote device has requested to read a characteristic * or descriptor. The application must respond by calling send_response */ -typedef void (*request_read_callback)(int conn_id, int trans_id, - const RawAddress& bda, int attr_handle, - int offset, bool is_long); +typedef void (*request_read_callback)(int conn_id, int trans_id, const RawAddress& bda, + int attr_handle, int offset, bool is_long); /** * Callback invoked when a remote device has requested to write to a * characteristic or descriptor. */ -typedef void (*request_write_callback)(int conn_id, int trans_id, - const RawAddress& bda, int attr_handle, - int offset, bool need_rsp, bool is_prep, +typedef void (*request_write_callback)(int conn_id, int trans_id, const RawAddress& bda, + int attr_handle, int offset, bool need_rsp, bool is_prep, const uint8_t* value, size_t length); /** Callback invoked when a previously prepared write is to be executed */ -typedef void (*request_exec_write_callback)(int conn_id, int trans_id, - const RawAddress& bda, +typedef void (*request_exec_write_callback)(int conn_id, int trans_id, const RawAddress& bda, int exec_write); /** @@ -109,20 +103,17 @@ typedef void (*congestion_callback)(int conn_id, bool congested); typedef void (*mtu_changed_callback)(int conn_id, int mtu); /** Callback invoked when the PHY for a given connection changes */ -typedef void (*phy_updated_callback)(int conn_id, uint8_t tx_phy, - uint8_t rx_phy, uint8_t status); +typedef void (*phy_updated_callback)(int conn_id, uint8_t tx_phy, uint8_t rx_phy, uint8_t status); /** Callback invoked when the connection parameters for a given connection * changes */ -typedef void (*conn_updated_callback)(int conn_id, uint16_t interval, - uint16_t latency, uint16_t timeout, - uint8_t status); +typedef void (*conn_updated_callback)(int conn_id, uint16_t interval, uint16_t latency, + uint16_t timeout, uint8_t status); /** Callback invoked when the subrate change event for a given connection * is received */ -typedef void (*subrate_change_callback)(int conn_id, uint16_t subrate_factor, - uint16_t latency, uint16_t cont_num, - uint16_t timeout, uint8_t status); +typedef void (*subrate_change_callback)(int conn_id, uint16_t subrate_factor, uint16_t latency, + uint16_t cont_num, uint16_t timeout, uint8_t status); typedef struct { register_server_callback register_server_cb; connection_callback connection_cb; @@ -146,19 +137,17 @@ typedef struct { /** Represents the standard BT-GATT server interface. */ typedef struct { /** Registers a GATT server application with the stack */ - bt_status_t (*register_server)(const bluetooth::Uuid& uuid, - bool eatt_support); + bt_status_t (*register_server)(const bluetooth::Uuid& uuid, bool eatt_support); /** Unregister a server application from the stack */ bt_status_t (*unregister_server)(int server_if); /** Create a connection to a remote peripheral */ - bt_status_t (*connect)(int server_if, const RawAddress& bd_addr, - uint8_t addr_type, bool is_direct, int transport); + bt_status_t (*connect)(int server_if, const RawAddress& bd_addr, uint8_t addr_type, + bool is_direct, int transport); /** Disconnect an established connection or cancel a pending one */ - bt_status_t (*disconnect)(int server_if, const RawAddress& bd_addr, - int conn_id); + bt_status_t (*disconnect)(int server_if, const RawAddress& bd_addr, int conn_id); /** Create a new service */ bt_status_t (*add_service)(int server_if, const btgatt_db_element_t* service, @@ -171,20 +160,18 @@ typedef struct { bt_status_t (*delete_service)(int server_if, int service_handle); /** Send value indication to a remote device */ - bt_status_t (*send_indication)(int server_if, int attribute_handle, - int conn_id, int confirm, const uint8_t* value, - size_t length); + bt_status_t (*send_indication)(int server_if, int attribute_handle, int conn_id, int confirm, + const uint8_t* value, size_t length); /** Send a response to a read/write operation */ bt_status_t (*send_response)(int conn_id, int trans_id, int status, const btgatt_response_t& response); - bt_status_t (*set_preferred_phy)(const RawAddress& bd_addr, uint8_t tx_phy, - uint8_t rx_phy, uint16_t phy_options); + bt_status_t (*set_preferred_phy)(const RawAddress& bd_addr, uint8_t tx_phy, uint8_t rx_phy, + uint16_t phy_options); - bt_status_t (*read_phy)( - const RawAddress& bd_addr, - base::Callback cb); + bt_status_t (*read_phy)(const RawAddress& bd_addr, + base::Callback cb); } btgatt_server_interface_t; diff --git a/system/include/hardware/bt_gatt_types.h b/system/include/hardware/bt_gatt_types.h index 3811928d3d3..8f0f4a511b3 100644 --- a/system/include/hardware/bt_gatt_types.h +++ b/system/include/hardware/bt_gatt_types.h @@ -17,12 +17,11 @@ #ifndef ANDROID_INCLUDE_BT_GATT_TYPES_H #define ANDROID_INCLUDE_BT_GATT_TYPES_H +#include #include #include #include -#include - __BEGIN_DECLS /** @@ -50,11 +49,7 @@ typedef struct { } btgatt_srvc_id_t; /** Preferred physical Transport for GATT connection */ -typedef enum { - GATT_TRANSPORT_AUTO, - GATT_TRANSPORT_BREDR, - GATT_TRANSPORT_LE -} btgatt_transport_t; +typedef enum { GATT_TRANSPORT_AUTO, GATT_TRANSPORT_BREDR, GATT_TRANSPORT_LE } btgatt_transport_t; __END_DECLS diff --git a/system/include/hardware/bt_has.h b/system/include/hardware/bt_has.h index 739edc041fe..631ca656d2c 100644 --- a/system/include/hardware/bt_has.h +++ b/system/include/hardware/bt_has.h @@ -76,12 +76,11 @@ static constexpr uint8_t kHasPresetIndexInvalid = 0x00; static constexpr int kHasGroupIdInvalid = -1; class HasClientCallbacks { - public: +public: virtual ~HasClientCallbacks() = default; /** Callback for profile connection state change */ - virtual void OnConnectionState(ConnectionState state, - const RawAddress& addr) = 0; + virtual void OnConnectionState(ConnectionState state, const RawAddress& addr) = 0; /** Callback for the new available device */ virtual void OnDeviceAvailable(const RawAddress& addr, uint8_t features) = 0; @@ -90,31 +89,28 @@ class HasClientCallbacks { virtual void OnFeaturesUpdate(const RawAddress& addr, uint8_t features) = 0; /** Callback for the currently active preset */ - virtual void OnActivePresetSelected( - std::variant addr_or_group_id, uint8_t preset_index) = 0; + virtual void OnActivePresetSelected(std::variant addr_or_group_id, + uint8_t preset_index) = 0; /** Callbacks for the active preset selection error */ - virtual void OnActivePresetSelectError( - std::variant addr_or_group_id, ErrorCode error_code) = 0; + virtual void OnActivePresetSelectError(std::variant addr_or_group_id, + ErrorCode error_code) = 0; /** Callbacks for the preset details event */ virtual void OnPresetInfo(std::variant addr_or_group_id, - PresetInfoReason change_id, - std::vector info_records) = 0; + PresetInfoReason change_id, std::vector info_records) = 0; /** Callback for the preset details get error */ virtual void OnPresetInfoError(std::variant addr_or_group_id, - uint8_t preset_index, - ErrorCode error_code) = 0; + uint8_t preset_index, ErrorCode error_code) = 0; /** Callback for the preset name set error */ - virtual void OnSetPresetNameError( - std::variant addr_or_group_id, uint8_t preset_index, - ErrorCode error_code) = 0; + virtual void OnSetPresetNameError(std::variant addr_or_group_id, + uint8_t preset_index, ErrorCode error_code) = 0; }; class HasClientInterface { - public: +public: virtual ~HasClientInterface() = default; /** Register the Hearing Aid Service Client profile callbacks */ @@ -127,23 +123,21 @@ class HasClientInterface { virtual void Disconnect(const RawAddress& addr) = 0; /** Select preset by the index as currently active */ - virtual void SelectActivePreset( - std::variant addr_or_group_id, uint8_t preset_index) = 0; + virtual void SelectActivePreset(std::variant addr_or_group_id, + uint8_t preset_index) = 0; /** Select next preset as currently active */ - virtual void NextActivePreset( - std::variant addr_or_group_id) = 0; + virtual void NextActivePreset(std::variant addr_or_group_id) = 0; /** Select previous preset as currently active */ - virtual void PreviousActivePreset( - std::variant addr_or_group_id) = 0; + virtual void PreviousActivePreset(std::variant addr_or_group_id) = 0; /** Get preset name by the index */ virtual void GetPresetInfo(const RawAddress& addr, uint8_t preset_index) = 0; /** Set preset name by the index */ - virtual void SetPresetName(std::variant addr_or_group_id, - uint8_t preset_index, std::string name) = 0; + virtual void SetPresetName(std::variant addr_or_group_id, uint8_t preset_index, + std::string name) = 0; /** Called when HAS capable device is unbonded */ virtual void RemoveDevice(const RawAddress& addr) = 0; diff --git a/system/include/hardware/bt_hd.h b/system/include/hardware/bt_hd.h index 732dc6168b3..b570656b8cc 100644 --- a/system/include/hardware/bt_hd.h +++ b/system/include/hardware/bt_hd.h @@ -31,10 +31,7 @@ typedef enum { BTHD_REPORT_TYPE_INTRDATA } bthd_report_type_t; -typedef enum { - BTHD_APP_STATE_NOT_REGISTERED, - BTHD_APP_STATE_REGISTERED -} bthd_application_state_t; +typedef enum { BTHD_APP_STATE_NOT_REGISTERED, BTHD_APP_STATE_REGISTERED } bthd_application_state_t; typedef enum { BTHD_CONN_STATE_CONNECTED, @@ -64,15 +61,11 @@ typedef struct { typedef void (*bthd_application_state_callback)(RawAddress* bd_addr, bthd_application_state_t state); -typedef void (*bthd_connection_state_callback)(RawAddress* bd_addr, - bthd_connection_state_t state); -typedef void (*bthd_get_report_callback)(uint8_t type, uint8_t id, - uint16_t buffer_size); -typedef void (*bthd_set_report_callback)(uint8_t type, uint8_t id, uint16_t len, - uint8_t* p_data); +typedef void (*bthd_connection_state_callback)(RawAddress* bd_addr, bthd_connection_state_t state); +typedef void (*bthd_get_report_callback)(uint8_t type, uint8_t id, uint16_t buffer_size); +typedef void (*bthd_set_report_callback)(uint8_t type, uint8_t id, uint16_t len, uint8_t* p_data); typedef void (*bthd_set_protocol_callback)(uint8_t protocol); -typedef void (*bthd_intr_data_callback)(uint8_t report_id, uint16_t len, - uint8_t* p_data); +typedef void (*bthd_intr_data_callback)(uint8_t report_id, uint16_t len, uint8_t* p_data); typedef void (*bthd_vc_unplug_callback)(void); /** BT-HD callbacks */ @@ -99,8 +92,7 @@ typedef struct { void (*cleanup)(void); /** register application */ - bt_status_t (*register_app)(bthd_app_param_t* app_param, - bthd_qos_param_t* in_qos, + bt_status_t (*register_app)(bthd_app_param_t* app_param, bthd_qos_param_t* in_qos, bthd_qos_param_t* out_qos); /** unregister application */ @@ -113,8 +105,7 @@ typedef struct { bt_status_t (*disconnect)(void); /** send report */ - bt_status_t (*send_report)(bthd_report_type_t type, uint8_t id, uint16_t len, - uint8_t* p_data); + bt_status_t (*send_report)(bthd_report_type_t type, uint8_t id, uint16_t len, uint8_t* p_data); /** notifies error for invalid SET_REPORT */ bt_status_t (*report_error)(uint8_t error); diff --git a/system/include/hardware/bt_hearing_aid.h b/system/include/hardware/bt_hearing_aid.h index 09e880d7c51..66c35c32686 100644 --- a/system/include/hardware/bt_hearing_aid.h +++ b/system/include/hardware/bt_hearing_aid.h @@ -23,20 +23,14 @@ namespace bluetooth { namespace hearing_aid { -enum class ConnectionState { - DISCONNECTED = 0, - CONNECTING, - CONNECTED, - DISCONNECTING -}; +enum class ConnectionState { DISCONNECTED = 0, CONNECTING, CONNECTED, DISCONNECTING }; class HearingAidCallbacks { - public: +public: virtual ~HearingAidCallbacks() = default; /** Callback for profile connection state change */ - virtual void OnConnectionState(ConnectionState state, - const RawAddress& address) = 0; + virtual void OnConnectionState(ConnectionState state, const RawAddress& address) = 0; /** Callback for device being available. Is executed when devices are loaded * from storage on stack bringup, and when new device is connected to profile. @@ -48,7 +42,7 @@ class HearingAidCallbacks { }; class HearingAidInterface { - public: +public: virtual ~HearingAidInterface() = default; /** Register the Hearing Aid callbacks */ diff --git a/system/include/hardware/bt_hf.h b/system/include/hardware/bt_hf.h index df1d016e08c..48771e21452 100644 --- a/system/include/hardware/bt_hf.h +++ b/system/include/hardware/bt_hf.h @@ -22,10 +22,7 @@ namespace bluetooth { namespace headset { /* AT response code - OK/Error */ -typedef enum { - BTHF_AT_RESPONSE_ERROR = 0, - BTHF_AT_RESPONSE_OK -} bthf_at_response_t; +typedef enum { BTHF_AT_RESPONSE_ERROR = 0, BTHF_AT_RESPONSE_OK } bthf_at_response_t; typedef enum { BTHF_CONNECTION_STATE_DISCONNECTED = 0, @@ -42,15 +39,9 @@ typedef enum { BTHF_AUDIO_STATE_DISCONNECTING } bthf_audio_state_t; -typedef enum { - BTHF_VR_STATE_STOPPED = 0, - BTHF_VR_STATE_STARTED -} bthf_vr_state_t; +typedef enum { BTHF_VR_STATE_STOPPED = 0, BTHF_VR_STATE_STARTED } bthf_vr_state_t; -typedef enum { - BTHF_VOLUME_TYPE_SPK = 0, - BTHF_VOLUME_TYPE_MIC -} bthf_volume_type_t; +typedef enum { BTHF_VOLUME_TYPE_SPK = 0, BTHF_VOLUME_TYPE_MIC } bthf_volume_type_t; /* Noise Reduction and Echo Cancellation */ typedef enum { BTHF_NREC_STOP, BTHF_NREC_START } bthf_nrec_t; @@ -59,10 +50,7 @@ typedef enum { BTHF_NREC_STOP, BTHF_NREC_START } bthf_nrec_t; typedef enum { BTHF_WBS_NONE, BTHF_WBS_NO, BTHF_WBS_YES } bthf_wbs_config_t; /* SWB codec */ -typedef enum { - BTHF_SWB_CODEC_LC3 = 0, - BTHF_SWB_CODEC_VENDOR_APTX -} bthf_swb_codec_t; +typedef enum { BTHF_SWB_CODEC_LC3 = 0, BTHF_SWB_CODEC_VENDOR_APTX } bthf_swb_codec_t; /* SWB codec setting */ typedef enum { @@ -73,13 +61,13 @@ typedef enum { /* CHLD - Call held handling */ typedef enum { - BTHF_CHLD_TYPE_RELEASEHELD, // Terminate all held or set UDUB("busy") to a - // waiting call + BTHF_CHLD_TYPE_RELEASEHELD, // Terminate all held or set UDUB("busy") to a + // waiting call BTHF_CHLD_TYPE_RELEASEACTIVE_ACCEPTHELD, // Terminate all active calls and // accepts a waiting/held call - BTHF_CHLD_TYPE_HOLDACTIVE_ACCEPTHELD, // Hold all active calls and accepts a - // waiting/held call - BTHF_CHLD_TYPE_ADDHELDTOCONF, // Add all held calls to a conference + BTHF_CHLD_TYPE_HOLDACTIVE_ACCEPTHELD, // Hold all active calls and accepts a + // waiting/held call + BTHF_CHLD_TYPE_ADDHELDTOCONF, // Add all held calls to a conference } bthf_chld_type_t; /* HF Indicators HFP 1.7 */ @@ -100,10 +88,7 @@ typedef enum { } bthf_network_state_t; /** Service type */ -typedef enum { - BTHF_SERVICE_TYPE_HOME = 0, - BTHF_SERVICE_TYPE_ROAMING -} bthf_service_type_t; +typedef enum { BTHF_SERVICE_TYPE_HOME = 0, BTHF_SERVICE_TYPE_ROAMING } bthf_service_type_t; typedef enum { BTHF_CALL_STATE_ACTIVE = 0, @@ -121,16 +106,9 @@ typedef enum { BTHF_CALL_DIRECTION_INCOMING } bthf_call_direction_t; -typedef enum { - BTHF_CALL_TYPE_VOICE = 0, - BTHF_CALL_TYPE_DATA, - BTHF_CALL_TYPE_FAX -} bthf_call_mode_t; +typedef enum { BTHF_CALL_TYPE_VOICE = 0, BTHF_CALL_TYPE_DATA, BTHF_CALL_TYPE_FAX } bthf_call_mode_t; -typedef enum { - BTHF_CALL_MPTY_TYPE_SINGLE = 0, - BTHF_CALL_MPTY_TYPE_MULTI -} bthf_call_mpty_type_t; +typedef enum { BTHF_CALL_MPTY_TYPE_SINGLE = 0, BTHF_CALL_MPTY_TYPE_MULTI } bthf_call_mpty_type_t; typedef enum { BTHF_CALL_ADDRTYPE_UNKNOWN = 0x81, diff --git a/system/include/hardware/bt_hf_client.h b/system/include/hardware/bt_hf_client.h index 83d005b8df3..4bf24c0babf 100644 --- a/system/include/hardware/bt_hf_client.h +++ b/system/include/hardware/bt_hf_client.h @@ -138,36 +138,30 @@ typedef enum { } bthf_client_in_band_ring_state_t; /* Peer features masks */ -#define BTHF_CLIENT_PEER_FEAT_3WAY 0x00000001 /* Three-way calling */ -#define BTHF_CLIENT_PEER_FEAT_ECNR \ - 0x00000002 /* Echo cancellation and/or noise reduction */ +#define BTHF_CLIENT_PEER_FEAT_3WAY 0x00000001 /* Three-way calling */ +#define BTHF_CLIENT_PEER_FEAT_ECNR 0x00000002 /* Echo cancellation and/or noise reduction */ #define BTHF_CLIENT_PEER_FEAT_VREC 0x00000004 /* Voice recognition */ #define BTHF_CLIENT_PEER_FEAT_INBAND 0x00000008 /* In-band ring tone */ -#define BTHF_CLIENT_PEER_FEAT_VTAG \ - 0x00000010 /* Attach a phone number to a voice tag */ -#define BTHF_CLIENT_PEER_FEAT_REJECT \ - 0x00000020 /* Ability to reject incoming call */ +#define BTHF_CLIENT_PEER_FEAT_VTAG 0x00000010 /* Attach a phone number to a voice tag */ +#define BTHF_CLIENT_PEER_FEAT_REJECT 0x00000020 /* Ability to reject incoming call */ #define BTHF_CLIENT_PEER_FEAT_ECS 0x00000040 /* Enhanced Call Status */ #define BTHF_CLIENT_PEER_FEAT_ECC 0x00000080 /* Enhanced Call Control */ #define BTHF_CLIENT_PEER_FEAT_EXTERR 0x00000100 /* Extended error codes */ #define BTHF_CLIENT_PEER_FEAT_CODEC 0x00000200 /* Codec Negotiation */ /* Peer call handling features masks */ -#define BTHF_CLIENT_CHLD_FEAT_REL \ - 0x00000001 /* 0 Release waiting call or held calls */ -#define BTHF_CLIENT_CHLD_FEAT_REL_ACC \ - 0x00000002 /* 1 Release active calls and accept other \ - (waiting or held) cal */ -#define BTHF_CLIENT_CHLD_FEAT_REL_X \ - 0x00000004 /* 1x Release specified active call only */ +#define BTHF_CLIENT_CHLD_FEAT_REL 0x00000001 /* 0 Release waiting call or held calls */ +#define BTHF_CLIENT_CHLD_FEAT_REL_ACC \ + 0x00000002 /* 1 Release active calls and accept other \ + (waiting or held) cal */ +#define BTHF_CLIENT_CHLD_FEAT_REL_X 0x00000004 /* 1x Release specified active call only */ #define BTHF_CLIENT_CHLD_FEAT_HOLD_ACC \ 0x00000008 /* 2 Active calls on hold and accept other \ (waiting or held) call */ -#define BTHF_CLIENT_CHLD_FEAT_PRIV_X \ - 0x00000010 /* 2x Request private mode with specified \ - call (put the rest on hold) */ -#define BTHF_CLIENT_CHLD_FEAT_MERGE \ - 0x00000020 /* 3 Add held call to multiparty */ +#define BTHF_CLIENT_CHLD_FEAT_PRIV_X \ + 0x00000010 /* 2x Request private mode with specified \ + call (put the rest on hold) */ +#define BTHF_CLIENT_CHLD_FEAT_MERGE 0x00000020 /* 3 Add held call to multiparty */ #define BTHF_CLIENT_CHLD_FEAT_MERGE_DETACH \ 0x00000040 /* 4 Connect two calls and leave \ (disconnect from) multiparty */ @@ -177,15 +171,16 @@ typedef enum { * peer/chld_features are valid only for * BTHF_CLIENT_CONNECTION_STATE_SLC_CONNECTED state */ -typedef void (*bthf_client_connection_state_callback)( - const RawAddress* bd_addr, bthf_client_connection_state_t state, - unsigned int peer_feat, unsigned int chld_feat); +typedef void (*bthf_client_connection_state_callback)(const RawAddress* bd_addr, + bthf_client_connection_state_t state, + unsigned int peer_feat, + unsigned int chld_feat); /** Callback for audio connection state change. * state will have one of the values from BtHfAudioState */ -typedef void (*bthf_client_audio_state_callback)( - const RawAddress* bd_addr, bthf_client_audio_state_t state); +typedef void (*bthf_client_audio_state_callback)(const RawAddress* bd_addr, + bthf_client_audio_state_t state); /** Callback for VR connection state change. * state will have one of the values from BtHfVRState @@ -195,38 +190,34 @@ typedef void (*bthf_client_vr_cmd_callback)(const RawAddress* bd_addr, /** Callback for network state change */ -typedef void (*bthf_client_network_state_callback)( - const RawAddress* bd_addr, bthf_client_network_state_t state); +typedef void (*bthf_client_network_state_callback)(const RawAddress* bd_addr, + bthf_client_network_state_t state); /** Callback for network roaming status change */ -typedef void (*bthf_client_network_roaming_callback)( - const RawAddress* bd_addr, bthf_client_service_type_t type); +typedef void (*bthf_client_network_roaming_callback)(const RawAddress* bd_addr, + bthf_client_service_type_t type); /** Callback for signal strength indication */ -typedef void (*bthf_client_network_signal_callback)(const RawAddress* bd_addr, - int signal_strength); +typedef void (*bthf_client_network_signal_callback)(const RawAddress* bd_addr, int signal_strength); /** Callback for battery level indication */ -typedef void (*bthf_client_battery_level_callback)(const RawAddress* bd_addr, - int battery_level); +typedef void (*bthf_client_battery_level_callback)(const RawAddress* bd_addr, int battery_level); /** Callback for current operator name */ -typedef void (*bthf_client_current_operator_callback)(const RawAddress* bd_addr, - const char* name); +typedef void (*bthf_client_current_operator_callback)(const RawAddress* bd_addr, const char* name); /** Callback for call indicator */ -typedef void (*bthf_client_call_callback)(const RawAddress* bd_addr, - bthf_client_call_t call); +typedef void (*bthf_client_call_callback)(const RawAddress* bd_addr, bthf_client_call_t call); /** Callback for callsetup indicator */ -typedef void (*bthf_client_callsetup_callback)( - const RawAddress* bd_addr, bthf_client_callsetup_t callsetup); +typedef void (*bthf_client_callsetup_callback)(const RawAddress* bd_addr, + bthf_client_callsetup_t callsetup); /** Callback for callheld indicator */ @@ -235,20 +226,18 @@ typedef void (*bthf_client_callheld_callback)(const RawAddress* bd_addr, /** Callback for response and hold */ -typedef void (*bthf_client_resp_and_hold_callback)( - const RawAddress* bd_addr, bthf_client_resp_and_hold_t resp_and_hold); +typedef void (*bthf_client_resp_and_hold_callback)(const RawAddress* bd_addr, + bthf_client_resp_and_hold_t resp_and_hold); /** Callback for Calling Line Identification notification * Will be called only when there is an incoming call and number is provided. */ -typedef void (*bthf_client_clip_callback)(const RawAddress* bd_addr, - const char* number); +typedef void (*bthf_client_clip_callback)(const RawAddress* bd_addr, const char* number); /** * Callback for Call Waiting notification */ -typedef void (*bthf_client_call_waiting_callback)(const RawAddress* bd_addr, - const char* number); +typedef void (*bthf_client_call_waiting_callback)(const RawAddress* bd_addr, const char* number); /** * Callback for listing current calls. Can be called multiple time. @@ -257,36 +246,34 @@ typedef void (*bthf_client_call_waiting_callback)(const RawAddress* bd_addr, typedef void (*bthf_client_current_calls)(const RawAddress* bd_addr, int index, bthf_client_call_direction_t dir, bthf_client_call_state_t state, - bthf_client_call_mpty_type_t mpty, - const char* number); + bthf_client_call_mpty_type_t mpty, const char* number); /** Callback for audio volume change */ -typedef void (*bthf_client_volume_change_callback)( - const RawAddress* bd_addr, bthf_client_volume_type_t type, int volume); +typedef void (*bthf_client_volume_change_callback)(const RawAddress* bd_addr, + bthf_client_volume_type_t type, int volume); /** Callback for command complete event * cme is valid only for BTHF_CLIENT_CMD_COMPLETE_ERROR_CME type */ -typedef void (*bthf_client_cmd_complete_callback)( - const RawAddress* bd_addr, bthf_client_cmd_complete_t type, int cme); +typedef void (*bthf_client_cmd_complete_callback)(const RawAddress* bd_addr, + bthf_client_cmd_complete_t type, int cme); /** Callback for subscriber information */ -typedef void (*bthf_client_subscriber_info_callback)( - const RawAddress* bd_addr, const char* name, - bthf_client_subscriber_service_type_t type); +typedef void (*bthf_client_subscriber_info_callback)(const RawAddress* bd_addr, const char* name, + bthf_client_subscriber_service_type_t type); /** Callback for in-band ring tone settings */ -typedef void (*bthf_client_in_band_ring_tone_callback)( - const RawAddress* bd_addr, bthf_client_in_band_ring_state_t state); +typedef void (*bthf_client_in_band_ring_tone_callback)(const RawAddress* bd_addr, + bthf_client_in_band_ring_state_t state); /** * Callback for requested number from AG */ -typedef void (*bthf_client_last_voice_tag_number_callback)( - const RawAddress* bd_addr, const char* number); +typedef void (*bthf_client_last_voice_tag_number_callback)(const RawAddress* bd_addr, + const char* number); /** * Callback for sending ring indication to app @@ -355,8 +342,8 @@ typedef struct { bt_status_t (*stop_voice_recognition)(const RawAddress* bd_addr); /** volume control */ - bt_status_t (*volume_control)(const RawAddress* bd_addr, - bthf_client_volume_type_t type, int volume); + bt_status_t (*volume_control)(const RawAddress* bd_addr, bthf_client_volume_type_t type, + int volume); /** place a call with number a number * if number is NULL last called number is called (aka re-dial)*/ @@ -368,8 +355,8 @@ typedef struct { /** perform specified call related action * idx is limited only for enhanced call control related action */ - bt_status_t (*handle_call_action)(const RawAddress* bd_addr, - bthf_client_call_action_t action, int idx); + bt_status_t (*handle_call_action)(const RawAddress* bd_addr, bthf_client_call_action_t action, + int idx); /** query list of current calls */ bt_status_t (*query_current_calls)(const RawAddress* bd_addr); @@ -390,8 +377,8 @@ typedef struct { void (*cleanup)(void); /** Send AT Command. */ - bt_status_t (*send_at_cmd)(const RawAddress* bd_addr, int cmd, int val1, - int val2, const char* arg); + bt_status_t (*send_at_cmd)(const RawAddress* bd_addr, int cmd, int val1, int val2, + const char* arg); /** Send hfp audio policy to remote */ bt_status_t (*send_android_at)(const RawAddress* bd_addr, const char* arg); @@ -399,6 +386,6 @@ typedef struct { namespace fmt { template <> -struct formatter - : enum_formatter {}; +struct formatter : enum_formatter { +}; } // namespace fmt diff --git a/system/include/hardware/bt_hh.h b/system/include/hardware/bt_hh.h index df9d649c97e..cd6079fc165 100644 --- a/system/include/hardware/bt_hh.h +++ b/system/include/hardware/bt_hh.h @@ -42,8 +42,7 @@ typedef enum { __END_DECLS -inline std::string bthh_connection_state_text( - const bthh_connection_state_t& state) { +inline std::string bthh_connection_state_text(const bthh_connection_state_t& state) { switch (state) { CASE_RETURN_TEXT(BTHH_CONN_STATE_CONNECTED); CASE_RETURN_TEXT(BTHH_CONN_STATE_CONNECTING); @@ -85,11 +84,7 @@ typedef enum { } bthh_protocol_mode_t; /* Report types */ -typedef enum { - BTHH_INPUT_REPORT = 1, - BTHH_OUTPUT_REPORT, - BTHH_FEATURE_REPORT -} bthh_report_type_t; +typedef enum { BTHH_INPUT_REPORT = 1, BTHH_OUTPUT_REPORT, BTHH_FEATURE_REPORT } bthh_report_type_t; /* Info for which profiles to enable */ typedef struct { @@ -112,60 +107,48 @@ typedef struct { /** Callback for connection state change. * state will have one of the values from bthh_connection_state_t */ -typedef void (*bthh_connection_state_callback)(RawAddress* bd_addr, - tBLE_ADDR_TYPE addr_type, +typedef void (*bthh_connection_state_callback)(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, tBT_TRANSPORT transport, bthh_connection_state_t state); /** Callback for vitual unplug api. * the status of the vitual unplug */ -typedef void (*bthh_virtual_unplug_callback)(RawAddress* bd_addr, - tBLE_ADDR_TYPE addr_type, - tBT_TRANSPORT transport, - bthh_status_t hh_status); +typedef void (*bthh_virtual_unplug_callback)(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, + tBT_TRANSPORT transport, bthh_status_t hh_status); /** Callback for get hid info * hid_info will contain attr_mask, sub_class, app_id, vendor_id, product_id, * version, ctry_code, len */ -typedef void (*bthh_hid_info_callback)(RawAddress* bd_addr, - tBLE_ADDR_TYPE addr_type, - tBT_TRANSPORT transport, - bthh_hid_info_t hid_info); +typedef void (*bthh_hid_info_callback)(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, + tBT_TRANSPORT transport, bthh_hid_info_t hid_info); /** Callback for get protocol api. * the protocol mode is one of the value from bthh_protocol_mode_t */ -typedef void (*bthh_protocol_mode_callback)(RawAddress* bd_addr, - tBLE_ADDR_TYPE addr_type, - tBT_TRANSPORT transport, - bthh_status_t hh_status, +typedef void (*bthh_protocol_mode_callback)(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, + tBT_TRANSPORT transport, bthh_status_t hh_status, bthh_protocol_mode_t mode); /** Callback for get/set_idle_time api. */ -typedef void (*bthh_idle_time_callback)(RawAddress* bd_addr, - tBLE_ADDR_TYPE addr_type, - tBT_TRANSPORT transport, - bthh_status_t hh_status, int idle_rate); +typedef void (*bthh_idle_time_callback)(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, + tBT_TRANSPORT transport, bthh_status_t hh_status, + int idle_rate); /** Callback for get report api. * if staus is ok rpt_data contains the report data */ -typedef void (*bthh_get_report_callback)(RawAddress* bd_addr, - tBLE_ADDR_TYPE addr_type, - tBT_TRANSPORT transport, - bthh_status_t hh_status, +typedef void (*bthh_get_report_callback)(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, + tBT_TRANSPORT transport, bthh_status_t hh_status, uint8_t* rpt_data, int rpt_size); /** Callback for set_report/set_protocol api and if error * occurs for get_report/get_protocol api. */ -typedef void (*bthh_handshake_callback)(RawAddress* bd_addr, - tBLE_ADDR_TYPE addr_type, - tBT_TRANSPORT transport, - bthh_status_t hh_status); +typedef void (*bthh_handshake_callback)(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, + tBT_TRANSPORT transport, bthh_status_t hh_status); /** BT-HH callback structure. */ typedef struct { @@ -192,30 +175,27 @@ typedef struct { bt_status_t (*init)(bthh_callbacks_t* callbacks); /** connect to hid device */ - bt_status_t (*connect)(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, - tBT_TRANSPORT transport); + bt_status_t (*connect)(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, tBT_TRANSPORT transport); /** dis-connect from hid device */ - bt_status_t (*disconnect)(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, - tBT_TRANSPORT transport, bool reconnect_allowed); + bt_status_t (*disconnect)(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, tBT_TRANSPORT transport, + bool reconnect_allowed); /** Virtual UnPlug (VUP) the specified HID device */ bt_status_t (*virtual_unplug)(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, tBT_TRANSPORT transport); /** Set the HID device descriptor for the specified HID device. */ - bt_status_t (*set_info)(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, - tBT_TRANSPORT transport, bthh_hid_info_t hid_info); + bt_status_t (*set_info)(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, tBT_TRANSPORT transport, + bthh_hid_info_t hid_info); /** Get the HID proto mode. */ bt_status_t (*get_protocol)(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, - tBT_TRANSPORT transport, - bthh_protocol_mode_t protocolMode); + tBT_TRANSPORT transport, bthh_protocol_mode_t protocolMode); /** Set the HID proto mode. */ bt_status_t (*set_protocol)(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, - tBT_TRANSPORT transport, - bthh_protocol_mode_t protocolMode); + tBT_TRANSPORT transport, bthh_protocol_mode_t protocolMode); /** Get the HID Idle Time */ bt_status_t (*get_idle_time)(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, @@ -226,24 +206,21 @@ typedef struct { tBT_TRANSPORT transport, uint8_t idleTime); /** Send a GET_REPORT to HID device. */ - bt_status_t (*get_report)(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, - tBT_TRANSPORT transport, - bthh_report_type_t reportType, uint8_t reportId, - int bufferSize); + bt_status_t (*get_report)(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, tBT_TRANSPORT transport, + bthh_report_type_t reportType, uint8_t reportId, int bufferSize); /** Send a GET_REPORT_REPLY to HID driver. */ bt_status_t (*get_report_reply)(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, - tBT_TRANSPORT transport, bthh_status_t status, - char* report, uint16_t size); + tBT_TRANSPORT transport, bthh_status_t status, char* report, + uint16_t size); /** Send a SET_REPORT to HID device. */ - bt_status_t (*set_report)(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, - tBT_TRANSPORT transport, + bt_status_t (*set_report)(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, tBT_TRANSPORT transport, bthh_report_type_t reportType, char* report); /** Send data to HID device. */ - bt_status_t (*send_data)(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, - tBT_TRANSPORT transport, char* data); + bt_status_t (*send_data)(RawAddress* bd_addr, tBLE_ADDR_TYPE addr_type, tBT_TRANSPORT transport, + char* data); /** Closes the interface. */ void (*cleanup)(void); @@ -259,11 +236,9 @@ __END_DECLS namespace fmt { template <> -struct formatter - : enum_formatter {}; +struct formatter : enum_formatter {}; template <> -struct formatter : enum_formatter { -}; +struct formatter : enum_formatter {}; template <> struct formatter : enum_formatter {}; } // namespace fmt diff --git a/system/include/hardware/bt_keystore.h b/system/include/hardware/bt_keystore.h index 186334dd48c..62f64dcd581 100644 --- a/system/include/hardware/bt_keystore.h +++ b/system/include/hardware/bt_keystore.h @@ -22,19 +22,18 @@ namespace bluetooth { namespace bluetooth_keystore { class BluetoothKeystoreCallbacks { - public: +public: virtual ~BluetoothKeystoreCallbacks() = default; /** Callback for key encrypt or remove key */ - virtual void set_encrypt_key_or_remove_key(std::string prefix, - std::string encryptedString) = 0; + virtual void set_encrypt_key_or_remove_key(std::string prefix, std::string encryptedString) = 0; /** Callback for get key. */ virtual std::string get_key(std::string prefix) = 0; }; class BluetoothKeystoreInterface { - public: +public: virtual ~BluetoothKeystoreInterface() = default; /** Register the bluetooth keystore callbacks */ @@ -44,8 +43,7 @@ class BluetoothKeystoreInterface { virtual void ConvertEncryptOrDecryptKeyIfNeeded() = 0; /** Interface for key encrypt or remove key */ - virtual bool set_encrypt_key_or_remove_key(std::string prefix, - std::string encryptedString) = 0; + virtual bool set_encrypt_key_or_remove_key(std::string prefix, std::string encryptedString) = 0; /** Interface for get key. */ virtual std::string get_key(std::string prefix) = 0; diff --git a/system/include/hardware/bt_le_audio.h b/system/include/hardware/bt_le_audio.h index c4414c5426d..9ba5ff3a4af 100644 --- a/system/include/hardware/bt_le_audio.h +++ b/system/include/hardware/bt_le_audio.h @@ -37,8 +37,7 @@ enum class LeAudioHealthBasedAction { INACTIVATE_GROUP, }; -inline std::ostream& operator<<(std::ostream& os, - const LeAudioHealthBasedAction action) { +inline std::ostream& operator<<(std::ostream& os, const LeAudioHealthBasedAction action) { switch (action) { case LeAudioHealthBasedAction::NONE: os << "NONE"; @@ -59,12 +58,7 @@ inline std::ostream& operator<<(std::ostream& os, return os; } -enum class ConnectionState { - DISCONNECTED = 0, - CONNECTING, - CONNECTED, - DISCONNECTING -}; +enum class ConnectionState { DISCONNECTED = 0, CONNECTING, CONNECTED, DISCONNECTING }; enum class GroupStatus { INACTIVE = 0, @@ -141,28 +135,37 @@ typedef enum { typedef struct btle_audio_codec_config { btle_audio_codec_index_t codec_type = LE_AUDIO_CODEC_INDEX_SOURCE_INVALID; btle_audio_sample_rate_index_t sample_rate = LE_AUDIO_SAMPLE_RATE_INDEX_NONE; - btle_audio_bits_per_sample_index_t bits_per_sample = - LE_AUDIO_BITS_PER_SAMPLE_INDEX_NONE; - btle_audio_channel_count_index_t channel_count = - LE_AUDIO_CHANNEL_COUNT_INDEX_NONE; - btle_audio_frame_duration_index_t frame_duration = - LE_AUDIO_FRAME_DURATION_INDEX_NONE; + btle_audio_bits_per_sample_index_t bits_per_sample = LE_AUDIO_BITS_PER_SAMPLE_INDEX_NONE; + btle_audio_channel_count_index_t channel_count = LE_AUDIO_CHANNEL_COUNT_INDEX_NONE; + btle_audio_frame_duration_index_t frame_duration = LE_AUDIO_FRAME_DURATION_INDEX_NONE; uint16_t octets_per_frame = 0; int32_t codec_priority = 0; bool operator!=(const btle_audio_codec_config& other) const { - if (codec_type != other.codec_type) return true; - if (sample_rate != other.sample_rate) return true; - if (bits_per_sample != other.bits_per_sample) return true; - if (channel_count != other.channel_count) return true; - if (frame_duration != other.frame_duration) return true; - if (octets_per_frame != other.octets_per_frame) return true; - if (codec_priority != other.codec_priority) return true; + if (codec_type != other.codec_type) { + return true; + } + if (sample_rate != other.sample_rate) { + return true; + } + if (bits_per_sample != other.bits_per_sample) { + return true; + } + if (channel_count != other.channel_count) { + return true; + } + if (frame_duration != other.frame_duration) { + return true; + } + if (octets_per_frame != other.octets_per_frame) { + return true; + } + if (codec_priority != other.codec_priority) { + return true; + } return false; - }; - bool operator==(const btle_audio_codec_config& other) const { - return !(*this != other); - }; + } + bool operator==(const btle_audio_codec_config& other) const { return !(*this != other); } std::string ToString() const { std::string codec_name_str; @@ -226,8 +229,7 @@ typedef struct btle_audio_codec_config { sample_rate_str = "384000 hz"; break; default: - sample_rate_str = - "Unknown LE sample rate " + std::to_string(sample_rate); + sample_rate_str = "Unknown LE sample rate " + std::to_string(sample_rate); break; } @@ -245,8 +247,7 @@ typedef struct btle_audio_codec_config { bits_per_sample_str = "32"; break; default: - bits_per_sample_str = - "Unknown LE bits per sample " + std::to_string(bits_per_sample); + bits_per_sample_str = "Unknown LE bits per sample " + std::to_string(bits_per_sample); break; } @@ -261,8 +262,7 @@ typedef struct btle_audio_codec_config { channel_count_str = "2"; break; default: - channel_count_str = - "Unknown LE channel count " + std::to_string(channel_count); + channel_count_str = "Unknown LE channel count " + std::to_string(channel_count); break; } @@ -277,45 +277,39 @@ typedef struct btle_audio_codec_config { frame_duration_str = "10000 us"; break; default: - frame_duration_str = - "Unknown LE frame duration " + std::to_string(frame_duration); + frame_duration_str = "Unknown LE frame duration " + std::to_string(frame_duration); break; } if (octets_per_frame < 0) { - octets_per_frame_str = - "Unknown LE octets per frame " + std::to_string(octets_per_frame); + octets_per_frame_str = "Unknown LE octets per frame " + std::to_string(octets_per_frame); } else { octets_per_frame_str = std::to_string(octets_per_frame); } if (codec_priority < -1) { - codec_priority_str = - "Unknown LE codec priority " + std::to_string(codec_priority); + codec_priority_str = "Unknown LE codec priority " + std::to_string(codec_priority); } else { codec_priority_str = std::to_string(codec_priority); } return "codec: " + codec_name_str + ", sample rate: " + sample_rate_str + - ", bits per sample: " + bits_per_sample_str + - ", channel count: " + channel_count_str + + ", bits per sample: " + bits_per_sample_str + ", channel count: " + channel_count_str + ", frame duration: " + frame_duration_str + - ", octets per frame: " + octets_per_frame_str + - ", codec priroty: " + codec_priority_str; + ", octets per frame: " + octets_per_frame_str + ", codec priroty: " + codec_priority_str; } } btle_audio_codec_config_t; class LeAudioClientCallbacks { - public: +public: virtual ~LeAudioClientCallbacks() = default; /* Callback to notify Java that stack is ready */ virtual void OnInitialized(void) = 0; /** Callback for profile connection state change */ - virtual void OnConnectionState(ConnectionState state, - const RawAddress& address) = 0; + virtual void OnConnectionState(ConnectionState state, const RawAddress& address) = 0; /* Callback with group status update */ virtual void OnGroupStatus(int group_id, GroupStatus group_status) = 0; @@ -324,49 +318,43 @@ class LeAudioClientCallbacks { virtual void OnGroupNodeStatus(const RawAddress& bd_addr, int group_id, GroupNodeStatus node_status) = 0; /* Callback for newly recognized or reconfigured existing le audio group */ - virtual void OnAudioConf(uint8_t direction, int group_id, - uint32_t snk_audio_location, - uint32_t src_audio_location, - uint16_t avail_cont) = 0; + virtual void OnAudioConf(uint8_t direction, int group_id, uint32_t snk_audio_location, + uint32_t src_audio_location, uint16_t avail_cont) = 0; /* Callback for sink audio location recognized */ virtual void OnSinkAudioLocationAvailable(const RawAddress& address, uint32_t snk_audio_locations) = 0; /* Callback with local codec capabilities */ virtual void OnAudioLocalCodecCapabilities( - std::vector local_input_capa_codec_conf, - std::vector local_output_capa_codec_conf) = 0; + std::vector local_input_capa_codec_conf, + std::vector local_output_capa_codec_conf) = 0; /* Callback with current group codec configurations. Should change when PACs * changes */ - virtual void OnAudioGroupCurrentCodecConf( - int group_id, btle_audio_codec_config_t input_codec_conf, - btle_audio_codec_config_t output_codec_conf) = 0; + virtual void OnAudioGroupCurrentCodecConf(int group_id, + btle_audio_codec_config_t input_codec_conf, + btle_audio_codec_config_t output_codec_conf) = 0; /* Callback with selectable group codec configurations. Should change when * context changes */ virtual void OnAudioGroupSelectableCodecConf( - int group_id, - std::vector input_selectable_codec_conf, - std::vector output_selectable_codec_conf) = 0; - virtual void OnHealthBasedRecommendationAction( - const RawAddress& address, LeAudioHealthBasedAction action) = 0; - virtual void OnHealthBasedGroupRecommendationAction( - int group_id, LeAudioHealthBasedAction action) = 0; + int group_id, std::vector input_selectable_codec_conf, + std::vector output_selectable_codec_conf) = 0; + virtual void OnHealthBasedRecommendationAction(const RawAddress& address, + LeAudioHealthBasedAction action) = 0; + virtual void OnHealthBasedGroupRecommendationAction(int group_id, + LeAudioHealthBasedAction action) = 0; - virtual void OnUnicastMonitorModeStatus(uint8_t direction, - UnicastMonitorModeStatus status) = 0; + virtual void OnUnicastMonitorModeStatus(uint8_t direction, UnicastMonitorModeStatus status) = 0; /* Callback with group stream status update */ - virtual void OnGroupStreamStatus(int group_id, - GroupStreamStatus group_stream_status) = 0; + virtual void OnGroupStreamStatus(int group_id, GroupStreamStatus group_stream_status) = 0; }; class LeAudioClientInterface { - public: +public: virtual ~LeAudioClientInterface() = default; /* Register the LeAudio callbacks */ - virtual void Initialize( - LeAudioClientCallbacks* callbacks, - const std::vector& offloading_preference) = 0; + virtual void Initialize(LeAudioClientCallbacks* callbacks, + const std::vector& offloading_preference) = 0; /** Connect to LEAudio */ virtual void Connect(const RawAddress& address) = 0; @@ -393,9 +381,8 @@ class LeAudioClientInterface { virtual void GroupSetActive(int group_id) = 0; /* Set codec config preference */ - virtual void SetCodecConfigPreference( - int group_id, btle_audio_codec_config_t input_codec_config, - btle_audio_codec_config_t output_codec_config) = 0; + virtual void SetCodecConfigPreference(int group_id, btle_audio_codec_config_t input_codec_config, + btle_audio_codec_config_t output_codec_config) = 0; /* Set Ccid for context type */ virtual void SetCcidInformation(int ccid, int context_type) = 0; @@ -407,9 +394,8 @@ class LeAudioClientInterface { virtual void SetUnicastMonitorMode(uint8_t direction, bool enable) = 0; /* Sends a preferred audio profiles change */ - virtual void SendAudioProfilePreferences( - int group_id, bool is_output_preference_le_audio, - bool is_duplex_preference_le_audio) = 0; + virtual void SendAudioProfilePreferences(int group_id, bool is_output_preference_le_audio, + bool is_duplex_preference_le_audio) = 0; /* Set allowed to stream context */ virtual void SetGroupAllowedContextMask(int group_id, int sink_context_types, @@ -509,7 +495,7 @@ struct BroadcastMetadata { }; class LeAudioBroadcasterCallbacks { - public: +public: virtual ~LeAudioBroadcasterCallbacks() = default; /* Callback for the newly created broadcast event. */ virtual void OnBroadcastCreated(uint32_t broadcast_id, bool success) = 0; @@ -517,15 +503,14 @@ class LeAudioBroadcasterCallbacks { /* Callback for the destroyed broadcast event. */ virtual void OnBroadcastDestroyed(uint32_t broadcast_id) = 0; /* Callback for the broadcast source state event. */ - virtual void OnBroadcastStateChanged(uint32_t broadcast_id, - BroadcastState state) = 0; + virtual void OnBroadcastStateChanged(uint32_t broadcast_id, BroadcastState state) = 0; /* Callback for the broadcast metadata change. */ - virtual void OnBroadcastMetadataChanged( - uint32_t broadcast_id, const BroadcastMetadata& broadcast_metadata) = 0; + virtual void OnBroadcastMetadataChanged(uint32_t broadcast_id, + const BroadcastMetadata& broadcast_metadata) = 0; }; class LeAudioBroadcasterInterface { - public: +public: virtual ~LeAudioBroadcasterInterface() = default; /* Register the LeAudio Broadcaster callbacks */ virtual void Initialize(LeAudioBroadcasterCallbacks* callbacks) = 0; @@ -534,17 +519,15 @@ class LeAudioBroadcasterInterface { /* Cleanup the LeAudio Broadcaster */ virtual void Cleanup(void) = 0; /* Create Broadcast instance */ - virtual void CreateBroadcast( - bool is_public, std::string broadcast_name, - std::optional broadcast_code, - std::vector public_metadata, - std::vector subgroup_quality, - std::vector> subgroup_metadata) = 0; + virtual void CreateBroadcast(bool is_public, std::string broadcast_name, + std::optional broadcast_code, + std::vector public_metadata, + std::vector subgroup_quality, + std::vector> subgroup_metadata) = 0; /* Update the ongoing Broadcast metadata */ - virtual void UpdateMetadata( - uint32_t broadcast_id, std::string broadcast_name, - std::vector public_metadata, - std::vector> subgroup_metadata) = 0; + virtual void UpdateMetadata(uint32_t broadcast_id, std::string broadcast_name, + std::vector public_metadata, + std::vector> subgroup_metadata) = 0; /* Start the existing Broadcast stream */ virtual void StartBroadcast(uint32_t broadcast_id) = 0; @@ -570,8 +553,7 @@ struct formatter : enum_formatter {}; template <> struct formatter - : enum_formatter { -}; + : enum_formatter {}; template <> struct formatter : enum_formatter {}; diff --git a/system/include/hardware/bt_pan.h b/system/include/hardware/bt_pan.h index 25261baf939..0b6b16bef3e 100644 --- a/system/include/hardware/bt_pan.h +++ b/system/include/hardware/bt_pan.h @@ -30,22 +30,16 @@ typedef enum { BTPAN_STATE_DISCONNECTING = 3 } btpan_connection_state_t; -typedef enum { - BTPAN_STATE_ENABLED = 0, - BTPAN_STATE_DISABLED = 1 -} btpan_control_state_t; +typedef enum { BTPAN_STATE_ENABLED = 0, BTPAN_STATE_DISABLED = 1 } btpan_control_state_t; /** * Callback for pan connection state */ -typedef void (*btpan_connection_state_callback)(btpan_connection_state_t state, - bt_status_t error, - const RawAddress* bd_addr, - int local_role, +typedef void (*btpan_connection_state_callback)(btpan_connection_state_t state, bt_status_t error, + const RawAddress* bd_addr, int local_role, int remote_role); -typedef void (*btpan_control_state_callback)(btpan_control_state_t state, - int local_role, bt_status_t error, - const char* ifname); +typedef void (*btpan_control_state_callback)(btpan_control_state_t state, int local_role, + bt_status_t error, const char* ifname); typedef struct { size_t size; @@ -74,8 +68,7 @@ typedef struct { * start bluetooth pan connection to the remote device by specified pan role. * The result state will be returned by btpan_connection_state_callback */ - bt_status_t (*connect)(const RawAddress* bd_addr, int local_role, - int remote_role); + bt_status_t (*connect)(const RawAddress* bd_addr, int local_role, int remote_role); /** * stop bluetooth pan connection. The result state will be returned by * btpan_connection_state_callback @@ -91,10 +84,8 @@ typedef struct { namespace fmt { template <> -struct formatter - : enum_formatter {}; +struct formatter : enum_formatter {}; template <> -struct formatter - : enum_formatter {}; +struct formatter : enum_formatter {}; } // namespace fmt diff --git a/system/include/hardware/bt_rc.h b/system/include/hardware/bt_rc.h index 84979394417..aa1baf84419 100644 --- a/system/include/hardware/bt_rc.h +++ b/system/include/hardware/bt_rc.h @@ -87,7 +87,7 @@ typedef enum { BTRC_FEAT_NONE = 0x00, /* AVRCP 1.0 */ BTRC_FEAT_METADATA = 0x01, /* AVRCP 1.3 */ BTRC_FEAT_ABSOLUTE_VOLUME = 0x02, /* Supports TG role and volume sync */ - BTRC_FEAT_BROWSE = 0x04, /* AVRCP 1.4 and up, with Browsing support */ + BTRC_FEAT_BROWSE = 0x04, /* AVRCP 1.4 and up, with Browsing support */ BTRC_FEAT_COVER_ARTWORK = 0x8, /* AVRCP 1.6 and up, Cover Art */ } btrc_remote_features_t; @@ -150,20 +150,20 @@ typedef enum { } btrc_player_shuffle_val_t; typedef enum { - BTRC_STS_BAD_CMD = 0x00, /* Invalid command */ - BTRC_STS_BAD_PARAM = 0x01, /* Invalid parameter */ - BTRC_STS_NOT_FOUND = 0x02, /* Specified parameter is wrong or not found */ - BTRC_STS_INTERNAL_ERR = 0x03, /* Internal Error */ - BTRC_STS_NO_ERROR = 0x04, /* Operation Success */ - BTRC_STS_UID_CHANGED = 0x05, /* UIDs changed */ - BTRC_STS_RESERVED = 0x06, /* Reserved */ - BTRC_STS_INV_DIRN = 0x07, /* Invalid direction */ - BTRC_STS_INV_DIRECTORY = 0x08, /* Invalid directory */ - BTRC_STS_INV_ITEM = 0x09, /* Invalid Item */ - BTRC_STS_INV_SCOPE = 0x0a, /* Invalid scope */ - BTRC_STS_INV_RANGE = 0x0b, /* Invalid range */ - BTRC_STS_DIRECTORY = 0x0c, /* UID is a directory */ - BTRC_STS_MEDIA_IN_USE = 0x0d, /* Media in use */ + BTRC_STS_BAD_CMD = 0x00, /* Invalid command */ + BTRC_STS_BAD_PARAM = 0x01, /* Invalid parameter */ + BTRC_STS_NOT_FOUND = 0x02, /* Specified parameter is wrong or not found */ + BTRC_STS_INTERNAL_ERR = 0x03, /* Internal Error */ + BTRC_STS_NO_ERROR = 0x04, /* Operation Success */ + BTRC_STS_UID_CHANGED = 0x05, /* UIDs changed */ + BTRC_STS_RESERVED = 0x06, /* Reserved */ + BTRC_STS_INV_DIRN = 0x07, /* Invalid direction */ + BTRC_STS_INV_DIRECTORY = 0x08, /* Invalid directory */ + BTRC_STS_INV_ITEM = 0x09, /* Invalid Item */ + BTRC_STS_INV_SCOPE = 0x0a, /* Invalid scope */ + BTRC_STS_INV_RANGE = 0x0b, /* Invalid range */ + BTRC_STS_DIRECTORY = 0x0c, /* UID is a directory */ + BTRC_STS_MEDIA_IN_USE = 0x0d, /* Media in use */ BTRC_STS_PLAY_LIST_FULL = 0x0e, /* Playing list full */ BTRC_STS_SRCH_NOT_SPRTD = 0x0f, /* Search not supported */ BTRC_STS_SRCH_IN_PROG = 0x10, /* Search in progress */ @@ -221,7 +221,9 @@ typedef struct { uint16_t uid_counter; } btrc_uids_changed_t; -typedef struct { uint16_t type; } btrc_now_playing_changed_t; +typedef struct { + uint16_t type; +} btrc_now_playing_changed_t; typedef union { btrc_play_status_t play_status; @@ -302,39 +304,37 @@ typedef void (*btrc_list_player_app_values_callback)(btrc_player_attr_t attr_id, /** Callback for getting the current player application settings value ** num_attr: specifies the number of attribute ids contained in p_attrs */ -typedef void (*btrc_get_player_app_value_callback)(uint8_t num_attr, - btrc_player_attr_t* p_attrs, +typedef void (*btrc_get_player_app_value_callback)(uint8_t num_attr, btrc_player_attr_t* p_attrs, const RawAddress& bd_addr); /** Callback for getting the player application settings attributes' text ** num_attr: specifies the number of attribute ids contained in p_attrs */ -typedef void (*btrc_get_player_app_attrs_text_callback)( - uint8_t num_attr, btrc_player_attr_t* p_attrs, const RawAddress& bd_addr); +typedef void (*btrc_get_player_app_attrs_text_callback)(uint8_t num_attr, + btrc_player_attr_t* p_attrs, + const RawAddress& bd_addr); /** Callback for getting the player application settings values' text ** num_attr: specifies the number of value ids contained in p_vals */ -typedef void (*btrc_get_player_app_values_text_callback)( - uint8_t attr_id, uint8_t num_val, uint8_t* p_vals, - const RawAddress& bd_addr); +typedef void (*btrc_get_player_app_values_text_callback)(uint8_t attr_id, uint8_t num_val, + uint8_t* p_vals, + const RawAddress& bd_addr); /** Callback for setting the player application settings values */ -typedef void (*btrc_set_player_app_value_callback)( - btrc_player_settings_t* p_vals, const RawAddress& bd_addr); +typedef void (*btrc_set_player_app_value_callback)(btrc_player_settings_t* p_vals, + const RawAddress& bd_addr); /** Callback to fetch the get element attributes of the current song ** num_attr: specifies the number of attributes requested in p_attrs */ -typedef void (*btrc_get_element_attr_callback)(uint8_t num_attr, - btrc_media_attr_t* p_attrs, +typedef void (*btrc_get_element_attr_callback)(uint8_t num_attr, btrc_media_attr_t* p_attrs, const RawAddress& bd_addr); /** Callback for register notification (Play state change/track change/...) ** param: Is only valid if event_id is BTRC_EVT_PLAY_POS_CHANGED */ -typedef void (*btrc_register_notification_callback)(btrc_event_id_t event_id, - uint32_t param, +typedef void (*btrc_register_notification_callback)(btrc_event_id_t event_id, uint32_t param, const RawAddress& bd_addr); /* AVRCP 1.4 Enhancements */ @@ -345,56 +345,47 @@ typedef void (*btrc_volume_change_callback)(uint8_t volume, uint8_t ctype, const RawAddress& bd_addr); /** Callback for passthrough commands */ -typedef void (*btrc_passthrough_cmd_callback)(int id, int key_state, - const RawAddress& bd_addr); +typedef void (*btrc_passthrough_cmd_callback)(int id, int key_state, const RawAddress& bd_addr); /** Callback for set addressed player response on TG **/ -typedef void (*btrc_set_addressed_player_callback)(uint16_t player_id, - const RawAddress& bd_addr); +typedef void (*btrc_set_addressed_player_callback)(uint16_t player_id, const RawAddress& bd_addr); /** Callback for set browsed player response on TG **/ -typedef void (*btrc_set_browsed_player_callback)(uint16_t player_id, - const RawAddress& bd_addr); +typedef void (*btrc_set_browsed_player_callback)(uint16_t player_id, const RawAddress& bd_addr); /** Callback for get folder items on TG ** num_attr: specifies the number of attributes requested in p_attr_ids */ -typedef void (*btrc_get_folder_items_callback)( - uint8_t scope, uint32_t start_item, uint32_t end_item, uint8_t num_attr, - uint32_t* p_attr_ids, const RawAddress& bd_addr); +typedef void (*btrc_get_folder_items_callback)(uint8_t scope, uint32_t start_item, + uint32_t end_item, uint8_t num_attr, + uint32_t* p_attr_ids, const RawAddress& bd_addr); /** Callback for changing browsed path on TG **/ -typedef void (*btrc_change_path_callback)(uint8_t direction, - uint8_t* folder_uid, +typedef void (*btrc_change_path_callback)(uint8_t direction, uint8_t* folder_uid, const RawAddress& bd_addr); /** Callback to fetch the get item attributes of the media item ** num_attr: specifies the number of attributes requested in p_attrs */ -typedef void (*btrc_get_item_attr_callback)(uint8_t scope, uint8_t* uid, - uint16_t uid_counter, - uint8_t num_attr, - btrc_media_attr_t* p_attrs, +typedef void (*btrc_get_item_attr_callback)(uint8_t scope, uint8_t* uid, uint16_t uid_counter, + uint8_t num_attr, btrc_media_attr_t* p_attrs, const RawAddress& bd_addr); /** Callback for play request for the media item indicated by an identifier */ -typedef void (*btrc_play_item_callback)(uint8_t scope, uint16_t uid_counter, - uint8_t* uid, +typedef void (*btrc_play_item_callback)(uint8_t scope, uint16_t uid_counter, uint8_t* uid, const RawAddress& bd_addr); /** Callback to fetch total number of items from a folder **/ -typedef void (*btrc_get_total_num_of_items_callback)(uint8_t scope, - const RawAddress& bd_addr); +typedef void (*btrc_get_total_num_of_items_callback)(uint8_t scope, const RawAddress& bd_addr); /** Callback for conducting recursive search on a current browsed path for a * specified string */ -typedef void (*btrc_search_callback)(uint16_t charset_id, uint16_t str_len, - uint8_t* p_str, const RawAddress& bd_addr); +typedef void (*btrc_search_callback)(uint16_t charset_id, uint16_t str_len, uint8_t* p_str, + const RawAddress& bd_addr); /** Callback to add a specified media item indicated by an identifier to now * playing queue. */ -typedef void (*btrc_add_to_now_playing_callback)(uint8_t scope, uint8_t* uid, - uint16_t uid_counter, +typedef void (*btrc_add_to_now_playing_callback)(uint8_t scope, uint8_t* uid, uint16_t uid_counter, const RawAddress& bd_addr); /** BT-RC Target callback structure. */ @@ -438,23 +429,20 @@ typedef struct { ** 2. Song duration/length ** 3. Song position */ - bt_status_t (*get_play_status_rsp)(const RawAddress& bd_addr, - btrc_play_status_t play_status, + bt_status_t (*get_play_status_rsp)(const RawAddress& bd_addr, btrc_play_status_t play_status, uint32_t song_len, uint32_t song_pos); /** Lists the support player application attributes (Shuffle/Repeat/...) ** num_attr: Specifies the number of attributes contained in the pointer *p_attrs */ - bt_status_t (*list_player_app_attr_rsp)(const RawAddress& bd_addr, - int num_attr, + bt_status_t (*list_player_app_attr_rsp)(const RawAddress& bd_addr, int num_attr, btrc_player_attr_t* p_attrs); /** Lists the support player application attributes (Shuffle Off/On/Group) ** num_val: Specifies the number of values contained in the pointer p_vals */ - bt_status_t (*list_player_app_value_rsp)(const RawAddress& bd_addr, - int num_val, uint8_t* p_vals); + bt_status_t (*list_player_app_value_rsp)(const RawAddress& bd_addr, int num_val, uint8_t* p_vals); /** Returns the current application attribute values for each of the specified * attr_id */ @@ -465,33 +453,29 @@ typedef struct { ** num_attr: Specifies the number of attributes' text contained in the *pointer p_attrs */ - bt_status_t (*get_player_app_attr_text_rsp)( - const RawAddress& bd_addr, int num_attr, - btrc_player_setting_text_t* p_attrs); + bt_status_t (*get_player_app_attr_text_rsp)(const RawAddress& bd_addr, int num_attr, + btrc_player_setting_text_t* p_attrs); /** Returns the application attributes text ("Shuffle"/"Repeat"/...) ** num_attr: Specifies the number of attribute values' text contained in the *pointer p_vals */ - bt_status_t (*get_player_app_value_text_rsp)( - const RawAddress& bd_addr, int num_val, - btrc_player_setting_text_t* p_vals); + bt_status_t (*get_player_app_value_text_rsp)(const RawAddress& bd_addr, int num_val, + btrc_player_setting_text_t* p_vals); /** Returns the current songs' element attributes text *("Title"/"Album"/"Artist") ** num_attr: Specifies the number of attributes' text contained in the *pointer p_attrs */ - bt_status_t (*get_element_attr_rsp)(const RawAddress& bd_addr, - uint8_t num_attr, + bt_status_t (*get_element_attr_rsp)(const RawAddress& bd_addr, uint8_t num_attr, btrc_element_attr_val_t* p_attrs); /** Response to set player attribute request ("Shuffle"/"Repeat") ** rsp_status: Status of setting the player attributes for the current media *player */ - bt_status_t (*set_player_app_value_rsp)(const RawAddress& bd_addr, - btrc_status_t rsp_status); + bt_status_t (*set_player_app_value_rsp)(const RawAddress& bd_addr, btrc_status_t rsp_status); /* Response to the register notification request (Play state change/track *change/...). @@ -499,9 +483,8 @@ typedef struct { ** type: Response type - interim/changed ** p_params: Based on the event_id, this parameter should be populated */ - bt_status_t (*register_notification_rsp)( - btrc_event_id_t event_id, btrc_notification_type_t type, - btrc_register_notification_t* p_param); + bt_status_t (*register_notification_rsp)(btrc_event_id_t event_id, btrc_notification_type_t type, + btrc_register_notification_t* p_param); /* AVRCP 1.4 enhancements */ @@ -510,121 +493,101 @@ typedef struct { ** This can be enhanced to support Relative Volume (AVRCP 1.0). ** With RelateVolume, we will send VOLUME_UP/VOLUME_DOWN opposed to absolute *volume level - ** volume: Should be in the range 0-127. bit7 is reseved and cannot be set + ** volume: Should be in the range 0-127. bit7 is reserved and cannot be set */ bt_status_t (*set_volume)(uint8_t volume); /* Set addressed player response from TG to CT */ - bt_status_t (*set_addressed_player_rsp)(const RawAddress& bd_addr, - btrc_status_t rsp_status); + bt_status_t (*set_addressed_player_rsp)(const RawAddress& bd_addr, btrc_status_t rsp_status); /* Set browsed player response from TG to CT */ - bt_status_t (*set_browsed_player_rsp)(const RawAddress& bd_addr, - btrc_status_t rsp_status, + bt_status_t (*set_browsed_player_rsp)(const RawAddress& bd_addr, btrc_status_t rsp_status, uint32_t num_items, uint16_t charset_id, - uint8_t folder_depth, - btrc_br_folder_name_t* p_folders); + uint8_t folder_depth, btrc_br_folder_name_t* p_folders); /* Get folder item list response from TG to CT */ - bt_status_t (*get_folder_items_list_rsp)(const RawAddress& bd_addr, - btrc_status_t rsp_status, - uint16_t uid_counter, - uint8_t num_items, + bt_status_t (*get_folder_items_list_rsp)(const RawAddress& bd_addr, btrc_status_t rsp_status, + uint16_t uid_counter, uint8_t num_items, btrc_folder_items_t* p_items); /* Change path response from TG to CT */ - bt_status_t (*change_path_rsp)(const RawAddress& bd_addr, - btrc_status_t rsp_status, uint32_t num_items); + bt_status_t (*change_path_rsp)(const RawAddress& bd_addr, btrc_status_t rsp_status, + uint32_t num_items); /** Returns the element's attributes num_attr: Specifies the number of * attributes' text contained in the pointer p_attrs */ - bt_status_t (*get_item_attr_rsp)(const RawAddress& bd_addr, - btrc_status_t rsp_status, uint8_t num_attr, - btrc_element_attr_val_t* p_attrs); + bt_status_t (*get_item_attr_rsp)(const RawAddress& bd_addr, btrc_status_t rsp_status, + uint8_t num_attr, btrc_element_attr_val_t* p_attrs); /* play media item response from TG to CT */ - bt_status_t (*play_item_rsp)(const RawAddress& bd_addr, - btrc_status_t rsp_status); + bt_status_t (*play_item_rsp)(const RawAddress& bd_addr, btrc_status_t rsp_status); /* get total number of items response from TG to CT*/ - bt_status_t (*get_total_num_of_items_rsp)(const RawAddress& bd_addr, - btrc_status_t rsp_status, - uint32_t uid_counter, - uint32_t num_items); + bt_status_t (*get_total_num_of_items_rsp)(const RawAddress& bd_addr, btrc_status_t rsp_status, + uint32_t uid_counter, uint32_t num_items); /* Search VFS response from TG to CT */ bt_status_t (*search_rsp)(const RawAddress& bd_addr, btrc_status_t rsp_status, uint32_t uid_counter, uint32_t num_items); /* add_to_now playing list response from TG to CT */ - bt_status_t (*add_to_now_playing_rsp)(const RawAddress& bd_addr, - btrc_status_t rsp_status); + bt_status_t (*add_to_now_playing_rsp)(const RawAddress& bd_addr, btrc_status_t rsp_status); /** Closes the interface. */ void (*cleanup)(void); } btrc_interface_t; -typedef void (*btrc_passthrough_rsp_callback)(const RawAddress& bd_addr, int id, - int key_state); +typedef void (*btrc_passthrough_rsp_callback)(const RawAddress& bd_addr, int id, int key_state); typedef void (*btrc_groupnavigation_rsp_callback)(int id, int key_state); typedef void (*btrc_connection_state_callback)(bool rc_connect, bool bt_connect, const RawAddress& bd_addr); -typedef void (*btrc_ctrl_getrcfeatures_callback)(const RawAddress& bd_addr, - int features); +typedef void (*btrc_ctrl_getrcfeatures_callback)(const RawAddress& bd_addr, int features); -typedef void (*btrc_ctrl_setabsvol_cmd_callback)(const RawAddress& bd_addr, - uint8_t abs_vol, +typedef void (*btrc_ctrl_setabsvol_cmd_callback)(const RawAddress& bd_addr, uint8_t abs_vol, uint8_t label); -typedef void (*btrc_ctrl_registernotification_abs_vol_callback)( - const RawAddress& bd_addr, uint8_t label); +typedef void (*btrc_ctrl_registernotification_abs_vol_callback)(const RawAddress& bd_addr, + uint8_t label); -typedef void (*btrc_ctrl_setplayerapplicationsetting_rsp_callback)( - const RawAddress& bd_addr, uint8_t accepted); +typedef void (*btrc_ctrl_setplayerapplicationsetting_rsp_callback)(const RawAddress& bd_addr, + uint8_t accepted); -typedef void (*btrc_ctrl_playerapplicationsetting_callback)( - const RawAddress& bd_addr, uint8_t num_attr, - btrc_player_app_attr_t* app_attrs, uint8_t num_ext_attr, - btrc_player_app_ext_attr_t* ext_attrs); +typedef void (*btrc_ctrl_playerapplicationsetting_callback)(const RawAddress& bd_addr, + uint8_t num_attr, + btrc_player_app_attr_t* app_attrs, + uint8_t num_ext_attr, + btrc_player_app_ext_attr_t* ext_attrs); typedef void (*btrc_ctrl_playerapplicationsetting_changed_callback)( - const RawAddress& bd_addr, const btrc_player_settings_t& vals); + const RawAddress& bd_addr, const btrc_player_settings_t& vals); -typedef void (*btrc_ctrl_track_changed_callback)( - const RawAddress& bd_addr, uint8_t num_attr, - btrc_element_attr_val_t* p_attrs); +typedef void (*btrc_ctrl_track_changed_callback)(const RawAddress& bd_addr, uint8_t num_attr, + btrc_element_attr_val_t* p_attrs); -typedef void (*btrc_ctrl_play_position_changed_callback)( - const RawAddress& bd_addr, uint32_t song_len, uint32_t song_pos); +typedef void (*btrc_ctrl_play_position_changed_callback)(const RawAddress& bd_addr, + uint32_t song_len, uint32_t song_pos); -typedef void (*btrc_ctrl_play_status_changed_callback)( - const RawAddress& bd_addr, btrc_play_status_t play_status); +typedef void (*btrc_ctrl_play_status_changed_callback)(const RawAddress& bd_addr, + btrc_play_status_t play_status); -typedef void (*btrc_ctrl_get_folder_items_callback)( - const RawAddress& bd_addr, btrc_status_t status, - const btrc_folder_items_t* folder_items, uint8_t count); +typedef void (*btrc_ctrl_get_folder_items_callback)(const RawAddress& bd_addr, btrc_status_t status, + const btrc_folder_items_t* folder_items, + uint8_t count); -typedef void (*btrc_ctrl_change_path_callback)(const RawAddress& bd_addr, - uint32_t count); +typedef void (*btrc_ctrl_change_path_callback)(const RawAddress& bd_addr, uint32_t count); -typedef void (*btrc_ctrl_set_browsed_player_callback)(const RawAddress& bd_addr, - uint8_t num_items, +typedef void (*btrc_ctrl_set_browsed_player_callback)(const RawAddress& bd_addr, uint8_t num_items, uint8_t depth); -typedef void (*btrc_ctrl_set_addressed_player_callback)( - const RawAddress& bd_addr, uint8_t status); -typedef void (*btrc_ctrl_addressed_player_changed_callback)( - const RawAddress& bd_addr, uint16_t id); -typedef void (*btrc_ctrl_now_playing_contents_changed_callback)( - const RawAddress& bd_addr); -typedef void (*btrc_ctrl_available_player_changed_callback)( - const RawAddress& bd_addr); - -typedef void (*btrc_ctrl_get_cover_art_psm_callback)(const RawAddress& bd_addr, - const uint16_t psm); +typedef void (*btrc_ctrl_set_addressed_player_callback)(const RawAddress& bd_addr, uint8_t status); +typedef void (*btrc_ctrl_addressed_player_changed_callback)(const RawAddress& bd_addr, uint16_t id); +typedef void (*btrc_ctrl_now_playing_contents_changed_callback)(const RawAddress& bd_addr); +typedef void (*btrc_ctrl_available_player_changed_callback)(const RawAddress& bd_addr); + +typedef void (*btrc_ctrl_get_cover_art_psm_callback)(const RawAddress& bd_addr, const uint16_t psm); /** BT-RC Controller callback structure. */ typedef struct { @@ -636,11 +599,9 @@ typedef struct { btrc_ctrl_getrcfeatures_callback getrcfeatures_cb; btrc_ctrl_setplayerapplicationsetting_rsp_callback setplayerappsetting_rsp_cb; btrc_ctrl_playerapplicationsetting_callback playerapplicationsetting_cb; - btrc_ctrl_playerapplicationsetting_changed_callback - playerapplicationsetting_changed_cb; + btrc_ctrl_playerapplicationsetting_changed_callback playerapplicationsetting_changed_cb; btrc_ctrl_setabsvol_cmd_callback setabsvol_cmd_cb; - btrc_ctrl_registernotification_abs_vol_callback - registernotification_absvol_cb; + btrc_ctrl_registernotification_abs_vol_callback registernotification_absvol_cb; btrc_ctrl_track_changed_callback track_changed_cb; btrc_ctrl_play_position_changed_callback play_position_changed_cb; btrc_ctrl_play_status_changed_callback play_status_changed_cb; @@ -649,8 +610,7 @@ typedef struct { btrc_ctrl_set_browsed_player_callback set_browsed_player_cb; btrc_ctrl_set_addressed_player_callback set_addressed_player_cb; btrc_ctrl_addressed_player_changed_callback addressed_player_changed_cb; - btrc_ctrl_now_playing_contents_changed_callback - now_playing_contents_changed_cb; + btrc_ctrl_now_playing_contents_changed_callback now_playing_contents_changed_cb; btrc_ctrl_available_player_changed_callback available_player_changed_cb; btrc_ctrl_get_cover_art_psm_callback get_cover_art_psm_cb; } btrc_ctrl_callbacks_t; @@ -665,22 +625,20 @@ typedef struct { bt_status_t (*init)(btrc_ctrl_callbacks_t* callbacks); /** send pass through command to target */ - bt_status_t (*send_pass_through_cmd)(const RawAddress& bd_addr, - uint8_t key_code, uint8_t key_state); + bt_status_t (*send_pass_through_cmd)(const RawAddress& bd_addr, uint8_t key_code, + uint8_t key_state); /** send group navigation command to target */ - bt_status_t (*send_group_navigation_cmd)(const RawAddress& bd_addr, - uint8_t key_code, uint8_t key_state); + bt_status_t (*send_group_navigation_cmd)(const RawAddress& bd_addr, uint8_t key_code, + uint8_t key_state); - /** send command to set player applicaiton setting attributes to target */ - bt_status_t (*set_player_app_setting_cmd)(const RawAddress& bd_addr, - uint8_t num_attrib, - uint8_t* attrib_ids, - uint8_t* attrib_vals); + /** send command to set player application setting attributes to target */ + bt_status_t (*set_player_app_setting_cmd)(const RawAddress& bd_addr, uint8_t num_attrib, + uint8_t* attrib_ids, uint8_t* attrib_vals); /** send command to play a particular item */ - bt_status_t (*play_item_cmd)(const RawAddress& bd_addr, uint8_t scope, - uint8_t* uid, uint16_t uid_counter); + bt_status_t (*play_item_cmd)(const RawAddress& bd_addr, uint8_t scope, uint8_t* uid, + uint16_t uid_counter); /** get the current track's media metadata */ bt_status_t (*get_current_metadata_cmd)(const RawAddress& bd_addr); @@ -689,36 +647,28 @@ typedef struct { bt_status_t (*get_playback_state_cmd)(const RawAddress& bd_addr); /** get the now playing list */ - bt_status_t (*get_now_playing_list_cmd)(const RawAddress& bd_addr, - uint32_t start, uint32_t end); + bt_status_t (*get_now_playing_list_cmd)(const RawAddress& bd_addr, uint32_t start, uint32_t end); /** get the folder list */ - bt_status_t (*get_folder_list_cmd)(const RawAddress& bd_addr, uint32_t start, - uint32_t end); + bt_status_t (*get_folder_list_cmd)(const RawAddress& bd_addr, uint32_t start, uint32_t end); /** get the player list */ - bt_status_t (*get_player_list_cmd)(const RawAddress& bd_addr, uint32_t start, - uint32_t end); + bt_status_t (*get_player_list_cmd)(const RawAddress& bd_addr, uint32_t start, uint32_t end); /** change the folder path */ - bt_status_t (*change_folder_path_cmd)(const RawAddress& bd_addr, - uint8_t direction, uint8_t* uid); + bt_status_t (*change_folder_path_cmd)(const RawAddress& bd_addr, uint8_t direction, uint8_t* uid); /** set browsed player */ - bt_status_t (*set_browsed_player_cmd)(const RawAddress& bd_addr, - uint16_t player_id); + bt_status_t (*set_browsed_player_cmd)(const RawAddress& bd_addr, uint16_t player_id); /** set addressed player */ - bt_status_t (*set_addressed_player_cmd)(const RawAddress& bd_addr, - uint16_t player_id); + bt_status_t (*set_addressed_player_cmd)(const RawAddress& bd_addr, uint16_t player_id); /** send rsp to set_abs_vol received from target */ - bt_status_t (*set_volume_rsp)(const RawAddress& bd_addr, uint8_t abs_vol, - uint8_t label); + bt_status_t (*set_volume_rsp)(const RawAddress& bd_addr, uint8_t abs_vol, uint8_t label); /** send notificaiton rsp for abs vol to target */ - bt_status_t (*register_abs_vol_rsp)(const RawAddress& bd_addr, - btrc_notification_type_t rsp_type, + bt_status_t (*register_abs_vol_rsp)(const RawAddress& bd_addr, btrc_notification_type_t rsp_type, uint8_t abs_vol, uint8_t label); /** Closes the interface. */ @@ -736,11 +686,9 @@ struct formatter : enum_formatter {}; template <> struct formatter : enum_formatter {}; template <> -struct formatter - : enum_formatter {}; +struct formatter : enum_formatter {}; template <> -struct formatter - : enum_formatter {}; +struct formatter : enum_formatter {}; } // namespace fmt #endif // __has_include() diff --git a/system/include/hardware/bt_sdp.h b/system/include/hardware/bt_sdp.h index fd4a970e057..db9c3b71cbc 100644 --- a/system/include/hardware/bt_sdp.h +++ b/system/include/hardware/bt_sdp.h @@ -132,10 +132,8 @@ typedef union { } bluetooth_sdp_record; /** Callback for SDP search */ -typedef void (*btsdp_search_callback)(bt_status_t status, - const RawAddress& bd_addr, - const bluetooth::Uuid& uuid, - int num_records, +typedef void (*btsdp_search_callback)(bt_status_t status, const RawAddress& bd_addr, + const bluetooth::Uuid& uuid, int num_records, bluetooth_sdp_record* records); typedef struct { @@ -170,8 +168,7 @@ typedef struct { * record_handle (out)The corresponding record handle will be written to * this pointer. */ - bt_status_t (*create_sdp_record)(bluetooth_sdp_record* record, - int* record_handle); + bt_status_t (*create_sdp_record)(bluetooth_sdp_record* record, int* record_handle); /** Remove a SDP record created by createSdpRecord */ bt_status_t (*remove_sdp_record)(int sdp_handle); diff --git a/system/include/hardware/bt_sock.h b/system/include/hardware/bt_sock.h index 4adc6fcb8b1..4755cef5f8b 100644 --- a/system/include/hardware/bt_sock.h +++ b/system/include/hardware/bt_sock.h @@ -72,8 +72,8 @@ typedef struct { * socket. This is used for traffic accounting purposes. */ bt_status_t (*listen)(btsock_type_t type, const char* service_name, - const bluetooth::Uuid* service_uuid, int channel, - int* sock_fd, int flags, int callingUid); + const bluetooth::Uuid* service_uuid, int channel, int* sock_fd, int flags, + int callingUid); /** * Connect to a RFCOMM UUID channel of remote device, It returns the socket fd @@ -82,9 +82,8 @@ typedef struct { * which is requesting the socket. This is used for traffic accounting * purposes. */ - bt_status_t (*connect)(const RawAddress* bd_addr, btsock_type_t type, - const bluetooth::Uuid* uuid, int channel, int* sock_fd, - int flags, int callingUid); + bt_status_t (*connect)(const RawAddress* bd_addr, btsock_type_t type, const bluetooth::Uuid* uuid, + int channel, int* sock_fd, int flags, int callingUid); /** * Set the LE Data Length value to this connected peer to the @@ -100,10 +99,9 @@ typedef struct { * This API allows the host to start the control request while it works as an * RFCOMM server. */ - bt_status_t (*control_req)(uint8_t dlci, const RawAddress& bd_addr, - uint8_t modem_signal, uint8_t break_signal, - uint8_t discard_buffers, uint8_t break_signal_seq, - bool fc); + bt_status_t (*control_req)(uint8_t dlci, const RawAddress& bd_addr, uint8_t modem_signal, + uint8_t break_signal, uint8_t discard_buffers, + uint8_t break_signal_seq, bool fc); /** * Disconnect all RFCOMM and L2CAP socket connections with the associated @@ -119,8 +117,7 @@ typedef struct { /** * Get L2CAP remote channel ID with the associated connection uuid. */ - bt_status_t (*get_l2cap_remote_cid)(bluetooth::Uuid& conn_uuid, - uint16_t* cid); + bt_status_t (*get_l2cap_remote_cid)(bluetooth::Uuid& conn_uuid, uint16_t* cid); } btsock_interface_t; diff --git a/system/include/hardware/bt_vc.h b/system/include/hardware/bt_vc.h index 090ff9cfba2..74ed8140029 100644 --- a/system/include/hardware/bt_vc.h +++ b/system/include/hardware/bt_vc.h @@ -25,47 +25,37 @@ namespace bluetooth { namespace vc { -enum class ConnectionState { - DISCONNECTED = 0, - CONNECTING, - CONNECTED, - DISCONNECTING -}; +enum class ConnectionState { DISCONNECTED = 0, CONNECTING, CONNECTED, DISCONNECTING }; class VolumeControlCallbacks { - public: +public: virtual ~VolumeControlCallbacks() = default; /** Callback for profile connection state change */ - virtual void OnConnectionState(ConnectionState state, - const RawAddress& address) = 0; + virtual void OnConnectionState(ConnectionState state, const RawAddress& address) = 0; /* Callback for the volume change changed on the device */ - virtual void OnVolumeStateChanged(const RawAddress& address, uint8_t volume, - bool mute, bool isAutonomous) = 0; + virtual void OnVolumeStateChanged(const RawAddress& address, uint8_t volume, bool mute, + bool isAutonomous) = 0; /* Callback for the volume change changed on the group*/ - virtual void OnGroupVolumeStateChanged(int group_id, uint8_t volume, - bool mute, bool isAutonomous) = 0; + virtual void OnGroupVolumeStateChanged(int group_id, uint8_t volume, bool mute, + bool isAutonomous) = 0; - virtual void OnDeviceAvailable(const RawAddress& address, - uint8_t num_offset) = 0; + virtual void OnDeviceAvailable(const RawAddress& address, uint8_t num_offset) = 0; /* Callbacks for Volume Offset Control Service (VOCS) - Extended Audio Outputs */ - virtual void OnExtAudioOutVolumeOffsetChanged(const RawAddress& address, - uint8_t ext_output_id, + virtual void OnExtAudioOutVolumeOffsetChanged(const RawAddress& address, uint8_t ext_output_id, int16_t offset) = 0; - virtual void OnExtAudioOutLocationChanged(const RawAddress& address, - uint8_t ext_output_id, + virtual void OnExtAudioOutLocationChanged(const RawAddress& address, uint8_t ext_output_id, uint32_t location) = 0; - virtual void OnExtAudioOutDescriptionChanged(const RawAddress& address, - uint8_t ext_output_id, + virtual void OnExtAudioOutDescriptionChanged(const RawAddress& address, uint8_t ext_output_id, std::string descr) = 0; }; class VolumeControlInterface { - public: +public: virtual ~VolumeControlInterface() = default; /** Register the Volume Control callbacks */ @@ -84,28 +74,21 @@ class VolumeControlInterface { virtual void RemoveDevice(const RawAddress& address) = 0; /** Set the volume */ - virtual void SetVolume(std::variant addr_or_group_id, - uint8_t volume) = 0; + virtual void SetVolume(std::variant addr_or_group_id, uint8_t volume) = 0; /** Mute the volume */ virtual void Mute(std::variant addr_or_group_id) = 0; /** Unmute the volume */ virtual void Unmute(std::variant addr_or_group_id) = 0; - virtual void GetExtAudioOutVolumeOffset(const RawAddress& address, - uint8_t ext_output_id) = 0; - virtual void SetExtAudioOutVolumeOffset(const RawAddress& address, - uint8_t ext_output_id, + virtual void GetExtAudioOutVolumeOffset(const RawAddress& address, uint8_t ext_output_id) = 0; + virtual void SetExtAudioOutVolumeOffset(const RawAddress& address, uint8_t ext_output_id, int16_t offset_val) = 0; - virtual void GetExtAudioOutLocation(const RawAddress& address, - uint8_t ext_output_id) = 0; - virtual void SetExtAudioOutLocation(const RawAddress& address, - uint8_t ext_output_id, + virtual void GetExtAudioOutLocation(const RawAddress& address, uint8_t ext_output_id) = 0; + virtual void SetExtAudioOutLocation(const RawAddress& address, uint8_t ext_output_id, uint32_t location) = 0; - virtual void GetExtAudioOutDescription(const RawAddress& address, - uint8_t ext_output_id) = 0; - virtual void SetExtAudioOutDescription(const RawAddress& address, - uint8_t ext_output_id, + virtual void GetExtAudioOutDescription(const RawAddress& address, uint8_t ext_output_id) = 0; + virtual void SetExtAudioOutDescription(const RawAddress& address, uint8_t ext_output_id, std::string descr) = 0; }; diff --git a/system/include/hardware/distance_measurement_interface.h b/system/include/hardware/distance_measurement_interface.h index 99aa7c2f2c7..4472e318d4c 100644 --- a/system/include/hardware/distance_measurement_interface.h +++ b/system/include/hardware/distance_measurement_interface.h @@ -24,30 +24,25 @@ * Bluetooth native stack All callbacks are invoked on the JNI thread */ class DistanceMeasurementCallbacks { - public: +public: virtual ~DistanceMeasurementCallbacks() = default; - virtual void OnDistanceMeasurementStarted(RawAddress address, - uint8_t method) = 0; - virtual void OnDistanceMeasurementStartFail(RawAddress address, - uint8_t reason, + virtual void OnDistanceMeasurementStarted(RawAddress address, uint8_t method) = 0; + virtual void OnDistanceMeasurementStartFail(RawAddress address, uint8_t reason, uint8_t method) = 0; - virtual void OnDistanceMeasurementStopped(RawAddress address, uint8_t reason, - uint8_t method) = 0; - virtual void OnDistanceMeasurementResult( - RawAddress address, uint32_t centimeter, uint32_t error_centimeter, - int azimuth_angle, int error_azimuth_angle, int altitude_angle, - int error_altitude_angle, uint8_t method) = 0; + virtual void OnDistanceMeasurementStopped(RawAddress address, uint8_t reason, uint8_t method) = 0; + virtual void OnDistanceMeasurementResult(RawAddress address, uint32_t centimeter, + uint32_t error_centimeter, int azimuth_angle, + int error_azimuth_angle, int altitude_angle, + int error_altitude_angle, uint8_t method) = 0; }; class DistanceMeasurementInterface { - public: +public: virtual ~DistanceMeasurementInterface() = default; - virtual void RegisterDistanceMeasurementCallbacks( - DistanceMeasurementCallbacks* callbacks) = 0; - virtual void StartDistanceMeasurement(RawAddress raw_address, - uint16_t interval, uint8_t method) = 0; - virtual void StopDistanceMeasurement(RawAddress raw_address, - uint8_t method) = 0; + virtual void RegisterDistanceMeasurementCallbacks(DistanceMeasurementCallbacks* callbacks) = 0; + virtual void StartDistanceMeasurement(RawAddress raw_address, uint16_t interval, + uint8_t method) = 0; + virtual void StopDistanceMeasurement(RawAddress raw_address, uint8_t method) = 0; }; #endif /* ANDROID_INCLUDE_DISTANCE_MEASUREMENT_INTERFACE_H */ diff --git a/system/include/macros.h b/system/include/macros.h index 68dd4df3f99..1bf83cd7b99 100644 --- a/system/include/macros.h +++ b/system/include/macros.h @@ -25,16 +25,13 @@ case code: \ return #code -#define CASE_RETURN_STRING(enumerator) \ - case enumerator: \ - return fmt::format(#enumerator "(0x{:x})", \ - static_cast(enumerator)) +#define CASE_RETURN_STRING(enumerator) \ + case enumerator: \ + return fmt::format(#enumerator "(0x{:x})", static_cast(enumerator)) -#define CASE_RETURN_STRING_HEX04(enumerator) \ - case enumerator: \ - return fmt::format(#enumerator "(0x{:04x})", \ - static_cast(enumerator)) +#define CASE_RETURN_STRING_HEX04(enumerator) \ + case enumerator: \ + return fmt::format(#enumerator "(0x{:04x})", static_cast(enumerator)) #define RETURN_UNKNOWN_TYPE_STRING(type, variable) \ - return fmt::format("Unknown {}(0x{:x})", #type, \ - static_cast(variable)) + return fmt::format("Unknown {}(0x{:x})", #type, static_cast(variable)) diff --git a/system/internal_include/bt_target.h b/system/internal_include/bt_target.h index 41e94f20c64..ab57f98cc58 100644 --- a/system/internal_include/bt_target.h +++ b/system/internal_include/bt_target.h @@ -28,7 +28,7 @@ #define TRUE true #endif -//------------------Added from bdroid_buildcfg.h--------------------- +// ------------------Added from bdroid_buildcfg.h--------------------- #ifndef L2CAP_EXTFEA_SUPPORTED_MASK #define L2CAP_EXTFEA_SUPPORTED_MASK \ (L2CAP_EXTFEA_ENH_RETRANS | L2CAP_EXTFEA_STREAM_MODE | L2CAP_EXTFEA_NO_CRC | \ @@ -40,8 +40,7 @@ #endif #ifndef BTA_RFC_MTU_SIZE -#define BTA_RFC_MTU_SIZE \ - (L2CAP_MTU_SIZE - L2CAP_MIN_OFFSET - RFCOMM_DATA_OVERHEAD) +#define BTA_RFC_MTU_SIZE (L2CAP_MTU_SIZE - L2CAP_MIN_OFFSET - RFCOMM_DATA_OVERHEAD) #endif #ifndef BTA_PAN_INCLUDED @@ -92,7 +91,7 @@ #define BTA_FTC_IDLE_TO_SNIFF_DELAY_MS 5000 #endif -//------------------End added from bdroid_buildcfg.h--------------------- +// ------------------End added from bdroid_buildcfg.h--------------------- /****************************************************************************** * @@ -323,8 +322,7 @@ #endif #ifndef L2CAP_LAST_FIXED_CHNL -#define L2CAP_LAST_FIXED_CHNL \ - (L2CAP_FIRST_FIXED_CHNL + L2CAP_NUM_FIXED_CHNLS - 1) +#define L2CAP_LAST_FIXED_CHNL (L2CAP_FIRST_FIXED_CHNL + L2CAP_NUM_FIXED_CHNLS - 1) #endif /* Used for conformance testing ONLY: When TRUE lets scriptwrapper overwrite @@ -707,7 +705,7 @@ /************************************************************************* * Definitions for Both HID-Host & Device -*/ + */ #ifndef HID_MAX_SVC_NAME_LEN #define HID_MAX_SVC_NAME_LEN 32 #endif @@ -722,7 +720,7 @@ /************************************************************************* * Definitions for HID-Host -*/ + */ #ifndef HID_HOST_INCLUDED #define HID_HOST_INCLUDED TRUE #endif diff --git a/system/internal_include/bt_trace.h b/system/internal_include/bt_trace.h index e6fdc6531dd..5bd07ca0e0e 100644 --- a/system/internal_include/bt_trace.h +++ b/system/internal_include/bt_trace.h @@ -34,8 +34,7 @@ /* Prints integral parameter x as hex string, with '0' fill */ template std::string loghex(T x) { - static_assert(std::is_integral::value, - "loghex parameter must be integral."); + static_assert(std::is_integral::value, "loghex parameter must be integral."); std::stringstream tmp; tmp << std::showbase << std::internal << std::hex << std::setfill('0') << std::setw((sizeof(T) * 2) + 2) << +x; @@ -45,12 +44,11 @@ std::string loghex(T x) { /* Prints integral array as hex string, with '0' fill */ template std::string loghex(std::array array) { - static_assert(std::is_integral::value, - "type stored in array must be integral."); + static_assert(std::is_integral::value, "type stored in array must be integral."); std::stringstream tmp; for (const auto& x : array) { - tmp << std::internal << std::hex << std::setfill('0') - << std::setw((sizeof(uint8_t) * 2) + 2) << +x; + tmp << std::internal << std::hex << std::setfill('0') << std::setw((sizeof(uint8_t) * 2) + 2) + << +x; } return tmp.str(); } @@ -65,12 +63,14 @@ std::string loghex(std::array array) { * @param name the field name to add * @return the result string */ -inline std::string& AppendField(std::string* p_result, bool append, - const std::string& name) { - bluetooth::log::assert_that(p_result != nullptr, - "assert failed: p_result != nullptr"); - if (!append) return *p_result; - if (!p_result->empty()) *p_result += "|"; +inline std::string& AppendField(std::string* p_result, bool append, const std::string& name) { + bluetooth::log::assert_that(p_result != nullptr, "assert failed: p_result != nullptr"); + if (!append) { + return *p_result; + } + if (!p_result->empty()) { + *p_result += "|"; + } *p_result += name; return *p_result; } diff --git a/system/log/include/bluetooth/log.h b/system/log/include/bluetooth/log.h index f7e923cf2e5..45ab7d93772 100644 --- a/system/log/include/bluetooth/log.h +++ b/system/log/include/bluetooth/log.h @@ -42,8 +42,7 @@ enum Level { /// Passing this parameter by default value will fill in /// the correct information. struct source_location { - source_location(char const* file_name = __builtin_FILE(), - int line = __builtin_LINE(), + source_location(char const* file_name = __builtin_FILE(), int line = __builtin_LINE(), char const* function_name = __builtin_FUNCTION()) : line(line), file_name(file_name), function_name(function_name) {} @@ -54,8 +53,8 @@ struct source_location { /// Write a single log line. /// The implementation of this function is dependent on the backend. -void vlog(Level level, char const* tag, source_location location, - fmt::string_view fmt, fmt::format_args vargs); +void vlog(Level level, char const* tag, source_location location, fmt::string_view fmt, + fmt::format_args vargs); /// Capture invalid parameter values that would cause runtime /// formatting errors. @@ -68,7 +67,9 @@ template template <> char const*& format_replace(char const*& arg) { static char const* nullptr_str = "(nullptr)"; - if (arg) return arg; + if (arg) { + return arg; + } return nullptr_str; } @@ -76,14 +77,15 @@ char const*& format_replace(char const*& arg) { template <> char*& format_replace(char*& arg) { static char* nullptr_str = (char*)"(nullptr)"; - if (arg) return arg; + if (arg) { + return arg; + } return nullptr_str; } template struct log { - log(fmt::format_string fmt, T&&... args, - source_location location = source_location()) { + log(fmt::format_string fmt, T&&... args, source_location location = source_location()) { vlog(level, LOG_TAG, location, static_cast(fmt), fmt::make_format_args(format_replace(args)...)); } @@ -150,29 +152,27 @@ verbose(fmt::format_string, T&&...) -> verbose; #endif // GCC / C++20 [[noreturn]] [[maybe_unused]] static void fatal( - fmt::format_string<> fmt, - log_internal::source_location location = log_internal::source_location()) { - vlog(log_internal::kFatal, LOG_TAG, location, - static_cast(fmt), fmt::make_format_args()); + fmt::format_string<> fmt, + log_internal::source_location location = log_internal::source_location()) { + vlog(log_internal::kFatal, LOG_TAG, location, static_cast(fmt), + fmt::make_format_args()); std::abort(); // Enforce [[noreturn]] } template [[noreturn]] [[maybe_unused]] static void fatal( - fmt::format_string fmt, T0&& arg0, - log_internal::source_location location = log_internal::source_location()) { - vlog(log_internal::kFatal, LOG_TAG, location, - static_cast(fmt), + fmt::format_string fmt, T0&& arg0, + log_internal::source_location location = log_internal::source_location()) { + vlog(log_internal::kFatal, LOG_TAG, location, static_cast(fmt), fmt::make_format_args(log_internal::format_replace(arg0))); std::abort(); // Enforce [[noreturn]] } template [[noreturn]] [[maybe_unused]] static void fatal( - fmt::format_string fmt, T0&& arg0, T1&& arg1, - log_internal::source_location location = log_internal::source_location()) { - vlog(log_internal::kFatal, LOG_TAG, location, - static_cast(fmt), + fmt::format_string fmt, T0&& arg0, T1&& arg1, + log_internal::source_location location = log_internal::source_location()) { + vlog(log_internal::kFatal, LOG_TAG, location, static_cast(fmt), fmt::make_format_args(log_internal::format_replace(arg0), log_internal::format_replace(arg1))); std::abort(); // Enforce [[noreturn]] @@ -180,25 +180,20 @@ template template [[noreturn]] [[maybe_unused]] static void fatal( - fmt::format_string fmt, T0&& arg0, T1&& arg1, T2&& arg2, - log_internal::source_location location = log_internal::source_location()) { - vlog(log_internal::kFatal, LOG_TAG, location, - static_cast(fmt), - fmt::make_format_args(log_internal::format_replace(arg0), - log_internal::format_replace(arg1), + fmt::format_string fmt, T0&& arg0, T1&& arg1, T2&& arg2, + log_internal::source_location location = log_internal::source_location()) { + vlog(log_internal::kFatal, LOG_TAG, location, static_cast(fmt), + fmt::make_format_args(log_internal::format_replace(arg0), log_internal::format_replace(arg1), log_internal::format_replace(arg2))); std::abort(); // Enforce [[noreturn]] } template [[noreturn]] [[maybe_unused]] static void fatal( - fmt::format_string fmt, T0&& arg0, T1&& arg1, T2&& arg2, - T3&& arg3, - log_internal::source_location location = log_internal::source_location()) { - vlog(log_internal::kFatal, LOG_TAG, location, - static_cast(fmt), - fmt::make_format_args(log_internal::format_replace(arg0), - log_internal::format_replace(arg1), + fmt::format_string fmt, T0&& arg0, T1&& arg1, T2&& arg2, T3&& arg3, + log_internal::source_location location = log_internal::source_location()) { + vlog(log_internal::kFatal, LOG_TAG, location, static_cast(fmt), + fmt::make_format_args(log_internal::format_replace(arg0), log_internal::format_replace(arg1), log_internal::format_replace(arg2), log_internal::format_replace(arg3))); std::abort(); // Enforce [[noreturn]] @@ -207,11 +202,9 @@ template template struct assert_that { assert_that(bool cond, fmt::format_string fmt, T&&... args, - log_internal::source_location location = - log_internal::source_location()) { + log_internal::source_location location = log_internal::source_location()) { if (!cond) { - vlog(log_internal::kFatal, LOG_TAG, location, - static_cast(fmt), + vlog(log_internal::kFatal, LOG_TAG, location, static_cast(fmt), fmt::make_format_args(log_internal::format_replace(args)...)); } } @@ -237,7 +230,7 @@ struct enum_formatter : fmt::formatter, CharT> { template typename Context::iterator format(EnumT value, Context& ctx) const { return fmt::formatter, CharT>::format( - static_cast>(value), ctx); + static_cast>(value), ctx); } }; diff --git a/system/log/src/truncating_buffer.h b/system/log/src/truncating_buffer.h index c2ad0014a95..b69c6bdf28c 100644 --- a/system/log/src/truncating_buffer.h +++ b/system/log/src/truncating_buffer.h @@ -61,7 +61,7 @@ struct truncating_buffer { return buffer; } - private: +private: char buffer[buffer_size]; size_t len{0}; }; diff --git a/system/log/src/vlog_android.cc b/system/log/src/vlog_android.cc index e6bb2006a5d..6f4ef34ff65 100644 --- a/system/log/src/vlog_android.cc +++ b/system/log/src/vlog_android.cc @@ -21,13 +21,12 @@ namespace bluetooth::log_internal { -static constexpr std::string_view kAndroidRepoLocation = - "packages/modules/Bluetooth/"; +static constexpr std::string_view kAndroidRepoLocation = "packages/modules/Bluetooth/"; static constexpr size_t kBufferSize = 1024; -void vlog(Level level, char const* tag, source_location location, - fmt::string_view fmt, fmt::format_args vargs) { +void vlog(Level level, char const* tag, source_location location, fmt::string_view fmt, + fmt::format_args vargs) { // Check if log is enabled. if (!__android_log_is_loggable(level, "bluetooth", ANDROID_LOG_INFO)) { return; @@ -35,8 +34,7 @@ void vlog(Level level, char const* tag, source_location location, // Strip prefix of file_name to remove kAndroidRepoLocation if present const char* file_name = location.file_name; - if (strncmp(kAndroidRepoLocation.data(), location.file_name, - kAndroidRepoLocation.size()) == 0) { + if (strncmp(kAndroidRepoLocation.data(), location.file_name, kAndroidRepoLocation.size()) == 0) { file_name = location.file_name + kAndroidRepoLocation.size(); } @@ -46,19 +44,19 @@ void vlog(Level level, char const* tag, source_location location, // In order to have consistent logs we include it manually in the log // message. truncating_buffer buffer; - fmt::format_to(std::back_insert_iterator(buffer), "{}:{} {}: ", file_name, - location.line, location.function_name); + fmt::format_to(std::back_insert_iterator(buffer), "{}:{} {}: ", file_name, location.line, + location.function_name); fmt::vformat_to(std::back_insert_iterator(buffer), fmt, vargs); // Send message to liblog. struct __android_log_message message = { - .struct_size = sizeof(__android_log_message), - .buffer_id = LOG_ID_MAIN, - .priority = static_cast(level), - .tag = tag, - .file = nullptr, - .line = 0, - .message = buffer.c_str(), + .struct_size = sizeof(__android_log_message), + .buffer_id = LOG_ID_MAIN, + .priority = static_cast(level), + .tag = tag, + .file = nullptr, + .line = 0, + .message = buffer.c_str(), }; __android_log_write_log_message(&message); diff --git a/system/log/src/vlog_syslog.cc b/system/log/src/vlog_syslog.cc index 9696aee4fff..73d7ec64e8c 100644 --- a/system/log/src/vlog_syslog.cc +++ b/system/log/src/vlog_syslog.cc @@ -48,8 +48,8 @@ Level GetDefaultLogLevel() { return gDefaultLogLevel; } // Default value for $MaxMessageSize for rsyslog. static constexpr size_t kBufferSize = 8192; -void vlog(Level level, char const* tag, source_location location, - fmt::string_view fmt, fmt::format_args vargs) { +void vlog(Level level, char const* tag, source_location location, fmt::string_view fmt, + fmt::format_args vargs) { // Filter out logs that don't meet level requirement. Level current_level = GetLogLevelForTag(tag); if (level < current_level) { @@ -82,8 +82,8 @@ void vlog(Level level, char const* tag, source_location location, truncating_buffer buffer; // Format file, line. - fmt::format_to(std::back_insert_iterator(buffer), "{} {}:{} {}: ", tag, - location.file_name, location.line, location.function_name); + fmt::format_to(std::back_insert_iterator(buffer), "{} {}:{} {}: ", tag, location.file_name, + location.line, location.function_name); // Format message. fmt::vformat_to(std::back_insert_iterator(buffer), fmt, vargs); @@ -108,8 +108,8 @@ void SetLogLevelForTag(char const* tag, uint8_t level) { level = bluetooth::log_internal::GetDefaultLogLevel(); } - bluetooth::log_internal::GetTagMap().emplace( - tag, static_cast(level)); + bluetooth::log_internal::GetTagMap().emplace(tag, + static_cast(level)); } void SetDefaultLogLevel(uint8_t level) { @@ -118,7 +118,6 @@ void SetDefaultLogLevel(uint8_t level) { return; } - bluetooth::log_internal::gDefaultLogLevel = - static_cast(level); + bluetooth::log_internal::gDefaultLogLevel = static_cast(level); } } diff --git a/system/log/src/vlog_test.cc b/system/log/src/vlog_test.cc index b5b3c093396..f8126a2416d 100644 --- a/system/log/src/vlog_test.cc +++ b/system/log/src/vlog_test.cc @@ -27,14 +27,12 @@ static std::optional<__android_log_message> androidLogMessage; /// Mask the implementation from liblog. -int __android_log_is_loggable(int /*prio*/, const char* /*tag*/, - int /*default_prio*/) { +int __android_log_is_loggable(int /*prio*/, const char* /*tag*/, int /*default_prio*/) { return true; } /// Mask the implementation from liblog. -void __android_log_write_log_message( - struct __android_log_message* log_message) { +void __android_log_write_log_message(struct __android_log_message* log_message) { if (log_message != nullptr) { log_message->message = strdup(log_message->message); androidLogMessage.emplace(*log_message); @@ -53,8 +51,7 @@ TEST(BluetoothLogTest, verbose) { EXPECT_STREQ(androidLogMessage->tag, LOG_TAG); EXPECT_EQ(androidLogMessage->file, nullptr); EXPECT_EQ(androidLogMessage->line, 0); - EXPECT_STREQ(androidLogMessage->message, - "system/log/src/vlog_test.cc:49 TestBody: verbose test"); + EXPECT_STREQ(androidLogMessage->message, "system/log/src/vlog_test.cc:47 TestBody: verbose test"); } TEST(BluetoothLogTest, debug) { @@ -67,8 +64,7 @@ TEST(BluetoothLogTest, debug) { EXPECT_STREQ(androidLogMessage->tag, LOG_TAG); EXPECT_STREQ(androidLogMessage->file, nullptr); EXPECT_EQ(androidLogMessage->line, 0); - EXPECT_STREQ(androidLogMessage->message, - "system/log/src/vlog_test.cc:63 TestBody: debug test"); + EXPECT_STREQ(androidLogMessage->message, "system/log/src/vlog_test.cc:60 TestBody: debug test"); } TEST(BluetoothLogTest, info) { @@ -81,8 +77,7 @@ TEST(BluetoothLogTest, info) { EXPECT_STREQ(androidLogMessage->tag, LOG_TAG); EXPECT_STREQ(androidLogMessage->file, nullptr); EXPECT_EQ(androidLogMessage->line, 0); - EXPECT_STREQ(androidLogMessage->message, - "system/log/src/vlog_test.cc:77 TestBody: info test"); + EXPECT_STREQ(androidLogMessage->message, "system/log/src/vlog_test.cc:73 TestBody: info test"); } TEST(BluetoothLogTest, warn) { @@ -95,8 +90,7 @@ TEST(BluetoothLogTest, warn) { EXPECT_STREQ(androidLogMessage->tag, LOG_TAG); EXPECT_STREQ(androidLogMessage->file, nullptr); EXPECT_EQ(androidLogMessage->line, 0); - EXPECT_STREQ(androidLogMessage->message, - "system/log/src/vlog_test.cc:91 TestBody: warn test"); + EXPECT_STREQ(androidLogMessage->message, "system/log/src/vlog_test.cc:86 TestBody: warn test"); } TEST(BluetoothLogTest, error) { @@ -109,39 +103,38 @@ TEST(BluetoothLogTest, error) { EXPECT_STREQ(androidLogMessage->tag, LOG_TAG); EXPECT_STREQ(androidLogMessage->file, nullptr); EXPECT_EQ(androidLogMessage->line, 0); - EXPECT_STREQ(androidLogMessage->message, - "system/log/src/vlog_test.cc:105 TestBody: error test"); + EXPECT_STREQ(androidLogMessage->message, "system/log/src/vlog_test.cc:99 TestBody: error test"); } TEST(BluetoothLogDeathTest, fatal) { androidLogMessage.reset(); ASSERT_DEATH( - { - log::fatal("fatal test"); - // Validate that the compiler is correctly handling log::fatal as - // [[noreturn]] by attempting to invoke an undefined function. - // This test will fail linking if this check fails. - void undefined_function(); - undefined_function(); - }, - "fatal test"); + { + log::fatal("fatal test"); + // Validate that the compiler is correctly handling log::fatal as + // [[noreturn]] by attempting to invoke an undefined function. + // This test will fail linking if this check fails. + void undefined_function(); + undefined_function(); + }, + "fatal test"); ASSERT_DEATH( - { - log::fatal("fatal test {}", "2"); - void undefined_function(); - undefined_function(); - }, - "fatal test 2"); + { + log::fatal("fatal test {}", "2"); + void undefined_function(); + undefined_function(); + }, + "fatal test 2"); ASSERT_DEATH( - { - log::fatal("fatal test {}, {}", 2, 3); - void undefined_function(); - undefined_function(); - }, - "fatal test 2, 3"); + { + log::fatal("fatal test {}, {}", 2, 3); + void undefined_function(); + undefined_function(); + }, + "fatal test 2, 3"); } TEST(BluetoothLogDeathTest, assert_that) { @@ -150,9 +143,7 @@ TEST(BluetoothLogDeathTest, assert_that) { log::assert_that(true, "assert_that test true"); log::assert_that(true, "assert_that test {}", "true"); - ASSERT_DEATH( - { log::assert_that(false, "assert_that test false"); }, - "assert_that test false"); + ASSERT_DEATH({ log::assert_that(false, "assert_that test false"); }, "assert_that test false"); } TEST(BluetoothLogTest, null_string_parameter) { @@ -161,19 +152,19 @@ TEST(BluetoothLogTest, null_string_parameter) { char const* const_null_str = nullptr; log::info("input: {}", const_null_str); EXPECT_STREQ(androidLogMessage->message, - "system/log/src/vlog_test.cc:162 TestBody: input: (nullptr)"); + "system/log/src/vlog_test.cc:153 TestBody: input: (nullptr)"); androidLogMessage.reset(); char* null_str = nullptr; log::info("input: {}", null_str); EXPECT_STREQ(androidLogMessage->message, - "system/log/src/vlog_test.cc:169 TestBody: input: (nullptr)"); + "system/log/src/vlog_test.cc:160 TestBody: input: (nullptr)"); androidLogMessage.reset(); char const* nonnull_str = "hello world"; log::info("input: {}", nonnull_str); EXPECT_STREQ(androidLogMessage->message, - "system/log/src/vlog_test.cc:176 TestBody: input: hello world"); + "system/log/src/vlog_test.cc:167 TestBody: input: hello world"); } diff --git a/system/main/bte_conf.cc b/system/main/bte_conf.cc index d0b2b696c89..58069396334 100644 --- a/system/main/bte_conf.cc +++ b/system/main/bte_conf.cc @@ -53,39 +53,31 @@ void bte_load_did_conf(const char* p_path) { } tSDP_DI_RECORD record; - record.vendor = - config_get_int(*config, section_name, "vendorId", LMP_COMPID_GOOGLE); - record.vendor_id_source = config_get_int( - *config, section_name, "vendorIdSource", DI_VENDOR_ID_SOURCE_BTSIG); + record.vendor = config_get_int(*config, section_name, "vendorId", LMP_COMPID_GOOGLE); + record.vendor_id_source = + config_get_int(*config, section_name, "vendorIdSource", DI_VENDOR_ID_SOURCE_BTSIG); record.product = config_get_int(*config, section_name, "productId", 0); record.version = config_get_int(*config, section_name, "version", 0); - record.primary_record = - config_get_bool(*config, section_name, "primaryRecord", false); + record.primary_record = config_get_bool(*config, section_name, "primaryRecord", false); std::string empty = ""; - strlcpy( - record.client_executable_url, - config_get_string(*config, section_name, "clientExecutableURL", &empty) - ->c_str(), - sizeof(record.client_executable_url)); - strlcpy( - record.service_description, - config_get_string(*config, section_name, "serviceDescription", &empty) - ->c_str(), - sizeof(record.service_description)); + strlcpy(record.client_executable_url, + config_get_string(*config, section_name, "clientExecutableURL", &empty)->c_str(), + sizeof(record.client_executable_url)); + strlcpy(record.service_description, + config_get_string(*config, section_name, "serviceDescription", &empty)->c_str(), + sizeof(record.service_description)); strlcpy(record.documentation_url, - config_get_string(*config, section_name, "documentationURL", &empty) - ->c_str(), + config_get_string(*config, section_name, "documentationURL", &empty)->c_str(), sizeof(record.documentation_url)); if (record.vendor_id_source != DI_VENDOR_ID_SOURCE_BTSIG && record.vendor_id_source != DI_VENDOR_ID_SOURCE_USBIF) { - log::error("invalid vendor id source {}; ignoring DID record {}.", - record.vendor_id_source, i); + log::error("invalid vendor id source {}; ignoring DID record {}.", record.vendor_id_source, + i); continue; } - log::info("Device ID record {} : {}", i, - record.primary_record ? "primary" : "not primary"); + log::info("Device ID record {} : {}", i, record.primary_record ? "primary" : "not primary"); log::info("vendorId = {:04x}", record.vendor); log::info("vendorIdSource = {:04x}", record.vendor_id_source); log::info("product = {:04x}", record.product); diff --git a/system/main/shim/acl.cc b/system/main/shim/acl.cc index e993c8c4bf3..7ba293bc4eb 100644 --- a/system/main/shim/acl.cc +++ b/system/main/shim/acl.cc @@ -67,7 +67,7 @@ extern tBTM_CB btm_cb; using namespace bluetooth; class ConnectAddressWithType : public bluetooth::common::IRedactableLoggable { - public: +public: explicit ConnectAddressWithType(hci::AddressWithType address_with_type) : address_(address_with_type.GetAddress()), type_(address_with_type.ToFilterAcceptListAddressType()) {} @@ -75,25 +75,22 @@ class ConnectAddressWithType : public bluetooth::common::IRedactableLoggable { // TODO: remove this method std::string const ToString() const { std::stringstream ss; - ss << address_.ToString() << "[" << FilterAcceptListAddressTypeText(type_) - << "]"; + ss << address_.ToString() << "[" << FilterAcceptListAddressTypeText(type_) << "]"; return ss.str(); } - std::string ToStringForLogging() const override { - return ToString(); - } + std::string ToStringForLogging() const override { return ToString(); } std::string ToRedactedStringForLogging() const override { std::stringstream ss; - ss << address_.ToRedactedStringForLogging() << "[" - << FilterAcceptListAddressTypeText(type_) << "]"; + ss << address_.ToRedactedStringForLogging() << "[" << FilterAcceptListAddressTypeText(type_) + << "]"; return ss.str(); } bool operator==(const ConnectAddressWithType& rhs) const { return address_ == rhs.address_ && type_ == rhs.type_; } - private: +private: friend std::hash; hci::Address address_; hci::FilterAcceptListAddressType type_; @@ -103,15 +100,13 @@ namespace std { template <> struct hash { std::size_t operator()(const ConnectAddressWithType& val) const { - static_assert(sizeof(uint64_t) >= - (bluetooth::hci::Address::kLength + - sizeof(bluetooth::hci::FilterAcceptListAddressType))); + static_assert(sizeof(uint64_t) >= (bluetooth::hci::Address::kLength + + sizeof(bluetooth::hci::FilterAcceptListAddressType))); uint64_t int_addr = 0; memcpy(reinterpret_cast(&int_addr), val.address_.data(), bluetooth::hci::Address::kLength); - memcpy(reinterpret_cast(&int_addr) + - bluetooth::hci::Address::kLength, - &val.type_, sizeof(bluetooth::hci::FilterAcceptListAddressType)); + memcpy(reinterpret_cast(&int_addr) + bluetooth::hci::Address::kLength, &val.type_, + sizeof(bluetooth::hci::FilterAcceptListAddressType)); return std::hash{}(int_addr); } }; @@ -121,11 +116,10 @@ namespace fmt { template <> struct formatter : formatter { template - typename Context::iterator format(const ConnectAddressWithType& address, - Context& ctx) const { + typename Context::iterator format(const ConnectAddressWithType& address, Context& ctx) const { std::string repr = bluetooth::os::should_log_be_redacted() - ? address.ToRedactedStringForLogging() - : address.ToStringForLogging(); + ? address.ToRedactedStringForLogging() + : address.ToStringForLogging(); return fmt::formatter::format(repr, ctx); } }; @@ -155,31 +149,26 @@ std::string EpochMillisToString(long long time_ms) { struct tm tm; localtime_r(&time_sec, &tm); std::string s = common::StringFormatTime(kConnectionDescriptorTimeFormat, tm); - return base::StringPrintf( - "%s.%03u", s.c_str(), - static_cast(time_ms % MillisPerSecond)); + return base::StringPrintf("%s.%03u", s.c_str(), + static_cast(time_ms % MillisPerSecond)); } inline bool IsRpa(const hci::AddressWithType address_with_type) { - return address_with_type.GetAddressType() == - hci::AddressType::RANDOM_DEVICE_ADDRESS && + return address_with_type.GetAddressType() == hci::AddressType::RANDOM_DEVICE_ADDRESS && ((address_with_type.GetAddress().address.data()[5] & 0xc0) == 0x40); } class ShadowAcceptlist { - public: - ShadowAcceptlist(uint8_t max_acceptlist_size) - : max_acceptlist_size_(max_acceptlist_size) {} +public: + ShadowAcceptlist(uint8_t max_acceptlist_size) : max_acceptlist_size_(max_acceptlist_size) {} bool Add(const hci::AddressWithType& address_with_type) { if (acceptlist_set_.size() == max_acceptlist_size_) { log::error("Acceptlist is full size:{}", acceptlist_set_.size()); return false; } - if (!acceptlist_set_.insert(ConnectAddressWithType(address_with_type)) - .second) { - log::warn("Attempted to add duplicate le address to acceptlist:{}", - address_with_type); + if (!acceptlist_set_.insert(ConnectAddressWithType(address_with_type)).second) { + log::warn("Attempted to add duplicate le address to acceptlist:{}", address_with_type); } return true; } @@ -187,17 +176,14 @@ class ShadowAcceptlist { bool Remove(const hci::AddressWithType& address_with_type) { auto iter = acceptlist_set_.find(ConnectAddressWithType(address_with_type)); if (iter == acceptlist_set_.end()) { - log::warn("Unknown device being removed from acceptlist:{}", - address_with_type); + log::warn("Unknown device being removed from acceptlist:{}", address_with_type); return false; } acceptlist_set_.erase(ConnectAddressWithType(*iter)); return true; } - std::unordered_set GetCopy() const { - return acceptlist_set_; - } + std::unordered_set GetCopy() const { return acceptlist_set_; } bool IsFull() const { return acceptlist_set_.size() == static_cast(max_acceptlist_size_); @@ -207,26 +193,24 @@ class ShadowAcceptlist { uint8_t GetMaxSize() const { return max_acceptlist_size_; } - private: +private: uint8_t max_acceptlist_size_{0}; std::unordered_set acceptlist_set_; }; class ShadowAddressResolutionList { - public: +public: ShadowAddressResolutionList(uint8_t max_address_resolution_size) : max_address_resolution_size_(max_address_resolution_size) {} bool Add(const hci::AddressWithType& address_with_type) { if (address_resolution_set_.size() == max_address_resolution_size_) { - log::error("Address Resolution is full size:{}", - address_resolution_set_.size()); + log::error("Address Resolution is full size:{}", address_resolution_set_.size()); return false; } if (!address_resolution_set_.insert(address_with_type).second) { - log::warn( - "Attempted to add duplicate le address to address_resolution:{}", - address_with_type); + log::warn("Attempted to add duplicate le address to address_resolution:{}", + address_with_type); } return true; } @@ -234,21 +218,17 @@ class ShadowAddressResolutionList { bool Remove(const hci::AddressWithType& address_with_type) { auto iter = address_resolution_set_.find(address_with_type); if (iter == address_resolution_set_.end()) { - log::warn("Unknown device being removed from address_resolution:{}", - address_with_type); + log::warn("Unknown device being removed from address_resolution:{}", address_with_type); return false; } address_resolution_set_.erase(iter); return true; } - std::unordered_set GetCopy() const { - return address_resolution_set_; - } + std::unordered_set GetCopy() const { return address_resolution_set_; } bool IsFull() const { - return address_resolution_set_.size() == - static_cast(max_address_resolution_size_); + return address_resolution_set_.size() == static_cast(max_address_resolution_size_); } size_t Size() const { return address_resolution_set_.size(); } @@ -257,7 +237,7 @@ class ShadowAddressResolutionList { uint8_t GetMaxSize() const { return max_address_resolution_size_; } - private: +private: uint8_t max_address_resolution_size_{0}; std::unordered_set address_resolution_set_; }; @@ -268,9 +248,8 @@ struct ConnectionDescriptor { uint16_t handle_; bool is_locally_initiated_; hci::ErrorCode disconnect_reason_; - ConnectionDescriptor(CreationTime creation_time, TeardownTime teardown_time, - uint16_t handle, bool is_locally_initiated, - hci::ErrorCode disconnect_reason) + ConnectionDescriptor(CreationTime creation_time, TeardownTime teardown_time, uint16_t handle, + bool is_locally_initiated, hci::ErrorCode disconnect_reason) : creation_time_(creation_time), teardown_time_(teardown_time), handle_(handle), @@ -280,29 +259,26 @@ struct ConnectionDescriptor { virtual ~ConnectionDescriptor() {} std::string ToString() const { return base::StringPrintf( - "peer:%s handle:0x%04x is_locally_initiated:%s" - " creation_time:%s teardown_time:%s disconnect_reason:%s", - GetPrivateRemoteAddress().c_str(), handle_, - is_locally_initiated_ ? "true" : "false", - common::StringFormatTimeWithMilliseconds( - kConnectionDescriptorTimeFormat, creation_time_) - .c_str(), - common::StringFormatTimeWithMilliseconds( - kConnectionDescriptorTimeFormat, teardown_time_) - .c_str(), - hci::ErrorCodeText(disconnect_reason_).c_str()); + "peer:%s handle:0x%04x is_locally_initiated:%s" + " creation_time:%s teardown_time:%s disconnect_reason:%s", + GetPrivateRemoteAddress().c_str(), handle_, is_locally_initiated_ ? "true" : "false", + common::StringFormatTimeWithMilliseconds(kConnectionDescriptorTimeFormat, + creation_time_) + .c_str(), + common::StringFormatTimeWithMilliseconds(kConnectionDescriptorTimeFormat, + teardown_time_) + .c_str(), + hci::ErrorCodeText(disconnect_reason_).c_str()); } }; struct ClassicConnectionDescriptor : public ConnectionDescriptor { const hci::Address remote_address_; - ClassicConnectionDescriptor(const hci::Address& remote_address, - CreationTime creation_time, + ClassicConnectionDescriptor(const hci::Address& remote_address, CreationTime creation_time, TeardownTime teardown_time, uint16_t handle, - bool is_locally_initiated, - hci::ErrorCode disconnect_reason) - : ConnectionDescriptor(creation_time, teardown_time, handle, - is_locally_initiated, disconnect_reason), + bool is_locally_initiated, hci::ErrorCode disconnect_reason) + : ConnectionDescriptor(creation_time, teardown_time, handle, is_locally_initiated, + disconnect_reason), remote_address_(remote_address) {} virtual std::string GetPrivateRemoteAddress() const { return ADDRESS_TO_LOGGABLE_CSTR(remote_address_); @@ -311,12 +287,11 @@ struct ClassicConnectionDescriptor : public ConnectionDescriptor { struct LeConnectionDescriptor : public ConnectionDescriptor { const hci::AddressWithType remote_address_with_type_; - LeConnectionDescriptor(hci::AddressWithType& remote_address_with_type, - CreationTime creation_time, TeardownTime teardown_time, - uint16_t handle, bool is_locally_initiated, + LeConnectionDescriptor(hci::AddressWithType& remote_address_with_type, CreationTime creation_time, + TeardownTime teardown_time, uint16_t handle, bool is_locally_initiated, hci::ErrorCode disconnect_reason) - : ConnectionDescriptor(creation_time, teardown_time, handle, - is_locally_initiated, disconnect_reason), + : ConnectionDescriptor(creation_time, teardown_time, handle, is_locally_initiated, + disconnect_reason), remote_address_with_type_(remote_address_with_type) {} std::string GetPrivateRemoteAddress() const { return ADDRESS_TO_LOGGABLE_CSTR(remote_address_with_type_); @@ -325,7 +300,7 @@ struct LeConnectionDescriptor : public ConnectionDescriptor { template class FixedQueue { - public: +public: explicit FixedQueue(size_t max_size) : max_size_(max_size) {} void Push(T element) { if (queue_.size() == max_size_) { @@ -342,7 +317,7 @@ class FixedQueue { return vector; } - private: +private: size_t max_size_{1}; std::deque queue_; }; @@ -360,20 +335,17 @@ void ValidateAclInterface(const shim::legacy::acl_interface_t& acl_interface) { log::assert_that(acl_interface.connection.classic.on_connected != nullptr, "Must provide to respond to successful classic connections"); - log::assert_that( - acl_interface.connection.classic.on_failed != nullptr, - "Must provide to respond when classic connection attempts fail"); - log::assert_that( - acl_interface.connection.classic.on_disconnected != nullptr, - "Must provide to respond when active classic connection disconnects"); + log::assert_that(acl_interface.connection.classic.on_failed != nullptr, + "Must provide to respond when classic connection attempts fail"); + log::assert_that(acl_interface.connection.classic.on_disconnected != nullptr, + "Must provide to respond when active classic connection disconnects"); log::assert_that(acl_interface.connection.le.on_connected != nullptr, "Must provide to respond to successful le connections"); log::assert_that(acl_interface.connection.le.on_failed != nullptr, "Must provide to respond when le connection attempts fail"); - log::assert_that( - acl_interface.connection.le.on_disconnected != nullptr, - "Must provide to respond when active le connection disconnects"); + log::assert_that(acl_interface.connection.le.on_disconnected != nullptr, + "Must provide to respond when active le connection disconnects"); } } // namespace @@ -390,9 +362,8 @@ void ValidateAclInterface(const shim::legacy::acl_interface_t& acl_interface) { constexpr HciHandle kInvalidHciHandle = 0xffff; class ShimAclConnection { - public: - ShimAclConnection(const HciHandle handle, SendDataUpwards send_data_upwards, - os::Handler* handler, +public: + ShimAclConnection(const HciHandle handle, SendDataUpwards send_data_upwards, os::Handler* handler, hci::acl_manager::AclConnection::QueueUpEnd* queue_up_end, CreationTime creation_time) : handle_(handle), @@ -400,19 +371,18 @@ class ShimAclConnection { send_data_upwards_(send_data_upwards), queue_up_end_(queue_up_end), creation_time_(creation_time) { - queue_up_end_->RegisterDequeue( - handler_, common::Bind(&ShimAclConnection::data_ready_callback, - common::Unretained(this))); + queue_up_end_->RegisterDequeue(handler_, common::Bind(&ShimAclConnection::data_ready_callback, + common::Unretained(this))); } virtual ~ShimAclConnection() { - if (!queue_.empty()) + if (!queue_.empty()) { log::error( - "ACL cleaned up with non-empty queue handle:0x{:04x} " - "stranded_pkts:{}", - handle_, queue_.size()); - log::assert_that(is_disconnected_, - "Shim Acl was not properly disconnected handle:0x{:04x}", + "ACL cleaned up with non-empty queue handle:0x{:04x} " + "stranded_pkts:{}", + handle_, queue_.size()); + } + log::assert_that(is_disconnected_, "Shim Acl was not properly disconnected handle:0x{:04x}", handle_); } @@ -440,14 +410,12 @@ class ShimAclConnection { preamble.push_back(LowByte(length)); preamble.push_back(HighByte(length)); BT_HDR* p_buf = MakeLegacyBtHdrPacket(std::move(packet), preamble); - log::assert_that(p_buf != nullptr, - "Unable to allocate BT_HDR legacy packet handle:{:04x}", + log::assert_that(p_buf != nullptr, "Unable to allocate BT_HDR legacy packet handle:{:04x}", handle_); if (send_data_upwards_ == nullptr) { log::warn("Dropping ACL data with no callback"); osi_free(p_buf); - } else if (do_in_main_thread(FROM_HERE, - base::BindOnce(send_data_upwards_, p_buf)) != + } else if (do_in_main_thread(FROM_HERE, base::BindOnce(send_data_upwards_, p_buf)) != BT_STATUS_SUCCESS) { osi_free(p_buf); } @@ -461,41 +429,40 @@ class ShimAclConnection { void Shutdown() { Disconnect(); - log::info("Shutdown and disconnect ACL connection handle:0x{:04x}", - handle_); + log::info("Shutdown and disconnect ACL connection handle:0x{:04x}", handle_); } - protected: +protected: const uint16_t handle_{kInvalidHciHandle}; os::Handler* handler_; void UnregisterEnqueue() { - if (!is_enqueue_registered_) return; + if (!is_enqueue_registered_) { + return; + } is_enqueue_registered_ = false; queue_up_end_->UnregisterEnqueue(); } void Disconnect() { if (is_disconnected_) { - log::error( - "Cannot disconnect ACL multiple times handle:{:04x} creation_time:{}", - handle_, - common::StringFormatTimeWithMilliseconds( - kConnectionDescriptorTimeFormat, creation_time_)); + log::error("Cannot disconnect ACL multiple times handle:{:04x} creation_time:{}", handle_, + common::StringFormatTimeWithMilliseconds(kConnectionDescriptorTimeFormat, + creation_time_)); return; } is_disconnected_ = true; UnregisterEnqueue(); queue_up_end_->UnregisterDequeue(); - if (!queue_.empty()) - log::warn( - "ACL disconnect with non-empty queue handle:{:04x} stranded_pkts::{}", - handle_, queue_.size()); + if (!queue_.empty()) { + log::warn("ACL disconnect with non-empty queue handle:{:04x} stranded_pkts::{}", handle_, + queue_.size()); + } } virtual void ReadRemoteControllerInformation() = 0; - private: +private: SendDataUpwards send_data_upwards_; hci::acl_manager::AclConnection::QueueUpEnd* queue_up_end_; @@ -505,38 +472,34 @@ class ShimAclConnection { CreationTime creation_time_; void RegisterEnqueue() { - log::assert_that( - !is_disconnected_, - "Unable to send data over disconnected channel handle:{:04x}", handle_); - if (is_enqueue_registered_) return; + log::assert_that(!is_disconnected_, + "Unable to send data over disconnected channel handle:{:04x}", handle_); + if (is_enqueue_registered_) { + return; + } is_enqueue_registered_ = true; queue_up_end_->RegisterEnqueue( - handler_, common::Bind(&ShimAclConnection::handle_enqueue, - common::Unretained(this))); + handler_, common::Bind(&ShimAclConnection::handle_enqueue, common::Unretained(this))); } virtual void RegisterCallbacks() = 0; }; -class ClassicShimAclConnection - : public ShimAclConnection, - public hci::acl_manager::ConnectionManagementCallbacks { - public: - ClassicShimAclConnection( - SendDataUpwards send_data_upwards, OnDisconnect on_disconnect, - const shim::legacy::acl_classic_link_interface_t& interface, - os::Handler* handler, - std::unique_ptr connection, - CreationTime creation_time) +class ClassicShimAclConnection : public ShimAclConnection, + public hci::acl_manager::ConnectionManagementCallbacks { +public: + ClassicShimAclConnection(SendDataUpwards send_data_upwards, OnDisconnect on_disconnect, + const shim::legacy::acl_classic_link_interface_t& interface, + os::Handler* handler, + std::unique_ptr connection, + CreationTime creation_time) : ShimAclConnection(connection->GetHandle(), send_data_upwards, handler, connection->GetAclQueueEnd(), creation_time), on_disconnect_(on_disconnect), interface_(interface), connection_(std::move(connection)) {} - void RegisterCallbacks() override { - connection_->RegisterCallbacks(this, handler_); - } + void RegisterCallbacks() override { connection_->RegisterCallbacks(this, handler_); } void ReadRemoteControllerInformation() override { connection_->ReadRemoteVersionInformation(); @@ -566,35 +529,28 @@ class ClassicShimAclConnection log::info("UNIMPLEMENTED"); } - void OnModeChange(hci::ErrorCode status, hci::Mode current_mode, - uint16_t interval) override { - TRY_POSTING_ON_MAIN(interface_.on_mode_change, ToLegacyHciErrorCode(status), - handle_, ToLegacyHciMode(current_mode), interval); + void OnModeChange(hci::ErrorCode status, hci::Mode current_mode, uint16_t interval) override { + TRY_POSTING_ON_MAIN(interface_.on_mode_change, ToLegacyHciErrorCode(status), handle_, + ToLegacyHciMode(current_mode), interval); } - void OnSniffSubrating(hci::ErrorCode hci_status, - uint16_t maximum_transmit_latency, - uint16_t maximum_receive_latency, - uint16_t minimum_remote_timeout, + void OnSniffSubrating(hci::ErrorCode hci_status, uint16_t maximum_transmit_latency, + uint16_t maximum_receive_latency, uint16_t minimum_remote_timeout, uint16_t minimum_local_timeout) { - TRY_POSTING_ON_MAIN(interface_.on_sniff_subrating, - ToLegacyHciErrorCode(hci_status), handle_, - maximum_transmit_latency, maximum_receive_latency, - minimum_remote_timeout, minimum_local_timeout); + TRY_POSTING_ON_MAIN(interface_.on_sniff_subrating, ToLegacyHciErrorCode(hci_status), handle_, + maximum_transmit_latency, maximum_receive_latency, minimum_remote_timeout, + minimum_local_timeout); } - void OnQosSetupComplete(hci::ServiceType /* service_type */, - uint32_t /* token_rate */, + void OnQosSetupComplete(hci::ServiceType /* service_type */, uint32_t /* token_rate */, uint32_t /* peak_bandwidth */, uint32_t /* latency */, uint32_t /* delay_variation */) override { log::info("UNIMPLEMENTED"); } void OnFlowSpecificationComplete(hci::FlowDirection /* flow_direction */, - hci::ServiceType /* service_type */, - uint32_t /* token_rate */, - uint32_t /* token_bucket_size */, - uint32_t /* peak_bandwidth */, + hci::ServiceType /* service_type */, uint32_t /* token_rate */, + uint32_t /* token_bucket_size */, uint32_t /* peak_bandwidth */, uint32_t /* access_latency */) override { log::info("UNIMPLEMENTED"); } @@ -605,28 +561,23 @@ class ClassicShimAclConnection log::info("UNIMPLEMENTED"); } - void OnReadLinkPolicySettingsComplete( - uint16_t /* link_policy_settings */) override { + void OnReadLinkPolicySettingsComplete(uint16_t /* link_policy_settings */) override { log::info("UNIMPLEMENTED"); } - void OnReadAutomaticFlushTimeoutComplete( - uint16_t /* flush_timeout */) override { + void OnReadAutomaticFlushTimeoutComplete(uint16_t /* flush_timeout */) override { log::info("UNIMPLEMENTED"); } - void OnReadTransmitPowerLevelComplete( - uint8_t /* transmit_power_level */) override { + void OnReadTransmitPowerLevelComplete(uint8_t /* transmit_power_level */) override { log::info("UNIMPLEMENTED"); } - void OnReadLinkSupervisionTimeoutComplete( - uint16_t /* link_supervision_timeout */) override { + void OnReadLinkSupervisionTimeoutComplete(uint16_t /* link_supervision_timeout */) override { log::info("UNIMPLEMENTED"); } - void OnReadFailedContactCounterComplete( - uint16_t /* failed_contact_counter */) override { + void OnReadFailedContactCounterComplete(uint16_t /* failed_contact_counter */) override { log::info("UNIMPLEMENTED"); } @@ -634,18 +585,14 @@ class ClassicShimAclConnection log::info("UNIMPLEMENTED"); } - void OnReadAfhChannelMapComplete( - hci::AfhMode /* afh_mode */, - std::array /* afh_channel_map */) override { + void OnReadAfhChannelMapComplete(hci::AfhMode /* afh_mode */, + std::array /* afh_channel_map */) override { log::info("UNIMPLEMENTED"); } - void OnReadRssiComplete(uint8_t /* rssi */) override { - log::info("UNIMPLEMENTED"); - } + void OnReadRssiComplete(uint8_t /* rssi */) override { log::info("UNIMPLEMENTED"); } - void OnReadClockComplete(uint32_t /* clock */, - uint16_t /* accuracy */) override { + void OnReadClockComplete(uint32_t /* clock */, uint16_t /* accuracy */) override { log::info("UNIMPLEMENTED"); } @@ -654,14 +601,12 @@ class ClassicShimAclConnection } void OnRoleChange(hci::ErrorCode hci_status, hci::Role new_role) override { - TRY_POSTING_ON_MAIN( - interface_.on_role_change, ToLegacyHciErrorCode(hci_status), - ToRawAddress(connection_->GetAddress()), ToLegacyRole(new_role)); - BTM_LogHistory(kBtmLogTag, ToRawAddress(connection_->GetAddress()), - "Role change", - base::StringPrintf("classic New_role:%s status:%s", - hci::RoleText(new_role).c_str(), - hci::ErrorCodeText(hci_status).c_str())); + TRY_POSTING_ON_MAIN(interface_.on_role_change, ToLegacyHciErrorCode(hci_status), + ToRawAddress(connection_->GetAddress()), ToLegacyRole(new_role)); + BTM_LogHistory( + kBtmLogTag, ToRawAddress(connection_->GetAddress()), "Role change", + base::StringPrintf("classic New_role:%s status:%s", hci::RoleText(new_role).c_str(), + hci::ErrorCodeText(hci_status).c_str())); } void OnDisconnection(hci::ErrorCode reason) override { @@ -669,40 +614,38 @@ class ClassicShimAclConnection on_disconnect_(handle_, reason); } - void OnReadRemoteVersionInformationComplete(hci::ErrorCode hci_status, - uint8_t lmp_version, + void OnReadRemoteVersionInformationComplete(hci::ErrorCode hci_status, uint8_t lmp_version, uint16_t manufacturer_name, uint16_t sub_version) override { TRY_POSTING_ON_MAIN(interface_.on_read_remote_version_information_complete, - ToLegacyHciErrorCode(hci_status), handle_, lmp_version, - manufacturer_name, sub_version); + ToLegacyHciErrorCode(hci_status), handle_, lmp_version, manufacturer_name, + sub_version); } void OnReadRemoteSupportedFeaturesComplete(uint64_t features) override { - TRY_POSTING_ON_MAIN(interface_.on_read_remote_supported_features_complete, - handle_, features); + TRY_POSTING_ON_MAIN(interface_.on_read_remote_supported_features_complete, handle_, features); - if (features & ((uint64_t(1) << 63))) { + if (features & (uint64_t(1) << 63)) { connection_->ReadRemoteExtendedFeatures(1); return; } log::debug("Device does not support extended features"); } - void OnReadRemoteExtendedFeaturesComplete(uint8_t page_number, - uint8_t max_page_number, + void OnReadRemoteExtendedFeaturesComplete(uint8_t page_number, uint8_t max_page_number, uint64_t features) override { - TRY_POSTING_ON_MAIN(interface_.on_read_remote_extended_features_complete, - handle_, page_number, max_page_number, features); + TRY_POSTING_ON_MAIN(interface_.on_read_remote_extended_features_complete, handle_, page_number, + max_page_number, features); // Supported features aliases to extended features page 0 - if (page_number == 0 && !(features & ((uint64_t(1) << 63)))) { + if (page_number == 0 && !(features & (uint64_t(1) << 63))) { log::debug("Device does not support extended features"); return; } - if (max_page_number != 0 && page_number != max_page_number) + if (max_page_number != 0 && page_number != max_page_number) { connection_->ReadRemoteExtendedFeatures(page_number + 1); + } } hci::Address GetRemoteAddress() const { return connection_->GetAddress(); } @@ -712,77 +655,62 @@ class ClassicShimAclConnection } void HoldMode(uint16_t max_interval, uint16_t min_interval) { - log::assert_that( - connection_->HoldMode(max_interval, min_interval), - "assert failed: connection_->HoldMode(max_interval, min_interval)"); + log::assert_that(connection_->HoldMode(max_interval, min_interval), + "assert failed: connection_->HoldMode(max_interval, min_interval)"); } - void SniffMode(uint16_t max_interval, uint16_t min_interval, uint16_t attempt, - uint16_t timeout) { - log::assert_that( - connection_->SniffMode(max_interval, min_interval, attempt, timeout), - "assert failed: connection_->SniffMode(max_interval, min_interval, " - "attempt, timeout)"); + void SniffMode(uint16_t max_interval, uint16_t min_interval, uint16_t attempt, uint16_t timeout) { + log::assert_that(connection_->SniffMode(max_interval, min_interval, attempt, timeout), + "assert failed: connection_->SniffMode(max_interval, min_interval, " + "attempt, timeout)"); } void ExitSniffMode() { - log::assert_that(connection_->ExitSniffMode(), - "assert failed: connection_->ExitSniffMode()"); + log::assert_that(connection_->ExitSniffMode(), "assert failed: connection_->ExitSniffMode()"); } void SniffSubrating(uint16_t maximum_latency, uint16_t minimum_remote_timeout, uint16_t minimum_local_timeout) { - log::assert_that( - connection_->SniffSubrating(maximum_latency, minimum_remote_timeout, - minimum_local_timeout), - "assert failed: connection_->SniffSubrating(maximum_latency, " - "minimum_remote_timeout, minimum_local_timeout)"); + log::assert_that(connection_->SniffSubrating(maximum_latency, minimum_remote_timeout, + minimum_local_timeout), + "assert failed: connection_->SniffSubrating(maximum_latency, " + "minimum_remote_timeout, minimum_local_timeout)"); } void SetConnectionEncryption(hci::Enable is_encryption_enabled) { - log::assert_that( - connection_->SetConnectionEncryption(is_encryption_enabled), - "assert failed: " - "connection_->SetConnectionEncryption(is_encryption_enabled)"); + log::assert_that(connection_->SetConnectionEncryption(is_encryption_enabled), + "assert failed: " + "connection_->SetConnectionEncryption(is_encryption_enabled)"); } - bool IsLocallyInitiated() const override { - return connection_->locally_initiated_; - } + bool IsLocallyInitiated() const override { return connection_->locally_initiated_; } void Flush() { connection_->Flush(); } - private: +private: OnDisconnect on_disconnect_; const shim::legacy::acl_classic_link_interface_t interface_; std::unique_ptr connection_; }; -class LeShimAclConnection - : public ShimAclConnection, - public hci::acl_manager::LeConnectionManagementCallbacks { - public: - LeShimAclConnection( - SendDataUpwards send_data_upwards, OnDisconnect on_disconnect, - const shim::legacy::acl_le_link_interface_t& interface, - os::Handler* handler, - std::unique_ptr connection, - std::chrono::time_point creation_time) +class LeShimAclConnection : public ShimAclConnection, + public hci::acl_manager::LeConnectionManagementCallbacks { +public: + LeShimAclConnection(SendDataUpwards send_data_upwards, OnDisconnect on_disconnect, + const shim::legacy::acl_le_link_interface_t& interface, os::Handler* handler, + std::unique_ptr connection, + std::chrono::time_point creation_time) : ShimAclConnection(connection->GetHandle(), send_data_upwards, handler, connection->GetAclQueueEnd(), creation_time), on_disconnect_(on_disconnect), interface_(interface), connection_(std::move(connection)) {} - void RegisterCallbacks() override { - connection_->RegisterCallbacks(this, handler_); - } + void RegisterCallbacks() override { connection_->RegisterCallbacks(this, handler_); } - void LeSubrateRequest(uint16_t subrate_min, uint16_t subrate_max, - uint16_t max_latency, uint16_t cont_num, - uint16_t sup_tout) { - connection_->LeSubrateRequest(subrate_min, subrate_max, max_latency, - cont_num, sup_tout); + void LeSubrateRequest(uint16_t subrate_min, uint16_t subrate_max, uint16_t max_latency, + uint16_t cont_num, uint16_t sup_tout) { + connection_->LeSubrateRequest(subrate_min, subrate_max, max_latency, cont_num, sup_tout); } void ReadRemoteControllerInformation() override { @@ -797,9 +725,7 @@ class LeShimAclConnection return connection_->GetLocalOtaAddress(); } - bluetooth::hci::AddressWithType GetPeerAddressWithType() { - return connection_->GetPeerAddress(); - } + bluetooth::hci::AddressWithType GetPeerAddressWithType() { return connection_->GetPeerAddress(); } bluetooth::hci::AddressWithType GetPeerOtaAddressWithType() { return connection_->GetPeerOtaAddress(); @@ -807,64 +733,54 @@ class LeShimAclConnection std::optional GetAdvertisingSetConnectedTo() { return std::visit( - [](auto&& data) { - using T = std::decay_t; - if constexpr (std::is_same_v) { - return data.advertising_set_id; - } else { - return std::optional{}; - } - }, - connection_->GetRoleSpecificData()); - } - - void OnConnectionUpdate(hci::ErrorCode hci_status, - uint16_t connection_interval, - uint16_t connection_latency, - uint16_t supervision_timeout) { - TRY_POSTING_ON_MAIN( - interface_.on_connection_update, ToLegacyHciErrorCode(hci_status), - handle_, connection_interval, connection_latency, supervision_timeout); - } - void OnParameterUpdateRequest(uint16_t interval_min, uint16_t interval_max, - uint16_t latency, + [](auto&& data) { + using T = std::decay_t; + if constexpr (std::is_same_v) { + return data.advertising_set_id; + } else { + return std::optional{}; + } + }, + connection_->GetRoleSpecificData()); + } + + void OnConnectionUpdate(hci::ErrorCode hci_status, uint16_t connection_interval, + uint16_t connection_latency, uint16_t supervision_timeout) { + TRY_POSTING_ON_MAIN(interface_.on_connection_update, ToLegacyHciErrorCode(hci_status), handle_, + connection_interval, connection_latency, supervision_timeout); + } + void OnParameterUpdateRequest(uint16_t interval_min, uint16_t interval_max, uint16_t latency, uint16_t supervision_timeout) { - TRY_POSTING_ON_MAIN(interface_.on_parameter_update_request, handle_, - interval_min, interval_max, latency, - supervision_timeout); + TRY_POSTING_ON_MAIN(interface_.on_parameter_update_request, handle_, interval_min, interval_max, + latency, supervision_timeout); } - void OnDataLengthChange(uint16_t max_tx_octets, uint16_t max_tx_time, - uint16_t max_rx_octets, uint16_t max_rx_time) { - TRY_POSTING_ON_MAIN(interface_.on_data_length_change, handle_, - max_tx_octets, max_tx_time, max_rx_octets, max_rx_time); + void OnDataLengthChange(uint16_t max_tx_octets, uint16_t max_tx_time, uint16_t max_rx_octets, + uint16_t max_rx_time) { + TRY_POSTING_ON_MAIN(interface_.on_data_length_change, handle_, max_tx_octets, max_tx_time, + max_rx_octets, max_rx_time); } void OnLeSubrateChange(hci::ErrorCode hci_status, uint16_t subrate_factor, - uint16_t peripheral_latency, - uint16_t continuation_number, + uint16_t peripheral_latency, uint16_t continuation_number, uint16_t supervision_timeout) { - TRY_POSTING_ON_MAIN(interface_.on_le_subrate_change, handle_, - subrate_factor, peripheral_latency, continuation_number, - supervision_timeout, ToLegacyHciErrorCode(hci_status)); + TRY_POSTING_ON_MAIN(interface_.on_le_subrate_change, handle_, subrate_factor, + peripheral_latency, continuation_number, supervision_timeout, + ToLegacyHciErrorCode(hci_status)); } - void OnReadRemoteVersionInformationComplete(hci::ErrorCode hci_status, - uint8_t lmp_version, + void OnReadRemoteVersionInformationComplete(hci::ErrorCode hci_status, uint8_t lmp_version, uint16_t manufacturer_name, uint16_t sub_version) override { TRY_POSTING_ON_MAIN(interface_.on_read_remote_version_information_complete, - ToLegacyHciErrorCode(hci_status), handle_, lmp_version, - manufacturer_name, sub_version); + ToLegacyHciErrorCode(hci_status), handle_, lmp_version, manufacturer_name, + sub_version); } - void OnLeReadRemoteFeaturesComplete(hci::ErrorCode /* hci_status */, - uint64_t /* features */) { + void OnLeReadRemoteFeaturesComplete(hci::ErrorCode /* hci_status */, uint64_t /* features */) { // TODO } - void OnPhyUpdate(hci::ErrorCode hci_status, uint8_t tx_phy, - uint8_t rx_phy) override { - TRY_POSTING_ON_MAIN(interface_.on_phy_update, - ToLegacyHciErrorCode(hci_status), handle_, tx_phy, + void OnPhyUpdate(hci::ErrorCode hci_status, uint8_t tx_phy, uint8_t rx_phy) override { + TRY_POSTING_ON_MAIN(interface_.on_phy_update, ToLegacyHciErrorCode(hci_status), handle_, tx_phy, rx_phy); } @@ -873,30 +789,24 @@ class LeShimAclConnection on_disconnect_(handle_, reason); } - hci::AddressWithType GetRemoteAddressWithType() const { - return connection_->GetRemoteAddress(); - } + hci::AddressWithType GetRemoteAddressWithType() const { return connection_->GetRemoteAddress(); } void InitiateDisconnect(hci::DisconnectReason reason) override { connection_->Disconnect(reason); } - bool IsLocallyInitiated() const override { - return connection_->locally_initiated_; - } + bool IsLocallyInitiated() const override { return connection_->locally_initiated_; } - bool IsInFilterAcceptList() const { - return connection_->IsInFilterAcceptList(); - } + bool IsInFilterAcceptList() const { return connection_->IsInFilterAcceptList(); } void UpdateConnectionParameters(uint16_t conn_int_min, uint16_t conn_int_max, - uint16_t conn_latency, uint16_t conn_timeout, - uint16_t min_ce_len, uint16_t max_ce_len) { - connection_->LeConnectionUpdate(conn_int_min, conn_int_max, conn_latency, - conn_timeout, min_ce_len, max_ce_len); + uint16_t conn_latency, uint16_t conn_timeout, uint16_t min_ce_len, + uint16_t max_ce_len) { + connection_->LeConnectionUpdate(conn_int_min, conn_int_max, conn_latency, conn_timeout, + min_ce_len, max_ce_len); } - private: +private: OnDisconnect on_disconnect_; const shim::legacy::acl_le_link_interface_t interface_; std::unique_ptr connection_; @@ -905,19 +815,16 @@ class LeShimAclConnection struct shim::legacy::Acl::impl { impl(uint8_t max_acceptlist_size, uint8_t max_address_resolution_size) : shadow_acceptlist_(ShadowAcceptlist(max_acceptlist_size)), - shadow_address_resolution_list_( - ShadowAddressResolutionList(max_address_resolution_size)) {} + shadow_address_resolution_list_(ShadowAddressResolutionList(max_address_resolution_size)) {} - std::map> - handle_to_classic_connection_map_; - std::map> - handle_to_le_connection_map_; + std::map> handle_to_classic_connection_map_; + std::map> handle_to_le_connection_map_; SyncMapCount classic_acl_disconnect_reason_; SyncMapCount le_acl_disconnect_reason_; FixedQueue> connection_history_ = - FixedQueue>(kConnectionHistorySize); + FixedQueue>(kConnectionHistorySize); ShadowAcceptlist shadow_acceptlist_; ShadowAddressResolutionList shadow_address_resolution_list_; @@ -927,10 +834,8 @@ struct shim::legacy::Acl::impl { handle_to_classic_connection_map_.end(); } - void EnqueueClassicPacket(HciHandle handle, - std::unique_ptr packet) { - log::assert_that(IsClassicAcl(handle), - "handle {} is not a classic connection", handle); + void EnqueueClassicPacket(HciHandle handle, std::unique_ptr packet) { + log::assert_that(IsClassicAcl(handle), "handle {} is not a classic connection", handle); handle_to_classic_connection_map_[handle]->EnqueuePacket(std::move(packet)); } @@ -943,14 +848,11 @@ struct shim::legacy::Acl::impl { } bool IsLeAcl(HciHandle handle) { - return handle_to_le_connection_map_.find(handle) != - handle_to_le_connection_map_.end(); + return handle_to_le_connection_map_.find(handle) != handle_to_le_connection_map_.end(); } - void EnqueueLePacket(HciHandle handle, - std::unique_ptr packet) { - log::assert_that(IsLeAcl(handle), "handle {} is not a LE connection", - handle); + void EnqueueLePacket(HciHandle handle, std::unique_ptr packet) { + log::assert_that(IsLeAcl(handle), "handle {} is not a LE connection", handle); handle_to_le_connection_map_[handle]->EnqueuePacket(std::move(packet)); } @@ -958,8 +860,7 @@ struct shim::legacy::Acl::impl { log::info("Disconnect gd acl shim classic connections"); std::vector disconnect_handles; for (auto& connection : handle_to_classic_connection_map_) { - disconnect_classic(connection.first, HCI_ERR_REMOTE_POWER_OFF, - "Suspend disconnect"); + disconnect_classic(connection.first, HCI_ERR_REMOTE_POWER_OFF, "Suspend disconnect"); disconnect_handles.push_back(connection.first); } @@ -972,7 +873,7 @@ struct shim::legacy::Acl::impl { auto found = handle_to_classic_connection_map_.find(handle); if (found != handle_to_classic_connection_map_.end()) { GetAclManager()->OnClassicSuspendInitiatedDisconnect( - found->first, hci::ErrorCode::CONNECTION_TERMINATED_BY_LOCAL_HOST); + found->first, hci::ErrorCode::CONNECTION_TERMINATED_BY_LOCAL_HOST); } } @@ -992,8 +893,7 @@ struct shim::legacy::Acl::impl { log::info("Disconnect gd acl shim le connections"); std::vector disconnect_handles; for (auto& connection : handle_to_le_connection_map_) { - disconnect_le(connection.first, HCI_ERR_REMOTE_POWER_OFF, - "Suspend disconnect"); + disconnect_le(connection.first, HCI_ERR_REMOTE_POWER_OFF, "Suspend disconnect"); disconnect_handles.push_back(connection.first); } @@ -1006,7 +906,7 @@ struct shim::legacy::Acl::impl { auto found = handle_to_le_connection_map_.find(handle); if (found != handle_to_le_connection_map_.end()) { GetAclManager()->OnLeSuspendInitiatedDisconnect( - found->first, hci::ErrorCode::CONNECTION_TERMINATED_BY_LOCAL_HOST); + found->first, hci::ErrorCode::CONNECTION_TERMINATED_BY_LOCAL_HOST); } } promise.set_value(); @@ -1036,129 +936,101 @@ struct shim::legacy::Acl::impl { connection.second->Shutdown(); } handle_to_le_connection_map_.clear(); - log::info("Cleared all le connections count:{}", - handle_to_le_connection_map_.size()); + log::info("Cleared all le connections count:{}", handle_to_le_connection_map_.size()); } promise.set_value(); } - void HoldMode(HciHandle handle, uint16_t max_interval, - uint16_t min_interval) { - log::assert_that(IsClassicAcl(handle), - "handle {} is not a classic connection", handle); - handle_to_classic_connection_map_[handle]->HoldMode(max_interval, - min_interval); + void HoldMode(HciHandle handle, uint16_t max_interval, uint16_t min_interval) { + log::assert_that(IsClassicAcl(handle), "handle {} is not a classic connection", handle); + handle_to_classic_connection_map_[handle]->HoldMode(max_interval, min_interval); } void ExitSniffMode(HciHandle handle) { - log::assert_that(IsClassicAcl(handle), - "handle {} is not a classic connection", handle); + log::assert_that(IsClassicAcl(handle), "handle {} is not a classic connection", handle); handle_to_classic_connection_map_[handle]->ExitSniffMode(); } - void SniffMode(HciHandle handle, uint16_t max_interval, uint16_t min_interval, - uint16_t attempt, uint16_t timeout) { - log::assert_that(IsClassicAcl(handle), - "handle {} is not a classic connection", handle); - handle_to_classic_connection_map_[handle]->SniffMode( - max_interval, min_interval, attempt, timeout); + void SniffMode(HciHandle handle, uint16_t max_interval, uint16_t min_interval, uint16_t attempt, + uint16_t timeout) { + log::assert_that(IsClassicAcl(handle), "handle {} is not a classic connection", handle); + handle_to_classic_connection_map_[handle]->SniffMode(max_interval, min_interval, attempt, + timeout); } - void SniffSubrating(HciHandle handle, uint16_t maximum_latency, - uint16_t minimum_remote_timeout, + void SniffSubrating(HciHandle handle, uint16_t maximum_latency, uint16_t minimum_remote_timeout, uint16_t minimum_local_timeout) { - log::assert_that(IsClassicAcl(handle), - "handle {} is not a classic connection", handle); + log::assert_that(IsClassicAcl(handle), "handle {} is not a classic connection", handle); handle_to_classic_connection_map_[handle]->SniffSubrating( - maximum_latency, minimum_remote_timeout, minimum_local_timeout); + maximum_latency, minimum_remote_timeout, minimum_local_timeout); } - void LeSetDefaultSubrate(uint16_t subrate_min, uint16_t subrate_max, - uint16_t max_latency, uint16_t cont_num, - uint16_t sup_tout) { - GetAclManager()->LeSetDefaultSubrate(subrate_min, subrate_max, max_latency, - cont_num, sup_tout); + void LeSetDefaultSubrate(uint16_t subrate_min, uint16_t subrate_max, uint16_t max_latency, + uint16_t cont_num, uint16_t sup_tout) { + GetAclManager()->LeSetDefaultSubrate(subrate_min, subrate_max, max_latency, cont_num, sup_tout); } - void LeSubrateRequest(HciHandle handle, uint16_t subrate_min, - uint16_t subrate_max, uint16_t max_latency, - uint16_t cont_num, uint16_t sup_tout) { - log::assert_that(IsLeAcl(handle), "handle {} is not a LE connection", - handle); - handle_to_le_connection_map_[handle]->LeSubrateRequest( - subrate_min, subrate_max, max_latency, cont_num, sup_tout); + void LeSubrateRequest(HciHandle handle, uint16_t subrate_min, uint16_t subrate_max, + uint16_t max_latency, uint16_t cont_num, uint16_t sup_tout) { + log::assert_that(IsLeAcl(handle), "handle {} is not a LE connection", handle); + handle_to_le_connection_map_[handle]->LeSubrateRequest(subrate_min, subrate_max, max_latency, + cont_num, sup_tout); } void SetConnectionEncryption(HciHandle handle, hci::Enable enable) { - log::assert_that(IsClassicAcl(handle), - "handle {} is not a classic connection", handle); + log::assert_that(IsClassicAcl(handle), "handle {} is not a classic connection", handle); handle_to_classic_connection_map_[handle]->SetConnectionEncryption(enable); } - void disconnect_classic(uint16_t handle, tHCI_STATUS reason, - std::string comment) { + void disconnect_classic(uint16_t handle, tHCI_STATUS reason, std::string comment) { auto connection = handle_to_classic_connection_map_.find(handle); if (connection != handle_to_classic_connection_map_.end()) { auto remote_address = connection->second->GetRemoteAddress(); - connection->second->InitiateDisconnect( - ToDisconnectReasonFromLegacy(reason)); - log::debug("Disconnection initiated classic remote:{} handle:{}", - remote_address, handle); - BTM_LogHistory(kBtmLogTag, ToRawAddress(remote_address), - "Disconnection initiated", + connection->second->InitiateDisconnect(ToDisconnectReasonFromLegacy(reason)); + log::debug("Disconnection initiated classic remote:{} handle:{}", remote_address, handle); + BTM_LogHistory(kBtmLogTag, ToRawAddress(remote_address), "Disconnection initiated", base::StringPrintf("classic reason:%s comment:%s", - hci_status_code_text(reason).c_str(), - comment.c_str())); + hci_status_code_text(reason).c_str(), comment.c_str())); classic_acl_disconnect_reason_.Put(comment); } else { - log::warn( - "Unable to disconnect unknown classic connection handle:0x{:04x}", - handle); + log::warn("Unable to disconnect unknown classic connection handle:0x{:04x}", handle); } } void disconnect_le(uint16_t handle, tHCI_STATUS reason, std::string comment) { auto connection = handle_to_le_connection_map_.find(handle); if (connection != handle_to_le_connection_map_.end()) { - auto remote_address_with_type = - connection->second->GetRemoteAddressWithType(); + auto remote_address_with_type = connection->second->GetRemoteAddressWithType(); if (!common::init_flags::use_unified_connection_manager_is_enabled()) { GetAclManager()->RemoveFromBackgroundList(remote_address_with_type); } - connection->second->InitiateDisconnect( - ToDisconnectReasonFromLegacy(reason)); - log::debug("Disconnection initiated le remote:{} handle:{}", - remote_address_with_type, handle); - BTM_LogHistory(kBtmLogTag, - ToLegacyAddressWithType(remote_address_with_type), + connection->second->InitiateDisconnect(ToDisconnectReasonFromLegacy(reason)); + log::debug("Disconnection initiated le remote:{} handle:{}", remote_address_with_type, + handle); + BTM_LogHistory(kBtmLogTag, ToLegacyAddressWithType(remote_address_with_type), "Disconnection initiated", base::StringPrintf("Le reason:%s comment:%s", - hci_status_code_text(reason).c_str(), - comment.c_str())); + hci_status_code_text(reason).c_str(), comment.c_str())); le_acl_disconnect_reason_.Put(comment); } else { - log::warn("Unable to disconnect unknown le connection handle:0x{:04x}", - handle); + log::warn("Unable to disconnect unknown le connection handle:0x{:04x}", handle); } } - void update_connection_parameters(uint16_t handle, uint16_t conn_int_min, - uint16_t conn_int_max, - uint16_t conn_latency, - uint16_t conn_timeout, uint16_t min_ce_len, - uint16_t max_ce_len) { + void update_connection_parameters(uint16_t handle, uint16_t conn_int_min, uint16_t conn_int_max, + uint16_t conn_latency, uint16_t conn_timeout, + uint16_t min_ce_len, uint16_t max_ce_len) { auto connection = handle_to_le_connection_map_.find(handle); if (connection == handle_to_le_connection_map_.end()) { log::warn("Unknown le connection handle:0x{:04x}", handle); return; } - connection->second->UpdateConnectionParameters(conn_int_min, conn_int_max, - conn_latency, conn_timeout, - min_ce_len, max_ce_len); + connection->second->UpdateConnectionParameters(conn_int_min, conn_int_max, conn_latency, + conn_timeout, min_ce_len, max_ce_len); } - void accept_le_connection_from(const hci::AddressWithType& address_with_type, - bool is_direct, std::promise promise) { + void accept_le_connection_from(const hci::AddressWithType& address_with_type, bool is_direct, + std::promise promise) { if (shadow_acceptlist_.IsFull()) { log::error("Acceptlist is full preventing new Le connection"); promise.set_value(false); @@ -1168,17 +1040,16 @@ struct shim::legacy::Acl::impl { promise.set_value(true); GetAclManager()->CreateLeConnection(address_with_type, is_direct); log::debug("Allow Le connection from remote:{}", address_with_type); - BTM_LogHistory(kBtmLogTag, ToLegacyAddressWithType(address_with_type), - "Allow connection from", "Le"); + BTM_LogHistory(kBtmLogTag, ToLegacyAddressWithType(address_with_type), "Allow connection from", + "Le"); } - void ignore_le_connection_from( - const hci::AddressWithType& address_with_type) { + void ignore_le_connection_from(const hci::AddressWithType& address_with_type) { shadow_acceptlist_.Remove(address_with_type); GetAclManager()->CancelLeConnect(address_with_type); log::debug("Ignore Le connection from remote:{}", address_with_type); - BTM_LogHistory(kBtmLogTag, ToLegacyAddressWithType(address_with_type), - "Ignore connection from", "Le"); + BTM_LogHistory(kBtmLogTag, ToLegacyAddressWithType(address_with_type), "Ignore connection from", + "Le"); } void clear_acceptlist() { @@ -1199,16 +1070,13 @@ struct shim::legacy::Acl::impl { } // TODO This should really be added upon successful completion shadow_address_resolution_list_.Add(address_with_type); - GetAclManager()->AddDeviceToResolvingList(address_with_type, peer_irk, - local_irk); + GetAclManager()->AddDeviceToResolvingList(address_with_type, peer_irk, local_irk); } - void RemoveFromAddressResolution( - const hci::AddressWithType& address_with_type) { + void RemoveFromAddressResolution(const hci::AddressWithType& address_with_type) { // TODO This should really be removed upon successful removal if (!shadow_address_resolution_list_.Remove(address_with_type)) { - log::warn("Unable to remove from Le Address Resolution list device:{}", - address_with_type); + log::warn("Unable to remove from Le Address Resolution list device:{}", address_with_type); } GetAclManager()->RemoveDeviceFromResolvingList(address_with_type); } @@ -1219,19 +1087,16 @@ struct shim::legacy::Acl::impl { shadow_address_resolution_list_.Clear(); } - void SetSystemSuspendState(bool suspended) { - GetAclManager()->SetSystemSuspendState(suspended); - } + void SetSystemSuspendState(bool suspended) { GetAclManager()->SetSystemSuspendState(suspended); } void DumpConnectionHistory() const { - std::vector history = - connection_history_.ReadElementsAsString(); + std::vector history = connection_history_.ReadElementsAsString(); for (auto& entry : history) { log::debug("{}", entry); } const auto acceptlist = shadow_acceptlist_.GetCopy(); - log::debug("Shadow le accept list size:{:<3} controller_max_size:{}", - acceptlist.size(), shadow_acceptlist_.GetMaxSize()); + log::debug("Shadow le accept list size:{:<3} controller_max_size:{}", acceptlist.size(), + shadow_acceptlist_.GetMaxSize()); for (auto& entry : acceptlist) { log::debug("acceptlist:{}", entry); } @@ -1239,15 +1104,13 @@ struct shim::legacy::Acl::impl { #define DUMPSYS_TAG "shim::acl" void DumpConnectionHistory(int fd) const { - std::vector history = - connection_history_.ReadElementsAsString(); + std::vector history = connection_history_.ReadElementsAsString(); for (auto& entry : history) { LOG_DUMPSYS(fd, "%s", entry.c_str()); } if (classic_acl_disconnect_reason_.Size() > 0) { LOG_DUMPSYS(fd, "Classic sources of initiated disconnects"); - for (const auto& item : - classic_acl_disconnect_reason_.GetSortedHighToLow()) { + for (const auto& item : classic_acl_disconnect_reason_.GetSortedHighToLow()) { LOG_DUMPSYS(fd, " %s:%zu", item.item.c_str(), item.count); } } @@ -1271,8 +1134,7 @@ struct shim::legacy::Acl::impl { LOG_DUMPSYS(fd, "Shadow le address resolution list size:%-3zu " "controller_max_size:%hhu", - address_resolution_list.size(), - shadow_address_resolution_list_.GetMaxSize()); + address_resolution_list.size(), shadow_address_resolution_list_.GetMaxSize()); cnt = 0; for (auto& entry : address_resolution_list) { LOG_DUMPSYS(fd, " %03u %s", ++cnt, ADDRESS_TO_LOGGABLE_CSTR(entry)); @@ -1293,13 +1155,14 @@ void DumpsysAcl(int fd) { for (int i = 0; i < MAX_L2CAP_LINKS; i++) { const tACL_CONN& link = acl_cb.acl_db[i]; - if (!link.in_use) continue; + if (!link.in_use) { + continue; + } LOG_DUMPSYS(fd, "remote_addr:%s handle:0x%04x transport:%s", ADDRESS_TO_LOGGABLE_CSTR(link.remote_addr), link.hci_handle, bt_transport_text(link.transport).c_str()); - LOG_DUMPSYS(fd, " link_up_issued:%5s", - (link.link_up_issued) ? "true" : "false"); + LOG_DUMPSYS(fd, " link_up_issued:%5s", (link.link_up_issued) ? "true" : "false"); LOG_DUMPSYS(fd, " flush_timeout:0x%04x", link.flush_timeout_in_ticks); LOG_DUMPSYS(fd, " link_supervision_timeout:%.3f sec", ticks_to_seconds(link.link_super_tout)); @@ -1307,18 +1170,18 @@ void DumpsysAcl(int fd) { if (link.is_transport_br_edr()) { for (int j = 0; j < HCI_EXT_FEATURES_PAGE_MAX + 1; j++) { - if (!link.peer_lmp_feature_valid[j]) continue; + if (!link.peer_lmp_feature_valid[j]) { + continue; + } LOG_DUMPSYS(fd, " peer_lmp_features[%d] valid:%s data:%s", j, common::ToString(link.peer_lmp_feature_valid[j]).c_str(), bd_features_text(link.peer_lmp_feature_pages[j]).c_str()); } LOG_DUMPSYS(fd, " [classic] link_policy:%s", - link_policy_text(static_cast(link.link_policy)) - .c_str()); + link_policy_text(static_cast(link.link_policy)).c_str()); LOG_DUMPSYS(fd, " [classic] sniff_subrating:%s", - common::ToString(HCI_SNIFF_SUB_RATE_SUPPORTED( - link.peer_lmp_feature_pages[0])) - .c_str()); + common::ToString(HCI_SNIFF_SUB_RATE_SUPPORTED(link.peer_lmp_feature_pages[0])) + .c_str()); LOG_DUMPSYS(fd, " pkt_types_mask:0x%04x", link.pkt_types_mask); LOG_DUMPSYS(fd, " role:%s", RoleText(link.link_role).c_str()); @@ -1348,8 +1211,7 @@ void DumpsysBtm(int fd) { struct tm tm; localtime_r(&then, &tm); auto s2 = common::StringFormatTime(kTimeFormat, tm); - LOG_DUMPSYS(fd, " %s.%03u %s", s2.c_str(), - static_cast(record.timestamp % 1000), + LOG_DUMPSYS(fd, " %s.%03u %s", s2.c_str(), static_cast(record.timestamp % 1000), record.entry.c_str()); } } @@ -1369,8 +1231,7 @@ void DumpsysRecord(int fd) { list_node_t* end = list_end(btm_sec_cb.sec_dev_rec); for (list_node_t* node = list_begin(btm_sec_cb.sec_dev_rec); node != end; node = list_next(node)) { - tBTM_SEC_DEV_REC* p_dev_rec = - static_cast(list_node(node)); + tBTM_SEC_DEV_REC* p_dev_rec = static_cast(list_node(node)); // TODO: handle in tBTM_SEC_DEV_REC.ToString LOG_DUMPSYS(fd, "%03u %s", ++cnt, p_dev_rec->ToString().c_str()); } @@ -1386,17 +1247,17 @@ void DumpsysNeighbor(int fd) { LOG_DUMPSYS(fd, "Classic inquiry:enabled duration_s:%.3f results:%lu", (timestamper_in_milliseconds.GetTimestamp() - btm_cb.neighbor.classic_inquiry.start_time_ms) / - 1000.0, + 1000.0, btm_cb.neighbor.classic_inquiry.results); } if (btm_cb.neighbor.le_scan.start_time_ms == 0) { LOG_DUMPSYS(fd, "Le scan:disabled"); } else { - LOG_DUMPSYS(fd, "Le scan:enabled duration_s:%.3f results:%lu", - (timestamper_in_milliseconds.GetTimestamp() - - btm_cb.neighbor.le_scan.start_time_ms) / + LOG_DUMPSYS( + fd, "Le scan:enabled duration_s:%.3f results:%lu", + (timestamper_in_milliseconds.GetTimestamp() - btm_cb.neighbor.le_scan.start_time_ms) / 1000.0, - btm_cb.neighbor.le_scan.results); + btm_cb.neighbor.le_scan.results); } const auto copy = btm_cb.neighbor.inquiry_history_->Pull(); LOG_DUMPSYS(fd, "Last %zu inquiry scans:", copy.size()); @@ -1405,9 +1266,8 @@ void DumpsysNeighbor(int fd) { " %s - %s duration_ms:%-5llu num_resp:%-2u" " std:%-2u rssi:%-2u ext:%-2u %12s", EpochMillisToString(it.entry.start_time_ms).c_str(), - EpochMillisToString(it.timestamp).c_str(), - it.timestamp - it.entry.start_time_ms, it.entry.num_resp, - it.entry.resp_type[BTM_INQ_RESULT_STANDARD], + EpochMillisToString(it.timestamp).c_str(), it.timestamp - it.entry.start_time_ms, + it.entry.num_resp, it.entry.resp_type[BTM_INQ_RESULT_STANDARD], it.entry.resp_type[BTM_INQ_RESULT_WITH_RSSI], it.entry.resp_type[BTM_INQ_RESULT_EXTENDED], btm_inquiry_cmpl_status_text(it.entry.status).c_str()); @@ -1423,21 +1283,17 @@ void shim::legacy::Acl::Dump(int fd) const { DumpsysBtm(fd); } -shim::legacy::Acl::Acl(os::Handler* handler, - const acl_interface_t& acl_interface, - uint8_t max_acceptlist_size, - uint8_t max_address_resolution_size) +shim::legacy::Acl::Acl(os::Handler* handler, const acl_interface_t& acl_interface, + uint8_t max_acceptlist_size, uint8_t max_address_resolution_size) : handler_(handler), acl_interface_(acl_interface) { log::assert_that(handler_ != nullptr, "assert failed: handler_ != nullptr"); ValidateAclInterface(acl_interface_); - pimpl_ = std::make_unique(max_acceptlist_size, - max_address_resolution_size); + pimpl_ = std::make_unique(max_acceptlist_size, max_address_resolution_size); GetAclManager()->RegisterCallbacks(this, handler_); GetAclManager()->RegisterLeCallbacks(this, handler_); GetController()->RegisterCompletedMonitorAclPacketsCallback( - handler->BindOn(this, &Acl::on_incoming_acl_credits)); - shim::RegisterDumpsysFunction(static_cast(this), - [this](int fd) { Dump(fd); }); + handler->BindOn(this, &Acl::on_incoming_acl_credits)); + shim::RegisterDumpsysFunction(static_cast(this), [this](int fd) { Dump(fd); }); } shim::legacy::Acl::~Acl() { @@ -1456,11 +1312,9 @@ bool shim::legacy::Acl::CheckForOrphanedAclConnections() const { log::error("About to destroy classic active ACL"); for (const auto& connection : pimpl_->handle_to_classic_connection_map_) { log::error("Orphaned classic ACL handle:0x{:04x} bd_addr:{} created:{}", - connection.second->Handle(), - connection.second->GetRemoteAddress(), - common::StringFormatTimeWithMilliseconds( - kConnectionDescriptorTimeFormat, - connection.second->GetCreationTime())); + connection.second->Handle(), connection.second->GetRemoteAddress(), + common::StringFormatTimeWithMilliseconds(kConnectionDescriptorTimeFormat, + connection.second->GetCreationTime())); } orphaned_acl_connections = true; } @@ -1469,24 +1323,21 @@ bool shim::legacy::Acl::CheckForOrphanedAclConnections() const { log::error("About to destroy le active ACL"); for (const auto& connection : pimpl_->handle_to_le_connection_map_) { log::error("Orphaned le ACL handle:0x{:04x} bd_addr:{} created:{}", - connection.second->Handle(), - connection.second->GetRemoteAddressWithType(), - common::StringFormatTimeWithMilliseconds( - kConnectionDescriptorTimeFormat, - connection.second->GetCreationTime())); + connection.second->Handle(), connection.second->GetRemoteAddressWithType(), + common::StringFormatTimeWithMilliseconds(kConnectionDescriptorTimeFormat, + connection.second->GetCreationTime())); } orphaned_acl_connections = true; } return orphaned_acl_connections; } -void shim::legacy::Acl::on_incoming_acl_credits(uint16_t handle, - uint16_t credits) { +void shim::legacy::Acl::on_incoming_acl_credits(uint16_t handle, uint16_t credits) { TRY_POSTING_ON_MAIN(acl_interface_.on_packets_completed, handle, credits); } -void shim::legacy::Acl::write_data_sync( - HciHandle handle, std::unique_ptr packet) { +void shim::legacy::Acl::write_data_sync(HciHandle handle, + std::unique_ptr packet) { if (pimpl_->IsClassicAcl(handle)) { pimpl_->EnqueueClassicPacket(handle, std::move(packet)); } else if (pimpl_->IsLeAcl(handle)) { @@ -1496,57 +1347,47 @@ void shim::legacy::Acl::write_data_sync( } } -void shim::legacy::Acl::WriteData(HciHandle handle, - std::unique_ptr packet) { - handler_->Post(common::BindOnce(&Acl::write_data_sync, - common::Unretained(this), handle, +void shim::legacy::Acl::WriteData(HciHandle handle, std::unique_ptr packet) { + handler_->Post(common::BindOnce(&Acl::write_data_sync, common::Unretained(this), handle, std::move(packet))); } void shim::legacy::Acl::flush(HciHandle handle) { pimpl_->Flush(handle); } void shim::legacy::Acl::Flush(HciHandle handle) { - handler_->Post( - common::BindOnce(&Acl::flush, common::Unretained(this), handle)); + handler_->Post(common::BindOnce(&Acl::flush, common::Unretained(this), handle)); } void shim::legacy::Acl::CreateClassicConnection(const hci::Address& address) { GetAclManager()->CreateConnection(address); log::debug("Connection initiated for classic to remote:{}", address); - BTM_LogHistory(kBtmLogTag, ToRawAddress(address), "Initiated connection", - "classic"); + BTM_LogHistory(kBtmLogTag, ToRawAddress(address), "Initiated connection", "classic"); } void shim::legacy::Acl::CancelClassicConnection(const hci::Address& address) { GetAclManager()->CancelConnect(address); log::debug("Connection cancelled for classic to remote:{}", address); - BTM_LogHistory(kBtmLogTag, ToRawAddress(address), "Cancelled connection", - "classic"); + BTM_LogHistory(kBtmLogTag, ToRawAddress(address), "Cancelled connection", "classic"); } -void shim::legacy::Acl::AcceptLeConnectionFrom( - const hci::AddressWithType& address_with_type, bool is_direct, - std::promise promise) { +void shim::legacy::Acl::AcceptLeConnectionFrom(const hci::AddressWithType& address_with_type, + bool is_direct, std::promise promise) { log::debug("AcceptLeConnectionFrom {}", address_with_type.GetAddress()); - handler_->CallOn(pimpl_.get(), &Acl::impl::accept_le_connection_from, - address_with_type, is_direct, std::move(promise)); + handler_->CallOn(pimpl_.get(), &Acl::impl::accept_le_connection_from, address_with_type, + is_direct, std::move(promise)); } -void shim::legacy::Acl::IgnoreLeConnectionFrom( - const hci::AddressWithType& address_with_type) { +void shim::legacy::Acl::IgnoreLeConnectionFrom(const hci::AddressWithType& address_with_type) { log::debug("IgnoreLeConnectionFrom {}", address_with_type.GetAddress()); - handler_->CallOn(pimpl_.get(), &Acl::impl::ignore_le_connection_from, - address_with_type); + handler_->CallOn(pimpl_.get(), &Acl::impl::ignore_le_connection_from, address_with_type); } -void shim::legacy::Acl::OnClassicLinkDisconnected(HciHandle handle, - hci::ErrorCode reason) { +void shim::legacy::Acl::OnClassicLinkDisconnected(HciHandle handle, hci::ErrorCode reason) { hci::Address remote_address = - pimpl_->handle_to_classic_connection_map_[handle]->GetRemoteAddress(); - CreationTime creation_time = - pimpl_->handle_to_classic_connection_map_[handle]->GetCreationTime(); + pimpl_->handle_to_classic_connection_map_[handle]->GetRemoteAddress(); + CreationTime creation_time = pimpl_->handle_to_classic_connection_map_[handle]->GetCreationTime(); bool is_locally_initiated = - pimpl_->handle_to_classic_connection_map_[handle]->IsLocallyInitiated(); + pimpl_->handle_to_classic_connection_map_[handle]->IsLocallyInitiated(); TeardownTime teardown_time = std::chrono::system_clock::now(); @@ -1554,19 +1395,16 @@ void shim::legacy::Acl::OnClassicLinkDisconnected(HciHandle handle, TRY_POSTING_ON_MAIN(acl_interface_.connection.classic.on_disconnected, ToLegacyHciErrorCode(hci::ErrorCode::SUCCESS), handle, ToLegacyHciErrorCode(reason)); - log::debug("Disconnected classic link remote:{} handle:{} reason:{}", - remote_address, handle, ErrorCodeText(reason)); - BTM_LogHistory( - kBtmLogTag, ToRawAddress(remote_address), "Disconnected", - base::StringPrintf("classic reason:%s", ErrorCodeText(reason).c_str())); - pimpl_->connection_history_.Push( - std::make_unique( - remote_address, creation_time, teardown_time, handle, - is_locally_initiated, reason)); + log::debug("Disconnected classic link remote:{} handle:{} reason:{}", remote_address, handle, + ErrorCodeText(reason)); + BTM_LogHistory(kBtmLogTag, ToRawAddress(remote_address), "Disconnected", + base::StringPrintf("classic reason:%s", ErrorCodeText(reason).c_str())); + pimpl_->connection_history_.Push(std::make_unique( + remote_address, creation_time, teardown_time, handle, is_locally_initiated, reason)); } -bluetooth::hci::AddressWithType shim::legacy::Acl::GetConnectionLocalAddress( - uint16_t handle, bool ota_address) { +bluetooth::hci::AddressWithType shim::legacy::Acl::GetConnectionLocalAddress(uint16_t handle, + bool ota_address) { bluetooth::hci::AddressWithType address_with_type; for (auto& [acl_handle, connection] : pimpl_->handle_to_le_connection_map_) { @@ -1583,8 +1421,8 @@ bluetooth::hci::AddressWithType shim::legacy::Acl::GetConnectionLocalAddress( return address_with_type; } -bluetooth::hci::AddressWithType shim::legacy::Acl::GetConnectionPeerAddress( - uint16_t handle, bool ota_address) { +bluetooth::hci::AddressWithType shim::legacy::Acl::GetConnectionPeerAddress(uint16_t handle, + bool ota_address) { bluetooth::hci::AddressWithType address_with_type; for (auto& [acl_handle, connection] : pimpl_->handle_to_le_connection_map_) { if (acl_handle != handle) { @@ -1601,7 +1439,7 @@ bluetooth::hci::AddressWithType shim::legacy::Acl::GetConnectionPeerAddress( } std::optional shim::legacy::Acl::GetAdvertisingSetConnectedTo( - const RawAddress& remote_bda) { + const RawAddress& remote_bda) { auto remote_address = ToGdAddress(remote_bda); for (auto& [handle, connection] : pimpl_->handle_to_le_connection_map_) { if (connection->GetRemoteAddressWithType().GetAddress() == remote_address) { @@ -1612,14 +1450,11 @@ std::optional shim::legacy::Acl::GetAdvertisingSetConnectedTo( return {}; } -void shim::legacy::Acl::OnLeLinkDisconnected(HciHandle handle, - hci::ErrorCode reason) { +void shim::legacy::Acl::OnLeLinkDisconnected(HciHandle handle, hci::ErrorCode reason) { hci::AddressWithType remote_address_with_type = - pimpl_->handle_to_le_connection_map_[handle]->GetRemoteAddressWithType(); - CreationTime creation_time = - pimpl_->handle_to_le_connection_map_[handle]->GetCreationTime(); - bool is_locally_initiated = - pimpl_->handle_to_le_connection_map_[handle]->IsLocallyInitiated(); + pimpl_->handle_to_le_connection_map_[handle]->GetRemoteAddressWithType(); + CreationTime creation_time = pimpl_->handle_to_le_connection_map_[handle]->GetCreationTime(); + bool is_locally_initiated = pimpl_->handle_to_le_connection_map_[handle]->IsLocallyInitiated(); TeardownTime teardown_time = std::chrono::system_clock::now(); @@ -1627,85 +1462,71 @@ void shim::legacy::Acl::OnLeLinkDisconnected(HciHandle handle, TRY_POSTING_ON_MAIN(acl_interface_.connection.le.on_disconnected, ToLegacyHciErrorCode(hci::ErrorCode::SUCCESS), handle, ToLegacyHciErrorCode(reason)); - log::debug("Disconnected le link remote:{} handle:{} reason:{}", - remote_address_with_type, handle, ErrorCodeText(reason)); - BTM_LogHistory( - kBtmLogTag, ToLegacyAddressWithType(remote_address_with_type), - "Disconnected", - base::StringPrintf("Le reason:%s", ErrorCodeText(reason).c_str())); + log::debug("Disconnected le link remote:{} handle:{} reason:{}", remote_address_with_type, handle, + ErrorCodeText(reason)); + BTM_LogHistory(kBtmLogTag, ToLegacyAddressWithType(remote_address_with_type), "Disconnected", + base::StringPrintf("Le reason:%s", ErrorCodeText(reason).c_str())); pimpl_->connection_history_.Push(std::make_unique( - remote_address_with_type, creation_time, teardown_time, handle, - is_locally_initiated, reason)); + remote_address_with_type, creation_time, teardown_time, handle, is_locally_initiated, + reason)); } void shim::legacy::Acl::OnConnectSuccess( - std::unique_ptr connection) { - log::assert_that(connection != nullptr, - "assert failed: connection != nullptr"); + std::unique_ptr connection) { + log::assert_that(connection != nullptr, "assert failed: connection != nullptr"); auto handle = connection->GetHandle(); bool locally_initiated = connection->locally_initiated_; const hci::Address remote_address = connection->GetAddress(); const RawAddress bd_addr = ToRawAddress(remote_address); pimpl_->handle_to_classic_connection_map_.emplace( - handle, std::make_unique( - acl_interface_.on_send_data_upwards, - std::bind(&shim::legacy::Acl::OnClassicLinkDisconnected, this, - std::placeholders::_1, std::placeholders::_2), - acl_interface_.link.classic, handler_, std::move(connection), - std::chrono::system_clock::now())); + handle, std::make_unique( + acl_interface_.on_send_data_upwards, + std::bind(&shim::legacy::Acl::OnClassicLinkDisconnected, this, + std::placeholders::_1, std::placeholders::_2), + acl_interface_.link.classic, handler_, std::move(connection), + std::chrono::system_clock::now())); pimpl_->handle_to_classic_connection_map_[handle]->RegisterCallbacks(); - pimpl_->handle_to_classic_connection_map_[handle] - ->ReadRemoteControllerInformation(); - - TRY_POSTING_ON_MAIN(acl_interface_.connection.classic.on_connected, bd_addr, - handle, false, locally_initiated); - log::debug("Connection successful classic remote:{} handle:{} initiator:{}", - remote_address, handle, (locally_initiated) ? "local" : "remote"); - BTM_LogHistory(kBtmLogTag, ToRawAddress(remote_address), - "Connection successful", - (locally_initiated) ? "classic Local initiated" - : "classic Remote initiated"); + pimpl_->handle_to_classic_connection_map_[handle]->ReadRemoteControllerInformation(); + + TRY_POSTING_ON_MAIN(acl_interface_.connection.classic.on_connected, bd_addr, handle, false, + locally_initiated); + log::debug("Connection successful classic remote:{} handle:{} initiator:{}", remote_address, + handle, (locally_initiated) ? "local" : "remote"); + BTM_LogHistory(kBtmLogTag, ToRawAddress(remote_address), "Connection successful", + (locally_initiated) ? "classic Local initiated" : "classic Remote initiated"); } -void shim::legacy::Acl::OnConnectRequest(hci::Address address, - hci::ClassOfDevice cod) { +void shim::legacy::Acl::OnConnectRequest(hci::Address address, hci::ClassOfDevice cod) { const RawAddress bd_addr = ToRawAddress(address); const DEV_CLASS dev_class = ToDevClass(cod); - TRY_POSTING_ON_MAIN(acl_interface_.connection.classic.on_connect_request, - bd_addr, cod); - log::debug("Received connect request remote:{} gd_cod:{} legacy_dev_class:{}", - address, cod.ToString(), dev_class_text(dev_class)); + TRY_POSTING_ON_MAIN(acl_interface_.connection.classic.on_connect_request, bd_addr, cod); + log::debug("Received connect request remote:{} gd_cod:{} legacy_dev_class:{}", address, + cod.ToString(), dev_class_text(dev_class)); BTM_LogHistory(kBtmLogTag, ToRawAddress(address), "Connection request", - base::StringPrintf("gd_cod:%s legacy_dev_class:%s", - cod.ToString().c_str(), + base::StringPrintf("gd_cod:%s legacy_dev_class:%s", cod.ToString().c_str(), dev_class_text(dev_class).c_str())); } -void shim::legacy::Acl::OnConnectFail(hci::Address address, - hci::ErrorCode reason, +void shim::legacy::Acl::OnConnectFail(hci::Address address, hci::ErrorCode reason, bool locally_initiated) { const RawAddress bd_addr = ToRawAddress(address); TRY_POSTING_ON_MAIN(acl_interface_.connection.classic.on_failed, bd_addr, ToLegacyHciErrorCode(reason), locally_initiated); - log::warn("Connection failed classic remote:{} reason:{}", address, - hci::ErrorCodeText(reason)); + log::warn("Connection failed classic remote:{} reason:{}", address, hci::ErrorCodeText(reason)); BTM_LogHistory(kBtmLogTag, ToRawAddress(address), "Connection failed", - base::StringPrintf("classic reason:%s", - hci::ErrorCodeText(reason).c_str())); + base::StringPrintf("classic reason:%s", hci::ErrorCodeText(reason).c_str())); } void shim::legacy::Acl::OnLeConnectSuccess( - hci::AddressWithType address_with_type, - std::unique_ptr connection) { - log::assert_that(connection != nullptr, - "assert failed: connection != nullptr"); + hci::AddressWithType address_with_type, + std::unique_ptr connection) { + log::assert_that(connection != nullptr, "assert failed: connection != nullptr"); auto handle = connection->GetHandle(); // Save the peer address, if any - hci::AddressWithType peer_address_with_type = - connection->peer_address_with_type_; + hci::AddressWithType peer_address_with_type = connection->peer_address_with_type_; hci::Role connection_role = connection->GetRole(); bool locally_initiated = connection->locally_initiated_; @@ -1714,41 +1535,39 @@ void shim::legacy::Acl::OnLeConnectSuccess( uint16_t conn_latency = connection->latency_; uint16_t conn_timeout = connection->supervision_timeout_; - RawAddress local_rpa = - ToRawAddress(connection->local_resolvable_private_address_); - RawAddress peer_rpa = - ToRawAddress(connection->peer_resolvable_private_address_); + RawAddress local_rpa = ToRawAddress(connection->local_resolvable_private_address_); + RawAddress peer_rpa = ToRawAddress(connection->peer_resolvable_private_address_); tBLE_ADDR_TYPE peer_addr_type = - (tBLE_ADDR_TYPE)connection->peer_address_with_type_.GetAddressType(); + (tBLE_ADDR_TYPE)connection->peer_address_with_type_.GetAddressType(); auto can_read_discoverable_characteristics = std::visit( - [&](auto&& data) { - using T = std::decay_t; - if constexpr (std::is_same_v) { - return data.connected_to_discoverable; - } else { - // if we are the central, the peer can always see discoverable - // characteristics - return true; - } - }, - connection->GetRoleSpecificData()); + [&](auto&& data) { + using T = std::decay_t; + if constexpr (std::is_same_v) { + return data.connected_to_discoverable; + } else { + // if we are the central, the peer can always see discoverable + // characteristics + return true; + } + }, + connection->GetRoleSpecificData()); pimpl_->handle_to_le_connection_map_.emplace( - handle, std::make_unique( - acl_interface_.on_send_data_upwards, - std::bind(&shim::legacy::Acl::OnLeLinkDisconnected, this, - std::placeholders::_1, std::placeholders::_2), - acl_interface_.link.le, handler_, std::move(connection), - std::chrono::system_clock::now())); + handle, std::make_unique( + acl_interface_.on_send_data_upwards, + std::bind(&shim::legacy::Acl::OnLeLinkDisconnected, this, + std::placeholders::_1, std::placeholders::_2), + acl_interface_.link.le, handler_, std::move(connection), + std::chrono::system_clock::now())); pimpl_->handle_to_le_connection_map_[handle]->RegisterCallbacks(); // Once an le connection has successfully been established // the device address is removed from the controller accept list. if (IsRpa(address_with_type)) { - log::debug("Connection address is rpa:{} identity_addr:{}", - address_with_type, peer_address_with_type); + log::debug("Connection address is rpa:{} identity_addr:{}", address_with_type, + peer_address_with_type); pimpl_->shadow_acceptlist_.Remove(peer_address_with_type); } else { log::debug("Connection address is not rpa addr:{}", address_with_type); @@ -1758,94 +1577,76 @@ void shim::legacy::Acl::OnLeConnectSuccess( if (!pimpl_->handle_to_le_connection_map_[handle]->IsInFilterAcceptList() && connection_role == hci::Role::CENTRAL) { pimpl_->handle_to_le_connection_map_[handle]->InitiateDisconnect( - hci::DisconnectReason::REMOTE_USER_TERMINATED_CONNECTION); + hci::DisconnectReason::REMOTE_USER_TERMINATED_CONNECTION); log::info("Disconnected ACL after connection canceled"); - BTM_LogHistory(kBtmLogTag, ToLegacyAddressWithType(address_with_type), - "Connection canceled", "Le"); + BTM_LogHistory(kBtmLogTag, ToLegacyAddressWithType(address_with_type), "Connection canceled", + "Le"); return; } - pimpl_->handle_to_le_connection_map_[handle] - ->ReadRemoteControllerInformation(); + pimpl_->handle_to_le_connection_map_[handle]->ReadRemoteControllerInformation(); - tBLE_BD_ADDR legacy_address_with_type = - ToLegacyAddressWithType(address_with_type); + tBLE_BD_ADDR legacy_address_with_type = ToLegacyAddressWithType(address_with_type); - TRY_POSTING_ON_MAIN(acl_interface_.connection.le.on_connected, - legacy_address_with_type, handle, - ToLegacyRole(connection_role), conn_interval, - conn_latency, conn_timeout, local_rpa, peer_rpa, - peer_addr_type, can_read_discoverable_characteristics); + TRY_POSTING_ON_MAIN(acl_interface_.connection.le.on_connected, legacy_address_with_type, handle, + ToLegacyRole(connection_role), conn_interval, conn_latency, conn_timeout, + local_rpa, peer_rpa, peer_addr_type, can_read_discoverable_characteristics); - log::debug("Connection successful le remote:{} handle:{} initiator:{}", - address_with_type, handle, + log::debug("Connection successful le remote:{} handle:{} initiator:{}", address_with_type, handle, (locally_initiated) ? "local" : "remote"); - BTM_LogHistory(kBtmLogTag, ToLegacyAddressWithType(address_with_type), - "Connection successful", "Le"); + BTM_LogHistory(kBtmLogTag, ToLegacyAddressWithType(address_with_type), "Connection successful", + "Le"); } void shim::legacy::Acl::OnLeConnectFail(hci::AddressWithType address_with_type, hci::ErrorCode reason) { - tBLE_BD_ADDR legacy_address_with_type = - ToLegacyAddressWithType(address_with_type); + tBLE_BD_ADDR legacy_address_with_type = ToLegacyAddressWithType(address_with_type); uint16_t handle = 0; /* TODO Unneeded */ bool enhanced = true; /* TODO logging metrics only */ tHCI_STATUS status = ToLegacyHciErrorCode(reason); - TRY_POSTING_ON_MAIN(acl_interface_.connection.le.on_failed, - legacy_address_with_type, handle, enhanced, status); + TRY_POSTING_ON_MAIN(acl_interface_.connection.le.on_failed, legacy_address_with_type, handle, + enhanced, status); pimpl_->shadow_acceptlist_.Remove(address_with_type); log::warn("Connection failed le remote:{}", address_with_type); - BTM_LogHistory( - kBtmLogTag, ToLegacyAddressWithType(address_with_type), - "Connection failed", - base::StringPrintf("le reason:%s", hci::ErrorCodeText(reason).c_str())); + BTM_LogHistory(kBtmLogTag, ToLegacyAddressWithType(address_with_type), "Connection failed", + base::StringPrintf("le reason:%s", hci::ErrorCodeText(reason).c_str())); } void shim::legacy::Acl::DisconnectClassic(uint16_t handle, tHCI_STATUS reason, std::string comment) { - handler_->CallOn(pimpl_.get(), &Acl::impl::disconnect_classic, handle, reason, - comment); + handler_->CallOn(pimpl_.get(), &Acl::impl::disconnect_classic, handle, reason, comment); } -void shim::legacy::Acl::DisconnectLe(uint16_t handle, tHCI_STATUS reason, - std::string comment) { - handler_->CallOn(pimpl_.get(), &Acl::impl::disconnect_le, handle, reason, - comment); +void shim::legacy::Acl::DisconnectLe(uint16_t handle, tHCI_STATUS reason, std::string comment) { + handler_->CallOn(pimpl_.get(), &Acl::impl::disconnect_le, handle, reason, comment); } -void shim::legacy::Acl::UpdateConnectionParameters( - uint16_t handle, uint16_t conn_int_min, uint16_t conn_int_max, - uint16_t conn_latency, uint16_t conn_timeout, uint16_t min_ce_len, - uint16_t max_ce_len) { - handler_->CallOn(pimpl_.get(), &Acl::impl::update_connection_parameters, - handle, conn_int_min, conn_int_max, conn_latency, - conn_timeout, min_ce_len, max_ce_len); +void shim::legacy::Acl::UpdateConnectionParameters(uint16_t handle, uint16_t conn_int_min, + uint16_t conn_int_max, uint16_t conn_latency, + uint16_t conn_timeout, uint16_t min_ce_len, + uint16_t max_ce_len) { + handler_->CallOn(pimpl_.get(), &Acl::impl::update_connection_parameters, handle, conn_int_min, + conn_int_max, conn_latency, conn_timeout, min_ce_len, max_ce_len); } -void shim::legacy::Acl::LeSetDefaultSubrate(uint16_t subrate_min, - uint16_t subrate_max, - uint16_t max_latency, - uint16_t cont_num, +void shim::legacy::Acl::LeSetDefaultSubrate(uint16_t subrate_min, uint16_t subrate_max, + uint16_t max_latency, uint16_t cont_num, uint16_t sup_tout) { - handler_->CallOn(pimpl_.get(), &Acl::impl::LeSetDefaultSubrate, subrate_min, - subrate_max, max_latency, cont_num, sup_tout); + handler_->CallOn(pimpl_.get(), &Acl::impl::LeSetDefaultSubrate, subrate_min, subrate_max, + max_latency, cont_num, sup_tout); } -void shim::legacy::Acl::LeSubrateRequest(uint16_t hci_handle, - uint16_t subrate_min, - uint16_t subrate_max, - uint16_t max_latency, +void shim::legacy::Acl::LeSubrateRequest(uint16_t hci_handle, uint16_t subrate_min, + uint16_t subrate_max, uint16_t max_latency, uint16_t cont_num, uint16_t sup_tout) { - handler_->CallOn(pimpl_.get(), &Acl::impl::LeSubrateRequest, hci_handle, - subrate_min, subrate_max, max_latency, cont_num, sup_tout); + handler_->CallOn(pimpl_.get(), &Acl::impl::LeSubrateRequest, hci_handle, subrate_min, subrate_max, + max_latency, cont_num, sup_tout); } -void shim::legacy::Acl::DumpConnectionHistory(int fd) const { - pimpl_->DumpConnectionHistory(fd); -} +void shim::legacy::Acl::DumpConnectionHistory(int fd) const { pimpl_->DumpConnectionHistory(fd); } void shim::legacy::Acl::DisconnectAllForSuspend() { if (CheckForOrphanedAclConnections()) { @@ -1876,8 +1677,7 @@ void shim::legacy::Acl::Shutdown() { shutdown_promise = std::promise(); shutdown_future = shutdown_promise.get_future(); - handler_->CallOn(pimpl_.get(), &Acl::impl::ShutdownLeConnections, - std::move(shutdown_promise)); + handler_->CallOn(pimpl_.get(), &Acl::impl::ShutdownLeConnections, std::move(shutdown_promise)); shutdown_future.wait(); log::warn("Flushed open ACL connections"); } else { @@ -1909,18 +1709,15 @@ void shim::legacy::Acl::ClearFilterAcceptList() { handler_->CallOn(pimpl_.get(), &Acl::impl::clear_acceptlist); } -void shim::legacy::Acl::AddToAddressResolution( - const hci::AddressWithType& address_with_type, - const std::array& peer_irk, - const std::array& local_irk) { - handler_->CallOn(pimpl_.get(), &Acl::impl::AddToAddressResolution, - address_with_type, peer_irk, local_irk); +void shim::legacy::Acl::AddToAddressResolution(const hci::AddressWithType& address_with_type, + const std::array& peer_irk, + const std::array& local_irk) { + handler_->CallOn(pimpl_.get(), &Acl::impl::AddToAddressResolution, address_with_type, peer_irk, + local_irk); } -void shim::legacy::Acl::RemoveFromAddressResolution( - const hci::AddressWithType& address_with_type) { - handler_->CallOn(pimpl_.get(), &Acl::impl::RemoveFromAddressResolution, - address_with_type); +void shim::legacy::Acl::RemoveFromAddressResolution(const hci::AddressWithType& address_with_type) { + handler_->CallOn(pimpl_.get(), &Acl::impl::RemoveFromAddressResolution, address_with_type); } void shim::legacy::Acl::ClearAddressResolution() { diff --git a/system/main/shim/acl.h b/system/main/shim/acl.h index d00b34e8f7d..5934af034bc 100644 --- a/system/main/shim/acl.h +++ b/system/main/shim/acl.h @@ -37,9 +37,9 @@ namespace legacy { class Acl : public hci::acl_manager::ConnectionCallbacks, public hci::acl_manager::LeConnectionCallbacks, public LinkConnectionInterface { - public: - Acl(os::Handler* handler, const acl_interface_t& acl_interface, - uint8_t max_acceptlist_size, uint8_t max_address_resolution_size); +public: + Acl(os::Handler* handler, const acl_interface_t& acl_interface, uint8_t max_acceptlist_size, + uint8_t max_address_resolution_size); Acl(const Acl&) = delete; Acl& operator=(const Acl&) = delete; @@ -47,61 +47,46 @@ class Acl : public hci::acl_manager::ConnectionCallbacks, ~Acl(); // hci::acl_manager::ConnectionCallbacks - void OnConnectSuccess( - std::unique_ptr) override; + void OnConnectSuccess(std::unique_ptr) override; void OnConnectRequest(hci::Address, hci::ClassOfDevice) override; - void OnConnectFail(hci::Address, hci::ErrorCode reason, - bool locally_initiated) override; + void OnConnectFail(hci::Address, hci::ErrorCode reason, bool locally_initiated) override; void OnClassicLinkDisconnected(uint16_t handle, hci::ErrorCode reason); // hci::acl_manager::LeConnectionCallbacks - void OnLeConnectSuccess( - hci::AddressWithType, - std::unique_ptr) override; + void OnLeConnectSuccess(hci::AddressWithType, + std::unique_ptr) override; void OnLeConnectFail(hci::AddressWithType, hci::ErrorCode reason) override; void OnLeLinkDisconnected(uint16_t handle, hci::ErrorCode reason); - bluetooth::hci::AddressWithType GetConnectionLocalAddress(uint16_t handle, - bool ota_address); - bluetooth::hci::AddressWithType GetConnectionPeerAddress(uint16_t handle, - bool ota_address); - std::optional GetAdvertisingSetConnectedTo( - const RawAddress& remote_bda); + bluetooth::hci::AddressWithType GetConnectionLocalAddress(uint16_t handle, bool ota_address); + bluetooth::hci::AddressWithType GetConnectionPeerAddress(uint16_t handle, bool ota_address); + std::optional GetAdvertisingSetConnectedTo(const RawAddress& remote_bda); // LinkConnectionInterface void CreateClassicConnection(const hci::Address& address) override; void CancelClassicConnection(const hci::Address& address) override; - void AcceptLeConnectionFrom(const hci::AddressWithType& address_with_type, - bool is_direct, + void AcceptLeConnectionFrom(const hci::AddressWithType& address_with_type, bool is_direct, std::promise promise) override; - void IgnoreLeConnectionFrom( - const hci::AddressWithType& address_with_type) override; - void DisconnectClassic(uint16_t handle, tHCI_REASON reason, - std::string comment) override; - void DisconnectLe(uint16_t handle, tHCI_REASON reason, - std::string comment) override; - void UpdateConnectionParameters(uint16_t handle, uint16_t conn_int_min, - uint16_t conn_int_max, uint16_t conn_latency, - uint16_t conn_timeout, uint16_t min_ce_len, + void IgnoreLeConnectionFrom(const hci::AddressWithType& address_with_type) override; + void DisconnectClassic(uint16_t handle, tHCI_REASON reason, std::string comment) override; + void DisconnectLe(uint16_t handle, tHCI_REASON reason, std::string comment) override; + void UpdateConnectionParameters(uint16_t handle, uint16_t conn_int_min, uint16_t conn_int_max, + uint16_t conn_latency, uint16_t conn_timeout, uint16_t min_ce_len, uint16_t max_ce_len) override; // Address Resolution List void AddToAddressResolution(const hci::AddressWithType& address_with_type, const std::array& peer_irk, const std::array& local_irk); - void RemoveFromAddressResolution( - const hci::AddressWithType& address_with_type); + void RemoveFromAddressResolution(const hci::AddressWithType& address_with_type); void ClearAddressResolution(); - void LeSetDefaultSubrate(uint16_t subrate_min, uint16_t subrate_max, - uint16_t max_latency, uint16_t cont_num, - uint16_t sup_tout); - void LeSubrateRequest(uint16_t hci_handle, uint16_t subrate_min, - uint16_t subrate_max, uint16_t max_latency, - uint16_t cont_num, uint16_t sup_tout); + void LeSetDefaultSubrate(uint16_t subrate_min, uint16_t subrate_max, uint16_t max_latency, + uint16_t cont_num, uint16_t sup_tout); + void LeSubrateRequest(uint16_t hci_handle, uint16_t subrate_min, uint16_t subrate_max, + uint16_t max_latency, uint16_t cont_num, uint16_t sup_tout); - void WriteData(uint16_t hci_handle, - std::unique_ptr packet); + void WriteData(uint16_t hci_handle, std::unique_ptr packet); void Flush(uint16_t hci_handle); @@ -115,13 +100,12 @@ class Acl : public hci::acl_manager::ConnectionCallbacks, void DisconnectAllForSuspend(); void SetSystemSuspendState(bool suspended); - protected: +protected: void on_incoming_acl_credits(uint16_t handle, uint16_t credits); - void write_data_sync(uint16_t hci_handle, - std::unique_ptr packet); + void write_data_sync(uint16_t hci_handle, std::unique_ptr packet); void flush(uint16_t hci_handle); - private: +private: os::Handler* handler_; const acl_interface_t acl_interface_; diff --git a/system/main/shim/acl_api.cc b/system/main/shim/acl_api.cc index 929f3ab97de..78e95c8b9d4 100644 --- a/system/main/shim/acl_api.cc +++ b/system/main/shim/acl_api.cc @@ -44,74 +44,63 @@ "bluetooth.core.gap.le.privacy.own_address_type.enabled" #endif -void bluetooth::shim::ACL_CreateClassicConnection( - const RawAddress& raw_address) { +void bluetooth::shim::ACL_CreateClassicConnection(const RawAddress& raw_address) { auto address = ToGdAddress(raw_address); Stack::GetInstance()->GetAcl()->CreateClassicConnection(address); } -void bluetooth::shim::ACL_CancelClassicConnection( - const RawAddress& raw_address) { +void bluetooth::shim::ACL_CancelClassicConnection(const RawAddress& raw_address) { auto address = ToGdAddress(raw_address); Stack::GetInstance()->GetAcl()->CancelClassicConnection(address); } -bool bluetooth::shim::ACL_AcceptLeConnectionFrom( - const tBLE_BD_ADDR& legacy_address_with_type, bool is_direct) { +bool bluetooth::shim::ACL_AcceptLeConnectionFrom(const tBLE_BD_ADDR& legacy_address_with_type, + bool is_direct) { std::promise promise; auto future = promise.get_future(); Stack::GetInstance()->GetAcl()->AcceptLeConnectionFrom( - ToAddressWithTypeFromLegacy(legacy_address_with_type), is_direct, - std::move(promise)); + ToAddressWithTypeFromLegacy(legacy_address_with_type), is_direct, std::move(promise)); return future.get(); } -void bluetooth::shim::ACL_IgnoreLeConnectionFrom( - const tBLE_BD_ADDR& legacy_address_with_type) { +void bluetooth::shim::ACL_IgnoreLeConnectionFrom(const tBLE_BD_ADDR& legacy_address_with_type) { Stack::GetInstance()->GetAcl()->IgnoreLeConnectionFrom( - ToAddressWithTypeFromLegacy(legacy_address_with_type)); + ToAddressWithTypeFromLegacy(legacy_address_with_type)); } void bluetooth::shim::ACL_WriteData(uint16_t handle, BT_HDR* p_buf) { - std::unique_ptr packet = MakeUniquePacket( - p_buf->data + p_buf->offset + HCI_DATA_PREAMBLE_SIZE, - p_buf->len - HCI_DATA_PREAMBLE_SIZE, IsPacketFlushable(p_buf)); + std::unique_ptr packet = + MakeUniquePacket(p_buf->data + p_buf->offset + HCI_DATA_PREAMBLE_SIZE, + p_buf->len - HCI_DATA_PREAMBLE_SIZE, IsPacketFlushable(p_buf)); Stack::GetInstance()->GetAcl()->WriteData(handle, std::move(packet)); osi_free(p_buf); } -void bluetooth::shim::ACL_Flush(uint16_t handle) { - Stack::GetInstance()->GetAcl()->Flush(handle); -} +void bluetooth::shim::ACL_Flush(uint16_t handle) { Stack::GetInstance()->GetAcl()->Flush(handle); } void bluetooth::shim::ACL_SendConnectionParameterUpdateRequest( - uint16_t handle, uint16_t conn_int_min, uint16_t conn_int_max, - uint16_t conn_latency, uint16_t conn_timeout, uint16_t min_ce_len, - uint16_t max_ce_len) { + uint16_t handle, uint16_t conn_int_min, uint16_t conn_int_max, uint16_t conn_latency, + uint16_t conn_timeout, uint16_t min_ce_len, uint16_t max_ce_len) { Stack::GetInstance()->GetAcl()->UpdateConnectionParameters( - handle, conn_int_min, conn_int_max, conn_latency, conn_timeout, - min_ce_len, max_ce_len); + handle, conn_int_min, conn_int_max, conn_latency, conn_timeout, min_ce_len, max_ce_len); } void bluetooth::shim::ACL_ConfigureLePrivacy(bool is_le_privacy_enabled) { hci::LeAddressManager::AddressPolicy address_policy = - is_le_privacy_enabled - ? hci::LeAddressManager::AddressPolicy::USE_RESOLVABLE_ADDRESS - : hci::LeAddressManager::AddressPolicy::USE_PUBLIC_ADDRESS; + is_le_privacy_enabled ? hci::LeAddressManager::AddressPolicy::USE_RESOLVABLE_ADDRESS + : hci::LeAddressManager::AddressPolicy::USE_PUBLIC_ADDRESS; /* This is a Floss only flag. Android determines address policy according to * privacy mode, hence it is not necessary to enable resolvable address with * another sysprop */ - if (com::android::bluetooth::flags:: - floss_separate_host_privacy_and_llprivacy()) { + if (com::android::bluetooth::flags::floss_separate_host_privacy_and_llprivacy()) { address_policy = hci::LeAddressManager::AddressPolicy::USE_PUBLIC_ADDRESS; - if (osi_property_get_bool(PROPERTY_BLE_PRIVACY_OWN_ADDRESS_ENABLED, - is_le_privacy_enabled)) - address_policy = - hci::LeAddressManager::AddressPolicy::USE_RESOLVABLE_ADDRESS; + if (osi_property_get_bool(PROPERTY_BLE_PRIVACY_OWN_ADDRESS_ENABLED, is_le_privacy_enabled)) { + address_policy = hci::LeAddressManager::AddressPolicy::USE_RESOLVABLE_ADDRESS; + } } - hci::AddressWithType empty_address_with_type( - hci::Address{}, hci::AddressType::RANDOM_DEVICE_ADDRESS); + hci::AddressWithType empty_address_with_type(hci::Address{}, + hci::AddressType::RANDOM_DEVICE_ADDRESS); /* Default to 7 minutes minimum, 15 minutes maximum for random address refreshing; * device can override. */ @@ -121,72 +110,58 @@ void bluetooth::shim::ACL_ConfigureLePrivacy(bool is_le_privacy_enabled) { android::sysprop::bluetooth::Ble::random_address_rotation_interval_max().value_or(15)); Stack::GetInstance() - ->GetStackManager() - ->GetInstance() - ->SetPrivacyPolicyForInitiatorAddress( - address_policy, empty_address_with_type, minimum_rotation_time, - maximum_rotation_time); + ->GetStackManager() + ->GetInstance() + ->SetPrivacyPolicyForInitiatorAddress(address_policy, empty_address_with_type, + minimum_rotation_time, maximum_rotation_time); } -void bluetooth::shim::ACL_Disconnect(uint16_t handle, bool is_classic, - tHCI_STATUS reason, std::string comment) { - (is_classic) - ? Stack::GetInstance()->GetAcl()->DisconnectClassic(handle, reason, - comment) - : Stack::GetInstance()->GetAcl()->DisconnectLe(handle, reason, comment); +void bluetooth::shim::ACL_Disconnect(uint16_t handle, bool is_classic, tHCI_STATUS reason, + std::string comment) { + (is_classic) ? Stack::GetInstance()->GetAcl()->DisconnectClassic(handle, reason, comment) + : Stack::GetInstance()->GetAcl()->DisconnectLe(handle, reason, comment); } -void bluetooth::shim::ACL_Shutdown() { - Stack::GetInstance()->GetAcl()->Shutdown(); -} +void bluetooth::shim::ACL_Shutdown() { Stack::GetInstance()->GetAcl()->Shutdown(); } void bluetooth::shim::ACL_IgnoreAllLeConnections() { return Stack::GetInstance()->GetAcl()->ClearFilterAcceptList(); } -void bluetooth::shim::ACL_ReadConnectionAddress(uint16_t handle, - RawAddress& conn_addr, - tBLE_ADDR_TYPE* p_addr_type, - bool ota_address) { +void bluetooth::shim::ACL_ReadConnectionAddress(uint16_t handle, RawAddress& conn_addr, + tBLE_ADDR_TYPE* p_addr_type, bool ota_address) { auto local_address = - Stack::GetInstance()->GetAcl()->GetConnectionLocalAddress(handle, - ota_address); + Stack::GetInstance()->GetAcl()->GetConnectionLocalAddress(handle, ota_address); conn_addr = ToRawAddress(local_address.GetAddress()); *p_addr_type = static_cast(local_address.GetAddressType()); } -void bluetooth::shim::ACL_ReadPeerConnectionAddress(uint16_t handle, - RawAddress& conn_addr, - tBLE_ADDR_TYPE* p_addr_type, - bool ota_address) { +void bluetooth::shim::ACL_ReadPeerConnectionAddress(uint16_t handle, RawAddress& conn_addr, + tBLE_ADDR_TYPE* p_addr_type, bool ota_address) { auto remote_ota_address = - Stack::GetInstance()->GetAcl()->GetConnectionPeerAddress(handle, - ota_address); + Stack::GetInstance()->GetAcl()->GetConnectionPeerAddress(handle, ota_address); conn_addr = ToRawAddress(remote_ota_address.GetAddress()); - *p_addr_type = - static_cast(remote_ota_address.GetAddressType()); + *p_addr_type = static_cast(remote_ota_address.GetAddressType()); } -std::optional bluetooth::shim::ACL_GetAdvertisingSetConnectedTo( - const RawAddress& addr) { +std::optional bluetooth::shim::ACL_GetAdvertisingSetConnectedTo(const RawAddress& addr) { return Stack::GetInstance()->GetAcl()->GetAdvertisingSetConnectedTo(addr); } -void bluetooth::shim::ACL_AddToAddressResolution( - const tBLE_BD_ADDR& legacy_address_with_type, const Octet16& peer_irk, - const Octet16& local_irk) { +void bluetooth::shim::ACL_AddToAddressResolution(const tBLE_BD_ADDR& legacy_address_with_type, + const Octet16& peer_irk, + const Octet16& local_irk) { Stack::GetInstance()->GetAcl()->AddToAddressResolution( - ToAddressWithType(legacy_address_with_type.bda, - legacy_address_with_type.type), - peer_irk, local_irk); + ToAddressWithType(legacy_address_with_type.bda, legacy_address_with_type.type), peer_irk, + local_irk); } void bluetooth::shim::ACL_RemoveFromAddressResolution( - const tBLE_BD_ADDR& legacy_address_with_type) { - Stack::GetInstance()->GetAcl()->RemoveFromAddressResolution(ToAddressWithType( - legacy_address_with_type.bda, legacy_address_with_type.type)); + const tBLE_BD_ADDR& legacy_address_with_type) { + Stack::GetInstance()->GetAcl()->RemoveFromAddressResolution( + ToAddressWithType(legacy_address_with_type.bda, legacy_address_with_type.type)); } void bluetooth::shim::ACL_ClearAddressResolution() { @@ -196,81 +171,73 @@ void bluetooth::shim::ACL_ClearAddressResolution() { void bluetooth::shim::ACL_ClearFilterAcceptList() { Stack::GetInstance()->GetAcl()->ClearFilterAcceptList(); } -void bluetooth::shim::ACL_LeSetDefaultSubrate(uint16_t subrate_min, - uint16_t subrate_max, - uint16_t max_latency, - uint16_t cont_num, +void bluetooth::shim::ACL_LeSetDefaultSubrate(uint16_t subrate_min, uint16_t subrate_max, + uint16_t max_latency, uint16_t cont_num, uint16_t sup_tout) { - Stack::GetInstance()->GetAcl()->LeSetDefaultSubrate( - subrate_min, subrate_max, max_latency, cont_num, sup_tout); + Stack::GetInstance()->GetAcl()->LeSetDefaultSubrate(subrate_min, subrate_max, max_latency, + cont_num, sup_tout); } -void bluetooth::shim::ACL_LeSubrateRequest( - uint16_t hci_handle, uint16_t subrate_min, uint16_t subrate_max, - uint16_t max_latency, uint16_t cont_num, uint16_t sup_tout) { - Stack::GetInstance()->GetAcl()->LeSubrateRequest( - hci_handle, subrate_min, subrate_max, max_latency, cont_num, sup_tout); +void bluetooth::shim::ACL_LeSubrateRequest(uint16_t hci_handle, uint16_t subrate_min, + uint16_t subrate_max, uint16_t max_latency, + uint16_t cont_num, uint16_t sup_tout) { + Stack::GetInstance()->GetAcl()->LeSubrateRequest(hci_handle, subrate_min, subrate_max, + max_latency, cont_num, sup_tout); } -void bluetooth::shim::ACL_RemoteNameRequest(const RawAddress& addr, - uint8_t page_scan_rep_mode, - uint8_t /* page_scan_mode */, - uint16_t clock_offset) { +void bluetooth::shim::ACL_RemoteNameRequest(const RawAddress& addr, uint8_t page_scan_rep_mode, + uint8_t /* page_scan_mode */, uint16_t clock_offset) { bluetooth::shim::GetRemoteNameRequest()->StartRemoteNameRequest( - ToGdAddress(addr), - hci::RemoteNameRequestBuilder::Create( - ToGdAddress(addr), hci::PageScanRepetitionMode(page_scan_rep_mode), - clock_offset & (~BTM_CLOCK_OFFSET_VALID), - (clock_offset & BTM_CLOCK_OFFSET_VALID) - ? hci::ClockOffsetValid::VALID - : hci::ClockOffsetValid::INVALID), - GetGdShimHandler()->BindOnce([](hci::ErrorCode status) { - if (status != hci::ErrorCode::SUCCESS) { - do_in_main_thread( - FROM_HERE, - base::BindOnce( - [](hci::ErrorCode status) { - // NOTE: we intentionally don't supply the address, to match - // the legacy behavior. - // Callsites that want the address should use - // StartRemoteNameRequest() directly, rather than going - // through this shim. - btm_process_remote_name(nullptr, nullptr, 0, - static_cast(status)); - btm_sec_rmt_name_request_complete( - nullptr, nullptr, static_cast(status)); + ToGdAddress(addr), + hci::RemoteNameRequestBuilder::Create( + ToGdAddress(addr), hci::PageScanRepetitionMode(page_scan_rep_mode), + clock_offset & (~BTM_CLOCK_OFFSET_VALID), + (clock_offset & BTM_CLOCK_OFFSET_VALID) ? hci::ClockOffsetValid::VALID + : hci::ClockOffsetValid::INVALID), + GetGdShimHandler()->BindOnce([](hci::ErrorCode status) { + if (status != hci::ErrorCode::SUCCESS) { + do_in_main_thread(FROM_HERE, base::BindOnce( + [](hci::ErrorCode status) { + // NOTE: we intentionally don't supply the + // address, to match the legacy behavior. + // Callsites that want the address should use + // StartRemoteNameRequest() directly, rather + // than going through this shim. + btm_process_remote_name( + nullptr, nullptr, 0, + static_cast(status)); + btm_sec_rmt_name_request_complete( + nullptr, nullptr, + static_cast(status)); + }, + status)); + } + }), + GetGdShimHandler()->BindOnce( + [](RawAddress addr, uint64_t features) { + static_assert(sizeof(features) == 8); + do_in_main_thread(FROM_HERE, + base::BindOnce(btm_sec_rmt_host_support_feat_evt, addr, + static_cast(features & 0xff))); + }, + addr), + GetGdShimHandler()->BindOnce( + [](RawAddress addr, hci::ErrorCode status, std::array name) { + do_in_main_thread( + FROM_HERE, + base::BindOnce( + [](RawAddress addr, hci::ErrorCode status, + std::array name) { + btm_process_remote_name(&addr, name.data(), name.size(), + static_cast(status)); + btm_sec_rmt_name_request_complete( + &addr, name.data(), static_cast(status)); + }, + addr, status, name)); }, - status)); - } - }), - GetGdShimHandler()->BindOnce( - [](RawAddress addr, uint64_t features) { - static_assert(sizeof(features) == 8); - do_in_main_thread( - FROM_HERE, - base::BindOnce(btm_sec_rmt_host_support_feat_evt, addr, - static_cast(features & 0xff))); - }, - addr), - GetGdShimHandler()->BindOnce( - [](RawAddress addr, hci::ErrorCode status, - std::array name) { - do_in_main_thread( - FROM_HERE, - base::BindOnce( - [](RawAddress addr, hci::ErrorCode status, - std::array name) { - btm_process_remote_name(&addr, name.data(), name.size(), - static_cast(status)); - btm_sec_rmt_name_request_complete( - &addr, name.data(), static_cast(status)); - }, - addr, status, name)); - }, - addr)); + addr)); } void bluetooth::shim::ACL_CancelRemoteNameRequest(const RawAddress& addr) { - bluetooth::shim::GetRemoteNameRequest()->CancelRemoteNameRequest( - ToGdAddress(addr)); + bluetooth::shim::GetRemoteNameRequest()->CancelRemoteNameRequest(ToGdAddress(addr)); } diff --git a/system/main/shim/acl_api.h b/system/main/shim/acl_api.h index 07ccfe1c69a..7a1a2c3955d 100644 --- a/system/main/shim/acl_api.h +++ b/system/main/shim/acl_api.h @@ -29,48 +29,40 @@ namespace shim { void ACL_CreateClassicConnection(const RawAddress& raw_address); void ACL_CancelClassicConnection(const RawAddress& raw_address); -bool ACL_AcceptLeConnectionFrom(const tBLE_BD_ADDR& legacy_address_with_type, - bool is_direct); +bool ACL_AcceptLeConnectionFrom(const tBLE_BD_ADDR& legacy_address_with_type, bool is_direct); void ACL_IgnoreLeConnectionFrom(const tBLE_BD_ADDR& legacy_address_with_type); -void ACL_Disconnect(uint16_t handle, bool is_classic, tHCI_STATUS reason, - std::string comment); +void ACL_Disconnect(uint16_t handle, bool is_classic, tHCI_STATUS reason, std::string comment); void ACL_WriteData(uint16_t handle, BT_HDR* p_buf); void ACL_Flush(uint16_t handle); void ACL_ConfigureLePrivacy(bool is_le_privacy_enabled); void ACL_Shutdown(); void ACL_IgnoreAllLeConnections(); -void ACL_ReadConnectionAddress(uint16_t handle, RawAddress& conn_addr, - tBLE_ADDR_TYPE* p_addr_type, bool ota_address); +void ACL_ReadConnectionAddress(uint16_t handle, RawAddress& conn_addr, tBLE_ADDR_TYPE* p_addr_type, + bool ota_address); void ACL_ReadPeerConnectionAddress(uint16_t handle, RawAddress& conn_addr, - tBLE_ADDR_TYPE* p_addr_type, - bool ota_address); + tBLE_ADDR_TYPE* p_addr_type, bool ota_address); std::optional ACL_GetAdvertisingSetConnectedTo(const RawAddress& addr); void ACL_AddToAddressResolution(const tBLE_BD_ADDR& legacy_address_with_type, - const Octet16& peer_irk, - const Octet16& local_irk); -void ACL_RemoveFromAddressResolution( - const tBLE_BD_ADDR& legacy_address_with_type); + const Octet16& peer_irk, const Octet16& local_irk); +void ACL_RemoveFromAddressResolution(const tBLE_BD_ADDR& legacy_address_with_type); void ACL_ClearAddressResolution(); void ACL_ClearFilterAcceptList(); -void ACL_LeSetDefaultSubrate(uint16_t subrate_min, uint16_t subrate_max, - uint16_t max_latency, uint16_t cont_num, - uint16_t sup_tout); -void ACL_SendConnectionParameterUpdateRequest( - uint16_t handle, uint16_t conn_int_min, uint16_t conn_int_max, - uint16_t conn_latency, uint16_t conn_timeout, uint16_t min_ce_len, - uint16_t max_ce_len); -void ACL_LeSubrateRequest(uint16_t hci_handle, uint16_t subrate_min, - uint16_t subrate_max, uint16_t max_latency, - uint16_t cont_num, uint16_t sup_tout); +void ACL_LeSetDefaultSubrate(uint16_t subrate_min, uint16_t subrate_max, uint16_t max_latency, + uint16_t cont_num, uint16_t sup_tout); +void ACL_SendConnectionParameterUpdateRequest(uint16_t handle, uint16_t conn_int_min, + uint16_t conn_int_max, uint16_t conn_latency, + uint16_t conn_timeout, uint16_t min_ce_len, + uint16_t max_ce_len); +void ACL_LeSubrateRequest(uint16_t hci_handle, uint16_t subrate_min, uint16_t subrate_max, + uint16_t max_latency, uint16_t cont_num, uint16_t sup_tout); -void ACL_RemoteNameRequest(const RawAddress& bd_addr, - uint8_t page_scan_rep_mode, uint8_t page_scan_mode, - uint16_t clock_offset); +void ACL_RemoteNameRequest(const RawAddress& bd_addr, uint8_t page_scan_rep_mode, + uint8_t page_scan_mode, uint16_t clock_offset); void ACL_CancelRemoteNameRequest(const RawAddress& addr); } // namespace shim diff --git a/system/main/shim/acl_legacy_interface.cc b/system/main/shim/acl_legacy_interface.cc index 7e46ec4b9cb..55f6421f2a8 100644 --- a/system/main/shim/acl_legacy_interface.cc +++ b/system/main/shim/acl_legacy_interface.cc @@ -21,23 +21,17 @@ #include "stack/include/sec_hci_link_interface.h" struct tBTM_ESCO_DATA; -void gatt_notify_phy_updated(tHCI_STATUS status, uint16_t handle, - uint8_t tx_phy, uint8_t rx_phy); -void gatt_notify_subrate_change(uint16_t handle, uint16_t subrate_factor, - uint16_t latency, uint16_t cont_num, - uint16_t timeout, uint8_t status); -void l2cble_process_subrate_change_evt(uint16_t handle, uint8_t status, - uint16_t subrate_factor, - uint16_t peripheral_latency, - uint16_t cont_num, uint16_t timeout); +void gatt_notify_phy_updated(tHCI_STATUS status, uint16_t handle, uint8_t tx_phy, uint8_t rx_phy); +void gatt_notify_subrate_change(uint16_t handle, uint16_t subrate_factor, uint16_t latency, + uint16_t cont_num, uint16_t timeout, uint8_t status); +void l2cble_process_subrate_change_evt(uint16_t handle, uint8_t status, uint16_t subrate_factor, + uint16_t peripheral_latency, uint16_t cont_num, + uint16_t timeout); -static void on_le_subrate_change(uint16_t handle, uint16_t subrate_factor, - uint16_t latency, uint16_t cont_num, - uint16_t timeout, uint8_t status) { - l2cble_process_subrate_change_evt(handle, status, subrate_factor, latency, - cont_num, timeout); - gatt_notify_subrate_change(handle & 0x0FFF, subrate_factor, latency, cont_num, - timeout, status); +static void on_le_subrate_change(uint16_t handle, uint16_t subrate_factor, uint16_t latency, + uint16_t cont_num, uint16_t timeout, uint8_t status) { + l2cble_process_subrate_change_evt(handle, status, subrate_factor, latency, cont_num, timeout); + gatt_notify_subrate_change(handle & 0x0FFF, subrate_factor, latency, cont_num, timeout, status); } namespace bluetooth { @@ -46,56 +40,51 @@ namespace legacy { const acl_interface_t& GetAclInterface() { static acl_interface_t acl_interface{ - .on_send_data_upwards = acl_rcv_acl_data, - .on_packets_completed = acl_packets_completed, + .on_send_data_upwards = acl_rcv_acl_data, + .on_packets_completed = acl_packets_completed, - .connection.classic.on_connected = on_acl_br_edr_connected, - .connection.classic.on_connect_request = btm_connection_request, - .connection.classic.on_failed = on_acl_br_edr_failed, - .connection.classic.on_disconnected = btm_acl_disconnected, + .connection.classic.on_connected = on_acl_br_edr_connected, + .connection.classic.on_connect_request = btm_connection_request, + .connection.classic.on_failed = on_acl_br_edr_failed, + .connection.classic.on_disconnected = btm_acl_disconnected, - .connection.le.on_connected = - acl_ble_enhanced_connection_complete_from_shim, - .connection.le.on_failed = acl_ble_connection_fail, - .connection.le.on_disconnected = btm_acl_disconnected, + .connection.le.on_connected = acl_ble_enhanced_connection_complete_from_shim, + .connection.le.on_failed = acl_ble_connection_fail, + .connection.le.on_disconnected = btm_acl_disconnected, - .link.classic.on_authentication_complete = btm_sec_auth_complete, - .link.classic.on_central_link_key_complete = nullptr, - .link.classic.on_change_connection_link_key_complete = nullptr, - .link.classic.on_encryption_change = nullptr, - .link.classic.on_flow_specification_complete = nullptr, - .link.classic.on_flush_occurred = nullptr, - .link.classic.on_mode_change = btm_pm_on_mode_change, - .link.classic.on_packet_type_changed = nullptr, - .link.classic.on_qos_setup_complete = nullptr, - .link.classic.on_read_afh_channel_map_complete = nullptr, - .link.classic.on_read_automatic_flush_timeout_complete = nullptr, - .link.classic.on_sniff_subrating = btm_pm_on_sniff_subrating, - .link.classic.on_read_clock_complete = nullptr, - .link.classic.on_read_clock_offset_complete = nullptr, - .link.classic.on_read_failed_contact_counter_complete = nullptr, - .link.classic.on_read_link_policy_settings_complete = nullptr, - .link.classic.on_read_link_quality_complete = nullptr, - .link.classic.on_read_link_supervision_timeout_complete = nullptr, - .link.classic.on_read_remote_version_information_complete = - btm_read_remote_version_complete, - .link.classic.on_read_remote_supported_features_complete = - acl_process_supported_features, - .link.classic.on_read_remote_extended_features_complete = - acl_process_extended_features, - .link.classic.on_read_rssi_complete = nullptr, - .link.classic.on_read_transmit_power_level_complete = nullptr, - .link.classic.on_role_change = btm_acl_role_changed, - .link.classic.on_role_discovery_complete = nullptr, + .link.classic.on_authentication_complete = btm_sec_auth_complete, + .link.classic.on_central_link_key_complete = nullptr, + .link.classic.on_change_connection_link_key_complete = nullptr, + .link.classic.on_encryption_change = nullptr, + .link.classic.on_flow_specification_complete = nullptr, + .link.classic.on_flush_occurred = nullptr, + .link.classic.on_mode_change = btm_pm_on_mode_change, + .link.classic.on_packet_type_changed = nullptr, + .link.classic.on_qos_setup_complete = nullptr, + .link.classic.on_read_afh_channel_map_complete = nullptr, + .link.classic.on_read_automatic_flush_timeout_complete = nullptr, + .link.classic.on_sniff_subrating = btm_pm_on_sniff_subrating, + .link.classic.on_read_clock_complete = nullptr, + .link.classic.on_read_clock_offset_complete = nullptr, + .link.classic.on_read_failed_contact_counter_complete = nullptr, + .link.classic.on_read_link_policy_settings_complete = nullptr, + .link.classic.on_read_link_quality_complete = nullptr, + .link.classic.on_read_link_supervision_timeout_complete = nullptr, + .link.classic.on_read_remote_version_information_complete = + btm_read_remote_version_complete, + .link.classic.on_read_remote_supported_features_complete = acl_process_supported_features, + .link.classic.on_read_remote_extended_features_complete = acl_process_extended_features, + .link.classic.on_read_rssi_complete = nullptr, + .link.classic.on_read_transmit_power_level_complete = nullptr, + .link.classic.on_role_change = btm_acl_role_changed, + .link.classic.on_role_discovery_complete = nullptr, - .link.le.on_connection_update = acl_ble_update_event_received, - .link.le.on_parameter_update_request = - acl_ble_update_request_event_received, - .link.le.on_data_length_change = acl_ble_data_length_change_event, - .link.le.on_read_remote_version_information_complete = - btm_read_remote_version_complete, - .link.le.on_phy_update = gatt_notify_phy_updated, - .link.le.on_le_subrate_change = on_le_subrate_change, + .link.le.on_connection_update = acl_ble_update_event_received, + .link.le.on_parameter_update_request = acl_ble_update_request_event_received, + .link.le.on_data_length_change = acl_ble_data_length_change_event, + .link.le.on_read_remote_version_information_complete = btm_read_remote_version_complete, + .link.le.on_phy_update = gatt_notify_phy_updated, + .link.le.on_le_subrate_change = on_le_subrate_change, }; return acl_interface; } diff --git a/system/main/shim/acl_legacy_interface.h b/system/main/shim/acl_legacy_interface.h index 65c006e87ff..6fd2bd46f94 100644 --- a/system/main/shim/acl_legacy_interface.h +++ b/system/main/shim/acl_legacy_interface.h @@ -34,95 +34,73 @@ typedef struct { void (*on_connected)(const RawAddress& bda, uint16_t handle, uint8_t enc_mode, bool locally_initiated); void (*on_connect_request)(const RawAddress& bda, const hci::ClassOfDevice&); - void (*on_failed)(const RawAddress& bda, tHCI_STATUS status, - bool locally_initiated); - void (*on_disconnected)(tHCI_STATUS status, uint16_t handle, - tHCI_STATUS reason); + void (*on_failed)(const RawAddress& bda, tHCI_STATUS status, bool locally_initiated); + void (*on_disconnected)(tHCI_STATUS status, uint16_t handle, tHCI_STATUS reason); } acl_classic_connection_interface_t; typedef struct { - void (*on_connected)(const tBLE_BD_ADDR& address_with_type, uint16_t handle, - tHCI_ROLE role, uint16_t conn_interval, - uint16_t conn_latency, uint16_t conn_timeout, + void (*on_connected)(const tBLE_BD_ADDR& address_with_type, uint16_t handle, tHCI_ROLE role, + uint16_t conn_interval, uint16_t conn_latency, uint16_t conn_timeout, const RawAddress& local_rpa, const RawAddress& peer_rpa, - tBLE_ADDR_TYPE peer_addr_type, - bool can_read_discoverable_characteristics); - void (*on_failed)(const tBLE_BD_ADDR& address_with_type, uint16_t handle, - bool enhanced, tHCI_STATUS status); - void (*on_disconnected)(tHCI_STATUS status, uint16_t handle, - tHCI_STATUS reason); + tBLE_ADDR_TYPE peer_addr_type, bool can_read_discoverable_characteristics); + void (*on_failed)(const tBLE_BD_ADDR& address_with_type, uint16_t handle, bool enhanced, + tHCI_STATUS status); + void (*on_disconnected)(tHCI_STATUS status, uint16_t handle, tHCI_STATUS reason); } acl_le_connection_interface_t; typedef struct { void (*on_authentication_complete)(uint16_t handle, tHCI_STATUS status); void (*on_change_connection_link_key_complete)(); void (*on_encryption_change)(bool enabled); - void (*on_flow_specification_complete)(uint16_t flow_direction, - uint16_t service_type, - uint32_t token_rate, - uint32_t token_bucket_size, - uint32_t peak_bandwidth, - uint32_t access_latency); + void (*on_flow_specification_complete)(uint16_t flow_direction, uint16_t service_type, + uint32_t token_rate, uint32_t token_bucket_size, + uint32_t peak_bandwidth, uint32_t access_latency); void (*on_flush_occurred)(); void (*on_central_link_key_complete)(uint8_t key_flag); - void (*on_mode_change)(tHCI_STATUS status, uint16_t handle, - tHCI_MODE current_mode, uint16_t interval); - void (*on_sniff_subrating)(tHCI_STATUS status, uint16_t handle, - uint16_t maximum_transmit_latency, - uint16_t maximum_receive_latency, - uint16_t minimum_remote_timeout, + void (*on_mode_change)(tHCI_STATUS status, uint16_t handle, tHCI_MODE current_mode, + uint16_t interval); + void (*on_sniff_subrating)(tHCI_STATUS status, uint16_t handle, uint16_t maximum_transmit_latency, + uint16_t maximum_receive_latency, uint16_t minimum_remote_timeout, uint16_t minimum_local_timeout); void (*on_packet_type_changed)(uint16_t packet_type); - void (*on_qos_setup_complete)(uint16_t service_type, uint32_t token_rate, - uint32_t peak_bandwidth, uint32_t latency, - uint32_t delay_variation); - void (*on_read_afh_channel_map_complete)(uint8_t afh_mode, - uint8_t afh_channel_map[]); + void (*on_qos_setup_complete)(uint16_t service_type, uint32_t token_rate, uint32_t peak_bandwidth, + uint32_t latency, uint32_t delay_variation); + void (*on_read_afh_channel_map_complete)(uint8_t afh_mode, uint8_t afh_channel_map[]); void (*on_read_automatic_flush_timeout_complete)(uint16_t flush_timeout); void (*on_read_clock_complete)(uint32_t clock, uint16_t accuracy); void (*on_read_clock_offset_complete)(uint16_t clock_offset); - void (*on_read_failed_contact_counter_complete)( - uint16_t failed_contact_counter); + void (*on_read_failed_contact_counter_complete)(uint16_t failed_contact_counter); void (*on_read_link_policy_settings_complete)(uint16_t link_policy_settings); void (*on_read_link_quality_complete)(uint8_t link_quality); - void (*on_read_link_supervision_timeout_complete)( - uint16_t link_supervision_timeout); - void (*on_read_remote_supported_features_complete)(uint16_t handle, - uint64_t features); - void (*on_read_remote_extended_features_complete)(uint16_t handle, - uint8_t current_page_number, - uint8_t max_page_number, - uint64_t features); - void (*on_read_remote_version_information_complete)( - tHCI_STATUS status, uint16_t handle, uint8_t lmp_version, - uint16_t manufacturer_name, uint16_t sub_version); + void (*on_read_link_supervision_timeout_complete)(uint16_t link_supervision_timeout); + void (*on_read_remote_supported_features_complete)(uint16_t handle, uint64_t features); + void (*on_read_remote_extended_features_complete)(uint16_t handle, uint8_t current_page_number, + uint8_t max_page_number, uint64_t features); + void (*on_read_remote_version_information_complete)(tHCI_STATUS status, uint16_t handle, + uint8_t lmp_version, + uint16_t manufacturer_name, + uint16_t sub_version); void (*on_read_rssi_complete)(uint8_t rssi); void (*on_read_transmit_power_level_complete)(uint8_t transmit_power_level); - void (*on_role_change)(tHCI_STATUS status, const RawAddress& bd_addr, - tHCI_ROLE new_role); + void (*on_role_change)(tHCI_STATUS status, const RawAddress& bd_addr, tHCI_ROLE new_role); void (*on_role_discovery_complete)(tHCI_ROLE current_role); } acl_classic_link_interface_t; typedef struct { - void (*on_connection_update)(tHCI_STATUS status, uint16_t handle, - uint16_t connection_interval, - uint16_t connection_latency, - uint16_t supervision_timeout); - void (*on_parameter_update_request)(uint16_t handle, uint16_t interval_min, - uint16_t interval_max, uint16_t latency, - uint16_t supervision_timeout); - void (*on_data_length_change)(uint16_t handle, uint16_t max_tx_octets, - uint16_t max_tx_time, uint16_t max_rx_octets, - uint16_t max_rx_time); - void (*on_read_remote_version_information_complete)( - tHCI_STATUS status, uint16_t handle, uint8_t lmp_version, - uint16_t manufacturer_name, uint16_t sub_version); - void (*on_phy_update)(tHCI_STATUS status, uint16_t handle, uint8_t tx_phy, - uint8_t rx_phy); + void (*on_connection_update)(tHCI_STATUS status, uint16_t handle, uint16_t connection_interval, + uint16_t connection_latency, uint16_t supervision_timeout); + void (*on_parameter_update_request)(uint16_t handle, uint16_t interval_min, uint16_t interval_max, + uint16_t latency, uint16_t supervision_timeout); + void (*on_data_length_change)(uint16_t handle, uint16_t max_tx_octets, uint16_t max_tx_time, + uint16_t max_rx_octets, uint16_t max_rx_time); + void (*on_read_remote_version_information_complete)(tHCI_STATUS status, uint16_t handle, + uint8_t lmp_version, + uint16_t manufacturer_name, + uint16_t sub_version); + void (*on_phy_update)(tHCI_STATUS status, uint16_t handle, uint8_t tx_phy, uint8_t rx_phy); - void (*on_le_subrate_change)(uint16_t handle, uint16_t subrate_factor, - uint16_t latency, uint16_t cont_num, - uint16_t timeout, uint8_t status); + void (*on_le_subrate_change)(uint16_t handle, uint16_t subrate_factor, uint16_t latency, + uint16_t cont_num, uint16_t timeout, uint8_t status); } acl_le_link_interface_t; typedef struct { diff --git a/system/main/shim/ble_scanner_interface_impl.h b/system/main/shim/ble_scanner_interface_impl.h index faa4c2d5bc1..3310381eb7d 100644 --- a/system/main/shim/ble_scanner_interface_impl.h +++ b/system/main/shim/ble_scanner_interface_impl.h @@ -36,13 +36,11 @@ extern ::ScanningCallbacks* default_scanning_callback; #if TARGET_FLOSS class MsftCallbacks { - public: +public: using MsftAdvMonitorAddCallback = - base::Callback; - using MsftAdvMonitorRemoveCallback = - base::Callback; - using MsftAdvMonitorEnableCallback = - base::Callback; + base::Callback; + using MsftAdvMonitorRemoveCallback = base::Callback; + using MsftAdvMonitorEnableCallback = base::Callback; MsftAdvMonitorAddCallback Add; MsftAdvMonitorRemoveCallback Remove; @@ -52,8 +50,8 @@ class MsftCallbacks { class BleScannerInterfaceImpl : public ::BleScannerInterface, public bluetooth::hci::ScanningCallback { - public: - ~BleScannerInterfaceImpl() override{}; +public: + ~BleScannerInterfaceImpl() override {} void Init(); @@ -61,77 +59,65 @@ class BleScannerInterfaceImpl : public ::BleScannerInterface, void RegisterScanner(const bluetooth::Uuid& uuid, RegisterCallback) override; void Unregister(int scanner_id) override; void Scan(bool start) override; - void ScanFilterParamSetup( - uint8_t client_if, uint8_t action, uint8_t filter_index, - std::unique_ptr filt_param, - FilterParamSetupCallback cb) override; + void ScanFilterParamSetup(uint8_t client_if, uint8_t action, uint8_t filter_index, + std::unique_ptr filt_param, + FilterParamSetupCallback cb) override; void ScanFilterAdd(int filter_index, std::vector filters, FilterConfigCallback cb) override; void ScanFilterClear(int filter_index, FilterConfigCallback cb) override; void ScanFilterEnable(bool enable, EnableCallback cb) override; #if TARGET_FLOSS bool IsMsftSupported() override; - void MsftAdvMonitorAdd(MsftAdvMonitor monitor, - MsftAdvMonitorAddCallback cb) override; - void MsftAdvMonitorRemove(uint8_t monitor_handle, - MsftAdvMonitorRemoveCallback cb) override; - void MsftAdvMonitorEnable(bool enable, - MsftAdvMonitorEnableCallback cb) override; + void MsftAdvMonitorAdd(MsftAdvMonitor monitor, MsftAdvMonitorAddCallback cb) override; + void MsftAdvMonitorRemove(uint8_t monitor_handle, MsftAdvMonitorRemoveCallback cb) override; + void MsftAdvMonitorEnable(bool enable, MsftAdvMonitorEnableCallback cb) override; #endif - void SetScanParameters(int scanner_id, uint8_t scan_type, int scan_interval, - int scan_window, int scan_phy, Callback cb) override; - void BatchscanConfigStorage(int client_if, int batch_scan_full_max, - int batch_scan_trunc_max, - int batch_scan_notify_threshold, - Callback cb) override; - void BatchscanEnable(int scan_mode, int scan_interval, int scan_window, - int addr_type, int discard_rule, Callback cb) override; + void SetScanParameters(int scanner_id, uint8_t scan_type, int scan_interval, int scan_window, + int scan_phy, Callback cb) override; + void BatchscanConfigStorage(int client_if, int batch_scan_full_max, int batch_scan_trunc_max, + int batch_scan_notify_threshold, Callback cb) override; + void BatchscanEnable(int scan_mode, int scan_interval, int scan_window, int addr_type, + int discard_rule, Callback cb) override; void BatchscanDisable(Callback cb) override; void BatchscanReadReports(int client_if, int scan_mode) override; - void StartSync(uint8_t sid, RawAddress address, uint16_t skip, - uint16_t timeout, int reg_id) override; + void StartSync(uint8_t sid, RawAddress address, uint16_t skip, uint16_t timeout, + int reg_id) override; void StopSync(uint16_t handle) override; void CancelCreateSync(uint8_t sid, RawAddress address) override; - void TransferSync(RawAddress address, uint16_t service_data, - uint16_t sync_handle, int pa_source) override; - void TransferSetInfo(RawAddress address, uint16_t service_data, - uint8_t adv_handle, int pa_source) override; - void SyncTxParameters(RawAddress addr, uint8_t mode, uint16_t skip, - uint16_t timeout, int reg_id) override; + void TransferSync(RawAddress address, uint16_t service_data, uint16_t sync_handle, + int pa_source) override; + void TransferSetInfo(RawAddress address, uint16_t service_data, uint8_t adv_handle, + int pa_source) override; + void SyncTxParameters(RawAddress addr, uint8_t mode, uint16_t skip, uint16_t timeout, + int reg_id) override; // bluetooth::hci::ScanningCallback void RegisterCallbacks(ScanningCallbacks* callbacks); void OnScannerRegistered(const bluetooth::hci::Uuid app_uuid, - bluetooth::hci::ScannerId scanner_id, - ScanningStatus status) override; + bluetooth::hci::ScannerId scanner_id, ScanningStatus status) override; void OnSetScannerParameterComplete(bluetooth::hci::ScannerId scanner_id, ScanningStatus status) override; - void OnScanResult(uint16_t event_type, uint8_t address_type, - bluetooth::hci::Address address, uint8_t primary_phy, - uint8_t secondary_phy, uint8_t advertising_sid, - int8_t tx_power, int8_t rssi, - uint16_t periodic_advertising_interval, + void OnScanResult(uint16_t event_type, uint8_t address_type, bluetooth::hci::Address address, + uint8_t primary_phy, uint8_t secondary_phy, uint8_t advertising_sid, + int8_t tx_power, int8_t rssi, uint16_t periodic_advertising_interval, std::vector advertising_data) override; - void OnTrackAdvFoundLost(bluetooth::hci::AdvertisingFilterOnFoundOnLostInfo - on_found_on_lost_info) override; - void OnBatchScanReports(int client_if, int status, int report_format, - int num_records, std::vector data) override; + void OnTrackAdvFoundLost( + bluetooth::hci::AdvertisingFilterOnFoundOnLostInfo on_found_on_lost_info) override; + void OnBatchScanReports(int client_if, int status, int report_format, int num_records, + std::vector data) override; void OnBatchScanThresholdCrossed(int client_if) override; void OnTimeout() override; void OnFilterEnable(bluetooth::hci::Enable enable, uint8_t status) override; - void OnFilterParamSetup(uint8_t available_spaces, - bluetooth::hci::ApcfAction action, + void OnFilterParamSetup(uint8_t available_spaces, bluetooth::hci::ApcfAction action, uint8_t status) override; - void OnFilterConfigCallback(bluetooth::hci::ApcfFilterType filter_type, - uint8_t available_spaces, - bluetooth::hci::ApcfAction action, - uint8_t status) override; + void OnFilterConfigCallback(bluetooth::hci::ApcfFilterType filter_type, uint8_t available_spaces, + bluetooth::hci::ApcfAction action, uint8_t status) override; void OnPeriodicSyncStarted(int reg_id, uint8_t status, uint16_t sync_handle, uint8_t advertising_sid, - bluetooth::hci::AddressWithType address_with_type, - uint8_t phy, uint16_t interval) override; - void OnPeriodicSyncReport(uint16_t sync_handle, int8_t tx_power, int8_t rssi, - uint8_t status, std::vector data) override; + bluetooth::hci::AddressWithType address_with_type, uint8_t phy, + uint16_t interval) override; + void OnPeriodicSyncReport(uint16_t sync_handle, int8_t tx_power, int8_t rssi, uint8_t status, + std::vector data) override; void OnPeriodicSyncLost(uint16_t sync_handle) override; void OnPeriodicSyncTransferred(int pa_source, uint8_t status, bluetooth::hci::Address address) override; @@ -139,28 +125,26 @@ class BleScannerInterfaceImpl : public ::BleScannerInterface, ::ScanningCallbacks* scanning_callbacks_ = default_scanning_callback; #if TARGET_FLOSS - void OnMsftAdvMonitorAdd(uint8_t monitor_handle, - bluetooth::hci::ErrorCode status); + void OnMsftAdvMonitorAdd(uint8_t monitor_handle, bluetooth::hci::ErrorCode status); void OnMsftAdvMonitorRemove(bluetooth::hci::ErrorCode status); void OnMsftAdvMonitorEnable(bool enable, bluetooth::hci::ErrorCode status); MsftCallbacks msft_callbacks_; #endif - private: - bool parse_filter_command( - bluetooth::hci::AdvertisingPacketContentFilterCommand& - advertising_packet_content_filter_command, - ApcfCommand apcf_command); +private: + bool parse_filter_command(bluetooth::hci::AdvertisingPacketContentFilterCommand& + advertising_packet_content_filter_command, + ApcfCommand apcf_command); void handle_remote_properties(RawAddress bd_addr, tBLE_ADDR_TYPE addr_type, std::vector advertising_data); class AddressCache { - public: + public: void init(void); void add(const RawAddress& p_bda); bool find(const RawAddress& p_bda); - private: + private: // all access to this variable should be done on the jni thread std::set remote_bdaddr_cache_; std::queue remote_bdaddr_cache_ordered_; diff --git a/system/main/shim/btm_api.cc b/system/main/shim/btm_api.cc index 01fc8cda599..4719b6a5891 100644 --- a/system/main/shim/btm_api.cc +++ b/system/main/shim/btm_api.cc @@ -49,28 +49,28 @@ tBTM_STATUS bluetooth::shim::BTM_ClearFilterAcceptList() { tBTM_STATUS bluetooth::shim::BTM_DisconnectAllAcls() { Stack::GetInstance()->GetAcl()->DisconnectAllForSuspend(); -// Stack::GetInstance()->GetAcl()->Shutdown(); + // Stack::GetInstance()->GetAcl()->Shutdown(); return BTM_SUCCESS; } tBTM_STATUS bluetooth::shim::BTM_SetEventFilterConnectionSetupAllDevices() { // Autoplumbed GetController()->SetEventFilterConnectionSetupAllDevices( - bluetooth::hci::AutoAcceptFlag::AUTO_ACCEPT_ON_ROLE_SWITCH_ENABLED); + bluetooth::hci::AutoAcceptFlag::AUTO_ACCEPT_ON_ROLE_SWITCH_ENABLED); return BTM_SUCCESS; } tBTM_STATUS bluetooth::shim::BTM_AllowWakeByHid( - std::vector classic_hid_devices, - std::vector> le_hid_devices) { + std::vector classic_hid_devices, + std::vector> le_hid_devices) { // First set ACL to suspended state. Stack::GetInstance()->GetAcl()->SetSystemSuspendState(/*suspended=*/true); // Allow classic HID wake. auto controller = GetController(); for (auto device : classic_hid_devices) { - controller->SetEventFilterConnectionSetupAddress( - bluetooth::ToGdAddress(device), hci::AutoAcceptFlag::AUTO_ACCEPT_OFF); + controller->SetEventFilterConnectionSetupAddress(bluetooth::ToGdAddress(device), + hci::AutoAcceptFlag::AUTO_ACCEPT_OFF); } // Allow BLE HID @@ -79,9 +79,9 @@ tBTM_STATUS bluetooth::shim::BTM_AllowWakeByHid( auto accept_future = accept_promise.get_future(); tBLE_BD_ADDR bdadr = BTM_Sec_GetAddressWithType(hid_address.first); - Stack::GetInstance()->GetAcl()->AcceptLeConnectionFrom( - ToAddressWithType(bdadr.bda, bdadr.type), - /*is_direct=*/false, std::move(accept_promise)); + Stack::GetInstance()->GetAcl()->AcceptLeConnectionFrom(ToAddressWithType(bdadr.bda, bdadr.type), + /*is_direct=*/false, + std::move(accept_promise)); accept_future.wait(); } @@ -90,7 +90,7 @@ tBTM_STATUS bluetooth::shim::BTM_AllowWakeByHid( } tBTM_STATUS bluetooth::shim::BTM_RestoreFilterAcceptList( - std::vector> le_devices) { + std::vector> le_devices) { // First, mark ACL as no longer suspended. Stack::GetInstance()->GetAcl()->SetSystemSuspendState(/*suspended=*/false); @@ -101,9 +101,9 @@ tBTM_STATUS bluetooth::shim::BTM_RestoreFilterAcceptList( auto accept_future = accept_promise.get_future(); tBLE_BD_ADDR bdadr = BTM_Sec_GetAddressWithType(address_pair.first); - Stack::GetInstance()->GetAcl()->AcceptLeConnectionFrom( - ToAddressWithType(bdadr.bda, bdadr.type), - /*is_direct=*/false, std::move(accept_promise)); + Stack::GetInstance()->GetAcl()->AcceptLeConnectionFrom(ToAddressWithType(bdadr.bda, bdadr.type), + /*is_direct=*/false, + std::move(accept_promise)); accept_future.wait(); } @@ -111,12 +111,9 @@ tBTM_STATUS bluetooth::shim::BTM_RestoreFilterAcceptList( return BTM_SUCCESS; } -tBTM_STATUS bluetooth::shim::BTM_SetDefaultEventMaskExcept(uint64_t mask, - uint64_t le_mask) { - uint64_t applied_mask = - bluetooth::hci::Controller::kDefaultEventMask & ~(mask); - uint64_t applied_le_mask = - bluetooth::hci::Controller::kDefaultLeEventMask & ~(le_mask); +tBTM_STATUS bluetooth::shim::BTM_SetDefaultEventMaskExcept(uint64_t mask, uint64_t le_mask) { + uint64_t applied_mask = bluetooth::hci::Controller::kDefaultEventMask & ~(mask); + uint64_t applied_le_mask = bluetooth::hci::Controller::kDefaultLeEventMask & ~(le_mask); GetController()->SetEventMask(applied_mask); GetController()->LeSetEventMask(applied_le_mask); return BTM_SUCCESS; diff --git a/system/main/shim/btm_api.h b/system/main/shim/btm_api.h index a6a14bd34b2..dff05ff1b91 100644 --- a/system/main/shim/btm_api.h +++ b/system/main/shim/btm_api.h @@ -94,9 +94,8 @@ tBTM_STATUS BTM_SetEventFilterConnectionSetupAllDevices(void); * Parameters std::vector of RawAddress * *******************************************************************************/ -tBTM_STATUS BTM_AllowWakeByHid( - std::vector classic_hid_devices, - std::vector> le_hid_devices); +tBTM_STATUS BTM_AllowWakeByHid(std::vector classic_hid_devices, + std::vector> le_hid_devices); /******************************************************************************* * @@ -107,8 +106,7 @@ tBTM_STATUS BTM_AllowWakeByHid( * Parameters * *******************************************************************************/ -tBTM_STATUS BTM_RestoreFilterAcceptList( - std::vector> le_devices); +tBTM_STATUS BTM_RestoreFilterAcceptList(std::vector> le_devices); /******************************************************************************* * diff --git a/system/main/shim/config.cc b/system/main/shim/config.cc index 27b57832aed..b392b38bae5 100644 --- a/system/main/shim/config.cc +++ b/system/main/shim/config.cc @@ -36,13 +36,12 @@ bool BtifConfigInterface::HasSection(const std::string& section) { return GetStorage()->HasSection(section); } -bool BtifConfigInterface::HasProperty(const std::string& section, - const std::string& property) { +bool BtifConfigInterface::HasProperty(const std::string& section, const std::string& property) { return GetStorage()->HasProperty(section, property); } -bool BtifConfigInterface::GetInt(const std::string& section, - const std::string& property, int* value) { +bool BtifConfigInterface::GetInt(const std::string& section, const std::string& property, + int* value) { log::assert_that(value != nullptr, "assert failed: value != nullptr"); auto ret = GetStorage()->GetInt(section, property); if (ret) { @@ -51,14 +50,13 @@ bool BtifConfigInterface::GetInt(const std::string& section, return ret.has_value(); } -bool BtifConfigInterface::SetInt(const std::string& section, - const std::string& property, int value) { +bool BtifConfigInterface::SetInt(const std::string& section, const std::string& property, + int value) { GetStorage()->SetInt(section, property, value); return true; } -bool BtifConfigInterface::GetUint64(const std::string& section, - const std::string& property, +bool BtifConfigInterface::GetUint64(const std::string& section, const std::string& property, uint64_t* value) { log::assert_that(value != nullptr, "assert failed: value != nullptr"); auto ret = GetStorage()->GetUint64(section, property); @@ -68,19 +66,16 @@ bool BtifConfigInterface::GetUint64(const std::string& section, return ret.has_value(); } -bool BtifConfigInterface::SetUint64(const std::string& section, - const std::string& property, +bool BtifConfigInterface::SetUint64(const std::string& section, const std::string& property, uint64_t value) { GetStorage()->SetUint64(section, property, value); return true; } -bool BtifConfigInterface::GetStr(const std::string& section, - const std::string& property, char* value, - int* size_bytes) { +bool BtifConfigInterface::GetStr(const std::string& section, const std::string& property, + char* value, int* size_bytes) { log::assert_that(value != nullptr, "assert failed: value != nullptr"); - log::assert_that(size_bytes != nullptr, - "assert failed: size_bytes != nullptr"); + log::assert_that(size_bytes != nullptr, "assert failed: size_bytes != nullptr"); if (*size_bytes == 0) { return HasProperty(section, property); } @@ -96,22 +91,20 @@ bool BtifConfigInterface::GetStr(const std::string& section, return true; } -std::optional BtifConfigInterface::GetStr( - const std::string& section, const std::string& property) { +std::optional BtifConfigInterface::GetStr(const std::string& section, + const std::string& property) { return GetStorage()->GetProperty(section, property); } -bool BtifConfigInterface::SetStr(const std::string& section, - const std::string& property, +bool BtifConfigInterface::SetStr(const std::string& section, const std::string& property, const std::string& value) { GetStorage()->SetProperty(section, property, value); return true; } // TODO: implement encrypted read -bool BtifConfigInterface::GetBin(const std::string& section, - const std::string& property, uint8_t* value, - size_t* length) { +bool BtifConfigInterface::GetBin(const std::string& section, const std::string& property, + uint8_t* value, size_t* length) { log::assert_that(value != nullptr, "assert failed: value != nullptr"); log::assert_that(length != nullptr, "assert failed: length != nullptr"); auto value_vec = GetStorage()->GetBin(section, property); @@ -122,24 +115,21 @@ bool BtifConfigInterface::GetBin(const std::string& section, std::memcpy(value, value_vec->data(), *length); return true; } -size_t BtifConfigInterface::GetBinLength(const std::string& section, - const std::string& property) { +size_t BtifConfigInterface::GetBinLength(const std::string& section, const std::string& property) { auto value_vec = GetStorage()->GetBin(section, property); if (!value_vec) { return 0; } return value_vec->size(); } -bool BtifConfigInterface::SetBin(const std::string& section, - const std::string& property, +bool BtifConfigInterface::SetBin(const std::string& section, const std::string& property, const uint8_t* value, size_t length) { log::assert_that(value != nullptr, "assert failed: value != nullptr"); std::vector value_vec(value, value + length); GetStorage()->SetBin(section, property, value_vec); return true; } -bool BtifConfigInterface::RemoveProperty(const std::string& section, - const std::string& property) { +bool BtifConfigInterface::RemoveProperty(const std::string& section, const std::string& property) { return GetStorage()->RemoveProperty(section, property); } diff --git a/system/main/shim/config.h b/system/main/shim/config.h index 7b12cf75c35..d8bb44e1005 100644 --- a/system/main/shim/config.h +++ b/system/main/shim/config.h @@ -25,33 +25,24 @@ namespace bluetooth { namespace shim { class BtifConfigInterface { - public: +public: ~BtifConfigInterface() = default; static bool HasSection(const std::string& section); - static bool HasProperty(const std::string& section, - const std::string& property); - static bool GetInt(const std::string& section, const std::string& key, - int* value); - static bool SetInt(const std::string& section, const std::string& key, - int value); - static bool GetUint64(const std::string& section, const std::string& key, - uint64_t* value); - static bool SetUint64(const std::string& section, const std::string& key, - uint64_t value); - static bool GetStr(const std::string& section, const std::string& key, - char* value, int* size_bytes); - static std::optional GetStr(const std::string& section, - const std::string& key); - static bool SetStr(const std::string& section, const std::string& key, - const std::string& value); - static bool GetBin(const std::string& section, const std::string& key, - uint8_t* value, size_t* length); - static size_t GetBinLength(const std::string& section, - const std::string& key); - static bool SetBin(const std::string& section, const std::string& key, - const uint8_t* value, size_t length); - static bool RemoveProperty(const std::string& section, - const std::string& key); + static bool HasProperty(const std::string& section, const std::string& property); + static bool GetInt(const std::string& section, const std::string& key, int* value); + static bool SetInt(const std::string& section, const std::string& key, int value); + static bool GetUint64(const std::string& section, const std::string& key, uint64_t* value); + static bool SetUint64(const std::string& section, const std::string& key, uint64_t value); + static bool GetStr(const std::string& section, const std::string& key, char* value, + int* size_bytes); + static std::optional GetStr(const std::string& section, const std::string& key); + static bool SetStr(const std::string& section, const std::string& key, const std::string& value); + static bool GetBin(const std::string& section, const std::string& key, uint8_t* value, + size_t* length); + static size_t GetBinLength(const std::string& section, const std::string& key); + static bool SetBin(const std::string& section, const std::string& key, const uint8_t* value, + size_t length); + static bool RemoveProperty(const std::string& section, const std::string& key); static void RemoveSection(const std::string& section); static std::vector GetPersistentDevices(); static void ConvertEncryptOrDecryptKeyIfNeeded(); diff --git a/system/main/shim/distance_measurement_manager.cc b/system/main/shim/distance_measurement_manager.cc index c93a054ee7c..42c0b6b687f 100644 --- a/system/main/shim/distance_measurement_manager.cc +++ b/system/main/shim/distance_measurement_manager.cc @@ -25,190 +25,159 @@ using bluetooth::hci::DistanceMeasurementErrorCode; using bluetooth::hci::DistanceMeasurementMethod; -class DistanceMeasurementInterfaceImpl - : public DistanceMeasurementInterface, - public bluetooth::hci::DistanceMeasurementCallbacks, - public bluetooth::ras::RasServerCallbacks, - public bluetooth::ras::RasClientCallbacks { - public: - ~DistanceMeasurementInterfaceImpl() override{}; +class DistanceMeasurementInterfaceImpl : public DistanceMeasurementInterface, + public bluetooth::hci::DistanceMeasurementCallbacks, + public bluetooth::ras::RasServerCallbacks, + public bluetooth::ras::RasClientCallbacks { +public: + ~DistanceMeasurementInterfaceImpl() override {} void Init() { // Register callback - bluetooth::shim::GetDistanceMeasurementManager() - ->RegisterDistanceMeasurementCallbacks(this); + bluetooth::shim::GetDistanceMeasurementManager()->RegisterDistanceMeasurementCallbacks(this); bluetooth::ras::GetRasServer()->RegisterCallbacks(this); bluetooth::ras::GetRasClient()->RegisterCallbacks(this); } - void RegisterDistanceMeasurementCallbacks( - ::DistanceMeasurementCallbacks* callbacks) { + void RegisterDistanceMeasurementCallbacks(::DistanceMeasurementCallbacks* callbacks) { distance_measurement_callbacks_ = callbacks; } - void StartDistanceMeasurement(RawAddress raw_address, uint16_t interval, - uint8_t method) { + void StartDistanceMeasurement(RawAddress raw_address, uint16_t interval, uint8_t method) { bluetooth::shim::GetDistanceMeasurementManager()->StartDistanceMeasurement( - bluetooth::ToGdAddress(raw_address), interval, - static_cast(method)); + bluetooth::ToGdAddress(raw_address), interval, + static_cast(method)); bluetooth::ras::GetRasClient()->Connect(raw_address); } void StopDistanceMeasurement(RawAddress raw_address, uint8_t method) { bluetooth::shim::GetDistanceMeasurementManager()->StopDistanceMeasurement( - bluetooth::ToGdAddress(raw_address), - static_cast(method)); + bluetooth::ToGdAddress(raw_address), static_cast(method)); } // Callbacks of bluetooth::hci::DistanceMeasurementCallbacks void OnDistanceMeasurementStarted(bluetooth::hci::Address address, DistanceMeasurementMethod method) override { - do_in_jni_thread(base::BindOnce( - &::DistanceMeasurementCallbacks::OnDistanceMeasurementStarted, - base::Unretained(distance_measurement_callbacks_), - bluetooth::ToRawAddress(address), static_cast(method))); + do_in_jni_thread(base::BindOnce(&::DistanceMeasurementCallbacks::OnDistanceMeasurementStarted, + base::Unretained(distance_measurement_callbacks_), + bluetooth::ToRawAddress(address), + static_cast(method))); } - void OnDistanceMeasurementStartFail( - bluetooth::hci::Address address, DistanceMeasurementErrorCode reason, - DistanceMeasurementMethod method) override { - do_in_jni_thread(base::BindOnce( - &::DistanceMeasurementCallbacks::OnDistanceMeasurementStartFail, - base::Unretained(distance_measurement_callbacks_), - bluetooth::ToRawAddress(address), static_cast(reason), - static_cast(method))); + void OnDistanceMeasurementStartFail(bluetooth::hci::Address address, + DistanceMeasurementErrorCode reason, + DistanceMeasurementMethod method) override { + do_in_jni_thread(base::BindOnce(&::DistanceMeasurementCallbacks::OnDistanceMeasurementStartFail, + base::Unretained(distance_measurement_callbacks_), + bluetooth::ToRawAddress(address), static_cast(reason), + static_cast(method))); } void OnDistanceMeasurementStopped(bluetooth::hci::Address address, DistanceMeasurementErrorCode reason, DistanceMeasurementMethod method) override { - do_in_jni_thread(base::BindOnce( - &::DistanceMeasurementCallbacks::OnDistanceMeasurementStopped, - base::Unretained(distance_measurement_callbacks_), - bluetooth::ToRawAddress(address), static_cast(reason), - static_cast(method))); + do_in_jni_thread(base::BindOnce(&::DistanceMeasurementCallbacks::OnDistanceMeasurementStopped, + base::Unretained(distance_measurement_callbacks_), + bluetooth::ToRawAddress(address), static_cast(reason), + static_cast(method))); } - void OnDistanceMeasurementResult(bluetooth::hci::Address address, - uint32_t centimeter, + void OnDistanceMeasurementResult(bluetooth::hci::Address address, uint32_t centimeter, uint32_t error_centimeter, int azimuth_angle, int error_azimuth_angle, int altitude_angle, int error_altitude_angle, DistanceMeasurementMethod method) override { - do_in_jni_thread(base::BindOnce( - &::DistanceMeasurementCallbacks::OnDistanceMeasurementResult, - base::Unretained(distance_measurement_callbacks_), - bluetooth::ToRawAddress(address), centimeter, error_centimeter, - azimuth_angle, error_azimuth_angle, altitude_angle, - error_altitude_angle, static_cast(method))); + do_in_jni_thread(base::BindOnce(&::DistanceMeasurementCallbacks::OnDistanceMeasurementResult, + base::Unretained(distance_measurement_callbacks_), + bluetooth::ToRawAddress(address), centimeter, error_centimeter, + azimuth_angle, error_azimuth_angle, altitude_angle, + error_altitude_angle, static_cast(method))); } - void OnRasFragmentReady(bluetooth::hci::Address address, - uint16_t procedure_counter, bool is_last, + void OnRasFragmentReady(bluetooth::hci::Address address, uint16_t procedure_counter, bool is_last, std::vector raw_data) { - bluetooth::ras::GetRasServer()->PushProcedureData( - bluetooth::ToRawAddress(address), procedure_counter, is_last, raw_data); + bluetooth::ras::GetRasServer()->PushProcedureData(bluetooth::ToRawAddress(address), + procedure_counter, is_last, raw_data); } - void OnVendorSpecificCharacteristics( - std::vector - vendor_specific_characteristics) { - std::vector - ras_vendor_specific_characteristics; + void OnVendorSpecificCharacteristics(std::vector + vendor_specific_characteristics) { + std::vector ras_vendor_specific_characteristics; for (auto& characteristic : vendor_specific_characteristics) { - bluetooth::ras::VendorSpecificCharacteristic - vendor_specific_characteristic; + bluetooth::ras::VendorSpecificCharacteristic vendor_specific_characteristic; vendor_specific_characteristic.characteristicUuid_ = - bluetooth::Uuid::From128BitBE(characteristic.characteristicUuid_); + bluetooth::Uuid::From128BitBE(characteristic.characteristicUuid_); vendor_specific_characteristic.value_ = characteristic.value_; - ras_vendor_specific_characteristics.emplace_back( - vendor_specific_characteristic); + ras_vendor_specific_characteristics.emplace_back(vendor_specific_characteristic); } bluetooth::ras::GetRasServer()->SetVendorSpecificCharacteristic( - ras_vendor_specific_characteristics); + ras_vendor_specific_characteristics); } - void OnVendorSpecificReply( - bluetooth::hci::Address address, - std::vector - vendor_specific_characteristics) { - std::vector - ras_vendor_specific_characteristics; + void OnVendorSpecificReply(bluetooth::hci::Address address, + std::vector + vendor_specific_characteristics) { + std::vector ras_vendor_specific_characteristics; for (auto& characteristic : vendor_specific_characteristics) { - bluetooth::ras::VendorSpecificCharacteristic - vendor_specific_characteristic; + bluetooth::ras::VendorSpecificCharacteristic vendor_specific_characteristic; vendor_specific_characteristic.characteristicUuid_ = - bluetooth::Uuid::From128BitBE(characteristic.characteristicUuid_); + bluetooth::Uuid::From128BitBE(characteristic.characteristicUuid_); vendor_specific_characteristic.value_ = characteristic.value_; - ras_vendor_specific_characteristics.emplace_back( - vendor_specific_characteristic); + ras_vendor_specific_characteristics.emplace_back(vendor_specific_characteristic); } - bluetooth::ras::GetRasClient()->SendVendorSpecificReply( - bluetooth::ToRawAddress(address), ras_vendor_specific_characteristics); + bluetooth::ras::GetRasClient()->SendVendorSpecificReply(bluetooth::ToRawAddress(address), + ras_vendor_specific_characteristics); } - void OnHandleVendorSpecificReplyComplete(bluetooth::hci::Address address, - bool success) { + void OnHandleVendorSpecificReplyComplete(bluetooth::hci::Address address, bool success) { bluetooth::ras::GetRasServer()->HandleVendorSpecificReplyComplete( - bluetooth::ToRawAddress(address), success); - }; + bluetooth::ToRawAddress(address), success); + } // Callbacks of bluetooth::ras::RasServerCallbacks void OnVendorSpecificReply( - const RawAddress& address, - const std::vector& - vendor_specific_reply) { - std::vector - hal_vendor_specific_characteristics; + const RawAddress& address, + const std::vector& vendor_specific_reply) { + std::vector hal_vendor_specific_characteristics; for (auto& characteristic : vendor_specific_reply) { - bluetooth::hal::VendorSpecificCharacteristic - vendor_specific_characteristic; + bluetooth::hal::VendorSpecificCharacteristic vendor_specific_characteristic; vendor_specific_characteristic.characteristicUuid_ = - characteristic.characteristicUuid_.To128BitBE(); + characteristic.characteristicUuid_.To128BitBE(); vendor_specific_characteristic.value_ = characteristic.reply_value_; - hal_vendor_specific_characteristics.emplace_back( - vendor_specific_characteristic); + hal_vendor_specific_characteristics.emplace_back(vendor_specific_characteristic); } bluetooth::shim::GetDistanceMeasurementManager()->HandleVendorSpecificReply( - bluetooth::ToGdAddress(address), hal_vendor_specific_characteristics); + bluetooth::ToGdAddress(address), hal_vendor_specific_characteristics); } // Callbacks of bluetooth::ras::RasClientCallbacks - void OnConnected( - const RawAddress& address, uint16_t att_handle, - const std::vector& - vendor_specific_characteristics) { - std::vector - hal_vendor_specific_characteristics; + void OnConnected(const RawAddress& address, uint16_t att_handle, + const std::vector& + vendor_specific_characteristics) { + std::vector hal_vendor_specific_characteristics; for (auto& characteristic : vendor_specific_characteristics) { - bluetooth::hal::VendorSpecificCharacteristic - vendor_specific_characteristic; + bluetooth::hal::VendorSpecificCharacteristic vendor_specific_characteristic; vendor_specific_characteristic.characteristicUuid_ = - characteristic.characteristicUuid_.To128BitBE(); + characteristic.characteristicUuid_.To128BitBE(); vendor_specific_characteristic.value_ = characteristic.value_; - hal_vendor_specific_characteristics.emplace_back( - vendor_specific_characteristic); + hal_vendor_specific_characteristics.emplace_back(vendor_specific_characteristic); } bluetooth::shim::GetDistanceMeasurementManager()->HandleRasConnectedEvent( - bluetooth::ToGdAddress(address), att_handle, - hal_vendor_specific_characteristics); + bluetooth::ToGdAddress(address), att_handle, hal_vendor_specific_characteristics); } - void OnWriteVendorSpecificReplyComplete(const RawAddress& address, - bool success) { - bluetooth::shim::GetDistanceMeasurementManager() - ->HandleVendorSpecificReplyComplete(bluetooth::ToGdAddress(address), - success); + void OnWriteVendorSpecificReplyComplete(const RawAddress& address, bool success) { + bluetooth::shim::GetDistanceMeasurementManager()->HandleVendorSpecificReplyComplete( + bluetooth::ToGdAddress(address), success); } - void OnRemoteData(const RawAddress& address, - const std::vector& data) { + void OnRemoteData(const RawAddress& address, const std::vector& data) { bluetooth::shim::GetDistanceMeasurementManager()->HandleRemoteData( - bluetooth::ToGdAddress(address), data); + bluetooth::ToGdAddress(address), data); } - private: +private: ::DistanceMeasurementCallbacks* distance_measurement_callbacks_; }; @@ -216,14 +185,13 @@ DistanceMeasurementInterfaceImpl* distance_measurement_instance = nullptr; void bluetooth::shim::init_distance_measurement_manager() { static_cast( - bluetooth::shim::get_distance_measurement_instance()) - ->Init(); + bluetooth::shim::get_distance_measurement_instance()) + ->Init(); } -DistanceMeasurementInterface* -bluetooth::shim::get_distance_measurement_instance() { +DistanceMeasurementInterface* bluetooth::shim::get_distance_measurement_instance() { if (distance_measurement_instance == nullptr) { distance_measurement_instance = new DistanceMeasurementInterfaceImpl(); } return distance_measurement_instance; -}; +} diff --git a/system/main/shim/dumpsys.cc b/system/main/shim/dumpsys.cc index 737c599d5aa..6b17fb21412 100644 --- a/system/main/shim/dumpsys.cc +++ b/system/main/shim/dumpsys.cc @@ -30,23 +30,19 @@ namespace { constexpr char kModuleName[] = "shim::legacy::dumpsys"; -static std::unordered_map - dumpsys_functions_; +static std::unordered_map dumpsys_functions_; } // namespace -void bluetooth::shim::RegisterDumpsysFunction(const void* token, - DumpsysFunction func) { +void bluetooth::shim::RegisterDumpsysFunction(const void* token, DumpsysFunction func) { log::assert_that(dumpsys_functions_.find(token) == dumpsys_functions_.end(), - "assert failed: dumpsys_functions_.find(token) == " - "dumpsys_functions_.end()"); + "assert failed: dumpsys_functions_.find(token) == dumpsys_functions_.end()"); dumpsys_functions_.insert({token, func}); } void bluetooth::shim::UnregisterDumpsysFunction(const void* token) { log::assert_that(dumpsys_functions_.find(token) != dumpsys_functions_.end(), - "assert failed: dumpsys_functions_.find(token) != " - "dumpsys_functions_.end()"); + "assert failed: dumpsys_functions_.find(token) != dumpsys_functions_.end()"); dumpsys_functions_.erase(token); } @@ -54,8 +50,7 @@ void bluetooth::shim::Dump(int fd, const char** args) { if (dumpsys_functions_.empty()) { dprintf(fd, "%s No registered dumpsys shim legacy targets\n", kModuleName); } else { - dprintf(fd, "%s Dumping shim legacy targets:%zd\n", kModuleName, - dumpsys_functions_.size()); + dprintf(fd, "%s Dumping shim legacy targets:%zd\n", kModuleName, dumpsys_functions_.size()); for (auto& dumpsys : dumpsys_functions_) { dumpsys.second(fd); } @@ -64,15 +59,13 @@ void bluetooth::shim::Dump(int fd, const char** args) { std::promise promise; std::future future = promise.get_future(); if (bluetooth::shim::Stack::GetInstance()->CallOnModule( - [&promise, fd, args](shim::Dumpsys* mod) { - mod->Dump(fd, args, std::move(promise)); - })) { - log::assert_that( - future.wait_for(std::chrono::seconds(1)) == std::future_status::ready, - "Timed out waiting for dumpsys to complete"); + [&promise, fd, args](shim::Dumpsys* mod) { + mod->Dump(fd, args, std::move(promise)); + })) { + log::assert_that(future.wait_for(std::chrono::seconds(1)) == std::future_status::ready, + "Timed out waiting for dumpsys to complete"); } else { - dprintf(fd, "%s NOTE: gd dumpsys module not loaded or started\n", - kModuleName); + dprintf(fd, "%s NOTE: gd dumpsys module not loaded or started\n", kModuleName); } } else { // !FLAG(dumpsys_acquire_stack_when_executing) bluetooth::shim::Stack::GetInstance()->LockForDumpsys([=]() { @@ -80,8 +73,7 @@ void bluetooth::shim::Dump(int fd, const char** args) { if (bluetooth::shim::is_gd_dumpsys_module_started()) { bluetooth::shim::GetDumpsys()->Dump(fd, args); } else { - dprintf(fd, "%s NOTE: gd dumpsys module not loaded or started\n", - kModuleName); + dprintf(fd, "%s NOTE: gd dumpsys module not loaded or started\n", kModuleName); } } else { dprintf(fd, "%s gd stack is enabled but not started\n", kModuleName); diff --git a/system/main/shim/dumpsys.h b/system/main/shim/dumpsys.h index 84f3ad70bea..854609c7359 100644 --- a/system/main/shim/dumpsys.h +++ b/system/main/shim/dumpsys.h @@ -30,15 +30,13 @@ } while (false) inline double ticks_to_seconds(uint16_t ticks) { - return (static_cast(ticks) * 0.625 * 0.001); + return static_cast(ticks) * 0.625 * 0.001; } -inline double ticks_to_milliseconds(uint16_t ticks) { - return (static_cast(ticks) * 0.625); -} +inline double ticks_to_milliseconds(uint16_t ticks) { return static_cast(ticks) * 0.625; } inline double supervision_timeout_to_seconds(uint16_t timeout) { - return (static_cast(timeout) * 0.01); + return static_cast(timeout) * 0.01; } namespace bluetooth { diff --git a/system/main/shim/entry.cc b/system/main/shim/entry.cc index ce9337c7d0d..d09b570745c 100644 --- a/system/main/shim/entry.cc +++ b/system/main/shim/entry.cc @@ -40,72 +40,50 @@ namespace shim { os::Handler* GetGdShimHandler() { return Stack::GetInstance()->GetHandler(); } hci::LeAdvertisingManager* GetAdvertising() { - return Stack::GetInstance() - ->GetStackManager() - ->GetInstance(); + return Stack::GetInstance()->GetStackManager()->GetInstance(); } hci::ControllerInterface* GetController() { - return Stack::GetInstance() - ->GetStackManager() - ->GetInstance(); + return Stack::GetInstance()->GetStackManager()->GetInstance(); } -Dumpsys* GetDumpsys() { - return Stack::GetInstance()->GetStackManager()->GetInstance(); -} +Dumpsys* GetDumpsys() { return Stack::GetInstance()->GetStackManager()->GetInstance(); } hci::HciInterface* GetHciLayer() { return Stack::GetInstance()->GetStackManager()->GetInstance(); } hci::RemoteNameRequestModule* GetRemoteNameRequest() { - return Stack::GetInstance() - ->GetStackManager() - ->GetInstance(); + return Stack::GetInstance()->GetStackManager()->GetInstance(); } hci::LeScanningManager* GetScanning() { - return Stack::GetInstance() - ->GetStackManager() - ->GetInstance(); + return Stack::GetInstance()->GetStackManager()->GetInstance(); } hci::DistanceMeasurementManager* GetDistanceMeasurementManager() { - return Stack::GetInstance() - ->GetStackManager() - ->GetInstance(); + return Stack::GetInstance()->GetStackManager()->GetInstance(); } hal::SnoopLogger* GetSnoopLogger() { - return Stack::GetInstance() - ->GetStackManager() - ->GetInstance(); + return Stack::GetInstance()->GetStackManager()->GetInstance(); } storage::StorageModule* GetStorage() { - return Stack::GetInstance() - ->GetStackManager() - ->GetInstance(); + return Stack::GetInstance()->GetStackManager()->GetInstance(); } hci::AclManager* GetAclManager() { - return Stack::GetInstance() - ->GetStackManager() - ->GetInstance(); + return Stack::GetInstance()->GetStackManager()->GetInstance(); } metrics::CounterMetrics* GetCounterMetrics() { - return Stack::GetInstance() - ->GetStackManager() - ->GetInstance(); + return Stack::GetInstance()->GetStackManager()->GetInstance(); } #if TARGET_FLOSS hci::MsftExtensionManager* GetMsftExtensionManager() { - return Stack::GetInstance() - ->GetStackManager() - ->GetInstance(); + return Stack::GetInstance()->GetStackManager()->GetInstance(); } #endif diff --git a/system/main/shim/entry.h b/system/main/shim/entry.h index 4d1ef017ff6..ff23bfb1cdd 100644 --- a/system/main/shim/entry.h +++ b/system/main/shim/entry.h @@ -48,7 +48,7 @@ class LeScanningManager; #if TARGET_FLOSS class MsftExtensionManager; #endif -} +} // namespace hci namespace metrics { class CounterMetrics; diff --git a/system/main/shim/hci_layer.cc b/system/main/shim/hci_layer.cc index 3ca8e980b83..ac5ce6c347c 100644 --- a/system/main/shim/hci_layer.cc +++ b/system/main/shim/hci_layer.cc @@ -82,7 +82,7 @@ bool register_event_code(bluetooth::hci::EventCode event_code) { default: return false; } -}; +} static bool register_subevent_code(bluetooth::hci::SubeventCode subevent_code) { switch (subevent_code) { @@ -111,14 +111,12 @@ static bool register_subevent_code(bluetooth::hci::SubeventCode subevent_code) { } // namespace namespace cpp { -bluetooth::common::BidiQueueEnd* hci_iso_queue_end = - nullptr; -static bluetooth::os::EnqueueBuffer* - pending_iso_data = nullptr; +bluetooth::common::BidiQueueEnd* + hci_iso_queue_end = nullptr; +static bluetooth::os::EnqueueBuffer* pending_iso_data = nullptr; -static std::unique_ptr MakeUniquePacket( - const uint8_t* data, size_t len) { +static std::unique_ptr MakeUniquePacket(const uint8_t* data, + size_t len) { bluetooth::packet::RawBuilder builder; std::vector bytes(data, data + len); @@ -128,9 +126,8 @@ static std::unique_ptr MakeUniquePacket( return payload; } -static BT_HDR* WrapPacketAndCopy( - uint16_t event, - bluetooth::hci::PacketView* data) { +static BT_HDR* WrapPacketAndCopy(uint16_t event, + bluetooth::hci::PacketView* data) { size_t packet_size = data->size() + kBtHdrSize; BT_HDR* packet = reinterpret_cast(osi_malloc(packet_size)); packet->offset = 0; @@ -145,24 +142,19 @@ static void event_callback(bluetooth::hci::EventView event_packet_view) { if (!send_data_upwards) { return; } - send_data_upwards.Run(FROM_HERE, WrapPacketAndCopy(MSG_HC_TO_STACK_HCI_EVT, - &event_packet_view)); + send_data_upwards.Run(FROM_HERE, WrapPacketAndCopy(MSG_HC_TO_STACK_HCI_EVT, &event_packet_view)); } -static void subevent_callback( - bluetooth::hci::LeMetaEventView le_meta_event_view) { +static void subevent_callback(bluetooth::hci::LeMetaEventView le_meta_event_view) { if (!send_data_upwards) { return; } - send_data_upwards.Run(FROM_HERE, WrapPacketAndCopy(MSG_HC_TO_STACK_HCI_EVT, - &le_meta_event_view)); + send_data_upwards.Run(FROM_HERE, WrapPacketAndCopy(MSG_HC_TO_STACK_HCI_EVT, &le_meta_event_view)); } -void OnTransmitPacketCommandComplete(command_complete_cb complete_callback, - void* context, +void OnTransmitPacketCommandComplete(command_complete_cb complete_callback, void* context, bluetooth::hci::CommandCompleteView view) { - log::debug("Received cmd complete for {}", - bluetooth::hci::OpCodeText(view.GetCommandOpCode())); + log::debug("Received cmd complete for {}", bluetooth::hci::OpCodeText(view.GetCommandOpCode())); BT_HDR* response = WrapPacketAndCopy(MSG_HC_TO_STACK_HCI_EVT, &view); complete_callback(response, context); } @@ -170,22 +162,19 @@ void OnTransmitPacketCommandComplete(command_complete_cb complete_callback, void OnTransmitPacketStatus(command_status_cb status_callback, void* context, std::unique_ptr command, bluetooth::hci::CommandStatusView view) { - log::debug("Received cmd status {} for {}", - bluetooth::hci::ErrorCodeText(view.GetStatus()), + log::debug("Received cmd status {} for {}", bluetooth::hci::ErrorCodeText(view.GetStatus()), bluetooth::hci::OpCodeText(view.GetCommandOpCode())); uint8_t status = static_cast(view.GetStatus()); status_callback(status, static_cast(command->Release()), context); } -static void transmit_command(const BT_HDR* command, - command_complete_cb complete_callback, +static void transmit_command(const BT_HDR* command, command_complete_cb complete_callback, command_status_cb status_callback, void* context) { log::assert_that(command != nullptr, "assert failed: command != nullptr"); const uint8_t* data = command->data + command->offset; size_t len = command->len; - log::assert_that( - len >= (kCommandOpcodeSize + kCommandLengthSize), - "assert failed: len >= (kCommandOpcodeSize + kCommandLengthSize)"); + log::assert_that(len >= (kCommandOpcodeSize + kCommandLengthSize), + "assert failed: len >= (kCommandOpcodeSize + kCommandLengthSize)"); // little endian command opcode uint16_t command_op_code = (data[1] << 8 | data[0]); @@ -197,22 +186,21 @@ static void transmit_command(const BT_HDR* command, auto op_code = static_cast(command_op_code); auto payload = MakeUniquePacket(data, len); - auto packet = - bluetooth::hci::CommandBuilder::Create(op_code, std::move(payload)); + auto packet = bluetooth::hci::CommandBuilder::Create(op_code, std::move(payload)); log::debug("Sending command {}", bluetooth::hci::OpCodeText(op_code)); if (bluetooth::hci::Checker::IsCommandStatusOpcode(op_code)) { auto command_unique = std::make_unique(command); bluetooth::shim::GetHciLayer()->EnqueueCommand( - std::move(packet), bluetooth::shim::GetGdShimHandler()->BindOnce( - OnTransmitPacketStatus, status_callback, context, - std::move(command_unique))); + std::move(packet), + bluetooth::shim::GetGdShimHandler()->BindOnce(OnTransmitPacketStatus, status_callback, + context, std::move(command_unique))); } else { bluetooth::shim::GetHciLayer()->EnqueueCommand( - std::move(packet), - bluetooth::shim::GetGdShimHandler()->BindOnce( - OnTransmitPacketCommandComplete, complete_callback, context)); + std::move(packet), + bluetooth::shim::GetGdShimHandler()->BindOnce(OnTransmitPacketCommandComplete, + complete_callback, context)); osi_free(const_cast(static_cast(command))); } } @@ -220,36 +208,31 @@ static void transmit_command(const BT_HDR* command, static void transmit_iso_fragment(const uint8_t* stream, size_t length) { uint16_t handle_with_flags; STREAM_TO_UINT16(handle_with_flags, stream); - auto pb_flag = static_cast( - handle_with_flags >> 12 & 0b11); - auto ts_flag = - static_cast(handle_with_flags >> 14); + auto pb_flag = static_cast(handle_with_flags >> 12 & 0b11); + auto ts_flag = static_cast(handle_with_flags >> 14); uint16_t handle = HCID_GET_HANDLE(handle_with_flags); - log::assert_that(handle <= HCI_HANDLE_MAX, - "Require handle <= 0x{:X}, but is 0x{:X}", HCI_HANDLE_MAX, - handle); + log::assert_that(handle <= HCI_HANDLE_MAX, "Require handle <= 0x{:X}, but is 0x{:X}", + HCI_HANDLE_MAX, handle); length -= 2; // skip data total length stream += 2; length -= 2; auto payload = MakeUniquePacket(stream, length); - auto iso_packet = bluetooth::hci::IsoBuilder::Create(handle, pb_flag, ts_flag, - std::move(payload)); + auto iso_packet = + bluetooth::hci::IsoBuilder::Create(handle, pb_flag, ts_flag, std::move(payload)); - pending_iso_data->Enqueue(std::move(iso_packet), - bluetooth::shim::GetGdShimHandler()); + pending_iso_data->Enqueue(std::move(iso_packet), bluetooth::shim::GetGdShimHandler()); } static void register_event(bluetooth::hci::EventCode event_code) { auto handler = bluetooth::shim::GetGdShimHandler(); - bluetooth::shim::GetHciLayer()->RegisterEventHandler( - event_code, handler->Bind(event_callback)); + bluetooth::shim::GetHciLayer()->RegisterEventHandler(event_code, handler->Bind(event_callback)); } static void register_le_event(bluetooth::hci::SubeventCode subevent_code) { auto handler = bluetooth::shim::GetGdShimHandler(); - bluetooth::shim::GetHciLayer()->RegisterLeEventHandler( - subevent_code, handler->Bind(subevent_callback)); + bluetooth::shim::GetHciLayer()->RegisterLeEventHandler(subevent_code, + handler->Bind(subevent_callback)); } static void iso_data_callback() { @@ -271,25 +254,21 @@ static void iso_data_callback() { static void register_for_iso() { hci_iso_queue_end = bluetooth::shim::GetHciLayer()->GetIsoQueueEnd(); - hci_iso_queue_end->RegisterDequeue( - bluetooth::shim::GetGdShimHandler(), - bluetooth::common::Bind(iso_data_callback)); + hci_iso_queue_end->RegisterDequeue(bluetooth::shim::GetGdShimHandler(), + bluetooth::common::Bind(iso_data_callback)); pending_iso_data = - new bluetooth::os::EnqueueBuffer( - hci_iso_queue_end); + new bluetooth::os::EnqueueBuffer(hci_iso_queue_end); // Register ISO for disconnect notifications bluetooth::shim::GetHciLayer()->RegisterForDisconnects( - get_main_thread()->Bind([](uint16_t handle, - bluetooth::hci::ErrorCode error_code) { - auto iso = bluetooth::hci::IsoManager::GetInstance(); - if (iso) { - auto reason = static_cast(error_code); - log::info( - "ISO disconnection from GD, handle: 0x{:02x}, reason: 0x{:02x}", - handle, reason); - iso->HandleDisconnect(handle, reason); - } - })); + get_main_thread()->Bind([](uint16_t handle, bluetooth::hci::ErrorCode error_code) { + auto iso = bluetooth::hci::IsoManager::GetInstance(); + if (iso) { + auto reason = static_cast(error_code); + log::info("ISO disconnection from GD, handle: 0x{:02x}, reason: 0x{:02x}", handle, + reason); + iso->HandleDisconnect(handle, reason); + } + })); } static void on_shutting_down() { @@ -310,13 +289,11 @@ using bluetooth::common::Bind; using bluetooth::common::BindOnce; using bluetooth::common::Unretained; -static void set_data_cb( - base::Callback send_data_cb) { +static void set_data_cb(base::Callback send_data_cb) { send_data_upwards = std::move(send_data_cb); } -static void transmit_command(const BT_HDR* command, - command_complete_cb complete_callback, +static void transmit_command(const BT_HDR* command, command_complete_cb complete_callback, command_status_cb status_callback, void* context) { cpp::transmit_command(command, complete_callback, status_callback, context); } @@ -326,8 +303,7 @@ static void transmit_fragment(BT_HDR* packet, bool send_transmit_finished) { // HCI command packets are freed on a different thread when the matching // event is received. Check packet->event before sending to avoid a race. - bool free_after_transmit = - event != MSG_STACK_TO_HC_HCI_CMD && send_transmit_finished; + bool free_after_transmit = event != MSG_STACK_TO_HC_HCI_CMD && send_transmit_finished; if (event == MSG_STACK_TO_HC_HCI_ISO) { const uint8_t* stream = packet->data + packet->offset; @@ -344,18 +320,16 @@ static void dispatch_reassembled(BT_HDR* packet) { log::assert_that((packet->event & MSG_EVT_MASK) == MSG_HC_TO_STACK_HCI_ISO, "assert failed: (packet->event & MSG_EVT_MASK) == " "MSG_HC_TO_STACK_HCI_ISO"); - log::assert_that(!send_data_upwards.is_null(), - "assert failed: !send_data_upwards.is_null()"); + log::assert_that(!send_data_upwards.is_null(), "assert failed: !send_data_upwards.is_null()"); send_data_upwards.Run(FROM_HERE, packet); } -static const packet_fragmenter_callbacks_t packet_fragmenter_callbacks = { - transmit_fragment, dispatch_reassembled}; +static const packet_fragmenter_callbacks_t packet_fragmenter_callbacks = {transmit_fragment, + dispatch_reassembled}; static void transmit_downward(void* raw_data, uint16_t iso_buffer_size) { - bluetooth::shim::GetGdShimHandler()->Call( - packet_fragmenter->fragment_and_dispatch, static_cast(raw_data), - iso_buffer_size); + bluetooth::shim::GetGdShimHandler()->Call(packet_fragmenter->fragment_and_dispatch, + static_cast(raw_data), iso_buffer_size); } static hci_t interface = {.set_data_cb = set_data_cb, @@ -369,8 +343,7 @@ const hci_t* bluetooth::shim::hci_layer_get_interface() { } void bluetooth::shim::hci_on_reset_complete() { - log::assert_that(!send_data_upwards.is_null(), - "assert failed: !send_data_upwards.is_null()"); + log::assert_that(!send_data_upwards.is_null(), "assert failed: !send_data_upwards.is_null()"); for (uint16_t event_code_raw = 0; event_code_raw < 0x100; event_code_raw++) { auto event_code = static_cast(event_code_raw); @@ -380,10 +353,8 @@ void bluetooth::shim::hci_on_reset_complete() { cpp::register_event(event_code); } - for (uint16_t subevent_code_raw = 0; subevent_code_raw < 0x100; - subevent_code_raw++) { - auto subevent_code = - static_cast(subevent_code_raw); + for (uint16_t subevent_code_raw = 0; subevent_code_raw < 0x100; subevent_code_raw++) { + auto subevent_code = static_cast(subevent_code_raw); if (!register_subevent_code(subevent_code)) { continue; } diff --git a/system/main/shim/helpers.h b/system/main/shim/helpers.h index f3dd5bcbedd..f23d128633e 100644 --- a/system/main/shim/helpers.h +++ b/system/main/shim/helpers.h @@ -57,61 +57,54 @@ inline hci::Address ToGdAddress(const RawAddress& address) { return ret; } -inline hci::AddressWithType ToAddressWithType( - const RawAddress& legacy_address, const tBLE_ADDR_TYPE& legacy_type) { +inline hci::AddressWithType ToAddressWithType(const RawAddress& legacy_address, + const tBLE_ADDR_TYPE& legacy_type) { hci::Address address = ToGdAddress(legacy_address); hci::AddressType type; - if (legacy_type == BLE_ADDR_PUBLIC) + if (legacy_type == BLE_ADDR_PUBLIC) { type = hci::AddressType::PUBLIC_DEVICE_ADDRESS; - else if (legacy_type == BLE_ADDR_RANDOM) + } else if (legacy_type == BLE_ADDR_RANDOM) { type = hci::AddressType::RANDOM_DEVICE_ADDRESS; - else if (legacy_type == BLE_ADDR_PUBLIC_ID) + } else if (legacy_type == BLE_ADDR_PUBLIC_ID) { type = hci::AddressType::PUBLIC_IDENTITY_ADDRESS; - else if (legacy_type == BLE_ADDR_RANDOM_ID) + } else if (legacy_type == BLE_ADDR_RANDOM_ID) { type = hci::AddressType::RANDOM_IDENTITY_ADDRESS; - else { + } else { log::fatal("Bad address type {:02x}", legacy_type); - return hci::AddressWithType{address, - hci::AddressType::PUBLIC_DEVICE_ADDRESS}; + return hci::AddressWithType{address, hci::AddressType::PUBLIC_DEVICE_ADDRESS}; } return hci::AddressWithType{address, type}; } inline hci::AddressWithType ToAddressWithTypeFromLegacy( - const tBLE_BD_ADDR& legacy_address_with_type) { - return ToAddressWithType(legacy_address_with_type.bda, - legacy_address_with_type.type); + const tBLE_BD_ADDR& legacy_address_with_type) { + return ToAddressWithType(legacy_address_with_type.bda, legacy_address_with_type.type); } -inline tBLE_BD_ADDR ToLegacyAddressWithType( - const hci::AddressWithType& address_with_type) { +inline tBLE_BD_ADDR ToLegacyAddressWithType(const hci::AddressWithType& address_with_type) { tBLE_BD_ADDR legacy_address_with_type; legacy_address_with_type.bda = ToRawAddress(address_with_type.GetAddress()); - if (address_with_type.GetAddressType() == - hci::AddressType::PUBLIC_DEVICE_ADDRESS) { + if (address_with_type.GetAddressType() == hci::AddressType::PUBLIC_DEVICE_ADDRESS) { legacy_address_with_type.type = BLE_ADDR_PUBLIC; - } else if (address_with_type.GetAddressType() == - hci::AddressType::RANDOM_DEVICE_ADDRESS) { + } else if (address_with_type.GetAddressType() == hci::AddressType::RANDOM_DEVICE_ADDRESS) { legacy_address_with_type.type = BLE_ADDR_RANDOM; - } else if (address_with_type.GetAddressType() == - hci::AddressType::PUBLIC_IDENTITY_ADDRESS) { + } else if (address_with_type.GetAddressType() == hci::AddressType::PUBLIC_IDENTITY_ADDRESS) { legacy_address_with_type.type = BLE_ADDR_PUBLIC_ID; - } else if (address_with_type.GetAddressType() == - hci::AddressType::RANDOM_IDENTITY_ADDRESS) { + } else if (address_with_type.GetAddressType() == hci::AddressType::RANDOM_IDENTITY_ADDRESS) { legacy_address_with_type.type = BLE_ADDR_RANDOM_ID; } else { - log::fatal("Bad address type {:02x}", - static_cast(address_with_type.GetAddressType())); + log::fatal("Bad address type {:02x}", static_cast(address_with_type.GetAddressType())); legacy_address_with_type.type = BLE_ADDR_PUBLIC; } return legacy_address_with_type; } -inline std::unique_ptr MakeUniquePacket( - const uint8_t* data, size_t len, bool is_flushable) { +inline std::unique_ptr MakeUniquePacket(const uint8_t* data, + size_t len, + bool is_flushable) { bluetooth::packet::RawBuilder builder; std::vector bytes(data, data + len); auto payload = std::make_unique(); @@ -121,22 +114,18 @@ inline std::unique_ptr MakeUniquePacket( } inline BT_HDR* MakeLegacyBtHdrPacket( - std::unique_ptr> - packet, - const std::vector& preamble) { + std::unique_ptr> packet, + const std::vector& preamble) { std::vector packet_vector(packet->begin(), packet->end()); - BT_HDR* buffer = static_cast( - osi_calloc(packet_vector.size() + preamble.size() + sizeof(BT_HDR))); + BT_HDR* buffer = + static_cast(osi_calloc(packet_vector.size() + preamble.size() + sizeof(BT_HDR))); std::copy(preamble.begin(), preamble.end(), buffer->data); - std::copy(packet_vector.begin(), packet_vector.end(), - buffer->data + preamble.size()); + std::copy(packet_vector.begin(), packet_vector.end(), buffer->data + preamble.size()); buffer->len = preamble.size() + packet_vector.size(); return buffer; } -inline tHCI_ROLE ToLegacyRole(hci::Role role) { - return to_hci_role(static_cast(role)); -} +inline tHCI_ROLE ToLegacyRole(hci::Role role) { return to_hci_role(static_cast(role)); } inline hci::Role ToHciRole(const hci_role_t& role) { switch (role) { @@ -186,18 +175,17 @@ inline tHCI_STATUS ToLegacyHciErrorCode(const hci::ErrorCode& reason) { case hci::ErrorCode::CONNECTION_ACCEPT_TIMEOUT: return HCI_ERR_HOST_TIMEOUT; case hci::ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE: - return static_cast( - hci::ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); + return static_cast(hci::ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); case hci::ErrorCode::INVALID_HCI_COMMAND_PARAMETERS: return HCI_ERR_ILLEGAL_PARAMETER_FMT; case hci::ErrorCode::REMOTE_USER_TERMINATED_CONNECTION: return HCI_ERR_PEER_USER; case hci::ErrorCode::REMOTE_DEVICE_TERMINATED_CONNECTION_LOW_RESOURCES: return static_cast( - hci::ErrorCode::REMOTE_DEVICE_TERMINATED_CONNECTION_LOW_RESOURCES); + hci::ErrorCode::REMOTE_DEVICE_TERMINATED_CONNECTION_LOW_RESOURCES); case hci::ErrorCode::REMOTE_DEVICE_TERMINATED_CONNECTION_POWER_OFF: return static_cast( - hci::ErrorCode::REMOTE_DEVICE_TERMINATED_CONNECTION_POWER_OFF); + hci::ErrorCode::REMOTE_DEVICE_TERMINATED_CONNECTION_POWER_OFF); case hci::ErrorCode::CONNECTION_TERMINATED_BY_LOCAL_HOST: return HCI_ERR_CONN_CAUSE_LOCAL_HOST; case hci::ErrorCode::REPEATED_ATTEMPTS: @@ -215,13 +203,11 @@ inline tHCI_STATUS ToLegacyHciErrorCode(const hci::ErrorCode& reason) { case hci::ErrorCode::SCO_AIR_MODE_REJECTED: return static_cast(hci::ErrorCode::SCO_AIR_MODE_REJECTED); case hci::ErrorCode::INVALID_LMP_OR_LL_PARAMETERS: - return static_cast( - hci::ErrorCode::INVALID_LMP_OR_LL_PARAMETERS); + return static_cast(hci::ErrorCode::INVALID_LMP_OR_LL_PARAMETERS); case hci::ErrorCode::UNSPECIFIED_ERROR: return HCI_ERR_UNSPECIFIED; case hci::ErrorCode::UNSUPPORTED_LMP_OR_LL_PARAMETER: - return static_cast( - hci::ErrorCode::UNSUPPORTED_LMP_OR_LL_PARAMETER); + return static_cast(hci::ErrorCode::UNSUPPORTED_LMP_OR_LL_PARAMETER); case hci::ErrorCode::ROLE_CHANGE_NOT_ALLOWED: return static_cast(hci::ErrorCode::ROLE_CHANGE_NOT_ALLOWED); case hci::ErrorCode::LINK_LAYER_COLLISION: @@ -241,12 +227,9 @@ inline tHCI_STATUS ToLegacyHciErrorCode(const hci::ErrorCode& reason) { } } -inline tHCI_MODE ToLegacyHciMode(const hci::Mode& mode) { - return static_cast(mode); -} +inline tHCI_MODE ToLegacyHciMode(const hci::Mode& mode) { return static_cast(mode); } -inline hci::DisconnectReason ToDisconnectReasonFromLegacy( - const tHCI_STATUS& reason) { +inline hci::DisconnectReason ToDisconnectReasonFromLegacy(const tHCI_STATUS& reason) { return static_cast(reason); } @@ -273,7 +256,9 @@ inline void DumpBtHdr(const BT_HDR* p_buf, const char* token) { char* pbuf = buf; pbuf += sprintf(pbuf, "len:%5u %5d: ", p_buf->len, cnt); for (int j = 0; j < 16; j++, --len, data++, cnt++) { - if (len == 0) break; + if (len == 0) { + break; + } pbuf += sprintf(pbuf, "0x%02x ", *data); } log::debug("{} {}", token, buf); diff --git a/system/main/shim/l2c_api.h b/system/main/shim/l2c_api.h index d668d175ff9..98f45b7d44f 100644 --- a/system/main/shim/l2c_api.h +++ b/system/main/shim/l2c_api.h @@ -41,9 +41,8 @@ namespace shim { * BTM_SetSecurityLevel(). * ******************************************************************************/ -uint16_t L2CA_Register(uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info, - bool enable_snoop, tL2CAP_ERTM_INFO* p_ertm_info, - uint16_t my_mtu, uint16_t required_remote_mtu, +uint16_t L2CA_Register(uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info, bool enable_snoop, + tL2CAP_ERTM_INFO* p_ertm_info, uint16_t my_mtu, uint16_t required_remote_mtu, uint16_t sec_level); /******************************************************************************* @@ -110,8 +109,8 @@ uint16_t L2CA_ConnectReq(uint16_t psm, const RawAddress& p_bd_addr); * and BTM_SetSecurityLevel(). * ******************************************************************************/ -uint16_t L2CA_RegisterLECoc(uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info, - uint16_t sec_level, tL2CAP_LE_CFG_INFO cfg); +uint16_t L2CA_RegisterLECoc(uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info, uint16_t sec_level, + tL2CAP_LE_CFG_INFO cfg); /******************************************************************************* * @@ -137,8 +136,7 @@ void L2CA_DeregisterLECoc(uint16_t psm); * Returns the CID of the connection, or 0 if it failed to start * ******************************************************************************/ -uint16_t L2CA_ConnectLECocReq(uint16_t psm, const RawAddress& p_bd_addr, - tL2CAP_LE_CFG_INFO* p_cfg); +uint16_t L2CA_ConnectLECocReq(uint16_t psm, const RawAddress& p_bd_addr, tL2CAP_LE_CFG_INFO* p_cfg); /******************************************************************************* * @@ -162,8 +160,7 @@ bool L2CA_GetPeerLECocConfig(uint16_t lcid, tL2CAP_LE_CFG_INFO* peer_cfg); * ******************************************************************************/ -bool L2CA_ReconfigCreditBasedConnsReq(const RawAddress& bd_addr, - std::vector& lcids, +bool L2CA_ReconfigCreditBasedConnsReq(const RawAddress& bd_addr, std::vector& lcids, tL2CAP_LE_CFG_INFO* p_cfg); /******************************************************************************* @@ -179,8 +176,8 @@ bool L2CA_ReconfigCreditBasedConnsReq(const RawAddress& bd_addr, * ******************************************************************************/ -extern std::vector L2CA_ConnectCreditBasedReq( - uint16_t psm, const RawAddress& p_bd_addr, tL2CAP_LE_CFG_INFO* p_cfg); +extern std::vector L2CA_ConnectCreditBasedReq(uint16_t psm, const RawAddress& p_bd_addr, + tL2CAP_LE_CFG_INFO* p_cfg); /******************************************************************************* * @@ -194,8 +191,8 @@ extern std::vector L2CA_ConnectCreditBasedReq( ******************************************************************************/ bool L2CA_ConnectCreditBasedRsp(const RawAddress& p_bd_addr, uint8_t id, - std::vector& accepted_lcids, - uint16_t result, tL2CAP_LE_CFG_INFO* p_cfg); + std::vector& accepted_lcids, uint16_t result, + tL2CAP_LE_CFG_INFO* p_cfg); /******************************************************************************* * @@ -313,8 +310,7 @@ bool L2CA_SetChnlFlushability(uint16_t cid, bool is_flushable); * Return value: true if peer is connected * ******************************************************************************/ -bool L2CA_GetPeerFeatures(const RawAddress& bd_addr, uint32_t* p_ext_feat, - uint8_t* p_chnl_mask); +bool L2CA_GetPeerFeatures(const RawAddress& bd_addr, uint32_t* p_ext_feat, uint8_t* p_chnl_mask); /******************************************************************************* * @@ -328,8 +324,7 @@ bool L2CA_GetPeerFeatures(const RawAddress& bd_addr, uint32_t* p_ext_feat, * Return value: true if registered OK * ******************************************************************************/ -bool L2CA_RegisterFixedChannel(uint16_t fixed_cid, - tL2CAP_FIXED_CHNL_REG* p_freg); +bool L2CA_RegisterFixedChannel(uint16_t fixed_cid, tL2CAP_FIXED_CHNL_REG* p_freg); /******************************************************************************* * @@ -359,8 +354,7 @@ bool L2CA_ConnectFixedChnl(uint16_t fixed_cid, const RawAddress& bd_addr); * tL2CAP_DW_RESULT::FAILED, if error * ******************************************************************************/ -uint16_t L2CA_SendFixedChnlData(uint16_t fixed_cid, const RawAddress& rem_bda, - BT_HDR* p_buf); +uint16_t L2CA_SendFixedChnlData(uint16_t fixed_cid, const RawAddress& rem_bda, BT_HDR* p_buf); /******************************************************************************* * @@ -380,9 +374,8 @@ bool L2CA_RemoveFixedChnl(uint16_t fixed_cid, const RawAddress& rem_bda); uint16_t L2CA_GetLeHandle(const RawAddress& rem_bda); hci_role_t L2CA_GetBleConnRole(const RawAddress& bd_addr); -void L2CA_LeConnectionUpdate(const RawAddress& rem_bda, uint16_t min_int, - uint16_t max_int, uint16_t latency, - uint16_t timeout, uint16_t min_ce_len, +void L2CA_LeConnectionUpdate(const RawAddress& rem_bda, uint16_t min_int, uint16_t max_int, + uint16_t latency, uint16_t timeout, uint16_t min_ce_len, uint16_t max_ce_len); /******************************************************************************* @@ -406,23 +399,20 @@ bool L2CA_SetLeGattTimeout(const RawAddress& rem_bda, uint16_t idle_tout); bool L2CA_MarkLeLinkAsActive(const RawAddress& rem_bda); -bool L2CA_UpdateBleConnParams(const RawAddress& rem_bda, uint16_t min_int, - uint16_t max_int, uint16_t latency, - uint16_t timeout, uint16_t min_ce_len, +bool L2CA_UpdateBleConnParams(const RawAddress& rem_bda, uint16_t min_int, uint16_t max_int, + uint16_t latency, uint16_t timeout, uint16_t min_ce_len, uint16_t max_ce_len); /* When called with lock=true, LE connection parameters will be locked on * fastest value, and we won't accept request to change it from remote. When * called with lock=false, parameters are relaxed. */ -void L2CA_LockBleConnParamsForServiceDiscovery(const RawAddress& rem_bda, - bool lock); +void L2CA_LockBleConnParamsForServiceDiscovery(const RawAddress& rem_bda, bool lock); /* When called with lock=true, LE connection parameters will be locked on * fastest value, and we won't accept request to change it from remote. When * called with lock=false, parameters are relaxed. */ -void L2CA_LockBleConnParamsForProfileConnection(const RawAddress& rem_bda, - bool lock); +void L2CA_LockBleConnParamsForProfileConnection(const RawAddress& rem_bda, bool lock); /******************************************************************************* * @@ -447,8 +437,8 @@ void L2CA_SetBondingState(const RawAddress& p_bd_addr, bool is_bonding); void L2CA_SwitchRoleToCentral(const RawAddress& addr); -bool L2CA_ReadRemoteVersion(const RawAddress& addr, uint8_t* lmp_version, - uint16_t* manufacturer, uint16_t* lmp_sub_version); +bool L2CA_ReadRemoteVersion(const RawAddress& addr, uint8_t* lmp_version, uint16_t* manufacturer, + uint16_t* lmp_sub_version); uint8_t* L2CA_ReadRemoteFeatures(const RawAddress& addr); @@ -458,12 +448,10 @@ uint16_t L2CA_GetNumLinks(); bool L2CA_IsLeLink(uint16_t acl_handle); -void L2CA_ReadConnectionAddr(const RawAddress& pseudo_addr, - RawAddress& conn_addr, +void L2CA_ReadConnectionAddr(const RawAddress& pseudo_addr, RawAddress& conn_addr, tBLE_ADDR_TYPE* p_addr_type); -bool L2CA_ReadRemoteConnectionAddr(const RawAddress& pseudo_addr, - RawAddress& conn_addr, +bool L2CA_ReadRemoteConnectionAddr(const RawAddress& pseudo_addr, RawAddress& conn_addr, tBLE_ADDR_TYPE* p_addr_type); } // namespace shim diff --git a/system/main/shim/le_advertising_manager.cc b/system/main/shim/le_advertising_manager.cc index 2c2c23cf27a..645f02633b6 100644 --- a/system/main/shim/le_advertising_manager.cc +++ b/system/main/shim/le_advertising_manager.cc @@ -51,8 +51,8 @@ constexpr char kBtmLogTag[] = "ADV"; class BleAdvertiserInterfaceImpl : public BleAdvertiserInterface, public bluetooth::hci::AdvertisingCallback { - public: - ~BleAdvertiserInterfaceImpl() override{}; +public: + ~BleAdvertiserInterfaceImpl() override {} void Init() { // Register callback @@ -63,22 +63,20 @@ class BleAdvertiserInterfaceImpl : public BleAdvertiserInterface, log::info("in shim layer"); bluetooth::shim::GetAdvertising()->RegisterAdvertiser( - bluetooth::shim::GetGdShimHandler()->BindOnce( - [](IdStatusCallback cb, uint8_t id, uint8_t status) { - do_in_main_thread( - FROM_HERE, - base::BindOnce([](IdStatusCallback cb, uint8_t id, - uint8_t status) { cb.Run(id, status); }, - cb, id, status)); - }, - cb)); + bluetooth::shim::GetGdShimHandler()->BindOnce( + [](IdStatusCallback cb, uint8_t id, uint8_t status) { + do_in_main_thread(FROM_HERE, + base::BindOnce([](IdStatusCallback cb, uint8_t id, + uint8_t status) { cb.Run(id, status); }, + cb, id, status)); + }, + cb)); } void Unregister(uint8_t advertiser_id) override { log::info("in shim layer"); bluetooth::shim::GetAdvertising()->RemoveAdvertiser(advertiser_id); - int reg_id = - bluetooth::shim::GetAdvertising()->GetAdvertiserRegId(advertiser_id); + int reg_id = bluetooth::shim::GetAdvertising()->GetAdvertiserRegId(advertiser_id); uint8_t client_id = is_native_advertiser(reg_id); // if registered by native client, remove the register id if (client_id != kAdvertiserClientIdJni) { @@ -107,21 +105,18 @@ class BleAdvertiserInterfaceImpl : public BleAdvertiserInterface, log::info("in shim layer"); std::vector advertising_data = {}; parse_gap_data(data, advertising_data); - bluetooth::shim::GetAdvertising()->SetData(advertiser_id, set_scan_rsp, - advertising_data); + bluetooth::shim::GetAdvertising()->SetData(advertiser_id, set_scan_rsp, advertising_data); } - void Enable(uint8_t advertiser_id, bool enable, StatusCallback /* cb */, - uint16_t duration, uint8_t maxExtAdvEvents, - StatusCallback /* timeout_cb */) override { + void Enable(uint8_t advertiser_id, bool enable, StatusCallback /* cb */, uint16_t duration, + uint8_t maxExtAdvEvents, StatusCallback /* timeout_cb */) override { log::info("in shim layer"); - bluetooth::shim::GetAdvertising()->EnableAdvertiser( - advertiser_id, enable, duration, maxExtAdvEvents); + bluetooth::shim::GetAdvertising()->EnableAdvertiser(advertiser_id, enable, duration, + maxExtAdvEvents); } // nobody use this function - void StartAdvertising(uint8_t advertiser_id, StatusCallback cb, - AdvertiseParameters params, + void StartAdvertising(uint8_t advertiser_id, StatusCallback cb, AdvertiseParameters params, std::vector advertise_data, std::vector scan_response_data, int timeout_s, StatusCallback timeout_cb) override { @@ -134,25 +129,21 @@ class BleAdvertiserInterfaceImpl : public BleAdvertiserInterface, parse_gap_data(scan_response_data, config.scan_response); bluetooth::shim::GetAdvertising()->StartAdvertising( - advertiser_id, config, timeout_s * 100, cb, timeout_cb, scan_callback, - set_terminated_callback, bluetooth::shim::GetGdShimHandler()); + advertiser_id, config, timeout_s * 100, cb, timeout_cb, scan_callback, + set_terminated_callback, bluetooth::shim::GetGdShimHandler()); } - void StartAdvertisingSet(uint8_t client_id, int reg_id, - IdTxPowerStatusCallback /* register_cb */, - AdvertiseParameters params, - std::vector advertise_data, + void StartAdvertisingSet(uint8_t client_id, int reg_id, IdTxPowerStatusCallback /* register_cb */, + AdvertiseParameters params, std::vector advertise_data, std::vector scan_response_data, PeriodicAdvertisingParameters periodic_params, - std::vector periodic_data, - uint16_t duration, uint8_t maxExtAdvEvents, - IdStatusCallback /* timeout_cb */) { + std::vector periodic_data, uint16_t duration, + uint8_t maxExtAdvEvents, IdStatusCallback /* timeout_cb */) { log::info("in shim layer"); bluetooth::hci::AdvertisingConfig config{}; parse_parameter(config, params); - parse_periodic_advertising_parameter(config.periodic_advertising_parameters, - periodic_params); + parse_periodic_advertising_parameter(config.periodic_advertising_parameters, periodic_params); parse_gap_data(advertise_data, config.advertisement); parse_gap_data(scan_response_data, config.scan_response); @@ -164,27 +155,25 @@ class BleAdvertiserInterfaceImpl : public BleAdvertiserInterface, } bluetooth::shim::GetAdvertising()->ExtendedCreateAdvertiser( - client_id, reg_id, config, scan_callback, set_terminated_callback, - duration, maxExtAdvEvents, bluetooth::shim::GetGdShimHandler()); + client_id, reg_id, config, scan_callback, set_terminated_callback, duration, + maxExtAdvEvents, bluetooth::shim::GetGdShimHandler()); - log::info("create advertising set, client_id:{}, reg_id:{}", client_id, - reg_id); + log::info("create advertising set, client_id:{}, reg_id:{}", client_id, reg_id); BTM_LogHistory(kBtmLogTag, RawAddress::kEmpty, "Le advert started", base::StringPrintf("reg_id:%d", reg_id)); return; } - void SetPeriodicAdvertisingParameters( - int advertiser_id, PeriodicAdvertisingParameters periodic_params, - StatusCallback /* cb */) override { + void SetPeriodicAdvertisingParameters(int advertiser_id, + PeriodicAdvertisingParameters periodic_params, + StatusCallback /* cb */) override { log::info("in shim layer"); bluetooth::hci::PeriodicAdvertisingParameters parameters; parameters.max_interval = periodic_params.max_interval; parameters.min_interval = periodic_params.min_interval; parameters.properties = periodic_params.periodic_advertising_properties; - bluetooth::shim::GetAdvertising()->SetPeriodicParameters(advertiser_id, - parameters); + bluetooth::shim::GetAdvertising()->SetPeriodicParameters(advertiser_id, parameters); } void SetPeriodicAdvertisingData(int advertiser_id, std::vector data, @@ -192,24 +181,19 @@ class BleAdvertiserInterfaceImpl : public BleAdvertiserInterface, log::info("in shim layer"); std::vector advertising_data = {}; parse_gap_data(data, advertising_data); - bluetooth::shim::GetAdvertising()->SetPeriodicData(advertiser_id, - advertising_data); + bluetooth::shim::GetAdvertising()->SetPeriodicData(advertiser_id, advertising_data); } - void SetPeriodicAdvertisingEnable(int advertiser_id, bool enable, - bool include_adi, + void SetPeriodicAdvertisingEnable(int advertiser_id, bool enable, bool include_adi, StatusCallback /* cb */) override { log::info("in shim layer"); - bluetooth::shim::GetAdvertising()->EnablePeriodicAdvertising( - advertiser_id, enable, include_adi); + bluetooth::shim::GetAdvertising()->EnablePeriodicAdvertising(advertiser_id, enable, + include_adi); } - void RegisterCallbacks(AdvertisingCallbacks* callbacks) { - advertising_callbacks_ = callbacks; - } + void RegisterCallbacks(AdvertisingCallbacks* callbacks) { advertising_callbacks_ = callbacks; } - void RegisterCallbacksNative(AdvertisingCallbacks* callbacks, - uint8_t client_id) { + void RegisterCallbacksNative(AdvertisingCallbacks* callbacks, uint8_t client_id) { native_adv_callbacks_map_[client_id] = callbacks; } @@ -222,119 +206,105 @@ class BleAdvertiserInterfaceImpl : public BleAdvertiserInterface, } const bluetooth::common::Callback scan_callback = - bluetooth::common::Bind(&BleAdvertiserInterfaceImpl::on_scan, - bluetooth::common::Unretained(this)); + bluetooth::common::Bind(&BleAdvertiserInterfaceImpl::on_scan, + bluetooth::common::Unretained(this)); - const bluetooth::common::Callback - set_terminated_callback = bluetooth::common::Bind( - &BleAdvertiserInterfaceImpl::on_set_terminated, - bluetooth::common::Unretained(this)); + const bluetooth::common::Callback set_terminated_callback = + bluetooth::common::Bind(&BleAdvertiserInterfaceImpl::on_set_terminated, + bluetooth::common::Unretained(this)); // AdvertisingCallback - void OnAdvertisingSetStarted(int reg_id, uint8_t advertiser_id, - int8_t tx_power, + void OnAdvertisingSetStarted(int reg_id, uint8_t advertiser_id, int8_t tx_power, AdvertisingStatus status) override { uint8_t client_id = is_native_advertiser(reg_id); if (client_id != kAdvertiserClientIdJni) { // Invoke callback for native client - do_in_main_thread( - FROM_HERE, - base::Bind(&AdvertisingCallbacks::OnAdvertisingSetStarted, - base::Unretained(native_adv_callbacks_map_[client_id]), - reg_id, advertiser_id, tx_power, status)); + do_in_main_thread(FROM_HERE, + base::Bind(&AdvertisingCallbacks::OnAdvertisingSetStarted, + base::Unretained(native_adv_callbacks_map_[client_id]), reg_id, + advertiser_id, tx_power, status)); return; } - do_in_jni_thread( - base::BindOnce(&AdvertisingCallbacks::OnAdvertisingSetStarted, - base::Unretained(advertising_callbacks_), reg_id, - advertiser_id, tx_power, status)); + do_in_jni_thread(base::BindOnce(&AdvertisingCallbacks::OnAdvertisingSetStarted, + base::Unretained(advertising_callbacks_), reg_id, advertiser_id, + tx_power, status)); } void OnAdvertisingEnabled(uint8_t advertiser_id, bool enable, AdvertisingStatus status) { - int reg_id = - bluetooth::shim::GetAdvertising()->GetAdvertiserRegId(advertiser_id); + int reg_id = bluetooth::shim::GetAdvertising()->GetAdvertiserRegId(advertiser_id); uint8_t client_id = is_native_advertiser(reg_id); if (client_id != kAdvertiserClientIdJni) { // Invoke callback for native client - do_in_main_thread( - FROM_HERE, - base::Bind(&AdvertisingCallbacks::OnAdvertisingEnabled, - base::Unretained(native_adv_callbacks_map_[client_id]), - advertiser_id, enable, status)); + do_in_main_thread(FROM_HERE, + base::Bind(&AdvertisingCallbacks::OnAdvertisingEnabled, + base::Unretained(native_adv_callbacks_map_[client_id]), + advertiser_id, enable, status)); return; } do_in_jni_thread(base::BindOnce(&AdvertisingCallbacks::OnAdvertisingEnabled, - base::Unretained(advertising_callbacks_), - advertiser_id, enable, status)); + base::Unretained(advertising_callbacks_), advertiser_id, enable, + status)); } void OnAdvertisingDataSet(uint8_t advertiser_id, AdvertisingStatus status) { - if (com::android::bluetooth::flags:: - leaudio_broadcast_update_metadata_callback()) { - int reg_id = - bluetooth::shim::GetAdvertising()->GetAdvertiserRegId(advertiser_id); + if (com::android::bluetooth::flags::leaudio_broadcast_update_metadata_callback()) { + int reg_id = bluetooth::shim::GetAdvertising()->GetAdvertiserRegId(advertiser_id); uint8_t client_id = is_native_advertiser(reg_id); if (client_id != kAdvertiserClientIdJni) { // Invoke callback for native client - do_in_main_thread( - FROM_HERE, - base::Bind(&AdvertisingCallbacks::OnAdvertisingDataSet, - base::Unretained(native_adv_callbacks_map_[client_id]), - advertiser_id, status)); + do_in_main_thread(FROM_HERE, + base::Bind(&AdvertisingCallbacks::OnAdvertisingDataSet, + base::Unretained(native_adv_callbacks_map_[client_id]), + advertiser_id, status)); return; } } do_in_jni_thread(base::BindOnce(&AdvertisingCallbacks::OnAdvertisingDataSet, - base::Unretained(advertising_callbacks_), - advertiser_id, status)); + base::Unretained(advertising_callbacks_), advertiser_id, + status)); } void OnScanResponseDataSet(uint8_t advertiser_id, AdvertisingStatus status) { - do_in_jni_thread(base::BindOnce( - &AdvertisingCallbacks::OnScanResponseDataSet, - base::Unretained(advertising_callbacks_), advertiser_id, status)); + do_in_jni_thread(base::BindOnce(&AdvertisingCallbacks::OnScanResponseDataSet, + base::Unretained(advertising_callbacks_), advertiser_id, + status)); } void OnAdvertisingParametersUpdated(uint8_t advertiser_id, int8_t tx_power, AdvertisingStatus status) { - do_in_jni_thread( - base::BindOnce(&AdvertisingCallbacks::OnAdvertisingParametersUpdated, - base::Unretained(advertising_callbacks_), advertiser_id, - tx_power, status)); + do_in_jni_thread(base::BindOnce(&AdvertisingCallbacks::OnAdvertisingParametersUpdated, + base::Unretained(advertising_callbacks_), advertiser_id, + tx_power, status)); } void OnPeriodicAdvertisingParametersUpdated(uint8_t advertiser_id, AdvertisingStatus status) { - do_in_jni_thread(base::BindOnce( - &AdvertisingCallbacks::OnPeriodicAdvertisingParametersUpdated, - base::Unretained(advertising_callbacks_), advertiser_id, status)); + do_in_jni_thread(base::BindOnce(&AdvertisingCallbacks::OnPeriodicAdvertisingParametersUpdated, + base::Unretained(advertising_callbacks_), advertiser_id, + status)); } void OnPeriodicAdvertisingDataSet(uint8_t advertiser_id, AdvertisingStatus status) { - if (com::android::bluetooth::flags:: - leaudio_broadcast_update_metadata_callback()) { - int reg_id = - bluetooth::shim::GetAdvertising()->GetAdvertiserRegId(advertiser_id); + if (com::android::bluetooth::flags::leaudio_broadcast_update_metadata_callback()) { + int reg_id = bluetooth::shim::GetAdvertising()->GetAdvertiserRegId(advertiser_id); uint8_t client_id = is_native_advertiser(reg_id); if (client_id != kAdvertiserClientIdJni) { // Invoke callback for native client - do_in_main_thread( - FROM_HERE, - base::Bind(&AdvertisingCallbacks::OnPeriodicAdvertisingDataSet, - base::Unretained(native_adv_callbacks_map_[client_id]), - advertiser_id, status)); + do_in_main_thread(FROM_HERE, + base::Bind(&AdvertisingCallbacks::OnPeriodicAdvertisingDataSet, + base::Unretained(native_adv_callbacks_map_[client_id]), + advertiser_id, status)); return; } } - do_in_jni_thread(base::BindOnce( - &AdvertisingCallbacks::OnPeriodicAdvertisingDataSet, - base::Unretained(advertising_callbacks_), advertiser_id, status)); + do_in_jni_thread(base::BindOnce(&AdvertisingCallbacks::OnPeriodicAdvertisingDataSet, + base::Unretained(advertising_callbacks_), advertiser_id, + status)); } void OnPeriodicAdvertisingEnabled(uint8_t advertiser_id, bool enable, AdvertisingStatus status) { - do_in_jni_thread( - base::BindOnce(&AdvertisingCallbacks::OnPeriodicAdvertisingEnabled, - base::Unretained(advertising_callbacks_), advertiser_id, - enable, status)); + do_in_jni_thread(base::BindOnce(&AdvertisingCallbacks::OnPeriodicAdvertisingEnabled, + base::Unretained(advertising_callbacks_), advertiser_id, enable, + status)); } void OnOwnAddressRead(uint8_t advertiser_id, uint8_t address_type, @@ -346,16 +316,15 @@ class BleAdvertiserInterfaceImpl : public BleAdvertiserInterface, return; } do_in_jni_thread(base::BindOnce(&AdvertisingCallbacks::OnOwnAddressRead, - base::Unretained(advertising_callbacks_), - advertiser_id, address_type, raw_address)); + base::Unretained(advertising_callbacks_), advertiser_id, + address_type, raw_address)); } AdvertisingCallbacks* advertising_callbacks_; std::map native_adv_callbacks_map_; - private: - void parse_parameter(bluetooth::hci::AdvertisingConfig& config, - AdvertiseParameters params) { +private: + void parse_parameter(bluetooth::hci::AdvertisingConfig& config, AdvertiseParameters params) { config.connectable = params.advertising_event_properties & 0x01; config.scannable = params.advertising_event_properties & 0x02; config.discoverable = params.advertising_event_properties & 0x04; @@ -368,40 +337,31 @@ class BleAdvertiserInterfaceImpl : public BleAdvertiserInterface, config.tx_power = params.tx_power; config.use_le_coded_phy = params.primary_advertising_phy == 0x03; config.secondary_advertising_phy = - static_cast( - params.secondary_advertising_phy); + static_cast(params.secondary_advertising_phy); config.enable_scan_request_notifications = - static_cast( - params.scan_request_notification_enable); + static_cast(params.scan_request_notification_enable); // Matching the ADDRESS_TYPE_* enums from Java switch (params.own_address_type) { case -1: - config.requested_advertiser_address_type = - AdvertiserAddressType::RESOLVABLE_RANDOM; + config.requested_advertiser_address_type = AdvertiserAddressType::RESOLVABLE_RANDOM; break; case 0: - config.requested_advertiser_address_type = - AdvertiserAddressType::PUBLIC; + config.requested_advertiser_address_type = AdvertiserAddressType::PUBLIC; break; case 1: - config.requested_advertiser_address_type = - AdvertiserAddressType::RESOLVABLE_RANDOM; + config.requested_advertiser_address_type = AdvertiserAddressType::RESOLVABLE_RANDOM; break; case 2: - config.requested_advertiser_address_type = - AdvertiserAddressType::NONRESOLVABLE_RANDOM; + config.requested_advertiser_address_type = AdvertiserAddressType::NONRESOLVABLE_RANDOM; break; default: - log::error("Received unexpected address type: {}", - params.own_address_type); - config.requested_advertiser_address_type = - AdvertiserAddressType::RESOLVABLE_RANDOM; + log::error("Received unexpected address type: {}", params.own_address_type); + config.requested_advertiser_address_type = AdvertiserAddressType::RESOLVABLE_RANDOM; } } - void parse_periodic_advertising_parameter( - bluetooth::hci::PeriodicAdvertisingParameters& config, - PeriodicAdvertisingParameters periodic_params) { + void parse_periodic_advertising_parameter(bluetooth::hci::PeriodicAdvertisingParameters& config, + PeriodicAdvertisingParameters periodic_params) { config.max_interval = periodic_params.max_interval; config.min_interval = periodic_params.min_interval; config.properties = periodic_params.periodic_advertising_properties; @@ -431,10 +391,8 @@ BleAdvertiserInterface* bluetooth::shim::get_ble_advertiser_instance() { bt_le_advertiser_instance = new BleAdvertiserInterfaceImpl(); } return bt_le_advertiser_instance; -}; +} void bluetooth::shim::init_advertising_manager() { - static_cast( - bluetooth::shim::get_ble_advertiser_instance()) - ->Init(); + static_cast(bluetooth::shim::get_ble_advertiser_instance())->Init(); } diff --git a/system/main/shim/le_scanning_manager.cc b/system/main/shim/le_scanning_manager.cc index c9b113541ac..605d62a7948 100644 --- a/system/main/shim/le_scanning_manager.cc +++ b/system/main/shim/le_scanning_manager.cc @@ -65,87 +65,69 @@ constexpr uint16_t kAllowAllFilter = 0x00; constexpr uint16_t kListLogicOr = 0x01; class DefaultScanningCallback : public ::ScanningCallbacks { - void OnScannerRegistered(const bluetooth::Uuid /* app_uuid */, - uint8_t /* scanner_id */, + void OnScannerRegistered(const bluetooth::Uuid /* app_uuid */, uint8_t /* scanner_id */, uint8_t /* status */) override { LogUnused(); } - void OnSetScannerParameterComplete(uint8_t /* scanner_id */, - uint8_t /* status */) override { + void OnSetScannerParameterComplete(uint8_t /* scanner_id */, uint8_t /* status */) override { LogUnused(); } - void OnScanResult(uint16_t /* event_type */, uint8_t /* address_type */, - RawAddress /* bda */, uint8_t /* primary_phy */, - uint8_t /* secondary_phy */, uint8_t /* advertising_sid */, - int8_t /* tx_power */, int8_t /* rssi */, + void OnScanResult(uint16_t /* event_type */, uint8_t /* address_type */, RawAddress /* bda */, + uint8_t /* primary_phy */, uint8_t /* secondary_phy */, + uint8_t /* advertising_sid */, int8_t /* tx_power */, int8_t /* rssi */, uint16_t /* periodic_advertising_interval */, std::vector /* advertising_data */) override { LogUnused(); } - void OnTrackAdvFoundLost( - AdvertisingTrackInfo /* advertising_track_info */) override { + void OnTrackAdvFoundLost(AdvertisingTrackInfo /* advertising_track_info */) override { LogUnused(); } - void OnBatchScanReports(int /* client_if */, int /* status */, - int /* report_format */, int /* num_records */, - std::vector /* data */) override { + void OnBatchScanReports(int /* client_if */, int /* status */, int /* report_format */, + int /* num_records */, std::vector /* data */) override { LogUnused(); } - void OnBatchScanThresholdCrossed(int /* client_if */) override { - LogUnused(); - } - void OnPeriodicSyncStarted(int /* reg_id */, uint8_t /* status */, - uint16_t /* sync_handle */, - uint8_t /* advertising_sid */, - uint8_t /* address_type */, + void OnBatchScanThresholdCrossed(int /* client_if */) override { LogUnused(); } + void OnPeriodicSyncStarted(int /* reg_id */, uint8_t /* status */, uint16_t /* sync_handle */, + uint8_t /* advertising_sid */, uint8_t /* address_type */, RawAddress /* address */, uint8_t /* phy */, uint16_t /* interval */) override { LogUnused(); - }; - void OnPeriodicSyncReport(uint16_t /* sync_handle */, int8_t /* tx_power */, - int8_t /* rssi */, uint8_t /* status */, - std::vector /* data */) override { + } + void OnPeriodicSyncReport(uint16_t /* sync_handle */, int8_t /* tx_power */, int8_t /* rssi */, + uint8_t /* status */, std::vector /* data */) override { LogUnused(); - }; - void OnPeriodicSyncLost(uint16_t /* sync_handle */) override { LogUnused(); }; + } + void OnPeriodicSyncLost(uint16_t /* sync_handle */) override { LogUnused(); } void OnPeriodicSyncTransferred(int /* pa_source */, uint8_t /* status */, RawAddress /* address */) override { LogUnused(); - }; + } - void OnBigInfoReport(uint16_t /* sync_handle */, - bool /* encrypted */) override { - LogUnused(); - }; + void OnBigInfoReport(uint16_t /* sync_handle */, bool /* encrypted */) override { LogUnused(); } - private: - static void LogUnused() { - log::warn("BLE Scanning callbacks have not been registered"); - } +private: + static void LogUnused() { log::warn("BLE Scanning callbacks have not been registered"); } } default_scanning_callback_; } // namespace ::ScanningCallbacks* bluetooth::shim::default_scanning_callback = - static_cast<::ScanningCallbacks*>(&default_scanning_callback_); + static_cast<::ScanningCallbacks*>(&default_scanning_callback_); extern ::ScanningCallbacks* bluetooth::shim::default_scanning_callback; -void btm_ble_process_adv_pkt_cont_for_inquiry( - uint16_t event_type, tBLE_ADDR_TYPE address_type, - const RawAddress& raw_address, uint8_t primary_phy, uint8_t secondary_phy, - uint8_t advertising_sid, int8_t tx_power, int8_t rssi, - uint16_t periodic_adv_int, std::vector advertising_data); +void btm_ble_process_adv_pkt_cont_for_inquiry(uint16_t event_type, tBLE_ADDR_TYPE address_type, + const RawAddress& raw_address, uint8_t primary_phy, + uint8_t secondary_phy, uint8_t advertising_sid, + int8_t tx_power, int8_t rssi, + uint16_t periodic_adv_int, + std::vector advertising_data); -extern void btif_dm_update_ble_remote_properties(const RawAddress& bd_addr, - BD_NAME bd_name, - DEV_CLASS dev_class, - tBT_DEVICE_TYPE dev_type); +extern void btif_dm_update_ble_remote_properties(const RawAddress& bd_addr, BD_NAME bd_name, + DEV_CLASS dev_class, tBT_DEVICE_TYPE dev_type); -void btm_ble_process_adv_addr(RawAddress& raw_address, - tBLE_ADDR_TYPE* address_type); +void btm_ble_process_adv_addr(RawAddress& raw_address, tBLE_ADDR_TYPE* address_type); -extern DEV_CLASS btm_ble_get_appearance_as_cod( - std::vector const& data); +extern DEV_CLASS btm_ble_get_appearance_as_cod(std::vector const& data); using bluetooth::shim::BleScannerInterfaceImpl; @@ -161,8 +143,7 @@ void BleScannerInterfaceImpl::Init() { } /** Registers a scanner with the stack */ -void BleScannerInterfaceImpl::RegisterScanner(const bluetooth::Uuid& uuid, - RegisterCallback) { +void BleScannerInterfaceImpl::RegisterScanner(const bluetooth::Uuid& uuid, RegisterCallback) { auto app_uuid = bluetooth::hci::Uuid::From128BitBE(uuid.To128BitBE()); log::info("in shim layer, UUID={}", app_uuid.ToString()); bluetooth::shim::GetScanning()->RegisterScanner(app_uuid); @@ -174,22 +155,21 @@ void BleScannerInterfaceImpl::Unregister(int scanner_id) { bluetooth::shim::GetScanning()->Unregister(scanner_id); } - /** Start or stop LE device scanning */ +/** Start or stop LE device scanning */ void BleScannerInterfaceImpl::Scan(bool start) { log::info("in shim layer {}", (start) ? "started" : "stopped"); bluetooth::shim::GetScanning()->Scan(start); if (start && !btm_cb.ble_ctr_cb.is_ble_observe_active()) { btm_cb.neighbor.le_scan = { - .start_time_ms = timestamper_in_milliseconds.GetTimestamp(), - .results = 0, + .start_time_ms = timestamper_in_milliseconds.GetTimestamp(), + .results = 0, }; BTM_LogHistory(kBtmLogTag, RawAddress::kEmpty, "Le scan started"); btm_cb.ble_ctr_cb.set_ble_observe_active(); } else if (!start && btm_cb.ble_ctr_cb.is_ble_observe_active()) { // stopped const unsigned long long duration_timestamp = - timestamper_in_milliseconds.GetTimestamp() - - btm_cb.neighbor.le_scan.start_time_ms; + timestamper_in_milliseconds.GetTimestamp() - btm_cb.neighbor.le_scan.start_time_ms; BTM_LogHistory(kBtmLogTag, RawAddress::kEmpty, "Le scan stopped", base::StringPrintf("duration_s:%6.3f results:%-3lu", (double)duration_timestamp / 1000.0, @@ -206,52 +186,45 @@ void BleScannerInterfaceImpl::Scan(bool start) { base::Unretained(&address_cache_))); } - /** Setup scan filter params */ +/** Setup scan filter params */ void BleScannerInterfaceImpl::ScanFilterParamSetup( - uint8_t client_if, uint8_t action, uint8_t filter_index, - std::unique_ptr filt_param, - FilterParamSetupCallback cb) { + uint8_t client_if, uint8_t action, uint8_t filter_index, + std::unique_ptr filt_param, FilterParamSetupCallback cb) { log::info("in shim layer, clientIf={}", client_if); auto apcf_action = static_cast(action); bluetooth::hci::AdvertisingFilterParameter advertising_filter_parameter; if (filt_param != nullptr) { - if (filt_param && filt_param->dely_mode == 1 && - apcf_action == hci::ApcfAction::ADD) { + if (filt_param && filt_param->dely_mode == 1 && apcf_action == hci::ApcfAction::ADD) { bluetooth::shim::GetScanning()->TrackAdvertiser(filter_index, client_if); } advertising_filter_parameter.feature_selection = filt_param->feat_seln; advertising_filter_parameter.list_logic_type = filt_param->list_logic_type; - advertising_filter_parameter.filter_logic_type = - filt_param->filt_logic_type; + advertising_filter_parameter.filter_logic_type = filt_param->filt_logic_type; advertising_filter_parameter.rssi_high_thresh = filt_param->rssi_high_thres; advertising_filter_parameter.delivery_mode = - static_cast(filt_param->dely_mode); + static_cast(filt_param->dely_mode); if (filt_param && filt_param->dely_mode == 1) { advertising_filter_parameter.onfound_timeout = filt_param->found_timeout; - advertising_filter_parameter.onfound_timeout_cnt = - filt_param->found_timeout_cnt; + advertising_filter_parameter.onfound_timeout_cnt = filt_param->found_timeout_cnt; advertising_filter_parameter.rssi_low_thresh = filt_param->rssi_low_thres; advertising_filter_parameter.onlost_timeout = filt_param->lost_timeout; - advertising_filter_parameter.num_of_tracking_entries = - filt_param->num_of_tracking_entries; + advertising_filter_parameter.num_of_tracking_entries = filt_param->num_of_tracking_entries; } } - bluetooth::shim::GetScanning()->ScanFilterParameterSetup( - apcf_action, filter_index, advertising_filter_parameter); + bluetooth::shim::GetScanning()->ScanFilterParameterSetup(apcf_action, filter_index, + advertising_filter_parameter); // TODO refactor callback mechanism do_in_jni_thread(base::BindOnce(cb, 0, 0, btm_status_value(BTM_SUCCESS))); } /** Configure a scan filter condition */ -void BleScannerInterfaceImpl::ScanFilterAdd(int filter_index, - std::vector filters, +void BleScannerInterfaceImpl::ScanFilterAdd(int filter_index, std::vector filters, FilterConfigCallback cb) { log::info("in shim layer"); - std::vector - new_filters = {}; + std::vector new_filters = {}; for (size_t i = 0; i < filters.size(); i++) { bluetooth::hci::AdvertisingPacketContentFilterCommand command{}; if (!parse_filter_command(command, filters[i])) { @@ -294,54 +267,51 @@ void BleScannerInterfaceImpl::MsftAdvMonitorAdd(MsftAdvMonitor monitor, log::info("in shim layer"); msft_callbacks_.Add = cb; bluetooth::shim::GetMsftExtensionManager()->MsftAdvMonitorAdd( - monitor, base::Bind(&BleScannerInterfaceImpl::OnMsftAdvMonitorAdd, - base::Unretained(this))); + monitor, + base::Bind(&BleScannerInterfaceImpl::OnMsftAdvMonitorAdd, base::Unretained(this))); } /** Removes MSFT filter */ -void BleScannerInterfaceImpl::MsftAdvMonitorRemove( - uint8_t monitor_handle, MsftAdvMonitorRemoveCallback cb) { +void BleScannerInterfaceImpl::MsftAdvMonitorRemove(uint8_t monitor_handle, + MsftAdvMonitorRemoveCallback cb) { log::info("in shim layer"); msft_callbacks_.Remove = cb; bluetooth::shim::GetMsftExtensionManager()->MsftAdvMonitorRemove( - monitor_handle, - base::Bind(&BleScannerInterfaceImpl::OnMsftAdvMonitorRemove, - base::Unretained(this))); + monitor_handle, + base::Bind(&BleScannerInterfaceImpl::OnMsftAdvMonitorRemove, base::Unretained(this))); } /** Enable / disable MSFT scan filter */ -void BleScannerInterfaceImpl::MsftAdvMonitorEnable( - bool enable, MsftAdvMonitorEnableCallback cb) { +void BleScannerInterfaceImpl::MsftAdvMonitorEnable(bool enable, MsftAdvMonitorEnableCallback cb) { log::info("in shim layer"); msft_callbacks_.Enable = cb; bluetooth::shim::GetMsftExtensionManager()->MsftAdvMonitorEnable( - enable, base::Bind(&BleScannerInterfaceImpl::OnMsftAdvMonitorEnable, - base::Unretained(this), enable)); + enable, base::Bind(&BleScannerInterfaceImpl::OnMsftAdvMonitorEnable, + base::Unretained(this), enable)); } /** Callback of adding MSFT filter */ -void BleScannerInterfaceImpl::OnMsftAdvMonitorAdd( - uint8_t monitor_handle, bluetooth::hci::ErrorCode status) { +void BleScannerInterfaceImpl::OnMsftAdvMonitorAdd(uint8_t monitor_handle, + bluetooth::hci::ErrorCode status) { log::info("in shim layer"); msft_callbacks_.Add.Run(monitor_handle, (uint8_t)status); } /** Callback of removing MSFT filter */ -void BleScannerInterfaceImpl::OnMsftAdvMonitorRemove( - bluetooth::hci::ErrorCode status) { +void BleScannerInterfaceImpl::OnMsftAdvMonitorRemove(bluetooth::hci::ErrorCode status) { log::info("in shim layer"); msft_callbacks_.Remove.Run((uint8_t)status); } /** Callback of enabling / disabling MSFT scan filter */ -void BleScannerInterfaceImpl::OnMsftAdvMonitorEnable( - bool enable, bluetooth::hci::ErrorCode status) { +void BleScannerInterfaceImpl::OnMsftAdvMonitorEnable(bool enable, + bluetooth::hci::ErrorCode status) { log::info("in shim layer"); if (status == bluetooth::hci::ErrorCode::SUCCESS) { bluetooth::shim::GetScanning()->SetScanFilterPolicy( - enable ? bluetooth::hci::LeScanningFilterPolicy::FILTER_ACCEPT_LIST_ONLY - : bluetooth::hci::LeScanningFilterPolicy::ACCEPT_ALL); + enable ? bluetooth::hci::LeScanningFilterPolicy::FILTER_ACCEPT_LIST_ONLY + : bluetooth::hci::LeScanningFilterPolicy::ACCEPT_ALL); } msft_callbacks_.Enable.Run((uint8_t)status); @@ -349,16 +319,12 @@ void BleScannerInterfaceImpl::OnMsftAdvMonitorEnable( #endif /** Sets the LE scan interval and window in units of N*0.625 msec */ -void BleScannerInterfaceImpl::SetScanParameters(int scanner_id, - uint8_t scan_type, - int scan_interval, - int scan_window, int scan_phy, +void BleScannerInterfaceImpl::SetScanParameters(int scanner_id, uint8_t scan_type, + int scan_interval, int scan_window, int scan_phy, Callback /* cb */) { log::info("in shim layer, scannerId={}", scanner_id); - if (BTM_BLE_ISVALID_PARAM(scan_interval, BTM_BLE_SCAN_INT_MIN, - BTM_BLE_EXT_SCAN_INT_MAX) && - BTM_BLE_ISVALID_PARAM(scan_window, BTM_BLE_SCAN_WIN_MIN, - BTM_BLE_EXT_SCAN_WIN_MAX)) { + if (BTM_BLE_ISVALID_PARAM(scan_interval, BTM_BLE_SCAN_INT_MIN, BTM_BLE_EXT_SCAN_INT_MAX) && + BTM_BLE_ISVALID_PARAM(scan_window, BTM_BLE_SCAN_WIN_MIN, BTM_BLE_EXT_SCAN_WIN_MAX)) { btm_cb.ble_ctr_cb.inq_var.scan_type = BTM_BLE_SCAN_MODE_ACTI; btm_cb.ble_ctr_cb.inq_var.scan_interval = scan_interval; btm_cb.ble_ctr_cb.inq_var.scan_window = scan_window; @@ -366,32 +332,28 @@ void BleScannerInterfaceImpl::SetScanParameters(int scanner_id, } bluetooth::shim::GetScanning()->SetScanParameters( - scanner_id, static_cast(scan_type), - scan_interval, scan_window, scan_phy); + scanner_id, static_cast(scan_type), scan_interval, + scan_window, scan_phy); } /* Configure the batchscan storage */ -void BleScannerInterfaceImpl::BatchscanConfigStorage( - int client_if, int batch_scan_full_max, int batch_scan_trunc_max, - int batch_scan_notify_threshold, Callback cb) { +void BleScannerInterfaceImpl::BatchscanConfigStorage(int client_if, int batch_scan_full_max, + int batch_scan_trunc_max, + int batch_scan_notify_threshold, Callback cb) { log::info("in shim layer"); - bluetooth::shim::GetScanning()->BatchScanConifgStorage( - batch_scan_full_max, batch_scan_trunc_max, batch_scan_notify_threshold, - client_if); + bluetooth::shim::GetScanning()->BatchScanConifgStorage(batch_scan_full_max, batch_scan_trunc_max, + batch_scan_notify_threshold, client_if); do_in_jni_thread(base::BindOnce(cb, btm_status_value(BTM_SUCCESS))); } /* Enable batchscan */ -void BleScannerInterfaceImpl::BatchscanEnable(int scan_mode, int scan_interval, - int scan_window, - int /* addr_type */, - int discard_rule, Callback cb) { +void BleScannerInterfaceImpl::BatchscanEnable(int scan_mode, int scan_interval, int scan_window, + int /* addr_type */, int discard_rule, Callback cb) { log::info("in shim layer"); auto batch_scan_mode = static_cast(scan_mode); - auto batch_scan_discard_rule = - static_cast(discard_rule); - bluetooth::shim::GetScanning()->BatchScanEnable( - batch_scan_mode, scan_window, scan_interval, batch_scan_discard_rule); + auto batch_scan_discard_rule = static_cast(discard_rule); + bluetooth::shim::GetScanning()->BatchScanEnable(batch_scan_mode, scan_window, scan_interval, + batch_scan_discard_rule); do_in_jni_thread(base::BindOnce(cb, btm_status_value(BTM_SUCCESS))); } @@ -403,28 +365,23 @@ void BleScannerInterfaceImpl::BatchscanDisable(Callback cb) { } /* Read out batchscan reports */ -void BleScannerInterfaceImpl::BatchscanReadReports(int client_if, - int scan_mode) { +void BleScannerInterfaceImpl::BatchscanReadReports(int client_if, int scan_mode) { log::info("in shim layer"); auto batch_scan_mode = static_cast(scan_mode); auto scanner_id = static_cast(client_if); - bluetooth::shim::GetScanning()->BatchScanReadReport(scanner_id, - batch_scan_mode); + bluetooth::shim::GetScanning()->BatchScanReadReport(scanner_id, batch_scan_mode); } bool btm_random_pseudo_to_identity_addr(RawAddress* random_pseudo, tBLE_ADDR_TYPE* p_identity_addr_type); -bool btm_identity_addr_to_random_pseudo(RawAddress* bd_addr, - tBLE_ADDR_TYPE* p_addr_type, +bool btm_identity_addr_to_random_pseudo(RawAddress* bd_addr, tBLE_ADDR_TYPE* p_addr_type, bool refresh); -extern tACL_CONN* btm_acl_for_bda(const RawAddress& bd_addr, - tBT_TRANSPORT transport); +extern tACL_CONN* btm_acl_for_bda(const RawAddress& bd_addr, tBT_TRANSPORT transport); -void BleScannerInterfaceImpl::StartSync(uint8_t sid, RawAddress address, - uint16_t skip, uint16_t timeout, - int reg_id) { +void BleScannerInterfaceImpl::StartSync(uint8_t sid, RawAddress address, uint16_t skip, + uint16_t timeout, int reg_id) { log::info("in shim layer"); tBLE_ADDR_TYPE address_type = BLE_ADDR_RANDOM; tINQ_DB_ENT* p_i = btm_inq_db_find(address); @@ -433,8 +390,8 @@ void BleScannerInterfaceImpl::StartSync(uint8_t sid, RawAddress address, } btm_random_pseudo_to_identity_addr(&address, &address_type); address_type &= ~BLE_ADDR_TYPE_ID_BIT; - bluetooth::shim::GetScanning()->StartSync( - sid, ToAddressWithType(address, address_type), skip, timeout, reg_id); + bluetooth::shim::GetScanning()->StartSync(sid, ToAddressWithType(address, address_type), skip, + timeout, reg_id); } void BleScannerInterfaceImpl::StopSync(uint16_t handle) { @@ -442,56 +399,45 @@ void BleScannerInterfaceImpl::StopSync(uint16_t handle) { bluetooth::shim::GetScanning()->StopSync(handle); } -void BleScannerInterfaceImpl::CancelCreateSync(uint8_t sid, - RawAddress address) { +void BleScannerInterfaceImpl::CancelCreateSync(uint8_t sid, RawAddress address) { log::info("in shim layer"); bluetooth::shim::GetScanning()->CancelCreateSync(sid, ToGdAddress(address)); } -void BleScannerInterfaceImpl::TransferSync(RawAddress address, - uint16_t service_data, - uint16_t sync_handle, - int pa_source) { +void BleScannerInterfaceImpl::TransferSync(RawAddress address, uint16_t service_data, + uint16_t sync_handle, int pa_source) { log::info("in shim layer"); tACL_CONN* p_acl = btm_acl_for_bda(address, BT_TRANSPORT_LE); - if (p_acl == NULL || !HCI_LE_PERIODIC_ADVERTISING_SYNC_TRANSFER_RECIPIENT( - p_acl->peer_le_features)) { + if (p_acl == NULL || + !HCI_LE_PERIODIC_ADVERTISING_SYNC_TRANSFER_RECIPIENT(p_acl->peer_le_features)) { log::error("[PAST] Remote doesn't support PAST"); - scanning_callbacks_->OnPeriodicSyncTransferred( - pa_source, BTM_MODE_UNSUPPORTED, address); + scanning_callbacks_->OnPeriodicSyncTransferred(pa_source, BTM_MODE_UNSUPPORTED, address); return; } - bluetooth::shim::GetScanning()->TransferSync(ToGdAddress(address), - p_acl->Handle(), service_data, + bluetooth::shim::GetScanning()->TransferSync(ToGdAddress(address), p_acl->Handle(), service_data, sync_handle, pa_source); } -void BleScannerInterfaceImpl::TransferSetInfo(RawAddress address, - uint16_t service_data, - uint8_t adv_handle, - int pa_source) { +void BleScannerInterfaceImpl::TransferSetInfo(RawAddress address, uint16_t service_data, + uint8_t adv_handle, int pa_source) { log::info("in shim layer"); tACL_CONN* p_acl = btm_acl_for_bda(address, BT_TRANSPORT_LE); - if (p_acl == NULL || !HCI_LE_PERIODIC_ADVERTISING_SYNC_TRANSFER_RECIPIENT( - p_acl->peer_le_features)) { + if (p_acl == NULL || + !HCI_LE_PERIODIC_ADVERTISING_SYNC_TRANSFER_RECIPIENT(p_acl->peer_le_features)) { log::error("[PAST] Remote doesn't support PAST"); - scanning_callbacks_->OnPeriodicSyncTransferred( - pa_source, BTM_MODE_UNSUPPORTED, address); + scanning_callbacks_->OnPeriodicSyncTransferred(pa_source, BTM_MODE_UNSUPPORTED, address); return; } - bluetooth::shim::GetScanning()->TransferSetInfo(ToGdAddress(address), - p_acl->Handle(), service_data, - adv_handle, pa_source); + bluetooth::shim::GetScanning()->TransferSetInfo(ToGdAddress(address), p_acl->Handle(), + service_data, adv_handle, pa_source); } -void BleScannerInterfaceImpl::SyncTxParameters(RawAddress addr, uint8_t mode, - uint16_t skip, uint16_t timeout, - int reg_id) { +void BleScannerInterfaceImpl::SyncTxParameters(RawAddress addr, uint8_t mode, uint16_t skip, + uint16_t timeout, int reg_id) { log::info("in shim layer"); - bluetooth::shim::GetScanning()->SyncTxParameters(ToGdAddress(addr), mode, - skip, timeout, reg_id); + bluetooth::shim::GetScanning()->SyncTxParameters(ToGdAddress(addr), mode, skip, timeout, reg_id); } void BleScannerInterfaceImpl::RegisterCallbacks(ScanningCallbacks* callbacks) { @@ -499,27 +445,26 @@ void BleScannerInterfaceImpl::RegisterCallbacks(ScanningCallbacks* callbacks) { scanning_callbacks_ = callbacks; } -void BleScannerInterfaceImpl::OnScannerRegistered( - const bluetooth::hci::Uuid app_uuid, bluetooth::hci::ScannerId scanner_id, - ScanningStatus status) { +void BleScannerInterfaceImpl::OnScannerRegistered(const bluetooth::hci::Uuid app_uuid, + bluetooth::hci::ScannerId scanner_id, + ScanningStatus status) { auto uuid = bluetooth::Uuid::From128BitBE(app_uuid.To128BitBE()); do_in_jni_thread(base::BindOnce(&ScanningCallbacks::OnScannerRegistered, - base::Unretained(scanning_callbacks_), uuid, - scanner_id, status)); + base::Unretained(scanning_callbacks_), uuid, scanner_id, status)); } -void BleScannerInterfaceImpl::OnSetScannerParameterComplete( - bluetooth::hci::ScannerId scanner_id, ScanningStatus status) { - do_in_jni_thread(base::BindOnce( - &ScanningCallbacks::OnSetScannerParameterComplete, - base::Unretained(scanning_callbacks_), scanner_id, status)); +void BleScannerInterfaceImpl::OnSetScannerParameterComplete(bluetooth::hci::ScannerId scanner_id, + ScanningStatus status) { + do_in_jni_thread(base::BindOnce(&ScanningCallbacks::OnSetScannerParameterComplete, + base::Unretained(scanning_callbacks_), scanner_id, status)); } -void BleScannerInterfaceImpl::OnScanResult( - uint16_t event_type, uint8_t address_type, bluetooth::hci::Address address, - uint8_t primary_phy, uint8_t secondary_phy, uint8_t advertising_sid, - int8_t tx_power, int8_t rssi, uint16_t periodic_advertising_interval, - std::vector advertising_data) { +void BleScannerInterfaceImpl::OnScanResult(uint16_t event_type, uint8_t address_type, + bluetooth::hci::Address address, uint8_t primary_phy, + uint8_t secondary_phy, uint8_t advertising_sid, + int8_t tx_power, int8_t rssi, + uint16_t periodic_advertising_interval, + std::vector advertising_data) { RawAddress raw_address = ToRawAddress(address); tBLE_ADDR_TYPE ble_addr_type = to_ble_addr_type(address_type); @@ -528,43 +473,38 @@ void BleScannerInterfaceImpl::OnScanResult( btm_ble_process_adv_addr(raw_address, &ble_addr_type); } - do_in_jni_thread(base::BindOnce( - &BleScannerInterfaceImpl::handle_remote_properties, - base::Unretained(this), raw_address, ble_addr_type, advertising_data)); + do_in_jni_thread(base::BindOnce(&BleScannerInterfaceImpl::handle_remote_properties, + base::Unretained(this), raw_address, ble_addr_type, + advertising_data)); do_in_jni_thread(base::BindOnce( - &ScanningCallbacks::OnScanResult, base::Unretained(scanning_callbacks_), - event_type, static_cast(address_type), raw_address, primary_phy, - secondary_phy, advertising_sid, tx_power, rssi, - periodic_advertising_interval, advertising_data)); + &ScanningCallbacks::OnScanResult, base::Unretained(scanning_callbacks_), event_type, + static_cast(address_type), raw_address, primary_phy, secondary_phy, + advertising_sid, tx_power, rssi, periodic_advertising_interval, advertising_data)); // TODO: Remove when StartInquiry in GD part implemented - btm_ble_process_adv_pkt_cont_for_inquiry( - event_type, ble_addr_type, raw_address, primary_phy, secondary_phy, - advertising_sid, tx_power, rssi, periodic_advertising_interval, - advertising_data); + btm_ble_process_adv_pkt_cont_for_inquiry(event_type, ble_addr_type, raw_address, primary_phy, + secondary_phy, advertising_sid, tx_power, rssi, + periodic_advertising_interval, advertising_data); } void BleScannerInterfaceImpl::OnTrackAdvFoundLost( - bluetooth::hci::AdvertisingFilterOnFoundOnLostInfo on_found_on_lost_info) { + bluetooth::hci::AdvertisingFilterOnFoundOnLostInfo on_found_on_lost_info) { AdvertisingTrackInfo track_info = {}; - RawAddress raw_address = - ToRawAddress(on_found_on_lost_info.advertiser_address); + RawAddress raw_address = ToRawAddress(on_found_on_lost_info.advertiser_address); if (on_found_on_lost_info.advertiser_address_type != BLE_ADDR_ANONYMOUS) { - btm_ble_process_adv_addr(raw_address, - &on_found_on_lost_info.advertiser_address_type); + btm_ble_process_adv_addr(raw_address, &on_found_on_lost_info.advertiser_address_type); } track_info.monitor_handle = on_found_on_lost_info.monitor_handle; track_info.advertiser_address = raw_address; - track_info.advertiser_address_type = - on_found_on_lost_info.advertiser_address_type; + track_info.advertiser_address_type = on_found_on_lost_info.advertiser_address_type; track_info.scanner_id = on_found_on_lost_info.scanner_id; track_info.filter_index = on_found_on_lost_info.filter_index; track_info.advertiser_state = on_found_on_lost_info.advertiser_state; track_info.advertiser_info_present = - static_cast(on_found_on_lost_info.advertiser_info_present); + static_cast(on_found_on_lost_info.advertiser_info_present); if (on_found_on_lost_info.advertiser_info_present == bluetooth::hci::AdvtInfoPresent::ADVT_INFO_PRESENT) { track_info.tx_power = on_found_on_lost_info.tx_power; @@ -573,119 +513,104 @@ void BleScannerInterfaceImpl::OnTrackAdvFoundLost( auto adv_data = on_found_on_lost_info.adv_packet; track_info.adv_packet_len = (uint8_t)adv_data.size(); track_info.adv_packet.reserve(adv_data.size()); - track_info.adv_packet.insert(track_info.adv_packet.end(), adv_data.begin(), - adv_data.end()); + track_info.adv_packet.insert(track_info.adv_packet.end(), adv_data.begin(), adv_data.end()); auto scan_rsp_data = on_found_on_lost_info.scan_response; track_info.scan_response_len = (uint8_t)scan_rsp_data.size(); track_info.scan_response.reserve(adv_data.size()); - track_info.scan_response.insert(track_info.scan_response.end(), - scan_rsp_data.begin(), scan_rsp_data.end()); + track_info.scan_response.insert(track_info.scan_response.end(), scan_rsp_data.begin(), + scan_rsp_data.end()); } do_in_jni_thread(base::BindOnce(&ScanningCallbacks::OnTrackAdvFoundLost, - base::Unretained(scanning_callbacks_), - track_info)); + base::Unretained(scanning_callbacks_), track_info)); } -void BleScannerInterfaceImpl::OnBatchScanReports(int client_if, int status, - int report_format, - int num_records, - std::vector data) { +void BleScannerInterfaceImpl::OnBatchScanReports(int client_if, int status, int report_format, + int num_records, std::vector data) { do_in_jni_thread(base::BindOnce(&ScanningCallbacks::OnBatchScanReports, - base::Unretained(scanning_callbacks_), - client_if, status, report_format, num_records, - data)); + base::Unretained(scanning_callbacks_), client_if, status, + report_format, num_records, data)); } void BleScannerInterfaceImpl::OnBatchScanThresholdCrossed(int client_if) { - do_in_jni_thread( - base::BindOnce(&ScanningCallbacks::OnBatchScanThresholdCrossed, - base::Unretained(scanning_callbacks_), client_if)); + do_in_jni_thread(base::BindOnce(&ScanningCallbacks::OnBatchScanThresholdCrossed, + base::Unretained(scanning_callbacks_), client_if)); } void BleScannerInterfaceImpl::OnPeriodicSyncStarted( - int reg_id, uint8_t status, uint16_t sync_handle, uint8_t advertising_sid, - bluetooth::hci::AddressWithType address_with_type, uint8_t phy, - uint16_t interval) { + int reg_id, uint8_t status, uint16_t sync_handle, uint8_t advertising_sid, + bluetooth::hci::AddressWithType address_with_type, uint8_t phy, uint16_t interval) { RawAddress raw_address = ToRawAddress(address_with_type.GetAddress()); - tBLE_ADDR_TYPE ble_addr_type = - to_ble_addr_type((uint8_t)address_with_type.GetAddressType()); + tBLE_ADDR_TYPE ble_addr_type = to_ble_addr_type((uint8_t)address_with_type.GetAddressType()); if (ble_addr_type & BLE_ADDR_TYPE_ID_BIT) { btm_identity_addr_to_random_pseudo(&raw_address, &ble_addr_type, true); } do_in_jni_thread(base::BindOnce(&ScanningCallbacks::OnPeriodicSyncStarted, - base::Unretained(scanning_callbacks_), reg_id, - status, sync_handle, advertising_sid, - static_cast(ble_addr_type), raw_address, - phy, interval)); + base::Unretained(scanning_callbacks_), reg_id, status, + sync_handle, advertising_sid, static_cast(ble_addr_type), + raw_address, phy, interval)); } -void BleScannerInterfaceImpl::OnPeriodicSyncReport(uint16_t sync_handle, - int8_t tx_power, int8_t rssi, - uint8_t status, +void BleScannerInterfaceImpl::OnPeriodicSyncReport(uint16_t sync_handle, int8_t tx_power, + int8_t rssi, uint8_t status, std::vector data) { do_in_jni_thread(base::BindOnce(&ScanningCallbacks::OnPeriodicSyncReport, - base::Unretained(scanning_callbacks_), - sync_handle, tx_power, rssi, status, - std::move(data))); + base::Unretained(scanning_callbacks_), sync_handle, tx_power, + rssi, status, std::move(data))); } void BleScannerInterfaceImpl::OnPeriodicSyncLost(uint16_t sync_handle) { do_in_jni_thread(base::BindOnce(&ScanningCallbacks::OnPeriodicSyncLost, - base::Unretained(scanning_callbacks_), - sync_handle)); + base::Unretained(scanning_callbacks_), sync_handle)); } -void BleScannerInterfaceImpl::OnPeriodicSyncTransferred( - int pa_source, uint8_t status, bluetooth::hci::Address address) { +void BleScannerInterfaceImpl::OnPeriodicSyncTransferred(int pa_source, uint8_t status, + bluetooth::hci::Address address) { do_in_jni_thread(base::BindOnce(&ScanningCallbacks::OnPeriodicSyncTransferred, - base::Unretained(scanning_callbacks_), - pa_source, status, ToRawAddress(address))); + base::Unretained(scanning_callbacks_), pa_source, status, + ToRawAddress(address))); } void BleScannerInterfaceImpl::OnBigInfoReport(uint16_t sync_handle, bool encrypted) { do_in_jni_thread(base::BindOnce(&ScanningCallbacks::OnBigInfoReport, - base::Unretained(scanning_callbacks_), - sync_handle, encrypted)); + base::Unretained(scanning_callbacks_), sync_handle, encrypted)); } void BleScannerInterfaceImpl::OnTimeout() {} -void BleScannerInterfaceImpl::OnFilterEnable( - bluetooth::hci::Enable /* enable */, uint8_t /* status */) {} -void BleScannerInterfaceImpl::OnFilterParamSetup( - uint8_t /* available_spaces */, bluetooth::hci::ApcfAction /* action */, - uint8_t /* status */) {} +void BleScannerInterfaceImpl::OnFilterEnable(bluetooth::hci::Enable /* enable */, + uint8_t /* status */) {} +void BleScannerInterfaceImpl::OnFilterParamSetup(uint8_t /* available_spaces */, + bluetooth::hci::ApcfAction /* action */, + uint8_t /* status */) {} void BleScannerInterfaceImpl::OnFilterConfigCallback( - bluetooth::hci::ApcfFilterType /* filter_type */, - uint8_t /* available_spaces */, bluetooth::hci::ApcfAction /* action */, - uint8_t /* status */) {} + bluetooth::hci::ApcfFilterType /* filter_type */, uint8_t /* available_spaces */, + bluetooth::hci::ApcfAction /* action */, uint8_t /* status */) {} bool BleScannerInterfaceImpl::parse_filter_command( - bluetooth::hci::AdvertisingPacketContentFilterCommand& - advertising_packet_content_filter_command, - ApcfCommand apcf_command) { + bluetooth::hci::AdvertisingPacketContentFilterCommand& + advertising_packet_content_filter_command, + ApcfCommand apcf_command) { advertising_packet_content_filter_command.filter_type = - static_cast(apcf_command.type); + static_cast(apcf_command.type); bluetooth::hci::Address address = ToGdAddress(apcf_command.address); advertising_packet_content_filter_command.address = address; advertising_packet_content_filter_command.application_address_type = - static_cast( - apcf_command.addr_type); + static_cast(apcf_command.addr_type); if (!apcf_command.uuid.IsEmpty()) { uint8_t uuid_len = apcf_command.uuid.GetShortestRepresentationSize(); switch (uuid_len) { case bluetooth::Uuid::kNumBytes16: { advertising_packet_content_filter_command.uuid = - bluetooth::hci::Uuid::From16Bit(apcf_command.uuid.As16Bit()); + bluetooth::hci::Uuid::From16Bit(apcf_command.uuid.As16Bit()); } break; case bluetooth::Uuid::kNumBytes32: { advertising_packet_content_filter_command.uuid = - bluetooth::hci::Uuid::From32Bit(apcf_command.uuid.As32Bit()); + bluetooth::hci::Uuid::From32Bit(apcf_command.uuid.As32Bit()); } break; case bluetooth::Uuid::kNumBytes128: { advertising_packet_content_filter_command.uuid = - bluetooth::hci::Uuid::From128BitBE(apcf_command.uuid.To128BitBE()); + bluetooth::hci::Uuid::From128BitBE(apcf_command.uuid.To128BitBE()); } break; default: log::warn("illegal UUID length {}", (uint16_t)uuid_len); @@ -698,16 +623,15 @@ bool BleScannerInterfaceImpl::parse_filter_command( switch (uuid_len) { case bluetooth::Uuid::kNumBytes16: { advertising_packet_content_filter_command.uuid_mask = - bluetooth::hci::Uuid::From16Bit(apcf_command.uuid_mask.As16Bit()); + bluetooth::hci::Uuid::From16Bit(apcf_command.uuid_mask.As16Bit()); } break; case bluetooth::Uuid::kNumBytes32: { advertising_packet_content_filter_command.uuid_mask = - bluetooth::hci::Uuid::From32Bit(apcf_command.uuid_mask.As32Bit()); + bluetooth::hci::Uuid::From32Bit(apcf_command.uuid_mask.As32Bit()); } break; case bluetooth::Uuid::kNumBytes128: { advertising_packet_content_filter_command.uuid_mask = - bluetooth::hci::Uuid::From128BitBE( - apcf_command.uuid_mask.To128BitBE()); + bluetooth::hci::Uuid::From128BitBE(apcf_command.uuid_mask.To128BitBE()); } break; default: log::warn("illegal UUID length {}", (uint16_t)uuid_len); @@ -715,32 +639,28 @@ bool BleScannerInterfaceImpl::parse_filter_command( } } - advertising_packet_content_filter_command.name.assign( - apcf_command.name.begin(), apcf_command.name.end()); + advertising_packet_content_filter_command.name.assign(apcf_command.name.begin(), + apcf_command.name.end()); advertising_packet_content_filter_command.company = apcf_command.company; - advertising_packet_content_filter_command.company_mask = - apcf_command.company_mask; + advertising_packet_content_filter_command.company_mask = apcf_command.company_mask; advertising_packet_content_filter_command.ad_type = apcf_command.ad_type; advertising_packet_content_filter_command.org_id = apcf_command.org_id; advertising_packet_content_filter_command.tds_flags = apcf_command.tds_flags; - advertising_packet_content_filter_command.tds_flags_mask = - apcf_command.tds_flags_mask; + advertising_packet_content_filter_command.tds_flags_mask = apcf_command.tds_flags_mask; advertising_packet_content_filter_command.meta_data_type = - static_cast( - apcf_command.meta_data_type); - advertising_packet_content_filter_command.meta_data.assign( - apcf_command.meta_data.begin(), apcf_command.meta_data.end()); - advertising_packet_content_filter_command.data.assign( - apcf_command.data.begin(), apcf_command.data.end()); - advertising_packet_content_filter_command.data_mask.assign( - apcf_command.data_mask.begin(), apcf_command.data_mask.end()); + static_cast(apcf_command.meta_data_type); + advertising_packet_content_filter_command.meta_data.assign(apcf_command.meta_data.begin(), + apcf_command.meta_data.end()); + advertising_packet_content_filter_command.data.assign(apcf_command.data.begin(), + apcf_command.data.end()); + advertising_packet_content_filter_command.data_mask.assign(apcf_command.data_mask.begin(), + apcf_command.data_mask.end()); advertising_packet_content_filter_command.irk = apcf_command.irk; return true; } -void BleScannerInterfaceImpl::handle_remote_properties( - RawAddress bd_addr, tBLE_ADDR_TYPE addr_type, - std::vector advertising_data) { +void BleScannerInterfaceImpl::handle_remote_properties(RawAddress bd_addr, tBLE_ADDR_TYPE addr_type, + std::vector advertising_data) { if (!bluetooth::shim::is_gd_stack_started_up()) { log::warn("Gd stack is stopped, return"); return; @@ -753,8 +673,8 @@ void BleScannerInterfaceImpl::handle_remote_properties( auto device_type = bluetooth::hci::DeviceType::LE; uint8_t flag_len; - const uint8_t* p_flag = AdvertiseDataParser::GetFieldByType( - advertising_data, BTM_BLE_AD_TYPE_FLAG, &flag_len); + const uint8_t* p_flag = + AdvertiseDataParser::GetFieldByType(advertising_data, BTM_BLE_AD_TYPE_FLAG, &flag_len); if (p_flag != NULL && flag_len != 0) { if ((BTM_BLE_BREDR_NOT_SPT & *p_flag) == 0) { @@ -764,11 +684,11 @@ void BleScannerInterfaceImpl::handle_remote_properties( uint8_t remote_name_len; const uint8_t* p_eir_remote_name = AdvertiseDataParser::GetFieldByType( - advertising_data, HCI_EIR_COMPLETE_LOCAL_NAME_TYPE, &remote_name_len); + advertising_data, HCI_EIR_COMPLETE_LOCAL_NAME_TYPE, &remote_name_len); if (p_eir_remote_name == NULL) { p_eir_remote_name = AdvertiseDataParser::GetFieldByType( - advertising_data, HCI_EIR_SHORTENED_LOCAL_NAME_TYPE, &remote_name_len); + advertising_data, HCI_EIR_SHORTENED_LOCAL_NAME_TYPE, &remote_name_len); } bt_bdname_t bdname = {0}; @@ -779,25 +699,22 @@ void BleScannerInterfaceImpl::handle_remote_properties( address_cache_.add(bd_addr); if (remote_name_len > BD_NAME_LEN + 1 || - (remote_name_len == BD_NAME_LEN + 1 && - p_eir_remote_name[BD_NAME_LEN] != '\0')) { - log::info("dropping invalid packet - device name too long: {}", - remote_name_len); + (remote_name_len == BD_NAME_LEN + 1 && p_eir_remote_name[BD_NAME_LEN] != '\0')) { + log::info("dropping invalid packet - device name too long: {}", remote_name_len); return; } memcpy(bdname.name, p_eir_remote_name, remote_name_len); - if (remote_name_len < BD_NAME_LEN + 1) + if (remote_name_len < BD_NAME_LEN + 1) { bdname.name[remote_name_len] = '\0'; - btif_dm_update_ble_remote_properties(bd_addr, bdname.name, kDevClassEmpty, - device_type); + } + btif_dm_update_ble_remote_properties(bd_addr, bdname.name, kDevClassEmpty, device_type); } } DEV_CLASS dev_class = btm_ble_get_appearance_as_cod(advertising_data); if (dev_class != kDevClassUnclassified) { - btif_dm_update_ble_remote_properties(bd_addr, bdname.name, dev_class, - device_type); + btif_dm_update_ble_remote_properties(bd_addr, bdname.name, dev_class, device_type); } auto* storage_module = bluetooth::shim::GetStorage(); @@ -805,16 +722,14 @@ void BleScannerInterfaceImpl::handle_remote_properties( // update device type auto mutation = storage_module->Modify(); - bluetooth::storage::Device device = - storage_module->GetDeviceByLegacyKey(address); + bluetooth::storage::Device device = storage_module->GetDeviceByLegacyKey(address); mutation.Add(device.SetDeviceType(device_type)); mutation.Commit(); // update address type auto mutation2 = storage_module->Modify(); bluetooth::storage::LeDevice le_device = device.Le(); - mutation2.Add( - le_device.SetAddressType((bluetooth::hci::AddressType)addr_type)); + mutation2.Add(le_device.SetAddressType((bluetooth::hci::AddressType)addr_type)); mutation2.Commit(); } @@ -830,7 +745,7 @@ void BleScannerInterfaceImpl::AddressCache::add(const RawAddress& p_bda) { } bool BleScannerInterfaceImpl::AddressCache::find(const RawAddress& p_bda) { - return (remote_bdaddr_cache_.find(p_bda) != remote_bdaddr_cache_.end()); + return remote_bdaddr_cache_.find(p_bda) != remote_bdaddr_cache_.end(); } void BleScannerInterfaceImpl::AddressCache::init(void) { @@ -848,9 +763,7 @@ BleScannerInterface* bluetooth::shim::get_ble_scanner_instance() { } void bluetooth::shim::init_scanning_manager() { - static_cast( - bluetooth::shim::get_ble_scanner_instance()) - ->Init(); + static_cast(bluetooth::shim::get_ble_scanner_instance())->Init(); } bool bluetooth::shim::is_ad_type_filter_supported() { @@ -859,42 +772,39 @@ bool bluetooth::shim::is_ad_type_filter_supported() { void bluetooth::shim::set_ad_type_rsi_filter(bool enable) { bluetooth::hci::AdvertisingFilterParameter advertising_filter_parameter; - bluetooth::shim::GetScanning()->ScanFilterParameterSetup( - bluetooth::hci::ApcfAction::DELETE, 0x00, advertising_filter_parameter); + bluetooth::shim::GetScanning()->ScanFilterParameterSetup(bluetooth::hci::ApcfAction::DELETE, 0x00, + advertising_filter_parameter); if (enable) { - std::vector filters = - {}; + std::vector filters = {}; bluetooth::hci::AdvertisingPacketContentFilterCommand filter{}; filter.filter_type = bluetooth::hci::ApcfFilterType::AD_TYPE; filter.ad_type = BTM_BLE_AD_TYPE_RSI; filters.push_back(filter); bluetooth::shim::GetScanning()->ScanFilterAdd(0x00, filters); - advertising_filter_parameter.delivery_mode = - bluetooth::hci::DeliveryMode::IMMEDIATE; + advertising_filter_parameter.delivery_mode = bluetooth::hci::DeliveryMode::IMMEDIATE; advertising_filter_parameter.feature_selection = kAllowADTypeFilter; advertising_filter_parameter.list_logic_type = kAllowADTypeFilter; advertising_filter_parameter.filter_logic_type = kFilterLogicOr; advertising_filter_parameter.rssi_high_thresh = kLowestRssiValue; - bluetooth::shim::GetScanning()->ScanFilterParameterSetup( - bluetooth::hci::ApcfAction::ADD, 0x00, advertising_filter_parameter); + bluetooth::shim::GetScanning()->ScanFilterParameterSetup(bluetooth::hci::ApcfAction::ADD, 0x00, + advertising_filter_parameter); } } void bluetooth::shim::set_empty_filter(bool enable) { bluetooth::hci::AdvertisingFilterParameter advertising_filter_parameter; - bluetooth::shim::GetScanning()->ScanFilterParameterSetup( - bluetooth::hci::ApcfAction::DELETE, 0x00, advertising_filter_parameter); + bluetooth::shim::GetScanning()->ScanFilterParameterSetup(bluetooth::hci::ApcfAction::DELETE, 0x00, + advertising_filter_parameter); if (enable) { /* Add an allow-all filter on index 0 */ - advertising_filter_parameter.delivery_mode = - bluetooth::hci::DeliveryMode::IMMEDIATE; + advertising_filter_parameter.delivery_mode = bluetooth::hci::DeliveryMode::IMMEDIATE; advertising_filter_parameter.feature_selection = kAllowAllFilter; advertising_filter_parameter.list_logic_type = kListLogicOr; advertising_filter_parameter.filter_logic_type = kFilterLogicOr; advertising_filter_parameter.rssi_high_thresh = kLowestRssiValue; - bluetooth::shim::GetScanning()->ScanFilterParameterSetup( - bluetooth::hci::ApcfAction::ADD, 0x00, advertising_filter_parameter); + bluetooth::shim::GetScanning()->ScanFilterParameterSetup(bluetooth::hci::ApcfAction::ADD, 0x00, + advertising_filter_parameter); } } @@ -905,21 +815,20 @@ void bluetooth::shim::set_target_announcements_filter(bool enable) { bluetooth::hci::AdvertisingFilterParameter advertising_filter_parameter = {}; bluetooth::shim::GetScanning()->ScanFilterParameterSetup( - bluetooth::hci::ApcfAction::DELETE, filter_index, - advertising_filter_parameter); + bluetooth::hci::ApcfAction::DELETE, filter_index, advertising_filter_parameter); - if (!enable) return; + if (!enable) { + return; + } - advertising_filter_parameter.delivery_mode = - bluetooth::hci::DeliveryMode::IMMEDIATE; + advertising_filter_parameter.delivery_mode = bluetooth::hci::DeliveryMode::IMMEDIATE; advertising_filter_parameter.feature_selection = kAllowServiceDataFilter; advertising_filter_parameter.list_logic_type = kListLogicOr; advertising_filter_parameter.filter_logic_type = kFilterLogicAnd; advertising_filter_parameter.rssi_high_thresh = kLowestRssiValue; /* Add targeted announcements filter on index 4 */ - std::vector - cap_bap_filter = {}; + std::vector cap_bap_filter = {}; bluetooth::hci::AdvertisingPacketContentFilterCommand cap_filter{}; cap_filter.filter_type = bluetooth::hci::ApcfFilterType::SERVICE_DATA; @@ -936,6 +845,5 @@ void bluetooth::shim::set_target_announcements_filter(bool enable) { bluetooth::shim::GetScanning()->ScanFilterAdd(filter_index, cap_bap_filter); bluetooth::shim::GetScanning()->ScanFilterParameterSetup( - bluetooth::hci::ApcfAction::ADD, filter_index, - advertising_filter_parameter); + bluetooth::hci::ApcfAction::ADD, filter_index, advertising_filter_parameter); } diff --git a/system/main/shim/link_connection_interface.h b/system/main/shim/link_connection_interface.h index 86d5975ae91..69245875bce 100644 --- a/system/main/shim/link_connection_interface.h +++ b/system/main/shim/link_connection_interface.h @@ -27,27 +27,21 @@ namespace bluetooth { namespace shim { class LinkConnectionInterface { - public: +public: virtual ~LinkConnectionInterface() {} - virtual void CreateClassicConnection( - const bluetooth::hci::Address& address) = 0; - virtual void CancelClassicConnection( - const bluetooth::hci::Address& address) = 0; - virtual void AcceptLeConnectionFrom( - const bluetooth::hci::AddressWithType& address_with_type, bool is_direct, - std::promise) = 0; - virtual void IgnoreLeConnectionFrom( - const bluetooth::hci::AddressWithType& address_with_type) = 0; - - virtual void DisconnectClassic(uint16_t handle, tHCI_REASON reason, - std::string comment) = 0; - virtual void DisconnectLe(uint16_t handle, tHCI_REASON reason, - std::string comment) = 0; - virtual void UpdateConnectionParameters( - uint16_t handle, uint16_t conn_int_min, uint16_t conn_int_max, - uint16_t conn_latency, uint16_t conn_timeout, uint16_t min_ce_len, - uint16_t max_ce_len) = 0; + virtual void CreateClassicConnection(const bluetooth::hci::Address& address) = 0; + virtual void CancelClassicConnection(const bluetooth::hci::Address& address) = 0; + virtual void AcceptLeConnectionFrom(const bluetooth::hci::AddressWithType& address_with_type, + bool is_direct, std::promise) = 0; + virtual void IgnoreLeConnectionFrom(const bluetooth::hci::AddressWithType& address_with_type) = 0; + + virtual void DisconnectClassic(uint16_t handle, tHCI_REASON reason, std::string comment) = 0; + virtual void DisconnectLe(uint16_t handle, tHCI_REASON reason, std::string comment) = 0; + virtual void UpdateConnectionParameters(uint16_t handle, uint16_t conn_int_min, + uint16_t conn_int_max, uint16_t conn_latency, + uint16_t conn_timeout, uint16_t min_ce_len, + uint16_t max_ce_len) = 0; }; } // namespace shim diff --git a/system/main/shim/metric_id_api.cc b/system/main/shim/metric_id_api.cc index cce6b050033..ea067e96160 100644 --- a/system/main/shim/metric_id_api.cc +++ b/system/main/shim/metric_id_api.cc @@ -27,32 +27,28 @@ namespace bluetooth { namespace shim { using CallbackGd = std::function; -bool InitMetricIdAllocator( - const std::unordered_map& paired_device_map, - CallbackLegacy save_id_callback, CallbackLegacy forget_device_callback) { +bool InitMetricIdAllocator(const std::unordered_map& paired_device_map, + CallbackLegacy save_id_callback, CallbackLegacy forget_device_callback) { std::unordered_map paired_device_map_gd; for (const auto& device : paired_device_map) { Address address = bluetooth::ToGdAddress(device.first); paired_device_map_gd[address] = device.second; } - CallbackGd save_id_callback_gd = [save_id_callback](const Address& address, - const int id) { + CallbackGd save_id_callback_gd = [save_id_callback](const Address& address, const int id) { return save_id_callback(bluetooth::ToRawAddress(address), id); }; - CallbackGd forget_device_callback_gd = - [forget_device_callback](const Address& address, const int id) { - return forget_device_callback(bluetooth::ToRawAddress(address), id); - }; - return MetricIdManager::GetInstance().Init( - paired_device_map_gd, save_id_callback_gd, forget_device_callback_gd); + CallbackGd forget_device_callback_gd = [forget_device_callback](const Address& address, + const int id) { + return forget_device_callback(bluetooth::ToRawAddress(address), id); + }; + return MetricIdManager::GetInstance().Init(paired_device_map_gd, save_id_callback_gd, + forget_device_callback_gd); } bool CloseMetricIdAllocator() { return MetricIdManager::GetInstance().Close(); } -bool IsEmptyMetricIdAllocator() { - return MetricIdManager::GetInstance().IsEmpty(); -} +bool IsEmptyMetricIdAllocator() { return MetricIdManager::GetInstance().IsEmpty(); } int AllocateIdFromMetricIdAllocator(const RawAddress& raw_address) { Address address = bluetooth::ToGdAddress(raw_address); diff --git a/system/main/shim/metric_id_api.h b/system/main/shim/metric_id_api.h index c8726ea68bb..9cb3cb7d2f0 100644 --- a/system/main/shim/metric_id_api.h +++ b/system/main/shim/metric_id_api.h @@ -18,12 +18,12 @@ #include #include + #include "types/raw_address.h" namespace bluetooth { namespace shim { -using CallbackLegacy = - std::function; +using CallbackLegacy = std::function; /** * Initialize the allocator * @@ -35,9 +35,8 @@ using CallbackLegacy = * successful id deletion for forgotten device, * @return true if successfully initialized */ -bool InitMetricIdAllocator( - const std::unordered_map& paired_device_map, - CallbackLegacy save_id_callback, CallbackLegacy forget_device_callback); +bool InitMetricIdAllocator(const std::unordered_map& paired_device_map, + CallbackLegacy save_id_callback, CallbackLegacy forget_device_callback); /** * Close the allocator. should be called when Bluetooth process is killed diff --git a/system/main/shim/metrics_api.cc b/system/main/shim/metrics_api.cc index 27969760106..cc4e60dd55e 100644 --- a/system/main/shim/metrics_api.cc +++ b/system/main/shim/metrics_api.cc @@ -27,146 +27,127 @@ using bluetooth::hci::Address; namespace bluetooth { namespace shim { -void LogMetricLinkLayerConnectionEvent( - const RawAddress* raw_address, uint32_t connection_handle, - android::bluetooth::DirectionEnum direction, uint16_t link_type, - uint32_t hci_cmd, uint16_t hci_event, uint16_t hci_ble_event, - uint16_t cmd_status, uint16_t reason_code) { +void LogMetricLinkLayerConnectionEvent(const RawAddress* raw_address, uint32_t connection_handle, + android::bluetooth::DirectionEnum direction, + uint16_t link_type, uint32_t hci_cmd, uint16_t hci_event, + uint16_t hci_ble_event, uint16_t cmd_status, + uint16_t reason_code) { Address address = Address::kEmpty; if (raw_address != nullptr) { address = bluetooth::ToGdAddress(*raw_address); } bluetooth::os::LogMetricLinkLayerConnectionEvent( - raw_address == nullptr ? nullptr : &address, connection_handle, direction, - link_type, hci_cmd, hci_event, hci_ble_event, cmd_status, reason_code); + raw_address == nullptr ? nullptr : &address, connection_handle, direction, link_type, + hci_cmd, hci_event, hci_ble_event, cmd_status, reason_code); } void LogMetricA2dpAudioUnderrunEvent(const RawAddress& raw_address, - uint64_t encoding_interval_millis, - int num_missing_pcm_bytes) { + uint64_t encoding_interval_millis, int num_missing_pcm_bytes) { Address address = bluetooth::ToGdAddress(raw_address); - bluetooth::os::LogMetricA2dpAudioUnderrunEvent( - address, encoding_interval_millis, num_missing_pcm_bytes); + bluetooth::os::LogMetricA2dpAudioUnderrunEvent(address, encoding_interval_millis, + num_missing_pcm_bytes); } void LogMetricA2dpAudioOverrunEvent(const RawAddress& raw_address, - uint64_t encoding_interval_millis, - int num_dropped_buffers, - int num_dropped_encoded_frames, - int num_dropped_encoded_bytes) { + uint64_t encoding_interval_millis, int num_dropped_buffers, + int num_dropped_encoded_frames, int num_dropped_encoded_bytes) { Address address = bluetooth::ToGdAddress(raw_address); - bluetooth::os::LogMetricA2dpAudioOverrunEvent( - address, encoding_interval_millis, num_dropped_buffers, - num_dropped_encoded_frames, num_dropped_encoded_bytes); + bluetooth::os::LogMetricA2dpAudioOverrunEvent(address, encoding_interval_millis, + num_dropped_buffers, num_dropped_encoded_frames, + num_dropped_encoded_bytes); } -void LogMetricA2dpPlaybackEvent(const RawAddress& raw_address, - int playback_state, int audio_coding_mode) { +void LogMetricA2dpPlaybackEvent(const RawAddress& raw_address, int playback_state, + int audio_coding_mode) { Address address = bluetooth::ToGdAddress(raw_address); - bluetooth::os::LogMetricA2dpPlaybackEvent(address, playback_state, - audio_coding_mode); + bluetooth::os::LogMetricA2dpPlaybackEvent(address, playback_state, audio_coding_mode); } -void LogMetricA2dpSessionMetricsEvent( - const RawAddress& raw_address, int64_t audio_duration_ms, - int media_timer_min_ms, int media_timer_max_ms, int media_timer_avg_ms, - int total_scheduling_count, int buffer_overruns_max_count, - int buffer_overruns_total, float buffer_underruns_average, - int buffer_underruns_count, int64_t codec_index, bool is_a2dp_offload) { +void LogMetricA2dpSessionMetricsEvent(const RawAddress& raw_address, int64_t audio_duration_ms, + int media_timer_min_ms, int media_timer_max_ms, + int media_timer_avg_ms, int total_scheduling_count, + int buffer_overruns_max_count, int buffer_overruns_total, + float buffer_underruns_average, int buffer_underruns_count, + int64_t codec_index, bool is_a2dp_offload) { Address address = bluetooth::ToGdAddress(raw_address); bluetooth::os::LogMetricA2dpSessionMetricsEvent( - address, audio_duration_ms, media_timer_min_ms, media_timer_max_ms, - media_timer_avg_ms, total_scheduling_count, buffer_overruns_max_count, - buffer_overruns_total, buffer_underruns_average, buffer_underruns_count, - codec_index, is_a2dp_offload); + address, audio_duration_ms, media_timer_min_ms, media_timer_max_ms, media_timer_avg_ms, + total_scheduling_count, buffer_overruns_max_count, buffer_overruns_total, + buffer_underruns_average, buffer_underruns_count, codec_index, is_a2dp_offload); } -void LogMetricHfpPacketLossStats(const RawAddress& raw_address, - int num_decoded_frames, - double packet_loss_ratio, - uint16_t codec_type) { +void LogMetricHfpPacketLossStats(const RawAddress& raw_address, int num_decoded_frames, + double packet_loss_ratio, uint16_t codec_type) { Address address = bluetooth::ToGdAddress(raw_address); - bluetooth::os::LogMetricHfpPacketLossStats(address, num_decoded_frames, - packet_loss_ratio, codec_type); + bluetooth::os::LogMetricHfpPacketLossStats(address, num_decoded_frames, packet_loss_ratio, + codec_type); } -void LogMetricMmcTranscodeRttStats(int maximum_rtt, double mean_rtt, - int num_requests, int codec_type) { - bluetooth::os::LogMetricMmcTranscodeRttStats(maximum_rtt, mean_rtt, - num_requests, codec_type); +void LogMetricMmcTranscodeRttStats(int maximum_rtt, double mean_rtt, int num_requests, + int codec_type) { + bluetooth::os::LogMetricMmcTranscodeRttStats(maximum_rtt, mean_rtt, num_requests, codec_type); } -void LogMetricReadRssiResult(const RawAddress& raw_address, uint16_t handle, - uint32_t cmd_status, int8_t rssi) { +void LogMetricReadRssiResult(const RawAddress& raw_address, uint16_t handle, uint32_t cmd_status, + int8_t rssi) { Address address = bluetooth::ToGdAddress(raw_address); bluetooth::os::LogMetricReadRssiResult(address, handle, cmd_status, rssi); } -void LogMetricReadFailedContactCounterResult(const RawAddress& raw_address, - uint16_t handle, - uint32_t cmd_status, - int32_t failed_contact_counter) { +void LogMetricReadFailedContactCounterResult(const RawAddress& raw_address, uint16_t handle, + uint32_t cmd_status, int32_t failed_contact_counter) { Address address = bluetooth::ToGdAddress(raw_address); - bluetooth::os::LogMetricReadFailedContactCounterResult( - address, handle, cmd_status, failed_contact_counter); + bluetooth::os::LogMetricReadFailedContactCounterResult(address, handle, cmd_status, + failed_contact_counter); } -void LogMetricReadTxPowerLevelResult(const RawAddress& raw_address, - uint16_t handle, uint32_t cmd_status, - int32_t transmit_power_level) { +void LogMetricReadTxPowerLevelResult(const RawAddress& raw_address, uint16_t handle, + uint32_t cmd_status, int32_t transmit_power_level) { Address address = bluetooth::ToGdAddress(raw_address); - bluetooth::os::LogMetricReadTxPowerLevelResult(address, handle, cmd_status, - transmit_power_level); + bluetooth::os::LogMetricReadTxPowerLevelResult(address, handle, cmd_status, transmit_power_level); } void LogMetricSmpPairingEvent(const RawAddress& raw_address, uint16_t smp_cmd, android::bluetooth::DirectionEnum direction, uint16_t smp_fail_reason) { Address address = bluetooth::ToGdAddress(raw_address); - bluetooth::os::LogMetricSmpPairingEvent(address, smp_cmd, direction, - smp_fail_reason); + bluetooth::os::LogMetricSmpPairingEvent(address, smp_cmd, direction, smp_fail_reason); } -void LogMetricClassicPairingEvent(const RawAddress& raw_address, - uint16_t handle, uint32_t hci_cmd, - uint16_t hci_event, uint16_t cmd_status, - uint16_t reason_code, int64_t event_value) { +void LogMetricClassicPairingEvent(const RawAddress& raw_address, uint16_t handle, uint32_t hci_cmd, + uint16_t hci_event, uint16_t cmd_status, uint16_t reason_code, + int64_t event_value) { Address address = bluetooth::ToGdAddress(raw_address); - bluetooth::os::LogMetricClassicPairingEvent(address, handle, hci_cmd, - hci_event, cmd_status, + bluetooth::os::LogMetricClassicPairingEvent(address, handle, hci_cmd, hci_event, cmd_status, reason_code, event_value); } -void LogMetricSdpAttribute(const RawAddress& raw_address, - uint16_t protocol_uuid, uint16_t attribute_id, - size_t attribute_size, const char* attribute_value) { +void LogMetricSdpAttribute(const RawAddress& raw_address, uint16_t protocol_uuid, + uint16_t attribute_id, size_t attribute_size, + const char* attribute_value) { Address address = bluetooth::ToGdAddress(raw_address); - bluetooth::os::LogMetricSdpAttribute(address, protocol_uuid, attribute_id, - attribute_size, attribute_value); + bluetooth::os::LogMetricSdpAttribute(address, protocol_uuid, attribute_id, attribute_size, + attribute_value); } -void LogMetricSocketConnectionState( - const RawAddress& raw_address, int port, int type, - android::bluetooth::SocketConnectionstateEnum connection_state, - int64_t tx_bytes, int64_t rx_bytes, int uid, int server_port, - android::bluetooth::SocketRoleEnum socket_role) { +void LogMetricSocketConnectionState(const RawAddress& raw_address, int port, int type, + android::bluetooth::SocketConnectionstateEnum connection_state, + int64_t tx_bytes, int64_t rx_bytes, int uid, int server_port, + android::bluetooth::SocketRoleEnum socket_role) { Address address = bluetooth::ToGdAddress(raw_address); - bluetooth::os::LogMetricSocketConnectionState( - address, port, type, connection_state, tx_bytes, rx_bytes, uid, - server_port, socket_role); -} - -void LogMetricManufacturerInfo( - const RawAddress& raw_address, - android::bluetooth::AddressTypeEnum address_type, - android::bluetooth::DeviceInfoSrcEnum source_type, - const std::string& source_name, const std::string& manufacturer, - const std::string& model, const std::string& hardware_version, - const std::string& software_version) { + bluetooth::os::LogMetricSocketConnectionState(address, port, type, connection_state, tx_bytes, + rx_bytes, uid, server_port, socket_role); +} + +void LogMetricManufacturerInfo(const RawAddress& raw_address, + android::bluetooth::AddressTypeEnum address_type, + android::bluetooth::DeviceInfoSrcEnum source_type, + const std::string& source_name, const std::string& manufacturer, + const std::string& model, const std::string& hardware_version, + const std::string& software_version) { Address address = bluetooth::ToGdAddress(raw_address); - bluetooth::os::LogMetricManufacturerInfo(address, address_type, source_type, - source_name, manufacturer, model, - hardware_version, software_version); + bluetooth::os::LogMetricManufacturerInfo(address, address_type, source_type, source_name, + manufacturer, model, hardware_version, software_version); } bool CountCounterMetrics(int32_t key, int64_t count) { @@ -178,14 +159,13 @@ bool CountCounterMetrics(int32_t key, int64_t count) { } void LogMetricBluetoothLEConnectionMetricEvent( - const RawAddress& raw_address, - android::bluetooth::le::LeConnectionOriginType origin_type, - android::bluetooth::le::LeConnectionType connection_type, - android::bluetooth::le::LeConnectionState transaction_state, - std::vector> argument_list) { - + const RawAddress& raw_address, android::bluetooth::le::LeConnectionOriginType origin_type, + android::bluetooth::le::LeConnectionType connection_type, + android::bluetooth::le::LeConnectionState transaction_state, + std::vector> argument_list) { Address address = bluetooth::ToGdAddress(raw_address); - bluetooth::os::LogMetricBluetoothLEConnectionMetricEvent(address, origin_type, connection_type, transaction_state, argument_list); + bluetooth::os::LogMetricBluetoothLEConnectionMetricEvent(address, origin_type, connection_type, + transaction_state, argument_list); } } // namespace shim diff --git a/system/main/shim/metrics_api.h b/system/main/shim/metrics_api.h index f36ac4e0a75..070ea8f2bce 100644 --- a/system/main/shim/metrics_api.h +++ b/system/main/shim/metrics_api.h @@ -41,11 +41,11 @@ namespace shim { * @param cmd_status Command status associated with this event, if any * @param reason_code Reason code associated with this event, if any */ -void LogMetricLinkLayerConnectionEvent( - const RawAddress* address, uint32_t connection_handle, - android::bluetooth::DirectionEnum direction, uint16_t link_type, - uint32_t hci_cmd, uint16_t hci_event, uint16_t hci_ble_event, - uint16_t cmd_status, uint16_t reason_code); +void LogMetricLinkLayerConnectionEvent(const RawAddress* address, uint32_t connection_handle, + android::bluetooth::DirectionEnum direction, + uint16_t link_type, uint32_t hci_cmd, uint16_t hci_event, + uint16_t hci_ble_event, uint16_t cmd_status, + uint16_t reason_code); /** * Log A2DP audio buffer underrun event @@ -55,8 +55,7 @@ void LogMetricLinkLayerConnectionEvent( * @param num_missing_pcm_bytes number of PCM bytes that cannot be read from * the source */ -void LogMetricA2dpAudioUnderrunEvent(const RawAddress& address, - uint64_t encoding_interval_millis, +void LogMetricA2dpAudioUnderrunEvent(const RawAddress& address, uint64_t encoding_interval_millis, int num_missing_pcm_bytes); /** @@ -70,10 +69,8 @@ void LogMetricA2dpAudioUnderrunEvent(const RawAddress& address, * @param num_dropped_encoded_bytes number of encoded bytes dropped from Tx * queue */ -void LogMetricA2dpAudioOverrunEvent(const RawAddress& address, - uint64_t encoding_interval_millis, - int num_dropped_buffers, - int num_dropped_encoded_frames, +void LogMetricA2dpAudioOverrunEvent(const RawAddress& address, uint64_t encoding_interval_millis, + int num_dropped_buffers, int num_dropped_encoded_frames, int num_dropped_encoded_bytes); /** @@ -83,8 +80,8 @@ void LogMetricA2dpAudioOverrunEvent(const RawAddress& address, * @param playback_state A2DP audio playback state, on/off * @param audio_coding_mode A2DP audio codec encoding mode, hw/sw */ -void LogMetricA2dpPlaybackEvent(const RawAddress& raw_address, - int playback_state, int audio_coding_mode); +void LogMetricA2dpPlaybackEvent(const RawAddress& raw_address, int playback_state, + int audio_coding_mode); /** * Log A2DP audio session metrics event @@ -105,12 +102,12 @@ void LogMetricA2dpPlaybackEvent(const RawAddress& raw_address, * @param codec_index A2DP codec index (SBC=0, AAC=1, etc...) * @param is_a2dp_offload if A2DP is offload */ -void LogMetricA2dpSessionMetricsEvent( - const RawAddress& address, int64_t audio_duration_ms, - int media_timer_min_ms, int media_timer_max_ms, int media_timer_avg_ms, - int total_scheduling_count, int buffer_overruns_max_count, - int buffer_overruns_total, float buffer_underruns_average, - int buffer_underruns_count, int64_t codec_index, bool is_a2dp_offload); +void LogMetricA2dpSessionMetricsEvent(const RawAddress& address, int64_t audio_duration_ms, + int media_timer_min_ms, int media_timer_max_ms, + int media_timer_avg_ms, int total_scheduling_count, + int buffer_overruns_max_count, int buffer_overruns_total, + float buffer_underruns_average, int buffer_underruns_count, + int64_t codec_index, bool is_a2dp_offload); /** * Log HFP audio capture packet loss statistics * @@ -119,8 +116,7 @@ void LogMetricA2dpSessionMetricsEvent( * @param packet_loss_ratio ratio of packet loss frames * @param codec_id codec ID of the packet (mSBC=2, LC3=3) */ -void LogMetricHfpPacketLossStats(const RawAddress& address, - int num_decoded_frames, +void LogMetricHfpPacketLossStats(const RawAddress& address, int num_decoded_frames, double packet_loss_ratio, uint16_t codec_id); /** @@ -131,8 +127,8 @@ void LogMetricHfpPacketLossStats(const RawAddress& address, * @param num_requests the number of transcoding requests in the session * @param codec_type codec type used in this session */ -void LogMetricMmcTranscodeRttStats(int maximum_rtt, double mean_rtt, - int num_requests, int codec_type); +void LogMetricMmcTranscodeRttStats(int maximum_rtt, double mean_rtt, int num_requests, + int codec_type); /** * Log read RSSI result @@ -143,8 +139,8 @@ void LogMetricMmcTranscodeRttStats(int maximum_rtt, double mean_rtt, * @param cmd_status command status from read RSSI command * @param rssi rssi value in dBm */ -void LogMetricReadRssiResult(const RawAddress& address, uint16_t handle, - uint32_t cmd_status, int8_t rssi); +void LogMetricReadRssiResult(const RawAddress& address, uint16_t handle, uint32_t cmd_status, + int8_t rssi); /** * Log failed contact counter report @@ -156,10 +152,8 @@ void LogMetricReadRssiResult(const RawAddress& address, uint16_t handle, * @param failed_contact_counter Number of consecutive failed contacts for a * connection corresponding to the Handle */ -void LogMetricReadFailedContactCounterResult(const RawAddress& address, - uint16_t handle, - uint32_t cmd_status, - int32_t failed_contact_counter); +void LogMetricReadFailedContactCounterResult(const RawAddress& address, uint16_t handle, + uint32_t cmd_status, int32_t failed_contact_counter); /** * Log transmit power level for a particular device after read @@ -172,8 +166,7 @@ void LogMetricReadFailedContactCounterResult(const RawAddress& address, * device */ void LogMetricReadTxPowerLevelResult(const RawAddress& address, uint16_t handle, - uint32_t cmd_status, - int32_t transmit_power_level); + uint32_t cmd_status, int32_t transmit_power_level); /** * Logs when there is an event related to Bluetooth Security Manager Protocol @@ -199,9 +192,8 @@ void LogMetricSmpPairingEvent(const RawAddress& address, uint16_t smp_cmd, * @param reason_code Reason code associated with this event * @param event_value A status value related to this specific event */ -void LogMetricClassicPairingEvent(const RawAddress& address, uint16_t handle, - uint32_t hci_cmd, uint16_t hci_event, - uint16_t cmd_status, uint16_t reason_code, +void LogMetricClassicPairingEvent(const RawAddress& address, uint16_t handle, uint32_t hci_cmd, + uint16_t hci_event, uint16_t cmd_status, uint16_t reason_code, int64_t event_value); /** @@ -214,9 +206,8 @@ void LogMetricClassicPairingEvent(const RawAddress& address, uint16_t handle, * @param attribute_value pointer to the attribute data, must be larger than * attribute_size */ -void LogMetricSdpAttribute(const RawAddress& address, uint16_t protocol_uuid, - uint16_t attribute_id, size_t attribute_size, - const char* attribute_value); +void LogMetricSdpAttribute(const RawAddress& address, uint16_t protocol_uuid, uint16_t attribute_id, + size_t attribute_size, const char* attribute_value); /** * Logs when there is a change in Bluetooth socket connection state @@ -233,11 +224,10 @@ void LogMetricSdpAttribute(const RawAddress& address, uint16_t protocol_uuid, * @param socket_role role of this socket, server or connection * @param uid socket owner's uid */ -void LogMetricSocketConnectionState( - const RawAddress& address, int port, int type, - android::bluetooth::SocketConnectionstateEnum connection_state, - int64_t tx_bytes, int64_t rx_bytes, int uid, int server_port, - android::bluetooth::SocketRoleEnum socket_role); +void LogMetricSocketConnectionState(const RawAddress& address, int port, int type, + android::bluetooth::SocketConnectionstateEnum connection_state, + int64_t tx_bytes, int64_t rx_bytes, int uid, int server_port, + android::bluetooth::SocketRoleEnum socket_role); /** * Logs when a Bluetooth device's manufacturer information is learnt @@ -250,20 +240,19 @@ void LogMetricSocketConnectionState( * @param hardware_version hardware version of this device * @param software_version software version of this device */ -void LogMetricManufacturerInfo( - const RawAddress& address, android::bluetooth::AddressTypeEnum address_type, - android::bluetooth::DeviceInfoSrcEnum source_type, - const std::string& source_name, const std::string& manufacturer, - const std::string& model, const std::string& hardware_version, - const std::string& software_version); +void LogMetricManufacturerInfo(const RawAddress& address, + android::bluetooth::AddressTypeEnum address_type, + android::bluetooth::DeviceInfoSrcEnum source_type, + const std::string& source_name, const std::string& manufacturer, + const std::string& model, const std::string& hardware_version, + const std::string& software_version); bool CountCounterMetrics(int32_t key, int64_t count); void LogMetricBluetoothLEConnectionMetricEvent( - const RawAddress& raw_address, - android::bluetooth::le::LeConnectionOriginType origin_type, - android::bluetooth::le::LeConnectionType connection_type, - android::bluetooth::le::LeConnectionState transaction_state, - std::vector> argument_list); + const RawAddress& raw_address, android::bluetooth::le::LeConnectionOriginType origin_type, + android::bluetooth::le::LeConnectionType connection_type, + android::bluetooth::le::LeConnectionState transaction_state, + std::vector> argument_list); } // namespace shim } // namespace bluetooth diff --git a/system/main/shim/shim.cc b/system/main/shim/shim.cc index 15494537e18..3e37c888ea1 100644 --- a/system/main/shim/shim.cc +++ b/system/main/shim/shim.cc @@ -31,12 +31,9 @@ static const hci_t* hci; void btu_hci_msg_process(BT_HDR* p_msg); -static void post_to_main_message_loop(const base::Location& from_here, - BT_HDR* p_msg) { - if (do_in_main_thread(from_here, base::Bind(&btu_hci_msg_process, p_msg)) != - BT_STATUS_SUCCESS) { - bluetooth::log::error(": do_in_main_thread failed from {}", - from_here.ToString()); +static void post_to_main_message_loop(const base::Location& from_here, BT_HDR* p_msg) { + if (do_in_main_thread(from_here, base::Bind(&btu_hci_msg_process, p_msg)) != BT_STATUS_SUCCESS) { + bluetooth::log::error(": do_in_main_thread failed from {}", from_here.ToString()); } } @@ -55,13 +52,12 @@ static future_t* GeneralShutDown() { return kReturnImmediate; } -EXPORT_SYMBOL extern const module_t gd_shim_module = { - .name = GD_SHIM_MODULE, - .init = kUnusedModuleApi, - .start_up = ShimModuleStartUp, - .shut_down = GeneralShutDown, - .clean_up = kUnusedModuleApi, - .dependencies = {kUnusedModuleDependencies}}; +EXPORT_SYMBOL extern const module_t gd_shim_module = {.name = GD_SHIM_MODULE, + .init = kUnusedModuleApi, + .start_up = ShimModuleStartUp, + .shut_down = GeneralShutDown, + .clean_up = kUnusedModuleApi, + .dependencies = {kUnusedModuleDependencies}}; bool bluetooth::shim::is_gd_stack_started_up() { return bluetooth::shim::Stack::GetInstance()->IsRunning(); diff --git a/system/main/shim/stack.cc b/system/main/shim/stack.cc index f4bed817f9f..f72adafaa65 100644 --- a/system/main/shim/stack.cc +++ b/system/main/shim/stack.cc @@ -99,13 +99,11 @@ void Stack::StartEverything() { Start(&modules); is_running_ = true; // Make sure the leaf modules are started - log::assert_that( - stack_manager_.GetInstance() != nullptr, - "assert failed: stack_manager_.GetInstance() != " - "nullptr"); - log::assert_that( - stack_manager_.GetInstance() != nullptr, - "assert failed: stack_manager_.GetInstance() != nullptr"); + log::assert_that(stack_manager_.GetInstance() != nullptr, + "assert failed: stack_manager_.GetInstance() != " + "nullptr"); + log::assert_that(stack_manager_.GetInstance() != nullptr, + "assert failed: stack_manager_.GetInstance() != nullptr"); if (stack_manager_.IsStarted()) { pimpl_->acl_ = new legacy::Acl(stack_handler_, legacy::GetAclInterface(), GetController()->GetLeFilterAcceptListSize(), @@ -120,8 +118,7 @@ void Stack::StartEverything() { bluetooth::shim::init_distance_measurement_manager(); } -void Stack::StartModuleStack(const ModuleList* modules, - const os::Thread* thread) { +void Stack::StartModuleStack(const ModuleList* modules, const os::Thread* thread) { std::lock_guard lock(mutex_); log::assert_that(!is_running_, "Gd stack already running"); stack_thread_ = const_cast(thread); @@ -138,8 +135,7 @@ void Stack::Start(ModuleList* modules) { log::assert_that(!is_running_, "Gd stack already running"); log::info("Starting Gd stack"); - stack_thread_ = - new os::Thread("gd_stack_thread", os::Thread::Priority::REAL_TIME); + stack_thread_ = new os::Thread("gd_stack_thread", os::Thread::Priority::REAL_TIME); stack_manager_.StartUp(modules, stack_thread_); stack_handler_ = new os::Handler(stack_thread_); @@ -195,8 +191,7 @@ const StackManager* Stack::GetStackManager() const { legacy::Acl* Stack::GetAcl() { std::lock_guard lock(mutex_); log::assert_that(is_running_, "assert failed: is_running_"); - log::assert_that(pimpl_->acl_ != nullptr, - "Acl shim layer has not been created"); + log::assert_that(pimpl_->acl_ != nullptr, "Acl shim layer has not been created"); return pimpl_->acl_; } diff --git a/system/main/shim/stack.h b/system/main/shim/stack.h index acff1b40b97..1d489505933 100644 --- a/system/main/shim/stack.h +++ b/system/main/shim/stack.h @@ -36,7 +36,7 @@ class Acl; // GD shim stack, having modes corresponding to legacy stack class Stack { - public: +public: static Stack* GetInstance(); Stack(); @@ -76,7 +76,7 @@ class Stack { size_t NumModules() const { return num_modules_; } - private: +private: struct impl; std::shared_ptr pimpl_; diff --git a/system/main/shim/utils.cc b/system/main/shim/utils.cc index bf42398ba45..357ecb74e17 100644 --- a/system/main/shim/utils.cc +++ b/system/main/shim/utils.cc @@ -22,27 +22,25 @@ namespace bluetooth { namespace shim { -void parse_gap_data(const std::vector &raw_data, - std::vector &output) { - size_t offset = 0; - while (offset < raw_data.size()) { - hci::GapData gap_data; - uint8_t len = raw_data[offset]; +void parse_gap_data(const std::vector &raw_data, std::vector &output) { + size_t offset = 0; + while (offset < raw_data.size()) { + hci::GapData gap_data; + uint8_t len = raw_data[offset]; - if (offset + len + 1 > raw_data.size()) { - log::warn("GAP data out of bound"); - break; - } - - auto begin = raw_data.begin() + offset; - auto end = begin + len + 1; // 1 byte for len - auto data_copy = std::make_shared>(begin, end); - bluetooth::packet::PacketView packet( - data_copy); - hci::GapData::Parse(&gap_data, packet.begin()); - output.push_back(gap_data); - offset += len + 1; // 1 byte for len + if (offset + len + 1 > raw_data.size()) { + log::warn("GAP data out of bound"); + break; } + + auto begin = raw_data.begin() + offset; + auto end = begin + len + 1; // 1 byte for len + auto data_copy = std::make_shared>(begin, end); + bluetooth::packet::PacketView packet(data_copy); + hci::GapData::Parse(&gap_data, packet.begin()); + output.push_back(gap_data); + offset += len + 1; // 1 byte for len + } } } // namespace shim diff --git a/system/main/shim/utils.h b/system/main/shim/utils.h index 56da2a0a0ae..2994f3603b0 100644 --- a/system/main/shim/utils.h +++ b/system/main/shim/utils.h @@ -26,7 +26,6 @@ namespace shim { * @param raw_data input, raw bytes * @param output vector of GapData */ -void parse_gap_data(const std::vector &raw_data, - std::vector &output); +void parse_gap_data(const std::vector &raw_data, std::vector &output); } // namespace shim } // namespace bluetooth diff --git a/system/main/stack_config.cc b/system/main/stack_config.cc index a2de7e71302..ae5ebc4da51 100644 --- a/system/main/stack_config.cc +++ b/system/main/stack_config.cc @@ -35,14 +35,12 @@ const char* PTS_DISABLE_SDP_LE_PAIR = "PTS_DisableSDPOnLEPair"; const char* PTS_SMP_PAIRING_OPTIONS_KEY = "PTS_SmpOptions"; const char* PTS_SMP_FAILURE_CASE_KEY = "PTS_SmpFailureCase"; const char* PTS_FORCE_EATT_FOR_NOTIFICATIONS = "PTS_ForceEattForNotifications"; -const char* PTS_CONNECT_EATT_UNCONDITIONALLY = - "PTS_ConnectEattUncondictionally"; +const char* PTS_CONNECT_EATT_UNCONDITIONALLY = "PTS_ConnectEattUncondictionally"; const char* PTS_CONNECT_EATT_UNENCRYPTED = "PTS_ConnectEattUnencrypted"; const char* PTS_BROADCAST_UNENCRYPTED = "PTS_BroadcastUnencrypted"; const char* PTS_FORCE_LE_AUDIO_MULTIPLE_CONTEXTS_METADATA = - "PTS_ForceLeAudioMultipleContextsMetadata"; -const char* PTS_EATT_PERIPHERAL_COLLISION_SUPPORT = - "PTS_EattPeripheralCollionSupport"; + "PTS_ForceLeAudioMultipleContextsMetadata"; +const char* PTS_EATT_PERIPHERAL_COLLISION_SUPPORT = "PTS_EattPeripheralCollionSupport"; const char* PTS_EATT_USE_FOR_ALL_SERVICES = "PTS_UseEattForAllServices"; const char* PTS_L2CAP_ECOC_UPPER_TESTER = "PTS_L2capEcocUpperTester"; const char* PTS_L2CAP_ECOC_MIN_KEY_SIZE = "PTS_L2capEcocMinKeySize"; @@ -50,8 +48,7 @@ const char* PTS_L2CAP_ECOC_INITIAL_CHAN_CNT = "PTS_L2capEcocInitialChanCnt"; const char* PTS_L2CAP_ECOC_CONNECT_REMAINING = "PTS_L2capEcocConnectRemaining"; const char* PTS_L2CAP_ECOC_SEND_NUM_OF_SDU = "PTS_L2capEcocSendNumOfSdu"; const char* PTS_L2CAP_ECOC_RECONFIGURE = "PTS_L2capEcocReconfigure"; -const char* PTS_BROADCAST_AUDIO_CONFIG_OPTION = - "PTS_BroadcastAudioConfigOption"; +const char* PTS_BROADCAST_AUDIO_CONFIG_OPTION = "PTS_BroadcastAudioConfigOption"; const char* PTS_LE_AUDIO_SUSPEND_STREAMING = "PTS_LeAudioSuspendStreaming"; static std::unique_ptr config; @@ -86,73 +83,61 @@ static future_t* clean_up() { return future_new_immediate(FUTURE_SUCCESS); } -EXPORT_SYMBOL extern const module_t stack_config_module = { - .name = STACK_CONFIG_MODULE, - .init = init, - .start_up = NULL, - .shut_down = NULL, - .clean_up = clean_up, - .dependencies = {NULL}}; +EXPORT_SYMBOL extern const module_t stack_config_module = {.name = STACK_CONFIG_MODULE, + .init = init, + .start_up = NULL, + .shut_down = NULL, + .clean_up = clean_up, + .dependencies = {NULL}}; // Interface functions static bool get_pts_avrcp_test(void) { - return config_get_bool(*config, CONFIG_DEFAULT_SECTION, PTS_AVRCP_TEST, - false); + return config_get_bool(*config, CONFIG_DEFAULT_SECTION, PTS_AVRCP_TEST, false); } static bool get_pts_secure_only_mode(void) { - return config_get_bool(*config, CONFIG_DEFAULT_SECTION, PTS_SECURE_ONLY_MODE, - false); + return config_get_bool(*config, CONFIG_DEFAULT_SECTION, PTS_SECURE_ONLY_MODE, false); } static bool get_pts_conn_updates_disabled(void) { - return config_get_bool(*config, CONFIG_DEFAULT_SECTION, - PTS_LE_CONN_UPDATED_DISABLED, false); + return config_get_bool(*config, CONFIG_DEFAULT_SECTION, PTS_LE_CONN_UPDATED_DISABLED, false); } static bool get_pts_crosskey_sdp_disable(void) { - return config_get_bool(*config, CONFIG_DEFAULT_SECTION, - PTS_DISABLE_SDP_LE_PAIR, false); + return config_get_bool(*config, CONFIG_DEFAULT_SECTION, PTS_DISABLE_SDP_LE_PAIR, false); } static const std::string* get_pts_smp_options(void) { - return config_get_string(*config, CONFIG_DEFAULT_SECTION, - PTS_SMP_PAIRING_OPTIONS_KEY, NULL); + return config_get_string(*config, CONFIG_DEFAULT_SECTION, PTS_SMP_PAIRING_OPTIONS_KEY, NULL); } static int get_pts_smp_failure_case(void) { - return config_get_int(*config, CONFIG_DEFAULT_SECTION, - PTS_SMP_FAILURE_CASE_KEY, 0); + return config_get_int(*config, CONFIG_DEFAULT_SECTION, PTS_SMP_FAILURE_CASE_KEY, 0); } static bool get_pts_force_eatt_for_notifications(void) { - return config_get_bool(*config, CONFIG_DEFAULT_SECTION, - PTS_FORCE_EATT_FOR_NOTIFICATIONS, false); + return config_get_bool(*config, CONFIG_DEFAULT_SECTION, PTS_FORCE_EATT_FOR_NOTIFICATIONS, false); } static bool get_pts_connect_eatt_unconditionally(void) { - return config_get_bool(*config, CONFIG_DEFAULT_SECTION, - PTS_CONNECT_EATT_UNCONDITIONALLY, false); + return config_get_bool(*config, CONFIG_DEFAULT_SECTION, PTS_CONNECT_EATT_UNCONDITIONALLY, false); } static bool get_pts_connect_eatt_before_encryption(void) { - return config_get_bool(*config, CONFIG_DEFAULT_SECTION, - PTS_CONNECT_EATT_UNENCRYPTED, false); + return config_get_bool(*config, CONFIG_DEFAULT_SECTION, PTS_CONNECT_EATT_UNENCRYPTED, false); } static bool get_pts_unencrypt_broadcast(void) { - return config_get_bool(*config, CONFIG_DEFAULT_SECTION, - PTS_BROADCAST_UNENCRYPTED, false); + return config_get_bool(*config, CONFIG_DEFAULT_SECTION, PTS_BROADCAST_UNENCRYPTED, false); } static bool get_pts_eatt_peripheral_collision_support(void) { - return config_get_bool(*config, CONFIG_DEFAULT_SECTION, - PTS_EATT_PERIPHERAL_COLLISION_SUPPORT, false); + return config_get_bool(*config, CONFIG_DEFAULT_SECTION, PTS_EATT_PERIPHERAL_COLLISION_SUPPORT, + false); } static bool get_pts_use_eatt_for_all_services(void) { - return config_get_bool(*config, CONFIG_DEFAULT_SECTION, - PTS_EATT_USE_FOR_ALL_SERVICES, false); + return config_get_bool(*config, CONFIG_DEFAULT_SECTION, PTS_EATT_USE_FOR_ALL_SERVICES, false); } static bool get_pts_force_le_audio_multiple_contexts_metadata(void) { @@ -161,33 +146,27 @@ static bool get_pts_force_le_audio_multiple_contexts_metadata(void) { } static bool get_pts_l2cap_ecoc_upper_tester(void) { - return config_get_bool(*config, CONFIG_DEFAULT_SECTION, - PTS_L2CAP_ECOC_UPPER_TESTER, false); + return config_get_bool(*config, CONFIG_DEFAULT_SECTION, PTS_L2CAP_ECOC_UPPER_TESTER, false); } static int get_pts_l2cap_ecoc_min_key_size(void) { - return config_get_int(*config, CONFIG_DEFAULT_SECTION, - PTS_L2CAP_ECOC_MIN_KEY_SIZE, -1); + return config_get_int(*config, CONFIG_DEFAULT_SECTION, PTS_L2CAP_ECOC_MIN_KEY_SIZE, -1); } static int get_pts_l2cap_ecoc_initial_chan_cnt(void) { - return config_get_int(*config, CONFIG_DEFAULT_SECTION, - PTS_L2CAP_ECOC_INITIAL_CHAN_CNT, -1); + return config_get_int(*config, CONFIG_DEFAULT_SECTION, PTS_L2CAP_ECOC_INITIAL_CHAN_CNT, -1); } static bool get_pts_l2cap_ecoc_connect_remaining(void) { - return config_get_bool(*config, CONFIG_DEFAULT_SECTION, - PTS_L2CAP_ECOC_CONNECT_REMAINING, false); + return config_get_bool(*config, CONFIG_DEFAULT_SECTION, PTS_L2CAP_ECOC_CONNECT_REMAINING, false); } static int get_pts_l2cap_ecoc_send_num_of_sdu(void) { - return config_get_int(*config, CONFIG_DEFAULT_SECTION, - PTS_L2CAP_ECOC_SEND_NUM_OF_SDU, -1); + return config_get_int(*config, CONFIG_DEFAULT_SECTION, PTS_L2CAP_ECOC_SEND_NUM_OF_SDU, -1); } static bool get_pts_l2cap_ecoc_reconfigure(void) { - return config_get_bool(*config, CONFIG_DEFAULT_SECTION, - PTS_L2CAP_ECOC_RECONFIGURE, false); + return config_get_bool(*config, CONFIG_DEFAULT_SECTION, PTS_L2CAP_ECOC_RECONFIGURE, false); } static const std::string* get_pts_broadcast_audio_config_options(void) { @@ -195,39 +174,37 @@ static const std::string* get_pts_broadcast_audio_config_options(void) { log::info("Config isn't ready, use default option"); return NULL; } - return config_get_string(*config, CONFIG_DEFAULT_SECTION, - PTS_BROADCAST_AUDIO_CONFIG_OPTION, NULL); + return config_get_string(*config, CONFIG_DEFAULT_SECTION, PTS_BROADCAST_AUDIO_CONFIG_OPTION, + NULL); } static bool get_pts_le_audio_disable_ases_before_stopping(void) { - return config_get_bool(*config, CONFIG_DEFAULT_SECTION, - PTS_LE_AUDIO_SUSPEND_STREAMING, false); + return config_get_bool(*config, CONFIG_DEFAULT_SECTION, PTS_LE_AUDIO_SUSPEND_STREAMING, false); } static config_t* get_all(void) { return config.get(); } -const stack_config_t interface = { - get_pts_avrcp_test, - get_pts_secure_only_mode, - get_pts_conn_updates_disabled, - get_pts_crosskey_sdp_disable, - get_pts_smp_options, - get_pts_smp_failure_case, - get_pts_force_eatt_for_notifications, - get_pts_connect_eatt_unconditionally, - get_pts_connect_eatt_before_encryption, - get_pts_unencrypt_broadcast, - get_pts_eatt_peripheral_collision_support, - get_pts_use_eatt_for_all_services, - get_pts_force_le_audio_multiple_contexts_metadata, - get_pts_l2cap_ecoc_upper_tester, - get_pts_l2cap_ecoc_min_key_size, - get_pts_l2cap_ecoc_initial_chan_cnt, - get_pts_l2cap_ecoc_connect_remaining, - get_pts_l2cap_ecoc_send_num_of_sdu, - get_pts_l2cap_ecoc_reconfigure, - get_pts_broadcast_audio_config_options, - get_pts_le_audio_disable_ases_before_stopping, - get_all}; +const stack_config_t interface = {get_pts_avrcp_test, + get_pts_secure_only_mode, + get_pts_conn_updates_disabled, + get_pts_crosskey_sdp_disable, + get_pts_smp_options, + get_pts_smp_failure_case, + get_pts_force_eatt_for_notifications, + get_pts_connect_eatt_unconditionally, + get_pts_connect_eatt_before_encryption, + get_pts_unencrypt_broadcast, + get_pts_eatt_peripheral_collision_support, + get_pts_use_eatt_for_all_services, + get_pts_force_le_audio_multiple_contexts_metadata, + get_pts_l2cap_ecoc_upper_tester, + get_pts_l2cap_ecoc_min_key_size, + get_pts_l2cap_ecoc_initial_chan_cnt, + get_pts_l2cap_ecoc_connect_remaining, + get_pts_l2cap_ecoc_send_num_of_sdu, + get_pts_l2cap_ecoc_reconfigure, + get_pts_broadcast_audio_config_options, + get_pts_le_audio_disable_ases_before_stopping, + get_all}; const stack_config_t* stack_config_get_interface(void) { return &interface; } diff --git a/system/main/test/common_stack_test.cc b/system/main/test/common_stack_test.cc index 3f137c1530a..674471804c1 100644 --- a/system/main/test/common_stack_test.cc +++ b/system/main/test/common_stack_test.cc @@ -25,11 +25,7 @@ using namespace testing; // Ensure default to_test operatives provide expect output for a sample subset. TEST(CommonStackTest, any_to_text_unknown_default) { - ASSERT_STREQ( - "UNKNOWN[255]", - gatt_client_event_text(static_cast(255)).c_str()); - ASSERT_STREQ("UNKNOWN[255]", - preferred_role_text(static_cast(255)).c_str()); - ASSERT_TRUE(bta_hh_status_text(static_cast(255)) - .starts_with("Unknown")); + ASSERT_STREQ("UNKNOWN[255]", gatt_client_event_text(static_cast(255)).c_str()); + ASSERT_STREQ("UNKNOWN[255]", preferred_role_text(static_cast(255)).c_str()); + ASSERT_TRUE(bta_hh_status_text(static_cast(255)).starts_with("Unknown")); } diff --git a/system/main/test/main_shim_dumpsys_test.cc b/system/main/test/main_shim_dumpsys_test.cc index 06f89a50339..cf8aca3f8b9 100644 --- a/system/main/test/main_shim_dumpsys_test.cc +++ b/system/main/test/main_shim_dumpsys_test.cc @@ -41,8 +41,8 @@ constexpr char kReadOnlyDebuggableProperty[] = "ro.debuggable"; } // namespace class MainShimDumpsysTest : public testing::Test { - public: - protected: +public: +protected: void SetUp() override { bluetooth::common::InitFlags::SetAllForTesting(); @@ -64,8 +64,7 @@ TEST_F(MainShimDumpsysTest, dumpsys_developer) { std::promise promise; auto future = promise.get_future(); - stack_manager_.GetInstance()->Dump(STDOUT_FILENO, nullptr, - std::move(promise)); + stack_manager_.GetInstance()->Dump(STDOUT_FILENO, nullptr, std::move(promise)); future.get(); } @@ -74,7 +73,6 @@ TEST_F(MainShimDumpsysTest, dumpsys_user) { std::promise promise; auto future = promise.get_future(); - stack_manager_.GetInstance()->Dump(STDOUT_FILENO, nullptr, - std::move(promise)); + stack_manager_.GetInstance()->Dump(STDOUT_FILENO, nullptr, std::move(promise)); future.get(); } diff --git a/system/main/test/main_shim_stack_dumpsys_test.cc b/system/main/test/main_shim_stack_dumpsys_test.cc index 7cdd262e405..30e6df12250 100644 --- a/system/main/test/main_shim_stack_dumpsys_test.cc +++ b/system/main/test/main_shim_stack_dumpsys_test.cc @@ -50,7 +50,7 @@ const packet_fragmenter_t* packet_fragmenter_get_interface() { return nullptr; } // main::shim::hci_layer bluetooth::common::TimestamperInMilliseconds - timestamper_in_milliseconds; // main::shim::le_scanning_manager + timestamper_in_milliseconds; // main::shim::le_scanning_manager namespace { constexpr char kLogTagStopped[] = "STOPPED"; @@ -72,7 +72,7 @@ inline void log_tag(std::string tag) { } class MainThread { - public: +public: MainThread() { main_thread_start_up(); post_on_bt_main([]() { log::info("<=== tid Main loop started"); }); @@ -83,7 +83,7 @@ class MainThread { main_thread_shut_down(); } - private: +private: void sync_main_handler() { std::promise promise = std::promise(); std::future future = promise.get_future(); @@ -93,7 +93,7 @@ class MainThread { }; class TestStackManager { - public: +public: TestStackManager() { // Stack manager is started in the test after each test uses the default // or adds their own modules @@ -112,19 +112,22 @@ class TestStackManager { } void Start() { - if (stack_started_) return; + if (stack_started_) { + return; + } log::info("Starting up stack manager"); stack_started_ = true; bluetooth::os::Thread* stack_thread = new bluetooth::os::Thread( - kTestStackThreadName, bluetooth::os::Thread::Priority::NORMAL); - bluetooth::shim::Stack::GetInstance()->StartModuleStack(&modules_, - stack_thread); + kTestStackThreadName, bluetooth::os::Thread::Priority::NORMAL); + bluetooth::shim::Stack::GetInstance()->StartModuleStack(&modules_, stack_thread); bluetooth::shim::Stack::GetInstance()->GetHandler()->Call( - []() { log::info("<=== tid GD Event loop started"); }); + []() { log::info("<=== tid GD Event loop started"); }); } void Stop() { - if (!stack_started_) return; + if (!stack_started_) { + return; + } stack_started_ = false; bluetooth::shim::Stack::GetInstance()->Stop(); } @@ -133,14 +136,12 @@ class TestStackManager { // if stack manager has not started or shutdown template static T* GetUnsafeModule() { - return bluetooth::shim::Stack::GetInstance() - ->GetStackManager() - ->GetInstance(); + return bluetooth::shim::Stack::GetInstance()->GetStackManager()->GetInstance(); } size_t NumModules() const { return modules_.NumModules(); } - private: +private: bluetooth::ModuleList modules_; bool stack_started_{false}; }; @@ -160,24 +161,22 @@ struct TestData { } // namespace -class TestStackDumpsysBase : public bluetooth::Module, - public ModuleMainloop, - public ModuleJniloop { - public: +class TestStackDumpsysBase : public bluetooth::Module, public ModuleMainloop, public ModuleJniloop { +public: TestStackDumpsysBase(const TestStackDumpsysBase&) = delete; TestStackDumpsysBase& operator=(const TestStackDumpsysBase&) = delete; - virtual ~TestStackDumpsysBase(){}; + virtual ~TestStackDumpsysBase() {} static const ModuleFactory Factory; virtual void TestMethod(TestData test_data) const { log::info("Test base class iter:{} tag:{}", test_data.iter, test_data.tag); } - protected: - void ListDependencies(ModuleList* /* list */) const override{}; - void Start() override { log::error("Started TestStackDumpsysBase"); }; - void Stop() override { log::error("Stopped TestStackDumpsysBase"); }; +protected: + void ListDependencies(ModuleList* /* list */) const override {} + void Start() override { log::error("Started TestStackDumpsysBase"); } + void Stop() override { log::error("Stopped TestStackDumpsysBase"); } std::string ToString() const override { return std::string("TestFunction"); } TestStackDumpsysBase() = default; @@ -188,7 +187,7 @@ struct StackRunningData { }; class TestStackDumpsys1 : public TestStackDumpsysBase { - public: +public: TestStackDumpsys1(const TestStackDumpsys1&) = delete; TestStackDumpsys1& operator=(const TestStackDumpsys1&) = delete; virtual ~TestStackDumpsys1() = default; @@ -198,7 +197,7 @@ class TestStackDumpsys1 : public TestStackDumpsysBase { void TestMethod(TestData test_data) const override; void IsStackRunning(StackRunningData stack_running_data) const; - private: +private: struct impl; std::shared_ptr impl_; TestStackDumpsys1(); @@ -207,13 +206,12 @@ class TestStackDumpsys1 : public TestStackDumpsysBase { struct TestStackDumpsys1::impl : public ModuleMainloop, public ModuleJniloop { void test(TestData test_data) { TestCallbackData callback_data{ - .iter = test_data.iter, - .tag = std::string(__func__), + .iter = test_data.iter, + .tag = std::string(__func__), }; - PostFunctionOnMain( - [](std::function callback, - TestCallbackData data) { callback(data); }, - test_data.callback, callback_data); + PostFunctionOnMain([](std::function callback, + TestCallbackData data) { callback(data); }, + test_data.callback, callback_data); } void is_stack_running(StackRunningData stack_running_data) const { bool is_running = bluetooth::shim::Stack::GetInstance()->IsRunning(); @@ -231,14 +229,12 @@ void TestStackDumpsys1::TestMethod(TestData test_data) const { PostMethodOnMain(impl_, &impl::test, test_data); } -void TestStackDumpsys1::IsStackRunning( - StackRunningData stack_running_data) const { - GetHandler()->CallOn(impl_.get(), &impl::is_stack_running, - stack_running_data); +void TestStackDumpsys1::IsStackRunning(StackRunningData stack_running_data) const { + GetHandler()->CallOn(impl_.get(), &impl::is_stack_running, stack_running_data); } class TestStackDumpsys2 : public TestStackDumpsysBase { - public: +public: TestStackDumpsys2(const TestStackDumpsys2&) = delete; TestStackDumpsys2& operator=(const TestStackDumpsys2&) = delete; virtual ~TestStackDumpsys2() = default; @@ -247,7 +243,7 @@ class TestStackDumpsys2 : public TestStackDumpsysBase { void TestMethod(TestData test_data) const override; - private: +private: struct impl; std::shared_ptr impl_; TestStackDumpsys2(); @@ -256,13 +252,12 @@ class TestStackDumpsys2 : public TestStackDumpsysBase { struct TestStackDumpsys2::impl : public ModuleMainloop, public ModuleJniloop { void test(TestData test_data) { TestCallbackData callback_data{ - .iter = test_data.iter, - .tag = std::string(__func__), + .iter = test_data.iter, + .tag = std::string(__func__), }; - PostFunctionOnMain( - [](std::function callback, - TestCallbackData data) { callback(data); }, - test_data.callback, callback_data); + PostFunctionOnMain([](std::function callback, + TestCallbackData data) { callback(data); }, + test_data.callback, callback_data); } }; @@ -275,7 +270,7 @@ void TestStackDumpsys2::TestMethod(TestData test_data) const { } class TestStackDumpsys3 : public TestStackDumpsysBase { - public: +public: TestStackDumpsys3(const TestStackDumpsys3&) = delete; TestStackDumpsys3& operator=(const TestStackDumpsys3&) = delete; virtual ~TestStackDumpsys3() = default; @@ -284,7 +279,7 @@ class TestStackDumpsys3 : public TestStackDumpsysBase { void TestMethod(TestData test_data) const override; - private: +private: struct impl; std::shared_ptr impl_; TestStackDumpsys3(); @@ -293,13 +288,12 @@ class TestStackDumpsys3 : public TestStackDumpsysBase { struct TestStackDumpsys3::impl : public ModuleMainloop, public ModuleJniloop { void test(TestData test_data) { TestCallbackData callback_data{ - .iter = test_data.iter, - .tag = std::string(__func__), + .iter = test_data.iter, + .tag = std::string(__func__), }; - PostFunctionOnMain( - [](std::function callback, - TestCallbackData data) { callback(data); }, - test_data.callback, callback_data); + PostFunctionOnMain([](std::function callback, + TestCallbackData data) { callback(data); }, + test_data.callback, callback_data); } }; @@ -312,7 +306,7 @@ void TestStackDumpsys3::TestMethod(TestData test_data) const { } class TestStackDumpsys4 : public TestStackDumpsysBase { - public: +public: TestStackDumpsys4(const TestStackDumpsys4&) = delete; TestStackDumpsys4& operator=(const TestStackDumpsys3&) = delete; virtual ~TestStackDumpsys4() = default; @@ -323,7 +317,7 @@ class TestStackDumpsys4 : public TestStackDumpsysBase { log::info("mod:{} iter:{} tag:{}", __func__, test_data.iter, test_data.tag); } - private: +private: struct impl; std::shared_ptr impl_; TestStackDumpsys4() : TestStackDumpsysBase() {} @@ -332,33 +326,31 @@ class TestStackDumpsys4 : public TestStackDumpsysBase { struct TestStackDumpsys4::impl : public ModuleMainloop, public ModuleJniloop {}; const ModuleFactory TestStackDumpsysBase::Factory = - ModuleFactory([]() { return new TestStackDumpsysBase(); }); + ModuleFactory([]() { return new TestStackDumpsysBase(); }); const ModuleFactory TestStackDumpsys1::Factory = - ModuleFactory([]() { return new TestStackDumpsys1(); }); + ModuleFactory([]() { return new TestStackDumpsys1(); }); const ModuleFactory TestStackDumpsys2::Factory = - ModuleFactory([]() { return new TestStackDumpsys2(); }); + ModuleFactory([]() { return new TestStackDumpsys2(); }); const ModuleFactory TestStackDumpsys3::Factory = - ModuleFactory([]() { return new TestStackDumpsys3(); }); + ModuleFactory([]() { return new TestStackDumpsys3(); }); const ModuleFactory TestStackDumpsys4::Factory = - ModuleFactory([]() { return new TestStackDumpsys4(); }); + ModuleFactory([]() { return new TestStackDumpsys4(); }); class StackWithMainThreadUnitTest : public ::testing::Test { - protected: +protected: void SetUp() override { main_thread_ = std::make_unique(); } void TearDown() override { main_thread_.reset(); } - private: +private: std::unique_ptr main_thread_; }; class StackLifecycleUnitTest : public StackWithMainThreadUnitTest { - public: - std::shared_ptr StackManager() const { - return stack_manager_; - } +public: + std::shared_ptr StackManager() const { return stack_manager_; } - protected: +protected: void SetUp() override { StackWithMainThreadUnitTest::SetUp(); stack_manager_ = std::make_shared(); @@ -369,12 +361,12 @@ class StackLifecycleUnitTest : public StackWithMainThreadUnitTest { StackWithMainThreadUnitTest::TearDown(); } - private: +private: std::shared_ptr stack_manager_; }; class MainShimStackDumpsysTest : public StackLifecycleUnitTest { - protected: +protected: void SetUp() override { StackLifecycleUnitTest::SetUp(); StackManager()->AddModule(); @@ -384,9 +376,8 @@ class MainShimStackDumpsysTest : public StackLifecycleUnitTest { StackManager()->Start(); ASSERT_EQ(4U, StackManager()->NumModules()); - bluetooth::shim::RegisterDumpsysFunction((void*)this, [](int fd) { - log::info("Callback to dump legacy data fd:{}", fd); - }); + bluetooth::shim::RegisterDumpsysFunction( + (void*)this, [](int fd) { log::info("Callback to dump legacy data fd:{}", fd); }); } void TearDown() override { @@ -399,14 +390,13 @@ struct CallablePostCnt { size_t success{0}; size_t misses{0}; CallablePostCnt operator+=(const CallablePostCnt& post_cnt) { - return CallablePostCnt( - {success += post_cnt.success, misses += post_cnt.misses}); + return CallablePostCnt({success += post_cnt.success, misses += post_cnt.misses}); } }; // Provide a client user of the stack manager module services class Client { - public: +public: Client(int id) : id_(id) {} Client(const Client&) = default; virtual ~Client() = default; @@ -416,17 +406,16 @@ class Client { thread_ = new os::Thread(common::StringFormat("ClientThread%d", id_), os::Thread::Priority::NORMAL); handler_ = new os::Handler(thread_); - handler_->Post(common::BindOnce( - [](int id) { log::info("<=== tid Started client id:{}", id); }, id_)); + handler_->Post( + common::BindOnce([](int id) { log::info("<=== tid Started client id:{}", id); }, id_)); } // Ensure all the client handlers are running void Await() { std::promise promise; std::future future = promise.get_future(); - handler_->Post( - base::BindOnce([](std::promise promise) { promise.set_value(); }, - std::move(promise))); + handler_->Post(base::BindOnce([](std::promise promise) { promise.set_value(); }, + std::move(promise))); future.wait(); } @@ -442,16 +431,18 @@ class Client { // Safely prevent new work tasks from being posted void Quiesce() { - if (quiesced_) return; + if (quiesced_) { + return; + } quiesced_ = true; std::promise promise = std::promise(); std::future future = promise.get_future(); handler_->Post(common::BindOnce( - [](std::promise promise, int id) { - promise.set_value(); - log::info("<=== tid Quiesced client id:{}", id); - }, - std::move(promise), id_)); + [](std::promise promise, int id) { + promise.set_value(); + log::info("<=== tid Quiesced client id:{}", id); + }, + std::move(promise), id_)); future.wait_for(std::chrono::milliseconds(kSyncMainLoopTimeoutMs)); } @@ -461,8 +452,7 @@ class Client { Quiesce(); } handler_->Clear(); - handler_->WaitUntilStopped( - std::chrono::milliseconds(kWaitUntilHandlerStoppedMs)); + handler_->WaitUntilStopped(std::chrono::milliseconds(kWaitUntilHandlerStoppedMs)); delete handler_; delete thread_; } @@ -471,11 +461,9 @@ class Client { CallablePostCnt GetCallablePostCnt() const { return post_cnt_; } - std::string Name() const { - return common::StringFormat("%s%d", __func__, id_); - } + std::string Name() const { return common::StringFormat("%s%d", __func__, id_); } - private: +private: int id_{0}; CallablePostCnt post_cnt_{}; bool quiesced_{false}; @@ -485,7 +473,7 @@ class Client { // Convenience object to handle multiple clients with logging class ClientGroup { - public: +public: explicit ClientGroup(size_t num_clients) { for (size_t i = 0; i < num_clients; i++) { clients_.emplace_back(std::make_unique(i)); @@ -524,8 +512,7 @@ class ClientGroup { void Dump() const { for (auto& c : clients_) { log::info("Callable post cnt client_id:{} success:{} misses:{}", c->Id(), - c->GetCallablePostCnt().success, - c->GetCallablePostCnt().misses); + c->GetCallablePostCnt().success, c->GetCallablePostCnt().misses); } } @@ -543,7 +530,7 @@ class ClientGroup { }; class MainShimStackDumpsysWithClientsTest : public MainShimStackDumpsysTest { - protected: +protected: void SetUp() override { MainShimStackDumpsysTest::SetUp(); client_group_.Start(); @@ -560,10 +547,10 @@ class MainShimStackDumpsysWithClientsTest : public MainShimStackDumpsysTest { TEST_F(MainShimStackDumpsysWithClientsTest, all_clients_check_stack_running) { StackRunningData stack_running_data = { - .cb = - [](bool is_stack_running) { - log::info("Stack is running:{}", (is_stack_running) ? 'T' : 'F'); - }, + .cb = + [](bool is_stack_running) { + log::info("Stack is running:{}", (is_stack_running) ? 'T' : 'F'); + }, }; // Ensure the dumpsys instance is included within the stack @@ -571,24 +558,23 @@ TEST_F(MainShimStackDumpsysWithClientsTest, all_clients_check_stack_running) { for (auto& c : client_group_.clients_) { c->Post(base::BindOnce( - [](StackRunningData stack_running_data) { - bluetooth::shim::Stack::GetInstance() - ->GetStackManager() - ->GetInstance() - ->IsStackRunning(stack_running_data); - }, - stack_running_data)); + [](StackRunningData stack_running_data) { + bluetooth::shim::Stack::GetInstance() + ->GetStackManager() + ->GetInstance() + ->IsStackRunning(stack_running_data); + }, + stack_running_data)); } } -TEST_F(MainShimStackDumpsysWithClientsTest, - all_clients_check_stack_running_with_iterations) { +TEST_F(MainShimStackDumpsysWithClientsTest, all_clients_check_stack_running_with_iterations) { StackRunningData stack_running_data = { - .cb = - [](bool is_stack_running) { - log::info("Run on mainloop: Stack is running:{}", - (is_stack_running) ? 'T' : 'F'); - }, + .cb = + [](bool is_stack_running) { + log::info("Run on mainloop: Stack is running:{}", + (is_stack_running) ? 'T' : 'F'); + }, }; // Ensure the dumpsys instance is included within the stack @@ -598,13 +584,13 @@ TEST_F(MainShimStackDumpsysWithClientsTest, log::info("Iteration:{}", i); for (auto& c : client_group_.clients_) { c->Post(base::BindOnce( - [](StackRunningData stack_running_data) { - bluetooth::shim::Stack::GetInstance() - ->GetStackManager() - ->GetInstance() - ->IsStackRunning(stack_running_data); - }, - stack_running_data)); + [](StackRunningData stack_running_data) { + bluetooth::shim::Stack::GetInstance() + ->GetStackManager() + ->GetInstance() + ->IsStackRunning(stack_running_data); + }, + stack_running_data)); } } } @@ -615,16 +601,15 @@ TEST_F(MainShimStackDumpsysWithClientsTest, dumpsys_single_client) { const int fd = 1; client_group_.clients_[0]->Post( - base::BindOnce([](int fd) { bluetooth::shim::Dump(fd, nullptr); }, fd)); + base::BindOnce([](int fd) { bluetooth::shim::Dump(fd, nullptr); }, fd)); } -TEST_F(MainShimStackDumpsysWithClientsTest, - dumpsys_single_client_with_running_check) { +TEST_F(MainShimStackDumpsysWithClientsTest, dumpsys_single_client_with_running_check) { StackRunningData stack_running_data = { - .cb = - [](bool is_stack_running) { - log::info("Stack is running:{}", (is_stack_running) ? 'T' : 'F'); - }, + .cb = + [](bool is_stack_running) { + log::info("Stack is running:{}", (is_stack_running) ? 'T' : 'F'); + }, }; // Ensure the dumpsys instance is included within the stack @@ -632,28 +617,27 @@ TEST_F(MainShimStackDumpsysWithClientsTest, const int fd = 1; client_group_.clients_[0]->Post(base::BindOnce( - [](StackRunningData stack_running_data) { - bluetooth::shim::Stack::GetInstance() - ->GetStackManager() - ->GetInstance() - ->IsStackRunning(stack_running_data); - }, - stack_running_data)); + [](StackRunningData stack_running_data) { + bluetooth::shim::Stack::GetInstance() + ->GetStackManager() + ->GetInstance() + ->IsStackRunning(stack_running_data); + }, + stack_running_data)); client_group_.clients_[0]->Post( - base::BindOnce([](int fd) { bluetooth::shim::Dump(fd, nullptr); }, fd)); + base::BindOnce([](int fd) { bluetooth::shim::Dump(fd, nullptr); }, fd)); } TEST_F(MainShimStackDumpsysWithClientsTest, dumpsys_many_clients) { StackRunningData stack_running_data = { - .cb = - [](bool is_stack_running) { - log::info("Stack is running:{}", (is_stack_running) ? 'T' : 'F'); - }, + .cb = + [](bool is_stack_running) { + log::info("Stack is running:{}", (is_stack_running) ? 'T' : 'F'); + }, }; const int fd = 1; for (auto& c : client_group_.clients_) { - c->Post( - base::BindOnce([](int fd) { bluetooth::shim::Dump(fd, nullptr); }, fd)); + c->Post(base::BindOnce([](int fd) { bluetooth::shim::Dump(fd, nullptr); }, fd)); } } diff --git a/system/main/test/main_shim_stack_lifecycle_test.cc b/system/main/test/main_shim_stack_lifecycle_test.cc index f8c4048d793..7acf5f7078e 100644 --- a/system/main/test/main_shim_stack_lifecycle_test.cc +++ b/system/main/test/main_shim_stack_lifecycle_test.cc @@ -49,7 +49,9 @@ constexpr char kTestStackThreadName[] = "test_stack_thread"; constexpr char kTestDataTag[] = "This is a test"; inline void maybe_yield() { - if (std::rand() & 1) std::this_thread::yield(); + if (std::rand() & 1) { + std::this_thread::yield(); + } } constexpr size_t kTagLength = 48 + sizeof(' ') + sizeof(' '); @@ -60,7 +62,7 @@ inline void log_tag(std::string tag) { } class MainThread { - public: +public: MainThread() { main_thread_start_up(); } ~MainThread() { @@ -68,7 +70,7 @@ class MainThread { main_thread_shut_down(); } - private: +private: void sync_main_handler() { std::promise promise = std::promise(); std::future future = promise.get_future(); @@ -78,7 +80,7 @@ class MainThread { }; class TestStackManager { - public: +public: TestStackManager() { // Start is executed by the test after each test adds the default // or their own modules @@ -97,17 +99,20 @@ class TestStackManager { } void Start() { - if (stack_started_) return; + if (stack_started_) { + return; + } log::info("Started stack manager"); stack_started_ = true; bluetooth::os::Thread* stack_thread = new bluetooth::os::Thread( - kTestStackThreadName, bluetooth::os::Thread::Priority::NORMAL); - bluetooth::shim::Stack::GetInstance()->StartModuleStack(&modules_, - stack_thread); + kTestStackThreadName, bluetooth::os::Thread::Priority::NORMAL); + bluetooth::shim::Stack::GetInstance()->StartModuleStack(&modules_, stack_thread); } void Stop() { - if (!stack_started_) return; + if (!stack_started_) { + return; + } stack_started_ = false; bluetooth::shim::Stack::GetInstance()->Stop(); } @@ -116,14 +121,12 @@ class TestStackManager { // if stack manager has not started or shutdown template static T* GetUnsafeModule() { - return bluetooth::shim::Stack::GetInstance() - ->GetStackManager() - ->GetInstance(); + return bluetooth::shim::Stack::GetInstance()->GetStackManager()->GetInstance(); } size_t NumModules() const { return modules_.NumModules(); } - private: +private: bluetooth::ModuleList modules_; bool stack_started_{false}; }; @@ -141,31 +144,29 @@ struct TestData { std::function callback; }; -class TestStackModuleBase : public bluetooth::Module, - public ModuleMainloop, - public ModuleJniloop { - public: +class TestStackModuleBase : public bluetooth::Module, public ModuleMainloop, public ModuleJniloop { +public: TestStackModuleBase(const TestStackModuleBase&) = delete; TestStackModuleBase& operator=(const TestStackModuleBase&) = delete; - virtual ~TestStackModuleBase(){}; + virtual ~TestStackModuleBase() {} static const ModuleFactory Factory; virtual void TestMethod(TestData test_data) const { log::info("Test base class iter:{} tag:{}", test_data.iter, test_data.tag); } - protected: - void ListDependencies(ModuleList* list) const override{}; - void Start() override { log::error("Started TestStackModuleBase"); }; - void Stop() override { log::error("Stopped TestStackModuleBase"); }; +protected: + void ListDependencies(ModuleList* list) const override {} + void Start() override { log::error("Started TestStackModuleBase"); } + void Stop() override { log::error("Stopped TestStackModuleBase"); } std::string ToString() const override { return std::string("TestFunction"); } TestStackModuleBase() = default; }; class TestStackModule1 : public TestStackModuleBase { - public: +public: TestStackModule1(const TestStackModule1&) = delete; TestStackModule1& operator=(const TestStackModule1&) = delete; virtual ~TestStackModule1() = default; @@ -174,7 +175,7 @@ class TestStackModule1 : public TestStackModuleBase { void TestMethod(TestData test_data) const override; - private: +private: struct impl; std::shared_ptr impl_; TestStackModule1(); @@ -183,26 +184,23 @@ class TestStackModule1 : public TestStackModuleBase { struct TestStackModule1::impl : public ModuleMainloop, public ModuleJniloop { void test(TestData test_data) { TestCallbackData callback_data{ - .iter = test_data.iter, - .tag = std::string(__func__), + .iter = test_data.iter, + .tag = std::string(__func__), }; - PostFunctionOnMain( - [](std::function callback, - TestCallbackData data) { callback(data); }, - test_data.callback, callback_data); + PostFunctionOnMain([](std::function callback, + TestCallbackData data) { callback(data); }, + test_data.callback, callback_data); } }; -TestStackModule1::TestStackModule1() : TestStackModuleBase() { - impl_ = std::make_shared(); -} +TestStackModule1::TestStackModule1() : TestStackModuleBase() { impl_ = std::make_shared(); } void TestStackModule1::TestMethod(TestData test_data) const { PostMethodOnMain(impl_, &impl::test, test_data); } class TestStackModule2 : public TestStackModuleBase { - public: +public: TestStackModule2(const TestStackModule2&) = delete; TestStackModule2& operator=(const TestStackModule2&) = delete; virtual ~TestStackModule2() = default; @@ -211,7 +209,7 @@ class TestStackModule2 : public TestStackModuleBase { void TestMethod(TestData test_data) const override; - private: +private: struct impl; std::shared_ptr impl_; TestStackModule2(); @@ -220,26 +218,23 @@ class TestStackModule2 : public TestStackModuleBase { struct TestStackModule2::impl : public ModuleMainloop, public ModuleJniloop { void test(TestData test_data) { TestCallbackData callback_data{ - .iter = test_data.iter, - .tag = std::string(__func__), + .iter = test_data.iter, + .tag = std::string(__func__), }; - PostFunctionOnMain( - [](std::function callback, - TestCallbackData data) { callback(data); }, - test_data.callback, callback_data); + PostFunctionOnMain([](std::function callback, + TestCallbackData data) { callback(data); }, + test_data.callback, callback_data); } }; -TestStackModule2::TestStackModule2() : TestStackModuleBase() { - impl_ = std::make_shared(); -} +TestStackModule2::TestStackModule2() : TestStackModuleBase() { impl_ = std::make_shared(); } void TestStackModule2::TestMethod(TestData test_data) const { PostMethodOnMain(impl_, &impl::test, test_data); } class TestStackModule3 : public TestStackModuleBase { - public: +public: TestStackModule3(const TestStackModule3&) = delete; TestStackModule3& operator=(const TestStackModule3&) = delete; virtual ~TestStackModule3() = default; @@ -248,7 +243,7 @@ class TestStackModule3 : public TestStackModuleBase { void TestMethod(TestData test_data) const override; - private: +private: struct impl; std::shared_ptr impl_; TestStackModule3(); @@ -257,26 +252,23 @@ class TestStackModule3 : public TestStackModuleBase { struct TestStackModule3::impl : public ModuleMainloop, public ModuleJniloop { void test(TestData test_data) { TestCallbackData callback_data{ - .iter = test_data.iter, - .tag = std::string(__func__), + .iter = test_data.iter, + .tag = std::string(__func__), }; - PostFunctionOnMain( - [](std::function callback, - TestCallbackData data) { callback(data); }, - test_data.callback, callback_data); + PostFunctionOnMain([](std::function callback, + TestCallbackData data) { callback(data); }, + test_data.callback, callback_data); } }; -TestStackModule3::TestStackModule3() : TestStackModuleBase() { - impl_ = std::make_shared(); -} +TestStackModule3::TestStackModule3() : TestStackModuleBase() { impl_ = std::make_shared(); } void TestStackModule3::TestMethod(TestData test_data) const { PostMethodOnMain(impl_, &impl::test, test_data); } class TestStackModule4 : public TestStackModuleBase { - public: +public: TestStackModule4(const TestStackModule4&) = delete; TestStackModule4& operator=(const TestStackModule3&) = delete; virtual ~TestStackModule4() = default; @@ -287,7 +279,7 @@ class TestStackModule4 : public TestStackModuleBase { log::info("mod:{} iter:{} tag:{}", __func__, test_data.iter, test_data.tag); } - private: +private: struct impl; std::shared_ptr impl_; TestStackModule4() : TestStackModuleBase() {} @@ -298,33 +290,31 @@ struct TestStackModule4::impl : public ModuleMainloop, public ModuleJniloop {}; } // namespace const ModuleFactory TestStackModuleBase::Factory = - ModuleFactory([]() { return new TestStackModuleBase(); }); + ModuleFactory([]() { return new TestStackModuleBase(); }); const ModuleFactory TestStackModule1::Factory = - ModuleFactory([]() { return new TestStackModule1(); }); + ModuleFactory([]() { return new TestStackModule1(); }); const ModuleFactory TestStackModule2::Factory = - ModuleFactory([]() { return new TestStackModule2(); }); + ModuleFactory([]() { return new TestStackModule2(); }); const ModuleFactory TestStackModule3::Factory = - ModuleFactory([]() { return new TestStackModule3(); }); + ModuleFactory([]() { return new TestStackModule3(); }); const ModuleFactory TestStackModule4::Factory = - ModuleFactory([]() { return new TestStackModule4(); }); + ModuleFactory([]() { return new TestStackModule4(); }); class StackWithMainThreadUnitTest : public ::testing::Test { - protected: +protected: void SetUp() override { main_thread_ = std::make_unique(); } void TearDown() override { main_thread_.reset(); } - private: +private: std::unique_ptr main_thread_; }; class StackLifecycleUnitTest : public StackWithMainThreadUnitTest { - public: - std::shared_ptr StackManager() const { - return stack_manager_; - } +public: + std::shared_ptr StackManager() const { return stack_manager_; } - protected: +protected: void SetUp() override { StackWithMainThreadUnitTest::SetUp(); stack_manager_ = std::make_shared(); @@ -335,16 +325,14 @@ class StackLifecycleUnitTest : public StackWithMainThreadUnitTest { StackWithMainThreadUnitTest::TearDown(); } - private: +private: std::shared_ptr stack_manager_; }; -TEST_F(StackLifecycleUnitTest, no_modules_in_stack) { - ASSERT_EQ(0U, StackManager()->NumModules()); -} +TEST_F(StackLifecycleUnitTest, no_modules_in_stack) { ASSERT_EQ(0U, StackManager()->NumModules()); } class StackLifecycleWithDefaultModulesUnitTest : public StackLifecycleUnitTest { - protected: +protected: void SetUp() override { StackLifecycleUnitTest::SetUp(); StackManager()->AddModule(); @@ -361,14 +349,13 @@ struct CallablePostCnt { size_t success{0}; size_t misses{0}; CallablePostCnt operator+=(const CallablePostCnt& post_cnt) { - return CallablePostCnt( - {success += post_cnt.success, misses += post_cnt.misses}); + return CallablePostCnt({success += post_cnt.success, misses += post_cnt.misses}); } }; // Provide a client user of the stack manager module services class Client { - public: +public: Client(int id) : id_(id) {} Client(const Client&) = default; virtual ~Client() = default; @@ -379,17 +366,15 @@ class Client { thread_ = new os::Thread(common::StringFormat("ClientThread%d", id_), os::Thread::Priority::NORMAL); handler_ = new os::Handler(thread_); - handler_->Post(common::BindOnce( - [](int id) { log::info("Started client {}", id); }, id_)); + handler_->Post(common::BindOnce([](int id) { log::info("Started client {}", id); }, id_)); } // Ensure all the client handlers are running void Await() { std::promise promise; std::future future = promise.get_future(); - handler_->Post( - base::BindOnce([](std::promise promise) { promise.set_value(); }, - std::move(promise))); + handler_->Post(base::BindOnce([](std::promise promise) { promise.set_value(); }, + std::move(promise))); future.wait(); } @@ -407,13 +392,14 @@ class Client { // Safely prevent new work tasks from being posted void Quiesce() { - if (quiesced_) return; + if (quiesced_) { + return; + } quiesced_ = true; std::promise promise = std::promise(); std::future future = promise.get_future(); - handler_->Post(common::BindOnce( - [](std::promise promise) { promise.set_value(); }, - std::move(promise))); + handler_->Post(common::BindOnce([](std::promise promise) { promise.set_value(); }, + std::move(promise))); future.wait_for(std::chrono::milliseconds(kSyncMainLoopTimeoutMs)); } @@ -423,8 +409,7 @@ class Client { Quiesce(); } handler_->Clear(); - handler_->WaitUntilStopped( - std::chrono::milliseconds(kWaitUntilHandlerStoppedMs)); + handler_->WaitUntilStopped(std::chrono::milliseconds(kWaitUntilHandlerStoppedMs)); delete handler_; delete thread_; } @@ -433,11 +418,9 @@ class Client { CallablePostCnt GetCallablePostCnt() const { return post_cnt_; } - std::string Name() const { - return common::StringFormat("%s%d", __func__, id_); - } + std::string Name() const { return common::StringFormat("%s%d", __func__, id_); } - private: +private: int id_{0}; CallablePostCnt post_cnt_{}; bool quiesced_{false}; @@ -447,8 +430,8 @@ class Client { // Convenience object to handle multiple clients with logging class ClientGroup { - public: - ClientGroup(){}; +public: + ClientGroup() {} void Start() { for (auto& c : clients_) { @@ -482,8 +465,7 @@ class ClientGroup { void Dump() const { for (auto& c : clients_) { log::info("Callable post cnt client_id:{} success:{} misses:{}", c->Id(), - c->GetCallablePostCnt().success, - c->GetCallablePostCnt().misses); + c->GetCallablePostCnt().success, c->GetCallablePostCnt().misses); } } @@ -498,8 +480,7 @@ class ClientGroup { size_t NumClients() const { return kNumTestClients; } std::unique_ptr clients_[kNumTestClients] = { - std::make_unique(1), std::make_unique(2), - std::make_unique(3)}; + std::make_unique(1), std::make_unique(2), std::make_unique(3)}; }; TEST_F(StackLifecycleWithDefaultModulesUnitTest, clients_start) { @@ -522,35 +503,32 @@ TEST_F(StackLifecycleWithDefaultModulesUnitTest, client_using_stack_manager) { for (int i = 0; i < kNumIters; i++) { for (auto& c : client_group.clients_) { c->Post(base::BindOnce( - [](int id, int iter, - std::shared_ptr stack_manager) { - stack_manager->GetUnsafeModule()->TestMethod({ - .iter = iter, - .tag = std::string(kTestDataTag), - .callback = [](TestCallbackData data) {}, - }); - }, - c->Id(), i, StackManager())); + [](int id, int iter, std::shared_ptr stack_manager) { + stack_manager->GetUnsafeModule()->TestMethod({ + .iter = iter, + .tag = std::string(kTestDataTag), + .callback = [](TestCallbackData data) {}, + }); + }, + c->Id(), i, StackManager())); c->Post(base::BindOnce( - [](int id, int iter, - std::shared_ptr stack_manager) { - stack_manager->GetUnsafeModule()->TestMethod({ - .iter = iter, - .tag = std::string(kTestDataTag), - .callback = [](TestCallbackData data) {}, - }); - }, - c->Id(), i, StackManager())); + [](int id, int iter, std::shared_ptr stack_manager) { + stack_manager->GetUnsafeModule()->TestMethod({ + .iter = iter, + .tag = std::string(kTestDataTag), + .callback = [](TestCallbackData data) {}, + }); + }, + c->Id(), i, StackManager())); c->Post(base::BindOnce( - [](int id, int iter, - std::shared_ptr stack_manager) { - stack_manager->GetUnsafeModule()->TestMethod({ - .iter = iter, - .tag = std::string(kTestDataTag), - .callback = [](TestCallbackData data) {}, - }); - }, - c->Id(), i, StackManager())); + [](int id, int iter, std::shared_ptr stack_manager) { + stack_manager->GetUnsafeModule()->TestMethod({ + .iter = iter, + .tag = std::string(kTestDataTag), + .callback = [](TestCallbackData data) {}, + }); + }, + c->Id(), i, StackManager())); } } @@ -559,12 +537,10 @@ TEST_F(StackLifecycleWithDefaultModulesUnitTest, client_using_stack_manager) { client_group.Dump(); ASSERT_EQ(client_group.NumClients() * kNumIters * kNumTestModules, - client_group.GetCallablePostCnt().success + - client_group.GetCallablePostCnt().misses); + client_group.GetCallablePostCnt().success + client_group.GetCallablePostCnt().misses); } -TEST_F(StackLifecycleWithDefaultModulesUnitTest, - client_using_stack_manager_when_shutdown) { +TEST_F(StackLifecycleWithDefaultModulesUnitTest, client_using_stack_manager_when_shutdown) { struct Counters { struct { std::atomic_size_t cnt{0}; @@ -578,62 +554,53 @@ TEST_F(StackLifecycleWithDefaultModulesUnitTest, for (int i = 0; i < kNumIters; i++) { for (auto& c : client_group.clients_) { c->Post(base::BindOnce( - [](int id, int iter, Counters* counters, - std::shared_ptr stack_manager) { - TestData test_data = { - .iter = iter, - .tag = std::string(kTestDataTag), - .callback = [](TestCallbackData data) {}, - }; - if (bluetooth::shim::Stack::GetInstance() - ->CallOnModule( - [test_data](TestStackModule1* mod) { - mod->TestMethod(test_data); - })) { - counters->up.cnt++; - } else { - counters->down.cnt++; - } - }, - c->Id(), i, &counters, StackManager())); + [](int id, int iter, Counters* counters, + std::shared_ptr stack_manager) { + TestData test_data = { + .iter = iter, + .tag = std::string(kTestDataTag), + .callback = [](TestCallbackData data) {}, + }; + if (bluetooth::shim::Stack::GetInstance()->CallOnModule( + [test_data](TestStackModule1* mod) { mod->TestMethod(test_data); })) { + counters->up.cnt++; + } else { + counters->down.cnt++; + } + }, + c->Id(), i, &counters, StackManager())); c->Post(base::BindOnce( - [](int id, int iter, Counters* counters, - std::shared_ptr stack_manager) { - TestData test_data = { - .iter = iter, - .tag = std::string(kTestDataTag), - .callback = [](TestCallbackData data) {}, - }; - if (bluetooth::shim::Stack::GetInstance() - ->CallOnModule( - [test_data](TestStackModule2* mod) { - mod->TestMethod(test_data); - })) { - counters->up.cnt++; - } else { - counters->down.cnt++; - } - }, - c->Id(), i, &counters, StackManager())); + [](int id, int iter, Counters* counters, + std::shared_ptr stack_manager) { + TestData test_data = { + .iter = iter, + .tag = std::string(kTestDataTag), + .callback = [](TestCallbackData data) {}, + }; + if (bluetooth::shim::Stack::GetInstance()->CallOnModule( + [test_data](TestStackModule2* mod) { mod->TestMethod(test_data); })) { + counters->up.cnt++; + } else { + counters->down.cnt++; + } + }, + c->Id(), i, &counters, StackManager())); c->Post(base::BindOnce( - [](int id, int iter, Counters* counters, - std::shared_ptr stack_manager) { - TestData test_data = { - .iter = iter, - .tag = std::string(kTestDataTag), - .callback = [](TestCallbackData data) {}, - }; - if (bluetooth::shim::Stack::GetInstance() - ->CallOnModule( - [test_data](TestStackModule3* mod) { - mod->TestMethod(test_data); - })) { - counters->up.cnt++; - } else { - counters->down.cnt++; - } - }, - c->Id(), i, &counters, StackManager())); + [](int id, int iter, Counters* counters, + std::shared_ptr stack_manager) { + TestData test_data = { + .iter = iter, + .tag = std::string(kTestDataTag), + .callback = [](TestCallbackData data) {}, + }; + if (bluetooth::shim::Stack::GetInstance()->CallOnModule( + [test_data](TestStackModule3* mod) { mod->TestMethod(test_data); })) { + counters->up.cnt++; + } else { + counters->down.cnt++; + } + }, + c->Id(), i, &counters, StackManager())); } // Abruptly shutdown stack at some point through the iterations if (i == kAbruptStackShutdownIter) { @@ -644,10 +611,9 @@ TEST_F(StackLifecycleWithDefaultModulesUnitTest, client_group.Quiesce(); client_group.Stop(); - log::info("Execution stack availability counters up:{} down:{}", - counters.up.cnt, counters.down.cnt); + log::info("Execution stack availability counters up:{} down:{}", counters.up.cnt, + counters.down.cnt); ASSERT_EQ(client_group.NumClients() * kNumIters * kNumTestModules, - client_group.GetCallablePostCnt().success + - client_group.GetCallablePostCnt().misses); + client_group.GetCallablePostCnt().success + client_group.GetCallablePostCnt().misses); } diff --git a/system/main/test/main_shim_test.cc b/system/main/test/main_shim_test.cc index a84331f3abc..266f35a64f7 100644 --- a/system/main/test/main_shim_test.cc +++ b/system/main/test/main_shim_test.cc @@ -85,8 +85,7 @@ tBTM_CB btm_cb; tBTM_SEC_CB btm_sec_cb; btif_hh_cb_t btif_hh_cb; -struct bluetooth::hci::LeScanningManager::impl - : public bluetooth::hci::LeAddressManagerCallback {}; +struct bluetooth::hci::LeScanningManager::impl : public bluetooth::hci::LeAddressManagerCallback {}; namespace { const hci::Address kAddress = {{0x11, 0x22, 0x33, 0x44, 0x55, 0x66}}; @@ -101,7 +100,7 @@ std::map> mock_function_handle_promise_map; // Utility to provide a file descriptor for /dev/null when possible, but // defaulting to STDERR when not possible. class DevNullOrStdErr { - public: +public: DevNullOrStdErr() { fd_ = open("/dev/null", O_CLOEXEC | O_WRONLY); } ~DevNullOrStdErr() { if (fd_ != -1) { @@ -111,7 +110,7 @@ class DevNullOrStdErr { } int Fd() const { return (fd_ == -1) ? STDERR_FILENO : fd_; } - private: +private: int fd_{-1}; }; @@ -123,89 +122,81 @@ void mock_on_send_data_upwards(BT_HDR*) {} void mock_on_packets_completed(uint16_t handle, uint16_t num_packets) {} -void mock_connection_classic_on_connected(const RawAddress& bda, - uint16_t handle, uint8_t enc_mode, +void mock_connection_classic_on_connected(const RawAddress& bda, uint16_t handle, uint8_t enc_mode, bool locally_initiated) {} -void mock_connection_classic_on_failed(const RawAddress& bda, - tHCI_STATUS status, +void mock_connection_classic_on_failed(const RawAddress& bda, tHCI_STATUS status, bool locally_initiated) {} -void mock_connection_classic_on_disconnected(tHCI_STATUS status, - uint16_t handle, +void mock_connection_classic_on_disconnected(tHCI_STATUS status, uint16_t handle, tHCI_STATUS reason) { ASSERT_TRUE(mock_function_handle_promise_map.find(__func__) != mock_function_handle_promise_map.end()); mock_function_handle_promise_map[__func__].set_value(handle); } -void mock_connection_le_on_connected( - const tBLE_BD_ADDR& address_with_type, uint16_t handle, tHCI_ROLE role, - uint16_t conn_interval, uint16_t conn_latency, uint16_t conn_timeout, - const RawAddress& local_rpa, const RawAddress& peer_rpa, - tBLE_ADDR_TYPE peer_addr_type, bool can_read_discoverable_characteristics) { -} -void mock_connection_le_on_failed(const tBLE_BD_ADDR& address_with_type, - uint16_t handle, bool enhanced, - tHCI_STATUS status) {} +void mock_connection_le_on_connected(const tBLE_BD_ADDR& address_with_type, uint16_t handle, + tHCI_ROLE role, uint16_t conn_interval, uint16_t conn_latency, + uint16_t conn_timeout, const RawAddress& local_rpa, + const RawAddress& peer_rpa, tBLE_ADDR_TYPE peer_addr_type, + bool can_read_discoverable_characteristics) {} +void mock_connection_le_on_failed(const tBLE_BD_ADDR& address_with_type, uint16_t handle, + bool enhanced, tHCI_STATUS status) {} static std::promise mock_connection_le_on_disconnected_promise; -void mock_connection_le_on_disconnected(tHCI_STATUS status, uint16_t handle, - tHCI_STATUS reason) { +void mock_connection_le_on_disconnected(tHCI_STATUS status, uint16_t handle, tHCI_STATUS reason) { mock_connection_le_on_disconnected_promise.set_value(handle); } -void mock_link_classic_on_read_remote_extended_features_complete( - uint16_t handle, uint8_t current_page_number, uint8_t max_page_number, - uint64_t features) {} +void mock_link_classic_on_read_remote_extended_features_complete(uint16_t handle, + uint8_t current_page_number, + uint8_t max_page_number, + uint64_t features) {} shim::legacy::acl_interface_t acl_interface{ - .on_send_data_upwards = mock_on_send_data_upwards, - .on_packets_completed = mock_on_packets_completed, - - .connection.classic.on_connected = mock_connection_classic_on_connected, - .connection.classic.on_failed = mock_connection_classic_on_failed, - .connection.classic.on_disconnected = - mock_connection_classic_on_disconnected, - .connection.classic.on_connect_request = nullptr, - - .connection.le.on_connected = mock_connection_le_on_connected, - .connection.le.on_failed = mock_connection_le_on_failed, - .connection.le.on_disconnected = mock_connection_le_on_disconnected, - - .link.classic.on_authentication_complete = nullptr, - .link.classic.on_central_link_key_complete = nullptr, - .link.classic.on_change_connection_link_key_complete = nullptr, - .link.classic.on_encryption_change = nullptr, - .link.classic.on_flow_specification_complete = nullptr, - .link.classic.on_flush_occurred = nullptr, - .link.classic.on_mode_change = nullptr, - .link.classic.on_packet_type_changed = nullptr, - .link.classic.on_qos_setup_complete = nullptr, - .link.classic.on_read_afh_channel_map_complete = nullptr, - .link.classic.on_read_automatic_flush_timeout_complete = nullptr, - .link.classic.on_sniff_subrating = nullptr, - .link.classic.on_read_clock_complete = nullptr, - .link.classic.on_read_clock_offset_complete = nullptr, - .link.classic.on_read_failed_contact_counter_complete = nullptr, - .link.classic.on_read_link_policy_settings_complete = nullptr, - .link.classic.on_read_link_quality_complete = nullptr, - .link.classic.on_read_link_supervision_timeout_complete = nullptr, - .link.classic.on_read_remote_version_information_complete = nullptr, - .link.classic.on_read_remote_extended_features_complete = - mock_link_classic_on_read_remote_extended_features_complete, - .link.classic.on_read_rssi_complete = nullptr, - .link.classic.on_read_transmit_power_level_complete = nullptr, - .link.classic.on_role_change = nullptr, - .link.classic.on_role_discovery_complete = nullptr, - - .link.le.on_connection_update = nullptr, - .link.le.on_parameter_update_request = nullptr, - .link.le.on_data_length_change = nullptr, - .link.le.on_read_remote_version_information_complete = nullptr, + .on_send_data_upwards = mock_on_send_data_upwards, + .on_packets_completed = mock_on_packets_completed, + + .connection.classic.on_connected = mock_connection_classic_on_connected, + .connection.classic.on_failed = mock_connection_classic_on_failed, + .connection.classic.on_disconnected = mock_connection_classic_on_disconnected, + .connection.classic.on_connect_request = nullptr, + + .connection.le.on_connected = mock_connection_le_on_connected, + .connection.le.on_failed = mock_connection_le_on_failed, + .connection.le.on_disconnected = mock_connection_le_on_disconnected, + + .link.classic.on_authentication_complete = nullptr, + .link.classic.on_central_link_key_complete = nullptr, + .link.classic.on_change_connection_link_key_complete = nullptr, + .link.classic.on_encryption_change = nullptr, + .link.classic.on_flow_specification_complete = nullptr, + .link.classic.on_flush_occurred = nullptr, + .link.classic.on_mode_change = nullptr, + .link.classic.on_packet_type_changed = nullptr, + .link.classic.on_qos_setup_complete = nullptr, + .link.classic.on_read_afh_channel_map_complete = nullptr, + .link.classic.on_read_automatic_flush_timeout_complete = nullptr, + .link.classic.on_sniff_subrating = nullptr, + .link.classic.on_read_clock_complete = nullptr, + .link.classic.on_read_clock_offset_complete = nullptr, + .link.classic.on_read_failed_contact_counter_complete = nullptr, + .link.classic.on_read_link_policy_settings_complete = nullptr, + .link.classic.on_read_link_quality_complete = nullptr, + .link.classic.on_read_link_supervision_timeout_complete = nullptr, + .link.classic.on_read_remote_version_information_complete = nullptr, + .link.classic.on_read_remote_extended_features_complete = + mock_link_classic_on_read_remote_extended_features_complete, + .link.classic.on_read_rssi_complete = nullptr, + .link.classic.on_read_transmit_power_level_complete = nullptr, + .link.classic.on_role_change = nullptr, + .link.classic.on_role_discovery_complete = nullptr, + + .link.le.on_connection_update = nullptr, + .link.le.on_parameter_update_request = nullptr, + .link.le.on_data_length_change = nullptr, + .link.le.on_read_remote_version_information_complete = nullptr, }; -const shim::legacy::acl_interface_t& GetMockAclInterface() { - return acl_interface; -} +const shim::legacy::acl_interface_t& GetMockAclInterface() { return acl_interface; } struct hci_packet_parser_t; const hci_packet_parser_t* hci_packet_parser_get_interface() { return nullptr; } @@ -217,8 +208,7 @@ template class MockEnQueue : public os::IQueueEnqueue { using EnqueueCallback = base::Callback()>; - void RegisterEnqueue(os::Handler* handler, - EnqueueCallback callback) override {} + void RegisterEnqueue(os::Handler* handler, EnqueueCallback callback) override {} void UnregisterEnqueue() override {} }; @@ -226,35 +216,29 @@ template class MockDeQueue : public os::IQueueDequeue { using DequeueCallback = base::Callback; - void RegisterDequeue(os::Handler* handler, - DequeueCallback callback) override {} + void RegisterDequeue(os::Handler* handler, DequeueCallback callback) override {} void UnregisterDequeue() override {} std::unique_ptr TryDequeue() override { return nullptr; } }; -class MockClassicAclConnection - : public bluetooth::hci::acl_manager::ClassicAclConnection { - public: +class MockClassicAclConnection : public bluetooth::hci::acl_manager::ClassicAclConnection { +public: MockClassicAclConnection(const hci::Address& address, uint16_t handle) { address_ = address; // ClassicAclConnection handle_ = handle; // AclConnection } - void RegisterCallbacks( - hci::acl_manager::ConnectionManagementCallbacks* callbacks, - os::Handler* handler) override { + void RegisterCallbacks(hci::acl_manager::ConnectionManagementCallbacks* callbacks, + os::Handler* handler) override { callbacks_ = callbacks; handler_ = handler; } // Returns the bidi queue for this mock connection - AclConnection::QueueUpEnd* GetAclQueueEnd() const override { - return &mock_acl_queue_; - } + AclConnection::QueueUpEnd* GetAclQueueEnd() const override { return &mock_acl_queue_; } - mutable common::BidiQueueEnd> - mock_acl_queue_{&tx_, &rx_}; + mutable common::BidiQueueEnd> + mock_acl_queue_{&tx_, &rx_}; MockEnQueue tx_; MockDeQueue> rx_; @@ -285,32 +269,26 @@ class MockClassicAclConnection int disconnect_cnt_{0}; }; -class MockLeAclConnection - : public bluetooth::hci::acl_manager::LeAclConnection { - public: - MockLeAclConnection(uint16_t handle, - hci::acl_manager::RoleSpecificData role_specific_data, +class MockLeAclConnection : public bluetooth::hci::acl_manager::LeAclConnection { +public: + MockLeAclConnection(uint16_t handle, hci::acl_manager::RoleSpecificData role_specific_data, hci::AddressWithType remote_address) { handle_ = handle; role_specific_data_ = role_specific_data; remote_address_ = remote_address; } - void RegisterCallbacks( - hci::acl_manager::LeConnectionManagementCallbacks* callbacks, - os::Handler* handler) override { + void RegisterCallbacks(hci::acl_manager::LeConnectionManagementCallbacks* callbacks, + os::Handler* handler) override { callbacks_ = callbacks; handler_ = handler; } // Returns the bidi queue for this mock connection - AclConnection::QueueUpEnd* GetAclQueueEnd() const override { - return &mock_acl_queue_; - } + AclConnection::QueueUpEnd* GetAclQueueEnd() const override { return &mock_acl_queue_; } - mutable common::BidiQueueEnd> - mock_acl_queue_{&tx_, &rx_}; + mutable common::BidiQueueEnd> + mock_acl_queue_{&tx_, &rx_}; MockEnQueue tx_; MockDeQueue> rx_; @@ -348,8 +326,8 @@ const ModuleFactory HciHal::Factory = ModuleFactory([]() { return nullptr; }); } // namespace bluetooth class MainShimTest : public testing::Test { - public: - protected: +public: +protected: void SetUp() override { main_thread_start_up(); post_on_bt_main([]() { log::info("Main thread started"); }); @@ -357,16 +335,14 @@ class MainShimTest : public testing::Test { thread_ = new os::Thread("acl_thread", os::Thread::Priority::NORMAL); handler_ = new os::Handler(thread_); - /* extern */ test::mock_controller_ = - new bluetooth::hci::testing::MockControllerInterface(); - /* extern */ test::mock_acl_manager_ = - new bluetooth::hci::testing::MockAclManager(); + /* extern */ test::mock_controller_ = new bluetooth::hci::testing::MockControllerInterface(); + /* extern */ test::mock_acl_manager_ = new bluetooth::hci::testing::MockAclManager(); /* extern */ test::mock_le_scanning_manager_ = - new bluetooth::hci::testing::MockLeScanningManager(); + new bluetooth::hci::testing::MockLeScanningManager(); /* extern */ test::mock_le_advertising_manager_ = - new bluetooth::hci::testing::MockLeAdvertisingManager(); + new bluetooth::hci::testing::MockLeAdvertisingManager(); /* extern */ test::mock_distance_measurement_manager_ = - new bluetooth::hci::testing::MockDistanceMeasurementManager(); + new bluetooth::hci::testing::MockDistanceMeasurementManager(); } void TearDown() override { delete test::mock_controller_; @@ -395,20 +371,15 @@ class MainShimTest : public testing::Test { std::unique_ptr MakeAcl() { EXPECT_CALL(*test::mock_acl_manager_, RegisterCallbacks(_, _)).Times(1); EXPECT_CALL(*test::mock_acl_manager_, RegisterLeCallbacks(_, _)).Times(1); - EXPECT_CALL(*test::mock_controller_, - RegisterCompletedMonitorAclPacketsCallback(_)) - .Times(1); - EXPECT_CALL(*test::mock_controller_, - UnregisterCompletedMonitorAclPacketsCallback) - .Times(1); + EXPECT_CALL(*test::mock_controller_, RegisterCompletedMonitorAclPacketsCallback(_)).Times(1); + EXPECT_CALL(*test::mock_controller_, UnregisterCompletedMonitorAclPacketsCallback).Times(1); return std::make_unique(handler_, GetMockAclInterface(), - kMaxLeAcceptlistSize, - kMaxAddressResolutionSize); + kMaxLeAcceptlistSize, kMaxAddressResolutionSize); } }; class MainShimTestWithClassicConnection : public MainShimTest { - protected: +protected: void SetUp() override { MainShimTest::SetUp(); hci::Address address({0x11, 0x22, 0x33, 0x44, 0x55, 0x66}); @@ -422,8 +393,7 @@ class MainShimTestWithClassicConnection : public MainShimTest { // Respond with a mock connection created auto connection = std::make_unique(address, 123); ASSERT_EQ(123, connection->GetHandle()); - ASSERT_EQ(hci::Address({0x11, 0x22, 0x33, 0x44, 0x55, 0x66}), - connection->GetAddress()); + ASSERT_EQ(hci::Address({0x11, 0x22, 0x33, 0x44, 0x55, 0x66}), connection->GetAddress()); raw_connection_ = connection.get(); acl_->OnConnectSuccess(std::move(connection)); @@ -433,8 +403,7 @@ class MainShimTestWithClassicConnection : public MainShimTest { void TearDown() override { // Specify local disconnect request - auto tx_disconnect_future = - raw_connection_->disconnect_promise_.get_future(); + auto tx_disconnect_future = raw_connection_->disconnect_promise_.get_future(); acl_->DisconnectClassic(123, HCI_SUCCESS, {}); // Wait for disconnect to be received @@ -444,8 +413,8 @@ class MainShimTestWithClassicConnection : public MainShimTest { // Now emulate the remote disconnect response auto handle_promise = std::promise(); auto rx_disconnect_future = handle_promise.get_future(); - mock_function_handle_promise_map - ["mock_connection_classic_on_disconnected"] = std::move(handle_promise); + mock_function_handle_promise_map["mock_connection_classic_on_disconnected"] = + std::move(handle_promise); raw_connection_->callbacks_->OnDisconnection(hci::ErrorCode::SUCCESS); result = rx_disconnect_future.get(); @@ -454,8 +423,7 @@ class MainShimTestWithClassicConnection : public MainShimTest { // *Our* task completing indicates reactor is done std::promise done; auto future = done.get_future(); - handler_->Call([](std::promise done) { done.set_value(); }, - std::move(done)); + handler_->Call([](std::promise done) { done.set_value(); }, std::move(done)); future.wait(); acl_.reset(); @@ -479,8 +447,7 @@ TEST_F(MainShimTest, helpers) { do { hci::ErrorCode gd_error_code = static_cast(reason); tHCI_STATUS legacy_code = ToLegacyHciErrorCode(gd_error_code); - ASSERT_EQ(reason, - static_cast(ToLegacyHciErrorCode(gd_error_code))); + ASSERT_EQ(reason, static_cast(ToLegacyHciErrorCode(gd_error_code))); ASSERT_EQ(reason, static_cast(legacy_code)); } while (++reason != 0); } @@ -497,8 +464,7 @@ TEST_F(MainShimTest, connect_and_disconnect) { // Respond with a mock connection created auto connection = std::make_unique(address, 123); ASSERT_EQ(123, connection->GetHandle()); - ASSERT_EQ(hci::Address({0x11, 0x22, 0x33, 0x44, 0x55, 0x66}), - connection->GetAddress()); + ASSERT_EQ(hci::Address({0x11, 0x22, 0x33, 0x44, 0x55, 0x66}), connection->GetAddress()); MockClassicAclConnection* raw_connection = connection.get(); acl->OnConnectSuccess(std::move(connection)); @@ -516,7 +482,7 @@ TEST_F(MainShimTest, connect_and_disconnect) { auto handle_promise = std::promise(); auto rx_disconnect_future = handle_promise.get_future(); mock_function_handle_promise_map["mock_connection_classic_on_disconnected"] = - std::move(handle_promise); + std::move(handle_promise); raw_connection->callbacks_->OnDisconnection(hci::ErrorCode::SUCCESS); result = rx_disconnect_future.get(); @@ -525,8 +491,7 @@ TEST_F(MainShimTest, connect_and_disconnect) { // *Our* task completing indicates reactor is done std::promise done; auto future = done.get_future(); - handler_->Call([](std::promise done) { done.set_value(); }, - std::move(done)); + handler_->Call([](std::promise done) { done.set_value(); }, std::move(done)); future.wait(); connection.reset(); @@ -534,8 +499,7 @@ TEST_F(MainShimTest, connect_and_disconnect) { TEST_F(MainShimTest, is_flushable) { { - alignas(BT_HDR) - std::byte hdr_data[sizeof(BT_HDR) + sizeof(HciDataPreamble)]{}; + alignas(BT_HDR) std::byte hdr_data[sizeof(BT_HDR) + sizeof(HciDataPreamble)]{}; BT_HDR* bt_hdr = reinterpret_cast(hdr_data); ASSERT_TRUE(!IsPacketFlushable(bt_hdr)); @@ -546,8 +510,7 @@ TEST_F(MainShimTest, is_flushable) { { const size_t offset = 1024; - alignas(BT_HDR) - std::byte hdr_data[sizeof(BT_HDR) + sizeof(HciDataPreamble) + offset]{}; + alignas(BT_HDR) std::byte hdr_data[sizeof(BT_HDR) + sizeof(HciDataPreamble) + offset]{}; BT_HDR* bt_hdr = reinterpret_cast(hdr_data); ASSERT_TRUE(!IsPacketFlushable(bt_hdr)); @@ -558,13 +521,11 @@ TEST_F(MainShimTest, is_flushable) { { const size_t offset = 1024; - alignas(BT_HDR) - std::byte hdr_data[sizeof(BT_HDR) + sizeof(HciDataPreamble) + offset]{}; + alignas(BT_HDR) std::byte hdr_data[sizeof(BT_HDR) + sizeof(HciDataPreamble) + offset]{}; BT_HDR* bt_hdr = reinterpret_cast(hdr_data); uint8_t* p = ToPacketData(bt_hdr, L2CAP_SEND_CMD_OFFSET); - UINT16_TO_STREAM( - p, 0x123 | (L2CAP_PKT_START_NON_FLUSHABLE << L2CAP_PKT_TYPE_SHIFT)); + UINT16_TO_STREAM(p, 0x123 | (L2CAP_PKT_START_NON_FLUSHABLE << L2CAP_PKT_TYPE_SHIFT)); ASSERT_TRUE(!IsPacketFlushable(bt_hdr)); p = ToPacketData(bt_hdr, L2CAP_SEND_CMD_OFFSET); @@ -575,48 +536,38 @@ TEST_F(MainShimTest, is_flushable) { TEST_F(MainShimTest, BleScannerInterfaceImpl_nop) { auto* ble = static_cast( - bluetooth::shim::get_ble_scanner_instance()); + bluetooth::shim::get_ble_scanner_instance()); ASSERT_NE(nullptr, ble); } class TestScanningCallbacks : public ::ScanningCallbacks { - public: +public: ~TestScanningCallbacks() {} void OnScannerRegistered(const bluetooth::Uuid app_uuid, uint8_t scannerId, uint8_t status) override {} - void OnSetScannerParameterComplete(uint8_t scannerId, - uint8_t status) override {} - void OnScanResult(uint16_t event_type, uint8_t addr_type, RawAddress bda, - uint8_t primary_phy, uint8_t secondary_phy, - uint8_t advertising_sid, int8_t tx_power, int8_t rssi, - uint16_t periodic_adv_int, - std::vector adv_data) override {} - void OnTrackAdvFoundLost( - AdvertisingTrackInfo advertising_track_info) override {} - void OnBatchScanReports(int client_if, int status, int report_format, - int num_records, std::vector data) override { - } + void OnSetScannerParameterComplete(uint8_t scannerId, uint8_t status) override {} + void OnScanResult(uint16_t event_type, uint8_t addr_type, RawAddress bda, uint8_t primary_phy, + uint8_t secondary_phy, uint8_t advertising_sid, int8_t tx_power, int8_t rssi, + uint16_t periodic_adv_int, std::vector adv_data) override {} + void OnTrackAdvFoundLost(AdvertisingTrackInfo advertising_track_info) override {} + void OnBatchScanReports(int client_if, int status, int report_format, int num_records, + std::vector data) override {} void OnBatchScanThresholdCrossed(int client_if) override {} void OnPeriodicSyncStarted(int reg_id, uint8_t status, uint16_t sync_handle, - uint8_t advertising_sid, uint8_t address_type, - RawAddress address, uint8_t phy, - uint16_t interval) override{}; - void OnPeriodicSyncReport(uint16_t sync_handle, int8_t tx_power, int8_t rssi, - uint8_t status, - std::vector data) override{}; - void OnPeriodicSyncLost(uint16_t sync_handle) override{}; - void OnPeriodicSyncTransferred(int pa_source, uint8_t status, - RawAddress address) override{}; - void OnBigInfoReport(uint16_t sync_handle, bool encrypted) override{}; + uint8_t advertising_sid, uint8_t address_type, RawAddress address, + uint8_t phy, uint16_t interval) override {} + void OnPeriodicSyncReport(uint16_t sync_handle, int8_t tx_power, int8_t rssi, uint8_t status, + std::vector data) override {} + void OnPeriodicSyncLost(uint16_t sync_handle) override {} + void OnPeriodicSyncTransferred(int pa_source, uint8_t status, RawAddress address) override {} + void OnBigInfoReport(uint16_t sync_handle, bool encrypted) override {} }; TEST_F(MainShimTest, DISABLED_BleScannerInterfaceImpl_OnScanResult) { auto* ble = static_cast( - bluetooth::shim::get_ble_scanner_instance()); + bluetooth::shim::get_ble_scanner_instance()); - EXPECT_CALL(*hci::testing::mock_le_scanning_manager_, - RegisterScanningCallback(_)) - .Times(1); + EXPECT_CALL(*hci::testing::mock_le_scanning_manager_, RegisterScanningCallback(_)).Times(1); ; bluetooth::shim::init_scanning_manager(); @@ -636,9 +587,9 @@ TEST_F(MainShimTest, DISABLED_BleScannerInterfaceImpl_OnScanResult) { uint16_t periodic_advertising_interval = 0; std::vector advertising_data; - ble->OnScanResult(event_type, address_type, address, primary_phy, - secondary_phy, advertising_sid, tx_power, rssi, - periodic_advertising_interval, advertising_data); + ble->OnScanResult(event_type, address_type, address, primary_phy, secondary_phy, + advertising_sid, tx_power, rssi, periodic_advertising_interval, + advertising_data); } ASSERT_EQ(2 * 2048UL, do_in_jni_thread_task_queue.size()); @@ -651,12 +602,10 @@ TEST_F(MainShimTest, DISABLED_LeShimAclConnection_local_disconnect) { auto acl = MakeAcl(); EXPECT_CALL(*test::mock_acl_manager_, CreateLeConnection(_, _)).Times(1); - hci::AddressWithType local_address( - hci::Address{{0x01, 0x02, 0x03, 0x04, 0x05, 0x6}}, - hci::AddressType::RANDOM_DEVICE_ADDRESS); - hci::AddressWithType remote_address( - hci::Address{{0x01, 0x02, 0x03, 0x04, 0x05, 0x6}}, - hci::AddressType::RANDOM_DEVICE_ADDRESS); + hci::AddressWithType local_address(hci::Address{{0x01, 0x02, 0x03, 0x04, 0x05, 0x6}}, + hci::AddressType::RANDOM_DEVICE_ADDRESS); + hci::AddressWithType remote_address(hci::Address{{0x01, 0x02, 0x03, 0x04, 0x05, 0x6}}, + hci::AddressType::RANDOM_DEVICE_ADDRESS); // Allow LE connections to be accepted std::promise promise; @@ -667,9 +616,8 @@ TEST_F(MainShimTest, DISABLED_LeShimAclConnection_local_disconnect) { // Simulate LE connection successful uint16_t handle = 0x1234; auto connection = std::make_unique( - handle, - hci::acl_manager::DataAsPeripheral{local_address, std::nullopt, true}, - remote_address); + handle, hci::acl_manager::DataAsPeripheral{local_address, std::nullopt, true}, + remote_address); auto raw_connection = connection.get(); acl->OnLeConnectSuccess(remote_address, std::move(connection)); ASSERT_EQ(nullptr, connection); @@ -677,8 +625,7 @@ TEST_F(MainShimTest, DISABLED_LeShimAclConnection_local_disconnect) { // Initiate local LE disconnect mock_connection_le_on_disconnected_promise = std::promise(); - auto disconnect_future = - mock_connection_le_on_disconnected_promise.get_future(); + auto disconnect_future = mock_connection_le_on_disconnected_promise.get_future(); { raw_connection->disconnect_promise_ = std::promise(); auto future = raw_connection->disconnect_promise_.get_future(); @@ -696,22 +643,21 @@ TEST_F(MainShimTestWithClassicConnection, nop) {} TEST_F(MainShimTestWithClassicConnection, read_extended_feature) { int read_remote_extended_feature_call_count = 0; raw_connection_->read_remote_extended_features_function_ = - [&read_remote_extended_feature_call_count](uint8_t page_number) { - read_remote_extended_feature_call_count++; - }; + [&read_remote_extended_feature_call_count](uint8_t page_number) { + read_remote_extended_feature_call_count++; + }; // Handle typical case { read_remote_extended_feature_call_count = 0; const uint8_t max_page = 3; - raw_connection_->callbacks_->OnReadRemoteExtendedFeaturesComplete( - 1, max_page, 0xabcdef9876543210); - raw_connection_->callbacks_->OnReadRemoteExtendedFeaturesComplete( - 2, max_page, 0xbcdef9876543210a); - raw_connection_->callbacks_->OnReadRemoteExtendedFeaturesComplete( - 3, max_page, 0xcdef9876543210ab); - ASSERT_EQ(static_cast(max_page) - 1, - read_remote_extended_feature_call_count); + raw_connection_->callbacks_->OnReadRemoteExtendedFeaturesComplete(1, max_page, + 0xabcdef9876543210); + raw_connection_->callbacks_->OnReadRemoteExtendedFeaturesComplete(2, max_page, + 0xbcdef9876543210a); + raw_connection_->callbacks_->OnReadRemoteExtendedFeaturesComplete(3, max_page, + 0xcdef9876543210ab); + ASSERT_EQ(static_cast(max_page) - 1, read_remote_extended_feature_call_count); } // Handle extreme case @@ -720,36 +666,31 @@ TEST_F(MainShimTestWithClassicConnection, read_extended_feature) { const uint8_t max_page = 255; for (int page = 1; page < static_cast(max_page) + 1; page++) { raw_connection_->callbacks_->OnReadRemoteExtendedFeaturesComplete( - static_cast(page), max_page, 0xabcdef9876543210); + static_cast(page), max_page, 0xabcdef9876543210); } - ASSERT_EQ(static_cast(max_page - 1), - read_remote_extended_feature_call_count); + ASSERT_EQ(static_cast(max_page - 1), read_remote_extended_feature_call_count); } // Handle case where device returns max page of zero { read_remote_extended_feature_call_count = 0; const uint8_t max_page = 0; - raw_connection_->callbacks_->OnReadRemoteExtendedFeaturesComplete( - 1, max_page, 0xabcdef9876543210); + raw_connection_->callbacks_->OnReadRemoteExtendedFeaturesComplete(1, max_page, + 0xabcdef9876543210); ASSERT_EQ(0, read_remote_extended_feature_call_count); } raw_connection_->read_remote_extended_features_function_ = {}; } -TEST_F(MainShimTest, acl_dumpsys) { - MakeAcl()->Dump(std::make_unique()->Fd()); -} +TEST_F(MainShimTest, acl_dumpsys) { MakeAcl()->Dump(std::make_unique()->Fd()); } TEST_F(MainShimTest, ticks_to_milliseconds) { - ASSERT_THAT(kTicksInMs, - DoubleNear(ticks_to_milliseconds(kTicks), kMaxAbsoluteError)); + ASSERT_THAT(kTicksInMs, DoubleNear(ticks_to_milliseconds(kTicks), kMaxAbsoluteError)); } TEST_F(MainShimTest, ticks_to_seconds) { - ASSERT_THAT(kTicksInSec, - DoubleNear(ticks_to_seconds(kTicks), kMaxAbsoluteError)); + ASSERT_THAT(kTicksInSec, DoubleNear(ticks_to_seconds(kTicks), kMaxAbsoluteError)); } TEST_F(MainShimTest, DumpConnectionHistory) { @@ -758,11 +699,11 @@ TEST_F(MainShimTest, DumpConnectionHistory) { } TEST_F(MainShimTest, OnConnectRequest) { - acl_interface.connection.classic.on_connect_request = - [](const RawAddress& bda, const hci::ClassOfDevice& cod) { - ASSERT_STREQ(kAddress.ToString().c_str(), bda.ToString().c_str()); - ASSERT_STREQ(kCod.ToString().c_str(), cod.ToString().c_str()); - }; + acl_interface.connection.classic.on_connect_request = [](const RawAddress& bda, + const hci::ClassOfDevice& cod) { + ASSERT_STREQ(kAddress.ToString().c_str(), bda.ToString().c_str()); + ASSERT_STREQ(kCod.ToString().c_str(), cod.ToString().c_str()); + }; auto acl = MakeAcl(); acl->OnConnectRequest(kAddress, kCod); } @@ -772,19 +713,19 @@ TEST_F(MainShimTest, DumpsysNeighbor) { btm_cb.neighbor = {}; btm_cb.neighbor.inquiry_history_->Push({ - .status = tBTM_INQUIRY_CMPL::CANCELED, - .hci_status = HCI_SUCCESS, - .num_resp = 45, - .resp_type = {20, 30, 40}, - .start_time_ms = 0, + .status = tBTM_INQUIRY_CMPL::CANCELED, + .hci_status = HCI_SUCCESS, + .num_resp = 45, + .resp_type = {20, 30, 40}, + .start_time_ms = 0, }); btm_cb.neighbor.inquiry_history_->Push({ - .status = tBTM_INQUIRY_CMPL::CANCELED, - .hci_status = HCI_SUCCESS, - .num_resp = 123, - .resp_type = {50, 60, 70}, - .start_time_ms = -1, + .status = tBTM_INQUIRY_CMPL::CANCELED, + .hci_status = HCI_SUCCESS, + .num_resp = 123, + .resp_type = {50, 60, 70}, + .start_time_ms = -1, }); DumpsysNeighbor(STDOUT_FILENO); @@ -799,5 +740,5 @@ TEST(MainShimRegressionTest, OOB_In_StartAdvertisingSet) { bluetooth::shim::parse_gap_data(raw_data, res); - ASSERT_EQ(res.size(), (size_t) 0); + ASSERT_EQ(res.size(), (size_t)0); } diff --git a/system/osi/include/alarm.h b/system/osi/include/alarm.h index 2db228bf79d..486568db451 100644 --- a/system/osi/include/alarm.h +++ b/system/osi/include/alarm.h @@ -70,14 +70,12 @@ void alarm_free(alarm_t* alarm); // thread is not same as the caller’s thread. If two (or more) // alarms are set back-to-back with the same |interval_ms|, the // callbacks will be called in the order the alarms are set. -void alarm_set(alarm_t* alarm, uint64_t interval_ms, alarm_callback_t cb, - void* data); +void alarm_set(alarm_t* alarm, uint64_t interval_ms, alarm_callback_t cb, void* data); // Sets an |alarm| to execute a callback in the main message loop. This function // is same as |alarm_set| except that the |cb| callback is scheduled for // execution in the context of the main message loop. -void alarm_set_on_mloop(alarm_t* alarm, uint64_t interval_ms, - alarm_callback_t cb, void* data); +void alarm_set_on_mloop(alarm_t* alarm, uint64_t interval_ms, alarm_callback_t cb, void* data); // This function cancels the |alarm| if it was previously set. // When this call returns, the caller has a guarantee that the diff --git a/system/osi/include/allocator.h b/system/osi/include/allocator.h index f4cfc393700..af4b57ee92d 100644 --- a/system/osi/include/allocator.h +++ b/system/osi/include/allocator.h @@ -48,12 +48,12 @@ void osi_free(void* ptr); void osi_free_and_reset(void** p_ptr); class OsiObject { - public: +public: OsiObject(void* ptr); OsiObject(const void* ptr); ~OsiObject(); void* Release(); - private: +private: void* ptr_; }; diff --git a/system/osi/include/config.h b/system/osi/include/config.h index a74314d55a4..f0a0e642f7d 100644 --- a/system/osi/include/config.h +++ b/system/osi/include/config.h @@ -17,6 +17,7 @@ // - All strings are case sensitive. #include + #include #include #include @@ -70,14 +71,13 @@ bool config_has_section(const config_t& config, const std::string& section); // Returns true if the config file has a key named |key| under |section|. // Returns false otherwise. -bool config_has_key(const config_t& config, const std::string& section, - const std::string& key); +bool config_has_key(const config_t& config, const std::string& section, const std::string& key); // Returns the integral value for a given |key| in |section|. If |section| // or |key| do not exist, or the value cannot be fully converted to an integer, // this function returns |def_value|. -int config_get_int(const config_t& config, const std::string& section, - const std::string& key, int def_value); +int config_get_int(const config_t& config, const std::string& section, const std::string& key, + int def_value); // Returns the uint64_t value for a given |key| in |section|. If |section| // or |key| do not exist, or the value cannot be fully converted to an integer, @@ -88,37 +88,35 @@ uint64_t config_get_uint64(const config_t& config, const std::string& section, // Returns the boolean value for a given |key| in |section|. If |section| // or |key| do not exist, or the value cannot be converted to a boolean, this // function returns |def_value|. -bool config_get_bool(const config_t& config, const std::string& section, - const std::string& key, bool def_value); +bool config_get_bool(const config_t& config, const std::string& section, const std::string& key, + bool def_value); // Returns the string value for a given |key| in |section|. If |section| or // |key| do not exist, this function returns |def_value|. The returned string // is owned by the config module and must not be freed or modified. |def_value| // may be NULL. -const std::string* config_get_string(const config_t& config, - const std::string& section, - const std::string& key, - const std::string* def_value); +const std::string* config_get_string(const config_t& config, const std::string& section, + const std::string& key, const std::string* def_value); // Sets an integral value for the |key| in |section|. If |key| or |section| do // not already exist, this function creates them. |config| must not be NULL. -void config_set_int(config_t* config, const std::string& section, - const std::string& key, int value); +void config_set_int(config_t* config, const std::string& section, const std::string& key, + int value); // Sets a uint64_t value for the |key| in |section|. If |key| or |section| do // not already exist, this function creates them. |config| must not be NULL. -void config_set_uint64(config_t* config, const std::string& section, - const std::string& key, uint64_t value); +void config_set_uint64(config_t* config, const std::string& section, const std::string& key, + uint64_t value); // Sets a boolean value for the |key| in |section|. If |key| or |section| do // not already exist, this function creates them. |config| must not be NULL. -void config_set_bool(config_t* config, const std::string& section, - const std::string& key, bool value); +void config_set_bool(config_t* config, const std::string& section, const std::string& key, + bool value); // Sets a string value for the |key| in |section|. If |key| or |section| do // not already exist, this function creates them. |config| must not be NULL. -void config_set_string(config_t* config, const std::string& section, - const std::string& key, const std::string& value); +void config_set_string(config_t* config, const std::string& section, const std::string& key, + const std::string& value); // Removes |section| from the |config| (and, as a result, all keys in the // section). @@ -131,8 +129,7 @@ bool config_remove_section(config_t* config, const std::string& section); // true // if the section and key were found and the key was removed, false otherwise. // |config|may not be NULL. -bool config_remove_key(config_t* config, const std::string& section, - const std::string& key); +bool config_remove_key(config_t* config, const std::string& section, const std::string& key); // Saves |config| to a file given by |filename|. Note that this could be a // destructive operation: if |filename| already exists, it will be overwritten. diff --git a/system/osi/include/fixed_queue.h b/system/osi/include/fixed_queue.h index adbc5be1bde..1d164546e6a 100644 --- a/system/osi/include/fixed_queue.h +++ b/system/osi/include/fixed_queue.h @@ -125,8 +125,8 @@ int fixed_queue_get_dequeue_fd(const fixed_queue_t* queue); // element in the queue, ready_cb will be called. The |context| parameter is // passed, untouched, to the callback routine. Neither |queue|, nor |reactor|, // nor |read_cb| may be NULL. |context| may be NULL. -void fixed_queue_register_dequeue(fixed_queue_t* queue, reactor_t* reactor, - fixed_queue_cb ready_cb, void* context); +void fixed_queue_register_dequeue(fixed_queue_t* queue, reactor_t* reactor, fixed_queue_cb ready_cb, + void* context); // Unregisters the dequeue ready callback for |queue| from whichever reactor // it is registered with, if any. This function is idempotent. diff --git a/system/osi/include/hash_map_utils.h b/system/osi/include/hash_map_utils.h index b55d670ddc4..833c974f4be 100644 --- a/system/osi/include/hash_map_utils.h +++ b/system/osi/include/hash_map_utils.h @@ -30,5 +30,5 @@ // "key0=;key1=value1;" -> map: [key0]="" [key1]="value1" // "=value0;key1=value1;" -> map: [key1]="value1" // A new hash map or NULL is returned and is owned by the caller. -std::unordered_map -hash_map_utils_new_from_string_params(const char* params); +std::unordered_map hash_map_utils_new_from_string_params( + const char* params); diff --git a/system/osi/include/list.h b/system/osi/include/list.h index ae738f5581e..b97981fd741 100644 --- a/system/osi/include/list.h +++ b/system/osi/include/list.h @@ -114,8 +114,7 @@ void list_clear(list_t* list); // the list inside the callback. If an element is added before the node being // visited, there will be no callback for the newly-inserted node. Neither // |list| nor |callback| may be NULL. -list_node_t* list_foreach(const list_t* list, list_iter_cb callback, - void* context); +list_node_t* list_foreach(const list_t* list, list_iter_cb callback, void* context); // Returns an iterator to the first element in |list|. |list| may not be NULL. // The returned iterator is valid as long as it does not equal the value diff --git a/system/osi/include/properties.h b/system/osi/include/properties.h index 3d2b3a68f21..c170c18331d 100644 --- a/system/osi/include/properties.h +++ b/system/osi/include/properties.h @@ -55,5 +55,5 @@ bool osi_property_get_bool(const char* key, bool default_value); // Helper function that returns the value of |key| coerced into a vector of // uint32_t. If the property is not set, then the |default_value| is used. -std::vector osi_property_get_uintlist( - const char* key, std::vector default_value); \ No newline at end of file +std::vector osi_property_get_uintlist(const char* key, + std::vector default_value); \ No newline at end of file diff --git a/system/osi/include/reactor.h b/system/osi/include/reactor.h index 211cdd8bfc8..ccb4c311ddc 100644 --- a/system/osi/include/reactor.h +++ b/system/osi/include/reactor.h @@ -77,8 +77,7 @@ reactor_object_t* reactor_register(reactor_t* reactor, int fd, void* context, // |write_ready| callback routines, they can call this routine. Returns true if // the subscription was changed, false otherwise. // |object| may not be NULL, |read_ready| and |write_ready| may be NULL. -bool reactor_change_registration(reactor_object_t* object, - void (*read_ready)(void* context), +bool reactor_change_registration(reactor_object_t* object, void (*read_ready)(void* context), void (*write_ready)(void* context)); // Unregisters a previously registered file descriptor with its reactor. |obj| diff --git a/system/osi/include/ringbuffer.h b/system/osi/include/ringbuffer.h index af7982ab068..03a7447b570 100644 --- a/system/osi/include/ringbuffer.h +++ b/system/osi/include/ringbuffer.h @@ -52,8 +52,7 @@ size_t ringbuffer_insert(ringbuffer_t* rb, const uint8_t* p, size_t length); // into the buffer |p|. Return the actual number of bytes peeked. Can be less // than |length| if there is less than |length| data available. |offset| must // be non-negative. -size_t ringbuffer_peek(const ringbuffer_t* rb, off_t offset, uint8_t* p, - size_t length); +size_t ringbuffer_peek(const ringbuffer_t* rb, off_t offset, uint8_t* p, size_t length); // Does the same as |ringbuffer_peek|, but also advances the ring buffer head size_t ringbuffer_pop(ringbuffer_t* rb, uint8_t* p, size_t length); diff --git a/system/osi/include/socket.h b/system/osi/include/socket.h index 83a4f2d5488..25559fdc7de 100644 --- a/system/osi/include/socket.h +++ b/system/osi/include/socket.h @@ -84,8 +84,7 @@ ssize_t socket_write(const socket_t* socket, const void* buf, size_t count); // of |fd| transfers to this function and the descriptor must not be used any // longer. If |fd| is INVALID_FD, this function behaves the same as // |socket_write|. -ssize_t socket_write_and_transfer_fd(const socket_t* socket, const void* buf, - size_t count, int fd); +ssize_t socket_write_and_transfer_fd(const socket_t* socket, const void* buf, size_t count, int fd); // Returns the number of bytes that can be read from |socket| without blocking. // On error, this function returns -1. |socket| may not be NULL. @@ -101,8 +100,8 @@ ssize_t socket_bytes_available(const socket_t* socket); // be called. The |context| parameter is passed, untouched, to each of the // callback routines. Neither |socket| nor |reactor| may be NULL. |read_cb|, // |write_cb|, and |context| may be NULL. -void socket_register(socket_t* socket, reactor_t* reactor, void* context, - socket_cb read_cb, socket_cb write_cb); +void socket_register(socket_t* socket, reactor_t* reactor, void* context, socket_cb read_cb, + socket_cb write_cb); // Unregisters |socket| from whichever reactor it is registered with, if any. // This function is idempotent. diff --git a/system/osi/include/socket_utils/socket_local.h b/system/osi/include/socket_utils/socket_local.h index 9fcb9d53583..8bdc97a3435 100644 --- a/system/osi/include/socket_utils/socket_local.h +++ b/system/osi/include/socket_utils/socket_local.h @@ -32,5 +32,5 @@ * * @return 0 on success or -1 on failure */ -int osi_socket_make_sockaddr_un(const char* name, int namespaceId, - struct sockaddr_un* p_addr, socklen_t* alen); +int osi_socket_make_sockaddr_un(const char* name, int namespaceId, struct sockaddr_un* p_addr, + socklen_t* alen); diff --git a/system/osi/include/socket_utils/sockets.h b/system/osi/include/socket_utils/sockets.h index 9597c2a1ee7..d44f76abdd8 100644 --- a/system/osi/include/socket_utils/sockets.h +++ b/system/osi/include/socket_utils/sockets.h @@ -65,6 +65,5 @@ static inline int osi_android_get_control_socket(const char* name) { int osi_socket_local_server(const char* name, int namespaceId, int type); int osi_socket_local_server_bind(int s, const char* name, int namespaceId); -int osi_socket_local_client_connect(int fd, const char* name, int namespaceId, - int type); +int osi_socket_local_client_connect(int fd, const char* name, int namespaceId, int type); int osi_socket_local_client(const char* name, int namespaceId, int type); diff --git a/system/osi/include/stack_power_telemetry.h b/system/osi/include/stack_power_telemetry.h index 1626d6d45e7..927c1f6c63f 100644 --- a/system/osi/include/stack_power_telemetry.h +++ b/system/osi/include/stack_power_telemetry.h @@ -26,7 +26,7 @@ namespace power_telemetry { struct PowerTelemetryImpl; class PowerTelemetry { - public: +public: PowerTelemetry(); void RecordLogDataContainer(); @@ -35,19 +35,18 @@ class PowerTelemetry { void LogHciCmdDetail(); void LogHciEvtDetail(); - void LogLinkDetails(uint16_t handle, const RawAddress& bdaddr, - bool isConnected, bool is_acl_link); + void LogLinkDetails(uint16_t handle, const RawAddress& bdaddr, bool isConnected, + bool is_acl_link); void LogRxAclPktData(uint16_t len); void LogTxAclPktData(uint16_t len); - void LogChannelConnected(uint16_t psm, int32_t src_id, int32_t dst_id, - const RawAddress& bd_addr); + void LogChannelConnected(uint16_t psm, int32_t src_id, int32_t dst_id, const RawAddress& bd_addr); void LogChannelDisconnected(uint16_t psm, int32_t src_id, int32_t dst_id, const RawAddress& bd_addr); - void LogRxBytes(uint16_t psm, int32_t src_id, int32_t dst_id, - const RawAddress& bd_addr, int32_t num_bytes); - void LogTxBytes(uint16_t psm, int32_t src_id, int32_t dst_id, - const RawAddress& bd_addr, int32_t num_bytes); + void LogRxBytes(uint16_t psm, int32_t src_id, int32_t dst_id, const RawAddress& bd_addr, + int32_t num_bytes); + void LogTxBytes(uint16_t psm, int32_t src_id, int32_t dst_id, const RawAddress& bd_addr, + int32_t num_bytes); void LogSniffStarted(uint16_t handle, const RawAddress& bdaddr); void LogSniffStopped(uint16_t handle, const RawAddress& bdaddr); diff --git a/system/osi/src/alarm.cc b/system/osi/src/alarm.cc index b0206d326ac..0d515c486df 100644 --- a/system/osi/src/alarm.cc +++ b/system/osi/src/alarm.cc @@ -73,7 +73,9 @@ struct CancelableClosureInStruct { base::CancelableClosure i; CancelableClosureInStruct& operator=(const CancelableClosureInStruct& in) { - if (!in.i.callback().is_null()) i.Reset(in.i.callback()); + if (!in.i.callback().is_null()) { + i.Reset(in.i.callback()); + } return *this; } }; @@ -96,7 +98,7 @@ struct alarm_t { void* data; alarm_stats_t stats; - bool for_msg_loop; // True, if the alarm should be processed on message loop + bool for_msg_loop; // True, if the alarm should be processed on message loop CancelableClosureInStruct closure; // posted to message loop for processing }; @@ -128,8 +130,7 @@ static fixed_queue_t* default_callback_queue; static alarm_t* alarm_new_internal(const char* name, bool is_periodic); static bool lazy_initialize(void); static uint64_t now_ms(void); -static void alarm_set_internal(alarm_t* alarm, uint64_t period_ms, - alarm_callback_t cb, void* data, +static void alarm_set_internal(alarm_t* alarm, uint64_t period_ms, alarm_callback_t cb, void* data, fixed_queue_t* queue, bool for_msg_loop); static void alarm_cancel_internal(alarm_t* alarm); static void remove_pending_alarm(alarm_t* alarm); @@ -139,24 +140,22 @@ static void alarm_queue_ready(fixed_queue_t* queue, void* context); static void timer_callback(void* data); static void callback_dispatch(void* context); static bool timer_create_internal(const clockid_t clock_id, timer_t* timer); -static void update_scheduling_stats(alarm_stats_t* stats, uint64_t now_ms, - uint64_t deadline_ms); +static void update_scheduling_stats(alarm_stats_t* stats, uint64_t now_ms, uint64_t deadline_ms); // Registers |queue| for processing alarm callbacks on |thread|. // |queue| may not be NULL. |thread| may not be NULL. -static void alarm_register_processing_queue(fixed_queue_t* queue, - thread_t* thread); +static void alarm_register_processing_queue(fixed_queue_t* queue, thread_t* thread); static void update_stat(stat_t* stat, uint64_t delta_ms) { - if (stat->max_ms < delta_ms) stat->max_ms = delta_ms; + if (stat->max_ms < delta_ms) { + stat->max_ms = delta_ms; + } stat->total_ms += delta_ms; stat->count++; } alarm_t* alarm_new(const char* name) { return alarm_new_internal(name, false); } -alarm_t* alarm_new_periodic(const char* name) { - return alarm_new_internal(name, true); -} +alarm_t* alarm_new_periodic(const char* name) { return alarm_new_internal(name, true); } static alarm_t* alarm_new_internal(const char* name, bool is_periodic) { // Make sure we have a list we can insert alarms into. @@ -183,7 +182,9 @@ static alarm_t* alarm_new_internal(const char* name, bool is_periodic) { } void alarm_free(alarm_t* alarm) { - if (!alarm) return; + if (!alarm) { + return; + } alarm_cancel(alarm); @@ -199,26 +200,23 @@ uint64_t alarm_get_remaining_ms(const alarm_t* alarm) { uint64_t just_now_ms = now_ms(); std::lock_guard lock(alarms_mutex); - if (alarm->deadline_ms > just_now_ms) + if (alarm->deadline_ms > just_now_ms) { remaining_ms = alarm->deadline_ms - just_now_ms; + } return remaining_ms; } -void alarm_set(alarm_t* alarm, uint64_t interval_ms, alarm_callback_t cb, - void* data) { - alarm_set_internal(alarm, interval_ms, cb, data, default_callback_queue, - false); +void alarm_set(alarm_t* alarm, uint64_t interval_ms, alarm_callback_t cb, void* data) { + alarm_set_internal(alarm, interval_ms, cb, data, default_callback_queue, false); } -void alarm_set_on_mloop(alarm_t* alarm, uint64_t interval_ms, - alarm_callback_t cb, void* data) { +void alarm_set_on_mloop(alarm_t* alarm, uint64_t interval_ms, alarm_callback_t cb, void* data) { alarm_set_internal(alarm, interval_ms, cb, data, NULL, true); } // Runs in exclusion with alarm_cancel and timer_callback. -static void alarm_set_internal(alarm_t* alarm, uint64_t period_ms, - alarm_callback_t cb, void* data, +static void alarm_set_internal(alarm_t* alarm, uint64_t period_ms, alarm_callback_t cb, void* data, fixed_queue_t* queue, bool for_msg_loop) { log::assert_that(alarms != NULL, "assert failed: alarms != NULL"); log::assert_that(alarm != NULL, "assert failed: alarm != NULL"); @@ -239,7 +237,9 @@ static void alarm_set_internal(alarm_t* alarm, uint64_t period_ms, void alarm_cancel(alarm_t* alarm) { log::assert_that(alarms != NULL, "assert failed: alarms != NULL"); - if (!alarm) return; + if (!alarm) { + return; + } std::shared_ptr local_mutex_ref; { @@ -255,8 +255,7 @@ void alarm_cancel(alarm_t* alarm) { // Internal implementation of canceling an alarm. // The caller must hold the |alarms_mutex| static void alarm_cancel_internal(alarm_t* alarm) { - bool needs_reschedule = - (!list_is_empty(alarms) && list_front(alarms) == alarm); + bool needs_reschedule = (!list_is_empty(alarms) && list_front(alarms) == alarm); remove_pending_alarm(alarm); @@ -267,17 +266,23 @@ static void alarm_cancel_internal(alarm_t* alarm) { alarm->stats.canceled_count++; alarm->queue = NULL; - if (needs_reschedule) reschedule_root_alarm(); + if (needs_reschedule) { + reschedule_root_alarm(); + } } bool alarm_is_scheduled(const alarm_t* alarm) { - if ((alarms == NULL) || (alarm == NULL)) return false; - return (alarm->callback != NULL); + if ((alarms == NULL) || (alarm == NULL)) { + return false; + } + return alarm->callback != NULL; } void alarm_cleanup(void) { // If lazy_initialize never ran there is nothing else to do - if (!alarms) return; + if (!alarms) { + return; + } dispatcher_thread_active = false; semaphore_post(alarm_expired); @@ -316,7 +321,9 @@ static bool lazy_initialize(void) { goto error; } - if (!timer_create_internal(CLOCK_ID, &timer)) goto error; + if (!timer_create_internal(CLOCK_ID, &timer)) { + goto error; + } timer_initialized = true; if (!timer_create_internal(CLOCK_BOOTTIME_ALARM, &wakeup_timer)) { @@ -332,8 +339,7 @@ static bool lazy_initialize(void) { goto error; } - default_callback_thread = - thread_new_sized("alarm_default_callbacks", SIZE_MAX); + default_callback_thread = thread_new_sized("alarm_default_callbacks", SIZE_MAX); if (default_callback_thread == NULL) { log::error("unable to create default alarm callbacks thread."); goto error; @@ -344,8 +350,7 @@ static bool lazy_initialize(void) { log::error("unable to create default alarm callbacks queue."); goto error; } - alarm_register_processing_queue(default_callback_queue, - default_callback_thread); + alarm_register_processing_queue(default_callback_queue, default_callback_thread); dispatcher_thread_active = true; dispatcher_thread = thread_new("alarm_dispatcher"); @@ -371,9 +376,13 @@ error: semaphore_free(alarm_expired); alarm_expired = NULL; - if (wakeup_timer_initialized) timer_delete(wakeup_timer); + if (wakeup_timer_initialized) { + timer_delete(wakeup_timer); + } - if (timer_initialized) timer_delete(timer); + if (timer_initialized) { + timer_delete(timer); + } list_free(alarms); alarms = NULL; @@ -413,25 +422,24 @@ static void remove_pending_alarm(alarm_t* alarm) { static void schedule_next_instance(alarm_t* alarm) { // If the alarm is currently set and it's at the start of the list, // we'll need to re-schedule since we've adjusted the earliest deadline. - bool needs_reschedule = - (!list_is_empty(alarms) && list_front(alarms) == alarm); - if (alarm->callback) remove_pending_alarm(alarm); + bool needs_reschedule = (!list_is_empty(alarms) && list_front(alarms) == alarm); + if (alarm->callback) { + remove_pending_alarm(alarm); + } // Calculate the next deadline for this alarm uint64_t just_now_ms = now_ms(); uint64_t ms_into_period = 0; - if ((alarm->is_periodic) && (alarm->period_ms != 0)) - ms_into_period = - ((just_now_ms - alarm->creation_time_ms) % alarm->period_ms); + if ((alarm->is_periodic) && (alarm->period_ms != 0)) { + ms_into_period = ((just_now_ms - alarm->creation_time_ms) % alarm->period_ms); + } alarm->deadline_ms = just_now_ms + (alarm->period_ms - ms_into_period); // Add it into the timer list sorted by deadline (earliest deadline first). - if (list_is_empty(alarms) || - ((alarm_t*)list_front(alarms))->deadline_ms > alarm->deadline_ms) { + if (list_is_empty(alarms) || ((alarm_t*)list_front(alarms))->deadline_ms > alarm->deadline_ms) { list_prepend(alarms, alarm); } else { - for (list_node_t* node = list_begin(alarms); node != list_end(alarms); - node = list_next(node)) { + for (list_node_t* node = list_begin(alarms); node != list_end(alarms); node = list_next(node)) { list_node_t* next = list_next(node); if (next == list_end(alarms) || ((alarm_t*)list_node(next))->deadline_ms > alarm->deadline_ms) { @@ -443,8 +451,7 @@ static void schedule_next_instance(alarm_t* alarm) { // If the new alarm has the earliest deadline, we need to re-evaluate our // schedule. - if (needs_reschedule || - (!list_is_empty(alarms) && list_front(alarms) == alarm)) { + if (needs_reschedule || (!list_is_empty(alarms) && list_front(alarms) == alarm)) { reschedule_root_alarm(); } } @@ -461,7 +468,9 @@ static void reschedule_root_alarm(void) { struct itimerspec timer_time; memset(&timer_time, 0, sizeof(timer_time)); - if (list_is_empty(alarms)) goto done; + if (list_is_empty(alarms)) { + goto done; + } next = static_cast(list_front(alarms)); next_expiration = next->deadline_ms - now_ms(); @@ -500,19 +509,20 @@ static void reschedule_root_alarm(void) { wakeup_time.it_value.tv_sec = (next->deadline_ms / 1000); wakeup_time.it_value.tv_nsec = (next->deadline_ms % 1000) * 1000000LL; - if (timer_settime(wakeup_timer, TIMER_ABSTIME, &wakeup_time, NULL) == -1) + if (timer_settime(wakeup_timer, TIMER_ABSTIME, &wakeup_time, NULL) == -1) { log::error("unable to set wakeup timer: {}", strerror(errno)); + } } done: - timer_set = - timer_time.it_value.tv_sec != 0 || timer_time.it_value.tv_nsec != 0; + timer_set = timer_time.it_value.tv_sec != 0 || timer_time.it_value.tv_nsec != 0; if (timer_was_set && !timer_set) { wakelock_release(); } - if (timer_settime(timer, TIMER_ABSTIME, &timer_time, NULL) == -1) + if (timer_settime(timer, TIMER_ABSTIME, &timer_time, NULL) == -1) { log::error("unable to set timer: {}", strerror(errno)); + } // If next expiration was in the past (e.g. short timer that got context // switched) then the timer might have diarmed itself. Detect this case and @@ -527,26 +537,21 @@ done: if (timer_set) { struct itimerspec time_to_expire; timer_gettime(timer, &time_to_expire); - if (time_to_expire.it_value.tv_sec == 0 && - time_to_expire.it_value.tv_nsec == 0) { - log::info( - "alarm expiration too close for posix timers, switching to guns"); + if (time_to_expire.it_value.tv_sec == 0 && time_to_expire.it_value.tv_nsec == 0) { + log::info("alarm expiration too close for posix timers, switching to guns"); semaphore_post(alarm_expired); } } } -static void alarm_register_processing_queue(fixed_queue_t* queue, - thread_t* thread) { +static void alarm_register_processing_queue(fixed_queue_t* queue, thread_t* thread) { log::assert_that(queue != NULL, "assert failed: queue != NULL"); log::assert_that(thread != NULL, "assert failed: thread != NULL"); - fixed_queue_register_dequeue(queue, thread_get_reactor(thread), - alarm_queue_ready, NULL); + fixed_queue_register_dequeue(queue, thread_get_reactor(thread), alarm_queue_ready, NULL); } -static void alarm_ready_generic(alarm_t* alarm, - std::unique_lock& lock) { +static void alarm_ready_generic(alarm_t* alarm, std::unique_lock& lock) { if (alarm == NULL) { return; // The alarm was probably canceled } @@ -610,7 +615,9 @@ static void timer_callback(void* /* ptr */) { semaphore_post(alarm_expired); } static void callback_dispatch(void* /* context */) { while (true) { semaphore_wait(alarm_expired); - if (!dispatcher_thread_active) break; + if (!dispatcher_thread_active) { + break; + } std::lock_guard lock(alarms_mutex); alarm_t* alarm; @@ -619,8 +626,7 @@ static void callback_dispatch(void* /* context */) { // We're done here if there are no alarms or the alarm at the front is in // the future. Exit right away since there's nothing left to do. if (list_is_empty(alarms) || - (alarm = static_cast(list_front(alarms)))->deadline_ms > - now_ms()) { + (alarm = static_cast(list_front(alarms)))->deadline_ms > now_ms()) { reschedule_root_alarm(); continue; } @@ -668,17 +674,16 @@ static bool timer_create_internal(const clockid_t clock_id, timer_t* timer) { sigevent.sigev_notify_function = (void (*)(union sigval))timer_callback; sigevent.sigev_notify_attributes = &thread_attr; if (timer_create(clock_id, &sigevent, timer) == -1) { - log::error("unable to create timer with clock {}: {}", clock_id, - strerror(errno)); + log::error("unable to create timer with clock {}: {}", clock_id, strerror(errno)); if (clock_id == CLOCK_BOOTTIME_ALARM) { log::error( - "The kernel might not have support for " - "timer_create(CLOCK_BOOTTIME_ALARM): " - "https://lwn.net/Articles/429925/"); + "The kernel might not have support for " + "timer_create(CLOCK_BOOTTIME_ALARM): " + "https://lwn.net/Articles/429925/"); log::error( - "See following patches: " - "https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/log/" - "?qt=grep&q=CLOCK_BOOTTIME_ALARM"); + "See following patches: " + "https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/log/" + "?qt=grep&q=CLOCK_BOOTTIME_ALARM"); } return false; } @@ -686,8 +691,7 @@ static bool timer_create_internal(const clockid_t clock_id, timer_t* timer) { return true; } -static void update_scheduling_stats(alarm_stats_t* stats, uint64_t now_ms, - uint64_t deadline_ms) { +static void update_scheduling_stats(alarm_stats_t* stats, uint64_t now_ms, uint64_t deadline_ms) { stats->total_updates++; stats->last_update_ms = now_ms; @@ -704,11 +708,12 @@ static void update_scheduling_stats(alarm_stats_t* stats, uint64_t now_ms, static void dump_stat(int fd, stat_t* stat, const char* description) { uint64_t average_time_ms = 0; - if (stat->count != 0) average_time_ms = stat->total_ms / stat->count; + if (stat->count != 0) { + average_time_ms = stat->total_ms / stat->count; + } - dprintf(fd, "%-51s: %llu / %llu / %llu\n", description, - (unsigned long long)stat->total_ms, (unsigned long long)stat->max_ms, - (unsigned long long)average_time_ms); + dprintf(fd, "%-51s: %llu / %llu / %llu\n", description, (unsigned long long)stat->total_ms, + (unsigned long long)stat->max_ms, (unsigned long long)average_time_ms); } void alarm_debug_dump(int fd) { @@ -726,31 +731,24 @@ void alarm_debug_dump(int fd) { dprintf(fd, " Total Alarms: %zu\n\n", list_length(alarms)); // Dump info for each alarm - for (list_node_t* node = list_begin(alarms); node != list_end(alarms); - node = list_next(node)) { + for (list_node_t* node = list_begin(alarms); node != list_end(alarms); node = list_next(node)) { alarm_t* alarm = (alarm_t*)list_node(node); alarm_stats_t* stats = &alarm->stats; - dprintf(fd, " Alarm : %s (%s)\n", stats->name, - (alarm->is_periodic) ? "PERIODIC" : "SINGLE"); + dprintf(fd, " Alarm : %s (%s)\n", stats->name, (alarm->is_periodic) ? "PERIODIC" : "SINGLE"); - dprintf(fd, "%-51s: %zu / %zu / %zu / %zu\n", - " Action counts (sched/resched/exec/cancel)", - stats->scheduled_count, stats->rescheduled_count, - stats->total_updates, stats->canceled_count); + dprintf(fd, "%-51s: %zu / %zu / %zu / %zu\n", " Action counts (sched/resched/exec/cancel)", + stats->scheduled_count, stats->rescheduled_count, stats->total_updates, + stats->canceled_count); - dprintf(fd, "%-51s: %zu / %zu\n", - " Deviation counts (overdue/premature)", + dprintf(fd, "%-51s: %zu / %zu\n", " Deviation counts (overdue/premature)", stats->overdue_scheduling.count, stats->premature_scheduling.count); - dprintf(fd, "%-51s: %llu / %llu / %lld\n", - " Time in ms (since creation/interval/remaining)", + dprintf(fd, "%-51s: %llu / %llu / %lld\n", " Time in ms (since creation/interval/remaining)", (unsigned long long)(just_now_ms - alarm->creation_time_ms), - (unsigned long long)alarm->period_ms, - (long long)(alarm->deadline_ms - just_now_ms)); + (unsigned long long)alarm->period_ms, (long long)(alarm->deadline_ms - just_now_ms)); - dump_stat(fd, &stats->overdue_scheduling, - " Overdue scheduling time in ms (total/max/avg)"); + dump_stat(fd, &stats->overdue_scheduling, " Overdue scheduling time in ms (total/max/avg)"); dump_stat(fd, &stats->premature_scheduling, " Premature scheduling time in ms (total/max/avg)"); diff --git a/system/osi/src/allocator.cc b/system/osi/src/allocator.cc index 1ffd7dcbc00..fb651468bcc 100644 --- a/system/osi/src/allocator.cc +++ b/system/osi/src/allocator.cc @@ -26,10 +26,11 @@ using namespace bluetooth; char* osi_strdup(const char* str) { size_t size = strlen(str) + 1; // + 1 for the null terminator char* new_string = (char*)malloc(size); - log::assert_that(new_string != nullptr, - "assert failed: new_string != nullptr"); + log::assert_that(new_string != nullptr, "assert failed: new_string != nullptr"); - if (!new_string) return NULL; + if (!new_string) { + return NULL; + } memcpy(new_string, str, size); return new_string; @@ -37,13 +38,16 @@ char* osi_strdup(const char* str) { char* osi_strndup(const char* str, size_t len) { size_t size = strlen(str); - if (len < size) size = len; + if (len < size) { + size = len; + } char* new_string = (char*)malloc(size + 1); - log::assert_that(new_string != nullptr, - "assert failed: new_string != nullptr"); + log::assert_that(new_string != nullptr, "assert failed: new_string != nullptr"); - if (!new_string) return NULL; + if (!new_string) { + return NULL; + } memcpy(new_string, str, size); new_string[size] = '\0'; diff --git a/system/osi/src/compat.cc b/system/osi/src/compat.cc index 34e5d6eb9de..bb3071abfed 100644 --- a/system/osi/src/compat.cc +++ b/system/osi/src/compat.cc @@ -25,13 +25,14 @@ * ******************************************************************************/ +#include "osi/include/compat.h" + #include #include #include #include #include -#include "osi/include/compat.h" #include "osi/include/osi.h" #if __GLIBC__ @@ -69,17 +70,21 @@ size_t strlcpy(char* dst, const char* src, size_t siz) { /* Copy as many bytes as will fit */ if (n != 0) { while (--n != 0) { - if ((*d++ = *s++) == '\0') break; + if ((*d++ = *s++) == '\0') { + break; + } } } /* Not enough room in dst, add NUL and traverse rest of src */ if (n == 0) { - if (siz != 0) *d = '\0'; /* NUL-terminate dst */ + if (siz != 0) { + *d = '\0'; /* NUL-terminate dst */ + } while (*s++) ; } - return (s - src - 1); /* count does not include NUL */ + return s - src - 1; /* count does not include NUL */ } #endif diff --git a/system/osi/src/config.cc b/system/osi/src/config.cc index 71b2b22bfa2..658ab786b7b 100644 --- a/system/osi/src/config.cc +++ b/system/osi/src/config.cc @@ -42,57 +42,49 @@ void section_t::Set(std::string key, std::string value) { } } // add a new key to the section - entries.emplace_back( - entry_t{.key = std::move(key), .value = std::move(value)}); + entries.emplace_back(entry_t{.key = std::move(key), .value = std::move(value)}); } std::list::iterator section_t::Find(const std::string& key) { - return std::find_if( - entries.begin(), entries.end(), - [&key](const entry_t& entry) { return entry.key == key; }); + return std::find_if(entries.begin(), entries.end(), + [&key](const entry_t& entry) { return entry.key == key; }); } -bool section_t::Has(const std::string& key) { - return Find(key) != entries.end(); -} +bool section_t::Has(const std::string& key) { return Find(key) != entries.end(); } std::list::iterator config_t::Find(const std::string& section) { - return std::find_if( - sections.begin(), sections.end(), - [§ion](const section_t& sec) { return sec.name == section; }); + return std::find_if(sections.begin(), sections.end(), + [§ion](const section_t& sec) { return sec.name == section; }); } -bool config_t::Has(const std::string& key) { - return Find(key) != sections.end(); -} +bool config_t::Has(const std::string& key) { return Find(key) != sections.end(); } static bool config_parse(FILE* fp, config_t* config); -template ::type>::value>> +template ::type>::value>> static auto section_find(T& config, const std::string& section) { - return std::find_if( - config.sections.begin(), config.sections.end(), - [§ion](const section_t& sec) { return sec.name == section; }); + return std::find_if(config.sections.begin(), config.sections.end(), + [§ion](const section_t& sec) { return sec.name == section; }); } -static const entry_t* entry_find(const config_t& config, - const std::string& section, +static const entry_t* entry_find(const config_t& config, const std::string& section, const std::string& key) { auto sec = section_find(config, section); - if (sec == config.sections.end()) return nullptr; + if (sec == config.sections.end()) { + return nullptr; + } for (const entry_t& entry : sec->entries) { - if (entry.key == key) return &entry; + if (entry.key == key) { + return &entry; + } } return nullptr; } -std::unique_ptr config_new_empty(void) { - return std::make_unique(); -} +std::unique_ptr config_new_empty(void) { return std::make_unique(); } std::unique_ptr config_new(const char* filename) { log::assert_that(filename != nullptr, "assert failed: filename != nullptr"); @@ -139,18 +131,19 @@ std::unique_ptr config_new_clone(const config_t& src) { } bool config_has_section(const config_t& config, const std::string& section) { - return (section_find(config, section) != config.sections.end()); + return section_find(config, section) != config.sections.end(); } -bool config_has_key(const config_t& config, const std::string& section, - const std::string& key) { - return (entry_find(config, section, key) != nullptr); +bool config_has_key(const config_t& config, const std::string& section, const std::string& key) { + return entry_find(config, section, key) != nullptr; } -int config_get_int(const config_t& config, const std::string& section, - const std::string& key, int def_value) { +int config_get_int(const config_t& config, const std::string& section, const std::string& key, + int def_value) { const entry_t* entry = entry_find(config, section, key); - if (!entry) return def_value; + if (!entry) { + return def_value; + } char* endptr; int ret = strtol(entry->value.c_str(), &endptr, 0); @@ -160,51 +153,59 @@ int config_get_int(const config_t& config, const std::string& section, uint64_t config_get_uint64(const config_t& config, const std::string& section, const std::string& key, uint64_t def_value) { const entry_t* entry = entry_find(config, section, key); - if (!entry) return def_value; + if (!entry) { + return def_value; + } char* endptr; uint64_t ret = strtoull(entry->value.c_str(), &endptr, 0); return (*endptr == '\0') ? ret : def_value; } -bool config_get_bool(const config_t& config, const std::string& section, - const std::string& key, bool def_value) { +bool config_get_bool(const config_t& config, const std::string& section, const std::string& key, + bool def_value) { const entry_t* entry = entry_find(config, section, key); - if (!entry) return def_value; + if (!entry) { + return def_value; + } - if (entry->value == "true") return true; - if (entry->value == "false") return false; + if (entry->value == "true") { + return true; + } + if (entry->value == "false") { + return false; + } return def_value; } -const std::string* config_get_string(const config_t& config, - const std::string& section, - const std::string& key, - const std::string* def_value) { +const std::string* config_get_string(const config_t& config, const std::string& section, + const std::string& key, const std::string* def_value) { const entry_t* entry = entry_find(config, section, key); - if (!entry) return def_value; + if (!entry) { + return def_value; + } return &entry->value; } -void config_set_int(config_t* config, const std::string& section, - const std::string& key, int value) { +void config_set_int(config_t* config, const std::string& section, const std::string& key, + int value) { config_set_string(config, section, key, std::to_string(value)); } -void config_set_uint64(config_t* config, const std::string& section, - const std::string& key, uint64_t value) { +void config_set_uint64(config_t* config, const std::string& section, const std::string& key, + uint64_t value) { config_set_string(config, section, key, std::to_string(value)); } -void config_set_bool(config_t* config, const std::string& section, - const std::string& key, bool value) { +void config_set_bool(config_t* config, const std::string& section, const std::string& key, + bool value) { config_set_string(config, section, key, value ? "true" : "false"); } -void config_set_string(config_t* config, const std::string& section, - const std::string& key, const std::string& value) { +void config_set_string(config_t* config, const std::string& section, const std::string& key, + const std::string& value) { log::assert_that(config != nullptr, "assert failed: config != nullptr"); auto sec = section_find(*config, section); @@ -235,20 +236,22 @@ bool config_remove_section(config_t* config, const std::string& section) { log::assert_that(config != nullptr, "assert failed: config != nullptr"); auto sec = section_find(*config, section); - if (sec == config->sections.end()) return false; + if (sec == config->sections.end()) { + return false; + } config->sections.erase(sec); return true; } -bool config_remove_key(config_t* config, const std::string& section, - const std::string& key) { +bool config_remove_key(config_t* config, const std::string& section, const std::string& key) { log::assert_that(config != nullptr, "assert failed: config != nullptr"); auto sec = section_find(*config, section); - if (sec == config->sections.end()) return false; + if (sec == config->sections.end()) { + return false; + } - for (auto entry = sec->entries.begin(); entry != sec->entries.end(); - ++entry) { + for (auto entry = sec->entries.begin(); entry != sec->entries.end(); ++entry) { if (entry->key == key) { sec->entries.erase(entry); return true; @@ -280,8 +283,7 @@ bool config_save(const config_t& config, const std::string& filename) { // Extract directory from file path (e.g. /data/misc/bluedroid). const std::string directoryname = base::FilePath(filename).DirName().value(); if (directoryname.empty()) { - log::error("error extracting directory from '{}': {}", filename, - strerror(errno)); + log::error("error extracting directory from '{}': {}", filename, strerror(errno)); goto error; } @@ -293,30 +295,28 @@ bool config_save(const config_t& config, const std::string& filename) { fp = fopen(temp_filename.c_str(), "wt"); if (!fp) { - log::error("unable to write to file '{}': {}", temp_filename, - strerror(errno)); + log::error("unable to write to file '{}': {}", temp_filename, strerror(errno)); goto error; } for (const section_t& section : config.sections) { serialized << "[" << section.name << "]" << std::endl; - for (const entry_t& entry : section.entries) + for (const entry_t& entry : section.entries) { serialized << entry.key << " = " << entry.value << std::endl; + } serialized << std::endl; } if (fprintf(fp, "%s", serialized.str().c_str()) < 0) { - log::error("unable to write to file '{}': {}", temp_filename, - strerror(errno)); + log::error("unable to write to file '{}': {}", temp_filename, strerror(errno)); goto error; } // Flush the stream buffer to the temp file. if (fflush(fp) < 0) { - log::error("unable to write flush buffer to file '{}': {}", temp_filename, - strerror(errno)); + log::error("unable to write flush buffer to file '{}': {}", temp_filename, strerror(errno)); goto error; } @@ -333,10 +333,8 @@ bool config_save(const config_t& config, const std::string& filename) { fp = nullptr; // Change the file's permissions to Read/Write by User and Group - if (chmod(temp_filename.c_str(), S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP) == - -1) { - log::error("unable to change file permissions '{}': {}", filename, - strerror(errno)); + if (chmod(temp_filename.c_str(), S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP) == -1) { + log::error("unable to change file permissions '{}': {}", filename, strerror(errno)); goto error; } @@ -362,8 +360,12 @@ error: // This indicates there is a write issue. Unlink as partial data is not // acceptable. unlink(temp_filename.c_str()); - if (fp) fclose(fp); - if (dir_fd != -1) close(dir_fd); + if (fp) { + fclose(fp); + } + if (dir_fd != -1) { + close(dir_fd); + } return false; } @@ -391,8 +393,7 @@ bool checksum_save(const std::string& checksum, const std::string& filename) { // Extract directory from file path (e.g. /data/misc/bluedroid). const std::string directoryname = base::FilePath(filename).DirName().value(); if (directoryname.empty()) { - log::error("error extracting directory from '{}': {}", filename, - strerror(errno)); + log::error("error extracting directory from '{}': {}", filename, strerror(errno)); goto error2; } @@ -402,16 +403,14 @@ bool checksum_save(const std::string& checksum, const std::string& filename) { goto error2; } - if (base::WriteFile(path, checksum.data(), checksum.size()) != - (int)checksum.size()) { + if (base::WriteFile(path, checksum.data(), checksum.size()) != (int)checksum.size()) { log::error("unable to write file '{}", filename); goto error2; } fp = fopen(temp_filename.c_str(), "rb"); if (!fp) { - log::error("unable to write to file '{}': {}", temp_filename, - strerror(errno)); + log::error("unable to write to file '{}': {}", temp_filename, strerror(errno)); goto error2; } @@ -428,10 +427,8 @@ bool checksum_save(const std::string& checksum, const std::string& filename) { fp = nullptr; // Change the file's permissions to Read/Write by User and Group - if (chmod(temp_filename.c_str(), S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP) == - -1) { - log::error("unable to change file permissions '{}': {}", filename, - strerror(errno)); + if (chmod(temp_filename.c_str(), S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP) == -1) { + log::error("unable to change file permissions '{}': {}", filename, strerror(errno)); goto error2; } @@ -457,18 +454,28 @@ error2: // This indicates there is a write issue. Unlink as partial data is not // acceptable. unlink(temp_filename.c_str()); - if (fp) fclose(fp); - if (dir_fd != -1) close(dir_fd); + if (fp) { + fclose(fp); + } + if (dir_fd != -1) { + close(dir_fd); + } return false; } static char* trim(char* str) { - while (isspace(*str)) ++str; + while (isspace(*str)) { + ++str; + } - if (!*str) return str; + if (!*str) { + return str; + } char* end_str = str + strlen(str) - 1; - while (end_str > str && isspace(*end_str)) --end_str; + while (end_str > str && isspace(*end_str)) { + --end_str; + } end_str[1] = '\0'; return str; @@ -488,7 +495,9 @@ static bool config_parse(FILE* fp, config_t* config) { ++line_num; // Skip blank and comment lines. - if (*line_ptr == '\0' || *line_ptr == '#') continue; + if (*line_ptr == '\0' || *line_ptr == '#') { + continue; + } if (*line_ptr == '[') { size_t len = strlen(line_ptr); diff --git a/system/osi/src/fixed_queue.cc b/system/osi/src/fixed_queue.cc index 5e41ae79936..4a349ddc783 100644 --- a/system/osi/src/fixed_queue.cc +++ b/system/osi/src/fixed_queue.cc @@ -46,20 +46,25 @@ typedef struct fixed_queue_t { static void internal_dequeue_ready(void* context); fixed_queue_t* fixed_queue_new(size_t capacity) { - fixed_queue_t* ret = - static_cast(osi_calloc(sizeof(fixed_queue_t))); + fixed_queue_t* ret = static_cast(osi_calloc(sizeof(fixed_queue_t))); ret->mutex = new std::mutex; ret->capacity = capacity; ret->list = list_new(NULL); - if (!ret->list) goto error; + if (!ret->list) { + goto error; + } ret->enqueue_sem = semaphore_new(capacity); - if (!ret->enqueue_sem) goto error; + if (!ret->enqueue_sem) { + goto error; + } ret->dequeue_sem = semaphore_new(0); - if (!ret->dequeue_sem) goto error; + if (!ret->dequeue_sem) { + goto error; + } return ret; @@ -69,14 +74,18 @@ error: } void fixed_queue_free(fixed_queue_t* queue, fixed_queue_free_cb free_cb) { - if (!queue) return; + if (!queue) { + return; + } fixed_queue_unregister_dequeue(queue); - if (free_cb) - for (const list_node_t* node = list_begin(queue->list); - node != list_end(queue->list); node = list_next(node)) + if (free_cb) { + for (const list_node_t* node = list_begin(queue->list); node != list_end(queue->list); + node = list_next(node)) { free_cb(list_node(node)); + } + } list_free(queue->list); semaphore_free(queue->enqueue_sem); @@ -86,7 +95,9 @@ void fixed_queue_free(fixed_queue_t* queue, fixed_queue_free_cb free_cb) { } void fixed_queue_flush(fixed_queue_t* queue, fixed_queue_free_cb free_cb) { - if (!queue) return; + if (!queue) { + return; + } while (!fixed_queue_is_empty(queue)) { void* data = fixed_queue_try_dequeue(queue); @@ -97,14 +108,18 @@ void fixed_queue_flush(fixed_queue_t* queue, fixed_queue_free_cb free_cb) { } bool fixed_queue_is_empty(fixed_queue_t* queue) { - if (queue == NULL) return true; + if (queue == NULL) { + return true; + } std::lock_guard lock(*queue->mutex); return list_is_empty(queue->list); } size_t fixed_queue_length(fixed_queue_t* queue) { - if (queue == NULL) return 0; + if (queue == NULL) { + return 0; + } std::lock_guard lock(*queue->mutex); return list_length(queue->list); @@ -151,7 +166,9 @@ bool fixed_queue_try_enqueue(fixed_queue_t* queue, void* data) { log::assert_that(queue != NULL, "assert failed: queue != NULL"); log::assert_that(data != NULL, "assert failed: data != NULL"); - if (!semaphore_try_wait(queue->enqueue_sem)) return false; + if (!semaphore_try_wait(queue->enqueue_sem)) { + return false; + } { std::lock_guard lock(*queue->mutex); @@ -163,9 +180,13 @@ bool fixed_queue_try_enqueue(fixed_queue_t* queue, void* data) { } void* fixed_queue_try_dequeue(fixed_queue_t* queue) { - if (queue == NULL) return NULL; + if (queue == NULL) { + return NULL; + } - if (!semaphore_try_wait(queue->dequeue_sem)) return NULL; + if (!semaphore_try_wait(queue->dequeue_sem)) { + return NULL; + } void* ret = NULL; { @@ -180,27 +201,32 @@ void* fixed_queue_try_dequeue(fixed_queue_t* queue) { } void* fixed_queue_try_peek_first(fixed_queue_t* queue) { - if (queue == NULL) return NULL; + if (queue == NULL) { + return NULL; + } std::lock_guard lock(*queue->mutex); return list_is_empty(queue->list) ? NULL : list_front(queue->list); } void* fixed_queue_try_peek_last(fixed_queue_t* queue) { - if (queue == NULL) return NULL; + if (queue == NULL) { + return NULL; + } std::lock_guard lock(*queue->mutex); return list_is_empty(queue->list) ? NULL : list_back(queue->list); } void* fixed_queue_try_remove_from_queue(fixed_queue_t* queue, void* data) { - if (queue == NULL) return NULL; + if (queue == NULL) { + return NULL; + } bool removed = false; { std::lock_guard lock(*queue->mutex); - if (list_contains(queue->list, data) && - semaphore_try_wait(queue->dequeue_sem)) { + if (list_contains(queue->list, data) && semaphore_try_wait(queue->dequeue_sem)) { removed = list_remove(queue->list, data); log::assert_that(removed, "assert failed: removed"); } @@ -232,8 +258,8 @@ int fixed_queue_get_enqueue_fd(const fixed_queue_t* queue) { return semaphore_get_fd(queue->enqueue_sem); } -void fixed_queue_register_dequeue(fixed_queue_t* queue, reactor_t* reactor, - fixed_queue_cb ready_cb, void* context) { +void fixed_queue_register_dequeue(fixed_queue_t* queue, reactor_t* reactor, fixed_queue_cb ready_cb, + void* context) { log::assert_that(queue != NULL, "assert failed: queue != NULL"); log::assert_that(reactor != NULL, "assert failed: reactor != NULL"); log::assert_that(ready_cb != NULL, "assert failed: ready_cb != NULL"); @@ -243,9 +269,8 @@ void fixed_queue_register_dequeue(fixed_queue_t* queue, reactor_t* reactor, queue->dequeue_ready = ready_cb; queue->dequeue_context = context; - queue->dequeue_object = - reactor_register(reactor, fixed_queue_get_dequeue_fd(queue), queue, - internal_dequeue_ready, NULL); + queue->dequeue_object = reactor_register(reactor, fixed_queue_get_dequeue_fd(queue), queue, + internal_dequeue_ready, NULL); } void fixed_queue_unregister_dequeue(fixed_queue_t* queue) { diff --git a/system/osi/src/future.cc b/system/osi/src/future.cc index ce5ec0c8933..63dc2541235 100644 --- a/system/osi/src/future.cc +++ b/system/osi/src/future.cc @@ -63,8 +63,7 @@ future_t* future_new_immediate(void* value) { void future_ready(future_t* future, void* value) { log::assert_that(future != NULL, "assert failed: future != NULL"); - log::assert_that(future->ready_can_be_called, - "assert failed: future->ready_can_be_called"); + log::assert_that(future->ready_can_be_called, "assert failed: future->ready_can_be_called"); future->ready_can_be_called = false; future->result = value; @@ -75,7 +74,9 @@ void* future_await(future_t* future) { log::assert_that(future != NULL, "assert failed: future != NULL"); // If the future is immediate, it will not have a semaphore - if (future->semaphore) semaphore_wait(future->semaphore); + if (future->semaphore) { + semaphore_wait(future->semaphore); + } void* result = future->result; future_free(future); @@ -83,7 +84,9 @@ void* future_await(future_t* future) { } static void future_free(future_t* future) { - if (!future) return; + if (!future) { + return; + } semaphore_free(future->semaphore); osi_free(future); diff --git a/system/osi/src/hash_map_utils.cc b/system/osi/src/hash_map_utils.cc index 536f5f31036..3ee29c7d392 100644 --- a/system/osi/src/hash_map_utils.cc +++ b/system/osi/src/hash_map_utils.cc @@ -27,14 +27,16 @@ #include "osi/include/allocator.h" #include "osi/include/osi.h" -std::unordered_map -hash_map_utils_new_from_string_params(const char* params) { +std::unordered_map hash_map_utils_new_from_string_params( + const char* params) { bluetooth::log::assert_that(params != NULL, "assert failed: params != NULL"); std::unordered_map map; char* str = osi_strdup(params); - if (!str) return map; + if (!str) { + return map; + } // Parse |str| and add extracted key-and-value pair(s) in |map|. char* tmpstr; @@ -42,7 +44,9 @@ hash_map_utils_new_from_string_params(const char* params) { while (kvpair && *kvpair) { char* eq = strchr(kvpair, '='); - if (eq == kvpair) goto next_pair; + if (eq == kvpair) { + goto next_pair; + } char* key; char* value; diff --git a/system/osi/src/internal/semaphore.cc b/system/osi/src/internal/semaphore.cc index 358a35db0f4..23aa60c1315 100644 --- a/system/osi/src/internal/semaphore.cc +++ b/system/osi/src/internal/semaphore.cc @@ -53,26 +53,29 @@ semaphore_t* semaphore_new(unsigned int value) { } void semaphore_free(semaphore_t* semaphore) { - if (!semaphore) return; + if (!semaphore) { + return; + } - if (semaphore->fd != INVALID_FD) close(semaphore->fd); + if (semaphore->fd != INVALID_FD) { + close(semaphore->fd); + } osi_free(semaphore); } void semaphore_wait(semaphore_t* semaphore) { log::assert_that(semaphore != NULL, "assert failed: semaphore != NULL"); - log::assert_that(semaphore->fd != INVALID_FD, - "assert failed: semaphore->fd != INVALID_FD"); + log::assert_that(semaphore->fd != INVALID_FD, "assert failed: semaphore->fd != INVALID_FD"); eventfd_t value; - if (eventfd_read(semaphore->fd, &value) == -1) + if (eventfd_read(semaphore->fd, &value) == -1) { log::error("unable to wait on semaphore: {}", strerror(errno)); + } } bool semaphore_try_wait(semaphore_t* semaphore) { log::assert_that(semaphore != NULL, "assert failed: semaphore != NULL"); - log::assert_that(semaphore->fd != INVALID_FD, - "assert failed: semaphore->fd != INVALID_FD"); + log::assert_that(semaphore->fd != INVALID_FD, "assert failed: semaphore->fd != INVALID_FD"); int flags = fcntl(semaphore->fd, F_GETFL); if (flags == -1) { @@ -80,32 +83,33 @@ bool semaphore_try_wait(semaphore_t* semaphore) { return false; } if (fcntl(semaphore->fd, F_SETFL, flags | O_NONBLOCK) == -1) { - log::error("unable to set O_NONBLOCK for semaphore fd: {}", - strerror(errno)); + log::error("unable to set O_NONBLOCK for semaphore fd: {}", strerror(errno)); return false; } bool rc = true; eventfd_t value; - if (eventfd_read(semaphore->fd, &value) == -1) rc = false; + if (eventfd_read(semaphore->fd, &value) == -1) { + rc = false; + } - if (fcntl(semaphore->fd, F_SETFL, flags) == -1) + if (fcntl(semaphore->fd, F_SETFL, flags) == -1) { log::error("unable to restore flags for semaphore fd: {}", strerror(errno)); + } return rc; } void semaphore_post(semaphore_t* semaphore) { log::assert_that(semaphore != NULL, "assert failed: semaphore != NULL"); - log::assert_that(semaphore->fd != INVALID_FD, - "assert failed: semaphore->fd != INVALID_FD"); + log::assert_that(semaphore->fd != INVALID_FD, "assert failed: semaphore->fd != INVALID_FD"); - if (eventfd_write(semaphore->fd, 1ULL) == -1) + if (eventfd_write(semaphore->fd, 1ULL) == -1) { log::error("unable to post to semaphore: {}", strerror(errno)); + } } int semaphore_get_fd(const semaphore_t* semaphore) { log::assert_that(semaphore != NULL, "assert failed: semaphore != NULL"); - log::assert_that(semaphore->fd != INVALID_FD, - "assert failed: semaphore->fd != INVALID_FD"); + log::assert_that(semaphore->fd != INVALID_FD, "assert failed: semaphore->fd != INVALID_FD"); return semaphore->fd; } diff --git a/system/osi/src/list.cc b/system/osi/src/list.cc index 00c4d59744f..5fe07aaf424 100644 --- a/system/osi/src/list.cc +++ b/system/osi/src/list.cc @@ -24,22 +24,23 @@ static list_node_t* list_free_node_(list_t* list, list_node_t* node); // Hidden constructor, only to be used by the hash map for the allocation // tracker. // Behaves the same as |list_new|, except you get to specify the allocator. -list_t* list_new_internal(list_free_cb callback, - const allocator_t* zeroed_allocator) { +list_t* list_new_internal(list_free_cb callback, const allocator_t* zeroed_allocator) { list_t* list = (list_t*)zeroed_allocator->alloc(sizeof(list_t)); - if (!list) return NULL; + if (!list) { + return NULL; + } list->free_cb = callback; list->allocator = zeroed_allocator; return list; } -list_t* list_new(list_free_cb callback) { - return list_new_internal(callback, &allocator_calloc); -} +list_t* list_new(list_free_cb callback) { return list_new_internal(callback, &allocator_calloc); } void list_free(list_t* list) { - if (!list) return; + if (!list) { + return; + } list_clear(list); list->allocator->free(list); @@ -47,16 +48,17 @@ void list_free(list_t* list) { bool list_is_empty(const list_t* list) { log::assert_that(list != NULL, "assert failed: list != NULL"); - return (list->length == 0); + return list->length == 0; } bool list_contains(const list_t* list, const void* data) { log::assert_that(list != NULL, "assert failed: list != NULL"); log::assert_that(data != NULL, "assert failed: data != NULL"); - for (const list_node_t* node = list_begin(list); node != list_end(list); - node = list_next(node)) { - if (list_node(node) == data) return true; + for (const list_node_t* node = list_begin(list); node != list_end(list); node = list_next(node)) { + if (list_node(node) == data) { + return true; + } } return false; @@ -94,12 +96,16 @@ bool list_insert_after(list_t* list, list_node_t* prev_node, void* data) { log::assert_that(data != NULL, "assert failed: data != NULL"); list_node_t* node = (list_node_t*)list->allocator->alloc(sizeof(list_node_t)); - if (!node) return false; + if (!node) { + return false; + } node->next = prev_node->next; node->data = data; prev_node->next = node; - if (list->tail == prev_node) list->tail = node; + if (list->tail == prev_node) { + list->tail = node; + } ++list->length; return true; } @@ -109,11 +115,15 @@ bool list_prepend(list_t* list, void* data) { log::assert_that(data != NULL, "assert failed: data != NULL"); list_node_t* node = (list_node_t*)list->allocator->alloc(sizeof(list_node_t)); - if (!node) return false; + if (!node) { + return false; + } node->next = list->head; node->data = data; list->head = node; - if (list->tail == NULL) list->tail = list->head; + if (list->tail == NULL) { + list->tail = list->head; + } ++list->length; return true; } @@ -123,7 +133,9 @@ bool list_append(list_t* list, void* data) { log::assert_that(data != NULL, "assert failed: data != NULL"); list_node_t* node = (list_node_t*)list->allocator->alloc(sizeof(list_node_t)); - if (!node) return false; + if (!node) { + return false; + } node->next = NULL; node->data = data; if (list->tail == NULL) { @@ -141,43 +153,52 @@ bool list_remove(list_t* list, void* data) { log::assert_that(list != NULL, "assert failed: list != NULL"); log::assert_that(data != NULL, "assert failed: data != NULL"); - if (list_is_empty(list)) return false; + if (list_is_empty(list)) { + return false; + } if (list->head->data == data) { list_node_t* next = list_free_node_(list, list->head); - if (list->tail == list->head) list->tail = next; + if (list->tail == list->head) { + list->tail = next; + } list->head = next; return true; } for (list_node_t *prev = list->head, *node = list->head->next; node; - prev = node, node = node->next) + prev = node, node = node->next) { if (node->data == data) { prev->next = list_free_node_(list, node); - if (list->tail == node) list->tail = prev; + if (list->tail == node) { + list->tail = prev; + } return true; } + } return false; } void list_clear(list_t* list) { log::assert_that(list != NULL, "assert failed: list != NULL"); - for (list_node_t* node = list->head; node;) + for (list_node_t* node = list->head; node;) { node = list_free_node_(list, node); + } list->head = NULL; list->tail = NULL; list->length = 0; } -list_node_t* list_foreach(const list_t* list, list_iter_cb callback, - void* context) { +list_node_t* list_foreach(const list_t* list, list_iter_cb callback, void* context) { log::assert_that(list != NULL, "assert failed: list != NULL"); log::assert_that(callback != NULL, "assert failed: callback != NULL"); for (list_node_t* node = list->head; node;) { list_node_t* next = node->next; - if (!callback(node->data, context)) return node; + if (!callback(node->data, context)) { + return node; + } node = next; } return NULL; @@ -209,7 +230,9 @@ static list_node_t* list_free_node_(list_t* list, list_node_t* node) { list_node_t* next = node->next; - if (list->free_cb) list->free_cb(node->data); + if (list->free_cb) { + list->free_cb(node->data); + } list->allocator->free(node); --list->length; diff --git a/system/osi/src/mutex.cc b/system/osi/src/mutex.cc index 0634f098373..b04e3d8cbda 100644 --- a/system/osi/src/mutex.cc +++ b/system/osi/src/mutex.cc @@ -18,10 +18,10 @@ #define LOG_TAG "bt_osi_mutex" -#include - #include "osi/include/mutex.h" +#include + static std::recursive_mutex global_mutex; void mutex_global_lock(void) { global_mutex.lock(); } diff --git a/system/osi/src/properties.cc b/system/osi/src/properties.cc index 000cccd0c64..0c2f42f4dd1 100644 --- a/system/osi/src/properties.cc +++ b/system/osi/src/properties.cc @@ -73,8 +73,8 @@ bool osi_property_get_bool(const char* key, bool default_value) { } } -std::vector osi_property_get_uintlist( - const char* key, const std::vector default_value) { +std::vector osi_property_get_uintlist(const char* key, + const std::vector default_value) { std::optional result = bluetooth::os::GetSystemProperty(key); if (!result || result->empty() || result->size() > PROPERTY_VALUE_MAX) { return default_value; diff --git a/system/osi/src/reactor.cc b/system/osi/src/reactor.cc index 1d3eab35829..045bc24f3c0 100644 --- a/system/osi/src/reactor.cc +++ b/system/osi/src/reactor.cc @@ -54,7 +54,7 @@ struct reactor_object_t { int fd; // the file descriptor to monitor for events. void* context; // a context that's passed back to the *_ready functions. reactor_t* reactor; // the reactor instance this object is registered with. - std::mutex* mutex; // protects the lifetime of this object and all variables. + std::mutex* mutex; // protects the lifetime of this object and all variables. void (*read_ready)(void* context); // function to call when the file // descriptor becomes readable. @@ -97,8 +97,7 @@ reactor_t* reactor_new(void) { event.events = EPOLLIN; event.data.ptr = NULL; if (epoll_ctl(ret->epoll_fd, EPOLL_CTL_ADD, ret->event_fd, &event) == -1) { - log::error("unable to register eventfd with epoll set: {}", - strerror(errno)); + log::error("unable to register eventfd with epoll set: {}", strerror(errno)); goto error; } @@ -110,7 +109,9 @@ error:; } void reactor_free(reactor_t* reactor) { - if (!reactor) return; + if (!reactor) { + return; + } list_free(reactor->invalidation_list); close(reactor->event_fd); @@ -141,8 +142,7 @@ reactor_object_t* reactor_register(reactor_t* reactor, int fd, void* context, log::assert_that(reactor != NULL, "assert failed: reactor != NULL"); log::assert_that(fd != INVALID_FD, "assert failed: fd != INVALID_FD"); - reactor_object_t* object = - (reactor_object_t*)osi_calloc(sizeof(reactor_object_t)); + reactor_object_t* object = (reactor_object_t*)osi_calloc(sizeof(reactor_object_t)); object->reactor = reactor; object->fd = fd; @@ -153,13 +153,16 @@ reactor_object_t* reactor_register(reactor_t* reactor, int fd, void* context, struct epoll_event event; memset(&event, 0, sizeof(event)); - if (read_ready) event.events |= (EPOLLIN | EPOLLRDHUP); - if (write_ready) event.events |= EPOLLOUT; + if (read_ready) { + event.events |= (EPOLLIN | EPOLLRDHUP); + } + if (write_ready) { + event.events |= EPOLLOUT; + } event.data.ptr = object; if (epoll_ctl(reactor->epoll_fd, EPOLL_CTL_ADD, fd, &event) == -1) { - log::error("unable to register fd {} to epoll set: {}", fd, - strerror(errno)); + log::error("unable to register fd {} to epoll set: {}", fd, strerror(errno)); delete object->mutex; osi_free(object); return NULL; @@ -168,21 +171,22 @@ reactor_object_t* reactor_register(reactor_t* reactor, int fd, void* context, return object; } -bool reactor_change_registration(reactor_object_t* object, - void (*read_ready)(void* context), +bool reactor_change_registration(reactor_object_t* object, void (*read_ready)(void* context), void (*write_ready)(void* context)) { log::assert_that(object != NULL, "assert failed: object != NULL"); struct epoll_event event; memset(&event, 0, sizeof(event)); - if (read_ready) event.events |= (EPOLLIN | EPOLLRDHUP); - if (write_ready) event.events |= EPOLLOUT; + if (read_ready) { + event.events |= (EPOLLIN | EPOLLRDHUP); + } + if (write_ready) { + event.events |= EPOLLOUT; + } event.data.ptr = object; - if (epoll_ctl(object->reactor->epoll_fd, EPOLL_CTL_MOD, object->fd, &event) == - -1) { - log::error("unable to modify interest set for fd {}: {}", object->fd, - strerror(errno)); + if (epoll_ctl(object->reactor->epoll_fd, EPOLL_CTL_MOD, object->fd, &event) == -1) { + log::error("unable to modify interest set for fd {}: {}", object->fd, strerror(errno)); return false; } @@ -198,12 +202,11 @@ void reactor_unregister(reactor_object_t* obj) { reactor_t* reactor = obj->reactor; - if (epoll_ctl(reactor->epoll_fd, EPOLL_CTL_DEL, obj->fd, NULL) == -1) - log::error("unable to unregister fd {} from epoll set: {}", obj->fd, - strerror(errno)); + if (epoll_ctl(reactor->epoll_fd, EPOLL_CTL_DEL, obj->fd, NULL) == -1) { + log::error("unable to unregister fd {} from epoll set: {}", obj->fd, strerror(errno)); + } - if (reactor->is_running && - pthread_equal(pthread_self(), reactor->run_thread)) { + if (reactor->is_running && pthread_equal(pthread_self(), reactor->run_thread)) { reactor->object_removed = true; return; } @@ -275,12 +278,12 @@ static reactor_status_t run_reactor(reactor_t* reactor, int iterations) { lock.unlock(); reactor->object_removed = false; - if (events[j].events & (EPOLLIN | EPOLLHUP | EPOLLRDHUP | EPOLLERR) && - object->read_ready) + if (events[j].events & (EPOLLIN | EPOLLHUP | EPOLLRDHUP | EPOLLERR) && object->read_ready) { object->read_ready(object->context); - if (!reactor->object_removed && events[j].events & EPOLLOUT && - object->write_ready) + } + if (!reactor->object_removed && events[j].events & EPOLLOUT && object->write_ready) { object->write_ready(object->context); + } } if (reactor->object_removed) { diff --git a/system/osi/src/ringbuffer.cc b/system/osi/src/ringbuffer.cc index fc0128e43df..0631432458e 100644 --- a/system/osi/src/ringbuffer.cc +++ b/system/osi/src/ringbuffer.cc @@ -34,8 +34,7 @@ struct ringbuffer_t { }; ringbuffer_t* ringbuffer_init(const size_t size) { - ringbuffer_t* p = - static_cast(osi_calloc(sizeof(ringbuffer_t))); + ringbuffer_t* p = static_cast(osi_calloc(sizeof(ringbuffer_t))); p->base = static_cast(osi_calloc(size)); p->head = p->tail = p->base; @@ -45,7 +44,9 @@ ringbuffer_t* ringbuffer_init(const size_t size) { } void ringbuffer_free(ringbuffer_t* rb) { - if (rb != NULL) osi_free(rb->base); + if (rb != NULL) { + osi_free(rb->base); + } osi_free(rb); } @@ -63,11 +64,15 @@ size_t ringbuffer_insert(ringbuffer_t* rb, const uint8_t* p, size_t length) { log::assert_that(rb != nullptr, "assert failed: rb != nullptr"); log::assert_that(p != nullptr, "assert failed: p != nullptr"); - if (length > ringbuffer_available(rb)) length = ringbuffer_available(rb); + if (length > ringbuffer_available(rb)) { + length = ringbuffer_available(rb); + } for (size_t i = 0; i != length; ++i) { *rb->tail++ = *p++; - if (rb->tail >= (rb->base + rb->total)) rb->tail = rb->base; + if (rb->tail >= (rb->base + rb->total)) { + rb->tail = rb->base; + } } rb->available -= length; @@ -77,17 +82,20 @@ size_t ringbuffer_insert(ringbuffer_t* rb, const uint8_t* p, size_t length) { size_t ringbuffer_delete(ringbuffer_t* rb, size_t length) { log::assert_that(rb != nullptr, "assert failed: rb != nullptr"); - if (length > ringbuffer_size(rb)) length = ringbuffer_size(rb); + if (length > ringbuffer_size(rb)) { + length = ringbuffer_size(rb); + } rb->head += length; - if (rb->head >= (rb->base + rb->total)) rb->head -= rb->total; + if (rb->head >= (rb->base + rb->total)) { + rb->head -= rb->total; + } rb->available += length; return length; } -size_t ringbuffer_peek(const ringbuffer_t* rb, off_t offset, uint8_t* p, - size_t length) { +size_t ringbuffer_peek(const ringbuffer_t* rb, off_t offset, uint8_t* p, size_t length) { log::assert_that(rb != nullptr, "assert failed: rb != nullptr"); log::assert_that(p != nullptr, "assert failed: p != nullptr"); log::assert_that(offset >= 0, "assert failed: offset >= 0"); @@ -95,13 +103,14 @@ size_t ringbuffer_peek(const ringbuffer_t* rb, off_t offset, uint8_t* p, "assert failed: (size_t)offset <= ringbuffer_size(rb)"); uint8_t* b = ((rb->head - rb->base + offset) % rb->total) + rb->base; - const size_t bytes_to_copy = (offset + length > ringbuffer_size(rb)) - ? ringbuffer_size(rb) - offset - : length; + const size_t bytes_to_copy = + (offset + length > ringbuffer_size(rb)) ? ringbuffer_size(rb) - offset : length; for (size_t copied = 0; copied < bytes_to_copy; ++copied) { *p++ = *b++; - if (b >= (rb->base + rb->total)) b = rb->base; + if (b >= (rb->base + rb->total)) { + b = rb->base; + } } return bytes_to_copy; @@ -113,7 +122,9 @@ size_t ringbuffer_pop(ringbuffer_t* rb, uint8_t* p, size_t length) { const size_t copied = ringbuffer_peek(rb, 0, p, length); rb->head += copied; - if (rb->head >= (rb->base + rb->total)) rb->head -= rb->total; + if (rb->head >= (rb->base + rb->total)) { + rb->head -= rb->total; + } rb->available += copied; return copied; diff --git a/system/osi/src/socket.cc b/system/osi/src/socket.cc index 60c22e5e03d..c1694e68c38 100644 --- a/system/osi/src/socket.cc +++ b/system/osi/src/socket.cc @@ -59,8 +59,7 @@ socket_t* socket_new(void) { goto error; } - if (setsockopt(ret->fd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)) == - -1) { + if (setsockopt(ret->fd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)) == -1) { log::error("unable to set SO_REUSEADDR: {}", strerror(errno)); goto error; } @@ -68,7 +67,9 @@ socket_t* socket_new(void) { return ret; error:; - if (ret) close(ret->fd); + if (ret) { + close(ret->fd); + } osi_free(ret); return NULL; } @@ -83,7 +84,9 @@ socket_t* socket_new_from_fd(int fd) { } void socket_free(socket_t* socket) { - if (!socket) return; + if (!socket) { + return; + } socket_unregister(socket); close(socket->fd); @@ -146,12 +149,14 @@ ssize_t socket_write(const socket_t* socket, const void* buf, size_t count) { return ret; } -ssize_t socket_write_and_transfer_fd(const socket_t* socket, const void* buf, - size_t count, int fd) { +ssize_t socket_write_and_transfer_fd(const socket_t* socket, const void* buf, size_t count, + int fd) { log::assert_that(socket != NULL, "assert failed: socket != NULL"); log::assert_that(buf != NULL, "assert failed: buf != NULL"); - if (fd == INVALID_FD) return socket_write(socket, buf, count); + if (fd == INVALID_FD) { + return socket_write(socket, buf, count); + } struct msghdr msg; struct iovec iov; @@ -184,12 +189,14 @@ ssize_t socket_bytes_available(const socket_t* socket) { log::assert_that(socket != NULL, "assert failed: socket != NULL"); int size = 0; - if (ioctl(socket->fd, FIONREAD, &size) == -1) return -1; + if (ioctl(socket->fd, FIONREAD, &size) == -1) { + return -1; + } return size; } -void socket_register(socket_t* socket, reactor_t* reactor, void* context, - socket_cb read_cb, socket_cb write_cb) { +void socket_register(socket_t* socket, reactor_t* reactor, void* context, socket_cb read_cb, + socket_cb write_cb) { log::assert_that(socket != NULL, "assert failed: socket != NULL"); // Make sure the socket isn't currently registered. @@ -202,14 +209,15 @@ void socket_register(socket_t* socket, reactor_t* reactor, void* context, void (*read_fn)(void*) = (read_cb != NULL) ? internal_read_ready : NULL; void (*write_fn)(void*) = (write_cb != NULL) ? internal_write_ready : NULL; - socket->reactor_object = - reactor_register(reactor, socket->fd, socket, read_fn, write_fn); + socket->reactor_object = reactor_register(reactor, socket->fd, socket, read_fn, write_fn); } void socket_unregister(socket_t* socket) { log::assert_that(socket != NULL, "assert failed: socket != NULL"); - if (socket->reactor_object) reactor_unregister(socket->reactor_object); + if (socket->reactor_object) { + reactor_unregister(socket->reactor_object); + } socket->reactor_object = NULL; } diff --git a/system/osi/src/socket_utils/socket_local_client.cc b/system/osi/src/socket_utils/socket_local_client.cc index 2c0d9c39293..aab6bfcf4ca 100644 --- a/system/osi/src/socket_utils/socket_local_client.cc +++ b/system/osi/src/socket_utils/socket_local_client.cc @@ -30,8 +30,8 @@ #define LISTEN_BACKLOG 4 /* Documented in header file. */ -int osi_socket_make_sockaddr_un(const char* name, int namespaceId, - struct sockaddr_un* p_addr, socklen_t* alen) { +int osi_socket_make_sockaddr_un(const char* name, int namespaceId, struct sockaddr_un* p_addr, + socklen_t* alen) { memset(p_addr, 0, sizeof(*p_addr)); size_t namelen; @@ -57,8 +57,7 @@ int osi_socket_make_sockaddr_un(const char* name, int namespaceId, namelen = strlen(name) + strlen(FILESYSTEM_SOCKET_PREFIX); /* unix_path_max appears to be missing on linux */ - if (namelen > - sizeof(*p_addr) - offsetof(struct sockaddr_un, sun_path) - 1) { + if (namelen > sizeof(*p_addr) - offsetof(struct sockaddr_un, sun_path) - 1) { goto error; } @@ -70,8 +69,7 @@ int osi_socket_make_sockaddr_un(const char* name, int namespaceId, case ANDROID_SOCKET_NAMESPACE_RESERVED: namelen = strlen(name) + strlen(ANDROID_RESERVED_SOCKET_PREFIX); /* unix_path_max appears to be missing on linux */ - if (namelen > - sizeof(*p_addr) - offsetof(struct sockaddr_un, sun_path) - 1) { + if (namelen > sizeof(*p_addr) - offsetof(struct sockaddr_un, sun_path) - 1) { goto error; } @@ -82,8 +80,7 @@ int osi_socket_make_sockaddr_un(const char* name, int namespaceId, case ANDROID_SOCKET_NAMESPACE_FILESYSTEM: namelen = strlen(name); /* unix_path_max appears to be missing on linux */ - if (namelen > - sizeof(*p_addr) - offsetof(struct sockaddr_un, sun_path) - 1) { + if (namelen > sizeof(*p_addr) - offsetof(struct sockaddr_un, sun_path) - 1) { goto error; } @@ -108,8 +105,7 @@ error: * * Used by AndroidSocketImpl */ -int osi_socket_local_client_connect(int fd, const char* name, int namespaceId, - int /* type */) { +int osi_socket_local_client_connect(int fd, const char* name, int namespaceId, int /* type */) { struct sockaddr_un addr; socklen_t alen; int err; @@ -139,7 +135,9 @@ int osi_socket_local_client(const char* name, int namespaceId, int type) { int s; s = socket(AF_LOCAL, type, 0); - if (s < 0) return -1; + if (s < 0) { + return -1; + } if (0 > osi_socket_local_client_connect(s, name, namespaceId, type)) { close(s); diff --git a/system/osi/src/socket_utils/socket_local_server.cc b/system/osi/src/socket_utils/socket_local_server.cc index 94ec4c1111f..08fe5548360 100644 --- a/system/osi/src/socket_utils/socket_local_server.cc +++ b/system/osi/src/socket_utils/socket_local_server.cc @@ -80,7 +80,9 @@ int osi_socket_local_server(const char* name, int namespaceId, int type) { int s; s = socket(AF_LOCAL, type, 0); - if (s < 0) return -1; + if (s < 0) { + return -1; + } err = osi_socket_local_server_bind(s, name, namespaceId); diff --git a/system/osi/src/stack_power_telemetry.cc b/system/osi/src/stack_power_telemetry.cc index 1c463a59125..06695776df2 100644 --- a/system/osi/src/stack_power_telemetry.cc +++ b/system/osi/src/stack_power_telemetry.cc @@ -44,9 +44,8 @@ namespace { constexpr int64_t kTrafficLogTime = 120; // 120seconds constexpr uint8_t kLogEntriesSize{15}; constexpr std::string_view kLogPerChannelProperty = - "bluetooth.powertelemetry.log_per_channel.enabled"; -constexpr std::string_view kPowerTelemetryEnabledProperty = - "bluetooth.powertelemetry.enabled"; + "bluetooth.powertelemetry.log_per_channel.enabled"; +constexpr std::string_view kPowerTelemetryEnabledProperty = "bluetooth.powertelemetry.enabled"; bool power_telemerty_enabled_ = false; std::string GetTimeString(time_t tstamp) { @@ -132,7 +131,7 @@ struct SniffData { }; class LogDataContainer { - public: +public: struct Duration lifetime; std::map> channel_map; DataTransfer l2c_data, rfc_data; @@ -152,20 +151,16 @@ struct power_telemetry::PowerTelemetryImpl { PowerTelemetryImpl() { idx_containers = 0; traffic_logged_ts_ = get_current_time(); - log_per_channel_ = osi_property_get_bool( - std::string(kLogPerChannelProperty).c_str(), false); - power_telemetry_enabled_property_ = osi_property_get_bool( - std::string(kPowerTelemetryEnabledProperty).c_str(), true); + log_per_channel_ = osi_property_get_bool(std::string(kLogPerChannelProperty).c_str(), false); + power_telemetry_enabled_property_ = + osi_property_get_bool(std::string(kPowerTelemetryEnabledProperty).c_str(), true); // Enable this feature when both feature flag and sysprops turn on. - power_telemerty_enabled_ = - com::android::bluetooth::flags::bluetooth_power_telemetry() && - power_telemetry_enabled_property_; + power_telemerty_enabled_ = com::android::bluetooth::flags::bluetooth_power_telemetry() && + power_telemetry_enabled_property_; } - LogDataContainer& GetCurrentLogDataContainer() { - return log_data_containers_[idx_containers]; - } + LogDataContainer& GetCurrentLogDataContainer() { return log_data_containers_[idx_containers]; } void maybe_log_data() { if ((get_current_time() - traffic_logged_ts_) >= kTrafficLogTime) { @@ -203,85 +198,87 @@ struct power_telemetry::PowerTelemetryImpl { }; void power_telemetry::PowerTelemetryImpl::LogDataTransfer() { - if (!power_telemerty_enabled_) return; + if (!power_telemerty_enabled_) { + return; + } LogDataContainer& ldc = GetCurrentLogDataContainer(); if ((l2c.rx.bytes_ != 0) || (l2c.tx.bytes_ != 0)) { ldc.l2c_data = { - .rx = - { - .bytes = l2c.rx.bytes_, - }, - .tx = - { - .bytes = l2c.tx.bytes_, - }, + .rx = + { + .bytes = l2c.rx.bytes_, + }, + .tx = + { + .bytes = l2c.tx.bytes_, + }, }; l2c = {}; } if ((rfc.rx.bytes_ != 0) || (rfc.tx.bytes_ != 0)) { ldc.rfc_data = { - .rx = - { - .bytes = rfc.rx.bytes_, - }, - .tx = - { - .bytes = rfc.tx.bytes_, - }, + .rx = + { + .bytes = rfc.rx.bytes_, + }, + .tx = + { + .bytes = rfc.tx.bytes_, + }, }; rfc = {}; } if (scan.count_ != 0) { ldc.scan_details = { - .count = scan.count_, + .count = scan.count_, }; scan.count_ = 0; } if (inq_scan.count_ != 0) { ldc.inq_scan_details = { - .count = inq_scan.count_, + .count = inq_scan.count_, }; inq_scan.count_ = 0; } if ((rx.pkt_ != 0) || (tx.pkt_ != 0)) { ldc.acl_pkt_ds = { - .rx = - { - .pkt_count = rx.pkt_, - .byte_count = rx.len_, - }, - .tx = - { - .pkt_count = tx.pkt_, - .byte_count = tx.len_, - }, + .rx = + { + .pkt_count = rx.pkt_, + .byte_count = rx.len_, + }, + .tx = + { + .pkt_count = tx.pkt_, + .byte_count = tx.len_, + }, }; rx.pkt_ = tx.pkt_ = rx.len_ = tx.len_ = 0; } if ((cmd.count_ != 0) || (event.count_ != 0)) { ldc.hci_cmd_evt_ds = { - .rx = - { - .pkt_count = event.count_, - }, - .tx = - { - .pkt_count = cmd.count_, - }, + .rx = + { + .pkt_count = event.count_, + }, + .tx = + { + .pkt_count = cmd.count_, + }, }; cmd.count_ = event.count_ = 0; } if (ble_scan.count_ != 0) { ldc.le_scan_details = { - .count = ble_scan.count_, + .count = ble_scan.count_, }; ble_scan.count_ = 0; } @@ -294,17 +291,18 @@ void power_telemetry::PowerTelemetryImpl::LogDataTransfer() { } void power_telemetry::PowerTelemetryImpl::RecordLogDataContainer() { - if (!power_telemerty_enabled_) return; + if (!power_telemerty_enabled_) { + return; + } LogDataContainer& ldc = GetCurrentLogDataContainer(); log::info( - "bt_power: scan: {}, inqScan: {}, aclTx: {}, aclRx: {}, hciCmd: {}, " - "hciEvt: {}, bleScan: {}", - ldc.scan_details.count, ldc.inq_scan_details.count, - ldc.acl_pkt_ds.tx.pkt_count, ldc.acl_pkt_ds.rx.pkt_count, - ldc.hci_cmd_evt_ds.tx.pkt_count, ldc.hci_cmd_evt_ds.rx.pkt_count, - ldc.le_scan_details.count); + "bt_power: scan: {}, inqScan: {}, aclTx: {}, aclRx: {}, hciCmd: {}, " + "hciEvt: {}, bleScan: {}", + ldc.scan_details.count, ldc.inq_scan_details.count, ldc.acl_pkt_ds.tx.pkt_count, + ldc.acl_pkt_ds.rx.pkt_count, ldc.hci_cmd_evt_ds.tx.pkt_count, + ldc.hci_cmd_evt_ds.rx.pkt_count, ldc.le_scan_details.count); idx_containers++; if (idx_containers >= kLogEntriesSize) { @@ -324,7 +322,9 @@ power_telemetry::PowerTelemetry::PowerTelemetry() { } void power_telemetry::PowerTelemetry::LogInqScanStarted() { - if (!power_telemerty_enabled_) return; + if (!power_telemerty_enabled_) { + return; + } std::lock_guard lock(pimpl_->dumpsys_mutex_); pimpl_->inq_scan.count_++; @@ -332,14 +332,18 @@ void power_telemetry::PowerTelemetry::LogInqScanStarted() { } void power_telemetry::PowerTelemetry::LogInqScanStopped() { - if (!power_telemerty_enabled_) return; + if (!power_telemerty_enabled_) { + return; + } std::lock_guard lock(pimpl_->dumpsys_mutex_); pimpl_->maybe_log_data(); } void power_telemetry::PowerTelemetry::LogBleScan(uint16_t num_resps) { - if (!power_telemerty_enabled_) return; + if (!power_telemerty_enabled_) { + return; + } std::lock_guard lock(pimpl_->dumpsys_mutex_); pimpl_->ble_scan.count_ += num_resps; @@ -347,7 +351,9 @@ void power_telemetry::PowerTelemetry::LogBleScan(uint16_t num_resps) { } void power_telemetry::PowerTelemetry::LogBleAdvStarted() { - if (!power_telemerty_enabled_) return; + if (!power_telemerty_enabled_) { + return; + } std::lock_guard lock(pimpl_->dumpsys_mutex_); const time_t current_time = get_current_time(); @@ -356,7 +362,9 @@ void power_telemetry::PowerTelemetry::LogBleAdvStarted() { } void power_telemetry::PowerTelemetry::LogBleAdvStopped() { - if (!power_telemerty_enabled_) return; + if (!power_telemerty_enabled_) { + return; + } std::lock_guard lock(pimpl_->dumpsys_mutex_); const time_t current_time = get_current_time(); @@ -370,7 +378,9 @@ void power_telemetry::PowerTelemetry::LogBleAdvStopped() { } void power_telemetry::PowerTelemetry::LogTxPower(void* res) { - if (!power_telemerty_enabled_) return; + if (!power_telemerty_enabled_) { + return; + } std::lock_guard lock(pimpl_->dumpsys_mutex_); tBTM_TX_POWER_RESULT* result = (tBTM_TX_POWER_RESULT*)res; @@ -392,18 +402,18 @@ void power_telemetry::PowerTelemetry::LogTxPower(void* res) { pimpl_->maybe_log_data(); } -void power_telemetry::PowerTelemetry::LogLinkDetails(uint16_t handle, - const RawAddress& bd_addr, - bool is_connected, - bool is_acl_link) { - if (!power_telemerty_enabled_) return; +void power_telemetry::PowerTelemetry::LogLinkDetails(uint16_t handle, const RawAddress& bd_addr, + bool is_connected, bool is_acl_link) { + if (!power_telemerty_enabled_) { + return; + } std::lock_guard lock(pimpl_->dumpsys_mutex_); LogDataContainer& ldc = pimpl_->GetCurrentLogDataContainer(); std::map& link_map = - is_acl_link ? ldc.acl.link_details_map : ldc.sco.link_details_map; + is_acl_link ? ldc.acl.link_details_map : ldc.sco.link_details_map; std::list& link_list = - is_acl_link ? ldc.acl.link_details_list : ldc.sco.link_details_list; + is_acl_link ? ldc.acl.link_details_list : ldc.sco.link_details_list; if (is_connected == false && link_map.count(handle) != 0) { LinkDetails link_details = link_map[handle]; @@ -412,10 +422,10 @@ void power_telemetry::PowerTelemetry::LogLinkDetails(uint16_t handle, link_map.erase(handle); } else if (is_connected == true) { link_map[handle] = { - .bd_addr = bd_addr, - .handle = handle, - .duration.begin = get_current_time(), - .tx_power_level = 0, + .bd_addr = bd_addr, + .handle = handle, + .duration.begin = get_current_time(), + .tx_power_level = 0, }; if (is_acl_link) { @@ -434,7 +444,9 @@ void power_telemetry::PowerTelemetry::LogLinkDetails(uint16_t handle, } void power_telemetry::PowerTelemetry::LogHciCmdDetail() { - if (!power_telemerty_enabled_) return; + if (!power_telemerty_enabled_) { + return; + } std::lock_guard lock(pimpl_->dumpsys_mutex_); pimpl_->cmd.count_++; @@ -442,16 +454,19 @@ void power_telemetry::PowerTelemetry::LogHciCmdDetail() { } void power_telemetry::PowerTelemetry::LogHciEvtDetail() { - if (!power_telemerty_enabled_) return; + if (!power_telemerty_enabled_) { + return; + } std::lock_guard lock(pimpl_->dumpsys_mutex_); pimpl_->event.count_++; pimpl_->maybe_log_data(); } -void power_telemetry::PowerTelemetry::LogSniffStarted( - uint16_t handle, const RawAddress& bd_addr) { - if (!power_telemerty_enabled_) return; +void power_telemetry::PowerTelemetry::LogSniffStarted(uint16_t handle, const RawAddress& bd_addr) { + if (!power_telemerty_enabled_) { + return; + } std::lock_guard lock(pimpl_->dumpsys_mutex_); const time_t current_timestamp = get_current_time(); @@ -463,17 +478,17 @@ void power_telemetry::PowerTelemetry::LogSniffStarted( sniff_data = ldc.sniff_activity_map[handle]; } sniff_data.sniff_count++; - sniff_data.active_duration_ts += - current_timestamp - sniff_data.last_mode_change_ts; + sniff_data.active_duration_ts += current_timestamp - sniff_data.last_mode_change_ts; sniff_data.last_mode_change_ts = get_current_time(); ldc.sniff_activity_map[handle] = sniff_data; pimpl_->maybe_log_data(); } -void power_telemetry::PowerTelemetry::LogSniffStopped( - uint16_t handle, const RawAddress& bd_addr) { - if (!power_telemerty_enabled_) return; +void power_telemetry::PowerTelemetry::LogSniffStopped(uint16_t handle, const RawAddress& bd_addr) { + if (!power_telemerty_enabled_) { + return; + } std::lock_guard lock(pimpl_->dumpsys_mutex_); const time_t current_timestamp = get_current_time(); @@ -485,8 +500,7 @@ void power_telemetry::PowerTelemetry::LogSniffStopped( sniff_data = ldc.sniff_activity_map[handle]; } sniff_data.active_count++; - sniff_data.sniff_duration_ts += - current_timestamp - sniff_data.last_mode_change_ts; + sniff_data.sniff_duration_ts += current_timestamp - sniff_data.last_mode_change_ts; sniff_data.last_mode_change_ts = get_current_time(); ldc.sniff_activity_map[handle] = sniff_data; @@ -494,7 +508,9 @@ void power_telemetry::PowerTelemetry::LogSniffStopped( } void power_telemetry::PowerTelemetry::LogScanStarted() { - if (!power_telemerty_enabled_) return; + if (!power_telemerty_enabled_) { + return; + } std::lock_guard lock(pimpl_->dumpsys_mutex_); pimpl_->scan.count_++; @@ -502,7 +518,9 @@ void power_telemetry::PowerTelemetry::LogScanStarted() { } void power_telemetry::PowerTelemetry::LogTxAclPktData(uint16_t len) { - if (!power_telemerty_enabled_) return; + if (!power_telemerty_enabled_) { + return; + } std::lock_guard lock(pimpl_->dumpsys_mutex_); pimpl_->tx.pkt_++; @@ -511,7 +529,9 @@ void power_telemetry::PowerTelemetry::LogTxAclPktData(uint16_t len) { } void power_telemetry::PowerTelemetry::LogRxAclPktData(uint16_t len) { - if (!power_telemerty_enabled_) return; + if (!power_telemerty_enabled_) { + return; + } std::lock_guard lock(pimpl_->dumpsys_mutex_); pimpl_->rx.pkt_++; @@ -519,30 +539,33 @@ void power_telemetry::PowerTelemetry::LogRxAclPktData(uint16_t len) { pimpl_->maybe_log_data(); } -void power_telemetry::PowerTelemetry::LogChannelConnected( - uint16_t psm, int32_t src_id, int32_t dst_id, const RawAddress& bd_addr) { - if (!power_telemerty_enabled_) return; +void power_telemetry::PowerTelemetry::LogChannelConnected(uint16_t psm, int32_t src_id, + int32_t dst_id, + const RawAddress& bd_addr) { + if (!power_telemerty_enabled_) { + return; + } std::lock_guard lock(pimpl_->dumpsys_mutex_); std::list channel_details_list; LogDataContainer& ldc = pimpl_->GetCurrentLogDataContainer(); const ChannelType channel_type = PsmToChannelType(psm); ChannelDetails channel_details = { - .bd_addr = bd_addr, - .psm = psm, - .src.cid = static_cast(src_id), - .dst.cid = static_cast(dst_id), - .state = State::kConnected, - .channel_type = channel_type, - .data_transfer = {}, - .duration.begin = get_current_time(), - .rx = {}, - .tx = {}, + .bd_addr = bd_addr, + .psm = psm, + .src.cid = static_cast(src_id), + .dst.cid = static_cast(dst_id), + .state = State::kConnected, + .channel_type = channel_type, + .data_transfer = {}, + .duration.begin = get_current_time(), + .rx = {}, + .tx = {}, }; if (ldc.channel_map.count(bd_addr) == 0) { ldc.channel_map.insert(std::pair>( - bd_addr, std::list({channel_details}))); + bd_addr, std::list({channel_details}))); } else { ldc.channel_map[bd_addr].emplace_back(channel_details); } @@ -550,9 +573,12 @@ void power_telemetry::PowerTelemetry::LogChannelConnected( pimpl_->maybe_log_data(); } -void power_telemetry::PowerTelemetry::LogChannelDisconnected( - uint16_t psm, int32_t src_id, int32_t dst_id, const RawAddress& bd_addr) { - if (!power_telemerty_enabled_) return; +void power_telemetry::PowerTelemetry::LogChannelDisconnected(uint16_t psm, int32_t src_id, + int32_t dst_id, + const RawAddress& bd_addr) { + if (!power_telemerty_enabled_) { + return; + } std::lock_guard lock(pimpl_->dumpsys_mutex_); std::list channel_details_list; @@ -575,11 +601,11 @@ void power_telemetry::PowerTelemetry::LogChannelDisconnected( pimpl_->maybe_log_data(); } -void power_telemetry::PowerTelemetry::LogTxBytes(uint16_t psm, int32_t src_id, - int32_t dst_id, - const RawAddress& bd_addr, - int32_t num_bytes) { - if (!power_telemerty_enabled_) return; +void power_telemetry::PowerTelemetry::LogTxBytes(uint16_t psm, int32_t src_id, int32_t dst_id, + const RawAddress& bd_addr, int32_t num_bytes) { + if (!power_telemerty_enabled_) { + return; + } const ChannelType channel_type = PsmToChannelType(psm); std::lock_guard lock(pimpl_->dumpsys_mutex_); @@ -591,8 +617,7 @@ void power_telemetry::PowerTelemetry::LogTxBytes(uint16_t psm, int32_t src_id, } for (auto& channel_details : ldc.channel_map[bd_addr]) { - if (channel_details.src.cid == src_id && - channel_details.dst.cid == dst_id && + if (channel_details.src.cid == src_id && channel_details.dst.cid == dst_id && channel_details.channel_type == channel_type) { channel_details.data_transfer.tx.bytes += num_bytes; channel_details.tx.last_data_sent = get_current_time(); @@ -608,11 +633,11 @@ void power_telemetry::PowerTelemetry::LogTxBytes(uint16_t psm, int32_t src_id, pimpl_->maybe_log_data(); } -void power_telemetry::PowerTelemetry::LogRxBytes(uint16_t psm, int32_t src_id, - int32_t dst_id, - const RawAddress& bd_addr, - int32_t num_bytes) { - if (!power_telemerty_enabled_) return; +void power_telemetry::PowerTelemetry::LogRxBytes(uint16_t psm, int32_t src_id, int32_t dst_id, + const RawAddress& bd_addr, int32_t num_bytes) { + if (!power_telemerty_enabled_) { + return; + } const ChannelType channel_type = PsmToChannelType(psm); std::lock_guard lock(pimpl_->dumpsys_mutex_); @@ -624,8 +649,7 @@ void power_telemetry::PowerTelemetry::LogRxBytes(uint16_t psm, int32_t src_id, } for (auto& channel_detail : ldc.channel_map[bd_addr]) { - if (channel_detail.src.cid == src_id && - channel_detail.dst.cid == dst_id && + if (channel_detail.src.cid == src_id && channel_detail.dst.cid == dst_id && channel_detail.channel_type == channel_type) { channel_detail.data_transfer.rx.bytes += num_bytes; channel_detail.rx.last_data_sent = get_current_time(); @@ -649,81 +673,73 @@ void power_telemetry::PowerTelemetry::LogRxBytes(uint16_t psm, int32_t src_id, } void power_telemetry::PowerTelemetry::Dumpsys(int32_t fd) { - if (!power_telemerty_enabled_) return; + if (!power_telemerty_enabled_) { + return; + } std::lock_guard lock(pimpl_->dumpsys_mutex_); pimpl_->RecordLogDataContainer(); dprintf(fd, "\nPower Telemetry Data:\n"); dprintf(fd, "\nBR/EDR Scan Events:\n"); - dprintf(fd, "%-22s %-22s %-15s\n", "StartTimeStamp", "EndTimeStamp", - "Number of Scans"); + dprintf(fd, "%-22s %-22s %-15s\n", "StartTimeStamp", "EndTimeStamp", "Number of Scans"); for (auto&& ldc : pimpl_->log_data_containers_) { if (ldc.scan_details.count == 0) { continue; } - dprintf(fd, "%-22s %-22s %-15d\n", - GetTimeString(ldc.lifetime.begin).c_str(), + dprintf(fd, "%-22s %-22s %-15d\n", GetTimeString(ldc.lifetime.begin).c_str(), GetTimeString(ldc.lifetime.end).c_str(), ldc.scan_details.count); } dprintf(fd, "\nBR/EDR InqScan Events:\n"); - dprintf(fd, "%-22s %-22s %-15s\n", "StartTimeStamp", "EndTimeStamp", - "Number of InqScans"); + dprintf(fd, "%-22s %-22s %-15s\n", "StartTimeStamp", "EndTimeStamp", "Number of InqScans"); for (auto&& ldc : pimpl_->log_data_containers_) { if (ldc.inq_scan_details.count == 0) { continue; } - dprintf( - fd, "%-22s %-22s %-15d\n", GetTimeString(ldc.lifetime.begin).c_str(), - GetTimeString(ldc.lifetime.end).c_str(), ldc.inq_scan_details.count); + dprintf(fd, "%-22s %-22s %-15d\n", GetTimeString(ldc.lifetime.begin).c_str(), + GetTimeString(ldc.lifetime.end).c_str(), ldc.inq_scan_details.count); } dprintf(fd, "\nACL Packet Details:\n"); - dprintf(fd, "%-22s %-22s %-12s %-12s %-12s %-12s\n", "StartTimeStamp", - "EndTimeStamp", "Tx Packets", "Tx Bytes", "Rx Packets", "Rx Bytes"); + dprintf(fd, "%-22s %-22s %-12s %-12s %-12s %-12s\n", "StartTimeStamp", "EndTimeStamp", + "Tx Packets", "Tx Bytes", "Rx Packets", "Rx Bytes"); for (auto&& ldc : pimpl_->log_data_containers_) { - if ((ldc.acl_pkt_ds.tx.byte_count == 0) && - (ldc.acl_pkt_ds.rx.byte_count == 0)) { + if ((ldc.acl_pkt_ds.tx.byte_count == 0) && (ldc.acl_pkt_ds.rx.byte_count == 0)) { continue; } dprintf(fd, "%-22s %-22s %-12d %-12ld %-12d %-12ld\n", - GetTimeString(ldc.lifetime.begin).c_str(), - GetTimeString(ldc.lifetime.end).c_str(), + GetTimeString(ldc.lifetime.begin).c_str(), GetTimeString(ldc.lifetime.end).c_str(), ldc.acl_pkt_ds.tx.pkt_count, (long)ldc.acl_pkt_ds.tx.byte_count, ldc.acl_pkt_ds.rx.pkt_count, (long)ldc.acl_pkt_ds.rx.byte_count); } dprintf(fd, "\nHCI CMD/EVT Details:\n"); - dprintf(fd, "%-22s %-22s %-14s %-14s\n", "StartTimeStamp", "EndTimeStamp", - "HCI Commands", "HCI Events"); + dprintf(fd, "%-22s %-22s %-14s %-14s\n", "StartTimeStamp", "EndTimeStamp", "HCI Commands", + "HCI Events"); for (auto&& ldc : pimpl_->log_data_containers_) { - if ((ldc.hci_cmd_evt_ds.tx.pkt_count == 0) && - (ldc.hci_cmd_evt_ds.rx.pkt_count == 0)) { + if ((ldc.hci_cmd_evt_ds.tx.pkt_count == 0) && (ldc.hci_cmd_evt_ds.rx.pkt_count == 0)) { continue; } - dprintf(fd, "%-22s %-22s %-14d %-14d\n", - GetTimeString(ldc.lifetime.begin).c_str(), - GetTimeString(ldc.lifetime.end).c_str(), - ldc.hci_cmd_evt_ds.tx.pkt_count, ldc.hci_cmd_evt_ds.rx.pkt_count); + dprintf(fd, "%-22s %-22s %-14d %-14d\n", GetTimeString(ldc.lifetime.begin).c_str(), + GetTimeString(ldc.lifetime.end).c_str(), ldc.hci_cmd_evt_ds.tx.pkt_count, + ldc.hci_cmd_evt_ds.rx.pkt_count); } dprintf(fd, "\nBLE Scan Details:\n"); - dprintf(fd, "%-22s %-22s %-14s\n", "StartTimeStamp", "EndTimeStamp", - "Number of scans"); + dprintf(fd, "%-22s %-22s %-14s\n", "StartTimeStamp", "EndTimeStamp", "Number of scans"); for (auto&& ldc : pimpl_->log_data_containers_) { if (ldc.le_scan_details.count == 0) { continue; } - dprintf(fd, "%-22s %-22s %-14d\n", - GetTimeString(ldc.lifetime.begin).c_str(), + dprintf(fd, "%-22s %-22s %-14d\n", GetTimeString(ldc.lifetime.begin).c_str(), GetTimeString(ldc.lifetime.end).c_str(), ldc.le_scan_details.count); } dprintf(fd, "\nL2CAP/RFCOMM Channel Events:\n"); - dprintf(fd, "%-19s %-7s %-7s %-7s %-8s %-22s", "RemoteAddress", "Type", - "SrcId", "DstId", "PSM", "ConnectedTimeStamp"); + dprintf(fd, "%-19s %-7s %-7s %-7s %-8s %-22s", "RemoteAddress", "Type", "SrcId", "DstId", "PSM", + "ConnectedTimeStamp"); dprintf(fd, " %-22s %-14s ", "DisconnectedTimeStamp", "State"); if (pimpl_->log_per_channel_ == true) { - dprintf(fd, " %-10s %-10s %-22s %-22s", "TxBytes", "RxBytes", - "LastTxTimeStamp", "LastRxTimeStamp"); + dprintf(fd, " %-10s %-10s %-22s %-22s", "TxBytes", "RxBytes", "LastTxTimeStamp", + "LastRxTimeStamp"); } dprintf(fd, "\n"); for (auto&& ldc : pimpl_->log_data_containers_) { @@ -733,18 +749,13 @@ void power_telemetry::PowerTelemetry::Dumpsys(int32_t fd) { for (auto& channel_details : channel_details_list) { dprintf(fd, "%-19s ", ADDRESS_TO_LOGGABLE_CSTR(bd_addr)); dprintf(fd, "%-7s %-7d %-7d %-8d %-22s %-22s %-14s", - (channel_details.channel_type == ChannelType::kRfcomm) - ? "RFCOMM" - : "L2CAP", - channel_details.src.cid, channel_details.dst.cid, - channel_details.psm, + (channel_details.channel_type == ChannelType::kRfcomm) ? "RFCOMM" : "L2CAP", + channel_details.src.cid, channel_details.dst.cid, channel_details.psm, GetTimeString(channel_details.duration.begin).c_str(), GetTimeString(channel_details.duration.end).c_str(), - (channel_details.state == State::kDisconnected) ? "DISCONNECTED" - : "CONNECTED"); + (channel_details.state == State::kDisconnected) ? "DISCONNECTED" : "CONNECTED"); if (pimpl_->log_per_channel_ == true) { - dprintf(fd, "%-10ld %-10ld %-22s %-22s", - (long)channel_details.data_transfer.tx.bytes, + dprintf(fd, "%-10ld %-10ld %-22s %-22s", (long)channel_details.data_transfer.tx.bytes, (long)channel_details.data_transfer.rx.bytes, GetTimeString(channel_details.tx.last_data_sent).c_str(), GetTimeString(channel_details.rx.last_data_sent).c_str()); @@ -756,75 +767,66 @@ void power_telemetry::PowerTelemetry::Dumpsys(int32_t fd) { dprintf(fd, "\n\nBluetooth Data Traffic Details\n"); dprintf(fd, "L2cap Data Traffic\n"); - dprintf(fd, "%-22s %-22s %-10s %-10s\n", "StartTime", "EndTime", "TxBytes", - "RxBytes"); + dprintf(fd, "%-22s %-22s %-10s %-10s\n", "StartTime", "EndTime", "TxBytes", "RxBytes"); for (auto&& ldc : pimpl_->log_data_containers_) { if (ldc.l2c_data.tx.bytes == 0 && ldc.l2c_data.rx.bytes) { continue; } - dprintf(fd, "%-22s %-22s %-10ld %-10ld\n", - GetTimeString(ldc.lifetime.begin).c_str(), - GetTimeString(ldc.lifetime.end).c_str(), - (long)ldc.l2c_data.tx.bytes, (long)ldc.l2c_data.rx.bytes); + dprintf(fd, "%-22s %-22s %-10ld %-10ld\n", GetTimeString(ldc.lifetime.begin).c_str(), + GetTimeString(ldc.lifetime.end).c_str(), (long)ldc.l2c_data.tx.bytes, + (long)ldc.l2c_data.rx.bytes); } dprintf(fd, "\nRfcomm Data Traffic\n"); - dprintf(fd, "%-22s %-22s %-10s %-10s\n", "StartTime", "EndTime", "TxBytes", - "RxBytes"); + dprintf(fd, "%-22s %-22s %-10s %-10s\n", "StartTime", "EndTime", "TxBytes", "RxBytes"); for (auto&& ldc : pimpl_->log_data_containers_) { if (ldc.rfc_data.tx.bytes == 0 && ldc.rfc_data.rx.bytes == 0) { continue; } - dprintf(fd, "%-22s %-22s %-10ld %-10ld\n", - GetTimeString(ldc.lifetime.begin).c_str(), - GetTimeString(ldc.lifetime.end).c_str(), - (long)ldc.rfc_data.tx.bytes, (long)ldc.rfc_data.rx.bytes); + dprintf(fd, "%-22s %-22s %-10ld %-10ld\n", GetTimeString(ldc.lifetime.begin).c_str(), + GetTimeString(ldc.lifetime.end).c_str(), (long)ldc.rfc_data.tx.bytes, + (long)ldc.rfc_data.rx.bytes); } dprintf(fd, "\n\nSniff Activity Details\n"); - dprintf(fd, "%-8s %-19s %-19s %-24s %-19s %-24s\n", "Handle", "BDADDR", - "ActiveModeCount", "ActiveModeDuration(sec)", "SniffModeCount", - "SniffModeDuration(sec)"); + dprintf(fd, "%-8s %-19s %-19s %-24s %-19s %-24s\n", "Handle", "BDADDR", "ActiveModeCount", + "ActiveModeDuration(sec)", "SniffModeCount", "SniffModeDuration(sec)"); for (auto&& ldc : pimpl_->log_data_containers_) { for (auto itr : ldc.sniff_activity_map) { uint16_t handle = itr.first; SniffData sniff_data = itr.second; dprintf(fd, "%-8d %-19s %-19d %-24ld %-19d %-24ld\n", handle, - ADDRESS_TO_LOGGABLE_CSTR(sniff_data.bd_addr), - sniff_data.active_count, (long)sniff_data.active_duration_ts, - sniff_data.sniff_count, (long)sniff_data.sniff_duration_ts); + ADDRESS_TO_LOGGABLE_CSTR(sniff_data.bd_addr), sniff_data.active_count, + (long)sniff_data.active_duration_ts, sniff_data.sniff_count, + (long)sniff_data.sniff_duration_ts); } } dprintf(fd, "\n\nACL Link Details\n"); - dprintf(fd, "%-6s %-19s %-22s %-22s %-8s\n", "handle", "BDADDR", - "ConnectedTimeStamp", "DisconnectedTimeStamp", "TxPower"); + dprintf(fd, "%-6s %-19s %-22s %-22s %-8s\n", "handle", "BDADDR", "ConnectedTimeStamp", + "DisconnectedTimeStamp", "TxPower"); for (auto&& ldc : pimpl_->log_data_containers_) { for (auto it : ldc.acl.link_details_map) { uint16_t handle = it.first; LinkDetails lds = it.second; - dprintf(fd, "%-6d %-19s %-22s %-22s %-8d\n", handle, - ADDRESS_TO_LOGGABLE_CSTR(lds.bd_addr), - GetTimeString(lds.duration.begin).c_str(), - GetTimeString(lds.duration.end).c_str(), lds.tx_power_level); + dprintf(fd, "%-6d %-19s %-22s %-22s %-8d\n", handle, ADDRESS_TO_LOGGABLE_CSTR(lds.bd_addr), + GetTimeString(lds.duration.begin).c_str(), GetTimeString(lds.duration.end).c_str(), + lds.tx_power_level); } for (auto& it : ldc.acl.link_details_list) { - dprintf(fd, "%-6d %-19s %-22s %-22s %-8d\n", it.handle, - ADDRESS_TO_LOGGABLE_CSTR(it.bd_addr), - GetTimeString(it.duration.begin).c_str(), - GetTimeString(it.duration.end).c_str(), it.tx_power_level); + dprintf(fd, "%-6d %-19s %-22s %-22s %-8d\n", it.handle, ADDRESS_TO_LOGGABLE_CSTR(it.bd_addr), + GetTimeString(it.duration.begin).c_str(), GetTimeString(it.duration.end).c_str(), + it.tx_power_level); } } dprintf(fd, "\nSCO Link Details\n"); - dprintf(fd, "%-6s %-19s %-22s %-22s\n", "handle", "BDADDR", - "ConnectedTimeStamp", "DisconnectedTimeStamp"); + dprintf(fd, "%-6s %-19s %-22s %-22s\n", "handle", "BDADDR", "ConnectedTimeStamp", + "DisconnectedTimeStamp"); for (auto&& ldc : pimpl_->log_data_containers_) { for (auto& it : ldc.sco.link_details_list) { - dprintf(fd, "%-6d %-19s %-22s %-22s\n", it.handle, - ADDRESS_TO_LOGGABLE_CSTR(it.bd_addr), - GetTimeString(it.duration.begin).c_str(), - GetTimeString(it.duration.end).c_str()); + dprintf(fd, "%-6d %-19s %-22s %-22s\n", it.handle, ADDRESS_TO_LOGGABLE_CSTR(it.bd_addr), + GetTimeString(it.duration.begin).c_str(), GetTimeString(it.duration.end).c_str()); } } diff --git a/system/osi/src/thread.cc b/system/osi/src/thread.cc index e165d670c45..686c99f2f5b 100644 --- a/system/osi/src/thread.cc +++ b/system/osi/src/thread.cc @@ -68,21 +68,26 @@ static const size_t DEFAULT_WORK_QUEUE_CAPACITY = 128; thread_t* thread_new_sized(const char* name, size_t work_queue_capacity) { log::assert_that(name != NULL, "assert failed: name != NULL"); - log::assert_that(work_queue_capacity != 0, - "assert failed: work_queue_capacity != 0"); + log::assert_that(work_queue_capacity != 0, "assert failed: work_queue_capacity != 0"); thread_t* ret = static_cast(osi_calloc(sizeof(thread_t))); ret->reactor = reactor_new(); - if (!ret->reactor) goto error; + if (!ret->reactor) { + goto error; + } ret->work_queue = fixed_queue_new(work_queue_capacity); - if (!ret->work_queue) goto error; + if (!ret->work_queue) { + goto error; + } // Start is on the stack, but we use a semaphore, so it's safe struct start_arg start; start.start_sem = semaphore_new(0); - if (!start.start_sem) goto error; + if (!start.start_sem) { + goto error; + } strncpy(ret->name, name, THREAD_NAME_MAX); start.thread = ret; @@ -91,7 +96,9 @@ thread_t* thread_new_sized(const char* name, size_t work_queue_capacity) { semaphore_wait(start.start_sem); semaphore_free(start.start_sem); - if (start.error) goto error; + if (start.error) { + goto error; + } return ret; @@ -109,7 +116,9 @@ thread_t* thread_new(const char* name) { } void thread_free(thread_t* thread) { - if (!thread) return; + if (!thread) { + return; + } thread_stop(thread); thread_join(thread); @@ -122,8 +131,9 @@ void thread_free(thread_t* thread) { void thread_join(thread_t* thread) { log::assert_that(thread != NULL, "assert failed: thread != NULL"); - if (!std::atomic_exchange(&thread->is_joined, true)) + if (!std::atomic_exchange(&thread->is_joined, true)) { pthread_join(thread->pthread, NULL); + } } bool thread_post(thread_t* thread, thread_fn func, void* context) { @@ -149,12 +159,13 @@ void thread_stop(thread_t* thread) { } bool thread_set_priority(thread_t* thread, int priority) { - if (!thread) return false; + if (!thread) { + return false; + } const int rc = setpriority(PRIO_PROCESS, thread->tid, priority); if (rc < 0) { - log::error("unable to set thread priority {} for tid {}, error {}", - priority, thread->tid, rc); + log::error("unable to set thread priority {} for tid {}, error {}", priority, thread->tid, rc); return false; } @@ -162,15 +173,17 @@ bool thread_set_priority(thread_t* thread, int priority) { } bool thread_set_rt_priority(thread_t* thread, int priority) { - if (!thread) return false; + if (!thread) { + return false; + } struct sched_param rt_params; rt_params.sched_priority = priority; const int rc = sched_setscheduler(thread->tid, SCHED_FIFO, &rt_params); if (rc != 0) { - log::error("unable to set SCHED_FIFO priority {} for tid {}, error {}", - priority, thread->tid, strerror(errno)); + log::error("unable to set SCHED_FIFO priority {} for tid {}, error {}", priority, thread->tid, + strerror(errno)); return false; } @@ -216,7 +229,7 @@ static void* run_thread(void* start_arg) { void* context = thread->work_queue; reactor_object_t* work_queue_object = - reactor_register(thread->reactor, fd, context, work_queue_read_cb, NULL); + reactor_register(thread->reactor, fd, context, work_queue_read_cb, NULL); reactor_start(thread->reactor); reactor_unregister(work_queue_object); @@ -224,18 +237,17 @@ static void* run_thread(void* start_arg) { // This allows a caller to safely tear down by enqueuing a teardown // work item and then joining the thread. size_t count = 0; - work_item_t* item = - static_cast(fixed_queue_try_dequeue(thread->work_queue)); + work_item_t* item = static_cast(fixed_queue_try_dequeue(thread->work_queue)); while (item && count <= fixed_queue_capacity(thread->work_queue)) { item->func(item->context); osi_free(item); - item = - static_cast(fixed_queue_try_dequeue(thread->work_queue)); + item = static_cast(fixed_queue_try_dequeue(thread->work_queue)); ++count; } - if (count > fixed_queue_capacity(thread->work_queue)) + if (count > fixed_queue_capacity(thread->work_queue)) { log::info("growing event queue on shutdown."); + } log::warn("thread id {}, thread name {} exited", thread->tid, thread->name); return NULL; diff --git a/system/osi/src/thread_scheduler.cc b/system/osi/src/thread_scheduler.cc index b001c2c8c16..bb7a44e410e 100644 --- a/system/osi/src/thread_scheduler.cc +++ b/system/osi/src/thread_scheduler.cc @@ -22,8 +22,7 @@ constexpr int kRealTimeFifoSchedulingPriority = 1; } // namespace bool thread_scheduler_enable_real_time(pid_t linux_tid) { - struct sched_param rt_params = {.sched_priority = - kRealTimeFifoSchedulingPriority}; + struct sched_param rt_params = {.sched_priority = kRealTimeFifoSchedulingPriority}; return sched_setscheduler(linux_tid, SCHED_FIFO, &rt_params) == 0; } diff --git a/system/osi/src/wakelock.cc b/system/osi/src/wakelock.cc index 1a81f4717e5..9865ecb16a1 100644 --- a/system/osi/src/wakelock.cc +++ b/system/osi/src/wakelock.cc @@ -99,22 +99,23 @@ bool wakelock_acquire(void) { bt_status_t status = BT_STATUS_FAIL; - if (is_native) + if (is_native) { status = wakelock_acquire_native(); - else + } else { status = wakelock_acquire_callout(); + } update_wakelock_acquired_stats(status); - if (status != BT_STATUS_SUCCESS) + if (status != BT_STATUS_SUCCESS) { log::error("unable to acquire wake lock: {}", status); + } - return (status == BT_STATUS_SUCCESS); + return status == BT_STATUS_SUCCESS; } static bt_status_t wakelock_acquire_callout(void) { - return static_cast( - wakelock_os_callouts->acquire_wake_lock(WAKE_LOCK_ID)); + return static_cast(wakelock_os_callouts->acquire_wake_lock(WAKE_LOCK_ID)); } static bt_status_t wakelock_acquire_native(void) { @@ -145,19 +146,19 @@ bool wakelock_release(void) { bt_status_t status = BT_STATUS_FAIL; - if (is_native) + if (is_native) { status = wakelock_release_native(); - else + } else { status = wakelock_release_callout(); + } update_wakelock_released_stats(status); - return (status == BT_STATUS_SUCCESS); + return status == BT_STATUS_SUCCESS; } static bt_status_t wakelock_release_callout(void) { - return static_cast( - wakelock_os_callouts->release_wake_lock(WAKE_LOCK_ID)); + return static_cast(wakelock_os_callouts->release_wake_lock(WAKE_LOCK_ID)); } static bt_status_t wakelock_release_native(void) { @@ -178,25 +179,30 @@ static bt_status_t wakelock_release_native(void) { static void wakelock_initialize(void) { reset_wakelock_stats(); - if (is_native) wakelock_initialize_native(); + if (is_native) { + wakelock_initialize_native(); + } } static void wakelock_initialize_native(void) { log::info("opening wake locks"); - if (wake_lock_path.empty()) wake_lock_path = DEFAULT_WAKE_LOCK_PATH; + if (wake_lock_path.empty()) { + wake_lock_path = DEFAULT_WAKE_LOCK_PATH; + } wake_lock_fd = open(wake_lock_path.c_str(), O_RDWR | O_CLOEXEC); if (wake_lock_fd == INVALID_FD) { log::error("can't open wake lock {}: {}", wake_lock_path, strerror(errno)); } - if (wake_unlock_path.empty()) wake_unlock_path = DEFAULT_WAKE_UNLOCK_PATH; + if (wake_unlock_path.empty()) { + wake_unlock_path = DEFAULT_WAKE_UNLOCK_PATH; + } wake_unlock_fd = open(wake_unlock_path.c_str(), O_RDWR | O_CLOEXEC); if (wake_unlock_fd == INVALID_FD) { - log::error("can't open wake unlock {}: {}", wake_unlock_path, - strerror(errno)); + log::error("can't open wake unlock {}: {}", wake_unlock_path, strerror(errno)); } } @@ -211,9 +217,13 @@ void wakelock_cleanup(void) { } void wakelock_set_paths(const char* lock_path, const char* unlock_path) { - if (lock_path) wake_lock_path = lock_path; + if (lock_path) { + wake_lock_path = lock_path; + } - if (unlock_path) wake_unlock_path = unlock_path; + if (unlock_path) { + wake_unlock_path = unlock_path; + } } static uint64_t now_ms(void) { @@ -271,8 +281,8 @@ static void update_wakelock_acquired_stats(bt_status_t acquired_status) { wakelock_stats.acquired_count++; wakelock_stats.last_acquired_timestamp_ms = just_now_ms; - BluetoothMetricsLogger::GetInstance()->LogWakeEvent( - bluetooth::common::WAKE_EVENT_ACQUIRED, "", "", just_now_ms); + BluetoothMetricsLogger::GetInstance()->LogWakeEvent(bluetooth::common::WAKE_EVENT_ACQUIRED, "", + "", just_now_ms); } // @@ -303,8 +313,7 @@ static void update_wakelock_released_stats(bt_status_t released_status) { // Compute the acquired interval and update the statistics uint64_t delta_ms = just_now_ms - wakelock_stats.last_acquired_timestamp_ms; - if (delta_ms < wakelock_stats.min_acquired_interval_ms || - wakelock_stats.released_count == 1) { + if (delta_ms < wakelock_stats.min_acquired_interval_ms || wakelock_stats.released_count == 1) { wakelock_stats.min_acquired_interval_ms = delta_ms; } if (delta_ms > wakelock_stats.max_acquired_interval_ms) { @@ -313,8 +322,8 @@ static void update_wakelock_released_stats(bt_status_t released_status) { wakelock_stats.last_acquired_interval_ms = delta_ms; wakelock_stats.total_acquired_interval_ms += delta_ms; - BluetoothMetricsLogger::GetInstance()->LogWakeEvent( - bluetooth::common::WAKE_EVENT_RELEASED, "", "", just_now_ms); + BluetoothMetricsLogger::GetInstance()->LogWakeEvent(bluetooth::common::WAKE_EVENT_RELEASED, "", + "", just_now_ms); } void wakelock_debug_dump(int fd) { @@ -331,35 +340,34 @@ void wakelock_debug_dump(int fd) { if (wakelock_stats.is_acquired) { delta_ms = just_now_ms - wakelock_stats.last_acquired_timestamp_ms; - if (delta_ms > max_interval_ms) max_interval_ms = delta_ms; - if (delta_ms < min_interval_ms) min_interval_ms = delta_ms; + if (delta_ms > max_interval_ms) { + max_interval_ms = delta_ms; + } + if (delta_ms < min_interval_ms) { + min_interval_ms = delta_ms; + } last_interval_ms = delta_ms; } - uint64_t total_interval_ms = - wakelock_stats.total_acquired_interval_ms + delta_ms; + uint64_t total_interval_ms = wakelock_stats.total_acquired_interval_ms + delta_ms; - if (wakelock_stats.acquired_count > 0) + if (wakelock_stats.acquired_count > 0) { avg_interval_ms = total_interval_ms / wakelock_stats.acquired_count; + } dprintf(fd, "\nBluetooth Wakelock Statistics:\n"); dprintf(fd, " Is acquired : %s\n", wakelock_stats.is_acquired ? "true" : "false"); - dprintf(fd, " Acquired/released count : %zu / %zu\n", - wakelock_stats.acquired_count, wakelock_stats.released_count); - dprintf(fd, " Acquired/released error count : %zu / %zu\n", - wakelock_stats.acquired_errors, wakelock_stats.released_errors); - dprintf(fd, " Last acquire/release error code: %d / %d\n", - wakelock_stats.last_acquired_error, + dprintf(fd, " Acquired/released count : %zu / %zu\n", wakelock_stats.acquired_count, + wakelock_stats.released_count); + dprintf(fd, " Acquired/released error count : %zu / %zu\n", wakelock_stats.acquired_errors, + wakelock_stats.released_errors); + dprintf(fd, " Last acquire/release error code: %d / %d\n", wakelock_stats.last_acquired_error, wakelock_stats.last_released_error); - dprintf(fd, " Last acquired time (ms) : %llu\n", - (unsigned long long)last_interval_ms); + dprintf(fd, " Last acquired time (ms) : %llu\n", (unsigned long long)last_interval_ms); dprintf(fd, " Acquired time min/max/avg (ms) : %llu / %llu / %llu\n", - (unsigned long long)min_interval_ms, - (unsigned long long)max_interval_ms, + (unsigned long long)min_interval_ms, (unsigned long long)max_interval_ms, (unsigned long long)avg_interval_ms); - dprintf(fd, " Total acquired time (ms) : %llu\n", - (unsigned long long)total_interval_ms); + dprintf(fd, " Total acquired time (ms) : %llu\n", (unsigned long long)total_interval_ms); dprintf(fd, " Total run time (ms) : %llu\n", - (unsigned long long)(just_now_ms - - wakelock_stats.last_reset_timestamp_ms)); + (unsigned long long)(just_now_ms - wakelock_stats.last_reset_timestamp_ms)); } diff --git a/system/osi/test/alarm_mock.h b/system/osi/test/alarm_mock.h index a15bb6ea340..f3fb4411665 100644 --- a/system/osi/test/alarm_mock.h +++ b/system/osi/test/alarm_mock.h @@ -4,14 +4,14 @@ struct alarm_t; class AlarmMock { - public: +public: MOCK_METHOD1(AlarmNew, alarm_t*(const char*)); MOCK_METHOD1(AlarmFree, void(alarm_t*)); MOCK_METHOD1(AlarmCancel, void(alarm_t*)); - MOCK_METHOD4(AlarmSet, void(alarm_t* alarm, uint64_t interval_ms, - alarm_callback_t cb, void* data)); - MOCK_METHOD4(AlarmSetOnMloop, void(alarm_t* alarm, uint64_t interval_ms, - alarm_callback_t cb, void* data)); + MOCK_METHOD4(AlarmSet, + void(alarm_t* alarm, uint64_t interval_ms, alarm_callback_t cb, void* data)); + MOCK_METHOD4(AlarmSetOnMloop, + void(alarm_t* alarm, uint64_t interval_ms, alarm_callback_t cb, void* data)); MOCK_METHOD1(AlarmIsScheduled, bool(const alarm_t*)); alarm_t* AlarmNewImpl(const char* name) { @@ -37,30 +37,24 @@ class AlarmMock { static inline void Reset() { localAlarmMock = std::make_unique(); } - private: +private: static std::unique_ptr localAlarmMock; }; std::unique_ptr AlarmMock::localAlarmMock; -alarm_t* alarm_new(const char* name) { - return AlarmMock::Get()->AlarmNewImpl(name); -} +alarm_t* alarm_new(const char* name) { return AlarmMock::Get()->AlarmNewImpl(name); } void alarm_free(alarm_t* alarm) { AlarmMock::Get()->AlarmFreeImpl(alarm); } -void alarm_set_on_mloop(alarm_t* alarm, uint64_t interval_ms, - alarm_callback_t cb, void* data) { +void alarm_set_on_mloop(alarm_t* alarm, uint64_t interval_ms, alarm_callback_t cb, void* data) { AlarmMock::Get()->AlarmSetOnMloop(alarm, interval_ms, cb, data); } -void alarm_set(alarm_t* alarm, uint64_t interval_ms, alarm_callback_t cb, - void* data) { +void alarm_set(alarm_t* alarm, uint64_t interval_ms, alarm_callback_t cb, void* data) { AlarmMock::Get()->AlarmSet(alarm, interval_ms, cb, data); } -bool alarm_is_scheduled(const alarm_t* alarm) { - return AlarmMock::Get()->AlarmIsScheduled(alarm); -} +bool alarm_is_scheduled(const alarm_t* alarm) { return AlarmMock::Get()->AlarmIsScheduled(alarm); } void alarm_cancel(alarm_t* alarm) { AlarmMock::Get()->AlarmCancel(alarm); } diff --git a/system/osi/test/alarm_test.cc b/system/osi/test/alarm_test.cc index b3325984da9..5eab1cbc41d 100644 --- a/system/osi/test/alarm_test.cc +++ b/system/osi/test/alarm_test.cc @@ -57,11 +57,11 @@ static int release_wake_lock_cb(const char* lock_name) { return BT_STATUS_SUCCESS; } -static bt_os_callouts_t bt_wakelock_callouts = { - sizeof(bt_os_callouts_t), acquire_wake_lock_cb, release_wake_lock_cb}; +static bt_os_callouts_t bt_wakelock_callouts = {sizeof(bt_os_callouts_t), acquire_wake_lock_cb, + release_wake_lock_cb}; class AlarmTest : public ::testing::Test { - protected: +protected: void SetUp() override { TIMER_INTERVAL_FOR_WAKELOCK_IN_MS = 500; @@ -88,7 +88,9 @@ static void cb(void* /* data */) { static void ordered_cb(void* data) { int i = PTR_TO_INT(data); - if (i != cb_counter) cb_misordered_counter++; + if (i != cb_counter) { + cb_misordered_counter++; + } ++cb_counter; semaphore_post(semaphore); } @@ -227,8 +229,7 @@ TEST_F(AlarmTest, test_set_short_long) { alarm_new("alarm_test.test_set_short_long_1")}; alarm_set(alarm[0], 10, cb, NULL); - alarm_set(alarm[1], 10 + TIMER_INTERVAL_FOR_WAKELOCK_IN_MS + EPSILON_MS, cb, - NULL); + alarm_set(alarm[1], 10 + TIMER_INTERVAL_FOR_WAKELOCK_IN_MS + EPSILON_MS, cb, NULL); EXPECT_EQ(cb_counter, 0); EXPECT_TRUE(is_wake_lock_acquired); @@ -252,8 +253,7 @@ TEST_F(AlarmTest, test_set_long_long) { alarm_new("alarm_test.test_set_long_long_1")}; alarm_set(alarm[0], TIMER_INTERVAL_FOR_WAKELOCK_IN_MS + EPSILON_MS, cb, NULL); - alarm_set(alarm[1], 2 * (TIMER_INTERVAL_FOR_WAKELOCK_IN_MS + EPSILON_MS), cb, - NULL); + alarm_set(alarm[1], 2 * (TIMER_INTERVAL_FOR_WAKELOCK_IN_MS + EPSILON_MS), cb, NULL); EXPECT_EQ(cb_counter, 0); EXPECT_FALSE(is_wake_lock_acquired); @@ -297,8 +297,7 @@ TEST_F(AlarmTest, test_callback_ordering) { alarm_t* alarms[100]; for (int i = 0; i < 100; i++) { - const std::string alarm_name = - "alarm_test.test_callback_ordering[" + std::to_string(i) + "]"; + const std::string alarm_name = "alarm_test.test_callback_ordering[" + std::to_string(i) + "]"; alarms[i] = alarm_new(alarm_name.c_str()); } @@ -313,7 +312,9 @@ TEST_F(AlarmTest, test_callback_ordering) { EXPECT_EQ(cb_counter, 100); EXPECT_EQ(cb_misordered_counter, 0); - for (int i = 0; i < 100; i++) alarm_free(alarms[i]); + for (int i = 0; i < 100; i++) { + alarm_free(alarms[i]); + } EXPECT_FALSE(is_wake_lock_acquired); } @@ -333,7 +334,7 @@ TEST_F(AlarmTest, test_callback_ordering_on_mloop) { for (int i = 0; i < 100; i++) { const std::string alarm_name = - "alarm_test.test_callback_ordering_on_mloop[" + std::to_string(i) + "]"; + "alarm_test.test_callback_ordering_on_mloop[" + std::to_string(i) + "]"; alarms[i] = alarm_new(alarm_name.c_str()); } @@ -348,7 +349,9 @@ TEST_F(AlarmTest, test_callback_ordering_on_mloop) { EXPECT_EQ(cb_counter, 100); EXPECT_EQ(cb_misordered_counter, 0); - for (int i = 0; i < 100; i++) alarm_free(alarms[i]); + for (int i = 0; i < 100; i++) { + alarm_free(alarms[i]); + } message_loop_thread.ShutDown(); EXPECT_FALSE(is_wake_lock_acquired); @@ -357,8 +360,7 @@ TEST_F(AlarmTest, test_callback_ordering_on_mloop) { // Try to catch any race conditions between the timer callback and |alarm_free|. TEST_F(AlarmTest, test_callback_free_race) { for (int i = 0; i < 1000; ++i) { - const std::string alarm_name = - "alarm_test.test_callback_free_race[" + std::to_string(i) + "]"; + const std::string alarm_name = "alarm_test.test_callback_free_race[" + std::to_string(i) + "]"; alarm_t* alarm = alarm_new(alarm_name.c_str()); alarm_set(alarm, 0, cb, NULL); alarm_free(alarm); diff --git a/system/osi/test/config_test.cc b/system/osi/test/config_test.cc index a6d41419479..8148dc9df93 100644 --- a/system/osi/test/config_test.cc +++ b/system/osi/test/config_test.cc @@ -22,10 +22,10 @@ #include static const std::filesystem::path kConfigFile = - std::filesystem::temp_directory_path() / "config_test.conf"; + std::filesystem::temp_directory_path() / "config_test.conf"; static const char* CONFIG_FILE = kConfigFile.c_str(); static const char CONFIG_FILE_CONTENT[] = - " \n\ + " \n\ first_key=value \n\ \n\ # Device ID (DID) configuration \n\ @@ -69,7 +69,7 @@ HiSyncId2 = 15001900 "; class ConfigTest : public ::testing::Test { - protected: +protected: void SetUp() override { FILE* fp = fopen(CONFIG_FILE, "wt"); ASSERT_NE(fp, nullptr); @@ -78,9 +78,7 @@ class ConfigTest : public ::testing::Test { ASSERT_EQ(fclose(fp), 0); } - void TearDown() override { - EXPECT_TRUE(std::filesystem::remove(kConfigFile)); - } + void TearDown() override { EXPECT_TRUE(std::filesystem::remove(kConfigFile)); } }; TEST_F(ConfigTest, config_find) { @@ -149,15 +147,11 @@ TEST_F(ConfigTest, config_new_clone) { std::unique_ptr config = config_new(CONFIG_FILE); std::unique_ptr clone = config_new_clone(*config); - config_set_string(clone.get(), CONFIG_DEFAULT_SECTION, "first_key", - "not_value"); + config_set_string(clone.get(), CONFIG_DEFAULT_SECTION, "first_key", "not_value"); std::string one = std::string("one"); - EXPECT_STRNE( - config_get_string(*config, CONFIG_DEFAULT_SECTION, "first_key", &one) - ->c_str(), - config_get_string(*clone, CONFIG_DEFAULT_SECTION, "first_key", &one) - ->c_str()); + EXPECT_STRNE(config_get_string(*config, CONFIG_DEFAULT_SECTION, "first_key", &one)->c_str(), + config_get_string(*clone, CONFIG_DEFAULT_SECTION, "first_key", &one)->c_str()); } TEST_F(ConfigTest, config_has_section) { @@ -168,10 +162,8 @@ TEST_F(ConfigTest, config_has_section) { TEST_F(ConfigTest, config_has_key_in_default_section) { std::unique_ptr config = config_new(CONFIG_FILE); EXPECT_TRUE(config_has_key(*config, CONFIG_DEFAULT_SECTION, "first_key")); - EXPECT_STREQ( - config_get_string(*config, CONFIG_DEFAULT_SECTION, "first_key", nullptr) - ->c_str(), - "value"); + EXPECT_STREQ(config_get_string(*config, CONFIG_DEFAULT_SECTION, "first_key", nullptr)->c_str(), + "value"); } TEST_F(ConfigTest, config_has_keys) { @@ -186,8 +178,7 @@ TEST_F(ConfigTest, config_no_bad_keys) { std::unique_ptr config = config_new(CONFIG_FILE); EXPECT_FALSE(config_has_key(*config, "DID_BAD", "primaryRecord")); EXPECT_FALSE(config_has_key(*config, "DID", "primaryRecord_BAD")); - EXPECT_FALSE( - config_has_key(*config, CONFIG_DEFAULT_SECTION, "primaryRecord")); + EXPECT_FALSE(config_has_key(*config, CONFIG_DEFAULT_SECTION, "primaryRecord")); } TEST_F(ConfigTest, config_get_int_version) { @@ -202,16 +193,13 @@ TEST_F(ConfigTest, config_get_int_default) { TEST_F(ConfigTest, config_get_uint64) { std::unique_ptr config = config_new(CONFIG_FILE); - EXPECT_EQ(config_get_uint64(*config, "DID", "HiSyncId", 0), - 0xFFFFFFFFFFFFFFFF); - EXPECT_EQ(config_get_uint64(*config, "DID", "HiSyncId2", 0), - uint64_t(15001900)); + EXPECT_EQ(config_get_uint64(*config, "DID", "HiSyncId", 0), 0xFFFFFFFFFFFFFFFF); + EXPECT_EQ(config_get_uint64(*config, "DID", "HiSyncId2", 0), uint64_t(15001900)); } TEST_F(ConfigTest, config_get_uint64_default) { std::unique_ptr config = config_new(CONFIG_FILE); - EXPECT_EQ(config_get_uint64(*config, "DID", "primaryRecord", 123), - uint64_t(123)); + EXPECT_EQ(config_get_uint64(*config, "DID", "primaryRecord", 123), uint64_t(123)); } TEST_F(ConfigTest, config_remove_section) { @@ -251,8 +239,7 @@ TEST_F(ConfigTest, checksum_read) { std::string checksum = "0x1234"; base::FilePath file_path(filename.string()); - EXPECT_EQ(base::WriteFile(file_path, checksum.data(), checksum.size()), - (int)checksum.size()); + EXPECT_EQ(base::WriteFile(file_path, checksum.data(), checksum.size()), (int)checksum.size()); EXPECT_EQ(checksum_read(filename.c_str()), checksum.c_str()); diff --git a/system/osi/test/fixed_queue_test.cc b/system/osi/test/fixed_queue_test.cc index 88370cb24ba..2efd7a3dc0e 100644 --- a/system/osi/test/fixed_queue_test.cc +++ b/system/osi/test/fixed_queue_test.cc @@ -263,28 +263,24 @@ TEST_F(FixedQueueTest, test_fixed_queue_try_remove_from_queue) { ASSERT_TRUE(queue != NULL); // Test removing from a NULL queue - EXPECT_EQ(NULL, - fixed_queue_try_remove_from_queue(NULL, (void*)DUMMY_DATA_STRING)); + EXPECT_EQ(NULL, fixed_queue_try_remove_from_queue(NULL, (void*)DUMMY_DATA_STRING)); // Test removing from an empty queue - EXPECT_EQ(NULL, - fixed_queue_try_remove_from_queue(queue, (void*)DUMMY_DATA_STRING)); + EXPECT_EQ(NULL, fixed_queue_try_remove_from_queue(queue, (void*)DUMMY_DATA_STRING)); // Test removing a queued string from a queue fixed_queue_enqueue(queue, (void*)DUMMY_DATA_STRING1); fixed_queue_enqueue(queue, (void*)DUMMY_DATA_STRING2); fixed_queue_enqueue(queue, (void*)DUMMY_DATA_STRING3); EXPECT_EQ((size_t)3, fixed_queue_length(queue)); - EXPECT_EQ(DUMMY_DATA_STRING2, fixed_queue_try_remove_from_queue( - queue, (void*)DUMMY_DATA_STRING2)); + EXPECT_EQ(DUMMY_DATA_STRING2, + fixed_queue_try_remove_from_queue(queue, (void*)DUMMY_DATA_STRING2)); EXPECT_EQ((size_t)2, fixed_queue_length(queue)); // Removing again should fail - EXPECT_EQ(NULL, fixed_queue_try_remove_from_queue(queue, - (void*)DUMMY_DATA_STRING2)); + EXPECT_EQ(NULL, fixed_queue_try_remove_from_queue(queue, (void*)DUMMY_DATA_STRING2)); // Test removing a non-queued string from a queue - EXPECT_EQ(NULL, - fixed_queue_try_remove_from_queue(queue, (void*)DUMMY_DATA_STRING)); + EXPECT_EQ(NULL, fixed_queue_try_remove_from_queue(queue, (void*)DUMMY_DATA_STRING)); fixed_queue_free(queue, NULL); } @@ -334,8 +330,7 @@ TEST_F(FixedQueueTest, test_fixed_queue_register_dequeue) { thread_t* worker_thread = thread_new("test_fixed_queue_worker_thread"); ASSERT_TRUE(worker_thread != NULL); - fixed_queue_register_dequeue(queue, thread_get_reactor(worker_thread), - fixed_queue_ready, NULL); + fixed_queue_register_dequeue(queue, thread_get_reactor(worker_thread), fixed_queue_ready, NULL); // Add a message to the queue, and expect to receive it fixed_queue_enqueue(queue, (void*)DUMMY_DATA_STRING); diff --git a/system/osi/test/future_test.cc b/system/osi/test/future_test.cc index be17511b8d4..a3ed6203022 100644 --- a/system/osi/test/future_test.cc +++ b/system/osi/test/future_test.cc @@ -27,7 +27,7 @@ using bluetooth::common::MessageLoopThread; static const char* pass_back_data0 = "fancy a sandwich? it's a fancy sandwich"; static const char* pass_back_data1 = - "what kind of ice cream truck plays the worst christmas song of all time?"; + "what kind of ice cream truck plays the worst christmas song of all time?"; class FutureTest : public ::testing::Test {}; diff --git a/system/osi/test/fuzzers/alarm/fuzz_alarm.cc b/system/osi/test/fuzzers/alarm/fuzz_alarm.cc index 99ddd768ed9..5bf587fcfd8 100644 --- a/system/osi/test/fuzzers/alarm/fuzz_alarm.cc +++ b/system/osi/test/fuzzers/alarm/fuzz_alarm.cc @@ -16,9 +16,9 @@ #include #include -#include "osi/include/alarm.h" #include "common/message_loop_thread.h" +#include "osi/include/alarm.h" using base::Closure; using bluetooth::common::MessageLoopThread; @@ -28,7 +28,7 @@ using bluetooth::common::MessageLoopThread; #define MAX_ALARM_DURATION 25 class btsemaphore { - public: +public: void post() { std::lock_guard lock(mMutex); ++mCount; @@ -52,7 +52,7 @@ class btsemaphore { return false; } - private: +private: std::mutex mMutex; std::condition_variable mCondition; unsigned long mCount = 0; @@ -68,16 +68,13 @@ static void cb(void* data) { semaphore.post(); } -void setup() { - cb_counter = 0; -} -void teardown() { } +void setup() { cb_counter = 0; } +void teardown() {} alarm_t* fuzz_init_alarm(FuzzedDataProvider* dataProvider) { - size_t name_len = - dataProvider->ConsumeIntegralInRange(0, MAX_BUFFER_LEN); + size_t name_len = dataProvider->ConsumeIntegralInRange(0, MAX_BUFFER_LEN); std::vector alarm_name_vect = - dataProvider->ConsumeBytesWithTerminator(name_len, '\0'); + dataProvider->ConsumeBytesWithTerminator(name_len, '\0'); char* alarm_name = alarm_name_vect.data(); // Determine if our alarm will be periodic @@ -92,15 +89,13 @@ bool fuzz_set_alarm(alarm_t* alarm, uint64_t interval, alarm_callback_t cb, FuzzedDataProvider* dataProvider) { // Generate a random buffer (or null) void* data_buffer = nullptr; - size_t buff_len = - dataProvider->ConsumeIntegralInRange(1, MAX_BUFFER_LEN); + size_t buff_len = dataProvider->ConsumeIntegralInRange(1, MAX_BUFFER_LEN); if (buff_len == 0) { return false; } // allocate our space - std::vector data_vector = - dataProvider->ConsumeBytes(buff_len); + std::vector data_vector = dataProvider->ConsumeBytes(buff_len); data_buffer = data_vector.data(); // Make sure alarm is non-null @@ -145,11 +140,9 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* Data, size_t Size) { if (alarm) { // Set up another set of alarms & let these ones run - int num_alarms = - dataProvider.ConsumeIntegralInRange(0, MAX_CONCURRENT_ALARMS); + int num_alarms = dataProvider.ConsumeIntegralInRange(0, MAX_CONCURRENT_ALARMS); for (int i = 0; i < num_alarms; i++) { - uint64_t interval = - dataProvider.ConsumeIntegralInRange(0, MAX_ALARM_DURATION); + uint64_t interval = dataProvider.ConsumeIntegralInRange(0, MAX_ALARM_DURATION); if (!fuzz_set_alarm(alarm, interval, cb, &dataProvider)) { num_alarms = i; break; diff --git a/system/osi/test/fuzzers/allocator/fuzz_allocator.cc b/system/osi/test/fuzzers/allocator/fuzz_allocator.cc index bdfd99a1d4a..36b41606941 100644 --- a/system/osi/test/fuzzers/allocator/fuzz_allocator.cc +++ b/system/osi/test/fuzzers/allocator/fuzz_allocator.cc @@ -15,14 +15,14 @@ */ #include + #include "osi/include/allocator.h" #include "osi/test/fuzzers/include/libosiFuzzHelperFunctions.h" #define MAX_NUM_FUNCTIONS 512 #define MAX_BUF_SIZE 256 -void callArbitraryFunction(std::vector* alloc_vector, - FuzzedDataProvider* dataProvider) { +void callArbitraryFunction(std::vector* alloc_vector, FuzzedDataProvider* dataProvider) { // Get our function identifier char func_id = dataProvider->ConsumeIntegralInRange(0, 6); @@ -34,8 +34,7 @@ void callArbitraryFunction(std::vector* alloc_vector, // Let case 1 be osi_malloc, and 2 be osi_calloc case 1: case 2: { - size_t size = - dataProvider->ConsumeIntegralInRange(0, MAX_BUF_SIZE); + size_t size = dataProvider->ConsumeIntegralInRange(0, MAX_BUF_SIZE); void* ptr = nullptr; if (size == 0) { return; @@ -56,8 +55,7 @@ void callArbitraryFunction(std::vector* alloc_vector, if (alloc_vector->size() == 0) { return; } - size_t index = dataProvider->ConsumeIntegralInRange( - 0, alloc_vector->size() - 1); + size_t index = dataProvider->ConsumeIntegralInRange(0, alloc_vector->size() - 1); void* ptr = alloc_vector->at(index); if (ptr) { if (func_id == 3) { @@ -81,8 +79,7 @@ void callArbitraryFunction(std::vector* alloc_vector, if (func_id == 5) { str = osi_strdup(buf); } else { - size_t size = - dataProvider->ConsumeIntegralInRange(1, MAX_BUF_SIZE); + size_t size = dataProvider->ConsumeIntegralInRange(1, MAX_BUF_SIZE); str = osi_strndup(buf, size); } free(buf); @@ -103,8 +100,7 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* Data, size_t Size) { // Keep a vector of our allocated objects for freeing later std::vector alloc_vector; // Call some functions, create some buffers - size_t num_functions = - dataProvider.ConsumeIntegralInRange(0, MAX_NUM_FUNCTIONS); + size_t num_functions = dataProvider.ConsumeIntegralInRange(0, MAX_NUM_FUNCTIONS); for (size_t i = 0; i < num_functions; i++) { callArbitraryFunction(&alloc_vector, &dataProvider); } diff --git a/system/osi/test/fuzzers/compat/fuzz_compat.cc b/system/osi/test/fuzzers/compat/fuzz_compat.cc index b690818e224..84d986ef64f 100644 --- a/system/osi/test/fuzzers/compat/fuzz_compat.cc +++ b/system/osi/test/fuzzers/compat/fuzz_compat.cc @@ -14,6 +14,7 @@ * limitations under the License. */ #include + #include "osi/include/compat.h" #define MAX_BUFFER_SIZE 4096 @@ -24,8 +25,7 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* Data, size_t Size) { // Init our wrapper FuzzedDataProvider dataProvider(Data, Size); - size_t buf_size = - dataProvider.ConsumeIntegralInRange(0, MAX_BUFFER_SIZE); + size_t buf_size = dataProvider.ConsumeIntegralInRange(0, MAX_BUFFER_SIZE); if (buf_size == 0) { return 0; } @@ -33,8 +33,7 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* Data, size_t Size) { // Set up our buffers // NOTE: If the src buffer is not NULL-terminated, the strlcpy will // overread regardless of the len arg. Force null-term for now. - std::vector bytes = - dataProvider.ConsumeBytesWithTerminator(buf_size, '\0'); + std::vector bytes = dataProvider.ConsumeBytesWithTerminator(buf_size, '\0'); if (bytes.empty()) { return 0; } @@ -49,8 +48,7 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* Data, size_t Size) { // Copy, then concat size_t len_to_cpy = dataProvider.ConsumeIntegralInRange(0, buf_size); - strlcpy(reinterpret_cast(dst_buf), - reinterpret_cast(bytes.data()), len_to_cpy); + strlcpy(reinterpret_cast(dst_buf), reinterpret_cast(bytes.data()), len_to_cpy); // Clear out our dest buffer free(dst_buf); diff --git a/system/osi/test/fuzzers/fixed_queue/fuzz_fixed_queue.cc b/system/osi/test/fuzzers/fixed_queue/fuzz_fixed_queue.cc index f8a426a6a74..30c163390c4 100644 --- a/system/osi/test/fuzzers/fixed_queue/fuzz_fixed_queue.cc +++ b/system/osi/test/fuzzers/fixed_queue/fuzz_fixed_queue.cc @@ -16,6 +16,7 @@ #include #include + #include "osi/include/fixed_queue.h" #include "osi/include/future.h" #include "osi/include/thread.h" @@ -70,8 +71,7 @@ void createNewFuture() { received_message_future = future_new(); } -void callArbitraryFunction(fixed_queue_t* fixed_queue, - std::vector* live_buffer_vector, +void callArbitraryFunction(fixed_queue_t* fixed_queue, std::vector* live_buffer_vector, std::vector* live_thread_vector, FuzzedDataProvider* dataProvider) { void* buf_ptr = nullptr; @@ -148,8 +148,7 @@ void callArbitraryFunction(fixed_queue_t* fixed_queue, return; } // Grab an existing buffer - index = dataProvider->ConsumeIntegralInRange( - 0, live_buffer_vector->size() - 1); + index = dataProvider->ConsumeIntegralInRange(0, live_buffer_vector->size() - 1); buf_ptr = live_buffer_vector->at(index); if (buf_ptr != nullptr) { fixed_queue_try_remove_from_queue(fixed_queue, buf_ptr); @@ -157,8 +156,7 @@ void callArbitraryFunction(fixed_queue_t* fixed_queue, return; // Try to remove nonexistant element case 12: - buf_ptr = - reinterpret_cast(dataProvider->ConsumeIntegral()); + buf_ptr = reinterpret_cast(dataProvider->ConsumeIntegral()); if (buf_ptr != nullptr) { fixed_queue_try_remove_from_queue(fixed_queue, buf_ptr); } @@ -213,16 +211,13 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* Data, size_t Size) { std::vector live_buffer_vector; std::vector live_thread_vector; - size_t start_capacity = - dataProvider.ConsumeIntegralInRange(0, MAX_START_SIZE); + size_t start_capacity = dataProvider.ConsumeIntegralInRange(0, MAX_START_SIZE); fixed_queue_t* fixed_queue = fixed_queue_new(start_capacity); // How many functions are we going to call? - size_t num_functions = - dataProvider.ConsumeIntegralInRange(0, MAX_NUM_FUNCTIONS); + size_t num_functions = dataProvider.ConsumeIntegralInRange(0, MAX_NUM_FUNCTIONS); for (size_t i = 0; i < num_functions; i++) { - callArbitraryFunction(fixed_queue, &live_buffer_vector, &live_thread_vector, - &dataProvider); + callArbitraryFunction(fixed_queue, &live_buffer_vector, &live_thread_vector, &dataProvider); } // Free our queue (with either a null or placeholder callback) diff --git a/system/osi/test/fuzzers/future/fuzz_future.cc b/system/osi/test/fuzzers/future/fuzz_future.cc index 1df3e7da0ff..146378423cb 100644 --- a/system/osi/test/fuzzers/future/fuzz_future.cc +++ b/system/osi/test/fuzzers/future/fuzz_future.cc @@ -15,6 +15,7 @@ */ #include + #include "osi/include/future.h" #define MAX_BUFFER_SIZE 8 @@ -24,8 +25,7 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* Data, size_t Size) { FuzzedDataProvider dataProvider(Data, Size); // The value of this result ptr shouldn't matter, but make a buffer to be safe - size_t buf_size = - dataProvider.ConsumeIntegralInRange(1, MAX_BUFFER_SIZE); + size_t buf_size = dataProvider.ConsumeIntegralInRange(1, MAX_BUFFER_SIZE); void* buf = malloc(buf_size); if (buf == nullptr) { return 0; diff --git a/system/osi/test/fuzzers/include/libosiFuzzHelperFunctions.h b/system/osi/test/fuzzers/include/libosiFuzzHelperFunctions.h index 395b85ec777..ffb9be7a807 100644 --- a/system/osi/test/fuzzers/include/libosiFuzzHelperFunctions.h +++ b/system/osi/test/fuzzers/include/libosiFuzzHelperFunctions.h @@ -18,13 +18,13 @@ #define LIBOSI_FUZZ_HELPERS_H_ #include + #include char* generateBuffer(FuzzedDataProvider* dataProvider, size_t max_buffer_size, bool null_terminate) { // Get our buffer size - size_t buf_size = - dataProvider->ConsumeIntegralInRange(0, max_buffer_size); + size_t buf_size = dataProvider->ConsumeIntegralInRange(0, max_buffer_size); if (buf_size == 0) { return nullptr; } diff --git a/system/osi/test/fuzzers/list/fuzz_list.cc b/system/osi/test/fuzzers/list/fuzz_list.cc index a5814740a17..e0e74165d20 100644 --- a/system/osi/test/fuzzers/list/fuzz_list.cc +++ b/system/osi/test/fuzzers/list/fuzz_list.cc @@ -15,6 +15,7 @@ */ #include + #include "osi/include/list.h" #include "osi/test/fuzzers/include/libosiFuzzHelperFunctions.h" @@ -29,8 +30,7 @@ struct list_node_t { void cb(void* data) {} // Pass a ptr to FuzzedDataProvider in context bool list_iter_cb_impl(void* data, void* context) { - FuzzedDataProvider* dataProvider = - reinterpret_cast(context); + FuzzedDataProvider* dataProvider = reinterpret_cast(context); return dataProvider->ConsumeBool(); } @@ -43,14 +43,12 @@ list_t* createList(FuzzedDataProvider* dataProvider) { } } -void* getArbitraryElement(std::vector* vector, - FuzzedDataProvider* dataProvider) { +void* getArbitraryElement(std::vector* vector, FuzzedDataProvider* dataProvider) { if (vector->size() == 0) { return nullptr; } // Get an index - size_t index = - dataProvider->ConsumeIntegralInRange(0, vector->size() - 1); + size_t index = dataProvider->ConsumeIntegralInRange(0, vector->size() - 1); return vector->at(index); } @@ -58,8 +56,7 @@ list_node_t* getArbitraryNode(list_t* list, FuzzedDataProvider* dataProvider) { if (list == nullptr || list_is_empty(list)) { return nullptr; } - size_t index = - dataProvider->ConsumeIntegralInRange(0, list_length(list) - 1); + size_t index = dataProvider->ConsumeIntegralInRange(0, list_length(list) - 1); list_node_t* node = list_begin(list); for (size_t i = 0; i < index; i++) { node = node->next; @@ -68,8 +65,7 @@ list_node_t* getArbitraryNode(list_t* list, FuzzedDataProvider* dataProvider) { return node; } -void callArbitraryFunction(std::vector* list_vector, - std::vector* alloc_vector, +void callArbitraryFunction(std::vector* list_vector, std::vector* alloc_vector, FuzzedDataProvider* dataProvider) { list_t* list = nullptr; // Get our function identifier @@ -88,8 +84,7 @@ void callArbitraryFunction(std::vector* list_vector, size_t index = 0; if (list_vector->size() > 0) { // Get an index - index = dataProvider->ConsumeIntegralInRange( - 0, list_vector->size() - 1); + index = dataProvider->ConsumeIntegralInRange(0, list_vector->size() - 1); list = reinterpret_cast(list_vector->at(index)); } list_free(list); @@ -100,15 +95,13 @@ void callArbitraryFunction(std::vector* list_vector, return; } case 3: - list = reinterpret_cast( - getArbitraryElement(list_vector, dataProvider)); + list = reinterpret_cast(getArbitraryElement(list_vector, dataProvider)); if (list != nullptr) { list_is_empty(list); } return; case 4: - list = reinterpret_cast( - getArbitraryElement(list_vector, dataProvider)); + list = reinterpret_cast(getArbitraryElement(list_vector, dataProvider)); if (list != nullptr) { void* search_buf = getArbitraryElement(alloc_vector, dataProvider); if (search_buf != nullptr) { @@ -117,36 +110,31 @@ void callArbitraryFunction(std::vector* list_vector, } return; case 5: - list = reinterpret_cast( - getArbitraryElement(list_vector, dataProvider)); + list = reinterpret_cast(getArbitraryElement(list_vector, dataProvider)); if (list != nullptr) { list_length(list); } return; case 6: - list = reinterpret_cast( - getArbitraryElement(list_vector, dataProvider)); + list = reinterpret_cast(getArbitraryElement(list_vector, dataProvider)); if (list != nullptr && !list_is_empty(list)) { list_front(list); } return; case 7: - list = reinterpret_cast( - getArbitraryElement(list_vector, dataProvider)); + list = reinterpret_cast(getArbitraryElement(list_vector, dataProvider)); if (list != nullptr && !list_is_empty(list)) { list_back(list); } return; case 8: - list = reinterpret_cast( - getArbitraryElement(list_vector, dataProvider)); + list = reinterpret_cast(getArbitraryElement(list_vector, dataProvider)); if (list != nullptr && !list_is_empty(list)) { list_back_node(list); } return; case 9: { - list = reinterpret_cast( - getArbitraryElement(list_vector, dataProvider)); + list = reinterpret_cast(getArbitraryElement(list_vector, dataProvider)); if (list == nullptr) { return; } @@ -159,8 +147,7 @@ void callArbitraryFunction(std::vector* list_vector, return; } case 10: { - list = reinterpret_cast( - getArbitraryElement(list_vector, dataProvider)); + list = reinterpret_cast(getArbitraryElement(list_vector, dataProvider)); void* buf = generateBuffer(dataProvider, MAX_BUF_SIZE, false); alloc_vector->push_back(buf); if (list != nullptr && buf != nullptr) { @@ -169,8 +156,7 @@ void callArbitraryFunction(std::vector* list_vector, return; } case 11: { - list = reinterpret_cast( - getArbitraryElement(list_vector, dataProvider)); + list = reinterpret_cast(getArbitraryElement(list_vector, dataProvider)); void* buf = generateBuffer(dataProvider, MAX_BUF_SIZE, false); alloc_vector->push_back(buf); if (list != nullptr && buf != nullptr) { @@ -179,8 +165,7 @@ void callArbitraryFunction(std::vector* list_vector, return; } case 12: { - list = reinterpret_cast( - getArbitraryElement(list_vector, dataProvider)); + list = reinterpret_cast(getArbitraryElement(list_vector, dataProvider)); // The buffer will be valid, but may be for a different list void* buf = getArbitraryElement(alloc_vector, dataProvider); if (list != nullptr && buf != nullptr) { @@ -189,36 +174,31 @@ void callArbitraryFunction(std::vector* list_vector, return; } case 13: - list = reinterpret_cast( - getArbitraryElement(list_vector, dataProvider)); + list = reinterpret_cast(getArbitraryElement(list_vector, dataProvider)); if (list != nullptr) { list_clear(list); } return; case 14: - list = reinterpret_cast( - getArbitraryElement(list_vector, dataProvider)); + list = reinterpret_cast(getArbitraryElement(list_vector, dataProvider)); if (list != nullptr) { list_foreach(list, list_iter_cb_impl, dataProvider); } return; case 15: - list = reinterpret_cast( - getArbitraryElement(list_vector, dataProvider)); + list = reinterpret_cast(getArbitraryElement(list_vector, dataProvider)); if (list != nullptr) { list_begin(list); } return; case 16: - list = reinterpret_cast( - getArbitraryElement(list_vector, dataProvider)); + list = reinterpret_cast(getArbitraryElement(list_vector, dataProvider)); if (list != nullptr) { list_end(list); } return; case 17: { - list = reinterpret_cast( - getArbitraryElement(list_vector, dataProvider)); + list = reinterpret_cast(getArbitraryElement(list_vector, dataProvider)); if (list == nullptr) { return; } @@ -229,8 +209,7 @@ void callArbitraryFunction(std::vector* list_vector, return; } case 18: { - list = reinterpret_cast( - getArbitraryElement(list_vector, dataProvider)); + list = reinterpret_cast(getArbitraryElement(list_vector, dataProvider)); if (list == nullptr) { return; } @@ -254,8 +233,7 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* Data, size_t Size) { std::vector alloc_vector; // Call some functions, create some buffers - size_t num_functions = - dataProvider.ConsumeIntegralInRange(0, MAX_NUM_FUNCTIONS); + size_t num_functions = dataProvider.ConsumeIntegralInRange(0, MAX_NUM_FUNCTIONS); for (size_t i = 0; i < num_functions; i++) { callArbitraryFunction(&list_vector, &alloc_vector, &dataProvider); } diff --git a/system/osi/test/fuzzers/ringbuffer/fuzz_ringbuffer.cc b/system/osi/test/fuzzers/ringbuffer/fuzz_ringbuffer.cc index adc219c22ca..f676bb6f83b 100644 --- a/system/osi/test/fuzzers/ringbuffer/fuzz_ringbuffer.cc +++ b/system/osi/test/fuzzers/ringbuffer/fuzz_ringbuffer.cc @@ -15,6 +15,7 @@ */ #include + #include "osi/include/ringbuffer.h" #define MAX_NUM_FUNCTIONS 512 @@ -26,8 +27,7 @@ ringbuffer_t* getArbitraryRingBuf(std::vector* ringbuf_vector, return nullptr; } - size_t index = dataProvider->ConsumeIntegralInRange( - 0, ringbuf_vector->size() - 1); + size_t index = dataProvider->ConsumeIntegralInRange(0, ringbuf_vector->size() - 1); return ringbuf_vector->at(index); } @@ -43,8 +43,7 @@ void callArbitraryFunction(std::vector* ringbuf_vector, case 0: return; case 1: { - size_t size = - dataProvider->ConsumeIntegralInRange(0, MAX_BUF_SIZE); + size_t size = dataProvider->ConsumeIntegralInRange(0, MAX_BUF_SIZE); buf = ringbuffer_init(size); if (buf) { ringbuf_vector->push_back(buf); @@ -55,8 +54,7 @@ void callArbitraryFunction(std::vector* ringbuf_vector, if (ringbuf_vector->empty()) { return; } - size_t index = dataProvider->ConsumeIntegralInRange( - 0, ringbuf_vector->size() - 1); + size_t index = dataProvider->ConsumeIntegralInRange(0, ringbuf_vector->size() - 1); buf = ringbuf_vector->at(index); if (buf) { ringbuffer_free(buf); @@ -78,8 +76,7 @@ void callArbitraryFunction(std::vector* ringbuf_vector, return; case 5: { buf = getArbitraryRingBuf(ringbuf_vector, dataProvider); - size_t size = - dataProvider->ConsumeIntegralInRange(1, MAX_BUF_SIZE); + size_t size = dataProvider->ConsumeIntegralInRange(1, MAX_BUF_SIZE); if (buf == nullptr || size == 0) { return; } @@ -117,10 +114,8 @@ void callArbitraryFunction(std::vector* ringbuf_vector, } if (func_id == 6) { off_t offset = dataProvider->ConsumeIntegral(); - if (offset >= 0 && - static_cast(offset) <= ringbuffer_size(buf)) { - ringbuffer_peek(buf, offset, reinterpret_cast(dst_buf), - size); + if (offset >= 0 && static_cast(offset) <= ringbuffer_size(buf)) { + ringbuffer_peek(buf, offset, reinterpret_cast(dst_buf), size); } } else { ringbuffer_pop(buf, reinterpret_cast(dst_buf), size); @@ -130,8 +125,7 @@ void callArbitraryFunction(std::vector* ringbuf_vector, return; case 8: { buf = getArbitraryRingBuf(ringbuf_vector, dataProvider); - size_t size = - dataProvider->ConsumeIntegralInRange(0, MAX_BUF_SIZE); + size_t size = dataProvider->ConsumeIntegralInRange(0, MAX_BUF_SIZE); if (buf) { ringbuffer_delete(buf, size); } @@ -150,8 +144,7 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* Data, size_t Size) { std::vector ringbuf_vector; // Call some functions, create some buffers - size_t num_functions = - dataProvider.ConsumeIntegralInRange(0, MAX_NUM_FUNCTIONS); + size_t num_functions = dataProvider.ConsumeIntegralInRange(0, MAX_NUM_FUNCTIONS); for (size_t i = 0; i < num_functions; i++) { callArbitraryFunction(&ringbuf_vector, &dataProvider); } diff --git a/system/osi/test/hash_map_utils_test.cc b/system/osi/test/hash_map_utils_test.cc index 23241d438f7..c31975a3445 100644 --- a/system/osi/test/hash_map_utils_test.cc +++ b/system/osi/test/hash_map_utils_test.cc @@ -24,7 +24,7 @@ #include "osi/include/allocator.h" class HashMapUtilsTest : public ::testing::Test { - protected: +protected: void TearDown() override { map.clear(); } std::unordered_map map; diff --git a/system/osi/test/internal/semaphore_test.cc b/system/osi/test/internal/semaphore_test.cc index 9b1b993dd21..612804749f3 100644 --- a/system/osi/test/internal/semaphore_test.cc +++ b/system/osi/test/internal/semaphore_test.cc @@ -17,8 +17,7 @@ struct SemaphoreTestSequenceHelper { namespace { void sleep_then_increment_counter(void* context) { - SemaphoreTestSequenceHelper* helper = - reinterpret_cast(context); + SemaphoreTestSequenceHelper* helper = reinterpret_cast(context); EXPECT_NE(helper, nullptr); if (helper == nullptr) { return; @@ -84,11 +83,9 @@ TEST_F(SemaphoreTest, test_ensure_wait) { EXPECT_FALSE(semaphore_try_wait(semaphore)); SemaphoreTestSequenceHelper sequence_helper = {semaphore, 0}; - thread.DoInThread(FROM_HERE, base::BindOnce(sleep_then_increment_counter, - &sequence_helper)); + thread.DoInThread(FROM_HERE, base::BindOnce(sleep_then_increment_counter, &sequence_helper)); semaphore_wait(semaphore); - EXPECT_EQ(sequence_helper.counter, 1) - << "semaphore_wait() did not wait for counter to increment"; + EXPECT_EQ(sequence_helper.counter, 1) << "semaphore_wait() did not wait for counter to increment"; semaphore_free(semaphore); thread.ShutDown(); diff --git a/system/osi/test/list_test.cc b/system/osi/test/list_test.cc index 3de702c71b4..4b7e00fa526 100644 --- a/system/osi/test/list_test.cc +++ b/system/osi/test/list_test.cc @@ -68,7 +68,9 @@ TEST_F(ListTest, test_list_front) { int x[] = {1, 2, 3, 4, 5}; list_t* list = list_new(NULL); - for (size_t i = 0; i < ARRAY_SIZE(x); ++i) list_append(list, &x[i]); + for (size_t i = 0; i < ARRAY_SIZE(x); ++i) { + list_append(list, &x[i]); + } EXPECT_EQ(list_front(list), &x[0]); @@ -79,7 +81,9 @@ TEST_F(ListTest, test_list_back) { int x[] = {1, 2, 3, 4, 5}; list_t* list = list_new(NULL); - for (size_t i = 0; i < ARRAY_SIZE(x); ++i) list_append(list, &x[i]); + for (size_t i = 0; i < ARRAY_SIZE(x); ++i) { + list_append(list, &x[i]); + } EXPECT_EQ(list_back(list), &x[ARRAY_SIZE(x) - 1]); @@ -90,7 +94,9 @@ TEST_F(ListTest, test_list_clear) { int x[] = {1, 2, 3, 4, 5}; list_t* list = list_new(NULL); - for (size_t i = 0; i < ARRAY_SIZE(x); ++i) list_append(list, &x[i]); + for (size_t i = 0; i < ARRAY_SIZE(x); ++i) { + list_append(list, &x[i]); + } list_clear(list); EXPECT_TRUE(list_is_empty(list)); @@ -103,12 +109,15 @@ TEST_F(ListTest, test_list_append_multiple) { int x[] = {1, 2, 3, 4, 5}; list_t* list = list_new(NULL); - for (size_t i = 0; i < ARRAY_SIZE(x); ++i) list_append(list, &x[i]); + for (size_t i = 0; i < ARRAY_SIZE(x); ++i) { + list_append(list, &x[i]); + } int i = 0; - for (const list_node_t *node = list_begin(list); node != list_end(list); - node = list_next(node), ++i) + for (const list_node_t* node = list_begin(list); node != list_end(list); + node = list_next(node), ++i) { EXPECT_EQ(list_node(node), &x[i]); + } list_free(list); } @@ -117,12 +126,15 @@ TEST_F(ListTest, test_list_prepend_multiple) { int x[] = {1, 2, 3, 4, 5}; list_t* list = list_new(NULL); - for (size_t i = 0; i < ARRAY_SIZE(x); ++i) list_prepend(list, &x[i]); + for (size_t i = 0; i < ARRAY_SIZE(x); ++i) { + list_prepend(list, &x[i]); + } int i = ARRAY_SIZE(x) - 1; - for (const list_node_t *node = list_begin(list); node != list_end(list); - node = list_next(node), --i) + for (const list_node_t* node = list_begin(list); node != list_end(list); + node = list_next(node), --i) { EXPECT_EQ(list_node(node), &x[i]); + } list_free(list); } @@ -153,7 +165,7 @@ static bool list_callback_sum(void* data, void* context) { static bool list_callback_find_int(void* data, void* context) { EXPECT_NE(data, nullptr); EXPECT_NE(context, nullptr); - return (*(int*)data != *(int*)context); + return *(int*)data != *(int*)context; } TEST_F(ListTest, test_list_foreach_full) { @@ -161,7 +173,9 @@ TEST_F(ListTest, test_list_foreach_full) { // Fill in test data int x[] = {1, 2, 3, 4, 5}; - for (size_t i = 0; i < ARRAY_SIZE(x); ++i) list_append(list, &x[i]); + for (size_t i = 0; i < ARRAY_SIZE(x); ++i) { + list_append(list, &x[i]); + } EXPECT_EQ(list_length(list), (size_t)5); // Test complete iteration @@ -178,7 +192,9 @@ TEST_F(ListTest, test_list_foreach_partial) { // Fill in test data int x[] = {1, 2, 3, 4, 5}; - for (size_t i = 0; i < ARRAY_SIZE(x); ++i) list_append(list, &x[i]); + for (size_t i = 0; i < ARRAY_SIZE(x); ++i) { + list_append(list, &x[i]); + } EXPECT_EQ(list_length(list), (size_t)5); // Test partial iteration diff --git a/system/osi/test/ringbuffer_test.cc b/system/osi/test/ringbuffer_test.cc index 3475973bf1c..8149b017946 100644 --- a/system/osi/test/ringbuffer_test.cc +++ b/system/osi/test/ringbuffer_test.cc @@ -1,7 +1,8 @@ +#include "osi/include/ringbuffer.h" + #include #include "osi/include/osi.h" -#include "osi/include/ringbuffer.h" TEST(RingbufferTest, test_new_simple) { ringbuffer_t* rb = ringbuffer_init(4096); @@ -14,8 +15,7 @@ TEST(RingbufferTest, test_new_simple) { TEST(RingbufferTest, test_insert_basic) { ringbuffer_t* rb = ringbuffer_init(16); - uint8_t buffer[10] = {0x01, 0x02, 0x03, 0x04, 0x05, - 0x06, 0x07, 0x08, 0x09, 0x0A}; + uint8_t buffer[10] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A}; ringbuffer_insert(rb, buffer, 10); EXPECT_EQ((size_t)10, ringbuffer_size(rb)); EXPECT_EQ((size_t)6, ringbuffer_available(rb)); diff --git a/system/osi/test/stack_power_telemetry_test.cc b/system/osi/test/stack_power_telemetry_test.cc index 8668e39c01e..cc48518eaa0 100644 --- a/system/osi/test/stack_power_telemetry_test.cc +++ b/system/osi/test/stack_power_telemetry_test.cc @@ -6,7 +6,7 @@ #include "types/raw_address.h" class PowerTelemetryTest : public ::testing::Test { - protected: +protected: uint16_t handle = 123; RawAddress bdaddr; bool isConnected = true; @@ -15,8 +15,7 @@ class PowerTelemetryTest : public ::testing::Test { power_telemetry::GetInstance().pimpl_->LogDataTransfer(); power_telemetry::GetInstance().pimpl_->idx_containers = 0; for (int i = 0; i < kLogEntriesSize; i++) { - power_telemetry::GetInstance().pimpl_->log_data_containers_[i] = - LogDataContainer(); + power_telemetry::GetInstance().pimpl_->log_data_containers_[i] = LogDataContainer(); } } @@ -69,8 +68,7 @@ TEST_F(PowerTelemetryTest, test_LogBleScan) { TEST_F(PowerTelemetryTest, test_LogBleAdvDetails) { reset(); - LogDataContainer& ldc = - power_telemetry::GetInstance().pimpl_->GetCurrentLogDataContainer(); + LogDataContainer& ldc = power_telemetry::GetInstance().pimpl_->GetCurrentLogDataContainer(); // Failed Case. Shouldn't crash if run false first power_telemetry::GetInstance().LogBleAdvStopped(); @@ -94,8 +92,7 @@ TEST_F(PowerTelemetryTest, test_LogBleAdvDetails) { TEST_F(PowerTelemetryTest, test_LogTxPower) { reset(); - LogDataContainer& ldc = - power_telemetry::GetInstance().pimpl_->GetCurrentLogDataContainer(); + LogDataContainer& ldc = power_telemetry::GetInstance().pimpl_->GetCurrentLogDataContainer(); tBTM_TX_POWER_RESULT dummy_res; dummy_res.rem_bda = bdaddr; @@ -105,70 +102,59 @@ TEST_F(PowerTelemetryTest, test_LogTxPower) { power_telemetry::GetInstance().LogTxPower(p); // init data - power_telemetry::GetInstance().LogLinkDetails(handle, bdaddr, isConnected, - true); + power_telemetry::GetInstance().LogLinkDetails(handle, bdaddr, isConnected, true); // Successful case dummy_res.tx_power = 100; power_telemetry::GetInstance().LogTxPower(p); - ASSERT_EQ(dummy_res.tx_power, - ldc.acl.link_details_map[handle].tx_power_level); + ASSERT_EQ(dummy_res.tx_power, ldc.acl.link_details_map[handle].tx_power_level); // Failed case dummy_res.tx_power = 99; dummy_res.status = BTM_UNDEFINED; power_telemetry::GetInstance().LogTxPower(p); - ASSERT_NE(dummy_res.tx_power, - ldc.acl.link_details_map[handle].tx_power_level); + ASSERT_NE(dummy_res.tx_power, ldc.acl.link_details_map[handle].tx_power_level); } TEST_F(PowerTelemetryTest, test_LogAclLinkDetails) { reset(); - LogDataContainer& ldc = - power_telemetry::GetInstance().pimpl_->GetCurrentLogDataContainer(); + LogDataContainer& ldc = power_telemetry::GetInstance().pimpl_->GetCurrentLogDataContainer(); // Failed Case. Shouldn't crash if first invoke function with false isConnected = false; - power_telemetry::GetInstance().LogLinkDetails(handle, bdaddr, isConnected, - true); + power_telemetry::GetInstance().LogLinkDetails(handle, bdaddr, isConnected, true); ASSERT_EQ(0, (int)ldc.acl.link_details_list.size()); // Successful case isConnected = true; - power_telemetry::GetInstance().LogLinkDetails(handle, bdaddr, isConnected, - true); + power_telemetry::GetInstance().LogLinkDetails(handle, bdaddr, isConnected, true); ASSERT_EQ(1, (int)ldc.acl.link_details_map.count(handle)); ASSERT_EQ(0, (int)ldc.acl.link_details_list.size()); ASSERT_EQ(1, (int)ldc.sniff_activity_map.count(handle)); isConnected = false; - power_telemetry::GetInstance().LogLinkDetails(handle, bdaddr, isConnected, - true); + power_telemetry::GetInstance().LogLinkDetails(handle, bdaddr, isConnected, true); ASSERT_EQ(0, (int)ldc.acl.link_details_map.count(handle)); ASSERT_EQ(1, (int)ldc.acl.link_details_list.size()); } TEST_F(PowerTelemetryTest, test_LogScoLinkDetails) { reset(); - LogDataContainer& ldc = - power_telemetry::GetInstance().pimpl_->GetCurrentLogDataContainer(); + LogDataContainer& ldc = power_telemetry::GetInstance().pimpl_->GetCurrentLogDataContainer(); // Failed Case. Shouldn't crash if first invoke function with false isConnected = false; - power_telemetry::GetInstance().LogLinkDetails(handle, bdaddr, isConnected, - false); + power_telemetry::GetInstance().LogLinkDetails(handle, bdaddr, isConnected, false); ASSERT_EQ(0, (int)ldc.sco.link_details_list.size()); // Successful case isConnected = true; - power_telemetry::GetInstance().LogLinkDetails(handle, bdaddr, isConnected, - false); + power_telemetry::GetInstance().LogLinkDetails(handle, bdaddr, isConnected, false); ASSERT_EQ(1, (int)ldc.sco.link_details_map.count(handle)); ASSERT_EQ(0, (int)ldc.sco.link_details_list.size()); isConnected = false; - power_telemetry::GetInstance().LogLinkDetails(handle, bdaddr, isConnected, - false); + power_telemetry::GetInstance().LogLinkDetails(handle, bdaddr, isConnected, false); ASSERT_EQ(0, (int)ldc.sco.link_details_map.count(handle)); ASSERT_EQ(1, (int)ldc.sco.link_details_list.size()); } @@ -189,8 +175,7 @@ TEST_F(PowerTelemetryTest, test_LogHciCmdEvtDetails) { TEST_F(PowerTelemetryTest, test_LogSniffActivity) { reset(); - LogDataContainer& ldc = - power_telemetry::GetInstance().pimpl_->GetCurrentLogDataContainer(); + LogDataContainer& ldc = power_telemetry::GetInstance().pimpl_->GetCurrentLogDataContainer(); power_telemetry::GetInstance().LogSniffStarted(handle, bdaddr); ASSERT_EQ(1, (int)ldc.sniff_activity_map[handle].sniff_count); @@ -231,24 +216,20 @@ TEST_F(PowerTelemetryTest, test_LogAclPktDetails) { TEST_F(PowerTelemetryTest, test_LogChannelConnected) { reset(); - LogDataContainer& ldc = - power_telemetry::GetInstance().pimpl_->GetCurrentLogDataContainer(); + LogDataContainer& ldc = power_telemetry::GetInstance().pimpl_->GetCurrentLogDataContainer(); - power_telemetry::GetInstance().LogChannelConnected(BT_PSM_RFCOMM, 0, 0, - bdaddr); + power_telemetry::GetInstance().LogChannelConnected(BT_PSM_RFCOMM, 0, 0, bdaddr); ASSERT_EQ(1, (int)ldc.channel_map[bdaddr].size()); ASSERT_EQ(State::kConnected, ldc.channel_map[bdaddr].back().state); - power_telemetry::GetInstance().LogChannelConnected(BT_PSM_RFCOMM, 0, 0, - bdaddr); + power_telemetry::GetInstance().LogChannelConnected(BT_PSM_RFCOMM, 0, 0, bdaddr); ASSERT_EQ(2, (int)ldc.channel_map[bdaddr].size()); ASSERT_EQ(State::kConnected, ldc.channel_map[bdaddr].back().state); } TEST_F(PowerTelemetryTest, test_LogChannelDisconnected) { reset(); - LogDataContainer& ldc = - power_telemetry::GetInstance().pimpl_->GetCurrentLogDataContainer(); + LogDataContainer& ldc = power_telemetry::GetInstance().pimpl_->GetCurrentLogDataContainer(); power_telemetry::GetInstance().LogChannelConnected(0, 0, 0, bdaddr); power_telemetry::GetInstance().LogChannelDisconnected(0, 0, 0, bdaddr); @@ -285,14 +266,12 @@ TEST_F(PowerTelemetryTest, test_feature_flag) { // init data isConnected = true; - LogDataContainer& ldc = - power_telemetry::GetInstance().pimpl_->GetCurrentLogDataContainer(); + LogDataContainer& ldc = power_telemetry::GetInstance().pimpl_->GetCurrentLogDataContainer(); tBTM_TX_POWER_RESULT dummy_res; dummy_res.rem_bda = bdaddr; dummy_res.status = BTM_SUCCESS; void* p = &dummy_res; - power_telemetry::GetInstance().LogLinkDetails(handle, bdaddr, isConnected, - true); + power_telemetry::GetInstance().LogLinkDetails(handle, bdaddr, isConnected, true); // Set feature flag to false // All function shouldn't work if flag is false @@ -334,13 +313,11 @@ TEST_F(PowerTelemetryTest, test_feature_flag) { power_telemetry::GetInstance().LogHciEvtDetail(); ASSERT_EQ(0, (int)power_telemetry::GetInstance().pimpl_->event.count_); - power_telemetry::GetInstance().LogLinkDetails(handle, bdaddr, isConnected, - false); + power_telemetry::GetInstance().LogLinkDetails(handle, bdaddr, isConnected, false); ASSERT_EQ(0, (int)ldc.sco.link_details_map.count(handle)); // Set to 1 because of fake data - power_telemetry::GetInstance().LogLinkDetails(handle, bdaddr, isConnected, - true); + power_telemetry::GetInstance().LogLinkDetails(handle, bdaddr, isConnected, true); ASSERT_EQ(1, (int)ldc.acl.link_details_map.count(handle)); dummy_res.tx_power = 100; diff --git a/system/osi/test/test_stubs.h b/system/osi/test/test_stubs.h index 77c89ce4796..80e35bb1479 100644 --- a/system/osi/test/test_stubs.h +++ b/system/osi/test/test_stubs.h @@ -30,19 +30,18 @@ name##_callcount++; // Expect a certain number of calls to the specified stub function -#define EXPECT_CALL_COUNT(name, count) \ - EXPECT_EQ((count), (name##_callcount)) \ - << "expected " #name " to be called " #count " times" +#define EXPECT_CALL_COUNT(name, count) \ + EXPECT_EQ((count), (name##_callcount)) << "expected " #name " to be called " #count " times" -// Reset the call count for the specificed stub function +// Reset the call count for the specified stub function #define RESET_CALL_COUNT(name) ((name##_callcount) = 0) // Use this in a stub function to catch unexpected calls. // Prints out a nice message including the call count, the // stub function name, and the mode index (sadly no mode name) -#define UNEXPECTED_CALL \ - EXPECT_TRUE(false) << "unexpected call " << _local_callcount << " to " \ - << __func__ << " during mode " << (int)_current_mode +#define UNEXPECTED_CALL \ + ADD_FAILURE() << "unexpected call " << _local_callcount << " to " << __func__ << " during mode " \ + << (int)_current_mode #define MODE_IS(mode) (_current_mode == (mode)) @@ -51,8 +50,7 @@ #define OVERLOAD_SELECT(NAME, NUM) OVERLOAD_CAT(NAME##_, NUM) #define OVERLOAD_GET_COUNT(_1, _2, _3, _4, _5, _6, COUNT, ...) COUNT #define OVERLOAD_VA_SIZE(...) OVERLOAD_GET_COUNT(__VA_ARGS__, 6, 5, 4, 3, 2, 1) -#define OVERLOAD_OF(NAME, ...) \ - OVERLOAD_SELECT(NAME, OVERLOAD_VA_SIZE(__VA_ARGS__))(__VA_ARGS__) +#define OVERLOAD_OF(NAME, ...) OVERLOAD_SELECT(NAME, OVERLOAD_VA_SIZE(__VA_ARGS__))(__VA_ARGS__) // Use this to branch stub function execution to a specific mode or modes. // Treat it like an if statement. For example: @@ -63,16 +61,14 @@ #define DURING_1(mode0) if (MODE_IS(mode0)) #define DURING_2(mode0, mode1) if (MODE_IS(mode0) || MODE_IS(mode1)) -#define DURING_3(mode0, mode1, mode2) \ - if (MODE_IS(mode0) || MODE_IS(mode1) || MODE_IS(mode2)) +#define DURING_3(mode0, mode1, mode2) if (MODE_IS(mode0) || MODE_IS(mode1) || MODE_IS(mode2)) #define DURING_4(mode0, mode1, mode2, mode3) \ if (MODE_IS(mode0) || MODE_IS(mode1) || MODE_IS(mode2) || MODE_IS(mode3)) -#define DURING_5(mode0, mode1, mode2, mode3, mode4) \ - if (MODE_IS(mode0) || MODE_IS(mode1) || MODE_IS(mode2) || MODE_IS(mode3) || \ - MODE_IS(mode4)) -#define DURING_6(mode0, mode1, mode2, mode3, mode4, mode5) \ - if (MODE_IS(mode0) || MODE_IS(mode1) || MODE_IS(mode2) || MODE_IS(mode3) || \ - MODE_IS(mode4) || MODE_IS(mode5)) +#define DURING_5(mode0, mode1, mode2, mode3, mode4) \ + if (MODE_IS(mode0) || MODE_IS(mode1) || MODE_IS(mode2) || MODE_IS(mode3) || MODE_IS(mode4)) +#define DURING_6(mode0, mode1, mode2, mode3, mode4, mode5) \ + if (MODE_IS(mode0) || MODE_IS(mode1) || MODE_IS(mode2) || MODE_IS(mode3) || MODE_IS(mode4) || \ + MODE_IS(mode5)) // Use this to branch stub function exeuction to a specific call // count index (zero based). Treat it like an if statement. diff --git a/system/osi/test/wakelock_test.cc b/system/osi/test/wakelock_test.cc index d767a98d13d..2596553d66d 100644 --- a/system/osi/test/wakelock_test.cc +++ b/system/osi/test/wakelock_test.cc @@ -36,11 +36,11 @@ static int release_wake_lock_cb(const char* lock_name) { return BT_STATUS_SUCCESS; } -static bt_os_callouts_t bt_wakelock_callouts = { - sizeof(bt_os_callouts_t), acquire_wake_lock_cb, release_wake_lock_cb}; +static bt_os_callouts_t bt_wakelock_callouts = {sizeof(bt_os_callouts_t), acquire_wake_lock_cb, + release_wake_lock_cb}; class WakelockTest : public ::testing::Test { - protected: +protected: void SetUp() override { // TODO (jamuraa): maybe use base::CreateNewTempDirectory instead? #ifdef __ANDROID__ @@ -95,11 +95,9 @@ class WakelockTest : public ::testing::Test { EXPECT_GE(lock_stat.st_size, unlock_stat.st_size); - void* lock_file = - mmap(nullptr, lock_stat.st_size, PROT_READ, MAP_PRIVATE, lock_fd, 0); + void* lock_file = mmap(nullptr, lock_stat.st_size, PROT_READ, MAP_PRIVATE, lock_fd, 0); - void* unlock_file = mmap(nullptr, unlock_stat.st_size, PROT_READ, - MAP_PRIVATE, unlock_fd, 0); + void* unlock_file = mmap(nullptr, unlock_stat.st_size, PROT_READ, MAP_PRIVATE, unlock_fd, 0); if (memcmp(lock_file, unlock_file, unlock_stat.st_size) == 0) { acquired = lock_stat.st_size > unlock_stat.st_size; diff --git a/system/packet/avrcp/avrcp_browse_packet.cc b/system/packet/avrcp/avrcp_browse_packet.cc index 14fdff4c5bb..d66b4ea1855 100644 --- a/system/packet/avrcp/avrcp_browse_packet.cc +++ b/system/packet/avrcp/avrcp_browse_packet.cc @@ -22,21 +22,18 @@ namespace bluetooth { namespace avrcp { std::unique_ptr BrowsePacketBuilder::MakeBuilder( - BrowsePdu pdu, std::unique_ptr<::bluetooth::PacketBuilder> payload) { + BrowsePdu pdu, std::unique_ptr<::bluetooth::PacketBuilder> payload) { std::unique_ptr builder = - std::unique_ptr(new BrowsePacketBuilder(pdu)); + std::unique_ptr(new BrowsePacketBuilder(pdu)); builder->payload_ = std::move(payload); return builder; } -size_t BrowsePacketBuilder::size() const { - return BrowsePacket::kMinSize() + payload_->size(); -} +size_t BrowsePacketBuilder::size() const { return BrowsePacket::kMinSize() + payload_->size(); } -bool BrowsePacketBuilder::Serialize( - const std::shared_ptr<::bluetooth::Packet>& pkt) { +bool BrowsePacketBuilder::Serialize(const std::shared_ptr<::bluetooth::Packet>& pkt) { ReserveSpace(pkt, size()); PushHeader(pkt, payload_->size()); @@ -44,20 +41,17 @@ bool BrowsePacketBuilder::Serialize( return payload_->Serialize(pkt); } -void BrowsePacketBuilder::PushHeader( - const std::shared_ptr<::bluetooth::Packet>& pkt, uint16_t length) { +void BrowsePacketBuilder::PushHeader(const std::shared_ptr<::bluetooth::Packet>& pkt, + uint16_t length) { AddPayloadOctets1(pkt, (uint8_t)pdu_); AddPayloadOctets2(pkt, base::ByteSwap(length)); } -std::shared_ptr BrowsePacket::Parse( - std::shared_ptr<::bluetooth::Packet> pkt) { +std::shared_ptr BrowsePacket::Parse(std::shared_ptr<::bluetooth::Packet> pkt) { return std::shared_ptr(new BrowsePacket(pkt)); } -BrowsePdu BrowsePacket::GetPdu() const { - return static_cast(*begin()); -} +BrowsePdu BrowsePacket::GetPdu() const { return static_cast(*begin()); } uint16_t BrowsePacket::GetLength() const { auto it = begin() + static_cast(1); @@ -65,7 +59,9 @@ uint16_t BrowsePacket::GetLength() const { } bool BrowsePacket::IsValid() const { - if (size() < kMinSize()) return false; + if (size() < kMinSize()) { + return false; + } return size() == GetLength() + kMinSize(); } diff --git a/system/packet/avrcp/avrcp_browse_packet.h b/system/packet/avrcp/avrcp_browse_packet.h index 113b0e9f34e..6a9270ae11e 100644 --- a/system/packet/avrcp/avrcp_browse_packet.h +++ b/system/packet/avrcp/avrcp_browse_packet.h @@ -28,35 +28,32 @@ namespace bluetooth { namespace avrcp { class BrowsePacketBuilder : public ::bluetooth::PacketBuilder { - public: +public: virtual ~BrowsePacketBuilder() = default; static std::unique_ptr MakeBuilder( - BrowsePdu pdu, std::unique_ptr<::bluetooth::PacketBuilder> payload); + BrowsePdu pdu, std::unique_ptr<::bluetooth::PacketBuilder> payload); virtual size_t size() const override; - virtual bool Serialize( - const std::shared_ptr<::bluetooth::Packet>& pkt) override; + virtual bool Serialize(const std::shared_ptr<::bluetooth::Packet>& pkt) override; - protected: +protected: BrowsePdu pdu_; std::unique_ptr<::bluetooth::PacketBuilder> payload_; - void PushHeader(const std::shared_ptr<::bluetooth::Packet>& pkt, - uint16_t length); + void PushHeader(const std::shared_ptr<::bluetooth::Packet>& pkt, uint16_t length); - BrowsePacketBuilder(BrowsePdu pdu) : pdu_(pdu){}; + BrowsePacketBuilder(BrowsePdu pdu) : pdu_(pdu) {} }; class BrowsePacket : public ::bluetooth::Packet { - public: +public: BrowsePacket(const BrowsePacket&) = delete; BrowsePacket& operator=(const BrowsePacket&) = delete; virtual ~BrowsePacket() = default; - static std::shared_ptr Parse( - std::shared_ptr<::bluetooth::Packet> pkt); + static std::shared_ptr Parse(std::shared_ptr<::bluetooth::Packet> pkt); /** * Avrcp Browse Packet Layout @@ -72,10 +69,10 @@ class BrowsePacket : public ::bluetooth::Packet { virtual bool IsValid() const override; virtual std::string ToString() const override; - protected: +protected: using ::bluetooth::Packet::Packet; - private: +private: virtual std::pair GetPayloadIndecies() const override; }; diff --git a/system/packet/avrcp/avrcp_packet.cc b/system/packet/avrcp/avrcp_packet.cc index 10526e07bd7..5254fbbf1c3 100644 --- a/system/packet/avrcp/avrcp_packet.cc +++ b/system/packet/avrcp/avrcp_packet.cc @@ -14,20 +14,20 @@ * limitations under the License. */ +#include "avrcp_packet.h" + #include #include #include -#include "avrcp_packet.h" - namespace bluetooth { namespace avrcp { std::unique_ptr PacketBuilder::MakeBuilder( - CType type, uint8_t subunit_type, uint8_t subunit_id, Opcode opcode, - std::unique_ptr<::bluetooth::PacketBuilder> payload) { - std::unique_ptr builder = std::unique_ptr( - new PacketBuilder(type, subunit_type, subunit_id, opcode)); + CType type, uint8_t subunit_type, uint8_t subunit_id, Opcode opcode, + std::unique_ptr<::bluetooth::PacketBuilder> payload) { + std::unique_ptr builder = + std::unique_ptr(new PacketBuilder(type, subunit_type, subunit_id, opcode)); builder->payload_ = std::move(payload); @@ -49,15 +49,14 @@ bool PacketBuilder::Serialize(const std::shared_ptr<::bluetooth::Packet>& pkt) { return payload_->Serialize(pkt); } -void PacketBuilder::PushHeader( - const std::shared_ptr<::bluetooth::Packet>& pkt) { +void PacketBuilder::PushHeader(const std::shared_ptr<::bluetooth::Packet>& pkt) { AddPayloadOctets1(pkt, static_cast(c_type_)); AddPayloadOctets1(pkt, (subunit_type_ << 3) | subunit_id_); AddPayloadOctets1(pkt, static_cast(opcode_)); } -bool PacketBuilder::PushCompanyId( - const std::shared_ptr<::bluetooth::Packet>& pkt, uint32_t company_id) { +bool PacketBuilder::PushCompanyId(const std::shared_ptr<::bluetooth::Packet>& pkt, + uint32_t company_id) { company_id = base::ByteSwap(company_id); for (int i = 0; i < 3; i++) { company_id >>= 8; @@ -67,8 +66,7 @@ bool PacketBuilder::PushCompanyId( return true; } -std::shared_ptr Packet::Parse( - std::shared_ptr<::bluetooth::Packet> pkt) { +std::shared_ptr Packet::Parse(std::shared_ptr<::bluetooth::Packet> pkt) { return std::shared_ptr(new Packet(pkt)); } @@ -77,13 +75,9 @@ CType Packet::GetCType() const { return static_cast(value); } -uint8_t Packet::GetSubunitType() const { - return *(begin() + static_cast(1)) >> 3; -} +uint8_t Packet::GetSubunitType() const { return *(begin() + static_cast(1)) >> 3; } -uint8_t Packet::GetSubunitId() const { - return *(begin() + static_cast(1)) & 0b00000111; -} +uint8_t Packet::GetSubunitId() const { return *(begin() + static_cast(1)) & 0b00000111; } Opcode Packet::GetOpcode() const { auto value = *(begin() + static_cast(2)); diff --git a/system/packet/avrcp/avrcp_packet.h b/system/packet/avrcp/avrcp_packet.h index 8dd0099a8c3..017ad7d8b9c 100644 --- a/system/packet/avrcp/avrcp_packet.h +++ b/system/packet/avrcp/avrcp_packet.h @@ -28,18 +28,17 @@ namespace bluetooth { namespace avrcp { class PacketBuilder : public ::bluetooth::PacketBuilder { - public: +public: virtual ~PacketBuilder() = default; static std::unique_ptr MakeBuilder( - CType cType, uint8_t subunit_type, uint8_t subunit_id, Opcode opcode, - std::unique_ptr<::bluetooth::PacketBuilder> packet); + CType cType, uint8_t subunit_type, uint8_t subunit_id, Opcode opcode, + std::unique_ptr<::bluetooth::PacketBuilder> packet); virtual size_t size() const override; - virtual bool Serialize( - const std::shared_ptr<::bluetooth::Packet>& pkt) override; + virtual bool Serialize(const std::shared_ptr<::bluetooth::Packet>& pkt) override; - protected: +protected: CType c_type_; uint8_t subunit_type_ : 5; uint8_t subunit_id_ : 3; @@ -47,19 +46,14 @@ class PacketBuilder : public ::bluetooth::PacketBuilder { std::unique_ptr<::bluetooth::PacketBuilder> payload_; void PushHeader(const std::shared_ptr<::bluetooth::Packet>& pkt); - bool PushCompanyId(const std::shared_ptr<::bluetooth::Packet>& pkt, - uint32_t company_id); - - PacketBuilder(CType type, uint8_t subunit_type, uint8_t subunit_id, - Opcode opcode) - : c_type_(type), - subunit_type_(subunit_type), - subunit_id_(subunit_id), - opcode_(opcode){}; + bool PushCompanyId(const std::shared_ptr<::bluetooth::Packet>& pkt, uint32_t company_id); + + PacketBuilder(CType type, uint8_t subunit_type, uint8_t subunit_id, Opcode opcode) + : c_type_(type), subunit_type_(subunit_type), subunit_id_(subunit_id), opcode_(opcode) {} }; class Packet : public ::bluetooth::Packet { - public: +public: Packet(const Packet&) = delete; Packet& operator=(const Packet&) = delete; @@ -68,8 +62,7 @@ class Packet : public ::bluetooth::Packet { // TODO (apanicke): Right now we can use this to build an AvrcpPacket from // another packet type. In the future, we can remove this in favor of // getting an AVRCP Packet directly from an AVCTP Packet - static std::shared_ptr Parse( - std::shared_ptr<::bluetooth::Packet> pkt); + static std::shared_ptr Parse(std::shared_ptr<::bluetooth::Packet> pkt); /** * Avrcp Packet Layout @@ -79,7 +72,7 @@ class Packet : public ::bluetooth::Packet { * Opcode opcode_; * uint8_t[] payload_; */ - static constexpr size_t kMinSize() { return 3; }; + static constexpr size_t kMinSize() { return 3; } // Getter Functions CType GetCType() const; @@ -91,7 +84,7 @@ class Packet : public ::bluetooth::Packet { virtual bool IsValid() const override; virtual std::string ToString() const override; - protected: +protected: using ::bluetooth::Packet::Packet; static inline uint32_t PullCompanyId(Iterator it) { @@ -103,7 +96,7 @@ class Packet : public ::bluetooth::Packet { return value; } - private: +private: virtual std::pair GetPayloadIndecies() const override; }; diff --git a/system/packet/avrcp/avrcp_reject_packet.cc b/system/packet/avrcp/avrcp_reject_packet.cc index d4ad7ad51e1..91ea3cb3fe8 100644 --- a/system/packet/avrcp/avrcp_reject_packet.cc +++ b/system/packet/avrcp/avrcp_reject_packet.cc @@ -19,10 +19,9 @@ namespace bluetooth { namespace avrcp { -std::unique_ptr RejectBuilder::MakeBuilder(CommandPdu pdu, - Status reason) { +std::unique_ptr RejectBuilder::MakeBuilder(CommandPdu pdu, Status reason) { std::unique_ptr builder = - std::unique_ptr(new RejectBuilder(pdu, reason)); + std::unique_ptr(new RejectBuilder(pdu, reason)); return builder; } diff --git a/system/packet/avrcp/avrcp_reject_packet.h b/system/packet/avrcp/avrcp_reject_packet.h index 9b7f3a995de..b735edb6866 100644 --- a/system/packet/avrcp/avrcp_reject_packet.h +++ b/system/packet/avrcp/avrcp_reject_packet.h @@ -22,22 +22,19 @@ namespace bluetooth { namespace avrcp { class RejectBuilder : public VendorPacketBuilder { - public: +public: virtual ~RejectBuilder() = default; - static std::unique_ptr MakeBuilder(CommandPdu pdu, - Status reason); + static std::unique_ptr MakeBuilder(CommandPdu pdu, Status reason); virtual size_t size() const override; - virtual bool Serialize( - const std::shared_ptr<::bluetooth::Packet>& pkt) override; + virtual bool Serialize(const std::shared_ptr<::bluetooth::Packet>& pkt) override; - protected: +protected: Status reason_; RejectBuilder(CommandPdu pdu, Status reason) - : VendorPacketBuilder(CType::REJECTED, pdu, PacketType::SINGLE), - reason_(reason){}; + : VendorPacketBuilder(CType::REJECTED, pdu, PacketType::SINGLE), reason_(reason) {} }; } // namespace avrcp diff --git a/system/packet/avrcp/capabilities_packet.cc b/system/packet/avrcp/capabilities_packet.cc index 92cad147398..e150fba90ba 100644 --- a/system/packet/avrcp/capabilities_packet.cc +++ b/system/packet/avrcp/capabilities_packet.cc @@ -23,20 +23,17 @@ namespace bluetooth { namespace avrcp { -std::unique_ptr -GetCapabilitiesRequestBuilder::MakeBuilder(Capability capability) { +std::unique_ptr GetCapabilitiesRequestBuilder::MakeBuilder( + Capability capability) { std::unique_ptr builder( - new GetCapabilitiesRequestBuilder(capability)); + new GetCapabilitiesRequestBuilder(capability)); return builder; } -size_t GetCapabilitiesRequestBuilder::size() const { - return GetCapabilitiesRequest::kMinSize(); -} +size_t GetCapabilitiesRequestBuilder::size() const { return GetCapabilitiesRequest::kMinSize(); } -bool GetCapabilitiesRequestBuilder::Serialize( - const std::shared_ptr<::bluetooth::Packet>& pkt) { +bool GetCapabilitiesRequestBuilder::Serialize(const std::shared_ptr<::bluetooth::Packet>& pkt) { ReserveSpace(pkt, size()); // Push the standard avrcp headers @@ -55,8 +52,10 @@ Capability GetCapabilitiesRequest::GetCapabilityRequested() const { } bool GetCapabilitiesRequest::IsValid() const { - if (!VendorPacket::IsValid()) return false; - return (size() == VendorPacket::kMinSize() + 1); + if (!VendorPacket::IsValid()) { + return false; + } + return size() == VendorPacket::kMinSize() + 1; } std::string GetCapabilitiesRequest::ToString() const { @@ -75,10 +74,9 @@ std::string GetCapabilitiesRequest::ToString() const { } std::unique_ptr -GetCapabilitiesResponseBuilder::MakeCompanyIdBuilder( - uint32_t company_id_element) { +GetCapabilitiesResponseBuilder::MakeCompanyIdBuilder(uint32_t company_id_element) { std::unique_ptr builder( - new GetCapabilitiesResponseBuilder(Capability::COMPANY_ID)); + new GetCapabilitiesResponseBuilder(Capability::COMPANY_ID)); company_id_element &= 0x00FFFFFF; builder->elements_.insert(company_id_element); @@ -89,19 +87,17 @@ GetCapabilitiesResponseBuilder::MakeCompanyIdBuilder( std::unique_ptr GetCapabilitiesResponseBuilder::MakeEventsSupportedBuilder(Event event) { std::unique_ptr builder( - new GetCapabilitiesResponseBuilder(Capability::EVENTS_SUPPORTED)); + new GetCapabilitiesResponseBuilder(Capability::EVENTS_SUPPORTED)); builder->elements_.insert(static_cast(event)); return builder; } -GetCapabilitiesResponseBuilder* GetCapabilitiesResponseBuilder::AddCompanyId( - uint32_t company_id) { +GetCapabilitiesResponseBuilder* GetCapabilitiesResponseBuilder::AddCompanyId(uint32_t company_id) { log::assert_that(capability_ == Capability::COMPANY_ID, "assert failed: capability_ == Capability::COMPANY_ID"); - log::assert_that(elements_.size() < size_t(0xFF), - "maximum capability count reached"); + log::assert_that(elements_.size() < size_t(0xFF), "maximum capability count reached"); company_id &= 0x00FFFFFF; elements_.insert(company_id); @@ -109,13 +105,10 @@ GetCapabilitiesResponseBuilder* GetCapabilitiesResponseBuilder::AddCompanyId( return this; } -GetCapabilitiesResponseBuilder* GetCapabilitiesResponseBuilder::AddEvent( - Event event) { - log::assert_that( - capability_ == Capability::EVENTS_SUPPORTED, - "assert failed: capability_ == Capability::EVENTS_SUPPORTED"); - log::assert_that(elements_.size() < size_t(0xFF), - "maximum capability count reached"); +GetCapabilitiesResponseBuilder* GetCapabilitiesResponseBuilder::AddEvent(Event event) { + log::assert_that(capability_ == Capability::EVENTS_SUPPORTED, + "assert failed: capability_ == Capability::EVENTS_SUPPORTED"); + log::assert_that(elements_.size() < size_t(0xFF), "maximum capability count reached"); elements_.insert(static_cast(event)); @@ -127,12 +120,10 @@ size_t GetCapabilitiesResponseBuilder::size() const { size_t capability_count = elements_.size(); size_t capability_size = capability_ == Capability::COMPANY_ID ? 3 : 1; - return GetCapabilitiesResponse::kMinSize() + - (capability_count * capability_size); + return GetCapabilitiesResponse::kMinSize() + (capability_count * capability_size); } -bool GetCapabilitiesResponseBuilder::Serialize( - const std::shared_ptr<::bluetooth::Packet>& pkt) { +bool GetCapabilitiesResponseBuilder::Serialize(const std::shared_ptr<::bluetooth::Packet>& pkt) { ReserveSpace(pkt, size()); // Push the standard avrcp headers @@ -146,10 +137,11 @@ bool GetCapabilitiesResponseBuilder::Serialize( AddPayloadOctets1(pkt, static_cast(capability_)); AddPayloadOctets1(pkt, elements_.size()); for (auto it = elements_.begin(); it != elements_.end(); it++) { - if (capability_ == Capability::COMPANY_ID) + if (capability_ == Capability::COMPANY_ID) { PushCompanyId(pkt, *it); - else + } else { AddPayloadOctets1(pkt, *it); + } } return true; diff --git a/system/packet/avrcp/capabilities_packet.h b/system/packet/avrcp/capabilities_packet.h index 3a4607f0b20..9ef34dbf0cd 100644 --- a/system/packet/avrcp/capabilities_packet.h +++ b/system/packet/avrcp/capabilities_packet.h @@ -24,27 +24,24 @@ namespace bluetooth { namespace avrcp { class GetCapabilitiesRequestBuilder : public VendorPacketBuilder { - public: +public: virtual ~GetCapabilitiesRequestBuilder() = default; - static std::unique_ptr MakeBuilder( - Capability capability); + static std::unique_ptr MakeBuilder(Capability capability); virtual size_t size() const override; - virtual bool Serialize( - const std::shared_ptr<::bluetooth::Packet>& pkt) override; + virtual bool Serialize(const std::shared_ptr<::bluetooth::Packet>& pkt) override; - protected: +protected: Capability capability_; GetCapabilitiesRequestBuilder(Capability capability) - : VendorPacketBuilder(CType::STATUS, CommandPdu::GET_CAPABILITIES, - PacketType::SINGLE), - capability_(capability){}; + : VendorPacketBuilder(CType::STATUS, CommandPdu::GET_CAPABILITIES, PacketType::SINGLE), + capability_(capability) {} }; class GetCapabilitiesRequest : public VendorPacket { - public: +public: virtual ~GetCapabilitiesRequest() = default; /** @@ -62,7 +59,7 @@ class GetCapabilitiesRequest : public VendorPacket { * GetCapabilitiesRequestPacket: * uint8_t capability_requested: */ - static constexpr size_t kMinSize() { return VendorPacket::kMinSize() + 1; }; + static constexpr size_t kMinSize() { return VendorPacket::kMinSize() + 1; } // Getter Functions Capability GetCapabilityRequested() const; @@ -71,39 +68,36 @@ class GetCapabilitiesRequest : public VendorPacket { virtual bool IsValid() const override; virtual std::string ToString() const override; - protected: +protected: using VendorPacket::VendorPacket; }; class GetCapabilitiesResponseBuilder : public VendorPacketBuilder { - public: +public: virtual ~GetCapabilitiesResponseBuilder() = default; static std::unique_ptr MakeCompanyIdBuilder( - uint32_t company_id_element); + uint32_t company_id_element); - static std::unique_ptr - MakeEventsSupportedBuilder(Event event); + static std::unique_ptr MakeEventsSupportedBuilder(Event event); GetCapabilitiesResponseBuilder* AddCompanyId(uint32_t company_id); GetCapabilitiesResponseBuilder* AddEvent(Event event); virtual size_t size() const override; - virtual bool Serialize( - const std::shared_ptr<::bluetooth::Packet>& pkt) override; + virtual bool Serialize(const std::shared_ptr<::bluetooth::Packet>& pkt) override; - private: +private: Capability capability_; std::set elements_; GetCapabilitiesResponseBuilder(Capability capability) - : VendorPacketBuilder(CType::STABLE, CommandPdu::GET_CAPABILITIES, - PacketType::SINGLE), - capability_(capability){}; + : VendorPacketBuilder(CType::STABLE, CommandPdu::GET_CAPABILITIES, PacketType::SINGLE), + capability_(capability) {} }; class GetCapabilitiesResponse : public VendorPacket { - public: +public: /** * Get Capabilities Response Packet Layout * AvrcpPacket: @@ -124,7 +118,7 @@ class GetCapabilitiesResponse : public VendorPacket { * uint8_t company_id[3]; * } capability_array[]; */ - static constexpr size_t kMinSize() { return VendorPacket::kMinSize() + 2; }; + static constexpr size_t kMinSize() { return VendorPacket::kMinSize() + 2; } // TODO: Implement these for AVRCP Controller // virtual uint8_t GetCapabilityReturned() const; diff --git a/system/packet/avrcp/change_path.cc b/system/packet/avrcp/change_path.cc index b5f9ab4acb4..afb42ad2aeb 100644 --- a/system/packet/avrcp/change_path.cc +++ b/system/packet/avrcp/change_path.cc @@ -19,11 +19,10 @@ namespace bluetooth { namespace avrcp { -std::unique_ptr -ChangePathResponseBuilder::MakeBuilder(Status status, - uint32_t num_items_in_folder) { +std::unique_ptr ChangePathResponseBuilder::MakeBuilder( + Status status, uint32_t num_items_in_folder) { std::unique_ptr builder( - new ChangePathResponseBuilder(status, num_items_in_folder)); + new ChangePathResponseBuilder(status, num_items_in_folder)); return builder; } @@ -31,20 +30,23 @@ ChangePathResponseBuilder::MakeBuilder(Status status, size_t ChangePathResponseBuilder::size() const { size_t len = BrowsePacket::kMinSize(); len += 1; // Status - if (status_ != Status::NO_ERROR) return len; + if (status_ != Status::NO_ERROR) { + return len; + } len += 4; // Number of items in folder return len; } -bool ChangePathResponseBuilder::Serialize( - const std::shared_ptr<::bluetooth::Packet>& pkt) { +bool ChangePathResponseBuilder::Serialize(const std::shared_ptr<::bluetooth::Packet>& pkt) { ReserveSpace(pkt, size()); BrowsePacketBuilder::PushHeader(pkt, size() - BrowsePacket::kMinSize()); AddPayloadOctets1(pkt, (uint8_t)status_); - if (status_ != Status::NO_ERROR) return true; + if (status_ != Status::NO_ERROR) { + return true; + } AddPayloadOctets4(pkt, base::ByteSwap(num_items_in_folder_)); return true; @@ -66,7 +68,9 @@ uint64_t ChangePathRequest::GetUid() const { } bool ChangePathRequest::IsValid() const { - if (!BrowsePacket::IsValid()) return false; + if (!BrowsePacket::IsValid()) { + return false; + } // Change path request packets are always the same size return size() == kMinSize(); } @@ -85,19 +89,16 @@ std::string ChangePathRequest::ToString() const { } std::unique_ptr ChangePathRequestBuilder::MakeBuilder( - uint16_t uid_counter, Direction direction, uint64_t folder_uid) { + uint16_t uid_counter, Direction direction, uint64_t folder_uid) { std::unique_ptr builder( - new ChangePathRequestBuilder(uid_counter, direction, folder_uid)); + new ChangePathRequestBuilder(uid_counter, direction, folder_uid)); return builder; } -size_t ChangePathRequestBuilder::size() const { - return ChangePathRequest::kMinSize(); -} +size_t ChangePathRequestBuilder::size() const { return ChangePathRequest::kMinSize(); } -bool ChangePathRequestBuilder::Serialize( - const std::shared_ptr<::bluetooth::Packet>& pkt) { +bool ChangePathRequestBuilder::Serialize(const std::shared_ptr<::bluetooth::Packet>& pkt) { ReserveSpace(pkt, size()); BrowsePacketBuilder::PushHeader(pkt, size() - BrowsePacket::kMinSize()); diff --git a/system/packet/avrcp/change_path.h b/system/packet/avrcp/change_path.h index a033aa8271d..8be60b0ea75 100644 --- a/system/packet/avrcp/change_path.h +++ b/system/packet/avrcp/change_path.h @@ -22,17 +22,16 @@ namespace bluetooth { namespace avrcp { class ChangePathResponseBuilder : public BrowsePacketBuilder { - public: +public: virtual ~ChangePathResponseBuilder() = default; - static std::unique_ptr MakeBuilder( - Status status, uint32_t num_items_in_folder); + static std::unique_ptr MakeBuilder(Status status, + uint32_t num_items_in_folder); virtual size_t size() const override; - virtual bool Serialize( - const std::shared_ptr<::bluetooth::Packet>& pkt) override; + virtual bool Serialize(const std::shared_ptr<::bluetooth::Packet>& pkt) override; - private: +private: Status status_; uint32_t num_items_in_folder_; @@ -43,7 +42,7 @@ class ChangePathResponseBuilder : public BrowsePacketBuilder { }; class ChangePathRequest : public BrowsePacket { - public: +public: virtual ~ChangePathRequest() = default; /** @@ -65,28 +64,27 @@ class ChangePathRequest : public BrowsePacket { virtual bool IsValid() const override; virtual std::string ToString() const override; - protected: +protected: using BrowsePacket::BrowsePacket; }; class ChangePathRequestBuilder : public BrowsePacketBuilder { - public: +public: virtual ~ChangePathRequestBuilder() = default; - static std::unique_ptr MakeBuilder( - uint16_t uid_counter, Direction direction, uint64_t folder_uid); + static std::unique_ptr MakeBuilder(uint16_t uid_counter, + Direction direction, + uint64_t folder_uid); virtual size_t size() const override; - virtual bool Serialize( - const std::shared_ptr<::bluetooth::Packet>& pkt) override; + virtual bool Serialize(const std::shared_ptr<::bluetooth::Packet>& pkt) override; - private: - ChangePathRequestBuilder(uint16_t uid_counter, Direction direction, - uint64_t folder_uid) +private: + ChangePathRequestBuilder(uint16_t uid_counter, Direction direction, uint64_t folder_uid) : BrowsePacketBuilder(BrowsePdu::CHANGE_PATH), uid_counter_(uid_counter), direction_(direction), - folder_uid_(folder_uid){}; + folder_uid_(folder_uid) {} uint16_t uid_counter_; Direction direction_; diff --git a/system/packet/avrcp/general_reject_packet.cc b/system/packet/avrcp/general_reject_packet.cc index db3d31af157..a615bd7f499 100644 --- a/system/packet/avrcp/general_reject_packet.cc +++ b/system/packet/avrcp/general_reject_packet.cc @@ -21,17 +21,14 @@ namespace avrcp { std::unique_ptr GeneralRejectBuilder::MakeBuilder(Status reason) { std::unique_ptr builder = - std::unique_ptr(new GeneralRejectBuilder(reason)); + std::unique_ptr(new GeneralRejectBuilder(reason)); return builder; } -size_t GeneralRejectBuilder::size() const { - return BrowsePacket::kMinSize() + 1; -} +size_t GeneralRejectBuilder::size() const { return BrowsePacket::kMinSize() + 1; } -bool GeneralRejectBuilder::Serialize( - const std::shared_ptr<::bluetooth::Packet>& pkt) { +bool GeneralRejectBuilder::Serialize(const std::shared_ptr<::bluetooth::Packet>& pkt) { ReserveSpace(pkt, size()); BrowsePacketBuilder::PushHeader(pkt, size() - BrowsePacket::kMinSize()); diff --git a/system/packet/avrcp/general_reject_packet.h b/system/packet/avrcp/general_reject_packet.h index b3fb2fea63d..06bd7c9f9b3 100644 --- a/system/packet/avrcp/general_reject_packet.h +++ b/system/packet/avrcp/general_reject_packet.h @@ -22,19 +22,19 @@ namespace bluetooth { namespace avrcp { class GeneralRejectBuilder : public BrowsePacketBuilder { - public: +public: virtual ~GeneralRejectBuilder() = default; static std::unique_ptr MakeBuilder(Status reason); virtual size_t size() const override; - virtual bool Serialize( - const std::shared_ptr<::bluetooth::Packet>& pkt) override; + virtual bool Serialize(const std::shared_ptr<::bluetooth::Packet>& pkt) override; - protected: +protected: Status reason_; - GeneralRejectBuilder(Status reason) : BrowsePacketBuilder(BrowsePdu::GENERAL_REJECT), reason_(reason){}; + GeneralRejectBuilder(Status reason) + : BrowsePacketBuilder(BrowsePdu::GENERAL_REJECT), reason_(reason) {} }; } // namespace avrcp diff --git a/system/packet/avrcp/get_current_player_application_setting_value.cc b/system/packet/avrcp/get_current_player_application_setting_value.cc index 95fb46f5baf..1c48b8fc5e7 100644 --- a/system/packet/avrcp/get_current_player_application_setting_value.cc +++ b/system/packet/avrcp/get_current_player_application_setting_value.cc @@ -21,10 +21,10 @@ namespace avrcp { std::unique_ptr GetCurrentPlayerApplicationSettingValueResponseBuilder::MakeBuilder( - std::vector attributes, std::vector values) { - std::unique_ptr - builder(new GetCurrentPlayerApplicationSettingValueResponseBuilder( - std::move(attributes), std::move(values))); + std::vector attributes, std::vector values) { + std::unique_ptr builder( + new GetCurrentPlayerApplicationSettingValueResponseBuilder(std::move(attributes), + std::move(values))); return builder; } @@ -38,7 +38,7 @@ size_t GetCurrentPlayerApplicationSettingValueResponseBuilder::size() const { } bool GetCurrentPlayerApplicationSettingValueResponseBuilder::Serialize( - const std::shared_ptr<::bluetooth::Packet>& pkt) { + const std::shared_ptr<::bluetooth::Packet>& pkt) { ReserveSpace(pkt, size()); PacketBuilder::PushHeader(pkt); @@ -54,9 +54,7 @@ bool GetCurrentPlayerApplicationSettingValueResponseBuilder::Serialize( return true; } -uint8_t -GetCurrentPlayerApplicationSettingValueRequest::GetNumberOfRequestedAttributes() - const { +uint8_t GetCurrentPlayerApplicationSettingValueRequest::GetNumberOfRequestedAttributes() const { auto it = begin() + VendorPacket::kMinSize(); return *it; } @@ -73,8 +71,12 @@ GetCurrentPlayerApplicationSettingValueRequest::GetRequestedAttributes() const { } bool GetCurrentPlayerApplicationSettingValueRequest::IsValid() const { - if (!VendorPacket::IsValid()) return false; - if (size() < kMinSize()) return false; + if (!VendorPacket::IsValid()) { + return false; + } + if (size() < kMinSize()) { + return false; + } size_t num_attributes = GetNumberOfRequestedAttributes(); auto attr_start = begin() + VendorPacket::kMinSize() + static_cast(1); @@ -93,8 +95,7 @@ std::string GetCurrentPlayerApplicationSettingValueRequest::ToString() const { ss << " └ Command PDU = " << GetCommandPdu() << std::endl; ss << " └ PacketType = " << GetPacketType() << std::endl; ss << " └ Parameter Length = " << loghex(GetParameterLength()) << std::endl; - ss << " └ Num Attributes = " << loghex(GetNumberOfRequestedAttributes()) - << std::endl; + ss << " └ Num Attributes = " << loghex(GetNumberOfRequestedAttributes()) << std::endl; auto attr_list = GetRequestedAttributes(); ss << " └ Player Attribute List: Size: " << attr_list.size() << std::endl; diff --git a/system/packet/avrcp/get_current_player_application_setting_value.h b/system/packet/avrcp/get_current_player_application_setting_value.h index 510ffb96f8f..b00e1af2a1a 100644 --- a/system/packet/avrcp/get_current_player_application_setting_value.h +++ b/system/packet/avrcp/get_current_player_application_setting_value.h @@ -23,35 +23,30 @@ namespace bluetooth { namespace avrcp { -class GetCurrentPlayerApplicationSettingValueResponseBuilder - : public VendorPacketBuilder { - public: +class GetCurrentPlayerApplicationSettingValueResponseBuilder : public VendorPacketBuilder { +public: virtual ~GetCurrentPlayerApplicationSettingValueResponseBuilder() = default; - static std::unique_ptr - MakeBuilder(std::vector attributes, - std::vector values); + static std::unique_ptr MakeBuilder( + std::vector attributes, std::vector values); virtual size_t size() const override; - virtual bool Serialize( - const std::shared_ptr<::bluetooth::Packet>& pkt) override; + virtual bool Serialize(const std::shared_ptr<::bluetooth::Packet>& pkt) override; - protected: +protected: std::vector attributes_; std::vector values_; - GetCurrentPlayerApplicationSettingValueResponseBuilder( - std::vector attributes, std::vector values) - : VendorPacketBuilder( - CType::STABLE, - CommandPdu::GET_CURRENT_PLAYER_APPLICATION_SETTING_VALUE, - PacketType::SINGLE), + GetCurrentPlayerApplicationSettingValueResponseBuilder(std::vector attributes, + std::vector values) + : VendorPacketBuilder(CType::STABLE, CommandPdu::GET_CURRENT_PLAYER_APPLICATION_SETTING_VALUE, + PacketType::SINGLE), attributes_(std::move(attributes)), - values_(std::move(values)){}; + values_(std::move(values)) {} }; class GetCurrentPlayerApplicationSettingValueRequest : public VendorPacket { - public: +public: virtual ~GetCurrentPlayerApplicationSettingValueRequest() = default; /** @@ -70,9 +65,7 @@ class GetCurrentPlayerApplicationSettingValueRequest : public VendorPacket { * uint8_t number_of_attributes; * std::vector attributes; */ - static constexpr size_t kMinSize() { - return VendorPacket::kMinSize() + sizeof(uint8_t); - } + static constexpr size_t kMinSize() { return VendorPacket::kMinSize() + sizeof(uint8_t); } uint8_t GetNumberOfRequestedAttributes() const; std::vector GetRequestedAttributes() const; @@ -80,7 +73,7 @@ class GetCurrentPlayerApplicationSettingValueRequest : public VendorPacket { virtual bool IsValid() const override; virtual std::string ToString() const override; - protected: +protected: using VendorPacket::VendorPacket; }; diff --git a/system/packet/avrcp/get_element_attributes_packet.cc b/system/packet/avrcp/get_element_attributes_packet.cc index 4e90a455c08..59d3c815c37 100644 --- a/system/packet/avrcp/get_element_attributes_packet.cc +++ b/system/packet/avrcp/get_element_attributes_packet.cc @@ -33,8 +33,7 @@ uint8_t GetElementAttributesRequest::GetNumAttributes() const { return it.extract(); } -std::vector GetElementAttributesRequest::GetAttributesRequested() - const { +std::vector GetElementAttributesRequest::GetAttributesRequested() const { auto it = begin() + VendorPacket::kMinSize() + static_cast(8); size_t number_of_attributes = it.extract(); @@ -49,8 +48,12 @@ std::vector GetElementAttributesRequest::GetAttributesRequested() } bool GetElementAttributesRequest::IsValid() const { - if (!VendorPacket::IsValid()) return false; - if (size() < kMinSize()) return false; + if (!VendorPacket::IsValid()) { + return false; + } + if (size() < kMinSize()) { + return false; + } size_t num_attributes = GetNumAttributes(); auto attr_start = begin() + VendorPacket::kMinSize() + static_cast(9); @@ -87,13 +90,12 @@ std::string GetElementAttributesRequest::ToString() const { std::unique_ptr GetElementAttributesResponseBuilder::MakeBuilder(size_t mtu) { std::unique_ptr builder( - new GetElementAttributesResponseBuilder(mtu)); + new GetElementAttributesResponseBuilder(mtu)); return builder; } -size_t GetElementAttributesResponseBuilder::AddAttributeEntry( - AttributeEntry entry) { +size_t GetElementAttributesResponseBuilder::AddAttributeEntry(AttributeEntry entry) { log::assert_that(entries_.size() < size_t(0xFF), "attribute entry overflow"); size_t remaining_space = mtu_ - size(); @@ -109,8 +111,8 @@ size_t GetElementAttributesResponseBuilder::AddAttributeEntry( return entry.size(); } -size_t GetElementAttributesResponseBuilder::AddAttributeEntry( - Attribute attribute, const std::string& value) { +size_t GetElementAttributesResponseBuilder::AddAttributeEntry(Attribute attribute, + const std::string& value) { return AddAttributeEntry(AttributeEntry(attribute, value)); } @@ -125,7 +127,7 @@ size_t GetElementAttributesResponseBuilder::size() const { } bool GetElementAttributesResponseBuilder::Serialize( - const std::shared_ptr<::bluetooth::Packet>& pkt) { + const std::shared_ptr<::bluetooth::Packet>& pkt) { ReserveSpace(pkt, size()); PacketBuilder::PushHeader(pkt); diff --git a/system/packet/avrcp/get_element_attributes_packet.h b/system/packet/avrcp/get_element_attributes_packet.h index 9d816732528..c2b9a21346a 100644 --- a/system/packet/avrcp/get_element_attributes_packet.h +++ b/system/packet/avrcp/get_element_attributes_packet.h @@ -25,7 +25,7 @@ namespace bluetooth { namespace avrcp { class GetElementAttributesRequest : public VendorPacket { - public: +public: virtual ~GetElementAttributesRequest() = default; /** @@ -56,7 +56,7 @@ class GetElementAttributesRequest : public VendorPacket { virtual bool IsValid() const override; virtual std::string ToString() const override; - protected: +protected: using VendorPacket::VendorPacket; }; @@ -64,7 +64,7 @@ template class AttributesResponseBuilderTestUser; class GetElementAttributesResponseBuilder : public VendorPacketBuilder { - public: +public: virtual ~GetElementAttributesResponseBuilder() = default; using Builder = std::unique_ptr; static Builder MakeBuilder(size_t mtu); @@ -77,19 +77,16 @@ class GetElementAttributesResponseBuilder : public VendorPacketBuilder { static constexpr size_t kHeaderSize() { return VendorPacket::kMinSize() + 1; } virtual size_t size() const override; - virtual bool Serialize( - const std::shared_ptr<::bluetooth::Packet>& pkt) override; + virtual bool Serialize(const std::shared_ptr<::bluetooth::Packet>& pkt) override; - private: +private: std::set entries_; size_t mtu_; - friend class AttributesResponseBuilderTestUser< - GetElementAttributesResponseBuilder>; + friend class AttributesResponseBuilderTestUser; GetElementAttributesResponseBuilder(size_t mtu) - : VendorPacketBuilder(CType::STABLE, CommandPdu::GET_ELEMENT_ATTRIBUTES, - PacketType::SINGLE), - mtu_(mtu){}; + : VendorPacketBuilder(CType::STABLE, CommandPdu::GET_ELEMENT_ATTRIBUTES, PacketType::SINGLE), + mtu_(mtu) {} }; } // namespace avrcp diff --git a/system/packet/avrcp/get_folder_items.cc b/system/packet/avrcp/get_folder_items.cc index b8081536f2c..01d9af694eb 100644 --- a/system/packet/avrcp/get_folder_items.cc +++ b/system/packet/avrcp/get_folder_items.cc @@ -21,34 +21,26 @@ namespace bluetooth { namespace avrcp { -std::unique_ptr -GetFolderItemsResponseBuilder::MakePlayerListBuilder(Status status, - uint16_t uid_counter, - size_t mtu) { +std::unique_ptr GetFolderItemsResponseBuilder::MakePlayerListBuilder( + Status status, uint16_t uid_counter, size_t mtu) { std::unique_ptr builder( - new GetFolderItemsResponseBuilder(Scope::MEDIA_PLAYER_LIST, status, - uid_counter, mtu)); + new GetFolderItemsResponseBuilder(Scope::MEDIA_PLAYER_LIST, status, uid_counter, mtu)); return builder; } -std::unique_ptr -GetFolderItemsResponseBuilder::MakeVFSBuilder(Status status, - uint16_t uid_counter, - size_t mtu) { +std::unique_ptr GetFolderItemsResponseBuilder::MakeVFSBuilder( + Status status, uint16_t uid_counter, size_t mtu) { std::unique_ptr builder( - new GetFolderItemsResponseBuilder(Scope::VFS, status, uid_counter, mtu)); + new GetFolderItemsResponseBuilder(Scope::VFS, status, uid_counter, mtu)); return builder; } -std::unique_ptr -GetFolderItemsResponseBuilder::MakeNowPlayingBuilder(Status status, - uint16_t uid_counter, - size_t mtu) { +std::unique_ptr GetFolderItemsResponseBuilder::MakeNowPlayingBuilder( + Status status, uint16_t uid_counter, size_t mtu) { std::unique_ptr builder( - new GetFolderItemsResponseBuilder(Scope::NOW_PLAYING, status, uid_counter, - mtu)); + new GetFolderItemsResponseBuilder(Scope::NOW_PLAYING, status, uid_counter, mtu)); return builder; } @@ -59,7 +51,9 @@ size_t GetFolderItemsResponseBuilder::size() const { // There is nothing other than the status in the packet if the status isn't // NO_ERROR - if (status_ != Status::NO_ERROR || items_.size() == 0) return len; + if (status_ != Status::NO_ERROR || items_.size() == 0) { + return len; + } len += 2; // UID Counter len += 2; // Number of Items; @@ -70,8 +64,7 @@ size_t GetFolderItemsResponseBuilder::size() const { return len; } -bool GetFolderItemsResponseBuilder::Serialize( - const std::shared_ptr<::bluetooth::Packet>& pkt) { +bool GetFolderItemsResponseBuilder::Serialize(const std::shared_ptr<::bluetooth::Packet>& pkt) { ReserveSpace(pkt, size()); BrowsePacketBuilder::PushHeader(pkt, size() - BrowsePacket::kMinSize()); @@ -82,7 +75,9 @@ bool GetFolderItemsResponseBuilder::Serialize( } AddPayloadOctets1(pkt, (uint8_t)status_); // Status - if (status_ != Status::NO_ERROR) return true; + if (status_ != Status::NO_ERROR) { + return true; + } AddPayloadOctets2(pkt, base::ByteSwap(uid_counter_)); uint16_t num_items = items_.size(); @@ -99,18 +94,21 @@ bool GetFolderItemsResponseBuilder::AddMediaPlayer(MediaPlayerItem item) { log::assert_that(scope_ == Scope::MEDIA_PLAYER_LIST, "assert failed: scope_ == Scope::MEDIA_PLAYER_LIST"); - if (size() + item.size() > mtu_) return false; + if (size() + item.size() > mtu_) { + return false; + } items_.push_back(MediaListItem(item)); return true; } bool GetFolderItemsResponseBuilder::AddSong(MediaElementItem item) { - log::assert_that( - scope_ == Scope::VFS || scope_ == Scope::NOW_PLAYING, - "assert failed: scope_ == Scope::VFS || scope_ == Scope::NOW_PLAYING"); + log::assert_that(scope_ == Scope::VFS || scope_ == Scope::NOW_PLAYING, + "assert failed: scope_ == Scope::VFS || scope_ == Scope::NOW_PLAYING"); - if (size() + item.size() > mtu_) return false; + if (size() + item.size() > mtu_) { + return false; + } items_.push_back(MediaListItem(item)); return true; @@ -119,15 +117,16 @@ bool GetFolderItemsResponseBuilder::AddSong(MediaElementItem item) { bool GetFolderItemsResponseBuilder::AddFolder(FolderItem item) { log::assert_that(scope_ == Scope::VFS, "assert failed: scope_ == Scope::VFS"); - if (size() + item.size() > mtu_) return false; + if (size() + item.size() > mtu_) { + return false; + } items_.push_back(MediaListItem(item)); return true; } void GetFolderItemsResponseBuilder::PushMediaListItem( - const std::shared_ptr<::bluetooth::Packet>& pkt, - const MediaListItem& item) { + const std::shared_ptr<::bluetooth::Packet>& pkt, const MediaListItem& item) { switch (item.type_) { case MediaListItem::PLAYER: PushMediaPlayerItem(pkt, item.player_); @@ -142,16 +141,14 @@ void GetFolderItemsResponseBuilder::PushMediaListItem( } void GetFolderItemsResponseBuilder::PushMediaPlayerItem( - const std::shared_ptr<::bluetooth::Packet>& pkt, - const MediaPlayerItem& item) { + const std::shared_ptr<::bluetooth::Packet>& pkt, const MediaPlayerItem& item) { AddPayloadOctets1(pkt, 0x01); // Media Player Item uint16_t item_len = item.size() - 3; AddPayloadOctets2(pkt, base::ByteSwap(item_len)); // Item length AddPayloadOctets2(pkt, base::ByteSwap(item.id_)); // Player ID AddPayloadOctets1(pkt, 0x01); // Player Type AddPayloadOctets4(pkt, 0x00000000); // Player Subtype - AddPayloadOctets1( - pkt, 0x02); // Player Play Status // TODO: Add this as a passed field + AddPayloadOctets1(pkt, 0x02); // Player Play Status // TODO: Add this as a passed field // Features AddPayloadOctets1(pkt, 0x00); @@ -185,8 +182,8 @@ void GetFolderItemsResponseBuilder::PushMediaPlayerItem( } } -void GetFolderItemsResponseBuilder::PushFolderItem( - const std::shared_ptr<::bluetooth::Packet>& pkt, const FolderItem& item) { +void GetFolderItemsResponseBuilder::PushFolderItem(const std::shared_ptr<::bluetooth::Packet>& pkt, + const FolderItem& item) { AddPayloadOctets1(pkt, 0x02); // Folder Item uint16_t item_len = item.size() - 3; AddPayloadOctets2(pkt, base::ByteSwap(item_len)); @@ -203,8 +200,7 @@ void GetFolderItemsResponseBuilder::PushFolderItem( } void GetFolderItemsResponseBuilder::PushMediaElementItem( - const std::shared_ptr<::bluetooth::Packet>& pkt, - const MediaElementItem& item) { + const std::shared_ptr<::bluetooth::Packet>& pkt, const MediaElementItem& item) { AddPayloadOctets1(pkt, 0x03); // Media Element Item uint16_t item_len = item.size() - 3; AddPayloadOctets2(pkt, base::ByteSwap(item_len)); @@ -261,7 +257,9 @@ std::vector GetFolderItemsRequest::GetAttributesRequested() const { std::vector attribute_list; // No attributes requested - if (number_of_attributes == 0xFF) return attribute_list; + if (number_of_attributes == 0xFF) { + return attribute_list; + } // TODO: If the number of attributes equals 0, then all attributes are // requested right now thats handled in the service itself, but it'd be nice @@ -275,14 +273,20 @@ std::vector GetFolderItemsRequest::GetAttributesRequested() const { } bool GetFolderItemsRequest::IsValid() const { - if (!BrowsePacket::IsValid()) return false; + if (!BrowsePacket::IsValid()) { + return false; + } // The minimum size required to be valid - if (size() < kMinSize()) return false; + if (size() < kMinSize()) { + return false; + } auto attr_count = GetNumAttributes(); // No items requested - if (attr_count == 0xFF) return true; + if (attr_count == 0xFF) { + return true; + } auto attr_start = begin() + kMinSize(); @@ -306,13 +310,11 @@ std::string GetFolderItemsRequest::ToString() const { return ss.str(); } -std::unique_ptr -GetFolderItemsRequestBuilder::MakeBuilder( - Scope scope, uint32_t start_item, uint32_t end_item, - const std::set& requested_attrs) { +std::unique_ptr GetFolderItemsRequestBuilder::MakeBuilder( + Scope scope, uint32_t start_item, uint32_t end_item, + const std::set& requested_attrs) { std::unique_ptr builder( - new GetFolderItemsRequestBuilder(scope, start_item, end_item, - requested_attrs)); + new GetFolderItemsRequestBuilder(scope, start_item, end_item, requested_attrs)); return builder; } @@ -323,8 +325,7 @@ size_t GetFolderItemsRequestBuilder::size() const { return len; } -bool GetFolderItemsRequestBuilder::Serialize( - const std::shared_ptr<::bluetooth::Packet>& pkt) { +bool GetFolderItemsRequestBuilder::Serialize(const std::shared_ptr<::bluetooth::Packet>& pkt) { ReserveSpace(pkt, size()); BrowsePacketBuilder::PushHeader(pkt, size() - BrowsePacket::kMinSize()); diff --git a/system/packet/avrcp/get_folder_items.h b/system/packet/avrcp/get_folder_items.h index f5291afd9ae..c13b8ab1cc0 100644 --- a/system/packet/avrcp/get_folder_items.h +++ b/system/packet/avrcp/get_folder_items.h @@ -22,52 +22,52 @@ namespace bluetooth { namespace avrcp { class GetFolderItemsResponseBuilder : public BrowsePacketBuilder { - public: +public: virtual ~GetFolderItemsResponseBuilder() = default; - static std::unique_ptr MakePlayerListBuilder( - Status status, uint16_t uid_counter, size_t mtu); - static std::unique_ptr MakeVFSBuilder( - Status status, uint16_t uid_counter, size_t mtu); - static std::unique_ptr MakeNowPlayingBuilder( - Status status, uint16_t uid_counter, size_t mtu); + static std::unique_ptr MakePlayerListBuilder(Status status, + uint16_t uid_counter, + size_t mtu); + static std::unique_ptr MakeVFSBuilder(Status status, + uint16_t uid_counter, + size_t mtu); + static std::unique_ptr MakeNowPlayingBuilder(Status status, + uint16_t uid_counter, + size_t mtu); virtual size_t size() const override; - virtual bool Serialize( - const std::shared_ptr<::bluetooth::Packet>& pkt) override; + virtual bool Serialize(const std::shared_ptr<::bluetooth::Packet>& pkt) override; // Returns false if adding an item would exceed the MTU bool AddMediaPlayer(MediaPlayerItem item); bool AddSong(MediaElementItem item); bool AddFolder(FolderItem item); - protected: +protected: Scope scope_; std::vector items_; Status status_; uint16_t uid_counter_; size_t mtu_; - GetFolderItemsResponseBuilder(Scope scope, Status status, - uint16_t uid_counter, size_t mtu) + GetFolderItemsResponseBuilder(Scope scope, Status status, uint16_t uid_counter, size_t mtu) : BrowsePacketBuilder(BrowsePdu::GET_FOLDER_ITEMS), scope_(scope), status_(status), uid_counter_(uid_counter), - mtu_(mtu){}; + mtu_(mtu) {} - private: +private: void PushMediaListItem(const std::shared_ptr<::bluetooth::Packet>& pkt, const MediaListItem& item); void PushMediaPlayerItem(const std::shared_ptr<::bluetooth::Packet>& pkt, const MediaPlayerItem& item); void PushMediaElementItem(const std::shared_ptr<::bluetooth::Packet>& pkt, const MediaElementItem& item); - void PushFolderItem(const std::shared_ptr<::bluetooth::Packet>& pkt, - const FolderItem& item); + void PushFolderItem(const std::shared_ptr<::bluetooth::Packet>& pkt, const FolderItem& item); }; class GetFolderItemsRequest : public BrowsePacket { - public: +public: virtual ~GetFolderItemsRequest() = default; /** @@ -93,31 +93,29 @@ class GetFolderItemsRequest : public BrowsePacket { virtual bool IsValid() const override; virtual std::string ToString() const override; - protected: +protected: using BrowsePacket::BrowsePacket; }; class GetFolderItemsRequestBuilder : public BrowsePacketBuilder { - public: +public: virtual ~GetFolderItemsRequestBuilder() = default; static std::unique_ptr MakeBuilder( - Scope scope, uint32_t start_item, uint32_t end_item, - const std::set& requested_attrs); + Scope scope, uint32_t start_item, uint32_t end_item, + const std::set& requested_attrs); virtual size_t size() const override; - virtual bool Serialize( - const std::shared_ptr<::bluetooth::Packet>& pkt) override; + virtual bool Serialize(const std::shared_ptr<::bluetooth::Packet>& pkt) override; - protected: - GetFolderItemsRequestBuilder(Scope scope, uint32_t start_item, - uint32_t end_item, +protected: + GetFolderItemsRequestBuilder(Scope scope, uint32_t start_item, uint32_t end_item, const std::set& requested_attrs) : BrowsePacketBuilder(BrowsePdu::GET_FOLDER_ITEMS), scope_(scope), start_item_(start_item), end_item_(end_item), - requested_attrs_(requested_attrs){}; + requested_attrs_(requested_attrs) {} Scope scope_; uint32_t start_item_; diff --git a/system/packet/avrcp/get_item_attributes.cc b/system/packet/avrcp/get_item_attributes.cc index 1720c1e7ca9..28ee438f166 100644 --- a/system/packet/avrcp/get_item_attributes.cc +++ b/system/packet/avrcp/get_item_attributes.cc @@ -19,18 +19,16 @@ namespace bluetooth { namespace avrcp { -std::unique_ptr -GetItemAttributesResponseBuilder::MakeBuilder(Status status, size_t mtu) { +std::unique_ptr GetItemAttributesResponseBuilder::MakeBuilder( + Status status, size_t mtu) { std::unique_ptr builder( - new GetItemAttributesResponseBuilder(status, mtu)); + new GetItemAttributesResponseBuilder(status, mtu)); return builder; } -size_t GetItemAttributesResponseBuilder::AddAttributeEntry( - AttributeEntry entry) { - log::assert_that(entries_.size() < 0xFF, - "assert failed: entries_.size() < 0xFF"); +size_t GetItemAttributesResponseBuilder::AddAttributeEntry(AttributeEntry entry) { + log::assert_that(entries_.size() < 0xFF, "assert failed: entries_.size() < 0xFF"); size_t remaining_space = mtu_ - size(); if (entry.size() > remaining_space) { @@ -45,14 +43,16 @@ size_t GetItemAttributesResponseBuilder::AddAttributeEntry( return entry.size(); } -size_t GetItemAttributesResponseBuilder::AddAttributeEntry( - Attribute attribute, const std::string& value) { +size_t GetItemAttributesResponseBuilder::AddAttributeEntry(Attribute attribute, + const std::string& value) { return AddAttributeEntry(AttributeEntry(attribute, value)); } size_t GetItemAttributesResponseBuilder::size() const { size_t len = kHeaderSize(); - if (status_ != Status::NO_ERROR) return kErrorHeaderSize(); + if (status_ != Status::NO_ERROR) { + return kErrorHeaderSize(); + } for (const auto& entry : entries_) { len += entry.size(); @@ -60,14 +60,15 @@ size_t GetItemAttributesResponseBuilder::size() const { return len; } -bool GetItemAttributesResponseBuilder::Serialize( - const std::shared_ptr<::bluetooth::Packet>& pkt) { +bool GetItemAttributesResponseBuilder::Serialize(const std::shared_ptr<::bluetooth::Packet>& pkt) { ReserveSpace(pkt, size()); BrowsePacketBuilder::PushHeader(pkt, size() - BrowsePacket::kMinSize()); AddPayloadOctets1(pkt, (uint8_t)status_); - if (status_ != Status::NO_ERROR) return true; + if (status_ != Status::NO_ERROR) { + return true; + } AddPayloadOctets1(pkt, entries_.size()); for (const auto& entry : entries_) { @@ -104,8 +105,7 @@ uint8_t GetItemAttributesRequest::GetNumAttributes() const { return *it; } -std::vector GetItemAttributesRequest::GetAttributesRequested() - const { +std::vector GetItemAttributesRequest::GetAttributesRequested() const { auto it = begin() + BrowsePacket::kMinSize() + static_cast(11); size_t number_of_attributes = it.extract(); @@ -118,8 +118,12 @@ std::vector GetItemAttributesRequest::GetAttributesRequested() } bool GetItemAttributesRequest::IsValid() const { - if (!BrowsePacket::IsValid()) return false; - if (size() < kMinSize()) return false; + if (!BrowsePacket::IsValid()) { + return false; + } + if (size() < kMinSize()) { + return false; + } // Casting the int returned from end - attr_start should be fine. If an // overflow occurs we can definitly say the packet is invalid diff --git a/system/packet/avrcp/get_item_attributes.h b/system/packet/avrcp/get_item_attributes.h index 70aac1e8865..9fa3a6e7c46 100644 --- a/system/packet/avrcp/get_item_attributes.h +++ b/system/packet/avrcp/get_item_attributes.h @@ -28,7 +28,7 @@ template class AttributesResponseBuilderTestUser; class GetItemAttributesResponseBuilder : public BrowsePacketBuilder { - public: +public: virtual ~GetItemAttributesResponseBuilder() = default; using Builder = std::unique_ptr; static Builder MakeBuilder(Status status, size_t mtu); @@ -52,24 +52,20 @@ class GetItemAttributesResponseBuilder : public BrowsePacketBuilder { } virtual size_t size() const override; - virtual bool Serialize( - const std::shared_ptr<::bluetooth::Packet>& pkt) override; + virtual bool Serialize(const std::shared_ptr<::bluetooth::Packet>& pkt) override; - private: +private: Status status_; size_t mtu_; std::set entries_; - friend class AttributesResponseBuilderTestUser< - GetItemAttributesResponseBuilder>; + friend class AttributesResponseBuilderTestUser; GetItemAttributesResponseBuilder(Status status, size_t mtu) - : BrowsePacketBuilder(BrowsePdu::GET_ITEM_ATTRIBUTES), - status_(status), - mtu_(mtu) {} + : BrowsePacketBuilder(BrowsePdu::GET_ITEM_ATTRIBUTES), status_(status), mtu_(mtu) {} }; class GetItemAttributesRequest : public BrowsePacket { - public: +public: virtual ~GetItemAttributesRequest() = default; /** @@ -89,14 +85,13 @@ class GetItemAttributesRequest : public BrowsePacket { Scope GetScope() const; uint64_t GetUid() const; uint16_t GetUidCounter() const; - uint8_t GetNumAttributes() - const; // If this value is zero, then all attributes are requested + uint8_t GetNumAttributes() const; // If this value is zero, then all attributes are requested std::vector GetAttributesRequested() const; virtual bool IsValid() const override; virtual std::string ToString() const override; - protected: +protected: using BrowsePacket::BrowsePacket; }; diff --git a/system/packet/avrcp/get_play_status_packet.cc b/system/packet/avrcp/get_play_status_packet.cc index 8a40de9ac24..ed7ff542ac1 100644 --- a/system/packet/avrcp/get_play_status_packet.cc +++ b/system/packet/avrcp/get_play_status_packet.cc @@ -19,27 +19,19 @@ namespace bluetooth { namespace avrcp { -std::string GetPlayStatusRequest::ToString() const { - return "GetPlayStatusRequest"; -} +std::string GetPlayStatusRequest::ToString() const { return "GetPlayStatusRequest"; } -std::unique_ptr -GetPlayStatusResponseBuilder::MakeBuilder(uint32_t song_length, - uint32_t song_position, - uint8_t play_status) { +std::unique_ptr GetPlayStatusResponseBuilder::MakeBuilder( + uint32_t song_length, uint32_t song_position, uint8_t play_status) { std::unique_ptr builder( - new GetPlayStatusResponseBuilder(song_length, song_position, - play_status)); + new GetPlayStatusResponseBuilder(song_length, song_position, play_status)); return builder; } -size_t GetPlayStatusResponseBuilder::size() const { - return VendorPacket::kMinSize() + 4 + 4 + 1; -} +size_t GetPlayStatusResponseBuilder::size() const { return VendorPacket::kMinSize() + 4 + 4 + 1; } -bool GetPlayStatusResponseBuilder::Serialize( - const std::shared_ptr<::bluetooth::Packet>& pkt) { +bool GetPlayStatusResponseBuilder::Serialize(const std::shared_ptr<::bluetooth::Packet>& pkt) { ReserveSpace(pkt, size()); // Push the standard avrcp headers diff --git a/system/packet/avrcp/get_play_status_packet.h b/system/packet/avrcp/get_play_status_packet.h index 5714c26a925..b725bfecaaf 100644 --- a/system/packet/avrcp/get_play_status_packet.h +++ b/system/packet/avrcp/get_play_status_packet.h @@ -25,7 +25,7 @@ namespace avrcp { // zero extra information other than it is a strong type and provides a // validator class GetPlayStatusRequest : public VendorPacket { - public: +public: virtual ~GetPlayStatusRequest() = default; /** @@ -47,33 +47,31 @@ class GetPlayStatusRequest : public VendorPacket { virtual bool IsValid() const override; virtual std::string ToString() const override; - protected: +protected: using VendorPacket::VendorPacket; }; class GetPlayStatusResponseBuilder : public VendorPacketBuilder { - public: +public: virtual ~GetPlayStatusResponseBuilder() = default; - static std::unique_ptr MakeBuilder( - uint32_t song_length, uint32_t song_position, uint8_t play_status); + static std::unique_ptr MakeBuilder(uint32_t song_length, + uint32_t song_position, + uint8_t play_status); virtual size_t size() const override; - virtual bool Serialize( - const std::shared_ptr<::bluetooth::Packet>& pkt) override; + virtual bool Serialize(const std::shared_ptr<::bluetooth::Packet>& pkt) override; - protected: +protected: uint32_t song_length_; uint32_t song_position_; uint8_t play_status_; - GetPlayStatusResponseBuilder(uint32_t song_length, uint32_t song_position, - uint8_t play_status) - : VendorPacketBuilder(CType::STABLE, CommandPdu::GET_PLAY_STATUS, - PacketType::SINGLE), + GetPlayStatusResponseBuilder(uint32_t song_length, uint32_t song_position, uint8_t play_status) + : VendorPacketBuilder(CType::STABLE, CommandPdu::GET_PLAY_STATUS, PacketType::SINGLE), song_length_(song_length), song_position_(song_position), - play_status_(play_status){}; + play_status_(play_status) {} }; } // namespace avrcp diff --git a/system/packet/avrcp/get_total_number_of_items.cc b/system/packet/avrcp/get_total_number_of_items.cc index ab601ea6d6e..60e44508237 100644 --- a/system/packet/avrcp/get_total_number_of_items.cc +++ b/system/packet/avrcp/get_total_number_of_items.cc @@ -20,11 +20,10 @@ namespace bluetooth { namespace avrcp { std::unique_ptr -GetTotalNumberOfItemsResponseBuilder::MakeBuilder( - Status status, uint16_t uid_counter, uint32_t num_items_in_folder) { +GetTotalNumberOfItemsResponseBuilder::MakeBuilder(Status status, uint16_t uid_counter, + uint32_t num_items_in_folder) { std::unique_ptr builder( - new GetTotalNumberOfItemsResponseBuilder(status, uid_counter, - num_items_in_folder)); + new GetTotalNumberOfItemsResponseBuilder(status, uid_counter, num_items_in_folder)); return builder; } @@ -33,7 +32,9 @@ size_t GetTotalNumberOfItemsResponseBuilder::size() const { size_t len = BrowsePacket::kMinSize(); len += 1; // Status - if (status_ != Status::NO_ERROR) return len; + if (status_ != Status::NO_ERROR) { + return len; + } len += 2; // UID Counter len += 4; // Number of items in folder @@ -41,14 +42,16 @@ size_t GetTotalNumberOfItemsResponseBuilder::size() const { } bool GetTotalNumberOfItemsResponseBuilder::Serialize( - const std::shared_ptr<::bluetooth::Packet>& pkt) { + const std::shared_ptr<::bluetooth::Packet>& pkt) { ReserveSpace(pkt, size()); BrowsePacketBuilder::PushHeader(pkt, size() - BrowsePacket::kMinSize()); AddPayloadOctets1(pkt, (uint8_t)status_); - if (status_ != Status::NO_ERROR) return true; + if (status_ != Status::NO_ERROR) { + return true; + } AddPayloadOctets2(pkt, base::ByteSwap(uid_counter_)); AddPayloadOctets4(pkt, base::ByteSwap(num_items_in_folder_)); return true; @@ -60,7 +63,9 @@ Scope GetTotalNumberOfItemsRequest::GetScope() const { } bool GetTotalNumberOfItemsRequest::IsValid() const { - if (!BrowsePacket::IsValid()) return false; + if (!BrowsePacket::IsValid()) { + return false; + } return size() == kMinSize(); } diff --git a/system/packet/avrcp/get_total_number_of_items.h b/system/packet/avrcp/get_total_number_of_items.h index 51842c9329e..9f0a8810b49 100644 --- a/system/packet/avrcp/get_total_number_of_items.h +++ b/system/packet/avrcp/get_total_number_of_items.h @@ -22,17 +22,16 @@ namespace bluetooth { namespace avrcp { class GetTotalNumberOfItemsResponseBuilder : public BrowsePacketBuilder { - public: +public: virtual ~GetTotalNumberOfItemsResponseBuilder() = default; static std::unique_ptr MakeBuilder( - Status status, uint16_t uid_counter, uint32_t num_items_in_folder); + Status status, uint16_t uid_counter, uint32_t num_items_in_folder); virtual size_t size() const override; - virtual bool Serialize( - const std::shared_ptr<::bluetooth::Packet>& pkt) override; + virtual bool Serialize(const std::shared_ptr<::bluetooth::Packet>& pkt) override; - protected: +protected: Status status_; uint16_t uid_counter_; uint32_t num_items_in_folder_; @@ -42,11 +41,11 @@ class GetTotalNumberOfItemsResponseBuilder : public BrowsePacketBuilder { : BrowsePacketBuilder(BrowsePdu::GET_TOTAL_NUMBER_OF_ITEMS), status_(status), uid_counter_(uid_counter), - num_items_in_folder_(num_items_in_folder){}; + num_items_in_folder_(num_items_in_folder) {} }; class GetTotalNumberOfItemsRequest : public BrowsePacket { - public: +public: virtual ~GetTotalNumberOfItemsRequest() = default; /** @@ -64,7 +63,7 @@ class GetTotalNumberOfItemsRequest : public BrowsePacket { virtual bool IsValid() const override; virtual std::string ToString() const override; - protected: +protected: using BrowsePacket::BrowsePacket; }; diff --git a/system/packet/avrcp/list_player_application_setting_attributes.cc b/system/packet/avrcp/list_player_application_setting_attributes.cc index 14c19e2d27a..436dfa955e3 100644 --- a/system/packet/avrcp/list_player_application_setting_attributes.cc +++ b/system/packet/avrcp/list_player_application_setting_attributes.cc @@ -21,10 +21,9 @@ namespace avrcp { std::unique_ptr ListPlayerApplicationSettingAttributesResponseBuilder::MakeBuilder( - std::vector attributes) { - std::unique_ptr - builder(new ListPlayerApplicationSettingAttributesResponseBuilder( - std::move(attributes))); + std::vector attributes) { + std::unique_ptr builder( + new ListPlayerApplicationSettingAttributesResponseBuilder(std::move(attributes))); return builder; } @@ -37,7 +36,7 @@ size_t ListPlayerApplicationSettingAttributesResponseBuilder::size() const { } bool ListPlayerApplicationSettingAttributesResponseBuilder::Serialize( - const std::shared_ptr<::bluetooth::Packet>& pkt) { + const std::shared_ptr<::bluetooth::Packet>& pkt) { ReserveSpace(pkt, size()); PacketBuilder::PushHeader(pkt); diff --git a/system/packet/avrcp/list_player_application_setting_attributes.h b/system/packet/avrcp/list_player_application_setting_attributes.h index 53ff7cc554f..800e73cac5a 100644 --- a/system/packet/avrcp/list_player_application_setting_attributes.h +++ b/system/packet/avrcp/list_player_application_setting_attributes.h @@ -23,28 +23,23 @@ namespace bluetooth { namespace avrcp { -class ListPlayerApplicationSettingAttributesResponseBuilder - : public VendorPacketBuilder { - public: +class ListPlayerApplicationSettingAttributesResponseBuilder : public VendorPacketBuilder { +public: virtual ~ListPlayerApplicationSettingAttributesResponseBuilder() = default; - static std::unique_ptr - MakeBuilder(std::vector attributes); + static std::unique_ptr MakeBuilder( + std::vector attributes); virtual size_t size() const override; - virtual bool Serialize( - const std::shared_ptr<::bluetooth::Packet>& pkt) override; + virtual bool Serialize(const std::shared_ptr<::bluetooth::Packet>& pkt) override; - protected: +protected: std::vector attributes_; - ListPlayerApplicationSettingAttributesResponseBuilder( - std::vector attributes) - : VendorPacketBuilder( - CType::STABLE, - CommandPdu::LIST_PLAYER_APPLICATION_SETTING_ATTRIBUTES, - PacketType::SINGLE), - attributes_(std::move(attributes)){}; + ListPlayerApplicationSettingAttributesResponseBuilder(std::vector attributes) + : VendorPacketBuilder(CType::STABLE, CommandPdu::LIST_PLAYER_APPLICATION_SETTING_ATTRIBUTES, + PacketType::SINGLE), + attributes_(std::move(attributes)) {} }; } // namespace avrcp diff --git a/system/packet/avrcp/list_player_application_setting_values.cc b/system/packet/avrcp/list_player_application_setting_values.cc index 19870f63379..603279824b8 100644 --- a/system/packet/avrcp/list_player_application_setting_values.cc +++ b/system/packet/avrcp/list_player_application_setting_values.cc @@ -20,10 +20,9 @@ namespace bluetooth { namespace avrcp { std::unique_ptr -ListPlayerApplicationSettingValuesResponseBuilder::MakeBuilder( - std::vector values) { +ListPlayerApplicationSettingValuesResponseBuilder::MakeBuilder(std::vector values) { std::unique_ptr builder( - new ListPlayerApplicationSettingValuesResponseBuilder(std::move(values))); + new ListPlayerApplicationSettingValuesResponseBuilder(std::move(values))); return builder; } @@ -36,7 +35,7 @@ size_t ListPlayerApplicationSettingValuesResponseBuilder::size() const { } bool ListPlayerApplicationSettingValuesResponseBuilder::Serialize( - const std::shared_ptr<::bluetooth::Packet>& pkt) { + const std::shared_ptr<::bluetooth::Packet>& pkt) { ReserveSpace(pkt, size()); PacketBuilder::PushHeader(pkt); @@ -51,14 +50,15 @@ bool ListPlayerApplicationSettingValuesResponseBuilder::Serialize( return true; } -PlayerAttribute -ListPlayerApplicationSettingValuesRequest::GetRequestedAttribute() const { +PlayerAttribute ListPlayerApplicationSettingValuesRequest::GetRequestedAttribute() const { auto it = begin() + VendorPacket::kMinSize(); return static_cast(it.extract8()); } bool ListPlayerApplicationSettingValuesRequest::IsValid() const { - if (!VendorPacket::IsValid()) return false; + if (!VendorPacket::IsValid()) { + return false; + } return size() == kMinSize(); } @@ -73,8 +73,7 @@ std::string ListPlayerApplicationSettingValuesRequest::ToString() const { ss << " └ Command PDU = " << GetCommandPdu() << std::endl; ss << " └ PacketType = " << GetPacketType() << std::endl; ss << " └ Parameter Length = " << loghex(GetParameterLength()) << std::endl; - ss << " └ Player Setting Attribute = " << GetRequestedAttribute() - << std::endl; + ss << " └ Player Setting Attribute = " << GetRequestedAttribute() << std::endl; ss << std::endl; return ss.str(); diff --git a/system/packet/avrcp/list_player_application_setting_values.h b/system/packet/avrcp/list_player_application_setting_values.h index 38f202c7e6a..c1a2d4227b1 100644 --- a/system/packet/avrcp/list_player_application_setting_values.h +++ b/system/packet/avrcp/list_player_application_setting_values.h @@ -23,30 +23,27 @@ namespace bluetooth { namespace avrcp { -class ListPlayerApplicationSettingValuesResponseBuilder - : public VendorPacketBuilder { - public: +class ListPlayerApplicationSettingValuesResponseBuilder : public VendorPacketBuilder { +public: virtual ~ListPlayerApplicationSettingValuesResponseBuilder() = default; - static std::unique_ptr - MakeBuilder(std::vector values); + static std::unique_ptr MakeBuilder( + std::vector values); virtual size_t size() const override; - virtual bool Serialize( - const std::shared_ptr<::bluetooth::Packet>& pkt) override; + virtual bool Serialize(const std::shared_ptr<::bluetooth::Packet>& pkt) override; - protected: +protected: std::vector values_; ListPlayerApplicationSettingValuesResponseBuilder(std::vector values) - : VendorPacketBuilder(CType::STABLE, - CommandPdu::LIST_PLAYER_APPLICATION_SETTING_VALUES, + : VendorPacketBuilder(CType::STABLE, CommandPdu::LIST_PLAYER_APPLICATION_SETTING_VALUES, PacketType::SINGLE), - values_(std::move(values)){}; + values_(std::move(values)) {} }; class ListPlayerApplicationSettingValuesRequest : public VendorPacket { - public: +public: virtual ~ListPlayerApplicationSettingValuesRequest() = default; /** @@ -64,16 +61,14 @@ class ListPlayerApplicationSettingValuesRequest : public VendorPacket { * ListPlayerApplicationSettingValuesRequest: * PlayerAttribute attribute; */ - static constexpr size_t kMinSize() { - return VendorPacket::kMinSize() + sizeof(uint8_t); - } + static constexpr size_t kMinSize() { return VendorPacket::kMinSize() + sizeof(uint8_t); } PlayerAttribute GetRequestedAttribute() const; virtual bool IsValid() const override; virtual std::string ToString() const override; - protected: +protected: using VendorPacket::VendorPacket; }; diff --git a/system/packet/avrcp/pass_through_packet.cc b/system/packet/avrcp/pass_through_packet.cc index 67b8d16eee6..dce89902ae9 100644 --- a/system/packet/avrcp/pass_through_packet.cc +++ b/system/packet/avrcp/pass_through_packet.cc @@ -20,25 +20,24 @@ namespace bluetooth { namespace avrcp { std::unique_ptr PassThroughPacketBuilder::MakeBuilder( - bool response, bool pushed, uint8_t opperation_id) { + bool response, bool pushed, uint8_t operation_id) { auto builder = std::unique_ptr( - new PassThroughPacketBuilder(response, pushed, opperation_id)); + new PassThroughPacketBuilder(response, pushed, operation_id)); return builder; } -size_t PassThroughPacketBuilder::size() const { - return PassThroughPacket::kMinSize(); -} +size_t PassThroughPacketBuilder::size() const { return PassThroughPacket::kMinSize(); } -bool PassThroughPacketBuilder::Serialize( - const std::shared_ptr<::bluetooth::Packet>& pkt) { +bool PassThroughPacketBuilder::Serialize(const std::shared_ptr<::bluetooth::Packet>& pkt) { ReserveSpace(pkt, size()); PacketBuilder::PushHeader(pkt); - uint8_t byte = opperation_id_ & 0b01111111; - if (!pushed_) byte |= 0b10000000; + uint8_t byte = operation_id_ & 0b01111111; + if (!pushed_) { + byte |= 0b10000000; + } AddPayloadOctets1(pkt, byte); // Data length, for this packet it's always 0; AddPayloadOctets1(pkt, 0x00); @@ -65,7 +64,7 @@ std::string PassThroughPacket::ToString() const { ss << " └ Subunit ID = " << loghex(GetSubunitId()) << std::endl; ss << " └ OpCode = " << GetOpcode() << std::endl; ss << " └ Pushed = " << GetKeyState() << std::endl; - ss << " └ Opperation ID = " << loghex(GetOperationId()) << std::endl; + ss << " └ Operation ID = " << loghex(GetOperationId()) << std::endl; return ss.str(); } diff --git a/system/packet/avrcp/pass_through_packet.h b/system/packet/avrcp/pass_through_packet.h index 903b3d87809..050ed919196 100644 --- a/system/packet/avrcp/pass_through_packet.h +++ b/system/packet/avrcp/pass_through_packet.h @@ -22,29 +22,28 @@ namespace bluetooth { namespace avrcp { class PassThroughPacketBuilder : public PacketBuilder { - public: +public: virtual ~PassThroughPacketBuilder() = default; - static std::unique_ptr MakeBuilder( - bool response, bool pushed, uint8_t operation_id); + static std::unique_ptr MakeBuilder(bool response, bool pushed, + uint8_t operation_id); virtual size_t size() const override; - virtual bool Serialize( - const std::shared_ptr<::bluetooth::Packet>& pkt) override; + virtual bool Serialize(const std::shared_ptr<::bluetooth::Packet>& pkt) override; - private: +private: bool pushed_; - uint8_t opperation_id_; + uint8_t operation_id_; - PassThroughPacketBuilder(bool response, bool pushed, uint8_t opperation_id) + PassThroughPacketBuilder(bool response, bool pushed, uint8_t operation_id) : PacketBuilder(response ? CType::ACCEPTED : CType::CONTROL, 0x09, 0x00, Opcode::PASS_THROUGH), pushed_(pushed), - opperation_id_(opperation_id){}; + operation_id_(operation_id) {} }; class PassThroughPacket : public Packet { - public: +public: virtual ~PassThroughPacket() = default; /** @@ -56,7 +55,7 @@ class PassThroughPacket : public Packet { * Opcode opcode_; * PassThroughPacket: * uint8_t state : 1; - * uint8_t opperation_id : 7; + * uint8_t operation_id : 7; * uint8_t data_length; */ static constexpr size_t kMinSize() { return Packet::kMinSize() + 2; } @@ -69,7 +68,7 @@ class PassThroughPacket : public Packet { virtual bool IsValid() const override; virtual std::string ToString() const override; - protected: +protected: using Packet::Packet; }; diff --git a/system/packet/avrcp/play_item.cc b/system/packet/avrcp/play_item.cc index d7bb9b73d0e..af850dc2c0b 100644 --- a/system/packet/avrcp/play_item.cc +++ b/system/packet/avrcp/play_item.cc @@ -19,10 +19,8 @@ namespace bluetooth { namespace avrcp { -std::unique_ptr PlayItemResponseBuilder::MakeBuilder( - Status status) { - std::unique_ptr builder( - new PlayItemResponseBuilder(status)); +std::unique_ptr PlayItemResponseBuilder::MakeBuilder(Status status) { + std::unique_ptr builder(new PlayItemResponseBuilder(status)); return builder; } @@ -33,8 +31,7 @@ size_t PlayItemResponseBuilder::size() const { return len; } -bool PlayItemResponseBuilder::Serialize( - const std::shared_ptr<::bluetooth::Packet>& pkt) { +bool PlayItemResponseBuilder::Serialize(const std::shared_ptr<::bluetooth::Packet>& pkt) { ReserveSpace(pkt, size()); PacketBuilder::PushHeader(pkt); @@ -62,7 +59,9 @@ uint16_t PlayItemRequest::GetUidCounter() const { } bool PlayItemRequest::IsValid() const { - if (!VendorPacket::IsValid()) return false; + if (!VendorPacket::IsValid()) { + return false; + } return size() == kMinSize(); } diff --git a/system/packet/avrcp/play_item.h b/system/packet/avrcp/play_item.h index e1c2d488929..32a27605759 100644 --- a/system/packet/avrcp/play_item.h +++ b/system/packet/avrcp/play_item.h @@ -22,26 +22,24 @@ namespace bluetooth { namespace avrcp { class PlayItemResponseBuilder : public VendorPacketBuilder { - public: +public: virtual ~PlayItemResponseBuilder() = default; static std::unique_ptr MakeBuilder(Status status); virtual size_t size() const override; - virtual bool Serialize( - const std::shared_ptr<::bluetooth::Packet>& pkt) override; + virtual bool Serialize(const std::shared_ptr<::bluetooth::Packet>& pkt) override; - protected: +protected: Status status_; PlayItemResponseBuilder(Status status) - : VendorPacketBuilder(CType::ACCEPTED, CommandPdu::PLAY_ITEM, - PacketType::SINGLE), - status_(status){}; + : VendorPacketBuilder(CType::ACCEPTED, CommandPdu::PLAY_ITEM, PacketType::SINGLE), + status_(status) {} }; class PlayItemRequest : public VendorPacket { - public: +public: virtual ~PlayItemRequest() = default; /** @@ -70,7 +68,7 @@ class PlayItemRequest : public VendorPacket { virtual bool IsValid() const override; virtual std::string ToString() const override; - protected: +protected: using VendorPacket::VendorPacket; }; diff --git a/system/packet/avrcp/register_notification_packet.cc b/system/packet/avrcp/register_notification_packet.cc index 02462825679..2adeae761ec 100644 --- a/system/packet/avrcp/register_notification_packet.cc +++ b/system/packet/avrcp/register_notification_packet.cc @@ -23,9 +23,7 @@ namespace bluetooth { namespace avrcp { -bool RegisterNotificationResponse::IsInterim() const { - return GetCType() == CType::INTERIM; -} +bool RegisterNotificationResponse::IsInterim() const { return GetCType() == CType::INTERIM; } Event RegisterNotificationResponse::GetEvent() const { auto value = *(begin() + VendorPacket::kMinSize()); @@ -40,9 +38,14 @@ uint8_t RegisterNotificationResponse::GetVolume() const { } bool RegisterNotificationResponse::IsValid() const { - if (!VendorPacket::IsValid()) return false; - if (size() < kMinSize()) return false; - if (GetCType() != CType::INTERIM && GetCType() != CType::CHANGED && GetCType() != CType::REJECTED) { + if (!VendorPacket::IsValid()) { + return false; + } + if (size() < kMinSize()) { + return false; + } + if (GetCType() != CType::INTERIM && GetCType() != CType::CHANGED && + GetCType() != CType::REJECTED) { return false; } @@ -74,45 +77,39 @@ std::string RegisterNotificationResponse::ToString() const { } std::unique_ptr -RegisterNotificationResponseBuilder::MakePlaybackStatusBuilder( - bool interim, uint8_t play_status) { +RegisterNotificationResponseBuilder::MakePlaybackStatusBuilder(bool interim, uint8_t play_status) { std::unique_ptr builder( - new RegisterNotificationResponseBuilder(interim, - Event::PLAYBACK_STATUS_CHANGED)); + new RegisterNotificationResponseBuilder(interim, Event::PLAYBACK_STATUS_CHANGED)); builder->data_union_.play_status = play_status; return builder; } std::unique_ptr -RegisterNotificationResponseBuilder::MakeTrackChangedBuilder( - bool interim, uint64_t track_uid) { +RegisterNotificationResponseBuilder::MakeTrackChangedBuilder(bool interim, uint64_t track_uid) { std::unique_ptr builder( - new RegisterNotificationResponseBuilder(interim, Event::TRACK_CHANGED)); + new RegisterNotificationResponseBuilder(interim, Event::TRACK_CHANGED)); builder->data_union_.track_uid = track_uid; return builder; } std::unique_ptr -RegisterNotificationResponseBuilder::MakePlaybackPositionBuilder( - bool interim, uint32_t playback_pos) { +RegisterNotificationResponseBuilder::MakePlaybackPositionBuilder(bool interim, + uint32_t playback_pos) { std::unique_ptr builder( - new RegisterNotificationResponseBuilder(interim, - Event::PLAYBACK_POS_CHANGED)); + new RegisterNotificationResponseBuilder(interim, Event::PLAYBACK_POS_CHANGED)); builder->data_union_.playback_pos = playback_pos; return builder; } std::unique_ptr RegisterNotificationResponseBuilder::MakePlayerSettingChangedBuilder( - bool interim, std::vector attributes, - std::vector values) { + bool interim, std::vector attributes, std::vector values) { std::unique_ptr builder( - new RegisterNotificationResponseBuilder( - interim, Event::PLAYER_APPLICATION_SETTING_CHANGED)); + new RegisterNotificationResponseBuilder(interim, + Event::PLAYER_APPLICATION_SETTING_CHANGED)); builder->data_union_.player_settings.number_of_attributes = - static_cast(attributes.size()); - for (int i = 0; i < builder->data_union_.player_settings.number_of_attributes; - i++) { + static_cast(attributes.size()); + for (int i = 0; i < builder->data_union_.player_settings.number_of_attributes; i++) { builder->data_union_.player_settings.attributes[i] = attributes.at(i); builder->data_union_.player_settings.values[i] = values.at(i); } @@ -122,35 +119,31 @@ RegisterNotificationResponseBuilder::MakePlayerSettingChangedBuilder( std::unique_ptr RegisterNotificationResponseBuilder::MakeNowPlayingBuilder(bool interim) { std::unique_ptr builder( - new RegisterNotificationResponseBuilder( - interim, Event::NOW_PLAYING_CONTENT_CHANGED)); + new RegisterNotificationResponseBuilder(interim, Event::NOW_PLAYING_CONTENT_CHANGED)); return builder; } std::unique_ptr RegisterNotificationResponseBuilder::MakeAvailablePlayersBuilder(bool interim) { std::unique_ptr builder( - new RegisterNotificationResponseBuilder( - interim, Event::AVAILABLE_PLAYERS_CHANGED)); + new RegisterNotificationResponseBuilder(interim, Event::AVAILABLE_PLAYERS_CHANGED)); return builder; } std::unique_ptr -RegisterNotificationResponseBuilder::MakeAddressedPlayerBuilder( - bool interim, uint16_t player_id, uint16_t uid_counter) { +RegisterNotificationResponseBuilder::MakeAddressedPlayerBuilder(bool interim, uint16_t player_id, + uint16_t uid_counter) { std::unique_ptr builder( - new RegisterNotificationResponseBuilder(interim, - Event::ADDRESSED_PLAYER_CHANGED)); + new RegisterNotificationResponseBuilder(interim, Event::ADDRESSED_PLAYER_CHANGED)); builder->data_union_.addressed_player.player_id = player_id; builder->data_union_.addressed_player.uid_counter = uid_counter; return builder; } std::unique_ptr -RegisterNotificationResponseBuilder::MakeUidsChangedBuilder( - bool interim, uint16_t uid_counter) { +RegisterNotificationResponseBuilder::MakeUidsChangedBuilder(bool interim, uint16_t uid_counter) { std::unique_ptr builder( - new RegisterNotificationResponseBuilder(interim, Event::UIDS_CHANGED)); + new RegisterNotificationResponseBuilder(interim, Event::UIDS_CHANGED)); builder->data_union_.uid_counter = uid_counter; return builder; } @@ -172,8 +165,7 @@ size_t RegisterNotificationResponseBuilder::size() const { break; case Event::PLAYER_APPLICATION_SETTING_CHANGED: data_size = sizeof(uint8_t) + - 2 * data_union_.player_settings.number_of_attributes * - sizeof(uint8_t); + 2 * data_union_.player_settings.number_of_attributes * sizeof(uint8_t); break; case Event::NOW_PLAYING_CONTENT_CHANGED: data_size = 0; @@ -196,7 +188,7 @@ size_t RegisterNotificationResponseBuilder::size() const { } bool RegisterNotificationResponseBuilder::Serialize( - const std::shared_ptr<::bluetooth::Packet>& pkt) { + const std::shared_ptr<::bluetooth::Packet>& pkt) { ReserveSpace(pkt, size()); PacketBuilder::PushHeader(pkt); @@ -219,10 +211,8 @@ bool RegisterNotificationResponseBuilder::Serialize( } case Event::PLAYER_APPLICATION_SETTING_CHANGED: { AddPayloadOctets1(pkt, data_union_.player_settings.number_of_attributes); - for (int i = 0; i < data_union_.player_settings.number_of_attributes; - i++) { - AddPayloadOctets1(pkt, static_cast( - data_union_.player_settings.attributes[i])); + for (int i = 0; i < data_union_.player_settings.number_of_attributes; i++) { + AddPayloadOctets1(pkt, static_cast(data_union_.player_settings.attributes[i])); AddPayloadOctets1(pkt, data_union_.player_settings.values[i]); } break; // No additional data @@ -232,10 +222,8 @@ bool RegisterNotificationResponseBuilder::Serialize( case Event::AVAILABLE_PLAYERS_CHANGED: break; // No additional data case Event::ADDRESSED_PLAYER_CHANGED: { - AddPayloadOctets2(pkt, - base::ByteSwap(data_union_.addressed_player.player_id)); - AddPayloadOctets2( - pkt, base::ByteSwap(data_union_.addressed_player.uid_counter)); + AddPayloadOctets2(pkt, base::ByteSwap(data_union_.addressed_player.player_id)); + AddPayloadOctets2(pkt, base::ByteSwap(data_union_.addressed_player.uid_counter)); break; } case Event::UIDS_CHANGED: { @@ -261,9 +249,7 @@ uint32_t RegisterNotificationRequest::GetInterval() const { return it.extractBE(); } -bool RegisterNotificationRequest::IsValid() const { - return (size() == kMinSize()); -} +bool RegisterNotificationRequest::IsValid() const { return size() == kMinSize(); } std::string RegisterNotificationRequest::ToString() const { std::stringstream ss; @@ -283,11 +269,10 @@ std::string RegisterNotificationRequest::ToString() const { return ss.str(); } -std::unique_ptr -RegisterNotificationRequestBuilder::MakeBuilder(Event event, - uint32_t interval) { +std::unique_ptr RegisterNotificationRequestBuilder::MakeBuilder( + Event event, uint32_t interval) { std::unique_ptr builder( - new RegisterNotificationRequestBuilder(event, interval)); + new RegisterNotificationRequestBuilder(event, interval)); return builder; } @@ -297,7 +282,7 @@ size_t RegisterNotificationRequestBuilder::size() const { } bool RegisterNotificationRequestBuilder::Serialize( - const std::shared_ptr<::bluetooth::Packet>& pkt) { + const std::shared_ptr<::bluetooth::Packet>& pkt) { ReserveSpace(pkt, size()); PacketBuilder::PushHeader(pkt); diff --git a/system/packet/avrcp/register_notification_packet.h b/system/packet/avrcp/register_notification_packet.h index f66b699f7ea..cc6ed1bc012 100644 --- a/system/packet/avrcp/register_notification_packet.h +++ b/system/packet/avrcp/register_notification_packet.h @@ -22,7 +22,7 @@ namespace bluetooth { namespace avrcp { class RegisterNotificationResponse : public VendorPacket { - public: +public: virtual ~RegisterNotificationResponse() = default; /** @@ -51,46 +51,41 @@ class RegisterNotificationResponse : public VendorPacket { virtual bool IsValid() const override; virtual std::string ToString() const override; - protected: +protected: using VendorPacket::VendorPacket; }; class RegisterNotificationResponseBuilder : public VendorPacketBuilder { - public: +public: virtual ~RegisterNotificationResponseBuilder() = default; - static std::unique_ptr - MakePlaybackStatusBuilder(bool interim, uint8_t play_status); + static std::unique_ptr MakePlaybackStatusBuilder( + bool interim, uint8_t play_status); - static std::unique_ptr - MakeTrackChangedBuilder(bool interim, uint64_t track_uid); + static std::unique_ptr MakeTrackChangedBuilder( + bool interim, uint64_t track_uid); - static std::unique_ptr - MakePlaybackPositionBuilder(bool interim, uint32_t playback_pos); + static std::unique_ptr MakePlaybackPositionBuilder( + bool interim, uint32_t playback_pos); - static std::unique_ptr - MakePlayerSettingChangedBuilder(bool interim, - std::vector attributes, - std::vector values); + static std::unique_ptr MakePlayerSettingChangedBuilder( + bool interim, std::vector attributes, std::vector values); - static std::unique_ptr - MakeNowPlayingBuilder(bool interim); + static std::unique_ptr MakeNowPlayingBuilder(bool interim); - static std::unique_ptr - MakeAvailablePlayersBuilder(bool interim); + static std::unique_ptr MakeAvailablePlayersBuilder( + bool interim); - static std::unique_ptr - MakeAddressedPlayerBuilder(bool interim, uint16_t player_id, - uint16_t uid_counter); + static std::unique_ptr MakeAddressedPlayerBuilder( + bool interim, uint16_t player_id, uint16_t uid_counter); - static std::unique_ptr - MakeUidsChangedBuilder(bool interim, uint16_t uid_counter); + static std::unique_ptr MakeUidsChangedBuilder( + bool interim, uint16_t uid_counter); virtual size_t size() const override; - virtual bool Serialize( - const std::shared_ptr<::bluetooth::Packet>& pkt) override; + virtual bool Serialize(const std::shared_ptr<::bluetooth::Packet>& pkt) override; - protected: +protected: Event event_; union { uint8_t play_status; @@ -110,13 +105,12 @@ class RegisterNotificationResponseBuilder : public VendorPacketBuilder { RegisterNotificationResponseBuilder(bool interim, Event event) : VendorPacketBuilder(interim ? CType::INTERIM : CType::CHANGED, - CommandPdu::REGISTER_NOTIFICATION, - PacketType::SINGLE), - event_(event){}; + CommandPdu::REGISTER_NOTIFICATION, PacketType::SINGLE), + event_(event) {} }; class RegisterNotificationRequest : public VendorPacket { - public: +public: virtual ~RegisterNotificationRequest() = default; /** @@ -145,30 +139,28 @@ class RegisterNotificationRequest : public VendorPacket { virtual bool IsValid() const override; virtual std::string ToString() const override; - protected: +protected: using VendorPacket::VendorPacket; }; class RegisterNotificationRequestBuilder : public VendorPacketBuilder { - public: +public: virtual ~RegisterNotificationRequestBuilder() = default; - static std::unique_ptr MakeBuilder( - Event event, uint32_t interval); + static std::unique_ptr MakeBuilder(Event event, + uint32_t interval); virtual size_t size() const override; - virtual bool Serialize( - const std::shared_ptr<::bluetooth::Packet>& pkt) override; + virtual bool Serialize(const std::shared_ptr<::bluetooth::Packet>& pkt) override; - protected: +protected: Event event_; uint32_t interval_; RegisterNotificationRequestBuilder(Event event, uint32_t interval) - : VendorPacketBuilder(CType::NOTIFY, CommandPdu::REGISTER_NOTIFICATION, - PacketType::SINGLE), + : VendorPacketBuilder(CType::NOTIFY, CommandPdu::REGISTER_NOTIFICATION, PacketType::SINGLE), event_(event), - interval_(interval){}; + interval_(interval) {} }; } // namespace avrcp diff --git a/system/packet/avrcp/set_absolute_volume.cc b/system/packet/avrcp/set_absolute_volume.cc index ff6b7acac91..81cada510dc 100644 --- a/system/packet/avrcp/set_absolute_volume.cc +++ b/system/packet/avrcp/set_absolute_volume.cc @@ -19,20 +19,17 @@ namespace bluetooth { namespace avrcp { -std::unique_ptr -SetAbsoluteVolumeRequestBuilder::MakeBuilder(uint8_t volume) { +std::unique_ptr SetAbsoluteVolumeRequestBuilder::MakeBuilder( + uint8_t volume) { std::unique_ptr builder( - new SetAbsoluteVolumeRequestBuilder(volume & 0x7F)); + new SetAbsoluteVolumeRequestBuilder(volume & 0x7F)); return builder; } -size_t SetAbsoluteVolumeRequestBuilder::size() const { - return VendorPacket::kMinSize() + 1; -} +size_t SetAbsoluteVolumeRequestBuilder::size() const { return VendorPacket::kMinSize() + 1; } -bool SetAbsoluteVolumeRequestBuilder::Serialize( - const std::shared_ptr<::bluetooth::Packet>& pkt) { +bool SetAbsoluteVolumeRequestBuilder::Serialize(const std::shared_ptr<::bluetooth::Packet>& pkt) { ReserveSpace(pkt, size()); PacketBuilder::PushHeader(pkt); @@ -50,8 +47,12 @@ uint8_t SetAbsoluteVolumeResponse::GetVolume() const { } bool SetAbsoluteVolumeResponse::IsValid() const { - if (!VendorPacket::IsValid()) return false; - if (GetCType() != CType::ACCEPTED) return false; + if (!VendorPacket::IsValid()) { + return false; + } + if (GetCType() != CType::ACCEPTED) { + return false; + } return size() == kMinSize(); } diff --git a/system/packet/avrcp/set_absolute_volume.h b/system/packet/avrcp/set_absolute_volume.h index 48cd388798d..17125938df9 100644 --- a/system/packet/avrcp/set_absolute_volume.h +++ b/system/packet/avrcp/set_absolute_volume.h @@ -28,27 +28,24 @@ namespace bluetooth { namespace avrcp { class SetAbsoluteVolumeRequestBuilder : public VendorPacketBuilder { - public: +public: virtual ~SetAbsoluteVolumeRequestBuilder() = default; - static std::unique_ptr MakeBuilder( - uint8_t volume); + static std::unique_ptr MakeBuilder(uint8_t volume); virtual size_t size() const override; - virtual bool Serialize( - const std::shared_ptr<::bluetooth::Packet>& pkt) override; + virtual bool Serialize(const std::shared_ptr<::bluetooth::Packet>& pkt) override; - protected: +protected: uint8_t volume_; SetAbsoluteVolumeRequestBuilder(uint8_t volume) - : VendorPacketBuilder(CType::CONTROL, CommandPdu::SET_ABSOLUTE_VOLUME, - PacketType::SINGLE), - volume_(volume){}; + : VendorPacketBuilder(CType::CONTROL, CommandPdu::SET_ABSOLUTE_VOLUME, PacketType::SINGLE), + volume_(volume) {} }; class SetAbsoluteVolumeResponse : public VendorPacket { - public: +public: virtual ~SetAbsoluteVolumeResponse() = default; /** @@ -73,7 +70,7 @@ class SetAbsoluteVolumeResponse : public VendorPacket { virtual bool IsValid() const override; virtual std::string ToString() const override; - protected: +protected: using VendorPacket::VendorPacket; }; diff --git a/system/packet/avrcp/set_addressed_player.cc b/system/packet/avrcp/set_addressed_player.cc index d1a99092569..f760cadde12 100644 --- a/system/packet/avrcp/set_addressed_player.cc +++ b/system/packet/avrcp/set_addressed_player.cc @@ -19,10 +19,10 @@ namespace bluetooth { namespace avrcp { -std::unique_ptr -SetAddressedPlayerResponseBuilder::MakeBuilder(Status status) { +std::unique_ptr SetAddressedPlayerResponseBuilder::MakeBuilder( + Status status) { std::unique_ptr builder( - new SetAddressedPlayerResponseBuilder(status)); + new SetAddressedPlayerResponseBuilder(status)); return builder; } @@ -33,8 +33,7 @@ size_t SetAddressedPlayerResponseBuilder::size() const { return len; } -bool SetAddressedPlayerResponseBuilder::Serialize( - const std::shared_ptr<::bluetooth::Packet>& pkt) { +bool SetAddressedPlayerResponseBuilder::Serialize(const std::shared_ptr<::bluetooth::Packet>& pkt) { ReserveSpace(pkt, size()); PacketBuilder::PushHeader(pkt); @@ -52,7 +51,9 @@ uint16_t SetAddressedPlayerRequest::GetPlayerId() const { } bool SetAddressedPlayerRequest::IsValid() const { - if (!VendorPacket::IsValid()) return false; + if (!VendorPacket::IsValid()) { + return false; + } return size() == kMinSize(); } diff --git a/system/packet/avrcp/set_addressed_player.h b/system/packet/avrcp/set_addressed_player.h index 823411603a5..b764f5660cb 100644 --- a/system/packet/avrcp/set_addressed_player.h +++ b/system/packet/avrcp/set_addressed_player.h @@ -22,27 +22,24 @@ namespace bluetooth { namespace avrcp { class SetAddressedPlayerResponseBuilder : public VendorPacketBuilder { - public: +public: virtual ~SetAddressedPlayerResponseBuilder() = default; - static std::unique_ptr MakeBuilder( - Status status); + static std::unique_ptr MakeBuilder(Status status); virtual size_t size() const override; - virtual bool Serialize( - const std::shared_ptr<::bluetooth::Packet>& pkt) override; + virtual bool Serialize(const std::shared_ptr<::bluetooth::Packet>& pkt) override; - protected: +protected: Status status_; SetAddressedPlayerResponseBuilder(Status status) - : VendorPacketBuilder(CType::ACCEPTED, CommandPdu::SET_ADDRESSED_PLAYER, - PacketType::SINGLE), - status_(status){}; + : VendorPacketBuilder(CType::ACCEPTED, CommandPdu::SET_ADDRESSED_PLAYER, PacketType::SINGLE), + status_(status) {} }; class SetAddressedPlayerRequest : public VendorPacket { - public: +public: virtual ~SetAddressedPlayerRequest() = default; /** @@ -67,7 +64,7 @@ class SetAddressedPlayerRequest : public VendorPacket { virtual bool IsValid() const override; virtual std::string ToString() const override; - protected: +protected: using VendorPacket::VendorPacket; }; diff --git a/system/packet/avrcp/set_browsed_player.cc b/system/packet/avrcp/set_browsed_player.cc index 85795a2fa94..d9dadc699b6 100644 --- a/system/packet/avrcp/set_browsed_player.cc +++ b/system/packet/avrcp/set_browsed_player.cc @@ -21,14 +21,10 @@ namespace bluetooth { namespace avrcp { -std::unique_ptr -SetBrowsedPlayerResponseBuilder::MakeBuilder(Status status, - uint16_t uid_counter, - uint32_t num_items_in_folder, - uint8_t folder_depth, - std::string folder_name) { - std::unique_ptr builder( - new SetBrowsedPlayerResponseBuilder( +std::unique_ptr SetBrowsedPlayerResponseBuilder::MakeBuilder( + Status status, uint16_t uid_counter, uint32_t num_items_in_folder, uint8_t folder_depth, + std::string folder_name) { + std::unique_ptr builder(new SetBrowsedPlayerResponseBuilder( status, uid_counter, num_items_in_folder, folder_depth, folder_name)); return builder; @@ -39,7 +35,9 @@ size_t SetBrowsedPlayerResponseBuilder::size() const { len += 1; // Status // If the status isn't success the rest of the fields are ommited - if (status_ != Status::NO_ERROR) return len; + if (status_ != Status::NO_ERROR) { + return len; + } len += 2; // UID Counter len += 4; // Number of items in folder @@ -55,22 +53,25 @@ size_t SetBrowsedPlayerResponseBuilder::size() const { return len; } -bool SetBrowsedPlayerResponseBuilder::Serialize( - const std::shared_ptr<::bluetooth::Packet>& pkt) { +bool SetBrowsedPlayerResponseBuilder::Serialize(const std::shared_ptr<::bluetooth::Packet>& pkt) { ReserveSpace(pkt, size()); BrowsePacketBuilder::PushHeader(pkt, size() - BrowsePacket::kMinSize()); AddPayloadOctets1(pkt, (uint8_t)status_); - if (status_ != Status::NO_ERROR) return true; + if (status_ != Status::NO_ERROR) { + return true; + } AddPayloadOctets2(pkt, base::ByteSwap(uid_counter_)); AddPayloadOctets4(pkt, base::ByteSwap(num_items_in_folder_)); AddPayloadOctets2(pkt, base::ByteSwap((uint16_t)0x006a)); // UTF-8 AddPayloadOctets1(pkt, folder_depth_); // Skip adding the folder name if the folder depth is 0 - if (folder_depth_ == 0) return true; + if (folder_depth_ == 0) { + return true; + } uint16_t folder_name_len = folder_name_.size(); AddPayloadOctets2(pkt, base::ByteSwap(folder_name_len)); for (auto it = folder_name_.begin(); it != folder_name_.end(); it++) { @@ -86,7 +87,9 @@ uint16_t SetBrowsedPlayerRequest::GetPlayerId() const { } bool SetBrowsedPlayerRequest::IsValid() const { - if (!BrowsePacket::IsValid()) return false; + if (!BrowsePacket::IsValid()) { + return false; + } return size() == kMinSize(); } diff --git a/system/packet/avrcp/set_browsed_player.h b/system/packet/avrcp/set_browsed_player.h index 336c4e15a2c..15ccc7bba32 100644 --- a/system/packet/avrcp/set_browsed_player.h +++ b/system/packet/avrcp/set_browsed_player.h @@ -22,26 +22,26 @@ namespace bluetooth { namespace avrcp { class SetBrowsedPlayerResponseBuilder : public BrowsePacketBuilder { - public: +public: virtual ~SetBrowsedPlayerResponseBuilder() = default; - static std::unique_ptr MakeBuilder( - Status status, uint16_t uid_counter, uint32_t num_items_in_folder, - uint8_t folder_depth, std::string folder_name); + static std::unique_ptr MakeBuilder(Status status, + uint16_t uid_counter, + uint32_t num_items_in_folder, + uint8_t folder_depth, + std::string folder_name); virtual size_t size() const override; - virtual bool Serialize( - const std::shared_ptr<::bluetooth::Packet>& pkt) override; + virtual bool Serialize(const std::shared_ptr<::bluetooth::Packet>& pkt) override; - protected: +protected: Status status_; uint16_t uid_counter_; uint32_t num_items_in_folder_; uint8_t folder_depth_; std::string folder_name_; - SetBrowsedPlayerResponseBuilder(Status status, uint16_t uid_counter, - uint32_t num_items_in_folder, + SetBrowsedPlayerResponseBuilder(Status status, uint16_t uid_counter, uint32_t num_items_in_folder, uint8_t folder_depth, std::string folder_name) : BrowsePacketBuilder(BrowsePdu::SET_BROWSED_PLAYER), status_(status), @@ -52,7 +52,7 @@ class SetBrowsedPlayerResponseBuilder : public BrowsePacketBuilder { }; class SetBrowsedPlayerRequest : public BrowsePacket { - public: +public: virtual ~SetBrowsedPlayerRequest() = default; /** @@ -70,7 +70,7 @@ class SetBrowsedPlayerRequest : public BrowsePacket { virtual bool IsValid() const override; virtual std::string ToString() const override; - protected: +protected: using BrowsePacket::BrowsePacket; }; diff --git a/system/packet/avrcp/set_player_application_setting_value.cc b/system/packet/avrcp/set_player_application_setting_value.cc index c606d12ce07..a01741ed7e6 100644 --- a/system/packet/avrcp/set_player_application_setting_value.cc +++ b/system/packet/avrcp/set_player_application_setting_value.cc @@ -22,7 +22,7 @@ namespace avrcp { std::unique_ptr SetPlayerApplicationSettingValueResponseBuilder::MakeBuilder() { std::unique_ptr builder( - new SetPlayerApplicationSettingValueResponseBuilder()); + new SetPlayerApplicationSettingValueResponseBuilder()); return builder; } @@ -32,7 +32,7 @@ size_t SetPlayerApplicationSettingValueResponseBuilder::size() const { } bool SetPlayerApplicationSettingValueResponseBuilder::Serialize( - const std::shared_ptr<::bluetooth::Packet>& pkt) { + const std::shared_ptr<::bluetooth::Packet>& pkt) { ReserveSpace(pkt, size()); PacketBuilder::PushHeader(pkt); @@ -42,15 +42,13 @@ bool SetPlayerApplicationSettingValueResponseBuilder::Serialize( return true; } -uint8_t -SetPlayerApplicationSettingValueRequest::GetNumberOfRequestedAttributes() - const { +uint8_t SetPlayerApplicationSettingValueRequest::GetNumberOfRequestedAttributes() const { auto it = begin() + VendorPacket::kMinSize(); return *it; } -std::vector -SetPlayerApplicationSettingValueRequest::GetRequestedAttributes() const { +std::vector SetPlayerApplicationSettingValueRequest::GetRequestedAttributes() + const { auto it = begin() + VendorPacket::kMinSize() + static_cast(1); // Point to the first attribute std::vector attribute_list; @@ -63,8 +61,7 @@ SetPlayerApplicationSettingValueRequest::GetRequestedAttributes() const { return attribute_list; } -std::vector -SetPlayerApplicationSettingValueRequest::GetRequestedValues() const { +std::vector SetPlayerApplicationSettingValueRequest::GetRequestedValues() const { auto it = begin() + VendorPacket::kMinSize() + static_cast(1); // Point to the first attribute std::vector values_list; @@ -78,8 +75,12 @@ SetPlayerApplicationSettingValueRequest::GetRequestedValues() const { } bool SetPlayerApplicationSettingValueRequest::IsValid() const { - if (!VendorPacket::IsValid()) return false; - if (size() < kMinSize()) return false; + if (!VendorPacket::IsValid()) { + return false; + } + if (size() < kMinSize()) { + return false; + } size_t num_of_attrs = GetNumberOfRequestedAttributes(); auto attr_start = begin() + VendorPacket::kMinSize() + static_cast(1); @@ -98,16 +99,14 @@ std::string SetPlayerApplicationSettingValueRequest::ToString() const { ss << " └ Command PDU = " << GetCommandPdu() << std::endl; ss << " └ PacketType = " << GetPacketType() << std::endl; ss << " └ Parameter Length = " << loghex(GetParameterLength()) << std::endl; - ss << " └ Num Attributes = " << loghex(GetNumberOfRequestedAttributes()) - << std::endl; + ss << " └ Num Attributes = " << loghex(GetNumberOfRequestedAttributes()) << std::endl; auto attribute_list_ = GetRequestedAttributes(); auto values_list_ = GetRequestedValues(); - ss << " └ Player Attributes and Values List: Size: " - << attribute_list_.size() << std::endl; + ss << " └ Player Attributes and Values List: Size: " << attribute_list_.size() << std::endl; for (size_t i = 0; i < attribute_list_.size(); i++) { - ss << " └ " << static_cast(attribute_list_.at(i)) - << ": " << std::to_string(values_list_.at(i)) << std::endl; + ss << " └ " << static_cast(attribute_list_.at(i)) << ": " + << std::to_string(values_list_.at(i)) << std::endl; } ss << std::endl; diff --git a/system/packet/avrcp/set_player_application_setting_value.h b/system/packet/avrcp/set_player_application_setting_value.h index b38399e6864..e60b5c45f75 100644 --- a/system/packet/avrcp/set_player_application_setting_value.h +++ b/system/packet/avrcp/set_player_application_setting_value.h @@ -23,27 +23,23 @@ namespace bluetooth { namespace avrcp { -class SetPlayerApplicationSettingValueResponseBuilder - : public VendorPacketBuilder { - public: +class SetPlayerApplicationSettingValueResponseBuilder : public VendorPacketBuilder { +public: virtual ~SetPlayerApplicationSettingValueResponseBuilder() = default; - static std::unique_ptr - MakeBuilder(); + static std::unique_ptr MakeBuilder(); virtual size_t size() const override; - virtual bool Serialize( - const std::shared_ptr<::bluetooth::Packet>& pkt) override; + virtual bool Serialize(const std::shared_ptr<::bluetooth::Packet>& pkt) override; - protected: +protected: SetPlayerApplicationSettingValueResponseBuilder() - : VendorPacketBuilder(CType::ACCEPTED, - CommandPdu::SET_PLAYER_APPLICATION_SETTING_VALUE, - PacketType::SINGLE){}; + : VendorPacketBuilder(CType::ACCEPTED, CommandPdu::SET_PLAYER_APPLICATION_SETTING_VALUE, + PacketType::SINGLE) {} }; class SetPlayerApplicationSettingValueRequest : public VendorPacket { - public: +public: virtual ~SetPlayerApplicationSettingValueRequest() = default; /** @@ -63,9 +59,7 @@ class SetPlayerApplicationSettingValueRequest : public VendorPacket { * std::vector attributes; * std::vector values; */ - static constexpr size_t kMinSize() { - return VendorPacket::kMinSize() + sizeof(uint8_t); - } + static constexpr size_t kMinSize() { return VendorPacket::kMinSize() + sizeof(uint8_t); } uint8_t GetNumberOfRequestedAttributes() const; std::vector GetRequestedAttributes() const; @@ -74,7 +68,7 @@ class SetPlayerApplicationSettingValueRequest : public VendorPacket { virtual bool IsValid() const override; virtual std::string ToString() const override; - protected: +protected: using VendorPacket::VendorPacket; }; diff --git a/system/packet/avrcp/vendor_packet.cc b/system/packet/avrcp/vendor_packet.cc index d4f924d1680..22a63f53f35 100644 --- a/system/packet/avrcp/vendor_packet.cc +++ b/system/packet/avrcp/vendor_packet.cc @@ -24,54 +24,45 @@ namespace bluetooth { namespace avrcp { std::unique_ptr VendorPacketBuilder::MakeBuilder( - CType ctype, CommandPdu pdu, PacketType packet_type, - std::unique_ptr<::bluetooth::PacketBuilder> payload) { + CType ctype, CommandPdu pdu, PacketType packet_type, + std::unique_ptr<::bluetooth::PacketBuilder> payload) { // If the payload size is greater than max uint16_t // the packet should be fragmented - log::assert_that(payload->size() <= size_t(0xFFFF), - "payload size bigger than uint16_t"); + log::assert_that(payload->size() <= size_t(0xFFFF), "payload size bigger than uint16_t"); - std::unique_ptr builder( - new VendorPacketBuilder(ctype, pdu, packet_type)); + std::unique_ptr builder(new VendorPacketBuilder(ctype, pdu, packet_type)); builder->payload_ = std::move(payload); return builder; } -size_t VendorPacketBuilder::size() const { - return VendorPacket::kMinSize() + payload_->size(); -} +size_t VendorPacketBuilder::size() const { return VendorPacket::kMinSize() + payload_->size(); } -bool VendorPacketBuilder::Serialize( - const std::shared_ptr<::bluetooth::Packet>& pkt) { +bool VendorPacketBuilder::Serialize(const std::shared_ptr<::bluetooth::Packet>& pkt) { ReserveSpace(pkt, size()); // Push the standard avrcp headers PacketBuilder::PushHeader(pkt); // Push the avrcp vendor command headers - log::assert_that(payload_->size() < size_t(0xFFFF), - "payload size bigger than uint16_t"); + log::assert_that(payload_->size() < size_t(0xFFFF), "payload size bigger than uint16_t"); PushHeader(pkt, payload_->size()); // Push the payload for the packet return payload_->Serialize(pkt); } -void VendorPacketBuilder::PushHeader( - const std::shared_ptr<::bluetooth::Packet>& pkt, - uint16_t parameter_length) { +void VendorPacketBuilder::PushHeader(const std::shared_ptr<::bluetooth::Packet>& pkt, + uint16_t parameter_length) { PushCompanyId(pkt, BLUETOOTH_COMPANY_ID); AddPayloadOctets1(pkt, static_cast(pdu_)); AddPayloadOctets1(pkt, static_cast(packet_type_)); AddPayloadOctets2(pkt, base::ByteSwap(parameter_length)); } -bool VendorPacketBuilder::PushAttributeValue( - const std::shared_ptr<::bluetooth::Packet>& pkt, - const AttributeEntry& entry) { - AddPayloadOctets4(pkt, - base::ByteSwap(static_cast(entry.attribute()))); +bool VendorPacketBuilder::PushAttributeValue(const std::shared_ptr<::bluetooth::Packet>& pkt, + const AttributeEntry& entry) { + AddPayloadOctets4(pkt, base::ByteSwap(static_cast(entry.attribute()))); uint16_t character_set = 0x006a; // UTF-8 AddPayloadOctets2(pkt, base::ByteSwap(character_set)); uint16_t value_length = entry.value().length(); @@ -83,9 +74,7 @@ bool VendorPacketBuilder::PushAttributeValue( return true; } -uint32_t VendorPacket::GetCompanyId() const { - return PullCompanyId(begin() + Packet::kMinSize()); -} +uint32_t VendorPacket::GetCompanyId() const { return PullCompanyId(begin() + Packet::kMinSize()); } CommandPdu VendorPacket::GetCommandPdu() const { auto value = *(begin() + Packet::kMinSize() + static_cast(3)); @@ -104,7 +93,9 @@ uint16_t VendorPacket::GetParameterLength() const { } bool VendorPacket::IsValid() const { - if (size() < VendorPacket::kMinSize()) return false; + if (size() < VendorPacket::kMinSize()) { + return false; + } auto start = begin() + VendorPacket::kMinSize(); // Even if end is less than start and a sign extension occurs, thats fine as diff --git a/system/packet/avrcp/vendor_packet.h b/system/packet/avrcp/vendor_packet.h index b9e1f104958..fb28df6136b 100644 --- a/system/packet/avrcp/vendor_packet.h +++ b/system/packet/avrcp/vendor_packet.h @@ -22,37 +22,33 @@ namespace bluetooth { namespace avrcp { class VendorPacketBuilder : public avrcp::PacketBuilder { - public: +public: virtual ~VendorPacketBuilder() = default; static std::unique_ptr MakeBuilder( - CType ctype, CommandPdu pdu, PacketType packet_type, - std::unique_ptr<::bluetooth::PacketBuilder> payload); + CType ctype, CommandPdu pdu, PacketType packet_type, + std::unique_ptr<::bluetooth::PacketBuilder> payload); virtual size_t size() const override; - virtual bool Serialize( - const std::shared_ptr<::bluetooth::Packet>& pkt) override; + virtual bool Serialize(const std::shared_ptr<::bluetooth::Packet>& pkt) override; - protected: +protected: CommandPdu pdu_; PacketType packet_type_; uint16_t param_length_; - void PushHeader(const std::shared_ptr<::bluetooth::Packet>& pkt, - uint16_t parameter_length); + void PushHeader(const std::shared_ptr<::bluetooth::Packet>& pkt, uint16_t parameter_length); // Helper function used a couple other AVRCP packet builders bool PushAttributeValue(const std::shared_ptr<::bluetooth::Packet>& pkt, const AttributeEntry& entry); VendorPacketBuilder(CType ctype, CommandPdu pdu, PacketType packet_type) - : PacketBuilder(ctype, 0x09, 0x00, Opcode::VENDOR), - pdu_(pdu), - packet_type_(packet_type){}; + : PacketBuilder(ctype, 0x09, 0x00, Opcode::VENDOR), pdu_(pdu), packet_type_(packet_type) {} }; class VendorPacket : public avrcp::Packet { - public: +public: virtual ~VendorPacket() = default; /** @@ -69,7 +65,7 @@ class VendorPacket : public avrcp::Packet { * uint16_t parameter_length; * uint8_t[] payload; */ - static constexpr size_t kMinSize() { return Packet::kMinSize() + 7; }; + static constexpr size_t kMinSize() { return Packet::kMinSize() + 7; } // Getter Functions uint32_t GetCompanyId() const; @@ -81,7 +77,7 @@ class VendorPacket : public avrcp::Packet { virtual bool IsValid() const override; virtual std::string ToString() const override; - protected: +protected: using Packet::Packet; }; diff --git a/system/packet/base/iterator.cc b/system/packet/base/iterator.cc index 36235573e1d..1837cf8681b 100644 --- a/system/packet/base/iterator.cc +++ b/system/packet/base/iterator.cc @@ -42,8 +42,7 @@ Iterator Iterator::operator+(size_t offset) { Iterator& Iterator::operator+=(size_t offset) { size_t new_offset = index_ + offset; - index_ = new_offset > packet_->packet_end_index_ ? packet_->packet_end_index_ - : new_offset; + index_ = new_offset > packet_->packet_end_index_ ? packet_->packet_end_index_ : new_offset; return *this; } @@ -51,7 +50,9 @@ Iterator Iterator::operator++(int) { auto itr(*this); index_++; - if (index_ > packet_->packet_end_index_) index_ = packet_->packet_end_index_; + if (index_ > packet_->packet_end_index_) { + index_ = packet_->packet_end_index_; + } return itr; } @@ -59,7 +60,9 @@ Iterator Iterator::operator++(int) { Iterator& Iterator::operator++() { index_++; - if (index_ > packet_->packet_end_index_) index_ = packet_->packet_end_index_; + if (index_ > packet_->packet_end_index_) { + index_ = packet_->packet_end_index_; + } return *this; } @@ -74,21 +77,25 @@ int Iterator::operator-(const Iterator& itr) { return index_ - itr.index_; } Iterator& Iterator::operator-=(size_t offset) { index_ = (index_ < offset || index_ - offset < packet_->packet_start_index_) - ? packet_->packet_start_index_ - : index_ - offset; + ? packet_->packet_start_index_ + : index_ - offset; return *this; } Iterator Iterator::operator--(int) { auto itr(*this); - if (index_ != packet_->packet_start_index_) index_--; + if (index_ != packet_->packet_start_index_) { + index_--; + } return itr; } Iterator& Iterator::operator--() { - if (index_ != packet_->packet_start_index_) index_--; + if (index_ != packet_->packet_start_index_) { + index_--; + } return *this; } @@ -101,25 +108,25 @@ Iterator& Iterator::operator=(const Iterator& itr) { } bool Iterator::operator==(const Iterator& itr) const { - return ((packet_ == itr.packet_) && (index_ == itr.index_)); + return (packet_ == itr.packet_) && (index_ == itr.index_); } bool Iterator::operator!=(const Iterator& itr) const { return !(*this == itr); } bool Iterator::operator<(const Iterator& itr) const { - return ((packet_ == itr.packet_) && (index_ < itr.index_)); + return (packet_ == itr.packet_) && (index_ < itr.index_); } bool Iterator::operator>(const Iterator& itr) const { - return ((packet_ == itr.packet_) && (index_ > itr.index_)); + return (packet_ == itr.packet_) && (index_ > itr.index_); } bool Iterator::operator<=(const Iterator& itr) const { - return ((packet_ == itr.packet_) && (index_ <= itr.index_)); + return (packet_ == itr.packet_) && (index_ <= itr.index_); } bool Iterator::operator>=(const Iterator& itr) const { - return ((packet_ == itr.packet_) && (index_ >= itr.index_)); + return (packet_ == itr.packet_) && (index_ >= itr.index_); } uint8_t Iterator::operator*() const { diff --git a/system/packet/base/iterator.h b/system/packet/base/iterator.h index cfb0f34a275..23d69f14255 100644 --- a/system/packet/base/iterator.h +++ b/system/packet/base/iterator.h @@ -35,13 +35,12 @@ struct IteratorTraits { using reference = uint8_t&; }; #else -struct IteratorTraits - : public std::iterator {}; +struct IteratorTraits : public std::iterator {}; #endif // Iterator is a custom iterator class for Packets. class Iterator : public IteratorTraits { - public: +public: Iterator(std::shared_ptr packet, size_t i); Iterator(const Iterator& itr); @@ -106,7 +105,7 @@ class Iterator : public IteratorTraits { uint32_t extract32() { return extract(); } uint64_t extract64() { return extract(); } - private: +private: std::shared_ptr packet_; size_t index_; }; // Iterator diff --git a/system/packet/base/packet.cc b/system/packet/base/packet.cc index 51d59739dbe..72f4686156f 100644 --- a/system/packet/base/packet.cc +++ b/system/packet/base/packet.cc @@ -26,27 +26,19 @@ namespace bluetooth { size_t Packet::size() const { return packet_end_index_ - packet_start_index_; } -Iterator Packet::begin() const { - return Iterator(shared_from_this(), packet_start_index_); -} +Iterator Packet::begin() const { return Iterator(shared_from_this(), packet_start_index_); } -Iterator Packet::end() const { - return Iterator(shared_from_this(), packet_end_index_); -} +Iterator Packet::end() const { return Iterator(shared_from_this(), packet_end_index_); } // For the Array operator, treat index 0 as the relative start of the packet -uint8_t Packet::operator[](size_t i) { - return get_at_index(i + packet_start_index_); -} +uint8_t Packet::operator[](size_t i) { return get_at_index(i + packet_start_index_); } size_t Packet::get_length() const { return data_->size(); } // Iterators use the absolute index to access data. uint8_t Packet::get_at_index(size_t index) const { - log::assert_that(index >= packet_start_index_, - "assert failed: index >= packet_start_index_"); - log::assert_that(index < packet_end_index_, - "assert failed: index < packet_end_index_"); + log::assert_that(index >= packet_start_index_, "assert failed: index >= packet_start_index_"); + log::assert_that(index < packet_end_index_, "assert failed: index < packet_end_index_"); return data_->at(index); } diff --git a/system/packet/base/packet.h b/system/packet/base/packet.h index 2de22abac21..3126b9f31d9 100644 --- a/system/packet/base/packet.h +++ b/system/packet/base/packet.h @@ -31,23 +31,23 @@ class Packet : public std::enable_shared_from_this { friend class Iterator; friend class PacketBuilder; - public: +public: virtual ~Packet() = default; - protected: +protected: Packet() : packet_start_index_(0), packet_end_index_(0), - data_(std::make_shared>(0)){}; + data_(std::make_shared>(0)) {} Packet(std::shared_ptr pkt, size_t start, size_t end) - : packet_start_index_(start), packet_end_index_(end), data_(pkt->data_){}; + : packet_start_index_(start), packet_end_index_(end), data_(pkt->data_) {} Packet(std::shared_ptr pkt) : data_(pkt->data_) { auto indices = pkt->GetPayloadIndecies(); packet_start_index_ = indices.first; packet_end_index_ = indices.second; - }; + } - public: +public: size_t size() const; class Iterator begin() const; class Iterator end() const; @@ -76,17 +76,16 @@ class Packet : public std::enable_shared_from_this { "Unable to specialize to something that isn't a packet"); static_assert(std::is_convertible::value, "Can not convert between the two packet types."); - return std::shared_ptr( - new T(pkt, pkt->packet_start_index_, pkt->packet_end_index_)); - }; + return std::shared_ptr(new T(pkt, pkt->packet_start_index_, pkt->packet_end_index_)); + } - protected: +protected: // Packet should be immutable other than when building size_t packet_start_index_; size_t packet_end_index_; std::shared_ptr> data_; - private: +private: // Only Available to the iterators virtual size_t get_length() const; virtual uint8_t get_at_index(size_t index) const; diff --git a/system/packet/base/packet_builder.cc b/system/packet/base/packet_builder.cc index b34412e8345..dccef224f9d 100644 --- a/system/packet/base/packet_builder.cc +++ b/system/packet/base/packet_builder.cc @@ -22,15 +22,13 @@ namespace bluetooth { -void PacketBuilder::ReserveSpace(const std::shared_ptr& pkt, - size_t size) { +void PacketBuilder::ReserveSpace(const std::shared_ptr& pkt, size_t size) { pkt->data_->reserve(size); } -bool PacketBuilder::AddPayloadOctets(const std::shared_ptr& pkt, - size_t octets, uint64_t value) { - log::assert_that(octets <= sizeof(uint64_t), - "assert failed: octets <= sizeof(uint64_t)"); +bool PacketBuilder::AddPayloadOctets(const std::shared_ptr& pkt, size_t octets, + uint64_t value) { + log::assert_that(octets <= sizeof(uint64_t), "assert failed: octets <= sizeof(uint64_t)"); for (size_t i = 0; i < octets; i++) { pkt->data_->push_back(value & 0xff); diff --git a/system/packet/base/packet_builder.h b/system/packet/base/packet_builder.h index eb717089cb5..a7f996e2780 100644 --- a/system/packet/base/packet_builder.h +++ b/system/packet/base/packet_builder.h @@ -23,13 +23,13 @@ namespace bluetooth { class Packet; class PacketBuilder { - public: +public: virtual size_t size() const = 0; virtual bool Serialize(const std::shared_ptr& pkt) = 0; virtual ~PacketBuilder() = default; - protected: +protected: // Only Builders should be able to call these void ReserveSpace(const std::shared_ptr& pkt, size_t size); bool AddPayloadOctets1(const std::shared_ptr& pkt, uint8_t value) { @@ -51,12 +51,11 @@ class PacketBuilder { return AddPayloadOctets(pkt, 8, value); } - private: +private: // Add |octets| bytes to the payload. Return true if: // - the value of |value| fits in |octets| bytes and // - the new size of the payload is still < |kMaxPayloadOctets| - bool AddPayloadOctets(const std::shared_ptr& pkt, size_t octets, - uint64_t value); + bool AddPayloadOctets(const std::shared_ptr& pkt, size_t octets, uint64_t value); }; } // namespace bluetooth \ No newline at end of file diff --git a/system/packet/tests/avrcp/avrcp_browse_packet_test.cc b/system/packet/tests/avrcp/avrcp_browse_packet_test.cc index cde0867de27..d5a382514be 100644 --- a/system/packet/tests/avrcp/avrcp_browse_packet_test.cc +++ b/system/packet/tests/avrcp/avrcp_browse_packet_test.cc @@ -14,9 +14,10 @@ * limitations under the License. */ +#include "avrcp_browse_packet.h" + #include -#include "avrcp_browse_packet.h" #include "avrcp_test_packets.h" #include "packet_test_helper.h" @@ -24,23 +25,22 @@ namespace bluetooth { // A helper class that has public accessors to protected methods class TestPacketBuilder : public PacketBuilder { - public: - static std::unique_ptr MakeBuilder( - std::vector data) { +public: + static std::unique_ptr MakeBuilder(std::vector data) { std::unique_ptr builder(new TestPacketBuilder(data)); return builder; - }; + } // Make all the utility functions public - using PacketBuilder::ReserveSpace; using PacketBuilder::AddPayloadOctets1; using PacketBuilder::AddPayloadOctets2; using PacketBuilder::AddPayloadOctets3; using PacketBuilder::AddPayloadOctets4; using PacketBuilder::AddPayloadOctets6; using PacketBuilder::AddPayloadOctets8; + using PacketBuilder::ReserveSpace; - size_t size() const override { return data_.size(); }; + size_t size() const override { return data_.size(); } bool Serialize(const std::shared_ptr& pkt) override { ReserveSpace(pkt, size()); @@ -52,7 +52,7 @@ class TestPacketBuilder : public PacketBuilder { return true; } - TestPacketBuilder(std::vector data) : data_(data){}; + TestPacketBuilder(std::vector data) : data_(data) {} std::vector data_; }; @@ -62,13 +62,12 @@ namespace avrcp { using TestBrowsePacket = TestPacketType; TEST(AvrcpBrowsePacketBuilderTest, buildPacketTest) { - std::vector get_folder_items_request_payload = { - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00}; - auto payload_builder = - TestPacketBuilder::MakeBuilder(get_folder_items_request_payload); + std::vector get_folder_items_request_payload = {0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x03, 0x00}; + auto payload_builder = TestPacketBuilder::MakeBuilder(get_folder_items_request_payload); - auto builder = BrowsePacketBuilder::MakeBuilder(BrowsePdu::GET_FOLDER_ITEMS, - std::move(payload_builder)); + auto builder = + BrowsePacketBuilder::MakeBuilder(BrowsePdu::GET_FOLDER_ITEMS, std::move(payload_builder)); ASSERT_EQ(builder->size(), get_folder_items_request.size()); @@ -86,15 +85,14 @@ TEST(AvrcpBrowsePacketTest, gettersTest) { TEST(AvrcpBrowsePacketTest, payloadBoundsTest) { auto test_browse_packet = TestBrowsePacket::Make(get_folder_items_request); - std::vector get_folder_items_request_payload = { - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00}; + std::vector get_folder_items_request_payload = {0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x03, 0x00}; // Make a folder items payload packet out of the payload of the browse packet auto get_folder_items_payload = TestBrowsePacket::Make(test_browse_packet); for (size_t i = 0; i < get_folder_items_request_payload.size(); i++) { - ASSERT_EQ((*get_folder_items_payload)[i], - get_folder_items_request_payload[i]); + ASSERT_EQ((*get_folder_items_payload)[i], get_folder_items_request_payload[i]); } } diff --git a/system/packet/tests/avrcp/avrcp_packet_test.cc b/system/packet/tests/avrcp/avrcp_packet_test.cc index 8a438b31d5a..222609a0df8 100644 --- a/system/packet/tests/avrcp/avrcp_packet_test.cc +++ b/system/packet/tests/avrcp/avrcp_packet_test.cc @@ -14,9 +14,10 @@ * limitations under the License. */ +#include "avrcp_packet.h" + #include -#include "avrcp_packet.h" #include "avrcp_test_packets.h" #include "packet_test_helper.h" @@ -24,23 +25,22 @@ namespace bluetooth { // A helper class that has public accessors to protected methods class TestPacketBuilder : public PacketBuilder { - public: - static std::unique_ptr MakeBuilder( - std::vector data) { +public: + static std::unique_ptr MakeBuilder(std::vector data) { std::unique_ptr builder(new TestPacketBuilder(data)); return builder; - }; + } // Make all the utility functions public - using PacketBuilder::ReserveSpace; using PacketBuilder::AddPayloadOctets1; using PacketBuilder::AddPayloadOctets2; using PacketBuilder::AddPayloadOctets3; using PacketBuilder::AddPayloadOctets4; using PacketBuilder::AddPayloadOctets6; using PacketBuilder::AddPayloadOctets8; + using PacketBuilder::ReserveSpace; - size_t size() const override { return data_.size(); }; + size_t size() const override { return data_.size(); } bool Serialize(const std::shared_ptr& pkt) override { ReserveSpace(pkt, size()); @@ -52,7 +52,7 @@ class TestPacketBuilder : public PacketBuilder { return true; } - TestPacketBuilder(std::vector data) : data_(data){}; + TestPacketBuilder(std::vector data) : data_(data) {} std::vector data_; }; @@ -62,13 +62,12 @@ namespace avrcp { using TestAvrcpPacket = TestPacketType; TEST(AvrcpPacketBuilderTest, buildPacketTest) { - std::vector get_capabilities_request_payload = { - 0x00, 0x19, 0x58, 0x10, 0x00, 0x00, 0x01, 0x03}; - auto cap_req_builder = - TestPacketBuilder::MakeBuilder(get_capabilities_request_payload); + std::vector get_capabilities_request_payload = {0x00, 0x19, 0x58, 0x10, + 0x00, 0x00, 0x01, 0x03}; + auto cap_req_builder = TestPacketBuilder::MakeBuilder(get_capabilities_request_payload); - auto builder = PacketBuilder::MakeBuilder( - CType::STATUS, 0x09, 0x00, Opcode::VENDOR, std::move(cap_req_builder)); + auto builder = PacketBuilder::MakeBuilder(CType::STATUS, 0x09, 0x00, Opcode::VENDOR, + std::move(cap_req_builder)); ASSERT_EQ(builder->size(), get_capabilities_request.size()); @@ -101,8 +100,7 @@ TEST(AvrcpPacketTest, getterMaskTests) { TEST(AvrcpPacketTest, payloadBoundsTest) { auto test_avrcp_packet = TestAvrcpPacket::Make(get_capabilities_request); - std::vector get_cap_payload_data = {0x00, 0x19, 0x58, 0x10, - 0x00, 0x00, 0x01, 0x03}; + std::vector get_cap_payload_data = {0x00, 0x19, 0x58, 0x10, 0x00, 0x00, 0x01, 0x03}; auto get_cap_payload_packet = TestAvrcpPacket::Make(test_avrcp_packet); diff --git a/system/packet/tests/avrcp/avrcp_reject_packet_test.cc b/system/packet/tests/avrcp/avrcp_reject_packet_test.cc index fb4a3eb3a9a..1a98875651a 100644 --- a/system/packet/tests/avrcp/avrcp_reject_packet_test.cc +++ b/system/packet/tests/avrcp/avrcp_reject_packet_test.cc @@ -14,9 +14,10 @@ * limitations under the License. */ +#include "avrcp_reject_packet.h" + #include -#include "avrcp_reject_packet.h" #include "avrcp_test_packets.h" #include "packet_test_helper.h" @@ -26,9 +27,8 @@ namespace avrcp { using TestAvrcpPacket = TestPacketType; TEST(RejectPacketBuilderTest, buildPacketTest) { - auto builder = RejectBuilder::MakeBuilder( - CommandPdu::LIST_PLAYER_APPLICATION_SETTING_ATTRIBUTES, - Status::INVALID_COMMAND); + auto builder = RejectBuilder::MakeBuilder(CommandPdu::LIST_PLAYER_APPLICATION_SETTING_ATTRIBUTES, + Status::INVALID_COMMAND); ASSERT_EQ(builder->size(), reject_player_app_settings_response.size()); diff --git a/system/packet/tests/avrcp/avrcp_test_packets.h b/system/packet/tests/avrcp/avrcp_test_packets.h index 3abf96a1717..a60f9bc870b 100644 --- a/system/packet/tests/avrcp/avrcp_test_packets.h +++ b/system/packet/tests/avrcp/avrcp_test_packets.h @@ -22,52 +22,49 @@ namespace { // AVRCP Get Capabilities Request packet -std::vector get_capabilities_request = { - 0x01, 0x48, 0x00, 0x00, 0x19, 0x58, 0x10, 0x00, 0x00, 0x01, 0x03}; +std::vector get_capabilities_request = {0x01, 0x48, 0x00, 0x00, 0x19, 0x58, + 0x10, 0x00, 0x00, 0x01, 0x03}; // AVRCP Get Capabilities Request packet with Company ID -std::vector get_capabilities_request_company_id = { - 0x01, 0x48, 0x00, 0x00, 0x19, 0x58, 0x10, 0x00, 0x00, 0x01, 0x02}; +std::vector get_capabilities_request_company_id = {0x01, 0x48, 0x00, 0x00, 0x19, 0x58, + 0x10, 0x00, 0x00, 0x01, 0x02}; // AVRCP Get Capabilities Request packet with Unknown -std::vector get_capabilities_request_unknown = { - 0x01, 0x48, 0x00, 0x00, 0x19, 0x58, 0x10, 0x00, 0x00, 0x01, 0x7f}; +std::vector get_capabilities_request_unknown = {0x01, 0x48, 0x00, 0x00, 0x19, 0x58, + 0x10, 0x00, 0x00, 0x01, 0x7f}; // AVRCP Get Capabilities Response to Company ID request -std::vector get_capabilities_response_company_id = { - 0x0c, 0x48, 0x00, 0x00, 0x19, 0x58, 0x10, 0x00, 0x00, - 0x08, 0x02, 0x02, 0x00, 0x19, 0x58, 0x00, 0x23, 0x45}; +std::vector get_capabilities_response_company_id = {0x0c, 0x48, 0x00, 0x00, 0x19, 0x58, + 0x10, 0x00, 0x00, 0x08, 0x02, 0x02, + 0x00, 0x19, 0x58, 0x00, 0x23, 0x45}; // AVRCP Get Capabilities Response to Events Supported request std::vector get_capabilities_response_events_supported = { - 0x0c, 0x48, 0x00, 0x00, 0x19, 0x58, 0x10, 0x00, - 0x00, 0x05, 0x03, 0x03, 0x01, 0x02, 0x05}; + 0x0c, 0x48, 0x00, 0x00, 0x19, 0x58, 0x10, 0x00, 0x00, 0x05, 0x03, 0x03, 0x01, 0x02, 0x05}; // AVRCP Get Element Attributes request for current playing song and attribute // Title std::vector get_element_attributes_request_partial = { - 0x01, 0x48, 0x00, 0x00, 0x19, 0x58, 0x20, 0x00, 0x00, 0x0d, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01}; + 0x01, 0x48, 0x00, 0x00, 0x19, 0x58, 0x20, 0x00, 0x00, 0x0d, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01}; // AVRCP Get Element Attributes request for current playing song and attributes // Title, Artist, Album, Media Number, Playing Time, Total Number of Media, and // Genre std::vector get_element_attributes_request_full = { - 0x01, 0x48, 0x00, 0x00, 0x19, 0x58, 0x20, 0x00, 0x00, 0x25, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x01, 0x00, - 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x04, 0x00, - 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x06}; - + 0x01, 0x48, 0x00, 0x00, 0x19, 0x58, 0x20, 0x00, 0x00, 0x25, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x01, 0x00, + 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x04, 0x00, + 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x06}; // AVRCP Get Element Attributes request for current playing song and attributes // Title, Artist, Album, Media Number, Playing Time, Total Number of Media, // Genre, and Cover Art std::vector get_element_attributes_request_full_cover_art = { - 0x01, 0x48, 0x00, 0x00, 0x19, 0x58, 0x20, 0x00, 0x00, 0x29, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01, 0x00, - 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x04, 0x00, - 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x06, 0x00, - 0x00, 0x00, 0x08}; + 0x01, 0x48, 0x00, 0x00, 0x19, 0x58, 0x20, 0x00, 0x00, 0x29, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, + 0x02, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x07, + 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x08}; // AVRCP Get Element Attributes response with attribute values as follows // Title: "Test Song" @@ -78,192 +75,167 @@ std::vector get_element_attributes_request_full_cover_art = { // Genre: "Test Genre" // Duration: "1000" std::vector get_elements_attributes_response_full = { - 0x0c, 0x48, 0x00, 0x00, 0x19, 0x58, 0x20, 0x00, 0x00, 0x67, 0x07, 0x00, - 0x00, 0x00, 0x01, 0x00, 0x6a, 0x00, 0x09, 0x54, 0x65, 0x73, 0x74, 0x20, - 0x53, 0x6f, 0x6e, 0x67, 0x00, 0x00, 0x00, 0x02, 0x00, 0x6a, 0x00, 0x0b, - 0x54, 0x65, 0x73, 0x74, 0x20, 0x41, 0x72, 0x74, 0x69, 0x73, 0x74, 0x00, - 0x00, 0x00, 0x03, 0x00, 0x6a, 0x00, 0x0a, 0x54, 0x65, 0x73, 0x74, 0x20, - 0x41, 0x6c, 0x62, 0x75, 0x6d, 0x00, 0x00, 0x00, 0x04, 0x00, 0x6a, 0x00, - 0x01, 0x31, 0x00, 0x00, 0x00, 0x05, 0x00, 0x6a, 0x00, 0x01, 0x32, 0x00, - 0x00, 0x00, 0x06, 0x00, 0x6a, 0x00, 0x0a, 0x54, 0x65, 0x73, 0x74, 0x20, - 0x47, 0x65, 0x6e, 0x72, 0x65, 0x00, 0x00, 0x00, 0x07, 0x00, 0x6a, 0x00, - 0x04, 0x31, 0x30, 0x30, 0x30}; + 0x0c, 0x48, 0x00, 0x00, 0x19, 0x58, 0x20, 0x00, 0x00, 0x67, 0x07, 0x00, 0x00, 0x00, 0x01, + 0x00, 0x6a, 0x00, 0x09, 0x54, 0x65, 0x73, 0x74, 0x20, 0x53, 0x6f, 0x6e, 0x67, 0x00, 0x00, + 0x00, 0x02, 0x00, 0x6a, 0x00, 0x0b, 0x54, 0x65, 0x73, 0x74, 0x20, 0x41, 0x72, 0x74, 0x69, + 0x73, 0x74, 0x00, 0x00, 0x00, 0x03, 0x00, 0x6a, 0x00, 0x0a, 0x54, 0x65, 0x73, 0x74, 0x20, + 0x41, 0x6c, 0x62, 0x75, 0x6d, 0x00, 0x00, 0x00, 0x04, 0x00, 0x6a, 0x00, 0x01, 0x31, 0x00, + 0x00, 0x00, 0x05, 0x00, 0x6a, 0x00, 0x01, 0x32, 0x00, 0x00, 0x00, 0x06, 0x00, 0x6a, 0x00, + 0x0a, 0x54, 0x65, 0x73, 0x74, 0x20, 0x47, 0x65, 0x6e, 0x72, 0x65, 0x00, 0x00, 0x00, 0x07, + 0x00, 0x6a, 0x00, 0x04, 0x31, 0x30, 0x30, 0x30}; // AVRCP Get Play Status Request std::vector get_play_status_request = {0x01, 0x48, 0x00, 0x00, 0x19, 0x58, 0x30, 0x00, 0x00, 0x00}; // AVRCP Get Play Status Response -std::vector get_play_status_response = { - 0x0c, 0x48, 0x00, 0x00, 0x19, 0x58, 0x30, 0x00, 0x00, 0x09, - 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0x00}; +std::vector get_play_status_response = {0x0c, 0x48, 0x00, 0x00, 0x19, 0x58, 0x30, + 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 0x00, + 0xff, 0xff, 0xff, 0xff, 0x00}; // AVRCP List Player Application Setting Attributes Request std::vector list_player_application_setting_attributes_request = { - 0x01, 0x48, 0x00, 0x00, 0x19, 0x58, 0x11, 0x00, 0x00, 0x00}; + 0x01, 0x48, 0x00, 0x00, 0x19, 0x58, 0x11, 0x00, 0x00, 0x00}; // AVRCP List Player Application Setting Attributes Response std::vector list_player_application_setting_attributes_response = { - 0x0c, 0x48, 0x00, 0x00, 0x19, 0x58, 0x11, - 0x00, 0x00, 0x03, 0x02, 0x02, 0x03}; + 0x0c, 0x48, 0x00, 0x00, 0x19, 0x58, 0x11, 0x00, 0x00, 0x03, 0x02, 0x02, 0x03}; // AVRCP List Player Application Setting Attribute Values Request -std::vector list_player_application_setting_attribute_values_request = - {0x01, 0x48, 0x00, 0x00, 0x19, 0x58, 0x12, 0x00, 0x00, 0x01, 0x02}; +std::vector list_player_application_setting_attribute_values_request = { + 0x01, 0x48, 0x00, 0x00, 0x19, 0x58, 0x12, 0x00, 0x00, 0x01, 0x02}; // AVRCP List Player Application Setting Attribute Values - Invalid Setting // Request -std::vector - invalid_setting_list_player_application_setting_attribute_values_request = { +std::vector invalid_setting_list_player_application_setting_attribute_values_request = { 0x01, 0x48, 0x00, 0x00, 0x19, 0x58, 0x12, 0x00, 0x00, 0x01, 0xff}; // AVRCP List Player Application Setting Attribute Values - Invalid Length // Request -std::vector - invalid_length_list_player_application_setting_attribute_values_request = { +std::vector invalid_length_list_player_application_setting_attribute_values_request = { 0x01, 0x48, 0x00, 0x00, 0x19, 0x58, 0x12, 0x00, 0x00, 0x00}; // AVRCP List Player Application Setting Attribute Values Response -std::vector list_player_application_setting_attribute_values_response = - {0x0c, 0x48, 0x00, 0x00, 0x19, 0x58, 0x12, 0x00, - 0x00, 0x05, 0x04, 0x01, 0x02, 0x03, 0x04}; +std::vector list_player_application_setting_attribute_values_response = { + 0x0c, 0x48, 0x00, 0x00, 0x19, 0x58, 0x12, 0x00, 0x00, 0x05, 0x04, 0x01, 0x02, 0x03, 0x04}; // AVRCP Get Current Player Application Setting Value Request std::vector get_current_player_application_setting_value_request = { - 0x01, 0x48, 0x00, 0x00, 0x19, 0x58, 0x13, - 0x00, 0x00, 0x03, 0x02, 0x02, 0x03}; + 0x01, 0x48, 0x00, 0x00, 0x19, 0x58, 0x13, 0x00, 0x00, 0x03, 0x02, 0x02, 0x03}; // AVRCP Get Current Player Application Setting Value - Invalid Setting // Request -std::vector - invalid_setting_get_current_player_application_setting_value_request = { - 0x01, 0x48, 0x00, 0x00, 0x19, 0x58, 0x13, - 0x00, 0x00, 0x03, 0x02, 0x02, 0x7f}; +std::vector invalid_setting_get_current_player_application_setting_value_request = { + 0x01, 0x48, 0x00, 0x00, 0x19, 0x58, 0x13, 0x00, 0x00, 0x03, 0x02, 0x02, 0x7f}; // AVRCP Get Current Player Application Setting Value - Invalid Length // Request -std::vector - invalid_length_get_current_player_application_setting_value_request = { +std::vector invalid_length_get_current_player_application_setting_value_request = { 0x01, 0x48, 0x00, 0x00, 0x19, 0x58, 0x13, 0x00, 0x00, 0x00}; // AVRCP Get Current Player Application Setting Value Response std::vector get_current_player_application_setting_value_response = { - 0x0c, 0x48, 0x00, 0x00, 0x19, 0x58, 0x13, 0x00, - 0x00, 0x05, 0x02, 0x02, 0x01, 0x03, 0x01}; + 0x0c, 0x48, 0x00, 0x00, 0x19, 0x58, 0x13, 0x00, 0x00, 0x05, 0x02, 0x02, 0x01, 0x03, 0x01}; // AVRCP Set Player Application Setting Value Request std::vector set_player_application_setting_value_request = { - 0x00, 0x48, 0x00, 0x00, 0x19, 0x58, 0x14, 0x00, - 0x00, 0x05, 0x02, 0x02, 0x01, 0x03, 0x01}; + 0x00, 0x48, 0x00, 0x00, 0x19, 0x58, 0x14, 0x00, 0x00, 0x05, 0x02, 0x02, 0x01, 0x03, 0x01}; // AVRCP Set Player Application Setting Value Request - Invalid Setting // Request -std::vector - invalid_setting_set_player_application_setting_value_request = { - 0x00, 0x48, 0x00, 0x00, 0x19, 0x58, 0x14, 0x00, - 0x00, 0x05, 0x02, 0x02, 0x01, 0x7f, 0x01}; +std::vector invalid_setting_set_player_application_setting_value_request = { + 0x00, 0x48, 0x00, 0x00, 0x19, 0x58, 0x14, 0x00, 0x00, 0x05, 0x02, 0x02, 0x01, 0x7f, 0x01}; // AVRCP Set Player Application Setting Value Request - Invalid Value // Request -std::vector - invalid_value_set_player_application_setting_value_request = { - 0x00, 0x48, 0x00, 0x00, 0x19, 0x58, 0x14, 0x00, - 0x00, 0x05, 0x02, 0x02, 0x01, 0x03, 0x7f}; +std::vector invalid_value_set_player_application_setting_value_request = { + 0x00, 0x48, 0x00, 0x00, 0x19, 0x58, 0x14, 0x00, 0x00, 0x05, 0x02, 0x02, 0x01, 0x03, 0x7f}; // AVRCP Set Player Application Setting Value Request - Invalid Length // Request -std::vector - invalid_length_set_player_application_setting_value_request = { +std::vector invalid_length_set_player_application_setting_value_request = { 0x00, 0x48, 0x00, 0x00, 0x19, 0x58, 0x14, 0x00, 0x00, 0x00}; // AVRCP Set Player Application Setting Value Response -std::vector set_player_application_setting_value_response = { - 0x09, 0x48, 0x00, 0x00, 0x19, 0x58, 0x14, 0x00, 0x00, 0x00}; +std::vector set_player_application_setting_value_response = {0x09, 0x48, 0x00, 0x00, 0x19, + 0x58, 0x14, 0x00, 0x00, 0x00}; // AVRCP Pass Through Command Play Pushed Request -std::vector pass_through_command_play_pushed = {0x00, 0x48, 0x7c, 0x44, - 0x00}; +std::vector pass_through_command_play_pushed = {0x00, 0x48, 0x7c, 0x44, 0x00}; // AVRCP Pass Through Command Play Pushed Response -std::vector pass_through_command_play_released = {0x09, 0x48, 0x7c, - 0xc4, 0x00}; +std::vector pass_through_command_play_released = {0x09, 0x48, 0x7c, 0xc4, 0x00}; // AVRCP Register Playback Status Notification std::vector register_play_status_notification = { - 0x03, 0x48, 0x00, 0x00, 0x19, 0x58, 0x31, 0x00, - 0x00, 0x05, 0x01, 0x00, 0x00, 0x00, 0x05}; + 0x03, 0x48, 0x00, 0x00, 0x19, 0x58, 0x31, 0x00, 0x00, 0x05, 0x01, 0x00, 0x00, 0x00, 0x05}; // AVRCP Register Volume Changed Notification std::vector register_volume_changed_notification = { - 0x03, 0x48, 0x00, 0x00, 0x19, 0x58, 0x31, 0x00, - 0x00, 0x05, 0x0d, 0x00, 0x00, 0x00, 0x00}; + 0x03, 0x48, 0x00, 0x00, 0x19, 0x58, 0x31, 0x00, 0x00, 0x05, 0x0d, 0x00, 0x00, 0x00, 0x00}; // AVRCP Register Notification without any parameter std::vector register_notification_invalid = {0x03, 0x48, 0x00, 0x00, 0x19, 0x58, 0x31, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00}; // AVRCP Interim Playback Status Notification -std::vector interim_play_status_notification = { - 0x0f, 0x48, 0x00, 0x00, 0x19, 0x58, 0x31, 0x00, 0x00, 0x02, 0x01, 0x00}; +std::vector interim_play_status_notification = {0x0f, 0x48, 0x00, 0x00, 0x19, 0x58, + 0x31, 0x00, 0x00, 0x02, 0x01, 0x00}; // AVRCP Interim Track Changed Notification -std::vector interim_track_changed_notification = { - 0x0f, 0x48, 0x00, 0x00, 0x19, 0x58, 0x31, 0x00, 0x00, 0x09, - 0x02, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}; +std::vector interim_track_changed_notification = {0x0f, 0x48, 0x00, 0x00, 0x19, 0x58, 0x31, + 0x00, 0x00, 0x09, 0x02, 0x01, 0x02, 0x03, + 0x04, 0x05, 0x06, 0x07, 0x08}; // AVRCP Changed Playback Position Notification std::vector changed_play_pos_notification = { - 0x0d, 0x48, 0x00, 0x00, 0x19, 0x58, 0x31, 0x00, - 0x00, 0x05, 0x05, 0x00, 0x00, 0x00, 0x00}; + 0x0d, 0x48, 0x00, 0x00, 0x19, 0x58, 0x31, 0x00, 0x00, 0x05, 0x05, 0x00, 0x00, 0x00, 0x00}; // AVRCP Interim Changed Player Setting Notification std::vector interim_changed_player_setting_notification = { - 0x0f, 0x48, 0x00, 0x00, 0x19, 0x58, 0x31, 0x00, 0x00, 0x0a, - 0x08, 0x04, 0x01, 0x01, 0x02, 0x01, 0x03, 0x01, 0x04, 0x01}; + 0x0f, 0x48, 0x00, 0x00, 0x19, 0x58, 0x31, 0x00, 0x00, 0x0a, + 0x08, 0x04, 0x01, 0x01, 0x02, 0x01, 0x03, 0x01, 0x04, 0x01}; // AVRCP Changed Player Setting Notification -std::vector changed_player_setting_notification = { - 0x0d, 0x48, 0x00, 0x00, 0x19, 0x58, 0x31, 0x00, - 0x00, 0x06, 0x08, 0x02, 0x02, 0x01, 0x03, 0x02}; +std::vector changed_player_setting_notification = {0x0d, 0x48, 0x00, 0x00, 0x19, 0x58, + 0x31, 0x00, 0x00, 0x06, 0x08, 0x02, + 0x02, 0x01, 0x03, 0x02}; // AVRCP Interim Now Playing Changed Notification -std::vector interim_now_playing_notification = { - 0x0f, 0x48, 0x00, 0x00, 0x19, 0x58, 0x31, 0x00, 0x00, 0x01, 0x09}; +std::vector interim_now_playing_notification = {0x0f, 0x48, 0x00, 0x00, 0x19, 0x58, + 0x31, 0x00, 0x00, 0x01, 0x09}; // AVRCP Interim Available Players Changed Notification -std::vector interim_available_players_notification = { - 0x0f, 0x48, 0x00, 0x00, 0x19, 0x58, 0x31, 0x00, 0x00, 0x01, 0x0a}; +std::vector interim_available_players_notification = {0x0f, 0x48, 0x00, 0x00, 0x19, 0x58, + 0x31, 0x00, 0x00, 0x01, 0x0a}; // AVRCP Interim Addressed Player Changed Notification with active // player ID 1 std::vector interim_addressed_player_notification = { - 0x0f, 0x48, 0x00, 0x00, 0x19, 0x58, 0x31, 0x00, - 0x00, 0x05, 0x0b, 0x00, 0x01, 0x00, 0x00}; + 0x0f, 0x48, 0x00, 0x00, 0x19, 0x58, 0x31, 0x00, 0x00, 0x05, 0x0b, 0x00, 0x01, 0x00, 0x00}; // AVRCP Interim UIDs Changed Notification -std::vector interim_uids_notificaiton = {0x0f, 0x48, 0x00, 0x00, 0x19, - 0x58, 0x31, 0x00, 0x00, 0x03, - 0x0c, 0x00, 0x00}; +std::vector interim_uids_notification = {0x0f, 0x48, 0x00, 0x00, 0x19, 0x58, 0x31, + 0x00, 0x00, 0x03, 0x0c, 0x00, 0x00}; // AVRCP Interim Volume Changed Notification with volume at 55% (0x47) -std::vector interim_volume_changed_notification = { - 0x0f, 0x48, 0x00, 0x00, 0x19, 0x58, 0x31, 0x00, 0x00, 0x02, 0x0d, 0x47}; +std::vector interim_volume_changed_notification = {0x0f, 0x48, 0x00, 0x00, 0x19, 0x58, + 0x31, 0x00, 0x00, 0x02, 0x0d, 0x47}; // AVRCP Rejected Volume Changed Notification with volume at 0% -std::vector rejected_volume_changed_notification = { - 0x0a, 0x48, 0x00, 0x00, 0x19, 0x58, 0x31, 0x00, 0x00, 0x02, 0x0d, 0x00}; +std::vector rejected_volume_changed_notification = {0x0a, 0x48, 0x00, 0x00, 0x19, 0x58, + 0x31, 0x00, 0x00, 0x02, 0x0d, 0x00}; // AVRCP Changed Volume Changed Notification with volume at 55% (0x47) -std::vector changed_volume_changed_notification = { - 0x0d, 0x48, 0x00, 0x00, 0x19, 0x58, 0x31, 0x00, 0x00, 0x02, 0x0d, 0x47}; +std::vector changed_volume_changed_notification = {0x0d, 0x48, 0x00, 0x00, 0x19, 0x58, + 0x31, 0x00, 0x00, 0x02, 0x0d, 0x47}; // AVRCP Reject List Player Application Settings Response -std::vector reject_player_app_settings_response = { - 0x0a, 0x48, 0x00, 0x00, 0x19, 0x58, 0x11, 0x00, 0x00, 0x01, 0x00}; +std::vector reject_player_app_settings_response = {0x0a, 0x48, 0x00, 0x00, 0x19, 0x58, + 0x11, 0x00, 0x00, 0x01, 0x00}; // AVRCP Browse General Reject packet for invalid PDU ID -std::vector general_reject_invalid_command_packet = {0xa0, 0x00, 0x01, - 0x00}; +std::vector general_reject_invalid_command_packet = {0xa0, 0x00, 0x01, 0x00}; // AVRCP Browse Get Folder Items Request packet for media players with // the following data: @@ -271,9 +243,8 @@ std::vector general_reject_invalid_command_packet = {0xa0, 0x00, 0x01, // start_item = 0x00 // end_item = 0x03 // attributes_requested: all -std::vector get_folder_items_request = {0x71, 0x00, 0x0a, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x03, 0x00}; +std::vector get_folder_items_request = {0x71, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x03, 0x00}; // AVRCP Browse Get Folder Items Request packet for media players with // the following data: @@ -281,9 +252,8 @@ std::vector get_folder_items_request = {0x71, 0x00, 0x0a, 0x00, 0x00, // start_item = 0x00 // end_item = 0x09 // attributes_requested: none -std::vector get_folder_items_request_no_attrs = { - 0x71, 0x00, 0x0a, 0x01, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x09, 0xff}; +std::vector get_folder_items_request_no_attrs = {0x71, 0x00, 0x0a, 0x01, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x09, 0xff}; // AVRCP Browse Get Folder Items Request packet for media players with // the following data: @@ -291,9 +261,9 @@ std::vector get_folder_items_request_no_attrs = { // start_item = 0x00 // end_item = 0x09 // attributes_requested: Title -std::vector get_folder_items_request_title = { - 0x71, 0x00, 0x0e, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x09, 0x01, 0x00, 0x00, 0x00, 0x1}; +std::vector get_folder_items_request_title = {0x71, 0x00, 0x0e, 0x01, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, + 0x01, 0x00, 0x00, 0x00, 0x1}; // AVRCP Browse Get Folder Items Request packet for vfs with // the following data: @@ -301,9 +271,9 @@ std::vector get_folder_items_request_title = { // start_item = 0x00 // end_item = 0x05 // attributes_requested: TITLE -std::vector get_folder_items_request_vfs = { - 0x71, 0x00, 0x0e, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x05, 0x01, 0x00, 0x00, 0x00, 0x01}; +std::vector get_folder_items_request_vfs = {0x71, 0x00, 0x0e, 0x01, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, + 0x01, 0x00, 0x00, 0x00, 0x01}; // AVRCP Browse Get Folder Items Request packet for now playing with // the following data: @@ -311,8 +281,8 @@ std::vector get_folder_items_request_vfs = { // start_item = 0x00 // end_item = 0x05 // attributes_requested: All Items -std::vector get_folder_items_request_now_playing = {0x71, 0x00, 0x0a, 0x03, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x05, 0x00}; +std::vector get_folder_items_request_now_playing = { + 0x71, 0x00, 0x0a, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00}; // AVRCP Browse Get Folder Items Response packet with range out of bounds error std::vector get_folder_items_error_response = {0x71, 0x00, 0x01, 0x0b}; @@ -323,12 +293,11 @@ std::vector get_folder_items_error_response = {0x71, 0x00, 0x01, 0x0b}; // name = "com.google.android.music" // browsing_supported = true std::vector get_folder_items_media_player_response = { - 0x71, 0x00, 0x3c, 0x04, 0x00, 0x00, 0x00, 0x01, 0x01, 0x00, 0x34, - 0x00, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, - 0x00, 0x00, 0xb7, 0x01, 0x0c, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x6a, 0x00, 0x18, 0x63, 0x6f, 0x6d, 0x2e, 0x67, - 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x6e, 0x64, 0x72, 0x6f, - 0x69, 0x64, 0x2e, 0x6d, 0x75, 0x73, 0x69, 0x63}; + 0x71, 0x00, 0x3c, 0x04, 0x00, 0x00, 0x00, 0x01, 0x01, 0x00, 0x34, 0x00, 0x01, + 0x01, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xb7, 0x01, + 0x0c, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6a, 0x00, 0x18, + 0x63, 0x6f, 0x6d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x6e, + 0x64, 0x72, 0x6f, 0x69, 0x64, 0x2e, 0x6d, 0x75, 0x73, 0x69, 0x63}; // AVRCP Browse Get Folder Items Response packet with one folder // with the following fields: @@ -337,9 +306,9 @@ std::vector get_folder_items_media_player_response = { // name = "Test Folder" // is_playable = true std::vector get_folder_items_folder_response = { - 0x71, 0x00, 0x21, 0x04, 0x00, 0x00, 0x00, 0x01, 0x02, 0x00, 0x19, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x6a, 0x00, - 0x0b, 0x54, 0x65, 0x73, 0x74, 0x20, 0x46, 0x6f, 0x6c, 0x64, 0x65, 0x72}; + 0x71, 0x00, 0x21, 0x04, 0x00, 0x00, 0x00, 0x01, 0x02, 0x00, 0x19, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x6a, 0x00, + 0x0b, 0x54, 0x65, 0x73, 0x74, 0x20, 0x46, 0x6f, 0x6c, 0x64, 0x65, 0x72}; // AVRCP Browse Get Folder Items Response packet with one song // with the following fields: @@ -347,25 +316,21 @@ std::vector get_folder_items_folder_response = { // name = "Test Title" // attribute[TITLE] = "Test Title" std::vector get_folder_items_song_response = { - 0x71, 0x00, 0x32, 0x04, 0x00, 0x00, 0x00, 0x01, 0x03, 0x00, 0x2a, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x6a, - 0x00, 0x0a, 0x54, 0x65, 0x73, 0x74, 0x20, 0x54, 0x69, 0x74, 0x6c, - 0x65, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x6a, 0x00, 0x0a, 0x54, - 0x65, 0x73, 0x74, 0x20, 0x54, 0x69, 0x74, 0x6c, 0x65}; + 0x71, 0x00, 0x32, 0x04, 0x00, 0x00, 0x00, 0x01, 0x03, 0x00, 0x2a, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x6a, 0x00, 0x0a, 0x54, 0x65, 0x73, 0x74, + 0x20, 0x54, 0x69, 0x74, 0x6c, 0x65, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x6a, 0x00, + 0x0a, 0x54, 0x65, 0x73, 0x74, 0x20, 0x54, 0x69, 0x74, 0x6c, 0x65}; // AVRCP Browse Change Path Request down to folder with UID 0x0000000000000002 -std::vector change_path_request = {0x72, 0x00, 0x0b, 0x00, 0x00, - 0x01, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x02}; +std::vector change_path_request = {0x72, 0x00, 0x0b, 0x00, 0x00, 0x01, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02}; // AVRCP Browse Change Path Request up -std::vector change_path_up_request = {0x72, 0x00, 0x0b, 0x00, 0x00, - 0x00, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF}; +std::vector change_path_up_request = {0x72, 0x00, 0x0b, 0x00, 0x00, 0x00, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; // AVRCP Browse Change Path Response with two items in current folder -std::vector change_path_response = {0x72, 0x00, 0x05, 0x04, - 0x00, 0x00, 0x00, 0x02}; +std::vector change_path_response = {0x72, 0x00, 0x05, 0x04, 0x00, 0x00, 0x00, 0x02}; // AVRCP Browse Change Path Response with an error of invalid direction std::vector change_path_error_response = {0x72, 0x00, 0x01, 0x07}; @@ -376,10 +341,9 @@ std::vector change_path_error_response = {0x72, 0x00, 0x01, 0x07}; // uid_counter = 0x0000 // uid = 0x0000000000000001 std::vector get_item_attributes_request_all_attributes = { - 0x73, 0x00, 0x28, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x01, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, - 0x02, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, - 0x00, 0x05, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x07}; + 0x73, 0x00, 0x28, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x07, + 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, + 0x04, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x07}; // AVRCP Get Item Attributes request with all attributes requested // with the following fields: @@ -389,11 +353,10 @@ std::vector get_item_attributes_request_all_attributes = { // attributes = Title, Artist, Album, Media Number, Playing Time, // Total Number of Media, Genre, and Cover Art std::vector get_item_attributes_request_all_attributes_with_cover_art = { - 0x73, 0x00, 0x2C, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x01, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, - 0x02, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, - 0x00, 0x05, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x07, 0x00, - 0x00, 0x00, 0x08}; + 0x73, 0x00, 0x2C, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, + 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, + 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x05, 0x00, + 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x08}; // AVRCP Get Item Attributes request with all attributes requested // with the following fields: @@ -401,97 +364,93 @@ std::vector get_item_attributes_request_all_attributes_with_cover_art = // uid_counter = 0x0001 // uid = 0x0000000000000001 std::vector get_item_attributes_request_all_attributes_invalid = { - 0x73, 0x00, 0x28, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x01, 0x00, 0x01, 0x07, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, - 0x02, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, - 0x00, 0x05, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x07}; + 0x73, 0x00, 0x28, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x07, + 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, + 0x04, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x07}; // AVRCP Get Item Attributes Response with the following attributes: // title = "Test Song" // artist = "Test Artist" // album = "Test Album" std::vector get_item_attributes_song_response = { - 0x73, 0x00, 0x38, 0x04, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x6a, 0x00, - 0x09, 0x54, 0x65, 0x73, 0x74, 0x20, 0x53, 0x6f, 0x6e, 0x67, 0x00, 0x00, - 0x00, 0x02, 0x00, 0x6a, 0x00, 0x0b, 0x54, 0x65, 0x73, 0x74, 0x20, 0x41, - 0x72, 0x74, 0x69, 0x73, 0x74, 0x00, 0x00, 0x00, 0x03, 0x00, 0x6a, 0x00, - 0x0a, 0x54, 0x65, 0x73, 0x74, 0x20, 0x41, 0x6c, 0x62, 0x75, 0x6d}; + 0x73, 0x00, 0x38, 0x04, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x6a, 0x00, 0x09, 0x54, 0x65, + 0x73, 0x74, 0x20, 0x53, 0x6f, 0x6e, 0x67, 0x00, 0x00, 0x00, 0x02, 0x00, 0x6a, 0x00, 0x0b, + 0x54, 0x65, 0x73, 0x74, 0x20, 0x41, 0x72, 0x74, 0x69, 0x73, 0x74, 0x00, 0x00, 0x00, 0x03, + 0x00, 0x6a, 0x00, 0x0a, 0x54, 0x65, 0x73, 0x74, 0x20, 0x41, 0x6c, 0x62, 0x75, 0x6d}; // AVRCP Set Addressed Player Request with player_id = 0 -std::vector set_addressed_player_request = { - 0x00, 0x48, 0x00, 0x00, 0x19, 0x58, 0x60, 0x00, 0x00, 0x02, 0x00, 0x00}; +std::vector set_addressed_player_request = {0x00, 0x48, 0x00, 0x00, 0x19, 0x58, + 0x60, 0x00, 0x00, 0x02, 0x00, 0x00}; // AVRCP Set Addressed Player Request with player_id = 1 -std::vector set_addressed_player_id_1_request = { - 0x00, 0x48, 0x00, 0x00, 0x19, 0x58, 0x60, 0x00, 0x00, 0x02, 0x00, 0x01}; +std::vector set_addressed_player_id_1_request = {0x00, 0x48, 0x00, 0x00, 0x19, 0x58, + 0x60, 0x00, 0x00, 0x02, 0x00, 0x01}; // AVRCP Set Addressed Player Response with status success -std::vector set_addressed_player_response = { - 0x09, 0x48, 0x00, 0x00, 0x19, 0x58, 0x60, 0x00, 0x00, 0x01, 0x04}; +std::vector set_addressed_player_response = {0x09, 0x48, 0x00, 0x00, 0x19, 0x58, + 0x60, 0x00, 0x00, 0x01, 0x04}; // AVRCP Set Browsed Player Request with player_id = 2 -std::vector set_browsed_player_request = {0x70, 0x00, 0x02, 0x00, - 0x02}; +std::vector set_browsed_player_request = {0x70, 0x00, 0x02, 0x00, 0x02}; // AVRCP Set Browsed Player Request with player_id = 0 -std::vector set_browsed_player_id_0_request = {0x70, 0x00, 0x02, 0x00, - 0x00}; +std::vector set_browsed_player_id_0_request = {0x70, 0x00, 0x02, 0x00, 0x00}; // AVRCP Set Browsed Player Response with num items = 4 and depth = 0 -std::vector set_browsed_player_response = { - 0x70, 0x00, 0x0a, 0x04, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x04, 0x00, 0x6a, 0x00}; +std::vector set_browsed_player_response = {0x70, 0x00, 0x0a, 0x04, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x04, 0x00, 0x6a, 0x00}; // AVRCP Get Total Number of Items Request with Scope = Media Player List -std::vector get_total_number_of_items_request_media_players = { - 0x75, 0x00, 0x01, 0x00}; +std::vector get_total_number_of_items_request_media_players = {0x75, 0x00, 0x01, 0x00}; // AVRCP Get Total Number of Items Request with Scope = VFS -std::vector get_total_number_of_items_request_vfs = {0x75, 0x00, 0x01, - 0x01}; +std::vector get_total_number_of_items_request_vfs = {0x75, 0x00, 0x01, 0x01}; // AVRCP Get Total Number of Items Request with Scope = Now Playing List -std::vector get_total_number_of_items_request_now_playing = { - 0x75, 0x00, 0x01, 0x03}; +std::vector get_total_number_of_items_request_now_playing = {0x75, 0x00, 0x01, 0x03}; // AVRCP Get Total number of Items Response with 5 items in folder -std::vector get_total_number_of_items_response = { - 0x75, 0x00, 0x07, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05}; +std::vector get_total_number_of_items_response = {0x75, 0x00, 0x07, 0x04, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x05}; // AVRCP Play Item Request with scope = Now Playing and // UID = 0x0000000000000003 -std::vector play_item_request = { - 0x00, 0x48, 0x00, 0x00, 0x19, 0x58, 0x74, 0x00, 0x00, 0x0b, 0x03, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00}; +std::vector play_item_request = {0x00, 0x48, 0x00, 0x00, 0x19, 0x58, 0x74, + 0x00, 0x00, 0x0b, 0x03, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00}; // AVRCP Play Item Response std::vector play_item_response = {0x09, 0x48, 0x00, 0x00, 0x19, 0x58, 0x74, 0x00, 0x00, 0x01, 0x04}; // AVRCP Set Absolute Volume Request with volume at 56% (0x48) -std::vector set_absolute_volume_request = { - 0x00, 0x48, 0x00, 0x00, 0x19, 0x58, 0x50, 0x00, 0x00, 0x01, 0x48}; +std::vector set_absolute_volume_request = {0x00, 0x48, 0x00, 0x00, 0x19, 0x58, + 0x50, 0x00, 0x00, 0x01, 0x48}; // AVRCP Set Absolute Volume Response with voume at 52% (0x43) -std::vector set_absolute_volume_response = { - 0x09, 0x48, 0x00, 0x00, 0x19, 0x58, 0x50, 0x00, 0x00, 0x01, 0x43}; +std::vector set_absolute_volume_response = {0x09, 0x48, 0x00, 0x00, 0x19, 0x58, + 0x50, 0x00, 0x00, 0x01, 0x43}; // Invalid Packets // Short Vendor Packet -std::vector short_vendor_packet = {0x01, 0x48, 0x00, 0x00, 0x19, 0x58, 0x10, 0x00, 0x00, 0x01}; +std::vector short_vendor_packet = {0x01, 0x48, 0x00, 0x00, 0x19, + 0x58, 0x10, 0x00, 0x00, 0x01}; // Short Get Capabilities Request Packet -std::vector short_get_capabilities_request = {0x01, 0x48, 0x00, 0x00, 0x19, 0x58, 0x10, 0x00, 0x00, 0x00}; +std::vector short_get_capabilities_request = {0x01, 0x48, 0x00, 0x00, 0x19, + 0x58, 0x10, 0x00, 0x00, 0x00}; // Short Get Element Attributes Request Packet std::vector short_get_element_attributes_request = {0x01, 0x48, 0x00, 0x00, 0x19, 0x58, 0x20, 0x00, 0x00, 0x00}; // Short Play Item Request Packet -std::vector short_play_item_request = {0x00, 0x48, 0x00, 0x00, 0x19, 0x58, 0x74, 0x00, 0x00, 0x00}; +std::vector short_play_item_request = {0x00, 0x48, 0x00, 0x00, 0x19, + 0x58, 0x74, 0x00, 0x00, 0x00}; // Short Set Addressed Player Request Packet -std::vector short_set_addressed_player_request = {0x00, 0x48, 0x00, 0x00, 0x19, 0x58, 0x60, 0x00, 0x00, 0x00}; +std::vector short_set_addressed_player_request = {0x00, 0x48, 0x00, 0x00, 0x19, + 0x58, 0x60, 0x00, 0x00, 0x00}; // Short Browse Packet std::vector short_browse_packet = {0x71, 0x00, 0x0a}; diff --git a/system/packet/tests/avrcp/change_path_packet_test.cc b/system/packet/tests/avrcp/change_path_packet_test.cc index c114f6ff1ae..49281b7c313 100644 --- a/system/packet/tests/avrcp/change_path_packet_test.cc +++ b/system/packet/tests/avrcp/change_path_packet_test.cc @@ -38,8 +38,7 @@ TEST(ChangePathResponseBuilderTest, builderTest) { TEST(ChangePathResponseBuilderTest, builderErrorStatusTest) { // NOTE: The num items in folder field doesn't matter when the status is // not NO_ERROR - auto builder = - ChangePathResponseBuilder::MakeBuilder(Status::INVALID_DIRECTION, 2); + auto builder = ChangePathResponseBuilder::MakeBuilder(Status::INVALID_DIRECTION, 2); ASSERT_EQ(builder->size(), change_path_error_response.size()); auto test_packet = TestChangePathReqPacket::Make(); diff --git a/system/packet/tests/avrcp/general_reject_packet_test.cc b/system/packet/tests/avrcp/general_reject_packet_test.cc index 4d73dbaeda8..aeda62d1d36 100644 --- a/system/packet/tests/avrcp/general_reject_packet_test.cc +++ b/system/packet/tests/avrcp/general_reject_packet_test.cc @@ -14,10 +14,11 @@ * limitations under the License. */ +#include "general_reject_packet.h" + #include #include "avrcp_test_packets.h" -#include "general_reject_packet.h" #include "packet_test_helper.h" namespace bluetooth { diff --git a/system/packet/tests/avrcp/get_capabilities_packet_test.cc b/system/packet/tests/avrcp/get_capabilities_packet_test.cc index 4e4c195d08e..114992d8918 100644 --- a/system/packet/tests/avrcp/get_capabilities_packet_test.cc +++ b/system/packet/tests/avrcp/get_capabilities_packet_test.cc @@ -30,8 +30,7 @@ using GetCapRequestTestPacket = TestPacketType; TEST(GetCapabilitiesRequestPacketTest, getterTest) { auto test_packet = GetCapRequestTestPacket::Make(get_capabilities_request); - ASSERT_EQ(test_packet->GetCapabilityRequested(), - Capability::EVENTS_SUPPORTED); + ASSERT_EQ(test_packet->GetCapabilityRequested(), Capability::EVENTS_SUPPORTED); } TEST(GetCapabilitiesRequestPacketTest, validTest) { @@ -46,7 +45,7 @@ TEST(GetCapabilitiesRequestPacketTest, invalidTest) { ASSERT_FALSE(test_packet->IsValid()); std::vector short_packet = { - 0, 1, 2, 3, 4, 5, 6, + 0, 1, 2, 3, 4, 5, 6, }; test_packet = GetCapRequestTestPacket::Make(short_packet); ASSERT_FALSE(test_packet->IsValid()); @@ -63,7 +62,7 @@ TEST(GetCapabilityResponseBuilder, builderLengthTest) { ASSERT_EQ(builder->size(), 21u); builder = GetCapabilitiesResponseBuilder::MakeEventsSupportedBuilder( - Event::PLAYBACK_STATUS_CHANGED); + Event::PLAYBACK_STATUS_CHANGED); ASSERT_EQ(builder->size(), 13u); builder->AddEvent(Event::TRACK_CHANGED); ASSERT_EQ(builder->size(), 14u); @@ -79,7 +78,7 @@ TEST(GetCapabilityResponseBuilder, duplicateAddTest) { ASSERT_EQ(builder->size(), 15u); builder = GetCapabilitiesResponseBuilder::MakeEventsSupportedBuilder( - Event::PLAYBACK_STATUS_CHANGED); + Event::PLAYBACK_STATUS_CHANGED); ASSERT_EQ(builder->size(), 13u); builder->AddEvent(Event::PLAYBACK_STATUS_CHANGED); ASSERT_EQ(builder->size(), 13u); @@ -98,13 +97,12 @@ TEST(GetCapabilityResponseBuilderDeathTest, mismatchAddDeathTest) { } builder = GetCapabilitiesResponseBuilder::MakeEventsSupportedBuilder( - Event::PLAYBACK_STATUS_CHANGED); + Event::PLAYBACK_STATUS_CHANGED); // this will silent SIGABRT sent in ASSERT_DEATH below ScopedSilentDeath _silentDeath; - ASSERT_DEATH(builder->AddCompanyId(0x000000), - "capability_ == Capability::COMPANY_ID"); + ASSERT_DEATH(builder->AddCompanyId(0x000000), "capability_ == Capability::COMPANY_ID"); } // Test building a GetCapabilities Response to a Company ID request @@ -120,7 +118,7 @@ TEST(GetCapabilityResponseBuilder, comanyIdBuilderTest) { // Test building a GetCapabilities Response to an Events Supported request TEST(GetCapabilityResponseBuilder, eventsSupportedBuilderTest) { auto builder = GetCapabilitiesResponseBuilder::MakeEventsSupportedBuilder( - Event::PLAYBACK_STATUS_CHANGED); + Event::PLAYBACK_STATUS_CHANGED); builder->AddEvent(Event::TRACK_CHANGED); builder->AddEvent(Event::PLAYBACK_POS_CHANGED); diff --git a/system/packet/tests/avrcp/get_current_player_application_setting_value_test.cc b/system/packet/tests/avrcp/get_current_player_application_setting_value_test.cc index de380b5e137..8c9a775d0e7 100644 --- a/system/packet/tests/avrcp/get_current_player_application_setting_value_test.cc +++ b/system/packet/tests/avrcp/get_current_player_application_setting_value_test.cc @@ -25,16 +25,13 @@ namespace bluetooth { namespace avrcp { using GetCurrentPlayerApplicationSettingValueRequestTestPacket = - TestPacketType; -using GetCurrentPlayerApplicationSettingValueRspTestPacket = - TestPacketType; + TestPacketType; +using GetCurrentPlayerApplicationSettingValueRspTestPacket = TestPacketType; // Test parsing a Get Current Player Application Setting Value Request TEST(GetCurrentPlayerApplicationSettingValueRequestPacketTest, getterTest) { - std::vector attrs = {PlayerAttribute::REPEAT, - PlayerAttribute::SHUFFLE}; - auto test_packet = - GetCurrentPlayerApplicationSettingValueRequestTestPacket::Make( + std::vector attrs = {PlayerAttribute::REPEAT, PlayerAttribute::SHUFFLE}; + auto test_packet = GetCurrentPlayerApplicationSettingValueRequestTestPacket::Make( get_current_player_application_setting_value_request); ASSERT_EQ(test_packet->GetNumberOfRequestedAttributes(), 2); @@ -42,45 +39,34 @@ TEST(GetCurrentPlayerApplicationSettingValueRequestPacketTest, getterTest) { } TEST(GetCurrentPlayerApplicationSettingValueRequestPacketTest, validTest) { - auto test_packet = - GetCurrentPlayerApplicationSettingValueRequestTestPacket::Make( + auto test_packet = GetCurrentPlayerApplicationSettingValueRequestTestPacket::Make( get_current_player_application_setting_value_request); ASSERT_TRUE(test_packet->IsValid()); } TEST(GetCurrentPlayerApplicationSettingValueRequestPacketTest, invalidTest) { - std::vector packet_copy = - get_current_player_application_setting_value_request; + std::vector packet_copy = get_current_player_application_setting_value_request; packet_copy.push_back(0x00); - auto test_packet = - GetCurrentPlayerApplicationSettingValueRequestTestPacket::Make( - packet_copy); + auto test_packet = GetCurrentPlayerApplicationSettingValueRequestTestPacket::Make(packet_copy); ASSERT_FALSE(test_packet->IsValid()); std::vector short_packet = { - 0, 1, 2, 3, 4, 5, 6, + 0, 1, 2, 3, 4, 5, 6, }; - test_packet = GetCurrentPlayerApplicationSettingValueRequestTestPacket::Make( - short_packet); + test_packet = GetCurrentPlayerApplicationSettingValueRequestTestPacket::Make(short_packet); ASSERT_FALSE(test_packet->IsValid()); } TEST(GetCurrentPlayerApplicationSettingValueResponseBuilderTest, builderTest) { - std::vector attrs = {PlayerAttribute::REPEAT, - PlayerAttribute::SHUFFLE}; + std::vector attrs = {PlayerAttribute::REPEAT, PlayerAttribute::SHUFFLE}; std::vector vals = {0x01, 0x01}; // All values: OFF - auto builder = - GetCurrentPlayerApplicationSettingValueResponseBuilder::MakeBuilder(attrs, - vals); + auto builder = GetCurrentPlayerApplicationSettingValueResponseBuilder::MakeBuilder(attrs, vals); - ASSERT_EQ(builder->size(), - get_current_player_application_setting_value_response.size()); + ASSERT_EQ(builder->size(), get_current_player_application_setting_value_response.size()); - auto test_packet = - GetCurrentPlayerApplicationSettingValueRspTestPacket::Make(); + auto test_packet = GetCurrentPlayerApplicationSettingValueRspTestPacket::Make(); builder->Serialize(test_packet); - ASSERT_EQ(test_packet->GetData(), - get_current_player_application_setting_value_response); + ASSERT_EQ(test_packet->GetData(), get_current_player_application_setting_value_response); } } // namespace avrcp diff --git a/system/packet/tests/avrcp/get_element_attributes_packet_test.cc b/system/packet/tests/avrcp/get_element_attributes_packet_test.cc index 96ae1fa6c45..2dbfecc87bf 100644 --- a/system/packet/tests/avrcp/get_element_attributes_packet_test.cc +++ b/system/packet/tests/avrcp/get_element_attributes_packet_test.cc @@ -14,10 +14,11 @@ * limitations under the License. */ +#include "get_element_attributes_packet.h" + #include #include "avrcp_test_packets.h" -#include "get_element_attributes_packet.h" #include "packet_test_helper.h" namespace bluetooth { @@ -27,8 +28,7 @@ using TestGetElemAttrReqPacket = TestPacketType; TEST(GetElementAttributesRequestPacketTest, getterTest) { // Only Title is requested - auto test_packet = - TestGetElemAttrReqPacket::Make(get_element_attributes_request_partial); + auto test_packet = TestGetElemAttrReqPacket::Make(get_element_attributes_request_partial); ASSERT_EQ(test_packet->GetIdentifier(), 0u); @@ -38,8 +38,7 @@ TEST(GetElementAttributesRequestPacketTest, getterTest) { // Title, Artist, Album, Media Numer, Playing Time, Total Number of Media, // and Genre requested - test_packet = - TestGetElemAttrReqPacket::Make(get_element_attributes_request_full); + test_packet = TestGetElemAttrReqPacket::Make(get_element_attributes_request_full); ASSERT_EQ(test_packet->GetIdentifier(), 0u); @@ -55,12 +54,10 @@ TEST(GetElementAttributesRequestPacketTest, getterTest) { } TEST(GetElementAttributesRequestPacketTest, validTest) { - auto test_packet = - TestGetElemAttrReqPacket::Make(get_element_attributes_request_partial); + auto test_packet = TestGetElemAttrReqPacket::Make(get_element_attributes_request_partial); ASSERT_TRUE(test_packet->IsValid()); - test_packet = - TestGetElemAttrReqPacket::Make(get_element_attributes_request_full); + test_packet = TestGetElemAttrReqPacket::Make(get_element_attributes_request_full); ASSERT_TRUE(test_packet->IsValid()); } @@ -70,8 +67,7 @@ TEST(GetElementAttributesRequestPacketTest, invalidTest) { auto test_packet = TestGetElemAttrReqPacket::Make(packet_copy); ASSERT_FALSE(test_packet->IsValid()); - std::vector short_packet = {0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00}; + std::vector short_packet = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; test_packet = TestGetElemAttrReqPacket::Make(short_packet); ASSERT_FALSE(test_packet->IsValid()); } @@ -105,20 +101,13 @@ TEST(GetElementAttributesResponseBuilderTest, builderTest) { TEST(GetElementAttributesResponseBuilderTest, builderMtuTest) { std::vector test_data = { - {Attribute::TITLE, "Test Song 1"}, - {Attribute::ARTIST_NAME, "Test Artist"}, - {Attribute::ALBUM_NAME, "Test Album"}, - {Attribute::TRACK_NUMBER, "1"}, - {Attribute::TOTAL_NUMBER_OF_TRACKS, "2"}, - {Attribute::GENRE, "Test Genre"}, - {Attribute::PLAYING_TIME, "10 200"}, - {Attribute::TITLE, "Test Song 2"}, - {Attribute::ARTIST_NAME, "Test Artist"}, - {Attribute::ALBUM_NAME, "Test Album"}, - {Attribute::TRACK_NUMBER, "2"}, - {Attribute::TOTAL_NUMBER_OF_TRACKS, "2"}, - {Attribute::GENRE, "Test Genre"}, - {Attribute::PLAYING_TIME, "1500"}, + {Attribute::TITLE, "Test Song 1"}, {Attribute::ARTIST_NAME, "Test Artist"}, + {Attribute::ALBUM_NAME, "Test Album"}, {Attribute::TRACK_NUMBER, "1"}, + {Attribute::TOTAL_NUMBER_OF_TRACKS, "2"}, {Attribute::GENRE, "Test Genre"}, + {Attribute::PLAYING_TIME, "10 200"}, {Attribute::TITLE, "Test Song 2"}, + {Attribute::ARTIST_NAME, "Test Artist"}, {Attribute::ALBUM_NAME, "Test Album"}, + {Attribute::TRACK_NUMBER, "2"}, {Attribute::TOTAL_NUMBER_OF_TRACKS, "2"}, + {Attribute::GENRE, "Test Genre"}, {Attribute::PLAYING_TIME, "1500"}, }; using Builder = GetElementAttributesResponseBuilder; @@ -150,14 +139,11 @@ TEST(GetElementAttributesResponseBuilderTest, truncateBuilderTest) { truncated_size += 1; // Number of attributes truncated_size += attribute.size(); // Attribute size - auto truncated_builder = - GetElementAttributesResponseBuilder::MakeBuilder(truncated_size); - ASSERT_TRUE( - truncated_builder->AddAttributeEntry(Attribute::TITLE, "1234truncated")); + auto truncated_builder = GetElementAttributesResponseBuilder::MakeBuilder(truncated_size); + ASSERT_TRUE(truncated_builder->AddAttributeEntry(Attribute::TITLE, "1234truncated")); ASSERT_EQ(truncated_builder->size(), truncated_size); - ASSERT_FALSE(truncated_builder->AddAttributeEntry(Attribute::ARTIST_NAME, - "Can not add")); + ASSERT_FALSE(truncated_builder->AddAttributeEntry(Attribute::ARTIST_NAME, "Can not add")); auto truncated_packet = TestGetElemAttrReqPacket::Make(); truncated_builder->Serialize(truncated_packet); diff --git a/system/packet/tests/avrcp/get_folder_items_packet_test.cc b/system/packet/tests/avrcp/get_folder_items_packet_test.cc index b8289021f28..9ad3396a298 100644 --- a/system/packet/tests/avrcp/get_folder_items_packet_test.cc +++ b/system/packet/tests/avrcp/get_folder_items_packet_test.cc @@ -27,8 +27,8 @@ namespace avrcp { using TestGetFolderItemsReqPacket = TestPacketType; TEST(GetFolderItemsResponseBuilderTest, builderMediaPlayerSizeTest) { - auto builder = GetFolderItemsResponseBuilder::MakePlayerListBuilder( - Status::NO_ERROR, 0x0000, 0xFFFF); + auto builder = + GetFolderItemsResponseBuilder::MakePlayerListBuilder(Status::NO_ERROR, 0x0000, 0xFFFF); // If there are no items, then the only data in the packet is the status ASSERT_EQ(builder->size(), get_folder_items_error_response.size()); @@ -38,8 +38,8 @@ TEST(GetFolderItemsResponseBuilderTest, builderMediaPlayerSizeTest) { } TEST(GetFolderItemsResponseBuilderTest, builderMediaPlayerAddTest) { - auto builder = GetFolderItemsResponseBuilder::MakePlayerListBuilder( - Status::NO_ERROR, 0x0000, 0xFFFF); + auto builder = + GetFolderItemsResponseBuilder::MakePlayerListBuilder(Status::NO_ERROR, 0x0000, 0xFFFF); auto player = MediaPlayerItem(0x0001, "com.google.android.music", true); builder->AddMediaPlayer(player); @@ -57,8 +57,8 @@ TEST(GetFolderItemsResponseBuilderTest, builderPlayerAddMtuTest) { auto packet_size = BrowsePacket::kMinSize() + 5; packet_size += player1.size() + player3.size(); - auto builder = GetFolderItemsResponseBuilder::MakePlayerListBuilder( - Status::NO_ERROR, 0x0000, packet_size); + auto builder = GetFolderItemsResponseBuilder::MakePlayerListBuilder(Status::NO_ERROR, 0x0000, + packet_size); ASSERT_TRUE(builder->AddMediaPlayer(player1)); ASSERT_FALSE(builder->AddMediaPlayer(player2)); @@ -66,8 +66,7 @@ TEST(GetFolderItemsResponseBuilderTest, builderPlayerAddMtuTest) { } TEST(GetFolderItemsResponseBuilderTest, builderFolderSizeTest) { - auto builder = GetFolderItemsResponseBuilder::MakeVFSBuilder(Status::NO_ERROR, - 0x0000, 0xFFFF); + auto builder = GetFolderItemsResponseBuilder::MakeVFSBuilder(Status::NO_ERROR, 0x0000, 0xFFFF); ASSERT_EQ(builder->size(), get_folder_items_error_response.size()); auto folder = FolderItem(0x0000000000000001, 0x00, true, "Test Folder"); @@ -76,8 +75,7 @@ TEST(GetFolderItemsResponseBuilderTest, builderFolderSizeTest) { } TEST(GetFolderItemsResponseBuilderTest, builderFolderAddTest) { - auto builder = GetFolderItemsResponseBuilder::MakeVFSBuilder(Status::NO_ERROR, - 0x0000, 0xFFFF); + auto builder = GetFolderItemsResponseBuilder::MakeVFSBuilder(Status::NO_ERROR, 0x0000, 0xFFFF); auto folder = FolderItem(0x0000000000000001, 0x00, true, "Test Folder"); builder->AddFolder(folder); @@ -95,8 +93,8 @@ TEST(GetFolderItemsResponseBuilderTest, builderFolderAddMtuTest) { auto packet_size = BrowsePacket::kMinSize() + 5; packet_size += folder1.size() + folder3.size(); - auto builder = GetFolderItemsResponseBuilder::MakeVFSBuilder( - Status::NO_ERROR, 0x0000, packet_size); + auto builder = + GetFolderItemsResponseBuilder::MakeVFSBuilder(Status::NO_ERROR, 0x0000, packet_size); ASSERT_TRUE(builder->AddFolder(folder1)); ASSERT_FALSE(builder->AddFolder(folder2)); @@ -104,8 +102,8 @@ TEST(GetFolderItemsResponseBuilderTest, builderFolderAddMtuTest) { } TEST(GetFolderItemsResponseBuilderTest, builderSongSizeTest) { - auto builder = GetFolderItemsResponseBuilder::MakeNowPlayingBuilder( - Status::NO_ERROR, 0x0000, 0xFFFF); + auto builder = + GetFolderItemsResponseBuilder::MakeNowPlayingBuilder(Status::NO_ERROR, 0x0000, 0xFFFF); ASSERT_EQ(builder->size(), get_folder_items_error_response.size()); std::set attributes; @@ -116,8 +114,8 @@ TEST(GetFolderItemsResponseBuilderTest, builderSongSizeTest) { } TEST(GetFolderItemsResponseBuilderTest, builderSongAddTest) { - auto builder = GetFolderItemsResponseBuilder::MakeNowPlayingBuilder( - Status::NO_ERROR, 0x0000, 0xFFFF); + auto builder = + GetFolderItemsResponseBuilder::MakeNowPlayingBuilder(Status::NO_ERROR, 0x0000, 0xFFFF); std::set attributes; attributes.insert(AttributeEntry(Attribute::TITLE, "Test Title")); auto song = MediaElementItem(0x02, "Test Title", attributes); @@ -130,15 +128,14 @@ TEST(GetFolderItemsResponseBuilderTest, builderSongAddTest) { TEST(GetFolderItemsResponseBuilderTest, builderSongAddMtuTest) { MediaElementItem song1(0x01, "Song 1 that fits", std::set()); - MediaElementItem song2(0x02, "Song 2 that doesn't fit", - std::set()); + MediaElementItem song2(0x02, "Song 2 that doesn't fit", std::set()); MediaElementItem song3(0x03, "Song 3 that fits", std::set()); auto packet_size = BrowsePacket::kMinSize() + 5; packet_size += song1.size() + song3.size(); - auto builder = GetFolderItemsResponseBuilder::MakeNowPlayingBuilder( - Status::NO_ERROR, 0x0000, packet_size); + auto builder = GetFolderItemsResponseBuilder::MakeNowPlayingBuilder(Status::NO_ERROR, 0x0000, + packet_size); ASSERT_TRUE(builder->AddSong(song1)); ASSERT_FALSE(builder->AddSong(song2)); @@ -146,20 +143,18 @@ TEST(GetFolderItemsResponseBuilderTest, builderSongAddMtuTest) { } TEST(GetFolderItemsResponseBuilderTest, builderNoItemsTest) { - auto builder = GetFolderItemsResponseBuilder::MakePlayerListBuilder( - Status::NO_ERROR, 0x0000, 0xFFFF); + auto builder = + GetFolderItemsResponseBuilder::MakePlayerListBuilder(Status::NO_ERROR, 0x0000, 0xFFFF); auto test_packet = TestGetFolderItemsReqPacket::Make(); builder->Serialize(test_packet); ASSERT_EQ(test_packet->GetData(), get_folder_items_error_response); - builder = GetFolderItemsResponseBuilder::MakeVFSBuilder(Status::NO_ERROR, - 0x0000, 0xFFFF); + builder = GetFolderItemsResponseBuilder::MakeVFSBuilder(Status::NO_ERROR, 0x0000, 0xFFFF); test_packet = TestGetFolderItemsReqPacket::Make(); builder->Serialize(test_packet); ASSERT_EQ(test_packet->GetData(), get_folder_items_error_response); - builder = GetFolderItemsResponseBuilder::MakeNowPlayingBuilder( - Status::NO_ERROR, 0x0000, 0xFFFF); + builder = GetFolderItemsResponseBuilder::MakeNowPlayingBuilder(Status::NO_ERROR, 0x0000, 0xFFFF); test_packet = TestGetFolderItemsReqPacket::Make(); builder->Serialize(test_packet); ASSERT_EQ(test_packet->GetData(), get_folder_items_error_response); @@ -168,8 +163,8 @@ TEST(GetFolderItemsResponseBuilderTest, builderNoItemsTest) { TEST(GetFolderItemsResponseBuilderTest, builderErrorStatusTest) { std::vector get_folder_items_inv_scope = {0x71, 0x00, 0x01, 0x0a}; - auto builder = GetFolderItemsResponseBuilder::MakePlayerListBuilder( - Status::INVALID_SCOPE, 0x0000, 0xFFFF); + auto builder = GetFolderItemsResponseBuilder::MakePlayerListBuilder(Status::INVALID_SCOPE, 0x0000, + 0xFFFF); // Check that the status remains INVALID_SCOPE even though there are zero // items @@ -192,8 +187,8 @@ TEST(GetFolderItemsResponseBuilderDeathTest, builderDeathTest) { auto folder = FolderItem(0x01, 0x00, true, "test folder"); auto song = MediaElementItem(0x01, "test song", std::set()); - auto builder = GetFolderItemsResponseBuilder::MakePlayerListBuilder( - Status::NO_ERROR, 0x0000, 0xFFFF); + auto builder = + GetFolderItemsResponseBuilder::MakePlayerListBuilder(Status::NO_ERROR, 0x0000, 0xFFFF); { // this will silent SIGABRT sent in ASSERT_DEATH below ScopedSilentDeath _silentDeath; @@ -203,30 +198,25 @@ TEST(GetFolderItemsResponseBuilderDeathTest, builderDeathTest) { "scope_ == Scope::VFS \\|\\| scope_ == Scope::NOW_PLAYING"); } - builder = GetFolderItemsResponseBuilder::MakeVFSBuilder(Status::NO_ERROR, - 0x0000, 0xFFFF); + builder = GetFolderItemsResponseBuilder::MakeVFSBuilder(Status::NO_ERROR, 0x0000, 0xFFFF); { // this will silent SIGABRT sent in ASSERT_DEATH below ScopedSilentDeath _silentDeath; - ASSERT_DEATH(builder->AddMediaPlayer(player), - "scope_ == Scope::MEDIA_PLAYER_LIST"); + ASSERT_DEATH(builder->AddMediaPlayer(player), "scope_ == Scope::MEDIA_PLAYER_LIST"); } - builder = GetFolderItemsResponseBuilder::MakeNowPlayingBuilder( - Status::NO_ERROR, 0x0000, 0xFFFF); + builder = GetFolderItemsResponseBuilder::MakeNowPlayingBuilder(Status::NO_ERROR, 0x0000, 0xFFFF); // this will silent SIGABRT sent in ASSERT_DEATH below ScopedSilentDeath _silentDeath; - ASSERT_DEATH(builder->AddMediaPlayer(player), - "scope_ == Scope::MEDIA_PLAYER_LIST"); + ASSERT_DEATH(builder->AddMediaPlayer(player), "scope_ == Scope::MEDIA_PLAYER_LIST"); ASSERT_DEATH(builder->AddFolder(folder), "scope_ == Scope::VFS"); } TEST(GetFolderItemsRequestTest, getterTest) { - auto test_packet = - TestGetFolderItemsReqPacket::Make(get_folder_items_request_vfs); + auto test_packet = TestGetFolderItemsReqPacket::Make(get_folder_items_request_vfs); ASSERT_EQ(test_packet->GetScope(), Scope::VFS); ASSERT_EQ(test_packet->GetStartItem(), 0x00000000u); @@ -238,8 +228,7 @@ TEST(GetFolderItemsRequestTest, getterTest) { } TEST(GetFolderItemsRequestBuilderTest, builderZeroAttrsTest) { - auto builder = - GetFolderItemsRequestBuilder::MakeBuilder(Scope::VFS, 0, 9, {}); + auto builder = GetFolderItemsRequestBuilder::MakeBuilder(Scope::VFS, 0, 9, {}); ASSERT_EQ(builder->size(), get_folder_items_request_no_attrs.size()); auto test_packet = TestGetFolderItemsReqPacket::Make(); @@ -248,8 +237,7 @@ TEST(GetFolderItemsRequestBuilderTest, builderZeroAttrsTest) { } TEST(GetFolderItemsRequestBuilderTest, builderTest) { - auto builder = GetFolderItemsRequestBuilder::MakeBuilder(Scope::VFS, 0, 9, - {Attribute::TITLE}); + auto builder = GetFolderItemsRequestBuilder::MakeBuilder(Scope::VFS, 0, 9, {Attribute::TITLE}); ASSERT_EQ(builder->size(), get_folder_items_request_title.size()); auto test_packet = TestGetFolderItemsReqPacket::Make(); diff --git a/system/packet/tests/avrcp/get_item_attributes_packet_test.cc b/system/packet/tests/avrcp/get_item_attributes_packet_test.cc index 4f1da7b3392..bc4ae02479e 100644 --- a/system/packet/tests/avrcp/get_item_attributes_packet_test.cc +++ b/system/packet/tests/avrcp/get_item_attributes_packet_test.cc @@ -26,8 +26,7 @@ namespace avrcp { using TestGetItemAttrsReqPacket = TestPacketType; TEST(GetItemAttributesResponseBuilderTest, builderSizeTest) { - auto builder = - GetItemAttributesResponseBuilder::MakeBuilder(Status::NO_ERROR, 0xFFFF); + auto builder = GetItemAttributesResponseBuilder::MakeBuilder(Status::NO_ERROR, 0xFFFF); ASSERT_EQ(builder->size(), 5u); builder->AddAttributeEntry(Attribute::TITLE, "Test Song"); @@ -41,8 +40,7 @@ TEST(GetItemAttributesResponseBuilderTest, builderSizeTest) { } TEST(GetItemAttributesResponseBuilderTest, builderTest) { - auto builder = - GetItemAttributesResponseBuilder::MakeBuilder(Status::NO_ERROR, 0xFFFF); + auto builder = GetItemAttributesResponseBuilder::MakeBuilder(Status::NO_ERROR, 0xFFFF); builder->AddAttributeEntry(Attribute::TITLE, "Test Song"); builder->AddAttributeEntry(Attribute::ARTIST_NAME, "Test Artist"); builder->AddAttributeEntry(Attribute::ALBUM_NAME, "Test Album"); @@ -55,23 +53,20 @@ TEST(GetItemAttributesResponseBuilderTest, builderTest) { TEST(GetItemAttributesResponseBuilderTest, truncateBuilderTest) { auto attribute = AttributeEntry(Attribute::TITLE, "1234"); size_t truncated_size = BrowsePacket::kMinSize(); - truncated_size += 2; // Status field + Number of attributes field + truncated_size += 2; // Status field + Number of attributes field truncated_size += attribute.size(); // Attribute size - auto truncated_builder = GetItemAttributesResponseBuilder::MakeBuilder( - Status::NO_ERROR, truncated_size); - ASSERT_TRUE( - truncated_builder->AddAttributeEntry(Attribute::TITLE, "1234truncated")); + auto truncated_builder = + GetItemAttributesResponseBuilder::MakeBuilder(Status::NO_ERROR, truncated_size); + ASSERT_TRUE(truncated_builder->AddAttributeEntry(Attribute::TITLE, "1234truncated")); ASSERT_EQ(truncated_builder->size(), truncated_size); - ASSERT_FALSE(truncated_builder->AddAttributeEntry(Attribute::ARTIST_NAME, - "Can not add")); + ASSERT_FALSE(truncated_builder->AddAttributeEntry(Attribute::ARTIST_NAME, "Can not add")); auto truncated_packet = TestGetItemAttrsReqPacket::Make(); truncated_builder->Serialize(truncated_packet); - auto builder = - GetItemAttributesResponseBuilder::MakeBuilder(Status::NO_ERROR, 0xFFFF); + auto builder = GetItemAttributesResponseBuilder::MakeBuilder(Status::NO_ERROR, 0xFFFF); builder->AddAttributeEntry(attribute); auto test_packet = TestGetItemAttrsReqPacket::Make(); builder->Serialize(test_packet); @@ -81,8 +76,7 @@ TEST(GetItemAttributesResponseBuilderTest, truncateBuilderTest) { TEST(GetItemAttributesResponseBuilderTest, errorStatusTest) { std::vector does_not_exist_status = {0x73, 0x00, 0x01, 0x09}; - auto builder = GetItemAttributesResponseBuilder::MakeBuilder( - Status::DOES_NOT_EXIST, 0xFFFF); + auto builder = GetItemAttributesResponseBuilder::MakeBuilder(Status::DOES_NOT_EXIST, 0xFFFF); ASSERT_EQ(builder->size(), does_not_exist_status.size()); auto test_packet = TestGetItemAttrsReqPacket::Make(); @@ -91,8 +85,7 @@ TEST(GetItemAttributesResponseBuilderTest, errorStatusTest) { } TEST(GetItemAttributesRequestTest, getterTest) { - auto test_packet = TestGetItemAttrsReqPacket::Make( - get_item_attributes_request_all_attributes); + auto test_packet = TestGetItemAttrsReqPacket::Make(get_item_attributes_request_all_attributes); ASSERT_EQ(test_packet->GetScope(), Scope::NOW_PLAYING); ASSERT_EQ(test_packet->GetUidCounter(), 0x0000u); @@ -109,8 +102,7 @@ TEST(GetItemAttributesRequestTest, getterTest) { } TEST(GetItemAttributesRequestTest, validTest) { - auto test_packet = TestGetItemAttrsReqPacket::Make( - get_item_attributes_request_all_attributes); + auto test_packet = TestGetItemAttrsReqPacket::Make(get_item_attributes_request_all_attributes); ASSERT_TRUE(test_packet->IsValid()); } @@ -120,36 +112,26 @@ TEST(GetItemAttributesRequestTest, invalidTest) { auto test_packet = TestGetItemAttrsReqPacket::Make(packet_copy); ASSERT_FALSE(test_packet->IsValid()); - std::vector short_packet = {0x00, 0x01, 0x02, 0x03, - 0x04, 0x05, 0x06, 0x07}; + std::vector short_packet = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}; test_packet = TestGetItemAttrsReqPacket::Make(short_packet); ASSERT_FALSE(test_packet->IsValid()); } TEST(GetItemAttributesRequestTest, builderMtuTest) { std::vector test_data = { - {Attribute::TITLE, "Test Song 1"}, - {Attribute::ARTIST_NAME, "Test Artist"}, - {Attribute::ALBUM_NAME, "Test Album"}, - {Attribute::TRACK_NUMBER, "1"}, - {Attribute::TOTAL_NUMBER_OF_TRACKS, "2"}, - {Attribute::GENRE, "Test Genre"}, - {Attribute::PLAYING_TIME, "10 200"}, - {Attribute::TITLE, "Test Song 2"}, - {Attribute::ARTIST_NAME, "Test Artist"}, - {Attribute::ALBUM_NAME, "Test Album"}, - {Attribute::TRACK_NUMBER, "2"}, - {Attribute::TOTAL_NUMBER_OF_TRACKS, "2"}, - {Attribute::GENRE, "Test Genre"}, - {Attribute::PLAYING_TIME, "1500"}, + {Attribute::TITLE, "Test Song 1"}, {Attribute::ARTIST_NAME, "Test Artist"}, + {Attribute::ALBUM_NAME, "Test Album"}, {Attribute::TRACK_NUMBER, "1"}, + {Attribute::TOTAL_NUMBER_OF_TRACKS, "2"}, {Attribute::GENRE, "Test Genre"}, + {Attribute::PLAYING_TIME, "10 200"}, {Attribute::TITLE, "Test Song 2"}, + {Attribute::ARTIST_NAME, "Test Artist"}, {Attribute::ALBUM_NAME, "Test Album"}, + {Attribute::TRACK_NUMBER, "2"}, {Attribute::TOTAL_NUMBER_OF_TRACKS, "2"}, + {Attribute::GENRE, "Test Genre"}, {Attribute::PLAYING_TIME, "1500"}, }; using Builder = GetItemAttributesResponseBuilder; using Helper = FragmentationBuilderHelper; size_t mtu = size_t(-1); - Helper helper(mtu, [](size_t mtu) { - return Builder::MakeBuilder(Status::NO_ERROR, mtu); - }); + Helper helper(mtu, [](size_t mtu) { return Builder::MakeBuilder(Status::NO_ERROR, mtu); }); EXPECT_NO_FATAL_FAILURE(helper.runTest(test_data, mtu, false, false)); diff --git a/system/packet/tests/avrcp/get_play_status_packet_test.cc b/system/packet/tests/avrcp/get_play_status_packet_test.cc index c15147dc881..80c38f6bb96 100644 --- a/system/packet/tests/avrcp/get_play_status_packet_test.cc +++ b/system/packet/tests/avrcp/get_play_status_packet_test.cc @@ -14,10 +14,11 @@ * limitations under the License. */ +#include "get_play_status_packet.h" + #include #include "avrcp_test_packets.h" -#include "get_play_status_packet.h" #include "packet_test_helper.h" namespace bluetooth { diff --git a/system/packet/tests/avrcp/get_total_number_of_items_packet_test.cc b/system/packet/tests/avrcp/get_total_number_of_items_packet_test.cc index eb7efc26e90..9982ec399c3 100644 --- a/system/packet/tests/avrcp/get_total_number_of_items_packet_test.cc +++ b/system/packet/tests/avrcp/get_total_number_of_items_packet_test.cc @@ -23,12 +23,11 @@ namespace bluetooth { namespace avrcp { -using TestGetTotalNumItemsReqPacket = - TestPacketType; +using TestGetTotalNumItemsReqPacket = TestPacketType; TEST(GetTotalNumberOfItemsResponseBuilderTest, builderTest) { - auto builder = GetTotalNumberOfItemsResponseBuilder::MakeBuilder( - Status::NO_ERROR, 0x0000u, 0x00000005u); + auto builder = + GetTotalNumberOfItemsResponseBuilder::MakeBuilder(Status::NO_ERROR, 0x0000u, 0x00000005u); ASSERT_EQ(builder->size(), get_total_number_of_items_response.size()); auto test_packet = TestGetTotalNumItemsReqPacket::Make(); @@ -38,8 +37,8 @@ TEST(GetTotalNumberOfItemsResponseBuilderTest, builderTest) { TEST(GetTotalNumberOfItemsResponseBuilderTest, errorStatusTest) { std::vector inv_scope_status_packet = {0x75, 0x00, 0x01, 0x0a}; - auto builder = GetTotalNumberOfItemsResponseBuilder::MakeBuilder( - Status::INVALID_SCOPE, 0x1234u, 0x56789abcu); + auto builder = GetTotalNumberOfItemsResponseBuilder::MakeBuilder(Status::INVALID_SCOPE, 0x1234u, + 0x56789abcu); ASSERT_EQ(builder->size(), inv_scope_status_packet.size()); auto test_packet = TestGetTotalNumItemsReqPacket::Make(); @@ -48,14 +47,14 @@ TEST(GetTotalNumberOfItemsResponseBuilderTest, errorStatusTest) { } TEST(GetTotalNumberOfItemsRequestTest, getterTest) { - auto test_packet = TestGetTotalNumItemsReqPacket::Make( - get_total_number_of_items_request_now_playing); + auto test_packet = + TestGetTotalNumItemsReqPacket::Make(get_total_number_of_items_request_now_playing); ASSERT_EQ(test_packet->GetScope(), Scope::NOW_PLAYING); } TEST(GetTotalNumberOfItemsRequestTest, validTest) { - auto test_packet = TestGetTotalNumItemsReqPacket::Make( - get_total_number_of_items_request_now_playing); + auto test_packet = + TestGetTotalNumItemsReqPacket::Make(get_total_number_of_items_request_now_playing); ASSERT_TRUE(test_packet->IsValid()); } diff --git a/system/packet/tests/avrcp/list_player_application_setting_attributes_test.cc b/system/packet/tests/avrcp/list_player_application_setting_attributes_test.cc index 488d65b95ac..48269951eef 100644 --- a/system/packet/tests/avrcp/list_player_application_setting_attributes_test.cc +++ b/system/packet/tests/avrcp/list_player_application_setting_attributes_test.cc @@ -24,23 +24,17 @@ namespace bluetooth { namespace avrcp { -using TestListPlayerApplicationSettingAttributesRspPacket = - TestPacketType; +using TestListPlayerApplicationSettingAttributesRspPacket = TestPacketType; TEST(ListPlayerApplicationSettingAttributesResponseBuilderTest, builderTest) { - std::vector attrs = {PlayerAttribute::REPEAT, - PlayerAttribute::SHUFFLE}; - auto builder = - ListPlayerApplicationSettingAttributesResponseBuilder::MakeBuilder(attrs); + std::vector attrs = {PlayerAttribute::REPEAT, PlayerAttribute::SHUFFLE}; + auto builder = ListPlayerApplicationSettingAttributesResponseBuilder::MakeBuilder(attrs); - ASSERT_EQ(builder->size(), - list_player_application_setting_attributes_response.size()); + ASSERT_EQ(builder->size(), list_player_application_setting_attributes_response.size()); - auto test_packet = - TestListPlayerApplicationSettingAttributesRspPacket::Make(); + auto test_packet = TestListPlayerApplicationSettingAttributesRspPacket::Make(); builder->Serialize(test_packet); - ASSERT_EQ(test_packet->GetData(), - list_player_application_setting_attributes_response); + ASSERT_EQ(test_packet->GetData(), list_player_application_setting_attributes_response); } } // namespace avrcp diff --git a/system/packet/tests/avrcp/list_player_application_setting_values_test.cc b/system/packet/tests/avrcp/list_player_application_setting_values_test.cc index 12c6bc66dc2..54ed1d50124 100644 --- a/system/packet/tests/avrcp/list_player_application_setting_values_test.cc +++ b/system/packet/tests/avrcp/list_player_application_setting_values_test.cc @@ -26,54 +26,45 @@ namespace bluetooth { namespace avrcp { using ListPlayerApplicationSettingValuesRequestTestPacket = - TestPacketType; -using ListPlayerApplicationSettingAttributeValuesRspTestPacket = - TestPacketType; + TestPacketType; +using ListPlayerApplicationSettingAttributeValuesRspTestPacket = TestPacketType; // Test parsing a List Player Application Setting Values Request TEST(ListPlayerApplicationSettingValuesRequestPacketTest, getterTest) { auto test_packet = ListPlayerApplicationSettingValuesRequestTestPacket::Make( - list_player_application_setting_attribute_values_request); + list_player_application_setting_attribute_values_request); ASSERT_EQ(test_packet->GetRequestedAttribute(), PlayerAttribute::REPEAT); } TEST(ListPlayerApplicationSettingValuesRequestPacketTest, validTest) { auto test_packet = ListPlayerApplicationSettingValuesRequestTestPacket::Make( - list_player_application_setting_attribute_values_request); + list_player_application_setting_attribute_values_request); ASSERT_TRUE(test_packet->IsValid()); } TEST(ListPlayerApplicationSettingValuesRequestPacketTest, invalidTest) { - std::vector packet_copy = - list_player_application_setting_attribute_values_request; + std::vector packet_copy = list_player_application_setting_attribute_values_request; packet_copy.push_back(0x00); - auto test_packet = - ListPlayerApplicationSettingValuesRequestTestPacket::Make(packet_copy); + auto test_packet = ListPlayerApplicationSettingValuesRequestTestPacket::Make(packet_copy); ASSERT_FALSE(test_packet->IsValid()); std::vector short_packet = { - 0, 1, 2, 3, 4, 5, 6, + 0, 1, 2, 3, 4, 5, 6, }; - test_packet = - ListPlayerApplicationSettingValuesRequestTestPacket::Make(short_packet); + test_packet = ListPlayerApplicationSettingValuesRequestTestPacket::Make(short_packet); ASSERT_FALSE(test_packet->IsValid()); } TEST(ListPlayerApplicationSettingValuesResponseBuilderTest, builderTest) { - std::vector vals = {0x01, 0x02, 0x03, - 0x04}; // All possible repeat vals - auto builder = - ListPlayerApplicationSettingValuesResponseBuilder::MakeBuilder(vals); + std::vector vals = {0x01, 0x02, 0x03, 0x04}; // All possible repeat vals + auto builder = ListPlayerApplicationSettingValuesResponseBuilder::MakeBuilder(vals); - ASSERT_EQ(builder->size(), - list_player_application_setting_attribute_values_response.size()); + ASSERT_EQ(builder->size(), list_player_application_setting_attribute_values_response.size()); - auto test_packet = - ListPlayerApplicationSettingAttributeValuesRspTestPacket::Make(); + auto test_packet = ListPlayerApplicationSettingAttributeValuesRspTestPacket::Make(); builder->Serialize(test_packet); - ASSERT_EQ(test_packet->GetData(), - list_player_application_setting_attribute_values_response); + ASSERT_EQ(test_packet->GetData(), list_player_application_setting_attribute_values_response); } } // namespace avrcp diff --git a/system/packet/tests/avrcp/pass_through_packet_test.cc b/system/packet/tests/avrcp/pass_through_packet_test.cc index 5ea749f5795..4587b35e29f 100644 --- a/system/packet/tests/avrcp/pass_through_packet_test.cc +++ b/system/packet/tests/avrcp/pass_through_packet_test.cc @@ -14,11 +14,12 @@ * limitations under the License. */ +#include "pass_through_packet.h" + #include #include "avrcp_test_packets.h" #include "packet_test_helper.h" -#include "pass_through_packet.h" namespace bluetooth { namespace avrcp { @@ -40,8 +41,7 @@ TEST(PassThroughPacketBuilderTest, builderTest) { } TEST(PassThroughPacketTest, getterTest) { - auto test_packet = - TestPassThroughPacket::Make(pass_through_command_play_pushed); + auto test_packet = TestPassThroughPacket::Make(pass_through_command_play_pushed); ASSERT_EQ(test_packet->GetKeyState(), KeyState::PUSHED); ASSERT_EQ(test_packet->GetOperationId(), 0x44); @@ -51,8 +51,7 @@ TEST(PassThroughPacketTest, getterTest) { } TEST(PassThroughPacketTest, validTest) { - auto test_packet = - TestPassThroughPacket::Make(pass_through_command_play_pushed); + auto test_packet = TestPassThroughPacket::Make(pass_through_command_play_pushed); ASSERT_TRUE(test_packet->IsValid()); test_packet = TestPassThroughPacket::Make(pass_through_command_play_released); diff --git a/system/packet/tests/avrcp/register_notification_packet_test.cc b/system/packet/tests/avrcp/register_notification_packet_test.cc index 6855048b63b..7d613267a4f 100644 --- a/system/packet/tests/avrcp/register_notification_packet_test.cc +++ b/system/packet/tests/avrcp/register_notification_packet_test.cc @@ -30,16 +30,14 @@ using TestRegNotifReqPacket = TestPacketType; using TestRegNotifRspPacket = TestPacketType; TEST(RegisterNotificationRequestTest, getterTest) { - auto test_packet = - TestRegNotifReqPacket::Make(register_play_status_notification); + auto test_packet = TestRegNotifReqPacket::Make(register_play_status_notification); ASSERT_EQ(test_packet->GetEventRegistered(), Event::PLAYBACK_STATUS_CHANGED); ASSERT_EQ(test_packet->GetInterval(), 5u); } TEST(RegisterNotificationRequestTest, validTest) { - auto test_packet = - TestRegNotifReqPacket::Make(register_play_status_notification); + auto test_packet = TestRegNotifReqPacket::Make(register_play_status_notification); ASSERT_TRUE(test_packet->IsValid()); } @@ -55,8 +53,7 @@ TEST(RegisterNotificationRequestTest, invalidTest) { } TEST(RegisterNotificationRequestBuilderTest, builderTest) { - auto builder = - RegisterNotificationRequestBuilder::MakeBuilder(Event::VOLUME_CHANGED, 0); + auto builder = RegisterNotificationRequestBuilder::MakeBuilder(Event::VOLUME_CHANGED, 0); ASSERT_EQ(builder->size(), register_volume_changed_notification.size()); auto test_packet = TestRegNotifReqPacket::Make(); @@ -65,8 +62,7 @@ TEST(RegisterNotificationRequestBuilderTest, builderTest) { } TEST(RegisterNotificationResponseTest, volumeGetterTest) { - auto test_packet = - TestRegNotifRspPacket::Make(interim_volume_changed_notification); + auto test_packet = TestRegNotifRspPacket::Make(interim_volume_changed_notification); ASSERT_TRUE(test_packet->IsInterim()); ASSERT_EQ(test_packet->GetEvent(), Event::VOLUME_CHANGED); @@ -74,8 +70,7 @@ TEST(RegisterNotificationResponseTest, volumeGetterTest) { } TEST(RegisterNotificationResponseTest, validTest) { - auto test_packet = - TestRegNotifRspPacket::Make(interim_volume_changed_notification); + auto test_packet = TestRegNotifRspPacket::Make(interim_volume_changed_notification); ASSERT_TRUE(test_packet->IsValid()); } @@ -104,13 +99,11 @@ TEST(RegisterNotificationResponseDeathTest, wrongEventDeathTest) { // this will silent SIGABRT sent in ASSERT_DEATH below ScopedSilentDeath _silentDeath; - ASSERT_DEATH(test_packet->GetVolume(), - "GetEvent\\(\\) == Event::VOLUME_CHANGED"); + ASSERT_DEATH(test_packet->GetVolume(), "GetEvent\\(\\) == Event::VOLUME_CHANGED"); } TEST(RegisterNotificationResponseBuilderTest, playStatusBuilderTest) { - auto builder = RegisterNotificationResponseBuilder::MakePlaybackStatusBuilder( - true, 0x00); + auto builder = RegisterNotificationResponseBuilder::MakePlaybackStatusBuilder(true, 0x00); ASSERT_EQ(builder->size(), interim_play_status_notification.size()); auto test_packet = TestRegNotifReqPacket::Make(); builder->Serialize(test_packet); @@ -118,39 +111,31 @@ TEST(RegisterNotificationResponseBuilderTest, playStatusBuilderTest) { } TEST(RegisterNotificationResponseBuilderTest, trackChangedBuilderTest) { - auto builder = RegisterNotificationResponseBuilder::MakeTrackChangedBuilder( - true, 0x0102030405060708); + auto builder = + RegisterNotificationResponseBuilder::MakeTrackChangedBuilder(true, 0x0102030405060708); ASSERT_EQ(builder->size(), interim_track_changed_notification.size()); auto test_packet = TestRegNotifReqPacket::Make(); builder->Serialize(test_packet); ASSERT_EQ(test_packet->GetData(), interim_track_changed_notification); } -TEST(RegisterNotificationResponseBuilderTest, - interimPlayerSettingChangedBuilderTest) { - std::vector attrs = { - PlayerAttribute::EQUALIZER, PlayerAttribute::REPEAT, - PlayerAttribute::SHUFFLE, PlayerAttribute::SCAN}; +TEST(RegisterNotificationResponseBuilderTest, interimPlayerSettingChangedBuilderTest) { + std::vector attrs = {PlayerAttribute::EQUALIZER, PlayerAttribute::REPEAT, + PlayerAttribute::SHUFFLE, PlayerAttribute::SCAN}; std::vector vals = {0x01, 0x01, 0x01, 0x01}; // All off auto builder = - RegisterNotificationResponseBuilder::MakePlayerSettingChangedBuilder( - true, attrs, vals); - ASSERT_EQ(builder->size(), - interim_changed_player_setting_notification.size()); + RegisterNotificationResponseBuilder::MakePlayerSettingChangedBuilder(true, attrs, vals); + ASSERT_EQ(builder->size(), interim_changed_player_setting_notification.size()); auto test_packet = TestRegNotifReqPacket::Make(); builder->Serialize(test_packet); - ASSERT_EQ(test_packet->GetData(), - interim_changed_player_setting_notification); + ASSERT_EQ(test_packet->GetData(), interim_changed_player_setting_notification); } TEST(RegisterNotificationResponseBuilderTest, playerSettingChangedBuilderTest) { - std::vector attrs = {PlayerAttribute::REPEAT, - PlayerAttribute::SHUFFLE}; - std::vector vals = {(uint8_t)PlayerRepeatValue::OFF, - (uint8_t)PlayerShuffleValue::ALL}; + std::vector attrs = {PlayerAttribute::REPEAT, PlayerAttribute::SHUFFLE}; + std::vector vals = {(uint8_t)PlayerRepeatValue::OFF, (uint8_t)PlayerShuffleValue::ALL}; auto builder = - RegisterNotificationResponseBuilder::MakePlayerSettingChangedBuilder( - false, attrs, vals); + RegisterNotificationResponseBuilder::MakePlayerSettingChangedBuilder(false, attrs, vals); ASSERT_EQ(builder->size(), changed_player_setting_notification.size()); auto test_packet = TestRegNotifReqPacket::Make(); builder->Serialize(test_packet); @@ -159,8 +144,7 @@ TEST(RegisterNotificationResponseBuilderTest, playerSettingChangedBuilderTest) { TEST(RegisterNotificationResponseBuilderTest, playPositionBuilderTest) { auto builder = - RegisterNotificationResponseBuilder::MakePlaybackPositionBuilder( - false, 0x00000000); + RegisterNotificationResponseBuilder::MakePlaybackPositionBuilder(false, 0x00000000); ASSERT_EQ(builder->size(), changed_play_pos_notification.size()); auto test_packet = TestRegNotifReqPacket::Make(); builder->Serialize(test_packet); @@ -168,8 +152,7 @@ TEST(RegisterNotificationResponseBuilderTest, playPositionBuilderTest) { } TEST(RegisterNotificationResponseBuilderTest, nowPlayingBuilderTest) { - auto builder = - RegisterNotificationResponseBuilder::MakeNowPlayingBuilder(true); + auto builder = RegisterNotificationResponseBuilder::MakeNowPlayingBuilder(true); ASSERT_EQ(builder->size(), interim_now_playing_notification.size()); auto test_packet = TestRegNotifReqPacket::Make(); builder->Serialize(test_packet); @@ -177,8 +160,7 @@ TEST(RegisterNotificationResponseBuilderTest, nowPlayingBuilderTest) { } TEST(RegisterNotificationResponseBuilderTest, availablePlayersBuilderTest) { - auto builder = - RegisterNotificationResponseBuilder::MakeAvailablePlayersBuilder(true); + auto builder = RegisterNotificationResponseBuilder::MakeAvailablePlayersBuilder(true); ASSERT_EQ(builder->size(), interim_available_players_notification.size()); auto test_packet = TestRegNotifReqPacket::Make(); builder->Serialize(test_packet); @@ -186,9 +168,7 @@ TEST(RegisterNotificationResponseBuilderTest, availablePlayersBuilderTest) { } TEST(RegisterNotificationResponseBuilderTest, addressedPlayerBuilderTest) { - auto builder = - RegisterNotificationResponseBuilder::MakeAddressedPlayerBuilder(true, 1, - 0x0000); + auto builder = RegisterNotificationResponseBuilder::MakeAddressedPlayerBuilder(true, 1, 0x0000); ASSERT_EQ(builder->size(), interim_addressed_player_notification.size()); auto test_packet = TestRegNotifReqPacket::Make(); builder->Serialize(test_packet); @@ -196,12 +176,11 @@ TEST(RegisterNotificationResponseBuilderTest, addressedPlayerBuilderTest) { } TEST(RegisterNotificationResponseBuilderTest, uidsChangedBuilderTest) { - auto builder = - RegisterNotificationResponseBuilder::MakeUidsChangedBuilder(true, 0x0000); - ASSERT_EQ(builder->size(), interim_uids_notificaiton.size()); + auto builder = RegisterNotificationResponseBuilder::MakeUidsChangedBuilder(true, 0x0000); + ASSERT_EQ(builder->size(), interim_uids_notification.size()); auto test_packet = TestRegNotifReqPacket::Make(); builder->Serialize(test_packet); - ASSERT_EQ(test_packet->GetData(), interim_uids_notificaiton); + ASSERT_EQ(test_packet->GetData(), interim_uids_notification); } } // namespace avrcp diff --git a/system/packet/tests/avrcp/set_addressed_player_packet_test.cc b/system/packet/tests/avrcp/set_addressed_player_packet_test.cc index a6ced9e6005..238a296f218 100644 --- a/system/packet/tests/avrcp/set_addressed_player_packet_test.cc +++ b/system/packet/tests/avrcp/set_addressed_player_packet_test.cc @@ -26,8 +26,7 @@ namespace avrcp { using TestSetAddrPlayerPacket = TestPacketType; TEST(SetAddressedPlayerResponseBuilderTest, builderTest) { - auto builder = - SetAddressedPlayerResponseBuilder::MakeBuilder(Status::NO_ERROR); + auto builder = SetAddressedPlayerResponseBuilder::MakeBuilder(Status::NO_ERROR); ASSERT_EQ(builder->size(), set_addressed_player_response.size()); auto test_packet = TestSetAddrPlayerPacket::Make(); @@ -36,15 +35,13 @@ TEST(SetAddressedPlayerResponseBuilderTest, builderTest) { } TEST(SetAddressedPlayerRequestTest, getterTest) { - auto test_packet = - TestSetAddrPlayerPacket::Make(set_addressed_player_request); + auto test_packet = TestSetAddrPlayerPacket::Make(set_addressed_player_request); ASSERT_EQ(test_packet->GetPlayerId(), 0x0000u); } TEST(SetAddressedPlayerRequestTest, validTest) { - auto test_packet = - TestSetAddrPlayerPacket::Make(set_addressed_player_request); + auto test_packet = TestSetAddrPlayerPacket::Make(set_addressed_player_request); ASSERT_TRUE(test_packet->IsValid()); } diff --git a/system/packet/tests/avrcp/set_browsed_player_packet_test.cc b/system/packet/tests/avrcp/set_browsed_player_packet_test.cc index 828df18ab05..3e3a8bbfcd1 100644 --- a/system/packet/tests/avrcp/set_browsed_player_packet_test.cc +++ b/system/packet/tests/avrcp/set_browsed_player_packet_test.cc @@ -26,8 +26,7 @@ namespace avrcp { using TestSetBrowsedPlayerPacket = TestPacketType; TEST(SetBrowsedPlayerResponseBuilder, builderTest) { - auto builder = SetBrowsedPlayerResponseBuilder::MakeBuilder(Status::NO_ERROR, - 0x0000, 4, 0, ""); + auto builder = SetBrowsedPlayerResponseBuilder::MakeBuilder(Status::NO_ERROR, 0x0000, 4, 0, ""); ASSERT_EQ(builder->size(), set_browsed_player_response.size()); auto test_packet = TestSetBrowsedPlayerPacket::Make(); @@ -37,8 +36,8 @@ TEST(SetBrowsedPlayerResponseBuilder, builderTest) { TEST(SetBrowsedPlayerResponseBuilder, errorStatusTest) { std::vector player_not_browsable_status = {0x70, 0x00, 0x01, 0x12}; - auto builder = SetBrowsedPlayerResponseBuilder::MakeBuilder( - Status::PLAYER_NOT_BROWSABLE, 0x1234, 5, 6, "Field Not Used"); + auto builder = SetBrowsedPlayerResponseBuilder::MakeBuilder(Status::PLAYER_NOT_BROWSABLE, 0x1234, + 5, 6, "Field Not Used"); ASSERT_EQ(builder->size(), player_not_browsable_status.size()); auto test_packet = TestSetBrowsedPlayerPacket::Make(); @@ -47,15 +46,13 @@ TEST(SetBrowsedPlayerResponseBuilder, errorStatusTest) { } TEST(SetBrowsedPlayerRequestTest, getterTest) { - auto test_packet = - TestSetBrowsedPlayerPacket::Make(set_browsed_player_request); + auto test_packet = TestSetBrowsedPlayerPacket::Make(set_browsed_player_request); ASSERT_EQ(test_packet->GetPlayerId(), 0x0002u); } TEST(SetBrowsedPlayerRequestTest, validTest) { - auto test_packet = - TestSetBrowsedPlayerPacket::Make(set_browsed_player_request); + auto test_packet = TestSetBrowsedPlayerPacket::Make(set_browsed_player_request); ASSERT_TRUE(test_packet->IsValid()); } diff --git a/system/packet/tests/avrcp/set_player_application_setting_value_test.cc b/system/packet/tests/avrcp/set_player_application_setting_value_test.cc index 00254e91392..3fa8d650b2f 100644 --- a/system/packet/tests/avrcp/set_player_application_setting_value_test.cc +++ b/system/packet/tests/avrcp/set_player_application_setting_value_test.cc @@ -25,16 +25,15 @@ namespace bluetooth { namespace avrcp { using SetPlayerApplicationSettingValueRequestTestPacket = - TestPacketType; + TestPacketType; using SetPlayerApplicationSettingValueRspTestPacket = TestPacketType; // Test parsing a Set Player Application Setting Value Request TEST(SetPlayerApplicationSettingValueRequestPacketTest, getterTest) { - std::vector attrs = {PlayerAttribute::REPEAT, - PlayerAttribute::SHUFFLE}; + std::vector attrs = {PlayerAttribute::REPEAT, PlayerAttribute::SHUFFLE}; std::vector vals = {0x01, 0x01}; // All values: OFF auto test_packet = SetPlayerApplicationSettingValueRequestTestPacket::Make( - set_player_application_setting_value_request); + set_player_application_setting_value_request); ASSERT_EQ(test_packet->GetNumberOfRequestedAttributes(), 2); ASSERT_EQ(test_packet->GetRequestedAttributes(), attrs); @@ -43,36 +42,31 @@ TEST(SetPlayerApplicationSettingValueRequestPacketTest, getterTest) { TEST(SetPlayerApplicationSettingValueRequestPacketTest, validTest) { auto test_packet = SetPlayerApplicationSettingValueRequestTestPacket::Make( - set_player_application_setting_value_request); + set_player_application_setting_value_request); ASSERT_TRUE(test_packet->IsValid()); } TEST(SetPlayerApplicationSettingValueRequestPacketTest, invalidTest) { - std::vector packet_copy = - set_player_application_setting_value_request; + std::vector packet_copy = set_player_application_setting_value_request; packet_copy.push_back(0x00); - auto test_packet = - SetPlayerApplicationSettingValueRequestTestPacket::Make(packet_copy); + auto test_packet = SetPlayerApplicationSettingValueRequestTestPacket::Make(packet_copy); ASSERT_FALSE(test_packet->IsValid()); std::vector short_packet = { - 0, 1, 2, 3, 4, 5, 6, + 0, 1, 2, 3, 4, 5, 6, }; - test_packet = - SetPlayerApplicationSettingValueRequestTestPacket::Make(short_packet); + test_packet = SetPlayerApplicationSettingValueRequestTestPacket::Make(short_packet); ASSERT_FALSE(test_packet->IsValid()); } TEST(SetPlayerApplicationSettingValueResponseBuilderBuilderTest, builderTest) { auto builder = SetPlayerApplicationSettingValueResponseBuilder::MakeBuilder(); - ASSERT_EQ(builder->size(), - set_player_application_setting_value_response.size()); + ASSERT_EQ(builder->size(), set_player_application_setting_value_response.size()); auto test_packet = SetPlayerApplicationSettingValueRspTestPacket::Make(); builder->Serialize(test_packet); - ASSERT_EQ(test_packet->GetData(), - set_player_application_setting_value_response); + ASSERT_EQ(test_packet->GetData(), set_player_application_setting_value_response); } } // namespace avrcp diff --git a/system/packet/tests/avrcp/vendor_packet_test.cc b/system/packet/tests/avrcp/vendor_packet_test.cc index e933824ab73..c826f129929 100644 --- a/system/packet/tests/avrcp/vendor_packet_test.cc +++ b/system/packet/tests/avrcp/vendor_packet_test.cc @@ -14,35 +14,35 @@ * limitations under the License. */ -#include +#include "vendor_packet.h" #include +#include + #include "avrcp_test_packets.h" #include "packet_test_helper.h" -#include "vendor_packet.h" namespace bluetooth { // A helper class that has public accessors to protected methods class TestPacketBuilder : public PacketBuilder { - public: - static std::unique_ptr MakeBuilder( - std::vector data) { +public: + static std::unique_ptr MakeBuilder(std::vector data) { std::unique_ptr builder(new TestPacketBuilder(data)); return builder; - }; + } // Make all the utility functions public - using PacketBuilder::ReserveSpace; using PacketBuilder::AddPayloadOctets1; using PacketBuilder::AddPayloadOctets2; using PacketBuilder::AddPayloadOctets3; using PacketBuilder::AddPayloadOctets4; using PacketBuilder::AddPayloadOctets6; using PacketBuilder::AddPayloadOctets8; + using PacketBuilder::ReserveSpace; - size_t size() const override { return data_.size(); }; + size_t size() const override { return data_.size(); } bool Serialize(const std::shared_ptr& pkt) override { ReserveSpace(pkt, size()); @@ -54,7 +54,7 @@ class TestPacketBuilder : public PacketBuilder { return true; } - TestPacketBuilder(std::vector data) : data_(data){}; + TestPacketBuilder(std::vector data) : data_(data) {} std::vector data_; }; @@ -68,9 +68,8 @@ TEST(VendorPacketBuilderTest, builderTest) { auto get_cap_payload = TestPacketBuilder::MakeBuilder(get_cap_payload_data); - auto builder = VendorPacketBuilder::MakeBuilder( - CType::STATUS, CommandPdu::GET_CAPABILITIES, PacketType::SINGLE, - std::move(get_cap_payload)); + auto builder = VendorPacketBuilder::MakeBuilder(CType::STATUS, CommandPdu::GET_CAPABILITIES, + PacketType::SINGLE, std::move(get_cap_payload)); ASSERT_EQ(builder->size(), get_capabilities_request.size()); @@ -81,35 +80,33 @@ TEST(VendorPacketBuilderTest, builderTest) { using TestParam = std::tuple, CommandPdu>; class VendorPacketTest : public ::testing::TestWithParam { - public: +public: std::vector GetPacketData() { return std::get<0>(GetParam()); } CommandPdu GetCommandPdu() { return std::get<1>(GetParam()); } }; INSTANTIATE_TEST_CASE_P( - VendorPacketParameterTest, VendorPacketTest, - ::testing::Values( - std::make_tuple(get_capabilities_request, CommandPdu::GET_CAPABILITIES), - std::make_tuple(get_capabilities_response_company_id, - CommandPdu::GET_CAPABILITIES), - std::make_tuple(get_capabilities_response_events_supported, - CommandPdu::GET_CAPABILITIES), - std::make_tuple(get_element_attributes_request_partial, - CommandPdu::GET_ELEMENT_ATTRIBUTES), - std::make_tuple(get_element_attributes_request_full, - CommandPdu::GET_ELEMENT_ATTRIBUTES), - std::make_tuple(get_elements_attributes_response_full, - CommandPdu::GET_ELEMENT_ATTRIBUTES), - std::make_tuple(get_play_status_request, CommandPdu::GET_PLAY_STATUS), - std::make_tuple(get_play_status_response, CommandPdu::GET_PLAY_STATUS), - std::make_tuple(register_play_status_notification, - CommandPdu::REGISTER_NOTIFICATION), - std::make_tuple(interim_play_status_notification, - CommandPdu::REGISTER_NOTIFICATION), - std::make_tuple(interim_track_changed_notification, - CommandPdu::REGISTER_NOTIFICATION), - std::make_tuple(changed_play_pos_notification, - CommandPdu::REGISTER_NOTIFICATION))); + VendorPacketParameterTest, VendorPacketTest, + ::testing::Values( + std::make_tuple(get_capabilities_request, CommandPdu::GET_CAPABILITIES), + std::make_tuple(get_capabilities_response_company_id, CommandPdu::GET_CAPABILITIES), + std::make_tuple(get_capabilities_response_events_supported, + CommandPdu::GET_CAPABILITIES), + std::make_tuple(get_element_attributes_request_partial, + CommandPdu::GET_ELEMENT_ATTRIBUTES), + std::make_tuple(get_element_attributes_request_full, + CommandPdu::GET_ELEMENT_ATTRIBUTES), + std::make_tuple(get_elements_attributes_response_full, + CommandPdu::GET_ELEMENT_ATTRIBUTES), + std::make_tuple(get_play_status_request, CommandPdu::GET_PLAY_STATUS), + std::make_tuple(get_play_status_response, CommandPdu::GET_PLAY_STATUS), + std::make_tuple(register_play_status_notification, + CommandPdu::REGISTER_NOTIFICATION), + std::make_tuple(interim_play_status_notification, + CommandPdu::REGISTER_NOTIFICATION), + std::make_tuple(interim_track_changed_notification, + CommandPdu::REGISTER_NOTIFICATION), + std::make_tuple(changed_play_pos_notification, CommandPdu::REGISTER_NOTIFICATION))); TEST_P(VendorPacketTest, getterTest) { auto test_packet = TestVendorPacket::Make(GetPacketData()); diff --git a/system/packet/tests/base/iterator_test.cc b/system/packet/tests/base/iterator_test.cc index c4999138261..d5c35f7a09f 100644 --- a/system/packet/tests/base/iterator_test.cc +++ b/system/packet/tests/base/iterator_test.cc @@ -27,9 +27,8 @@ namespace bluetooth { using pair = std::pair; -class IteratorTest - : public ::testing::TestWithParam> { - public: +class IteratorTest : public ::testing::TestWithParam> { +public: std::shared_ptr GetTestPacket() { auto bounds = GetParam(); auto lower_bound = bounds.first; @@ -56,15 +55,13 @@ INSTANTIATE_TEST_CASE_P(IteratorParameterTest, IteratorDeathTest, pair(3, test_l2cap_data.size() - 2))); TEST_F(IteratorDeathTest, iteratorCreateDeathTest) { - auto packet = - TestPacket::Make(test_l2cap_data, 3, test_l2cap_data.size() - 2); + auto packet = TestPacket::Make(test_l2cap_data, 3, test_l2cap_data.size() - 2); // this will silent SIGABRT sent in ASSERT_DEATH below ScopedSilentDeath _silentDeath; ASSERT_DEATH(Iterator(packet, 0), "index_ >= packet->packet_start_index_"); - ASSERT_DEATH(Iterator(packet, test_l2cap_data.size()), - "index_ <= packet->packet_end_index_"); + ASSERT_DEATH(Iterator(packet, test_l2cap_data.size()), "index_ <= packet->packet_end_index_"); } TEST_F(IteratorTest, extractTest) { @@ -89,8 +86,7 @@ TEST_F(IteratorTest, extractBETest) { TEST_P(IteratorTest, payloadBoundsTest) { auto packet = GetTestPacket(); - ASSERT_EQ(static_cast(packet->end() - packet->begin()), - GetTestPacketLength()); + ASSERT_EQ(static_cast(packet->end() - packet->begin()), GetTestPacketLength()); auto it = packet->begin(); for (size_t i = 0; i < GetTestPacketLength(); i++) { @@ -105,14 +101,10 @@ TEST_P(IteratorDeathTest, extractBoundsDeathTest) { // this will silent SIGABRT sent in ASSERT_DEATH below ScopedSilentDeath _silentDeath; - ASSERT_DEATH(bounds_test.extract(), - "index_ != packet_->packet_end_index_"); - ASSERT_DEATH(bounds_test.extract(), - "index_ != packet_->packet_end_index_"); - ASSERT_DEATH(bounds_test.extract(), - "index_ != packet_->packet_end_index_"); - ASSERT_DEATH(bounds_test.extract(), - "index_ != packet_->packet_end_index_"); + ASSERT_DEATH(bounds_test.extract(), "index_ != packet_->packet_end_index_"); + ASSERT_DEATH(bounds_test.extract(), "index_ != packet_->packet_end_index_"); + ASSERT_DEATH(bounds_test.extract(), "index_ != packet_->packet_end_index_"); + ASSERT_DEATH(bounds_test.extract(), "index_ != packet_->packet_end_index_"); } TEST_P(IteratorDeathTest, extractBEBoundsDeathTest) { @@ -122,22 +114,17 @@ TEST_P(IteratorDeathTest, extractBEBoundsDeathTest) { // this will silent SIGABRT sent in ASSERT_DEATH below ScopedSilentDeath _silentDeath; - ASSERT_DEATH(bounds_test.extractBE(), - "index_ != packet_->packet_end_index_"); - ASSERT_DEATH(bounds_test.extractBE(), - "index_ != packet_->packet_end_index_"); - ASSERT_DEATH(bounds_test.extractBE(), - "index_ != packet_->packet_end_index_"); - ASSERT_DEATH(bounds_test.extractBE(), - "index_ != packet_->packet_end_index_"); + ASSERT_DEATH(bounds_test.extractBE(), "index_ != packet_->packet_end_index_"); + ASSERT_DEATH(bounds_test.extractBE(), "index_ != packet_->packet_end_index_"); + ASSERT_DEATH(bounds_test.extractBE(), "index_ != packet_->packet_end_index_"); + ASSERT_DEATH(bounds_test.extractBE(), "index_ != packet_->packet_end_index_"); } TEST_P(IteratorDeathTest, dereferenceDeathTest) { auto packet = GetTestPacket(); Iterator dereference_test = packet->end(); - ASSERT_EQ((*packet)[GetTestPacketLength() - 1], - *(dereference_test - static_cast(1))); + ASSERT_EQ((*packet)[GetTestPacketLength() - 1], *(dereference_test - static_cast(1))); // this will silent SIGABRT sent in ASSERT_DEATH below ScopedSilentDeath _silentDeath; @@ -150,8 +137,7 @@ TEST_P(IteratorTest, plusEqTest) { Iterator plus_eq = packet->begin(); for (size_t i = 0; i < GetTestPacketLength(); i += 2) { ASSERT_EQ(test_l2cap_data[i + GetLowerBound()], *plus_eq) - << "+= test: Dereferenced iterator does not equal expected at index " - << i; + << "+= test: Dereferenced iterator does not equal expected at index " << i; plus_eq += 2; } @@ -163,8 +149,8 @@ TEST_P(IteratorTest, preIncrementTest) { Iterator plus_plus = packet->begin(); for (size_t i = 0; i < GetTestPacketLength() - 1; i++) { ASSERT_EQ(test_l2cap_data[i + GetLowerBound() + 1], *(++plus_plus)) - << "Pre-increment test: Dereferenced iterator does not equal expected " - << "at index " << i; + << "Pre-increment test: Dereferenced iterator does not equal expected " << "at index " + << i; } } @@ -173,8 +159,8 @@ TEST_P(IteratorTest, postIncrementTest) { Iterator plus_plus = packet->begin(); for (size_t i = 0; i < GetTestPacketLength(); i++) { ASSERT_EQ(test_l2cap_data[i + GetLowerBound()], *(plus_plus++)) - << "Post-increment test: Dereferenced iterator does not equal expected " - << "at index " << i; + << "Post-increment test: Dereferenced iterator does not equal expected " << "at index " + << i; } } @@ -183,8 +169,7 @@ TEST_P(IteratorTest, additionTest) { Iterator plus = packet->begin(); for (size_t i = 0; i < GetTestPacketLength(); i++) { ASSERT_EQ(test_l2cap_data[i + GetLowerBound()], *plus) - << "+ test: Dereferenced iterator does not equal expected at index " - << i; + << "+ test: Dereferenced iterator does not equal expected at index " << i; plus = plus + static_cast(1); } } @@ -194,10 +179,8 @@ TEST_P(IteratorTest, minusEqTest) { Iterator minus_eq = packet->end(); minus_eq -= 1; for (int i = GetTestPacketLength() - 1; i > 0; i -= 2) { - ASSERT_EQ(test_l2cap_data[static_cast(i) + GetLowerBound()], - *minus_eq) - << "-= test: Dereferenced iterator does not equal expected at index " - << i; + ASSERT_EQ(test_l2cap_data[static_cast(i) + GetLowerBound()], *minus_eq) + << "-= test: Dereferenced iterator does not equal expected at index " << i; minus_eq -= 2; } } @@ -206,10 +189,9 @@ TEST_P(IteratorTest, preDecrementTest) { auto packet = GetTestPacket(); Iterator minus_minus = packet->end(); for (int i = GetTestPacketLength(); i > 0; i--) { - ASSERT_EQ(test_l2cap_data[static_cast(i) + GetLowerBound() - 1], - *(--minus_minus)) - << "Pre-decrement test: Dereferenced iterator does not equal expected " - << "at index " << i; + ASSERT_EQ(test_l2cap_data[static_cast(i) + GetLowerBound() - 1], *(--minus_minus)) + << "Pre-decrement test: Dereferenced iterator does not equal expected " << "at index " + << i; } } @@ -218,10 +200,9 @@ TEST_P(IteratorTest, postDecrementTest) { Iterator minus_minus = packet->end(); minus_minus--; for (int i = GetTestPacketLength() - 1; i > 0; i--) { - ASSERT_EQ(test_l2cap_data[static_cast(i) + GetLowerBound()], - *(minus_minus--)) - << "Post-decrement test: Dereferenced iterator does not equal expected " - << "at index " << i; + ASSERT_EQ(test_l2cap_data[static_cast(i) + GetLowerBound()], *(minus_minus--)) + << "Post-decrement test: Dereferenced iterator does not equal expected " << "at index " + << i; } } @@ -231,8 +212,7 @@ TEST_P(IteratorTest, subtractionTest) { minus = minus - static_cast(1); for (int i = GetTestPacketLength() - 1; i > 0; i--) { ASSERT_EQ(test_l2cap_data[static_cast(i) + GetLowerBound()], *minus) - << "- test: Dereferenced iterator does not equal expected at index " - << i; + << "- test: Dereferenced iterator does not equal expected at index " << i; minus = minus - static_cast(1); } } @@ -243,7 +223,7 @@ TEST_P(IteratorTest, plusEqBoundsTest) { for (size_t i = 0; i < 100; i++) { plus_eq += i; ASSERT_EQ(packet->end(), plus_eq) - << "+= test: Iterator exceeded the upper bound set by get_length()"; + << "+= test: Iterator exceeded the upper bound set by get_length()"; } } @@ -253,8 +233,7 @@ TEST_P(IteratorTest, preIncrementBoundsTest) { plus_plus--; for (size_t i = 0; i < 100; i++) { ASSERT_EQ(packet->end(), ++plus_plus) - << "Pre-increment test: Iterator exceeded the upper bound set " - "by get_length()"; + << "Pre-increment test: Iterator exceeded the upper bound set by get_length()"; } } @@ -263,8 +242,7 @@ TEST_P(IteratorTest, postIncrementBoundsTest) { Iterator plus_plus = packet->end(); for (size_t i = 0; i < 100; i++) { ASSERT_EQ(packet->end(), plus_plus++) - << "Post-increment test: Iterator exceeded the upper bound set " - "by get_length()"; + << "Post-increment test: Iterator exceeded the upper bound set by get_length()"; } } @@ -274,7 +252,7 @@ TEST_P(IteratorTest, additionBoundsTest) { for (size_t i = 0; i < 100; i++) { plus = plus + static_cast(i); ASSERT_EQ(packet->end(), plus) - << "+ test: Iterator exceeded the upper bound set by get_length()"; + << "+ test: Iterator exceeded the upper bound set by get_length()"; } } @@ -284,8 +262,7 @@ TEST_P(IteratorTest, minusEqBoundsTest) { for (size_t i = 0; i < 100; i++) { minus_eq -= i; ASSERT_EQ(test_l2cap_data[GetLowerBound()], *minus_eq) - << "-= test: Iterator is less than the lower bound set by " - "packet->begin()"; + << "-= test: Iterator is less than the lower bound set by packet->begin()"; } } @@ -294,8 +271,7 @@ TEST_P(IteratorTest, preDecrementBoundsTest) { Iterator minus_minus = packet->begin(); for (size_t i = 0; i < 100; i++) { ASSERT_EQ(test_l2cap_data[GetLowerBound()], *(--minus_minus)) - << "Pre-decrement test: Iterator is less than the lower bound set by " - "packet->begin()"; + << "Pre-decrement test: Iterator is less than the lower bound set by packet->begin()"; } } @@ -304,8 +280,7 @@ TEST_P(IteratorTest, postDecrementBoundsTest) { Iterator minus_minus = packet->begin(); for (size_t i = 0; i < 100; i++) { ASSERT_EQ(test_l2cap_data[GetLowerBound()], *(minus_minus--)) - << "Post-decrement test: Iterator is less than the lower bound set by " - "packet->begin()"; + << "Post-decrement test: Iterator is less than the lower bound set by packet->begin()"; } } @@ -315,8 +290,7 @@ TEST_P(IteratorTest, subtractionBoundsTest) { for (size_t i = 0; i < 100; i++) { minus = minus - static_cast(i); ASSERT_EQ(test_l2cap_data[GetLowerBound()], *minus) - << "- test: Iterator is less than the lower bound set " - "by packet->begin()"; + << "- test: Iterator is less than the lower bound set by packet->begin()"; } } diff --git a/system/packet/tests/base/packet_builder_test.cc b/system/packet/tests/base/packet_builder_test.cc index c057606ba5d..f4c862e8d3a 100644 --- a/system/packet/tests/base/packet_builder_test.cc +++ b/system/packet/tests/base/packet_builder_test.cc @@ -15,6 +15,7 @@ */ #include + #include #include "packet.h" diff --git a/system/packet/tests/base/packet_test.cc b/system/packet/tests/base/packet_test.cc index 5b42e6e1a9d..09e172c4ede 100644 --- a/system/packet/tests/base/packet_test.cc +++ b/system/packet/tests/base/packet_test.cc @@ -28,8 +28,8 @@ namespace bluetooth { // same payload bounds as the old packet. TEST(PacketTest, newPacketFromPacketTest) { // Create a packet with payload bounds - auto packet = TestPacket::Make( - test_avctp_data, test_avctp_data_payload_offset, test_avctp_data.size()); + auto packet = + TestPacket::Make(test_avctp_data, test_avctp_data_payload_offset, test_avctp_data.size()); // Create packet from bounded packet auto new_packet = TestPacket::Make(packet); @@ -46,8 +46,8 @@ TEST(PacketTest, sizeTest) { auto packet = TestPacket::Make(test_avctp_data); ASSERT_EQ(packet->size(), test_avctp_data.size()); - packet = TestPacket::Make(test_avctp_data, test_avctp_data_payload_offset, - test_avctp_data.size()); + packet = + TestPacket::Make(test_avctp_data, test_avctp_data_payload_offset, test_avctp_data.size()); ASSERT_EQ(packet->size(), test_avrcp_data.size()); } @@ -58,8 +58,8 @@ TEST(PacketTest, arrayAccessTest) { ASSERT_EQ(test_l2cap_data[i], (*packet)[i]); } - packet = TestPacket::Make(test_avctp_data, test_avctp_data_payload_offset, - test_avctp_data.size()); + packet = + TestPacket::Make(test_avctp_data, test_avctp_data_payload_offset, test_avctp_data.size()); for (size_t i = 0; i < test_avrcp_data.size(); i++) { ASSERT_EQ(test_avrcp_data[i], (*packet)[i]); } @@ -67,8 +67,7 @@ TEST(PacketTest, arrayAccessTest) { // Test that accessing past the end of the defined payload dies TEST(PacketDeathTest, arrayAccessDeathTest) { - auto packet = - TestPacket::Make(test_l2cap_data, 3, test_l2cap_data.size() - 2); + auto packet = TestPacket::Make(test_l2cap_data, 3, test_l2cap_data.size() - 2); // this will silent SIGABRT sent in ASSERT_DEATH below ScopedSilentDeath _silentDeath; @@ -78,8 +77,8 @@ TEST(PacketDeathTest, arrayAccessDeathTest) { // Test that the iterator and array access operator return the same data TEST(PacketTest, iteratorTest) { - auto packet = TestPacket::Make( - test_avctp_data, test_avctp_data_payload_offset, test_avctp_data.size()); + auto packet = + TestPacket::Make(test_avctp_data, test_avctp_data_payload_offset, test_avctp_data.size()); // Check to see if the data matches auto it = packet->begin(); @@ -92,18 +91,17 @@ TEST(PacketTest, iteratorTest) { } class ChildTestPacket : public TestPacket { - public: +public: using TestPacket::TestPacket; - std::string ToString() const override { return "ChildTestPacket"; }; + std::string ToString() const override { return "ChildTestPacket"; } }; // Test specializing a packet to another packet type TEST(PacketTest, specializeTest) { auto packet = TestPacket::Make(test_l2cap_data); - std::shared_ptr specialized_packet = - Packet::Specialize(packet); + std::shared_ptr specialized_packet = Packet::Specialize(packet); // Test that the new packet is an instance of ChildTestPacket ASSERT_EQ(specialized_packet->ToString(), "ChildTestPacket"); diff --git a/system/packet/tests/base/packet_test_common.h b/system/packet/tests/base/packet_test_common.h index a74735d7fb2..3a16633fcb1 100644 --- a/system/packet/tests/base/packet_test_common.h +++ b/system/packet/tests/base/packet_test_common.h @@ -26,8 +26,8 @@ namespace { template std::string loghex(T x) { std::stringstream tmp; - tmp << "0x" << std::internal << std::hex << std::setfill('0') - << std::setw(sizeof(T) * 2) << (unsigned int)x; + tmp << "0x" << std::internal << std::hex << std::setfill('0') << std::setw(sizeof(T) * 2) + << (unsigned int)x; return tmp.str(); } } // namespace @@ -35,15 +35,15 @@ std::string loghex(T x) { namespace bluetooth { class PacketImpl : public Packet { - public: +public: using Packet::Packet; // Inherit constructors virtual bool IsValid() const { return true; } virtual std::string ToString() const { std::stringstream ss; - ss << "TestPacket: Start = " << packet_start_index_ - << " : End = " << packet_end_index_ << std::endl; + ss << "TestPacket: Start = " << packet_start_index_ << " : End = " << packet_end_index_ + << std::endl; ss << " └ Payload ="; for (auto it = begin(); it != end(); it++) { ss << " " << loghex(*it); @@ -51,7 +51,7 @@ class PacketImpl : public Packet { ss << std::endl; return ss.str(); - }; + } virtual std::pair GetPayloadIndecies() const { return std::pair(packet_start_index_, packet_end_index_); @@ -62,23 +62,22 @@ using TestPacket = TestPacketType; // A helper class that has public accessors to protected methods class TestPacketBuilder : public PacketBuilder { - public: - static std::unique_ptr MakeBuilder( - std::vector data) { +public: + static std::unique_ptr MakeBuilder(std::vector data) { std::unique_ptr builder(new TestPacketBuilder(data)); return builder; - }; + } // Make all the utility functions public - using PacketBuilder::ReserveSpace; using PacketBuilder::AddPayloadOctets1; using PacketBuilder::AddPayloadOctets2; using PacketBuilder::AddPayloadOctets3; using PacketBuilder::AddPayloadOctets4; using PacketBuilder::AddPayloadOctets6; using PacketBuilder::AddPayloadOctets8; + using PacketBuilder::ReserveSpace; - size_t size() const override { return data_.size(); }; + size_t size() const override { return data_.size(); } bool Serialize(const std::shared_ptr& pkt) override { ReserveSpace(pkt, size()); @@ -90,7 +89,7 @@ class TestPacketBuilder : public PacketBuilder { return true; } - TestPacketBuilder(std::vector data) : data_(data){}; + TestPacketBuilder(std::vector data) : data_(data) {} std::vector data_; }; diff --git a/system/packet/tests/fuzzers/avrcp_packet_fuzzer.cc b/system/packet/tests/fuzzers/avrcp_packet_fuzzer.cc index a63ac7049b0..8f305501533 100644 --- a/system/packet/tests/fuzzers/avrcp_packet_fuzzer.cc +++ b/system/packet/tests/fuzzers/avrcp_packet_fuzzer.cc @@ -17,6 +17,7 @@ // Adapted from avrcp_packet_test.cc #include #include + #include "avrcp_packet.h" #include "avrcp_test_packets.h" #include "packet_test_helper.h" @@ -25,9 +26,8 @@ namespace bluetooth { // A helper class that has public accessors to protected methods class TestPacketBuilder : public PacketBuilder { - public: - static std::unique_ptr MakeBuilder( - std::vector data) { +public: + static std::unique_ptr MakeBuilder(std::vector data) { std::unique_ptr builder(new TestPacketBuilder(data)); return builder; } @@ -41,7 +41,7 @@ class TestPacketBuilder : public PacketBuilder { using PacketBuilder::AddPayloadOctets8; using PacketBuilder::ReserveSpace; - size_t size() const override { return data_.size(); }; + size_t size() const override { return data_.size(); } bool Serialize(const std::shared_ptr& pkt) override { ReserveSpace(pkt, size()); @@ -71,11 +71,10 @@ extern "C" int LLVMFuzzerTestOneInput(const char* data, size_t size) { get_capabilities_request_payload.push_back(data[x]); } - auto cap_req_builder = - TestPacketBuilder::MakeBuilder(get_capabilities_request_payload); + auto cap_req_builder = TestPacketBuilder::MakeBuilder(get_capabilities_request_payload); - auto builder = PacketBuilder::MakeBuilder( - CType::STATUS, 0x09, 0x00, Opcode::VENDOR, std::move(cap_req_builder)); + auto builder = PacketBuilder::MakeBuilder(CType::STATUS, 0x09, 0x00, Opcode::VENDOR, + std::move(cap_req_builder)); auto test_packet = TestAvrcpPacket::Make(); } diff --git a/system/packet/tests/fuzzers/change_path_res_fuzzer.cc b/system/packet/tests/fuzzers/change_path_res_fuzzer.cc index 804628a91d9..bd96367431c 100644 --- a/system/packet/tests/fuzzers/change_path_res_fuzzer.cc +++ b/system/packet/tests/fuzzers/change_path_res_fuzzer.cc @@ -33,8 +33,8 @@ using TestChangePathReqPacket = TestPacketType; // Getter extern "C" int LLVMFuzzerTestOneInput(uint8_t* data, size_t size) { FuzzedDataProvider data_provider(data, size); - auto builder = ChangePathResponseBuilder::MakeBuilder( - Status::NO_ERROR, data_provider.ConsumeIntegral()); + auto builder = ChangePathResponseBuilder::MakeBuilder(Status::NO_ERROR, + data_provider.ConsumeIntegral()); auto test_packet = TestChangePathReqPacket::Make(); builder->Serialize(test_packet); diff --git a/system/packet/tests/fuzzers/get_capabilities_res_fuzzer.cc b/system/packet/tests/fuzzers/get_capabilities_res_fuzzer.cc index a01cda138d1..6ba2d3fdfe5 100644 --- a/system/packet/tests/fuzzers/get_capabilities_res_fuzzer.cc +++ b/system/packet/tests/fuzzers/get_capabilities_res_fuzzer.cc @@ -30,12 +30,12 @@ namespace avrcp { extern "C" int LLVMFuzzerTestOneInput(uint8_t* data, size_t size) { FuzzedDataProvider data_provider(data, size); auto builder = GetCapabilitiesResponseBuilder::MakeCompanyIdBuilder( - data_provider.ConsumeIntegral()); + data_provider.ConsumeIntegral()); builder->AddCompanyId(data_provider.ConsumeIntegral()); builder->AddCompanyId(data_provider.ConsumeIntegral()); builder = GetCapabilitiesResponseBuilder::MakeEventsSupportedBuilder( - Event::PLAYBACK_STATUS_CHANGED); + Event::PLAYBACK_STATUS_CHANGED); builder->AddEvent(Event::TRACK_CHANGED); builder->AddEvent(Event::PLAYBACK_POS_CHANGED); diff --git a/system/packet/tests/fuzzers/get_element_attributes_req_packet_fuzzer.cc b/system/packet/tests/fuzzers/get_element_attributes_req_packet_fuzzer.cc index 68c038f9c0a..5c552556d49 100644 --- a/system/packet/tests/fuzzers/get_element_attributes_req_packet_fuzzer.cc +++ b/system/packet/tests/fuzzers/get_element_attributes_req_packet_fuzzer.cc @@ -35,9 +35,10 @@ extern "C" int LLVMFuzzerTestOneInput(const char* data, size_t size) { get_element_attributes_request_full.push_back(data[x]); } - auto test_packet = - TestGetElemAttrReqPacket::Make(get_element_attributes_request_full); - if (!test_packet->IsValid()) return 0; + auto test_packet = TestGetElemAttrReqPacket::Make(get_element_attributes_request_full); + if (!test_packet->IsValid()) { + return 0; + } test_packet->GetIdentifier(); auto tpString = test_packet->ToString(); } diff --git a/system/packet/tests/fuzzers/get_folder_items_req_fuzzer.cc b/system/packet/tests/fuzzers/get_folder_items_req_fuzzer.cc index fe2478cfd65..f16fde3d06b 100644 --- a/system/packet/tests/fuzzers/get_folder_items_req_fuzzer.cc +++ b/system/packet/tests/fuzzers/get_folder_items_req_fuzzer.cc @@ -34,8 +34,7 @@ extern "C" int LLVMFuzzerTestOneInput(const char* data, size_t size) { get_folder_items_request_vfs.push_back(data[x]); } - auto test_packet = - TestGetFolderItemsReqPacket::Make(get_folder_items_request_vfs); + auto test_packet = TestGetFolderItemsReqPacket::Make(get_folder_items_request_vfs); test_packet->GetScope(); test_packet->GetStartItem(); diff --git a/system/packet/tests/fuzzers/get_folder_items_res_fuzzer.cc b/system/packet/tests/fuzzers/get_folder_items_res_fuzzer.cc index 09e525282d7..f0da6af38fd 100644 --- a/system/packet/tests/fuzzers/get_folder_items_res_fuzzer.cc +++ b/system/packet/tests/fuzzers/get_folder_items_res_fuzzer.cc @@ -28,8 +28,8 @@ namespace avrcp { using TestGetFolderItemsReqPacket = TestPacketType; extern "C" int LLVMFuzzerTestOneInput(uint8_t* data, size_t size) { - auto builder = GetFolderItemsResponseBuilder::MakeNowPlayingBuilder( - Status::NO_ERROR, 0x0000, 0xFFFF); + auto builder = + GetFolderItemsResponseBuilder::MakeNowPlayingBuilder(Status::NO_ERROR, 0x0000, 0xFFFF); std::set attributes; FuzzedDataProvider data_provider(data, size); std::string s = data_provider.ConsumeRemainingBytesAsString(); @@ -42,8 +42,7 @@ extern "C" int LLVMFuzzerTestOneInput(uint8_t* data, size_t size) { test_packet->GetData(); // Second test with the same data. - auto builder2 = GetFolderItemsResponseBuilder::MakeVFSBuilder( - Status::NO_ERROR, 0x0000, 0xFFFF); + auto builder2 = GetFolderItemsResponseBuilder::MakeVFSBuilder(Status::NO_ERROR, 0x0000, 0xFFFF); auto folder = FolderItem(0x0000000000000001, 0x00, true, s); builder2->AddFolder(folder); @@ -59,8 +58,8 @@ extern "C" int LLVMFuzzerTestOneInput(uint8_t* data, size_t size) { auto packet_size = BrowsePacket::kMinSize() + 5; packet_size += player1.size(); - auto builder3 = GetFolderItemsResponseBuilder::MakePlayerListBuilder( - Status::NO_ERROR, 0x0000, packet_size); + auto builder3 = GetFolderItemsResponseBuilder::MakePlayerListBuilder(Status::NO_ERROR, 0x0000, + packet_size); builder3->AddMediaPlayer(player1); diff --git a/system/packet/tests/fuzzers/get_item_attributes_req_fuzzer.cc b/system/packet/tests/fuzzers/get_item_attributes_req_fuzzer.cc index 88fdcd38ee4..b6b234491fa 100644 --- a/system/packet/tests/fuzzers/get_item_attributes_req_fuzzer.cc +++ b/system/packet/tests/fuzzers/get_item_attributes_req_fuzzer.cc @@ -36,8 +36,7 @@ extern "C" int LLVMFuzzerTestOneInput(const char* data, size_t size) { for (size_t x = 0; x < size; x++) { get_item_attributes_request.push_back(data[x]); } - auto test_packet = - TestGetItemAttrsReqPacket::Make(get_item_attributes_request); + auto test_packet = TestGetItemAttrsReqPacket::Make(get_item_attributes_request); } return 0; diff --git a/system/packet/tests/fuzzers/get_item_attributes_res_fuzzer.cc b/system/packet/tests/fuzzers/get_item_attributes_res_fuzzer.cc index ca50fb50fa9..350080b5fbf 100644 --- a/system/packet/tests/fuzzers/get_item_attributes_res_fuzzer.cc +++ b/system/packet/tests/fuzzers/get_item_attributes_res_fuzzer.cc @@ -32,8 +32,7 @@ using TestGetItemAttrsReqPacket = TestPacketType; extern "C" int LLVMFuzzerTestOneInput(uint8_t* data, size_t size) { FuzzedDataProvider data_provider(data, size); std::string s = data_provider.ConsumeRemainingBytesAsString(); - auto builder = - GetItemAttributesResponseBuilder::MakeBuilder(Status::NO_ERROR, 0xFFFF); + auto builder = GetItemAttributesResponseBuilder::MakeBuilder(Status::NO_ERROR, 0xFFFF); builder->AddAttributeEntry(Attribute::TITLE, s); builder->AddAttributeEntry(Attribute::ARTIST_NAME, s); builder->AddAttributeEntry(Attribute::ALBUM_NAME, s); diff --git a/system/packet/tests/fuzzers/get_play_status_req_fuzzer.cc b/system/packet/tests/fuzzers/get_play_status_req_fuzzer.cc index 25c549e880a..8262156effd 100644 --- a/system/packet/tests/fuzzers/get_play_status_req_fuzzer.cc +++ b/system/packet/tests/fuzzers/get_play_status_req_fuzzer.cc @@ -33,7 +33,7 @@ extern "C" int LLVMFuzzerTestOneInput(uint8_t* data, size_t size) { FuzzedDataProvider data_provider(data, size); auto builder = GetPlayStatusResponseBuilder::MakeBuilder( - 0, data_provider.ConsumeIntegral(), 0); + 0, data_provider.ConsumeIntegral(), 0); auto test_packet = TestGetPlayStatusRspPacket::Make(); builder->Serialize(test_packet); diff --git a/system/packet/tests/fuzzers/get_play_status_res_fuzzer.cc b/system/packet/tests/fuzzers/get_play_status_res_fuzzer.cc index cfadfb307d1..65957b3012a 100644 --- a/system/packet/tests/fuzzers/get_play_status_res_fuzzer.cc +++ b/system/packet/tests/fuzzers/get_play_status_res_fuzzer.cc @@ -31,7 +31,7 @@ using TestGetPlayStatusRspPacket = TestPacketType; extern "C" int LLVMFuzzerTestOneInput(uint8_t* data, size_t size) { FuzzedDataProvider data_provider(data, size); auto builder = GetPlayStatusResponseBuilder::MakeBuilder( - 0, data_provider.ConsumeIntegral(), 0); + 0, data_provider.ConsumeIntegral(), 0); auto test_packet = TestGetPlayStatusRspPacket::Make(); builder->Serialize(test_packet); diff --git a/system/packet/tests/fuzzers/get_total_number_of_items_req_fuzzer.cc b/system/packet/tests/fuzzers/get_total_number_of_items_req_fuzzer.cc index ef290b0e34c..a00d7ac307f 100644 --- a/system/packet/tests/fuzzers/get_total_number_of_items_req_fuzzer.cc +++ b/system/packet/tests/fuzzers/get_total_number_of_items_req_fuzzer.cc @@ -25,8 +25,7 @@ namespace bluetooth { namespace avrcp { -using TestGetTotalNumItemsReqPacket = - TestPacketType; +using TestGetTotalNumItemsReqPacket = TestPacketType; extern "C" int LLVMFuzzerTestOneInput(const char* data, size_t size) { std::vector get_total_number_of_items_request_now_playing; @@ -37,8 +36,8 @@ extern "C" int LLVMFuzzerTestOneInput(const char* data, size_t size) { get_total_number_of_items_request_now_playing.push_back(data[x]); } - auto test_packet = TestGetTotalNumItemsReqPacket::Make( - get_total_number_of_items_request_now_playing); + auto test_packet = + TestGetTotalNumItemsReqPacket::Make(get_total_number_of_items_request_now_playing); test_packet->GetScope(); test_packet->IsValid(); test_packet->GetData(); diff --git a/system/packet/tests/fuzzers/get_total_number_of_items_res_fuzzer.cc b/system/packet/tests/fuzzers/get_total_number_of_items_res_fuzzer.cc index b456d3230ac..e8230bca51a 100644 --- a/system/packet/tests/fuzzers/get_total_number_of_items_res_fuzzer.cc +++ b/system/packet/tests/fuzzers/get_total_number_of_items_res_fuzzer.cc @@ -27,14 +27,13 @@ namespace bluetooth { namespace avrcp { -using TestGetTotalNumItemsReqPacket = - TestPacketType; +using TestGetTotalNumItemsReqPacket = TestPacketType; extern "C" int LLVMFuzzerTestOneInput(uint8_t* data, size_t size) { FuzzedDataProvider data_provider(data, size); auto builder = GetTotalNumberOfItemsResponseBuilder::MakeBuilder( - Status::NO_ERROR, data_provider.ConsumeIntegral(), - data_provider.ConsumeIntegral()); + Status::NO_ERROR, data_provider.ConsumeIntegral(), + data_provider.ConsumeIntegral()); auto test_packet = TestGetTotalNumItemsReqPacket::Make(); builder->Serialize(test_packet); diff --git a/system/packet/tests/fuzzers/pass_through_packet_fuzzer.cc b/system/packet/tests/fuzzers/pass_through_packet_fuzzer.cc index 52b48bf28b0..3cee7725e76 100644 --- a/system/packet/tests/fuzzers/pass_through_packet_fuzzer.cc +++ b/system/packet/tests/fuzzers/pass_through_packet_fuzzer.cc @@ -36,13 +36,11 @@ extern "C" int LLVMFuzzerTestOneInput(const char* data, size_t size) { pass_through_command_play_pushed.push_back(data[x]); } - auto test_packet = - TestPassThroughPacket::Make(pass_through_command_play_pushed); + auto test_packet = TestPassThroughPacket::Make(pass_through_command_play_pushed); test_packet->GetKeyState(); test_packet->GetOperationId(); - test_packet = - TestPassThroughPacket::Make(pass_through_command_play_released); + test_packet = TestPassThroughPacket::Make(pass_through_command_play_released); test_packet->GetKeyState(); test_packet->GetOperationId(); test_packet->GetData(); diff --git a/system/packet/tests/fuzzers/register_notification_packet_fuzzer.cc b/system/packet/tests/fuzzers/register_notification_packet_fuzzer.cc index 70328d03401..16867f1a6fc 100644 --- a/system/packet/tests/fuzzers/register_notification_packet_fuzzer.cc +++ b/system/packet/tests/fuzzers/register_notification_packet_fuzzer.cc @@ -42,8 +42,7 @@ extern "C" int LLVMFuzzerTestOneInput(const char* data, size_t size) { register_play_status_notification.push_back(data[x]); } - auto test_packet = - TestRegNotifReqPacket::Make(register_play_status_notification); + auto test_packet = TestRegNotifReqPacket::Make(register_play_status_notification); test_packet->GetEventRegistered(); test_packet->GetInterval(); diff --git a/system/packet/tests/fuzzers/reject_packet_fuzzer.cc b/system/packet/tests/fuzzers/reject_packet_fuzzer.cc index 8ef77472ab5..5c0ae1d3c73 100644 --- a/system/packet/tests/fuzzers/reject_packet_fuzzer.cc +++ b/system/packet/tests/fuzzers/reject_packet_fuzzer.cc @@ -36,8 +36,7 @@ extern "C" int LLVMFuzzerTestOneInput(const char* data, size_t size) { rejected_volume_changed_notification.push_back(data[x]); } - auto test_packet = - TestAvrcpPacket::Make(rejected_volume_changed_notification); + auto test_packet = TestAvrcpPacket::Make(rejected_volume_changed_notification); test_packet->GetData(); } diff --git a/system/packet/tests/fuzzers/set_absolute_volume_packet_fuzzer.cc b/system/packet/tests/fuzzers/set_absolute_volume_packet_fuzzer.cc index 28713a9d26b..6b9b3c0c57d 100644 --- a/system/packet/tests/fuzzers/set_absolute_volume_packet_fuzzer.cc +++ b/system/packet/tests/fuzzers/set_absolute_volume_packet_fuzzer.cc @@ -37,8 +37,7 @@ extern "C" int LLVMFuzzerTestOneInput(const char* data, size_t size) { for (size_t x = 0; x < size; x++) { set_absolute_volume_response.push_back(data[x]); } - auto test_packet = - TestSetVolumeRspPacket::Make(set_absolute_volume_response); + auto test_packet = TestSetVolumeRspPacket::Make(set_absolute_volume_response); test_packet->IsValid(); test_packet->GetVolume(); diff --git a/system/packet/tests/fuzzers/set_addressed_player_packet_fuzzer.cc b/system/packet/tests/fuzzers/set_addressed_player_packet_fuzzer.cc index 83277b65f3f..146e377796a 100644 --- a/system/packet/tests/fuzzers/set_addressed_player_packet_fuzzer.cc +++ b/system/packet/tests/fuzzers/set_addressed_player_packet_fuzzer.cc @@ -34,8 +34,7 @@ extern "C" int LLVMFuzzerTestOneInput(const char* data, size_t size) { for (size_t x = 0; x < size; x++) { short_set_addressed_player_request.push_back(data[x]); } - auto test_packet = - TestSetAddrPlayerPacket::Make(set_addressed_player_request); + auto test_packet = TestSetAddrPlayerPacket::Make(set_addressed_player_request); test_packet->GetPlayerId(); test_packet->GetData(); diff --git a/system/packet/tests/fuzzers/set_browsed_player_req_fuzzer.cc b/system/packet/tests/fuzzers/set_browsed_player_req_fuzzer.cc index 0586d3f68ad..2923a6ec7db 100644 --- a/system/packet/tests/fuzzers/set_browsed_player_req_fuzzer.cc +++ b/system/packet/tests/fuzzers/set_browsed_player_req_fuzzer.cc @@ -36,8 +36,7 @@ extern "C" int LLVMFuzzerTestOneInput(const char* data, size_t size) { set_browsed_player_response.push_back(data[x]); } - auto test_packet = - TestSetBrowsedPlayerPacket::Make(set_browsed_player_response); + auto test_packet = TestSetBrowsedPlayerPacket::Make(set_browsed_player_response); test_packet->GetPlayerId(); test_packet->GetData(); diff --git a/system/packet/tests/fuzzers/set_browsed_player_res_fuzzer.cc b/system/packet/tests/fuzzers/set_browsed_player_res_fuzzer.cc index e26e2c5aca8..d18ffc20b4b 100644 --- a/system/packet/tests/fuzzers/set_browsed_player_res_fuzzer.cc +++ b/system/packet/tests/fuzzers/set_browsed_player_res_fuzzer.cc @@ -34,8 +34,7 @@ extern "C" int LLVMFuzzerTestOneInput(const char* data, size_t size) { set_browsed_player_request.push_back(data[x]); } - auto test_packet = - TestSetBrowsedPlayerPacket::Make(set_browsed_player_request); + auto test_packet = TestSetBrowsedPlayerPacket::Make(set_browsed_player_request); test_packet->GetPlayerId(); test_packet->GetData(); diff --git a/system/packet/tests/fuzzers/vendor_packet_fuzzer.cc b/system/packet/tests/fuzzers/vendor_packet_fuzzer.cc index 50a8c5d0d9a..84a717d72a3 100644 --- a/system/packet/tests/fuzzers/vendor_packet_fuzzer.cc +++ b/system/packet/tests/fuzzers/vendor_packet_fuzzer.cc @@ -17,6 +17,7 @@ // Adapted from vendor_packet_test.cc #include + #include #include "avrcp_test_packets.h" @@ -31,7 +32,7 @@ using TestVendorPacket = TestPacketType; using TestParam = std::tuple, CommandPdu>; class VendorPacketTest : public ::testing::TestWithParam { - public: +public: std::vector GetPacketData() { return std::get<0>(GetParam()); } CommandPdu GetCommandPdu() { return std::get<1>(GetParam()); } }; diff --git a/system/packet/tests/packet_test_helper.h b/system/packet/tests/packet_test_helper.h index e03280c440d..e91979317ee 100644 --- a/system/packet/tests/packet_test_helper.h +++ b/system/packet/tests/packet_test_helper.h @@ -27,30 +27,25 @@ namespace bluetooth { // testing easier template class TestPacketType : public PacketType { - public: +public: using PacketType::PacketType; static std::shared_ptr> Make() { - return std::shared_ptr>( - new TestPacketType()); + return std::shared_ptr>(new TestPacketType()); } - static std::shared_ptr> Make( - std::shared_ptr packet) { - return std::shared_ptr>( - new TestPacketType(packet)); + static std::shared_ptr> Make(std::shared_ptr packet) { + return std::shared_ptr>(new TestPacketType(packet)); } - static std::shared_ptr> Make( - std::vector payload) { + static std::shared_ptr> Make(std::vector payload) { size_t end = payload.size(); return Make(std::move(payload), 0, end); } - static std::shared_ptr> Make( - std::vector payload, size_t start, size_t end) { - auto pkt = std::shared_ptr>( - new TestPacketType()); + static std::shared_ptr> Make(std::vector payload, + size_t start, size_t end) { + auto pkt = std::shared_ptr>(new TestPacketType()); pkt->packet_start_index_ = start; pkt->packet_end_index_ = end; pkt->data_ = std::make_shared>(std::move(payload)); @@ -59,9 +54,7 @@ class TestPacketType : public PacketType { const std::vector& GetData() { return *PacketType::data_; } - std::shared_ptr> GetDataPointer() { - return PacketType::data_; - } + std::shared_ptr> GetDataPointer() { return PacketType::data_; } }; namespace avrcp { @@ -108,17 +101,15 @@ inline bool operator==(const AttributeEntry& a, const AttributeEntry& b) { return (a.attribute() == b.attribute()) && (a.value() == b.value()); } -inline bool operator!=(const AttributeEntry& a, const AttributeEntry& b) { - return !(a == b); -} +inline bool operator!=(const AttributeEntry& a, const AttributeEntry& b) { return !(a == b); } template class AttributesResponseBuilderTestUser { - public: +public: using Builder = AttributesResponseBuilder; using Maker = std::function; - private: +private: Maker maker; typename Builder::Builder _builder; size_t _mtu; @@ -142,7 +133,7 @@ class AttributesResponseBuilderTestUser { size_t expected_size() { return Builder::kHeaderSize() + _current_size; } - public: +public: std::string getReport() const { return _report.str(); } AttributesResponseBuilderTestUser(size_t m_size, Maker maker) @@ -170,11 +161,10 @@ class AttributesResponseBuilderTestUser { void finishTest() { reset(); if (_order_control.size() != _sended_order.size()) { - _report << __func__ << ": testOrder FAIL: " - << "the count of entries which should send (" + _report << __func__ << ": testOrder FAIL: " << "the count of entries which should send (" << _order_control.size() << ") is not equal to sended entries(" - << _sended_order.size() << ")) \n input:\n " - << to_string(_order_control) << "\n sended:\n" + << _sended_order.size() << ")) \n input:\n " << to_string(_order_control) + << "\n sended:\n" << to_string(_sended_order) << "\n"; _order_test_result = false; return; @@ -204,13 +194,12 @@ class AttributesResponseBuilderTestUser { } } - private: +private: void wholeEntry(size_t f, AttributeEntry&& entry) { _control_set.insert(entry); _order_control.push_back(entry); if (_builder->size() != expected_size()) { - _report << __func__ << "FAIL for \"" << to_string(entry) - << "\": not allowed to add.\n"; + _report << __func__ << "FAIL for \"" << to_string(entry) << "\": not allowed to add.\n"; _test_result = false; } } @@ -218,35 +207,29 @@ class AttributesResponseBuilderTestUser { void fractionEntry(size_t f, AttributeEntry&& entry) { auto l_value = entry.value().size() - (entry.size() - f); if (f != 0) { - auto pushed_entry = AttributeEntry( - entry.attribute(), std::string(entry.value(), 0, l_value)); + auto pushed_entry = AttributeEntry(entry.attribute(), std::string(entry.value(), 0, l_value)); _control_set.insert(pushed_entry); _order_control.push_back(pushed_entry); } if (expected_size() != _builder->size()) { _test_result = false; - _report << __func__ << "FAIL for \"" << to_string(entry) - << "\": not allowed to add.\n"; + _report << __func__ << "FAIL for \"" << to_string(entry) << "\": not allowed to add.\n"; } - if (_builder->size() != expected_size() || - _builder->entries_.size() != _entry_counter) { - _report << __func__ << "FAIL for \"" << to_string(entry) - << "\": unexpected size of packet\n"; + if (_builder->size() != expected_size() || _builder->entries_.size() != _entry_counter) { + _report << __func__ << "FAIL for \"" << to_string(entry) << "\": unexpected size of packet\n"; _test_result = false; } - for (auto dat = _builder->entries_.begin(), ex = _control_set.begin(); - ex != _control_set.end(); ++dat, ++ex) { + for (auto dat = _builder->entries_.begin(), ex = _control_set.begin(); ex != _control_set.end(); + ++dat, ++ex) { if (*dat != *ex) { - _report << __func__ << "FAIL for \"" << to_string(entry) - << "\": unexpected entry order\n"; + _report << __func__ << "FAIL for \"" << to_string(entry) << "\": unexpected entry order\n"; _test_result = false; } } auto tail = (f == 0) ? entry - : AttributeEntry(entry.attribute(), - std::string(entry.value(), l_value)); + : AttributeEntry(entry.attribute(), std::string(entry.value(), l_value)); if (_builder->entries_.size() != 0) { reset(); AddAttributeEntry(tail); @@ -262,7 +245,7 @@ class AttributesResponseBuilderTestUser { template class FragmentationBuilderHelper { - public: +public: using Builder = AttributesBuilder; using Helper = AttributesResponseBuilderTestUser; using Maker = typename Helper::Maker; @@ -270,8 +253,8 @@ class FragmentationBuilderHelper { FragmentationBuilderHelper(size_t mtu, Maker m) : _helper(mtu, m) {} template - void runTest(const TestCollection& test_data, size_t mtu, - bool expect_fragmentation = true, bool expect_ordering = true) { + void runTest(const TestCollection& test_data, size_t mtu, bool expect_fragmentation = true, + bool expect_ordering = true) { _helper.startTest(mtu); for (auto& i : test_data) { @@ -279,13 +262,11 @@ class FragmentationBuilderHelper { } _helper.finishTest(); - EXPECT_EQ(expect_fragmentation, _helper.testResult()) - << "Report: " << _helper.getReport(); - EXPECT_EQ(expect_ordering, _helper.testOrder()) - << "Report: " << _helper.getReport(); + EXPECT_EQ(expect_fragmentation, _helper.testResult()) << "Report: " << _helper.getReport(); + EXPECT_EQ(expect_ordering, _helper.testOrder()) << "Report: " << _helper.getReport(); } - private: +private: Helper _helper; }; } // namespace avrcp diff --git a/system/packet/tests/test_packets.h b/system/packet/tests/test_packets.h index c7628cfa21b..9ae773006d2 100644 --- a/system/packet/tests/test_packets.h +++ b/system/packet/tests/test_packets.h @@ -22,47 +22,41 @@ namespace { // L2CAP packet pulled from Wireshark std::vector test_l2cap_data = { - 0x02, 0xdc, 0x2e, 0x66, 0x00, 0x62, 0x00, 0x13, 0x00, 0x0a, 0x00, 0x00, - 0x00, 0x01, 0x00, 0xb8, 0x9c, 0x00, 0x80, 0x56, 0x00, 0x43, 0xc4, 0x9a, - 0x86, 0x36, 0x10, 0x00, 0x26, 0x43, 0x1c, 0x9b, 0x88, 0x1d, 0x06, 0x03, - 0x26, 0x86, 0x36, 0x10, 0x00, 0x26, 0x43, 0xb4, 0x9b, 0x88, 0x1d, 0x06, - 0x03, 0x26, 0x86, 0x36, 0x10, 0x00, 0x26, 0x43, 0xe4, 0x9b, 0x88, 0x1d, - 0x06, 0x03, 0x26, 0x86, 0x36, 0x10, 0x00, 0x26, 0x43, 0xf8, 0x9b, 0x88, - 0x1d, 0x06, 0x03, 0x26, 0x86, 0x36, 0x10, 0x00, 0x26, 0x43, 0x08, 0x9c, - 0x88, 0x1d, 0x06, 0x03, 0x26, 0x86, 0x36, 0x10, 0x00, 0x26, 0x43, 0xa8, - 0x9c, 0x88, 0x1d, 0x06, 0x03, 0x26, 0x86, 0x36, 0x10, 0x00, 0x26}; + 0x02, 0xdc, 0x2e, 0x66, 0x00, 0x62, 0x00, 0x13, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x01, + 0x00, 0xb8, 0x9c, 0x00, 0x80, 0x56, 0x00, 0x43, 0xc4, 0x9a, 0x86, 0x36, 0x10, 0x00, + 0x26, 0x43, 0x1c, 0x9b, 0x88, 0x1d, 0x06, 0x03, 0x26, 0x86, 0x36, 0x10, 0x00, 0x26, + 0x43, 0xb4, 0x9b, 0x88, 0x1d, 0x06, 0x03, 0x26, 0x86, 0x36, 0x10, 0x00, 0x26, 0x43, + 0xe4, 0x9b, 0x88, 0x1d, 0x06, 0x03, 0x26, 0x86, 0x36, 0x10, 0x00, 0x26, 0x43, 0xf8, + 0x9b, 0x88, 0x1d, 0x06, 0x03, 0x26, 0x86, 0x36, 0x10, 0x00, 0x26, 0x43, 0x08, 0x9c, + 0x88, 0x1d, 0x06, 0x03, 0x26, 0x86, 0x36, 0x10, 0x00, 0x26, 0x43, 0xa8, 0x9c, 0x88, + 0x1d, 0x06, 0x03, 0x26, 0x86, 0x36, 0x10, 0x00, 0x26}; // AVCTP packet pulled from Wireshark std::vector test_avctp_data = { - 0xf2, 0x11, 0x0e, 0x0c, 0x48, 0x00, 0x00, 0x19, 0x58, 0x20, 0x00, 0x00, - 0x85, 0x07, 0x00, 0x00, 0x00, 0x01, 0x00, 0x6a, 0x00, 0x22, 0x57, 0x61, - 0x72, 0x20, 0x50, 0x69, 0x67, 0x73, 0x20, 0x28, 0x32, 0x30, 0x30, 0x39, - 0x20, 0x52, 0x65, 0x6d, 0x61, 0x73, 0x74, 0x65, 0x72, 0x65, 0x64, 0x20, - 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x29, 0x00, 0x00, 0x00, 0x02, - 0x00, 0x6a, 0x00, 0x0d, 0x42, 0x6c, 0x61, 0x63, 0x6b, 0x20, 0x53, 0x61, - 0x62, 0x62, 0x61, 0x74, 0x68, 0x00, 0x00, 0x00, 0x03, 0x00, 0x6a, 0x00, - 0x17, 0x54, 0x68, 0x65, 0x20, 0x55, 0x6c, 0x74, 0x69, 0x6d, 0x61, 0x74, - 0x65, 0x20, 0x43, 0x6f, 0x6c, 0x6c, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, - 0x00, 0x00, 0x00, 0x04, 0x00, 0x6a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, - 0x00, 0x6a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x6a, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x07, 0x00, 0x6a, 0x00, 0x06, 0x34, 0x37, 0x33, 0x30, - 0x30, 0x30}; + 0xf2, 0x11, 0x0e, 0x0c, 0x48, 0x00, 0x00, 0x19, 0x58, 0x20, 0x00, 0x00, 0x85, 0x07, 0x00, + 0x00, 0x00, 0x01, 0x00, 0x6a, 0x00, 0x22, 0x57, 0x61, 0x72, 0x20, 0x50, 0x69, 0x67, 0x73, + 0x20, 0x28, 0x32, 0x30, 0x30, 0x39, 0x20, 0x52, 0x65, 0x6d, 0x61, 0x73, 0x74, 0x65, 0x72, + 0x65, 0x64, 0x20, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x29, 0x00, 0x00, 0x00, 0x02, + 0x00, 0x6a, 0x00, 0x0d, 0x42, 0x6c, 0x61, 0x63, 0x6b, 0x20, 0x53, 0x61, 0x62, 0x62, 0x61, + 0x74, 0x68, 0x00, 0x00, 0x00, 0x03, 0x00, 0x6a, 0x00, 0x17, 0x54, 0x68, 0x65, 0x20, 0x55, + 0x6c, 0x74, 0x69, 0x6d, 0x61, 0x74, 0x65, 0x20, 0x43, 0x6f, 0x6c, 0x6c, 0x65, 0x63, 0x74, + 0x69, 0x6f, 0x6e, 0x00, 0x00, 0x00, 0x04, 0x00, 0x6a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, + 0x00, 0x6a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x6a, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x07, 0x00, 0x6a, 0x00, 0x06, 0x34, 0x37, 0x33, 0x30, 0x30, 0x30}; // An avrcp packet pulled from wireshark. This data is the payload of // test_avctp_packet size_t test_avctp_data_payload_offset = 3; std::vector test_avrcp_data = { - 0x0c, 0x48, 0x00, 0x00, 0x19, 0x58, 0x20, 0x00, 0x00, 0x85, 0x07, 0x00, - 0x00, 0x00, 0x01, 0x00, 0x6a, 0x00, 0x22, 0x57, 0x61, 0x72, 0x20, 0x50, - 0x69, 0x67, 0x73, 0x20, 0x28, 0x32, 0x30, 0x30, 0x39, 0x20, 0x52, 0x65, - 0x6d, 0x61, 0x73, 0x74, 0x65, 0x72, 0x65, 0x64, 0x20, 0x56, 0x65, 0x72, - 0x73, 0x69, 0x6f, 0x6e, 0x29, 0x00, 0x00, 0x00, 0x02, 0x00, 0x6a, 0x00, - 0x0d, 0x42, 0x6c, 0x61, 0x63, 0x6b, 0x20, 0x53, 0x61, 0x62, 0x62, 0x61, - 0x74, 0x68, 0x00, 0x00, 0x00, 0x03, 0x00, 0x6a, 0x00, 0x17, 0x54, 0x68, - 0x65, 0x20, 0x55, 0x6c, 0x74, 0x69, 0x6d, 0x61, 0x74, 0x65, 0x20, 0x43, - 0x6f, 0x6c, 0x6c, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x00, 0x00, 0x00, - 0x04, 0x00, 0x6a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x6a, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x6a, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x07, 0x00, 0x6a, 0x00, 0x06, 0x34, 0x37, 0x33, 0x30, 0x30, 0x30}; + 0x0c, 0x48, 0x00, 0x00, 0x19, 0x58, 0x20, 0x00, 0x00, 0x85, 0x07, 0x00, 0x00, 0x00, 0x01, + 0x00, 0x6a, 0x00, 0x22, 0x57, 0x61, 0x72, 0x20, 0x50, 0x69, 0x67, 0x73, 0x20, 0x28, 0x32, + 0x30, 0x30, 0x39, 0x20, 0x52, 0x65, 0x6d, 0x61, 0x73, 0x74, 0x65, 0x72, 0x65, 0x64, 0x20, + 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x29, 0x00, 0x00, 0x00, 0x02, 0x00, 0x6a, 0x00, + 0x0d, 0x42, 0x6c, 0x61, 0x63, 0x6b, 0x20, 0x53, 0x61, 0x62, 0x62, 0x61, 0x74, 0x68, 0x00, + 0x00, 0x00, 0x03, 0x00, 0x6a, 0x00, 0x17, 0x54, 0x68, 0x65, 0x20, 0x55, 0x6c, 0x74, 0x69, + 0x6d, 0x61, 0x74, 0x65, 0x20, 0x43, 0x6f, 0x6c, 0x6c, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, + 0x00, 0x00, 0x00, 0x04, 0x00, 0x6a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x6a, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x6a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x00, 0x6a, + 0x00, 0x06, 0x34, 0x37, 0x33, 0x30, 0x30, 0x30}; } // namespace diff --git a/system/pdl/hci/address.cc b/system/pdl/hci/address.cc index 8736c16de8d..5b9a90c9d48 100644 --- a/system/pdl/hci/address.cc +++ b/system/pdl/hci/address.cc @@ -32,9 +32,7 @@ const Address Address::kEmpty{{0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}; // Address cannot initialize member variables as it is a POD type // NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init) -Address::Address(const uint8_t (&addr)[6]) { - std::copy(addr, addr + kLength, data()); -} +Address::Address(const uint8_t (&addr)[6]) { std::copy(addr, addr + kLength, data()); } Address::Address(std::initializer_list l) { std::copy(l.begin(), std::min(l.begin() + kLength, l.end()), data()); @@ -47,8 +45,7 @@ std::string Address::_ToMaskedColonSepHexString(int bytes_to_mask) const { if (count++ < bytes_to_mask) { ss << "xx"; } else { - ss << std::nouppercase << std::hex << std::setw(2) << std::setfill('0') - << +*it; + ss << std::nouppercase << std::hex << std::setw(2) << std::setfill('0') << +*it; } if (std::next(it) != address.rend()) { ss << ':'; @@ -59,17 +56,11 @@ std::string Address::_ToMaskedColonSepHexString(int bytes_to_mask) const { std::string Address::ToString() const { return _ToMaskedColonSepHexString(0); } -std::string Address::ToColonSepHexString() const { - return _ToMaskedColonSepHexString(0); -} +std::string Address::ToColonSepHexString() const { return _ToMaskedColonSepHexString(0); } -std::string Address::ToStringForLogging() const { - return _ToMaskedColonSepHexString(0); -} +std::string Address::ToStringForLogging() const { return _ToMaskedColonSepHexString(0); } -std::string Address::ToRedactedStringForLogging() const { - return _ToMaskedColonSepHexString(4); -} +std::string Address::ToRedactedStringForLogging() const { return _ToMaskedColonSepHexString(4); } std::string Address::ToLegacyConfigString() const { return ToString(); } @@ -129,7 +120,7 @@ bool Address::FromString(const std::string& from, Address& to) { size_t Address::FromOctets(const uint8_t* from) { std::copy(from, from + kLength, data()); return kLength; -}; +} bool Address::IsValidAddress(const std::string& address) { return Address::FromString(address).has_value(); diff --git a/system/pdl/hci/class_of_device.cc b/system/pdl/hci/class_of_device.cc index c4506f5dc67..a7b16dce0f2 100644 --- a/system/pdl/hci/class_of_device.cc +++ b/system/pdl/hci/class_of_device.cc @@ -32,20 +32,17 @@ namespace hci { // NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init) ClassOfDevice::ClassOfDevice(const uint8_t (&class_of_device)[kLength]) { std::copy(class_of_device, class_of_device + kLength, cod.data()); -}; +} std::string ClassOfDevice::ToString() const { char buffer[] = "000-0-00"; std::snprintf(&buffer[0], sizeof(buffer), "%03x-%01x-%02x", - (static_cast(cod[2]) << 4) | cod[1] >> 4, - cod[1] & 0x0f, cod[0]); + (static_cast(cod[2]) << 4) | cod[1] >> 4, cod[1] & 0x0f, cod[0]); std::string str(buffer); return str; } -std::string ClassOfDevice::ToLegacyConfigString() const { - return std::to_string(ToUint32Legacy()); -} +std::string ClassOfDevice::ToLegacyConfigString() const { return std::to_string(ToUint32Legacy()); } std::optional ClassOfDevice::FromString(const std::string& str) { if (str.length() != 8) { @@ -111,8 +108,7 @@ std::optional ClassOfDevice::FromUint32Legacy(uint32_t cod_int) { return result; } -std::optional ClassOfDevice::FromLegacyConfigString( - const std::string& str) { +std::optional ClassOfDevice::FromLegacyConfigString(const std::string& str) { char* ptr = nullptr; auto num = std::strtoull(str.data(), &ptr, 10); if (num > 0xffffff) { @@ -121,14 +117,12 @@ std::optional ClassOfDevice::FromLegacyConfigString( return FromUint32Legacy(static_cast(num)); } -uint32_t ClassOfDevice::ToUint32Legacy() const { - return (cod[2]) | (cod[1] << 8) | (cod[0] << 16); -} +uint32_t ClassOfDevice::ToUint32Legacy() const { return (cod[2]) | (cod[1] << 8) | (cod[0] << 16); } size_t ClassOfDevice::FromOctets(const uint8_t* from) { std::copy(from, from + kLength, data()); return kLength; -}; +} bool ClassOfDevice::IsValid(const std::string& cod) { return ClassOfDevice::FromString(cod).has_value(); diff --git a/system/pdl/hci/include/hci/address.h b/system/pdl/hci/include/hci/address.h index d176a74774d..3ae0131ca62 100644 --- a/system/pdl/hci/include/hci/address.h +++ b/system/pdl/hci/include/hci/address.h @@ -36,7 +36,7 @@ namespace hci { class Address final : public packet::CustomFieldFixedSizeInterface

, public storage::Serializable
, public bluetooth::common::IRedactableLoggable { - public: +public: static constexpr size_t kLength = 6; // Bluetooth MAC address bytes saved in little endian format. @@ -65,7 +65,7 @@ class Address final : public packet::CustomFieldFixedSizeInterface
, bool operator<(const Address& rhs) const { return address < rhs.address; } bool operator==(const Address& rhs) const { return address == rhs.address; } - bool operator>(const Address& rhs) const { return (rhs < *this); } + bool operator>(const Address& rhs) const { return rhs < *this; } bool operator<=(const Address& rhs) const { return !(*this > rhs); } bool operator>=(const Address& rhs) const { return !(*this < rhs); } bool operator!=(const Address& rhs) const { return !(*this == rhs); } @@ -85,7 +85,7 @@ class Address final : public packet::CustomFieldFixedSizeInterface
, static const Address kEmpty; // 00:00:00:00:00:00 static const Address kAny; // FF:FF:FF:FF:FF:FF - private: +private: std::string _ToMaskedColonSepHexString(int bytes_to_mask) const; }; @@ -105,8 +105,7 @@ struct hash { std::size_t operator()(const bluetooth::hci::Address& val) const { static_assert(sizeof(uint64_t) >= bluetooth::hci::Address::kLength); uint64_t int_addr = 0; - memcpy(reinterpret_cast(&int_addr), val.data(), - bluetooth::hci::Address::kLength); + memcpy(reinterpret_cast(&int_addr), val.data(), bluetooth::hci::Address::kLength); return std::hash{}(int_addr); } }; @@ -119,11 +118,10 @@ namespace fmt { template <> struct formatter : formatter { template - typename Context::iterator format(const bluetooth::hci::Address& address, - Context& ctx) const { + typename Context::iterator format(const bluetooth::hci::Address& address, Context& ctx) const { std::string repr = bluetooth::os::should_log_be_redacted() - ? address.ToRedactedStringForLogging() - : address.ToStringForLogging(); + ? address.ToRedactedStringForLogging() + : address.ToStringForLogging(); return fmt::formatter::format(repr, ctx); } }; diff --git a/system/pdl/hci/include/hci/class_of_device.h b/system/pdl/hci/include/hci/class_of_device.h index a310ba9c661..d3a57fcc331 100644 --- a/system/pdl/hci/include/hci/class_of_device.h +++ b/system/pdl/hci/include/hci/class_of_device.h @@ -28,10 +28,9 @@ namespace bluetooth { namespace hci { -class ClassOfDevice final - : public packet::CustomFieldFixedSizeInterface, - public storage::Serializable { - public: +class ClassOfDevice final : public packet::CustomFieldFixedSizeInterface, + public storage::Serializable { +public: static constexpr size_t kLength = 3; std::array cod = {}; @@ -47,12 +46,11 @@ class ClassOfDevice final std::string ToString() const; static std::optional FromString(const std::string& str); std::string ToLegacyConfigString() const override; - static std::optional FromLegacyConfigString( - const std::string& str); + static std::optional FromLegacyConfigString(const std::string& str); bool operator<(const ClassOfDevice& rhs) const { return cod < rhs.cod; } bool operator==(const ClassOfDevice& rhs) const { return cod == rhs.cod; } - bool operator>(const ClassOfDevice& rhs) const { return (rhs < *this); } + bool operator>(const ClassOfDevice& rhs) const { return rhs < *this; } bool operator<=(const ClassOfDevice& rhs) const { return !(*this > rhs); } bool operator>=(const ClassOfDevice& rhs) const { return !(*this < rhs); } bool operator!=(const ClassOfDevice& rhs) const { return !(*this == rhs); } diff --git a/system/profile/avrcp/avrcp_config.h b/system/profile/avrcp/avrcp_config.h index 3f9e74d0e2c..79e62e72a9c 100644 --- a/system/profile/avrcp/avrcp_config.h +++ b/system/profile/avrcp/avrcp_config.h @@ -27,16 +27,12 @@ // Supported Features for AVRCP Version 1.5 #ifndef AVRCP_SUPF_TG_1_5 -#define AVRCP_SUPF_TG_1_5 \ - (AVRC_SUPF_TG_CAT1 | AVRC_SUPF_TG_MULTI_PLAYER | \ - AVRC_SUPF_TG_BROWSE) +#define AVRCP_SUPF_TG_1_5 (AVRC_SUPF_TG_CAT1 | AVRC_SUPF_TG_MULTI_PLAYER | AVRC_SUPF_TG_BROWSE) #endif // Supported Features for AVRCP Version 1.4 #ifndef AVRCP_SUPF_TG_1_4 -#define AVRCP_SUPF_TG_1_4 \ - (AVRC_SUPF_TG_CAT1 | AVRC_SUPF_TG_MULTI_PLAYER | \ - AVRC_SUPF_TG_BROWSE) +#define AVRCP_SUPF_TG_1_4 (AVRC_SUPF_TG_CAT1 | AVRC_SUPF_TG_MULTI_PLAYER | AVRC_SUPF_TG_BROWSE) #endif // Supported Features for AVRCP Version 1.3 "Compatibility Mode" diff --git a/system/profile/avrcp/avrcp_internal.h b/system/profile/avrcp/avrcp_internal.h index d29d785867a..665382ce61d 100644 --- a/system/profile/avrcp/avrcp_internal.h +++ b/system/profile/avrcp/avrcp_internal.h @@ -25,32 +25,28 @@ #include "types/raw_address.h" /** - * Wrapper classes for the API functions currently defined in "packages/modules/Bluetooth/system/stack". - * ConnectionHandler and AvrcpDevice both use this interface to manage AVRCP - * SDP, connections, and packets. We use these intermediate interfaces instead - * of calling the functions directly in order to make mocking and testing - * easier. + * Wrapper classes for the API functions currently defined in + * "packages/modules/Bluetooth/system/stack". ConnectionHandler and AvrcpDevice both use this + * interface to manage AVRCP SDP, connections, and packets. We use these intermediate interfaces + * instead of calling the functions directly in order to make mocking and testing easier. */ -// TODO (apanicke): Update the api's in "packages/modules/Bluetooth/system/stack" so that no wrapper is -// required +// TODO (apanicke): Update the api's in "packages/modules/Bluetooth/system/stack" so that no wrapper +// is required class AvrcpInterface { - public: +public: virtual uint16_t GetAvrcpVersion() = 0; virtual uint16_t AddRecord(uint16_t service_uuid, const char* p_service_name, - const char* p_provider_name, uint16_t categories, - uint32_t sdp_handle, bool browse_supported, - uint16_t profile_version, + const char* p_provider_name, uint16_t categories, uint32_t sdp_handle, + bool browse_supported, uint16_t profile_version, uint16_t cover_art_psm) = 0; virtual uint16_t RemoveRecord(uint32_t sdp_handle) = 0; virtual uint16_t FindService(uint16_t service_uuid, const RawAddress& bd_addr, - tAVRC_SDP_DB_PARAMS* p_db, - tAVRC_FIND_CBACK p_cback) = 0; + tAVRC_SDP_DB_PARAMS* p_db, tAVRC_FIND_CBACK p_cback) = 0; - virtual uint16_t Open(uint8_t* p_handle, tAVRC_CONN_CB* p_ccb, - const RawAddress& bd_addr) = 0; + virtual uint16_t Open(uint8_t* p_handle, tAVRC_CONN_CB* p_ccb, const RawAddress& bd_addr) = 0; virtual uint16_t OpenBrowse(uint8_t handle, uint8_t conn_role) = 0; @@ -62,42 +58,35 @@ class AvrcpInterface { virtual uint16_t CloseBrowse(uint8_t handle) = 0; - virtual uint16_t MsgReq(uint8_t handle, uint8_t label, uint8_t ctype, - BT_HDR* p_pkt) = 0; + virtual uint16_t MsgReq(uint8_t handle, uint8_t label, uint8_t ctype, BT_HDR* p_pkt) = 0; - virtual void SaveControllerVersion(const RawAddress& bdaddr, - uint16_t version) = 0; + virtual void SaveControllerVersion(const RawAddress& bdaddr, uint16_t version) = 0; virtual ~AvrcpInterface() = default; }; class SdpInterface { - public: +public: virtual bool InitDiscoveryDb(tSDP_DISCOVERY_DB* a, uint32_t b, uint16_t c, - const bluetooth::Uuid* d, uint16_t e, - uint16_t* f) = 0; + const bluetooth::Uuid* d, uint16_t e, uint16_t* f) = 0; - virtual bool ServiceSearchAttributeRequest(const RawAddress& a, - tSDP_DISCOVERY_DB* b, + virtual bool ServiceSearchAttributeRequest(const RawAddress& a, tSDP_DISCOVERY_DB* b, tSDP_DISC_CMPL_CB* c) = 0; - virtual tSDP_DISC_REC* FindServiceInDb(tSDP_DISCOVERY_DB* a, uint16_t b, - t_sdp_disc_rec* c) = 0; + virtual tSDP_DISC_REC* FindServiceInDb(tSDP_DISCOVERY_DB* a, uint16_t b, t_sdp_disc_rec* c) = 0; virtual tSDP_DISC_ATTR* FindAttributeInRec(t_sdp_disc_rec* a, uint16_t b) = 0; - virtual bool FindProfileVersionInRec(t_sdp_disc_rec* a, uint16_t b, - uint16_t* c) = 0; + virtual bool FindProfileVersionInRec(t_sdp_disc_rec* a, uint16_t b, uint16_t* c) = 0; virtual ~SdpInterface() = default; }; class A2dpInterface { - public: +public: virtual RawAddress active_peer() = 0; virtual bool is_peer_in_silence_mode(const RawAddress& peer_address) = 0; - virtual void connect_audio_sink_delayed(uint8_t handle, - const RawAddress& peer_address) = 0; + virtual void connect_audio_sink_delayed(uint8_t handle, const RawAddress& peer_address) = 0; virtual uint16_t find_audio_sink_service(const RawAddress& peer_address, tA2DP_FIND_CBACK p_cback) = 0; virtual ~A2dpInterface() = default; diff --git a/system/profile/avrcp/avrcp_message_converter.h b/system/profile/avrcp/avrcp_message_converter.h index db6dd4946c9..724bc2739fe 100644 --- a/system/profile/avrcp/avrcp_message_converter.h +++ b/system/profile/avrcp/avrcp_message_converter.h @@ -27,12 +27,12 @@ // These classes are temporary placeholders to easily switch between BT_HDR and // packets. class VectorPacket : public ::bluetooth::Packet { - public: +public: using Packet::Packet; // Inherit constructors static std::shared_ptr Make() { return std::shared_ptr(new VectorPacket()); - }; + } static std::shared_ptr Make(std::vector payload) { auto pkt = VectorPacket::Make(); @@ -40,9 +40,9 @@ class VectorPacket : public ::bluetooth::Packet { pkt->packet_end_index_ = payload.size(); pkt->data_ = std::make_shared>(std::move(payload)); return pkt; - }; + } - const std::vector& GetData() { return *data_; }; + const std::vector& GetData() { return *data_; } virtual std::string ToString() const override { std::stringstream ss; @@ -54,7 +54,7 @@ class VectorPacket : public ::bluetooth::Packet { ss << std::endl; return ss.str(); - }; + } virtual std::pair GetPayloadIndecies() const override { return std::pair(packet_start_index_, packet_end_index_); @@ -66,7 +66,7 @@ class VectorPacket : public ::bluetooth::Packet { // TODO (apanicke): When deleting the old AVRCP Stack, remove this class and // instead create a BT_HDR Parsing packet. class AvrcpMessageConverter { - public: +public: static std::shared_ptr<::bluetooth::Packet> Parse(tAVRC_MSG* m) { std::vector data; diff --git a/system/profile/avrcp/connection_handler.cc b/system/profile/avrcp/connection_handler.cc index 68b3bda739e..987b4faaaea 100644 --- a/system/profile/avrcp/connection_handler.cc +++ b/system/profile/avrcp/connection_handler.cc @@ -73,9 +73,8 @@ bool IsAbsoluteVolumeEnabled(const RawAddress* bdaddr) { return true; } -bool ConnectionHandler::Initialize(const ConnectionCallback& callback, - AvrcpInterface* avrcp, SdpInterface* sdp, - VolumeInterface* vol) { +bool ConnectionHandler::Initialize(const ConnectionCallback& callback, AvrcpInterface* avrcp, + SdpInterface* sdp, VolumeInterface* vol) { log::assert_that(instance_ == nullptr, "assert failed: instance_ == nullptr"); log::assert_that(avrcp != nullptr, "assert failed: avrcp != nullptr"); log::assert_that(sdp != nullptr, "assert failed: sdp != nullptr"); @@ -102,8 +101,7 @@ bool ConnectionHandler::CleanUp() { // TODO (apanicke): Cleanup the SDP Entries here std::lock_guard lock(device_map_lock); - for (auto entry = instance_->device_map_.begin(); - entry != instance_->device_map_.end();) { + for (auto entry = instance_->device_map_.begin(); entry != instance_->device_map_.end();) { auto curr = entry; entry++; curr->second->DeviceDisconnected(); @@ -135,15 +133,14 @@ bool ConnectionHandler::ConnectDevice(const RawAddress& bdaddr) { } } - auto connection_lambda = [](ConnectionHandler* instance_, - const RawAddress& bdaddr, uint16_t status, - uint16_t version, uint16_t features) { + auto connection_lambda = [](ConnectionHandler* instance_, const RawAddress& bdaddr, + uint16_t status, uint16_t version, uint16_t features) { log::info("SDP Completed features=0x{:x}", features); if (status != AVRC_SUCCESS || !(features & BTA_AV_FEAT_RCCT)) { log::error( - "Failed to do SDP: status=0x{:x} features=0x{:x} supports " - "controller: {}", - status, features, features & BTA_AV_FEAT_RCCT); + "Failed to do SDP: status=0x{:x} features=0x{:x} supports " + "controller: {}", + status, features, features & BTA_AV_FEAT_RCCT); instance_->connection_cb_.Run(std::shared_ptr()); } @@ -182,8 +179,7 @@ bool ConnectionHandler::DisconnectDevice(const RawAddress& bdaddr) { return false; } -void ConnectionHandler::SetBipClientStatus(const RawAddress& bdaddr, - bool connected) { +void ConnectionHandler::SetBipClientStatus(const RawAddress& bdaddr, bool connected) { for (auto it = device_map_.begin(); it != device_map_.end(); it++) { if (bdaddr == it->second->GetAddress()) { it->second->SetBipClientStatus(connected); @@ -192,8 +188,7 @@ void ConnectionHandler::SetBipClientStatus(const RawAddress& bdaddr, } } -std::vector> ConnectionHandler::GetListOfDevices() - const { +std::vector> ConnectionHandler::GetListOfDevices() const { std::vector> list; std::lock_guard lock(device_map_lock); for (const auto& device : device_map_) { @@ -202,29 +197,23 @@ std::vector> ConnectionHandler::GetListOfDevices() return list; } -bool ConnectionHandler::SdpLookup(const RawAddress& bdaddr, SdpCallback cb, - bool retry) { +bool ConnectionHandler::SdpLookup(const RawAddress& bdaddr, SdpCallback cb, bool retry) { log::info(""); tAVRC_SDP_DB_PARAMS db_params; // TODO (apanicke): This needs to be replaced with smarter memory management. - tSDP_DISCOVERY_DB* disc_db = - (tSDP_DISCOVERY_DB*)osi_malloc(BT_DEFAULT_BUFFER_SIZE); - uint16_t attr_list[] = {ATTR_ID_SERVICE_CLASS_ID_LIST, - ATTR_ID_BT_PROFILE_DESC_LIST, + tSDP_DISCOVERY_DB* disc_db = (tSDP_DISCOVERY_DB*)osi_malloc(BT_DEFAULT_BUFFER_SIZE); + uint16_t attr_list[] = {ATTR_ID_SERVICE_CLASS_ID_LIST, ATTR_ID_BT_PROFILE_DESC_LIST, ATTR_ID_SUPPORTED_FEATURES}; - db_params.db_len = - BT_DEFAULT_BUFFER_SIZE; // Some magic number found in the AVRCP code + db_params.db_len = BT_DEFAULT_BUFFER_SIZE; // Some magic number found in the AVRCP code db_params.num_attr = sizeof(attr_list) / sizeof(attr_list[0]); db_params.p_db = disc_db; db_params.p_attrs = attr_list; - return avrc_->FindService(UUID_SERVCLASS_AV_REMOTE_CONTROL, bdaddr, - &db_params, - base::Bind(&ConnectionHandler::SdpCb, - weak_ptr_factory_.GetWeakPtr(), bdaddr, - cb, disc_db, retry)) == AVRC_SUCCESS; + return avrc_->FindService(UUID_SERVCLASS_AV_REMOTE_CONTROL, bdaddr, &db_params, + base::Bind(&ConnectionHandler::SdpCb, weak_ptr_factory_.GetWeakPtr(), + bdaddr, cb, disc_db, retry)) == AVRC_SUCCESS; } bool ConnectionHandler::AvrcpConnect(bool initiator, const RawAddress& bdaddr) { @@ -232,21 +221,18 @@ bool ConnectionHandler::AvrcpConnect(bool initiator, const RawAddress& bdaddr) { tAVRC_CONN_CB open_cb; if (initiator) { - open_cb.ctrl_cback = base::Bind(&ConnectionHandler::InitiatorControlCb, - weak_ptr_factory_.GetWeakPtr()); + open_cb.ctrl_cback = + base::Bind(&ConnectionHandler::InitiatorControlCb, weak_ptr_factory_.GetWeakPtr()); } else { - open_cb.ctrl_cback = base::Bind(&ConnectionHandler::AcceptorControlCb, - weak_ptr_factory_.GetWeakPtr()); + open_cb.ctrl_cback = + base::Bind(&ConnectionHandler::AcceptorControlCb, weak_ptr_factory_.GetWeakPtr()); } - open_cb.msg_cback = - base::Bind(&ConnectionHandler::MessageCb, weak_ptr_factory_.GetWeakPtr()); + open_cb.msg_cback = base::Bind(&ConnectionHandler::MessageCb, weak_ptr_factory_.GetWeakPtr()); open_cb.company_id = AVRC_CO_GOOGLE; - open_cb.conn = initiator ? AVRC_CONN_INT - : AVRC_CONN_ACP; // 0 if initiator, 1 if acceptor + open_cb.conn = initiator ? AVRC_CONN_INT : AVRC_CONN_ACP; // 0 if initiator, 1 if acceptor // TODO (apanicke): We shouldn't need RCCT to do absolute volume. The current // AVRC_API requires it though. - open_cb.control = BTA_AV_FEAT_RCTG | BTA_AV_FEAT_RCCT | BTA_AV_FEAT_METADATA | - AVRC_CT_PASSIVE; + open_cb.control = BTA_AV_FEAT_RCTG | BTA_AV_FEAT_RCCT | BTA_AV_FEAT_METADATA | AVRC_CT_PASSIVE; uint8_t handle = 0; uint16_t status = avrc_->Open(&handle, &open_cb, bdaddr); @@ -254,8 +240,7 @@ bool ConnectionHandler::AvrcpConnect(bool initiator, const RawAddress& bdaddr) { return status == AVRC_SUCCESS; } -void ConnectionHandler::InitiatorControlCb(uint8_t handle, uint8_t event, - uint16_t result, +void ConnectionHandler::InitiatorControlCb(uint8_t handle, uint8_t event, uint16_t result, const RawAddress* peer_addr) { DCHECK(!connection_cb_.is_null()); @@ -269,8 +254,8 @@ void ConnectionHandler::InitiatorControlCb(uint8_t handle, uint8_t event, const auto& feature_iter = feature_map_.find(*peer_addr); if (feature_iter == feature_map_.end()) { log::error( - "Features do not exist even though SDP should have been " - "done first"); + "Features do not exist even though SDP should have been " + "done first"); return; } @@ -284,12 +269,12 @@ void ConnectionHandler::InitiatorControlCb(uint8_t handle, uint8_t event, // devices SDP is completed after the device connects AVRCP so that // information isn't very useful when trying to control our // capabilities. For now always use AVRCP 1.6. - auto&& callback = base::BindRepeating(&ConnectionHandler::SendMessage, - base::Unretained(this), handle); + auto&& callback = + base::BindRepeating(&ConnectionHandler::SendMessage, base::Unretained(this), handle); auto&& ctrl_mtu = avrc_->GetPeerMtu(handle) - AVCT_HDR_LEN; auto&& browse_mtu = avrc_->GetBrowseMtu(handle) - AVCT_HDR_LEN; - std::shared_ptr newDevice = std::make_shared( - *peer_addr, !supports_browsing, callback, ctrl_mtu, browse_mtu); + std::shared_ptr newDevice = std::make_shared(*peer_addr, !supports_browsing, + callback, ctrl_mtu, browse_mtu); device_map_[handle] = newDevice; // TODO (apanicke): Create the device with all of the interfaces it @@ -346,8 +331,7 @@ void ConnectionHandler::InitiatorControlCb(uint8_t handle, uint8_t event, } } -void ConnectionHandler::AcceptorControlCb(uint8_t handle, uint8_t event, - uint16_t result, +void ConnectionHandler::AcceptorControlCb(uint8_t handle, uint8_t event, uint16_t result, const RawAddress* peer_addr) { DCHECK(!connection_cb_.is_null()); @@ -360,8 +344,7 @@ void ConnectionHandler::AcceptorControlCb(uint8_t handle, uint8_t event, if (peer_addr == NULL) { return; } - if (btif_av_src_sink_coexist_enabled() && - btif_av_peer_is_connected_source(*peer_addr)) { + if (btif_av_src_sink_coexist_enabled() && btif_av_peer_is_connected_source(*peer_addr)) { log::warn("peer is src, close new avrcp cback"); if (device_map_.find(handle) != device_map_.end()) { std::lock_guard lock(device_map_lock); @@ -373,23 +356,20 @@ void ConnectionHandler::AcceptorControlCb(uint8_t handle, uint8_t event, AvrcpConnect(false, RawAddress::kAny); return; } - auto&& callback = - base::BindRepeating(&ConnectionHandler::SendMessage, - weak_ptr_factory_.GetWeakPtr(), handle); + auto&& callback = base::BindRepeating(&ConnectionHandler::SendMessage, + weak_ptr_factory_.GetWeakPtr(), handle); auto&& ctrl_mtu = avrc_->GetPeerMtu(handle) - AVCT_HDR_LEN; auto&& browse_mtu = avrc_->GetBrowseMtu(handle) - AVCT_HDR_LEN; - std::shared_ptr newDevice = std::make_shared( - *peer_addr, false, callback, ctrl_mtu, browse_mtu); + std::shared_ptr newDevice = + std::make_shared(*peer_addr, false, callback, ctrl_mtu, browse_mtu); device_map_[handle] = newDevice; connection_cb_.Run(newDevice); log::info("Performing SDP on connected device. address={}", *peer_addr); - auto sdp_lambda = [](ConnectionHandler* instance_, uint8_t handle, - uint16_t status, uint16_t version, - uint16_t features) { - if (instance_->device_map_.find(handle) == - instance_->device_map_.end()) { + auto sdp_lambda = [](ConnectionHandler* instance_, uint8_t handle, uint16_t status, + uint16_t version, uint16_t features) { + if (instance_->device_map_.find(handle) == instance_->device_map_.end()) { log::warn("No device found for handle: 0x{:x}", handle); return; } @@ -416,8 +396,7 @@ void ConnectionHandler::AcceptorControlCb(uint8_t handle, uint8_t event, // SDP search failed, this could be due to a collision between outgoing // and incoming connection. In any case, we need to reject the current // connection. - log::error("SDP search failed for handle: 0x{:x}, closing connection", - handle); + log::error("SDP search failed for handle: 0x{:x}, closing connection", handle); DisconnectDevice(*peer_addr); } // Open for the next incoming connection. The handle will not be the same @@ -469,11 +448,9 @@ void ConnectionHandler::AcceptorControlCb(uint8_t handle, uint8_t event, } } -void ConnectionHandler::MessageCb(uint8_t handle, uint8_t label, uint8_t opcode, - tAVRC_MSG* p_msg) { +void ConnectionHandler::MessageCb(uint8_t handle, uint8_t label, uint8_t opcode, tAVRC_MSG* p_msg) { if (device_map_.find(handle) == device_map_.end()) { - log::error("Message received for unconnected device: handle=0x{:x}", - handle); + log::error("Message received for unconnected device: handle=0x{:x}", handle); return; } @@ -495,9 +472,8 @@ void ConnectionHandler::MessageCb(uint8_t handle, uint8_t label, uint8_t opcode, device_map_[handle]->MessageReceived(label, Packet::Parse(pkt)); } -void ConnectionHandler::SdpCb(RawAddress bdaddr, SdpCallback cb, - tSDP_DISCOVERY_DB* disc_db, bool retry, - uint16_t status) { +void ConnectionHandler::SdpCb(RawAddress bdaddr, SdpCallback cb, tSDP_DISCOVERY_DB* disc_db, + bool retry, uint16_t status) { log::verbose("SDP lookup callback received"); if (status == SDP_CONN_FAILED && !retry) { @@ -517,19 +493,16 @@ void ConnectionHandler::SdpCb(RawAddress bdaddr, SdpCallback cb, uint16_t peer_avrcp_version = 0; // TODO (apanicke): Replace this in favor of our own supported features. - sdp_record = - sdp_->FindServiceInDb(disc_db, UUID_SERVCLASS_AV_REMOTE_CONTROL, nullptr); + sdp_record = sdp_->FindServiceInDb(disc_db, UUID_SERVCLASS_AV_REMOTE_CONTROL, nullptr); if (sdp_record != nullptr) { log::info("Device {} supports remote control", bdaddr); peer_features |= BTA_AV_FEAT_RCCT; - if ((sdp_->FindAttributeInRec(sdp_record, ATTR_ID_BT_PROFILE_DESC_LIST)) != - NULL) { + if ((sdp_->FindAttributeInRec(sdp_record, ATTR_ID_BT_PROFILE_DESC_LIST)) != NULL) { /* get profile version (if failure, version parameter is not updated) */ - sdp_->FindProfileVersionInRec( - sdp_record, UUID_SERVCLASS_AV_REMOTE_CONTROL, &peer_avrcp_version); - log::verbose("Device {} peer avrcp version=0x{:x}", bdaddr, - peer_avrcp_version); + sdp_->FindProfileVersionInRec(sdp_record, UUID_SERVCLASS_AV_REMOTE_CONTROL, + &peer_avrcp_version); + log::verbose("Device {} peer avrcp version=0x{:x}", bdaddr, peer_avrcp_version); if (peer_avrcp_version >= AVRC_REV_1_3) { // These are the standard features, another way to check this is to @@ -541,7 +514,7 @@ void ConnectionHandler::SdpCb(RawAddress bdaddr, SdpCallback cb, /* get supported categories */ log::verbose("Get Supported categories"); tSDP_DISC_ATTR* sdp_attribute = - sdp_->FindAttributeInRec(sdp_record, ATTR_ID_SUPPORTED_FEATURES); + sdp_->FindAttributeInRec(sdp_record, ATTR_ID_SUPPORTED_FEATURES); if (sdp_attribute != NULL && SDP_DISC_ATTR_TYPE(sdp_attribute->attr_len_type) == UINT_DESC_TYPE && SDP_DISC_ATTR_LEN(sdp_attribute->attr_len_type) >= 2) { @@ -566,24 +539,21 @@ void ConnectionHandler::SdpCb(RawAddress bdaddr, SdpCallback cb, } } - sdp_record = sdp_->FindServiceInDb(disc_db, UUID_SERVCLASS_AV_REM_CTRL_TARGET, - nullptr); + sdp_record = sdp_->FindServiceInDb(disc_db, UUID_SERVCLASS_AV_REM_CTRL_TARGET, nullptr); if (sdp_record != nullptr) { log::verbose("Device {} supports remote control target", bdaddr); uint16_t peer_avrcp_target_version = 0; sdp_->FindProfileVersionInRec(sdp_record, UUID_SERVCLASS_AV_REMOTE_CONTROL, &peer_avrcp_target_version); - log::verbose("Device {} peer avrcp target version=0x{:x}", bdaddr, - peer_avrcp_target_version); + log::verbose("Device {} peer avrcp target version=0x{:x}", bdaddr, peer_avrcp_target_version); - if ((sdp_->FindAttributeInRec(sdp_record, ATTR_ID_BT_PROFILE_DESC_LIST)) != - NULL) { + if ((sdp_->FindAttributeInRec(sdp_record, ATTR_ID_BT_PROFILE_DESC_LIST)) != NULL) { if (peer_avrcp_target_version >= AVRC_REV_1_4) { /* get supported categories */ log::verbose("Get Supported categories"); tSDP_DISC_ATTR* sdp_attribute = - sdp_->FindAttributeInRec(sdp_record, ATTR_ID_SUPPORTED_FEATURES); + sdp_->FindAttributeInRec(sdp_record, ATTR_ID_SUPPORTED_FEATURES); if (sdp_attribute != NULL && SDP_DISC_ATTR_TYPE(sdp_attribute->attr_len_type) == UINT_DESC_TYPE && SDP_DISC_ATTR_LEN(sdp_attribute->attr_len_type) >= 2) { @@ -605,16 +575,14 @@ void ConnectionHandler::SdpCb(RawAddress bdaddr, SdpCallback cb, cb.Run(status, peer_avrcp_version, peer_features); } -void ConnectionHandler::SendMessage( - uint8_t handle, uint8_t label, bool browse, - std::unique_ptr<::bluetooth::PacketBuilder> message) { +void ConnectionHandler::SendMessage(uint8_t handle, uint8_t label, bool browse, + std::unique_ptr<::bluetooth::PacketBuilder> message) { std::shared_ptr<::bluetooth::Packet> packet = VectorPacket::Make(); message->Serialize(packet); uint8_t ctype = AVRC_RSP_ACCEPT; if (!browse) { - ctype = - (uint8_t)(::bluetooth::Packet::Specialize(packet)->GetCType()); + ctype = (uint8_t)(::bluetooth::Packet::Specialize(packet)->GetCType()); } log::info("SendMessage to handle=0x{:x}", handle); @@ -628,8 +596,7 @@ void ConnectionHandler::SendMessage( // the packet so none of these layer specific fields will be used. pkt->event = 0xFFFF; /* Handle for AVRCP fragment */ - uint16_t op_code = - (uint16_t)(::bluetooth::Packet::Specialize(packet)->GetOpcode()); + uint16_t op_code = (uint16_t)(::bluetooth::Packet::Specialize(packet)->GetOpcode()); if (!browse && (op_code == (uint16_t)(Opcode::VENDOR))) { pkt->event = op_code; } @@ -673,17 +640,15 @@ bool ConnectionHandler::SdpLookupAudioRole(uint16_t handle) { auto device = device_map_[handle]; log::info( - "Performing SDP for AUDIO_SINK on connected device: address={}, " - "handle={}", - ADDRESS_TO_LOGGABLE_STR(device->GetAddress()), handle); + "Performing SDP for AUDIO_SINK on connected device: address={}, " + "handle={}", + ADDRESS_TO_LOGGABLE_STR(device->GetAddress()), handle); - return device->find_sink_service( - base::Bind(&ConnectionHandler::SdpLookupAudioRoleCb, - weak_ptr_factory_.GetWeakPtr(), handle)); + return device->find_sink_service(base::Bind(&ConnectionHandler::SdpLookupAudioRoleCb, + weak_ptr_factory_.GetWeakPtr(), handle)); } -void ConnectionHandler::SdpLookupAudioRoleCb(uint16_t handle, bool found, - tA2DP_Service* p_service, +void ConnectionHandler::SdpLookupAudioRoleCb(uint16_t handle, bool found, tA2DP_Service* p_service, const RawAddress& peer_address) { if (device_map_.find(handle) == device_map_.end()) { log::warn("No device found for handle: {}", loghex(handle)); @@ -692,8 +657,7 @@ void ConnectionHandler::SdpLookupAudioRoleCb(uint16_t handle, bool found, auto device = device_map_[handle]; log::debug("SDP callback for address={}, handle={}, AUDIO_SINK {}", - ADDRESS_TO_LOGGABLE_STR(device->GetAddress()), handle, - found ? "found" : "not found"); + ADDRESS_TO_LOGGABLE_STR(device->GetAddress()), handle, found ? "found" : "not found"); if (found) { device->connect_a2dp_sink_delayed(handle); diff --git a/system/profile/avrcp/connection_handler.h b/system/profile/avrcp/connection_handler.h index 46346aee922..b4cfd612b25 100644 --- a/system/profile/avrcp/connection_handler.h +++ b/system/profile/avrcp/connection_handler.h @@ -46,14 +46,13 @@ namespace avrcp { * and multiplexing/delivering messages to devices. */ class ConnectionHandler { - public: +public: /** * This callback is used to return a new device after a connection attempt. * A reference to the new Avrcp device is located in the shared_ptr. * If there was an issue during connection the pointer value will be null. */ - using ConnectionCallback = - base::RepeatingCallback)>; + using ConnectionCallback = base::RepeatingCallback)>; /** * Initializes the singleton instance and sets up SDP. Also Opens the @@ -66,9 +65,8 @@ class ConnectionHandler { * * TODO: Add message loop to determine which thread events are posted to */ - static bool Initialize(const ConnectionCallback& callback, - AvrcpInterface* avrcp, SdpInterface* sdp, - VolumeInterface* vol); + static bool Initialize(const ConnectionCallback& callback, AvrcpInterface* avrcp, + SdpInterface* sdp, VolumeInterface* vol); /** * Clears the singleton and tears down SDP @@ -132,7 +130,7 @@ class ConnectionHandler { virtual void RegisterVolChanged(const RawAddress& bdaddr); - private: +private: AvrcpInterface* avrc_; SdpInterface* sdp_; VolumeInterface* vol_; @@ -146,11 +144,10 @@ class ConnectionHandler { static ConnectionHandler* instance_; - using SdpCallback = base::Callback; + using SdpCallback = base::Callback; virtual bool SdpLookup(const RawAddress& bdaddr, SdpCallback cb, bool retry); - void SdpCb(RawAddress bdaddr, SdpCallback cb, - tSDP_DISCOVERY_DB* disc_db, bool retry, uint16_t status); + void SdpCb(RawAddress bdaddr, SdpCallback cb, tSDP_DISCOVERY_DB* disc_db, bool retry, + uint16_t status); virtual bool AvrcpConnect(bool initiator, const RawAddress& bdaddr); @@ -159,10 +156,9 @@ class ConnectionHandler { const RawAddress* peer_addr); void AcceptorControlCb(uint8_t handle, uint8_t event, uint16_t result, const RawAddress* peer_addr); - void MessageCb(uint8_t handle, uint8_t label, uint8_t opcode, - tAVRC_MSG* p_msg); + void MessageCb(uint8_t handle, uint8_t label, uint8_t opcode, tAVRC_MSG* p_msg); - ConnectionHandler() : weak_ptr_factory_(this){}; + ConnectionHandler() : weak_ptr_factory_(this) {} ConnectionHandler(const ConnectionHandler&) = delete; ConnectionHandler& operator=(const ConnectionHandler&) = delete; @@ -175,8 +171,7 @@ class ConnectionHandler { // Check peer role: audio src or sink. If any role supported send // delayed a2dp connect request bool SdpLookupAudioRole(uint16_t handle); - void SdpLookupAudioRoleCb(uint16_t handle, bool found, - tA2DP_Service* p_service, + void SdpLookupAudioRoleCb(uint16_t handle, bool found, tA2DP_Service* p_service, const RawAddress& peer_address); base::WeakPtrFactory weak_ptr_factory_; diff --git a/system/profile/avrcp/device.cc b/system/profile/avrcp/device.cc index cdd350b9bcb..fc0f3cd9216 100644 --- a/system/profile/avrcp/device.cc +++ b/system/profile/avrcp/device.cc @@ -40,8 +40,7 @@ extern bool btif_av_both_enable(void); extern bool btif_av_src_sink_coexist_enabled(void); template <> -struct fmt::formatter - : enum_formatter {}; +struct fmt::formatter : enum_formatter {}; namespace bluetooth { namespace avrcp { @@ -50,10 +49,9 @@ namespace avrcp { #define VOL_REGISTRATION_FAILED -2 Device::Device(const RawAddress& bdaddr, bool avrcp13_compatibility, - base::RepeatingCallback< - void(uint8_t label, bool browse, - std::unique_ptr<::bluetooth::PacketBuilder> message)> - send_msg_cb, + base::RepeatingCallback message)> + send_msg_cb, uint16_t ctrl_mtu, uint16_t browse_mtu) : weak_ptr_factory_(this), address_(bdaddr), @@ -63,14 +61,11 @@ Device::Device(const RawAddress& bdaddr, bool avrcp13_compatibility, browse_mtu_(browse_mtu), has_bip_client_(false) {} -void Device::RegisterInterfaces( - MediaInterface* media_interface, A2dpInterface* a2dp_interface, - VolumeInterface* volume_interface, - PlayerSettingsInterface* player_settings_interface) { - log::assert_that(media_interface != nullptr, - "assert failed: media_interface != nullptr"); - log::assert_that(a2dp_interface != nullptr, - "assert failed: a2dp_interface != nullptr"); +void Device::RegisterInterfaces(MediaInterface* media_interface, A2dpInterface* a2dp_interface, + VolumeInterface* volume_interface, + PlayerSettingsInterface* player_settings_interface) { + log::assert_that(media_interface != nullptr, "assert failed: media_interface != nullptr"); + log::assert_that(a2dp_interface != nullptr, "assert failed: a2dp_interface != nullptr"); a2dp_interface_ = a2dp_interface; media_interface_ = media_interface; volume_interface_ = volume_interface; @@ -100,24 +95,17 @@ void filter_cover_art(SongInfo& s) { } } -bool Device::IsActive() const { - return address_ == a2dp_interface_->active_peer(); -} +bool Device::IsActive() const { return address_ == a2dp_interface_->active_peer(); } -bool Device::IsInSilenceMode() const { - return a2dp_interface_->is_peer_in_silence_mode(address_); -} +bool Device::IsInSilenceMode() const { return a2dp_interface_->is_peer_in_silence_mode(address_); } -void Device::VendorPacketHandler(uint8_t label, - std::shared_ptr pkt) { - log::assert_that(media_interface_ != nullptr, - "assert failed: media_interface_ != nullptr"); +void Device::VendorPacketHandler(uint8_t label, std::shared_ptr pkt) { + log::assert_that(media_interface_ != nullptr, "assert failed: media_interface_ != nullptr"); log::verbose("pdu={}", pkt->GetCommandPdu()); if (!pkt->IsValid()) { log::warn("{}: Request packet is not valid", address_); - auto response = RejectBuilder::MakeBuilder(static_cast(0), - Status::INVALID_COMMAND); + auto response = RejectBuilder::MakeBuilder(static_cast(0), Status::INVALID_COMMAND); send_message(label, false, std::move(response)); return; } @@ -131,16 +119,15 @@ void Device::VendorPacketHandler(uint8_t label, switch (pkt->GetCommandPdu()) { // VOLUME_CHANGED is the only notification we register for while target. case CommandPdu::REGISTER_NOTIFICATION: { - auto register_notification = - Packet::Specialize(pkt); + auto register_notification = Packet::Specialize(pkt); if ((!btif_av_src_sink_coexist_enabled() || (btif_av_src_sink_coexist_enabled() && register_notification->GetEvent() == Event::VOLUME_CHANGED)) && !register_notification->IsValid()) { log::warn("{}: Request packet is not valid", address_); - auto response = RejectBuilder::MakeBuilder(pkt->GetCommandPdu(), - Status::INVALID_PARAMETER); + auto response = + RejectBuilder::MakeBuilder(pkt->GetCommandPdu(), Status::INVALID_PARAMETER); send_message(label, false, std::move(response)); active_labels_.erase(label); volume_interface_ = nullptr; @@ -149,8 +136,8 @@ void Device::VendorPacketHandler(uint8_t label, } if (register_notification->GetEvent() != Event::VOLUME_CHANGED) { - log::warn("{}: Unhandled register notification received: {}", - address_, register_notification->GetEvent()); + log::warn("{}: Unhandled register notification received: {}", address_, + register_notification->GetEvent()); return; } HandleVolumeChanged(label, register_notification); @@ -162,8 +149,7 @@ void Device::VendorPacketHandler(uint8_t label, // about the response to this message. break; default: - log::warn("{}: Unhandled Response: pdu={}", address_, - pkt->GetCommandPdu()); + log::warn("{}: Unhandled Response: pdu={}", address_, pkt->GetCommandPdu()); break; } return; @@ -171,35 +157,31 @@ void Device::VendorPacketHandler(uint8_t label, switch (pkt->GetCommandPdu()) { case CommandPdu::GET_CAPABILITIES: { - HandleGetCapabilities(label, - Packet::Specialize(pkt)); + HandleGetCapabilities(label, Packet::Specialize(pkt)); } break; case CommandPdu::REGISTER_NOTIFICATION: { - HandleNotification(label, - Packet::Specialize(pkt)); + HandleNotification(label, Packet::Specialize(pkt)); } break; case CommandPdu::GET_ELEMENT_ATTRIBUTES: { auto get_element_attributes_request_pkt = - Packet::Specialize(pkt); + Packet::Specialize(pkt); if (!get_element_attributes_request_pkt->IsValid()) { log::warn("{}: Request packet is not valid", address_); - auto response = RejectBuilder::MakeBuilder(pkt->GetCommandPdu(), - Status::INVALID_PARAMETER); + auto response = RejectBuilder::MakeBuilder(pkt->GetCommandPdu(), Status::INVALID_PARAMETER); send_message(label, false, std::move(response)); return; } - media_interface_->GetSongInfo(base::Bind( - &Device::GetElementAttributesResponse, weak_ptr_factory_.GetWeakPtr(), - label, get_element_attributes_request_pkt)); + media_interface_->GetSongInfo(base::Bind(&Device::GetElementAttributesResponse, + weak_ptr_factory_.GetWeakPtr(), label, + get_element_attributes_request_pkt)); } break; case CommandPdu::GET_PLAY_STATUS: { - media_interface_->GetPlayStatus(base::Bind(&Device::GetPlayStatusResponse, - weak_ptr_factory_.GetWeakPtr(), - label)); + media_interface_->GetPlayStatus( + base::Bind(&Device::GetPlayStatusResponse, weak_ptr_factory_.GetWeakPtr(), label)); } break; case CommandPdu::PLAY_ITEM: { @@ -211,139 +193,121 @@ void Device::VendorPacketHandler(uint8_t label, // this currently since the current implementation only has one // player and the player will never change, but we need it for a // more complete implementation. - auto set_addressed_player_request = - Packet::Specialize(pkt); + auto set_addressed_player_request = Packet::Specialize(pkt); if (!set_addressed_player_request->IsValid()) { log::warn("{}: Request packet is not valid", address_); - auto response = RejectBuilder::MakeBuilder(pkt->GetCommandPdu(), - Status::INVALID_PARAMETER); + auto response = RejectBuilder::MakeBuilder(pkt->GetCommandPdu(), Status::INVALID_PARAMETER); send_message(label, false, std::move(response)); return; } - media_interface_->GetMediaPlayerList(base::Bind( - &Device::HandleSetAddressedPlayer, weak_ptr_factory_.GetWeakPtr(), - label, set_addressed_player_request)); + media_interface_->GetMediaPlayerList(base::Bind(&Device::HandleSetAddressedPlayer, + weak_ptr_factory_.GetWeakPtr(), label, + set_addressed_player_request)); } break; case CommandPdu::LIST_PLAYER_APPLICATION_SETTING_ATTRIBUTES: { if (player_settings_interface_ == nullptr) { log::error("Player Settings Interface not initialized."); - auto response = RejectBuilder::MakeBuilder(pkt->GetCommandPdu(), - Status::INVALID_COMMAND); + auto response = RejectBuilder::MakeBuilder(pkt->GetCommandPdu(), Status::INVALID_COMMAND); send_message(label, false, std::move(response)); return; } player_settings_interface_->ListPlayerSettings( - base::Bind(&Device::ListPlayerApplicationSettingAttributesResponse, - weak_ptr_factory_.GetWeakPtr(), label)); + base::Bind(&Device::ListPlayerApplicationSettingAttributesResponse, + weak_ptr_factory_.GetWeakPtr(), label)); } break; case CommandPdu::LIST_PLAYER_APPLICATION_SETTING_VALUES: { if (player_settings_interface_ == nullptr) { log::error("Player Settings Interface not initialized."); - auto response = RejectBuilder::MakeBuilder(pkt->GetCommandPdu(), - Status::INVALID_COMMAND); + auto response = RejectBuilder::MakeBuilder(pkt->GetCommandPdu(), Status::INVALID_COMMAND); send_message(label, false, std::move(response)); return; } auto list_player_setting_values_request = - Packet::Specialize(pkt); + Packet::Specialize(pkt); if (!list_player_setting_values_request->IsValid()) { log::warn("{}: Request packet is not valid", address_); - auto response = RejectBuilder::MakeBuilder(pkt->GetCommandPdu(), - Status::INVALID_PARAMETER); + auto response = RejectBuilder::MakeBuilder(pkt->GetCommandPdu(), Status::INVALID_PARAMETER); send_message(label, false, std::move(response)); return; } - PlayerAttribute attribute = - list_player_setting_values_request->GetRequestedAttribute(); - if (attribute < PlayerAttribute::EQUALIZER || - attribute > PlayerAttribute::SCAN) { + PlayerAttribute attribute = list_player_setting_values_request->GetRequestedAttribute(); + if (attribute < PlayerAttribute::EQUALIZER || attribute > PlayerAttribute::SCAN) { log::warn("{}: Player Setting Attribute is not valid", address_); - auto response = RejectBuilder::MakeBuilder(pkt->GetCommandPdu(), - Status::INVALID_PARAMETER); + auto response = RejectBuilder::MakeBuilder(pkt->GetCommandPdu(), Status::INVALID_PARAMETER); send_message(label, false, std::move(response)); return; } player_settings_interface_->ListPlayerSettingValues( - attribute, - base::Bind(&Device::ListPlayerApplicationSettingValuesResponse, - weak_ptr_factory_.GetWeakPtr(), label)); + attribute, base::Bind(&Device::ListPlayerApplicationSettingValuesResponse, + weak_ptr_factory_.GetWeakPtr(), label)); } break; case CommandPdu::GET_CURRENT_PLAYER_APPLICATION_SETTING_VALUE: { if (player_settings_interface_ == nullptr) { log::error("Player Settings Interface not initialized."); - auto response = RejectBuilder::MakeBuilder(pkt->GetCommandPdu(), - Status::INVALID_COMMAND); + auto response = RejectBuilder::MakeBuilder(pkt->GetCommandPdu(), Status::INVALID_COMMAND); send_message(label, false, std::move(response)); return; } auto get_current_player_setting_value_request = - Packet::Specialize( - pkt); + Packet::Specialize(pkt); if (!get_current_player_setting_value_request->IsValid()) { log::warn("{}: Request packet is not valid", address_); - auto response = RejectBuilder::MakeBuilder(pkt->GetCommandPdu(), - Status::INVALID_PARAMETER); + auto response = RejectBuilder::MakeBuilder(pkt->GetCommandPdu(), Status::INVALID_PARAMETER); send_message(label, false, std::move(response)); return; } std::vector attributes = - get_current_player_setting_value_request->GetRequestedAttributes(); + get_current_player_setting_value_request->GetRequestedAttributes(); for (auto attribute : attributes) { - if (attribute < PlayerAttribute::EQUALIZER || - attribute > PlayerAttribute::SCAN) { + if (attribute < PlayerAttribute::EQUALIZER || attribute > PlayerAttribute::SCAN) { log::warn("{}: Player Setting Attribute is not valid", address_); - auto response = RejectBuilder::MakeBuilder(pkt->GetCommandPdu(), - Status::INVALID_PARAMETER); + auto response = + RejectBuilder::MakeBuilder(pkt->GetCommandPdu(), Status::INVALID_PARAMETER); send_message(label, false, std::move(response)); return; } } player_settings_interface_->GetCurrentPlayerSettingValue( - attributes, - base::Bind(&Device::GetPlayerApplicationSettingValueResponse, - weak_ptr_factory_.GetWeakPtr(), label)); + attributes, base::Bind(&Device::GetPlayerApplicationSettingValueResponse, + weak_ptr_factory_.GetWeakPtr(), label)); } break; case CommandPdu::SET_PLAYER_APPLICATION_SETTING_VALUE: { if (player_settings_interface_ == nullptr) { log::error("Player Settings Interface not initialized."); - auto response = RejectBuilder::MakeBuilder(pkt->GetCommandPdu(), - Status::INVALID_COMMAND); + auto response = RejectBuilder::MakeBuilder(pkt->GetCommandPdu(), Status::INVALID_COMMAND); send_message(label, false, std::move(response)); return; } auto set_player_setting_value_request = - Packet::Specialize(pkt); + Packet::Specialize(pkt); if (!set_player_setting_value_request->IsValid()) { log::warn("{} : Request packet is not valid", address_); - auto response = RejectBuilder::MakeBuilder(pkt->GetCommandPdu(), - Status::INVALID_PARAMETER); + auto response = RejectBuilder::MakeBuilder(pkt->GetCommandPdu(), Status::INVALID_PARAMETER); send_message(label, false, std::move(response)); return; } std::vector attributes = - set_player_setting_value_request->GetRequestedAttributes(); - std::vector values = - set_player_setting_value_request->GetRequestedValues(); + set_player_setting_value_request->GetRequestedAttributes(); + std::vector values = set_player_setting_value_request->GetRequestedValues(); bool invalid_request = false; for (size_t i = 0; i < attributes.size(); i++) { - if (attributes[i] < PlayerAttribute::EQUALIZER || - attributes[i] > PlayerAttribute::SCAN) { + if (attributes[i] < PlayerAttribute::EQUALIZER || attributes[i] > PlayerAttribute::SCAN) { log::warn("{}: Player Setting Attribute is not valid", address_); invalid_request = true; break; @@ -351,16 +315,14 @@ void Device::VendorPacketHandler(uint8_t label, if (attributes[i] == PlayerAttribute::REPEAT) { PlayerRepeatValue value = static_cast(values[i]); - if (value < PlayerRepeatValue::OFF || - value > PlayerRepeatValue::GROUP) { + if (value < PlayerRepeatValue::OFF || value > PlayerRepeatValue::GROUP) { log::warn("{}: Player Repeat Value is not valid", address_); invalid_request = true; break; } } else if (attributes[i] == PlayerAttribute::SHUFFLE) { PlayerShuffleValue value = static_cast(values[i]); - if (value < PlayerShuffleValue::OFF || - value > PlayerShuffleValue::GROUP) { + if (value < PlayerShuffleValue::OFF || value > PlayerShuffleValue::GROUP) { log::warn("{}: Player Shuffle Value is not valid", address_); invalid_request = true; break; @@ -369,34 +331,31 @@ void Device::VendorPacketHandler(uint8_t label, } if (invalid_request) { - auto response = RejectBuilder::MakeBuilder(pkt->GetCommandPdu(), - Status::INVALID_PARAMETER); + auto response = RejectBuilder::MakeBuilder(pkt->GetCommandPdu(), Status::INVALID_PARAMETER); send_message(label, false, std::move(response)); return; } player_settings_interface_->SetPlayerSettings( - attributes, values, - base::Bind(&Device::SetPlayerApplicationSettingValueResponse, - weak_ptr_factory_.GetWeakPtr(), label, - pkt->GetCommandPdu())); + attributes, values, + base::Bind(&Device::SetPlayerApplicationSettingValueResponse, + weak_ptr_factory_.GetWeakPtr(), label, pkt->GetCommandPdu())); } break; default: { log::error("{}: Unhandled Vendor Packet: {}", address_, pkt->ToString()); - auto response = RejectBuilder::MakeBuilder( - (CommandPdu)pkt->GetCommandPdu(), Status::INVALID_COMMAND); + auto response = + RejectBuilder::MakeBuilder((CommandPdu)pkt->GetCommandPdu(), Status::INVALID_COMMAND); send_message(label, false, std::move(response)); } break; } } -void Device::HandleGetCapabilities( - uint8_t label, const std::shared_ptr& pkt) { +void Device::HandleGetCapabilities(uint8_t label, + const std::shared_ptr& pkt) { if (!pkt->IsValid()) { log::warn("{}: Request packet is not valid", address_); - auto response = RejectBuilder::MakeBuilder(pkt->GetCommandPdu(), - Status::INVALID_PARAMETER); + auto response = RejectBuilder::MakeBuilder(pkt->GetCommandPdu(), Status::INVALID_PARAMETER); send_message(label, false, std::move(response)); return; } @@ -405,15 +364,13 @@ void Device::HandleGetCapabilities( switch (pkt->GetCapabilityRequested()) { case Capability::COMPANY_ID: { - auto response = - GetCapabilitiesResponseBuilder::MakeCompanyIdBuilder(0x001958); + auto response = GetCapabilitiesResponseBuilder::MakeCompanyIdBuilder(0x001958); response->AddCompanyId(0x002345); send_message_cb_.Run(label, false, std::move(response)); } break; case Capability::EVENTS_SUPPORTED: { - auto response = - GetCapabilitiesResponseBuilder::MakeEventsSupportedBuilder( + auto response = GetCapabilitiesResponseBuilder::MakeEventsSupportedBuilder( Event::PLAYBACK_STATUS_CHANGED); response->AddEvent(Event::TRACK_CHANGED); response->AddEvent(Event::PLAYBACK_POS_CHANGED); @@ -432,21 +389,19 @@ void Device::HandleGetCapabilities( } break; default: { - log::warn("{}: Unhandled Capability: {}", address_, - pkt->GetCapabilityRequested()); - auto response = RejectBuilder::MakeBuilder(CommandPdu::GET_CAPABILITIES, - Status::INVALID_PARAMETER); + log::warn("{}: Unhandled Capability: {}", address_, pkt->GetCapabilityRequested()); + auto response = + RejectBuilder::MakeBuilder(CommandPdu::GET_CAPABILITIES, Status::INVALID_PARAMETER); send_message(label, false, std::move(response)); } break; } } -void Device::HandleNotification( - uint8_t label, const std::shared_ptr& pkt) { +void Device::HandleNotification(uint8_t label, + const std::shared_ptr& pkt) { if (!pkt->IsValid()) { log::warn("{}: Request packet is not valid", address_); - auto response = RejectBuilder::MakeBuilder(pkt->GetCommandPdu(), - Status::INVALID_PARAMETER); + auto response = RejectBuilder::MakeBuilder(pkt->GetCommandPdu(), Status::INVALID_PARAMETER); send_message(label, false, std::move(response)); return; } @@ -455,45 +410,39 @@ void Device::HandleNotification( switch (pkt->GetEventRegistered()) { case Event::TRACK_CHANGED: { - media_interface_->GetNowPlayingList( - base::Bind(&Device::TrackChangedNotificationResponse, - weak_ptr_factory_.GetWeakPtr(), label, true)); + media_interface_->GetNowPlayingList(base::Bind(&Device::TrackChangedNotificationResponse, + weak_ptr_factory_.GetWeakPtr(), label, true)); } break; case Event::PLAYBACK_STATUS_CHANGED: { - media_interface_->GetPlayStatus( - base::Bind(&Device::PlaybackStatusNotificationResponse, - weak_ptr_factory_.GetWeakPtr(), label, true)); + media_interface_->GetPlayStatus(base::Bind(&Device::PlaybackStatusNotificationResponse, + weak_ptr_factory_.GetWeakPtr(), label, true)); } break; case Event::PLAYBACK_POS_CHANGED: { play_pos_interval_ = pkt->GetInterval(); - media_interface_->GetPlayStatus( - base::Bind(&Device::PlaybackPosNotificationResponse, - weak_ptr_factory_.GetWeakPtr(), label, true)); + media_interface_->GetPlayStatus(base::Bind(&Device::PlaybackPosNotificationResponse, + weak_ptr_factory_.GetWeakPtr(), label, true)); } break; case Event::PLAYER_APPLICATION_SETTING_CHANGED: { if (player_settings_interface_ == nullptr) { log::error("Player Settings Interface not initialized."); - auto response = RejectBuilder::MakeBuilder(pkt->GetCommandPdu(), - Status::INVALID_COMMAND); + auto response = RejectBuilder::MakeBuilder(pkt->GetCommandPdu(), Status::INVALID_COMMAND); send_message(label, false, std::move(response)); return; } - std::vector attributes = { - PlayerAttribute::EQUALIZER, PlayerAttribute::REPEAT, - PlayerAttribute::SHUFFLE, PlayerAttribute::SCAN}; + std::vector attributes = {PlayerAttribute::EQUALIZER, + PlayerAttribute::REPEAT, PlayerAttribute::SHUFFLE, + PlayerAttribute::SCAN}; player_settings_interface_->GetCurrentPlayerSettingValue( - attributes, - base::Bind(&Device::PlayerSettingChangedNotificationResponse, - weak_ptr_factory_.GetWeakPtr(), label, true)); + attributes, base::Bind(&Device::PlayerSettingChangedNotificationResponse, + weak_ptr_factory_.GetWeakPtr(), label, true)); } break; case Event::NOW_PLAYING_CONTENT_CHANGED: { - media_interface_->GetNowPlayingList( - base::Bind(&Device::HandleNowPlayingNotificationResponse, - weak_ptr_factory_.GetWeakPtr(), label, true)); + media_interface_->GetNowPlayingList(base::Bind(&Device::HandleNowPlayingNotificationResponse, + weak_ptr_factory_.GetWeakPtr(), label, true)); } break; case Event::AVAILABLE_PLAYERS_CHANGED: { @@ -502,16 +451,13 @@ void Device::HandleNotification( // Respond immediately since this notification doesn't require any info avail_players_changed_ = Notification(true, label); - auto response = - RegisterNotificationResponseBuilder::MakeAvailablePlayersBuilder( - true); + auto response = RegisterNotificationResponseBuilder::MakeAvailablePlayersBuilder(true); send_message(label, false, std::move(response)); } break; case Event::ADDRESSED_PLAYER_CHANGED: { - media_interface_->GetMediaPlayerList( - base::Bind(&Device::AddressedPlayerNotificationResponse, - weak_ptr_factory_.GetWeakPtr(), label, true)); + media_interface_->GetMediaPlayerList(base::Bind(&Device::AddressedPlayerNotificationResponse, + weak_ptr_factory_.GetWeakPtr(), label, true)); } break; case Event::UIDS_CHANGED: { @@ -520,16 +466,14 @@ void Device::HandleNotification( // Respond immediately since this notification doesn't require any info uids_changed_ = Notification(true, label); - auto response = - RegisterNotificationResponseBuilder::MakeUidsChangedBuilder(true, 0); + auto response = RegisterNotificationResponseBuilder::MakeUidsChangedBuilder(true, 0); send_message(label, false, std::move(response)); } break; default: { - log::error("{}: Unknown event registered. Event ID={}", address_, - pkt->GetEventRegistered()); - auto response = RejectBuilder::MakeBuilder( - (CommandPdu)pkt->GetCommandPdu(), Status::INVALID_PARAMETER); + log::error("{}: Unknown event registered. Event ID={}", address_, pkt->GetEventRegistered()); + auto response = RejectBuilder::MakeBuilder((CommandPdu)pkt->GetCommandPdu(), + Status::INVALID_PARAMETER); send_message(label, false, std::move(response)); } break; } @@ -537,10 +481,11 @@ void Device::HandleNotification( void Device::RegisterVolumeChanged() { log::verbose(""); - if (volume_interface_ == nullptr) return; + if (volume_interface_ == nullptr) { + return; + } - auto request = - RegisterNotificationRequestBuilder::MakeBuilder(Event::VOLUME_CHANGED, 0); + auto request = RegisterNotificationRequestBuilder::MakeBuilder(Event::VOLUME_CHANGED, 0); // Find an open transaction label to prevent conflicts with other commands // that are in flight. We can not use the reserved label while the @@ -555,18 +500,19 @@ void Device::RegisterVolumeChanged() { } if (label == MAX_TRANSACTION_LABEL) { - log::fatal("{}: Abandon all hope, something went catastrophically wrong", - address_); + log::fatal("{}: Abandon all hope, something went catastrophically wrong", address_); } send_message_cb_.Run(label, false, std::move(request)); } -void Device::HandleVolumeChanged( - uint8_t label, const std::shared_ptr& pkt) { +void Device::HandleVolumeChanged(uint8_t label, + const std::shared_ptr& pkt) { log::verbose("interim={}", pkt->IsInterim()); - if (volume_interface_ == nullptr) return; + if (volume_interface_ == nullptr) { + return; + } if (pkt->GetCType() == CType::REJECTED) { // Disable Absolute Volume @@ -588,8 +534,7 @@ void Device::HandleVolumeChanged( volume_ = pkt->GetVolume(); volume_ &= ~0x80; // remove RFA bit volume_interface_->DeviceConnected( - GetAddress(), - base::Bind(&Device::SetVolume, weak_ptr_factory_.GetWeakPtr())); + GetAddress(), base::Bind(&Device::SetVolume, weak_ptr_factory_.GetWeakPtr())); // Ignore the returned volume in favor of the volume returned // by the volume interface. @@ -611,8 +556,7 @@ void Device::SetVolume(int8_t volume) { // TODO (apanicke): Implement logic for Multi-AVRCP log::verbose("volume={}", (int)volume); if (volume == volume_) { - log::warn("{}: Ignoring volume change same as current volume level", - address_); + log::warn("{}: Ignoring volume change same as current volume level", address_); return; } auto request = SetAbsoluteVolumeRequestBuilder::MakeBuilder(volume); @@ -630,8 +574,7 @@ void Device::SetVolume(int8_t volume) { send_message_cb_.Run(label, false, std::move(request)); } -void Device::TrackChangedNotificationResponse(uint8_t label, bool interim, - std::string curr_song_id, +void Device::TrackChangedNotificationResponse(uint8_t label, bool interim, std::string curr_song_id, std::vector song_list) { log::verbose(""); @@ -657,9 +600,7 @@ void Device::TrackChangedNotificationResponse(uint8_t label, bool interim, if (stack_config_get_interface()->get_pts_avrcp_test()) { log::warn("{}: pts test mode", address_); uint64_t uid = curr_song_id.empty() ? 0xffffffffffffffff : 0; - auto response = - RegisterNotificationResponseBuilder::MakeTrackChangedBuilder(interim, - uid); + auto response = RegisterNotificationResponseBuilder::MakeTrackChangedBuilder(interim, uid); send_message_cb_.Run(label, false, std::move(response)); return; } @@ -681,15 +622,15 @@ void Device::TrackChangedNotificationResponse(uint8_t label, bool interim, log::error("{}: No match for media ID found", address_); } - auto response = RegisterNotificationResponseBuilder::MakeTrackChangedBuilder( - interim, uid); + auto response = RegisterNotificationResponseBuilder::MakeTrackChangedBuilder(interim, uid); send_message_cb_.Run(label, false, std::move(response)); } -void Device::PlaybackStatusNotificationResponse(uint8_t label, bool interim, - PlayStatus status) { +void Device::PlaybackStatusNotificationResponse(uint8_t label, bool interim, PlayStatus status) { log::verbose(""); - if (status.state == PlayState::PAUSED) play_pos_update_cb_.Cancel(); + if (status.state == PlayState::PAUSED) { + play_pos_update_cb_.Cancel(); + } if (interim) { play_status_changed_ = Notification(true, label); @@ -699,17 +640,17 @@ void Device::PlaybackStatusNotificationResponse(uint8_t label, bool interim, } auto state_to_send = status.state; - if (!IsActive()) state_to_send = PlayState::PAUSED; + if (!IsActive()) { + state_to_send = PlayState::PAUSED; + } if (!interim && state_to_send == last_play_status_.state) { - log::verbose("Not sending notification due to no state update {}", - address_); + log::verbose("Not sending notification due to no state update {}", address_); return; } last_play_status_.state = state_to_send; - auto response = - RegisterNotificationResponseBuilder::MakePlaybackStatusBuilder( + auto response = RegisterNotificationResponseBuilder::MakePlaybackStatusBuilder( interim, IsActive() ? status.state : PlayState::PAUSED); send_message_cb_.Run(label, false, std::move(response)); @@ -719,8 +660,7 @@ void Device::PlaybackStatusNotificationResponse(uint8_t label, bool interim, } } -void Device::PlaybackPosNotificationResponse(uint8_t label, bool interim, - PlayStatus status) { +void Device::PlaybackPosNotificationResponse(uint8_t label, bool interim, PlayStatus status) { log::verbose(""); if (interim) { @@ -735,9 +675,8 @@ void Device::PlaybackPosNotificationResponse(uint8_t label, bool interim, return; } - auto response = - RegisterNotificationResponseBuilder::MakePlaybackPositionBuilder( - interim, status.position); + auto response = RegisterNotificationResponseBuilder::MakePlaybackPositionBuilder(interim, + status.position); send_message_cb_.Run(label, false, std::move(response)); last_play_status_.position = status.position; @@ -752,23 +691,22 @@ void Device::PlaybackPosNotificationResponse(uint8_t label, bool interim, // the status bar on the remote device move. if (status.state == PlayState::PLAYING && !IsInSilenceMode()) { log::verbose("Queue next play position update"); - play_pos_update_cb_.Reset(base::Bind(&Device::HandlePlayPosUpdate, - weak_ptr_factory_.GetWeakPtr())); + play_pos_update_cb_.Reset( + base::Bind(&Device::HandlePlayPosUpdate, weak_ptr_factory_.GetWeakPtr())); btbase::AbstractMessageLoop::current_task_runner()->PostDelayedTask( - FROM_HERE, play_pos_update_cb_.callback(), + FROM_HERE, play_pos_update_cb_.callback(), #if BASE_VER < 931007 - base::TimeDelta::FromSeconds(play_pos_interval_)); + base::TimeDelta::FromSeconds(play_pos_interval_)); #else - base::Seconds(play_pos_interval_)); + base::Seconds(play_pos_interval_)); #endif } } // TODO (apanicke): Finish implementing when we add support for more than one // player -void Device::AddressedPlayerNotificationResponse( - uint8_t label, bool interim, uint16_t curr_player, - std::vector /* unused */) { +void Device::AddressedPlayerNotificationResponse(uint8_t label, bool interim, uint16_t curr_player, + std::vector /* unused */) { log::verbose("curr_player_id={}", (unsigned int)curr_player); if (interim) { @@ -782,10 +720,11 @@ void Device::AddressedPlayerNotificationResponse( // default NOTE: Using any browsing commands before the browsed player is set // is a violation of the AVRCP Spec but there are some carkits that try too // anyways - if (curr_browsed_player_id_ == -1) curr_browsed_player_id_ = curr_player; + if (curr_browsed_player_id_ == -1) { + curr_browsed_player_id_ = curr_player; + } - auto response = - RegisterNotificationResponseBuilder::MakeAddressedPlayerBuilder( + auto response = RegisterNotificationResponseBuilder::MakeAddressedPlayerBuilder( interim, curr_player, 0x0000); send_message_cb_.Run(label, false, std::move(response)); @@ -798,13 +737,12 @@ void Device::AddressedPlayerNotificationResponse( void Device::RejectNotification() { log::verbose(""); - Notification* rejectNotification[] = {&play_status_changed_, &track_changed_, - &play_pos_changed_, + Notification* rejectNotification[] = {&play_status_changed_, &track_changed_, &play_pos_changed_, &now_playing_changed_}; for (int i = 0; i < 4; i++) { uint8_t label = rejectNotification[i]->second; - auto response = RejectBuilder::MakeBuilder( - CommandPdu::REGISTER_NOTIFICATION, Status::ADDRESSED_PLAYER_CHANGED); + auto response = RejectBuilder::MakeBuilder(CommandPdu::REGISTER_NOTIFICATION, + Status::ADDRESSED_PLAYER_CHANGED); send_message_cb_.Run(label, false, std::move(response)); active_labels_.erase(label); rejectNotification[i] = new Notification(false, 0); @@ -812,20 +750,17 @@ void Device::RejectNotification() { } void Device::GetPlayStatusResponse(uint8_t label, PlayStatus status) { - log::verbose("position={} duration={} state={}", status.position, - status.duration, status.state); + log::verbose("position={} duration={} state={}", status.position, status.duration, status.state); auto response = GetPlayStatusResponseBuilder::MakeBuilder( - status.duration, status.position, - IsActive() ? status.state : PlayState::PAUSED); + status.duration, status.position, IsActive() ? status.state : PlayState::PAUSED); send_message(label, false, std::move(response)); } -void Device::GetElementAttributesResponse( - uint8_t label, std::shared_ptr pkt, - SongInfo info) { +void Device::GetElementAttributesResponse(uint8_t label, + std::shared_ptr pkt, + SongInfo info) { auto get_element_attributes_pkt = pkt; - auto attributes_requested = - get_element_attributes_pkt->GetAttributesRequested(); + auto attributes_requested = get_element_attributes_pkt->GetAttributesRequested(); auto response = GetElementAttributesResponseBuilder::MakeBuilder(ctrl_mtu_); @@ -854,8 +789,7 @@ void Device::GetElementAttributesResponse( void Device::MessageReceived(uint8_t label, std::shared_ptr pkt) { if (!pkt->IsValid()) { log::warn("{}: Request packet is not valid", address_); - auto response = RejectBuilder::MakeBuilder(static_cast(0), - Status::INVALID_COMMAND); + auto response = RejectBuilder::MakeBuilder(static_cast(0), Status::INVALID_COMMAND); send_message(label, false, std::move(response)); return; } @@ -871,24 +805,24 @@ void Device::MessageReceived(uint8_t label, std::shared_ptr pkt) { } break; case Opcode::PASS_THROUGH: { /** Newavrcp not passthrough response pkt. @{ */ - if (pkt->GetCType() == CType::ACCEPTED || - pkt->GetCType() == CType::REJECTED || - pkt->GetCType() == CType::NOT_IMPLEMENTED) + if (pkt->GetCType() == CType::ACCEPTED || pkt->GetCType() == CType::REJECTED || + pkt->GetCType() == CType::NOT_IMPLEMENTED) { break; + } /** @} */ auto pass_through_packet = Packet::Specialize(pkt); if (!pass_through_packet->IsValid()) { log::warn("{}: Request packet is not valid", address_); - auto response = RejectBuilder::MakeBuilder(static_cast(0), - Status::INVALID_COMMAND); + auto response = + RejectBuilder::MakeBuilder(static_cast(0), Status::INVALID_COMMAND); send_message(label, false, std::move(response)); return; } auto response = PassThroughPacketBuilder::MakeBuilder( - true, pass_through_packet->GetKeyState() == KeyState::PUSHED, - pass_through_packet->GetOperationId()); + true, pass_through_packet->GetKeyState() == KeyState::PUSHED, + pass_through_packet->GetOperationId()); send_message(label, false, std::move(response)); // TODO (apanicke): Use an enum for media key ID's @@ -898,23 +832,24 @@ void Device::MessageReceived(uint8_t label, std::shared_ptr pkt) { // what the actual playstate is without being modified // by whether the device is active. media_interface_->GetPlayStatus(base::Bind( - [](base::WeakPtr d, PlayStatus s) { - if (!d) return; - - if (!d->IsActive()) { - log::info("Setting {} to be the active device", d->address_); - d->media_interface_->SetActiveDevice(d->address_); - - if (s.state == PlayState::PLAYING) { - log::info( - "Skipping sendKeyEvent since music is already playing"); - return; - } - } - - d->media_interface_->SendKeyEvent(0x44, KeyState::PUSHED); - }, - weak_ptr_factory_.GetWeakPtr())); + [](base::WeakPtr d, PlayStatus s) { + if (!d) { + return; + } + + if (!d->IsActive()) { + log::info("Setting {} to be the active device", d->address_); + d->media_interface_->SetActiveDevice(d->address_); + + if (s.state == PlayState::PLAYING) { + log::info("Skipping sendKeyEvent since music is already playing"); + return; + } + } + + d->media_interface_->SendKeyEvent(0x44, KeyState::PUSHED); + }, + weak_ptr_factory_.GetWeakPtr())); return; } @@ -930,12 +865,10 @@ void Device::MessageReceived(uint8_t label, std::shared_ptr pkt) { } } -void Device::HandlePlayItem(uint8_t label, - std::shared_ptr pkt) { +void Device::HandlePlayItem(uint8_t label, std::shared_ptr pkt) { if (!pkt->IsValid()) { log::warn("{}: Request packet is not valid", address_); - auto response = RejectBuilder::MakeBuilder(pkt->GetCommandPdu(), - Status::INVALID_PARAMETER); + auto response = RejectBuilder::MakeBuilder(pkt->GetCommandPdu(), Status::INVALID_PARAMETER); send_message(label, false, std::move(response)); return; } @@ -956,39 +889,36 @@ void Device::HandlePlayItem(uint8_t label, if (media_id == "") { log::verbose("Could not find item"); - auto response = RejectBuilder::MakeBuilder(CommandPdu::PLAY_ITEM, - Status::DOES_NOT_EXIST); + auto response = RejectBuilder::MakeBuilder(CommandPdu::PLAY_ITEM, Status::DOES_NOT_EXIST); send_message(label, false, std::move(response)); return; } - media_interface_->PlayItem(curr_browsed_player_id_, - pkt->GetScope() == Scope::NOW_PLAYING, media_id); + media_interface_->PlayItem(curr_browsed_player_id_, pkt->GetScope() == Scope::NOW_PLAYING, + media_id); auto response = PlayItemResponseBuilder::MakeBuilder(Status::NO_ERROR); send_message(label, false, std::move(response)); } -void Device::HandleSetAddressedPlayer( - uint8_t label, std::shared_ptr pkt, - uint16_t curr_player, std::vector players) { +void Device::HandleSetAddressedPlayer(uint8_t label, std::shared_ptr pkt, + uint16_t curr_player, std::vector players) { log::verbose("PlayerId={}", pkt->GetPlayerId()); if (curr_player != pkt->GetPlayerId()) { log::verbose("Reject invalid addressed player ID"); - auto response = RejectBuilder::MakeBuilder(CommandPdu::SET_ADDRESSED_PLAYER, - Status::INVALID_PLAYER_ID); + auto response = + RejectBuilder::MakeBuilder(CommandPdu::SET_ADDRESSED_PLAYER, Status::INVALID_PLAYER_ID); send_message(label, false, std::move(response)); return; } - auto response = - SetAddressedPlayerResponseBuilder::MakeBuilder(Status::NO_ERROR); + auto response = SetAddressedPlayerResponseBuilder::MakeBuilder(Status::NO_ERROR); send_message(label, false, std::move(response)); } void Device::ListPlayerApplicationSettingAttributesResponse( - uint8_t label, std::vector attributes) { + uint8_t label, std::vector attributes) { uint8_t num_of_attributes = attributes.size(); log::verbose("num_of_attributes={}", num_of_attributes); if (num_of_attributes > 0) { @@ -997,16 +927,14 @@ void Device::ListPlayerApplicationSettingAttributesResponse( } } auto response = - ListPlayerApplicationSettingAttributesResponseBuilder::MakeBuilder( - std::move(attributes)); + ListPlayerApplicationSettingAttributesResponseBuilder::MakeBuilder(std::move(attributes)); send_message(label, false, std::move(response)); } -void Device::ListPlayerApplicationSettingValuesResponse( - uint8_t label, PlayerAttribute attribute, std::vector values) { +void Device::ListPlayerApplicationSettingValuesResponse(uint8_t label, PlayerAttribute attribute, + std::vector values) { uint8_t number_of_values = values.size(); - log::verbose("attribute={}, number_of_values={}", attribute, - number_of_values); + log::verbose("attribute={}, number_of_values={}", attribute, number_of_values); if (number_of_values > 0) { if (attribute == PlayerAttribute::REPEAT) { @@ -1022,15 +950,13 @@ void Device::ListPlayerApplicationSettingValuesResponse( } } - auto response = - ListPlayerApplicationSettingValuesResponseBuilder::MakeBuilder( - std::move(values)); + auto response = ListPlayerApplicationSettingValuesResponseBuilder::MakeBuilder(std::move(values)); send_message(label, false, std::move(response)); } -void Device::GetPlayerApplicationSettingValueResponse( - uint8_t label, std::vector attributes, - std::vector values) { +void Device::GetPlayerApplicationSettingValueResponse(uint8_t label, + std::vector attributes, + std::vector values) { for (size_t i = 0; i < attributes.size(); i++) { log::verbose("attribute={}", static_cast(attributes[i])); if (attributes[i] == PlayerAttribute::REPEAT) { @@ -1042,15 +968,12 @@ void Device::GetPlayerApplicationSettingValueResponse( } } - auto response = - GetCurrentPlayerApplicationSettingValueResponseBuilder::MakeBuilder( + auto response = GetCurrentPlayerApplicationSettingValueResponseBuilder::MakeBuilder( std::move(attributes), std::move(values)); send_message(label, false, std::move(response)); } -void Device::SetPlayerApplicationSettingValueResponse(uint8_t label, - CommandPdu pdu, - bool success) { +void Device::SetPlayerApplicationSettingValueResponse(uint8_t label, CommandPdu pdu, bool success) { if (!success) { log::error("{}: Set Player Application Setting Value failed", address_); auto response = RejectBuilder::MakeBuilder(pdu, Status::INVALID_PARAMETER); @@ -1058,13 +981,11 @@ void Device::SetPlayerApplicationSettingValueResponse(uint8_t label, return; } - auto response = - SetPlayerApplicationSettingValueResponseBuilder::MakeBuilder(); + auto response = SetPlayerApplicationSettingValueResponseBuilder::MakeBuilder(); send_message(label, false, std::move(response)); } -void Device::BrowseMessageReceived(uint8_t label, - std::shared_ptr pkt) { +void Device::BrowseMessageReceived(uint8_t label, std::shared_ptr pkt) { if (!pkt->IsValid()) { log::warn("{}: Request packet is not valid", address_); auto response = GeneralRejectBuilder::MakeBuilder(Status::INVALID_COMMAND); @@ -1076,41 +997,35 @@ void Device::BrowseMessageReceived(uint8_t label, switch (pkt->GetPdu()) { case BrowsePdu::SET_BROWSED_PLAYER: - HandleSetBrowsedPlayer(label, - Packet::Specialize(pkt)); + HandleSetBrowsedPlayer(label, Packet::Specialize(pkt)); break; case BrowsePdu::GET_FOLDER_ITEMS: - HandleGetFolderItems(label, - Packet::Specialize(pkt)); + HandleGetFolderItems(label, Packet::Specialize(pkt)); break; case BrowsePdu::CHANGE_PATH: HandleChangePath(label, Packet::Specialize(pkt)); break; case BrowsePdu::GET_ITEM_ATTRIBUTES: - HandleGetItemAttributes( - label, Packet::Specialize(pkt)); + HandleGetItemAttributes(label, Packet::Specialize(pkt)); break; case BrowsePdu::GET_TOTAL_NUMBER_OF_ITEMS: - HandleGetTotalNumberOfItems( - label, Packet::Specialize(pkt)); + HandleGetTotalNumberOfItems(label, Packet::Specialize(pkt)); break; default: log::warn("{}: pdu={}", address_, pkt->GetPdu()); - auto response = - GeneralRejectBuilder::MakeBuilder(Status::INVALID_COMMAND); + auto response = GeneralRejectBuilder::MakeBuilder(Status::INVALID_COMMAND); send_message(label, true, std::move(response)); break; } } -void Device::HandleGetFolderItems(uint8_t label, - std::shared_ptr pkt) { +void Device::HandleGetFolderItems(uint8_t label, std::shared_ptr pkt) { if (!pkt->IsValid()) { // The specific get folder items builder is unimportant on failure. log::warn("{}: Get folder items request packet is not valid", address_); - auto response = GetFolderItemsResponseBuilder::MakePlayerListBuilder( - Status::INVALID_PARAMETER, 0x0000, browse_mtu_); + auto response = GetFolderItemsResponseBuilder::MakePlayerListBuilder(Status::INVALID_PARAMETER, + 0x0000, browse_mtu_); send_message(label, true, std::move(response)); return; } @@ -1119,36 +1034,33 @@ void Device::HandleGetFolderItems(uint8_t label, switch (pkt->GetScope()) { case Scope::MEDIA_PLAYER_LIST: - media_interface_->GetMediaPlayerList( - base::Bind(&Device::GetMediaPlayerListResponse, - weak_ptr_factory_.GetWeakPtr(), label, pkt)); + media_interface_->GetMediaPlayerList(base::Bind(&Device::GetMediaPlayerListResponse, + weak_ptr_factory_.GetWeakPtr(), label, pkt)); break; case Scope::VFS: media_interface_->GetFolderItems( - curr_browsed_player_id_, CurrentFolder(), - base::Bind(&Device::GetVFSListResponse, - weak_ptr_factory_.GetWeakPtr(), label, pkt)); + curr_browsed_player_id_, CurrentFolder(), + base::Bind(&Device::GetVFSListResponse, weak_ptr_factory_.GetWeakPtr(), label, pkt)); break; case Scope::NOW_PLAYING: - media_interface_->GetNowPlayingList( - base::Bind(&Device::GetNowPlayingListResponse, - weak_ptr_factory_.GetWeakPtr(), label, pkt)); + media_interface_->GetNowPlayingList(base::Bind(&Device::GetNowPlayingListResponse, + weak_ptr_factory_.GetWeakPtr(), label, pkt)); break; default: log::error("{}: scope={}", address_, pkt->GetScope()); auto response = GetFolderItemsResponseBuilder::MakePlayerListBuilder( - Status::INVALID_PARAMETER, 0, browse_mtu_); + Status::INVALID_PARAMETER, 0, browse_mtu_); send_message(label, true, std::move(response)); break; } } -void Device::HandleGetTotalNumberOfItems( - uint8_t label, std::shared_ptr pkt) { +void Device::HandleGetTotalNumberOfItems(uint8_t label, + std::shared_ptr pkt) { if (!pkt->IsValid()) { log::warn("{}: Request packet is not valid", address_); - auto response = GetTotalNumberOfItemsResponseBuilder::MakeBuilder( - Status::INVALID_PARAMETER, 0x0000, 0); + auto response = + GetTotalNumberOfItemsResponseBuilder::MakeBuilder(Status::INVALID_PARAMETER, 0x0000, 0); send_message(label, true, std::move(response)); return; } @@ -1158,20 +1070,19 @@ void Device::HandleGetTotalNumberOfItems( switch (pkt->GetScope()) { case Scope::MEDIA_PLAYER_LIST: { media_interface_->GetMediaPlayerList( - base::Bind(&Device::GetTotalNumberOfItemsMediaPlayersResponse, - weak_ptr_factory_.GetWeakPtr(), label)); + base::Bind(&Device::GetTotalNumberOfItemsMediaPlayersResponse, + weak_ptr_factory_.GetWeakPtr(), label)); break; } case Scope::VFS: - media_interface_->GetFolderItems( - curr_browsed_player_id_, CurrentFolder(), - base::Bind(&Device::GetTotalNumberOfItemsVFSResponse, - weak_ptr_factory_.GetWeakPtr(), label)); + media_interface_->GetFolderItems(curr_browsed_player_id_, CurrentFolder(), + base::Bind(&Device::GetTotalNumberOfItemsVFSResponse, + weak_ptr_factory_.GetWeakPtr(), label)); break; case Scope::NOW_PLAYING: media_interface_->GetNowPlayingList( - base::Bind(&Device::GetTotalNumberOfItemsNowPlayingResponse, - weak_ptr_factory_.GetWeakPtr(), label)); + base::Bind(&Device::GetTotalNumberOfItemsNowPlayingResponse, + weak_ptr_factory_.GetWeakPtr(), label)); break; default: log::error("{}: scope={}", address_, pkt->GetScope()); @@ -1179,50 +1090,45 @@ void Device::HandleGetTotalNumberOfItems( } } -void Device::GetTotalNumberOfItemsMediaPlayersResponse( - uint8_t label, uint16_t curr_player, std::vector list) { +void Device::GetTotalNumberOfItemsMediaPlayersResponse(uint8_t label, uint16_t curr_player, + std::vector list) { log::verbose("num_items={}", list.size()); - auto builder = GetTotalNumberOfItemsResponseBuilder::MakeBuilder( - Status::NO_ERROR, 0x0000, list.size()); + auto builder = + GetTotalNumberOfItemsResponseBuilder::MakeBuilder(Status::NO_ERROR, 0x0000, list.size()); send_message(label, true, std::move(builder)); } -void Device::GetTotalNumberOfItemsVFSResponse(uint8_t label, - std::vector list) { +void Device::GetTotalNumberOfItemsVFSResponse(uint8_t label, std::vector list) { log::verbose("num_items={}", list.size()); - auto builder = GetTotalNumberOfItemsResponseBuilder::MakeBuilder( - Status::NO_ERROR, 0x0000, list.size()); + auto builder = + GetTotalNumberOfItemsResponseBuilder::MakeBuilder(Status::NO_ERROR, 0x0000, list.size()); send_message(label, true, std::move(builder)); } -void Device::GetTotalNumberOfItemsNowPlayingResponse( - uint8_t label, std::string curr_song_id, std::vector list) { +void Device::GetTotalNumberOfItemsNowPlayingResponse(uint8_t label, std::string curr_song_id, + std::vector list) { log::verbose("num_items={}", list.size()); - auto builder = GetTotalNumberOfItemsResponseBuilder::MakeBuilder( - Status::NO_ERROR, 0x0000, list.size()); + auto builder = + GetTotalNumberOfItemsResponseBuilder::MakeBuilder(Status::NO_ERROR, 0x0000, list.size()); send_message(label, true, std::move(builder)); } -void Device::HandleChangePath(uint8_t label, - std::shared_ptr pkt) { +void Device::HandleChangePath(uint8_t label, std::shared_ptr pkt) { if (!pkt->IsValid()) { log::warn("{}: Request packet is not valid", address_); - auto response = - ChangePathResponseBuilder::MakeBuilder(Status::INVALID_PARAMETER, 0); + auto response = ChangePathResponseBuilder::MakeBuilder(Status::INVALID_PARAMETER, 0); send_message(label, true, std::move(response)); return; } log::verbose("direction={} uid=0x{:x}", pkt->GetDirection(), pkt->GetUid()); - if (pkt->GetDirection() == Direction::DOWN && - vfs_ids_.get_media_id(pkt->GetUid()) == "") { + if (pkt->GetDirection() == Direction::DOWN && vfs_ids_.get_media_id(pkt->GetUid()) == "") { log::error("{}: No item found for UID={}", address_, pkt->GetUid()); - auto builder = - ChangePathResponseBuilder::MakeBuilder(Status::DOES_NOT_EXIST, 0); + auto builder = ChangePathResponseBuilder::MakeBuilder(Status::DOES_NOT_EXIST, 0); send_message(label, true, std::move(builder)); return; } @@ -1236,8 +1142,7 @@ void Device::HandleChangePath(uint8_t label, current_path_.pop(); } else { log::error("{}: Trying to change directory up past root.", address_); - auto builder = - ChangePathResponseBuilder::MakeBuilder(Status::DOES_NOT_EXIST, 0); + auto builder = ChangePathResponseBuilder::MakeBuilder(Status::DOES_NOT_EXIST, 0); send_message(label, true, std::move(builder)); return; } @@ -1246,56 +1151,49 @@ void Device::HandleChangePath(uint8_t label, } media_interface_->GetFolderItems( - curr_browsed_player_id_, CurrentFolder(), - base::Bind(&Device::ChangePathResponse, weak_ptr_factory_.GetWeakPtr(), - label, pkt)); + curr_browsed_player_id_, CurrentFolder(), + base::Bind(&Device::ChangePathResponse, weak_ptr_factory_.GetWeakPtr(), label, pkt)); } -void Device::ChangePathResponse(uint8_t label, - std::shared_ptr pkt, +void Device::ChangePathResponse(uint8_t label, std::shared_ptr pkt, std::vector list) { // TODO (apanicke): Reconstruct the VFS ID's here. Right now it gets // reconstructed in GetFolderItemsVFS - auto builder = - ChangePathResponseBuilder::MakeBuilder(Status::NO_ERROR, list.size()); + auto builder = ChangePathResponseBuilder::MakeBuilder(Status::NO_ERROR, list.size()); send_message(label, true, std::move(builder)); } -void Device::HandleGetItemAttributes( - uint8_t label, std::shared_ptr pkt) { +void Device::HandleGetItemAttributes(uint8_t label, std::shared_ptr pkt) { if (!pkt->IsValid()) { log::warn("{}: Request packet is not valid", address_); - auto builder = GetItemAttributesResponseBuilder::MakeBuilder( - Status::INVALID_PARAMETER, browse_mtu_); + auto builder = + GetItemAttributesResponseBuilder::MakeBuilder(Status::INVALID_PARAMETER, browse_mtu_); send_message(label, true, std::move(builder)); return; } - log::verbose("scope={} uid=0x{:x} uid counter=0x{:x}", pkt->GetScope(), - pkt->GetUid(), pkt->GetUidCounter()); + log::verbose("scope={} uid=0x{:x} uid counter=0x{:x}", pkt->GetScope(), pkt->GetUid(), + pkt->GetUidCounter()); if (pkt->GetUidCounter() != 0x0000) { // For database unaware player, use 0 log::warn("{}: UidCounter is invalid", address_); - auto builder = GetItemAttributesResponseBuilder::MakeBuilder( - Status::UIDS_CHANGED, browse_mtu_); + auto builder = GetItemAttributesResponseBuilder::MakeBuilder(Status::UIDS_CHANGED, browse_mtu_); send_message(label, true, std::move(builder)); return; } switch (pkt->GetScope()) { case Scope::NOW_PLAYING: { - media_interface_->GetNowPlayingList( - base::Bind(&Device::GetItemAttributesNowPlayingResponse, - weak_ptr_factory_.GetWeakPtr(), label, pkt)); + media_interface_->GetNowPlayingList(base::Bind(&Device::GetItemAttributesNowPlayingResponse, + weak_ptr_factory_.GetWeakPtr(), label, pkt)); } break; case Scope::VFS: // TODO (apanicke): Check the vfs_ids_ here. If the item doesn't exist // then we can auto send the error without calling up. We do this check // later right now though in order to prevent race conditions with updates // on the media layer. - media_interface_->GetFolderItems( - curr_browsed_player_id_, CurrentFolder(), - base::Bind(&Device::GetItemAttributesVFSResponse, - weak_ptr_factory_.GetWeakPtr(), label, pkt)); + media_interface_->GetFolderItems(curr_browsed_player_id_, CurrentFolder(), + base::Bind(&Device::GetItemAttributesVFSResponse, + weak_ptr_factory_.GetWeakPtr(), label, pkt)); break; default: log::error("{}: UNKNOWN SCOPE FOR HANDLE GET ITEM ATTRIBUTES", address_); @@ -1303,12 +1201,12 @@ void Device::HandleGetItemAttributes( } } -void Device::GetItemAttributesNowPlayingResponse( - uint8_t label, std::shared_ptr pkt, - std::string curr_media_id, std::vector song_list) { +void Device::GetItemAttributesNowPlayingResponse(uint8_t label, + std::shared_ptr pkt, + std::string curr_media_id, + std::vector song_list) { log::verbose("uid=0x{:x}", pkt->GetUid()); - auto builder = GetItemAttributesResponseBuilder::MakeBuilder(Status::NO_ERROR, - browse_mtu_); + auto builder = GetItemAttributesResponseBuilder::MakeBuilder(Status::NO_ERROR, browse_mtu_); auto media_id = now_playing_ids_.get_media_id(pkt->GetUid()); if (media_id == "") { @@ -1352,22 +1250,21 @@ void Device::GetItemAttributesNowPlayingResponse( send_message(label, true, std::move(builder)); } -void Device::GetItemAttributesVFSResponse( - uint8_t label, std::shared_ptr pkt, - std::vector item_list) { +void Device::GetItemAttributesVFSResponse(uint8_t label, + std::shared_ptr pkt, + std::vector item_list) { log::verbose("uid=0x{:x}", pkt->GetUid()); auto media_id = vfs_ids_.get_media_id(pkt->GetUid()); if (media_id == "") { log::warn("Item not found"); - auto builder = GetItemAttributesResponseBuilder::MakeBuilder( - Status::DOES_NOT_EXIST, browse_mtu_); + auto builder = + GetItemAttributesResponseBuilder::MakeBuilder(Status::DOES_NOT_EXIST, browse_mtu_); send_message(label, true, std::move(builder)); return; } - auto builder = GetItemAttributesResponseBuilder::MakeBuilder(Status::NO_ERROR, - browse_mtu_); + auto builder = GetItemAttributesResponseBuilder::MakeBuilder(Status::NO_ERROR, browse_mtu_); ListItem item_requested; item_requested.type = ListItem::SONG; @@ -1393,8 +1290,7 @@ void Device::GetItemAttributesVFSResponse( } else { for (auto& attr : attributes_requested) { if (attr == Attribute::TITLE) { - builder->AddAttributeEntry(Attribute::TITLE, - item_requested.folder.name); + builder->AddAttributeEntry(Attribute::TITLE, item_requested.folder.name); } } } @@ -1403,8 +1299,7 @@ void Device::GetItemAttributesVFSResponse( for (const auto& attribute : attributes_requested) { if (item_requested.song.attributes.find(attribute) != item_requested.song.attributes.end()) { - builder->AddAttributeEntry( - *item_requested.song.attributes.find(attribute)); + builder->AddAttributeEntry(*item_requested.song.attributes.find(attribute)); } } } else { @@ -1419,19 +1314,19 @@ void Device::GetItemAttributesVFSResponse( send_message(label, true, std::move(builder)); } -void Device::GetMediaPlayerListResponse( - uint8_t label, std::shared_ptr pkt, - uint16_t curr_player, std::vector players) { +void Device::GetMediaPlayerListResponse(uint8_t label, std::shared_ptr pkt, + uint16_t curr_player, + std::vector players) { log::verbose(""); if (players.size() == 0) { auto no_items_rsp = GetFolderItemsResponseBuilder::MakePlayerListBuilder( - Status::RANGE_OUT_OF_BOUNDS, 0x0000, browse_mtu_); + Status::RANGE_OUT_OF_BOUNDS, 0x0000, browse_mtu_); send_message(label, true, std::move(no_items_rsp)); } - auto builder = GetFolderItemsResponseBuilder::MakePlayerListBuilder( - Status::NO_ERROR, 0x0000, browse_mtu_); + auto builder = GetFolderItemsResponseBuilder::MakePlayerListBuilder(Status::NO_ERROR, 0x0000, + browse_mtu_); // Move the current player to the first slot due to some carkits always // connecting to the first listed player rather than using the ID @@ -1446,18 +1341,16 @@ void Device::GetMediaPlayerListResponse( } } - for (size_t i = pkt->GetStartItem(); - i <= pkt->GetEndItem() && i < players.size(); i++) { - MediaPlayerItem item(players[i].id, players[i].name, - players[i].browsing_supported); + for (size_t i = pkt->GetStartItem(); i <= pkt->GetEndItem() && i < players.size(); i++) { + MediaPlayerItem item(players[i].id, players[i].name, players[i].browsing_supported); builder->AddMediaPlayer(item); } send_message(label, true, std::move(builder)); } -std::set filter_attributes_requested( - const SongInfo& song, const std::vector& attrs) { +std::set filter_attributes_requested(const SongInfo& song, + const std::vector& attrs) { std::set result; for (const auto& attr : attrs) { if (song.attributes.find(attr) != song.attributes.end()) { @@ -1468,15 +1361,13 @@ std::set filter_attributes_requested( return result; } -void Device::GetVFSListResponse(uint8_t label, - std::shared_ptr pkt, +void Device::GetVFSListResponse(uint8_t label, std::shared_ptr pkt, std::vector items) { - log::verbose("start_item={} end_item={}", pkt->GetStartItem(), - pkt->GetEndItem()); + log::verbose("start_item={} end_item={}", pkt->GetStartItem(), pkt->GetEndItem()); // The builder will automatically correct the status if there are zero items - auto builder = GetFolderItemsResponseBuilder::MakeVFSBuilder( - Status::NO_ERROR, 0x0000, browse_mtu_); + auto builder = + GetFolderItemsResponseBuilder::MakeVFSBuilder(Status::NO_ERROR, 0x0000, browse_mtu_); // TODO (apanicke): Add test that checks if vfs_ids_ is the correct size after // an operation. @@ -1493,14 +1384,15 @@ void Device::GetVFSListResponse(uint8_t label, // happens. These items do not need to correspond with the now playing list as // the UID's only need to be unique in the context of the current scope and // the current folder - for (auto i = pkt->GetStartItem(); i <= pkt->GetEndItem() && i < items.size(); - i++) { + for (auto i = pkt->GetStartItem(); i <= pkt->GetEndItem() && i < items.size(); i++) { if (items[i].type == ListItem::FOLDER) { auto folder = items[i].folder; // right now we always use folders of mixed type - FolderItem folder_item(vfs_ids_.get_uid(folder.media_id), 0x00, - folder.is_playable, folder.name); - if (!builder->AddFolder(folder_item)) break; + FolderItem folder_item(vfs_ids_.get_uid(folder.media_id), 0x00, folder.is_playable, + folder.name); + if (!builder->AddFolder(folder_item)) { + break; + } } else if (items[i].type == ListItem::SONG) { auto song = items[i].song; @@ -1509,43 +1401,42 @@ void Device::GetVFSListResponse(uint8_t label, filter_cover_art(song); } - auto title = - song.attributes.find(Attribute::TITLE) != song.attributes.end() - ? song.attributes.find(Attribute::TITLE)->value() - : "No Song Info"; + auto title = song.attributes.find(Attribute::TITLE) != song.attributes.end() + ? song.attributes.find(Attribute::TITLE)->value() + : "No Song Info"; MediaElementItem song_item(vfs_ids_.get_uid(song.media_id), title, std::set()); if (pkt->GetNumAttributes() == 0x00) { // All attributes requested song_item.attributes_ = std::move(song.attributes); } else { - song_item.attributes_ = - filter_attributes_requested(song, pkt->GetAttributesRequested()); + song_item.attributes_ = filter_attributes_requested(song, pkt->GetAttributesRequested()); } // If we fail to add a song, don't accidentally add one later that might // fit. - if (!builder->AddSong(song_item)) break; + if (!builder->AddSong(song_item)) { + break; + } } } send_message(label, true, std::move(builder)); } -void Device::GetNowPlayingListResponse( - uint8_t label, std::shared_ptr pkt, - std::string /* unused curr_song_id */, std::vector song_list) { +void Device::GetNowPlayingListResponse(uint8_t label, std::shared_ptr pkt, + std::string /* unused curr_song_id */, + std::vector song_list) { log::verbose(""); - auto builder = GetFolderItemsResponseBuilder::MakeNowPlayingBuilder( - Status::NO_ERROR, 0x0000, browse_mtu_); + auto builder = GetFolderItemsResponseBuilder::MakeNowPlayingBuilder(Status::NO_ERROR, 0x0000, + browse_mtu_); now_playing_ids_.clear(); for (const SongInfo& song : song_list) { now_playing_ids_.insert(song.media_id); } - for (size_t i = pkt->GetStartItem(); - i <= pkt->GetEndItem() && i < song_list.size(); i++) { + for (size_t i = pkt->GetStartItem(); i <= pkt->GetEndItem() && i < song_list.size(); i++) { auto song = song_list[i]; // Filter out DEFAULT_COVER_ART handle if this device has no client @@ -1554,59 +1445,56 @@ void Device::GetNowPlayingListResponse( } auto title = song.attributes.find(Attribute::TITLE) != song.attributes.end() - ? song.attributes.find(Attribute::TITLE)->value() - : "No Song Info"; + ? song.attributes.find(Attribute::TITLE)->value() + : "No Song Info"; MediaElementItem item(i + 1, title, std::set()); if (pkt->GetNumAttributes() == 0x00) { item.attributes_ = std::move(song.attributes); } else { - item.attributes_ = - filter_attributes_requested(song, pkt->GetAttributesRequested()); + item.attributes_ = filter_attributes_requested(song, pkt->GetAttributesRequested()); } // If we fail to add a song, don't accidentally add one later that might // fit. - if (!builder->AddSong(item)) break; + if (!builder->AddSong(item)) { + break; + } } send_message(label, true, std::move(builder)); } -void Device::HandleSetBrowsedPlayer( - uint8_t label, std::shared_ptr pkt) { +void Device::HandleSetBrowsedPlayer(uint8_t label, std::shared_ptr pkt) { if (!pkt->IsValid()) { log::warn("{}: Request packet is not valid", address_); - auto response = SetBrowsedPlayerResponseBuilder::MakeBuilder( - Status::INVALID_PARAMETER, 0x0000, 0, 0, ""); + auto response = SetBrowsedPlayerResponseBuilder::MakeBuilder(Status::INVALID_PARAMETER, 0x0000, + 0, 0, ""); send_message(label, true, std::move(response)); return; } log::verbose("player_id={}", pkt->GetPlayerId()); - media_interface_->SetBrowsedPlayer( - pkt->GetPlayerId(), - base::Bind(&Device::SetBrowsedPlayerResponse, - weak_ptr_factory_.GetWeakPtr(), label, pkt)); + media_interface_->SetBrowsedPlayer(pkt->GetPlayerId(), + base::Bind(&Device::SetBrowsedPlayerResponse, + weak_ptr_factory_.GetWeakPtr(), label, pkt)); } -void Device::SetBrowsedPlayerResponse( - uint8_t label, std::shared_ptr pkt, bool success, - std::string root_id, uint32_t num_items) { - log::verbose("success={} root_id=\"{}\" num_items={}", success, root_id, - num_items); +void Device::SetBrowsedPlayerResponse(uint8_t label, std::shared_ptr pkt, + bool success, std::string root_id, uint32_t num_items) { + log::verbose("success={} root_id=\"{}\" num_items={}", success, root_id, num_items); if (!success) { - auto response = SetBrowsedPlayerResponseBuilder::MakeBuilder( - Status::INVALID_PLAYER_ID, 0x0000, num_items, 0, ""); + auto response = SetBrowsedPlayerResponseBuilder::MakeBuilder(Status::INVALID_PLAYER_ID, 0x0000, + num_items, 0, ""); send_message(label, true, std::move(response)); return; } if (pkt->GetPlayerId() == 0 && num_items == 0) { // Response fail if no browsable player in Bluetooth Player - auto response = SetBrowsedPlayerResponseBuilder::MakeBuilder( - Status::PLAYER_NOT_BROWSABLE, 0x0000, num_items, 0, ""); + auto response = SetBrowsedPlayerResponseBuilder::MakeBuilder(Status::PLAYER_NOT_BROWSABLE, + 0x0000, num_items, 0, ""); send_message(label, true, std::move(response)); return; } @@ -1617,18 +1505,17 @@ void Device::SetBrowsedPlayerResponse( current_path_ = std::stack(); current_path_.push(root_id); - auto response = SetBrowsedPlayerResponseBuilder::MakeBuilder( - Status::NO_ERROR, 0x0000, num_items, 0, ""); + auto response = + SetBrowsedPlayerResponseBuilder::MakeBuilder(Status::NO_ERROR, 0x0000, num_items, 0, ""); send_message(label, true, std::move(response)); } void Device::SendMediaUpdate(bool metadata, bool play_status, bool queue) { bool is_silence = IsInSilenceMode(); - log::assert_that(media_interface_ != nullptr, - "assert failed: media_interface_ != nullptr"); - log::verbose("Metadata={} : play_status= {} : queue={} : is_silence={}", - metadata, play_status, queue, is_silence); + log::assert_that(media_interface_ != nullptr, "assert failed: media_interface_ != nullptr"); + log::verbose("Metadata={} : play_status= {} : queue={} : is_silence={}", metadata, play_status, + queue, is_silence); if (queue) { HandleNowPlayingUpdate(); @@ -1641,13 +1528,13 @@ void Device::SendMediaUpdate(bool metadata, bool play_status, bool queue) { } } - if (metadata) HandleTrackUpdate(); + if (metadata) { + HandleTrackUpdate(); + } } -void Device::SendFolderUpdate(bool available_players, bool addressed_player, - bool uids) { - log::assert_that(media_interface_ != nullptr, - "assert failed: media_interface_ != nullptr"); +void Device::SendFolderUpdate(bool available_players, bool addressed_player, bool uids) { + log::assert_that(media_interface_ != nullptr, "assert failed: media_interface_ != nullptr"); log::verbose(""); if (available_players) { @@ -1666,9 +1553,9 @@ void Device::HandleTrackUpdate() { return; } - media_interface_->GetNowPlayingList( - base::Bind(&Device::TrackChangedNotificationResponse, - weak_ptr_factory_.GetWeakPtr(), track_changed_.second, false)); + media_interface_->GetNowPlayingList(base::Bind(&Device::TrackChangedNotificationResponse, + weak_ptr_factory_.GetWeakPtr(), + track_changed_.second, false)); } void Device::HandlePlayStatusUpdate() { @@ -1678,9 +1565,9 @@ void Device::HandlePlayStatusUpdate() { return; } - media_interface_->GetPlayStatus(base::Bind( - &Device::PlaybackStatusNotificationResponse, - weak_ptr_factory_.GetWeakPtr(), play_status_changed_.second, false)); + media_interface_->GetPlayStatus(base::Bind(&Device::PlaybackStatusNotificationResponse, + weak_ptr_factory_.GetWeakPtr(), + play_status_changed_.second, false)); } void Device::HandleNowPlayingUpdate() { @@ -1691,9 +1578,9 @@ void Device::HandleNowPlayingUpdate() { return; } - media_interface_->GetNowPlayingList(base::Bind( - &Device::HandleNowPlayingNotificationResponse, - weak_ptr_factory_.GetWeakPtr(), now_playing_changed_.second, false)); + media_interface_->GetNowPlayingList(base::Bind(&Device::HandleNowPlayingNotificationResponse, + weak_ptr_factory_.GetWeakPtr(), + now_playing_changed_.second, false)); } void Device::HandlePlayerSettingChanged(std::vector attributes, @@ -1715,15 +1602,14 @@ void Device::HandlePlayerSettingChanged(std::vector attributes, } } - auto response = - RegisterNotificationResponseBuilder::MakePlayerSettingChangedBuilder( + auto response = RegisterNotificationResponseBuilder::MakePlayerSettingChangedBuilder( false, attributes, values); send_message(player_setting_changed_.second, false, std::move(response)); } -void Device::PlayerSettingChangedNotificationResponse( - uint8_t label, bool interim, std::vector attributes, - std::vector values) { +void Device::PlayerSettingChangedNotificationResponse(uint8_t label, bool interim, + std::vector attributes, + std::vector values) { log::verbose("interim: {}", interim); for (size_t i = 0; i < attributes.size(); i++) { log::verbose("attribute: {}", attributes[i]); @@ -1743,8 +1629,7 @@ void Device::PlayerSettingChangedNotificationResponse( return; } - auto response = - RegisterNotificationResponseBuilder::MakePlayerSettingChangedBuilder( + auto response = RegisterNotificationResponseBuilder::MakePlayerSettingChangedBuilder( interim, attributes, values); send_message(player_setting_changed_.second, false, std::move(response)); @@ -1754,9 +1639,9 @@ void Device::PlayerSettingChangedNotificationResponse( } } -void Device::HandleNowPlayingNotificationResponse( - uint8_t label, bool interim, std::string curr_song_id, - std::vector song_list) { +void Device::HandleNowPlayingNotificationResponse(uint8_t label, bool interim, + std::string curr_song_id, + std::vector song_list) { if (interim) { now_playing_changed_ = Notification(true, label); } else if (!now_playing_changed_.first) { @@ -1769,8 +1654,7 @@ void Device::HandleNowPlayingNotificationResponse( now_playing_ids_.insert(song.media_id); } - auto response = - RegisterNotificationResponseBuilder::MakeNowPlayingBuilder(interim); + auto response = RegisterNotificationResponseBuilder::MakeNowPlayingBuilder(interim); send_message(now_playing_changed_.second, false, std::move(response)); if (!interim) { @@ -1786,9 +1670,9 @@ void Device::HandlePlayPosUpdate() { return; } - media_interface_->GetPlayStatus(base::Bind( - &Device::PlaybackPosNotificationResponse, weak_ptr_factory_.GetWeakPtr(), - play_pos_changed_.second, false)); + media_interface_->GetPlayStatus(base::Bind(&Device::PlaybackPosNotificationResponse, + weak_ptr_factory_.GetWeakPtr(), + play_pos_changed_.second, false)); } void Device::HandleAvailablePlayerUpdate() { @@ -1799,10 +1683,8 @@ void Device::HandleAvailablePlayerUpdate() { return; } - auto response = - RegisterNotificationResponseBuilder::MakeAvailablePlayersBuilder(false); - send_message_cb_.Run(avail_players_changed_.second, false, - std::move(response)); + auto response = RegisterNotificationResponseBuilder::MakeAvailablePlayersBuilder(false); + send_message_cb_.Run(avail_players_changed_.second, false, std::move(response)); if (!avail_players_changed_.first) { active_labels_.erase(avail_players_changed_.second); @@ -1813,13 +1695,12 @@ void Device::HandleAvailablePlayerUpdate() { void Device::HandleAddressedPlayerUpdate() { log::verbose(""); if (!addr_player_changed_.first) { - log::warn("{}: Device is not registered for addressed player updates", - address_); + log::warn("{}: Device is not registered for addressed player updates", address_); return; } - media_interface_->GetMediaPlayerList(base::Bind( - &Device::AddressedPlayerNotificationResponse, - weak_ptr_factory_.GetWeakPtr(), addr_player_changed_.second, false)); + media_interface_->GetMediaPlayerList(base::Bind(&Device::AddressedPlayerNotificationResponse, + weak_ptr_factory_.GetWeakPtr(), + addr_player_changed_.second, false)); } void Device::DeviceDisconnected() { @@ -1828,8 +1709,9 @@ void Device::DeviceDisconnected() { // TODO (apanicke): Once the interfaces are set in the Device construction, // remove these conditionals. - if (volume_interface_ != nullptr) + if (volume_interface_ != nullptr) { volume_interface_->DeviceDisconnected(GetAddress()); + } // The volume at connection is set by the remote device when indicating // that it supports absolute volume, in case it's not, we need // to reset the local volume var to be sure we send the correct value @@ -1838,34 +1720,53 @@ void Device::DeviceDisconnected() { } static std::string volumeToStr(int8_t volume) { - if (volume == VOL_NOT_SUPPORTED) return "Absolute Volume not supported"; - if (volume == VOL_REGISTRATION_FAILED) + if (volume == VOL_NOT_SUPPORTED) { + return "Absolute Volume not supported"; + } + if (volume == VOL_REGISTRATION_FAILED) { return "Volume changed notification was rejected"; + } return std::to_string(volume); } std::ostream& operator<<(std::ostream& out, const Device& d) { // TODO: whether this should be turned into LOGGABLE STRING? out << " " << ADDRESS_TO_LOGGABLE_STR(d.address_); - if (d.IsActive()) out << " "; + if (d.IsActive()) { + out << " "; + } out << std::endl; out << " Current Volume: " << volumeToStr(d.volume_) << std::endl; - out << " Current Browsed Player ID: " << d.curr_browsed_player_id_ - << std::endl; + out << " Current Browsed Player ID: " << d.curr_browsed_player_id_ << std::endl; out << " Registered Notifications:\n"; - if (d.track_changed_.first) out << " Track Changed\n"; - if (d.play_status_changed_.first) out << " Play Status\n"; - if (d.play_pos_changed_.first) out << " Play Position\n"; - if (d.player_setting_changed_.first) out << " Player Setting Changed\n"; - if (d.now_playing_changed_.first) out << " Now Playing\n"; - if (d.addr_player_changed_.first) out << " Addressed Player\n"; - if (d.avail_players_changed_.first) out << " Available Players\n"; - if (d.uids_changed_.first) out << " UIDs Changed\n"; + if (d.track_changed_.first) { + out << " Track Changed\n"; + } + if (d.play_status_changed_.first) { + out << " Play Status\n"; + } + if (d.play_pos_changed_.first) { + out << " Play Position\n"; + } + if (d.player_setting_changed_.first) { + out << " Player Setting Changed\n"; + } + if (d.now_playing_changed_.first) { + out << " Now Playing\n"; + } + if (d.addr_player_changed_.first) { + out << " Addressed Player\n"; + } + if (d.avail_players_changed_.first) { + out << " Available Players\n"; + } + if (d.uids_changed_.first) { + out << " UIDs Changed\n"; + } out << " Last Play State: " << d.last_play_status_.state << std::endl; out << " Last Song Sent ID: \"" << d.last_song_info_.media_id << "\"\n"; out << " Current Folder: \"" << d.CurrentFolder() << "\"\n"; - out << " MTU Sizes: CTRL=" << d.ctrl_mtu_ << " BROWSE=" << d.browse_mtu_ - << std::endl; + out << " MTU Sizes: CTRL=" << d.ctrl_mtu_ << " BROWSE=" << d.browse_mtu_ << std::endl; // TODO (apanicke): Add supported features as well as media keys return out; } diff --git a/system/profile/avrcp/device.h b/system/profile/avrcp/device.h index 2d1ff3dfa77..1f965031728 100644 --- a/system/profile/avrcp/device.h +++ b/system/profile/avrcp/device.h @@ -57,7 +57,7 @@ namespace avrcp { // responders for Browse and Classic AVRCP Messages move the device around via a // weak pointer. class Device { - public: +public: /** * Device is friends with Avrcp::ConnectionHandler so that ConnectionHandler * can deliver messages to individual devices. @@ -65,10 +65,9 @@ class Device { friend class ConnectionHandler; Device(const RawAddress& bdaddr, bool avrcp13_compatibility, - base::RepeatingCallback< - void(uint8_t label, bool browse, - std::unique_ptr<::bluetooth::PacketBuilder> message)> - send_msg_cb, + base::RepeatingCallback message)> + send_msg_cb, uint16_t ctrl_mtu, uint16_t browse_mtu); Device(const Device&) = delete; @@ -82,7 +81,7 @@ class Device { */ base::WeakPtr Get(); - const RawAddress& GetAddress() const { return address_; }; + const RawAddress& GetAddress() const { return address_; } /** * Disconnects the AVRCP connection that this device represents. @@ -116,8 +115,7 @@ class Device { * is created valid and can't be accidentally interacted with when no * interfaces are registered. */ - void RegisterInterfaces(MediaInterface* interface, - A2dpInterface* a2dp_interface, + void RegisterInterfaces(MediaInterface* interface, A2dpInterface* a2dp_interface, VolumeInterface* volume_interface, PlayerSettingsInterface* player_settings_interface); @@ -139,8 +137,7 @@ class Device { * have updated via a boolean. Each boolean represents whether its respective * content has updated. */ - virtual void SendFolderUpdate(bool available_player, bool addressed_player, - bool uids); + virtual void SendFolderUpdate(bool available_player, bool addressed_player, bool uids); // TODO (apanicke): Split the message handlers into two files. One // for handling Browse Messages and the other for handling all other @@ -159,51 +156,49 @@ class Device { ********************/ // CURRENT TRACK CHANGED virtual void HandleTrackUpdate(); - virtual void TrackChangedNotificationResponse( - uint8_t label, bool interim, std::string curr_song_id, - std::vector song_list); + virtual void TrackChangedNotificationResponse(uint8_t label, bool interim, + std::string curr_song_id, + std::vector song_list); // GET CAPABILITY - virtual void HandleGetCapabilities( - uint8_t label, const std::shared_ptr& pkt); + virtual void HandleGetCapabilities(uint8_t label, + const std::shared_ptr& pkt); // REGISTER NOTIFICATION - virtual void HandleNotification( - uint8_t label, const std::shared_ptr& pkt); + virtual void HandleNotification(uint8_t label, + const std::shared_ptr& pkt); // PLAY STATUS CHANGED virtual void HandlePlayStatusUpdate(); // NOW PLAYING LIST CHANGED virtual void HandleNowPlayingUpdate(); - virtual void HandleNowPlayingNotificationResponse( - uint8_t label, bool interim, std::string curr_song_id, - std::vector song_list); + virtual void HandleNowPlayingNotificationResponse(uint8_t label, bool interim, + std::string curr_song_id, + std::vector song_list); // PLAY POSITION CHANGED virtual void HandlePlayPosUpdate(); - virtual void PlaybackPosNotificationResponse(uint8_t label, bool interim, - PlayStatus status); + virtual void PlaybackPosNotificationResponse(uint8_t label, bool interim, PlayStatus status); // GET PLAY STATUS virtual void GetPlayStatusResponse(uint8_t label, PlayStatus status); - virtual void PlaybackStatusNotificationResponse(uint8_t label, bool interim, - PlayStatus status); + virtual void PlaybackStatusNotificationResponse(uint8_t label, bool interim, PlayStatus status); // PLAYER APPLICATION SETTINGS CHANGED - virtual void HandlePlayerSettingChanged( - std::vector attributes, std::vector values); - virtual void PlayerSettingChangedNotificationResponse( - uint8_t label, bool interim, std::vector attributes, - std::vector values); + virtual void HandlePlayerSettingChanged(std::vector attributes, + std::vector values); + virtual void PlayerSettingChangedNotificationResponse(uint8_t label, bool interim, + std::vector attributes, + std::vector values); // GET ELEMENT ATTRIBUTE // TODO (apanicke): Add a Handler function for this so if a specific device // needs to implement an interop fix, you only need to overload the one // function. - virtual void GetElementAttributesResponse( - uint8_t label, std::shared_ptr pkt, - SongInfo info); + virtual void GetElementAttributesResponse(uint8_t label, + std::shared_ptr pkt, + SongInfo info); // AVAILABLE PLAYER CHANGED virtual void HandleAvailablePlayerUpdate(); @@ -211,82 +206,74 @@ class Device { // ADDRESSED PLAYER CHANGED virtual void HandleAddressedPlayerUpdate(); virtual void RejectNotification(); - virtual void AddressedPlayerNotificationResponse( - uint8_t label, bool interim, uint16_t curr_player, - std::vector /* unused */); + virtual void AddressedPlayerNotificationResponse(uint8_t label, bool interim, + uint16_t curr_player, + std::vector /* unused */); // GET FOLDER ITEMS - virtual void HandleGetFolderItems( - uint8_t label, std::shared_ptr request); - virtual void GetMediaPlayerListResponse( - uint8_t label, std::shared_ptr pkt, - uint16_t curr_player, std::vector players); - virtual void GetVFSListResponse(uint8_t label, - std::shared_ptr pkt, + virtual void HandleGetFolderItems(uint8_t label, std::shared_ptr request); + virtual void GetMediaPlayerListResponse(uint8_t label, std::shared_ptr pkt, + uint16_t curr_player, + std::vector players); + virtual void GetVFSListResponse(uint8_t label, std::shared_ptr pkt, std::vector items); - virtual void GetNowPlayingListResponse( - uint8_t label, std::shared_ptr pkt, - std::string curr_song_id, std::vector song_list); + virtual void GetNowPlayingListResponse(uint8_t label, std::shared_ptr pkt, + std::string curr_song_id, std::vector song_list); // GET TOTAL NUMBER OF ITEMS - virtual void HandleGetTotalNumberOfItems( - uint8_t label, std::shared_ptr pkt); - virtual void GetTotalNumberOfItemsMediaPlayersResponse( - uint8_t label, uint16_t curr_player, std::vector list); - virtual void GetTotalNumberOfItemsVFSResponse(uint8_t label, - std::vector items); - virtual void GetTotalNumberOfItemsNowPlayingResponse( - uint8_t label, std::string curr_song_id, std::vector song_list); + virtual void HandleGetTotalNumberOfItems(uint8_t label, + std::shared_ptr pkt); + virtual void GetTotalNumberOfItemsMediaPlayersResponse(uint8_t label, uint16_t curr_player, + std::vector list); + virtual void GetTotalNumberOfItemsVFSResponse(uint8_t label, std::vector items); + virtual void GetTotalNumberOfItemsNowPlayingResponse(uint8_t label, std::string curr_song_id, + std::vector song_list); // GET ITEM ATTRIBUTES - virtual void HandleGetItemAttributes( - uint8_t label, std::shared_ptr request); - virtual void GetItemAttributesNowPlayingResponse( - uint8_t label, std::shared_ptr pkt, - std::string curr_media_id, std::vector song_list); - virtual void GetItemAttributesVFSResponse( - uint8_t label, std::shared_ptr pkt, - std::vector item_list); + virtual void HandleGetItemAttributes(uint8_t label, + std::shared_ptr request); + virtual void GetItemAttributesNowPlayingResponse(uint8_t label, + std::shared_ptr pkt, + std::string curr_media_id, + std::vector song_list); + virtual void GetItemAttributesVFSResponse(uint8_t label, + std::shared_ptr pkt, + std::vector item_list); // SET BROWSED PLAYER - virtual void HandleSetBrowsedPlayer( - uint8_t label, std::shared_ptr request); - virtual void SetBrowsedPlayerResponse( - uint8_t label, std::shared_ptr pkt, bool success, - std::string root_id, uint32_t num_items); + virtual void HandleSetBrowsedPlayer(uint8_t label, + std::shared_ptr request); + virtual void SetBrowsedPlayerResponse(uint8_t label, std::shared_ptr pkt, + bool success, std::string root_id, uint32_t num_items); // CHANGE PATH - virtual void HandleChangePath(uint8_t label, - std::shared_ptr request); - virtual void ChangePathResponse(uint8_t label, - std::shared_ptr request, + virtual void HandleChangePath(uint8_t label, std::shared_ptr request); + virtual void ChangePathResponse(uint8_t label, std::shared_ptr request, std::vector list); // PLAY ITEM - virtual void HandlePlayItem(uint8_t label, - std::shared_ptr request); + virtual void HandlePlayItem(uint8_t label, std::shared_ptr request); // SET ADDRESSED PLAYER - virtual void HandleSetAddressedPlayer( - uint8_t label, std::shared_ptr request, - uint16_t curr_player, std::vector players); + virtual void HandleSetAddressedPlayer(uint8_t label, + std::shared_ptr request, + uint16_t curr_player, std::vector players); // LIST PLAYER APPLICATION SETTING ATTRIBUTES virtual void ListPlayerApplicationSettingAttributesResponse( - uint8_t label, std::vector attributes); + uint8_t label, std::vector attributes); // LIST PLAYER APPLICATION SETTING VALUES - virtual void ListPlayerApplicationSettingValuesResponse( - uint8_t label, PlayerAttribute setting, std::vector values); + virtual void ListPlayerApplicationSettingValuesResponse(uint8_t label, PlayerAttribute setting, + std::vector values); // GET CURRENT PLAYER APPLICATION SETTING VALUE - virtual void GetPlayerApplicationSettingValueResponse( - uint8_t label, std::vector attributes, - std::vector values); + virtual void GetPlayerApplicationSettingValueResponse(uint8_t label, + std::vector attributes, + std::vector values); // SET PLAYER APPLICATION SETTING VALUE - virtual void SetPlayerApplicationSettingValueResponse(uint8_t label, - CommandPdu pdu, + virtual void SetPlayerApplicationSettingValueResponse(uint8_t label, CommandPdu pdu, bool success); /******************** @@ -294,8 +281,8 @@ class Device { ********************/ // VOLUME CHANGED NOTIFICATION virtual void RegisterVolumeChanged(); - virtual void HandleVolumeChanged( - uint8_t label, const std::shared_ptr& pkt); + virtual void HandleVolumeChanged(uint8_t label, + const std::shared_ptr& pkt); // SET VOLUME virtual void SetVolume(int8_t volume); @@ -314,11 +301,13 @@ class Device { friend std::ostream& operator<<(std::ostream& out, const Device& c); - private: +private: // This should always contain one item which represents the root id on the // current player. std::string CurrentFolder() const { - if (current_path_.empty()) return ""; + if (current_path_.empty()) { + return ""; + } return current_path_.top(); } @@ -334,8 +323,7 @@ class Device { } bool find_sink_service(tA2DP_FIND_CBACK p_cback) const { - return a2dp_interface_->find_audio_sink_service(address_, p_cback) == - A2DP_SUCCESS; + return a2dp_interface_->find_audio_sink_service(address_, p_cback) == A2DP_SUCCESS; } base::WeakPtrFactory weak_ptr_factory_; @@ -346,10 +334,9 @@ class Device { // Enables AVRCP 1.3 Compatibility mode. This disables any AVRCP 1.4+ features // such as browsing and playlists but has the highest chance of working. bool avrcp13_compatibility_ = false; - base::RepeatingCallback message)> - send_message_cb_; + base::RepeatingCallback message)> + send_message_cb_; uint16_t ctrl_mtu_; uint16_t browse_mtu_; bool has_bip_client_; diff --git a/system/profile/avrcp/media_id_map.h b/system/profile/avrcp/media_id_map.h index f282f20d35a..7bc2bacae3b 100644 --- a/system/profile/avrcp/media_id_map.h +++ b/system/profile/avrcp/media_id_map.h @@ -25,7 +25,7 @@ namespace avrcp { // received from the AVRCP Media Interface layer into UID's to be used // with connected devices. class MediaIdMap { - public: +public: void clear() { media_id_to_uid_.clear(); uid_to_media_id_.clear(); @@ -33,13 +33,17 @@ class MediaIdMap { std::string get_media_id(uint64_t uid) { const auto& uid_it = uid_to_media_id_.find(uid); - if (uid_it == uid_to_media_id_.end()) return ""; + if (uid_it == uid_to_media_id_.end()) { + return ""; + } return uid_it->second; } uint64_t get_uid(std::string media_id) { const auto& media_id_it = media_id_to_uid_.find(media_id); - if (media_id_it == media_id_to_uid_.end()) return 0; + if (media_id_it == media_id_to_uid_.end()) { + return 0; + } return media_id_it->second; } @@ -54,7 +58,7 @@ class MediaIdMap { return uid; } - private: +private: std::map media_id_to_uid_; std::map uid_to_media_id_; }; diff --git a/system/profile/avrcp/tests/avrcp_connection_handler_test.cc b/system/profile/avrcp/tests/avrcp_connection_handler_test.cc index 7b3ea7bd226..68b43e75857 100644 --- a/system/profile/avrcp/tests/avrcp_connection_handler_test.cc +++ b/system/profile/avrcp/tests/avrcp_connection_handler_test.cc @@ -34,12 +34,8 @@ using ::testing::SaveArgPointee; using ::testing::SetArgPointee; using ::testing::StrictMock; -bool btif_av_peer_is_connected_sink(const RawAddress& peer_address) { - return true; -} -bool btif_av_peer_is_connected_source(const RawAddress& peer_address) { - return false; -} +bool btif_av_peer_is_connected_sink(const RawAddress& peer_address) { return true; } +bool btif_av_peer_is_connected_source(const RawAddress& peer_address) { return false; } bool btif_av_both_enable(void) { return false; } namespace bluetooth { @@ -48,43 +44,45 @@ namespace avrcp { using device_ptr = std::shared_ptr; class AvrcpConnectionHandlerTest : public testing::Test { - public: - void SetUp() override { - ON_CALL(mock_avrcp_, Close(_)).WillByDefault(Return(0)); - } +public: + void SetUp() override { ON_CALL(mock_avrcp_, Close(_)).WillByDefault(Return(0)); } void SetUpSdp(tAVRC_FIND_CBACK* sdp_cb, bool browsing, bool absolute_volume) { EXPECT_CALL(mock_avrcp_, FindService(_, _, _, _)) - .Times(1) - .WillOnce(DoAll(SaveArg<3>(sdp_cb), Return(0))); + .Times(1) + .WillOnce(DoAll(SaveArg<3>(sdp_cb), Return(0))); static tSDP_DISC_ATTR fake_features; fake_features = { - .p_next_attr = nullptr, - .attr_id = 0, - .attr_len_type = (UINT_DESC_TYPE<<12) | 2, - .attr_value = {.v = {.u16 = 0}}, + .p_next_attr = nullptr, + .attr_id = 0, + .attr_len_type = (UINT_DESC_TYPE << 12) | 2, + .attr_value = {.v = {.u16 = 0}}, }; - if (browsing) fake_features.attr_value.v.u16 |= AVRC_SUPF_CT_BROWSE; - if (absolute_volume) fake_features.attr_value.v.u16 |= AVRC_SUPF_CT_CAT2; + if (browsing) { + fake_features.attr_value.v.u16 |= AVRC_SUPF_CT_BROWSE; + } + if (absolute_volume) { + fake_features.attr_value.v.u16 |= AVRC_SUPF_CT_CAT2; + } EXPECT_CALL(mock_sdp_, FindAttributeInRec(_, _)) - .Times(4) - .WillRepeatedly(Return(&fake_features)); + .Times(4) + .WillRepeatedly(Return(&fake_features)); EXPECT_CALL(mock_sdp_, FindServiceInDb(_, _, _)) - .Times(2) - .WillOnce(Return((tSDP_DISC_REC*)0x01)) // Return any non null pointer - .WillOnce(Return((tSDP_DISC_REC*)0x01)); // Return any non null pointer + .Times(2) + .WillOnce(Return((tSDP_DISC_REC*)0x01)) // Return any non null pointer + .WillOnce(Return((tSDP_DISC_REC*)0x01)); // Return any non null pointer EXPECT_CALL(mock_sdp_, FindProfileVersionInRec(_, _, _)) - .Times(2) - .WillRepeatedly(DoAll(SetArgPointee<2>(AVRC_REV_1_6), Return(true))); + .Times(2) + .WillRepeatedly(DoAll(SetArgPointee<2>(AVRC_REV_1_6), Return(true))); } - protected: +protected: ConnectionHandler* connection_handler_ = nullptr; // We use NiceMock's here because each function of this code does quite a few @@ -101,14 +99,13 @@ TEST_F(AvrcpConnectionHandlerTest, initializeTest) { // connection callback once it is called tAVRC_CONN_CB conn_cb; EXPECT_CALL(mock_avrcp_, Open(_, _, RawAddress::kAny)) - .Times(1) - .WillOnce( - DoAll(SetArgPointee<0>(1), SaveArgPointee<1>(&conn_cb), Return(0))); - - auto bound_callback = base::BindRepeating( - &MockFunction::Call, base::Unretained(&device_cb)); - ASSERT_TRUE(ConnectionHandler::Initialize(bound_callback, &mock_avrcp_, - &mock_sdp_, &mock_volume_)); + .Times(1) + .WillOnce(DoAll(SetArgPointee<0>(1), SaveArgPointee<1>(&conn_cb), Return(0))); + + auto bound_callback = + base::BindRepeating(&MockFunction::Call, base::Unretained(&device_cb)); + ASSERT_TRUE( + ConnectionHandler::Initialize(bound_callback, &mock_avrcp_, &mock_sdp_, &mock_volume_)); connection_handler_ = ConnectionHandler::Get(); // Check that the callback was sent with us as the acceptor @@ -124,15 +121,14 @@ TEST_F(AvrcpConnectionHandlerTest, notConnectedDisconnectTest) { // the connection callback once it is called. tAVRC_CONN_CB conn_cb; EXPECT_CALL(mock_avrcp_, Open(_, _, RawAddress::kAny)) - .Times(1) - .WillOnce( - DoAll(SetArgPointee<0>(1), SaveArgPointee<1>(&conn_cb), Return(0))); + .Times(1) + .WillOnce(DoAll(SetArgPointee<0>(1), SaveArgPointee<1>(&conn_cb), Return(0))); // Initialize the interface - auto bound_callback = base::BindRepeating( - &MockFunction::Call, base::Unretained(&device_cb)); - ASSERT_TRUE(ConnectionHandler::Initialize(bound_callback, &mock_avrcp_, - &mock_sdp_, &mock_volume_)); + auto bound_callback = + base::BindRepeating(&MockFunction::Call, base::Unretained(&device_cb)); + ASSERT_TRUE( + ConnectionHandler::Initialize(bound_callback, &mock_avrcp_, &mock_sdp_, &mock_volume_)); connection_handler_ = ConnectionHandler::Get(); // Call the callback with a message saying the connection has closed @@ -140,7 +136,7 @@ TEST_F(AvrcpConnectionHandlerTest, notConnectedDisconnectTest) { connection_handler_ = nullptr; ConnectionHandler::CleanUp(); -}; +} // Test calling the connection callback after the handler is cleaned up TEST_F(AvrcpConnectionHandlerTest, disconnectAfterCleanupTest) { @@ -148,15 +144,14 @@ TEST_F(AvrcpConnectionHandlerTest, disconnectAfterCleanupTest) { // the connection callback once it is called. tAVRC_CONN_CB conn_cb; EXPECT_CALL(mock_avrcp_, Open(_, _, RawAddress::kAny)) - .Times(1) - .WillOnce( - DoAll(SetArgPointee<0>(1), SaveArgPointee<1>(&conn_cb), Return(0))); + .Times(1) + .WillOnce(DoAll(SetArgPointee<0>(1), SaveArgPointee<1>(&conn_cb), Return(0))); // Initialize the interface - auto bound_callback = base::BindRepeating( - &MockFunction::Call, base::Unretained(&device_cb)); - ASSERT_TRUE(ConnectionHandler::Initialize(bound_callback, &mock_avrcp_, - &mock_sdp_, &mock_volume_)); + auto bound_callback = + base::BindRepeating(&MockFunction::Call, base::Unretained(&device_cb)); + ASSERT_TRUE( + ConnectionHandler::Initialize(bound_callback, &mock_avrcp_, &mock_sdp_, &mock_volume_)); connection_handler_ = ConnectionHandler::Get(); connection_handler_ = nullptr; @@ -164,7 +159,7 @@ TEST_F(AvrcpConnectionHandlerTest, disconnectAfterCleanupTest) { // Call the callback with a message saying the connection has closed conn_cb.ctrl_cback.Run(1, AVRC_CLOSE_IND_EVT, 0, &RawAddress::kAny); -}; +} /** * Check that we can handle having a remote device connect to us, start SDP, and @@ -175,17 +170,15 @@ TEST_F(AvrcpConnectionHandlerTest, remoteDeviceConnectionTest) { // the connection callback once it is called. tAVRC_CONN_CB conn_cb; EXPECT_CALL(mock_avrcp_, Open(_, _, RawAddress::kAny)) - .Times(2) - .WillOnce( - DoAll(SetArgPointee<0>(1), SaveArgPointee<1>(&conn_cb), Return(0))) - .WillOnce( - DoAll(SetArgPointee<0>(2), SaveArgPointee<1>(&conn_cb), Return(0))); + .Times(2) + .WillOnce(DoAll(SetArgPointee<0>(1), SaveArgPointee<1>(&conn_cb), Return(0))) + .WillOnce(DoAll(SetArgPointee<0>(2), SaveArgPointee<1>(&conn_cb), Return(0))); // Initialize the interface - auto bound_callback = base::BindRepeating( - &MockFunction::Call, base::Unretained(&device_cb)); - ASSERT_TRUE(ConnectionHandler::Initialize(bound_callback, &mock_avrcp_, - &mock_sdp_, &mock_volume_)); + auto bound_callback = + base::BindRepeating(&MockFunction::Call, base::Unretained(&device_cb)); + ASSERT_TRUE( + ConnectionHandler::Initialize(bound_callback, &mock_avrcp_, &mock_sdp_, &mock_volume_)); connection_handler_ = ConnectionHandler::Get(); // Check that the callback was sent with us as the acceptor @@ -221,17 +214,15 @@ TEST_F(AvrcpConnectionHandlerTest, noAbsoluteVolumeTest) { // the connection callback once it is called. tAVRC_CONN_CB conn_cb; EXPECT_CALL(mock_avrcp_, Open(_, _, RawAddress::kAny)) - .Times(2) - .WillOnce( - DoAll(SetArgPointee<0>(1), SaveArgPointee<1>(&conn_cb), Return(0))) - .WillOnce( - DoAll(SetArgPointee<0>(2), SaveArgPointee<1>(&conn_cb), Return(0))); + .Times(2) + .WillOnce(DoAll(SetArgPointee<0>(1), SaveArgPointee<1>(&conn_cb), Return(0))) + .WillOnce(DoAll(SetArgPointee<0>(2), SaveArgPointee<1>(&conn_cb), Return(0))); // Initialize the interface - auto bound_callback = base::BindRepeating( - &MockFunction::Call, base::Unretained(&device_cb)); - ASSERT_TRUE(ConnectionHandler::Initialize(bound_callback, &mock_avrcp_, - &mock_sdp_, &mock_volume_)); + auto bound_callback = + base::BindRepeating(&MockFunction::Call, base::Unretained(&device_cb)); + ASSERT_TRUE( + ConnectionHandler::Initialize(bound_callback, &mock_avrcp_, &mock_sdp_, &mock_volume_)); connection_handler_ = ConnectionHandler::Get(); // Set an Expectations that SDP will be performed @@ -259,19 +250,17 @@ TEST_F(AvrcpConnectionHandlerTest, absoluteVolumeTest) { // the connection callback once it is called. tAVRC_CONN_CB conn_cb; EXPECT_CALL(mock_avrcp_, Open(_, _, RawAddress::kAny)) - .Times(2) - .WillOnce( - DoAll(SetArgPointee<0>(1), SaveArgPointee<1>(&conn_cb), Return(0))) - .WillOnce( - DoAll(SetArgPointee<0>(2), SaveArgPointee<1>(&conn_cb), Return(0))); + .Times(2) + .WillOnce(DoAll(SetArgPointee<0>(1), SaveArgPointee<1>(&conn_cb), Return(0))) + .WillOnce(DoAll(SetArgPointee<0>(2), SaveArgPointee<1>(&conn_cb), Return(0))); // Initialize the interface - auto bound_callback = base::BindRepeating( - &MockFunction::Call, base::Unretained(&device_cb)); + auto bound_callback = + base::BindRepeating(&MockFunction::Call, base::Unretained(&device_cb)); StrictMock strict_volume; - ASSERT_TRUE(ConnectionHandler::Initialize(bound_callback, &mock_avrcp_, - &mock_sdp_, &strict_volume)); + ASSERT_TRUE( + ConnectionHandler::Initialize(bound_callback, &mock_avrcp_, &mock_sdp_, &strict_volume)); connection_handler_ = ConnectionHandler::Get(); // Set an Expectations that SDP will be performed with absolute volume @@ -294,16 +283,15 @@ TEST_F(AvrcpConnectionHandlerTest, disconnectTest) { // the connection callback once it is called. tAVRC_CONN_CB conn_cb; EXPECT_CALL(mock_avrcp_, Open(_, _, RawAddress::kAny)) - .Times(2) - .WillOnce( - DoAll(SetArgPointee<0>(1), SaveArgPointee<1>(&conn_cb), Return(0))) - .WillOnce(DoAll(SetArgPointee<0>(2), Return(0))); + .Times(2) + .WillOnce(DoAll(SetArgPointee<0>(1), SaveArgPointee<1>(&conn_cb), Return(0))) + .WillOnce(DoAll(SetArgPointee<0>(2), Return(0))); // Initialize the interface - auto bound_callback = base::BindRepeating( - &MockFunction::Call, base::Unretained(&device_cb)); - ASSERT_TRUE(ConnectionHandler::Initialize(bound_callback, &mock_avrcp_, - &mock_sdp_, &mock_volume_)); + auto bound_callback = + base::BindRepeating(&MockFunction::Call, base::Unretained(&device_cb)); + ASSERT_TRUE( + ConnectionHandler::Initialize(bound_callback, &mock_avrcp_, &mock_sdp_, &mock_volume_)); connection_handler_ = ConnectionHandler::Get(); // Call the callback with a message saying that a remote device has connected @@ -329,19 +317,16 @@ TEST_F(AvrcpConnectionHandlerTest, multipleRemoteDeviceConnectionTest) { // save the connection callback once it is called. tAVRC_CONN_CB conn_cb; EXPECT_CALL(mock_avrcp_, Open(_, _, RawAddress::kAny)) - .Times(3) - .WillOnce( - DoAll(SetArgPointee<0>(1), SaveArgPointee<1>(&conn_cb), Return(0))) - .WillOnce( - DoAll(SetArgPointee<0>(2), SaveArgPointee<1>(&conn_cb), Return(0))) - .WillOnce( - DoAll(SetArgPointee<0>(3), SaveArgPointee<1>(&conn_cb), Return(0))); + .Times(3) + .WillOnce(DoAll(SetArgPointee<0>(1), SaveArgPointee<1>(&conn_cb), Return(0))) + .WillOnce(DoAll(SetArgPointee<0>(2), SaveArgPointee<1>(&conn_cb), Return(0))) + .WillOnce(DoAll(SetArgPointee<0>(3), SaveArgPointee<1>(&conn_cb), Return(0))); // Initialize the interface - auto bound_callback = base::BindRepeating( - &MockFunction::Call, base::Unretained(&device_cb)); - ASSERT_TRUE(ConnectionHandler::Initialize(bound_callback, &mock_avrcp_, - &mock_sdp_, &mock_volume_)); + auto bound_callback = + base::BindRepeating(&MockFunction::Call, base::Unretained(&device_cb)); + ASSERT_TRUE( + ConnectionHandler::Initialize(bound_callback, &mock_avrcp_, &mock_sdp_, &mock_volume_)); connection_handler_ = ConnectionHandler::Get(); // Check that the callback was sent with us as the acceptor @@ -389,18 +374,15 @@ TEST_F(AvrcpConnectionHandlerTest, cleanupTest) { // Set Up Expectations for Initialize tAVRC_CONN_CB conn_cb; EXPECT_CALL(mock_avrcp_, Open(_, _, _)) - .WillOnce( - DoAll(SetArgPointee<0>(1), SaveArgPointee<1>(&conn_cb), Return(0))) - .WillOnce( - DoAll(SetArgPointee<0>(2), SaveArgPointee<1>(&conn_cb), Return(0))) - .WillOnce( - DoAll(SetArgPointee<0>(3), SaveArgPointee<1>(&conn_cb), Return(0))); + .WillOnce(DoAll(SetArgPointee<0>(1), SaveArgPointee<1>(&conn_cb), Return(0))) + .WillOnce(DoAll(SetArgPointee<0>(2), SaveArgPointee<1>(&conn_cb), Return(0))) + .WillOnce(DoAll(SetArgPointee<0>(3), SaveArgPointee<1>(&conn_cb), Return(0))); // Initialize the interface - auto bound_callback = base::BindRepeating( - &MockFunction::Call, base::Unretained(&device_cb)); - ASSERT_TRUE(ConnectionHandler::Initialize(bound_callback, &mock_avrcp_, - &mock_sdp_, &mock_volume_)); + auto bound_callback = + base::BindRepeating(&MockFunction::Call, base::Unretained(&device_cb)); + ASSERT_TRUE( + ConnectionHandler::Initialize(bound_callback, &mock_avrcp_, &mock_sdp_, &mock_volume_)); connection_handler_ = ConnectionHandler::Get(); // Call the callback twice with a message saying that a remote device has @@ -419,10 +401,10 @@ TEST_F(AvrcpConnectionHandlerTest, cleanupTest) { TEST_F(AvrcpConnectionHandlerTest, connectToRemoteDeviceTest) { // Initialize the interface - auto bound_callback = base::BindRepeating( - &MockFunction::Call, base::Unretained(&device_cb)); - ASSERT_TRUE(ConnectionHandler::Initialize(bound_callback, &mock_avrcp_, - &mock_sdp_, &mock_volume_)); + auto bound_callback = + base::BindRepeating(&MockFunction::Call, base::Unretained(&device_cb)); + ASSERT_TRUE( + ConnectionHandler::Initialize(bound_callback, &mock_avrcp_, &mock_sdp_, &mock_volume_)); connection_handler_ = ConnectionHandler::Get(); // Set an Expectation that SDP will be performed @@ -436,9 +418,8 @@ TEST_F(AvrcpConnectionHandlerTest, connectToRemoteDeviceTest) { // after doing SDP tAVRC_CONN_CB conn_cb; EXPECT_CALL(mock_avrcp_, Open(_, _, RawAddress::kEmpty)) - .Times(1) - .WillOnce( - DoAll(SetArgPointee<0>(1), SaveArgPointee<1>(&conn_cb), Return(0))); + .Times(1) + .WillOnce(DoAll(SetArgPointee<0>(1), SaveArgPointee<1>(&conn_cb), Return(0))); // Complete SDP sdp_cb.Run(0); @@ -464,10 +445,10 @@ TEST_F(AvrcpConnectionHandlerTest, connectToRemoteDeviceTest) { TEST_F(AvrcpConnectionHandlerTest, connectToBrowsableRemoteDeviceTest) { // Initialize the interface - auto bound_callback = base::BindRepeating( - &MockFunction::Call, base::Unretained(&device_cb)); - ASSERT_TRUE(ConnectionHandler::Initialize(bound_callback, &mock_avrcp_, - &mock_sdp_, &mock_volume_)); + auto bound_callback = + base::BindRepeating(&MockFunction::Call, base::Unretained(&device_cb)); + ASSERT_TRUE( + ConnectionHandler::Initialize(bound_callback, &mock_avrcp_, &mock_sdp_, &mock_volume_)); connection_handler_ = ConnectionHandler::Get(); // Set an Expectation that SDP will be performed @@ -481,9 +462,8 @@ TEST_F(AvrcpConnectionHandlerTest, connectToBrowsableRemoteDeviceTest) { // after doing SDP tAVRC_CONN_CB conn_cb; EXPECT_CALL(mock_avrcp_, Open(_, _, RawAddress::kEmpty)) - .Times(1) - .WillOnce( - DoAll(SetArgPointee<0>(1), SaveArgPointee<1>(&conn_cb), Return(0))); + .Times(1) + .WillOnce(DoAll(SetArgPointee<0>(1), SaveArgPointee<1>(&conn_cb), Return(0))); // Complete SDP sdp_cb.Run(0); @@ -512,16 +492,15 @@ TEST_F(AvrcpConnectionHandlerTest, disconnectWhileDoingSdpTest) { // the connection callback once it is called. tAVRC_CONN_CB conn_cb; EXPECT_CALL(mock_avrcp_, Open(_, _, RawAddress::kAny)) - .Times(2) - .WillOnce( - DoAll(SetArgPointee<0>(1), SaveArgPointee<1>(&conn_cb), Return(0))) - .WillOnce(DoAll(SetArgPointee<0>(2), Return(0))); + .Times(2) + .WillOnce(DoAll(SetArgPointee<0>(1), SaveArgPointee<1>(&conn_cb), Return(0))) + .WillOnce(DoAll(SetArgPointee<0>(2), Return(0))); // Initialize the interface - auto bound_callback = base::BindRepeating( - &MockFunction::Call, base::Unretained(&device_cb)); - ASSERT_TRUE(ConnectionHandler::Initialize(bound_callback, &mock_avrcp_, - &mock_sdp_, &mock_volume_)); + auto bound_callback = + base::BindRepeating(&MockFunction::Call, base::Unretained(&device_cb)); + ASSERT_TRUE( + ConnectionHandler::Initialize(bound_callback, &mock_avrcp_, &mock_sdp_, &mock_volume_)); connection_handler_ = ConnectionHandler::Get(); // Set an Expectation that SDP will be performed @@ -549,17 +528,15 @@ TEST_F(AvrcpConnectionHandlerTest, disconnectWhileDoingSdpTest) { TEST_F(AvrcpConnectionHandlerTest, connectionCollisionTest) { tAVRC_CONN_CB conn_cb; EXPECT_CALL(mock_avrcp_, Open(_, _, RawAddress::kAny)) - .Times(2) - .WillOnce( - DoAll(SetArgPointee<0>(1), SaveArgPointee<1>(&conn_cb), Return(0))) - .WillOnce( - DoAll(SetArgPointee<0>(2), SaveArgPointee<1>(&conn_cb), Return(0))); + .Times(2) + .WillOnce(DoAll(SetArgPointee<0>(1), SaveArgPointee<1>(&conn_cb), Return(0))) + .WillOnce(DoAll(SetArgPointee<0>(2), SaveArgPointee<1>(&conn_cb), Return(0))); // Initialize the interface - auto bound_callback = base::BindRepeating( - &MockFunction::Call, base::Unretained(&device_cb)); - ASSERT_TRUE(ConnectionHandler::Initialize(bound_callback, &mock_avrcp_, - &mock_sdp_, &mock_volume_)); + auto bound_callback = + base::BindRepeating(&MockFunction::Call, base::Unretained(&device_cb)); + ASSERT_TRUE( + ConnectionHandler::Initialize(bound_callback, &mock_avrcp_, &mock_sdp_, &mock_volume_)); connection_handler_ = ConnectionHandler::Get(); // Check that the callback was sent with us as the acceptor @@ -576,8 +553,8 @@ TEST_F(AvrcpConnectionHandlerTest, connectionCollisionTest) { // Set an Expectations that SDP search will be performed again but will fail EXPECT_CALL(mock_avrcp_, FindService(_, _, _, _)) - .Times(1) - .WillOnce(DoAll(SaveArg<3>(&sdp_cb), Return(1))); + .Times(1) + .WillOnce(DoAll(SaveArg<3>(&sdp_cb), Return(1))); // Set an expectation that the incoming connection will be closed EXPECT_CALL(mock_avrcp_, Close(1)); @@ -604,17 +581,15 @@ TEST_F(AvrcpConnectionHandlerTest, acceptorSdpSearchFailTest) { // save the connection callback once it is called. tAVRC_CONN_CB conn_cb; EXPECT_CALL(mock_avrcp_, Open(_, _, RawAddress::kAny)) - .Times(2) - .WillOnce( - DoAll(SetArgPointee<0>(1), SaveArgPointee<1>(&conn_cb), Return(0))) - .WillOnce( - DoAll(SetArgPointee<0>(2), SaveArgPointee<1>(&conn_cb), Return(0))); + .Times(2) + .WillOnce(DoAll(SetArgPointee<0>(1), SaveArgPointee<1>(&conn_cb), Return(0))) + .WillOnce(DoAll(SetArgPointee<0>(2), SaveArgPointee<1>(&conn_cb), Return(0))); // Initialize the interface - auto bound_callback = base::BindRepeating( - &MockFunction::Call, base::Unretained(&device_cb)); - ASSERT_TRUE(ConnectionHandler::Initialize(bound_callback, &mock_avrcp_, - &mock_sdp_, &mock_volume_)); + auto bound_callback = + base::BindRepeating(&MockFunction::Call, base::Unretained(&device_cb)); + ASSERT_TRUE( + ConnectionHandler::Initialize(bound_callback, &mock_avrcp_, &mock_sdp_, &mock_volume_)); connection_handler_ = ConnectionHandler::Get(); // Check that the callback was sent with us as the acceptor @@ -626,8 +601,8 @@ TEST_F(AvrcpConnectionHandlerTest, acceptorSdpSearchFailTest) { // Set an expectation that SDP search will be performed but will fail tAVRC_FIND_CBACK sdp_cb; EXPECT_CALL(mock_avrcp_, FindService(_, _, _, _)) - .Times(1) - .WillOnce(DoAll(SaveArg<3>(&sdp_cb), Return(1))); + .Times(1) + .WillOnce(DoAll(SaveArg<3>(&sdp_cb), Return(1))); // Set an expectation that the incoming connection will be closed EXPECT_CALL(mock_avrcp_, Close(1)); diff --git a/system/profile/avrcp/tests/avrcp_device_fuzz/avrcp_device_fuzz.cc b/system/profile/avrcp/tests/avrcp_device_fuzz/avrcp_device_fuzz.cc index 32de7223266..1ec4719ab20 100644 --- a/system/profile/avrcp/tests/avrcp_device_fuzz/avrcp_device_fuzz.cc +++ b/system/profile/avrcp/tests/avrcp_device_fuzz/avrcp_device_fuzz.cc @@ -35,13 +35,12 @@ static uint8_t kMediaOpId = 0x44; static uint8_t kMask = 0xFF; static uint8_t k8BitShift = 8; -const Opcode kValidOpCodes[] = {Opcode::VENDOR, Opcode::UNIT_INFO, - Opcode::SUBUNIT_INFO, Opcode::PASS_THROUGH}; +const Opcode kValidOpCodes[] = {Opcode::VENDOR, Opcode::UNIT_INFO, Opcode::SUBUNIT_INFO, + Opcode::PASS_THROUGH}; -const CType kValidCTypes[] = { - CType::CONTROL, CType::STATUS, CType::NOTIFY, - CType::NOT_IMPLEMENTED, CType::ACCEPTED, CType::REJECTED, - CType::STABLE, CType::CHANGED, CType::INTERIM}; +const CType kValidCTypes[] = {CType::CONTROL, CType::STATUS, CType::NOTIFY, + CType::NOT_IMPLEMENTED, CType::ACCEPTED, CType::REJECTED, + CType::STABLE, CType::CHANGED, CType::INTERIM}; const BrowsePdu kPduVal[] = {BrowsePdu::SET_BROWSED_PLAYER, BrowsePdu::GET_FOLDER_ITEMS, @@ -50,21 +49,20 @@ const BrowsePdu kPduVal[] = {BrowsePdu::SET_BROWSED_PLAYER, BrowsePdu::GET_TOTAL_NUMBER_OF_ITEMS, BrowsePdu::GENERAL_REJECT}; -const CommandPdu kCommandPduVal[] = { - CommandPdu::GET_CAPABILITIES, - CommandPdu::LIST_PLAYER_APPLICATION_SETTING_ATTRIBUTES, - CommandPdu::LIST_PLAYER_APPLICATION_SETTING_VALUES, - CommandPdu::GET_CURRENT_PLAYER_APPLICATION_SETTING_VALUE, - CommandPdu::SET_PLAYER_APPLICATION_SETTING_VALUE, - CommandPdu::GET_ELEMENT_ATTRIBUTES, - CommandPdu::GET_PLAY_STATUS, - CommandPdu::REGISTER_NOTIFICATION, - CommandPdu::SET_ABSOLUTE_VOLUME, - CommandPdu::SET_ADDRESSED_PLAYER, - CommandPdu::PLAY_ITEM}; +const CommandPdu kCommandPduVal[] = {CommandPdu::GET_CAPABILITIES, + CommandPdu::LIST_PLAYER_APPLICATION_SETTING_ATTRIBUTES, + CommandPdu::LIST_PLAYER_APPLICATION_SETTING_VALUES, + CommandPdu::GET_CURRENT_PLAYER_APPLICATION_SETTING_VALUE, + CommandPdu::SET_PLAYER_APPLICATION_SETTING_VALUE, + CommandPdu::GET_ELEMENT_ATTRIBUTES, + CommandPdu::GET_PLAY_STATUS, + CommandPdu::REGISTER_NOTIFICATION, + CommandPdu::SET_ABSOLUTE_VOLUME, + CommandPdu::SET_ADDRESSED_PLAYER, + CommandPdu::PLAY_ITEM}; class FakeMediaInterface : public MediaInterface { - public: +public: FakeMediaInterface(FuzzedDataProvider* fdp) : mFdp(fdp) {} void SendKeyEvent(uint8_t /* key */, KeyState /* state */) { return; } using SongInfoCallback = base::Callback; @@ -72,9 +70,9 @@ class FakeMediaInterface : public MediaInterface { SongInfo sInfo; sInfo.media_id = mFdp->ConsumeRandomLengthString(kMaxLen); sInfo.attributes.insert(AttributeEntry( - Attribute(mFdp->ConsumeIntegralInRange( - uint8_t(Attribute::TITLE), uint8_t(Attribute::DEFAULT_COVER_ART))), - mFdp->ConsumeRandomLengthString(kMaxLen))); + Attribute(mFdp->ConsumeIntegralInRange(uint8_t(Attribute::TITLE), + uint8_t(Attribute::DEFAULT_COVER_ART))), + mFdp->ConsumeRandomLengthString(kMaxLen))); info_cb.Run(sInfo); return; } @@ -84,8 +82,7 @@ class FakeMediaInterface : public MediaInterface { status_cb.Run(pst); return; } - using NowPlayingCallback = - base::Callback)>; + using NowPlayingCallback = base::Callback)>; void GetNowPlayingList(NowPlayingCallback now_playing_cb) { std::string currentSongId = mFdp->ConsumeRandomLengthString(kMaxLen); size_t size = mFdp->ConsumeIntegralInRange(kMinSize, kMaxSize); @@ -93,18 +90,17 @@ class FakeMediaInterface : public MediaInterface { for (size_t iter = 0; iter < size; ++iter) { SongInfo tempSongInfo; tempSongInfo.media_id = mFdp->ConsumeRandomLengthString(kMaxLen); - tempSongInfo.attributes.insert( - AttributeEntry(Attribute(mFdp->ConsumeIntegralInRange( - uint8_t(Attribute::TITLE), - uint8_t(Attribute::DEFAULT_COVER_ART))), - mFdp->ConsumeRandomLengthString(kMaxLen))); + tempSongInfo.attributes.insert(AttributeEntry( + Attribute(mFdp->ConsumeIntegralInRange( + uint8_t(Attribute::TITLE), uint8_t(Attribute::DEFAULT_COVER_ART))), + mFdp->ConsumeRandomLengthString(kMaxLen))); songInfoVec.push_back(tempSongInfo); } now_playing_cb.Run(currentSongId, songInfoVec); return; } using MediaListCallback = - base::Callback)>; + base::Callback)>; void GetMediaPlayerList(MediaListCallback list_cb) { uint16_t currentPlayer = mFdp->ConsumeIntegral(); size_t size = mFdp->ConsumeIntegralInRange(kMinSize, kMaxSize); @@ -131,38 +127,35 @@ class FakeMediaInterface : public MediaInterface { tempList.folder.name = mFdp->ConsumeRandomLengthString(kMaxLen); tempList.folder.is_playable = mFdp->ConsumeBool(); tempList.song.media_id = mFdp->ConsumeRandomLengthString(kMaxLen); - tempList.song.attributes.insert( - AttributeEntry(Attribute(mFdp->ConsumeIntegralInRange( - uint8_t(Attribute::TITLE), - uint8_t(Attribute::DEFAULT_COVER_ART))), - mFdp->ConsumeRandomLengthString(kMaxLen))); + tempList.song.attributes.insert(AttributeEntry( + Attribute(mFdp->ConsumeIntegralInRange( + uint8_t(Attribute::TITLE), uint8_t(Attribute::DEFAULT_COVER_ART))), + mFdp->ConsumeRandomLengthString(kMaxLen))); list.push_back(tempList); } folder_cb.Run(list); } - using SetBrowsedPlayerCallback = base::Callback; - void SetBrowsedPlayer(uint16_t player_id, - SetBrowsedPlayerCallback browse_cb) { + using SetBrowsedPlayerCallback = + base::Callback; + void SetBrowsedPlayer(uint16_t player_id, SetBrowsedPlayerCallback browse_cb) { std::string rootId = mFdp->ConsumeRandomLengthString(kMaxLen); uint32_t numItems = mFdp->ConsumeIntegral(); browse_cb.Run(player_id, rootId, numItems); return; } - void PlayItem(uint16_t /* player_id */, bool /* now_playing */, - std::string /* media_id */) { + void PlayItem(uint16_t /* player_id */, bool /* now_playing */, std::string /* media_id */) { return; } void SetActiveDevice(const RawAddress& /* address */) { return; } void RegisterUpdateCallback(MediaCallbacks* /* callback */) { return; } void UnregisterUpdateCallback(MediaCallbacks* /* callback */) { return; } - private: +private: FuzzedDataProvider* mFdp; }; class FakeVolumeInterface : public VolumeInterface { - public: +public: FakeVolumeInterface(FuzzedDataProvider* fdp) : mFdp(fdp) {} void DeviceConnected(const RawAddress& /* bdaddr */) { return; } void DeviceConnected(const RawAddress& /* bdaddr */, VolumeChangedCb cb) { @@ -173,29 +166,26 @@ class FakeVolumeInterface : public VolumeInterface { void DeviceDisconnected(const RawAddress& /* bdaddr */) { return; } void SetVolume(int8_t /* volume */) { return; } - private: +private: FuzzedDataProvider* mFdp; }; class FakePlayerSettingsInterface : public PlayerSettingsInterface { - public: +public: FakePlayerSettingsInterface(FuzzedDataProvider* fdp) : mFdp(fdp) {} void ListPlayerSettings(ListPlayerSettingsCallback cb) { uint8_t label = mFdp->ConsumeIntegral(); size_t size = mFdp->ConsumeIntegralInRange(kMinSize, kMaxSize); std::vector attributes; for (size_t iter = 0; iter < size; ++iter) { - PlayerAttribute playerAttr = - (PlayerAttribute)mFdp->ConsumeIntegralInRange( - uint8_t(PlayerAttribute::EQUALIZER), - uint8_t(PlayerAttribute::SCAN)); + PlayerAttribute playerAttr = (PlayerAttribute)mFdp->ConsumeIntegralInRange( + uint8_t(PlayerAttribute::EQUALIZER), uint8_t(PlayerAttribute::SCAN)); attributes.push_back(playerAttr); } cb.Run(attributes); return; } - void ListPlayerSettingValues(PlayerAttribute setting, - ListPlayerSettingValuesCallback cb) { + void ListPlayerSettingValues(PlayerAttribute setting, ListPlayerSettingValuesCallback cb) { size_t size = mFdp->ConsumeIntegralInRange(kMinSize, kMaxSize); std::vector values = mFdp->ConsumeBytes(size); cb.Run(setting, values); @@ -211,25 +201,21 @@ class FakePlayerSettingsInterface : public PlayerSettingsInterface { return; } void SetPlayerSettings(std::vector /* attributes */, - std::vector /* values */, - SetPlayerSettingValueCallback cb) { + std::vector /* values */, SetPlayerSettingValueCallback cb) { bool success = mFdp->ConsumeBool(); cb.Run(success); return; } - private: +private: FuzzedDataProvider* mFdp; }; class FakeA2dpInterface : public A2dpInterface { - public: +public: RawAddress active_peer() { return RawAddress::kAny; } - bool is_peer_in_silence_mode(const RawAddress& /* peer_address */) { - return false; - } - void connect_audio_sink_delayed(uint8_t /* handle */, - const RawAddress& /* peer_address */) { + bool is_peer_in_silence_mode(const RawAddress& /* peer_address */) { return false; } + void connect_audio_sink_delayed(uint8_t /* handle */, const RawAddress& /* peer_address */) { return; } uint16_t find_audio_sink_service(const RawAddress& /* peer_address */, @@ -266,11 +252,11 @@ const stack_config_t interface = {get_pts_avrcp_test, void Callback(uint8_t, bool, std::unique_ptr<::bluetooth::PacketBuilder>) {} class AVRCPDeviceFuzzer { - public: +public: AVRCPDeviceFuzzer(const uint8_t* Data, size_t Size) : mFdp(Data, Size) {} void Process(); - private: +private: void CreateBrowsePacket(std::vector& packet); void CreateAvrcpPacket(std::vector& packet); FuzzedDataProvider mFdp; @@ -280,8 +266,8 @@ void AVRCPDeviceFuzzer::CreateBrowsePacket(std::vector& packet) { // Used to consume a maximum of 50% of the data to create packet. // This ensures that we don't completely exhaust data and use the rest 50% for // fuzzing of APIs. - packet = mFdp.ConsumeBytes(mFdp.ConsumeIntegralInRange( - 0, mFdp.remaining_bytes() * 50 / 100)); + packet = mFdp.ConsumeBytes( + mFdp.ConsumeIntegralInRange(0, mFdp.remaining_bytes() * 50 / 100)); if (packet.size() < Packet::kMinSize()) { packet.resize(Packet::kMinSize()); @@ -297,8 +283,8 @@ void AVRCPDeviceFuzzer::CreateAvrcpPacket(std::vector& packet) { // Used to consume a maximum of 50% of the data to create packet. // This ensures that we don't completely exhaust data and use the rest 50% for // fuzzing of APIs. - packet = mFdp.ConsumeBytes(mFdp.ConsumeIntegralInRange( - 0, mFdp.remaining_bytes() * 50 / 100)); + packet = mFdp.ConsumeBytes( + mFdp.ConsumeIntegralInRange(0, mFdp.remaining_bytes() * 50 / 100)); if (packet.size() < Packet::kMinSize()) { packet.resize(Packet::kMinSize()); } @@ -306,8 +292,7 @@ void AVRCPDeviceFuzzer::CreateAvrcpPacket(std::vector& packet) { packet[2] = (uint8_t)mFdp.PickValueInArray(kValidOpCodes); if (packet[2] == uint8_t(Opcode::PASS_THROUGH)) { packet.resize(PassThroughPacket::kMinSize()); - packet[3] = - mFdp.ConsumeBool() ? kMediaOpId : mFdp.ConsumeIntegral(); + packet[3] = mFdp.ConsumeBool() ? kMediaOpId : mFdp.ConsumeIntegral(); } else if (packet[2] == uint8_t(Opcode::VENDOR)) { if (packet.size() <= VendorPacket::kMinSize()) { packet.resize(VendorPacket::kMinSize() + 1); @@ -327,53 +312,42 @@ void AVRCPDeviceFuzzer::Process() { FakeA2dpInterface fai; FakePlayerSettingsInterface fpsi(&mFdp); - Device device( - RawAddress::kAny /* bdaddr */, - mFdp.ConsumeBool() /* avrcp13_compatibility */, - base::BindRepeating( - [](uint8_t, bool, std::unique_ptr<::bluetooth::PacketBuilder>) { - }) /* send_msg_cb */, - mFdp.ConsumeIntegral() /* ctrl_mtu */, - mFdp.ConsumeIntegral() /* browse_mtu */); + Device device(RawAddress::kAny /* bdaddr */, mFdp.ConsumeBool() /* avrcp13_compatibility */, + base::BindRepeating([](uint8_t, bool, std::unique_ptr<::bluetooth::PacketBuilder>) { + }) /* send_msg_cb */, + mFdp.ConsumeIntegral() /* ctrl_mtu */, + mFdp.ConsumeIntegral() /* browse_mtu */); device.RegisterInterfaces(&fmi, &fai, &fvi, &fpsi); while (mFdp.remaining_bytes()) { auto invokeAVRCP = mFdp.PickValueInArray>({ - [&]() { - device.SetBrowseMtu( - mFdp.ConsumeIntegral() /* browse_mtu */); - }, - [&]() { - device.SetBipClientStatus(mFdp.ConsumeBool() /* connected */); - }, - [&]() { - std::vector browse_packet; - CreateBrowsePacket(browse_packet); - auto browse_request = - TestPacketType::Make(browse_packet); - device.BrowseMessageReceived( - mFdp.ConsumeIntegral() /* label */, browse_request); - }, - [&]() { - /* Crafting PassThroughPacket Packets */ - std::vector avrcp_packet; - CreateAvrcpPacket(avrcp_packet); - auto avrcp_request = - TestPacketType::Make(avrcp_packet); - device.MessageReceived(mFdp.ConsumeIntegral() /* label */, - avrcp_request); - }, - [&]() { - device.SendMediaUpdate(mFdp.ConsumeBool() /* metadata */, - mFdp.ConsumeBool() /* play_status */, - mFdp.ConsumeBool() /* queue */); - }, - [&]() { - device.SendFolderUpdate(mFdp.ConsumeBool() /* available_players */, - mFdp.ConsumeBool() /* addressed_player */, - mFdp.ConsumeBool() /* uids */); - }, + [&]() { device.SetBrowseMtu(mFdp.ConsumeIntegral() /* browse_mtu */); }, + [&]() { device.SetBipClientStatus(mFdp.ConsumeBool() /* connected */); }, + [&]() { + std::vector browse_packet; + CreateBrowsePacket(browse_packet); + auto browse_request = TestPacketType::Make(browse_packet); + device.BrowseMessageReceived(mFdp.ConsumeIntegral() /* label */, + browse_request); + }, + [&]() { + /* Crafting PassThroughPacket Packets */ + std::vector avrcp_packet; + CreateAvrcpPacket(avrcp_packet); + auto avrcp_request = TestPacketType::Make(avrcp_packet); + device.MessageReceived(mFdp.ConsumeIntegral() /* label */, avrcp_request); + }, + [&]() { + device.SendMediaUpdate(mFdp.ConsumeBool() /* metadata */, + mFdp.ConsumeBool() /* play_status */, + mFdp.ConsumeBool() /* queue */); + }, + [&]() { + device.SendFolderUpdate(mFdp.ConsumeBool() /* available_players */, + mFdp.ConsumeBool() /* addressed_player */, + mFdp.ConsumeBool() /* uids */); + }, }); invokeAVRCP(); } @@ -388,6 +362,4 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* Data, size_t Size) { } // namespace avrcp } // namespace bluetooth -const stack_config_t* stack_config_get_interface(void) { - return &bluetooth::avrcp::interface; -} +const stack_config_t* stack_config_get_interface(void) { return &bluetooth::avrcp::interface; } diff --git a/system/profile/avrcp/tests/avrcp_device_test.cc b/system/profile/avrcp/tests/avrcp_device_test.cc index 52672baa59c..997096ca591 100644 --- a/system/profile/avrcp/tests/avrcp_device_test.cc +++ b/system/profile/avrcp/tests/avrcp_device_test.cc @@ -77,16 +77,15 @@ const stack_config_t interface = {get_pts_avrcp_test, // TODO (apanicke): All the tests below are just basic positive unit tests. // Add more tests to increase code coverage. class AvrcpDeviceTest : public ::testing::Test { - public: +public: void SetUp() override { // NOTE: We use a wrapper lambda for the MockFunction in order to // add a const qualifier to the response. Otherwise the MockFunction // type doesn't match the callback type and a compiler error occurs. base::RepeatingCallback cb = - base::BindRepeating( - [](MockFunction* a, - uint8_t b, bool c, AvrcpResponse d) { a->Call(b, c, d); }, - &response_cb); + base::BindRepeating([](MockFunction* a, + uint8_t b, bool c, AvrcpResponse d) { a->Call(b, c, d); }, + &response_cb); // TODO (apanicke): Test setting avrc13 to false once we have full // functionality. @@ -106,9 +105,7 @@ class AvrcpDeviceTest : public ::testing::Test { test_device->BrowseMessageReceived(label, message); } - void SetBipClientStatus(bool connected) { - test_device->SetBipClientStatus(connected); - } + void SetBipClientStatus(bool connected) { test_device->SetBipClientStatus(connected); } void FilterCoverArt(SongInfo& s) { for (auto it = s.attributes.begin(); it != s.attributes.end(); it++) { @@ -125,10 +122,9 @@ class AvrcpDeviceTest : public ::testing::Test { TEST_F(AvrcpDeviceTest, addressTest) { base::RepeatingCallback cb = - base::BindRepeating( - [](MockFunction* a, - uint8_t b, bool c, AvrcpResponse d) { a->Call(b, c, d); }, - &response_cb); + base::BindRepeating([](MockFunction* a, + uint8_t b, bool c, AvrcpResponse d) { a->Call(b, c, d); }, + &response_cb); Device device(RawAddress::kAny, true, cb, 0xFFFF, 0xFFFF); ASSERT_EQ(device.GetAddress(), RawAddress::kAny); @@ -146,8 +142,7 @@ TEST_F(AvrcpDeviceTest, trackChangedTest) { MockMediaInterface interface; NiceMock a2dp_interface; - test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, - nullptr); + test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, nullptr); SongInfo info = {"test_id", {// The attribute map @@ -162,28 +157,21 @@ TEST_F(AvrcpDeviceTest, trackChangedTest) { std::vector list = {info}; EXPECT_CALL(interface, GetNowPlayingList(_)) - .Times(2) - .WillRepeatedly(InvokeCb<0>("test_id", list)); + .Times(2) + .WillRepeatedly(InvokeCb<0>("test_id", list)); // Test the interim response for track changed - auto interim_response = - RegisterNotificationResponseBuilder::MakeTrackChangedBuilder(true, 0x01); - EXPECT_CALL(response_cb, - Call(1, false, matchPacket(std::move(interim_response)))) - .Times(1); + auto interim_response = RegisterNotificationResponseBuilder::MakeTrackChangedBuilder(true, 0x01); + EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(interim_response)))).Times(1); - auto request = - RegisterNotificationRequestBuilder::MakeBuilder(Event::TRACK_CHANGED, 0); + auto request = RegisterNotificationRequestBuilder::MakeBuilder(Event::TRACK_CHANGED, 0); auto pkt = TestAvrcpPacket::Make(); request->Serialize(pkt); SendMessage(1, pkt); // Test the changed response for track changed - auto changed_response = - RegisterNotificationResponseBuilder::MakeTrackChangedBuilder(false, 0x01); - EXPECT_CALL(response_cb, - Call(1, false, matchPacket(std::move(changed_response)))) - .Times(1); + auto changed_response = RegisterNotificationResponseBuilder::MakeTrackChangedBuilder(false, 0x01); + EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(changed_response)))).Times(1); test_device->HandleTrackUpdate(); } @@ -192,40 +180,31 @@ TEST_F(AvrcpDeviceTest, playerSettingsChangedTest) { MockMediaInterface interface; NiceMock a2dp_interface; MockPlayerSettingsInterface player_settings_interface; - std::vector attributes = {PlayerAttribute::REPEAT, - PlayerAttribute::SHUFFLE}; - std::vector attributes_values = { - static_cast(PlayerRepeatValue::OFF), - static_cast(PlayerShuffleValue::ALL)}; + std::vector attributes = {PlayerAttribute::REPEAT, PlayerAttribute::SHUFFLE}; + std::vector attributes_values = {static_cast(PlayerRepeatValue::OFF), + static_cast(PlayerShuffleValue::ALL)}; - test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, - &player_settings_interface); + test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, &player_settings_interface); EXPECT_CALL(player_settings_interface, GetCurrentPlayerSettingValue(_, _)) - .Times(1) - .WillRepeatedly(InvokeCb<1>(attributes, attributes_values)); + .Times(1) + .WillRepeatedly(InvokeCb<1>(attributes, attributes_values)); // Test the interim response for player settings changed - auto interim_response = - RegisterNotificationResponseBuilder::MakePlayerSettingChangedBuilder( + auto interim_response = RegisterNotificationResponseBuilder::MakePlayerSettingChangedBuilder( true, attributes, attributes_values); - EXPECT_CALL(response_cb, - Call(1, false, matchPacket(std::move(interim_response)))) - .Times(1); + EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(interim_response)))).Times(1); auto request = RegisterNotificationRequestBuilder::MakeBuilder( - Event::PLAYER_APPLICATION_SETTING_CHANGED, 0); + Event::PLAYER_APPLICATION_SETTING_CHANGED, 0); auto pkt = TestAvrcpPacket::Make(); request->Serialize(pkt); SendMessage(1, pkt); // Test the changed response for player settings changed - auto changed_response = - RegisterNotificationResponseBuilder::MakePlayerSettingChangedBuilder( + auto changed_response = RegisterNotificationResponseBuilder::MakePlayerSettingChangedBuilder( false, attributes, attributes_values); - EXPECT_CALL(response_cb, - Call(1, false, matchPacket(std::move(changed_response)))) - .Times(1); + EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(changed_response)))).Times(1); test_device->HandlePlayerSettingChanged(attributes, attributes_values); } @@ -234,16 +213,14 @@ TEST_F(AvrcpDeviceTest, playerSettingsChangedNotSupportedTest) { MockMediaInterface interface; NiceMock a2dp_interface; - test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, - nullptr); + test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, nullptr); - auto response = RejectBuilder::MakeBuilder(CommandPdu::REGISTER_NOTIFICATION, - Status::INVALID_COMMAND); - EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(response)))) - .Times(1); + auto response = + RejectBuilder::MakeBuilder(CommandPdu::REGISTER_NOTIFICATION, Status::INVALID_COMMAND); + EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(response)))).Times(1); auto request = RegisterNotificationRequestBuilder::MakeBuilder( - Event::PLAYER_APPLICATION_SETTING_CHANGED, 0); + Event::PLAYER_APPLICATION_SETTING_CHANGED, 0); auto pkt = TestAvrcpPacket::Make(); request->Serialize(pkt); SendMessage(1, pkt); @@ -253,42 +230,33 @@ TEST_F(AvrcpDeviceTest, playStatusTest) { MockMediaInterface interface; NiceMock a2dp_interface; - test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, - nullptr); + test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, nullptr); PlayStatus status1 = {0x1234, 0x5678, PlayState::PLAYING}; PlayStatus status2 = {0x1234, 0x5678, PlayState::STOPPED}; EXPECT_CALL(interface, GetPlayStatus(_)) - .Times(2) - .WillOnce(InvokeCb<0>(status1)) - .WillOnce(InvokeCb<0>(status2)); + .Times(2) + .WillOnce(InvokeCb<0>(status1)) + .WillOnce(InvokeCb<0>(status2)); // Pretend the device is active - EXPECT_CALL(a2dp_interface, active_peer()) - .WillRepeatedly(Return(test_device->GetAddress())); + EXPECT_CALL(a2dp_interface, active_peer()).WillRepeatedly(Return(test_device->GetAddress())); // Test the interim response for play status changed auto interim_response = - RegisterNotificationResponseBuilder::MakePlaybackStatusBuilder( - true, PlayState::PLAYING); - EXPECT_CALL(response_cb, - Call(1, false, matchPacket(std::move(interim_response)))) - .Times(1); + RegisterNotificationResponseBuilder::MakePlaybackStatusBuilder(true, PlayState::PLAYING); + EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(interim_response)))).Times(1); - auto request = RegisterNotificationRequestBuilder::MakeBuilder( - Event::PLAYBACK_STATUS_CHANGED, 0); + auto request = RegisterNotificationRequestBuilder::MakeBuilder(Event::PLAYBACK_STATUS_CHANGED, 0); auto pkt = TestAvrcpPacket::Make(); request->Serialize(pkt); SendMessage(1, pkt); // Test the changed response for play status changed auto changed_response = - RegisterNotificationResponseBuilder::MakePlaybackStatusBuilder( - false, PlayState::STOPPED); - EXPECT_CALL(response_cb, - Call(1, false, matchPacket(std::move(changed_response)))) - .Times(1); + RegisterNotificationResponseBuilder::MakePlaybackStatusBuilder(false, PlayState::STOPPED); + EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(changed_response)))).Times(1); test_device->HandlePlayStatusUpdate(); } @@ -296,8 +264,7 @@ TEST_F(AvrcpDeviceTest, playPositionTest) { MockMediaInterface interface; NiceMock a2dp_interface; - test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, - nullptr); + test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, nullptr); // TODO (apanicke): Add an underlying message loop so we can test the playing // state. @@ -305,35 +272,27 @@ TEST_F(AvrcpDeviceTest, playPositionTest) { PlayStatus status2 = {0x5678, 0x9ABC, PlayState::STOPPED}; EXPECT_CALL(interface, GetPlayStatus(_)) - .Times(2) - .WillOnce(InvokeCb<0>(status1)) - .WillOnce(InvokeCb<0>(status2)); + .Times(2) + .WillOnce(InvokeCb<0>(status1)) + .WillOnce(InvokeCb<0>(status2)); // Pretend the device is active - EXPECT_CALL(a2dp_interface, active_peer()) - .WillRepeatedly(Return(test_device->GetAddress())); + EXPECT_CALL(a2dp_interface, active_peer()).WillRepeatedly(Return(test_device->GetAddress())); // Test the interim response for play position changed auto interim_response = - RegisterNotificationResponseBuilder::MakePlaybackPositionBuilder(true, - 0x1234); - EXPECT_CALL(response_cb, - Call(1, false, matchPacket(std::move(interim_response)))) - .Times(1); + RegisterNotificationResponseBuilder::MakePlaybackPositionBuilder(true, 0x1234); + EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(interim_response)))).Times(1); - auto request = RegisterNotificationRequestBuilder::MakeBuilder( - Event::PLAYBACK_POS_CHANGED, 0); + auto request = RegisterNotificationRequestBuilder::MakeBuilder(Event::PLAYBACK_POS_CHANGED, 0); auto pkt = TestAvrcpPacket::Make(); request->Serialize(pkt); SendMessage(1, pkt); // Test the changed response for play position changed auto changed_response = - RegisterNotificationResponseBuilder::MakePlaybackPositionBuilder(false, - 0x5678); - EXPECT_CALL(response_cb, - Call(1, false, matchPacket(std::move(changed_response)))) - .Times(1); + RegisterNotificationResponseBuilder::MakePlaybackPositionBuilder(false, 0x5678); + EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(changed_response)))).Times(1); test_device->HandlePlayPosUpdate(); } @@ -341,12 +300,10 @@ TEST_F(AvrcpDeviceTest, trackChangedBeforeInterimTest) { MockMediaInterface interface; NiceMock a2dp_interface; - test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, - nullptr); + test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, nullptr); // Pretend the device is active - EXPECT_CALL(a2dp_interface, active_peer()) - .WillRepeatedly(Return(test_device->GetAddress())); + EXPECT_CALL(a2dp_interface, active_peer()).WillRepeatedly(Return(test_device->GetAddress())); SongInfo info = {"test_id", {// The attribute map @@ -364,26 +321,19 @@ TEST_F(AvrcpDeviceTest, trackChangedBeforeInterimTest) { MediaInterface::NowPlayingCallback changed_cb; EXPECT_CALL(interface, GetNowPlayingList(_)) - .Times(2) - .WillOnce(SaveArg<0>(&interim_cb)) - .WillOnce(SaveArg<0>(&changed_cb)); + .Times(2) + .WillOnce(SaveArg<0>(&interim_cb)) + .WillOnce(SaveArg<0>(&changed_cb)); // Test that the changed response doesn't get sent before the interim ::testing::InSequence s; - auto interim_response = - RegisterNotificationResponseBuilder::MakeTrackChangedBuilder(true, 0x01); - EXPECT_CALL(response_cb, - Call(1, false, matchPacket(std::move(interim_response)))) - .Times(1); - auto changed_response = - RegisterNotificationResponseBuilder::MakeTrackChangedBuilder(false, 0x01); - EXPECT_CALL(response_cb, - Call(1, false, matchPacket(std::move(changed_response)))) - .Times(1); + auto interim_response = RegisterNotificationResponseBuilder::MakeTrackChangedBuilder(true, 0x01); + EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(interim_response)))).Times(1); + auto changed_response = RegisterNotificationResponseBuilder::MakeTrackChangedBuilder(false, 0x01); + EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(changed_response)))).Times(1); // Register for the update, sets interim_cb - auto request = - RegisterNotificationRequestBuilder::MakeBuilder(Event::TRACK_CHANGED, 0); + auto request = RegisterNotificationRequestBuilder::MakeBuilder(Event::TRACK_CHANGED, 0); auto pkt = TestAvrcpPacket::Make(); request->Serialize(pkt); SendMessage(1, pkt); @@ -404,38 +354,29 @@ TEST_F(AvrcpDeviceTest, playStatusChangedBeforeInterimTest) { NiceMock a2dp_interface; // Pretend the device is active - EXPECT_CALL(a2dp_interface, active_peer()) - .WillRepeatedly(Return(test_device->GetAddress())); + EXPECT_CALL(a2dp_interface, active_peer()).WillRepeatedly(Return(test_device->GetAddress())); - test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, - nullptr); + test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, nullptr); MediaInterface::PlayStatusCallback interim_cb; MediaInterface::PlayStatusCallback changed_cb; EXPECT_CALL(interface, GetPlayStatus(_)) - .Times(2) - .WillOnce(SaveArg<0>(&interim_cb)) - .WillOnce(SaveArg<0>(&changed_cb)); + .Times(2) + .WillOnce(SaveArg<0>(&interim_cb)) + .WillOnce(SaveArg<0>(&changed_cb)); // Test that the changed response doesn't get sent before the interim ::testing::InSequence s; auto interim_response = - RegisterNotificationResponseBuilder::MakePlaybackStatusBuilder( - true, PlayState::PLAYING); - EXPECT_CALL(response_cb, - Call(1, false, matchPacket(std::move(interim_response)))) - .Times(1); + RegisterNotificationResponseBuilder::MakePlaybackStatusBuilder(true, PlayState::PLAYING); + EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(interim_response)))).Times(1); auto changed_response = - RegisterNotificationResponseBuilder::MakePlaybackStatusBuilder( - false, PlayState::STOPPED); - EXPECT_CALL(response_cb, - Call(1, false, matchPacket(std::move(changed_response)))) - .Times(1); + RegisterNotificationResponseBuilder::MakePlaybackStatusBuilder(false, PlayState::STOPPED); + EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(changed_response)))).Times(1); // Send the registration packet - auto request = RegisterNotificationRequestBuilder::MakeBuilder( - Event::PLAYBACK_STATUS_CHANGED, 0); + auto request = RegisterNotificationRequestBuilder::MakeBuilder(Event::PLAYBACK_STATUS_CHANGED, 0); auto pkt = TestAvrcpPacket::Make(); request->Serialize(pkt); SendMessage(1, pkt); @@ -459,38 +400,29 @@ TEST_F(AvrcpDeviceTest, playPositionChangedBeforeInterimTest) { NiceMock a2dp_interface; // Pretend the device is active - EXPECT_CALL(a2dp_interface, active_peer()) - .WillRepeatedly(Return(test_device->GetAddress())); + EXPECT_CALL(a2dp_interface, active_peer()).WillRepeatedly(Return(test_device->GetAddress())); - test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, - nullptr); + test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, nullptr); MediaInterface::PlayStatusCallback interim_cb; MediaInterface::PlayStatusCallback changed_cb; EXPECT_CALL(interface, GetPlayStatus(_)) - .Times(2) - .WillOnce(SaveArg<0>(&interim_cb)) - .WillOnce(SaveArg<0>(&changed_cb)); + .Times(2) + .WillOnce(SaveArg<0>(&interim_cb)) + .WillOnce(SaveArg<0>(&changed_cb)); // Test that the changed response doesn't get sent before the interim ::testing::InSequence s; auto interim_response = - RegisterNotificationResponseBuilder::MakePlaybackPositionBuilder(true, - 0x1234); - EXPECT_CALL(response_cb, - Call(1, false, matchPacket(std::move(interim_response)))) - .Times(1); + RegisterNotificationResponseBuilder::MakePlaybackPositionBuilder(true, 0x1234); + EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(interim_response)))).Times(1); auto changed_response = - RegisterNotificationResponseBuilder::MakePlaybackPositionBuilder(false, - 0x5678); - EXPECT_CALL(response_cb, - Call(1, false, matchPacket(std::move(changed_response)))) - .Times(1); + RegisterNotificationResponseBuilder::MakePlaybackPositionBuilder(false, 0x5678); + EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(changed_response)))).Times(1); // Send the registration packet - auto request = RegisterNotificationRequestBuilder::MakeBuilder( - Event::PLAYBACK_POS_CHANGED, 0); + auto request = RegisterNotificationRequestBuilder::MakeBuilder(Event::PLAYBACK_POS_CHANGED, 0); auto pkt = TestAvrcpPacket::Make(); request->Serialize(pkt); SendMessage(1, pkt); @@ -514,8 +446,7 @@ TEST_F(AvrcpDeviceTest, nowPlayingChangedBeforeInterim) { MockMediaInterface interface; NiceMock a2dp_interface; - test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, - nullptr); + test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, nullptr); SongInfo info = {"test_id", {// The attribute map @@ -533,26 +464,20 @@ TEST_F(AvrcpDeviceTest, nowPlayingChangedBeforeInterim) { MediaInterface::NowPlayingCallback changed_cb; EXPECT_CALL(interface, GetNowPlayingList(_)) - .Times(2) - .WillOnce(SaveArg<0>(&interim_cb)) - .WillOnce(SaveArg<0>(&changed_cb)); + .Times(2) + .WillOnce(SaveArg<0>(&interim_cb)) + .WillOnce(SaveArg<0>(&changed_cb)); // Test that the changed response doesn't get sent before the interim ::testing::InSequence s; - auto interim_response = - RegisterNotificationResponseBuilder::MakeNowPlayingBuilder(true); - EXPECT_CALL(response_cb, - Call(1, false, matchPacket(std::move(interim_response)))) - .Times(1); - auto changed_response = - RegisterNotificationResponseBuilder::MakeNowPlayingBuilder(false); - EXPECT_CALL(response_cb, - Call(1, false, matchPacket(std::move(changed_response)))) - .Times(1); + auto interim_response = RegisterNotificationResponseBuilder::MakeNowPlayingBuilder(true); + EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(interim_response)))).Times(1); + auto changed_response = RegisterNotificationResponseBuilder::MakeNowPlayingBuilder(false); + EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(changed_response)))).Times(1); // Send the registration packet - auto request = RegisterNotificationRequestBuilder::MakeBuilder( - Event::NOW_PLAYING_CONTENT_CHANGED, 0); + auto request = + RegisterNotificationRequestBuilder::MakeBuilder(Event::NOW_PLAYING_CONTENT_CHANGED, 0); auto pkt = TestAvrcpPacket::Make(); request->Serialize(pkt); SendMessage(1, pkt); @@ -573,42 +498,33 @@ TEST_F(AvrcpDeviceTest, addressPlayerChangedBeforeInterim) { MockMediaInterface interface; NiceMock a2dp_interface; - test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, - nullptr); + test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, nullptr); MediaInterface::MediaListCallback interim_cb; MediaInterface::MediaListCallback changed_cb; EXPECT_CALL(interface, GetMediaPlayerList(_)) - .Times(2) - .WillOnce(SaveArg<0>(&interim_cb)) - .WillOnce(SaveArg<0>(&changed_cb)); + .Times(2) + .WillOnce(SaveArg<0>(&interim_cb)) + .WillOnce(SaveArg<0>(&changed_cb)); // Test that the changed response doesn't get sent before the interim ::testing::InSequence s; auto interim_response = - RegisterNotificationResponseBuilder::MakeAddressedPlayerBuilder(true, 0, - 0); - EXPECT_CALL(response_cb, - Call(1, false, matchPacket(std::move(interim_response)))) - .Times(1); + RegisterNotificationResponseBuilder::MakeAddressedPlayerBuilder(true, 0, 0); + EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(interim_response)))).Times(1); auto changed_response = - RegisterNotificationResponseBuilder::MakeAddressedPlayerBuilder(false, 0, - 0); - EXPECT_CALL(response_cb, - Call(1, false, matchPacket(std::move(changed_response)))) - .Times(1); + RegisterNotificationResponseBuilder::MakeAddressedPlayerBuilder(false, 0, 0); + EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(changed_response)))).Times(1); // TODO (apanicke): Remove this expectation once b/110957802 is fixed and // we don't try to reject notifications that aren't registered. - auto rejected_response = RejectBuilder::MakeBuilder( - CommandPdu::REGISTER_NOTIFICATION, Status::ADDRESSED_PLAYER_CHANGED); - EXPECT_CALL(response_cb, - Call(_, false, matchPacket(std::move(rejected_response)))) - .Times(4); + auto rejected_response = RejectBuilder::MakeBuilder(CommandPdu::REGISTER_NOTIFICATION, + Status::ADDRESSED_PLAYER_CHANGED); + EXPECT_CALL(response_cb, Call(_, false, matchPacket(std::move(rejected_response)))).Times(4); // Send the registration packet - auto request = RegisterNotificationRequestBuilder::MakeBuilder( - Event::ADDRESSED_PLAYER_CHANGED, 0); + auto request = + RegisterNotificationRequestBuilder::MakeBuilder(Event::ADDRESSED_PLAYER_CHANGED, 0); auto pkt = TestAvrcpPacket::Make(); request->Serialize(pkt); SendMessage(1, pkt); @@ -631,8 +547,7 @@ TEST_F(AvrcpDeviceTest, nowPlayingTest) { MockMediaInterface interface; NiceMock a2dp_interface; - test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, - nullptr); + test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, nullptr); SongInfo info = {"test_id", {// The attribute map @@ -646,28 +561,22 @@ TEST_F(AvrcpDeviceTest, nowPlayingTest) { AttributeEntry(Attribute::DEFAULT_COVER_ART, "0000001")}}; std::vector list = {info}; EXPECT_CALL(interface, GetNowPlayingList(_)) - .Times(2) - .WillRepeatedly(InvokeCb<0>("test_id", list)); + .Times(2) + .WillRepeatedly(InvokeCb<0>("test_id", list)); // Test the interim response for now playing list changed - auto interim_response = - RegisterNotificationResponseBuilder::MakeNowPlayingBuilder(true); - EXPECT_CALL(response_cb, - Call(1, false, matchPacket(std::move(interim_response)))) - .Times(1); + auto interim_response = RegisterNotificationResponseBuilder::MakeNowPlayingBuilder(true); + EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(interim_response)))).Times(1); - auto request = RegisterNotificationRequestBuilder::MakeBuilder( - Event::NOW_PLAYING_CONTENT_CHANGED, 0); + auto request = + RegisterNotificationRequestBuilder::MakeBuilder(Event::NOW_PLAYING_CONTENT_CHANGED, 0); auto pkt = TestAvrcpPacket::Make(); request->Serialize(pkt); SendMessage(1, pkt); // Test the changed response for now playing list changed - auto changed_response = - RegisterNotificationResponseBuilder::MakeNowPlayingBuilder(false); - EXPECT_CALL(response_cb, - Call(1, false, matchPacket(std::move(changed_response)))) - .Times(1); + auto changed_response = RegisterNotificationResponseBuilder::MakeNowPlayingBuilder(false); + EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(changed_response)))).Times(1); test_device->HandleNowPlayingUpdate(); } @@ -675,24 +584,18 @@ TEST_F(AvrcpDeviceTest, getPlayStatusTest) { MockMediaInterface interface; NiceMock a2dp_interface; - test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, - nullptr); + test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, nullptr); PlayStatus status = {0x1234, 0x5678, PlayState::PLAYING}; - EXPECT_CALL(interface, GetPlayStatus(_)) - .Times(1) - .WillOnce(InvokeCb<0>(status)); + EXPECT_CALL(interface, GetPlayStatus(_)).Times(1).WillOnce(InvokeCb<0>(status)); // Pretend the device is active - EXPECT_CALL(a2dp_interface, active_peer()) - .WillRepeatedly(Return(test_device->GetAddress())); + EXPECT_CALL(a2dp_interface, active_peer()).WillRepeatedly(Return(test_device->GetAddress())); - auto expected_response = GetPlayStatusResponseBuilder::MakeBuilder( - 0x5678, 0x1234, PlayState::PLAYING); - EXPECT_CALL(response_cb, - Call(1, false, matchPacket(std::move(expected_response)))) - .Times(1); + auto expected_response = + GetPlayStatusResponseBuilder::MakeBuilder(0x5678, 0x1234, PlayState::PLAYING); + EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(expected_response)))).Times(1); auto request = TestAvrcpPacket::Make(get_play_status_request); SendMessage(1, request); @@ -702,8 +605,7 @@ TEST_F(AvrcpDeviceTest, getElementAttributesTest) { MockMediaInterface interface; NiceMock a2dp_interface; - test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, - nullptr); + test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, nullptr); SongInfo info = {"test_id", {// The attribute map @@ -718,16 +620,12 @@ TEST_F(AvrcpDeviceTest, getElementAttributesTest) { EXPECT_CALL(interface, GetSongInfo(_)).WillRepeatedly(InvokeCb<0>(info)); - auto compare_to_partial = - GetElementAttributesResponseBuilder::MakeBuilder(0xFFFF); + auto compare_to_partial = GetElementAttributesResponseBuilder::MakeBuilder(0xFFFF); compare_to_partial->AddAttributeEntry(Attribute::TITLE, "Test Song"); - EXPECT_CALL(response_cb, - Call(2, false, matchPacket(std::move(compare_to_partial)))) - .Times(1); + EXPECT_CALL(response_cb, Call(2, false, matchPacket(std::move(compare_to_partial)))).Times(1); SendMessage(2, TestAvrcpPacket::Make(get_element_attributes_request_partial)); - auto compare_to_full = - GetElementAttributesResponseBuilder::MakeBuilder(0xFFFF); + auto compare_to_full = GetElementAttributesResponseBuilder::MakeBuilder(0xFFFF); compare_to_full->AddAttributeEntry(Attribute::TITLE, "Test Song"); compare_to_full->AddAttributeEntry(Attribute::ARTIST_NAME, "Test Artist"); compare_to_full->AddAttributeEntry(Attribute::ALBUM_NAME, "Test Album"); @@ -735,9 +633,7 @@ TEST_F(AvrcpDeviceTest, getElementAttributesTest) { compare_to_full->AddAttributeEntry(Attribute::TOTAL_NUMBER_OF_TRACKS, "2"); compare_to_full->AddAttributeEntry(Attribute::GENRE, "Test Genre"); compare_to_full->AddAttributeEntry(Attribute::PLAYING_TIME, "1000"); - EXPECT_CALL(response_cb, - Call(3, false, matchPacket(std::move(compare_to_full)))) - .Times(1); + EXPECT_CALL(response_cb, Call(3, false, matchPacket(std::move(compare_to_full)))).Times(1); SendMessage(3, TestAvrcpPacket::Make(get_element_attributes_request_full)); } @@ -745,8 +641,7 @@ TEST_F(AvrcpDeviceTest, getElementAttributesWithCoverArtTest) { MockMediaInterface interface; NiceMock a2dp_interface; - test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, - nullptr); + test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, nullptr); SongInfo info = {"test_id", {// The attribute map @@ -762,8 +657,7 @@ TEST_F(AvrcpDeviceTest, getElementAttributesWithCoverArtTest) { EXPECT_CALL(interface, GetSongInfo(_)).WillRepeatedly(InvokeCb<0>(info)); SetBipClientStatus(false); - auto compare_to_no_art = - GetElementAttributesResponseBuilder::MakeBuilder(0xFFFF); + auto compare_to_no_art = GetElementAttributesResponseBuilder::MakeBuilder(0xFFFF); compare_to_no_art->AddAttributeEntry(Attribute::TITLE, "Test Song"); compare_to_no_art->AddAttributeEntry(Attribute::ARTIST_NAME, "Test Artist"); compare_to_no_art->AddAttributeEntry(Attribute::ALBUM_NAME, "Test Album"); @@ -771,16 +665,12 @@ TEST_F(AvrcpDeviceTest, getElementAttributesWithCoverArtTest) { compare_to_no_art->AddAttributeEntry(Attribute::TOTAL_NUMBER_OF_TRACKS, "2"); compare_to_no_art->AddAttributeEntry(Attribute::GENRE, "Test Genre"); compare_to_no_art->AddAttributeEntry(Attribute::PLAYING_TIME, "1000"); - EXPECT_CALL(response_cb, - Call(3, false, matchPacket(std::move(compare_to_no_art)))) - .Times(1); - SendMessage(3, - TestAvrcpPacket::Make(get_element_attributes_request_full_cover_art)); + EXPECT_CALL(response_cb, Call(3, false, matchPacket(std::move(compare_to_no_art)))).Times(1); + SendMessage(3, TestAvrcpPacket::Make(get_element_attributes_request_full_cover_art)); SetBipClientStatus(true); - auto compare_to_full = - GetElementAttributesResponseBuilder::MakeBuilder(0xFFFF); + auto compare_to_full = GetElementAttributesResponseBuilder::MakeBuilder(0xFFFF); compare_to_full->AddAttributeEntry(Attribute::TITLE, "Test Song"); compare_to_full->AddAttributeEntry(Attribute::ARTIST_NAME, "Test Artist"); compare_to_full->AddAttributeEntry(Attribute::ALBUM_NAME, "Test Album"); @@ -789,138 +679,109 @@ TEST_F(AvrcpDeviceTest, getElementAttributesWithCoverArtTest) { compare_to_full->AddAttributeEntry(Attribute::GENRE, "Test Genre"); compare_to_full->AddAttributeEntry(Attribute::PLAYING_TIME, "1000"); compare_to_full->AddAttributeEntry(Attribute::DEFAULT_COVER_ART, "0000001"); - EXPECT_CALL(response_cb, - Call(3, false, matchPacket(std::move(compare_to_full)))) - .Times(1); - SendMessage(3, - TestAvrcpPacket::Make(get_element_attributes_request_full_cover_art)); + EXPECT_CALL(response_cb, Call(3, false, matchPacket(std::move(compare_to_full)))).Times(1); + SendMessage(3, TestAvrcpPacket::Make(get_element_attributes_request_full_cover_art)); } TEST_F(AvrcpDeviceTest, getElementAttributesMtuTest) { - auto truncated_packet = - GetElementAttributesResponseBuilder::MakeBuilder(0xFFFF); + auto truncated_packet = GetElementAttributesResponseBuilder::MakeBuilder(0xFFFF); truncated_packet->AddAttributeEntry(Attribute::TITLE, "1234"); MockMediaInterface interface; NiceMock a2dp_interface; base::RepeatingCallback cb = - base::BindRepeating( - [](MockFunction* a, - uint8_t b, bool c, AvrcpResponse d) { a->Call(b, c, d); }, - &response_cb); + base::BindRepeating([](MockFunction* a, + uint8_t b, bool c, AvrcpResponse d) { a->Call(b, c, d); }, + &response_cb); Device device(RawAddress::kAny, true, cb, truncated_packet->size(), 0xFFFF); device.RegisterInterfaces(&interface, &a2dp_interface, nullptr, nullptr); - SongInfo info = {"test_id", - {AttributeEntry(Attribute::TITLE, "1234truncated")}}; + SongInfo info = {"test_id", {AttributeEntry(Attribute::TITLE, "1234truncated")}}; EXPECT_CALL(interface, GetSongInfo(_)).WillRepeatedly(InvokeCb<0>(info)); - EXPECT_CALL(response_cb, - Call(1, false, matchPacket(std::move(truncated_packet)))) - .Times(1); + EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(truncated_packet)))).Times(1); - device.MessageReceived( - 1, TestAvrcpPacket::Make(get_element_attributes_request_full)); + device.MessageReceived(1, TestAvrcpPacket::Make(get_element_attributes_request_full)); } TEST_F(AvrcpDeviceTest, getTotalNumberOfItemsMediaPlayersTest) { MockMediaInterface interface; NiceMock a2dp_interface; - test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, - nullptr); + test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, nullptr); std::vector player_list = { - {0, "player1", true}, {1, "player2", true}, {2, "player3", true}, + {0, "player1", true}, + {1, "player2", true}, + {2, "player3", true}, }; - EXPECT_CALL(interface, GetMediaPlayerList(_)) - .Times(1) - .WillOnce(InvokeCb<0>(0, player_list)); + EXPECT_CALL(interface, GetMediaPlayerList(_)).Times(1).WillOnce(InvokeCb<0>(0, player_list)); - auto expected_response = GetTotalNumberOfItemsResponseBuilder::MakeBuilder( - Status::NO_ERROR, 0, player_list.size()); - EXPECT_CALL(response_cb, - Call(1, true, matchPacket(std::move(expected_response)))) - .Times(1); + auto expected_response = GetTotalNumberOfItemsResponseBuilder::MakeBuilder(Status::NO_ERROR, 0, + player_list.size()); + EXPECT_CALL(response_cb, Call(1, true, matchPacket(std::move(expected_response)))).Times(1); - SendBrowseMessage(1, TestBrowsePacket::Make( - get_total_number_of_items_request_media_players)); + SendBrowseMessage(1, TestBrowsePacket::Make(get_total_number_of_items_request_media_players)); } TEST_F(AvrcpDeviceTest, getTotalNumberOfItemsVFSTest) { MockMediaInterface interface; NiceMock a2dp_interface; - test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, - nullptr); + test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, nullptr); std::vector vfs_list = { - {ListItem::FOLDER, {"id1", true, "folder1"}, SongInfo()}, - {ListItem::FOLDER, {"id2", true, "folder2"}, SongInfo()}, + {ListItem::FOLDER, {"id1", true, "folder1"}, SongInfo()}, + {ListItem::FOLDER, {"id2", true, "folder2"}, SongInfo()}, }; - EXPECT_CALL(interface, GetFolderItems(_, "", _)) - .Times(1) - .WillOnce(InvokeCb<2>(vfs_list)); + EXPECT_CALL(interface, GetFolderItems(_, "", _)).Times(1).WillOnce(InvokeCb<2>(vfs_list)); - auto expected_response = GetTotalNumberOfItemsResponseBuilder::MakeBuilder( - Status::NO_ERROR, 0, vfs_list.size()); - EXPECT_CALL(response_cb, - Call(1, true, matchPacket(std::move(expected_response)))) - .Times(1); + auto expected_response = + GetTotalNumberOfItemsResponseBuilder::MakeBuilder(Status::NO_ERROR, 0, vfs_list.size()); + EXPECT_CALL(response_cb, Call(1, true, matchPacket(std::move(expected_response)))).Times(1); - SendBrowseMessage( - 1, TestBrowsePacket::Make(get_total_number_of_items_request_vfs)); + SendBrowseMessage(1, TestBrowsePacket::Make(get_total_number_of_items_request_vfs)); } TEST_F(AvrcpDeviceTest, getTotalNumberOfItemsNowPlayingTest) { MockMediaInterface interface; NiceMock a2dp_interface; - test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, - nullptr); + test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, nullptr); std::vector now_playing_list = { - {"test_id1", {}}, {"test_id2", {}}, {"test_id3", {}}, - {"test_id4", {}}, {"test_id5", {}}, + {"test_id1", {}}, {"test_id2", {}}, {"test_id3", {}}, {"test_id4", {}}, {"test_id5", {}}, }; EXPECT_CALL(interface, GetNowPlayingList(_)) - .WillRepeatedly(InvokeCb<0>("test_id1", now_playing_list)); + .WillRepeatedly(InvokeCb<0>("test_id1", now_playing_list)); auto expected_response = GetTotalNumberOfItemsResponseBuilder::MakeBuilder( - Status::NO_ERROR, 0, now_playing_list.size()); - EXPECT_CALL(response_cb, - Call(1, true, matchPacket(std::move(expected_response)))) - .Times(1); + Status::NO_ERROR, 0, now_playing_list.size()); + EXPECT_CALL(response_cb, Call(1, true, matchPacket(std::move(expected_response)))).Times(1); - SendBrowseMessage( - 1, TestBrowsePacket::Make(get_total_number_of_items_request_now_playing)); + SendBrowseMessage(1, TestBrowsePacket::Make(get_total_number_of_items_request_now_playing)); } TEST_F(AvrcpDeviceTest, getMediaPlayerListTest) { MockMediaInterface interface; NiceMock a2dp_interface; - test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, - nullptr); + test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, nullptr); MediaPlayerInfo info = {0, "Test Player", true}; std::vector list = {info}; - EXPECT_CALL(interface, GetMediaPlayerList(_)) - .Times(1) - .WillOnce(InvokeCb<0>(0, list)); + EXPECT_CALL(interface, GetMediaPlayerList(_)).Times(1).WillOnce(InvokeCb<0>(0, list)); - auto expected_response = GetFolderItemsResponseBuilder::MakePlayerListBuilder( - Status::NO_ERROR, 0x0000, 0xFFFF); + auto expected_response = + GetFolderItemsResponseBuilder::MakePlayerListBuilder(Status::NO_ERROR, 0x0000, 0xFFFF); expected_response->AddMediaPlayer(MediaPlayerItem(0, "Test Player", true)); - EXPECT_CALL(response_cb, - Call(1, true, matchPacket(std::move(expected_response)))) - .Times(1); + EXPECT_CALL(response_cb, Call(1, true, matchPacket(std::move(expected_response)))).Times(1); auto request = TestBrowsePacket::Make(get_folder_items_request); SendBrowseMessage(1, request); @@ -930,8 +791,7 @@ TEST_F(AvrcpDeviceTest, getNowPlayingListTest) { MockMediaInterface interface; NiceMock a2dp_interface; - test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, - nullptr); + test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, nullptr); SetBipClientStatus(false); SongInfo info = {"test_id", @@ -946,16 +806,13 @@ TEST_F(AvrcpDeviceTest, getNowPlayingListTest) { AttributeEntry(Attribute::DEFAULT_COVER_ART, "0000001")}}; std::vector list = {info}; - EXPECT_CALL(interface, GetNowPlayingList(_)) - .WillRepeatedly(InvokeCb<0>("test_id", list)); + EXPECT_CALL(interface, GetNowPlayingList(_)).WillRepeatedly(InvokeCb<0>("test_id", list)); FilterCoverArt(info); - auto expected_response = GetFolderItemsResponseBuilder::MakeNowPlayingBuilder( - Status::NO_ERROR, 0x0000, 0xFFFF); + auto expected_response = + GetFolderItemsResponseBuilder::MakeNowPlayingBuilder(Status::NO_ERROR, 0x0000, 0xFFFF); expected_response->AddSong(MediaElementItem(1, "Test Song", info.attributes)); - EXPECT_CALL(response_cb, - Call(1, true, matchPacket(std::move(expected_response)))) - .Times(1); + EXPECT_CALL(response_cb, Call(1, true, matchPacket(std::move(expected_response)))).Times(1); auto request = TestBrowsePacket::Make(get_folder_items_request_now_playing); SendBrowseMessage(1, request); } @@ -964,8 +821,7 @@ TEST_F(AvrcpDeviceTest, getNowPlayingListWithCoverArtTest) { MockMediaInterface interface; NiceMock a2dp_interface; - test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, - nullptr); + test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, nullptr); SetBipClientStatus(true); SongInfo info = {"test_id", @@ -980,16 +836,13 @@ TEST_F(AvrcpDeviceTest, getNowPlayingListWithCoverArtTest) { AttributeEntry(Attribute::DEFAULT_COVER_ART, "0000001")}}; std::vector list = {info}; - EXPECT_CALL(interface, GetNowPlayingList(_)) - .WillRepeatedly(InvokeCb<0>("test_id", list)); + EXPECT_CALL(interface, GetNowPlayingList(_)).WillRepeatedly(InvokeCb<0>("test_id", list)); - auto expected_response = GetFolderItemsResponseBuilder::MakeNowPlayingBuilder( - Status::NO_ERROR, 0x0000, 0xFFFF); + auto expected_response = + GetFolderItemsResponseBuilder::MakeNowPlayingBuilder(Status::NO_ERROR, 0x0000, 0xFFFF); expected_response->AddSong(MediaElementItem(1, "Test Song", info.attributes)); - EXPECT_CALL(response_cb, - Call(1, true, matchPacket(std::move(expected_response)))) - .Times(1); + EXPECT_CALL(response_cb, Call(1, true, matchPacket(std::move(expected_response)))).Times(1); auto request = TestBrowsePacket::Make(get_folder_items_request_now_playing); SendBrowseMessage(1, request); } @@ -998,41 +851,35 @@ TEST_F(AvrcpDeviceTest, getVFSFolderTest) { MockMediaInterface interface; NiceMock a2dp_interface; - test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, - nullptr); + test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, nullptr); FolderInfo info = {"test_id", true, "Test Folder"}; ListItem item = {ListItem::FOLDER, info, SongInfo()}; std::vector list = {item}; - EXPECT_CALL(interface, GetFolderItems(_, "", _)) - .Times(1) - .WillOnce(InvokeCb<2>(list)); + EXPECT_CALL(interface, GetFolderItems(_, "", _)).Times(1).WillOnce(InvokeCb<2>(list)); - auto expected_response = GetFolderItemsResponseBuilder::MakeVFSBuilder( - Status::NO_ERROR, 0x0000, 0xFFFF); + auto expected_response = + GetFolderItemsResponseBuilder::MakeVFSBuilder(Status::NO_ERROR, 0x0000, 0xFFFF); expected_response->AddFolder(FolderItem(1, 0, true, "Test Folder")); - EXPECT_CALL(response_cb, - Call(1, true, matchPacket(std::move(expected_response)))) - .Times(1); + EXPECT_CALL(response_cb, Call(1, true, matchPacket(std::move(expected_response)))).Times(1); auto request = TestBrowsePacket::Make(get_folder_items_request_vfs); SendBrowseMessage(1, request); } TEST_F(AvrcpDeviceTest, getFolderItemsMtuTest) { - auto truncated_packet = GetFolderItemsResponseBuilder::MakeVFSBuilder( - Status::NO_ERROR, 0x0000, 0xFFFF); + auto truncated_packet = + GetFolderItemsResponseBuilder::MakeVFSBuilder(Status::NO_ERROR, 0x0000, 0xFFFF); truncated_packet->AddFolder(FolderItem(1, 0, true, "Test Folder0")); truncated_packet->AddFolder(FolderItem(2, 0, true, "Test Folder1")); MockMediaInterface interface; NiceMock a2dp_interface; base::RepeatingCallback cb = - base::BindRepeating( - [](MockFunction* a, - uint8_t b, bool c, AvrcpResponse d) { a->Call(b, c, d); }, - &response_cb); + base::BindRepeating([](MockFunction* a, + uint8_t b, bool c, AvrcpResponse d) { a->Call(b, c, d); }, + &response_cb); Device device(RawAddress::kAny, true, cb, 0xFFFF, truncated_packet->size() + FolderItem::kHeaderSize() + 5); @@ -1051,31 +898,24 @@ TEST_F(AvrcpDeviceTest, getFolderItemsMtuTest) { ListItem item3 = {ListItem::FOLDER, small_info, SongInfo()}; std::vector list0 = {item0, item1, item2, item3}; - EXPECT_CALL(interface, GetFolderItems(_, "", _)) - .WillRepeatedly(InvokeCb<2>(list0)); + EXPECT_CALL(interface, GetFolderItems(_, "", _)).WillRepeatedly(InvokeCb<2>(list0)); - EXPECT_CALL(response_cb, - Call(1, true, matchPacket(std::move(truncated_packet)))) - .Times(1); - device.BrowseMessageReceived( - 1, TestBrowsePacket::Make(get_folder_items_request_vfs)); + EXPECT_CALL(response_cb, Call(1, true, matchPacket(std::move(truncated_packet)))).Times(1); + device.BrowseMessageReceived(1, TestBrowsePacket::Make(get_folder_items_request_vfs)); } TEST_F(AvrcpDeviceTest, changePathTest) { MockMediaInterface interface; NiceMock a2dp_interface; - test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, - nullptr); + test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, nullptr); FolderInfo info0 = {"test_id0", true, "Test Folder0"}; FolderInfo info1 = {"test_id1", true, "Test Folder1"}; ListItem item0 = {ListItem::FOLDER, info0, SongInfo()}; ListItem item1 = {ListItem::FOLDER, info1, SongInfo()}; std::vector list0 = {item0, item1}; - EXPECT_CALL(interface, GetFolderItems(_, "", _)) - .Times(1) - .WillRepeatedly(InvokeCb<2>(list0)); + EXPECT_CALL(interface, GetFolderItems(_, "", _)).Times(1).WillRepeatedly(InvokeCb<2>(list0)); FolderInfo info2 = {"test_id2", true, "Test Folder2"}; FolderInfo info3 = {"test_id3", true, "Test Folder3"}; @@ -1085,73 +925,57 @@ TEST_F(AvrcpDeviceTest, changePathTest) { ListItem item4 = {ListItem::FOLDER, info4, SongInfo()}; std::vector list1 = {item2, item3, item4}; EXPECT_CALL(interface, GetFolderItems(_, "test_id1", _)) - .Times(3) - .WillRepeatedly(InvokeCb<2>(list1)); + .Times(3) + .WillRepeatedly(InvokeCb<2>(list1)); std::vector list2 = {}; - EXPECT_CALL(interface, GetFolderItems(_, "test_id3", _)) - .Times(1) - .WillOnce(InvokeCb<2>(list2)); + EXPECT_CALL(interface, GetFolderItems(_, "test_id3", _)).Times(1).WillOnce(InvokeCb<2>(list2)); // Populate the VFS ID map - auto folder_items_response = GetFolderItemsResponseBuilder::MakeVFSBuilder( - Status::NO_ERROR, 0x0000, 0xFFFF); + auto folder_items_response = + GetFolderItemsResponseBuilder::MakeVFSBuilder(Status::NO_ERROR, 0x0000, 0xFFFF); folder_items_response->AddFolder(FolderItem(1, 0, true, "Test Folder0")); folder_items_response->AddFolder(FolderItem(2, 0, true, "Test Folder1")); - EXPECT_CALL(response_cb, - Call(1, true, matchPacket(std::move(folder_items_response)))) - .Times(1); + EXPECT_CALL(response_cb, Call(1, true, matchPacket(std::move(folder_items_response)))).Times(1); - auto folder_request_builder = - GetFolderItemsRequestBuilder::MakeBuilder(Scope::VFS, 0, 3, {}); + auto folder_request_builder = GetFolderItemsRequestBuilder::MakeBuilder(Scope::VFS, 0, 3, {}); auto request = TestBrowsePacket::Make(); folder_request_builder->Serialize(request); SendBrowseMessage(1, request); // Change path down into Test Folder1 auto change_path_response = - ChangePathResponseBuilder::MakeBuilder(Status::NO_ERROR, list1.size()); - EXPECT_CALL(response_cb, - Call(2, true, matchPacket(std::move(change_path_response)))); - auto path_request_builder = - ChangePathRequestBuilder::MakeBuilder(0, Direction::DOWN, 2); + ChangePathResponseBuilder::MakeBuilder(Status::NO_ERROR, list1.size()); + EXPECT_CALL(response_cb, Call(2, true, matchPacket(std::move(change_path_response)))); + auto path_request_builder = ChangePathRequestBuilder::MakeBuilder(0, Direction::DOWN, 2); request = TestBrowsePacket::Make(); path_request_builder->Serialize(request); SendBrowseMessage(2, request); // Populate the new VFS ID - folder_items_response = GetFolderItemsResponseBuilder::MakeVFSBuilder( - Status::NO_ERROR, 0x0000, 0xFFFF); + folder_items_response = + GetFolderItemsResponseBuilder::MakeVFSBuilder(Status::NO_ERROR, 0x0000, 0xFFFF); folder_items_response->AddFolder(FolderItem(3, 0, true, "Test Folder2")); folder_items_response->AddFolder(FolderItem(4, 0, true, "Test Folder3")); folder_items_response->AddFolder(FolderItem(5, 0, true, "Test Folder4")); - EXPECT_CALL(response_cb, - Call(3, true, matchPacket(std::move(folder_items_response)))) - .Times(1); - folder_request_builder = - GetFolderItemsRequestBuilder::MakeBuilder(Scope::VFS, 0, 3, {}); + EXPECT_CALL(response_cb, Call(3, true, matchPacket(std::move(folder_items_response)))).Times(1); + folder_request_builder = GetFolderItemsRequestBuilder::MakeBuilder(Scope::VFS, 0, 3, {}); request = TestBrowsePacket::Make(); folder_request_builder->Serialize(request); SendBrowseMessage(3, request); // Change path down into Test Folder3 - change_path_response = - ChangePathResponseBuilder::MakeBuilder(Status::NO_ERROR, list2.size()); - EXPECT_CALL(response_cb, - Call(4, true, matchPacket(std::move(change_path_response)))); - path_request_builder = - ChangePathRequestBuilder::MakeBuilder(0, Direction::DOWN, 4); + change_path_response = ChangePathResponseBuilder::MakeBuilder(Status::NO_ERROR, list2.size()); + EXPECT_CALL(response_cb, Call(4, true, matchPacket(std::move(change_path_response)))); + path_request_builder = ChangePathRequestBuilder::MakeBuilder(0, Direction::DOWN, 4); request = TestBrowsePacket::Make(); path_request_builder->Serialize(request); SendBrowseMessage(4, request); // Change path up back into Test Folder1 - change_path_response = - ChangePathResponseBuilder::MakeBuilder(Status::NO_ERROR, list1.size()); - EXPECT_CALL(response_cb, - Call(5, true, matchPacket(std::move(change_path_response)))); - path_request_builder = - ChangePathRequestBuilder::MakeBuilder(0, Direction::UP, 0); + change_path_response = ChangePathResponseBuilder::MakeBuilder(Status::NO_ERROR, list1.size()); + EXPECT_CALL(response_cb, Call(5, true, matchPacket(std::move(change_path_response)))); + path_request_builder = ChangePathRequestBuilder::MakeBuilder(0, Direction::UP, 0); request = TestBrowsePacket::Make(); path_request_builder->Serialize(request); SendBrowseMessage(5, request); @@ -1161,8 +985,7 @@ TEST_F(AvrcpDeviceTest, getItemAttributesNowPlayingTest) { MockMediaInterface interface; NiceMock a2dp_interface; - test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, - nullptr); + test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, nullptr); SongInfo info = {"test_id", {// The attribute map @@ -1176,13 +999,11 @@ TEST_F(AvrcpDeviceTest, getItemAttributesNowPlayingTest) { AttributeEntry(Attribute::DEFAULT_COVER_ART, "0000001")}}; std::vector list = {info}; - EXPECT_CALL(interface, GetNowPlayingList(_)) - .WillRepeatedly(InvokeCb<0>("test_id", list)); + EXPECT_CALL(interface, GetNowPlayingList(_)).WillRepeatedly(InvokeCb<0>("test_id", list)); SetBipClientStatus(false); - auto compare_to_full = - GetItemAttributesResponseBuilder::MakeBuilder(Status::NO_ERROR, 0xFFFF); + auto compare_to_full = GetItemAttributesResponseBuilder::MakeBuilder(Status::NO_ERROR, 0xFFFF); compare_to_full->AddAttributeEntry(Attribute::TITLE, "Test Song"); compare_to_full->AddAttributeEntry(Attribute::ARTIST_NAME, "Test Artist"); compare_to_full->AddAttributeEntry(Attribute::ALBUM_NAME, "Test Album"); @@ -1190,12 +1011,9 @@ TEST_F(AvrcpDeviceTest, getItemAttributesNowPlayingTest) { compare_to_full->AddAttributeEntry(Attribute::TOTAL_NUMBER_OF_TRACKS, "2"); compare_to_full->AddAttributeEntry(Attribute::GENRE, "Test Genre"); compare_to_full->AddAttributeEntry(Attribute::PLAYING_TIME, "1000"); - EXPECT_CALL(response_cb, - Call(1, true, matchPacket(std::move(compare_to_full)))) - .Times(1); + EXPECT_CALL(response_cb, Call(1, true, matchPacket(std::move(compare_to_full)))).Times(1); - auto request = - TestBrowsePacket::Make(get_item_attributes_request_all_attributes); + auto request = TestBrowsePacket::Make(get_item_attributes_request_all_attributes); SendBrowseMessage(1, request); } @@ -1203,8 +1021,7 @@ TEST_F(AvrcpDeviceTest, getItemAttributesNowPlayingWithCoverArtTest) { MockMediaInterface interface; NiceMock a2dp_interface; - test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, - nullptr); + test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, nullptr); SongInfo info = {"test_id", {// The attribute map @@ -1218,14 +1035,12 @@ TEST_F(AvrcpDeviceTest, getItemAttributesNowPlayingWithCoverArtTest) { AttributeEntry(Attribute::DEFAULT_COVER_ART, "0000001")}}; std::vector list = {info}; - EXPECT_CALL(interface, GetNowPlayingList(_)) - .WillRepeatedly(InvokeCb<0>("test_id", list)); + EXPECT_CALL(interface, GetNowPlayingList(_)).WillRepeatedly(InvokeCb<0>("test_id", list)); SetBipClientStatus(true); - auto compare_to_full = - GetItemAttributesResponseBuilder::MakeBuilder(Status::NO_ERROR, 0xFFFF); - compare_to_full->AddAttributeEntry(Attribute::TITLE,"Test Song"); + auto compare_to_full = GetItemAttributesResponseBuilder::MakeBuilder(Status::NO_ERROR, 0xFFFF); + compare_to_full->AddAttributeEntry(Attribute::TITLE, "Test Song"); compare_to_full->AddAttributeEntry(Attribute::ARTIST_NAME, "Test Artist"); compare_to_full->AddAttributeEntry(Attribute::ALBUM_NAME, "Test Album"); compare_to_full->AddAttributeEntry(Attribute::TRACK_NUMBER, "1"); @@ -1233,19 +1048,15 @@ TEST_F(AvrcpDeviceTest, getItemAttributesNowPlayingWithCoverArtTest) { compare_to_full->AddAttributeEntry(Attribute::GENRE, "Test Genre"); compare_to_full->AddAttributeEntry(Attribute::PLAYING_TIME, "1000"); compare_to_full->AddAttributeEntry(Attribute::DEFAULT_COVER_ART, "0000001"); - EXPECT_CALL(response_cb, - Call(1, true, matchPacket(std::move(compare_to_full)))) - .Times(1); + EXPECT_CALL(response_cb, Call(1, true, matchPacket(std::move(compare_to_full)))).Times(1); auto requestWithBip = - TestBrowsePacket::Make( - get_item_attributes_request_all_attributes_with_cover_art); + TestBrowsePacket::Make(get_item_attributes_request_all_attributes_with_cover_art); SendBrowseMessage(1, requestWithBip); SetBipClientStatus(false); - auto compare_to_no_art = - GetItemAttributesResponseBuilder::MakeBuilder(Status::NO_ERROR, 0xFFFF); + auto compare_to_no_art = GetItemAttributesResponseBuilder::MakeBuilder(Status::NO_ERROR, 0xFFFF); compare_to_no_art->AddAttributeEntry(Attribute::TITLE, "Test Song"); compare_to_no_art->AddAttributeEntry(Attribute::ARTIST_NAME, "Test Artist"); compare_to_no_art->AddAttributeEntry(Attribute::ALBUM_NAME, "Test Album"); @@ -1253,74 +1064,58 @@ TEST_F(AvrcpDeviceTest, getItemAttributesNowPlayingWithCoverArtTest) { compare_to_no_art->AddAttributeEntry(Attribute::TOTAL_NUMBER_OF_TRACKS, "2"); compare_to_no_art->AddAttributeEntry(Attribute::GENRE, "Test Genre"); compare_to_no_art->AddAttributeEntry(Attribute::PLAYING_TIME, "1000"); - EXPECT_CALL(response_cb, - Call(1, true, matchPacket(std::move(compare_to_no_art)))) - .Times(1); + EXPECT_CALL(response_cb, Call(1, true, matchPacket(std::move(compare_to_no_art)))).Times(1); auto requestWithoutBip = - TestBrowsePacket::Make( - get_item_attributes_request_all_attributes_with_cover_art); + TestBrowsePacket::Make(get_item_attributes_request_all_attributes_with_cover_art); SendBrowseMessage(1, requestWithoutBip); } TEST_F(AvrcpDeviceTest, getItemAttributesMtuTest) { - auto truncated_packet = - GetItemAttributesResponseBuilder::MakeBuilder(Status::NO_ERROR, 0xFFFF); + auto truncated_packet = GetItemAttributesResponseBuilder::MakeBuilder(Status::NO_ERROR, 0xFFFF); truncated_packet->AddAttributeEntry(Attribute::TITLE, "1234"); MockMediaInterface interface; NiceMock a2dp_interface; base::RepeatingCallback cb = - base::BindRepeating( - [](MockFunction* a, - uint8_t b, bool c, AvrcpResponse d) { a->Call(b, c, d); }, - &response_cb); + base::BindRepeating([](MockFunction* a, + uint8_t b, bool c, AvrcpResponse d) { a->Call(b, c, d); }, + &response_cb); Device device(RawAddress::kAny, true, cb, 0xFFFF, truncated_packet->size()); device.RegisterInterfaces(&interface, &a2dp_interface, nullptr, nullptr); - SongInfo info = {"test_id", - {AttributeEntry(Attribute::TITLE, "1234truncated")}}; + SongInfo info = {"test_id", {AttributeEntry(Attribute::TITLE, "1234truncated")}}; std::vector list = {info}; - EXPECT_CALL(interface, GetNowPlayingList(_)) - .WillRepeatedly(InvokeCb<0>("test_id", list)); + EXPECT_CALL(interface, GetNowPlayingList(_)).WillRepeatedly(InvokeCb<0>("test_id", list)); - EXPECT_CALL(response_cb, - Call(1, true, matchPacket(std::move(truncated_packet)))) - .Times(1); - device.BrowseMessageReceived( - 1, TestBrowsePacket::Make(get_item_attributes_request_all_attributes)); + EXPECT_CALL(response_cb, Call(1, true, matchPacket(std::move(truncated_packet)))).Times(1); + device.BrowseMessageReceived(1, + TestBrowsePacket::Make(get_item_attributes_request_all_attributes)); } TEST_F(AvrcpDeviceTest, setAddressedPlayerTest) { MockMediaInterface interface; NiceMock a2dp_interface; - test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, - nullptr); + test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, nullptr); MediaPlayerInfo info = {0, "Test Player", true}; std::vector list = {info}; - EXPECT_CALL(interface, GetMediaPlayerList(_)) - .WillRepeatedly(InvokeCb<0>(0, list)); + EXPECT_CALL(interface, GetMediaPlayerList(_)).WillRepeatedly(InvokeCb<0>(0, list)); - auto set_addr_player_rej_rsp = RejectBuilder::MakeBuilder( - CommandPdu::SET_ADDRESSED_PLAYER, Status::INVALID_PLAYER_ID); + auto set_addr_player_rej_rsp = + RejectBuilder::MakeBuilder(CommandPdu::SET_ADDRESSED_PLAYER, Status::INVALID_PLAYER_ID); - EXPECT_CALL(response_cb, - Call(1, false, matchPacket(std::move(set_addr_player_rej_rsp)))) - .Times(1); + EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(set_addr_player_rej_rsp)))) + .Times(1); - auto player_id_1_request = - TestAvrcpPacket::Make(set_addressed_player_id_1_request); + auto player_id_1_request = TestAvrcpPacket::Make(set_addressed_player_id_1_request); SendMessage(1, player_id_1_request); - auto set_addr_player_rsp = - SetAddressedPlayerResponseBuilder::MakeBuilder(Status::NO_ERROR); + auto set_addr_player_rsp = SetAddressedPlayerResponseBuilder::MakeBuilder(Status::NO_ERROR); - EXPECT_CALL(response_cb, - Call(1, false, matchPacket(std::move(set_addr_player_rsp)))) - .Times(1); + EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(set_addr_player_rsp)))).Times(1); auto request = TestAvrcpPacket::Make(set_addressed_player_request); SendMessage(1, request); @@ -1330,37 +1125,29 @@ TEST_F(AvrcpDeviceTest, setBrowsedPlayerTest) { MockMediaInterface interface; NiceMock a2dp_interface; - test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, - nullptr); + test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, nullptr); EXPECT_CALL(interface, SetBrowsedPlayer(_, _)) - .Times(3) - .WillOnce(InvokeCb<1>(true, "", 0)) - .WillOnce(InvokeCb<1>(false, "", 0)) - .WillOnce(InvokeCb<1>(true, "", 2)); + .Times(3) + .WillOnce(InvokeCb<1>(true, "", 0)) + .WillOnce(InvokeCb<1>(false, "", 0)) + .WillOnce(InvokeCb<1>(true, "", 2)); auto not_browsable_rsp = SetBrowsedPlayerResponseBuilder::MakeBuilder( - Status::PLAYER_NOT_BROWSABLE, 0x0000, 0, 0, ""); - EXPECT_CALL(response_cb, - Call(1, true, matchPacket(std::move(not_browsable_rsp)))) - .Times(1); + Status::PLAYER_NOT_BROWSABLE, 0x0000, 0, 0, ""); + EXPECT_CALL(response_cb, Call(1, true, matchPacket(std::move(not_browsable_rsp)))).Times(1); - auto player_id_0_request = - TestBrowsePacket::Make(set_browsed_player_id_0_request); + auto player_id_0_request = TestBrowsePacket::Make(set_browsed_player_id_0_request); SendBrowseMessage(1, player_id_0_request); - auto invalid_id_rsp = SetBrowsedPlayerResponseBuilder::MakeBuilder( - Status::INVALID_PLAYER_ID, 0x0000, 0, 0, ""); - EXPECT_CALL(response_cb, - Call(2, true, matchPacket(std::move(invalid_id_rsp)))) - .Times(1); + auto invalid_id_rsp = + SetBrowsedPlayerResponseBuilder::MakeBuilder(Status::INVALID_PLAYER_ID, 0x0000, 0, 0, ""); + EXPECT_CALL(response_cb, Call(2, true, matchPacket(std::move(invalid_id_rsp)))).Times(1); SendBrowseMessage(2, player_id_0_request); - auto response = SetBrowsedPlayerResponseBuilder::MakeBuilder( - Status::NO_ERROR, 0x0000, 2, 0, ""); - EXPECT_CALL(response_cb, Call(3, true, matchPacket(std::move(response)))) - .Times(1); + auto response = SetBrowsedPlayerResponseBuilder::MakeBuilder(Status::NO_ERROR, 0x0000, 2, 0, ""); + EXPECT_CALL(response_cb, Call(3, true, matchPacket(std::move(response)))).Times(1); SendBrowseMessage(3, player_id_0_request); } @@ -1370,34 +1157,27 @@ TEST_F(AvrcpDeviceTest, volumeChangedTest) { NiceMock a2dp_interface; MockVolumeInterface vol_interface; - test_device->RegisterInterfaces(&interface, &a2dp_interface, &vol_interface, - nullptr); + test_device->RegisterInterfaces(&interface, &a2dp_interface, &vol_interface, nullptr); // Pretend the device is active - EXPECT_CALL(a2dp_interface, active_peer()) - .WillRepeatedly(Return(test_device->GetAddress())); + EXPECT_CALL(a2dp_interface, active_peer()).WillRepeatedly(Return(test_device->GetAddress())); - auto reg_notif = - RegisterNotificationRequestBuilder::MakeBuilder(Event::VOLUME_CHANGED, 0); - EXPECT_CALL(response_cb, Call(_, false, matchPacket(std::move(reg_notif)))) - .Times(1); + auto reg_notif = RegisterNotificationRequestBuilder::MakeBuilder(Event::VOLUME_CHANGED, 0); + EXPECT_CALL(response_cb, Call(_, false, matchPacket(std::move(reg_notif)))).Times(1); test_device->RegisterVolumeChanged(); EXPECT_CALL(vol_interface, DeviceConnected(test_device->GetAddress(), _)) - .Times(1) - .WillOnce(InvokeCb<1>(0x30)); + .Times(1) + .WillOnce(InvokeCb<1>(0x30)); auto set_vol = SetAbsoluteVolumeRequestBuilder::MakeBuilder(0x30); - EXPECT_CALL(response_cb, Call(_, false, matchPacket(std::move(set_vol)))) - .Times(1); + EXPECT_CALL(response_cb, Call(_, false, matchPacket(std::move(set_vol)))).Times(1); auto response = TestAvrcpPacket::Make(interim_volume_changed_notification); SendMessage(1, response); EXPECT_CALL(vol_interface, SetVolume(0x47)).Times(1); - auto reg_notif2 = - RegisterNotificationRequestBuilder::MakeBuilder(Event::VOLUME_CHANGED, 0); - EXPECT_CALL(response_cb, Call(_, false, matchPacket(std::move(reg_notif2)))) - .Times(1); + auto reg_notif2 = RegisterNotificationRequestBuilder::MakeBuilder(Event::VOLUME_CHANGED, 0); + EXPECT_CALL(response_cb, Call(_, false, matchPacket(std::move(reg_notif2)))).Times(1); response = TestAvrcpPacket::Make(changed_volume_changed_notification); SendMessage(1, response); response = TestAvrcpPacket::Make(interim_volume_changed_notification); @@ -1409,25 +1189,20 @@ TEST_F(AvrcpDeviceTest, volumeChangedNonActiveTest) { NiceMock a2dp_interface; MockVolumeInterface vol_interface; - test_device->RegisterInterfaces(&interface, &a2dp_interface, &vol_interface, - nullptr); + test_device->RegisterInterfaces(&interface, &a2dp_interface, &vol_interface, nullptr); // Pretend the device isn't active - EXPECT_CALL(a2dp_interface, active_peer()) - .WillRepeatedly(Return(RawAddress::kEmpty)); + EXPECT_CALL(a2dp_interface, active_peer()).WillRepeatedly(Return(RawAddress::kEmpty)); - auto reg_notif = - RegisterNotificationRequestBuilder::MakeBuilder(Event::VOLUME_CHANGED, 0); - EXPECT_CALL(response_cb, Call(_, false, matchPacket(std::move(reg_notif)))) - .Times(1); + auto reg_notif = RegisterNotificationRequestBuilder::MakeBuilder(Event::VOLUME_CHANGED, 0); + EXPECT_CALL(response_cb, Call(_, false, matchPacket(std::move(reg_notif)))).Times(1); test_device->RegisterVolumeChanged(); EXPECT_CALL(vol_interface, DeviceConnected(test_device->GetAddress(), _)) - .Times(1) - .WillOnce(InvokeCb<1>(0x30)); + .Times(1) + .WillOnce(InvokeCb<1>(0x30)); auto set_vol = SetAbsoluteVolumeRequestBuilder::MakeBuilder(0x30); - EXPECT_CALL(response_cb, Call(_, false, matchPacket(std::move(set_vol)))) - .Times(1); + EXPECT_CALL(response_cb, Call(_, false, matchPacket(std::move(set_vol)))).Times(1); auto response = TestAvrcpPacket::Make(interim_volume_changed_notification); SendMessage(1, response); @@ -1435,10 +1210,8 @@ TEST_F(AvrcpDeviceTest, volumeChangedNonActiveTest) { // Ensure that SetVolume is never called EXPECT_CALL(vol_interface, SetVolume(0x47)).Times(0); - auto reg_notif2 = - RegisterNotificationRequestBuilder::MakeBuilder(Event::VOLUME_CHANGED, 0); - EXPECT_CALL(response_cb, Call(_, false, matchPacket(std::move(reg_notif2)))) - .Times(1); + auto reg_notif2 = RegisterNotificationRequestBuilder::MakeBuilder(Event::VOLUME_CHANGED, 0); + EXPECT_CALL(response_cb, Call(_, false, matchPacket(std::move(reg_notif2)))).Times(1); response = TestAvrcpPacket::Make(changed_volume_changed_notification); SendMessage(1, response); response = TestAvrcpPacket::Make(interim_volume_changed_notification); @@ -1450,13 +1223,10 @@ TEST_F(AvrcpDeviceTest, volumeRejectedTest) { NiceMock a2dp_interface; MockVolumeInterface vol_interface; - test_device->RegisterInterfaces(&interface, &a2dp_interface, &vol_interface, - nullptr); + test_device->RegisterInterfaces(&interface, &a2dp_interface, &vol_interface, nullptr); - auto reg_notif = - RegisterNotificationRequestBuilder::MakeBuilder(Event::VOLUME_CHANGED, 0); - EXPECT_CALL(response_cb, Call(_, false, matchPacket(std::move(reg_notif)))) - .Times(1); + auto reg_notif = RegisterNotificationRequestBuilder::MakeBuilder(Event::VOLUME_CHANGED, 0); + EXPECT_CALL(response_cb, Call(_, false, matchPacket(std::move(reg_notif)))).Times(1); test_device->RegisterVolumeChanged(); auto response = TestAvrcpPacket::Make(rejected_volume_changed_notification); @@ -1471,8 +1241,7 @@ TEST_F(AvrcpDeviceTest, setVolumeOnceTest) { auto set_abs_vol = SetAbsoluteVolumeRequestBuilder::MakeBuilder(vol); // Ensure that SetVolume only been call once. - EXPECT_CALL(response_cb, Call(_, false, matchPacket(std::move(set_abs_vol)))) - .Times(1); + EXPECT_CALL(response_cb, Call(_, false, matchPacket(std::move(set_abs_vol)))).Times(1); test_device->SetVolume(vol); test_device->SetVolume(vol); @@ -1485,8 +1254,7 @@ TEST_F(AvrcpDeviceTest, setVolumeAfterReconnectionTest) { // Ensure that SetVolume is called twice as DeviceDisconnected will // reset the previous stored volume. - EXPECT_CALL(response_cb, Call(_, false, matchPacket(std::move(set_abs_vol)))) - .Times(2); + EXPECT_CALL(response_cb, Call(_, false, matchPacket(std::move(set_abs_vol)))).Times(2); test_device->SetVolume(vol); test_device->DeviceDisconnected(); @@ -1498,24 +1266,17 @@ TEST_F(AvrcpDeviceTest, playPushedActiveDeviceTest) { NiceMock a2dp_interface; MockVolumeInterface vol_interface; - test_device->RegisterInterfaces(&interface, &a2dp_interface, &vol_interface, - nullptr); + test_device->RegisterInterfaces(&interface, &a2dp_interface, &vol_interface, nullptr); // Pretend the device is active - EXPECT_CALL(a2dp_interface, active_peer()) - .WillRepeatedly(Return(test_device->GetAddress())); + EXPECT_CALL(a2dp_interface, active_peer()).WillRepeatedly(Return(test_device->GetAddress())); auto play_pushed = PassThroughPacketBuilder::MakeBuilder(false, true, 0x44); - auto play_pushed_response = - PassThroughPacketBuilder::MakeBuilder(true, true, 0x44); - EXPECT_CALL(response_cb, - Call(_, false, matchPacket(std::move(play_pushed_response)))) - .Times(1); + auto play_pushed_response = PassThroughPacketBuilder::MakeBuilder(true, true, 0x44); + EXPECT_CALL(response_cb, Call(_, false, matchPacket(std::move(play_pushed_response)))).Times(1); PlayStatus status = {0x1234, 0x5678, PlayState::PLAYING}; - EXPECT_CALL(interface, GetPlayStatus(_)) - .Times(1) - .WillOnce(InvokeCb<0>(status)); + EXPECT_CALL(interface, GetPlayStatus(_)).Times(1).WillOnce(InvokeCb<0>(status)); EXPECT_CALL(interface, SendKeyEvent(0x44, KeyState::PUSHED)).Times(1); @@ -1530,28 +1291,21 @@ TEST_F(AvrcpDeviceTest, playPushedInactiveDeviceTest) { NiceMock a2dp_interface; MockVolumeInterface vol_interface; - test_device->RegisterInterfaces(&interface, &a2dp_interface, &vol_interface, - nullptr); + test_device->RegisterInterfaces(&interface, &a2dp_interface, &vol_interface, nullptr); // Pretend the device is not active - EXPECT_CALL(a2dp_interface, active_peer()) - .WillRepeatedly(Return(RawAddress::kEmpty)); + EXPECT_CALL(a2dp_interface, active_peer()).WillRepeatedly(Return(RawAddress::kEmpty)); auto play_pushed = PassThroughPacketBuilder::MakeBuilder(false, true, 0x44); - auto play_pushed_response = - PassThroughPacketBuilder::MakeBuilder(true, true, 0x44); - EXPECT_CALL(response_cb, - Call(_, false, matchPacket(std::move(play_pushed_response)))) - .Times(1); + auto play_pushed_response = PassThroughPacketBuilder::MakeBuilder(true, true, 0x44); + EXPECT_CALL(response_cb, Call(_, false, matchPacket(std::move(play_pushed_response)))).Times(1); // Expect that the device will try to set itself as active EXPECT_CALL(interface, SetActiveDevice(test_device->GetAddress())).Times(1); // No play command should be sent since the music is already playing PlayStatus status = {0x1234, 0x5678, PlayState::PLAYING}; - EXPECT_CALL(interface, GetPlayStatus(_)) - .Times(1) - .WillOnce(InvokeCb<0>(status)); + EXPECT_CALL(interface, GetPlayStatus(_)).Times(1).WillOnce(InvokeCb<0>(status)); EXPECT_CALL(interface, SendKeyEvent(0x44, KeyState::PUSHED)).Times(0); auto play_pushed_pkt = TestAvrcpPacket::Make(); @@ -1565,20 +1319,14 @@ TEST_F(AvrcpDeviceTest, mediaKeyActiveDeviceTest) { NiceMock a2dp_interface; MockVolumeInterface vol_interface; - test_device->RegisterInterfaces(&interface, &a2dp_interface, &vol_interface, - nullptr); + test_device->RegisterInterfaces(&interface, &a2dp_interface, &vol_interface, nullptr); // Pretend the device is active - EXPECT_CALL(a2dp_interface, active_peer()) - .WillRepeatedly(Return(test_device->GetAddress())); + EXPECT_CALL(a2dp_interface, active_peer()).WillRepeatedly(Return(test_device->GetAddress())); - auto play_released = - PassThroughPacketBuilder::MakeBuilder(false, false, 0x44); - auto play_released_response = - PassThroughPacketBuilder::MakeBuilder(true, false, 0x44); - EXPECT_CALL(response_cb, - Call(_, false, matchPacket(std::move(play_released_response)))) - .Times(1); + auto play_released = PassThroughPacketBuilder::MakeBuilder(false, false, 0x44); + auto play_released_response = PassThroughPacketBuilder::MakeBuilder(true, false, 0x44); + EXPECT_CALL(response_cb, Call(_, false, matchPacket(std::move(play_released_response)))).Times(1); EXPECT_CALL(interface, GetPlayStatus(_)).Times(0); @@ -1595,20 +1343,14 @@ TEST_F(AvrcpDeviceTest, mediaKeyInactiveDeviceTest) { NiceMock a2dp_interface; MockVolumeInterface vol_interface; - test_device->RegisterInterfaces(&interface, &a2dp_interface, &vol_interface, - nullptr); + test_device->RegisterInterfaces(&interface, &a2dp_interface, &vol_interface, nullptr); // Pretend the device is not active - EXPECT_CALL(a2dp_interface, active_peer()) - .WillRepeatedly(Return(RawAddress::kEmpty)); + EXPECT_CALL(a2dp_interface, active_peer()).WillRepeatedly(Return(RawAddress::kEmpty)); - auto play_released = - PassThroughPacketBuilder::MakeBuilder(false, false, 0x44); - auto play_released_response = - PassThroughPacketBuilder::MakeBuilder(true, false, 0x44); - EXPECT_CALL(response_cb, - Call(_, false, matchPacket(std::move(play_released_response)))) - .Times(1); + auto play_released = PassThroughPacketBuilder::MakeBuilder(false, false, 0x44); + auto play_released_response = PassThroughPacketBuilder::MakeBuilder(true, false, 0x44); + EXPECT_CALL(response_cb, Call(_, false, matchPacket(std::move(play_released_response)))).Times(1); EXPECT_CALL(interface, GetPlayStatus(_)).Times(0); @@ -1626,50 +1368,40 @@ TEST_F(AvrcpDeviceTest, getCapabilitiesTest) { NiceMock a2dp_interface; MockPlayerSettingsInterface player_settings_interface; - test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, - &player_settings_interface); + test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, &player_settings_interface); // GetCapabilities with CapabilityID COMPANY_ID - auto request_company_id_response = - GetCapabilitiesResponseBuilder::MakeCompanyIdBuilder(0x001958); + auto request_company_id_response = GetCapabilitiesResponseBuilder::MakeCompanyIdBuilder(0x001958); request_company_id_response->AddCompanyId(0x002345); - EXPECT_CALL( - response_cb, - Call(1, false, matchPacket(std::move(request_company_id_response)))) - .Times(1); + EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(request_company_id_response)))) + .Times(1); - auto request_company_id = - TestAvrcpPacket::Make(get_capabilities_request_company_id); + auto request_company_id = TestAvrcpPacket::Make(get_capabilities_request_company_id); SendMessage(1, request_company_id); // GetCapabilities with CapabilityID EVENTS_SUPPORTED auto request_events_supported_response = - GetCapabilitiesResponseBuilder::MakeEventsSupportedBuilder( - Event::PLAYBACK_STATUS_CHANGED); + GetCapabilitiesResponseBuilder::MakeEventsSupportedBuilder( + Event::PLAYBACK_STATUS_CHANGED); request_events_supported_response->AddEvent(Event::TRACK_CHANGED); request_events_supported_response->AddEvent(Event::PLAYBACK_POS_CHANGED); - request_events_supported_response->AddEvent( - Event::PLAYER_APPLICATION_SETTING_CHANGED); + request_events_supported_response->AddEvent(Event::PLAYER_APPLICATION_SETTING_CHANGED); - EXPECT_CALL( - response_cb, - Call(2, false, matchPacket(std::move(request_events_supported_response)))) - .Times(1); + EXPECT_CALL(response_cb, + Call(2, false, matchPacket(std::move(request_events_supported_response)))) + .Times(1); - auto request_events_supported = - TestAvrcpPacket::Make(get_capabilities_request); + auto request_events_supported = TestAvrcpPacket::Make(get_capabilities_request); SendMessage(2, request_events_supported); // GetCapabilities with CapabilityID UNKNOWN - auto request_unknown_response = RejectBuilder::MakeBuilder( - CommandPdu::GET_CAPABILITIES, Status::INVALID_PARAMETER); + auto request_unknown_response = + RejectBuilder::MakeBuilder(CommandPdu::GET_CAPABILITIES, Status::INVALID_PARAMETER); - EXPECT_CALL(response_cb, - Call(3, false, matchPacket(std::move(request_unknown_response)))) - .Times(1); + EXPECT_CALL(response_cb, Call(3, false, matchPacket(std::move(request_unknown_response)))) + .Times(1); - auto request_unknown = - TestAvrcpPacket::Make(get_capabilities_request_unknown); + auto request_unknown = TestAvrcpPacket::Make(get_capabilities_request_unknown); SendMessage(3, request_unknown); } @@ -1677,48 +1409,39 @@ TEST_F(AvrcpDeviceTest, getCapabilitiesPlayerSettingsNotSupportedTest) { MockMediaInterface interface; NiceMock a2dp_interface; - test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, - nullptr); + test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, nullptr); // GetCapabilities with CapabilityID COMPANY_ID - auto request_company_id_response = - GetCapabilitiesResponseBuilder::MakeCompanyIdBuilder(0x001958); + auto request_company_id_response = GetCapabilitiesResponseBuilder::MakeCompanyIdBuilder(0x001958); request_company_id_response->AddCompanyId(0x002345); - EXPECT_CALL( - response_cb, - Call(1, false, matchPacket(std::move(request_company_id_response)))) - .Times(1); + EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(request_company_id_response)))) + .Times(1); - auto request_company_id = - TestAvrcpPacket::Make(get_capabilities_request_company_id); + auto request_company_id = TestAvrcpPacket::Make(get_capabilities_request_company_id); SendMessage(1, request_company_id); // GetCapabilities with CapabilityID EVENTS_SUPPORTED auto request_events_supported_response = - GetCapabilitiesResponseBuilder::MakeEventsSupportedBuilder( - Event::PLAYBACK_STATUS_CHANGED); + GetCapabilitiesResponseBuilder::MakeEventsSupportedBuilder( + Event::PLAYBACK_STATUS_CHANGED); request_events_supported_response->AddEvent(Event::TRACK_CHANGED); request_events_supported_response->AddEvent(Event::PLAYBACK_POS_CHANGED); - EXPECT_CALL( - response_cb, - Call(2, false, matchPacket(std::move(request_events_supported_response)))) - .Times(1); + EXPECT_CALL(response_cb, + Call(2, false, matchPacket(std::move(request_events_supported_response)))) + .Times(1); - auto request_events_supported = - TestAvrcpPacket::Make(get_capabilities_request); + auto request_events_supported = TestAvrcpPacket::Make(get_capabilities_request); SendMessage(2, request_events_supported); // GetCapabilities with CapabilityID UNKNOWN - auto request_unknown_response = RejectBuilder::MakeBuilder( - CommandPdu::GET_CAPABILITIES, Status::INVALID_PARAMETER); + auto request_unknown_response = + RejectBuilder::MakeBuilder(CommandPdu::GET_CAPABILITIES, Status::INVALID_PARAMETER); - EXPECT_CALL(response_cb, - Call(3, false, matchPacket(std::move(request_unknown_response)))) - .Times(1); + EXPECT_CALL(response_cb, Call(3, false, matchPacket(std::move(request_unknown_response)))) + .Times(1); - auto request_unknown = - TestAvrcpPacket::Make(get_capabilities_request_unknown); + auto request_unknown = TestAvrcpPacket::Make(get_capabilities_request_unknown); SendMessage(3, request_unknown); } @@ -1726,8 +1449,7 @@ TEST_F(AvrcpDeviceTest, getInvalidItemAttributesTest) { MockMediaInterface interface; NiceMock a2dp_interface; - test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, - nullptr); + test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, nullptr); SongInfo info = {"test_id", {// The attribute map @@ -1740,11 +1462,10 @@ TEST_F(AvrcpDeviceTest, getInvalidItemAttributesTest) { AttributeEntry(Attribute::PLAYING_TIME, "1000")}}; std::vector list = {info}; - EXPECT_CALL(interface, GetNowPlayingList(_)) - .WillRepeatedly(InvokeCb<0>("test_id", list)); + EXPECT_CALL(interface, GetNowPlayingList(_)).WillRepeatedly(InvokeCb<0>("test_id", list)); - auto compare_to_full = GetItemAttributesResponseBuilder::MakeBuilder( - Status::UIDS_CHANGED, 0xFFFF); + auto compare_to_full = + GetItemAttributesResponseBuilder::MakeBuilder(Status::UIDS_CHANGED, 0xFFFF); compare_to_full->AddAttributeEntry(Attribute::TITLE, "Test Song"); compare_to_full->AddAttributeEntry(Attribute::ARTIST_NAME, "Test Artist"); compare_to_full->AddAttributeEntry(Attribute::ALBUM_NAME, "Test Album"); @@ -1753,12 +1474,9 @@ TEST_F(AvrcpDeviceTest, getInvalidItemAttributesTest) { compare_to_full->AddAttributeEntry(Attribute::GENRE, "Test Genre"); compare_to_full->AddAttributeEntry(Attribute::PLAYING_TIME, "1000"); compare_to_full->AddAttributeEntry(Attribute::DEFAULT_COVER_ART, "0000001"); - EXPECT_CALL(response_cb, - Call(1, true, matchPacket(std::move(compare_to_full)))) - .Times(1); + EXPECT_CALL(response_cb, Call(1, true, matchPacket(std::move(compare_to_full)))).Times(1); - auto request = TestBrowsePacket::Make( - get_item_attributes_request_all_attributes_invalid); + auto request = TestBrowsePacket::Make(get_item_attributes_request_all_attributes_invalid); SendBrowseMessage(1, request); } @@ -1766,26 +1484,20 @@ TEST_F(AvrcpDeviceTest, listPlayerSettingsTest) { MockMediaInterface interface; NiceMock a2dp_interface; MockPlayerSettingsInterface player_settings_interface; - std::vector attributes = {PlayerAttribute::REPEAT, - PlayerAttribute::SHUFFLE}; + std::vector attributes = {PlayerAttribute::REPEAT, PlayerAttribute::SHUFFLE}; - test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, - &player_settings_interface); + test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, &player_settings_interface); EXPECT_CALL(player_settings_interface, ListPlayerSettings(_)) - .WillRepeatedly(InvokeCb<0>(attributes)); + .WillRepeatedly(InvokeCb<0>(attributes)); auto player_settings_list_response = - ListPlayerApplicationSettingAttributesResponseBuilder::MakeBuilder( - attributes); + ListPlayerApplicationSettingAttributesResponseBuilder::MakeBuilder(attributes); - EXPECT_CALL( - response_cb, - Call(1, false, matchPacket(std::move(player_settings_list_response)))) - .Times(1); + EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(player_settings_list_response)))) + .Times(1); - auto request = - TestAvrcpPacket::Make(list_player_application_setting_attributes_request); + auto request = TestAvrcpPacket::Make(list_player_application_setting_attributes_request); SendMessage(1, request); } @@ -1793,18 +1505,14 @@ TEST_F(AvrcpDeviceTest, listPlayerSettingsNotSupportedTest) { MockMediaInterface interface; NiceMock a2dp_interface; - test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, - nullptr); + test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, nullptr); - auto response = RejectBuilder::MakeBuilder( - CommandPdu::LIST_PLAYER_APPLICATION_SETTING_ATTRIBUTES, - Status::INVALID_COMMAND); + auto response = RejectBuilder::MakeBuilder(CommandPdu::LIST_PLAYER_APPLICATION_SETTING_ATTRIBUTES, + Status::INVALID_COMMAND); - EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(response)))) - .Times(1); + EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(response)))).Times(1); - auto request = - TestAvrcpPacket::Make(list_player_application_setting_attributes_request); + auto request = TestAvrcpPacket::Make(list_player_application_setting_attributes_request); SendMessage(1, request); } @@ -1813,30 +1521,24 @@ TEST_F(AvrcpDeviceTest, listPlayerSettingValuesTest) { NiceMock a2dp_interface; MockPlayerSettingsInterface player_settings_interface; PlayerAttribute attribute = PlayerAttribute::REPEAT; - std::vector attribute_values = { - static_cast(PlayerRepeatValue::OFF), - static_cast(PlayerRepeatValue::SINGLE), - static_cast(PlayerRepeatValue::ALL), - static_cast(PlayerRepeatValue::GROUP)}; + std::vector attribute_values = {static_cast(PlayerRepeatValue::OFF), + static_cast(PlayerRepeatValue::SINGLE), + static_cast(PlayerRepeatValue::ALL), + static_cast(PlayerRepeatValue::GROUP)}; - test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, - &player_settings_interface); + test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, &player_settings_interface); EXPECT_CALL(player_settings_interface, ListPlayerSettingValues(attribute, _)) - .WillRepeatedly(InvokeCb<1>(attribute, attribute_values)); + .WillRepeatedly(InvokeCb<1>(attribute, attribute_values)); auto player_settings_list_values_response = - ListPlayerApplicationSettingValuesResponseBuilder::MakeBuilder( - attribute_values); + ListPlayerApplicationSettingValuesResponseBuilder::MakeBuilder(attribute_values); - EXPECT_CALL( - response_cb, - Call(1, false, - matchPacket(std::move(player_settings_list_values_response)))) - .Times(1); + EXPECT_CALL(response_cb, + Call(1, false, matchPacket(std::move(player_settings_list_values_response)))) + .Times(1); - auto request = TestAvrcpPacket::Make( - list_player_application_setting_attribute_values_request); + auto request = TestAvrcpPacket::Make(list_player_application_setting_attribute_values_request); SendMessage(1, request); } @@ -1844,18 +1546,14 @@ TEST_F(AvrcpDeviceTest, listPlayerSettingValuesNotSupportedTest) { MockMediaInterface interface; NiceMock a2dp_interface; - test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, - nullptr); + test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, nullptr); - auto response = RejectBuilder::MakeBuilder( - CommandPdu::LIST_PLAYER_APPLICATION_SETTING_VALUES, - Status::INVALID_COMMAND); + auto response = RejectBuilder::MakeBuilder(CommandPdu::LIST_PLAYER_APPLICATION_SETTING_VALUES, + Status::INVALID_COMMAND); - EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(response)))) - .Times(1); + EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(response)))).Times(1); - auto request = TestAvrcpPacket::Make( - list_player_application_setting_attribute_values_request); + auto request = TestAvrcpPacket::Make(list_player_application_setting_attribute_values_request); SendMessage(1, request); } @@ -1864,17 +1562,14 @@ TEST_F(AvrcpDeviceTest, invalidSettingListPlayerSettingValuesTest) { NiceMock a2dp_interface; MockPlayerSettingsInterface player_settings_interface; - test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, - &player_settings_interface); + test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, &player_settings_interface); - auto rej_rsp = RejectBuilder::MakeBuilder( - CommandPdu::LIST_PLAYER_APPLICATION_SETTING_VALUES, - Status::INVALID_PARAMETER); - EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(rej_rsp)))) - .Times(1); + auto rej_rsp = RejectBuilder::MakeBuilder(CommandPdu::LIST_PLAYER_APPLICATION_SETTING_VALUES, + Status::INVALID_PARAMETER); + EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(rej_rsp)))).Times(1); auto list_values_request = TestAvrcpPacket::Make( - invalid_setting_list_player_application_setting_attribute_values_request); + invalid_setting_list_player_application_setting_attribute_values_request); SendMessage(1, list_values_request); } @@ -1883,17 +1578,14 @@ TEST_F(AvrcpDeviceTest, invalidLengthListPlayerSettingValuesTest) { NiceMock a2dp_interface; MockPlayerSettingsInterface player_settings_interface; - test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, - &player_settings_interface); + test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, &player_settings_interface); - auto rej_rsp = RejectBuilder::MakeBuilder( - CommandPdu::LIST_PLAYER_APPLICATION_SETTING_VALUES, - Status::INVALID_PARAMETER); - EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(rej_rsp)))) - .Times(1); + auto rej_rsp = RejectBuilder::MakeBuilder(CommandPdu::LIST_PLAYER_APPLICATION_SETTING_VALUES, + Status::INVALID_PARAMETER); + EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(rej_rsp)))).Times(1); auto list_values_request = TestAvrcpPacket::Make( - invalid_length_list_player_application_setting_attribute_values_request); + invalid_length_list_player_application_setting_attribute_values_request); SendMessage(1, list_values_request); } @@ -1901,91 +1593,71 @@ TEST_F(AvrcpDeviceTest, getCurrentPlayerApplicationSettingValueTest) { MockMediaInterface interface; NiceMock a2dp_interface; MockPlayerSettingsInterface player_settings_interface; - std::vector attributes = {PlayerAttribute::REPEAT, - PlayerAttribute::SHUFFLE}; - std::vector attributes_values = { - static_cast(PlayerRepeatValue::OFF), - static_cast(PlayerShuffleValue::OFF)}; + std::vector attributes = {PlayerAttribute::REPEAT, PlayerAttribute::SHUFFLE}; + std::vector attributes_values = {static_cast(PlayerRepeatValue::OFF), + static_cast(PlayerShuffleValue::OFF)}; - test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, - &player_settings_interface); + test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, &player_settings_interface); - EXPECT_CALL(player_settings_interface, - GetCurrentPlayerSettingValue(attributes, _)) - .WillRepeatedly(InvokeCb<1>(attributes, attributes_values)); + EXPECT_CALL(player_settings_interface, GetCurrentPlayerSettingValue(attributes, _)) + .WillRepeatedly(InvokeCb<1>(attributes, attributes_values)); auto player_settings_get_current_values_response = - GetCurrentPlayerApplicationSettingValueResponseBuilder::MakeBuilder( - attributes, attributes_values); + GetCurrentPlayerApplicationSettingValueResponseBuilder::MakeBuilder(attributes, + attributes_values); - EXPECT_CALL( - response_cb, - Call(1, false, - matchPacket(std::move(player_settings_get_current_values_response)))) - .Times(1); + EXPECT_CALL(response_cb, + Call(1, false, matchPacket(std::move(player_settings_get_current_values_response)))) + .Times(1); - auto request = TestAvrcpPacket::Make( - get_current_player_application_setting_value_request); + auto request = TestAvrcpPacket::Make(get_current_player_application_setting_value_request); SendMessage(1, request); } -TEST_F(AvrcpDeviceTest, - getCurrentPlayerApplicationSettingValueNotSupportedTest) { +TEST_F(AvrcpDeviceTest, getCurrentPlayerApplicationSettingValueNotSupportedTest) { MockMediaInterface interface; NiceMock a2dp_interface; - test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, - nullptr); + test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, nullptr); auto response = RejectBuilder::MakeBuilder( - CommandPdu::GET_CURRENT_PLAYER_APPLICATION_SETTING_VALUE, - Status::INVALID_COMMAND); + CommandPdu::GET_CURRENT_PLAYER_APPLICATION_SETTING_VALUE, Status::INVALID_COMMAND); - EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(response)))) - .Times(1); + EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(response)))).Times(1); - auto request = TestAvrcpPacket::Make( - get_current_player_application_setting_value_request); + auto request = TestAvrcpPacket::Make(get_current_player_application_setting_value_request); SendMessage(1, request); } -TEST_F(AvrcpDeviceTest, - invalidSettingGetCurrentPlayerApplicationSettingValueTest) { +TEST_F(AvrcpDeviceTest, invalidSettingGetCurrentPlayerApplicationSettingValueTest) { MockMediaInterface interface; NiceMock a2dp_interface; MockPlayerSettingsInterface player_settings_interface; - test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, - &player_settings_interface); + test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, &player_settings_interface); auto rej_rsp = RejectBuilder::MakeBuilder( - CommandPdu::GET_CURRENT_PLAYER_APPLICATION_SETTING_VALUE, - Status::INVALID_PARAMETER); - EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(rej_rsp)))) - .Times(1); + CommandPdu::GET_CURRENT_PLAYER_APPLICATION_SETTING_VALUE, Status::INVALID_PARAMETER); + EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(rej_rsp)))).Times(1); auto request = TestAvrcpPacket::Make( - invalid_setting_get_current_player_application_setting_value_request); + invalid_setting_get_current_player_application_setting_value_request); SendMessage(1, request); } -TEST_F(AvrcpDeviceTest, - invalidLengthGetCurrentPlayerApplicationSettingValueTest) { +TEST_F(AvrcpDeviceTest, invalidLengthGetCurrentPlayerApplicationSettingValueTest) { MockMediaInterface interface; NiceMock a2dp_interface; MockPlayerSettingsInterface player_settings_interface; - test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, - &player_settings_interface); + test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, &player_settings_interface); auto rej_rsp = RejectBuilder::MakeBuilder( - CommandPdu::GET_CURRENT_PLAYER_APPLICATION_SETTING_VALUE, - Status::INVALID_PARAMETER); - EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(rej_rsp)))) - .Times(1); + CommandPdu::GET_CURRENT_PLAYER_APPLICATION_SETTING_VALUE, Status::INVALID_PARAMETER); + EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(rej_rsp)))).Times(1); auto request = TestAvrcpPacket::Make( - invalid_length_get_current_player_application_setting_value_request); + invalid_length_get_current_player_application_setting_value_request); SendMessage(1, request); } @@ -1993,29 +1665,22 @@ TEST_F(AvrcpDeviceTest, setPlayerApplicationSettingValueTest) { MockMediaInterface interface; NiceMock a2dp_interface; MockPlayerSettingsInterface player_settings_interface; - std::vector attributes = {PlayerAttribute::REPEAT, - PlayerAttribute::SHUFFLE}; - std::vector attributes_values = { - static_cast(PlayerRepeatValue::OFF), - static_cast(PlayerShuffleValue::OFF)}; + std::vector attributes = {PlayerAttribute::REPEAT, PlayerAttribute::SHUFFLE}; + std::vector attributes_values = {static_cast(PlayerRepeatValue::OFF), + static_cast(PlayerShuffleValue::OFF)}; - test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, - &player_settings_interface); + test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, &player_settings_interface); - EXPECT_CALL(player_settings_interface, - SetPlayerSettings(attributes, attributes_values, _)) - .WillRepeatedly(InvokeCb<2>(true)); + EXPECT_CALL(player_settings_interface, SetPlayerSettings(attributes, attributes_values, _)) + .WillRepeatedly(InvokeCb<2>(true)); auto set_player_settings_response = - SetPlayerApplicationSettingValueResponseBuilder::MakeBuilder(); + SetPlayerApplicationSettingValueResponseBuilder::MakeBuilder(); - EXPECT_CALL( - response_cb, - Call(1, false, matchPacket(std::move(set_player_settings_response)))) - .Times(1); + EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(set_player_settings_response)))) + .Times(1); - auto request = - TestAvrcpPacket::Make(set_player_application_setting_value_request); + auto request = TestAvrcpPacket::Make(set_player_application_setting_value_request); SendMessage(1, request); } @@ -2023,18 +1688,14 @@ TEST_F(AvrcpDeviceTest, setPlayerApplicationSettingValueNotSupportedTest) { MockMediaInterface interface; NiceMock a2dp_interface; - test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, - nullptr); + test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, nullptr); - auto response = RejectBuilder::MakeBuilder( - CommandPdu::SET_PLAYER_APPLICATION_SETTING_VALUE, - Status::INVALID_COMMAND); + auto response = RejectBuilder::MakeBuilder(CommandPdu::SET_PLAYER_APPLICATION_SETTING_VALUE, + Status::INVALID_COMMAND); - EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(response)))) - .Times(1); + EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(response)))).Times(1); - auto request = - TestAvrcpPacket::Make(set_player_application_setting_value_request); + auto request = TestAvrcpPacket::Make(set_player_application_setting_value_request); SendMessage(1, request); } @@ -2043,17 +1704,14 @@ TEST_F(AvrcpDeviceTest, invalidSettingSetPlayerApplicationSettingValueTest) { NiceMock a2dp_interface; MockPlayerSettingsInterface player_settings_interface; - test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, - &player_settings_interface); + test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, &player_settings_interface); - auto rej_rsp = RejectBuilder::MakeBuilder( - CommandPdu::SET_PLAYER_APPLICATION_SETTING_VALUE, - Status::INVALID_PARAMETER); - EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(rej_rsp)))) - .Times(1); + auto rej_rsp = RejectBuilder::MakeBuilder(CommandPdu::SET_PLAYER_APPLICATION_SETTING_VALUE, + Status::INVALID_PARAMETER); + EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(rej_rsp)))).Times(1); - auto request = TestAvrcpPacket::Make( - invalid_setting_set_player_application_setting_value_request); + auto request = + TestAvrcpPacket::Make(invalid_setting_set_player_application_setting_value_request); SendMessage(1, request); } @@ -2062,17 +1720,13 @@ TEST_F(AvrcpDeviceTest, invalidValueSetPlayerApplicationSettingValueTest) { NiceMock a2dp_interface; MockPlayerSettingsInterface player_settings_interface; - test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, - &player_settings_interface); + test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, &player_settings_interface); - auto rej_rsp = RejectBuilder::MakeBuilder( - CommandPdu::SET_PLAYER_APPLICATION_SETTING_VALUE, - Status::INVALID_PARAMETER); - EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(rej_rsp)))) - .Times(1); + auto rej_rsp = RejectBuilder::MakeBuilder(CommandPdu::SET_PLAYER_APPLICATION_SETTING_VALUE, + Status::INVALID_PARAMETER); + EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(rej_rsp)))).Times(1); - auto request = TestAvrcpPacket::Make( - invalid_value_set_player_application_setting_value_request); + auto request = TestAvrcpPacket::Make(invalid_value_set_player_application_setting_value_request); SendMessage(1, request); } @@ -2081,17 +1735,13 @@ TEST_F(AvrcpDeviceTest, invalidLengthSetPlayerApplicationSettingValueTest) { NiceMock a2dp_interface; MockPlayerSettingsInterface player_settings_interface; - test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, - &player_settings_interface); + test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, &player_settings_interface); - auto rej_rsp = RejectBuilder::MakeBuilder( - CommandPdu::SET_PLAYER_APPLICATION_SETTING_VALUE, - Status::INVALID_PARAMETER); - EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(rej_rsp)))) - .Times(1); + auto rej_rsp = RejectBuilder::MakeBuilder(CommandPdu::SET_PLAYER_APPLICATION_SETTING_VALUE, + Status::INVALID_PARAMETER); + EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(rej_rsp)))).Times(1); - auto request = TestAvrcpPacket::Make( - invalid_length_set_player_application_setting_value_request); + auto request = TestAvrcpPacket::Make(invalid_length_set_player_application_setting_value_request); SendMessage(1, request); } @@ -2099,14 +1749,11 @@ TEST_F(AvrcpDeviceTest, invalidRegisterNotificationTest) { MockMediaInterface interface; NiceMock a2dp_interface; - test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, - nullptr); + test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, nullptr); - auto reg_notif_rej_rsp = RejectBuilder::MakeBuilder( - CommandPdu::REGISTER_NOTIFICATION, Status::INVALID_PARAMETER); - EXPECT_CALL(response_cb, - Call(1, false, matchPacket(std::move(reg_notif_rej_rsp)))) - .Times(1); + auto reg_notif_rej_rsp = + RejectBuilder::MakeBuilder(CommandPdu::REGISTER_NOTIFICATION, Status::INVALID_PARAMETER); + EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(reg_notif_rej_rsp)))).Times(1); auto reg_notif_request = TestAvrcpPacket::Make(register_notification_invalid); SendMessage(1, reg_notif_request); @@ -2116,8 +1763,7 @@ TEST_F(AvrcpDeviceTest, invalidVendorPacketTest) { MockMediaInterface interface; NiceMock a2dp_interface; - test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, - nullptr); + test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, nullptr); auto rsp = RejectBuilder::MakeBuilder(static_cast(0), Status::INVALID_COMMAND); EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(rsp)))).Times(1); @@ -2129,8 +1775,7 @@ TEST_F(AvrcpDeviceTest, invalidCapabilitiesPacketTest) { MockMediaInterface interface; NiceMock a2dp_interface; - test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, - nullptr); + test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, nullptr); auto rsp = RejectBuilder::MakeBuilder(CommandPdu::GET_CAPABILITIES, Status::INVALID_PARAMETER); EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(rsp)))).Times(1); @@ -2142,10 +1787,10 @@ TEST_F(AvrcpDeviceTest, invalidGetElementAttributesPacketTest) { MockMediaInterface interface; NiceMock a2dp_interface; - test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, - nullptr); + test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, nullptr); - auto rsp = RejectBuilder::MakeBuilder(CommandPdu::GET_ELEMENT_ATTRIBUTES, Status::INVALID_PARAMETER); + auto rsp = + RejectBuilder::MakeBuilder(CommandPdu::GET_ELEMENT_ATTRIBUTES, Status::INVALID_PARAMETER); EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(rsp)))).Times(1); auto short_packet = TestAvrcpPacket::Make(short_get_element_attributes_request); SendMessage(1, short_packet); @@ -2155,8 +1800,7 @@ TEST_F(AvrcpDeviceTest, invalidPlayItemPacketTest) { MockMediaInterface interface; NiceMock a2dp_interface; - test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, - nullptr); + test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, nullptr); auto rsp = RejectBuilder::MakeBuilder(CommandPdu::PLAY_ITEM, Status::INVALID_PARAMETER); EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(rsp)))).Times(1); @@ -2168,10 +1812,10 @@ TEST_F(AvrcpDeviceTest, invalidSetAddressedPlayerPacketTest) { MockMediaInterface interface; NiceMock a2dp_interface; - test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, - nullptr); + test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, nullptr); - auto rsp = RejectBuilder::MakeBuilder(CommandPdu::SET_ADDRESSED_PLAYER, Status::INVALID_PARAMETER); + auto rsp = + RejectBuilder::MakeBuilder(CommandPdu::SET_ADDRESSED_PLAYER, Status::INVALID_PARAMETER); EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(rsp)))).Times(1); auto short_packet = TestAvrcpPacket::Make(short_set_addressed_player_request); SendMessage(1, short_packet); @@ -2181,8 +1825,7 @@ TEST_F(AvrcpDeviceTest, invalidBrowsePacketTest) { MockMediaInterface interface; NiceMock a2dp_interface; - test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, - nullptr); + test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, nullptr); auto rsp = GeneralRejectBuilder::MakeBuilder(Status::INVALID_COMMAND); EXPECT_CALL(response_cb, Call(1, false, matchPacket(std::move(rsp)))).Times(1); @@ -2194,10 +1837,10 @@ TEST_F(AvrcpDeviceTest, invalidGetFolderItemsPacketTest) { MockMediaInterface interface; NiceMock a2dp_interface; - test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, - nullptr); + test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, nullptr); - auto rsp = GetFolderItemsResponseBuilder::MakePlayerListBuilder(Status::INVALID_PARAMETER, 0x0000, 0xFFFF); + auto rsp = GetFolderItemsResponseBuilder::MakePlayerListBuilder(Status::INVALID_PARAMETER, 0x0000, + 0xFFFF); EXPECT_CALL(response_cb, Call(1, true, matchPacket(std::move(rsp)))).Times(1); auto short_packet = TestBrowsePacket::Make(short_get_folder_items_request); SendBrowseMessage(1, short_packet); @@ -2207,10 +1850,10 @@ TEST_F(AvrcpDeviceTest, invalidGetTotalNumberOfItemsPacketTest) { MockMediaInterface interface; NiceMock a2dp_interface; - test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, - nullptr); + test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, nullptr); - auto rsp = GetTotalNumberOfItemsResponseBuilder::MakeBuilder(Status::INVALID_PARAMETER, 0x0000, 0xFFFF); + auto rsp = GetTotalNumberOfItemsResponseBuilder::MakeBuilder(Status::INVALID_PARAMETER, 0x0000, + 0xFFFF); EXPECT_CALL(response_cb, Call(1, true, matchPacket(std::move(rsp)))).Times(1); auto short_packet = TestBrowsePacket::Make(short_get_total_number_of_items_request); SendBrowseMessage(1, short_packet); @@ -2220,8 +1863,7 @@ TEST_F(AvrcpDeviceTest, invalidChangePathPacketTest) { MockMediaInterface interface; NiceMock a2dp_interface; - test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, - nullptr); + test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, nullptr); auto rsp = ChangePathResponseBuilder::MakeBuilder(Status::INVALID_PARAMETER, 0); EXPECT_CALL(response_cb, Call(1, true, matchPacket(std::move(rsp)))).Times(1); @@ -2233,8 +1875,7 @@ TEST_F(AvrcpDeviceTest, invalidGetItemAttributesPacketTest) { MockMediaInterface interface; NiceMock a2dp_interface; - test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, - nullptr); + test_device->RegisterInterfaces(&interface, &a2dp_interface, nullptr, nullptr); auto rsp = GetItemAttributesResponseBuilder::MakeBuilder(Status::INVALID_PARAMETER, 0xFFFF); EXPECT_CALL(response_cb, Call(1, true, matchPacket(std::move(rsp)))).Times(1); @@ -2245,6 +1886,4 @@ TEST_F(AvrcpDeviceTest, invalidGetItemAttributesPacketTest) { } // namespace avrcp } // namespace bluetooth -const stack_config_t* stack_config_get_interface(void) { - return &bluetooth::avrcp::interface; -} +const stack_config_t* stack_config_get_interface(void) { return &bluetooth::avrcp::interface; } diff --git a/system/profile/avrcp/tests/avrcp_test_helper.h b/system/profile/avrcp/tests/avrcp_test_helper.h index 2a3064d5d24..91d076e99a1 100644 --- a/system/profile/avrcp/tests/avrcp_test_helper.h +++ b/system/profile/avrcp/tests/avrcp_test_helper.h @@ -37,16 +37,14 @@ using TestAvrcpPacket = TestPacketType; using TestBrowsePacket = TestPacketType; class MockMediaInterface : public MediaInterface { - public: +public: MOCK_METHOD2(SendKeyEvent, void(uint8_t, KeyState)); MOCK_METHOD1(GetSongInfo, void(MediaInterface::SongInfoCallback)); MOCK_METHOD1(GetPlayStatus, void(MediaInterface::PlayStatusCallback)); MOCK_METHOD1(GetNowPlayingList, void(MediaInterface::NowPlayingCallback)); MOCK_METHOD1(GetMediaPlayerList, void(MediaInterface::MediaListCallback)); - MOCK_METHOD3(GetFolderItems, void(uint16_t, std::string, - MediaInterface::FolderItemsCallback)); - MOCK_METHOD2(SetBrowsedPlayer, - void(uint16_t, MediaInterface::SetBrowsedPlayerCallback)); + MOCK_METHOD3(GetFolderItems, void(uint16_t, std::string, MediaInterface::FolderItemsCallback)); + MOCK_METHOD2(SetBrowsedPlayer, void(uint16_t, MediaInterface::SetBrowsedPlayerCallback)); MOCK_METHOD3(PlayItem, void(uint16_t, bool, std::string)); MOCK_METHOD1(SetActiveDevice, void(const RawAddress&)); MOCK_METHOD1(RegisterUpdateCallback, void(MediaCallbacks*)); @@ -54,7 +52,7 @@ class MockMediaInterface : public MediaInterface { }; class MockVolumeInterface : public VolumeInterface { - public: +public: MOCK_METHOD1(DeviceConnected, void(const RawAddress&)); MOCK_METHOD2(DeviceConnected, void(const RawAddress&, VolumeChangedCb)); MOCK_METHOD1(DeviceDisconnected, void(const RawAddress&)); @@ -62,26 +60,23 @@ class MockVolumeInterface : public VolumeInterface { }; class MockPlayerSettingsInterface : public PlayerSettingsInterface { - public: +public: MOCK_METHOD1(ListPlayerSettings, void(ListPlayerSettingsCallback)); - MOCK_METHOD2(ListPlayerSettingValues, - void(PlayerAttribute, ListPlayerSettingValuesCallback)); + MOCK_METHOD2(ListPlayerSettingValues, void(PlayerAttribute, ListPlayerSettingValuesCallback)); MOCK_METHOD2(GetCurrentPlayerSettingValue, - void(std::vector, - GetCurrentPlayerSettingValueCallback)); - MOCK_METHOD3(SetPlayerSettings, - void(std::vector, std::vector, - SetPlayerSettingValueCallback)); + void(std::vector, GetCurrentPlayerSettingValueCallback)); + MOCK_METHOD3(SetPlayerSettings, void(std::vector, std::vector, + SetPlayerSettingValueCallback)); }; class MockAvrcpInterface : public AvrcpInterface { - public: +public: MOCK_METHOD0(GetAvrcpVersion, uint16_t(void)); - MOCK_METHOD8(AddRecord, uint16_t(uint16_t, const char*, const char*, uint16_t, - uint32_t, bool, uint16_t, uint16_t)); + MOCK_METHOD8(AddRecord, uint16_t(uint16_t, const char*, const char*, uint16_t, uint32_t, bool, + uint16_t, uint16_t)); MOCK_METHOD1(RemoveRecord, uint16_t(uint32_t)); - MOCK_METHOD4(FindService, uint16_t(uint16_t, const RawAddress&, - tAVRC_SDP_DB_PARAMS*, tAVRC_FIND_CBACK)); + MOCK_METHOD4(FindService, + uint16_t(uint16_t, const RawAddress&, tAVRC_SDP_DB_PARAMS*, tAVRC_FIND_CBACK)); MOCK_METHOD3(Open, uint16_t(uint8_t*, tAVRC_CONN_CB*, const RawAddress&)); MOCK_METHOD2(OpenBrowse, uint16_t(uint8_t, uint8_t)); MOCK_METHOD1(GetPeerMtu, uint16_t(uint8_t)); @@ -93,55 +88,47 @@ class MockAvrcpInterface : public AvrcpInterface { }; class MockA2dpInterface : public A2dpInterface { - public: +public: MOCK_METHOD1(event_open, void(const RawAddress&)); MOCK_METHOD1(event_close, void(const RawAddress&)); MOCK_METHOD0(active_peer, RawAddress()); MOCK_METHOD1(is_peer_in_silence_mode, bool(const RawAddress&)); MOCK_METHOD2(connect_audio_sink_delayed, void(uint8_t, const RawAddress&)); - MOCK_METHOD2(find_audio_sink_service, - uint16_t(const RawAddress&, tA2DP_FIND_CBACK)); + MOCK_METHOD2(find_audio_sink_service, uint16_t(const RawAddress&, tA2DP_FIND_CBACK)); }; class MockSdpInterface : public SdpInterface { - public: - MOCK_METHOD6(InitDiscoveryDb, - bool(tSDP_DISCOVERY_DB*, uint32_t, uint16_t, - const bluetooth::Uuid*, uint16_t, uint16_t*)); +public: + MOCK_METHOD6(InitDiscoveryDb, bool(tSDP_DISCOVERY_DB*, uint32_t, uint16_t, const bluetooth::Uuid*, + uint16_t, uint16_t*)); MOCK_METHOD3(ServiceSearchAttributeRequest, bool(const RawAddress&, tSDP_DISCOVERY_DB*, tSDP_DISC_CMPL_CB*)); - MOCK_METHOD3(FindServiceInDb, - tSDP_DISC_REC*(tSDP_DISCOVERY_DB*, uint16_t, t_sdp_disc_rec*)); + MOCK_METHOD3(FindServiceInDb, tSDP_DISC_REC*(tSDP_DISCOVERY_DB*, uint16_t, t_sdp_disc_rec*)); MOCK_METHOD2(FindAttributeInRec, tSDP_DISC_ATTR*(t_sdp_disc_rec*, uint16_t)); - MOCK_METHOD3(FindProfileVersionInRec, - bool(t_sdp_disc_rec*, uint16_t, uint16_t*)); + MOCK_METHOD3(FindProfileVersionInRec, bool(t_sdp_disc_rec*, uint16_t, uint16_t*)); }; -ACTION_TEMPLATE(InvokeCb, HAS_1_TEMPLATE_PARAMS(int, k), - AND_1_VALUE_PARAMS(input)) { +ACTION_TEMPLATE(InvokeCb, HAS_1_TEMPLATE_PARAMS(int, k), AND_1_VALUE_PARAMS(input)) { ::testing::get(args).Run(input); } -ACTION_TEMPLATE(InvokeCb, HAS_1_TEMPLATE_PARAMS(int, k), - AND_2_VALUE_PARAMS(a, b)) { +ACTION_TEMPLATE(InvokeCb, HAS_1_TEMPLATE_PARAMS(int, k), AND_2_VALUE_PARAMS(a, b)) { ::testing::get(args).Run(a, b); } -ACTION_TEMPLATE(InvokeCb, HAS_1_TEMPLATE_PARAMS(int, k), - AND_3_VALUE_PARAMS(a, b, c)) { +ACTION_TEMPLATE(InvokeCb, HAS_1_TEMPLATE_PARAMS(int, k), AND_3_VALUE_PARAMS(a, b, c)) { ::testing::get(args).Run(a, b, c); } template class PacketMatcher : public ::testing::MatcherInterface { - public: +public: AvrcpResponse pkt_to_compare_to_; PacketMatcher(AvrcpResponse&& pkt) { pkt_to_compare_to_ = std::move(pkt); } - bool MatchAndExplain( - const AvrcpResponse& r, - ::testing::MatchResultListener* listener) const override { + bool MatchAndExplain(const AvrcpResponse& r, + ::testing::MatchResultListener* listener) const override { auto packet1 = TestPacketType::Make(); r->Serialize(packet1); @@ -161,13 +148,12 @@ class PacketMatcher : public ::testing::MatcherInterface { void DescribeTo(::std::ostream* os) const override { *os << "Packets match"; } }; -inline ::testing::Matcher matchPacket( - std::unique_ptr&& arg) { +inline ::testing::Matcher matchPacket(std::unique_ptr&& arg) { return MakeMatcher(new PacketMatcher(std::move(arg))); } inline ::testing::Matcher matchPacket( - std::unique_ptr&& arg) { + std::unique_ptr&& arg) { return MakeMatcher(new PacketMatcher(std::move(arg))); } diff --git a/system/profile/sdp/common/data_element_reader.cc b/system/profile/sdp/common/data_element_reader.cc index 5bba1905768..95c4d57e154 100644 --- a/system/profile/sdp/common/data_element_reader.cc +++ b/system/profile/sdp/common/data_element_reader.cc @@ -39,8 +39,12 @@ namespace bluetooth { namespace sdp { DataElementReader::DataElement DataElementReader::ReadNext() { - if (it_ > end_) log::fatal("Beginning of buffer is past end of buffer."); - if (it_ == end_) return std::monostate(); + if (it_ > end_) { + log::fatal("Beginning of buffer is past end of buffer."); + } + if (it_ == end_) { + return std::monostate(); + } uint8_t descriptor = *it_++; DataElementType type = static_cast(descriptor >> 3); @@ -60,7 +64,7 @@ DataElementReader::DataElement DataElementReader::ReadNext() { } CHECK_REMAINING_LEN(1); - return (it_.extract() != 0); + return it_.extract() != 0; case DataElementType::SIGNED_INT: return ReadSignedInt(size); case DataElementType::UNSIGNED_INT: @@ -88,8 +92,7 @@ DataElementReader::DataElement DataElementReader::ParseFail() { template DataElementReader::DataElement DataElementReader::ReadInteger() { - static_assert(std::is_integral::value, - "ReadInteger requires an integral type."); + static_assert(std::is_integral::value, "ReadInteger requires an integral type."); CHECK_REMAINING_LEN(sizeof(IntegerType)); return it_.extractBE(); @@ -106,8 +109,7 @@ DataElementReader::DataElement DataElementReader::ReadLargeInt() { return array; } -DataElementReader::DataElement DataElementReader::ReadSignedInt( - DataElementSize size) { +DataElementReader::DataElement DataElementReader::ReadSignedInt(DataElementSize size) { switch (size) { case DataElementSize::BYTE1: return ReadInteger(); @@ -126,8 +128,7 @@ DataElementReader::DataElement DataElementReader::ReadSignedInt( return ParseFail(); } -DataElementReader::DataElement DataElementReader::ReadUnsignedInt( - DataElementSize size) { +DataElementReader::DataElement DataElementReader::ReadUnsignedInt(DataElementSize size) { switch (size) { case DataElementSize::BYTE1: return ReadInteger(); @@ -146,8 +147,7 @@ DataElementReader::DataElement DataElementReader::ReadUnsignedInt( return ParseFail(); } -DataElementReader::DataElement DataElementReader::ReadUuid( - DataElementSize size) { +DataElementReader::DataElement DataElementReader::ReadUuid(DataElementSize size) { if (size == DataElementSize::BYTE2) { CHECK_REMAINING_LEN(2); return Uuid::From16Bit(it_.extractBE()); @@ -173,8 +173,7 @@ DataElementReader::DataElement DataElementReader::ReadUuid( return ParseFail(); } -DataElementReader::DataElement DataElementReader::ReadString( - DataElementSize size) { +DataElementReader::DataElement DataElementReader::ReadString(DataElementSize size) { uint32_t num_bytes = 0; switch (size) { @@ -205,8 +204,7 @@ DataElementReader::DataElement DataElementReader::ReadString( return str; } -DataElementReader::DataElement DataElementReader::ReadSequence( - DataElementSize size) { +DataElementReader::DataElement DataElementReader::ReadSequence(DataElementSize size) { uint32_t num_bytes = 0; switch (size) { diff --git a/system/profile/sdp/common/data_element_reader.h b/system/profile/sdp/common/data_element_reader.h index 5b4d770a268..eea58ece435 100644 --- a/system/profile/sdp/common/data_element_reader.h +++ b/system/profile/sdp/common/data_element_reader.h @@ -29,21 +29,20 @@ namespace sdp { // A helper class that helps extract data element objects from SDP packets. class DataElementReader { - public: +public: // If the DataElement contains monostate, that means parsing has failed. using DataElement = - std::variant; + std::variant; - DataElementReader(Iterator begin, Iterator end) : it_(begin), end_(end){}; + DataElementReader(Iterator begin, Iterator end) : it_(begin), end_(end) {} // Get the next Data Element in the data. If reading fails for any reason, // the DataElementReader becomes invalid and will continuously fail to read // from that point onward. DataElement ReadNext(); - private: +private: // Extraction Helpers DataElement ParseFail(); template diff --git a/system/profile/sdp/common/test/data_element_reader_test.cc b/system/profile/sdp/common/test/data_element_reader_test.cc index 429eaba8052..71ba0a4a698 100644 --- a/system/profile/sdp/common/test/data_element_reader_test.cc +++ b/system/profile/sdp/common/test/data_element_reader_test.cc @@ -28,7 +28,7 @@ using DataElement = DataElementReader::DataElement; // A helper class to help work with the Data Element classes. class ReaderPacket : public ::bluetooth::Packet { - public: +public: using Packet::Packet; static std::shared_ptr Make(std::vector payload) { @@ -54,10 +54,14 @@ bool operator==(DataElementReader a, DataElementReader b) { DataElement a_elem = a.ReadNext(); DataElement b_elem = b.ReadNext(); - if (a_elem != b_elem) return false; + if (a_elem != b_elem) { + return false; + } // If we get here that means both a and b have reached the end. - if (a_elem == DataElement(std::monostate())) break; + if (a_elem == DataElement(std::monostate())) { + break; + } } return true; @@ -81,111 +85,92 @@ using ValidTestParam = std::tuple, DataElement>; class ValidReadTest : public TestWithParam {}; std::vector valid_values = { - // Boolean Tests - ValidTestParam{ - {Desc(DataElementType::BOOLEAN, DataElementSize::BYTE1), 0x01}, - true, - }, - ValidTestParam{ - {Desc(DataElementType::BOOLEAN, DataElementSize::BYTE1), 0x00}, - false, - }, - - // Signed Integer Tests - ValidTestParam{ - {Desc(DataElementType::SIGNED_INT, DataElementSize::BYTE1), 0xFF}, - static_cast(-1)}, - ValidTestParam{ - {Desc(DataElementType::SIGNED_INT, DataElementSize::BYTE2), 0xFF, 0xFF}, - static_cast(-1)}, - ValidTestParam{{Desc(DataElementType::SIGNED_INT, DataElementSize::BYTE4), - 0xFF, 0xFF, 0xFF, 0xFF}, - static_cast(-1)}, - ValidTestParam{{Desc(DataElementType::SIGNED_INT, DataElementSize::BYTE8), - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, - static_cast(-1)}, - ValidTestParam{{Desc(DataElementType::SIGNED_INT, DataElementSize::BYTE16), - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, - std::array{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF}}, - - // Unsigned Integer Tests - ValidTestParam{ - {Desc(DataElementType::UNSIGNED_INT, DataElementSize::BYTE1), 0x01}, - static_cast(1)}, - ValidTestParam{{Desc(DataElementType::UNSIGNED_INT, DataElementSize::BYTE2), - 0x00, 0x01}, - static_cast(1)}, - ValidTestParam{{Desc(DataElementType::UNSIGNED_INT, DataElementSize::BYTE4), - 0x00, 0x00, 0x00, 0x01}, - static_cast(1)}, - ValidTestParam{{Desc(DataElementType::UNSIGNED_INT, DataElementSize::BYTE8), - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}, - static_cast(1)}, - ValidTestParam{ - {Desc(DataElementType::UNSIGNED_INT, DataElementSize::BYTE16), 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x01}, - std::array{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x01}}, - - // UUID Tests - ValidTestParam{ - {Desc(DataElementType::UUID, DataElementSize::BYTE2), 0x01, 0x02}, - Uuid::From16Bit(0x0102)}, - ValidTestParam{{Desc(DataElementType::UUID, DataElementSize::BYTE4), 0x01, - 0x02, 0x03, 0x04}, - Uuid::From32Bit(0x01020304)}, - ValidTestParam{ - {Desc(DataElementType::UUID, DataElementSize::BYTE16), 0x00, 0x01, 0x02, - 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, - 0x0F}, - Uuid::From128BitBE({0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, - 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F})}, - - // String Tests - ValidTestParam{ - {Desc(DataElementType::STRING, DataElementSize::ADDITIONAL_8BIT), 0x05, - 'T', 'e', 's', 't', '1'}, - std::string("Test1")}, - ValidTestParam{ - {Desc(DataElementType::STRING, DataElementSize::ADDITIONAL_16BIT), 0x00, - 0x05, 'T', 'e', 's', 't', '2'}, - std::string("Test2")}, - ValidTestParam{ - {Desc(DataElementType::STRING, DataElementSize::ADDITIONAL_32BIT), 0x00, - 0x00, 0x00, 0x05, 'T', 'e', 's', 't', '3'}, - std::string("Test3")}, - - // Nested Data Element List Tests - ValidTestParam{ - {Desc(DataElementType::DATA_ELEMENT_SEQUENCE, - DataElementSize::ADDITIONAL_8BIT), - 0x04, Desc(DataElementType::BOOLEAN, DataElementSize::BYTE1), 0x01, - Desc(DataElementType::BOOLEAN, DataElementSize::BYTE1), 0x00}, - CreateReader( - {Desc(DataElementType::BOOLEAN, DataElementSize::BYTE1), 0x01, - Desc(DataElementType::BOOLEAN, DataElementSize::BYTE1), 0x00})}, - ValidTestParam{ - {Desc(DataElementType::DATA_ELEMENT_SEQUENCE, - DataElementSize::ADDITIONAL_16BIT), - 0x00, 0x04, Desc(DataElementType::BOOLEAN, DataElementSize::BYTE1), - 0x01, Desc(DataElementType::BOOLEAN, DataElementSize::BYTE1), 0x00}, - CreateReader( - {Desc(DataElementType::BOOLEAN, DataElementSize::BYTE1), 0x01, - Desc(DataElementType::BOOLEAN, DataElementSize::BYTE1), 0x00})}, - ValidTestParam{ - {Desc(DataElementType::DATA_ELEMENT_SEQUENCE, - DataElementSize::ADDITIONAL_32BIT), - 0x00, 0x00, 0x00, 0x04, - Desc(DataElementType::BOOLEAN, DataElementSize::BYTE1), 0x01, - Desc(DataElementType::BOOLEAN, DataElementSize::BYTE1), 0x00}, - CreateReader( - {Desc(DataElementType::BOOLEAN, DataElementSize::BYTE1), 0x01, - Desc(DataElementType::BOOLEAN, DataElementSize::BYTE1), 0x00})}, + // Boolean Tests + ValidTestParam{ + {Desc(DataElementType::BOOLEAN, DataElementSize::BYTE1), 0x01}, + true, + }, + ValidTestParam{ + {Desc(DataElementType::BOOLEAN, DataElementSize::BYTE1), 0x00}, + false, + }, + + // Signed Integer Tests + ValidTestParam{{Desc(DataElementType::SIGNED_INT, DataElementSize::BYTE1), 0xFF}, + static_cast(-1)}, + ValidTestParam{{Desc(DataElementType::SIGNED_INT, DataElementSize::BYTE2), 0xFF, 0xFF}, + static_cast(-1)}, + ValidTestParam{ + {Desc(DataElementType::SIGNED_INT, DataElementSize::BYTE4), 0xFF, 0xFF, 0xFF, 0xFF}, + static_cast(-1)}, + ValidTestParam{{Desc(DataElementType::SIGNED_INT, DataElementSize::BYTE8), 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, + static_cast(-1)}, + ValidTestParam{ + {Desc(DataElementType::SIGNED_INT, DataElementSize::BYTE16), 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, + std::array{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}}, + + // Unsigned Integer Tests + ValidTestParam{{Desc(DataElementType::UNSIGNED_INT, DataElementSize::BYTE1), 0x01}, + static_cast(1)}, + ValidTestParam{{Desc(DataElementType::UNSIGNED_INT, DataElementSize::BYTE2), 0x00, 0x01}, + static_cast(1)}, + ValidTestParam{{Desc(DataElementType::UNSIGNED_INT, DataElementSize::BYTE4), 0x00, 0x00, + 0x00, 0x01}, + static_cast(1)}, + ValidTestParam{{Desc(DataElementType::UNSIGNED_INT, DataElementSize::BYTE8), 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}, + static_cast(1)}, + ValidTestParam{ + {Desc(DataElementType::UNSIGNED_INT, DataElementSize::BYTE16), 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}, + std::array{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}}, + + // UUID Tests + ValidTestParam{{Desc(DataElementType::UUID, DataElementSize::BYTE2), 0x01, 0x02}, + Uuid::From16Bit(0x0102)}, + ValidTestParam{ + {Desc(DataElementType::UUID, DataElementSize::BYTE4), 0x01, 0x02, 0x03, 0x04}, + Uuid::From32Bit(0x01020304)}, + ValidTestParam{ + {Desc(DataElementType::UUID, DataElementSize::BYTE16), 0x00, 0x01, 0x02, 0x03, 0x04, + 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, + Uuid::From128BitBE({0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, + 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F})}, + + // String Tests + ValidTestParam{{Desc(DataElementType::STRING, DataElementSize::ADDITIONAL_8BIT), 0x05, 'T', + 'e', 's', 't', '1'}, + std::string("Test1")}, + ValidTestParam{{Desc(DataElementType::STRING, DataElementSize::ADDITIONAL_16BIT), 0x00, + 0x05, 'T', 'e', 's', 't', '2'}, + std::string("Test2")}, + ValidTestParam{{Desc(DataElementType::STRING, DataElementSize::ADDITIONAL_32BIT), 0x00, + 0x00, 0x00, 0x05, 'T', 'e', 's', 't', '3'}, + std::string("Test3")}, + + // Nested Data Element List Tests + ValidTestParam{ + {Desc(DataElementType::DATA_ELEMENT_SEQUENCE, DataElementSize::ADDITIONAL_8BIT), + 0x04, Desc(DataElementType::BOOLEAN, DataElementSize::BYTE1), 0x01, + Desc(DataElementType::BOOLEAN, DataElementSize::BYTE1), 0x00}, + CreateReader({Desc(DataElementType::BOOLEAN, DataElementSize::BYTE1), 0x01, + Desc(DataElementType::BOOLEAN, DataElementSize::BYTE1), 0x00})}, + ValidTestParam{ + {Desc(DataElementType::DATA_ELEMENT_SEQUENCE, DataElementSize::ADDITIONAL_16BIT), + 0x00, 0x04, Desc(DataElementType::BOOLEAN, DataElementSize::BYTE1), 0x01, + Desc(DataElementType::BOOLEAN, DataElementSize::BYTE1), 0x00}, + CreateReader({Desc(DataElementType::BOOLEAN, DataElementSize::BYTE1), 0x01, + Desc(DataElementType::BOOLEAN, DataElementSize::BYTE1), 0x00})}, + ValidTestParam{ + {Desc(DataElementType::DATA_ELEMENT_SEQUENCE, DataElementSize::ADDITIONAL_32BIT), + 0x00, 0x00, 0x00, 0x04, Desc(DataElementType::BOOLEAN, DataElementSize::BYTE1), + 0x01, Desc(DataElementType::BOOLEAN, DataElementSize::BYTE1), 0x00}, + CreateReader({Desc(DataElementType::BOOLEAN, DataElementSize::BYTE1), 0x01, + Desc(DataElementType::BOOLEAN, DataElementSize::BYTE1), 0x00})}, }; INSTANTIATE_TEST_CASE_P(ReadNext, ValidReadTest, ValuesIn(valid_values)); @@ -206,16 +191,15 @@ TEST_P(ValidReadTest, Test) { // defined end. TEST(ReadNext, BoundedSubreaderTest) { std::vector payload = { - // Subsequence descriptor byte. - Desc(DataElementType::DATA_ELEMENT_SEQUENCE, - DataElementSize::ADDITIONAL_8BIT), - // Subsequence length. - 0x04, - // Subsequence that contains two booleans with values true and false. - Desc(DataElementType::BOOLEAN, DataElementSize::BYTE1), 0x01, - Desc(DataElementType::BOOLEAN, DataElementSize::BYTE1), 0x00, - // Additional int16 at the end of the original sequence. - Desc(DataElementType::SIGNED_INT, DataElementSize::BYTE2), 0x01, 0x23}; + // Subsequence descriptor byte. + Desc(DataElementType::DATA_ELEMENT_SEQUENCE, DataElementSize::ADDITIONAL_8BIT), + // Subsequence length. + 0x04, + // Subsequence that contains two booleans with values true and false. + Desc(DataElementType::BOOLEAN, DataElementSize::BYTE1), 0x01, + Desc(DataElementType::BOOLEAN, DataElementSize::BYTE1), 0x00, + // Additional int16 at the end of the original sequence. + Desc(DataElementType::SIGNED_INT, DataElementSize::BYTE2), 0x01, 0x23}; auto packet = ReaderPacket::Make(payload); DataElementReader reader(packet->begin(), packet->end()); @@ -268,131 +252,113 @@ using InvalidTestParam = std::vector; class InvalidReadTest : public TestWithParam {}; std::vector invalid_values = { - // Boolean Tests: - // Invalid size field. - InvalidTestParam{ - Desc(DataElementType::BOOLEAN, DataElementSize::BYTE2), - }, - // Insufficient data. - InvalidTestParam{Desc(DataElementType::BOOLEAN, DataElementSize::BYTE1)}, - - // Signed Integer Tests: - // Invalid size field. - InvalidTestParam{ - Desc(DataElementType::SIGNED_INT, DataElementSize::ADDITIONAL_8BIT)}, - // 1 byte insufficient data. - InvalidTestParam{Desc(DataElementType::SIGNED_INT, DataElementSize::BYTE1)}, - // 2 byte insufficient data. - InvalidTestParam{Desc(DataElementType::SIGNED_INT, DataElementSize::BYTE2), - 0x00}, - // 4 byte insufficient data. - InvalidTestParam{Desc(DataElementType::SIGNED_INT, DataElementSize::BYTE4), - 0x00, 0x00, 0x00}, - // 8 Byte insufficient data. - InvalidTestParam{Desc(DataElementType::SIGNED_INT, DataElementSize::BYTE8), - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - // 16 Byte insufficient data. - InvalidTestParam{Desc(DataElementType::SIGNED_INT, DataElementSize::BYTE16), - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00}, - - // Unsigned Integer Tests: - // Invalid size field. - InvalidTestParam{ - Desc(DataElementType::UNSIGNED_INT, DataElementSize::ADDITIONAL_8BIT)}, - // 1 byte insufficient data. - InvalidTestParam{ - Desc(DataElementType::UNSIGNED_INT, DataElementSize::BYTE1)}, - // 2 byte insufficient data. - InvalidTestParam{ - Desc(DataElementType::UNSIGNED_INT, DataElementSize::BYTE2), 0x00}, - // 4 byte insufficient data. - InvalidTestParam{ - Desc(DataElementType::UNSIGNED_INT, DataElementSize::BYTE4), 0x00, 0x00, - 0x00}, - // 8 Byte insufficient data. - InvalidTestParam{ - Desc(DataElementType::UNSIGNED_INT, DataElementSize::BYTE8), 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00}, - // 16 Byte insufficient data. - InvalidTestParam{ - Desc(DataElementType::UNSIGNED_INT, DataElementSize::BYTE16), 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - - // UUID Tests: - // Invalid size field. - InvalidTestParam{ - Desc(DataElementType::UUID, DataElementSize::ADDITIONAL_8BIT)}, - // 2 byte insufficient data. - InvalidTestParam{Desc(DataElementType::UUID, DataElementSize::BYTE2), 0x00}, - // 4 byte insufficient data. - InvalidTestParam{Desc(DataElementType::UUID, DataElementSize::BYTE4), 0x00, - 0x00, 0x00}, - // 16 Byte insufficient data. - InvalidTestParam{Desc(DataElementType::UUID, DataElementSize::BYTE16), 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00}, - - // String Tests: - // Invalid size field. - InvalidTestParam{Desc(DataElementType::STRING, DataElementSize::BYTE1)}, - // Insufficient data for additional 8 bits len. - InvalidTestParam{ - Desc(DataElementType::STRING, DataElementSize::ADDITIONAL_8BIT)}, - // Insufficient data for additional 16 bits len. - InvalidTestParam{ - Desc(DataElementType::STRING, DataElementSize::ADDITIONAL_16BIT), - 0x00, - }, - // Insufficient data for additional 32 bit len. - InvalidTestParam{ - Desc(DataElementType::STRING, DataElementSize::ADDITIONAL_32BIT), - 0x00, - 0x00, - 0x00, - }, - // Insufficient data for reported length. - InvalidTestParam{ - Desc(DataElementType::STRING, DataElementSize::ADDITIONAL_8BIT), 0x04, - '1', '2', '3'}, - - // Nested Data Element List Tests: - // Invalid size field. - InvalidTestParam{ - Desc(DataElementType::DATA_ELEMENT_SEQUENCE, DataElementSize::BYTE1)}, - // Insufficient data for additional 8 bits len. - InvalidTestParam{Desc(DataElementType::DATA_ELEMENT_SEQUENCE, - DataElementSize::ADDITIONAL_8BIT)}, - // Insufficient data for additional 16 bits len. - InvalidTestParam{ - Desc(DataElementType::DATA_ELEMENT_SEQUENCE, - DataElementSize::ADDITIONAL_16BIT), - 0x00, - }, - // Insufficient data for additional 32 bit len. - InvalidTestParam{ - Desc(DataElementType::DATA_ELEMENT_SEQUENCE, - DataElementSize::ADDITIONAL_32BIT), - 0x00, - 0x00, - 0x00, - }, - // Insufficient data for reported length. - InvalidTestParam{Desc(DataElementType::DATA_ELEMENT_SEQUENCE, - DataElementSize::ADDITIONAL_8BIT), - 0x04, 0x00, 0x00, 0x00}, - - // Unhandled Data Element Types Tests: - // NOTE: These tests should go away as we begin to handle the types. - // Nil Type. - InvalidTestParam{Desc(DataElementType::NIL, DataElementSize::BYTE1)}, - // Data Element Alternative List Type. - InvalidTestParam{Desc(DataElementType::DATA_ELEMENT_ALTERNATIVE, - DataElementSize::ADDITIONAL_8BIT), - 0x00}, - // URL Type. - InvalidTestParam{ - Desc(DataElementType::URL, DataElementSize::ADDITIONAL_8BIT), 0x00}}; + // Boolean Tests: + // Invalid size field. + InvalidTestParam{ + Desc(DataElementType::BOOLEAN, DataElementSize::BYTE2), + }, + // Insufficient data. + InvalidTestParam{Desc(DataElementType::BOOLEAN, DataElementSize::BYTE1)}, + + // Signed Integer Tests: + // Invalid size field. + InvalidTestParam{Desc(DataElementType::SIGNED_INT, DataElementSize::ADDITIONAL_8BIT)}, + // 1 byte insufficient data. + InvalidTestParam{Desc(DataElementType::SIGNED_INT, DataElementSize::BYTE1)}, + // 2 byte insufficient data. + InvalidTestParam{Desc(DataElementType::SIGNED_INT, DataElementSize::BYTE2), 0x00}, + // 4 byte insufficient data. + InvalidTestParam{Desc(DataElementType::SIGNED_INT, DataElementSize::BYTE4), 0x00, 0x00, + 0x00}, + // 8 Byte insufficient data. + InvalidTestParam{Desc(DataElementType::SIGNED_INT, DataElementSize::BYTE8), 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00}, + // 16 Byte insufficient data. + InvalidTestParam{Desc(DataElementType::SIGNED_INT, DataElementSize::BYTE16), 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, + + // Unsigned Integer Tests: + // Invalid size field. + InvalidTestParam{Desc(DataElementType::UNSIGNED_INT, DataElementSize::ADDITIONAL_8BIT)}, + // 1 byte insufficient data. + InvalidTestParam{Desc(DataElementType::UNSIGNED_INT, DataElementSize::BYTE1)}, + // 2 byte insufficient data. + InvalidTestParam{Desc(DataElementType::UNSIGNED_INT, DataElementSize::BYTE2), 0x00}, + // 4 byte insufficient data. + InvalidTestParam{Desc(DataElementType::UNSIGNED_INT, DataElementSize::BYTE4), 0x00, 0x00, + 0x00}, + // 8 Byte insufficient data. + InvalidTestParam{Desc(DataElementType::UNSIGNED_INT, DataElementSize::BYTE8), 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00}, + // 16 Byte insufficient data. + InvalidTestParam{Desc(DataElementType::UNSIGNED_INT, DataElementSize::BYTE16), 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, + + // UUID Tests: + // Invalid size field. + InvalidTestParam{Desc(DataElementType::UUID, DataElementSize::ADDITIONAL_8BIT)}, + // 2 byte insufficient data. + InvalidTestParam{Desc(DataElementType::UUID, DataElementSize::BYTE2), 0x00}, + // 4 byte insufficient data. + InvalidTestParam{Desc(DataElementType::UUID, DataElementSize::BYTE4), 0x00, 0x00, 0x00}, + // 16 Byte insufficient data. + InvalidTestParam{Desc(DataElementType::UUID, DataElementSize::BYTE16), 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, + + // String Tests: + // Invalid size field. + InvalidTestParam{Desc(DataElementType::STRING, DataElementSize::BYTE1)}, + // Insufficient data for additional 8 bits len. + InvalidTestParam{Desc(DataElementType::STRING, DataElementSize::ADDITIONAL_8BIT)}, + // Insufficient data for additional 16 bits len. + InvalidTestParam{ + Desc(DataElementType::STRING, DataElementSize::ADDITIONAL_16BIT), + 0x00, + }, + // Insufficient data for additional 32 bit len. + InvalidTestParam{ + Desc(DataElementType::STRING, DataElementSize::ADDITIONAL_32BIT), + 0x00, + 0x00, + 0x00, + }, + // Insufficient data for reported length. + InvalidTestParam{Desc(DataElementType::STRING, DataElementSize::ADDITIONAL_8BIT), 0x04, '1', + '2', '3'}, + + // Nested Data Element List Tests: + // Invalid size field. + InvalidTestParam{Desc(DataElementType::DATA_ELEMENT_SEQUENCE, DataElementSize::BYTE1)}, + // Insufficient data for additional 8 bits len. + InvalidTestParam{ + Desc(DataElementType::DATA_ELEMENT_SEQUENCE, DataElementSize::ADDITIONAL_8BIT)}, + // Insufficient data for additional 16 bits len. + InvalidTestParam{ + Desc(DataElementType::DATA_ELEMENT_SEQUENCE, DataElementSize::ADDITIONAL_16BIT), + 0x00, + }, + // Insufficient data for additional 32 bit len. + InvalidTestParam{ + Desc(DataElementType::DATA_ELEMENT_SEQUENCE, DataElementSize::ADDITIONAL_32BIT), + 0x00, + 0x00, + 0x00, + }, + // Insufficient data for reported length. + InvalidTestParam{ + Desc(DataElementType::DATA_ELEMENT_SEQUENCE, DataElementSize::ADDITIONAL_8BIT), + 0x04, 0x00, 0x00, 0x00}, + + // Unhandled Data Element Types Tests: + // NOTE: These tests should go away as we begin to handle the types. + // Nil Type. + InvalidTestParam{Desc(DataElementType::NIL, DataElementSize::BYTE1)}, + // Data Element Alternative List Type. + InvalidTestParam{ + Desc(DataElementType::DATA_ELEMENT_ALTERNATIVE, DataElementSize::ADDITIONAL_8BIT), + 0x00}, + // URL Type. + InvalidTestParam{Desc(DataElementType::URL, DataElementSize::ADDITIONAL_8BIT), 0x00}}; INSTANTIATE_TEST_CASE_P(ReadNext, InvalidReadTest, ValuesIn(invalid_values)); TEST_P(InvalidReadTest, Test) { diff --git a/system/profile/sdp/sdp_logging_helper.h b/system/profile/sdp/sdp_logging_helper.h index d556b6e5367..66aa6ae33ae 100644 --- a/system/profile/sdp/sdp_logging_helper.h +++ b/system/profile/sdp/sdp_logging_helper.h @@ -46,9 +46,7 @@ inline std::string PduIdText(const PduId& id) { } } -inline std::ostream& operator<<(std::ostream& os, const PduId& id) { - return os << PduIdText(id); -} +inline std::ostream& operator<<(std::ostream& os, const PduId& id) { return os << PduIdText(id); } inline std::string AttributeIdText(const AttributeId& id) { switch (id) { diff --git a/system/rust/src/connection/ffi/connection_shim.cc b/system/rust/src/connection/ffi/connection_shim.cc index c52cd19ee2a..1ff23b96295 100644 --- a/system/rust/src/connection/ffi/connection_shim.cc +++ b/system/rust/src/connection/ffi/connection_shim.cc @@ -41,10 +41,10 @@ struct LeAclManagerCallbackShim { } void OnLeConnectFail(core::AddressWithType addr, uint8_t status) const { log::fatal("system/rust not available in Floss"); - }; + } void OnLeDisconnection(core::AddressWithType addr) const { log::fatal("system/rust not available in Floss"); - }; + } }; using BoxedLeAclManagerCallbackShim = std::unique_ptr; @@ -59,8 +59,7 @@ namespace { hci::AddressWithType ToCppAddress(core::AddressWithType address) { auto hci_address = hci::Address(); hci_address.FromOctets(address.address.data()); - return hci::AddressWithType(hci_address, - (hci::AddressType)address.address_type); + return hci::AddressWithType(hci_address, (hci::AddressType)address.address_type); } core::AddressWithType ToRustAddress(hci::AddressWithType address) { @@ -70,7 +69,7 @@ core::AddressWithType ToRustAddress(hci::AddressWithType address) { } // namespace struct LeAclManagerShim::impl : hci::acl_manager::LeAcceptlistCallbacks { - public: +public: impl() { acl_manager_ = shim::GetAclManager(); } ~impl() { @@ -104,10 +103,8 @@ struct LeAclManagerShim::impl : hci::acl_manager::LeAcceptlistCallbacks { } // hci::acl_manager::LeAcceptlistCallbacks - virtual void OnLeConnectFail(hci::AddressWithType address, - hci::ErrorCode reason) { - callbacks_.value()->OnLeConnectFail(ToRustAddress(address), - static_cast(reason)); + virtual void OnLeConnectFail(hci::AddressWithType address, hci::ErrorCode reason) { + callbacks_.value()->OnLeConnectFail(ToRustAddress(address), static_cast(reason)); } // hci::acl_manager::LeAcceptlistCallbacks @@ -118,19 +115,16 @@ struct LeAclManagerShim::impl : hci::acl_manager::LeAcceptlistCallbacks { // hci::acl_manager::LeAcceptlistCallbacks virtual void OnResolvingListChange() {} - private: +private: std::optional callbacks_; hci::AclManager* acl_manager_{}; }; -LeAclManagerShim::LeAclManagerShim() { - pimpl_ = std::make_unique(); -} +LeAclManagerShim::LeAclManagerShim() { pimpl_ = std::make_unique(); } LeAclManagerShim::~LeAclManagerShim() = default; -void LeAclManagerShim::CreateLeConnection(core::AddressWithType address, - bool is_direct) const { +void LeAclManagerShim::CreateLeConnection(core::AddressWithType address, bool is_direct) const { pimpl_->CreateLeConnection(address, is_direct); } @@ -139,8 +133,7 @@ void LeAclManagerShim::CancelLeConnect(core::AddressWithType address) const { } #ifndef TARGET_FLOSS -void LeAclManagerShim::RegisterRustCallbacks( - BoxedLeAclManagerCallbackShim callbacks) { +void LeAclManagerShim::RegisterRustCallbacks(BoxedLeAclManagerCallbackShim callbacks) { pimpl_->RegisterRustCallbacks(std::move(callbacks)); } #endif @@ -151,28 +144,20 @@ std::optional connection_manager; } // namespace -RustConnectionManager& GetConnectionManager() { - return connection_manager.value(); -} +RustConnectionManager& GetConnectionManager() { return connection_manager.value(); } void RegisterRustApis( - ::rust::Fn - start_direct_connection, - ::rust::Fn - stop_direct_connection, - ::rust::Fn - add_background_connection, - ::rust::Fn - remove_background_connection, - ::rust::Fn remove_client, - ::rust::Fn - stop_all_connections_to_device) { - connection_manager = {start_direct_connection, - stop_direct_connection, - add_background_connection, - remove_background_connection, - remove_client, - stop_all_connections_to_device}; + ::rust::Fn start_direct_connection, + ::rust::Fn stop_direct_connection, + ::rust::Fn + add_background_connection, + ::rust::Fn + remove_background_connection, + ::rust::Fn remove_client, + ::rust::Fn stop_all_connections_to_device) { + connection_manager = { + start_direct_connection, stop_direct_connection, add_background_connection, + remove_background_connection, remove_client, stop_all_connections_to_device}; } core::AddressWithType ResolveRawAddress(RawAddress bd_addr) { diff --git a/system/rust/src/connection/ffi/connection_shim.h b/system/rust/src/connection/ffi/connection_shim.h index f7976c0da59..5346c07db94 100644 --- a/system/rust/src/connection/ffi/connection_shim.h +++ b/system/rust/src/connection/ffi/connection_shim.h @@ -28,7 +28,7 @@ namespace connection { struct LeAclManagerCallbackShim; class LeAclManagerShim { - public: +public: LeAclManagerShim(); ~LeAclManagerShim(); @@ -40,36 +40,28 @@ class LeAclManagerShim { void RegisterRustCallbacks(::rust::Box callbacks); #endif - private: +private: struct impl; std::unique_ptr pimpl_; }; void RegisterRustApis( - ::rust::Fn - start_direct_connection, - ::rust::Fn - stop_direct_connection, - ::rust::Fn - add_background_connection, - ::rust::Fn - remove_background_connection, - ::rust::Fn remove_client, - ::rust::Fn - stop_all_connections_to_device); + ::rust::Fn start_direct_connection, + ::rust::Fn stop_direct_connection, + ::rust::Fn + add_background_connection, + ::rust::Fn + remove_background_connection, + ::rust::Fn remove_client, + ::rust::Fn stop_all_connections_to_device); struct RustConnectionManager { - ::rust::Fn - start_direct_connection; - ::rust::Fn - stop_direct_connection; - ::rust::Fn - add_background_connection; - ::rust::Fn - remove_background_connection; + ::rust::Fn start_direct_connection; + ::rust::Fn stop_direct_connection; + ::rust::Fn add_background_connection; + ::rust::Fn remove_background_connection; ::rust::Fn remove_client; - ::rust::Fn - stop_all_connections_to_device; + ::rust::Fn stop_all_connections_to_device; }; RustConnectionManager& GetConnectionManager(); diff --git a/system/rust/src/core/ffi/module.cc b/system/rust/src/core/ffi/module.cc index 3b7d916daec..cfee5cf84e9 100644 --- a/system/rust/src/core/ffi/module.cc +++ b/system/rust/src/core/ffi/module.cc @@ -58,15 +58,14 @@ future_t* Start() { // startup/cleanup logic and start the stack without GATT, but don't fully // mock out the native layer. bluetooth::log::error( - "GATT profile not started, so we cannot start the Rust loop - this " - "happens only in tests."); + "GATT profile not started, so we cannot start the Rust loop - this " + "happens only in tests."); bluetooth::rust_shim::FutureReady(*fut); return fut; } bluetooth::rust_shim::start( - std::make_unique( - *bt_gatt_callbacks->server), - std::make_unique(), *fut); + std::make_unique(*bt_gatt_callbacks->server), + std::make_unique(), *fut); return fut; } diff --git a/system/rust/src/core/ffi/types.h b/system/rust/src/core/ffi/types.h index 7c303058d2d..62476acfc24 100644 --- a/system/rust/src/core/ffi/types.h +++ b/system/rust/src/core/ffi/types.h @@ -36,9 +36,8 @@ struct AddressWithType { inline core::AddressWithType ToRustAddress(tBLE_BD_ADDR address) { auto array = address.bda.ToArray(); std::reverse(std::begin(array), std::end(array)); - return core::AddressWithType{array, address.IsPublic() - ? core::AddressType::Public - : core::AddressType::Random}; + return core::AddressWithType{ + array, address.IsPublic() ? core::AddressType::Public : core::AddressType::Random}; } } // namespace core diff --git a/system/rust/src/gatt/ffi/gatt_shim.cc b/system/rust/src/gatt/ffi/gatt_shim.cc index 99ac8d31c62..2ac8156b8fd 100644 --- a/system/rust/src/gatt/ffi/gatt_shim.cc +++ b/system/rust/src/gatt/ffi/gatt_shim.cc @@ -38,8 +38,7 @@ std::optional AddressOfConnection(uint16_t conn_id) { tGATT_IF gatt_if; RawAddress remote_bda; tBT_TRANSPORT transport; - auto valid = - GATT_GetConnectionInfor(conn_id, &gatt_if, remote_bda, &transport); + auto valid = GATT_GetConnectionInfor(conn_id, &gatt_if, remote_bda, &transport); if (!valid) { return std::nullopt; } @@ -50,52 +49,42 @@ std::optional AddressOfConnection(uint16_t conn_id) { namespace bluetooth { namespace gatt { -void GattServerCallbacks::OnServerRead(uint16_t conn_id, uint32_t trans_id, - uint16_t attr_handle, - AttributeBackingType attr_type, - uint32_t offset, bool is_long) const { +void GattServerCallbacks::OnServerRead(uint16_t conn_id, uint32_t trans_id, uint16_t attr_handle, + AttributeBackingType attr_type, uint32_t offset, + bool is_long) const { auto addr = AddressOfConnection(conn_id); if (!addr.has_value()) { - log::warn( - "Dropping server read characteristic since connection {} not found", - conn_id); + log::warn("Dropping server read characteristic since connection {} not found", conn_id); return; } switch (attr_type) { case AttributeBackingType::CHARACTERISTIC: - do_in_jni_thread(base::BindOnce(callbacks.request_read_characteristic_cb, - conn_id, trans_id, addr.value(), - attr_handle, offset, is_long)); + do_in_jni_thread(base::BindOnce(callbacks.request_read_characteristic_cb, conn_id, trans_id, + addr.value(), attr_handle, offset, is_long)); break; case AttributeBackingType::DESCRIPTOR: - do_in_jni_thread(base::BindOnce(callbacks.request_read_descriptor_cb, - conn_id, trans_id, addr.value(), - attr_handle, offset, is_long)); + do_in_jni_thread(base::BindOnce(callbacks.request_read_descriptor_cb, conn_id, trans_id, + addr.value(), attr_handle, offset, is_long)); break; default: log::fatal("Unexpected backing type {}", attr_type); } } -static void request_write_with_vec(request_write_callback cb, int conn_id, - int trans_id, const RawAddress& bda, - int attr_handle, int offset, bool need_rsp, - bool is_prep, - const std::vector& value) { - cb(conn_id, trans_id, bda, attr_handle, offset, need_rsp, is_prep, - value.data(), value.size()); +static void request_write_with_vec(request_write_callback cb, int conn_id, int trans_id, + const RawAddress& bda, int attr_handle, int offset, + bool need_rsp, bool is_prep, const std::vector& value) { + cb(conn_id, trans_id, bda, attr_handle, offset, need_rsp, is_prep, value.data(), value.size()); } -void GattServerCallbacks::OnServerWrite( - uint16_t conn_id, uint32_t trans_id, uint16_t attr_handle, - AttributeBackingType attr_type, uint32_t offset, bool need_response, - bool is_prepare, ::rust::Slice value) const { +void GattServerCallbacks::OnServerWrite(uint16_t conn_id, uint32_t trans_id, uint16_t attr_handle, + AttributeBackingType attr_type, uint32_t offset, + bool need_response, bool is_prepare, + ::rust::Slice value) const { auto addr = AddressOfConnection(conn_id); if (!addr.has_value()) { - log::warn( - "Dropping server write characteristic since connection {} not found", - conn_id); + log::warn("Dropping server write characteristic since connection {} not found", conn_id); return; } @@ -104,38 +93,32 @@ void GattServerCallbacks::OnServerWrite( switch (attr_type) { case AttributeBackingType::CHARACTERISTIC: do_in_jni_thread(base::BindOnce( - request_write_with_vec, callbacks.request_write_characteristic_cb, - conn_id, trans_id, addr.value(), attr_handle, offset, need_response, - is_prepare, std::move(buf))); + request_write_with_vec, callbacks.request_write_characteristic_cb, conn_id, trans_id, + addr.value(), attr_handle, offset, need_response, is_prepare, std::move(buf))); break; case AttributeBackingType::DESCRIPTOR: - do_in_jni_thread(base::BindOnce( - request_write_with_vec, callbacks.request_write_descriptor_cb, - conn_id, trans_id, addr.value(), attr_handle, offset, need_response, - is_prepare, std::move(buf))); + do_in_jni_thread(base::BindOnce(request_write_with_vec, callbacks.request_write_descriptor_cb, + conn_id, trans_id, addr.value(), attr_handle, offset, + need_response, is_prepare, std::move(buf))); break; default: log::fatal("Unexpected backing type {}", attr_type); } } -void GattServerCallbacks::OnIndicationSentConfirmation(uint16_t conn_id, - int status) const { - do_in_jni_thread( - base::BindOnce(callbacks.indication_sent_cb, conn_id, status)); +void GattServerCallbacks::OnIndicationSentConfirmation(uint16_t conn_id, int status) const { + do_in_jni_thread(base::BindOnce(callbacks.indication_sent_cb, conn_id, status)); } -void GattServerCallbacks::OnExecute(uint16_t conn_id, uint32_t trans_id, - bool execute) const { +void GattServerCallbacks::OnExecute(uint16_t conn_id, uint32_t trans_id, bool execute) const { auto addr = AddressOfConnection(conn_id); if (!addr.has_value()) { - log::warn("Dropping server execute write since connection {} not found", - conn_id); + log::warn("Dropping server execute write since connection {} not found", conn_id); return; } - do_in_jni_thread(base::BindOnce(callbacks.request_exec_write_cb, conn_id, - trans_id, addr.value(), execute)); + do_in_jni_thread(base::BindOnce(callbacks.request_exec_write_cb, conn_id, trans_id, addr.value(), + execute)); } } // namespace gatt diff --git a/system/rust/src/gatt/ffi/gatt_shim.h b/system/rust/src/gatt/ffi/gatt_shim.h index faa68513341..0ddbab0c963 100644 --- a/system/rust/src/gatt/ffi/gatt_shim.h +++ b/system/rust/src/gatt/ffi/gatt_shim.h @@ -37,24 +37,21 @@ enum class AttributeBackingType { }; class GattServerCallbacks { - public: - GattServerCallbacks(const btgatt_server_callbacks_t& callbacks) - : callbacks(callbacks){}; +public: + GattServerCallbacks(const btgatt_server_callbacks_t& callbacks) : callbacks(callbacks) {} void OnServerRead(uint16_t conn_id, uint32_t trans_id, uint16_t attr_handle, - AttributeBackingType attr_type, uint32_t offset, - bool is_long) const; + AttributeBackingType attr_type, uint32_t offset, bool is_long) const; void OnServerWrite(uint16_t conn_id, uint32_t trans_id, uint16_t attr_handle, - AttributeBackingType attr_type, uint32_t offset, - bool need_response, bool is_prepare, - ::rust::Slice value) const; + AttributeBackingType attr_type, uint32_t offset, bool need_response, + bool is_prepare, ::rust::Slice value) const; void OnIndicationSentConfirmation(uint16_t conn_id, int status) const; void OnExecute(uint16_t conn_id, uint32_t trans_id, bool execute) const; - private: +private: const btgatt_server_callbacks_t& callbacks; }; diff --git a/system/stack/a2dp/a2dp_aac.cc b/system/stack/a2dp/a2dp_aac.cc index 96c28664ea1..7352824238b 100644 --- a/system/stack/a2dp/a2dp_aac.cc +++ b/system/stack/a2dp/a2dp_aac.cc @@ -57,92 +57,91 @@ static tA2DP_AAC_CIE a2dp_aac_source_caps = {}; /* AAC Source codec capabilities */ static const tA2DP_AAC_CIE a2dp_aac_cbr_source_caps = { - // objectType - A2DP_AAC_OBJECT_TYPE_MPEG2_LC, - // sampleRate - // TODO: AAC 48.0kHz sampling rate should be added back - see b/62301376 - A2DP_AAC_SAMPLING_FREQ_44100, - // channelMode - A2DP_AAC_CHANNEL_MODE_STEREO, - // variableBitRateSupport - A2DP_AAC_VARIABLE_BIT_RATE_DISABLED, - // bitRate - A2DP_AAC_DEFAULT_BITRATE, - // bits_per_sample - BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16}; + // objectType + A2DP_AAC_OBJECT_TYPE_MPEG2_LC, + // sampleRate + // TODO: AAC 48.0kHz sampling rate should be added back - see b/62301376 + A2DP_AAC_SAMPLING_FREQ_44100, + // channelMode + A2DP_AAC_CHANNEL_MODE_STEREO, + // variableBitRateSupport + A2DP_AAC_VARIABLE_BIT_RATE_DISABLED, + // bitRate + A2DP_AAC_DEFAULT_BITRATE, + // bits_per_sample + BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16}; /* AAC Source codec capabilities */ static const tA2DP_AAC_CIE a2dp_aac_vbr_source_caps = { - // objectType - A2DP_AAC_OBJECT_TYPE_MPEG2_LC, - // sampleRate - // TODO: AAC 48.0kHz sampling rate should be added back - see b/62301376 - A2DP_AAC_SAMPLING_FREQ_44100, - // channelMode - A2DP_AAC_CHANNEL_MODE_STEREO, - // variableBitRateSupport - A2DP_AAC_VARIABLE_BIT_RATE_ENABLED, - // bitRate - A2DP_AAC_DEFAULT_BITRATE, - // bits_per_sample - BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16}; + // objectType + A2DP_AAC_OBJECT_TYPE_MPEG2_LC, + // sampleRate + // TODO: AAC 48.0kHz sampling rate should be added back - see b/62301376 + A2DP_AAC_SAMPLING_FREQ_44100, + // channelMode + A2DP_AAC_CHANNEL_MODE_STEREO, + // variableBitRateSupport + A2DP_AAC_VARIABLE_BIT_RATE_ENABLED, + // bitRate + A2DP_AAC_DEFAULT_BITRATE, + // bits_per_sample + BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16}; /* AAC Sink codec capabilities */ static const tA2DP_AAC_CIE a2dp_aac_sink_caps = { - // objectType - A2DP_AAC_OBJECT_TYPE_MPEG2_LC, - // sampleRate - A2DP_AAC_SAMPLING_FREQ_44100 | A2DP_AAC_SAMPLING_FREQ_48000, - // channelMode - A2DP_AAC_CHANNEL_MODE_MONO | A2DP_AAC_CHANNEL_MODE_STEREO, - // variableBitRateSupport - A2DP_AAC_VARIABLE_BIT_RATE_ENABLED, - // bitRate - A2DP_AAC_DEFAULT_BITRATE, - // bits_per_sample - BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16}; + // objectType + A2DP_AAC_OBJECT_TYPE_MPEG2_LC, + // sampleRate + A2DP_AAC_SAMPLING_FREQ_44100 | A2DP_AAC_SAMPLING_FREQ_48000, + // channelMode + A2DP_AAC_CHANNEL_MODE_MONO | A2DP_AAC_CHANNEL_MODE_STEREO, + // variableBitRateSupport + A2DP_AAC_VARIABLE_BIT_RATE_ENABLED, + // bitRate + A2DP_AAC_DEFAULT_BITRATE, + // bits_per_sample + BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16}; /* Default AAC codec configuration */ static const tA2DP_AAC_CIE a2dp_aac_default_config = { - A2DP_AAC_OBJECT_TYPE_MPEG2_LC, // objectType - A2DP_AAC_SAMPLING_FREQ_44100, // sampleRate - A2DP_AAC_CHANNEL_MODE_STEREO, // channelMode - A2DP_AAC_VARIABLE_BIT_RATE_DISABLED, // variableBitRateSupport - A2DP_AAC_DEFAULT_BITRATE, // bitRate - BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16 // bits_per_sample + A2DP_AAC_OBJECT_TYPE_MPEG2_LC, // objectType + A2DP_AAC_SAMPLING_FREQ_44100, // sampleRate + A2DP_AAC_CHANNEL_MODE_STEREO, // channelMode + A2DP_AAC_VARIABLE_BIT_RATE_DISABLED, // variableBitRateSupport + A2DP_AAC_DEFAULT_BITRATE, // bitRate + BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16 // bits_per_sample }; static const tA2DP_ENCODER_INTERFACE a2dp_encoder_interface_aac = { - a2dp_aac_encoder_init, - a2dp_aac_encoder_cleanup, - a2dp_aac_feeding_reset, - a2dp_aac_feeding_flush, - a2dp_aac_get_encoder_interval_ms, - a2dp_aac_get_effective_frame_size, - a2dp_aac_send_frames, - nullptr // set_transmit_queue_length + a2dp_aac_encoder_init, + a2dp_aac_encoder_cleanup, + a2dp_aac_feeding_reset, + a2dp_aac_feeding_flush, + a2dp_aac_get_encoder_interval_ms, + a2dp_aac_get_effective_frame_size, + a2dp_aac_send_frames, + nullptr // set_transmit_queue_length }; static const tA2DP_DECODER_INTERFACE a2dp_decoder_interface_aac = { - a2dp_aac_decoder_init, - a2dp_aac_decoder_cleanup, - a2dp_aac_decoder_decode_packet, - nullptr, // decoder_start - nullptr, // decoder_suspend - nullptr, // decoder_configure + a2dp_aac_decoder_init, + a2dp_aac_decoder_cleanup, + a2dp_aac_decoder_decode_packet, + nullptr, // decoder_start + nullptr, // decoder_suspend + nullptr, // decoder_configure }; -static tA2DP_STATUS A2DP_CodecInfoMatchesCapabilityAac( - const tA2DP_AAC_CIE* p_cap, const uint8_t* p_codec_info, - bool is_capability); +static tA2DP_STATUS A2DP_CodecInfoMatchesCapabilityAac(const tA2DP_AAC_CIE* p_cap, + const uint8_t* p_codec_info, + bool is_capability); // Builds the AAC Media Codec Capabilities byte sequence beginning from the // LOSC octet. |media_type| is the media type |AVDT_MEDIA_TYPE_*|. // |p_ie| is a pointer to the AAC Codec Information Element information. // The result is stored in |p_result|. Returns A2DP_SUCCESS on success, // otherwise the corresponding A2DP error status code. -static tA2DP_STATUS A2DP_BuildInfoAac(uint8_t media_type, - const tA2DP_AAC_CIE* p_ie, +static tA2DP_STATUS A2DP_BuildInfoAac(uint8_t media_type, const tA2DP_AAC_CIE* p_ie, uint8_t* p_result) { if (p_ie == NULL || p_result == NULL) { return A2DP_INVALID_PARAMS; @@ -153,16 +152,22 @@ static tA2DP_STATUS A2DP_BuildInfoAac(uint8_t media_type, *p_result++ = A2DP_MEDIA_CT_AAC; // Object Type - if (p_ie->objectType == 0) return A2DP_INVALID_PARAMS; + if (p_ie->objectType == 0) { + return A2DP_INVALID_PARAMS; + } *p_result++ = p_ie->objectType; // Sampling Frequency - if (p_ie->sampleRate == 0) return A2DP_INVALID_PARAMS; + if (p_ie->sampleRate == 0) { + return A2DP_INVALID_PARAMS; + } *p_result++ = (uint8_t)(p_ie->sampleRate & A2DP_AAC_SAMPLING_FREQ_MASK0); *p_result = (uint8_t)((p_ie->sampleRate & A2DP_AAC_SAMPLING_FREQ_MASK1) >> 8); // Channel Mode - if (p_ie->channelMode == 0) return A2DP_INVALID_PARAMS; + if (p_ie->channelMode == 0) { + return A2DP_INVALID_PARAMS; + } *p_result++ |= (p_ie->channelMode & A2DP_AAC_CHANNEL_MODE_MASK); // Variable Bit Rate Support @@ -182,18 +187,21 @@ static tA2DP_STATUS A2DP_BuildInfoAac(uint8_t media_type, // codec capabilities, otherwise is codec configuration. // Returns A2DP_SUCCESS on success, otherwise the corresponding A2DP error // status code. -static tA2DP_STATUS A2DP_ParseInfoAac(tA2DP_AAC_CIE* p_ie, - const uint8_t* p_codec_info, +static tA2DP_STATUS A2DP_ParseInfoAac(tA2DP_AAC_CIE* p_ie, const uint8_t* p_codec_info, bool is_capability) { uint8_t losc; uint8_t media_type; tA2DP_CODEC_TYPE codec_type; - if (p_ie == NULL || p_codec_info == NULL) return A2DP_INVALID_PARAMS; + if (p_ie == NULL || p_codec_info == NULL) { + return A2DP_INVALID_PARAMS; + } // Check the codec capability length losc = *p_codec_info++; - if (losc != A2DP_AAC_CODEC_LEN) return A2DP_WRONG_CODEC; + if (losc != A2DP_AAC_CODEC_LEN) { + return A2DP_WRONG_CODEC; + } media_type = (*p_codec_info++) >> 4; codec_type = *p_codec_info++; @@ -209,8 +217,7 @@ static tA2DP_STATUS A2DP_ParseInfoAac(tA2DP_AAC_CIE* p_ie, p_ie->channelMode = *p_codec_info & A2DP_AAC_CHANNEL_MODE_MASK; p_codec_info++; - p_ie->variableBitRateSupport = - *p_codec_info & A2DP_AAC_VARIABLE_BIT_RATE_MASK; + p_ie->variableBitRateSupport = *p_codec_info & A2DP_AAC_VARIABLE_BIT_RATE_MASK; p_ie->bitRate = ((*p_codec_info) << 16 & A2DP_AAC_BIT_RATE_MASK0) | (*(p_codec_info + 1) << 8 & A2DP_AAC_BIT_RATE_MASK1) | @@ -220,22 +227,28 @@ static tA2DP_STATUS A2DP_ParseInfoAac(tA2DP_AAC_CIE* p_ie, if (is_capability) { // NOTE: The checks here are very liberal. We should be using more // pedantic checks specific to the SRC or SNK as specified in the spec. - if (A2DP_BitsSet(p_ie->objectType) == A2DP_SET_ZERO_BIT) + if (A2DP_BitsSet(p_ie->objectType) == A2DP_SET_ZERO_BIT) { return A2DP_BAD_OBJ_TYPE; - if (A2DP_BitsSet(p_ie->sampleRate) == A2DP_SET_ZERO_BIT) + } + if (A2DP_BitsSet(p_ie->sampleRate) == A2DP_SET_ZERO_BIT) { return A2DP_BAD_SAMP_FREQ; - if (A2DP_BitsSet(p_ie->channelMode) == A2DP_SET_ZERO_BIT) + } + if (A2DP_BitsSet(p_ie->channelMode) == A2DP_SET_ZERO_BIT) { return A2DP_BAD_CH_MODE; + } return A2DP_SUCCESS; } - if (A2DP_BitsSet(p_ie->objectType) != A2DP_SET_ONE_BIT) + if (A2DP_BitsSet(p_ie->objectType) != A2DP_SET_ONE_BIT) { return A2DP_BAD_OBJ_TYPE; - if (A2DP_BitsSet(p_ie->sampleRate) != A2DP_SET_ONE_BIT) + } + if (A2DP_BitsSet(p_ie->sampleRate) != A2DP_SET_ONE_BIT) { return A2DP_BAD_SAMP_FREQ; - if (A2DP_BitsSet(p_ie->channelMode) != A2DP_SET_ONE_BIT) + } + if (A2DP_BitsSet(p_ie->channelMode) != A2DP_SET_ONE_BIT) { return A2DP_BAD_CH_MODE; + } return A2DP_SUCCESS; } @@ -273,13 +286,13 @@ bool A2DP_IsPeerSinkCodecValidAac(const uint8_t* p_codec_info) { } bool A2DP_IsSinkCodecSupportedAac(const uint8_t* p_codec_info) { - return A2DP_CodecInfoMatchesCapabilityAac(&a2dp_aac_sink_caps, p_codec_info, - false) == A2DP_SUCCESS; + return A2DP_CodecInfoMatchesCapabilityAac(&a2dp_aac_sink_caps, p_codec_info, false) == + A2DP_SUCCESS; } bool A2DP_IsPeerSourceCodecSupportedAac(const uint8_t* p_codec_info) { - return A2DP_CodecInfoMatchesCapabilityAac(&a2dp_aac_sink_caps, p_codec_info, - true) == A2DP_SUCCESS; + return A2DP_CodecInfoMatchesCapabilityAac(&a2dp_aac_sink_caps, p_codec_info, true) == + A2DP_SUCCESS; } // Checks whether A2DP AAC codec configuration matches with a device's codec @@ -288,9 +301,9 @@ bool A2DP_IsPeerSourceCodecSupportedAac(const uint8_t* p_codec_info) { // |p_codec_info| contains A2DP codec capability. // Returns A2DP_SUCCESS if the codec configuration matches with capabilities, // otherwise the corresponding A2DP error status code. -static tA2DP_STATUS A2DP_CodecInfoMatchesCapabilityAac( - const tA2DP_AAC_CIE* p_cap, const uint8_t* p_codec_info, - bool is_capability) { +static tA2DP_STATUS A2DP_CodecInfoMatchesCapabilityAac(const tA2DP_AAC_CIE* p_cap, + const uint8_t* p_codec_info, + bool is_capability) { tA2DP_STATUS status; tA2DP_AAC_CIE cfg_cie; @@ -303,25 +316,29 @@ static tA2DP_STATUS A2DP_CodecInfoMatchesCapabilityAac( /* verify that each parameter is in range */ - log::verbose("Object Type peer: 0x{:x}, capability 0x{:x}", - cfg_cie.objectType, p_cap->objectType); - log::verbose("Sample Rate peer: {}, capability {}", cfg_cie.sampleRate, - p_cap->sampleRate); - log::verbose("Channel Mode peer: 0x{:x}, capability 0x{:x}", - cfg_cie.channelMode, p_cap->channelMode); + log::verbose("Object Type peer: 0x{:x}, capability 0x{:x}", cfg_cie.objectType, + p_cap->objectType); + log::verbose("Sample Rate peer: {}, capability {}", cfg_cie.sampleRate, p_cap->sampleRate); + log::verbose("Channel Mode peer: 0x{:x}, capability 0x{:x}", cfg_cie.channelMode, + p_cap->channelMode); log::verbose("Variable Bit Rate Support peer: 0x{:x}, capability 0x{:x}", cfg_cie.variableBitRateSupport, p_cap->variableBitRateSupport); - log::verbose("Bit Rate peer: {}, capability {}", cfg_cie.bitRate, - p_cap->bitRate); + log::verbose("Bit Rate peer: {}, capability {}", cfg_cie.bitRate, p_cap->bitRate); /* Object Type */ - if ((cfg_cie.objectType & p_cap->objectType) == 0) return A2DP_BAD_OBJ_TYPE; + if ((cfg_cie.objectType & p_cap->objectType) == 0) { + return A2DP_BAD_OBJ_TYPE; + } /* Sample Rate */ - if ((cfg_cie.sampleRate & p_cap->sampleRate) == 0) return A2DP_BAD_SAMP_FREQ; + if ((cfg_cie.sampleRate & p_cap->sampleRate) == 0) { + return A2DP_BAD_SAMP_FREQ; + } /* Channel Mode */ - if ((cfg_cie.channelMode & p_cap->channelMode) == 0) return A2DP_NS_CH_MODE; + if ((cfg_cie.channelMode & p_cap->channelMode) == 0) { + return A2DP_NS_CH_MODE; + } return A2DP_SUCCESS; } @@ -331,18 +348,14 @@ bool A2DP_UsesRtpHeaderAac(bool /* content_protection_enabled */, return true; } -const char* A2DP_CodecNameAac(const uint8_t* /* p_codec_info */) { - return "AAC"; -} +const char* A2DP_CodecNameAac(const uint8_t* /* p_codec_info */) { return "AAC"; } -bool A2DP_CodecTypeEqualsAac(const uint8_t* p_codec_info_a, - const uint8_t* p_codec_info_b) { +bool A2DP_CodecTypeEqualsAac(const uint8_t* p_codec_info_a, const uint8_t* p_codec_info_b) { tA2DP_AAC_CIE aac_cie_a; tA2DP_AAC_CIE aac_cie_b; // Check whether the codec info contains valid data - tA2DP_STATUS a2dp_status = - A2DP_ParseInfoAac(&aac_cie_a, p_codec_info_a, true); + tA2DP_STATUS a2dp_status = A2DP_ParseInfoAac(&aac_cie_a, p_codec_info_a, true); if (a2dp_status != A2DP_SUCCESS) { log::error("cannot decode codec information: {}", a2dp_status); return false; @@ -356,14 +369,12 @@ bool A2DP_CodecTypeEqualsAac(const uint8_t* p_codec_info_a, return true; } -bool A2DP_CodecEqualsAac(const uint8_t* p_codec_info_a, - const uint8_t* p_codec_info_b) { +bool A2DP_CodecEqualsAac(const uint8_t* p_codec_info_a, const uint8_t* p_codec_info_b) { tA2DP_AAC_CIE aac_cie_a; tA2DP_AAC_CIE aac_cie_b; // Check whether the codec info contains valid data - tA2DP_STATUS a2dp_status = - A2DP_ParseInfoAac(&aac_cie_a, p_codec_info_a, true); + tA2DP_STATUS a2dp_status = A2DP_ParseInfoAac(&aac_cie_a, p_codec_info_a, true); if (a2dp_status != A2DP_SUCCESS) { log::error("cannot decode codec information: {}", a2dp_status); return false; @@ -377,8 +388,7 @@ bool A2DP_CodecEqualsAac(const uint8_t* p_codec_info_a, return (aac_cie_a.objectType == aac_cie_b.objectType) && (aac_cie_a.sampleRate == aac_cie_b.sampleRate) && (aac_cie_a.channelMode == aac_cie_b.channelMode) && - (aac_cie_a.variableBitRateSupport == - aac_cie_b.variableBitRateSupport) && + (aac_cie_a.variableBitRateSupport == aac_cie_b.variableBitRateSupport) && (aac_cie_a.bitRate == aac_cie_b.bitRate); } @@ -565,7 +575,9 @@ int A2DP_ComputeMaxBitRateAac(const uint8_t* p_codec_info, uint16_t mtu) { } int sampling_freq = A2DP_GetTrackSampleRateAac(p_codec_info); - if (sampling_freq == -1) return -1; + if (sampling_freq == -1) { + return -1; + } int pcm_channel_samples_per_frame = 0; switch (aac_cie.objectType) { @@ -580,22 +592,23 @@ int A2DP_ComputeMaxBitRateAac(const uint8_t* p_codec_info, uint16_t mtu) { default: break; } - if (pcm_channel_samples_per_frame == 0) return -1; + if (pcm_channel_samples_per_frame == 0) { + return -1; + } // See Section 3.2.1 Estimating Average Frame Size from // the aacEncoder.pdf document included with the AAC source code. return (8 * mtu * sampling_freq) / pcm_channel_samples_per_frame; } -bool A2DP_GetPacketTimestampAac(const uint8_t* p_codec_info, - const uint8_t* p_data, uint32_t* p_timestamp) { +bool A2DP_GetPacketTimestampAac(const uint8_t* p_codec_info, const uint8_t* p_data, + uint32_t* p_timestamp) { // TODO: Is this function really codec-specific? *p_timestamp = *(const uint32_t*)p_data; return true; } -bool A2DP_BuildCodecHeaderAac(const uint8_t* /* p_codec_info */, - BT_HDR* /* p_buf */, +bool A2DP_BuildCodecHeaderAac(const uint8_t* /* p_codec_info */, BT_HDR* /* p_buf */, uint16_t /* frames_per_packet */) { return true; } @@ -608,8 +621,7 @@ std::string A2DP_CodecInfoStringAac(const uint8_t* p_codec_info) { a2dp_status = A2DP_ParseInfoAac(&aac_cie, p_codec_info, true); if (a2dp_status != A2DP_SUCCESS) { - res << "A2DP_ParseInfoAac fail: " - << loghex(static_cast(a2dp_status)); + res << "A2DP_ParseInfoAac fail: " << loghex(static_cast(a2dp_status)); return res.str(); } @@ -618,60 +630,40 @@ std::string A2DP_CodecInfoStringAac(const uint8_t* p_codec_info) { // Object type field.clear(); AppendField(&field, (aac_cie.objectType == 0), "NONE"); - AppendField(&field, (aac_cie.objectType & A2DP_AAC_OBJECT_TYPE_MPEG2_LC), - "(MPEG-2 AAC LC)"); - AppendField(&field, (aac_cie.objectType & A2DP_AAC_OBJECT_TYPE_MPEG4_LC), - "(MPEG-4 AAC LC)"); - AppendField(&field, (aac_cie.objectType & A2DP_AAC_OBJECT_TYPE_MPEG4_LTP), - "(MPEG-4 AAC LTP)"); - AppendField(&field, - (aac_cie.objectType & A2DP_AAC_OBJECT_TYPE_MPEG4_SCALABLE), + AppendField(&field, (aac_cie.objectType & A2DP_AAC_OBJECT_TYPE_MPEG2_LC), "(MPEG-2 AAC LC)"); + AppendField(&field, (aac_cie.objectType & A2DP_AAC_OBJECT_TYPE_MPEG4_LC), "(MPEG-4 AAC LC)"); + AppendField(&field, (aac_cie.objectType & A2DP_AAC_OBJECT_TYPE_MPEG4_LTP), "(MPEG-4 AAC LTP)"); + AppendField(&field, (aac_cie.objectType & A2DP_AAC_OBJECT_TYPE_MPEG4_SCALABLE), "(MPEG-4 AAC Scalable)"); - res << "\tobjectType: " << field << " (" << loghex(aac_cie.objectType) - << ")\n"; + res << "\tobjectType: " << field << " (" << loghex(aac_cie.objectType) << ")\n"; // Sample frequency field.clear(); AppendField(&field, (aac_cie.sampleRate == 0), "NONE"); - AppendField(&field, (aac_cie.sampleRate & A2DP_AAC_SAMPLING_FREQ_8000), - "8000"); - AppendField(&field, (aac_cie.sampleRate & A2DP_AAC_SAMPLING_FREQ_11025), - "11025"); - AppendField(&field, (aac_cie.sampleRate & A2DP_AAC_SAMPLING_FREQ_12000), - "12000"); - AppendField(&field, (aac_cie.sampleRate & A2DP_AAC_SAMPLING_FREQ_16000), - "16000"); - AppendField(&field, (aac_cie.sampleRate & A2DP_AAC_SAMPLING_FREQ_22050), - "22050"); - AppendField(&field, (aac_cie.sampleRate & A2DP_AAC_SAMPLING_FREQ_24000), - "24000"); - AppendField(&field, (aac_cie.sampleRate & A2DP_AAC_SAMPLING_FREQ_32000), - "32000"); - AppendField(&field, (aac_cie.sampleRate & A2DP_AAC_SAMPLING_FREQ_44100), - "44100"); - AppendField(&field, (aac_cie.sampleRate & A2DP_AAC_SAMPLING_FREQ_48000), - "48000"); - AppendField(&field, (aac_cie.sampleRate & A2DP_AAC_SAMPLING_FREQ_64000), - "64000"); - AppendField(&field, (aac_cie.sampleRate & A2DP_AAC_SAMPLING_FREQ_88200), - "88200"); - AppendField(&field, (aac_cie.sampleRate & A2DP_AAC_SAMPLING_FREQ_96000), - "96000"); - res << "\tsamp_freq: " << field << " (" << loghex(aac_cie.sampleRate) - << ")\n"; + AppendField(&field, (aac_cie.sampleRate & A2DP_AAC_SAMPLING_FREQ_8000), "8000"); + AppendField(&field, (aac_cie.sampleRate & A2DP_AAC_SAMPLING_FREQ_11025), "11025"); + AppendField(&field, (aac_cie.sampleRate & A2DP_AAC_SAMPLING_FREQ_12000), "12000"); + AppendField(&field, (aac_cie.sampleRate & A2DP_AAC_SAMPLING_FREQ_16000), "16000"); + AppendField(&field, (aac_cie.sampleRate & A2DP_AAC_SAMPLING_FREQ_22050), "22050"); + AppendField(&field, (aac_cie.sampleRate & A2DP_AAC_SAMPLING_FREQ_24000), "24000"); + AppendField(&field, (aac_cie.sampleRate & A2DP_AAC_SAMPLING_FREQ_32000), "32000"); + AppendField(&field, (aac_cie.sampleRate & A2DP_AAC_SAMPLING_FREQ_44100), "44100"); + AppendField(&field, (aac_cie.sampleRate & A2DP_AAC_SAMPLING_FREQ_48000), "48000"); + AppendField(&field, (aac_cie.sampleRate & A2DP_AAC_SAMPLING_FREQ_64000), "64000"); + AppendField(&field, (aac_cie.sampleRate & A2DP_AAC_SAMPLING_FREQ_88200), "88200"); + AppendField(&field, (aac_cie.sampleRate & A2DP_AAC_SAMPLING_FREQ_96000), "96000"); + res << "\tsamp_freq: " << field << " (" << loghex(aac_cie.sampleRate) << ")\n"; // Channel mode field.clear(); AppendField(&field, (aac_cie.channelMode == 0), "NONE"); - AppendField(&field, (aac_cie.channelMode == A2DP_AAC_CHANNEL_MODE_MONO), - "Mono"); - AppendField(&field, (aac_cie.channelMode == A2DP_AAC_CHANNEL_MODE_STEREO), - "Stereo"); + AppendField(&field, (aac_cie.channelMode == A2DP_AAC_CHANNEL_MODE_MONO), "Mono"); + AppendField(&field, (aac_cie.channelMode == A2DP_AAC_CHANNEL_MODE_STEREO), "Stereo"); res << "\tch_mode: " << field << " (" << loghex(aac_cie.channelMode) << ")\n"; // Variable bit rate support - res << "\tvariableBitRateSupport: " << std::boolalpha - << (aac_cie.variableBitRateSupport != 0) << "\n"; + res << "\tvariableBitRateSupport: " << std::boolalpha << (aac_cie.variableBitRateSupport != 0) + << "\n"; // Bit rate res << "\tbitRate: " << std::to_string(aac_cie.bitRate) << "\n"; @@ -679,16 +671,18 @@ std::string A2DP_CodecInfoStringAac(const uint8_t* p_codec_info) { return res.str(); } -const tA2DP_ENCODER_INTERFACE* A2DP_GetEncoderInterfaceAac( - const uint8_t* p_codec_info) { - if (!A2DP_IsSourceCodecValidAac(p_codec_info)) return NULL; +const tA2DP_ENCODER_INTERFACE* A2DP_GetEncoderInterfaceAac(const uint8_t* p_codec_info) { + if (!A2DP_IsSourceCodecValidAac(p_codec_info)) { + return NULL; + } return &a2dp_encoder_interface_aac; } -const tA2DP_DECODER_INTERFACE* A2DP_GetDecoderInterfaceAac( - const uint8_t* p_codec_info) { - if (!A2DP_IsSinkCodecValidAac(p_codec_info)) return NULL; +const tA2DP_DECODER_INTERFACE* A2DP_GetDecoderInterfaceAac(const uint8_t* p_codec_info) { + if (!A2DP_IsSinkCodecValidAac(p_codec_info)) { + return NULL; + } return &a2dp_decoder_interface_aac; } @@ -697,19 +691,18 @@ bool A2DP_AdjustCodecAac(uint8_t* p_codec_info) { tA2DP_AAC_CIE cfg_cie; // Nothing to do: just verify the codec info is valid - if (A2DP_ParseInfoAac(&cfg_cie, p_codec_info, true) != A2DP_SUCCESS) + if (A2DP_ParseInfoAac(&cfg_cie, p_codec_info, true) != A2DP_SUCCESS) { return false; + } return true; } -btav_a2dp_codec_index_t A2DP_SourceCodecIndexAac( - const uint8_t* /* p_codec_info */) { +btav_a2dp_codec_index_t A2DP_SourceCodecIndexAac(const uint8_t* /* p_codec_info */) { return BTAV_A2DP_CODEC_INDEX_SOURCE_AAC; } -btav_a2dp_codec_index_t A2DP_SinkCodecIndexAac( - const uint8_t* /* p_codec_info */) { +btav_a2dp_codec_index_t A2DP_SinkCodecIndexAac(const uint8_t* /* p_codec_info */) { return BTAV_A2DP_CODEC_INDEX_SINK_AAC; } @@ -721,17 +714,16 @@ void aac_source_caps_initialize() { if (aac_source_caps_configured) { return; } - a2dp_aac_source_caps = - osi_property_get_bool("persist.bluetooth.a2dp_aac.vbr_supported", false) - ? a2dp_aac_vbr_source_caps - : a2dp_aac_cbr_source_caps; + a2dp_aac_source_caps = osi_property_get_bool("persist.bluetooth.a2dp_aac.vbr_supported", false) + ? a2dp_aac_vbr_source_caps + : a2dp_aac_cbr_source_caps; aac_source_caps_configured = true; } bool A2DP_InitCodecConfigAac(AvdtpSepConfig* p_cfg) { aac_source_caps_initialize(); - if (A2DP_BuildInfoAac(AVDT_MEDIA_TYPE_AUDIO, &a2dp_aac_source_caps, - p_cfg->codec_info) != A2DP_SUCCESS) { + if (A2DP_BuildInfoAac(AVDT_MEDIA_TYPE_AUDIO, &a2dp_aac_source_caps, p_cfg->codec_info) != + A2DP_SUCCESS) { return false; } @@ -739,34 +731,38 @@ bool A2DP_InitCodecConfigAac(AvdtpSepConfig* p_cfg) { } bool A2DP_InitCodecConfigAacSink(AvdtpSepConfig* p_cfg) { - return A2DP_BuildInfoAac(AVDT_MEDIA_TYPE_AUDIO, &a2dp_aac_sink_caps, - p_cfg->codec_info) == A2DP_SUCCESS; + return A2DP_BuildInfoAac(AVDT_MEDIA_TYPE_AUDIO, &a2dp_aac_sink_caps, p_cfg->codec_info) == + A2DP_SUCCESS; } UNUSED_ATTR static void build_codec_config(const tA2DP_AAC_CIE& config_cie, btav_a2dp_codec_config_t* result) { - if (config_cie.sampleRate & A2DP_AAC_SAMPLING_FREQ_44100) + if (config_cie.sampleRate & A2DP_AAC_SAMPLING_FREQ_44100) { result->sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_44100; - if (config_cie.sampleRate & A2DP_AAC_SAMPLING_FREQ_48000) + } + if (config_cie.sampleRate & A2DP_AAC_SAMPLING_FREQ_48000) { result->sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_48000; - if (config_cie.sampleRate & A2DP_AAC_SAMPLING_FREQ_88200) + } + if (config_cie.sampleRate & A2DP_AAC_SAMPLING_FREQ_88200) { result->sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_88200; - if (config_cie.sampleRate & A2DP_AAC_SAMPLING_FREQ_96000) + } + if (config_cie.sampleRate & A2DP_AAC_SAMPLING_FREQ_96000) { result->sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_96000; + } result->bits_per_sample = config_cie.bits_per_sample; - if (config_cie.channelMode & A2DP_AAC_CHANNEL_MODE_MONO) + if (config_cie.channelMode & A2DP_AAC_CHANNEL_MODE_MONO) { result->channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_MONO; + } if (config_cie.channelMode & A2DP_AAC_CHANNEL_MODE_STEREO) { result->channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; } } -A2dpCodecConfigAacSource::A2dpCodecConfigAacSource( - btav_a2dp_codec_priority_t codec_priority) - : A2dpCodecConfigAacBase(BTAV_A2DP_CODEC_INDEX_SOURCE_AAC, - A2DP_CodecIndexStrAac(), codec_priority, true) { +A2dpCodecConfigAacSource::A2dpCodecConfigAacSource(btav_a2dp_codec_priority_t codec_priority) + : A2dpCodecConfigAacBase(BTAV_A2DP_CODEC_INDEX_SOURCE_AAC, A2DP_CodecIndexStrAac(), + codec_priority, true) { aac_source_caps_initialize(); // Compute the local capability if (a2dp_aac_source_caps.sampleRate & A2DP_AAC_SAMPLING_FREQ_44100) { @@ -781,8 +777,7 @@ A2dpCodecConfigAacSource::A2dpCodecConfigAacSource( if (a2dp_aac_source_caps.sampleRate & A2DP_AAC_SAMPLING_FREQ_96000) { codec_local_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_96000; } - codec_local_capability_.bits_per_sample = - a2dp_aac_source_caps.bits_per_sample; + codec_local_capability_.bits_per_sample = a2dp_aac_source_caps.bits_per_sample; if (a2dp_aac_source_caps.channelMode & A2DP_AAC_CHANNEL_MODE_MONO) { codec_local_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_MONO; } @@ -794,7 +789,9 @@ A2dpCodecConfigAacSource::A2dpCodecConfigAacSource( A2dpCodecConfigAacSource::~A2dpCodecConfigAacSource() {} bool A2dpCodecConfigAacSource::init() { - if (!isValid()) return false; + if (!isValid()) { + return false; + } // Load the encoder if (!A2DP_LoadEncoderAac()) { @@ -812,8 +809,7 @@ bool A2dpCodecConfigAacSource::useRtpHeaderMarkerBit() const { return true; } // The result is stored in |p_result| and |p_codec_config|. // Returns true if a selection was made, otherwise false. // -static bool select_best_sample_rate(uint16_t sampleRate, - tA2DP_AAC_CIE* p_result, +static bool select_best_sample_rate(uint16_t sampleRate, tA2DP_AAC_CIE* p_result, btav_a2dp_codec_config_t* p_codec_config) { if (sampleRate & A2DP_AAC_SAMPLING_FREQ_96000) { p_result->sampleRate = A2DP_AAC_SAMPLING_FREQ_96000; @@ -844,9 +840,9 @@ static bool select_best_sample_rate(uint16_t sampleRate, // The result is stored in |p_result| and |p_codec_config|. // Returns true if a selection was made, otherwise false. // -static bool select_audio_sample_rate( - const btav_a2dp_codec_config_t* p_codec_audio_config, uint16_t sampleRate, - tA2DP_AAC_CIE* p_result, btav_a2dp_codec_config_t* p_codec_config) { +static bool select_audio_sample_rate(const btav_a2dp_codec_config_t* p_codec_audio_config, + uint16_t sampleRate, tA2DP_AAC_CIE* p_result, + btav_a2dp_codec_config_t* p_codec_config) { switch (p_codec_audio_config->sample_rate) { case BTAV_A2DP_CODEC_SAMPLE_RATE_44100: if (sampleRate & A2DP_AAC_SAMPLING_FREQ_44100) { @@ -892,9 +888,9 @@ static bool select_audio_sample_rate( // The result is stored in |p_result| and |p_codec_config|. // Returns true if a selection was made, otherwise false. // -static bool select_best_bits_per_sample( - btav_a2dp_codec_bits_per_sample_t bits_per_sample, tA2DP_AAC_CIE* p_result, - btav_a2dp_codec_config_t* p_codec_config) { +static bool select_best_bits_per_sample(btav_a2dp_codec_bits_per_sample_t bits_per_sample, + tA2DP_AAC_CIE* p_result, + btav_a2dp_codec_config_t* p_codec_config) { if (bits_per_sample & BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32) { p_codec_config->bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32; p_result->bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32; @@ -919,10 +915,10 @@ static bool select_best_bits_per_sample( // The result is stored in |p_result| and |p_codec_config|. // Returns true if a selection was made, otherwise false. // -static bool select_audio_bits_per_sample( - const btav_a2dp_codec_config_t* p_codec_audio_config, - btav_a2dp_codec_bits_per_sample_t bits_per_sample, tA2DP_AAC_CIE* p_result, - btav_a2dp_codec_config_t* p_codec_config) { +static bool select_audio_bits_per_sample(const btav_a2dp_codec_config_t* p_codec_audio_config, + btav_a2dp_codec_bits_per_sample_t bits_per_sample, + tA2DP_AAC_CIE* p_result, + btav_a2dp_codec_config_t* p_codec_config) { switch (p_codec_audio_config->bits_per_sample) { case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16: if (bits_per_sample & BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16) { @@ -956,8 +952,7 @@ static bool select_audio_bits_per_sample( // The result is stored in |p_result| and |p_codec_config|. // Returns true if a selection was made, otherwise false. // -static bool select_best_channel_mode(uint8_t channelMode, - tA2DP_AAC_CIE* p_result, +static bool select_best_channel_mode(uint8_t channelMode, tA2DP_AAC_CIE* p_result, btav_a2dp_codec_config_t* p_codec_config) { if (channelMode & A2DP_AAC_CHANNEL_MODE_STEREO) { p_result->channelMode = A2DP_AAC_CHANNEL_MODE_STEREO; @@ -978,9 +973,9 @@ static bool select_best_channel_mode(uint8_t channelMode, // The result is stored in |p_result| and |p_codec_config|. // Returns true if a selection was made, otherwise false. // -static bool select_audio_channel_mode( - const btav_a2dp_codec_config_t* p_codec_audio_config, uint8_t channelMode, - tA2DP_AAC_CIE* p_result, btav_a2dp_codec_config_t* p_codec_config) { +static bool select_audio_channel_mode(const btav_a2dp_codec_config_t* p_codec_audio_config, + uint8_t channelMode, tA2DP_AAC_CIE* p_result, + btav_a2dp_codec_config_t* p_codec_config) { switch (p_codec_audio_config->channel_mode) { case BTAV_A2DP_CODEC_CHANNEL_MODE_MONO: if (channelMode & A2DP_AAC_CHANNEL_MODE_MONO) { @@ -1003,8 +998,7 @@ static bool select_audio_channel_mode( return false; } -bool A2dpCodecConfigAacBase::setCodecConfig(const uint8_t* p_peer_codec_info, - bool is_capability, +bool A2dpCodecConfigAacBase::setCodecConfig(const uint8_t* p_peer_codec_info, bool is_capability, uint8_t* p_result_codec_config) { std::lock_guard lock(codec_mutex_); tA2DP_AAC_CIE peer_info_cie; @@ -1012,14 +1006,12 @@ bool A2dpCodecConfigAacBase::setCodecConfig(const uint8_t* p_peer_codec_info, uint8_t channelMode; uint16_t sampleRate; btav_a2dp_codec_bits_per_sample_t bits_per_sample; - const tA2DP_AAC_CIE* p_a2dp_aac_caps = - (is_source_) ? &a2dp_aac_source_caps : &a2dp_aac_sink_caps; + const tA2DP_AAC_CIE* p_a2dp_aac_caps = (is_source_) ? &a2dp_aac_source_caps : &a2dp_aac_sink_caps; // Save the internal state btav_a2dp_codec_config_t saved_codec_config = codec_config_; btav_a2dp_codec_config_t saved_codec_capability = codec_capability_; - btav_a2dp_codec_config_t saved_codec_selectable_capability = - codec_selectable_capability_; + btav_a2dp_codec_config_t saved_codec_selectable_capability = codec_selectable_capability_; btav_a2dp_codec_config_t saved_codec_user_config = codec_user_config_; btav_a2dp_codec_config_t saved_codec_audio_config = codec_audio_config_; uint8_t saved_ota_codec_config[AVDT_CODEC_SIZE]; @@ -1028,11 +1020,9 @@ bool A2dpCodecConfigAacBase::setCodecConfig(const uint8_t* p_peer_codec_info, memcpy(saved_ota_codec_config, ota_codec_config_, sizeof(ota_codec_config_)); memcpy(saved_ota_codec_peer_capability, ota_codec_peer_capability_, sizeof(ota_codec_peer_capability_)); - memcpy(saved_ota_codec_peer_config, ota_codec_peer_config_, - sizeof(ota_codec_peer_config_)); + memcpy(saved_ota_codec_peer_config, ota_codec_peer_config_, sizeof(ota_codec_peer_config_)); - tA2DP_STATUS status = - A2DP_ParseInfoAac(&peer_info_cie, p_peer_codec_info, is_capability); + tA2DP_STATUS status = A2DP_ParseInfoAac(&peer_info_cie, p_peer_codec_info, is_capability); if (status != A2DP_SUCCESS) { log::error("can't parse peer's capabilities: error = {}", status); goto fail; @@ -1047,15 +1037,13 @@ bool A2dpCodecConfigAacBase::setCodecConfig(const uint8_t* p_peer_codec_info, result_config_cie.objectType = p_a2dp_aac_caps->objectType; // The Variable Bit Rate Support is disabled if either side disables it result_config_cie.variableBitRateSupport = - p_a2dp_aac_caps->variableBitRateSupport & - peer_info_cie.variableBitRateSupport; - if (result_config_cie.variableBitRateSupport != - A2DP_AAC_VARIABLE_BIT_RATE_DISABLED) { + p_a2dp_aac_caps->variableBitRateSupport & peer_info_cie.variableBitRateSupport; + if (result_config_cie.variableBitRateSupport != A2DP_AAC_VARIABLE_BIT_RATE_DISABLED) { codec_config_.codec_specific_1 = - static_cast(AacEncoderBitrateMode::AACENC_BR_MODE_VBR_5); + static_cast(AacEncoderBitrateMode::AACENC_BR_MODE_VBR_5); } else { codec_config_.codec_specific_1 = - static_cast(AacEncoderBitrateMode::AACENC_BR_MODE_CBR); + static_cast(AacEncoderBitrateMode::AACENC_BR_MODE_CBR); } // Set the bit rate as follows: @@ -1071,8 +1059,7 @@ bool A2dpCodecConfigAacBase::setCodecConfig(const uint8_t* p_peer_codec_info, // Bogus bit rate result_config_cie.bitRate = p_a2dp_aac_caps->bitRate; } else { - result_config_cie.bitRate = - std::min(p_a2dp_aac_caps->bitRate, peer_info_cie.bitRate); + result_config_cie.bitRate = std::min(p_a2dp_aac_caps->bitRate, peer_info_cie.bitRate); } // @@ -1123,58 +1110,58 @@ bool A2dpCodecConfigAacBase::setCodecConfig(const uint8_t* p_peer_codec_info, do { // Compute the selectable capability if (sampleRate & A2DP_AAC_SAMPLING_FREQ_44100) { - codec_selectable_capability_.sample_rate |= - BTAV_A2DP_CODEC_SAMPLE_RATE_44100; + codec_selectable_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_44100; } if (sampleRate & A2DP_AAC_SAMPLING_FREQ_48000) { - codec_selectable_capability_.sample_rate |= - BTAV_A2DP_CODEC_SAMPLE_RATE_48000; + codec_selectable_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_48000; } if (sampleRate & A2DP_AAC_SAMPLING_FREQ_88200) { - codec_selectable_capability_.sample_rate |= - BTAV_A2DP_CODEC_SAMPLE_RATE_88200; + codec_selectable_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_88200; } if (sampleRate & A2DP_AAC_SAMPLING_FREQ_96000) { - codec_selectable_capability_.sample_rate |= - BTAV_A2DP_CODEC_SAMPLE_RATE_96000; + codec_selectable_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_96000; } - if (codec_config_.sample_rate != BTAV_A2DP_CODEC_SAMPLE_RATE_NONE) break; + if (codec_config_.sample_rate != BTAV_A2DP_CODEC_SAMPLE_RATE_NONE) { + break; + } // Compute the common capability - if (sampleRate & A2DP_AAC_SAMPLING_FREQ_44100) + if (sampleRate & A2DP_AAC_SAMPLING_FREQ_44100) { codec_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_44100; - if (sampleRate & A2DP_AAC_SAMPLING_FREQ_48000) + } + if (sampleRate & A2DP_AAC_SAMPLING_FREQ_48000) { codec_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_48000; - if (sampleRate & A2DP_AAC_SAMPLING_FREQ_88200) + } + if (sampleRate & A2DP_AAC_SAMPLING_FREQ_88200) { codec_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_88200; - if (sampleRate & A2DP_AAC_SAMPLING_FREQ_96000) + } + if (sampleRate & A2DP_AAC_SAMPLING_FREQ_96000) { codec_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_96000; + } // No user preference - try the codec audio config - if (select_audio_sample_rate(&codec_audio_config_, sampleRate, - &result_config_cie, &codec_config_)) { + if (select_audio_sample_rate(&codec_audio_config_, sampleRate, &result_config_cie, + &codec_config_)) { break; } // No user preference - try the default config - if (select_best_sample_rate( - a2dp_aac_default_config.sampleRate & peer_info_cie.sampleRate, - &result_config_cie, &codec_config_)) { + if (select_best_sample_rate(a2dp_aac_default_config.sampleRate & peer_info_cie.sampleRate, + &result_config_cie, &codec_config_)) { break; } // No user preference - use the best match - if (select_best_sample_rate(sampleRate, &result_config_cie, - &codec_config_)) { + if (select_best_sample_rate(sampleRate, &result_config_cie, &codec_config_)) { break; } } while (false); if (codec_config_.sample_rate == BTAV_A2DP_CODEC_SAMPLE_RATE_NONE) { log::error( - "cannot match sample frequency: source caps = 0x{:x} peer info = " - "0x{:x}", - p_a2dp_aac_caps->sampleRate, peer_info_cie.sampleRate); + "cannot match sample frequency: source caps = 0x{:x} peer info = " + "0x{:x}", + p_a2dp_aac_caps->sampleRate, peer_info_cie.sampleRate); goto fail; } @@ -1217,40 +1204,38 @@ bool A2dpCodecConfigAacBase::setCodecConfig(const uint8_t* p_peer_codec_info, // Select the bits per sample if there is no user preference do { // Compute the selectable capability - codec_selectable_capability_.bits_per_sample = - p_a2dp_aac_caps->bits_per_sample; + codec_selectable_capability_.bits_per_sample = p_a2dp_aac_caps->bits_per_sample; - if (codec_config_.bits_per_sample != BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE) + if (codec_config_.bits_per_sample != BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE) { break; + } // Compute the common capability codec_capability_.bits_per_sample = bits_per_sample; // No user preference - the the codec audio config - if (select_audio_bits_per_sample(&codec_audio_config_, - p_a2dp_aac_caps->bits_per_sample, + if (select_audio_bits_per_sample(&codec_audio_config_, p_a2dp_aac_caps->bits_per_sample, &result_config_cie, &codec_config_)) { break; } // No user preference - try the default config - if (select_best_bits_per_sample(a2dp_aac_default_config.bits_per_sample, - &result_config_cie, &codec_config_)) { + if (select_best_bits_per_sample(a2dp_aac_default_config.bits_per_sample, &result_config_cie, + &codec_config_)) { break; } // No user preference - use the best match - if (select_best_bits_per_sample(p_a2dp_aac_caps->bits_per_sample, - &result_config_cie, &codec_config_)) { + if (select_best_bits_per_sample(p_a2dp_aac_caps->bits_per_sample, &result_config_cie, + &codec_config_)) { break; } } while (false); if (codec_config_.bits_per_sample == BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE) { log::error( - "cannot match bits per sample: default = 0x{:x} user preference = " - "0x{:x}", - a2dp_aac_default_config.bits_per_sample, - codec_user_config_.bits_per_sample); + "cannot match bits per sample: default = 0x{:x} user preference = " + "0x{:x}", + a2dp_aac_default_config.bits_per_sample, codec_user_config_.bits_per_sample); goto fail; } @@ -1284,46 +1269,44 @@ bool A2dpCodecConfigAacBase::setCodecConfig(const uint8_t* p_peer_codec_info, do { // Compute the selectable capability if (channelMode & A2DP_AAC_CHANNEL_MODE_MONO) { - codec_selectable_capability_.channel_mode |= - BTAV_A2DP_CODEC_CHANNEL_MODE_MONO; + codec_selectable_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_MONO; } if (channelMode & A2DP_AAC_CHANNEL_MODE_STEREO) { - codec_selectable_capability_.channel_mode |= - BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; + codec_selectable_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; } - if (codec_config_.channel_mode != BTAV_A2DP_CODEC_CHANNEL_MODE_NONE) break; + if (codec_config_.channel_mode != BTAV_A2DP_CODEC_CHANNEL_MODE_NONE) { + break; + } // Compute the common capability - if (channelMode & A2DP_AAC_CHANNEL_MODE_MONO) + if (channelMode & A2DP_AAC_CHANNEL_MODE_MONO) { codec_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_MONO; + } if (channelMode & A2DP_AAC_CHANNEL_MODE_STEREO) { codec_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; } // No user preference - try the codec audio config - if (select_audio_channel_mode(&codec_audio_config_, channelMode, - &result_config_cie, &codec_config_)) { + if (select_audio_channel_mode(&codec_audio_config_, channelMode, &result_config_cie, + &codec_config_)) { break; } // No user preference - try the default config - if (select_best_channel_mode( - a2dp_aac_default_config.channelMode & peer_info_cie.channelMode, - &result_config_cie, &codec_config_)) { + if (select_best_channel_mode(a2dp_aac_default_config.channelMode & peer_info_cie.channelMode, + &result_config_cie, &codec_config_)) { break; } // No user preference - use the best match - if (select_best_channel_mode(channelMode, &result_config_cie, - &codec_config_)) { + if (select_best_channel_mode(channelMode, &result_config_cie, &codec_config_)) { break; } } while (false); if (codec_config_.channel_mode == BTAV_A2DP_CODEC_CHANNEL_MODE_NONE) { - log::error( - "cannot match channel mode: source caps = 0x{:x} peer info = 0x{:x}", - p_a2dp_aac_caps->channelMode, peer_info_cie.channelMode); + log::error("cannot match channel mode: source caps = 0x{:x} peer info = 0x{:x}", + p_a2dp_aac_caps->channelMode, peer_info_cie.channelMode); goto fail; } @@ -1331,14 +1314,12 @@ bool A2dpCodecConfigAacBase::setCodecConfig(const uint8_t* p_peer_codec_info, // Copy the codec-specific fields if they are not zero // if (codec_user_config_.codec_specific_1 != 0) { - if (result_config_cie.variableBitRateSupport != - A2DP_AAC_VARIABLE_BIT_RATE_DISABLED) { + if (result_config_cie.variableBitRateSupport != A2DP_AAC_VARIABLE_BIT_RATE_DISABLED) { auto user_bitrate_mode = codec_user_config_.codec_specific_1; switch (static_cast(user_bitrate_mode)) { case AacEncoderBitrateMode::AACENC_BR_MODE_VBR_C: // VBR is supported, and is disabled by the user preference - result_config_cie.variableBitRateSupport = - A2DP_AAC_VARIABLE_BIT_RATE_DISABLED; + result_config_cie.variableBitRateSupport = A2DP_AAC_VARIABLE_BIT_RATE_DISABLED; [[fallthrough]]; case AacEncoderBitrateMode::AACENC_BR_MODE_VBR_1: [[fallthrough]]; @@ -1353,42 +1334,40 @@ bool A2dpCodecConfigAacBase::setCodecConfig(const uint8_t* p_peer_codec_info, break; default: codec_config_.codec_specific_1 = - static_cast(AacEncoderBitrateMode::AACENC_BR_MODE_VBR_5); + static_cast(AacEncoderBitrateMode::AACENC_BR_MODE_VBR_5); } } else { // It is no needed to check the user preference when Variable Bitrate // unsupported by one of source or sink codec_config_.codec_specific_1 = - static_cast(AacEncoderBitrateMode::AACENC_BR_MODE_CBR); + static_cast(AacEncoderBitrateMode::AACENC_BR_MODE_CBR); } } - if (codec_user_config_.codec_specific_2 != 0) + if (codec_user_config_.codec_specific_2 != 0) { codec_config_.codec_specific_2 = codec_user_config_.codec_specific_2; - if (codec_user_config_.codec_specific_3 != 0) + } + if (codec_user_config_.codec_specific_3 != 0) { codec_config_.codec_specific_3 = codec_user_config_.codec_specific_3; - if (codec_user_config_.codec_specific_4 != 0) + } + if (codec_user_config_.codec_specific_4 != 0) { codec_config_.codec_specific_4 = codec_user_config_.codec_specific_4; + } - if (A2DP_BuildInfoAac(AVDT_MEDIA_TYPE_AUDIO, &result_config_cie, - p_result_codec_config) != A2DP_SUCCESS) { + if (A2DP_BuildInfoAac(AVDT_MEDIA_TYPE_AUDIO, &result_config_cie, p_result_codec_config) != + A2DP_SUCCESS) { goto fail; } // Create a local copy of the peer codec capability/config, and the // result codec config. if (is_capability) { - status = A2DP_BuildInfoAac(AVDT_MEDIA_TYPE_AUDIO, &peer_info_cie, - ota_codec_peer_capability_); + status = A2DP_BuildInfoAac(AVDT_MEDIA_TYPE_AUDIO, &peer_info_cie, ota_codec_peer_capability_); } else { - status = A2DP_BuildInfoAac(AVDT_MEDIA_TYPE_AUDIO, &peer_info_cie, - ota_codec_peer_config_); - } - log::assert_that(status == A2DP_SUCCESS, - "assert failed: status == A2DP_SUCCESS"); - status = A2DP_BuildInfoAac(AVDT_MEDIA_TYPE_AUDIO, &result_config_cie, - ota_codec_config_); - log::assert_that(status == A2DP_SUCCESS, - "assert failed: status == A2DP_SUCCESS"); + status = A2DP_BuildInfoAac(AVDT_MEDIA_TYPE_AUDIO, &peer_info_cie, ota_codec_peer_config_); + } + log::assert_that(status == A2DP_SUCCESS, "assert failed: status == A2DP_SUCCESS"); + status = A2DP_BuildInfoAac(AVDT_MEDIA_TYPE_AUDIO, &result_config_cie, ota_codec_config_); + log::assert_that(status == A2DP_SUCCESS, "assert failed: status == A2DP_SUCCESS"); return true; fail: @@ -1401,30 +1380,25 @@ fail: memcpy(ota_codec_config_, saved_ota_codec_config, sizeof(ota_codec_config_)); memcpy(ota_codec_peer_capability_, saved_ota_codec_peer_capability, sizeof(ota_codec_peer_capability_)); - memcpy(ota_codec_peer_config_, saved_ota_codec_peer_config, - sizeof(ota_codec_peer_config_)); + memcpy(ota_codec_peer_config_, saved_ota_codec_peer_config, sizeof(ota_codec_peer_config_)); return false; } -bool A2dpCodecConfigAacBase::setPeerCodecCapabilities( - const uint8_t* p_peer_codec_capabilities) { +bool A2dpCodecConfigAacBase::setPeerCodecCapabilities(const uint8_t* p_peer_codec_capabilities) { std::lock_guard lock(codec_mutex_); tA2DP_AAC_CIE peer_info_cie; uint8_t channelMode; uint16_t sampleRate; uint8_t variableBitRateSupport; - const tA2DP_AAC_CIE* p_a2dp_aac_caps = - (is_source_) ? &a2dp_aac_source_caps : &a2dp_aac_sink_caps; + const tA2DP_AAC_CIE* p_a2dp_aac_caps = (is_source_) ? &a2dp_aac_source_caps : &a2dp_aac_sink_caps; // Save the internal state - btav_a2dp_codec_config_t saved_codec_selectable_capability = - codec_selectable_capability_; + btav_a2dp_codec_config_t saved_codec_selectable_capability = codec_selectable_capability_; uint8_t saved_ota_codec_peer_capability[AVDT_CODEC_SIZE]; memcpy(saved_ota_codec_peer_capability, ota_codec_peer_capability_, sizeof(ota_codec_peer_capability_)); - tA2DP_STATUS status = - A2DP_ParseInfoAac(&peer_info_cie, p_peer_codec_capabilities, true); + tA2DP_STATUS status = A2DP_ParseInfoAac(&peer_info_cie, p_peer_codec_capabilities, true); if (status != A2DP_SUCCESS) { log::error("can't parse peer's capabilities: error = {}", status); goto fail; @@ -1433,52 +1407,43 @@ bool A2dpCodecConfigAacBase::setPeerCodecCapabilities( // Compute the selectable capability - sample rate sampleRate = p_a2dp_aac_caps->sampleRate & peer_info_cie.sampleRate; if (sampleRate & A2DP_AAC_SAMPLING_FREQ_44100) { - codec_selectable_capability_.sample_rate |= - BTAV_A2DP_CODEC_SAMPLE_RATE_44100; + codec_selectable_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_44100; } if (sampleRate & A2DP_AAC_SAMPLING_FREQ_48000) { - codec_selectable_capability_.sample_rate |= - BTAV_A2DP_CODEC_SAMPLE_RATE_48000; + codec_selectable_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_48000; } if (sampleRate & A2DP_AAC_SAMPLING_FREQ_88200) { - codec_selectable_capability_.sample_rate |= - BTAV_A2DP_CODEC_SAMPLE_RATE_88200; + codec_selectable_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_88200; } if (sampleRate & A2DP_AAC_SAMPLING_FREQ_96000) { - codec_selectable_capability_.sample_rate |= - BTAV_A2DP_CODEC_SAMPLE_RATE_96000; + codec_selectable_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_96000; } // Compute the selectable capability - bits per sample - codec_selectable_capability_.bits_per_sample = - p_a2dp_aac_caps->bits_per_sample; + codec_selectable_capability_.bits_per_sample = p_a2dp_aac_caps->bits_per_sample; // Compute the selectable capability - channel mode channelMode = p_a2dp_aac_caps->channelMode & peer_info_cie.channelMode; if (channelMode & A2DP_AAC_CHANNEL_MODE_MONO) { - codec_selectable_capability_.channel_mode |= - BTAV_A2DP_CODEC_CHANNEL_MODE_MONO; + codec_selectable_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_MONO; } if (channelMode & A2DP_AAC_CHANNEL_MODE_STEREO) { - codec_selectable_capability_.channel_mode |= - BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; + codec_selectable_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; } // Compute the selectable capability - variable bitrate mode - variableBitRateSupport = p_a2dp_aac_caps->variableBitRateSupport & - peer_info_cie.variableBitRateSupport; + variableBitRateSupport = + p_a2dp_aac_caps->variableBitRateSupport & peer_info_cie.variableBitRateSupport; if (variableBitRateSupport != A2DP_AAC_VARIABLE_BIT_RATE_DISABLED) { codec_selectable_capability_.codec_specific_1 = - static_cast(AacEncoderBitrateMode::AACENC_BR_MODE_VBR_5); + static_cast(AacEncoderBitrateMode::AACENC_BR_MODE_VBR_5); } else { codec_selectable_capability_.codec_specific_1 = - static_cast(AacEncoderBitrateMode::AACENC_BR_MODE_CBR); + static_cast(AacEncoderBitrateMode::AACENC_BR_MODE_CBR); } - status = A2DP_BuildInfoAac(AVDT_MEDIA_TYPE_AUDIO, &peer_info_cie, - ota_codec_peer_capability_); - log::assert_that(status == A2DP_SUCCESS, - "assert failed: status == A2DP_SUCCESS"); + status = A2DP_BuildInfoAac(AVDT_MEDIA_TYPE_AUDIO, &peer_info_cie, ota_codec_peer_capability_); + log::assert_that(status == A2DP_SUCCESS, "assert failed: status == A2DP_SUCCESS"); return true; fail: @@ -1489,16 +1454,16 @@ fail: return false; } -A2dpCodecConfigAacSink::A2dpCodecConfigAacSink( - btav_a2dp_codec_priority_t codec_priority) - : A2dpCodecConfigAacBase(BTAV_A2DP_CODEC_INDEX_SINK_AAC, - A2DP_CodecIndexStrAacSink(), codec_priority, - false) {} +A2dpCodecConfigAacSink::A2dpCodecConfigAacSink(btav_a2dp_codec_priority_t codec_priority) + : A2dpCodecConfigAacBase(BTAV_A2DP_CODEC_INDEX_SINK_AAC, A2DP_CodecIndexStrAacSink(), + codec_priority, false) {} A2dpCodecConfigAacSink::~A2dpCodecConfigAacSink() {} bool A2dpCodecConfigAacSink::init() { - if (!isValid()) return false; + if (!isValid()) { + return false; + } // Load the decoder if (!A2DP_LoadDecoderAac()) { diff --git a/system/stack/a2dp/a2dp_aac_decoder.cc b/system/stack/a2dp/a2dp_aac_decoder.cc index 6221ed0eead..e1fb4f49292 100644 --- a/system/stack/a2dp/a2dp_aac_decoder.cc +++ b/system/stack/a2dp/a2dp_aac_decoder.cc @@ -48,18 +48,18 @@ void A2DP_UnloadDecoderAac(void) { a2dp_aac_decoder_cleanup(); } bool a2dp_aac_decoder_init(decoded_data_callback_t decode_callback) { a2dp_aac_decoder_cleanup(); - a2dp_aac_decoder_cb.aac_handle = - aacDecoder_Open(TT_MP4_LATM_MCP1, 1 /* nrOfLayers */); + a2dp_aac_decoder_cb.aac_handle = aacDecoder_Open(TT_MP4_LATM_MCP1, 1 /* nrOfLayers */); a2dp_aac_decoder_cb.has_aac_handle = true; a2dp_aac_decoder_cb.decode_buf = static_cast( - osi_malloc(sizeof(a2dp_aac_decoder_cb.decode_buf[0]) * DECODE_BUF_LEN)); + osi_malloc(sizeof(a2dp_aac_decoder_cb.decode_buf[0]) * DECODE_BUF_LEN)); a2dp_aac_decoder_cb.decode_callback = decode_callback; return true; } void a2dp_aac_decoder_cleanup(void) { - if (a2dp_aac_decoder_cb.has_aac_handle) + if (a2dp_aac_decoder_cb.has_aac_handle) { aacDecoder_Close(a2dp_aac_decoder_cb.aac_handle); + } osi_free(a2dp_aac_decoder_cb.decode_buf); memset(&a2dp_aac_decoder_cb, 0, sizeof(a2dp_aac_decoder_cb)); } @@ -69,38 +69,34 @@ bool a2dp_aac_decoder_decode_packet(BT_HDR* p_buf) { UINT bufferSize = p_buf->len; UINT bytesValid = p_buf->len; while (bytesValid > 0) { - AAC_DECODER_ERROR err = aacDecoder_Fill(a2dp_aac_decoder_cb.aac_handle, - &pBuffer, &bufferSize, &bytesValid); + AAC_DECODER_ERROR err = + aacDecoder_Fill(a2dp_aac_decoder_cb.aac_handle, &pBuffer, &bufferSize, &bytesValid); if (err != AAC_DEC_OK) { log::error("aacDecoder_Fill failed: 0x{:x}", static_cast(err)); return false; } while (true) { - err = aacDecoder_DecodeFrame(a2dp_aac_decoder_cb.aac_handle, - a2dp_aac_decoder_cb.decode_buf, + err = aacDecoder_DecodeFrame(a2dp_aac_decoder_cb.aac_handle, a2dp_aac_decoder_cb.decode_buf, DECODE_BUF_LEN, 0 /* flags */); if (err == AAC_DEC_NOT_ENOUGH_BITS) { break; } if (err != AAC_DEC_OK) { - log::error("aacDecoder_DecodeFrame failed: 0x{:x}", - static_cast(err)); + log::error("aacDecoder_DecodeFrame failed: 0x{:x}", static_cast(err)); break; } - CStreamInfo* info = - aacDecoder_GetStreamInfo(a2dp_aac_decoder_cb.aac_handle); + CStreamInfo* info = aacDecoder_GetStreamInfo(a2dp_aac_decoder_cb.aac_handle); if (!info || info->sampleRate <= 0) { log::error("Invalid stream info"); break; } - size_t frame_len = info->frameSize * info->numChannels * - sizeof(a2dp_aac_decoder_cb.decode_buf[0]); + size_t frame_len = + info->frameSize * info->numChannels * sizeof(a2dp_aac_decoder_cb.decode_buf[0]); a2dp_aac_decoder_cb.decode_callback( - reinterpret_cast(a2dp_aac_decoder_cb.decode_buf), - frame_len); + reinterpret_cast(a2dp_aac_decoder_cb.decode_buf), frame_len); } } diff --git a/system/stack/a2dp/a2dp_aac_decoder_linux.cc b/system/stack/a2dp/a2dp_aac_decoder_linux.cc index e0df52e796d..1c29daf7f40 100644 --- a/system/stack/a2dp/a2dp_aac_decoder_linux.cc +++ b/system/stack/a2dp/a2dp_aac_decoder_linux.cc @@ -25,9 +25,7 @@ bool A2DP_LoadDecoderAac(void) { return false; } void A2DP_UnloadDecoderAac(void) {} -bool a2dp_aac_decoder_init(decoded_data_callback_t decode_callback) { - return false; -} +bool a2dp_aac_decoder_init(decoded_data_callback_t decode_callback) { return false; } void a2dp_aac_decoder_cleanup(void) {} diff --git a/system/stack/a2dp/a2dp_aac_encoder.cc b/system/stack/a2dp/a2dp_aac_encoder.cc index 0f019b5ca2b..d322d7f8cf1 100644 --- a/system/stack/a2dp/a2dp_aac_encoder.cc +++ b/system/stack/a2dp/a2dp_aac_encoder.cc @@ -81,7 +81,7 @@ typedef struct { bool use_SCMS_T; tA2DP_ENCODER_INIT_PEER_PARAMS peer_params; - uint32_t timestamp; // Timestamp for the A2DP frames + uint32_t timestamp; // Timestamp for the A2DP frames HANDLE_AACENCODER aac_handle; bool has_aac_handle; // True if aac_handle is valid @@ -97,17 +97,13 @@ static tA2DP_AAC_ENCODER_CB a2dp_aac_encoder_cb; static uint32_t a2dp_aac_encoder_interval_ms = A2DP_AAC_ENCODER_INTERVAL_MS; -static void a2dp_aac_encoder_update(A2dpCodecConfig* a2dp_codec_config, - bool* p_restart_input, - bool* p_restart_output, - bool* p_config_updated); -static void a2dp_aac_get_num_frame_iteration(uint8_t* num_of_iterations, - uint8_t* num_of_frames, +static void a2dp_aac_encoder_update(A2dpCodecConfig* a2dp_codec_config, bool* p_restart_input, + bool* p_restart_output, bool* p_config_updated); +static void a2dp_aac_get_num_frame_iteration(uint8_t* num_of_iterations, uint8_t* num_of_frames, uint64_t timestamp_us); static void a2dp_aac_encode_frames(uint8_t nb_frame); static bool a2dp_aac_read_feeding(uint8_t* read_buffer, uint32_t* bytes_read); -static uint16_t adjust_effective_mtu( - const tA2DP_ENCODER_INIT_PEER_PARAMS& peer_params); +static uint16_t adjust_effective_mtu(const tA2DP_ENCODER_INIT_PEER_PARAMS& peer_params); bool A2DP_LoadEncoderAac(void) { // Nothing to do - the library is statically linked @@ -116,8 +112,9 @@ bool A2DP_LoadEncoderAac(void) { void A2DP_UnloadEncoderAac(void) { // Nothing to do - the library is statically linked - if (a2dp_aac_encoder_cb.has_aac_handle) + if (a2dp_aac_encoder_cb.has_aac_handle) { aacEncClose(&a2dp_aac_encoder_cb.aac_handle); + } memset(&a2dp_aac_encoder_cb, 0, sizeof(a2dp_aac_encoder_cb)); } @@ -125,12 +122,12 @@ void a2dp_aac_encoder_init(const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params, A2dpCodecConfig* a2dp_codec_config, a2dp_source_read_callback_t read_callback, a2dp_source_enqueue_callback_t enqueue_callback) { - if (a2dp_aac_encoder_cb.has_aac_handle) + if (a2dp_aac_encoder_cb.has_aac_handle) { aacEncClose(&a2dp_aac_encoder_cb.aac_handle); + } memset(&a2dp_aac_encoder_cb, 0, sizeof(a2dp_aac_encoder_cb)); - a2dp_aac_encoder_cb.stats.session_start_us = - bluetooth::common::time_get_os_boottime_us(); + a2dp_aac_encoder_cb.stats.session_start_us = bluetooth::common::time_get_os_boottime_us(); a2dp_aac_encoder_cb.read_callback = read_callback; a2dp_aac_encoder_cb.enqueue_callback = enqueue_callback; @@ -144,18 +141,14 @@ void a2dp_aac_encoder_init(const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params, bool restart_input = false; bool restart_output = false; bool config_updated = false; - a2dp_aac_encoder_update(a2dp_codec_config, &restart_input, &restart_output, - &config_updated); + a2dp_aac_encoder_update(a2dp_codec_config, &restart_input, &restart_output, &config_updated); } // Update the A2DP AAC encoder. // |a2dp_codec_config| is the A2DP codec to use for the update. -static void a2dp_aac_encoder_update(A2dpCodecConfig* a2dp_codec_config, - bool* p_restart_input, - bool* p_restart_output, - bool* p_config_updated) { - tA2DP_AAC_ENCODER_PARAMS* p_encoder_params = - &a2dp_aac_encoder_cb.aac_encoder_params; +static void a2dp_aac_encoder_update(A2dpCodecConfig* a2dp_codec_config, bool* p_restart_input, + bool* p_restart_output, bool* p_config_updated) { + tA2DP_AAC_ENCODER_PARAMS* p_encoder_params = &a2dp_aac_encoder_cb.aac_encoder_params; uint8_t codec_info[AVDT_CODEC_SIZE]; AACENC_ERROR aac_error; int aac_param_value, aac_sampling_freq, aac_peak_bit_rate; @@ -165,8 +158,8 @@ static void a2dp_aac_encoder_update(A2dpCodecConfig* a2dp_codec_config, *p_config_updated = false; if (!a2dp_aac_encoder_cb.has_aac_handle) { - AACENC_ERROR aac_error = aacEncOpen(&a2dp_aac_encoder_cb.aac_handle, 0, - 2 /* max 2 channels: stereo */); + AACENC_ERROR aac_error = + aacEncOpen(&a2dp_aac_encoder_cb.aac_handle, 0, 2 /* max 2 channels: stereo */); if (aac_error != AACENC_OK) { log::error("Cannot open AAC encoder handle: AAC error 0x{:x}", aac_error); return; // TODO: Return an error? @@ -184,23 +177,18 @@ static void a2dp_aac_encoder_update(A2dpCodecConfig* a2dp_codec_config, // The feeding parameters tA2DP_FEEDING_PARAMS* p_feeding_params = &a2dp_aac_encoder_cb.feeding_params; p_feeding_params->sample_rate = A2DP_GetTrackSampleRateAac(p_codec_info); - p_feeding_params->bits_per_sample = - a2dp_codec_config->getAudioBitsPerSample(); + p_feeding_params->bits_per_sample = a2dp_codec_config->getAudioBitsPerSample(); p_feeding_params->channel_count = A2DP_GetTrackChannelCountAac(p_codec_info); - log::info("sample_rate={} bits_per_sample={} channel_count={}", - p_feeding_params->sample_rate, p_feeding_params->bits_per_sample, - p_feeding_params->channel_count); + log::info("sample_rate={} bits_per_sample={} channel_count={}", p_feeding_params->sample_rate, + p_feeding_params->bits_per_sample, p_feeding_params->channel_count); // The codec parameters - p_encoder_params->sample_rate = - a2dp_aac_encoder_cb.feeding_params.sample_rate; + p_encoder_params->sample_rate = a2dp_aac_encoder_cb.feeding_params.sample_rate; p_encoder_params->channel_mode = A2DP_GetChannelModeCodeAac(p_codec_info); - const tA2DP_ENCODER_INIT_PEER_PARAMS& peer_params = - a2dp_aac_encoder_cb.peer_params; + const tA2DP_ENCODER_INIT_PEER_PARAMS& peer_params = a2dp_aac_encoder_cb.peer_params; a2dp_aac_encoder_cb.TxAaMtuSize = adjust_effective_mtu(peer_params); - log::info("MTU={}, peer_mtu={}", a2dp_aac_encoder_cb.TxAaMtuSize, - peer_params.peer_mtu); + log::info("MTU={}, peer_mtu={}", a2dp_aac_encoder_cb.TxAaMtuSize, peer_params.peer_mtu); log::info("sample_rate: {} channel_mode: {}", p_encoder_params->sample_rate, p_encoder_params->channel_mode); @@ -225,49 +213,45 @@ static void a2dp_aac_encoder_update(A2dpCodecConfig* a2dp_codec_config, aac_param_value = AOT_AAC_SCAL; break; default: - log::error("Cannot set AAC parameter AACENC_AOT: invalid object type {}", - object_type); + log::error("Cannot set AAC parameter AACENC_AOT: invalid object type {}", object_type); return; // TODO: Return an error? } - aac_error = aacEncoder_SetParam(a2dp_aac_encoder_cb.aac_handle, AACENC_AOT, - aac_param_value); + aac_error = aacEncoder_SetParam(a2dp_aac_encoder_cb.aac_handle, AACENC_AOT, aac_param_value); if (aac_error != AACENC_OK) { - log::error("Cannot set AAC parameter AACENC_AOT to {}: AAC error 0x{:x}", - aac_param_value, aac_error); + log::error("Cannot set AAC parameter AACENC_AOT to {}: AAC error 0x{:x}", aac_param_value, + aac_error); return; // TODO: Return an error? } // Set the encoder's parameters: audioMuxVersion aac_param_value = 2; // audioMuxVersion = "2" - aac_error = aacEncoder_SetParam(a2dp_aac_encoder_cb.aac_handle, - AACENC_AUDIOMUXVER, aac_param_value); + aac_error = + aacEncoder_SetParam(a2dp_aac_encoder_cb.aac_handle, AACENC_AUDIOMUXVER, aac_param_value); if (aac_error != AACENC_OK) { - log::error( - "Cannot set AAC parameter AACENC_AUDIOMUXVER to {}: AAC error 0x{:x}", - aac_param_value, aac_error); + log::error("Cannot set AAC parameter AACENC_AUDIOMUXVER to {}: AAC error 0x{:x}", + aac_param_value, aac_error); return; // TODO: Return an error? } // Set the encoder's parameters: Signaling mode of the extension AOT aac_param_value = 1; // Signaling mode of the extension AOT = 1 - aac_error = aacEncoder_SetParam(a2dp_aac_encoder_cb.aac_handle, - AACENC_SIGNALING_MODE, aac_param_value); + aac_error = aacEncoder_SetParam(a2dp_aac_encoder_cb.aac_handle, AACENC_SIGNALING_MODE, + aac_param_value); if (aac_error != AACENC_OK) { log::error( - "Cannot set AAC parameter AACENC_SIGNALING_MODE to {}: AAC error " - "0x{:x}", - aac_param_value, aac_error); + "Cannot set AAC parameter AACENC_SIGNALING_MODE to {}: AAC error " + "0x{:x}", + aac_param_value, aac_error); return; // TODO: Return an error? } // Set the encoder's parameters: Sample Rate - MANDATORY aac_param_value = A2DP_GetTrackSampleRateAac(p_codec_info); - aac_error = aacEncoder_SetParam(a2dp_aac_encoder_cb.aac_handle, - AACENC_SAMPLERATE, aac_param_value); + aac_error = + aacEncoder_SetParam(a2dp_aac_encoder_cb.aac_handle, AACENC_SAMPLERATE, aac_param_value); if (aac_error != AACENC_OK) { - log::error( - "Cannot set AAC parameter AACENC_SAMPLERATE to {}: AAC error 0x{:x}", - aac_param_value, aac_error); + log::error("Cannot set AAC parameter AACENC_SAMPLERATE to {}: AAC error 0x{:x}", + aac_param_value, aac_error); return; // TODO: Return an error? } aac_sampling_freq = aac_param_value; // Save for extra usage below @@ -275,33 +259,27 @@ static void a2dp_aac_encoder_update(A2dpCodecConfig* a2dp_codec_config, // Set the encoder's parameters: Bit Rate - MANDATORY aac_param_value = A2DP_GetBitRateAac(p_codec_info); // Calculate the bit rate from MTU and sampling frequency - aac_peak_bit_rate = - A2DP_ComputeMaxBitRateAac(p_codec_info, a2dp_aac_encoder_cb.TxAaMtuSize); + aac_peak_bit_rate = A2DP_ComputeMaxBitRateAac(p_codec_info, a2dp_aac_encoder_cb.TxAaMtuSize); aac_param_value = std::min(aac_param_value, aac_peak_bit_rate); - log::info("MTU = {} Sampling Frequency = {} Bit Rate = {}", - a2dp_aac_encoder_cb.TxAaMtuSize, aac_sampling_freq, - aac_param_value); + log::info("MTU = {} Sampling Frequency = {} Bit Rate = {}", a2dp_aac_encoder_cb.TxAaMtuSize, + aac_sampling_freq, aac_param_value); if (aac_param_value == -1) { - log::error( - "Cannot set AAC parameter AACENC_BITRATE: invalid codec bit rate"); + log::error("Cannot set AAC parameter AACENC_BITRATE: invalid codec bit rate"); return; // TODO: Return an error? } - aac_error = aacEncoder_SetParam(a2dp_aac_encoder_cb.aac_handle, - AACENC_BITRATE, aac_param_value); + aac_error = aacEncoder_SetParam(a2dp_aac_encoder_cb.aac_handle, AACENC_BITRATE, aac_param_value); if (aac_error != AACENC_OK) { - log::error( - "Cannot set AAC parameter AACENC_BITRATE to {}: AAC error 0x{:x}", - aac_param_value, aac_error); + log::error("Cannot set AAC parameter AACENC_BITRATE to {}: AAC error 0x{:x}", aac_param_value, + aac_error); return; // TODO: Return an error? } // Set the encoder's parameters: PEAK Bit Rate - aac_error = aacEncoder_SetParam(a2dp_aac_encoder_cb.aac_handle, - AACENC_PEAK_BITRATE, aac_peak_bit_rate); + aac_error = aacEncoder_SetParam(a2dp_aac_encoder_cb.aac_handle, AACENC_PEAK_BITRATE, + aac_peak_bit_rate); if (aac_error != AACENC_OK) { - log::error( - "Cannot set AAC parameter AACENC_PEAK_BITRATE to {}: AAC error 0x{:x}", - aac_peak_bit_rate, aac_error); + log::error("Cannot set AAC parameter AACENC_PEAK_BITRATE to {}: AAC error 0x{:x}", + aac_peak_bit_rate, aac_error); return; // TODO: Return an error? } @@ -311,34 +289,30 @@ static void a2dp_aac_encoder_update(A2dpCodecConfig* a2dp_codec_config, } else { aac_param_value = MODE_2; // Stereo } - aac_error = aacEncoder_SetParam(a2dp_aac_encoder_cb.aac_handle, - AACENC_CHANNELMODE, aac_param_value); + aac_error = + aacEncoder_SetParam(a2dp_aac_encoder_cb.aac_handle, AACENC_CHANNELMODE, aac_param_value); if (aac_error != AACENC_OK) { - log::error( - "Cannot set AAC parameter AACENC_CHANNELMODE to {}: AAC error 0x{:x}", - aac_param_value, aac_error); + log::error("Cannot set AAC parameter AACENC_CHANNELMODE to {}: AAC error 0x{:x}", + aac_param_value, aac_error); return; // TODO: Return an error? } // Set the encoder's parameters: Transport Type aac_param_value = TT_MP4_LATM_MCP1; // muxConfigPresent = 1 - aac_error = aacEncoder_SetParam(a2dp_aac_encoder_cb.aac_handle, - AACENC_TRANSMUX, aac_param_value); + aac_error = aacEncoder_SetParam(a2dp_aac_encoder_cb.aac_handle, AACENC_TRANSMUX, aac_param_value); if (aac_error != AACENC_OK) { - log::error( - "Cannot set AAC parameter AACENC_TRANSMUX to {}: AAC error 0x{:x}", - aac_param_value, aac_error); + log::error("Cannot set AAC parameter AACENC_TRANSMUX to {}: AAC error 0x{:x}", aac_param_value, + aac_error); return; // TODO: Return an error? } // Set the encoder's parameters: Header Period aac_param_value = 1; - aac_error = aacEncoder_SetParam(a2dp_aac_encoder_cb.aac_handle, - AACENC_HEADER_PERIOD, aac_param_value); + aac_error = aacEncoder_SetParam(a2dp_aac_encoder_cb.aac_handle, AACENC_HEADER_PERIOD, + aac_param_value); if (aac_error != AACENC_OK) { - log::error( - "Cannot set AAC parameter AACENC_HEADER_PERIOD to {}: AAC error 0x{:x}", - aac_param_value, aac_error); + log::error("Cannot set AAC parameter AACENC_HEADER_PERIOD to {}: AAC error 0x{:x}", + aac_param_value, aac_error); return; // TODO: Return an error? } @@ -346,8 +320,8 @@ static void a2dp_aac_encoder_update(A2dpCodecConfig* a2dp_codec_config, aac_param_value = A2DP_GetVariableBitRateSupportAac(p_codec_info); if (aac_param_value == -1) { log::error( - "Cannot set AAC parameter AACENC_BITRATEMODE: invalid codec bit rate " - "mode"); + "Cannot set AAC parameter AACENC_BITRATEMODE: invalid codec bit rate " + "mode"); return; // TODO: Return an error? } else if (aac_param_value == A2DP_AAC_VARIABLE_BIT_RATE_ENABLED) { // VBR has 5 modes defined in external/aac/libAACenc/src/aacenc.h @@ -365,28 +339,23 @@ static void a2dp_aac_encoder_update(A2dpCodecConfig* a2dp_codec_config, case AacEncoderBitrateMode::AACENC_BR_MODE_VBR_5: break; default: - bitrate_mode = - static_cast(AacEncoderBitrateMode::AACENC_BR_MODE_VBR_5); + bitrate_mode = static_cast(AacEncoderBitrateMode::AACENC_BR_MODE_VBR_5); } - aac_param_value = - static_cast(bitrate_mode) & ~A2DP_AAC_VARIABLE_BIT_RATE_MASK; + aac_param_value = static_cast(bitrate_mode) & ~A2DP_AAC_VARIABLE_BIT_RATE_MASK; } log::info("AACENC_BITRATEMODE: {}", aac_param_value); - aac_error = aacEncoder_SetParam(a2dp_aac_encoder_cb.aac_handle, - AACENC_BITRATEMODE, aac_param_value); + aac_error = + aacEncoder_SetParam(a2dp_aac_encoder_cb.aac_handle, AACENC_BITRATEMODE, aac_param_value); if (aac_error != AACENC_OK) { - log::error( - "Cannot set AAC parameter AACENC_BITRATEMODE to {}: AAC error 0x{:x}", - aac_param_value, aac_error); + log::error("Cannot set AAC parameter AACENC_BITRATEMODE to {}: AAC error 0x{:x}", + aac_param_value, aac_error); return; // TODO: Return an error? } // Mark the end of setting the encoder's parameters - aac_error = - aacEncEncode(a2dp_aac_encoder_cb.aac_handle, NULL, NULL, NULL, NULL); + aac_error = aacEncEncode(a2dp_aac_encoder_cb.aac_handle, NULL, NULL, NULL, NULL); if (aac_error != AACENC_OK) { - log::error("Cannot complete setting the AAC parameters: AAC error 0x{:x}", - aac_error); + log::error("Cannot complete setting the AAC parameters: AAC error 0x{:x}", aac_error); return; // TODO: Return an error? } @@ -394,26 +363,26 @@ static void a2dp_aac_encoder_update(A2dpCodecConfig* a2dp_codec_config, AACENC_InfoStruct aac_info; aac_error = aacEncInfo(a2dp_aac_encoder_cb.aac_handle, &aac_info); if (aac_error != AACENC_OK) { - log::error("Cannot retrieve the AAC encoder info: AAC error 0x{:x}", - aac_error); + log::error("Cannot retrieve the AAC encoder info: AAC error 0x{:x}", aac_error); return; // TODO: Return an error? } p_encoder_params->frame_length = aac_info.frameLength; p_encoder_params->input_channels_n = aac_info.inputChannels; p_encoder_params->max_encoded_buffer_bytes = aac_info.maxOutBufBytes; log::info( - "AAC frame_length = {} input_channels_n = {} max_encoded_buffer_bytes = " - "{}", - p_encoder_params->frame_length, p_encoder_params->input_channels_n, - p_encoder_params->max_encoded_buffer_bytes); + "AAC frame_length = {} input_channels_n = {} max_encoded_buffer_bytes = " + "{}", + p_encoder_params->frame_length, p_encoder_params->input_channels_n, + p_encoder_params->max_encoded_buffer_bytes); // After encoder params ready, reset the feeding state and its interval. a2dp_aac_feeding_reset(); } void a2dp_aac_encoder_cleanup(void) { - if (a2dp_aac_encoder_cb.has_aac_handle) + if (a2dp_aac_encoder_cb.has_aac_handle) { aacEncClose(&a2dp_aac_encoder_cb.aac_handle); + } memset(&a2dp_aac_encoder_cb, 0, sizeof(a2dp_aac_encoder_cb)); } @@ -431,46 +400,39 @@ void a2dp_aac_feeding_reset(void) { // * feeding_params.channel_count * (T_interval_ms / 1000); // Here we use the nearest integer not greater than the value. a2dp_aac_encoder_interval_ms = frame_length * 1000 / sample_rate; - if (a2dp_aac_encoder_interval_ms < A2DP_AAC_ENCODER_INTERVAL_MS) + if (a2dp_aac_encoder_interval_ms < A2DP_AAC_ENCODER_INTERVAL_MS) { a2dp_aac_encoder_interval_ms = A2DP_AAC_ENCODER_INTERVAL_MS; + } } /* By default, just clear the entire state */ - memset(&a2dp_aac_encoder_cb.aac_feeding_state, 0, - sizeof(a2dp_aac_encoder_cb.aac_feeding_state)); + memset(&a2dp_aac_encoder_cb.aac_feeding_state, 0, sizeof(a2dp_aac_encoder_cb.aac_feeding_state)); a2dp_aac_encoder_cb.aac_feeding_state.bytes_per_tick = - (a2dp_aac_encoder_cb.feeding_params.sample_rate * - a2dp_aac_encoder_cb.feeding_params.bits_per_sample / 8 * - a2dp_aac_encoder_cb.feeding_params.channel_count * - a2dp_aac_encoder_interval_ms) / - 1000; - - log::info("PCM bytes {} per tick {} ms", - a2dp_aac_encoder_cb.aac_feeding_state.bytes_per_tick, + (a2dp_aac_encoder_cb.feeding_params.sample_rate * + a2dp_aac_encoder_cb.feeding_params.bits_per_sample / 8 * + a2dp_aac_encoder_cb.feeding_params.channel_count * a2dp_aac_encoder_interval_ms) / + 1000; + + log::info("PCM bytes {} per tick {} ms", a2dp_aac_encoder_cb.aac_feeding_state.bytes_per_tick, a2dp_aac_encoder_interval_ms); } -void a2dp_aac_feeding_flush(void) { - a2dp_aac_encoder_cb.aac_feeding_state.counter = 0.0f; -} +void a2dp_aac_feeding_flush(void) { a2dp_aac_encoder_cb.aac_feeding_state.counter = 0.0f; } -uint64_t a2dp_aac_get_encoder_interval_ms(void) { - return a2dp_aac_encoder_interval_ms; -} +uint64_t a2dp_aac_get_encoder_interval_ms(void) { return a2dp_aac_encoder_interval_ms; } -int a2dp_aac_get_effective_frame_size() { - return a2dp_aac_encoder_cb.TxAaMtuSize; -} +int a2dp_aac_get_effective_frame_size() { return a2dp_aac_encoder_cb.TxAaMtuSize; } void a2dp_aac_send_frames(uint64_t timestamp_us) { uint8_t nb_frame = 0; uint8_t nb_iterations = 0; a2dp_aac_get_num_frame_iteration(&nb_iterations, &nb_frame, timestamp_us); - log::verbose("Sending {} frames per iteration, {} iterations", nb_frame, - nb_iterations); - if (nb_frame == 0) return; + log::verbose("Sending {} frames per iteration, {} iterations", nb_frame, nb_iterations); + if (nb_frame == 0) { + return; + } for (uint8_t counter = 0; counter < nb_iterations; counter++) { // Transcode frame and enqueue @@ -481,29 +443,27 @@ void a2dp_aac_send_frames(uint64_t timestamp_us) { // Obtains the number of frames to send and number of iterations // to be used. |num_of_iterations| and |num_of_frames| parameters // are used as output param for returning the respective values. -static void a2dp_aac_get_num_frame_iteration(uint8_t* num_of_iterations, - uint8_t* num_of_frames, +static void a2dp_aac_get_num_frame_iteration(uint8_t* num_of_iterations, uint8_t* num_of_frames, uint64_t timestamp_us) { uint32_t result = 0; uint8_t nof = 0; uint8_t noi = 1; - uint32_t pcm_bytes_per_frame = - a2dp_aac_encoder_cb.aac_encoder_params.frame_length * - a2dp_aac_encoder_cb.feeding_params.channel_count * - a2dp_aac_encoder_cb.feeding_params.bits_per_sample / 8; + uint32_t pcm_bytes_per_frame = a2dp_aac_encoder_cb.aac_encoder_params.frame_length * + a2dp_aac_encoder_cb.feeding_params.channel_count * + a2dp_aac_encoder_cb.feeding_params.bits_per_sample / 8; log::verbose("pcm_bytes_per_frame {}", pcm_bytes_per_frame); uint32_t us_this_tick = a2dp_aac_encoder_interval_ms * 1000; uint64_t now_us = timestamp_us; - if (a2dp_aac_encoder_cb.aac_feeding_state.last_frame_us != 0) - us_this_tick = - (now_us - a2dp_aac_encoder_cb.aac_feeding_state.last_frame_us); + if (a2dp_aac_encoder_cb.aac_feeding_state.last_frame_us != 0) { + us_this_tick = (now_us - a2dp_aac_encoder_cb.aac_feeding_state.last_frame_us); + } a2dp_aac_encoder_cb.aac_feeding_state.last_frame_us = now_us; a2dp_aac_encoder_cb.aac_feeding_state.counter += - (float)a2dp_aac_encoder_cb.aac_feeding_state.bytes_per_tick * - us_this_tick / (a2dp_aac_encoder_interval_ms * 1000); + (float)a2dp_aac_encoder_cb.aac_feeding_state.bytes_per_tick * us_this_tick / + (a2dp_aac_encoder_interval_ms * 1000); result = a2dp_aac_encoder_cb.aac_feeding_state.counter / pcm_bytes_per_frame; a2dp_aac_encoder_cb.aac_feeding_state.counter -= result * pcm_bytes_per_frame; @@ -516,13 +476,11 @@ static void a2dp_aac_get_num_frame_iteration(uint8_t* num_of_iterations, } static void a2dp_aac_encode_frames(uint8_t nb_frame) { - tA2DP_AAC_ENCODER_PARAMS* p_encoder_params = - &a2dp_aac_encoder_cb.aac_encoder_params; + tA2DP_AAC_ENCODER_PARAMS* p_encoder_params = &a2dp_aac_encoder_cb.aac_encoder_params; tA2DP_FEEDING_PARAMS* p_feeding_params = &a2dp_aac_encoder_cb.feeding_params; uint8_t remain_nb_frame = nb_frame; uint8_t read_buffer[BT_DEFAULT_BUFFER_SIZE]; - int pcm_bytes_per_frame = p_encoder_params->frame_length * - p_feeding_params->channel_count * + int pcm_bytes_per_frame = p_encoder_params->frame_length * p_feeding_params->channel_count * p_feeding_params->bits_per_sample / 8; log::assert_that(pcm_bytes_per_frame <= static_cast(sizeof(read_buffer)), "assert failed: pcm_bytes_per_frame <= " @@ -552,19 +510,16 @@ static void a2dp_aac_encode_frames(uint8_t nb_frame) { out_buf_desc.bufferIdentifiers = out_buf_identifiers; out_buf_desc.bufSizes = out_buf_sizes; out_buf_desc.bufElSizes = out_buf_element_sizes; - log::assert_that( - p_encoder_params->max_encoded_buffer_bytes <= - static_cast(BT_DEFAULT_BUFFER_SIZE - sizeof(BT_HDR)), - "assert failed: p_encoder_params->max_encoded_buffer_bytes <= " - "static_cast(BT_DEFAULT_BUFFER_SIZE - sizeof(BT_HDR))"); + log::assert_that(p_encoder_params->max_encoded_buffer_bytes <= + static_cast(BT_DEFAULT_BUFFER_SIZE - sizeof(BT_HDR)), + "assert failed: p_encoder_params->max_encoded_buffer_bytes <= " + "static_cast(BT_DEFAULT_BUFFER_SIZE - sizeof(BT_HDR))"); AACENC_InArgs aac_in_args; - aac_in_args.numInSamples = - p_encoder_params->frame_length * p_feeding_params->channel_count; + aac_in_args.numInSamples = p_encoder_params->frame_length * p_feeding_params->channel_count; aac_in_args.numAncBytes = 0; - AACENC_OutArgs aac_out_args = { - .numOutBytes = 0, .numInSamples = 0, .numAncBytes = 0}; + AACENC_OutArgs aac_out_args = {.numOutBytes = 0, .numInSamples = 0, .numAncBytes = 0}; uint32_t count; uint32_t total_bytes_read = 0; @@ -593,9 +548,8 @@ static void a2dp_aac_encode_frames(uint8_t nb_frame) { } in_buf_vector[0] = read_buffer; out_buf_vector[0] = packet + count; - AACENC_ERROR aac_error = - aacEncEncode(a2dp_aac_encoder_cb.aac_handle, &in_buf_desc, - &out_buf_desc, &aac_in_args, &aac_out_args); + AACENC_ERROR aac_error = aacEncEncode(a2dp_aac_encoder_cb.aac_handle, &in_buf_desc, + &out_buf_desc, &aac_in_args, &aac_out_args); if (aac_error != AACENC_OK) { log::error("AAC encoding error: 0x{:x}", aac_error); a2dp_aac_encoder_cb.stats.media_read_total_dropped_packets++; @@ -609,10 +563,9 @@ static void a2dp_aac_encode_frames(uint8_t nb_frame) { p_buf->layer_specific++; // added a frame to the buffer } else { log::warn("underflow {}", nb_frame); - a2dp_aac_encoder_cb.aac_feeding_state.counter += - nb_frame * p_encoder_params->frame_length * - p_feeding_params->channel_count * - p_feeding_params->bits_per_sample / 8; + a2dp_aac_encoder_cb.aac_feeding_state.counter += nb_frame * p_encoder_params->frame_length * + p_feeding_params->channel_count * + p_feeding_params->bits_per_sample / 8; // no more pcm to read nb_frame = 0; @@ -634,15 +587,15 @@ static void a2dp_aac_encode_frames(uint8_t nb_frame) { // Timestamp will wrap over to 0 if stream continues on long enough // (>25H @ 48KHz). The parameters are promoted to 64bit to ensure that // no unsigned overflow is triggered as ubsan is always enabled. - a2dp_aac_encoder_cb.timestamp = - ((uint64_t)a2dp_aac_encoder_cb.timestamp + - (p_buf->layer_specific * p_encoder_params->frame_length)) & UINT32_MAX; + a2dp_aac_encoder_cb.timestamp = ((uint64_t)a2dp_aac_encoder_cb.timestamp + + (p_buf->layer_specific * p_encoder_params->frame_length)) & + UINT32_MAX; uint8_t done_nb_frame = remain_nb_frame - nb_frame; remain_nb_frame = nb_frame; - if (!a2dp_aac_encoder_cb.enqueue_callback(p_buf, done_nb_frame, - total_bytes_read)) + if (!a2dp_aac_encoder_cb.enqueue_callback(p_buf, done_nb_frame, total_bytes_read)) { return; + } } else { a2dp_aac_encoder_cb.stats.media_read_total_dropped_packets++; osi_free(p_buf); @@ -659,13 +612,14 @@ static bool a2dp_aac_read_feeding(uint8_t* read_buffer, uint32_t* bytes_read) { a2dp_aac_encoder_cb.stats.media_read_total_expected_read_bytes += read_size; /* Read Data from UIPC channel */ - uint32_t nb_byte_read = - a2dp_aac_encoder_cb.read_callback(read_buffer, read_size); + uint32_t nb_byte_read = a2dp_aac_encoder_cb.read_callback(read_buffer, read_size); a2dp_aac_encoder_cb.stats.media_read_total_actual_read_bytes += nb_byte_read; *bytes_read = nb_byte_read; if (nb_byte_read < read_size) { - if (nb_byte_read == 0) return false; + if (nb_byte_read == 0) { + return false; + } /* Fill the unfilled part of the read buffer with silence (0) */ memset(((uint8_t*)read_buffer) + nb_byte_read, 0, read_size - nb_byte_read); @@ -676,8 +630,7 @@ static bool a2dp_aac_read_feeding(uint8_t* read_buffer, uint32_t* bytes_read) { return true; } -static uint16_t adjust_effective_mtu( - const tA2DP_ENCODER_INIT_PEER_PARAMS& peer_params) { +static uint16_t adjust_effective_mtu(const tA2DP_ENCODER_INIT_PEER_PARAMS& peer_params) { uint16_t mtu_size = BT_DEFAULT_BUFFER_SIZE - A2DP_AAC_OFFSET - sizeof(BT_HDR); if (mtu_size > peer_params.peer_mtu) { mtu_size = peer_params.peer_mtu; @@ -689,8 +642,7 @@ static uint16_t adjust_effective_mtu( // exceeds the 2DH5 packet size. log::verbose("The remote device is EDR but does not support 3 Mbps"); if (mtu_size > MAX_2MBPS_AVDTP_MTU) { - log::warn("Restricting AVDTP MTU size from {} to {}", mtu_size, - MAX_2MBPS_AVDTP_MTU); + log::warn("Restricting AVDTP MTU size from {} to {}", mtu_size, MAX_2MBPS_AVDTP_MTU); mtu_size = MAX_2MBPS_AVDTP_MTU; } } @@ -703,31 +655,25 @@ void A2dpCodecConfigAacSource::debug_codec_dump(int fd) { A2dpCodecConfig::debug_codec_dump(fd); auto codec_specific_1 = getCodecConfig().codec_specific_1; - dprintf( - fd, - " AAC bitrate mode : %s " - "(0x%" PRIx64 ")\n", - ((codec_specific_1 & ~A2DP_AAC_VARIABLE_BIT_RATE_MASK) == 0 ? "Constant" - : "Variable"), - codec_specific_1); - dprintf(fd, " Encoder interval (ms): %" PRIu64 "\n", - a2dp_aac_get_encoder_interval_ms()); + dprintf(fd, + " AAC bitrate mode : %s " + "(0x%" PRIx64 ")\n", + ((codec_specific_1 & ~A2DP_AAC_VARIABLE_BIT_RATE_MASK) == 0 ? "Constant" : "Variable"), + codec_specific_1); + dprintf(fd, " Encoder interval (ms): %" PRIu64 "\n", a2dp_aac_get_encoder_interval_ms()); dprintf(fd, " Effective MTU: %d\n", a2dp_aac_get_effective_frame_size()); dprintf(fd, " Packet counts (expected/dropped) : %zu / " "%zu\n", - stats->media_read_total_expected_packets, - stats->media_read_total_dropped_packets); + stats->media_read_total_expected_packets, stats->media_read_total_dropped_packets); dprintf(fd, " PCM read counts (expected/actual) : %zu / " "%zu\n", - stats->media_read_total_expected_reads_count, - stats->media_read_total_actual_reads_count); + stats->media_read_total_expected_reads_count, stats->media_read_total_actual_reads_count); dprintf(fd, " PCM read bytes (expected/actual) : %zu / " "%zu\n", - stats->media_read_total_expected_read_bytes, - stats->media_read_total_actual_read_bytes); + stats->media_read_total_expected_read_bytes, stats->media_read_total_actual_read_bytes); } diff --git a/system/stack/a2dp/a2dp_aac_encoder_linux.cc b/system/stack/a2dp/a2dp_aac_encoder_linux.cc index adcec72b821..0388840cd61 100644 --- a/system/stack/a2dp/a2dp_aac_encoder_linux.cc +++ b/system/stack/a2dp/a2dp_aac_encoder_linux.cc @@ -35,19 +35,19 @@ const int A2DP_AAC_HEADER_LEN = 9; const int A2DP_AAC_MAX_LEN_REPR = 4; const int A2DP_AAC_MAX_PREFIX_SIZE = - AVDT_MEDIA_HDR_SIZE + A2DP_AAC_HEADER_LEN + A2DP_AAC_MAX_LEN_REPR; + AVDT_MEDIA_HDR_SIZE + A2DP_AAC_HEADER_LEN + A2DP_AAC_MAX_LEN_REPR; using namespace bluetooth; class FFmpegInterface { - public: +public: // Updates the context and configures codec parameters. // // Returns: // The (fixed) input pcm frame size that the encoder accepts. // Otherwise a negative errno on error. - int prepare_context(int sample_rate, int channel_count, int bit_rate, - int bit_depth, int effective_frame_size) { + int prepare_context(int sample_rate, int channel_count, int bit_rate, int bit_depth, + int effective_frame_size) { clear_context(); client = new mmc::CodecClient; @@ -97,7 +97,7 @@ class FFmpegInterface { return rc; } - private: +private: mmc::CodecClient* client = nullptr; }; @@ -130,13 +130,11 @@ typedef struct { a2dp_aac_encoder_stats_t stats; } tA2DP_AAC_ENCODER_CB; -static void a2dp_aac_get_num_frame_iteration(uint8_t* num_of_iterations, - uint8_t* num_of_frames, +static void a2dp_aac_get_num_frame_iteration(uint8_t* num_of_iterations, uint8_t* num_of_frames, uint64_t timestamp_us); static void a2dp_aac_encode_frames(uint8_t nb_frame); static bool a2dp_aac_read_feeding(uint8_t* read_buffer, uint32_t* bytes_read); -static uint16_t adjust_effective_mtu( - const tA2DP_ENCODER_INIT_PEER_PARAMS& peer_params); +static uint16_t adjust_effective_mtu(const tA2DP_ENCODER_INIT_PEER_PARAMS& peer_params); namespace { tA2DP_AAC_ENCODER_CB a2dp_aac_encoder_cb; @@ -163,18 +161,15 @@ void a2dp_aac_encoder_init(const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params, uint16_t mtu = adjust_effective_mtu(*p_peer_params); - int max_bit_rate = - A2DP_ComputeMaxBitRateAac(codec_info, mtu - A2DP_AAC_MAX_PREFIX_SIZE) / - 8 * 8; + int max_bit_rate = A2DP_ComputeMaxBitRateAac(codec_info, mtu - A2DP_AAC_MAX_PREFIX_SIZE) / 8 * 8; int bit_rate = std::min(A2DP_GetBitRateAac(codec_info) / 8 * 8, max_bit_rate); tA2DP_SAMPLE_RATE sample_rate = A2DP_GetTrackSampleRateAac(codec_info); tA2DP_CHANNEL_COUNT channel_count = A2DP_GetTrackChannelCountAac(codec_info); - tA2DP_BITS_PER_SAMPLE bits_per_sample = - a2dp_codec_config->getAudioBitsPerSample(); + tA2DP_BITS_PER_SAMPLE bits_per_sample = a2dp_codec_config->getAudioBitsPerSample(); - int pcm_samples_per_frame = codec_intf.prepare_context( - sample_rate, channel_count, bit_rate, bits_per_sample, mtu); + int pcm_samples_per_frame = + codec_intf.prepare_context(sample_rate, channel_count, bit_rate, bits_per_sample, mtu); if (pcm_samples_per_frame < 0) { log::error("Failed to prepare context: {}", pcm_samples_per_frame); @@ -185,29 +180,29 @@ void a2dp_aac_encoder_init(const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params, uint32_t encoder_interval_ms = pcm_samples_per_frame * 1000 / sample_rate; a2dp_aac_encoder_cb = tA2DP_AAC_ENCODER_CB{ - .read_callback = read_callback, - .enqueue_callback = enqueue_callback, - .TxAaMtuSize = mtu, - .peer_params = *p_peer_params, - .timestamp = bluetooth::os::GenerateRandom(), // (RFC 6416) - .feeding_params = - { - .sample_rate = sample_rate, - .bits_per_sample = bits_per_sample, - .channel_count = channel_count, - }, - .aac_feeding_state = - tA2DP_AAC_FEEDING_STATE{ - .bytes_per_tick = (sample_rate * bits_per_sample / 8 * - channel_count * encoder_interval_ms) / - 1000, - }, - .pcm_samples_per_frame = static_cast(pcm_samples_per_frame), - .encoder_interval_ms = encoder_interval_ms, - .stats = - a2dp_aac_encoder_stats_t{ - .session_start_us = bluetooth::common::time_get_os_boottime_us(), - }, + .read_callback = read_callback, + .enqueue_callback = enqueue_callback, + .TxAaMtuSize = mtu, + .peer_params = *p_peer_params, + .timestamp = bluetooth::os::GenerateRandom(), // (RFC 6416) + .feeding_params = + { + .sample_rate = sample_rate, + .bits_per_sample = bits_per_sample, + .channel_count = channel_count, + }, + .aac_feeding_state = + tA2DP_AAC_FEEDING_STATE{ + .bytes_per_tick = (sample_rate * bits_per_sample / 8 * channel_count * + encoder_interval_ms) / + 1000, + }, + .pcm_samples_per_frame = static_cast(pcm_samples_per_frame), + .encoder_interval_ms = encoder_interval_ms, + .stats = + a2dp_aac_encoder_stats_t{ + .session_start_us = bluetooth::common::time_get_os_boottime_us(), + }, }; } @@ -227,36 +222,31 @@ void a2dp_aac_feeding_reset() { a2dp_aac_encoder_cb.encoder_interval_ms = frame_length * 1000 / sample_rate; a2dp_aac_encoder_cb.aac_feeding_state = tA2DP_AAC_FEEDING_STATE{ - .bytes_per_tick = (a2dp_aac_encoder_cb.feeding_params.sample_rate * - a2dp_aac_encoder_cb.feeding_params.bits_per_sample / - 8 * a2dp_aac_encoder_cb.feeding_params.channel_count * - a2dp_aac_encoder_cb.encoder_interval_ms) / - 1000, + .bytes_per_tick = (a2dp_aac_encoder_cb.feeding_params.sample_rate * + a2dp_aac_encoder_cb.feeding_params.bits_per_sample / 8 * + a2dp_aac_encoder_cb.feeding_params.channel_count * + a2dp_aac_encoder_cb.encoder_interval_ms) / + 1000, }; - log::warn("PCM bytes {} per tick ({}ms)", - a2dp_aac_encoder_cb.aac_feeding_state.bytes_per_tick, + log::warn("PCM bytes {} per tick ({}ms)", a2dp_aac_encoder_cb.aac_feeding_state.bytes_per_tick, a2dp_aac_encoder_cb.encoder_interval_ms); } -void a2dp_aac_feeding_flush() { - a2dp_aac_encoder_cb.aac_feeding_state.counter = 0.0f; -} +void a2dp_aac_feeding_flush() { a2dp_aac_encoder_cb.aac_feeding_state.counter = 0.0f; } -uint64_t a2dp_aac_get_encoder_interval_ms() { - return a2dp_aac_encoder_cb.encoder_interval_ms; -} +uint64_t a2dp_aac_get_encoder_interval_ms() { return a2dp_aac_encoder_cb.encoder_interval_ms; } -int a2dp_aac_get_effective_frame_size() { - return a2dp_aac_encoder_cb.TxAaMtuSize; -} +int a2dp_aac_get_effective_frame_size() { return a2dp_aac_encoder_cb.TxAaMtuSize; } void a2dp_aac_send_frames(uint64_t timestamp_us) { uint8_t nb_frame = 0; uint8_t nb_iterations = 0; a2dp_aac_get_num_frame_iteration(&nb_iterations, &nb_frame, timestamp_us); - if (nb_frame == 0) return; + if (nb_frame == 0) { + return; + } for (uint8_t counter = 0; counter < nb_iterations; counter++) { a2dp_aac_encode_frames(nb_frame); @@ -266,29 +256,27 @@ void a2dp_aac_send_frames(uint64_t timestamp_us) { // Obtains the number of frames to send and number of iterations // to be used. |num_of_iterations| and |num_of_frames| parameters // are used as output param for returning the respective values. -static void a2dp_aac_get_num_frame_iteration(uint8_t* num_of_iterations, - uint8_t* num_of_frames, +static void a2dp_aac_get_num_frame_iteration(uint8_t* num_of_iterations, uint8_t* num_of_frames, uint64_t timestamp_us) { uint32_t result = 0; uint8_t nof = 0; uint8_t noi = 1; - uint32_t pcm_bytes_per_frame = - a2dp_aac_encoder_cb.pcm_samples_per_frame * - a2dp_aac_encoder_cb.feeding_params.channel_count * - a2dp_aac_encoder_cb.feeding_params.bits_per_sample / 8; + uint32_t pcm_bytes_per_frame = a2dp_aac_encoder_cb.pcm_samples_per_frame * + a2dp_aac_encoder_cb.feeding_params.channel_count * + a2dp_aac_encoder_cb.feeding_params.bits_per_sample / 8; log::verbose("pcm_bytes_per_frame {}", pcm_bytes_per_frame); uint32_t us_this_tick = a2dp_aac_encoder_cb.encoder_interval_ms * 1000; uint64_t now_us = timestamp_us; - if (a2dp_aac_encoder_cb.aac_feeding_state.last_frame_us != 0) - us_this_tick = - (now_us - a2dp_aac_encoder_cb.aac_feeding_state.last_frame_us); + if (a2dp_aac_encoder_cb.aac_feeding_state.last_frame_us != 0) { + us_this_tick = (now_us - a2dp_aac_encoder_cb.aac_feeding_state.last_frame_us); + } a2dp_aac_encoder_cb.aac_feeding_state.last_frame_us = now_us; a2dp_aac_encoder_cb.aac_feeding_state.counter += - (float)a2dp_aac_encoder_cb.aac_feeding_state.bytes_per_tick * - us_this_tick / (a2dp_aac_encoder_cb.encoder_interval_ms * 1000); + (float)a2dp_aac_encoder_cb.aac_feeding_state.bytes_per_tick * us_this_tick / + (a2dp_aac_encoder_cb.encoder_interval_ms * 1000); result = a2dp_aac_encoder_cb.aac_feeding_state.counter / pcm_bytes_per_frame; a2dp_aac_encoder_cb.aac_feeding_state.counter -= result * pcm_bytes_per_frame; @@ -304,8 +292,7 @@ static void a2dp_aac_encode_frames(uint8_t nb_frame) { uint8_t read_buffer[BT_DEFAULT_BUFFER_SIZE]; int pcm_bytes_per_frame = a2dp_aac_encoder_cb.pcm_samples_per_frame * a2dp_aac_encoder_cb.feeding_params.channel_count * - a2dp_aac_encoder_cb.feeding_params.bits_per_sample / - 8; + a2dp_aac_encoder_cb.feeding_params.bits_per_sample / 8; log::assert_that(pcm_bytes_per_frame <= static_cast(sizeof(read_buffer)), "assert failed: pcm_bytes_per_frame <= " "static_cast(sizeof(read_buffer))"); @@ -317,9 +304,9 @@ static void a2dp_aac_encode_frames(uint8_t nb_frame) { if (!a2dp_aac_read_feeding(read_buffer, &bytes_read)) { log::warn("Underflow {}", nb_frame); a2dp_aac_encoder_cb.aac_feeding_state.counter += - nb_frame * a2dp_aac_encoder_cb.pcm_samples_per_frame * - a2dp_aac_encoder_cb.feeding_params.channel_count * - a2dp_aac_encoder_cb.feeding_params.bits_per_sample / 8; + nb_frame * a2dp_aac_encoder_cb.pcm_samples_per_frame * + a2dp_aac_encoder_cb.feeding_params.channel_count * + a2dp_aac_encoder_cb.feeding_params.bits_per_sample / 8; return; } @@ -328,9 +315,9 @@ static void a2dp_aac_encode_frames(uint8_t nb_frame) { p_buf->len = 0; p_buf->layer_specific = 0; - int written = codec_intf.encode_pcm( - read_buffer, bytes_read, (uint8_t*)(p_buf + 1) + p_buf->offset, - BT_DEFAULT_BUFFER_SIZE - 1 - p_buf->offset); + int written = + codec_intf.encode_pcm(read_buffer, bytes_read, (uint8_t*)(p_buf + 1) + p_buf->offset, + BT_DEFAULT_BUFFER_SIZE - 1 - p_buf->offset); if (written < 0) { a2dp_aac_encoder_cb.stats.media_read_total_dropped_packets++; @@ -352,9 +339,11 @@ static void a2dp_aac_encode_frames(uint8_t nb_frame) { *((uint32_t*)(p_buf + 1)) = a2dp_aac_encoder_cb.timestamp; a2dp_aac_encoder_cb.timestamp += - p_buf->layer_specific * a2dp_aac_encoder_cb.pcm_samples_per_frame; + p_buf->layer_specific * a2dp_aac_encoder_cb.pcm_samples_per_frame; - if (!a2dp_aac_encoder_cb.enqueue_callback(p_buf, 1, bytes_read)) return; + if (!a2dp_aac_encoder_cb.enqueue_callback(p_buf, 1, bytes_read)) { + return; + } } } @@ -367,17 +356,17 @@ static bool a2dp_aac_read_feeding(uint8_t* read_buffer, uint32_t* bytes_read) { a2dp_aac_encoder_cb.stats.media_read_total_expected_read_bytes += read_size; /* Read Data from UIPC channel */ - uint32_t nb_byte_read = - a2dp_aac_encoder_cb.read_callback(read_buffer, read_size); + uint32_t nb_byte_read = a2dp_aac_encoder_cb.read_callback(read_buffer, read_size); a2dp_aac_encoder_cb.stats.media_read_total_actual_read_bytes += nb_byte_read; *bytes_read = nb_byte_read; if (nb_byte_read < read_size) { - if (nb_byte_read == 0) return false; + if (nb_byte_read == 0) { + return false; + } /* Fill the unfilled part of the read buffer with silence (0) */ - std::fill_n((uint8_t*)read_buffer + nb_byte_read, read_size - nb_byte_read, - 0x00); + std::fill_n((uint8_t*)read_buffer + nb_byte_read, read_size - nb_byte_read, 0x00); nb_byte_read = read_size; } a2dp_aac_encoder_cb.stats.media_read_total_actual_reads_count++; @@ -385,10 +374,8 @@ static bool a2dp_aac_read_feeding(uint8_t* read_buffer, uint32_t* bytes_read) { return true; } -static uint16_t adjust_effective_mtu( - const tA2DP_ENCODER_INIT_PEER_PARAMS& peer_params) { - uint16_t mtu_size = - BT_DEFAULT_BUFFER_SIZE - AVDT_MEDIA_OFFSET - sizeof(BT_HDR); +static uint16_t adjust_effective_mtu(const tA2DP_ENCODER_INIT_PEER_PARAMS& peer_params) { + uint16_t mtu_size = BT_DEFAULT_BUFFER_SIZE - AVDT_MEDIA_OFFSET - sizeof(BT_HDR); if (mtu_size > peer_params.peer_mtu) { mtu_size = peer_params.peer_mtu; } @@ -399,8 +386,7 @@ static uint16_t adjust_effective_mtu( // exceeds the 2DH5 packet size. log::verbose("The remote device is EDR but does not support 3 Mbps"); if (mtu_size > MAX_2MBPS_AVDTP_MTU) { - log::warn("Restricting AVDTP MTU size from {} to {}", mtu_size, - MAX_2MBPS_AVDTP_MTU); + log::warn("Restricting AVDTP MTU size from {} to {}", mtu_size, MAX_2MBPS_AVDTP_MTU); mtu_size = MAX_2MBPS_AVDTP_MTU; } } @@ -413,31 +399,25 @@ void A2dpCodecConfigAacSource::debug_codec_dump(int fd) { A2dpCodecConfig::debug_codec_dump(fd); auto codec_specific_1 = getCodecConfig().codec_specific_1; - dprintf( - fd, - " AAC bitrate mode : %s " - "(0x%" PRIx64 ")\n", - ((codec_specific_1 & ~A2DP_AAC_VARIABLE_BIT_RATE_MASK) == 0 ? "Constant" - : "Variable"), - codec_specific_1); - dprintf(fd, " Encoder interval (ms): %" PRIu64 "\n", - a2dp_aac_get_encoder_interval_ms()); + dprintf(fd, + " AAC bitrate mode : %s " + "(0x%" PRIx64 ")\n", + ((codec_specific_1 & ~A2DP_AAC_VARIABLE_BIT_RATE_MASK) == 0 ? "Constant" : "Variable"), + codec_specific_1); + dprintf(fd, " Encoder interval (ms): %" PRIu64 "\n", a2dp_aac_get_encoder_interval_ms()); dprintf(fd, " Effective MTU: %d\n", a2dp_aac_get_effective_frame_size()); dprintf(fd, " Packet counts (expected/dropped) : %zu / " "%zu\n", - stats->media_read_total_expected_packets, - stats->media_read_total_dropped_packets); + stats->media_read_total_expected_packets, stats->media_read_total_dropped_packets); dprintf(fd, " PCM read counts (expected/actual) : %zu / " "%zu\n", - stats->media_read_total_expected_reads_count, - stats->media_read_total_actual_reads_count); + stats->media_read_total_expected_reads_count, stats->media_read_total_actual_reads_count); dprintf(fd, " PCM read bytes (expected/actual) : %zu / " "%zu\n", - stats->media_read_total_expected_read_bytes, - stats->media_read_total_actual_read_bytes); + stats->media_read_total_expected_read_bytes, stats->media_read_total_actual_read_bytes); } diff --git a/system/stack/a2dp/a2dp_api.cc b/system/stack/a2dp/a2dp_api.cc index d6b49899570..fee00f1d2c2 100644 --- a/system/stack/a2dp/a2dp_api.cc +++ b/system/stack/a2dp/a2dp_api.cc @@ -50,10 +50,9 @@ using bluetooth::Uuid; ****************************************************************************/ tA2DP_CB a2dp_cb; static uint16_t a2dp_attr_list[] = { - ATTR_ID_SERVICE_CLASS_ID_LIST, /* update A2DP_NUM_ATTR, if changed */ - ATTR_ID_BT_PROFILE_DESC_LIST, ATTR_ID_SUPPORTED_FEATURES, - ATTR_ID_SERVICE_NAME, ATTR_ID_PROTOCOL_DESC_LIST, - ATTR_ID_PROVIDER_NAME}; + ATTR_ID_SERVICE_CLASS_ID_LIST, /* update A2DP_NUM_ATTR, if changed */ + ATTR_ID_BT_PROFILE_DESC_LIST, ATTR_ID_SUPPORTED_FEATURES, ATTR_ID_SERVICE_NAME, + ATTR_ID_PROTOCOL_DESC_LIST, ATTR_ID_PROVIDER_NAME}; /****************************************************************************** * @@ -70,8 +69,7 @@ static uint16_t a2dp_attr_list[] = { * Returns Nothing. * *****************************************************************************/ -static void a2dp_sdp_cback(const RawAddress& /* bd_addr */, - tSDP_STATUS status) { +static void a2dp_sdp_cback(const RawAddress& /* bd_addr */, tSDP_STATUS status) { tSDP_DISC_REC* p_rec = NULL; tSDP_DISC_ATTR* p_attr; bool found = false; @@ -86,7 +84,7 @@ static void a2dp_sdp_cback(const RawAddress& /* bd_addr */, do { /* get next record; if none found, we're done */ if ((p_rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb( - a2dp_cb.find.p_db, a2dp_cb.find.service_uuid, p_rec)) == NULL) { + a2dp_cb.find.p_db, a2dp_cb.find.service_uuid, p_rec)) == NULL) { break; } memset(&a2dp_svc, 0, sizeof(tA2DP_Service)); @@ -94,7 +92,7 @@ static void a2dp_sdp_cback(const RawAddress& /* bd_addr */, /* get service name */ if ((p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - p_rec, ATTR_ID_SERVICE_NAME)) != NULL) { + p_rec, ATTR_ID_SERVICE_NAME)) != NULL) { if (SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == TEXT_STR_DESC_TYPE) { a2dp_svc.p_service_name = (char*)p_attr->attr_value.v.array; a2dp_svc.service_len = SDP_DISC_ATTR_LEN(p_attr->attr_len_type); @@ -107,7 +105,7 @@ static void a2dp_sdp_cback(const RawAddress& /* bd_addr */, /* get provider name */ if ((p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - p_rec, ATTR_ID_PROVIDER_NAME)) != NULL) { + p_rec, ATTR_ID_PROVIDER_NAME)) != NULL) { if (SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == TEXT_STR_DESC_TYPE) { a2dp_svc.p_provider_name = (char*)p_attr->attr_value.v.array; a2dp_svc.provider_len = SDP_DISC_ATTR_LEN(p_attr->attr_len_type); @@ -120,7 +118,7 @@ static void a2dp_sdp_cback(const RawAddress& /* bd_addr */, /* get supported features */ if ((p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - p_rec, ATTR_ID_SUPPORTED_FEATURES)) != NULL) { + p_rec, ATTR_ID_SUPPORTED_FEATURES)) != NULL) { if (SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == UINT_DESC_TYPE && SDP_DISC_ATTR_LEN(p_attr->attr_len_type) >= 2) { a2dp_svc.features = p_attr->attr_value.v.u16; @@ -133,7 +131,7 @@ static void a2dp_sdp_cback(const RawAddress& /* bd_addr */, /* get AVDTP version */ if (get_legacy_stack_sdp_api()->record.SDP_FindProtocolListElemInRec( - p_rec, UUID_PROTOCOL_AVDTP, &elem)) { + p_rec, UUID_PROTOCOL_AVDTP, &elem)) { a2dp_svc.avdt_version = elem.params[0]; log::verbose("avdt_version: 0x{:x}", a2dp_svc.avdt_version); } @@ -165,9 +163,7 @@ static void a2dp_sdp_cback(const RawAddress& /* bd_addr */, * Returns None * ******************************************************************************/ -void a2dp_set_avdt_sdp_ver(uint16_t avdt_sdp_ver) { - a2dp_cb.avdt_sdp_ver = avdt_sdp_ver; -} +void a2dp_set_avdt_sdp_ver(uint16_t avdt_sdp_ver) { a2dp_cb.avdt_sdp_ver = avdt_sdp_ver; } /****************************************************************************** * @@ -199,9 +195,8 @@ void a2dp_set_avdt_sdp_ver(uint16_t avdt_sdp_ver) { * A2DP_FAIL if function execution failed. * *****************************************************************************/ -tA2DP_STATUS A2DP_AddRecord(uint16_t service_uuid, char* p_service_name, - char* p_provider_name, uint16_t features, - uint32_t sdp_handle) { +tA2DP_STATUS A2DP_AddRecord(uint16_t service_uuid, char* p_service_name, char* p_provider_name, + uint16_t features, uint32_t sdp_handle) { uint16_t browse_list[1]; bool result = true; uint8_t temp[8]; @@ -210,16 +205,16 @@ tA2DP_STATUS A2DP_AddRecord(uint16_t service_uuid, char* p_service_name, log::verbose("uuid: 0x{:x}", service_uuid); - if ((sdp_handle == 0) || (service_uuid != UUID_SERVCLASS_AUDIO_SOURCE && - service_uuid != UUID_SERVCLASS_AUDIO_SINK)) + if ((sdp_handle == 0) || + (service_uuid != UUID_SERVCLASS_AUDIO_SOURCE && service_uuid != UUID_SERVCLASS_AUDIO_SINK)) { return A2DP_INVALID_PARAMS; + } /* add service class id list */ - result &= get_legacy_stack_sdp_api()->handle.SDP_AddServiceClassIdList( - sdp_handle, 1, &service_uuid); + result &= get_legacy_stack_sdp_api()->handle.SDP_AddServiceClassIdList(sdp_handle, 1, + &service_uuid); - memset((void*)proto_list, 0, - A2DP_NUM_PROTO_ELEMS * sizeof(tSDP_PROTOCOL_ELEM)); + memset((void*)proto_list, 0, A2DP_NUM_PROTO_ELEMS * sizeof(tSDP_PROTOCOL_ELEM)); /* add protocol descriptor list */ proto_list[0].protocol_uuid = UUID_PROTOCOL_L2CAP; @@ -229,42 +224,41 @@ tA2DP_STATUS A2DP_AddRecord(uint16_t service_uuid, char* p_service_name, proto_list[1].num_params = 1; proto_list[1].params[0] = a2dp_cb.avdt_sdp_ver; - result &= get_legacy_stack_sdp_api()->handle.SDP_AddProtocolList( - sdp_handle, A2DP_NUM_PROTO_ELEMS, proto_list); + result &= get_legacy_stack_sdp_api()->handle.SDP_AddProtocolList(sdp_handle, A2DP_NUM_PROTO_ELEMS, + proto_list); /* add profile descriptor list */ result &= get_legacy_stack_sdp_api()->handle.SDP_AddProfileDescriptorList( - sdp_handle, UUID_SERVCLASS_ADV_AUDIO_DISTRIBUTION, A2DP_VERSION); + sdp_handle, UUID_SERVCLASS_ADV_AUDIO_DISTRIBUTION, A2DP_VERSION); /* add supported feature */ if (features != 0) { p = temp; UINT16_TO_BE_STREAM(p, features); result &= get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - sdp_handle, ATTR_ID_SUPPORTED_FEATURES, UINT_DESC_TYPE, (uint32_t)2, - (uint8_t*)temp); + sdp_handle, ATTR_ID_SUPPORTED_FEATURES, UINT_DESC_TYPE, (uint32_t)2, (uint8_t*)temp); } /* add provider name */ if (p_provider_name != NULL) { result &= get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - sdp_handle, ATTR_ID_PROVIDER_NAME, TEXT_STR_DESC_TYPE, - (uint32_t)(strlen(p_provider_name) + 1), (uint8_t*)p_provider_name); + sdp_handle, ATTR_ID_PROVIDER_NAME, TEXT_STR_DESC_TYPE, + (uint32_t)(strlen(p_provider_name) + 1), (uint8_t*)p_provider_name); } /* add service name */ if (p_service_name != NULL) { result &= get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - sdp_handle, ATTR_ID_SERVICE_NAME, TEXT_STR_DESC_TYPE, - (uint32_t)(strlen(p_service_name) + 1), (uint8_t*)p_service_name); + sdp_handle, ATTR_ID_SERVICE_NAME, TEXT_STR_DESC_TYPE, + (uint32_t)(strlen(p_service_name) + 1), (uint8_t*)p_service_name); } /* add browse group list */ browse_list[0] = UUID_SERVCLASS_PUBLIC_BROWSE_GROUP; result &= get_legacy_stack_sdp_api()->handle.SDP_AddUuidSequence( - sdp_handle, ATTR_ID_BROWSE_GROUP_LIST, 1, browse_list); + sdp_handle, ATTR_ID_BROWSE_GROUP_LIST, 1, browse_list); - return (result ? A2DP_SUCCESS : A2DP_FAIL); + return result ? A2DP_SUCCESS : A2DP_FAIL; } /****************************************************************************** @@ -303,22 +297,17 @@ tA2DP_STATUS A2DP_AddRecord(uint16_t service_uuid, char* p_service_name, * *****************************************************************************/ tA2DP_STATUS A2DP_FindService(uint16_t service_uuid, const RawAddress& bd_addr, - tA2DP_SDP_DB_PARAMS* p_db, - tA2DP_FIND_CBACK p_cback) { - if ((service_uuid != UUID_SERVCLASS_AUDIO_SOURCE && - service_uuid != UUID_SERVCLASS_AUDIO_SINK) || + tA2DP_SDP_DB_PARAMS* p_db, tA2DP_FIND_CBACK p_cback) { + if ((service_uuid != UUID_SERVCLASS_AUDIO_SOURCE && service_uuid != UUID_SERVCLASS_AUDIO_SINK) || p_db == NULL || p_cback.is_null()) { - log::error( - "Cannot find service for peer {} UUID 0x{:04x}: invalid parameters", - bd_addr, service_uuid); + log::error("Cannot find service for peer {} UUID 0x{:04x}: invalid parameters", bd_addr, + service_uuid); return A2DP_INVALID_PARAMS; } if (a2dp_cb.find.service_uuid == UUID_SERVCLASS_AUDIO_SOURCE || - a2dp_cb.find.service_uuid == UUID_SERVCLASS_AUDIO_SINK || - a2dp_cb.find.p_db != NULL) { - log::error("Cannot find service for peer {} UUID 0x{:04x}: busy", bd_addr, - service_uuid); + a2dp_cb.find.service_uuid == UUID_SERVCLASS_AUDIO_SINK || a2dp_cb.find.p_db != NULL) { + log::error("Cannot find service for peer {} UUID 0x{:04x}: busy", bd_addr, service_uuid); return A2DP_BUSY; } @@ -331,11 +320,10 @@ tA2DP_STATUS A2DP_FindService(uint16_t service_uuid, const RawAddress& bd_addr, Uuid uuid_list = Uuid::From16Bit(service_uuid); if (!get_legacy_stack_sdp_api()->service.SDP_InitDiscoveryDb( - a2dp_cb.find.p_db, p_db->db_len, 1, &uuid_list, p_db->num_attr, - p_db->p_attrs)) { + a2dp_cb.find.p_db, p_db->db_len, 1, &uuid_list, p_db->num_attr, p_db->p_attrs)) { osi_free_and_reset((void**)&a2dp_cb.find.p_db); - log::error("Unable to initialize SDP discovery for peer {} UUID 0x{:04X}", - bd_addr, service_uuid); + log::error("Unable to initialize SDP discovery for peer {} UUID 0x{:04X}", bd_addr, + service_uuid); return A2DP_FAIL; } @@ -345,17 +333,15 @@ tA2DP_STATUS A2DP_FindService(uint16_t service_uuid, const RawAddress& bd_addr, /* perform service search */ if (!get_legacy_stack_sdp_api()->service.SDP_ServiceSearchAttributeRequest( - bd_addr, a2dp_cb.find.p_db, a2dp_sdp_cback)) { + bd_addr, a2dp_cb.find.p_db, a2dp_sdp_cback)) { a2dp_cb.find.service_uuid = 0; a2dp_cb.find.p_cback.Reset(); osi_free_and_reset((void**)&a2dp_cb.find.p_db); - log::error("Cannot find service for peer {} UUID 0x{:04x}: SDP error", - bd_addr, service_uuid); + log::error("Cannot find service for peer {} UUID 0x{:04x}: SDP error", bd_addr, service_uuid); return A2DP_FAIL; } - log::info( - "A2DP service discovery for peer {} UUID 0x{:04x}: SDP search started", - bd_addr, service_uuid); + log::info("A2DP service discovery for peer {} UUID 0x{:04x}: SDP search started", bd_addr, + service_uuid); return A2DP_SUCCESS; } @@ -368,8 +354,12 @@ tA2DP_STATUS A2DP_FindService(uint16_t service_uuid, const RawAddress& bd_addr, * A2DP_SET_MULTL_BIT, if multiple bits are set *****************************************************************************/ uint8_t A2DP_BitsSet(uint64_t num) { - if (num == 0) return A2DP_SET_ZERO_BIT; - if ((num & (num - 1)) == 0) return A2DP_SET_ONE_BIT; + if (num == 0) { + return A2DP_SET_ZERO_BIT; + } + if ((num & (num - 1)) == 0) { + return A2DP_SET_ONE_BIT; + } return A2DP_SET_MULTL_BIT; } diff --git a/system/stack/a2dp/a2dp_codec_config.cc b/system/stack/a2dp/a2dp_codec_config.cc index 3609f80495c..bec302a5c23 100644 --- a/system/stack/a2dp/a2dp_codec_config.cc +++ b/system/stack/a2dp/a2dp_codec_config.cc @@ -52,17 +52,16 @@ using namespace bluetooth; -static void init_btav_a2dp_codec_config( - btav_a2dp_codec_config_t* codec_config, btav_a2dp_codec_index_t codec_index, - btav_a2dp_codec_priority_t codec_priority) { +static void init_btav_a2dp_codec_config(btav_a2dp_codec_config_t* codec_config, + btav_a2dp_codec_index_t codec_index, + btav_a2dp_codec_priority_t codec_priority) { memset(codec_config, 0, sizeof(btav_a2dp_codec_config_t)); codec_config->codec_type = codec_index; codec_config->codec_priority = codec_priority; } -A2dpCodecConfig::A2dpCodecConfig(btav_a2dp_codec_index_t codec_index, - uint64_t codec_id, const std::string& name, - btav_a2dp_codec_priority_t codec_priority) +A2dpCodecConfig::A2dpCodecConfig(btav_a2dp_codec_index_t codec_index, uint64_t codec_id, + const std::string& name, btav_a2dp_codec_priority_t codec_priority) : codec_index_(codec_index), codec_id_(codec_id), name_(name), @@ -70,16 +69,11 @@ A2dpCodecConfig::A2dpCodecConfig(btav_a2dp_codec_index_t codec_index, setCodecPriority(codec_priority); init_btav_a2dp_codec_config(&codec_config_, codec_index_, codecPriority()); - init_btav_a2dp_codec_config(&codec_capability_, codec_index_, - codecPriority()); - init_btav_a2dp_codec_config(&codec_local_capability_, codec_index_, - codecPriority()); - init_btav_a2dp_codec_config(&codec_selectable_capability_, codec_index_, - codecPriority()); - init_btav_a2dp_codec_config(&codec_user_config_, codec_index_, - BTAV_A2DP_CODEC_PRIORITY_DEFAULT); - init_btav_a2dp_codec_config(&codec_audio_config_, codec_index_, - BTAV_A2DP_CODEC_PRIORITY_DEFAULT); + init_btav_a2dp_codec_config(&codec_capability_, codec_index_, codecPriority()); + init_btav_a2dp_codec_config(&codec_local_capability_, codec_index_, codecPriority()); + init_btav_a2dp_codec_config(&codec_selectable_capability_, codec_index_, codecPriority()); + init_btav_a2dp_codec_config(&codec_user_config_, codec_index_, BTAV_A2DP_CODEC_PRIORITY_DEFAULT); + init_btav_a2dp_codec_config(&codec_audio_config_, codec_index_, BTAV_A2DP_CODEC_PRIORITY_DEFAULT); memset(ota_codec_config_, 0, sizeof(ota_codec_config_)); memset(ota_codec_peer_capability_, 0, sizeof(ota_codec_peer_capability_)); @@ -88,8 +82,7 @@ A2dpCodecConfig::A2dpCodecConfig(btav_a2dp_codec_index_t codec_index, A2dpCodecConfig::~A2dpCodecConfig() {} -void A2dpCodecConfig::setCodecPriority( - btav_a2dp_codec_priority_t codec_priority) { +void A2dpCodecConfig::setCodecPriority(btav_a2dp_codec_priority_t codec_priority) { if (codec_priority == BTAV_A2DP_CODEC_PRIORITY_DEFAULT) { // Compute the default codec priority setDefaultCodecPriority(); @@ -110,9 +103,8 @@ void A2dpCodecConfig::setDefaultCodecPriority() { codec_config_.codec_priority = codec_priority_; } -A2dpCodecConfig* A2dpCodecConfig::createCodec( - btav_a2dp_codec_index_t codec_index, - btav_a2dp_codec_priority_t codec_priority) { +A2dpCodecConfig* A2dpCodecConfig::createCodec(btav_a2dp_codec_index_t codec_index, + btav_a2dp_codec_priority_t codec_priority) { log::info("{}", A2DP_CodecIndexStr(codec_index)); // Hardware offload codec extensibility: @@ -210,12 +202,10 @@ bool A2dpCodecConfig::getCodecSpecificConfig(tBT_A2DP_OFFLOAD* p_a2dp_offload) { tA2DP_CODEC_TYPE codec_type = A2DP_GetCodecType(codec_config); switch (codec_type) { case A2DP_MEDIA_CT_SBC: - p_a2dp_offload->codec_info[0] = - codec_config[4]; // blk_len | subbands | Alloc Method + p_a2dp_offload->codec_info[0] = codec_config[4]; // blk_len | subbands | Alloc Method p_a2dp_offload->codec_info[1] = codec_config[5]; // Min bit pool p_a2dp_offload->codec_info[2] = codec_config[6]; // Max bit pool - p_a2dp_offload->codec_info[3] = - codec_config[3]; // Sample freq | channel mode + p_a2dp_offload->codec_info[3] = codec_config[3]; // Sample freq | channel mode break; #if !defined(EXCLUDE_NONSTANDARD_CODECS) case A2DP_MEDIA_CT_AAC: @@ -232,35 +222,28 @@ bool A2dpCodecConfig::getCodecSpecificConfig(tBT_A2DP_OFFLOAD* p_a2dp_offload) { p_a2dp_offload->codec_info[4] = (codec_id & 0x000000FF); p_a2dp_offload->codec_info[5] = (codec_id & 0x0000FF00) >> 8; if (vendor_id == A2DP_LDAC_VENDOR_ID && codec_id == A2DP_LDAC_CODEC_ID) { - if (codec_config_.codec_specific_1 == 0) { // default is 0, ABR - p_a2dp_offload->codec_info[6] = - A2DP_LDAC_QUALITY_ABR_OFFLOAD; // ABR in offload + if (codec_config_.codec_specific_1 == 0) { // default is 0, ABR + p_a2dp_offload->codec_info[6] = A2DP_LDAC_QUALITY_ABR_OFFLOAD; // ABR in offload } else { switch (codec_config_.codec_specific_1 % 10) { case 0: - p_a2dp_offload->codec_info[6] = - A2DP_LDAC_QUALITY_HIGH; // High bitrate + p_a2dp_offload->codec_info[6] = A2DP_LDAC_QUALITY_HIGH; // High bitrate break; case 1: - p_a2dp_offload->codec_info[6] = - A2DP_LDAC_QUALITY_MID; // Mid birate + p_a2dp_offload->codec_info[6] = A2DP_LDAC_QUALITY_MID; // Mid birate break; case 2: - p_a2dp_offload->codec_info[6] = - A2DP_LDAC_QUALITY_LOW; // Low birate + p_a2dp_offload->codec_info[6] = A2DP_LDAC_QUALITY_LOW; // Low birate break; case 3: FALLTHROUGH_INTENDED; /* FALLTHROUGH */ default: - p_a2dp_offload->codec_info[6] = - A2DP_LDAC_QUALITY_ABR_OFFLOAD; // ABR in offload + p_a2dp_offload->codec_info[6] = A2DP_LDAC_QUALITY_ABR_OFFLOAD; // ABR in offload break; } } - p_a2dp_offload->codec_info[7] = - codec_config[10]; // LDAC specific channel mode - log::verbose("Ldac specific channelmode ={}", - p_a2dp_offload->codec_info[7]); + p_a2dp_offload->codec_info[7] = codec_config[10]; // LDAC specific channel mode + log::verbose("Ldac specific channelmode ={}", p_a2dp_offload->codec_info[7]); } break; #endif @@ -340,26 +323,21 @@ uint8_t A2dpCodecConfig::getAudioBitsPerSample() { return 0; } -bool A2dpCodecConfig::isCodecConfigEmpty( - const btav_a2dp_codec_config_t& codec_config) { - return ( - (codec_config.codec_priority == BTAV_A2DP_CODEC_PRIORITY_DEFAULT) && - (codec_config.sample_rate == BTAV_A2DP_CODEC_SAMPLE_RATE_NONE) && - (codec_config.bits_per_sample == BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE) && - (codec_config.channel_mode == BTAV_A2DP_CODEC_CHANNEL_MODE_NONE) && - (codec_config.codec_specific_1 == 0) && - (codec_config.codec_specific_2 == 0) && - (codec_config.codec_specific_3 == 0) && - (codec_config.codec_specific_4 == 0)); -} - -bool A2dpCodecConfig::setCodecUserConfig( - const btav_a2dp_codec_config_t& codec_user_config, - const btav_a2dp_codec_config_t& codec_audio_config, - const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params, - const uint8_t* p_peer_codec_info, bool is_capability, - uint8_t* p_result_codec_config, bool* p_restart_input, - bool* p_restart_output, bool* p_config_updated) { +bool A2dpCodecConfig::isCodecConfigEmpty(const btav_a2dp_codec_config_t& codec_config) { + return (codec_config.codec_priority == BTAV_A2DP_CODEC_PRIORITY_DEFAULT) && + (codec_config.sample_rate == BTAV_A2DP_CODEC_SAMPLE_RATE_NONE) && + (codec_config.bits_per_sample == BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE) && + (codec_config.channel_mode == BTAV_A2DP_CODEC_CHANNEL_MODE_NONE) && + (codec_config.codec_specific_1 == 0) && (codec_config.codec_specific_2 == 0) && + (codec_config.codec_specific_3 == 0) && (codec_config.codec_specific_4 == 0); +} + +bool A2dpCodecConfig::setCodecUserConfig(const btav_a2dp_codec_config_t& codec_user_config, + const btav_a2dp_codec_config_t& codec_audio_config, + const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params, + const uint8_t* p_peer_codec_info, bool is_capability, + uint8_t* p_result_codec_config, bool* p_restart_input, + bool* p_restart_output, bool* p_config_updated) { std::lock_guard lock(codec_mutex_); *p_restart_input = false; *p_restart_output = false; @@ -375,8 +353,7 @@ bool A2dpCodecConfig::setCodecUserConfig( codec_user_config_ = codec_user_config; btav_a2dp_codec_config_t saved_codec_audio_config = codec_audio_config_; codec_audio_config_ = codec_audio_config; - bool success = - setCodecConfig(p_peer_codec_info, is_capability, p_result_codec_config); + bool success = setCodecConfig(p_peer_codec_info, is_capability, p_result_codec_config); if (!success) { // Restore the local copy of the user and audio config codec_user_config_ = saved_codec_user_config; @@ -389,8 +366,7 @@ bool A2dpCodecConfig::setCodecUserConfig( // btav_a2dp_codec_config_t new_codec_config = getCodecConfig(); if ((saved_codec_config.sample_rate != new_codec_config.sample_rate) || - (saved_codec_config.bits_per_sample != - new_codec_config.bits_per_sample) || + (saved_codec_config.bits_per_sample != new_codec_config.bits_per_sample) || (saved_codec_config.channel_mode != new_codec_config.channel_mode)) { *p_restart_input = true; } @@ -403,25 +379,26 @@ bool A2dpCodecConfig::setCodecUserConfig( *p_restart_output = true; } - if (*p_restart_input || *p_restart_output) *p_config_updated = true; + if (*p_restart_input || *p_restart_output) { + *p_config_updated = true; + } return true; } -bool A2dpCodecConfig::codecConfigIsValid( - const btav_a2dp_codec_config_t& codec_config) { +bool A2dpCodecConfig::codecConfigIsValid(const btav_a2dp_codec_config_t& codec_config) { return (codec_config.codec_type < BTAV_A2DP_CODEC_INDEX_MAX) && (codec_config.sample_rate != BTAV_A2DP_CODEC_SAMPLE_RATE_NONE) && - (codec_config.bits_per_sample != - BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE) && + (codec_config.bits_per_sample != BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE) && (codec_config.channel_mode != BTAV_A2DP_CODEC_CHANNEL_MODE_NONE); } -std::string A2dpCodecConfig::codecConfig2Str( - const btav_a2dp_codec_config_t& codec_config) { +std::string A2dpCodecConfig::codecConfig2Str(const btav_a2dp_codec_config_t& codec_config) { std::string result; - if (!codecConfigIsValid(codec_config)) return "Invalid"; + if (!codecConfigIsValid(codec_config)) { + return "Invalid"; + } result.append("Rate="); result.append(codecSampleRate2Str(codec_config.sample_rate)); @@ -433,32 +410,43 @@ std::string A2dpCodecConfig::codecConfig2Str( return result; } -std::string A2dpCodecConfig::codecSampleRate2Str( - btav_a2dp_codec_sample_rate_t codec_sample_rate) { +std::string A2dpCodecConfig::codecSampleRate2Str(btav_a2dp_codec_sample_rate_t codec_sample_rate) { std::string result; if (codec_sample_rate & BTAV_A2DP_CODEC_SAMPLE_RATE_44100) { - if (!result.empty()) result += "|"; + if (!result.empty()) { + result += "|"; + } result += "44100"; } if (codec_sample_rate & BTAV_A2DP_CODEC_SAMPLE_RATE_48000) { - if (!result.empty()) result += "|"; + if (!result.empty()) { + result += "|"; + } result += "48000"; } if (codec_sample_rate & BTAV_A2DP_CODEC_SAMPLE_RATE_88200) { - if (!result.empty()) result += "|"; + if (!result.empty()) { + result += "|"; + } result += "88200"; } if (codec_sample_rate & BTAV_A2DP_CODEC_SAMPLE_RATE_96000) { - if (!result.empty()) result += "|"; + if (!result.empty()) { + result += "|"; + } result += "96000"; } if (codec_sample_rate & BTAV_A2DP_CODEC_SAMPLE_RATE_176400) { - if (!result.empty()) result += "|"; + if (!result.empty()) { + result += "|"; + } result += "176400"; } if (codec_sample_rate & BTAV_A2DP_CODEC_SAMPLE_RATE_192000) { - if (!result.empty()) result += "|"; + if (!result.empty()) { + result += "|"; + } result += "192000"; } if (result.empty()) { @@ -471,19 +459,25 @@ std::string A2dpCodecConfig::codecSampleRate2Str( } std::string A2dpCodecConfig::codecBitsPerSample2Str( - btav_a2dp_codec_bits_per_sample_t codec_bits_per_sample) { + btav_a2dp_codec_bits_per_sample_t codec_bits_per_sample) { std::string result; if (codec_bits_per_sample & BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16) { - if (!result.empty()) result += "|"; + if (!result.empty()) { + result += "|"; + } result += "16"; } if (codec_bits_per_sample & BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24) { - if (!result.empty()) result += "|"; + if (!result.empty()) { + result += "|"; + } result += "24"; } if (codec_bits_per_sample & BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32) { - if (!result.empty()) result += "|"; + if (!result.empty()) { + result += "|"; + } result += "32"; } if (result.empty()) { @@ -496,15 +490,19 @@ std::string A2dpCodecConfig::codecBitsPerSample2Str( } std::string A2dpCodecConfig::codecChannelMode2Str( - btav_a2dp_codec_channel_mode_t codec_channel_mode) { + btav_a2dp_codec_channel_mode_t codec_channel_mode) { std::string result; if (codec_channel_mode & BTAV_A2DP_CODEC_CHANNEL_MODE_MONO) { - if (!result.empty()) result += "|"; + if (!result.empty()) { + result += "|"; + } result += "MONO"; } if (codec_channel_mode & BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO) { - if (!result.empty()) result += "|"; + if (!result.empty()) { + result += "|"; + } result += "STEREO"; } if (result.empty()) { @@ -547,14 +545,12 @@ int A2DP_IotGetPeerSinkCodecType(const uint8_t* p_codec_info) { log::verbose("codec_id = {}", codec_id); log::verbose("vendor_id = {:x}", vendor_id); - if (codec_id == A2DP_APTX_CODEC_ID_BLUETOOTH && - vendor_id == A2DP_APTX_VENDOR_ID) { + if (codec_id == A2DP_APTX_CODEC_ID_BLUETOOTH && vendor_id == A2DP_APTX_VENDOR_ID) { peer_codec_type = IOT_CONF_VAL_A2DP_CODECTYPE_APTX; } else if (codec_id == A2DP_APTX_HD_CODEC_ID_BLUETOOTH && vendor_id == A2DP_APTX_HD_VENDOR_ID) { peer_codec_type = IOT_CONF_VAL_A2DP_CODECTYPE_APTXHD; - } else if (codec_id == A2DP_LDAC_CODEC_ID && - vendor_id == A2DP_LDAC_VENDOR_ID) { + } else if (codec_id == A2DP_LDAC_CODEC_ID && vendor_id == A2DP_LDAC_VENDOR_ID) { peer_codec_type = IOT_CONF_VAL_A2DP_CODECTYPE_LDAC; } break; @@ -575,19 +571,20 @@ int A2DP_IotGetPeerSinkCodecType(const uint8_t* p_codec_info) { // If |lhs| and |rhs| have same priority, the unique codec index is used // as a tie-breaker: larger codec index value means higher priority. // -static bool compare_codec_priority(const A2dpCodecConfig* lhs, - const A2dpCodecConfig* rhs) { - if (lhs->codecPriority() > rhs->codecPriority()) return true; - if (lhs->codecPriority() < rhs->codecPriority()) return false; - return (lhs->codecIndex() > rhs->codecIndex()); +static bool compare_codec_priority(const A2dpCodecConfig* lhs, const A2dpCodecConfig* rhs) { + if (lhs->codecPriority() > rhs->codecPriority()) { + return true; + } + if (lhs->codecPriority() < rhs->codecPriority()) { + return false; + } + return lhs->codecIndex() > rhs->codecIndex(); } -A2dpCodecs::A2dpCodecs( - const std::vector& codec_priorities) +A2dpCodecs::A2dpCodecs(const std::vector& codec_priorities) : current_codec_config_(nullptr) { for (auto config : codec_priorities) { - codec_priorities_.insert( - std::make_pair(config.codec_type, config.codec_priority)); + codec_priorities_.insert(std::make_pair(config.codec_type, config.codec_priority)); } } @@ -606,16 +603,13 @@ bool A2dpCodecs::init() { log::info(""); std::lock_guard lock(codec_mutex_); - bool opus_enabled = - osi_property_get_bool("persist.bluetooth.opus.enabled", false); + bool opus_enabled = osi_property_get_bool("persist.bluetooth.opus.enabled", false); for (int i = BTAV_A2DP_CODEC_INDEX_MIN; i < BTAV_A2DP_CODEC_INDEX_MAX; i++) { - btav_a2dp_codec_index_t codec_index = - static_cast(i); + btav_a2dp_codec_index_t codec_index = static_cast(i); // Select the codec priority if explicitly configured - btav_a2dp_codec_priority_t codec_priority = - BTAV_A2DP_CODEC_PRIORITY_DEFAULT; + btav_a2dp_codec_priority_t codec_priority = BTAV_A2DP_CODEC_PRIORITY_DEFAULT; auto cp_iter = codec_priorities_.find(codec_index); if (cp_iter != codec_priorities_.end()) { codec_priority = cp_iter->second; @@ -637,13 +631,13 @@ bool A2dpCodecs::init() { log::info("OPUS codec disabled, updated priority to {}", codec_priority); } - A2dpCodecConfig* codec_config = - A2dpCodecConfig::createCodec(codec_index, codec_priority); - if (codec_config == nullptr) continue; + A2dpCodecConfig* codec_config = A2dpCodecConfig::createCodec(codec_index, codec_priority); + if (codec_config == nullptr) { + continue; + } if (codec_priority != BTAV_A2DP_CODEC_PRIORITY_DEFAULT) { - log::info("updated {} codec priority to {}", codec_config->name(), - codec_priority); + log::info("updated {} codec priority to {}", codec_config->name(), codec_priority); } // Test if the codec is disabled @@ -667,49 +661,55 @@ bool A2dpCodecs::init() { log::error("no Source codecs were initialized"); } else { for (auto iter : ordered_source_codecs_) { - log::info("initialized Source codec {}, idx {}", iter->name(), - iter->codecIndex()); + log::info("initialized Source codec {}, idx {}", iter->name(), iter->codecIndex()); } } if (ordered_sink_codecs_.empty()) { log::error("no Sink codecs were initialized"); } else { for (auto iter : ordered_sink_codecs_) { - log::info("initialized Sink codec {}, idx {}", iter->name(), - iter->codecIndex()); + log::info("initialized Sink codec {}, idx {}", iter->name(), iter->codecIndex()); } } - return (!ordered_source_codecs_.empty() && !ordered_sink_codecs_.empty()); + return !ordered_source_codecs_.empty() && !ordered_sink_codecs_.empty(); } -A2dpCodecConfig* A2dpCodecs::findSourceCodecConfig( - const uint8_t* p_codec_info) { +A2dpCodecConfig* A2dpCodecs::findSourceCodecConfig(const uint8_t* p_codec_info) { std::lock_guard lock(codec_mutex_); btav_a2dp_codec_index_t codec_index = A2DP_SourceCodecIndex(p_codec_info); - if (codec_index == BTAV_A2DP_CODEC_INDEX_MAX) return nullptr; + if (codec_index == BTAV_A2DP_CODEC_INDEX_MAX) { + return nullptr; + } auto iter = indexed_codecs_.find(codec_index); - if (iter == indexed_codecs_.end()) return nullptr; + if (iter == indexed_codecs_.end()) { + return nullptr; + } return iter->second; } -A2dpCodecConfig* A2dpCodecs::findSourceCodecConfig( - btav_a2dp_codec_index_t codec_index) { +A2dpCodecConfig* A2dpCodecs::findSourceCodecConfig(btav_a2dp_codec_index_t codec_index) { std::lock_guard lock(codec_mutex_); auto iter = indexed_codecs_.find(codec_index); - if (iter == indexed_codecs_.end()) return nullptr; + if (iter == indexed_codecs_.end()) { + return nullptr; + } return iter->second; } A2dpCodecConfig* A2dpCodecs::findSinkCodecConfig(const uint8_t* p_codec_info) { std::lock_guard lock(codec_mutex_); btav_a2dp_codec_index_t codec_index = A2DP_SinkCodecIndex(p_codec_info); - if (codec_index == BTAV_A2DP_CODEC_INDEX_MAX) return nullptr; + if (codec_index == BTAV_A2DP_CODEC_INDEX_MAX) { + return nullptr; + } auto iter = indexed_codecs_.find(codec_index); - if (iter == indexed_codecs_.end()) return nullptr; + if (iter == indexed_codecs_.end()) { + return nullptr; + } return iter->second; } @@ -718,15 +718,14 @@ bool A2dpCodecs::isSupportedCodec(btav_a2dp_codec_index_t codec_index) { return indexed_codecs_.find(codec_index) != indexed_codecs_.end(); } -bool A2dpCodecs::setCodecConfig(const uint8_t* p_peer_codec_info, - bool is_capability, - uint8_t* p_result_codec_config, - bool select_current_codec) { +bool A2dpCodecs::setCodecConfig(const uint8_t* p_peer_codec_info, bool is_capability, + uint8_t* p_result_codec_config, bool select_current_codec) { std::lock_guard lock(codec_mutex_); A2dpCodecConfig* a2dp_codec_config = findSourceCodecConfig(p_peer_codec_info); - if (a2dp_codec_config == nullptr) return false; - if (!a2dp_codec_config->setCodecConfig(p_peer_codec_info, is_capability, - p_result_codec_config)) { + if (a2dp_codec_config == nullptr) { + return false; + } + if (!a2dp_codec_config->setCodecConfig(p_peer_codec_info, is_capability, p_result_codec_config)) { return false; } if (select_current_codec) { @@ -735,15 +734,14 @@ bool A2dpCodecs::setCodecConfig(const uint8_t* p_peer_codec_info, return true; } -bool A2dpCodecs::setSinkCodecConfig(const uint8_t* p_peer_codec_info, - bool is_capability, - uint8_t* p_result_codec_config, - bool select_current_codec) { +bool A2dpCodecs::setSinkCodecConfig(const uint8_t* p_peer_codec_info, bool is_capability, + uint8_t* p_result_codec_config, bool select_current_codec) { std::lock_guard lock(codec_mutex_); A2dpCodecConfig* a2dp_codec_config = findSinkCodecConfig(p_peer_codec_info); - if (a2dp_codec_config == nullptr) return false; - if (!a2dp_codec_config->setCodecConfig(p_peer_codec_info, is_capability, - p_result_codec_config)) { + if (a2dp_codec_config == nullptr) { + return false; + } + if (!a2dp_codec_config->setCodecConfig(p_peer_codec_info, is_capability, p_result_codec_config)) { return false; } if (select_current_codec) { @@ -752,11 +750,11 @@ bool A2dpCodecs::setSinkCodecConfig(const uint8_t* p_peer_codec_info, return true; } -bool A2dpCodecs::setCodecUserConfig( - const btav_a2dp_codec_config_t& codec_user_config, - const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params, - const uint8_t* p_peer_sink_capabilities, uint8_t* p_result_codec_config, - bool* p_restart_input, bool* p_restart_output, bool* p_config_updated) { +bool A2dpCodecs::setCodecUserConfig(const btav_a2dp_codec_config_t& codec_user_config, + const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params, + const uint8_t* p_peer_sink_capabilities, + uint8_t* p_result_codec_config, bool* p_restart_input, + bool* p_restart_output, bool* p_config_updated) { std::lock_guard lock(codec_mutex_); btav_a2dp_codec_config_t codec_audio_config; A2dpCodecConfig* a2dp_codec_config = nullptr; @@ -769,20 +767,23 @@ bool A2dpCodecs::setCodecUserConfig( if (codec_user_config.codec_type < BTAV_A2DP_CODEC_INDEX_MAX) { auto iter = indexed_codecs_.find(codec_user_config.codec_type); - if (iter == indexed_codecs_.end()) goto fail; + if (iter == indexed_codecs_.end()) { + goto fail; + } a2dp_codec_config = iter->second; } else { // Update the default codec a2dp_codec_config = current_codec_config_; } - if (a2dp_codec_config == nullptr) goto fail; + if (a2dp_codec_config == nullptr) { + goto fail; + } // Reuse the existing codec audio config codec_audio_config = a2dp_codec_config->getCodecAudioConfig(); - if (!a2dp_codec_config->setCodecUserConfig( - codec_user_config, codec_audio_config, p_peer_params, - p_peer_sink_capabilities, true, p_result_codec_config, - p_restart_input, p_restart_output, p_config_updated)) { + if (!a2dp_codec_config->setCodecUserConfig(codec_user_config, codec_audio_config, p_peer_params, + p_peer_sink_capabilities, true, p_result_codec_config, + p_restart_input, p_restart_output, p_config_updated)) { goto fail; } @@ -790,8 +791,7 @@ bool A2dpCodecs::setCodecUserConfig( // if a new codec needs to be selected. do { // Update the codec priority - btav_a2dp_codec_priority_t old_priority = - a2dp_codec_config->codecPriority(); + btav_a2dp_codec_priority_t old_priority = a2dp_codec_config->codecPriority(); btav_a2dp_codec_priority_t new_priority = codec_user_config.codec_priority; a2dp_codec_config->setCodecPriority(new_priority); // Get the actual (recomputed) priority @@ -807,7 +807,9 @@ bool A2dpCodecs::setCodecUserConfig( // Check if the priority of the current codec was updated if (a2dp_codec_config == last_codec_config) { - if (old_priority == new_priority) break; // No change in priority + if (old_priority == new_priority) { + break; // No change in priority + } *p_config_updated = true; if (new_priority < old_priority) { @@ -821,8 +823,7 @@ bool A2dpCodecs::setCodecUserConfig( if (new_priority <= old_priority) { // No change in priority, or the priority has become lower. // This wasn't the current codec, so we shouldn't select a new codec. - if (*p_restart_input || *p_restart_output || - (old_priority != new_priority)) { + if (*p_restart_input || *p_restart_output || (old_priority != new_priority)) { *p_config_updated = true; } *p_restart_input = false; @@ -842,11 +843,12 @@ bool A2dpCodecs::setCodecUserConfig( } while (false); ordered_source_codecs_.sort(compare_codec_priority); - if (*p_restart_input || *p_restart_output) *p_config_updated = true; + if (*p_restart_input || *p_restart_output) { + *p_config_updated = true; + } - log::info( - "Configured: restart_input = {} restart_output = {} config_updated = {}", - *p_restart_input, *p_restart_output, *p_config_updated); + log::info("Configured: restart_input = {} restart_output = {} config_updated = {}", + *p_restart_input, *p_restart_output, *p_config_updated); return true; @@ -855,37 +857,37 @@ fail: return false; } -bool A2dpCodecs::setCodecAudioConfig( - const btav_a2dp_codec_config_t& codec_audio_config, - const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params, - const uint8_t* p_peer_sink_capabilities, uint8_t* p_result_codec_config, - bool* p_restart_output, bool* p_config_updated) { +bool A2dpCodecs::setCodecAudioConfig(const btav_a2dp_codec_config_t& codec_audio_config, + const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params, + const uint8_t* p_peer_sink_capabilities, + uint8_t* p_result_codec_config, bool* p_restart_output, + bool* p_config_updated) { std::lock_guard lock(codec_mutex_); btav_a2dp_codec_config_t codec_user_config; A2dpCodecConfig* a2dp_codec_config = current_codec_config_; *p_restart_output = false; *p_config_updated = false; - if (a2dp_codec_config == nullptr) return false; + if (a2dp_codec_config == nullptr) { + return false; + } // Reuse the existing codec user config codec_user_config = a2dp_codec_config->getCodecUserConfig(); bool restart_input = false; // Flag ignored - input was just restarted - if (!a2dp_codec_config->setCodecUserConfig( - codec_user_config, codec_audio_config, p_peer_params, - p_peer_sink_capabilities, true, p_result_codec_config, &restart_input, - p_restart_output, p_config_updated)) { + if (!a2dp_codec_config->setCodecUserConfig(codec_user_config, codec_audio_config, p_peer_params, + p_peer_sink_capabilities, true, p_result_codec_config, + &restart_input, p_restart_output, p_config_updated)) { return false; } return true; } -bool A2dpCodecs::setCodecOtaConfig( - const uint8_t* p_ota_codec_config, - const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params, - uint8_t* p_result_codec_config, bool* p_restart_input, - bool* p_restart_output, bool* p_config_updated) { +bool A2dpCodecs::setCodecOtaConfig(const uint8_t* p_ota_codec_config, + const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params, + uint8_t* p_result_codec_config, bool* p_restart_input, + bool* p_restart_output, bool* p_config_updated) { std::lock_guard lock(codec_mutex_); btav_a2dp_codec_index_t codec_type; btav_a2dp_codec_config_t codec_user_config; @@ -902,9 +904,9 @@ bool A2dpCodecs::setCodecOtaConfig( codec_user_config = current_codec_config_->getCodecUserConfig(); if (!A2dpCodecConfig::isCodecConfigEmpty(codec_user_config)) { log::warn( - "ignoring peer OTA configuration for codec {}: existing user " - "configuration for current codec {}", - A2DP_CodecName(p_ota_codec_config), current_codec_config_->name()); + "ignoring peer OTA configuration for codec {}: existing user " + "configuration for current codec {}", + A2DP_CodecName(p_ota_codec_config), current_codec_config_->name()); goto fail; } } @@ -925,23 +927,24 @@ bool A2dpCodecs::setCodecOtaConfig( } a2dp_codec_config = iter->second; } - if (a2dp_codec_config == nullptr) goto fail; + if (a2dp_codec_config == nullptr) { + goto fail; + } codec_user_config = a2dp_codec_config->getCodecUserConfig(); if (!A2dpCodecConfig::isCodecConfigEmpty(codec_user_config)) { log::warn( - "ignoring peer OTA configuration for codec {}: existing user " - "configuration for same codec", - A2DP_CodecName(p_ota_codec_config)); + "ignoring peer OTA configuration for codec {}: existing user " + "configuration for same codec", + A2DP_CodecName(p_ota_codec_config)); goto fail; } current_codec_config_ = a2dp_codec_config; // Reuse the existing codec user config and codec audio config codec_audio_config = a2dp_codec_config->getCodecAudioConfig(); - if (!a2dp_codec_config->setCodecUserConfig( - codec_user_config, codec_audio_config, p_peer_params, - p_ota_codec_config, false, p_result_codec_config, p_restart_input, - p_restart_output, p_config_updated)) { + if (!a2dp_codec_config->setCodecUserConfig(codec_user_config, codec_audio_config, p_peer_params, + p_ota_codec_config, false, p_result_codec_config, + p_restart_input, p_restart_output, p_config_updated)) { log::warn("cannot set codec configuration for peer OTA codec {}", A2DP_CodecName(p_ota_codec_config)); goto fail; @@ -949,7 +952,9 @@ bool A2dpCodecs::setCodecOtaConfig( log::assert_that(current_codec_config_ != nullptr, "assert failed: current_codec_config_ != nullptr"); - if (*p_restart_input || *p_restart_output) *p_config_updated = true; + if (*p_restart_input || *p_restart_output) { + *p_config_updated = true; + } return true; @@ -958,41 +963,43 @@ fail: return false; } -bool A2dpCodecs::setPeerSinkCodecCapabilities( - const uint8_t* p_peer_codec_capabilities) { +bool A2dpCodecs::setPeerSinkCodecCapabilities(const uint8_t* p_peer_codec_capabilities) { std::lock_guard lock(codec_mutex_); - A2dpCodecConfig* a2dp_codec_config = - findSourceCodecConfig(p_peer_codec_capabilities); - if (a2dp_codec_config == nullptr) return false; + A2dpCodecConfig* a2dp_codec_config = findSourceCodecConfig(p_peer_codec_capabilities); + if (a2dp_codec_config == nullptr) { + return false; + } // Bypass the validation for codecs that are offloaded: // the stack does not need to know about the peer capabilities, // since the validation and selection will be performed by the // bluetooth audio HAL for offloaded codecs. - if (!::bluetooth::audio::a2dp::provider::supports_codec( - a2dp_codec_config->codecIndex()) && - !A2DP_IsPeerSinkCodecValid(p_peer_codec_capabilities)) + if (!::bluetooth::audio::a2dp::provider::supports_codec(a2dp_codec_config->codecIndex()) && + !A2DP_IsPeerSinkCodecValid(p_peer_codec_capabilities)) { return false; + } return a2dp_codec_config->setPeerCodecCapabilities(p_peer_codec_capabilities); } -bool A2dpCodecs::setPeerSourceCodecCapabilities( - const uint8_t* p_peer_codec_capabilities) { +bool A2dpCodecs::setPeerSourceCodecCapabilities(const uint8_t* p_peer_codec_capabilities) { std::lock_guard lock(codec_mutex_); - if (!A2DP_IsPeerSourceCodecValid(p_peer_codec_capabilities)) return false; - A2dpCodecConfig* a2dp_codec_config = - findSinkCodecConfig(p_peer_codec_capabilities); - if (a2dp_codec_config == nullptr) return false; + if (!A2DP_IsPeerSourceCodecValid(p_peer_codec_capabilities)) { + return false; + } + A2dpCodecConfig* a2dp_codec_config = findSinkCodecConfig(p_peer_codec_capabilities); + if (a2dp_codec_config == nullptr) { + return false; + } return a2dp_codec_config->setPeerCodecCapabilities(p_peer_codec_capabilities); } bool A2dpCodecs::getCodecConfigAndCapabilities( - btav_a2dp_codec_config_t* p_codec_config, - std::vector* p_codecs_local_capabilities, - std::vector* p_codecs_selectable_capabilities) { + btav_a2dp_codec_config_t* p_codec_config, + std::vector* p_codecs_local_capabilities, + std::vector* p_codecs_selectable_capabilities) { std::lock_guard lock(codec_mutex_); if (current_codec_config_ != nullptr) { @@ -1011,12 +1018,10 @@ bool A2dpCodecs::getCodecConfigAndCapabilities( codecs_capabilities.clear(); for (auto codec : orderedSourceCodecs()) { - btav_a2dp_codec_config_t codec_capability = - codec->getCodecSelectableCapability(); + btav_a2dp_codec_config_t codec_capability = codec->getCodecSelectableCapability(); // Don't add entries that cannot be used if ((codec_capability.sample_rate == BTAV_A2DP_CODEC_SAMPLE_RATE_NONE) || - (codec_capability.bits_per_sample == - BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE) || + (codec_capability.bits_per_sample == BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE) || (codec_capability.channel_mode == BTAV_A2DP_CODEC_CHANNEL_MODE_NONE)) { continue; } @@ -1164,15 +1169,14 @@ bool A2DP_IsPeerSourceCodecSupported(const uint8_t* p_codec_info) { return false; } -void A2DP_InitDefaultCodec(uint8_t* p_codec_info) { - A2DP_InitDefaultCodecSbc(p_codec_info); -} +void A2DP_InitDefaultCodec(uint8_t* p_codec_info) { A2DP_InitDefaultCodecSbc(p_codec_info); } -bool A2DP_UsesRtpHeader(bool content_protection_enabled, - const uint8_t* p_codec_info) { +bool A2DP_UsesRtpHeader(bool content_protection_enabled, const uint8_t* p_codec_info) { tA2DP_CODEC_TYPE codec_type = A2DP_GetCodecType(p_codec_info); - if (codec_type != A2DP_MEDIA_CT_NON_A2DP) return true; + if (codec_type != A2DP_MEDIA_CT_NON_A2DP) { + return true; + } #if !defined(EXCLUDE_NONSTANDARD_CODECS) return A2DP_VendorUsesRtpHeader(content_protection_enabled, p_codec_info); @@ -1206,12 +1210,13 @@ const char* A2DP_CodecName(const uint8_t* p_codec_info) { return "UNKNOWN CODEC"; } -bool A2DP_CodecTypeEquals(const uint8_t* p_codec_info_a, - const uint8_t* p_codec_info_b) { +bool A2DP_CodecTypeEquals(const uint8_t* p_codec_info_a, const uint8_t* p_codec_info_b) { tA2DP_CODEC_TYPE codec_type_a = A2DP_GetCodecType(p_codec_info_a); tA2DP_CODEC_TYPE codec_type_b = A2DP_GetCodecType(p_codec_info_b); - if (codec_type_a != codec_type_b) return false; + if (codec_type_a != codec_type_b) { + return false; + } switch (codec_type_a) { case A2DP_MEDIA_CT_SBC: @@ -1230,12 +1235,13 @@ bool A2DP_CodecTypeEquals(const uint8_t* p_codec_info_a, return false; } -bool A2DP_CodecEquals(const uint8_t* p_codec_info_a, - const uint8_t* p_codec_info_b) { +bool A2DP_CodecEquals(const uint8_t* p_codec_info_a, const uint8_t* p_codec_info_b) { tA2DP_CODEC_TYPE codec_type_a = A2DP_GetCodecType(p_codec_info_a); tA2DP_CODEC_TYPE codec_type_b = A2DP_GetCodecType(p_codec_info_b); - if (codec_type_a != codec_type_b) return false; + if (codec_type_a != codec_type_b) { + return false; + } switch (codec_type_a) { case A2DP_MEDIA_CT_SBC: @@ -1355,8 +1361,7 @@ bool A2DP_GetPacketTimestamp(const uint8_t* p_codec_info, const uint8_t* p_data, return false; } -bool A2DP_BuildCodecHeader(const uint8_t* p_codec_info, BT_HDR* p_buf, - uint16_t frames_per_packet) { +bool A2DP_BuildCodecHeader(const uint8_t* p_codec_info, BT_HDR* p_buf, uint16_t frames_per_packet) { tA2DP_CODEC_TYPE codec_type = A2DP_GetCodecType(p_codec_info); switch (codec_type) { @@ -1366,8 +1371,7 @@ bool A2DP_BuildCodecHeader(const uint8_t* p_codec_info, BT_HDR* p_buf, case A2DP_MEDIA_CT_AAC: return A2DP_BuildCodecHeaderAac(p_codec_info, p_buf, frames_per_packet); case A2DP_MEDIA_CT_NON_A2DP: - return A2DP_VendorBuildCodecHeader(p_codec_info, p_buf, - frames_per_packet); + return A2DP_VendorBuildCodecHeader(p_codec_info, p_buf, frames_per_packet); #endif default: break; @@ -1377,12 +1381,10 @@ bool A2DP_BuildCodecHeader(const uint8_t* p_codec_info, BT_HDR* p_buf, return false; } -const tA2DP_ENCODER_INTERFACE* A2DP_GetEncoderInterface( - const uint8_t* p_codec_info) { +const tA2DP_ENCODER_INTERFACE* A2DP_GetEncoderInterface(const uint8_t* p_codec_info) { tA2DP_CODEC_TYPE codec_type = A2DP_GetCodecType(p_codec_info); - if (::bluetooth::audio::a2dp::provider::supports_codec( - A2DP_SourceCodecIndex(p_codec_info))) { + if (::bluetooth::audio::a2dp::provider::supports_codec(A2DP_SourceCodecIndex(p_codec_info))) { return A2DP_GetEncoderInterfaceExt(p_codec_info); } @@ -1403,8 +1405,7 @@ const tA2DP_ENCODER_INTERFACE* A2DP_GetEncoderInterface( return NULL; } -const tA2DP_DECODER_INTERFACE* A2DP_GetDecoderInterface( - const uint8_t* p_codec_info) { +const tA2DP_DECODER_INTERFACE* A2DP_GetDecoderInterface(const uint8_t* p_codec_info) { tA2DP_CODEC_TYPE codec_type = A2DP_GetCodecType(p_codec_info); switch (codec_type) { @@ -1447,8 +1448,7 @@ bool A2DP_AdjustCodec(uint8_t* p_codec_info) { btav_a2dp_codec_index_t A2DP_SourceCodecIndex(const uint8_t* p_codec_info) { tA2DP_CODEC_TYPE codec_type = A2DP_GetCodecType(p_codec_info); - auto ext_codec_index = - bluetooth::audio::a2dp::provider::source_codec_index(p_codec_info); + auto ext_codec_index = bluetooth::audio::a2dp::provider::source_codec_index(p_codec_info); if (ext_codec_index.has_value()) { return ext_codec_index.value(); } @@ -1473,8 +1473,7 @@ btav_a2dp_codec_index_t A2DP_SourceCodecIndex(const uint8_t* p_codec_info) { btav_a2dp_codec_index_t A2DP_SinkCodecIndex(const uint8_t* p_codec_info) { tA2DP_CODEC_TYPE codec_type = A2DP_GetCodecType(p_codec_info); - auto ext_codec_index = - bluetooth::audio::a2dp::provider::sink_codec_index(p_codec_info); + auto ext_codec_index = bluetooth::audio::a2dp::provider::sink_codec_index(p_codec_info); if (ext_codec_index.has_value()) { return ext_codec_index.value(); } @@ -1501,8 +1500,7 @@ const char* A2DP_CodecIndexStr(btav_a2dp_codec_index_t codec_index) { codec_index < BTAV_A2DP_CODEC_INDEX_SOURCE_EXT_MAX) || (codec_index >= BTAV_A2DP_CODEC_INDEX_SINK_EXT_MIN && codec_index < BTAV_A2DP_CODEC_INDEX_SINK_EXT_MAX)) { - auto codec_index_str = - bluetooth::audio::a2dp::provider::codec_index_str(codec_index); + auto codec_index_str = bluetooth::audio::a2dp::provider::codec_index_str(codec_index); if (codec_index_str.has_value()) { return codec_index_str.value(); } @@ -1524,15 +1522,15 @@ const char* A2DP_CodecIndexStr(btav_a2dp_codec_index_t codec_index) { } #if !defined(EXCLUDE_NONSTANDARD_CODECS) - if (codec_index < BTAV_A2DP_CODEC_INDEX_MAX) + if (codec_index < BTAV_A2DP_CODEC_INDEX_MAX) { return A2DP_VendorCodecIndexStr(codec_index); + } #endif return "UNKNOWN CODEC INDEX"; } -bool A2DP_InitCodecConfig(btav_a2dp_codec_index_t codec_index, - AvdtpSepConfig* p_cfg) { +bool A2DP_InitCodecConfig(btav_a2dp_codec_index_t codec_index, AvdtpSepConfig* p_cfg) { log::verbose("codec {}", A2DP_CodecIndexStr(codec_index)); /* Default: no content protection info */ @@ -1540,8 +1538,8 @@ bool A2DP_InitCodecConfig(btav_a2dp_codec_index_t codec_index, p_cfg->protect_info[0] = 0; if (::bluetooth::audio::a2dp::provider::supports_codec(codec_index)) { - return ::bluetooth::audio::a2dp::provider::codec_info( - codec_index, nullptr, p_cfg->codec_info, nullptr); + return ::bluetooth::audio::a2dp::provider::codec_info(codec_index, nullptr, p_cfg->codec_info, + nullptr); } switch (codec_index) { @@ -1560,8 +1558,9 @@ bool A2DP_InitCodecConfig(btav_a2dp_codec_index_t codec_index, } #if !defined(EXCLUDE_NONSTANDARD_CODECS) - if (codec_index < BTAV_A2DP_CODEC_INDEX_MAX) + if (codec_index < BTAV_A2DP_CODEC_INDEX_MAX) { return A2DP_VendorInitCodecConfig(codec_index, p_cfg); + } #endif return false; @@ -1587,9 +1586,6 @@ std::string A2DP_CodecInfoString(const uint8_t* p_codec_info) { } int A2DP_GetEecoderEffectiveFrameSize(const uint8_t* p_codec_info) { - const tA2DP_ENCODER_INTERFACE* a2dp_encoder_interface = - A2DP_GetEncoderInterface(p_codec_info); - return a2dp_encoder_interface - ? a2dp_encoder_interface->get_effective_frame_size() - : 0; + const tA2DP_ENCODER_INTERFACE* a2dp_encoder_interface = A2DP_GetEncoderInterface(p_codec_info); + return a2dp_encoder_interface ? a2dp_encoder_interface->get_effective_frame_size() : 0; } diff --git a/system/stack/a2dp/a2dp_ext.cc b/system/stack/a2dp/a2dp_ext.cc index b377632fc0e..5238ec4b0e6 100644 --- a/system/stack/a2dp/a2dp_ext.cc +++ b/system/stack/a2dp/a2dp_ext.cc @@ -27,29 +27,24 @@ using namespace bluetooth; static uint64_t codec_id(btav_a2dp_codec_index_t codec_index) { uint64_t id = 0; - auto result = ::bluetooth::audio::a2dp::provider::codec_info( - codec_index, &id, nullptr, nullptr); + auto result = ::bluetooth::audio::a2dp::provider::codec_info(codec_index, &id, nullptr, nullptr); log::assert_that(result, "provider::codec_info unexpectdly failed"); return id; } -A2dpCodecConfigExt::A2dpCodecConfigExt(btav_a2dp_codec_index_t codec_index, - bool is_source) - : A2dpCodecConfig( - codec_index, codec_id(codec_index), - bluetooth::audio::a2dp::provider::codec_index_str(codec_index) - .value(), - BTAV_A2DP_CODEC_PRIORITY_DEFAULT), +A2dpCodecConfigExt::A2dpCodecConfigExt(btav_a2dp_codec_index_t codec_index, bool is_source) + : A2dpCodecConfig(codec_index, codec_id(codec_index), + bluetooth::audio::a2dp::provider::codec_index_str(codec_index).value(), + BTAV_A2DP_CODEC_PRIORITY_DEFAULT), is_source_(is_source) { // Load the local capabilities from the provider info. auto result = ::bluetooth::audio::a2dp::provider::codec_info( - codec_index, nullptr, ota_codec_config_, &codec_capability_); + codec_index, nullptr, ota_codec_config_, &codec_capability_); log::assert_that(result, "provider::codec_info unexpectdly failed"); codec_selectable_capability_ = codec_capability_; } -bool A2dpCodecConfigExt::setCodecConfig(const uint8_t* p_peer_codec_info, - bool is_capability, +bool A2dpCodecConfigExt::setCodecConfig(const uint8_t* p_peer_codec_info, bool is_capability, uint8_t* p_result_codec_config) { // Call get_a2dp_config to recompute best capabilities. // This method need to update codec_capability_, codec_config_, @@ -57,14 +52,13 @@ bool A2dpCodecConfigExt::setCodecConfig(const uint8_t* p_peer_codec_info, // peer_codec_info. using namespace bluetooth::audio::a2dp; provider::a2dp_remote_capabilities capabilities = { - .seid = 0, // the SEID does not matter here. - .capabilities = p_peer_codec_info, + .seid = 0, // the SEID does not matter here. + .capabilities = p_peer_codec_info, }; auto result = provider::get_a2dp_configuration( - RawAddress::kEmpty, - std::vector{capabilities}, - codec_user_config_); + RawAddress::kEmpty, std::vector{capabilities}, + codec_user_config_); if (!result.has_value()) { log::error("Failed to set a configuration for {}", name_); return false; @@ -77,8 +71,7 @@ bool A2dpCodecConfigExt::setCodecConfig(const uint8_t* p_peer_codec_info, return true; } -bool A2dpCodecConfigExt::setPeerCodecCapabilities( - const uint8_t* p_peer_codec_capabilities) { +bool A2dpCodecConfigExt::setPeerCodecCapabilities(const uint8_t* p_peer_codec_capabilities) { // setPeerCodecCapabilities updates the selectable // capabilities in the codec config. It can be safely // ignored as providing a superset of the selectable @@ -87,16 +80,15 @@ bool A2dpCodecConfigExt::setPeerCodecCapabilities( } tA2DP_ENCODER_INTERFACE const a2dp_encoder_interface_ext = { - .encoder_init = [](const tA2DP_ENCODER_INIT_PEER_PARAMS*, A2dpCodecConfig*, - a2dp_source_read_callback_t, - a2dp_source_enqueue_callback_t) {}, - .encoder_cleanup = []() {}, - .feeding_reset = []() {}, - .feeding_flush = []() {}, - .get_encoder_interval_ms = []() { return (uint64_t)20; }, - .get_effective_frame_size = []() { return 0; }, - .send_frames = [](uint64_t) {}, - .set_transmit_queue_length = [](size_t) {}, + .encoder_init = [](const tA2DP_ENCODER_INIT_PEER_PARAMS*, A2dpCodecConfig*, + a2dp_source_read_callback_t, a2dp_source_enqueue_callback_t) {}, + .encoder_cleanup = []() {}, + .feeding_reset = []() {}, + .feeding_flush = []() {}, + .get_encoder_interval_ms = []() { return (uint64_t)20; }, + .get_effective_frame_size = []() { return 0; }, + .send_frames = [](uint64_t) {}, + .set_transmit_queue_length = [](size_t) {}, }; const tA2DP_ENCODER_INTERFACE* A2DP_GetEncoderInterfaceExt(const uint8_t*) { diff --git a/system/stack/a2dp/a2dp_int.h b/system/stack/a2dp/a2dp_int.h index 05ae3be4685..1ad0cce8f67 100644 --- a/system/stack/a2dp/a2dp_int.h +++ b/system/stack/a2dp/a2dp_int.h @@ -43,13 +43,13 @@ /* Control block used by A2DP_FindService(). */ typedef struct { - tA2DP_FIND_CBACK p_cback; /* application callback */ - tSDP_DISCOVERY_DB* p_db; /* pointer to discovery database */ - uint16_t service_uuid; /* service UUID of search */ + tA2DP_FIND_CBACK p_cback; /* application callback */ + tSDP_DISCOVERY_DB* p_db; /* pointer to discovery database */ + uint16_t service_uuid; /* service UUID of search */ } tA2DP_FIND_CB; typedef struct { - tA2DP_FIND_CB find; /* find service control block */ + tA2DP_FIND_CB find; /* find service control block */ uint16_t avdt_sdp_ver; /* AVDTP version */ } tA2DP_CB; diff --git a/system/stack/a2dp/a2dp_sbc.cc b/system/stack/a2dp/a2dp_sbc.cc index 01590955143..593503f25b9 100644 --- a/system/stack/a2dp/a2dp_sbc.cc +++ b/system/stack/a2dp/a2dp_sbc.cc @@ -55,84 +55,80 @@ typedef struct { /* SBC Source codec capabilities */ static const tA2DP_SBC_CIE a2dp_sbc_source_caps = { - (A2DP_SBC_IE_SAMP_FREQ_44), /* samp_freq */ - (A2DP_SBC_IE_CH_MD_MONO | A2DP_SBC_IE_CH_MD_JOINT), /* ch_mode */ - (A2DP_SBC_IE_BLOCKS_16 | A2DP_SBC_IE_BLOCKS_12 | A2DP_SBC_IE_BLOCKS_8 | - A2DP_SBC_IE_BLOCKS_4), /* block_len */ - A2DP_SBC_IE_SUBBAND_8, /* num_subbands */ - A2DP_SBC_IE_ALLOC_MD_L, /* alloc_method */ - A2DP_SBC_IE_MIN_BITPOOL, /* min_bitpool */ - A2DP_SBC_MAX_BITPOOL, /* max_bitpool */ - BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16 /* bits_per_sample */ + (A2DP_SBC_IE_SAMP_FREQ_44), /* samp_freq */ + (A2DP_SBC_IE_CH_MD_MONO | A2DP_SBC_IE_CH_MD_JOINT), /* ch_mode */ + (A2DP_SBC_IE_BLOCKS_16 | A2DP_SBC_IE_BLOCKS_12 | A2DP_SBC_IE_BLOCKS_8 | + A2DP_SBC_IE_BLOCKS_4), /* block_len */ + A2DP_SBC_IE_SUBBAND_8, /* num_subbands */ + A2DP_SBC_IE_ALLOC_MD_L, /* alloc_method */ + A2DP_SBC_IE_MIN_BITPOOL, /* min_bitpool */ + A2DP_SBC_MAX_BITPOOL, /* max_bitpool */ + BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16 /* bits_per_sample */ }; /* SBC Sink codec capabilities */ static const tA2DP_SBC_CIE a2dp_sbc_sink_caps = { - (A2DP_SBC_IE_SAMP_FREQ_48 | A2DP_SBC_IE_SAMP_FREQ_44), /* samp_freq */ - (A2DP_SBC_IE_CH_MD_MONO | A2DP_SBC_IE_CH_MD_STEREO | - A2DP_SBC_IE_CH_MD_JOINT | A2DP_SBC_IE_CH_MD_DUAL), /* ch_mode */ - (A2DP_SBC_IE_BLOCKS_16 | A2DP_SBC_IE_BLOCKS_12 | A2DP_SBC_IE_BLOCKS_8 | - A2DP_SBC_IE_BLOCKS_4), /* block_len */ - (A2DP_SBC_IE_SUBBAND_4 | A2DP_SBC_IE_SUBBAND_8), /* num_subbands */ - (A2DP_SBC_IE_ALLOC_MD_L | A2DP_SBC_IE_ALLOC_MD_S), /* alloc_method */ - A2DP_SBC_IE_MIN_BITPOOL, /* min_bitpool */ - A2DP_SBC_MAX_BITPOOL, /* max_bitpool */ - BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16 /* bits_per_sample */ + (A2DP_SBC_IE_SAMP_FREQ_48 | A2DP_SBC_IE_SAMP_FREQ_44), /* samp_freq */ + (A2DP_SBC_IE_CH_MD_MONO | A2DP_SBC_IE_CH_MD_STEREO | A2DP_SBC_IE_CH_MD_JOINT | + A2DP_SBC_IE_CH_MD_DUAL), /* ch_mode */ + (A2DP_SBC_IE_BLOCKS_16 | A2DP_SBC_IE_BLOCKS_12 | A2DP_SBC_IE_BLOCKS_8 | + A2DP_SBC_IE_BLOCKS_4), /* block_len */ + (A2DP_SBC_IE_SUBBAND_4 | A2DP_SBC_IE_SUBBAND_8), /* num_subbands */ + (A2DP_SBC_IE_ALLOC_MD_L | A2DP_SBC_IE_ALLOC_MD_S), /* alloc_method */ + A2DP_SBC_IE_MIN_BITPOOL, /* min_bitpool */ + A2DP_SBC_MAX_BITPOOL, /* max_bitpool */ + BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16 /* bits_per_sample */ }; /* Default SBC codec configuration */ const tA2DP_SBC_CIE a2dp_sbc_default_config = { - A2DP_SBC_IE_SAMP_FREQ_44, /* samp_freq */ - A2DP_SBC_IE_CH_MD_JOINT, /* ch_mode */ - A2DP_SBC_IE_BLOCKS_16, /* block_len */ - A2DP_SBC_IE_SUBBAND_8, /* num_subbands */ - A2DP_SBC_IE_ALLOC_MD_L, /* alloc_method */ - A2DP_SBC_IE_MIN_BITPOOL, /* min_bitpool */ - A2DP_SBC_MAX_BITPOOL, /* max_bitpool */ - BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16 /* bits_per_sample */ + A2DP_SBC_IE_SAMP_FREQ_44, /* samp_freq */ + A2DP_SBC_IE_CH_MD_JOINT, /* ch_mode */ + A2DP_SBC_IE_BLOCKS_16, /* block_len */ + A2DP_SBC_IE_SUBBAND_8, /* num_subbands */ + A2DP_SBC_IE_ALLOC_MD_L, /* alloc_method */ + A2DP_SBC_IE_MIN_BITPOOL, /* min_bitpool */ + A2DP_SBC_MAX_BITPOOL, /* max_bitpool */ + BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16 /* bits_per_sample */ }; static const tA2DP_ENCODER_INTERFACE a2dp_encoder_interface_sbc = { - a2dp_sbc_encoder_init, - a2dp_sbc_encoder_cleanup, - a2dp_sbc_feeding_reset, - a2dp_sbc_feeding_flush, - a2dp_sbc_get_encoder_interval_ms, - a2dp_sbc_get_effective_frame_size, - a2dp_sbc_send_frames, - nullptr // set_transmit_queue_length + a2dp_sbc_encoder_init, + a2dp_sbc_encoder_cleanup, + a2dp_sbc_feeding_reset, + a2dp_sbc_feeding_flush, + a2dp_sbc_get_encoder_interval_ms, + a2dp_sbc_get_effective_frame_size, + a2dp_sbc_send_frames, + nullptr // set_transmit_queue_length }; static const tA2DP_DECODER_INTERFACE a2dp_decoder_interface_sbc = { - a2dp_sbc_decoder_init, - a2dp_sbc_decoder_cleanup, - a2dp_sbc_decoder_decode_packet, - nullptr, // decoder_start - nullptr, // decoder_suspend - nullptr, // decoder_configure + a2dp_sbc_decoder_init, + a2dp_sbc_decoder_cleanup, + a2dp_sbc_decoder_decode_packet, + nullptr, // decoder_start + nullptr, // decoder_suspend + nullptr, // decoder_configure }; -static tA2DP_STATUS A2DP_CodecInfoMatchesCapabilitySbc( - const tA2DP_SBC_CIE* p_cap, const uint8_t* p_codec_info, - bool is_capability); -static void A2DP_ParseMplHeaderSbc(uint8_t* p_src, bool* p_frag, bool* p_start, - bool* p_last, uint8_t* p_num); +static tA2DP_STATUS A2DP_CodecInfoMatchesCapabilitySbc(const tA2DP_SBC_CIE* p_cap, + const uint8_t* p_codec_info, + bool is_capability); +static void A2DP_ParseMplHeaderSbc(uint8_t* p_src, bool* p_frag, bool* p_start, bool* p_last, + uint8_t* p_num); // Builds the SBC Media Codec Capabilities byte sequence beginning from the // LOSC octet. |media_type| is the media type |AVDT_MEDIA_TYPE_*|. // |p_ie| is a pointer to the SBC Codec Information Element information. // The result is stored in |p_result|. Returns A2DP_SUCCESS on success, // otherwise the corresponding A2DP error status code. -static tA2DP_STATUS A2DP_BuildInfoSbc(uint8_t media_type, - const tA2DP_SBC_CIE* p_ie, +static tA2DP_STATUS A2DP_BuildInfoSbc(uint8_t media_type, const tA2DP_SBC_CIE* p_ie, uint8_t* p_result) { - if (p_ie == NULL || p_result == NULL || - (p_ie->samp_freq & ~A2DP_SBC_IE_SAMP_FREQ_MSK) || - (p_ie->ch_mode & ~A2DP_SBC_IE_CH_MD_MSK) || - (p_ie->block_len & ~A2DP_SBC_IE_BLOCKS_MSK) || + if (p_ie == NULL || p_result == NULL || (p_ie->samp_freq & ~A2DP_SBC_IE_SAMP_FREQ_MSK) || + (p_ie->ch_mode & ~A2DP_SBC_IE_CH_MD_MSK) || (p_ie->block_len & ~A2DP_SBC_IE_BLOCKS_MSK) || (p_ie->num_subbands & ~A2DP_SBC_IE_SUBBAND_MSK) || - (p_ie->alloc_method & ~A2DP_SBC_IE_ALLOC_MD_MSK) || - (p_ie->min_bitpool > p_ie->max_bitpool) || + (p_ie->alloc_method & ~A2DP_SBC_IE_ALLOC_MD_MSK) || (p_ie->min_bitpool > p_ie->max_bitpool) || (p_ie->min_bitpool < A2DP_SBC_IE_MIN_BITPOOL) || (p_ie->min_bitpool > A2DP_SBC_IE_MAX_BITPOOL) || (p_ie->max_bitpool < A2DP_SBC_IE_MIN_BITPOOL) || @@ -162,18 +158,21 @@ static tA2DP_STATUS A2DP_BuildInfoSbc(uint8_t media_type, // codec capability. // Returns A2DP_SUCCESS on success, otherwise the corresponding A2DP error // status code. -static tA2DP_STATUS A2DP_ParseInfoSbc(tA2DP_SBC_CIE* p_ie, - const uint8_t* p_codec_info, +static tA2DP_STATUS A2DP_ParseInfoSbc(tA2DP_SBC_CIE* p_ie, const uint8_t* p_codec_info, bool is_capability) { uint8_t losc; uint8_t media_type; tA2DP_CODEC_TYPE codec_type; - if (p_ie == NULL || p_codec_info == NULL) return A2DP_INVALID_PARAMS; + if (p_ie == NULL || p_codec_info == NULL) { + return A2DP_INVALID_PARAMS; + } // Check the codec capability length losc = *p_codec_info++; - if (losc != A2DP_SBC_INFO_LEN) return A2DP_WRONG_CODEC; + if (losc != A2DP_SBC_INFO_LEN) { + return A2DP_WRONG_CODEC; + } media_type = (*p_codec_info++) >> 4; codec_type = *p_codec_info++; @@ -191,13 +190,11 @@ static tA2DP_STATUS A2DP_ParseInfoSbc(tA2DP_SBC_CIE* p_ie, p_codec_info++; p_ie->min_bitpool = *p_codec_info++; p_ie->max_bitpool = *p_codec_info++; - if (p_ie->min_bitpool < A2DP_SBC_IE_MIN_BITPOOL || - p_ie->min_bitpool > A2DP_SBC_IE_MAX_BITPOOL) { + if (p_ie->min_bitpool < A2DP_SBC_IE_MIN_BITPOOL || p_ie->min_bitpool > A2DP_SBC_IE_MAX_BITPOOL) { return A2DP_BAD_MIN_BITPOOL; } - if (p_ie->max_bitpool < A2DP_SBC_IE_MIN_BITPOOL || - p_ie->max_bitpool > A2DP_SBC_IE_MAX_BITPOOL || + if (p_ie->max_bitpool < A2DP_SBC_IE_MIN_BITPOOL || p_ie->max_bitpool > A2DP_SBC_IE_MAX_BITPOOL || p_ie->max_bitpool < p_ie->min_bitpool) { return A2DP_BAD_MAX_BITPOOL; } @@ -205,29 +202,40 @@ static tA2DP_STATUS A2DP_ParseInfoSbc(tA2DP_SBC_CIE* p_ie, if (is_capability) { // NOTE: The checks here are very liberal. We should be using more // pedantic checks specific to the SRC or SNK as specified in the spec. - if (A2DP_BitsSet(p_ie->samp_freq) == A2DP_SET_ZERO_BIT) + if (A2DP_BitsSet(p_ie->samp_freq) == A2DP_SET_ZERO_BIT) { return A2DP_BAD_SAMP_FREQ; - if (A2DP_BitsSet(p_ie->ch_mode) == A2DP_SET_ZERO_BIT) + } + if (A2DP_BitsSet(p_ie->ch_mode) == A2DP_SET_ZERO_BIT) { return A2DP_BAD_CH_MODE; - if (A2DP_BitsSet(p_ie->block_len) == A2DP_SET_ZERO_BIT) + } + if (A2DP_BitsSet(p_ie->block_len) == A2DP_SET_ZERO_BIT) { return A2DP_BAD_BLOCK_LEN; - if (A2DP_BitsSet(p_ie->num_subbands) == A2DP_SET_ZERO_BIT) + } + if (A2DP_BitsSet(p_ie->num_subbands) == A2DP_SET_ZERO_BIT) { return A2DP_BAD_SUBBANDS; - if (A2DP_BitsSet(p_ie->alloc_method) == A2DP_SET_ZERO_BIT) + } + if (A2DP_BitsSet(p_ie->alloc_method) == A2DP_SET_ZERO_BIT) { return A2DP_BAD_ALLOC_METHOD; + } return A2DP_SUCCESS; } - if (A2DP_BitsSet(p_ie->samp_freq) != A2DP_SET_ONE_BIT) + if (A2DP_BitsSet(p_ie->samp_freq) != A2DP_SET_ONE_BIT) { return A2DP_BAD_SAMP_FREQ; - if (A2DP_BitsSet(p_ie->ch_mode) != A2DP_SET_ONE_BIT) return A2DP_BAD_CH_MODE; - if (A2DP_BitsSet(p_ie->block_len) != A2DP_SET_ONE_BIT) + } + if (A2DP_BitsSet(p_ie->ch_mode) != A2DP_SET_ONE_BIT) { + return A2DP_BAD_CH_MODE; + } + if (A2DP_BitsSet(p_ie->block_len) != A2DP_SET_ONE_BIT) { return A2DP_BAD_BLOCK_LEN; - if (A2DP_BitsSet(p_ie->num_subbands) != A2DP_SET_ONE_BIT) + } + if (A2DP_BitsSet(p_ie->num_subbands) != A2DP_SET_ONE_BIT) { return A2DP_BAD_SUBBANDS; - if (A2DP_BitsSet(p_ie->alloc_method) != A2DP_SET_ONE_BIT) + } + if (A2DP_BitsSet(p_ie->alloc_method) != A2DP_SET_ONE_BIT) { return A2DP_BAD_ALLOC_METHOD; + } return A2DP_SUCCESS; } @@ -239,15 +247,22 @@ static tA2DP_STATUS A2DP_ParseInfoSbc(tA2DP_SBC_CIE* p_ie, // |last| is true for the last packet of a fragmented frame. // If |frag| is false, |num| is the number of number of frames in the packet, // otherwise is the number of remaining fragments (including this one). -static void A2DP_BuildMediaPayloadHeaderSbc(uint8_t* p_dst, bool frag, - bool start, bool last, +static void A2DP_BuildMediaPayloadHeaderSbc(uint8_t* p_dst, bool frag, bool start, bool last, uint8_t num) { - if (p_dst == NULL) return; + if (p_dst == NULL) { + return; + } *p_dst = 0; - if (frag) *p_dst |= A2DP_SBC_HDR_F_MSK; - if (start) *p_dst |= A2DP_SBC_HDR_S_MSK; - if (last) *p_dst |= A2DP_SBC_HDR_L_MSK; + if (frag) { + *p_dst |= A2DP_SBC_HDR_F_MSK; + } + if (start) { + *p_dst |= A2DP_SBC_HDR_S_MSK; + } + if (last) { + *p_dst |= A2DP_SBC_HDR_L_MSK; + } *p_dst |= (A2DP_SBC_HDR_NUM_MSK & num); } @@ -275,9 +290,8 @@ static void A2DP_BuildMediaPayloadHeaderSbc(uint8_t* p_dst, bool frag, * * Returns void. *****************************************************************************/ -UNUSED_ATTR static void A2DP_ParseMplHeaderSbc(uint8_t* p_src, bool* p_frag, - bool* p_start, bool* p_last, - uint8_t* p_num) { +UNUSED_ATTR static void A2DP_ParseMplHeaderSbc(uint8_t* p_src, bool* p_frag, bool* p_start, + bool* p_last, uint8_t* p_num) { if (p_src && p_frag && p_start && p_last && p_num) { *p_frag = (*p_src & A2DP_SBC_HDR_F_MSK) ? true : false; *p_start = (*p_src & A2DP_SBC_HDR_S_MSK) ? true : false; @@ -286,9 +300,7 @@ UNUSED_ATTR static void A2DP_ParseMplHeaderSbc(uint8_t* p_src, bool* p_frag, } } -const char* A2DP_CodecNameSbc(const uint8_t* /* p_codec_info */) { - return "SBC"; -} +const char* A2DP_CodecNameSbc(const uint8_t* /* p_codec_info */) { return "SBC"; } bool A2DP_IsSourceCodecValidSbc(const uint8_t* p_codec_info) { tA2DP_SBC_CIE cfg_cie; @@ -323,18 +335,18 @@ bool A2DP_IsPeerSinkCodecValidSbc(const uint8_t* p_codec_info) { } bool A2DP_IsSinkCodecSupportedSbc(const uint8_t* p_codec_info) { - return (A2DP_CodecInfoMatchesCapabilitySbc(&a2dp_sbc_sink_caps, p_codec_info, - false) == A2DP_SUCCESS); + return A2DP_CodecInfoMatchesCapabilitySbc(&a2dp_sbc_sink_caps, p_codec_info, false) == + A2DP_SUCCESS; } bool A2DP_IsPeerSourceCodecSupportedSbc(const uint8_t* p_codec_info) { - return (A2DP_CodecInfoMatchesCapabilitySbc(&a2dp_sbc_sink_caps, p_codec_info, - true) == A2DP_SUCCESS); + return A2DP_CodecInfoMatchesCapabilitySbc(&a2dp_sbc_sink_caps, p_codec_info, true) == + A2DP_SUCCESS; } void A2DP_InitDefaultCodecSbc(uint8_t* p_codec_info) { - if (A2DP_BuildInfoSbc(AVDT_MEDIA_TYPE_AUDIO, &a2dp_sbc_default_config, - p_codec_info) != A2DP_SUCCESS) { + if (A2DP_BuildInfoSbc(AVDT_MEDIA_TYPE_AUDIO, &a2dp_sbc_default_config, p_codec_info) != + A2DP_SUCCESS) { log::error("A2DP_BuildInfoSbc failed"); } } @@ -345,9 +357,9 @@ void A2DP_InitDefaultCodecSbc(uint8_t* p_codec_info) { // |p_codec_info| contains A2DP codec capability. // Returns A2DP_SUCCESS if the codec configuration matches with capabilities, // otherwise the corresponding A2DP error status code. -static tA2DP_STATUS A2DP_CodecInfoMatchesCapabilitySbc( - const tA2DP_SBC_CIE* p_cap, const uint8_t* p_codec_info, - bool is_capability) { +static tA2DP_STATUS A2DP_CodecInfoMatchesCapabilitySbc(const tA2DP_SBC_CIE* p_cap, + const uint8_t* p_codec_info, + bool is_capability) { tA2DP_STATUS status; tA2DP_SBC_CIE cfg_cie; @@ -360,55 +372,62 @@ static tA2DP_STATUS A2DP_CodecInfoMatchesCapabilitySbc( /* verify that each parameter is in range */ - log::verbose("FREQ peer: 0x{:x}, capability 0x{:x}", cfg_cie.samp_freq, - p_cap->samp_freq); - log::verbose("CH_MODE peer: 0x{:x}, capability 0x{:x}", cfg_cie.ch_mode, - p_cap->ch_mode); - log::verbose("BLOCK_LEN peer: 0x{:x}, capability 0x{:x}", cfg_cie.block_len, - p_cap->block_len); + log::verbose("FREQ peer: 0x{:x}, capability 0x{:x}", cfg_cie.samp_freq, p_cap->samp_freq); + log::verbose("CH_MODE peer: 0x{:x}, capability 0x{:x}", cfg_cie.ch_mode, p_cap->ch_mode); + log::verbose("BLOCK_LEN peer: 0x{:x}, capability 0x{:x}", cfg_cie.block_len, p_cap->block_len); log::verbose("SUB_BAND peer: 0x{:x}, capability 0x{:x}", cfg_cie.num_subbands, p_cap->num_subbands); - log::verbose("ALLOC_METHOD peer: 0x{:x}, capability 0x{:x}", - cfg_cie.alloc_method, p_cap->alloc_method); - log::verbose("MIN_BitPool peer: 0x{:x}, capability 0x{:x}", - cfg_cie.min_bitpool, p_cap->min_bitpool); - log::verbose("MAX_BitPool peer: 0x{:x}, capability 0x{:x}", - cfg_cie.max_bitpool, p_cap->max_bitpool); + log::verbose("ALLOC_METHOD peer: 0x{:x}, capability 0x{:x}", cfg_cie.alloc_method, + p_cap->alloc_method); + log::verbose("MIN_BitPool peer: 0x{:x}, capability 0x{:x}", cfg_cie.min_bitpool, + p_cap->min_bitpool); + log::verbose("MAX_BitPool peer: 0x{:x}, capability 0x{:x}", cfg_cie.max_bitpool, + p_cap->max_bitpool); /* sampling frequency */ - if ((cfg_cie.samp_freq & p_cap->samp_freq) == 0) return A2DP_NS_SAMP_FREQ; + if ((cfg_cie.samp_freq & p_cap->samp_freq) == 0) { + return A2DP_NS_SAMP_FREQ; + } /* channel mode */ - if ((cfg_cie.ch_mode & p_cap->ch_mode) == 0) return A2DP_NS_CH_MODE; + if ((cfg_cie.ch_mode & p_cap->ch_mode) == 0) { + return A2DP_NS_CH_MODE; + } /* block length */ - if ((cfg_cie.block_len & p_cap->block_len) == 0) return A2DP_BAD_BLOCK_LEN; + if ((cfg_cie.block_len & p_cap->block_len) == 0) { + return A2DP_BAD_BLOCK_LEN; + } /* subbands */ - if ((cfg_cie.num_subbands & p_cap->num_subbands) == 0) + if ((cfg_cie.num_subbands & p_cap->num_subbands) == 0) { return A2DP_NS_SUBBANDS; + } /* allocation method */ - if ((cfg_cie.alloc_method & p_cap->alloc_method) == 0) + if ((cfg_cie.alloc_method & p_cap->alloc_method) == 0) { return A2DP_NS_ALLOC_METHOD; + } /* min bitpool */ - if (cfg_cie.min_bitpool > p_cap->max_bitpool) return A2DP_NS_MIN_BITPOOL; + if (cfg_cie.min_bitpool > p_cap->max_bitpool) { + return A2DP_NS_MIN_BITPOOL; + } /* max bitpool */ - if (cfg_cie.max_bitpool < p_cap->min_bitpool) return A2DP_NS_MAX_BITPOOL; + if (cfg_cie.max_bitpool < p_cap->min_bitpool) { + return A2DP_NS_MAX_BITPOOL; + } return A2DP_SUCCESS; } -bool A2DP_CodecTypeEqualsSbc(const uint8_t* p_codec_info_a, - const uint8_t* p_codec_info_b) { +bool A2DP_CodecTypeEqualsSbc(const uint8_t* p_codec_info_a, const uint8_t* p_codec_info_b) { tA2DP_SBC_CIE sbc_cie_a; tA2DP_SBC_CIE sbc_cie_b; // Check whether the codec info contains valid data - tA2DP_STATUS a2dp_status = - A2DP_ParseInfoSbc(&sbc_cie_a, p_codec_info_a, true); + tA2DP_STATUS a2dp_status = A2DP_ParseInfoSbc(&sbc_cie_a, p_codec_info_a, true); if (a2dp_status != A2DP_SUCCESS) { log::error("cannot decode codec information: {}", a2dp_status); return false; @@ -425,14 +444,12 @@ bool A2DP_CodecTypeEqualsSbc(const uint8_t* p_codec_info_a, return (codec_type_a == codec_type_b) && (codec_type_a == A2DP_MEDIA_CT_SBC); } -bool A2DP_CodecEqualsSbc(const uint8_t* p_codec_info_a, - const uint8_t* p_codec_info_b) { +bool A2DP_CodecEqualsSbc(const uint8_t* p_codec_info_a, const uint8_t* p_codec_info_b) { tA2DP_SBC_CIE sbc_cie_a; tA2DP_SBC_CIE sbc_cie_b; // Check whether the codec info contains valid data - tA2DP_STATUS a2dp_status = - A2DP_ParseInfoSbc(&sbc_cie_a, p_codec_info_a, true); + tA2DP_STATUS a2dp_status = A2DP_ParseInfoSbc(&sbc_cie_a, p_codec_info_a, true); if (a2dp_status != A2DP_SUCCESS) { log::error("cannot decode codec information: {}", a2dp_status); return false; @@ -446,11 +463,11 @@ bool A2DP_CodecEqualsSbc(const uint8_t* p_codec_info_a, tA2DP_CODEC_TYPE codec_type_a = A2DP_GetCodecType(p_codec_info_a); tA2DP_CODEC_TYPE codec_type_b = A2DP_GetCodecType(p_codec_info_b); - if ((codec_type_a != codec_type_b) || (codec_type_a != A2DP_MEDIA_CT_SBC)) + if ((codec_type_a != codec_type_b) || (codec_type_a != A2DP_MEDIA_CT_SBC)) { return false; + } - return (sbc_cie_a.samp_freq == sbc_cie_b.samp_freq) && - (sbc_cie_a.ch_mode == sbc_cie_b.ch_mode) && + return (sbc_cie_a.samp_freq == sbc_cie_b.samp_freq) && (sbc_cie_a.ch_mode == sbc_cie_b.ch_mode) && (sbc_cie_a.block_len == sbc_cie_b.block_len) && (sbc_cie_a.num_subbands == sbc_cie_b.num_subbands) && (sbc_cie_a.alloc_method == sbc_cie_b.alloc_method) && @@ -684,8 +701,8 @@ int A2DP_GetSinkTrackChannelTypeSbc(const uint8_t* p_codec_info) { return -1; } -bool A2DP_GetPacketTimestampSbc(const uint8_t* /* p_codec_info */, - const uint8_t* p_data, uint32_t* p_timestamp) { +bool A2DP_GetPacketTimestampSbc(const uint8_t* /* p_codec_info */, const uint8_t* p_data, + uint32_t* p_timestamp) { *p_timestamp = *(const uint32_t*)p_data; return true; } @@ -705,8 +722,7 @@ bool A2DP_BuildCodecHeaderSbc(const uint8_t* /* p_codec_info */, BT_HDR* p_buf, p_buf->offset -= A2DP_SBC_MPL_HDR_LEN; uint8_t* p = (uint8_t*)(p_buf + 1) + p_buf->offset; p_buf->len += A2DP_SBC_MPL_HDR_LEN; - A2DP_BuildMediaPayloadHeaderSbc(p, false, false, false, - (uint8_t)frames_per_packet); + A2DP_BuildMediaPayloadHeaderSbc(p, false, false, false, (uint8_t)frames_per_packet); return true; } @@ -719,8 +735,7 @@ std::string A2DP_CodecInfoStringSbc(const uint8_t* p_codec_info) { a2dp_status = A2DP_ParseInfoSbc(&sbc_cie, p_codec_info, true); if (a2dp_status != A2DP_SUCCESS) { - res << "A2DP_ParseInfoSbc fail: " - << loghex(static_cast(a2dp_status)); + res << "A2DP_ParseInfoSbc fail: " << loghex(static_cast(a2dp_status)); return res.str(); } @@ -758,17 +773,14 @@ std::string A2DP_CodecInfoStringSbc(const uint8_t* p_codec_info) { AppendField(&field, (sbc_cie.num_subbands == 0), "NONE"); AppendField(&field, (sbc_cie.num_subbands & A2DP_SBC_IE_SUBBAND_4), "4"); AppendField(&field, (sbc_cie.num_subbands & A2DP_SBC_IE_SUBBAND_8), "8"); - res << "\tnum_subbands: " << field << " (" << loghex(sbc_cie.num_subbands) - << ")\n"; + res << "\tnum_subbands: " << field << " (" << loghex(sbc_cie.num_subbands) << ")\n"; // Allocation method field.clear(); AppendField(&field, (sbc_cie.alloc_method == 0), "NONE"); AppendField(&field, (sbc_cie.alloc_method & A2DP_SBC_IE_ALLOC_MD_S), "SNR"); - AppendField(&field, (sbc_cie.alloc_method & A2DP_SBC_IE_ALLOC_MD_L), - "Loundess"); - res << "\talloc_method: " << field << " (" << loghex(sbc_cie.alloc_method) - << ")\n"; + AppendField(&field, (sbc_cie.alloc_method & A2DP_SBC_IE_ALLOC_MD_L), "Loundess"); + res << "\talloc_method: " << field << " (" << loghex(sbc_cie.alloc_method) << ")\n"; // Min/max bitloop res << "\tBit pool Min: " << std::to_string(sbc_cie.min_bitpool) @@ -777,16 +789,18 @@ std::string A2DP_CodecInfoStringSbc(const uint8_t* p_codec_info) { return res.str(); } -const tA2DP_ENCODER_INTERFACE* A2DP_GetEncoderInterfaceSbc( - const uint8_t* p_codec_info) { - if (!A2DP_IsSourceCodecValidSbc(p_codec_info)) return NULL; +const tA2DP_ENCODER_INTERFACE* A2DP_GetEncoderInterfaceSbc(const uint8_t* p_codec_info) { + if (!A2DP_IsSourceCodecValidSbc(p_codec_info)) { + return NULL; + } return &a2dp_encoder_interface_sbc; } -const tA2DP_DECODER_INTERFACE* A2DP_GetDecoderInterfaceSbc( - const uint8_t* p_codec_info) { - if (!A2DP_IsSinkCodecValidSbc(p_codec_info)) return NULL; +const tA2DP_DECODER_INTERFACE* A2DP_GetDecoderInterfaceSbc(const uint8_t* p_codec_info) { + if (!A2DP_IsSinkCodecValidSbc(p_codec_info)) { + return NULL; + } return &a2dp_decoder_interface_sbc; } @@ -794,27 +808,25 @@ const tA2DP_DECODER_INTERFACE* A2DP_GetDecoderInterfaceSbc( bool A2DP_AdjustCodecSbc(uint8_t* p_codec_info) { tA2DP_SBC_CIE cfg_cie; - if (A2DP_ParseInfoSbc(&cfg_cie, p_codec_info, true) != A2DP_SUCCESS) + if (A2DP_ParseInfoSbc(&cfg_cie, p_codec_info, true) != A2DP_SUCCESS) { return false; + } // Updated the max bitpool if (cfg_cie.max_bitpool > A2DP_SBC_MAX_BITPOOL) { - log::warn("Updated the SBC codec max bitpool from {} to {}", - cfg_cie.max_bitpool, A2DP_SBC_MAX_BITPOOL); + log::warn("Updated the SBC codec max bitpool from {} to {}", cfg_cie.max_bitpool, + A2DP_SBC_MAX_BITPOOL); cfg_cie.max_bitpool = A2DP_SBC_MAX_BITPOOL; } - return (A2DP_BuildInfoSbc(AVDT_MEDIA_TYPE_AUDIO, &cfg_cie, p_codec_info) == - A2DP_SUCCESS); + return A2DP_BuildInfoSbc(AVDT_MEDIA_TYPE_AUDIO, &cfg_cie, p_codec_info) == A2DP_SUCCESS; } -btav_a2dp_codec_index_t A2DP_SourceCodecIndexSbc( - const uint8_t* /* p_codec_info */) { +btav_a2dp_codec_index_t A2DP_SourceCodecIndexSbc(const uint8_t* /* p_codec_info */) { return BTAV_A2DP_CODEC_INDEX_SOURCE_SBC; } -btav_a2dp_codec_index_t A2DP_SinkCodecIndexSbc( - const uint8_t* /* p_codec_info */) { +btav_a2dp_codec_index_t A2DP_SinkCodecIndexSbc(const uint8_t* /* p_codec_info */) { return BTAV_A2DP_CODEC_INDEX_SINK_SBC; } @@ -823,8 +835,8 @@ const char* A2DP_CodecIndexStrSbc(void) { return "SBC"; } const char* A2DP_CodecIndexStrSbcSink(void) { return "SBC SINK"; } bool A2DP_InitCodecConfigSbc(AvdtpSepConfig* p_cfg) { - if (A2DP_BuildInfoSbc(AVDT_MEDIA_TYPE_AUDIO, &a2dp_sbc_source_caps, - p_cfg->codec_info) != A2DP_SUCCESS) { + if (A2DP_BuildInfoSbc(AVDT_MEDIA_TYPE_AUDIO, &a2dp_sbc_source_caps, p_cfg->codec_info) != + A2DP_SUCCESS) { return false; } @@ -832,8 +844,8 @@ bool A2DP_InitCodecConfigSbc(AvdtpSepConfig* p_cfg) { } bool A2DP_InitCodecConfigSbcSink(AvdtpSepConfig* p_cfg) { - if (A2DP_BuildInfoSbc(AVDT_MEDIA_TYPE_AUDIO, &a2dp_sbc_sink_caps, - p_cfg->codec_info) != A2DP_SUCCESS) { + if (A2DP_BuildInfoSbc(AVDT_MEDIA_TYPE_AUDIO, &a2dp_sbc_sink_caps, p_cfg->codec_info) != + A2DP_SUCCESS) { return false; } @@ -842,26 +854,28 @@ bool A2DP_InitCodecConfigSbcSink(AvdtpSepConfig* p_cfg) { UNUSED_ATTR static void build_codec_config(const tA2DP_SBC_CIE& config_cie, btav_a2dp_codec_config_t* result) { - if (config_cie.samp_freq & A2DP_SBC_IE_SAMP_FREQ_44) + if (config_cie.samp_freq & A2DP_SBC_IE_SAMP_FREQ_44) { result->sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_44100; - if (config_cie.samp_freq & A2DP_SBC_IE_SAMP_FREQ_48) + } + if (config_cie.samp_freq & A2DP_SBC_IE_SAMP_FREQ_48) { result->sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_48000; + } result->bits_per_sample = config_cie.bits_per_sample; - if (config_cie.ch_mode & A2DP_SBC_IE_CH_MD_MONO) + if (config_cie.ch_mode & A2DP_SBC_IE_CH_MD_MONO) { result->channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_MONO; + } - if (config_cie.ch_mode & (A2DP_SBC_IE_CH_MD_STEREO | A2DP_SBC_IE_CH_MD_JOINT | - A2DP_SBC_IE_CH_MD_DUAL)) { + if (config_cie.ch_mode & + (A2DP_SBC_IE_CH_MD_STEREO | A2DP_SBC_IE_CH_MD_JOINT | A2DP_SBC_IE_CH_MD_DUAL)) { result->channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; } } -A2dpCodecConfigSbcSource::A2dpCodecConfigSbcSource( - btav_a2dp_codec_priority_t codec_priority) - : A2dpCodecConfigSbcBase(BTAV_A2DP_CODEC_INDEX_SOURCE_SBC, - A2DP_CodecIndexStrSbc(), codec_priority, true) { +A2dpCodecConfigSbcSource::A2dpCodecConfigSbcSource(btav_a2dp_codec_priority_t codec_priority) + : A2dpCodecConfigSbcBase(BTAV_A2DP_CODEC_INDEX_SOURCE_SBC, A2DP_CodecIndexStrSbc(), + codec_priority, true) { // Compute the local capability if (a2dp_sbc_source_caps.samp_freq & A2DP_SBC_IE_SAMP_FREQ_44) { codec_local_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_44100; @@ -869,8 +883,7 @@ A2dpCodecConfigSbcSource::A2dpCodecConfigSbcSource( if (a2dp_sbc_source_caps.samp_freq & A2DP_SBC_IE_SAMP_FREQ_48) { codec_local_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_48000; } - codec_local_capability_.bits_per_sample = - a2dp_sbc_source_caps.bits_per_sample; + codec_local_capability_.bits_per_sample = a2dp_sbc_source_caps.bits_per_sample; if (a2dp_sbc_source_caps.ch_mode & A2DP_SBC_IE_CH_MD_MONO) { codec_local_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_MONO; } @@ -888,7 +901,9 @@ A2dpCodecConfigSbcSource::A2dpCodecConfigSbcSource( A2dpCodecConfigSbcSource::~A2dpCodecConfigSbcSource() {} bool A2dpCodecConfigSbcSource::init() { - if (!isValid()) return false; + if (!isValid()) { + return false; + } // Load the encoder if (!A2DP_LoadEncoderSbc()) { @@ -927,9 +942,9 @@ static bool select_best_sample_rate(uint8_t samp_freq, tA2DP_SBC_CIE* p_result, // The result is stored in |p_result| and |p_codec_config|. // Returns true if a selection was made, otherwise false. // -static bool select_audio_sample_rate( - const btav_a2dp_codec_config_t* p_codec_audio_config, uint8_t samp_freq, - tA2DP_SBC_CIE* p_result, btav_a2dp_codec_config_t* p_codec_config) { +static bool select_audio_sample_rate(const btav_a2dp_codec_config_t* p_codec_audio_config, + uint8_t samp_freq, tA2DP_SBC_CIE* p_result, + btav_a2dp_codec_config_t* p_codec_config) { switch (p_codec_audio_config->sample_rate) { case BTAV_A2DP_CODEC_SAMPLE_RATE_44100: if (samp_freq & A2DP_SBC_IE_SAMP_FREQ_44) { @@ -963,8 +978,7 @@ static bool select_audio_sample_rate( // The result is stored in |p_codec_config|. // Returns true if a selection was made, otherwise false. // -static bool select_best_bits_per_sample( - btav_a2dp_codec_config_t* p_codec_config) { +static bool select_best_bits_per_sample(btav_a2dp_codec_config_t* p_codec_config) { p_codec_config->bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16; return true; } @@ -974,9 +988,8 @@ static bool select_best_bits_per_sample( // The result is stored in |p_codec_config|. // Returns true if a selection was made, otherwise false. // -static bool select_audio_bits_per_sample( - const btav_a2dp_codec_config_t* p_codec_audio_config, - btav_a2dp_codec_config_t* p_codec_config) { +static bool select_audio_bits_per_sample(const btav_a2dp_codec_config_t* p_codec_audio_config, + btav_a2dp_codec_config_t* p_codec_config) { switch (p_codec_audio_config->bits_per_sample) { case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16: p_codec_config->bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16; @@ -1025,9 +1038,9 @@ static bool select_best_channel_mode(uint8_t ch_mode, tA2DP_SBC_CIE* p_result, // The result is stored in |p_result| and |p_codec_config|. // Returns true if a selection was made, otherwise false. // -static bool select_audio_channel_mode( - const btav_a2dp_codec_config_t* p_codec_audio_config, uint8_t ch_mode, - tA2DP_SBC_CIE* p_result, btav_a2dp_codec_config_t* p_codec_config) { +static bool select_audio_channel_mode(const btav_a2dp_codec_config_t* p_codec_audio_config, + uint8_t ch_mode, tA2DP_SBC_CIE* p_result, + btav_a2dp_codec_config_t* p_codec_config) { switch (p_codec_audio_config->channel_mode) { case BTAV_A2DP_CODEC_CHANNEL_MODE_MONO: if (ch_mode & A2DP_SBC_IE_CH_MD_MONO) { @@ -1060,8 +1073,7 @@ static bool select_audio_channel_mode( return false; } -bool A2dpCodecConfigSbcBase::setCodecConfig(const uint8_t* p_peer_codec_info, - bool is_capability, +bool A2dpCodecConfigSbcBase::setCodecConfig(const uint8_t* p_peer_codec_info, bool is_capability, uint8_t* p_result_codec_config) { std::lock_guard lock(codec_mutex_); tA2DP_SBC_CIE peer_info_cie; @@ -1071,14 +1083,12 @@ bool A2dpCodecConfigSbcBase::setCodecConfig(const uint8_t* p_peer_codec_info, uint8_t block_len; uint8_t num_subbands; uint8_t alloc_method; - const tA2DP_SBC_CIE* p_a2dp_sbc_caps = - (is_source_) ? &a2dp_sbc_source_caps : &a2dp_sbc_sink_caps; + const tA2DP_SBC_CIE* p_a2dp_sbc_caps = (is_source_) ? &a2dp_sbc_source_caps : &a2dp_sbc_sink_caps; // Save the internal state btav_a2dp_codec_config_t saved_codec_config = codec_config_; btav_a2dp_codec_config_t saved_codec_capability = codec_capability_; - btav_a2dp_codec_config_t saved_codec_selectable_capability = - codec_selectable_capability_; + btav_a2dp_codec_config_t saved_codec_selectable_capability = codec_selectable_capability_; btav_a2dp_codec_config_t saved_codec_user_config = codec_user_config_; btav_a2dp_codec_config_t saved_codec_audio_config = codec_audio_config_; uint8_t saved_ota_codec_config[AVDT_CODEC_SIZE]; @@ -1087,11 +1097,9 @@ bool A2dpCodecConfigSbcBase::setCodecConfig(const uint8_t* p_peer_codec_info, memcpy(saved_ota_codec_config, ota_codec_config_, sizeof(ota_codec_config_)); memcpy(saved_ota_codec_peer_capability, ota_codec_peer_capability_, sizeof(ota_codec_peer_capability_)); - memcpy(saved_ota_codec_peer_config, ota_codec_peer_config_, - sizeof(ota_codec_peer_config_)); + memcpy(saved_ota_codec_peer_config, ota_codec_peer_config_, sizeof(ota_codec_peer_config_)); - tA2DP_STATUS status = - A2DP_ParseInfoSbc(&peer_info_cie, p_peer_codec_info, is_capability); + tA2DP_STATUS status = A2DP_ParseInfoSbc(&peer_info_cie, p_peer_codec_info, is_capability); if (status != A2DP_SUCCESS) { log::error("can't parse peer's capabilities: error = {}", status); goto fail; @@ -1101,21 +1109,17 @@ bool A2dpCodecConfigSbcBase::setCodecConfig(const uint8_t* p_peer_codec_info, if (is_capability) { if (is_source_) { if (A2DP_IsPeerSinkCodecValidSbc(ota_codec_peer_config_)) { - status = - A2DP_ParseInfoSbc(&peer_info_cie, ota_codec_peer_config_, false); + status = A2DP_ParseInfoSbc(&peer_info_cie, ota_codec_peer_config_, false); } } else { if (A2DP_IsPeerSourceCodecValidSbc(ota_codec_peer_config_)) { - status = - A2DP_ParseInfoSbc(&peer_info_cie, ota_codec_peer_config_, false); + status = A2DP_ParseInfoSbc(&peer_info_cie, ota_codec_peer_config_, false); } } if (status != A2DP_SUCCESS) { // Use the peer codec capability - status = - A2DP_ParseInfoSbc(&peer_info_cie, p_peer_codec_info, is_capability); - log::assert_that(status == A2DP_SUCCESS, - "assert failed: status == A2DP_SUCCESS"); + status = A2DP_ParseInfoSbc(&peer_info_cie, p_peer_codec_info, is_capability); + log::assert_that(status == A2DP_SUCCESS, "assert failed: status == A2DP_SUCCESS"); } } @@ -1160,45 +1164,44 @@ bool A2dpCodecConfigSbcBase::setCodecConfig(const uint8_t* p_peer_codec_info, do { // Compute the selectable capability if (samp_freq & A2DP_SBC_IE_SAMP_FREQ_44) { - codec_selectable_capability_.sample_rate |= - BTAV_A2DP_CODEC_SAMPLE_RATE_44100; + codec_selectable_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_44100; } if (samp_freq & A2DP_SBC_IE_SAMP_FREQ_48) { - codec_selectable_capability_.sample_rate |= - BTAV_A2DP_CODEC_SAMPLE_RATE_48000; + codec_selectable_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_48000; } - if (codec_config_.sample_rate != BTAV_A2DP_CODEC_SAMPLE_RATE_NONE) break; + if (codec_config_.sample_rate != BTAV_A2DP_CODEC_SAMPLE_RATE_NONE) { + break; + } // Compute the common capability - if (samp_freq & A2DP_SBC_IE_SAMP_FREQ_44) + if (samp_freq & A2DP_SBC_IE_SAMP_FREQ_44) { codec_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_44100; - if (samp_freq & A2DP_SBC_IE_SAMP_FREQ_48) + } + if (samp_freq & A2DP_SBC_IE_SAMP_FREQ_48) { codec_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_48000; + } // No user preference - try the codec audio config - if (select_audio_sample_rate(&codec_audio_config_, samp_freq, - &result_config_cie, &codec_config_)) { + if (select_audio_sample_rate(&codec_audio_config_, samp_freq, &result_config_cie, + &codec_config_)) { break; } // No user preference - try the default config - if (select_best_sample_rate( - a2dp_sbc_default_config.samp_freq & peer_info_cie.samp_freq, - &result_config_cie, &codec_config_)) { + if (select_best_sample_rate(a2dp_sbc_default_config.samp_freq & peer_info_cie.samp_freq, + &result_config_cie, &codec_config_)) { break; } // No user preference - use the best match - if (select_best_sample_rate(samp_freq, &result_config_cie, - &codec_config_)) { + if (select_best_sample_rate(samp_freq, &result_config_cie, &codec_config_)) { break; } } while (false); if (codec_config_.sample_rate == BTAV_A2DP_CODEC_SAMPLE_RATE_NONE) { - log::error( - "cannot match sample frequency: local caps = 0x{:x} peer info = 0x{:x}", - p_a2dp_sbc_caps->samp_freq, peer_info_cie.samp_freq); + log::error("cannot match sample frequency: local caps = 0x{:x} peer info = 0x{:x}", + p_a2dp_sbc_caps->samp_freq, peer_info_cie.samp_freq); goto fail; } @@ -1224,11 +1227,11 @@ bool A2dpCodecConfigSbcBase::setCodecConfig(const uint8_t* p_peer_codec_info, // Select the bits per sample if there is no user preference do { // Compute the selectable capability - codec_selectable_capability_.bits_per_sample = - p_a2dp_sbc_caps->bits_per_sample; + codec_selectable_capability_.bits_per_sample = p_a2dp_sbc_caps->bits_per_sample; - if (codec_config_.bits_per_sample != BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE) + if (codec_config_.bits_per_sample != BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE) { break; + } // Compute the common capability codec_capability_.bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16; @@ -1298,42 +1301,39 @@ bool A2dpCodecConfigSbcBase::setCodecConfig(const uint8_t* p_peer_codec_info, do { // Compute the selectable capability if (ch_mode & A2DP_SBC_IE_CH_MD_MONO) { - codec_selectable_capability_.channel_mode |= - BTAV_A2DP_CODEC_CHANNEL_MODE_MONO; + codec_selectable_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_MONO; } if (ch_mode & A2DP_SBC_IE_CH_MD_JOINT) { - codec_selectable_capability_.channel_mode |= - BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; + codec_selectable_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; } if (ch_mode & A2DP_SBC_IE_CH_MD_STEREO) { - codec_selectable_capability_.channel_mode |= - BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; + codec_selectable_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; } if (ch_mode & A2DP_SBC_IE_CH_MD_DUAL) { - codec_selectable_capability_.channel_mode |= - BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; + codec_selectable_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; } - if (codec_config_.channel_mode != BTAV_A2DP_CODEC_CHANNEL_MODE_NONE) break; + if (codec_config_.channel_mode != BTAV_A2DP_CODEC_CHANNEL_MODE_NONE) { + break; + } // Compute the common capability - if (ch_mode & A2DP_SBC_IE_CH_MD_MONO) + if (ch_mode & A2DP_SBC_IE_CH_MD_MONO) { codec_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_MONO; - if (ch_mode & (A2DP_SBC_IE_CH_MD_JOINT | A2DP_SBC_IE_CH_MD_STEREO | - A2DP_SBC_IE_CH_MD_DUAL)) { + } + if (ch_mode & (A2DP_SBC_IE_CH_MD_JOINT | A2DP_SBC_IE_CH_MD_STEREO | A2DP_SBC_IE_CH_MD_DUAL)) { codec_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; } // No user preference - use the codec audio config - if (select_audio_channel_mode(&codec_audio_config_, ch_mode, - &result_config_cie, &codec_config_)) { + if (select_audio_channel_mode(&codec_audio_config_, ch_mode, &result_config_cie, + &codec_config_)) { break; } // No user preference - try the default config - if (select_best_channel_mode( - a2dp_sbc_default_config.ch_mode & peer_info_cie.ch_mode, - &result_config_cie, &codec_config_)) { + if (select_best_channel_mode(a2dp_sbc_default_config.ch_mode & peer_info_cie.ch_mode, + &result_config_cie, &codec_config_)) { break; } @@ -1343,9 +1343,8 @@ bool A2dpCodecConfigSbcBase::setCodecConfig(const uint8_t* p_peer_codec_info, } } while (false); if (codec_config_.channel_mode == BTAV_A2DP_CODEC_CHANNEL_MODE_NONE) { - log::error( - "cannot match channel mode: local caps = 0x{:x} peer info = 0x{:x}", - p_a2dp_sbc_caps->ch_mode, peer_info_cie.ch_mode); + log::error("cannot match channel mode: local caps = 0x{:x} peer info = 0x{:x}", + p_a2dp_sbc_caps->ch_mode, peer_info_cie.ch_mode); goto fail; } @@ -1362,9 +1361,8 @@ bool A2dpCodecConfigSbcBase::setCodecConfig(const uint8_t* p_peer_codec_info, } else if (block_len & A2DP_SBC_IE_BLOCKS_4) { result_config_cie.block_len = A2DP_SBC_IE_BLOCKS_4; } else { - log::error( - "cannot match block length: local caps = 0x{:x} peer info = 0x{:x}", - p_a2dp_sbc_caps->block_len, peer_info_cie.block_len); + log::error("cannot match block length: local caps = 0x{:x} peer info = 0x{:x}", + p_a2dp_sbc_caps->block_len, peer_info_cie.block_len); goto fail; } @@ -1377,10 +1375,8 @@ bool A2dpCodecConfigSbcBase::setCodecConfig(const uint8_t* p_peer_codec_info, } else if (num_subbands & A2DP_SBC_IE_SUBBAND_4) { result_config_cie.num_subbands = A2DP_SBC_IE_SUBBAND_4; } else { - log::error( - "cannot match number of sub-bands: local caps = 0x{:x} peer info = " - "0x{:x}", - p_a2dp_sbc_caps->num_subbands, peer_info_cie.num_subbands); + log::error("cannot match number of sub-bands: local caps = 0x{:x} peer info = 0x{:x}", + p_a2dp_sbc_caps->num_subbands, peer_info_cie.num_subbands); goto fail; } @@ -1393,10 +1389,8 @@ bool A2dpCodecConfigSbcBase::setCodecConfig(const uint8_t* p_peer_codec_info, } else if (alloc_method & A2DP_SBC_IE_ALLOC_MD_S) { result_config_cie.alloc_method = A2DP_SBC_IE_ALLOC_MD_S; } else { - log::error( - "cannot match allocation method: local caps = 0x{:x} peer info = " - "0x{:x}", - p_a2dp_sbc_caps->alloc_method, peer_info_cie.alloc_method); + log::error("cannot match allocation method: local caps = 0x{:x} peer info = 0x{:x}", + p_a2dp_sbc_caps->alloc_method, peer_info_cie.alloc_method); goto fail; } @@ -1404,52 +1398,53 @@ bool A2dpCodecConfigSbcBase::setCodecConfig(const uint8_t* p_peer_codec_info, // Select the min/max bitpool // result_config_cie.min_bitpool = p_a2dp_sbc_caps->min_bitpool; - if (result_config_cie.min_bitpool < peer_info_cie.min_bitpool) + if (result_config_cie.min_bitpool < peer_info_cie.min_bitpool) { result_config_cie.min_bitpool = peer_info_cie.min_bitpool; + } result_config_cie.max_bitpool = p_a2dp_sbc_caps->max_bitpool; - if (result_config_cie.max_bitpool > peer_info_cie.max_bitpool) + if (result_config_cie.max_bitpool > peer_info_cie.max_bitpool) { result_config_cie.max_bitpool = peer_info_cie.max_bitpool; + } if (result_config_cie.min_bitpool > result_config_cie.max_bitpool) { log::error( - "cannot match min/max bitpool: local caps min/max = 0x{:x}/0x{:x} peer " - "info min/max = 0x{:x}/0x{:x}", - p_a2dp_sbc_caps->min_bitpool, p_a2dp_sbc_caps->max_bitpool, - peer_info_cie.min_bitpool, peer_info_cie.max_bitpool); + "cannot match min/max bitpool: local caps min/max = 0x{:x}/0x{:x} peer " + "info min/max = 0x{:x}/0x{:x}", + p_a2dp_sbc_caps->min_bitpool, p_a2dp_sbc_caps->max_bitpool, peer_info_cie.min_bitpool, + peer_info_cie.max_bitpool); goto fail; } - if (A2DP_BuildInfoSbc(AVDT_MEDIA_TYPE_AUDIO, &result_config_cie, - p_result_codec_config) != A2DP_SUCCESS) { + if (A2DP_BuildInfoSbc(AVDT_MEDIA_TYPE_AUDIO, &result_config_cie, p_result_codec_config) != + A2DP_SUCCESS) { goto fail; } // // Copy the codec-specific fields if they are not zero // - if (codec_user_config_.codec_specific_1 != 0) + if (codec_user_config_.codec_specific_1 != 0) { codec_config_.codec_specific_1 = codec_user_config_.codec_specific_1; - if (codec_user_config_.codec_specific_2 != 0) + } + if (codec_user_config_.codec_specific_2 != 0) { codec_config_.codec_specific_2 = codec_user_config_.codec_specific_2; - if (codec_user_config_.codec_specific_3 != 0) + } + if (codec_user_config_.codec_specific_3 != 0) { codec_config_.codec_specific_3 = codec_user_config_.codec_specific_3; - if (codec_user_config_.codec_specific_4 != 0) + } + if (codec_user_config_.codec_specific_4 != 0) { codec_config_.codec_specific_4 = codec_user_config_.codec_specific_4; + } // Create a local copy of the peer codec capability/config, and the // result codec config. if (is_capability) { - status = A2DP_BuildInfoSbc(AVDT_MEDIA_TYPE_AUDIO, &peer_info_cie, - ota_codec_peer_capability_); + status = A2DP_BuildInfoSbc(AVDT_MEDIA_TYPE_AUDIO, &peer_info_cie, ota_codec_peer_capability_); } else { - status = A2DP_BuildInfoSbc(AVDT_MEDIA_TYPE_AUDIO, &peer_info_cie, - ota_codec_peer_config_); - } - log::assert_that(status == A2DP_SUCCESS, - "assert failed: status == A2DP_SUCCESS"); - status = A2DP_BuildInfoSbc(AVDT_MEDIA_TYPE_AUDIO, &result_config_cie, - ota_codec_config_); - log::assert_that(status == A2DP_SUCCESS, - "assert failed: status == A2DP_SUCCESS"); + status = A2DP_BuildInfoSbc(AVDT_MEDIA_TYPE_AUDIO, &peer_info_cie, ota_codec_peer_config_); + } + log::assert_that(status == A2DP_SUCCESS, "assert failed: status == A2DP_SUCCESS"); + status = A2DP_BuildInfoSbc(AVDT_MEDIA_TYPE_AUDIO, &result_config_cie, ota_codec_config_); + log::assert_that(status == A2DP_SUCCESS, "assert failed: status == A2DP_SUCCESS"); return true; fail: @@ -1462,29 +1457,24 @@ fail: memcpy(ota_codec_config_, saved_ota_codec_config, sizeof(ota_codec_config_)); memcpy(ota_codec_peer_capability_, saved_ota_codec_peer_capability, sizeof(ota_codec_peer_capability_)); - memcpy(ota_codec_peer_config_, saved_ota_codec_peer_config, - sizeof(ota_codec_peer_config_)); + memcpy(ota_codec_peer_config_, saved_ota_codec_peer_config, sizeof(ota_codec_peer_config_)); return false; } -bool A2dpCodecConfigSbcBase::setPeerCodecCapabilities( - const uint8_t* p_peer_codec_capabilities) { +bool A2dpCodecConfigSbcBase::setPeerCodecCapabilities(const uint8_t* p_peer_codec_capabilities) { std::lock_guard lock(codec_mutex_); tA2DP_SBC_CIE peer_info_cie; uint8_t samp_freq; uint8_t ch_mode; - const tA2DP_SBC_CIE* p_a2dp_sbc_caps = - (is_source_) ? &a2dp_sbc_source_caps : &a2dp_sbc_sink_caps; + const tA2DP_SBC_CIE* p_a2dp_sbc_caps = (is_source_) ? &a2dp_sbc_source_caps : &a2dp_sbc_sink_caps; // Save the internal state - btav_a2dp_codec_config_t saved_codec_selectable_capability = - codec_selectable_capability_; + btav_a2dp_codec_config_t saved_codec_selectable_capability = codec_selectable_capability_; uint8_t saved_ota_codec_peer_capability[AVDT_CODEC_SIZE]; memcpy(saved_ota_codec_peer_capability, ota_codec_peer_capability_, sizeof(ota_codec_peer_capability_)); - tA2DP_STATUS status = - A2DP_ParseInfoSbc(&peer_info_cie, p_peer_codec_capabilities, true); + tA2DP_STATUS status = A2DP_ParseInfoSbc(&peer_info_cie, p_peer_codec_capabilities, true); if (status != A2DP_SUCCESS) { log::error("can't parse peer's capabilities: error = {}", status); goto fail; @@ -1493,41 +1483,32 @@ bool A2dpCodecConfigSbcBase::setPeerCodecCapabilities( // Compute the selectable capability - sample rate samp_freq = p_a2dp_sbc_caps->samp_freq & peer_info_cie.samp_freq; if (samp_freq & A2DP_SBC_IE_SAMP_FREQ_44) { - codec_selectable_capability_.sample_rate |= - BTAV_A2DP_CODEC_SAMPLE_RATE_44100; + codec_selectable_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_44100; } if (samp_freq & A2DP_SBC_IE_SAMP_FREQ_48) { - codec_selectable_capability_.sample_rate |= - BTAV_A2DP_CODEC_SAMPLE_RATE_48000; + codec_selectable_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_48000; } // Compute the selectable capability - bits per sample - codec_selectable_capability_.bits_per_sample = - p_a2dp_sbc_caps->bits_per_sample; + codec_selectable_capability_.bits_per_sample = p_a2dp_sbc_caps->bits_per_sample; // Compute the selectable capability - channel mode ch_mode = p_a2dp_sbc_caps->ch_mode & peer_info_cie.ch_mode; if (ch_mode & A2DP_SBC_IE_CH_MD_MONO) { - codec_selectable_capability_.channel_mode |= - BTAV_A2DP_CODEC_CHANNEL_MODE_MONO; + codec_selectable_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_MONO; } if (ch_mode & A2DP_SBC_IE_CH_MD_JOINT) { - codec_selectable_capability_.channel_mode |= - BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; + codec_selectable_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; } if (ch_mode & A2DP_SBC_IE_CH_MD_STEREO) { - codec_selectable_capability_.channel_mode |= - BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; + codec_selectable_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; } if (ch_mode & A2DP_SBC_IE_CH_MD_DUAL) { - codec_selectable_capability_.channel_mode |= - BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; + codec_selectable_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; } - status = A2DP_BuildInfoSbc(AVDT_MEDIA_TYPE_AUDIO, &peer_info_cie, - ota_codec_peer_capability_); - log::assert_that(status == A2DP_SUCCESS, - "assert failed: status == A2DP_SUCCESS"); + status = A2DP_BuildInfoSbc(AVDT_MEDIA_TYPE_AUDIO, &peer_info_cie, ota_codec_peer_capability_); + log::assert_that(status == A2DP_SUCCESS, "assert failed: status == A2DP_SUCCESS"); return true; fail: @@ -1538,16 +1519,16 @@ fail: return false; } -A2dpCodecConfigSbcSink::A2dpCodecConfigSbcSink( - btav_a2dp_codec_priority_t codec_priority) - : A2dpCodecConfigSbcBase(BTAV_A2DP_CODEC_INDEX_SINK_SBC, - A2DP_CodecIndexStrSbcSink(), codec_priority, - false) {} +A2dpCodecConfigSbcSink::A2dpCodecConfigSbcSink(btav_a2dp_codec_priority_t codec_priority) + : A2dpCodecConfigSbcBase(BTAV_A2DP_CODEC_INDEX_SINK_SBC, A2DP_CodecIndexStrSbcSink(), + codec_priority, false) {} A2dpCodecConfigSbcSink::~A2dpCodecConfigSbcSink() {} bool A2dpCodecConfigSbcSink::init() { - if (!isValid()) return false; + if (!isValid()) { + return false; + } // Load the decoder if (!A2DP_LoadDecoderSbc()) { diff --git a/system/stack/a2dp/a2dp_sbc_decoder.cc b/system/stack/a2dp/a2dp_sbc_decoder.cc index 7ec8800b267..ac6bc5e09e5 100644 --- a/system/stack/a2dp/a2dp_sbc_decoder.cc +++ b/system/stack/a2dp/a2dp_sbc_decoder.cc @@ -49,8 +49,8 @@ void A2DP_UnloadDecoderSbc(void) { a2dp_sbc_decoder_cleanup(); } bool a2dp_sbc_decoder_init(decoded_data_callback_t decode_callback) { OI_STATUS status = OI_CODEC_SBC_DecoderReset( - &a2dp_sbc_decoder_cb.decoder_context, a2dp_sbc_decoder_cb.context_data, - sizeof(a2dp_sbc_decoder_cb.context_data), 2, 2, false); + &a2dp_sbc_decoder_cb.decoder_context, a2dp_sbc_decoder_cb.context_data, + sizeof(a2dp_sbc_decoder_cb.context_data), 2, 2, false); if (!OI_SUCCESS(status)) { log::error("OI_CODEC_SBC_DecoderReset failed with error code {}", status); return false; @@ -83,9 +83,8 @@ bool a2dp_sbc_decoder_decode_packet(BT_HDR* p_buf) { for (size_t i = 0; i < num_frames; ++i) { uint32_t out_size = out_avail; - OI_STATUS status = - OI_CODEC_SBC_DecodeFrame(&a2dp_sbc_decoder_cb.decoder_context, &oi_data, - &oi_size, out_ptr, &out_size); + OI_STATUS status = OI_CODEC_SBC_DecodeFrame(&a2dp_sbc_decoder_cb.decoder_context, &oi_data, + &oi_size, out_ptr, &out_size); if (!OI_SUCCESS(status)) { log::error("Decoding failure: {}", status); return false; @@ -94,9 +93,8 @@ bool a2dp_sbc_decoder_decode_packet(BT_HDR* p_buf) { out_ptr += out_size / sizeof(*out_ptr); } - size_t out_used = - (out_ptr - a2dp_sbc_decoder_cb.decode_buf) * sizeof(*out_ptr); - a2dp_sbc_decoder_cb.decode_callback( - reinterpret_cast(a2dp_sbc_decoder_cb.decode_buf), out_used); + size_t out_used = (out_ptr - a2dp_sbc_decoder_cb.decode_buf) * sizeof(*out_ptr); + a2dp_sbc_decoder_cb.decode_callback(reinterpret_cast(a2dp_sbc_decoder_cb.decode_buf), + out_used); return true; } diff --git a/system/stack/a2dp/a2dp_sbc_encoder.cc b/system/stack/a2dp/a2dp_sbc_encoder.cc index 20f2384411d..7e682e12220 100644 --- a/system/stack/a2dp/a2dp_sbc_encoder.cc +++ b/system/stack/a2dp/a2dp_sbc_encoder.cc @@ -92,7 +92,7 @@ typedef struct { uint16_t TxAaMtuSize; uint8_t tx_sbc_frames; tA2DP_ENCODER_INIT_PEER_PARAMS peer_params; - uint32_t timestamp; /* Timestamp for the A2DP frames */ + uint32_t timestamp; /* Timestamp for the A2DP frames */ SBC_ENC_PARAMS sbc_encoder_params; tA2DP_FEEDING_PARAMS feeding_params; tA2DP_SBC_FEEDING_STATE feeding_state; @@ -103,17 +103,13 @@ typedef struct { static tA2DP_SBC_ENCODER_CB a2dp_sbc_encoder_cb; -static void a2dp_sbc_encoder_update(A2dpCodecConfig* a2dp_codec_config, - bool* p_restart_input, - bool* p_restart_output, - bool* p_config_updated); +static void a2dp_sbc_encoder_update(A2dpCodecConfig* a2dp_codec_config, bool* p_restart_input, + bool* p_restart_output, bool* p_config_updated); static bool a2dp_sbc_read_feeding(uint32_t* bytes); static void a2dp_sbc_encode_frames(uint8_t nb_frame); -static void a2dp_sbc_get_num_frame_iteration(uint8_t* num_of_iterations, - uint8_t* num_of_frames, +static void a2dp_sbc_get_num_frame_iteration(uint8_t* num_of_iterations, uint8_t* num_of_frames, uint64_t timestamp_us); -static uint16_t adjust_effective_mtu( - const tA2DP_ENCODER_INIT_PEER_PARAMS& peer_params); +static uint16_t adjust_effective_mtu(const tA2DP_ENCODER_INIT_PEER_PARAMS& peer_params); static uint8_t calculate_max_frames_per_packet(void); static uint16_t a2dp_sbc_source_rate(bool is_peer_edr); static uint32_t a2dp_sbc_frame_length(void); @@ -133,8 +129,7 @@ void a2dp_sbc_encoder_init(const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params, a2dp_source_enqueue_callback_t enqueue_callback) { memset(&a2dp_sbc_encoder_cb, 0, sizeof(a2dp_sbc_encoder_cb)); - a2dp_sbc_encoder_cb.stats.session_start_us = - bluetooth::common::time_get_os_boottime_us(); + a2dp_sbc_encoder_cb.stats.session_start_us = bluetooth::common::time_get_os_boottime_us(); a2dp_sbc_encoder_cb.read_callback = read_callback; a2dp_sbc_encoder_cb.enqueue_callback = enqueue_callback; @@ -146,16 +141,13 @@ void a2dp_sbc_encoder_init(const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params, bool restart_input = false; bool restart_output = false; bool config_updated = false; - a2dp_sbc_encoder_update(a2dp_codec_config, &restart_input, &restart_output, - &config_updated); + a2dp_sbc_encoder_update(a2dp_codec_config, &restart_input, &restart_output, &config_updated); } // Update the A2DP SBC encoder. // |a2dp_codec_config| is the A2DP codec to use for the update. -static void a2dp_sbc_encoder_update(A2dpCodecConfig* a2dp_codec_config, - bool* p_restart_input, - bool* p_restart_output, - bool* p_config_updated) { +static void a2dp_sbc_encoder_update(A2dpCodecConfig* a2dp_codec_config, bool* p_restart_input, + bool* p_restart_output, bool* p_config_updated) { SBC_ENC_PARAMS* p_encoder_params = &a2dp_sbc_encoder_cb.sbc_encoder_params; uint8_t codec_info[AVDT_CODEC_SIZE]; uint16_t s16SamplingFreq; @@ -181,119 +173,107 @@ static void a2dp_sbc_encoder_update(A2dpCodecConfig* a2dp_codec_config, // The feeding parameters tA2DP_FEEDING_PARAMS* p_feeding_params = &a2dp_sbc_encoder_cb.feeding_params; p_feeding_params->sample_rate = A2DP_GetTrackSampleRateSbc(p_codec_info); - p_feeding_params->bits_per_sample = - a2dp_codec_config->getAudioBitsPerSample(); + p_feeding_params->bits_per_sample = a2dp_codec_config->getAudioBitsPerSample(); p_feeding_params->channel_count = A2DP_GetTrackChannelCountSbc(p_codec_info); - log::info("sample_rate={} bits_per_sample={} channel_count={}", - p_feeding_params->sample_rate, p_feeding_params->bits_per_sample, - p_feeding_params->channel_count); + log::info("sample_rate={} bits_per_sample={} channel_count={}", p_feeding_params->sample_rate, + p_feeding_params->bits_per_sample, p_feeding_params->channel_count); a2dp_sbc_feeding_reset(); // The codec parameters p_encoder_params->s16ChannelMode = A2DP_GetChannelModeCodeSbc(p_codec_info); - p_encoder_params->s16NumOfSubBands = - A2DP_GetNumberOfSubbandsSbc(p_codec_info); + p_encoder_params->s16NumOfSubBands = A2DP_GetNumberOfSubbandsSbc(p_codec_info); p_encoder_params->s16NumOfBlocks = A2DP_GetNumberOfBlocksSbc(p_codec_info); - p_encoder_params->s16AllocationMethod = - A2DP_GetAllocationMethodCodeSbc(p_codec_info); - p_encoder_params->s16SamplingFreq = - A2DP_GetSamplingFrequencyCodeSbc(p_codec_info); - p_encoder_params->s16NumOfChannels = - A2DP_GetTrackChannelCountSbc(p_codec_info); + p_encoder_params->s16AllocationMethod = A2DP_GetAllocationMethodCodeSbc(p_codec_info); + p_encoder_params->s16SamplingFreq = A2DP_GetSamplingFrequencyCodeSbc(p_codec_info); + p_encoder_params->s16NumOfChannels = A2DP_GetTrackChannelCountSbc(p_codec_info); // Reset invalid parameters if (!p_encoder_params->s16NumOfSubBands) { - log::warn("SubBands are set to 0, resetting to max ({})", - SBC_MAX_NUM_OF_SUBBANDS); + log::warn("SubBands are set to 0, resetting to max ({})", SBC_MAX_NUM_OF_SUBBANDS); p_encoder_params->s16NumOfSubBands = SBC_MAX_NUM_OF_SUBBANDS; } if (!p_encoder_params->s16NumOfBlocks) { - log::warn("Blocks are set to 0, resetting to max ({})", - SBC_MAX_NUM_OF_BLOCKS); + log::warn("Blocks are set to 0, resetting to max ({})", SBC_MAX_NUM_OF_BLOCKS); p_encoder_params->s16NumOfBlocks = SBC_MAX_NUM_OF_BLOCKS; } if (!p_encoder_params->s16NumOfChannels) { - log::warn("Channels are set to 0, resetting to max ({})", - SBC_MAX_NUM_OF_CHANNELS); + log::warn("Channels are set to 0, resetting to max ({})", SBC_MAX_NUM_OF_CHANNELS); p_encoder_params->s16NumOfChannels = SBC_MAX_NUM_OF_CHANNELS; } - if (p_encoder_params->s16SamplingFreq == SBC_sf16000) + if (p_encoder_params->s16SamplingFreq == SBC_sf16000) { s16SamplingFreq = 16000; - else if (p_encoder_params->s16SamplingFreq == SBC_sf32000) + } else if (p_encoder_params->s16SamplingFreq == SBC_sf32000) { s16SamplingFreq = 32000; - else if (p_encoder_params->s16SamplingFreq == SBC_sf44100) + } else if (p_encoder_params->s16SamplingFreq == SBC_sf44100) { s16SamplingFreq = 44100; - else + } else { s16SamplingFreq = 48000; + } // Set the initial target bit rate - const tA2DP_ENCODER_INIT_PEER_PARAMS& peer_params = - a2dp_sbc_encoder_cb.peer_params; + const tA2DP_ENCODER_INIT_PEER_PARAMS& peer_params = a2dp_sbc_encoder_cb.peer_params; p_encoder_params->u16BitRate = a2dp_sbc_source_rate(peer_params.is_peer_edr); a2dp_sbc_encoder_cb.TxAaMtuSize = adjust_effective_mtu(peer_params); - log::info("MTU={}, peer_mtu={} min_bitpool={} max_bitpool={}", - a2dp_sbc_encoder_cb.TxAaMtuSize, peer_params.peer_mtu, min_bitpool, - max_bitpool); + log::info("MTU={}, peer_mtu={} min_bitpool={} max_bitpool={}", a2dp_sbc_encoder_cb.TxAaMtuSize, + peer_params.peer_mtu, min_bitpool, max_bitpool); log::info( - "ChannelMode={}, NumOfSubBands={}, NumOfBlocks={}, AllocationMethod={}, " - "BitRate={}, SamplingFreq={} BitPool={}", - p_encoder_params->s16ChannelMode, p_encoder_params->s16NumOfSubBands, - p_encoder_params->s16NumOfBlocks, p_encoder_params->s16AllocationMethod, - p_encoder_params->u16BitRate, s16SamplingFreq, - p_encoder_params->s16BitPool); + "ChannelMode={}, NumOfSubBands={}, NumOfBlocks={}, AllocationMethod={}, " + "BitRate={}, SamplingFreq={} BitPool={}", + p_encoder_params->s16ChannelMode, p_encoder_params->s16NumOfSubBands, + p_encoder_params->s16NumOfBlocks, p_encoder_params->s16AllocationMethod, + p_encoder_params->u16BitRate, s16SamplingFreq, p_encoder_params->s16BitPool); do { if ((p_encoder_params->s16ChannelMode == SBC_JOINT_STEREO) || (p_encoder_params->s16ChannelMode == SBC_STEREO)) { - s16BitPool = (int16_t)((p_encoder_params->u16BitRate * - p_encoder_params->s16NumOfSubBands * 1000 / - s16SamplingFreq) - - ((32 + (4 * p_encoder_params->s16NumOfSubBands * - p_encoder_params->s16NumOfChannels) + + s16BitPool = (int16_t)((p_encoder_params->u16BitRate * p_encoder_params->s16NumOfSubBands * + 1000 / s16SamplingFreq) - + ((32 + + (4 * p_encoder_params->s16NumOfSubBands * + p_encoder_params->s16NumOfChannels) + ((p_encoder_params->s16ChannelMode - 2) * p_encoder_params->s16NumOfSubBands)) / p_encoder_params->s16NumOfBlocks)); - s16FrameLen = 4 + - (4 * p_encoder_params->s16NumOfSubBands * - p_encoder_params->s16NumOfChannels) / - 8 + - (((p_encoder_params->s16ChannelMode - 2) * - p_encoder_params->s16NumOfSubBands) + - (p_encoder_params->s16NumOfBlocks * s16BitPool)) / - 8; + s16FrameLen = + 4 + + (4 * p_encoder_params->s16NumOfSubBands * p_encoder_params->s16NumOfChannels) / 8 + + (((p_encoder_params->s16ChannelMode - 2) * p_encoder_params->s16NumOfSubBands) + + (p_encoder_params->s16NumOfBlocks * s16BitPool)) / + 8; s16BitRate = (8 * s16FrameLen * s16SamplingFreq) / - (p_encoder_params->s16NumOfSubBands * - p_encoder_params->s16NumOfBlocks * 1000); + (p_encoder_params->s16NumOfSubBands * p_encoder_params->s16NumOfBlocks * 1000); - if (s16BitRate > p_encoder_params->u16BitRate) s16BitPool--; + if (s16BitRate > p_encoder_params->u16BitRate) { + s16BitPool--; + } - if (p_encoder_params->s16NumOfSubBands == 8) + if (p_encoder_params->s16NumOfSubBands == 8) { s16BitPool = (s16BitPool > 255) ? 255 : s16BitPool; - else + } else { s16BitPool = (s16BitPool > 128) ? 128 : s16BitPool; + } } else { - s16BitPool = - (int16_t)(((p_encoder_params->s16NumOfSubBands * - p_encoder_params->u16BitRate * 1000) / - (s16SamplingFreq * p_encoder_params->s16NumOfChannels)) - - (((32 / p_encoder_params->s16NumOfChannels) + - (4 * p_encoder_params->s16NumOfSubBands)) / - p_encoder_params->s16NumOfBlocks)); - - p_encoder_params->s16BitPool = - (s16BitPool > (16 * p_encoder_params->s16NumOfSubBands)) - ? (16 * p_encoder_params->s16NumOfSubBands) - : s16BitPool; + s16BitPool = (int16_t)(((p_encoder_params->s16NumOfSubBands * p_encoder_params->u16BitRate * + 1000) / + (s16SamplingFreq * p_encoder_params->s16NumOfChannels)) - + (((32 / p_encoder_params->s16NumOfChannels) + + (4 * p_encoder_params->s16NumOfSubBands)) / + p_encoder_params->s16NumOfBlocks)); + + p_encoder_params->s16BitPool = (s16BitPool > (16 * p_encoder_params->s16NumOfSubBands)) + ? (16 * p_encoder_params->s16NumOfSubBands) + : s16BitPool; } - if (s16BitPool < 0) s16BitPool = 0; + if (s16BitPool < 0) { + s16BitPool = 0; + } - log::verbose("bitpool candidate: {} ({} kbps)", s16BitPool, - p_encoder_params->u16BitRate); + log::verbose("bitpool candidate: {} ({} kbps)", s16BitPool, p_encoder_params->u16BitRate); if (s16BitPool > max_bitpool) { log::verbose("computed bitpool too large ({})", s16BitPool); @@ -310,7 +290,9 @@ static void a2dp_sbc_encoder_update(A2dpCodecConfig* a2dp_codec_config, /* Record that we have increased the bitrate */ protect |= 2; /* Check over-flow */ - if (p_encoder_params->u16BitRate < previous_u16BitRate) protect |= 3; + if (p_encoder_params->u16BitRate < previous_u16BitRate) { + protect |= 3; + } } else { break; } @@ -324,8 +306,8 @@ static void a2dp_sbc_encoder_update(A2dpCodecConfig* a2dp_codec_config, /* Finally update the bitpool in the encoder structure */ p_encoder_params->s16BitPool = s16BitPool; - log::info("final bit rate {}, final bit pool {}", - p_encoder_params->u16BitRate, p_encoder_params->s16BitPool); + log::info("final bit rate {}, final bit pool {}", p_encoder_params->u16BitRate, + p_encoder_params->s16BitPool); /* Reset the SBC encoder */ SBC_Encoder_Init(&a2dp_sbc_encoder_cb.sbc_encoder_params); @@ -338,18 +320,15 @@ void a2dp_sbc_encoder_cleanup(void) { void a2dp_sbc_feeding_reset(void) { /* By default, just clear the entire state */ - memset(&a2dp_sbc_encoder_cb.feeding_state, 0, - sizeof(a2dp_sbc_encoder_cb.feeding_state)); + memset(&a2dp_sbc_encoder_cb.feeding_state, 0, sizeof(a2dp_sbc_encoder_cb.feeding_state)); a2dp_sbc_encoder_cb.feeding_state.bytes_per_tick = - (a2dp_sbc_encoder_cb.feeding_params.sample_rate * - a2dp_sbc_encoder_cb.feeding_params.bits_per_sample / 8 * - a2dp_sbc_encoder_cb.feeding_params.channel_count * - A2DP_SBC_ENCODER_INTERVAL_MS) / - 1000; - - log::info("PCM bytes per tick {}", - a2dp_sbc_encoder_cb.feeding_state.bytes_per_tick); + (a2dp_sbc_encoder_cb.feeding_params.sample_rate * + a2dp_sbc_encoder_cb.feeding_params.bits_per_sample / 8 * + a2dp_sbc_encoder_cb.feeding_params.channel_count * A2DP_SBC_ENCODER_INTERVAL_MS) / + 1000; + + log::info("PCM bytes per tick {}", a2dp_sbc_encoder_cb.feeding_state.bytes_per_tick); } void a2dp_sbc_feeding_flush(void) { @@ -357,22 +336,19 @@ void a2dp_sbc_feeding_flush(void) { a2dp_sbc_encoder_cb.feeding_state.aa_feed_residue = 0; } -uint64_t a2dp_sbc_get_encoder_interval_ms(void) { - return A2DP_SBC_ENCODER_INTERVAL_MS; -} +uint64_t a2dp_sbc_get_encoder_interval_ms(void) { return A2DP_SBC_ENCODER_INTERVAL_MS; } -int a2dp_sbc_get_effective_frame_size() { - return a2dp_sbc_encoder_cb.TxAaMtuSize; -} +int a2dp_sbc_get_effective_frame_size() { return a2dp_sbc_encoder_cb.TxAaMtuSize; } void a2dp_sbc_send_frames(uint64_t timestamp_us) { uint8_t nb_frame = 0; uint8_t nb_iterations = 0; a2dp_sbc_get_num_frame_iteration(&nb_iterations, &nb_frame, timestamp_us); - log::verbose("Sending {} frames per iteration, {} iterations", nb_frame, - nb_iterations); - if (nb_frame == 0) return; + log::verbose("Sending {} frames per iteration, {} iterations", nb_frame, nb_iterations); + if (nb_frame == 0) { + return; + } for (uint8_t counter = 0; counter < nb_iterations; counter++) { // Transcode frame and enqueue @@ -383,33 +359,31 @@ void a2dp_sbc_send_frames(uint64_t timestamp_us) { // Obtains the number of frames to send and number of iterations // to be used. |num_of_iterations| and |num_of_frames| parameters // are used as output param for returning the respective values. -static void a2dp_sbc_get_num_frame_iteration(uint8_t* num_of_iterations, - uint8_t* num_of_frames, +static void a2dp_sbc_get_num_frame_iteration(uint8_t* num_of_iterations, uint8_t* num_of_frames, uint64_t timestamp_us) { uint8_t nof = 0; uint8_t noi = 1; uint32_t projected_nof = 0; - uint32_t pcm_bytes_per_frame = - a2dp_sbc_encoder_cb.sbc_encoder_params.s16NumOfSubBands * - a2dp_sbc_encoder_cb.sbc_encoder_params.s16NumOfBlocks * - a2dp_sbc_encoder_cb.feeding_params.channel_count * - a2dp_sbc_encoder_cb.feeding_params.bits_per_sample / 8; + uint32_t pcm_bytes_per_frame = a2dp_sbc_encoder_cb.sbc_encoder_params.s16NumOfSubBands * + a2dp_sbc_encoder_cb.sbc_encoder_params.s16NumOfBlocks * + a2dp_sbc_encoder_cb.feeding_params.channel_count * + a2dp_sbc_encoder_cb.feeding_params.bits_per_sample / 8; log::verbose("pcm_bytes_per_frame {}", pcm_bytes_per_frame); uint32_t us_this_tick = A2DP_SBC_ENCODER_INTERVAL_MS * 1000; uint64_t now_us = timestamp_us; - if (a2dp_sbc_encoder_cb.feeding_state.last_frame_us != 0) + if (a2dp_sbc_encoder_cb.feeding_state.last_frame_us != 0) { us_this_tick = (now_us - a2dp_sbc_encoder_cb.feeding_state.last_frame_us); + } a2dp_sbc_encoder_cb.feeding_state.last_frame_us = now_us; a2dp_sbc_encoder_cb.feeding_state.counter += - (float)a2dp_sbc_encoder_cb.feeding_state.bytes_per_tick * - (float)us_this_tick / (A2DP_SBC_ENCODER_INTERVAL_MS * 1000); + (float)a2dp_sbc_encoder_cb.feeding_state.bytes_per_tick * (float)us_this_tick / + (A2DP_SBC_ENCODER_INTERVAL_MS * 1000); /* Calculate the number of frames pending for this media tick */ - projected_nof = - a2dp_sbc_encoder_cb.feeding_state.counter / (float)pcm_bytes_per_frame; + projected_nof = a2dp_sbc_encoder_cb.feeding_state.counter / (float)pcm_bytes_per_frame; // Update the stats a2dp_sbc_encoder_cb.stats.media_read_total_expected_frames += projected_nof; @@ -444,8 +418,7 @@ static void a2dp_sbc_get_num_frame_iteration(uint8_t* num_of_iterations, log::error("Audio Congestion (iterations:{} > max ({}))", noi, A2DP_SBC_MAX_PCM_ITER_NUM_PER_TICK); noi = A2DP_SBC_MAX_PCM_ITER_NUM_PER_TICK; - a2dp_sbc_encoder_cb.feeding_state.counter = - noi * nof * (float)pcm_bytes_per_frame; + a2dp_sbc_encoder_cb.feeding_state.counter = noi * nof * (float)pcm_bytes_per_frame; } projected_nof = nof; } else { @@ -467,12 +440,11 @@ static void a2dp_sbc_get_num_frame_iteration(uint8_t* num_of_iterations, projected_nof = MAX_PCM_FRAME_NUM_PER_TICK; a2dp_sbc_encoder_cb.feeding_state.counter = - (float)noi * (float)projected_nof * (float)pcm_bytes_per_frame; + (float)noi * (float)projected_nof * (float)pcm_bytes_per_frame; } nof = projected_nof; } - a2dp_sbc_encoder_cb.feeding_state.counter -= - noi * nof * (float)pcm_bytes_per_frame; + a2dp_sbc_encoder_cb.feeding_state.counter -= noi * nof * (float)pcm_bytes_per_frame; log::verbose("effective num of frames {}, iterations {}", nof, noi); *num_of_frames = nof; @@ -482,8 +454,7 @@ static void a2dp_sbc_get_num_frame_iteration(uint8_t* num_of_iterations, static void a2dp_sbc_encode_frames(uint8_t nb_frame) { SBC_ENC_PARAMS* p_encoder_params = &a2dp_sbc_encoder_cb.sbc_encoder_params; uint8_t remain_nb_frame = nb_frame; - uint16_t blocm_x_subband = - p_encoder_params->s16NumOfSubBands * p_encoder_params->s16NumOfBlocks; + uint16_t blocm_x_subband = p_encoder_params->s16NumOfSubBands * p_encoder_params->s16NumOfBlocks; uint8_t last_frame_len = 0; @@ -517,19 +488,16 @@ static void a2dp_sbc_encode_frames(uint8_t nb_frame) { bytes_read += num_bytes; } else { - log::warn("underflow {}, {}", nb_frame, - a2dp_sbc_encoder_cb.feeding_state.aa_feed_residue); + log::warn("underflow {}, {}", nb_frame, a2dp_sbc_encoder_cb.feeding_state.aa_feed_residue); a2dp_sbc_encoder_cb.feeding_state.counter += - nb_frame * p_encoder_params->s16NumOfSubBands * - p_encoder_params->s16NumOfBlocks * - a2dp_sbc_encoder_cb.feeding_params.channel_count * - a2dp_sbc_encoder_cb.feeding_params.bits_per_sample / 8; + nb_frame * p_encoder_params->s16NumOfSubBands * p_encoder_params->s16NumOfBlocks * + a2dp_sbc_encoder_cb.feeding_params.channel_count * + a2dp_sbc_encoder_cb.feeding_params.bits_per_sample / 8; /* no more pcm to read */ nb_frame = 0; } - } while ( - ((p_buf->len + last_frame_len) < a2dp_sbc_encoder_cb.TxAaMtuSize) && - (p_buf->layer_specific < 0x0F) && nb_frame); + } while (((p_buf->len + last_frame_len) < a2dp_sbc_encoder_cb.TxAaMtuSize) && + (p_buf->layer_specific < 0x0F) && nb_frame); if (p_buf->len) { /* @@ -541,15 +509,15 @@ static void a2dp_sbc_encode_frames(uint8_t nb_frame) { // Timestamp will wrap over to 0 if stream continues on long enough // (>25H @ 48KHz). The parameters are promoted to 64bit to ensure that // no unsigned overflow is triggered as ubsan is always enabled. - a2dp_sbc_encoder_cb.timestamp = - ((uint64_t)a2dp_sbc_encoder_cb.timestamp + - (p_buf->layer_specific * blocm_x_subband)) & UINT32_MAX; + a2dp_sbc_encoder_cb.timestamp = ((uint64_t)a2dp_sbc_encoder_cb.timestamp + + (p_buf->layer_specific * blocm_x_subband)) & + UINT32_MAX; uint8_t done_nb_frame = remain_nb_frame - nb_frame; remain_nb_frame = nb_frame; - if (!a2dp_sbc_encoder_cb.enqueue_callback(p_buf, done_nb_frame, - bytes_read)) + if (!a2dp_sbc_encoder_cb.enqueue_callback(p_buf, done_nb_frame, bytes_read)) { return; + } } else { a2dp_sbc_encoder_cb.stats.media_read_total_dropped_packets++; osi_free(p_buf); @@ -559,19 +527,15 @@ static void a2dp_sbc_encode_frames(uint8_t nb_frame) { static bool a2dp_sbc_read_feeding(uint32_t* bytes_read) { SBC_ENC_PARAMS* p_encoder_params = &a2dp_sbc_encoder_cb.sbc_encoder_params; - uint16_t blocm_x_subband = - p_encoder_params->s16NumOfSubBands * p_encoder_params->s16NumOfBlocks; + uint16_t blocm_x_subband = p_encoder_params->s16NumOfSubBands * p_encoder_params->s16NumOfBlocks; uint32_t read_size; uint32_t sbc_sampling = 48000; uint32_t src_samples; uint16_t bytes_needed = blocm_x_subband * p_encoder_params->s16NumOfChannels * - a2dp_sbc_encoder_cb.feeding_params.bits_per_sample / - 8; + a2dp_sbc_encoder_cb.feeding_params.bits_per_sample / 8; static uint16_t up_sampled_buffer[SBC_MAX_NUM_FRAME * SBC_MAX_NUM_OF_BLOCKS * - SBC_MAX_NUM_OF_CHANNELS * - SBC_MAX_NUM_OF_SUBBANDS * 2]; - static uint16_t read_buffer[SBC_MAX_NUM_FRAME * SBC_MAX_NUM_OF_BLOCKS * - SBC_MAX_NUM_OF_CHANNELS * + SBC_MAX_NUM_OF_CHANNELS * SBC_MAX_NUM_OF_SUBBANDS * 2]; + static uint16_t read_buffer[SBC_MAX_NUM_FRAME * SBC_MAX_NUM_OF_BLOCKS * SBC_MAX_NUM_OF_CHANNELS * SBC_MAX_NUM_OF_SUBBANDS]; uint32_t src_size_used; uint32_t dst_size_used; @@ -598,15 +562,13 @@ static bool a2dp_sbc_read_feeding(uint32_t* bytes_read) { a2dp_sbc_encoder_cb.stats.media_read_total_expected_reads_count++; if (sbc_sampling == a2dp_sbc_encoder_cb.feeding_params.sample_rate) { - read_size = - bytes_needed - a2dp_sbc_encoder_cb.feeding_state.aa_feed_residue; + read_size = bytes_needed - a2dp_sbc_encoder_cb.feeding_state.aa_feed_residue; a2dp_sbc_encoder_cb.stats.media_read_total_expected_read_bytes += read_size; nb_byte_read = a2dp_sbc_encoder_cb.read_callback( - ((uint8_t*)a2dp_sbc_encoder_cb.pcmBuffer) + - a2dp_sbc_encoder_cb.feeding_state.aa_feed_residue, - read_size); - a2dp_sbc_encoder_cb.stats.media_read_total_actual_read_bytes += - nb_byte_read; + ((uint8_t*)a2dp_sbc_encoder_cb.pcmBuffer) + + a2dp_sbc_encoder_cb.feeding_state.aa_feed_residue, + read_size); + a2dp_sbc_encoder_cb.stats.media_read_total_actual_read_bytes += nb_byte_read; *bytes_read = nb_byte_read; if (nb_byte_read != read_size) { @@ -663,12 +625,13 @@ static bool a2dp_sbc_read_feeding(uint32_t* bytes_read) { a2dp_sbc_encoder_cb.stats.media_read_total_expected_read_bytes += read_size; /* Read Data from UIPC channel */ - nb_byte_read = - a2dp_sbc_encoder_cb.read_callback((uint8_t*)read_buffer, read_size); + nb_byte_read = a2dp_sbc_encoder_cb.read_callback((uint8_t*)read_buffer, read_size); a2dp_sbc_encoder_cb.stats.media_read_total_actual_read_bytes += nb_byte_read; if (nb_byte_read < read_size) { - if (nb_byte_read == 0) return false; + if (nb_byte_read == 0) { + return false; + } /* Fill the unfilled part of the read buffer with silence (0) */ memset(((uint8_t*)read_buffer) + nb_byte_read, 0, read_size - nb_byte_read); @@ -677,8 +640,7 @@ static bool a2dp_sbc_read_feeding(uint32_t* bytes_read) { a2dp_sbc_encoder_cb.stats.media_read_total_actual_reads_count++; /* Initialize PCM up-sampling engine */ - a2dp_sbc_init_up_sample(a2dp_sbc_encoder_cb.feeding_params.sample_rate, - sbc_sampling, + a2dp_sbc_init_up_sample(a2dp_sbc_encoder_cb.feeding_params.sample_rate, sbc_sampling, a2dp_sbc_encoder_cb.feeding_params.bits_per_sample, a2dp_sbc_encoder_cb.feeding_params.channel_count); @@ -687,36 +649,33 @@ static bool a2dp_sbc_read_feeding(uint32_t* bytes_read) { * The output PCM buffer will be stereo, 16 bit per sample. */ dst_size_used = a2dp_sbc_up_sample( - (uint8_t*)read_buffer, - (uint8_t*)up_sampled_buffer + - a2dp_sbc_encoder_cb.feeding_state.aa_feed_residue, - nb_byte_read, sizeof(up_sampled_buffer) - - a2dp_sbc_encoder_cb.feeding_state.aa_feed_residue, - &src_size_used); + (uint8_t*)read_buffer, + (uint8_t*)up_sampled_buffer + a2dp_sbc_encoder_cb.feeding_state.aa_feed_residue, + nb_byte_read, + sizeof(up_sampled_buffer) - a2dp_sbc_encoder_cb.feeding_state.aa_feed_residue, + &src_size_used); /* update the residue */ a2dp_sbc_encoder_cb.feeding_state.aa_feed_residue += dst_size_used; /* only copy the pcm sample when we have up-sampled enough PCM */ - if (a2dp_sbc_encoder_cb.feeding_state.aa_feed_residue < bytes_needed) + if (a2dp_sbc_encoder_cb.feeding_state.aa_feed_residue < bytes_needed) { return false; + } /* Copy the output pcm samples in SBC encoding buffer */ - memcpy((uint8_t*)a2dp_sbc_encoder_cb.pcmBuffer, (uint8_t*)up_sampled_buffer, - bytes_needed); + memcpy((uint8_t*)a2dp_sbc_encoder_cb.pcmBuffer, (uint8_t*)up_sampled_buffer, bytes_needed); /* update the residue */ a2dp_sbc_encoder_cb.feeding_state.aa_feed_residue -= bytes_needed; if (a2dp_sbc_encoder_cb.feeding_state.aa_feed_residue != 0) { - memcpy((uint8_t*)up_sampled_buffer, - (uint8_t*)up_sampled_buffer + bytes_needed, + memcpy((uint8_t*)up_sampled_buffer, (uint8_t*)up_sampled_buffer + bytes_needed, a2dp_sbc_encoder_cb.feeding_state.aa_feed_residue); } return true; } -static uint16_t adjust_effective_mtu( - const tA2DP_ENCODER_INIT_PEER_PARAMS& peer_params) { +static uint16_t adjust_effective_mtu(const tA2DP_ENCODER_INIT_PEER_PARAMS& peer_params) { uint16_t mtu_size = A2DP_SBC_BUFFER_SIZE - A2DP_SBC_OFFSET - sizeof(BT_HDR); if (mtu_size > peer_params.peer_mtu) { mtu_size = peer_params.peer_mtu; @@ -728,8 +687,7 @@ static uint16_t adjust_effective_mtu( // exceeds the 2DH5 packet size. log::verbose("The remote device is EDR but does not support 3 Mbps"); if (mtu_size > MAX_2MBPS_AVDTP_MTU) { - log::warn("Restricting AVDTP MTU size from {} to {}", mtu_size, - MAX_2MBPS_AVDTP_MTU); + log::warn("Restricting AVDTP MTU size from {} to {}", mtu_size, MAX_2MBPS_AVDTP_MTU); mtu_size = MAX_2MBPS_AVDTP_MTU; } } @@ -741,13 +699,11 @@ static uint8_t calculate_max_frames_per_packet(void) { uint16_t result = 0; uint32_t frame_len; - a2dp_sbc_encoder_cb.TxAaMtuSize = - adjust_effective_mtu(a2dp_sbc_encoder_cb.peer_params); + a2dp_sbc_encoder_cb.TxAaMtuSize = adjust_effective_mtu(a2dp_sbc_encoder_cb.peer_params); const uint16_t& effective_mtu_size = a2dp_sbc_encoder_cb.TxAaMtuSize; if (!p_encoder_params->s16NumOfSubBands) { - log::error("SubBands are set to 0, resetting to {}", - SBC_MAX_NUM_OF_SUBBANDS); + log::error("SubBands are set to 0, resetting to {}", SBC_MAX_NUM_OF_SUBBANDS); p_encoder_params->s16NumOfSubBands = SBC_MAX_NUM_OF_SUBBANDS; } if (!p_encoder_params->s16NumOfBlocks) { @@ -755,8 +711,7 @@ static uint8_t calculate_max_frames_per_packet(void) { p_encoder_params->s16NumOfBlocks = SBC_MAX_NUM_OF_BLOCKS; } if (!p_encoder_params->s16NumOfChannels) { - log::error("Channels are set to 0, resetting to {}", - SBC_MAX_NUM_OF_CHANNELS); + log::error("Channels are set to 0, resetting to {}", SBC_MAX_NUM_OF_CHANNELS); p_encoder_params->s16NumOfChannels = SBC_MAX_NUM_OF_CHANNELS; } @@ -809,50 +764,43 @@ static uint32_t a2dp_sbc_frame_length(void) { uint32_t frame_len = 0; log::verbose( - "channel mode: {}, sub-band: {}, number of block: {}, bitpool: {}, " - "sampling frequency: {}, num channels: {}", - p_encoder_params->s16ChannelMode, p_encoder_params->s16NumOfSubBands, - p_encoder_params->s16NumOfBlocks, p_encoder_params->s16BitPool, - p_encoder_params->s16SamplingFreq, p_encoder_params->s16NumOfChannels); + "channel mode: {}, sub-band: {}, number of block: {}, bitpool: {}, " + "sampling frequency: {}, num channels: {}", + p_encoder_params->s16ChannelMode, p_encoder_params->s16NumOfSubBands, + p_encoder_params->s16NumOfBlocks, p_encoder_params->s16BitPool, + p_encoder_params->s16SamplingFreq, p_encoder_params->s16NumOfChannels); switch (p_encoder_params->s16ChannelMode) { case SBC_MONO: FALLTHROUGH_INTENDED; /* FALLTHROUGH */ case SBC_DUAL: frame_len = A2DP_SBC_FRAME_HEADER_SIZE_BYTES + - ((uint32_t)(A2DP_SBC_SCALE_FACTOR_BITS * - p_encoder_params->s16NumOfSubBands * + ((uint32_t)(A2DP_SBC_SCALE_FACTOR_BITS * p_encoder_params->s16NumOfSubBands * p_encoder_params->s16NumOfChannels) / CHAR_BIT) + ((uint32_t)(p_encoder_params->s16NumOfBlocks * - p_encoder_params->s16NumOfChannels * - p_encoder_params->s16BitPool) / + p_encoder_params->s16NumOfChannels * p_encoder_params->s16BitPool) / CHAR_BIT); break; case SBC_STEREO: frame_len = A2DP_SBC_FRAME_HEADER_SIZE_BYTES + - ((uint32_t)(A2DP_SBC_SCALE_FACTOR_BITS * - p_encoder_params->s16NumOfSubBands * + ((uint32_t)(A2DP_SBC_SCALE_FACTOR_BITS * p_encoder_params->s16NumOfSubBands * p_encoder_params->s16NumOfChannels) / CHAR_BIT) + - ((uint32_t)(p_encoder_params->s16NumOfBlocks * - p_encoder_params->s16BitPool) / + ((uint32_t)(p_encoder_params->s16NumOfBlocks * p_encoder_params->s16BitPool) / CHAR_BIT); break; case SBC_JOINT_STEREO: frame_len = A2DP_SBC_FRAME_HEADER_SIZE_BYTES + - ((uint32_t)(A2DP_SBC_SCALE_FACTOR_BITS * - p_encoder_params->s16NumOfSubBands * + ((uint32_t)(A2DP_SBC_SCALE_FACTOR_BITS * p_encoder_params->s16NumOfSubBands * p_encoder_params->s16NumOfChannels) / CHAR_BIT) + ((uint32_t)(p_encoder_params->s16NumOfSubBands + - (p_encoder_params->s16NumOfBlocks * - p_encoder_params->s16BitPool)) / + (p_encoder_params->s16NumOfBlocks * p_encoder_params->s16BitPool)) / CHAR_BIT); break; default: - log::verbose("Invalid channel number: {}", - p_encoder_params->s16ChannelMode); + log::verbose("Invalid channel number: {}", p_encoder_params->s16ChannelMode); break; } log::verbose("calculated frame length: {}", frame_len); @@ -872,45 +820,35 @@ void A2dpCodecConfigSbcSource::debug_codec_dump(int fd) { uint8_t codec_info[AVDT_CODEC_SIZE]; if (copyOutOtaCodecConfig(codec_info)) { - dprintf(fd, - " SBC Block length : %d\n", + dprintf(fd, " SBC Block length : %d\n", A2DP_GetNumberOfBlocksSbc(codec_info)); - dprintf(fd, - " SBC Number of subbands : %d\n", + dprintf(fd, " SBC Number of subbands : %d\n", A2DP_GetNumberOfSubbandsSbc(codec_info)); - dprintf(fd, - " SBC Allocation method : %d\n", + dprintf(fd, " SBC Allocation method : %d\n", A2DP_GetAllocationMethodCodeSbc(codec_info)); - dprintf( - fd, - " SBC Bitpool (min/max) : %d / %d\n", - A2DP_GetMinBitpoolSbc(codec_info), A2DP_GetMaxBitpoolSbc(codec_info)); + dprintf(fd, " SBC Bitpool (min/max) : %d / %d\n", + A2DP_GetMinBitpoolSbc(codec_info), A2DP_GetMaxBitpoolSbc(codec_info)); } - dprintf(fd, " Encoder interval (ms): %" PRIu64 "\n", - a2dp_sbc_get_encoder_interval_ms()); + dprintf(fd, " Encoder interval (ms): %" PRIu64 "\n", a2dp_sbc_get_encoder_interval_ms()); dprintf(fd, " Effective MTU: %d\n", a2dp_sbc_get_effective_frame_size()); dprintf(fd, " Packet counts (expected/dropped) : %zu / " "%zu\n", - stats->media_read_total_expected_packets, - stats->media_read_total_dropped_packets); + stats->media_read_total_expected_packets, stats->media_read_total_dropped_packets); dprintf(fd, " PCM read counts (expected/actual) : %zu / " "%zu\n", - stats->media_read_total_expected_reads_count, - stats->media_read_total_actual_reads_count); + stats->media_read_total_expected_reads_count, stats->media_read_total_actual_reads_count); dprintf(fd, " PCM read bytes (expected/actual) : %zu / " "%zu\n", - stats->media_read_total_expected_read_bytes, - stats->media_read_total_actual_read_bytes); + stats->media_read_total_expected_read_bytes, stats->media_read_total_actual_read_bytes); dprintf(fd, " Frames counts (expected/dropped) : %zu / " "%zu\n", - stats->media_read_total_expected_frames, - stats->media_read_total_dropped_frames); + stats->media_read_total_expected_frames, stats->media_read_total_dropped_frames); } diff --git a/system/stack/a2dp/a2dp_sbc_up_sample.cc b/system/stack/a2dp/a2dp_sbc_up_sample.cc index 28cac858596..a3fc8930288 100644 --- a/system/stack/a2dp/a2dp_sbc_up_sample.cc +++ b/system/stack/a2dp/a2dp_sbc_up_sample.cc @@ -25,8 +25,8 @@ #include "a2dp_sbc_up_sample.h" -typedef int(tA2DP_SBC_ACT)(void* p_src, void* p_dst, uint32_t src_samples, - uint32_t dst_samples, uint32_t* p_ret); +typedef int(tA2DP_SBC_ACT)(void* p_src, void* p_dst, uint32_t src_samples, uint32_t dst_samples, + uint32_t* p_ret); typedef struct { int32_t cur_pos; /* current position */ @@ -56,8 +56,7 @@ tA2DP_SBC_UPS_CB a2dp_sbc_ups_cb; * Returns none * ******************************************************************************/ -void a2dp_sbc_init_up_sample(uint32_t src_sps, uint32_t dst_sps, uint8_t bits, - uint8_t n_channels) { +void a2dp_sbc_init_up_sample(uint32_t src_sps, uint32_t dst_sps, uint8_t bits, uint8_t n_channels) { a2dp_sbc_ups_cb.cur_pos = -1; a2dp_sbc_ups_cb.src_sps = src_sps; a2dp_sbc_ups_cb.dst_sps = dst_sps; @@ -111,8 +110,8 @@ void a2dp_sbc_init_up_sample(uint32_t src_sps, uint32_t dst_sps, uint8_t bits, * The number of bytes used in p_src (in *p_ret) * ******************************************************************************/ -int a2dp_sbc_up_sample(void* p_src, void* p_dst, uint32_t src_samples, - uint32_t dst_samples, uint32_t* p_ret) { +int a2dp_sbc_up_sample(void* p_src, void* p_dst, uint32_t src_samples, uint32_t dst_samples, + uint32_t* p_ret) { uint32_t src; uint32_t dst; @@ -145,8 +144,8 @@ int a2dp_sbc_up_sample(void* p_src, void* p_dst, uint32_t src_samples, * The number of bytes used in p_src (in *p_ret) * ******************************************************************************/ -int a2dp_sbc_up_sample_16s(void* p_src, void* p_dst, uint32_t src_samples, - uint32_t dst_samples, uint32_t* p_ret) { +int a2dp_sbc_up_sample_16s(void* p_src, void* p_dst, uint32_t src_samples, uint32_t dst_samples, + uint32_t* p_ret) { int16_t* p_src_tmp = (int16_t*)p_src; int16_t* p_dst_tmp = (int16_t*)p_dst; int16_t* p_worker1 = &a2dp_sbc_ups_cb.worker1; @@ -179,10 +178,12 @@ int a2dp_sbc_up_sample_16s(void* p_src, void* p_dst, uint32_t src_samples, a2dp_sbc_ups_cb.cur_pos += dst_sps; } - if (a2dp_sbc_ups_cb.cur_pos == (int32_t)dst_sps) a2dp_sbc_ups_cb.cur_pos = 0; + if (a2dp_sbc_ups_cb.cur_pos == (int32_t)dst_sps) { + a2dp_sbc_ups_cb.cur_pos = 0; + } *p_ret = ((char*)p_src_tmp - (char*)p_src); - return ((char*)p_dst_tmp - (char*)p_dst); + return (char*)p_dst_tmp - (char*)p_dst; } /******************************************************************************* @@ -204,8 +205,8 @@ int a2dp_sbc_up_sample_16s(void* p_src, void* p_dst, uint32_t src_samples, * The number of bytes used in p_src (in *p_ret) * ******************************************************************************/ -int a2dp_sbc_up_sample_16m(void* p_src, void* p_dst, uint32_t src_samples, - uint32_t dst_samples, uint32_t* p_ret) { +int a2dp_sbc_up_sample_16m(void* p_src, void* p_dst, uint32_t src_samples, uint32_t dst_samples, + uint32_t* p_ret) { int16_t* p_src_tmp = (int16_t*)p_src; int16_t* p_dst_tmp = (int16_t*)p_dst; int16_t* p_worker = &a2dp_sbc_ups_cb.worker1; @@ -239,10 +240,12 @@ int a2dp_sbc_up_sample_16m(void* p_src, void* p_dst, uint32_t src_samples, a2dp_sbc_ups_cb.cur_pos += dst_sps; } - if (a2dp_sbc_ups_cb.cur_pos == (int32_t)dst_sps) a2dp_sbc_ups_cb.cur_pos = 0; + if (a2dp_sbc_ups_cb.cur_pos == (int32_t)dst_sps) { + a2dp_sbc_ups_cb.cur_pos = 0; + } *p_ret = ((char*)p_src_tmp - (char*)p_src); - return ((char*)p_dst_tmp - (char*)p_dst); + return (char*)p_dst_tmp - (char*)p_dst; } /******************************************************************************* @@ -264,8 +267,8 @@ int a2dp_sbc_up_sample_16m(void* p_src, void* p_dst, uint32_t src_samples, * The number of bytes used in p_src (in *p_ret) * ******************************************************************************/ -int a2dp_sbc_up_sample_8s(void* p_src, void* p_dst, uint32_t src_samples, - uint32_t dst_samples, uint32_t* p_ret) { +int a2dp_sbc_up_sample_8s(void* p_src, void* p_dst, uint32_t src_samples, uint32_t dst_samples, + uint32_t* p_ret) { uint8_t* p_src_tmp = (uint8_t*)p_src; int16_t* p_dst_tmp = (int16_t*)p_dst; int16_t* p_worker1 = &a2dp_sbc_ups_cb.worker1; @@ -304,10 +307,12 @@ int a2dp_sbc_up_sample_8s(void* p_src, void* p_dst, uint32_t src_samples, a2dp_sbc_ups_cb.cur_pos += dst_sps; } - if (a2dp_sbc_ups_cb.cur_pos == (int32_t)dst_sps) a2dp_sbc_ups_cb.cur_pos = 0; + if (a2dp_sbc_ups_cb.cur_pos == (int32_t)dst_sps) { + a2dp_sbc_ups_cb.cur_pos = 0; + } *p_ret = ((char*)p_src_tmp - (char*)p_src); - return ((char*)p_dst_tmp - (char*)p_dst); + return (char*)p_dst_tmp - (char*)p_dst; } /******************************************************************************* @@ -328,8 +333,8 @@ int a2dp_sbc_up_sample_8s(void* p_src, void* p_dst, uint32_t src_samples, * The number of bytes used in p_src (in *p_ret) * ******************************************************************************/ -int a2dp_sbc_up_sample_8m(void* p_src, void* p_dst, uint32_t src_samples, - uint32_t dst_samples, uint32_t* p_ret) { +int a2dp_sbc_up_sample_8m(void* p_src, void* p_dst, uint32_t src_samples, uint32_t dst_samples, + uint32_t* p_ret) { uint8_t* p_src_tmp = (uint8_t*)p_src; int16_t* p_dst_tmp = (int16_t*)p_dst; int16_t* p_worker = &a2dp_sbc_ups_cb.worker1; @@ -363,8 +368,10 @@ int a2dp_sbc_up_sample_8m(void* p_src, void* p_dst, uint32_t src_samples, a2dp_sbc_ups_cb.cur_pos += dst_sps; } - if (a2dp_sbc_ups_cb.cur_pos == (int32_t)dst_sps) a2dp_sbc_ups_cb.cur_pos = 0; + if (a2dp_sbc_ups_cb.cur_pos == (int32_t)dst_sps) { + a2dp_sbc_ups_cb.cur_pos = 0; + } *p_ret = ((char*)p_src_tmp - (char*)p_src); - return ((char*)p_dst_tmp - (char*)p_dst); + return (char*)p_dst_tmp - (char*)p_dst; } diff --git a/system/stack/a2dp/a2dp_vendor.cc b/system/stack/a2dp/a2dp_vendor.cc index 95093dfb515..fd7e0a6f2ad 100644 --- a/system/stack/a2dp/a2dp_vendor.cc +++ b/system/stack/a2dp/a2dp_vendor.cc @@ -34,14 +34,12 @@ bool A2DP_IsVendorSourceCodecValid(const uint8_t* p_codec_info) { uint16_t codec_id = A2DP_VendorCodecGetCodecId(p_codec_info); // Check for aptX - if (vendor_id == A2DP_APTX_VENDOR_ID && - codec_id == A2DP_APTX_CODEC_ID_BLUETOOTH) { + if (vendor_id == A2DP_APTX_VENDOR_ID && codec_id == A2DP_APTX_CODEC_ID_BLUETOOTH) { return A2DP_IsVendorSourceCodecValidAptx(p_codec_info); } // Check for aptX-HD - if (vendor_id == A2DP_APTX_HD_VENDOR_ID && - codec_id == A2DP_APTX_HD_CODEC_ID_BLUETOOTH) { + if (vendor_id == A2DP_APTX_HD_VENDOR_ID && codec_id == A2DP_APTX_HD_CODEC_ID_BLUETOOTH) { return A2DP_IsVendorSourceCodecValidAptxHd(p_codec_info); } @@ -105,14 +103,12 @@ bool A2DP_IsVendorPeerSinkCodecValid(const uint8_t* p_codec_info) { uint16_t codec_id = A2DP_VendorCodecGetCodecId(p_codec_info); // Check for aptX - if (vendor_id == A2DP_APTX_VENDOR_ID && - codec_id == A2DP_APTX_CODEC_ID_BLUETOOTH) { + if (vendor_id == A2DP_APTX_VENDOR_ID && codec_id == A2DP_APTX_CODEC_ID_BLUETOOTH) { return A2DP_IsVendorPeerSinkCodecValidAptx(p_codec_info); } // Check for aptX-HD - if (vendor_id == A2DP_APTX_HD_VENDOR_ID && - codec_id == A2DP_APTX_HD_CODEC_ID_BLUETOOTH) { + if (vendor_id == A2DP_APTX_HD_VENDOR_ID && codec_id == A2DP_APTX_HD_CODEC_ID_BLUETOOTH) { return A2DP_IsVendorPeerSinkCodecValidAptxHd(p_codec_info); } @@ -175,8 +171,7 @@ uint32_t A2DP_VendorCodecGetVendorId(const uint8_t* p_codec_info) { const uint8_t* p = &p_codec_info[A2DP_VENDOR_CODEC_VENDOR_ID_START_IDX]; uint32_t vendor_id = (p[0] & 0x000000ff) | ((p[1] << 8) & 0x0000ff00) | - ((p[2] << 16) & 0x00ff0000) | - ((p[3] << 24) & 0xff000000); + ((p[2] << 16) & 0x00ff0000) | ((p[3] << 24) & 0xff000000); return vendor_id; } @@ -189,35 +184,28 @@ uint16_t A2DP_VendorCodecGetCodecId(const uint8_t* p_codec_info) { return codec_id; } -bool A2DP_VendorUsesRtpHeader(bool content_protection_enabled, - const uint8_t* p_codec_info) { +bool A2DP_VendorUsesRtpHeader(bool content_protection_enabled, const uint8_t* p_codec_info) { uint32_t vendor_id = A2DP_VendorCodecGetVendorId(p_codec_info); uint16_t codec_id = A2DP_VendorCodecGetCodecId(p_codec_info); // Check for aptX - if (vendor_id == A2DP_APTX_VENDOR_ID && - codec_id == A2DP_APTX_CODEC_ID_BLUETOOTH) { - return A2DP_VendorUsesRtpHeaderAptx(content_protection_enabled, - p_codec_info); + if (vendor_id == A2DP_APTX_VENDOR_ID && codec_id == A2DP_APTX_CODEC_ID_BLUETOOTH) { + return A2DP_VendorUsesRtpHeaderAptx(content_protection_enabled, p_codec_info); } // Check for aptX-HD - if (vendor_id == A2DP_APTX_HD_VENDOR_ID && - codec_id == A2DP_APTX_HD_CODEC_ID_BLUETOOTH) { - return A2DP_VendorUsesRtpHeaderAptxHd(content_protection_enabled, - p_codec_info); + if (vendor_id == A2DP_APTX_HD_VENDOR_ID && codec_id == A2DP_APTX_HD_CODEC_ID_BLUETOOTH) { + return A2DP_VendorUsesRtpHeaderAptxHd(content_protection_enabled, p_codec_info); } // Check for LDAC if (vendor_id == A2DP_LDAC_VENDOR_ID && codec_id == A2DP_LDAC_CODEC_ID) { - return A2DP_VendorUsesRtpHeaderLdac(content_protection_enabled, - p_codec_info); + return A2DP_VendorUsesRtpHeaderLdac(content_protection_enabled, p_codec_info); } // Check for Opus if (vendor_id == A2DP_OPUS_VENDOR_ID && codec_id == A2DP_OPUS_CODEC_ID) { - return A2DP_VendorUsesRtpHeaderOpus(content_protection_enabled, - p_codec_info); + return A2DP_VendorUsesRtpHeaderOpus(content_protection_enabled, p_codec_info); } // Add checks based on @@ -230,14 +218,12 @@ const char* A2DP_VendorCodecName(const uint8_t* p_codec_info) { uint16_t codec_id = A2DP_VendorCodecGetCodecId(p_codec_info); // Check for aptX - if (vendor_id == A2DP_APTX_VENDOR_ID && - codec_id == A2DP_APTX_CODEC_ID_BLUETOOTH) { + if (vendor_id == A2DP_APTX_VENDOR_ID && codec_id == A2DP_APTX_CODEC_ID_BLUETOOTH) { return A2DP_VendorCodecNameAptx(p_codec_info); } // Check for aptX-HD - if (vendor_id == A2DP_APTX_HD_VENDOR_ID && - codec_id == A2DP_APTX_HD_CODEC_ID_BLUETOOTH) { + if (vendor_id == A2DP_APTX_HD_VENDOR_ID && codec_id == A2DP_APTX_HD_CODEC_ID_BLUETOOTH) { return A2DP_VendorCodecNameAptxHd(p_codec_info); } @@ -256,13 +242,11 @@ const char* A2DP_VendorCodecName(const uint8_t* p_codec_info) { return "UNKNOWN VENDOR CODEC"; } -bool A2DP_VendorCodecTypeEquals(const uint8_t* p_codec_info_a, - const uint8_t* p_codec_info_b) { +bool A2DP_VendorCodecTypeEquals(const uint8_t* p_codec_info_a, const uint8_t* p_codec_info_b) { tA2DP_CODEC_TYPE codec_type_a = A2DP_GetCodecType(p_codec_info_a); tA2DP_CODEC_TYPE codec_type_b = A2DP_GetCodecType(p_codec_info_b); - if ((codec_type_a != codec_type_b) || - (codec_type_a != A2DP_MEDIA_CT_NON_A2DP)) { + if ((codec_type_a != codec_type_b) || (codec_type_a != A2DP_MEDIA_CT_NON_A2DP)) { return false; } @@ -271,17 +255,17 @@ bool A2DP_VendorCodecTypeEquals(const uint8_t* p_codec_info_a, uint32_t vendor_id_b = A2DP_VendorCodecGetVendorId(p_codec_info_b); uint16_t codec_id_b = A2DP_VendorCodecGetCodecId(p_codec_info_b); - if (vendor_id_a != vendor_id_b || codec_id_a != codec_id_b) return false; + if (vendor_id_a != vendor_id_b || codec_id_a != codec_id_b) { + return false; + } // Check for aptX - if (vendor_id_a == A2DP_APTX_VENDOR_ID && - codec_id_a == A2DP_APTX_CODEC_ID_BLUETOOTH) { + if (vendor_id_a == A2DP_APTX_VENDOR_ID && codec_id_a == A2DP_APTX_CODEC_ID_BLUETOOTH) { return A2DP_VendorCodecTypeEqualsAptx(p_codec_info_a, p_codec_info_b); } // Check for aptX-HD - if (vendor_id_a == A2DP_APTX_HD_VENDOR_ID && - codec_id_a == A2DP_APTX_HD_CODEC_ID_BLUETOOTH) { + if (vendor_id_a == A2DP_APTX_HD_VENDOR_ID && codec_id_a == A2DP_APTX_HD_CODEC_ID_BLUETOOTH) { return A2DP_VendorCodecTypeEqualsAptxHd(p_codec_info_a, p_codec_info_b); } @@ -301,13 +285,11 @@ bool A2DP_VendorCodecTypeEquals(const uint8_t* p_codec_info_a, return true; } -bool A2DP_VendorCodecEquals(const uint8_t* p_codec_info_a, - const uint8_t* p_codec_info_b) { +bool A2DP_VendorCodecEquals(const uint8_t* p_codec_info_a, const uint8_t* p_codec_info_b) { tA2DP_CODEC_TYPE codec_type_a = A2DP_GetCodecType(p_codec_info_a); tA2DP_CODEC_TYPE codec_type_b = A2DP_GetCodecType(p_codec_info_b); - if ((codec_type_a != codec_type_b) || - (codec_type_a != A2DP_MEDIA_CT_NON_A2DP)) { + if ((codec_type_a != codec_type_b) || (codec_type_a != A2DP_MEDIA_CT_NON_A2DP)) { return false; } @@ -316,17 +298,17 @@ bool A2DP_VendorCodecEquals(const uint8_t* p_codec_info_a, uint32_t vendor_id_b = A2DP_VendorCodecGetVendorId(p_codec_info_b); uint16_t codec_id_b = A2DP_VendorCodecGetCodecId(p_codec_info_b); - if ((vendor_id_a != vendor_id_b) || (codec_id_a != codec_id_b)) return false; + if ((vendor_id_a != vendor_id_b) || (codec_id_a != codec_id_b)) { + return false; + } // Check for aptX - if (vendor_id_a == A2DP_APTX_VENDOR_ID && - codec_id_a == A2DP_APTX_CODEC_ID_BLUETOOTH) { + if (vendor_id_a == A2DP_APTX_VENDOR_ID && codec_id_a == A2DP_APTX_CODEC_ID_BLUETOOTH) { return A2DP_VendorCodecEqualsAptx(p_codec_info_a, p_codec_info_b); } // Check for aptX-HD - if (vendor_id_a == A2DP_APTX_HD_VENDOR_ID && - codec_id_a == A2DP_APTX_HD_CODEC_ID_BLUETOOTH) { + if (vendor_id_a == A2DP_APTX_HD_VENDOR_ID && codec_id_a == A2DP_APTX_HD_CODEC_ID_BLUETOOTH) { return A2DP_VendorCodecEqualsAptxHd(p_codec_info_a, p_codec_info_b); } @@ -351,14 +333,12 @@ int A2DP_VendorGetBitRate(const uint8_t* p_codec_info) { uint16_t codec_id = A2DP_VendorCodecGetCodecId(p_codec_info); // Check for aptX - if (vendor_id == A2DP_APTX_VENDOR_ID && - codec_id == A2DP_APTX_CODEC_ID_BLUETOOTH) { + if (vendor_id == A2DP_APTX_VENDOR_ID && codec_id == A2DP_APTX_CODEC_ID_BLUETOOTH) { return A2DP_VendorGetBitRateAptx(p_codec_info); } // Check for aptX-HD - if (vendor_id == A2DP_APTX_HD_VENDOR_ID && - codec_id == A2DP_APTX_HD_CODEC_ID_BLUETOOTH) { + if (vendor_id == A2DP_APTX_HD_VENDOR_ID && codec_id == A2DP_APTX_HD_CODEC_ID_BLUETOOTH) { return A2DP_VendorGetBitRateAptxHd(p_codec_info); } @@ -382,14 +362,12 @@ int A2DP_VendorGetTrackSampleRate(const uint8_t* p_codec_info) { uint16_t codec_id = A2DP_VendorCodecGetCodecId(p_codec_info); // Check for aptX - if (vendor_id == A2DP_APTX_VENDOR_ID && - codec_id == A2DP_APTX_CODEC_ID_BLUETOOTH) { + if (vendor_id == A2DP_APTX_VENDOR_ID && codec_id == A2DP_APTX_CODEC_ID_BLUETOOTH) { return A2DP_VendorGetTrackSampleRateAptx(p_codec_info); } // Check for aptX-HD - if (vendor_id == A2DP_APTX_HD_VENDOR_ID && - codec_id == A2DP_APTX_HD_CODEC_ID_BLUETOOTH) { + if (vendor_id == A2DP_APTX_HD_VENDOR_ID && codec_id == A2DP_APTX_HD_CODEC_ID_BLUETOOTH) { return A2DP_VendorGetTrackSampleRateAptxHd(p_codec_info); } @@ -413,14 +391,12 @@ int A2DP_VendorGetTrackBitsPerSample(const uint8_t* p_codec_info) { uint16_t codec_id = A2DP_VendorCodecGetCodecId(p_codec_info); // Check for aptX - if (vendor_id == A2DP_APTX_VENDOR_ID && - codec_id == A2DP_APTX_CODEC_ID_BLUETOOTH) { + if (vendor_id == A2DP_APTX_VENDOR_ID && codec_id == A2DP_APTX_CODEC_ID_BLUETOOTH) { return A2DP_VendorGetTrackBitsPerSampleAptx(p_codec_info); } // Check for aptX-HD - if (vendor_id == A2DP_APTX_HD_VENDOR_ID && - codec_id == A2DP_APTX_HD_CODEC_ID_BLUETOOTH) { + if (vendor_id == A2DP_APTX_HD_VENDOR_ID && codec_id == A2DP_APTX_HD_CODEC_ID_BLUETOOTH) { return A2DP_VendorGetTrackBitsPerSampleAptxHd(p_codec_info); } @@ -444,14 +420,12 @@ int A2DP_VendorGetTrackChannelCount(const uint8_t* p_codec_info) { uint16_t codec_id = A2DP_VendorCodecGetCodecId(p_codec_info); // Check for aptX - if (vendor_id == A2DP_APTX_VENDOR_ID && - codec_id == A2DP_APTX_CODEC_ID_BLUETOOTH) { + if (vendor_id == A2DP_APTX_VENDOR_ID && codec_id == A2DP_APTX_CODEC_ID_BLUETOOTH) { return A2DP_VendorGetTrackChannelCountAptx(p_codec_info); } // Check for aptX-HD - if (vendor_id == A2DP_APTX_HD_VENDOR_ID && - codec_id == A2DP_APTX_HD_CODEC_ID_BLUETOOTH) { + if (vendor_id == A2DP_APTX_HD_VENDOR_ID && codec_id == A2DP_APTX_HD_CODEC_ID_BLUETOOTH) { return A2DP_VendorGetTrackChannelCountAptxHd(p_codec_info); } @@ -490,23 +464,19 @@ int A2DP_VendorGetSinkTrackChannelType(const uint8_t* p_codec_info) { return -1; } -bool A2DP_VendorGetPacketTimestamp(const uint8_t* p_codec_info, - const uint8_t* p_data, +bool A2DP_VendorGetPacketTimestamp(const uint8_t* p_codec_info, const uint8_t* p_data, uint32_t* p_timestamp) { uint32_t vendor_id = A2DP_VendorCodecGetVendorId(p_codec_info); uint16_t codec_id = A2DP_VendorCodecGetCodecId(p_codec_info); // Check for aptX - if (vendor_id == A2DP_APTX_VENDOR_ID && - codec_id == A2DP_APTX_CODEC_ID_BLUETOOTH) { + if (vendor_id == A2DP_APTX_VENDOR_ID && codec_id == A2DP_APTX_CODEC_ID_BLUETOOTH) { return A2DP_VendorGetPacketTimestampAptx(p_codec_info, p_data, p_timestamp); } // Check for aptX-HD - if (vendor_id == A2DP_APTX_HD_VENDOR_ID && - codec_id == A2DP_APTX_HD_CODEC_ID_BLUETOOTH) { - return A2DP_VendorGetPacketTimestampAptxHd(p_codec_info, p_data, - p_timestamp); + if (vendor_id == A2DP_APTX_HD_VENDOR_ID && codec_id == A2DP_APTX_HD_CODEC_ID_BLUETOOTH) { + return A2DP_VendorGetPacketTimestampAptxHd(p_codec_info, p_data, p_timestamp); } // Check for LDAC @@ -530,29 +500,23 @@ bool A2DP_VendorBuildCodecHeader(const uint8_t* p_codec_info, BT_HDR* p_buf, uint16_t codec_id = A2DP_VendorCodecGetCodecId(p_codec_info); // Check for aptX - if (vendor_id == A2DP_APTX_VENDOR_ID && - codec_id == A2DP_APTX_CODEC_ID_BLUETOOTH) { - return A2DP_VendorBuildCodecHeaderAptx(p_codec_info, p_buf, - frames_per_packet); + if (vendor_id == A2DP_APTX_VENDOR_ID && codec_id == A2DP_APTX_CODEC_ID_BLUETOOTH) { + return A2DP_VendorBuildCodecHeaderAptx(p_codec_info, p_buf, frames_per_packet); } // Check for aptX-HD - if (vendor_id == A2DP_APTX_HD_VENDOR_ID && - codec_id == A2DP_APTX_HD_CODEC_ID_BLUETOOTH) { - return A2DP_VendorBuildCodecHeaderAptxHd(p_codec_info, p_buf, - frames_per_packet); + if (vendor_id == A2DP_APTX_HD_VENDOR_ID && codec_id == A2DP_APTX_HD_CODEC_ID_BLUETOOTH) { + return A2DP_VendorBuildCodecHeaderAptxHd(p_codec_info, p_buf, frames_per_packet); } // Check for LDAC if (vendor_id == A2DP_LDAC_VENDOR_ID && codec_id == A2DP_LDAC_CODEC_ID) { - return A2DP_VendorBuildCodecHeaderLdac(p_codec_info, p_buf, - frames_per_packet); + return A2DP_VendorBuildCodecHeaderLdac(p_codec_info, p_buf, frames_per_packet); } // Check for Opus if (vendor_id == A2DP_OPUS_VENDOR_ID && codec_id == A2DP_OPUS_CODEC_ID) { - return A2DP_VendorBuildCodecHeaderOpus(p_codec_info, p_buf, - frames_per_packet); + return A2DP_VendorBuildCodecHeaderOpus(p_codec_info, p_buf, frames_per_packet); } // Add checks based on @@ -560,20 +524,17 @@ bool A2DP_VendorBuildCodecHeader(const uint8_t* p_codec_info, BT_HDR* p_buf, return false; } -const tA2DP_ENCODER_INTERFACE* A2DP_VendorGetEncoderInterface( - const uint8_t* p_codec_info) { +const tA2DP_ENCODER_INTERFACE* A2DP_VendorGetEncoderInterface(const uint8_t* p_codec_info) { uint32_t vendor_id = A2DP_VendorCodecGetVendorId(p_codec_info); uint16_t codec_id = A2DP_VendorCodecGetCodecId(p_codec_info); // Check for aptX - if (vendor_id == A2DP_APTX_VENDOR_ID && - codec_id == A2DP_APTX_CODEC_ID_BLUETOOTH) { + if (vendor_id == A2DP_APTX_VENDOR_ID && codec_id == A2DP_APTX_CODEC_ID_BLUETOOTH) { return A2DP_VendorGetEncoderInterfaceAptx(p_codec_info); } // Check for aptX-HD - if (vendor_id == A2DP_APTX_HD_VENDOR_ID && - codec_id == A2DP_APTX_HD_CODEC_ID_BLUETOOTH) { + if (vendor_id == A2DP_APTX_HD_VENDOR_ID && codec_id == A2DP_APTX_HD_CODEC_ID_BLUETOOTH) { return A2DP_VendorGetEncoderInterfaceAptxHd(p_codec_info); } @@ -592,8 +553,7 @@ const tA2DP_ENCODER_INTERFACE* A2DP_VendorGetEncoderInterface( return NULL; } -const tA2DP_DECODER_INTERFACE* A2DP_VendorGetDecoderInterface( - const uint8_t* p_codec_info) { +const tA2DP_DECODER_INTERFACE* A2DP_VendorGetDecoderInterface(const uint8_t* p_codec_info) { uint32_t vendor_id = A2DP_VendorCodecGetVendorId(p_codec_info); uint16_t codec_id = A2DP_VendorCodecGetCodecId(p_codec_info); @@ -618,14 +578,12 @@ bool A2DP_VendorAdjustCodec(uint8_t* p_codec_info) { uint16_t codec_id = A2DP_VendorCodecGetCodecId(p_codec_info); // Check for aptX - if (vendor_id == A2DP_APTX_VENDOR_ID && - codec_id == A2DP_APTX_CODEC_ID_BLUETOOTH) { + if (vendor_id == A2DP_APTX_VENDOR_ID && codec_id == A2DP_APTX_CODEC_ID_BLUETOOTH) { return A2DP_VendorAdjustCodecAptx(p_codec_info); } // Check for aptX-HD - if (vendor_id == A2DP_APTX_HD_VENDOR_ID && - codec_id == A2DP_APTX_HD_CODEC_ID_BLUETOOTH) { + if (vendor_id == A2DP_APTX_HD_VENDOR_ID && codec_id == A2DP_APTX_HD_CODEC_ID_BLUETOOTH) { return A2DP_VendorAdjustCodecAptxHd(p_codec_info); } @@ -644,20 +602,17 @@ bool A2DP_VendorAdjustCodec(uint8_t* p_codec_info) { return false; } -btav_a2dp_codec_index_t A2DP_VendorSourceCodecIndex( - const uint8_t* p_codec_info) { +btav_a2dp_codec_index_t A2DP_VendorSourceCodecIndex(const uint8_t* p_codec_info) { uint32_t vendor_id = A2DP_VendorCodecGetVendorId(p_codec_info); uint16_t codec_id = A2DP_VendorCodecGetCodecId(p_codec_info); // Check for aptX - if (vendor_id == A2DP_APTX_VENDOR_ID && - codec_id == A2DP_APTX_CODEC_ID_BLUETOOTH) { + if (vendor_id == A2DP_APTX_VENDOR_ID && codec_id == A2DP_APTX_CODEC_ID_BLUETOOTH) { return A2DP_VendorSourceCodecIndexAptx(p_codec_info); } // Check for aptX-HD - if (vendor_id == A2DP_APTX_HD_VENDOR_ID && - codec_id == A2DP_APTX_HD_CODEC_ID_BLUETOOTH) { + if (vendor_id == A2DP_APTX_HD_VENDOR_ID && codec_id == A2DP_APTX_HD_CODEC_ID_BLUETOOTH) { return A2DP_VendorSourceCodecIndexAptxHd(p_codec_info); } @@ -729,8 +684,7 @@ const char* A2DP_VendorCodecIndexStr(btav_a2dp_codec_index_t codec_index) { return "UNKNOWN CODEC INDEX"; } -bool A2DP_VendorInitCodecConfig(btav_a2dp_codec_index_t codec_index, - AvdtpSepConfig* p_cfg) { +bool A2DP_VendorInitCodecConfig(btav_a2dp_codec_index_t codec_index, AvdtpSepConfig* p_cfg) { // Add checks based on codec_index switch (codec_index) { case BTAV_A2DP_CODEC_INDEX_SOURCE_SBC: @@ -768,14 +722,12 @@ std::string A2DP_VendorCodecInfoString(const uint8_t* p_codec_info) { uint16_t codec_id = A2DP_VendorCodecGetCodecId(p_codec_info); // Check for aptX - if (vendor_id == A2DP_APTX_VENDOR_ID && - codec_id == A2DP_APTX_CODEC_ID_BLUETOOTH) { + if (vendor_id == A2DP_APTX_VENDOR_ID && codec_id == A2DP_APTX_CODEC_ID_BLUETOOTH) { return A2DP_VendorCodecInfoStringAptx(p_codec_info); } // Check for aptX-HD - if (vendor_id == A2DP_APTX_HD_VENDOR_ID && - codec_id == A2DP_APTX_HD_CODEC_ID_BLUETOOTH) { + if (vendor_id == A2DP_APTX_HD_VENDOR_ID && codec_id == A2DP_APTX_HD_CODEC_ID_BLUETOOTH) { return A2DP_VendorCodecInfoStringAptxHd(p_codec_info); } @@ -791,6 +743,5 @@ std::string A2DP_VendorCodecInfoString(const uint8_t* p_codec_info) { // Add checks based on - return "Unsupported codec vendor_id: " + loghex(vendor_id) + - " codec_id: " + loghex(codec_id); + return "Unsupported codec vendor_id: " + loghex(vendor_id) + " codec_id: " + loghex(codec_id); } diff --git a/system/stack/a2dp/a2dp_vendor_aptx.cc b/system/stack/a2dp/a2dp_vendor_aptx.cc index a5a425f9718..81f94d4412a 100644 --- a/system/stack/a2dp/a2dp_vendor_aptx.cc +++ b/system/stack/a2dp/a2dp_vendor_aptx.cc @@ -50,48 +50,47 @@ typedef struct { /* aptX Source codec capabilities */ static const tA2DP_APTX_CIE a2dp_aptx_source_caps = { - A2DP_APTX_VENDOR_ID, /* vendorId */ - A2DP_APTX_CODEC_ID_BLUETOOTH, /* codecId */ - (A2DP_APTX_SAMPLERATE_44100 | A2DP_APTX_SAMPLERATE_48000), /* sampleRate */ - A2DP_APTX_CHANNELS_STEREO, /* channelMode */ - A2DP_APTX_FUTURE_1, /* future1 */ - A2DP_APTX_FUTURE_2, /* future2 */ - BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16 /* bits_per_sample */ + A2DP_APTX_VENDOR_ID, /* vendorId */ + A2DP_APTX_CODEC_ID_BLUETOOTH, /* codecId */ + (A2DP_APTX_SAMPLERATE_44100 | A2DP_APTX_SAMPLERATE_48000), /* sampleRate */ + A2DP_APTX_CHANNELS_STEREO, /* channelMode */ + A2DP_APTX_FUTURE_1, /* future1 */ + A2DP_APTX_FUTURE_2, /* future2 */ + BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16 /* bits_per_sample */ }; /* Default aptX codec configuration */ static const tA2DP_APTX_CIE a2dp_aptx_default_config = { - A2DP_APTX_VENDOR_ID, /* vendorId */ - A2DP_APTX_CODEC_ID_BLUETOOTH, /* codecId */ - A2DP_APTX_SAMPLERATE_48000, /* sampleRate */ - A2DP_APTX_CHANNELS_STEREO, /* channelMode */ - A2DP_APTX_FUTURE_1, /* future1 */ - A2DP_APTX_FUTURE_2, /* future2 */ - BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16 /* bits_per_sample */ + A2DP_APTX_VENDOR_ID, /* vendorId */ + A2DP_APTX_CODEC_ID_BLUETOOTH, /* codecId */ + A2DP_APTX_SAMPLERATE_48000, /* sampleRate */ + A2DP_APTX_CHANNELS_STEREO, /* channelMode */ + A2DP_APTX_FUTURE_1, /* future1 */ + A2DP_APTX_FUTURE_2, /* future2 */ + BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16 /* bits_per_sample */ }; static const tA2DP_ENCODER_INTERFACE a2dp_encoder_interface_aptx = { - a2dp_vendor_aptx_encoder_init, - a2dp_vendor_aptx_encoder_cleanup, - a2dp_vendor_aptx_feeding_reset, - a2dp_vendor_aptx_feeding_flush, - a2dp_vendor_aptx_get_encoder_interval_ms, - a2dp_vendor_aptx_get_effective_frame_size, - a2dp_vendor_aptx_send_frames, - nullptr // set_transmit_queue_length + a2dp_vendor_aptx_encoder_init, + a2dp_vendor_aptx_encoder_cleanup, + a2dp_vendor_aptx_feeding_reset, + a2dp_vendor_aptx_feeding_flush, + a2dp_vendor_aptx_get_encoder_interval_ms, + a2dp_vendor_aptx_get_effective_frame_size, + a2dp_vendor_aptx_send_frames, + nullptr // set_transmit_queue_length }; -static tA2DP_STATUS A2DP_CodecInfoMatchesCapabilityAptx( - const tA2DP_APTX_CIE* p_cap, const uint8_t* p_codec_info, - bool is_peer_codec_info); +static tA2DP_STATUS A2DP_CodecInfoMatchesCapabilityAptx(const tA2DP_APTX_CIE* p_cap, + const uint8_t* p_codec_info, + bool is_peer_codec_info); // Builds the aptX Media Codec Capabilities byte sequence beginning from the // LOSC octet. |media_type| is the media type |AVDT_MEDIA_TYPE_*|. // |p_ie| is a pointer to the aptX Codec Information Element information. // The result is stored in |p_result|. Returns A2DP_SUCCESS on success, // otherwise the corresponding A2DP error status code. -static tA2DP_STATUS A2DP_BuildInfoAptx(uint8_t media_type, - const tA2DP_APTX_CIE* p_ie, +static tA2DP_STATUS A2DP_BuildInfoAptx(uint8_t media_type, const tA2DP_APTX_CIE* p_ie, uint8_t* p_result) { if (p_ie == NULL || p_result == NULL) { return A2DP_INVALID_PARAMS; @@ -117,38 +116,37 @@ static tA2DP_STATUS A2DP_BuildInfoAptx(uint8_t media_type, // codec capabilities, otherwise is codec configuration. // Returns A2DP_SUCCESS on success, otherwise the corresponding A2DP error // status code. -static tA2DP_STATUS A2DP_ParseInfoAptx(tA2DP_APTX_CIE* p_ie, - const uint8_t* p_codec_info, +static tA2DP_STATUS A2DP_ParseInfoAptx(tA2DP_APTX_CIE* p_ie, const uint8_t* p_codec_info, bool is_capability) { uint8_t losc; uint8_t media_type; tA2DP_CODEC_TYPE codec_type; - if (p_ie == NULL || p_codec_info == NULL) return A2DP_INVALID_PARAMS; + if (p_ie == NULL || p_codec_info == NULL) { + return A2DP_INVALID_PARAMS; + } // Check the codec capability length losc = *p_codec_info++; - if (losc != A2DP_APTX_CODEC_LEN) return A2DP_WRONG_CODEC; + if (losc != A2DP_APTX_CODEC_LEN) { + return A2DP_WRONG_CODEC; + } media_type = (*p_codec_info++) >> 4; codec_type = *p_codec_info++; /* Check the Media Type and Media Codec Type */ - if (media_type != AVDT_MEDIA_TYPE_AUDIO || - codec_type != A2DP_MEDIA_CT_NON_A2DP) { + if (media_type != AVDT_MEDIA_TYPE_AUDIO || codec_type != A2DP_MEDIA_CT_NON_A2DP) { return A2DP_WRONG_CODEC; } // Check the Vendor ID and Codec ID */ - p_ie->vendorId = (*p_codec_info & 0x000000FF) | - (*(p_codec_info + 1) << 8 & 0x0000FF00) | + p_ie->vendorId = (*p_codec_info & 0x000000FF) | (*(p_codec_info + 1) << 8 & 0x0000FF00) | (*(p_codec_info + 2) << 16 & 0x00FF0000) | (*(p_codec_info + 3) << 24 & 0xFF000000); p_codec_info += 4; - p_ie->codecId = - (*p_codec_info & 0x00FF) | (*(p_codec_info + 1) << 8 & 0xFF00); + p_ie->codecId = (*p_codec_info & 0x00FF) | (*(p_codec_info + 1) << 8 & 0xFF00); p_codec_info += 2; - if (p_ie->vendorId != A2DP_APTX_VENDOR_ID || - p_ie->codecId != A2DP_APTX_CODEC_ID_BLUETOOTH) { + if (p_ie->vendorId != A2DP_APTX_VENDOR_ID || p_ie->codecId != A2DP_APTX_CODEC_ID_BLUETOOTH) { return A2DP_WRONG_CODEC; } @@ -159,18 +157,22 @@ static tA2DP_STATUS A2DP_ParseInfoAptx(tA2DP_APTX_CIE* p_ie, if (is_capability) { // NOTE: The checks here are very liberal. We should be using more // pedantic checks specific to the SRC or SNK as specified in the spec. - if (A2DP_BitsSet(p_ie->sampleRate) == A2DP_SET_ZERO_BIT) + if (A2DP_BitsSet(p_ie->sampleRate) == A2DP_SET_ZERO_BIT) { return A2DP_BAD_SAMP_FREQ; - if (A2DP_BitsSet(p_ie->channelMode) == A2DP_SET_ZERO_BIT) + } + if (A2DP_BitsSet(p_ie->channelMode) == A2DP_SET_ZERO_BIT) { return A2DP_BAD_CH_MODE; + } return A2DP_SUCCESS; } - if (A2DP_BitsSet(p_ie->sampleRate) != A2DP_SET_ONE_BIT) + if (A2DP_BitsSet(p_ie->sampleRate) != A2DP_SET_ONE_BIT) { return A2DP_BAD_SAMP_FREQ; - if (A2DP_BitsSet(p_ie->channelMode) != A2DP_SET_ONE_BIT) + } + if (A2DP_BitsSet(p_ie->channelMode) != A2DP_SET_ONE_BIT) { return A2DP_BAD_CH_MODE; + } return A2DP_SUCCESS; } @@ -200,9 +202,9 @@ bool A2DP_IsVendorPeerSinkCodecValidAptx(const uint8_t* p_codec_info) { // is acting as an A2DP source. // Returns A2DP_SUCCESS if the codec configuration matches with capabilities, // otherwise the corresponding A2DP error status code. -UNUSED_ATTR static tA2DP_STATUS A2DP_CodecInfoMatchesCapabilityAptx( - const tA2DP_APTX_CIE* p_cap, const uint8_t* p_codec_info, - bool is_capability) { +UNUSED_ATTR static tA2DP_STATUS A2DP_CodecInfoMatchesCapabilityAptx(const tA2DP_APTX_CIE* p_cap, + const uint8_t* p_codec_info, + bool is_capability) { tA2DP_STATUS status; tA2DP_APTX_CIE cfg_cie; @@ -215,16 +217,18 @@ UNUSED_ATTR static tA2DP_STATUS A2DP_CodecInfoMatchesCapabilityAptx( /* verify that each parameter is in range */ - log::verbose("FREQ peer: 0x{:x}, capability 0x{:x}", cfg_cie.sampleRate, - p_cap->sampleRate); - log::verbose("CH_MODE peer: 0x{:x}, capability 0x{:x}", cfg_cie.channelMode, - p_cap->channelMode); + log::verbose("FREQ peer: 0x{:x}, capability 0x{:x}", cfg_cie.sampleRate, p_cap->sampleRate); + log::verbose("CH_MODE peer: 0x{:x}, capability 0x{:x}", cfg_cie.channelMode, p_cap->channelMode); /* sampling frequency */ - if ((cfg_cie.sampleRate & p_cap->sampleRate) == 0) return A2DP_NS_SAMP_FREQ; + if ((cfg_cie.sampleRate & p_cap->sampleRate) == 0) { + return A2DP_NS_SAMP_FREQ; + } /* channel mode */ - if ((cfg_cie.channelMode & p_cap->channelMode) == 0) return A2DP_NS_CH_MODE; + if ((cfg_cie.channelMode & p_cap->channelMode) == 0) { + return A2DP_NS_CH_MODE; + } return A2DP_SUCCESS; } @@ -235,18 +239,14 @@ bool A2DP_VendorUsesRtpHeaderAptx(bool /* content_protection_enabled */, return false; } -const char* A2DP_VendorCodecNameAptx(const uint8_t* /* p_codec_info */) { - return "aptX"; -} +const char* A2DP_VendorCodecNameAptx(const uint8_t* /* p_codec_info */) { return "aptX"; } -bool A2DP_VendorCodecTypeEqualsAptx(const uint8_t* p_codec_info_a, - const uint8_t* p_codec_info_b) { +bool A2DP_VendorCodecTypeEqualsAptx(const uint8_t* p_codec_info_a, const uint8_t* p_codec_info_b) { tA2DP_APTX_CIE aptx_cie_a; tA2DP_APTX_CIE aptx_cie_b; // Check whether the codec info contains valid data - tA2DP_STATUS a2dp_status = - A2DP_ParseInfoAptx(&aptx_cie_a, p_codec_info_a, true); + tA2DP_STATUS a2dp_status = A2DP_ParseInfoAptx(&aptx_cie_a, p_codec_info_a, true); if (a2dp_status != A2DP_SUCCESS) { log::error("cannot decode codec information: {}", a2dp_status); return false; @@ -260,14 +260,12 @@ bool A2DP_VendorCodecTypeEqualsAptx(const uint8_t* p_codec_info_a, return true; } -bool A2DP_VendorCodecEqualsAptx(const uint8_t* p_codec_info_a, - const uint8_t* p_codec_info_b) { +bool A2DP_VendorCodecEqualsAptx(const uint8_t* p_codec_info_a, const uint8_t* p_codec_info_b) { tA2DP_APTX_CIE aptx_cie_a; tA2DP_APTX_CIE aptx_cie_b; // Check whether the codec info contains valid data - tA2DP_STATUS a2dp_status = - A2DP_ParseInfoAptx(&aptx_cie_a, p_codec_info_a, true); + tA2DP_STATUS a2dp_status = A2DP_ParseInfoAptx(&aptx_cie_a, p_codec_info_a, true); if (a2dp_status != A2DP_SUCCESS) { log::error("cannot decode codec information: {}", a2dp_status); return false; @@ -299,8 +297,12 @@ int A2DP_VendorGetTrackSampleRateAptx(const uint8_t* p_codec_info) { return -1; } - if (aptx_cie.sampleRate == A2DP_APTX_SAMPLERATE_44100) return 44100; - if (aptx_cie.sampleRate == A2DP_APTX_SAMPLERATE_48000) return 48000; + if (aptx_cie.sampleRate == A2DP_APTX_SAMPLERATE_44100) { + return 44100; + } + if (aptx_cie.sampleRate == A2DP_APTX_SAMPLERATE_48000) { + return 48000; + } return -1; } @@ -339,16 +341,14 @@ int A2DP_VendorGetTrackChannelCountAptx(const uint8_t* p_codec_info) { return -1; } -bool A2DP_VendorGetPacketTimestampAptx(const uint8_t* /* p_codec_info */, - const uint8_t* p_data, +bool A2DP_VendorGetPacketTimestampAptx(const uint8_t* /* p_codec_info */, const uint8_t* p_data, uint32_t* p_timestamp) { // TODO: Is this function really codec-specific? *p_timestamp = *(const uint32_t*)p_data; return true; } -bool A2DP_VendorBuildCodecHeaderAptx(const uint8_t* /* p_codec_info */, - BT_HDR* /* p_buf */, +bool A2DP_VendorBuildCodecHeaderAptx(const uint8_t* /* p_codec_info */, BT_HDR* /* p_buf */, uint16_t /* frames_per_packet */) { // Nothing to do return true; @@ -362,8 +362,7 @@ std::string A2DP_VendorCodecInfoStringAptx(const uint8_t* p_codec_info) { a2dp_status = A2DP_ParseInfoAptx(&aptx_cie, p_codec_info, true); if (a2dp_status != A2DP_SUCCESS) { - res << "A2DP_ParseInfoAptx fail: " - << loghex(static_cast(a2dp_status)); + res << "A2DP_ParseInfoAptx fail: " << loghex(static_cast(a2dp_status)); return res.str(); } @@ -372,28 +371,24 @@ std::string A2DP_VendorCodecInfoStringAptx(const uint8_t* p_codec_info) { // Sample frequency field.clear(); AppendField(&field, (aptx_cie.sampleRate == 0), "NONE"); - AppendField(&field, (aptx_cie.sampleRate & A2DP_APTX_SAMPLERATE_44100), - "44100"); - AppendField(&field, (aptx_cie.sampleRate & A2DP_APTX_SAMPLERATE_48000), - "48000"); - res << "\tsamp_freq: " << field << " (" << loghex(aptx_cie.sampleRate) - << ")\n"; + AppendField(&field, (aptx_cie.sampleRate & A2DP_APTX_SAMPLERATE_44100), "44100"); + AppendField(&field, (aptx_cie.sampleRate & A2DP_APTX_SAMPLERATE_48000), "48000"); + res << "\tsamp_freq: " << field << " (" << loghex(aptx_cie.sampleRate) << ")\n"; // Channel mode field.clear(); AppendField(&field, (aptx_cie.channelMode == 0), "NONE"); AppendField(&field, (aptx_cie.channelMode & A2DP_APTX_CHANNELS_MONO), "Mono"); - AppendField(&field, (aptx_cie.channelMode & A2DP_APTX_CHANNELS_STEREO), - "Stereo"); - res << "\tch_mode: " << field << " (" << loghex(aptx_cie.channelMode) - << ")\n"; + AppendField(&field, (aptx_cie.channelMode & A2DP_APTX_CHANNELS_STEREO), "Stereo"); + res << "\tch_mode: " << field << " (" << loghex(aptx_cie.channelMode) << ")\n"; return res.str(); } -const tA2DP_ENCODER_INTERFACE* A2DP_VendorGetEncoderInterfaceAptx( - const uint8_t* p_codec_info) { - if (!A2DP_IsVendorSourceCodecValidAptx(p_codec_info)) return NULL; +const tA2DP_ENCODER_INTERFACE* A2DP_VendorGetEncoderInterfaceAptx(const uint8_t* p_codec_info) { + if (!A2DP_IsVendorSourceCodecValidAptx(p_codec_info)) { + return NULL; + } return &a2dp_encoder_interface_aptx; } @@ -402,30 +397,29 @@ bool A2DP_VendorAdjustCodecAptx(uint8_t* p_codec_info) { tA2DP_APTX_CIE cfg_cie; // Nothing to do: just verify the codec info is valid - if (A2DP_ParseInfoAptx(&cfg_cie, p_codec_info, true) != A2DP_SUCCESS) + if (A2DP_ParseInfoAptx(&cfg_cie, p_codec_info, true) != A2DP_SUCCESS) { return false; + } return true; } -btav_a2dp_codec_index_t A2DP_VendorSourceCodecIndexAptx( - const uint8_t* /* p_codec_info */) { +btav_a2dp_codec_index_t A2DP_VendorSourceCodecIndexAptx(const uint8_t* /* p_codec_info */) { return BTAV_A2DP_CODEC_INDEX_SOURCE_APTX; } const char* A2DP_VendorCodecIndexStrAptx(void) { return "aptX"; } bool A2DP_VendorInitCodecConfigAptx(AvdtpSepConfig* p_cfg) { - if (A2DP_BuildInfoAptx(AVDT_MEDIA_TYPE_AUDIO, &a2dp_aptx_source_caps, - p_cfg->codec_info) != A2DP_SUCCESS) { + if (A2DP_BuildInfoAptx(AVDT_MEDIA_TYPE_AUDIO, &a2dp_aptx_source_caps, p_cfg->codec_info) != + A2DP_SUCCESS) { return false; } return true; } -A2dpCodecConfigAptx::A2dpCodecConfigAptx( - btav_a2dp_codec_priority_t codec_priority) +A2dpCodecConfigAptx::A2dpCodecConfigAptx(btav_a2dp_codec_priority_t codec_priority) : A2dpCodecConfig(BTAV_A2DP_CODEC_INDEX_SOURCE_APTX, A2DP_CODEC_ID_APTX, A2DP_VendorCodecIndexStrAptx(), codec_priority) { // Compute the local capability @@ -435,8 +429,7 @@ A2dpCodecConfigAptx::A2dpCodecConfigAptx( if (a2dp_aptx_source_caps.sampleRate & A2DP_APTX_SAMPLERATE_48000) { codec_local_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_48000; } - codec_local_capability_.bits_per_sample = - a2dp_aptx_source_caps.bits_per_sample; + codec_local_capability_.bits_per_sample = a2dp_aptx_source_caps.bits_per_sample; if (a2dp_aptx_source_caps.channelMode & A2DP_APTX_CHANNELS_MONO) { codec_local_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_MONO; } @@ -448,7 +441,9 @@ A2dpCodecConfigAptx::A2dpCodecConfigAptx( A2dpCodecConfigAptx::~A2dpCodecConfigAptx() {} bool A2dpCodecConfigAptx::init() { - if (!isValid()) return false; + if (!isValid()) { + return false; + } // Load the encoder if (A2DP_VendorLoadEncoderAptx() != LOAD_SUCCESS) { @@ -466,8 +461,7 @@ bool A2dpCodecConfigAptx::useRtpHeaderMarkerBit() const { return false; } // The result is stored in |p_result| and p_codec_config|. // Returns true if a selection was made, otherwise false. // -static bool select_best_sample_rate(uint8_t sampleRate, - tA2DP_APTX_CIE* p_result, +static bool select_best_sample_rate(uint8_t sampleRate, tA2DP_APTX_CIE* p_result, btav_a2dp_codec_config_t* p_codec_config) { if (sampleRate & A2DP_APTX_SAMPLERATE_48000) { p_result->sampleRate = A2DP_APTX_SAMPLERATE_48000; @@ -488,9 +482,9 @@ static bool select_best_sample_rate(uint8_t sampleRate, // The result is stored in |p_result| and |p_codec_config|. // Returns true if a selection was made, otherwise false. // -static bool select_audio_sample_rate( - const btav_a2dp_codec_config_t* p_codec_audio_config, uint8_t sampleRate, - tA2DP_APTX_CIE* p_result, btav_a2dp_codec_config_t* p_codec_config) { +static bool select_audio_sample_rate(const btav_a2dp_codec_config_t* p_codec_audio_config, + uint8_t sampleRate, tA2DP_APTX_CIE* p_result, + btav_a2dp_codec_config_t* p_codec_config) { switch (p_codec_audio_config->sample_rate) { case BTAV_A2DP_CODEC_SAMPLE_RATE_44100: if (sampleRate & A2DP_APTX_SAMPLERATE_44100) { @@ -523,8 +517,7 @@ static bool select_audio_sample_rate( // The result is stored in |p_codec_config|. // Returns true if a selection was made, otherwise false. // -static bool select_best_bits_per_sample( - btav_a2dp_codec_config_t* p_codec_config) { +static bool select_best_bits_per_sample(btav_a2dp_codec_config_t* p_codec_config) { p_codec_config->bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16; return true; } @@ -534,9 +527,8 @@ static bool select_best_bits_per_sample( // The result is stored in |p_codec_config|. // Returns true if a selection was made, otherwise false. // -static bool select_audio_bits_per_sample( - const btav_a2dp_codec_config_t* p_codec_audio_config, - btav_a2dp_codec_config_t* p_codec_config) { +static bool select_audio_bits_per_sample(const btav_a2dp_codec_config_t* p_codec_audio_config, + btav_a2dp_codec_config_t* p_codec_config) { switch (p_codec_audio_config->bits_per_sample) { case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16: p_codec_config->bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16; @@ -554,8 +546,7 @@ static bool select_audio_bits_per_sample( // The result is stored in |p_result| and |p_codec_config|. // Returns true if a selection was made, otherwise false. // -static bool select_best_channel_mode(uint8_t channelMode, - tA2DP_APTX_CIE* p_result, +static bool select_best_channel_mode(uint8_t channelMode, tA2DP_APTX_CIE* p_result, btav_a2dp_codec_config_t* p_codec_config) { if (channelMode & A2DP_APTX_CHANNELS_STEREO) { p_result->channelMode = A2DP_APTX_CHANNELS_STEREO; @@ -576,9 +567,9 @@ static bool select_best_channel_mode(uint8_t channelMode, // The result is stored in |p_result| and |p_codec_config|. // Returns true if a selection was made, otherwise false. // -static bool select_audio_channel_mode( - const btav_a2dp_codec_config_t* p_codec_audio_config, uint8_t channelMode, - tA2DP_APTX_CIE* p_result, btav_a2dp_codec_config_t* p_codec_config) { +static bool select_audio_channel_mode(const btav_a2dp_codec_config_t* p_codec_audio_config, + uint8_t channelMode, tA2DP_APTX_CIE* p_result, + btav_a2dp_codec_config_t* p_codec_config) { switch (p_codec_audio_config->channel_mode) { case BTAV_A2DP_CODEC_CHANNEL_MODE_MONO: if (channelMode & A2DP_APTX_CHANNELS_MONO) { @@ -601,8 +592,7 @@ static bool select_audio_channel_mode( return false; } -bool A2dpCodecConfigAptx::setCodecConfig(const uint8_t* p_peer_codec_info, - bool is_capability, +bool A2dpCodecConfigAptx::setCodecConfig(const uint8_t* p_peer_codec_info, bool is_capability, uint8_t* p_result_codec_config) { std::lock_guard lock(codec_mutex_); tA2DP_APTX_CIE peer_info_cie; @@ -616,8 +606,7 @@ bool A2dpCodecConfigAptx::setCodecConfig(const uint8_t* p_peer_codec_info, // Save the internal state btav_a2dp_codec_config_t saved_codec_config = codec_config_; btav_a2dp_codec_config_t saved_codec_capability = codec_capability_; - btav_a2dp_codec_config_t saved_codec_selectable_capability = - codec_selectable_capability_; + btav_a2dp_codec_config_t saved_codec_selectable_capability = codec_selectable_capability_; btav_a2dp_codec_config_t saved_codec_user_config = codec_user_config_; btav_a2dp_codec_config_t saved_codec_audio_config = codec_audio_config_; uint8_t saved_ota_codec_config[AVDT_CODEC_SIZE]; @@ -626,11 +615,9 @@ bool A2dpCodecConfigAptx::setCodecConfig(const uint8_t* p_peer_codec_info, memcpy(saved_ota_codec_config, ota_codec_config_, sizeof(ota_codec_config_)); memcpy(saved_ota_codec_peer_capability, ota_codec_peer_capability_, sizeof(ota_codec_peer_capability_)); - memcpy(saved_ota_codec_peer_config, ota_codec_peer_config_, - sizeof(ota_codec_peer_config_)); + memcpy(saved_ota_codec_peer_config, ota_codec_peer_config_, sizeof(ota_codec_peer_config_)); - tA2DP_STATUS status = - A2DP_ParseInfoAptx(&peer_info_cie, p_peer_codec_info, is_capability); + tA2DP_STATUS status = A2DP_ParseInfoAptx(&peer_info_cie, p_peer_codec_info, is_capability); if (status != A2DP_SUCCESS) { log::error("can't parse peer's capabilities: error = {}", status); goto fail; @@ -679,45 +666,44 @@ bool A2dpCodecConfigAptx::setCodecConfig(const uint8_t* p_peer_codec_info, do { // Compute the selectable capability if (sampleRate & A2DP_APTX_SAMPLERATE_44100) { - codec_selectable_capability_.sample_rate |= - BTAV_A2DP_CODEC_SAMPLE_RATE_44100; + codec_selectable_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_44100; } if (sampleRate & A2DP_APTX_SAMPLERATE_48000) { - codec_selectable_capability_.sample_rate |= - BTAV_A2DP_CODEC_SAMPLE_RATE_48000; + codec_selectable_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_48000; } - if (codec_config_.sample_rate != BTAV_A2DP_CODEC_SAMPLE_RATE_NONE) break; + if (codec_config_.sample_rate != BTAV_A2DP_CODEC_SAMPLE_RATE_NONE) { + break; + } // Compute the common capability - if (sampleRate & A2DP_APTX_SAMPLERATE_44100) + if (sampleRate & A2DP_APTX_SAMPLERATE_44100) { codec_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_44100; - if (sampleRate & A2DP_APTX_SAMPLERATE_48000) + } + if (sampleRate & A2DP_APTX_SAMPLERATE_48000) { codec_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_48000; + } // No user preference - try the codec audio config - if (select_audio_sample_rate(&codec_audio_config_, sampleRate, - &result_config_cie, &codec_config_)) { + if (select_audio_sample_rate(&codec_audio_config_, sampleRate, &result_config_cie, + &codec_config_)) { break; } // No user preference - try the default config - if (select_best_sample_rate( - a2dp_aptx_default_config.sampleRate & peer_info_cie.sampleRate, - &result_config_cie, &codec_config_)) { + if (select_best_sample_rate(a2dp_aptx_default_config.sampleRate & peer_info_cie.sampleRate, + &result_config_cie, &codec_config_)) { break; } // No user preference - use the best match - if (select_best_sample_rate(sampleRate, &result_config_cie, - &codec_config_)) { + if (select_best_sample_rate(sampleRate, &result_config_cie, &codec_config_)) { break; } } while (false); if (codec_config_.sample_rate == BTAV_A2DP_CODEC_SAMPLE_RATE_NONE) { - log::error( - "cannot match sample frequency: local caps = 0x{:x} peer info = 0x{:x}", - a2dp_aptx_source_caps.sampleRate, peer_info_cie.sampleRate); + log::error("cannot match sample frequency: local caps = 0x{:x} peer info = 0x{:x}", + a2dp_aptx_source_caps.sampleRate, peer_info_cie.sampleRate); goto fail; } @@ -743,11 +729,11 @@ bool A2dpCodecConfigAptx::setCodecConfig(const uint8_t* p_peer_codec_info, // Select the bits per sample if there is no user preference do { // Compute the selectable capability - codec_selectable_capability_.bits_per_sample = - a2dp_aptx_source_caps.bits_per_sample; + codec_selectable_capability_.bits_per_sample = a2dp_aptx_source_caps.bits_per_sample; - if (codec_config_.bits_per_sample != BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE) + if (codec_config_.bits_per_sample != BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE) { break; + } // Compute the common capability codec_capability_.bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16; @@ -804,88 +790,84 @@ bool A2dpCodecConfigAptx::setCodecConfig(const uint8_t* p_peer_codec_info, do { // Compute the selectable capability if (channelMode & A2DP_APTX_CHANNELS_MONO) { - codec_selectable_capability_.channel_mode |= - BTAV_A2DP_CODEC_CHANNEL_MODE_MONO; + codec_selectable_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_MONO; } if (channelMode & A2DP_APTX_CHANNELS_STEREO) { - codec_selectable_capability_.channel_mode |= - BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; + codec_selectable_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; } - if (codec_config_.channel_mode != BTAV_A2DP_CODEC_CHANNEL_MODE_NONE) break; + if (codec_config_.channel_mode != BTAV_A2DP_CODEC_CHANNEL_MODE_NONE) { + break; + } // Compute the common capability - if (channelMode & A2DP_APTX_CHANNELS_MONO) + if (channelMode & A2DP_APTX_CHANNELS_MONO) { codec_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_MONO; - if (channelMode & A2DP_APTX_CHANNELS_STEREO) + } + if (channelMode & A2DP_APTX_CHANNELS_STEREO) { codec_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; + } // No user preference - try the codec audio config - if (select_audio_channel_mode(&codec_audio_config_, channelMode, - &result_config_cie, &codec_config_)) { + if (select_audio_channel_mode(&codec_audio_config_, channelMode, &result_config_cie, + &codec_config_)) { break; } // No user preference - try the default config - if (select_best_channel_mode( - a2dp_aptx_default_config.channelMode & peer_info_cie.channelMode, - &result_config_cie, &codec_config_)) { + if (select_best_channel_mode(a2dp_aptx_default_config.channelMode & peer_info_cie.channelMode, + &result_config_cie, &codec_config_)) { break; } // No user preference - use the best match - if (select_best_channel_mode(channelMode, &result_config_cie, - &codec_config_)) { + if (select_best_channel_mode(channelMode, &result_config_cie, &codec_config_)) { break; } } while (false); if (codec_config_.channel_mode == BTAV_A2DP_CODEC_CHANNEL_MODE_NONE) { - log::error( - "cannot match channel mode: local caps = 0x{:x} peer info = 0x{:x}", - a2dp_aptx_source_caps.channelMode, peer_info_cie.channelMode); + log::error("cannot match channel mode: local caps = 0x{:x} peer info = 0x{:x}", + a2dp_aptx_source_caps.channelMode, peer_info_cie.channelMode); goto fail; } // // Set the rest of the fields as bit-wise AND operation // - result_config_cie.future1 = - a2dp_aptx_source_caps.future1 & peer_info_cie.future1; - result_config_cie.future2 = - a2dp_aptx_source_caps.future2 & peer_info_cie.future2; + result_config_cie.future1 = a2dp_aptx_source_caps.future1 & peer_info_cie.future1; + result_config_cie.future2 = a2dp_aptx_source_caps.future2 & peer_info_cie.future2; - if (A2DP_BuildInfoAptx(AVDT_MEDIA_TYPE_AUDIO, &result_config_cie, - p_result_codec_config) != A2DP_SUCCESS) { + if (A2DP_BuildInfoAptx(AVDT_MEDIA_TYPE_AUDIO, &result_config_cie, p_result_codec_config) != + A2DP_SUCCESS) { goto fail; } // // Copy the codec-specific fields if they are not zero // - if (codec_user_config_.codec_specific_1 != 0) + if (codec_user_config_.codec_specific_1 != 0) { codec_config_.codec_specific_1 = codec_user_config_.codec_specific_1; - if (codec_user_config_.codec_specific_2 != 0) + } + if (codec_user_config_.codec_specific_2 != 0) { codec_config_.codec_specific_2 = codec_user_config_.codec_specific_2; - if (codec_user_config_.codec_specific_3 != 0) + } + if (codec_user_config_.codec_specific_3 != 0) { codec_config_.codec_specific_3 = codec_user_config_.codec_specific_3; - if (codec_user_config_.codec_specific_4 != 0) + } + if (codec_user_config_.codec_specific_4 != 0) { codec_config_.codec_specific_4 = codec_user_config_.codec_specific_4; + } // Create a local copy of the peer codec capability/config, and the // result codec config. if (is_capability) { - status = A2DP_BuildInfoAptx(AVDT_MEDIA_TYPE_AUDIO, &peer_info_cie, - ota_codec_peer_capability_); + status = A2DP_BuildInfoAptx(AVDT_MEDIA_TYPE_AUDIO, &peer_info_cie, ota_codec_peer_capability_); } else { - status = A2DP_BuildInfoAptx(AVDT_MEDIA_TYPE_AUDIO, &peer_info_cie, - ota_codec_peer_config_); + status = A2DP_BuildInfoAptx(AVDT_MEDIA_TYPE_AUDIO, &peer_info_cie, ota_codec_peer_config_); } - log::assert_that(status == A2DP_SUCCESS, - "assert failed: status == A2DP_SUCCESS"); - status = A2DP_BuildInfoAptx(AVDT_MEDIA_TYPE_AUDIO, &result_config_cie, - ota_codec_config_); - log::assert_that(status == A2DP_SUCCESS, - "assert failed: status == A2DP_SUCCESS"); + log::assert_that(status == A2DP_SUCCESS, "assert failed: status == A2DP_SUCCESS"); + status = A2DP_BuildInfoAptx(AVDT_MEDIA_TYPE_AUDIO, &result_config_cie, ota_codec_config_); + log::assert_that(status == A2DP_SUCCESS, "assert failed: status == A2DP_SUCCESS"); return true; @@ -899,27 +881,23 @@ fail: memcpy(ota_codec_config_, saved_ota_codec_config, sizeof(ota_codec_config_)); memcpy(ota_codec_peer_capability_, saved_ota_codec_peer_capability, sizeof(ota_codec_peer_capability_)); - memcpy(ota_codec_peer_config_, saved_ota_codec_peer_config, - sizeof(ota_codec_peer_config_)); + memcpy(ota_codec_peer_config_, saved_ota_codec_peer_config, sizeof(ota_codec_peer_config_)); return false; } -bool A2dpCodecConfigAptx::setPeerCodecCapabilities( - const uint8_t* p_peer_codec_capabilities) { +bool A2dpCodecConfigAptx::setPeerCodecCapabilities(const uint8_t* p_peer_codec_capabilities) { std::lock_guard lock(codec_mutex_); tA2DP_APTX_CIE peer_info_cie; uint8_t sampleRate; uint8_t channelMode; // Save the internal state - btav_a2dp_codec_config_t saved_codec_selectable_capability = - codec_selectable_capability_; + btav_a2dp_codec_config_t saved_codec_selectable_capability = codec_selectable_capability_; uint8_t saved_ota_codec_peer_capability[AVDT_CODEC_SIZE]; memcpy(saved_ota_codec_peer_capability, ota_codec_peer_capability_, sizeof(ota_codec_peer_capability_)); - tA2DP_STATUS status = - A2DP_ParseInfoAptx(&peer_info_cie, p_peer_codec_capabilities, true); + tA2DP_STATUS status = A2DP_ParseInfoAptx(&peer_info_cie, p_peer_codec_capabilities, true); if (status != A2DP_SUCCESS) { log::error("can't parse peer's capabilities: error = {}", status); goto fail; @@ -928,33 +906,26 @@ bool A2dpCodecConfigAptx::setPeerCodecCapabilities( // Compute the selectable capability - sample rate sampleRate = a2dp_aptx_source_caps.sampleRate & peer_info_cie.sampleRate; if (sampleRate & A2DP_APTX_SAMPLERATE_44100) { - codec_selectable_capability_.sample_rate |= - BTAV_A2DP_CODEC_SAMPLE_RATE_44100; + codec_selectable_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_44100; } if (sampleRate & A2DP_APTX_SAMPLERATE_48000) { - codec_selectable_capability_.sample_rate |= - BTAV_A2DP_CODEC_SAMPLE_RATE_48000; + codec_selectable_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_48000; } // Compute the selectable capability - bits per sample - codec_selectable_capability_.bits_per_sample = - a2dp_aptx_source_caps.bits_per_sample; + codec_selectable_capability_.bits_per_sample = a2dp_aptx_source_caps.bits_per_sample; // Compute the selectable capability - channel mode channelMode = a2dp_aptx_source_caps.channelMode & peer_info_cie.channelMode; if (channelMode & A2DP_APTX_CHANNELS_MONO) { - codec_selectable_capability_.channel_mode |= - BTAV_A2DP_CODEC_CHANNEL_MODE_MONO; + codec_selectable_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_MONO; } if (channelMode & A2DP_APTX_CHANNELS_STEREO) { - codec_selectable_capability_.channel_mode |= - BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; + codec_selectable_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; } - status = A2DP_BuildInfoAptx(AVDT_MEDIA_TYPE_AUDIO, &peer_info_cie, - ota_codec_peer_capability_); - log::assert_that(status == A2DP_SUCCESS, - "assert failed: status == A2DP_SUCCESS"); + status = A2DP_BuildInfoAptx(AVDT_MEDIA_TYPE_AUDIO, &peer_info_cie, ota_codec_peer_capability_); + log::assert_that(status == A2DP_SUCCESS, "assert failed: status == A2DP_SUCCESS"); return true; fail: diff --git a/system/stack/a2dp/a2dp_vendor_aptx_encoder.cc b/system/stack/a2dp/a2dp_vendor_aptx_encoder.cc index b24beefb2a1..2fbc4a07b3e 100644 --- a/system/stack/a2dp/a2dp_vendor_aptx_encoder.cc +++ b/system/stack/a2dp/a2dp_vendor_aptx_encoder.cc @@ -39,9 +39,9 @@ using namespace bluetooth; // static const tAPTX_API aptx_api = { - .init_func = aptxbtenc_init, - .encode_stereo_func = aptxbtenc_encodestereo, - .sizeof_params_func = SizeofAptxbtenc, + .init_func = aptxbtenc_init, + .encode_stereo_func = aptxbtenc_encodestereo, + .sizeof_params_func = SizeofAptxbtenc, }; // offset @@ -76,7 +76,7 @@ typedef struct { bool use_SCMS_T; tA2DP_ENCODER_INIT_PEER_PARAMS peer_params; - uint32_t timestamp; // Timestamp for the A2DP frames + uint32_t timestamp; // Timestamp for the A2DP frames tA2DP_FEEDING_PARAMS feeding_params; tAPTX_FRAMING_PARAMS framing_params; @@ -87,14 +87,12 @@ typedef struct { static tA2DP_APTX_ENCODER_CB a2dp_aptx_encoder_cb; static void a2dp_vendor_aptx_encoder_update(A2dpCodecConfig* a2dp_codec_config, - bool* p_restart_input, - bool* p_restart_output, + bool* p_restart_input, bool* p_restart_output, bool* p_config_updated); static void aptx_init_framing_params(tAPTX_FRAMING_PARAMS* framing_params); static void aptx_update_framing_params(tAPTX_FRAMING_PARAMS* framing_params); -static size_t aptx_encode_16bit(tAPTX_FRAMING_PARAMS* framing_params, - size_t* data_out_index, uint16_t* data16_in, - uint8_t* data_out); +static size_t aptx_encode_16bit(tAPTX_FRAMING_PARAMS* framing_params, size_t* data_out_index, + uint16_t* data16_in, uint8_t* data_out); /******************************************************************************* * @@ -121,15 +119,13 @@ void A2DP_VendorUnloadEncoderAptx(void) { // nothing to do } -void a2dp_vendor_aptx_encoder_init( - const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params, - A2dpCodecConfig* a2dp_codec_config, - a2dp_source_read_callback_t read_callback, - a2dp_source_enqueue_callback_t enqueue_callback) { +void a2dp_vendor_aptx_encoder_init(const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params, + A2dpCodecConfig* a2dp_codec_config, + a2dp_source_read_callback_t read_callback, + a2dp_source_enqueue_callback_t enqueue_callback) { memset(&a2dp_aptx_encoder_cb, 0, sizeof(a2dp_aptx_encoder_cb)); - a2dp_aptx_encoder_cb.stats.session_start_us = - bluetooth::common::time_get_os_boottime_us(); + a2dp_aptx_encoder_cb.stats.session_start_us = bluetooth::common::time_get_os_boottime_us(); a2dp_aptx_encoder_cb.read_callback = read_callback; a2dp_aptx_encoder_cb.enqueue_callback = enqueue_callback; @@ -139,8 +135,7 @@ void a2dp_vendor_aptx_encoder_init( /* aptX encoder config */ a2dp_aptx_encoder_cb.use_SCMS_T = false; - a2dp_aptx_encoder_cb.aptx_encoder_state = - osi_malloc(aptx_api.sizeof_params_func()); + a2dp_aptx_encoder_cb.aptx_encoder_state = osi_malloc(aptx_api.sizeof_params_func()); if (a2dp_aptx_encoder_cb.aptx_encoder_state != NULL) { aptx_api.init_func(a2dp_aptx_encoder_cb.aptx_encoder_state, 0); } else { @@ -153,15 +148,14 @@ void a2dp_vendor_aptx_encoder_init( bool restart_input = false; bool restart_output = false; bool config_updated = false; - a2dp_vendor_aptx_encoder_update(a2dp_codec_config, &restart_input, - &restart_output, &config_updated); + a2dp_vendor_aptx_encoder_update(a2dp_codec_config, &restart_input, &restart_output, + &config_updated); } // Update the A2DP aptX encoder. // |a2dp_codec_config| is the A2DP codec to use for the update. static void a2dp_vendor_aptx_encoder_update(A2dpCodecConfig* a2dp_codec_config, - bool* p_restart_input, - bool* p_restart_output, + bool* p_restart_input, bool* p_restart_output, bool* p_config_updated) { uint8_t codec_info[AVDT_CODEC_SIZE]; @@ -177,15 +171,11 @@ static void a2dp_vendor_aptx_encoder_update(A2dpCodecConfig* a2dp_codec_config, // The feeding parameters tA2DP_FEEDING_PARAMS* p_feeding_params = &a2dp_aptx_encoder_cb.feeding_params; - p_feeding_params->sample_rate = - A2DP_VendorGetTrackSampleRateAptx(p_codec_info); - p_feeding_params->bits_per_sample = - a2dp_codec_config->getAudioBitsPerSample(); - p_feeding_params->channel_count = - A2DP_VendorGetTrackChannelCountAptx(p_codec_info); - log::info("sample_rate={} bits_per_sample={} channel_count={}", - p_feeding_params->sample_rate, p_feeding_params->bits_per_sample, - p_feeding_params->channel_count); + p_feeding_params->sample_rate = A2DP_VendorGetTrackSampleRateAptx(p_codec_info); + p_feeding_params->bits_per_sample = a2dp_codec_config->getAudioBitsPerSample(); + p_feeding_params->channel_count = A2DP_VendorGetTrackChannelCountAptx(p_codec_info); + log::info("sample_rate={} bits_per_sample={} channel_count={}", p_feeding_params->sample_rate, + p_feeding_params->bits_per_sample, p_feeding_params->channel_count); a2dp_vendor_aptx_feeding_reset(); } @@ -275,11 +265,11 @@ static void aptx_update_framing_params(tAPTX_FRAMING_PARAMS* framing_params) { } log::verbose( - "sleep_time_ns={} aptx_bytes={} pcm_bytes_per_read={} pcm_reads={} " - "frame_size_counter={}", - framing_params->sleep_time_ns, framing_params->aptx_bytes, - framing_params->pcm_bytes_per_read, framing_params->pcm_reads, - framing_params->frame_size_counter); + "sleep_time_ns={} aptx_bytes={} pcm_bytes_per_read={} pcm_reads={} " + "frame_size_counter={}", + framing_params->sleep_time_ns, framing_params->aptx_bytes, + framing_params->pcm_bytes_per_read, framing_params->pcm_reads, + framing_params->frame_size_counter); } void a2dp_vendor_aptx_feeding_reset(void) { @@ -316,24 +306,21 @@ void a2dp_vendor_aptx_send_frames(uint64_t timestamp_us) { // Read the PCM data and encode it // uint16_t read_buffer16[A2DP_APTX_MAX_PCM_BYTES_PER_READ / sizeof(uint16_t)]; - uint32_t expected_read_bytes = - framing_params->pcm_reads * framing_params->pcm_bytes_per_read; + uint32_t expected_read_bytes = framing_params->pcm_reads * framing_params->pcm_bytes_per_read; size_t encoded_ptr_index = 0; size_t pcm_bytes_encoded = 0; uint32_t bytes_read = 0; a2dp_aptx_encoder_cb.stats.media_read_total_expected_packets++; a2dp_aptx_encoder_cb.stats.media_read_total_expected_reads_count++; - a2dp_aptx_encoder_cb.stats.media_read_total_expected_read_bytes += - expected_read_bytes; + a2dp_aptx_encoder_cb.stats.media_read_total_expected_read_bytes += expected_read_bytes; log::verbose("PCM read of size {}", expected_read_bytes); - bytes_read = a2dp_aptx_encoder_cb.read_callback((uint8_t*)read_buffer16, - expected_read_bytes); + bytes_read = a2dp_aptx_encoder_cb.read_callback((uint8_t*)read_buffer16, expected_read_bytes); a2dp_aptx_encoder_cb.stats.media_read_total_actual_read_bytes += bytes_read; if (bytes_read < expected_read_bytes) { - log::warn("underflow at PCM reading: read {} bytes instead of {}", - bytes_read, expected_read_bytes); + log::warn("underflow at PCM reading: read {} bytes instead of {}", bytes_read, + expected_read_bytes); a2dp_aptx_encoder_cb.stats.media_read_total_dropped_packets++; osi_free(p_buf); return; @@ -341,8 +328,7 @@ void a2dp_vendor_aptx_send_frames(uint64_t timestamp_us) { a2dp_aptx_encoder_cb.stats.media_read_total_actual_reads_count++; for (uint32_t reads = 0, offset = 0; reads < framing_params->pcm_reads; - reads++, offset += - (framing_params->pcm_bytes_per_read / sizeof(uint16_t))) { + reads++, offset += (framing_params->pcm_bytes_per_read / sizeof(uint16_t))) { pcm_bytes_encoded += aptx_encode_16bit(framing_params, &encoded_ptr_index, read_buffer16 + offset, encoded_ptr); } @@ -358,14 +344,13 @@ void a2dp_vendor_aptx_send_frames(uint64_t timestamp_us) { const uint8_t BYTES_PER_FRAME = 2; uint32_t rtp_timestamp = - (pcm_bytes_encoded / a2dp_aptx_encoder_cb.feeding_params.channel_count) / - BYTES_PER_FRAME; + (pcm_bytes_encoded / a2dp_aptx_encoder_cb.feeding_params.channel_count) / BYTES_PER_FRAME; // Timestamp will wrap over to 0 if stream continues on long enough // (>25H @ 48KHz). The parameters are promoted to 64bit to ensure that // no unsigned overflow is triggered as ubsan is always enabled. a2dp_aptx_encoder_cb.timestamp = - ((uint64_t)a2dp_aptx_encoder_cb.timestamp + rtp_timestamp) & UINT32_MAX; + ((uint64_t)a2dp_aptx_encoder_cb.timestamp + rtp_timestamp) & UINT32_MAX; if (p_buf->len > 0) { a2dp_aptx_encoder_cb.enqueue_callback(p_buf, 1, bytes_read); @@ -375,25 +360,24 @@ void a2dp_vendor_aptx_send_frames(uint64_t timestamp_us) { } } -static size_t aptx_encode_16bit(tAPTX_FRAMING_PARAMS* framing_params, - size_t* data_out_index, uint16_t* data16_in, - uint8_t* data_out) { +static size_t aptx_encode_16bit(tAPTX_FRAMING_PARAMS* framing_params, size_t* data_out_index, + uint16_t* data16_in, uint8_t* data_out) { size_t pcm_bytes_encoded = 0; size_t frame = 0; - for (size_t aptx_samples = 0; - aptx_samples < framing_params->pcm_bytes_per_read / 16; aptx_samples++) { + for (size_t aptx_samples = 0; aptx_samples < framing_params->pcm_bytes_per_read / 16; + aptx_samples++) { uint32_t pcmL[4]; uint32_t pcmR[4]; uint16_t encoded_sample[2]; for (size_t i = 0, j = frame; i < 4; i++, j++) { - pcmL[i] = (uint16_t) * (data16_in + (2 * j)); - pcmR[i] = (uint16_t) * (data16_in + ((2 * j) + 1)); + pcmL[i] = (uint16_t)*(data16_in + (2 * j)); + pcmR[i] = (uint16_t)*(data16_in + ((2 * j) + 1)); } - aptx_api.encode_stereo_func(a2dp_aptx_encoder_cb.aptx_encoder_state, &pcmL, - &pcmR, &encoded_sample); + aptx_api.encode_stereo_func(a2dp_aptx_encoder_cb.aptx_encoder_state, &pcmL, &pcmR, + &encoded_sample); data_out[*data_out_index + 0] = (uint8_t)((encoded_sample[0] >> 8) & 0xff); data_out[*data_out_index + 1] = (uint8_t)((encoded_sample[0] >> 0) & 0xff); @@ -413,25 +397,20 @@ void A2dpCodecConfigAptx::debug_codec_dump(int fd) { A2dpCodecConfig::debug_codec_dump(fd); - dprintf(fd, " Encoder interval (ms): %" PRIu64 "\n", - a2dp_vendor_aptx_get_encoder_interval_ms()); - dprintf(fd, " Effective MTU: %d\n", - a2dp_vendor_aptx_get_effective_frame_size()); + dprintf(fd, " Encoder interval (ms): %" PRIu64 "\n", a2dp_vendor_aptx_get_encoder_interval_ms()); + dprintf(fd, " Effective MTU: %d\n", a2dp_vendor_aptx_get_effective_frame_size()); dprintf(fd, " Packet counts (expected/dropped) : %zu / " "%zu\n", - stats->media_read_total_expected_packets, - stats->media_read_total_dropped_packets); + stats->media_read_total_expected_packets, stats->media_read_total_dropped_packets); dprintf(fd, " PCM read counts (expected/actual) : %zu / " "%zu\n", - stats->media_read_total_expected_reads_count, - stats->media_read_total_actual_reads_count); + stats->media_read_total_expected_reads_count, stats->media_read_total_actual_reads_count); dprintf(fd, " PCM read bytes (expected/actual) : %zu / " "%zu\n", - stats->media_read_total_expected_read_bytes, - stats->media_read_total_actual_read_bytes); + stats->media_read_total_expected_read_bytes, stats->media_read_total_actual_read_bytes); } diff --git a/system/stack/a2dp/a2dp_vendor_aptx_hd.cc b/system/stack/a2dp/a2dp_vendor_aptx_hd.cc index b1d98859491..e3ac7c6be6f 100644 --- a/system/stack/a2dp/a2dp_vendor_aptx_hd.cc +++ b/system/stack/a2dp/a2dp_vendor_aptx_hd.cc @@ -53,53 +53,51 @@ typedef struct { /* aptX-HD Source codec capabilities */ static const tA2DP_APTX_HD_CIE a2dp_aptx_hd_source_caps = { - A2DP_APTX_HD_VENDOR_ID, /* vendorId */ - A2DP_APTX_HD_CODEC_ID_BLUETOOTH, /* codecId */ - (A2DP_APTX_HD_SAMPLERATE_44100 | - A2DP_APTX_HD_SAMPLERATE_48000), /* sampleRate */ - A2DP_APTX_HD_CHANNELS_STEREO, /* channelMode */ - A2DP_APTX_HD_ACL_SPRINT_RESERVED0, /* acl_sprint_reserved0 */ - A2DP_APTX_HD_ACL_SPRINT_RESERVED1, /* acl_sprint_reserved1 */ - A2DP_APTX_HD_ACL_SPRINT_RESERVED2, /* acl_sprint_reserved2 */ - A2DP_APTX_HD_ACL_SPRINT_RESERVED3, /* acl_sprint_reserved3 */ - BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24 /* bits_per_sample */ + A2DP_APTX_HD_VENDOR_ID, /* vendorId */ + A2DP_APTX_HD_CODEC_ID_BLUETOOTH, /* codecId */ + (A2DP_APTX_HD_SAMPLERATE_44100 | A2DP_APTX_HD_SAMPLERATE_48000), /* sampleRate */ + A2DP_APTX_HD_CHANNELS_STEREO, /* channelMode */ + A2DP_APTX_HD_ACL_SPRINT_RESERVED0, /* acl_sprint_reserved0 */ + A2DP_APTX_HD_ACL_SPRINT_RESERVED1, /* acl_sprint_reserved1 */ + A2DP_APTX_HD_ACL_SPRINT_RESERVED2, /* acl_sprint_reserved2 */ + A2DP_APTX_HD_ACL_SPRINT_RESERVED3, /* acl_sprint_reserved3 */ + BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24 /* bits_per_sample */ }; /* Default aptX-HD codec configuration */ static const tA2DP_APTX_HD_CIE a2dp_aptx_hd_default_config = { - A2DP_APTX_HD_VENDOR_ID, /* vendorId */ - A2DP_APTX_HD_CODEC_ID_BLUETOOTH, /* codecId */ - A2DP_APTX_HD_SAMPLERATE_48000, /* sampleRate */ - A2DP_APTX_HD_CHANNELS_STEREO, /* channelMode */ - A2DP_APTX_HD_ACL_SPRINT_RESERVED0, /* acl_sprint_reserved0 */ - A2DP_APTX_HD_ACL_SPRINT_RESERVED1, /* acl_sprint_reserved1 */ - A2DP_APTX_HD_ACL_SPRINT_RESERVED2, /* acl_sprint_reserved2 */ - A2DP_APTX_HD_ACL_SPRINT_RESERVED3, /* acl_sprint_reserved3 */ - BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24 /* bits_per_sample */ + A2DP_APTX_HD_VENDOR_ID, /* vendorId */ + A2DP_APTX_HD_CODEC_ID_BLUETOOTH, /* codecId */ + A2DP_APTX_HD_SAMPLERATE_48000, /* sampleRate */ + A2DP_APTX_HD_CHANNELS_STEREO, /* channelMode */ + A2DP_APTX_HD_ACL_SPRINT_RESERVED0, /* acl_sprint_reserved0 */ + A2DP_APTX_HD_ACL_SPRINT_RESERVED1, /* acl_sprint_reserved1 */ + A2DP_APTX_HD_ACL_SPRINT_RESERVED2, /* acl_sprint_reserved2 */ + A2DP_APTX_HD_ACL_SPRINT_RESERVED3, /* acl_sprint_reserved3 */ + BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24 /* bits_per_sample */ }; static const tA2DP_ENCODER_INTERFACE a2dp_encoder_interface_aptx_hd = { - a2dp_vendor_aptx_hd_encoder_init, - a2dp_vendor_aptx_hd_encoder_cleanup, - a2dp_vendor_aptx_hd_feeding_reset, - a2dp_vendor_aptx_hd_feeding_flush, - a2dp_vendor_aptx_hd_get_encoder_interval_ms, - a2dp_vendor_aptx_hd_get_effective_frame_size, - a2dp_vendor_aptx_hd_send_frames, - nullptr // set_transmit_queue_length + a2dp_vendor_aptx_hd_encoder_init, + a2dp_vendor_aptx_hd_encoder_cleanup, + a2dp_vendor_aptx_hd_feeding_reset, + a2dp_vendor_aptx_hd_feeding_flush, + a2dp_vendor_aptx_hd_get_encoder_interval_ms, + a2dp_vendor_aptx_hd_get_effective_frame_size, + a2dp_vendor_aptx_hd_send_frames, + nullptr // set_transmit_queue_length }; -static tA2DP_STATUS A2DP_CodecInfoMatchesCapabilityAptxHd( - const tA2DP_APTX_HD_CIE* p_cap, const uint8_t* p_codec_info, - bool is_peer_codec_info); +static tA2DP_STATUS A2DP_CodecInfoMatchesCapabilityAptxHd(const tA2DP_APTX_HD_CIE* p_cap, + const uint8_t* p_codec_info, + bool is_peer_codec_info); // Builds the aptX-HD Media Codec Capabilities byte sequence beginning from the // LOSC octet. |media_type| is the media type |AVDT_MEDIA_TYPE_*|. // |p_ie| is a pointer to the aptX-HD Codec Information Element information. // The result is stored in |p_result|. Returns A2DP_SUCCESS on success, // otherwise the corresponding A2DP error status code. -static tA2DP_STATUS A2DP_BuildInfoAptxHd(uint8_t media_type, - const tA2DP_APTX_HD_CIE* p_ie, +static tA2DP_STATUS A2DP_BuildInfoAptxHd(uint8_t media_type, const tA2DP_APTX_HD_CIE* p_ie, uint8_t* p_result) { if (p_ie == NULL || p_result == NULL) { return A2DP_INVALID_PARAMS; @@ -129,35 +127,35 @@ static tA2DP_STATUS A2DP_BuildInfoAptxHd(uint8_t media_type, // codec capabilities, otherwise is codec configuration. // Returns A2DP_SUCCESS on success, otherwise the corresponding A2DP error // status code. -static tA2DP_STATUS A2DP_ParseInfoAptxHd(tA2DP_APTX_HD_CIE* p_ie, - const uint8_t* p_codec_info, +static tA2DP_STATUS A2DP_ParseInfoAptxHd(tA2DP_APTX_HD_CIE* p_ie, const uint8_t* p_codec_info, bool is_capability) { uint8_t losc; uint8_t media_type; tA2DP_CODEC_TYPE codec_type; - if (p_ie == NULL || p_codec_info == NULL) return A2DP_INVALID_PARAMS; + if (p_ie == NULL || p_codec_info == NULL) { + return A2DP_INVALID_PARAMS; + } // Check the codec capability length losc = *p_codec_info++; - if (losc != A2DP_APTX_HD_CODEC_LEN) return A2DP_WRONG_CODEC; + if (losc != A2DP_APTX_HD_CODEC_LEN) { + return A2DP_WRONG_CODEC; + } media_type = (*p_codec_info++) >> 4; codec_type = *p_codec_info++; /* Check the Media Type and Media Codec Type */ - if (media_type != AVDT_MEDIA_TYPE_AUDIO || - codec_type != A2DP_MEDIA_CT_NON_A2DP) { + if (media_type != AVDT_MEDIA_TYPE_AUDIO || codec_type != A2DP_MEDIA_CT_NON_A2DP) { return A2DP_WRONG_CODEC; } // Check the Vendor ID and Codec ID */ - p_ie->vendorId = (*p_codec_info & 0x000000FF) | - (*(p_codec_info + 1) << 8 & 0x0000FF00) | + p_ie->vendorId = (*p_codec_info & 0x000000FF) | (*(p_codec_info + 1) << 8 & 0x0000FF00) | (*(p_codec_info + 2) << 16 & 0x00FF0000) | (*(p_codec_info + 3) << 24 & 0xFF000000); p_codec_info += 4; - p_ie->codecId = - (*p_codec_info & 0x00FF) | (*(p_codec_info + 1) << 8 & 0xFF00); + p_ie->codecId = (*p_codec_info & 0x00FF) | (*(p_codec_info + 1) << 8 & 0xFF00); p_codec_info += 2; if (p_ie->vendorId != A2DP_APTX_HD_VENDOR_ID || p_ie->codecId != A2DP_APTX_HD_CODEC_ID_BLUETOOTH) { @@ -176,18 +174,22 @@ static tA2DP_STATUS A2DP_ParseInfoAptxHd(tA2DP_APTX_HD_CIE* p_ie, if (is_capability) { // NOTE: The checks here are very liberal. We should be using more // pedantic checks specific to the SRC or SNK as specified in the spec. - if (A2DP_BitsSet(p_ie->sampleRate) == A2DP_SET_ZERO_BIT) + if (A2DP_BitsSet(p_ie->sampleRate) == A2DP_SET_ZERO_BIT) { return A2DP_BAD_SAMP_FREQ; - if (A2DP_BitsSet(p_ie->channelMode) == A2DP_SET_ZERO_BIT) + } + if (A2DP_BitsSet(p_ie->channelMode) == A2DP_SET_ZERO_BIT) { return A2DP_BAD_CH_MODE; + } return A2DP_SUCCESS; } - if (A2DP_BitsSet(p_ie->sampleRate) != A2DP_SET_ONE_BIT) + if (A2DP_BitsSet(p_ie->sampleRate) != A2DP_SET_ONE_BIT) { return A2DP_BAD_SAMP_FREQ; - if (A2DP_BitsSet(p_ie->channelMode) != A2DP_SET_ONE_BIT) + } + if (A2DP_BitsSet(p_ie->channelMode) != A2DP_SET_ONE_BIT) { return A2DP_BAD_CH_MODE; + } return A2DP_SUCCESS; } @@ -196,8 +198,7 @@ bool A2DP_IsVendorSourceCodecValidAptxHd(const uint8_t* p_codec_info) { tA2DP_APTX_HD_CIE cfg_cie; /* Use a liberal check when parsing the codec info */ - return (A2DP_ParseInfoAptxHd(&cfg_cie, p_codec_info, false) == - A2DP_SUCCESS) || + return (A2DP_ParseInfoAptxHd(&cfg_cie, p_codec_info, false) == A2DP_SUCCESS) || (A2DP_ParseInfoAptxHd(&cfg_cie, p_codec_info, true) == A2DP_SUCCESS); } @@ -205,8 +206,7 @@ bool A2DP_IsVendorPeerSinkCodecValidAptxHd(const uint8_t* p_codec_info) { tA2DP_APTX_HD_CIE cfg_cie; /* Use a liberal check when parsing the codec info */ - return (A2DP_ParseInfoAptxHd(&cfg_cie, p_codec_info, false) == - A2DP_SUCCESS) || + return (A2DP_ParseInfoAptxHd(&cfg_cie, p_codec_info, false) == A2DP_SUCCESS) || (A2DP_ParseInfoAptxHd(&cfg_cie, p_codec_info, true) == A2DP_SUCCESS); } @@ -220,8 +220,7 @@ bool A2DP_IsVendorPeerSinkCodecValidAptxHd(const uint8_t* p_codec_info) { // Returns A2DP_SUCCESS if the codec configuration matches with capabilities, // otherwise the corresponding A2DP error status code. UNUSED_ATTR static tA2DP_STATUS A2DP_CodecInfoMatchesCapabilityAptxHd( - const tA2DP_APTX_HD_CIE* p_cap, const uint8_t* p_codec_info, - bool is_capability) { + const tA2DP_APTX_HD_CIE* p_cap, const uint8_t* p_codec_info, bool is_capability) { tA2DP_STATUS status; tA2DP_APTX_HD_CIE cfg_cie; @@ -234,16 +233,18 @@ UNUSED_ATTR static tA2DP_STATUS A2DP_CodecInfoMatchesCapabilityAptxHd( /* verify that each parameter is in range */ - log::verbose("FREQ peer: 0x{:x}, capability 0x{:x}", cfg_cie.sampleRate, - p_cap->sampleRate); - log::verbose("CH_MODE peer: 0x{:x}, capability 0x{:x}", cfg_cie.channelMode, - p_cap->channelMode); + log::verbose("FREQ peer: 0x{:x}, capability 0x{:x}", cfg_cie.sampleRate, p_cap->sampleRate); + log::verbose("CH_MODE peer: 0x{:x}, capability 0x{:x}", cfg_cie.channelMode, p_cap->channelMode); /* sampling frequency */ - if ((cfg_cie.sampleRate & p_cap->sampleRate) == 0) return A2DP_NS_SAMP_FREQ; + if ((cfg_cie.sampleRate & p_cap->sampleRate) == 0) { + return A2DP_NS_SAMP_FREQ; + } /* channel mode */ - if ((cfg_cie.channelMode & p_cap->channelMode) == 0) return A2DP_NS_CH_MODE; + if ((cfg_cie.channelMode & p_cap->channelMode) == 0) { + return A2DP_NS_CH_MODE; + } return A2DP_SUCCESS; } @@ -253,9 +254,7 @@ bool A2DP_VendorUsesRtpHeaderAptxHd(bool /* content_protection_enabled */, return true; } -const char* A2DP_VendorCodecNameAptxHd(const uint8_t* /* p_codec_info */) { - return "aptX-HD"; -} +const char* A2DP_VendorCodecNameAptxHd(const uint8_t* /* p_codec_info */) { return "aptX-HD"; } bool A2DP_VendorCodecTypeEqualsAptxHd(const uint8_t* p_codec_info_a, const uint8_t* p_codec_info_b) { @@ -263,8 +262,7 @@ bool A2DP_VendorCodecTypeEqualsAptxHd(const uint8_t* p_codec_info_a, tA2DP_APTX_HD_CIE aptx_hd_cie_b; // Check whether the codec info contains valid data - tA2DP_STATUS a2dp_status = - A2DP_ParseInfoAptxHd(&aptx_hd_cie_a, p_codec_info_a, true); + tA2DP_STATUS a2dp_status = A2DP_ParseInfoAptxHd(&aptx_hd_cie_a, p_codec_info_a, true); if (a2dp_status != A2DP_SUCCESS) { log::error("cannot decode codec information: {}", a2dp_status); return false; @@ -278,14 +276,12 @@ bool A2DP_VendorCodecTypeEqualsAptxHd(const uint8_t* p_codec_info_a, return true; } -bool A2DP_VendorCodecEqualsAptxHd(const uint8_t* p_codec_info_a, - const uint8_t* p_codec_info_b) { +bool A2DP_VendorCodecEqualsAptxHd(const uint8_t* p_codec_info_a, const uint8_t* p_codec_info_b) { tA2DP_APTX_HD_CIE aptx_hd_cie_a; tA2DP_APTX_HD_CIE aptx_hd_cie_b; // Check whether the codec info contains valid data - tA2DP_STATUS a2dp_status = - A2DP_ParseInfoAptxHd(&aptx_hd_cie_a, p_codec_info_a, true); + tA2DP_STATUS a2dp_status = A2DP_ParseInfoAptxHd(&aptx_hd_cie_a, p_codec_info_a, true); if (a2dp_status != A2DP_SUCCESS) { log::error("cannot decode codec information: {}", a2dp_status); return false; @@ -311,15 +307,18 @@ int A2DP_VendorGetTrackSampleRateAptxHd(const uint8_t* p_codec_info) { tA2DP_APTX_HD_CIE aptx_hd_cie; // Check whether the codec info contains valid data - tA2DP_STATUS a2dp_status = - A2DP_ParseInfoAptxHd(&aptx_hd_cie, p_codec_info, false); + tA2DP_STATUS a2dp_status = A2DP_ParseInfoAptxHd(&aptx_hd_cie, p_codec_info, false); if (a2dp_status != A2DP_SUCCESS) { log::error("cannot decode codec information: {}", a2dp_status); return -1; } - if (aptx_hd_cie.sampleRate == A2DP_APTX_HD_SAMPLERATE_44100) return 44100; - if (aptx_hd_cie.sampleRate == A2DP_APTX_HD_SAMPLERATE_48000) return 48000; + if (aptx_hd_cie.sampleRate == A2DP_APTX_HD_SAMPLERATE_44100) { + return 44100; + } + if (aptx_hd_cie.sampleRate == A2DP_APTX_HD_SAMPLERATE_48000) { + return 48000; + } return -1; } @@ -328,8 +327,7 @@ int A2DP_VendorGetTrackBitsPerSampleAptxHd(const uint8_t* p_codec_info) { tA2DP_APTX_HD_CIE aptx_hd_cie; // Check whether the codec info contains valid data - tA2DP_STATUS a2dp_status = - A2DP_ParseInfoAptxHd(&aptx_hd_cie, p_codec_info, false); + tA2DP_STATUS a2dp_status = A2DP_ParseInfoAptxHd(&aptx_hd_cie, p_codec_info, false); if (a2dp_status != A2DP_SUCCESS) { log::error("cannot decode codec information: {}", a2dp_status); return -1; @@ -343,8 +341,7 @@ int A2DP_VendorGetTrackChannelCountAptxHd(const uint8_t* p_codec_info) { tA2DP_APTX_HD_CIE aptx_hd_cie; // Check whether the codec info contains valid data - tA2DP_STATUS a2dp_status = - A2DP_ParseInfoAptxHd(&aptx_hd_cie, p_codec_info, false); + tA2DP_STATUS a2dp_status = A2DP_ParseInfoAptxHd(&aptx_hd_cie, p_codec_info, false); if (a2dp_status != A2DP_SUCCESS) { log::error("cannot decode codec information: {}", a2dp_status); return -1; @@ -360,16 +357,14 @@ int A2DP_VendorGetTrackChannelCountAptxHd(const uint8_t* p_codec_info) { return -1; } -bool A2DP_VendorGetPacketTimestampAptxHd(const uint8_t* /* p_codec_info */, - const uint8_t* p_data, +bool A2DP_VendorGetPacketTimestampAptxHd(const uint8_t* /* p_codec_info */, const uint8_t* p_data, uint32_t* p_timestamp) { // TODO: Is this function really codec-specific? *p_timestamp = *(const uint32_t*)p_data; return true; } -bool A2DP_VendorBuildCodecHeaderAptxHd(const uint8_t* /* p_codec_info */, - BT_HDR* /* p_buf */, +bool A2DP_VendorBuildCodecHeaderAptxHd(const uint8_t* /* p_codec_info */, BT_HDR* /* p_buf */, uint16_t /* frames_per_packet */) { // Nothing to do return true; @@ -383,8 +378,7 @@ std::string A2DP_VendorCodecInfoStringAptxHd(const uint8_t* p_codec_info) { a2dp_status = A2DP_ParseInfoAptxHd(&aptx_hd_cie, p_codec_info, true); if (a2dp_status != A2DP_SUCCESS) { - res << "A2DP_ParseInfoAptxHd fail: " - << loghex(static_cast(a2dp_status)); + res << "A2DP_ParseInfoAptxHd fail: " << loghex(static_cast(a2dp_status)); return res.str(); } @@ -393,29 +387,24 @@ std::string A2DP_VendorCodecInfoStringAptxHd(const uint8_t* p_codec_info) { // Sample frequency field.clear(); AppendField(&field, (aptx_hd_cie.sampleRate == 0), "NONE"); - AppendField(&field, (aptx_hd_cie.sampleRate & A2DP_APTX_HD_SAMPLERATE_44100), - "44100"); - AppendField(&field, (aptx_hd_cie.sampleRate & A2DP_APTX_HD_SAMPLERATE_48000), - "48000"); - res << "\tsamp_freq: " << field << " (" << loghex(aptx_hd_cie.sampleRate) - << ")\n"; + AppendField(&field, (aptx_hd_cie.sampleRate & A2DP_APTX_HD_SAMPLERATE_44100), "44100"); + AppendField(&field, (aptx_hd_cie.sampleRate & A2DP_APTX_HD_SAMPLERATE_48000), "48000"); + res << "\tsamp_freq: " << field << " (" << loghex(aptx_hd_cie.sampleRate) << ")\n"; // Channel mode field.clear(); AppendField(&field, (aptx_hd_cie.channelMode == 0), "NONE"); - AppendField(&field, (aptx_hd_cie.channelMode & A2DP_APTX_HD_CHANNELS_MONO), - "Mono"); - AppendField(&field, (aptx_hd_cie.channelMode & A2DP_APTX_HD_CHANNELS_STEREO), - "Stereo"); - res << "\tch_mode: " << field << " (" << loghex(aptx_hd_cie.channelMode) - << ")\n"; + AppendField(&field, (aptx_hd_cie.channelMode & A2DP_APTX_HD_CHANNELS_MONO), "Mono"); + AppendField(&field, (aptx_hd_cie.channelMode & A2DP_APTX_HD_CHANNELS_STEREO), "Stereo"); + res << "\tch_mode: " << field << " (" << loghex(aptx_hd_cie.channelMode) << ")\n"; return res.str(); } -const tA2DP_ENCODER_INTERFACE* A2DP_VendorGetEncoderInterfaceAptxHd( - const uint8_t* p_codec_info) { - if (!A2DP_IsVendorSourceCodecValidAptxHd(p_codec_info)) return NULL; +const tA2DP_ENCODER_INTERFACE* A2DP_VendorGetEncoderInterfaceAptxHd(const uint8_t* p_codec_info) { + if (!A2DP_IsVendorSourceCodecValidAptxHd(p_codec_info)) { + return NULL; + } return &a2dp_encoder_interface_aptx_hd; } @@ -424,33 +413,31 @@ bool A2DP_VendorAdjustCodecAptxHd(uint8_t* p_codec_info) { tA2DP_APTX_HD_CIE cfg_cie; // Nothing to do: just verify the codec info is valid - if (A2DP_ParseInfoAptxHd(&cfg_cie, p_codec_info, true) != A2DP_SUCCESS) + if (A2DP_ParseInfoAptxHd(&cfg_cie, p_codec_info, true) != A2DP_SUCCESS) { return false; + } return true; } -btav_a2dp_codec_index_t A2DP_VendorSourceCodecIndexAptxHd( - const uint8_t* p_codec_info) { +btav_a2dp_codec_index_t A2DP_VendorSourceCodecIndexAptxHd(const uint8_t* p_codec_info) { return BTAV_A2DP_CODEC_INDEX_SOURCE_APTX_HD; } const char* A2DP_VendorCodecIndexStrAptxHd(void) { return "aptX-HD"; } bool A2DP_VendorInitCodecConfigAptxHd(AvdtpSepConfig* p_cfg) { - if (A2DP_BuildInfoAptxHd(AVDT_MEDIA_TYPE_AUDIO, &a2dp_aptx_hd_source_caps, - p_cfg->codec_info) != A2DP_SUCCESS) { + if (A2DP_BuildInfoAptxHd(AVDT_MEDIA_TYPE_AUDIO, &a2dp_aptx_hd_source_caps, p_cfg->codec_info) != + A2DP_SUCCESS) { return false; } return true; } -A2dpCodecConfigAptxHd::A2dpCodecConfigAptxHd( - btav_a2dp_codec_priority_t codec_priority) - : A2dpCodecConfig(BTAV_A2DP_CODEC_INDEX_SOURCE_APTX_HD, - A2DP_CODEC_ID_APTX_HD, A2DP_VendorCodecIndexStrAptxHd(), - codec_priority) { +A2dpCodecConfigAptxHd::A2dpCodecConfigAptxHd(btav_a2dp_codec_priority_t codec_priority) + : A2dpCodecConfig(BTAV_A2DP_CODEC_INDEX_SOURCE_APTX_HD, A2DP_CODEC_ID_APTX_HD, + A2DP_VendorCodecIndexStrAptxHd(), codec_priority) { // Compute the local capability if (a2dp_aptx_hd_source_caps.sampleRate & A2DP_APTX_HD_SAMPLERATE_44100) { codec_local_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_44100; @@ -458,8 +445,7 @@ A2dpCodecConfigAptxHd::A2dpCodecConfigAptxHd( if (a2dp_aptx_hd_source_caps.sampleRate & A2DP_APTX_HD_SAMPLERATE_48000) { codec_local_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_48000; } - codec_local_capability_.bits_per_sample = - a2dp_aptx_hd_source_caps.bits_per_sample; + codec_local_capability_.bits_per_sample = a2dp_aptx_hd_source_caps.bits_per_sample; if (a2dp_aptx_hd_source_caps.channelMode & A2DP_APTX_HD_CHANNELS_MONO) { codec_local_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_MONO; } @@ -471,7 +457,9 @@ A2dpCodecConfigAptxHd::A2dpCodecConfigAptxHd( A2dpCodecConfigAptxHd::~A2dpCodecConfigAptxHd() {} bool A2dpCodecConfigAptxHd::init() { - if (!isValid()) return false; + if (!isValid()) { + return false; + } // Load the encoder if (A2DP_VendorLoadEncoderAptxHd() != LOAD_SUCCESS) { @@ -489,8 +477,7 @@ bool A2dpCodecConfigAptxHd::useRtpHeaderMarkerBit() const { return false; } // The result is stored in |p_result| and p_codec_config|. // Returns true if a selection was made, otherwise false. // -static bool select_best_sample_rate(uint8_t sampleRate, - tA2DP_APTX_HD_CIE* p_result, +static bool select_best_sample_rate(uint8_t sampleRate, tA2DP_APTX_HD_CIE* p_result, btav_a2dp_codec_config_t* p_codec_config) { if (sampleRate & A2DP_APTX_HD_SAMPLERATE_48000) { p_result->sampleRate = A2DP_APTX_HD_SAMPLERATE_48000; @@ -511,9 +498,9 @@ static bool select_best_sample_rate(uint8_t sampleRate, // The result is stored in |p_result| and |p_codec_config|. // Returns true if a selection was made, otherwise false. // -static bool select_audio_sample_rate( - const btav_a2dp_codec_config_t* p_codec_audio_config, uint8_t sampleRate, - tA2DP_APTX_HD_CIE* p_result, btav_a2dp_codec_config_t* p_codec_config) { +static bool select_audio_sample_rate(const btav_a2dp_codec_config_t* p_codec_audio_config, + uint8_t sampleRate, tA2DP_APTX_HD_CIE* p_result, + btav_a2dp_codec_config_t* p_codec_config) { switch (p_codec_audio_config->sample_rate) { case BTAV_A2DP_CODEC_SAMPLE_RATE_44100: if (sampleRate & A2DP_APTX_HD_SAMPLERATE_44100) { @@ -546,8 +533,7 @@ static bool select_audio_sample_rate( // The result is stored in |p_codec_config|. // Returns true if a selection was made, otherwise false. // -static bool select_best_bits_per_sample( - btav_a2dp_codec_config_t* p_codec_config) { +static bool select_best_bits_per_sample(btav_a2dp_codec_config_t* p_codec_config) { p_codec_config->bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24; return true; } @@ -557,9 +543,8 @@ static bool select_best_bits_per_sample( // The result is stored in |p_codec_config|. // Returns true if a selection was made, otherwise false. // -static bool select_audio_bits_per_sample( - const btav_a2dp_codec_config_t* p_codec_audio_config, - btav_a2dp_codec_config_t* p_codec_config) { +static bool select_audio_bits_per_sample(const btav_a2dp_codec_config_t* p_codec_audio_config, + btav_a2dp_codec_config_t* p_codec_config) { switch (p_codec_audio_config->bits_per_sample) { case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24: p_codec_config->bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24; @@ -577,8 +562,7 @@ static bool select_audio_bits_per_sample( // The result is stored in |p_result| and |p_codec_config|. // Returns true if a selection was made, otherwise false. // -static bool select_best_channel_mode(uint8_t channelMode, - tA2DP_APTX_HD_CIE* p_result, +static bool select_best_channel_mode(uint8_t channelMode, tA2DP_APTX_HD_CIE* p_result, btav_a2dp_codec_config_t* p_codec_config) { if (channelMode & A2DP_APTX_HD_CHANNELS_STEREO) { p_result->channelMode = A2DP_APTX_HD_CHANNELS_STEREO; @@ -599,9 +583,9 @@ static bool select_best_channel_mode(uint8_t channelMode, // The result is stored in |p_result| and |p_codec_config|. // Returns true if a selection was made, otherwise false. // -static bool select_audio_channel_mode( - const btav_a2dp_codec_config_t* p_codec_audio_config, uint8_t channelMode, - tA2DP_APTX_HD_CIE* p_result, btav_a2dp_codec_config_t* p_codec_config) { +static bool select_audio_channel_mode(const btav_a2dp_codec_config_t* p_codec_audio_config, + uint8_t channelMode, tA2DP_APTX_HD_CIE* p_result, + btav_a2dp_codec_config_t* p_codec_config) { switch (p_codec_audio_config->channel_mode) { case BTAV_A2DP_CODEC_CHANNEL_MODE_MONO: if (channelMode & A2DP_APTX_HD_CHANNELS_MONO) { @@ -624,8 +608,7 @@ static bool select_audio_channel_mode( return false; } -bool A2dpCodecConfigAptxHd::setCodecConfig(const uint8_t* p_peer_codec_info, - bool is_capability, +bool A2dpCodecConfigAptxHd::setCodecConfig(const uint8_t* p_peer_codec_info, bool is_capability, uint8_t* p_result_codec_config) { std::lock_guard lock(codec_mutex_); tA2DP_APTX_HD_CIE peer_info_cie; @@ -636,8 +619,7 @@ bool A2dpCodecConfigAptxHd::setCodecConfig(const uint8_t* p_peer_codec_info, // Save the internal state btav_a2dp_codec_config_t saved_codec_config = codec_config_; btav_a2dp_codec_config_t saved_codec_capability = codec_capability_; - btav_a2dp_codec_config_t saved_codec_selectable_capability = - codec_selectable_capability_; + btav_a2dp_codec_config_t saved_codec_selectable_capability = codec_selectable_capability_; btav_a2dp_codec_config_t saved_codec_user_config = codec_user_config_; btav_a2dp_codec_config_t saved_codec_audio_config = codec_audio_config_; uint8_t saved_ota_codec_config[AVDT_CODEC_SIZE]; @@ -646,11 +628,9 @@ bool A2dpCodecConfigAptxHd::setCodecConfig(const uint8_t* p_peer_codec_info, memcpy(saved_ota_codec_config, ota_codec_config_, sizeof(ota_codec_config_)); memcpy(saved_ota_codec_peer_capability, ota_codec_peer_capability_, sizeof(ota_codec_peer_capability_)); - memcpy(saved_ota_codec_peer_config, ota_codec_peer_config_, - sizeof(ota_codec_peer_config_)); + memcpy(saved_ota_codec_peer_config, ota_codec_peer_config_, sizeof(ota_codec_peer_config_)); - tA2DP_STATUS status = - A2DP_ParseInfoAptxHd(&peer_info_cie, p_peer_codec_info, is_capability); + tA2DP_STATUS status = A2DP_ParseInfoAptxHd(&peer_info_cie, p_peer_codec_info, is_capability); if (status != A2DP_SUCCESS) { log::error("can't parse peer's capabilities: error = {}", status); goto fail; @@ -699,45 +679,44 @@ bool A2dpCodecConfigAptxHd::setCodecConfig(const uint8_t* p_peer_codec_info, do { // Compute the selectable capability if (sampleRate & A2DP_APTX_HD_SAMPLERATE_44100) { - codec_selectable_capability_.sample_rate |= - BTAV_A2DP_CODEC_SAMPLE_RATE_44100; + codec_selectable_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_44100; } if (sampleRate & A2DP_APTX_HD_SAMPLERATE_48000) { - codec_selectable_capability_.sample_rate |= - BTAV_A2DP_CODEC_SAMPLE_RATE_48000; + codec_selectable_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_48000; } - if (codec_config_.sample_rate != BTAV_A2DP_CODEC_SAMPLE_RATE_NONE) break; + if (codec_config_.sample_rate != BTAV_A2DP_CODEC_SAMPLE_RATE_NONE) { + break; + } // Compute the common capability - if (sampleRate & A2DP_APTX_HD_SAMPLERATE_44100) + if (sampleRate & A2DP_APTX_HD_SAMPLERATE_44100) { codec_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_44100; - if (sampleRate & A2DP_APTX_HD_SAMPLERATE_48000) + } + if (sampleRate & A2DP_APTX_HD_SAMPLERATE_48000) { codec_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_48000; + } // No user preference - try the codec audio config - if (select_audio_sample_rate(&codec_audio_config_, sampleRate, - &result_config_cie, &codec_config_)) { + if (select_audio_sample_rate(&codec_audio_config_, sampleRate, &result_config_cie, + &codec_config_)) { break; } // No user preference - try the default config - if (select_best_sample_rate( - a2dp_aptx_hd_default_config.sampleRate & peer_info_cie.sampleRate, - &result_config_cie, &codec_config_)) { + if (select_best_sample_rate(a2dp_aptx_hd_default_config.sampleRate & peer_info_cie.sampleRate, + &result_config_cie, &codec_config_)) { break; } // No user preference - use the best match - if (select_best_sample_rate(sampleRate, &result_config_cie, - &codec_config_)) { + if (select_best_sample_rate(sampleRate, &result_config_cie, &codec_config_)) { break; } } while (false); if (codec_config_.sample_rate == BTAV_A2DP_CODEC_SAMPLE_RATE_NONE) { - log::error( - "cannot match sample frequency: local caps = 0x{:x} peer info = 0x{:x}", - a2dp_aptx_hd_source_caps.sampleRate, peer_info_cie.sampleRate); + log::error("cannot match sample frequency: local caps = 0x{:x} peer info = 0x{:x}", + a2dp_aptx_hd_source_caps.sampleRate, peer_info_cie.sampleRate); goto fail; } @@ -763,11 +742,11 @@ bool A2dpCodecConfigAptxHd::setCodecConfig(const uint8_t* p_peer_codec_info, // Select the bits per sample if there is no user preference do { // Compute the selectable capability - codec_selectable_capability_.bits_per_sample = - a2dp_aptx_hd_source_caps.bits_per_sample; + codec_selectable_capability_.bits_per_sample = a2dp_aptx_hd_source_caps.bits_per_sample; - if (codec_config_.bits_per_sample != BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE) + if (codec_config_.bits_per_sample != BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE) { break; + } // Compute the common capability codec_capability_.bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24; @@ -797,8 +776,7 @@ bool A2dpCodecConfigAptxHd::setCodecConfig(const uint8_t* p_peer_codec_info, // // Select the channel mode // - channelMode = - a2dp_aptx_hd_source_caps.channelMode & peer_info_cie.channelMode; + channelMode = a2dp_aptx_hd_source_caps.channelMode & peer_info_cie.channelMode; codec_config_.channel_mode = BTAV_A2DP_CODEC_CHANNEL_MODE_NONE; switch (codec_user_config_.channel_mode) { case BTAV_A2DP_CODEC_CHANNEL_MODE_MONO: @@ -825,45 +803,45 @@ bool A2dpCodecConfigAptxHd::setCodecConfig(const uint8_t* p_peer_codec_info, do { // Compute the selectable capability if (channelMode & A2DP_APTX_HD_CHANNELS_MONO) { - codec_selectable_capability_.channel_mode |= - BTAV_A2DP_CODEC_CHANNEL_MODE_MONO; + codec_selectable_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_MONO; } if (channelMode & A2DP_APTX_HD_CHANNELS_STEREO) { - codec_selectable_capability_.channel_mode |= - BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; + codec_selectable_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; } - if (codec_config_.channel_mode != BTAV_A2DP_CODEC_CHANNEL_MODE_NONE) break; + if (codec_config_.channel_mode != BTAV_A2DP_CODEC_CHANNEL_MODE_NONE) { + break; + } // Compute the common capability - if (channelMode & A2DP_APTX_HD_CHANNELS_MONO) + if (channelMode & A2DP_APTX_HD_CHANNELS_MONO) { codec_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_MONO; - if (channelMode & A2DP_APTX_HD_CHANNELS_STEREO) + } + if (channelMode & A2DP_APTX_HD_CHANNELS_STEREO) { codec_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; + } // No user preference - try the codec audio config - if (select_audio_channel_mode(&codec_audio_config_, channelMode, - &result_config_cie, &codec_config_)) { + if (select_audio_channel_mode(&codec_audio_config_, channelMode, &result_config_cie, + &codec_config_)) { break; } // No user preference - try the default config if (select_best_channel_mode( - a2dp_aptx_hd_default_config.channelMode & peer_info_cie.channelMode, - &result_config_cie, &codec_config_)) { + a2dp_aptx_hd_default_config.channelMode & peer_info_cie.channelMode, + &result_config_cie, &codec_config_)) { break; } // No user preference - use the best match - if (select_best_channel_mode(channelMode, &result_config_cie, - &codec_config_)) { + if (select_best_channel_mode(channelMode, &result_config_cie, &codec_config_)) { break; } } while (false); if (codec_config_.channel_mode == BTAV_A2DP_CODEC_CHANNEL_MODE_NONE) { - log::error( - "cannot match channel mode: local caps = 0x{:x} peer info = 0x{:x}", - a2dp_aptx_hd_source_caps.channelMode, peer_info_cie.channelMode); + log::error("cannot match channel mode: local caps = 0x{:x} peer info = 0x{:x}", + a2dp_aptx_hd_source_caps.channelMode, peer_info_cie.channelMode); goto fail; } @@ -871,50 +849,46 @@ bool A2dpCodecConfigAptxHd::setCodecConfig(const uint8_t* p_peer_codec_info, // Set the rest of the fields as bit-wise AND operation // result_config_cie.acl_sprint_reserved0 = - a2dp_aptx_hd_source_caps.acl_sprint_reserved0 & - peer_info_cie.acl_sprint_reserved0; + a2dp_aptx_hd_source_caps.acl_sprint_reserved0 & peer_info_cie.acl_sprint_reserved0; result_config_cie.acl_sprint_reserved1 = - a2dp_aptx_hd_source_caps.acl_sprint_reserved1 & - peer_info_cie.acl_sprint_reserved1; + a2dp_aptx_hd_source_caps.acl_sprint_reserved1 & peer_info_cie.acl_sprint_reserved1; result_config_cie.acl_sprint_reserved2 = - a2dp_aptx_hd_source_caps.acl_sprint_reserved2 & - peer_info_cie.acl_sprint_reserved2; + a2dp_aptx_hd_source_caps.acl_sprint_reserved2 & peer_info_cie.acl_sprint_reserved2; result_config_cie.acl_sprint_reserved3 = - a2dp_aptx_hd_source_caps.acl_sprint_reserved3 & - peer_info_cie.acl_sprint_reserved3; + a2dp_aptx_hd_source_caps.acl_sprint_reserved3 & peer_info_cie.acl_sprint_reserved3; - if (A2DP_BuildInfoAptxHd(AVDT_MEDIA_TYPE_AUDIO, &result_config_cie, - p_result_codec_config) != A2DP_SUCCESS) { + if (A2DP_BuildInfoAptxHd(AVDT_MEDIA_TYPE_AUDIO, &result_config_cie, p_result_codec_config) != + A2DP_SUCCESS) { goto fail; } // // Copy the codec-specific fields if they are not zero // - if (codec_user_config_.codec_specific_1 != 0) + if (codec_user_config_.codec_specific_1 != 0) { codec_config_.codec_specific_1 = codec_user_config_.codec_specific_1; - if (codec_user_config_.codec_specific_2 != 0) + } + if (codec_user_config_.codec_specific_2 != 0) { codec_config_.codec_specific_2 = codec_user_config_.codec_specific_2; - if (codec_user_config_.codec_specific_3 != 0) + } + if (codec_user_config_.codec_specific_3 != 0) { codec_config_.codec_specific_3 = codec_user_config_.codec_specific_3; - if (codec_user_config_.codec_specific_4 != 0) + } + if (codec_user_config_.codec_specific_4 != 0) { codec_config_.codec_specific_4 = codec_user_config_.codec_specific_4; + } // Create a local copy of the peer codec capability/config, and the // result codec config. if (is_capability) { - status = A2DP_BuildInfoAptxHd(AVDT_MEDIA_TYPE_AUDIO, &peer_info_cie, - ota_codec_peer_capability_); + status = + A2DP_BuildInfoAptxHd(AVDT_MEDIA_TYPE_AUDIO, &peer_info_cie, ota_codec_peer_capability_); } else { - status = A2DP_BuildInfoAptxHd(AVDT_MEDIA_TYPE_AUDIO, &peer_info_cie, - ota_codec_peer_config_); - } - log::assert_that(status == A2DP_SUCCESS, - "assert failed: status == A2DP_SUCCESS"); - status = A2DP_BuildInfoAptxHd(AVDT_MEDIA_TYPE_AUDIO, &result_config_cie, - ota_codec_config_); - log::assert_that(status == A2DP_SUCCESS, - "assert failed: status == A2DP_SUCCESS"); + status = A2DP_BuildInfoAptxHd(AVDT_MEDIA_TYPE_AUDIO, &peer_info_cie, ota_codec_peer_config_); + } + log::assert_that(status == A2DP_SUCCESS, "assert failed: status == A2DP_SUCCESS"); + status = A2DP_BuildInfoAptxHd(AVDT_MEDIA_TYPE_AUDIO, &result_config_cie, ota_codec_config_); + log::assert_that(status == A2DP_SUCCESS, "assert failed: status == A2DP_SUCCESS"); return true; fail: @@ -927,27 +901,23 @@ fail: memcpy(ota_codec_config_, saved_ota_codec_config, sizeof(ota_codec_config_)); memcpy(ota_codec_peer_capability_, saved_ota_codec_peer_capability, sizeof(ota_codec_peer_capability_)); - memcpy(ota_codec_peer_config_, saved_ota_codec_peer_config, - sizeof(ota_codec_peer_config_)); + memcpy(ota_codec_peer_config_, saved_ota_codec_peer_config, sizeof(ota_codec_peer_config_)); return false; } -bool A2dpCodecConfigAptxHd::setPeerCodecCapabilities( - const uint8_t* p_peer_codec_capabilities) { +bool A2dpCodecConfigAptxHd::setPeerCodecCapabilities(const uint8_t* p_peer_codec_capabilities) { std::lock_guard lock(codec_mutex_); tA2DP_APTX_HD_CIE peer_info_cie; uint8_t sampleRate; uint8_t channelMode; // Save the internal state - btav_a2dp_codec_config_t saved_codec_selectable_capability = - codec_selectable_capability_; + btav_a2dp_codec_config_t saved_codec_selectable_capability = codec_selectable_capability_; uint8_t saved_ota_codec_peer_capability[AVDT_CODEC_SIZE]; memcpy(saved_ota_codec_peer_capability, ota_codec_peer_capability_, sizeof(ota_codec_peer_capability_)); - tA2DP_STATUS status = - A2DP_ParseInfoAptxHd(&peer_info_cie, p_peer_codec_capabilities, true); + tA2DP_STATUS status = A2DP_ParseInfoAptxHd(&peer_info_cie, p_peer_codec_capabilities, true); if (status != A2DP_SUCCESS) { log::error("can't parse peer's capabilities: error = {}", status); goto fail; @@ -956,34 +926,26 @@ bool A2dpCodecConfigAptxHd::setPeerCodecCapabilities( // Compute the selectable capability - sample rate sampleRate = a2dp_aptx_hd_source_caps.sampleRate & peer_info_cie.sampleRate; if (sampleRate & A2DP_APTX_HD_SAMPLERATE_44100) { - codec_selectable_capability_.sample_rate |= - BTAV_A2DP_CODEC_SAMPLE_RATE_44100; + codec_selectable_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_44100; } if (sampleRate & A2DP_APTX_HD_SAMPLERATE_48000) { - codec_selectable_capability_.sample_rate |= - BTAV_A2DP_CODEC_SAMPLE_RATE_48000; + codec_selectable_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_48000; } // Compute the selectable capability - bits per sample - codec_selectable_capability_.bits_per_sample = - a2dp_aptx_hd_source_caps.bits_per_sample; + codec_selectable_capability_.bits_per_sample = a2dp_aptx_hd_source_caps.bits_per_sample; // Compute the selectable capability - channel mode - channelMode = - a2dp_aptx_hd_source_caps.channelMode & peer_info_cie.channelMode; + channelMode = a2dp_aptx_hd_source_caps.channelMode & peer_info_cie.channelMode; if (channelMode & A2DP_APTX_HD_CHANNELS_MONO) { - codec_selectable_capability_.channel_mode |= - BTAV_A2DP_CODEC_CHANNEL_MODE_MONO; + codec_selectable_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_MONO; } if (channelMode & A2DP_APTX_HD_CHANNELS_STEREO) { - codec_selectable_capability_.channel_mode |= - BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; + codec_selectable_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; } - status = A2DP_BuildInfoAptxHd(AVDT_MEDIA_TYPE_AUDIO, &peer_info_cie, - ota_codec_peer_capability_); - log::assert_that(status == A2DP_SUCCESS, - "assert failed: status == A2DP_SUCCESS"); + status = A2DP_BuildInfoAptxHd(AVDT_MEDIA_TYPE_AUDIO, &peer_info_cie, ota_codec_peer_capability_); + log::assert_that(status == A2DP_SUCCESS, "assert failed: status == A2DP_SUCCESS"); return true; fail: diff --git a/system/stack/a2dp/a2dp_vendor_aptx_hd_encoder.cc b/system/stack/a2dp/a2dp_vendor_aptx_hd_encoder.cc index fed6c9a4fc9..ea83f0391e4 100644 --- a/system/stack/a2dp/a2dp_vendor_aptx_hd_encoder.cc +++ b/system/stack/a2dp/a2dp_vendor_aptx_hd_encoder.cc @@ -39,9 +39,9 @@ using namespace bluetooth; // static const tAPTX_HD_API aptx_hd_api = { - .init_func = aptxhdbtenc_init, - .encode_stereo_func = aptxhdbtenc_encodestereo, - .sizeof_params_func = SizeofAptxhdbtenc, + .init_func = aptxhdbtenc_init, + .encode_stereo_func = aptxhdbtenc_encodestereo, + .sizeof_params_func = SizeofAptxhdbtenc, }; // offset @@ -75,7 +75,7 @@ typedef struct { bool use_SCMS_T; tA2DP_ENCODER_INIT_PEER_PARAMS peer_params; - uint32_t timestamp; // Timestamp for the A2DP frames + uint32_t timestamp; // Timestamp for the A2DP frames tA2DP_FEEDING_PARAMS feeding_params; tAPTX_HD_FRAMING_PARAMS framing_params; @@ -85,16 +85,13 @@ typedef struct { static tA2DP_APTX_HD_ENCODER_CB a2dp_aptx_hd_encoder_cb; -static void a2dp_vendor_aptx_hd_encoder_update( - A2dpCodecConfig* a2dp_codec_config, bool* p_restart_input, - bool* p_restart_output, bool* p_config_updated); -static void aptx_hd_init_framing_params( - tAPTX_HD_FRAMING_PARAMS* framing_params); -static void aptx_hd_update_framing_params( - tAPTX_HD_FRAMING_PARAMS* framing_params); -static size_t aptx_hd_encode_24bit(tAPTX_HD_FRAMING_PARAMS* framing_params, - size_t* data_out_index, uint32_t* data32_in, - uint8_t* data_out); +static void a2dp_vendor_aptx_hd_encoder_update(A2dpCodecConfig* a2dp_codec_config, + bool* p_restart_input, bool* p_restart_output, + bool* p_config_updated); +static void aptx_hd_init_framing_params(tAPTX_HD_FRAMING_PARAMS* framing_params); +static void aptx_hd_update_framing_params(tAPTX_HD_FRAMING_PARAMS* framing_params); +static size_t aptx_hd_encode_24bit(tAPTX_HD_FRAMING_PARAMS* framing_params, size_t* data_out_index, + uint32_t* data32_in, uint8_t* data_out); /******************************************************************************* * @@ -121,15 +118,13 @@ void A2DP_VendorUnloadEncoderAptxHd(void) { // nothing to do } -void a2dp_vendor_aptx_hd_encoder_init( - const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params, - A2dpCodecConfig* a2dp_codec_config, - a2dp_source_read_callback_t read_callback, - a2dp_source_enqueue_callback_t enqueue_callback) { +void a2dp_vendor_aptx_hd_encoder_init(const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params, + A2dpCodecConfig* a2dp_codec_config, + a2dp_source_read_callback_t read_callback, + a2dp_source_enqueue_callback_t enqueue_callback) { memset(&a2dp_aptx_hd_encoder_cb, 0, sizeof(a2dp_aptx_hd_encoder_cb)); - a2dp_aptx_hd_encoder_cb.stats.session_start_us = - bluetooth::common::time_get_os_boottime_us(); + a2dp_aptx_hd_encoder_cb.stats.session_start_us = bluetooth::common::time_get_os_boottime_us(); a2dp_aptx_hd_encoder_cb.read_callback = read_callback; a2dp_aptx_hd_encoder_cb.enqueue_callback = enqueue_callback; @@ -139,8 +134,7 @@ void a2dp_vendor_aptx_hd_encoder_init( /* aptX-HD encoder config */ a2dp_aptx_hd_encoder_cb.use_SCMS_T = false; - a2dp_aptx_hd_encoder_cb.aptx_hd_encoder_state = - osi_malloc(aptx_hd_api.sizeof_params_func()); + a2dp_aptx_hd_encoder_cb.aptx_hd_encoder_state = osi_malloc(aptx_hd_api.sizeof_params_func()); if (a2dp_aptx_hd_encoder_cb.aptx_hd_encoder_state != NULL) { aptx_hd_api.init_func(a2dp_aptx_hd_encoder_cb.aptx_hd_encoder_state, 0); } else { @@ -153,15 +147,15 @@ void a2dp_vendor_aptx_hd_encoder_init( bool restart_input = false; bool restart_output = false; bool config_updated = false; - a2dp_vendor_aptx_hd_encoder_update(a2dp_codec_config, &restart_input, - &restart_output, &config_updated); + a2dp_vendor_aptx_hd_encoder_update(a2dp_codec_config, &restart_input, &restart_output, + &config_updated); } // Update the A2DP aptX-HD encoder. // |a2dp_codec_config| is the A2DP codec to use for the update. -static void a2dp_vendor_aptx_hd_encoder_update( - A2dpCodecConfig* a2dp_codec_config, bool* p_restart_input, - bool* p_restart_output, bool* p_config_updated) { +static void a2dp_vendor_aptx_hd_encoder_update(A2dpCodecConfig* a2dp_codec_config, + bool* p_restart_input, bool* p_restart_output, + bool* p_config_updated) { uint8_t codec_info[AVDT_CODEC_SIZE]; *p_restart_input = false; @@ -175,17 +169,12 @@ static void a2dp_vendor_aptx_hd_encoder_update( const uint8_t* p_codec_info = codec_info; // The feeding parameters - tA2DP_FEEDING_PARAMS* p_feeding_params = - &a2dp_aptx_hd_encoder_cb.feeding_params; - p_feeding_params->sample_rate = - A2DP_VendorGetTrackSampleRateAptxHd(p_codec_info); - p_feeding_params->bits_per_sample = - a2dp_codec_config->getAudioBitsPerSample(); - p_feeding_params->channel_count = - A2DP_VendorGetTrackChannelCountAptxHd(p_codec_info); - log::info("sample_rate={} bits_per_sample={} channel_count={}", - p_feeding_params->sample_rate, p_feeding_params->bits_per_sample, - p_feeding_params->channel_count); + tA2DP_FEEDING_PARAMS* p_feeding_params = &a2dp_aptx_hd_encoder_cb.feeding_params; + p_feeding_params->sample_rate = A2DP_VendorGetTrackSampleRateAptxHd(p_codec_info); + p_feeding_params->bits_per_sample = a2dp_codec_config->getAudioBitsPerSample(); + p_feeding_params->channel_count = A2DP_VendorGetTrackChannelCountAptxHd(p_codec_info); + log::info("sample_rate={} bits_per_sample={} channel_count={}", p_feeding_params->sample_rate, + p_feeding_params->bits_per_sample, p_feeding_params->channel_count); a2dp_vendor_aptx_hd_feeding_reset(); } @@ -198,8 +187,7 @@ void a2dp_vendor_aptx_hd_encoder_cleanup(void) { // Initialize the framing parameters, and set those that don't change // while streaming (e.g., 'sleep_time_ns'). // -static void aptx_hd_init_framing_params( - tAPTX_HD_FRAMING_PARAMS* framing_params) { +static void aptx_hd_init_framing_params(tAPTX_HD_FRAMING_PARAMS* framing_params) { framing_params->sleep_time_ns = 0; framing_params->pcm_reads = 0; framing_params->pcm_bytes_per_read = 0; @@ -224,8 +212,7 @@ static void aptx_hd_init_framing_params( // and // number of aptX samples produced = pcm_bytes_per_read / 16 // -static void aptx_hd_update_framing_params( - tAPTX_HD_FRAMING_PARAMS* framing_params) { +static void aptx_hd_update_framing_params(tAPTX_HD_FRAMING_PARAMS* framing_params) { if (a2dp_aptx_hd_encoder_cb.feeding_params.sample_rate == 48000) { framing_params->aptx_hd_bytes = 648; framing_params->pcm_bytes_per_read = 24; @@ -253,16 +240,17 @@ static void aptx_hd_update_framing_params( framing_params->pcm_reads = 99; } framing_params->frame_size_counter++; - if (framing_params->frame_size_counter == 80) + if (framing_params->frame_size_counter == 80) { framing_params->frame_size_counter = 0; + } } log::verbose( - "sleep_time_ns={} aptx_hd_bytes={} pcm_bytes_per_read={} pcm_reads={} " - "frame_size_counter={}", - framing_params->sleep_time_ns, framing_params->aptx_hd_bytes, - framing_params->pcm_bytes_per_read, framing_params->pcm_reads, - framing_params->frame_size_counter); + "sleep_time_ns={} aptx_hd_bytes={} pcm_bytes_per_read={} pcm_reads={} " + "frame_size_counter={}", + framing_params->sleep_time_ns, framing_params->aptx_hd_bytes, + framing_params->pcm_bytes_per_read, framing_params->pcm_reads, + framing_params->frame_size_counter); } void a2dp_vendor_aptx_hd_feeding_reset(void) { @@ -282,8 +270,7 @@ int a2dp_vendor_aptx_hd_get_effective_frame_size() { } void a2dp_vendor_aptx_hd_send_frames(uint64_t timestamp_us) { - tAPTX_HD_FRAMING_PARAMS* framing_params = - &a2dp_aptx_hd_encoder_cb.framing_params; + tAPTX_HD_FRAMING_PARAMS* framing_params = &a2dp_aptx_hd_encoder_cb.framing_params; // Prepare the packet to send BT_HDR* p_buf = (BT_HDR*)osi_malloc(BT_DEFAULT_BUFFER_SIZE); @@ -299,27 +286,22 @@ void a2dp_vendor_aptx_hd_send_frames(uint64_t timestamp_us) { // // Read the PCM data and encode it // - uint32_t - read_buffer32[A2DP_APTX_HD_MAX_PCM_BYTES_PER_READ / sizeof(uint32_t)]; - uint32_t expected_read_bytes = - framing_params->pcm_reads * framing_params->pcm_bytes_per_read; + uint32_t read_buffer32[A2DP_APTX_HD_MAX_PCM_BYTES_PER_READ / sizeof(uint32_t)]; + uint32_t expected_read_bytes = framing_params->pcm_reads * framing_params->pcm_bytes_per_read; size_t encoded_ptr_index = 0; size_t pcm_bytes_encoded = 0; uint32_t bytes_read = 0; a2dp_aptx_hd_encoder_cb.stats.media_read_total_expected_packets++; a2dp_aptx_hd_encoder_cb.stats.media_read_total_expected_reads_count++; - a2dp_aptx_hd_encoder_cb.stats.media_read_total_expected_read_bytes += - expected_read_bytes; + a2dp_aptx_hd_encoder_cb.stats.media_read_total_expected_read_bytes += expected_read_bytes; log::verbose("PCM read of size {}", expected_read_bytes); - bytes_read = a2dp_aptx_hd_encoder_cb.read_callback((uint8_t*)read_buffer32, - expected_read_bytes); - a2dp_aptx_hd_encoder_cb.stats.media_read_total_actual_read_bytes += - bytes_read; + bytes_read = a2dp_aptx_hd_encoder_cb.read_callback((uint8_t*)read_buffer32, expected_read_bytes); + a2dp_aptx_hd_encoder_cb.stats.media_read_total_actual_read_bytes += bytes_read; if (bytes_read < expected_read_bytes) { - log::warn("underflow at PCM reading: read {} bytes instead of {}", - bytes_read, expected_read_bytes); + log::warn("underflow at PCM reading: read {} bytes instead of {}", bytes_read, + expected_read_bytes); a2dp_aptx_hd_encoder_cb.stats.media_read_total_dropped_packets++; osi_free(p_buf); return; @@ -327,11 +309,9 @@ void a2dp_vendor_aptx_hd_send_frames(uint64_t timestamp_us) { a2dp_aptx_hd_encoder_cb.stats.media_read_total_actual_reads_count++; for (uint32_t reads = 0, offset = 0; reads < framing_params->pcm_reads; - reads++, offset += - framing_params->pcm_bytes_per_read / sizeof(uint32_t)) { - pcm_bytes_encoded += - aptx_hd_encode_24bit(framing_params, &encoded_ptr_index, - read_buffer32 + offset, encoded_ptr); + reads++, offset += framing_params->pcm_bytes_per_read / sizeof(uint32_t)) { + pcm_bytes_encoded += aptx_hd_encode_24bit(framing_params, &encoded_ptr_index, + read_buffer32 + offset, encoded_ptr); } // Compute the number of encoded bytes @@ -344,15 +324,14 @@ void a2dp_vendor_aptx_hd_send_frames(uint64_t timestamp_us) { *((uint32_t*)(p_buf + 1)) = a2dp_aptx_hd_encoder_cb.timestamp; const uint8_t BYTES_PER_FRAME = 3; uint32_t rtp_timestamp = - (pcm_bytes_encoded / - a2dp_aptx_hd_encoder_cb.feeding_params.channel_count) / - BYTES_PER_FRAME; + (pcm_bytes_encoded / a2dp_aptx_hd_encoder_cb.feeding_params.channel_count) / + BYTES_PER_FRAME; // Timestamp will wrap over to 0 if stream continues on long enough // (>25H @ 48KHz). The parameters are promoted to 64bit to ensure that // no unsigned overflow is triggered as ubsan is always enabled. a2dp_aptx_hd_encoder_cb.timestamp = - ((uint64_t)a2dp_aptx_hd_encoder_cb.timestamp + rtp_timestamp) & UINT32_MAX; + ((uint64_t)a2dp_aptx_hd_encoder_cb.timestamp + rtp_timestamp) & UINT32_MAX; if (p_buf->len > 0) { a2dp_aptx_hd_encoder_cb.enqueue_callback(p_buf, 1, bytes_read); @@ -362,14 +341,12 @@ void a2dp_vendor_aptx_hd_send_frames(uint64_t timestamp_us) { } } -static size_t aptx_hd_encode_24bit(tAPTX_HD_FRAMING_PARAMS* framing_params, - size_t* data_out_index, uint32_t* data32_in, - uint8_t* data_out) { +static size_t aptx_hd_encode_24bit(tAPTX_HD_FRAMING_PARAMS* framing_params, size_t* data_out_index, + uint32_t* data32_in, uint8_t* data_out) { size_t pcm_bytes_encoded = 0; const uint8_t* p = (const uint8_t*)(data32_in); - for (size_t aptx_hd_samples = 0; - aptx_hd_samples < framing_params->pcm_bytes_per_read / 24; + for (size_t aptx_hd_samples = 0; aptx_hd_samples < framing_params->pcm_bytes_per_read / 24; aptx_hd_samples++) { uint32_t pcmL[4]; uint32_t pcmR[4]; @@ -384,9 +361,8 @@ static size_t aptx_hd_encode_24bit(tAPTX_HD_FRAMING_PARAMS* framing_params, p += 3; } - aptx_hd_api.encode_stereo_func( - a2dp_aptx_hd_encoder_cb.aptx_hd_encoder_state, &pcmL, &pcmR, - &encoded_sample); + aptx_hd_api.encode_stereo_func(a2dp_aptx_hd_encoder_cb.aptx_hd_encoder_state, &pcmL, &pcmR, + &encoded_sample); uint8_t* encoded_ptr = (uint8_t*)&encoded_sample[0]; data_out[*data_out_index + 0] = *(encoded_ptr + 2); @@ -410,23 +386,13 @@ void A2dpCodecConfigAptxHd::debug_codec_dump(int fd) { dprintf(fd, " Encoder interval (ms): %" PRIu64 "\n", a2dp_vendor_aptx_hd_get_encoder_interval_ms()); - dprintf(fd, " Effective MTU: %d\n", - a2dp_vendor_aptx_hd_get_effective_frame_size()); - dprintf(fd, - " Packet counts (expected/dropped) : %zu / " - "%zu\n", - stats->media_read_total_expected_packets, - stats->media_read_total_dropped_packets); - - dprintf(fd, - " PCM read counts (expected/actual) : %zu / " - "%zu\n", - stats->media_read_total_expected_reads_count, - stats->media_read_total_actual_reads_count); - - dprintf(fd, - " PCM read bytes (expected/actual) : %zu / " - "%zu\n", - stats->media_read_total_expected_read_bytes, - stats->media_read_total_actual_read_bytes); + dprintf(fd, " Effective MTU: %d\n", a2dp_vendor_aptx_hd_get_effective_frame_size()); + dprintf(fd, " Packet counts (expected/dropped) : %zu / %zu\n", + stats->media_read_total_expected_packets, stats->media_read_total_dropped_packets); + + dprintf(fd, " PCM read counts (expected/actual) : %zu / %zu\n", + stats->media_read_total_expected_reads_count, stats->media_read_total_actual_reads_count); + + dprintf(fd, " PCM read bytes (expected/actual) : %zu / %zu\n", + stats->media_read_total_expected_read_bytes, stats->media_read_total_actual_read_bytes); } diff --git a/system/stack/a2dp/a2dp_vendor_aptx_hd_linux.cc b/system/stack/a2dp/a2dp_vendor_aptx_hd_linux.cc index 25731516c7b..ec8cb66243c 100644 --- a/system/stack/a2dp/a2dp_vendor_aptx_hd_linux.cc +++ b/system/stack/a2dp/a2dp_vendor_aptx_hd_linux.cc @@ -20,65 +20,45 @@ #include "a2dp_vendor_aptx_hd.h" -bool A2DP_IsVendorSourceCodecValidAptxHd(const uint8_t* p_codec_info) { - return false; -} +bool A2DP_IsVendorSourceCodecValidAptxHd(const uint8_t* p_codec_info) { return false; } -bool A2DP_IsVendorPeerSinkCodecValidAptxHd(const uint8_t* p_codec_info) { - return false; -} +bool A2DP_IsVendorPeerSinkCodecValidAptxHd(const uint8_t* p_codec_info) { return false; } -bool A2DP_VendorUsesRtpHeaderAptxHd(bool content_protection_enabled, - const uint8_t* p_codec_info) { +bool A2DP_VendorUsesRtpHeaderAptxHd(bool content_protection_enabled, const uint8_t* p_codec_info) { return false; } -const char* A2DP_VendorCodecNameAptxHd(const uint8_t* p_codec_info) { - return "AptxHd"; -} +const char* A2DP_VendorCodecNameAptxHd(const uint8_t* p_codec_info) { return "AptxHd"; } bool A2DP_VendorCodecTypeEqualsAptxHd(const uint8_t* p_codec_info_a, const uint8_t* p_codec_info_b) { return false; } -bool A2DP_VendorCodecEqualsAptxHd(const uint8_t* p_codec_info_a, - const uint8_t* p_codec_info_b) { +bool A2DP_VendorCodecEqualsAptxHd(const uint8_t* p_codec_info_a, const uint8_t* p_codec_info_b) { return false; } int A2DP_VendorGetBitRateAptxHd(const uint8_t* p_codec_info) { return -1; } -int A2DP_VendorGetTrackSampleRateAptxHd(const uint8_t* p_codec_info) { - return -1; -} +int A2DP_VendorGetTrackSampleRateAptxHd(const uint8_t* p_codec_info) { return -1; } -int A2DP_VendorGetTrackBitsPerSampleAptxHd(const uint8_t* p_codec_info) { - return -1; -} +int A2DP_VendorGetTrackBitsPerSampleAptxHd(const uint8_t* p_codec_info) { return -1; } -int A2DP_VendorGetTrackChannelCountAptxHd(const uint8_t* p_codec_info) { - return -1; -} +int A2DP_VendorGetTrackChannelCountAptxHd(const uint8_t* p_codec_info) { return -1; } -int A2DP_VendorGetSinkTrackChannelTypeAptxHd(const uint8_t* p_codec_info) { - return -1; -} +int A2DP_VendorGetSinkTrackChannelTypeAptxHd(const uint8_t* p_codec_info) { return -1; } -int A2DP_VendorGetChannelModeCodeAptxHd(const uint8_t* p_codec_info) { - return -1; -} +int A2DP_VendorGetChannelModeCodeAptxHd(const uint8_t* p_codec_info) { return -1; } int A2DP_VendorGetFrameSizeAptxHd(const uint8_t* p_codec_info) { return -1; } -bool A2DP_VendorGetPacketTimestampAptxHd(const uint8_t* p_codec_info, - const uint8_t* p_data, +bool A2DP_VendorGetPacketTimestampAptxHd(const uint8_t* p_codec_info, const uint8_t* p_data, uint32_t* p_timestamp) { return false; } -bool A2DP_VendorBuildCodecHeaderAptxHd(const uint8_t* p_codec_info, - BT_HDR* p_buf, +bool A2DP_VendorBuildCodecHeaderAptxHd(const uint8_t* p_codec_info, BT_HDR* p_buf, uint16_t frames_per_packet) { return false; } @@ -87,25 +67,21 @@ std::string A2DP_VendorCodecInfoStringAptxHd(const uint8_t* p_codec_info) { return "Unsupported codec: AptxHd"; } -const tA2DP_ENCODER_INTERFACE* A2DP_VendorGetEncoderInterfaceAptxHd( - const uint8_t* p_codec_info) { +const tA2DP_ENCODER_INTERFACE* A2DP_VendorGetEncoderInterfaceAptxHd(const uint8_t* p_codec_info) { return nullptr; } -const tA2DP_DECODER_INTERFACE* A2DP_VendorGetDecoderInterfaceAptxHd( - const uint8_t* p_codec_info) { +const tA2DP_DECODER_INTERFACE* A2DP_VendorGetDecoderInterfaceAptxHd(const uint8_t* p_codec_info) { return nullptr; } bool A2DP_VendorAdjustCodecAptxHd(uint8_t* p_codec_info) { return false; } -btav_a2dp_codec_index_t A2DP_VendorSourceCodecIndexAptxHd( - const uint8_t* p_codec_info) { +btav_a2dp_codec_index_t A2DP_VendorSourceCodecIndexAptxHd(const uint8_t* p_codec_info) { return BTAV_A2DP_CODEC_INDEX_MAX; } -btav_a2dp_codec_index_t A2DP_VendorSinkCodecIndexAptxHd( - const uint8_t* p_codec_info) { +btav_a2dp_codec_index_t A2DP_VendorSinkCodecIndexAptxHd(const uint8_t* p_codec_info) { return BTAV_A2DP_CODEC_INDEX_MAX; } @@ -113,11 +89,9 @@ const char* A2DP_VendorCodecIndexStrAptxHd(void) { return "AptxHd"; } bool A2DP_VendorInitCodecConfigAptxHd(AvdtpSepConfig* p_cfg) { return false; } -A2dpCodecConfigAptxHd::A2dpCodecConfigAptxHd( - btav_a2dp_codec_priority_t codec_priority) - : A2dpCodecConfig(BTAV_A2DP_CODEC_INDEX_SOURCE_APTX_HD, - A2DP_CODEC_ID_APTX_HD, A2DP_VendorCodecIndexStrAptxHd(), - codec_priority) {} +A2dpCodecConfigAptxHd::A2dpCodecConfigAptxHd(btav_a2dp_codec_priority_t codec_priority) + : A2dpCodecConfig(BTAV_A2DP_CODEC_INDEX_SOURCE_APTX_HD, A2DP_CODEC_ID_APTX_HD, + A2DP_VendorCodecIndexStrAptxHd(), codec_priority) {} A2dpCodecConfigAptxHd::~A2dpCodecConfigAptxHd() {} @@ -127,13 +101,11 @@ bool A2dpCodecConfigAptxHd::useRtpHeaderMarkerBit() const { return false; } void A2dpCodecConfigAptxHd::debug_codec_dump(int fd) {} -bool A2dpCodecConfigAptxHd::setCodecConfig(const uint8_t* p_peer_codec_info, - bool is_capability, +bool A2dpCodecConfigAptxHd::setCodecConfig(const uint8_t* p_peer_codec_info, bool is_capability, uint8_t* p_result_codec_config) { return false; } -bool A2dpCodecConfigAptxHd::setPeerCodecCapabilities( - const uint8_t* p_peer_codec_capabilities) { +bool A2dpCodecConfigAptxHd::setPeerCodecCapabilities(const uint8_t* p_peer_codec_capabilities) { return false; } diff --git a/system/stack/a2dp/a2dp_vendor_aptx_linux.cc b/system/stack/a2dp/a2dp_vendor_aptx_linux.cc index 0b8b81ed054..3889481767a 100644 --- a/system/stack/a2dp/a2dp_vendor_aptx_linux.cc +++ b/system/stack/a2dp/a2dp_vendor_aptx_linux.cc @@ -20,59 +20,39 @@ #include "a2dp_vendor_aptx.h" -bool A2DP_IsVendorSourceCodecValidAptx(const uint8_t* p_codec_info) { - return false; -} +bool A2DP_IsVendorSourceCodecValidAptx(const uint8_t* p_codec_info) { return false; } -bool A2DP_IsVendorPeerSinkCodecValidAptx(const uint8_t* p_codec_info) { - return false; -} +bool A2DP_IsVendorPeerSinkCodecValidAptx(const uint8_t* p_codec_info) { return false; } -bool A2DP_VendorUsesRtpHeaderAptx(bool content_protection_enabled, - const uint8_t* p_codec_info) { +bool A2DP_VendorUsesRtpHeaderAptx(bool content_protection_enabled, const uint8_t* p_codec_info) { return false; } -const char* A2DP_VendorCodecNameAptx(const uint8_t* p_codec_info) { - return "Aptx"; -} +const char* A2DP_VendorCodecNameAptx(const uint8_t* p_codec_info) { return "Aptx"; } -bool A2DP_VendorCodecTypeEqualsAptx(const uint8_t* p_codec_info_a, - const uint8_t* p_codec_info_b) { +bool A2DP_VendorCodecTypeEqualsAptx(const uint8_t* p_codec_info_a, const uint8_t* p_codec_info_b) { return false; } -bool A2DP_VendorCodecEqualsAptx(const uint8_t* p_codec_info_a, - const uint8_t* p_codec_info_b) { +bool A2DP_VendorCodecEqualsAptx(const uint8_t* p_codec_info_a, const uint8_t* p_codec_info_b) { return false; } int A2DP_VendorGetBitRateAptx(const uint8_t* p_codec_info) { return -1; } -int A2DP_VendorGetTrackSampleRateAptx(const uint8_t* p_codec_info) { - return -1; -} +int A2DP_VendorGetTrackSampleRateAptx(const uint8_t* p_codec_info) { return -1; } -int A2DP_VendorGetTrackBitsPerSampleAptx(const uint8_t* p_codec_info) { - return -1; -} +int A2DP_VendorGetTrackBitsPerSampleAptx(const uint8_t* p_codec_info) { return -1; } -int A2DP_VendorGetTrackChannelCountAptx(const uint8_t* p_codec_info) { - return -1; -} +int A2DP_VendorGetTrackChannelCountAptx(const uint8_t* p_codec_info) { return -1; } -int A2DP_VendorGetSinkTrackChannelTypeAptx(const uint8_t* p_codec_info) { - return -1; -} +int A2DP_VendorGetSinkTrackChannelTypeAptx(const uint8_t* p_codec_info) { return -1; } -int A2DP_VendorGetChannelModeCodeAptx(const uint8_t* p_codec_info) { - return -1; -} +int A2DP_VendorGetChannelModeCodeAptx(const uint8_t* p_codec_info) { return -1; } int A2DP_VendorGetFrameSizeAptx(const uint8_t* p_codec_info) { return -1; } -bool A2DP_VendorGetPacketTimestampAptx(const uint8_t* p_codec_info, - const uint8_t* p_data, +bool A2DP_VendorGetPacketTimestampAptx(const uint8_t* p_codec_info, const uint8_t* p_data, uint32_t* p_timestamp) { return false; } @@ -86,25 +66,21 @@ std::string A2DP_VendorCodecInfoStringAptx(const uint8_t* p_codec_info) { return "Unsupported codec: Aptx"; } -const tA2DP_ENCODER_INTERFACE* A2DP_VendorGetEncoderInterfaceAptx( - const uint8_t* p_codec_info) { +const tA2DP_ENCODER_INTERFACE* A2DP_VendorGetEncoderInterfaceAptx(const uint8_t* p_codec_info) { return nullptr; } -const tA2DP_DECODER_INTERFACE* A2DP_VendorGetDecoderInterfaceAptx( - const uint8_t* p_codec_info) { +const tA2DP_DECODER_INTERFACE* A2DP_VendorGetDecoderInterfaceAptx(const uint8_t* p_codec_info) { return nullptr; } bool A2DP_VendorAdjustCodecAptx(uint8_t* p_codec_info) { return false; } -btav_a2dp_codec_index_t A2DP_VendorSourceCodecIndexAptx( - const uint8_t* p_codec_info) { +btav_a2dp_codec_index_t A2DP_VendorSourceCodecIndexAptx(const uint8_t* p_codec_info) { return BTAV_A2DP_CODEC_INDEX_MAX; } -btav_a2dp_codec_index_t A2DP_VendorSinkCodecIndexAptx( - const uint8_t* p_codec_info) { +btav_a2dp_codec_index_t A2DP_VendorSinkCodecIndexAptx(const uint8_t* p_codec_info) { return BTAV_A2DP_CODEC_INDEX_MAX; } @@ -112,8 +88,7 @@ const char* A2DP_VendorCodecIndexStrAptx(void) { return "Aptx"; } bool A2DP_VendorInitCodecConfigAptx(AvdtpSepConfig* p_cfg) { return false; } -A2dpCodecConfigAptx::A2dpCodecConfigAptx( - btav_a2dp_codec_priority_t codec_priority) +A2dpCodecConfigAptx::A2dpCodecConfigAptx(btav_a2dp_codec_priority_t codec_priority) : A2dpCodecConfig(BTAV_A2DP_CODEC_INDEX_SOURCE_APTX, A2DP_CODEC_ID_APTX, A2DP_VendorCodecIndexStrAptx(), codec_priority) {} @@ -125,13 +100,11 @@ bool A2dpCodecConfigAptx::useRtpHeaderMarkerBit() const { return false; } void A2dpCodecConfigAptx::debug_codec_dump(int fd) {} -bool A2dpCodecConfigAptx::setCodecConfig(const uint8_t* p_peer_codec_info, - bool is_capability, +bool A2dpCodecConfigAptx::setCodecConfig(const uint8_t* p_peer_codec_info, bool is_capability, uint8_t* p_result_codec_config) { return false; } -bool A2dpCodecConfigAptx::setPeerCodecCapabilities( - const uint8_t* p_peer_codec_capabilities) { +bool A2dpCodecConfigAptx::setPeerCodecCapabilities(const uint8_t* p_peer_codec_capabilities) { return false; } diff --git a/system/stack/a2dp/a2dp_vendor_ldac.cc b/system/stack/a2dp/a2dp_vendor_ldac.cc index e898299fd96..655d056317e 100644 --- a/system/stack/a2dp/a2dp_vendor_ldac.cc +++ b/system/stack/a2dp/a2dp_vendor_ldac.cc @@ -50,67 +50,65 @@ typedef struct { /* LDAC Source codec capabilities */ static const tA2DP_LDAC_CIE a2dp_ldac_source_caps = { - A2DP_LDAC_VENDOR_ID, // vendorId - A2DP_LDAC_CODEC_ID, // codecId - // sampleRate - (A2DP_LDAC_SAMPLING_FREQ_44100 | A2DP_LDAC_SAMPLING_FREQ_48000 | - A2DP_LDAC_SAMPLING_FREQ_88200 | A2DP_LDAC_SAMPLING_FREQ_96000), - // channelMode - (A2DP_LDAC_CHANNEL_MODE_DUAL | A2DP_LDAC_CHANNEL_MODE_STEREO), - // bits_per_sample - (BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16 | BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24 | - BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32)}; + A2DP_LDAC_VENDOR_ID, // vendorId + A2DP_LDAC_CODEC_ID, // codecId + // sampleRate + (A2DP_LDAC_SAMPLING_FREQ_44100 | A2DP_LDAC_SAMPLING_FREQ_48000 | + A2DP_LDAC_SAMPLING_FREQ_88200 | A2DP_LDAC_SAMPLING_FREQ_96000), + // channelMode + (A2DP_LDAC_CHANNEL_MODE_DUAL | A2DP_LDAC_CHANNEL_MODE_STEREO), + // bits_per_sample + (BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16 | BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24 | + BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32)}; /* LDAC Sink codec capabilities */ static const tA2DP_LDAC_CIE a2dp_ldac_sink_caps = { - A2DP_LDAC_VENDOR_ID, // vendorId - A2DP_LDAC_CODEC_ID, // codecId - // sampleRate - (A2DP_LDAC_SAMPLING_FREQ_44100 | A2DP_LDAC_SAMPLING_FREQ_48000 | - A2DP_LDAC_SAMPLING_FREQ_88200 | A2DP_LDAC_SAMPLING_FREQ_96000), - // channelMode - (A2DP_LDAC_CHANNEL_MODE_MONO | A2DP_LDAC_CHANNEL_MODE_DUAL | - A2DP_LDAC_CHANNEL_MODE_STEREO), - // bits_per_sample - (BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16 | BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24 | - BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32)}; + A2DP_LDAC_VENDOR_ID, // vendorId + A2DP_LDAC_CODEC_ID, // codecId + // sampleRate + (A2DP_LDAC_SAMPLING_FREQ_44100 | A2DP_LDAC_SAMPLING_FREQ_48000 | + A2DP_LDAC_SAMPLING_FREQ_88200 | A2DP_LDAC_SAMPLING_FREQ_96000), + // channelMode + (A2DP_LDAC_CHANNEL_MODE_MONO | A2DP_LDAC_CHANNEL_MODE_DUAL | A2DP_LDAC_CHANNEL_MODE_STEREO), + // bits_per_sample + (BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16 | BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24 | + BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32)}; /* Default LDAC codec configuration */ static const tA2DP_LDAC_CIE a2dp_ldac_default_config = { - A2DP_LDAC_VENDOR_ID, // vendorId - A2DP_LDAC_CODEC_ID, // codecId - A2DP_LDAC_SAMPLING_FREQ_96000, // sampleRate - A2DP_LDAC_CHANNEL_MODE_STEREO, // channelMode - BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32 // bits_per_sample + A2DP_LDAC_VENDOR_ID, // vendorId + A2DP_LDAC_CODEC_ID, // codecId + A2DP_LDAC_SAMPLING_FREQ_96000, // sampleRate + A2DP_LDAC_CHANNEL_MODE_STEREO, // channelMode + BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32 // bits_per_sample }; static const tA2DP_ENCODER_INTERFACE a2dp_encoder_interface_ldac = { - a2dp_vendor_ldac_encoder_init, - a2dp_vendor_ldac_encoder_cleanup, - a2dp_vendor_ldac_feeding_reset, - a2dp_vendor_ldac_feeding_flush, - a2dp_vendor_ldac_get_encoder_interval_ms, - a2dp_vendor_ldac_get_effective_frame_size, - a2dp_vendor_ldac_send_frames, - a2dp_vendor_ldac_set_transmit_queue_length}; + a2dp_vendor_ldac_encoder_init, + a2dp_vendor_ldac_encoder_cleanup, + a2dp_vendor_ldac_feeding_reset, + a2dp_vendor_ldac_feeding_flush, + a2dp_vendor_ldac_get_encoder_interval_ms, + a2dp_vendor_ldac_get_effective_frame_size, + a2dp_vendor_ldac_send_frames, + a2dp_vendor_ldac_set_transmit_queue_length}; static const tA2DP_DECODER_INTERFACE a2dp_decoder_interface_ldac = { - a2dp_vendor_ldac_decoder_init, a2dp_vendor_ldac_decoder_cleanup, - a2dp_vendor_ldac_decoder_decode_packet, a2dp_vendor_ldac_decoder_start, - a2dp_vendor_ldac_decoder_suspend, a2dp_vendor_ldac_decoder_configure, + a2dp_vendor_ldac_decoder_init, a2dp_vendor_ldac_decoder_cleanup, + a2dp_vendor_ldac_decoder_decode_packet, a2dp_vendor_ldac_decoder_start, + a2dp_vendor_ldac_decoder_suspend, a2dp_vendor_ldac_decoder_configure, }; -static tA2DP_STATUS A2DP_CodecInfoMatchesCapabilityLdac( - const tA2DP_LDAC_CIE* p_cap, const uint8_t* p_codec_info, - bool is_peer_codec_info); +static tA2DP_STATUS A2DP_CodecInfoMatchesCapabilityLdac(const tA2DP_LDAC_CIE* p_cap, + const uint8_t* p_codec_info, + bool is_peer_codec_info); // Builds the LDAC Media Codec Capabilities byte sequence beginning from the // LOSC octet. |media_type| is the media type |AVDT_MEDIA_TYPE_*|. // |p_ie| is a pointer to the LDAC Codec Information Element information. // The result is stored in |p_result|. Returns A2DP_SUCCESS on success, // otherwise the corresponding A2DP error status code. -static tA2DP_STATUS A2DP_BuildInfoLdac(uint8_t media_type, - const tA2DP_LDAC_CIE* p_ie, +static tA2DP_STATUS A2DP_BuildInfoLdac(uint8_t media_type, const tA2DP_LDAC_CIE* p_ie, uint8_t* p_result) { if (p_ie == NULL || p_result == NULL) { return A2DP_INVALID_PARAMS; @@ -130,12 +128,16 @@ static tA2DP_STATUS A2DP_BuildInfoLdac(uint8_t media_type, // Sampling Frequency *p_result = (uint8_t)(p_ie->sampleRate & A2DP_LDAC_SAMPLING_FREQ_MASK); - if (*p_result == 0) return A2DP_INVALID_PARAMS; + if (*p_result == 0) { + return A2DP_INVALID_PARAMS; + } p_result++; // Channel Mode *p_result = (uint8_t)(p_ie->channelMode & A2DP_LDAC_CHANNEL_MODE_MASK); - if (*p_result == 0) return A2DP_INVALID_PARAMS; + if (*p_result == 0) { + return A2DP_INVALID_PARAMS; + } return A2DP_SUCCESS; } @@ -146,38 +148,37 @@ static tA2DP_STATUS A2DP_BuildInfoLdac(uint8_t media_type, // codec capabilities, otherwise is codec configuration. // Returns A2DP_SUCCESS on success, otherwise the corresponding A2DP error // status code. -static tA2DP_STATUS A2DP_ParseInfoLdac(tA2DP_LDAC_CIE* p_ie, - const uint8_t* p_codec_info, +static tA2DP_STATUS A2DP_ParseInfoLdac(tA2DP_LDAC_CIE* p_ie, const uint8_t* p_codec_info, bool is_capability) { uint8_t losc; uint8_t media_type; tA2DP_CODEC_TYPE codec_type; - if (p_ie == NULL || p_codec_info == NULL) return A2DP_INVALID_PARAMS; + if (p_ie == NULL || p_codec_info == NULL) { + return A2DP_INVALID_PARAMS; + } // Check the codec capability length losc = *p_codec_info++; - if (losc != A2DP_LDAC_CODEC_LEN) return A2DP_WRONG_CODEC; + if (losc != A2DP_LDAC_CODEC_LEN) { + return A2DP_WRONG_CODEC; + } media_type = (*p_codec_info++) >> 4; codec_type = *p_codec_info++; /* Check the Media Type and Media Codec Type */ - if (media_type != AVDT_MEDIA_TYPE_AUDIO || - codec_type != A2DP_MEDIA_CT_NON_A2DP) { + if (media_type != AVDT_MEDIA_TYPE_AUDIO || codec_type != A2DP_MEDIA_CT_NON_A2DP) { return A2DP_WRONG_CODEC; } // Check the Vendor ID and Codec ID */ - p_ie->vendorId = (*p_codec_info & 0x000000FF) | - (*(p_codec_info + 1) << 8 & 0x0000FF00) | + p_ie->vendorId = (*p_codec_info & 0x000000FF) | (*(p_codec_info + 1) << 8 & 0x0000FF00) | (*(p_codec_info + 2) << 16 & 0x00FF0000) | (*(p_codec_info + 3) << 24 & 0xFF000000); p_codec_info += 4; - p_ie->codecId = - (*p_codec_info & 0x00FF) | (*(p_codec_info + 1) << 8 & 0xFF00); + p_ie->codecId = (*p_codec_info & 0x00FF) | (*(p_codec_info + 1) << 8 & 0xFF00); p_codec_info += 2; - if (p_ie->vendorId != A2DP_LDAC_VENDOR_ID || - p_ie->codecId != A2DP_LDAC_CODEC_ID) { + if (p_ie->vendorId != A2DP_LDAC_VENDOR_ID || p_ie->codecId != A2DP_LDAC_CODEC_ID) { return A2DP_WRONG_CODEC; } @@ -187,18 +188,22 @@ static tA2DP_STATUS A2DP_ParseInfoLdac(tA2DP_LDAC_CIE* p_ie, if (is_capability) { // NOTE: The checks here are very liberal. We should be using more // pedantic checks specific to the SRC or SNK as specified in the spec. - if (A2DP_BitsSet(p_ie->sampleRate) == A2DP_SET_ZERO_BIT) + if (A2DP_BitsSet(p_ie->sampleRate) == A2DP_SET_ZERO_BIT) { return A2DP_BAD_SAMP_FREQ; - if (A2DP_BitsSet(p_ie->channelMode) == A2DP_SET_ZERO_BIT) + } + if (A2DP_BitsSet(p_ie->channelMode) == A2DP_SET_ZERO_BIT) { return A2DP_BAD_CH_MODE; + } return A2DP_SUCCESS; } - if (A2DP_BitsSet(p_ie->sampleRate) != A2DP_SET_ONE_BIT) + if (A2DP_BitsSet(p_ie->sampleRate) != A2DP_SET_ONE_BIT) { return A2DP_BAD_SAMP_FREQ; - if (A2DP_BitsSet(p_ie->channelMode) != A2DP_SET_ONE_BIT) + } + if (A2DP_BitsSet(p_ie->channelMode) != A2DP_SET_ONE_BIT) { return A2DP_BAD_CH_MODE; + } return A2DP_SUCCESS; } @@ -210,15 +215,22 @@ static tA2DP_STATUS A2DP_ParseInfoLdac(tA2DP_LDAC_CIE* p_ie, // |last| is true for the last packet of a fragmented frame. // If |frag| is false, |num| is the number of number of frames in the packet, // otherwise is the number of remaining fragments (including this one). -static void A2DP_BuildMediaPayloadHeaderLdac(uint8_t* p_dst, bool frag, - bool start, bool last, +static void A2DP_BuildMediaPayloadHeaderLdac(uint8_t* p_dst, bool frag, bool start, bool last, uint8_t num) { - if (p_dst == NULL) return; + if (p_dst == NULL) { + return; + } *p_dst = 0; - if (frag) *p_dst |= A2DP_LDAC_HDR_F_MSK; - if (start) *p_dst |= A2DP_LDAC_HDR_S_MSK; - if (last) *p_dst |= A2DP_LDAC_HDR_L_MSK; + if (frag) { + *p_dst |= A2DP_LDAC_HDR_F_MSK; + } + if (start) { + *p_dst |= A2DP_LDAC_HDR_S_MSK; + } + if (last) { + *p_dst |= A2DP_LDAC_HDR_L_MSK; + } *p_dst |= (A2DP_LDAC_HDR_NUM_MSK & num); } @@ -255,12 +267,12 @@ bool A2DP_IsVendorPeerSinkCodecValidLdac(const uint8_t* p_codec_info) { } bool A2DP_IsVendorSinkCodecSupportedLdac(const uint8_t* p_codec_info) { - return A2DP_CodecInfoMatchesCapabilityLdac(&a2dp_ldac_sink_caps, p_codec_info, - false) == A2DP_SUCCESS; + return A2DP_CodecInfoMatchesCapabilityLdac(&a2dp_ldac_sink_caps, p_codec_info, false) == + A2DP_SUCCESS; } bool A2DP_IsPeerSourceCodecSupportedLdac(const uint8_t* p_codec_info) { - return A2DP_CodecInfoMatchesCapabilityLdac(&a2dp_ldac_sink_caps, p_codec_info, - true) == A2DP_SUCCESS; + return A2DP_CodecInfoMatchesCapabilityLdac(&a2dp_ldac_sink_caps, p_codec_info, true) == + A2DP_SUCCESS; } // Checks whether A2DP LDAC codec configuration matches with a device's codec @@ -272,9 +284,9 @@ bool A2DP_IsPeerSourceCodecSupportedLdac(const uint8_t* p_codec_info) { // is acting as an A2DP source. // Returns A2DP_SUCCESS if the codec configuration matches with capabilities, // otherwise the corresponding A2DP error status code. -static tA2DP_STATUS A2DP_CodecInfoMatchesCapabilityLdac( - const tA2DP_LDAC_CIE* p_cap, const uint8_t* p_codec_info, - bool is_capability) { +static tA2DP_STATUS A2DP_CodecInfoMatchesCapabilityLdac(const tA2DP_LDAC_CIE* p_cap, + const uint8_t* p_codec_info, + bool is_capability) { tA2DP_STATUS status; tA2DP_LDAC_CIE cfg_cie; @@ -287,16 +299,18 @@ static tA2DP_STATUS A2DP_CodecInfoMatchesCapabilityLdac( /* verify that each parameter is in range */ - log::verbose("FREQ peer: 0x{:x}, capability 0x{:x}", cfg_cie.sampleRate, - p_cap->sampleRate); - log::verbose("CH_MODE peer: 0x{:x}, capability 0x{:x}", cfg_cie.channelMode, - p_cap->channelMode); + log::verbose("FREQ peer: 0x{:x}, capability 0x{:x}", cfg_cie.sampleRate, p_cap->sampleRate); + log::verbose("CH_MODE peer: 0x{:x}, capability 0x{:x}", cfg_cie.channelMode, p_cap->channelMode); /* sampling frequency */ - if ((cfg_cie.sampleRate & p_cap->sampleRate) == 0) return A2DP_NS_SAMP_FREQ; + if ((cfg_cie.sampleRate & p_cap->sampleRate) == 0) { + return A2DP_NS_SAMP_FREQ; + } /* channel mode */ - if ((cfg_cie.channelMode & p_cap->channelMode) == 0) return A2DP_NS_CH_MODE; + if ((cfg_cie.channelMode & p_cap->channelMode) == 0) { + return A2DP_NS_CH_MODE; + } return A2DP_SUCCESS; } @@ -307,18 +321,14 @@ bool A2DP_VendorUsesRtpHeaderLdac(bool /* content_protection_enabled */, return true; } -const char* A2DP_VendorCodecNameLdac(const uint8_t* /* p_codec_info */) { - return "LDAC"; -} +const char* A2DP_VendorCodecNameLdac(const uint8_t* /* p_codec_info */) { return "LDAC"; } -bool A2DP_VendorCodecTypeEqualsLdac(const uint8_t* p_codec_info_a, - const uint8_t* p_codec_info_b) { +bool A2DP_VendorCodecTypeEqualsLdac(const uint8_t* p_codec_info_a, const uint8_t* p_codec_info_b) { tA2DP_LDAC_CIE ldac_cie_a; tA2DP_LDAC_CIE ldac_cie_b; // Check whether the codec info contains valid data - tA2DP_STATUS a2dp_status = - A2DP_ParseInfoLdac(&ldac_cie_a, p_codec_info_a, true); + tA2DP_STATUS a2dp_status = A2DP_ParseInfoLdac(&ldac_cie_a, p_codec_info_a, true); if (a2dp_status != A2DP_SUCCESS) { log::error("cannot decode codec information: {}", a2dp_status); return false; @@ -332,14 +342,12 @@ bool A2DP_VendorCodecTypeEqualsLdac(const uint8_t* p_codec_info_a, return true; } -bool A2DP_VendorCodecEqualsLdac(const uint8_t* p_codec_info_a, - const uint8_t* p_codec_info_b) { +bool A2DP_VendorCodecEqualsLdac(const uint8_t* p_codec_info_a, const uint8_t* p_codec_info_b) { tA2DP_LDAC_CIE ldac_cie_a; tA2DP_LDAC_CIE ldac_cie_b; // Check whether the codec info contains valid data - tA2DP_STATUS a2dp_status = - A2DP_ParseInfoLdac(&ldac_cie_a, p_codec_info_a, true); + tA2DP_STATUS a2dp_status = A2DP_ParseInfoLdac(&ldac_cie_a, p_codec_info_a, true); if (a2dp_status != A2DP_SUCCESS) { log::error("cannot decode codec information: {}", a2dp_status); return false; @@ -360,26 +368,30 @@ int A2DP_VendorGetBitRateLdac(const uint8_t* p_codec_info) { int samplerate = A2DP_GetTrackSampleRate(p_codec_info); switch (codec_config_.codec_specific_1 % 10) { case 0: - if (samplerate == 44100 || samplerate == 88200) + if (samplerate == 44100 || samplerate == 88200) { return 909000; - else + } else { return 990000; + } case 1: - if (samplerate == 44100 || samplerate == 88200) + if (samplerate == 44100 || samplerate == 88200) { return 606000; - else + } else { return 660000; + } case 2: - if (samplerate == 44100 || samplerate == 88200) + if (samplerate == 44100 || samplerate == 88200) { return 303000; - else + } else { return 330000; + } case 3: default: - if (samplerate == 44100 || samplerate == 88200) + if (samplerate == 44100 || samplerate == 88200) { return 909000; - else + } else { return 990000; + } } return 0; } @@ -506,16 +518,14 @@ int A2DP_VendorGetChannelModeCodeLdac(const uint8_t* p_codec_info) { return -1; } -bool A2DP_VendorGetPacketTimestampLdac(const uint8_t* /* p_codec_info */, - const uint8_t* p_data, +bool A2DP_VendorGetPacketTimestampLdac(const uint8_t* /* p_codec_info */, const uint8_t* p_data, uint32_t* p_timestamp) { // TODO: Is this function really codec-specific? *p_timestamp = *(const uint32_t*)p_data; return true; } -bool A2DP_VendorBuildCodecHeaderLdac(const uint8_t* /* p_codec_info */, - BT_HDR* p_buf, +bool A2DP_VendorBuildCodecHeaderLdac(const uint8_t* /* p_codec_info */, BT_HDR* p_buf, uint16_t frames_per_packet) { uint8_t* p; @@ -527,8 +537,7 @@ bool A2DP_VendorBuildCodecHeaderLdac(const uint8_t* /* p_codec_info */, p_buf->offset -= A2DP_LDAC_MPL_HDR_LEN; p = (uint8_t*)(p_buf + 1) + p_buf->offset; p_buf->len += A2DP_LDAC_MPL_HDR_LEN; - A2DP_BuildMediaPayloadHeaderLdac(p, false, false, false, - (uint8_t)frames_per_packet); + A2DP_BuildMediaPayloadHeaderLdac(p, false, false, false, (uint8_t)frames_per_packet); return true; } @@ -541,8 +550,7 @@ std::string A2DP_VendorCodecInfoStringLdac(const uint8_t* p_codec_info) { a2dp_status = A2DP_ParseInfoLdac(&ldac_cie, p_codec_info, true); if (a2dp_status != A2DP_SUCCESS) { - res << "A2DP_ParseInfoLdac fail: " - << loghex(static_cast(a2dp_status)); + res << "A2DP_ParseInfoLdac fail: " << loghex(static_cast(a2dp_status)); return res.str(); } @@ -551,46 +559,37 @@ std::string A2DP_VendorCodecInfoStringLdac(const uint8_t* p_codec_info) { // Sample frequency field.clear(); AppendField(&field, (ldac_cie.sampleRate == 0), "NONE"); - AppendField(&field, (ldac_cie.sampleRate & A2DP_LDAC_SAMPLING_FREQ_44100), - "44100"); - AppendField(&field, (ldac_cie.sampleRate & A2DP_LDAC_SAMPLING_FREQ_48000), - "48000"); - AppendField(&field, (ldac_cie.sampleRate & A2DP_LDAC_SAMPLING_FREQ_88200), - "88200"); - AppendField(&field, (ldac_cie.sampleRate & A2DP_LDAC_SAMPLING_FREQ_96000), - "96000"); - AppendField(&field, (ldac_cie.sampleRate & A2DP_LDAC_SAMPLING_FREQ_176400), - "176400"); - AppendField(&field, (ldac_cie.sampleRate & A2DP_LDAC_SAMPLING_FREQ_192000), - "192000"); - res << "\tsamp_freq: " << field << " (" << loghex(ldac_cie.sampleRate) - << ")\n"; + AppendField(&field, (ldac_cie.sampleRate & A2DP_LDAC_SAMPLING_FREQ_44100), "44100"); + AppendField(&field, (ldac_cie.sampleRate & A2DP_LDAC_SAMPLING_FREQ_48000), "48000"); + AppendField(&field, (ldac_cie.sampleRate & A2DP_LDAC_SAMPLING_FREQ_88200), "88200"); + AppendField(&field, (ldac_cie.sampleRate & A2DP_LDAC_SAMPLING_FREQ_96000), "96000"); + AppendField(&field, (ldac_cie.sampleRate & A2DP_LDAC_SAMPLING_FREQ_176400), "176400"); + AppendField(&field, (ldac_cie.sampleRate & A2DP_LDAC_SAMPLING_FREQ_192000), "192000"); + res << "\tsamp_freq: " << field << " (" << loghex(ldac_cie.sampleRate) << ")\n"; // Channel mode field.clear(); AppendField(&field, (ldac_cie.channelMode == 0), "NONE"); - AppendField(&field, (ldac_cie.channelMode & A2DP_LDAC_CHANNEL_MODE_MONO), - "Mono"); - AppendField(&field, (ldac_cie.channelMode & A2DP_LDAC_CHANNEL_MODE_DUAL), - "Dual"); - AppendField(&field, (ldac_cie.channelMode & A2DP_LDAC_CHANNEL_MODE_STEREO), - "Stereo"); - res << "\tch_mode: " << field << " (" << loghex(ldac_cie.channelMode) - << ")\n"; + AppendField(&field, (ldac_cie.channelMode & A2DP_LDAC_CHANNEL_MODE_MONO), "Mono"); + AppendField(&field, (ldac_cie.channelMode & A2DP_LDAC_CHANNEL_MODE_DUAL), "Dual"); + AppendField(&field, (ldac_cie.channelMode & A2DP_LDAC_CHANNEL_MODE_STEREO), "Stereo"); + res << "\tch_mode: " << field << " (" << loghex(ldac_cie.channelMode) << ")\n"; return res.str(); } -const tA2DP_ENCODER_INTERFACE* A2DP_VendorGetEncoderInterfaceLdac( - const uint8_t* p_codec_info) { - if (!A2DP_IsVendorSourceCodecValidLdac(p_codec_info)) return NULL; +const tA2DP_ENCODER_INTERFACE* A2DP_VendorGetEncoderInterfaceLdac(const uint8_t* p_codec_info) { + if (!A2DP_IsVendorSourceCodecValidLdac(p_codec_info)) { + return NULL; + } return &a2dp_encoder_interface_ldac; } -const tA2DP_DECODER_INTERFACE* A2DP_VendorGetDecoderInterfaceLdac( - const uint8_t* p_codec_info) { - if (!A2DP_IsVendorSinkCodecValidLdac(p_codec_info)) return NULL; +const tA2DP_DECODER_INTERFACE* A2DP_VendorGetDecoderInterfaceLdac(const uint8_t* p_codec_info) { + if (!A2DP_IsVendorSinkCodecValidLdac(p_codec_info)) { + return NULL; + } return &a2dp_decoder_interface_ldac; } @@ -599,19 +598,18 @@ bool A2DP_VendorAdjustCodecLdac(uint8_t* p_codec_info) { tA2DP_LDAC_CIE cfg_cie; // Nothing to do: just verify the codec info is valid - if (A2DP_ParseInfoLdac(&cfg_cie, p_codec_info, true) != A2DP_SUCCESS) + if (A2DP_ParseInfoLdac(&cfg_cie, p_codec_info, true) != A2DP_SUCCESS) { return false; + } return true; } -btav_a2dp_codec_index_t A2DP_VendorSourceCodecIndexLdac( - const uint8_t* /* p_codec_info */) { +btav_a2dp_codec_index_t A2DP_VendorSourceCodecIndexLdac(const uint8_t* /* p_codec_info */) { return BTAV_A2DP_CODEC_INDEX_SOURCE_LDAC; } -btav_a2dp_codec_index_t A2DP_VendorSinkCodecIndexLdac( - const uint8_t* /* p_codec_info */) { +btav_a2dp_codec_index_t A2DP_VendorSinkCodecIndexLdac(const uint8_t* /* p_codec_info */) { return BTAV_A2DP_CODEC_INDEX_SINK_LDAC; } @@ -620,8 +618,8 @@ const char* A2DP_VendorCodecIndexStrLdac(void) { return "LDAC"; } const char* A2DP_VendorCodecIndexStrLdacSink(void) { return "LDAC SINK"; } bool A2DP_VendorInitCodecConfigLdac(AvdtpSepConfig* p_cfg) { - if (A2DP_BuildInfoLdac(AVDT_MEDIA_TYPE_AUDIO, &a2dp_ldac_source_caps, - p_cfg->codec_info) != A2DP_SUCCESS) { + if (A2DP_BuildInfoLdac(AVDT_MEDIA_TYPE_AUDIO, &a2dp_ldac_source_caps, p_cfg->codec_info) != + A2DP_SUCCESS) { return false; } @@ -629,40 +627,44 @@ bool A2DP_VendorInitCodecConfigLdac(AvdtpSepConfig* p_cfg) { } bool A2DP_VendorInitCodecConfigLdacSink(AvdtpSepConfig* p_cfg) { - return A2DP_BuildInfoLdac(AVDT_MEDIA_TYPE_AUDIO, &a2dp_ldac_sink_caps, - p_cfg->codec_info) == A2DP_SUCCESS; + return A2DP_BuildInfoLdac(AVDT_MEDIA_TYPE_AUDIO, &a2dp_ldac_sink_caps, p_cfg->codec_info) == + A2DP_SUCCESS; } UNUSED_ATTR static void build_codec_config(const tA2DP_LDAC_CIE& config_cie, btav_a2dp_codec_config_t* result) { - if (config_cie.sampleRate & A2DP_LDAC_SAMPLING_FREQ_44100) + if (config_cie.sampleRate & A2DP_LDAC_SAMPLING_FREQ_44100) { result->sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_44100; - if (config_cie.sampleRate & A2DP_LDAC_SAMPLING_FREQ_48000) + } + if (config_cie.sampleRate & A2DP_LDAC_SAMPLING_FREQ_48000) { result->sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_48000; - if (config_cie.sampleRate & A2DP_LDAC_SAMPLING_FREQ_88200) + } + if (config_cie.sampleRate & A2DP_LDAC_SAMPLING_FREQ_88200) { result->sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_88200; - if (config_cie.sampleRate & A2DP_LDAC_SAMPLING_FREQ_96000) + } + if (config_cie.sampleRate & A2DP_LDAC_SAMPLING_FREQ_96000) { result->sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_96000; - if (config_cie.sampleRate & A2DP_LDAC_SAMPLING_FREQ_176400) + } + if (config_cie.sampleRate & A2DP_LDAC_SAMPLING_FREQ_176400) { result->sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_176400; - if (config_cie.sampleRate & A2DP_LDAC_SAMPLING_FREQ_192000) + } + if (config_cie.sampleRate & A2DP_LDAC_SAMPLING_FREQ_192000) { result->sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_192000; + } result->bits_per_sample = config_cie.bits_per_sample; - if (config_cie.channelMode & A2DP_LDAC_CHANNEL_MODE_MONO) + if (config_cie.channelMode & A2DP_LDAC_CHANNEL_MODE_MONO) { result->channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_MONO; - if (config_cie.channelMode & - (A2DP_LDAC_CHANNEL_MODE_DUAL | A2DP_LDAC_CHANNEL_MODE_STEREO)) { + } + if (config_cie.channelMode & (A2DP_LDAC_CHANNEL_MODE_DUAL | A2DP_LDAC_CHANNEL_MODE_STEREO)) { result->channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; } } -A2dpCodecConfigLdacSource::A2dpCodecConfigLdacSource( - btav_a2dp_codec_priority_t codec_priority) - : A2dpCodecConfigLdacBase(BTAV_A2DP_CODEC_INDEX_SOURCE_LDAC, - A2DP_VendorCodecIndexStrLdac(), codec_priority, - true) { +A2dpCodecConfigLdacSource::A2dpCodecConfigLdacSource(btav_a2dp_codec_priority_t codec_priority) + : A2dpCodecConfigLdacBase(BTAV_A2DP_CODEC_INDEX_SOURCE_LDAC, A2DP_VendorCodecIndexStrLdac(), + codec_priority, true) { // Compute the local capability if (a2dp_ldac_source_caps.sampleRate & A2DP_LDAC_SAMPLING_FREQ_44100) { codec_local_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_44100; @@ -682,8 +684,7 @@ A2dpCodecConfigLdacSource::A2dpCodecConfigLdacSource( if (a2dp_ldac_source_caps.sampleRate & A2DP_LDAC_SAMPLING_FREQ_192000) { codec_local_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_192000; } - codec_local_capability_.bits_per_sample = - a2dp_ldac_source_caps.bits_per_sample; + codec_local_capability_.bits_per_sample = a2dp_ldac_source_caps.bits_per_sample; if (a2dp_ldac_source_caps.channelMode & A2DP_LDAC_CHANNEL_MODE_MONO) { codec_local_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_MONO; } @@ -698,7 +699,9 @@ A2dpCodecConfigLdacSource::A2dpCodecConfigLdacSource( A2dpCodecConfigLdacSource::~A2dpCodecConfigLdacSource() {} bool A2dpCodecConfigLdacSource::init() { - if (!isValid()) return false; + if (!isValid()) { + return false; + } // Load the encoder if (!A2DP_VendorLoadEncoderLdac()) { @@ -716,8 +719,7 @@ bool A2dpCodecConfigLdacSource::useRtpHeaderMarkerBit() const { return false; } // The result is stored in |p_result| and |p_codec_config|. // Returns true if a selection was made, otherwise false. // -static bool select_best_sample_rate(uint8_t sampleRate, - tA2DP_LDAC_CIE* p_result, +static bool select_best_sample_rate(uint8_t sampleRate, tA2DP_LDAC_CIE* p_result, btav_a2dp_codec_config_t* p_codec_config) { if (sampleRate & A2DP_LDAC_SAMPLING_FREQ_192000) { p_result->sampleRate = A2DP_LDAC_SAMPLING_FREQ_192000; @@ -758,9 +760,9 @@ static bool select_best_sample_rate(uint8_t sampleRate, // The result is stored in |p_result| and |p_codec_config|. // Returns true if a selection was made, otherwise false. // -static bool select_audio_sample_rate( - const btav_a2dp_codec_config_t* p_codec_audio_config, uint8_t sampleRate, - tA2DP_LDAC_CIE* p_result, btav_a2dp_codec_config_t* p_codec_config) { +static bool select_audio_sample_rate(const btav_a2dp_codec_config_t* p_codec_audio_config, + uint8_t sampleRate, tA2DP_LDAC_CIE* p_result, + btav_a2dp_codec_config_t* p_codec_config) { switch (p_codec_audio_config->sample_rate) { case BTAV_A2DP_CODEC_SAMPLE_RATE_44100: if (sampleRate & A2DP_LDAC_SAMPLING_FREQ_44100) { @@ -818,9 +820,9 @@ static bool select_audio_sample_rate( // The result is stored in |p_result| and |p_codec_config|. // Returns true if a selection was made, otherwise false. // -static bool select_best_bits_per_sample( - btav_a2dp_codec_bits_per_sample_t bits_per_sample, tA2DP_LDAC_CIE* p_result, - btav_a2dp_codec_config_t* p_codec_config) { +static bool select_best_bits_per_sample(btav_a2dp_codec_bits_per_sample_t bits_per_sample, + tA2DP_LDAC_CIE* p_result, + btav_a2dp_codec_config_t* p_codec_config) { if (bits_per_sample & BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32) { p_codec_config->bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32; p_result->bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32; @@ -845,10 +847,10 @@ static bool select_best_bits_per_sample( // The result is stored in |p_result| and |p_codec_config|. // Returns true if a selection was made, otherwise false. // -static bool select_audio_bits_per_sample( - const btav_a2dp_codec_config_t* p_codec_audio_config, - btav_a2dp_codec_bits_per_sample_t bits_per_sample, tA2DP_LDAC_CIE* p_result, - btav_a2dp_codec_config_t* p_codec_config) { +static bool select_audio_bits_per_sample(const btav_a2dp_codec_config_t* p_codec_audio_config, + btav_a2dp_codec_bits_per_sample_t bits_per_sample, + tA2DP_LDAC_CIE* p_result, + btav_a2dp_codec_config_t* p_codec_config) { switch (p_codec_audio_config->bits_per_sample) { case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16: if (bits_per_sample & BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16) { @@ -882,8 +884,7 @@ static bool select_audio_bits_per_sample( // The result is stored in |p_result| and |p_codec_config|. // Returns true if a selection was made, otherwise false. // -static bool select_best_channel_mode(uint8_t channelMode, - tA2DP_LDAC_CIE* p_result, +static bool select_best_channel_mode(uint8_t channelMode, tA2DP_LDAC_CIE* p_result, btav_a2dp_codec_config_t* p_codec_config) { if (channelMode & A2DP_LDAC_CHANNEL_MODE_STEREO) { p_result->channelMode = A2DP_LDAC_CHANNEL_MODE_STEREO; @@ -909,9 +910,9 @@ static bool select_best_channel_mode(uint8_t channelMode, // The result is stored in |p_result| and |p_codec_config|. // Returns true if a selection was made, otherwise false. // -static bool select_audio_channel_mode( - const btav_a2dp_codec_config_t* p_codec_audio_config, uint8_t channelMode, - tA2DP_LDAC_CIE* p_result, btav_a2dp_codec_config_t* p_codec_config) { +static bool select_audio_channel_mode(const btav_a2dp_codec_config_t* p_codec_audio_config, + uint8_t channelMode, tA2DP_LDAC_CIE* p_result, + btav_a2dp_codec_config_t* p_codec_config) { switch (p_codec_audio_config->channel_mode) { case BTAV_A2DP_CODEC_CHANNEL_MODE_MONO: if (channelMode & A2DP_LDAC_CHANNEL_MODE_MONO) { @@ -939,8 +940,7 @@ static bool select_audio_channel_mode( return false; } -bool A2dpCodecConfigLdacBase::setCodecConfig(const uint8_t* p_peer_codec_info, - bool is_capability, +bool A2dpCodecConfigLdacBase::setCodecConfig(const uint8_t* p_peer_codec_info, bool is_capability, uint8_t* p_result_codec_config) { std::lock_guard lock(codec_mutex_); tA2DP_LDAC_CIE peer_info_cie; @@ -949,13 +949,12 @@ bool A2dpCodecConfigLdacBase::setCodecConfig(const uint8_t* p_peer_codec_info, uint8_t sampleRate; btav_a2dp_codec_bits_per_sample_t bits_per_sample; const tA2DP_LDAC_CIE* p_a2dp_ldac_caps = - (is_source_) ? &a2dp_ldac_source_caps : &a2dp_ldac_sink_caps; + (is_source_) ? &a2dp_ldac_source_caps : &a2dp_ldac_sink_caps; // Save the internal state btav_a2dp_codec_config_t saved_codec_config = codec_config_; btav_a2dp_codec_config_t saved_codec_capability = codec_capability_; - btav_a2dp_codec_config_t saved_codec_selectable_capability = - codec_selectable_capability_; + btav_a2dp_codec_config_t saved_codec_selectable_capability = codec_selectable_capability_; btav_a2dp_codec_config_t saved_codec_user_config = codec_user_config_; btav_a2dp_codec_config_t saved_codec_audio_config = codec_audio_config_; uint8_t saved_ota_codec_config[AVDT_CODEC_SIZE]; @@ -964,11 +963,9 @@ bool A2dpCodecConfigLdacBase::setCodecConfig(const uint8_t* p_peer_codec_info, memcpy(saved_ota_codec_config, ota_codec_config_, sizeof(ota_codec_config_)); memcpy(saved_ota_codec_peer_capability, ota_codec_peer_capability_, sizeof(ota_codec_peer_capability_)); - memcpy(saved_ota_codec_peer_config, ota_codec_peer_config_, - sizeof(ota_codec_peer_config_)); + memcpy(saved_ota_codec_peer_config, ota_codec_peer_config_, sizeof(ota_codec_peer_config_)); - tA2DP_STATUS status = - A2DP_ParseInfoLdac(&peer_info_cie, p_peer_codec_info, is_capability); + tA2DP_STATUS status = A2DP_ParseInfoLdac(&peer_info_cie, p_peer_codec_info, is_capability); if (status != A2DP_SUCCESS) { log::error("can't parse peer's capabilities: error = {}", status); goto fail; @@ -1041,69 +1038,68 @@ bool A2dpCodecConfigLdacBase::setCodecConfig(const uint8_t* p_peer_codec_info, do { // Compute the selectable capability if (sampleRate & A2DP_LDAC_SAMPLING_FREQ_44100) { - codec_selectable_capability_.sample_rate |= - BTAV_A2DP_CODEC_SAMPLE_RATE_44100; + codec_selectable_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_44100; } if (sampleRate & A2DP_LDAC_SAMPLING_FREQ_48000) { - codec_selectable_capability_.sample_rate |= - BTAV_A2DP_CODEC_SAMPLE_RATE_48000; + codec_selectable_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_48000; } if (sampleRate & A2DP_LDAC_SAMPLING_FREQ_88200) { - codec_selectable_capability_.sample_rate |= - BTAV_A2DP_CODEC_SAMPLE_RATE_88200; + codec_selectable_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_88200; } if (sampleRate & A2DP_LDAC_SAMPLING_FREQ_96000) { - codec_selectable_capability_.sample_rate |= - BTAV_A2DP_CODEC_SAMPLE_RATE_96000; + codec_selectable_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_96000; } if (sampleRate & A2DP_LDAC_SAMPLING_FREQ_176400) { - codec_selectable_capability_.sample_rate |= - BTAV_A2DP_CODEC_SAMPLE_RATE_176400; + codec_selectable_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_176400; } if (sampleRate & A2DP_LDAC_SAMPLING_FREQ_192000) { - codec_selectable_capability_.sample_rate |= - BTAV_A2DP_CODEC_SAMPLE_RATE_192000; + codec_selectable_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_192000; } - if (codec_config_.sample_rate != BTAV_A2DP_CODEC_SAMPLE_RATE_NONE) break; + if (codec_config_.sample_rate != BTAV_A2DP_CODEC_SAMPLE_RATE_NONE) { + break; + } // Compute the common capability - if (sampleRate & A2DP_LDAC_SAMPLING_FREQ_44100) + if (sampleRate & A2DP_LDAC_SAMPLING_FREQ_44100) { codec_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_44100; - if (sampleRate & A2DP_LDAC_SAMPLING_FREQ_48000) + } + if (sampleRate & A2DP_LDAC_SAMPLING_FREQ_48000) { codec_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_48000; - if (sampleRate & A2DP_LDAC_SAMPLING_FREQ_88200) + } + if (sampleRate & A2DP_LDAC_SAMPLING_FREQ_88200) { codec_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_88200; - if (sampleRate & A2DP_LDAC_SAMPLING_FREQ_96000) + } + if (sampleRate & A2DP_LDAC_SAMPLING_FREQ_96000) { codec_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_96000; - if (sampleRate & A2DP_LDAC_SAMPLING_FREQ_176400) + } + if (sampleRate & A2DP_LDAC_SAMPLING_FREQ_176400) { codec_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_176400; - if (sampleRate & A2DP_LDAC_SAMPLING_FREQ_192000) + } + if (sampleRate & A2DP_LDAC_SAMPLING_FREQ_192000) { codec_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_192000; + } // No user preference - try the codec audio config - if (select_audio_sample_rate(&codec_audio_config_, sampleRate, - &result_config_cie, &codec_config_)) { + if (select_audio_sample_rate(&codec_audio_config_, sampleRate, &result_config_cie, + &codec_config_)) { break; } // No user preference - try the default config - if (select_best_sample_rate( - a2dp_ldac_default_config.sampleRate & peer_info_cie.sampleRate, - &result_config_cie, &codec_config_)) { + if (select_best_sample_rate(a2dp_ldac_default_config.sampleRate & peer_info_cie.sampleRate, + &result_config_cie, &codec_config_)) { break; } // No user preference - use the best match - if (select_best_sample_rate(sampleRate, &result_config_cie, - &codec_config_)) { + if (select_best_sample_rate(sampleRate, &result_config_cie, &codec_config_)) { break; } } while (false); if (codec_config_.sample_rate == BTAV_A2DP_CODEC_SAMPLE_RATE_NONE) { - log::error( - "cannot match sample frequency: local caps = 0x{:x} peer info = 0x{:x}", - p_a2dp_ldac_caps->sampleRate, peer_info_cie.sampleRate); + log::error("cannot match sample frequency: local caps = 0x{:x} peer info = 0x{:x}", + p_a2dp_ldac_caps->sampleRate, peer_info_cie.sampleRate); goto fail; } @@ -1146,40 +1142,38 @@ bool A2dpCodecConfigLdacBase::setCodecConfig(const uint8_t* p_peer_codec_info, // Select the bits per sample if there is no user preference do { // Compute the selectable capability - codec_selectable_capability_.bits_per_sample = - p_a2dp_ldac_caps->bits_per_sample; + codec_selectable_capability_.bits_per_sample = p_a2dp_ldac_caps->bits_per_sample; - if (codec_config_.bits_per_sample != BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE) + if (codec_config_.bits_per_sample != BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE) { break; + } // Compute the common capability codec_capability_.bits_per_sample = bits_per_sample; // No user preference - the the codec audio config - if (select_audio_bits_per_sample(&codec_audio_config_, - p_a2dp_ldac_caps->bits_per_sample, + if (select_audio_bits_per_sample(&codec_audio_config_, p_a2dp_ldac_caps->bits_per_sample, &result_config_cie, &codec_config_)) { break; } // No user preference - try the default config - if (select_best_bits_per_sample(a2dp_ldac_default_config.bits_per_sample, - &result_config_cie, &codec_config_)) { + if (select_best_bits_per_sample(a2dp_ldac_default_config.bits_per_sample, &result_config_cie, + &codec_config_)) { break; } // No user preference - use the best match - if (select_best_bits_per_sample(p_a2dp_ldac_caps->bits_per_sample, - &result_config_cie, &codec_config_)) { + if (select_best_bits_per_sample(p_a2dp_ldac_caps->bits_per_sample, &result_config_cie, + &codec_config_)) { break; } } while (false); if (codec_config_.bits_per_sample == BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE) { log::error( - "cannot match bits per sample: default = 0x{:x} user preference = " - "0x{:x}", - a2dp_ldac_default_config.bits_per_sample, - codec_user_config_.bits_per_sample); + "cannot match bits per sample: default = 0x{:x} user preference = " + "0x{:x}", + a2dp_ldac_default_config.bits_per_sample, codec_user_config_.bits_per_sample); goto fail; } @@ -1220,86 +1214,81 @@ bool A2dpCodecConfigLdacBase::setCodecConfig(const uint8_t* p_peer_codec_info, do { // Compute the selectable capability if (channelMode & A2DP_LDAC_CHANNEL_MODE_MONO) { - codec_selectable_capability_.channel_mode |= - BTAV_A2DP_CODEC_CHANNEL_MODE_MONO; + codec_selectable_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_MONO; } if (channelMode & A2DP_LDAC_CHANNEL_MODE_STEREO) { - codec_selectable_capability_.channel_mode |= - BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; + codec_selectable_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; } if (channelMode & A2DP_LDAC_CHANNEL_MODE_DUAL) { - codec_selectable_capability_.channel_mode |= - BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; + codec_selectable_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; } - if (codec_config_.channel_mode != BTAV_A2DP_CODEC_CHANNEL_MODE_NONE) break; + if (codec_config_.channel_mode != BTAV_A2DP_CODEC_CHANNEL_MODE_NONE) { + break; + } // Compute the common capability - if (channelMode & A2DP_LDAC_CHANNEL_MODE_MONO) + if (channelMode & A2DP_LDAC_CHANNEL_MODE_MONO) { codec_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_MONO; - if (channelMode & - (A2DP_LDAC_CHANNEL_MODE_STEREO | A2DP_LDAC_CHANNEL_MODE_DUAL)) { + } + if (channelMode & (A2DP_LDAC_CHANNEL_MODE_STEREO | A2DP_LDAC_CHANNEL_MODE_DUAL)) { codec_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; } // No user preference - try the codec audio config - if (select_audio_channel_mode(&codec_audio_config_, channelMode, - &result_config_cie, &codec_config_)) { + if (select_audio_channel_mode(&codec_audio_config_, channelMode, &result_config_cie, + &codec_config_)) { break; } // No user preference - try the default config - if (select_best_channel_mode( - a2dp_ldac_default_config.channelMode & peer_info_cie.channelMode, - &result_config_cie, &codec_config_)) { + if (select_best_channel_mode(a2dp_ldac_default_config.channelMode & peer_info_cie.channelMode, + &result_config_cie, &codec_config_)) { break; } // No user preference - use the best match - if (select_best_channel_mode(channelMode, &result_config_cie, - &codec_config_)) { + if (select_best_channel_mode(channelMode, &result_config_cie, &codec_config_)) { break; } } while (false); if (codec_config_.channel_mode == BTAV_A2DP_CODEC_CHANNEL_MODE_NONE) { - log::error( - "cannot match channel mode: local caps = 0x{:x} peer info = 0x{:x}", - p_a2dp_ldac_caps->channelMode, peer_info_cie.channelMode); + log::error("cannot match channel mode: local caps = 0x{:x} peer info = 0x{:x}", + p_a2dp_ldac_caps->channelMode, peer_info_cie.channelMode); goto fail; } - if (A2DP_BuildInfoLdac(AVDT_MEDIA_TYPE_AUDIO, &result_config_cie, - p_result_codec_config) != A2DP_SUCCESS) { + if (A2DP_BuildInfoLdac(AVDT_MEDIA_TYPE_AUDIO, &result_config_cie, p_result_codec_config) != + A2DP_SUCCESS) { goto fail; } // // Copy the codec-specific fields if they are not zero // - if (codec_user_config_.codec_specific_1 != 0) + if (codec_user_config_.codec_specific_1 != 0) { codec_config_.codec_specific_1 = codec_user_config_.codec_specific_1; - if (codec_user_config_.codec_specific_2 != 0) + } + if (codec_user_config_.codec_specific_2 != 0) { codec_config_.codec_specific_2 = codec_user_config_.codec_specific_2; - if (codec_user_config_.codec_specific_3 != 0) + } + if (codec_user_config_.codec_specific_3 != 0) { codec_config_.codec_specific_3 = codec_user_config_.codec_specific_3; - if (codec_user_config_.codec_specific_4 != 0) + } + if (codec_user_config_.codec_specific_4 != 0) { codec_config_.codec_specific_4 = codec_user_config_.codec_specific_4; + } // Create a local copy of the peer codec capability, and the // result codec config. if (is_capability) { - status = A2DP_BuildInfoLdac(AVDT_MEDIA_TYPE_AUDIO, &peer_info_cie, - ota_codec_peer_capability_); + status = A2DP_BuildInfoLdac(AVDT_MEDIA_TYPE_AUDIO, &peer_info_cie, ota_codec_peer_capability_); } else { - status = A2DP_BuildInfoLdac(AVDT_MEDIA_TYPE_AUDIO, &peer_info_cie, - ota_codec_peer_config_); - } - log::assert_that(status == A2DP_SUCCESS, - "assert failed: status == A2DP_SUCCESS"); - status = A2DP_BuildInfoLdac(AVDT_MEDIA_TYPE_AUDIO, &result_config_cie, - ota_codec_config_); - log::assert_that(status == A2DP_SUCCESS, - "assert failed: status == A2DP_SUCCESS"); + status = A2DP_BuildInfoLdac(AVDT_MEDIA_TYPE_AUDIO, &peer_info_cie, ota_codec_peer_config_); + } + log::assert_that(status == A2DP_SUCCESS, "assert failed: status == A2DP_SUCCESS"); + status = A2DP_BuildInfoLdac(AVDT_MEDIA_TYPE_AUDIO, &result_config_cie, ota_codec_config_); + log::assert_that(status == A2DP_SUCCESS, "assert failed: status == A2DP_SUCCESS"); return true; fail: @@ -1312,29 +1301,25 @@ fail: memcpy(ota_codec_config_, saved_ota_codec_config, sizeof(ota_codec_config_)); memcpy(ota_codec_peer_capability_, saved_ota_codec_peer_capability, sizeof(ota_codec_peer_capability_)); - memcpy(ota_codec_peer_config_, saved_ota_codec_peer_config, - sizeof(ota_codec_peer_config_)); + memcpy(ota_codec_peer_config_, saved_ota_codec_peer_config, sizeof(ota_codec_peer_config_)); return false; } -bool A2dpCodecConfigLdacBase::setPeerCodecCapabilities( - const uint8_t* p_peer_codec_capabilities) { +bool A2dpCodecConfigLdacBase::setPeerCodecCapabilities(const uint8_t* p_peer_codec_capabilities) { std::lock_guard lock(codec_mutex_); tA2DP_LDAC_CIE peer_info_cie; uint8_t channelMode; uint8_t sampleRate; const tA2DP_LDAC_CIE* p_a2dp_ldac_caps = - (is_source_) ? &a2dp_ldac_source_caps : &a2dp_ldac_sink_caps; + (is_source_) ? &a2dp_ldac_source_caps : &a2dp_ldac_sink_caps; // Save the internal state - btav_a2dp_codec_config_t saved_codec_selectable_capability = - codec_selectable_capability_; + btav_a2dp_codec_config_t saved_codec_selectable_capability = codec_selectable_capability_; uint8_t saved_ota_codec_peer_capability[AVDT_CODEC_SIZE]; memcpy(saved_ota_codec_peer_capability, ota_codec_peer_capability_, sizeof(ota_codec_peer_capability_)); - tA2DP_STATUS status = - A2DP_ParseInfoLdac(&peer_info_cie, p_peer_codec_capabilities, true); + tA2DP_STATUS status = A2DP_ParseInfoLdac(&peer_info_cie, p_peer_codec_capabilities, true); if (status != A2DP_SUCCESS) { log::error("can't parse peer's capabilities: error = {}", status); goto fail; @@ -1343,53 +1328,41 @@ bool A2dpCodecConfigLdacBase::setPeerCodecCapabilities( // Compute the selectable capability - sample rate sampleRate = p_a2dp_ldac_caps->sampleRate & peer_info_cie.sampleRate; if (sampleRate & A2DP_LDAC_SAMPLING_FREQ_44100) { - codec_selectable_capability_.sample_rate |= - BTAV_A2DP_CODEC_SAMPLE_RATE_44100; + codec_selectable_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_44100; } if (sampleRate & A2DP_LDAC_SAMPLING_FREQ_48000) { - codec_selectable_capability_.sample_rate |= - BTAV_A2DP_CODEC_SAMPLE_RATE_48000; + codec_selectable_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_48000; } if (sampleRate & A2DP_LDAC_SAMPLING_FREQ_88200) { - codec_selectable_capability_.sample_rate |= - BTAV_A2DP_CODEC_SAMPLE_RATE_88200; + codec_selectable_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_88200; } if (sampleRate & A2DP_LDAC_SAMPLING_FREQ_96000) { - codec_selectable_capability_.sample_rate |= - BTAV_A2DP_CODEC_SAMPLE_RATE_96000; + codec_selectable_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_96000; } if (sampleRate & A2DP_LDAC_SAMPLING_FREQ_176400) { - codec_selectable_capability_.sample_rate |= - BTAV_A2DP_CODEC_SAMPLE_RATE_176400; + codec_selectable_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_176400; } if (sampleRate & A2DP_LDAC_SAMPLING_FREQ_192000) { - codec_selectable_capability_.sample_rate |= - BTAV_A2DP_CODEC_SAMPLE_RATE_192000; + codec_selectable_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_192000; } // Compute the selectable capability - bits per sample - codec_selectable_capability_.bits_per_sample = - p_a2dp_ldac_caps->bits_per_sample; + codec_selectable_capability_.bits_per_sample = p_a2dp_ldac_caps->bits_per_sample; // Compute the selectable capability - channel mode channelMode = p_a2dp_ldac_caps->channelMode & peer_info_cie.channelMode; if (channelMode & A2DP_LDAC_CHANNEL_MODE_MONO) { - codec_selectable_capability_.channel_mode |= - BTAV_A2DP_CODEC_CHANNEL_MODE_MONO; + codec_selectable_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_MONO; } if (channelMode & A2DP_LDAC_CHANNEL_MODE_STEREO) { - codec_selectable_capability_.channel_mode |= - BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; + codec_selectable_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; } if (channelMode & A2DP_LDAC_CHANNEL_MODE_DUAL) { - codec_selectable_capability_.channel_mode |= - BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; + codec_selectable_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; } - status = A2DP_BuildInfoLdac(AVDT_MEDIA_TYPE_AUDIO, &peer_info_cie, - ota_codec_peer_capability_); - log::assert_that(status == A2DP_SUCCESS, - "assert failed: status == A2DP_SUCCESS"); + status = A2DP_BuildInfoLdac(AVDT_MEDIA_TYPE_AUDIO, &peer_info_cie, ota_codec_peer_capability_); + log::assert_that(status == A2DP_SUCCESS, "assert failed: status == A2DP_SUCCESS"); return true; fail: @@ -1400,16 +1373,16 @@ fail: return false; } -A2dpCodecConfigLdacSink::A2dpCodecConfigLdacSink( - btav_a2dp_codec_priority_t codec_priority) - : A2dpCodecConfigLdacBase(BTAV_A2DP_CODEC_INDEX_SINK_LDAC, - A2DP_VendorCodecIndexStrLdacSink(), +A2dpCodecConfigLdacSink::A2dpCodecConfigLdacSink(btav_a2dp_codec_priority_t codec_priority) + : A2dpCodecConfigLdacBase(BTAV_A2DP_CODEC_INDEX_SINK_LDAC, A2DP_VendorCodecIndexStrLdacSink(), codec_priority, false) {} A2dpCodecConfigLdacSink::~A2dpCodecConfigLdacSink() {} bool A2dpCodecConfigLdacSink::init() { - if (!isValid()) return false; + if (!isValid()) { + return false; + } // Load the decoder if (!A2DP_VendorLoadDecoderLdac()) { diff --git a/system/stack/a2dp/a2dp_vendor_ldac_decoder.cc b/system/stack/a2dp/a2dp_vendor_ldac_decoder.cc index 395fb21d701..4babdc79dc0 100644 --- a/system/stack/a2dp/a2dp_vendor_ldac_decoder.cc +++ b/system/stack/a2dp/a2dp_vendor_ldac_decoder.cc @@ -47,15 +47,13 @@ static const char* LDAC_BCO_LIB_NAME = "libldacBT_bco.so"; static void* ldac_bco_lib_handle = NULL; static const char* LDAC_BCO_INIT_NAME = "ldac_BCO_init"; -typedef HANDLE_LDAC_BCO (*tLDAC_BCO_INIT)( - decoded_data_callback_t decode_callback); +typedef HANDLE_LDAC_BCO (*tLDAC_BCO_INIT)(decoded_data_callback_t decode_callback); static const char* LDAC_BCO_CLEANUP_NAME = "ldac_BCO_cleanup"; typedef int32_t (*tLDAC_BCO_CLEANUP)(HANDLE_LDAC_BCO hLdacBco); static const char* LDAC_BCO_DECODE_PACKET_NAME = "ldac_BCO_decode_packet"; -typedef int32_t (*tLDAC_BCO_DECODE_PACKET)(HANDLE_LDAC_BCO hLdacBco, void* data, - int32_t length); +typedef int32_t (*tLDAC_BCO_DECODE_PACKET)(HANDLE_LDAC_BCO hLdacBco, void* data, int32_t length); static const char* LDAC_BCO_START_NAME = "ldac_BCO_start"; typedef int32_t (*tLDAC_BCO_START)(HANDLE_LDAC_BCO hLdacBco); @@ -64,10 +62,8 @@ static const char* LDAC_BCO_SUSPEND_NAME = "ldac_BCO_suspend"; typedef int32_t (*tLDAC_BCO_SUSPEND)(HANDLE_LDAC_BCO hLdacBco); static const char* LDAC_BCO_CONFIGURE_NAME = "ldac_BCO_configure"; -typedef int32_t (*tLDAC_BCO_CONFIGURE)(HANDLE_LDAC_BCO hLdacBco, - int32_t sample_rate, - int32_t bits_per_sample, - int32_t channel_mode); +typedef int32_t (*tLDAC_BCO_CONFIGURE)(HANDLE_LDAC_BCO hLdacBco, int32_t sample_rate, + int32_t bits_per_sample, int32_t channel_mode); static tLDAC_BCO_INIT ldac_BCO_init_func; static tLDAC_BCO_CLEANUP ldac_BCO_cleanup_func; @@ -106,8 +102,7 @@ static tA2DP_LDAC_DECODER_CB a2dp_ldac_decoder_cb; static void* load_func(const char* func_name) { void* func_ptr = dlsym(ldac_bco_lib_handle, func_name); if (func_ptr == NULL) { - log::error("cannot find function '{}' in the decoder library: {}", - func_name, dlerror()); + log::error("cannot find function '{}' in the decoder library: {}", func_name, dlerror()); A2DP_VendorUnloadDecoderLdac(); return NULL; } @@ -115,7 +110,9 @@ static void* load_func(const char* func_name) { } bool A2DP_VendorLoadDecoderLdac(void) { - if (ldac_bco_lib_handle != NULL) return true; // Already loaded + if (ldac_bco_lib_handle != NULL) { + return true; // Already loaded + } // Initialize the control block memset(&a2dp_ldac_decoder_cb, 0, sizeof(a2dp_ldac_decoder_cb)); @@ -125,39 +122,49 @@ bool A2DP_VendorLoadDecoderLdac(void) { // Open the decoder library ldac_bco_lib_handle = dlopen(LDAC_BCO_LIB_NAME, RTLD_NOW); if (ldac_bco_lib_handle == NULL) { - log::info("cannot open LDAC decoder library {}: {}", LDAC_BCO_LIB_NAME, - dlerror()); + log::info("cannot open LDAC decoder library {}: {}", LDAC_BCO_LIB_NAME, dlerror()); return false; } // Load all functions ldac_BCO_init_func = (tLDAC_BCO_INIT)load_func(LDAC_BCO_INIT_NAME); - if (ldac_BCO_init_func == NULL) return false; + if (ldac_BCO_init_func == NULL) { + return false; + } ldac_BCO_cleanup_func = (tLDAC_BCO_CLEANUP)load_func(LDAC_BCO_CLEANUP_NAME); - if (ldac_BCO_cleanup_func == NULL) return false; + if (ldac_BCO_cleanup_func == NULL) { + return false; + } - ldac_BCO_decode_packet_func = - (tLDAC_BCO_DECODE_PACKET)load_func(LDAC_BCO_DECODE_PACKET_NAME); - if (ldac_BCO_decode_packet_func == NULL) return false; + ldac_BCO_decode_packet_func = (tLDAC_BCO_DECODE_PACKET)load_func(LDAC_BCO_DECODE_PACKET_NAME); + if (ldac_BCO_decode_packet_func == NULL) { + return false; + } ldac_BCO_start_func = (tLDAC_BCO_START)load_func(LDAC_BCO_START_NAME); - if (ldac_BCO_start_func == NULL) return false; + if (ldac_BCO_start_func == NULL) { + return false; + } ldac_BCO_suspend_func = (tLDAC_BCO_SUSPEND)load_func(LDAC_BCO_SUSPEND_NAME); - if (ldac_BCO_suspend_func == NULL) return false; + if (ldac_BCO_suspend_func == NULL) { + return false; + } - ldac_BCO_configure_func = - (tLDAC_BCO_CONFIGURE)load_func(LDAC_BCO_CONFIGURE_NAME); - if (ldac_BCO_configure_func == NULL) return false; + ldac_BCO_configure_func = (tLDAC_BCO_CONFIGURE)load_func(LDAC_BCO_CONFIGURE_NAME); + if (ldac_BCO_configure_func == NULL) { + return false; + } return true; } void A2DP_VendorUnloadDecoderLdac(void) { // Cleanup any LDAC-related state - if (a2dp_ldac_decoder_cb.has_ldac_handle && ldac_BCO_cleanup_func != NULL) + if (a2dp_ldac_decoder_cb.has_ldac_handle && ldac_BCO_cleanup_func != NULL) { ldac_BCO_cleanup_func(a2dp_ldac_decoder_cb.ldac_handle_bco); + } pthread_mutex_destroy(&(a2dp_ldac_decoder_cb.mutex)); memset(&a2dp_ldac_decoder_cb, 0, sizeof(a2dp_ldac_decoder_cb)); @@ -177,12 +184,12 @@ void A2DP_VendorUnloadDecoderLdac(void) { bool a2dp_vendor_ldac_decoder_init(decoded_data_callback_t decode_callback) { pthread_mutex_lock(&(a2dp_ldac_decoder_cb.mutex)); - if (a2dp_ldac_decoder_cb.has_ldac_handle) + if (a2dp_ldac_decoder_cb.has_ldac_handle) { ldac_BCO_cleanup_func(a2dp_ldac_decoder_cb.ldac_handle_bco); + } a2dp_ldac_decoder_cb.ldac_handle_bco = ldac_BCO_init_func(decode_callback); - a2dp_ldac_decoder_cb.has_ldac_handle = - (a2dp_ldac_decoder_cb.ldac_handle_bco != NULL); + a2dp_ldac_decoder_cb.has_ldac_handle = (a2dp_ldac_decoder_cb.ldac_handle_bco != NULL); pthread_mutex_unlock(&(a2dp_ldac_decoder_cb.mutex)); return true; @@ -190,8 +197,9 @@ bool a2dp_vendor_ldac_decoder_init(decoded_data_callback_t decode_callback) { void a2dp_vendor_ldac_decoder_cleanup(void) { pthread_mutex_lock(&(a2dp_ldac_decoder_cb.mutex)); - if (a2dp_ldac_decoder_cb.has_ldac_handle) + if (a2dp_ldac_decoder_cb.has_ldac_handle) { ldac_BCO_cleanup_func(a2dp_ldac_decoder_cb.ldac_handle_bco); + } a2dp_ldac_decoder_cb.ldac_handle_bco = NULL; pthread_mutex_unlock(&(a2dp_ldac_decoder_cb.mutex)); } @@ -202,8 +210,7 @@ bool a2dp_vendor_ldac_decoder_decode_packet(BT_HDR* p_buf) { return false; } pthread_mutex_lock(&(a2dp_ldac_decoder_cb.mutex)); - unsigned char* pBuffer = - reinterpret_cast(p_buf->data + p_buf->offset); + unsigned char* pBuffer = reinterpret_cast(p_buf->data + p_buf->offset); // unsigned int bufferSize = p_buf->len; unsigned int bytesValid = p_buf->len; if (bytesValid == 0) { @@ -219,9 +226,9 @@ bool a2dp_vendor_ldac_decoder_decode_packet(BT_HDR* p_buf) { bytesValid -= 1; log::info("INPUT size : {}, frame : {}", bs_bytes, frame_number); - if (a2dp_ldac_decoder_cb.has_ldac_handle) - ldac_BCO_decode_packet_func(a2dp_ldac_decoder_cb.ldac_handle_bco, pBuffer, - bs_bytes); + if (a2dp_ldac_decoder_cb.has_ldac_handle) { + ldac_BCO_decode_packet_func(a2dp_ldac_decoder_cb.ldac_handle_bco, pBuffer, bs_bytes); + } pthread_mutex_unlock(&(a2dp_ldac_decoder_cb.mutex)); return true; @@ -230,16 +237,18 @@ bool a2dp_vendor_ldac_decoder_decode_packet(BT_HDR* p_buf) { void a2dp_vendor_ldac_decoder_start(void) { pthread_mutex_lock(&(a2dp_ldac_decoder_cb.mutex)); log::info(""); - if (a2dp_ldac_decoder_cb.has_ldac_handle) + if (a2dp_ldac_decoder_cb.has_ldac_handle) { ldac_BCO_start_func(a2dp_ldac_decoder_cb.ldac_handle_bco); + } pthread_mutex_unlock(&(a2dp_ldac_decoder_cb.mutex)); } void a2dp_vendor_ldac_decoder_suspend(void) { pthread_mutex_lock(&(a2dp_ldac_decoder_cb.mutex)); log::info(""); - if (a2dp_ldac_decoder_cb.has_ldac_handle) + if (a2dp_ldac_decoder_cb.has_ldac_handle) { ldac_BCO_suspend_func(a2dp_ldac_decoder_cb.ldac_handle_bco); + } pthread_mutex_unlock(&(a2dp_ldac_decoder_cb.mutex)); } @@ -258,11 +267,12 @@ void a2dp_vendor_ldac_decoder_configure(const uint8_t* p_codec_info) { bits_per_sample = A2DP_VendorGetTrackBitsPerSampleLdac(p_codec_info); channel_mode = A2DP_VendorGetChannelModeCodeLdac(p_codec_info); - log::info(", sample_rate={}, bits_per_sample={}, channel_mode={}", - sample_rate, bits_per_sample, channel_mode); + log::info(", sample_rate={}, bits_per_sample={}, channel_mode={}", sample_rate, bits_per_sample, + channel_mode); - if (a2dp_ldac_decoder_cb.has_ldac_handle) - ldac_BCO_configure_func(a2dp_ldac_decoder_cb.ldac_handle_bco, sample_rate, - bits_per_sample, channel_mode); + if (a2dp_ldac_decoder_cb.has_ldac_handle) { + ldac_BCO_configure_func(a2dp_ldac_decoder_cb.ldac_handle_bco, sample_rate, bits_per_sample, + channel_mode); + } pthread_mutex_unlock(&(a2dp_ldac_decoder_cb.mutex)); } diff --git a/system/stack/a2dp/a2dp_vendor_ldac_encoder.cc b/system/stack/a2dp/a2dp_vendor_ldac_encoder.cc index 0c93ae4c162..342a2f9f408 100644 --- a/system/stack/a2dp/a2dp_vendor_ldac_encoder.cc +++ b/system/stack/a2dp/a2dp_vendor_ldac_encoder.cc @@ -91,7 +91,7 @@ typedef struct { bool use_SCMS_T; tA2DP_ENCODER_INIT_PEER_PARAMS peer_params; - uint32_t timestamp; // Timestamp for the A2DP frames + uint32_t timestamp; // Timestamp for the A2DP frames HANDLE_LDAC_BT ldac_handle; bool has_ldac_handle; // True if ldac_handle is valid @@ -113,16 +113,13 @@ static bool ldac_abr_loaded = true; // the library is statically linked static tA2DP_LDAC_ENCODER_CB a2dp_ldac_encoder_cb; static void a2dp_vendor_ldac_encoder_update(A2dpCodecConfig* a2dp_codec_config, - bool* p_restart_input, - bool* p_restart_output, + bool* p_restart_input, bool* p_restart_output, bool* p_config_updated); -static void a2dp_ldac_get_num_frame_iteration(uint8_t* num_of_iterations, - uint8_t* num_of_frames, +static void a2dp_ldac_get_num_frame_iteration(uint8_t* num_of_iterations, uint8_t* num_of_frames, uint64_t timestamp_us); static void a2dp_ldac_encode_frames(uint8_t nb_frame); static bool a2dp_ldac_read_feeding(uint8_t* read_buffer, uint32_t* bytes_read); -static uint16_t adjust_effective_mtu( - const tA2DP_ENCODER_INIT_PEER_PARAMS& peer_params); +static uint16_t adjust_effective_mtu(const tA2DP_ENCODER_INIT_PEER_PARAMS& peer_params); static std::string quality_mode_index_to_name(int quality_mode_index); bool A2DP_VendorLoadEncoderLdac(void) { @@ -135,15 +132,13 @@ void A2DP_VendorUnloadEncoderLdac(void) { a2dp_vendor_ldac_encoder_cleanup(); } -void a2dp_vendor_ldac_encoder_init( - const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params, - A2dpCodecConfig* a2dp_codec_config, - a2dp_source_read_callback_t read_callback, - a2dp_source_enqueue_callback_t enqueue_callback) { +void a2dp_vendor_ldac_encoder_init(const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params, + A2dpCodecConfig* a2dp_codec_config, + a2dp_source_read_callback_t read_callback, + a2dp_source_enqueue_callback_t enqueue_callback) { a2dp_vendor_ldac_encoder_cleanup(); - a2dp_ldac_encoder_cb.stats.session_start_us = - bluetooth::common::time_get_os_boottime_us(); + a2dp_ldac_encoder_cb.stats.session_start_us = bluetooth::common::time_get_os_boottime_us(); a2dp_ldac_encoder_cb.read_callback = read_callback; a2dp_ldac_encoder_cb.enqueue_callback = enqueue_callback; @@ -161,18 +156,16 @@ void a2dp_vendor_ldac_encoder_init( bool restart_input = false; bool restart_output = false; bool config_updated = false; - a2dp_vendor_ldac_encoder_update(a2dp_codec_config, &restart_input, - &restart_output, &config_updated); + a2dp_vendor_ldac_encoder_update(a2dp_codec_config, &restart_input, &restart_output, + &config_updated); } // Update the A2DP LDAC encoder. // |a2dp_codec_config| is the A2DP codec to use for the update. static void a2dp_vendor_ldac_encoder_update(A2dpCodecConfig* a2dp_codec_config, - bool* p_restart_input, - bool* p_restart_output, + bool* p_restart_input, bool* p_restart_output, bool* p_config_updated) { - tA2DP_LDAC_ENCODER_PARAMS* p_encoder_params = - &a2dp_ldac_encoder_cb.ldac_encoder_params; + tA2DP_LDAC_ENCODER_PARAMS* p_encoder_params = &a2dp_ldac_encoder_cb.ldac_encoder_params; uint8_t codec_info[AVDT_CODEC_SIZE]; *p_restart_input = false; @@ -187,9 +180,8 @@ static void a2dp_vendor_ldac_encoder_update(A2dpCodecConfig* a2dp_codec_config, } a2dp_ldac_encoder_cb.has_ldac_handle = true; } - log::assert_that( - a2dp_ldac_encoder_cb.ldac_handle != nullptr, - "assert failed: a2dp_ldac_encoder_cb.ldac_handle != nullptr"); + log::assert_that(a2dp_ldac_encoder_cb.ldac_handle != nullptr, + "assert failed: a2dp_ldac_encoder_cb.ldac_handle != nullptr"); if (!a2dp_codec_config->copyOutOtaCodecConfig(codec_info)) { log::error("Cannot update the codec encoder for {}: invalid codec config", @@ -201,22 +193,16 @@ static void a2dp_vendor_ldac_encoder_update(A2dpCodecConfig* a2dp_codec_config, // The feeding parameters tA2DP_FEEDING_PARAMS* p_feeding_params = &a2dp_ldac_encoder_cb.feeding_params; - p_feeding_params->sample_rate = - A2DP_VendorGetTrackSampleRateLdac(p_codec_info); - p_feeding_params->bits_per_sample = - a2dp_codec_config->getAudioBitsPerSample(); - p_feeding_params->channel_count = - A2DP_VendorGetTrackChannelCountLdac(p_codec_info); - log::info("sample_rate={} bits_per_sample={} channel_count={}", - p_feeding_params->sample_rate, p_feeding_params->bits_per_sample, - p_feeding_params->channel_count); + p_feeding_params->sample_rate = A2DP_VendorGetTrackSampleRateLdac(p_codec_info); + p_feeding_params->bits_per_sample = a2dp_codec_config->getAudioBitsPerSample(); + p_feeding_params->channel_count = A2DP_VendorGetTrackChannelCountLdac(p_codec_info); + log::info("sample_rate={} bits_per_sample={} channel_count={}", p_feeding_params->sample_rate, + p_feeding_params->bits_per_sample, p_feeding_params->channel_count); a2dp_vendor_ldac_feeding_reset(); // The codec parameters - p_encoder_params->sample_rate = - a2dp_ldac_encoder_cb.feeding_params.sample_rate; - p_encoder_params->channel_mode = - A2DP_VendorGetChannelModeCodeLdac(p_codec_info); + p_encoder_params->sample_rate = a2dp_ldac_encoder_cb.feeding_params.sample_rate; + p_encoder_params->channel_mode = A2DP_VendorGetChannelModeCodeLdac(p_codec_info); // Set the quality mode index int old_quality_mode_index = p_encoder_params->quality_mode_index; @@ -234,14 +220,11 @@ static void a2dp_vendor_ldac_encoder_update(A2dpCodecConfig* a2dp_codec_config, if (p_encoder_params->quality_mode_index == A2DP_LDAC_QUALITY_ABR) { if (!ldac_abr_loaded) { p_encoder_params->quality_mode_index = A2DP_LDAC_QUALITY_MID; - log::warn( - "LDAC ABR library is not loaded, resetting quality mode to {}", - quality_mode_index_to_name(p_encoder_params->quality_mode_index)); + log::warn("LDAC ABR library is not loaded, resetting quality mode to {}", + quality_mode_index_to_name(p_encoder_params->quality_mode_index)); } else { - log::info( - "changing mode from {} to {}", - quality_mode_index_to_name(old_quality_mode_index), - quality_mode_index_to_name(p_encoder_params->quality_mode_index)); + log::info("changing mode from {} to {}", quality_mode_index_to_name(old_quality_mode_index), + quality_mode_index_to_name(p_encoder_params->quality_mode_index)); if (a2dp_ldac_encoder_cb.ldac_abr_handle != NULL) { log::info("already in LDAC ABR mode, do nothing."); } else { @@ -251,20 +234,17 @@ static void a2dp_vendor_ldac_encoder_update(A2dpCodecConfig* a2dp_codec_config, a2dp_ldac_encoder_cb.has_ldac_abr_handle = true; a2dp_ldac_encoder_cb.last_ldac_abr_eqmid = -1; a2dp_ldac_encoder_cb.ldac_abr_adjustments = 0; - ldac_ABR_Init(a2dp_ldac_encoder_cb.ldac_abr_handle, - A2DP_LDAC_ENCODER_INTERVAL_MS); + ldac_ABR_Init(a2dp_ldac_encoder_cb.ldac_abr_handle, A2DP_LDAC_ENCODER_INTERVAL_MS); } else { p_encoder_params->quality_mode_index = A2DP_LDAC_QUALITY_MID; - log::info( - "get LDAC ABR handle failed, resetting quality mode to {}.", - quality_mode_index_to_name(p_encoder_params->quality_mode_index)); + log::info("get LDAC ABR handle failed, resetting quality mode to {}.", + quality_mode_index_to_name(p_encoder_params->quality_mode_index)); } } } } else { ldac_eqmid = p_encoder_params->quality_mode_index; - log::info("in {} mode, free LDAC ABR handle.", - quality_mode_index_to_name(ldac_eqmid)); + log::info("in {} mode, free LDAC ABR handle.", quality_mode_index_to_name(ldac_eqmid)); if (a2dp_ldac_encoder_cb.has_ldac_abr_handle) { ldac_ABR_free_handle(a2dp_ldac_encoder_cb.ldac_abr_handle); a2dp_ldac_encoder_cb.ldac_abr_handle = NULL; @@ -274,46 +254,44 @@ static void a2dp_vendor_ldac_encoder_update(A2dpCodecConfig* a2dp_codec_config, } } - if (p_encoder_params->quality_mode_index != old_quality_mode_index) + if (p_encoder_params->quality_mode_index != old_quality_mode_index) { *p_config_updated = true; + } - p_encoder_params->pcm_wlength = - a2dp_ldac_encoder_cb.feeding_params.bits_per_sample >> 3; + p_encoder_params->pcm_wlength = a2dp_ldac_encoder_cb.feeding_params.bits_per_sample >> 3; // Set the Audio format from pcm_wlength p_encoder_params->pcm_fmt = LDACBT_SMPL_FMT_S16; - if (p_encoder_params->pcm_wlength == 2) + if (p_encoder_params->pcm_wlength == 2) { p_encoder_params->pcm_fmt = LDACBT_SMPL_FMT_S16; - else if (p_encoder_params->pcm_wlength == 3) + } else if (p_encoder_params->pcm_wlength == 3) { p_encoder_params->pcm_fmt = LDACBT_SMPL_FMT_S24; - else if (p_encoder_params->pcm_wlength == 4) + } else if (p_encoder_params->pcm_wlength == 4) { p_encoder_params->pcm_fmt = LDACBT_SMPL_FMT_S32; + } - const tA2DP_ENCODER_INIT_PEER_PARAMS& peer_params = - a2dp_ldac_encoder_cb.peer_params; + const tA2DP_ENCODER_INIT_PEER_PARAMS& peer_params = a2dp_ldac_encoder_cb.peer_params; a2dp_ldac_encoder_cb.TxAaMtuSize = adjust_effective_mtu(peer_params); - log::info("MTU={}, peer_mtu={}", a2dp_ldac_encoder_cb.TxAaMtuSize, - peer_params.peer_mtu); + log::info("MTU={}, peer_mtu={}", a2dp_ldac_encoder_cb.TxAaMtuSize, peer_params.peer_mtu); log::info( - "sample_rate: {} channel_mode: {} quality_mode_index: {} pcm_wlength: {} " - "pcm_fmt: {}", - p_encoder_params->sample_rate, p_encoder_params->channel_mode, - p_encoder_params->quality_mode_index, p_encoder_params->pcm_wlength, - p_encoder_params->pcm_fmt); + "sample_rate: {} channel_mode: {} quality_mode_index: {} pcm_wlength: {} " + "pcm_fmt: {}", + p_encoder_params->sample_rate, p_encoder_params->channel_mode, + p_encoder_params->quality_mode_index, p_encoder_params->pcm_wlength, + p_encoder_params->pcm_fmt); // Initialize the encoder. // NOTE: MTU in the initialization must include the AVDT media header size. - int result = ldacBT_init_handle_encode( - a2dp_ldac_encoder_cb.ldac_handle, - a2dp_ldac_encoder_cb.TxAaMtuSize + AVDT_MEDIA_HDR_SIZE, ldac_eqmid, - p_encoder_params->channel_mode, p_encoder_params->pcm_fmt, - p_encoder_params->sample_rate); + int result = ldacBT_init_handle_encode(a2dp_ldac_encoder_cb.ldac_handle, + a2dp_ldac_encoder_cb.TxAaMtuSize + AVDT_MEDIA_HDR_SIZE, + ldac_eqmid, p_encoder_params->channel_mode, + p_encoder_params->pcm_fmt, p_encoder_params->sample_rate); if (result != 0) { int err_code = ldacBT_get_error_code(a2dp_ldac_encoder_cb.ldac_handle); log::error( - "error initializing the LDAC encoder: {} api_error = {} handle_error = " - "{} block_error = {} error_code = 0x{:x}", - result, LDACBT_API_ERR(err_code), LDACBT_HANDLE_ERR(err_code), - LDACBT_BLOCK_ERR(err_code), err_code); + "error initializing the LDAC encoder: {} api_error = {} handle_error = " + "{} block_error = {} error_code = 0x{:x}", + result, LDACBT_API_ERR(err_code), LDACBT_HANDLE_ERR(err_code), + LDACBT_BLOCK_ERR(err_code), err_code); } } @@ -333,47 +311,42 @@ void a2dp_vendor_ldac_feeding_reset(void) { sizeof(a2dp_ldac_encoder_cb.ldac_feeding_state)); a2dp_ldac_encoder_cb.ldac_feeding_state.bytes_per_tick = - (a2dp_ldac_encoder_cb.feeding_params.sample_rate * - a2dp_ldac_encoder_cb.feeding_params.bits_per_sample / 8 * - a2dp_ldac_encoder_cb.feeding_params.channel_count * - A2DP_LDAC_ENCODER_INTERVAL_MS) / - 1000; - - log::info("PCM bytes per tick {}", - a2dp_ldac_encoder_cb.ldac_feeding_state.bytes_per_tick); + (a2dp_ldac_encoder_cb.feeding_params.sample_rate * + a2dp_ldac_encoder_cb.feeding_params.bits_per_sample / 8 * + a2dp_ldac_encoder_cb.feeding_params.channel_count * A2DP_LDAC_ENCODER_INTERVAL_MS) / + 1000; + + log::info("PCM bytes per tick {}", a2dp_ldac_encoder_cb.ldac_feeding_state.bytes_per_tick); } void a2dp_vendor_ldac_feeding_flush(void) { a2dp_ldac_encoder_cb.ldac_feeding_state.counter = 0.0f; } -uint64_t a2dp_vendor_ldac_get_encoder_interval_ms(void) { - return A2DP_LDAC_ENCODER_INTERVAL_MS; -} +uint64_t a2dp_vendor_ldac_get_encoder_interval_ms(void) { return A2DP_LDAC_ENCODER_INTERVAL_MS; } -int a2dp_vendor_ldac_get_effective_frame_size() { - return a2dp_ldac_encoder_cb.TxAaMtuSize; -} +int a2dp_vendor_ldac_get_effective_frame_size() { return a2dp_ldac_encoder_cb.TxAaMtuSize; } void a2dp_vendor_ldac_send_frames(uint64_t timestamp_us) { uint8_t nb_frame = 0; uint8_t nb_iterations = 0; a2dp_ldac_get_num_frame_iteration(&nb_iterations, &nb_frame, timestamp_us); - log::verbose("Sending {} frames per iteration, {} iterations", nb_frame, - nb_iterations); - if (nb_frame == 0) return; + log::verbose("Sending {} frames per iteration, {} iterations", nb_frame, nb_iterations); + if (nb_frame == 0) { + return; + } for (uint8_t counter = 0; counter < nb_iterations; counter++) { if (a2dp_ldac_encoder_cb.has_ldac_abr_handle) { int flag_enable = 1; int prev_eqmid = a2dp_ldac_encoder_cb.last_ldac_abr_eqmid; a2dp_ldac_encoder_cb.last_ldac_abr_eqmid = - ldac_ABR_Proc(a2dp_ldac_encoder_cb.ldac_handle, - a2dp_ldac_encoder_cb.ldac_abr_handle, - a2dp_ldac_encoder_cb.TxQueueLength, flag_enable); - if (prev_eqmid != a2dp_ldac_encoder_cb.last_ldac_abr_eqmid) + ldac_ABR_Proc(a2dp_ldac_encoder_cb.ldac_handle, a2dp_ldac_encoder_cb.ldac_abr_handle, + a2dp_ldac_encoder_cb.TxQueueLength, flag_enable); + if (prev_eqmid != a2dp_ldac_encoder_cb.last_ldac_abr_eqmid) { a2dp_ldac_encoder_cb.ldac_abr_adjustments++; + } #ifdef __ANDROID__ ATRACE_INT("LDAC ABR level", a2dp_ldac_encoder_cb.last_ldac_abr_eqmid); #endif @@ -386,34 +359,30 @@ void a2dp_vendor_ldac_send_frames(uint64_t timestamp_us) { // Obtains the number of frames to send and number of iterations // to be used. |num_of_iterations| and |num_of_frames| parameters // are used as output param for returning the respective values. -static void a2dp_ldac_get_num_frame_iteration(uint8_t* num_of_iterations, - uint8_t* num_of_frames, +static void a2dp_ldac_get_num_frame_iteration(uint8_t* num_of_iterations, uint8_t* num_of_frames, uint64_t timestamp_us) { uint32_t result = 0; uint8_t nof = 0; uint8_t noi = 1; - uint32_t pcm_bytes_per_frame = - A2DP_LDAC_MEDIA_BYTES_PER_FRAME * - a2dp_ldac_encoder_cb.feeding_params.channel_count * - a2dp_ldac_encoder_cb.feeding_params.bits_per_sample / 8; + uint32_t pcm_bytes_per_frame = A2DP_LDAC_MEDIA_BYTES_PER_FRAME * + a2dp_ldac_encoder_cb.feeding_params.channel_count * + a2dp_ldac_encoder_cb.feeding_params.bits_per_sample / 8; log::verbose("pcm_bytes_per_frame {}", pcm_bytes_per_frame); uint32_t us_this_tick = A2DP_LDAC_ENCODER_INTERVAL_MS * 1000; uint64_t now_us = timestamp_us; - if (a2dp_ldac_encoder_cb.ldac_feeding_state.last_frame_us != 0) - us_this_tick = - (now_us - a2dp_ldac_encoder_cb.ldac_feeding_state.last_frame_us); + if (a2dp_ldac_encoder_cb.ldac_feeding_state.last_frame_us != 0) { + us_this_tick = (now_us - a2dp_ldac_encoder_cb.ldac_feeding_state.last_frame_us); + } a2dp_ldac_encoder_cb.ldac_feeding_state.last_frame_us = now_us; a2dp_ldac_encoder_cb.ldac_feeding_state.counter += - (float)a2dp_ldac_encoder_cb.ldac_feeding_state.bytes_per_tick * us_this_tick / - (A2DP_LDAC_ENCODER_INTERVAL_MS * 1000); + (float)a2dp_ldac_encoder_cb.ldac_feeding_state.bytes_per_tick * us_this_tick / + (A2DP_LDAC_ENCODER_INTERVAL_MS * 1000); - result = - a2dp_ldac_encoder_cb.ldac_feeding_state.counter / pcm_bytes_per_frame; - a2dp_ldac_encoder_cb.ldac_feeding_state.counter -= - result * pcm_bytes_per_frame; + result = a2dp_ldac_encoder_cb.ldac_feeding_state.counter / pcm_bytes_per_frame; + a2dp_ldac_encoder_cb.ldac_feeding_state.counter -= result * pcm_bytes_per_frame; nof = result; log::verbose("effective num of frames {}, iterations {}", nof, noi); @@ -423,8 +392,7 @@ static void a2dp_ldac_get_num_frame_iteration(uint8_t* num_of_iterations, } static void a2dp_ldac_encode_frames(uint8_t nb_frame) { - tA2DP_LDAC_ENCODER_PARAMS* p_encoder_params = - &a2dp_ldac_encoder_cb.ldac_encoder_params; + tA2DP_LDAC_ENCODER_PARAMS* p_encoder_params = &a2dp_ldac_encoder_cb.ldac_encoder_params; uint8_t remain_nb_frame = nb_frame; uint16_t ldac_frame_size; uint8_t read_buffer[LDACBT_MAX_LSU * 4 /* byte/sample */ * 2 /* ch */]; @@ -473,17 +441,16 @@ static void a2dp_ldac_encode_frames(uint8_t nb_frame) { osi_free(p_buf); return; } - int result = ldacBT_encode( - a2dp_ldac_encoder_cb.ldac_handle, read_buffer, (int*)&encode_count, - packet + count, (int*)&written, (int*)&out_frames); + int result = + ldacBT_encode(a2dp_ldac_encoder_cb.ldac_handle, read_buffer, (int*)&encode_count, + packet + count, (int*)&written, (int*)&out_frames); if (result != 0) { - int err_code = - ldacBT_get_error_code(a2dp_ldac_encoder_cb.ldac_handle); + int err_code = ldacBT_get_error_code(a2dp_ldac_encoder_cb.ldac_handle); log::error( - "LDAC encoding error: {} api_error = {} handle_error = {} " - "block_error = {} error_code = 0x{:x}", - result, LDACBT_API_ERR(err_code), LDACBT_HANDLE_ERR(err_code), - LDACBT_BLOCK_ERR(err_code), err_code); + "LDAC encoding error: {} api_error = {} handle_error = {} " + "block_error = {} error_code = 0x{:x}", + result, LDACBT_API_ERR(err_code), LDACBT_HANDLE_ERR(err_code), + LDACBT_BLOCK_ERR(err_code), err_code); a2dp_ldac_encoder_cb.stats.media_read_total_dropped_packets++; osi_free(p_buf); return; @@ -495,9 +462,8 @@ static void a2dp_ldac_encode_frames(uint8_t nb_frame) { } else { log::warn("underflow {}", nb_frame); a2dp_ldac_encoder_cb.ldac_feeding_state.counter += - nb_frame * LDACBT_ENC_LSU * - a2dp_ldac_encoder_cb.feeding_params.channel_count * - a2dp_ldac_encoder_cb.feeding_params.bits_per_sample / 8; + nb_frame * LDACBT_ENC_LSU * a2dp_ldac_encoder_cb.feeding_params.channel_count * + a2dp_ldac_encoder_cb.feeding_params.bits_per_sample / 8; // no more pcm to read nb_frame = 0; @@ -514,15 +480,15 @@ static void a2dp_ldac_encode_frames(uint8_t nb_frame) { // Timestamp will wrap over to 0 if stream continues on long enough // (>25H @ 48KHz). The parameters are promoted to 64bit to ensure that // no unsigned overflow is triggered as ubsan is always enabled. - a2dp_ldac_encoder_cb.timestamp = - ((uint64_t)a2dp_ldac_encoder_cb.timestamp + - (p_buf->layer_specific * ldac_frame_size)) & UINT32_MAX; + a2dp_ldac_encoder_cb.timestamp = ((uint64_t)a2dp_ldac_encoder_cb.timestamp + + (p_buf->layer_specific * ldac_frame_size)) & + UINT32_MAX; uint8_t done_nb_frame = remain_nb_frame - nb_frame; remain_nb_frame = nb_frame; - if (!a2dp_ldac_encoder_cb.enqueue_callback(p_buf, done_nb_frame, - bytes_read)) + if (!a2dp_ldac_encoder_cb.enqueue_callback(p_buf, done_nb_frame, bytes_read)) { return; + } } else { // NOTE: Unlike the execution path for other codecs, it is normal for // LDAC to NOT write encoded data to the last buffer if there wasn't @@ -535,20 +501,20 @@ static void a2dp_ldac_encode_frames(uint8_t nb_frame) { } static bool a2dp_ldac_read_feeding(uint8_t* read_buffer, uint32_t* bytes_read) { - uint32_t read_size = LDACBT_ENC_LSU * - a2dp_ldac_encoder_cb.feeding_params.channel_count * + uint32_t read_size = LDACBT_ENC_LSU * a2dp_ldac_encoder_cb.feeding_params.channel_count * a2dp_ldac_encoder_cb.feeding_params.bits_per_sample / 8; a2dp_ldac_encoder_cb.stats.media_read_total_expected_reads_count++; a2dp_ldac_encoder_cb.stats.media_read_total_expected_read_bytes += read_size; /* Read Data from UIPC channel */ - uint32_t nb_byte_read = - a2dp_ldac_encoder_cb.read_callback(read_buffer, read_size); + uint32_t nb_byte_read = a2dp_ldac_encoder_cb.read_callback(read_buffer, read_size); a2dp_ldac_encoder_cb.stats.media_read_total_actual_read_bytes += nb_byte_read; if (nb_byte_read < read_size) { - if (nb_byte_read == 0) return false; + if (nb_byte_read == 0) { + return false; + } /* Fill the unfilled part of the read buffer with silence (0) */ memset(((uint8_t*)read_buffer) + nb_byte_read, 0, read_size - nb_byte_read); @@ -560,10 +526,8 @@ static bool a2dp_ldac_read_feeding(uint8_t* read_buffer, uint32_t* bytes_read) { return true; } -static uint16_t adjust_effective_mtu( - const tA2DP_ENCODER_INIT_PEER_PARAMS& peer_params) { - uint16_t mtu_size = - BT_DEFAULT_BUFFER_SIZE - A2DP_LDAC_OFFSET - sizeof(BT_HDR); +static uint16_t adjust_effective_mtu(const tA2DP_ENCODER_INIT_PEER_PARAMS& peer_params) { + uint16_t mtu_size = BT_DEFAULT_BUFFER_SIZE - A2DP_LDAC_OFFSET - sizeof(BT_HDR); if (mtu_size > peer_params.peer_mtu) { mtu_size = peer_params.peer_mtu; } @@ -592,49 +556,38 @@ void a2dp_vendor_ldac_set_transmit_queue_length(size_t transmit_queue_length) { void A2dpCodecConfigLdacSource::debug_codec_dump(int fd) { a2dp_ldac_encoder_stats_t* stats = &a2dp_ldac_encoder_cb.stats; - tA2DP_LDAC_ENCODER_PARAMS* p_encoder_params = - &a2dp_ldac_encoder_cb.ldac_encoder_params; + tA2DP_LDAC_ENCODER_PARAMS* p_encoder_params = &a2dp_ldac_encoder_cb.ldac_encoder_params; A2dpCodecConfig::debug_codec_dump(fd); - dprintf( - fd, " LDAC quality mode : %s\n", - quality_mode_index_to_name(p_encoder_params->quality_mode_index).c_str()); + dprintf(fd, " LDAC quality mode : %s\n", + quality_mode_index_to_name(p_encoder_params->quality_mode_index).c_str()); - dprintf(fd, - " LDAC transmission bitrate (Kbps) : %d\n", + dprintf(fd, " LDAC transmission bitrate (Kbps) : %d\n", ldacBT_get_bitrate(a2dp_ldac_encoder_cb.ldac_handle)); - dprintf(fd, - " LDAC saved transmit queue length : %zu\n", + dprintf(fd, " LDAC saved transmit queue length : %zu\n", a2dp_ldac_encoder_cb.TxQueueLength); if (a2dp_ldac_encoder_cb.has_ldac_abr_handle) { - dprintf(fd, - " LDAC adaptive bit rate encode quality mode index : %d\n", + dprintf(fd, " LDAC adaptive bit rate encode quality mode index : %d\n", a2dp_ldac_encoder_cb.last_ldac_abr_eqmid); - dprintf(fd, - " LDAC adaptive bit rate adjustments : %zu\n", + dprintf(fd, " LDAC adaptive bit rate adjustments : %zu\n", a2dp_ldac_encoder_cb.ldac_abr_adjustments); } - dprintf(fd, " Encoder interval (ms): %" PRIu64 "\n", - a2dp_vendor_ldac_get_encoder_interval_ms()); - dprintf(fd, " Effective MTU: %d\n", - a2dp_vendor_ldac_get_effective_frame_size()); + dprintf(fd, " Encoder interval (ms): %" PRIu64 "\n", a2dp_vendor_ldac_get_encoder_interval_ms()); + dprintf(fd, " Effective MTU: %d\n", a2dp_vendor_ldac_get_effective_frame_size()); dprintf(fd, " Packet counts (expected/dropped) : %zu / " "%zu\n", - stats->media_read_total_expected_packets, - stats->media_read_total_dropped_packets); + stats->media_read_total_expected_packets, stats->media_read_total_dropped_packets); dprintf(fd, " PCM read counts (expected/actual) : %zu / " "%zu\n", - stats->media_read_total_expected_reads_count, - stats->media_read_total_actual_reads_count); + stats->media_read_total_expected_reads_count, stats->media_read_total_actual_reads_count); dprintf(fd, " PCM read bytes (expected/actual) : %zu / " "%zu\n", - stats->media_read_total_expected_read_bytes, - stats->media_read_total_actual_read_bytes); + stats->media_read_total_expected_read_bytes, stats->media_read_total_actual_read_bytes); } diff --git a/system/stack/a2dp/a2dp_vendor_ldac_linux.cc b/system/stack/a2dp/a2dp_vendor_ldac_linux.cc index e856cd9a8fb..9b761857583 100644 --- a/system/stack/a2dp/a2dp_vendor_ldac_linux.cc +++ b/system/stack/a2dp/a2dp_vendor_ldac_linux.cc @@ -18,74 +18,46 @@ #include "a2dp_vendor_ldac.h" -bool A2DP_IsVendorSourceCodecValidLdac(const uint8_t* p_codec_info) { - return false; -} +bool A2DP_IsVendorSourceCodecValidLdac(const uint8_t* p_codec_info) { return false; } -bool A2DP_IsVendorSinkCodecValidLdac(const uint8_t* p_codec_info) { - return false; -} +bool A2DP_IsVendorSinkCodecValidLdac(const uint8_t* p_codec_info) { return false; } -bool A2DP_IsVendorPeerSourceCodecValidLdac(const uint8_t* p_codec_info) { - return false; -} +bool A2DP_IsVendorPeerSourceCodecValidLdac(const uint8_t* p_codec_info) { return false; } -bool A2DP_IsVendorPeerSinkCodecValidLdac(const uint8_t* p_codec_info) { - return false; -} +bool A2DP_IsVendorPeerSinkCodecValidLdac(const uint8_t* p_codec_info) { return false; } -bool A2DP_IsVendorSinkCodecSupportedLdac(const uint8_t* p_codec_info) { - return false; -} -bool A2DP_IsPeerSourceCodecSupportedLdac(const uint8_t* p_codec_info) { - return false; -} +bool A2DP_IsVendorSinkCodecSupportedLdac(const uint8_t* p_codec_info) { return false; } +bool A2DP_IsPeerSourceCodecSupportedLdac(const uint8_t* p_codec_info) { return false; } -bool A2DP_VendorUsesRtpHeaderLdac(bool content_protection_enabled, - const uint8_t* p_codec_info) { +bool A2DP_VendorUsesRtpHeaderLdac(bool content_protection_enabled, const uint8_t* p_codec_info) { return false; } -const char* A2DP_VendorCodecNameLdac(const uint8_t* p_codec_info) { - return "Ldac"; -} +const char* A2DP_VendorCodecNameLdac(const uint8_t* p_codec_info) { return "Ldac"; } -bool A2DP_VendorCodecTypeEqualsLdac(const uint8_t* p_codec_info_a, - const uint8_t* p_codec_info_b) { +bool A2DP_VendorCodecTypeEqualsLdac(const uint8_t* p_codec_info_a, const uint8_t* p_codec_info_b) { return false; } -bool A2DP_VendorCodecEqualsLdac(const uint8_t* p_codec_info_a, - const uint8_t* p_codec_info_b) { +bool A2DP_VendorCodecEqualsLdac(const uint8_t* p_codec_info_a, const uint8_t* p_codec_info_b) { return false; } int A2DP_VendorGetBitRateLdac(const uint8_t* p_codec_info) { return -1; } -int A2DP_VendorGetTrackSampleRateLdac(const uint8_t* p_codec_info) { - return -1; -} +int A2DP_VendorGetTrackSampleRateLdac(const uint8_t* p_codec_info) { return -1; } -int A2DP_VendorGetTrackBitsPerSampleLdac(const uint8_t* p_codec_info) { - return -1; -} +int A2DP_VendorGetTrackBitsPerSampleLdac(const uint8_t* p_codec_info) { return -1; } -int A2DP_VendorGetTrackChannelCountLdac(const uint8_t* p_codec_info) { - return -1; -} +int A2DP_VendorGetTrackChannelCountLdac(const uint8_t* p_codec_info) { return -1; } -int A2DP_VendorGetSinkTrackChannelTypeLdac(const uint8_t* p_codec_info) { - return -1; -} +int A2DP_VendorGetSinkTrackChannelTypeLdac(const uint8_t* p_codec_info) { return -1; } -int A2DP_VendorGetChannelModeCodeLdac(const uint8_t* p_codec_info) { - return -1; -} +int A2DP_VendorGetChannelModeCodeLdac(const uint8_t* p_codec_info) { return -1; } int A2DP_VendorGetFrameSizeLdac(const uint8_t* p_codec_info) { return -1; } -bool A2DP_VendorGetPacketTimestampLdac(const uint8_t* p_codec_info, - const uint8_t* p_data, +bool A2DP_VendorGetPacketTimestampLdac(const uint8_t* p_codec_info, const uint8_t* p_data, uint32_t* p_timestamp) { return false; } @@ -99,25 +71,21 @@ std::string A2DP_VendorCodecInfoStringLdac(const uint8_t* p_codec_info) { return "Unsupported codec: Ldac"; } -const tA2DP_ENCODER_INTERFACE* A2DP_VendorGetEncoderInterfaceLdac( - const uint8_t* p_codec_info) { +const tA2DP_ENCODER_INTERFACE* A2DP_VendorGetEncoderInterfaceLdac(const uint8_t* p_codec_info) { return nullptr; } -const tA2DP_DECODER_INTERFACE* A2DP_VendorGetDecoderInterfaceLdac( - const uint8_t* p_codec_info) { +const tA2DP_DECODER_INTERFACE* A2DP_VendorGetDecoderInterfaceLdac(const uint8_t* p_codec_info) { return nullptr; } bool A2DP_VendorAdjustCodecLdac(uint8_t* p_codec_info) { return false; } -btav_a2dp_codec_index_t A2DP_VendorSourceCodecIndexLdac( - const uint8_t* p_codec_info) { +btav_a2dp_codec_index_t A2DP_VendorSourceCodecIndexLdac(const uint8_t* p_codec_info) { return BTAV_A2DP_CODEC_INDEX_MAX; } -btav_a2dp_codec_index_t A2DP_VendorSinkCodecIndexLdac( - const uint8_t* p_codec_info) { +btav_a2dp_codec_index_t A2DP_VendorSinkCodecIndexLdac(const uint8_t* p_codec_info) { return BTAV_A2DP_CODEC_INDEX_MAX; } @@ -129,11 +97,9 @@ bool A2DP_VendorInitCodecConfigLdac(AvdtpSepConfig* p_cfg) { return false; } bool A2DP_VendorInitCodecConfigLdacSink(AvdtpSepConfig* p_cfg) { return false; } -A2dpCodecConfigLdacSource::A2dpCodecConfigLdacSource( - btav_a2dp_codec_priority_t codec_priority) - : A2dpCodecConfigLdacBase(BTAV_A2DP_CODEC_INDEX_SOURCE_LDAC, - A2DP_VendorCodecIndexStrLdac(), codec_priority, - true) {} +A2dpCodecConfigLdacSource::A2dpCodecConfigLdacSource(btav_a2dp_codec_priority_t codec_priority) + : A2dpCodecConfigLdacBase(BTAV_A2DP_CODEC_INDEX_SOURCE_LDAC, A2DP_VendorCodecIndexStrLdac(), + codec_priority, true) {} A2dpCodecConfigLdacSource::~A2dpCodecConfigLdacSource() {} @@ -143,21 +109,17 @@ bool A2dpCodecConfigLdacSource::useRtpHeaderMarkerBit() const { return false; } void A2dpCodecConfigLdacSource::debug_codec_dump(int fd) {} -bool A2dpCodecConfigLdacBase::setCodecConfig(const uint8_t* p_peer_codec_info, - bool is_capability, +bool A2dpCodecConfigLdacBase::setCodecConfig(const uint8_t* p_peer_codec_info, bool is_capability, uint8_t* p_result_codec_config) { return false; } -bool A2dpCodecConfigLdacBase::setPeerCodecCapabilities( - const uint8_t* p_peer_codec_capabilities) { +bool A2dpCodecConfigLdacBase::setPeerCodecCapabilities(const uint8_t* p_peer_codec_capabilities) { return false; } -A2dpCodecConfigLdacSink::A2dpCodecConfigLdacSink( - btav_a2dp_codec_priority_t codec_priority) - : A2dpCodecConfigLdacBase(BTAV_A2DP_CODEC_INDEX_SINK_LDAC, - A2DP_VendorCodecIndexStrLdacSink(), +A2dpCodecConfigLdacSink::A2dpCodecConfigLdacSink(btav_a2dp_codec_priority_t codec_priority) + : A2dpCodecConfigLdacBase(BTAV_A2DP_CODEC_INDEX_SINK_LDAC, A2DP_VendorCodecIndexStrLdacSink(), codec_priority, false) {} A2dpCodecConfigLdacSink::~A2dpCodecConfigLdacSink() {} diff --git a/system/stack/a2dp/a2dp_vendor_opus.cc b/system/stack/a2dp/a2dp_vendor_opus.cc index 5d1f24b383e..04dce02aa79 100644 --- a/system/stack/a2dp/a2dp_vendor_opus.cc +++ b/system/stack/a2dp/a2dp_vendor_opus.cc @@ -51,83 +51,80 @@ typedef struct { } tA2DP_OPUS_CIE; /* Opus Source codec capabilities */ -static const tA2DP_OPUS_CIE a2dp_opus_source_caps = { - A2DP_OPUS_VENDOR_ID, // vendorId - A2DP_OPUS_CODEC_ID, // codecId - // sampleRate - (A2DP_OPUS_SAMPLING_FREQ_48000), - // channelMode - (A2DP_OPUS_CHANNEL_MODE_STEREO), - // bits_per_sample - (BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16), - // future 1 frameSize - (A2DP_OPUS_20MS_FRAMESIZE), - // future 2 - 0x00, - // future 3 - 0x00, - // future 4 - 0x00}; +static const tA2DP_OPUS_CIE a2dp_opus_source_caps = {A2DP_OPUS_VENDOR_ID, // vendorId + A2DP_OPUS_CODEC_ID, // codecId + // sampleRate + (A2DP_OPUS_SAMPLING_FREQ_48000), + // channelMode + (A2DP_OPUS_CHANNEL_MODE_STEREO), + // bits_per_sample + (BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16), + // future 1 frameSize + (A2DP_OPUS_20MS_FRAMESIZE), + // future 2 + 0x00, + // future 3 + 0x00, + // future 4 + 0x00}; /* Opus Sink codec capabilities */ -static const tA2DP_OPUS_CIE a2dp_opus_sink_caps = { - A2DP_OPUS_VENDOR_ID, // vendorId - A2DP_OPUS_CODEC_ID, // codecId - // sampleRate - (A2DP_OPUS_SAMPLING_FREQ_48000), - // channelMode - (A2DP_OPUS_CHANNEL_MODE_STEREO), - // bits_per_sample - (BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16), - // future 1 frameSize - (A2DP_OPUS_20MS_FRAMESIZE), - // future 2 - 0x00, - // future 3 - 0x00, - // future 4 - 0x00}; +static const tA2DP_OPUS_CIE a2dp_opus_sink_caps = {A2DP_OPUS_VENDOR_ID, // vendorId + A2DP_OPUS_CODEC_ID, // codecId + // sampleRate + (A2DP_OPUS_SAMPLING_FREQ_48000), + // channelMode + (A2DP_OPUS_CHANNEL_MODE_STEREO), + // bits_per_sample + (BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16), + // future 1 frameSize + (A2DP_OPUS_20MS_FRAMESIZE), + // future 2 + 0x00, + // future 3 + 0x00, + // future 4 + 0x00}; /* Default Opus codec configuration */ static const tA2DP_OPUS_CIE a2dp_opus_default_config = { - A2DP_OPUS_VENDOR_ID, // vendorId - A2DP_OPUS_CODEC_ID, // codecId - A2DP_OPUS_SAMPLING_FREQ_48000, // sampleRate - A2DP_OPUS_CHANNEL_MODE_STEREO, // channelMode - BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16, // bits_per_sample - A2DP_OPUS_20MS_FRAMESIZE, // frameSize - 0x00, // future 2 - 0x00, // future 3 - 0x00 // future 4 + A2DP_OPUS_VENDOR_ID, // vendorId + A2DP_OPUS_CODEC_ID, // codecId + A2DP_OPUS_SAMPLING_FREQ_48000, // sampleRate + A2DP_OPUS_CHANNEL_MODE_STEREO, // channelMode + BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16, // bits_per_sample + A2DP_OPUS_20MS_FRAMESIZE, // frameSize + 0x00, // future 2 + 0x00, // future 3 + 0x00 // future 4 }; static const tA2DP_ENCODER_INTERFACE a2dp_encoder_interface_opus = { - a2dp_vendor_opus_encoder_init, - a2dp_vendor_opus_encoder_cleanup, - a2dp_vendor_opus_feeding_reset, - a2dp_vendor_opus_feeding_flush, - a2dp_vendor_opus_get_encoder_interval_ms, - a2dp_vendor_opus_get_effective_frame_size, - a2dp_vendor_opus_send_frames, - a2dp_vendor_opus_set_transmit_queue_length}; + a2dp_vendor_opus_encoder_init, + a2dp_vendor_opus_encoder_cleanup, + a2dp_vendor_opus_feeding_reset, + a2dp_vendor_opus_feeding_flush, + a2dp_vendor_opus_get_encoder_interval_ms, + a2dp_vendor_opus_get_effective_frame_size, + a2dp_vendor_opus_send_frames, + a2dp_vendor_opus_set_transmit_queue_length}; static const tA2DP_DECODER_INTERFACE a2dp_decoder_interface_opus = { - a2dp_vendor_opus_decoder_init, a2dp_vendor_opus_decoder_cleanup, - a2dp_vendor_opus_decoder_decode_packet, a2dp_vendor_opus_decoder_start, - a2dp_vendor_opus_decoder_suspend, a2dp_vendor_opus_decoder_configure, + a2dp_vendor_opus_decoder_init, a2dp_vendor_opus_decoder_cleanup, + a2dp_vendor_opus_decoder_decode_packet, a2dp_vendor_opus_decoder_start, + a2dp_vendor_opus_decoder_suspend, a2dp_vendor_opus_decoder_configure, }; -static tA2DP_STATUS A2DP_CodecInfoMatchesCapabilityOpus( - const tA2DP_OPUS_CIE* p_cap, const uint8_t* p_codec_info, - bool is_peer_codec_info); +static tA2DP_STATUS A2DP_CodecInfoMatchesCapabilityOpus(const tA2DP_OPUS_CIE* p_cap, + const uint8_t* p_codec_info, + bool is_peer_codec_info); // Builds the Opus Media Codec Capabilities byte sequence beginning from the // LOSC octet. |media_type| is the media type |AVDT_MEDIA_TYPE_*|. // |p_ie| is a pointer to the Opus Codec Information Element information. // The result is stored in |p_result|. Returns A2DP_SUCCESS on success, // otherwise the corresponding A2DP error status code. -static tA2DP_STATUS A2DP_BuildInfoOpus(uint8_t media_type, - const tA2DP_OPUS_CIE* p_ie, +static tA2DP_STATUS A2DP_BuildInfoOpus(uint8_t media_type, const tA2DP_OPUS_CIE* p_ie, uint8_t* p_result) { if (p_ie == NULL || p_result == NULL) { log::error("invalid information element"); @@ -176,8 +173,7 @@ static tA2DP_STATUS A2DP_BuildInfoOpus(uint8_t media_type, // codec capabilities, otherwise is codec configuration. // Returns A2DP_SUCCESS on success, otherwise the corresponding A2DP error // status code. -static tA2DP_STATUS A2DP_ParseInfoOpus(tA2DP_OPUS_CIE* p_ie, - const uint8_t* p_codec_info, +static tA2DP_STATUS A2DP_ParseInfoOpus(tA2DP_OPUS_CIE* p_ie, const uint8_t* p_codec_info, bool is_capability) { uint8_t losc; uint8_t media_type; @@ -198,23 +194,19 @@ static tA2DP_STATUS A2DP_ParseInfoOpus(tA2DP_OPUS_CIE* p_ie, media_type = (*p_codec_info++) >> 4; codec_type = *p_codec_info++; /* Check the Media Type and Media Codec Type */ - if (media_type != AVDT_MEDIA_TYPE_AUDIO || - codec_type != A2DP_MEDIA_CT_NON_A2DP) { + if (media_type != AVDT_MEDIA_TYPE_AUDIO || codec_type != A2DP_MEDIA_CT_NON_A2DP) { log::error("invalid codec"); return A2DP_WRONG_CODEC; } // Check the Vendor ID and Codec ID */ - p_ie->vendorId = (*p_codec_info & 0x000000FF) | - (*(p_codec_info + 1) << 8 & 0x0000FF00) | + p_ie->vendorId = (*p_codec_info & 0x000000FF) | (*(p_codec_info + 1) << 8 & 0x0000FF00) | (*(p_codec_info + 2) << 16 & 0x00FF0000) | (*(p_codec_info + 3) << 24 & 0xFF000000); p_codec_info += 4; - p_ie->codecId = - (*p_codec_info & 0x00FF) | (*(p_codec_info + 1) << 8 & 0xFF00); + p_ie->codecId = (*p_codec_info & 0x00FF) | (*(p_codec_info + 1) << 8 & 0xFF00); p_codec_info += 2; - if (p_ie->vendorId != A2DP_OPUS_VENDOR_ID || - p_ie->codecId != A2DP_OPUS_CODEC_ID) { + if (p_ie->vendorId != A2DP_OPUS_VENDOR_ID || p_ie->codecId != A2DP_OPUS_CODEC_ID) { log::error("wrong vendor or codec id"); return A2DP_WRONG_CODEC; } @@ -258,15 +250,22 @@ static tA2DP_STATUS A2DP_ParseInfoOpus(tA2DP_OPUS_CIE* p_ie, // |last| is true for the last packet of a fragmented frame. // If |frag| is false, |num| is the number of number of frames in the packet, // otherwise is the number of remaining fragments (including this one). -static void A2DP_BuildMediaPayloadHeaderOpus(uint8_t* p_dst, bool frag, - bool start, bool last, +static void A2DP_BuildMediaPayloadHeaderOpus(uint8_t* p_dst, bool frag, bool start, bool last, uint8_t num) { - if (p_dst == NULL) return; + if (p_dst == NULL) { + return; + } *p_dst = 0; - if (frag) *p_dst |= A2DP_OPUS_HDR_F_MSK; - if (start) *p_dst |= A2DP_OPUS_HDR_S_MSK; - if (last) *p_dst |= A2DP_OPUS_HDR_L_MSK; + if (frag) { + *p_dst |= A2DP_OPUS_HDR_F_MSK; + } + if (start) { + *p_dst |= A2DP_OPUS_HDR_S_MSK; + } + if (last) { + *p_dst |= A2DP_OPUS_HDR_L_MSK; + } *p_dst |= (A2DP_OPUS_HDR_NUM_MSK & num); } @@ -303,12 +302,12 @@ bool A2DP_IsVendorPeerSinkCodecValidOpus(const uint8_t* p_codec_info) { } bool A2DP_IsVendorSinkCodecSupportedOpus(const uint8_t* p_codec_info) { - return A2DP_CodecInfoMatchesCapabilityOpus(&a2dp_opus_sink_caps, p_codec_info, - false) == A2DP_SUCCESS; + return A2DP_CodecInfoMatchesCapabilityOpus(&a2dp_opus_sink_caps, p_codec_info, false) == + A2DP_SUCCESS; } bool A2DP_IsPeerSourceCodecSupportedOpus(const uint8_t* p_codec_info) { - return A2DP_CodecInfoMatchesCapabilityOpus(&a2dp_opus_sink_caps, p_codec_info, - true) == A2DP_SUCCESS; + return A2DP_CodecInfoMatchesCapabilityOpus(&a2dp_opus_sink_caps, p_codec_info, true) == + A2DP_SUCCESS; } // Checks whether A2DP Opus codec configuration matches with a device's codec @@ -320,9 +319,9 @@ bool A2DP_IsPeerSourceCodecSupportedOpus(const uint8_t* p_codec_info) { // is acting as an A2DP source. // Returns A2DP_SUCCESS if the codec configuration matches with capabilities, // otherwise the corresponding A2DP error status code. -static tA2DP_STATUS A2DP_CodecInfoMatchesCapabilityOpus( - const tA2DP_OPUS_CIE* p_cap, const uint8_t* p_codec_info, - bool is_capability) { +static tA2DP_STATUS A2DP_CodecInfoMatchesCapabilityOpus(const tA2DP_OPUS_CIE* p_cap, + const uint8_t* p_codec_info, + bool is_capability) { tA2DP_STATUS status; tA2DP_OPUS_CIE cfg_cie; @@ -335,21 +334,25 @@ static tA2DP_STATUS A2DP_CodecInfoMatchesCapabilityOpus( /* verify that each parameter is in range */ - log::verbose("SAMPLING FREQ peer: 0x{:x}, capability 0x{:x}", - cfg_cie.sampleRate, p_cap->sampleRate); - log::verbose("CH_MODE peer: 0x{:x}, capability 0x{:x}", cfg_cie.channelMode, - p_cap->channelMode); - log::verbose("FRAMESIZE peer: 0x{:x}, capability 0x{:x}", cfg_cie.future1, - p_cap->future1); + log::verbose("SAMPLING FREQ peer: 0x{:x}, capability 0x{:x}", cfg_cie.sampleRate, + p_cap->sampleRate); + log::verbose("CH_MODE peer: 0x{:x}, capability 0x{:x}", cfg_cie.channelMode, p_cap->channelMode); + log::verbose("FRAMESIZE peer: 0x{:x}, capability 0x{:x}", cfg_cie.future1, p_cap->future1); /* sampling frequency */ - if ((cfg_cie.sampleRate & p_cap->sampleRate) == 0) return A2DP_NS_SAMP_FREQ; + if ((cfg_cie.sampleRate & p_cap->sampleRate) == 0) { + return A2DP_NS_SAMP_FREQ; + } /* channel mode */ - if ((cfg_cie.channelMode & p_cap->channelMode) == 0) return A2DP_NS_CH_MODE; + if ((cfg_cie.channelMode & p_cap->channelMode) == 0) { + return A2DP_NS_CH_MODE; + } /* frameSize */ - if ((cfg_cie.future1 & p_cap->future1) == 0) return A2DP_NS_FRAMESIZE; + if ((cfg_cie.future1 & p_cap->future1) == 0) { + return A2DP_NS_FRAMESIZE; + } return A2DP_SUCCESS; } @@ -359,18 +362,14 @@ bool A2DP_VendorUsesRtpHeaderOpus(bool /* content_protection_enabled */, return true; } -const char* A2DP_VendorCodecNameOpus(const uint8_t* /* p_codec_info */) { - return "Opus"; -} +const char* A2DP_VendorCodecNameOpus(const uint8_t* /* p_codec_info */) { return "Opus"; } -bool A2DP_VendorCodecTypeEqualsOpus(const uint8_t* p_codec_info_a, - const uint8_t* p_codec_info_b) { +bool A2DP_VendorCodecTypeEqualsOpus(const uint8_t* p_codec_info_a, const uint8_t* p_codec_info_b) { tA2DP_OPUS_CIE Opus_cie_a; tA2DP_OPUS_CIE Opus_cie_b; // Check whether the codec info contains valid data - tA2DP_STATUS a2dp_status = - A2DP_ParseInfoOpus(&Opus_cie_a, p_codec_info_a, true); + tA2DP_STATUS a2dp_status = A2DP_ParseInfoOpus(&Opus_cie_a, p_codec_info_a, true); if (a2dp_status != A2DP_SUCCESS) { log::error("cannot decode codec information: {}", a2dp_status); return false; @@ -384,14 +383,12 @@ bool A2DP_VendorCodecTypeEqualsOpus(const uint8_t* p_codec_info_a, return true; } -bool A2DP_VendorCodecEqualsOpus(const uint8_t* p_codec_info_a, - const uint8_t* p_codec_info_b) { +bool A2DP_VendorCodecEqualsOpus(const uint8_t* p_codec_info_a, const uint8_t* p_codec_info_b) { tA2DP_OPUS_CIE Opus_cie_a; tA2DP_OPUS_CIE Opus_cie_b; // Check whether the codec info contains valid data - tA2DP_STATUS a2dp_status = - A2DP_ParseInfoOpus(&Opus_cie_a, p_codec_info_a, true); + tA2DP_STATUS a2dp_status = A2DP_ParseInfoOpus(&Opus_cie_a, p_codec_info_a, true); if (a2dp_status != A2DP_SUCCESS) { log::error("cannot decode codec information: {}", a2dp_status); return false; @@ -419,8 +416,9 @@ int A2DP_VendorGetBitRateOpus(const uint8_t* p_codec_info) { return 256000; } else if (channel_count == 1) { return 128000; - } else + } else { return -1; + } default: return -1; } @@ -553,15 +551,13 @@ int A2DP_VendorGetFrameSizeOpus(const uint8_t* p_codec_info) { return -1; } -bool A2DP_VendorGetPacketTimestampOpus(const uint8_t* /* p_codec_info */, - const uint8_t* p_data, +bool A2DP_VendorGetPacketTimestampOpus(const uint8_t* /* p_codec_info */, const uint8_t* p_data, uint32_t* p_timestamp) { *p_timestamp = *(const uint32_t*)p_data; return true; } -bool A2DP_VendorBuildCodecHeaderOpus(const uint8_t* /* p_codec_info */, - BT_HDR* p_buf, +bool A2DP_VendorBuildCodecHeaderOpus(const uint8_t* /* p_codec_info */, BT_HDR* p_buf, uint16_t frames_per_packet) { uint8_t* p; @@ -573,8 +569,7 @@ bool A2DP_VendorBuildCodecHeaderOpus(const uint8_t* /* p_codec_info */, p = (uint8_t*)(p_buf + 1) + p_buf->offset; p_buf->len += A2DP_OPUS_MPL_HDR_LEN; - A2DP_BuildMediaPayloadHeaderOpus(p, false, false, false, - (uint8_t)frames_per_packet); + A2DP_BuildMediaPayloadHeaderOpus(p, false, false, false, (uint8_t)frames_per_packet); return true; } @@ -587,8 +582,7 @@ std::string A2DP_VendorCodecInfoStringOpus(const uint8_t* p_codec_info) { a2dp_status = A2DP_ParseInfoOpus(&Opus_cie, p_codec_info, true); if (a2dp_status != A2DP_SUCCESS) { - res << "A2DP_ParseInfoOpus fail: " - << loghex(static_cast(a2dp_status)); + res << "A2DP_ParseInfoOpus fail: " << loghex(static_cast(a2dp_status)); return res.str(); } @@ -597,20 +591,15 @@ std::string A2DP_VendorCodecInfoStringOpus(const uint8_t* p_codec_info) { // Sample frequency field.clear(); AppendField(&field, (Opus_cie.sampleRate == 0), "NONE"); - AppendField(&field, (Opus_cie.sampleRate & A2DP_OPUS_SAMPLING_FREQ_48000), - "48000"); - res << "\tsamp_freq: " << field << " (" << loghex(Opus_cie.sampleRate) - << ")\n"; + AppendField(&field, (Opus_cie.sampleRate & A2DP_OPUS_SAMPLING_FREQ_48000), "48000"); + res << "\tsamp_freq: " << field << " (" << loghex(Opus_cie.sampleRate) << ")\n"; // Channel mode field.clear(); AppendField(&field, (Opus_cie.channelMode == 0), "NONE"); - AppendField(&field, (Opus_cie.channelMode & A2DP_OPUS_CHANNEL_MODE_MONO), - "Mono"); - AppendField(&field, (Opus_cie.channelMode & A2DP_OPUS_CHANNEL_MODE_STEREO), - "Stereo"); - res << "\tch_mode: " << field << " (" << loghex(Opus_cie.channelMode) - << ")\n"; + AppendField(&field, (Opus_cie.channelMode & A2DP_OPUS_CHANNEL_MODE_MONO), "Mono"); + AppendField(&field, (Opus_cie.channelMode & A2DP_OPUS_CHANNEL_MODE_STEREO), "Stereo"); + res << "\tch_mode: " << field << " (" << loghex(Opus_cie.channelMode) << ")\n"; // Framesize field.clear(); @@ -622,16 +611,18 @@ std::string A2DP_VendorCodecInfoStringOpus(const uint8_t* p_codec_info) { return res.str(); } -const tA2DP_ENCODER_INTERFACE* A2DP_VendorGetEncoderInterfaceOpus( - const uint8_t* p_codec_info) { - if (!A2DP_IsVendorSourceCodecValidOpus(p_codec_info)) return NULL; +const tA2DP_ENCODER_INTERFACE* A2DP_VendorGetEncoderInterfaceOpus(const uint8_t* p_codec_info) { + if (!A2DP_IsVendorSourceCodecValidOpus(p_codec_info)) { + return NULL; + } return &a2dp_encoder_interface_opus; } -const tA2DP_DECODER_INTERFACE* A2DP_VendorGetDecoderInterfaceOpus( - const uint8_t* p_codec_info) { - if (!A2DP_IsVendorSinkCodecValidOpus(p_codec_info)) return NULL; +const tA2DP_DECODER_INTERFACE* A2DP_VendorGetDecoderInterfaceOpus(const uint8_t* p_codec_info) { + if (!A2DP_IsVendorSinkCodecValidOpus(p_codec_info)) { + return NULL; + } return &a2dp_decoder_interface_opus; } @@ -640,19 +631,18 @@ bool A2DP_VendorAdjustCodecOpus(uint8_t* p_codec_info) { tA2DP_OPUS_CIE cfg_cie; // Nothing to do: just verify the codec info is valid - if (A2DP_ParseInfoOpus(&cfg_cie, p_codec_info, true) != A2DP_SUCCESS) + if (A2DP_ParseInfoOpus(&cfg_cie, p_codec_info, true) != A2DP_SUCCESS) { return false; + } return true; } -btav_a2dp_codec_index_t A2DP_VendorSourceCodecIndexOpus( - const uint8_t* /* p_codec_info */) { +btav_a2dp_codec_index_t A2DP_VendorSourceCodecIndexOpus(const uint8_t* /* p_codec_info */) { return BTAV_A2DP_CODEC_INDEX_SOURCE_OPUS; } -btav_a2dp_codec_index_t A2DP_VendorSinkCodecIndexOpus( - const uint8_t* /* p_codec_info */) { +btav_a2dp_codec_index_t A2DP_VendorSinkCodecIndexOpus(const uint8_t* /* p_codec_info */) { return BTAV_A2DP_CODEC_INDEX_SINK_OPUS; } @@ -661,8 +651,8 @@ const char* A2DP_VendorCodecIndexStrOpus(void) { return "Opus"; } const char* A2DP_VendorCodecIndexStrOpusSink(void) { return "Opus SINK"; } bool A2DP_VendorInitCodecConfigOpus(AvdtpSepConfig* p_cfg) { - if (A2DP_BuildInfoOpus(AVDT_MEDIA_TYPE_AUDIO, &a2dp_opus_source_caps, - p_cfg->codec_info) != A2DP_SUCCESS) { + if (A2DP_BuildInfoOpus(AVDT_MEDIA_TYPE_AUDIO, &a2dp_opus_source_caps, p_cfg->codec_info) != + A2DP_SUCCESS) { return false; } @@ -670,40 +660,41 @@ bool A2DP_VendorInitCodecConfigOpus(AvdtpSepConfig* p_cfg) { } bool A2DP_VendorInitCodecConfigOpusSink(AvdtpSepConfig* p_cfg) { - return A2DP_BuildInfoOpus(AVDT_MEDIA_TYPE_AUDIO, &a2dp_opus_sink_caps, - p_cfg->codec_info) == A2DP_SUCCESS; + return A2DP_BuildInfoOpus(AVDT_MEDIA_TYPE_AUDIO, &a2dp_opus_sink_caps, p_cfg->codec_info) == + A2DP_SUCCESS; } UNUSED_ATTR static void build_codec_config(const tA2DP_OPUS_CIE& config_cie, btav_a2dp_codec_config_t* result) { - if (config_cie.sampleRate & A2DP_OPUS_SAMPLING_FREQ_48000) + if (config_cie.sampleRate & A2DP_OPUS_SAMPLING_FREQ_48000) { result->sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_48000; + } result->bits_per_sample = config_cie.bits_per_sample; - if (config_cie.channelMode & A2DP_OPUS_CHANNEL_MODE_MONO) + if (config_cie.channelMode & A2DP_OPUS_CHANNEL_MODE_MONO) { result->channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_MONO; + } if (config_cie.channelMode & A2DP_OPUS_CHANNEL_MODE_STEREO) { result->channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; } - if (config_cie.future1 & A2DP_OPUS_20MS_FRAMESIZE) + if (config_cie.future1 & A2DP_OPUS_20MS_FRAMESIZE) { result->codec_specific_1 |= BTAV_A2DP_CODEC_FRAME_SIZE_20MS; - if (config_cie.future1 & A2DP_OPUS_10MS_FRAMESIZE) + } + if (config_cie.future1 & A2DP_OPUS_10MS_FRAMESIZE) { result->codec_specific_1 |= BTAV_A2DP_CODEC_FRAME_SIZE_10MS; + } } -A2dpCodecConfigOpusSource::A2dpCodecConfigOpusSource( - btav_a2dp_codec_priority_t codec_priority) - : A2dpCodecConfigOpusBase(BTAV_A2DP_CODEC_INDEX_SOURCE_OPUS, - A2DP_VendorCodecIndexStrOpus(), codec_priority, - true) { +A2dpCodecConfigOpusSource::A2dpCodecConfigOpusSource(btav_a2dp_codec_priority_t codec_priority) + : A2dpCodecConfigOpusBase(BTAV_A2DP_CODEC_INDEX_SOURCE_OPUS, A2DP_VendorCodecIndexStrOpus(), + codec_priority, true) { // Compute the local capability if (a2dp_opus_source_caps.sampleRate & A2DP_OPUS_SAMPLING_FREQ_48000) { codec_local_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_48000; } - codec_local_capability_.bits_per_sample = - a2dp_opus_source_caps.bits_per_sample; + codec_local_capability_.bits_per_sample = a2dp_opus_source_caps.bits_per_sample; if (a2dp_opus_source_caps.channelMode & A2DP_OPUS_CHANNEL_MODE_MONO) { codec_local_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_MONO; } @@ -715,7 +706,9 @@ A2dpCodecConfigOpusSource::A2dpCodecConfigOpusSource( A2dpCodecConfigOpusSource::~A2dpCodecConfigOpusSource() {} bool A2dpCodecConfigOpusSource::init() { - if (!isValid()) return false; + if (!isValid()) { + return false; + } return true; } @@ -727,8 +720,7 @@ bool A2dpCodecConfigOpusSource::useRtpHeaderMarkerBit() const { return false; } // The result is stored in |p_result| and |p_codec_config|. // Returns true if a selection was made, otherwise false. // -static bool select_best_sample_rate(uint8_t sampleRate, - tA2DP_OPUS_CIE* p_result, +static bool select_best_sample_rate(uint8_t sampleRate, tA2DP_OPUS_CIE* p_result, btav_a2dp_codec_config_t* p_codec_config) { if (sampleRate & A2DP_OPUS_SAMPLING_FREQ_48000) { p_result->sampleRate = A2DP_OPUS_SAMPLING_FREQ_48000; @@ -744,9 +736,9 @@ static bool select_best_sample_rate(uint8_t sampleRate, // The result is stored in |p_result| and |p_codec_config|. // Returns true if a selection was made, otherwise false. // -static bool select_audio_sample_rate( - const btav_a2dp_codec_config_t* p_codec_audio_config, uint8_t sampleRate, - tA2DP_OPUS_CIE* p_result, btav_a2dp_codec_config_t* p_codec_config) { +static bool select_audio_sample_rate(const btav_a2dp_codec_config_t* p_codec_audio_config, + uint8_t sampleRate, tA2DP_OPUS_CIE* p_result, + btav_a2dp_codec_config_t* p_codec_config) { switch (p_codec_audio_config->sample_rate) { case BTAV_A2DP_CODEC_SAMPLE_RATE_48000: if (sampleRate & A2DP_OPUS_SAMPLING_FREQ_48000) { @@ -775,9 +767,9 @@ static bool select_audio_sample_rate( // The result is stored in |p_result| and |p_codec_config|. // Returns true if a selection was made, otherwise false. // -static bool select_best_bits_per_sample( - btav_a2dp_codec_bits_per_sample_t bits_per_sample, tA2DP_OPUS_CIE* p_result, - btav_a2dp_codec_config_t* p_codec_config) { +static bool select_best_bits_per_sample(btav_a2dp_codec_bits_per_sample_t bits_per_sample, + tA2DP_OPUS_CIE* p_result, + btav_a2dp_codec_config_t* p_codec_config) { if (bits_per_sample & BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32) { p_codec_config->bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32; p_result->bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32; @@ -802,10 +794,10 @@ static bool select_best_bits_per_sample( // The result is stored in |p_result| and |p_codec_config|. // Returns true if a selection was made, otherwise false. // -static bool select_audio_bits_per_sample( - const btav_a2dp_codec_config_t* p_codec_audio_config, - btav_a2dp_codec_bits_per_sample_t bits_per_sample, tA2DP_OPUS_CIE* p_result, - btav_a2dp_codec_config_t* p_codec_config) { +static bool select_audio_bits_per_sample(const btav_a2dp_codec_config_t* p_codec_audio_config, + btav_a2dp_codec_bits_per_sample_t bits_per_sample, + tA2DP_OPUS_CIE* p_result, + btav_a2dp_codec_config_t* p_codec_config) { switch (p_codec_audio_config->bits_per_sample) { case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16: if (bits_per_sample & BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16) { @@ -839,8 +831,7 @@ static bool select_audio_bits_per_sample( // The result is stored in |p_result| and |p_codec_config|. // Returns true if a selection was made, otherwise false. // -static bool select_best_channel_mode(uint8_t channelMode, - tA2DP_OPUS_CIE* p_result, +static bool select_best_channel_mode(uint8_t channelMode, tA2DP_OPUS_CIE* p_result, btav_a2dp_codec_config_t* p_codec_config) { if (channelMode & A2DP_OPUS_CHANNEL_MODE_STEREO) { p_result->channelMode = A2DP_OPUS_CHANNEL_MODE_STEREO; @@ -861,9 +852,9 @@ static bool select_best_channel_mode(uint8_t channelMode, // The result is stored in |p_result| and |p_codec_config|. // Returns true if a selection was made, otherwise false. // -static bool select_audio_channel_mode( - const btav_a2dp_codec_config_t* p_codec_audio_config, uint8_t channelMode, - tA2DP_OPUS_CIE* p_result, btav_a2dp_codec_config_t* p_codec_config) { +static bool select_audio_channel_mode(const btav_a2dp_codec_config_t* p_codec_audio_config, + uint8_t channelMode, tA2DP_OPUS_CIE* p_result, + btav_a2dp_codec_config_t* p_codec_config) { switch (p_codec_audio_config->channel_mode) { case BTAV_A2DP_CODEC_CHANNEL_MODE_MONO: if (channelMode & A2DP_OPUS_CHANNEL_MODE_MONO) { @@ -886,8 +877,7 @@ static bool select_audio_channel_mode( return false; } -bool A2dpCodecConfigOpusBase::setCodecConfig(const uint8_t* p_peer_codec_info, - bool is_capability, +bool A2dpCodecConfigOpusBase::setCodecConfig(const uint8_t* p_peer_codec_info, bool is_capability, uint8_t* p_result_codec_config) { std::lock_guard lock(codec_mutex_); tA2DP_OPUS_CIE peer_info_cie; @@ -897,20 +887,18 @@ bool A2dpCodecConfigOpusBase::setCodecConfig(const uint8_t* p_peer_codec_info, uint8_t frameSize; btav_a2dp_codec_bits_per_sample_t bits_per_sample; const tA2DP_OPUS_CIE* p_a2dp_opus_caps = - (is_source_) ? &a2dp_opus_source_caps : &a2dp_opus_sink_caps; + (is_source_) ? &a2dp_opus_source_caps : &a2dp_opus_sink_caps; btav_a2dp_codec_config_t device_codec_config_ = getCodecConfig(); - log::info( - "AudioManager stream config {} sample rate {} bit depth {} channel mode", - device_codec_config_.sample_rate, device_codec_config_.bits_per_sample, - device_codec_config_.channel_mode); + log::info("AudioManager stream config {} sample rate {} bit depth {} channel mode", + device_codec_config_.sample_rate, device_codec_config_.bits_per_sample, + device_codec_config_.channel_mode); // Save the internal state btav_a2dp_codec_config_t saved_codec_config = codec_config_; btav_a2dp_codec_config_t saved_codec_capability = codec_capability_; - btav_a2dp_codec_config_t saved_codec_selectable_capability = - codec_selectable_capability_; + btav_a2dp_codec_config_t saved_codec_selectable_capability = codec_selectable_capability_; btav_a2dp_codec_config_t saved_codec_user_config = codec_user_config_; btav_a2dp_codec_config_t saved_codec_audio_config = codec_audio_config_; uint8_t saved_ota_codec_config[AVDT_CODEC_SIZE]; @@ -919,11 +907,9 @@ bool A2dpCodecConfigOpusBase::setCodecConfig(const uint8_t* p_peer_codec_info, memcpy(saved_ota_codec_config, ota_codec_config_, sizeof(ota_codec_config_)); memcpy(saved_ota_codec_peer_capability, ota_codec_peer_capability_, sizeof(ota_codec_peer_capability_)); - memcpy(saved_ota_codec_peer_config, ota_codec_peer_config_, - sizeof(ota_codec_peer_config_)); + memcpy(saved_ota_codec_peer_config, ota_codec_peer_config_, sizeof(ota_codec_peer_config_)); - tA2DP_STATUS status = - A2DP_ParseInfoOpus(&peer_info_cie, p_peer_codec_info, is_capability); + tA2DP_STATUS status = A2DP_ParseInfoOpus(&peer_info_cie, p_peer_codec_info, is_capability); if (status != A2DP_SUCCESS) { log::error("can't parse peer's capabilities: error = {}", status); goto fail; @@ -967,39 +953,38 @@ bool A2dpCodecConfigOpusBase::setCodecConfig(const uint8_t* p_peer_codec_info, do { // Compute the selectable capability if (sampleRate & A2DP_OPUS_SAMPLING_FREQ_48000) { - codec_selectable_capability_.sample_rate |= - BTAV_A2DP_CODEC_SAMPLE_RATE_48000; + codec_selectable_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_48000; } - if (codec_config_.sample_rate != BTAV_A2DP_CODEC_SAMPLE_RATE_NONE) break; + if (codec_config_.sample_rate != BTAV_A2DP_CODEC_SAMPLE_RATE_NONE) { + break; + } // Compute the common capability - if (sampleRate & A2DP_OPUS_SAMPLING_FREQ_48000) + if (sampleRate & A2DP_OPUS_SAMPLING_FREQ_48000) { codec_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_48000; + } // No user preference - try the codec audio config - if (select_audio_sample_rate(&codec_audio_config_, sampleRate, - &result_config_cie, &codec_config_)) { + if (select_audio_sample_rate(&codec_audio_config_, sampleRate, &result_config_cie, + &codec_config_)) { break; } // No user preference - try the default config - if (select_best_sample_rate( - a2dp_opus_default_config.sampleRate & peer_info_cie.sampleRate, - &result_config_cie, &codec_config_)) { + if (select_best_sample_rate(a2dp_opus_default_config.sampleRate & peer_info_cie.sampleRate, + &result_config_cie, &codec_config_)) { break; } // No user preference - use the best match - if (select_best_sample_rate(sampleRate, &result_config_cie, - &codec_config_)) { + if (select_best_sample_rate(sampleRate, &result_config_cie, &codec_config_)) { break; } } while (false); if (codec_config_.sample_rate == BTAV_A2DP_CODEC_SAMPLE_RATE_NONE) { - log::error( - "cannot match sample frequency: local caps = 0x{:x} peer info = 0x{:x}", - p_a2dp_opus_caps->sampleRate, peer_info_cie.sampleRate); + log::error("cannot match sample frequency: local caps = 0x{:x} peer info = 0x{:x}", + p_a2dp_opus_caps->sampleRate, peer_info_cie.sampleRate); goto fail; } @@ -1042,40 +1027,38 @@ bool A2dpCodecConfigOpusBase::setCodecConfig(const uint8_t* p_peer_codec_info, // Select the bits per sample if there is no user preference do { // Compute the selectable capability - codec_selectable_capability_.bits_per_sample = - p_a2dp_opus_caps->bits_per_sample; + codec_selectable_capability_.bits_per_sample = p_a2dp_opus_caps->bits_per_sample; - if (codec_config_.bits_per_sample != BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE) + if (codec_config_.bits_per_sample != BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE) { break; + } // Compute the common capability codec_capability_.bits_per_sample = bits_per_sample; // No user preference - try yhe codec audio config - if (select_audio_bits_per_sample(&codec_audio_config_, - p_a2dp_opus_caps->bits_per_sample, + if (select_audio_bits_per_sample(&codec_audio_config_, p_a2dp_opus_caps->bits_per_sample, &result_config_cie, &codec_config_)) { break; } // No user preference - try the default config - if (select_best_bits_per_sample(a2dp_opus_default_config.bits_per_sample, - &result_config_cie, &codec_config_)) { + if (select_best_bits_per_sample(a2dp_opus_default_config.bits_per_sample, &result_config_cie, + &codec_config_)) { break; } // No user preference - use the best match - if (select_best_bits_per_sample(p_a2dp_opus_caps->bits_per_sample, - &result_config_cie, &codec_config_)) { + if (select_best_bits_per_sample(p_a2dp_opus_caps->bits_per_sample, &result_config_cie, + &codec_config_)) { break; } } while (false); if (codec_config_.bits_per_sample == BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE) { log::error( - "cannot match bits per sample: default = 0x{:x} user preference = " - "0x{:x}", - a2dp_opus_default_config.bits_per_sample, - codec_user_config_.bits_per_sample); + "cannot match bits per sample: default = 0x{:x} user preference = " + "0x{:x}", + a2dp_opus_default_config.bits_per_sample, codec_user_config_.bits_per_sample); goto fail; } @@ -1109,46 +1092,44 @@ bool A2dpCodecConfigOpusBase::setCodecConfig(const uint8_t* p_peer_codec_info, do { // Compute the selectable capability if (channelMode & A2DP_OPUS_CHANNEL_MODE_MONO) { - codec_selectable_capability_.channel_mode |= - BTAV_A2DP_CODEC_CHANNEL_MODE_MONO; + codec_selectable_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_MONO; } if (channelMode & A2DP_OPUS_CHANNEL_MODE_STEREO) { - codec_selectable_capability_.channel_mode |= - BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; + codec_selectable_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; } - if (codec_config_.channel_mode != BTAV_A2DP_CODEC_CHANNEL_MODE_NONE) break; + if (codec_config_.channel_mode != BTAV_A2DP_CODEC_CHANNEL_MODE_NONE) { + break; + } // Compute the common capability - if (channelMode & A2DP_OPUS_CHANNEL_MODE_MONO) + if (channelMode & A2DP_OPUS_CHANNEL_MODE_MONO) { codec_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_MONO; + } if (channelMode & A2DP_OPUS_CHANNEL_MODE_STEREO) { codec_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; } // No user preference - try the codec audio config - if (select_audio_channel_mode(&codec_audio_config_, channelMode, - &result_config_cie, &codec_config_)) { + if (select_audio_channel_mode(&codec_audio_config_, channelMode, &result_config_cie, + &codec_config_)) { break; } // No user preference - try the default config - if (select_best_channel_mode( - a2dp_opus_default_config.channelMode & peer_info_cie.channelMode, - &result_config_cie, &codec_config_)) { + if (select_best_channel_mode(a2dp_opus_default_config.channelMode & peer_info_cie.channelMode, + &result_config_cie, &codec_config_)) { break; } // No user preference - use the best match - if (select_best_channel_mode(channelMode, &result_config_cie, - &codec_config_)) { + if (select_best_channel_mode(channelMode, &result_config_cie, &codec_config_)) { break; } } while (false); if (codec_config_.channel_mode == BTAV_A2DP_CODEC_CHANNEL_MODE_NONE) { - log::error( - "cannot match channel mode: local caps = 0x{:x} peer info = 0x{:x}", - p_a2dp_opus_caps->channelMode, peer_info_cie.channelMode); + log::error("cannot match channel mode: local caps = 0x{:x} peer info = 0x{:x}", + p_a2dp_opus_caps->channelMode, peer_info_cie.channelMode); goto fail; } @@ -1161,16 +1142,14 @@ bool A2dpCodecConfigOpusBase::setCodecConfig(const uint8_t* p_peer_codec_info, case BTAV_A2DP_CODEC_FRAME_SIZE_20MS: if (frameSize & A2DP_OPUS_20MS_FRAMESIZE) { result_config_cie.future1 = A2DP_OPUS_20MS_FRAMESIZE; - codec_capability_.codec_specific_1 = - codec_user_config_.codec_specific_1; + codec_capability_.codec_specific_1 = codec_user_config_.codec_specific_1; codec_config_.codec_specific_1 = codec_user_config_.codec_specific_1; } break; case BTAV_A2DP_CODEC_FRAME_SIZE_10MS: if (frameSize & A2DP_OPUS_10MS_FRAMESIZE) { result_config_cie.future1 = A2DP_OPUS_10MS_FRAMESIZE; - codec_capability_.codec_specific_1 = - codec_user_config_.codec_specific_1; + codec_capability_.codec_specific_1 = codec_user_config_.codec_specific_1; codec_config_.codec_specific_1 = codec_user_config_.codec_specific_1; } break; @@ -1186,14 +1165,13 @@ bool A2dpCodecConfigOpusBase::setCodecConfig(const uint8_t* p_peer_codec_info, result_config_cie.future3 = 0x00; if (codec_config_.codec_specific_1 == BTAV_A2DP_CODEC_FRAME_SIZE_NONE) { - log::error( - "cannot match frame size: local caps = 0x{:x} peer info = 0x{:x}", - p_a2dp_opus_caps->future1, peer_info_cie.future1); + log::error("cannot match frame size: local caps = 0x{:x} peer info = 0x{:x}", + p_a2dp_opus_caps->future1, peer_info_cie.future1); goto fail; } - if (A2DP_BuildInfoOpus(AVDT_MEDIA_TYPE_AUDIO, &result_config_cie, - p_result_codec_config) != A2DP_SUCCESS) { + if (A2DP_BuildInfoOpus(AVDT_MEDIA_TYPE_AUDIO, &result_config_cie, p_result_codec_config) != + A2DP_SUCCESS) { log::error("failed to BuildInfoOpus for result_config_cie"); goto fail; } @@ -1201,31 +1179,30 @@ bool A2dpCodecConfigOpusBase::setCodecConfig(const uint8_t* p_peer_codec_info, // // Copy the codec-specific fields if they are not zero // - if (codec_user_config_.codec_specific_1 != 0) + if (codec_user_config_.codec_specific_1 != 0) { codec_config_.codec_specific_1 = codec_user_config_.codec_specific_1; - if (codec_user_config_.codec_specific_2 != 0) + } + if (codec_user_config_.codec_specific_2 != 0) { codec_config_.codec_specific_2 = codec_user_config_.codec_specific_2; - if (codec_user_config_.codec_specific_3 != 0) + } + if (codec_user_config_.codec_specific_3 != 0) { codec_config_.codec_specific_3 = codec_user_config_.codec_specific_3; - if (codec_user_config_.codec_specific_4 != 0) + } + if (codec_user_config_.codec_specific_4 != 0) { codec_config_.codec_specific_4 = codec_user_config_.codec_specific_4; + } // Create a local copy of the peer codec capability, and the // result codec config. if (is_capability) { - status = A2DP_BuildInfoOpus(AVDT_MEDIA_TYPE_AUDIO, &peer_info_cie, - ota_codec_peer_capability_); + status = A2DP_BuildInfoOpus(AVDT_MEDIA_TYPE_AUDIO, &peer_info_cie, ota_codec_peer_capability_); } else { - status = A2DP_BuildInfoOpus(AVDT_MEDIA_TYPE_AUDIO, &peer_info_cie, - ota_codec_peer_config_); + status = A2DP_BuildInfoOpus(AVDT_MEDIA_TYPE_AUDIO, &peer_info_cie, ota_codec_peer_config_); } - log::assert_that(status == A2DP_SUCCESS, - "assert failed: status == A2DP_SUCCESS"); + log::assert_that(status == A2DP_SUCCESS, "assert failed: status == A2DP_SUCCESS"); - status = A2DP_BuildInfoOpus(AVDT_MEDIA_TYPE_AUDIO, &result_config_cie, - ota_codec_config_); - log::assert_that(status == A2DP_SUCCESS, - "assert failed: status == A2DP_SUCCESS"); + status = A2DP_BuildInfoOpus(AVDT_MEDIA_TYPE_AUDIO, &result_config_cie, ota_codec_config_); + log::assert_that(status == A2DP_SUCCESS, "assert failed: status == A2DP_SUCCESS"); return true; fail: @@ -1238,29 +1215,25 @@ fail: memcpy(ota_codec_config_, saved_ota_codec_config, sizeof(ota_codec_config_)); memcpy(ota_codec_peer_capability_, saved_ota_codec_peer_capability, sizeof(ota_codec_peer_capability_)); - memcpy(ota_codec_peer_config_, saved_ota_codec_peer_config, - sizeof(ota_codec_peer_config_)); + memcpy(ota_codec_peer_config_, saved_ota_codec_peer_config, sizeof(ota_codec_peer_config_)); return false; } -bool A2dpCodecConfigOpusBase::setPeerCodecCapabilities( - const uint8_t* p_peer_codec_capabilities) { +bool A2dpCodecConfigOpusBase::setPeerCodecCapabilities(const uint8_t* p_peer_codec_capabilities) { std::lock_guard lock(codec_mutex_); tA2DP_OPUS_CIE peer_info_cie; uint8_t channelMode; uint8_t sampleRate; const tA2DP_OPUS_CIE* p_a2dp_opus_caps = - (is_source_) ? &a2dp_opus_source_caps : &a2dp_opus_sink_caps; + (is_source_) ? &a2dp_opus_source_caps : &a2dp_opus_sink_caps; // Save the internal state - btav_a2dp_codec_config_t saved_codec_selectable_capability = - codec_selectable_capability_; + btav_a2dp_codec_config_t saved_codec_selectable_capability = codec_selectable_capability_; uint8_t saved_ota_codec_peer_capability[AVDT_CODEC_SIZE]; memcpy(saved_ota_codec_peer_capability, ota_codec_peer_capability_, sizeof(ota_codec_peer_capability_)); - tA2DP_STATUS status = - A2DP_ParseInfoOpus(&peer_info_cie, p_peer_codec_capabilities, true); + tA2DP_STATUS status = A2DP_ParseInfoOpus(&peer_info_cie, p_peer_codec_capabilities, true); if (status != A2DP_SUCCESS) { log::error("can't parse peer's capabilities: error = {}", status); goto fail; @@ -1269,30 +1242,24 @@ bool A2dpCodecConfigOpusBase::setPeerCodecCapabilities( // Compute the selectable capability - sample rate sampleRate = p_a2dp_opus_caps->sampleRate & peer_info_cie.sampleRate; if (sampleRate & A2DP_OPUS_SAMPLING_FREQ_48000) { - codec_selectable_capability_.sample_rate |= - BTAV_A2DP_CODEC_SAMPLE_RATE_48000; + codec_selectable_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_48000; } // Compute the selectable capability - bits per sample - codec_selectable_capability_.bits_per_sample = - p_a2dp_opus_caps->bits_per_sample; + codec_selectable_capability_.bits_per_sample = p_a2dp_opus_caps->bits_per_sample; // Compute the selectable capability - channel mode channelMode = p_a2dp_opus_caps->channelMode & peer_info_cie.channelMode; if (channelMode & A2DP_OPUS_CHANNEL_MODE_MONO) { - codec_selectable_capability_.channel_mode |= - BTAV_A2DP_CODEC_CHANNEL_MODE_MONO; + codec_selectable_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_MONO; } if (channelMode & A2DP_OPUS_CHANNEL_MODE_STEREO) { - codec_selectable_capability_.channel_mode |= - BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; + codec_selectable_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; } log::info("BuildInfoOpus for peer info cie for ota caps"); - status = A2DP_BuildInfoOpus(AVDT_MEDIA_TYPE_AUDIO, &peer_info_cie, - ota_codec_peer_capability_); - log::assert_that(status == A2DP_SUCCESS, - "assert failed: status == A2DP_SUCCESS"); + status = A2DP_BuildInfoOpus(AVDT_MEDIA_TYPE_AUDIO, &peer_info_cie, ota_codec_peer_capability_); + log::assert_that(status == A2DP_SUCCESS, "assert failed: status == A2DP_SUCCESS"); return true; fail: @@ -1303,16 +1270,16 @@ fail: return false; } -A2dpCodecConfigOpusSink::A2dpCodecConfigOpusSink( - btav_a2dp_codec_priority_t codec_priority) - : A2dpCodecConfigOpusBase(BTAV_A2DP_CODEC_INDEX_SINK_OPUS, - A2DP_VendorCodecIndexStrOpusSink(), +A2dpCodecConfigOpusSink::A2dpCodecConfigOpusSink(btav_a2dp_codec_priority_t codec_priority) + : A2dpCodecConfigOpusBase(BTAV_A2DP_CODEC_INDEX_SINK_OPUS, A2DP_VendorCodecIndexStrOpusSink(), codec_priority, false) {} A2dpCodecConfigOpusSink::~A2dpCodecConfigOpusSink() {} bool A2dpCodecConfigOpusSink::init() { - if (!isValid()) return false; + if (!isValid()) { + return false; + } return true; } @@ -1320,8 +1287,7 @@ bool A2dpCodecConfigOpusSink::init() { bool A2dpCodecConfigOpusSink::useRtpHeaderMarkerBit() const { return false; } bool A2dpCodecConfigOpusSink::updateEncoderUserConfig( - const tA2DP_ENCODER_INIT_PEER_PARAMS* /* p_peer_params */, - bool* /* p_restart_input */, bool* /* p_restart_output */, - bool* /* p_config_updated */) { + const tA2DP_ENCODER_INIT_PEER_PARAMS* /* p_peer_params */, bool* /* p_restart_input */, + bool* /* p_restart_output */, bool* /* p_config_updated */) { return false; } diff --git a/system/stack/a2dp/a2dp_vendor_opus_decoder.cc b/system/stack/a2dp/a2dp_vendor_opus_decoder.cc index 1dc3fd11b43..479e0fffeab 100644 --- a/system/stack/a2dp/a2dp_vendor_opus_decoder.cc +++ b/system/stack/a2dp/a2dp_vendor_opus_decoder.cc @@ -41,8 +41,7 @@ void a2dp_vendor_opus_decoder_cleanup(void) { osi_free(a2dp_opus_decoder_cb.opus_handle); if (a2dp_opus_decoder_cb.decode_buf != nullptr) { - memset(a2dp_opus_decoder_cb.decode_buf, 0, - A2DP_OPUS_DECODE_BUFFER_LENGTH); + memset(a2dp_opus_decoder_cb.decode_buf, 0, A2DP_OPUS_DECODE_BUFFER_LENGTH); osi_free(a2dp_opus_decoder_cb.decode_buf); a2dp_opus_decoder_cb.decode_buf = nullptr; } @@ -59,20 +58,18 @@ bool a2dp_vendor_opus_decoder_init(decoded_data_callback_t decode_callback) { int32_t size = 0; size = opus_decoder_get_size(A2DP_OPUS_CODEC_OUTPUT_CHS); - a2dp_opus_decoder_cb.opus_handle = - static_cast(osi_malloc(size)); + a2dp_opus_decoder_cb.opus_handle = static_cast(osi_malloc(size)); if (a2dp_opus_decoder_cb.opus_handle == nullptr) { log::error("failed to allocate opus decoder handle"); return false; } - err_val = opus_decoder_init(a2dp_opus_decoder_cb.opus_handle, - A2DP_OPUS_CODEC_DEFAULT_SAMPLERATE, + err_val = opus_decoder_init(a2dp_opus_decoder_cb.opus_handle, A2DP_OPUS_CODEC_DEFAULT_SAMPLERATE, A2DP_OPUS_CODEC_OUTPUT_CHS); if (err_val == OPUS_OK) { a2dp_opus_decoder_cb.has_opus_handle = true; a2dp_opus_decoder_cb.decode_buf = - static_cast(osi_malloc(A2DP_OPUS_DECODE_BUFFER_LENGTH)); + static_cast(osi_malloc(A2DP_OPUS_DECODE_BUFFER_LENGTH)); memset(a2dp_opus_decoder_cb.decode_buf, 0, A2DP_OPUS_DECODE_BUFFER_LENGTH); @@ -107,50 +104,43 @@ bool a2dp_vendor_opus_decoder_decode_packet(BT_HDR* p_buf) { return false; } - auto* pBuffer = - reinterpret_cast(p_buf->data + p_buf->offset + 1); + auto* pBuffer = reinterpret_cast(p_buf->data + p_buf->offset + 1); int32_t bufferSize = p_buf->len - 1; numChannels = opus_packet_get_nb_channels(pBuffer); numFrames = opus_packet_get_nb_frames(pBuffer, bufferSize); - frameSize = opus_packet_get_samples_per_frame( - pBuffer, A2DP_OPUS_CODEC_DEFAULT_SAMPLERATE); - frameLen = opus_packet_get_nb_samples(pBuffer, bufferSize, - A2DP_OPUS_CODEC_DEFAULT_SAMPLERATE); + frameSize = opus_packet_get_samples_per_frame(pBuffer, A2DP_OPUS_CODEC_DEFAULT_SAMPLERATE); + frameLen = opus_packet_get_nb_samples(pBuffer, bufferSize, A2DP_OPUS_CODEC_DEFAULT_SAMPLERATE); uint32_t num_frames = pBuffer[0] & 0xf; - log::error("numframes {} framesize {} framelen {} bufferSize {}", num_frames, - frameSize, frameLen, bufferSize); - log::error("numChannels {} numFrames {} offset {}", numChannels, numFrames, - p_buf->offset); + log::error("numframes {} framesize {} framelen {} bufferSize {}", num_frames, frameSize, frameLen, + bufferSize); + log::error("numChannels {} numFrames {} offset {}", numChannels, numFrames, p_buf->offset); for (uint32_t frame = 0; frame < numFrames; ++frame) { { numChannels = opus_packet_get_nb_channels(pBuffer); ret_val = opus_decode(a2dp_opus_decoder_cb.opus_handle, - reinterpret_cast(pBuffer), - bufferSize, a2dp_opus_decoder_cb.decode_buf, - A2DP_OPUS_DECODE_BUFFER_LENGTH, 0 /* flags */); + reinterpret_cast(pBuffer), bufferSize, + a2dp_opus_decoder_cb.decode_buf, A2DP_OPUS_DECODE_BUFFER_LENGTH, + 0 /* flags */); if (ret_val < OPUS_OK) { log::error("Opus DecodeFrame failed {}, applying concealment", ret_val); ret_val = opus_decode(a2dp_opus_decoder_cb.opus_handle, NULL, 0, - a2dp_opus_decoder_cb.decode_buf, - A2DP_OPUS_DECODE_BUFFER_LENGTH, 0 /* flags */); + a2dp_opus_decoder_cb.decode_buf, A2DP_OPUS_DECODE_BUFFER_LENGTH, + 0 /* flags */); } if (ret_val < OPUS_OK) { - log::error("Opus DecodeFrame retry failed with {}, dropping packet", - ret_val); + log::error("Opus DecodeFrame retry failed with {}, dropping packet", ret_val); return false; } - size_t frame_len = - ret_val * numChannels * sizeof(a2dp_opus_decoder_cb.decode_buf[0]); + size_t frame_len = ret_val * numChannels * sizeof(a2dp_opus_decoder_cb.decode_buf[0]); a2dp_opus_decoder_cb.decode_callback( - reinterpret_cast(a2dp_opus_decoder_cb.decode_buf), - frame_len); + reinterpret_cast(a2dp_opus_decoder_cb.decode_buf), frame_len); } } return true; @@ -162,8 +152,7 @@ void a2dp_vendor_opus_decoder_suspend(void) { int32_t err_val = 0; if (a2dp_opus_decoder_cb.has_opus_handle) { - err_val = - opus_decoder_ctl(a2dp_opus_decoder_cb.opus_handle, OPUS_RESET_STATE); + err_val = opus_decoder_ctl(a2dp_opus_decoder_cb.opus_handle, OPUS_RESET_STATE); if (err_val != OPUS_OK) { log::error("failed to reset decoder"); } diff --git a/system/stack/a2dp/a2dp_vendor_opus_encoder.cc b/system/stack/a2dp/a2dp_vendor_opus_encoder.cc index fd7419ed8e8..e04d92750ea 100644 --- a/system/stack/a2dp/a2dp_vendor_opus_encoder.cc +++ b/system/stack/a2dp/a2dp_vendor_opus_encoder.cc @@ -86,13 +86,10 @@ typedef struct { static tA2DP_OPUS_ENCODER_CB a2dp_opus_encoder_cb; -static bool a2dp_vendor_opus_encoder_update(uint16_t peer_mtu, - A2dpCodecConfig* a2dp_codec_config, - bool* p_restart_input, - bool* p_restart_output, +static bool a2dp_vendor_opus_encoder_update(uint16_t peer_mtu, A2dpCodecConfig* a2dp_codec_config, + bool* p_restart_input, bool* p_restart_output, bool* p_config_updated); -static void a2dp_opus_get_num_frame_iteration(uint8_t* num_of_iterations, - uint8_t* num_of_frames, +static void a2dp_opus_get_num_frame_iteration(uint8_t* num_of_iterations, uint8_t* num_of_frames, uint64_t timestamp_us); static void a2dp_opus_encode_frames(uint8_t nb_frame); static bool a2dp_opus_read_feeding(uint8_t* read_buffer, uint32_t* bytes_read); @@ -105,8 +102,7 @@ void a2dp_vendor_opus_encoder_cleanup(void) { } memset(&a2dp_opus_encoder_cb, 0, sizeof(a2dp_opus_encoder_cb)); - a2dp_opus_encoder_cb.stats.session_start_us = - bluetooth::common::time_get_os_boottime_us(); + a2dp_opus_encoder_cb.stats.session_start_us = bluetooth::common::time_get_os_boottime_us(); a2dp_opus_encoder_cb.timestamp = 0; a2dp_opus_encoder_cb.use_SCMS_T = false; @@ -114,11 +110,10 @@ void a2dp_vendor_opus_encoder_cleanup(void) { return; } -void a2dp_vendor_opus_encoder_init( - const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params, - A2dpCodecConfig* a2dp_codec_config, - a2dp_source_read_callback_t read_callback, - a2dp_source_enqueue_callback_t enqueue_callback) { +void a2dp_vendor_opus_encoder_init(const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params, + A2dpCodecConfig* a2dp_codec_config, + a2dp_source_read_callback_t read_callback, + a2dp_source_enqueue_callback_t enqueue_callback) { uint32_t error_val; a2dp_vendor_opus_encoder_cleanup(); @@ -136,57 +131,49 @@ void a2dp_vendor_opus_encoder_init( bool config_updated = false; uint32_t size = opus_encoder_get_size(A2DP_OPUS_CODEC_OUTPUT_CHS); - a2dp_opus_encoder_cb.opus_handle = - static_cast(osi_malloc(size)); + a2dp_opus_encoder_cb.opus_handle = static_cast(osi_malloc(size)); if (a2dp_opus_encoder_cb.opus_handle == nullptr) { log::error("failed to allocate opus encoder handle"); return; } - error_val = opus_encoder_init( - a2dp_opus_encoder_cb.opus_handle, A2DP_OPUS_CODEC_DEFAULT_SAMPLERATE, - A2DP_OPUS_CODEC_OUTPUT_CHS, OPUS_APPLICATION_AUDIO); + error_val = + opus_encoder_init(a2dp_opus_encoder_cb.opus_handle, A2DP_OPUS_CODEC_DEFAULT_SAMPLERATE, + A2DP_OPUS_CODEC_OUTPUT_CHS, OPUS_APPLICATION_AUDIO); if (error_val != OPUS_OK) { log::error( - "failed to init opus encoder (handle size {}, sampling rate {}, output " - "chs {}, error {})", - size, A2DP_OPUS_CODEC_DEFAULT_SAMPLERATE, A2DP_OPUS_CODEC_OUTPUT_CHS, - error_val); + "failed to init opus encoder (handle size {}, sampling rate {}, output " + "chs {}, error {})", + size, A2DP_OPUS_CODEC_DEFAULT_SAMPLERATE, A2DP_OPUS_CODEC_OUTPUT_CHS, error_val); osi_free(a2dp_opus_encoder_cb.opus_handle); return; } else { a2dp_opus_encoder_cb.has_opus_handle = true; } - a2dp_vendor_opus_encoder_update(a2dp_opus_encoder_cb.peer_mtu, - a2dp_codec_config, &restart_input, + a2dp_vendor_opus_encoder_update(a2dp_opus_encoder_cb.peer_mtu, a2dp_codec_config, &restart_input, &restart_output, &config_updated); return; } bool A2dpCodecConfigOpusSource::updateEncoderUserConfig( - const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params, bool* p_restart_input, - bool* p_restart_output, bool* p_config_updated) { + const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params, bool* p_restart_input, + bool* p_restart_output, bool* p_config_updated) { if (a2dp_opus_encoder_cb.peer_mtu == 0) { - log::error("Cannot update the codec encoder for {}: invalid peer MTU", - name()); + log::error("Cannot update the codec encoder for {}: invalid peer MTU", name()); return false; } - return a2dp_vendor_opus_encoder_update(a2dp_opus_encoder_cb.peer_mtu, this, - p_restart_input, p_restart_output, - p_config_updated); + return a2dp_vendor_opus_encoder_update(a2dp_opus_encoder_cb.peer_mtu, this, p_restart_input, + p_restart_output, p_config_updated); } -static bool a2dp_vendor_opus_encoder_update(uint16_t peer_mtu, - A2dpCodecConfig* a2dp_codec_config, - bool* p_restart_input, - bool* p_restart_output, +static bool a2dp_vendor_opus_encoder_update(uint16_t peer_mtu, A2dpCodecConfig* a2dp_codec_config, + bool* p_restart_input, bool* p_restart_output, bool* p_config_updated) { - tA2DP_OPUS_ENCODER_PARAMS* p_encoder_params = - &a2dp_opus_encoder_cb.opus_encoder_params; + tA2DP_OPUS_ENCODER_PARAMS* p_encoder_params = &a2dp_opus_encoder_cb.opus_encoder_params; uint8_t codec_info[AVDT_CODEC_SIZE]; uint32_t error = 0; @@ -194,14 +181,12 @@ static bool a2dp_vendor_opus_encoder_update(uint16_t peer_mtu, *p_restart_output = false; *p_config_updated = false; - if (!a2dp_opus_encoder_cb.has_opus_handle || - a2dp_opus_encoder_cb.opus_handle == NULL) { + if (!a2dp_opus_encoder_cb.has_opus_handle || a2dp_opus_encoder_cb.opus_handle == NULL) { log::error("Cannot get Opus encoder handle"); return false; } - log::assert_that( - a2dp_opus_encoder_cb.opus_handle != nullptr, - "assert failed: a2dp_opus_encoder_cb.opus_handle != nullptr"); + log::assert_that(a2dp_opus_encoder_cb.opus_handle != nullptr, + "assert failed: a2dp_opus_encoder_cb.opus_handle != nullptr"); if (!a2dp_codec_config->copyOutOtaCodecConfig(codec_info)) { log::error("Cannot update the codec encoder for {}: invalid codec config", @@ -213,28 +198,21 @@ static bool a2dp_vendor_opus_encoder_update(uint16_t peer_mtu, // The feeding parameters tA2DP_FEEDING_PARAMS* p_feeding_params = &a2dp_opus_encoder_cb.feeding_params; - p_feeding_params->sample_rate = - A2DP_VendorGetTrackSampleRateOpus(p_codec_info); - p_feeding_params->bits_per_sample = - a2dp_codec_config->getAudioBitsPerSample(); - p_feeding_params->channel_count = - A2DP_VendorGetTrackChannelCountOpus(p_codec_info); - log::info("sample_rate={} bits_per_sample={} channel_count={}", - p_feeding_params->sample_rate, p_feeding_params->bits_per_sample, - p_feeding_params->channel_count); + p_feeding_params->sample_rate = A2DP_VendorGetTrackSampleRateOpus(p_codec_info); + p_feeding_params->bits_per_sample = a2dp_codec_config->getAudioBitsPerSample(); + p_feeding_params->channel_count = A2DP_VendorGetTrackChannelCountOpus(p_codec_info); + log::info("sample_rate={} bits_per_sample={} channel_count={}", p_feeding_params->sample_rate, + p_feeding_params->bits_per_sample, p_feeding_params->channel_count); // The codec parameters - p_encoder_params->sample_rate = - a2dp_opus_encoder_cb.feeding_params.sample_rate; - p_encoder_params->channel_mode = - A2DP_VendorGetChannelModeCodeOpus(p_codec_info); + p_encoder_params->sample_rate = a2dp_opus_encoder_cb.feeding_params.sample_rate; + p_encoder_params->channel_mode = A2DP_VendorGetChannelModeCodeOpus(p_codec_info); p_encoder_params->framesize = A2DP_VendorGetFrameSizeOpus(p_codec_info); p_encoder_params->bitrate = A2DP_VendorGetBitRateOpus(p_codec_info); a2dp_vendor_opus_feeding_reset(); - uint16_t mtu_size = - BT_DEFAULT_BUFFER_SIZE - A2DP_OPUS_OFFSET - sizeof(BT_HDR); + uint16_t mtu_size = BT_DEFAULT_BUFFER_SIZE - A2DP_OPUS_OFFSET - sizeof(BT_HDR); if (mtu_size < peer_mtu) { a2dp_opus_encoder_cb.TxAaMtuSize = mtu_size; } else { @@ -244,25 +222,21 @@ static bool a2dp_vendor_opus_encoder_update(uint16_t peer_mtu, // Set the bitrate quality mode index if (codec_config.codec_specific_3 != 0) { p_encoder_params->quality_mode_index = codec_config.codec_specific_3 % 10; - log::info("setting bitrate quality mode to {}", - p_encoder_params->quality_mode_index); + log::info("setting bitrate quality mode to {}", p_encoder_params->quality_mode_index); } else { p_encoder_params->quality_mode_index = 5; - log::info("setting bitrate quality mode to default {}", - p_encoder_params->quality_mode_index); + log::info("setting bitrate quality mode to default {}", p_encoder_params->quality_mode_index); } - error = opus_encoder_ctl( - a2dp_opus_encoder_cb.opus_handle, - OPUS_SET_COMPLEXITY(p_encoder_params->quality_mode_index)); + error = opus_encoder_ctl(a2dp_opus_encoder_cb.opus_handle, + OPUS_SET_COMPLEXITY(p_encoder_params->quality_mode_index)); if (error != OPUS_OK) { log::error("failed to set encoder bitrate quality setting"); return false; } - p_encoder_params->pcm_wlength = - a2dp_opus_encoder_cb.feeding_params.bits_per_sample >> 3; + p_encoder_params->pcm_wlength = a2dp_opus_encoder_cb.feeding_params.bits_per_sample >> 3; log::info("setting bitrate to {}", p_encoder_params->bitrate); error = opus_encoder_ctl(a2dp_opus_encoder_cb.opus_handle, @@ -274,12 +248,13 @@ static bool a2dp_vendor_opus_encoder_update(uint16_t peer_mtu, } // Set the Audio format from pcm_wlength - if (p_encoder_params->pcm_wlength == 2) + if (p_encoder_params->pcm_wlength == 2) { p_encoder_params->pcm_fmt = 16; - else if (p_encoder_params->pcm_wlength == 3) + } else if (p_encoder_params->pcm_wlength == 3) { p_encoder_params->pcm_fmt = 24; - else if (p_encoder_params->pcm_wlength == 4) + } else if (p_encoder_params->pcm_wlength == 4) { p_encoder_params->pcm_fmt = 32; + } return true; } @@ -289,11 +264,11 @@ void a2dp_vendor_opus_feeding_reset(void) { sizeof(a2dp_opus_encoder_cb.opus_feeding_state)); a2dp_opus_encoder_cb.opus_feeding_state.bytes_per_tick = - (a2dp_opus_encoder_cb.feeding_params.sample_rate * - a2dp_opus_encoder_cb.feeding_params.bits_per_sample / 8 * - a2dp_opus_encoder_cb.feeding_params.channel_count * - a2dp_vendor_opus_get_encoder_interval_ms()) / - 1000; + (a2dp_opus_encoder_cb.feeding_params.sample_rate * + a2dp_opus_encoder_cb.feeding_params.bits_per_sample / 8 * + a2dp_opus_encoder_cb.feeding_params.channel_count * + a2dp_vendor_opus_get_encoder_interval_ms()) / + 1000; return; } @@ -305,8 +280,8 @@ void a2dp_vendor_opus_feeding_flush(void) { } uint64_t a2dp_vendor_opus_get_encoder_interval_ms(void) { - return ((a2dp_opus_encoder_cb.opus_encoder_params.framesize * 1000) / - a2dp_opus_encoder_cb.opus_encoder_params.sample_rate); + return (a2dp_opus_encoder_cb.opus_encoder_params.framesize * 1000) / + a2dp_opus_encoder_cb.opus_encoder_params.sample_rate; } void a2dp_vendor_opus_send_frames(uint64_t timestamp_us) { @@ -314,7 +289,9 @@ void a2dp_vendor_opus_send_frames(uint64_t timestamp_us) { uint8_t nb_iterations = 0; a2dp_opus_get_num_frame_iteration(&nb_iterations, &nb_frame, timestamp_us); - if (nb_frame == 0) return; + if (nb_frame == 0) { + return; + } for (uint8_t counter = 0; counter < nb_iterations; counter++) { // Transcode frame and enqueue @@ -327,33 +304,29 @@ void a2dp_vendor_opus_send_frames(uint64_t timestamp_us) { // Obtains the number of frames to send and number of iterations // to be used. |num_of_iterations| and |num_of_frames| parameters // are used as output param for returning the respective values. -static void a2dp_opus_get_num_frame_iteration(uint8_t* num_of_iterations, - uint8_t* num_of_frames, +static void a2dp_opus_get_num_frame_iteration(uint8_t* num_of_iterations, uint8_t* num_of_frames, uint64_t timestamp_us) { uint32_t result = 0; uint8_t nof = 0; uint8_t noi = 1; - uint32_t pcm_bytes_per_frame = - a2dp_opus_encoder_cb.opus_encoder_params.framesize * - a2dp_opus_encoder_cb.feeding_params.channel_count * - a2dp_opus_encoder_cb.feeding_params.bits_per_sample / 8; + uint32_t pcm_bytes_per_frame = a2dp_opus_encoder_cb.opus_encoder_params.framesize * + a2dp_opus_encoder_cb.feeding_params.channel_count * + a2dp_opus_encoder_cb.feeding_params.bits_per_sample / 8; uint32_t us_this_tick = a2dp_vendor_opus_get_encoder_interval_ms() * 1000; uint64_t now_us = timestamp_us; - if (a2dp_opus_encoder_cb.opus_feeding_state.last_frame_us != 0) - us_this_tick = - (now_us - a2dp_opus_encoder_cb.opus_feeding_state.last_frame_us); + if (a2dp_opus_encoder_cb.opus_feeding_state.last_frame_us != 0) { + us_this_tick = (now_us - a2dp_opus_encoder_cb.opus_feeding_state.last_frame_us); + } a2dp_opus_encoder_cb.opus_feeding_state.last_frame_us = now_us; a2dp_opus_encoder_cb.opus_feeding_state.counter += - (float)a2dp_opus_encoder_cb.opus_feeding_state.bytes_per_tick * - us_this_tick / (a2dp_vendor_opus_get_encoder_interval_ms() * 1000); + (float)a2dp_opus_encoder_cb.opus_feeding_state.bytes_per_tick * us_this_tick / + (a2dp_vendor_opus_get_encoder_interval_ms() * 1000); - result = - a2dp_opus_encoder_cb.opus_feeding_state.counter / pcm_bytes_per_frame; - a2dp_opus_encoder_cb.opus_feeding_state.counter -= - result * pcm_bytes_per_frame; + result = a2dp_opus_encoder_cb.opus_feeding_state.counter / pcm_bytes_per_frame; + a2dp_opus_encoder_cb.opus_feeding_state.counter -= result * pcm_bytes_per_frame; nof = result; *num_of_frames = nof; @@ -361,13 +334,11 @@ static void a2dp_opus_get_num_frame_iteration(uint8_t* num_of_iterations, } static void a2dp_opus_encode_frames(uint8_t nb_frame) { - tA2DP_OPUS_ENCODER_PARAMS* p_encoder_params = - &a2dp_opus_encoder_cb.opus_encoder_params; + tA2DP_OPUS_ENCODER_PARAMS* p_encoder_params = &a2dp_opus_encoder_cb.opus_encoder_params; unsigned char* packet; uint8_t remain_nb_frame = nb_frame; uint16_t opus_frame_size = p_encoder_params->framesize; - uint8_t read_buffer[p_encoder_params->framesize * - p_encoder_params->pcm_wlength * + uint8_t read_buffer[p_encoder_params->framesize * p_encoder_params->pcm_wlength * p_encoder_params->channel_mode]; int32_t out_frames = 0; @@ -397,10 +368,8 @@ static void a2dp_opus_encode_frames(uint8_t nb_frame) { return; } - written = - opus_encode(a2dp_opus_encoder_cb.opus_handle, - (const opus_int16*)&read_buffer[0], opus_frame_size, - packet, (BT_DEFAULT_BUFFER_SIZE - p_buf->offset)); + written = opus_encode(a2dp_opus_encoder_cb.opus_handle, (const opus_int16*)&read_buffer[0], + opus_frame_size, packet, (BT_DEFAULT_BUFFER_SIZE - p_buf->offset)); if (written <= 0) { log::error("OPUS encoding error"); @@ -416,9 +385,8 @@ static void a2dp_opus_encode_frames(uint8_t nb_frame) { } else { log::warn("Opus src buffer underflow {}", nb_frame); a2dp_opus_encoder_cb.opus_feeding_state.counter += - nb_frame * opus_frame_size * - a2dp_opus_encoder_cb.feeding_params.channel_count * - a2dp_opus_encoder_cb.feeding_params.bits_per_sample / 8; + nb_frame * opus_frame_size * a2dp_opus_encoder_cb.feeding_params.channel_count * + a2dp_opus_encoder_cb.feeding_params.bits_per_sample / 8; // no more pcm to read nb_frame = 0; @@ -435,16 +403,16 @@ static void a2dp_opus_encode_frames(uint8_t nb_frame) { // Timestamp will wrap over to 0 if stream continues on long enough // (>25H @ 48KHz). The parameters are promoted to 64bit to ensure that // no unsigned overflow is triggered as ubsan is always enabled. - a2dp_opus_encoder_cb.timestamp = - ((uint64_t)a2dp_opus_encoder_cb.timestamp + - (p_buf->layer_specific * opus_frame_size)) & UINT32_MAX; + a2dp_opus_encoder_cb.timestamp = ((uint64_t)a2dp_opus_encoder_cb.timestamp + + (p_buf->layer_specific * opus_frame_size)) & + UINT32_MAX; uint8_t done_nb_frame = remain_nb_frame - nb_frame; remain_nb_frame = nb_frame; - if (!a2dp_opus_encoder_cb.enqueue_callback(p_buf, done_nb_frame, - bytes_read)) + if (!a2dp_opus_encoder_cb.enqueue_callback(p_buf, done_nb_frame, bytes_read)) { return; + } } else { a2dp_opus_encoder_cb.stats.media_read_total_dropped_packets++; osi_free(p_buf); @@ -461,12 +429,13 @@ static bool a2dp_opus_read_feeding(uint8_t* read_buffer, uint32_t* bytes_read) { a2dp_opus_encoder_cb.stats.media_read_total_expected_read_bytes += read_size; /* Read Data from UIPC channel */ - uint32_t nb_byte_read = - a2dp_opus_encoder_cb.read_callback(read_buffer, read_size); + uint32_t nb_byte_read = a2dp_opus_encoder_cb.read_callback(read_buffer, read_size); a2dp_opus_encoder_cb.stats.media_read_total_actual_read_bytes += nb_byte_read; if (nb_byte_read < read_size) { - if (nb_byte_read == 0) return false; + if (nb_byte_read == 0) { + return false; + } /* Fill the unfilled part of the read buffer with silence (0) */ memset(((uint8_t*)read_buffer) + nb_byte_read, 0, read_size - nb_byte_read); @@ -488,41 +457,33 @@ uint64_t A2dpCodecConfigOpusSource::encoderIntervalMs() const { return a2dp_vendor_opus_get_encoder_interval_ms(); } -int a2dp_vendor_opus_get_effective_frame_size() { - return a2dp_opus_encoder_cb.TxAaMtuSize; -} +int a2dp_vendor_opus_get_effective_frame_size() { return a2dp_opus_encoder_cb.TxAaMtuSize; } void A2dpCodecConfigOpusSource::debug_codec_dump(int fd) { a2dp_opus_encoder_stats_t* stats = &a2dp_opus_encoder_cb.stats; - tA2DP_OPUS_ENCODER_PARAMS* p_encoder_params = - &a2dp_opus_encoder_cb.opus_encoder_params; + tA2DP_OPUS_ENCODER_PARAMS* p_encoder_params = &a2dp_opus_encoder_cb.opus_encoder_params; A2dpCodecConfig::debug_codec_dump(fd); dprintf(fd, " Packet counts (expected/dropped) : %zu / " "%zu\n", - stats->media_read_total_expected_packets, - stats->media_read_total_dropped_packets); + stats->media_read_total_expected_packets, stats->media_read_total_dropped_packets); dprintf(fd, " PCM read counts (expected/actual) : %zu / " "%zu\n", - stats->media_read_total_expected_reads_count, - stats->media_read_total_actual_reads_count); + stats->media_read_total_expected_reads_count, stats->media_read_total_actual_reads_count); dprintf(fd, " PCM read bytes (expected/actual) : %zu / " "%zu\n", - stats->media_read_total_expected_read_bytes, - stats->media_read_total_actual_read_bytes); + stats->media_read_total_expected_read_bytes, stats->media_read_total_actual_read_bytes); - dprintf(fd, - " OPUS transmission bitrate (Kbps) : %d\n", + dprintf(fd, " OPUS transmission bitrate (Kbps) : %d\n", p_encoder_params->bitrate); - dprintf(fd, - " OPUS saved transmit queue length : %zu\n", + dprintf(fd, " OPUS saved transmit queue length : %zu\n", a2dp_opus_encoder_cb.TxQueueLength); return; diff --git a/system/stack/a2dp/a2dp_vendor_opus_linux.cc b/system/stack/a2dp/a2dp_vendor_opus_linux.cc index 15a3a123cb5..2ebbc12648c 100644 --- a/system/stack/a2dp/a2dp_vendor_opus_linux.cc +++ b/system/stack/a2dp/a2dp_vendor_opus_linux.cc @@ -19,74 +19,46 @@ #include "a2dp_vendor.h" #include "a2dp_vendor_opus.h" -bool A2DP_IsVendorSourceCodecValidOpus(const uint8_t* p_codec_info) { - return false; -} +bool A2DP_IsVendorSourceCodecValidOpus(const uint8_t* p_codec_info) { return false; } -bool A2DP_IsVendorSinkCodecValidOpus(const uint8_t* p_codec_info) { - return false; -} +bool A2DP_IsVendorSinkCodecValidOpus(const uint8_t* p_codec_info) { return false; } -bool A2DP_IsVendorPeerSourceCodecValidOpus(const uint8_t* p_codec_info) { - return false; -} +bool A2DP_IsVendorPeerSourceCodecValidOpus(const uint8_t* p_codec_info) { return false; } -bool A2DP_IsVendorPeerSinkCodecValidOpus(const uint8_t* p_codec_info) { - return false; -} +bool A2DP_IsVendorPeerSinkCodecValidOpus(const uint8_t* p_codec_info) { return false; } -bool A2DP_IsVendorSinkCodecSupportedOpus(const uint8_t* p_codec_info) { - return false; -} -bool A2DP_IsPeerSourceCodecSupportedOpus(const uint8_t* p_codec_info) { - return false; -} +bool A2DP_IsVendorSinkCodecSupportedOpus(const uint8_t* p_codec_info) { return false; } +bool A2DP_IsPeerSourceCodecSupportedOpus(const uint8_t* p_codec_info) { return false; } -bool A2DP_VendorUsesRtpHeaderOpus(bool content_protection_enabled, - const uint8_t* p_codec_info) { +bool A2DP_VendorUsesRtpHeaderOpus(bool content_protection_enabled, const uint8_t* p_codec_info) { return false; } -const char* A2DP_VendorCodecNameOpus(const uint8_t* p_codec_info) { - return "Opus"; -} +const char* A2DP_VendorCodecNameOpus(const uint8_t* p_codec_info) { return "Opus"; } -bool A2DP_VendorCodecTypeEqualsOpus(const uint8_t* p_codec_info_a, - const uint8_t* p_codec_info_b) { +bool A2DP_VendorCodecTypeEqualsOpus(const uint8_t* p_codec_info_a, const uint8_t* p_codec_info_b) { return false; } -bool A2DP_VendorCodecEqualsOpus(const uint8_t* p_codec_info_a, - const uint8_t* p_codec_info_b) { +bool A2DP_VendorCodecEqualsOpus(const uint8_t* p_codec_info_a, const uint8_t* p_codec_info_b) { return false; } int A2DP_VendorGetBitRateOpus(const uint8_t* p_codec_info) { return -1; } -int A2DP_VendorGetTrackSampleRateOpus(const uint8_t* p_codec_info) { - return -1; -} +int A2DP_VendorGetTrackSampleRateOpus(const uint8_t* p_codec_info) { return -1; } -int A2DP_VendorGetTrackBitsPerSampleOpus(const uint8_t* p_codec_info) { - return -1; -} +int A2DP_VendorGetTrackBitsPerSampleOpus(const uint8_t* p_codec_info) { return -1; } -int A2DP_VendorGetTrackChannelCountOpus(const uint8_t* p_codec_info) { - return -1; -} +int A2DP_VendorGetTrackChannelCountOpus(const uint8_t* p_codec_info) { return -1; } -int A2DP_VendorGetSinkTrackChannelTypeOpus(const uint8_t* p_codec_info) { - return -1; -} +int A2DP_VendorGetSinkTrackChannelTypeOpus(const uint8_t* p_codec_info) { return -1; } -int A2DP_VendorGetChannelModeCodeOpus(const uint8_t* p_codec_info) { - return -1; -} +int A2DP_VendorGetChannelModeCodeOpus(const uint8_t* p_codec_info) { return -1; } int A2DP_VendorGetFrameSizeOpus(const uint8_t* p_codec_info) { return -1; } -bool A2DP_VendorGetPacketTimestampOpus(const uint8_t* p_codec_info, - const uint8_t* p_data, +bool A2DP_VendorGetPacketTimestampOpus(const uint8_t* p_codec_info, const uint8_t* p_data, uint32_t* p_timestamp) { return false; } @@ -100,25 +72,21 @@ std::string A2DP_VendorCodecInfoStringOpus(const uint8_t* p_codec_info) { return "Unsupported codec: Opus"; } -const tA2DP_ENCODER_INTERFACE* A2DP_VendorGetEncoderInterfaceOpus( - const uint8_t* p_codec_info) { +const tA2DP_ENCODER_INTERFACE* A2DP_VendorGetEncoderInterfaceOpus(const uint8_t* p_codec_info) { return nullptr; } -const tA2DP_DECODER_INTERFACE* A2DP_VendorGetDecoderInterfaceOpus( - const uint8_t* p_codec_info) { +const tA2DP_DECODER_INTERFACE* A2DP_VendorGetDecoderInterfaceOpus(const uint8_t* p_codec_info) { return nullptr; } bool A2DP_VendorAdjustCodecOpus(uint8_t* p_codec_info) { return false; } -btav_a2dp_codec_index_t A2DP_VendorSourceCodecIndexOpus( - const uint8_t* p_codec_info) { +btav_a2dp_codec_index_t A2DP_VendorSourceCodecIndexOpus(const uint8_t* p_codec_info) { return BTAV_A2DP_CODEC_INDEX_MAX; } -btav_a2dp_codec_index_t A2DP_VendorSinkCodecIndexOpus( - const uint8_t* p_codec_info) { +btav_a2dp_codec_index_t A2DP_VendorSinkCodecIndexOpus(const uint8_t* p_codec_info) { return BTAV_A2DP_CODEC_INDEX_MAX; } @@ -130,11 +98,9 @@ bool A2DP_VendorInitCodecConfigOpus(AvdtpSepConfig* p_cfg) { return false; } bool A2DP_VendorInitCodecConfigOpusSink(AvdtpSepConfig* p_cfg) { return false; } -A2dpCodecConfigOpusSource::A2dpCodecConfigOpusSource( - btav_a2dp_codec_priority_t codec_priority) - : A2dpCodecConfigOpusBase(BTAV_A2DP_CODEC_INDEX_SOURCE_OPUS, - A2DP_VendorCodecIndexStrOpus(), codec_priority, - true) {} +A2dpCodecConfigOpusSource::A2dpCodecConfigOpusSource(btav_a2dp_codec_priority_t codec_priority) + : A2dpCodecConfigOpusBase(BTAV_A2DP_CODEC_INDEX_SOURCE_OPUS, A2DP_VendorCodecIndexStrOpus(), + codec_priority, true) {} A2dpCodecConfigOpusSource::~A2dpCodecConfigOpusSource() {} @@ -144,21 +110,17 @@ bool A2dpCodecConfigOpusSource::useRtpHeaderMarkerBit() const { return false; } void A2dpCodecConfigOpusSource::debug_codec_dump(int fd) {} -bool A2dpCodecConfigOpusBase::setCodecConfig(const uint8_t* p_peer_codec_info, - bool is_capability, +bool A2dpCodecConfigOpusBase::setCodecConfig(const uint8_t* p_peer_codec_info, bool is_capability, uint8_t* p_result_codec_config) { return false; } -bool A2dpCodecConfigOpusBase::setPeerCodecCapabilities( - const uint8_t* p_peer_codec_capabilities) { +bool A2dpCodecConfigOpusBase::setPeerCodecCapabilities(const uint8_t* p_peer_codec_capabilities) { return false; } -A2dpCodecConfigOpusSink::A2dpCodecConfigOpusSink( - btav_a2dp_codec_priority_t codec_priority) - : A2dpCodecConfigOpusBase(BTAV_A2DP_CODEC_INDEX_SINK_OPUS, - A2DP_VendorCodecIndexStrOpusSink(), +A2dpCodecConfigOpusSink::A2dpCodecConfigOpusSink(btav_a2dp_codec_priority_t codec_priority) + : A2dpCodecConfigOpusBase(BTAV_A2DP_CODEC_INDEX_SINK_OPUS, A2DP_VendorCodecIndexStrOpusSink(), codec_priority, false) {} A2dpCodecConfigOpusSink::~A2dpCodecConfigOpusSink() {} @@ -168,7 +130,7 @@ bool A2dpCodecConfigOpusSink::init() { return false; } bool A2dpCodecConfigOpusSink::useRtpHeaderMarkerBit() const { return false; } bool A2dpCodecConfigOpusSink::updateEncoderUserConfig( - const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params, bool* p_restart_input, - bool* p_restart_output, bool* p_config_updated) { + const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params, bool* p_restart_input, + bool* p_restart_output, bool* p_config_updated) { return false; } diff --git a/system/stack/acl/acl.cc b/system/stack/acl/acl.cc index 8342ad9751f..71b26747726 100644 --- a/system/stack/acl/acl.cc +++ b/system/stack/acl/acl.cc @@ -15,6 +15,7 @@ */ #include "stack/acl/acl.h" + #include "types/raw_address.h" void tACL_CONN::Reset() { diff --git a/system/stack/acl/acl.h b/system/stack/acl/acl.h index 818c27ad4a6..1bcedb8085f 100644 --- a/system/stack/acl/acl.h +++ b/system/stack/acl/acl.h @@ -58,14 +58,13 @@ typedef enum : uint16_t { typedef uint16_t tLINK_POLICY; constexpr tLINK_POLICY kAllLinkPoliciesEnabled = - (HCI_ENABLE_CENTRAL_PERIPHERAL_SWITCH | HCI_ENABLE_HOLD_MODE | - HCI_ENABLE_SNIFF_MODE); + (HCI_ENABLE_CENTRAL_PERIPHERAL_SWITCH | HCI_ENABLE_HOLD_MODE | HCI_ENABLE_SNIFF_MODE); static const char* link_policy_string[] = { - " role_switch ", - " hold_mode ", - " sniff_mode ", - " park_mode ", + " role_switch ", + " hold_mode ", + " sniff_mode ", + " park_mode ", }; inline std::string link_policy_text(tLINK_POLICY policy) { @@ -73,7 +72,9 @@ inline std::string link_policy_text(tLINK_POLICY policy) { os << "0x" << loghex(static_cast(policy)) << " :"; std::string s = os.str(); for (uint16_t i = 0; i < 4; i++) { - if (policy & (0x1 << i)) s += link_policy_string[i]; + if (policy & (0x1 << i)) { + s += link_policy_string[i]; + } } return s; } @@ -93,8 +94,7 @@ enum : uint8_t { typedef uint8_t tBTM_PM_STATE; inline std::string power_mode_state_text(tBTM_PM_STATE state) { - std::string s = - std::string((state & BTM_PM_STORED_MASK) ? "stored:" : "immediate:"); + std::string s = std::string((state & BTM_PM_STORED_MASK) ? "stored:" : "immediate:"); switch (state & ~BTM_PM_STORED_MASK) { case BTM_PM_ST_ACTIVE: return s + std::string("active"); @@ -118,15 +118,13 @@ inline std::string power_mode_state_text(tBTM_PM_STATE state) { namespace bluetooth { namespace shim { tBTM_STATUS BTM_SetPowerMode(uint16_t handle, const tBTM_PM_PWR_MD& new_mode); -tBTM_STATUS BTM_SetSsrParams(uint16_t handle, uint16_t max_lat, - uint16_t min_rmt_to, uint16_t min_loc_to); -void btm_pm_on_mode_change(tHCI_STATUS status, uint16_t handle, - tHCI_MODE hci_mode, uint16_t interval); +tBTM_STATUS BTM_SetSsrParams(uint16_t handle, uint16_t max_lat, uint16_t min_rmt_to, + uint16_t min_loc_to); +void btm_pm_on_mode_change(tHCI_STATUS status, uint16_t handle, tHCI_MODE hci_mode, + uint16_t interval); void btm_pm_on_sniff_subrating(tHCI_STATUS status, uint16_t handle, - uint16_t maximum_transmit_latency, - uint16_t maximum_receive_latency, - uint16_t minimum_remote_timeout, - uint16_t minimum_local_timeout); + uint16_t maximum_transmit_latency, uint16_t maximum_receive_latency, + uint16_t minimum_remote_timeout, uint16_t minimum_local_timeout); } // namespace shim } // namespace bluetooth @@ -139,9 +137,8 @@ typedef struct { #define BTM_PM_REC_NOT_USED 0 typedef struct tBTM_PM_RCB { - tBTM_PM_STATUS_CBACK* cback = - nullptr; /* to notify the registered party of mode change event */ - uint8_t mask = 0; /* registered request mask. 0, if this entry is not used */ + tBTM_PM_STATUS_CBACK* cback = nullptr; /* to notify the registered party of mode change event */ + uint8_t mask = 0; /* registered request mask. 0, if this entry is not used */ } tBTM_PM_RCB; /* Structure returned with Role Switch information (in tBTM_CMPL_CB callback @@ -185,7 +182,7 @@ struct tACL_CONN { RawAddress remote_addr; bool in_use{false}; - public: +public: bool InUse() const { return in_use; } const RawAddress RemoteAddress() const { return remote_addr; } @@ -193,24 +190,22 @@ struct tACL_CONN { tBT_TRANSPORT transport; bool is_transport_br_edr() const { return transport == BT_TRANSPORT_BR_EDR; } bool is_transport_ble() const { return transport == BT_TRANSPORT_LE; } - bool is_transport_valid() const { - return is_transport_ble() || is_transport_br_edr(); - } + bool is_transport_valid() const { return is_transport_ble() || is_transport_br_edr(); } uint16_t flush_timeout_in_ticks; uint16_t hci_handle; tLINK_POLICY link_policy; - public: +public: uint16_t Handle() const { return hci_handle; } uint16_t link_super_tout; uint16_t pkt_types_mask; uint8_t disconnect_reason; - private: +private: btm_acl_encrypt_state_t encrypt_state_; - public: +public: void set_encryption_off() { if (encrypt_state_ != BTM_ACL_ENCRYPT_STATE_ENCRYPT_OFF) { btsnd_hcic_set_conn_encrypt(hci_handle, false); @@ -225,11 +220,9 @@ struct tACL_CONN { } void set_encryption_idle() { encrypt_state_ = BTM_ACL_ENCRYPT_STATE_IDLE; } - void set_encryption_switching() { - encrypt_state_ = BTM_ACL_ENCRYPT_STATE_TEMP_FUNC; - } + void set_encryption_switching() { encrypt_state_ = BTM_ACL_ENCRYPT_STATE_TEMP_FUNC; } - public: +public: bool is_encrypted = false; tHCI_ROLE link_role; uint8_t switch_role_failed_attempts; @@ -239,52 +232,32 @@ struct tACL_CONN { #define BTM_SEC_RS_NOT_PENDING 0 /* Role Switch not in progress */ #define BTM_SEC_RS_PENDING 1 /* Role Switch in progress */ #define BTM_SEC_DISC_PENDING 2 /* Disconnect is pending */ - private: +private: uint8_t rs_disc_pending = BTM_SEC_RS_NOT_PENDING; friend struct StackAclBtmAcl; - friend tBTM_STATUS btm_remove_acl(const RawAddress& bd_addr, - tBT_TRANSPORT transport); - friend void acl_disconnect_after_role_switch(uint16_t conn_handle, - tHCI_STATUS reason, std::string); - friend void bluetooth::shim::btm_pm_on_mode_change(tHCI_STATUS status, - uint16_t handle, - tHCI_MODE hci_mode, - uint16_t interval); - friend void btm_acl_encrypt_change(uint16_t handle, uint8_t status, - uint8_t encr_enable); - - public: - bool is_disconnect_pending() const { - return rs_disc_pending == BTM_SEC_DISC_PENDING; - } - bool is_role_switch_pending() const { - return rs_disc_pending == BTM_SEC_RS_PENDING; - } - - private: + friend tBTM_STATUS btm_remove_acl(const RawAddress& bd_addr, tBT_TRANSPORT transport); + friend void acl_disconnect_after_role_switch(uint16_t conn_handle, tHCI_STATUS reason, + std::string); + friend void bluetooth::shim::btm_pm_on_mode_change(tHCI_STATUS status, uint16_t handle, + tHCI_MODE hci_mode, uint16_t interval); + friend void btm_acl_encrypt_change(uint16_t handle, uint8_t status, uint8_t encr_enable); + +public: + bool is_disconnect_pending() const { return rs_disc_pending == BTM_SEC_DISC_PENDING; } + bool is_role_switch_pending() const { return rs_disc_pending == BTM_SEC_RS_PENDING; } + +private: uint8_t switch_role_state_; - public: +public: void reset_switch_role() { switch_role_state_ = BTM_ACL_SWKEY_STATE_IDLE; } - void set_switch_role_changing() { - switch_role_state_ = BTM_ACL_SWKEY_STATE_MODE_CHANGE; - } - void set_switch_role_encryption_off() { - switch_role_state_ = BTM_ACL_SWKEY_STATE_ENCRYPTION_OFF; - } - void set_switch_role_encryption_on() { - switch_role_state_ = BTM_ACL_SWKEY_STATE_ENCRYPTION_ON; - } - void set_switch_role_in_progress() { - switch_role_state_ = BTM_ACL_SWKEY_STATE_IN_PROGRESS; - } - void set_switch_role_switching() { - switch_role_state_ = BTM_ACL_SWKEY_STATE_SWITCHING; - } + void set_switch_role_changing() { switch_role_state_ = BTM_ACL_SWKEY_STATE_MODE_CHANGE; } + void set_switch_role_encryption_off() { switch_role_state_ = BTM_ACL_SWKEY_STATE_ENCRYPTION_OFF; } + void set_switch_role_encryption_on() { switch_role_state_ = BTM_ACL_SWKEY_STATE_ENCRYPTION_ON; } + void set_switch_role_in_progress() { switch_role_state_ = BTM_ACL_SWKEY_STATE_IN_PROGRESS; } + void set_switch_role_switching() { switch_role_state_ = BTM_ACL_SWKEY_STATE_SWITCHING; } - bool is_switch_role_idle() const { - return switch_role_state_ == BTM_ACL_SWKEY_STATE_IDLE; - } + bool is_switch_role_idle() const { return switch_role_state_ == BTM_ACL_SWKEY_STATE_IDLE; } bool is_switch_role_encryption_off() const { return switch_role_state_ == BTM_ACL_SWKEY_STATE_ENCRYPTION_OFF; } @@ -304,7 +277,7 @@ struct tACL_CONN { return is_switch_role_switching() || is_switch_role_in_progress(); } - public: +public: uint8_t sca; /* Sleep clock accuracy */ void Reset(); @@ -313,16 +286,15 @@ struct tACL_CONN { /**************************************************** ** ACL Management API ****************************************************/ -constexpr uint16_t kDefaultPacketTypeMask = - HCI_PKT_TYPES_MASK_DH1 | HCI_PKT_TYPES_MASK_DM1 | HCI_PKT_TYPES_MASK_DH3 | - HCI_PKT_TYPES_MASK_DM3 | HCI_PKT_TYPES_MASK_DH5 | HCI_PKT_TYPES_MASK_DM5; +constexpr uint16_t kDefaultPacketTypeMask = HCI_PKT_TYPES_MASK_DH1 | HCI_PKT_TYPES_MASK_DM1 | + HCI_PKT_TYPES_MASK_DH3 | HCI_PKT_TYPES_MASK_DM3 | + HCI_PKT_TYPES_MASK_DH5 | HCI_PKT_TYPES_MASK_DM5; struct tACL_CB { - private: +private: friend uint8_t btm_handle_to_acl_index(uint16_t hci_handle); friend void btm_acl_device_down(void); - friend void btm_acl_encrypt_change(uint16_t handle, uint8_t status, - uint8_t encr_enable); + friend void btm_acl_encrypt_change(uint16_t handle, uint8_t status, uint8_t encr_enable); friend void DumpsysAcl(int fd); friend struct StackAclBtmAcl; @@ -334,7 +306,7 @@ struct tACL_CB { tHCI_STATUS acl_disc_reason = HCI_ERR_UNDEFINED; bool locally_initiated; - public: +public: void SetDefaultPacketTypeMask(uint16_t packet_type_mask) { btm_acl_pkt_types_supported = packet_type_mask; } @@ -353,7 +325,9 @@ struct tACL_CB { unsigned NumberOfActiveLinks() const { unsigned cnt = 0; for (int i = 0; i < MAX_L2CAP_LINKS; i++) { - if (acl_db[i].InUse()) ++cnt; + if (acl_db[i].InUse()) { + ++cnt; + } } return cnt; } @@ -361,5 +335,4 @@ struct tACL_CB { tACL_CONN* btm_acl_for_bda(const RawAddress& bd_addr, tBT_TRANSPORT transport); -void btm_acl_encrypt_change(uint16_t handle, uint8_t status, - uint8_t encr_enable); \ No newline at end of file +void btm_acl_encrypt_change(uint16_t handle, uint8_t status, uint8_t encr_enable); \ No newline at end of file diff --git a/system/stack/acl/ble_acl.cc b/system/stack/acl/ble_acl.cc index 964e1ee03ef..c5ac81f293f 100644 --- a/system/stack/acl/ble_acl.cc +++ b/system/stack/acl/ble_acl.cc @@ -39,33 +39,32 @@ extern tBTM_CB btm_cb; void btm_ble_increment_link_topology_mask(uint8_t link_role); -static bool acl_ble_common_connection( - const tBLE_BD_ADDR& address_with_type, uint16_t handle, tHCI_ROLE role, - bool is_in_security_db, uint16_t conn_interval, uint16_t conn_latency, - uint16_t conn_timeout, bool can_read_discoverable_characteristics) { +static bool acl_ble_common_connection(const tBLE_BD_ADDR& address_with_type, uint16_t handle, + tHCI_ROLE role, bool is_in_security_db, + uint16_t conn_interval, uint16_t conn_latency, + uint16_t conn_timeout, + bool can_read_discoverable_characteristics) { if (role == HCI_ROLE_CENTRAL) { btm_cb.ble_ctr_cb.set_connection_state_idle(); btm_ble_clear_topology_mask(BTM_BLE_STATE_INIT_BIT); } // Inform any applications that a connection has completed. - if (!bluetooth::common::init_flags:: - use_unified_connection_manager_is_enabled()) { + if (!bluetooth::common::init_flags::use_unified_connection_manager_is_enabled()) { connection_manager::on_connection_complete(address_with_type.bda); } // Allocate or update the security device record for this device - btm_ble_connected(address_with_type.bda, handle, HCI_ENCRYPT_MODE_DISABLED, - role, address_with_type.type, is_in_security_db, + btm_ble_connected(address_with_type.bda, handle, HCI_ENCRYPT_MODE_DISABLED, role, + address_with_type.type, is_in_security_db, can_read_discoverable_characteristics); // Update the link topology information for our device btm_ble_increment_link_topology_mask(role); // Inform l2cap of a potential connection. - if (!l2cble_conn_comp(handle, role, address_with_type.bda, - address_with_type.type, conn_interval, conn_latency, - conn_timeout)) { + if (!l2cble_conn_comp(handle, role, address_with_type.bda, address_with_type.type, conn_interval, + conn_latency, conn_timeout)) { btm_sec_disconnect(handle, HCI_ERR_PEER_USER, "stack::acl::ble_acl fail"); log::warn("Unable to complete l2cap connection"); return false; @@ -77,125 +76,109 @@ static bool acl_ble_common_connection( return true; } -void acl_ble_enhanced_connection_complete( - const tBLE_BD_ADDR& address_with_type, uint16_t handle, tHCI_ROLE role, - bool match, uint16_t conn_interval, uint16_t conn_latency, - uint16_t conn_timeout, const RawAddress& /* local_rpa */, - const RawAddress& peer_rpa, tBLE_ADDR_TYPE peer_addr_type, - bool can_read_discoverable_characteristics) { - if (!acl_ble_common_connection(address_with_type, handle, role, match, - conn_interval, conn_latency, conn_timeout, +void acl_ble_enhanced_connection_complete(const tBLE_BD_ADDR& address_with_type, uint16_t handle, + tHCI_ROLE role, bool match, uint16_t conn_interval, + uint16_t conn_latency, uint16_t conn_timeout, + const RawAddress& /* local_rpa */, + const RawAddress& peer_rpa, tBLE_ADDR_TYPE peer_addr_type, + bool can_read_discoverable_characteristics) { + if (!acl_ble_common_connection(address_with_type, handle, role, match, conn_interval, + conn_latency, conn_timeout, can_read_discoverable_characteristics)) { log::warn("Unable to create enhanced ble acl connection"); return; } - if (peer_addr_type & BLE_ADDR_TYPE_ID_BIT) - btm_ble_refresh_peer_resolvable_private_addr(address_with_type.bda, - peer_rpa, BTM_BLE_ADDR_RRA); + if (peer_addr_type & BLE_ADDR_TYPE_ID_BIT) { + btm_ble_refresh_peer_resolvable_private_addr(address_with_type.bda, peer_rpa, BTM_BLE_ADDR_RRA); + } btm_ble_update_mode_operation(role, &address_with_type.bda, HCI_SUCCESS); } -static bool maybe_resolve_received_address( - const tBLE_BD_ADDR& address_with_type, - tBLE_BD_ADDR* resolved_address_with_type) { +static bool maybe_resolve_received_address(const tBLE_BD_ADDR& address_with_type, + tBLE_BD_ADDR* resolved_address_with_type) { log::assert_that(resolved_address_with_type != nullptr, "assert failed: resolved_address_with_type != nullptr"); *resolved_address_with_type = address_with_type; - return maybe_resolve_address(&resolved_address_with_type->bda, - &resolved_address_with_type->type); + return maybe_resolve_address(&resolved_address_with_type->bda, &resolved_address_with_type->type); } void acl_ble_enhanced_connection_complete_from_shim( - const tBLE_BD_ADDR& address_with_type, uint16_t handle, tHCI_ROLE role, - uint16_t conn_interval, uint16_t conn_latency, uint16_t conn_timeout, - const RawAddress& local_rpa, const RawAddress& peer_rpa, - tBLE_ADDR_TYPE peer_addr_type, bool can_read_discoverable_characteristics) { - if (!bluetooth::common::init_flags:: - use_unified_connection_manager_is_enabled()) { + const tBLE_BD_ADDR& address_with_type, uint16_t handle, tHCI_ROLE role, + uint16_t conn_interval, uint16_t conn_latency, uint16_t conn_timeout, + const RawAddress& local_rpa, const RawAddress& peer_rpa, tBLE_ADDR_TYPE peer_addr_type, + bool can_read_discoverable_characteristics) { + if (!bluetooth::common::init_flags::use_unified_connection_manager_is_enabled()) { connection_manager::on_connection_complete(address_with_type.bda); } tBLE_BD_ADDR resolved_address_with_type; - const bool is_in_security_db = maybe_resolve_received_address( - address_with_type, &resolved_address_with_type); + const bool is_in_security_db = + maybe_resolve_received_address(address_with_type, &resolved_address_with_type); acl_set_locally_initiated(role == tHCI_ROLE::HCI_ROLE_CENTRAL); acl_ble_enhanced_connection_complete( - resolved_address_with_type, handle, role, is_in_security_db, - conn_interval, conn_latency, conn_timeout, local_rpa, peer_rpa, - peer_addr_type, can_read_discoverable_characteristics); + resolved_address_with_type, handle, role, is_in_security_db, conn_interval, conn_latency, + conn_timeout, local_rpa, peer_rpa, peer_addr_type, can_read_discoverable_characteristics); // The legacy stack continues the LE connection after the read remote // version complete has been received. // maybe_chain_more_commands_after_read_remote_version_complete } -void acl_ble_connection_fail(const tBLE_BD_ADDR& address_with_type, - uint16_t /* handle */, bool /* enhanced */, - tHCI_STATUS status) { - acl_set_locally_initiated( - true); // LE connection failures are always locally initiated +void acl_ble_connection_fail(const tBLE_BD_ADDR& address_with_type, uint16_t /* handle */, + bool /* enhanced */, tHCI_STATUS status) { + acl_set_locally_initiated(true); // LE connection failures are always locally initiated btm_acl_create_failed(address_with_type.bda, BT_TRANSPORT_LE, status); if (status != HCI_ERR_ADVERTISING_TIMEOUT) { btm_cb.ble_ctr_cb.set_connection_state_idle(); btm_ble_clear_topology_mask(BTM_BLE_STATE_INIT_BIT); tBLE_BD_ADDR resolved_address_with_type; - maybe_resolve_received_address(address_with_type, - &resolved_address_with_type); - if (!bluetooth::common::init_flags:: - use_unified_connection_manager_is_enabled()) { - connection_manager::on_connection_timed_out_from_shim( - resolved_address_with_type.bda); + maybe_resolve_received_address(address_with_type, &resolved_address_with_type); + if (!bluetooth::common::init_flags::use_unified_connection_manager_is_enabled()) { + connection_manager::on_connection_timed_out_from_shim(resolved_address_with_type.bda); } - log::warn("LE connection fail peer:{} bd_addr:{} hci_status:{}", - address_with_type, resolved_address_with_type.bda, - hci_status_code_text(status)); + log::warn("LE connection fail peer:{} bd_addr:{} hci_status:{}", address_with_type, + resolved_address_with_type.bda, hci_status_code_text(status)); } else { btm_cb.ble_ctr_cb.inq_var.adv_mode = BTM_BLE_ADV_DISABLE; } - btm_ble_update_mode_operation(HCI_ROLE_UNKNOWN, &address_with_type.bda, - status); + btm_ble_update_mode_operation(HCI_ROLE_UNKNOWN, &address_with_type.bda, status); } -void gatt_notify_conn_update(const RawAddress& remote, uint16_t interval, - uint16_t latency, uint16_t timeout, - tHCI_STATUS status); -void acl_ble_update_event_received(tHCI_STATUS status, uint16_t handle, - uint16_t interval, uint16_t latency, - uint16_t timeout) { +void gatt_notify_conn_update(const RawAddress& remote, uint16_t interval, uint16_t latency, + uint16_t timeout, tHCI_STATUS status); +void acl_ble_update_event_received(tHCI_STATUS status, uint16_t handle, uint16_t interval, + uint16_t latency, uint16_t timeout) { l2cble_process_conn_update_evt(handle, status, interval, latency, timeout); tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev_by_handle(handle); - if (!p_dev_rec) return; + if (!p_dev_rec) { + return; + } - gatt_notify_conn_update(p_dev_rec->ble.pseudo_addr, interval, latency, - timeout, status); + gatt_notify_conn_update(p_dev_rec->ble.pseudo_addr, interval, latency, timeout, status); } -void acl_ble_update_request_event_received(uint16_t handle, - uint16_t interval_min, - uint16_t interval_max, - uint16_t latency, uint16_t timeout) { - l2cble_process_rc_param_request_evt(handle, interval_min, interval_max, - latency, timeout); +void acl_ble_update_request_event_received(uint16_t handle, uint16_t interval_min, + uint16_t interval_max, uint16_t latency, + uint16_t timeout) { + l2cble_process_rc_param_request_evt(handle, interval_min, interval_max, latency, timeout); } -void acl_ble_data_length_change_event(uint16_t handle, uint16_t max_tx_octets, - uint16_t max_tx_time, - uint16_t max_rx_octets, - uint16_t max_rx_time) { +void acl_ble_data_length_change_event(uint16_t handle, uint16_t max_tx_octets, uint16_t max_tx_time, + uint16_t max_rx_octets, uint16_t max_rx_time) { log::debug( - "Data length change event received handle:0x{:04x} max_tx_octets:{} " - "max_tx_time:{} max_rx_octets:{} max_rx_time:{}", - handle, max_tx_octets, max_tx_time, max_rx_octets, max_rx_time); + "Data length change event received handle:0x{:04x} max_tx_octets:{} " + "max_tx_time:{} max_rx_octets:{} max_rx_time:{}", + handle, max_tx_octets, max_tx_time, max_rx_octets, max_rx_time); l2cble_process_data_length_change_event(handle, max_tx_octets, max_rx_octets); } -uint64_t btm_get_next_private_addrress_interval_ms() { +uint64_t btm_get_next_private_address_interval_ms() { /* 7 minutes minimum, 15 minutes maximum for random address refreshing */ const uint64_t interval_min_ms = (7 * 60 * 1000); const uint64_t interval_random_part_max_ms = (8 * 60 * 1000); diff --git a/system/stack/acl/btm_acl.cc b/system/stack/acl/btm_acl.cc index d30d126478e..4ec9d3096c1 100644 --- a/system/stack/acl/btm_acl.cc +++ b/system/stack/acl/btm_acl.cc @@ -80,8 +80,7 @@ #include "types/raw_address.h" #ifndef PROPERTY_LINK_SUPERVISION_TIMEOUT -#define PROPERTY_LINK_SUPERVISION_TIMEOUT \ - "bluetooth.core.acl.link_supervision_timeout" +#define PROPERTY_LINK_SUPERVISION_TIMEOUT "bluetooth.core.acl.link_supervision_timeout" #endif using namespace bluetooth; @@ -90,10 +89,8 @@ using bluetooth::legacy::hci::GetInterface; void BTM_update_version_info(const RawAddress& bd_addr, const remote_version_info& remote_version_info); -static void find_in_device_record(const RawAddress& bd_addr, - tBLE_BD_ADDR* address_with_type); -void l2c_link_hci_conn_comp(tHCI_STATUS status, uint16_t handle, - const RawAddress& p_bda); +static void find_in_device_record(const RawAddress& bd_addr, tBLE_BD_ADDR* address_with_type); +void l2c_link_hci_conn_comp(tHCI_STATUS status, uint16_t handle, const RawAddress& p_bda); void BTM_db_reset(void); @@ -105,18 +102,15 @@ struct StackAclBtmAcl { tACL_CONN* acl_allocate_connection(); tACL_CONN* acl_get_connection_from_handle(uint16_t handle); tACL_CONN* btm_bda_to_acl(const RawAddress& bda, tBT_TRANSPORT transport); - bool change_connection_packet_types(tACL_CONN& link, - const uint16_t new_packet_type_bitmask); + bool change_connection_packet_types(tACL_CONN& link, const uint16_t new_packet_type_bitmask); void btm_establish_continue(tACL_CONN* p_acl_cb); void btm_set_default_link_policy(tLINK_POLICY settings); - void btm_acl_role_changed(tHCI_STATUS hci_status, const RawAddress& bd_addr, - tHCI_ROLE new_role); + void btm_acl_role_changed(tHCI_STATUS hci_status, const RawAddress& bd_addr, tHCI_ROLE new_role); void hci_start_role_switch_to_central(tACL_CONN& p_acl); void set_default_packet_types_supported(uint16_t packet_types_supported) { btm_cb.acl_cb_.btm_acl_pkt_types_supported = packet_types_supported; } - void btm_acl_consolidate(const RawAddress& identity_addr, - const RawAddress& rpa); + void btm_acl_consolidate(const RawAddress& identity_addr, const RawAddress& rpa); }; struct RoleChangeView { @@ -127,7 +121,7 @@ struct RoleChangeView { namespace { StackAclBtmAcl internal_; std::unique_ptr delayed_role_change_ = nullptr; -} +} // namespace typedef struct { uint16_t handle; @@ -139,13 +133,12 @@ constexpr uint8_t BTM_MAX_SW_ROLE_FAILED_ATTEMPTS = 3; /* Define masks for supported and exception 2.0 ACL packet types */ constexpr uint16_t BTM_ACL_SUPPORTED_PKTS_MASK = - (HCI_PKT_TYPES_MASK_DM1 | HCI_PKT_TYPES_MASK_DH1 | HCI_PKT_TYPES_MASK_DM3 | - HCI_PKT_TYPES_MASK_DH3 | HCI_PKT_TYPES_MASK_DM5 | HCI_PKT_TYPES_MASK_DH5); + (HCI_PKT_TYPES_MASK_DM1 | HCI_PKT_TYPES_MASK_DH1 | HCI_PKT_TYPES_MASK_DM3 | + HCI_PKT_TYPES_MASK_DH3 | HCI_PKT_TYPES_MASK_DM5 | HCI_PKT_TYPES_MASK_DH5); constexpr uint16_t BTM_ACL_EXCEPTION_PKTS_MASK = - (HCI_PKT_TYPES_MASK_NO_2_DH1 | HCI_PKT_TYPES_MASK_NO_3_DH1 | - HCI_PKT_TYPES_MASK_NO_2_DH3 | HCI_PKT_TYPES_MASK_NO_3_DH3 | - HCI_PKT_TYPES_MASK_NO_2_DH5 | HCI_PKT_TYPES_MASK_NO_3_DH5); + (HCI_PKT_TYPES_MASK_NO_2_DH1 | HCI_PKT_TYPES_MASK_NO_3_DH1 | HCI_PKT_TYPES_MASK_NO_2_DH3 | + HCI_PKT_TYPES_MASK_NO_3_DH3 | HCI_PKT_TYPES_MASK_NO_2_DH5 | HCI_PKT_TYPES_MASK_NO_3_DH5); static bool IsEprAvailable(const tACL_CONN& p_acl) { if (!p_acl.peer_lmp_feature_valid[0]) { @@ -156,8 +149,7 @@ static bool IsEprAvailable(const tACL_CONN& p_acl) { bluetooth::shim::GetController()->SupportsEncryptionPause(); } -static void btm_process_remote_ext_features(tACL_CONN* p_acl_cb, - uint8_t max_page_number); +static void btm_process_remote_ext_features(tACL_CONN* p_acl_cb, uint8_t max_page_number); static void btm_read_failed_contact_counter_timeout(void* data); static void btm_read_remote_ext_features(uint16_t handle, uint8_t page_number); static void btm_read_rssi_timeout(void* data); @@ -196,19 +188,17 @@ void NotifyAclFeaturesReadComplete(tACL_CONN& p_acl, uint8_t max_page_number) { } // namespace -static void disconnect_acl(tACL_CONN& p_acl, tHCI_STATUS reason, - std::string comment) { +static void disconnect_acl(tACL_CONN& p_acl, tHCI_STATUS reason, std::string comment) { log::info("Disconnecting peer:{} reason:{} comment:{}", p_acl.remote_addr, hci_error_code_text(reason), comment); p_acl.disconnect_reason = reason; - return bluetooth::shim::ACL_Disconnect( - p_acl.hci_handle, p_acl.is_transport_br_edr(), reason, comment); + return bluetooth::shim::ACL_Disconnect(p_acl.hci_handle, p_acl.is_transport_br_edr(), reason, + comment); } void StackAclBtmAcl::hci_start_role_switch_to_central(tACL_CONN& p_acl) { - GetInterface().StartRoleSwitch(p_acl.remote_addr, - static_cast(HCI_ROLE_CENTRAL)); + GetInterface().StartRoleSwitch(p_acl.remote_addr, static_cast(HCI_ROLE_CENTRAL)); p_acl.set_switch_role_in_progress(); p_acl.rs_disc_pending = BTM_SEC_RS_PENDING; } @@ -216,21 +206,20 @@ void StackAclBtmAcl::hci_start_role_switch_to_central(tACL_CONN& p_acl) { void hci_btm_set_link_supervision_timeout(tACL_CONN& link, uint16_t timeout) { if (link.link_role != HCI_ROLE_CENTRAL) { /* Only send if current role is Central; 2.0 spec requires this */ - log::warn("Can only set link supervision timeout if central role:{}", - RoleText(link.link_role)); + log::warn("Can only set link supervision timeout if central role:{}", RoleText(link.link_role)); return; } if (!bluetooth::shim::GetController()->IsSupported( - bluetooth::hci::OpCode::WRITE_LINK_SUPERVISION_TIMEOUT)) { + bluetooth::hci::OpCode::WRITE_LINK_SUPERVISION_TIMEOUT)) { log::warn( - "UNSUPPORTED by controller write link supervision timeout:{:.2f}ms " - "bd_addr:{}", - supervision_timeout_to_seconds(timeout), link.RemoteAddress()); + "UNSUPPORTED by controller write link supervision timeout:{:.2f}ms " + "bd_addr:{}", + supervision_timeout_to_seconds(timeout), link.RemoteAddress()); return; } - log::debug("Setting link supervision timeout:{:.2f}s peer:{}", - double(timeout) * 0.01, link.RemoteAddress()); + log::debug("Setting link supervision timeout:{:.2f}s peer:{}", double(timeout) * 0.01, + link.RemoteAddress()); link.link_super_tout = timeout; btsnd_hcic_write_link_super_tout(link.Handle(), timeout); } @@ -239,45 +228,42 @@ void hci_btm_set_link_supervision_timeout(tACL_CONN& link, uint16_t timeout) { #define BTM_DEV_REPLY_TIMEOUT_MS (3 * 1000) void BTM_acl_after_controller_started() { - internal_.btm_set_default_link_policy( - HCI_ENABLE_CENTRAL_PERIPHERAL_SWITCH | HCI_ENABLE_HOLD_MODE | - HCI_ENABLE_SNIFF_MODE | HCI_ENABLE_PARK_MODE); + internal_.btm_set_default_link_policy(HCI_ENABLE_CENTRAL_PERIPHERAL_SWITCH | + HCI_ENABLE_HOLD_MODE | HCI_ENABLE_SNIFF_MODE | + HCI_ENABLE_PARK_MODE); /* Create ACL supported packet types mask */ - uint16_t btm_acl_pkt_types_supported = - (HCI_PKT_TYPES_MASK_DH1 + HCI_PKT_TYPES_MASK_DM1); + uint16_t btm_acl_pkt_types_supported = (HCI_PKT_TYPES_MASK_DH1 + HCI_PKT_TYPES_MASK_DM1); - if (bluetooth::shim::GetController()->Supports3SlotPackets()) - btm_acl_pkt_types_supported |= - (HCI_PKT_TYPES_MASK_DH3 + HCI_PKT_TYPES_MASK_DM3); + if (bluetooth::shim::GetController()->Supports3SlotPackets()) { + btm_acl_pkt_types_supported |= (HCI_PKT_TYPES_MASK_DH3 + HCI_PKT_TYPES_MASK_DM3); + } - if (bluetooth::shim::GetController()->Supports5SlotPackets()) - btm_acl_pkt_types_supported |= - (HCI_PKT_TYPES_MASK_DH5 + HCI_PKT_TYPES_MASK_DM5); + if (bluetooth::shim::GetController()->Supports5SlotPackets()) { + btm_acl_pkt_types_supported |= (HCI_PKT_TYPES_MASK_DH5 + HCI_PKT_TYPES_MASK_DM5); + } /* Add in EDR related ACL types */ if (!bluetooth::shim::GetController()->SupportsClassic2mPhy()) { - btm_acl_pkt_types_supported |= - (HCI_PKT_TYPES_MASK_NO_2_DH1 + HCI_PKT_TYPES_MASK_NO_2_DH3 + - HCI_PKT_TYPES_MASK_NO_2_DH5); + btm_acl_pkt_types_supported |= (HCI_PKT_TYPES_MASK_NO_2_DH1 + HCI_PKT_TYPES_MASK_NO_2_DH3 + + HCI_PKT_TYPES_MASK_NO_2_DH5); } if (!bluetooth::shim::GetController()->SupportsClassic3mPhy()) { - btm_acl_pkt_types_supported |= - (HCI_PKT_TYPES_MASK_NO_3_DH1 + HCI_PKT_TYPES_MASK_NO_3_DH3 + - HCI_PKT_TYPES_MASK_NO_3_DH5); + btm_acl_pkt_types_supported |= (HCI_PKT_TYPES_MASK_NO_3_DH1 + HCI_PKT_TYPES_MASK_NO_3_DH3 + + HCI_PKT_TYPES_MASK_NO_3_DH5); } /* Check to see if 3 and 5 slot packets are available */ if (bluetooth::shim::GetController()->SupportsClassic2mPhy() || bluetooth::shim::GetController()->SupportsClassic3mPhy()) { - if (!bluetooth::shim::GetController()->Supports3SlotEdrPackets()) - btm_acl_pkt_types_supported |= - (HCI_PKT_TYPES_MASK_NO_2_DH3 + HCI_PKT_TYPES_MASK_NO_3_DH3); + if (!bluetooth::shim::GetController()->Supports3SlotEdrPackets()) { + btm_acl_pkt_types_supported |= (HCI_PKT_TYPES_MASK_NO_2_DH3 + HCI_PKT_TYPES_MASK_NO_3_DH3); + } - if (!bluetooth::shim::GetController()->Supports5SlotEdrPackets()) - btm_acl_pkt_types_supported |= - (HCI_PKT_TYPES_MASK_NO_2_DH5 + HCI_PKT_TYPES_MASK_NO_3_DH5); + if (!bluetooth::shim::GetController()->Supports5SlotEdrPackets()) { + btm_acl_pkt_types_supported |= (HCI_PKT_TYPES_MASK_NO_2_DH5 + HCI_PKT_TYPES_MASK_NO_3_DH5); + } } internal_.set_default_packet_types_supported(btm_acl_pkt_types_supported); } @@ -297,28 +283,26 @@ void BTM_acl_after_controller_started() { * nullptr if not found. * ******************************************************************************/ -tACL_CONN* StackAclBtmAcl::btm_bda_to_acl(const RawAddress& bda, - tBT_TRANSPORT transport) { +tACL_CONN* StackAclBtmAcl::btm_bda_to_acl(const RawAddress& bda, tBT_TRANSPORT transport) { tACL_CONN* p_acl = &btm_cb.acl_cb_.acl_db[0]; for (uint8_t index = 0; index < MAX_L2CAP_LINKS; index++, p_acl++) { - if ((p_acl->in_use) && p_acl->remote_addr == bda && - p_acl->transport == transport) { + if ((p_acl->in_use) && p_acl->remote_addr == bda && p_acl->transport == transport) { return p_acl; } } return nullptr; } -tACL_CONN* acl_get_connection_from_address(const RawAddress& bd_addr, - tBT_TRANSPORT transport) { +tACL_CONN* acl_get_connection_from_address(const RawAddress& bd_addr, tBT_TRANSPORT transport) { return internal_.btm_bda_to_acl(bd_addr, transport); } -void StackAclBtmAcl::btm_acl_consolidate(const RawAddress& identity_addr, - const RawAddress& rpa) { +void StackAclBtmAcl::btm_acl_consolidate(const RawAddress& identity_addr, const RawAddress& rpa) { tACL_CONN* p_acl = &btm_cb.acl_cb_.acl_db[0]; for (uint8_t index = 0; index < MAX_L2CAP_LINKS; index++, p_acl++) { - if (!p_acl->in_use) continue; + if (!p_acl->in_use) { + continue; + } if (p_acl->remote_addr == rpa) { log::info("consolidate {} -> {}", rpa, identity_addr); @@ -328,8 +312,7 @@ void StackAclBtmAcl::btm_acl_consolidate(const RawAddress& identity_addr, } } -void btm_acl_consolidate(const RawAddress& identity_addr, - const RawAddress& rpa) { +void btm_acl_consolidate(const RawAddress& identity_addr, const RawAddress& rpa) { return internal_.btm_acl_consolidate(identity_addr, rpa); } @@ -353,12 +336,14 @@ uint8_t btm_handle_to_acl_index(uint16_t hci_handle) { } /* If here, no BD Addr found */ - return (xx); + return xx; } tACL_CONN* StackAclBtmAcl::acl_get_connection_from_handle(uint16_t hci_handle) { uint8_t index = btm_handle_to_acl_index(hci_handle); - if (index >= MAX_L2CAP_LINKS) return nullptr; + if (index >= MAX_L2CAP_LINKS) { + return nullptr; + } return &btm_cb.acl_cb_.acl_db[index]; } @@ -405,8 +390,8 @@ tACL_CONN* StackAclBtmAcl::acl_allocate_connection() { return nullptr; } -void btm_acl_created(const RawAddress& bda, uint16_t hci_handle, - tHCI_ROLE link_role, tBT_TRANSPORT transport) { +void btm_acl_created(const RawAddress& bda, uint16_t hci_handle, tHCI_ROLE link_role, + tBT_TRANSPORT transport) { tACL_CONN* p_acl = internal_.btm_bda_to_acl(bda, transport); if (p_acl != (tACL_CONN*)NULL) { p_acl->hci_handle = hci_handle; @@ -416,9 +401,9 @@ void btm_acl_created(const RawAddress& bda, uint16_t hci_handle, btm_set_link_policy(p_acl, btm_cb.acl_cb_.DefaultLinkPolicy()); } log::warn( - "Unable to create duplicate acl when one already exists handle:{} " - "role:{} transport:{}", - hci_handle, RoleText(link_role), bt_transport_text(transport)); + "Unable to create duplicate acl when one already exists handle:{} " + "role:{} transport:{}", + hci_handle, RoleText(link_role), bt_transport_text(transport)); return; } @@ -438,10 +423,8 @@ void btm_acl_created(const RawAddress& bda, uint16_t hci_handle, p_acl->switch_role_failed_attempts = 0; p_acl->reset_switch_role(); - log::debug( - "Created new ACL connection peer:{} role:{} handle:0x{:04x} transport:{}", - bda, RoleText(p_acl->link_role), hci_handle, - bt_transport_text(transport)); + log::debug("Created new ACL connection peer:{} role:{} handle:0x{:04x} transport:{}", bda, + RoleText(p_acl->link_role), hci_handle, bt_transport_text(transport)); if (p_acl->is_transport_br_edr()) { BTM_PM_OnConnected(hci_handle, bda); @@ -460,8 +443,7 @@ void btm_acl_created(const RawAddress& bda, uint16_t hci_handle, btm_ble_get_acl_remote_addr(hci_handle, p_acl->active_remote_addr, &p_acl->active_remote_addr_type); - if (bluetooth::shim::GetController() - ->SupportsBlePeripheralInitiatedFeaturesExchange() || + if (bluetooth::shim::GetController()->SupportsBlePeripheralInitiatedFeaturesExchange() || link_role == HCI_ROLE_CENTRAL) { btsnd_hcic_ble_read_remote_feat(p_acl->hci_handle); } else { @@ -470,8 +452,7 @@ void btm_acl_created(const RawAddress& bda, uint16_t hci_handle, } } -void btm_acl_create_failed(const RawAddress& bda, tBT_TRANSPORT transport, - tHCI_STATUS hci_status) { +void btm_acl_create_failed(const RawAddress& bda, tBT_TRANSPORT transport, tHCI_STATUS hci_status) { BTA_dm_acl_up_failed(bda, transport, hci_status); } @@ -527,8 +508,7 @@ tBTM_STATUS BTM_GetRole(const RawAddress& remote_bd_addr, tHCI_ROLE* p_role) { } *p_role = HCI_ROLE_UNKNOWN; - tACL_CONN* p_acl = - internal_.btm_bda_to_acl(remote_bd_addr, BT_TRANSPORT_BR_EDR); + tACL_CONN* p_acl = internal_.btm_bda_to_acl(remote_bd_addr, BT_TRANSPORT_BR_EDR); if (p_acl == nullptr) { log::warn("Unable to find active acl"); return BTM_UNKNOWN_ADDR; @@ -560,8 +540,7 @@ tBTM_STATUS BTM_SwitchRoleToCentral(const RawAddress& remote_bd_addr) { return BTM_MODE_UNSUPPORTED; } - tACL_CONN* p_acl = - internal_.btm_bda_to_acl(remote_bd_addr, BT_TRANSPORT_BR_EDR); + tACL_CONN* p_acl = internal_.btm_bda_to_acl(remote_bd_addr, BT_TRANSPORT_BR_EDR); if (p_acl == nullptr) { log::warn("Unable to find active acl"); return BTM_UNKNOWN_ADDR; @@ -595,8 +574,8 @@ tBTM_STATUS BTM_SwitchRoleToCentral(const RawAddress& remote_bd_addr) { tBTM_PM_MODE pwr_mode; if (!BTM_ReadPowerMode(p_acl->remote_addr, &pwr_mode)) { log::warn( - "Unable to find device to read current power mode prior to role " - "switch"); + "Unable to find device to read current power mode prior to role " + "switch"); return BTM_UNKNOWN_ADDR; }; @@ -633,8 +612,7 @@ tBTM_STATUS BTM_SwitchRoleToCentral(const RawAddress& remote_bd_addr) { * Returns void * ******************************************************************************/ -void btm_acl_encrypt_change(uint16_t handle, uint8_t /* status */, - uint8_t encr_enable) { +void btm_acl_encrypt_change(uint16_t handle, uint8_t /* status */, uint8_t encr_enable) { tACL_CONN* p = internal_.acl_get_connection_from_handle(handle); if (p == nullptr) { log::warn("Unable to find active acl"); @@ -646,9 +624,9 @@ void btm_acl_encrypt_change(uint16_t handle, uint8_t /* status */, if (bluetooth::os::ParameterProvider::IsCommonCriteriaMode()) { if (p->is_encrypted && !encr_enable) { log::error( - "attempting to decrypt encrypted connection, disconnecting. handle: " - "0x{:x}", - handle); + "attempting to decrypt encrypted connection, disconnecting. handle: " + "0x{:x}", + handle); acl_disconnect_from_handle(handle, HCI_ERR_HOST_REJECT_SECURITY, "stack::btu::btu_hcif::read_drop_encryption " @@ -675,16 +653,14 @@ void btm_acl_encrypt_change(uint16_t handle, uint8_t /* status */, else if (p->is_switch_role_encryption_on()) { p->reset_switch_role(); p->set_encryption_idle(); - NotifyAclRoleSwitchComplete( - btm_cb.acl_cb_.switch_role_ref_data.remote_bd_addr, - btm_cb.acl_cb_.switch_role_ref_data.role, - btm_cb.acl_cb_.switch_role_ref_data.hci_status); + NotifyAclRoleSwitchComplete(btm_cb.acl_cb_.switch_role_ref_data.remote_bd_addr, + btm_cb.acl_cb_.switch_role_ref_data.role, + btm_cb.acl_cb_.switch_role_ref_data.hci_status); /* If a disconnect is pending, issue it now that role switch has completed */ if (p->rs_disc_pending == BTM_SEC_DISC_PENDING) { - disconnect_acl(*p, HCI_ERR_PEER_USER, - "stack::acl::btm_acl::encrypt after role switch"); + disconnect_acl(*p, HCI_ERR_PEER_USER, "stack::acl::btm_acl::encrypt after role switch"); } p->rs_disc_pending = BTM_SEC_RS_NOT_PENDING; /* reset flag */ } @@ -720,12 +696,10 @@ void btm_set_link_policy(tACL_CONN* conn, tLINK_POLICY policy) { interop_match_addr(INTEROP_DISABLE_SNIFF, &(conn->remote_addr))) { conn->link_policy &= (~HCI_ENABLE_SNIFF_MODE); } - btsnd_hcic_write_policy_set(conn->hci_handle, - static_cast(conn->link_policy)); + btsnd_hcic_write_policy_set(conn->hci_handle, static_cast(conn->link_policy)); } -static void btm_toggle_policy_on_for(const RawAddress& peer_addr, - uint16_t flag) { +static void btm_toggle_policy_on_for(const RawAddress& peer_addr, uint16_t flag) { auto conn = internal_.btm_bda_to_acl(peer_addr, BT_TRANSPORT_BR_EDR); if (!conn) { log::warn("Unable to find active acl"); @@ -734,8 +708,7 @@ static void btm_toggle_policy_on_for(const RawAddress& peer_addr, btm_set_link_policy(conn, conn->link_policy | flag); } -static void btm_toggle_policy_off_for(const RawAddress& peer_addr, - uint16_t flag) { +static void btm_toggle_policy_off_for(const RawAddress& peer_addr, uint16_t flag) { auto conn = internal_.btm_bda_to_acl(peer_addr, BT_TRANSPORT_BR_EDR); if (!conn) { log::warn("Unable to find active acl"); @@ -770,13 +743,12 @@ void BTM_block_role_switch_for(const RawAddress& peer_addr) { } void BTM_unblock_role_switch_and_sniff_mode_for(const RawAddress& peer_addr) { - btm_toggle_policy_on_for( - peer_addr, HCI_ENABLE_SNIFF_MODE | HCI_ENABLE_CENTRAL_PERIPHERAL_SWITCH); + btm_toggle_policy_on_for(peer_addr, HCI_ENABLE_SNIFF_MODE | HCI_ENABLE_CENTRAL_PERIPHERAL_SWITCH); } void BTM_block_role_switch_and_sniff_mode_for(const RawAddress& peer_addr) { - btm_toggle_policy_off_for( - peer_addr, HCI_ENABLE_SNIFF_MODE | HCI_ENABLE_CENTRAL_PERIPHERAL_SWITCH); + btm_toggle_policy_off_for(peer_addr, + HCI_ENABLE_SNIFF_MODE | HCI_ENABLE_CENTRAL_PERIPHERAL_SWITCH); } void StackAclBtmAcl::btm_set_default_link_policy(tLINK_POLICY settings) { @@ -790,8 +762,7 @@ void BTM_default_unblock_role_switch() { HCI_ENABLE_CENTRAL_PERIPHERAL_SWITCH); } -extern void bta_gattc_continue_discovery_if_needed(const RawAddress& bd_addr, - uint16_t acl_handle); +extern void bta_gattc_continue_discovery_if_needed(const RawAddress& bd_addr, uint16_t acl_handle); /******************************************************************************* * @@ -803,8 +774,8 @@ extern void bta_gattc_continue_discovery_if_needed(const RawAddress& bd_addr, * Returns void * ******************************************************************************/ -static void maybe_chain_more_commands_after_read_remote_version_complete( - uint8_t /* status */, uint16_t handle) { +static void maybe_chain_more_commands_after_read_remote_version_complete(uint8_t /* status */, + uint16_t handle) { tACL_CONN* p_acl_cb = internal_.acl_get_connection_from_handle(handle); if (p_acl_cb == nullptr) { log::warn("Received remote version complete for unknown device"); @@ -815,8 +786,7 @@ static void maybe_chain_more_commands_after_read_remote_version_complete( case BT_TRANSPORT_LE: l2cble_notify_le_connection(p_acl_cb->remote_addr); l2cble_use_preferred_conn_params(p_acl_cb->remote_addr); - bta_gattc_continue_discovery_if_needed(p_acl_cb->remote_addr, - p_acl_cb->Handle()); + bta_gattc_continue_discovery_if_needed(p_acl_cb->remote_addr, p_acl_cb->Handle()); break; case BT_TRANSPORT_BR_EDR: /** @@ -834,10 +804,8 @@ static void maybe_chain_more_commands_after_read_remote_version_complete( btm_iot_save_remote_versions(p_acl_cb); } -void btm_process_remote_version_complete(uint8_t status, uint16_t handle, - uint8_t lmp_version, - uint16_t manufacturer, - uint16_t lmp_subversion) { +void btm_process_remote_version_complete(uint8_t status, uint16_t handle, uint8_t lmp_version, + uint16_t manufacturer, uint16_t lmp_subversion) { tACL_CONN* p_acl_cb = internal_.acl_get_connection_from_handle(handle); if (p_acl_cb == nullptr) { log::warn("Received remote version complete for unknown acl"); @@ -850,22 +818,18 @@ void btm_process_remote_version_complete(uint8_t status, uint16_t handle, p_acl_cb->remote_version_info.manufacturer = manufacturer; p_acl_cb->remote_version_info.lmp_subversion = lmp_subversion; p_acl_cb->remote_version_info.valid = true; - BTM_update_version_info(p_acl_cb->RemoteAddress(), - p_acl_cb->remote_version_info); + BTM_update_version_info(p_acl_cb->RemoteAddress(), p_acl_cb->remote_version_info); - bluetooth::common::LogRemoteVersionInfo(handle, status, lmp_version, - manufacturer, lmp_subversion); + bluetooth::common::LogRemoteVersionInfo(handle, status, lmp_version, manufacturer, + lmp_subversion); } else { bluetooth::common::LogRemoteVersionInfo(handle, status, 0, 0, 0); } } -void btm_read_remote_version_complete(tHCI_STATUS status, uint16_t handle, - uint8_t lmp_version, - uint16_t manufacturer, - uint16_t lmp_subversion) { - btm_process_remote_version_complete(status, handle, lmp_version, manufacturer, - lmp_subversion); +void btm_read_remote_version_complete(tHCI_STATUS status, uint16_t handle, uint8_t lmp_version, + uint16_t manufacturer, uint16_t lmp_subversion) { + btm_process_remote_version_complete(status, handle, lmp_version, manufacturer, lmp_subversion); maybe_chain_more_commands_after_read_remote_version_complete(status, handle); } @@ -879,27 +843,20 @@ void btm_read_remote_version_complete(tHCI_STATUS status, uint16_t handle, * Returns void * ******************************************************************************/ -void btm_process_remote_ext_features(tACL_CONN* p_acl_cb, - uint8_t max_page_number) { +void btm_process_remote_ext_features(tACL_CONN* p_acl_cb, uint8_t max_page_number) { log::assert_that(p_acl_cb != nullptr, "assert failed: p_acl_cb != nullptr"); if (!p_acl_cb->peer_lmp_feature_valid[max_page_number]) { log::warn("Checking remote features but remote feature read is incomplete"); } - bool ssp_supported = - HCI_SSP_HOST_SUPPORTED(p_acl_cb->peer_lmp_feature_pages[1]); - bool secure_connections_supported = - HCI_SC_HOST_SUPPORTED(p_acl_cb->peer_lmp_feature_pages[1]); - bool role_switch_supported = - HCI_SWITCH_SUPPORTED(p_acl_cb->peer_lmp_feature_pages[0]); - bool br_edr_supported = - !HCI_BREDR_NOT_SPT_SUPPORTED(p_acl_cb->peer_lmp_feature_pages[0]); - bool le_supported = - HCI_LE_SPT_SUPPORTED(p_acl_cb->peer_lmp_feature_pages[0]) && - HCI_LE_HOST_SUPPORTED(p_acl_cb->peer_lmp_feature_pages[1]); - btm_sec_set_peer_sec_caps(p_acl_cb->hci_handle, ssp_supported, - secure_connections_supported, role_switch_supported, - br_edr_supported, le_supported); + bool ssp_supported = HCI_SSP_HOST_SUPPORTED(p_acl_cb->peer_lmp_feature_pages[1]); + bool secure_connections_supported = HCI_SC_HOST_SUPPORTED(p_acl_cb->peer_lmp_feature_pages[1]); + bool role_switch_supported = HCI_SWITCH_SUPPORTED(p_acl_cb->peer_lmp_feature_pages[0]); + bool br_edr_supported = !HCI_BREDR_NOT_SPT_SUPPORTED(p_acl_cb->peer_lmp_feature_pages[0]); + bool le_supported = HCI_LE_SPT_SUPPORTED(p_acl_cb->peer_lmp_feature_pages[0]) && + HCI_LE_HOST_SUPPORTED(p_acl_cb->peer_lmp_feature_pages[1]); + btm_sec_set_peer_sec_caps(p_acl_cb->hci_handle, ssp_supported, secure_connections_supported, + role_switch_supported, br_edr_supported, le_supported); } /******************************************************************************* @@ -957,8 +914,7 @@ void btm_read_remote_ext_features_complete_raw(uint8_t* p, uint8_t evt_len) { btm_read_remote_ext_features_complete(handle, page_num, max_page, p); } -void btm_read_remote_ext_features_complete(uint16_t handle, uint8_t page_num, - uint8_t max_page, +void btm_read_remote_ext_features_complete(uint16_t handle, uint8_t page_num, uint8_t max_page, uint8_t* features) { /* Validate parameters */ auto* p_acl_cb = internal_.acl_get_connection_from_handle(handle); @@ -968,16 +924,14 @@ void btm_read_remote_ext_features_complete(uint16_t handle, uint8_t page_num, } /* Copy the received features page */ - STREAM_TO_ARRAY(p_acl_cb->peer_lmp_feature_pages[page_num], features, - HCI_FEATURE_BYTES_PER_PAGE); + STREAM_TO_ARRAY(p_acl_cb->peer_lmp_feature_pages[page_num], features, HCI_FEATURE_BYTES_PER_PAGE); p_acl_cb->peer_lmp_feature_valid[page_num] = true; /* save remote extended features to iot conf file */ std::string key = IOT_CONF_KEY_RT_EXT_FEATURES "_" + std::to_string(page_num); DEVICE_IOT_CONFIG_ADDR_SET_BIN(p_acl_cb->remote_addr, key, - p_acl_cb->peer_lmp_feature_pages[page_num], - BD_FEATURES_LEN); + p_acl_cb->peer_lmp_feature_pages[page_num], BD_FEATURES_LEN); /* If there is the next remote features page and * we have space to keep this page data - read this page */ @@ -1042,21 +996,17 @@ void StackAclBtmAcl::btm_establish_continue(tACL_CONN* p_acl) { /* For now there are a some devices that do not like sending */ /* commands events and data at the same time. */ /* Set the packet types to the default allowed by the device */ - const uint16_t default_packet_type_mask = - btm_cb.acl_cb_.DefaultPacketTypes(); - if (!internal_.change_connection_packet_types(*p_acl, - default_packet_type_mask)) { - log::error( - "Unable to change connection packet type types:{:04x} address:{}", - default_packet_type_mask, p_acl->RemoteAddress()); + const uint16_t default_packet_type_mask = btm_cb.acl_cb_.DefaultPacketTypes(); + if (!internal_.change_connection_packet_types(*p_acl, default_packet_type_mask)) { + log::error("Unable to change connection packet type types:{:04x} address:{}", + default_packet_type_mask, p_acl->RemoteAddress()); } btm_set_link_policy(p_acl, btm_cb.acl_cb_.DefaultLinkPolicy()); } NotifyAclLinkUp(*p_acl); } -void btm_establish_continue_from_address(const RawAddress& bda, - tBT_TRANSPORT transport) { +void btm_establish_continue_from_address(const RawAddress& bda, tBT_TRANSPORT transport) { tACL_CONN* p_acl = internal_.btm_bda_to_acl(bda, transport); if (p_acl == nullptr) { log::warn("Unable to find active acl"); @@ -1074,11 +1024,9 @@ void btm_establish_continue_from_address(const RawAddress& bda, * Returns status of the operation * ******************************************************************************/ -tBTM_STATUS BTM_GetLinkSuperTout(const RawAddress& remote_bda, - uint16_t* p_timeout) { +tBTM_STATUS BTM_GetLinkSuperTout(const RawAddress& remote_bda, uint16_t* p_timeout) { log::assert_that(p_timeout != nullptr, "assert failed: p_timeout != nullptr"); - const tACL_CONN* p_acl = - internal_.btm_bda_to_acl(remote_bda, BT_TRANSPORT_BR_EDR); + const tACL_CONN* p_acl = internal_.btm_bda_to_acl(remote_bda, BT_TRANSPORT_BR_EDR); if (p_acl == nullptr) { log::warn("Unable to find active acl"); return BTM_UNKNOWN_ADDR; @@ -1096,8 +1044,7 @@ tBTM_STATUS BTM_GetLinkSuperTout(const RawAddress& remote_bda, * Returns status of the operation * ******************************************************************************/ -tBTM_STATUS BTM_SetLinkSuperTout(const RawAddress& remote_bda, - uint16_t timeout) { +tBTM_STATUS BTM_SetLinkSuperTout(const RawAddress& remote_bda, uint16_t timeout) { tACL_CONN* p_acl = internal_.btm_bda_to_acl(remote_bda, BT_TRANSPORT_BR_EDR); if (p_acl == nullptr) { log::warn("Unable to find active acl"); @@ -1107,11 +1054,11 @@ tBTM_STATUS BTM_SetLinkSuperTout(const RawAddress& remote_bda, /* Only send if current role is Central; 2.0 spec requires this */ if (p_acl->link_role == HCI_ROLE_CENTRAL) { if (!bluetooth::shim::GetController()->IsSupported( - bluetooth::hci::OpCode::WRITE_LINK_SUPERVISION_TIMEOUT)) { + bluetooth::hci::OpCode::WRITE_LINK_SUPERVISION_TIMEOUT)) { log::warn( - "UNSUPPORTED by controller write link supervision timeout:{:.2f}ms " - "bd_addr:{}", - supervision_timeout_to_seconds(timeout), remote_bda); + "UNSUPPORTED by controller write link supervision timeout:{:.2f}ms " + "bd_addr:{}", + supervision_timeout_to_seconds(timeout), remote_bda); return BTM_MODE_UNSUPPORTED; } p_acl->link_super_tout = timeout; @@ -1121,20 +1068,18 @@ tBTM_STATUS BTM_SetLinkSuperTout(const RawAddress& remote_bda, return BTM_CMD_STARTED; } else { log::warn( - "Role is peripheral so unable to set supervision timeout:{:.2f}ms " - "bd_addr:{}", - supervision_timeout_to_seconds(timeout), remote_bda); + "Role is peripheral so unable to set supervision timeout:{:.2f}ms " + "bd_addr:{}", + supervision_timeout_to_seconds(timeout), remote_bda); return BTM_SUCCESS; } } -bool BTM_IsAclConnectionUp(const RawAddress& remote_bda, - tBT_TRANSPORT transport) { +bool BTM_IsAclConnectionUp(const RawAddress& remote_bda, tBT_TRANSPORT transport) { return internal_.btm_bda_to_acl(remote_bda, transport) != nullptr; } -bool BTM_IsAclConnectionUpAndHandleValid(const RawAddress& remote_bda, - tBT_TRANSPORT transport) { +bool BTM_IsAclConnectionUpAndHandleValid(const RawAddress& remote_bda, tBT_TRANSPORT transport) { tACL_CONN* p_acl = internal_.btm_bda_to_acl(remote_bda, transport); if (p_acl == nullptr) { return false; @@ -1166,9 +1111,7 @@ uint16_t BTM_GetNumAclLinks(void) { * Returns true if connection is up, else false. * ******************************************************************************/ -tHCI_REASON btm_get_acl_disc_reason_code(void) { - return btm_cb.acl_cb_.get_disconnect_reason(); -} +tHCI_REASON btm_get_acl_disc_reason_code(void) { return btm_cb.acl_cb_.get_disconnect_reason(); } /******************************************************************************* * @@ -1180,9 +1123,7 @@ tHCI_REASON btm_get_acl_disc_reason_code(void) { * Returns true if connection is locally initiated, else false. * ******************************************************************************/ -bool btm_is_acl_locally_initiated(void) { - return btm_cb.acl_cb_.is_locally_initiated(); -} +bool btm_is_acl_locally_initiated(void) { return btm_cb.acl_cb_.is_locally_initiated(); } /******************************************************************************* * @@ -1194,12 +1135,11 @@ bool btm_is_acl_locally_initiated(void) { * Returns the handle of the connection, or HCI_INVALID_HANDLE if none. * ******************************************************************************/ -uint16_t BTM_GetHCIConnHandle(const RawAddress& remote_bda, - tBT_TRANSPORT transport) { +uint16_t BTM_GetHCIConnHandle(const RawAddress& remote_bda, tBT_TRANSPORT transport) { tACL_CONN* p; p = internal_.btm_bda_to_acl(remote_bda, transport); if (p != (tACL_CONN*)NULL) { - return (p->hci_handle); + return p->hci_handle; } /* If here, no BD Addr found */ @@ -1263,12 +1203,12 @@ uint8_t BTM_GetPeerSCA(const RawAddress& remote_bda, tBT_TRANSPORT transport) { tACL_CONN* p; p = internal_.btm_bda_to_acl(remote_bda, transport); if (p != (tACL_CONN*)NULL) { - return (p->sca); + return p->sca; } log::warn("Unable to find active acl"); /* If here, no BD Addr found */ - return (0xFF); + return 0xFF; } /******************************************************************************* @@ -1285,8 +1225,7 @@ uint8_t BTM_GetPeerSCA(const RawAddress& remote_bda, tBT_TRANSPORT transport) { * Returns void * *******************************************************************************/ -void btm_rejectlist_role_change_device(const RawAddress& bd_addr, - uint8_t hci_status) { +void btm_rejectlist_role_change_device(const RawAddress& bd_addr, uint8_t hci_status) { tACL_CONN* p = internal_.btm_bda_to_acl(bd_addr, BT_TRANSPORT_BR_EDR); if (!p) { @@ -1299,22 +1238,21 @@ void btm_rejectlist_role_change_device(const RawAddress& bd_addr, } /* check for carkits */ - const uint32_t cod_audio_device = - (BTM_COD_SERVICE_AUDIO | BTM_COD_MAJOR_AUDIO) << 8; + const uint32_t cod_audio_device = (BTM_COD_SERVICE_AUDIO | BTM_COD_MAJOR_AUDIO) << 8; DEV_CLASS dev_class = btm_get_dev_class(bd_addr); - if (dev_class == kDevClassEmpty) return; - const uint32_t cod = - ((dev_class[0] << 16) | (dev_class[1] << 8) | dev_class[2]) & 0xffffff; - if ((hci_status != HCI_SUCCESS) && - (p->is_switch_role_switching_or_in_progress()) && + if (dev_class == kDevClassEmpty) { + return; + } + const uint32_t cod = ((dev_class[0] << 16) | (dev_class[1] << 8) | dev_class[2]) & 0xffffff; + if ((hci_status != HCI_SUCCESS) && (p->is_switch_role_switching_or_in_progress()) && ((cod & cod_audio_device) == cod_audio_device) && (!interop_match_addr(INTEROP_DYNAMIC_ROLE_SWITCH, &bd_addr))) { p->switch_role_failed_attempts++; if (p->switch_role_failed_attempts == BTM_MAX_SW_ROLE_FAILED_ATTEMPTS) { log::warn( - "Device {} rejectlisted for role switching - multiple role switch " - "failed attempts: {}", - bd_addr, p->switch_role_failed_attempts); + "Device {} rejectlisted for role switching - multiple role switch " + "failed attempts: {}", + bd_addr, p->switch_role_failed_attempts); interop_database_add(INTEROP_DYNAMIC_ROLE_SWITCH, &bd_addr, 3); } } @@ -1333,14 +1271,12 @@ void btm_rejectlist_role_change_device(const RawAddress& bd_addr, * ******************************************************************************/ -void acl_cache_role(const RawAddress& bd_addr, tHCI_ROLE new_role, - bool overwrite_cache) { +void acl_cache_role(const RawAddress& bd_addr, tHCI_ROLE new_role, bool overwrite_cache) { if (overwrite_cache || delayed_role_change_ == nullptr) { RoleChangeView role_change; role_change.new_role = new_role; role_change.bd_addr = bd_addr; - delayed_role_change_ = - std::make_unique(std::move(role_change)); + delayed_role_change_ = std::make_unique(std::move(role_change)); } } @@ -1356,8 +1292,7 @@ void acl_cache_role(const RawAddress& bd_addr, tHCI_ROLE new_role, * Returns void * ******************************************************************************/ -void StackAclBtmAcl::btm_acl_role_changed(tHCI_STATUS hci_status, - const RawAddress& bd_addr, +void StackAclBtmAcl::btm_acl_role_changed(tHCI_STATUS hci_status, const RawAddress& bd_addr, tHCI_ROLE new_role) { tACL_CONN* p_acl = internal_.btm_bda_to_acl(bd_addr, BT_TRANSPORT_BR_EDR); if (p_acl == nullptr) { @@ -1369,8 +1304,8 @@ void StackAclBtmAcl::btm_acl_role_changed(tHCI_STATUS hci_status, } tBTM_ROLE_SWITCH_CMPL* p_switch_role = &btm_cb.acl_cb_.switch_role_ref_data; - log::debug("Role change event received peer:{} hci_status:{} new_role:{}", - bd_addr, hci_error_code_text(hci_status), RoleText(new_role)); + log::debug("Role change event received peer:{} hci_status:{} new_role:{}", bd_addr, + hci_error_code_text(hci_status), RoleText(new_role)); p_switch_role->hci_status = hci_status; if (hci_status == HCI_SUCCESS) { @@ -1384,7 +1319,7 @@ void StackAclBtmAcl::btm_acl_role_changed(tHCI_STATUS hci_status, * switch */ if (new_role == HCI_ROLE_CENTRAL) { uint16_t link_supervision_timeout = - osi_property_get_int32(PROPERTY_LINK_SUPERVISION_TIMEOUT, 8000); + osi_property_get_int32(PROPERTY_LINK_SUPERVISION_TIMEOUT, 8000); BTM_SetLinkSuperTout(bd_addr, link_supervision_timeout); } } else { @@ -1414,21 +1349,18 @@ void StackAclBtmAcl::btm_acl_role_changed(tHCI_STATUS hci_status, /* If a disconnect is pending, issue it now that role switch has completed */ if (p_acl->rs_disc_pending == BTM_SEC_DISC_PENDING) { - disconnect_acl(*p_acl, HCI_ERR_PEER_USER, - "stack::acl::btm_acl::role after role switch"); + disconnect_acl(*p_acl, HCI_ERR_PEER_USER, "stack::acl::btm_acl::role after role switch"); } p_acl->rs_disc_pending = BTM_SEC_RS_NOT_PENDING; /* reset flag */ } -void btm_acl_role_changed(tHCI_STATUS hci_status, const RawAddress& bd_addr, - tHCI_ROLE new_role) { +void btm_acl_role_changed(tHCI_STATUS hci_status, const RawAddress& bd_addr, tHCI_ROLE new_role) { btm_rejectlist_role_change_device(bd_addr, hci_status); if (hci_status == HCI_SUCCESS) { l2c_link_role_changed(&bd_addr, new_role, hci_status); } else { - l2c_link_role_changed(nullptr, HCI_ROLE_UNKNOWN, - HCI_ERR_COMMAND_DISALLOWED); + l2c_link_role_changed(nullptr, HCI_ROLE_UNKNOWN, HCI_ERR_COMMAND_DISALLOWED); } internal_.btm_acl_role_changed(hci_status, bd_addr, new_role); } @@ -1444,19 +1376,17 @@ void btm_acl_role_changed(tHCI_STATUS hci_status, const RawAddress& bd_addr, * Returns status of the operation * ******************************************************************************/ -bool StackAclBtmAcl::change_connection_packet_types( - tACL_CONN& link, const uint16_t new_packet_type_mask) { +bool StackAclBtmAcl::change_connection_packet_types(tACL_CONN& link, + const uint16_t new_packet_type_mask) { // Start with the default configured packet types const uint16_t default_packet_type_mask = btm_cb.acl_cb_.DefaultPacketTypes(); uint16_t packet_type_mask = - default_packet_type_mask & - (new_packet_type_mask & BTM_ACL_SUPPORTED_PKTS_MASK); + default_packet_type_mask & (new_packet_type_mask & BTM_ACL_SUPPORTED_PKTS_MASK); /* OR in any exception packet types if at least 2.0 version of spec */ - packet_type_mask |= - ((new_packet_type_mask & BTM_ACL_EXCEPTION_PKTS_MASK) | - (BTM_ACL_EXCEPTION_PKTS_MASK & default_packet_type_mask)); + packet_type_mask |= ((new_packet_type_mask & BTM_ACL_EXCEPTION_PKTS_MASK) | + (BTM_ACL_EXCEPTION_PKTS_MASK & default_packet_type_mask)); /* Exclude packet types not supported by the peer */ if (link.peer_lmp_feature_valid[0]) { @@ -1465,26 +1395,24 @@ bool StackAclBtmAcl::change_connection_packet_types( packet_type_mask |= peer_packet_types.acl.unsupported; } else { log::info( - "Unable to include remote supported packet types as read feature " - "incomplete"); + "Unable to include remote supported packet types as read feature " + "incomplete"); log::info("TIP: Maybe wait until read feature complete beforehand"); } if (packet_type_mask == 0) { - log::warn("Unable to send controller illegal change packet mask:0x{:04x}", - packet_type_mask); + log::warn("Unable to send controller illegal change packet mask:0x{:04x}", packet_type_mask); return false; } link.pkt_types_mask = packet_type_mask; GetInterface().ChangeConnectionPacketType(link.Handle(), link.pkt_types_mask); - log::debug("Started change connection packet type:0x{:04x} address:{}", - link.pkt_types_mask, link.RemoteAddress()); + log::debug("Started change connection packet type:0x{:04x} address:{}", link.pkt_types_mask, + link.RemoteAddress()); return true; } -void btm_set_packet_types_from_address(const RawAddress& bd_addr, - uint16_t pkt_types) { +void btm_set_packet_types_from_address(const RawAddress& bd_addr, uint16_t pkt_types) { tACL_CONN* p_acl = internal_.btm_bda_to_acl(bd_addr, BT_TRANSPORT_BR_EDR); if (p_acl == nullptr) { log::warn("Unable to find active acl"); @@ -1492,9 +1420,8 @@ void btm_set_packet_types_from_address(const RawAddress& bd_addr, } if (!internal_.change_connection_packet_types(*p_acl, pkt_types)) { - log::error( - "Unable to change connection packet type types:{:04x} address:{}", - pkt_types, bd_addr); + log::error("Unable to change connection packet type types:{:04x} address:{}", pkt_types, + bd_addr); } } @@ -1514,40 +1441,40 @@ uint16_t BTM_GetMaxPacketSize(const RawAddress& addr) { pkt_types = p->pkt_types_mask; } else { /* Special case for when info for the local device is requested */ - if (addr == bluetooth::ToRawAddress( - bluetooth::shim::GetController()->GetMacAddress())) { + if (addr == bluetooth::ToRawAddress(bluetooth::shim::GetController()->GetMacAddress())) { pkt_types = btm_cb.acl_cb_.DefaultPacketTypes(); } } if (pkt_types) { - if (!(pkt_types & HCI_PKT_TYPES_MASK_NO_3_DH5)) + if (!(pkt_types & HCI_PKT_TYPES_MASK_NO_3_DH5)) { pkt_size = HCI_EDR3_DH5_PACKET_SIZE; - else if (!(pkt_types & HCI_PKT_TYPES_MASK_NO_2_DH5)) + } else if (!(pkt_types & HCI_PKT_TYPES_MASK_NO_2_DH5)) { pkt_size = HCI_EDR2_DH5_PACKET_SIZE; - else if (!(pkt_types & HCI_PKT_TYPES_MASK_NO_3_DH3)) + } else if (!(pkt_types & HCI_PKT_TYPES_MASK_NO_3_DH3)) { pkt_size = HCI_EDR3_DH3_PACKET_SIZE; - else if (pkt_types & HCI_PKT_TYPES_MASK_DH5) + } else if (pkt_types & HCI_PKT_TYPES_MASK_DH5) { pkt_size = HCI_DH5_PACKET_SIZE; - else if (!(pkt_types & HCI_PKT_TYPES_MASK_NO_2_DH3)) + } else if (!(pkt_types & HCI_PKT_TYPES_MASK_NO_2_DH3)) { pkt_size = HCI_EDR2_DH3_PACKET_SIZE; - else if (pkt_types & HCI_PKT_TYPES_MASK_DM5) + } else if (pkt_types & HCI_PKT_TYPES_MASK_DM5) { pkt_size = HCI_DM5_PACKET_SIZE; - else if (pkt_types & HCI_PKT_TYPES_MASK_DH3) + } else if (pkt_types & HCI_PKT_TYPES_MASK_DH3) { pkt_size = HCI_DH3_PACKET_SIZE; - else if (pkt_types & HCI_PKT_TYPES_MASK_DM3) + } else if (pkt_types & HCI_PKT_TYPES_MASK_DM3) { pkt_size = HCI_DM3_PACKET_SIZE; - else if (!(pkt_types & HCI_PKT_TYPES_MASK_NO_3_DH1)) + } else if (!(pkt_types & HCI_PKT_TYPES_MASK_NO_3_DH1)) { pkt_size = HCI_EDR3_DH1_PACKET_SIZE; - else if (!(pkt_types & HCI_PKT_TYPES_MASK_NO_2_DH1)) + } else if (!(pkt_types & HCI_PKT_TYPES_MASK_NO_2_DH1)) { pkt_size = HCI_EDR2_DH1_PACKET_SIZE; - else if (pkt_types & HCI_PKT_TYPES_MASK_DH1) + } else if (pkt_types & HCI_PKT_TYPES_MASK_DH1) { pkt_size = HCI_DH1_PACKET_SIZE; - else if (pkt_types & HCI_PKT_TYPES_MASK_DM1) + } else if (pkt_types & HCI_PKT_TYPES_MASK_DM1) { pkt_size = HCI_DM1_PACKET_SIZE; + } } - return (pkt_size); + return pkt_size; } /******************************************************************************* @@ -1574,8 +1501,8 @@ bool BTM_IsRemoteVersionReceived(const RawAddress& addr) { * Returns If connected report peer device info * ******************************************************************************/ -bool BTM_ReadRemoteVersion(const RawAddress& addr, uint8_t* lmp_version, - uint16_t* manufacturer, uint16_t* lmp_sub_version) { +bool BTM_ReadRemoteVersion(const RawAddress& addr, uint8_t* lmp_version, uint16_t* manufacturer, + uint16_t* lmp_sub_version) { const tACL_CONN* p_acl = internal_.btm_bda_to_acl(addr, BT_TRANSPORT_BR_EDR); if (p_acl == nullptr) { p_acl = internal_.btm_bda_to_acl(addr, BT_TRANSPORT_LE); @@ -1590,12 +1517,17 @@ bool BTM_ReadRemoteVersion(const RawAddress& addr, uint8_t* lmp_version, return false; } - if (lmp_version) *lmp_version = p_acl->remote_version_info.lmp_version; + if (lmp_version) { + *lmp_version = p_acl->remote_version_info.lmp_version; + } - if (manufacturer) *manufacturer = p_acl->remote_version_info.manufacturer; + if (manufacturer) { + *manufacturer = p_acl->remote_version_info.manufacturer; + } - if (lmp_sub_version) + if (lmp_sub_version) { *lmp_sub_version = p_acl->remote_version_info.lmp_subversion; + } return true; } @@ -1611,10 +1543,10 @@ uint8_t* BTM_ReadRemoteFeatures(const RawAddress& addr) { tACL_CONN* p = internal_.btm_bda_to_acl(addr, BT_TRANSPORT_BR_EDR); if (p == NULL) { log::warn("Unable to find active acl"); - return (NULL); + return NULL; } - return (p->peer_lmp_feature_pages[0]); + return p->peer_lmp_feature_pages[0]; } /******************************************************************************* @@ -1635,7 +1567,9 @@ tBTM_STATUS BTM_ReadRSSI(const RawAddress& remote_bda, tBTM_CMPL_CB* p_cb) { tBLE_ADDR_TYPE addr_type; /* If someone already waiting on the version, do not allow another */ - if (btm_cb.devcb.p_rssi_cmpl_cb) return (BTM_BUSY); + if (btm_cb.devcb.p_rssi_cmpl_cb) { + return BTM_BUSY; + } BTM_ReadDevInfo(remote_bda, &dev_type, &addr_type); @@ -1653,12 +1587,12 @@ tBTM_STATUS BTM_ReadRSSI(const RawAddress& remote_bda, tBTM_CMPL_CB* p_cb) { btm_read_rssi_timeout, NULL); btsnd_hcic_read_rssi(p->hci_handle); - return (BTM_CMD_STARTED); + return BTM_CMD_STARTED; } log::warn("Unable to find active acl"); /* If here, no BD Addr found */ - return (BTM_UNKNOWN_ADDR); + return BTM_UNKNOWN_ADDR; } /******************************************************************************* @@ -1672,33 +1606,35 @@ tBTM_STATUS BTM_ReadRSSI(const RawAddress& remote_bda, tBTM_CMPL_CB* p_cb) { * Returns BTM_CMD_STARTED if successfully initiated or error code * ******************************************************************************/ -tBTM_STATUS BTM_ReadFailedContactCounter(const RawAddress& remote_bda, - tBTM_CMPL_CB* p_cb) { +tBTM_STATUS BTM_ReadFailedContactCounter(const RawAddress& remote_bda, tBTM_CMPL_CB* p_cb) { tACL_CONN* p; tBT_TRANSPORT transport = BT_TRANSPORT_BR_EDR; tBT_DEVICE_TYPE dev_type; tBLE_ADDR_TYPE addr_type; /* If someone already waiting on the result, do not allow another */ - if (btm_cb.devcb.p_failed_contact_counter_cmpl_cb) return (BTM_BUSY); + if (btm_cb.devcb.p_failed_contact_counter_cmpl_cb) { + return BTM_BUSY; + } BTM_ReadDevInfo(remote_bda, &dev_type, &addr_type); - if (dev_type == BT_DEVICE_TYPE_BLE) transport = BT_TRANSPORT_LE; + if (dev_type == BT_DEVICE_TYPE_BLE) { + transport = BT_TRANSPORT_LE; + } p = internal_.btm_bda_to_acl(remote_bda, transport); if (p != (tACL_CONN*)NULL) { btm_cb.devcb.p_failed_contact_counter_cmpl_cb = p_cb; - alarm_set_on_mloop(btm_cb.devcb.read_failed_contact_counter_timer, - BTM_DEV_REPLY_TIMEOUT_MS, + alarm_set_on_mloop(btm_cb.devcb.read_failed_contact_counter_timer, BTM_DEV_REPLY_TIMEOUT_MS, btm_read_failed_contact_counter_timeout, NULL); btsnd_hcic_read_failed_contact_counter(p->hci_handle); - return (BTM_CMD_STARTED); + return BTM_CMD_STARTED; } log::warn("Unable to find active acl"); /* If here, no BD Addr found */ - return (BTM_UNKNOWN_ADDR); + return BTM_UNKNOWN_ADDR; } /******************************************************************************* @@ -1713,8 +1649,8 @@ tBTM_STATUS BTM_ReadFailedContactCounter(const RawAddress& remote_bda, * Returns BTM_CMD_STARTED if successfully initiated or error code * ******************************************************************************/ -tBTM_STATUS BTM_ReadTxPower(const RawAddress& remote_bda, - tBT_TRANSPORT transport, tBTM_CMPL_CB* p_cb) { +tBTM_STATUS BTM_ReadTxPower(const RawAddress& remote_bda, tBT_TRANSPORT transport, + tBTM_CMPL_CB* p_cb) { tACL_CONN* p; #define BTM_READ_RSSI_TYPE_CUR 0x00 #define BTM_READ_RSSI_TYPE_MAX 0X01 @@ -1722,14 +1658,15 @@ tBTM_STATUS BTM_ReadTxPower(const RawAddress& remote_bda, log::verbose("RemBdAddr: {}", remote_bda); /* If someone already waiting on the version, do not allow another */ - if (btm_cb.devcb.p_tx_power_cmpl_cb) return (BTM_BUSY); + if (btm_cb.devcb.p_tx_power_cmpl_cb) { + return BTM_BUSY; + } p = internal_.btm_bda_to_acl(remote_bda, transport); if (p != (tACL_CONN*)NULL) { btm_cb.devcb.p_tx_power_cmpl_cb = p_cb; - alarm_set_on_mloop(btm_cb.devcb.read_tx_power_timer, - BTM_DEV_REPLY_TIMEOUT_MS, btm_read_tx_power_timeout, - NULL); + alarm_set_on_mloop(btm_cb.devcb.read_tx_power_timer, BTM_DEV_REPLY_TIMEOUT_MS, + btm_read_tx_power_timeout, NULL); if (p->transport == BT_TRANSPORT_LE) { btm_cb.devcb.read_tx_pwr_addr = remote_bda; @@ -1738,13 +1675,13 @@ tBTM_STATUS BTM_ReadTxPower(const RawAddress& remote_bda, btsnd_hcic_read_tx_power(p->hci_handle, BTM_READ_RSSI_TYPE_CUR); } - return (BTM_CMD_STARTED); + return BTM_CMD_STARTED; } log::warn("Unable to find active acl"); /* If here, no BD Addr found */ - return (BTM_UNKNOWN_ADDR); + return BTM_UNKNOWN_ADDR; } /******************************************************************************* @@ -1759,7 +1696,9 @@ tBTM_STATUS BTM_ReadTxPower(const RawAddress& remote_bda, void btm_read_tx_power_timeout(void* /* data */) { tBTM_CMPL_CB* p_cb = btm_cb.devcb.p_tx_power_cmpl_cb; btm_cb.devcb.p_tx_power_cmpl_cb = NULL; - if (p_cb) (*p_cb)((void*)NULL); + if (p_cb) { + (*p_cb)((void*)NULL); + } } /******************************************************************************* @@ -1812,9 +1751,8 @@ void btm_read_tx_power_complete(uint8_t* p, uint16_t evt_len, bool is_ble) { STREAM_TO_UINT8(result.tx_power, p); result.rem_bda = btm_cb.devcb.read_tx_pwr_addr; } - log::debug( - "Transmit power complete: tx_power:{} hci status:{}", result.tx_power, - hci_error_code_text(static_cast(result.hci_status))); + log::debug("Transmit power complete: tx_power:{} hci status:{}", result.tx_power, + hci_error_code_text(static_cast(result.hci_status))); } else { result.status = BTM_ERR_PROCESSING; } @@ -1824,8 +1762,8 @@ void btm_read_tx_power_complete(uint8_t* p, uint16_t evt_len, bool is_ble) { return; - err_out: - log::error("Bogus event packet, too short"); +err_out: + log::error("Bogus event packet, too short"); } /******************************************************************************* @@ -1842,7 +1780,9 @@ void btm_read_rssi_timeout(void* /* data */) { tBTM_CMPL_CB* p_cb = btm_cb.devcb.p_rssi_cmpl_cb; btm_cb.devcb.p_rssi_cmpl_cb = NULL; result.status = BTM_DEVICE_TIMEOUT; - if (p_cb) (*p_cb)(&result); + if (p_cb) { + (*p_cb)(&result); + } } /******************************************************************************* @@ -1894,8 +1834,8 @@ void btm_read_rssi_complete(uint8_t* p, uint16_t evt_len) { return; - err_out: - log::error("Bogus event packet, too short"); +err_out: + log::error("Bogus event packet, too short"); } /******************************************************************************* @@ -1912,7 +1852,9 @@ void btm_read_failed_contact_counter_timeout(void* /* data */) { tBTM_CMPL_CB* p_cb = btm_cb.devcb.p_failed_contact_counter_cmpl_cb; btm_cb.devcb.p_failed_contact_counter_cmpl_cb = NULL; result.status = BTM_DEVICE_TIMEOUT; - if (p_cb) (*p_cb)(&result); + if (p_cb) { + (*p_cb)(&result); + } } /******************************************************************************* @@ -1989,10 +1931,9 @@ void btm_read_automatic_flush_timeout_complete(uint8_t* p) { STREAM_TO_UINT16(handle, p); STREAM_TO_UINT16(result.automatic_flush_timeout, p); - log::debug( - "Read automatic flush timeout complete timeout:{} hci_status:{}", - result.automatic_flush_timeout, - hci_error_code_text(static_cast(result.hci_status))); + log::debug("Read automatic flush timeout complete timeout:{} hci_status:{}", + result.automatic_flush_timeout, + hci_error_code_text(static_cast(result.hci_status))); tACL_CONN* p_acl_cb = internal_.acl_get_connection_from_handle(handle); if (p_acl_cb != nullptr) { @@ -2028,15 +1969,14 @@ tBTM_STATUS btm_remove_acl(const RawAddress& bd_addr, tBT_TRANSPORT transport) { if (p_acl->rs_disc_pending == BTM_SEC_RS_PENDING) { log::debug( - "Delay disconnect until role switch is complete bd_addr:{} " - "transport:{}", - bd_addr, bt_transport_text(transport)); + "Delay disconnect until role switch is complete bd_addr:{} " + "transport:{}", + bd_addr, bt_transport_text(transport)); p_acl->rs_disc_pending = BTM_SEC_DISC_PENDING; return BTM_SUCCESS; } - disconnect_acl(*p_acl, HCI_ERR_PEER_USER, - "stack::acl::btm_acl::btm_remove_acl"); + disconnect_acl(*p_acl, HCI_ERR_PEER_USER, "stack::acl::btm_acl::btm_remove_acl"); return BTM_SUCCESS; } @@ -2085,10 +2025,8 @@ bool BTM_BLE_IS_RESOLVE_BDA(const RawAddress& x) { } bool acl_refresh_remote_address(const RawAddress& identity_address, - tBLE_ADDR_TYPE identity_address_type, - const RawAddress& bda, - tBLE_RAND_ADDR_TYPE rra_type, - const RawAddress& rpa) { + tBLE_ADDR_TYPE identity_address_type, const RawAddress& bda, + tBLE_RAND_ADDR_TYPE rra_type, const RawAddress& rpa) { tACL_CONN* p_acl = internal_.btm_bda_to_acl(bda, BT_TRANSPORT_LE); if (p_acl == nullptr) { log::warn("Unable to find active acl"); @@ -2113,8 +2051,7 @@ bool acl_refresh_remote_address(const RawAddress& identity_address, return true; } -bool acl_peer_supports_ble_connection_parameters_request( - const RawAddress& remote_bda) { +bool acl_peer_supports_ble_connection_parameters_request(const RawAddress& remote_bda) { tACL_CONN* p_acl = internal_.btm_bda_to_acl(remote_bda, BT_TRANSPORT_LE); if (p_acl == nullptr) { log::warn("Unable to find active acl"); @@ -2126,13 +2063,12 @@ bool acl_peer_supports_ble_connection_parameters_request( return HCI_LE_CONN_PARAM_REQ_SUPPORTED(p_acl->peer_le_features); } -void acl_ble_connection_parameters_request( - uint16_t handle, uint16_t conn_int_min, uint16_t conn_int_max, - uint16_t conn_latency, uint16_t conn_timeout, uint16_t min_ce_len, - uint16_t max_ce_len) { +void acl_ble_connection_parameters_request(uint16_t handle, uint16_t conn_int_min, + uint16_t conn_int_max, uint16_t conn_latency, + uint16_t conn_timeout, uint16_t min_ce_len, + uint16_t max_ce_len) { bluetooth::shim::ACL_SendConnectionParameterUpdateRequest( - handle, conn_int_min, conn_int_max, conn_latency, conn_timeout, - min_ce_len, max_ce_len); + handle, conn_int_min, conn_int_max, conn_latency, conn_timeout, min_ce_len, max_ce_len); } bool acl_peer_supports_sniff_subrating(const RawAddress& remote_bda) { @@ -2159,8 +2095,7 @@ bool acl_peer_supports_ble_connection_subrating(const RawAddress& remote_bda) { return HCI_LE_CONN_SUBRATING_SUPPORT(p_acl->peer_le_features); } -bool acl_peer_supports_ble_connection_subrating_host( - const RawAddress& remote_bda) { +bool acl_peer_supports_ble_connection_subrating_host(const RawAddress& remote_bda) { tACL_CONN* p_acl = internal_.btm_bda_to_acl(remote_bda, BT_TRANSPORT_LE); if (p_acl == nullptr) { log::warn("Unable to find active acl"); @@ -2182,8 +2117,7 @@ bool acl_peer_supports_ble_connection_subrating_host( * Returns void * ******************************************************************************/ -void BTM_ReadConnectionAddr(const RawAddress& remote_bda, - RawAddress& local_conn_addr, +void BTM_ReadConnectionAddr(const RawAddress& remote_bda, RawAddress& local_conn_addr, tBLE_ADDR_TYPE* p_addr_type, bool ota_address) { tBTM_SEC_DEV_REC* p_sec_rec = btm_find_dev(remote_bda); if (p_sec_rec == nullptr) { @@ -2191,8 +2125,8 @@ void BTM_ReadConnectionAddr(const RawAddress& remote_bda, return; } - bluetooth::shim::ACL_ReadConnectionAddress( - p_sec_rec->ble_hci_handle, local_conn_addr, p_addr_type, ota_address); + bluetooth::shim::ACL_ReadConnectionAddress(p_sec_rec->ble_hci_handle, local_conn_addr, + p_addr_type, ota_address); } /******************************************************************************* @@ -2207,7 +2141,9 @@ void BTM_ReadConnectionAddr(const RawAddress& remote_bda, ******************************************************************************/ bool BTM_IsBleConnection(uint16_t hci_handle) { const tACL_CONN* p_acl = internal_.acl_get_connection_from_handle(hci_handle); - if (p_acl == nullptr) return false; + if (p_acl == nullptr) { + return false; + } return p_acl->is_transport_ble(); } @@ -2219,8 +2155,7 @@ const RawAddress acl_address_from_handle(uint16_t handle) { return p_acl->remote_addr; } -bool acl_is_switch_role_idle(const RawAddress& bd_addr, - tBT_TRANSPORT transport) { +bool acl_is_switch_role_idle(const RawAddress& bd_addr, tBT_TRANSPORT transport) { tACL_CONN* p_acl = internal_.btm_bda_to_acl(bd_addr, transport); if (p_acl == nullptr) { log::warn("Unable to find active acl"); @@ -2246,18 +2181,16 @@ bool acl_is_switch_role_idle(const RawAddress& bd_addr, * Returns bool, true if connection to remote device exists, else false * ******************************************************************************/ -bool BTM_ReadRemoteConnectionAddr(const RawAddress& pseudo_addr, - RawAddress& conn_addr, - tBLE_ADDR_TYPE* p_addr_type, - bool ota_address) { +bool BTM_ReadRemoteConnectionAddr(const RawAddress& pseudo_addr, RawAddress& conn_addr, + tBLE_ADDR_TYPE* p_addr_type, bool ota_address) { tBTM_SEC_DEV_REC* p_sec_rec = btm_find_dev(pseudo_addr); if (p_sec_rec == nullptr) { log::warn("No matching known device {} in record", pseudo_addr); return false; } - bluetooth::shim::ACL_ReadPeerConnectionAddress( - p_sec_rec->ble_hci_handle, conn_addr, p_addr_type, ota_address); + bluetooth::shim::ACL_ReadPeerConnectionAddress(p_sec_rec->ble_hci_handle, conn_addr, p_addr_type, + ota_address); return true; } @@ -2312,16 +2245,12 @@ void acl_set_locally_initiated(bool locally_initiated) { } bool acl_is_role_switch_allowed() { - return btm_cb.acl_cb_.DefaultLinkPolicy() & - HCI_ENABLE_CENTRAL_PERIPHERAL_SWITCH; + return btm_cb.acl_cb_.DefaultLinkPolicy() & HCI_ENABLE_CENTRAL_PERIPHERAL_SWITCH; } -uint16_t acl_get_supported_packet_types() { - return btm_cb.acl_cb_.DefaultPacketTypes(); -} +uint16_t acl_get_supported_packet_types() { return btm_cb.acl_cb_.DefaultPacketTypes(); } -bool acl_set_peer_le_features_from_handle(uint16_t hci_handle, - const uint8_t* p) { +bool acl_set_peer_le_features_from_handle(uint16_t hci_handle, const uint8_t* p) { tACL_CONN* p_acl = internal_.acl_get_connection_from_handle(hci_handle); if (p_acl == nullptr) { return false; @@ -2333,24 +2262,22 @@ bool acl_set_peer_le_features_from_handle(uint16_t hci_handle, /* save LE remote supported features to iot conf file */ std::string key = IOT_CONF_KEY_RT_SUPP_FEATURES "_" + std::to_string(0); - DEVICE_IOT_CONFIG_ADDR_SET_BIN(p_acl->remote_addr, key, - p_acl->peer_le_features, BD_FEATURES_LEN); + DEVICE_IOT_CONFIG_ADDR_SET_BIN(p_acl->remote_addr, key, p_acl->peer_le_features, BD_FEATURES_LEN); return true; } -void on_acl_br_edr_connected(const RawAddress& bda, uint16_t handle, - uint8_t enc_mode, bool locally_initiated) { +void on_acl_br_edr_connected(const RawAddress& bda, uint16_t handle, uint8_t enc_mode, + bool locally_initiated) { power_telemetry::GetInstance().LogLinkDetails(handle, bda, true, true); if (delayed_role_change_ != nullptr && delayed_role_change_->bd_addr == bda) { - btm_sec_connected(bda, handle, HCI_SUCCESS, enc_mode, - delayed_role_change_->new_role); + btm_sec_connected(bda, handle, HCI_SUCCESS, enc_mode, delayed_role_change_->new_role); } else { btm_sec_connected(bda, handle, HCI_SUCCESS, enc_mode); } delayed_role_change_ = nullptr; l2c_link_hci_conn_comp(HCI_SUCCESS, handle, bda); uint16_t link_supervision_timeout = - osi_property_get_int32(PROPERTY_LINK_SUPERVISION_TIMEOUT, 8000); + osi_property_get_int32(PROPERTY_LINK_SUPERVISION_TIMEOUT, 8000); BTM_SetLinkSuperTout(bda, link_supervision_timeout); tACL_CONN* p_acl = internal_.acl_get_connection_from_handle(handle); @@ -2370,13 +2297,10 @@ void on_acl_br_edr_connected(const RawAddress& bda, uint16_t handle, NotifyAclLinkUp(*p_acl); } -void on_acl_br_edr_failed(const RawAddress& bda, tHCI_STATUS status, - bool locally_initiated) { - log::assert_that(status != HCI_SUCCESS, - "Successful connection entering failing code path"); +void on_acl_br_edr_failed(const RawAddress& bda, tHCI_STATUS status, bool locally_initiated) { + log::assert_that(status != HCI_SUCCESS, "Successful connection entering failing code path"); if (delayed_role_change_ != nullptr && delayed_role_change_->bd_addr == bda) { - btm_sec_connected(bda, HCI_INVALID_HANDLE, status, false, - delayed_role_change_->new_role); + btm_sec_connected(bda, HCI_INVALID_HANDLE, status, false, delayed_role_change_->new_role); } else { btm_sec_connected(bda, HCI_INVALID_HANDLE, status, false); } @@ -2387,25 +2311,22 @@ void on_acl_br_edr_failed(const RawAddress& bda, tHCI_STATUS status, btm_acl_create_failed(bda, BT_TRANSPORT_BR_EDR, status); } -void btm_acl_connected(const RawAddress& bda, uint16_t handle, - tHCI_STATUS status, uint8_t enc_mode) { +void btm_acl_connected(const RawAddress& bda, uint16_t handle, tHCI_STATUS status, + uint8_t enc_mode) { switch (status) { case HCI_SUCCESS: power_telemetry::GetInstance().LogLinkDetails(handle, bda, true, true); - return on_acl_br_edr_connected(bda, handle, enc_mode, - true /* locally_initiated */); + return on_acl_br_edr_connected(bda, handle, enc_mode, true /* locally_initiated */); default: return on_acl_br_edr_failed(bda, status, /* locally_initiated */ true); } } -void btm_acl_disconnected(tHCI_STATUS status, uint16_t handle, - tHCI_REASON reason) { +void btm_acl_disconnected(tHCI_STATUS status, uint16_t handle, tHCI_REASON reason) { if (status != HCI_SUCCESS) { log::warn("Received disconnect with error:{}", hci_error_code_text(status)); } - power_telemetry::GetInstance().LogLinkDetails(handle, RawAddress::kEmpty, - false, true); + power_telemetry::GetInstance().LogLinkDetails(handle, RawAddress::kEmpty, false, true); /* There can be a case when we rejected PIN code authentication */ /* otherwise save a new reason */ if (btm_get_acl_disc_reason_code() != HCI_ERR_HOST_REJECT_SECURITY) { @@ -2416,12 +2337,10 @@ void btm_acl_disconnected(tHCI_STATUS status, uint16_t handle, l2c_link_hci_disc_comp(handle, reason); /* Notify security manager */ - btm_sec_disconnected(handle, reason, - "stack::acl::btm_acl::btm_acl_disconnected"); + btm_sec_disconnected(handle, reason, "stack::acl::btm_acl::btm_acl_disconnected"); } -void btm_connection_request(const RawAddress& bda, - const bluetooth::hci::ClassOfDevice& cod) { +void btm_connection_request(const RawAddress& bda, const bluetooth::hci::ClassOfDevice& cod) { // Copy Cod information DEV_CLASS dc; @@ -2438,8 +2357,7 @@ void btm_connection_request(const RawAddress& bda, btm_sec_conn_req(bda, dc); } -void acl_disconnect_from_handle(uint16_t handle, tHCI_STATUS reason, - std::string comment) { +void acl_disconnect_from_handle(uint16_t handle, tHCI_STATUS reason, std::string comment) { acl_disconnect_after_role_switch(handle, reason, comment); } @@ -2467,9 +2385,9 @@ void acl_disconnect_after_role_switch(uint16_t conn_handle, tHCI_STATUS reason, std::string comment) { if (!is_disconnect_reason_valid(reason)) { log::warn( - "Controller will not accept invalid reason parameter:{} instead " - "sending:{}", - hci_error_code_text(reason), hci_error_code_text(HCI_ERR_PEER_USER)); + "Controller will not accept invalid reason parameter:{} instead " + "sending:{}", + hci_error_code_text(reason), hci_error_code_text(HCI_ERR_PEER_USER)); reason = HCI_ERR_PEER_USER; } @@ -2484,49 +2402,46 @@ void acl_disconnect_after_role_switch(uint16_t conn_handle, tHCI_STATUS reason, * controller problem */ if (p_acl->rs_disc_pending == BTM_SEC_RS_PENDING) { log::debug( - "Role switch in progress - Set DISC Pending flag in " - "btm_sec_send_hci_disconnect to delay disconnect"); + "Role switch in progress - Set DISC Pending flag in " + "btm_sec_send_hci_disconnect to delay disconnect"); p_acl->rs_disc_pending = BTM_SEC_DISC_PENDING; } else { - log::debug("Sending acl disconnect reason:{} [{}]", - hci_error_code_text(reason), reason); + log::debug("Sending acl disconnect reason:{} [{}]", hci_error_code_text(reason), reason); disconnect_acl(*p_acl, reason, comment); } } void acl_send_data_packet_br_edr(const RawAddress& bd_addr, BT_HDR* p_buf) { - tACL_CONN* p_acl = internal_.btm_bda_to_acl(bd_addr, BT_TRANSPORT_BR_EDR); - if (p_acl == nullptr) { - log::warn("Acl br_edr data write for unknown device:{}", bd_addr); - osi_free(p_buf); - return; - } - power_telemetry::GetInstance().LogTxAclPktData(p_buf->len); - return bluetooth::shim::ACL_WriteData(p_acl->hci_handle, p_buf); + tACL_CONN* p_acl = internal_.btm_bda_to_acl(bd_addr, BT_TRANSPORT_BR_EDR); + if (p_acl == nullptr) { + log::warn("Acl br_edr data write for unknown device:{}", bd_addr); + osi_free(p_buf); + return; + } + power_telemetry::GetInstance().LogTxAclPktData(p_buf->len); + return bluetooth::shim::ACL_WriteData(p_acl->hci_handle, p_buf); } void acl_send_data_packet_ble(const RawAddress& bd_addr, BT_HDR* p_buf) { - tACL_CONN* p_acl = internal_.btm_bda_to_acl(bd_addr, BT_TRANSPORT_LE); - if (p_acl == nullptr) { - log::warn("Acl le data write for unknown device:{}", bd_addr); - osi_free(p_buf); - return; - } - power_telemetry::GetInstance().LogTxAclPktData(p_buf->len); - return bluetooth::shim::ACL_WriteData(p_acl->hci_handle, p_buf); + tACL_CONN* p_acl = internal_.btm_bda_to_acl(bd_addr, BT_TRANSPORT_LE); + if (p_acl == nullptr) { + log::warn("Acl le data write for unknown device:{}", bd_addr); + osi_free(p_buf); + return; + } + power_telemetry::GetInstance().LogTxAclPktData(p_buf->len); + return bluetooth::shim::ACL_WriteData(p_acl->hci_handle, p_buf); } -void acl_write_automatic_flush_timeout(const RawAddress& bd_addr, - uint16_t flush_timeout_in_ticks) { +void acl_write_automatic_flush_timeout(const RawAddress& bd_addr, uint16_t flush_timeout_in_ticks) { tACL_CONN* p_acl = internal_.btm_bda_to_acl(bd_addr, BT_TRANSPORT_BR_EDR); if (p_acl == nullptr) { log::warn("Unable to find active acl"); return; } if (p_acl->flush_timeout_in_ticks == flush_timeout_in_ticks) { - log::info( - "Ignoring since cached value is same as requested flush_timeout:{}", - flush_timeout_in_ticks); + log::info("Ignoring since cached value is same as requested flush_timeout:{}", + flush_timeout_in_ticks); return; } flush_timeout_in_ticks &= HCI_MAX_AUTOMATIC_FLUSH_TIMEOUT; @@ -2537,28 +2452,26 @@ void acl_write_automatic_flush_timeout(const RawAddress& bd_addr, bool acl_create_le_connection_with_id(uint8_t id, const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type) { tBLE_BD_ADDR address_with_type{ - .type = addr_type, - .bda = bd_addr, + .type = addr_type, + .bda = bd_addr, }; find_in_device_record(bd_addr, &address_with_type); - log::debug("Creating le direct connection to:{} type:{} (initial type: {})", - address_with_type, AddressTypeText(address_with_type.type), - AddressTypeText(addr_type)); + log::debug("Creating le direct connection to:{} type:{} (initial type: {})", address_with_type, + AddressTypeText(address_with_type.type), AddressTypeText(addr_type)); if (address_with_type.type == BLE_ADDR_ANONYMOUS) { log::warn( - "Creating le direct connection to:{}, address type 'anonymous' is " - "invalid", - address_with_type); + "Creating le direct connection to:{}, address type 'anonymous' is " + "invalid", + address_with_type); return false; } - if (bluetooth::common::init_flags:: - use_unified_connection_manager_is_enabled()) { + if (bluetooth::common::init_flags::use_unified_connection_manager_is_enabled()) { bluetooth::connection::GetConnectionManager().start_direct_connection( - id, bluetooth::core::ToRustAddress(address_with_type)); + id, bluetooth::core::ToRustAddress(address_with_type)); } else { bluetooth::shim::ACL_AcceptLeConnectionFrom(address_with_type, /* is_direct */ true); @@ -2576,8 +2489,8 @@ bool acl_create_le_connection(const RawAddress& bd_addr) { void acl_rcv_acl_data(BT_HDR* p_msg) { acl_header_t acl_header{ - .handle = HCI_INVALID_HANDLE, - .hci_len = 0, + .handle = HCI_INVALID_HANDLE, + .hci_len = 0, }; const uint8_t* p = (uint8_t*)(p_msg + 1) + p_msg->offset; @@ -2588,8 +2501,8 @@ void acl_rcv_acl_data(BT_HDR* p_msg) { STREAM_TO_UINT16(acl_header.hci_len, p); if (acl_header.hci_len < L2CAP_PKT_OVERHEAD || acl_header.hci_len != p_msg->len - sizeof(acl_header)) { - log::warn("Received mismatched hci header length:{} data_len:{}", - acl_header.hci_len, p_msg->len - sizeof(acl_header)); + log::warn("Received mismatched hci header length:{} data_len:{}", acl_header.hci_len, + p_msg->len - sizeof(acl_header)); osi_free(p_msg); return; } @@ -2598,8 +2511,7 @@ void acl_rcv_acl_data(BT_HDR* p_msg) { void acl_packets_completed(uint16_t handle, uint16_t credits) { l2c_packets_completed(handle, credits); - bluetooth::hci::IsoManager::GetInstance()->HandleNumComplDataPkts(handle, - credits); + bluetooth::hci::IsoManager::GetInstance()->HandleNumComplDataPkts(handle, credits); } void acl_process_supported_features(uint16_t handle, uint64_t features) { @@ -2610,19 +2522,18 @@ void acl_process_supported_features(uint16_t handle, uint64_t features) { } const uint8_t current_page_number = 0; - memcpy(p_acl->peer_lmp_feature_pages[current_page_number], - (uint8_t*)&features, sizeof(uint64_t)); + memcpy(p_acl->peer_lmp_feature_pages[current_page_number], (uint8_t*)&features, sizeof(uint64_t)); p_acl->peer_lmp_feature_valid[current_page_number] = true; log::debug( - "Copied supported feature pages handle:{} current_page_number:{} " - "features:{}", - handle, current_page_number, - bd_features_text(p_acl->peer_lmp_feature_pages[current_page_number])); + "Copied supported feature pages handle:{} current_page_number:{} " + "features:{}", + handle, current_page_number, + bd_features_text(p_acl->peer_lmp_feature_pages[current_page_number])); if ((HCI_LMP_EXTENDED_SUPPORTED(p_acl->peer_lmp_feature_pages[0])) && (bluetooth::shim::GetController()->IsSupported( - bluetooth::hci::OpCode::READ_REMOTE_EXTENDED_FEATURES))) { + bluetooth::hci::OpCode::READ_REMOTE_EXTENDED_FEATURES))) { log::debug("Waiting for remote extended feature response to arrive"); } else { log::debug("No more remote features outstanding so notify upper layer"); @@ -2641,15 +2552,14 @@ void acl_process_extended_features(uint16_t handle, uint8_t current_page_number, log::warn("Unable to find active acl"); return; } - memcpy(p_acl->peer_lmp_feature_pages[current_page_number], - (uint8_t*)&features, sizeof(uint64_t)); + memcpy(p_acl->peer_lmp_feature_pages[current_page_number], (uint8_t*)&features, sizeof(uint64_t)); p_acl->peer_lmp_feature_valid[current_page_number] = true; log::debug( - "Copied extended feature pages handle:{} current_page_number:{} " - "max_page_number:{} features:{}", - handle, current_page_number, max_page_number, - bd_features_text(p_acl->peer_lmp_feature_pages[current_page_number])); + "Copied extended feature pages handle:{} current_page_number:{} " + "max_page_number:{} features:{}", + handle, current_page_number, max_page_number, + bd_features_text(p_acl->peer_lmp_feature_pages[current_page_number])); if (max_page_number == 0 || max_page_number == current_page_number) { NotifyAclFeaturesReadComplete(*p_acl, max_page_number); @@ -2673,8 +2583,7 @@ tACL_CONN* btm_acl_for_bda(const RawAddress& bd_addr, tBT_TRANSPORT transport) { return p_acl; } -void find_in_device_record(const RawAddress& bd_addr, - tBLE_BD_ADDR* address_with_type) { +void find_in_device_record(const RawAddress& bd_addr, tBLE_BD_ADDR* address_with_type) { const tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr); if (p_dev_rec == nullptr) { return; @@ -2682,8 +2591,7 @@ void find_in_device_record(const RawAddress& bd_addr, if (p_dev_rec->device_type & BT_DEVICE_TYPE_BLE) { if (p_dev_rec->ble.identity_address_with_type.bda.IsEmpty()) { - *address_with_type = {.type = p_dev_rec->ble.AddressType(), - .bda = bd_addr}; + *address_with_type = {.type = p_dev_rec->ble.AddressType(), .bda = bd_addr}; return; } *address_with_type = p_dev_rec->ble.identity_address_with_type; diff --git a/system/stack/acl/btm_pm.cc b/system/stack/acl/btm_pm.cc index 50b8ba4bbbf..2d566a03678 100644 --- a/system/stack/acl/btm_pm.cc +++ b/system/stack/acl/btm_pm.cc @@ -76,44 +76,39 @@ tBTM_PM_RCB pm_reg_db; /* per application/module */ uint8_t pm_pend_id = 0; /* the id pf the module, which has a pending PM cmd */ constexpr char kBtmLogTag[] = "ACL"; -} +} // namespace /*****************************************************************************/ /* to handle different modes */ /*****************************************************************************/ -#define BTM_PM_NUM_SET_MODES 3 /* only hold, sniff & park */ +#define BTM_PM_NUM_SET_MODES 3 /* only hold, sniff & park */ #define BTM_PM_GET_MD1 1 #define BTM_PM_GET_MD2 2 #define BTM_PM_GET_COMP 3 -const uint8_t - btm_pm_md_comp_matrix[BTM_PM_NUM_SET_MODES * BTM_PM_NUM_SET_MODES] = { +const uint8_t btm_pm_md_comp_matrix[BTM_PM_NUM_SET_MODES * BTM_PM_NUM_SET_MODES] = { BTM_PM_GET_COMP, BTM_PM_GET_MD2, BTM_PM_GET_MD2, BTM_PM_GET_MD1, BTM_PM_GET_COMP, BTM_PM_GET_MD1, BTM_PM_GET_MD1, BTM_PM_GET_MD2, BTM_PM_GET_COMP}; -static void send_sniff_subrating(uint16_t handle, const RawAddress& addr, - uint16_t max_lat, uint16_t min_rmt_to, - uint16_t min_loc_to) { +static void send_sniff_subrating(uint16_t handle, const RawAddress& addr, uint16_t max_lat, + uint16_t min_rmt_to, uint16_t min_loc_to) { uint16_t new_max_lat = 0; - if (interop_match_addr_get_max_lat(INTEROP_UPDATE_HID_SSR_MAX_LAT, &addr, - &new_max_lat)) { + if (interop_match_addr_get_max_lat(INTEROP_UPDATE_HID_SSR_MAX_LAT, &addr, &new_max_lat)) { max_lat = new_max_lat; } btsnd_hcic_sniff_sub_rate(handle, max_lat, min_rmt_to, min_loc_to); BTM_LogHistory(kBtmLogTag, addr, "Sniff subrating", - base::StringPrintf( - "max_latency:%.2f peer_timeout:%.2f local_timeout:%.2f", - ticks_to_seconds(max_lat), ticks_to_seconds(min_rmt_to), - ticks_to_seconds(min_loc_to))); + base::StringPrintf("max_latency:%.2f peer_timeout:%.2f local_timeout:%.2f", + ticks_to_seconds(max_lat), ticks_to_seconds(min_rmt_to), + ticks_to_seconds(min_loc_to))); } -static tBTM_STATUS btm_pm_snd_md_req(uint16_t handle, uint8_t pm_id, - int link_ind, +static tBTM_STATUS btm_pm_snd_md_req(uint16_t handle, uint8_t pm_id, int link_ind, const tBTM_PM_PWR_MD* p_mode); /*****************************************************************************/ @@ -130,18 +125,21 @@ static tBTM_STATUS btm_pm_snd_md_req(uint16_t handle, uint8_t pm_id, * BTM_ILLEGAL_VALUE * ******************************************************************************/ -tBTM_STATUS BTM_PmRegister(uint8_t mask, uint8_t* p_pm_id, - tBTM_PM_STATUS_CBACK* p_cb) { +tBTM_STATUS BTM_PmRegister(uint8_t mask, uint8_t* p_pm_id, tBTM_PM_STATUS_CBACK* p_cb) { /* de-register */ if (mask & BTM_PM_DEREG) { - if (*p_pm_id >= BTM_MAX_PM_RECORDS) return BTM_ILLEGAL_VALUE; + if (*p_pm_id >= BTM_MAX_PM_RECORDS) { + return BTM_ILLEGAL_VALUE; + } pm_reg_db.mask = BTM_PM_REC_NOT_USED; return BTM_SUCCESS; } if (pm_reg_db.mask == BTM_PM_REC_NOT_USED) { /* if register for notification, should provide callback routine */ - if (p_cb == NULL) return BTM_ILLEGAL_VALUE; + if (p_cb == NULL) { + return BTM_ILLEGAL_VALUE; + } pm_reg_db.cback = p_cb; pm_reg_db.mask = mask; *p_pm_id = 0; @@ -153,8 +151,7 @@ tBTM_STATUS BTM_PmRegister(uint8_t mask, uint8_t* p_pm_id, void BTM_PM_OnConnected(uint16_t handle, const RawAddress& remote_bda) { if (pm_mode_db.find(handle) != pm_mode_db.end()) { - log::error("Overwriting power mode db entry handle:{} peer:{}", handle, - remote_bda); + log::error("Overwriting power mode db entry handle:{} peer:{}", handle, remote_bda); } pm_mode_db[handle] = {}; pm_mode_db[handle].Init(remote_bda, handle); @@ -218,8 +215,7 @@ tBTM_STATUS BTM_SetPowerMode(uint8_t pm_id, const RawAddress& remote_bda, (mode == BTM_PM_MD_SNIFF && !controller->SupportsSniffMode()) || (mode == BTM_PM_MD_PARK && !controller->SupportsParkMode()) || interop_match_addr(INTEROP_DISABLE_SNIFF, &remote_bda)) { - log::error("pm_id {} mode {} is not supported for {}", pm_id, mode, - remote_bda); + log::error("pm_id {} mode {} is not supported for {}", pm_id, mode, remote_bda); return BTM_MODE_UNSUPPORTED; } } @@ -230,12 +226,11 @@ tBTM_STATUS BTM_SetPowerMode(uint8_t pm_id, const RawAddress& remote_bda, if ((mode == BTM_PM_MD_ACTIVE) || ((p_mode->mode & BTM_PM_MD_FORCE) && (p_mode->max >= p_cb->interval) && (p_mode->min <= p_cb->interval)) || - ((p_mode->mode & BTM_PM_MD_FORCE) == 0 && - (p_mode->max >= p_cb->interval))) { + ((p_mode->mode & BTM_PM_MD_FORCE) == 0 && (p_mode->max >= p_cb->interval))) { log::debug( - "Device is already in requested mode {}, interval: {}, max: {}, min: " - "{}", - p_mode->mode, p_cb->interval, p_mode->max, p_mode->min); + "Device is already in requested mode {}, interval: {}, max: {}, min: " + "{}", + p_mode->mode, p_cb->interval, p_mode->max, p_mode->min); return BTM_SUCCESS; } } @@ -253,9 +248,9 @@ tBTM_STATUS BTM_SetPowerMode(uint8_t pm_id, const RawAddress& remote_bda, if ((p_cb->state == BTM_PM_STS_HOLD) || (p_cb->state == BTM_PM_STS_PENDING) || (pm_pend_link != 0)) { log::info( - "Current power mode is hold or pending status or pending links " - "state:{}[{}] pm_pending_link:{}", - power_mode_state_text(p_cb->state), p_cb->state, pm_pend_link); + "Current power mode is hold or pending status or pending links " + "state:{}[{}] pm_pending_link:{}", + power_mode_state_text(p_cb->state), p_cb->state, pm_pend_link); /* command pending */ if (handle != pm_pend_link) { p_cb->state |= BTM_PM_STORED_MASK; @@ -264,10 +259,9 @@ tBTM_STATUS BTM_SetPowerMode(uint8_t pm_id, const RawAddress& remote_bda, return BTM_CMD_STORED; } - log::info( - "Setting power mode for peer:{} current_mode:{}[{}] new_mode:{}[{}]", - remote_bda, power_mode_state_text(p_cb->state), p_cb->state, - power_mode_text(p_mode->mode), p_mode->mode); + log::info("Setting power mode for peer:{} current_mode:{}[{}] new_mode:{}[{}]", remote_bda, + power_mode_state_text(p_cb->state), p_cb->state, power_mode_text(p_mode->mode), + p_mode->mode); return btm_pm_snd_md_req(p_cb->handle_, pm_id, p_cb->handle_, p_mode); } @@ -318,8 +312,8 @@ bool BTM_ReadPowerMode(const RawAddress& remote_bda, tBTM_PM_MODE* p_mode) { * BTM_CMD_STORED if the command is stored * ******************************************************************************/ -tBTM_STATUS BTM_SetSsrParams(const RawAddress& remote_bda, uint16_t max_lat, - uint16_t min_rmt_to, uint16_t min_loc_to) { +tBTM_STATUS BTM_SetSsrParams(const RawAddress& remote_bda, uint16_t max_lat, uint16_t min_rmt_to, + uint16_t min_loc_to) { tBTM_PM_MCB* p_cb = btm_pm_get_power_manager_from_address(remote_bda); if (p_cb == nullptr) { log::warn("Unable to find power manager for peer:{}", remote_bda); @@ -333,12 +327,10 @@ tBTM_STATUS BTM_SetSsrParams(const RawAddress& remote_bda, uint16_t max_lat, if (p_cb->state == BTM_PM_ST_ACTIVE || p_cb->state == BTM_PM_ST_SNIFF) { log::info( - "Set sniff subrating state:{}[{}] max_latency:0x{:04x} " - "min_remote_timeout:0x{:04x} min_local_timeout:0x{:04x}", - power_mode_state_text(p_cb->state), p_cb->state, max_lat, min_rmt_to, - min_loc_to); - send_sniff_subrating(p_cb->handle_, remote_bda, max_lat, min_rmt_to, - min_loc_to); + "Set sniff subrating state:{}[{}] max_latency:0x{:04x} " + "min_remote_timeout:0x{:04x} min_local_timeout:0x{:04x}", + power_mode_state_text(p_cb->state), p_cb->state, max_lat, min_rmt_to, min_loc_to); + send_sniff_subrating(p_cb->handle_, remote_bda, max_lat, min_rmt_to, min_loc_to); return BTM_SUCCESS; } log::info("pm_mode_db state: {}", p_cb->state); @@ -387,8 +379,7 @@ void btm_pm_reset(void) { * ******************************************************************************/ static tBTM_PM_PWR_MD* btm_pm_compare_modes(const tBTM_PM_PWR_MD* p_md1, - const tBTM_PM_PWR_MD* p_md2, - tBTM_PM_PWR_MD* p_res) { + const tBTM_PM_PWR_MD* p_md2, tBTM_PM_PWR_MD* p_res) { uint8_t res; if (p_md1 == NULL) { @@ -434,14 +425,14 @@ static tBTM_PM_PWR_MD* btm_pm_compare_modes(const tBTM_PM_PWR_MD* p_md1, p_res->min = (p_md1->min > p_md2->min) ? (p_md1->min) : (p_md2->min); /* the intersection is NULL */ - if (p_res->max < p_res->min) return NULL; + if (p_res->max < p_res->min) { + return NULL; + } if (p_res->mode == BTM_PM_MD_SNIFF) { /* max of the two */ - p_res->attempt = (p_md1->attempt > p_md2->attempt) ? (p_md1->attempt) - : (p_md2->attempt); - p_res->timeout = (p_md1->timeout > p_md2->timeout) ? (p_md1->timeout) - : (p_md2->timeout); + p_res->attempt = (p_md1->attempt > p_md2->attempt) ? (p_md1->attempt) : (p_md2->attempt); + p_res->timeout = (p_md1->timeout > p_md2->timeout) ? (p_md1->timeout) : (p_md2->timeout); } return p_res; } @@ -459,8 +450,7 @@ static tBTM_PM_PWR_MD* btm_pm_compare_modes(const tBTM_PM_PWR_MD* p_md1, * ******************************************************************************/ static tBTM_PM_MODE btm_pm_get_set_mode(uint8_t pm_id, tBTM_PM_MCB* p_cb, - const tBTM_PM_PWR_MD* p_mode, - tBTM_PM_PWR_MD* p_res) { + const tBTM_PM_PWR_MD* p_mode, tBTM_PM_PWR_MD* p_res) { tBTM_PM_PWR_MD* p_md = NULL; if (p_mode != NULL && p_mode->mode & BTM_PM_MD_FORCE) { @@ -476,8 +466,9 @@ static tBTM_PM_MODE btm_pm_get_set_mode(uint8_t pm_id, tBTM_PM_MCB* p_cb, return BTM_PM_MD_ACTIVE; } else { /* if registered parties give conflicting information, stay active */ - if ((btm_pm_compare_modes(p_md, &p_cb->req_mode, p_res)) == NULL) + if ((btm_pm_compare_modes(p_md, &p_cb->req_mode, p_res)) == NULL) { return BTM_PM_MD_ACTIVE; + } p_md = p_res; } } @@ -485,17 +476,18 @@ static tBTM_PM_MODE btm_pm_get_set_mode(uint8_t pm_id, tBTM_PM_MCB* p_cb, /* if the resulting mode is NULL(nobody registers SET), use the requested mode */ if (p_md == NULL) { - if (p_mode) + if (p_mode) { *p_res = *((tBTM_PM_PWR_MD*)p_mode); - else /* p_mode is NULL when btm_pm_snd_md_req is called from - btm_pm_proc_mode_change */ + } else { /* p_mode is NULL when btm_pm_snd_md_req is called from + btm_pm_proc_mode_change */ return BTM_PM_MD_ACTIVE; + } } else { /* if the command is from unregistered party, compare the resulting mode from registered party*/ - if ((pm_id == BTM_PM_SET_ONLY_ID) && - ((btm_pm_compare_modes(p_mode, p_md, p_res)) == NULL)) + if ((pm_id == BTM_PM_SET_ONLY_ID) && ((btm_pm_compare_modes(p_mode, p_md, p_res)) == NULL)) { return BTM_PM_MD_ACTIVE; + } } return p_res->mode; @@ -508,11 +500,10 @@ static tBTM_PM_MODE btm_pm_get_set_mode(uint8_t pm_id, tBTM_PM_MCB* p_cb, * Returns tBTM_STATUS *, bool *p_chg_ind ******************************************************************************/ -static tBTM_STATUS btm_pm_snd_md_req(uint16_t handle, uint8_t pm_id, - int link_ind, +static tBTM_STATUS btm_pm_snd_md_req(uint16_t handle, uint8_t pm_id, int link_ind, const tBTM_PM_PWR_MD* p_mode) { - log::assert_that(pm_mode_db.count(handle) != 0, - "Unable to find active acl for handle {}", handle); + log::assert_that(pm_mode_db.count(handle) != 0, "Unable to find active acl for handle {}", + handle); tBTM_PM_PWR_MD md_res; tBTM_PM_MODE mode; tBTM_PM_MCB* p_cb = &pm_mode_db[handle]; @@ -524,8 +515,8 @@ static tBTM_STATUS btm_pm_snd_md_req(uint16_t handle, uint8_t pm_id, log::verbose("Found controller in mode:{}", power_mode_text(mode)); if (p_cb->state == mode) { - log::info("Link already in requested mode pm_id:{} link_ind:{} mode:{}[{}]", - pm_id, link_ind, power_mode_text(mode), mode); + log::info("Link already in requested mode pm_id:{} link_ind:{} mode:{}[{}]", pm_id, link_ind, + power_mode_text(mode), mode); /* already in the resulting mode */ if ((mode == BTM_PM_MD_ACTIVE) || @@ -550,8 +541,7 @@ static tBTM_STATUS btm_pm_snd_md_req(uint16_t handle, uint8_t pm_id, } else if (BTM_PM_MD_SNIFF == md_res.mode && p_cb->max_lat) { if (bluetooth::shim::GetController()->SupportsSniffSubrating()) { log::debug("Sending sniff subrating to controller"); - send_sniff_subrating(handle, p_cb->bda_, p_cb->max_lat, p_cb->min_rmt_to, - p_cb->min_loc_to); + send_sniff_subrating(handle, p_cb->bda_, p_cb->max_lat, p_cb->min_rmt_to, p_cb->min_loc_to); } p_cb->max_lat = 0; } @@ -561,14 +551,12 @@ static tBTM_STATUS btm_pm_snd_md_req(uint16_t handle, uint8_t pm_id, /* send the appropriate HCI command */ pm_pend_id = pm_id; - log::info("Switching from {}[0x{:02x}] to {}[0x{:02x}]", - power_mode_state_text(p_cb->state), p_cb->state, - power_mode_state_text(md_res.mode), md_res.mode); + log::info("Switching from {}[0x{:02x}] to {}[0x{:02x}]", power_mode_state_text(p_cb->state), + p_cb->state, power_mode_state_text(md_res.mode), md_res.mode); BTM_LogHistory(kBtmLogTag, p_cb->bda_, "Power mode change", - base::StringPrintf( - "%s[0x%02x] ==> %s[0x%02x]", - power_mode_state_text(p_cb->state).c_str(), p_cb->state, - power_mode_state_text(md_res.mode).c_str(), md_res.mode)); + base::StringPrintf("%s[0x%02x] ==> %s[0x%02x]", + power_mode_state_text(p_cb->state).c_str(), p_cb->state, + power_mode_state_text(md_res.mode).c_str(), md_res.mode)); switch (md_res.mode) { case BTM_PM_MD_ACTIVE: @@ -593,8 +581,7 @@ static tBTM_STATUS btm_pm_snd_md_req(uint16_t handle, uint8_t pm_id, break; case BTM_PM_MD_SNIFF: - btsnd_hcic_sniff_mode(handle, md_res.max, md_res.min, md_res.attempt, - md_res.timeout); + btsnd_hcic_sniff_mode(handle, md_res.max, md_res.min, md_res.attempt, md_res.timeout); pm_pend_link = handle; break; @@ -610,7 +597,7 @@ static tBTM_STATUS btm_pm_snd_md_req(uint16_t handle, uint8_t pm_id, if (pm_pend_link == 0) { /* the command was not sent */ log::error("pm_pending_link maxed out"); - return (BTM_NO_RESOURCES); + return BTM_NO_RESOURCES; } return BTM_CMD_STARTED; @@ -620,10 +607,8 @@ static void btm_pm_continue_pending_mode_changes() { for (auto& entry : pm_mode_db) { if (entry.second.state & BTM_PM_STORED_MASK) { entry.second.state &= ~BTM_PM_STORED_MASK; - log::info("Found another link requiring power mode change:{}", - entry.second.bda_); - btm_pm_snd_md_req(entry.second.handle_, BTM_PM_SET_ONLY_ID, - entry.second.handle_, NULL); + log::info("Found another link requiring power mode change:{}", entry.second.bda_); + btm_pm_snd_md_req(entry.second.handle_, BTM_PM_SET_ONLY_ID, entry.second.handle_, NULL); return; } } @@ -644,16 +629,16 @@ static void btm_pm_continue_pending_mode_changes() { void btm_pm_proc_cmd_status(tHCI_STATUS status) { if (pm_pend_link == 0) { log::error( - "There are no links pending power mode changes; try to find other " - "pending changes"); + "There are no links pending power mode changes; try to find other " + "pending changes"); btm_pm_continue_pending_mode_changes(); return; } if (pm_mode_db.count(pm_pend_link) == 0) { log::error( - "Got PM change status for disconnected link {}; forgot to clean up " - "pm_pend_link?", - pm_pend_link); + "Got PM change status for disconnected link {}; forgot to clean up " + "pm_pend_link?", + pm_pend_link); btm_pm_continue_pending_mode_changes(); return; } @@ -671,13 +656,11 @@ void btm_pm_proc_cmd_status(tHCI_STATUS status) { /* notify the caller is appropriate */ if ((pm_pend_id != BTM_PM_SET_ONLY_ID) && (pm_reg_db.mask & BTM_PM_REG_SET)) { const RawAddress bd_addr = pm_mode_db[pm_pend_link].bda_; - log::verbose("Notifying callback that link power mode is complete peer:{}", - bd_addr); + log::verbose("Notifying callback that link power mode is complete peer:{}", bd_addr); (*pm_reg_db.cback)(bd_addr, pm_status, 0, status); } - log::verbose("Clearing pending power mode link state:{}", - power_mode_state_text(p_cb->state)); + log::verbose("Clearing pending power mode link state:{}", power_mode_state_text(p_cb->state)); pm_pend_link = 0; btm_pm_continue_pending_mode_changes(); @@ -700,8 +683,8 @@ void btm_pm_proc_cmd_status(tHCI_STATUS status) { * Returns none. * ******************************************************************************/ -void btm_pm_proc_mode_change(tHCI_STATUS hci_status, uint16_t hci_handle, - tHCI_MODE hci_mode, uint16_t interval) { +void btm_pm_proc_mode_change(tHCI_STATUS hci_status, uint16_t hci_handle, tHCI_MODE hci_mode, + uint16_t interval) { tBTM_PM_STATUS mode = static_cast(hci_mode); /* update control block */ @@ -715,21 +698,21 @@ void btm_pm_proc_mode_change(tHCI_STATUS hci_status, uint16_t hci_handle, p_cb->state = mode; p_cb->interval = interval; - log::info("Power mode switched from {}[{}] to {}[{}]", - power_mode_state_text(old_state), old_state, - power_mode_state_text(p_cb->state), p_cb->state); + log::info("Power mode switched from {}[{}] to {}[{}]", power_mode_state_text(old_state), + old_state, power_mode_state_text(p_cb->state), p_cb->state); if ((p_cb->state == BTM_PM_ST_ACTIVE) || (p_cb->state == BTM_PM_ST_SNIFF)) { l2c_OnHciModeChangeSendPendingPackets(p_cb->bda_); } (mode != BTM_PM_ST_ACTIVE) - ? power_telemetry::GetInstance().LogSniffStarted(hci_handle, p_cb->bda_) - : power_telemetry::GetInstance().LogSniffStopped(hci_handle, p_cb->bda_); + ? power_telemetry::GetInstance().LogSniffStarted(hci_handle, p_cb->bda_) + : power_telemetry::GetInstance().LogSniffStopped(hci_handle, p_cb->bda_); /* set req_mode HOLD mode->ACTIVE */ - if ((mode == BTM_PM_MD_ACTIVE) && (p_cb->req_mode.mode == BTM_PM_MD_HOLD)) + if ((mode == BTM_PM_MD_ACTIVE) && (p_cb->req_mode.mode == BTM_PM_MD_HOLD)) { p_cb->req_mode.mode = BTM_PM_MD_ACTIVE; + } /* new request has been made. - post a message to BTU task */ if (old_state & BTM_PM_STORED_MASK) { @@ -737,8 +720,7 @@ void btm_pm_proc_mode_change(tHCI_STATUS hci_status, uint16_t hci_handle, } else { for (auto& entry : pm_mode_db) { if (entry.second.chg_ind) { - btm_pm_snd_md_req(entry.second.handle_, BTM_PM_SET_ONLY_ID, - entry.second.handle_, NULL); + btm_pm_snd_md_req(entry.second.handle_, BTM_PM_SET_ONLY_ID, entry.second.handle_, NULL); break; } } @@ -765,8 +747,8 @@ void btm_pm_proc_mode_change(tHCI_STATUS hci_status, uint16_t hci_handle, * Returns none. * ******************************************************************************/ -void process_ssr_event(tHCI_STATUS status, uint16_t handle, - uint16_t /* max_tx_lat */, uint16_t max_rx_lat) { +void process_ssr_event(tHCI_STATUS status, uint16_t handle, uint16_t /* max_tx_lat */, + uint16_t max_rx_lat) { if (pm_mode_db.count(handle) == 0) { log::warn("Received sniff subrating event with no active ACL"); return; @@ -776,8 +758,7 @@ void process_ssr_event(tHCI_STATUS status, uint16_t handle, bool use_ssr = true; if (p_cb->interval == max_rx_lat) { - log::verbose( - "Sniff subrating unsupported so dropping to legacy sniff mode"); + log::verbose("Sniff subrating unsupported so dropping to legacy sniff mode"); use_ssr = false; } else { log::verbose("Sniff subrating enabled"); @@ -789,18 +770,16 @@ void process_ssr_event(tHCI_STATUS status, uint16_t handle, cnt++; } log::debug( - "Notified sniff subrating registered clients cnt:{} peer:{} use_ssr:{} " - "status:{}", - cnt, bd_addr, use_ssr, hci_error_code_text(status)); + "Notified sniff subrating registered clients cnt:{} peer:{} use_ssr:{} " + "status:{}", + cnt, bd_addr, use_ssr, hci_error_code_text(status)); } void btm_pm_on_sniff_subrating(tHCI_STATUS status, uint16_t handle, - uint16_t maximum_transmit_latency, - uint16_t maximum_receive_latency, + uint16_t maximum_transmit_latency, uint16_t maximum_receive_latency, uint16_t /* minimum_remote_timeout */, uint16_t /* minimum_local_timeout */) { - process_ssr_event(status, handle, maximum_transmit_latency, - maximum_receive_latency); + process_ssr_event(status, handle, maximum_transmit_latency, maximum_receive_latency); } void btm_pm_proc_ssr_evt(uint8_t* p, uint16_t /* evt_len */) { @@ -814,8 +793,7 @@ void btm_pm_proc_ssr_evt(uint8_t* p, uint16_t /* evt_len */) { STREAM_TO_UINT16(max_tx_lat, p); STREAM_TO_UINT16(max_rx_lat, p); - process_ssr_event(static_cast(status), handle, max_tx_lat, - max_rx_lat); + process_ssr_event(static_cast(status), handle, max_tx_lat, max_rx_lat); } /******************************************************************************* @@ -856,8 +834,7 @@ static bool btm_pm_device_in_active_or_sniff_mode(void) { ******************************************************************************/ bool BTM_PM_DeviceInScanState(void) { /* Check for inquiry */ - if ((btm_cb.btm_inq_vars.inq_active & - (BTM_GENERAL_INQUIRY | BTM_BLE_GENERAL_INQUIRY)) != 0) { + if ((btm_cb.btm_inq_vars.inq_active & (BTM_GENERAL_INQUIRY | BTM_BLE_GENERAL_INQUIRY)) != 0) { log::verbose("BTM_PM_DeviceInScanState- Inq active"); return true; } @@ -876,12 +853,13 @@ bool BTM_PM_DeviceInScanState(void) { * ******************************************************************************/ tBTM_CONTRL_STATE BTM_PM_ReadControllerState(void) { - if (btm_pm_device_in_active_or_sniff_mode()) + if (btm_pm_device_in_active_or_sniff_mode()) { return BTM_CONTRL_ACTIVE; - else if (BTM_PM_DeviceInScanState()) + } else if (BTM_PM_DeviceInScanState()) { return BTM_CONTRL_SCAN; - else + } else { return BTM_CONTRL_IDLE; + } } /******************************************************************************* @@ -937,8 +915,8 @@ uint32_t BTM_PM_ReadBleScanDutyCycle(void) { return (scan_window * 100) / scan_interval; } -void btm_pm_on_mode_change(tHCI_STATUS status, uint16_t handle, - tHCI_MODE current_mode, uint16_t interval) { +void btm_pm_on_mode_change(tHCI_STATUS status, uint16_t handle, tHCI_MODE current_mode, + uint16_t interval) { btm_sco_chk_pend_unpark(status, handle); btm_pm_proc_mode_change(status, handle, current_mode, interval); } diff --git a/system/stack/acl/peer_packet_types.h b/system/stack/acl/peer_packet_types.h index 78aa9466866..291197f889a 100644 --- a/system/stack/acl/peer_packet_types.h +++ b/system/stack/acl/peer_packet_types.h @@ -19,8 +19,7 @@ #include "stack/include/hcidefs.h" #define BD_FEATURES_LEN 8 -typedef uint8_t - BD_FEATURES[BD_FEATURES_LEN]; /* LMP features supported by device */ +typedef uint8_t BD_FEATURES[BD_FEATURES_LEN]; /* LMP features supported by device */ // Bit order [0]:0-7 [1]:8-15 ... [7]:56-63 inline std::string bd_features_text(const BD_FEATURES& features) { @@ -38,7 +37,7 @@ inline std::string bd_features_text(const BD_FEATURES& features) { * Create a bitmask of packet types from the remote feature */ class PeerPacketTypes { - public: +public: struct { uint16_t supported{0}; uint16_t unsupported{0}; @@ -46,41 +45,42 @@ class PeerPacketTypes { PeerPacketTypes(const BD_FEATURES& features) { /* 3 and 5 slot packets? */ - if (HCI_3_SLOT_PACKETS_SUPPORTED(features)) + if (HCI_3_SLOT_PACKETS_SUPPORTED(features)) { acl.supported |= (HCI_PKT_TYPES_MASK_DH3 | HCI_PKT_TYPES_MASK_DM3); + } - if (HCI_5_SLOT_PACKETS_SUPPORTED(features)) + if (HCI_5_SLOT_PACKETS_SUPPORTED(features)) { acl.supported |= HCI_PKT_TYPES_MASK_DH5 | HCI_PKT_TYPES_MASK_DM5; + } /* 2 and 3 MPS support? */ - if (!HCI_EDR_ACL_2MPS_SUPPORTED(features)) + if (!HCI_EDR_ACL_2MPS_SUPPORTED(features)) { /* Not supported. Add 'not_supported' mask for all 2MPS packet types */ - acl.unsupported |= - (HCI_PKT_TYPES_MASK_NO_2_DH1 | HCI_PKT_TYPES_MASK_NO_2_DH3 | - HCI_PKT_TYPES_MASK_NO_2_DH5); + acl.unsupported |= (HCI_PKT_TYPES_MASK_NO_2_DH1 | HCI_PKT_TYPES_MASK_NO_2_DH3 | + HCI_PKT_TYPES_MASK_NO_2_DH5); + } - if (!HCI_EDR_ACL_3MPS_SUPPORTED(features)) + if (!HCI_EDR_ACL_3MPS_SUPPORTED(features)) { /* Not supported. Add 'not_supported' mask for all 3MPS packet types */ - acl.unsupported |= - (HCI_PKT_TYPES_MASK_NO_3_DH1 | HCI_PKT_TYPES_MASK_NO_3_DH3 | - HCI_PKT_TYPES_MASK_NO_3_DH5); + acl.unsupported |= (HCI_PKT_TYPES_MASK_NO_3_DH1 | HCI_PKT_TYPES_MASK_NO_3_DH3 | + HCI_PKT_TYPES_MASK_NO_3_DH5); + } /* EDR 3 and 5 slot support? */ - if (HCI_EDR_ACL_2MPS_SUPPORTED(features) || - HCI_EDR_ACL_3MPS_SUPPORTED(features)) { - if (!HCI_3_SLOT_EDR_ACL_SUPPORTED(features)) + if (HCI_EDR_ACL_2MPS_SUPPORTED(features) || HCI_EDR_ACL_3MPS_SUPPORTED(features)) { + if (!HCI_3_SLOT_EDR_ACL_SUPPORTED(features)) { /* Not supported. Add 'not_supported' mask for all 3-slot EDR packet * types */ - acl.unsupported |= - (HCI_PKT_TYPES_MASK_NO_2_DH3 | HCI_PKT_TYPES_MASK_NO_3_DH3); + acl.unsupported |= (HCI_PKT_TYPES_MASK_NO_2_DH3 | HCI_PKT_TYPES_MASK_NO_3_DH3); + } - if (!HCI_5_SLOT_EDR_ACL_SUPPORTED(features)) + if (!HCI_5_SLOT_EDR_ACL_SUPPORTED(features)) { /* Not supported. Add 'not_supported' mask for all 5-slot EDR packet * types */ - acl.unsupported |= - (HCI_PKT_TYPES_MASK_NO_2_DH5 | HCI_PKT_TYPES_MASK_NO_3_DH5); + acl.unsupported |= (HCI_PKT_TYPES_MASK_NO_2_DH5 | HCI_PKT_TYPES_MASK_NO_3_DH5); + } } } }; diff --git a/system/stack/arbiter/acl_arbiter.cc b/system/stack/arbiter/acl_arbiter.cc index c2fc1c04ba0..4193f342164 100644 --- a/system/stack/arbiter/acl_arbiter.cc +++ b/system/stack/arbiter/acl_arbiter.cc @@ -35,8 +35,7 @@ namespace { struct RustArbiterCallbacks { ::rust::Fn on_le_connect; ::rust::Fn on_le_disconnect; - ::rust::Fn buffer)> - intercept_packet; + ::rust::Fn buffer)> intercept_packet; ::rust::Fn on_outgoing_mtu_req; ::rust::Fn on_incoming_mtu_resp; ::rust::Fn on_incoming_mtu_req; @@ -61,8 +60,7 @@ void AclArbiter::OnLeDisconnect(uint8_t tcb_idx) { callbacks_.on_le_disconnect(tcb_idx); } -InterceptAction AclArbiter::InterceptAttPacket(uint8_t tcb_idx, - const BT_HDR* packet) { +InterceptAction AclArbiter::InterceptAttPacket(uint8_t tcb_idx, const BT_HDR* packet) { #ifdef TARGET_FLOSS return InterceptAction::FORWARD; #endif @@ -100,15 +98,13 @@ void AclArbiter::OnIncomingMtuReq(uint8_t tcb_idx, size_t mtu) { callbacks_.on_incoming_mtu_req(tcb_idx, mtu); } -void AclArbiter::SendPacketToPeer(uint8_t tcb_idx, - ::rust::Vec buffer) { +void AclArbiter::SendPacketToPeer(uint8_t tcb_idx, ::rust::Vec buffer) { #ifdef TARGET_FLOSS return; #endif tGATT_TCB* p_tcb = gatt_get_tcb_by_idx(tcb_idx); if (p_tcb != nullptr) { - BT_HDR* p_buf = - (BT_HDR*)osi_malloc(sizeof(BT_HDR) + buffer.size() + L2CAP_MIN_OFFSET); + BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + buffer.size() + L2CAP_MIN_OFFSET); if (p_buf == nullptr) { log::fatal("OOM when sending packet"); } @@ -118,8 +114,8 @@ void AclArbiter::SendPacketToPeer(uint8_t tcb_idx, p_buf->len = buffer.size(); if (L2CA_SendFixedChnlData(L2CAP_ATT_CID, p_tcb->peer_bda, p_buf) != tL2CAP_DW_RESULT::SUCCESS) { - log::warn("Unable to send L2CAP data peer:{} fixed_cid:{} len:{}", - p_tcb->peer_bda, L2CAP_ATT_CID, p_buf->len); + log::warn("Unable to send L2CAP data peer:{} fixed_cid:{} len:{}", p_tcb->peer_bda, + L2CAP_ATT_CID, p_buf->len); } } else { log::error("Dropping packet since connection no longer exists"); @@ -127,22 +123,21 @@ void AclArbiter::SendPacketToPeer(uint8_t tcb_idx, } void StoreCallbacksFromRust( - ::rust::Fn on_le_connect, - ::rust::Fn on_le_disconnect, - ::rust::Fn buffer)> - intercept_packet, - ::rust::Fn on_outgoing_mtu_req, - ::rust::Fn on_incoming_mtu_resp, - ::rust::Fn on_incoming_mtu_req) { + ::rust::Fn on_le_connect, + ::rust::Fn on_le_disconnect, + ::rust::Fn buffer)> intercept_packet, + ::rust::Fn on_outgoing_mtu_req, + ::rust::Fn on_incoming_mtu_resp, + ::rust::Fn on_incoming_mtu_req) { log::info("Received callbacks from Rust, registering in Arbiter"); callbacks_ = {on_le_connect, on_le_disconnect, intercept_packet, on_outgoing_mtu_req, on_incoming_mtu_resp, on_incoming_mtu_req}; } void SendPacketToPeer(uint8_t tcb_idx, ::rust::Vec buffer) { - do_in_main_thread(FROM_HERE, base::BindOnce(&AclArbiter::SendPacketToPeer, - base::Unretained(&GetArbiter()), - tcb_idx, std::move(buffer))); + do_in_main_thread(FROM_HERE, + base::BindOnce(&AclArbiter::SendPacketToPeer, base::Unretained(&GetArbiter()), + tcb_idx, std::move(buffer))); } AclArbiter& GetArbiter() { diff --git a/system/stack/arbiter/acl_arbiter.h b/system/stack/arbiter/acl_arbiter.h index 65c6df796cb..263ec99d770 100644 --- a/system/stack/arbiter/acl_arbiter.h +++ b/system/stack/arbiter/acl_arbiter.h @@ -38,7 +38,7 @@ enum class InterceptAction { }; class AclArbiter { - public: +public: void OnLeConnect(uint8_t tcb_idx, uint16_t advertiser_id); void OnLeDisconnect(uint8_t tcb_idx); InterceptAction InterceptAttPacket(uint8_t tcb_idx, const BT_HDR* packet); @@ -56,13 +56,12 @@ class AclArbiter { }; void StoreCallbacksFromRust( - ::rust::Fn on_le_connect, - ::rust::Fn on_le_disconnect, - ::rust::Fn buffer)> - intercept_packet, - ::rust::Fn on_outgoing_mtu_req, - ::rust::Fn on_incoming_mtu_resp, - ::rust::Fn on_incoming_mtu_req); + ::rust::Fn on_le_connect, + ::rust::Fn on_le_disconnect, + ::rust::Fn buffer)> intercept_packet, + ::rust::Fn on_outgoing_mtu_req, + ::rust::Fn on_incoming_mtu_resp, + ::rust::Fn on_incoming_mtu_req); void SendPacketToPeer(uint8_t tcb_idx, ::rust::Vec buffer); diff --git a/system/stack/avct/avct_api.cc b/system/stack/avct/avct_api.cc index c9dd22ec311..b9ded9cf1f3 100644 --- a/system/stack/avct/avct_api.cc +++ b/system/stack/avct/avct_api.cc @@ -62,23 +62,20 @@ void AVCT_Register() { memset(&avct_cb, 0, sizeof(tAVCT_CB)); /* register PSM with L2CAP */ - if (!L2CA_RegisterWithSecurity(AVCT_PSM, avct_l2c_appl, - true /* enable_snoop */, nullptr, kAvrcMtu, 0, - BTA_SEC_AUTHENTICATE)) { - log::error( - "Unable to register with L2CAP AVCT profile psm:AVCT_PSM[0x0017]"); + if (!L2CA_RegisterWithSecurity(AVCT_PSM, avct_l2c_appl, true /* enable_snoop */, nullptr, + kAvrcMtu, 0, BTA_SEC_AUTHENTICATE)) { + log::error("Unable to register with L2CAP AVCT profile psm:AVCT_PSM[0x0017]"); } /* Include the browsing channel which uses eFCR */ tL2CAP_ERTM_INFO ertm_info; ertm_info.preferred_mode = L2CAP_FCR_ERTM_MODE; - if (!L2CA_RegisterWithSecurity(AVCT_BR_PSM, avct_l2c_br_appl, - true /*enable_snoop*/, &ertm_info, kAvrcBrMtu, - AVCT_MIN_BROWSE_MTU, BTA_SEC_AUTHENTICATE)) { + if (!L2CA_RegisterWithSecurity(AVCT_BR_PSM, avct_l2c_br_appl, true /*enable_snoop*/, &ertm_info, + kAvrcBrMtu, AVCT_MIN_BROWSE_MTU, BTA_SEC_AUTHENTICATE)) { log::error( - "Unable to register with L2CAP AVCT_BR profile " - "psm:AVCT_BR_PSM[0x001b]"); + "Unable to register with L2CAP AVCT_BR profile " + "psm:AVCT_BR_PSM[0x001b]"); } } @@ -120,8 +117,7 @@ void AVCT_Deregister(void) { * Returns AVCT_SUCCESS if successful, otherwise error. * ******************************************************************************/ -uint16_t AVCT_CreateConn(uint8_t* p_handle, tAVCT_CC* p_cc, - const RawAddress& peer_addr) { +uint16_t AVCT_CreateConn(uint8_t* p_handle, tAVCT_CC* p_cc, const RawAddress& peer_addr) { uint16_t result = AVCT_SUCCESS; tAVCT_CCB* p_ccb; tAVCT_LCB* p_lcb; diff --git a/system/stack/avct/avct_bcb_act.cc b/system/stack/avct/avct_bcb_act.cc index 853d3b66389..c7466e4efb8 100644 --- a/system/stack/avct/avct_bcb_act.cc +++ b/system/stack/avct/avct_bcb_act.cc @@ -45,22 +45,22 @@ using namespace bluetooth; /* action function list */ const tAVCT_BCB_ACTION avct_bcb_action[] = { - avct_bcb_chnl_open, /* AVCT_LCB_CHNL_OPEN */ - avct_bcb_chnl_disc, /* AVCT_LCB_CHNL_DISC */ - avct_bcb_send_msg, /* AVCT_LCB_SEND_MSG */ - avct_bcb_open_ind, /* AVCT_LCB_OPEN_IND */ - avct_bcb_open_fail, /* AVCT_LCB_OPEN_FAIL */ - avct_bcb_close_ind, /* AVCT_LCB_CLOSE_IND */ - avct_bcb_close_cfm, /* AVCT_LCB_CLOSE_CFM */ - avct_bcb_msg_ind, /* AVCT_LCB_MSG_IND */ - avct_bcb_cong_ind, /* AVCT_LCB_CONG_IND */ - avct_bcb_bind_conn, /* AVCT_LCB_BIND_CONN */ - avct_bcb_bind_fail, /* AVCT_LCB_BIND_FAIL */ - avct_bcb_unbind_disc, /* AVCT_LCB_UNBIND_DISC */ - avct_bcb_chk_disc, /* AVCT_LCB_CHK_DISC */ - avct_bcb_discard_msg, /* AVCT_LCB_DISCARD_MSG */ - avct_bcb_dealloc, /* AVCT_LCB_DEALLOC */ - avct_bcb_free_msg_ind /* AVCT_LCB_FREE_MSG_IND */ + avct_bcb_chnl_open, /* AVCT_LCB_CHNL_OPEN */ + avct_bcb_chnl_disc, /* AVCT_LCB_CHNL_DISC */ + avct_bcb_send_msg, /* AVCT_LCB_SEND_MSG */ + avct_bcb_open_ind, /* AVCT_LCB_OPEN_IND */ + avct_bcb_open_fail, /* AVCT_LCB_OPEN_FAIL */ + avct_bcb_close_ind, /* AVCT_LCB_CLOSE_IND */ + avct_bcb_close_cfm, /* AVCT_LCB_CLOSE_CFM */ + avct_bcb_msg_ind, /* AVCT_LCB_MSG_IND */ + avct_bcb_cong_ind, /* AVCT_LCB_CONG_IND */ + avct_bcb_bind_conn, /* AVCT_LCB_BIND_CONN */ + avct_bcb_bind_fail, /* AVCT_LCB_BIND_FAIL */ + avct_bcb_unbind_disc, /* AVCT_LCB_UNBIND_DISC */ + avct_bcb_chk_disc, /* AVCT_LCB_CHK_DISC */ + avct_bcb_discard_msg, /* AVCT_LCB_DISCARD_MSG */ + avct_bcb_dealloc, /* AVCT_LCB_DEALLOC */ + avct_bcb_free_msg_ind /* AVCT_LCB_FREE_MSG_IND */ }; /******************************************************************************* @@ -115,8 +115,7 @@ void avct_bcb_chnl_open(tAVCT_BCB* p_bcb, tAVCT_LCB_EVT* /* p_data */) { /* call l2cap connect req */ p_bcb->ch_state = AVCT_CH_CONN; - p_bcb->ch_lcid = L2CA_ConnectReqWithSecurity(AVCT_BR_PSM, p_lcb->peer_addr, - BTA_SEC_AUTHENTICATE); + p_bcb->ch_lcid = L2CA_ConnectReqWithSecurity(AVCT_BR_PSM, p_lcb->peer_addr, BTA_SEC_AUTHENTICATE); if (p_bcb->ch_lcid == 0) { /* if connect req failed, send ourselves close event */ tAVCT_LCB_EVT avct_lcb_evt; @@ -137,8 +136,8 @@ void avct_bcb_chnl_open(tAVCT_BCB* p_bcb, tAVCT_LCB_EVT* /* p_data */) { ******************************************************************************/ void avct_bcb_unbind_disc(tAVCT_BCB* /* p_bcb */, tAVCT_LCB_EVT* p_data) { p_data->p_ccb->p_bcb = NULL; - (*p_data->p_ccb->cc.p_ctrl_cback)(avct_ccb_to_idx(p_data->p_ccb), - AVCT_BROWSE_DISCONN_CFM_EVT, 0, NULL); + (*p_data->p_ccb->cc.p_ctrl_cback)(avct_ccb_to_idx(p_data->p_ccb), AVCT_BROWSE_DISCONN_CFM_EVT, 0, + NULL); } /******************************************************************************* @@ -168,20 +167,19 @@ void avct_bcb_open_ind(tAVCT_BCB* p_bcb, tAVCT_LCB_EVT* p_data) { if (p_ccb->p_bcb == p_bcb) { bind = true; p_ccb_bind = p_ccb; - p_ccb->cc.p_ctrl_cback(avct_ccb_to_idx(p_ccb), AVCT_BROWSE_CONN_CFM_EVT, - 0, &p_ccb->p_lcb->peer_addr); + p_ccb->cc.p_ctrl_cback(avct_ccb_to_idx(p_ccb), AVCT_BROWSE_CONN_CFM_EVT, 0, + &p_ccb->p_lcb->peer_addr); } /* if unbound acceptor and lcb allocated and bd_addr are the same for bcb and lcb */ - else if ((p_ccb->p_bcb == NULL) && (p_ccb->cc.role == AVCT_ACP) && - (p_ccb->p_lcb != NULL) && + else if ((p_ccb->p_bcb == NULL) && (p_ccb->cc.role == AVCT_ACP) && (p_ccb->p_lcb != NULL) && p_bcb->peer_addr == p_ccb->p_lcb->peer_addr) { /* bind bcb to ccb and send connect ind event */ bind = true; p_ccb_bind = p_ccb; p_ccb->p_bcb = p_bcb; - p_ccb->cc.p_ctrl_cback(avct_ccb_to_idx(p_ccb), AVCT_BROWSE_CONN_IND_EVT, - 0, &p_ccb->p_lcb->peer_addr); + p_ccb->cc.p_ctrl_cback(avct_ccb_to_idx(p_ccb), AVCT_BROWSE_CONN_IND_EVT, 0, + &p_ccb->p_lcb->peer_addr); } } } @@ -248,12 +246,10 @@ void avct_bcb_close_ind(tAVCT_BCB* p_bcb, tAVCT_LCB_EVT* /* p_data */) { for (int idx = 0; idx < AVCT_NUM_CONN; idx++, p_ccb++) { if (p_ccb->allocated && (p_ccb->p_bcb == p_bcb)) { if (p_ccb->cc.role == AVCT_INT) { - (*p_ccb->cc.p_ctrl_cback)(avct_ccb_to_idx(p_ccb), - AVCT_BROWSE_DISCONN_CFM_EVT, 0, + (*p_ccb->cc.p_ctrl_cback)(avct_ccb_to_idx(p_ccb), AVCT_BROWSE_DISCONN_CFM_EVT, 0, &p_lcb->peer_addr); } else { - (*p_ccb->cc.p_ctrl_cback)(avct_ccb_to_idx(p_ccb), - AVCT_BROWSE_DISCONN_IND_EVT, 0, + (*p_ccb->cc.p_ctrl_cback)(avct_ccb_to_idx(p_ccb), AVCT_BROWSE_DISCONN_IND_EVT, 0, &p_lcb->peer_addr); } p_ccb->p_bcb = NULL; @@ -292,9 +288,10 @@ void avct_bcb_close_cfm(tAVCT_BCB* p_bcb, tAVCT_LCB_EVT* p_data) { p_cback = p_ccb->cc.p_ctrl_cback; p_ccb->p_bcb = NULL; - if (p_ccb->p_lcb == NULL) avct_ccb_dealloc(p_ccb, AVCT_NO_EVT, 0, NULL); - (*p_cback)(avct_ccb_to_idx(p_ccb), event, p_data->result, - &p_bcb->peer_addr); + if (p_ccb->p_lcb == NULL) { + avct_ccb_dealloc(p_ccb, AVCT_NO_EVT, 0, NULL); + } + (*p_cback)(avct_ccb_to_idx(p_ccb), event, p_data->result, &p_bcb->peer_addr); } } } @@ -312,8 +309,7 @@ void avct_bcb_close_cfm(tAVCT_BCB* p_bcb, tAVCT_LCB_EVT* p_data) { void avct_bcb_bind_conn(tAVCT_BCB* p_bcb, tAVCT_LCB_EVT* p_data) { tAVCT_LCB* p_lcb = avct_lcb_by_bcb(p_bcb); p_data->p_ccb->p_bcb = p_bcb; - (*p_data->p_ccb->cc.p_ctrl_cback)(avct_ccb_to_idx(p_data->p_ccb), - AVCT_BROWSE_CONN_CFM_EVT, 0, + (*p_data->p_ccb->cc.p_ctrl_cback)(avct_ccb_to_idx(p_data->p_ccb), AVCT_BROWSE_CONN_CFM_EVT, 0, &p_lcb->peer_addr); } @@ -366,9 +362,8 @@ void avct_bcb_chnl_disc(tAVCT_BCB* p_bcb, tAVCT_LCB_EVT* /* p_data */) { ******************************************************************************/ void avct_bcb_bind_fail(tAVCT_BCB* /* p_bcb */, tAVCT_LCB_EVT* p_data) { p_data->p_ccb->p_bcb = NULL; - (*p_data->p_ccb->cc.p_ctrl_cback)(avct_ccb_to_idx(p_data->p_ccb), - AVCT_BROWSE_CONN_CFM_EVT, AVCT_RESULT_FAIL, - NULL); + (*p_data->p_ccb->cc.p_ctrl_cback)(avct_ccb_to_idx(p_data->p_ccb), AVCT_BROWSE_CONN_CFM_EVT, + AVCT_RESULT_FAIL, NULL); } /******************************************************************************* @@ -387,14 +382,12 @@ void avct_bcb_cong_ind(tAVCT_BCB* p_bcb, tAVCT_LCB_EVT* p_data) { tAVCT_LCB* p_lcb = avct_lcb_by_bcb(p_bcb); /* set event */ - event = - (p_data->cong) ? AVCT_BROWSE_CONG_IND_EVT : AVCT_BROWSE_UNCONG_IND_EVT; + event = (p_data->cong) ? AVCT_BROWSE_CONG_IND_EVT : AVCT_BROWSE_UNCONG_IND_EVT; /* send event to all ccbs on this lcb */ for (int idx = 0; idx < AVCT_NUM_CONN; idx++, p_ccb++) { if (p_ccb->allocated && (p_ccb->p_bcb == p_bcb)) { - (*p_ccb->cc.p_ctrl_cback)(avct_ccb_to_idx(p_ccb), event, 0, - &p_lcb->peer_addr); + (*p_ccb->cc.p_ctrl_cback)(avct_ccb_to_idx(p_ccb), event, 0, &p_lcb->peer_addr); } } } @@ -420,15 +413,13 @@ void avct_bcb_discard_msg(tAVCT_BCB* p_bcb, tAVCT_LCB_EVT* p_data) { p_bcb->p_tx_msg = p_data->ul_msg.p_buf; if (p_bcb->p_tx_msg) { - p_bcb->p_tx_msg->layer_specific = - (p_data->ul_msg.cr << 8) + p_data->ul_msg.label; + p_bcb->p_tx_msg->layer_specific = (p_data->ul_msg.cr << 8) + p_data->ul_msg.label; /* the channel is closed, opening or closing - open it again */ - log::verbose("ch_state: {}, allocated:{}->{}", p_bcb->ch_state, - p_bcb->allocated, p_data->ul_msg.p_ccb->p_lcb->allocated); + log::verbose("ch_state: {}, allocated:{}->{}", p_bcb->ch_state, p_bcb->allocated, + p_data->ul_msg.p_ccb->p_lcb->allocated); p_bcb->allocated = p_data->ul_msg.p_ccb->p_lcb->allocated; - avct_bcb_event(p_bcb, AVCT_LCB_UL_BIND_EVT, - (tAVCT_LCB_EVT*)p_data->ul_msg.p_ccb); + avct_bcb_event(p_bcb, AVCT_LCB_UL_BIND_EVT, (tAVCT_LCB_EVT*)p_data->ul_msg.p_ccb); } } @@ -454,8 +445,8 @@ void avct_bcb_send_msg(tAVCT_BCB* p_bcb, tAVCT_LCB_EVT* p_data) { /* initialize packet type and other stuff */ if (curr_msg_len > (p_bcb->peer_mtu - AVCT_HDR_LEN_SINGLE)) { - log::error("msg len ({}) exceeds peer mtu({}-{})!!", curr_msg_len, - p_bcb->peer_mtu, AVCT_HDR_LEN_SINGLE); + log::error("msg len ({}) exceeds peer mtu({}-{})!!", curr_msg_len, p_bcb->peer_mtu, + AVCT_HDR_LEN_SINGLE); osi_free_and_reset((void**)&p_data->ul_msg.p_buf); return; } @@ -477,8 +468,7 @@ void avct_bcb_send_msg(tAVCT_BCB* p_bcb, tAVCT_LCB_EVT* p_data) { /* send message to L2CAP */ if (L2CA_DataWrite(p_bcb->ch_lcid, p_buf) != tL2CAP_DW_RESULT::SUCCESS) { - log::warn("Unable to write L2CAP data peer:{} cid:{}", p_bcb->peer_addr, - p_bcb->ch_lcid); + log::warn("Unable to write L2CAP data peer:{} cid:{}", p_bcb->peer_addr, p_bcb->ch_lcid); } } @@ -493,7 +483,9 @@ void avct_bcb_send_msg(tAVCT_BCB* p_bcb, tAVCT_LCB_EVT* p_data) { * ******************************************************************************/ void avct_bcb_free_msg_ind(tAVCT_BCB* /* p_bcb */, tAVCT_LCB_EVT* p_data) { - if (p_data) osi_free_and_reset((void**)&p_data->p_buf); + if (p_data) { + osi_free_and_reset((void**)&p_data->p_buf); + } } /******************************************************************************* @@ -531,8 +523,8 @@ void avct_bcb_msg_ind(tAVCT_BCB* p_bcb, tAVCT_LCB_EVT* p_data) { } if (p_data->p_buf->len < AVCT_HDR_LEN_SINGLE) { - log::warn("Invalid AVCTP packet length {}: must be at least {}", - p_data->p_buf->len, AVCT_HDR_LEN_SINGLE); + log::warn("Invalid AVCTP packet length {}: must be at least {}", p_data->p_buf->len, + AVCT_HDR_LEN_SINGLE); osi_free_and_reset((void**)&p_data->p_buf); return; } @@ -555,7 +547,9 @@ void avct_bcb_msg_ind(tAVCT_BCB* p_bcb, tAVCT_LCB_EVT* p_data) { if (btif_av_src_sink_coexist_enabled()) { bind = avct_msg_ind_for_src_sink_coexist(p_lcb, p_data, label, cr_ipid); osi_free_and_reset((void**)&p_data->p_buf); - if (bind) return; + if (bind) { + return; + } } else { /* lookup PID */ p_ccb = avct_lcb_has_pid(p_lcb, pid); @@ -563,8 +557,7 @@ void avct_bcb_msg_ind(tAVCT_BCB* p_bcb, tAVCT_LCB_EVT* p_data) { /* PID found; send msg up, adjust bt hdr and call msg callback */ p_data->p_buf->offset += AVCT_HDR_LEN_SINGLE; p_data->p_buf->len -= AVCT_HDR_LEN_SINGLE; - (*p_ccb->cc.p_msg_cback)(avct_ccb_to_idx(p_ccb), label, cr_ipid, - p_data->p_buf); + (*p_ccb->cc.p_msg_cback)(avct_ccb_to_idx(p_ccb), label, cr_ipid, p_data->p_buf); return; } } @@ -583,8 +576,7 @@ void avct_bcb_msg_ind(tAVCT_BCB* p_bcb, tAVCT_LCB_EVT* p_data) { UINT16_TO_BE_STREAM(p, pid); p_buf->layer_specific = AVCT_DATA_BROWSE; if (L2CA_DataWrite(p_bcb->ch_lcid, p_buf) != tL2CAP_DW_RESULT::SUCCESS) { - log::warn("Unable to write L2CAP data peer:{} cid:{}", p_bcb->peer_addr, - p_bcb->ch_lcid); + log::warn("Unable to write L2CAP data peer:{} cid:{}", p_bcb->peer_addr, p_bcb->ch_lcid); } } } @@ -644,9 +636,7 @@ void avct_close_bcb(tAVCT_LCB* p_lcb, tAVCT_LCB_EVT* p_data) { * Returns pointer to the lcb. * ******************************************************************************/ -tAVCT_LCB* avct_lcb_by_bcb(tAVCT_BCB* p_bcb) { - return &avct_cb.lcb[p_bcb->allocated - 1]; -} +tAVCT_LCB* avct_lcb_by_bcb(tAVCT_BCB* p_bcb) { return &avct_cb.lcb[p_bcb->allocated - 1]; } /******************************************************************************* * @@ -657,9 +647,7 @@ tAVCT_LCB* avct_lcb_by_bcb(tAVCT_BCB* p_bcb) { * Returns pointer to the lcb. * ******************************************************************************/ -tAVCT_BCB* avct_bcb_by_lcb(tAVCT_LCB* p_lcb) { - return &avct_cb.bcb[p_lcb->allocated - 1]; -} +tAVCT_BCB* avct_bcb_by_lcb(tAVCT_LCB* p_lcb) { return &avct_cb.bcb[p_lcb->allocated - 1]; } /******************************************************************************* * @@ -677,7 +665,9 @@ uint8_t avct_bcb_get_last_ccb_index(tAVCT_BCB* p_bcb, tAVCT_CCB* p_ccb_last) { for (int i = 0; i < AVCT_NUM_CONN; i++, p_ccb++) { if (p_ccb->allocated && (p_ccb->p_bcb == p_bcb)) { - if (p_ccb != p_ccb_last) return 0; + if (p_ccb != p_ccb_last) { + return 0; + } idx = (uint8_t)(i + 1); } } @@ -699,8 +689,7 @@ tAVCT_BCB* avct_bcb_by_lcid(uint16_t lcid) { int idx; for (idx = 0; idx < AVCT_NUM_LINKS; idx++, p_bcb++) { - if (p_bcb->allocated && - ((p_bcb->ch_lcid == lcid) || (p_bcb->conflict_lcid == lcid))) { + if (p_bcb->allocated && ((p_bcb->ch_lcid == lcid) || (p_bcb->conflict_lcid == lcid))) { return p_bcb; } } diff --git a/system/stack/avct/avct_ccb.cc b/system/stack/avct/avct_ccb.cc index c31df28d802..6210fd2fa7b 100644 --- a/system/stack/avct/avct_ccb.cc +++ b/system/stack/avct/avct_ccb.cc @@ -77,8 +77,7 @@ tAVCT_CCB* avct_ccb_alloc(tAVCT_CC* p_cc) { * Returns void. * ******************************************************************************/ -void avct_ccb_dealloc(tAVCT_CCB* p_ccb, uint8_t event, uint16_t result, - const RawAddress* bd_addr) { +void avct_ccb_dealloc(tAVCT_CCB* p_ccb, uint8_t event, uint16_t result, const RawAddress* bd_addr) { tAVCT_CTRL_CBACK* p_cback = p_ccb->cc.p_ctrl_cback; log::verbose("avct_ccb_dealloc {}", avct_ccb_to_idx(p_ccb)); @@ -88,8 +87,7 @@ void avct_ccb_dealloc(tAVCT_CCB* p_ccb, uint8_t event, uint16_t result, } else { /* control channel is down, but the browsing channel is still connected 0 * disconnect it now */ - avct_bcb_event(p_ccb->p_bcb, AVCT_LCB_UL_UNBIND_EVT, - (tAVCT_LCB_EVT*)&p_ccb); + avct_bcb_event(p_ccb->p_bcb, AVCT_LCB_UL_UNBIND_EVT, (tAVCT_LCB_EVT*)&p_ccb); p_ccb->p_lcb = NULL; } diff --git a/system/stack/avct/avct_defs.h b/system/stack/avct/avct_defs.h index 71748c5020e..c01def85e3d 100644 --- a/system/stack/avct/avct_defs.h +++ b/system/stack/avct/avct_defs.h @@ -48,8 +48,7 @@ * message parsing and building macros ****************************************************************************/ -#define AVCT_BUILD_HDR(p, label, type, cr_ipid) \ - *(p)++ = ((label) << 4) | ((type) << 2) | (cr_ipid); +#define AVCT_BUILD_HDR(p, label, type, cr_ipid) *(p)++ = ((label) << 4) | ((type) << 2) | (cr_ipid); #define AVCT_PARSE_HDR(p, label, type, cr_ipid) \ do { \ diff --git a/system/stack/avct/avct_int.h b/system/stack/avct/avct_int.h index 50a53f2ced2..c7d1eebf4cb 100644 --- a/system/stack/avct/avct_int.h +++ b/system/stack/avct/avct_int.h @@ -86,17 +86,17 @@ typedef struct { /* browse control block type */ typedef struct { - uint16_t peer_mtu; /* peer l2c mtu */ - uint16_t ch_result; /* L2CAP connection result value */ - uint16_t ch_lcid; /* L2CAP channel LCID */ - uint8_t allocated; /* 0, not allocated. index+1, otherwise. */ - uint8_t state; /* The state machine state */ - uint8_t ch_state; /* L2CAP channel state */ + uint16_t peer_mtu; /* peer l2c mtu */ + uint16_t ch_result; /* L2CAP connection result value */ + uint16_t ch_lcid; /* L2CAP channel LCID */ + uint8_t allocated; /* 0, not allocated. index+1, otherwise. */ + uint8_t state; /* The state machine state */ + uint8_t ch_state; /* L2CAP channel state */ uint16_t conflict_lcid; /* L2CAP channel LCID */ - BT_HDR* p_tx_msg; /* Message to be sent - in case the browsing channel is not - open when MsgReg is called */ - uint8_t ch_close; /* CCB index+1, if CCB initiated channel close */ - RawAddress peer_addr; /* BD address of peer */ + BT_HDR* p_tx_msg; /* Message to be sent - in case the browsing channel is not + open when MsgReg is called */ + uint8_t ch_close; /* CCB index+1, if CCB initiated channel close */ + RawAddress peer_addr; /* BD address of peer */ } tAVCT_BCB; #define AVCT_ALOC_LCB 0x01 @@ -196,13 +196,11 @@ extern const uint8_t avct_lcb_pkt_type_len[]; /* CCB function declarations */ tAVCT_CCB* avct_ccb_alloc(tAVCT_CC* p_cc); -void avct_ccb_dealloc(tAVCT_CCB* p_ccb, uint8_t event, uint16_t result, - const RawAddress* bd_addr); +void avct_ccb_dealloc(tAVCT_CCB* p_ccb, uint8_t event, uint16_t result, const RawAddress* bd_addr); uint8_t avct_ccb_to_idx(tAVCT_CCB* p_ccb); tAVCT_CCB* avct_ccb_by_idx(uint8_t idx); -extern bool avct_msg_ind_for_src_sink_coexist(tAVCT_LCB* p_lcb, - tAVCT_LCB_EVT* p_data, +extern bool avct_msg_ind_for_src_sink_coexist(tAVCT_LCB* p_lcb, tAVCT_LCB_EVT* p_data, uint8_t label, uint8_t cr_ipid); /***************************************************************************** diff --git a/system/stack/avct/avct_l2c.cc b/system/stack/avct/avct_l2c.cc index c472cbf1a51..225572d09f0 100644 --- a/system/stack/avct/avct_l2c.cc +++ b/system/stack/avct/avct_l2c.cc @@ -39,11 +39,9 @@ using namespace bluetooth; /* callback function declarations */ -void avct_l2c_connect_ind_cback(const RawAddress& bd_addr, uint16_t lcid, - uint16_t psm, uint8_t id); +void avct_l2c_connect_ind_cback(const RawAddress& bd_addr, uint16_t lcid, uint16_t psm, uint8_t id); void avct_l2c_connect_cfm_cback(uint16_t lcid, uint16_t result); -void avct_l2c_config_cfm_cback(uint16_t lcid, uint16_t result, - tL2CAP_CFG_INFO* p_cfg); +void avct_l2c_config_cfm_cback(uint16_t lcid, uint16_t result, tL2CAP_CFG_INFO* p_cfg); void avct_l2c_config_ind_cback(uint16_t lcid, tL2CAP_CFG_INFO* p_cfg); void avct_l2c_disconnect_ind_cback(uint16_t lcid, bool ack_needed); void avct_l2c_congestion_ind_cback(uint16_t lcid, bool is_congested); @@ -52,20 +50,20 @@ static void avct_on_l2cap_error(uint16_t lcid, uint16_t result); /* L2CAP callback function structure */ const tL2CAP_APPL_INFO avct_l2c_appl = { - avct_l2c_connect_ind_cback, - avct_l2c_connect_cfm_cback, - avct_l2c_config_ind_cback, - avct_l2c_config_cfm_cback, - avct_l2c_disconnect_ind_cback, - NULL, - avct_l2c_data_ind_cback, - avct_l2c_congestion_ind_cback, - NULL, - avct_on_l2cap_error, - NULL, - NULL, - NULL, - NULL, + avct_l2c_connect_ind_cback, + avct_l2c_connect_cfm_cback, + avct_l2c_config_ind_cback, + avct_l2c_config_cfm_cback, + avct_l2c_disconnect_ind_cback, + NULL, + avct_l2c_data_ind_cback, + avct_l2c_congestion_ind_cback, + NULL, + avct_on_l2cap_error, + NULL, + NULL, + NULL, + NULL, }; /******************************************************************************* @@ -105,8 +103,8 @@ static bool avct_l2c_is_passive(tAVCT_LCB* p_lcb) { * Returns void * ******************************************************************************/ -void avct_l2c_connect_ind_cback(const RawAddress& bd_addr, uint16_t lcid, - uint16_t /* psm */, uint8_t id) { +void avct_l2c_connect_ind_cback(const RawAddress& bd_addr, uint16_t lcid, uint16_t /* psm */, + uint8_t id) { tAVCT_LCB* p_lcb; uint16_t result = L2CAP_CONN_OK; @@ -129,21 +127,19 @@ void avct_l2c_connect_ind_cback(const RawAddress& bd_addr, uint16_t lcid, /* TG role only - accept the connection from CT. move the channel ID to * the conflict list */ p_lcb->conflict_lcid = p_lcb->ch_lcid; - log::verbose("avct_l2c_connect_ind_cback conflict_lcid:0x{:x}", - p_lcb->conflict_lcid); + log::verbose("avct_l2c_connect_ind_cback conflict_lcid:0x{:x}", p_lcb->conflict_lcid); } } if (p_lcb) { - log::verbose("avct_l2c_connect_ind_cback: 0x{:x}, res: {}, ch_state: {}", - lcid, result, p_lcb->ch_state); + log::verbose("avct_l2c_connect_ind_cback: 0x{:x}, res: {}, ch_state: {}", lcid, result, + p_lcb->ch_state); } /* If we reject the connection, send DisconnectReq */ if (result != L2CAP_CONN_OK) { if (!L2CA_DisconnectReq(lcid)) { - log::warn("Unable to send L2CAP disconnect request peer:{} cid:{}", - bd_addr, lcid); + log::warn("Unable to send L2CAP disconnect request peer:{} cid:{}", bd_addr, lcid); } } @@ -152,13 +148,10 @@ void avct_l2c_connect_ind_cback(const RawAddress& bd_addr, uint16_t lcid, if (btif_av_src_sink_coexist_enabled()) { tAVCT_CCB* p_ccb = &avct_cb.ccb[0]; for (int i = 0; i < AVCT_NUM_CONN; i++, p_ccb++) { - if (p_ccb && p_ccb->allocated && (p_ccb->p_lcb == NULL) && - (p_ccb->cc.role == AVCT_ACP)) { + if (p_ccb && p_ccb->allocated && (p_ccb->p_lcb == NULL) && (p_ccb->cc.role == AVCT_ACP)) { p_ccb->p_lcb = p_lcb; - log::verbose( - "ACP bind {} ccb to lcb, alloc {}, lcb {}, role {}, pid 0x{:x}", - i, p_ccb->allocated, fmt::ptr(p_ccb->p_lcb), p_ccb->cc.role, - p_ccb->cc.pid); + log::verbose("ACP bind {} ccb to lcb, alloc {}, lcb {}, role {}, pid 0x{:x}", i, + p_ccb->allocated, fmt::ptr(p_ccb->p_lcb), p_ccb->cc.role, p_ccb->cc.pid); } } } @@ -169,15 +162,18 @@ void avct_l2c_connect_ind_cback(const RawAddress& bd_addr, uint16_t lcid, p_lcb->ch_state = AVCT_CH_CFG; } - if (p_lcb) log::verbose("ch_state cni: {}", p_lcb->ch_state); + if (p_lcb) { + log::verbose("ch_state cni: {}", p_lcb->ch_state); + } } static void avct_on_l2cap_error(uint16_t lcid, uint16_t result) { tAVCT_LCB* p_lcb = avct_lcb_by_lcid(lcid); - if (p_lcb == nullptr) return; + if (p_lcb == nullptr) { + return; + } if (p_lcb->ch_state == AVCT_CH_CONN) { - log::verbose("avct_l2c_connect_cfm_cback conflict_lcid:0x{:x}", - p_lcb->conflict_lcid); + log::verbose("avct_l2c_connect_cfm_cback conflict_lcid:0x{:x}", p_lcb->conflict_lcid); if (p_lcb->conflict_lcid == lcid) { p_lcb->conflict_lcid = 0; } else { @@ -186,15 +182,13 @@ static void avct_on_l2cap_error(uint16_t lcid, uint16_t result) { avct_lcb_event(p_lcb, AVCT_LCB_LL_CLOSE_EVT, &avct_lcb_evt); } } else if (p_lcb->ch_state == AVCT_CH_CFG) { - log::verbose("ERROR avct_l2c_config_cfm_cback L2CA_DisconnectReq {}", - p_lcb->ch_state); + log::verbose("ERROR avct_l2c_config_cfm_cback L2CA_DisconnectReq {}", p_lcb->ch_state); /* store result value */ p_lcb->ch_result = result; /* Send L2CAP disconnect req */ if (!L2CA_DisconnectReq(lcid)) { - log::warn("Unable to send L2CAP disconnect request peer:{} cid:{}", - p_lcb->peer_addr, lcid); + log::warn("Unable to send L2CAP disconnect request peer:{} cid:{}", p_lcb->peer_addr, lcid); } } } @@ -216,9 +210,9 @@ void avct_l2c_connect_cfm_cback(uint16_t lcid, uint16_t result) { p_lcb = avct_lcb_by_lcid(lcid); if (p_lcb != NULL) { log::verbose( - "avct_l2c_connect_cfm_cback lcid:0x{:x} result: {} ch_state: {}, " - "conflict_lcid:0x{:x}", - lcid, result, p_lcb->ch_state, p_lcb->conflict_lcid); + "avct_l2c_connect_cfm_cback lcid:0x{:x} result: {} ch_state: {}, " + "conflict_lcid:0x{:x}", + lcid, result, p_lcb->ch_state, p_lcb->conflict_lcid); /* if in correct state */ if (p_lcb->ch_state == AVCT_CH_CONN) { /* if result successful */ @@ -232,15 +226,14 @@ void avct_l2c_connect_cfm_cback(uint16_t lcid, uint16_t result) { } } else if (p_lcb->conflict_lcid == lcid) { /* we must be in AVCT_CH_CFG state for the ch_lcid channel */ - log::verbose( - "avct_l2c_connect_cfm_cback ch_state: {}, conflict_lcid:0x{:x}", - p_lcb->ch_state, p_lcb->conflict_lcid); + log::verbose("avct_l2c_connect_cfm_cback ch_state: {}, conflict_lcid:0x{:x}", p_lcb->ch_state, + p_lcb->conflict_lcid); if (result == L2CAP_CONN_OK) { /* just in case the peer also accepts our connection - Send L2CAP * disconnect req */ if (!L2CA_DisconnectReq(lcid)) { - log::warn("Unable to send L2CAP disconnect request peer:{} cid:{}", - p_lcb->peer_addr, lcid); + log::warn("Unable to send L2CAP disconnect request peer:{} cid:{}", p_lcb->peer_addr, + lcid); } } p_lcb->conflict_lcid = 0; @@ -259,8 +252,7 @@ void avct_l2c_connect_cfm_cback(uint16_t lcid, uint16_t result) { * Returns void * ******************************************************************************/ -void avct_l2c_config_cfm_cback(uint16_t lcid, uint16_t initiator, - tL2CAP_CFG_INFO* p_cfg) { +void avct_l2c_config_cfm_cback(uint16_t lcid, uint16_t initiator, tL2CAP_CFG_INFO* p_cfg) { avct_l2c_config_ind_cback(lcid, p_cfg); tAVCT_LCB* p_lcb; @@ -268,8 +260,7 @@ void avct_l2c_config_cfm_cback(uint16_t lcid, uint16_t initiator, /* look up lcb for this channel */ p_lcb = avct_lcb_by_lcid(lcid); if (p_lcb != NULL) { - log::verbose("avct_l2c_config_cfm_cback: 0x{:x}, ch_state: {},", lcid, - p_lcb->ch_state); + log::verbose("avct_l2c_config_cfm_cback: 0x{:x}, ch_state: {},", lcid, p_lcb->ch_state); /* if in correct state */ if (p_lcb->ch_state == AVCT_CH_CFG) { p_lcb->ch_state = AVCT_CH_OPEN; @@ -295,8 +286,7 @@ void avct_l2c_config_ind_cback(uint16_t lcid, tL2CAP_CFG_INFO* p_cfg) { /* look up lcb for this channel */ p_lcb = avct_lcb_by_lcid(lcid); if (p_lcb != NULL) { - log::verbose("avct_l2c_config_ind_cback: 0x{:x}, ch_state: {}", lcid, - p_lcb->ch_state); + log::verbose("avct_l2c_config_ind_cback: 0x{:x}, ch_state: {}", lcid, p_lcb->ch_state); /* store the mtu in tbl */ if (p_cfg->mtu_present) { p_lcb->peer_mtu = p_cfg->mtu; @@ -323,8 +313,7 @@ void avct_l2c_disconnect_ind_cback(uint16_t lcid, bool ack_needed) { /* look up lcb for this channel */ p_lcb = avct_lcb_by_lcid(lcid); if (p_lcb != NULL) { - log::verbose("avct_l2c_disconnect_ind_cback: 0x{:x}, ch_state: {}", lcid, - p_lcb->ch_state); + log::verbose("avct_l2c_disconnect_ind_cback: 0x{:x}, ch_state: {}", lcid, p_lcb->ch_state); tAVCT_LCB_EVT avct_lcb_evt; avct_lcb_evt.result = result; avct_lcb_event(p_lcb, AVCT_LCB_LL_CLOSE_EVT, &avct_lcb_evt); @@ -343,8 +332,8 @@ void avct_l2c_disconnect(uint16_t lcid, uint16_t result) { /* look up lcb for this channel */ p_lcb = avct_lcb_by_lcid(lcid); if (p_lcb != NULL) { - log::verbose("avct_l2c_disconnect_cfm_cback: 0x{:x}, ch_state: {}, res: {}", - lcid, p_lcb->ch_state, result); + log::verbose("avct_l2c_disconnect_cfm_cback: 0x{:x}, ch_state: {}, res: {}", lcid, + p_lcb->ch_state, result); /* result value may be previously stored */ res = (p_lcb->ch_result != 0) ? p_lcb->ch_result : result; p_lcb->ch_result = 0; diff --git a/system/stack/avct/avct_l2c_br.cc b/system/stack/avct/avct_l2c_br.cc index 6a74031f7c6..a4e666e9026 100644 --- a/system/stack/avct/avct_l2c_br.cc +++ b/system/stack/avct/avct_l2c_br.cc @@ -41,11 +41,10 @@ using namespace bluetooth; /* callback function declarations */ -void avct_l2c_br_connect_ind_cback(const RawAddress& bd_addr, uint16_t lcid, - uint16_t psm, uint8_t id); +void avct_l2c_br_connect_ind_cback(const RawAddress& bd_addr, uint16_t lcid, uint16_t psm, + uint8_t id); void avct_l2c_br_connect_cfm_cback(uint16_t lcid, uint16_t result); -void avct_l2c_br_config_cfm_cback(uint16_t lcid, uint16_t result, - tL2CAP_CFG_INFO* p_cfg); +void avct_l2c_br_config_cfm_cback(uint16_t lcid, uint16_t result, tL2CAP_CFG_INFO* p_cfg); void avct_l2c_br_config_ind_cback(uint16_t lcid, tL2CAP_CFG_INFO* p_cfg); void avct_l2c_br_disconnect_ind_cback(uint16_t lcid, bool ack_needed); void avct_l2c_br_congestion_ind_cback(uint16_t lcid, bool is_congested); @@ -87,8 +86,7 @@ static bool avct_l2c_br_is_passive(tAVCT_BCB* p_bcb) { for (i = 0; i < AVCT_NUM_CONN; i++, p_ccb++) { if (p_ccb->allocated && (p_ccb->p_lcb == p_lcb)) { - log::verbose("Is bcb associated ccb control passive :0x{:x}", - p_ccb->cc.control); + log::verbose("Is bcb associated ccb control passive :0x{:x}", p_ccb->cc.control); if (p_ccb->cc.control & AVCT_PASSIVE) { is_passive = true; break; @@ -108,8 +106,8 @@ static bool avct_l2c_br_is_passive(tAVCT_BCB* p_bcb) { * Returns void * ******************************************************************************/ -void avct_l2c_br_connect_ind_cback(const RawAddress& bd_addr, uint16_t lcid, - uint16_t /* psm */, uint8_t id) { +void avct_l2c_br_connect_ind_cback(const RawAddress& bd_addr, uint16_t lcid, uint16_t /* psm */, + uint8_t id) { tAVCT_LCB* p_lcb; uint16_t result = L2CAP_CONN_NO_RESOURCES; tAVCT_BCB* p_bcb; @@ -165,7 +163,9 @@ void avct_l2c_br_connect_ind_cback(const RawAddress& bd_addr, uint16_t lcid, void avct_br_on_l2cap_error(uint16_t lcid, uint16_t result) { tAVCT_BCB* p_bcb = avct_bcb_by_lcid(lcid); - if (p_bcb == nullptr) return; + if (p_bcb == nullptr) { + return; + } if (p_bcb->ch_state == AVCT_CH_CONN && p_bcb->conflict_lcid == lcid) { log::verbose("Reset conflict_lcid:0x{:x}", p_bcb->conflict_lcid); @@ -216,8 +216,7 @@ void avct_l2c_br_connect_cfm_cback(uint16_t lcid, uint16_t result) { * disconnect req */ log::verbose("Disconnect conflict_lcid:0x{:x}", p_bcb->conflict_lcid); if (!L2CA_DisconnectReq(lcid)) { - log::warn("Unable to send L2CAP disconnect request peer:{} cid:{}", - p_bcb->peer_addr, lcid); + log::warn("Unable to send L2CAP disconnect request peer:{} cid:{}", p_bcb->peer_addr, lcid); } } p_bcb->conflict_lcid = 0; @@ -234,15 +233,16 @@ void avct_l2c_br_connect_cfm_cback(uint16_t lcid, uint16_t result) { * Returns void * ******************************************************************************/ -void avct_l2c_br_config_cfm_cback(uint16_t lcid, uint16_t initiator, - tL2CAP_CFG_INFO* p_cfg) { +void avct_l2c_br_config_cfm_cback(uint16_t lcid, uint16_t initiator, tL2CAP_CFG_INFO* p_cfg) { avct_l2c_br_config_ind_cback(lcid, p_cfg); tAVCT_BCB* p_lcb; /* look up lcb for this channel */ p_lcb = avct_bcb_by_lcid(lcid); - if ((p_lcb == NULL) || (p_lcb->ch_state != AVCT_CH_CFG)) return; + if ((p_lcb == NULL) || (p_lcb->ch_state != AVCT_CH_CFG)) { + return; + } p_lcb->ch_state = AVCT_CH_OPEN; avct_bcb_event(p_lcb, AVCT_LCB_LL_OPEN_EVT, NULL); @@ -264,7 +264,9 @@ void avct_l2c_br_config_ind_cback(uint16_t lcid, tL2CAP_CFG_INFO* p_cfg) { /* look up lcb for this channel */ p_lcb = avct_bcb_by_lcid(lcid); - if (p_lcb == NULL) return; + if (p_lcb == NULL) { + return; + } /* store the mtu in tbl */ p_lcb->peer_mtu = L2CAP_DEFAULT_MTU; @@ -295,7 +297,9 @@ void avct_l2c_br_disconnect_ind_cback(uint16_t lcid, bool ack_needed) { /* look up lcb for this channel */ p_lcb = avct_bcb_by_lcid(lcid); - if (p_lcb == NULL) return; + if (p_lcb == NULL) { + return; + } tAVCT_LCB_EVT avct_lcb_evt; avct_lcb_evt.result = result; @@ -312,7 +316,9 @@ void avct_l2c_br_disconnect(uint16_t lcid, uint16_t result) { /* look up lcb for this channel */ p_lcb = avct_bcb_by_lcid(lcid); - if (p_lcb == NULL) return; + if (p_lcb == NULL) { + return; + } /* result value may be previously stored */ res = (p_lcb->ch_result != 0) ? p_lcb->ch_result : result; @@ -338,7 +344,9 @@ void avct_l2c_br_congestion_ind_cback(uint16_t lcid, bool is_congested) { /* look up lcb for this channel */ p_lcb = avct_bcb_by_lcid(lcid); - if (p_lcb == NULL) return; + if (p_lcb == NULL) { + return; + } tAVCT_LCB_EVT avct_lcb_evt; avct_lcb_evt.cong = is_congested; diff --git a/system/stack/avct/avct_lcb.cc b/system/stack/avct/avct_lcb.cc index c75cf2c26aa..c8e12c4f08f 100644 --- a/system/stack/avct/avct_lcb.cc +++ b/system/stack/avct/avct_lcb.cc @@ -44,21 +44,16 @@ using namespace bluetooth; ****************************************************************************/ /* verbose state strings for trace */ -const char* const avct_lcb_st_str[] = {"LCB_IDLE_ST", "LCB_OPENING_ST", - "LCB_OPEN_ST", "LCB_CLOSING_ST"}; +const char* const avct_lcb_st_str[] = {"LCB_IDLE_ST", "LCB_OPENING_ST", "LCB_OPEN_ST", + "LCB_CLOSING_ST"}; /* verbose event strings for trace */ -const char* const avct_lcb_evt_str[] = { - "UL_BIND_EVT", "UL_UNBIND_EVT", "UL_MSG_EVT", "INT_CLOSE_EVT", - "LL_OPEN_EVT", "LL_CLOSE_EVT", "LL_MSG_EVT", "LL_CONG_EVT"}; +const char* const avct_lcb_evt_str[] = {"UL_BIND_EVT", "UL_UNBIND_EVT", "UL_MSG_EVT", + "INT_CLOSE_EVT", "LL_OPEN_EVT", "LL_CLOSE_EVT", + "LL_MSG_EVT", "LL_CONG_EVT"}; /* lcb state machine states */ -enum { - AVCT_LCB_IDLE_ST, - AVCT_LCB_OPENING_ST, - AVCT_LCB_OPEN_ST, - AVCT_LCB_CLOSING_ST -}; +enum { AVCT_LCB_IDLE_ST, AVCT_LCB_OPENING_ST, AVCT_LCB_OPEN_ST, AVCT_LCB_CLOSING_ST }; /* state machine action enumeration list */ enum { @@ -88,12 +83,10 @@ typedef void (*tAVCT_LCB_ACTION)(tAVCT_LCB* p_ccb, tAVCT_LCB_EVT* p_data); /* action function list */ const tAVCT_LCB_ACTION avct_lcb_action[] = { - avct_lcb_chnl_open, avct_lcb_chnl_disc, avct_lcb_send_msg, - avct_lcb_open_ind, avct_lcb_open_fail, avct_lcb_close_ind, - avct_lcb_close_cfm, avct_lcb_msg_ind, avct_lcb_cong_ind, - avct_lcb_bind_conn, avct_lcb_bind_fail, avct_lcb_unbind_disc, - avct_lcb_chk_disc, avct_lcb_discard_msg, avct_lcb_dealloc, - avct_lcb_free_msg_ind}; + avct_lcb_chnl_open, avct_lcb_chnl_disc, avct_lcb_send_msg, avct_lcb_open_ind, + avct_lcb_open_fail, avct_lcb_close_ind, avct_lcb_close_cfm, avct_lcb_msg_ind, + avct_lcb_cong_ind, avct_lcb_bind_conn, avct_lcb_bind_fail, avct_lcb_unbind_disc, + avct_lcb_chk_disc, avct_lcb_discard_msg, avct_lcb_dealloc, avct_lcb_free_msg_ind}; /* state table information */ #define AVCT_LCB_ACTIONS 2 /* number of actions */ @@ -102,60 +95,58 @@ const tAVCT_LCB_ACTION avct_lcb_action[] = { /* state table for idle state */ const uint8_t avct_lcb_st_idle[][AVCT_LCB_NUM_COLS] = { - /* Event Action 1 Action 2 Next state */ - /* UL_BIND */ {AVCT_LCB_CHNL_OPEN, AVCT_LCB_IGNORE, AVCT_LCB_OPENING_ST}, - /* UL_UNBIND */ {AVCT_LCB_UNBIND_DISC, AVCT_LCB_IGNORE, AVCT_LCB_IDLE_ST}, - /* UL_MSG */ {AVCT_LCB_DISCARD_MSG, AVCT_LCB_IGNORE, AVCT_LCB_IDLE_ST}, - /* INT_CLOSE */ {AVCT_LCB_IGNORE, AVCT_LCB_IGNORE, AVCT_LCB_IDLE_ST}, - /* LL_OPEN */ {AVCT_LCB_OPEN_IND, AVCT_LCB_IGNORE, AVCT_LCB_OPEN_ST}, - /* LL_CLOSE */ {AVCT_LCB_CLOSE_IND, AVCT_LCB_DEALLOC, AVCT_LCB_IDLE_ST}, - /* LL_MSG */ {AVCT_LCB_FREE_MSG_IND, AVCT_LCB_IGNORE, AVCT_LCB_IDLE_ST}, - /* LL_CONG */ {AVCT_LCB_IGNORE, AVCT_LCB_IGNORE, AVCT_LCB_IDLE_ST}}; + /* Event Action 1 Action 2 Next state */ + /* UL_BIND */ {AVCT_LCB_CHNL_OPEN, AVCT_LCB_IGNORE, AVCT_LCB_OPENING_ST}, + /* UL_UNBIND */ {AVCT_LCB_UNBIND_DISC, AVCT_LCB_IGNORE, AVCT_LCB_IDLE_ST}, + /* UL_MSG */ {AVCT_LCB_DISCARD_MSG, AVCT_LCB_IGNORE, AVCT_LCB_IDLE_ST}, + /* INT_CLOSE */ {AVCT_LCB_IGNORE, AVCT_LCB_IGNORE, AVCT_LCB_IDLE_ST}, + /* LL_OPEN */ {AVCT_LCB_OPEN_IND, AVCT_LCB_IGNORE, AVCT_LCB_OPEN_ST}, + /* LL_CLOSE */ {AVCT_LCB_CLOSE_IND, AVCT_LCB_DEALLOC, AVCT_LCB_IDLE_ST}, + /* LL_MSG */ {AVCT_LCB_FREE_MSG_IND, AVCT_LCB_IGNORE, AVCT_LCB_IDLE_ST}, + /* LL_CONG */ {AVCT_LCB_IGNORE, AVCT_LCB_IGNORE, AVCT_LCB_IDLE_ST}}; /* state table for opening state */ const uint8_t avct_lcb_st_opening[][AVCT_LCB_NUM_COLS] = { - /* Event Action 1 Action 2 Next state */ - /* UL_BIND */ {AVCT_LCB_IGNORE, AVCT_LCB_IGNORE, AVCT_LCB_OPENING_ST}, - /* UL_UNBIND */ {AVCT_LCB_UNBIND_DISC, AVCT_LCB_IGNORE, - AVCT_LCB_OPENING_ST}, - /* UL_MSG */ {AVCT_LCB_DISCARD_MSG, AVCT_LCB_IGNORE, AVCT_LCB_OPENING_ST}, - /* INT_CLOSE */ {AVCT_LCB_CHNL_DISC, AVCT_LCB_IGNORE, AVCT_LCB_CLOSING_ST}, - /* LL_OPEN */ {AVCT_LCB_OPEN_IND, AVCT_LCB_IGNORE, AVCT_LCB_OPEN_ST}, - /* LL_CLOSE */ {AVCT_LCB_OPEN_FAIL, AVCT_LCB_DEALLOC, AVCT_LCB_IDLE_ST}, - /* LL_MSG */ {AVCT_LCB_FREE_MSG_IND, AVCT_LCB_IGNORE, AVCT_LCB_OPENING_ST}, - /* LL_CONG */ {AVCT_LCB_CONG_IND, AVCT_LCB_IGNORE, AVCT_LCB_OPENING_ST}}; + /* Event Action 1 Action 2 Next state */ + /* UL_BIND */ {AVCT_LCB_IGNORE, AVCT_LCB_IGNORE, AVCT_LCB_OPENING_ST}, + /* UL_UNBIND */ {AVCT_LCB_UNBIND_DISC, AVCT_LCB_IGNORE, AVCT_LCB_OPENING_ST}, + /* UL_MSG */ {AVCT_LCB_DISCARD_MSG, AVCT_LCB_IGNORE, AVCT_LCB_OPENING_ST}, + /* INT_CLOSE */ {AVCT_LCB_CHNL_DISC, AVCT_LCB_IGNORE, AVCT_LCB_CLOSING_ST}, + /* LL_OPEN */ {AVCT_LCB_OPEN_IND, AVCT_LCB_IGNORE, AVCT_LCB_OPEN_ST}, + /* LL_CLOSE */ {AVCT_LCB_OPEN_FAIL, AVCT_LCB_DEALLOC, AVCT_LCB_IDLE_ST}, + /* LL_MSG */ {AVCT_LCB_FREE_MSG_IND, AVCT_LCB_IGNORE, AVCT_LCB_OPENING_ST}, + /* LL_CONG */ {AVCT_LCB_CONG_IND, AVCT_LCB_IGNORE, AVCT_LCB_OPENING_ST}}; /* state table for open state */ const uint8_t avct_lcb_st_open[][AVCT_LCB_NUM_COLS] = { - /* Event Action 1 Action 2 Next state */ - /* UL_BIND */ {AVCT_LCB_BIND_CONN, AVCT_LCB_IGNORE, AVCT_LCB_OPEN_ST}, - /* UL_UNBIND */ {AVCT_LCB_CHK_DISC, AVCT_LCB_IGNORE, AVCT_LCB_OPEN_ST}, - /* UL_MSG */ {AVCT_LCB_SEND_MSG, AVCT_LCB_IGNORE, AVCT_LCB_OPEN_ST}, - /* INT_CLOSE */ {AVCT_LCB_CHNL_DISC, AVCT_LCB_IGNORE, AVCT_LCB_CLOSING_ST}, - /* LL_OPEN */ {AVCT_LCB_IGNORE, AVCT_LCB_IGNORE, AVCT_LCB_OPEN_ST}, - /* LL_CLOSE */ {AVCT_LCB_CLOSE_IND, AVCT_LCB_DEALLOC, AVCT_LCB_IDLE_ST}, - /* LL_MSG */ {AVCT_LCB_MSG_IND, AVCT_LCB_IGNORE, AVCT_LCB_OPEN_ST}, - /* LL_CONG */ {AVCT_LCB_CONG_IND, AVCT_LCB_IGNORE, AVCT_LCB_OPEN_ST}}; + /* Event Action 1 Action 2 Next state */ + /* UL_BIND */ {AVCT_LCB_BIND_CONN, AVCT_LCB_IGNORE, AVCT_LCB_OPEN_ST}, + /* UL_UNBIND */ {AVCT_LCB_CHK_DISC, AVCT_LCB_IGNORE, AVCT_LCB_OPEN_ST}, + /* UL_MSG */ {AVCT_LCB_SEND_MSG, AVCT_LCB_IGNORE, AVCT_LCB_OPEN_ST}, + /* INT_CLOSE */ {AVCT_LCB_CHNL_DISC, AVCT_LCB_IGNORE, AVCT_LCB_CLOSING_ST}, + /* LL_OPEN */ {AVCT_LCB_IGNORE, AVCT_LCB_IGNORE, AVCT_LCB_OPEN_ST}, + /* LL_CLOSE */ {AVCT_LCB_CLOSE_IND, AVCT_LCB_DEALLOC, AVCT_LCB_IDLE_ST}, + /* LL_MSG */ {AVCT_LCB_MSG_IND, AVCT_LCB_IGNORE, AVCT_LCB_OPEN_ST}, + /* LL_CONG */ {AVCT_LCB_CONG_IND, AVCT_LCB_IGNORE, AVCT_LCB_OPEN_ST}}; /* state table for closing state */ const uint8_t avct_lcb_st_closing[][AVCT_LCB_NUM_COLS] = { - /* Event Action 1 Action 2 Next state */ - /* UL_BIND */ {AVCT_LCB_BIND_FAIL, AVCT_LCB_IGNORE, AVCT_LCB_CLOSING_ST}, - /* UL_UNBIND */ {AVCT_LCB_IGNORE, AVCT_LCB_IGNORE, AVCT_LCB_CLOSING_ST}, - /* UL_MSG */ {AVCT_LCB_DISCARD_MSG, AVCT_LCB_IGNORE, AVCT_LCB_CLOSING_ST}, - /* INT_CLOSE */ {AVCT_LCB_IGNORE, AVCT_LCB_IGNORE, AVCT_LCB_CLOSING_ST}, - /* LL_OPEN */ {AVCT_LCB_IGNORE, AVCT_LCB_IGNORE, AVCT_LCB_CLOSING_ST}, - /* LL_CLOSE */ {AVCT_LCB_CLOSE_CFM, AVCT_LCB_DEALLOC, AVCT_LCB_IDLE_ST}, - /* LL_MSG */ {AVCT_LCB_FREE_MSG_IND, AVCT_LCB_IGNORE, AVCT_LCB_CLOSING_ST}, - /* LL_CONG */ {AVCT_LCB_IGNORE, AVCT_LCB_IGNORE, AVCT_LCB_CLOSING_ST}}; + /* Event Action 1 Action 2 Next state */ + /* UL_BIND */ {AVCT_LCB_BIND_FAIL, AVCT_LCB_IGNORE, AVCT_LCB_CLOSING_ST}, + /* UL_UNBIND */ {AVCT_LCB_IGNORE, AVCT_LCB_IGNORE, AVCT_LCB_CLOSING_ST}, + /* UL_MSG */ {AVCT_LCB_DISCARD_MSG, AVCT_LCB_IGNORE, AVCT_LCB_CLOSING_ST}, + /* INT_CLOSE */ {AVCT_LCB_IGNORE, AVCT_LCB_IGNORE, AVCT_LCB_CLOSING_ST}, + /* LL_OPEN */ {AVCT_LCB_IGNORE, AVCT_LCB_IGNORE, AVCT_LCB_CLOSING_ST}, + /* LL_CLOSE */ {AVCT_LCB_CLOSE_CFM, AVCT_LCB_DEALLOC, AVCT_LCB_IDLE_ST}, + /* LL_MSG */ {AVCT_LCB_FREE_MSG_IND, AVCT_LCB_IGNORE, AVCT_LCB_CLOSING_ST}, + /* LL_CONG */ {AVCT_LCB_IGNORE, AVCT_LCB_IGNORE, AVCT_LCB_CLOSING_ST}}; /* type for state table */ typedef const uint8_t (*tAVCT_LCB_ST_TBL)[AVCT_LCB_NUM_COLS]; /* state table */ -const tAVCT_LCB_ST_TBL avct_lcb_st_tbl[] = { - avct_lcb_st_idle, avct_lcb_st_opening, avct_lcb_st_open, - avct_lcb_st_closing}; +const tAVCT_LCB_ST_TBL avct_lcb_st_tbl[] = {avct_lcb_st_idle, avct_lcb_st_opening, avct_lcb_st_open, + avct_lcb_st_closing}; /******************************************************************************* * @@ -172,15 +163,15 @@ void avct_lcb_event(tAVCT_LCB* p_lcb, uint8_t event, tAVCT_LCB_EVT* p_data) { uint8_t action; int i; - log::verbose("LCB lcb={} event={} state={}", p_lcb->allocated, - avct_lcb_evt_str[event], avct_lcb_st_str[p_lcb->state]); + log::verbose("LCB lcb={} event={} state={}", p_lcb->allocated, avct_lcb_evt_str[event], + avct_lcb_st_str[p_lcb->state]); /* look up the state table for the current state */ state_table = avct_lcb_st_tbl[p_lcb->state]; - if (p_lcb->state == AVCT_LCB_IDLE_ST && event == AVCT_LCB_LL_OPEN_EVT) - DEVICE_IOT_CONFIG_ADDR_INT_ADD_ONE(p_lcb->peer_addr, - IOT_CONF_KEY_AVRCP_CONN_COUNT); + if (p_lcb->state == AVCT_LCB_IDLE_ST && event == AVCT_LCB_LL_OPEN_EVT) { + DEVICE_IOT_CONFIG_ADDR_INT_ADD_ONE(p_lcb->peer_addr, IOT_CONF_KEY_AVRCP_CONN_COUNT); + } /* set next state */ p_lcb->state = state_table[event][AVCT_LCB_NEXT_STATE]; @@ -211,8 +202,8 @@ void avct_bcb_event(tAVCT_BCB* p_bcb, uint8_t event, tAVCT_LCB_EVT* p_data) { uint8_t action; int i; - log::verbose("BCB lcb={} event={} state={}", p_bcb->allocated, - avct_lcb_evt_str[event], avct_lcb_st_str[p_bcb->state]); + log::verbose("BCB lcb={} event={} state={}", p_bcb->allocated, avct_lcb_evt_str[event], + avct_lcb_st_str[p_bcb->state]); /* look up the state table for the current state */ state_table = avct_lcb_st_tbl[p_bcb->state]; @@ -340,8 +331,7 @@ tAVCT_LCB* avct_lcb_by_lcid(uint16_t lcid) { int i; for (i = 0; i < AVCT_NUM_LINKS; i++, p_lcb++) { - if (p_lcb->allocated && - ((p_lcb->ch_lcid == lcid) || (p_lcb->conflict_lcid == lcid))) { + if (p_lcb->allocated && ((p_lcb->ch_lcid == lcid) || (p_lcb->conflict_lcid == lcid))) { break; } } @@ -393,9 +383,8 @@ bool avct_lcb_last_ccb(tAVCT_LCB* p_lcb, tAVCT_CCB* p_ccb_last) { log::warn("avct_lcb_last_ccb"); for (i = 0; i < AVCT_NUM_CONN; i++, p_ccb++) { - log::warn("{:x}: aloc:{}, lcb:0x{}/0x{}, ccb:0x{}/0x{}", i, - p_ccb->allocated, fmt::ptr(p_ccb->p_lcb), fmt::ptr(p_lcb), - fmt::ptr(p_ccb), fmt::ptr(p_ccb_last)); + log::warn("{:x}: aloc:{}, lcb:0x{}/0x{}, ccb:0x{}/0x{}", i, p_ccb->allocated, + fmt::ptr(p_ccb->p_lcb), fmt::ptr(p_lcb), fmt::ptr(p_ccb), fmt::ptr(p_ccb_last)); if (p_ccb->allocated && (p_ccb->p_lcb == p_lcb) && (p_ccb != p_ccb_last)) { return false; } diff --git a/system/stack/avct/avct_lcb_act.cc b/system/stack/avct/avct_lcb_act.cc index 1f38cfeb9b3..9705fd855e2 100644 --- a/system/stack/avct/avct_lcb_act.cc +++ b/system/stack/avct/avct_lcb_act.cc @@ -39,8 +39,7 @@ using namespace bluetooth; /* packet header length lookup table */ -const uint8_t avct_lcb_pkt_type_len[] = {AVCT_HDR_LEN_SINGLE, - AVCT_HDR_LEN_START, AVCT_HDR_LEN_CONT, +const uint8_t avct_lcb_pkt_type_len[] = {AVCT_HDR_LEN_SINGLE, AVCT_HDR_LEN_START, AVCT_HDR_LEN_CONT, AVCT_HDR_LEN_END}; /******************************************************************************* @@ -79,7 +78,9 @@ static BT_HDR* avct_lcb_msg_asmbl(tAVCT_LCB* p_lcb, BT_HDR* p_buf) { /* single packet */ else if (pkt_type == AVCT_PKT_TYPE_SINGLE) { /* if reassembly in progress drop message and process new single */ - if (p_lcb->p_rx_msg != NULL) log::warn("Got single during reassembly"); + if (p_lcb->p_rx_msg != NULL) { + log::warn("Got single during reassembly"); + } osi_free_and_reset((void**)&p_lcb->p_rx_msg); @@ -88,7 +89,9 @@ static BT_HDR* avct_lcb_msg_asmbl(tAVCT_LCB* p_lcb, BT_HDR* p_buf) { /* start packet */ else if (pkt_type == AVCT_PKT_TYPE_START) { /* if reassembly in progress drop message and process new start */ - if (p_lcb->p_rx_msg != NULL) log::warn("Got start during reassembly"); + if (p_lcb->p_rx_msg != NULL) { + log::warn("Got start during reassembly"); + } osi_free_and_reset((void**)&p_lcb->p_rx_msg); @@ -184,8 +187,7 @@ void avct_lcb_chnl_open(tAVCT_LCB* p_lcb, tAVCT_LCB_EVT* /* p_data */) { uint16_t result = AVCT_RESULT_FAIL; p_lcb->ch_state = AVCT_CH_CONN; - p_lcb->ch_lcid = L2CA_ConnectReqWithSecurity(AVCT_PSM, p_lcb->peer_addr, - BTA_SEC_AUTHENTICATE); + p_lcb->ch_lcid = L2CA_ConnectReqWithSecurity(AVCT_PSM, p_lcb->peer_addr, BTA_SEC_AUTHENTICATE); if (p_lcb->ch_lcid == 0) { /* if connect req failed, send ourselves close event */ tAVCT_LCB_EVT avct_lcb_evt; @@ -230,8 +232,7 @@ void avct_lcb_open_ind(tAVCT_LCB* p_lcb, tAVCT_LCB_EVT* p_data) { bool is_originater = false; for (i = 0; i < AVCT_NUM_CONN; i++, p_ccb++) { - if (p_ccb->allocated && (p_ccb->p_lcb == p_lcb) && - p_ccb->cc.role == AVCT_INT) { + if (p_ccb->allocated && (p_ccb->p_lcb == p_lcb) && p_ccb->cc.role == AVCT_INT) { log::verbose("find int handle {}", i); is_originater = true; } @@ -242,28 +243,25 @@ void avct_lcb_open_ind(tAVCT_LCB* p_lcb, tAVCT_LCB_EVT* p_data) { /* if ccb allocated and */ /** M: to avoid avctp collision, make sure the collision can be checked @{ */ - log::verbose("{} ccb to lcb, alloc {}, lcb {}, role {}, pid 0x{:x}", i, - p_ccb->allocated, fmt::ptr(p_ccb->p_lcb), p_ccb->cc.role, - p_ccb->cc.pid); + log::verbose("{} ccb to lcb, alloc {}, lcb {}, role {}, pid 0x{:x}", i, p_ccb->allocated, + fmt::ptr(p_ccb->p_lcb), p_ccb->cc.role, p_ccb->cc.pid); if (p_ccb->allocated && (p_ccb->p_lcb == p_lcb)) { /* if bound to this lcb send connect confirm event */ if (p_ccb->cc.role == AVCT_INT) { /** @} */ bind = true; if (!L2CA_SetTxPriority(p_lcb->ch_lcid, L2CAP_CHNL_PRIORITY_HIGH)) { - log::warn( - "Unable to set L2CAP transmit high priority peer:{} cid:{}", - p_ccb->p_lcb->peer_addr, p_lcb->ch_lcid); + log::warn("Unable to set L2CAP transmit high priority peer:{} cid:{}", + p_ccb->p_lcb->peer_addr, p_lcb->ch_lcid); } - p_ccb->cc.p_ctrl_cback(avct_ccb_to_idx(p_ccb), AVCT_CONNECT_CFM_EVT, - 0, &p_lcb->peer_addr); + p_ccb->cc.p_ctrl_cback(avct_ccb_to_idx(p_ccb), AVCT_CONNECT_CFM_EVT, 0, + &p_lcb->peer_addr); } /* if unbound acceptor and lcb doesn't already have a ccb for this PID */ /** M: to avoid avctp collision, make sure the collision can be checked @{ */ - else if ((p_ccb->cc.role == AVCT_ACP) && - avct_lcb_has_pid(p_lcb, p_ccb->cc.pid)) { + else if ((p_ccb->cc.role == AVCT_ACP) && avct_lcb_has_pid(p_lcb, p_ccb->cc.pid)) { /* bind ccb to lcb and send connect ind event */ if (is_originater) { log::error("int exist, unbind acp handle:{}", i); @@ -272,12 +270,11 @@ void avct_lcb_open_ind(tAVCT_LCB* p_lcb, tAVCT_LCB_EVT* p_data) { bind = true; p_ccb->p_lcb = p_lcb; if (!L2CA_SetTxPriority(p_lcb->ch_lcid, L2CAP_CHNL_PRIORITY_HIGH)) { - log::warn( - "Unable to set L2CAP transmit high priority peer:{} cid:{}", - p_ccb->p_lcb->peer_addr, p_lcb->ch_lcid); + log::warn("Unable to set L2CAP transmit high priority peer:{} cid:{}", + p_ccb->p_lcb->peer_addr, p_lcb->ch_lcid); } - p_ccb->cc.p_ctrl_cback(avct_ccb_to_idx(p_ccb), AVCT_CONNECT_IND_EVT, - 0, &p_lcb->peer_addr); + p_ccb->cc.p_ctrl_cback(avct_ccb_to_idx(p_ccb), AVCT_CONNECT_IND_EVT, 0, + &p_lcb->peer_addr); } } } @@ -290,12 +287,11 @@ void avct_lcb_open_ind(tAVCT_LCB* p_lcb, tAVCT_LCB_EVT* p_data) { if (p_ccb->p_lcb == p_lcb) { bind = true; if (!L2CA_SetTxPriority(p_lcb->ch_lcid, L2CAP_CHNL_PRIORITY_HIGH)) { - log::warn( - "Unable to set L2CAP transmit high priority peer:{} cid:{}", - p_ccb->p_lcb->peer_addr, p_lcb->ch_lcid); + log::warn("Unable to set L2CAP transmit high priority peer:{} cid:{}", + p_ccb->p_lcb->peer_addr, p_lcb->ch_lcid); } - p_ccb->cc.p_ctrl_cback(avct_ccb_to_idx(p_ccb), AVCT_CONNECT_CFM_EVT, - 0, &p_lcb->peer_addr); + p_ccb->cc.p_ctrl_cback(avct_ccb_to_idx(p_ccb), AVCT_CONNECT_CFM_EVT, 0, + &p_lcb->peer_addr); } /* if unbound acceptor and lcb doesn't already have a ccb for this PID */ @@ -305,12 +301,11 @@ void avct_lcb_open_ind(tAVCT_LCB* p_lcb, tAVCT_LCB_EVT* p_data) { bind = true; p_ccb->p_lcb = p_lcb; if (!L2CA_SetTxPriority(p_lcb->ch_lcid, L2CAP_CHNL_PRIORITY_HIGH)) { - log::warn( - "Unable to set L2CAP transmit high priority peer:{} cid:{}", - p_ccb->p_lcb->peer_addr, p_lcb->ch_lcid); + log::warn("Unable to set L2CAP transmit high priority peer:{} cid:{}", + p_ccb->p_lcb->peer_addr, p_lcb->ch_lcid); } - p_ccb->cc.p_ctrl_cback(avct_ccb_to_idx(p_ccb), AVCT_CONNECT_IND_EVT, - 0, &p_lcb->peer_addr); + p_ccb->cc.p_ctrl_cback(avct_ccb_to_idx(p_ccb), AVCT_CONNECT_IND_EVT, 0, + &p_lcb->peer_addr); } } } @@ -318,8 +313,7 @@ void avct_lcb_open_ind(tAVCT_LCB* p_lcb, tAVCT_LCB_EVT* p_data) { /* if no ccbs bound to this lcb, disconnect */ if (!bind) { - DEVICE_IOT_CONFIG_ADDR_INT_ADD_ONE(p_lcb->peer_addr, - IOT_CONF_KEY_AVRCP_CONN_FAIL_COUNT); + DEVICE_IOT_CONFIG_ADDR_INT_ADD_ONE(p_lcb->peer_addr, IOT_CONF_KEY_AVRCP_CONN_FAIL_COUNT); avct_lcb_event(p_lcb, AVCT_LCB_INT_CLOSE_EVT, p_data); } } @@ -341,10 +335,8 @@ void avct_lcb_open_fail(tAVCT_LCB* p_lcb, tAVCT_LCB_EVT* p_data) { for (i = 0; i < AVCT_NUM_CONN; i++, p_ccb++) { if (p_ccb->allocated && (p_ccb->p_lcb == p_lcb)) { - avct_ccb_dealloc(p_ccb, AVCT_CONNECT_CFM_EVT, p_data->result, - &p_lcb->peer_addr); - DEVICE_IOT_CONFIG_ADDR_INT_ADD_ONE(p_lcb->peer_addr, - IOT_CONF_KEY_AVRCP_CONN_FAIL_COUNT); + avct_ccb_dealloc(p_ccb, AVCT_CONNECT_CFM_EVT, p_data->result, &p_lcb->peer_addr); + DEVICE_IOT_CONFIG_ADDR_INT_ADD_ONE(p_lcb->peer_addr, IOT_CONF_KEY_AVRCP_CONN_FAIL_COUNT); } } } @@ -370,8 +362,7 @@ void avct_lcb_close_ind(tAVCT_LCB* p_lcb, tAVCT_LCB_EVT* /* p_data */) { avct_ccb_dealloc(p_ccb, AVCT_DISCONNECT_IND_EVT, 0, &p_lcb->peer_addr); } else { p_ccb->p_lcb = NULL; - (*p_ccb->cc.p_ctrl_cback)(avct_ccb_to_idx(p_ccb), - AVCT_DISCONNECT_IND_EVT, 0, + (*p_ccb->cc.p_ctrl_cback)(avct_ccb_to_idx(p_ccb), AVCT_DISCONNECT_IND_EVT, 0, &p_lcb->peer_addr); } } @@ -408,8 +399,7 @@ void avct_lcb_close_cfm(tAVCT_LCB* p_lcb, tAVCT_LCB_EVT* p_data) { avct_ccb_dealloc(p_ccb, event, p_data->result, &p_lcb->peer_addr); } else { p_ccb->p_lcb = NULL; - (*p_ccb->cc.p_ctrl_cback)(avct_ccb_to_idx(p_ccb), event, p_data->result, - &p_lcb->peer_addr); + (*p_ccb->cc.p_ctrl_cback)(avct_ccb_to_idx(p_ccb), event, p_data->result, &p_lcb->peer_addr); } } } @@ -427,8 +417,8 @@ void avct_lcb_close_cfm(tAVCT_LCB* p_lcb, tAVCT_LCB_EVT* p_data) { ******************************************************************************/ void avct_lcb_bind_conn(tAVCT_LCB* p_lcb, tAVCT_LCB_EVT* p_data) { p_data->p_ccb->p_lcb = p_lcb; - (*p_data->p_ccb->cc.p_ctrl_cback)(avct_ccb_to_idx(p_data->p_ccb), - AVCT_CONNECT_CFM_EVT, 0, &p_lcb->peer_addr); + (*p_data->p_ccb->cc.p_ctrl_cback)(avct_ccb_to_idx(p_data->p_ccb), AVCT_CONNECT_CFM_EVT, 0, + &p_lcb->peer_addr); } /******************************************************************************* @@ -481,8 +471,7 @@ void avct_lcb_chnl_disc(tAVCT_LCB* p_lcb, tAVCT_LCB_EVT* /* p_data */) { ******************************************************************************/ void avct_lcb_bind_fail(tAVCT_LCB* p_lcb, tAVCT_LCB_EVT* p_data) { avct_ccb_dealloc(p_data->p_ccb, AVCT_CONNECT_CFM_EVT, AVCT_RESULT_FAIL, NULL); - DEVICE_IOT_CONFIG_ADDR_INT_ADD_ONE(p_lcb->peer_addr, - IOT_CONF_KEY_AVRCP_CONN_FAIL_COUNT); + DEVICE_IOT_CONFIG_ADDR_INT_ADD_ONE(p_lcb->peer_addr, IOT_CONF_KEY_AVRCP_CONN_FAIL_COUNT); } /******************************************************************************* @@ -505,10 +494,8 @@ void avct_lcb_cong_ind(tAVCT_LCB* p_lcb, tAVCT_LCB_EVT* p_data) { event = (p_data->cong) ? AVCT_CONG_IND_EVT : AVCT_UNCONG_IND_EVT; p_lcb->cong = p_data->cong; if (!p_lcb->cong && !fixed_queue_is_empty(p_lcb->tx_q)) { - while (!p_lcb->cong && - (p_buf = (BT_HDR*)fixed_queue_try_dequeue(p_lcb->tx_q)) != NULL) { - if (L2CA_DataWrite(p_lcb->ch_lcid, p_buf) == - tL2CAP_DW_RESULT::CONGESTED) { + while (!p_lcb->cong && (p_buf = (BT_HDR*)fixed_queue_try_dequeue(p_lcb->tx_q)) != NULL) { + if (L2CA_DataWrite(p_lcb->ch_lcid, p_buf) == tL2CAP_DW_RESULT::CONGESTED) { p_lcb->cong = true; } } @@ -517,8 +504,7 @@ void avct_lcb_cong_ind(tAVCT_LCB* p_lcb, tAVCT_LCB_EVT* p_data) { /* send event to all ccbs on this lcb */ for (i = 0; i < AVCT_NUM_CONN; i++, p_ccb++) { if (p_ccb->allocated && (p_ccb->p_lcb == p_lcb)) { - (*p_ccb->cc.p_ctrl_cback)(avct_ccb_to_idx(p_ccb), event, 0, - &p_lcb->peer_addr); + (*p_ccb->cc.p_ctrl_cback)(avct_ccb_to_idx(p_ccb), event, 0, &p_lcb->peer_addr); } } } @@ -567,7 +553,9 @@ void avct_lcb_send_msg(tAVCT_LCB* p_lcb, tAVCT_LCB_EVT* p_data) { pkt_type = AVCT_PKT_TYPE_START; temp = (curr_msg_len + AVCT_HDR_LEN_START - p_lcb->peer_mtu); nosp = temp / (p_lcb->peer_mtu - 1) + 1; - if ((temp % (p_lcb->peer_mtu - 1)) != 0) nosp++; + if ((temp % (p_lcb->peer_mtu - 1)) != 0) { + nosp++; + } } /* while we haven't sent all packets */ @@ -586,10 +574,8 @@ void avct_lcb_send_msg(tAVCT_LCB* p_lcb, tAVCT_LCB_EVT* p_data) { p_buf->offset = L2CAP_MIN_OFFSET + hdr_len; p_buf->len = p_lcb->peer_mtu - hdr_len; - memcpy( - (uint8_t*)(p_buf + 1) + p_buf->offset, - (uint8_t*)(p_data->ul_msg.p_buf + 1) + p_data->ul_msg.p_buf->offset, - p_buf->len); + memcpy((uint8_t*)(p_buf + 1) + p_buf->offset, + (uint8_t*)(p_data->ul_msg.p_buf + 1) + p_data->ul_msg.p_buf->offset, p_buf->len); p_data->ul_msg.p_buf->offset += p_buf->len; p_data->ul_msg.p_buf->len -= p_buf->len; @@ -609,8 +595,7 @@ void avct_lcb_send_msg(tAVCT_LCB* p_lcb, tAVCT_LCB_EVT* p_data) { if (pkt_type == AVCT_PKT_TYPE_START) { UINT8_TO_STREAM(p, nosp); } - if ((pkt_type == AVCT_PKT_TYPE_START) || - (pkt_type == AVCT_PKT_TYPE_SINGLE)) { + if ((pkt_type == AVCT_PKT_TYPE_START) || (pkt_type == AVCT_PKT_TYPE_SINGLE)) { UINT16_TO_BE_STREAM(p, p_data->ul_msg.p_ccb->cc.pid); } @@ -620,8 +605,7 @@ void avct_lcb_send_msg(tAVCT_LCB* p_lcb, tAVCT_LCB_EVT* p_data) { /* send message to L2CAP */ else { - if (L2CA_DataWrite(p_lcb->ch_lcid, p_buf) == - tL2CAP_DW_RESULT::CONGESTED) { + if (L2CA_DataWrite(p_lcb->ch_lcid, p_buf) == tL2CAP_DW_RESULT::CONGESTED) { p_lcb->cong = true; } } @@ -648,7 +632,9 @@ void avct_lcb_send_msg(tAVCT_LCB* p_lcb, tAVCT_LCB_EVT* p_data) { * ******************************************************************************/ void avct_lcb_free_msg_ind(tAVCT_LCB* /* p_lcb */, tAVCT_LCB_EVT* p_data) { - if (p_data == NULL) return; + if (p_data == NULL) { + return; + } osi_free_and_reset((void**)&p_data->p_buf); } @@ -699,7 +685,9 @@ void avct_lcb_msg_ind(tAVCT_LCB* p_lcb, tAVCT_LCB_EVT* p_data) { if (btif_av_src_sink_coexist_enabled()) { bind = avct_msg_ind_for_src_sink_coexist(p_lcb, p_data, label, cr_ipid); osi_free_and_reset((void**)&p_data->p_buf); - if (bind) return; + if (bind) { + return; + } } else { /* lookup PID */ p_ccb = avct_lcb_has_pid(p_lcb, pid); @@ -707,8 +695,7 @@ void avct_lcb_msg_ind(tAVCT_LCB* p_lcb, tAVCT_LCB_EVT* p_data) { /* PID found; send msg up, adjust bt hdr and call msg callback */ p_data->p_buf->offset += AVCT_HDR_LEN_SINGLE; p_data->p_buf->len -= AVCT_HDR_LEN_SINGLE; - (*p_ccb->cc.p_msg_cback)(avct_ccb_to_idx(p_ccb), label, cr_ipid, - p_data->p_buf); + (*p_ccb->cc.p_msg_cback)(avct_ccb_to_idx(p_ccb), label, cr_ipid, p_data->p_buf); return; } } @@ -726,14 +713,14 @@ void avct_lcb_msg_ind(tAVCT_LCB* p_lcb, tAVCT_LCB_EVT* p_data) { AVCT_BUILD_HDR(p, label, AVCT_PKT_TYPE_SINGLE, AVCT_REJ); UINT16_TO_BE_STREAM(p, pid); if (L2CA_DataWrite(p_lcb->ch_lcid, p_buf) != tL2CAP_DW_RESULT::SUCCESS) { - log::warn("Unable to write L2CAP data peer:{} cid:{} len:{}", - p_lcb->peer_addr, p_lcb->ch_lcid, p_buf->len); + log::warn("Unable to write L2CAP data peer:{} cid:{} len:{}", p_lcb->peer_addr, + p_lcb->ch_lcid, p_buf->len); } } } -bool avct_msg_ind_for_src_sink_coexist(tAVCT_LCB* p_lcb, tAVCT_LCB_EVT* p_data, - uint8_t label, uint8_t cr_ipid) { +bool avct_msg_ind_for_src_sink_coexist(tAVCT_LCB* p_lcb, tAVCT_LCB_EVT* p_data, uint8_t label, + uint8_t cr_ipid) { bool bind = false; tAVCT_CCB* p_ccb; int p_buf_len; @@ -758,8 +745,7 @@ bool avct_msg_ind_for_src_sink_coexist(tAVCT_LCB* p_lcb, tAVCT_LCB_EVT* p_data, bind = true; BT_HDR* p_tmp_buf = (BT_HDR*)osi_malloc(p_buf_len); memcpy(p_tmp_buf, p_data->p_buf, p_buf_len); - (*p_ccb->cc.p_msg_cback)(avct_ccb_to_idx(p_ccb), label, cr_ipid, - p_tmp_buf); + (*p_ccb->cc.p_msg_cback)(avct_ccb_to_idx(p_ccb), label, cr_ipid, p_tmp_buf); } } diff --git a/system/stack/avdt/avdt_ad.cc b/system/stack/avdt/avdt_ad.cc index 8702e1d6928..28e80b5320c 100644 --- a/system/stack/avdt/avdt_ad.cc +++ b/system/stack/avdt/avdt_ad.cc @@ -38,8 +38,7 @@ using namespace bluetooth; -AvdtpScb* AvdtpAdaptationLayer::LookupAvdtpScb( - const AvdtpTransportChannel& tc) { +AvdtpScb* AvdtpAdaptationLayer::LookupAvdtpScb(const AvdtpTransportChannel& tc) { if (tc.ccb_idx >= AVDT_NUM_LINKS) { log::error("AvdtpScb entry not found: invalid ccb_idx:{}", tc.ccb_idx); return nullptr; @@ -49,8 +48,7 @@ AvdtpScb* AvdtpAdaptationLayer::LookupAvdtpScb( return nullptr; } const AvdtpRoutingEntry& re = rt_tbl[tc.ccb_idx][tc.tcid]; - log::verbose("ccb_idx:{} tcid:{} scb_hdl:{}", tc.ccb_idx, tc.tcid, - re.scb_hdl); + log::verbose("ccb_idx:{} tcid:{} scb_hdl:{}", tc.ccb_idx, tc.tcid, re.scb_hdl); return avdt_scb_by_hdl(re.scb_hdl); } @@ -140,8 +138,7 @@ void avdt_ad_init(void) { * first matching entry (there could be more than one). * ******************************************************************************/ -AvdtpTransportChannel* avdt_ad_tc_tbl_by_st(uint8_t type, AvdtpCcb* p_ccb, - uint8_t state) { +AvdtpTransportChannel* avdt_ad_tc_tbl_by_st(uint8_t type, AvdtpCcb* p_ccb, uint8_t state) { int i; AvdtpTransportChannel* p_tbl = avdtp_cb.ad.tc_tbl; uint8_t ccb_idx; @@ -160,14 +157,12 @@ AvdtpTransportChannel* avdt_ad_tc_tbl_by_st(uint8_t type, AvdtpCcb* p_ccb, for (i = 0; i < AVDT_NUM_TC_TBL; i++, p_tbl++) { if (type == AVDT_CHAN_SIG) { /* if control channel, tcid always zero */ - if ((p_tbl->tcid == 0) && (p_tbl->ccb_idx == ccb_idx) && - (p_tbl->state == state)) { + if ((p_tbl->tcid == 0) && (p_tbl->ccb_idx == ccb_idx) && (p_tbl->state == state)) { break; } } else { /* if other channel, tcid is always > zero */ - if ((p_tbl->tcid > 0) && (p_tbl->ccb_idx == ccb_idx) && - (p_tbl->state == state)) { + if ((p_tbl->tcid > 0) && (p_tbl->ccb_idx == ccb_idx) && (p_tbl->state == state)) { break; } } @@ -212,8 +207,7 @@ AvdtpTransportChannel* avdt_ad_tc_tbl_by_lcid(uint16_t lcid) { * Returns Pointer to transport channel table entry. * ******************************************************************************/ -AvdtpTransportChannel* avdt_ad_tc_tbl_by_type(uint8_t type, AvdtpCcb* p_ccb, - AvdtpScb* p_scb) { +AvdtpTransportChannel* avdt_ad_tc_tbl_by_type(uint8_t type, AvdtpCcb* p_ccb, AvdtpScb* p_scb) { uint8_t tcid; int i; AvdtpTransportChannel* p_tbl = avdtp_cb.ad.tc_tbl; @@ -317,8 +311,7 @@ void avdt_ad_tc_close_ind(AvdtpTransportChannel* p_tbl) { /* look up scb in stream routing table by ccb, tcid */ p_scb = avdtp_cb.ad.LookupAvdtpScb(*p_tbl); if (p_scb == nullptr) { - log::error("Cannot find AvdtScb entry: ccb_idx:{} tcid:{}", p_tbl->ccb_idx, - p_tbl->tcid); + log::error("Cannot find AvdtScb entry: ccb_idx:{} tcid:{}", p_tbl->ccb_idx, p_tbl->tcid); return; } close.tcid = p_tbl->tcid; @@ -346,8 +339,8 @@ void avdt_ad_tc_open_ind(AvdtpTransportChannel* p_tbl) { tAVDT_OPEN open; tAVDT_EVT_HDR evt; - log::verbose("p_tbl:{} state:{} ccb_idx:{} tcid:{} scb_hdl:{}", - fmt::ptr(p_tbl), p_tbl->state, p_tbl->ccb_idx, p_tbl->tcid, + log::verbose("p_tbl:{} state:{} ccb_idx:{} tcid:{} scb_hdl:{}", fmt::ptr(p_tbl), p_tbl->state, + p_tbl->ccb_idx, p_tbl->tcid, avdtp_cb.ad.rt_tbl[p_tbl->ccb_idx][p_tbl->tcid].scb_hdl); p_tbl->state = AVDT_AD_ST_OPEN; @@ -355,9 +348,8 @@ void avdt_ad_tc_open_ind(AvdtpTransportChannel* p_tbl) { /* if signaling channel, notify ccb that channel open */ if (p_tbl->tcid == 0) { /* set the signal channel to use high priority within the ACL link */ - if (!L2CA_SetTxPriority( - avdtp_cb.ad.rt_tbl[p_tbl->ccb_idx][AVDT_CHAN_SIG].lcid, - L2CAP_CHNL_PRIORITY_HIGH)) { + if (!L2CA_SetTxPriority(avdtp_cb.ad.rt_tbl[p_tbl->ccb_idx][AVDT_CHAN_SIG].lcid, + L2CAP_CHNL_PRIORITY_HIGH)) { log::warn("Unable to set L2CAP transmit high priority cid:{}", avdtp_cb.ad.rt_tbl[p_tbl->ccb_idx][AVDT_CHAN_SIG].lcid); } @@ -378,8 +370,7 @@ void avdt_ad_tc_open_ind(AvdtpTransportChannel* p_tbl) { /* look up scb in stream routing table by ccb, tcid */ p_scb = avdtp_cb.ad.LookupAvdtpScb(*p_tbl); if (p_scb == nullptr) { - log::error("Cannot find AvdtScb entry: ccb_idx:{} tcid:{}", p_tbl->ccb_idx, - p_tbl->tcid); + log::error("Cannot find AvdtScb entry: ccb_idx:{} tcid:{}", p_tbl->ccb_idx, p_tbl->tcid); return; } /* put lcid in event data */ @@ -421,8 +412,7 @@ void avdt_ad_tc_cong_ind(AvdtpTransportChannel* p_tbl, bool is_congested) { /* look up scb in stream routing table by ccb, tcid */ p_scb = avdtp_cb.ad.LookupAvdtpScb(*p_tbl); if (p_scb == nullptr) { - log::error("Cannot find AvdtScb entry: ccb_idx:{} tcid:{}", p_tbl->ccb_idx, - p_tbl->tcid); + log::error("Cannot find AvdtScb entry: ccb_idx:{} tcid:{}", p_tbl->ccb_idx, p_tbl->tcid); return; } tAVDT_SCB_EVT avdt_scb_evt; @@ -458,8 +448,7 @@ void avdt_ad_tc_data_ind(AvdtpTransportChannel* p_tbl, BT_HDR* p_buf) { /* if media or other channel, send event to scb */ p_scb = avdtp_cb.ad.LookupAvdtpScb(*p_tbl); if (p_scb == nullptr) { - log::error("Cannot find AvdtScb entry: ccb_idx:{} tcid:{}", p_tbl->ccb_idx, - p_tbl->tcid); + log::error("Cannot find AvdtScb entry: ccb_idx:{} tcid:{}", p_tbl->ccb_idx, p_tbl->tcid); osi_free(p_buf); log::error("buffer freed"); return; @@ -483,15 +472,13 @@ void avdt_ad_tc_data_ind(AvdtpTransportChannel* p_tbl, BT_HDR* p_buf) { * AVDT_AD_FAILED, if error * ******************************************************************************/ -tL2CAP_DW_RESULT avdt_ad_write_req(uint8_t type, AvdtpCcb* p_ccb, - AvdtpScb* p_scb, BT_HDR* p_buf) { +tL2CAP_DW_RESULT avdt_ad_write_req(uint8_t type, AvdtpCcb* p_ccb, AvdtpScb* p_scb, BT_HDR* p_buf) { uint8_t tcid; /* get tcid from type, scb */ tcid = avdt_ad_type_to_tcid(type, p_scb); - return L2CA_DataWrite(avdtp_cb.ad.rt_tbl[avdt_ccb_to_idx(p_ccb)][tcid].lcid, - p_buf); + return L2CA_DataWrite(avdtp_cb.ad.rt_tbl[avdt_ccb_to_idx(p_ccb)][tcid].lcid, p_buf); } /******************************************************************************* @@ -510,8 +497,7 @@ tL2CAP_DW_RESULT avdt_ad_write_req(uint8_t type, AvdtpCcb* p_ccb, * Returns Nothing. * ******************************************************************************/ -void avdt_ad_open_req(uint8_t type, AvdtpCcb* p_ccb, AvdtpScb* p_scb, - uint8_t role) { +void avdt_ad_open_req(uint8_t type, AvdtpCcb* p_ccb, AvdtpScb* p_scb, uint8_t role) { AvdtpTransportChannel* p_tbl; uint16_t lcid; @@ -522,8 +508,7 @@ void avdt_ad_open_req(uint8_t type, AvdtpCcb* p_ccb, AvdtpScb* p_scb, } p_tbl->tcid = avdt_ad_type_to_tcid(type, p_scb); - log::verbose("avdt_ad_open_req: type: {}, role: {}, tcid:{}", type, role, - p_tbl->tcid); + log::verbose("avdt_ad_open_req: type: {}, role: {}, tcid:{}", type, role, p_tbl->tcid); if (type == AVDT_CHAN_SIG) { /* if signaling, get mtu from registration control block */ @@ -533,10 +518,9 @@ void avdt_ad_open_req(uint8_t type, AvdtpCcb* p_ccb, AvdtpScb* p_scb, p_tbl->my_mtu = kAvdtpMtu; /* also set scb_hdl in rt_tbl */ - avdtp_cb.ad.rt_tbl[avdt_ccb_to_idx(p_ccb)][p_tbl->tcid].scb_hdl = - avdt_scb_to_hdl(p_scb); - log::verbose("avdtp_cb.ad.rt_tbl[{}][{}].scb_hdl = {}", - avdt_ccb_to_idx(p_ccb), p_tbl->tcid, avdt_scb_to_hdl(p_scb)); + avdtp_cb.ad.rt_tbl[avdt_ccb_to_idx(p_ccb)][p_tbl->tcid].scb_hdl = avdt_scb_to_hdl(p_scb); + log::verbose("avdtp_cb.ad.rt_tbl[{}][{}].scb_hdl = {}", avdt_ccb_to_idx(p_ccb), p_tbl->tcid, + avdt_scb_to_hdl(p_scb)); } /* if we're acceptor, we're done; just sit back and listen */ @@ -548,17 +532,15 @@ void avdt_ad_open_req(uint8_t type, AvdtpCcb* p_ccb, AvdtpScb* p_scb, p_tbl->state = AVDT_AD_ST_CONN; /* call l2cap connect req */ - lcid = L2CA_ConnectReqWithSecurity(AVDT_PSM, p_ccb->peer_addr, - BTM_SEC_OUT_AUTHENTICATE); + lcid = L2CA_ConnectReqWithSecurity(AVDT_PSM, p_ccb->peer_addr, BTM_SEC_OUT_AUTHENTICATE); if (lcid != 0) { /* if connect req ok, store tcid in lcid table */ avdtp_cb.ad.lcid_tbl[lcid] = avdt_ad_tc_tbl_to_idx(p_tbl); - log::verbose("avdtp_cb.ad.lcid_tbl[{}] = {}", lcid, - avdt_ad_tc_tbl_to_idx(p_tbl)); + log::verbose("avdtp_cb.ad.lcid_tbl[{}] = {}", lcid, avdt_ad_tc_tbl_to_idx(p_tbl)); avdtp_cb.ad.rt_tbl[avdt_ccb_to_idx(p_ccb)][p_tbl->tcid].lcid = lcid; - log::verbose("avdtp_cb.ad.rt_tbl[{}][{}].lcid = 0x{:x}", - avdt_ccb_to_idx(p_ccb), p_tbl->tcid, lcid); + log::verbose("avdtp_cb.ad.rt_tbl[{}][{}].lcid = 0x{:x}", avdt_ccb_to_idx(p_ccb), p_tbl->tcid, + lcid); } else { /* if connect req failed, call avdt_ad_tc_close_ind() */ avdt_ad_tc_close_ind(p_tbl); @@ -598,7 +580,6 @@ void avdt_ad_close_req(uint8_t type, AvdtpCcb* p_ccb, AvdtpScb* p_scb) { tcid = avdt_ad_type_to_tcid(type, p_scb); /* call l2cap disconnect req */ - avdt_l2c_disconnect( - avdtp_cb.ad.rt_tbl[avdt_ccb_to_idx(p_ccb)][tcid].lcid); + avdt_l2c_disconnect(avdtp_cb.ad.rt_tbl[avdt_ccb_to_idx(p_ccb)][tcid].lcid); } } diff --git a/system/stack/avdt/avdt_api.cc b/system/stack/avdt/avdt_api.cc index e40f3c65d47..91e51f8804f 100644 --- a/system/stack/avdt/avdt_api.cc +++ b/system/stack/avdt/avdt_api.cc @@ -98,11 +98,9 @@ void avdt_scb_transport_channel_timer_timeout(void* data) { ******************************************************************************/ void AVDT_Register(AvdtpRcb* p_reg, tAVDT_CTRL_CBACK* p_cback) { /* register PSM with L2CAP */ - if (!L2CA_RegisterWithSecurity(AVDT_PSM, avdt_l2c_appl, - true /* enable_snoop */, nullptr, kAvdtpMtu, 0, - BTA_SEC_AUTHENTICATE)) { - log::error( - "Unable to register with L2CAP profile AVDT psm:AVDT_PSM[0x0019]"); + if (!L2CA_RegisterWithSecurity(AVDT_PSM, avdt_l2c_appl, true /* enable_snoop */, nullptr, + kAvdtpMtu, 0, BTA_SEC_AUTHENTICATE)) { + log::error("Unable to register with L2CAP profile AVDT psm:AVDT_PSM[0x0019]"); } /* initialize AVDTP data structures */ @@ -168,23 +166,20 @@ uint16_t AVDT_CreateStream(uint8_t peer_id, uint8_t* p_handle, if (((avdtp_stream_config.cfg.psc_mask & (~AVDT_PSC)) != 0) || (avdtp_stream_config.p_avdt_ctrl_cback == NULL)) { result = AVDT_BAD_PARAMS; - log::error( - "Invalid AVDT stream endpoint parameters peer_id={} scb_index={}", - peer_id, avdtp_stream_config.scb_index); + log::error("Invalid AVDT stream endpoint parameters peer_id={} scb_index={}", peer_id, + avdtp_stream_config.scb_index); } /* Allocate scb; if no scbs, return failure */ else { p_scb = avdt_scb_alloc(peer_id, avdtp_stream_config); if (p_scb == NULL) { - log::error( - "Unable to create AVDT stream endpoint peer_id={} scb_index={}", - peer_id, avdtp_stream_config.scb_index); + log::error("Unable to create AVDT stream endpoint peer_id={} scb_index={}", peer_id, + avdtp_stream_config.scb_index); result = AVDT_NO_RESOURCES; } else { *p_handle = avdt_scb_to_hdl(p_scb); - log::debug("Created stream endpoint peer_id={} handle={}", peer_id, - *p_handle); + log::debug("Created stream endpoint peer_id={} handle={}", peer_id, *p_handle); } } return static_cast(result); @@ -253,8 +248,7 @@ uint16_t AVDT_RemoveStream(uint8_t handle) { * ******************************************************************************/ uint16_t AVDT_DiscoverReq(const RawAddress& bd_addr, uint8_t channel_index, - tAVDT_SEP_INFO* p_sep_info, uint8_t max_seps, - tAVDT_CTRL_CBACK* p_cback) { + tAVDT_SEP_INFO* p_sep_info, uint8_t max_seps, tAVDT_CTRL_CBACK* p_cback) { AvdtpCcb* p_ccb; uint16_t result = AVDT_SUCCESS; tAVDT_CCB_EVT evt; @@ -300,15 +294,13 @@ uint16_t AVDT_DiscoverReq(const RawAddress& bd_addr, uint8_t channel_index, * Returns AVDT_SUCCESS if successful, otherwise error. * ******************************************************************************/ -static uint16_t avdt_get_cap_req(const RawAddress& bd_addr, - uint8_t channel_index, +static uint16_t avdt_get_cap_req(const RawAddress& bd_addr, uint8_t channel_index, tAVDT_CCB_API_GETCAP* p_evt) { AvdtpCcb* p_ccb = NULL; uint16_t result = AVDT_SUCCESS; /* verify SEID */ - if ((p_evt->single.seid < AVDT_SEID_MIN) || - (p_evt->single.seid > AVDT_SEID_MAX)) { + if ((p_evt->single.seid < AVDT_SEID_MIN) || (p_evt->single.seid > AVDT_SEID_MAX)) { log::error("seid: {}", p_evt->single.seid); result = AVDT_BAD_PARAMS; } @@ -365,14 +357,13 @@ static uint16_t avdt_get_cap_req(const RawAddress& bd_addr, * Returns AVDT_SUCCESS if successful, otherwise error. * ******************************************************************************/ -uint16_t AVDT_GetCapReq(const RawAddress& bd_addr, uint8_t channel_index, - uint8_t seid, AvdtpSepConfig* p_cfg, - tAVDT_CTRL_CBACK* p_cback, bool get_all_cap) { +uint16_t AVDT_GetCapReq(const RawAddress& bd_addr, uint8_t channel_index, uint8_t seid, + AvdtpSepConfig* p_cfg, tAVDT_CTRL_CBACK* p_cback, bool get_all_cap) { tAVDT_CCB_API_GETCAP getcap; uint16_t result = AVDT_SUCCESS; - log::info("bd_addr={} channel_index={} seid=0x{:x} get_all_capabilities={}", - bd_addr, channel_index, seid, get_all_cap); + log::info("bd_addr={} channel_index={} seid=0x{:x} get_all_capabilities={}", bd_addr, + channel_index, seid, get_all_cap); getcap.single.seid = seid; if (get_all_cap) { @@ -440,9 +431,8 @@ uint16_t AVDT_DelayReport(uint8_t handle, uint8_t seid, uint16_t delay) { * Returns AVDT_SUCCESS if successful, otherwise error. * ******************************************************************************/ -uint16_t AVDT_OpenReq(uint8_t handle, const RawAddress& bd_addr, - uint8_t channel_index, uint8_t seid, - AvdtpSepConfig* p_cfg) { +uint16_t AVDT_OpenReq(uint8_t handle, const RawAddress& bd_addr, uint8_t channel_index, + uint8_t seid, AvdtpSepConfig* p_cfg) { AvdtpCcb* p_ccb = NULL; AvdtpScb* p_scb = NULL; uint16_t result = AVDT_SUCCESS; @@ -501,15 +491,14 @@ uint16_t AVDT_OpenReq(uint8_t handle, const RawAddress& bd_addr, * Returns AVDT_SUCCESS if successful, otherwise error. * ******************************************************************************/ -uint16_t AVDT_ConfigRsp(uint8_t handle, uint8_t label, uint8_t error_code, - uint8_t category) { +uint16_t AVDT_ConfigRsp(uint8_t handle, uint8_t label, uint8_t error_code, uint8_t category) { AvdtpScb* p_scb; tAVDT_SCB_EVT evt; uint16_t result = AVDT_SUCCESS; uint8_t event_code; - log::info("avdt_handle={} label={} error_code=0x{:x} category={}", handle, - label, error_code, category); + log::info("avdt_handle={} label={} error_code=0x{:x} category={}", handle, label, error_code, + category); /* map handle to scb */ p_scb = avdt_scb_by_hdl(handle); @@ -789,14 +778,13 @@ uint16_t AVDT_SecurityReq(uint8_t handle, uint8_t* p_data, uint16_t len) { * Returns AVDT_SUCCESS if successful, otherwise error. * ******************************************************************************/ -uint16_t AVDT_SecurityRsp(uint8_t handle, uint8_t label, uint8_t error_code, - uint8_t* p_data, uint16_t len) { +uint16_t AVDT_SecurityRsp(uint8_t handle, uint8_t label, uint8_t error_code, uint8_t* p_data, + uint16_t len) { AvdtpScb* p_scb; uint16_t result = AVDT_SUCCESS; tAVDT_SCB_EVT evt; - log::info("avdt_handle={} label={} error_code=0x{:x} len={}", handle, - label, error_code, len); + log::info("avdt_handle={} label={} error_code=0x{:x} len={}", handle, label, error_code, len); /* map handle to scb */ p_scb = avdt_scb_by_hdl(handle); @@ -855,14 +843,13 @@ uint16_t AVDT_SecurityRsp(uint8_t handle, uint8_t label, uint8_t error_code, * Returns AVDT_SUCCESS if successful, otherwise error. * ******************************************************************************/ -uint16_t AVDT_WriteReqOpt(uint8_t handle, BT_HDR* p_pkt, uint32_t time_stamp, - uint8_t m_pt, tAVDT_DATA_OPT_MASK opt) { +uint16_t AVDT_WriteReqOpt(uint8_t handle, BT_HDR* p_pkt, uint32_t time_stamp, uint8_t m_pt, + tAVDT_DATA_OPT_MASK opt) { AvdtpScb* p_scb; tAVDT_SCB_EVT evt; uint16_t result = AVDT_SUCCESS; - log::verbose("avdt_handle={} timestamp={} m_pt=0x{:x} opt=0x{:x}", handle, - time_stamp, m_pt, opt); + log::verbose("avdt_handle={} timestamp={} m_pt=0x{:x} opt=0x{:x}", handle, time_stamp, m_pt, opt); /* map handle to scb */ p_scb = avdt_scb_by_hdl(handle); @@ -941,8 +928,7 @@ uint16_t AVDT_ConnectReq(const RawAddress& bd_addr, uint8_t channel_index, * Returns AVDT_SUCCESS if successful, otherwise error. * ******************************************************************************/ -uint16_t AVDT_DisconnectReq(const RawAddress& bd_addr, - tAVDT_CTRL_CBACK* p_cback) { +uint16_t AVDT_DisconnectReq(const RawAddress& bd_addr, tAVDT_CTRL_CBACK* p_cback) { AvdtpCcb* p_ccb = NULL; tAVDT_RESULT result = AVDT_SUCCESS; tAVDT_CCB_EVT evt; @@ -978,21 +964,19 @@ uint16_t AVDT_GetL2CapChannel(uint8_t handle) { uint16_t lcid = 0; /* map handle to scb */ - if (((p_scb = avdt_scb_by_hdl(handle)) != NULL) && - ((p_ccb = p_scb->p_ccb) != NULL)) { + if (((p_scb = avdt_scb_by_hdl(handle)) != NULL) && ((p_ccb = p_scb->p_ccb) != NULL)) { /* get tcid from type, scb */ tcid = avdt_ad_type_to_tcid(AVDT_CHAN_MEDIA, p_scb); lcid = avdtp_cb.ad.rt_tbl[avdt_ccb_to_idx(p_ccb)][tcid].lcid; } - return (lcid); + return lcid; } void stack_debug_avdtp_api_dump(int fd) { dprintf(fd, "\nAVDTP Stack State:\n"); - dprintf(fd, " AVDTP signalling L2CAP channel MTU: %d\n", - avdtp_cb.rcb.ctrl_mtu); + dprintf(fd, " AVDTP signalling L2CAP channel MTU: %d\n", avdtp_cb.rcb.ctrl_mtu); for (size_t i = 0; i < AVDT_NUM_LINKS; i++) { const AvdtpCcb& ccb = avdtp_cb.ccb[i]; @@ -1003,13 +987,10 @@ void stack_debug_avdtp_api_dump(int fd) { ADDRESS_TO_LOGGABLE_CSTR(ccb.peer_addr)); dprintf(fd, " Allocated: %s\n", ccb.allocated ? "true" : "false"); dprintf(fd, " State: %d\n", ccb.state); - dprintf(fd, " Link-layer opened: %s\n", - ccb.ll_opened ? "true" : "false"); - dprintf(fd, " Discover in progress: %s\n", - ccb.proc_busy ? "true" : "false"); + dprintf(fd, " Link-layer opened: %s\n", ccb.ll_opened ? "true" : "false"); + dprintf(fd, " Discover in progress: %s\n", ccb.proc_busy ? "true" : "false"); dprintf(fd, " Congested: %s\n", ccb.cong ? "true" : "false"); - dprintf(fd, " Reinitiate connection on idle: %s\n", - ccb.reconn ? "true" : "false"); + dprintf(fd, " Reinitiate connection on idle: %s\n", ccb.reconn ? "true" : "false"); dprintf(fd, " Command retransmission count: %d\n", ccb.ret_count); dprintf(fd, " BTA AV SCB index: %d\n", ccb.BtaAvScbIndex()); @@ -1019,8 +1000,7 @@ void stack_debug_avdtp_api_dump(int fd) { continue; } dprintf(fd, "\n Stream control block: %zu\n", i); - dprintf(fd, " SEP codec: %s\n", - A2DP_CodecName(scb.stream_config.cfg.codec_info)); + dprintf(fd, " SEP codec: %s\n", A2DP_CodecName(scb.stream_config.cfg.codec_info)); dprintf(fd, " SEP protocol service capabilities: 0x%x\n", scb.stream_config.cfg.psc_mask); dprintf(fd, " SEP type: 0x%x\n", scb.stream_config.tsep); @@ -1028,18 +1008,12 @@ void stack_debug_avdtp_api_dump(int fd) { dprintf(fd, " MTU: %d\n", scb.stream_config.mtu); dprintf(fd, " AVDT SCB handle: %d\n", scb.ScbHandle()); dprintf(fd, " SCB index: %d\n", scb.stream_config.scb_index); - dprintf(fd, " Configured codec: %s\n", - A2DP_CodecName(scb.curr_cfg.codec_info)); - dprintf(fd, " Requested codec: %s\n", - A2DP_CodecName(scb.req_cfg.codec_info)); + dprintf(fd, " Configured codec: %s\n", A2DP_CodecName(scb.curr_cfg.codec_info)); + dprintf(fd, " Requested codec: %s\n", A2DP_CodecName(scb.req_cfg.codec_info)); dprintf(fd, " Transport channel connect timer: %s\n", - alarm_is_scheduled(scb.transport_channel_timer) - ? "Scheduled" - : "Not scheduled"); + alarm_is_scheduled(scb.transport_channel_timer) ? "Scheduled" : "Not scheduled"); dprintf(fd, " Channel control block peer: %s\n", - (scb.p_ccb != nullptr) - ? ADDRESS_TO_LOGGABLE_CSTR(scb.p_ccb->peer_addr) - : "null"); + (scb.p_ccb != nullptr) ? ADDRESS_TO_LOGGABLE_CSTR(scb.p_ccb->peer_addr) : "null"); dprintf(fd, " Allocated: %s\n", scb.allocated ? "true" : "false"); dprintf(fd, " In use: %s\n", scb.in_use ? "true" : "false"); dprintf(fd, " Role: 0x%x\n", scb.role); diff --git a/system/stack/avdt/avdt_ccb.cc b/system/stack/avdt/avdt_ccb.cc index ce46603f907..eca5c1f6ad6 100644 --- a/system/stack/avdt/avdt_ccb.cc +++ b/system/stack/avdt/avdt_ccb.cc @@ -40,46 +40,39 @@ using namespace bluetooth; ****************************************************************************/ /* verbose state strings for trace */ -const char* const avdt_ccb_st_str[] = {"CCB_IDLE_ST", "CCB_OPENING_ST", - "CCB_OPEN_ST", "CCB_CLOSING_ST"}; +const char* const avdt_ccb_st_str[] = {"CCB_IDLE_ST", "CCB_OPENING_ST", "CCB_OPEN_ST", + "CCB_CLOSING_ST"}; /* verbose event strings for trace */ -const char* const avdt_ccb_evt_str[] = { - "API_DISCOVER_REQ_EVT", "API_GETCAP_REQ_EVT", - "API_START_REQ_EVT", "API_SUSPEND_REQ_EVT", - "API_DISCOVER_RSP_EVT", "API_GETCAP_RSP_EVT", - "API_START_RSP_EVT", "API_SUSPEND_RSP_EVT", - "API_CONNECT_REQ_EVT", "API_DISCONNECT_REQ_EVT", - "MSG_DISCOVER_CMD_EVT", "MSG_GETCAP_CMD_EVT", - "MSG_START_CMD_EVT", "MSG_SUSPEND_CMD_EVT", - "MSG_DISCOVER_RSP_EVT", "MSG_GETCAP_RSP_EVT", - "MSG_START_RSP_EVT", "MSG_SUSPEND_RSP_EVT", - "RCVRSP_EVT", "SENDMSG_EVT", - "RET_TOUT_EVT", "RSP_TOUT_EVT", - "IDLE_TOUT_EVT", "UL_OPEN_EVT", - "UL_CLOSE_EVT", "LL_OPEN_EVT", - "LL_CLOSE_EVT", "LL_CONG_EVT"}; +const char* const avdt_ccb_evt_str[] = {"API_DISCOVER_REQ_EVT", "API_GETCAP_REQ_EVT", + "API_START_REQ_EVT", "API_SUSPEND_REQ_EVT", + "API_DISCOVER_RSP_EVT", "API_GETCAP_RSP_EVT", + "API_START_RSP_EVT", "API_SUSPEND_RSP_EVT", + "API_CONNECT_REQ_EVT", "API_DISCONNECT_REQ_EVT", + "MSG_DISCOVER_CMD_EVT", "MSG_GETCAP_CMD_EVT", + "MSG_START_CMD_EVT", "MSG_SUSPEND_CMD_EVT", + "MSG_DISCOVER_RSP_EVT", "MSG_GETCAP_RSP_EVT", + "MSG_START_RSP_EVT", "MSG_SUSPEND_RSP_EVT", + "RCVRSP_EVT", "SENDMSG_EVT", + "RET_TOUT_EVT", "RSP_TOUT_EVT", + "IDLE_TOUT_EVT", "UL_OPEN_EVT", + "UL_CLOSE_EVT", "LL_OPEN_EVT", + "LL_CLOSE_EVT", "LL_CONG_EVT"}; /* action function list */ const tAVDT_CCB_ACTION avdt_ccb_action[] = { - avdt_ccb_chan_open, avdt_ccb_chan_close, - avdt_ccb_chk_close, avdt_ccb_hdl_discover_cmd, - avdt_ccb_hdl_discover_rsp, avdt_ccb_hdl_getcap_cmd, - avdt_ccb_hdl_getcap_rsp, avdt_ccb_hdl_start_cmd, - avdt_ccb_hdl_start_rsp, avdt_ccb_hdl_suspend_cmd, - avdt_ccb_hdl_suspend_rsp, avdt_ccb_snd_discover_cmd, - avdt_ccb_snd_discover_rsp, avdt_ccb_snd_getcap_cmd, - avdt_ccb_snd_getcap_rsp, avdt_ccb_snd_start_cmd, - avdt_ccb_snd_start_rsp, avdt_ccb_snd_suspend_cmd, - avdt_ccb_snd_suspend_rsp, avdt_ccb_clear_cmds, - avdt_ccb_cmd_fail, avdt_ccb_free_cmd, - avdt_ccb_cong_state, avdt_ccb_ret_cmd, - avdt_ccb_snd_cmd, avdt_ccb_snd_msg, - avdt_ccb_set_reconn, avdt_ccb_clr_reconn, - avdt_ccb_chk_reconn, avdt_ccb_chk_timer, - avdt_ccb_set_conn, avdt_ccb_set_disconn, - avdt_ccb_do_disconn, avdt_ccb_ll_closed, - avdt_ccb_ll_opened, avdt_ccb_dealloc}; + avdt_ccb_chan_open, avdt_ccb_chan_close, avdt_ccb_chk_close, + avdt_ccb_hdl_discover_cmd, avdt_ccb_hdl_discover_rsp, avdt_ccb_hdl_getcap_cmd, + avdt_ccb_hdl_getcap_rsp, avdt_ccb_hdl_start_cmd, avdt_ccb_hdl_start_rsp, + avdt_ccb_hdl_suspend_cmd, avdt_ccb_hdl_suspend_rsp, avdt_ccb_snd_discover_cmd, + avdt_ccb_snd_discover_rsp, avdt_ccb_snd_getcap_cmd, avdt_ccb_snd_getcap_rsp, + avdt_ccb_snd_start_cmd, avdt_ccb_snd_start_rsp, avdt_ccb_snd_suspend_cmd, + avdt_ccb_snd_suspend_rsp, avdt_ccb_clear_cmds, avdt_ccb_cmd_fail, + avdt_ccb_free_cmd, avdt_ccb_cong_state, avdt_ccb_ret_cmd, + avdt_ccb_snd_cmd, avdt_ccb_snd_msg, avdt_ccb_set_reconn, + avdt_ccb_clr_reconn, avdt_ccb_chk_reconn, avdt_ccb_chk_timer, + avdt_ccb_set_conn, avdt_ccb_set_disconn, avdt_ccb_do_disconn, + avdt_ccb_ll_closed, avdt_ccb_ll_opened, avdt_ccb_dealloc}; /* state table information */ #define AVDT_CCB_ACTIONS 2 /* number of actions */ @@ -88,255 +81,254 @@ const tAVDT_CCB_ACTION avdt_ccb_action[] = { /* state table for idle state */ const uint8_t avdt_ccb_st_idle[][AVDT_CCB_NUM_COLS] = { - /* Event */ - /* Action 1 Action 2 Next state */ - /* API_DISCOVER_REQ_EVT */ - {AVDT_CCB_SND_DISCOVER_CMD, AVDT_CCB_CHAN_OPEN, AVDT_CCB_OPENING_ST}, - /* API_GETCAP_REQ_EVT */ - {AVDT_CCB_SND_GETCAP_CMD, AVDT_CCB_CHAN_OPEN, AVDT_CCB_OPENING_ST}, - /* API_START_REQ_EVT */ - {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_IDLE_ST}, - /* API_SUSPEND_REQ_EVT */ - {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_IDLE_ST}, - /* API_DISCOVER_RSP_EVT */ - {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_IDLE_ST}, - /* API_GETCAP_RSP_EVT */ - {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_IDLE_ST}, - /* API_START_RSP_EVT */ - {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_IDLE_ST}, - /* API_SUSPEND_RSP_EVT */ - {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_IDLE_ST}, - /* API_CONNECT_REQ_EVT */ - {AVDT_CCB_SET_CONN, AVDT_CCB_CHAN_OPEN, AVDT_CCB_OPENING_ST}, - /* API_DISCONNECT_REQ_EVT */ - {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_IDLE_ST}, - /* MSG_DISCOVER_CMD_EVT */ - {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_IDLE_ST}, - /* MSG_GETCAP_CMD_EVT */ - {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_IDLE_ST}, - /* MSG_START_CMD_EVT */ - {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_IDLE_ST}, - /* MSG_SUSPEND_CMD_EVT */ - {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_IDLE_ST}, - /* MSG_DISCOVER_RSP_EVT */ - {AVDT_CCB_HDL_DISCOVER_RSP, AVDT_CCB_IGNORE, AVDT_CCB_IDLE_ST}, - /* MSG_GETCAP_RSP_EVT */ - {AVDT_CCB_HDL_GETCAP_RSP, AVDT_CCB_IGNORE, AVDT_CCB_IDLE_ST}, - /* MSG_START_RSP_EVT */ - {AVDT_CCB_HDL_START_RSP, AVDT_CCB_IGNORE, AVDT_CCB_IDLE_ST}, - /* MSG_SUSPEND_RSP_EVT */ - {AVDT_CCB_HDL_SUSPEND_RSP, AVDT_CCB_IGNORE, AVDT_CCB_IDLE_ST}, - /* RCVRSP_EVT */ - {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_IDLE_ST}, - /* SENDMSG_EVT */ - {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_IDLE_ST}, - /* RET_TOUT_EVT */ - {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_IDLE_ST}, - /* RSP_TOUT_EVT */ - {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_IDLE_ST}, - /* IDLE_TOUT_EVT */ - {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_IDLE_ST}, - /* UL_OPEN_EVT */ - {AVDT_CCB_CHAN_OPEN, AVDT_CCB_IGNORE, AVDT_CCB_OPENING_ST}, - /* UL_CLOSE_EVT */ - {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_IDLE_ST}, - /* LL_OPEN_EVT */ - {AVDT_CCB_LL_OPENED, AVDT_CCB_IGNORE, AVDT_CCB_OPEN_ST}, - /* LL_CLOSE_EVT */ - {AVDT_CCB_LL_CLOSED, AVDT_CCB_IGNORE, AVDT_CCB_IDLE_ST}, - /* LL_CONG_EVT */ - {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_IDLE_ST}}; + /* Event */ + /* Action 1 Action 2 Next state */ + /* API_DISCOVER_REQ_EVT */ + {AVDT_CCB_SND_DISCOVER_CMD, AVDT_CCB_CHAN_OPEN, AVDT_CCB_OPENING_ST}, + /* API_GETCAP_REQ_EVT */ + {AVDT_CCB_SND_GETCAP_CMD, AVDT_CCB_CHAN_OPEN, AVDT_CCB_OPENING_ST}, + /* API_START_REQ_EVT */ + {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_IDLE_ST}, + /* API_SUSPEND_REQ_EVT */ + {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_IDLE_ST}, + /* API_DISCOVER_RSP_EVT */ + {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_IDLE_ST}, + /* API_GETCAP_RSP_EVT */ + {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_IDLE_ST}, + /* API_START_RSP_EVT */ + {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_IDLE_ST}, + /* API_SUSPEND_RSP_EVT */ + {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_IDLE_ST}, + /* API_CONNECT_REQ_EVT */ + {AVDT_CCB_SET_CONN, AVDT_CCB_CHAN_OPEN, AVDT_CCB_OPENING_ST}, + /* API_DISCONNECT_REQ_EVT */ + {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_IDLE_ST}, + /* MSG_DISCOVER_CMD_EVT */ + {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_IDLE_ST}, + /* MSG_GETCAP_CMD_EVT */ + {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_IDLE_ST}, + /* MSG_START_CMD_EVT */ + {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_IDLE_ST}, + /* MSG_SUSPEND_CMD_EVT */ + {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_IDLE_ST}, + /* MSG_DISCOVER_RSP_EVT */ + {AVDT_CCB_HDL_DISCOVER_RSP, AVDT_CCB_IGNORE, AVDT_CCB_IDLE_ST}, + /* MSG_GETCAP_RSP_EVT */ + {AVDT_CCB_HDL_GETCAP_RSP, AVDT_CCB_IGNORE, AVDT_CCB_IDLE_ST}, + /* MSG_START_RSP_EVT */ + {AVDT_CCB_HDL_START_RSP, AVDT_CCB_IGNORE, AVDT_CCB_IDLE_ST}, + /* MSG_SUSPEND_RSP_EVT */ + {AVDT_CCB_HDL_SUSPEND_RSP, AVDT_CCB_IGNORE, AVDT_CCB_IDLE_ST}, + /* RCVRSP_EVT */ + {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_IDLE_ST}, + /* SENDMSG_EVT */ + {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_IDLE_ST}, + /* RET_TOUT_EVT */ + {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_IDLE_ST}, + /* RSP_TOUT_EVT */ + {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_IDLE_ST}, + /* IDLE_TOUT_EVT */ + {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_IDLE_ST}, + /* UL_OPEN_EVT */ + {AVDT_CCB_CHAN_OPEN, AVDT_CCB_IGNORE, AVDT_CCB_OPENING_ST}, + /* UL_CLOSE_EVT */ + {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_IDLE_ST}, + /* LL_OPEN_EVT */ + {AVDT_CCB_LL_OPENED, AVDT_CCB_IGNORE, AVDT_CCB_OPEN_ST}, + /* LL_CLOSE_EVT */ + {AVDT_CCB_LL_CLOSED, AVDT_CCB_IGNORE, AVDT_CCB_IDLE_ST}, + /* LL_CONG_EVT */ + {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_IDLE_ST}}; /* state table for opening state */ const uint8_t avdt_ccb_st_opening[][AVDT_CCB_NUM_COLS] = { - /* Event */ - /* Action 1 Action 2 Next state */ - /* API_DISCOVER_REQ_EVT */ - {AVDT_CCB_SND_DISCOVER_CMD, AVDT_CCB_IGNORE, AVDT_CCB_OPENING_ST}, - /* API_GETCAP_REQ_EVT */ - {AVDT_CCB_SND_GETCAP_CMD, AVDT_CCB_IGNORE, AVDT_CCB_OPENING_ST}, - /* API_START_REQ_EVT */ - {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_OPENING_ST}, - /* API_SUSPEND_REQ_EVT */ - {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_OPENING_ST}, - /* API_DISCOVER_RSP_EVT */ - {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_OPENING_ST}, - /* API_GETCAP_RSP_EVT */ - {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_OPENING_ST}, - /* API_START_RSP_EVT */ - {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_OPENING_ST}, - /* API_SUSPEND_RSP_EVT */ - {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_OPENING_ST}, - /* API_CONNECT_REQ_EVT */ - {AVDT_CCB_SET_CONN, AVDT_CCB_IGNORE, AVDT_CCB_OPENING_ST}, - /* API_DISCONNECT_REQ_EVT */ - {AVDT_CCB_SET_DISCONN, AVDT_CCB_DO_DISCONN, AVDT_CCB_CLOSING_ST}, - /* MSG_DISCOVER_CMD_EVT */ - {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_OPENING_ST}, - /* MSG_GETCAP_CMD_EVT */ - {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_OPENING_ST}, - /* MSG_START_CMD_EVT */ - {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_OPENING_ST}, - /* MSG_SUSPEND_CMD_EVT */ - {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_OPENING_ST}, - /* MSG_DISCOVER_RSP_EVT */ - {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_OPENING_ST}, - /* MSG_GETCAP_RSP_EVT */ - {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_OPENING_ST}, - /* MSG_START_RSP_EVT */ - {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_OPENING_ST}, - /* MSG_SUSPEND_RSP_EVT */ - {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_OPENING_ST}, - /* RCVRSP_EVT */ - {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_OPENING_ST}, - /* SENDMSG_EVT */ - {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_OPENING_ST}, - /* RET_TOUT_EVT */ - {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_OPENING_ST}, - /* RSP_TOUT_EVT */ - {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_OPENING_ST}, - /* IDLE_TOUT_EVT */ - {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_OPENING_ST}, - /* UL_OPEN_EVT */ - {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_OPENING_ST}, - /* UL_CLOSE_EVT */ - {AVDT_CCB_CLEAR_CMDS, AVDT_CCB_CHAN_CLOSE, AVDT_CCB_CLOSING_ST}, - /* LL_OPEN_EVT */ - {AVDT_CCB_SND_CMD, AVDT_CCB_LL_OPENED, AVDT_CCB_OPEN_ST}, - /* LL_CLOSE_EVT */ - {AVDT_CCB_LL_CLOSED, AVDT_CCB_IGNORE, AVDT_CCB_IDLE_ST}, - /* LL_CONG_EVT */ - {AVDT_CCB_CONG_STATE, AVDT_CCB_IGNORE, AVDT_CCB_OPENING_ST}}; + /* Event */ + /* Action 1 Action 2 Next state */ + /* API_DISCOVER_REQ_EVT */ + {AVDT_CCB_SND_DISCOVER_CMD, AVDT_CCB_IGNORE, AVDT_CCB_OPENING_ST}, + /* API_GETCAP_REQ_EVT */ + {AVDT_CCB_SND_GETCAP_CMD, AVDT_CCB_IGNORE, AVDT_CCB_OPENING_ST}, + /* API_START_REQ_EVT */ + {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_OPENING_ST}, + /* API_SUSPEND_REQ_EVT */ + {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_OPENING_ST}, + /* API_DISCOVER_RSP_EVT */ + {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_OPENING_ST}, + /* API_GETCAP_RSP_EVT */ + {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_OPENING_ST}, + /* API_START_RSP_EVT */ + {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_OPENING_ST}, + /* API_SUSPEND_RSP_EVT */ + {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_OPENING_ST}, + /* API_CONNECT_REQ_EVT */ + {AVDT_CCB_SET_CONN, AVDT_CCB_IGNORE, AVDT_CCB_OPENING_ST}, + /* API_DISCONNECT_REQ_EVT */ + {AVDT_CCB_SET_DISCONN, AVDT_CCB_DO_DISCONN, AVDT_CCB_CLOSING_ST}, + /* MSG_DISCOVER_CMD_EVT */ + {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_OPENING_ST}, + /* MSG_GETCAP_CMD_EVT */ + {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_OPENING_ST}, + /* MSG_START_CMD_EVT */ + {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_OPENING_ST}, + /* MSG_SUSPEND_CMD_EVT */ + {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_OPENING_ST}, + /* MSG_DISCOVER_RSP_EVT */ + {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_OPENING_ST}, + /* MSG_GETCAP_RSP_EVT */ + {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_OPENING_ST}, + /* MSG_START_RSP_EVT */ + {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_OPENING_ST}, + /* MSG_SUSPEND_RSP_EVT */ + {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_OPENING_ST}, + /* RCVRSP_EVT */ + {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_OPENING_ST}, + /* SENDMSG_EVT */ + {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_OPENING_ST}, + /* RET_TOUT_EVT */ + {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_OPENING_ST}, + /* RSP_TOUT_EVT */ + {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_OPENING_ST}, + /* IDLE_TOUT_EVT */ + {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_OPENING_ST}, + /* UL_OPEN_EVT */ + {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_OPENING_ST}, + /* UL_CLOSE_EVT */ + {AVDT_CCB_CLEAR_CMDS, AVDT_CCB_CHAN_CLOSE, AVDT_CCB_CLOSING_ST}, + /* LL_OPEN_EVT */ + {AVDT_CCB_SND_CMD, AVDT_CCB_LL_OPENED, AVDT_CCB_OPEN_ST}, + /* LL_CLOSE_EVT */ + {AVDT_CCB_LL_CLOSED, AVDT_CCB_IGNORE, AVDT_CCB_IDLE_ST}, + /* LL_CONG_EVT */ + {AVDT_CCB_CONG_STATE, AVDT_CCB_IGNORE, AVDT_CCB_OPENING_ST}}; /* state table for open state */ const uint8_t avdt_ccb_st_open[][AVDT_CCB_NUM_COLS] = { - /* Event */ - /* Action 1 Action 2 Next state */ - /* API_DISCOVER_REQ_EVT */ - {AVDT_CCB_SND_DISCOVER_CMD, AVDT_CCB_SND_CMD, AVDT_CCB_OPEN_ST}, - /* API_GETCAP_REQ_EVT */ - {AVDT_CCB_SND_GETCAP_CMD, AVDT_CCB_SND_CMD, AVDT_CCB_OPEN_ST}, - /* API_START_REQ_EVT */ - {AVDT_CCB_SND_START_CMD, AVDT_CCB_SND_CMD, AVDT_CCB_OPEN_ST}, - /* API_SUSPEND_REQ_EVT */ - {AVDT_CCB_SND_SUSPEND_CMD, AVDT_CCB_SND_CMD, AVDT_CCB_OPEN_ST}, - /* API_DISCOVER_RSP_EVT */ - {AVDT_CCB_SND_DISCOVER_RSP, AVDT_CCB_SND_CMD, AVDT_CCB_OPEN_ST}, - /* API_GETCAP_RSP_EVT */ - {AVDT_CCB_SND_GETCAP_RSP, AVDT_CCB_SND_CMD, AVDT_CCB_OPEN_ST}, - /* API_START_RSP_EVT */ - {AVDT_CCB_SND_START_RSP, AVDT_CCB_SND_CMD, AVDT_CCB_OPEN_ST}, - /* API_SUSPEND_RSP_EVT */ - {AVDT_CCB_SND_SUSPEND_RSP, AVDT_CCB_SND_CMD, AVDT_CCB_OPEN_ST}, - /* API_CONNECT_REQ_EVT */ - {AVDT_CCB_SET_CONN, AVDT_CCB_LL_OPENED, AVDT_CCB_OPEN_ST}, - /* API_DISCONNECT_REQ_EVT */ - {AVDT_CCB_SET_DISCONN, AVDT_CCB_DO_DISCONN, AVDT_CCB_CLOSING_ST}, - /* MSG_DISCOVER_CMD_EVT */ - {AVDT_CCB_HDL_DISCOVER_CMD, AVDT_CCB_IGNORE, AVDT_CCB_OPEN_ST}, - /* MSG_GETCAP_CMD_EVT */ - {AVDT_CCB_HDL_GETCAP_CMD, AVDT_CCB_IGNORE, AVDT_CCB_OPEN_ST}, - /* MSG_START_CMD_EVT */ - {AVDT_CCB_HDL_START_CMD, AVDT_CCB_IGNORE, AVDT_CCB_OPEN_ST}, - /* MSG_SUSPEND_CMD_EVT */ - {AVDT_CCB_HDL_SUSPEND_CMD, AVDT_CCB_IGNORE, AVDT_CCB_OPEN_ST}, - /* MSG_DISCOVER_RSP_EVT */ - {AVDT_CCB_CHK_CLOSE, AVDT_CCB_HDL_DISCOVER_RSP, AVDT_CCB_OPEN_ST}, - /* MSG_GETCAP_RSP_EVT */ - {AVDT_CCB_CHK_CLOSE, AVDT_CCB_HDL_GETCAP_RSP, AVDT_CCB_OPEN_ST}, - /* MSG_START_RSP_EVT */ - {AVDT_CCB_HDL_START_RSP, AVDT_CCB_IGNORE, AVDT_CCB_OPEN_ST}, - /* MSG_SUSPEND_RSP_EVT */ - {AVDT_CCB_HDL_SUSPEND_RSP, AVDT_CCB_IGNORE, AVDT_CCB_OPEN_ST}, - /* RCVRSP_EVT */ - {AVDT_CCB_FREE_CMD, AVDT_CCB_SND_CMD, AVDT_CCB_OPEN_ST}, - /* SENDMSG_EVT */ - {AVDT_CCB_SND_MSG, AVDT_CCB_IGNORE, AVDT_CCB_OPEN_ST}, - /* RET_TOUT_EVT */ - {AVDT_CCB_RET_CMD, AVDT_CCB_IGNORE, AVDT_CCB_OPEN_ST}, - /* RSP_TOUT_EVT */ - {AVDT_CCB_CMD_FAIL, AVDT_CCB_SND_CMD, AVDT_CCB_OPEN_ST}, - /* IDLE_TOUT_EVT */ - {AVDT_CCB_CLEAR_CMDS, AVDT_CCB_CHAN_CLOSE, AVDT_CCB_CLOSING_ST}, - /* UL_OPEN_EVT */ - {AVDT_CCB_CHK_TIMER, AVDT_CCB_IGNORE, AVDT_CCB_OPEN_ST}, - /* UL_CLOSE_EVT */ - {AVDT_CCB_CHK_CLOSE, AVDT_CCB_IGNORE, AVDT_CCB_OPEN_ST}, - /* LL_OPEN_EVT */ - {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_OPEN_ST}, - /* LL_CLOSE_EVT */ - {AVDT_CCB_LL_CLOSED, AVDT_CCB_IGNORE, AVDT_CCB_IDLE_ST}, - /* LL_CONG_EVT */ - {AVDT_CCB_CONG_STATE, AVDT_CCB_SND_MSG, AVDT_CCB_OPEN_ST}}; + /* Event */ + /* Action 1 Action 2 Next state */ + /* API_DISCOVER_REQ_EVT */ + {AVDT_CCB_SND_DISCOVER_CMD, AVDT_CCB_SND_CMD, AVDT_CCB_OPEN_ST}, + /* API_GETCAP_REQ_EVT */ + {AVDT_CCB_SND_GETCAP_CMD, AVDT_CCB_SND_CMD, AVDT_CCB_OPEN_ST}, + /* API_START_REQ_EVT */ + {AVDT_CCB_SND_START_CMD, AVDT_CCB_SND_CMD, AVDT_CCB_OPEN_ST}, + /* API_SUSPEND_REQ_EVT */ + {AVDT_CCB_SND_SUSPEND_CMD, AVDT_CCB_SND_CMD, AVDT_CCB_OPEN_ST}, + /* API_DISCOVER_RSP_EVT */ + {AVDT_CCB_SND_DISCOVER_RSP, AVDT_CCB_SND_CMD, AVDT_CCB_OPEN_ST}, + /* API_GETCAP_RSP_EVT */ + {AVDT_CCB_SND_GETCAP_RSP, AVDT_CCB_SND_CMD, AVDT_CCB_OPEN_ST}, + /* API_START_RSP_EVT */ + {AVDT_CCB_SND_START_RSP, AVDT_CCB_SND_CMD, AVDT_CCB_OPEN_ST}, + /* API_SUSPEND_RSP_EVT */ + {AVDT_CCB_SND_SUSPEND_RSP, AVDT_CCB_SND_CMD, AVDT_CCB_OPEN_ST}, + /* API_CONNECT_REQ_EVT */ + {AVDT_CCB_SET_CONN, AVDT_CCB_LL_OPENED, AVDT_CCB_OPEN_ST}, + /* API_DISCONNECT_REQ_EVT */ + {AVDT_CCB_SET_DISCONN, AVDT_CCB_DO_DISCONN, AVDT_CCB_CLOSING_ST}, + /* MSG_DISCOVER_CMD_EVT */ + {AVDT_CCB_HDL_DISCOVER_CMD, AVDT_CCB_IGNORE, AVDT_CCB_OPEN_ST}, + /* MSG_GETCAP_CMD_EVT */ + {AVDT_CCB_HDL_GETCAP_CMD, AVDT_CCB_IGNORE, AVDT_CCB_OPEN_ST}, + /* MSG_START_CMD_EVT */ + {AVDT_CCB_HDL_START_CMD, AVDT_CCB_IGNORE, AVDT_CCB_OPEN_ST}, + /* MSG_SUSPEND_CMD_EVT */ + {AVDT_CCB_HDL_SUSPEND_CMD, AVDT_CCB_IGNORE, AVDT_CCB_OPEN_ST}, + /* MSG_DISCOVER_RSP_EVT */ + {AVDT_CCB_CHK_CLOSE, AVDT_CCB_HDL_DISCOVER_RSP, AVDT_CCB_OPEN_ST}, + /* MSG_GETCAP_RSP_EVT */ + {AVDT_CCB_CHK_CLOSE, AVDT_CCB_HDL_GETCAP_RSP, AVDT_CCB_OPEN_ST}, + /* MSG_START_RSP_EVT */ + {AVDT_CCB_HDL_START_RSP, AVDT_CCB_IGNORE, AVDT_CCB_OPEN_ST}, + /* MSG_SUSPEND_RSP_EVT */ + {AVDT_CCB_HDL_SUSPEND_RSP, AVDT_CCB_IGNORE, AVDT_CCB_OPEN_ST}, + /* RCVRSP_EVT */ + {AVDT_CCB_FREE_CMD, AVDT_CCB_SND_CMD, AVDT_CCB_OPEN_ST}, + /* SENDMSG_EVT */ + {AVDT_CCB_SND_MSG, AVDT_CCB_IGNORE, AVDT_CCB_OPEN_ST}, + /* RET_TOUT_EVT */ + {AVDT_CCB_RET_CMD, AVDT_CCB_IGNORE, AVDT_CCB_OPEN_ST}, + /* RSP_TOUT_EVT */ + {AVDT_CCB_CMD_FAIL, AVDT_CCB_SND_CMD, AVDT_CCB_OPEN_ST}, + /* IDLE_TOUT_EVT */ + {AVDT_CCB_CLEAR_CMDS, AVDT_CCB_CHAN_CLOSE, AVDT_CCB_CLOSING_ST}, + /* UL_OPEN_EVT */ + {AVDT_CCB_CHK_TIMER, AVDT_CCB_IGNORE, AVDT_CCB_OPEN_ST}, + /* UL_CLOSE_EVT */ + {AVDT_CCB_CHK_CLOSE, AVDT_CCB_IGNORE, AVDT_CCB_OPEN_ST}, + /* LL_OPEN_EVT */ + {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_OPEN_ST}, + /* LL_CLOSE_EVT */ + {AVDT_CCB_LL_CLOSED, AVDT_CCB_IGNORE, AVDT_CCB_IDLE_ST}, + /* LL_CONG_EVT */ + {AVDT_CCB_CONG_STATE, AVDT_CCB_SND_MSG, AVDT_CCB_OPEN_ST}}; /* state table for closing state */ const uint8_t avdt_ccb_st_closing[][AVDT_CCB_NUM_COLS] = { - /* Event */ - /* Action 1 Action 2 Next state */ - /* API_DISCOVER_REQ_EVT */ - {AVDT_CCB_SET_RECONN, AVDT_CCB_SND_DISCOVER_CMD, AVDT_CCB_CLOSING_ST}, - /* API_GETCAP_REQ_EVT */ - {AVDT_CCB_SET_RECONN, AVDT_CCB_SND_GETCAP_CMD, AVDT_CCB_CLOSING_ST}, - /* API_START_REQ_EVT */ - {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_CLOSING_ST}, - /* API_SUSPEND_REQ_EVT */ - {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_CLOSING_ST}, - /* API_DISCOVER_RSP_EVT */ - {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_CLOSING_ST}, - /* API_GETCAP_RSP_EVT */ - {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_CLOSING_ST}, - /* API_START_RSP_EVT */ - {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_CLOSING_ST}, - /* API_SUSPEND_RSP_EVT */ - {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_CLOSING_ST}, - /* API_CONNECT_REQ_EVT */ - {AVDT_CCB_SET_RECONN, AVDT_CCB_SET_CONN, AVDT_CCB_CLOSING_ST}, - /* API_DISCONNECT_REQ_EVT */ - {AVDT_CCB_CLR_RECONN, AVDT_CCB_SET_DISCONN, AVDT_CCB_CLOSING_ST}, - /* MSG_DISCOVER_CMD_EVT */ - {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_CLOSING_ST}, - /* MSG_GETCAP_CMD_EVT */ - {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_CLOSING_ST}, - /* MSG_START_CMD_EVT */ - {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_CLOSING_ST}, - /* MSG_SUSPEND_CMD_EVT */ - {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_CLOSING_ST}, - /* MSG_DISCOVER_RSP_EVT */ - {AVDT_CCB_HDL_DISCOVER_RSP, AVDT_CCB_IGNORE, AVDT_CCB_CLOSING_ST}, - /* MSG_GETCAP_RSP_EVT */ - {AVDT_CCB_HDL_GETCAP_RSP, AVDT_CCB_IGNORE, AVDT_CCB_CLOSING_ST}, - /* MSG_START_RSP_EVT */ - {AVDT_CCB_HDL_START_RSP, AVDT_CCB_IGNORE, AVDT_CCB_CLOSING_ST}, - /* MSG_SUSPEND_RSP_EVT */ - {AVDT_CCB_HDL_SUSPEND_RSP, AVDT_CCB_IGNORE, AVDT_CCB_CLOSING_ST}, - /* RCVRSP_EVT */ - {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_CLOSING_ST}, - /* SENDMSG_EVT */ - {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_CLOSING_ST}, - /* RET_TOUT_EVT */ - {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_CLOSING_ST}, - /* RSP_TOUT_EVT */ - {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_CLOSING_ST}, - /* IDLE_TOUT_EVT */ - {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_CLOSING_ST}, - /* UL_OPEN_EVT */ - {AVDT_CCB_SET_RECONN, AVDT_CCB_IGNORE, AVDT_CCB_CLOSING_ST}, - /* UL_CLOSE_EVT */ - {AVDT_CCB_CLR_RECONN, AVDT_CCB_IGNORE, AVDT_CCB_CLOSING_ST}, - /* LL_OPEN_EVT */ - {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_CLOSING_ST}, - /* LL_CLOSE_EVT */ - {AVDT_CCB_CHK_RECONN, AVDT_CCB_IGNORE, AVDT_CCB_IDLE_ST}, - /* LL_CONG_EVT */ - {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_CLOSING_ST}}; + /* Event */ + /* Action 1 Action 2 Next state */ + /* API_DISCOVER_REQ_EVT */ + {AVDT_CCB_SET_RECONN, AVDT_CCB_SND_DISCOVER_CMD, AVDT_CCB_CLOSING_ST}, + /* API_GETCAP_REQ_EVT */ + {AVDT_CCB_SET_RECONN, AVDT_CCB_SND_GETCAP_CMD, AVDT_CCB_CLOSING_ST}, + /* API_START_REQ_EVT */ + {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_CLOSING_ST}, + /* API_SUSPEND_REQ_EVT */ + {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_CLOSING_ST}, + /* API_DISCOVER_RSP_EVT */ + {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_CLOSING_ST}, + /* API_GETCAP_RSP_EVT */ + {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_CLOSING_ST}, + /* API_START_RSP_EVT */ + {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_CLOSING_ST}, + /* API_SUSPEND_RSP_EVT */ + {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_CLOSING_ST}, + /* API_CONNECT_REQ_EVT */ + {AVDT_CCB_SET_RECONN, AVDT_CCB_SET_CONN, AVDT_CCB_CLOSING_ST}, + /* API_DISCONNECT_REQ_EVT */ + {AVDT_CCB_CLR_RECONN, AVDT_CCB_SET_DISCONN, AVDT_CCB_CLOSING_ST}, + /* MSG_DISCOVER_CMD_EVT */ + {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_CLOSING_ST}, + /* MSG_GETCAP_CMD_EVT */ + {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_CLOSING_ST}, + /* MSG_START_CMD_EVT */ + {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_CLOSING_ST}, + /* MSG_SUSPEND_CMD_EVT */ + {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_CLOSING_ST}, + /* MSG_DISCOVER_RSP_EVT */ + {AVDT_CCB_HDL_DISCOVER_RSP, AVDT_CCB_IGNORE, AVDT_CCB_CLOSING_ST}, + /* MSG_GETCAP_RSP_EVT */ + {AVDT_CCB_HDL_GETCAP_RSP, AVDT_CCB_IGNORE, AVDT_CCB_CLOSING_ST}, + /* MSG_START_RSP_EVT */ + {AVDT_CCB_HDL_START_RSP, AVDT_CCB_IGNORE, AVDT_CCB_CLOSING_ST}, + /* MSG_SUSPEND_RSP_EVT */ + {AVDT_CCB_HDL_SUSPEND_RSP, AVDT_CCB_IGNORE, AVDT_CCB_CLOSING_ST}, + /* RCVRSP_EVT */ + {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_CLOSING_ST}, + /* SENDMSG_EVT */ + {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_CLOSING_ST}, + /* RET_TOUT_EVT */ + {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_CLOSING_ST}, + /* RSP_TOUT_EVT */ + {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_CLOSING_ST}, + /* IDLE_TOUT_EVT */ + {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_CLOSING_ST}, + /* UL_OPEN_EVT */ + {AVDT_CCB_SET_RECONN, AVDT_CCB_IGNORE, AVDT_CCB_CLOSING_ST}, + /* UL_CLOSE_EVT */ + {AVDT_CCB_CLR_RECONN, AVDT_CCB_IGNORE, AVDT_CCB_CLOSING_ST}, + /* LL_OPEN_EVT */ + {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_CLOSING_ST}, + /* LL_CLOSE_EVT */ + {AVDT_CCB_CHK_RECONN, AVDT_CCB_IGNORE, AVDT_CCB_IDLE_ST}, + /* LL_CONG_EVT */ + {AVDT_CCB_IGNORE, AVDT_CCB_IGNORE, AVDT_CCB_CLOSING_ST}}; /* type for state table */ typedef const uint8_t (*tAVDT_CCB_ST_TBL)[AVDT_CCB_NUM_COLS]; /* state table */ -const tAVDT_CCB_ST_TBL avdt_ccb_st_tbl[] = { - avdt_ccb_st_idle, avdt_ccb_st_opening, avdt_ccb_st_open, - avdt_ccb_st_closing}; +const tAVDT_CCB_ST_TBL avdt_ccb_st_tbl[] = {avdt_ccb_st_idle, avdt_ccb_st_opening, avdt_ccb_st_open, + avdt_ccb_st_closing}; /******************************************************************************* * @@ -372,8 +364,7 @@ void avdt_ccb_event(AvdtpCcb* p_ccb, uint8_t event, tAVDT_CCB_EVT* p_data) { #if (AVDT_DEBUG == TRUE) log::verbose("CCB ccb={} event={} state={} p_ccb={}", avdt_ccb_to_idx(p_ccb), - avdt_ccb_evt_str[event], avdt_ccb_st_str[p_ccb->state], - fmt::ptr(p_ccb)); + avdt_ccb_evt_str[event], avdt_ccb_st_str[p_ccb->state], fmt::ptr(p_ccb)); #endif /* look up the state table for the current state */ @@ -452,23 +443,20 @@ AvdtpCcb* avdt_ccb_alloc(const RawAddress& bd_addr) { return nullptr; } -AvdtpCcb* avdt_ccb_alloc_by_channel_index(const RawAddress& bd_addr, - uint8_t channel_index) { +AvdtpCcb* avdt_ccb_alloc_by_channel_index(const RawAddress& bd_addr, uint8_t channel_index) { // Allocate the entry for the specified channel index if (channel_index >= AVDT_NUM_LINKS) { - log::error("peer {} invalid channel index {} (max {})", bd_addr, - channel_index, AVDT_NUM_LINKS); + log::error("peer {} invalid channel index {} (max {})", bd_addr, channel_index, AVDT_NUM_LINKS); return nullptr; } AvdtpCcb* p_ccb = &avdtp_cb.ccb[channel_index]; if (p_ccb->allocated) { - log::error("peer {} channel index {} already allocated", bd_addr, - channel_index); + log::error("peer {} channel index {} already allocated", bd_addr, channel_index); return nullptr; } p_ccb->Allocate(bd_addr); - log::verbose("allocated (index {}) peer={} p_ccb={}", channel_index, - p_ccb->peer_addr, fmt::ptr(p_ccb)); + log::verbose("allocated (index {}) peer={} p_ccb={}", channel_index, p_ccb->peer_addr, + fmt::ptr(p_ccb)); return p_ccb; } @@ -494,8 +482,8 @@ void AvdtpCcb::Allocate(const RawAddress& peer_address) { * ******************************************************************************/ void avdt_ccb_dealloc(AvdtpCcb* p_ccb, tAVDT_CCB_EVT* /* p_data */) { - log::verbose("deallocated (index {}) peer={} p_ccb={}", - avdt_ccb_to_idx(p_ccb), p_ccb->peer_addr, fmt::ptr(p_ccb)); + log::verbose("deallocated (index {}) peer={} p_ccb={}", avdt_ccb_to_idx(p_ccb), p_ccb->peer_addr, + fmt::ptr(p_ccb)); p_ccb->ResetCcb(); } diff --git a/system/stack/avdt/avdt_ccb_act.cc b/system/stack/avdt/avdt_ccb_act.cc index deb2156c4b6..df905c1e792 100644 --- a/system/stack/avdt/avdt_ccb_act.cc +++ b/system/stack/avdt/avdt_ccb_act.cc @@ -64,8 +64,9 @@ static void avdt_ccb_clear_ccb(AvdtpCcb* p_ccb) { osi_free_and_reset((void**)&p_ccb->p_rx_msg); /* clear out response queue */ - while ((p_buf = (BT_HDR*)fixed_queue_try_dequeue(p_ccb->rsp_q)) != NULL) + while ((p_buf = (BT_HDR*)fixed_queue_try_dequeue(p_ccb->rsp_q)) != NULL) { osi_free(p_buf); + } } /******************************************************************************* @@ -126,8 +127,7 @@ void avdt_ccb_chk_close(AvdtpCcb* p_ccb, tAVDT_CCB_EVT* /* p_data */) { alarm_cancel(p_ccb->ret_ccb_timer); alarm_cancel(p_ccb->rsp_ccb_timer); uint64_t interval_ms = avdtp_cb.rcb.idle_tout * 1000; - alarm_set_on_mloop(p_ccb->idle_ccb_timer, interval_ms, - avdt_ccb_idle_ccb_timer_timeout, p_ccb); + alarm_set_on_mloop(p_ccb->idle_ccb_timer, interval_ms, avdt_ccb_idle_ccb_timer_timeout, p_ccb); } } @@ -159,10 +159,8 @@ void avdt_ccb_hdl_discover_cmd(AvdtpCcb* p_ccb, tAVDT_CCB_EVT* p_data) { /* copy sep info */ sep_info[p_data->msg.discover_rsp.num_seps].in_use = p_scb->in_use; sep_info[p_data->msg.discover_rsp.num_seps].seid = p_scb->ScbHandle(); - sep_info[p_data->msg.discover_rsp.num_seps].media_type = - p_scb->stream_config.media_type; - sep_info[p_data->msg.discover_rsp.num_seps].tsep = - p_scb->stream_config.tsep; + sep_info[p_data->msg.discover_rsp.num_seps].media_type = p_scb->stream_config.media_type; + sep_info[p_data->msg.discover_rsp.num_seps].tsep = p_scb->stream_config.tsep; p_data->msg.discover_rsp.num_seps++; } @@ -190,8 +188,7 @@ void avdt_ccb_hdl_discover_rsp(AvdtpCcb* p_ccb, tAVDT_CCB_EVT* p_data) { /* call app callback with results */ (*p_ccb->proc_cback)(0, p_ccb->peer_addr, AVDT_DISCOVER_CFM_EVT, - (tAVDT_CTRL*)(&p_data->msg.discover_rsp), - p_ccb->BtaAvScbIndex()); + (tAVDT_CTRL*)(&p_data->msg.discover_rsp), p_ccb->BtaAvScbIndex()); } /******************************************************************************* @@ -241,8 +238,7 @@ void avdt_ccb_hdl_getcap_rsp(AvdtpCcb* p_ccb, tAVDT_CCB_EVT* p_data) { p_ccb->proc_busy = false; /* call app callback with results */ - (*p_ccb->proc_cback)(0, p_ccb->peer_addr, AVDT_GETCAP_CFM_EVT, - (tAVDT_CTRL*)(&p_data->msg.svccap), + (*p_ccb->proc_cback)(0, p_ccb->peer_addr, AVDT_GETCAP_CFM_EVT, (tAVDT_CTRL*)(&p_data->msg.svccap), p_ccb->BtaAvScbIndex()); } @@ -263,9 +259,8 @@ void avdt_ccb_hdl_start_cmd(AvdtpCcb* p_ccb, tAVDT_CCB_EVT* p_data) { uint8_t err_code = 0; /* verify all streams in the right state */ - uint8_t seid = - avdt_scb_verify(p_ccb, AVDT_VERIFY_START, p_data->msg.multi.seid_list, - p_data->msg.multi.num_seps, &err_code); + uint8_t seid = avdt_scb_verify(p_ccb, AVDT_VERIFY_START, p_data->msg.multi.seid_list, + p_data->msg.multi.num_seps, &err_code); if (seid == 0 && err_code == 0) { /* we're ok, send response */ avdt_ccb_event(p_ccb, AVDT_CCB_API_START_RSP_EVT, p_data); @@ -297,8 +292,7 @@ void avdt_ccb_hdl_start_rsp(AvdtpCcb* p_ccb, tAVDT_CCB_EVT* p_data) { AvdtpScb* p_scb; /* determine rsp or rej event */ - event = (p_data->msg.hdr.err_code == 0) ? AVDT_SCB_MSG_START_RSP_EVT - : AVDT_SCB_MSG_START_REJ_EVT; + event = (p_data->msg.hdr.err_code == 0) ? AVDT_SCB_MSG_START_RSP_EVT : AVDT_SCB_MSG_START_REJ_EVT; /* get to where seid's are stashed in current cmd */ p = (uint8_t*)(p_ccb->p_curr_cmd + 1); @@ -331,8 +325,7 @@ void avdt_ccb_hdl_suspend_cmd(AvdtpCcb* p_ccb, tAVDT_CCB_EVT* p_data) { uint8_t err_code = 0; /* verify all streams in the right state */ - if ((seid = avdt_scb_verify(p_ccb, AVDT_VERIFY_SUSPEND, - p_data->msg.multi.seid_list, + if ((seid = avdt_scb_verify(p_ccb, AVDT_VERIFY_SUSPEND, p_data->msg.multi.seid_list, p_data->msg.multi.num_seps, &err_code)) == 0 && err_code == 0) { /* we're ok, send response */ @@ -449,8 +442,9 @@ void avdt_ccb_snd_getcap_cmd(AvdtpCcb* p_ccb, tAVDT_CCB_EVT* p_data) { p_ccb->proc_busy = true; /* build and queue discover req */ - if (p_data->msg.hdr.sig_id == AVDT_SIG_GET_ALLCAP) + if (p_data->msg.hdr.sig_id == AVDT_SIG_GET_ALLCAP) { sig_id = AVDT_SIG_GET_ALLCAP; + } avdt_msg_send_cmd(p_ccb, NULL, sig_id, (tAVDT_MSG*)&p_data->getcap.single); } @@ -470,8 +464,9 @@ void avdt_ccb_snd_getcap_cmd(AvdtpCcb* p_ccb, tAVDT_CCB_EVT* p_data) { void avdt_ccb_snd_getcap_rsp(AvdtpCcb* p_ccb, tAVDT_CCB_EVT* p_data) { uint8_t sig_id = AVDT_SIG_GETCAP; - if (p_data->msg.hdr.sig_id == AVDT_SIG_GET_ALLCAP) + if (p_data->msg.hdr.sig_id == AVDT_SIG_GET_ALLCAP) { sig_id = AVDT_SIG_GET_ALLCAP; + } /* send response */ avdt_msg_send_rsp(p_ccb, sig_id, &p_data->msg); @@ -502,9 +497,8 @@ void avdt_ccb_snd_start_cmd(AvdtpCcb* p_ccb, tAVDT_CCB_EVT* p_data) { memcpy(seid_list, p_data->msg.multi.seid_list, p_data->msg.multi.num_seps); /* verify all streams in the right state */ - avdt_msg.hdr.err_param = - avdt_scb_verify(p_ccb, AVDT_VERIFY_OPEN, p_data->msg.multi.seid_list, - p_data->msg.multi.num_seps, &avdt_msg.hdr.err_code); + avdt_msg.hdr.err_param = avdt_scb_verify(p_ccb, AVDT_VERIFY_OPEN, p_data->msg.multi.seid_list, + p_data->msg.multi.num_seps, &avdt_msg.hdr.err_code); if (avdt_msg.hdr.err_param == 0) { log::verbose("AVDT_SIG_START"); @@ -581,8 +575,8 @@ void avdt_ccb_snd_suspend_cmd(AvdtpCcb* p_ccb, tAVDT_CCB_EVT* p_data) { /* verify all streams in the right state */ avdt_msg.hdr.err_param = - avdt_scb_verify(p_ccb, AVDT_VERIFY_STREAMING, p_data->msg.multi.seid_list, - p_data->msg.multi.num_seps, &avdt_msg.hdr.err_code); + avdt_scb_verify(p_ccb, AVDT_VERIFY_STREAMING, p_data->msg.multi.seid_list, + p_data->msg.multi.num_seps, &avdt_msg.hdr.err_code); if (avdt_msg.hdr.err_param == 0) { /* set peer seid list in messsage */ avdt_scb_peer_seid_list(&p_data->msg.multi); @@ -746,9 +740,7 @@ void avdt_ccb_free_cmd(AvdtpCcb* p_ccb, tAVDT_CCB_EVT* /* p_data */) { * Returns void. * ******************************************************************************/ -void avdt_ccb_cong_state(AvdtpCcb* p_ccb, tAVDT_CCB_EVT* p_data) { - p_ccb->cong = p_data->llcong; -} +void avdt_ccb_cong_state(AvdtpCcb* p_ccb, tAVDT_CCB_EVT* p_data) { p_ccb->cong = p_data->llcong; } /******************************************************************************* * @@ -776,13 +768,11 @@ void avdt_ccb_ret_cmd(AvdtpCcb* p_ccb, tAVDT_CCB_EVT* p_data) { avdt_ccb_snd_cmd(p_ccb, p_data); } else { /* if command pending and we're not congested and not sending a fragment */ - if ((!p_ccb->cong) && (p_ccb->p_curr_msg == NULL) && - (p_ccb->p_curr_cmd != NULL)) { + if ((!p_ccb->cong) && (p_ccb->p_curr_msg == NULL) && (p_ccb->p_curr_cmd != NULL)) { /* make copy of message in p_curr_cmd and send it */ BT_HDR* p_msg = (BT_HDR*)osi_malloc(AVDT_CMD_BUF_SIZE); memcpy(p_msg, p_ccb->p_curr_cmd, - (sizeof(BT_HDR) + p_ccb->p_curr_cmd->offset + - p_ccb->p_curr_cmd->len)); + (sizeof(BT_HDR) + p_ccb->p_curr_cmd->offset + p_ccb->p_curr_cmd->len)); avdt_msg_send(p_ccb, p_msg); } @@ -790,8 +780,7 @@ void avdt_ccb_ret_cmd(AvdtpCcb* p_ccb, tAVDT_CCB_EVT* p_data) { alarm_cancel(p_ccb->idle_ccb_timer); alarm_cancel(p_ccb->rsp_ccb_timer); uint64_t interval_ms = avdtp_cb.rcb.ret_tout * 1000; - alarm_set_on_mloop(p_ccb->ret_ccb_timer, interval_ms, - avdt_ccb_ret_ccb_timer_timeout, p_ccb); + alarm_set_on_mloop(p_ccb->ret_ccb_timer, interval_ms, avdt_ccb_ret_ccb_timer_timeout, p_ccb); } } @@ -812,14 +801,12 @@ void avdt_ccb_snd_cmd(AvdtpCcb* p_ccb, tAVDT_CCB_EVT* /* p_data */) { /* do we have commands to send? send next command; make sure we're clear; ** not congested, not sending fragment, not waiting for response */ - if ((!p_ccb->cong) && (p_ccb->p_curr_msg == NULL) && - (p_ccb->p_curr_cmd == NULL)) { + if ((!p_ccb->cong) && (p_ccb->p_curr_msg == NULL) && (p_ccb->p_curr_cmd == NULL)) { p_msg = (BT_HDR*)fixed_queue_try_dequeue(p_ccb->cmd_q); if (p_msg != NULL) { /* make a copy of buffer in p_curr_cmd */ p_ccb->p_curr_cmd = (BT_HDR*)osi_malloc(AVDT_CMD_BUF_SIZE); - memcpy(p_ccb->p_curr_cmd, p_msg, - (sizeof(BT_HDR) + p_msg->offset + p_msg->len)); + memcpy(p_ccb->p_curr_cmd, p_msg, (sizeof(BT_HDR) + p_msg->offset + p_msg->len)); avdt_msg_send(p_ccb, p_msg); } } @@ -871,9 +858,7 @@ void avdt_ccb_snd_msg(AvdtpCcb* p_ccb, tAVDT_CCB_EVT* /* p_data */) { * Returns void. * ******************************************************************************/ -void avdt_ccb_set_reconn(AvdtpCcb* p_ccb, tAVDT_CCB_EVT* /* p_data */) { - p_ccb->reconn = true; -} +void avdt_ccb_set_reconn(AvdtpCcb* p_ccb, tAVDT_CCB_EVT* /* p_data */) { p_ccb->reconn = true; } /******************************************************************************* * @@ -885,9 +870,7 @@ void avdt_ccb_set_reconn(AvdtpCcb* p_ccb, tAVDT_CCB_EVT* /* p_data */) { * Returns void. * ******************************************************************************/ -void avdt_ccb_clr_reconn(AvdtpCcb* p_ccb, tAVDT_CCB_EVT* /* p_data */) { - p_ccb->reconn = false; -} +void avdt_ccb_clr_reconn(AvdtpCcb* p_ccb, tAVDT_CCB_EVT* /* p_data */) { p_ccb->reconn = false; } /******************************************************************************* * @@ -967,8 +950,9 @@ void avdt_ccb_set_disconn(AvdtpCcb* p_ccb, tAVDT_CCB_EVT* p_data) { p_ccb->p_conn_cback, p_data->disconnect.p_cback); */ /* save callback */ - if (p_data->disconnect.p_cback) + if (p_data->disconnect.p_cback) { p_ccb->p_conn_cback = p_data->disconnect.p_cback; + } } /******************************************************************************* @@ -1010,7 +994,9 @@ void avdt_ccb_ll_closed(AvdtpCcb* p_ccb, tAVDT_CCB_EVT* /* p_data */) { /* save callback pointer, bd addr */ p_cback = p_ccb->p_conn_cback; - if (!p_cback) p_cback = avdtp_cb.p_conn_cback; + if (!p_cback) { + p_cback = avdtp_cb.p_conn_cback; + } RawAddress bd_addr = p_ccb->peer_addr; uint8_t bta_av_scb_index = p_ccb->BtaAvScbIndex(); @@ -1020,8 +1006,7 @@ void avdt_ccb_ll_closed(AvdtpCcb* p_ccb, tAVDT_CCB_EVT* /* p_data */) { /* call callback */ if (p_cback) { avdt_ctrl.hdr.err_code = 0; - (*p_cback)(0, bd_addr, AVDT_DISCONNECT_IND_EVT, &avdt_ctrl, - bta_av_scb_index); + (*p_cback)(0, bd_addr, AVDT_DISCONNECT_IND_EVT, &avdt_ctrl, bta_av_scb_index); } } @@ -1038,17 +1023,19 @@ void avdt_ccb_ll_closed(AvdtpCcb* p_ccb, tAVDT_CCB_EVT* /* p_data */) { void avdt_ccb_ll_opened(AvdtpCcb* p_ccb, tAVDT_CCB_EVT* p_data) { tAVDT_CTRL avdt_ctrl; - log::verbose("peer {} BtaAvScbIndex={} p_ccb={}", p_ccb->peer_addr, - p_ccb->BtaAvScbIndex(), fmt::ptr(p_ccb)); + log::verbose("peer {} BtaAvScbIndex={} p_ccb={}", p_ccb->peer_addr, p_ccb->BtaAvScbIndex(), + fmt::ptr(p_ccb)); p_ccb->ll_opened = true; - if (!p_ccb->p_conn_cback) p_ccb->p_conn_cback = avdtp_cb.p_conn_cback; + if (!p_ccb->p_conn_cback) { + p_ccb->p_conn_cback = avdtp_cb.p_conn_cback; + } /* call callback */ if (p_ccb->p_conn_cback) { avdt_ctrl.hdr.err_code = 0; avdt_ctrl.hdr.err_param = p_data->msg.hdr.err_param; - (*p_ccb->p_conn_cback)(0, p_ccb->peer_addr, AVDT_CONNECT_IND_EVT, - &avdt_ctrl, p_ccb->BtaAvScbIndex()); + (*p_ccb->p_conn_cback)(0, p_ccb->peer_addr, AVDT_CONNECT_IND_EVT, &avdt_ctrl, + p_ccb->BtaAvScbIndex()); } } diff --git a/system/stack/avdt/avdt_int.h b/system/stack/avdt/avdt_int.h index 3bc2e777529..86310e8809c 100644 --- a/system/stack/avdt/avdt_int.h +++ b/system/stack/avdt/avdt_int.h @@ -46,8 +46,8 @@ /* channel types */ enum { - AVDT_CHAN_SIG, /* signaling channel */ - AVDT_CHAN_MEDIA, /* media channel */ + AVDT_CHAN_SIG, /* signaling channel */ + AVDT_CHAN_MEDIA, /* media channel */ AVDT_CHAN_REPORT, /* reporting channel */ AVDT_CHAN_NUM_TYPES }; @@ -78,7 +78,7 @@ enum { * | BT_HDR | SCB handles | L2CAP + HCI header | AVDTP header | data ... | * * Note that we "hide" the scb handles at the top of the message buffer. -*/ + */ #define AVDT_MSG_OFFSET (L2CAP_MIN_OFFSET + AVDT_NUM_SEPS + AVDT_LEN_TYPE_START) /* scb transport channel connect timeout value (in milliseconds) */ @@ -93,12 +93,7 @@ enum { #endif /* ccb state machine states */ -enum { - AVDT_CCB_IDLE_ST, - AVDT_CCB_OPENING_ST, - AVDT_CCB_OPEN_ST, - AVDT_CCB_CLOSING_ST -}; +enum { AVDT_CCB_IDLE_ST, AVDT_CCB_OPENING_ST, AVDT_CCB_OPEN_ST, AVDT_CCB_CLOSING_ST }; /* state machine action enumeration list */ enum : uint8_t { @@ -177,7 +172,7 @@ enum { /* scb state machine states; these state values are private to this module so * the scb state cannot be read or set by actions functions -*/ + */ enum { AVDT_SCB_IDLE_ST, AVDT_SCB_CONF_ST, @@ -365,7 +360,9 @@ typedef struct { } tAVDT_CCB_API_CONNECT; /* data type for AVDT_CCB_API_DISCONNECT_REQ_EVT */ -typedef struct { tAVDT_CTRL_CBACK* p_cback; } tAVDT_CCB_API_DISCONNECT; +typedef struct { + tAVDT_CTRL_CBACK* p_cback; +} tAVDT_CCB_API_DISCONNECT; /* union associated with ccb state machine events */ typedef union { @@ -410,7 +407,7 @@ class AvdtpCcb; * AVDTP Stream Control Block. */ class AvdtpScb { - public: +public: AvdtpScb() : transport_channel_timer(nullptr), p_pkt(nullptr), @@ -434,8 +431,7 @@ class AvdtpScb { * @param p_avdtp_ccb the AvdtCcb entry to use * @param avdtp_stream_config the stream config to use */ - void Allocate(AvdtpCcb* p_avdtp_ccb, - const AvdtpStreamConfig& avdtp_stream_config); + void Allocate(AvdtpCcb* p_avdtp_ccb, const AvdtpStreamConfig& avdtp_stream_config); /** * Recycle the entry by resetting it, mark it as allocated and keeping @@ -491,16 +487,16 @@ class AvdtpScb { uint16_t media_seq; // Media packet sequence number bool allocated; // True if the SCB is allocated bool in_use; // True if used by peer - uint8_t role; // Initiator/acceptor role in current procedure - bool remove; // True if the SCB is marked for removal - uint8_t state; // State machine state - uint8_t peer_seid; // SEID of peer stream - uint8_t curr_evt; // current event; set only by the state machine - bool cong; // True if the media transport channel is congested - uint8_t close_code; // Error code received in close response - bool curr_stream; // True if the SCB is the current stream, False otherwise - - private: + uint8_t role; // Initiator/acceptor role in current procedure + bool remove; // True if the SCB is marked for removal + uint8_t state; // State machine state + uint8_t peer_seid; // SEID of peer stream + uint8_t curr_evt; // current event; set only by the state machine + bool cong; // True if the media transport channel is congested + uint8_t close_code; // Error code received in close response + bool curr_stream; // True if the SCB is the current stream, False otherwise + +private: uint8_t scb_handle_; // Unique handle for this AvdtpScb entry }; @@ -508,7 +504,7 @@ class AvdtpScb { * AVDTP Channel Control Block. */ class AvdtpCcb { - public: +public: AvdtpCcb() : peer_addr(RawAddress::kEmpty), scb{}, @@ -606,31 +602,31 @@ class AvdtpCcb { * NOTE: idle_ccb_timer, ret_ccb_timer and rsp_ccb_timer are mutually * exclusive - no more than one timer should be running at the same time. */ - alarm_t* idle_ccb_timer; // Idle CCB timer entry - alarm_t* ret_ccb_timer; // Ret CCB timer entry - alarm_t* rsp_ccb_timer; // Rsp CCB timer entry - fixed_queue_t* cmd_q; // Queue for outgoing command messages - fixed_queue_t* rsp_q; // Queue for outgoing response and reject messages + alarm_t* idle_ccb_timer; // Idle CCB timer entry + alarm_t* ret_ccb_timer; // Ret CCB timer entry + alarm_t* rsp_ccb_timer; // Rsp CCB timer entry + fixed_queue_t* cmd_q; // Queue for outgoing command messages + fixed_queue_t* rsp_q; // Queue for outgoing response and reject messages tAVDT_CTRL_CBACK* proc_cback; // Procedure callback function tAVDT_CTRL_CBACK* p_conn_cback; // Connection/disconnection callback function void* p_proc_data; // Pointer to data storage for procedure - BT_HDR* p_curr_cmd; // Current command being sent awaiting response - BT_HDR* p_curr_msg; // Current message being sent - BT_HDR* p_rx_msg; // Current message being received - bool allocated; // Whether ccb is allocated - uint8_t state; // The CCB state machine state - bool ll_opened; // True if LL is opened - bool proc_busy; // True when a discover or get capabilities procedure in - // progress - uint8_t proc_param; // Procedure parameter; either SEID for get capabilities - // or number of SEPS for discover - bool cong; // True if the signaling channel is congested - uint8_t label; // Message header "label" (sequence number) - bool reconn; // If true, reinitiate connection after transitioning from - // CLOSING to IDLE state - uint8_t ret_count; // Command retransmission count - - private: + BT_HDR* p_curr_cmd; // Current command being sent awaiting response + BT_HDR* p_curr_msg; // Current message being sent + BT_HDR* p_rx_msg; // Current message being received + bool allocated; // Whether ccb is allocated + uint8_t state; // The CCB state machine state + bool ll_opened; // True if LL is opened + bool proc_busy; // True when a discover or get capabilities procedure in + // progress + uint8_t proc_param; // Procedure parameter; either SEID for get capabilities + // or number of SEPS for discover + bool cong; // True if the signaling channel is congested + uint8_t label; // Message header "label" (sequence number) + bool reconn; // If true, reinitiate connection after transitioning from + // CLOSING to IDLE state + uint8_t ret_count; // Command retransmission count + +private: // The corresponding BTA AV stream control block index for this entry uint8_t bta_av_scb_index_; }; @@ -640,15 +636,9 @@ class AvdtpCcb { * Used in the transport channel table in the adaptation layer. */ class AvdtpTransportChannel { - public: +public: AvdtpTransportChannel() - : peer_mtu(0), - my_mtu(0), - lcid(0), - tcid(0), - ccb_idx(0), - state(0), - cfg_flags(0) {} + : peer_mtu(0), my_mtu(0), lcid(0), tcid(0), ccb_idx(0), state(0), cfg_flags(0) {} void Reset() { peer_mtu = 0; @@ -660,8 +650,8 @@ class AvdtpTransportChannel { cfg_flags = 0; } - uint16_t peer_mtu; // L2CAP MTU of the peer device - uint16_t my_mtu; // Our MTU for this channel + uint16_t peer_mtu; // L2CAP MTU of the peer device + uint16_t my_mtu; // Our MTU for this channel uint16_t lcid; uint8_t tcid; // Transport channel ID uint8_t ccb_idx; // Channel control block for with this transport channel @@ -674,7 +664,7 @@ class AvdtpTransportChannel { * Used in the routing table in the adaption layer. */ class AvdtpRoutingEntry { - public: +public: AvdtpRoutingEntry() : lcid(0), scb_hdl(0) {} void Reset() { @@ -690,7 +680,7 @@ class AvdtpRoutingEntry { * AVDTP adaption layer control block. */ class AvdtpAdaptationLayer { - public: +public: AvdtpAdaptationLayer() {} void Reset() { @@ -730,12 +720,9 @@ typedef void (*tAVDT_SCB_ACTION)(AvdtpScb* p_scb, tAVDT_SCB_EVT* p_data); * Control block for AVDTP. */ class AvdtpCb { - public: +public: AvdtpCb() - : p_conf_cback(nullptr), - p_ccb_act(nullptr), - p_scb_act(nullptr), - p_conn_cback(nullptr) {} + : p_conf_cback(nullptr), p_ccb_act(nullptr), p_scb_act(nullptr), p_conn_cback(nullptr) {} void Reset() { rcb.Reset(); @@ -789,8 +776,7 @@ void avdt_ccb_init(void); void avdt_ccb_event(AvdtpCcb* p_ccb, uint8_t event, tAVDT_CCB_EVT* p_data); AvdtpCcb* avdt_ccb_by_bd(const RawAddress& bd_addr); AvdtpCcb* avdt_ccb_alloc(const RawAddress& bd_addr); -AvdtpCcb* avdt_ccb_alloc_by_channel_index(const RawAddress& bd_addr, - uint8_t channel_index); +AvdtpCcb* avdt_ccb_alloc_by_channel_index(const RawAddress& bd_addr, uint8_t channel_index); void avdt_ccb_dealloc(AvdtpCcb* p_ccb, tAVDT_CCB_EVT* p_data); uint8_t avdt_ccb_to_idx(AvdtpCcb* p_ccb); AvdtpCcb* avdt_ccb_by_idx(uint8_t idx); @@ -835,13 +821,12 @@ void avdt_ccb_ll_opened(AvdtpCcb* p_ccb, tAVDT_CCB_EVT* p_data); /* SCB function prototypes */ void avdt_scb_event(AvdtpScb* p_scb, uint8_t event, tAVDT_SCB_EVT* p_data); void avdt_scb_init(void); -AvdtpScb* avdt_scb_alloc(uint8_t peer_id, - const AvdtpStreamConfig& avdtp_stream_config); +AvdtpScb* avdt_scb_alloc(uint8_t peer_id, const AvdtpStreamConfig& avdtp_stream_config); void avdt_scb_dealloc(AvdtpScb* p_scb, tAVDT_SCB_EVT* p_data); uint8_t avdt_scb_to_hdl(AvdtpScb* p_scb); AvdtpScb* avdt_scb_by_hdl(uint8_t hdl); -uint8_t avdt_scb_verify(AvdtpCcb* p_ccb, uint8_t state, uint8_t* p_seid, - uint16_t num_seid, uint8_t* p_err_code); +uint8_t avdt_scb_verify(AvdtpCcb* p_ccb, uint8_t state, uint8_t* p_seid, uint16_t num_seid, + uint8_t* p_err_code); void avdt_scb_peer_seid_list(tAVDT_MULTI* p_multi); uint32_t avdt_scb_gen_ssrc(AvdtpScb* p_scb); @@ -908,8 +893,7 @@ void avdt_scb_clr_vars(AvdtpScb* p_scb, tAVDT_SCB_EVT* p_data); /* msg function declarations */ bool avdt_msg_send(AvdtpCcb* p_ccb, BT_HDR* p_msg); -void avdt_msg_send_cmd(AvdtpCcb* p_ccb, void* p_scb, uint8_t sig_id, - tAVDT_MSG* p_params); +void avdt_msg_send_cmd(AvdtpCcb* p_ccb, void* p_scb, uint8_t sig_id, tAVDT_MSG* p_params); void avdt_msg_send_rsp(AvdtpCcb* p_ccb, uint8_t sig_id, tAVDT_MSG* p_params); void avdt_msg_send_rej(AvdtpCcb* p_ccb, uint8_t sig_id, tAVDT_MSG* p_params); void avdt_msg_send_grej(AvdtpCcb* p_ccb, uint8_t sig_id, tAVDT_MSG* p_params); @@ -918,8 +902,7 @@ void avdt_msg_ind(AvdtpCcb* p_ccb, BT_HDR* p_buf); /* adaption layer function declarations */ void avdt_ad_init(void); uint8_t avdt_ad_type_to_tcid(uint8_t type, AvdtpScb* p_scb); -AvdtpTransportChannel* avdt_ad_tc_tbl_by_st(uint8_t type, AvdtpCcb* p_ccb, - uint8_t state); +AvdtpTransportChannel* avdt_ad_tc_tbl_by_st(uint8_t type, AvdtpCcb* p_ccb, uint8_t state); AvdtpTransportChannel* avdt_ad_tc_tbl_by_lcid(uint16_t lcid); AvdtpTransportChannel* avdt_ad_tc_tbl_alloc(AvdtpCcb* p_ccb); uint8_t avdt_ad_tc_tbl_to_idx(AvdtpTransportChannel* p_tbl); @@ -927,12 +910,9 @@ void avdt_ad_tc_close_ind(AvdtpTransportChannel* p_tbl); void avdt_ad_tc_open_ind(AvdtpTransportChannel* p_tbl); void avdt_ad_tc_cong_ind(AvdtpTransportChannel* p_tbl, bool is_congested); void avdt_ad_tc_data_ind(AvdtpTransportChannel* p_tbl, BT_HDR* p_buf); -AvdtpTransportChannel* avdt_ad_tc_tbl_by_type(uint8_t type, AvdtpCcb* p_ccb, - AvdtpScb* p_scb); -tL2CAP_DW_RESULT avdt_ad_write_req(uint8_t type, AvdtpCcb* p_ccb, - AvdtpScb* p_scb, BT_HDR* p_buf); -void avdt_ad_open_req(uint8_t type, AvdtpCcb* p_ccb, AvdtpScb* p_scb, - uint8_t role); +AvdtpTransportChannel* avdt_ad_tc_tbl_by_type(uint8_t type, AvdtpCcb* p_ccb, AvdtpScb* p_scb); +tL2CAP_DW_RESULT avdt_ad_write_req(uint8_t type, AvdtpCcb* p_ccb, AvdtpScb* p_scb, BT_HDR* p_buf); +void avdt_ad_open_req(uint8_t type, AvdtpCcb* p_ccb, AvdtpScb* p_scb, uint8_t role); void avdt_ad_close_req(uint8_t type, AvdtpCcb* p_ccb, AvdtpScb* p_scb); void avdt_ccb_idle_ccb_timer_timeout(void* data); @@ -946,12 +926,12 @@ void avdt_scb_transport_channel_timer_timeout(void* data); /* we store the scb and the label in the layer_specific field of the * current cmd -*/ + */ #define AVDT_BLD_LAYERSPEC(ls, msg, label) ls = (((label) << 4) | (msg)) #define AVDT_LAYERSPEC_LABEL(ls) ((uint8_t)((ls) >> 4)) -#define AVDT_LAYERSPEC_MSG(ls) ((uint8_t)((ls)&0x000F)) +#define AVDT_LAYERSPEC_MSG(ls) ((uint8_t)((ls) & 0x000F)) /***************************************************************************** * global data diff --git a/system/stack/avdt/avdt_l2c.cc b/system/stack/avdt/avdt_l2c.cc index b582948f974..f4e233477dd 100644 --- a/system/stack/avdt/avdt_l2c.cc +++ b/system/stack/avdt/avdt_l2c.cc @@ -40,11 +40,9 @@ using namespace bluetooth; /* callback function declarations */ -void avdt_l2c_connect_ind_cback(const RawAddress& bd_addr, uint16_t lcid, - uint16_t psm, uint8_t id); +void avdt_l2c_connect_ind_cback(const RawAddress& bd_addr, uint16_t lcid, uint16_t psm, uint8_t id); void avdt_l2c_connect_cfm_cback(uint16_t lcid, uint16_t result); -void avdt_l2c_config_cfm_cback(uint16_t lcid, uint16_t result, - tL2CAP_CFG_INFO* p_cfg); +void avdt_l2c_config_cfm_cback(uint16_t lcid, uint16_t result, tL2CAP_CFG_INFO* p_cfg); void avdt_l2c_config_ind_cback(uint16_t lcid, tL2CAP_CFG_INFO* p_cfg); void avdt_l2c_disconnect_ind_cback(uint16_t lcid, bool ack_needed); void avdt_l2c_congestion_ind_cback(uint16_t lcid, bool is_congested); @@ -77,8 +75,7 @@ const tL2CAP_APPL_INFO avdt_l2c_appl = {avdt_l2c_connect_ind_cback, * Returns void * ******************************************************************************/ -static void avdt_sec_check_complete_term(const RawAddress* bd_addr, - tBT_TRANSPORT transport, +static void avdt_sec_check_complete_term(const RawAddress* bd_addr, tBT_TRANSPORT transport, void* p_ref_data) { AvdtpCcb* p_ccb = NULL; AvdtpTransportChannel* p_tbl; @@ -86,7 +83,9 @@ static void avdt_sec_check_complete_term(const RawAddress* bd_addr, p_ccb = avdt_ccb_by_bd(*bd_addr); p_tbl = avdt_ad_tc_tbl_by_st(AVDT_CHAN_SIG, p_ccb, AVDT_AD_ST_SEC_ACP); - if (p_tbl == NULL) return; + if (p_tbl == NULL) { + return; + } /* store idx in LCID table, store LCID in routing table */ avdtp_cb.ad.lcid_tbl[p_tbl->lcid] = avdt_ad_tc_tbl_to_idx(p_tbl); @@ -106,16 +105,19 @@ static void avdt_sec_check_complete_term(const RawAddress* bd_addr, * Returns void * ******************************************************************************/ -static void avdt_sec_check_complete_orig(const RawAddress* bd_addr, - tBT_TRANSPORT trasnport, +static void avdt_sec_check_complete_orig(const RawAddress* bd_addr, tBT_TRANSPORT transport, void* /* p_ref_data */, uint8_t res) { AvdtpCcb* p_ccb = NULL; AvdtpTransportChannel* p_tbl; log::verbose("avdt_sec_check_complete_orig res: {}", res); - if (bd_addr) p_ccb = avdt_ccb_by_bd(*bd_addr); + if (bd_addr) { + p_ccb = avdt_ccb_by_bd(*bd_addr); + } p_tbl = avdt_ad_tc_tbl_by_st(AVDT_CHAN_SIG, p_ccb, AVDT_AD_ST_SEC_INT); - if (p_tbl == NULL) return; + if (p_tbl == NULL) { + return; + } if (res == BTM_SUCCESS) { /* set channel state */ @@ -135,8 +137,8 @@ static void avdt_sec_check_complete_orig(const RawAddress* bd_addr, * Returns void * ******************************************************************************/ -void avdt_l2c_connect_ind_cback(const RawAddress& bd_addr, uint16_t lcid, - uint16_t /* psm */, uint8_t id) { +void avdt_l2c_connect_ind_cback(const RawAddress& bd_addr, uint16_t lcid, uint16_t /* psm */, + uint8_t id) { AvdtpCcb* p_ccb; AvdtpTransportChannel* p_tbl = NULL; uint16_t result; @@ -167,13 +169,11 @@ void avdt_l2c_connect_ind_cback(const RawAddress& bd_addr, uint16_t lcid, if (interop_match_addr(INTEROP_2MBPS_LINK_ONLY, &bd_addr)) { // Disable 3DH packets for AVDT ACL to improve sensitivity on HS btm_set_packet_types_from_address( - bd_addr, - (acl_get_supported_packet_types() | HCI_PKT_TYPES_MASK_NO_3_DH1 | - HCI_PKT_TYPES_MASK_NO_3_DH3 | HCI_PKT_TYPES_MASK_NO_3_DH5)); + bd_addr, (acl_get_supported_packet_types() | HCI_PKT_TYPES_MASK_NO_3_DH1 | + HCI_PKT_TYPES_MASK_NO_3_DH3 | HCI_PKT_TYPES_MASK_NO_3_DH5)); } /* Assume security check is complete */ - avdt_sec_check_complete_term(&p_ccb->peer_addr, BT_TRANSPORT_BR_EDR, - nullptr); + avdt_sec_check_complete_term(&p_ccb->peer_addr, BT_TRANSPORT_BR_EDR, nullptr); return; } } else { @@ -223,9 +223,7 @@ void avdt_l2c_connect_ind_cback(const RawAddress& bd_addr, uint16_t lcid, p_tbl->state = AVDT_AD_ST_CFG; } -static void avdt_on_l2cap_error(uint16_t lcid, uint16_t result) { - avdt_l2c_disconnect(lcid); -} +static void avdt_on_l2cap_error(uint16_t lcid, uint16_t result) { avdt_l2c_disconnect(lcid); } /******************************************************************************* * @@ -262,19 +260,17 @@ void avdt_l2c_connect_cfm_cback(uint16_t lcid, uint16_t result) { p_tbl->lcid = lcid; p_tbl->cfg_flags = AVDT_L2C_CFG_CONN_INT; - if (interop_match_addr(INTEROP_2MBPS_LINK_ONLY, - (const RawAddress*)&p_ccb->peer_addr)) { + if (interop_match_addr(INTEROP_2MBPS_LINK_ONLY, (const RawAddress*)&p_ccb->peer_addr)) { // Disable 3DH packets for AVDT ACL to improve sensitivity on HS btm_set_packet_types_from_address( - p_ccb->peer_addr, - (acl_get_supported_packet_types() | - HCI_PKT_TYPES_MASK_NO_3_DH1 | HCI_PKT_TYPES_MASK_NO_3_DH3 | - HCI_PKT_TYPES_MASK_NO_3_DH5)); + p_ccb->peer_addr, + (acl_get_supported_packet_types() | HCI_PKT_TYPES_MASK_NO_3_DH1 | + HCI_PKT_TYPES_MASK_NO_3_DH3 | HCI_PKT_TYPES_MASK_NO_3_DH5)); } /* Assume security check is complete */ - avdt_sec_check_complete_orig(&p_ccb->peer_addr, BT_TRANSPORT_BR_EDR, - nullptr, BTM_SUCCESS); + avdt_sec_check_complete_orig(&p_ccb->peer_addr, BT_TRANSPORT_BR_EDR, nullptr, + BTM_SUCCESS); } } } @@ -297,8 +293,7 @@ void avdt_l2c_connect_cfm_cback(uint16_t lcid, uint16_t result) { * Returns void * ******************************************************************************/ -void avdt_l2c_config_cfm_cback(uint16_t lcid, uint16_t initiator, - tL2CAP_CFG_INFO* p_cfg) { +void avdt_l2c_config_cfm_cback(uint16_t lcid, uint16_t initiator, tL2CAP_CFG_INFO* p_cfg) { avdt_l2c_config_ind_cback(lcid, p_cfg); AvdtpTransportChannel* p_tbl; @@ -358,8 +353,7 @@ void avdt_l2c_config_ind_cback(uint16_t lcid, tL2CAP_CFG_INFO* p_cfg) { void avdt_l2c_disconnect_ind_cback(uint16_t lcid, bool ack_needed) { AvdtpTransportChannel* p_tbl; - log::verbose("avdt_l2c_disconnect_ind_cback lcid: {}, ack_needed: {}", lcid, - ack_needed); + log::verbose("avdt_l2c_disconnect_ind_cback lcid: {}, ack_needed: {}", lcid, ack_needed); /* look up info for this channel */ p_tbl = avdt_ad_tc_tbl_by_lcid(lcid); if (p_tbl != NULL) { @@ -419,6 +413,7 @@ void avdt_l2c_data_ind_cback(uint16_t lcid, BT_HDR* p_buf) { p_tbl = avdt_ad_tc_tbl_by_lcid(lcid); if (p_tbl != NULL) { avdt_ad_tc_data_ind(p_tbl, p_buf); - } else /* prevent buffer leak */ + } else { /* prevent buffer leak */ osi_free(p_buf); + } } diff --git a/system/stack/avdt/avdt_msg.cc b/system/stack/avdt/avdt_msg.cc index 9021a77fca2..bc691270052 100644 --- a/system/stack/avdt/avdt_msg.cc +++ b/system/stack/avdt/avdt_msg.cc @@ -48,9 +48,9 @@ using namespace bluetooth; ****************************************************************************/ /* mask of all psc values */ -#define AVDT_MSG_PSC_MASK \ - (AVDT_PSC_TRANS | AVDT_PSC_REPORT | AVDT_PSC_DELAY_RPT | AVDT_PSC_RECOV | \ - AVDT_PSC_HDRCMP | AVDT_PSC_MUX) +#define AVDT_MSG_PSC_MASK \ + (AVDT_PSC_TRANS | AVDT_PSC_REPORT | AVDT_PSC_DELAY_RPT | AVDT_PSC_RECOV | AVDT_PSC_HDRCMP | \ + AVDT_PSC_MUX) #define AVDT_PSC_PROTECT (1 << 4) /* Content Protection */ #define AVDT_PSC_CODEC (1 << 7) /* codec */ @@ -82,22 +82,15 @@ static void avdt_msg_bld_delay_rpt(uint8_t** p, tAVDT_MSG* p_msg); static uint8_t avdt_msg_prs_none(tAVDT_MSG* p_msg, uint8_t* p, uint16_t len); static uint8_t avdt_msg_prs_single(tAVDT_MSG* p_msg, uint8_t* p, uint16_t len); -static uint8_t avdt_msg_prs_setconfig_cmd(tAVDT_MSG* p_msg, uint8_t* p, - uint16_t len); -static uint8_t avdt_msg_prs_reconfig_cmd(tAVDT_MSG* p_msg, uint8_t* p, - uint16_t len); +static uint8_t avdt_msg_prs_setconfig_cmd(tAVDT_MSG* p_msg, uint8_t* p, uint16_t len); +static uint8_t avdt_msg_prs_reconfig_cmd(tAVDT_MSG* p_msg, uint8_t* p, uint16_t len); static uint8_t avdt_msg_prs_multi(tAVDT_MSG* p_msg, uint8_t* p, uint16_t len); -static uint8_t avdt_msg_prs_security_cmd(tAVDT_MSG* p_msg, uint8_t* p, - uint16_t len); -static uint8_t avdt_msg_prs_discover_rsp(tAVDT_MSG* p_msg, uint8_t* p, - uint16_t len); +static uint8_t avdt_msg_prs_security_cmd(tAVDT_MSG* p_msg, uint8_t* p, uint16_t len); +static uint8_t avdt_msg_prs_discover_rsp(tAVDT_MSG* p_msg, uint8_t* p, uint16_t len); static uint8_t avdt_msg_prs_svccap(tAVDT_MSG* p_msg, uint8_t* p, uint16_t len); -static uint8_t avdt_msg_prs_all_svccap(tAVDT_MSG* p_msg, uint8_t* p, - uint16_t len); -static uint8_t avdt_msg_prs_security_rsp(tAVDT_MSG* p_msg, uint8_t* p, - uint16_t len); -static uint8_t avdt_msg_prs_delay_rpt(tAVDT_MSG* p_msg, uint8_t* p, - uint16_t len); +static uint8_t avdt_msg_prs_all_svccap(tAVDT_MSG* p_msg, uint8_t* p, uint16_t len); +static uint8_t avdt_msg_prs_security_rsp(tAVDT_MSG* p_msg, uint8_t* p, uint16_t len); +static uint8_t avdt_msg_prs_delay_rpt(tAVDT_MSG* p_msg, uint8_t* p, uint16_t len); /***************************************************************************** * constants @@ -105,165 +98,164 @@ static uint8_t avdt_msg_prs_delay_rpt(tAVDT_MSG* p_msg, uint8_t* p, /* table of information element minimum lengths used for parsing */ const uint8_t avdt_msg_ie_len_min[] = { - 0, /* unused */ - AVDT_LEN_TRANS_MIN, /* media transport */ - AVDT_LEN_REPORT_MIN, /* reporting */ - AVDT_LEN_RECOV_MIN, /* recovery */ - AVDT_LEN_PROTECT_MIN, /* content protection */ - AVDT_LEN_HDRCMP_MIN, /* header compression */ - AVDT_LEN_MUX_MIN, /* multiplexing */ - AVDT_LEN_CODEC_MIN, /* codec */ - AVDT_LEN_DELAY_RPT_MIN /* delay report */ + 0, /* unused */ + AVDT_LEN_TRANS_MIN, /* media transport */ + AVDT_LEN_REPORT_MIN, /* reporting */ + AVDT_LEN_RECOV_MIN, /* recovery */ + AVDT_LEN_PROTECT_MIN, /* content protection */ + AVDT_LEN_HDRCMP_MIN, /* header compression */ + AVDT_LEN_MUX_MIN, /* multiplexing */ + AVDT_LEN_CODEC_MIN, /* codec */ + AVDT_LEN_DELAY_RPT_MIN /* delay report */ }; /* table of information element minimum lengths used for parsing */ const uint8_t avdt_msg_ie_len_max[] = { - 0, /* unused */ - AVDT_LEN_TRANS_MAX, /* media transport */ - AVDT_LEN_REPORT_MAX, /* reporting */ - AVDT_LEN_RECOV_MAX, /* recovery */ - AVDT_LEN_PROTECT_MAX, /* content protection */ - AVDT_LEN_HDRCMP_MAX, /* header compression */ - AVDT_LEN_MUX_MAX, /* multiplexing */ - AVDT_LEN_CODEC_MAX, /* codec */ - AVDT_LEN_DELAY_RPT_MAX /* delay report */ + 0, /* unused */ + AVDT_LEN_TRANS_MAX, /* media transport */ + AVDT_LEN_REPORT_MAX, /* reporting */ + AVDT_LEN_RECOV_MAX, /* recovery */ + AVDT_LEN_PROTECT_MAX, /* content protection */ + AVDT_LEN_HDRCMP_MAX, /* header compression */ + AVDT_LEN_MUX_MAX, /* multiplexing */ + AVDT_LEN_CODEC_MAX, /* codec */ + AVDT_LEN_DELAY_RPT_MAX /* delay report */ }; /* table of error codes used when decoding information elements */ const uint8_t avdt_msg_ie_err[] = { - 0, /* unused */ - AVDT_ERR_MEDIA_TRANS, /* media transport */ - AVDT_ERR_LENGTH, /* reporting */ - AVDT_ERR_RECOV_FMT, /* recovery */ - AVDT_ERR_CP_FMT, /* content protection */ - AVDT_ERR_ROHC_FMT, /* header compression */ - AVDT_ERR_MUX_FMT, /* multiplexing */ - AVDT_ERR_SERVICE, /* codec */ - AVDT_ERR_SERVICE /* delay report ?? */ + 0, /* unused */ + AVDT_ERR_MEDIA_TRANS, /* media transport */ + AVDT_ERR_LENGTH, /* reporting */ + AVDT_ERR_RECOV_FMT, /* recovery */ + AVDT_ERR_CP_FMT, /* content protection */ + AVDT_ERR_ROHC_FMT, /* header compression */ + AVDT_ERR_MUX_FMT, /* multiplexing */ + AVDT_ERR_SERVICE, /* codec */ + AVDT_ERR_SERVICE /* delay report ?? */ }; /* table of packet type minimum lengths */ -static const uint8_t avdt_msg_pkt_type_len[] = { - AVDT_LEN_TYPE_SINGLE, AVDT_LEN_TYPE_START, AVDT_LEN_TYPE_CONT, - AVDT_LEN_TYPE_END}; +static const uint8_t avdt_msg_pkt_type_len[] = {AVDT_LEN_TYPE_SINGLE, AVDT_LEN_TYPE_START, + AVDT_LEN_TYPE_CONT, AVDT_LEN_TYPE_END}; /* function table for building command messages */ const tAVDT_MSG_BLD avdt_msg_bld_cmd[] = { - avdt_msg_bld_none, /* discover */ - avdt_msg_bld_single, /* get capabilities */ - avdt_msg_bld_setconfig_cmd, /* set configuration */ - avdt_msg_bld_single, /* get configuration */ - avdt_msg_bld_reconfig_cmd, /* reconfigure */ - avdt_msg_bld_single, /* open */ - avdt_msg_bld_multi, /* start */ - avdt_msg_bld_single, /* close */ - avdt_msg_bld_multi, /* suspend */ - avdt_msg_bld_single, /* abort */ - avdt_msg_bld_security_cmd, /* security control */ - avdt_msg_bld_single, /* get all capabilities */ - avdt_msg_bld_delay_rpt /* delay report */ + avdt_msg_bld_none, /* discover */ + avdt_msg_bld_single, /* get capabilities */ + avdt_msg_bld_setconfig_cmd, /* set configuration */ + avdt_msg_bld_single, /* get configuration */ + avdt_msg_bld_reconfig_cmd, /* reconfigure */ + avdt_msg_bld_single, /* open */ + avdt_msg_bld_multi, /* start */ + avdt_msg_bld_single, /* close */ + avdt_msg_bld_multi, /* suspend */ + avdt_msg_bld_single, /* abort */ + avdt_msg_bld_security_cmd, /* security control */ + avdt_msg_bld_single, /* get all capabilities */ + avdt_msg_bld_delay_rpt /* delay report */ }; /* function table for building response messages */ const tAVDT_MSG_BLD avdt_msg_bld_rsp[] = { - avdt_msg_bld_discover_rsp, /* discover */ - avdt_msg_bld_svccap, /* get capabilities */ - avdt_msg_bld_none, /* set configuration */ - avdt_msg_bld_all_svccap, /* get configuration */ - avdt_msg_bld_none, /* reconfigure */ - avdt_msg_bld_none, /* open */ - avdt_msg_bld_none, /* start */ - avdt_msg_bld_none, /* close */ - avdt_msg_bld_none, /* suspend */ - avdt_msg_bld_none, /* abort */ - avdt_msg_bld_security_rsp, /* security control */ - avdt_msg_bld_all_svccap, /* get all capabilities */ - avdt_msg_bld_none /* delay report */ + avdt_msg_bld_discover_rsp, /* discover */ + avdt_msg_bld_svccap, /* get capabilities */ + avdt_msg_bld_none, /* set configuration */ + avdt_msg_bld_all_svccap, /* get configuration */ + avdt_msg_bld_none, /* reconfigure */ + avdt_msg_bld_none, /* open */ + avdt_msg_bld_none, /* start */ + avdt_msg_bld_none, /* close */ + avdt_msg_bld_none, /* suspend */ + avdt_msg_bld_none, /* abort */ + avdt_msg_bld_security_rsp, /* security control */ + avdt_msg_bld_all_svccap, /* get all capabilities */ + avdt_msg_bld_none /* delay report */ }; /* function table for parsing command messages */ const tAVDT_MSG_PRS avdt_msg_prs_cmd[] = { - avdt_msg_prs_none, /* discover */ - avdt_msg_prs_single, /* get capabilities */ - avdt_msg_prs_setconfig_cmd, /* set configuration */ - avdt_msg_prs_single, /* get configuration */ - avdt_msg_prs_reconfig_cmd, /* reconfigure */ - avdt_msg_prs_single, /* open */ - avdt_msg_prs_multi, /* start */ - avdt_msg_prs_single, /* close */ - avdt_msg_prs_multi, /* suspend */ - avdt_msg_prs_single, /* abort */ - avdt_msg_prs_security_cmd, /* security control */ - avdt_msg_prs_single, /* get all capabilities */ - avdt_msg_prs_delay_rpt /* delay report */ + avdt_msg_prs_none, /* discover */ + avdt_msg_prs_single, /* get capabilities */ + avdt_msg_prs_setconfig_cmd, /* set configuration */ + avdt_msg_prs_single, /* get configuration */ + avdt_msg_prs_reconfig_cmd, /* reconfigure */ + avdt_msg_prs_single, /* open */ + avdt_msg_prs_multi, /* start */ + avdt_msg_prs_single, /* close */ + avdt_msg_prs_multi, /* suspend */ + avdt_msg_prs_single, /* abort */ + avdt_msg_prs_security_cmd, /* security control */ + avdt_msg_prs_single, /* get all capabilities */ + avdt_msg_prs_delay_rpt /* delay report */ }; /* function table for parsing response messages */ const tAVDT_MSG_PRS avdt_msg_prs_rsp[] = { - avdt_msg_prs_discover_rsp, /* discover */ - avdt_msg_prs_svccap, /* get capabilities */ - avdt_msg_prs_none, /* set configuration */ - avdt_msg_prs_all_svccap, /* get configuration */ - avdt_msg_prs_none, /* reconfigure */ - avdt_msg_prs_none, /* open */ - avdt_msg_prs_none, /* start */ - avdt_msg_prs_none, /* close */ - avdt_msg_prs_none, /* suspend */ - avdt_msg_prs_none, /* abort */ - avdt_msg_prs_security_rsp, /* security control */ - avdt_msg_prs_all_svccap, /* get all capabilities */ - avdt_msg_prs_none /* delay report */ + avdt_msg_prs_discover_rsp, /* discover */ + avdt_msg_prs_svccap, /* get capabilities */ + avdt_msg_prs_none, /* set configuration */ + avdt_msg_prs_all_svccap, /* get configuration */ + avdt_msg_prs_none, /* reconfigure */ + avdt_msg_prs_none, /* open */ + avdt_msg_prs_none, /* start */ + avdt_msg_prs_none, /* close */ + avdt_msg_prs_none, /* suspend */ + avdt_msg_prs_none, /* abort */ + avdt_msg_prs_security_rsp, /* security control */ + avdt_msg_prs_all_svccap, /* get all capabilities */ + avdt_msg_prs_none /* delay report */ }; /* command message-to-event lookup table */ const uint8_t avdt_msg_cmd_2_evt[] = { - AVDT_CCB_MSG_DISCOVER_CMD_EVT + AVDT_CCB_MKR, /* discover */ - AVDT_CCB_MSG_GETCAP_CMD_EVT + AVDT_CCB_MKR, /* get capabilities */ - AVDT_SCB_MSG_SETCONFIG_CMD_EVT, /* set configuration */ - AVDT_SCB_MSG_GETCONFIG_CMD_EVT, /* get configuration */ - AVDT_SCB_MSG_RECONFIG_CMD_EVT, /* reconfigure */ - AVDT_SCB_MSG_OPEN_CMD_EVT, /* open */ - AVDT_CCB_MSG_START_CMD_EVT + AVDT_CCB_MKR, /* start */ - AVDT_SCB_MSG_CLOSE_CMD_EVT, /* close */ - AVDT_CCB_MSG_SUSPEND_CMD_EVT + AVDT_CCB_MKR, /* suspend */ - AVDT_SCB_MSG_ABORT_CMD_EVT, /* abort */ - AVDT_SCB_MSG_SECURITY_CMD_EVT, /* security control */ - AVDT_CCB_MSG_GETCAP_CMD_EVT + AVDT_CCB_MKR, /* get all capabilities */ - AVDT_SCB_MSG_DELAY_RPT_CMD_EVT /* delay report */ + AVDT_CCB_MSG_DISCOVER_CMD_EVT + AVDT_CCB_MKR, /* discover */ + AVDT_CCB_MSG_GETCAP_CMD_EVT + AVDT_CCB_MKR, /* get capabilities */ + AVDT_SCB_MSG_SETCONFIG_CMD_EVT, /* set configuration */ + AVDT_SCB_MSG_GETCONFIG_CMD_EVT, /* get configuration */ + AVDT_SCB_MSG_RECONFIG_CMD_EVT, /* reconfigure */ + AVDT_SCB_MSG_OPEN_CMD_EVT, /* open */ + AVDT_CCB_MSG_START_CMD_EVT + AVDT_CCB_MKR, /* start */ + AVDT_SCB_MSG_CLOSE_CMD_EVT, /* close */ + AVDT_CCB_MSG_SUSPEND_CMD_EVT + AVDT_CCB_MKR, /* suspend */ + AVDT_SCB_MSG_ABORT_CMD_EVT, /* abort */ + AVDT_SCB_MSG_SECURITY_CMD_EVT, /* security control */ + AVDT_CCB_MSG_GETCAP_CMD_EVT + AVDT_CCB_MKR, /* get all capabilities */ + AVDT_SCB_MSG_DELAY_RPT_CMD_EVT /* delay report */ }; /* response message-to-event lookup table */ const uint8_t avdt_msg_rsp_2_evt[] = { - AVDT_CCB_MSG_DISCOVER_RSP_EVT + AVDT_CCB_MKR, /* discover */ - AVDT_CCB_MSG_GETCAP_RSP_EVT + AVDT_CCB_MKR, /* get capabilities */ - AVDT_SCB_MSG_SETCONFIG_RSP_EVT, /* set configuration */ - AVDT_SCB_MSG_GETCONFIG_RSP_EVT, /* get configuration */ - AVDT_SCB_MSG_RECONFIG_RSP_EVT, /* reconfigure */ - AVDT_SCB_MSG_OPEN_RSP_EVT, /* open */ - AVDT_CCB_MSG_START_RSP_EVT + AVDT_CCB_MKR, /* start */ - AVDT_SCB_MSG_CLOSE_RSP_EVT, /* close */ - AVDT_CCB_MSG_SUSPEND_RSP_EVT + AVDT_CCB_MKR, /* suspend */ - AVDT_SCB_MSG_ABORT_RSP_EVT, /* abort */ - AVDT_SCB_MSG_SECURITY_RSP_EVT, /* security control */ - AVDT_CCB_MSG_GETCAP_RSP_EVT + AVDT_CCB_MKR, /* get all capabilities */ - AVDT_SCB_MSG_DELAY_RPT_RSP_EVT /* delay report */ + AVDT_CCB_MSG_DISCOVER_RSP_EVT + AVDT_CCB_MKR, /* discover */ + AVDT_CCB_MSG_GETCAP_RSP_EVT + AVDT_CCB_MKR, /* get capabilities */ + AVDT_SCB_MSG_SETCONFIG_RSP_EVT, /* set configuration */ + AVDT_SCB_MSG_GETCONFIG_RSP_EVT, /* get configuration */ + AVDT_SCB_MSG_RECONFIG_RSP_EVT, /* reconfigure */ + AVDT_SCB_MSG_OPEN_RSP_EVT, /* open */ + AVDT_CCB_MSG_START_RSP_EVT + AVDT_CCB_MKR, /* start */ + AVDT_SCB_MSG_CLOSE_RSP_EVT, /* close */ + AVDT_CCB_MSG_SUSPEND_RSP_EVT + AVDT_CCB_MKR, /* suspend */ + AVDT_SCB_MSG_ABORT_RSP_EVT, /* abort */ + AVDT_SCB_MSG_SECURITY_RSP_EVT, /* security control */ + AVDT_CCB_MSG_GETCAP_RSP_EVT + AVDT_CCB_MKR, /* get all capabilities */ + AVDT_SCB_MSG_DELAY_RPT_RSP_EVT /* delay report */ }; /* reject message-to-event lookup table */ const uint8_t avdt_msg_rej_2_evt[] = { - AVDT_CCB_MSG_DISCOVER_RSP_EVT + AVDT_CCB_MKR, /* discover */ - AVDT_CCB_MSG_GETCAP_RSP_EVT + AVDT_CCB_MKR, /* get capabilities */ - AVDT_SCB_MSG_SETCONFIG_REJ_EVT, /* set configuration */ - AVDT_SCB_MSG_GETCONFIG_RSP_EVT, /* get configuration */ - AVDT_SCB_MSG_RECONFIG_RSP_EVT, /* reconfigure */ - AVDT_SCB_MSG_OPEN_REJ_EVT, /* open */ - AVDT_CCB_MSG_START_RSP_EVT + AVDT_CCB_MKR, /* start */ - AVDT_SCB_MSG_CLOSE_RSP_EVT, /* close */ - AVDT_CCB_MSG_SUSPEND_RSP_EVT + AVDT_CCB_MKR, /* suspend */ - AVDT_SCB_MSG_ABORT_RSP_EVT, /* abort */ - AVDT_SCB_MSG_SECURITY_RSP_EVT, /* security control */ - AVDT_CCB_MSG_GETCAP_RSP_EVT + AVDT_CCB_MKR, /* get all capabilities */ - 0 /* delay report */ + AVDT_CCB_MSG_DISCOVER_RSP_EVT + AVDT_CCB_MKR, /* discover */ + AVDT_CCB_MSG_GETCAP_RSP_EVT + AVDT_CCB_MKR, /* get capabilities */ + AVDT_SCB_MSG_SETCONFIG_REJ_EVT, /* set configuration */ + AVDT_SCB_MSG_GETCONFIG_RSP_EVT, /* get configuration */ + AVDT_SCB_MSG_RECONFIG_RSP_EVT, /* reconfigure */ + AVDT_SCB_MSG_OPEN_REJ_EVT, /* open */ + AVDT_CCB_MSG_START_RSP_EVT + AVDT_CCB_MKR, /* start */ + AVDT_SCB_MSG_CLOSE_RSP_EVT, /* close */ + AVDT_CCB_MSG_SUSPEND_RSP_EVT + AVDT_CCB_MKR, /* suspend */ + AVDT_SCB_MSG_ABORT_RSP_EVT, /* abort */ + AVDT_SCB_MSG_SECURITY_RSP_EVT, /* security control */ + AVDT_CCB_MSG_GETCAP_RSP_EVT + AVDT_CCB_MKR, /* get all capabilities */ + 0 /* delay report */ }; /******************************************************************************* @@ -299,7 +291,9 @@ static void avdt_msg_bld_cfg(uint8_t** p, AvdtpSepConfig* p_cfg) { if (p_cfg->num_codec != 0) { *(*p)++ = AVDT_CAT_CODEC; len = p_cfg->codec_info[0] + 1; - if (len > AVDT_CODEC_SIZE) len = AVDT_CODEC_SIZE; + if (len > AVDT_CODEC_SIZE) { + len = AVDT_CODEC_SIZE; + } memcpy(*p, p_cfg->codec_info, len); *p += len; @@ -309,7 +303,9 @@ static void avdt_msg_bld_cfg(uint8_t** p, AvdtpSepConfig* p_cfg) { if (p_cfg->num_protect != 0) { *(*p)++ = AVDT_CAT_PROTECT; len = p_cfg->protect_info[0] + 1; - if (len > AVDT_PROTECT_SIZE) len = AVDT_PROTECT_SIZE; + if (len > AVDT_PROTECT_SIZE) { + len = AVDT_PROTECT_SIZE; + } memcpy(*p, p_cfg->protect_info, len); *p += len; @@ -332,9 +328,7 @@ static void avdt_msg_bld_cfg(uint8_t** p, AvdtpSepConfig* p_cfg) { * Returns void. * ******************************************************************************/ -static void avdt_msg_bld_none(uint8_t** /* p */, tAVDT_MSG* /* p_msg */) { - return; -} +static void avdt_msg_bld_none(uint8_t** /* p */, tAVDT_MSG* /* p_msg */) { return; } /******************************************************************************* * @@ -453,10 +447,9 @@ static void avdt_msg_bld_discover_rsp(uint8_t** p, tAVDT_MSG* p_msg) { for (i = 0; i < p_msg->discover_rsp.num_seps; i++) { /* build discover rsp info */ - AVDT_MSG_BLD_DISC(*p, p_msg->discover_rsp.p_sep_info[i].seid, - p_msg->discover_rsp.p_sep_info[i].in_use, - p_msg->discover_rsp.p_sep_info[i].media_type, - p_msg->discover_rsp.p_sep_info[i].tsep); + AVDT_MSG_BLD_DISC( + *p, p_msg->discover_rsp.p_sep_info[i].seid, p_msg->discover_rsp.p_sep_info[i].in_use, + p_msg->discover_rsp.p_sep_info[i].media_type, p_msg->discover_rsp.p_sep_info[i].tsep); } } @@ -523,8 +516,8 @@ static void avdt_msg_bld_security_rsp(uint8_t** p, tAVDT_MSG* p_msg) { * in p_elem. * ******************************************************************************/ -static uint8_t avdt_msg_prs_cfg(AvdtpSepConfig* p_cfg, uint8_t* p, uint16_t len, - uint8_t* p_elem, uint8_t sig_id) { +static uint8_t avdt_msg_prs_cfg(AvdtpSepConfig* p_cfg, uint8_t* p, uint16_t len, uint8_t* p_elem, + uint8_t sig_id) { uint8_t* p_end; uint8_t elem = 0; uint8_t elem_len; @@ -570,22 +563,19 @@ static uint8_t avdt_msg_prs_cfg(AvdtpSepConfig* p_cfg, uint8_t* p, uint16_t len, { /* Skip unknown categories. */ p += elem_len; - log::verbose("skipping unknown service category={} len: {}", elem, - elem_len); + log::verbose("skipping unknown service category={} len: {}", elem, elem_len); continue; } } - if ((elem_len > avdt_msg_ie_len_max[elem]) || - (elem_len < avdt_msg_ie_len_min[elem])) { + if ((elem_len > avdt_msg_ie_len_max[elem]) || (elem_len < avdt_msg_ie_len_min[elem])) { err = avdt_msg_ie_err[elem]; break; } /* add element to psc mask, but mask out codec or protect */ p_cfg->psc_mask |= (1 << elem); - log::verbose("elem={} elem_len: {} psc_mask=0x{:x}", elem, elem_len, - p_cfg->psc_mask); + log::verbose("elem={} elem_len: {} psc_mask=0x{:x}", elem, elem_len, p_cfg->psc_mask); /* parse individual information elements with additional parameters */ switch (elem) { @@ -655,10 +645,9 @@ static uint8_t avdt_msg_prs_cfg(AvdtpSepConfig* p_cfg, uint8_t* p, uint16_t len, p += elem_len; break; } /* switch */ - } /* while ! err, !end*/ + } /* while ! err, !end*/ *p_elem = elem; - log::verbose("err=0x{:x}, elem:0x{:x} psc_mask=0x{:x}", err, elem, - p_cfg->psc_mask); + log::verbose("err=0x{:x}, elem:0x{:x} psc_mask=0x{:x}", err, elem, p_cfg->psc_mask); return err; } @@ -674,8 +663,7 @@ static uint8_t avdt_msg_prs_cfg(AvdtpSepConfig* p_cfg, uint8_t* p, uint16_t len, * Returns Error code or zero if no error. * ******************************************************************************/ -static uint8_t avdt_msg_prs_none(tAVDT_MSG* /* p_msg */, uint8_t* /* p */, - uint16_t /* len */) { +static uint8_t avdt_msg_prs_none(tAVDT_MSG* /* p_msg */, uint8_t* /* p */, uint16_t /* len */) { return 0; } @@ -717,8 +705,7 @@ static uint8_t avdt_msg_prs_single(tAVDT_MSG* p_msg, uint8_t* p, uint16_t len) { * Returns Error code or zero if no error. * ******************************************************************************/ -static uint8_t avdt_msg_prs_setconfig_cmd(tAVDT_MSG* p_msg, uint8_t* p, - uint16_t len) { +static uint8_t avdt_msg_prs_setconfig_cmd(tAVDT_MSG* p_msg, uint8_t* p, uint16_t len) { uint8_t err = 0; p_msg->hdr.err_param = 0; @@ -743,8 +730,8 @@ static uint8_t avdt_msg_prs_setconfig_cmd(tAVDT_MSG* p_msg, uint8_t* p, if (!err) { /* parse configuration parameters */ len -= 2; - err = avdt_msg_prs_cfg(p_msg->config_cmd.p_cfg, p, len, - &p_msg->hdr.err_param, AVDT_SIG_SETCONFIG); + err = avdt_msg_prs_cfg(p_msg->config_cmd.p_cfg, p, len, &p_msg->hdr.err_param, + AVDT_SIG_SETCONFIG); if (!err) { /* verify protocol service capabilities are supported */ @@ -769,8 +756,7 @@ static uint8_t avdt_msg_prs_setconfig_cmd(tAVDT_MSG* p_msg, uint8_t* p, * Returns Error code or zero if no error. * ******************************************************************************/ -static uint8_t avdt_msg_prs_reconfig_cmd(tAVDT_MSG* p_msg, uint8_t* p, - uint16_t len) { +static uint8_t avdt_msg_prs_reconfig_cmd(tAVDT_MSG* p_msg, uint8_t* p, uint16_t len) { uint8_t err = 0; p_msg->hdr.err_param = 0; @@ -786,8 +772,8 @@ static uint8_t avdt_msg_prs_reconfig_cmd(tAVDT_MSG* p_msg, uint8_t* p, } else { /* parse config parameters */ len--; - err = avdt_msg_prs_cfg(p_msg->config_cmd.p_cfg, p, len, - &p_msg->hdr.err_param, AVDT_SIG_RECONFIG); + err = avdt_msg_prs_cfg(p_msg->config_cmd.p_cfg, p, len, &p_msg->hdr.err_param, + AVDT_SIG_RECONFIG); /* verify no protocol service capabilities in parameters */ if (!err) { @@ -851,8 +837,7 @@ static uint8_t avdt_msg_prs_multi(tAVDT_MSG* p_msg, uint8_t* p, uint16_t len) { * Returns Error code or zero if no error. * ******************************************************************************/ -static uint8_t avdt_msg_prs_security_cmd(tAVDT_MSG* p_msg, uint8_t* p, - uint16_t len) { +static uint8_t avdt_msg_prs_security_cmd(tAVDT_MSG* p_msg, uint8_t* p, uint16_t len) { uint8_t err = 0; /* verify len */ @@ -882,8 +867,7 @@ static uint8_t avdt_msg_prs_security_cmd(tAVDT_MSG* p_msg, uint8_t* p, * Returns Error code or zero if no error. * ******************************************************************************/ -static uint8_t avdt_msg_prs_discover_rsp(tAVDT_MSG* p_msg, uint8_t* p, - uint16_t len) { +static uint8_t avdt_msg_prs_discover_rsp(tAVDT_MSG* p_msg, uint8_t* p, uint16_t len) { int i; uint8_t err = 0; @@ -897,10 +881,9 @@ static uint8_t avdt_msg_prs_discover_rsp(tAVDT_MSG* p_msg, uint8_t* p, /* parse out sep info */ for (i = 0; i < p_msg->discover_rsp.num_seps; i++) { /* parse discover rsp info */ - AVDT_MSG_PRS_DISC(p, p_msg->discover_rsp.p_sep_info[i].seid, - p_msg->discover_rsp.p_sep_info[i].in_use, - p_msg->discover_rsp.p_sep_info[i].media_type, - p_msg->discover_rsp.p_sep_info[i].tsep); + AVDT_MSG_PRS_DISC( + p, p_msg->discover_rsp.p_sep_info[i].seid, p_msg->discover_rsp.p_sep_info[i].in_use, + p_msg->discover_rsp.p_sep_info[i].media_type, p_msg->discover_rsp.p_sep_info[i].tsep); /* verify that seid is valid */ if ((p_msg->discover_rsp.p_sep_info[i].seid < AVDT_SEID_MIN) || @@ -926,13 +909,13 @@ static uint8_t avdt_msg_prs_discover_rsp(tAVDT_MSG* p_msg, uint8_t* p, ******************************************************************************/ static uint8_t avdt_msg_prs_svccap(tAVDT_MSG* p_msg, uint8_t* p, uint16_t len) { /* parse parameters */ - uint8_t err = avdt_msg_prs_cfg(p_msg->svccap.p_cfg, p, len, - &p_msg->hdr.err_param, AVDT_SIG_GETCAP); + uint8_t err = + avdt_msg_prs_cfg(p_msg->svccap.p_cfg, p, len, &p_msg->hdr.err_param, AVDT_SIG_GETCAP); if (p_msg->svccap.p_cfg) { p_msg->svccap.p_cfg->psc_mask &= AVDT_LEG_PSC; } - return (err); + return err; } /******************************************************************************* @@ -946,14 +929,13 @@ static uint8_t avdt_msg_prs_svccap(tAVDT_MSG* p_msg, uint8_t* p, uint16_t len) { * Returns Error code or zero if no error. * ******************************************************************************/ -static uint8_t avdt_msg_prs_all_svccap(tAVDT_MSG* p_msg, uint8_t* p, - uint16_t len) { - uint8_t err = avdt_msg_prs_cfg(p_msg->svccap.p_cfg, p, len, - &p_msg->hdr.err_param, AVDT_SIG_GET_ALLCAP); +static uint8_t avdt_msg_prs_all_svccap(tAVDT_MSG* p_msg, uint8_t* p, uint16_t len) { + uint8_t err = + avdt_msg_prs_cfg(p_msg->svccap.p_cfg, p, len, &p_msg->hdr.err_param, AVDT_SIG_GET_ALLCAP); if (p_msg->svccap.p_cfg) { p_msg->svccap.p_cfg->psc_mask &= AVDT_MSG_PSC_MASK; } - return (err); + return err; } /******************************************************************************* @@ -967,8 +949,7 @@ static uint8_t avdt_msg_prs_all_svccap(tAVDT_MSG* p_msg, uint8_t* p, * Returns Error code or zero if no error. * ******************************************************************************/ -static uint8_t avdt_msg_prs_security_rsp(tAVDT_MSG* p_msg, uint8_t* p, - uint16_t len) { +static uint8_t avdt_msg_prs_security_rsp(tAVDT_MSG* p_msg, uint8_t* p, uint16_t len) { p_msg->security_rsp.p_data = p; p_msg->security_rsp.len = len; @@ -985,8 +966,7 @@ static uint8_t avdt_msg_prs_security_rsp(tAVDT_MSG* p_msg, uint8_t* p, * Returns Error code or zero if no error. * ******************************************************************************/ -static uint8_t avdt_msg_prs_rej(tAVDT_MSG* p_msg, uint8_t* p, uint16_t len, - uint8_t sig) { +static uint8_t avdt_msg_prs_rej(tAVDT_MSG* p_msg, uint8_t* p, uint16_t len, uint8_t sig) { uint8_t error = 0; if (len > 0) { @@ -1019,14 +999,12 @@ static uint8_t avdt_msg_prs_rej(tAVDT_MSG* p_msg, uint8_t* p, uint16_t len, * Returns Error code or zero if no error. * ******************************************************************************/ -static uint8_t avdt_msg_prs_delay_rpt(tAVDT_MSG* p_msg, uint8_t* p, - uint16_t len) { +static uint8_t avdt_msg_prs_delay_rpt(tAVDT_MSG* p_msg, uint8_t* p, uint16_t len) { uint8_t err = 0; /* verify len */ if (len != AVDT_LEN_DELAY_RPT) { - log::warn("avdt_msg_prs_delay_rpt expected len: {} got: {}", - AVDT_LEN_DELAY_RPT, len); + log::warn("avdt_msg_prs_delay_rpt expected len: {} got: {}", AVDT_LEN_DELAY_RPT, len); err = AVDT_ERR_LENGTH; } else { /* get seid */ @@ -1036,8 +1014,7 @@ static uint8_t avdt_msg_prs_delay_rpt(tAVDT_MSG* p_msg, uint8_t* p, err = AVDT_ERR_SEID; } else { BE_STREAM_TO_UINT16(p_msg->delay_rpt_cmd.delay, p); - log::verbose("avdt_msg_prs_delay_rpt delay: {}", - p_msg->delay_rpt_cmd.delay); + log::verbose("avdt_msg_prs_delay_rpt delay: {}", p_msg->delay_rpt_cmd.delay); } } return err; @@ -1091,12 +1068,11 @@ bool avdt_msg_send(AvdtpCcb* p_ccb, BT_HDR* p_msg) { } /* if message isn't being fragmented and it doesn't fit in mtu */ else if ((p_ccb->p_curr_msg->offset == AVDT_MSG_OFFSET) && - (p_ccb->p_curr_msg->len > - p_tbl->peer_mtu - AVDT_LEN_TYPE_SINGLE)) { + (p_ccb->p_curr_msg->len > p_tbl->peer_mtu - AVDT_LEN_TYPE_SINGLE)) { pkt_type = AVDT_PKT_TYPE_START; hdr_len = AVDT_LEN_TYPE_START; nosp = (p_ccb->p_curr_msg->len + AVDT_LEN_TYPE_START - p_tbl->peer_mtu) / - (p_tbl->peer_mtu - 1) + + (p_tbl->peer_mtu - 1) + 2; /* get a new buffer for fragment we are sending */ @@ -1106,13 +1082,11 @@ bool avdt_msg_send(AvdtpCcb* p_ccb, BT_HDR* p_msg) { p_buf->offset = L2CAP_MIN_OFFSET + hdr_len; p_buf->len = p_tbl->peer_mtu - hdr_len; memcpy((uint8_t*)(p_buf + 1) + p_buf->offset, - (uint8_t*)(p_ccb->p_curr_msg + 1) + p_ccb->p_curr_msg->offset, - p_buf->len); + (uint8_t*)(p_ccb->p_curr_msg + 1) + p_ccb->p_curr_msg->offset, p_buf->len); } /* if message is being fragmented and remaining bytes don't fit in mtu */ else if ((p_ccb->p_curr_msg->offset > AVDT_MSG_OFFSET) && - (p_ccb->p_curr_msg->len > - (p_tbl->peer_mtu - AVDT_LEN_TYPE_CONT))) { + (p_ccb->p_curr_msg->len > (p_tbl->peer_mtu - AVDT_LEN_TYPE_CONT))) { pkt_type = AVDT_PKT_TYPE_CONT; hdr_len = AVDT_LEN_TYPE_CONT; @@ -1123,8 +1097,7 @@ bool avdt_msg_send(AvdtpCcb* p_ccb, BT_HDR* p_msg) { p_buf->offset = L2CAP_MIN_OFFSET + hdr_len; p_buf->len = p_tbl->peer_mtu - hdr_len; memcpy((uint8_t*)(p_buf + 1) + p_buf->offset, - (uint8_t*)(p_ccb->p_curr_msg + 1) + p_ccb->p_curr_msg->offset, - p_buf->len); + (uint8_t*)(p_ccb->p_curr_msg + 1) + p_ccb->p_curr_msg->offset, p_buf->len); } /* if message is being fragmented and remaining bytes do fit in mtu */ else { @@ -1148,19 +1121,19 @@ bool avdt_msg_send(AvdtpCcb* p_ccb, BT_HDR* p_msg) { /* start timer here for commands */ if (msg == AVDT_MSG_TYPE_CMD) { /* if retransmit timeout set to zero, sig doesn't use retransmit */ - if ((sig == AVDT_SIG_DISCOVER) || (sig == AVDT_SIG_GETCAP) || - (sig == AVDT_SIG_SECURITY) || (avdtp_cb.rcb.ret_tout == 0)) { + if ((sig == AVDT_SIG_DISCOVER) || (sig == AVDT_SIG_GETCAP) || (sig == AVDT_SIG_SECURITY) || + (avdtp_cb.rcb.ret_tout == 0)) { alarm_cancel(p_ccb->idle_ccb_timer); alarm_cancel(p_ccb->ret_ccb_timer); uint64_t interval_ms = avdtp_cb.rcb.sig_tout * 1000; - alarm_set_on_mloop(p_ccb->rsp_ccb_timer, interval_ms, - avdt_ccb_rsp_ccb_timer_timeout, p_ccb); + alarm_set_on_mloop(p_ccb->rsp_ccb_timer, interval_ms, avdt_ccb_rsp_ccb_timer_timeout, + p_ccb); } else if (sig != AVDT_SIG_DELAY_RPT) { alarm_cancel(p_ccb->idle_ccb_timer); alarm_cancel(p_ccb->rsp_ccb_timer); uint64_t interval_ms = avdtp_cb.rcb.ret_tout * 1000; - alarm_set_on_mloop(p_ccb->ret_ccb_timer, interval_ms, - avdt_ccb_ret_ccb_timer_timeout, p_ccb); + alarm_set_on_mloop(p_ccb->ret_ccb_timer, interval_ms, avdt_ccb_ret_ccb_timer_timeout, + p_ccb); } } } else { @@ -1179,15 +1152,14 @@ bool avdt_msg_send(AvdtpCcb* p_ccb, BT_HDR* p_msg) { if (pkt_type == AVDT_PKT_TYPE_START) { AVDT_MSG_BLD_NOSP(p, nosp); } - if ((pkt_type == AVDT_PKT_TYPE_START) || - (pkt_type == AVDT_PKT_TYPE_SINGLE)) { + if ((pkt_type == AVDT_PKT_TYPE_START) || (pkt_type == AVDT_PKT_TYPE_SINGLE)) { AVDT_MSG_BLD_SIG(p, sig); } /* send msg buffer down */ avdt_ad_write_req(AVDT_CHAN_SIG, p_ccb, NULL, p_buf); } - return (p_ccb->cong); + return p_ccb->cong; } /******************************************************************************* @@ -1226,7 +1198,9 @@ BT_HDR* avdt_msg_asmbl(AvdtpCcb* p_ccb, BT_HDR* p_buf) { /* single packet */ else if (pkt_type == AVDT_PKT_TYPE_SINGLE) { /* if reassembly in progress drop message and process new single */ - if (p_ccb->p_rx_msg != NULL) log::warn("Got single during reassembly"); + if (p_ccb->p_rx_msg != NULL) { + log::warn("Got single during reassembly"); + } osi_free_and_reset((void**)&p_ccb->p_rx_msg); @@ -1235,7 +1209,9 @@ BT_HDR* avdt_msg_asmbl(AvdtpCcb* p_ccb, BT_HDR* p_buf) { /* start packet */ else if (pkt_type == AVDT_PKT_TYPE_START) { /* if reassembly in progress drop message and process new single */ - if (p_ccb->p_rx_msg != NULL) log::warn("Got start during reassembly"); + if (p_ccb->p_rx_msg != NULL) { + log::warn("Got start during reassembly"); + } osi_free_and_reset((void**)&p_ccb->p_rx_msg); @@ -1289,7 +1265,7 @@ BT_HDR* avdt_msg_asmbl(AvdtpCcb* p_ccb, BT_HDR* p_buf) { p_buf->len -= AVDT_LEN_TYPE_CONT; /* verify length */ - if (((size_t) p_ccb->p_rx_msg->offset + (size_t) p_buf->len) > buf_len) { + if (((size_t)p_ccb->p_rx_msg->offset + (size_t)p_buf->len) > buf_len) { /* won't fit; free everything */ log::warn("Fragmented message too big!"); osi_free_and_reset((void**)&p_ccb->p_rx_msg); @@ -1332,8 +1308,7 @@ BT_HDR* avdt_msg_asmbl(AvdtpCcb* p_ccb, BT_HDR* p_buf) { * Returns Nothing. * ******************************************************************************/ -void avdt_msg_send_cmd(AvdtpCcb* p_ccb, void* p_scb, uint8_t sig_id, - tAVDT_MSG* p_params) { +void avdt_msg_send_cmd(AvdtpCcb* p_ccb, void* p_scb, uint8_t sig_id, tAVDT_MSG* p_params) { uint8_t* p; uint8_t* p_start; BT_HDR* p_buf = (BT_HDR*)osi_malloc(AVDT_CMD_BUF_SIZE); @@ -1406,8 +1381,7 @@ void avdt_msg_send_rsp(AvdtpCcb* p_ccb, uint8_t sig_id, tAVDT_MSG* p_params) { /* stash sig, label, and message type in buf */ p_buf->event = sig_id; - AVDT_BLD_LAYERSPEC(p_buf->layer_specific, AVDT_MSG_TYPE_RSP, - p_params->hdr.label); + AVDT_BLD_LAYERSPEC(p_buf->layer_specific, AVDT_MSG_TYPE_RSP, p_params->hdr.label); /* queue message and trigger ccb to send it */ fixed_queue_enqueue(p_ccb->rsp_q, p_buf); @@ -1457,8 +1431,7 @@ void avdt_msg_send_rej(AvdtpCcb* p_ccb, uint8_t sig_id, tAVDT_MSG* p_params) { /* stash sig, label, and message type in buf */ p_buf->event = sig_id; - AVDT_BLD_LAYERSPEC(p_buf->layer_specific, AVDT_MSG_TYPE_REJ, - p_params->hdr.label); + AVDT_BLD_LAYERSPEC(p_buf->layer_specific, AVDT_MSG_TYPE_REJ, p_params->hdr.label); /* queue message and trigger ccb to send it */ fixed_queue_enqueue(p_ccb->rsp_q, p_buf); @@ -1494,8 +1467,7 @@ void avdt_msg_send_grej(AvdtpCcb* p_ccb, uint8_t sig_id, tAVDT_MSG* p_params) { /* stash sig, label, and message type in buf */ p_buf->event = sig_id; - AVDT_BLD_LAYERSPEC(p_buf->layer_specific, AVDT_MSG_TYPE_GRJ, - p_params->hdr.label); + AVDT_BLD_LAYERSPEC(p_buf->layer_specific, AVDT_MSG_TYPE_GRJ, p_params->hdr.label); log::verbose(""); /* queue message and trigger ccb to send it */ @@ -1554,8 +1526,7 @@ void avdt_msg_ind(AvdtpCcb* p_ccb, BT_HDR* p_buf) { ok = false; } /* check for general reject */ - else if ((msg_type == AVDT_MSG_TYPE_REJ) && - (p_buf->len == AVDT_LEN_GEN_REJ)) { + else if ((msg_type == AVDT_MSG_TYPE_REJ) && (p_buf->len == AVDT_LEN_GEN_REJ)) { gen_rej = true; if (p_ccb->p_curr_cmd != NULL) { msg.hdr.sig_id = sig = (uint8_t)p_ccb->p_curr_cmd->event; @@ -1607,12 +1578,10 @@ void avdt_msg_ind(AvdtpCcb* p_ccb, BT_HDR* p_buf) { /* parse message; while we're at it map message sig to event */ if (msg_type == AVDT_MSG_TYPE_CMD) { - msg.hdr.err_code = err = - (*avdt_msg_prs_cmd[sig - 1])(&msg, p, p_buf->len); + msg.hdr.err_code = err = (*avdt_msg_prs_cmd[sig - 1])(&msg, p, p_buf->len); evt = avdt_msg_cmd_2_evt[sig - 1]; } else if (msg_type == AVDT_MSG_TYPE_RSP) { - msg.hdr.err_code = err = - (*avdt_msg_prs_rsp[sig - 1])(&msg, p, p_buf->len); + msg.hdr.err_code = err = (*avdt_msg_prs_rsp[sig - 1])(&msg, p, p_buf->len); evt = avdt_msg_rsp_2_evt[sig - 1]; } else /* msg_type == AVDT_MSG_TYPE_REJ */ { diff --git a/system/stack/avdt/avdt_scb.cc b/system/stack/avdt/avdt_scb.cc index dab6da167c5..9adcb699885 100644 --- a/system/stack/avdt/avdt_scb.cc +++ b/system/stack/avdt/avdt_scb.cc @@ -42,28 +42,27 @@ using namespace bluetooth; #if (AVDT_DEBUG == TRUE) /* verbose state strings for trace */ -const char* const avdt_scb_st_str[] = {"SCB_IDLE_ST", "SCB_CONF_ST", - "SCB_OPENING_ST", "SCB_OPEN_ST", - "SCB_STREAM_ST", "SCB_CLOSING_ST"}; +const char* const avdt_scb_st_str[] = {"SCB_IDLE_ST", "SCB_CONF_ST", "SCB_OPENING_ST", + "SCB_OPEN_ST", "SCB_STREAM_ST", "SCB_CLOSING_ST"}; /* verbose event strings for trace */ const char* const avdt_scb_evt_str[] = { - "API_REMOVE_EVT", "API_WRITE_REQ_EVT", "API_GETCONFIG_REQ_EVT", - "API_DELAY_RPT_REQ", "API_SETCONFIG_REQ_EVT", "API_OPEN_REQ_EVT", - "API_CLOSE_REQ_EVT", "API_RECONFIG_REQ_EVT", "API_SECURITY_REQ_EVT", - "API_ABORT_REQ_EVT", "API_GETCONFIG_RSP_EVT", "API_SETCONFIG_RSP_EVT", - "API_SETCONFIG_REJ_EVT", "API_OPEN_RSP_EVT", "API_CLOSE_RSP_EVT", - "API_RECONFIG_RSP_EVT", "API_SECURITY_RSP_EVT", "API_ABORT_RSP_EVT", - "MSG_SETCONFIG_CMD_EVT", "MSG_GETCONFIG_CMD_EVT", "MSG_OPEN_CMD_EVT", - "MSG_START_CMD_EVT", "MSG_SUSPEND_CMD_EVT", "MSG_CLOSE_CMD_EVT", - "MSG_ABORT_CMD_EVT", "MSG_RECONFIG_CMD_EVT", "MSG_SECURITY_CMD_EVT", - "MSG_DELAY_RPT_CMD_EVT", "MSG_DELAY_RPT_RSP_EVT", "MSG_SETCONFIG_RSP_EVT", - "MSG_GETCONFIG_RSP_EVT", "MSG_OPEN_RSP_EVT", "MSG_START_RSP_EVT", - "MSG_SUSPEND_RSP_EVT", "MSG_CLOSE_RSP_EVT", "MSG_ABORT_RSP_EVT", - "MSG_RECONFIG_RSP_EVT", "MSG_SECURITY_RSP_EVT", "MSG_SETCONFIG_REJ_EVT", - "MSG_OPEN_REJ_EVT", "MSG_START_REJ_EVT", "MSG_SUSPEND_REJ_EVT", - "TC_TOUT_EVT", "TC_OPEN_EVT", "TC_CLOSE_EVT", - "TC_CONG_EVT", "TC_DATA_EVT", "CC_CLOSE_EVT"}; + "API_REMOVE_EVT", "API_WRITE_REQ_EVT", "API_GETCONFIG_REQ_EVT", + "API_DELAY_RPT_REQ", "API_SETCONFIG_REQ_EVT", "API_OPEN_REQ_EVT", + "API_CLOSE_REQ_EVT", "API_RECONFIG_REQ_EVT", "API_SECURITY_REQ_EVT", + "API_ABORT_REQ_EVT", "API_GETCONFIG_RSP_EVT", "API_SETCONFIG_RSP_EVT", + "API_SETCONFIG_REJ_EVT", "API_OPEN_RSP_EVT", "API_CLOSE_RSP_EVT", + "API_RECONFIG_RSP_EVT", "API_SECURITY_RSP_EVT", "API_ABORT_RSP_EVT", + "MSG_SETCONFIG_CMD_EVT", "MSG_GETCONFIG_CMD_EVT", "MSG_OPEN_CMD_EVT", + "MSG_START_CMD_EVT", "MSG_SUSPEND_CMD_EVT", "MSG_CLOSE_CMD_EVT", + "MSG_ABORT_CMD_EVT", "MSG_RECONFIG_CMD_EVT", "MSG_SECURITY_CMD_EVT", + "MSG_DELAY_RPT_CMD_EVT", "MSG_DELAY_RPT_RSP_EVT", "MSG_SETCONFIG_RSP_EVT", + "MSG_GETCONFIG_RSP_EVT", "MSG_OPEN_RSP_EVT", "MSG_START_RSP_EVT", + "MSG_SUSPEND_RSP_EVT", "MSG_CLOSE_RSP_EVT", "MSG_ABORT_RSP_EVT", + "MSG_RECONFIG_RSP_EVT", "MSG_SECURITY_RSP_EVT", "MSG_SETCONFIG_REJ_EVT", + "MSG_OPEN_REJ_EVT", "MSG_START_REJ_EVT", "MSG_SUSPEND_REJ_EVT", + "TC_TOUT_EVT", "TC_OPEN_EVT", "TC_CLOSE_EVT", + "TC_CONG_EVT", "TC_DATA_EVT", "CC_CLOSE_EVT"}; #endif @@ -136,617 +135,617 @@ const tAVDT_SCB_ACTION avdt_scb_action[] = {avdt_scb_hdl_abort_cmd, /* state table for idle state */ const uint8_t avdt_scb_st_idle[][AVDT_SCB_NUM_COLS] = { - /* Event */ - /* Action 1 Action 2 Next state */ - /* API_REMOVE_EVT */ - {AVDT_SCB_DEALLOC, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, - /* API_WRITE_REQ_EVT */ - {AVDT_SCB_FREE_PKT, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, - /* API_GETCONFIG_REQ_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, - /* API_DELAY_RPT_REQ_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, - /* API_SETCONFIG_REQ_EVT */ - {AVDT_SCB_SND_SETCONFIG_REQ, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, - /* API_OPEN_REQ_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, - /* API_CLOSE_REQ_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, - /* API_RECONFIG_REQ_EVT */ - {AVDT_SCB_CB_ERR, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, - /* API_SECURITY_REQ_EVT */ - {AVDT_SCB_CB_ERR, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, - /* API_ABORT_REQ_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, - /* API_GETCONFIG_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, - /* API_SETCONFIG_RSP_EVT */ - {AVDT_SCB_SND_SETCONFIG_RSP, AVDT_SCB_SND_SNK_DELAY_RPT_REQ, AVDT_SCB_CONF_ST}, - /* API_SETCONFIG_REJ_EVT */ - {AVDT_SCB_SND_SETCONFIG_REJ, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, - /* API_OPEN_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, - /* API_CLOSE_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, - /* API_RECONFIG_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, - /* API_SECURITY_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, - /* API_ABORT_RSP_EVT */ - {AVDT_SCB_SND_ABORT_RSP, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, - /* MSG_SETCONFIG_CMD_EVT */ - {AVDT_SCB_HDL_SETCONFIG_CMD, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, - /* MSG_GETCONFIG_CMD_EVT */ - {AVDT_SCB_REJ_STATE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, - /* MSG_OPEN_CMD_EVT */ - {AVDT_SCB_REJ_STATE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, - /* MSG_START_CMD_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, - /* MSG_SUSPEND_CMD_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, - /* MSG_CLOSE_CMD_EVT */ - {AVDT_SCB_REJ_STATE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, - /* MSG_ABORT_CMD_EVT */ - {AVDT_SCB_HDL_ABORT_CMD, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, - /* MSG_RECONFIG_CMD_EVT */ - {AVDT_SCB_REJ_NOT_IN_USE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, - /* MSG_SECURITY_CMD_EVT */ - {AVDT_SCB_REJ_STATE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, - /* MSG_DELAY_RPT_CMD_EVT */ - {AVDT_SCB_REJ_STATE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, - /* MSG_DELAY_RPT_RSP_EVT */ - {AVDT_SCB_HDL_DELAY_RPT_RSP, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, - /* MSG_SETCONFIG_RSP_EVT */ - {AVDT_SCB_HDL_SETCONFIG_RSP, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, - /* MSG_GETCONFIG_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, - /* MSG_OPEN_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, - /* MSG_START_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, - /* MSG_SUSPEND_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, - /* MSG_CLOSE_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, - /* MSG_ABORT_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, - /* MSG_RECONFIG_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, - /* MSG_SECURITY_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, - /* MSG_SETCONFIG_REJ_EVT */ - {AVDT_SCB_HDL_SETCONFIG_REJ, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, - /* MSG_OPEN_REJ_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, - /* MSG_START_REJ_EVT */ - {AVDT_SCB_HDL_START_RSP, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, - /* MSG_SUSPEND_REJ_EVT */ - {AVDT_SCB_HDL_SUSPEND_RSP, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, - /* TC_TOUT_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, - /* TC_OPEN_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, - /* TC_CLOSE_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, - /* TC_CONG_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, - /* TC_DATA_EVT */ - {AVDT_SCB_DROP_PKT, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, - /* CC_CLOSE_EVT */ - {AVDT_SCB_CLR_VARS, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}}; + /* Event */ + /* Action 1 Action 2 Next state */ + /* API_REMOVE_EVT */ + {AVDT_SCB_DEALLOC, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, + /* API_WRITE_REQ_EVT */ + {AVDT_SCB_FREE_PKT, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, + /* API_GETCONFIG_REQ_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, + /* API_DELAY_RPT_REQ_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, + /* API_SETCONFIG_REQ_EVT */ + {AVDT_SCB_SND_SETCONFIG_REQ, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, + /* API_OPEN_REQ_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, + /* API_CLOSE_REQ_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, + /* API_RECONFIG_REQ_EVT */ + {AVDT_SCB_CB_ERR, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, + /* API_SECURITY_REQ_EVT */ + {AVDT_SCB_CB_ERR, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, + /* API_ABORT_REQ_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, + /* API_GETCONFIG_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, + /* API_SETCONFIG_RSP_EVT */ + {AVDT_SCB_SND_SETCONFIG_RSP, AVDT_SCB_SND_SNK_DELAY_RPT_REQ, AVDT_SCB_CONF_ST}, + /* API_SETCONFIG_REJ_EVT */ + {AVDT_SCB_SND_SETCONFIG_REJ, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, + /* API_OPEN_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, + /* API_CLOSE_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, + /* API_RECONFIG_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, + /* API_SECURITY_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, + /* API_ABORT_RSP_EVT */ + {AVDT_SCB_SND_ABORT_RSP, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, + /* MSG_SETCONFIG_CMD_EVT */ + {AVDT_SCB_HDL_SETCONFIG_CMD, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, + /* MSG_GETCONFIG_CMD_EVT */ + {AVDT_SCB_REJ_STATE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, + /* MSG_OPEN_CMD_EVT */ + {AVDT_SCB_REJ_STATE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, + /* MSG_START_CMD_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, + /* MSG_SUSPEND_CMD_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, + /* MSG_CLOSE_CMD_EVT */ + {AVDT_SCB_REJ_STATE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, + /* MSG_ABORT_CMD_EVT */ + {AVDT_SCB_HDL_ABORT_CMD, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, + /* MSG_RECONFIG_CMD_EVT */ + {AVDT_SCB_REJ_NOT_IN_USE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, + /* MSG_SECURITY_CMD_EVT */ + {AVDT_SCB_REJ_STATE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, + /* MSG_DELAY_RPT_CMD_EVT */ + {AVDT_SCB_REJ_STATE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, + /* MSG_DELAY_RPT_RSP_EVT */ + {AVDT_SCB_HDL_DELAY_RPT_RSP, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, + /* MSG_SETCONFIG_RSP_EVT */ + {AVDT_SCB_HDL_SETCONFIG_RSP, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, + /* MSG_GETCONFIG_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, + /* MSG_OPEN_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, + /* MSG_START_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, + /* MSG_SUSPEND_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, + /* MSG_CLOSE_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, + /* MSG_ABORT_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, + /* MSG_RECONFIG_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, + /* MSG_SECURITY_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, + /* MSG_SETCONFIG_REJ_EVT */ + {AVDT_SCB_HDL_SETCONFIG_REJ, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, + /* MSG_OPEN_REJ_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, + /* MSG_START_REJ_EVT */ + {AVDT_SCB_HDL_START_RSP, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, + /* MSG_SUSPEND_REJ_EVT */ + {AVDT_SCB_HDL_SUSPEND_RSP, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, + /* TC_TOUT_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, + /* TC_OPEN_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, + /* TC_CLOSE_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, + /* TC_CONG_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, + /* TC_DATA_EVT */ + {AVDT_SCB_DROP_PKT, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, + /* CC_CLOSE_EVT */ + {AVDT_SCB_CLR_VARS, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}}; /* state table for configured state */ const uint8_t avdt_scb_st_conf[][AVDT_SCB_NUM_COLS] = { - /* Event */ - /* Action 1 Action 2 Next state */ - /* API_REMOVE_EVT */ - {AVDT_SCB_SND_ABORT_REQ, AVDT_SCB_SET_REMOVE, AVDT_SCB_CONF_ST}, - /* API_WRITE_REQ_EVT */ - {AVDT_SCB_FREE_PKT, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, - /* API_GETCONFIG_REQ_EVT */ - {AVDT_SCB_SND_GETCONFIG_REQ, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, - /* API_DELAY_RPT_REQ_EVT */ - {AVDT_SCB_SND_DELAY_RPT_REQ, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, - /* API_SETCONFIG_REQ_EVT */ - {AVDT_SCB_CB_ERR, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, - /* API_OPEN_REQ_EVT */ - {AVDT_SCB_SND_OPEN_REQ, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, - /* API_CLOSE_REQ_EVT */ - {AVDT_SCB_SND_ABORT_REQ, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, - /* API_RECONFIG_REQ_EVT */ - {AVDT_SCB_CB_ERR, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, - /* API_SECURITY_REQ_EVT */ - {AVDT_SCB_SND_SECURITY_REQ, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, - /* API_ABORT_REQ_EVT */ - {AVDT_SCB_SND_ABORT_REQ, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, - /* API_GETCONFIG_RSP_EVT */ - {AVDT_SCB_SND_GETCONFIG_RSP, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, - /* API_SETCONFIG_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, - /* API_SETCONFIG_REJ_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, - /* API_OPEN_RSP_EVT */ - {AVDT_SCB_SND_OPEN_RSP, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, - /* API_CLOSE_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, - /* API_RECONFIG_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, - /* API_SECURITY_RSP_EVT */ - {AVDT_SCB_SND_SECURITY_RSP, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, - /* API_ABORT_RSP_EVT */ - {AVDT_SCB_SND_ABORT_RSP, AVDT_SCB_HDL_TC_CLOSE, AVDT_SCB_IDLE_ST}, - /* MSG_SETCONFIG_CMD_EVT */ - {AVDT_SCB_REJ_IN_USE, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, - /* MSG_GETCONFIG_CMD_EVT */ - {AVDT_SCB_HDL_GETCONFIG_CMD, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, - /* MSG_OPEN_CMD_EVT */ - {AVDT_SCB_HDL_OPEN_CMD, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, - /* MSG_START_CMD_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, - /* MSG_SUSPEND_CMD_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, - /* MSG_CLOSE_CMD_EVT */ - {AVDT_SCB_REJ_STATE, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, - /* MSG_ABORT_CMD_EVT */ - {AVDT_SCB_HDL_ABORT_CMD, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, - /* MSG_RECONFIG_CMD_EVT */ - {AVDT_SCB_REJ_STATE, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, - /* MSG_SECURITY_CMD_EVT */ - {AVDT_SCB_HDL_SECURITY_CMD, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, - /* MSG_DELAY_RPT_CMD_EVT */ - {AVDT_SCB_HDL_DELAY_RPT_CMD, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, - /* MSG_DELAY_RPT_RSP_EVT */ - {AVDT_SCB_HDL_DELAY_RPT_RSP, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, - /* MSG_SETCONFIG_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, - /* MSG_GETCONFIG_RSP_EVT */ - {AVDT_SCB_HDL_GETCONFIG_RSP, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, - /* MSG_OPEN_RSP_EVT */ - {AVDT_SCB_HDL_OPEN_RSP, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, - /* MSG_START_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, - /* MSG_SUSPEND_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, - /* MSG_CLOSE_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, - /* MSG_ABORT_RSP_EVT */ - {AVDT_SCB_HDL_ABORT_RSP, AVDT_SCB_HDL_TC_CLOSE, AVDT_SCB_IDLE_ST}, - /* MSG_RECONFIG_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, - /* MSG_SECURITY_RSP_EVT */ - {AVDT_SCB_HDL_SECURITY_RSP, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, - /* MSG_SETCONFIG_REJ_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, - /* MSG_OPEN_REJ_EVT */ - {AVDT_SCB_HDL_OPEN_REJ, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, - /* MSG_START_REJ_EVT */ - {AVDT_SCB_HDL_START_RSP, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, - /* MSG_SUSPEND_REJ_EVT */ - {AVDT_SCB_HDL_SUSPEND_RSP, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, - /* TC_TOUT_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, - /* TC_OPEN_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, - /* TC_CLOSE_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, - /* TC_CONG_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, - /* TC_DATA_EVT */ - {AVDT_SCB_DROP_PKT, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, - /* CC_CLOSE_EVT */ - {AVDT_SCB_HDL_TC_CLOSE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}}; + /* Event */ + /* Action 1 Action 2 Next state */ + /* API_REMOVE_EVT */ + {AVDT_SCB_SND_ABORT_REQ, AVDT_SCB_SET_REMOVE, AVDT_SCB_CONF_ST}, + /* API_WRITE_REQ_EVT */ + {AVDT_SCB_FREE_PKT, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, + /* API_GETCONFIG_REQ_EVT */ + {AVDT_SCB_SND_GETCONFIG_REQ, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, + /* API_DELAY_RPT_REQ_EVT */ + {AVDT_SCB_SND_DELAY_RPT_REQ, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, + /* API_SETCONFIG_REQ_EVT */ + {AVDT_SCB_CB_ERR, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, + /* API_OPEN_REQ_EVT */ + {AVDT_SCB_SND_OPEN_REQ, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, + /* API_CLOSE_REQ_EVT */ + {AVDT_SCB_SND_ABORT_REQ, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, + /* API_RECONFIG_REQ_EVT */ + {AVDT_SCB_CB_ERR, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, + /* API_SECURITY_REQ_EVT */ + {AVDT_SCB_SND_SECURITY_REQ, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, + /* API_ABORT_REQ_EVT */ + {AVDT_SCB_SND_ABORT_REQ, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, + /* API_GETCONFIG_RSP_EVT */ + {AVDT_SCB_SND_GETCONFIG_RSP, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, + /* API_SETCONFIG_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, + /* API_SETCONFIG_REJ_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, + /* API_OPEN_RSP_EVT */ + {AVDT_SCB_SND_OPEN_RSP, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, + /* API_CLOSE_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, + /* API_RECONFIG_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, + /* API_SECURITY_RSP_EVT */ + {AVDT_SCB_SND_SECURITY_RSP, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, + /* API_ABORT_RSP_EVT */ + {AVDT_SCB_SND_ABORT_RSP, AVDT_SCB_HDL_TC_CLOSE, AVDT_SCB_IDLE_ST}, + /* MSG_SETCONFIG_CMD_EVT */ + {AVDT_SCB_REJ_IN_USE, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, + /* MSG_GETCONFIG_CMD_EVT */ + {AVDT_SCB_HDL_GETCONFIG_CMD, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, + /* MSG_OPEN_CMD_EVT */ + {AVDT_SCB_HDL_OPEN_CMD, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, + /* MSG_START_CMD_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, + /* MSG_SUSPEND_CMD_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, + /* MSG_CLOSE_CMD_EVT */ + {AVDT_SCB_REJ_STATE, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, + /* MSG_ABORT_CMD_EVT */ + {AVDT_SCB_HDL_ABORT_CMD, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, + /* MSG_RECONFIG_CMD_EVT */ + {AVDT_SCB_REJ_STATE, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, + /* MSG_SECURITY_CMD_EVT */ + {AVDT_SCB_HDL_SECURITY_CMD, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, + /* MSG_DELAY_RPT_CMD_EVT */ + {AVDT_SCB_HDL_DELAY_RPT_CMD, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, + /* MSG_DELAY_RPT_RSP_EVT */ + {AVDT_SCB_HDL_DELAY_RPT_RSP, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, + /* MSG_SETCONFIG_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, + /* MSG_GETCONFIG_RSP_EVT */ + {AVDT_SCB_HDL_GETCONFIG_RSP, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, + /* MSG_OPEN_RSP_EVT */ + {AVDT_SCB_HDL_OPEN_RSP, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, + /* MSG_START_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, + /* MSG_SUSPEND_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, + /* MSG_CLOSE_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, + /* MSG_ABORT_RSP_EVT */ + {AVDT_SCB_HDL_ABORT_RSP, AVDT_SCB_HDL_TC_CLOSE, AVDT_SCB_IDLE_ST}, + /* MSG_RECONFIG_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, + /* MSG_SECURITY_RSP_EVT */ + {AVDT_SCB_HDL_SECURITY_RSP, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, + /* MSG_SETCONFIG_REJ_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, + /* MSG_OPEN_REJ_EVT */ + {AVDT_SCB_HDL_OPEN_REJ, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, + /* MSG_START_REJ_EVT */ + {AVDT_SCB_HDL_START_RSP, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, + /* MSG_SUSPEND_REJ_EVT */ + {AVDT_SCB_HDL_SUSPEND_RSP, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, + /* TC_TOUT_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, + /* TC_OPEN_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, + /* TC_CLOSE_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, + /* TC_CONG_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, + /* TC_DATA_EVT */ + {AVDT_SCB_DROP_PKT, AVDT_SCB_IGNORE, AVDT_SCB_CONF_ST}, + /* CC_CLOSE_EVT */ + {AVDT_SCB_HDL_TC_CLOSE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}}; /* state table for opening state */ const uint8_t avdt_scb_st_opening[][AVDT_SCB_NUM_COLS] = { - /* Event */ - /* Action 1 Action 2 Next state */ - /* API_REMOVE_EVT */ - {AVDT_SCB_SND_CLOSE_REQ, AVDT_SCB_SET_REMOVE, AVDT_SCB_CLOSING_ST}, - /* API_WRITE_REQ_EVT */ - {AVDT_SCB_FREE_PKT, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, - /* API_GETCONFIG_REQ_EVT */ - {AVDT_SCB_SND_GETCONFIG_REQ, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, - /* API_DELAY_RPT_REQ_EVT */ - {AVDT_SCB_SND_DELAY_RPT_REQ, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, - /* API_SETCONFIG_REQ_EVT */ - {AVDT_SCB_CB_ERR, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, - /* API_OPEN_REQ_EVT */ - {AVDT_SCB_CB_ERR, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, - /* API_CLOSE_REQ_EVT */ - {AVDT_SCB_SND_CLOSE_REQ, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, - /* API_RECONFIG_REQ_EVT */ - {AVDT_SCB_CB_ERR, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, - /* API_SECURITY_REQ_EVT */ - {AVDT_SCB_SND_SECURITY_REQ, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, - /* API_ABORT_REQ_EVT */ - {AVDT_SCB_SND_ABORT_REQ, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, - /* API_GETCONFIG_RSP_EVT */ - {AVDT_SCB_SND_GETCONFIG_RSP, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, - /* API_SETCONFIG_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, - /* API_SETCONFIG_REJ_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, - /* API_OPEN_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, - /* API_CLOSE_RSP_EVT */ - {AVDT_SCB_SND_CLOSE_RSP, AVDT_SCB_SND_TC_CLOSE, AVDT_SCB_CLOSING_ST}, - /* API_RECONFIG_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, - /* API_SECURITY_RSP_EVT */ - {AVDT_SCB_SND_SECURITY_RSP, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, - /* API_ABORT_RSP_EVT */ - {AVDT_SCB_SND_ABORT_RSP, AVDT_SCB_SND_TC_CLOSE, AVDT_SCB_CLOSING_ST}, - /* MSG_SETCONFIG_CMD_EVT */ - {AVDT_SCB_REJ_STATE, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, - /* MSG_GETCONFIG_CMD_EVT */ - {AVDT_SCB_HDL_GETCONFIG_CMD, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, - /* MSG_OPEN_CMD_EVT */ - {AVDT_SCB_REJ_STATE, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, - /* MSG_START_CMD_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, - /* MSG_SUSPEND_CMD_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, - /* MSG_CLOSE_CMD_EVT */ - {AVDT_SCB_HDL_CLOSE_CMD, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, - /* MSG_ABORT_CMD_EVT */ - {AVDT_SCB_HDL_ABORT_CMD, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, - /* MSG_RECONFIG_CMD_EVT */ - {AVDT_SCB_REJ_STATE, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, - /* MSG_SECURITY_CMD_EVT */ - {AVDT_SCB_HDL_SECURITY_CMD, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, - /* MSG_DELAY_RPT_CMD_EVT */ - {AVDT_SCB_HDL_DELAY_RPT_CMD, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, - /* MSG_DELAY_RPT_RSP_EVT */ - {AVDT_SCB_HDL_DELAY_RPT_RSP, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, - /* MSG_SETCONFIG_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, - /* MSG_GETCONFIG_RSP_EVT */ - {AVDT_SCB_HDL_GETCONFIG_RSP, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, - /* MSG_OPEN_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, - /* MSG_START_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, - /* MSG_SUSPEND_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, - /* MSG_CLOSE_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, - /* MSG_ABORT_RSP_EVT */ - {AVDT_SCB_SND_TC_CLOSE, AVDT_SCB_HDL_ABORT_RSP, AVDT_SCB_CLOSING_ST}, - /* MSG_RECONFIG_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, - /* MSG_SECURITY_RSP_EVT */ - {AVDT_SCB_HDL_SECURITY_RSP, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, - /* MSG_SETCONFIG_REJ_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, - /* MSG_OPEN_REJ_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, - /* MSG_START_REJ_EVT */ - {AVDT_SCB_HDL_START_RSP, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, - /* MSG_SUSPEND_REJ_EVT */ - {AVDT_SCB_HDL_SUSPEND_RSP, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, - /* TC_TOUT_EVT */ - {AVDT_SCB_SND_ABORT_REQ, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, - /* TC_OPEN_EVT */ - {AVDT_SCB_HDL_TC_OPEN, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, - /* TC_CLOSE_EVT */ - {AVDT_SCB_HDL_TC_CLOSE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, - /* TC_CONG_EVT */ - {AVDT_SCB_CONG_STATE, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, - /* TC_DATA_EVT */ - {AVDT_SCB_DROP_PKT, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, - /* CC_CLOSE_EVT */ - {AVDT_SCB_SND_TC_CLOSE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}}; + /* Event */ + /* Action 1 Action 2 Next state */ + /* API_REMOVE_EVT */ + {AVDT_SCB_SND_CLOSE_REQ, AVDT_SCB_SET_REMOVE, AVDT_SCB_CLOSING_ST}, + /* API_WRITE_REQ_EVT */ + {AVDT_SCB_FREE_PKT, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, + /* API_GETCONFIG_REQ_EVT */ + {AVDT_SCB_SND_GETCONFIG_REQ, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, + /* API_DELAY_RPT_REQ_EVT */ + {AVDT_SCB_SND_DELAY_RPT_REQ, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, + /* API_SETCONFIG_REQ_EVT */ + {AVDT_SCB_CB_ERR, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, + /* API_OPEN_REQ_EVT */ + {AVDT_SCB_CB_ERR, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, + /* API_CLOSE_REQ_EVT */ + {AVDT_SCB_SND_CLOSE_REQ, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, + /* API_RECONFIG_REQ_EVT */ + {AVDT_SCB_CB_ERR, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, + /* API_SECURITY_REQ_EVT */ + {AVDT_SCB_SND_SECURITY_REQ, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, + /* API_ABORT_REQ_EVT */ + {AVDT_SCB_SND_ABORT_REQ, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, + /* API_GETCONFIG_RSP_EVT */ + {AVDT_SCB_SND_GETCONFIG_RSP, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, + /* API_SETCONFIG_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, + /* API_SETCONFIG_REJ_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, + /* API_OPEN_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, + /* API_CLOSE_RSP_EVT */ + {AVDT_SCB_SND_CLOSE_RSP, AVDT_SCB_SND_TC_CLOSE, AVDT_SCB_CLOSING_ST}, + /* API_RECONFIG_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, + /* API_SECURITY_RSP_EVT */ + {AVDT_SCB_SND_SECURITY_RSP, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, + /* API_ABORT_RSP_EVT */ + {AVDT_SCB_SND_ABORT_RSP, AVDT_SCB_SND_TC_CLOSE, AVDT_SCB_CLOSING_ST}, + /* MSG_SETCONFIG_CMD_EVT */ + {AVDT_SCB_REJ_STATE, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, + /* MSG_GETCONFIG_CMD_EVT */ + {AVDT_SCB_HDL_GETCONFIG_CMD, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, + /* MSG_OPEN_CMD_EVT */ + {AVDT_SCB_REJ_STATE, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, + /* MSG_START_CMD_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, + /* MSG_SUSPEND_CMD_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, + /* MSG_CLOSE_CMD_EVT */ + {AVDT_SCB_HDL_CLOSE_CMD, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, + /* MSG_ABORT_CMD_EVT */ + {AVDT_SCB_HDL_ABORT_CMD, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, + /* MSG_RECONFIG_CMD_EVT */ + {AVDT_SCB_REJ_STATE, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, + /* MSG_SECURITY_CMD_EVT */ + {AVDT_SCB_HDL_SECURITY_CMD, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, + /* MSG_DELAY_RPT_CMD_EVT */ + {AVDT_SCB_HDL_DELAY_RPT_CMD, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, + /* MSG_DELAY_RPT_RSP_EVT */ + {AVDT_SCB_HDL_DELAY_RPT_RSP, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, + /* MSG_SETCONFIG_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, + /* MSG_GETCONFIG_RSP_EVT */ + {AVDT_SCB_HDL_GETCONFIG_RSP, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, + /* MSG_OPEN_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, + /* MSG_START_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, + /* MSG_SUSPEND_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, + /* MSG_CLOSE_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, + /* MSG_ABORT_RSP_EVT */ + {AVDT_SCB_SND_TC_CLOSE, AVDT_SCB_HDL_ABORT_RSP, AVDT_SCB_CLOSING_ST}, + /* MSG_RECONFIG_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, + /* MSG_SECURITY_RSP_EVT */ + {AVDT_SCB_HDL_SECURITY_RSP, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, + /* MSG_SETCONFIG_REJ_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, + /* MSG_OPEN_REJ_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, + /* MSG_START_REJ_EVT */ + {AVDT_SCB_HDL_START_RSP, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, + /* MSG_SUSPEND_REJ_EVT */ + {AVDT_SCB_HDL_SUSPEND_RSP, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, + /* TC_TOUT_EVT */ + {AVDT_SCB_SND_ABORT_REQ, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, + /* TC_OPEN_EVT */ + {AVDT_SCB_HDL_TC_OPEN, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, + /* TC_CLOSE_EVT */ + {AVDT_SCB_HDL_TC_CLOSE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, + /* TC_CONG_EVT */ + {AVDT_SCB_CONG_STATE, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, + /* TC_DATA_EVT */ + {AVDT_SCB_DROP_PKT, AVDT_SCB_IGNORE, AVDT_SCB_OPENING_ST}, + /* CC_CLOSE_EVT */ + {AVDT_SCB_SND_TC_CLOSE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}}; /* state table for open state */ const uint8_t avdt_scb_st_open[][AVDT_SCB_NUM_COLS] = { - /* Event */ - /* Action 1 Action 2 Next state */ - /* API_REMOVE_EVT */ - {AVDT_SCB_SND_CLOSE_REQ, AVDT_SCB_SET_REMOVE, AVDT_SCB_CLOSING_ST}, - /* API_WRITE_REQ_EVT */ - {AVDT_SCB_FREE_PKT, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, - /* API_GETCONFIG_REQ_EVT */ - {AVDT_SCB_SND_GETCONFIG_REQ, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, - /* API_DELAY_RPT_REQ_EVT */ - {AVDT_SCB_SND_DELAY_RPT_REQ, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, - /* API_SETCONFIG_REQ_EVT */ - {AVDT_SCB_CB_ERR, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, - /* API_OPEN_REQ_EVT */ - {AVDT_SCB_CB_ERR, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, - /* API_CLOSE_REQ_EVT */ - {AVDT_SCB_SND_CLOSE_REQ, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, - /* API_RECONFIG_REQ_EVT */ - {AVDT_SCB_SND_RECONFIG_REQ, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, - /* API_SECURITY_REQ_EVT */ - {AVDT_SCB_SND_SECURITY_REQ, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, - /* API_ABORT_REQ_EVT */ - {AVDT_SCB_SND_ABORT_REQ, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, - /* API_GETCONFIG_RSP_EVT */ - {AVDT_SCB_SND_GETCONFIG_RSP, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, - /* API_SETCONFIG_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, - /* API_SETCONFIG_REJ_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, - /* API_OPEN_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, - /* API_CLOSE_RSP_EVT */ - {AVDT_SCB_SND_CLOSE_RSP, AVDT_SCB_TC_TIMER, AVDT_SCB_CLOSING_ST}, - /* API_RECONFIG_RSP_EVT */ - {AVDT_SCB_SND_RECONFIG_RSP, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, - /* API_SECURITY_RSP_EVT */ - {AVDT_SCB_SND_SECURITY_RSP, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, - /* API_ABORT_RSP_EVT */ - {AVDT_SCB_SND_ABORT_RSP, AVDT_SCB_TC_TIMER, AVDT_SCB_CLOSING_ST}, - /* MSG_SETCONFIG_CMD_EVT */ - {AVDT_SCB_REJ_STATE, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, - /* MSG_GETCONFIG_CMD_EVT */ - {AVDT_SCB_HDL_GETCONFIG_CMD, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, - /* MSG_OPEN_CMD_EVT */ - {AVDT_SCB_REJ_STATE, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, - /* MSG_START_CMD_EVT */ - {AVDT_SCB_HDL_START_CMD, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, - /* MSG_SUSPEND_CMD_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, - /* MSG_CLOSE_CMD_EVT */ - {AVDT_SCB_HDL_CLOSE_CMD, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, - /* MSG_ABORT_CMD_EVT */ - {AVDT_SCB_HDL_ABORT_CMD, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, - /* MSG_RECONFIG_CMD_EVT */ - {AVDT_SCB_HDL_RECONFIG_CMD, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, - /* MSG_SECURITY_CMD_EVT */ - {AVDT_SCB_HDL_SECURITY_CMD, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, - /* MSG_DELAY_RPT_CMD_EVT */ - {AVDT_SCB_HDL_DELAY_RPT_CMD, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, - /* MSG_DELAY_RPT_RSP_EVT */ - {AVDT_SCB_HDL_DELAY_RPT_RSP, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, - /* MSG_SETCONFIG_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, - /* MSG_GETCONFIG_RSP_EVT */ - {AVDT_SCB_HDL_GETCONFIG_RSP, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, - /* MSG_OPEN_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, - /* MSG_START_RSP_EVT */ - {AVDT_SCB_HDL_START_RSP, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, - /* MSG_SUSPEND_RSP_EVT */ - {AVDT_SCB_HDL_SUSPEND_RSP, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, - /* MSG_CLOSE_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, - /* MSG_ABORT_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, - /* MSG_RECONFIG_RSP_EVT */ - {AVDT_SCB_HDL_RECONFIG_RSP, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, - /* MSG_SECURITY_RSP_EVT */ - {AVDT_SCB_HDL_SECURITY_RSP, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, - /* MSG_SETCONFIG_REJ_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, - /* MSG_OPEN_REJ_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, - /* MSG_START_REJ_EVT */ - {AVDT_SCB_HDL_START_RSP, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, - /* MSG_SUSPEND_REJ_EVT */ - {AVDT_SCB_HDL_SUSPEND_RSP, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, - /* TC_TOUT_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, - /* TC_OPEN_EVT */ - {AVDT_SCB_HDL_TC_OPEN_STO, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, - /* TC_CLOSE_EVT */ - {AVDT_SCB_HDL_TC_CLOSE_STO, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, - /* TC_CONG_EVT */ - {AVDT_SCB_CONG_STATE, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, - /* TC_DATA_EVT */ - {AVDT_SCB_DROP_PKT, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, - /* CC_CLOSE_EVT */ - {AVDT_SCB_SND_TC_CLOSE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}}; + /* Event */ + /* Action 1 Action 2 Next state */ + /* API_REMOVE_EVT */ + {AVDT_SCB_SND_CLOSE_REQ, AVDT_SCB_SET_REMOVE, AVDT_SCB_CLOSING_ST}, + /* API_WRITE_REQ_EVT */ + {AVDT_SCB_FREE_PKT, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, + /* API_GETCONFIG_REQ_EVT */ + {AVDT_SCB_SND_GETCONFIG_REQ, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, + /* API_DELAY_RPT_REQ_EVT */ + {AVDT_SCB_SND_DELAY_RPT_REQ, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, + /* API_SETCONFIG_REQ_EVT */ + {AVDT_SCB_CB_ERR, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, + /* API_OPEN_REQ_EVT */ + {AVDT_SCB_CB_ERR, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, + /* API_CLOSE_REQ_EVT */ + {AVDT_SCB_SND_CLOSE_REQ, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, + /* API_RECONFIG_REQ_EVT */ + {AVDT_SCB_SND_RECONFIG_REQ, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, + /* API_SECURITY_REQ_EVT */ + {AVDT_SCB_SND_SECURITY_REQ, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, + /* API_ABORT_REQ_EVT */ + {AVDT_SCB_SND_ABORT_REQ, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, + /* API_GETCONFIG_RSP_EVT */ + {AVDT_SCB_SND_GETCONFIG_RSP, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, + /* API_SETCONFIG_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, + /* API_SETCONFIG_REJ_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, + /* API_OPEN_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, + /* API_CLOSE_RSP_EVT */ + {AVDT_SCB_SND_CLOSE_RSP, AVDT_SCB_TC_TIMER, AVDT_SCB_CLOSING_ST}, + /* API_RECONFIG_RSP_EVT */ + {AVDT_SCB_SND_RECONFIG_RSP, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, + /* API_SECURITY_RSP_EVT */ + {AVDT_SCB_SND_SECURITY_RSP, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, + /* API_ABORT_RSP_EVT */ + {AVDT_SCB_SND_ABORT_RSP, AVDT_SCB_TC_TIMER, AVDT_SCB_CLOSING_ST}, + /* MSG_SETCONFIG_CMD_EVT */ + {AVDT_SCB_REJ_STATE, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, + /* MSG_GETCONFIG_CMD_EVT */ + {AVDT_SCB_HDL_GETCONFIG_CMD, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, + /* MSG_OPEN_CMD_EVT */ + {AVDT_SCB_REJ_STATE, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, + /* MSG_START_CMD_EVT */ + {AVDT_SCB_HDL_START_CMD, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, + /* MSG_SUSPEND_CMD_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, + /* MSG_CLOSE_CMD_EVT */ + {AVDT_SCB_HDL_CLOSE_CMD, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, + /* MSG_ABORT_CMD_EVT */ + {AVDT_SCB_HDL_ABORT_CMD, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, + /* MSG_RECONFIG_CMD_EVT */ + {AVDT_SCB_HDL_RECONFIG_CMD, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, + /* MSG_SECURITY_CMD_EVT */ + {AVDT_SCB_HDL_SECURITY_CMD, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, + /* MSG_DELAY_RPT_CMD_EVT */ + {AVDT_SCB_HDL_DELAY_RPT_CMD, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, + /* MSG_DELAY_RPT_RSP_EVT */ + {AVDT_SCB_HDL_DELAY_RPT_RSP, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, + /* MSG_SETCONFIG_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, + /* MSG_GETCONFIG_RSP_EVT */ + {AVDT_SCB_HDL_GETCONFIG_RSP, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, + /* MSG_OPEN_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, + /* MSG_START_RSP_EVT */ + {AVDT_SCB_HDL_START_RSP, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, + /* MSG_SUSPEND_RSP_EVT */ + {AVDT_SCB_HDL_SUSPEND_RSP, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, + /* MSG_CLOSE_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, + /* MSG_ABORT_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, + /* MSG_RECONFIG_RSP_EVT */ + {AVDT_SCB_HDL_RECONFIG_RSP, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, + /* MSG_SECURITY_RSP_EVT */ + {AVDT_SCB_HDL_SECURITY_RSP, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, + /* MSG_SETCONFIG_REJ_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, + /* MSG_OPEN_REJ_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, + /* MSG_START_REJ_EVT */ + {AVDT_SCB_HDL_START_RSP, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, + /* MSG_SUSPEND_REJ_EVT */ + {AVDT_SCB_HDL_SUSPEND_RSP, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, + /* TC_TOUT_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, + /* TC_OPEN_EVT */ + {AVDT_SCB_HDL_TC_OPEN_STO, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, + /* TC_CLOSE_EVT */ + {AVDT_SCB_HDL_TC_CLOSE_STO, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, + /* TC_CONG_EVT */ + {AVDT_SCB_CONG_STATE, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, + /* TC_DATA_EVT */ + {AVDT_SCB_DROP_PKT, AVDT_SCB_IGNORE, AVDT_SCB_OPEN_ST}, + /* CC_CLOSE_EVT */ + {AVDT_SCB_SND_TC_CLOSE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}}; /* state table for streaming state */ const uint8_t avdt_scb_st_stream[][AVDT_SCB_NUM_COLS] = { - /* Event */ - /* Action 1 Action 2 Next state */ - /* API_REMOVE_EVT */ - {AVDT_SCB_SND_STREAM_CLOSE, AVDT_SCB_SET_REMOVE, AVDT_SCB_CLOSING_ST}, - /* API_WRITE_REQ_EVT */ - {AVDT_SCB_HDL_WRITE_REQ, AVDT_SCB_CHK_SND_PKT, AVDT_SCB_STREAM_ST}, - /* API_GETCONFIG_REQ_EVT */ - {AVDT_SCB_SND_GETCONFIG_REQ, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, - /* API_DELAY_RPT_REQ_EVT */ - {AVDT_SCB_SND_DELAY_RPT_REQ, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, - /* API_SETCONFIG_REQ_EVT */ - {AVDT_SCB_CB_ERR, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, - /* API_OPEN_REQ_EVT */ - {AVDT_SCB_CB_ERR, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, - /* API_CLOSE_REQ_EVT */ - {AVDT_SCB_SND_STREAM_CLOSE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, - /* API_RECONFIG_REQ_EVT */ - {AVDT_SCB_CB_ERR, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, - /* API_SECURITY_REQ_EVT */ - {AVDT_SCB_SND_SECURITY_REQ, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, - /* API_ABORT_REQ_EVT */ - {AVDT_SCB_SND_ABORT_REQ, AVDT_SCB_CLR_PKT, AVDT_SCB_CLOSING_ST}, - /* API_GETCONFIG_RSP_EVT */ - {AVDT_SCB_SND_GETCONFIG_RSP, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, - /* API_SETCONFIG_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, - /* API_SETCONFIG_REJ_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, - /* API_OPEN_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, - /* API_CLOSE_RSP_EVT */ - {AVDT_SCB_SND_CLOSE_RSP, AVDT_SCB_TC_TIMER, AVDT_SCB_CLOSING_ST}, - /* API_RECONFIG_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, - /* API_SECURITY_RSP_EVT */ - {AVDT_SCB_SND_SECURITY_RSP, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, - /* API_ABORT_RSP_EVT */ - {AVDT_SCB_SND_ABORT_RSP, AVDT_SCB_TC_TIMER, AVDT_SCB_CLOSING_ST}, - /* MSG_SETCONFIG_CMD_EVT */ - {AVDT_SCB_REJ_STATE, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, - /* MSG_GETCONFIG_CMD_EVT */ - {AVDT_SCB_HDL_GETCONFIG_CMD, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, - /* MSG_OPEN_CMD_EVT */ - {AVDT_SCB_REJ_STATE, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, - /* MSG_START_CMD_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, - /* MSG_SUSPEND_CMD_EVT */ - {AVDT_SCB_HDL_SUSPEND_CMD, AVDT_SCB_CLR_PKT, AVDT_SCB_OPEN_ST}, - /* MSG_CLOSE_CMD_EVT */ - {AVDT_SCB_HDL_CLOSE_CMD, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, - /* MSG_ABORT_CMD_EVT */ - {AVDT_SCB_HDL_ABORT_CMD, AVDT_SCB_CLR_PKT, AVDT_SCB_STREAM_ST}, - /* MSG_RECONFIG_CMD_EVT */ - {AVDT_SCB_REJ_STATE, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, - /* MSG_SECURITY_CMD_EVT */ - {AVDT_SCB_HDL_SECURITY_CMD, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, - /* MSG_DELAY_RPT_CMD_EVT */ - {AVDT_SCB_HDL_DELAY_RPT_CMD, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, - /* MSG_DELAY_RPT_RSP_EVT */ - {AVDT_SCB_HDL_DELAY_RPT_RSP, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, - /* MSG_SETCONFIG_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, - /* MSG_GETCONFIG_RSP_EVT */ - {AVDT_SCB_HDL_GETCONFIG_RSP, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, - /* MSG_OPEN_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, - /* MSG_START_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, - /* MSG_SUSPEND_RSP_EVT */ - {AVDT_SCB_HDL_SUSPEND_RSP, AVDT_SCB_CLR_PKT, AVDT_SCB_OPEN_ST}, - /* MSG_CLOSE_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, - /* MSG_ABORT_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, - /* MSG_RECONFIG_RSP_EVT */ - {AVDT_SCB_HDL_RECONFIG_RSP, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, - /* MSG_SECURITY_RSP_EVT */ - {AVDT_SCB_HDL_SECURITY_RSP, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, - /* MSG_SETCONFIG_REJ_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, - /* MSG_OPEN_REJ_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, - /* MSG_START_REJ_EVT */ - {AVDT_SCB_HDL_START_RSP, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, - /* MSG_SUSPEND_REJ_EVT */ - {AVDT_SCB_HDL_SUSPEND_RSP, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, - /* TC_TOUT_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, - /* TC_OPEN_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, - /* TC_CLOSE_EVT */ - {AVDT_SCB_HDL_TC_CLOSE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, - /* TC_CONG_EVT */ - {AVDT_SCB_CONG_STATE, AVDT_SCB_CHK_SND_PKT, AVDT_SCB_STREAM_ST}, - /* TC_DATA_EVT */ - {AVDT_SCB_HDL_PKT, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, - /* CC_CLOSE_EVT */ - {AVDT_SCB_SND_TC_CLOSE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}}; + /* Event */ + /* Action 1 Action 2 Next state */ + /* API_REMOVE_EVT */ + {AVDT_SCB_SND_STREAM_CLOSE, AVDT_SCB_SET_REMOVE, AVDT_SCB_CLOSING_ST}, + /* API_WRITE_REQ_EVT */ + {AVDT_SCB_HDL_WRITE_REQ, AVDT_SCB_CHK_SND_PKT, AVDT_SCB_STREAM_ST}, + /* API_GETCONFIG_REQ_EVT */ + {AVDT_SCB_SND_GETCONFIG_REQ, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, + /* API_DELAY_RPT_REQ_EVT */ + {AVDT_SCB_SND_DELAY_RPT_REQ, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, + /* API_SETCONFIG_REQ_EVT */ + {AVDT_SCB_CB_ERR, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, + /* API_OPEN_REQ_EVT */ + {AVDT_SCB_CB_ERR, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, + /* API_CLOSE_REQ_EVT */ + {AVDT_SCB_SND_STREAM_CLOSE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, + /* API_RECONFIG_REQ_EVT */ + {AVDT_SCB_CB_ERR, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, + /* API_SECURITY_REQ_EVT */ + {AVDT_SCB_SND_SECURITY_REQ, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, + /* API_ABORT_REQ_EVT */ + {AVDT_SCB_SND_ABORT_REQ, AVDT_SCB_CLR_PKT, AVDT_SCB_CLOSING_ST}, + /* API_GETCONFIG_RSP_EVT */ + {AVDT_SCB_SND_GETCONFIG_RSP, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, + /* API_SETCONFIG_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, + /* API_SETCONFIG_REJ_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, + /* API_OPEN_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, + /* API_CLOSE_RSP_EVT */ + {AVDT_SCB_SND_CLOSE_RSP, AVDT_SCB_TC_TIMER, AVDT_SCB_CLOSING_ST}, + /* API_RECONFIG_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, + /* API_SECURITY_RSP_EVT */ + {AVDT_SCB_SND_SECURITY_RSP, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, + /* API_ABORT_RSP_EVT */ + {AVDT_SCB_SND_ABORT_RSP, AVDT_SCB_TC_TIMER, AVDT_SCB_CLOSING_ST}, + /* MSG_SETCONFIG_CMD_EVT */ + {AVDT_SCB_REJ_STATE, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, + /* MSG_GETCONFIG_CMD_EVT */ + {AVDT_SCB_HDL_GETCONFIG_CMD, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, + /* MSG_OPEN_CMD_EVT */ + {AVDT_SCB_REJ_STATE, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, + /* MSG_START_CMD_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, + /* MSG_SUSPEND_CMD_EVT */ + {AVDT_SCB_HDL_SUSPEND_CMD, AVDT_SCB_CLR_PKT, AVDT_SCB_OPEN_ST}, + /* MSG_CLOSE_CMD_EVT */ + {AVDT_SCB_HDL_CLOSE_CMD, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, + /* MSG_ABORT_CMD_EVT */ + {AVDT_SCB_HDL_ABORT_CMD, AVDT_SCB_CLR_PKT, AVDT_SCB_STREAM_ST}, + /* MSG_RECONFIG_CMD_EVT */ + {AVDT_SCB_REJ_STATE, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, + /* MSG_SECURITY_CMD_EVT */ + {AVDT_SCB_HDL_SECURITY_CMD, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, + /* MSG_DELAY_RPT_CMD_EVT */ + {AVDT_SCB_HDL_DELAY_RPT_CMD, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, + /* MSG_DELAY_RPT_RSP_EVT */ + {AVDT_SCB_HDL_DELAY_RPT_RSP, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, + /* MSG_SETCONFIG_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, + /* MSG_GETCONFIG_RSP_EVT */ + {AVDT_SCB_HDL_GETCONFIG_RSP, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, + /* MSG_OPEN_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, + /* MSG_START_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, + /* MSG_SUSPEND_RSP_EVT */ + {AVDT_SCB_HDL_SUSPEND_RSP, AVDT_SCB_CLR_PKT, AVDT_SCB_OPEN_ST}, + /* MSG_CLOSE_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, + /* MSG_ABORT_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, + /* MSG_RECONFIG_RSP_EVT */ + {AVDT_SCB_HDL_RECONFIG_RSP, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, + /* MSG_SECURITY_RSP_EVT */ + {AVDT_SCB_HDL_SECURITY_RSP, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, + /* MSG_SETCONFIG_REJ_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, + /* MSG_OPEN_REJ_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, + /* MSG_START_REJ_EVT */ + {AVDT_SCB_HDL_START_RSP, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, + /* MSG_SUSPEND_REJ_EVT */ + {AVDT_SCB_HDL_SUSPEND_RSP, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, + /* TC_TOUT_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, + /* TC_OPEN_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, + /* TC_CLOSE_EVT */ + {AVDT_SCB_HDL_TC_CLOSE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, + /* TC_CONG_EVT */ + {AVDT_SCB_CONG_STATE, AVDT_SCB_CHK_SND_PKT, AVDT_SCB_STREAM_ST}, + /* TC_DATA_EVT */ + {AVDT_SCB_HDL_PKT, AVDT_SCB_IGNORE, AVDT_SCB_STREAM_ST}, + /* CC_CLOSE_EVT */ + {AVDT_SCB_SND_TC_CLOSE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}}; /* state table for closing state */ const uint8_t avdt_scb_st_closing[][AVDT_SCB_NUM_COLS] = { - /* Event */ - /* Action 1 Action 2 Next state */ - /* API_REMOVE_EVT */ - {AVDT_SCB_SET_REMOVE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, - /* API_WRITE_REQ_EVT */ - {AVDT_SCB_FREE_PKT, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, - /* API_GETCONFIG_REQ_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, - /* API_DELAY_RPT_REQ_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, - /* API_SETCONFIG_REQ_EVT */ - {AVDT_SCB_CB_ERR, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, - /* API_OPEN_REQ_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, - /* API_CLOSE_REQ_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, - /* API_RECONFIG_REQ_EVT */ - {AVDT_SCB_CB_ERR, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, - /* API_SECURITY_REQ_EVT */ - {AVDT_SCB_CB_ERR, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, - /* API_ABORT_REQ_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, - /* API_GETCONFIG_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, - /* API_SETCONFIG_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, - /* API_SETCONFIG_REJ_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, - /* API_OPEN_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, - /* API_CLOSE_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, - /* API_RECONFIG_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, - /* API_SECURITY_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, - /* API_ABORT_RSP_EVT */ - {AVDT_SCB_SND_ABORT_RSP, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, - /* MSG_SETCONFIG_CMD_EVT */ - {AVDT_SCB_REJ_STATE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, - /* MSG_GETCONFIG_CMD_EVT */ - {AVDT_SCB_REJ_STATE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, - /* MSG_OPEN_CMD_EVT */ - {AVDT_SCB_REJ_STATE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, - /* MSG_START_CMD_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, - /* MSG_SUSPEND_CMD_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, - /* MSG_CLOSE_CMD_EVT */ - {AVDT_SCB_REJ_STATE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, - /* MSG_ABORT_CMD_EVT */ - {AVDT_SCB_HDL_ABORT_CMD, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, - /* MSG_RECONFIG_CMD_EVT */ - {AVDT_SCB_REJ_STATE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, - /* MSG_SECURITY_CMD_EVT */ - {AVDT_SCB_REJ_STATE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, - /* MSG_DELAY_RPT_CMD_EVT */ - {AVDT_SCB_REJ_STATE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, - /* MSG_DELAY_RPT_RSP_EVT */ - {AVDT_SCB_HDL_DELAY_RPT_RSP, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, - /* MSG_SETCONFIG_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, - /* MSG_GETCONFIG_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, - /* MSG_OPEN_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, - /* MSG_START_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, - /* MSG_SUSPEND_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, - /* MSG_CLOSE_RSP_EVT */ - {AVDT_SCB_SND_TC_CLOSE, AVDT_SCB_HDL_CLOSE_RSP, AVDT_SCB_CLOSING_ST}, - /* MSG_ABORT_RSP_EVT */ - {AVDT_SCB_SND_TC_CLOSE, AVDT_SCB_HDL_ABORT_RSP, AVDT_SCB_CLOSING_ST}, - /* MSG_RECONFIG_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, - /* MSG_SECURITY_RSP_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, - /* MSG_SETCONFIG_REJ_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, - /* MSG_OPEN_REJ_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, - /* MSG_START_REJ_EVT */ - {AVDT_SCB_HDL_START_RSP, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, - /* MSG_SUSPEND_REJ_EVT */ - {AVDT_SCB_HDL_SUSPEND_RSP, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, - /* TC_TOUT_EVT */ - {AVDT_SCB_SND_TC_CLOSE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, - /* TC_OPEN_EVT */ - {AVDT_SCB_SND_TC_CLOSE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, - /* TC_CLOSE_EVT */ - {AVDT_SCB_HDL_TC_CLOSE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, - /* TC_CONG_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, - /* TC_DATA_EVT */ - {AVDT_SCB_DROP_PKT, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, - /* CC_CLOSE_EVT */ - {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}}; + /* Event */ + /* Action 1 Action 2 Next state */ + /* API_REMOVE_EVT */ + {AVDT_SCB_SET_REMOVE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, + /* API_WRITE_REQ_EVT */ + {AVDT_SCB_FREE_PKT, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, + /* API_GETCONFIG_REQ_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, + /* API_DELAY_RPT_REQ_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, + /* API_SETCONFIG_REQ_EVT */ + {AVDT_SCB_CB_ERR, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, + /* API_OPEN_REQ_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, + /* API_CLOSE_REQ_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, + /* API_RECONFIG_REQ_EVT */ + {AVDT_SCB_CB_ERR, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, + /* API_SECURITY_REQ_EVT */ + {AVDT_SCB_CB_ERR, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, + /* API_ABORT_REQ_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, + /* API_GETCONFIG_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, + /* API_SETCONFIG_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, + /* API_SETCONFIG_REJ_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, + /* API_OPEN_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, + /* API_CLOSE_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, + /* API_RECONFIG_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, + /* API_SECURITY_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, + /* API_ABORT_RSP_EVT */ + {AVDT_SCB_SND_ABORT_RSP, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, + /* MSG_SETCONFIG_CMD_EVT */ + {AVDT_SCB_REJ_STATE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, + /* MSG_GETCONFIG_CMD_EVT */ + {AVDT_SCB_REJ_STATE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, + /* MSG_OPEN_CMD_EVT */ + {AVDT_SCB_REJ_STATE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, + /* MSG_START_CMD_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, + /* MSG_SUSPEND_CMD_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, + /* MSG_CLOSE_CMD_EVT */ + {AVDT_SCB_REJ_STATE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, + /* MSG_ABORT_CMD_EVT */ + {AVDT_SCB_HDL_ABORT_CMD, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, + /* MSG_RECONFIG_CMD_EVT */ + {AVDT_SCB_REJ_STATE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, + /* MSG_SECURITY_CMD_EVT */ + {AVDT_SCB_REJ_STATE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, + /* MSG_DELAY_RPT_CMD_EVT */ + {AVDT_SCB_REJ_STATE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, + /* MSG_DELAY_RPT_RSP_EVT */ + {AVDT_SCB_HDL_DELAY_RPT_RSP, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, + /* MSG_SETCONFIG_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, + /* MSG_GETCONFIG_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, + /* MSG_OPEN_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, + /* MSG_START_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, + /* MSG_SUSPEND_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, + /* MSG_CLOSE_RSP_EVT */ + {AVDT_SCB_SND_TC_CLOSE, AVDT_SCB_HDL_CLOSE_RSP, AVDT_SCB_CLOSING_ST}, + /* MSG_ABORT_RSP_EVT */ + {AVDT_SCB_SND_TC_CLOSE, AVDT_SCB_HDL_ABORT_RSP, AVDT_SCB_CLOSING_ST}, + /* MSG_RECONFIG_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, + /* MSG_SECURITY_RSP_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, + /* MSG_SETCONFIG_REJ_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, + /* MSG_OPEN_REJ_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, + /* MSG_START_REJ_EVT */ + {AVDT_SCB_HDL_START_RSP, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, + /* MSG_SUSPEND_REJ_EVT */ + {AVDT_SCB_HDL_SUSPEND_RSP, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, + /* TC_TOUT_EVT */ + {AVDT_SCB_SND_TC_CLOSE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, + /* TC_OPEN_EVT */ + {AVDT_SCB_SND_TC_CLOSE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, + /* TC_CLOSE_EVT */ + {AVDT_SCB_HDL_TC_CLOSE, AVDT_SCB_IGNORE, AVDT_SCB_IDLE_ST}, + /* TC_CONG_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, + /* TC_DATA_EVT */ + {AVDT_SCB_DROP_PKT, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}, + /* CC_CLOSE_EVT */ + {AVDT_SCB_IGNORE, AVDT_SCB_IGNORE, AVDT_SCB_CLOSING_ST}}; /* type for state table */ typedef const uint8_t (*tAVDT_SCB_ST_TBL)[AVDT_SCB_NUM_COLS]; /* state table */ -const tAVDT_SCB_ST_TBL avdt_scb_st_tbl[] = { - avdt_scb_st_idle, avdt_scb_st_conf, avdt_scb_st_opening, - avdt_scb_st_open, avdt_scb_st_stream, avdt_scb_st_closing}; +const tAVDT_SCB_ST_TBL avdt_scb_st_tbl[] = {avdt_scb_st_idle, avdt_scb_st_conf, + avdt_scb_st_opening, avdt_scb_st_open, + avdt_scb_st_stream, avdt_scb_st_closing}; /******************************************************************************* * @@ -763,9 +762,8 @@ void avdt_scb_event(AvdtpScb* p_scb, uint8_t event, tAVDT_SCB_EVT* p_data) { uint8_t action; #if (AVDT_DEBUG == TRUE) - log::verbose("SCB hdl={} event={}/{} state={} p_avdt_scb={} scb_index={}", - avdt_scb_to_hdl(p_scb), event, avdt_scb_evt_str[event], - avdt_scb_st_str[p_scb->state], fmt::ptr(p_scb), + log::verbose("SCB hdl={} event={}/{} state={} p_avdt_scb={} scb_index={}", avdt_scb_to_hdl(p_scb), + event, avdt_scb_evt_str[event], avdt_scb_st_str[p_scb->state], fmt::ptr(p_scb), p_scb->stream_config.scb_index); #endif @@ -778,8 +776,7 @@ void avdt_scb_event(AvdtpScb* p_scb, uint8_t event, tAVDT_SCB_EVT* p_data) { for (int i = 0; i < AVDT_NUM_LINKS; i++) { for (int j = 0; j < AVDT_NUM_SEPS; j++) { AvdtpScb* p_avdt_scb = &avdtp_cb.ccb[i].scb[j]; - if (p_avdt_scb->allocated && - avdt_scb_st_tbl[p_avdt_scb->state] == avdt_scb_st_stream) { + if (p_avdt_scb->allocated && avdt_scb_st_tbl[p_avdt_scb->state] == avdt_scb_st_stream) { num_st_streams++; ccb_index = i; scb_index = j; @@ -791,8 +788,7 @@ void avdt_scb_event(AvdtpScb* p_scb, uint8_t event, tAVDT_SCB_EVT* p_data) { if (num_st_streams == 1) { avdtp_cb.ccb[ccb_index].scb[scb_index].curr_stream = true; - } else if (num_st_streams > 1 && !p_scb->curr_stream && - event == AVDT_SCB_API_WRITE_REQ_EVT) { + } else if (num_st_streams > 1 && !p_scb->curr_stream && event == AVDT_SCB_API_WRITE_REQ_EVT) { log::error("ignore AVDT_SCB_API_WRITE_REQ_EVT"); avdt_scb_free_pkt(p_scb, p_data); return; @@ -850,10 +846,8 @@ void avdt_scb_init(void) { * Returns pointer to the scb, or NULL if none could be allocated. * ******************************************************************************/ -AvdtpScb* avdt_scb_alloc(uint8_t peer_id, - const AvdtpStreamConfig& avdtp_stream_config) { - log::assert_that(peer_id < AVDT_NUM_LINKS, - "assert failed: peer_id < AVDT_NUM_LINKS"); +AvdtpScb* avdt_scb_alloc(uint8_t peer_id, const AvdtpStreamConfig& avdtp_stream_config) { + log::assert_that(peer_id < AVDT_NUM_LINKS, "assert failed: peer_id < AVDT_NUM_LINKS"); // Find available entry AvdtpScb* p_scb = &avdtp_cb.ccb[peer_id].scb[0]; @@ -870,8 +864,7 @@ AvdtpScb* avdt_scb_alloc(uint8_t peer_id, return nullptr; } -void AvdtpScb::Allocate(AvdtpCcb* p_avdtp_ccb, - const AvdtpStreamConfig& avdtp_stream_config) { +void AvdtpScb::Allocate(AvdtpCcb* p_avdtp_ccb, const AvdtpStreamConfig& avdtp_stream_config) { uint8_t scb_handle = avdtp_cb.ComputeScbHandle(this); Reset(scb_handle); p_ccb = p_avdtp_ccb; @@ -936,8 +929,8 @@ AvdtpScb* avdt_scb_by_hdl(uint8_t hdl) { return nullptr; } - log::verbose("SCB for handle {} found: p_scb={} scb_index={}", hdl, - fmt::ptr(p_scb), p_scb->stream_config.scb_index); + log::verbose("SCB for handle {} found: p_scb={} scb_index={}", hdl, fmt::ptr(p_scb), + p_scb->stream_config.scb_index); return p_scb; } @@ -951,8 +944,8 @@ AvdtpScb* avdt_scb_by_hdl(uint8_t hdl) { * Returns SEID that failed, or 0 if success. * ******************************************************************************/ -uint8_t avdt_scb_verify(AvdtpCcb* p_ccb, uint8_t state, uint8_t* p_seid, - uint16_t num_seid, uint8_t* p_err_code) { +uint8_t avdt_scb_verify(AvdtpCcb* p_ccb, uint8_t state, uint8_t* p_seid, uint16_t num_seid, + uint8_t* p_err_code) { log::verbose("avdt_scb_verify state {}", state); /* set nonsupported command mask */ /* translate public state into private state */ @@ -983,8 +976,7 @@ uint8_t avdt_scb_verify(AvdtpCcb* p_ccb, uint8_t state, uint8_t* p_seid, switch (state) { case AVDT_VERIFY_OPEN: case AVDT_VERIFY_START: - if (p_scb->state != AVDT_SCB_OPEN_ST && - p_scb->state != AVDT_SCB_STREAM_ST) { + if (p_scb->state != AVDT_SCB_OPEN_ST && p_scb->state != AVDT_SCB_STREAM_ST) { *p_err_code = AVDT_ERR_BAD_STATE; return p_seid[i]; } diff --git a/system/stack/avdt/avdt_scb_act.cc b/system/stack/avdt/avdt_scb_act.cc index 3351ed90d9b..a4669991baf 100644 --- a/system/stack/avdt/avdt_scb_act.cc +++ b/system/stack/avdt/avdt_scb_act.cc @@ -47,16 +47,16 @@ using namespace bluetooth; * allowing for this table. */ const uint8_t avdt_scb_cback_evt[] = { - 0, /* API_REMOVE_EVT (no event) */ - AVDT_WRITE_CFM_EVT, /* API_WRITE_REQ_EVT */ - 0, /* API_GETCONFIG_REQ_EVT (no event) */ - 0, /* API_DELAY_RPT_REQ_EVT (no event) */ - AVDT_OPEN_CFM_EVT, /* API_SETCONFIG_REQ_EVT */ - AVDT_OPEN_CFM_EVT, /* API_OPEN_REQ_EVT */ - AVDT_CLOSE_CFM_EVT, /* API_CLOSE_REQ_EVT */ - AVDT_RECONFIG_CFM_EVT, /* API_RECONFIG_REQ_EVT */ - AVDT_SECURITY_CFM_EVT, /* API_SECURITY_REQ_EVT */ - 0 /* API_ABORT_REQ_EVT (no event) */ + 0, /* API_REMOVE_EVT (no event) */ + AVDT_WRITE_CFM_EVT, /* API_WRITE_REQ_EVT */ + 0, /* API_GETCONFIG_REQ_EVT (no event) */ + 0, /* API_DELAY_RPT_REQ_EVT (no event) */ + AVDT_OPEN_CFM_EVT, /* API_SETCONFIG_REQ_EVT */ + AVDT_OPEN_CFM_EVT, /* API_OPEN_REQ_EVT */ + AVDT_CLOSE_CFM_EVT, /* API_CLOSE_REQ_EVT */ + AVDT_RECONFIG_CFM_EVT, /* API_RECONFIG_REQ_EVT */ + AVDT_SECURITY_CFM_EVT, /* API_SECURITY_REQ_EVT */ + 0 /* API_ABORT_REQ_EVT (no event) */ }; /******************************************************************************* @@ -70,8 +70,8 @@ const uint8_t avdt_scb_cback_evt[] = { ******************************************************************************/ uint32_t avdt_scb_gen_ssrc(AvdtpScb* p_scb) { /* combine the value of the media type and codec type of the SCB */ - return ((uint32_t)(p_scb->stream_config.cfg.codec_info[1] | - p_scb->stream_config.cfg.codec_info[2])); + return (uint32_t)(p_scb->stream_config.cfg.codec_info[1] | + p_scb->stream_config.cfg.codec_info[2]); } /******************************************************************************* @@ -99,10 +99,7 @@ void avdt_scb_hdl_abort_cmd(AvdtpScb* p_scb, tAVDT_SCB_EVT* p_data) { * Returns Nothing. * ******************************************************************************/ -void avdt_scb_hdl_abort_rsp(AvdtpScb* /* p_scb */, - tAVDT_SCB_EVT* /* p_data */) { - return; -} +void avdt_scb_hdl_abort_rsp(AvdtpScb* /* p_scb */, tAVDT_SCB_EVT* /* p_data */) { return; } /******************************************************************************* * @@ -160,10 +157,7 @@ void avdt_scb_hdl_getconfig_cmd(AvdtpScb* p_scb, tAVDT_SCB_EVT* p_data) { * Returns Nothing. * ******************************************************************************/ -void avdt_scb_hdl_getconfig_rsp(AvdtpScb* /* p_scb */, - tAVDT_SCB_EVT* /* p_data */) { - return; -} +void avdt_scb_hdl_getconfig_rsp(AvdtpScb* /* p_scb */, tAVDT_SCB_EVT* /* p_data */) { return; } /******************************************************************************* * @@ -212,8 +206,7 @@ void avdt_scb_hdl_open_rsp(AvdtpScb* p_scb, tAVDT_SCB_EVT* /* p_data */) { avdt_ad_open_req(AVDT_CHAN_MEDIA, p_scb->p_ccb, p_scb, AVDT_INT); /* start tc connect timer */ - alarm_set_on_mloop(p_scb->transport_channel_timer, - AVDT_SCB_TC_CONN_TIMEOUT_MS, + alarm_set_on_mloop(p_scb->transport_channel_timer, AVDT_SCB_TC_CONN_TIMEOUT_MS, avdt_scb_transport_channel_timer_timeout, p_scb); } @@ -243,7 +236,9 @@ void avdt_scb_hdl_pkt_no_frag(AvdtpScb* p_scb, tAVDT_SCB_EVT* p_data) { /* parse media packet header */ offset = 12; // AVDT_MSG_PRS_OCTET1(1) + AVDT_MSG_PRS_M_PT(1) + UINT16(2) + UINT32(4) + 4 - if (offset > len) goto length_error; + if (offset > len) { + goto length_error; + } AVDT_MSG_PRS_OCTET1(p, o_v, o_p, o_x, o_cc); AVDT_MSG_PRS_M_PT(p, m_pt, marker); BE_STREAM_TO_UINT16(seq, p); @@ -257,7 +252,9 @@ void avdt_scb_hdl_pkt_no_frag(AvdtpScb* p_scb, tAVDT_SCB_EVT* p_data) { /* check for and skip over extension header */ if (o_x) { offset += 4; - if (offset > len) goto length_error; + if (offset > len) { + goto length_error; + } p += 2; BE_STREAM_TO_UINT16(ex_len, p); p += ex_len * 4; @@ -288,9 +285,8 @@ void avdt_scb_hdl_pkt_no_frag(AvdtpScb* p_scb, tAVDT_SCB_EVT* p_data) { if (p_scb->stream_config.p_sink_data_cback != NULL) { /* report sequence number */ p_data->p_pkt->layer_specific = seq; - (*p_scb->stream_config.p_sink_data_cback)( - avdt_scb_to_hdl(p_scb), p_data->p_pkt, time_stamp, - (uint8_t)(m_pt | (marker << 7))); + (*p_scb->stream_config.p_sink_data_cback)(avdt_scb_to_hdl(p_scb), p_data->p_pkt, time_stamp, + (uint8_t)(m_pt | (marker << 7))); } else { osi_free_and_reset((void**)&p_data->p_pkt); } @@ -324,8 +320,7 @@ uint8_t* avdt_scb_hdl_report(AvdtpScb* p_scb, uint8_t* p, uint16_t len) { /* parse report packet header */ min_len += 8; if (min_len > len) { - log::warn("hdl packet length {} too short: must be at least {}", len, - min_len); + log::warn("hdl packet length {} too short: must be at least {}", len, min_len); goto avdt_scb_hdl_report_exit; } AVDT_MSG_PRS_RPT_OCTET1(p, o_v, o_p, o_cc); @@ -337,8 +332,7 @@ uint8_t* avdt_scb_hdl_report(AvdtpScb* p_scb, uint8_t* p, uint16_t len) { case AVDT_RTCP_PT_SR: /* the packet type - SR (Sender Report) */ min_len += 20; if (min_len > len) { - log::warn("hdl packet length {} too short: must be at least {}", len, - min_len); + log::warn("hdl packet length {} too short: must be at least {}", len, min_len); goto avdt_scb_hdl_report_exit; } BE_STREAM_TO_UINT32(report.sr.ntp_sec, p); @@ -351,8 +345,7 @@ uint8_t* avdt_scb_hdl_report(AvdtpScb* p_scb, uint8_t* p, uint16_t len) { case AVDT_RTCP_PT_RR: /* the packet type - RR (Receiver Report) */ min_len += 20; if (min_len > len) { - log::warn("hdl packet length {} too short: must be at least {}", len, - min_len); + log::warn("hdl packet length {} too short: must be at least {}", len, min_len); goto avdt_scb_hdl_report_exit; } report.rr.frag_lost = *p; @@ -368,8 +361,7 @@ uint8_t* avdt_scb_hdl_report(AvdtpScb* p_scb, uint8_t* p, uint16_t len) { uint8_t sdes_type; min_len += 1; if (min_len > len) { - log::warn("hdl packet length {} too short: must be at least {}", len, - min_len); + log::warn("hdl packet length {} too short: must be at least {}", len, min_len); goto avdt_scb_hdl_report_exit; } BE_STREAM_TO_UINT8(sdes_type, p); @@ -377,25 +369,21 @@ uint8_t* avdt_scb_hdl_report(AvdtpScb* p_scb, uint8_t* p, uint16_t len) { uint8_t name_length; min_len += 1; if (min_len > len) { - log::warn("hdl packet length {} too short: must be at least {}", - len, min_len); + log::warn("hdl packet length {} too short: must be at least {}", len, min_len); goto avdt_scb_hdl_report_exit; } BE_STREAM_TO_UINT8(name_length, p); - if (name_length > len - min_len || - name_length > AVDT_MAX_CNAME_SIZE) { + if (name_length > len - min_len || name_length > AVDT_MAX_CNAME_SIZE) { result = AVDT_BAD_PARAMS; } else { BE_STREAM_TO_ARRAY(p, &(report.cname[0]), name_length); } } else { if (min_len + 1 > len) { - log::warn("hdl packet length {} too short: must be at least {}", - len, min_len); + log::warn("hdl packet length {} too short: must be at least {}", len, min_len); goto avdt_scb_hdl_report_exit; } - log::warn("SDES SSRC=0x{:08x} sc={} {} len={}", ssrc, o_cc, sdes_type, - *p); + log::warn("SDES SSRC=0x{:08x} sc={} {} len={}", ssrc, o_cc, sdes_type, *p); result = AVDT_BUSY; } break; @@ -405,9 +393,9 @@ uint8_t* avdt_scb_hdl_report(AvdtpScb* p_scb, uint8_t* p, uint16_t len) { result = AVDT_BAD_PARAMS; } - if (result == AVDT_SUCCESS) - (*p_scb->stream_config.p_report_cback)(avdt_scb_to_hdl(p_scb), pt, - &report); + if (result == AVDT_SUCCESS) { + (*p_scb->stream_config.p_report_cback)(avdt_scb_to_hdl(p_scb), pt, &report); + } } avdt_scb_hdl_report_exit: p_start += len; @@ -471,8 +459,8 @@ void avdt_scb_hdl_reconfig_cmd(AvdtpScb* p_scb, tAVDT_SCB_EVT* p_data) { /* call application callback */ (*p_scb->stream_config.p_avdt_ctrl_cback)( - avdt_scb_to_hdl(p_scb), RawAddress::kEmpty, AVDT_RECONFIG_IND_EVT, - (tAVDT_CTRL*)&p_data->msg.reconfig_cmd, p_scb->stream_config.scb_index); + avdt_scb_to_hdl(p_scb), RawAddress::kEmpty, AVDT_RECONFIG_IND_EVT, + (tAVDT_CTRL*)&p_data->msg.reconfig_cmd, p_scb->stream_config.scb_index); } } @@ -491,22 +479,20 @@ void avdt_scb_hdl_reconfig_rsp(AvdtpScb* p_scb, tAVDT_SCB_EVT* p_data) { /* store new configuration */ if (p_scb->req_cfg.num_codec > 0) { p_scb->curr_cfg.num_codec = p_scb->req_cfg.num_codec; - memcpy(p_scb->curr_cfg.codec_info, p_scb->req_cfg.codec_info, - AVDT_CODEC_SIZE); + memcpy(p_scb->curr_cfg.codec_info, p_scb->req_cfg.codec_info, AVDT_CODEC_SIZE); } if (p_scb->req_cfg.num_protect > 0) { p_scb->curr_cfg.num_protect = p_scb->req_cfg.num_protect; - memcpy(p_scb->curr_cfg.protect_info, p_scb->req_cfg.protect_info, - AVDT_PROTECT_SIZE); + memcpy(p_scb->curr_cfg.protect_info, p_scb->req_cfg.protect_info, AVDT_PROTECT_SIZE); } } p_data->msg.svccap.p_cfg = &p_scb->curr_cfg; /* call application callback */ - (*p_scb->stream_config.p_avdt_ctrl_cback)( - avdt_scb_to_hdl(p_scb), RawAddress::kEmpty, AVDT_RECONFIG_CFM_EVT, - (tAVDT_CTRL*)&p_data->msg.svccap, p_scb->stream_config.scb_index); + (*p_scb->stream_config.p_avdt_ctrl_cback)(avdt_scb_to_hdl(p_scb), RawAddress::kEmpty, + AVDT_RECONFIG_CFM_EVT, (tAVDT_CTRL*)&p_data->msg.svccap, + p_scb->stream_config.scb_index); } /******************************************************************************* @@ -528,8 +514,8 @@ void avdt_scb_hdl_security_cmd(AvdtpScb* p_scb, tAVDT_SCB_EVT* p_data) { } else { /* call application callback */ (*p_scb->stream_config.p_avdt_ctrl_cback)( - avdt_scb_to_hdl(p_scb), RawAddress::kEmpty, AVDT_SECURITY_IND_EVT, - (tAVDT_CTRL*)&p_data->msg.security_cmd, p_scb->stream_config.scb_index); + avdt_scb_to_hdl(p_scb), RawAddress::kEmpty, AVDT_SECURITY_IND_EVT, + (tAVDT_CTRL*)&p_data->msg.security_cmd, p_scb->stream_config.scb_index); } } @@ -546,8 +532,8 @@ void avdt_scb_hdl_security_cmd(AvdtpScb* p_scb, tAVDT_SCB_EVT* p_data) { void avdt_scb_hdl_security_rsp(AvdtpScb* p_scb, tAVDT_SCB_EVT* p_data) { /* call application callback */ (*p_scb->stream_config.p_avdt_ctrl_cback)( - avdt_scb_to_hdl(p_scb), RawAddress::kEmpty, AVDT_SECURITY_CFM_EVT, - (tAVDT_CTRL*)&p_data->msg.security_cmd, p_scb->stream_config.scb_index); + avdt_scb_to_hdl(p_scb), RawAddress::kEmpty, AVDT_SECURITY_CFM_EVT, + (tAVDT_CTRL*)&p_data->msg.security_cmd, p_scb->stream_config.scb_index); } /******************************************************************************* @@ -562,14 +548,12 @@ void avdt_scb_hdl_security_rsp(AvdtpScb* p_scb, tAVDT_SCB_EVT* p_data) { * ******************************************************************************/ void avdt_scb_hdl_setconfig_cmd(AvdtpScb* p_scb, tAVDT_SCB_EVT* p_data) { - log::verbose("p_scb->in_use={} p_avdt_scb={} scb_index={}", p_scb->in_use, - fmt::ptr(p_scb), p_scb->stream_config.scb_index); + log::verbose("p_scb->in_use={} p_avdt_scb={} scb_index={}", p_scb->in_use, fmt::ptr(p_scb), + p_scb->stream_config.scb_index); if (!p_scb->in_use) { - log::verbose("codec: {}", - A2DP_CodecInfoString(p_scb->stream_config.cfg.codec_info)); - log::verbose("codec: {}", A2DP_CodecInfoString( - p_data->msg.config_cmd.p_cfg->codec_info)); + log::verbose("codec: {}", A2DP_CodecInfoString(p_scb->stream_config.cfg.codec_info)); + log::verbose("codec: {}", A2DP_CodecInfoString(p_data->msg.config_cmd.p_cfg->codec_info)); AvdtpSepConfig* p_cfg = p_data->msg.config_cmd.p_cfg; if (A2DP_GetCodecType(p_scb->stream_config.cfg.codec_info) == A2DP_GetCodecType(p_cfg->codec_info)) { @@ -577,10 +561,10 @@ void avdt_scb_hdl_setconfig_cmd(AvdtpScb* p_scb, tAVDT_SCB_EVT* p_data) { AvdtpCcb* p_ccb = avdt_ccb_by_idx(p_data->msg.config_cmd.hdr.ccb_idx); if (p_scb->p_ccb != p_ccb) { log::error( - "mismatch in AVDTP SCB/CCB state: (p_scb->p_ccb={} != p_ccb={}): " - "p_scb={} scb_handle={} ccb_idx={}", - fmt::ptr(p_scb->p_ccb), fmt::ptr(p_ccb), fmt::ptr(p_scb), - p_scb->ScbHandle(), p_data->msg.config_cmd.hdr.ccb_idx); + "mismatch in AVDTP SCB/CCB state: (p_scb->p_ccb={} != p_ccb={}): " + "p_scb={} scb_handle={} ccb_idx={}", + fmt::ptr(p_scb->p_ccb), fmt::ptr(p_ccb), fmt::ptr(p_scb), p_scb->ScbHandle(), + p_data->msg.config_cmd.hdr.ccb_idx); avdt_scb_rej_not_in_use(p_scb, p_data); return; } @@ -592,15 +576,14 @@ void avdt_scb_hdl_setconfig_cmd(AvdtpScb* p_scb, tAVDT_SCB_EVT* p_data) { /* call app callback */ /* handle of scb- which is same as sep handle of bta_av_cb.p_scb*/ (*p_scb->stream_config.p_avdt_ctrl_cback)( - avdt_scb_to_hdl(p_scb), - p_scb->p_ccb ? p_scb->p_ccb->peer_addr : RawAddress::kEmpty, - AVDT_CONFIG_IND_EVT, (tAVDT_CTRL*)&p_data->msg.config_cmd, - p_scb->stream_config.scb_index); + avdt_scb_to_hdl(p_scb), p_scb->p_ccb ? p_scb->p_ccb->peer_addr : RawAddress::kEmpty, + AVDT_CONFIG_IND_EVT, (tAVDT_CTRL*)&p_data->msg.config_cmd, + p_scb->stream_config.scb_index); } else { p_data->msg.hdr.err_code = AVDT_ERR_UNSUP_CFG; p_data->msg.hdr.err_param = 0; - avdt_msg_send_rej(avdt_ccb_by_idx(p_data->msg.hdr.ccb_idx), - p_data->msg.hdr.sig_id, &p_data->msg); + avdt_msg_send_rej(avdt_ccb_by_idx(p_data->msg.hdr.ccb_idx), p_data->msg.hdr.sig_id, + &p_data->msg); } } else { log::verbose("calling avdt_scb_rej_in_use()"); @@ -624,13 +607,12 @@ void avdt_scb_hdl_setconfig_rej(AvdtpScb* p_scb, tAVDT_SCB_EVT* p_data) { avdt_scb_clr_vars(p_scb, p_data); /* tell ccb we're done with signaling channel */ - avdt_ccb_event(avdt_ccb_by_idx(p_data->msg.hdr.ccb_idx), - AVDT_CCB_UL_CLOSE_EVT, NULL); + avdt_ccb_event(avdt_ccb_by_idx(p_data->msg.hdr.ccb_idx), AVDT_CCB_UL_CLOSE_EVT, NULL); /* call application callback */ - (*p_scb->stream_config.p_avdt_ctrl_cback)( - avdt_scb_to_hdl(p_scb), RawAddress::kEmpty, AVDT_OPEN_CFM_EVT, - (tAVDT_CTRL*)&p_data->msg.hdr, p_scb->stream_config.scb_index); + (*p_scb->stream_config.p_avdt_ctrl_cback)(avdt_scb_to_hdl(p_scb), RawAddress::kEmpty, + AVDT_OPEN_CFM_EVT, (tAVDT_CTRL*)&p_data->msg.hdr, + p_scb->stream_config.scb_index); } /******************************************************************************* @@ -642,8 +624,7 @@ void avdt_scb_hdl_setconfig_rej(AvdtpScb* p_scb, tAVDT_SCB_EVT* p_data) { * Returns Nothing. * ******************************************************************************/ -void avdt_scb_snd_snk_delay_rpt_req(AvdtpScb* p_scb, - tAVDT_SCB_EVT* /* p_data */) { +void avdt_scb_snd_snk_delay_rpt_req(AvdtpScb* p_scb, tAVDT_SCB_EVT* /* p_data */) { if (p_scb->p_ccb == NULL) { return; } @@ -705,9 +686,8 @@ void avdt_scb_hdl_setconfig_rsp(AvdtpScb* p_scb, tAVDT_SCB_EVT* p_data) { ******************************************************************************/ void avdt_scb_hdl_start_cmd(AvdtpScb* p_scb, tAVDT_SCB_EVT* /* p_data */) { (*p_scb->stream_config.p_avdt_ctrl_cback)( - avdt_scb_to_hdl(p_scb), - p_scb->p_ccb ? p_scb->p_ccb->peer_addr : RawAddress::kEmpty, - AVDT_START_IND_EVT, NULL, p_scb->stream_config.scb_index); + avdt_scb_to_hdl(p_scb), p_scb->p_ccb ? p_scb->p_ccb->peer_addr : RawAddress::kEmpty, + AVDT_START_IND_EVT, NULL, p_scb->stream_config.scb_index); } /******************************************************************************* @@ -722,10 +702,8 @@ void avdt_scb_hdl_start_cmd(AvdtpScb* p_scb, tAVDT_SCB_EVT* /* p_data */) { ******************************************************************************/ void avdt_scb_hdl_start_rsp(AvdtpScb* p_scb, tAVDT_SCB_EVT* p_data) { (*p_scb->stream_config.p_avdt_ctrl_cback)( - avdt_scb_to_hdl(p_scb), - p_scb->p_ccb ? p_scb->p_ccb->peer_addr : RawAddress::kEmpty, - AVDT_START_CFM_EVT, (tAVDT_CTRL*)&p_data->msg.hdr, - p_scb->stream_config.scb_index); + avdt_scb_to_hdl(p_scb), p_scb->p_ccb ? p_scb->p_ccb->peer_addr : RawAddress::kEmpty, + AVDT_START_CFM_EVT, (tAVDT_CTRL*)&p_data->msg.hdr, p_scb->stream_config.scb_index); } /******************************************************************************* @@ -740,9 +718,8 @@ void avdt_scb_hdl_start_rsp(AvdtpScb* p_scb, tAVDT_SCB_EVT* p_data) { ******************************************************************************/ void avdt_scb_hdl_suspend_cmd(AvdtpScb* p_scb, tAVDT_SCB_EVT* /* p_data */) { (*p_scb->stream_config.p_avdt_ctrl_cback)( - avdt_scb_to_hdl(p_scb), - p_scb->p_ccb ? p_scb->p_ccb->peer_addr : RawAddress::kEmpty, - AVDT_SUSPEND_IND_EVT, NULL, p_scb->stream_config.scb_index); + avdt_scb_to_hdl(p_scb), p_scb->p_ccb ? p_scb->p_ccb->peer_addr : RawAddress::kEmpty, + AVDT_SUSPEND_IND_EVT, NULL, p_scb->stream_config.scb_index); } /******************************************************************************* @@ -757,10 +734,8 @@ void avdt_scb_hdl_suspend_cmd(AvdtpScb* p_scb, tAVDT_SCB_EVT* /* p_data */) { ******************************************************************************/ void avdt_scb_hdl_suspend_rsp(AvdtpScb* p_scb, tAVDT_SCB_EVT* p_data) { (*p_scb->stream_config.p_avdt_ctrl_cback)( - avdt_scb_to_hdl(p_scb), - p_scb->p_ccb ? p_scb->p_ccb->peer_addr : RawAddress::kEmpty, - AVDT_SUSPEND_CFM_EVT, (tAVDT_CTRL*)&p_data->msg.hdr, - p_scb->stream_config.scb_index); + avdt_scb_to_hdl(p_scb), p_scb->p_ccb ? p_scb->p_ccb->peer_addr : RawAddress::kEmpty, + AVDT_SUSPEND_CFM_EVT, (tAVDT_CTRL*)&p_data->msg.hdr, p_scb->stream_config.scb_index); } /******************************************************************************* @@ -805,8 +780,7 @@ void avdt_scb_hdl_tc_close(AvdtpScb* p_scb, tAVDT_SCB_EVT* p_data) { /* tell ccb we're done with signaling channel */ avdt_ccb_event(p_ccb, AVDT_CCB_UL_CLOSE_EVT, NULL); } - event = - (p_scb->role == AVDT_CLOSE_INT) ? AVDT_CLOSE_CFM_EVT : AVDT_CLOSE_IND_EVT; + event = (p_scb->role == AVDT_CLOSE_INT) ? AVDT_CLOSE_CFM_EVT : AVDT_CLOSE_IND_EVT; p_scb->role = AVDT_CLOSE_ACP; if (p_scb->remove) { @@ -829,8 +803,7 @@ void avdt_scb_hdl_tc_close(AvdtpScb* p_scb, tAVDT_SCB_EVT* p_data) { ******************************************************************************/ void avdt_scb_snd_delay_rpt_req(AvdtpScb* p_scb, tAVDT_SCB_EVT* p_data) { if (p_scb->stream_config.cfg.psc_mask & AVDT_PSC_DELAY_RPT) { - avdt_msg_send_cmd(p_scb->p_ccb, p_scb, AVDT_SIG_DELAY_RPT, - (tAVDT_MSG*)&p_data->apidelay); + avdt_msg_send_cmd(p_scb->p_ccb, p_scb, AVDT_SIG_DELAY_RPT, (tAVDT_MSG*)&p_data->apidelay); } } @@ -846,15 +819,14 @@ void avdt_scb_snd_delay_rpt_req(AvdtpScb* p_scb, tAVDT_SCB_EVT* p_data) { ******************************************************************************/ void avdt_scb_hdl_delay_rpt_cmd(AvdtpScb* p_scb, tAVDT_SCB_EVT* p_data) { (*p_scb->stream_config.p_avdt_ctrl_cback)( - avdt_scb_to_hdl(p_scb), - p_scb->p_ccb ? p_scb->p_ccb->peer_addr : RawAddress::kEmpty, - AVDT_DELAY_REPORT_EVT, (tAVDT_CTRL*)&p_data->msg.hdr, - p_scb->stream_config.scb_index); + avdt_scb_to_hdl(p_scb), p_scb->p_ccb ? p_scb->p_ccb->peer_addr : RawAddress::kEmpty, + AVDT_DELAY_REPORT_EVT, (tAVDT_CTRL*)&p_data->msg.hdr, p_scb->stream_config.scb_index); - if (p_scb->p_ccb) + if (p_scb->p_ccb) { avdt_msg_send_rsp(p_scb->p_ccb, AVDT_SIG_DELAY_RPT, &p_data->msg); - else + } else { avdt_scb_rej_not_in_use(p_scb, p_data); + } } /******************************************************************************* @@ -869,10 +841,8 @@ void avdt_scb_hdl_delay_rpt_cmd(AvdtpScb* p_scb, tAVDT_SCB_EVT* p_data) { ******************************************************************************/ void avdt_scb_hdl_delay_rpt_rsp(AvdtpScb* p_scb, tAVDT_SCB_EVT* p_data) { (*p_scb->stream_config.p_avdt_ctrl_cback)( - avdt_scb_to_hdl(p_scb), - p_scb->p_ccb ? p_scb->p_ccb->peer_addr : RawAddress::kEmpty, - AVDT_DELAY_REPORT_CFM_EVT, (tAVDT_CTRL*)&p_data->msg.hdr, - p_scb->stream_config.scb_index); + avdt_scb_to_hdl(p_scb), p_scb->p_ccb ? p_scb->p_ccb->peer_addr : RawAddress::kEmpty, + AVDT_DELAY_REPORT_CFM_EVT, (tAVDT_CTRL*)&p_data->msg.hdr, p_scb->stream_config.scb_index); } /******************************************************************************* @@ -896,9 +866,8 @@ void avdt_scb_hdl_tc_close_sto(AvdtpScb* p_scb, tAVDT_SCB_EVT* p_data) { avdt_ctrl.hdr.err_param = 0; /* call app callback */ (*p_scb->stream_config.p_avdt_ctrl_cback)( - avdt_scb_to_hdl(p_scb), - p_scb->p_ccb ? p_scb->p_ccb->peer_addr : RawAddress::kEmpty, - AVDT_REPORT_DISCONN_EVT, &avdt_ctrl, p_scb->stream_config.scb_index); + avdt_scb_to_hdl(p_scb), p_scb->p_ccb ? p_scb->p_ccb->peer_addr : RawAddress::kEmpty, + AVDT_REPORT_DISCONN_EVT, &avdt_ctrl, p_scb->stream_config.scb_index); } } else { /* must be in OPEN state. need to go back to idle */ @@ -925,13 +894,11 @@ void avdt_scb_hdl_tc_open(AvdtpScb* p_scb, tAVDT_SCB_EVT* p_data) { alarm_cancel(p_scb->transport_channel_timer); - event = - (p_scb->role == AVDT_OPEN_INT) ? AVDT_OPEN_CFM_EVT : AVDT_OPEN_IND_EVT; + event = (p_scb->role == AVDT_OPEN_INT) ? AVDT_OPEN_CFM_EVT : AVDT_OPEN_IND_EVT; p_data->open.hdr.err_code = 0; - log::verbose("psc_mask: cfg: 0x{:x}, req:0x{:x}, cur: 0x{:x}", - p_scb->stream_config.cfg.psc_mask, p_scb->req_cfg.psc_mask, - p_scb->curr_cfg.psc_mask); + log::verbose("psc_mask: cfg: 0x{:x}, req:0x{:x}, cur: 0x{:x}", p_scb->stream_config.cfg.psc_mask, + p_scb->req_cfg.psc_mask, p_scb->curr_cfg.psc_mask); if (p_scb->curr_cfg.psc_mask & AVDT_PSC_REPORT) { /* open the reporting channel, if both devices support it */ role = (p_scb->role == AVDT_OPEN_INT) ? AVDT_INT : AVDT_ACP; @@ -940,9 +907,8 @@ void avdt_scb_hdl_tc_open(AvdtpScb* p_scb, tAVDT_SCB_EVT* p_data) { /* call app callback */ (*p_scb->stream_config.p_avdt_ctrl_cback)( - avdt_scb_to_hdl(p_scb), - p_scb->p_ccb ? p_scb->p_ccb->peer_addr : RawAddress::kEmpty, event, - (tAVDT_CTRL*)&p_data->open, p_scb->stream_config.scb_index); + avdt_scb_to_hdl(p_scb), p_scb->p_ccb ? p_scb->p_ccb->peer_addr : RawAddress::kEmpty, + event, (tAVDT_CTRL*)&p_data->open, p_scb->stream_config.scb_index); } /******************************************************************************* @@ -966,9 +932,8 @@ void avdt_scb_hdl_tc_open_sto(AvdtpScb* p_scb, tAVDT_SCB_EVT* p_data) { avdt_ctrl.hdr.err_code = 0; avdt_ctrl.hdr.err_param = 1; (*p_scb->stream_config.p_avdt_ctrl_cback)( - avdt_scb_to_hdl(p_scb), - p_scb->p_ccb ? p_scb->p_ccb->peer_addr : RawAddress::kEmpty, - AVDT_REPORT_CONN_EVT, &avdt_ctrl, p_scb->stream_config.scb_index); + avdt_scb_to_hdl(p_scb), p_scb->p_ccb ? p_scb->p_ccb->peer_addr : RawAddress::kEmpty, + AVDT_REPORT_CONN_EVT, &avdt_ctrl, p_scb->stream_config.scb_index); } } @@ -998,8 +963,7 @@ void avdt_scb_hdl_write_req(AvdtpScb* p_scb, tAVDT_SCB_EVT* p_data) { /* Recompute only if the RTP header wasn't disabled by the API */ if (add_rtp_header) { bool is_content_protection = (p_scb->curr_cfg.num_protect > 0); - add_rtp_header = - A2DP_UsesRtpHeader(is_content_protection, p_scb->curr_cfg.codec_info); + add_rtp_header = A2DP_UsesRtpHeader(is_content_protection, p_scb->curr_cfg.codec_info); } /* Build a media packet, and add an RTP header if required. */ @@ -1061,8 +1025,7 @@ void avdt_scb_snd_abort_req(AvdtpScb* p_scb, tAVDT_SCB_EVT* /* p_data */) { * ******************************************************************************/ void avdt_scb_snd_abort_rsp(AvdtpScb* /* p_scb */, tAVDT_SCB_EVT* p_data) { - avdt_msg_send_rsp(avdt_ccb_by_idx(p_data->msg.hdr.ccb_idx), AVDT_SIG_ABORT, - &p_data->msg); + avdt_msg_send_rsp(avdt_ccb_by_idx(p_data->msg.hdr.ccb_idx), AVDT_SIG_ABORT, &p_data->msg); } /******************************************************************************* @@ -1183,8 +1146,7 @@ void avdt_scb_snd_open_rsp(AvdtpScb* p_scb, tAVDT_SCB_EVT* p_data) { /* send response */ avdt_msg_send_rsp(p_scb->p_ccb, AVDT_SIG_OPEN, &p_data->msg); - alarm_set_on_mloop(p_scb->transport_channel_timer, - AVDT_SCB_TC_CONN_TIMEOUT_MS, + alarm_set_on_mloop(p_scb->transport_channel_timer, AVDT_SCB_TC_CONN_TIMEOUT_MS, avdt_scb_transport_channel_timer_timeout, p_scb); } @@ -1201,8 +1163,7 @@ void avdt_scb_snd_open_rsp(AvdtpScb* p_scb, tAVDT_SCB_EVT* p_data) { void avdt_scb_snd_reconfig_req(AvdtpScb* p_scb, tAVDT_SCB_EVT* p_data) { log::verbose("p_scb->peer_seid={} p_data->msg.hdr.seid={}", p_scb->peer_seid, p_data->msg.hdr.seid); - log::verbose("codec: {}", - A2DP_CodecInfoString(p_data->msg.config_cmd.p_cfg->codec_info)); + log::verbose("codec: {}", A2DP_CodecInfoString(p_data->msg.config_cmd.p_cfg->codec_info)); p_scb->req_cfg = *p_data->msg.config_cmd.p_cfg; p_data->msg.hdr.seid = p_scb->peer_seid; @@ -1224,13 +1185,11 @@ void avdt_scb_snd_reconfig_rsp(AvdtpScb* p_scb, tAVDT_SCB_EVT* p_data) { /* store new configuration */ if (p_scb->req_cfg.num_codec > 0) { p_scb->curr_cfg.num_codec = p_scb->req_cfg.num_codec; - memcpy(p_scb->curr_cfg.codec_info, p_scb->req_cfg.codec_info, - AVDT_CODEC_SIZE); + memcpy(p_scb->curr_cfg.codec_info, p_scb->req_cfg.codec_info, AVDT_CODEC_SIZE); } if (p_scb->req_cfg.num_protect > 0) { p_scb->curr_cfg.num_protect = p_scb->req_cfg.num_protect; - memcpy(p_scb->curr_cfg.protect_info, p_scb->req_cfg.protect_info, - AVDT_PROTECT_SIZE); + memcpy(p_scb->curr_cfg.protect_info, p_scb->req_cfg.protect_info, AVDT_PROTECT_SIZE); } /* send response */ @@ -1304,18 +1263,17 @@ void avdt_scb_snd_setconfig_rej(AvdtpScb* p_scb, tAVDT_SCB_EVT* p_data) { * ******************************************************************************/ void avdt_scb_snd_setconfig_req(AvdtpScb* p_scb, tAVDT_SCB_EVT* p_data) { - log::verbose("codec: {}", - A2DP_CodecInfoString(p_data->msg.config_cmd.p_cfg->codec_info)); + log::verbose("codec: {}", A2DP_CodecInfoString(p_data->msg.config_cmd.p_cfg->codec_info)); /* copy API parameters to scb, set scb as in use */ AvdtpCcb* p_ccb = avdt_ccb_by_idx(p_data->msg.config_cmd.hdr.ccb_idx); if (p_scb->p_ccb != p_ccb) { log::error( - "mismatch in AVDTP SCB/CCB state: (p_scb->p_ccb={} != p_ccb={}): " - "p_scb={} scb_handle={} ccb_idx={}", - fmt::ptr(p_scb->p_ccb), fmt::ptr(p_ccb), fmt::ptr(p_scb), - p_scb->ScbHandle(), p_data->msg.config_cmd.hdr.ccb_idx); + "mismatch in AVDTP SCB/CCB state: (p_scb->p_ccb={} != p_ccb={}): " + "p_scb={} scb_handle={} ccb_idx={}", + fmt::ptr(p_scb->p_ccb), fmt::ptr(p_ccb), fmt::ptr(p_scb), p_scb->ScbHandle(), + p_data->msg.config_cmd.hdr.ccb_idx); avdt_scb_rej_not_in_use(p_scb, p_data); return; } @@ -1359,8 +1317,9 @@ void avdt_scb_snd_setconfig_rsp(AvdtpScb* p_scb, tAVDT_SCB_EVT* p_data) { * ******************************************************************************/ void avdt_scb_snd_tc_close(AvdtpScb* p_scb, tAVDT_SCB_EVT* /* p_data */) { - if (p_scb->curr_cfg.psc_mask & AVDT_PSC_REPORT) + if (p_scb->curr_cfg.psc_mask & AVDT_PSC_REPORT) { avdt_ad_close_req(AVDT_CHAN_REPORT, p_scb->p_ccb, p_scb); + } avdt_ad_close_req(AVDT_CHAN_MEDIA, p_scb->p_ccb, p_scb); } @@ -1382,10 +1341,9 @@ void avdt_scb_cb_err(AvdtpScb* p_scb, tAVDT_SCB_EVT* /* p_data */) { avdt_ctrl.hdr.err_param = 0; /* call callback, using lookup table to get callback event */ - (*p_scb->stream_config.p_avdt_ctrl_cback)( - avdt_scb_to_hdl(p_scb), RawAddress::kEmpty, - avdt_scb_cback_evt[p_scb->curr_evt], &avdt_ctrl, - p_scb->stream_config.scb_index); + (*p_scb->stream_config.p_avdt_ctrl_cback)(avdt_scb_to_hdl(p_scb), RawAddress::kEmpty, + avdt_scb_cback_evt[p_scb->curr_evt], &avdt_ctrl, + p_scb->stream_config.scb_index); } /******************************************************************************* @@ -1398,9 +1356,7 @@ void avdt_scb_cb_err(AvdtpScb* p_scb, tAVDT_SCB_EVT* /* p_data */) { * Returns Nothing. * ******************************************************************************/ -void avdt_scb_cong_state(AvdtpScb* p_scb, tAVDT_SCB_EVT* p_data) { - p_scb->cong = p_data->llcong; -} +void avdt_scb_cong_state(AvdtpScb* p_scb, tAVDT_SCB_EVT* p_data) { p_scb->cong = p_data->llcong; } /******************************************************************************* * @@ -1415,8 +1371,7 @@ void avdt_scb_cong_state(AvdtpScb* p_scb, tAVDT_SCB_EVT* p_data) { void avdt_scb_rej_state(AvdtpScb* /* p_scb */, tAVDT_SCB_EVT* p_data) { p_data->msg.hdr.err_code = AVDT_ERR_BAD_STATE; p_data->msg.hdr.err_param = 0; - avdt_msg_send_rej(avdt_ccb_by_idx(p_data->msg.hdr.ccb_idx), - p_data->msg.hdr.sig_id, &p_data->msg); + avdt_msg_send_rej(avdt_ccb_by_idx(p_data->msg.hdr.ccb_idx), p_data->msg.hdr.sig_id, &p_data->msg); } /******************************************************************************* @@ -1432,8 +1387,7 @@ void avdt_scb_rej_state(AvdtpScb* /* p_scb */, tAVDT_SCB_EVT* p_data) { void avdt_scb_rej_in_use(AvdtpScb* /* p_scb */, tAVDT_SCB_EVT* p_data) { p_data->msg.hdr.err_code = AVDT_ERR_IN_USE; p_data->msg.hdr.err_param = 0; - avdt_msg_send_rej(avdt_ccb_by_idx(p_data->msg.hdr.ccb_idx), - p_data->msg.hdr.sig_id, &p_data->msg); + avdt_msg_send_rej(avdt_ccb_by_idx(p_data->msg.hdr.ccb_idx), p_data->msg.hdr.sig_id, &p_data->msg); } /******************************************************************************* @@ -1449,8 +1403,7 @@ void avdt_scb_rej_in_use(AvdtpScb* /* p_scb */, tAVDT_SCB_EVT* p_data) { void avdt_scb_rej_not_in_use(AvdtpScb* /* p_scb */, tAVDT_SCB_EVT* p_data) { p_data->msg.hdr.err_code = AVDT_ERR_NOT_IN_USE; p_data->msg.hdr.err_param = 0; - avdt_msg_send_rej(avdt_ccb_by_idx(p_data->msg.hdr.ccb_idx), - p_data->msg.hdr.sig_id, &p_data->msg); + avdt_msg_send_rej(avdt_ccb_by_idx(p_data->msg.hdr.ccb_idx), p_data->msg.hdr.sig_id, &p_data->msg); } /******************************************************************************* @@ -1462,9 +1415,7 @@ void avdt_scb_rej_not_in_use(AvdtpScb* /* p_scb */, tAVDT_SCB_EVT* p_data) { * Returns Nothing. * ******************************************************************************/ -void avdt_scb_set_remove(AvdtpScb* p_scb, tAVDT_SCB_EVT* /* p_data */) { - p_scb->remove = true; -} +void avdt_scb_set_remove(AvdtpScb* p_scb, tAVDT_SCB_EVT* /* p_data */) { p_scb->remove = true; } /******************************************************************************* * @@ -1487,9 +1438,9 @@ void avdt_scb_free_pkt(AvdtpScb* p_scb, tAVDT_SCB_EVT* p_data) { log::warn("Dropped media packet"); /* we need to call callback to keep data flow going */ - (*p_scb->stream_config.p_avdt_ctrl_cback)( - avdt_scb_to_hdl(p_scb), RawAddress::kEmpty, AVDT_WRITE_CFM_EVT, - &avdt_ctrl, p_scb->stream_config.scb_index); + (*p_scb->stream_config.p_avdt_ctrl_cback)(avdt_scb_to_hdl(p_scb), RawAddress::kEmpty, + AVDT_WRITE_CFM_EVT, &avdt_ctrl, + p_scb->stream_config.scb_index); } /******************************************************************************* @@ -1517,12 +1468,10 @@ void avdt_scb_clr_pkt(AvdtpScb* p_scb, tAVDT_SCB_EVT* /* p_data */) { tcid = avdt_ad_type_to_tcid(AVDT_CHAN_MEDIA, p_scb); lcid = avdtp_cb.ad.rt_tbl[avdt_ccb_to_idx(p_ccb)][tcid].lcid; - const uint16_t buffers_left = - L2CA_FlushChannel(lcid, L2CAP_FLUSH_CHANS_ALL); + const uint16_t buffers_left = L2CA_FlushChannel(lcid, L2CAP_FLUSH_CHANS_ALL); if (buffers_left) { - log::warn( - "Unable to flush L2CAP ALL channel peer:{} cid:{} buffers_left:{}", - p_ccb->peer_addr, lcid, buffers_left); + log::warn("Unable to flush L2CAP ALL channel peer:{} cid:{} buffers_left:{}", + p_ccb->peer_addr, lcid, buffers_left); } } @@ -1532,9 +1481,9 @@ void avdt_scb_clr_pkt(AvdtpScb* p_scb, tAVDT_SCB_EVT* /* p_data */) { log::verbose("Dropped stored media packet"); /* we need to call callback to keep data flow going */ - (*p_scb->stream_config.p_avdt_ctrl_cback)( - avdt_scb_to_hdl(p_scb), RawAddress::kEmpty, AVDT_WRITE_CFM_EVT, - &avdt_ctrl, p_scb->stream_config.scb_index); + (*p_scb->stream_config.p_avdt_ctrl_cback)(avdt_scb_to_hdl(p_scb), RawAddress::kEmpty, + AVDT_WRITE_CFM_EVT, &avdt_ctrl, + p_scb->stream_config.scb_index); } } @@ -1562,9 +1511,9 @@ void avdt_scb_chk_snd_pkt(AvdtpScb* p_scb, tAVDT_SCB_EVT* /* p_data */) { p_scb->p_pkt = NULL; avdt_ad_write_req(AVDT_CHAN_MEDIA, p_scb->p_ccb, p_scb, p_pkt); - (*p_scb->stream_config.p_avdt_ctrl_cback)( - avdt_scb_to_hdl(p_scb), RawAddress::kEmpty, AVDT_WRITE_CFM_EVT, - &avdt_ctrl, p_scb->stream_config.scb_index); + (*p_scb->stream_config.p_avdt_ctrl_cback)(avdt_scb_to_hdl(p_scb), RawAddress::kEmpty, + AVDT_WRITE_CFM_EVT, &avdt_ctrl, + p_scb->stream_config.scb_index); } } } @@ -1580,10 +1529,8 @@ void avdt_scb_chk_snd_pkt(AvdtpScb* p_scb, tAVDT_SCB_EVT* /* p_data */) { * Returns Nothing. * ******************************************************************************/ -void avdt_scb_transport_channel_timer(AvdtpScb* p_scb, - tAVDT_SCB_EVT* /* p_data */) { - alarm_set_on_mloop(p_scb->transport_channel_timer, - AVDT_SCB_TC_DISC_TIMEOUT_MS, +void avdt_scb_transport_channel_timer(AvdtpScb* p_scb, tAVDT_SCB_EVT* /* p_data */) { + alarm_set_on_mloop(p_scb->transport_channel_timer, AVDT_SCB_TC_DISC_TIMEOUT_MS, avdt_scb_transport_channel_timer_timeout, p_scb); } diff --git a/system/stack/avrc/avrc_api.cc b/system/stack/avrc/avrc_api.cc index a567d59ce4d..6d97d5c6af2 100644 --- a/system/stack/avrc/avrc_api.cc +++ b/system/stack/avrc/avrc_api.cc @@ -55,18 +55,18 @@ using namespace bluetooth; #endif static const uint8_t avrc_ctrl_event_map[] = { - AVRC_OPEN_IND_EVT, /* AVCT_CONNECT_CFM_EVT */ - AVRC_OPEN_IND_EVT, /* AVCT_CONNECT_IND_EVT */ - AVRC_CLOSE_IND_EVT, /* AVCT_DISCONNECT_CFM_EVT */ - AVRC_CLOSE_IND_EVT, /* AVCT_DISCONNECT_IND_EVT */ - AVRC_CONG_IND_EVT, /* AVCT_CONG_IND_EVT */ - AVRC_UNCONG_IND_EVT, /* AVCT_UNCONG_IND_EVT */ - AVRC_BROWSE_OPEN_IND_EVT, /* AVCT_BROWSE_CONN_CFM_EVT */ - AVRC_BROWSE_OPEN_IND_EVT, /* AVCT_BROWSE_CONN_IND_EVT */ - AVRC_BROWSE_CLOSE_IND_EVT, /* AVCT_BROWSE_DISCONN_CFM_EVT */ - AVRC_BROWSE_CLOSE_IND_EVT, /* AVCT_BROWSE_DISCONN_IND_EVT */ - AVRC_BROWSE_CONG_IND_EVT, /* AVCT_BROWSE_CONG_IND_EVT */ - AVRC_BROWSE_UNCONG_IND_EVT /* AVCT_BROWSE_UNCONG_IND_EVT */ + AVRC_OPEN_IND_EVT, /* AVCT_CONNECT_CFM_EVT */ + AVRC_OPEN_IND_EVT, /* AVCT_CONNECT_IND_EVT */ + AVRC_CLOSE_IND_EVT, /* AVCT_DISCONNECT_CFM_EVT */ + AVRC_CLOSE_IND_EVT, /* AVCT_DISCONNECT_IND_EVT */ + AVRC_CONG_IND_EVT, /* AVCT_CONG_IND_EVT */ + AVRC_UNCONG_IND_EVT, /* AVCT_UNCONG_IND_EVT */ + AVRC_BROWSE_OPEN_IND_EVT, /* AVCT_BROWSE_CONN_CFM_EVT */ + AVRC_BROWSE_OPEN_IND_EVT, /* AVCT_BROWSE_CONN_IND_EVT */ + AVRC_BROWSE_CLOSE_IND_EVT, /* AVCT_BROWSE_DISCONN_CFM_EVT */ + AVRC_BROWSE_CLOSE_IND_EVT, /* AVCT_BROWSE_DISCONN_IND_EVT */ + AVRC_BROWSE_CONG_IND_EVT, /* AVCT_BROWSE_CONG_IND_EVT */ + AVRC_BROWSE_UNCONG_IND_EVT /* AVCT_BROWSE_UNCONG_IND_EVT */ }; /* use this unused opcode to indication no need to call the callback function */ @@ -113,14 +113,14 @@ static void avrc_ctrl_cback(uint8_t handle, uint8_t event, uint16_t result, if (event <= AVRC_MAX_RCV_CTRL_EVT && avrc_cb.ccb[handle].ctrl_cback) { avrc_event = avrc_ctrl_event_map[event]; if (event == AVCT_CONNECT_CFM_EVT) { - if (result != 0) /* failed */ + if (result != 0) { /* failed */ avrc_event = AVRC_CLOSE_IND_EVT; + } } avrc_cb.ccb[handle].ctrl_cback.Run(handle, avrc_event, result, peer_addr); } - if ((event == AVCT_DISCONNECT_CFM_EVT) || - (event == AVCT_DISCONNECT_IND_EVT)) { + if ((event == AVCT_DISCONNECT_CFM_EVT) || (event == AVCT_DISCONNECT_IND_EVT)) { avrc_flush_cmd_q(handle); alarm_free(avrc_cb.ccb_int[handle].tle); avrc_cb.ccb_int[handle].tle = NULL; @@ -157,13 +157,13 @@ void avrc_flush_cmd_q(uint8_t handle) { void avrc_process_timeout(void* data) { tAVRC_PARAM* param = (tAVRC_PARAM*)data; - log::verbose("AVRC: command timeout (handle=0x{:02x}, label=0x{:02x})", - param->handle, param->label); + log::verbose("AVRC: command timeout (handle=0x{:02x}, label=0x{:02x})", param->handle, + param->label); /* Notify app */ if (avrc_cb.ccb[param->handle].ctrl_cback) { - avrc_cb.ccb[param->handle].ctrl_cback.Run( - param->handle, AVRC_CMD_TIMEOUT_EVT, param->label, NULL); + avrc_cb.ccb[param->handle].ctrl_cback.Run(param->handle, AVRC_CMD_TIMEOUT_EVT, param->label, + NULL); } /* If vendor command timed-out, then send next command in the queue */ @@ -186,19 +186,16 @@ void avrc_send_next_vendor_cmd(uint8_t handle) { BT_HDR* p_next_cmd; uint8_t next_label; - while ((p_next_cmd = (BT_HDR*)fixed_queue_try_dequeue( - avrc_cb.ccb_int[handle].cmd_q)) != NULL) { + while ((p_next_cmd = (BT_HDR*)fixed_queue_try_dequeue(avrc_cb.ccb_int[handle].cmd_q)) != NULL) { p_next_cmd->event &= 0xFF; /* opcode */ next_label = (p_next_cmd->layer_specific) >> 8; /* extract label */ - p_next_cmd->layer_specific &= 0xFF; /* AVCT_DATA_CTRL or AVCT_DATA_BROWSE */ + p_next_cmd->layer_specific &= 0xFF; /* AVCT_DATA_CTRL or AVCT_DATA_BROWSE */ - log::verbose( - "AVRC: Dequeuing command 0x{} (handle=0x{:02x}, label=0x{:02x})", - fmt::ptr(p_next_cmd), handle, next_label); + log::verbose("AVRC: Dequeuing command 0x{} (handle=0x{:02x}, label=0x{:02x})", + fmt::ptr(p_next_cmd), handle, next_label); /* Send the message */ - if ((AVCT_MsgReq(handle, next_label, AVCT_CMD, p_next_cmd)) == - AVCT_SUCCESS) { + if ((AVCT_MsgReq(handle, next_label, AVCT_CMD, p_next_cmd)) == AVCT_SUCCESS) { /* Start command timer to wait for response */ avrc_start_cmd_timer(handle, next_label, AVRC_MSG_MASK_IS_VENDOR_CMD); return; @@ -221,17 +218,14 @@ void avrc_send_next_vendor_cmd(uint8_t handle) { * *****************************************************************************/ void avrc_start_cmd_timer(uint8_t handle, uint8_t label, uint8_t msg_mask) { - tAVRC_PARAM* param = - static_cast(osi_malloc(sizeof(tAVRC_PARAM))); + tAVRC_PARAM* param = static_cast(osi_malloc(sizeof(tAVRC_PARAM))); param->handle = handle; param->label = label; param->msg_mask = msg_mask; - log::verbose("AVRC: starting timer (handle=0x{:02x}, label=0x{:02x})", handle, - label); + log::verbose("AVRC: starting timer (handle=0x{:02x}, label=0x{:02x})", handle, label); - alarm_set_on_mloop(avrc_cb.ccb_int[handle].tle, AVRC_CMD_TOUT_MS, - avrc_process_timeout, param); + alarm_set_on_mloop(avrc_cb.ccb_int[handle].tle, AVRC_CMD_TOUT_MS, avrc_process_timeout, param); } /****************************************************************************** @@ -243,9 +237,7 @@ void avrc_start_cmd_timer(uint8_t handle, uint8_t label, uint8_t msg_mask) { * Returns A pointer to the data payload. * *****************************************************************************/ -static uint8_t* avrc_get_data_ptr(BT_HDR* p_pkt) { - return (uint8_t*)(p_pkt + 1) + p_pkt->offset; -} +static uint8_t* avrc_get_data_ptr(BT_HDR* p_pkt) { return (uint8_t*)(p_pkt + 1) + p_pkt->offset; } /****************************************************************************** * @@ -298,10 +290,8 @@ static void avrc_prep_end_frag(uint8_t handle) { rsp_type = ((*p_orig_data) & AVRC_CTYPE_MASK); p_pkt_new = p_fcb->p_fmsg; - p_pkt_new->len -= - (AVRC_MAX_CTRL_DATA_LEN - AVRC_VENDOR_HDR_SIZE - AVRC_MIN_META_HDR_SIZE); - p_pkt_new->offset += - (AVRC_MAX_CTRL_DATA_LEN - AVRC_VENDOR_HDR_SIZE - AVRC_MIN_META_HDR_SIZE); + p_pkt_new->len -= (AVRC_MAX_CTRL_DATA_LEN - AVRC_VENDOR_HDR_SIZE - AVRC_MIN_META_HDR_SIZE); + p_pkt_new->offset += (AVRC_MAX_CTRL_DATA_LEN - AVRC_VENDOR_HDR_SIZE - AVRC_MIN_META_HDR_SIZE); p_data = (uint8_t*)(p_pkt_new + 1) + p_pkt_new->offset; *p_data++ = rsp_type; *p_data++ = (AVRC_SUB_PANEL << AVRC_SUBTYPE_SHIFT); @@ -311,8 +301,7 @@ static void avrc_prep_end_frag(uint8_t handle) { *p_data++ = AVRC_PKT_END; /* 4=pdu, pkt_type & len */ - UINT16_TO_BE_STREAM( - p_data, (p_pkt_new->len - AVRC_VENDOR_HDR_SIZE - AVRC_MIN_META_HDR_SIZE)); + UINT16_TO_BE_STREAM(p_data, (p_pkt_new->len - AVRC_VENDOR_HDR_SIZE - AVRC_MIN_META_HDR_SIZE)); } /****************************************************************************** @@ -351,8 +340,7 @@ static uint16_t avrc_send_continue_frag(uint8_t handle, uint8_t label) { p_data++; /* pdu */ *p_data++ = AVRC_PKT_CONTINUE; /* 4=pdu, pkt_type & len */ - UINT16_TO_BE_STREAM(p_data, - (AVRC_MAX_CTRL_DATA_LEN - AVRC_VENDOR_HDR_SIZE - 4)); + UINT16_TO_BE_STREAM(p_data, (AVRC_MAX_CTRL_DATA_LEN - AVRC_VENDOR_HDR_SIZE - 4)); /* prepare the left over for as an end fragment */ avrc_prep_end_frag(handle); @@ -373,8 +361,7 @@ static uint16_t avrc_send_continue_frag(uint8_t handle, uint8_t label) { * Returns if not NULL, the response to send right away. * *****************************************************************************/ -static BT_HDR* avrc_proc_vendor_command(uint8_t handle, uint8_t label, - BT_HDR* p_pkt, +static BT_HDR* avrc_proc_vendor_command(uint8_t handle, uint8_t label, BT_HDR* p_pkt, tAVRC_MSG_VENDOR* p_msg) { BT_HDR* p_rsp = NULL; uint8_t* p_data; @@ -413,8 +400,7 @@ static BT_HDR* avrc_proc_vendor_command(uint8_t handle, uint8_t label, p_pkt->len = (p_data - p_begin); } AVCT_MsgReq(handle, label, AVCT_RSP, p_pkt); - p_msg->hdr.opcode = - AVRC_OP_DROP; /* used the p_pkt to send response */ + p_msg->hdr.opcode = AVRC_OP_DROP; /* used the p_pkt to send response */ break; case AVRC_PDU_REQUEST_CONTINUATION_RSP: @@ -424,9 +410,8 @@ static BT_HDR* avrc_proc_vendor_command(uint8_t handle, uint8_t label, } else { /* the pdu id does not match - reject the command using the current * GKI buffer */ - log::error( - "continue pdu: 0x{:x} does not match the current pdu: 0x{:x}", - *(p_data + 4), p_fcb->frag_pdu); + log::error("continue pdu: 0x{:x} does not match the current pdu: 0x{:x}", *(p_data + 4), + p_fcb->frag_pdu); status = AVRC_STS_BAD_PARAM; abort_frag = true; } @@ -472,8 +457,8 @@ static BT_HDR* avrc_proc_vendor_command(uint8_t handle, uint8_t label, * Returns 0, to report the message with msg_cback . * *****************************************************************************/ -static uint8_t avrc_proc_far_msg(uint8_t handle, uint8_t label, uint8_t cr, - BT_HDR** pp_pkt, tAVRC_MSG_VENDOR* p_msg) { +static uint8_t avrc_proc_far_msg(uint8_t handle, uint8_t label, uint8_t cr, BT_HDR** pp_pkt, + tAVRC_MSG_VENDOR* p_msg) { BT_HDR* p_pkt = *pp_pkt; uint8_t* p_data; uint8_t drop_code = 0; @@ -514,8 +499,7 @@ static uint8_t avrc_proc_far_msg(uint8_t handle, uint8_t label, uint8_t cr, memcpy(p_rcb->p_rmsg, p_pkt, sizeof(BT_HDR)); /* Copy bt hdr */ /* Copy metadata message */ - memcpy((uint8_t*)(p_rcb->p_rmsg + 1), - (uint8_t*)(p_pkt + 1) + p_pkt->offset, p_pkt->len); + memcpy((uint8_t*)(p_rcb->p_rmsg + 1), (uint8_t*)(p_pkt + 1) + p_pkt->offset, p_pkt->len); /* offset of start of metadata response in reassembly buffer */ p_rcb->p_rmsg->offset = p_rcb->rasm_offset = 0; @@ -537,8 +521,8 @@ static uint8_t avrc_proc_far_msg(uint8_t handle, uint8_t label, uint8_t cr, /* Received a CONTINUE/END, but no corresponding START (or previous fragmented response was dropped) */ log::verbose( - "Received a CONTINUE/END without no corresponding START (or previous " - "fragmented response was dropped)"); + "Received a CONTINUE/END without no corresponding START (or previous " + "fragmented response was dropped)"); drop_code = 5; osi_free(p_pkt); *pp_pkt = NULL; @@ -577,10 +561,9 @@ static uint8_t avrc_proc_far_msg(uint8_t handle, uint8_t label, uint8_t cr, p_msg->vendor_len = p_pkt_new->len - AVRC_VENDOR_HDR_SIZE; p_data = p_msg->p_vendor_data + 1; /* skip pdu */ *p_data++ = AVRC_PKT_SINGLE; - UINT16_TO_BE_STREAM(p_data, - (p_msg->vendor_len - AVRC_MIN_META_HDR_SIZE)); - log::verbose("end frag:{}, total len:{}, offset:{}", p_pkt->len, - p_pkt_new->len, p_pkt_new->offset); + UINT16_TO_BE_STREAM(p_data, (p_msg->vendor_len - AVRC_MIN_META_HDR_SIZE)); + log::verbose("end frag:{}, total len:{}, offset:{}", p_pkt->len, p_pkt_new->len, + p_pkt_new->offset); } else { p_rcb->p_rmsg->offset += p_pkt->len; p_rcb->p_rmsg->len += p_pkt->len; @@ -600,8 +583,9 @@ static uint8_t avrc_proc_far_msg(uint8_t handle, uint8_t label, uint8_t cr, drop_code = 3; } else if (p_msg->hdr.opcode == AVRC_OP_DROP) { drop_code = 1; - } else if (p_msg->hdr.opcode == AVRC_OP_DROP_N_FREE) + } else if (p_msg->hdr.opcode == AVRC_OP_DROP_N_FREE) { drop_code = 4; + } } else if (cr == AVCT_RSP) { if (req_continue) { @@ -640,8 +624,7 @@ static uint8_t avrc_proc_far_msg(uint8_t handle, uint8_t label, uint8_t cr, * Returns Nothing. * *****************************************************************************/ -static void avrc_msg_cback(uint8_t handle, uint8_t label, uint8_t cr, - BT_HDR* p_pkt) { +static void avrc_msg_cback(uint8_t handle, uint8_t label, uint8_t cr, BT_HDR* p_pkt) { uint8_t opcode; tAVRC_MSG msg; uint8_t* p_data; @@ -655,10 +638,8 @@ static void avrc_msg_cback(uint8_t handle, uint8_t label, uint8_t cr, const char* p_drop_msg = "dropped"; tAVRC_MSG_VENDOR* p_msg = &msg.vendor; - if (cr == AVCT_CMD && (p_pkt->layer_specific & AVCT_DATA_CTRL && - p_pkt->len > AVRC_PACKET_LEN)) { - log::warn("Command length {} too long: must be at most {}", p_pkt->len, - AVRC_PACKET_LEN); + if (cr == AVCT_CMD && (p_pkt->layer_specific & AVCT_DATA_CTRL && p_pkt->len > AVRC_PACKET_LEN)) { + log::warn("Command length {} too long: must be at most {}", p_pkt->len, AVRC_PACKET_LEN); osi_free(p_pkt); return; } @@ -686,16 +667,14 @@ static void avrc_msg_cback(uint8_t handle, uint8_t label, uint8_t cr, msg.browse.p_browse_pkt = p_pkt; } else { if (p_pkt->len < AVRC_AVC_HDR_SIZE) { - log::warn("message length {} too short: must be at least {}", p_pkt->len, - AVRC_AVC_HDR_SIZE); + log::warn("message length {} too short: must be at least {}", p_pkt->len, AVRC_AVC_HDR_SIZE); osi_free(p_pkt); return; } msg.hdr.ctype = p_data[0] & AVRC_CTYPE_MASK; - log::verbose("handle:{}, ctype:{}, offset:{}, len: {}", handle, - msg.hdr.ctype, p_pkt->offset, p_pkt->len); - msg.hdr.subunit_type = - (p_data[1] & AVRC_SUBTYPE_MASK) >> AVRC_SUBTYPE_SHIFT; + log::verbose("handle:{}, ctype:{}, offset:{}, len: {}", handle, msg.hdr.ctype, p_pkt->offset, + p_pkt->len); + msg.hdr.subunit_type = (p_data[1] & AVRC_SUBTYPE_MASK) >> AVRC_SUBTYPE_SHIFT; msg.hdr.subunit_id = p_data[1] & AVRC_SUBID_MASK; opcode = p_data[2]; } @@ -718,22 +697,20 @@ static void avrc_msg_cback(uint8_t handle, uint8_t label, uint8_t cr, /* Panel subunit & id=0 */ *p_rsp_data++ = (AVRC_SUB_PANEL << AVRC_SUBTYPE_SHIFT); AVRC_CO_ID_TO_BE_STREAM(p_rsp_data, avrc_cb.ccb[handle].company_id); - p_rsp->len = - (uint16_t)(p_rsp_data - (uint8_t*)(p_rsp + 1) - p_rsp->offset); + p_rsp->len = (uint16_t)(p_rsp_data - (uint8_t*)(p_rsp + 1) - p_rsp->offset); cr = AVCT_RSP; p_drop_msg = "auto respond"; } else { /* parse response */ if (p_pkt->len < AVRC_OP_UNIT_INFO_RSP_LEN) { - log::warn("message length {} too short: must be at least {}", - p_pkt->len, AVRC_OP_UNIT_INFO_RSP_LEN); + log::warn("message length {} too short: must be at least {}", p_pkt->len, + AVRC_OP_UNIT_INFO_RSP_LEN); drop = true; p_drop_msg = "UNIT_INFO_RSP too short"; break; } p_data += 4; /* 3 bytes: ctype, subunit*, opcode + octet 3 (is 7)*/ - msg.unit.unit_type = - (*p_data & AVRC_SUBTYPE_MASK) >> AVRC_SUBTYPE_SHIFT; + msg.unit.unit_type = (*p_data & AVRC_SUBTYPE_MASK) >> AVRC_SUBTYPE_SHIFT; msg.unit.unit = *p_data & AVRC_SUBID_MASK; p_data++; AVRC_BE_STREAM_TO_CO_ID(msg.unit.company_id, p_data); @@ -754,27 +731,26 @@ static void avrc_msg_cback(uint8_t handle, uint8_t label, uint8_t cr, *p_rsp_data++ = (AVRC_SUB_PANEL << AVRC_SUBTYPE_SHIFT); memset(p_rsp_data, AVRC_CMD_OPRND_PAD, AVRC_SUBRSP_OPRND_BYTES); p_rsp_data += AVRC_SUBRSP_OPRND_BYTES; - p_rsp->len = - (uint16_t)(p_rsp_data - (uint8_t*)(p_rsp + 1) - p_rsp->offset); + p_rsp->len = (uint16_t)(p_rsp_data - (uint8_t*)(p_rsp + 1) - p_rsp->offset); cr = AVCT_RSP; p_drop_msg = "auto responded"; } else { /* parse response */ if (p_pkt->len < AVRC_OP_SUB_UNIT_INFO_RSP_LEN) { - log::warn("message length {} too short: must be at least {}", - p_pkt->len, AVRC_OP_SUB_UNIT_INFO_RSP_LEN); + log::warn("message length {} too short: must be at least {}", p_pkt->len, + AVRC_OP_SUB_UNIT_INFO_RSP_LEN); drop = true; p_drop_msg = "SUB_UNIT_INFO_RSP too short"; break; } p_data += AVRC_AVC_HDR_SIZE; /* 3 bytes: ctype, subunit*, opcode */ - msg.sub.page = - (*p_data++ >> AVRC_SUB_PAGE_SHIFT) & AVRC_SUB_PAGE_MASK; + msg.sub.page = (*p_data++ >> AVRC_SUB_PAGE_SHIFT) & AVRC_SUB_PAGE_MASK; xx = 0; while (*p_data != AVRC_CMD_OPRND_PAD && xx < AVRC_SUB_TYPE_LEN) { msg.sub.subunit_type[xx] = *p_data++ >> AVRC_SUBTYPE_SHIFT; - if (msg.sub.subunit_type[xx] == AVRC_SUB_PANEL) + if (msg.sub.subunit_type[xx] == AVRC_SUB_PANEL) { msg.sub.panel = true; + } xx++; } } @@ -783,13 +759,13 @@ static void avrc_msg_cback(uint8_t handle, uint8_t label, uint8_t cr, case AVRC_OP_VENDOR: { p_data = (uint8_t*)(p_pkt + 1) + p_pkt->offset; p_begin = p_data; - if (p_pkt->len < - AVRC_VENDOR_HDR_SIZE) /* 6 = ctype, subunit*, opcode & CO_ID */ + if (p_pkt->len < AVRC_VENDOR_HDR_SIZE) /* 6 = ctype, subunit*, opcode & CO_ID */ { - if (cr == AVCT_CMD) + if (cr == AVCT_CMD) { reject = true; - else + } else { drop = true; + } break; } p_data += AVRC_AVC_HDR_SIZE; /* skip the first 3 bytes: ctype, subunit*, @@ -802,19 +778,24 @@ static void avrc_msg_cback(uint8_t handle, uint8_t label, uint8_t cr, if (p_msg->company_id == AVRC_CO_METADATA) { /* Validate length for metadata message */ if (p_pkt->len < (AVRC_VENDOR_HDR_SIZE + AVRC_MIN_META_HDR_SIZE)) { - if (cr == AVCT_CMD) + if (cr == AVCT_CMD) { reject = true; - else + } else { drop = true; + } break; } /* Check+handle fragmented messages */ drop_code = avrc_proc_far_msg(handle, label, cr, &p_pkt, p_msg); - if (drop_code > 0) drop = true; + if (drop_code > 0) { + drop = true; + } } if (drop_code > 0) { - if (drop_code != 4) do_free = false; + if (drop_code != 4) { + do_free = false; + } switch (drop_code) { case 1: p_drop_msg = "sent_frag"; @@ -842,27 +823,31 @@ static void avrc_msg_cback(uint8_t handle, uint8_t label, uint8_t cr, case AVRC_OP_PASS_THRU: if (p_pkt->len < 5) /* 3 bytes: ctype, subunit*, opcode & op_id & len */ { - if (cr == AVCT_CMD) + if (cr == AVCT_CMD) { reject = true; - else + } else { drop = true; + } break; } p_data += AVRC_AVC_HDR_SIZE; /* skip the first 3 bytes: ctype, subunit*, opcode */ msg.pass.op_id = (AVRC_PASS_OP_ID_MASK & *p_data); - if (AVRC_PASS_STATE_MASK & *p_data) + if (AVRC_PASS_STATE_MASK & *p_data) { msg.pass.state = true; - else + } else { msg.pass.state = false; + } p_data++; msg.pass.pass_len = *p_data++; - if (msg.pass.pass_len != p_pkt->len - 5) + if (msg.pass.pass_len != p_pkt->len - 5) { msg.pass.pass_len = p_pkt->len - 5; - if (msg.pass.pass_len) + } + if (msg.pass.pass_len) { msg.pass.p_pass_data = p_data; - else + } else { msg.pass.p_pass_data = NULL; + } break; case AVRC_OP_BROWSE: @@ -874,8 +859,7 @@ static void avrc_msg_cback(uint8_t handle, uint8_t label, uint8_t cr, break; default: - if ((avrc_cb.ccb[handle].control & AVRC_CT_TARGET) && - (cr == AVCT_CMD)) { + if ((avrc_cb.ccb[handle].control & AVRC_CT_TARGET) && (cr == AVCT_CMD)) { /* reject unsupported opcode */ reject = true; } @@ -884,7 +868,9 @@ static void avrc_msg_cback(uint8_t handle, uint8_t label, uint8_t cr, } } else /* drop the event */ { - if (opcode != AVRC_OP_BROWSE) drop = true; + if (opcode != AVRC_OP_BROWSE) { + drop = true; + } } if (reject) { @@ -907,15 +893,17 @@ static void avrc_msg_cback(uint8_t handle, uint8_t label, uint8_t cr, msg.hdr.opcode = opcode; avrc_cb.ccb[handle].msg_cback.Run(handle, label, opcode, &msg); } else { - log::warn("{} msg handle:{}, control:{}, cr:{}, opcode:x{:x}", p_drop_msg, - handle, avrc_cb.ccb[handle].control, cr, opcode); + log::warn("{} msg handle:{}, control:{}, cr:{}, opcode:x{:x}", p_drop_msg, handle, + avrc_cb.ccb[handle].control, cr, opcode); } if (opcode == AVRC_OP_BROWSE && msg.browse.p_browse_pkt == NULL) { do_free = false; } - if (do_free) osi_free(p_pkt); + if (do_free) { + osi_free(p_pkt); + } } /****************************************************************************** @@ -949,7 +937,9 @@ static BT_HDR* avrc_pass_msg(tAVRC_MSG_PASS* p_msg) { *p_data++ = (AVRC_SUB_PANEL << AVRC_SUBTYPE_SHIFT); /* Panel subunit & id=0 */ *p_data++ = AVRC_OP_PASS_THRU; *p_data = (AVRC_PASS_OP_ID_MASK & p_msg->op_id); - if (p_msg->state) *p_data |= AVRC_PASS_STATE_MASK; + if (p_msg->state) { + *p_data |= AVRC_PASS_STATE_MASK; + } p_data++; if (p_msg->op_id == AVRC_ID_VENDOR) { @@ -983,16 +973,13 @@ uint16_t AVRC_GetControlProfileVersion() { uint16_t profile_version = AVRC_REV_1_3; char avrcp_version[PROPERTY_VALUE_MAX] = {0}; osi_property_get(AVRC_CONTROL_VERSION_PROPERTY, avrcp_version, - strncmp(volume_disabled, "true", 4) == 0 ? AVRC_1_3_STRING - : AVRC_1_4_STRING); + strncmp(volume_disabled, "true", 4) == 0 ? AVRC_1_3_STRING : AVRC_1_4_STRING); if (!strncmp(AVRC_1_6_STRING, avrcp_version, sizeof(AVRC_1_6_STRING))) { profile_version = AVRC_REV_1_6; - } else if (!strncmp(AVRC_1_5_STRING, avrcp_version, - sizeof(AVRC_1_5_STRING))) { + } else if (!strncmp(AVRC_1_5_STRING, avrcp_version, sizeof(AVRC_1_5_STRING))) { profile_version = AVRC_REV_1_5; - } else if (!strncmp(AVRC_1_4_STRING, avrcp_version, - sizeof(AVRC_1_4_STRING))) { + } else if (!strncmp(AVRC_1_4_STRING, avrcp_version, sizeof(AVRC_1_4_STRING))) { profile_version = AVRC_REV_1_4; } @@ -1015,11 +1002,9 @@ uint16_t AVRC_GetProfileVersion() { if (!strncmp(AVRC_1_6_STRING, avrcp_version, sizeof(AVRC_1_6_STRING))) { profile_version = AVRC_REV_1_6; - } else if (!strncmp(AVRC_1_5_STRING, avrcp_version, - sizeof(AVRC_1_5_STRING))) { + } else if (!strncmp(AVRC_1_5_STRING, avrcp_version, sizeof(AVRC_1_5_STRING))) { profile_version = AVRC_REV_1_5; - } else if (!strncmp(AVRC_1_3_STRING, avrcp_version, - sizeof(AVRC_1_3_STRING))) { + } else if (!strncmp(AVRC_1_3_STRING, avrcp_version, sizeof(AVRC_1_3_STRING))) { profile_version = AVRC_REV_1_3; } @@ -1074,8 +1059,7 @@ uint16_t AVRC_GetProfileVersion() { * the connection. * *****************************************************************************/ -uint16_t AVRC_Open(uint8_t* p_handle, tAVRC_CONN_CB* p_ccb, - const RawAddress& peer_addr) { +uint16_t AVRC_Open(uint8_t* p_handle, tAVRC_CONN_CB* p_ccb, const RawAddress& peer_addr) { uint16_t status; tAVCT_CC cc; @@ -1094,8 +1078,7 @@ uint16_t AVRC_Open(uint8_t* p_handle, tAVRC_CONN_CB* p_ccb, avrc_cb.ccb_int[*p_handle].tle = alarm_new("avrcp.commandTimer"); avrc_cb.ccb_int[*p_handle].cmd_q = fixed_queue_new(SIZE_MAX); } - log::verbose("role: {}, control:{} status:{}, handle:{}", cc.role, cc.control, - status, *p_handle); + log::verbose("role: {}, control:{} status:{}, handle:{}", cc.role, cc.control, status, *p_handle); return status; } @@ -1176,8 +1159,8 @@ uint16_t AVRC_CloseBrowse(uint8_t handle) { return AVCT_RemoveBrowse(handle); } * *****************************************************************************/ /* legacy and new avrcp send the different packet format for VENDOR op */ -uint16_t AVRC_MsgReq(uint8_t handle, uint8_t label, uint8_t ctype, - BT_HDR* p_pkt, bool is_new_avrcp) { +uint16_t AVRC_MsgReq(uint8_t handle, uint8_t label, uint8_t ctype, BT_HDR* p_pkt, + bool is_new_avrcp) { uint8_t* p_data; uint8_t cr = AVCT_CMD; bool chk_frag = true; @@ -1188,15 +1171,18 @@ uint16_t AVRC_MsgReq(uint8_t handle, uint8_t label, uint8_t ctype, uint8_t msg_mask = 0; uint16_t peer_mtu; - if (!p_pkt) return AVRC_BAD_PARAM; + if (!p_pkt) { + return AVRC_BAD_PARAM; + } - log::verbose("handle = {} label = {} ctype = {} len = {}", handle, label, - ctype, p_pkt->len); + log::verbose("handle = {} label = {} ctype = {} len = {}", handle, label, ctype, p_pkt->len); /* Handle for AVRCP fragment */ - if (btif_av_src_sink_coexist_enabled()) - is_new_avrcp = - osi_property_get_bool("bluetooth.profile.avrcp.target.enabled", false); - if (ctype >= AVRC_RSP_NOT_IMPL) cr = AVCT_RSP; + if (btif_av_src_sink_coexist_enabled()) { + is_new_avrcp = osi_property_get_bool("bluetooth.profile.avrcp.target.enabled", false); + } + if (ctype >= AVRC_RSP_NOT_IMPL) { + cr = AVCT_RSP; + } if (p_pkt->event == AVRC_OP_VENDOR) { if (is_new_avrcp) { @@ -1242,8 +1228,8 @@ uint16_t AVRC_MsgReq(uint8_t handle, uint8_t label, uint8_t ctype, peer_mtu = AVCT_GetPeerMtu(handle); } if (p_pkt->len > (peer_mtu - AVCT_HDR_LEN_SINGLE)) { - log::error("bigger than peer mtu (p_pkt->len({}) > peer_mtu({}-{}))", - p_pkt->len, peer_mtu, AVCT_HDR_LEN_SINGLE); + log::error("bigger than peer mtu (p_pkt->len({}) > peer_mtu({}-{}))", p_pkt->len, peer_mtu, + AVCT_HDR_LEN_SINGLE); osi_free(p_pkt); return AVRC_MSG_TOO_BIG; } @@ -1258,7 +1244,9 @@ uint16_t AVRC_MsgReq(uint8_t handle, uint8_t label, uint8_t ctype, return AVRC_NOT_OPEN; } - if (p_fcb->frag_enabled) p_fcb->frag_enabled = false; + if (p_fcb->frag_enabled) { + p_fcb->frag_enabled = false; + } osi_free_and_reset((void**)&p_fcb->p_fmsg); @@ -1268,8 +1256,7 @@ uint16_t AVRC_MsgReq(uint8_t handle, uint8_t label, uint8_t ctype, if ((cr == AVCT_RSP) && (chk_frag)) { if (p_pkt->len > AVRC_MAX_CTRL_DATA_LEN) { int offset_len = MAX(AVCT_MSG_OFFSET, p_pkt->offset); - BT_HDR* p_pkt_new = - (BT_HDR*)osi_calloc(AVRC_PACKET_LEN + offset_len + BT_HDR_SIZE); + BT_HDR* p_pkt_new = (BT_HDR*)osi_calloc(AVRC_PACKET_LEN + offset_len + BT_HDR_SIZE); if (p_start != NULL) { p_fcb->frag_enabled = true; p_fcb->p_fmsg = p_pkt; @@ -1289,14 +1276,12 @@ uint16_t AVRC_MsgReq(uint8_t handle, uint8_t label, uint8_t ctype, *p_data++ = AVRC_PKT_START; /* 4 pdu, pkt_type & len */ - len = (AVRC_MAX_CTRL_DATA_LEN - AVRC_VENDOR_HDR_SIZE - - AVRC_MIN_META_HDR_SIZE); + len = (AVRC_MAX_CTRL_DATA_LEN - AVRC_VENDOR_HDR_SIZE - AVRC_MIN_META_HDR_SIZE); UINT16_TO_BE_STREAM(p_data, len); /* prepare the left over for as an end fragment */ avrc_prep_end_frag(handle); - log::verbose("p_pkt len:{}/{}, next len:{}", p_pkt->len, len, - p_fcb->p_fmsg->len); + log::verbose("p_pkt len:{}/{}, next len:{}", p_pkt->len, len, p_fcb->p_fmsg->len); } else { /* TODO: Is this "else" block valid? Remove it? */ log::error("no buffers for fragmentation"); @@ -1313,9 +1298,8 @@ uint16_t AVRC_MsgReq(uint8_t handle, uint8_t label, uint8_t ctype, * command * is received (exception is continuation request command * must sent that to get additional response frags) */ - log::verbose( - "AVRC: Enqueuing command 0x{} (handle=0x{:02x}, label=0x{:02x})", - fmt::ptr(p_pkt), handle, label); + log::verbose("AVRC: Enqueuing command 0x{} (handle=0x{:02x}, label=0x{:02x})", fmt::ptr(p_pkt), + handle, label); /* label in BT_HDR (will need this later when the command is dequeued) */ p_pkt->layer_specific = (label << 8) | (p_pkt->layer_specific & 0xFF); @@ -1365,7 +1349,9 @@ uint16_t AVRC_MsgReq(uint8_t handle, uint8_t label, uint8_t ctype, uint16_t AVRC_PassCmd(uint8_t handle, uint8_t label, tAVRC_MSG_PASS* p_msg) { BT_HDR* p_buf; uint16_t status = AVRC_NO_RESOURCES; - if (!p_msg) return AVRC_BAD_PARAM; + if (!p_msg) { + return AVRC_BAD_PARAM; + } p_msg->hdr.ctype = AVRC_CMD_CTRL; p_buf = avrc_pass_msg(p_msg); @@ -1376,7 +1362,7 @@ uint16_t AVRC_PassCmd(uint8_t handle, uint8_t label, tAVRC_MSG_PASS* p_msg) { avrc_start_cmd_timer(handle, label, 0); } } - return (status); + return status; } /****************************************************************************** @@ -1407,10 +1393,14 @@ uint16_t AVRC_PassCmd(uint8_t handle, uint8_t label, tAVRC_MSG_PASS* p_msg) { *****************************************************************************/ uint16_t AVRC_PassRsp(uint8_t handle, uint8_t label, tAVRC_MSG_PASS* p_msg) { BT_HDR* p_buf; - if (!p_msg) return AVRC_BAD_PARAM; + if (!p_msg) { + return AVRC_BAD_PARAM; + } p_buf = avrc_pass_msg(p_msg); - if (p_buf) return AVCT_MsgReq(handle, label, AVCT_RSP, p_buf); + if (p_buf) { + return AVCT_MsgReq(handle, label, AVCT_RSP, p_buf); + } return AVRC_NO_RESOURCES; } @@ -1433,21 +1423,17 @@ uint16_t AVRC_PassRsp(uint8_t handle, uint8_t label, tAVRC_MSG_PASS* p_msg) { * Returns Nothing * *****************************************************************************/ -void AVRC_SaveControllerVersion(const RawAddress& bdaddr, - uint16_t new_version) { +void AVRC_SaveControllerVersion(const RawAddress& bdaddr, uint16_t new_version) { // store AVRC controller version into BT config uint16_t old_version = 0; size_t version_value_size = sizeof(old_version); - if (btif_config_get_bin(bdaddr.ToString(), - BTIF_STORAGE_KEY_AVRCP_CONTROLLER_VERSION, + if (btif_config_get_bin(bdaddr.ToString(), BTIF_STORAGE_KEY_AVRCP_CONTROLLER_VERSION, (uint8_t*)&old_version, &version_value_size) && new_version == old_version) { log::info("AVRC controller version same as cached config"); - } else if (btif_config_set_bin( - bdaddr.ToString(), BTIF_STORAGE_KEY_AVRCP_CONTROLLER_VERSION, - (const uint8_t*)&new_version, sizeof(new_version))) { - log::info("store AVRC controller version {:x} for {} into config.", - new_version, bdaddr); + } else if (btif_config_set_bin(bdaddr.ToString(), BTIF_STORAGE_KEY_AVRCP_CONTROLLER_VERSION, + (const uint8_t*)&new_version, sizeof(new_version))) { + log::info("store AVRC controller version {:x} for {} into config.", new_version, bdaddr); } else { log::warn("Failed to store AVRC controller version for {}", bdaddr); } diff --git a/system/stack/avrc/avrc_bld_ct.cc b/system/stack/avrc/avrc_bld_ct.cc index b619bf09abe..3ec21640460 100644 --- a/system/stack/avrc/avrc_bld_ct.cc +++ b/system/stack/avrc/avrc_bld_ct.cc @@ -55,7 +55,7 @@ static tAVRC_STS avrc_bld_next_cmd(tAVRC_NEXT_CMD* p_cmd, BT_HDR* p_pkt) { p_start = (uint8_t*)(p_pkt + 1) + p_pkt->offset; p_data = p_start + 2; /* pdu + rsvd */ - /* add fixed lenth 1 - pdu_id (1) */ + /* add fixed length 1 - pdu_id (1) */ UINT16_TO_BE_STREAM(p_data, 1); UINT8_TO_BE_STREAM(p_data, p_cmd->target_pdu); p_pkt->len = (p_data - p_start); @@ -77,15 +77,14 @@ static tAVRC_STS avrc_bld_next_cmd(tAVRC_NEXT_CMD* p_cmd, BT_HDR* p_pkt) { * Otherwise, the error code. * ******************************************************************************/ -static tAVRC_STS avrc_bld_set_abs_volume_cmd(tAVRC_SET_VOLUME_CMD* p_cmd, - BT_HDR* p_pkt) { +static tAVRC_STS avrc_bld_set_abs_volume_cmd(tAVRC_SET_VOLUME_CMD* p_cmd, BT_HDR* p_pkt) { uint8_t *p_data, *p_start; log::verbose("avrc_bld_set_abs_volume_cmd"); /* get the existing length, if any, and also the num attributes */ p_start = (uint8_t*)(p_pkt + 1) + p_pkt->offset; p_data = p_start + 2; /* pdu + rsvd */ - /* add fixed lenth 1 - volume (1) */ + /* add fixed length 1 - volume (1) */ UINT16_TO_BE_STREAM(p_data, 1); UINT8_TO_BE_STREAM(p_data, (AVRC_MAX_VOLUME & p_cmd->volume)); p_pkt->len = (p_data - p_start); @@ -102,8 +101,7 @@ static tAVRC_STS avrc_bld_set_abs_volume_cmd(tAVRC_SET_VOLUME_CMD* p_cmd, * Otherwise, the error code. * ******************************************************************************/ -static tAVRC_STS avrc_bld_register_notifn(BT_HDR* p_pkt, uint8_t event_id, - uint32_t event_param) { +static tAVRC_STS avrc_bld_register_notifn(BT_HDR* p_pkt, uint8_t event_id, uint32_t event_param) { uint8_t *p_data, *p_start; log::verbose("avrc_bld_register_notifn"); @@ -170,8 +168,7 @@ static tAVRC_STS avrc_bld_list_player_app_attr_cmd(BT_HDR* p_pkt) { * Otherwise, the error code. * ******************************************************************************/ -static tAVRC_STS avrc_bld_list_player_app_values_cmd(BT_HDR* p_pkt, - uint8_t attrib_id) { +static tAVRC_STS avrc_bld_list_player_app_values_cmd(BT_HDR* p_pkt, uint8_t attrib_id) { log::verbose("avrc_bld_list_player_app_values_cmd"); uint8_t* p_start = (uint8_t*)(p_pkt + 1) + p_pkt->offset; uint8_t* p_data = p_start + 2; /* pdu + rsvd */ @@ -193,13 +190,12 @@ static tAVRC_STS avrc_bld_list_player_app_values_cmd(BT_HDR* p_pkt, * Otherwise, the error code. * ******************************************************************************/ -static tAVRC_STS avrc_bld_get_current_player_app_values_cmd( - BT_HDR* p_pkt, uint8_t num_attrib_id, uint8_t* attrib_ids) { +static tAVRC_STS avrc_bld_get_current_player_app_values_cmd(BT_HDR* p_pkt, uint8_t num_attrib_id, + uint8_t* attrib_ids) { log::verbose("avrc_bld_get_current_player_app_values_cmd"); uint8_t* p_start = (uint8_t*)(p_pkt + 1) + p_pkt->offset; - uint8_t* p_data = p_start + 2; /* pdu + rsvd */ - uint8_t param_len = - num_attrib_id + 1; // 1 additional to hold num attributes feild + uint8_t* p_data = p_start + 2; /* pdu + rsvd */ + uint8_t param_len = num_attrib_id + 1; // 1 additional to hold num attributes field /* add length -*/ UINT16_TO_BE_STREAM(p_data, param_len); UINT8_TO_BE_STREAM(p_data, num_attrib_id); @@ -221,8 +217,8 @@ static tAVRC_STS avrc_bld_get_current_player_app_values_cmd( * Otherwise, the error code. * ******************************************************************************/ -static tAVRC_STS avrc_bld_set_current_player_app_values_cmd( - BT_HDR* p_pkt, uint8_t num_attrib_id, tAVRC_APP_SETTING* p_val) { +static tAVRC_STS avrc_bld_set_current_player_app_values_cmd(BT_HDR* p_pkt, uint8_t num_attrib_id, + tAVRC_APP_SETTING* p_val) { log::verbose("avrc_bld_set_current_player_app_values_cmd"); uint8_t* p_start = (uint8_t*)(p_pkt + 1) + p_pkt->offset; uint8_t* p_data = p_start + 2; /* pdu + rsvd */ @@ -252,8 +248,8 @@ static tAVRC_STS avrc_bld_set_current_player_app_values_cmd( * Otherwise, the error code. * ******************************************************************************/ -static tAVRC_STS avrc_bld_get_player_app_setting_attr_text_cmd( - BT_HDR* p_pkt, tAVRC_GET_APP_ATTR_TXT_CMD* p_cmd) { +static tAVRC_STS avrc_bld_get_player_app_setting_attr_text_cmd(BT_HDR* p_pkt, + tAVRC_GET_APP_ATTR_TXT_CMD* p_cmd) { log::verbose(""); uint8_t* p_start = (uint8_t*)(p_pkt + 1) + p_pkt->offset; @@ -281,8 +277,8 @@ static tAVRC_STS avrc_bld_get_player_app_setting_attr_text_cmd( * Otherwise, the error code. * ******************************************************************************/ -static tAVRC_STS avrc_bld_get_player_app_setting_value_text_cmd( - BT_HDR* p_pkt, tAVRC_GET_APP_VAL_TXT_CMD* p_cmd) { +static tAVRC_STS avrc_bld_get_player_app_setting_value_text_cmd(BT_HDR* p_pkt, + tAVRC_GET_APP_VAL_TXT_CMD* p_cmd) { log::verbose(""); uint8_t* p_start = (uint8_t*)(p_pkt + 1) + p_pkt->offset; @@ -309,8 +305,7 @@ static tAVRC_STS avrc_bld_get_player_app_setting_value_text_cmd( * Otherwise, the error code. * ******************************************************************************/ -static tAVRC_STS avrc_bld_get_element_attr_cmd(BT_HDR* p_pkt, - uint8_t num_attrib, +static tAVRC_STS avrc_bld_get_element_attr_cmd(BT_HDR* p_pkt, uint8_t num_attrib, uint32_t* attrib_ids) { log::verbose("avrc_bld_get_element_attr_cmd"); uint8_t* p_start = (uint8_t*)(p_pkt + 1) + p_pkt->offset; @@ -342,8 +337,8 @@ static tAVRC_STS avrc_bld_get_element_attr_cmd(BT_HDR* p_pkt, * Otherwise, the error code. * ******************************************************************************/ -static tAVRC_STS avrc_bld_play_item_cmd(BT_HDR* p_pkt, uint8_t scope, - uint8_t* uid, uint16_t uid_counter) { +static tAVRC_STS avrc_bld_play_item_cmd(BT_HDR* p_pkt, uint8_t scope, uint8_t* uid, + uint16_t uid_counter) { log::verbose("avrc_bld_get_element_attr_cmd"); uint8_t* p_start = (uint8_t*)(p_pkt + 1) + p_pkt->offset; uint8_t* p_data = p_start + 2; /* pdu + rsvd */ @@ -389,11 +384,9 @@ static tAVRC_STS avrc_bld_get_play_status_cmd(BT_HDR* p_pkt) { * Otherwise, the error code. * ******************************************************************************/ -static tAVRC_STS avrc_bld_get_folder_items_cmd(BT_HDR* p_pkt, - const tAVRC_GET_ITEMS_CMD* cmd) { - log::verbose( - "avrc_bld_get_folder_items_cmd scope {}, start_item {}, end_item {}", - cmd->scope, cmd->start_item, cmd->end_item); +static tAVRC_STS avrc_bld_get_folder_items_cmd(BT_HDR* p_pkt, const tAVRC_GET_ITEMS_CMD* cmd) { + log::verbose("avrc_bld_get_folder_items_cmd scope {}, start_item {}, end_item {}", cmd->scope, + cmd->start_item, cmd->end_item); uint8_t* p_start = (uint8_t*)(p_pkt + 1) + p_pkt->offset; /* This is where the PDU specific for AVRC starts * AVRCP Spec 1.4 section 22.19 */ @@ -406,7 +399,7 @@ static tAVRC_STS avrc_bld_get_folder_items_cmd(BT_HDR* p_pkt, UINT8_TO_BE_STREAM(p_data, cmd->scope); /* scope (1bytes) */ UINT32_TO_BE_STREAM(p_data, cmd->start_item); /* start item (4bytes) */ UINT32_TO_BE_STREAM(p_data, cmd->end_item); /* end item (4bytes) */ - UINT8_TO_BE_STREAM(p_data, 0); /* attribute count = 0 (1bytes) */ + UINT8_TO_BE_STREAM(p_data, 0); /* attribute count = 0 (1bytes) */ p_pkt->len = (p_data - p_start); return AVRC_STS_NO_ERROR; } @@ -421,8 +414,7 @@ static tAVRC_STS avrc_bld_get_folder_items_cmd(BT_HDR* p_pkt, * Otherwise, the error code. * ******************************************************************************/ -static tAVRC_STS avrc_bld_change_folder_cmd(BT_HDR* p_pkt, - const tAVRC_CHG_PATH_CMD* cmd) { +static tAVRC_STS avrc_bld_change_folder_cmd(BT_HDR* p_pkt, const tAVRC_CHG_PATH_CMD* cmd) { log::verbose("avrc_bld_change_folder_cmd"); uint8_t* p_start = (uint8_t*)(p_pkt + 1) + p_pkt->offset; /* This is where the PDU specific for AVRC starts @@ -439,8 +431,7 @@ static tAVRC_STS avrc_bld_change_folder_cmd(BT_HDR* p_pkt, p_pkt->len = (p_data - p_start); return AVRC_STS_NO_ERROR; } -static tAVRC_STS avrc_bld_get_item_attributes_cmd( - BT_HDR* p_pkt, const tAVRC_GET_ATTRS_CMD* cmd) { +static tAVRC_STS avrc_bld_get_item_attributes_cmd(BT_HDR* p_pkt, const tAVRC_GET_ATTRS_CMD* cmd) { log::verbose(""); uint8_t* p_start = (uint8_t*)(p_pkt + 1) + p_pkt->offset; /* This is where the PDU specific for AVRC starts @@ -467,8 +458,8 @@ static tAVRC_STS avrc_bld_get_item_attributes_cmd( * Otherwise, the error code. * ******************************************************************************/ -static tAVRC_STS avrc_bld_set_browsed_player_cmd( - BT_HDR* p_pkt, const tAVRC_SET_BR_PLAYER_CMD* cmd) { +static tAVRC_STS avrc_bld_set_browsed_player_cmd(BT_HDR* p_pkt, + const tAVRC_SET_BR_PLAYER_CMD* cmd) { log::verbose(""); uint8_t* p_start = (uint8_t*)(p_pkt + 1) + p_pkt->offset; /* This is where the PDU specific for AVRC starts @@ -494,8 +485,8 @@ static tAVRC_STS avrc_bld_set_browsed_player_cmd( * Otherwise, the error code. * ******************************************************************************/ -static tAVRC_STS avrc_bld_set_addressed_player_cmd( - BT_HDR* p_pkt, const tAVRC_SET_ADDR_PLAYER_CMD* cmd) { +static tAVRC_STS avrc_bld_set_addressed_player_cmd(BT_HDR* p_pkt, + const tAVRC_SET_ADDR_PLAYER_CMD* cmd) { log::verbose(""); /* get the existing length, if any, and also the num attributes */ uint8_t* p_start = (uint8_t*)(p_pkt + 1) + p_pkt->offset; @@ -524,8 +515,7 @@ static tAVRC_STS avrc_bld_set_addressed_player_cmd( static BT_HDR* avrc_bld_init_cmd_buffer(tAVRC_COMMAND* p_cmd) { uint16_t chnl = AVCT_DATA_CTRL; uint8_t opcode = avrc_opcode_from_pdu(p_cmd->pdu); - log::verbose("avrc_bld_init_cmd_buffer: pdu={:x}, opcode={:x}", p_cmd->pdu, - opcode); + log::verbose("avrc_bld_init_cmd_buffer: pdu={:x}, opcode={:x}", p_cmd->pdu, opcode); uint16_t offset = 0; switch (opcode) { @@ -554,14 +544,16 @@ static BT_HDR* avrc_bld_init_cmd_buffer(tAVRC_COMMAND* p_cmd) { p_start = p_data; /* pass thru - group navigation - has a two byte op_id, so dont do it here */ - if (opcode != AVRC_OP_PASS_THRU) *p_data++ = p_cmd->pdu; + if (opcode != AVRC_OP_PASS_THRU) { + *p_data++ = p_cmd->pdu; + } switch (opcode) { case AVRC_OP_VENDOR: /* reserved 0, packet_type 0 */ UINT8_TO_BE_STREAM(p_data, 0); /* continue to the next "case to add length */ - /* add fixed lenth - 0 */ + /* add fixed length - 0 */ UINT16_TO_BE_STREAM(p_data, 0); break; } @@ -586,12 +578,10 @@ static BT_HDR* avrc_bld_init_cmd_buffer(tAVRC_COMMAND* p_cmd) { tAVRC_STS AVRC_BldCommand(tAVRC_COMMAND* p_cmd, BT_HDR** pp_pkt) { tAVRC_STS status = AVRC_STS_BAD_PARAM; bool alloc = false; - log::verbose("AVRC_BldCommand: pdu={:x} status={:x}", p_cmd->cmd.pdu, - p_cmd->cmd.status); + log::verbose("AVRC_BldCommand: pdu={:x} status={:x}", p_cmd->cmd.pdu, p_cmd->cmd.status); if (!p_cmd || !pp_pkt) { - log::verbose( - "AVRC_BldCommand. Invalid parameters passed. p_cmd={}, pp_pkt={}", - fmt::ptr(p_cmd), fmt::ptr(pp_pkt)); + log::verbose("AVRC_BldCommand. Invalid parameters passed. p_cmd={}, pp_pkt={}", fmt::ptr(p_cmd), + fmt::ptr(pp_pkt)); return AVRC_STS_BAD_PARAM; } @@ -624,43 +614,37 @@ tAVRC_STS AVRC_BldCommand(tAVRC_COMMAND* p_cmd, BT_HDR** pp_pkt) { if (!avrcp_absolute_volume_is_enabled()) { break; } - status = avrc_bld_register_notifn(p_pkt, p_cmd->reg_notif.event_id, - p_cmd->reg_notif.param); + status = avrc_bld_register_notifn(p_pkt, p_cmd->reg_notif.event_id, p_cmd->reg_notif.param); break; case AVRC_PDU_GET_CAPABILITIES: - status = - avrc_bld_get_capability_cmd(p_pkt, p_cmd->get_caps.capability_id); + status = avrc_bld_get_capability_cmd(p_pkt, p_cmd->get_caps.capability_id); break; case AVRC_PDU_LIST_PLAYER_APP_ATTR: status = avrc_bld_list_player_app_attr_cmd(p_pkt); break; case AVRC_PDU_LIST_PLAYER_APP_VALUES: - status = avrc_bld_list_player_app_values_cmd( - p_pkt, p_cmd->list_app_values.attr_id); + status = avrc_bld_list_player_app_values_cmd(p_pkt, p_cmd->list_app_values.attr_id); break; case AVRC_PDU_GET_CUR_PLAYER_APP_VALUE: - status = avrc_bld_get_current_player_app_values_cmd( - p_pkt, p_cmd->get_cur_app_val.num_attr, p_cmd->get_cur_app_val.attrs); + status = avrc_bld_get_current_player_app_values_cmd(p_pkt, p_cmd->get_cur_app_val.num_attr, + p_cmd->get_cur_app_val.attrs); break; case AVRC_PDU_SET_PLAYER_APP_VALUE: - status = avrc_bld_set_current_player_app_values_cmd( - p_pkt, p_cmd->set_app_val.num_val, p_cmd->set_app_val.p_vals); + status = avrc_bld_set_current_player_app_values_cmd(p_pkt, p_cmd->set_app_val.num_val, + p_cmd->set_app_val.p_vals); break; case AVRC_PDU_GET_PLAYER_APP_ATTR_TEXT: - avrc_bld_get_player_app_setting_attr_text_cmd(p_pkt, - &p_cmd->get_app_attr_txt); + avrc_bld_get_player_app_setting_attr_text_cmd(p_pkt, &p_cmd->get_app_attr_txt); break; case AVRC_PDU_GET_PLAYER_APP_VALUE_TEXT: - avrc_bld_get_player_app_setting_value_text_cmd(p_pkt, - &p_cmd->get_app_val_txt); + avrc_bld_get_player_app_setting_value_text_cmd(p_pkt, &p_cmd->get_app_val_txt); break; case AVRC_PDU_GET_ELEMENT_ATTR: - status = avrc_bld_get_element_attr_cmd( - p_pkt, p_cmd->get_elem_attrs.num_attr, p_cmd->get_elem_attrs.attrs); + status = avrc_bld_get_element_attr_cmd(p_pkt, p_cmd->get_elem_attrs.num_attr, + p_cmd->get_elem_attrs.attrs); break; case AVRC_PDU_PLAY_ITEM: - status = avrc_bld_play_item_cmd(p_pkt, p_cmd->play_item.scope, - p_cmd->play_item.uid, + status = avrc_bld_play_item_cmd(p_pkt, p_cmd->play_item.scope, p_cmd->play_item.uid, p_cmd->play_item.uid_counter); break; case AVRC_PDU_GET_PLAY_STATUS: diff --git a/system/stack/avrc/avrc_bld_tg.cc b/system/stack/avrc/avrc_bld_tg.cc index af754bcd74d..e6ca39167e5 100644 --- a/system/stack/avrc/avrc_bld_tg.cc +++ b/system/stack/avrc/avrc_bld_tg.cc @@ -36,11 +36,10 @@ using namespace bluetooth; /***************************************************************************** * Global data ****************************************************************************/ -#define AVRC_ITEM_PLAYER_IS_VALID(_p_player) \ - ((_p_player)->name.p_str && \ - ((_p_player)->major_type & AVRC_MJ_TYPE_INVALID) == 0 && \ - ((_p_player)->sub_type & AVRC_SUB_TYPE_INVALID) == 0 && \ - (((_p_player)->play_status <= AVRC_PLAYSTATE_REV_SEEK) || \ +#define AVRC_ITEM_PLAYER_IS_VALID(_p_player) \ + ((_p_player)->name.p_str && ((_p_player)->major_type & AVRC_MJ_TYPE_INVALID) == 0 && \ + ((_p_player)->sub_type & AVRC_SUB_TYPE_INVALID) == 0 && \ + (((_p_player)->play_status <= AVRC_PLAYSTATE_REV_SEEK) || \ ((_p_player)->play_status == AVRC_PLAYSTATE_ERROR))) /* 17 = item_type(1) + item len(2) + min item (14) */ @@ -56,8 +55,7 @@ using namespace bluetooth; * Otherwise, the error code. * ******************************************************************************/ -static tAVRC_STS avrc_bld_get_capability_rsp(tAVRC_GET_CAPS_RSP* p_rsp, - BT_HDR* p_pkt) { +static tAVRC_STS avrc_bld_get_capability_rsp(tAVRC_GET_CAPS_RSP* p_rsp, BT_HDR* p_pkt) { uint8_t *p_data, *p_start, *p_len, *p_count; uint16_t len = 0; uint8_t xx; @@ -124,8 +122,8 @@ static tAVRC_STS avrc_bld_get_capability_rsp(tAVRC_GET_CAPS_RSP* p_rsp, * Otherwise, the error code. * ******************************************************************************/ -static tAVRC_STS avrc_bld_list_app_settings_attr_rsp( - tAVRC_LIST_APP_ATTR_RSP* p_rsp, BT_HDR* p_pkt) { +static tAVRC_STS avrc_bld_list_app_settings_attr_rsp(tAVRC_LIST_APP_ATTR_RSP* p_rsp, + BT_HDR* p_pkt) { uint8_t *p_data, *p_start, *p_len, *p_num; uint16_t len = 0; uint8_t xx; @@ -170,8 +168,8 @@ static tAVRC_STS avrc_bld_list_app_settings_attr_rsp( * Otherwise, the error code. * ******************************************************************************/ -static tAVRC_STS avrc_bld_list_app_settings_values_rsp( - tAVRC_LIST_APP_VALUES_RSP* p_rsp, BT_HDR* p_pkt) { +static tAVRC_STS avrc_bld_list_app_settings_values_rsp(tAVRC_LIST_APP_VALUES_RSP* p_rsp, + BT_HDR* p_pkt) { uint8_t *p_data, *p_start, *p_len, *p_num; uint8_t xx; uint16_t len; @@ -214,8 +212,8 @@ static tAVRC_STS avrc_bld_list_app_settings_values_rsp( * Otherwise, the error code. * ******************************************************************************/ -static tAVRC_STS avrc_bld_get_cur_app_setting_value_rsp( - tAVRC_GET_CUR_APP_VALUE_RSP* p_rsp, BT_HDR* p_pkt) { +static tAVRC_STS avrc_bld_get_cur_app_setting_value_rsp(tAVRC_GET_CUR_APP_VALUE_RSP* p_rsp, + BT_HDR* p_pkt) { uint8_t *p_data, *p_start, *p_len, *p_count; uint16_t len; uint8_t xx; @@ -241,8 +239,7 @@ static tAVRC_STS avrc_bld_get_cur_app_setting_value_rsp( } for (xx = 0; xx < p_rsp->num_val; xx++) { - if (avrc_is_valid_player_attrib_value(p_rsp->p_vals[xx].attr_id, - p_rsp->p_vals[xx].attr_val)) { + if (avrc_is_valid_player_attrib_value(p_rsp->p_vals[xx].attr_id, p_rsp->p_vals[xx].attr_val)) { (*p_count)++; UINT8_TO_BE_STREAM(p_data, p_rsp->p_vals[xx].attr_id); UINT8_TO_BE_STREAM(p_data, p_rsp->p_vals[xx].attr_val); @@ -266,8 +263,7 @@ static tAVRC_STS avrc_bld_get_cur_app_setting_value_rsp( * Otherwise, the error code. * ******************************************************************************/ -static tAVRC_STS avrc_bld_set_app_setting_value_rsp(tAVRC_RSP* /* p_rsp */, - BT_HDR* /* p_pkt */) { +static tAVRC_STS avrc_bld_set_app_setting_value_rsp(tAVRC_RSP* /* p_rsp */, BT_HDR* /* p_pkt */) { /* nothing to be added. */ log::verbose(""); return AVRC_STS_NO_ERROR; @@ -284,8 +280,7 @@ static tAVRC_STS avrc_bld_set_app_setting_value_rsp(tAVRC_RSP* /* p_rsp */, * Otherwise, the error code. * ******************************************************************************/ -static tAVRC_STS avrc_bld_app_setting_text_rsp( - tAVRC_GET_APP_ATTR_TXT_RSP* p_rsp, BT_HDR* p_pkt) { +static tAVRC_STS avrc_bld_app_setting_text_rsp(tAVRC_GET_APP_ATTR_TXT_RSP* p_rsp, BT_HDR* p_pkt) { uint8_t *p_data, *p_start, *p_len, *p_count; uint16_t len, len_left; uint8_t xx; @@ -318,8 +313,7 @@ static tAVRC_STS avrc_bld_app_setting_text_rsp( for (xx = 0; xx < p_rsp->num_attr; xx++) { if (len_left < (p_rsp->p_attrs[xx].str_len + 4)) { - log::error("out of room (str_len:{}, left:{})", - p_rsp->p_attrs[xx].str_len, len_left); + log::error("out of room (str_len:{}, left:{})", p_rsp->p_attrs[xx].str_len, len_left); p_rsp->num_attr = num_added; sts = AVRC_STS_INTERNAL_ERR; break; @@ -331,8 +325,7 @@ static tAVRC_STS avrc_bld_app_setting_text_rsp( UINT8_TO_BE_STREAM(p_data, p_rsp->p_attrs[xx].attr_id); UINT16_TO_BE_STREAM(p_data, p_rsp->p_attrs[xx].charset_id); UINT8_TO_BE_STREAM(p_data, p_rsp->p_attrs[xx].str_len); - ARRAY_TO_BE_STREAM(p_data, p_rsp->p_attrs[xx].p_str, - p_rsp->p_attrs[xx].str_len); + ARRAY_TO_BE_STREAM(p_data, p_rsp->p_attrs[xx].p_str, p_rsp->p_attrs[xx].str_len); (*p_count)++; num_added++; } @@ -354,8 +347,8 @@ static tAVRC_STS avrc_bld_app_setting_text_rsp( * Otherwise, the error code. * ******************************************************************************/ -static tAVRC_STS avrc_bld_get_app_setting_attr_text_rsp( - tAVRC_GET_APP_ATTR_TXT_RSP* p_rsp, BT_HDR* p_pkt) { +static tAVRC_STS avrc_bld_get_app_setting_attr_text_rsp(tAVRC_GET_APP_ATTR_TXT_RSP* p_rsp, + BT_HDR* p_pkt) { log::verbose(""); return avrc_bld_app_setting_text_rsp(p_rsp, p_pkt); } @@ -371,8 +364,8 @@ static tAVRC_STS avrc_bld_get_app_setting_attr_text_rsp( * Otherwise, the error code. * ******************************************************************************/ -static tAVRC_STS avrc_bld_get_app_setting_value_text_rsp( - tAVRC_GET_APP_ATTR_TXT_RSP* p_rsp, BT_HDR* p_pkt) { +static tAVRC_STS avrc_bld_get_app_setting_value_text_rsp(tAVRC_GET_APP_ATTR_TXT_RSP* p_rsp, + BT_HDR* p_pkt) { log::verbose(""); return avrc_bld_app_setting_text_rsp(p_rsp, p_pkt); } @@ -388,8 +381,7 @@ static tAVRC_STS avrc_bld_get_app_setting_value_text_rsp( * Otherwise, the error code. * ******************************************************************************/ -static tAVRC_STS avrc_bld_inform_charset_rsp(tAVRC_RSP* /* p_rsp */, - BT_HDR* /* p_pkt */) { +static tAVRC_STS avrc_bld_inform_charset_rsp(tAVRC_RSP* /* p_rsp */, BT_HDR* /* p_pkt */) { /* nothing to be added. */ log::verbose(""); return AVRC_STS_NO_ERROR; @@ -406,17 +398,14 @@ static tAVRC_STS avrc_bld_inform_charset_rsp(tAVRC_RSP* /* p_rsp */, * Otherwise, the error code. * ******************************************************************************/ -static tAVRC_STS avrc_bld_inform_battery_status_rsp(tAVRC_RSP* /* p_rsp */, - BT_HDR* /* p_pkt */) { +static tAVRC_STS avrc_bld_inform_battery_status_rsp(tAVRC_RSP* /* p_rsp */, BT_HDR* /* p_pkt */) { /* nothing to be added. */ log::verbose(""); return AVRC_STS_NO_ERROR; } -static void avrc_build_attribute_entries(int num_attrs, - tAVRC_ATTR_ENTRY* p_attrs, - int remaining_buffer_capacity, - uint8_t** pp_data, +static void avrc_build_attribute_entries(int num_attrs, tAVRC_ATTR_ENTRY* p_attrs, + int remaining_buffer_capacity, uint8_t** pp_data, uint8_t* p_attribute_count) { log::verbose("num_attrs: {}, remaining_buffer_capacity: {}", num_attrs, remaining_buffer_capacity); @@ -424,24 +413,21 @@ static void avrc_build_attribute_entries(int num_attrs, /* Fill in the Attribute ID, Character Set, Length and Values */ for (int index = 0; index < num_attrs; index++) { log::verbose("attr id[{}]: {}", index, p_attrs[index].attr_id); - log::assert_that( - AVRC_IS_VALID_MEDIA_ATTRIBUTE(p_attrs[index].attr_id), - "assert failed: AVRC_IS_VALID_MEDIA_ATTRIBUTE(p_attrs[index].attr_id)"); + log::assert_that(AVRC_IS_VALID_MEDIA_ATTRIBUTE(p_attrs[index].attr_id), + "assert failed: AVRC_IS_VALID_MEDIA_ATTRIBUTE(p_attrs[index].attr_id)"); if (!p_attrs[index].name.p_str) { p_attrs[index].name.str_len = 0; } /* 8 is the size of attr_id, char set and str_len */ remaining_buffer_capacity -= 8; if (remaining_buffer_capacity < 0) { - log::warn( - "not enough buffer space for attr_id[{}]: {}, skipping {} attributes", - index, p_attrs[index].attr_id, num_attrs - index); + log::warn("not enough buffer space for attr_id[{}]: {}, skipping {} attributes", index, + p_attrs[index].attr_id, num_attrs - index); break; } if (remaining_buffer_capacity < p_attrs[index].name.str_len) { - log::warn( - "not enough buffer space for attr_id[{}]: {}, truncating attribute", - index, p_attrs[index].attr_id); + log::warn("not enough buffer space for attr_id[{}]: {}, truncating attribute", index, + p_attrs[index].attr_id); p_attrs[index].name.str_len = remaining_buffer_capacity; remaining_buffer_capacity = 0; } @@ -449,13 +435,11 @@ static void avrc_build_attribute_entries(int num_attrs, UINT32_TO_BE_STREAM(p_data, p_attrs[index].attr_id); UINT16_TO_BE_STREAM(p_data, p_attrs[index].name.charset_id); UINT16_TO_BE_STREAM(p_data, p_attrs[index].name.str_len); - ARRAY_TO_BE_STREAM(p_data, p_attrs[index].name.p_str, - p_attrs[index].name.str_len); + ARRAY_TO_BE_STREAM(p_data, p_attrs[index].name.p_str, p_attrs[index].name.str_len); (*p_attribute_count)++; } *pp_data = p_data; - log::verbose("filled attributes, remaining_buffer_capacity: {}", - remaining_buffer_capacity); + log::verbose("filled attributes, remaining_buffer_capacity: {}", remaining_buffer_capacity); } /******************************************************************************* @@ -469,19 +453,16 @@ static void avrc_build_attribute_entries(int num_attrs, * Otherwise, the error code. * ******************************************************************************/ -static tAVRC_STS avrc_bld_get_elem_attrs_rsp(tAVRC_GET_ATTRS_RSP* p_rsp, - BT_HDR* p_pkt) { +static tAVRC_STS avrc_bld_get_elem_attrs_rsp(tAVRC_GET_ATTRS_RSP* p_rsp, BT_HDR* p_pkt) { log::verbose(""); if (!p_rsp->p_attrs) { log::error("NULL p_attrs"); return AVRC_STS_BAD_PARAM; } /* Figure out how much we have left in current buffer */ - int remaining_buffer_capacity = - BT_DEFAULT_BUFFER_SIZE - BT_HDR_SIZE - p_pkt->offset; + int remaining_buffer_capacity = BT_DEFAULT_BUFFER_SIZE - BT_HDR_SIZE - p_pkt->offset; if (remaining_buffer_capacity < 5) { - log::error("{} not enough buffer for packet header", - remaining_buffer_capacity); + log::error("{} not enough buffer for packet header", remaining_buffer_capacity); return AVRC_STS_INTERNAL_ERR; } /* Get to the beginning of PDU */ @@ -509,8 +490,7 @@ static tAVRC_STS avrc_bld_get_elem_attrs_rsp(tAVRC_GET_ATTRS_RSP* p_rsp, return AVRC_STS_BAD_PARAM; } /* Fill in the Attribute ID, Character Set, Length and Values */ - avrc_build_attribute_entries(p_rsp->num_attrs, p_rsp->p_attrs, - remaining_buffer_capacity, &p_data, + avrc_build_attribute_entries(p_rsp->num_attrs, p_rsp->p_attrs, remaining_buffer_capacity, &p_data, p_attribute_count); parameter_len = p_data - p_attribute_count; UINT16_TO_BE_STREAM(p_parameter_len, parameter_len); @@ -529,15 +509,14 @@ static tAVRC_STS avrc_bld_get_elem_attrs_rsp(tAVRC_GET_ATTRS_RSP* p_rsp, * Otherwise, the error code. * ******************************************************************************/ -static tAVRC_STS avrc_bld_get_play_status_rsp(tAVRC_GET_PLAY_STATUS_RSP* p_rsp, - BT_HDR* p_pkt) { +static tAVRC_STS avrc_bld_get_play_status_rsp(tAVRC_GET_PLAY_STATUS_RSP* p_rsp, BT_HDR* p_pkt) { uint8_t *p_data, *p_start; log::verbose(""); p_start = (uint8_t*)(p_pkt + 1) + p_pkt->offset; p_data = p_start + 2; - /* add fixed lenth - song len(4) + song position(4) + status(1) */ + /* add fixed length - song len(4) + song position(4) + status(1) */ UINT16_TO_BE_STREAM(p_data, 9); UINT32_TO_BE_STREAM(p_data, p_rsp->song_len); UINT32_TO_BE_STREAM(p_data, p_rsp->song_pos); @@ -557,8 +536,7 @@ static tAVRC_STS avrc_bld_get_play_status_rsp(tAVRC_GET_PLAY_STATUS_RSP* p_rsp, * Otherwise, the error code. * ******************************************************************************/ -static tAVRC_STS avrc_bld_notify_rsp(tAVRC_REG_NOTIF_RSP* p_rsp, - BT_HDR* p_pkt) { +static tAVRC_STS avrc_bld_notify_rsp(tAVRC_REG_NOTIF_RSP* p_rsp, BT_HDR* p_pkt) { uint8_t *p_data, *p_start; uint8_t* p_len; uint16_t len = 0; @@ -623,19 +601,18 @@ static tAVRC_STS avrc_bld_notify_rsp(tAVRC_REG_NOTIF_RSP* p_rsp, break; case AVRC_EVT_APP_SETTING_CHANGE: /* 0x08 */ - if (p_rsp->param.player_setting.num_attr > AVRC_MAX_APP_SETTINGS) + if (p_rsp->param.player_setting.num_attr > AVRC_MAX_APP_SETTINGS) { p_rsp->param.player_setting.num_attr = AVRC_MAX_APP_SETTINGS; + } if (p_rsp->param.player_setting.num_attr > 0) { UINT8_TO_BE_STREAM(p_data, p_rsp->param.player_setting.num_attr); len = 2; for (xx = 0; xx < p_rsp->param.player_setting.num_attr; xx++) { - if (avrc_is_valid_player_attrib_value( - p_rsp->param.player_setting.attr_id[xx], - p_rsp->param.player_setting.attr_value[xx])) { + if (avrc_is_valid_player_attrib_value(p_rsp->param.player_setting.attr_id[xx], + p_rsp->param.player_setting.attr_value[xx])) { UINT8_TO_BE_STREAM(p_data, p_rsp->param.player_setting.attr_id[xx]); - UINT8_TO_BE_STREAM(p_data, - p_rsp->param.player_setting.attr_value[xx]); + UINT8_TO_BE_STREAM(p_data, p_rsp->param.player_setting.attr_value[xx]); } else { log::error("bad player app seeting attribute or value"); status = AVRC_STS_BAD_PARAM; @@ -643,8 +620,9 @@ static tAVRC_STS avrc_bld_notify_rsp(tAVRC_REG_NOTIF_RSP* p_rsp, } len += 2; } - } else + } else { status = AVRC_STS_BAD_PARAM; + } break; case AVRC_EVT_VOLUME_CHANGE: /* 0x0d */ @@ -705,13 +683,12 @@ static tAVRC_STS avrc_bld_next_rsp(tAVRC_NEXT_RSP* p_rsp, BT_HDR* p_pkt) { * Returns AVRC_STS_NO_ERROR, if the response is build successfully * *****************************************************************************/ -static tAVRC_STS avrc_bld_set_absolute_volume_rsp(uint8_t abs_vol, - BT_HDR* p_pkt) { +static tAVRC_STS avrc_bld_set_absolute_volume_rsp(uint8_t abs_vol, BT_HDR* p_pkt) { log::verbose(""); uint8_t* p_start = (uint8_t*)(p_pkt + 1) + p_pkt->offset; /* To calculate length */ uint8_t* p_data = p_start + 2; - /* add fixed lenth status(1) */ + /* add fixed length status(1) */ UINT16_TO_BE_STREAM(p_data, 1); UINT8_TO_BE_STREAM(p_data, abs_vol); p_pkt->len = (p_data - p_start); @@ -755,13 +732,11 @@ static tAVRC_STS avrc_bld_rejected_rsp(tAVRC_RSP* p_rsp, BT_HDR* p_pkt) { uint8_t* p_data; uint8_t opcode = p_rsp->opcode; - log::verbose("status={}, pdu:x{:x}, opcode={:x}", p_rsp->status, p_rsp->pdu, - opcode); + log::verbose("status={}, pdu:x{:x}, opcode={:x}", p_rsp->status, p_rsp->pdu, opcode); if (opcode == AVRC_OP_BROWSE) { p_data = p_start + 1; - if ((AVRC_PDU_INVALID == *p_start) || - (avrc_opcode_from_pdu(*p_start) != AVRC_OP_BROWSE)) { + if ((AVRC_PDU_INVALID == *p_start) || (avrc_opcode_from_pdu(*p_start) != AVRC_OP_BROWSE)) { /* if invalid or the given opcode is not recognized as a browsing command * opcode, */ /* use general reject command */ @@ -798,7 +773,7 @@ static tAVRC_STS avrc_bld_ctrl_status_rsp(tAVRC_RSP* p_rsp, BT_HDR* p_pkt) { /* To calculate length */ uint8_t* p_data = p_start + 2; /* pdu + rsvd */ - /* add fixed lenth - status(1) */ + /* add fixed length - status(1) */ UINT16_TO_BE_STREAM(p_data, 1); UINT8_TO_BE_STREAM(p_data, p_rsp->status); p_pkt->len = (p_data - p_start); @@ -832,8 +807,7 @@ static tAVRC_STS avrc_bld_set_addr_player_rsp(tAVRC_RSP* p_rsp, BT_HDR* p_pkt) { * Otherwise, the error code. * ******************************************************************************/ -static tAVRC_STS avrc_bld_set_browsed_player_rsp(tAVRC_SET_BR_PLAYER_RSP* p_rsp, - BT_HDR* p_pkt) { +static tAVRC_STS avrc_bld_set_browsed_player_rsp(tAVRC_SET_BR_PLAYER_RSP* p_rsp, BT_HDR* p_pkt) { uint8_t *p_data, *p_start; uint8_t* p_len; uint16_t len; @@ -877,8 +851,7 @@ static tAVRC_STS avrc_bld_set_browsed_player_rsp(tAVRC_SET_BR_PLAYER_RSP* p_rsp, p_data = p_start + p_pkt->len; } - for (uint8_t xx = 0; - (xx < p_rsp->folder_depth) && (len_left > (p_folders[xx].str_len + 2)); + for (uint8_t xx = 0; (xx < p_rsp->folder_depth) && (len_left > (p_folders[xx].str_len + 2)); xx++) { (*p_folder_depth)++; UINT16_TO_BE_STREAM(p_data, p_folders[xx].str_len); @@ -907,8 +880,7 @@ static tAVRC_STS avrc_bld_set_browsed_player_rsp(tAVRC_SET_BR_PLAYER_RSP* p_rsp, * Otherwise, the error code. * ******************************************************************************/ -static tAVRC_STS avrc_bld_get_folder_items_rsp(tAVRC_GET_ITEMS_RSP* p_rsp, - BT_HDR* p_pkt) { +static tAVRC_STS avrc_bld_get_folder_items_rsp(tAVRC_GET_ITEMS_RSP* p_rsp, BT_HDR* p_pkt) { uint8_t *p_data, *p_start; uint8_t *p_len, xx; uint16_t len; @@ -932,12 +904,14 @@ static tAVRC_STS avrc_bld_get_folder_items_rsp(tAVRC_GET_ITEMS_RSP* p_rsp, len_left = BT_DEFAULT_BUFFER_SIZE - BT_HDR_SIZE; p = (uint8_t*)(p_pkt + 1); BE_STREAM_TO_UINT16(mtu, p); - if (len_left > mtu) len_left = mtu; + if (len_left > mtu) { + len_left = mtu; + } // according to spec // Version 5.3 | Vol 3, Part A, Chapter 5 // MTU may be controlled by the peer - if (len_left < p_pkt->offset + p_pkt->len) { + if (len_left < p_pkt->offset + p_pkt->len) { log::error("memory not enough (len_left={})", len_left); return AVRC_STS_INTERNAL_ERR; } @@ -973,13 +947,12 @@ static tAVRC_STS avrc_bld_get_folder_items_rsp(tAVRC_GET_ITEMS_RSP* p_rsp, log::verbose("len:{}, len_left:{}, num:{}", len, len_left, item_count); /* min len required = item_type(1) + item len(2) + min item (14) = 17 */ - for (xx = 0; - xx < p_rsp->item_count && len_left > AVRC_MIN_LEN_GET_FOLDER_ITEMS_RSP && - !multi_items_add_fail; + for (xx = 0; xx < p_rsp->item_count && len_left > AVRC_MIN_LEN_GET_FOLDER_ITEMS_RSP && + !multi_items_add_fail; xx++) { p_item_start = p_data; UINT8_TO_BE_STREAM(p_data, p_item_list[xx].item_type); - /* variable item lenth - save the location to add length */ + /* variable item length - save the location to add length */ p_item_len = p_data; p_data += 2; item_len = 0; @@ -991,8 +964,7 @@ static tAVRC_STS avrc_bld_get_folder_items_rsp(tAVRC_GET_ITEMS_RSP* p_rsp, p_player = &p_item_list[xx].u.player; item_len = AVRC_FEATURE_MASK_SIZE + p_player->name.str_len + 12; - if ((item_len_left < item_len) || - !AVRC_ITEM_PLAYER_IS_VALID(p_player)) { + if ((item_len_left < item_len) || !AVRC_ITEM_PLAYER_IS_VALID(p_player)) { if (item_len_left < item_len && item_count > 0) { multi_items_add_fail = true; } @@ -1006,8 +978,7 @@ static tAVRC_STS avrc_bld_get_folder_items_rsp(tAVRC_GET_ITEMS_RSP* p_rsp, ARRAY_TO_BE_STREAM(p_data, p_player->features, AVRC_FEATURE_MASK_SIZE); UINT16_TO_BE_STREAM(p_data, p_player->name.charset_id); UINT16_TO_BE_STREAM(p_data, p_player->name.str_len); - ARRAY_TO_BE_STREAM(p_data, p_player->name.p_str, - p_player->name.str_len); + ARRAY_TO_BE_STREAM(p_data, p_player->name.p_str, p_player->name.str_len); break; case AVRC_ITEM_FOLDER: @@ -1028,8 +999,7 @@ static tAVRC_STS avrc_bld_get_folder_items_rsp(tAVRC_GET_ITEMS_RSP* p_rsp, UINT8_TO_BE_STREAM(p_data, p_folder->playable); UINT16_TO_BE_STREAM(p_data, p_folder->name.charset_id); UINT16_TO_BE_STREAM(p_data, p_folder->name.str_len); - ARRAY_TO_BE_STREAM(p_data, p_folder->name.p_str, - p_folder->name.str_len); + ARRAY_TO_BE_STREAM(p_data, p_folder->name.p_str, p_folder->name.str_len); break; case AVRC_ITEM_MEDIA: @@ -1070,8 +1040,7 @@ static tAVRC_STS avrc_bld_get_folder_items_rsp(tAVRC_GET_ITEMS_RSP* p_rsp, UINT32_TO_BE_STREAM(p_data, p_attr[yy].attr_id); UINT16_TO_BE_STREAM(p_data, p_attr[yy].name.charset_id); UINT16_TO_BE_STREAM(p_data, p_attr[yy].name.str_len); - ARRAY_TO_BE_STREAM(p_data, p_attr[yy].name.p_str, - p_attr[yy].name.str_len); + ARRAY_TO_BE_STREAM(p_data, p_attr[yy].name.p_str, p_attr[yy].name.str_len); item_len += attribute_len; attribute_len_left -= attribute_len; } @@ -1081,20 +1050,20 @@ static tAVRC_STS avrc_bld_get_folder_items_rsp(tAVRC_GET_ITEMS_RSP* p_rsp, if (p_item_start != p_data) { /* successfully added the item */ item_count++; - /* fill in variable item lenth */ + /* fill in variable item length */ UINT16_TO_BE_STREAM(p_item_len, item_len); len_left -= item_len + item_header_len; len += item_len + item_header_len; } else if (!multi_items_add_fail) { /* some item is not added properly - set an error status */ - if (item_len_left < item_len) + if (item_len_left < item_len) { status = AVRC_STS_INTERNAL_ERR; - else + } else { status = AVRC_STS_BAD_PARAM; + } break; } - log::verbose("len:{}, len_left:{}, num:{}, item_len:{}", len, len_left, - item_count, item_len); + log::verbose("len:{}, len_left:{}, num:{}, item_len:{}", len, len_left, item_count, item_len); } /* for item_count */ UINT16_TO_BE_STREAM(p_num, item_count); @@ -1116,8 +1085,7 @@ static tAVRC_STS avrc_bld_get_folder_items_rsp(tAVRC_GET_ITEMS_RSP* p_rsp, * Otherwise, the error code. * ******************************************************************************/ -static tAVRC_STS avrc_bld_change_path_rsp(tAVRC_CHG_PATH_RSP* p_rsp, - BT_HDR* p_pkt) { +static tAVRC_STS avrc_bld_change_path_rsp(tAVRC_CHG_PATH_RSP* p_rsp, BT_HDR* p_pkt) { uint8_t *p_data, *p_start; /* get the existing length, if any, and also the num attributes */ @@ -1146,16 +1114,14 @@ static tAVRC_STS avrc_bld_change_path_rsp(tAVRC_CHG_PATH_RSP* p_rsp, * Otherwise, the error code. * ******************************************************************************/ -static tAVRC_STS avrc_bld_get_item_attrs_rsp(tAVRC_GET_ATTRS_RSP* p_rsp, - BT_HDR* p_pkt) { +static tAVRC_STS avrc_bld_get_item_attrs_rsp(tAVRC_GET_ATTRS_RSP* p_rsp, BT_HDR* p_pkt) { log::verbose(""); if (!p_rsp->p_attrs) { log::error("NULL p_attrs"); return AVRC_STS_BAD_PARAM; } /* Figure out how much we have left in current buffer */ - int remaining_buffer_capacity = - BT_DEFAULT_BUFFER_SIZE - BT_HDR_SIZE - p_pkt->offset; + int remaining_buffer_capacity = BT_DEFAULT_BUFFER_SIZE - BT_HDR_SIZE - p_pkt->offset; /* Get to the beginning of data section in buffer */ uint8_t* p_data = (uint8_t*)(p_pkt + 1); /* Get the MTU size that is filled in earlier */ @@ -1164,11 +1130,9 @@ static tAVRC_STS avrc_bld_get_item_attrs_rsp(tAVRC_GET_ATTRS_RSP* p_rsp, if (remaining_buffer_capacity > mtu) { remaining_buffer_capacity = mtu; } - log::verbose("remaining_buffer_capacity:{}, mtu:{}", - remaining_buffer_capacity, mtu); + log::verbose("remaining_buffer_capacity:{}, mtu:{}", remaining_buffer_capacity, mtu); if (remaining_buffer_capacity < 5) { - log::error("not enough space for packet header, remaining:{} < 5", - remaining_buffer_capacity); + log::error("not enough space for packet header, remaining:{} < 5", remaining_buffer_capacity); return AVRC_STS_INTERNAL_ERR; } /* Get to the beginning of PDU */ @@ -1199,8 +1163,7 @@ static tAVRC_STS avrc_bld_get_item_attrs_rsp(tAVRC_GET_ATTRS_RSP* p_rsp, } remaining_buffer_capacity -= p_data - p_pdu_start; /* Fill in the Attribute ID, Character Set, Length and Values */ - avrc_build_attribute_entries(p_rsp->num_attrs, p_rsp->p_attrs, - remaining_buffer_capacity, &p_data, + avrc_build_attribute_entries(p_rsp->num_attrs, p_rsp->p_attrs, remaining_buffer_capacity, &p_data, p_attribute_count); parameter_len = p_data - p_status; UINT16_TO_BE_STREAM(p_parameter_len, parameter_len); @@ -1222,8 +1185,7 @@ static tAVRC_STS avrc_bld_get_item_attrs_rsp(tAVRC_GET_ATTRS_RSP* p_rsp, * Otherwise, the error code. * ******************************************************************************/ -static tAVRC_STS avrc_bld_get_num_of_item_rsp(tAVRC_GET_NUM_OF_ITEMS_RSP* p_rsp, - BT_HDR* p_pkt) { +static tAVRC_STS avrc_bld_get_num_of_item_rsp(tAVRC_GET_NUM_OF_ITEMS_RSP* p_rsp, BT_HDR* p_pkt) { uint8_t *p_data, *p_start, *p_len; log::verbose(""); @@ -1232,7 +1194,7 @@ static tAVRC_STS avrc_bld_get_num_of_item_rsp(tAVRC_GET_NUM_OF_ITEMS_RSP* p_rsp, p_data = p_len = p_start + 1; /* pdu */ if (p_rsp->status == AVRC_STS_NO_ERROR) { - /* add fixed lenth - status(1) + uid_counter(2) + num_items(4) */ + /* add fixed length - status(1) + uid_counter(2) + num_items(4) */ UINT16_TO_BE_STREAM(p_data, 7); UINT8_TO_BE_STREAM(p_data, p_rsp->status); UINT16_TO_BE_STREAM(p_data, p_rsp->uid_counter); @@ -1240,7 +1202,7 @@ static tAVRC_STS avrc_bld_get_num_of_item_rsp(tAVRC_GET_NUM_OF_ITEMS_RSP* p_rsp, p_pkt->len = (p_data - p_start); return AVRC_STS_NO_ERROR; } else { - /* add fixed lenth - status(1) */ + /* add fixed length - status(1) */ UINT16_TO_BE_STREAM(p_data, 7); UINT8_TO_BE_STREAM(p_data, p_rsp->status); p_pkt->len = (p_data - p_start); @@ -1268,7 +1230,7 @@ static tAVRC_STS avrc_bld_search_rsp(tAVRC_SEARCH_RSP* p_rsp, BT_HDR* p_pkt) { p_start = (uint8_t*)(p_pkt + 1) + p_pkt->offset; p_data = p_len = p_start + 1; /* pdu */ - /* add fixed lenth - status(1) + uid_counter(2) + num_items(4) */ + /* add fixed length - status(1) + uid_counter(2) + num_items(4) */ UINT16_TO_BE_STREAM(p_data, 7); UINT8_TO_BE_STREAM(p_data, p_rsp->status); UINT16_TO_BE_STREAM(p_data, p_rsp->uid_counter); @@ -1302,8 +1264,7 @@ static tAVRC_STS avrc_bld_play_item_rsp(tAVRC_RSP* p_rsp, BT_HDR* p_pkt) { * Otherwise, the error code. * ******************************************************************************/ -static tAVRC_STS avrc_bld_add_to_now_playing_rsp(tAVRC_RSP* p_rsp, - BT_HDR* p_pkt) { +static tAVRC_STS avrc_bld_add_to_now_playing_rsp(tAVRC_RSP* p_rsp, BT_HDR* p_pkt) { log::verbose(""); return avrc_bld_ctrl_status_rsp(p_rsp, p_pkt); } @@ -1323,8 +1284,7 @@ static BT_HDR* avrc_bld_init_rsp_buffer(tAVRC_RESPONSE* p_rsp) { uint16_t chnl = AVCT_DATA_CTRL; uint8_t opcode = avrc_opcode_from_pdu(p_rsp->pdu); - log::verbose("pdu={:x}, opcode={:x}/{:x}", p_rsp->pdu, opcode, - p_rsp->rsp.opcode); + log::verbose("pdu={:x}, opcode={:x}/{:x}", p_rsp->pdu, opcode, p_rsp->rsp.opcode); if (opcode != p_rsp->rsp.opcode && p_rsp->rsp.status != AVRC_STS_NO_ERROR && avrc_is_valid_opcode(p_rsp->rsp.opcode)) { opcode = p_rsp->rsp.opcode; @@ -1357,7 +1317,9 @@ static BT_HDR* avrc_bld_init_rsp_buffer(tAVRC_RESPONSE* p_rsp) { p_start = p_data; /* pass thru - group navigation - has a two byte op_id, so dont do it here */ - if (opcode != AVRC_OP_PASS_THRU) *p_data++ = p_rsp->pdu; + if (opcode != AVRC_OP_PASS_THRU) { + *p_data++ = p_rsp->pdu; + } switch (opcode) { case AVRC_OP_VENDOR: @@ -1365,7 +1327,7 @@ static BT_HDR* avrc_bld_init_rsp_buffer(tAVRC_RESPONSE* p_rsp) { UINT8_TO_BE_STREAM(p_data, 0); [[fallthrough]]; case AVRC_OP_BROWSE: - /* add fixed lenth - 0 */ + /* add fixed length - 0 */ UINT16_TO_BE_STREAM(p_data, 0); break; } @@ -1387,8 +1349,7 @@ static BT_HDR* avrc_bld_init_rsp_buffer(tAVRC_RESPONSE* p_rsp) { * Otherwise, the error code. * ******************************************************************************/ -tAVRC_STS AVRC_BldResponse(uint8_t handle, tAVRC_RESPONSE* p_rsp, - BT_HDR** pp_pkt) { +tAVRC_STS AVRC_BldResponse(uint8_t handle, tAVRC_RESPONSE* p_rsp, BT_HDR** pp_pkt) { tAVRC_STS status = AVRC_STS_BAD_PARAM; BT_HDR* p_pkt; bool alloc = false; @@ -1396,8 +1357,8 @@ tAVRC_STS AVRC_BldResponse(uint8_t handle, tAVRC_RESPONSE* p_rsp, uint16_t peer_mtu; if (!p_rsp || !pp_pkt) { - log::verbose("Invalid parameters passed. p_rsp={}, pp_pkt={}", - fmt::ptr(p_rsp), fmt::ptr(pp_pkt)); + log::verbose("Invalid parameters passed. p_rsp={}, pp_pkt={}", fmt::ptr(p_rsp), + fmt::ptr(pp_pkt)); return AVRC_STS_BAD_PARAM; } @@ -1421,7 +1382,7 @@ tAVRC_STS AVRC_BldResponse(uint8_t handle, tAVRC_RESPONSE* p_rsp, log::verbose("pdu={:x} status={:x}", p_rsp->rsp.pdu, p_rsp->rsp.status); if (p_rsp->rsp.status != AVRC_STS_NO_ERROR) { - return (avrc_bld_rejected_rsp(&p_rsp->rsp, p_pkt)); + return avrc_bld_rejected_rsp(&p_rsp->rsp, p_pkt); } switch (p_rsp->pdu) { @@ -1435,18 +1396,15 @@ tAVRC_STS AVRC_BldResponse(uint8_t handle, tAVRC_RESPONSE* p_rsp, break; case AVRC_PDU_LIST_PLAYER_APP_ATTR: - status = - avrc_bld_list_app_settings_attr_rsp(&p_rsp->list_app_attr, p_pkt); + status = avrc_bld_list_app_settings_attr_rsp(&p_rsp->list_app_attr, p_pkt); break; case AVRC_PDU_LIST_PLAYER_APP_VALUES: - status = - avrc_bld_list_app_settings_values_rsp(&p_rsp->list_app_values, p_pkt); + status = avrc_bld_list_app_settings_values_rsp(&p_rsp->list_app_values, p_pkt); break; case AVRC_PDU_GET_CUR_PLAYER_APP_VALUE: - status = avrc_bld_get_cur_app_setting_value_rsp(&p_rsp->get_cur_app_val, - p_pkt); + status = avrc_bld_get_cur_app_setting_value_rsp(&p_rsp->get_cur_app_val, p_pkt); break; case AVRC_PDU_SET_PLAYER_APP_VALUE: @@ -1454,13 +1412,11 @@ tAVRC_STS AVRC_BldResponse(uint8_t handle, tAVRC_RESPONSE* p_rsp, break; case AVRC_PDU_GET_PLAYER_APP_ATTR_TEXT: - status = avrc_bld_get_app_setting_attr_text_rsp(&p_rsp->get_app_attr_txt, - p_pkt); + status = avrc_bld_get_app_setting_attr_text_rsp(&p_rsp->get_app_attr_txt, p_pkt); break; case AVRC_PDU_GET_PLAYER_APP_VALUE_TEXT: - status = avrc_bld_get_app_setting_value_text_rsp(&p_rsp->get_app_val_txt, - p_pkt); + status = avrc_bld_get_app_setting_value_text_rsp(&p_rsp->get_app_val_txt, p_pkt); break; case AVRC_PDU_INFORM_DISPLAY_CHARSET: @@ -1468,8 +1424,7 @@ tAVRC_STS AVRC_BldResponse(uint8_t handle, tAVRC_RESPONSE* p_rsp, break; case AVRC_PDU_INFORM_BATTERY_STAT_OF_CT: - status = avrc_bld_inform_battery_status_rsp(&p_rsp->inform_battery_status, - p_pkt); + status = avrc_bld_inform_battery_status_rsp(&p_rsp->inform_battery_status, p_pkt); break; case AVRC_PDU_GET_ELEMENT_ATTR: diff --git a/system/stack/avrc/avrc_int.h b/system/stack/avrc/avrc_int.h index b1b4e0a11bd..3394bb1c7df 100644 --- a/system/stack/avrc/avrc_int.h +++ b/system/stack/avrc/avrc_int.h @@ -67,9 +67,8 @@ #define AVRC_SINGLE_PARAM_SIZE 1 #define AVRC_METADATA_PKT_TYPE_MASK 0x03 -#define AVRC_PASS_THOUGH_MSG_MASK \ - 0x80 /* MSB of msg_type indicates the PAS THROUGH msg */ -#define AVRC_VENDOR_UNIQUE_MASK 0x70 /* vendor unique id */ +#define AVRC_PASS_THOUGH_MSG_MASK 0x80 /* MSB of msg_type indicates the PAS THROUGH msg */ +#define AVRC_VENDOR_UNIQUE_MASK 0x70 /* vendor unique id */ /* Company ID is 24-bit integer We can not use the macros in bt_types.h */ #define AVRC_CO_ID_TO_BE_STREAM(p, u32) \ @@ -92,15 +91,13 @@ #define AVRC_VENDOR_HDR_SIZE 6 /* ctype, subunit*, opcode, CO_ID */ #define AVRC_MSG_VENDOR_OFFSET 23 -#define AVRC_MIN_VENDOR_SIZE \ - (AVRC_MSG_VENDOR_OFFSET + BT_HDR_SIZE + AVRC_MIN_META_HDR_SIZE) +#define AVRC_MIN_VENDOR_SIZE (AVRC_MSG_VENDOR_OFFSET + BT_HDR_SIZE + AVRC_MIN_META_HDR_SIZE) #define AVRC_PASS_THRU_SIZE 8 #define AVRC_MSG_PASS_THRU_OFFSET 25 #define AVRC_MIN_PASS_THRU_SIZE (AVRC_MSG_PASS_THRU_OFFSET + BT_HDR_SIZE + 4) -#define AVRC_MIN_BROWSE_SIZE \ - (AVCT_BROWSE_OFFSET + BT_HDR_SIZE + AVRC_MIN_BROWSE_HDR_SIZE) +#define AVRC_MIN_BROWSE_SIZE (AVCT_BROWSE_OFFSET + BT_HDR_SIZE + AVRC_MIN_BROWSE_HDR_SIZE) #define AVRC_CTRL_PKT_LEN(pf, pk) \ { (pf) = (uint8_t*)((pk) + 1) + (pk)->offset + 2; } @@ -135,22 +132,19 @@ typedef struct { /* AVRC internal connection control block */ typedef struct { - fixed_queue_t* - cmd_q; /* Command queue for serializing vendor specific commands */ - uint8_t flags; /* See AVRC_CB_FLAGS_* definitions */ - alarm_t* tle; /* Command timeout timer */ + fixed_queue_t* cmd_q; /* Command queue for serializing vendor specific commands */ + uint8_t flags; /* See AVRC_CB_FLAGS_* definitions */ + alarm_t* tle; /* Command timeout timer */ } tAVRC_CONN_INT_CB; typedef struct { - tAVRC_CONN_CB - ccb[AVCT_NUM_CONN]; /* Connection control block from AVRC_Open API */ - tAVRC_CONN_INT_CB - ccb_int[AVCT_NUM_CONN]; /* Internal connection control block */ + tAVRC_CONN_CB ccb[AVCT_NUM_CONN]; /* Connection control block from AVRC_Open API */ + tAVRC_CONN_INT_CB ccb_int[AVCT_NUM_CONN]; /* Internal connection control block */ tAVRC_FRAG_CB fcb[AVCT_NUM_CONN]; tAVRC_RASM_CB rcb[AVCT_NUM_CONN]; tAVRC_FIND_CBACK find_cback; /* sdp discovery callback */ - tSDP_DISCOVERY_DB* p_db; /* pointer to discovery database */ - uint16_t service_uuid; /* service UUID to search */ + tSDP_DISCOVERY_DB* p_db; /* pointer to discovery database */ + uint16_t service_uuid; /* service UUID to search */ } tAVRC_CB; /****************************************************************************** @@ -161,8 +155,7 @@ extern tAVRC_CB avrc_cb; bool avrc_is_valid_pdu_id(uint8_t pdu_id); bool avrc_is_valid_player_attrib_value(uint8_t attrib, uint8_t value); BT_HDR* avrc_alloc_ctrl_pkt(uint8_t pdu); -tAVRC_STS avrc_pars_pass_thru(tAVRC_MSG_PASS* p_msg, - uint16_t* p_vendor_unique_id); +tAVRC_STS avrc_pars_pass_thru(tAVRC_MSG_PASS* p_msg, uint16_t* p_vendor_unique_id); uint8_t avrc_opcode_from_pdu(uint8_t pdu); bool avrc_is_valid_opcode(uint8_t opcode); void avrc_flush_cmd_q(uint8_t handle); diff --git a/system/stack/avrc/avrc_opt.cc b/system/stack/avrc/avrc_opt.cc index 09e623bf8d4..4488123f375 100644 --- a/system/stack/avrc/avrc_opt.cc +++ b/system/stack/avrc/avrc_opt.cc @@ -52,17 +52,16 @@ static BT_HDR* avrc_vendor_msg(tAVRC_MSG_VENDOR* p_msg) { BT_HDR* p_cmd; uint8_t* p_data; - /* - An AVRC cmd consists of at least of: - - A BT_HDR, plus - - AVCT_MSG_OFFSET, plus - - 3 bytes for ctype, subunit_type and op_vendor, plus - - 3 bytes for company_id - */ - #define AVRC_MIN_VENDOR_CMD_LEN (sizeof(BT_HDR) + AVCT_MSG_OFFSET + 3 + 3) - - if (p_msg == nullptr || - AVRC_META_CMD_BUF_SIZE < AVRC_MIN_VENDOR_CMD_LEN + p_msg->vendor_len) { +/* + An AVRC cmd consists of at least of: + - A BT_HDR, plus + - AVCT_MSG_OFFSET, plus + - 3 bytes for ctype, subunit_type and op_vendor, plus + - 3 bytes for company_id +*/ +#define AVRC_MIN_VENDOR_CMD_LEN (sizeof(BT_HDR) + AVCT_MSG_OFFSET + 3 + 3) + + if (p_msg == nullptr || AVRC_META_CMD_BUF_SIZE < AVRC_MIN_VENDOR_CMD_LEN + p_msg->vendor_len) { return nullptr; } @@ -71,14 +70,13 @@ static BT_HDR* avrc_vendor_msg(tAVRC_MSG_VENDOR* p_msg) { p_cmd->offset = AVCT_MSG_OFFSET; p_data = (uint8_t*)(p_cmd + 1) + p_cmd->offset; *p_data++ = (p_msg->hdr.ctype & AVRC_CTYPE_MASK); - *p_data++ = - (p_msg->hdr.subunit_type << AVRC_SUBTYPE_SHIFT) | p_msg->hdr.subunit_id; + *p_data++ = (p_msg->hdr.subunit_type << AVRC_SUBTYPE_SHIFT) | p_msg->hdr.subunit_id; *p_data++ = AVRC_OP_VENDOR; AVRC_CO_ID_TO_BE_STREAM(p_data, p_msg->company_id); - if (p_msg->vendor_len && p_msg->p_vendor_data) + if (p_msg->vendor_len && p_msg->p_vendor_data) { memcpy(p_data, p_msg->p_vendor_data, p_msg->vendor_len); - p_cmd->len = (uint16_t)(p_data + p_msg->vendor_len - (uint8_t*)(p_cmd + 1) - - p_cmd->offset); + } + p_cmd->len = (uint16_t)(p_data + p_msg->vendor_len - (uint8_t*)(p_cmd + 1) - p_cmd->offset); p_cmd->layer_specific = AVCT_DATA_CTRL; return p_cmd; @@ -116,8 +114,7 @@ uint16_t AVRC_UnitCmd(uint8_t handle, uint8_t label) { *p_data++ = (AVRC_SUB_UNIT << AVRC_SUBTYPE_SHIFT) | AVRC_SUBID_IGNORE; *p_data++ = AVRC_OP_UNIT_INFO; memset(p_data, AVRC_CMD_OPRND_PAD, AVRC_UNIT_OPRND_BYTES); - p_cmd->len = - p_data + AVRC_UNIT_OPRND_BYTES - (uint8_t*)(p_cmd + 1) - p_cmd->offset; + p_cmd->len = p_data + AVRC_UNIT_OPRND_BYTES - (uint8_t*)(p_cmd + 1) - p_cmd->offset; p_cmd->layer_specific = AVCT_DATA_CTRL; return AVCT_MsgReq(handle, label, AVCT_CMD, p_cmd); @@ -158,11 +155,9 @@ uint16_t AVRC_SubCmd(uint8_t handle, uint8_t label, uint8_t page) { /* unit & id ignore */ *p_data++ = (AVRC_SUB_UNIT << AVRC_SUBTYPE_SHIFT) | AVRC_SUBID_IGNORE; *p_data++ = AVRC_OP_SUB_INFO; - *p_data++ = - ((page & AVRC_SUB_PAGE_MASK) << AVRC_SUB_PAGE_SHIFT) | AVRC_SUB_EXT_CODE; + *p_data++ = ((page & AVRC_SUB_PAGE_MASK) << AVRC_SUB_PAGE_SHIFT) | AVRC_SUB_EXT_CODE; memset(p_data, AVRC_CMD_OPRND_PAD, AVRC_SUB_OPRND_BYTES); - p_cmd->len = - p_data + AVRC_SUB_OPRND_BYTES - (uint8_t*)(p_cmd + 1) - p_cmd->offset; + p_cmd->len = p_data + AVRC_SUB_OPRND_BYTES - (uint8_t*)(p_cmd + 1) - p_cmd->offset; p_cmd->layer_specific = AVCT_DATA_CTRL; return AVCT_MsgReq(handle, label, AVCT_CMD, p_cmd); @@ -191,13 +186,13 @@ uint16_t AVRC_SubCmd(uint8_t handle, uint8_t label, uint8_t page) { * AVRC_BAD_HANDLE if handle is invalid. * *****************************************************************************/ -uint16_t AVRC_VendorCmd(uint8_t handle, uint8_t label, - tAVRC_MSG_VENDOR* p_msg) { +uint16_t AVRC_VendorCmd(uint8_t handle, uint8_t label, tAVRC_MSG_VENDOR* p_msg) { BT_HDR* p_buf = avrc_vendor_msg(p_msg); - if (p_buf) + if (p_buf) { return AVCT_MsgReq(handle, label, AVCT_CMD, p_buf); - else + } else { return AVCT_NO_RESOURCES; + } } /****************************************************************************** @@ -226,11 +221,11 @@ uint16_t AVRC_VendorCmd(uint8_t handle, uint8_t label, * AVRC_BAD_HANDLE if handle is invalid. * *****************************************************************************/ -uint16_t AVRC_VendorRsp(uint8_t handle, uint8_t label, - tAVRC_MSG_VENDOR* p_msg) { +uint16_t AVRC_VendorRsp(uint8_t handle, uint8_t label, tAVRC_MSG_VENDOR* p_msg) { BT_HDR* p_buf = avrc_vendor_msg(p_msg); - if (p_buf) + if (p_buf) { return AVCT_MsgReq(handle, label, AVCT_RSP, p_buf); - else + } else { return AVCT_NO_RESOURCES; + } } diff --git a/system/stack/avrc/avrc_pars_ct.cc b/system/stack/avrc/avrc_pars_ct.cc index d336354daa1..ed65fc45e4a 100644 --- a/system/stack/avrc/avrc_pars_ct.cc +++ b/system/stack/avrc/avrc_pars_ct.cc @@ -46,31 +46,32 @@ using namespace bluetooth; * Otherwise, the error code defined by AVRCP 1.4 * ******************************************************************************/ -static tAVRC_STS avrc_pars_vendor_rsp(tAVRC_MSG_VENDOR* p_msg, - tAVRC_RESPONSE* p_result) { +static tAVRC_STS avrc_pars_vendor_rsp(tAVRC_MSG_VENDOR* p_msg, tAVRC_RESPONSE* p_result) { tAVRC_STS status = AVRC_STS_NO_ERROR; uint8_t* p; uint16_t len; uint8_t eventid = 0; /* Check the vendor data */ - if (p_msg->vendor_len == 0) return AVRC_STS_NO_ERROR; - if (p_msg->p_vendor_data == NULL) return AVRC_STS_INTERNAL_ERR; + if (p_msg->vendor_len == 0) { + return AVRC_STS_NO_ERROR; + } + if (p_msg->p_vendor_data == NULL) { + return AVRC_STS_INTERNAL_ERR; + } if (p_msg->vendor_len < 4) { - log::warn("message length {} too short: must be at least 4", - p_msg->vendor_len); + log::warn("message length {} too short: must be at least 4", p_msg->vendor_len); return AVRC_STS_INTERNAL_ERR; } p = p_msg->p_vendor_data; BE_STREAM_TO_UINT8(p_result->pdu, p); p++; /* skip the reserved/packe_type byte */ BE_STREAM_TO_UINT16(len, p); - log::verbose("ctype:0x{:x} pdu:0x{:x}, len:{}/0x{:x} vendor_len=0x{:x}", - p_msg->hdr.ctype, p_result->pdu, len, len, p_msg->vendor_len); + log::verbose("ctype:0x{:x} pdu:0x{:x}, len:{}/0x{:x} vendor_len=0x{:x}", p_msg->hdr.ctype, + p_result->pdu, len, len, p_msg->vendor_len); if (p_msg->vendor_len < len + 4) { - log::warn("message length {} too short: must be at least {}", - p_msg->vendor_len, len + 4); + log::warn("message length {} too short: must be at least {}", p_msg->vendor_len, len + 4); return AVRC_STS_INTERNAL_ERR; } @@ -84,16 +85,16 @@ static tAVRC_STS avrc_pars_vendor_rsp(tAVRC_MSG_VENDOR* p_msg, } switch (p_result->pdu) { -/* case AVRC_PDU_REQUEST_CONTINUATION_RSP: 0x40 */ -/* case AVRC_PDU_ABORT_CONTINUATION_RSP: 0x41 */ + /* case AVRC_PDU_REQUEST_CONTINUATION_RSP: 0x40 */ + /* case AVRC_PDU_ABORT_CONTINUATION_RSP: 0x41 */ case AVRC_PDU_SET_ABSOLUTE_VOLUME: /* 0x50 */ if (!avrcp_absolute_volume_is_enabled()) { break; } - if (len != 1) + if (len != 1) { status = AVRC_STS_INTERNAL_ERR; - else { + } else { BE_STREAM_TO_UINT8(p_result->volume.volume, p); } break; @@ -108,10 +109,8 @@ static tAVRC_STS avrc_pars_vendor_rsp(tAVRC_MSG_VENDOR* p_msg, } BE_STREAM_TO_UINT8(eventid, p); if (AVRC_EVT_VOLUME_CHANGE == eventid && - (AVRC_RSP_CHANGED == p_msg->hdr.ctype || - AVRC_RSP_INTERIM == p_msg->hdr.ctype || - AVRC_RSP_REJ == p_msg->hdr.ctype || - AVRC_RSP_NOT_IMPL == p_msg->hdr.ctype)) { + (AVRC_RSP_CHANGED == p_msg->hdr.ctype || AVRC_RSP_INTERIM == p_msg->hdr.ctype || + AVRC_RSP_REJ == p_msg->hdr.ctype || AVRC_RSP_NOT_IMPL == p_msg->hdr.ctype)) { if (len < 2) { log::warn("invalid parameter length {}: must be at least 2", len); return AVRC_STS_INTERNAL_ERR; @@ -131,40 +130,46 @@ static tAVRC_STS avrc_pars_vendor_rsp(tAVRC_MSG_VENDOR* p_msg, return status; } -tAVRC_STS avrc_parse_notification_rsp(uint8_t* p_stream, uint16_t len, - tAVRC_REG_NOTIF_RSP* p_rsp) { +tAVRC_STS avrc_parse_notification_rsp(uint8_t* p_stream, uint16_t len, tAVRC_REG_NOTIF_RSP* p_rsp) { uint32_t min_len = 1; - if (len < min_len) goto length_error; + if (len < min_len) { + goto length_error; + } BE_STREAM_TO_UINT8(p_rsp->event_id, p_stream); switch (p_rsp->event_id) { case AVRC_EVT_PLAY_STATUS_CHANGE: min_len += 1; - if (len < min_len) goto length_error; + if (len < min_len) { + goto length_error; + } BE_STREAM_TO_UINT8(p_rsp->param.play_status, p_stream); break; case AVRC_EVT_TRACK_CHANGE: min_len += 8; - if (len < min_len) goto length_error; + if (len < min_len) { + goto length_error; + } BE_STREAM_TO_ARRAY(p_stream, p_rsp->param.track, 8); break; case AVRC_EVT_APP_SETTING_CHANGE: min_len += 1; - if (len < min_len) goto length_error; + if (len < min_len) { + goto length_error; + } BE_STREAM_TO_UINT8(p_rsp->param.player_setting.num_attr, p_stream); if (p_rsp->param.player_setting.num_attr > AVRC_MAX_APP_SETTINGS) { p_rsp->param.player_setting.num_attr = AVRC_MAX_APP_SETTINGS; } min_len += p_rsp->param.player_setting.num_attr * 2; - if (len < min_len) goto length_error; - for (int index = 0; index < p_rsp->param.player_setting.num_attr; - index++) { - BE_STREAM_TO_UINT8(p_rsp->param.player_setting.attr_id[index], - p_stream); - BE_STREAM_TO_UINT8(p_rsp->param.player_setting.attr_value[index], - p_stream); + if (len < min_len) { + goto length_error; + } + for (int index = 0; index < p_rsp->param.player_setting.num_attr; index++) { + BE_STREAM_TO_UINT8(p_rsp->param.player_setting.attr_id[index], p_stream); + BE_STREAM_TO_UINT8(p_rsp->param.player_setting.attr_value[index], p_stream); } break; @@ -176,14 +181,18 @@ tAVRC_STS avrc_parse_notification_rsp(uint8_t* p_stream, uint16_t len, case AVRC_EVT_ADDR_PLAYER_CHANGE: min_len += 4; - if (len < min_len) goto length_error; + if (len < min_len) { + goto length_error; + } BE_STREAM_TO_UINT16(p_rsp->param.addr_player.player_id, p_stream); BE_STREAM_TO_UINT16(p_rsp->param.addr_player.uid_counter, p_stream); break; case AVRC_EVT_PLAY_POS_CHANGED: min_len += 4; - if (len < min_len) goto length_error; + if (len < min_len) { + goto length_error; + } BE_STREAM_TO_UINT32(p_rsp->param.play_pos, p_stream); break; @@ -205,8 +214,7 @@ length_error: return AVRC_STS_INTERNAL_ERR; } -static tAVRC_STS avrc_pars_browse_rsp(tAVRC_MSG_BROWSE* p_msg, - tAVRC_RESPONSE* p_rsp) { +static tAVRC_STS avrc_pars_browse_rsp(tAVRC_MSG_BROWSE* p_msg, tAVRC_RESPONSE* p_rsp) { tAVRC_STS status = AVRC_STS_NO_ERROR; uint8_t pdu; @@ -219,8 +227,7 @@ static tAVRC_STS avrc_pars_browse_rsp(tAVRC_MSG_BROWSE* p_msg, /* read the pdu */ if (p_msg->browse_len < 3) { - log::warn("message length {} too short: must be at least 3", - p_msg->browse_len); + log::warn("message length {} too short: must be at least 3", p_msg->browse_len); return AVRC_STS_BAD_PARAM; } BE_STREAM_TO_UINT8(pdu, p); @@ -232,8 +239,7 @@ static tAVRC_STS avrc_pars_browse_rsp(tAVRC_MSG_BROWSE* p_msg, log::verbose("pdu:{}, pkt_len:{}", pdu, pkt_len); if (p_msg->browse_len < (pkt_len + 3)) { - log::warn("message length {} too short: must be at least {}", - p_msg->browse_len, pkt_len + 3); + log::warn("message length {} too short: must be at least {}", p_msg->browse_len, pkt_len + 3); return AVRC_STS_INTERNAL_ERR; } @@ -244,7 +250,9 @@ static tAVRC_STS avrc_pars_browse_rsp(tAVRC_MSG_BROWSE* p_msg, get_item_rsp->pdu = pdu; min_len += 1; - if (pkt_len < min_len) goto browse_length_error; + if (pkt_len < min_len) { + goto browse_length_error; + } /* read the status */ BE_STREAM_TO_UINT8(get_item_rsp->status, p); if (get_item_rsp->status != AVRC_STS_NO_ERROR) { @@ -253,23 +261,27 @@ static tAVRC_STS avrc_pars_browse_rsp(tAVRC_MSG_BROWSE* p_msg, } min_len += 4; - if (pkt_len < min_len) goto browse_length_error; + if (pkt_len < min_len) { + goto browse_length_error; + } /* read the UID counter */ BE_STREAM_TO_UINT16(get_item_rsp->uid_counter, p); /* read the number of items */ BE_STREAM_TO_UINT16(get_item_rsp->item_count, p); - log::verbose("pdu {} status {} pkt_len {} uid counter {} item count {}", - get_item_rsp->pdu, get_item_rsp->status, pkt_len, - get_item_rsp->uid_counter, get_item_rsp->item_count); + log::verbose("pdu {} status {} pkt_len {} uid counter {} item count {}", get_item_rsp->pdu, + get_item_rsp->status, pkt_len, get_item_rsp->uid_counter, + get_item_rsp->item_count); /* get each of the items */ - get_item_rsp->p_item_list = (tAVRC_ITEM*)osi_calloc( - get_item_rsp->item_count * (sizeof(tAVRC_ITEM))); + get_item_rsp->p_item_list = + (tAVRC_ITEM*)osi_calloc(get_item_rsp->item_count * (sizeof(tAVRC_ITEM))); tAVRC_ITEM* curr_item = get_item_rsp->p_item_list; for (int i = 0; i < get_item_rsp->item_count; i++) { min_len += 1; - if (pkt_len < min_len) goto browse_length_error; + if (pkt_len < min_len) { + goto browse_length_error; + } BE_STREAM_TO_UINT8(curr_item->item_type, p); log::verbose("item type {}", curr_item->item_type); switch (curr_item->item_type) { @@ -278,7 +290,9 @@ static tAVRC_STS avrc_pars_browse_rsp(tAVRC_MSG_BROWSE* p_msg, tAVRC_ITEM_PLAYER* player = &(curr_item->u.player); uint8_t player_len; min_len += 10 + AVRC_FEATURE_MASK_SIZE; - if (pkt_len < min_len) goto browse_length_error; + if (pkt_len < min_len) { + goto browse_length_error; + } BE_STREAM_TO_UINT16(player_len, p); BE_STREAM_TO_UINT16(player->player_id, p); BE_STREAM_TO_UINT8(player->major_type, p); @@ -288,26 +302,30 @@ static tAVRC_STS avrc_pars_browse_rsp(tAVRC_MSG_BROWSE* p_msg, /* read str */ min_len += 4; - if (pkt_len < min_len) goto browse_length_error; + if (pkt_len < min_len) { + goto browse_length_error; + } BE_STREAM_TO_UINT16(player->name.charset_id, p); BE_STREAM_TO_UINT16(player->name.str_len, p); min_len += player->name.str_len; - if (pkt_len < min_len) goto browse_length_error; - player->name.p_str = (uint8_t*)osi_calloc( - (player->name.str_len + 1) * sizeof(uint8_t)); + if (pkt_len < min_len) { + goto browse_length_error; + } + player->name.p_str = (uint8_t*)osi_calloc((player->name.str_len + 1) * sizeof(uint8_t)); BE_STREAM_TO_ARRAY(p, player->name.p_str, player->name.str_len); - log::verbose( - "type {} id {} mtype {} stype {} ps {} cs {} name len {}", - curr_item->item_type, player->player_id, player->major_type, - player->sub_type, player->play_status, player->name.charset_id, - player->name.str_len); + log::verbose("type {} id {} mtype {} stype {} ps {} cs {} name len {}", + curr_item->item_type, player->player_id, player->major_type, + player->sub_type, player->play_status, player->name.charset_id, + player->name.str_len); } break; case AVRC_ITEM_FOLDER: { tAVRC_ITEM_FOLDER* folder = &(curr_item->u.folder); uint16_t folder_len; min_len += 4 + AVRC_UID_SIZE; - if (pkt_len < min_len) goto browse_length_error; + if (pkt_len < min_len) { + goto browse_length_error; + } BE_STREAM_TO_UINT16(folder_len, p); BE_STREAM_TO_ARRAY(p, folder->uid, AVRC_UID_SIZE); @@ -316,64 +334,72 @@ static tAVRC_STS avrc_pars_browse_rsp(tAVRC_MSG_BROWSE* p_msg, /* read str, encoding to be handled by upper layers */ min_len += 4; - if (pkt_len < min_len) goto browse_length_error; + if (pkt_len < min_len) { + goto browse_length_error; + } BE_STREAM_TO_UINT16(folder->name.charset_id, p); BE_STREAM_TO_UINT16(folder->name.str_len, p); min_len += folder->name.str_len; - if (pkt_len < min_len) goto browse_length_error; - folder->name.p_str = (uint8_t*)osi_calloc( - (folder->name.str_len + 1) * sizeof(uint8_t)); + if (pkt_len < min_len) { + goto browse_length_error; + } + folder->name.p_str = (uint8_t*)osi_calloc((folder->name.str_len + 1) * sizeof(uint8_t)); BE_STREAM_TO_ARRAY(p, folder->name.p_str, folder->name.str_len); - log::verbose("type {} playable {} cs {} name len {}", folder->type, - folder->playable, folder->name.charset_id, - folder->name.str_len); + log::verbose("type {} playable {} cs {} name len {}", folder->type, folder->playable, + folder->name.charset_id, folder->name.str_len); } break; case AVRC_ITEM_MEDIA: { tAVRC_ITEM_MEDIA* media = &(curr_item->u.media); uint8_t media_len; min_len += 3 + AVRC_UID_SIZE; - if (pkt_len < min_len) goto browse_length_error; + if (pkt_len < min_len) { + goto browse_length_error; + } BE_STREAM_TO_UINT16(media_len, p); BE_STREAM_TO_ARRAY(p, media->uid, AVRC_UID_SIZE); BE_STREAM_TO_UINT8(media->type, p); /* read str, encoding to be handled by upper layers */ min_len += 4; - if (pkt_len < min_len) goto browse_length_error; + if (pkt_len < min_len) { + goto browse_length_error; + } BE_STREAM_TO_UINT16(media->name.charset_id, p); BE_STREAM_TO_UINT16(media->name.str_len, p); min_len += 1 + media->name.str_len; - if (pkt_len < min_len) goto browse_length_error; - media->name.p_str = - (uint8_t*)osi_malloc((media->name.str_len) * sizeof(uint8_t)); + if (pkt_len < min_len) { + goto browse_length_error; + } + media->name.p_str = (uint8_t*)osi_malloc((media->name.str_len) * sizeof(uint8_t)); BE_STREAM_TO_ARRAY(p, media->name.p_str, media->name.str_len); BE_STREAM_TO_UINT8(media->attr_count, p); - log::verbose("media type {} charset id {} len {} attr ct {}", - media->type, media->name.charset_id, - media->name.str_len, media->attr_count); + log::verbose("media type {} charset id {} len {} attr ct {}", media->type, + media->name.charset_id, media->name.str_len, media->attr_count); - media->p_attr_list = (tAVRC_ATTR_ENTRY*)osi_calloc( - media->attr_count * sizeof(tAVRC_ATTR_ENTRY)); + media->p_attr_list = + (tAVRC_ATTR_ENTRY*)osi_calloc(media->attr_count * sizeof(tAVRC_ATTR_ENTRY)); for (int jk = 0; jk < media->attr_count; jk++) { tAVRC_ATTR_ENTRY* attr_entry = &(media->p_attr_list[jk]); min_len += 8; - if (pkt_len < min_len) goto browse_length_error; + if (pkt_len < min_len) { + goto browse_length_error; + } BE_STREAM_TO_UINT32(attr_entry->attr_id, p); /* Parse the name now */ BE_STREAM_TO_UINT16(attr_entry->name.charset_id, p); BE_STREAM_TO_UINT16(attr_entry->name.str_len, p); min_len += attr_entry->name.str_len; - if (pkt_len < min_len) goto browse_length_error; - attr_entry->name.p_str = (uint8_t*)osi_malloc( - attr_entry->name.str_len * sizeof(uint8_t)); - BE_STREAM_TO_ARRAY(p, attr_entry->name.p_str, - attr_entry->name.str_len); - log::verbose("media attr id {} cs {} name len {}", - attr_entry->attr_id, attr_entry->name.charset_id, - attr_entry->name.str_len); + if (pkt_len < min_len) { + goto browse_length_error; + } + attr_entry->name.p_str = + (uint8_t*)osi_malloc(attr_entry->name.str_len * sizeof(uint8_t)); + BE_STREAM_TO_ARRAY(p, attr_entry->name.p_str, attr_entry->name.str_len); + log::verbose("media attr id {} cs {} name len {}", attr_entry->attr_id, + attr_entry->name.charset_id, attr_entry->name.str_len); } } break; @@ -393,7 +419,9 @@ static tAVRC_STS avrc_pars_browse_rsp(tAVRC_MSG_BROWSE* p_msg, case AVRC_PDU_CHANGE_PATH: { tAVRC_CHG_PATH_RSP* change_path_rsp = &(p_rsp->chg_path); min_len += 5; - if (pkt_len < min_len) goto browse_length_error; + if (pkt_len < min_len) { + goto browse_length_error; + } /* Copyback the PDU */ change_path_rsp->pdu = pdu; /* Read the status */ @@ -401,8 +429,8 @@ static tAVRC_STS avrc_pars_browse_rsp(tAVRC_MSG_BROWSE* p_msg, /* Read the number of items in folder */ BE_STREAM_TO_UINT32(change_path_rsp->num_items, p); - log::verbose("pdu {} status {} item count {}", change_path_rsp->pdu, - change_path_rsp->status, change_path_rsp->num_items); + log::verbose("pdu {} status {} item count {}", change_path_rsp->pdu, change_path_rsp->status, + change_path_rsp->num_items); break; } @@ -415,19 +443,22 @@ static tAVRC_STS avrc_pars_browse_rsp(tAVRC_MSG_BROWSE* p_msg, } BE_STREAM_TO_UINT8(get_attr_rsp->status, p) BE_STREAM_TO_UINT8(get_attr_rsp->num_attrs, p); - get_attr_rsp->p_attrs = (tAVRC_ATTR_ENTRY*)osi_calloc( - get_attr_rsp->num_attrs * sizeof(tAVRC_ATTR_ENTRY)); + get_attr_rsp->p_attrs = + (tAVRC_ATTR_ENTRY*)osi_calloc(get_attr_rsp->num_attrs * sizeof(tAVRC_ATTR_ENTRY)); for (int i = 0; i < get_attr_rsp->num_attrs; i++) { tAVRC_ATTR_ENTRY* attr_entry = &(get_attr_rsp->p_attrs[i]); min_len += 8; - if (pkt_len < min_len) goto browse_length_error; + if (pkt_len < min_len) { + goto browse_length_error; + } BE_STREAM_TO_UINT32(attr_entry->attr_id, p); BE_STREAM_TO_UINT16(attr_entry->name.charset_id, p); BE_STREAM_TO_UINT16(attr_entry->name.str_len, p); min_len += attr_entry->name.str_len; - if (pkt_len < min_len) goto browse_length_error; - attr_entry->name.p_str = - (uint8_t*)osi_malloc(attr_entry->name.str_len * sizeof(uint8_t)); + if (pkt_len < min_len) { + goto browse_length_error; + } + attr_entry->name.p_str = (uint8_t*)osi_malloc(attr_entry->name.str_len * sizeof(uint8_t)); BE_STREAM_TO_ARRAY(p, attr_entry->name.p_str, attr_entry->name.str_len); log::verbose("media attr id {} cs {} name len {}", attr_entry->attr_id, attr_entry->name.charset_id, attr_entry->name.str_len); @@ -442,39 +473,41 @@ static tAVRC_STS avrc_pars_browse_rsp(tAVRC_MSG_BROWSE* p_msg, /* Read the status */ min_len += 10; - if (pkt_len < min_len) goto browse_length_error; + if (pkt_len < min_len) { + goto browse_length_error; + } BE_STREAM_TO_UINT8(set_br_pl_rsp->status, p); if (set_br_pl_rsp->status != AVRC_STS_NO_ERROR) { - log::error( - "Stopping further parsing because player not browsable sts {}", - set_br_pl_rsp->status); + log::error("Stopping further parsing because player not browsable sts {}", + set_br_pl_rsp->status); break; } BE_STREAM_TO_UINT16(set_br_pl_rsp->uid_counter, p); BE_STREAM_TO_UINT32(set_br_pl_rsp->num_items, p); BE_STREAM_TO_UINT16(set_br_pl_rsp->charset_id, p); BE_STREAM_TO_UINT8(set_br_pl_rsp->folder_depth, p); - log::verbose( - "AVRC_PDU_SET_BROWSED_PLAYER status {} items {} cs {} depth {}", - set_br_pl_rsp->status, set_br_pl_rsp->num_items, - set_br_pl_rsp->charset_id, set_br_pl_rsp->folder_depth); + log::verbose("AVRC_PDU_SET_BROWSED_PLAYER status {} items {} cs {} depth {}", + set_br_pl_rsp->status, set_br_pl_rsp->num_items, set_br_pl_rsp->charset_id, + set_br_pl_rsp->folder_depth); - set_br_pl_rsp->p_folders = (tAVRC_NAME*)osi_calloc( - set_br_pl_rsp->folder_depth * sizeof(tAVRC_NAME)); + set_br_pl_rsp->p_folders = + (tAVRC_NAME*)osi_calloc(set_br_pl_rsp->folder_depth * sizeof(tAVRC_NAME)); /* Read each of the folder in the depth */ for (uint32_t i = 0; i < set_br_pl_rsp->folder_depth; i++) { tAVRC_NAME* folder_name = &(set_br_pl_rsp->p_folders[i]); min_len += 2; - if (pkt_len < min_len) goto browse_length_error; + if (pkt_len < min_len) { + goto browse_length_error; + } BE_STREAM_TO_UINT16(folder_name->str_len, p); min_len += folder_name->str_len; - if (pkt_len < min_len) goto browse_length_error; - log::verbose("AVRC_PDU_SET_BROWSED_PLAYER item: {} len: {}", i, - folder_name->str_len); - folder_name->p_str = - (uint8_t*)osi_calloc((folder_name->str_len + 1) * sizeof(uint8_t)); + if (pkt_len < min_len) { + goto browse_length_error; + } + log::verbose("AVRC_PDU_SET_BROWSED_PLAYER item: {} len: {}", i, folder_name->str_len); + folder_name->p_str = (uint8_t*)osi_calloc((folder_name->str_len + 1) * sizeof(uint8_t)); BE_STREAM_TO_ARRAY(p, folder_name->p_str, folder_name->str_len); } break; @@ -487,8 +520,7 @@ static tAVRC_STS avrc_pars_browse_rsp(tAVRC_MSG_BROWSE* p_msg, return status; browse_length_error: - log::warn("invalid parameter length {}: must be at least {}", pkt_len, - min_len); + log::warn("invalid parameter length {}: must be at least {}", pkt_len, min_len); return AVRC_STS_BAD_CMD; } @@ -504,12 +536,10 @@ browse_length_error: * Otherwise, the error code defined by AVRCP 1.4 * ******************************************************************************/ -static tAVRC_STS avrc_ctrl_pars_vendor_rsp(tAVRC_MSG_VENDOR* p_msg, - tAVRC_RESPONSE* p_result, +static tAVRC_STS avrc_ctrl_pars_vendor_rsp(tAVRC_MSG_VENDOR* p_msg, tAVRC_RESPONSE* p_result, uint8_t* p_buf, uint16_t* buf_len) { if (p_msg->vendor_len < 4) { - log::warn("message length {} too short: must be at least 4", - p_msg->vendor_len); + log::warn("message length {} too short: must be at least 4", p_msg->vendor_len); return AVRC_STS_INTERNAL_ERR; } @@ -520,25 +550,26 @@ static tAVRC_STS avrc_ctrl_pars_vendor_rsp(tAVRC_MSG_VENDOR* p_msg, uint16_t len; uint32_t min_len = 0; BE_STREAM_TO_UINT16(len, p); - log::verbose("ctype:0x{:x} pdu:0x{:x}, len:{} vendor_len=0x{:x}", - p_msg->hdr.ctype, p_result->pdu, len, p_msg->vendor_len); + log::verbose("ctype:0x{:x} pdu:0x{:x}, len:{} vendor_len=0x{:x}", p_msg->hdr.ctype, + p_result->pdu, len, p_msg->vendor_len); if (p_msg->vendor_len < len + 4) { - log::warn("message length {} too short: must be at least {}", - p_msg->vendor_len, len + 4); + log::warn("message length {} too short: must be at least {}", p_msg->vendor_len, len + 4); return AVRC_STS_INTERNAL_ERR; } /* Todo: Issue in handling reject, check */ if (p_msg->hdr.ctype == AVRC_RSP_REJ) { min_len += 1; - if (len < min_len) goto length_error; + if (len < min_len) { + goto length_error; + } p_result->rsp.status = *p; return p_result->rsp.status; } /* TODO: Break the big switch into functions. */ switch (p_result->pdu) { - /* case AVRC_PDU_REQUEST_CONTINUATION_RSP: 0x40 */ - /* case AVRC_PDU_ABORT_CONTINUATION_RSP: 0x41 */ + /* case AVRC_PDU_REQUEST_CONTINUATION_RSP: 0x40 */ + /* case AVRC_PDU_ABORT_CONTINUATION_RSP: 0x41 */ case AVRC_PDU_REGISTER_NOTIFICATION: return avrc_parse_notification_rsp(p, len, &p_result->reg_notif); @@ -550,31 +581,34 @@ static tAVRC_STS avrc_ctrl_pars_vendor_rsp(tAVRC_MSG_VENDOR* p_msg, break; } min_len += 2; - if (len < min_len) goto length_error; + if (len < min_len) { + goto length_error; + } BE_STREAM_TO_UINT8(p_result->get_caps.capability_id, p); BE_STREAM_TO_UINT8(p_result->get_caps.count, p); - log::verbose("cap id = {}, cap_count = {}", - p_result->get_caps.capability_id, p_result->get_caps.count); + log::verbose("cap id = {}, cap_count = {}", p_result->get_caps.capability_id, + p_result->get_caps.count); if (p_result->get_caps.capability_id == AVRC_CAP_COMPANY_ID) { if (p_result->get_caps.count > AVRC_CAP_MAX_NUM_COMP_ID) { return AVRC_STS_INTERNAL_ERR; } min_len += MIN(p_result->get_caps.count, AVRC_CAP_MAX_NUM_COMP_ID) * 3; - if (len < min_len) goto length_error; - for (int xx = 0; ((xx < p_result->get_caps.count) && - (xx < AVRC_CAP_MAX_NUM_COMP_ID)); + if (len < min_len) { + goto length_error; + } + for (int xx = 0; ((xx < p_result->get_caps.count) && (xx < AVRC_CAP_MAX_NUM_COMP_ID)); xx++) { BE_STREAM_TO_UINT24(p_result->get_caps.param.company_id[xx], p); } - } else if (p_result->get_caps.capability_id == - AVRC_CAP_EVENTS_SUPPORTED) { + } else if (p_result->get_caps.capability_id == AVRC_CAP_EVENTS_SUPPORTED) { if (p_result->get_caps.count > AVRC_CAP_MAX_NUM_EVT_ID) { return AVRC_STS_INTERNAL_ERR; } min_len += MIN(p_result->get_caps.count, AVRC_CAP_MAX_NUM_EVT_ID); - if (len < min_len) goto length_error; - for (int xx = 0; ((xx < p_result->get_caps.count) && - (xx < AVRC_CAP_MAX_NUM_EVT_ID)); + if (len < min_len) { + goto length_error; + } + for (int xx = 0; ((xx < p_result->get_caps.count) && (xx < AVRC_CAP_MAX_NUM_EVT_ID)); xx++) { BE_STREAM_TO_UINT8(p_result->get_caps.param.event_id[xx], p); } @@ -595,7 +629,9 @@ static tAVRC_STS avrc_ctrl_pars_vendor_rsp(tAVRC_MSG_VENDOR* p_msg, } min_len += p_result->list_app_attr.num_attr; - if (len < min_len) goto length_error; + if (len < min_len) { + goto length_error; + } for (int xx = 0; xx < p_result->list_app_attr.num_attr; xx++) { BE_STREAM_TO_UINT8(p_result->list_app_attr.attrs[xx], p); } @@ -614,7 +650,9 @@ static tAVRC_STS avrc_ctrl_pars_vendor_rsp(tAVRC_MSG_VENDOR* p_msg, log::verbose("value count = {}", p_result->list_app_values.num_val); min_len += p_result->list_app_values.num_val; - if (len < min_len) goto length_error; + if (len < min_len) { + goto length_error; + } for (int xx = 0; xx < p_result->list_app_values.num_val; xx++) { BE_STREAM_TO_UINT8(p_result->list_app_values.vals[xx], p); } @@ -639,7 +677,7 @@ static tAVRC_STS avrc_ctrl_pars_vendor_rsp(tAVRC_MSG_VENDOR* p_msg, goto length_error; } tAVRC_APP_SETTING* app_sett = (tAVRC_APP_SETTING*)osi_calloc( - p_result->get_cur_app_val.num_val * sizeof(tAVRC_APP_SETTING)); + p_result->get_cur_app_val.num_val * sizeof(tAVRC_APP_SETTING)); for (int xx = 0; xx < p_result->get_cur_app_val.num_val; xx++) { BE_STREAM_TO_UINT8(app_sett[xx].attr_id, p); BE_STREAM_TO_UINT8(app_sett[xx].attr_val, p); @@ -662,8 +700,8 @@ static tAVRC_STS avrc_ctrl_pars_vendor_rsp(tAVRC_MSG_VENDOR* p_msg, log::verbose("attr count = {}", p_result->get_app_attr_txt.num_attr); p_result->get_app_attr_txt.num_attr = num_attrs; - p_result->get_app_attr_txt.p_attrs = (tAVRC_APP_SETTING_TEXT*)osi_calloc( - num_attrs * sizeof(tAVRC_APP_SETTING_TEXT)); + p_result->get_app_attr_txt.p_attrs = + (tAVRC_APP_SETTING_TEXT*)osi_calloc(num_attrs * sizeof(tAVRC_APP_SETTING_TEXT)); for (int xx = 0; xx < num_attrs; xx++) { min_len += 4; if (len < min_len) { @@ -675,8 +713,7 @@ static tAVRC_STS avrc_ctrl_pars_vendor_rsp(tAVRC_MSG_VENDOR* p_msg, goto length_error; } BE_STREAM_TO_UINT8(p_result->get_app_attr_txt.p_attrs[xx].attr_id, p); - BE_STREAM_TO_UINT16(p_result->get_app_attr_txt.p_attrs[xx].charset_id, - p); + BE_STREAM_TO_UINT16(p_result->get_app_attr_txt.p_attrs[xx].charset_id, p); BE_STREAM_TO_UINT8(p_result->get_app_attr_txt.p_attrs[xx].str_len, p); min_len += p_result->get_app_attr_txt.p_attrs[xx].str_len; if (len < min_len) { @@ -688,10 +725,8 @@ static tAVRC_STS avrc_ctrl_pars_vendor_rsp(tAVRC_MSG_VENDOR* p_msg, goto length_error; } if (p_result->get_app_attr_txt.p_attrs[xx].str_len != 0) { - uint8_t* p_str = (uint8_t*)osi_calloc( - p_result->get_app_attr_txt.p_attrs[xx].str_len); - BE_STREAM_TO_ARRAY(p, p_str, - p_result->get_app_attr_txt.p_attrs[xx].str_len); + uint8_t* p_str = (uint8_t*)osi_calloc(p_result->get_app_attr_txt.p_attrs[xx].str_len); + BE_STREAM_TO_ARRAY(p, p_str, p_result->get_app_attr_txt.p_attrs[xx].str_len); p_result->get_app_attr_txt.p_attrs[xx].p_str = p_str; } else { p_result->get_app_attr_txt.p_attrs[xx].p_str = NULL; @@ -714,8 +749,8 @@ static tAVRC_STS avrc_ctrl_pars_vendor_rsp(tAVRC_MSG_VENDOR* p_msg, p_result->get_app_val_txt.num_attr = num_vals; log::verbose("value count = {}", p_result->get_app_val_txt.num_attr); - p_result->get_app_val_txt.p_attrs = (tAVRC_APP_SETTING_TEXT*)osi_calloc( - num_vals * sizeof(tAVRC_APP_SETTING_TEXT)); + p_result->get_app_val_txt.p_attrs = + (tAVRC_APP_SETTING_TEXT*)osi_calloc(num_vals * sizeof(tAVRC_APP_SETTING_TEXT)); for (int i = 0; i < num_vals; i++) { min_len += 4; if (len < min_len) { @@ -739,10 +774,8 @@ static tAVRC_STS avrc_ctrl_pars_vendor_rsp(tAVRC_MSG_VENDOR* p_msg, goto length_error; } if (p_result->get_app_val_txt.p_attrs[i].str_len != 0) { - uint8_t* p_str = (uint8_t*)osi_calloc( - p_result->get_app_val_txt.p_attrs[i].str_len); - BE_STREAM_TO_ARRAY(p, p_str, - p_result->get_app_val_txt.p_attrs[i].str_len); + uint8_t* p_str = (uint8_t*)osi_calloc(p_result->get_app_val_txt.p_attrs[i].str_len); + BE_STREAM_TO_ARRAY(p, p_str, p_result->get_app_val_txt.p_attrs[i].str_len); p_result->get_app_val_txt.p_attrs[i].p_str = p_str; } else { p_result->get_app_val_txt.p_attrs[i].p_str = NULL; @@ -766,7 +799,7 @@ static tAVRC_STS avrc_ctrl_pars_vendor_rsp(tAVRC_MSG_VENDOR* p_msg, p_result->get_attrs.num_attrs = num_attrs; if (num_attrs) { tAVRC_ATTR_ENTRY* p_attrs = - (tAVRC_ATTR_ENTRY*)osi_calloc(num_attrs * sizeof(tAVRC_ATTR_ENTRY)); + (tAVRC_ATTR_ENTRY*)osi_calloc(num_attrs * sizeof(tAVRC_ATTR_ENTRY)); for (int i = 0; i < num_attrs; i++) { min_len += 8; if (len < min_len) { @@ -790,10 +823,8 @@ static tAVRC_STS avrc_ctrl_pars_vendor_rsp(tAVRC_MSG_VENDOR* p_msg, goto length_error; } if (p_attrs[i].name.str_len > 0) { - p_attrs[i].name.p_str = - (uint8_t*)osi_calloc(p_attrs[i].name.str_len); - BE_STREAM_TO_ARRAY(p, p_attrs[i].name.p_str, - p_attrs[i].name.str_len); + p_attrs[i].name.p_str = (uint8_t*)osi_calloc(p_attrs[i].name.str_len); + BE_STREAM_TO_ARRAY(p, p_attrs[i].name.p_str, p_attrs[i].name.str_len); } else { p_attrs[i].name.p_str = NULL; } @@ -807,7 +838,9 @@ static tAVRC_STS avrc_ctrl_pars_vendor_rsp(tAVRC_MSG_VENDOR* p_msg, break; } min_len += 9; - if (len < min_len) goto length_error; + if (len < min_len) { + goto length_error; + } BE_STREAM_TO_UINT32(p_result->get_play_status.song_len, p); BE_STREAM_TO_UINT32(p_result->get_play_status.song_pos, p); BE_STREAM_TO_UINT8(p_result->get_play_status.play_status, p); @@ -842,14 +875,13 @@ length_error: * Otherwise, the error code defined by AVRCP 1.4 * ******************************************************************************/ -tAVRC_STS AVRC_Ctrl_ParsResponse(tAVRC_MSG* p_msg, tAVRC_RESPONSE* p_result, - uint8_t* p_buf, uint16_t* buf_len) { +tAVRC_STS AVRC_Ctrl_ParsResponse(tAVRC_MSG* p_msg, tAVRC_RESPONSE* p_result, uint8_t* p_buf, + uint16_t* buf_len) { tAVRC_STS status = AVRC_STS_INTERNAL_ERR; if (p_msg && p_result) { switch (p_msg->hdr.opcode) { case AVRC_OP_VENDOR: /* 0x00 Vendor-dependent commands */ - status = - avrc_ctrl_pars_vendor_rsp(&p_msg->vendor, p_result, p_buf, buf_len); + status = avrc_ctrl_pars_vendor_rsp(&p_msg->vendor, p_result, p_buf, buf_len); break; case AVRC_OP_BROWSE: /* 0xff Browse commands */ @@ -878,8 +910,8 @@ tAVRC_STS AVRC_Ctrl_ParsResponse(tAVRC_MSG* p_msg, tAVRC_RESPONSE* p_result, * Otherwise, the error code defined by AVRCP 1.4 * ******************************************************************************/ -tAVRC_STS AVRC_ParsResponse(tAVRC_MSG* p_msg, tAVRC_RESPONSE* p_result, - uint8_t* /* p_buf */, uint16_t /* buf_len */) { +tAVRC_STS AVRC_ParsResponse(tAVRC_MSG* p_msg, tAVRC_RESPONSE* p_result, uint8_t* /* p_buf */, + uint16_t /* buf_len */) { tAVRC_STS status = AVRC_STS_INTERNAL_ERR; uint16_t id; diff --git a/system/stack/avrc/avrc_pars_tg.cc b/system/stack/avrc/avrc_pars_tg.cc index 578fcc15fb2..b178fd5acb3 100644 --- a/system/stack/avrc/avrc_pars_tg.cc +++ b/system/stack/avrc/avrc_pars_tg.cc @@ -35,20 +35,18 @@ using namespace bluetooth; * Function avrc_ctrl_pars_vendor_cmd * * Description This function parses the vendor specific commands defined by - * Bluetooth SIG for AVRCP Conroller. + * Bluetooth SIG for AVRCP Controller. * * Returns AVRC_STS_NO_ERROR, if the message in p_data is parsed * successfully. * Otherwise, the error code defined by AVRCP 1.4 * ******************************************************************************/ -static tAVRC_STS avrc_ctrl_pars_vendor_cmd(tAVRC_MSG_VENDOR* p_msg, - tAVRC_COMMAND* p_result) { +static tAVRC_STS avrc_ctrl_pars_vendor_cmd(tAVRC_MSG_VENDOR* p_msg, tAVRC_COMMAND* p_result) { tAVRC_STS status = AVRC_STS_NO_ERROR; if (p_msg->vendor_len < 4) { // 4 == pdu + reserved byte + len as uint16 - log::warn("message length {} too short: must be at least 4", - p_msg->vendor_len); + log::warn("message length {} too short: must be at least 4", p_msg->vendor_len); return AVRC_STS_INTERNAL_ERR; } uint8_t* p = p_msg->p_vendor_data; @@ -66,20 +64,24 @@ static tAVRC_STS avrc_ctrl_pars_vendor_cmd(tAVRC_MSG_VENDOR* p_msg, status = AVRC_STS_INTERNAL_ERR; } - if (status != AVRC_STS_NO_ERROR) return status; + if (status != AVRC_STS_NO_ERROR) { + return status; + } switch (p_result->pdu) { case AVRC_PDU_SET_ABSOLUTE_VOLUME: { - if (len != 1) + if (len != 1) { status = AVRC_STS_INTERNAL_ERR; - else { + } else { BE_STREAM_TO_UINT8(p_result->volume.volume, p); p_result->volume.volume = AVRC_MAX_VOLUME & p_result->volume.volume; } break; } case AVRC_PDU_REGISTER_NOTIFICATION: /* 0x31 */ - if (len < 5) return AVRC_STS_INTERNAL_ERR; + if (len < 5) { + return AVRC_STS_INTERNAL_ERR; + } BE_STREAM_TO_UINT8(p_result->reg_notif.event_id, p); BE_STREAM_TO_UINT32(p_result->reg_notif.param, p); @@ -108,9 +110,8 @@ static tAVRC_STS avrc_ctrl_pars_vendor_cmd(tAVRC_MSG_VENDOR* p_msg, * Otherwise, the error code defined by AVRCP 1.4 * ******************************************************************************/ -static tAVRC_STS avrc_pars_vendor_cmd(tAVRC_MSG_VENDOR* p_msg, - tAVRC_COMMAND* p_result, uint8_t* p_buf, - uint16_t buf_len) { +static tAVRC_STS avrc_pars_vendor_cmd(tAVRC_MSG_VENDOR* p_msg, tAVRC_COMMAND* p_result, + uint8_t* p_buf, uint16_t buf_len) { tAVRC_STS status = AVRC_STS_NO_ERROR; uint8_t* p; uint16_t len; @@ -122,12 +123,15 @@ static tAVRC_STS avrc_pars_vendor_cmd(tAVRC_MSG_VENDOR* p_msg, uint16_t size_needed; /* Check the vendor data */ - if (p_msg->vendor_len == 0) return AVRC_STS_NO_ERROR; - if (p_msg->p_vendor_data == NULL) return AVRC_STS_INTERNAL_ERR; + if (p_msg->vendor_len == 0) { + return AVRC_STS_NO_ERROR; + } + if (p_msg->p_vendor_data == NULL) { + return AVRC_STS_INTERNAL_ERR; + } if (p_msg->vendor_len < 4) { - log::warn("message length {} too short: must be at least 4", - p_msg->vendor_len); + log::warn("message length {} too short: must be at least 4", p_msg->vendor_len); return AVRC_STS_INTERNAL_ERR; } @@ -146,34 +150,44 @@ static tAVRC_STS avrc_pars_vendor_cmd(tAVRC_MSG_VENDOR* p_msg, status = AVRC_STS_INTERNAL_ERR; } - if (status != AVRC_STS_NO_ERROR) return status; + if (status != AVRC_STS_NO_ERROR) { + return status; + } switch (p_result->pdu) { case AVRC_PDU_GET_CAPABILITIES: /* 0x10 */ p_result->get_caps.capability_id = *p++; - if (!AVRC_IS_VALID_CAP_ID(p_result->get_caps.capability_id)) + if (!AVRC_IS_VALID_CAP_ID(p_result->get_caps.capability_id)) { status = AVRC_STS_BAD_PARAM; - else if (len != 1) + } else if (len != 1) { return AVRC_STS_INTERNAL_ERR; + } break; case AVRC_PDU_LIST_PLAYER_APP_ATTR: /* 0x11 */ /* no additional parameters */ - if (len != 0) return AVRC_STS_INTERNAL_ERR; + if (len != 0) { + return AVRC_STS_INTERNAL_ERR; + } break; case AVRC_PDU_LIST_PLAYER_APP_VALUES: /* 0x12 */ - if (len == 0) return AVRC_STS_INTERNAL_ERR; + if (len == 0) { + return AVRC_STS_INTERNAL_ERR; + } p_result->list_app_values.attr_id = *p++; - if (!AVRC_IS_VALID_ATTRIBUTE(p_result->list_app_values.attr_id)) + if (!AVRC_IS_VALID_ATTRIBUTE(p_result->list_app_values.attr_id)) { status = AVRC_STS_BAD_PARAM; - else if (len != 1) + } else if (len != 1) { status = AVRC_STS_INTERNAL_ERR; + } break; case AVRC_PDU_GET_CUR_PLAYER_APP_VALUE: /* 0x13 */ case AVRC_PDU_GET_PLAYER_APP_ATTR_TEXT: /* 0x15 */ - if (len == 0) return AVRC_STS_INTERNAL_ERR; + if (len == 0) { + return AVRC_STS_INTERNAL_ERR; + } BE_STREAM_TO_UINT8(p_result->get_cur_app_val.num_attr, p); if (len != (p_result->get_cur_app_val.num_attr + 1)) { status = AVRC_STS_INTERNAL_ERR; @@ -187,7 +201,9 @@ static tAVRC_STS avrc_pars_vendor_cmd(tAVRC_MSG_VENDOR* p_msg, p_u8 = p_result->get_cur_app_val.attrs; for (xx = 0, yy = 0; xx < p_result->get_cur_app_val.num_attr; xx++) { /* only report the valid player app attributes */ - if (AVRC_IsValidPlayerAttr(*p)) p_u8[yy++] = *p; + if (AVRC_IsValidPlayerAttr(*p)) { + p_u8[yy++] = *p; + } p++; } p_result->get_cur_app_val.num_attr = yy; @@ -197,48 +213,44 @@ static tAVRC_STS avrc_pars_vendor_cmd(tAVRC_MSG_VENDOR* p_msg, break; case AVRC_PDU_SET_PLAYER_APP_VALUE: /* 0x14 */ - if (len == 0) return AVRC_STS_INTERNAL_ERR; + if (len == 0) { + return AVRC_STS_INTERNAL_ERR; + } BE_STREAM_TO_UINT8(p_result->set_app_val.num_val, p); size_needed = sizeof(tAVRC_APP_SETTING); if (p_buf && (len == ((p_result->set_app_val.num_val << 1) + 1))) { p_result->set_app_val.p_vals = (tAVRC_APP_SETTING*)p_buf; p_app_set = p_result->set_app_val.p_vals; - for (xx = 0; - ((xx < p_result->set_app_val.num_val) && (buf_len > size_needed)); - xx++) { + for (xx = 0; ((xx < p_result->set_app_val.num_val) && (buf_len > size_needed)); xx++) { p_app_set[xx].attr_id = *p++; p_app_set[xx].attr_val = *p++; - if (!avrc_is_valid_player_attrib_value(p_app_set[xx].attr_id, - p_app_set[xx].attr_val)) + if (!avrc_is_valid_player_attrib_value(p_app_set[xx].attr_id, p_app_set[xx].attr_val)) { status = AVRC_STS_BAD_PARAM; + } } if (xx != p_result->set_app_val.num_val) { - log::error( - "AVRC_PDU_SET_PLAYER_APP_VALUE not enough room:{} orig " - "num_val:{}", - xx, p_result->set_app_val.num_val); + log::error("AVRC_PDU_SET_PLAYER_APP_VALUE not enough room:{} orig num_val:{}", xx, + p_result->set_app_val.num_val); p_result->set_app_val.num_val = xx; } } else { - log::error( - "AVRC_PDU_SET_PLAYER_APP_VALUE NULL decode buffer or bad len"); + log::error("AVRC_PDU_SET_PLAYER_APP_VALUE NULL decode buffer or bad len"); status = AVRC_STS_INTERNAL_ERR; } break; case AVRC_PDU_GET_PLAYER_APP_VALUE_TEXT: /* 0x16 */ - if (len < 3) + if (len < 3) { return AVRC_STS_INTERNAL_ERR; - else { + } else { BE_STREAM_TO_UINT8(p_result->get_app_val_txt.attr_id, p); - if (!AVRC_IS_VALID_ATTRIBUTE(p_result->get_app_val_txt.attr_id)) + if (!AVRC_IS_VALID_ATTRIBUTE(p_result->get_app_val_txt.attr_id)) { status = AVRC_STS_BAD_PARAM; - else { + } else { BE_STREAM_TO_UINT8(p_result->get_app_val_txt.num_val, p); - if ((len - 2 /* attr_id & num_val */) != - p_result->get_app_val_txt.num_val) + if ((len - 2 /* attr_id & num_val */) != p_result->get_app_val_txt.num_val) { status = AVRC_STS_INTERNAL_ERR; - else { + } else { if (p_result->get_app_val_txt.num_val > AVRC_MAX_APP_ATTR_SIZE) { p_result->get_app_val_txt.num_val = AVRC_MAX_APP_ATTR_SIZE; } @@ -246,8 +258,7 @@ static tAVRC_STS avrc_pars_vendor_cmd(tAVRC_MSG_VENDOR* p_msg, p_u8 = p_result->get_app_val_txt.vals; for (xx = 0; xx < p_result->get_app_val_txt.num_val; xx++) { p_u8[xx] = *p++; - if (!avrc_is_valid_player_attrib_value( - p_result->get_app_val_txt.attr_id, p_u8[xx])) { + if (!avrc_is_valid_player_attrib_value(p_result->get_app_val_txt.attr_id, p_u8[xx])) { status = AVRC_STS_BAD_PARAM; break; } @@ -258,16 +269,17 @@ static tAVRC_STS avrc_pars_vendor_cmd(tAVRC_MSG_VENDOR* p_msg, break; case AVRC_PDU_INFORM_DISPLAY_CHARSET: /* 0x17 */ - if (len < 3) + if (len < 3) { return AVRC_STS_INTERNAL_ERR; - else { + } else { BE_STREAM_TO_UINT8(p_result->inform_charset.num_id, p); - if ((len - 1 /* num_id */) != p_result->inform_charset.num_id * 2) + if ((len - 1 /* num_id */) != p_result->inform_charset.num_id * 2) { status = AVRC_STS_INTERNAL_ERR; - else { + } else { p_u16 = p_result->inform_charset.charsets; - if (p_result->inform_charset.num_id > AVRC_MAX_CHARSET_SIZE) + if (p_result->inform_charset.num_id > AVRC_MAX_CHARSET_SIZE) { p_result->inform_charset.num_id = AVRC_MAX_CHARSET_SIZE; + } for (xx = 0; xx < p_result->inform_charset.num_id; xx++) { BE_STREAM_TO_UINT16(p_u16[xx], p); } @@ -276,49 +288,52 @@ static tAVRC_STS avrc_pars_vendor_cmd(tAVRC_MSG_VENDOR* p_msg, break; case AVRC_PDU_INFORM_BATTERY_STAT_OF_CT: /* 0x18 */ - if (len != 1) + if (len != 1) { return AVRC_STS_INTERNAL_ERR; - else { + } else { p_result->inform_battery_status.battery_status = *p++; - if (!AVRC_IS_VALID_BATTERY_STATUS( - p_result->inform_battery_status.battery_status)) + if (!AVRC_IS_VALID_BATTERY_STATUS(p_result->inform_battery_status.battery_status)) { status = AVRC_STS_BAD_PARAM; + } } break; case AVRC_PDU_GET_ELEMENT_ATTR: /* 0x20 */ - if (len < 9) /* UID/8 and num_attr/1 */ + if (len < 9) { /* UID/8 and num_attr/1 */ return AVRC_STS_INTERNAL_ERR; - else { + } else { BE_STREAM_TO_UINT32(u32, p); BE_STREAM_TO_UINT32(u32_2, p); if (u32 == 0 && u32_2 == 0) { BE_STREAM_TO_UINT8(p_result->get_elem_attrs.num_attr, p); - if ((len - 9 /* UID/8 and num_attr/1 */) != - (p_result->get_elem_attrs.num_attr * 4)) + if ((len - 9 /* UID/8 and num_attr/1 */) != (p_result->get_elem_attrs.num_attr * 4)) { status = AVRC_STS_INTERNAL_ERR; - else { + } else { p_u32 = p_result->get_elem_attrs.attrs; - if (p_result->get_elem_attrs.num_attr > AVRC_MAX_ELEM_ATTR_SIZE) + if (p_result->get_elem_attrs.num_attr > AVRC_MAX_ELEM_ATTR_SIZE) { p_result->get_elem_attrs.num_attr = AVRC_MAX_ELEM_ATTR_SIZE; + } for (xx = 0; xx < p_result->get_elem_attrs.num_attr; xx++) { BE_STREAM_TO_UINT32(p_u32[xx], p); } } - } else + } else { status = AVRC_STS_NOT_FOUND; + } } break; case AVRC_PDU_GET_PLAY_STATUS: /* 0x30 */ /* no additional parameters */ - if (len != 0) return AVRC_STS_INTERNAL_ERR; + if (len != 0) { + return AVRC_STS_INTERNAL_ERR; + } break; case AVRC_PDU_REGISTER_NOTIFICATION: /* 0x31 */ - if (len != 5) + if (len != 5) { return AVRC_STS_INTERNAL_ERR; - else { + } else { BE_STREAM_TO_UINT8(p_result->reg_notif.event_id, p); if (!AVRC_IS_VALID_EVENT_ID(p_result->reg_notif.event_id)) { log::error("Invalid event id: {}", p_result->reg_notif.event_id); @@ -330,10 +345,11 @@ static tAVRC_STS avrc_pars_vendor_cmd(tAVRC_MSG_VENDOR* p_msg, break; case AVRC_PDU_SET_ABSOLUTE_VOLUME: /* 0x50 */ - if (len != 1) + if (len != 1) { return AVRC_STS_INTERNAL_ERR; - else + } else { p_result->volume.volume = *p++; + } break; case AVRC_PDU_REQUEST_CONTINUATION_RSP: /* 0x40 */ @@ -360,7 +376,9 @@ static tAVRC_STS avrc_pars_vendor_cmd(tAVRC_MSG_VENDOR* p_msg, case AVRC_PDU_PLAY_ITEM: /* 0x74 */ case AVRC_PDU_ADD_TO_NOW_PLAYING: /* 0x90 */ - if (len != (AVRC_UID_SIZE + 3)) return AVRC_STS_INTERNAL_ERR; + if (len != (AVRC_UID_SIZE + 3)) { + return AVRC_STS_INTERNAL_ERR; + } BE_STREAM_TO_UINT8(p_result->play_item.scope, p); if (p_result->play_item.scope > AVRC_SCOPE_NOW_PLAYING) { status = AVRC_STS_BAD_SCOPE; @@ -428,16 +446,14 @@ tAVRC_STS AVRC_Ctrl_ParsCommand(tAVRC_MSG* p_msg, tAVRC_COMMAND* p_result) { * Otherwise, the error code defined by AVRCP+1 * ******************************************************************************/ -static tAVRC_STS avrc_pars_browsing_cmd(tAVRC_MSG_BROWSE* p_msg, - tAVRC_COMMAND* p_result, uint8_t* p_buf, - uint16_t buf_len) { +static tAVRC_STS avrc_pars_browsing_cmd(tAVRC_MSG_BROWSE* p_msg, tAVRC_COMMAND* p_result, + uint8_t* p_buf, uint16_t buf_len) { tAVRC_STS status = AVRC_STS_NO_ERROR; uint8_t* p = p_msg->p_browse_data; int count; uint32_t min_len = 3; - RETURN_STATUS_IF_FALSE(AVRC_STS_BAD_CMD, (p_msg->browse_len >= min_len), - "msg too short"); + RETURN_STATUS_IF_FALSE(AVRC_STS_BAD_CMD, (p_msg->browse_len >= min_len), "msg too short"); p_result->pdu = *p++; log::verbose("avrc_pars_browsing_cmd() pdu:0x{:x}", p_result->pdu); @@ -447,8 +463,7 @@ static tAVRC_STS avrc_pars_browsing_cmd(tAVRC_MSG_BROWSE* p_msg, switch (p_result->pdu) { case AVRC_PDU_SET_BROWSED_PLAYER: /* 0x70 */ min_len += 2; - RETURN_STATUS_IF_FALSE(AVRC_STS_BAD_CMD, (p_msg->browse_len >= min_len), - "msg too short"); + RETURN_STATUS_IF_FALSE(AVRC_STS_BAD_CMD, (p_msg->browse_len >= min_len), "msg too short"); // For current implementation all players are browsable. BE_STREAM_TO_UINT16(p_result->br_player.player_id, p); @@ -457,8 +472,7 @@ static tAVRC_STS avrc_pars_browsing_cmd(tAVRC_MSG_BROWSE* p_msg, case AVRC_PDU_GET_FOLDER_ITEMS: /* 0x71 */ min_len += 10; - RETURN_STATUS_IF_FALSE(AVRC_STS_BAD_CMD, (p_msg->browse_len >= min_len), - "msg too short"); + RETURN_STATUS_IF_FALSE(AVRC_STS_BAD_CMD, (p_msg->browse_len >= min_len), "msg too short"); STREAM_TO_UINT8(p_result->get_items.scope, p); // To be modified later here (Scope) when all browsing commands are @@ -477,13 +491,12 @@ static tAVRC_STS avrc_pars_browsing_cmd(tAVRC_MSG_BROWSE* p_msg, (p_result->get_items.attr_count != AVRC_FOLDER_ITEM_COUNT_NONE)) { p_result->get_items.p_attr_list = (uint32_t*)p_buf; count = p_result->get_items.attr_count; - if (buf_len < (count << 2)) + if (buf_len < (count << 2)) { p_result->get_items.attr_count = count = (buf_len >> 2); + } for (int idx = 0; idx < count; idx++) { min_len += 4; - RETURN_STATUS_IF_FALSE(AVRC_STS_BAD_CMD, - (p_msg->browse_len >= min_len), - "msg too short"); + RETURN_STATUS_IF_FALSE(AVRC_STS_BAD_CMD, (p_msg->browse_len >= min_len), "msg too short"); BE_STREAM_TO_UINT32(p_result->get_items.p_attr_list[idx], p); } @@ -492,8 +505,7 @@ static tAVRC_STS avrc_pars_browsing_cmd(tAVRC_MSG_BROWSE* p_msg, case AVRC_PDU_CHANGE_PATH: /* 0x72 */ min_len += 11; - RETURN_STATUS_IF_FALSE(AVRC_STS_BAD_CMD, (p_msg->browse_len >= min_len), - "msg too short"); + RETURN_STATUS_IF_FALSE(AVRC_STS_BAD_CMD, (p_msg->browse_len >= min_len), "msg too short"); BE_STREAM_TO_UINT16(p_result->chg_path.uid_counter, p); BE_STREAM_TO_UINT8(p_result->chg_path.direction, p); @@ -506,8 +518,7 @@ static tAVRC_STS avrc_pars_browsing_cmd(tAVRC_MSG_BROWSE* p_msg, case AVRC_PDU_GET_ITEM_ATTRIBUTES: /* 0x73 */ min_len += 12; - RETURN_STATUS_IF_FALSE(AVRC_STS_BAD_CMD, (p_msg->browse_len >= min_len), - "msg too short"); + RETURN_STATUS_IF_FALSE(AVRC_STS_BAD_CMD, (p_msg->browse_len >= min_len), "msg too short"); BE_STREAM_TO_UINT8(p_result->get_attrs.scope, p); @@ -522,33 +533,30 @@ static tAVRC_STS avrc_pars_browsing_cmd(tAVRC_MSG_BROWSE* p_msg, if (p_result->get_attrs.attr_count && p_buf) { p_result->get_attrs.p_attr_list = (uint32_t*)p_buf; count = p_result->get_attrs.attr_count; - if (buf_len < (count << 2)) + if (buf_len < (count << 2)) { p_result->get_attrs.attr_count = count = (buf_len >> 2); - for (int idx = 0, count = 0; idx < p_result->get_attrs.attr_count; - idx++) { + } + for (int idx = 0, count = 0; idx < p_result->get_attrs.attr_count; idx++) { min_len += 4; - RETURN_STATUS_IF_FALSE(AVRC_STS_BAD_CMD, - (p_msg->browse_len >= min_len), - "msg too short"); + RETURN_STATUS_IF_FALSE(AVRC_STS_BAD_CMD, (p_msg->browse_len >= min_len), "msg too short"); BE_STREAM_TO_UINT32(p_result->get_attrs.p_attr_list[count], p); - if (AVRC_IS_VALID_MEDIA_ATTRIBUTE( - p_result->get_attrs.p_attr_list[count])) { + if (AVRC_IS_VALID_MEDIA_ATTRIBUTE(p_result->get_attrs.p_attr_list[count])) { count++; } } - if (p_result->get_attrs.attr_count != count && count == 0) + if (p_result->get_attrs.attr_count != count && count == 0) { status = AVRC_STS_BAD_PARAM; - else + } else { p_result->get_attrs.attr_count = count; + } } break; case AVRC_PDU_GET_TOTAL_NUM_OF_ITEMS: /* 0x75 */ ++min_len; - RETURN_STATUS_IF_FALSE(AVRC_STS_BAD_CMD, (p_msg->browse_len >= min_len), - "msg too short"); + RETURN_STATUS_IF_FALSE(AVRC_STS_BAD_CMD, (p_msg->browse_len >= min_len), "msg too short"); BE_STREAM_TO_UINT8(p_result->get_num_of_items.scope, p); if (p_result->get_num_of_items.scope > AVRC_SCOPE_NOW_PLAYING) { @@ -558,8 +566,7 @@ static tAVRC_STS avrc_pars_browsing_cmd(tAVRC_MSG_BROWSE* p_msg, case AVRC_PDU_SEARCH: /* 0x80 */ min_len += 4; - RETURN_STATUS_IF_FALSE(AVRC_STS_BAD_CMD, (p_msg->browse_len >= min_len), - "msg too short"); + RETURN_STATUS_IF_FALSE(AVRC_STS_BAD_CMD, (p_msg->browse_len >= min_len), "msg too short"); BE_STREAM_TO_UINT16(p_result->search.string.charset_id, p); BE_STREAM_TO_UINT16(p_result->search.string.str_len, p); @@ -569,8 +576,7 @@ static tAVRC_STS avrc_pars_browsing_cmd(tAVRC_MSG_BROWSE* p_msg, p_result->search.string.str_len = buf_len; } min_len += p_result->search.string.str_len; - RETURN_STATUS_IF_FALSE(AVRC_STS_BAD_CMD, (p_msg->browse_len >= min_len), - "msg too short"); + RETURN_STATUS_IF_FALSE(AVRC_STS_BAD_CMD, (p_msg->browse_len >= min_len), "msg too short"); BE_STREAM_TO_ARRAY(p, p_buf, p_result->search.string.str_len); } else { @@ -597,8 +603,8 @@ static tAVRC_STS avrc_pars_browsing_cmd(tAVRC_MSG_BROWSE* p_msg, * Otherwise, the error code defined by AVRCP 1.4 * ******************************************************************************/ -tAVRC_STS AVRC_ParsCommand(tAVRC_MSG* p_msg, tAVRC_COMMAND* p_result, - uint8_t* p_buf, uint16_t buf_len) { +tAVRC_STS AVRC_ParsCommand(tAVRC_MSG* p_msg, tAVRC_COMMAND* p_result, uint8_t* p_buf, + uint16_t buf_len) { tAVRC_STS status = AVRC_STS_INTERNAL_ERR; uint16_t id; @@ -616,8 +622,7 @@ tAVRC_STS AVRC_ParsCommand(tAVRC_MSG* p_msg, tAVRC_COMMAND* p_result, break; case AVRC_OP_BROWSE: - status = - avrc_pars_browsing_cmd(&p_msg->browse, p_result, p_buf, buf_len); + status = avrc_pars_browsing_cmd(&p_msg->browse, p_result, p_buf, buf_len); break; default: diff --git a/system/stack/avrc/avrc_sdp.cc b/system/stack/avrc/avrc_sdp.cc index 1f6c2e8ac4f..d412a672adf 100644 --- a/system/stack/avrc/avrc_sdp.cc +++ b/system/stack/avrc/avrc_sdp.cc @@ -46,10 +46,9 @@ using bluetooth::Uuid; ****************************************************************************/ tAVRC_CB avrc_cb; static uint16_t a2dp_attr_list_sdp[] = { - ATTR_ID_SERVICE_CLASS_ID_LIST, /* update A2DP_NUM_ATTR, if changed */ - ATTR_ID_BT_PROFILE_DESC_LIST, ATTR_ID_SUPPORTED_FEATURES, - ATTR_ID_SERVICE_NAME, ATTR_ID_PROTOCOL_DESC_LIST, - ATTR_ID_PROVIDER_NAME}; + ATTR_ID_SERVICE_CLASS_ID_LIST, /* update A2DP_NUM_ATTR, if changed */ + ATTR_ID_BT_PROFILE_DESC_LIST, ATTR_ID_SUPPORTED_FEATURES, ATTR_ID_SERVICE_NAME, + ATTR_ID_PROTOCOL_DESC_LIST, ATTR_ID_PROVIDER_NAME}; /****************************************************************************** * @@ -66,8 +65,7 @@ static uint16_t a2dp_attr_list_sdp[] = { * Returns Nothing. * *****************************************************************************/ -static void avrc_sdp_cback(const RawAddress& /* bd_addr */, - tSDP_STATUS status) { +static void avrc_sdp_cback(const RawAddress& /* bd_addr */, tSDP_STATUS status) { log::verbose("status: {}", status); /* reset service_uuid, so can start another find service */ @@ -119,21 +117,21 @@ static void avrc_sdp_cback(const RawAddress& /* bd_addr */, * *****************************************************************************/ uint16_t AVRC_FindService(uint16_t service_uuid, const RawAddress& bd_addr, - tAVRC_SDP_DB_PARAMS* p_db, - const tAVRC_FIND_CBACK& find_cback) { + tAVRC_SDP_DB_PARAMS* p_db, const tAVRC_FIND_CBACK& find_cback) { bool result = true; log::verbose("uuid: {:x}", service_uuid); if ((service_uuid != UUID_SERVCLASS_AV_REM_CTRL_TARGET && service_uuid != UUID_SERVCLASS_AV_REMOTE_CONTROL) || - p_db == NULL || p_db->p_db == NULL || find_cback.is_null()) + p_db == NULL || p_db->p_db == NULL || find_cback.is_null()) { return AVRC_BAD_PARAM; + } /* check if it is busy */ if (avrc_cb.service_uuid == UUID_SERVCLASS_AV_REM_CTRL_TARGET || - avrc_cb.service_uuid == UUID_SERVCLASS_AV_REMOTE_CONTROL) + avrc_cb.service_uuid == UUID_SERVCLASS_AV_REMOTE_CONTROL) { return AVRC_NO_RESOURCES; - + } if (p_db->p_attrs == NULL || p_db->num_attr == 0) { p_db->p_attrs = a2dp_attr_list_sdp; @@ -142,7 +140,7 @@ uint16_t AVRC_FindService(uint16_t service_uuid, const RawAddress& bd_addr, Uuid uuid_list = Uuid::From16Bit(service_uuid); result = get_legacy_stack_sdp_api()->service.SDP_InitDiscoveryDb( - p_db->p_db, p_db->db_len, 1, &uuid_list, p_db->num_attr, p_db->p_attrs); + p_db->p_db, p_db->db_len, 1, &uuid_list, p_db->num_attr, p_db->p_attrs); if (result) { /* store service_uuid and discovery db pointer */ @@ -151,8 +149,7 @@ uint16_t AVRC_FindService(uint16_t service_uuid, const RawAddress& bd_addr, avrc_cb.find_cback = find_cback; /* perform service search */ - result = - get_legacy_stack_sdp_api()->service.SDP_ServiceSearchAttributeRequest( + result = get_legacy_stack_sdp_api()->service.SDP_ServiceSearchAttributeRequest( bd_addr, p_db->p_db, avrc_sdp_cback); if (!result) { @@ -161,7 +158,7 @@ uint16_t AVRC_FindService(uint16_t service_uuid, const RawAddress& bd_addr, } } - return (result ? AVRC_SUCCESS : AVRC_FAIL); + return result ? AVRC_SUCCESS : AVRC_FAIL; } /****************************************************************************** @@ -207,9 +204,8 @@ uint16_t AVRC_FindService(uint16_t service_uuid, const RawAddress& bd_addr, * *****************************************************************************/ uint16_t AVRC_AddRecord(uint16_t service_uuid, const char* p_service_name, - const char* p_provider_name, uint16_t categories, - uint32_t sdp_handle, bool browse_supported, - uint16_t profile_version, uint16_t cover_art_psm) { + const char* p_provider_name, uint16_t categories, uint32_t sdp_handle, + bool browse_supported, uint16_t profile_version, uint16_t cover_art_psm) { uint16_t browse_list[1]; bool result = true; uint8_t temp[8]; @@ -219,23 +215,23 @@ uint16_t AVRC_AddRecord(uint16_t service_uuid, const char* p_service_name, uint16_t class_list[2]; log::verbose( - "Add AVRCP SDP record, uuid: {:x}, profile_version: 0x{:x}, " - "supported_features: 0x{:x}, psm: 0x{:x}", - service_uuid, profile_version, categories, cover_art_psm); + "Add AVRCP SDP record, uuid: {:x}, profile_version: 0x{:x}, " + "supported_features: 0x{:x}, psm: 0x{:x}", + service_uuid, profile_version, categories, cover_art_psm); if (service_uuid != UUID_SERVCLASS_AV_REM_CTRL_TARGET && - service_uuid != UUID_SERVCLASS_AV_REMOTE_CONTROL) + service_uuid != UUID_SERVCLASS_AV_REMOTE_CONTROL) { return AVRC_BAD_PARAM; + } /* add service class id list */ class_list[0] = service_uuid; - if ((service_uuid == UUID_SERVCLASS_AV_REMOTE_CONTROL) && - (profile_version > AVRC_REV_1_3)) { + if ((service_uuid == UUID_SERVCLASS_AV_REMOTE_CONTROL) && (profile_version > AVRC_REV_1_3)) { class_list[1] = UUID_SERVCLASS_AV_REM_CTRL_CONTROL; count = 2; } - result &= get_legacy_stack_sdp_api()->handle.SDP_AddServiceClassIdList( - sdp_handle, count, class_list); + result &= get_legacy_stack_sdp_api()->handle.SDP_AddServiceClassIdList(sdp_handle, count, + class_list); uint16_t protocol_reported_version; /* AVRCP versions 1.3 to 1.5 report (version - 1) in the protocol @@ -259,8 +255,8 @@ uint16_t AVRC_AddRecord(uint16_t service_uuid, const char* p_service_name, avrc_proto_desc_list[index].params[0] = protocol_reported_version; avrc_proto_desc_list[index].params[1] = 0; } - result &= get_legacy_stack_sdp_api()->handle.SDP_AddProtocolList( - sdp_handle, AVRC_NUM_PROTO_ELEMS, &avrc_proto_desc_list[0]); + result &= get_legacy_stack_sdp_api()->handle.SDP_AddProtocolList(sdp_handle, AVRC_NUM_PROTO_ELEMS, + &avrc_proto_desc_list[0]); /* additional protocal descriptor, required only for version > 1.3 */ if (profile_version > AVRC_REV_1_3) { @@ -274,80 +270,72 @@ uint16_t AVRC_AddRecord(uint16_t service_uuid, const char* p_service_name, num_additional_protocols++; avrc_add_proto_desc_lists[i].num_elems = 2; avrc_add_proto_desc_lists[i].list_elem[0].num_params = 1; - avrc_add_proto_desc_lists[i].list_elem[0].protocol_uuid = - UUID_PROTOCOL_L2CAP; + avrc_add_proto_desc_lists[i].list_elem[0].protocol_uuid = UUID_PROTOCOL_L2CAP; avrc_add_proto_desc_lists[i].list_elem[0].params[0] = AVCT_BR_PSM; avrc_add_proto_desc_lists[i].list_elem[0].params[1] = 0; avrc_add_proto_desc_lists[i].list_elem[1].num_params = 1; - avrc_add_proto_desc_lists[i].list_elem[1].protocol_uuid = - UUID_PROTOCOL_AVCTP; - avrc_add_proto_desc_lists[i].list_elem[1].params[0] = - protocol_reported_version; + avrc_add_proto_desc_lists[i].list_elem[1].protocol_uuid = UUID_PROTOCOL_AVCTP; + avrc_add_proto_desc_lists[i].list_elem[1].params[0] = protocol_reported_version; avrc_add_proto_desc_lists[i].list_elem[1].params[1] = 0; i++; } /* Add the BIP PSM for cover art on 1.6+ target devices that support it */ - if (profile_version >= AVRC_REV_1_6 && - service_uuid == UUID_SERVCLASS_AV_REM_CTRL_TARGET && + if (profile_version >= AVRC_REV_1_6 && service_uuid == UUID_SERVCLASS_AV_REM_CTRL_TARGET && cover_art_psm > 0) { log::verbose( - "Add AVRCP BIP PSM to additional protocol descriptor lists, psm: " - "0x{:x}", - cover_art_psm); + "Add AVRCP BIP PSM to additional protocol descriptor lists, psm: " + "0x{:x}", + cover_art_psm); num_additional_protocols++; avrc_add_proto_desc_lists[i].num_elems = 2; avrc_add_proto_desc_lists[i].list_elem[0].num_params = 1; - avrc_add_proto_desc_lists[i].list_elem[0].protocol_uuid = - UUID_PROTOCOL_L2CAP; + avrc_add_proto_desc_lists[i].list_elem[0].protocol_uuid = UUID_PROTOCOL_L2CAP; avrc_add_proto_desc_lists[i].list_elem[0].params[0] = cover_art_psm; avrc_add_proto_desc_lists[i].list_elem[0].params[1] = 0; avrc_add_proto_desc_lists[i].list_elem[1].num_params = 0; - avrc_add_proto_desc_lists[i].list_elem[1].protocol_uuid = - UUID_PROTOCOL_OBEX; + avrc_add_proto_desc_lists[i].list_elem[1].protocol_uuid = UUID_PROTOCOL_OBEX; avrc_add_proto_desc_lists[i].list_elem[1].params[0] = 0; i++; } /* Add the additional lists if we support any */ if (num_additional_protocols > 0) { - log::verbose("Add {} additional protocol descriptor lists", - num_additional_protocols); + log::verbose("Add {} additional protocol descriptor lists", num_additional_protocols); result &= get_legacy_stack_sdp_api()->handle.SDP_AddAdditionProtoLists( - sdp_handle, num_additional_protocols, avrc_add_proto_desc_lists); + sdp_handle, num_additional_protocols, avrc_add_proto_desc_lists); } } /* add profile descriptor list */ result &= get_legacy_stack_sdp_api()->handle.SDP_AddProfileDescriptorList( - sdp_handle, UUID_SERVCLASS_AV_REMOTE_CONTROL, profile_version); + sdp_handle, UUID_SERVCLASS_AV_REMOTE_CONTROL, profile_version); /* add supported categories */ p = temp; UINT16_TO_BE_STREAM(p, categories); result &= get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - sdp_handle, ATTR_ID_SUPPORTED_FEATURES, UINT_DESC_TYPE, (uint32_t)2, - (uint8_t*)temp); + sdp_handle, ATTR_ID_SUPPORTED_FEATURES, UINT_DESC_TYPE, (uint32_t)2, (uint8_t*)temp); /* add provider name */ if (p_provider_name != NULL) { result &= get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - sdp_handle, ATTR_ID_PROVIDER_NAME, TEXT_STR_DESC_TYPE, - (uint32_t)(strlen(p_provider_name) + 1), (uint8_t*)p_provider_name); + sdp_handle, ATTR_ID_PROVIDER_NAME, TEXT_STR_DESC_TYPE, + (uint32_t)(strlen(p_provider_name) + 1), (uint8_t*)p_provider_name); } /* add service name */ if (p_service_name != NULL) { result &= get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - sdp_handle, ATTR_ID_SERVICE_NAME, TEXT_STR_DESC_TYPE, - (uint32_t)(strlen(p_service_name) + 1), (uint8_t*)p_service_name); + sdp_handle, ATTR_ID_SERVICE_NAME, TEXT_STR_DESC_TYPE, + (uint32_t)(strlen(p_service_name) + 1), (uint8_t*)p_service_name); } /* add browse group list */ browse_list[0] = UUID_SERVCLASS_PUBLIC_BROWSE_GROUP; result &= get_legacy_stack_sdp_api()->handle.SDP_AddUuidSequence( - sdp_handle, ATTR_ID_BROWSE_GROUP_LIST, 1, browse_list); + sdp_handle, ATTR_ID_BROWSE_GROUP_LIST, 1, browse_list); - return (result ? AVRC_SUCCESS : AVRC_FAIL); + return result ? AVRC_SUCCESS : AVRC_FAIL; } /******************************************************************************* @@ -366,7 +354,7 @@ uint16_t AVRC_AddRecord(uint16_t service_uuid, const char* p_service_name, uint16_t AVRC_RemoveRecord(uint32_t sdp_handle) { log::verbose("remove AVRCP SDP record"); bool result = get_legacy_stack_sdp_api()->handle.SDP_DeleteRecord(sdp_handle); - return (result ? AVRC_SUCCESS : AVRC_FAIL); + return result ? AVRC_SUCCESS : AVRC_FAIL; } /******************************************************************************* @@ -380,6 +368,4 @@ uint16_t AVRC_RemoveRecord(uint32_t sdp_handle) { * Returns void * ******************************************************************************/ -void AVRC_Init(void) { - memset(&avrc_cb, 0, sizeof(tAVRC_CB)); -} +void AVRC_Init(void) { memset(&avrc_cb, 0, sizeof(tAVRC_CB)); } diff --git a/system/stack/avrc/avrc_utils.cc b/system/stack/avrc/avrc_utils.cc index ccba3e19334..cf2d428385b 100644 --- a/system/stack/avrc/avrc_utils.cc +++ b/system/stack/avrc/avrc_utils.cc @@ -51,7 +51,9 @@ bool AVRC_IsValidAvcType(uint8_t pdu_id, uint8_t avc_type) { case AVRC_PDU_GET_PLAYER_APP_VALUE_TEXT: /* 0x16 */ case AVRC_PDU_GET_ELEMENT_ATTR: /* 0x20 */ case AVRC_PDU_GET_PLAY_STATUS: /* 0x30 */ - if (avc_type == AVRC_CMD_STATUS) result = true; + if (avc_type == AVRC_CMD_STATUS) { + result = true; + } break; case AVRC_PDU_SET_PLAYER_APP_VALUE: /* 0x14 */ @@ -59,7 +61,9 @@ bool AVRC_IsValidAvcType(uint8_t pdu_id, uint8_t avc_type) { case AVRC_PDU_INFORM_BATTERY_STAT_OF_CT: /* 0x18 */ case AVRC_PDU_REQUEST_CONTINUATION_RSP: /* 0x40 */ case AVRC_PDU_ABORT_CONTINUATION_RSP: /* 0x41 */ - if (avc_type == AVRC_CMD_CTRL) result = true; + if (avc_type == AVRC_CMD_CTRL) { + result = true; + } break; case AVRC_PDU_GET_FOLDER_ITEMS: /* 0x71 */ @@ -70,17 +74,22 @@ bool AVRC_IsValidAvcType(uint8_t pdu_id, uint8_t avc_type) { case AVRC_PDU_SET_ADDRESSED_PLAYER: /* 0x60 */ case AVRC_PDU_PLAY_ITEM: /* 0x74 */ case AVRC_PDU_ADD_TO_NOW_PLAYING: /* 0x90 */ - if (avc_type == AVRC_CMD_CTRL) result = true; + if (avc_type == AVRC_CMD_CTRL) { + result = true; + } break; case AVRC_PDU_REGISTER_NOTIFICATION: /* 0x31 */ - if (avc_type == AVRC_CMD_NOTIF) result = true; + if (avc_type == AVRC_CMD_NOTIF) { + result = true; + } break; } } else /* response msg */ { - if (avc_type >= AVRC_RSP_NOT_IMPL && avc_type <= AVRC_RSP_INTERIM) + if (avc_type >= AVRC_RSP_NOT_IMPL && avc_type <= AVRC_RSP_INTERIM) { result = true; + } } return result; @@ -100,25 +109,31 @@ bool avrc_is_valid_player_attrib_value(uint8_t attrib, uint8_t value) { switch (attrib) { case AVRC_PLAYER_SETTING_EQUALIZER: - if ((value > 0) && (value <= AVRC_PLAYER_VAL_ON)) result = true; + if ((value > 0) && (value <= AVRC_PLAYER_VAL_ON)) { + result = true; + } break; case AVRC_PLAYER_SETTING_REPEAT: - if ((value > 0) && (value <= AVRC_PLAYER_VAL_GROUP_REPEAT)) result = true; + if ((value > 0) && (value <= AVRC_PLAYER_VAL_GROUP_REPEAT)) { + result = true; + } break; case AVRC_PLAYER_SETTING_SHUFFLE: case AVRC_PLAYER_SETTING_SCAN: - if ((value > 0) && (value <= AVRC_PLAYER_VAL_GROUP_SHUFFLE)) + if ((value > 0) && (value <= AVRC_PLAYER_VAL_GROUP_SHUFFLE)) { result = true; + } break; } - if (attrib >= AVRC_PLAYER_SETTING_LOW_MENU_EXT) result = true; + if (attrib >= AVRC_PLAYER_SETTING_LOW_MENU_EXT) { + result = true; + } if (!result) { - log::error("found not matching attrib(x{:x})-value(x{:x}) pair!", attrib, - value); + log::error("found not matching attrib(x{:x})-value(x{:x}) pair!", attrib, value); } return result; } @@ -135,8 +150,7 @@ bool avrc_is_valid_player_attrib_value(uint8_t attrib, uint8_t value) { bool AVRC_IsValidPlayerAttr(uint8_t attr) { bool result = false; - if ((attr >= AVRC_PLAYER_SETTING_EQUALIZER && - attr <= AVRC_PLAYER_SETTING_SCAN) || + if ((attr >= AVRC_PLAYER_SETTING_EQUALIZER && attr <= AVRC_PLAYER_SETTING_SCAN) || (attr >= AVRC_PLAYER_SETTING_LOW_MENU_EXT)) { result = true; } @@ -156,15 +170,13 @@ bool AVRC_IsValidPlayerAttr(uint8_t attr) { * Otherwise, the error code defined by AVRCP 1.4 * ******************************************************************************/ -tAVRC_STS avrc_pars_pass_thru(tAVRC_MSG_PASS* p_msg, - uint16_t* p_vendor_unique_id) { +tAVRC_STS avrc_pars_pass_thru(tAVRC_MSG_PASS* p_msg, uint16_t* p_vendor_unique_id) { uint8_t* p_data; uint32_t co_id; uint16_t id; tAVRC_STS status = AVRC_STS_BAD_CMD; - if (p_msg->op_id == AVRC_ID_VENDOR && - p_msg->pass_len == AVRC_PASS_THRU_GROUP_LEN) { + if (p_msg->op_id == AVRC_ID_VENDOR && p_msg->pass_len == AVRC_PASS_THRU_GROUP_LEN) { p_data = p_msg->p_pass_data; AVRC_BE_STREAM_TO_CO_ID(co_id, p_data); if (co_id == AVRC_CO_METADATA) { diff --git a/system/stack/bnep/bnep_api.cc b/system/stack/bnep/bnep_api.cc index fda4fd7d27c..af5196f2699 100644 --- a/system/stack/bnep/bnep_api.cc +++ b/system/stack/bnep/bnep_api.cc @@ -51,9 +51,7 @@ using bluetooth::Uuid; * Returns void * ******************************************************************************/ -void BNEP_Init(void) { - memset(&bnep_cb, 0, sizeof(tBNEP_CB)); -} +void BNEP_Init(void) { memset(&bnep_cb, 0, sizeof(tBNEP_CB)); } /******************************************************************************* * @@ -71,8 +69,9 @@ void BNEP_Init(void) { ******************************************************************************/ tBNEP_RESULT BNEP_Register(tBNEP_REGISTER* p_reg_info) { /* There should be connection state call back registered */ - if ((!p_reg_info) || (!(p_reg_info->p_conn_state_cb))) + if ((!p_reg_info) || (!(p_reg_info->p_conn_state_cb))) { return BNEP_SECURITY_FAIL; + } bnep_cb.p_conn_ind_cb = p_reg_info->p_conn_ind_cb; bnep_cb.p_conn_state_cb = p_reg_info->p_conn_state_cb; @@ -82,7 +81,9 @@ tBNEP_RESULT BNEP_Register(tBNEP_REGISTER* p_reg_info) { bnep_cb.p_mfilter_ind_cb = p_reg_info->p_mfilter_ind_cb; bnep_cb.p_tx_data_flow_cb = p_reg_info->p_tx_data_flow_cb; - if (bnep_register_with_l2cap()) return BNEP_SECURITY_FAIL; + if (bnep_register_with_l2cap()) { + return BNEP_SECURITY_FAIL; + } bnep_cb.profile_registered = true; return BNEP_SUCCESS; @@ -131,22 +132,25 @@ void BNEP_Deregister(void) { * BNEP_NO_RESOURCES if no resources * ******************************************************************************/ -tBNEP_RESULT BNEP_Connect(const RawAddress& p_rem_bda, const Uuid& src_uuid, - const Uuid& dst_uuid, uint16_t* p_handle, - uint32_t mx_chan_id) { +tBNEP_RESULT BNEP_Connect(const RawAddress& p_rem_bda, const Uuid& src_uuid, const Uuid& dst_uuid, + uint16_t* p_handle, uint32_t mx_chan_id) { uint16_t cid; tBNEP_CONN* p_bcb = bnepu_find_bcb_by_bd_addr(p_rem_bda); log::verbose("BDA:{}", p_rem_bda); - if (!bnep_cb.profile_registered) return BNEP_WRONG_STATE; + if (!bnep_cb.profile_registered) { + return BNEP_WRONG_STATE; + } if (!p_bcb) { p_bcb = bnepu_allocate_bcb(p_rem_bda); - if (p_bcb == NULL) return (BNEP_NO_RESOURCES); - } else if (p_bcb->con_state != BNEP_STATE_CONNECTED) + if (p_bcb == NULL) { + return BNEP_NO_RESOURCES; + } + } else if (p_bcb->con_state != BNEP_STATE_CONNECTED) { return BNEP_WRONG_STATE; - else { + } else { /* Backup current UUID values to restore if role change fails */ p_bcb->prv_src_uuid = p_bcb->src_uuid; p_bcb->prv_dst_uuid = p_bcb->dst_uuid; @@ -163,8 +167,7 @@ tBNEP_RESULT BNEP_Connect(const RawAddress& p_rem_bda, const Uuid& src_uuid, */ p_bcb->con_state = BNEP_STATE_SEC_CHECKING; - log::verbose("BNEP initiating security procedures for src uuid {}", - p_bcb->src_uuid.ToString()); + log::verbose("BNEP initiating security procedures for src uuid {}", p_bcb->src_uuid.ToString()); bnep_sec_check_complete(&p_bcb->rem_bda, BT_TRANSPORT_BR_EDR, p_bcb); } else { @@ -179,69 +182,71 @@ tBNEP_RESULT BNEP_Connect(const RawAddress& p_rem_bda, const Uuid& src_uuid, } else { log::error("BNEP - Originate failed"); - if (bnep_cb.p_conn_state_cb) - (*bnep_cb.p_conn_state_cb)(p_bcb->handle, p_bcb->rem_bda, - BNEP_CONN_FAILED, false); + if (bnep_cb.p_conn_state_cb) { + (*bnep_cb.p_conn_state_cb)(p_bcb->handle, p_bcb->rem_bda, BNEP_CONN_FAILED, false); + } bnepu_release_bcb(p_bcb); return BNEP_CONN_FAILED; } /* Start timer waiting for connect */ - alarm_set_on_mloop(p_bcb->conn_timer, BNEP_CONN_TIMEOUT_MS, - bnep_conn_timer_timeout, p_bcb); + alarm_set_on_mloop(p_bcb->conn_timer, BNEP_CONN_TIMEOUT_MS, bnep_conn_timer_timeout, p_bcb); } *p_handle = p_bcb->handle; - return (BNEP_SUCCESS); + return BNEP_SUCCESS; } /******************************************************************************* * * Function BNEP_ConnectResp * - * Description This function is called in responce to connection indication + * Description This function is called in response to connection indication * * * Parameters: handle - handle given in the connection indication - * resp - responce for the connection indication + * resp - response for the connection indication * * Returns BNEP_SUCCESS if connection started * BNEP_WRONG_HANDLE if the connection is not found - * BNEP_WRONG_STATE if the responce is not expected + * BNEP_WRONG_STATE if the response is not expected * ******************************************************************************/ tBNEP_RESULT BNEP_ConnectResp(uint16_t handle, tBNEP_RESULT resp) { tBNEP_CONN* p_bcb; uint16_t resp_code = BNEP_SETUP_CONN_OK; - if ((!handle) || (handle > BNEP_MAX_CONNECTIONS)) return (BNEP_WRONG_HANDLE); + if ((!handle) || (handle > BNEP_MAX_CONNECTIONS)) { + return BNEP_WRONG_HANDLE; + } p_bcb = &(bnep_cb.bcb[handle - 1]); - if (p_bcb->con_state != BNEP_STATE_CONN_SETUP || - (!(p_bcb->con_flags & BNEP_FLAGS_SETUP_RCVD))) - return (BNEP_WRONG_STATE); + if (p_bcb->con_state != BNEP_STATE_CONN_SETUP || (!(p_bcb->con_flags & BNEP_FLAGS_SETUP_RCVD))) { + return BNEP_WRONG_STATE; + } - log::debug("handle {}, responce {}", handle, resp); + log::debug("handle {}, response {}", handle, resp); - /* Form appropriate responce based on profile responce */ - if (resp == BNEP_CONN_FAILED_SRC_UUID) + /* Form appropriate response based on profile response */ + if (resp == BNEP_CONN_FAILED_SRC_UUID) { resp_code = BNEP_SETUP_INVALID_SRC_UUID; - else if (resp == BNEP_CONN_FAILED_DST_UUID) + } else if (resp == BNEP_CONN_FAILED_DST_UUID) { resp_code = BNEP_SETUP_INVALID_DEST_UUID; - else if (resp == BNEP_CONN_FAILED_UUID_SIZE) + } else if (resp == BNEP_CONN_FAILED_UUID_SIZE) { resp_code = BNEP_SETUP_INVALID_UUID_SIZE; - else if (resp == BNEP_SUCCESS) + } else if (resp == BNEP_SUCCESS) { resp_code = BNEP_SETUP_CONN_OK; - else + } else { resp_code = BNEP_SETUP_CONN_NOT_ALLOWED; + } bnep_send_conn_response(p_bcb, resp_code); p_bcb->con_flags &= (~BNEP_FLAGS_SETUP_RCVD); - if (resp == BNEP_SUCCESS) + if (resp == BNEP_SUCCESS) { bnep_connected(p_bcb); - else if (p_bcb->con_flags & BNEP_FLAGS_CONN_COMPLETED) { + } else if (p_bcb->con_flags & BNEP_FLAGS_CONN_COMPLETED) { /* Restore the original parameters */ p_bcb->con_state = BNEP_STATE_CONNECTED; p_bcb->con_flags &= (~BNEP_FLAGS_SETUP_RCVD); @@ -264,14 +269,16 @@ tBNEP_RESULT BNEP_ConnectResp(uint16_t handle, tBNEP_RESULT resp) { ext_type &= 0x7F; /* if unknown extension present stop processing */ - if (ext_type) break; + if (ext_type) { + break; + } p = bnep_process_control_packet(p_bcb, p, &rem_len, true); } osi_free_and_reset((void**)&p_bcb->p_pending_data); } - return (BNEP_SUCCESS); + return BNEP_SUCCESS; } /******************************************************************************* @@ -289,22 +296,26 @@ tBNEP_RESULT BNEP_ConnectResp(uint16_t handle, tBNEP_RESULT resp) { tBNEP_RESULT BNEP_Disconnect(uint16_t handle) { tBNEP_CONN* p_bcb; - if ((!handle) || (handle > BNEP_MAX_CONNECTIONS)) return (BNEP_WRONG_HANDLE); + if ((!handle) || (handle > BNEP_MAX_CONNECTIONS)) { + return BNEP_WRONG_HANDLE; + } p_bcb = &(bnep_cb.bcb[handle - 1]); - if (p_bcb->con_state == BNEP_STATE_IDLE) return (BNEP_WRONG_HANDLE); + if (p_bcb->con_state == BNEP_STATE_IDLE) { + return BNEP_WRONG_HANDLE; + } log::verbose("BNEP_Disconnect() for handle {}", handle); if (!L2CA_DisconnectReq(p_bcb->l2cap_cid)) { - log::warn("Unable to send L2CAP disconnect request peer:{} cid:{}", - p_bcb->rem_bda, p_bcb->l2cap_cid); + log::warn("Unable to send L2CAP disconnect request peer:{} cid:{}", p_bcb->rem_bda, + p_bcb->l2cap_cid); } bnepu_release_bcb(p_bcb); - return (BNEP_SUCCESS); + return BNEP_SUCCESS; } /******************************************************************************* @@ -323,22 +334,21 @@ tBNEP_RESULT BNEP_Disconnect(uint16_t handle) { * fw_ext_present - forwarded extensions present * * Returns: BNEP_WRONG_HANDLE - if passed handle is not valid - * BNEP_MTU_EXCEDED - If the data length is greater than + * BNEP_MTU_EXCEEDED - If the data length is greater than * the MTU * BNEP_IGNORE_CMD - If the packet is filtered out * BNEP_Q_SIZE_EXCEEDED - If the Tx Q is full * BNEP_SUCCESS - If written successfully * ******************************************************************************/ -tBNEP_RESULT BNEP_WriteBuf(uint16_t handle, const RawAddress& dest_addr, - BT_HDR* p_buf, uint16_t protocol, - const RawAddress& src_addr, bool fw_ext_present) { +tBNEP_RESULT BNEP_WriteBuf(uint16_t handle, const RawAddress& dest_addr, BT_HDR* p_buf, + uint16_t protocol, const RawAddress& src_addr, bool fw_ext_present) { tBNEP_CONN* p_bcb; uint8_t* p_data; if ((!handle) || (handle > BNEP_MAX_CONNECTIONS)) { osi_free(p_buf); - return (BNEP_WRONG_HANDLE); + return BNEP_WRONG_HANDLE; } p_bcb = &(bnep_cb.bcb[handle - 1]); @@ -346,13 +356,13 @@ tBNEP_RESULT BNEP_WriteBuf(uint16_t handle, const RawAddress& dest_addr, if (p_buf->len > BNEP_MTU_SIZE) { log::error("length {} exceeded MTU {}", p_buf->len, BNEP_MTU_SIZE); osi_free(p_buf); - return (BNEP_MTU_EXCEDED); + return BNEP_MTU_EXCEEDED; } /* Check if the packet should be filtered out */ p_data = (uint8_t*)(p_buf + 1) + p_buf->offset; - if (bnep_is_packet_allowed(p_bcb, dest_addr, protocol, fw_ext_present, p_data, - p_buf->len) != BNEP_SUCCESS) { + if (bnep_is_packet_allowed(p_bcb, dest_addr, protocol, fw_ext_present, p_data, p_buf->len) != + BNEP_SUCCESS) { /* ** If packet is filtered and ext headers are present ** drop the data and forward the ext headers @@ -382,9 +392,9 @@ tBNEP_RESULT BNEP_WriteBuf(uint16_t handle, const RawAddress& dest_addr, } while (ext & 0x80); - if (protocol != BNEP_802_1_P_PROTOCOL) + if (protocol != BNEP_802_1_P_PROTOCOL) { protocol = 0; - else { + } else { new_len += 4; if (new_len > org_len) { osi_free(p_buf); @@ -403,17 +413,16 @@ tBNEP_RESULT BNEP_WriteBuf(uint16_t handle, const RawAddress& dest_addr, /* Check transmit queue */ if (fixed_queue_length(p_bcb->xmit_q) >= BNEP_MAX_XMITQ_DEPTH) { osi_free(p_buf); - return (BNEP_Q_SIZE_EXCEEDED); + return BNEP_Q_SIZE_EXCEEDED; } /* Build the BNEP header */ - bnepu_build_bnep_hdr(p_bcb, p_buf, protocol, src_addr, dest_addr, - fw_ext_present); + bnepu_build_bnep_hdr(p_bcb, p_buf, protocol, src_addr, dest_addr, fw_ext_present); /* Send the data or queue it up */ bnepu_check_send_packet(p_bcb, p_buf); - return (BNEP_SUCCESS); + return BNEP_SUCCESS; } /******************************************************************************* @@ -432,7 +441,7 @@ tBNEP_RESULT BNEP_WriteBuf(uint16_t handle, const RawAddress& dest_addr, * fw_ext_present - forwarded extensions present * * Returns: BNEP_WRONG_HANDLE - if passed handle is not valid - * BNEP_MTU_EXCEDED - If the data length is greater than + * BNEP_MTU_EXCEEDED - If the data length is greater than * the MTU * BNEP_IGNORE_CMD - If the packet is filtered out * BNEP_Q_SIZE_EXCEEDED - If the Tx Q is full @@ -440,25 +449,26 @@ tBNEP_RESULT BNEP_WriteBuf(uint16_t handle, const RawAddress& dest_addr, * BNEP_SUCCESS - If written successfully * ******************************************************************************/ -tBNEP_RESULT BNEP_Write(uint16_t handle, const RawAddress& dest_addr, - uint8_t* p_data, uint16_t len, uint16_t protocol, - const RawAddress& src_addr, bool fw_ext_present) { +tBNEP_RESULT BNEP_Write(uint16_t handle, const RawAddress& dest_addr, uint8_t* p_data, uint16_t len, + uint16_t protocol, const RawAddress& src_addr, bool fw_ext_present) { tBNEP_CONN* p_bcb; uint8_t* p; /* Check MTU size. Consider the possibility of having extension headers */ if (len > BNEP_MTU_SIZE) { log::error("length {} exceeded MTU {}", len, BNEP_MTU_SIZE); - return (BNEP_MTU_EXCEDED); + return BNEP_MTU_EXCEEDED; } - if ((!handle) || (handle > BNEP_MAX_CONNECTIONS)) return (BNEP_WRONG_HANDLE); + if ((!handle) || (handle > BNEP_MAX_CONNECTIONS)) { + return BNEP_WRONG_HANDLE; + } p_bcb = &(bnep_cb.bcb[handle - 1]); /* Check if the packet should be filtered out */ - if (bnep_is_packet_allowed(p_bcb, dest_addr, protocol, fw_ext_present, p_data, - len) != BNEP_SUCCESS) { + if (bnep_is_packet_allowed(p_bcb, dest_addr, protocol, fw_ext_present, p_data, len) != + BNEP_SUCCESS) { /* ** If packet is filtered and ext headers are present ** drop the data and forward the ext headers @@ -481,27 +491,33 @@ tBNEP_RESULT BNEP_Write(uint16_t handle, const RawAddress& dest_addr, new_len += (length + 2); - if (new_len > org_len) return BNEP_IGNORE_CMD; + if (new_len > org_len) { + return BNEP_IGNORE_CMD; + } } while (ext & 0x80); - if (protocol != BNEP_802_1_P_PROTOCOL) + if (protocol != BNEP_802_1_P_PROTOCOL) { protocol = 0; - else { + } else { new_len += 4; - if (new_len > org_len) return BNEP_IGNORE_CMD; + if (new_len > org_len) { + return BNEP_IGNORE_CMD; + } p_data[2] = 0; p_data[3] = 0; } len = new_len; p_data = p; - } else + } else { return BNEP_IGNORE_CMD; + } } /* Check transmit queue */ - if (fixed_queue_length(p_bcb->xmit_q) >= BNEP_MAX_XMITQ_DEPTH) - return (BNEP_Q_SIZE_EXCEEDED); + if (fixed_queue_length(p_bcb->xmit_q) >= BNEP_MAX_XMITQ_DEPTH) { + return BNEP_Q_SIZE_EXCEEDED; + } /* Get a buffer to copy the data into */ BT_HDR* p_buf = (BT_HDR*)osi_malloc(BNEP_BUF_SIZE); @@ -513,13 +529,12 @@ tBNEP_RESULT BNEP_Write(uint16_t handle, const RawAddress& dest_addr, memcpy(p, p_data, len); /* Build the BNEP header */ - bnepu_build_bnep_hdr(p_bcb, p_buf, protocol, src_addr, dest_addr, - fw_ext_present); + bnepu_build_bnep_hdr(p_bcb, p_buf, protocol, src_addr, dest_addr, fw_ext_present); /* Send the data or queue it up */ bnepu_check_send_packet(p_bcb, p_buf); - return (BNEP_SUCCESS); + return BNEP_SUCCESS; } /******************************************************************************* @@ -541,26 +556,31 @@ tBNEP_RESULT BNEP_Write(uint16_t handle, const RawAddress& dest_addr, * BNEP_SUCCESS - if request sent successfully * ******************************************************************************/ -tBNEP_RESULT BNEP_SetProtocolFilters(uint16_t handle, uint16_t num_filters, - uint16_t* p_start_array, +tBNEP_RESULT BNEP_SetProtocolFilters(uint16_t handle, uint16_t num_filters, uint16_t* p_start_array, uint16_t* p_end_array) { uint16_t xx; tBNEP_CONN* p_bcb; - if ((!handle) || (handle > BNEP_MAX_CONNECTIONS)) return (BNEP_WRONG_HANDLE); + if ((!handle) || (handle > BNEP_MAX_CONNECTIONS)) { + return BNEP_WRONG_HANDLE; + } p_bcb = &(bnep_cb.bcb[handle - 1]); /* Check the connection state */ if ((p_bcb->con_state != BNEP_STATE_CONNECTED) && - (!(p_bcb->con_flags & BNEP_FLAGS_CONN_COMPLETED))) - return (BNEP_WRONG_STATE); + (!(p_bcb->con_flags & BNEP_FLAGS_CONN_COMPLETED))) { + return BNEP_WRONG_STATE; + } /* Validate the parameters */ - if (num_filters && (!p_start_array || !p_end_array)) - return (BNEP_SET_FILTER_FAIL); + if (num_filters && (!p_start_array || !p_end_array)) { + return BNEP_SET_FILTER_FAIL; + } - if (num_filters > BNEP_MAX_PROT_FILTERS) return (BNEP_TOO_MANY_FILTERS); + if (num_filters > BNEP_MAX_PROT_FILTERS) { + return BNEP_TOO_MANY_FILTERS; + } /* Fill the filter values in connnection block */ for (xx = 0; xx < num_filters; xx++) { @@ -572,7 +592,7 @@ tBNEP_RESULT BNEP_SetProtocolFilters(uint16_t handle, uint16_t num_filters, bnepu_send_peer_our_filters(p_bcb); - return (BNEP_SUCCESS); + return BNEP_SUCCESS; } /******************************************************************************* @@ -597,31 +617,35 @@ tBNEP_RESULT BNEP_SetProtocolFilters(uint16_t handle, uint16_t num_filters, * BNEP_SUCCESS - if request sent successfully * ******************************************************************************/ -tBNEP_RESULT BNEP_SetMulticastFilters(uint16_t handle, uint16_t num_filters, - uint8_t* p_start_array, +tBNEP_RESULT BNEP_SetMulticastFilters(uint16_t handle, uint16_t num_filters, uint8_t* p_start_array, uint8_t* p_end_array) { uint16_t xx; tBNEP_CONN* p_bcb; - if ((!handle) || (handle > BNEP_MAX_CONNECTIONS)) return (BNEP_WRONG_HANDLE); + if ((!handle) || (handle > BNEP_MAX_CONNECTIONS)) { + return BNEP_WRONG_HANDLE; + } p_bcb = &(bnep_cb.bcb[handle - 1]); /* Check the connection state */ if ((p_bcb->con_state != BNEP_STATE_CONNECTED) && - (!(p_bcb->con_flags & BNEP_FLAGS_CONN_COMPLETED))) - return (BNEP_WRONG_STATE); + (!(p_bcb->con_flags & BNEP_FLAGS_CONN_COMPLETED))) { + return BNEP_WRONG_STATE; + } /* Validate the parameters */ - if (num_filters && (!p_start_array || !p_end_array)) - return (BNEP_SET_FILTER_FAIL); + if (num_filters && (!p_start_array || !p_end_array)) { + return BNEP_SET_FILTER_FAIL; + } - if (num_filters > BNEP_MAX_MULTI_FILTERS) return (BNEP_TOO_MANY_FILTERS); + if (num_filters > BNEP_MAX_MULTI_FILTERS) { + return BNEP_TOO_MANY_FILTERS; + } /* Fill the multicast filter values in connnection block */ for (xx = 0; xx < num_filters; xx++) { - memcpy(p_bcb->sent_mcast_filter_start[xx].address, p_start_array, - BD_ADDR_LEN); + memcpy(p_bcb->sent_mcast_filter_start[xx].address, p_start_array, BD_ADDR_LEN); memcpy(p_bcb->sent_mcast_filter_end[xx].address, p_end_array, BD_ADDR_LEN); p_start_array += BD_ADDR_LEN; @@ -632,5 +656,5 @@ tBNEP_RESULT BNEP_SetMulticastFilters(uint16_t handle, uint16_t num_filters, bnepu_send_peer_our_multi_filters(p_bcb); - return (BNEP_SUCCESS); + return BNEP_SUCCESS; } diff --git a/system/stack/bnep/bnep_int.h b/system/stack/bnep/bnep_int.h index e553251952b..aebe4cd8619 100644 --- a/system/stack/bnep/bnep_int.h +++ b/system/stack/bnep/bnep_int.h @@ -34,7 +34,7 @@ #include "types/raw_address.h" /* BNEP frame types -*/ + */ #define BNEP_FRAME_GENERAL_ETHERNET 0x00 #define BNEP_FRAME_CONTROL 0x01 #define BNEP_FRAME_COMPRESSED_ETHERNET 0x02 @@ -42,7 +42,7 @@ #define BNEP_FRAME_COMPRESSED_ETHERNET_DEST_ONLY 0x04 /* BNEP filter control message types -*/ + */ #define BNEP_CONTROL_COMMAND_NOT_UNDERSTOOD 0x00 #define BNEP_SETUP_CONNECTION_REQUEST_MSG 0x01 #define BNEP_SETUP_CONNECTION_RESPONSE_MSG 0x02 @@ -52,11 +52,11 @@ #define BNEP_FILTER_MULTI_ADDR_RESPONSE_MSG 0x06 /* BNEP header extension types -*/ + */ #define BNEP_EXTENSION_FILTER_CONTROL 0x00 /* BNEP Setup Connection response codes -*/ + */ #define BNEP_SETUP_CONN_OK 0x0000 #define BNEP_SETUP_INVALID_DEST_UUID 0x0001 #define BNEP_SETUP_INVALID_SRC_UUID 0x0002 @@ -64,7 +64,7 @@ #define BNEP_SETUP_CONN_NOT_ALLOWED 0x0004 /* BNEP filter control response codes -*/ + */ #define BNEP_FILTER_CRL_OK 0x0000 #define BNEP_FILTER_CRL_UNSUPPORTED 0x0001 #define BNEP_FILTER_CRL_BAD_RANGE 0x0002 @@ -84,7 +84,7 @@ #define BNEP_MAX_RETRANSMITS 3 /* Define the BNEP Connection Control Block -*/ + */ typedef struct { #define BNEP_STATE_IDLE 0 #define BNEP_STATE_CONN_START 1 @@ -138,7 +138,7 @@ typedef struct { } tBNEP_CONN; /* The main BNEP control block -*/ + */ typedef struct { tL2CAP_CFG_INFO l2cap_my_cfg; /* My L2CAP config */ tBNEP_CONN bcb[BNEP_MAX_CONNECTIONS]; @@ -158,11 +158,11 @@ typedef struct { } tBNEP_CB; /* Global BNEP data -*/ + */ extern tBNEP_CB bnep_cb; /* Functions provided by bnep_main.cc -*/ + */ tBNEP_RESULT bnep_register_with_l2cap(void); void bnep_disconnect(tBNEP_CONN* p_bcb, uint16_t reason); tBNEP_CONN* bnep_conn_originate(uint8_t* p_bd_addr); @@ -170,7 +170,7 @@ void bnep_conn_timer_timeout(void* data); void bnep_connected(tBNEP_CONN* p_bcb); /* Functions provided by bnep_utils.cc -*/ + */ tBNEP_CONN* bnepu_find_bcb_by_cid(uint16_t cid); tBNEP_CONN* bnepu_find_bcb_by_bd_addr(const RawAddress& p_bda); tBNEP_CONN* bnepu_allocate_bcb(const RawAddress& p_rem_bda); @@ -179,31 +179,24 @@ void bnepu_send_peer_our_filters(tBNEP_CONN* p_bcb); void bnepu_send_peer_our_multi_filters(tBNEP_CONN* p_bcb); bool bnepu_does_dest_support_prot(tBNEP_CONN* p_bcb, uint16_t protocol); void bnepu_build_bnep_hdr(tBNEP_CONN* p_bcb, BT_HDR* p_buf, uint16_t protocol, - const RawAddress& src_addr, - const RawAddress& dest_addr, bool ext_bit); -void test_bnepu_build_bnep_hdr(tBNEP_CONN* p_bcb, BT_HDR* p_buf, - uint16_t protocol, uint8_t* p_src_addr, - uint8_t* p_dest_addr, uint8_t type); + const RawAddress& src_addr, const RawAddress& dest_addr, bool ext_bit); +void test_bnepu_build_bnep_hdr(tBNEP_CONN* p_bcb, BT_HDR* p_buf, uint16_t protocol, + uint8_t* p_src_addr, uint8_t* p_dest_addr, uint8_t type); tBNEP_CONN* bnepu_get_route_to_dest(uint8_t* p_bda); void bnepu_check_send_packet(tBNEP_CONN* p_bcb, BT_HDR* p_buf); void bnep_send_command_not_understood(tBNEP_CONN* p_bcb, uint8_t cmd_code); -void bnepu_process_peer_filter_set(tBNEP_CONN* p_bcb, uint8_t* p_filters, - uint16_t len); +void bnepu_process_peer_filter_set(tBNEP_CONN* p_bcb, uint8_t* p_filters, uint16_t len); void bnepu_process_peer_filter_rsp(tBNEP_CONN* p_bcb, uint8_t* p_data); void bnepu_process_multicast_filter_rsp(tBNEP_CONN* p_bcb, uint8_t* p_data); void bnep_send_conn_req(tBNEP_CONN* p_bcb); void bnep_send_conn_response(tBNEP_CONN* p_bcb, uint16_t resp_code); -void bnep_process_setup_conn_req(tBNEP_CONN* p_bcb, uint8_t* p_setup, - uint8_t len); -void bnep_process_setup_conn_responce(tBNEP_CONN* p_bcb, uint8_t* p_setup); -uint8_t* bnep_process_control_packet(tBNEP_CONN* p_bcb, uint8_t* p, - uint16_t* len, bool is_ext); -void bnep_sec_check_complete(const RawAddress* bd_addr, tBT_TRANSPORT trasnport, - void* p_ref_data); -tBNEP_RESULT bnep_is_packet_allowed(tBNEP_CONN* p_bcb, - const RawAddress& dest_addr, - uint16_t protocol, bool fw_ext_present, - uint8_t* p_data, uint16_t org_len); +void bnep_process_setup_conn_req(tBNEP_CONN* p_bcb, uint8_t* p_setup, uint8_t len); +void bnep_process_setup_conn_response(tBNEP_CONN* p_bcb, uint8_t* p_setup); +uint8_t* bnep_process_control_packet(tBNEP_CONN* p_bcb, uint8_t* p, uint16_t* len, bool is_ext); +void bnep_sec_check_complete(const RawAddress* bd_addr, tBT_TRANSPORT transport, void* p_ref_data); +tBNEP_RESULT bnep_is_packet_allowed(tBNEP_CONN* p_bcb, const RawAddress& dest_addr, + uint16_t protocol, bool fw_ext_present, uint8_t* p_data, + uint16_t org_len); #endif diff --git a/system/stack/bnep/bnep_main.cc b/system/stack/bnep/bnep_main.cc index 7572d2d13d8..f0cac0b4cd2 100644 --- a/system/stack/bnep/bnep_main.cc +++ b/system/stack/bnep/bnep_main.cc @@ -54,11 +54,10 @@ const uint16_t bnep_frame_hdr_sizes[] = {14, 1, 2, 8, 8}; /******************************************************************************/ /* L O C A L F U N C T I O N P R O T O T Y P E S */ /******************************************************************************/ -static void bnep_connect_ind(const RawAddress& bd_addr, uint16_t l2cap_cid, - uint16_t psm, uint8_t l2cap_id); +static void bnep_connect_ind(const RawAddress& bd_addr, uint16_t l2cap_cid, uint16_t psm, + uint8_t l2cap_id); static void bnep_connect_cfm(uint16_t l2cap_cid, uint16_t result); -static void bnep_config_cfm(uint16_t l2cap_cid, uint16_t result, - tL2CAP_CFG_INFO* p_cfg); +static void bnep_config_cfm(uint16_t l2cap_cid, uint16_t result, tL2CAP_CFG_INFO* p_cfg); static void bnep_disconnect_ind(uint16_t l2cap_cid, bool ack_needed); static void bnep_data_ind(uint16_t l2cap_cid, BT_HDR* p_msg); static void bnep_congestion_ind(uint16_t lcid, bool is_congested); @@ -89,8 +88,7 @@ tBNEP_RESULT bnep_register_with_l2cap(void) { bnep_cb.reg_info.pL2CA_Error_Cb = bnep_on_l2cap_error; /* Now, register with L2CAP */ - if (!L2CA_RegisterWithSecurity(BT_PSM_BNEP, bnep_cb.reg_info, - false /* enable_snoop */, nullptr, + if (!L2CA_RegisterWithSecurity(BT_PSM_BNEP, bnep_cb.reg_info, false /* enable_snoop */, nullptr, BNEP_MTU_SIZE, BNEP_MTU_SIZE, BTA_SEC_AUTHENTICATE | BTA_SEC_ENCRYPT)) { log::error("BNEP - Registration failed"); @@ -111,17 +109,15 @@ tBNEP_RESULT bnep_register_with_l2cap(void) { * Returns void * ******************************************************************************/ -static void bnep_connect_ind(const RawAddress& bd_addr, uint16_t l2cap_cid, - uint16_t /* psm */, uint8_t l2cap_id) { +static void bnep_connect_ind(const RawAddress& bd_addr, uint16_t l2cap_cid, uint16_t /* psm */, + uint8_t l2cap_id) { tBNEP_CONN* p_bcb = bnepu_find_bcb_by_bd_addr(bd_addr); /* If we are not acting as server, or already have a connection, or have */ /* no more resources to handle the connection, reject the connection. */ - if (!(bnep_cb.profile_registered) || (p_bcb) || - ((p_bcb = bnepu_allocate_bcb(bd_addr)) == NULL)) { + if (!(bnep_cb.profile_registered) || (p_bcb) || ((p_bcb = bnepu_allocate_bcb(bd_addr)) == NULL)) { if (!L2CA_DisconnectReq(l2cap_cid)) { - log::warn("Unable to request L2CAP disconnect peer:{} cid:{}", bd_addr, - l2cap_cid); + log::warn("Unable to request L2CAP disconnect peer:{} cid:{}", bd_addr, l2cap_cid); } return; } @@ -133,25 +129,24 @@ static void bnep_connect_ind(const RawAddress& bd_addr, uint16_t l2cap_cid, p_bcb->l2cap_cid = l2cap_cid; /* Start timer waiting for config setup */ - alarm_set_on_mloop(p_bcb->conn_timer, BNEP_CONN_TIMEOUT_MS, - bnep_conn_timer_timeout, p_bcb); + alarm_set_on_mloop(p_bcb->conn_timer, BNEP_CONN_TIMEOUT_MS, bnep_conn_timer_timeout, p_bcb); log::debug("BNEP - Rcvd L2CAP conn ind, CID: 0x{:x}", p_bcb->l2cap_cid); } static void bnep_on_l2cap_error(uint16_t l2cap_cid, uint16_t result) { tBNEP_CONN* p_bcb = bnepu_find_bcb_by_cid(l2cap_cid); - if (p_bcb == nullptr) return; + if (p_bcb == nullptr) { + return; + } /* Tell the upper layer, if there is a callback */ if ((p_bcb->con_flags & BNEP_FLAGS_IS_ORIG) && (bnep_cb.p_conn_state_cb)) { - (*bnep_cb.p_conn_state_cb)(p_bcb->handle, p_bcb->rem_bda, BNEP_CONN_FAILED, - false); + (*bnep_cb.p_conn_state_cb)(p_bcb->handle, p_bcb->rem_bda, BNEP_CONN_FAILED, false); } if (!L2CA_DisconnectReq(p_bcb->l2cap_cid)) { - log::warn("Unable to request L2CAP disconnect peer:{} cid:{}", - p_bcb->rem_bda, l2cap_cid); + log::warn("Unable to request L2CAP disconnect peer:{} cid:{}", p_bcb->rem_bda, l2cap_cid); } bnepu_release_bcb(p_bcb); @@ -180,16 +175,13 @@ static void bnep_connect_cfm(uint16_t l2cap_cid, uint16_t result) { /* If the connection response contains success status, then */ /* Transition to the next state and startup the timer. */ - if ((result == L2CAP_CONN_OK) && - (p_bcb->con_state == BNEP_STATE_CONN_START)) { + if ((result == L2CAP_CONN_OK) && (p_bcb->con_state == BNEP_STATE_CONN_START)) { p_bcb->con_state = BNEP_STATE_CFG_SETUP; /* Start timer waiting for config results */ - alarm_set_on_mloop(p_bcb->conn_timer, BNEP_CONN_TIMEOUT_MS, - bnep_conn_timer_timeout, p_bcb); + alarm_set_on_mloop(p_bcb->conn_timer, BNEP_CONN_TIMEOUT_MS, bnep_conn_timer_timeout, p_bcb); - log::debug("BNEP - got conn cnf, sent cfg req, CID: 0x{:x}", - p_bcb->l2cap_cid); + log::debug("BNEP - got conn cnf, sent cfg req, CID: 0x{:x}", p_bcb->l2cap_cid); } else { log::error("invoked with non OK status"); } @@ -205,8 +197,7 @@ static void bnep_connect_cfm(uint16_t l2cap_cid, uint16_t result) { * Returns void * ******************************************************************************/ -static void bnep_config_cfm(uint16_t l2cap_cid, uint16_t initiator, - tL2CAP_CFG_INFO* p_cfg) { +static void bnep_config_cfm(uint16_t l2cap_cid, uint16_t initiator, tL2CAP_CFG_INFO* p_cfg) { tBNEP_CONN* p_bcb; log::debug("BNEP - Rcvd cfg cfm, CID: 0x{:x}", l2cap_cid); @@ -222,8 +213,7 @@ static void bnep_config_cfm(uint16_t l2cap_cid, uint16_t initiator, p_bcb->con_state = BNEP_STATE_SEC_CHECKING; /* Start timer waiting for setup or response */ - alarm_set_on_mloop(p_bcb->conn_timer, BNEP_HOST_TIMEOUT_MS, - bnep_conn_timer_timeout, p_bcb); + alarm_set_on_mloop(p_bcb->conn_timer, BNEP_HOST_TIMEOUT_MS, bnep_conn_timer_timeout, p_bcb); if (p_bcb->con_flags & BNEP_FLAGS_IS_ORIG) { bnep_sec_check_complete(&p_bcb->rem_bda, BT_TRANSPORT_BR_EDR, p_bcb); @@ -254,15 +244,14 @@ static void bnep_disconnect_ind(uint16_t l2cap_cid, bool ack_needed) { /* Tell the user if there is a callback */ if (p_bcb->con_state == BNEP_STATE_CONNECTED) { - if (bnep_cb.p_conn_state_cb) - (*bnep_cb.p_conn_state_cb)(p_bcb->handle, p_bcb->rem_bda, - BNEP_CONN_DISCONNECTED, false); + if (bnep_cb.p_conn_state_cb) { + (*bnep_cb.p_conn_state_cb)(p_bcb->handle, p_bcb->rem_bda, BNEP_CONN_DISCONNECTED, false); + } } else { - if ((bnep_cb.p_conn_state_cb) && - ((p_bcb->con_flags & BNEP_FLAGS_IS_ORIG) || - (p_bcb->con_flags & BNEP_FLAGS_CONN_COMPLETED))) - (*bnep_cb.p_conn_state_cb)(p_bcb->handle, p_bcb->rem_bda, - BNEP_CONN_FAILED, false); + if ((bnep_cb.p_conn_state_cb) && ((p_bcb->con_flags & BNEP_FLAGS_IS_ORIG) || + (p_bcb->con_flags & BNEP_FLAGS_CONN_COMPLETED))) { + (*bnep_cb.p_conn_state_cb)(p_bcb->handle, p_bcb->rem_bda, BNEP_CONN_FAILED, false); + } } bnepu_release_bcb(p_bcb); @@ -302,11 +291,13 @@ static void bnep_congestion_ind(uint16_t l2cap_cid, bool is_congested) { while (!(p_bcb->con_flags & BNEP_FLAGS_L2CAP_CONGESTED)) { BT_HDR* p_buf = (BT_HDR*)fixed_queue_try_dequeue(p_bcb->xmit_q); - if (!p_buf) break; + if (!p_buf) { + break; + } if (L2CA_DataWrite(l2cap_cid, p_buf) != tL2CAP_DW_RESULT::SUCCESS) { - log::warn("Unable to write L2CAP data peer:{} cid:{} len:{}", - p_bcb->rem_bda, l2cap_cid, p_buf->len); + log::warn("Unable to write L2CAP data peer:{} cid:{} len:{}", p_bcb->rem_bda, l2cap_cid, + p_buf->len); } } } @@ -357,8 +348,7 @@ static void bnep_data_ind(uint16_t l2cap_cid, BT_HDR* p_buf) { return; } if ((rem_len <= bnep_frame_hdr_sizes[type]) || (rem_len > BNEP_MTU_SIZE)) { - log::debug("BNEP - rcvd frame, bad len: {} type: 0x{:02x}", p_buf->len, - type); + log::debug("BNEP - rcvd frame, bad len: {} type: 0x{:02x}", p_buf->len, type); osi_free(p_buf); return; } @@ -366,10 +356,9 @@ static void bnep_data_ind(uint16_t l2cap_cid, BT_HDR* p_buf) { rem_len--; if ((p_bcb->con_state != BNEP_STATE_CONNECTED) && - (!(p_bcb->con_flags & BNEP_FLAGS_CONN_COMPLETED)) && - (type != BNEP_FRAME_CONTROL)) { - log::warn("BNEP - Ignored L2CAP data while in state: {}, CID: 0x{:x}", - p_bcb->con_state, l2cap_cid); + (!(p_bcb->con_flags & BNEP_FLAGS_CONN_COMPLETED)) && (type != BNEP_FRAME_CONTROL)) { + log::warn("BNEP - Ignored L2CAP data while in state: {}, CID: 0x{:x}", p_bcb->con_state, + l2cap_cid); if (extension_present) { /* @@ -417,8 +406,7 @@ static void bnep_data_ind(uint16_t l2cap_cid, BT_HDR* p_buf) { return; } - log::debug("BNEP - rcv frame, type: {} len: {} Ext: {}", type, p_buf->len, - extension_present); + log::debug("BNEP - rcv frame, type: {} len: {} Ext: {}", type, p_buf->len, extension_present); /* Initialize addresses to 'not supplied' */ RawAddress src_addr = RawAddress::kEmpty; @@ -439,8 +427,7 @@ static void bnep_data_ind(uint16_t l2cap_cid, BT_HDR* p_buf) { p = bnep_process_control_packet(p_bcb, p, &rem_len, false); if (ctrl_type == BNEP_SETUP_CONNECTION_REQUEST_MSG && - p_bcb->con_state != BNEP_STATE_CONNECTED && extension_present && p && - rem_len) { + p_bcb->con_state != BNEP_STATE_CONNECTED && extension_present && p && rem_len) { osi_free(p_bcb->p_pending_data); p_bcb->p_pending_data = (BT_HDR*)osi_malloc(rem_len + sizeof(BT_HDR)); memcpy((uint8_t*)(p_bcb->p_pending_data + 1), p, rem_len); @@ -454,7 +441,9 @@ static void bnep_data_ind(uint16_t l2cap_cid, BT_HDR* p_buf) { ext_type &= 0x7F; /* if unknown extension present stop processing */ - if (ext_type != BNEP_EXTENSION_FILTER_CONTROL) break; + if (ext_type != BNEP_EXTENSION_FILTER_CONTROL) { + break; + } p = bnep_process_control_packet(p_bcb, p, &rem_len, true); } @@ -503,24 +492,26 @@ static void bnep_data_ind(uint16_t l2cap_cid, BT_HDR* p_buf) { p_buf->len = rem_len; /* Always give the upper layer MAC addresses */ - if (src_addr == RawAddress::kEmpty) src_addr = p_bcb->rem_bda; + if (src_addr == RawAddress::kEmpty) { + src_addr = p_bcb->rem_bda; + } - if (dst_addr == RawAddress::kEmpty) - dst_addr = bluetooth::ToRawAddress( - bluetooth::shim::GetController()->GetMacAddress()); + if (dst_addr == RawAddress::kEmpty) { + dst_addr = bluetooth::ToRawAddress(bluetooth::shim::GetController()->GetMacAddress()); + } /* check whether there are any extensions to be forwarded */ - if (ext_type) + if (ext_type) { fw_ext_present = true; - else + } else { fw_ext_present = false; + } if (bnep_cb.p_data_buf_cb) { - (*bnep_cb.p_data_buf_cb)(p_bcb->handle, src_addr, dst_addr, protocol, p_buf, - fw_ext_present); + (*bnep_cb.p_data_buf_cb)(p_bcb->handle, src_addr, dst_addr, protocol, p_buf, fw_ext_present); } else if (bnep_cb.p_data_ind_cb) { - (*bnep_cb.p_data_ind_cb)(p_bcb->handle, src_addr, dst_addr, protocol, p, - rem_len, fw_ext_present); + (*bnep_cb.p_data_ind_cb)(p_bcb->handle, src_addr, dst_addr, protocol, p, rem_len, + fw_ext_present); osi_free(p_buf); } } @@ -539,19 +530,16 @@ static void bnep_data_ind(uint16_t l2cap_cid, BT_HDR* p_buf) { void bnep_conn_timer_timeout(void* data) { tBNEP_CONN* p_bcb = (tBNEP_CONN*)data; - log::debug( - "BNEP - CCB timeout in state: {} CID: 0x{:x} flags {:x}, re_transmit {}", - p_bcb->con_state, p_bcb->l2cap_cid, p_bcb->con_flags, - p_bcb->re_transmits); + log::debug("BNEP - CCB timeout in state: {} CID: 0x{:x} flags {:x}, re_transmit {}", + p_bcb->con_state, p_bcb->l2cap_cid, p_bcb->con_flags, p_bcb->re_transmits); if (p_bcb->con_state == BNEP_STATE_CONN_SETUP) { - log::debug("BNEP - CCB timeout in state: {} CID: 0x{:x}", p_bcb->con_state, - p_bcb->l2cap_cid); + log::debug("BNEP - CCB timeout in state: {} CID: 0x{:x}", p_bcb->con_state, p_bcb->l2cap_cid); if (!(p_bcb->con_flags & BNEP_FLAGS_IS_ORIG)) { if (!L2CA_DisconnectReq(p_bcb->l2cap_cid)) { - log::warn("Unable to request L2CAP disconnect peer:{} cid:{}", - p_bcb->rem_bda, p_bcb->l2cap_cid); + log::warn("Unable to request L2CAP disconnect peer:{} cid:{}", p_bcb->rem_bda, + p_bcb->l2cap_cid); } bnepu_release_bcb(p_bcb); return; @@ -559,51 +547,49 @@ void bnep_conn_timer_timeout(void* data) { if (p_bcb->re_transmits++ != BNEP_MAX_RETRANSMITS) { bnep_send_conn_req(p_bcb); - alarm_set_on_mloop(p_bcb->conn_timer, BNEP_CONN_TIMEOUT_MS, - bnep_conn_timer_timeout, p_bcb); + alarm_set_on_mloop(p_bcb->conn_timer, BNEP_CONN_TIMEOUT_MS, bnep_conn_timer_timeout, p_bcb); } else { if (!L2CA_DisconnectReq(p_bcb->l2cap_cid)) { - log::warn("Unable to request L2CAP disconnect peer:{} cid:{}", - p_bcb->rem_bda, p_bcb->l2cap_cid); + log::warn("Unable to request L2CAP disconnect peer:{} cid:{}", p_bcb->rem_bda, + p_bcb->l2cap_cid); } - if ((p_bcb->con_flags & BNEP_FLAGS_IS_ORIG) && (bnep_cb.p_conn_state_cb)) - (*bnep_cb.p_conn_state_cb)(p_bcb->handle, p_bcb->rem_bda, - BNEP_CONN_FAILED, false); + if ((p_bcb->con_flags & BNEP_FLAGS_IS_ORIG) && (bnep_cb.p_conn_state_cb)) { + (*bnep_cb.p_conn_state_cb)(p_bcb->handle, p_bcb->rem_bda, BNEP_CONN_FAILED, false); + } bnepu_release_bcb(p_bcb); return; } } else if (p_bcb->con_state != BNEP_STATE_CONNECTED) { - log::debug("BNEP - CCB timeout in state: {} CID: 0x{:x}", p_bcb->con_state, - p_bcb->l2cap_cid); + log::debug("BNEP - CCB timeout in state: {} CID: 0x{:x}", p_bcb->con_state, p_bcb->l2cap_cid); if (!L2CA_DisconnectReq(p_bcb->l2cap_cid)) { - log::warn("Unable to request L2CAP disconnect peer:{} cid:{}", - p_bcb->rem_bda, p_bcb->l2cap_cid); + log::warn("Unable to request L2CAP disconnect peer:{} cid:{}", p_bcb->rem_bda, + p_bcb->l2cap_cid); } /* Tell the user if there is a callback */ - if ((p_bcb->con_flags & BNEP_FLAGS_IS_ORIG) && (bnep_cb.p_conn_state_cb)) - (*bnep_cb.p_conn_state_cb)(p_bcb->handle, p_bcb->rem_bda, - BNEP_CONN_FAILED, false); + if ((p_bcb->con_flags & BNEP_FLAGS_IS_ORIG) && (bnep_cb.p_conn_state_cb)) { + (*bnep_cb.p_conn_state_cb)(p_bcb->handle, p_bcb->rem_bda, BNEP_CONN_FAILED, false); + } bnepu_release_bcb(p_bcb); } else if (p_bcb->con_flags & BNEP_FLAGS_FILTER_RESP_PEND) { if (p_bcb->re_transmits++ != BNEP_MAX_RETRANSMITS) { bnepu_send_peer_our_filters(p_bcb); - alarm_set_on_mloop(p_bcb->conn_timer, BNEP_FILTER_SET_TIMEOUT_MS, - bnep_conn_timer_timeout, p_bcb); + alarm_set_on_mloop(p_bcb->conn_timer, BNEP_FILTER_SET_TIMEOUT_MS, bnep_conn_timer_timeout, + p_bcb); } else { if (!L2CA_DisconnectReq(p_bcb->l2cap_cid)) { - log::warn("Unable to request L2CAP disconnect peer:{} cid:{}", - p_bcb->rem_bda, p_bcb->l2cap_cid); + log::warn("Unable to request L2CAP disconnect peer:{} cid:{}", p_bcb->rem_bda, + p_bcb->l2cap_cid); } /* Tell the user if there is a callback */ - if (bnep_cb.p_conn_state_cb) - (*bnep_cb.p_conn_state_cb)(p_bcb->handle, p_bcb->rem_bda, - BNEP_SET_FILTER_FAIL, false); + if (bnep_cb.p_conn_state_cb) { + (*bnep_cb.p_conn_state_cb)(p_bcb->handle, p_bcb->rem_bda, BNEP_SET_FILTER_FAIL, false); + } bnepu_release_bcb(p_bcb); return; @@ -611,18 +597,18 @@ void bnep_conn_timer_timeout(void* data) { } else if (p_bcb->con_flags & BNEP_FLAGS_MULTI_RESP_PEND) { if (p_bcb->re_transmits++ != BNEP_MAX_RETRANSMITS) { bnepu_send_peer_our_multi_filters(p_bcb); - alarm_set_on_mloop(p_bcb->conn_timer, BNEP_FILTER_SET_TIMEOUT_MS, - bnep_conn_timer_timeout, p_bcb); + alarm_set_on_mloop(p_bcb->conn_timer, BNEP_FILTER_SET_TIMEOUT_MS, bnep_conn_timer_timeout, + p_bcb); } else { if (!L2CA_DisconnectReq(p_bcb->l2cap_cid)) { - log::warn("Unable to request L2CAP disconnect peer:{} cid:{}", - p_bcb->rem_bda, p_bcb->l2cap_cid); + log::warn("Unable to request L2CAP disconnect peer:{} cid:{}", p_bcb->rem_bda, + p_bcb->l2cap_cid); } /* Tell the user if there is a callback */ - if (bnep_cb.p_conn_state_cb) - (*bnep_cb.p_conn_state_cb)(p_bcb->handle, p_bcb->rem_bda, - BNEP_SET_FILTER_FAIL, false); + if (bnep_cb.p_conn_state_cb) { + (*bnep_cb.p_conn_state_cb)(p_bcb->handle, p_bcb->rem_bda, BNEP_SET_FILTER_FAIL, false); + } bnepu_release_bcb(p_bcb); return; @@ -643,10 +629,11 @@ void bnep_conn_timer_timeout(void* data) { void bnep_connected(tBNEP_CONN* p_bcb) { bool is_role_change; - if (p_bcb->con_flags & BNEP_FLAGS_CONN_COMPLETED) + if (p_bcb->con_flags & BNEP_FLAGS_CONN_COMPLETED) { is_role_change = true; - else + } else { is_role_change = false; + } p_bcb->con_state = BNEP_STATE_CONNECTED; p_bcb->con_flags |= BNEP_FLAGS_CONN_COMPLETED; @@ -657,7 +644,7 @@ void bnep_connected(tBNEP_CONN* p_bcb) { p_bcb->re_transmits = 0; /* Tell the upper layer, if there is a callback */ - if (bnep_cb.p_conn_state_cb) - (*bnep_cb.p_conn_state_cb)(p_bcb->handle, p_bcb->rem_bda, BNEP_SUCCESS, - is_role_change); + if (bnep_cb.p_conn_state_cb) { + (*bnep_cb.p_conn_state_cb)(p_bcb->handle, p_bcb->rem_bda, BNEP_SUCCESS, is_role_change); + } } diff --git a/system/stack/bnep/bnep_utils.cc b/system/stack/bnep/bnep_utils.cc index f1ccfc1d3b3..0dcccf06def 100644 --- a/system/stack/bnep/bnep_utils.cc +++ b/system/stack/bnep/bnep_utils.cc @@ -43,13 +43,10 @@ using bluetooth::Uuid; /******************************************************************************/ /* L O C A L F U N C T I O N P R O T O T Y P E S */ /******************************************************************************/ -static uint8_t* bnepu_init_hdr(BT_HDR* p_buf, uint16_t hdr_len, - uint8_t pkt_type); +static uint8_t* bnepu_init_hdr(BT_HDR* p_buf, uint16_t hdr_len, uint8_t pkt_type); -void bnepu_process_peer_multicast_filter_set(tBNEP_CONN* p_bcb, - uint8_t* p_filters, uint16_t len); -void bnepu_send_peer_multicast_filter_rsp(tBNEP_CONN* p_bcb, - uint16_t response_code); +void bnepu_process_peer_multicast_filter_set(tBNEP_CONN* p_bcb, uint8_t* p_filters, uint16_t len); +void bnepu_send_peer_multicast_filter_rsp(tBNEP_CONN* p_bcb, uint16_t response_code); /******************************************************************************* * @@ -67,12 +64,13 @@ tBNEP_CONN* bnepu_find_bcb_by_cid(uint16_t cid) { /* Look through each connection control block */ for (xx = 0, p_bcb = bnep_cb.bcb; xx < BNEP_MAX_CONNECTIONS; xx++, p_bcb++) { - if ((p_bcb->con_state != BNEP_STATE_IDLE) && (p_bcb->l2cap_cid == cid)) - return (p_bcb); + if ((p_bcb->con_state != BNEP_STATE_IDLE) && (p_bcb->l2cap_cid == cid)) { + return p_bcb; + } } /* If here, not found */ - return (NULL); + return NULL; } /******************************************************************************* @@ -92,12 +90,14 @@ tBNEP_CONN* bnepu_find_bcb_by_bd_addr(const RawAddress& p_bda) { /* Look through each connection control block */ for (xx = 0, p_bcb = bnep_cb.bcb; xx < BNEP_MAX_CONNECTIONS; xx++, p_bcb++) { if (p_bcb->con_state != BNEP_STATE_IDLE) { - if (p_bcb->rem_bda == p_bda) return (p_bcb); + if (p_bcb->rem_bda == p_bda) { + return p_bcb; + } } } /* If here, not found */ - return (NULL); + return NULL; } /******************************************************************************* @@ -124,12 +124,12 @@ tBNEP_CONN* bnepu_allocate_bcb(const RawAddress& p_rem_bda) { p_bcb->handle = xx + 1; p_bcb->xmit_q = fixed_queue_new(SIZE_MAX); - return (p_bcb); + return p_bcb; } } /* If here, no free BCB found */ - return (NULL); + return NULL; } /******************************************************************************* @@ -171,8 +171,7 @@ void bnep_send_conn_req(tBNEP_CONN* p_bcb) { BT_HDR* p_buf = (BT_HDR*)osi_malloc(BNEP_BUF_SIZE); uint8_t *p, *p_start; - log::verbose("sending setup req with dst uuid {}", - p_bcb->dst_uuid.ToString()); + log::verbose("sending setup req with dst uuid {}", p_bcb->dst_uuid.ToString()); p_buf->offset = L2CAP_MIN_OFFSET; p = p_start = (uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET; @@ -222,8 +221,7 @@ void bnep_send_conn_response(tBNEP_CONN* p_bcb, uint16_t resp_code) { BT_HDR* p_buf = (BT_HDR*)osi_malloc(BNEP_BUF_SIZE); uint8_t* p; - log::debug("BNEP - bnep_send_conn_response for CID: 0x{:x}", - p_bcb->l2cap_cid); + log::debug("BNEP - bnep_send_conn_response for CID: 0x{:x}", p_bcb->l2cap_cid); p_buf->offset = L2CAP_MIN_OFFSET; p = (uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET; @@ -279,8 +277,7 @@ void bnepu_send_peer_our_filters(tBNEP_CONN* p_bcb) { p_bcb->con_flags |= BNEP_FLAGS_FILTER_RESP_PEND; /* Start timer waiting for setup response */ - alarm_set_on_mloop(p_bcb->conn_timer, BNEP_FILTER_SET_TIMEOUT_MS, - bnep_conn_timer_timeout, p_bcb); + alarm_set_on_mloop(p_bcb->conn_timer, BNEP_FILTER_SET_TIMEOUT_MS, bnep_conn_timer_timeout, p_bcb); } /******************************************************************************* @@ -323,8 +320,7 @@ void bnepu_send_peer_our_multi_filters(tBNEP_CONN* p_bcb) { p_bcb->con_flags |= BNEP_FLAGS_MULTI_RESP_PEND; /* Start timer waiting for setup response */ - alarm_set_on_mloop(p_bcb->conn_timer, BNEP_FILTER_SET_TIMEOUT_MS, - bnep_conn_timer_timeout, p_bcb); + alarm_set_on_mloop(p_bcb->conn_timer, BNEP_FILTER_SET_TIMEOUT_MS, bnep_conn_timer_timeout, p_bcb); } /******************************************************************************* @@ -371,9 +367,8 @@ void bnep_send_command_not_understood(tBNEP_CONN* p_bcb, uint8_t cmd_code) { BT_HDR* p_buf = (BT_HDR*)osi_malloc(BNEP_BUF_SIZE); uint8_t* p; - log::verbose( - "BNEP - bnep_send_command_not_understood for CID: 0x{:x}, cmd 0x{:x}", - p_bcb->l2cap_cid, cmd_code); + log::verbose("BNEP - bnep_send_command_not_understood for CID: 0x{:x}, cmd 0x{:x}", + p_bcb->l2cap_cid, cmd_code); p_buf->offset = L2CAP_MIN_OFFSET; p = (uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET; @@ -403,12 +398,10 @@ void bnep_send_command_not_understood(tBNEP_CONN* p_bcb, uint8_t cmd_code) { * ******************************************************************************/ void bnepu_check_send_packet(tBNEP_CONN* p_bcb, BT_HDR* p_buf) { - log::debug("BNEP - bnepu_check_send_packet for CID: 0x{:x}", - p_bcb->l2cap_cid); + log::debug("BNEP - bnepu_check_send_packet for CID: 0x{:x}", p_bcb->l2cap_cid); if (p_bcb->con_flags & BNEP_FLAGS_L2CAP_CONGESTED) { if (fixed_queue_length(p_bcb->xmit_q) >= BNEP_MAX_XMITQ_DEPTH) { - log::warn("BNEP - congested, dropping buf, CID: 0x{:x}", - p_bcb->l2cap_cid); + log::warn("BNEP - congested, dropping buf, CID: 0x{:x}", p_bcb->l2cap_cid); osi_free(p_buf); } else { @@ -416,8 +409,8 @@ void bnepu_check_send_packet(tBNEP_CONN* p_bcb, BT_HDR* p_buf) { } } else { if (L2CA_DataWrite(p_bcb->l2cap_cid, p_buf) != tL2CAP_DW_RESULT::SUCCESS) { - log::warn("Unable to write L2CAP data peer:{} cid:{} len:{}", - p_bcb->rem_bda, p_bcb->l2cap_cid, p_buf->len); + log::warn("Unable to write L2CAP data peer:{} cid:{} len:{}", p_bcb->rem_bda, + p_bcb->l2cap_cid, p_buf->len); } } } @@ -434,8 +427,8 @@ void bnepu_check_send_packet(tBNEP_CONN* p_bcb, BT_HDR* p_buf) { * ******************************************************************************/ void bnepu_build_bnep_hdr(tBNEP_CONN* p_bcb, BT_HDR* p_buf, uint16_t protocol, - const RawAddress& src_addr, - const RawAddress& dest_addr, bool fw_ext_present) { + const RawAddress& src_addr, const RawAddress& dest_addr, + bool fw_ext_present) { uint8_t ext_bit, *p = (uint8_t*)NULL; uint8_t type = BNEP_FRAME_COMPRESSED_ETHERNET; RawAddress source_addr = src_addr; @@ -443,23 +436,22 @@ void bnepu_build_bnep_hdr(tBNEP_CONN* p_bcb, BT_HDR* p_buf, uint16_t protocol, ext_bit = fw_ext_present ? 0x80 : 0x00; if (source_addr != RawAddress::kEmpty && - source_addr != bluetooth::ToRawAddress( - bluetooth::shim::GetController()->GetMacAddress())) + source_addr != bluetooth::ToRawAddress(bluetooth::shim::GetController()->GetMacAddress())) { type = BNEP_FRAME_COMPRESSED_ETHERNET_SRC_ONLY; + } - if (dest_addr != p_bcb->rem_bda) - type = (type == BNEP_FRAME_COMPRESSED_ETHERNET) - ? BNEP_FRAME_COMPRESSED_ETHERNET_DEST_ONLY - : BNEP_FRAME_GENERAL_ETHERNET; + if (dest_addr != p_bcb->rem_bda) { + type = (type == BNEP_FRAME_COMPRESSED_ETHERNET) ? BNEP_FRAME_COMPRESSED_ETHERNET_DEST_ONLY + : BNEP_FRAME_GENERAL_ETHERNET; + } - if (source_addr == RawAddress::kEmpty) - source_addr = bluetooth::ToRawAddress( - bluetooth::shim::GetController()->GetMacAddress()); + if (source_addr == RawAddress::kEmpty) { + source_addr = bluetooth::ToRawAddress(bluetooth::shim::GetController()->GetMacAddress()); + } switch (type) { case BNEP_FRAME_GENERAL_ETHERNET: - p = bnepu_init_hdr(p_buf, 15, - (uint8_t)(ext_bit | BNEP_FRAME_GENERAL_ETHERNET)); + p = bnepu_init_hdr(p_buf, 15, (uint8_t)(ext_bit | BNEP_FRAME_GENERAL_ETHERNET)); memcpy(p, dest_addr.address, BD_ADDR_LEN); p += BD_ADDR_LEN; @@ -469,23 +461,18 @@ void bnepu_build_bnep_hdr(tBNEP_CONN* p_bcb, BT_HDR* p_buf, uint16_t protocol, break; case BNEP_FRAME_COMPRESSED_ETHERNET: - p = bnepu_init_hdr(p_buf, 3, - (uint8_t)(ext_bit | BNEP_FRAME_COMPRESSED_ETHERNET)); + p = bnepu_init_hdr(p_buf, 3, (uint8_t)(ext_bit | BNEP_FRAME_COMPRESSED_ETHERNET)); break; case BNEP_FRAME_COMPRESSED_ETHERNET_SRC_ONLY: - p = bnepu_init_hdr( - p_buf, 9, - (uint8_t)(ext_bit | BNEP_FRAME_COMPRESSED_ETHERNET_SRC_ONLY)); + p = bnepu_init_hdr(p_buf, 9, (uint8_t)(ext_bit | BNEP_FRAME_COMPRESSED_ETHERNET_SRC_ONLY)); memcpy(p, source_addr.address, BD_ADDR_LEN); p += BD_ADDR_LEN; break; case BNEP_FRAME_COMPRESSED_ETHERNET_DEST_ONLY: - p = bnepu_init_hdr( - p_buf, 9, - (uint8_t)(ext_bit | BNEP_FRAME_COMPRESSED_ETHERNET_DEST_ONLY)); + p = bnepu_init_hdr(p_buf, 9, (uint8_t)(ext_bit | BNEP_FRAME_COMPRESSED_ETHERNET_DEST_ONLY)); memcpy(p, dest_addr.address, BD_ADDR_LEN); p += BD_ADDR_LEN; @@ -504,15 +491,16 @@ void bnepu_build_bnep_hdr(tBNEP_CONN* p_bcb, BT_HDR* p_buf, uint16_t protocol, * Returns pointer to header in buffer * ******************************************************************************/ -static uint8_t* bnepu_init_hdr(BT_HDR* p_buf, uint16_t hdr_len, - uint8_t pkt_type) { +static uint8_t* bnepu_init_hdr(BT_HDR* p_buf, uint16_t hdr_len, uint8_t pkt_type) { uint8_t* p = (uint8_t*)(p_buf + 1) + p_buf->offset; /* See if we need to make space in the buffer */ if (p_buf->offset < (hdr_len + L2CAP_MIN_OFFSET)) { uint16_t xx, diff = BNEP_MINIMUM_OFFSET - p_buf->offset; p = p + p_buf->len - 1; - for (xx = 0; xx < p_buf->len; xx++, p--) p[diff] = *p; + for (xx = 0; xx < p_buf->len; xx++, p--) { + p[diff] = *p; + } p_buf->offset = BNEP_MINIMUM_OFFSET; p = (uint8_t*)(p_buf + 1) + p_buf->offset; @@ -524,7 +512,7 @@ static uint8_t* bnepu_init_hdr(BT_HDR* p_buf, uint16_t hdr_len, *p++ = pkt_type; - return (p); + return p; } /******************************************************************************* @@ -538,32 +526,26 @@ static uint8_t* bnepu_init_hdr(BT_HDR* p_buf, uint16_t hdr_len, * Returns void * ******************************************************************************/ -void bnep_process_setup_conn_req(tBNEP_CONN* p_bcb, uint8_t* p_setup, - uint8_t len) { +void bnep_process_setup_conn_req(tBNEP_CONN* p_bcb, uint8_t* p_setup, uint8_t len) { log::debug("BNEP - for CID: 0x{:x}", p_bcb->l2cap_cid); - if (p_bcb->con_state != BNEP_STATE_CONN_SETUP && - p_bcb->con_state != BNEP_STATE_SEC_CHECKING && + if (p_bcb->con_state != BNEP_STATE_CONN_SETUP && p_bcb->con_state != BNEP_STATE_SEC_CHECKING && p_bcb->con_state != BNEP_STATE_CONNECTED) { log::error("BNEP - setup request in bad state {}", p_bcb->con_state); bnep_send_conn_response(p_bcb, BNEP_SETUP_CONN_NOT_ALLOWED); return; } - /* Check if we already initiated security check or if waiting for user - * responce */ + /* Check if we already initiated security check or if waiting for user response */ if (p_bcb->con_flags & BNEP_FLAGS_SETUP_RCVD) { - log::warn( - "BNEP - Duplicate Setup message received while doing security check"); + log::warn("BNEP - Duplicate Setup message received while doing security check"); return; } /* Check if peer is the originator */ - if (p_bcb->con_state != BNEP_STATE_CONNECTED && - (!(p_bcb->con_flags & BNEP_FLAGS_SETUP_RCVD)) && + if (p_bcb->con_state != BNEP_STATE_CONNECTED && (!(p_bcb->con_flags & BNEP_FLAGS_SETUP_RCVD)) && (p_bcb->con_flags & BNEP_FLAGS_IS_ORIG)) { - log::error("BNEP - setup request when we are originator state:{}", - p_bcb->con_state); + log::error("BNEP - setup request when we are originator state:{}", p_bcb->con_state); bnep_send_conn_response(p_bcb, BNEP_SETUP_CONN_NOT_ALLOWED); return; } @@ -584,8 +566,7 @@ void bnep_process_setup_conn_req(tBNEP_CONN* p_bcb, uint8_t* p_setup, p_bcb->dst_uuid = Uuid::From16Bit(tmp); /* If nothing has changed don't bother the profile */ - if (p_bcb->con_state == BNEP_STATE_CONNECTED && - p_bcb->src_uuid == p_bcb->prv_src_uuid && + if (p_bcb->con_state == BNEP_STATE_CONNECTED && p_bcb->src_uuid == p_bcb->prv_src_uuid && p_bcb->dst_uuid == p_bcb->prv_dst_uuid) { bnep_send_conn_response(p_bcb, BNEP_SETUP_CONN_OK); return; @@ -620,7 +601,7 @@ void bnep_process_setup_conn_req(tBNEP_CONN* p_bcb, uint8_t* p_setup, /******************************************************************************* * - * Function bnep_process_setup_conn_responce + * Function bnep_process_setup_conn_response * * Description This function processes a peer's setup connection response * message. The response code is verified and @@ -629,11 +610,11 @@ void bnep_process_setup_conn_req(tBNEP_CONN* p_bcb, uint8_t* p_setup, * Returns void * ******************************************************************************/ -void bnep_process_setup_conn_responce(tBNEP_CONN* p_bcb, uint8_t* p_setup) { +void bnep_process_setup_conn_response(tBNEP_CONN* p_bcb, uint8_t* p_setup) { tBNEP_RESULT resp; uint16_t resp_code; - log::verbose("BNEP received setup responce"); + log::verbose("BNEP received setup response"); /* The state should be either SETUP or CONNECTED */ if (p_bcb->con_state != BNEP_STATE_CONN_SETUP) { /* Should we disconnect ? */ @@ -668,7 +649,7 @@ void bnep_process_setup_conn_responce(tBNEP_CONN* p_bcb, uint8_t* p_setup) { break; } - /* Check the responce code */ + /* Check the response code */ if (resp_code != BNEP_SETUP_CONN_OK) { if (p_bcb->con_flags & BNEP_FLAGS_CONN_COMPLETED) { log::verbose("BNEP - role change response is {}", resp_code); @@ -684,28 +665,30 @@ void bnep_process_setup_conn_responce(tBNEP_CONN* p_bcb, uint8_t* p_setup) { p_bcb->re_transmits = 0; /* Tell the user if there is a callback */ - if (bnep_cb.p_conn_state_cb) + if (bnep_cb.p_conn_state_cb) { (*bnep_cb.p_conn_state_cb)(p_bcb->handle, p_bcb->rem_bda, resp, true); + } return; } else { log::error("BNEP - setup response {} is not OK", resp_code); if (!L2CA_DisconnectReq(p_bcb->l2cap_cid)) { - log::warn("Unable to request L2CAP disconnect peer:{} cid:{}", - p_bcb->rem_bda, p_bcb->l2cap_cid); + log::warn("Unable to request L2CAP disconnect peer:{} cid:{}", p_bcb->rem_bda, + p_bcb->l2cap_cid); } /* Tell the user if there is a callback */ - if ((p_bcb->con_flags & BNEP_FLAGS_IS_ORIG) && (bnep_cb.p_conn_state_cb)) + if ((p_bcb->con_flags & BNEP_FLAGS_IS_ORIG) && (bnep_cb.p_conn_state_cb)) { (*bnep_cb.p_conn_state_cb)(p_bcb->handle, p_bcb->rem_bda, resp, false); + } bnepu_release_bcb(p_bcb); return; } } - /* Received successful responce */ + /* Received successful response */ bnep_connected(p_bcb); } @@ -720,70 +703,73 @@ void bnep_process_setup_conn_responce(tBNEP_CONN* p_bcb, uint8_t* p_setup) { * Returns void * ******************************************************************************/ -uint8_t* bnep_process_control_packet(tBNEP_CONN* p_bcb, uint8_t* p, - uint16_t* rem_len, bool is_ext) { +uint8_t* bnep_process_control_packet(tBNEP_CONN* p_bcb, uint8_t* p, uint16_t* rem_len, + bool is_ext) { uint8_t control_type; uint16_t len, ext_len = 0; if (p == NULL || rem_len == NULL) { - if (rem_len != NULL) *rem_len = 0; - log::verbose("invalid packet: p = {} rem_len = {}", fmt::ptr(p), - fmt::ptr(rem_len)); + if (rem_len != NULL) { + *rem_len = 0; + } + log::verbose("invalid packet: p = {} rem_len = {}", fmt::ptr(p), fmt::ptr(rem_len)); return NULL; } uint16_t rem_len_orig = *rem_len; if (is_ext) { - if (*rem_len < 1) goto bad_packet_length; + if (*rem_len < 1) { + goto bad_packet_length; + } ext_len = *p++; *rem_len = *rem_len - 1; } - if (*rem_len < 1) goto bad_packet_length; + if (*rem_len < 1) { + goto bad_packet_length; + } control_type = *p++; *rem_len = *rem_len - 1; - log::verbose( - "BNEP processing control packet rem_len {}, is_ext {}, ctrl_type {}", - *rem_len, is_ext, control_type); + log::verbose("BNEP processing control packet rem_len {}, is_ext {}, ctrl_type {}", *rem_len, + is_ext, control_type); switch (control_type) { case BNEP_CONTROL_COMMAND_NOT_UNDERSTOOD: if (*rem_len < 1) { - log::error( - "Received BNEP_CONTROL_COMMAND_NOT_UNDERSTOOD with bad length"); + log::error("Received BNEP_CONTROL_COMMAND_NOT_UNDERSTOOD with bad length"); goto bad_packet_length; } - log::error( - "Received BNEP_CONTROL_COMMAND_NOT_UNDERSTOOD for pkt type: {}", *p); + log::error("Received BNEP_CONTROL_COMMAND_NOT_UNDERSTOOD for pkt type: {}", *p); p++; *rem_len = *rem_len - 1; break; case BNEP_SETUP_CONNECTION_REQUEST_MSG: if (*rem_len < 1) { - log::error( - "Received BNEP_SETUP_CONNECTION_REQUEST_MSG with bad length"); + log::error("Received BNEP_SETUP_CONNECTION_REQUEST_MSG with bad length"); goto bad_packet_length; } len = *p++; if (*rem_len < ((2 * len) + 1)) { - log::error( - "Received BNEP_SETUP_CONNECTION_REQUEST_MSG with bad length"); + log::error("Received BNEP_SETUP_CONNECTION_REQUEST_MSG with bad length"); goto bad_packet_length; } - if (!is_ext) bnep_process_setup_conn_req(p_bcb, p, (uint8_t)len); + if (!is_ext) { + bnep_process_setup_conn_req(p_bcb, p, (uint8_t)len); + } p += (2 * len); *rem_len = *rem_len - (2 * len) - 1; break; case BNEP_SETUP_CONNECTION_RESPONSE_MSG: if (*rem_len < 2) { - log::error( - "Received BNEP_SETUP_CONNECTION_RESPONSE_MSG with bad length"); + log::error("Received BNEP_SETUP_CONNECTION_RESPONSE_MSG with bad length"); goto bad_packet_length; } - if (!is_ext) bnep_process_setup_conn_responce(p_bcb, p); + if (!is_ext) { + bnep_process_setup_conn_response(p_bcb, p); + } p += 2; *rem_len = *rem_len - 2; break; @@ -805,8 +791,7 @@ uint8_t* bnep_process_control_packet(tBNEP_CONN* p_bcb, uint8_t* p, case BNEP_FILTER_NET_TYPE_RESPONSE_MSG: if (*rem_len < 2) { - log::error( - "Received BNEP_FILTER_NET_TYPE_RESPONSE_MSG with bad length"); + log::error("Received BNEP_FILTER_NET_TYPE_RESPONSE_MSG with bad length"); goto bad_packet_length; } bnepu_process_peer_filter_rsp(p_bcb, p); @@ -831,8 +816,7 @@ uint8_t* bnep_process_control_packet(tBNEP_CONN* p_bcb, uint8_t* p, case BNEP_FILTER_MULTI_ADDR_RESPONSE_MSG: if (*rem_len < 2) { - log::error( - "Received BNEP_FILTER_MULTI_ADDR_RESPONSE_MSG with bad length"); + log::error("Received BNEP_FILTER_MULTI_ADDR_RESPONSE_MSG with bad length"); goto bad_packet_length; } bnepu_process_multicast_filter_rsp(p_bcb, p); @@ -855,8 +839,7 @@ uint8_t* bnep_process_control_packet(tBNEP_CONN* p_bcb, uint8_t* p, return p; bad_packet_length: - log::error("bad control packet length: original={} remaining={}", - rem_len_orig, *rem_len); + log::error("bad control packet length: original={} remaining={}", rem_len_orig, *rem_len); *rem_len = 0; return NULL; } @@ -872,8 +855,7 @@ bad_packet_length: * Returns void * ******************************************************************************/ -void bnepu_process_peer_filter_set(tBNEP_CONN* p_bcb, uint8_t* p_filters, - uint16_t len) { +void bnepu_process_peer_filter_set(tBNEP_CONN* p_bcb, uint8_t* p_filters, uint16_t len) { uint16_t num_filters = 0; uint16_t xx, resp_code = BNEP_FILTER_CRL_OK; uint16_t start, end; @@ -881,8 +863,7 @@ void bnepu_process_peer_filter_set(tBNEP_CONN* p_bcb, uint8_t* p_filters, if ((p_bcb->con_state != BNEP_STATE_CONNECTED) && (!(p_bcb->con_flags & BNEP_FLAGS_CONN_COMPLETED))) { - log::verbose( - "BNEP received filter set from peer when there is no connection"); + log::verbose("BNEP received filter set from peer when there is no connection"); return; } @@ -894,7 +875,9 @@ void bnepu_process_peer_filter_set(tBNEP_CONN* p_bcb, uint8_t* p_filters, return; } - if (len) num_filters = (uint16_t)(len >> 2); + if (len) { + num_filters = (uint16_t)(len >> 2); + } /* Validate filter values */ if (num_filters <= BNEP_MAX_PROT_FILTERS) { @@ -908,16 +891,18 @@ void bnepu_process_peer_filter_set(tBNEP_CONN* p_bcb, uint8_t* p_filters, break; } } - } else + } else { resp_code = BNEP_FILTER_CRL_MAX_REACHED; + } if (resp_code != BNEP_FILTER_CRL_OK) { bnepu_send_peer_filter_rsp(p_bcb, resp_code); return; } - if (bnep_cb.p_filter_ind_cb) + if (bnep_cb.p_filter_ind_cb) { (*bnep_cb.p_filter_ind_cb)(p_bcb->handle, true, 0, len, p_filters); + } p_bcb->rcvd_num_filters = num_filters; for (xx = 0; xx < num_filters; xx++) { @@ -945,7 +930,7 @@ void bnepu_process_peer_filter_rsp(tBNEP_CONN* p_bcb, uint8_t* p_data) { uint16_t resp_code; tBNEP_RESULT result; - log::verbose("BNEP received filter responce"); + log::verbose("BNEP received filter response"); /* The state should be CONNECTED */ if ((p_bcb->con_state != BNEP_STATE_CONNECTED) && (!(p_bcb->con_flags & BNEP_FLAGS_CONN_COMPLETED))) { @@ -967,10 +952,13 @@ void bnepu_process_peer_filter_rsp(tBNEP_CONN* p_bcb, uint8_t* p_data) { BE_STREAM_TO_UINT16(resp_code, p_data); result = BNEP_SUCCESS; - if (resp_code != BNEP_FILTER_CRL_OK) result = BNEP_SET_FILTER_FAIL; + if (resp_code != BNEP_FILTER_CRL_OK) { + result = BNEP_SET_FILTER_FAIL; + } - if (bnep_cb.p_filter_ind_cb) + if (bnep_cb.p_filter_ind_cb) { (*bnep_cb.p_filter_ind_cb)(p_bcb->handle, false, result, 0, NULL); + } } /******************************************************************************* @@ -987,12 +975,11 @@ void bnepu_process_multicast_filter_rsp(tBNEP_CONN* p_bcb, uint8_t* p_data) { uint16_t resp_code; tBNEP_RESULT result; - log::verbose("BNEP received multicast filter responce"); + log::verbose("BNEP received multicast filter response"); /* The state should be CONNECTED */ if ((p_bcb->con_state != BNEP_STATE_CONNECTED) && (!(p_bcb->con_flags & BNEP_FLAGS_CONN_COMPLETED))) { - log::error("BNEP - multicast filter response in bad state {}", - p_bcb->con_state); + log::error("BNEP - multicast filter response in bad state {}", p_bcb->con_state); return; } @@ -1010,10 +997,13 @@ void bnepu_process_multicast_filter_rsp(tBNEP_CONN* p_bcb, uint8_t* p_data) { BE_STREAM_TO_UINT16(resp_code, p_data); result = BNEP_SUCCESS; - if (resp_code != BNEP_FILTER_CRL_OK) result = BNEP_SET_FILTER_FAIL; + if (resp_code != BNEP_FILTER_CRL_OK) { + result = BNEP_SET_FILTER_FAIL; + } - if (bnep_cb.p_mfilter_ind_cb) + if (bnep_cb.p_mfilter_ind_cb) { (*bnep_cb.p_mfilter_ind_cb)(p_bcb->handle, false, result, 0, NULL); + } } /******************************************************************************* @@ -1027,8 +1017,7 @@ void bnepu_process_multicast_filter_rsp(tBNEP_CONN* p_bcb, uint8_t* p_data) { * Returns void * ******************************************************************************/ -void bnepu_process_peer_multicast_filter_set(tBNEP_CONN* p_bcb, - uint8_t* p_filters, uint16_t len) { +void bnepu_process_peer_multicast_filter_set(tBNEP_CONN* p_bcb, uint8_t* p_filters, uint16_t len) { uint16_t resp_code = BNEP_FILTER_CRL_OK; uint16_t num_filters, xx; uint8_t *p_temp_filters, null_bda[BD_ADDR_LEN] = {0, 0, 0, 0, 0, 0}; @@ -1036,8 +1025,8 @@ void bnepu_process_peer_multicast_filter_set(tBNEP_CONN* p_bcb, if ((p_bcb->con_state != BNEP_STATE_CONNECTED) && (!(p_bcb->con_flags & BNEP_FLAGS_CONN_COMPLETED))) { log::verbose( - "BNEP received multicast filter set from peer when there is no " - "connection"); + "BNEP received multicast filter set from peer when there is no " + "connection"); return; } @@ -1054,14 +1043,15 @@ void bnepu_process_peer_multicast_filter_set(tBNEP_CONN* p_bcb, } num_filters = 0; - if (len) num_filters = (uint16_t)(len / 12); + if (len) { + num_filters = (uint16_t)(len / 12); + } /* Validate filter values */ if (num_filters <= BNEP_MAX_MULTI_FILTERS) { p_temp_filters = p_filters; for (xx = 0; xx < num_filters; xx++) { - if (memcmp(p_temp_filters, p_temp_filters + BD_ADDR_LEN, BD_ADDR_LEN) > - 0) { + if (memcmp(p_temp_filters, p_temp_filters + BD_ADDR_LEN, BD_ADDR_LEN) > 0) { bnepu_send_peer_multicast_filter_rsp(p_bcb, BNEP_FILTER_CRL_BAD_RANGE); return; } @@ -1074,16 +1064,13 @@ void bnepu_process_peer_multicast_filter_set(tBNEP_CONN* p_bcb, p_temp_filters = p_filters; for (xx = 0; xx < num_filters; xx++) { memcpy(p_bcb->rcvd_mcast_filter_start[xx].address, p_temp_filters, BD_ADDR_LEN); - memcpy(p_bcb->rcvd_mcast_filter_end[xx].address, p_temp_filters + BD_ADDR_LEN, - BD_ADDR_LEN); + memcpy(p_bcb->rcvd_mcast_filter_end[xx].address, p_temp_filters + BD_ADDR_LEN, BD_ADDR_LEN); p_temp_filters += (BD_ADDR_LEN * 2); /* Check if any of the ranges have all zeros as both starting and ending * addresses */ - if ((memcmp(null_bda, p_bcb->rcvd_mcast_filter_start[xx].address, - BD_ADDR_LEN) == 0) && - (memcmp(null_bda, p_bcb->rcvd_mcast_filter_end[xx].address, - BD_ADDR_LEN) == 0)) { + if ((memcmp(null_bda, p_bcb->rcvd_mcast_filter_start[xx].address, BD_ADDR_LEN) == 0) && + (memcmp(null_bda, p_bcb->rcvd_mcast_filter_end[xx].address, BD_ADDR_LEN) == 0)) { p_bcb->rcvd_mcast_filters = 0xFFFF; break; } @@ -1092,8 +1079,9 @@ void bnepu_process_peer_multicast_filter_set(tBNEP_CONN* p_bcb, log::verbose("BNEP multicast filters {}", p_bcb->rcvd_mcast_filters); bnepu_send_peer_multicast_filter_rsp(p_bcb, resp_code); - if (bnep_cb.p_mfilter_ind_cb) + if (bnep_cb.p_mfilter_ind_cb) { (*bnep_cb.p_mfilter_ind_cb)(p_bcb->handle, true, 0, len, p_filters); + } } /******************************************************************************* @@ -1105,8 +1093,7 @@ void bnepu_process_peer_multicast_filter_set(tBNEP_CONN* p_bcb, * Returns void * ******************************************************************************/ -void bnepu_send_peer_multicast_filter_rsp(tBNEP_CONN* p_bcb, - uint16_t response_code) { +void bnepu_send_peer_multicast_filter_rsp(tBNEP_CONN* p_bcb, uint16_t response_code) { BT_HDR* p_buf = (BT_HDR*)osi_malloc(BNEP_BUF_SIZE); uint8_t* p; @@ -1138,21 +1125,20 @@ void bnepu_send_peer_multicast_filter_rsp(tBNEP_CONN* p_bcb, * Returns void * ******************************************************************************/ -void bnep_sec_check_complete(const RawAddress* bd_addr, tBT_TRANSPORT trasnport, - void* p_ref_data) { +void bnep_sec_check_complete(const RawAddress* bd_addr, tBT_TRANSPORT transport, void* p_ref_data) { tBNEP_CONN* p_bcb = (tBNEP_CONN*)p_ref_data; uint16_t resp_code = BNEP_SETUP_CONN_OK; bool is_role_change; - if (p_bcb->con_flags & BNEP_FLAGS_CONN_COMPLETED) + if (p_bcb->con_flags & BNEP_FLAGS_CONN_COMPLETED) { is_role_change = true; - else + } else { is_role_change = false; + } /* check if the port is still waiting for security to complete */ if (p_bcb->con_state != BNEP_STATE_SEC_CHECKING) { - log::error("BNEP Connection in wrong state {} when security is completed", - p_bcb->con_state); + log::error("BNEP Connection in wrong state {} when security is completed", p_bcb->con_state); return; } @@ -1163,15 +1149,14 @@ void bnep_sec_check_complete(const RawAddress* bd_addr, tBT_TRANSPORT trasnport, p_bcb->con_state = BNEP_STATE_CONN_SETUP; bnep_send_conn_req(p_bcb); - alarm_set_on_mloop(p_bcb->conn_timer, BNEP_CONN_TIMEOUT_MS, - bnep_conn_timer_timeout, p_bcb); + alarm_set_on_mloop(p_bcb->conn_timer, BNEP_CONN_TIMEOUT_MS, bnep_conn_timer_timeout, p_bcb); return; } if (bnep_cb.p_conn_ind_cb) { p_bcb->con_state = BNEP_STATE_CONN_SETUP; - (*bnep_cb.p_conn_ind_cb)(p_bcb->handle, p_bcb->rem_bda, p_bcb->dst_uuid, - p_bcb->src_uuid, is_role_change); + (*bnep_cb.p_conn_ind_cb)(p_bcb->handle, p_bcb->rem_bda, p_bcb->dst_uuid, p_bcb->src_uuid, + is_role_change); } else { /* Profile didn't register connection indication call back */ bnep_send_conn_response(p_bcb, resp_code); @@ -1190,10 +1175,9 @@ void bnep_sec_check_complete(const RawAddress* bd_addr, tBT_TRANSPORT trasnport, * BNEP_IGNORE_CMD - if the protocol is filtered out * ******************************************************************************/ -tBNEP_RESULT bnep_is_packet_allowed(tBNEP_CONN* p_bcb, - const RawAddress& dest_addr, - uint16_t protocol, bool fw_ext_present, - uint8_t* p_data, uint16_t org_len) { +tBNEP_RESULT bnep_is_packet_allowed(tBNEP_CONN* p_bcb, const RawAddress& dest_addr, + uint16_t protocol, bool fw_ext_present, uint8_t* p_data, + uint16_t org_len) { if (p_bcb->rcvd_num_filters) { uint16_t i, proto; @@ -1226,8 +1210,9 @@ tBNEP_RESULT bnep_is_packet_allowed(tBNEP_CONN* p_bcb, for (i = 0; i < p_bcb->rcvd_num_filters; i++) { if ((p_bcb->rcvd_prot_filter_start[i] <= proto) && - (proto <= p_bcb->rcvd_prot_filter_end[i])) + (proto <= p_bcb->rcvd_prot_filter_end[i])) { break; + } } if (i == p_bcb->rcvd_num_filters) { @@ -1236,7 +1221,7 @@ tBNEP_RESULT bnep_is_packet_allowed(tBNEP_CONN* p_bcb, } } - /* Ckeck for multicast address filtering */ + /* Check for multicast address filtering */ if ((dest_addr.address[0] & 0x01) && p_bcb->rcvd_mcast_filters) { uint16_t i; @@ -1244,11 +1229,12 @@ tBNEP_RESULT bnep_is_packet_allowed(tBNEP_CONN* p_bcb, if (p_bcb->rcvd_mcast_filters != 0xFFFF) { /* Check if the address is mentioned in the filter range */ for (i = 0; i < p_bcb->rcvd_mcast_filters; i++) { - if ((memcmp(p_bcb->rcvd_mcast_filter_start[i].address, - dest_addr.address, BD_ADDR_LEN) <= 0) && - (memcmp(p_bcb->rcvd_mcast_filter_end[i].address, dest_addr.address, - BD_ADDR_LEN) >= 0)) + if ((memcmp(p_bcb->rcvd_mcast_filter_start[i].address, dest_addr.address, BD_ADDR_LEN) <= + 0) && + (memcmp(p_bcb->rcvd_mcast_filter_end[i].address, dest_addr.address, BD_ADDR_LEN) >= + 0)) { break; + } } } @@ -1257,10 +1243,8 @@ tBNEP_RESULT bnep_is_packet_allowed(tBNEP_CONN* p_bcb, *range ** drop the packet */ - if ((p_bcb->rcvd_mcast_filters == 0xFFFF) || - (i == p_bcb->rcvd_mcast_filters)) { - log::verbose("Ignoring multicast address {} in BNEP data write", - dest_addr); + if ((p_bcb->rcvd_mcast_filters == 0xFFFF) || (i == p_bcb->rcvd_mcast_filters)) { + log::verbose("Ignoring multicast address {} in BNEP data write", dest_addr); return BNEP_IGNORE_CMD; } } diff --git a/system/stack/btm/ble_scanner_hci_interface.cc b/system/stack/btm/ble_scanner_hci_interface.cc index 9f43ba74637..9756caa164d 100644 --- a/system/stack/btm/ble_scanner_hci_interface.cc +++ b/system/stack/btm/ble_scanner_hci_interface.cc @@ -33,8 +33,7 @@ using namespace bluetooth; namespace { BleScannerHciInterface* instance = nullptr; -static void status_callback(base::Callback cb, uint8_t* data, - uint16_t len) { +static void status_callback(base::Callback cb, uint8_t* data, uint16_t len) { uint8_t status; log::assert_that(len == 1, "Received bad response length: {}", len); @@ -43,13 +42,12 @@ static void status_callback(base::Callback cb, uint8_t* data, cb.Run(status); } -static void status_handle_callback(base::Callback cb, - uint8_t* data, uint16_t len) { +static void status_handle_callback(base::Callback cb, uint8_t* data, + uint16_t len) { uint8_t status; uint16_t handle = HCI_INVALID_HANDLE; - log::assert_that((len > 0) && (len < 4), "Received bad response length: {}", - len); + log::assert_that((len > 0) && (len < 4), "Received bad response length: {}", len); uint8_t* pp = data; STREAM_TO_UINT8(status, pp); @@ -74,69 +72,62 @@ static void status_handle_callback(base::Callback cb, * controller's list of supported features. */ class BleScannerImplBase : public BleScannerHciInterface { - public: +public: void SetScanEventObserver(ScanEventObserver* observer) override { // TODO: Support multiple observers if ever needed. scan_event_observer = observer; } void PeriodicScanStart(uint8_t options, uint8_t set_id, uint8_t adv_addr_type, - const RawAddress& adv_addr, uint16_t skip_num, - uint16_t sync_timeout, + const RawAddress& adv_addr, uint16_t skip_num, uint16_t sync_timeout, uint8_t sync_cte_type) override { - btsnd_hcic_ble_periodic_advertising_create_sync( - options, set_id, adv_addr_type, adv_addr, skip_num, sync_timeout, - sync_cte_type); + btsnd_hcic_ble_periodic_advertising_create_sync(options, set_id, adv_addr_type, adv_addr, + skip_num, sync_timeout, sync_cte_type); } void PeriodicScanCancelStart(status_cb command_complete) override { btsnd_hcic_ble_periodic_advertising_create_sync_cancel( - base::Bind(&status_callback, std::move(command_complete))); + base::Bind(&status_callback, std::move(command_complete))); } - void PeriodicScanTerminate(uint16_t sync_handle, - status_cb command_complete) override { + void PeriodicScanTerminate(uint16_t sync_handle, status_cb command_complete) override { btsnd_hcic_ble_periodic_advertising_terminate_sync( - sync_handle, base::Bind(&status_callback, std::move(command_complete))); + sync_handle, base::Bind(&status_callback, std::move(command_complete))); } void PeriodicScanResultEvtEnable(uint16_t sync_handle, bool enable, status_cb command_complete) override { btsnd_hcic_ble_set_periodic_advertising_receive_enable( - sync_handle, enable, - base::Bind(&status_callback, std::move(command_complete))); + sync_handle, enable, base::Bind(&status_callback, std::move(command_complete))); } void PeriodicAdvertiserListGetSize( - BleScannerHciInterface::list_size_cb command_complete) override { - command_complete.Run( - bluetooth::shim::GetController()->GetLePeriodicAdvertiserListSize()); + BleScannerHciInterface::list_size_cb command_complete) override { + command_complete.Run(bluetooth::shim::GetController()->GetLePeriodicAdvertiserListSize()); } - void PeriodicAdvertiserListAddDevice(uint8_t adv_addr_type, - RawAddress& adv_addr, uint8_t set_id, + void PeriodicAdvertiserListAddDevice(uint8_t adv_addr_type, RawAddress& adv_addr, uint8_t set_id, status_cb command_complete) override { btsnd_hci_ble_add_device_to_periodic_advertiser_list( - adv_addr_type, adv_addr, set_id, - base::Bind(&status_callback, std::move(command_complete))); + adv_addr_type, adv_addr, set_id, + base::Bind(&status_callback, std::move(command_complete))); } - void PeriodicAdvertiserListRemoveDevice(uint8_t adv_addr_type, - RawAddress& adv_addr, uint8_t set_id, - status_cb command_complete) override { + void PeriodicAdvertiserListRemoveDevice(uint8_t adv_addr_type, RawAddress& adv_addr, + uint8_t set_id, status_cb command_complete) override { btsnd_hci_ble_remove_device_from_periodic_advertiser_list( - adv_addr_type, adv_addr, set_id, - base::Bind(&status_callback, std::move(command_complete))); + adv_addr_type, adv_addr, set_id, + base::Bind(&status_callback, std::move(command_complete))); } void PeriodicAdvertiserListClear(status_cb command_complete) override { btsnd_hci_ble_clear_periodic_advertiser_list( - base::Bind(&status_callback, std::move(command_complete))); - }; + base::Bind(&status_callback, std::move(command_complete))); + } - void PeriodicAdvSyncTransfer( - const RawAddress& bd_addr, uint16_t service_data, uint16_t sync_handle, - BleScannerHciInterface::handle_cb command_complete) override { + void PeriodicAdvSyncTransfer(const RawAddress& bd_addr, uint16_t service_data, + uint16_t sync_handle, + BleScannerHciInterface::handle_cb command_complete) override { uint16_t acl_handle = get_btm_client_interface().peer.BTM_GetHCIConnHandle(bd_addr, BT_TRANSPORT_LE); @@ -146,13 +137,12 @@ class BleScannerImplBase : public BleScannerHciInterface { } btsnd_hcic_ble_periodic_advertising_sync_transfer( - acl_handle, service_data, sync_handle, - base::Bind(&status_handle_callback, std::move(command_complete))); + acl_handle, service_data, sync_handle, + base::Bind(&status_handle_callback, std::move(command_complete))); } - void PeriodicAdvSetInfoTransfer(const RawAddress& bd_addr, - uint16_t service_data, uint8_t adv_handle, - handle_cb command_complete) override { + void PeriodicAdvSetInfoTransfer(const RawAddress& bd_addr, uint16_t service_data, + uint8_t adv_handle, handle_cb command_complete) override { uint16_t acl_handle = get_btm_client_interface().peer.BTM_GetHCIConnHandle(bd_addr, BT_TRANSPORT_LE); @@ -162,13 +152,12 @@ class BleScannerImplBase : public BleScannerHciInterface { } btsnd_hcic_ble_periodic_advertising_set_info_transfer( - acl_handle, service_data, adv_handle, - base::Bind(&status_handle_callback, std::move(command_complete))); + acl_handle, service_data, adv_handle, + base::Bind(&status_handle_callback, std::move(command_complete))); } - void SetPeriodicAdvSyncTransferParams(const RawAddress& bd_addr, uint8_t mode, - uint16_t skip, uint16_t sync_timeout, - uint8_t cte_type, bool set_defaults, + void SetPeriodicAdvSyncTransferParams(const RawAddress& bd_addr, uint8_t mode, uint16_t skip, + uint16_t sync_timeout, uint8_t cte_type, bool set_defaults, status_cb command_complete) override { uint16_t acl_handle = get_btm_client_interface().peer.BTM_GetHCIConnHandle(bd_addr, BT_TRANSPORT_LE); @@ -178,76 +167,73 @@ class BleScannerImplBase : public BleScannerHciInterface { return; } - if (set_defaults) + if (set_defaults) { btsnd_hcic_ble_set_default_periodic_advertising_sync_transfer_params( - acl_handle, mode, skip, sync_timeout, cte_type, - base::Bind(&status_callback, std::move(command_complete))); - else + acl_handle, mode, skip, sync_timeout, cte_type, + base::Bind(&status_callback, std::move(command_complete))); + } else { btsnd_hcic_ble_set_periodic_advertising_sync_transfer_params( - acl_handle, mode, skip, sync_timeout, cte_type, - base::Bind(&status_callback, std::move(command_complete))); + acl_handle, mode, skip, sync_timeout, cte_type, + base::Bind(&status_callback, std::move(command_complete))); + } } - void OnPeriodicAdvSyncEstablished(uint8_t status, uint16_t sync_handle, - uint8_t adv_sid, uint8_t adv_addr_type, - RawAddress adv_addr, uint8_t adv_phy, - uint16_t adv_interval, - uint8_t adv_clock_accuracy) { + void OnPeriodicAdvSyncEstablished(uint8_t status, uint16_t sync_handle, uint8_t adv_sid, + uint8_t adv_addr_type, RawAddress adv_addr, uint8_t adv_phy, + uint16_t adv_interval, uint8_t adv_clock_accuracy) { if (scan_event_observer) { - scan_event_observer->OnPeriodicScanEstablished( - status, sync_handle, adv_sid, adv_addr_type, adv_addr, adv_phy, - adv_interval, adv_clock_accuracy); + scan_event_observer->OnPeriodicScanEstablished(status, sync_handle, adv_sid, adv_addr_type, + adv_addr, adv_phy, adv_interval, + adv_clock_accuracy); } } - void OnPeriodicScanResult(uint16_t sync_handle, uint8_t tx_power, int8_t rssi, - uint8_t cte_type, uint8_t pkt_data_status, - uint8_t pkt_data_len, const uint8_t* p_pkt_data) { + void OnPeriodicScanResult(uint16_t sync_handle, uint8_t tx_power, int8_t rssi, uint8_t cte_type, + uint8_t pkt_data_status, uint8_t pkt_data_len, + const uint8_t* p_pkt_data) { // The observer should handle the caching and reassembly of the fragmented // packet. if (scan_event_observer) { - scan_event_observer->OnPeriodicScanResult(sync_handle, tx_power, rssi, - cte_type, pkt_data_status, - pkt_data_len, p_pkt_data); + scan_event_observer->OnPeriodicScanResult(sync_handle, tx_power, rssi, cte_type, + pkt_data_status, pkt_data_len, p_pkt_data); } } void OnPeriodicSyncLost(uint16_t sync_handle) { - if (scan_event_observer) + if (scan_event_observer) { scan_event_observer->OnPeriodicScanLost(sync_handle); + } } - private: +private: ScanEventObserver* scan_event_observer = nullptr; }; class BleScannerListImpl : public virtual BleScannerImplBase { - void PeriodicAdvertiserListAddDevice(uint8_t adv_addr_type, - RawAddress& adv_addr, uint8_t set_id, + void PeriodicAdvertiserListAddDevice(uint8_t adv_addr_type, RawAddress& adv_addr, uint8_t set_id, status_cb command_complete) override { btsnd_hci_ble_add_device_to_periodic_advertiser_list( - adv_addr_type, adv_addr, set_id, - base::Bind(&status_callback, std::move(command_complete))); + adv_addr_type, adv_addr, set_id, + base::Bind(&status_callback, std::move(command_complete))); } - void PeriodicAdvertiserListRemoveDevice(uint8_t adv_addr_type, - RawAddress& adv_addr, uint8_t set_id, - status_cb command_complete) override { + void PeriodicAdvertiserListRemoveDevice(uint8_t adv_addr_type, RawAddress& adv_addr, + uint8_t set_id, status_cb command_complete) override { btsnd_hci_ble_remove_device_from_periodic_advertiser_list( - adv_addr_type, adv_addr, set_id, - base::Bind(&status_callback, std::move(command_complete))); + adv_addr_type, adv_addr, set_id, + base::Bind(&status_callback, std::move(command_complete))); } void PeriodicAdvertiserListClear(status_cb command_complete) override { btsnd_hci_ble_clear_periodic_advertiser_list( - base::Bind(&status_callback, std::move(command_complete))); - }; + base::Bind(&status_callback, std::move(command_complete))); + } }; class BleScannerSyncTransferImpl : public virtual BleScannerImplBase { - void PeriodicAdvSyncTransfer( - const RawAddress& bd_addr, uint16_t service_data, uint16_t sync_handle, - BleScannerHciInterface::handle_cb command_complete) override { + void PeriodicAdvSyncTransfer(const RawAddress& bd_addr, uint16_t service_data, + uint16_t sync_handle, + BleScannerHciInterface::handle_cb command_complete) override { uint16_t acl_handle = get_btm_client_interface().peer.BTM_GetHCIConnHandle(bd_addr, BT_TRANSPORT_LE); @@ -257,13 +243,12 @@ class BleScannerSyncTransferImpl : public virtual BleScannerImplBase { } btsnd_hcic_ble_periodic_advertising_sync_transfer( - acl_handle, service_data, sync_handle, - base::Bind(&status_handle_callback, std::move(command_complete))); + acl_handle, service_data, sync_handle, + base::Bind(&status_handle_callback, std::move(command_complete))); } - void PeriodicAdvSetInfoTransfer(const RawAddress& bd_addr, - uint16_t service_data, uint8_t adv_handle, - handle_cb command_complete) override { + void PeriodicAdvSetInfoTransfer(const RawAddress& bd_addr, uint16_t service_data, + uint8_t adv_handle, handle_cb command_complete) override { uint16_t acl_handle = get_btm_client_interface().peer.BTM_GetHCIConnHandle(bd_addr, BT_TRANSPORT_LE); @@ -273,13 +258,12 @@ class BleScannerSyncTransferImpl : public virtual BleScannerImplBase { } btsnd_hcic_ble_periodic_advertising_set_info_transfer( - acl_handle, service_data, adv_handle, - base::Bind(&status_handle_callback, std::move(command_complete))); + acl_handle, service_data, adv_handle, + base::Bind(&status_handle_callback, std::move(command_complete))); } - void SetPeriodicAdvSyncTransferParams(const RawAddress& bd_addr, uint8_t mode, - uint16_t skip, uint16_t sync_timeout, - uint8_t cte_type, bool set_defaults, + void SetPeriodicAdvSyncTransferParams(const RawAddress& bd_addr, uint8_t mode, uint16_t skip, + uint16_t sync_timeout, uint8_t cte_type, bool set_defaults, status_cb command_complete) override { uint16_t acl_handle = get_btm_client_interface().peer.BTM_GetHCIConnHandle(bd_addr, BT_TRANSPORT_LE); @@ -289,19 +273,19 @@ class BleScannerSyncTransferImpl : public virtual BleScannerImplBase { return; } - if (set_defaults) + if (set_defaults) { btsnd_hcic_ble_set_default_periodic_advertising_sync_transfer_params( - acl_handle, mode, skip, sync_timeout, cte_type, - base::Bind(&status_callback, std::move(command_complete))); - else + acl_handle, mode, skip, sync_timeout, cte_type, + base::Bind(&status_callback, std::move(command_complete))); + } else { btsnd_hcic_ble_set_periodic_advertising_sync_transfer_params( - acl_handle, mode, skip, sync_timeout, cte_type, - base::Bind(&status_callback, std::move(command_complete))); + acl_handle, mode, skip, sync_timeout, cte_type, + base::Bind(&status_callback, std::move(command_complete))); + } } }; -class BleScannerCompleteImpl : public BleScannerListImpl, - public BleScannerSyncTransferImpl { +class BleScannerCompleteImpl : public BleScannerListImpl, public BleScannerSyncTransferImpl { // Not much to do here :) }; @@ -311,17 +295,14 @@ void BleScannerHciInterface::Initialize() { log::assert_that(instance == nullptr, "Was already initialized."); if ((bluetooth::shim::GetController()->GetLePeriodicAdvertiserListSize()) && - (bluetooth::shim::GetController() - ->SupportsBlePeriodicAdvertisingSyncTransferSender())) { + (bluetooth::shim::GetController()->SupportsBlePeriodicAdvertisingSyncTransferSender())) { log::info("Advertiser list in controller can be used"); log::info("Periodic Adv Sync Transfer Sender role is supported"); instance = new BleScannerCompleteImpl(); - } else if (bluetooth::shim::GetController() - ->SupportsBlePeriodicAdvertisingSyncTransferSender()) { + } else if (bluetooth::shim::GetController()->SupportsBlePeriodicAdvertisingSyncTransferSender()) { log::info("Periodic Adv Sync Transfer Sender role is supported"); instance = new BleScannerSyncTransferImpl(); - } else if (bluetooth::shim::GetController() - ->GetLePeriodicAdvertiserListSize()) { + } else if (bluetooth::shim::GetController()->GetLePeriodicAdvertiserListSize()) { log::info("Periodic Adv Sync Transfer Recipient role is supported"); instance = new BleScannerListImpl(); } diff --git a/system/stack/btm/ble_scanner_hci_interface.h b/system/stack/btm/ble_scanner_hci_interface.h index 7a2e19910d1..16f0b4c5196 100644 --- a/system/stack/btm/ble_scanner_hci_interface.h +++ b/system/stack/btm/ble_scanner_hci_interface.h @@ -25,11 +25,10 @@ #include "types/raw_address.h" class BleScannerHciInterface { - public: +public: using status_cb = base::Callback; using list_size_cb = base::Callback; - using handle_cb = - base::Callback; + using handle_cb = base::Callback; static void Initialize(); static BleScannerHciInterface* Get(); @@ -38,17 +37,15 @@ class BleScannerHciInterface { virtual ~BleScannerHciInterface() = default; class ScanEventObserver { - public: + public: virtual ~ScanEventObserver() = default; - virtual void OnPeriodicScanResult(uint16_t sync_handle, uint8_t tx_power, - int8_t rssi, uint8_t cte_type, - uint8_t pkt_data_status, - uint8_t pkt_data_len, - const uint8_t* pkt_data) = 0; - virtual void OnPeriodicScanEstablished( - uint8_t status, uint16_t sync_handle, uint8_t set_id, - uint8_t adv_addr_type, const RawAddress& adv_addr, uint8_t adv_phy, - uint16_t adv_interval, uint8_t adv_clock_accuracy) = 0; + virtual void OnPeriodicScanResult(uint16_t sync_handle, uint8_t tx_power, int8_t rssi, + uint8_t cte_type, uint8_t pkt_data_status, + uint8_t pkt_data_len, const uint8_t* pkt_data) = 0; + virtual void OnPeriodicScanEstablished(uint8_t status, uint16_t sync_handle, uint8_t set_id, + uint8_t adv_addr_type, const RawAddress& adv_addr, + uint8_t adv_phy, uint16_t adv_interval, + uint8_t adv_clock_accuracy) = 0; virtual void OnPeriodicScanLost(uint16_t sync_handle) = 0; }; @@ -77,11 +74,9 @@ class BleScannerHciInterface { * bit 4: do not sync to packets without a Constant Tone Extension, all other * bits: reserved for future use. */ - virtual void PeriodicScanStart(uint8_t options, uint8_t set_id, - uint8_t adv_addr_type, + virtual void PeriodicScanStart(uint8_t options, uint8_t set_id, uint8_t adv_addr_type, const RawAddress& adv_addr, uint16_t skip_num, - uint16_t sync_timeout, - uint8_t sync_cte_type) = 0; + uint16_t sync_timeout, uint8_t sync_cte_type) = 0; /** * Used to cancel the HCI_LE_Periodic_Advertising_Create_Sync command while it @@ -108,8 +103,7 @@ class BleScannerHciInterface { * @param enable whether enable or disable the advertising reports * @param cb status callback */ - virtual void PeriodicScanResultEvtEnable(uint16_t sync_handle, bool enable, - status_cb cb) = 0; + virtual void PeriodicScanResultEvtEnable(uint16_t sync_handle, bool enable, status_cb cb) = 0; /** * Used to add an entry, consisting of a single device address and SID, to the @@ -123,10 +117,8 @@ class BleScannerHciInterface { * @param adv_sid advertising set ID * @param cb status callback */ - virtual void PeriodicAdvertiserListAddDevice(uint8_t adv_addr_type, - RawAddress& adv_addr, - uint8_t adv_sid, - status_cb cb) = 0; + virtual void PeriodicAdvertiserListAddDevice(uint8_t adv_addr_type, RawAddress& adv_addr, + uint8_t adv_sid, status_cb cb) = 0; /** * Remove one entry from the list of Periodic Advertisers stored in the * Controller. Removals from the Periodic Advertisers List take effect @@ -137,10 +129,8 @@ class BleScannerHciInterface { * @param adv_sid advertising set ID * @param cb status callback */ - virtual void PeriodicAdvertiserListRemoveDevice(uint8_t adv_addr_type, - RawAddress& adv_addr, - uint8_t adv_sid, - status_cb cb) = 0; + virtual void PeriodicAdvertiserListRemoveDevice(uint8_t adv_addr_type, RawAddress& adv_addr, + uint8_t adv_sid, status_cb cb) = 0; /** * Remove all entries from the list of Periodic Advertisers in the Controller. @@ -167,8 +157,7 @@ class BleScannerHciInterface { * @param sync_handle synced advewrtising handle * @param cb status and connection handle callback */ - virtual void PeriodicAdvSyncTransfer(const RawAddress& bd_addr, - uint16_t service_data, + virtual void PeriodicAdvSyncTransfer(const RawAddress& bd_addr, uint16_t service_data, uint16_t sync_handle, handle_cb cb) = 0; /** @@ -181,10 +170,8 @@ class BleScannerHciInterface { * @param sync_handle synced advertising handle * @param cb status and connection handle callback */ - virtual void PeriodicAdvSetInfoTransfer(const RawAddress& bd_addr, - uint16_t service_data, - uint8_t sync_handle, - handle_cb cb) = 0; + virtual void PeriodicAdvSetInfoTransfer(const RawAddress& bd_addr, uint16_t service_data, + uint8_t sync_handle, handle_cb cb) = 0; /** * Specify how the Controller will process periodic advertising @@ -216,11 +203,9 @@ class BleScannerHciInterface { * HCI_LE_SET_PERIODIC_ADVERTISING_SYNC_TRANSFER_PARAM. * @param cb status callback */ - virtual void SetPeriodicAdvSyncTransferParams(const RawAddress& bd_addr, - uint8_t mode, uint16_t skip, - uint16_t sync_timeout, - uint8_t cte_type, - bool set_defaults, + virtual void SetPeriodicAdvSyncTransferParams(const RawAddress& bd_addr, uint8_t mode, + uint16_t skip, uint16_t sync_timeout, + uint8_t cte_type, bool set_defaults, status_cb cb) = 0; static constexpr uint8_t kOptUseAdvertiserList = 0x01; diff --git a/system/stack/btm/btm_ble.cc b/system/stack/btm/btm_ble.cc index 12dc5ecebb6..6a5116299c8 100644 --- a/system/stack/btm/btm_ble.cc +++ b/system/stack/btm/btm_ble.cc @@ -75,8 +75,7 @@ void BTM_BleReceiverTest(uint8_t rx_freq, tBTM_CMPL_CB* p_cmd_cmpl_cback) { * p_cmd_cmpl_cback - Command Complete callback * ******************************************************************************/ -void BTM_BleTransmitterTest(uint8_t tx_freq, uint8_t test_data_len, - uint8_t packet_payload, +void BTM_BleTransmitterTest(uint8_t tx_freq, uint8_t test_data_len, uint8_t packet_payload, tBTM_CMPL_CB* p_cmd_cmpl_cback) { btm_cb.devcb.p_le_test_cmd_cmpl_cb = p_cmd_cmpl_cback; btsnd_hcic_ble_transmitter_test(tx_freq, test_data_len, packet_payload); @@ -131,12 +130,11 @@ bool BTM_UseLeLink(const RawAddress& bd_addr) { tBT_DEVICE_TYPE dev_type; tBLE_ADDR_TYPE addr_type; BTM_ReadDevInfo(bd_addr, &dev_type, &addr_type); - return (dev_type == BT_DEVICE_TYPE_BLE); + return dev_type == BT_DEVICE_TYPE_BLE; } -void read_phy_cb( - base::Callback cb, - uint8_t* data, uint16_t len) { +void read_phy_cb(base::Callback cb, + uint8_t* data, uint16_t len) { uint8_t status, tx_phy, rx_phy; uint16_t handle; @@ -164,9 +162,8 @@ void read_phy_cb( * BTM_WRONG_MODE if Device in wrong mode for request. * ******************************************************************************/ -void BTM_BleReadPhy( - const RawAddress& bd_addr, - base::Callback cb) { +void BTM_BleReadPhy(const RawAddress& bd_addr, + base::Callback cb) { if (!BTM_IsAclConnectionUp(bd_addr, BT_TRANSPORT_LE)) { log::error("Wrong mode: no LE link exist or LE not supported"); cb.Run(0, 0, HCI_ERR_NO_CONNECTION); @@ -197,32 +194,34 @@ void BTM_BleSetPhy(const RawAddress& bd_addr, uint8_t tx_phys, uint8_t rx_phys, uint16_t phy_options) { if (!BTM_IsAclConnectionUp(bd_addr, BT_TRANSPORT_LE)) { log::info( - "Unable to set phy preferences because no le acl is connected to " - "device"); + "Unable to set phy preferences because no le acl is connected to " + "device"); return; } uint8_t all_phys = 0; - if (tx_phys == 0) all_phys &= 0x01; - if (rx_phys == 0) all_phys &= 0x02; + if (tx_phys == 0) { + all_phys &= 0x01; + } + if (rx_phys == 0) { + all_phys &= 0x02; + } uint16_t handle = get_btm_client_interface().peer.BTM_GetHCIConnHandle(bd_addr, BT_TRANSPORT_LE); // checking if local controller supports it! if (!bluetooth::shim::GetController()->SupportsBle2mPhy() && !bluetooth::shim::GetController()->SupportsBleCodedPhy()) { - log::info( - "Local controller unable to support setting of le phy parameters"); - gatt_notify_phy_updated(static_cast(GATT_REQ_NOT_SUPPORTED), - handle, tx_phys, rx_phys); + log::info("Local controller unable to support setting of le phy parameters"); + gatt_notify_phy_updated(static_cast(GATT_REQ_NOT_SUPPORTED), handle, tx_phys, + rx_phys); return; } - if (!acl_peer_supports_ble_2m_phy(handle) && - !acl_peer_supports_ble_coded_phy(handle)) { + if (!acl_peer_supports_ble_2m_phy(handle) && !acl_peer_supports_ble_coded_phy(handle)) { log::info("Remote device unable to support setting of le phy parameter"); - gatt_notify_phy_updated(static_cast(GATT_REQ_NOT_SUPPORTED), - handle, tx_phys, rx_phys); + gatt_notify_phy_updated(static_cast(GATT_REQ_NOT_SUPPORTED), handle, tx_phys, + rx_phys); return; } @@ -234,6 +233,5 @@ void BTM_BleSetPhy(const RawAddress& bd_addr, uint8_t tx_phys, uint8_t rx_phys, UINT8_TO_STREAM(pp, tx_phys); UINT8_TO_STREAM(pp, rx_phys); UINT16_TO_STREAM(pp, phy_options); - btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_BLE_SET_PHY, data, len, - base::Bind(doNothing)); + btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_BLE_SET_PHY, data, len, base::Bind(doNothing)); } diff --git a/system/stack/btm/btm_ble_addr.cc b/system/stack/btm/btm_ble_addr.cc index df55826adb1..308a69cd85b 100644 --- a/system/stack/btm/btm_ble_addr.cc +++ b/system/stack/btm/btm_ble_addr.cc @@ -62,8 +62,7 @@ extern tBTM_CB btm_cb; * Returns true is updated; false otherwise. * ******************************************************************************/ -bool btm_ble_init_pseudo_addr(tBTM_SEC_DEV_REC* p_dev_rec, - const RawAddress& new_pseudo_addr) { +bool btm_ble_init_pseudo_addr(tBTM_SEC_DEV_REC* p_dev_rec, const RawAddress& new_pseudo_addr) { if (p_dev_rec->ble.pseudo_addr.IsEmpty()) { p_dev_rec->ble.pseudo_addr = new_pseudo_addr; return true; @@ -99,9 +98,10 @@ static bool rpa_matches_irk(const RawAddress& rpa, const Octet16& irk) { /** This function checks if a RPA is resolvable by the device key. * Returns true is resolvable; false otherwise. */ -bool btm_ble_addr_resolvable(const RawAddress& rpa, - tBTM_SEC_DEV_REC* p_dev_rec) { - if (!BTM_BLE_IS_RESOLVE_BDA(rpa)) return false; +bool btm_ble_addr_resolvable(const RawAddress& rpa, tBTM_SEC_DEV_REC* p_dev_rec) { + if (!BTM_BLE_IS_RESOLVE_BDA(rpa)) { + return false; + } if ((p_dev_rec->device_type & BT_DEVICE_TYPE_BLE) && (p_dev_rec->sec_rec.ble_keys.key_type & BTM_LE_KEY_PID)) { @@ -121,9 +121,10 @@ static bool btm_ble_match_random_bda(void* data, void* context) { RawAddress* random_bda = static_cast(context); if (!(p_dev_rec->device_type & BT_DEVICE_TYPE_BLE) || - !(p_dev_rec->sec_rec.ble_keys.key_type & BTM_LE_KEY_PID)) + !(p_dev_rec->sec_rec.ble_keys.key_type & BTM_LE_KEY_PID)) { // Match fails preconditions return true; + } if (rpa_matches_irk(*random_bda, p_dev_rec->sec_rec.ble_keys.irk)) { // Matched @@ -139,31 +140,34 @@ static bool btm_ble_match_random_bda(void* data, void* context) { * matched to. */ tBTM_SEC_DEV_REC* btm_ble_resolve_random_addr(const RawAddress& random_bda) { - if (btm_sec_cb.sec_dev_rec == nullptr) return nullptr; - list_node_t* n = list_foreach(btm_sec_cb.sec_dev_rec, - btm_ble_match_random_bda, (void*)&random_bda); - return (n == nullptr) ? (nullptr) - : (static_cast(list_node(n))); + if (btm_sec_cb.sec_dev_rec == nullptr) { + return nullptr; + } + list_node_t* n = + list_foreach(btm_sec_cb.sec_dev_rec, btm_ble_match_random_bda, (void*)&random_bda); + return (n == nullptr) ? (nullptr) : (static_cast(list_node(n))); } /******************************************************************************* * address mapping between pseudo address and real connection address ******************************************************************************/ /** Find the security record whose LE identity address is matching */ -static tBTM_SEC_DEV_REC* btm_find_dev_by_identity_addr( - const RawAddress& bd_addr, uint8_t addr_type) { - if (btm_sec_cb.sec_dev_rec == nullptr) return nullptr; +static tBTM_SEC_DEV_REC* btm_find_dev_by_identity_addr(const RawAddress& bd_addr, + uint8_t addr_type) { + if (btm_sec_cb.sec_dev_rec == nullptr) { + return nullptr; + } list_node_t* end = list_end(btm_sec_cb.sec_dev_rec); for (list_node_t* node = list_begin(btm_sec_cb.sec_dev_rec); node != end; node = list_next(node)) { - tBTM_SEC_DEV_REC* p_dev_rec = - static_cast(list_node(node)); + tBTM_SEC_DEV_REC* p_dev_rec = static_cast(list_node(node)); if (p_dev_rec->ble.identity_address_with_type.bda == bd_addr) { - if ((p_dev_rec->ble.identity_address_with_type.type & - (~BLE_ADDR_TYPE_ID_BIT)) != (addr_type & (~BLE_ADDR_TYPE_ID_BIT))) + if ((p_dev_rec->ble.identity_address_with_type.type & (~BLE_ADDR_TYPE_ID_BIT)) != + (addr_type & (~BLE_ADDR_TYPE_ID_BIT))) { log::warn("pseudo->random match with diff addr type: {} vs {}", p_dev_rec->ble.identity_address_with_type.type, addr_type); + } /* found the match */ return p_dev_rec; @@ -181,19 +185,16 @@ static tBTM_SEC_DEV_REC* btm_find_dev_by_identity_addr( * address in security database. * ******************************************************************************/ -bool btm_identity_addr_to_random_pseudo(RawAddress* bd_addr, - tBLE_ADDR_TYPE* p_addr_type, +bool btm_identity_addr_to_random_pseudo(RawAddress* bd_addr, tBLE_ADDR_TYPE* p_addr_type, bool refresh) { - tBTM_SEC_DEV_REC* p_dev_rec = - btm_find_dev_by_identity_addr(*bd_addr, *p_addr_type); + tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev_by_identity_addr(*bd_addr, *p_addr_type); if (p_dev_rec == nullptr) { return false; } /* evt reported on static address, map static address to random pseudo */ /* if RPA offloading is supported, or 4.2 controller, do RPA refresh */ - if (refresh && - bluetooth::shim::GetController()->GetLeResolvingListSize() != 0) { + if (refresh && bluetooth::shim::GetController()->GetLeResolvingListSize() != 0) { btm_ble_read_resolving_list_entry(p_dev_rec); } @@ -206,10 +207,10 @@ bool btm_identity_addr_to_random_pseudo(RawAddress* bd_addr, return true; } -bool btm_identity_addr_to_random_pseudo_from_address_with_type( - tBLE_BD_ADDR* address_with_type, bool refresh) { - return btm_identity_addr_to_random_pseudo( - &(address_with_type->bda), &(address_with_type->type), refresh); +bool btm_identity_addr_to_random_pseudo_from_address_with_type(tBLE_BD_ADDR* address_with_type, + bool refresh) { + return btm_identity_addr_to_random_pseudo(&(address_with_type->bda), &(address_with_type->type), + refresh); } /******************************************************************************* @@ -228,8 +229,9 @@ bool btm_random_pseudo_to_identity_addr(RawAddress* random_pseudo, if (p_dev_rec->ble.in_controller_list & BTM_RESOLVING_LIST_BIT) { *p_identity_addr_type = p_dev_rec->ble.identity_address_with_type.type; *random_pseudo = p_dev_rec->ble.identity_address_with_type.bda; - if (bluetooth::shim::GetController()->SupportsBlePrivacy()) + if (bluetooth::shim::GetController()->SupportsBlePrivacy()) { *p_identity_addr_type |= BLE_ADDR_TYPE_ID_BIT; + } return true; } } @@ -245,9 +247,9 @@ bool btm_random_pseudo_to_identity_addr(RawAddress* random_pseudo, * connection address. * ******************************************************************************/ -void btm_ble_refresh_peer_resolvable_private_addr( - const RawAddress& pseudo_bda, const RawAddress& rpa, - tBLE_RAND_ADDR_TYPE rra_type) { +void btm_ble_refresh_peer_resolvable_private_addr(const RawAddress& pseudo_bda, + const RawAddress& rpa, + tBLE_RAND_ADDR_TYPE rra_type) { tBTM_SEC_DEV_REC* p_sec_rec = btm_find_dev(pseudo_bda); if (p_sec_rec == nullptr) { log::warn("No matching known device in record"); @@ -257,8 +259,7 @@ void btm_ble_refresh_peer_resolvable_private_addr( p_sec_rec->ble.cur_rand_addr = rpa; if (rra_type == BTM_BLE_ADDR_PSEUDO) { - p_sec_rec->ble.active_addr_type = - rpa.IsEmpty() ? BTM_BLE_ADDR_STATIC : BTM_BLE_ADDR_RRA; + p_sec_rec->ble.active_addr_type = rpa.IsEmpty() ? BTM_BLE_ADDR_STATIC : BTM_BLE_ADDR_RRA; } else { p_sec_rec->ble.active_addr_type = rra_type; } @@ -267,12 +268,11 @@ void btm_ble_refresh_peer_resolvable_private_addr( const auto& identity_address = p_sec_rec->ble.identity_address_with_type.bda; auto identity_address_type = p_sec_rec->ble.identity_address_with_type.type; - if (!acl_refresh_remote_address(identity_address, identity_address_type, - p_sec_rec->bd_addr, rra_type, rpa)) { + if (!acl_refresh_remote_address(identity_address, identity_address_type, p_sec_rec->bd_addr, + rra_type, rpa)) { // Try looking up the pseudo random address if (!acl_refresh_remote_address(identity_address, identity_address_type, - p_sec_rec->ble.pseudo_addr, rra_type, - rpa)) { + p_sec_rec->ble.pseudo_addr, rra_type, rpa)) { log::error("Unknown device to refresh remote device"); } } @@ -281,8 +281,7 @@ void btm_ble_refresh_peer_resolvable_private_addr( bool maybe_resolve_address(RawAddress* bda, tBLE_ADDR_TYPE* bda_type) { bool is_in_security_db = false; tBLE_ADDR_TYPE peer_addr_type = *bda_type; - bool addr_is_rpa = - (peer_addr_type == BLE_ADDR_RANDOM && BTM_BLE_IS_RESOLVE_BDA(*bda)); + bool addr_is_rpa = (peer_addr_type == BLE_ADDR_RANDOM && BTM_BLE_IS_RESOLVE_BDA(*bda)); /* We must translate whatever address we received into the "pseudo" address. * i.e. if we bonded with device that was using RPA for first connection, diff --git a/system/stack/btm/btm_ble_adv_filter.cc b/system/stack/btm/btm_ble_adv_filter.cc index f345c4c2b10..4dc2a50f709 100644 --- a/system/stack/btm/btm_ble_adv_filter.cc +++ b/system/stack/btm/btm_ble_adv_filter.cc @@ -56,14 +56,12 @@ using bluetooth::Uuid; tBTM_BLE_ADV_FILTER_CB btm_ble_adv_filt_cb; tBTM_BLE_VSC_CB cmn_ble_vsc_cb; -static uint8_t btm_ble_cs_update_pf_counter(tBTM_BLE_SCAN_COND_OP action, - uint8_t cond_type, - tBLE_BD_ADDR* p_bd_addr, - uint8_t num_available); +static uint8_t btm_ble_cs_update_pf_counter(tBTM_BLE_SCAN_COND_OP action, uint8_t cond_type, + tBLE_BD_ADDR* p_bd_addr, uint8_t num_available); #define BTM_BLE_SET_SCAN_PF_OPCODE(x, y) (((x) << 4) | (y)) #define BTM_BLE_GET_SCAN_PF_SUBCODE(x) ((x) >> 4) -#define BTM_BLE_GET_SCAN_PF_ACTION(x) ((x)&0x0f) +#define BTM_BLE_GET_SCAN_PF_ACTION(x) ((x) & 0x0f) #define BTM_BLE_INVALID_COUNTER 0xff /* length of each multi adv sub command */ @@ -124,8 +122,8 @@ static uint8_t btm_ble_ocf_to_condtype(uint8_t ocf) { return cond_type; } -static void btm_flt_update_cb(uint8_t expected_ocf, tBTM_BLE_PF_CFG_CBACK cb, - uint8_t* p, uint16_t evt_len) { +static void btm_flt_update_cb(uint8_t expected_ocf, tBTM_BLE_PF_CFG_CBACK cb, uint8_t* p, + uint16_t evt_len) { if (evt_len != 4) { log::error("bad length: {}", evt_len); return; @@ -138,8 +136,7 @@ static void btm_flt_update_cb(uint8_t expected_ocf, tBTM_BLE_PF_CFG_CBACK cb, STREAM_TO_UINT8(num_avail, p); if (expected_ocf != op_subcode) { - log::error("Incorrect opcode: 0x{:02x}, expected: 0x{:02x}", expected_ocf, - op_subcode); + log::error("Incorrect opcode: 0x{:02x}, expected: 0x{:02x}", expected_ocf, op_subcode); return; } @@ -151,16 +148,15 @@ static void btm_flt_update_cb(uint8_t expected_ocf, tBTM_BLE_PF_CFG_CBACK cb, } uint8_t cond_type = btm_ble_ocf_to_condtype(expected_ocf); - log::verbose("Recd: {}, {}, {}, {}, {}", op_subcode, expected_ocf, action, - status, num_avail); + log::verbose("Recd: {}, {}, {}, {}, {}", op_subcode, expected_ocf, action, status, num_avail); if (HCI_SUCCESS == status) { - if (btm_ble_adv_filt_cb.cur_filter_target.bda.IsEmpty()) - btm_ble_cs_update_pf_counter(static_cast(action), - cond_type, NULL, num_avail); - else - btm_ble_cs_update_pf_counter( - static_cast(action), cond_type, - &btm_ble_adv_filt_cb.cur_filter_target, num_avail); + if (btm_ble_adv_filt_cb.cur_filter_target.bda.IsEmpty()) { + btm_ble_cs_update_pf_counter(static_cast(action), cond_type, NULL, + num_avail); + } else { + btm_ble_cs_update_pf_counter(static_cast(action), cond_type, + &btm_ble_adv_filt_cb.cur_filter_target, num_avail); + } } /* send ADV PF operation complete */ @@ -179,13 +175,13 @@ static void btm_flt_update_cb(uint8_t expected_ocf, tBTM_BLE_PF_CFG_CBACK cb, * Returns pointer to the counter if found; NULL otherwise. * ******************************************************************************/ -static tBTM_BLE_PF_COUNT* btm_ble_find_addr_filter_counter( - tBLE_BD_ADDR* p_le_bda) { +static tBTM_BLE_PF_COUNT* btm_ble_find_addr_filter_counter(tBLE_BD_ADDR* p_le_bda) { uint8_t i; - tBTM_BLE_PF_COUNT* p_addr_filter = - &btm_ble_adv_filt_cb.p_addr_filter_count[1]; + tBTM_BLE_PF_COUNT* p_addr_filter = &btm_ble_adv_filt_cb.p_addr_filter_count[1]; - if (p_le_bda == NULL) return &btm_ble_adv_filt_cb.p_addr_filter_count[0]; + if (p_le_bda == NULL) { + return &btm_ble_adv_filt_cb.p_addr_filter_count[0]; + } for (i = 0; i < cmn_ble_vsc_cb.max_filter; i++, p_addr_filter++) { if (p_addr_filter->in_use && p_le_bda->bda == p_addr_filter->bd_addr) { @@ -205,11 +201,9 @@ static tBTM_BLE_PF_COUNT* btm_ble_find_addr_filter_counter( * otherwise. * ******************************************************************************/ -static tBTM_BLE_PF_COUNT* btm_ble_alloc_addr_filter_counter( - const RawAddress& bd_addr) { +static tBTM_BLE_PF_COUNT* btm_ble_alloc_addr_filter_counter(const RawAddress& bd_addr) { uint8_t i; - tBTM_BLE_PF_COUNT* p_addr_filter = - &btm_ble_adv_filt_cb.p_addr_filter_count[1]; + tBTM_BLE_PF_COUNT* p_addr_filter = &btm_ble_adv_filt_cb.p_addr_filter_count[1]; for (i = 0; i < cmn_ble_vsc_cb.max_filter; i++, p_addr_filter++) { if (p_addr_filter->bd_addr.IsEmpty()) { @@ -229,24 +223,23 @@ static tBTM_BLE_PF_COUNT* btm_ble_alloc_addr_filter_counter( * Returns true if deallocation succeed; false otherwise. * ******************************************************************************/ -static bool btm_ble_dealloc_addr_filter_counter(tBLE_BD_ADDR* p_bd_addr, - uint8_t filter_type) { +static bool btm_ble_dealloc_addr_filter_counter(tBLE_BD_ADDR* p_bd_addr, uint8_t filter_type) { uint8_t i; - tBTM_BLE_PF_COUNT* p_addr_filter = - &btm_ble_adv_filt_cb.p_addr_filter_count[1]; + tBTM_BLE_PF_COUNT* p_addr_filter = &btm_ble_adv_filt_cb.p_addr_filter_count[1]; bool found = false; - if (BTM_BLE_PF_TYPE_ALL == filter_type && NULL == p_bd_addr) - memset(&btm_ble_adv_filt_cb.p_addr_filter_count[0], 0, - sizeof(tBTM_BLE_PF_COUNT)); + if (BTM_BLE_PF_TYPE_ALL == filter_type && NULL == p_bd_addr) { + memset(&btm_ble_adv_filt_cb.p_addr_filter_count[0], 0, sizeof(tBTM_BLE_PF_COUNT)); + } for (i = 0; i < cmn_ble_vsc_cb.max_filter; i++, p_addr_filter++) { - if (p_addr_filter->in_use && - (!p_bd_addr || p_bd_addr->bda == p_addr_filter->bd_addr)) { + if (p_addr_filter->in_use && (!p_bd_addr || p_bd_addr->bda == p_addr_filter->bd_addr)) { found = true; memset(p_addr_filter, 0, sizeof(tBTM_BLE_PF_COUNT)); - if (p_bd_addr) break; + if (p_bd_addr) { + break; + } } } return found; @@ -263,10 +256,8 @@ static bool btm_ble_dealloc_addr_filter_counter(tBLE_BD_ADDR* p_bd_addr, * counter update failed. * ******************************************************************************/ -static uint8_t btm_ble_cs_update_pf_counter(tBTM_BLE_SCAN_COND_OP action, - uint8_t cond_type, - tBLE_BD_ADDR* p_bd_addr, - uint8_t num_available) { +static uint8_t btm_ble_cs_update_pf_counter(tBTM_BLE_SCAN_COND_OP action, uint8_t cond_type, + tBLE_BD_ADDR* p_bd_addr, uint8_t num_available) { tBTM_BLE_PF_COUNT* p_addr_filter = NULL; uint8_t* p_counter = NULL; @@ -276,10 +267,10 @@ static uint8_t btm_ble_cs_update_pf_counter(tBTM_BLE_SCAN_COND_OP action, } /* for these three types of filter, always generic */ - if (BTM_BLE_PF_ADDR_FILTER == cond_type || - BTM_BLE_PF_MANU_DATA == cond_type || BTM_BLE_PF_LOCAL_NAME == cond_type || - BTM_BLE_PF_SRVC_DATA_PATTERN == cond_type) + if (BTM_BLE_PF_ADDR_FILTER == cond_type || BTM_BLE_PF_MANU_DATA == cond_type || + BTM_BLE_PF_LOCAL_NAME == cond_type || BTM_BLE_PF_SRVC_DATA_PATTERN == cond_type) { p_bd_addr = NULL; + } if ((p_addr_filter = btm_ble_find_addr_filter_counter(p_bd_addr)) == NULL && BTM_BLE_SCAN_COND_ADD == action) { @@ -288,23 +279,22 @@ static uint8_t btm_ble_cs_update_pf_counter(tBTM_BLE_SCAN_COND_OP action, if (NULL != p_addr_filter) { /* all filter just cleared */ - if ((BTM_BLE_PF_TYPE_ALL == cond_type && - BTM_BLE_SCAN_COND_CLEAR == action) || + if ((BTM_BLE_PF_TYPE_ALL == cond_type && BTM_BLE_SCAN_COND_CLEAR == action) || /* or bd address filter been deleted */ (BTM_BLE_PF_ADDR_FILTER == cond_type && - (BTM_BLE_SCAN_COND_DELETE == action || - BTM_BLE_SCAN_COND_CLEAR == action))) { + (BTM_BLE_SCAN_COND_DELETE == action || BTM_BLE_SCAN_COND_CLEAR == action))) { btm_ble_dealloc_addr_filter_counter(p_bd_addr, cond_type); } /* if not feature selection, update new addition/reduction of the filter counter */ else if (cond_type != BTM_BLE_PF_TYPE_ALL) { p_counter = p_addr_filter->pf_counter; - if (num_available > 0) p_counter[cond_type] += 1; + if (num_available > 0) { + p_counter[cond_type] += 1; + } - log::verbose("counter = {}, maxfilt = {}, num_avbl={}", - p_counter[cond_type], cmn_ble_vsc_cb.max_filter, - num_available); + log::verbose("counter = {}, maxfilt = {}, num_avbl={}", p_counter[cond_type], + cmn_ble_vsc_cb.max_filter, num_available); return p_counter[cond_type]; } } else { @@ -327,13 +317,12 @@ static uint8_t btm_ble_cs_update_pf_counter(tBTM_BLE_SCAN_COND_OP action, * cb - Callback * ******************************************************************************/ -void BTM_BleAdvFilterParamSetup( - tBTM_BLE_SCAN_COND_OP action, tBTM_BLE_PF_FILT_INDEX filt_index, - std::unique_ptr p_filt_params, - tBTM_BLE_PF_PARAM_CB cb) { +void BTM_BleAdvFilterParamSetup(tBTM_BLE_SCAN_COND_OP action, tBTM_BLE_PF_FILT_INDEX filt_index, + std::unique_ptr p_filt_params, + tBTM_BLE_PF_PARAM_CB cb) { tBTM_BLE_PF_COUNT* p_bda_filter = NULL; - uint8_t len = BTM_BLE_ADV_FILT_META_HDR_LENGTH + - BTM_BLE_ADV_FILT_FEAT_SELN_LEN + BTM_BLE_ADV_FILT_TRACK_NUM; + uint8_t len = BTM_BLE_ADV_FILT_META_HDR_LENGTH + BTM_BLE_ADV_FILT_FEAT_SELN_LEN + + BTM_BLE_ADV_FILT_TRACK_NUM; uint8_t param[len], *p; if (!is_filtering_supported()) { @@ -382,19 +371,20 @@ void BTM_BleAdvFilterParamSetup( /* set onlost timeout */ UINT16_TO_STREAM(p, p_filt_params->lost_timeout); /* set num_of_track_entries for firmware greater than L-release version */ - if (cmn_ble_vsc_cb.version_supported > BTM_VSC_CHIP_CAPABILITY_L_VERSION) + if (cmn_ble_vsc_cb.version_supported > BTM_VSC_CHIP_CAPABILITY_L_VERSION) { UINT16_TO_STREAM(p, p_filt_params->num_of_tracking_entries); + } } - if (cmn_ble_vsc_cb.version_supported == BTM_VSC_CHIP_CAPABILITY_L_VERSION) + if (cmn_ble_vsc_cb.version_supported == BTM_VSC_CHIP_CAPABILITY_L_VERSION) { len = BTM_BLE_ADV_FILT_META_HDR_LENGTH + BTM_BLE_ADV_FILT_FEAT_SELN_LEN; - else + } else { len = BTM_BLE_ADV_FILT_META_HDR_LENGTH + BTM_BLE_ADV_FILT_FEAT_SELN_LEN + BTM_BLE_ADV_FILT_TRACK_NUM; + } - btu_hcif_send_cmd_with_cb( - FROM_HERE, HCI_BLE_ADV_FILTER, param, len, - base::Bind(&btm_flt_update_cb, BTM_BLE_META_PF_FEAT_SEL, cb)); + btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_BLE_ADV_FILTER, param, len, + base::Bind(&btm_flt_update_cb, BTM_BLE_META_PF_FEAT_SEL, cb)); } else if (BTM_BLE_SCAN_COND_DELETE == action) { /* select feature based on control block settings */ UINT8_TO_STREAM(p, BTM_BLE_META_PF_FEAT_SEL); @@ -402,10 +392,9 @@ void BTM_BleAdvFilterParamSetup( /* Filter index */ UINT8_TO_STREAM(p, filt_index); - btu_hcif_send_cmd_with_cb( - FROM_HERE, HCI_BLE_ADV_FILTER, param, - (uint8_t)(BTM_BLE_ADV_FILT_META_HDR_LENGTH), - base::Bind(&btm_flt_update_cb, BTM_BLE_META_PF_FEAT_SEL, cb)); + btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_BLE_ADV_FILTER, param, + (uint8_t)(BTM_BLE_ADV_FILT_META_HDR_LENGTH), + base::Bind(&btm_flt_update_cb, BTM_BLE_META_PF_FEAT_SEL, cb)); } else if (BTM_BLE_SCAN_COND_CLEAR == action) { /* Deallocate all filters here */ @@ -415,10 +404,9 @@ void BTM_BleAdvFilterParamSetup( UINT8_TO_STREAM(p, BTM_BLE_META_PF_FEAT_SEL); UINT8_TO_STREAM(p, BTM_BLE_SCAN_COND_CLEAR); - btu_hcif_send_cmd_with_cb( - FROM_HERE, HCI_BLE_ADV_FILTER, param, - (uint8_t)(BTM_BLE_ADV_FILT_META_HDR_LENGTH - 1), - base::Bind(&btm_flt_update_cb, BTM_BLE_META_PF_FEAT_SEL, cb)); + btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_BLE_ADV_FILTER, param, + (uint8_t)(BTM_BLE_ADV_FILT_META_HDR_LENGTH - 1), + base::Bind(&btm_flt_update_cb, BTM_BLE_META_PF_FEAT_SEL, cb)); } } @@ -438,10 +426,12 @@ void btm_ble_adv_filter_init(void) { BTM_BleGetVendorCapabilities(&cmn_ble_vsc_cb); - if (!is_filtering_supported()) return; + if (!is_filtering_supported()) { + return; + } if (cmn_ble_vsc_cb.max_filter > 0) { - btm_ble_adv_filt_cb.p_addr_filter_count = (tBTM_BLE_PF_COUNT*)osi_malloc( - sizeof(tBTM_BLE_PF_COUNT) * cmn_ble_vsc_cb.max_filter); + btm_ble_adv_filt_cb.p_addr_filter_count = + (tBTM_BLE_PF_COUNT*)osi_malloc(sizeof(tBTM_BLE_PF_COUNT) * cmn_ble_vsc_cb.max_filter); } } diff --git a/system/stack/btm/btm_ble_bgconn.cc b/system/stack/btm/btm_ble_bgconn.cc index 6522b01498d..64625291fef 100644 --- a/system/stack/btm/btm_ble_bgconn.cc +++ b/system/stack/btm/btm_ble_bgconn.cc @@ -60,13 +60,11 @@ struct BackgroundConnection { struct BgConnHash { std::size_t operator()(const RawAddress& x) const { const uint8_t* a = x.address; - return a[0] ^ (a[1] << 8) ^ (a[2] << 16) ^ (a[3] << 24) ^ a[4] ^ - (a[5] << 8); + return a[0] ^ (a[1] << 8) ^ (a[2] << 16) ^ (a[3] << 24) ^ a[4] ^ (a[5] << 8); } }; -static std::unordered_map - background_connections; +static std::unordered_map background_connections; /******************************************************************************* * @@ -76,34 +74,30 @@ static std::unordered_map ******************************************************************************/ void btm_update_scanner_filter_policy(tBTM_BLE_SFP scan_policy) { uint32_t scan_interval = !btm_cb.ble_ctr_cb.inq_var.scan_interval - ? BTM_BLE_GAP_DISC_SCAN_INT - : btm_cb.ble_ctr_cb.inq_var.scan_interval; + ? BTM_BLE_GAP_DISC_SCAN_INT + : btm_cb.ble_ctr_cb.inq_var.scan_interval; uint32_t scan_window = !btm_cb.ble_ctr_cb.inq_var.scan_window - ? BTM_BLE_GAP_DISC_SCAN_WIN - : btm_cb.ble_ctr_cb.inq_var.scan_window; - uint8_t scan_phy = !btm_cb.ble_ctr_cb.inq_var.scan_phy - ? BTM_BLE_DEFAULT_PHYS - : btm_cb.ble_ctr_cb.inq_var.scan_phy; + ? BTM_BLE_GAP_DISC_SCAN_WIN + : btm_cb.ble_ctr_cb.inq_var.scan_window; + uint8_t scan_phy = !btm_cb.ble_ctr_cb.inq_var.scan_phy ? BTM_BLE_DEFAULT_PHYS + : btm_cb.ble_ctr_cb.inq_var.scan_phy; log::verbose(""); btm_cb.ble_ctr_cb.inq_var.sfp = scan_policy; btm_cb.ble_ctr_cb.inq_var.scan_type = - btm_cb.ble_ctr_cb.inq_var.scan_type == BTM_BLE_SCAN_MODE_NONE - ? BTM_BLE_SCAN_MODE_ACTI - : btm_cb.ble_ctr_cb.inq_var.scan_type; - - btm_send_hci_set_scan_params( - btm_cb.ble_ctr_cb.inq_var.scan_type, (uint16_t)scan_interval, - (uint16_t)scan_window, (uint8_t)scan_phy, - btm_cb.ble_ctr_cb.addr_mgnt_cb.own_addr_type, scan_policy); + btm_cb.ble_ctr_cb.inq_var.scan_type == BTM_BLE_SCAN_MODE_NONE + ? BTM_BLE_SCAN_MODE_ACTI + : btm_cb.ble_ctr_cb.inq_var.scan_type; + + btm_send_hci_set_scan_params(btm_cb.ble_ctr_cb.inq_var.scan_type, (uint16_t)scan_interval, + (uint16_t)scan_window, (uint8_t)scan_phy, + btm_cb.ble_ctr_cb.addr_mgnt_cb.own_addr_type, scan_policy); } /** Adds the device into acceptlist. Returns false if acceptlist is full and * device can't be added, true otherwise. */ -bool BTM_AcceptlistAdd(const RawAddress& address) { - return BTM_AcceptlistAdd(address, false); -} +bool BTM_AcceptlistAdd(const RawAddress& address) { return BTM_AcceptlistAdd(address, false); } /** Adds the device into acceptlist and indicates whether to using direct * connect parameters. Returns false if acceptlist is full and device can't @@ -114,8 +108,8 @@ bool BTM_AcceptlistAdd(const RawAddress& address, bool is_direct) { return false; } - return bluetooth::shim::ACL_AcceptLeConnectionFrom( - BTM_Sec_GetAddressWithType(address), is_direct); + return bluetooth::shim::ACL_AcceptLeConnectionFrom(BTM_Sec_GetAddressWithType(address), + is_direct); } /** Removes the device from acceptlist */ @@ -125,8 +119,7 @@ void BTM_AcceptlistRemove(const RawAddress& address) { return; } - bluetooth::shim::ACL_IgnoreLeConnectionFrom( - BTM_Sec_GetAddressWithType(address)); + bluetooth::shim::ACL_IgnoreLeConnectionFrom(BTM_Sec_GetAddressWithType(address)); return; } diff --git a/system/stack/btm/btm_ble_cont_energy.cc b/system/stack/btm/btm_ble_cont_energy.cc index 2f52cbed866..fc95f85caa0 100644 --- a/system/stack/btm/btm_ble_cont_energy.cc +++ b/system/stack/btm/btm_ble_cont_energy.cc @@ -46,8 +46,7 @@ tBTM_BLE_ENERGY_INFO_CB ble_energy_info_cb; static void btm_ble_cont_energy_cmpl_cback(tBTM_VSC_CMPL* p_params) { uint8_t* p = p_params->p_param_buf; uint16_t len = p_params->param_len; - uint32_t total_tx_time = 0, total_rx_time = 0, total_idle_time = 0, - total_energy_used = 0; + uint32_t total_tx_time = 0, total_rx_time = 0, total_idle_time = 0, total_energy_used = 0; if (len < 17) { log::error("wrong length for btm_ble_cont_energy_cmpl_cback"); @@ -62,14 +61,13 @@ static void btm_ble_cont_energy_cmpl_cback(tBTM_VSC_CMPL* p_params) { STREAM_TO_UINT32(total_idle_time, p); STREAM_TO_UINT32(total_energy_used, p); - log::verbose( - "energy_info status={},tx_t={}, rx_t={}, ener_used={}, idle_t={}", status, - total_tx_time, total_rx_time, total_energy_used, total_idle_time); + log::verbose("energy_info status={},tx_t={}, rx_t={}, ener_used={}, idle_t={}", status, + total_tx_time, total_rx_time, total_energy_used, total_idle_time); - if (NULL != ble_energy_info_cb.p_ener_cback) - ble_energy_info_cb.p_ener_cback(total_tx_time, total_rx_time, - total_idle_time, total_energy_used, - static_cast(status)); + if (NULL != ble_energy_info_cb.p_ener_cback) { + ble_energy_info_cb.p_ener_cback(total_tx_time, total_rx_time, total_idle_time, + total_energy_used, static_cast(status)); + } return; } @@ -98,7 +96,7 @@ tBTM_STATUS BTM_BleGetEnergyInfo(tBTM_BLE_ENERGY_INFO_CBACK* p_ener_cback) { } ble_energy_info_cb.p_ener_cback = p_ener_cback; - get_btm_client_interface().vendor.BTM_VendorSpecificCommand( - HCI_BLE_ENERGY_INFO, 0, NULL, btm_ble_cont_energy_cmpl_cback); + get_btm_client_interface().vendor.BTM_VendorSpecificCommand(HCI_BLE_ENERGY_INFO, 0, NULL, + btm_ble_cont_energy_cmpl_cback); return BTM_CMD_STARTED; } diff --git a/system/stack/btm/btm_ble_gap.cc b/system/stack/btm/btm_ble_gap.cc index 5eac9a18bba..e72c5581673 100644 --- a/system/stack/btm/btm_ble_gap.cc +++ b/system/stack/btm/btm_ble_gap.cc @@ -78,16 +78,13 @@ void btm_ble_adv_filter_init(void); #define BTM_EXT_BLE_RMT_NAME_TIMEOUT_MS (30 * 1000) #define MIN_ADV_LENGTH 2 #define BTM_VSC_CHIP_CAPABILITY_RSP_LEN 9 -#define BTM_VSC_CHIP_CAPABILITY_RSP_LEN_L_RELEASE \ - BTM_VSC_CHIP_CAPABILITY_RSP_LEN +#define BTM_VSC_CHIP_CAPABILITY_RSP_LEN_L_RELEASE BTM_VSC_CHIP_CAPABILITY_RSP_LEN #define BTM_VSC_CHIP_CAPABILITY_RSP_LEN_M_RELEASE 15 #define BTM_VSC_CHIP_CAPABILITY_RSP_LEN_S_RELEASE 25 /* Sysprop paths for scan parameters */ -static const char kPropertyInquiryScanInterval[] = - "bluetooth.core.le.inquiry_scan_interval"; -static const char kPropertyInquiryScanWindow[] = - "bluetooth.core.le.inquiry_scan_window"; +static const char kPropertyInquiryScanInterval[] = "bluetooth.core.le.inquiry_scan_interval"; +static const char kPropertyInquiryScanWindow[] = "bluetooth.core.le.inquiry_scan_window"; #ifndef PROPERTY_BLE_PRIVACY_OWN_ADDRESS_ENABLED #define PROPERTY_BLE_PRIVACY_OWN_ADDRESS_ENABLED \ @@ -112,7 +109,7 @@ constexpr uint8_t BLE_EVT_SCAN_RESPONSE_BIT = 3; constexpr uint8_t BLE_EVT_LEGACY_BIT = 4; class AdvertisingCache { - public: +public: /* Set the data to |data| for device |addr_type, addr| */ const std::vector& Set(uint8_t addr_type, const RawAddress& addr, std::vector data) { @@ -165,7 +162,7 @@ class AdvertisingCache { void ClearAll() { items.clear(); } - private: +private: struct Item { uint8_t addr_type; RawAddress addr; @@ -189,7 +186,7 @@ class AdvertisingCache { std::list items; }; -/* Devices in this cache are waiting for eiter scan response, or chained packets +/* Devices in this cache are waiting for either scan response, or chained packets * on secondary channel */ AdvertisingCache cache; @@ -203,12 +200,11 @@ bool ble_vnd_is_included() { static tBTM_BLE_CTRL_FEATURES_CBACK* p_ctrl_le_feature_rd_cmpl_cback = NULL; /**********PAST & PS *******************/ using StartSyncCb = base::Callback; -using SyncReportCb = base::Callback /*data*/)>; + uint8_t /*status*/, uint16_t /*sync_handle*/, uint8_t /*advertising_sid*/, + uint8_t /*address_type*/, RawAddress /*address*/, uint8_t /*phy*/, uint16_t /*interval*/)>; +using SyncReportCb = + base::Callback /*data*/)>; using SyncLostCb = base::Callback; using SyncTransferCb = base::Callback; #define MAX_SYNC_TRANSACTION 16 @@ -278,11 +274,9 @@ static void btm_ble_start_sync_timeout(void* data); ******************************************************************************/ static void btm_ble_update_adv_flag(uint8_t flag); void btm_ble_process_adv_pkt_cont(uint16_t evt_type, tBLE_ADDR_TYPE addr_type, - const RawAddress& bda, uint8_t primary_phy, - uint8_t secondary_phy, - uint8_t advertising_sid, int8_t tx_power, - int8_t rssi, uint16_t periodic_adv_int, - uint8_t data_len, const uint8_t* data, + const RawAddress& bda, uint8_t primary_phy, uint8_t secondary_phy, + uint8_t advertising_sid, int8_t tx_power, int8_t rssi, + uint16_t periodic_adv_int, uint8_t data_len, const uint8_t* data, const RawAddress& original_bda); static uint8_t btm_set_conn_mode_adv_init_addr(RawAddress& p_peer_addr_ptr, tBLE_ADDR_TYPE* p_peer_addr_type, @@ -320,169 +314,166 @@ static bool ble_evt_type_is_legacy(uint16_t evt_type) { return evt_type & (1 << BLE_EVT_LEGACY_BIT); } -static uint8_t ble_evt_type_data_status(uint16_t evt_type) { - return (evt_type >> 5) & 3; -} +static uint8_t ble_evt_type_data_status(uint16_t evt_type) { return (evt_type >> 5) & 3; } constexpr uint8_t UNSUPPORTED = 255; /* LE states combo bit to check */ const uint8_t btm_le_state_combo_tbl[BTM_BLE_STATE_MAX][BTM_BLE_STATE_MAX] = { - { - /* single state support */ - HCI_LE_STATES_CONN_ADV_BIT, /* conn_adv */ - HCI_LE_STATES_INIT_BIT, /* init */ - HCI_LE_STATES_INIT_BIT, /* central */ - HCI_LE_STATES_PERIPHERAL_BIT, /* peripheral */ - UNSUPPORTED, /* todo: lo du dir adv, not covered ? */ - HCI_LE_STATES_HI_DUTY_DIR_ADV_BIT, /* hi duty dir adv */ - HCI_LE_STATES_NON_CONN_ADV_BIT, /* non connectable adv */ - HCI_LE_STATES_PASS_SCAN_BIT, /* passive scan */ - HCI_LE_STATES_ACTIVE_SCAN_BIT, /* active scan */ - HCI_LE_STATES_SCAN_ADV_BIT /* scanable adv */ - }, - { - /* conn_adv =0 */ - UNSUPPORTED, /* conn_adv */ - HCI_LE_STATES_CONN_ADV_INIT_BIT, /* init: 32 */ - HCI_LE_STATES_CONN_ADV_CENTRAL_BIT, /* central: 35 */ - HCI_LE_STATES_CONN_ADV_PERIPHERAL_BIT, /* peripheral: 38,*/ - UNSUPPORTED, /* lo du dir adv */ - UNSUPPORTED, /* hi duty dir adv */ - UNSUPPORTED, /* non connectable adv */ - HCI_LE_STATES_CONN_ADV_PASS_SCAN_BIT, /* passive scan */ - HCI_LE_STATES_CONN_ADV_ACTIVE_SCAN_BIT, /* active scan */ - UNSUPPORTED /* scanable adv */ - }, - { - /* init */ - HCI_LE_STATES_CONN_ADV_INIT_BIT, /* conn_adv: 32 */ - UNSUPPORTED, /* init */ - HCI_LE_STATES_INIT_CENTRAL_BIT, /* central 28 */ - HCI_LE_STATES_INIT_CENTRAL_PERIPHERAL_BIT, /* peripheral 41 */ - HCI_LE_STATES_LO_DUTY_DIR_ADV_INIT_BIT, /* lo du dir adv 34 */ - HCI_LE_STATES_HI_DUTY_DIR_ADV_INIT_BIT, /* hi duty dir adv 33 */ - HCI_LE_STATES_NON_CONN_INIT_BIT, /* non connectable adv */ - HCI_LE_STATES_PASS_SCAN_INIT_BIT, /* passive scan */ - HCI_LE_STATES_ACTIVE_SCAN_INIT_BIT, /* active scan */ - HCI_LE_STATES_SCAN_ADV_INIT_BIT /* scanable adv */ - - }, - { - /* central */ - HCI_LE_STATES_CONN_ADV_CENTRAL_BIT, /* conn_adv: 35 */ - HCI_LE_STATES_INIT_CENTRAL_BIT, /* init 28 */ - HCI_LE_STATES_INIT_CENTRAL_BIT, /* central 28 */ - HCI_LE_STATES_CONN_ADV_INIT_BIT, /* peripheral: 32 */ - HCI_LE_STATES_LO_DUTY_DIR_ADV_CENTRAL_BIT, /* lo duty cycle adv 37 */ - HCI_LE_STATES_HI_DUTY_DIR_ADV_CENTRAL_BIT, /* hi duty cycle adv 36 */ - HCI_LE_STATES_NON_CONN_ADV_CENTRAL_BIT, /* non connectable adv*/ - HCI_LE_STATES_PASS_SCAN_CENTRAL_BIT, /* passive scan */ - HCI_LE_STATES_ACTIVE_SCAN_CENTRAL_BIT, /* active scan */ - HCI_LE_STATES_SCAN_ADV_CENTRAL_BIT /* scanable adv */ - - }, - { - /* peripheral */ - HCI_LE_STATES_CONN_ADV_PERIPHERAL_BIT, /* conn_adv: 38,*/ - HCI_LE_STATES_INIT_CENTRAL_PERIPHERAL_BIT, /* init 41 */ - HCI_LE_STATES_INIT_CENTRAL_PERIPHERAL_BIT, /* central 41 */ - HCI_LE_STATES_CONN_ADV_PERIPHERAL_BIT, /* peripheral: 38,*/ - HCI_LE_STATES_LO_DUTY_DIR_ADV_PERIPHERAL_BIT, /* lo duty cycle adv 40 */ - HCI_LE_STATES_HI_DUTY_DIR_ADV_PERIPHERAL_BIT, /* hi duty cycle adv 39 */ - HCI_LE_STATES_NON_CONN_ADV_PERIPHERAL_BIT, /* non connectable adv */ - HCI_LE_STATES_PASS_SCAN_PERIPHERAL_BIT, /* passive scan */ - HCI_LE_STATES_ACTIVE_SCAN_PERIPHERAL_BIT, /* active scan */ - HCI_LE_STATES_SCAN_ADV_PERIPHERAL_BIT /* scanable adv */ - - }, - { - /* lo duty cycle adv */ - UNSUPPORTED, /* conn_adv: 38,*/ - HCI_LE_STATES_LO_DUTY_DIR_ADV_INIT_BIT, /* init 34 */ - HCI_LE_STATES_LO_DUTY_DIR_ADV_CENTRAL_BIT, /* central 37 */ - HCI_LE_STATES_LO_DUTY_DIR_ADV_PERIPHERAL_BIT, /* peripheral: 40 */ - UNSUPPORTED, /* lo duty cycle adv 40 */ - UNSUPPORTED, /* hi duty cycle adv 39 */ - UNSUPPORTED, /* non connectable adv */ - UNSUPPORTED, /* TODO: passive scan, not covered? */ - UNSUPPORTED, /* TODO: active scan, not covered? */ - UNSUPPORTED /* scanable adv */ - }, - { - /* hi duty cycle adv */ - UNSUPPORTED, /* conn_adv: 38,*/ - HCI_LE_STATES_HI_DUTY_DIR_ADV_INIT_BIT, /* init 33 */ - HCI_LE_STATES_HI_DUTY_DIR_ADV_CENTRAL_BIT, /* central 36 */ - HCI_LE_STATES_HI_DUTY_DIR_ADV_PERIPHERAL_BIT, /* peripheral: 39*/ - UNSUPPORTED, /* lo duty cycle adv 40 */ - UNSUPPORTED, /* hi duty cycle adv 39 */ - UNSUPPORTED, /* non connectable adv */ - HCI_LE_STATES_HI_DUTY_DIR_ADV_PASS_SCAN_BIT, /* passive scan */ - HCI_LE_STATES_HI_DUTY_DIR_ADV_ACTIVE_SCAN_BIT, /* active scan */ - UNSUPPORTED /* scanable adv */ - }, - { - /* non connectable adv */ - UNSUPPORTED, /* conn_adv: */ - HCI_LE_STATES_NON_CONN_INIT_BIT, /* init */ - HCI_LE_STATES_NON_CONN_ADV_CENTRAL_BIT, /* central */ - HCI_LE_STATES_NON_CONN_ADV_PERIPHERAL_BIT, /* peripheral: */ - UNSUPPORTED, /* lo duty cycle adv */ - UNSUPPORTED, /* hi duty cycle adv */ - UNSUPPORTED, /* non connectable adv */ - HCI_LE_STATES_NON_CONN_ADV_PASS_SCAN_BIT, /* passive scan */ - HCI_LE_STATES_NON_CONN_ADV_ACTIVE_SCAN_BIT, /* active scan */ - UNSUPPORTED /* scanable adv */ - }, - { - /* passive scan */ - HCI_LE_STATES_CONN_ADV_PASS_SCAN_BIT, /* conn_adv: */ - HCI_LE_STATES_PASS_SCAN_INIT_BIT, /* init */ - HCI_LE_STATES_PASS_SCAN_CENTRAL_BIT, /* central */ - HCI_LE_STATES_PASS_SCAN_PERIPHERAL_BIT, /* peripheral: */ - UNSUPPORTED, /* lo duty cycle adv */ - HCI_LE_STATES_HI_DUTY_DIR_ADV_PASS_SCAN_BIT, /* hi duty cycle adv */ - HCI_LE_STATES_NON_CONN_ADV_PASS_SCAN_BIT, /* non connectable adv */ - UNSUPPORTED, /* passive scan */ - UNSUPPORTED, /* active scan */ - HCI_LE_STATES_SCAN_ADV_PASS_SCAN_BIT /* scanable adv */ - }, - { - /* active scan */ - HCI_LE_STATES_CONN_ADV_ACTIVE_SCAN_BIT, /* conn_adv: */ - HCI_LE_STATES_ACTIVE_SCAN_INIT_BIT, /* init */ - HCI_LE_STATES_ACTIVE_SCAN_CENTRAL_BIT, /* central */ - HCI_LE_STATES_ACTIVE_SCAN_PERIPHERAL_BIT, /* peripheral: */ - UNSUPPORTED, /* lo duty cycle adv */ - HCI_LE_STATES_HI_DUTY_DIR_ADV_ACTIVE_SCAN_BIT, /* hi duty cycle adv */ - HCI_LE_STATES_NON_CONN_ADV_ACTIVE_SCAN_BIT, /* non connectable adv */ - UNSUPPORTED, /* TODO: passive scan */ - UNSUPPORTED, /* TODO: active scan */ - HCI_LE_STATES_SCAN_ADV_ACTIVE_SCAN_BIT /* scanable adv */ - }, - { - /* scanable adv */ - UNSUPPORTED, /* conn_adv: */ - HCI_LE_STATES_SCAN_ADV_INIT_BIT, /* init */ - HCI_LE_STATES_SCAN_ADV_CENTRAL_BIT, /* central */ - HCI_LE_STATES_SCAN_ADV_PERIPHERAL_BIT, /* peripheral: */ - UNSUPPORTED, /* lo duty cycle adv */ - UNSUPPORTED, /* hi duty cycle adv */ - UNSUPPORTED, /* non connectable adv */ - HCI_LE_STATES_SCAN_ADV_PASS_SCAN_BIT, /* passive scan */ - HCI_LE_STATES_SCAN_ADV_ACTIVE_SCAN_BIT, /* active scan */ - UNSUPPORTED /* scanable adv */ - }}; + { + /* single state support */ + HCI_LE_STATES_CONN_ADV_BIT, /* conn_adv */ + HCI_LE_STATES_INIT_BIT, /* init */ + HCI_LE_STATES_INIT_BIT, /* central */ + HCI_LE_STATES_PERIPHERAL_BIT, /* peripheral */ + UNSUPPORTED, /* todo: lo du dir adv, not covered ? */ + HCI_LE_STATES_HI_DUTY_DIR_ADV_BIT, /* hi duty dir adv */ + HCI_LE_STATES_NON_CONN_ADV_BIT, /* non connectable adv */ + HCI_LE_STATES_PASS_SCAN_BIT, /* passive scan */ + HCI_LE_STATES_ACTIVE_SCAN_BIT, /* active scan */ + HCI_LE_STATES_SCAN_ADV_BIT /* scanable adv */ + }, + { + /* conn_adv =0 */ + UNSUPPORTED, /* conn_adv */ + HCI_LE_STATES_CONN_ADV_INIT_BIT, /* init: 32 */ + HCI_LE_STATES_CONN_ADV_CENTRAL_BIT, /* central: 35 */ + HCI_LE_STATES_CONN_ADV_PERIPHERAL_BIT, /* peripheral: 38,*/ + UNSUPPORTED, /* lo du dir adv */ + UNSUPPORTED, /* hi duty dir adv */ + UNSUPPORTED, /* non connectable adv */ + HCI_LE_STATES_CONN_ADV_PASS_SCAN_BIT, /* passive scan */ + HCI_LE_STATES_CONN_ADV_ACTIVE_SCAN_BIT, /* active scan */ + UNSUPPORTED /* scanable adv */ + }, + { + /* init */ + HCI_LE_STATES_CONN_ADV_INIT_BIT, /* conn_adv: 32 */ + UNSUPPORTED, /* init */ + HCI_LE_STATES_INIT_CENTRAL_BIT, /* central 28 */ + HCI_LE_STATES_INIT_CENTRAL_PERIPHERAL_BIT, /* peripheral 41 */ + HCI_LE_STATES_LO_DUTY_DIR_ADV_INIT_BIT, /* lo du dir adv 34 */ + HCI_LE_STATES_HI_DUTY_DIR_ADV_INIT_BIT, /* hi duty dir adv 33 */ + HCI_LE_STATES_NON_CONN_INIT_BIT, /* non connectable adv */ + HCI_LE_STATES_PASS_SCAN_INIT_BIT, /* passive scan */ + HCI_LE_STATES_ACTIVE_SCAN_INIT_BIT, /* active scan */ + HCI_LE_STATES_SCAN_ADV_INIT_BIT /* scanable adv */ + + }, + { + /* central */ + HCI_LE_STATES_CONN_ADV_CENTRAL_BIT, /* conn_adv: 35 */ + HCI_LE_STATES_INIT_CENTRAL_BIT, /* init 28 */ + HCI_LE_STATES_INIT_CENTRAL_BIT, /* central 28 */ + HCI_LE_STATES_CONN_ADV_INIT_BIT, /* peripheral: 32 */ + HCI_LE_STATES_LO_DUTY_DIR_ADV_CENTRAL_BIT, /* lo duty cycle adv 37 */ + HCI_LE_STATES_HI_DUTY_DIR_ADV_CENTRAL_BIT, /* hi duty cycle adv 36 */ + HCI_LE_STATES_NON_CONN_ADV_CENTRAL_BIT, /* non connectable adv*/ + HCI_LE_STATES_PASS_SCAN_CENTRAL_BIT, /* passive scan */ + HCI_LE_STATES_ACTIVE_SCAN_CENTRAL_BIT, /* active scan */ + HCI_LE_STATES_SCAN_ADV_CENTRAL_BIT /* scanable adv */ + + }, + { + /* peripheral */ + HCI_LE_STATES_CONN_ADV_PERIPHERAL_BIT, /* conn_adv: 38,*/ + HCI_LE_STATES_INIT_CENTRAL_PERIPHERAL_BIT, /* init 41 */ + HCI_LE_STATES_INIT_CENTRAL_PERIPHERAL_BIT, /* central 41 */ + HCI_LE_STATES_CONN_ADV_PERIPHERAL_BIT, /* peripheral: 38,*/ + HCI_LE_STATES_LO_DUTY_DIR_ADV_PERIPHERAL_BIT, /* lo duty cycle adv 40 */ + HCI_LE_STATES_HI_DUTY_DIR_ADV_PERIPHERAL_BIT, /* hi duty cycle adv 39 */ + HCI_LE_STATES_NON_CONN_ADV_PERIPHERAL_BIT, /* non connectable adv */ + HCI_LE_STATES_PASS_SCAN_PERIPHERAL_BIT, /* passive scan */ + HCI_LE_STATES_ACTIVE_SCAN_PERIPHERAL_BIT, /* active scan */ + HCI_LE_STATES_SCAN_ADV_PERIPHERAL_BIT /* scanable adv */ + + }, + { + /* lo duty cycle adv */ + UNSUPPORTED, /* conn_adv: 38,*/ + HCI_LE_STATES_LO_DUTY_DIR_ADV_INIT_BIT, /* init 34 */ + HCI_LE_STATES_LO_DUTY_DIR_ADV_CENTRAL_BIT, /* central 37 */ + HCI_LE_STATES_LO_DUTY_DIR_ADV_PERIPHERAL_BIT, /* peripheral: 40 */ + UNSUPPORTED, /* lo duty cycle adv 40 */ + UNSUPPORTED, /* hi duty cycle adv 39 */ + UNSUPPORTED, /* non connectable adv */ + UNSUPPORTED, /* TODO: passive scan, not covered? */ + UNSUPPORTED, /* TODO: active scan, not covered? */ + UNSUPPORTED /* scanable adv */ + }, + { + /* hi duty cycle adv */ + UNSUPPORTED, /* conn_adv: 38,*/ + HCI_LE_STATES_HI_DUTY_DIR_ADV_INIT_BIT, /* init 33 */ + HCI_LE_STATES_HI_DUTY_DIR_ADV_CENTRAL_BIT, /* central 36 */ + HCI_LE_STATES_HI_DUTY_DIR_ADV_PERIPHERAL_BIT, /* peripheral: 39*/ + UNSUPPORTED, /* lo duty cycle adv 40 */ + UNSUPPORTED, /* hi duty cycle adv 39 */ + UNSUPPORTED, /* non connectable adv */ + HCI_LE_STATES_HI_DUTY_DIR_ADV_PASS_SCAN_BIT, /* passive scan */ + HCI_LE_STATES_HI_DUTY_DIR_ADV_ACTIVE_SCAN_BIT, /* active scan */ + UNSUPPORTED /* scanable adv */ + }, + { + /* non connectable adv */ + UNSUPPORTED, /* conn_adv: */ + HCI_LE_STATES_NON_CONN_INIT_BIT, /* init */ + HCI_LE_STATES_NON_CONN_ADV_CENTRAL_BIT, /* central */ + HCI_LE_STATES_NON_CONN_ADV_PERIPHERAL_BIT, /* peripheral: */ + UNSUPPORTED, /* lo duty cycle adv */ + UNSUPPORTED, /* hi duty cycle adv */ + UNSUPPORTED, /* non connectable adv */ + HCI_LE_STATES_NON_CONN_ADV_PASS_SCAN_BIT, /* passive scan */ + HCI_LE_STATES_NON_CONN_ADV_ACTIVE_SCAN_BIT, /* active scan */ + UNSUPPORTED /* scanable adv */ + }, + { + /* passive scan */ + HCI_LE_STATES_CONN_ADV_PASS_SCAN_BIT, /* conn_adv: */ + HCI_LE_STATES_PASS_SCAN_INIT_BIT, /* init */ + HCI_LE_STATES_PASS_SCAN_CENTRAL_BIT, /* central */ + HCI_LE_STATES_PASS_SCAN_PERIPHERAL_BIT, /* peripheral: */ + UNSUPPORTED, /* lo duty cycle adv */ + HCI_LE_STATES_HI_DUTY_DIR_ADV_PASS_SCAN_BIT, /* hi duty cycle adv */ + HCI_LE_STATES_NON_CONN_ADV_PASS_SCAN_BIT, /* non connectable adv */ + UNSUPPORTED, /* passive scan */ + UNSUPPORTED, /* active scan */ + HCI_LE_STATES_SCAN_ADV_PASS_SCAN_BIT /* scanable adv */ + }, + { + /* active scan */ + HCI_LE_STATES_CONN_ADV_ACTIVE_SCAN_BIT, /* conn_adv: */ + HCI_LE_STATES_ACTIVE_SCAN_INIT_BIT, /* init */ + HCI_LE_STATES_ACTIVE_SCAN_CENTRAL_BIT, /* central */ + HCI_LE_STATES_ACTIVE_SCAN_PERIPHERAL_BIT, /* peripheral: */ + UNSUPPORTED, /* lo duty cycle adv */ + HCI_LE_STATES_HI_DUTY_DIR_ADV_ACTIVE_SCAN_BIT, /* hi duty cycle adv */ + HCI_LE_STATES_NON_CONN_ADV_ACTIVE_SCAN_BIT, /* non connectable adv */ + UNSUPPORTED, /* TODO: passive scan */ + UNSUPPORTED, /* TODO: active scan */ + HCI_LE_STATES_SCAN_ADV_ACTIVE_SCAN_BIT /* scanable adv */ + }, + { + /* scanable adv */ + UNSUPPORTED, /* conn_adv: */ + HCI_LE_STATES_SCAN_ADV_INIT_BIT, /* init */ + HCI_LE_STATES_SCAN_ADV_CENTRAL_BIT, /* central */ + HCI_LE_STATES_SCAN_ADV_PERIPHERAL_BIT, /* peripheral: */ + UNSUPPORTED, /* lo duty cycle adv */ + UNSUPPORTED, /* hi duty cycle adv */ + UNSUPPORTED, /* non connectable adv */ + HCI_LE_STATES_SCAN_ADV_PASS_SCAN_BIT, /* passive scan */ + HCI_LE_STATES_SCAN_ADV_ACTIVE_SCAN_BIT, /* active scan */ + UNSUPPORTED /* scanable adv */ + }}; /* check LE combo state supported */ inline bool BTM_LE_STATES_SUPPORTED(const uint64_t x, uint8_t bit_num) { uint64_t mask = 1 << bit_num; - return ((x)&mask); + return (x)&mask; } -void BTM_BleOpportunisticObserve(bool enable, - tBTM_INQ_RESULTS_CB* p_results_cb) { +void BTM_BleOpportunisticObserve(bool enable, tBTM_INQ_RESULTS_CB* p_results_cb) { if (enable) { btm_cb.ble_ctr_cb.p_opportunistic_obs_results_cb = p_results_cb; } else { @@ -490,8 +481,7 @@ void BTM_BleOpportunisticObserve(bool enable, } } -void BTM_BleTargetAnnouncementObserve(bool enable, - tBTM_INQ_RESULTS_CB* p_results_cb) { +void BTM_BleTargetAnnouncementObserve(bool enable, tBTM_INQ_RESULTS_CB* p_results_cb) { if (enable) { btm_cb.ble_ctr_cb.p_target_announcement_obs_results_cb = p_results_cb; } else { @@ -499,12 +489,11 @@ void BTM_BleTargetAnnouncementObserve(bool enable, } } -std::pair -get_low_latency_scan_params() { - uint16_t scan_interval = osi_property_get_int32(kPropertyInquiryScanInterval, - BTM_BLE_LOW_LATENCY_SCAN_INT); - uint16_t scan_window = osi_property_get_int32(kPropertyInquiryScanWindow, - BTM_BLE_LOW_LATENCY_SCAN_WIN); +std::pair get_low_latency_scan_params() { + uint16_t scan_interval = + osi_property_get_int32(kPropertyInquiryScanInterval, BTM_BLE_LOW_LATENCY_SCAN_INT); + uint16_t scan_window = + osi_property_get_int32(kPropertyInquiryScanWindow, BTM_BLE_LOW_LATENCY_SCAN_WIN); return std::make_pair(scan_interval, scan_window); } @@ -526,35 +515,33 @@ get_low_latency_scan_params() { * Returns void * ******************************************************************************/ -tBTM_STATUS BTM_BleObserve(bool start, uint8_t duration, - tBTM_INQ_RESULTS_CB* p_results_cb, +tBTM_STATUS BTM_BleObserve(bool start, uint8_t duration, tBTM_INQ_RESULTS_CB* p_results_cb, tBTM_CMPL_CB* p_cmpl_cb, bool low_latency_scan) { tBTM_STATUS status = BTM_WRONG_MODE; uint16_t scan_interval = !btm_cb.ble_ctr_cb.inq_var.scan_interval - ? BTM_BLE_GAP_DISC_SCAN_INT - : btm_cb.ble_ctr_cb.inq_var.scan_interval; + ? BTM_BLE_GAP_DISC_SCAN_INT + : btm_cb.ble_ctr_cb.inq_var.scan_interval; uint16_t scan_window = !btm_cb.ble_ctr_cb.inq_var.scan_window - ? BTM_BLE_GAP_DISC_SCAN_WIN - : btm_cb.ble_ctr_cb.inq_var.scan_window; + ? BTM_BLE_GAP_DISC_SCAN_WIN + : btm_cb.ble_ctr_cb.inq_var.scan_window; - uint8_t scan_phy = !btm_cb.ble_ctr_cb.inq_var.scan_phy - ? BTM_BLE_DEFAULT_PHYS - : btm_cb.ble_ctr_cb.inq_var.scan_phy; + uint8_t scan_phy = !btm_cb.ble_ctr_cb.inq_var.scan_phy ? BTM_BLE_DEFAULT_PHYS + : btm_cb.ble_ctr_cb.inq_var.scan_phy; // use low latency scanning if the scanning is active uint16_t ll_scan_interval, ll_scan_window; std::tie(ll_scan_interval, ll_scan_window) = get_low_latency_scan_params(); if (low_latency_scan) { - std::tie(scan_interval, scan_window) = - std::tie(ll_scan_interval, ll_scan_window); + std::tie(scan_interval, scan_window) = std::tie(ll_scan_interval, ll_scan_window); } - log::verbose("scan_type:{}, {}, {}", btm_cb.ble_ctr_cb.inq_var.scan_type, - scan_interval, scan_window); + log::verbose("scan_type:{}, {}, {}", btm_cb.ble_ctr_cb.inq_var.scan_type, scan_interval, + scan_window); - if (!bluetooth::shim::GetController()->SupportsBle()) + if (!bluetooth::shim::GetController()->SupportsBle()) { return BTM_ILLEGAL_VALUE; + } if (start) { /* shared inquiry database, do not allow observe if any inquiry is active. @@ -568,8 +555,7 @@ tBTM_STATUS BTM_BleObserve(bool start, uint8_t duration, log::error("Scan with no duration started twice!"); } } else { - if (!low_latency_scan && - alarm_is_scheduled(btm_cb.ble_ctr_cb.observer_timer)) { + if (!low_latency_scan && alarm_is_scheduled(btm_cb.ble_ctr_cb.observer_timer)) { log::error("Scan with duration started twice!"); } } @@ -578,12 +564,10 @@ tBTM_STATUS BTM_BleObserve(bool start, uint8_t duration, * 1. if the scan we wish to start is not low latency * 2. current ongoing scanning is low latency */ - bool is_ongoing_low_latency = - btm_cb.ble_ctr_cb.inq_var.scan_interval == ll_scan_interval && - btm_cb.ble_ctr_cb.inq_var.scan_window == ll_scan_window; + bool is_ongoing_low_latency = btm_cb.ble_ctr_cb.inq_var.scan_interval == ll_scan_interval && + btm_cb.ble_ctr_cb.inq_var.scan_window == ll_scan_window; if (!low_latency_scan || is_ongoing_low_latency) { - log::warn("Observer was already active, is_low_latency: {}", - is_ongoing_low_latency); + log::warn("Observer was already active, is_low_latency: {}", is_ongoing_low_latency); return BTM_CMD_STARTED; } // stop any scan without low latency config @@ -599,25 +583,24 @@ tBTM_STATUS BTM_BleObserve(bool start, uint8_t duration, /* allow config of scan type */ cache.ClearAll(); btm_cb.ble_ctr_cb.inq_var.scan_type = - (btm_cb.ble_ctr_cb.inq_var.scan_type == BTM_BLE_SCAN_MODE_NONE) - ? BTM_BLE_SCAN_MODE_ACTI - : btm_cb.ble_ctr_cb.inq_var.scan_type; - btm_send_hci_set_scan_params( - btm_cb.ble_ctr_cb.inq_var.scan_type, (uint16_t)scan_interval, - (uint8_t)scan_phy, (uint16_t)scan_window, - btm_cb.ble_ctr_cb.addr_mgnt_cb.own_addr_type, BTM_BLE_DEFAULT_SFP); + (btm_cb.ble_ctr_cb.inq_var.scan_type == BTM_BLE_SCAN_MODE_NONE) + ? BTM_BLE_SCAN_MODE_ACTI + : btm_cb.ble_ctr_cb.inq_var.scan_type; + btm_send_hci_set_scan_params(btm_cb.ble_ctr_cb.inq_var.scan_type, (uint16_t)scan_interval, + (uint8_t)scan_phy, (uint16_t)scan_window, + btm_cb.ble_ctr_cb.addr_mgnt_cb.own_addr_type, + BTM_BLE_DEFAULT_SFP); btm_ble_start_scan(); } btm_cb.neighbor.le_observe = { - .start_time_ms = timestamper_in_milliseconds.GetTimestamp(), - .results = 0, + .start_time_ms = timestamper_in_milliseconds.GetTimestamp(), + .results = 0, }; BTM_LogHistory(kBtmLogTag, RawAddress::kEmpty, "Le observe started", - base::StringPrintf("low latency scanning enabled: %d", - low_latency_scan)); + base::StringPrintf("low latency scanning enabled: %d", low_latency_scan)); if (status == BTM_CMD_STARTED) { btm_cb.ble_ctr_cb.set_ble_observe_active(); @@ -630,8 +613,7 @@ tBTM_STATUS BTM_BleObserve(bool start, uint8_t duration, } } else if (btm_cb.ble_ctr_cb.is_ble_observe_active()) { const unsigned long long duration_timestamp = - timestamper_in_milliseconds.GetTimestamp() - - btm_cb.neighbor.le_observe.start_time_ms; + timestamper_in_milliseconds.GetTimestamp() - btm_cb.neighbor.le_observe.start_time_ms; BTM_LogHistory(kBtmLogTag, RawAddress::kEmpty, "Le observe stopped", base::StringPrintf("duration_s:%6.3f results:%-3lu", (double)duration_timestamp / 1000.0, @@ -662,8 +644,7 @@ void BTM_BleGetVendorCapabilities(tBTM_BLE_VSC_CB* p_cmn_vsc_cb) { } } -void BTM_BleGetDynamicAudioBuffer( - tBTM_BT_DYNAMIC_AUDIO_BUFFER_CB p_dynamic_audio_buffer_cb[]) { +void BTM_BleGetDynamicAudioBuffer(tBTM_BT_DYNAMIC_AUDIO_BUFFER_CB p_dynamic_audio_buffer_cb[]) { log::verbose("BTM_BleGetDynamicAudioBuffer"); if (NULL != p_dynamic_audio_buffer_cb) { @@ -686,65 +667,58 @@ void BTM_BleGetDynamicAudioBuffer( * ******************************************************************************/ void BTM_BleReadControllerFeatures(tBTM_BLE_CTRL_FEATURES_CBACK* p_vsc_cback) { - if (!ble_vnd_is_included()) return; + if (!ble_vnd_is_included()) { + return; + } - if (btm_cb.cmn_ble_vsc_cb.values_read) return; + if (btm_cb.cmn_ble_vsc_cb.values_read) { + return; + } log::verbose("BTM_BleReadControllerFeatures"); btm_cb.cmn_ble_vsc_cb.values_read = true; bluetooth::hci::ControllerInterface::VendorCapabilities vendor_capabilities = - GetController()->GetVendorCapabilities(); + GetController()->GetVendorCapabilities(); btm_cb.cmn_ble_vsc_cb.adv_inst_max = vendor_capabilities.max_advt_instances_; btm_cb.cmn_ble_vsc_cb.rpa_offloading = - vendor_capabilities.offloaded_resolution_of_private_address_; - btm_cb.cmn_ble_vsc_cb.tot_scan_results_strg = - vendor_capabilities.total_scan_results_storage_; + vendor_capabilities.offloaded_resolution_of_private_address_; + btm_cb.cmn_ble_vsc_cb.tot_scan_results_strg = vendor_capabilities.total_scan_results_storage_; btm_cb.cmn_ble_vsc_cb.max_irk_list_sz = vendor_capabilities.max_irk_list_sz_; btm_cb.cmn_ble_vsc_cb.filter_support = vendor_capabilities.filtering_support_; btm_cb.cmn_ble_vsc_cb.max_filter = vendor_capabilities.max_filter_; - btm_cb.cmn_ble_vsc_cb.energy_support = - vendor_capabilities.activity_energy_info_support_; + btm_cb.cmn_ble_vsc_cb.energy_support = vendor_capabilities.activity_energy_info_support_; - btm_cb.cmn_ble_vsc_cb.version_supported = - vendor_capabilities.version_supported_; + btm_cb.cmn_ble_vsc_cb.version_supported = vendor_capabilities.version_supported_; btm_cb.cmn_ble_vsc_cb.total_trackable_advertisers = - vendor_capabilities.total_num_of_advt_tracked_; - btm_cb.cmn_ble_vsc_cb.extended_scan_support = - vendor_capabilities.extended_scan_support_; - btm_cb.cmn_ble_vsc_cb.debug_logging_supported = - vendor_capabilities.debug_logging_supported_; + vendor_capabilities.total_num_of_advt_tracked_; + btm_cb.cmn_ble_vsc_cb.extended_scan_support = vendor_capabilities.extended_scan_support_; + btm_cb.cmn_ble_vsc_cb.debug_logging_supported = vendor_capabilities.debug_logging_supported_; btm_cb.cmn_ble_vsc_cb.le_address_generation_offloading_support = - vendor_capabilities.le_address_generation_offloading_support_; + vendor_capabilities.le_address_generation_offloading_support_; btm_cb.cmn_ble_vsc_cb.a2dp_source_offload_capability_mask = - vendor_capabilities.a2dp_source_offload_capability_mask_; + vendor_capabilities.a2dp_source_offload_capability_mask_; btm_cb.cmn_ble_vsc_cb.quality_report_support = - vendor_capabilities.bluetooth_quality_report_support_; + vendor_capabilities.bluetooth_quality_report_support_; btm_cb.cmn_ble_vsc_cb.dynamic_audio_buffer_support = - vendor_capabilities.dynamic_audio_buffer_support_; - btm_cb.cmn_ble_vsc_cb.a2dp_offload_v2_support = - vendor_capabilities.a2dp_offload_v2_support_; + vendor_capabilities.dynamic_audio_buffer_support_; + btm_cb.cmn_ble_vsc_cb.a2dp_offload_v2_support = vendor_capabilities.a2dp_offload_v2_support_; if (vendor_capabilities.dynamic_audio_buffer_support_) { - std::array - capabilities = GetController()->GetDabCodecCapabilities(); + std::array + capabilities = GetController()->GetDabCodecCapabilities(); for (size_t i = 0; i < capabilities.size(); i++) { - btm_cb.dynamic_audio_buffer_cb[i].default_buffer_time = - capabilities[i].default_time_ms_; - btm_cb.dynamic_audio_buffer_cb[i].maximum_buffer_time = - capabilities[i].maximum_time_ms_; - btm_cb.dynamic_audio_buffer_cb[i].minimum_buffer_time = - capabilities[i].minimum_time_ms_; + btm_cb.dynamic_audio_buffer_cb[i].default_buffer_time = capabilities[i].default_time_ms_; + btm_cb.dynamic_audio_buffer_cb[i].maximum_buffer_time = capabilities[i].maximum_time_ms_; + btm_cb.dynamic_audio_buffer_cb[i].minimum_buffer_time = capabilities[i].minimum_time_ms_; } } if (btm_cb.cmn_ble_vsc_cb.filter_support == 1 && - GetController()->GetLocalVersionInformation().manufacturer_name_ == - LMP_COMPID_QTI) { + GetController()->GetLocalVersionInformation().manufacturer_name_ == LMP_COMPID_QTI) { // QTI controller, TDS data filter are supported by default. btm_cb.cmn_ble_vsc_cb.adv_filter_extended_features_mask = 0x01; } else { @@ -752,18 +726,17 @@ void BTM_BleReadControllerFeatures(tBTM_BLE_CTRL_FEATURES_CBACK* p_vsc_cback) { } log::verbose("irk={}, ADV ins:{}, rpa={}, ener={}, ext_scan={}", - btm_cb.cmn_ble_vsc_cb.max_irk_list_sz, - btm_cb.cmn_ble_vsc_cb.adv_inst_max, - btm_cb.cmn_ble_vsc_cb.rpa_offloading, - btm_cb.cmn_ble_vsc_cb.energy_support, + btm_cb.cmn_ble_vsc_cb.max_irk_list_sz, btm_cb.cmn_ble_vsc_cb.adv_inst_max, + btm_cb.cmn_ble_vsc_cb.rpa_offloading, btm_cb.cmn_ble_vsc_cb.energy_support, btm_cb.cmn_ble_vsc_cb.extended_scan_support); - if (btm_cb.cmn_ble_vsc_cb.max_filter > 0) btm_ble_adv_filter_init(); + if (btm_cb.cmn_ble_vsc_cb.max_filter > 0) { + btm_ble_adv_filter_init(); + } /* VS capability included and non-4.2 device */ if (GetController()->SupportsBle() && GetController()->SupportsBlePrivacy() && - btm_cb.cmn_ble_vsc_cb.max_irk_list_sz > 0 && - GetController()->GetLeResolvingListSize() == 0) { + btm_cb.cmn_ble_vsc_cb.max_irk_list_sz > 0 && GetController()->GetLeResolvingListSize() == 0) { btm_ble_resolving_list_init(btm_cb.cmn_ble_vsc_cb.max_irk_list_sz); } @@ -788,7 +761,9 @@ bool BTM_BleConfigPrivacy(bool privacy_mode) { log::warn("{}", (int)privacy_mode); /* if LE is not supported, return error */ - if (!bluetooth::shim::GetController()->SupportsBle()) return false; + if (!bluetooth::shim::GetController()->SupportsBle()) { + return false; + } tGAP_BLE_ATTR_VALUE gap_ble_attr_value; gap_ble_attr_value.addr_resolution = 0; @@ -797,11 +772,10 @@ bool BTM_BleConfigPrivacy(bool privacy_mode) { btm_cb.ble_ctr_cb.addr_mgnt_cb.own_addr_type = BLE_ADDR_PUBLIC; /* This is a Floss only flag. Allow host use random address when privacy * mode is not enabled by setting the sysprop true */ - if (com::android::bluetooth::flags:: - floss_separate_host_privacy_and_llprivacy()) { - if (osi_property_get_bool(PROPERTY_BLE_PRIVACY_OWN_ADDRESS_ENABLED, - privacy_mode)) + if (com::android::bluetooth::flags::floss_separate_host_privacy_and_llprivacy()) { + if (osi_property_get_bool(PROPERTY_BLE_PRIVACY_OWN_ADDRESS_ENABLED, privacy_mode)) { btm_cb.ble_ctr_cb.addr_mgnt_cb.own_addr_type = BLE_ADDR_RANDOM; + } } btm_cb.ble_ctr_cb.privacy_mode = BTM_PRIVACY_NONE; } else /* privacy is turned on*/ @@ -811,12 +785,11 @@ bool BTM_BleConfigPrivacy(bool privacy_mode) { btm_cb.ble_ctr_cb.addr_mgnt_cb.own_addr_type = BLE_ADDR_RANDOM; /* This is a Floss only flag. Allow host use public address when privacy * mode is enabled by setting the sysprop false */ - if (com::android::bluetooth::flags:: - floss_separate_host_privacy_and_llprivacy()) { + if (com::android::bluetooth::flags::floss_separate_host_privacy_and_llprivacy()) { /* use public address if own address privacy is false in sysprop */ - if (!osi_property_get_bool(PROPERTY_BLE_PRIVACY_OWN_ADDRESS_ENABLED, - privacy_mode)) + if (!osi_property_get_bool(PROPERTY_BLE_PRIVACY_OWN_ADDRESS_ENABLED, privacy_mode)) { btm_cb.ble_ctr_cb.addr_mgnt_cb.own_addr_type = BLE_ADDR_PUBLIC; + } } /* 4.2 controller only allow privacy 1.2 or mixed mode, resolvable private @@ -824,11 +797,11 @@ bool BTM_BleConfigPrivacy(bool privacy_mode) { if (bluetooth::shim::GetController()->SupportsBlePrivacy()) { gap_ble_attr_value.addr_resolution = 1; btm_cb.ble_ctr_cb.privacy_mode = BTM_PRIVACY_1_2; - } else /* 4.1/4.0 controller */ + } else { /* 4.1/4.0 controller */ btm_cb.ble_ctr_cb.privacy_mode = BTM_PRIVACY_1_1; + } } - log::verbose("privacy_mode: {} own_addr_type: {}", - btm_cb.ble_ctr_cb.privacy_mode, + log::verbose("privacy_mode: {} own_addr_type: {}", btm_cb.ble_ctr_cb.privacy_mode, btm_cb.ble_ctr_cb.addr_mgnt_cb.own_addr_type); GAP_BleAttrDBUpdate(GATT_UUID_GAP_CENTRAL_ADDR_RESOL, &gap_ble_attr_value); @@ -846,15 +819,14 @@ bool BTM_BleConfigPrivacy(bool privacy_mode) { * Returns Return true if local privacy is enabled else false * ******************************************************************************/ -bool BTM_BleLocalPrivacyEnabled(void) { - return (btm_cb.ble_ctr_cb.privacy_mode != BTM_PRIVACY_NONE); -} +bool BTM_BleLocalPrivacyEnabled(void) { return btm_cb.ble_ctr_cb.privacy_mode != BTM_PRIVACY_NONE; } static bool is_resolving_list_bit_set(void* data, void* /* context */) { tBTM_SEC_DEV_REC* p_dev_rec = static_cast(data); - if ((p_dev_rec->ble.in_controller_list & BTM_RESOLVING_LIST_BIT) != 0) + if ((p_dev_rec->ble.in_controller_list & BTM_RESOLVING_LIST_BIT) != 0) { return false; + } return true; } @@ -872,9 +844,8 @@ static void sync_queue_add(sync_node_t* p_param) { } // Validity check - log::assert_that( - list_length(sync_queue) < MAX_SYNC_TRANSACTION, - "assert failed: list_length(sync_queue) < MAX_SYNC_TRANSACTION"); + log::assert_that(list_length(sync_queue) < MAX_SYNC_TRANSACTION, + "assert failed: list_length(sync_queue) < MAX_SYNC_TRANSACTION"); sync_node_t* p_node = (sync_node_t*)osi_malloc(sizeof(sync_node_t)); *p_node = *p_param; list_append(sync_queue, p_node); @@ -902,17 +873,15 @@ static void sync_queue_cleanup(remove_sync_node_t* p_param) { while (node && node != list_end(sync_queue)) { sync_request = (sync_node_t*)list_node(node); node = list_next(node); - if (sync_request->sid == p_param->sid && - sync_request->address == p_param->address) { - log::info("removing connection request SID={:04X}, bd_addr={}, busy={}", - sync_request->sid, sync_request->address, sync_request->busy); + if (sync_request->sid == p_param->sid && sync_request->address == p_param->address) { + log::info("removing connection request SID={:04X}, bd_addr={}, busy={}", sync_request->sid, + sync_request->address, sync_request->busy); list_remove(sync_queue, sync_request); } } } -void btm_ble_start_sync_request(uint8_t sid, RawAddress addr, uint16_t skip, - uint16_t timeout) { +void btm_ble_start_sync_request(uint8_t sid, RawAddress addr, uint16_t skip, uint16_t timeout) { tBLE_ADDR_TYPE address_type = BLE_ADDR_RANDOM; tINQ_DB_ENT* p_i = btm_inq_db_find(addr); if (p_i) { @@ -933,8 +902,8 @@ void btm_ble_start_sync_request(uint8_t sid, RawAddress addr, uint16_t skip, p->sync_state = PERIODIC_SYNC_PENDING; if (BleScanningManager::IsInitialized()) { - BleScanningManager::Get()->PeriodicScanStart(options, sid, address_type, - addr, skip, timeout, cte_type); + BleScanningManager::Get()->PeriodicScanStart(options, sid, address_type, addr, skip, timeout, + cte_type); } alarm_set(sync_timeout_alarm, SYNC_TIMEOUT, btm_ble_start_sync_timeout, NULL); @@ -948,8 +917,7 @@ static void btm_queue_sync_next() { sync_node_t* p_head = (sync_node_t*)list_front(sync_queue); - log::info("executing sync request SID={:04X}, bd_addr={}", p_head->sid, - p_head->address); + log::info("executing sync request SID={:04X}, bd_addr={}", p_head->sid, p_head->address); if (p_head->busy) { log::debug("BUSY"); return; @@ -957,8 +925,7 @@ static void btm_queue_sync_next() { p_head->busy = true; alarm_cancel(sync_timeout_alarm); - btm_ble_start_sync_request(p_head->sid, p_head->address, p_head->skip, - p_head->timeout); + btm_ble_start_sync_request(p_head->sid, p_head->address, p_head->skip, p_head->timeout); } static void btm_ble_sync_queue_handle(uint16_t event, char* param) { @@ -1044,17 +1011,14 @@ static int btm_ble_get_psync_index(uint8_t adv_sid, RawAddress addr) { * * ******************************************************************************/ -void btm_ble_periodic_adv_sync_established(uint8_t status, uint16_t sync_handle, - uint8_t adv_sid, - uint8_t address_type, - const RawAddress& addr, uint8_t phy, - uint16_t interval, +void btm_ble_periodic_adv_sync_established(uint8_t status, uint16_t sync_handle, uint8_t adv_sid, + uint8_t address_type, const RawAddress& addr, + uint8_t phy, uint16_t interval, uint8_t adv_clock_accuracy) { log::debug( - "[PSync]: status={}, sync_handle={}, s_id={}, addr_type={}, " - "adv_phy={},adv_interval={}, clock_acc={}", - status, sync_handle, adv_sid, address_type, phy, interval, - adv_clock_accuracy); + "[PSync]: status={}, sync_handle={}, s_id={}, addr_type={}, " + "adv_phy={},adv_interval={}, clock_acc={}", + status, sync_handle, adv_sid, address_type, phy, interval, adv_clock_accuracy); /*if (param_len != ADV_SYNC_ESTB_EVT_LEN) { log::error("[PSync]Invalid event length"); @@ -1091,8 +1055,8 @@ void btm_ble_periodic_adv_sync_established(uint8_t status, uint16_t sync_handle, tBTM_BLE_PERIODIC_SYNC* ps = &btm_ble_pa_sync_cb.p_sync[index]; ps->sync_handle = sync_handle; ps->sync_state = PERIODIC_SYNC_ESTABLISHED; - ps->sync_start_cb.Run(status, sync_handle, adv_sid, - from_ble_addr_type(ble_addr_type), bda, phy, interval); + ps->sync_start_cb.Run(status, sync_handle, adv_sid, from_ble_addr_type(ble_addr_type), bda, phy, + interval); btm_sync_queue_advance(); } @@ -1104,14 +1068,13 @@ void btm_ble_periodic_adv_sync_established(uint8_t status, uint16_t sync_handle, * to a PA requested from host * ******************************************************************************/ -void btm_ble_periodic_adv_report(uint16_t sync_handle, uint8_t tx_power, - int8_t rssi, uint8_t cte_type, - uint8_t data_status, uint8_t data_len, +void btm_ble_periodic_adv_report(uint16_t sync_handle, uint8_t tx_power, int8_t rssi, + uint8_t cte_type, uint8_t data_status, uint8_t data_len, const uint8_t* periodic_data) { log::debug( - "[PSync]: sync_handle = {}, tx_power = {}, rssi = {},cte_type = {}, " - "data_status = {}, data_len = {}", - sync_handle, tx_power, rssi, cte_type, data_status, data_len); + "[PSync]: sync_handle = {}, tx_power = {}, rssi = {},cte_type = {}, " + "data_status = {}, data_len = {}", + sync_handle, tx_power, rssi, cte_type, data_status, data_len); std::vector data; for (int i = 0; i < data_len; i++) { @@ -1156,14 +1119,14 @@ void btm_ble_periodic_adv_sync_lost(uint16_t sync_handle) { * * Function btm_set_conn_mode_adv_init_addr * - * Description set initator address type and local address type based on + * Description set initiator address type and local address type based on * adv mode. * * ******************************************************************************/ -static uint8_t btm_set_conn_mode_adv_init_addr( - RawAddress& p_peer_addr_ptr, tBLE_ADDR_TYPE* p_peer_addr_type, - tBLE_ADDR_TYPE* p_own_addr_type) { +static uint8_t btm_set_conn_mode_adv_init_addr(RawAddress& p_peer_addr_ptr, + tBLE_ADDR_TYPE* p_peer_addr_type, + tBLE_ADDR_TYPE* p_own_addr_type) { uint8_t evt_type; tBTM_SEC_DEV_REC* p_dev_rec; @@ -1178,29 +1141,25 @@ static uint8_t btm_set_conn_mode_adv_init_addr( } if (evt_type == BTM_BLE_CONNECT_EVT) { - log::assert_that(p_peer_addr_type != nullptr, - "assert failed: p_peer_addr_type != nullptr"); + log::assert_that(p_peer_addr_type != nullptr, "assert failed: p_peer_addr_type != nullptr"); const tBLE_BD_ADDR ble_bd_addr = { - .type = *p_peer_addr_type, - .bda = p_peer_addr_ptr, + .type = *p_peer_addr_type, + .bda = p_peer_addr_ptr, }; log::debug("Received BLE connect event {}", ble_bd_addr); evt_type = btm_cb.ble_ctr_cb.inq_var.directed_conn; if (static_cast>( - btm_cb.ble_ctr_cb.inq_var.directed_conn) == - BTM_BLE_CONNECT_DIR_EVT || + btm_cb.ble_ctr_cb.inq_var.directed_conn) == BTM_BLE_CONNECT_DIR_EVT || static_cast>( - btm_cb.ble_ctr_cb.inq_var.directed_conn) == - BTM_BLE_CONNECT_LO_DUTY_DIR_EVT) { + btm_cb.ble_ctr_cb.inq_var.directed_conn) == BTM_BLE_CONNECT_LO_DUTY_DIR_EVT) { /* for privacy 1.2, convert peer address as static, own address set as ID * addr */ if (btm_cb.ble_ctr_cb.privacy_mode == BTM_PRIVACY_1_2 || btm_cb.ble_ctr_cb.privacy_mode == BTM_PRIVACY_MIXED) { /* only do so for bonded device */ - if ((p_dev_rec = btm_find_or_alloc_dev( - btm_cb.ble_ctr_cb.inq_var.direct_bda.bda)) != NULL && + if ((p_dev_rec = btm_find_or_alloc_dev(btm_cb.ble_ctr_cb.inq_var.direct_bda.bda)) != NULL && p_dev_rec->ble.in_controller_list & BTM_RESOLVING_LIST_BIT) { p_peer_addr_ptr = p_dev_rec->ble.identity_address_with_type.bda; *p_peer_addr_type = p_dev_rec->ble.identity_address_with_type.type; @@ -1221,13 +1180,11 @@ static uint8_t btm_set_conn_mode_adv_init_addr( if ((btm_cb.ble_ctr_cb.privacy_mode == BTM_PRIVACY_1_2 && btm_cb.ble_ctr_cb.inq_var.afp != AP_SCAN_CONN_ALL) || btm_cb.ble_ctr_cb.privacy_mode == BTM_PRIVACY_MIXED) { - list_node_t* n = - list_foreach(btm_sec_cb.sec_dev_rec, is_resolving_list_bit_set, NULL); + list_node_t* n = list_foreach(btm_sec_cb.sec_dev_rec, is_resolving_list_bit_set, NULL); if (n) { /* if enhanced privacy is required, set Identity address and matching IRK * peer */ - tBTM_SEC_DEV_REC* p_dev_rec = - static_cast(list_node(n)); + tBTM_SEC_DEV_REC* p_dev_rec = static_cast(list_node(n)); p_peer_addr_ptr = p_dev_rec->ble.identity_address_with_type.bda; *p_peer_addr_type = p_dev_rec->ble.identity_address_with_type.type; @@ -1258,8 +1215,7 @@ static uint8_t btm_set_conn_mode_adv_init_addr( * Returns void * ******************************************************************************/ -static void btm_ble_select_adv_interval(uint8_t evt_type, - uint16_t* p_adv_int_min, +static void btm_ble_select_adv_interval(uint8_t evt_type, uint16_t* p_adv_int_min, uint16_t* p_adv_int_max) { switch (evt_type) { case BTM_BLE_CONNECT_EVT: @@ -1300,22 +1256,22 @@ static void btm_ble_select_adv_interval(uint8_t evt_type, * Returns void * ******************************************************************************/ -void btm_ble_update_dmt_flag_bits(uint8_t* adv_flag_value, - const uint16_t connect_mode, +void btm_ble_update_dmt_flag_bits(uint8_t* adv_flag_value, const uint16_t connect_mode, const uint16_t disc_mode) { /* BR/EDR non-discoverable , non-connectable */ - if ((disc_mode & BTM_DISCOVERABLE_MASK) == 0 && - (connect_mode & BTM_CONNECTABLE_MASK) == 0) + if ((disc_mode & BTM_DISCOVERABLE_MASK) == 0 && (connect_mode & BTM_CONNECTABLE_MASK) == 0) { *adv_flag_value |= BTM_BLE_BREDR_NOT_SPT; - else + } else { *adv_flag_value &= ~BTM_BLE_BREDR_NOT_SPT; + } /* if local controller support, mark both controller and host support in flag */ - if (bluetooth::shim::GetController()->SupportsSimultaneousLeBrEdr()) + if (bluetooth::shim::GetController()->SupportsSimultaneousLeBrEdr()) { *adv_flag_value |= (BTM_BLE_DMT_CONTROLLER_SPT | BTM_BLE_DMT_HOST_SPT); - else + } else { *adv_flag_value &= ~(BTM_BLE_DMT_CONTROLLER_SPT | BTM_BLE_DMT_HOST_SPT); + } } /******************************************************************************* @@ -1334,7 +1290,9 @@ void btm_ble_set_adv_flag(uint16_t connect_mode, uint16_t disc_mode) { uint8_t flag = 0, old_flag = 0; tBTM_BLE_LOCAL_ADV_DATA* p_adv_data = &btm_cb.ble_ctr_cb.inq_var.adv_data; - if (p_adv_data->p_flags != NULL) flag = old_flag = *(p_adv_data->p_flags); + if (p_adv_data->p_flags != NULL) { + flag = old_flag = *(p_adv_data->p_flags); + } btm_ble_update_dmt_flag_bits(&flag, connect_mode, disc_mode); @@ -1373,23 +1331,24 @@ tBTM_STATUS btm_ble_set_discoverability(uint16_t combined_mode) { uint8_t evt_type; tBTM_STATUS status = BTM_SUCCESS; RawAddress address = RawAddress::kEmpty; - tBLE_ADDR_TYPE init_addr_type = BLE_ADDR_PUBLIC, - own_addr_type = p_addr_cb->own_addr_type; + tBLE_ADDR_TYPE init_addr_type = BLE_ADDR_PUBLIC, own_addr_type = p_addr_cb->own_addr_type; uint16_t adv_int_min, adv_int_max; log::verbose("mode=0x{:0x} combined_mode=0x{:x}", mode, combined_mode); /*** Check mode parameter ***/ - if (mode > BTM_BLE_MAX_DISCOVERABLE) return (BTM_ILLEGAL_VALUE); + if (mode > BTM_BLE_MAX_DISCOVERABLE) { + return BTM_ILLEGAL_VALUE; + } btm_cb.ble_ctr_cb.inq_var.discoverable_mode = mode; - evt_type = - btm_set_conn_mode_adv_init_addr(address, &init_addr_type, &own_addr_type); + evt_type = btm_set_conn_mode_adv_init_addr(address, &init_addr_type, &own_addr_type); if (btm_cb.ble_ctr_cb.inq_var.connectable_mode == BTM_BLE_NON_CONNECTABLE && - mode == BTM_BLE_NON_DISCOVERABLE) + mode == BTM_BLE_NON_DISCOVERABLE) { new_mode = BTM_BLE_ADV_DISABLE; + } btm_ble_select_adv_interval(evt_type, &adv_int_min, &adv_int_max); @@ -1408,38 +1367,35 @@ tBTM_STATUS btm_ble_set_discoverability(uint16_t combined_mode) { btm_ble_stop_adv(); /* update adv params */ - btsnd_hcic_ble_write_adv_params(adv_int_min, adv_int_max, evt_type, - own_addr_type, init_addr_type, address, - btm_cb.ble_ctr_cb.inq_var.adv_chnl_map, - btm_cb.ble_ctr_cb.inq_var.afp); + btsnd_hcic_ble_write_adv_params( + adv_int_min, adv_int_max, evt_type, own_addr_type, init_addr_type, address, + btm_cb.ble_ctr_cb.inq_var.adv_chnl_map, btm_cb.ble_ctr_cb.inq_var.afp); btm_cb.ble_ctr_cb.inq_var.evt_type = evt_type; btm_cb.ble_ctr_cb.inq_var.adv_addr_type = own_addr_type; } } if (status == BTM_SUCCESS && btm_cb.ble_ctr_cb.inq_var.adv_mode != new_mode) { - if (new_mode == BTM_BLE_ADV_ENABLE) + if (new_mode == BTM_BLE_ADV_ENABLE) { status = btm_ble_start_adv(); - else + } else { status = btm_ble_stop_adv(); + } } if (btm_cb.ble_ctr_cb.inq_var.adv_mode == BTM_BLE_ADV_ENABLE) { btm_cb.ble_ctr_cb.inq_var.fast_adv_on = true; /* start initial GAP mode adv timer */ - alarm_set_on_mloop(btm_cb.ble_ctr_cb.inq_var.fast_adv_timer, - BTM_BLE_GAP_FAST_ADV_TIMEOUT_MS, + alarm_set_on_mloop(btm_cb.ble_ctr_cb.inq_var.fast_adv_timer, BTM_BLE_GAP_FAST_ADV_TIMEOUT_MS, btm_ble_fast_adv_timer_timeout, NULL); } /* set up stop advertising timer */ if (status == BTM_SUCCESS && mode == BTM_BLE_LIMITED_DISCOVERABLE) { - log::verbose("start timer for limited disc mode duration={} ms", - BTM_BLE_GAP_LIM_TIMEOUT_MS); + log::verbose("start timer for limited disc mode duration={} ms", BTM_BLE_GAP_LIM_TIMEOUT_MS); /* start Tgap(lim_timeout) */ - alarm_set_on_mloop( - btm_cb.ble_ctr_cb.inq_var.inquiry_timer, BTM_BLE_GAP_LIM_TIMEOUT_MS, - btm_ble_inquiry_timer_gap_limited_discovery_timeout, NULL); + alarm_set_on_mloop(btm_cb.ble_ctr_cb.inq_var.inquiry_timer, BTM_BLE_GAP_LIM_TIMEOUT_MS, + btm_ble_inquiry_timer_gap_limited_discovery_timeout, NULL); } return status; } @@ -1462,23 +1418,24 @@ tBTM_STATUS btm_ble_set_connectability(uint16_t combined_mode) { uint8_t evt_type; tBTM_STATUS status = BTM_SUCCESS; RawAddress address = RawAddress::kEmpty; - tBLE_ADDR_TYPE peer_addr_type = BLE_ADDR_PUBLIC, - own_addr_type = p_addr_cb->own_addr_type; + tBLE_ADDR_TYPE peer_addr_type = BLE_ADDR_PUBLIC, own_addr_type = p_addr_cb->own_addr_type; uint16_t adv_int_min, adv_int_max; log::verbose("mode=0x{:0x} combined_mode=0x{:x}", mode, combined_mode); /*** Check mode parameter ***/ - if (mode > BTM_BLE_MAX_CONNECTABLE) return (BTM_ILLEGAL_VALUE); + if (mode > BTM_BLE_MAX_CONNECTABLE) { + return BTM_ILLEGAL_VALUE; + } btm_cb.ble_ctr_cb.inq_var.connectable_mode = mode; - evt_type = - btm_set_conn_mode_adv_init_addr(address, &peer_addr_type, &own_addr_type); + evt_type = btm_set_conn_mode_adv_init_addr(address, &peer_addr_type, &own_addr_type); if (mode == BTM_BLE_NON_CONNECTABLE && - btm_cb.ble_ctr_cb.inq_var.discoverable_mode == BTM_BLE_NON_DISCOVERABLE) + btm_cb.ble_ctr_cb.inq_var.discoverable_mode == BTM_BLE_NON_DISCOVERABLE) { new_mode = BTM_BLE_ADV_DISABLE; + } btm_ble_select_adv_interval(evt_type, &adv_int_min, &adv_int_max); @@ -1491,10 +1448,9 @@ tBTM_STATUS btm_ble_set_connectability(uint16_t combined_mode) { !btm_cb.ble_ctr_cb.inq_var.fast_adv_on) { btm_ble_stop_adv(); - btsnd_hcic_ble_write_adv_params(adv_int_min, adv_int_max, evt_type, - own_addr_type, peer_addr_type, address, - btm_cb.ble_ctr_cb.inq_var.adv_chnl_map, - btm_cb.ble_ctr_cb.inq_var.afp); + btsnd_hcic_ble_write_adv_params( + adv_int_min, adv_int_max, evt_type, own_addr_type, peer_addr_type, address, + btm_cb.ble_ctr_cb.inq_var.adv_chnl_map, btm_cb.ble_ctr_cb.inq_var.afp); btm_cb.ble_ctr_cb.inq_var.evt_type = evt_type; btm_cb.ble_ctr_cb.inq_var.adv_addr_type = own_addr_type; } @@ -1502,35 +1458,32 @@ tBTM_STATUS btm_ble_set_connectability(uint16_t combined_mode) { /* update advertising mode */ if (status == BTM_SUCCESS && new_mode != btm_cb.ble_ctr_cb.inq_var.adv_mode) { - if (new_mode == BTM_BLE_ADV_ENABLE) + if (new_mode == BTM_BLE_ADV_ENABLE) { status = btm_ble_start_adv(); - else + } else { status = btm_ble_stop_adv(); + } } if (btm_cb.ble_ctr_cb.inq_var.adv_mode == BTM_BLE_ADV_ENABLE) { btm_cb.ble_ctr_cb.inq_var.fast_adv_on = true; /* start initial GAP mode adv timer */ - alarm_set_on_mloop(btm_cb.ble_ctr_cb.inq_var.fast_adv_timer, - BTM_BLE_GAP_FAST_ADV_TIMEOUT_MS, + alarm_set_on_mloop(btm_cb.ble_ctr_cb.inq_var.fast_adv_timer, BTM_BLE_GAP_FAST_ADV_TIMEOUT_MS, btm_ble_fast_adv_timer_timeout, NULL); } return status; } -static void btm_send_hci_scan_enable(uint8_t enable, - uint8_t filter_duplicates) { +static void btm_send_hci_scan_enable(uint8_t enable, uint8_t filter_duplicates) { if (bluetooth::shim::GetController()->SupportsBleExtendedAdvertising()) { - btsnd_hcic_ble_set_extended_scan_enable(enable, filter_duplicates, 0x0000, - 0x0000); + btsnd_hcic_ble_set_extended_scan_enable(enable, filter_duplicates, 0x0000, 0x0000); } else { btsnd_hcic_ble_set_scan_enable(enable, filter_duplicates); } } -void btm_send_hci_set_scan_params(uint8_t scan_type, uint16_t scan_int, - uint16_t scan_win, uint8_t scan_phy, - tBLE_ADDR_TYPE addr_type_own, +void btm_send_hci_set_scan_params(uint8_t scan_type, uint16_t scan_int, uint16_t scan_win, + uint8_t scan_phy, tBLE_ADDR_TYPE addr_type_own, uint8_t scan_filter_policy) { if (bluetooth::shim::GetController()->SupportsBleExtendedAdvertising()) { scanning_phy_cfg phy_cfg; @@ -1539,11 +1492,10 @@ void btm_send_hci_set_scan_params(uint8_t scan_type, uint16_t scan_int, phy_cfg.scan_win = scan_win; if (com::android::bluetooth::flags::phy_to_native()) { - btsnd_hcic_ble_set_extended_scan_params(addr_type_own, scan_filter_policy, - scan_phy, &phy_cfg); + btsnd_hcic_ble_set_extended_scan_params(addr_type_own, scan_filter_policy, scan_phy, + &phy_cfg); } else { - btsnd_hcic_ble_set_extended_scan_params(addr_type_own, scan_filter_policy, - 1, &phy_cfg); + btsnd_hcic_ble_set_extended_scan_params(addr_type_own, scan_filter_policy, 1, &phy_cfg); } } else { btsnd_hcic_ble_set_scan_params(scan_type, scan_int, scan_win, addr_type_own, @@ -1552,9 +1504,9 @@ void btm_send_hci_set_scan_params(uint8_t scan_type, uint16_t scan_int, } /* Scan filter param config event */ -static void btm_ble_scan_filt_param_cfg_evt( - uint8_t /* avbl_space */, tBTM_BLE_SCAN_COND_OP /* action_type */, - tBTM_STATUS btm_status) { +static void btm_ble_scan_filt_param_cfg_evt(uint8_t /* avbl_space */, + tBTM_BLE_SCAN_COND_OP /* action_type */, + tBTM_STATUS btm_status) { if (btm_status != btm_status_value(BTM_SUCCESS)) { log::error("{}", btm_status); } else { @@ -1577,20 +1529,18 @@ static void btm_ble_scan_filt_param_cfg_evt( * ******************************************************************************/ tBTM_STATUS btm_ble_start_inquiry(uint8_t duration) { - log::verbose("btm_ble_start_inquiry: inq_active = 0x{:02x}", - btm_cb.btm_inq_vars.inq_active); + log::verbose("btm_ble_start_inquiry: inq_active = 0x{:02x}", btm_cb.btm_inq_vars.inq_active); /* if selective connection is active, or inquiry is already active, reject it */ if (btm_cb.ble_ctr_cb.is_ble_inquiry_active()) { log::error("LE Inquiry is active, can not start inquiry"); - return (BTM_BUSY); + return BTM_BUSY; } /* Cleanup anything remaining on index 0 */ - BTM_BleAdvFilterParamSetup(BTM_BLE_SCAN_COND_DELETE, - static_cast(0), nullptr, - base::Bind(btm_ble_scan_filt_param_cfg_evt)); + BTM_BleAdvFilterParamSetup(BTM_BLE_SCAN_COND_DELETE, static_cast(0), + nullptr, base::Bind(btm_ble_scan_filt_param_cfg_evt)); auto adv_filt_param = std::make_unique(); /* Add an allow-all filter on index 0*/ @@ -1601,7 +1551,8 @@ tBTM_STATUS btm_ble_start_inquiry(uint8_t duration) { adv_filt_param->rssi_low_thres = LOWEST_RSSI_VALUE; adv_filt_param->rssi_high_thres = LOWEST_RSSI_VALUE; BTM_BleAdvFilterParamSetup(BTM_BLE_SCAN_COND_ADD, static_cast(0), - std::move(adv_filt_param), base::Bind(btm_ble_scan_filt_param_cfg_evt)); + std::move(adv_filt_param), + base::Bind(btm_ble_scan_filt_param_cfg_evt)); uint16_t scan_interval, scan_window; @@ -1610,9 +1561,8 @@ tBTM_STATUS btm_ble_start_inquiry(uint8_t duration) { if (!btm_cb.ble_ctr_cb.is_ble_scan_active()) { cache.ClearAll(); - btm_send_hci_set_scan_params( - BTM_BLE_SCAN_MODE_ACTI, scan_interval, scan_window, scan_phy, - btm_cb.ble_ctr_cb.addr_mgnt_cb.own_addr_type, SP_ADV_ALL); + btm_send_hci_set_scan_params(BTM_BLE_SCAN_MODE_ACTI, scan_interval, scan_window, scan_phy, + btm_cb.ble_ctr_cb.addr_mgnt_cb.own_addr_type, SP_ADV_ALL); btm_cb.ble_ctr_cb.inq_var.scan_type = BTM_BLE_SCAN_MODE_ACTI; btm_ble_start_scan(); } else if ((btm_cb.ble_ctr_cb.inq_var.scan_interval != scan_interval) || @@ -1621,17 +1571,15 @@ tBTM_STATUS btm_ble_start_inquiry(uint8_t duration) { btm_cb.ble_ctr_cb.inq_var.scan_interval = scan_interval; btm_cb.ble_ctr_cb.inq_var.scan_window = scan_window; btm_send_hci_scan_enable(BTM_BLE_SCAN_DISABLE, BTM_BLE_DUPLICATE_ENABLE); - btm_send_hci_set_scan_params( - BTM_BLE_SCAN_MODE_ACTI, scan_interval, scan_window, scan_phy, - btm_cb.ble_ctr_cb.addr_mgnt_cb.own_addr_type, SP_ADV_ALL); + btm_send_hci_set_scan_params(BTM_BLE_SCAN_MODE_ACTI, scan_interval, scan_window, scan_phy, + btm_cb.ble_ctr_cb.addr_mgnt_cb.own_addr_type, SP_ADV_ALL); btm_send_hci_scan_enable(BTM_BLE_SCAN_ENABLE, BTM_BLE_DUPLICATE_DISABLE); } btm_cb.btm_inq_vars.inq_active |= BTM_BLE_GENERAL_INQUIRY; btm_cb.ble_ctr_cb.set_ble_inquiry_active(); - log::verbose("btm_ble_start_inquiry inq_active = 0x{:02x}", - btm_cb.btm_inq_vars.inq_active); + log::verbose("btm_ble_start_inquiry inq_active = 0x{:02x}", btm_cb.btm_inq_vars.inq_active); if (duration != 0) { /* start inquiry timer */ @@ -1641,8 +1589,8 @@ tBTM_STATUS btm_ble_start_inquiry(uint8_t duration) { } btm_cb.neighbor.le_inquiry = { - .start_time_ms = timestamper_in_milliseconds.GetTimestamp(), - .results = 0, + .start_time_ms = timestamper_in_milliseconds.GetTimestamp(), + .results = 0, }; BTM_LogHistory(kBtmLogTag, RawAddress::kEmpty, "Le inquiry started"); @@ -1658,8 +1606,8 @@ tBTM_STATUS btm_ble_start_inquiry(uint8_t duration) { * Returns void * ******************************************************************************/ -void btm_ble_read_remote_name_cmpl(bool status, const RawAddress& bda, - uint16_t length, char* p_name) { +void btm_ble_read_remote_name_cmpl(bool status, const RawAddress& bda, uint16_t length, + char* p_name) { tHCI_STATUS hci_status = HCI_SUCCESS; BD_NAME bd_name; bd_name_from_char_pointer(bd_name, p_name); @@ -1684,10 +1632,10 @@ void btm_ble_read_remote_name_cmpl(bool status, const RawAddress& bda, * Returns void * ******************************************************************************/ -tBTM_STATUS btm_ble_read_remote_name(const RawAddress& remote_bda, - tBTM_NAME_CMPL_CB* p_cb) { - if (!bluetooth::shim::GetController()->SupportsBle()) +tBTM_STATUS btm_ble_read_remote_name(const RawAddress& remote_bda, tBTM_NAME_CMPL_CB* p_cb) { + if (!bluetooth::shim::GetController()->SupportsBle()) { return BTM_ERR_PROCESSING; + } tINQ_DB_ENT* p_i = btm_inq_db_find(remote_bda); if (p_i && !ble_evt_type_is_connectable(p_i->inq_info.results.ble_evt_type)) { @@ -1702,8 +1650,9 @@ tBTM_STATUS btm_ble_read_remote_name(const RawAddress& remote_bda, return BTM_BUSY; } - if (!GAP_BleReadPeerDevName(remote_bda, btm_ble_read_remote_name_cmpl)) + if (!GAP_BleReadPeerDevName(remote_bda, btm_ble_read_remote_name_cmpl)) { return BTM_BUSY; + } btm_cb.rnr.p_remname_cmpl_cb = p_cb; btm_cb.rnr.remname_active = true; @@ -1778,8 +1727,8 @@ static void btm_ble_update_adv_flag(uint8_t flag) { p_adv_data->p_pad = p; } - btsnd_hcic_ble_set_adv_data( - (uint8_t)(p_adv_data->p_pad - p_adv_data->ad_data), p_adv_data->ad_data); + btsnd_hcic_ble_set_adv_data((uint8_t)(p_adv_data->p_pad - p_adv_data->ad_data), + p_adv_data->ad_data); p_adv_data->data_mask |= BTM_BLE_AD_BIT_FLAGS; } @@ -1792,14 +1741,15 @@ static uint8_t btm_ble_is_discoverable(const RawAddress& /* bda */, uint8_t scan_state = BTM_BLE_NOT_SCANNING; /* for observer, always "discoverable */ - if (btm_cb.ble_ctr_cb.is_ble_observe_active()) + if (btm_cb.ble_ctr_cb.is_ble_observe_active()) { scan_state |= BTM_BLE_OBS_RESULT; + } if (!adv_data.empty()) { uint8_t flag = 0; uint8_t data_len; - const uint8_t* p_flag = AdvertiseDataParser::GetFieldByType( - adv_data, BTM_BLE_AD_TYPE_FLAG, &data_len); + const uint8_t* p_flag = + AdvertiseDataParser::GetFieldByType(adv_data, BTM_BLE_AD_TYPE_FLAG, &data_len); if (p_flag != NULL && data_len != 0) { flag = *p_flag; @@ -1954,15 +1904,13 @@ DEV_CLASS btm_ble_get_appearance_as_cod(std::vector const& data) { * it is a HID device based on the service class. */ uint8_t len; - const uint8_t* p_uuid16 = AdvertiseDataParser::GetFieldByType( - data, BTM_BLE_AD_TYPE_APPEARANCE, &len); + const uint8_t* p_uuid16 = + AdvertiseDataParser::GetFieldByType(data, BTM_BLE_AD_TYPE_APPEARANCE, &len); if (p_uuid16 && len == 2) { - return btm_ble_appearance_to_cod((uint16_t)p_uuid16[0] | - (p_uuid16[1] << 8)); + return btm_ble_appearance_to_cod((uint16_t)p_uuid16[0] | (p_uuid16[1] << 8)); } - p_uuid16 = AdvertiseDataParser::GetFieldByType( - data, BTM_BLE_AD_TYPE_16SRV_CMPL, &len); + p_uuid16 = AdvertiseDataParser::GetFieldByType(data, BTM_BLE_AD_TYPE_16SRV_CMPL, &len); if (p_uuid16 == NULL) { return kDevClassUnclassified; } @@ -1986,12 +1934,10 @@ DEV_CLASS btm_ble_get_appearance_as_cod(std::vector const& data) { * Update adv packet information into inquiry result. */ static void btm_ble_update_inq_result(tINQ_DB_ENT* p_i, uint8_t addr_type, - const RawAddress& /* bda */, - uint16_t evt_type, uint8_t primary_phy, - uint8_t secondary_phy, - uint8_t advertising_sid, int8_t tx_power, - int8_t rssi, uint16_t periodic_adv_int, - std::vector const& data) { + const RawAddress& /* bda */, uint16_t evt_type, + uint8_t primary_phy, uint8_t secondary_phy, + uint8_t advertising_sid, int8_t tx_power, int8_t rssi, + uint16_t periodic_adv_int, std::vector const& data) { tBTM_INQ_RESULTS* p_cur = &p_i->inq_info.results; uint8_t len; @@ -2006,27 +1952,28 @@ static void btm_ble_update_inq_result(tINQ_DB_ENT* p_i, uint8_t addr_type, p_cur->ble_periodic_adv_int = periodic_adv_int; if (btm_cb.ble_ctr_cb.inq_var.scan_type == BTM_BLE_SCAN_MODE_ACTI && - ble_evt_type_is_scannable(evt_type) && - !ble_evt_type_is_scan_resp(evt_type)) { + ble_evt_type_is_scannable(evt_type) && !ble_evt_type_is_scan_resp(evt_type)) { p_i->scan_rsp = false; - } else + } else { p_i->scan_rsp = true; + } - if (p_i->inq_count != btm_cb.btm_inq_vars.inq_counter) + if (p_i->inq_count != btm_cb.btm_inq_vars.inq_counter) { p_cur->device_type = BT_DEVICE_TYPE_BLE; - else + } else { p_cur->device_type |= BT_DEVICE_TYPE_BLE; + } - if (evt_type != BTM_BLE_SCAN_RSP_EVT) p_cur->ble_evt_type = evt_type; + if (evt_type != BTM_BLE_SCAN_RSP_EVT) { + p_cur->ble_evt_type = evt_type; + } - p_i->inq_count = - btm_cb.btm_inq_vars.inq_counter; /* Mark entry for current inquiry */ + p_i->inq_count = btm_cb.btm_inq_vars.inq_counter; /* Mark entry for current inquiry */ bool has_advertising_flags = false; if (!data.empty()) { uint8_t local_flag = 0; - const uint8_t* p_flag = - AdvertiseDataParser::GetFieldByType(data, BTM_BLE_AD_TYPE_FLAG, &len); + const uint8_t* p_flag = AdvertiseDataParser::GetFieldByType(data, BTM_BLE_AD_TYPE_FLAG, &len); if (p_flag != NULL && len != 0) { has_advertising_flags = true; p_cur->flag = *p_flag; @@ -2035,8 +1982,7 @@ static void btm_ble_update_inq_result(tINQ_DB_ENT* p_i, uint8_t addr_type, p_cur->dev_class = btm_ble_get_appearance_as_cod(data); - const uint8_t* p_rsi = - AdvertiseDataParser::GetFieldByType(data, BTM_BLE_AD_TYPE_RSI, &len); + const uint8_t* p_rsi = AdvertiseDataParser::GetFieldByType(data, BTM_BLE_AD_TYPE_RSI, &len); if (p_rsi != nullptr && len == 6) { STREAM_TO_BDADDR(p_cur->ble_ad_rsi, p_rsi); } @@ -2045,9 +1991,9 @@ static void btm_ble_update_inq_result(tINQ_DB_ENT* p_i, uint8_t addr_type, uint8_t service_data_len = 0; while ((p_service_data = AdvertiseDataParser::GetFieldByType( - p_service_data + service_data_len, - data.size() - (p_service_data - data.data()) - service_data_len, - BTM_BLE_AD_TYPE_SERVICE_DATA_TYPE, &service_data_len))) { + p_service_data + service_data_len, + data.size() - (p_service_data - data.data()) - service_data_len, + BTM_BLE_AD_TYPE_SERVICE_DATA_TYPE, &service_data_len))) { uint16_t uuid; const uint8_t* p_uuid = p_service_data; if (service_data_len < 2) { @@ -2091,8 +2037,7 @@ static void btm_ble_update_inq_result(tINQ_DB_ENT* p_i, uint8_t addr_type, // should be assumed about their values (CSSv10, 1.3.1). Thus, do not // interpret the device type unless this packet has the flags set or is // connectable. - bool should_process_flags = - has_advertising_flags || ble_evt_type_is_connectable(evt_type); + bool should_process_flags = has_advertising_flags || ble_evt_type_is_connectable(evt_type); if (should_process_flags && (p_cur->flag & BTM_BLE_BREDR_NOT_SPT) == 0 && !ble_evt_type_is_directed(evt_type)) { if (p_cur->ble_addr_type != BLE_ADDR_RANDOM) { @@ -2135,16 +2080,16 @@ void btm_ble_process_adv_addr(RawAddress& bda, tBLE_ADDR_TYPE* addr_type) { * to process adv packet. */ void btm_ble_process_adv_pkt_cont(uint16_t evt_type, tBLE_ADDR_TYPE addr_type, - const RawAddress& bda, uint8_t primary_phy, - uint8_t secondary_phy, - uint8_t advertising_sid, int8_t tx_power, - int8_t rssi, uint16_t periodic_adv_int, - uint8_t data_len, const uint8_t* data, + const RawAddress& bda, uint8_t primary_phy, uint8_t secondary_phy, + uint8_t advertising_sid, int8_t tx_power, int8_t rssi, + uint16_t periodic_adv_int, uint8_t data_len, const uint8_t* data, const RawAddress& original_bda) { bool update = true; std::vector tmp; - if (data_len != 0) tmp.insert(tmp.begin(), data, data + data_len); + if (data_len != 0) { + tmp.insert(tmp.begin(), data, data + data_len); + } bool is_scannable = ble_evt_type_is_scannable(evt_type); bool is_scan_resp = ble_evt_type_is_scan_resp(evt_type); @@ -2155,18 +2100,21 @@ void btm_ble_process_adv_pkt_cont(uint16_t evt_type, tBLE_ADDR_TYPE addr_type, // has no ad flag, the device will be set to DUMO mode. The createbond // procedure will use the wrong device mode. // In such case no necessary to report scan response - if (is_legacy && is_scan_resp && !cache.Exist(addr_type, bda)) return; + if (is_legacy && is_scan_resp && !cache.Exist(addr_type, bda)) { + return; + } bool is_start = is_legacy && is_scannable && !is_scan_resp; - if (is_legacy) AdvertiseDataParser::RemoveTrailingZeros(tmp); + if (is_legacy) { + AdvertiseDataParser::RemoveTrailingZeros(tmp); + } // We might have send scan request to this device before, but didn't get the // response. In such case make sure data is put at start, not appended to // already existing data. - std::vector const& adv_data = - is_start ? cache.Set(addr_type, bda, std::move(tmp)) - : cache.Append(addr_type, bda, std::move(tmp)); + std::vector const& adv_data = is_start ? cache.Set(addr_type, bda, std::move(tmp)) + : cache.Append(addr_type, bda, std::move(tmp)); bool data_complete = (ble_evt_type_data_status(evt_type) != 0x01); @@ -2176,8 +2124,7 @@ void btm_ble_process_adv_pkt_cont(uint16_t evt_type, tBLE_ADDR_TYPE addr_type, return; } - bool is_active_scan = - btm_cb.ble_ctr_cb.inq_var.scan_type == BTM_BLE_SCAN_MODE_ACTI; + bool is_active_scan = btm_cb.ble_ctr_cb.inq_var.scan_type == BTM_BLE_SCAN_MODE_ACTI; if (is_active_scan && is_scannable && !is_scan_resp) { // If we didn't receive scan response yet, don't report the device. log::verbose("Waiting for scan response {}", bda); @@ -2193,8 +2140,7 @@ void btm_ble_process_adv_pkt_cont(uint16_t evt_type, tBLE_ADDR_TYPE addr_type, bool include_rsi = false; uint8_t len; - if (AdvertiseDataParser::GetFieldByType(adv_data, BTM_BLE_AD_TYPE_RSI, - &len)) { + if (AdvertiseDataParser::GetFieldByType(adv_data, BTM_BLE_AD_TYPE_RSI, &len)) { include_rsi = true; } @@ -2205,8 +2151,7 @@ void btm_ble_process_adv_pkt_cont(uint16_t evt_type, tBLE_ADDR_TYPE addr_type, /* never been report as an LE device */ if (p_i && (!(p_i->inq_info.results.device_type & BT_DEVICE_TYPE_BLE) || /* scan response to be updated */ - (!p_i->scan_rsp) || - (!p_i->inq_info.results.include_rsi && include_rsi))) { + (!p_i->scan_rsp) || (!p_i->inq_info.results.include_rsi && include_rsi))) { update = true; } else if (btm_cb.ble_ctr_cb.is_ble_observe_active()) { update = false; @@ -2223,39 +2168,36 @@ void btm_ble_process_adv_pkt_cont(uint16_t evt_type, tBLE_ADDR_TYPE addr_type, if (p_i != NULL) { btm_cb.btm_inq_vars.inq_cmpl_info.num_resp++; p_i->time_of_resp = bluetooth::common::time_get_os_boottime_ms(); - } else + } else { return; + } } else if (p_i->inq_count != - btm_cb.btm_inq_vars - .inq_counter) /* first time seen in this inquiry */ + btm_cb.btm_inq_vars.inq_counter) /* first time seen in this inquiry */ { p_i->time_of_resp = bluetooth::common::time_get_os_boottime_ms(); btm_cb.btm_inq_vars.inq_cmpl_info.num_resp++; } /* update the LE device information in inquiry database */ - btm_ble_update_inq_result(p_i, addr_type, bda, evt_type, primary_phy, - secondary_phy, advertising_sid, tx_power, rssi, - periodic_adv_int, adv_data); + btm_ble_update_inq_result(p_i, addr_type, bda, evt_type, primary_phy, secondary_phy, + advertising_sid, tx_power, rssi, periodic_adv_int, adv_data); if (include_rsi) { (&p_i->inq_info.results)->include_rsi = true; } tBTM_INQ_RESULTS_CB* p_opportunistic_obs_results_cb = - btm_cb.ble_ctr_cb.p_opportunistic_obs_results_cb; + btm_cb.ble_ctr_cb.p_opportunistic_obs_results_cb; if (p_opportunistic_obs_results_cb) { (p_opportunistic_obs_results_cb)((tBTM_INQ_RESULTS*)&p_i->inq_info.results, - const_cast(adv_data.data()), - adv_data.size()); + const_cast(adv_data.data()), adv_data.size()); } tBTM_INQ_RESULTS_CB* p_target_announcement_obs_results_cb = - btm_cb.ble_ctr_cb.p_target_announcement_obs_results_cb; + btm_cb.ble_ctr_cb.p_target_announcement_obs_results_cb; if (p_target_announcement_obs_results_cb) { - (p_target_announcement_obs_results_cb)( - (tBTM_INQ_RESULTS*)&p_i->inq_info.results, - const_cast(adv_data.data()), adv_data.size()); + (p_target_announcement_obs_results_cb)((tBTM_INQ_RESULTS*)&p_i->inq_info.results, + const_cast(adv_data.data()), adv_data.size()); } uint8_t result = btm_ble_is_discoverable(bda, adv_data); @@ -2265,7 +2207,9 @@ void btm_ble_process_adv_pkt_cont(uint16_t evt_type, tBLE_ADDR_TYPE addr_type, return; } - if (!update) result &= ~BTM_BLE_INQ_RESULT; + if (!update) { + result &= ~BTM_BLE_INQ_RESULT; + } tBTM_INQ_RESULTS_CB* p_inq_results_cb = btm_cb.btm_inq_vars.p_inq_results_cb; if (p_inq_results_cb && (result & BTM_BLE_INQ_RESULT)) { @@ -2289,22 +2233,22 @@ void btm_ble_process_adv_pkt_cont(uint16_t evt_type, tBLE_ADDR_TYPE addr_type, * This function copy from btm_ble_process_adv_pkt_cont to process adv packet * from gd scanning module to handle inquiry result callback. */ -void btm_ble_process_adv_pkt_cont_for_inquiry( - uint16_t evt_type, tBLE_ADDR_TYPE addr_type, const RawAddress& bda, - uint8_t primary_phy, uint8_t secondary_phy, uint8_t advertising_sid, - int8_t tx_power, int8_t rssi, uint16_t periodic_adv_int, - std::vector advertising_data) { +void btm_ble_process_adv_pkt_cont_for_inquiry(uint16_t evt_type, tBLE_ADDR_TYPE addr_type, + const RawAddress& bda, uint8_t primary_phy, + uint8_t secondary_phy, uint8_t advertising_sid, + int8_t tx_power, int8_t rssi, + uint16_t periodic_adv_int, + std::vector advertising_data) { bool update = true; bool include_rsi = false; uint8_t len; - if (AdvertiseDataParser::GetFieldByType(advertising_data, BTM_BLE_AD_TYPE_RSI, - &len)) { + if (AdvertiseDataParser::GetFieldByType(advertising_data, BTM_BLE_AD_TYPE_RSI, &len)) { include_rsi = true; } - const uint8_t* p_flag = AdvertiseDataParser::GetFieldByType( - advertising_data, BTM_BLE_AD_TYPE_FLAG, &len); + const uint8_t* p_flag = + AdvertiseDataParser::GetFieldByType(advertising_data, BTM_BLE_AD_TYPE_FLAG, &len); tINQ_DB_ENT* p_i = btm_inq_db_find(bda); @@ -2313,10 +2257,8 @@ void btm_ble_process_adv_pkt_cont_for_inquiry( /* never been report as an LE device */ if (p_i && (!(p_i->inq_info.results.device_type & BT_DEVICE_TYPE_BLE) || /* scan response to be updated */ - (!p_i->scan_rsp) || - (!p_i->inq_info.results.include_rsi && include_rsi) || - (com::android::bluetooth::flags:: - update_inquiry_result_on_flag_change() && + (!p_i->scan_rsp) || (!p_i->inq_info.results.include_rsi && include_rsi) || + (com::android::bluetooth::flags::update_inquiry_result_on_flag_change() && !p_i->inq_info.results.flag && p_flag && *p_flag))) { update = true; } else if (btm_cb.ble_ctr_cb.is_ble_observe_active()) { @@ -2342,36 +2284,34 @@ void btm_ble_process_adv_pkt_cont_for_inquiry( return; } } else if (p_i->inq_count != - btm_cb.btm_inq_vars - .inq_counter) /* first time seen in this inquiry */ + btm_cb.btm_inq_vars.inq_counter) /* first time seen in this inquiry */ { p_i->time_of_resp = bluetooth::common::time_get_os_boottime_ms(); btm_cb.btm_inq_vars.inq_cmpl_info.num_resp++; } /* update the LE device information in inquiry database */ - btm_ble_update_inq_result(p_i, addr_type, bda, evt_type, primary_phy, - secondary_phy, advertising_sid, tx_power, rssi, - periodic_adv_int, advertising_data); + btm_ble_update_inq_result(p_i, addr_type, bda, evt_type, primary_phy, secondary_phy, + advertising_sid, tx_power, rssi, periodic_adv_int, advertising_data); if (include_rsi) { (&p_i->inq_info.results)->include_rsi = true; } tBTM_INQ_RESULTS_CB* p_opportunistic_obs_results_cb = - btm_cb.ble_ctr_cb.p_opportunistic_obs_results_cb; + btm_cb.ble_ctr_cb.p_opportunistic_obs_results_cb; if (p_opportunistic_obs_results_cb) { - (p_opportunistic_obs_results_cb)( - (tBTM_INQ_RESULTS*)&p_i->inq_info.results, - const_cast(advertising_data.data()), advertising_data.size()); + (p_opportunistic_obs_results_cb)((tBTM_INQ_RESULTS*)&p_i->inq_info.results, + const_cast(advertising_data.data()), + advertising_data.size()); } tBTM_INQ_RESULTS_CB* p_target_announcement_obs_results_cb = - btm_cb.ble_ctr_cb.p_target_announcement_obs_results_cb; + btm_cb.ble_ctr_cb.p_target_announcement_obs_results_cb; if (p_target_announcement_obs_results_cb) { - (p_target_announcement_obs_results_cb)( - (tBTM_INQ_RESULTS*)&p_i->inq_info.results, - const_cast(advertising_data.data()), advertising_data.size()); + (p_target_announcement_obs_results_cb)((tBTM_INQ_RESULTS*)&p_i->inq_info.results, + const_cast(advertising_data.data()), + advertising_data.size()); } uint8_t result = btm_ble_is_discoverable(bda, advertising_data); @@ -2379,13 +2319,14 @@ void btm_ble_process_adv_pkt_cont_for_inquiry( return; } - if (!update) result &= ~BTM_BLE_INQ_RESULT; + if (!update) { + result &= ~BTM_BLE_INQ_RESULT; + } tBTM_INQ_RESULTS_CB* p_inq_results_cb = btm_cb.btm_inq_vars.p_inq_results_cb; if (p_inq_results_cb && (result & BTM_BLE_INQ_RESULT)) { (p_inq_results_cb)((tBTM_INQ_RESULTS*)&p_i->inq_info.results, - const_cast(advertising_data.data()), - advertising_data.size()); + const_cast(advertising_data.data()), advertising_data.size()); } } @@ -2400,19 +2341,19 @@ void btm_ble_process_adv_pkt_cont_for_inquiry( ******************************************************************************/ static void btm_ble_start_scan() { btm_cb.neighbor.le_legacy_scan = { - .start_time_ms = timestamper_in_milliseconds.GetTimestamp(), - .results = 0, + .start_time_ms = timestamper_in_milliseconds.GetTimestamp(), + .results = 0, }; - BTM_LogHistory(kBtmLogTag, RawAddress::kEmpty, "Le legacy scan started", - "Duplicates:disable"); + BTM_LogHistory(kBtmLogTag, RawAddress::kEmpty, "Le legacy scan started", "Duplicates:disable"); /* start scan, disable duplicate filtering */ btm_send_hci_scan_enable(BTM_BLE_SCAN_ENABLE, BTM_BLE_DUPLICATE_DISABLE); - if (btm_cb.ble_ctr_cb.inq_var.scan_type == BTM_BLE_SCAN_MODE_ACTI) + if (btm_cb.ble_ctr_cb.inq_var.scan_type == BTM_BLE_SCAN_MODE_ACTI) { btm_ble_set_topology_mask(BTM_BLE_STATE_ACTIVE_SCAN_BIT); - else + } else { btm_ble_set_topology_mask(BTM_BLE_STATE_PASSIVE_SCAN_BIT); + } } /******************************************************************************* @@ -2425,22 +2366,22 @@ static void btm_ble_start_scan() { * ******************************************************************************/ static void btm_ble_stop_scan(void) { - if (btm_cb.ble_ctr_cb.inq_var.scan_type == BTM_BLE_SCAN_MODE_ACTI) + if (btm_cb.ble_ctr_cb.inq_var.scan_type == BTM_BLE_SCAN_MODE_ACTI) { btm_ble_clear_topology_mask(BTM_BLE_STATE_ACTIVE_SCAN_BIT); - else + } else { btm_ble_clear_topology_mask(BTM_BLE_STATE_PASSIVE_SCAN_BIT); + } /* Clear the inquiry callback if set */ btm_cb.ble_ctr_cb.inq_var.scan_type = BTM_BLE_SCAN_MODE_NONE; /* stop discovery now */ const unsigned long long duration_timestamp = - timestamper_in_milliseconds.GetTimestamp() - - btm_cb.neighbor.le_legacy_scan.start_time_ms; - BTM_LogHistory(kBtmLogTag, RawAddress::kEmpty, "Le legacy scan stopped", - base::StringPrintf("duration_s:%6.3f results:%-3lu", - (double)duration_timestamp / 1000.0, - btm_cb.neighbor.le_legacy_scan.results)); + timestamper_in_milliseconds.GetTimestamp() - btm_cb.neighbor.le_legacy_scan.start_time_ms; + BTM_LogHistory( + kBtmLogTag, RawAddress::kEmpty, "Le legacy scan stopped", + base::StringPrintf("duration_s:%6.3f results:%-3lu", (double)duration_timestamp / 1000.0, + btm_cb.neighbor.le_legacy_scan.results)); btm_send_hci_scan_enable(BTM_BLE_SCAN_DISABLE, BTM_BLE_DUPLICATE_ENABLE); btm_update_scanner_filter_policy(SP_ADV_ALL); @@ -2458,25 +2399,22 @@ void btm_ble_stop_inquiry(void) { alarm_cancel(btm_cb.ble_ctr_cb.inq_var.inquiry_timer); const unsigned long long duration_timestamp = - timestamper_in_milliseconds.GetTimestamp() - - btm_cb.neighbor.le_inquiry.start_time_ms; - BTM_LogHistory(kBtmLogTag, RawAddress::kEmpty, "Le inquiry stopped", - base::StringPrintf("duration_s:%6.3f results:%-3lu", - (double)duration_timestamp / 1000.0, - btm_cb.neighbor.le_inquiry.results)); + timestamper_in_milliseconds.GetTimestamp() - btm_cb.neighbor.le_inquiry.start_time_ms; + BTM_LogHistory( + kBtmLogTag, RawAddress::kEmpty, "Le inquiry stopped", + base::StringPrintf("duration_s:%6.3f results:%-3lu", (double)duration_timestamp / 1000.0, + btm_cb.neighbor.le_inquiry.results)); btm_cb.ble_ctr_cb.reset_ble_inquiry(); /* Cleanup anything remaining on index 0 */ - BTM_BleAdvFilterParamSetup(BTM_BLE_SCAN_COND_DELETE, - static_cast(0), nullptr, - base::Bind(btm_ble_scan_filt_param_cfg_evt)); + BTM_BleAdvFilterParamSetup(BTM_BLE_SCAN_COND_DELETE, static_cast(0), + nullptr, base::Bind(btm_ble_scan_filt_param_cfg_evt)); /* If no more scan activity, stop LE scan now */ if (!btm_cb.ble_ctr_cb.is_ble_scan_active()) { btm_ble_stop_scan(); - } else if (get_low_latency_scan_params() != - std::pair(btm_cb.ble_ctr_cb.inq_var.scan_interval, - btm_cb.ble_ctr_cb.inq_var.scan_window)) { + } else if (get_low_latency_scan_params() != std::pair(btm_cb.ble_ctr_cb.inq_var.scan_interval, + btm_cb.ble_ctr_cb.inq_var.scan_window)) { log::verbose("setting default params for ongoing observe"); btm_ble_stop_scan(); btm_ble_start_scan(); @@ -2488,9 +2426,8 @@ void btm_ble_stop_inquiry(void) { btm_cb.btm_inq_vars.inq_cmpl_info.num_resp); // TODO: remove this call and make btm_process_inq_complete static - btm_process_inq_complete( - HCI_SUCCESS, - (uint8_t)(btm_cb.btm_inq_vars.inqparms.mode & BTM_BLE_GENERAL_INQUIRY)); + btm_process_inq_complete(HCI_SUCCESS, + (uint8_t)(btm_cb.btm_inq_vars.inqparms.mode & BTM_BLE_GENERAL_INQUIRY)); } /******************************************************************************* @@ -2516,7 +2453,9 @@ static void btm_ble_stop_observe(void) { btm_ble_stop_scan(); } - if (p_obs_cb) (p_obs_cb)(&btm_cb.btm_inq_vars.inq_cmpl_info); + if (p_obs_cb) { + (p_obs_cb)(&btm_cb.btm_inq_vars.inq_cmpl_info); + } } /******************************************************************************* * @@ -2528,8 +2467,7 @@ static void btm_ble_stop_observe(void) { * ******************************************************************************/ typedef bool(BTM_TOPOLOGY_FUNC_PTR)(tBTM_BLE_STATE_MASK); -static bool btm_ble_adv_states_operation(BTM_TOPOLOGY_FUNC_PTR* p_handler, - uint8_t adv_evt) { +static bool btm_ble_adv_states_operation(BTM_TOPOLOGY_FUNC_PTR* p_handler, uint8_t adv_evt) { bool rt = false; switch (adv_evt) { @@ -2570,14 +2508,13 @@ static bool btm_ble_adv_states_operation(BTM_TOPOLOGY_FUNC_PTR* p_handler, * ******************************************************************************/ static tBTM_STATUS btm_ble_start_adv(void) { - if (!btm_ble_adv_states_operation(btm_ble_topology_check, - btm_cb.ble_ctr_cb.inq_var.evt_type)) + if (!btm_ble_adv_states_operation(btm_ble_topology_check, btm_cb.ble_ctr_cb.inq_var.evt_type)) { return BTM_WRONG_MODE; + } btsnd_hcic_ble_set_adv_enable(BTM_BLE_ADV_ENABLE); btm_cb.ble_ctr_cb.inq_var.adv_mode = BTM_BLE_ADV_ENABLE; - btm_ble_adv_states_operation(btm_ble_set_topology_mask, - btm_cb.ble_ctr_cb.inq_var.evt_type); + btm_ble_adv_states_operation(btm_ble_set_topology_mask, btm_cb.ble_ctr_cb.inq_var.evt_type); power_telemetry::GetInstance().LogBleAdvStarted(); return BTM_SUCCESS; @@ -2628,35 +2565,28 @@ static void btm_ble_start_slow_adv(void) { btm_ble_stop_adv(); - btm_cb.ble_ctr_cb.inq_var.evt_type = btm_set_conn_mode_adv_init_addr( - address, &init_addr_type, &own_addr_type); + btm_cb.ble_ctr_cb.inq_var.evt_type = + btm_set_conn_mode_adv_init_addr(address, &init_addr_type, &own_addr_type); /* slow adv mode never goes into directed adv */ - btsnd_hcic_ble_write_adv_params( - BTM_BLE_GAP_ADV_SLOW_INT, BTM_BLE_GAP_ADV_SLOW_INT, - btm_cb.ble_ctr_cb.inq_var.evt_type, own_addr_type, init_addr_type, - address, btm_cb.ble_ctr_cb.inq_var.adv_chnl_map, - btm_cb.ble_ctr_cb.inq_var.afp); + btsnd_hcic_ble_write_adv_params(BTM_BLE_GAP_ADV_SLOW_INT, BTM_BLE_GAP_ADV_SLOW_INT, + btm_cb.ble_ctr_cb.inq_var.evt_type, own_addr_type, + init_addr_type, address, btm_cb.ble_ctr_cb.inq_var.adv_chnl_map, + btm_cb.ble_ctr_cb.inq_var.afp); btm_ble_start_adv(); } } -static void btm_ble_inquiry_timer_gap_limited_discovery_timeout( - void* /* data */) { +static void btm_ble_inquiry_timer_gap_limited_discovery_timeout(void* /* data */) { /* lim_timeout expired, limited discovery should exit now */ btm_cb.btm_inq_vars.discoverable_mode &= ~BTM_BLE_LIMITED_DISCOVERABLE; - btm_ble_set_adv_flag(btm_cb.btm_inq_vars.connectable_mode, - btm_cb.btm_inq_vars.discoverable_mode); + btm_ble_set_adv_flag(btm_cb.btm_inq_vars.connectable_mode, btm_cb.btm_inq_vars.discoverable_mode); } -static void btm_ble_inquiry_timer_timeout(void* /* data */) { - btm_ble_stop_inquiry(); -} +static void btm_ble_inquiry_timer_timeout(void* /* data */) { btm_ble_stop_inquiry(); } -static void btm_ble_observer_timer_timeout(void* /* data */) { - btm_ble_stop_observe(); -} +static void btm_ble_observer_timer_timeout(void* /* data */) { btm_ble_stop_observe(); } /******************************************************************************* * @@ -2698,8 +2628,7 @@ void btm_ble_read_remote_features_complete(uint8_t* p, uint8_t length) { } if (!acl_set_peer_le_features_from_handle(handle, p)) { - log::error( - "Unable to find existing connection after read remote features"); + log::error("Unable to find existing connection after read remote features"); return; } } @@ -2768,20 +2697,22 @@ bool btm_ble_clear_topology_mask(tBTM_BLE_STATE_MASK request_state_mask) { * Returns void * ******************************************************************************/ -static void btm_ble_update_link_topology_mask(uint8_t link_role, - bool increase) { +static void btm_ble_update_link_topology_mask(uint8_t link_role, bool increase) { btm_ble_clear_topology_mask(BTM_BLE_STATE_ALL_CONN_MASK); - if (increase) + if (increase) { btm_cb.ble_ctr_cb.link_count[link_role]++; - else if (btm_cb.ble_ctr_cb.link_count[link_role] > 0) + } else if (btm_cb.ble_ctr_cb.link_count[link_role] > 0) { btm_cb.ble_ctr_cb.link_count[link_role]--; + } - if (btm_cb.ble_ctr_cb.link_count[HCI_ROLE_CENTRAL]) + if (btm_cb.ble_ctr_cb.link_count[HCI_ROLE_CENTRAL]) { btm_ble_set_topology_mask(BTM_BLE_STATE_CENTRAL_BIT); + } - if (btm_cb.ble_ctr_cb.link_count[HCI_ROLE_PERIPHERAL]) + if (btm_cb.ble_ctr_cb.link_count[HCI_ROLE_PERIPHERAL]) { btm_ble_set_topology_mask(BTM_BLE_STATE_PERIPHERAL_BIT); + } if (link_role == HCI_ROLE_PERIPHERAL && increase) { btm_cb.ble_ctr_cb.inq_var.adv_mode = BTM_BLE_ADV_DISABLE; @@ -2810,8 +2741,7 @@ void btm_ble_decrement_link_topology_mask(uint8_t link_role) { * Returns void * ******************************************************************************/ -void btm_ble_update_mode_operation(uint8_t /* link_role */, - const RawAddress* /* bd_addr */, +void btm_ble_update_mode_operation(uint8_t /* link_role */, const RawAddress* /* bd_addr */, tHCI_STATUS status) { if (status == HCI_ERR_ADVERTISING_TIMEOUT) { btm_cb.ble_ctr_cb.inq_var.adv_mode = BTM_BLE_ADV_DISABLE; @@ -2855,15 +2785,13 @@ void btm_ble_init(void) { btm_cb.ble_ctr_cb.inq_var.sfp = BTM_BLE_DEFAULT_SFP; btm_cb.ble_ctr_cb.inq_var.connectable_mode = BTM_BLE_NON_CONNECTABLE; btm_cb.ble_ctr_cb.inq_var.discoverable_mode = BTM_BLE_NON_DISCOVERABLE; - btm_cb.ble_ctr_cb.inq_var.fast_adv_timer = - alarm_new("btm_ble_inq.fast_adv_timer"); - btm_cb.ble_ctr_cb.inq_var.inquiry_timer = - alarm_new("btm_ble_inq.inquiry_timer"); + btm_cb.ble_ctr_cb.inq_var.fast_adv_timer = alarm_new("btm_ble_inq.fast_adv_timer"); + btm_cb.ble_ctr_cb.inq_var.inquiry_timer = alarm_new("btm_ble_inq.inquiry_timer"); btm_cb.ble_ctr_cb.inq_var.evt_type = BTM_BLE_NON_CONNECT_EVT; btm_cb.ble_ctr_cb.addr_mgnt_cb.refresh_raddr_timer = - alarm_new("btm_ble_addr.refresh_raddr_timer"); + alarm_new("btm_ble_addr.refresh_raddr_timer"); btm_ble_pa_sync_cb = {}; sync_timeout_alarm = alarm_new("btm.sync_start_task"); if (!ble_vnd_is_included()) { @@ -2872,9 +2800,7 @@ void btm_ble_init(void) { } // Clean up btm ble control block -void btm_ble_free() { - alarm_free(btm_cb.ble_ctr_cb.addr_mgnt_cb.refresh_raddr_timer); -} +void btm_ble_free() { alarm_free(btm_cb.ble_ctr_cb.addr_mgnt_cb.refresh_raddr_timer); } /******************************************************************************* * @@ -2908,8 +2834,7 @@ bool btm_ble_topology_check(tBTM_BLE_STATE_MASK request_state_mask) { /* check if the requested state is supported or not */ uint8_t bit_num = btm_le_state_combo_tbl[0][request_state - 1]; - uint64_t ble_supported_states = - bluetooth::shim::GetController()->GetLeSupportedStates(); + uint64_t ble_supported_states = bluetooth::shim::GetController()->GetLeSupportedStates(); if (!BTM_LE_STATES_SUPPORTED(ble_supported_states, bit_num)) { log::error("state requested not supported: {}", request_state); diff --git a/system/stack/btm/btm_ble_int.h b/system/stack/btm/btm_ble_int.h index 3bc2b74f7b5..60d19c16eb2 100644 --- a/system/stack/btm/btm_ble_int.h +++ b/system/stack/btm/btm_ble_int.h @@ -32,24 +32,21 @@ #include "types/ble_address_with_type.h" #include "types/raw_address.h" -void btm_send_hci_set_scan_params(uint8_t scan_type, uint16_t scan_int, - uint16_t scan_win, uint8_t scan_phy, - tBLE_ADDR_TYPE addr_type_own, +void btm_send_hci_set_scan_params(uint8_t scan_type, uint16_t scan_int, uint16_t scan_win, + uint8_t scan_phy, tBLE_ADDR_TYPE addr_type_own, uint8_t scan_filter_policy); void btm_ble_init(void); void btm_ble_free(); -void btm_ble_connected(const RawAddress& bda, uint16_t handle, uint8_t enc_mode, - uint8_t role, tBLE_ADDR_TYPE addr_type, - bool addr_matched, +void btm_ble_connected(const RawAddress& bda, uint16_t handle, uint8_t enc_mode, uint8_t role, + tBLE_ADDR_TYPE addr_type, bool addr_matched, bool can_read_discoverable_characteristics); /* acceptlist function */ void btm_update_scanner_filter_policy(tBTM_BLE_SFP scan_policy); /* background connection function */ -void btm_ble_update_mode_operation(uint8_t link_role, const RawAddress* bda, - tHCI_STATUS status); +void btm_ble_update_mode_operation(uint8_t link_role, const RawAddress* bda, tHCI_STATUS status); /* BLE address management */ tBTM_SEC_DEV_REC* btm_ble_resolve_random_addr(const RawAddress& random_bda); diff --git a/system/stack/btm/btm_ble_int_types.h b/system/stack/btm/btm_ble_int_types.h index 4d3c3b30ef0..21cd5b1556e 100644 --- a/system/stack/btm/btm_ble_int_types.h +++ b/system/stack/btm/btm_ble_int_types.h @@ -85,7 +85,7 @@ typedef struct { uint16_t connectable_mode; uint16_t scan_window; uint16_t scan_interval; - uint8_t scan_type; /* current scan type: active or passive */ + uint8_t scan_type; /* current scan type: active or passive */ uint8_t scan_phy; tBTM_BLE_AFP afp; /* advertising filter policy */ @@ -97,9 +97,7 @@ typedef struct { uint8_t adv_mode; void enable_advertising_mode() { adv_mode = BTM_BLE_ADV_ENABLE; } void disable_advertising_mode() { adv_mode = BTM_BLE_ADV_DISABLE; } - bool is_advertising_mode_enabled() const { - return (adv_mode == BTM_BLE_ADV_ENABLE); - } + bool is_advertising_mode_enabled() const { return adv_mode == BTM_BLE_ADV_ENABLE; } tBLE_BD_ADDR direct_bda; tBTM_BLE_EVT directed_conn; @@ -140,7 +138,9 @@ enum : uint8_t { }; typedef uint8_t tBTM_BLE_RL_STATE; -typedef struct { void* p_param; } tBTM_BLE_CONN_REQ; +typedef struct { + void* p_param; +} tBTM_BLE_CONN_REQ; /* LE state request */ #define BTM_BLE_STATE_INVALID 0 @@ -163,8 +163,7 @@ typedef uint16_t tBTM_BLE_STATE_MASK; #define BTM_BLE_STATE_ALL_ADV_MASK \ (BTM_BLE_STATE_CONN_ADV_BIT | BTM_BLE_STATE_LO_DUTY_DIR_ADV_BIT | \ BTM_BLE_STATE_HI_DUTY_DIR_ADV_BIT | BTM_BLE_STATE_SCAN_ADV_BIT) -#define BTM_BLE_STATE_ALL_CONN_MASK \ - (BTM_BLE_STATE_CENTRAL_BIT | BTM_BLE_STATE_PERIPHERAL_BIT) +#define BTM_BLE_STATE_ALL_CONN_MASK (BTM_BLE_STATE_CENTRAL_BIT | BTM_BLE_STATE_PERIPHERAL_BIT) typedef struct { RawAddress* resolve_q_random_pseudo{nullptr}; @@ -174,30 +173,25 @@ typedef struct { } tBTM_BLE_RESOLVE_Q; /* BLE privacy mode */ -#define BTM_PRIVACY_NONE 0 /* BLE no privacy */ -#define BTM_PRIVACY_1_1 1 /* BLE privacy 1.1, do not support privacy 1.0 */ -#define BTM_PRIVACY_1_2 2 /* BLE privacy 1.2 */ -#define BTM_PRIVACY_MIXED \ - 3 /* BLE privacy mixed mode, broadcom propietary mode */ +#define BTM_PRIVACY_NONE 0 /* BLE no privacy */ +#define BTM_PRIVACY_1_1 1 /* BLE privacy 1.1, do not support privacy 1.0 */ +#define BTM_PRIVACY_1_2 2 /* BLE privacy 1.2 */ +#define BTM_PRIVACY_MIXED 3 /* BLE privacy mixed mode, broadcom propietary mode */ typedef uint8_t tBTM_PRIVACY_MODE; /* Define BLE Device Management control structure -*/ + */ constexpr uint8_t kBTM_BLE_INQUIRY_ACTIVE = 0x10; constexpr uint8_t kBTM_BLE_OBSERVE_ACTIVE = 0x80; constexpr size_t kCentralAndPeripheralCount = 2; typedef struct { - private: +private: uint8_t scan_activity_; /* LE scan activity mask */ - public: - bool is_ble_inquiry_active() const { - return (scan_activity_ & kBTM_BLE_INQUIRY_ACTIVE); - } - bool is_ble_observe_active() const { - return (scan_activity_ & kBTM_BLE_OBSERVE_ACTIVE); - } +public: + bool is_ble_inquiry_active() const { return scan_activity_ & kBTM_BLE_INQUIRY_ACTIVE; } + bool is_ble_observe_active() const { return scan_activity_ & kBTM_BLE_OBSERVE_ACTIVE; } void set_ble_inquiry_active() { scan_activity_ |= kBTM_BLE_INQUIRY_ACTIVE; } void set_ble_observe_active() { scan_activity_ |= kBTM_BLE_OBSERVE_ACTIVE; } @@ -205,9 +199,7 @@ typedef struct { void reset_ble_inquiry() { scan_activity_ &= ~kBTM_BLE_INQUIRY_ACTIVE; } void reset_ble_observe() { scan_activity_ &= ~kBTM_BLE_OBSERVE_ACTIVE; } - bool is_ble_scan_active() const { - return (is_ble_inquiry_active() || is_ble_observe_active()); - } + bool is_ble_scan_active() const { return is_ble_inquiry_active() || is_ble_observe_active(); } /***************************************************** ** BLE Inquiry @@ -225,21 +217,17 @@ typedef struct { /* target announcement observer */ tBTM_INQ_RESULTS_CB* p_target_announcement_obs_results_cb; - private: +private: enum : uint8_t { /* BLE connection state */ BLE_CONN_IDLE = 0, BLE_CONNECTING = 2, BLE_CONN_CANCEL = 3, } conn_state_{BLE_CONN_IDLE}; - public: +public: bool is_connection_state_idle() const { return conn_state_ == BLE_CONN_IDLE; } - bool is_connection_state_connecting() const { - return conn_state_ == BLE_CONNECTING; - } - bool is_connection_state_cancelled() const { - return conn_state_ == BLE_CONN_CANCEL; - } + bool is_connection_state_connecting() const { return conn_state_ == BLE_CONNECTING; } + bool is_connection_state_cancelled() const { return conn_state_ == BLE_CONN_CANCEL; } void set_connection_state_idle() { conn_state_ = BLE_CONN_IDLE; } void set_connection_state_connecting() { conn_state_ = BLE_CONNECTING; } void set_connection_state_cancelled() { conn_state_ = BLE_CONN_CANCEL; } @@ -247,8 +235,8 @@ typedef struct { /* random address management control block */ tBTM_LE_RANDOM_CB addr_mgnt_cb; - tBTM_PRIVACY_MODE privacy_mode; /* privacy mode */ - uint8_t resolving_list_avail_size; /* resolving list available size */ + tBTM_PRIVACY_MODE privacy_mode; /* privacy mode */ + uint8_t resolving_list_avail_size; /* resolving list available size */ tBTM_BLE_RESOLVE_Q resolving_list_pend_q; /* Resolving list queue */ tBTM_BLE_RL_STATE suspended_rl_state; /* Suspended resolving list state */ /* IRK list availability mask, up to max entry bits */ diff --git a/system/stack/btm/btm_ble_privacy.cc b/system/stack/btm/btm_ble_privacy.cc index bb37afb42bd..5e807c1ea44 100644 --- a/system/stack/btm/btm_ble_privacy.cc +++ b/system/stack/btm/btm_ble_privacy.cc @@ -76,8 +76,7 @@ extern tBTM_CB btm_cb; * Returns void * ******************************************************************************/ -static void btm_ble_enq_resolving_list_pending(const RawAddress& pseudo_bda, - uint8_t op_code) { +static void btm_ble_enq_resolving_list_pending(const RawAddress& pseudo_bda, uint8_t op_code) { tBTM_BLE_RESOLVE_Q* p_q = &btm_cb.ble_ctr_cb.resolving_list_pend_q; p_q->resolve_q_random_pseudo[p_q->q_next] = pseudo_bda; @@ -98,14 +97,14 @@ static void btm_ble_enq_resolving_list_pending(const RawAddress& pseudo_bda, * Returns void * ******************************************************************************/ -static bool btm_ble_brcm_find_resolving_pending_entry( - const RawAddress& pseudo_addr, uint8_t action) { +static bool btm_ble_brcm_find_resolving_pending_entry(const RawAddress& pseudo_addr, + uint8_t action) { tBTM_BLE_RESOLVE_Q* p_q = &btm_cb.ble_ctr_cb.resolving_list_pend_q; for (uint8_t i = p_q->q_pending; i != p_q->q_next;) { - if (p_q->resolve_q_random_pseudo[i] == pseudo_addr && - action == p_q->resolve_q_action[i]) + if (p_q->resolve_q_random_pseudo[i] == pseudo_addr && action == p_q->resolve_q_action[i]) { return true; + } i++; i %= bluetooth::shim::GetController()->GetLeResolvingListSize(); @@ -132,8 +131,7 @@ static bool btm_ble_deq_resolving_pending(RawAddress& pseudo_addr) { pseudo_addr = p_q->resolve_q_random_pseudo[p_q->q_pending]; p_q->resolve_q_random_pseudo[p_q->q_pending] = RawAddress::kEmpty; p_q->q_pending++; - p_q->q_pending %= - bluetooth::shim::GetController()->GetLeResolvingListSize(); + p_q->q_pending %= bluetooth::shim::GetController()->GetLeResolvingListSize(); return true; } @@ -198,15 +196,17 @@ static uint8_t btm_ble_find_irk_index(void) { * Returns void * ******************************************************************************/ -static void btm_ble_update_resolving_list(const RawAddress& pseudo_bda, - bool add) { +static void btm_ble_update_resolving_list(const RawAddress& pseudo_bda, bool add) { tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(pseudo_bda); - if (p_dev_rec == NULL) return; + if (p_dev_rec == NULL) { + return; + } if (add) { p_dev_rec->ble.in_controller_list |= BTM_RESOLVING_LIST_BIT; - if (!bluetooth::shim::GetController()->SupportsBlePrivacy()) + if (!bluetooth::shim::GetController()->SupportsBlePrivacy()) { p_dev_rec->ble.resolving_list_index = btm_ble_find_irk_index(); + } } else { p_dev_rec->ble.in_controller_list &= ~BTM_RESOLVING_LIST_BIT; if (!bluetooth::shim::GetController()->SupportsBlePrivacy()) { @@ -255,19 +255,19 @@ void btm_ble_clear_resolving_list_complete(uint8_t* p, uint16_t evt_len) { uint8_t irk_list_sz_max = 0; STREAM_TO_UINT8(irk_list_sz_max, p); - if (bluetooth::shim::GetController()->GetLeResolvingListSize() == 0) + if (bluetooth::shim::GetController()->GetLeResolvingListSize() == 0) { btm_ble_resolving_list_init(irk_list_sz_max); + } - uint8_t irk_mask_size = (irk_list_sz_max % 8) ? (irk_list_sz_max / 8 + 1) - : (irk_list_sz_max / 8); + uint8_t irk_mask_size = + (irk_list_sz_max % 8) ? (irk_list_sz_max / 8 + 1) : (irk_list_sz_max / 8); memset(btm_cb.ble_ctr_cb.irk_list_mask, 0, irk_mask_size); } btm_cb.ble_ctr_cb.resolving_list_avail_size = - bluetooth::shim::GetController()->GetLeResolvingListSize(); + bluetooth::shim::GetController()->GetLeResolvingListSize(); - log::verbose("resolving_list_avail_size={}", - btm_cb.ble_ctr_cb.resolving_list_avail_size); + log::verbose("resolving_list_avail_size={}", btm_cb.ble_ctr_cb.resolving_list_avail_size); list_foreach(btm_sec_cb.sec_dev_rec, clear_resolving_list_bit, NULL); } @@ -308,10 +308,10 @@ void btm_ble_add_resolving_list_entry_complete(uint8_t* p, uint16_t evt_len) { /* VSC complete has one extra byte for op code, skip it here */ p++; STREAM_TO_UINT8(btm_cb.ble_ctr_cb.resolving_list_avail_size, p); - } else + } else { btm_cb.ble_ctr_cb.resolving_list_avail_size--; - } else if (status == - HCI_ERR_MEMORY_FULL) /* BT_ERROR_CODE_MEMORY_CAPACITY_EXCEEDED */ + } + } else if (status == HCI_ERR_MEMORY_FULL) /* BT_ERROR_CODE_MEMORY_CAPACITY_EXCEEDED */ { btm_cb.ble_ctr_cb.resolving_list_avail_size = 0; log::verbose("Resolving list Full"); @@ -328,8 +328,7 @@ void btm_ble_add_resolving_list_entry_complete(uint8_t* p, uint16_t evt_len) { * Returns void * ******************************************************************************/ -void btm_ble_remove_resolving_list_entry_complete(uint8_t* p, - uint16_t evt_len) { +void btm_ble_remove_resolving_list_entry_complete(uint8_t* p, uint16_t evt_len) { RawAddress pseudo_bda; uint8_t status; @@ -347,8 +346,9 @@ void btm_ble_remove_resolving_list_entry_complete(uint8_t* p, if (evt_len > 2) { p++; /* skip opcode */ STREAM_TO_UINT8(btm_cb.ble_ctr_cb.resolving_list_avail_size, p); - } else + } else { btm_cb.ble_ctr_cb.resolving_list_avail_size++; + } } } @@ -362,8 +362,7 @@ void btm_ble_remove_resolving_list_entry_complete(uint8_t* p, * Returns void * ******************************************************************************/ -void btm_ble_read_resolving_list_entry_complete(const uint8_t* p, - uint16_t evt_len) { +void btm_ble_read_resolving_list_entry_complete(const uint8_t* p, uint16_t evt_len) { uint8_t status; RawAddress rra, pseudo_bda; @@ -387,8 +386,8 @@ void btm_ble_read_resolving_list_entry_complete(const uint8_t* p, } else { STREAM_TO_BDADDR(rra, p); } - btm_ble_refresh_peer_resolvable_private_addr( - pseudo_bda, rra, tBLE_RAND_ADDR_TYPE::BTM_BLE_ADDR_PSEUDO); + btm_ble_refresh_peer_resolvable_private_addr(pseudo_bda, rra, + tBLE_RAND_ADDR_TYPE::BTM_BLE_ADDR_PSEUDO); } } /******************************************************************************* @@ -438,15 +437,14 @@ static void btm_ble_resolving_list_vsc_op_cmpl(tBTM_VSC_CMPL* p_params) { * Returns status * ******************************************************************************/ -static tBTM_STATUS btm_ble_remove_resolving_list_entry( - tBTM_SEC_DEV_REC* p_dev_rec) { +static tBTM_STATUS btm_ble_remove_resolving_list_entry(tBTM_SEC_DEV_REC* p_dev_rec) { /* if controller does not support RPA offloading or privacy 1.2, skip */ - if (bluetooth::shim::GetController()->GetLeResolvingListSize() == 0) + if (bluetooth::shim::GetController()->GetLeResolvingListSize() == 0) { return BTM_WRONG_MODE; + } if (bluetooth::shim::GetController()->SupportsBlePrivacy()) { - bluetooth::shim::ACL_RemoveFromAddressResolution( - p_dev_rec->ble.identity_address_with_type); + bluetooth::shim::ACL_RemoveFromAddressResolution(p_dev_rec->ble.identity_address_with_type); } else { uint8_t param[20] = {0}; uint8_t* p = param; @@ -455,11 +453,10 @@ static tBTM_STATUS btm_ble_remove_resolving_list_entry( UINT8_TO_STREAM(p, p_dev_rec->ble.identity_address_with_type.type); BDADDR_TO_STREAM(p, p_dev_rec->ble.identity_address_with_type.bda); - get_btm_client_interface().vendor.BTM_VendorSpecificCommand( - HCI_VENDOR_BLE_RPA_VSC, BTM_BLE_META_REMOVE_IRK_LEN, param, - btm_ble_resolving_list_vsc_op_cmpl); - btm_ble_enq_resolving_list_pending(p_dev_rec->bd_addr, - BTM_BLE_META_REMOVE_IRK_ENTRY); + get_btm_client_interface().vendor.BTM_VendorSpecificCommand(HCI_VENDOR_BLE_RPA_VSC, + BTM_BLE_META_REMOVE_IRK_LEN, param, + btm_ble_resolving_list_vsc_op_cmpl); + btm_ble_enq_resolving_list_pending(p_dev_rec->bd_addr, BTM_BLE_META_REMOVE_IRK_ENTRY); } return BTM_CMD_STARTED; } @@ -481,9 +478,9 @@ static void btm_ble_clear_resolving_list(void) { uint8_t* p = param; UINT8_TO_STREAM(p, BTM_BLE_META_CLEAR_IRK_LIST); - get_btm_client_interface().vendor.BTM_VendorSpecificCommand( - HCI_VENDOR_BLE_RPA_VSC, BTM_BLE_META_CLEAR_IRK_LEN, param, - btm_ble_resolving_list_vsc_op_cmpl); + get_btm_client_interface().vendor.BTM_VendorSpecificCommand(HCI_VENDOR_BLE_RPA_VSC, + BTM_BLE_META_CLEAR_IRK_LEN, param, + btm_ble_resolving_list_vsc_op_cmpl); } } @@ -509,9 +506,8 @@ bool btm_ble_read_resolving_list_entry(tBTM_SEC_DEV_REC* p_dev_rec) { } if (bluetooth::shim::GetController()->SupportsBlePrivacy()) { - btsnd_hcic_ble_read_resolvable_addr_peer( - p_dev_rec->ble.identity_address_with_type.type, - p_dev_rec->ble.identity_address_with_type.bda); + btsnd_hcic_ble_read_resolvable_addr_peer(p_dev_rec->ble.identity_address_with_type.type, + p_dev_rec->ble.identity_address_with_type.bda); } else { uint8_t param[20] = {0}; uint8_t* p = param; @@ -519,18 +515,16 @@ bool btm_ble_read_resolving_list_entry(tBTM_SEC_DEV_REC* p_dev_rec) { UINT8_TO_STREAM(p, BTM_BLE_META_READ_IRK_ENTRY); UINT8_TO_STREAM(p, p_dev_rec->ble.resolving_list_index); - get_btm_client_interface().vendor.BTM_VendorSpecificCommand( - HCI_VENDOR_BLE_RPA_VSC, BTM_BLE_META_READ_IRK_LEN, param, - btm_ble_resolving_list_vsc_op_cmpl); + get_btm_client_interface().vendor.BTM_VendorSpecificCommand(HCI_VENDOR_BLE_RPA_VSC, + BTM_BLE_META_READ_IRK_LEN, param, + btm_ble_resolving_list_vsc_op_cmpl); - btm_ble_enq_resolving_list_pending(p_dev_rec->bd_addr, - BTM_BLE_META_READ_IRK_ENTRY); + btm_ble_enq_resolving_list_pending(p_dev_rec->bd_addr, BTM_BLE_META_READ_IRK_ENTRY); } return true; } -static void btm_ble_ble_unsupported_resolving_list_load_dev( - tBTM_SEC_DEV_REC* p_dev_rec) { +static void btm_ble_ble_unsupported_resolving_list_load_dev(tBTM_SEC_DEV_REC* p_dev_rec) { log::info("Controller does not support BLE privacy"); uint8_t param[40] = {0}; uint8_t* p = param; @@ -540,12 +534,11 @@ static void btm_ble_ble_unsupported_resolving_list_load_dev( UINT8_TO_STREAM(p, p_dev_rec->ble.identity_address_with_type.type); BDADDR_TO_STREAM(p, p_dev_rec->ble.identity_address_with_type.bda); - get_btm_client_interface().vendor.BTM_VendorSpecificCommand( - HCI_VENDOR_BLE_RPA_VSC, BTM_BLE_META_ADD_IRK_LEN, param, - btm_ble_resolving_list_vsc_op_cmpl); + get_btm_client_interface().vendor.BTM_VendorSpecificCommand(HCI_VENDOR_BLE_RPA_VSC, + BTM_BLE_META_ADD_IRK_LEN, param, + btm_ble_resolving_list_vsc_op_cmpl); - btm_ble_enq_resolving_list_pending(p_dev_rec->bd_addr, - BTM_BLE_META_ADD_IRK_ENTRY); + btm_ble_enq_resolving_list_pending(p_dev_rec->bd_addr, BTM_BLE_META_ADD_IRK_ENTRY); return; } @@ -571,8 +564,7 @@ void btm_ble_resolving_list_load_dev(tBTM_SEC_DEV_REC& dev_rec) { // No need to check for local identity key validity. It remains unchanged. if (!is_peer_identity_key_valid(dev_rec)) { - log::info("Peer is not an RPA enabled device:{}", - dev_rec.ble.identity_address_with_type); + log::info("Peer is not an RPA enabled device:{}", dev_rec.ble.identity_address_with_type); return; } @@ -587,8 +579,8 @@ void btm_ble_resolving_list_load_dev(tBTM_SEC_DEV_REC& dev_rec) { if (dev_rec.ble.identity_address_with_type.bda.IsEmpty()) { dev_rec.ble.identity_address_with_type = { - .type = dev_rec.ble.AddressType(), - .bda = dev_rec.bd_addr, + .type = dev_rec.ble.AddressType(), + .bda = dev_rec.bd_addr, }; } @@ -598,11 +590,10 @@ void btm_ble_resolving_list_load_dev(tBTM_SEC_DEV_REC& dev_rec) { return; } - bluetooth::shim::ACL_AddToAddressResolution( - dev_rec.ble.identity_address_with_type, peer_irk, local_irk); + bluetooth::shim::ACL_AddToAddressResolution(dev_rec.ble.identity_address_with_type, peer_irk, + local_irk); - log::debug("Added to Address Resolving list device:{}", - dev_rec.ble.identity_address_with_type); + log::debug("Added to Address Resolving list device:{}", dev_rec.ble.identity_address_with_type); dev_rec.ble.in_controller_list |= BTM_RESOLVING_LIST_BIT; } @@ -625,8 +616,8 @@ void btm_ble_resolving_list_remove_dev(tBTM_SEC_DEV_REC* p_dev_rec) { } if ((p_dev_rec->ble.in_controller_list & BTM_RESOLVING_LIST_BIT) && - !btm_ble_brcm_find_resolving_pending_entry( - p_dev_rec->bd_addr, BTM_BLE_META_REMOVE_IRK_ENTRY)) { + !btm_ble_brcm_find_resolving_pending_entry(p_dev_rec->bd_addr, + BTM_BLE_META_REMOVE_IRK_ENTRY)) { btm_ble_update_resolving_list(p_dev_rec->bd_addr, false); btm_ble_remove_resolving_list_entry(p_dev_rec); } else { @@ -647,20 +638,19 @@ void btm_ble_resolving_list_remove_dev(tBTM_SEC_DEV_REC* p_dev_rec) { ******************************************************************************/ void btm_ble_resolving_list_init(uint8_t max_irk_list_sz) { tBTM_BLE_RESOLVE_Q* p_q = &btm_cb.ble_ctr_cb.resolving_list_pend_q; - uint8_t irk_mask_size = - (max_irk_list_sz % 8) ? (max_irk_list_sz / 8 + 1) : (max_irk_list_sz / 8); + uint8_t irk_mask_size = (max_irk_list_sz % 8) ? (max_irk_list_sz / 8 + 1) : (max_irk_list_sz / 8); if (max_irk_list_sz > 0 && p_q->resolve_q_random_pseudo == nullptr) { // NOTE: This memory is never freed - p_q->resolve_q_random_pseudo = - (RawAddress*)osi_malloc(sizeof(RawAddress) * max_irk_list_sz); + p_q->resolve_q_random_pseudo = (RawAddress*)osi_malloc(sizeof(RawAddress) * max_irk_list_sz); // NOTE: This memory is never freed p_q->resolve_q_action = (uint8_t*)osi_malloc(max_irk_list_sz); /* RPA offloading feature */ - if (btm_cb.ble_ctr_cb.irk_list_mask == NULL) + if (btm_cb.ble_ctr_cb.irk_list_mask == NULL) { // NOTE: This memory is never freed btm_cb.ble_ctr_cb.irk_list_mask = (uint8_t*)osi_malloc(irk_mask_size); + } log::verbose("max_irk_list_sz={}", max_irk_list_sz); } diff --git a/system/stack/btm/btm_ble_scanner.cc b/system/stack/btm/btm_ble_scanner.cc index 08314687567..be44ee2abf7 100644 --- a/system/stack/btm/btm_ble_scanner.cc +++ b/system/stack/btm/btm_ble_scanner.cc @@ -35,22 +35,19 @@ static void status_callback(uint8_t status) { log::verbose("Received status_cb with status:{}", status); } -class BleScanningManagerImpl - : public BleScanningManager, - public BleScannerHciInterface::ScanEventObserver { - public: +class BleScanningManagerImpl : public BleScanningManager, + public BleScannerHciInterface::ScanEventObserver { +public: BleScanningManagerImpl(BleScannerHciInterface* interface) : hci_interface(interface), weak_factory_(this) {} ~BleScanningManagerImpl() {} void PeriodicScanStart(uint8_t options, uint8_t set_id, uint8_t adv_addr_type, - const RawAddress& adv_addr, uint16_t skip_num, - uint16_t sync_timeout, + const RawAddress& adv_addr, uint16_t skip_num, uint16_t sync_timeout, uint8_t sync_cte_type) override { - GetHciInterface()->PeriodicScanStart(options, set_id, adv_addr_type, - adv_addr, skip_num, sync_timeout, - sync_cte_type); + GetHciInterface()->PeriodicScanStart(options, set_id, adv_addr_type, adv_addr, skip_num, + sync_timeout, sync_cte_type); } void PeriodicScanCancelStart() override { @@ -58,60 +55,50 @@ class BleScanningManagerImpl } void PeriodicScanTerminate(uint16_t sync_handle) override { - GetHciInterface()->PeriodicScanTerminate(sync_handle, - base::Bind(&status_callback)); + GetHciInterface()->PeriodicScanTerminate(sync_handle, base::Bind(&status_callback)); } - void PeriodicAdvSyncTransfer( - const RawAddress& bd_addr, uint16_t service_data, uint16_t sync_handle, - BleScannerHciInterface::handle_cb command_complete) override { - GetHciInterface()->PeriodicAdvSyncTransfer(bd_addr, service_data, - sync_handle, command_complete); + void PeriodicAdvSyncTransfer(const RawAddress& bd_addr, uint16_t service_data, + uint16_t sync_handle, + BleScannerHciInterface::handle_cb command_complete) override { + GetHciInterface()->PeriodicAdvSyncTransfer(bd_addr, service_data, sync_handle, + command_complete); } - void PeriodicAdvSetInfoTransfer(const RawAddress& bd_addr, - uint16_t service_data, uint8_t adv_handle, - handle_cb command_complete) override { - GetHciInterface()->PeriodicAdvSetInfoTransfer(bd_addr, service_data, - adv_handle, command_complete); + void PeriodicAdvSetInfoTransfer(const RawAddress& bd_addr, uint16_t service_data, + uint8_t adv_handle, handle_cb command_complete) override { + GetHciInterface()->PeriodicAdvSetInfoTransfer(bd_addr, service_data, adv_handle, + command_complete); } - void SetPeriodicAdvSyncTransferParams(const RawAddress& bd_addr, uint8_t mode, - uint16_t skip, uint16_t sync_timeout, - uint8_t cte_type, bool set_defaults, + void SetPeriodicAdvSyncTransferParams(const RawAddress& bd_addr, uint8_t mode, uint16_t skip, + uint16_t sync_timeout, uint8_t cte_type, bool set_defaults, status_cb command_complete) override { - GetHciInterface()->SetPeriodicAdvSyncTransferParams( - bd_addr, mode, skip, sync_timeout, cte_type, set_defaults, - command_complete); + GetHciInterface()->SetPeriodicAdvSyncTransferParams(bd_addr, mode, skip, sync_timeout, cte_type, + set_defaults, command_complete); } - void OnPeriodicScanResult(uint16_t sync_handle, uint8_t tx_power, int8_t rssi, - uint8_t cte_type, uint8_t pkt_data_status, - uint8_t pkt_data_len, + void OnPeriodicScanResult(uint16_t sync_handle, uint8_t tx_power, int8_t rssi, uint8_t cte_type, + uint8_t pkt_data_status, uint8_t pkt_data_len, const uint8_t* pkt_data) override { - btm_ble_periodic_adv_report(sync_handle, tx_power, rssi, cte_type, - pkt_data_status, pkt_data_len, pkt_data); + btm_ble_periodic_adv_report(sync_handle, tx_power, rssi, cte_type, pkt_data_status, + pkt_data_len, pkt_data); } - void OnPeriodicScanEstablished(uint8_t status, uint16_t sync_handle, - uint8_t set_id, uint8_t adv_addr_type, - const RawAddress& adv_addr, uint8_t adv_phy, - uint16_t adv_interval, - uint8_t adv_clock_accuracy) override { - btm_ble_periodic_adv_sync_established(status, sync_handle, set_id, - adv_addr_type, adv_addr, adv_phy, - adv_interval, adv_clock_accuracy); + void OnPeriodicScanEstablished(uint8_t status, uint16_t sync_handle, uint8_t set_id, + uint8_t adv_addr_type, const RawAddress& adv_addr, uint8_t adv_phy, + uint16_t adv_interval, uint8_t adv_clock_accuracy) override { + btm_ble_periodic_adv_sync_established(status, sync_handle, set_id, adv_addr_type, adv_addr, + adv_phy, adv_interval, adv_clock_accuracy); } void OnPeriodicScanLost(uint16_t sync_handle) override { btm_ble_periodic_adv_sync_lost(sync_handle); } - base::WeakPtr GetWeakPtr() { - return weak_factory_.GetWeakPtr(); - } + base::WeakPtr GetWeakPtr() { return weak_factory_.GetWeakPtr(); } - private: +private: BleScannerHciInterface* GetHciInterface() { return hci_interface; } BleScannerHciInterface* hci_interface = nullptr; @@ -130,14 +117,12 @@ void BleScanningManager::Initialize(BleScannerHciInterface* interface) { bool BleScanningManager::IsInitialized() { return instance; } -base::WeakPtr BleScanningManager::Get() { - return instance_weakptr; -}; +base::WeakPtr BleScanningManager::Get() { return instance_weakptr; } void BleScanningManager::CleanUp() { delete instance; instance = nullptr; -}; +} /** * This function initializes the scanning manager. @@ -151,7 +136,7 @@ void btm_ble_scanner_init() { } if ((BleScannerHciInterface::Get()) && (BleScanningManager::Get())) { BleScannerHciInterface::Get()->SetScanEventObserver( - (BleScanningManagerImpl*)BleScanningManager::Get().get()); + (BleScanningManagerImpl*)BleScanningManager::Get().get()); } else { log::verbose("BleScannerHciInterface or BleScanningManager is null"); } diff --git a/system/stack/btm/btm_ble_sec.cc b/system/stack/btm/btm_ble_sec.cc index aab79ea7d2a..327f7a5abe6 100644 --- a/system/stack/btm/btm_ble_sec.cc +++ b/system/stack/btm/btm_ble_sec.cc @@ -64,15 +64,14 @@ using namespace bluetooth; extern tBTM_CB btm_cb; -bool btm_ble_init_pseudo_addr(tBTM_SEC_DEV_REC* p_dev_rec, - const RawAddress& new_pseudo_addr); +bool btm_ble_init_pseudo_addr(tBTM_SEC_DEV_REC* p_dev_rec, const RawAddress& new_pseudo_addr); namespace { constexpr char kBtmLogTag[] = "SEC"; } static constexpr char kPropertyCtkdDisableCsrkDistribution[] = - "bluetooth.core.smp.le.ctkd.quirk_disable_csrk_distribution"; + "bluetooth.core.smp.le.ctkd.quirk_disable_csrk_distribution"; /******************************************************************************/ /* External Function to be called by other modules */ @@ -97,8 +96,8 @@ void BTM_SecAddBleDevice(const RawAddress& bd_addr, tBT_DEVICE_TYPE dev_type, p_dev_rec->conn_params.supervision_tout = BTM_BLE_CONN_PARAM_UNDEF; p_dev_rec->conn_params.peripheral_latency = BTM_BLE_CONN_PARAM_UNDEF; - log::debug("Device added, handle=0x{:x}, p_dev_rec={}, bd_addr={}", - p_dev_rec->ble_hci_handle, fmt::ptr(p_dev_rec), bd_addr); + log::debug("Device added, handle=0x{:x}, p_dev_rec={}, bd_addr={}", p_dev_rec->ble_hci_handle, + fmt::ptr(p_dev_rec), bd_addr); } memset(p_dev_rec->sec_bd_name, 0, sizeof(BD_NAME)); @@ -107,8 +106,7 @@ void BTM_SecAddBleDevice(const RawAddress& bd_addr, tBT_DEVICE_TYPE dev_type, if (is_ble_addr_type_known(addr_type)) { p_dev_rec->ble.SetAddressType(addr_type); } else { - log::warn( - "Please do not update device record from anonymous le advertisement"); + log::warn("Please do not update device record from anonymous le advertisement"); } /* sync up with the Inq Data base*/ @@ -116,8 +114,8 @@ void BTM_SecAddBleDevice(const RawAddress& bd_addr, tBT_DEVICE_TYPE dev_type, if (p_info) { p_info->results.ble_addr_type = p_dev_rec->ble.AddressType(); p_dev_rec->device_type |= p_info->results.device_type; - log::debug("InqDb device_type =0x{:x} addr_type=0x{:x}", - p_dev_rec->device_type, p_info->results.ble_addr_type); + log::debug("InqDb device_type =0x{:x} addr_type=0x{:x}", p_dev_rec->device_type, + p_info->results.ble_addr_type); p_info->results.device_type = p_dev_rec->device_type; } } @@ -138,11 +136,9 @@ bool BTM_GetRemoteDeviceName(const RawAddress& bd_addr, BD_NAME bd_name) { bool ret = FALSE; bt_bdname_t bdname; bt_property_t prop_name; - BTIF_STORAGE_FILL_PROPERTY(&prop_name, BT_PROPERTY_BDNAME, - sizeof(bt_bdname_t), &bdname); + BTIF_STORAGE_FILL_PROPERTY(&prop_name, BT_PROPERTY_BDNAME, sizeof(bt_bdname_t), &bdname); - if (btif_storage_get_remote_device_property(&bd_addr, &prop_name) == - BT_STATUS_SUCCESS) { + if (btif_storage_get_remote_device_property(&bd_addr, &prop_name) == BT_STATUS_SUCCESS) { log::verbose("NV name={}", reinterpret_cast(bdname.name)); bd_name_copy(bd_name, bdname.name); ret = TRUE; @@ -169,11 +165,9 @@ void BTM_SecAddBleKey(const RawAddress& bd_addr, tBTM_LE_KEY_VALUE* p_le_key, tBTM_LE_KEY_TYPE key_type) { tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr); if (!p_dev_rec || !p_le_key || - (key_type != BTM_LE_KEY_PENC && key_type != BTM_LE_KEY_PID && - key_type != BTM_LE_KEY_PCSRK && key_type != BTM_LE_KEY_LENC && - key_type != BTM_LE_KEY_LCSRK && key_type != BTM_LE_KEY_LID)) { - log::warn("Wrong Type, or No Device record for bdaddr:{}, Type:0{}", - bd_addr, key_type); + (key_type != BTM_LE_KEY_PENC && key_type != BTM_LE_KEY_PID && key_type != BTM_LE_KEY_PCSRK && + key_type != BTM_LE_KEY_LENC && key_type != BTM_LE_KEY_LCSRK && key_type != BTM_LE_KEY_LID)) { + log::warn("Wrong Type, or No Device record for bdaddr:{}, Type:0{}", bd_addr, key_type); return; } @@ -206,8 +200,7 @@ void BTM_BleLoadLocalKeys(uint8_t key_type, tBTM_BLE_LOCAL_KEYS* p_key) { if (p_key != NULL) { switch (key_type) { case BTM_BLE_KEY_TYPE_ID: - memcpy(&p_devcb->id_keys, &p_key->id_keys, - sizeof(tBTM_BLE_LOCAL_ID_KEYS)); + memcpy(&p_devcb->id_keys, &p_key->id_keys, sizeof(tBTM_BLE_LOCAL_ID_KEYS)); break; case BTM_BLE_KEY_TYPE_ER: @@ -222,9 +215,7 @@ void BTM_BleLoadLocalKeys(uint8_t key_type, tBTM_BLE_LOCAL_KEYS* p_key) { } /** Returns local device encryption root (ER) */ -const Octet16& BTM_GetDeviceEncRoot() { - return btm_sec_cb.devcb.ble_encryption_key_value; -} +const Octet16& BTM_GetDeviceEncRoot() { return btm_sec_cb.devcb.ble_encryption_key_value; } /** Returns local device identity root (IR). */ const Octet16& BTM_GetDeviceIDRoot() { return btm_sec_cb.devcb.id_keys.irk; } @@ -247,12 +238,10 @@ const Octet16& BTM_GetDeviceDHK() { return btm_sec_cb.devcb.id_keys.dhk; } * ******************************************************************************/ void BTM_SecurityGrant(const RawAddress& bd_addr, uint8_t res) { - const tSMP_STATUS res_smp = - (res == BTM_SUCCESS) ? SMP_SUCCESS : SMP_REPEATED_ATTEMPTS; + const tSMP_STATUS res_smp = (res == BTM_SUCCESS) ? SMP_SUCCESS : SMP_REPEATED_ATTEMPTS; log::verbose("bd_addr:{}, res:{}", bd_addr, smp_status_text(res_smp)); BTM_LogHistory(kBtmLogTag, bd_addr, "Granted", - base::StringPrintf("passkey_status:%s", - smp_status_text(res_smp).c_str())); + base::StringPrintf("passkey_status:%s", smp_status_text(res_smp).c_str())); SMP_SecurityGrant(bd_addr, res_smp); } @@ -271,8 +260,7 @@ void BTM_SecurityGrant(const RawAddress& bd_addr, uint8_t res) { * p_passkey - pointer to array with the passkey * ******************************************************************************/ -void BTM_BlePasskeyReply(const RawAddress& bd_addr, uint8_t res, - uint32_t passkey) { +void BTM_BlePasskeyReply(const RawAddress& bd_addr, uint8_t res, uint32_t passkey) { tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr); log::verbose("bd_addr:{}, res:{}", bd_addr, res); if (p_dev_rec == NULL) { @@ -280,8 +268,7 @@ void BTM_BlePasskeyReply(const RawAddress& bd_addr, uint8_t res, return; } - const tSMP_STATUS res_smp = - (res == BTM_SUCCESS) ? SMP_SUCCESS : SMP_PASSKEY_ENTRY_FAIL; + const tSMP_STATUS res_smp = (res == BTM_SUCCESS) ? SMP_SUCCESS : SMP_PASSKEY_ENTRY_FAIL; BTM_LogHistory(kBtmLogTag, bd_addr, "Passkey reply", base::StringPrintf("transport:%s authenticate_status:%s", bt_transport_text(BT_TRANSPORT_LE).c_str(), @@ -310,14 +297,12 @@ void BTM_BleConfirmReply(const RawAddress& bd_addr, uint8_t res) { log::error("Unknown device:{}", bd_addr); return; } - const tSMP_STATUS res_smp = - (res == BTM_SUCCESS) ? SMP_SUCCESS : SMP_PASSKEY_ENTRY_FAIL; + const tSMP_STATUS res_smp = (res == BTM_SUCCESS) ? SMP_SUCCESS : SMP_PASSKEY_ENTRY_FAIL; BTM_LogHistory(kBtmLogTag, bd_addr, "Confirm reply", - base::StringPrintf( - "transport:%s numeric_comparison_authenticate_status:%s", - bt_transport_text(BT_TRANSPORT_LE).c_str(), - smp_status_text(res_smp).c_str())); + base::StringPrintf("transport:%s numeric_comparison_authenticate_status:%s", + bt_transport_text(BT_TRANSPORT_LE).c_str(), + smp_status_text(res_smp).c_str())); p_dev_rec->sec_rec.sec_flags |= BTM_SEC_LE_AUTHENTICATED; SMP_ConfirmReply(bd_addr, res_smp); @@ -338,8 +323,7 @@ void BTM_BleConfirmReply(const RawAddress& bd_addr, uint8_t res) { * "Security Manager TK Value". * ******************************************************************************/ -void BTM_BleOobDataReply(const RawAddress& bd_addr, uint8_t res, uint8_t len, - uint8_t* p_data) { +void BTM_BleOobDataReply(const RawAddress& bd_addr, uint8_t res, uint8_t len, uint8_t* p_data) { tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr); if (p_dev_rec == NULL) { log::error("Unknown device:{}", bd_addr); @@ -369,18 +353,15 @@ void BTM_BleOobDataReply(const RawAddress& bd_addr, uint8_t res, uint8_t len, * p_r - pointer to Randomizer * ******************************************************************************/ -void BTM_BleSecureConnectionOobDataReply(const RawAddress& bd_addr, - uint8_t* p_c, uint8_t* p_r) { +void BTM_BleSecureConnectionOobDataReply(const RawAddress& bd_addr, uint8_t* p_c, uint8_t* p_r) { tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr); if (p_dev_rec == NULL) { log::error("Unknown device:{}", bd_addr); return; } - BTM_LogHistory( - kBtmLogTag, bd_addr, "Oob data reply", - base::StringPrintf("transport:%s", - bt_transport_text(BT_TRANSPORT_LE).c_str())); + BTM_LogHistory(kBtmLogTag, bd_addr, "Oob data reply", + base::StringPrintf("transport:%s", bt_transport_text(BT_TRANSPORT_LE).c_str())); p_dev_rec->sec_rec.sec_flags |= BTM_SEC_LE_AUTHENTICATED; @@ -414,18 +395,15 @@ void BTM_BleSecureConnectionOobDataReply(const RawAddress& bd_addr, * ******************************************************************************/ void BTM_BleSetPrefConnParams(const RawAddress& bd_addr, uint16_t min_conn_int, - uint16_t max_conn_int, - uint16_t peripheral_latency, + uint16_t max_conn_int, uint16_t peripheral_latency, uint16_t supervision_tout) { tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr); - log::verbose("min:{},max:{},latency:{},tout:{}", min_conn_int, max_conn_int, - peripheral_latency, supervision_tout); + log::verbose("min:{},max:{},latency:{},tout:{}", min_conn_int, max_conn_int, peripheral_latency, + supervision_tout); - if (BTM_BLE_ISVALID_PARAM(min_conn_int, BTM_BLE_CONN_INT_MIN, - BTM_BLE_CONN_INT_MAX) && - BTM_BLE_ISVALID_PARAM(max_conn_int, BTM_BLE_CONN_INT_MIN, - BTM_BLE_CONN_INT_MAX) && + if (BTM_BLE_ISVALID_PARAM(min_conn_int, BTM_BLE_CONN_INT_MIN, BTM_BLE_CONN_INT_MAX) && + BTM_BLE_ISVALID_PARAM(max_conn_int, BTM_BLE_CONN_INT_MIN, BTM_BLE_CONN_INT_MAX) && BTM_BLE_ISVALID_PARAM(supervision_tout, BTM_BLE_CONN_SUP_TOUT_MIN, BTM_BLE_CONN_SUP_TOUT_MAX) && (peripheral_latency <= BTM_BLE_CONN_LATENCY_MAX || @@ -434,28 +412,30 @@ void BTM_BleSetPrefConnParams(const RawAddress& bd_addr, uint16_t min_conn_int, /* expect conn int and stout and peripheral latency to be updated all * together */ - if (min_conn_int != BTM_BLE_CONN_PARAM_UNDEF || - max_conn_int != BTM_BLE_CONN_PARAM_UNDEF) { - if (min_conn_int != BTM_BLE_CONN_PARAM_UNDEF) + if (min_conn_int != BTM_BLE_CONN_PARAM_UNDEF || max_conn_int != BTM_BLE_CONN_PARAM_UNDEF) { + if (min_conn_int != BTM_BLE_CONN_PARAM_UNDEF) { p_dev_rec->conn_params.min_conn_int = min_conn_int; - else + } else { p_dev_rec->conn_params.min_conn_int = max_conn_int; + } - if (max_conn_int != BTM_BLE_CONN_PARAM_UNDEF) + if (max_conn_int != BTM_BLE_CONN_PARAM_UNDEF) { p_dev_rec->conn_params.max_conn_int = max_conn_int; - else + } else { p_dev_rec->conn_params.max_conn_int = min_conn_int; + } - if (peripheral_latency != BTM_BLE_CONN_PARAM_UNDEF) + if (peripheral_latency != BTM_BLE_CONN_PARAM_UNDEF) { p_dev_rec->conn_params.peripheral_latency = peripheral_latency; - else - p_dev_rec->conn_params.peripheral_latency = - BTM_BLE_CONN_PERIPHERAL_LATENCY_DEF; + } else { + p_dev_rec->conn_params.peripheral_latency = BTM_BLE_CONN_PERIPHERAL_LATENCY_DEF; + } - if (supervision_tout != BTM_BLE_CONN_PARAM_UNDEF) + if (supervision_tout != BTM_BLE_CONN_PARAM_UNDEF) { p_dev_rec->conn_params.supervision_tout = supervision_tout; - else + } else { p_dev_rec->conn_params.supervision_tout = BTM_BLE_CONN_TIMEOUT_DEF; + } } } else { @@ -500,16 +480,16 @@ void BTM_ReadDevInfo(const RawAddress& remote_bda, tBT_DEVICE_TYPE* p_dev_type, /* new inquiry result, merge device type in security device record */ if (p_inq_info) { p_dev_rec->device_type |= p_inq_info->results.device_type; - if (is_ble_addr_type_known(p_inq_info->results.ble_addr_type)) + if (is_ble_addr_type_known(p_inq_info->results.ble_addr_type)) { p_dev_rec->ble.SetAddressType(p_inq_info->results.ble_addr_type); - else + } else { log::warn( - "Please do not update device record from anonymous le " - "advertisement"); + "Please do not update device record from anonymous le " + "advertisement"); + } } - if (p_dev_rec->bd_addr == remote_bda && - p_dev_rec->ble.pseudo_addr == remote_bda) { + if (p_dev_rec->bd_addr == remote_bda && p_dev_rec->ble.pseudo_addr == remote_bda) { *p_dev_type = p_dev_rec->device_type; *p_addr_type = p_dev_rec->ble.AddressType(); } else if (p_dev_rec->ble.pseudo_addr == remote_bda) { @@ -525,8 +505,8 @@ void BTM_ReadDevInfo(const RawAddress& remote_bda, tBT_DEVICE_TYPE* p_dev_type, *p_addr_type = BLE_ADDR_PUBLIC; } } - log::debug("Determined device_type:{} addr_type:{}", - DeviceTypeText(*p_dev_type), AddressTypeText(*p_addr_type)); + log::debug("Determined device_type:{} addr_type:{}", DeviceTypeText(*p_dev_type), + AddressTypeText(*p_addr_type)); } /******************************************************************************* @@ -543,12 +523,13 @@ void BTM_ReadDevInfo(const RawAddress& remote_bda, tBT_DEVICE_TYPE* p_dev_type, * Return true if an active link is identified; false otherwise * ******************************************************************************/ -bool BTM_ReadConnectedTransportAddress(RawAddress* remote_bda, - tBT_TRANSPORT transport) { +bool BTM_ReadConnectedTransportAddress(RawAddress* remote_bda, tBT_TRANSPORT transport) { tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(*remote_bda); /* if no device can be located, return */ - if (p_dev_rec == NULL) return false; + if (p_dev_rec == NULL) { + return false; + } if (transport == BT_TRANSPORT_BR_EDR) { if (BTM_IsAclConnectionUp(p_dev_rec->bd_addr, transport)) { @@ -556,26 +537,26 @@ bool BTM_ReadConnectedTransportAddress(RawAddress* remote_bda, return true; } else if (p_dev_rec->device_type & BT_DEVICE_TYPE_BREDR) { *remote_bda = p_dev_rec->bd_addr; - } else + } else { *remote_bda = RawAddress::kEmpty; + } return false; } if (transport == BT_TRANSPORT_LE) { *remote_bda = p_dev_rec->ble.pseudo_addr; - if (BTM_IsAclConnectionUp(p_dev_rec->ble.pseudo_addr, transport)) + if (BTM_IsAclConnectionUp(p_dev_rec->ble.pseudo_addr, transport)) { return true; - else + } else { return false; + } } return false; } -tBTM_STATUS BTM_SetBleDataLength(const RawAddress& bd_addr, - uint16_t tx_pdu_length) { - if (!bluetooth::shim::GetController() - ->SupportsBleDataPacketLengthExtension()) { +tBTM_STATUS BTM_SetBleDataLength(const RawAddress& bd_addr, uint16_t tx_pdu_length) { + if (!bluetooth::shim::GetController()->SupportsBleDataPacketLengthExtension()) { log::info("Local controller does not support le packet extension"); return BTM_ILLEGAL_VALUE; } @@ -588,10 +569,11 @@ tBTM_STATUS BTM_SetBleDataLength(const RawAddress& bd_addr, return BTM_UNKNOWN_ADDR; } - if (tx_pdu_length > BTM_BLE_DATA_SIZE_MAX) + if (tx_pdu_length > BTM_BLE_DATA_SIZE_MAX) { tx_pdu_length = BTM_BLE_DATA_SIZE_MAX; - else if (tx_pdu_length < BTM_BLE_DATA_SIZE_MIN) + } else if (tx_pdu_length < BTM_BLE_DATA_SIZE_MIN) { tx_pdu_length = BTM_BLE_DATA_SIZE_MIN; + } if (p_dev_rec->get_suggested_tx_octets() >= tx_pdu_length) { log::info("Suggested TX octect already set to controller {} >= {}", @@ -601,14 +583,13 @@ tBTM_STATUS BTM_SetBleDataLength(const RawAddress& bd_addr, uint16_t tx_time = BTM_BLE_DATA_TX_TIME_MAX_LEGACY; - if (bluetooth::shim::GetController() - ->GetLocalVersionInformation() - .hci_version_ >= bluetooth::hci::HciVersion::V_5_0) + if (bluetooth::shim::GetController()->GetLocalVersionInformation().hci_version_ >= + bluetooth::hci::HciVersion::V_5_0) { tx_time = BTM_BLE_DATA_TX_TIME_MAX; + } if (!BTM_IsAclConnectionUp(bd_addr, BT_TRANSPORT_LE)) { - log::info( - "Unable to set data length because no le acl link connected to device"); + log::info("Unable to set data length because no le acl link connected to device"); return BTM_WRONG_MODE; } @@ -620,13 +601,12 @@ tBTM_STATUS BTM_SetBleDataLength(const RawAddress& bd_addr, return BTM_ILLEGAL_VALUE; } - tx_pdu_length = - std::min(tx_pdu_length, bluetooth::shim::GetController() - ->GetLeMaximumDataLength() - .supported_max_tx_octets_); - tx_time = std::min(tx_time, bluetooth::shim::GetController() - ->GetLeMaximumDataLength() - .supported_max_tx_time_); + tx_pdu_length = std::min( + tx_pdu_length, + bluetooth::shim::GetController()->GetLeMaximumDataLength().supported_max_tx_octets_); + tx_time = std::min( + tx_time, + bluetooth::shim::GetController()->GetLeMaximumDataLength().supported_max_tx_time_); btsnd_hcic_ble_set_data_length(hci_handle, tx_pdu_length, tx_time); p_dev_rec->set_suggested_tx_octect(tx_pdu_length); @@ -649,8 +629,8 @@ tBTM_STATUS BTM_SetBleDataLength(const RawAddress& bd_addr, * Returns The appropriate security action required. * ******************************************************************************/ -static tBTM_SEC_ACTION btm_ble_determine_security_act( - bool is_originator, const RawAddress& bdaddr, uint16_t security_required) { +static tBTM_SEC_ACTION btm_ble_determine_security_act(bool is_originator, const RawAddress& bdaddr, + uint16_t security_required) { tBTM_LE_AUTH_REQ auth_req = 0x00; if (is_originator) { @@ -660,15 +640,18 @@ static tBTM_SEC_ACTION btm_ble_determine_security_act( return BTM_SEC_OK; } - if (security_required & BTM_SEC_OUT_MITM) auth_req |= BTM_LE_AUTH_REQ_MITM; + if (security_required & BTM_SEC_OUT_MITM) { + auth_req |= BTM_LE_AUTH_REQ_MITM; + } } else { - if ((security_required & BTM_SEC_IN_FLAGS) == 0 && - (security_required & BTM_SEC_IN_MITM) == 0) { + if ((security_required & BTM_SEC_IN_FLAGS) == 0 && (security_required & BTM_SEC_IN_MITM) == 0) { log::verbose("No security required for incoming connection"); return BTM_SEC_OK; } - if (security_required & BTM_SEC_IN_MITM) auth_req |= BTM_LE_AUTH_REQ_MITM; + if (security_required & BTM_SEC_IN_MITM) { + auth_req |= BTM_LE_AUTH_REQ_MITM; + } } tBTM_BLE_SEC_REQ_ACT ble_sec_act = {BTM_BLE_SEC_REQ_ACT_NONE}; @@ -676,9 +659,13 @@ static tBTM_SEC_ACTION btm_ble_determine_security_act( log::verbose("ble_sec_act {}", ble_sec_act); - if (ble_sec_act == BTM_BLE_SEC_REQ_ACT_DISCARD) return BTM_SEC_ENC_PENDING; + if (ble_sec_act == BTM_BLE_SEC_REQ_ACT_DISCARD) { + return BTM_SEC_ENC_PENDING; + } - if (ble_sec_act == BTM_BLE_SEC_REQ_ACT_NONE) return BTM_SEC_OK; + if (ble_sec_act == BTM_BLE_SEC_REQ_ACT_NONE) { + return BTM_SEC_OK; + } bool is_link_encrypted = BTM_IsEncrypted(bdaddr, BT_TRANSPORT_LE); bool is_key_mitm = BTM_IsLinkKeyAuthed(bdaddr, BT_TRANSPORT_LE); @@ -687,16 +674,18 @@ static tBTM_SEC_ACTION btm_ble_determine_security_act( if (!is_key_mitm) { return BTM_SEC_ENCRYPT_MITM; } else { - if (is_link_encrypted) + if (is_link_encrypted) { return BTM_SEC_OK; - else + } else { return BTM_SEC_ENCRYPT; + } } } else { - if (is_link_encrypted) + if (is_link_encrypted) { return BTM_SEC_OK; - else + } else { return BTM_SEC_ENCRYPT_NO_MITM; + } } return BTM_SEC_OK; @@ -718,13 +707,10 @@ static tBTM_SEC_ACTION btm_ble_determine_security_act( * Returns Returns - tBTM_STATUS * ******************************************************************************/ -tBTM_STATUS btm_ble_start_sec_check(const RawAddress& bd_addr, uint16_t psm, - bool is_originator, - tBTM_SEC_CALLBACK* p_callback, - void* p_ref_data) { +tBTM_STATUS btm_ble_start_sec_check(const RawAddress& bd_addr, uint16_t psm, bool is_originator, + tBTM_SEC_CALLBACK* p_callback, void* p_ref_data) { /* Find the service record for the PSM */ - tBTM_SEC_SERV_REC* p_serv_rec = - btm_sec_cb.find_first_serv_rec(is_originator, psm); + tBTM_SEC_SERV_REC* p_serv_rec = btm_sec_cb.find_first_serv_rec(is_originator, psm); /* If there is no application registered with this PSM do not allow connection */ @@ -740,8 +726,7 @@ tBTM_STATUS btm_ble_start_sec_check(const RawAddress& bd_addr, uint16_t psm, if (!is_originator) { if ((p_serv_rec->security_flags & BTM_SEC_IN_ENCRYPT) && !is_encrypted) { - log::error("BTM_NOT_ENCRYPTED. service security_flags=0x{:x}", - p_serv_rec->security_flags); + log::error("BTM_NOT_ENCRYPTED. service security_flags=0x{:x}", p_serv_rec->security_flags); return BTM_NOT_ENCRYPTED; } else if ((p_serv_rec->security_flags & BTM_SEC_IN_AUTHENTICATE) && !(is_link_key_authed || is_authenticated)) { @@ -753,8 +738,8 @@ tBTM_STATUS btm_ble_start_sec_check(const RawAddress& bd_addr, uint16_t psm, service is equal or smaller than the incoming connection key size. */ } - tBTM_SEC_ACTION sec_act = btm_ble_determine_security_act( - is_originator, bd_addr, p_serv_rec->security_flags); + tBTM_SEC_ACTION sec_act = + btm_ble_determine_security_act(is_originator, bd_addr, p_serv_rec->security_flags); tBTM_BLE_SEC_ACT ble_sec_act = BTM_BLE_SEC_NONE; @@ -790,8 +775,7 @@ tBTM_STATUS btm_ble_start_sec_check(const RawAddress& bd_addr, uint16_t psm, l2cble_update_sec_act(bd_addr, sec_act); - BTM_SetEncryption(bd_addr, BT_TRANSPORT_LE, p_callback, p_ref_data, - ble_sec_act); + BTM_SetEncryption(bd_addr, BT_TRANSPORT_LE, p_callback, p_ref_data, ble_sec_act); return BTM_SUCCESS; } @@ -811,8 +795,8 @@ void tBTM_SEC_REC::increment_sign_counter(bool local) { ble_keys.counter++; } - log::verbose("local={} local sign counter={} peer sign counter={}", local, - ble_keys.local_counter, ble_keys.counter); + log::verbose("local={} local sign counter={} peer sign counter={}", local, ble_keys.local_counter, + ble_keys.counter); } /******************************************************************************* @@ -880,46 +864,41 @@ void btm_sec_save_le_key(const RawAddress& bd_addr, tBTM_LE_KEY_TYPE key_type, tBTM_SEC_DEV_REC* p_rec; tBTM_LE_EVT_DATA cb_data; - log::verbose("key_type=0x{:x} pass_to_application={}", key_type, - pass_to_application); + log::verbose("key_type=0x{:x} pass_to_application={}", key_type, pass_to_application); /* Store the updated key in the device database */ - if ((p_rec = btm_find_dev(bd_addr)) != NULL && - (p_keys || key_type == BTM_LE_KEY_LID)) { + if ((p_rec = btm_find_dev(bd_addr)) != NULL && (p_keys || key_type == BTM_LE_KEY_LID)) { btm_ble_init_pseudo_addr(p_rec, bd_addr); switch (key_type) { case BTM_LE_KEY_PENC: p_rec->sec_rec.ble_keys.pltk = p_keys->penc_key.ltk; - memcpy(p_rec->sec_rec.ble_keys.rand, p_keys->penc_key.rand, - BT_OCTET8_LEN); + memcpy(p_rec->sec_rec.ble_keys.rand, p_keys->penc_key.rand, BT_OCTET8_LEN); p_rec->sec_rec.ble_keys.sec_level = p_keys->penc_key.sec_level; p_rec->sec_rec.ble_keys.ediv = p_keys->penc_key.ediv; p_rec->sec_rec.ble_keys.key_size = p_keys->penc_key.key_size; p_rec->sec_rec.ble_keys.key_type |= BTM_LE_KEY_PENC; p_rec->sec_rec.sec_flags |= BTM_SEC_LE_LINK_KEY_KNOWN; - if (p_keys->penc_key.sec_level == SMP_SEC_AUTHENTICATED) + if (p_keys->penc_key.sec_level == SMP_SEC_AUTHENTICATED) { p_rec->sec_rec.sec_flags |= BTM_SEC_LE_LINK_KEY_AUTHED; - else + } else { p_rec->sec_rec.sec_flags &= ~BTM_SEC_LE_LINK_KEY_AUTHED; - log::verbose( - "BTM_LE_KEY_PENC key_type=0x{:x} sec_flags=0x{:x} sec_leve=0x{:x}", - p_rec->sec_rec.ble_keys.key_type, p_rec->sec_rec.sec_flags, - p_rec->sec_rec.ble_keys.sec_level); + } + log::verbose("BTM_LE_KEY_PENC key_type=0x{:x} sec_flags=0x{:x} sec_leve=0x{:x}", + p_rec->sec_rec.ble_keys.key_type, p_rec->sec_rec.sec_flags, + p_rec->sec_rec.ble_keys.sec_level); break; case BTM_LE_KEY_PID: p_rec->sec_rec.ble_keys.irk = p_keys->pid_key.irk; - p_rec->ble.identity_address_with_type.bda = - p_keys->pid_key.identity_addr; - p_rec->ble.identity_address_with_type.type = - p_keys->pid_key.identity_addr_type; + p_rec->ble.identity_address_with_type.bda = p_keys->pid_key.identity_addr; + p_rec->ble.identity_address_with_type.type = p_keys->pid_key.identity_addr_type; p_rec->sec_rec.ble_keys.key_type |= BTM_LE_KEY_PID; log::verbose( - "BTM_LE_KEY_PID key_type=0x{:x} save peer IRK, change bd_addr={} " - "to id_addr={} id_addr_type=0x{:x}", - p_rec->sec_rec.ble_keys.key_type, p_rec->bd_addr, - p_keys->pid_key.identity_addr, p_keys->pid_key.identity_addr_type); + "BTM_LE_KEY_PID key_type=0x{:x} save peer IRK, change bd_addr={} " + "to id_addr={} id_addr_type=0x{:x}", + p_rec->sec_rec.ble_keys.key_type, p_rec->bd_addr, p_keys->pid_key.identity_addr, + p_keys->pid_key.identity_addr_type); /* update device record address as identity address */ p_rec->bd_addr = p_keys->pid_key.identity_addr; /* combine DUMO device security record if needed */ @@ -932,17 +911,17 @@ void btm_sec_save_le_key(const RawAddress& bd_addr, tBTM_LE_KEY_TYPE key_type, p_rec->sec_rec.ble_keys.counter = p_keys->pcsrk_key.counter; p_rec->sec_rec.ble_keys.key_type |= BTM_LE_KEY_PCSRK; p_rec->sec_rec.sec_flags |= BTM_SEC_LE_LINK_KEY_KNOWN; - if (p_keys->pcsrk_key.sec_level == SMP_SEC_AUTHENTICATED) + if (p_keys->pcsrk_key.sec_level == SMP_SEC_AUTHENTICATED) { p_rec->sec_rec.sec_flags |= BTM_SEC_LE_LINK_KEY_AUTHED; - else + } else { p_rec->sec_rec.sec_flags &= ~BTM_SEC_LE_LINK_KEY_AUTHED; + } log::verbose( - "BTM_LE_KEY_PCSRK key_type=0x{:x} sec_flags=0x{:x} " - "sec_level=0x{:x} peer_counter={}", - p_rec->sec_rec.ble_keys.key_type, p_rec->sec_rec.sec_flags, - p_rec->sec_rec.ble_keys.srk_sec_level, - p_rec->sec_rec.ble_keys.counter); + "BTM_LE_KEY_PCSRK key_type=0x{:x} sec_flags=0x{:x} " + "sec_level=0x{:x} peer_counter={}", + p_rec->sec_rec.ble_keys.key_type, p_rec->sec_rec.sec_flags, + p_rec->sec_rec.ble_keys.srk_sec_level, p_rec->sec_rec.ble_keys.counter); break; case BTM_LE_KEY_LENC: @@ -953,26 +932,24 @@ void btm_sec_save_le_key(const RawAddress& bd_addr, tBTM_LE_KEY_TYPE key_type, p_rec->sec_rec.ble_keys.key_type |= BTM_LE_KEY_LENC; log::verbose( - "BTM_LE_KEY_LENC key_type=0x{:x} DIV=0x{:x} key_size=0x{:x} " - "sec_level=0x{:x}", - p_rec->sec_rec.ble_keys.key_type, p_rec->sec_rec.ble_keys.div, - p_rec->sec_rec.ble_keys.key_size, - p_rec->sec_rec.ble_keys.sec_level); + "BTM_LE_KEY_LENC key_type=0x{:x} DIV=0x{:x} key_size=0x{:x} " + "sec_level=0x{:x}", + p_rec->sec_rec.ble_keys.key_type, p_rec->sec_rec.ble_keys.div, + p_rec->sec_rec.ble_keys.key_size, p_rec->sec_rec.ble_keys.sec_level); break; case BTM_LE_KEY_LCSRK: /* local CSRK has been delivered */ p_rec->sec_rec.ble_keys.lcsrk = p_keys->lcsrk_key.csrk; p_rec->sec_rec.ble_keys.div = p_keys->lcsrk_key.div; /* update DIV */ - p_rec->sec_rec.ble_keys.local_csrk_sec_level = - p_keys->lcsrk_key.sec_level; + p_rec->sec_rec.ble_keys.local_csrk_sec_level = p_keys->lcsrk_key.sec_level; p_rec->sec_rec.ble_keys.local_counter = p_keys->lcsrk_key.counter; p_rec->sec_rec.ble_keys.key_type |= BTM_LE_KEY_LCSRK; log::verbose( - "BTM_LE_KEY_LCSRK key_type=0x{:x} DIV=0x{:x} scrk_sec_level=0x{:x} " - "local_counter={}", - p_rec->sec_rec.ble_keys.key_type, p_rec->sec_rec.ble_keys.div, - p_rec->sec_rec.ble_keys.local_csrk_sec_level, - p_rec->sec_rec.ble_keys.local_counter); + "BTM_LE_KEY_LCSRK key_type=0x{:x} DIV=0x{:x} scrk_sec_level=0x{:x} " + "local_counter={}", + p_rec->sec_rec.ble_keys.key_type, p_rec->sec_rec.ble_keys.div, + p_rec->sec_rec.ble_keys.local_csrk_sec_level, + p_rec->sec_rec.ble_keys.local_counter); break; case BTM_LE_KEY_LID: @@ -996,8 +973,7 @@ void btm_sec_save_le_key(const RawAddress& bd_addr, tBTM_LE_KEY_TYPE key_type, return; } - log::warn("BLE key type 0x{:x}, called for Unknown BDA or type:{}", key_type, - bd_addr); + log::warn("BLE key type 0x{:x}, called for Unknown BDA or type:{}", key_type, bd_addr); if (p_rec) { log::verbose("sec_flags=0x{:x}", p_rec->sec_rec.sec_flags); @@ -1013,8 +989,7 @@ void btm_sec_save_le_key(const RawAddress& bd_addr, tBTM_LE_KEY_TYPE key_type, * Returns void * ******************************************************************************/ -void btm_ble_update_sec_key_size(const RawAddress& bd_addr, - uint8_t enc_key_size) { +void btm_ble_update_sec_key_size(const RawAddress& bd_addr, uint8_t enc_key_size) { tBTM_SEC_DEV_REC* p_rec; log::verbose("bd_addr:{}, enc_key_size={}", bd_addr, enc_key_size); @@ -1040,8 +1015,9 @@ uint8_t btm_ble_read_sec_key_size(const RawAddress& bd_addr) { p_rec = btm_find_dev(bd_addr); if (p_rec != NULL) { return p_rec->sec_rec.enc_key_size; - } else + } else { return 0; + } } /******************************************************************************* @@ -1053,8 +1029,7 @@ uint8_t btm_ble_read_sec_key_size(const RawAddress& bd_addr) { * Returns true: check is OK and the *p_sec_req_act contain the action * ******************************************************************************/ -void btm_ble_link_sec_check(const RawAddress& bd_addr, - tBTM_LE_AUTH_REQ auth_req, +void btm_ble_link_sec_check(const RawAddress& bd_addr, tBTM_LE_AUTH_REQ auth_req, tBTM_BLE_SEC_REQ_ACT* p_sec_req_act) { tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr); uint8_t req_sec_level = SMP_SEC_NONE, cur_sec_level = SMP_SEC_NONE; @@ -1081,17 +1056,19 @@ void btm_ble_link_sec_check(const RawAddress& bd_addr, /* currently encrpted */ if (p_dev_rec->sec_rec.sec_flags & BTM_SEC_LE_ENCRYPTED) { - if (p_dev_rec->sec_rec.sec_flags & BTM_SEC_LE_AUTHENTICATED) + if (p_dev_rec->sec_rec.sec_flags & BTM_SEC_LE_AUTHENTICATED) { cur_sec_level = SMP_SEC_AUTHENTICATED; - else + } else { cur_sec_level = SMP_SEC_UNAUTHENTICATE; + } } else /* unencrypted link */ { /* if bonded, get the key security level */ - if (p_dev_rec->sec_rec.ble_keys.key_type & BTM_LE_KEY_PENC) + if (p_dev_rec->sec_rec.ble_keys.key_type & BTM_LE_KEY_PENC) { cur_sec_level = p_dev_rec->sec_rec.ble_keys.sec_level; - else + } else { cur_sec_level = SMP_SEC_NONE; + } } if (cur_sec_level >= req_sec_level) { @@ -1104,8 +1081,8 @@ void btm_ble_link_sec_check(const RawAddress& bd_addr, } } - log::verbose("cur_sec_level={} req_sec_level={} sec_req_act={}", - cur_sec_level, req_sec_level, *p_sec_req_act); + log::verbose("cur_sec_level={} req_sec_level={} sec_req_act={}", cur_sec_level, req_sec_level, + *p_sec_req_act); } /******************************************************************************* @@ -1121,8 +1098,7 @@ void btm_ble_link_sec_check(const RawAddress& bd_addr, * the local device ER is copied into er * ******************************************************************************/ -tBTM_STATUS btm_ble_set_encryption(const RawAddress& bd_addr, - tBTM_BLE_SEC_ACT sec_act, +tBTM_STATUS btm_ble_set_encryption(const RawAddress& bd_addr, tBTM_BLE_SEC_ACT sec_act, uint8_t link_role) { tBTM_STATUS cmd = BTM_NO_RESOURCES; tBTM_SEC_DEV_REC* p_rec = btm_find_dev(bd_addr); @@ -1131,7 +1107,7 @@ tBTM_STATUS btm_ble_set_encryption(const RawAddress& bd_addr, if (p_rec == NULL) { log::warn("NULL device record!! sec_act=0x{:x}", sec_act); - return (BTM_WRONG_MODE); + return BTM_WRONG_MODE; } log::verbose("sec_act=0x{:x} role_central={}", sec_act, p_rec->role_central); @@ -1152,12 +1128,10 @@ tBTM_STATUS btm_ble_set_encryption(const RawAddress& bd_addr, FALLTHROUGH_INTENDED; /* FALLTHROUGH */ case BTM_BLE_SEC_ENCRYPT_NO_MITM: case BTM_BLE_SEC_ENCRYPT_MITM: - auth_req = (sec_act == BTM_BLE_SEC_ENCRYPT_NO_MITM) - ? SMP_AUTH_BOND - : (SMP_AUTH_BOND | SMP_AUTH_YN_BIT); + auth_req = (sec_act == BTM_BLE_SEC_ENCRYPT_NO_MITM) ? SMP_AUTH_BOND + : (SMP_AUTH_BOND | SMP_AUTH_YN_BIT); btm_ble_link_sec_check(bd_addr, auth_req, &sec_req_act); - if (sec_req_act == BTM_BLE_SEC_REQ_ACT_NONE || - sec_req_act == BTM_BLE_SEC_REQ_ACT_DISCARD) { + if (sec_req_act == BTM_BLE_SEC_REQ_ACT_NONE || sec_req_act == BTM_BLE_SEC_REQ_ACT_DISCARD) { log::verbose("no action needed. Ignore"); cmd = BTM_SUCCESS; break; @@ -1213,8 +1187,7 @@ void btm_ble_ltk_request(uint16_t handle, BT_OCTET8 rand, uint16_t ediv) { /** This function is called to start LE encryption. * Returns BTM_SUCCESS if encryption was started successfully */ -tBTM_STATUS btm_ble_start_encrypt(const RawAddress& bda, bool use_stk, - Octet16* p_stk) { +tBTM_STATUS btm_ble_start_encrypt(const RawAddress& bda, bool use_stk, Octet16* p_stk) { tBTM_SEC_CB* p_cb = &btm_sec_cb; tBTM_SEC_DEV_REC* p_rec = btm_find_dev(bda); BT_OCTET8 dummy_rand = {0}; @@ -1234,8 +1207,7 @@ tBTM_STATUS btm_ble_start_encrypt(const RawAddress& bda, bool use_stk, // Some controllers may not like encrypting both transports at the same time bool allow_le_enc_with_bredr = android::sysprop::bluetooth::Ble::allow_enc_with_bredr().value_or(false); - if (!allow_le_enc_with_bredr && - p_rec->sec_rec.is_security_state_bredr_encrypting()) { + if (!allow_le_enc_with_bredr && p_rec->sec_rec.is_security_state_bredr_encrypting()) { log::warn("BR/EDR link encryption is active, Busy!"); return BTM_BUSY; } @@ -1245,9 +1217,8 @@ tBTM_STATUS btm_ble_start_encrypt(const RawAddress& bda, bool use_stk, if (use_stk) { btsnd_hcic_ble_start_enc(p_rec->ble_hci_handle, dummy_rand, 0, *p_stk); } else if (p_rec->sec_rec.ble_keys.key_type & BTM_LE_KEY_PENC) { - btsnd_hcic_ble_start_enc( - p_rec->ble_hci_handle, p_rec->sec_rec.ble_keys.rand, - p_rec->sec_rec.ble_keys.ediv, p_rec->sec_rec.ble_keys.pltk); + btsnd_hcic_ble_start_enc(p_rec->ble_hci_handle, p_rec->sec_rec.ble_keys.rand, + p_rec->sec_rec.ble_keys.ediv, p_rec->sec_rec.ble_keys.pltk); } else { log::error("No key available to encrypt the link"); return BTM_ERR_KEY_MISSING; @@ -1272,18 +1243,16 @@ tBTM_STATUS btm_ble_start_encrypt(const RawAddress& bda, bool use_stk, * Returns void * ******************************************************************************/ -static void btm_ble_notify_enc_cmpl(const RawAddress& bd_addr, - bool encr_enable) { +static void btm_ble_notify_enc_cmpl(const RawAddress& bd_addr, bool encr_enable) { if (encr_enable) { uint8_t remote_lmp_version = 0; - if (!get_btm_client_interface().peer.BTM_ReadRemoteVersion( - bd_addr, &remote_lmp_version, nullptr, nullptr) || + if (!get_btm_client_interface().peer.BTM_ReadRemoteVersion(bd_addr, &remote_lmp_version, + nullptr, nullptr) || remote_lmp_version == 0) { log::warn("BLE Unable to determine remote version"); } - if (remote_lmp_version == 0 || - remote_lmp_version >= HCI_PROTO_VERSION_5_0) { + if (remote_lmp_version == 0 || remote_lmp_version >= HCI_PROTO_VERSION_5_0) { /* Link is encrypted, start EATT if remote LMP version is unknown, or 5.2 * or greater */ bluetooth::eatt::EattExtension::GetInstance()->Connect(bd_addr); @@ -1319,36 +1288,37 @@ void btm_ble_link_encrypted(const RawAddress& bd_addr, uint8_t encr_enable) { smp_link_encrypted(bd_addr, encr_enable); - log::verbose("p_dev_rec->sec_rec.sec_flags=0x{:x}", - p_dev_rec->sec_rec.sec_flags); + log::verbose("p_dev_rec->sec_rec.sec_flags=0x{:x}", p_dev_rec->sec_rec.sec_flags); - if (encr_enable && p_dev_rec->sec_rec.enc_key_size == 0) + if (encr_enable && p_dev_rec->sec_rec.enc_key_size == 0) { p_dev_rec->sec_rec.enc_key_size = p_dev_rec->sec_rec.ble_keys.key_size; + } p_dev_rec->sec_rec.sec_state = tSECURITY_STATE::IDLE; if (p_dev_rec->sec_rec.p_callback && enc_cback) { - if (encr_enable) btm_sec_dev_rec_cback_event(p_dev_rec, BTM_SUCCESS, true); + if (encr_enable) { + btm_sec_dev_rec_cback_event(p_dev_rec, BTM_SUCCESS, true); + } /* LTK missing on peripheral */ - else if (p_dev_rec->role_central && - (p_dev_rec->sec_rec.sec_status == HCI_ERR_KEY_MISSING)) { + else if (p_dev_rec->role_central && (p_dev_rec->sec_rec.sec_status == HCI_ERR_KEY_MISSING)) { btm_sec_dev_rec_cback_event(p_dev_rec, BTM_ERR_KEY_MISSING, true); } else if (!(p_dev_rec->sec_rec.sec_flags & BTM_SEC_LE_LINK_KEY_KNOWN)) { btm_sec_dev_rec_cback_event(p_dev_rec, BTM_FAILED_ON_SECURITY, true); - } else if (p_dev_rec->role_central) + } else if (p_dev_rec->role_central) { btm_sec_dev_rec_cback_event(p_dev_rec, BTM_ERR_PROCESSING, true); + } } BD_NAME remote_name = {}; /* to notify GATT to send data if any request is pending, or if IOP matched, delay notifying until SMP_CMPLT_EVT */ if (BTM_GetRemoteDeviceName(p_dev_rec->ble.pseudo_addr, remote_name) && - interop_match_name(INTEROP_SUSPEND_ATT_TRAFFIC_DURING_PAIRING, - (const char*)remote_name) && + interop_match_name(INTEROP_SUSPEND_ATT_TRAFFIC_DURING_PAIRING, (const char*)remote_name) && (btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_LE_ACTIVE) && btm_sec_cb.pairing_bda == p_dev_rec->ble.pseudo_addr) { log::info( - "INTEROP_DELAY_ATT_TRAFFIC_DURING_PAIRING: Waiting for bonding to " - "complete to notify enc complete"); + "INTEROP_DELAY_ATT_TRAFFIC_DURING_PAIRING: Waiting for bonding to " + "complete to notify enc complete"); } else { btm_ble_notify_enc_cmpl(p_dev_rec->ble.pseudo_addr, encr_enable); } @@ -1365,8 +1335,7 @@ void btm_ble_link_encrypted(const RawAddress& bd_addr, uint8_t encr_enable) { * Returns void * ******************************************************************************/ -void btm_ble_ltk_request_reply(const RawAddress& bda, bool use_stk, - const Octet16& stk) { +void btm_ble_ltk_request_reply(const RawAddress& bda, bool use_stk, const Octet16& stk) { tBTM_SEC_DEV_REC* p_rec = btm_find_dev(bda); tBTM_SEC_CB* p_cb = &btm_sec_cb; @@ -1387,8 +1356,7 @@ void btm_ble_ltk_request_reply(const RawAddress& bda, bool use_stk, } /* calculate LTK using peer device */ if (p_rec->sec_rec.ble_keys.key_type & BTM_LE_KEY_LENC) { - btsnd_hcic_ble_ltk_req_reply(btm_sec_cb.enc_handle, - p_rec->sec_rec.ble_keys.lltk); + btsnd_hcic_ble_ltk_req_reply(btm_sec_cb.enc_handle, p_rec->sec_rec.ble_keys.lltk); return; } @@ -1408,8 +1376,7 @@ void btm_ble_ltk_request_reply(const RawAddress& bda, bool use_stk, log::assert_that(p_rec->sec_rec.ble_keys.key_type & BTM_LE_KEY_LENC, "local enccryption key not present"); p_cb->key_size = p_rec->sec_rec.ble_keys.key_size; - btsnd_hcic_ble_ltk_req_reply(btm_sec_cb.enc_handle, - p_rec->sec_rec.ble_keys.lltk); + btsnd_hcic_ble_ltk_req_reply(btm_sec_cb.enc_handle, p_rec->sec_rec.ble_keys.lltk); } /******************************************************************************* @@ -1422,26 +1389,26 @@ void btm_ble_ltk_request_reply(const RawAddress& bda, bool use_stk, * Returns void * ******************************************************************************/ -static uint8_t btm_ble_io_capabilities_req(tBTM_SEC_DEV_REC* p_dev_rec, - tBTM_LE_IO_REQ* p_data) { +static uint8_t btm_ble_io_capabilities_req(tBTM_SEC_DEV_REC* p_dev_rec, tBTM_LE_IO_REQ* p_data) { uint8_t callback_rc = BTM_SUCCESS; log::verbose("p_dev_rec->bd_addr:{}", p_dev_rec->bd_addr); if (btm_sec_cb.api.p_le_callback) { /* the callback function implementation may change the IO capability... */ - callback_rc = (*btm_sec_cb.api.p_le_callback)( - BTM_LE_IO_REQ_EVT, p_dev_rec->bd_addr, (tBTM_LE_EVT_DATA*)p_data); + callback_rc = (*btm_sec_cb.api.p_le_callback)(BTM_LE_IO_REQ_EVT, p_dev_rec->bd_addr, + (tBTM_LE_EVT_DATA*)p_data); } if ((callback_rc == BTM_SUCCESS) || (BTM_OOB_UNKNOWN != p_data->oob_data)) { p_data->auth_req &= BTM_LE_AUTH_REQ_MASK; log::verbose("1:p_dev_rec->sec_rec.security_required={}, auth_req:{}", p_dev_rec->sec_rec.security_required, p_data->auth_req); - log::verbose("2:i_keys=0x{:x} r_keys=0x{:x} (bit 0-LTK 1-IRK 2-CSRK)", - p_data->init_keys, p_data->resp_keys); + log::verbose("2:i_keys=0x{:x} r_keys=0x{:x} (bit 0-LTK 1-IRK 2-CSRK)", p_data->init_keys, + p_data->resp_keys); /* if authentication requires MITM protection, put on the mask */ - if (p_dev_rec->sec_rec.security_required & BTM_SEC_IN_MITM) + if (p_dev_rec->sec_rec.security_required & BTM_SEC_IN_MITM) { p_data->auth_req |= BTM_LE_AUTH_REQ_MITM; + } if (!(p_data->auth_req & SMP_AUTH_BOND)) { log::verbose("Non bonding: No keys should be exchanged"); @@ -1450,29 +1417,27 @@ static uint8_t btm_ble_io_capabilities_req(tBTM_SEC_DEV_REC* p_dev_rec, } log::verbose("3:auth_req:{}", p_data->auth_req); - log::verbose("4:i_keys=0x{:x} r_keys=0x{:x}", p_data->init_keys, - p_data->resp_keys); + log::verbose("4:i_keys=0x{:x} r_keys=0x{:x}", p_data->init_keys, p_data->resp_keys); - log::verbose("5:p_data->io_cap={} auth_req:{}", p_data->io_cap, - p_data->auth_req); + log::verbose("5:p_data->io_cap={} auth_req:{}", p_data->io_cap, p_data->auth_req); /* remove MITM protection requirement if IO cap does not allow it */ - if ((p_data->io_cap == BTM_IO_CAP_NONE) && p_data->oob_data == SMP_OOB_NONE) + if ((p_data->io_cap == BTM_IO_CAP_NONE) && p_data->oob_data == SMP_OOB_NONE) { p_data->auth_req &= ~BTM_LE_AUTH_REQ_MITM; + } if (!(p_data->auth_req & SMP_SC_SUPPORT_BIT)) { /* if Secure Connections are not supported then remove LK derivation, ** and keypress notifications. */ - log::verbose( - "SC not supported -> No LK derivation, no keypress notifications"); + log::verbose("SC not supported -> No LK derivation, no keypress notifications"); p_data->auth_req &= ~SMP_KP_SUPPORT_BIT; p_data->init_keys &= ~SMP_SEC_KEY_TYPE_LK; p_data->resp_keys &= ~SMP_SEC_KEY_TYPE_LK; } - log::verbose("6:IO_CAP:{} oob_data:{} auth_req:0x{:02x}", p_data->io_cap, - p_data->oob_data, p_data->auth_req); + log::verbose("6:IO_CAP:{} oob_data:{} auth_req:0x{:02x}", p_data->io_cap, p_data->oob_data, + p_data->auth_req); } return callback_rc; } @@ -1487,17 +1452,16 @@ static uint8_t btm_ble_io_capabilities_req(tBTM_SEC_DEV_REC* p_dev_rec, * Returns void * ******************************************************************************/ -static uint8_t btm_ble_br_keys_req(tBTM_SEC_DEV_REC* p_dev_rec, - tBTM_LE_IO_REQ* p_data) { +static uint8_t btm_ble_br_keys_req(tBTM_SEC_DEV_REC* p_dev_rec, tBTM_LE_IO_REQ* p_data) { uint8_t callback_rc = BTM_SUCCESS; log::verbose("p_dev_rec->bd_addr:{}", p_dev_rec->bd_addr); *p_data = tBTM_LE_IO_REQ{ - .io_cap = BTM_IO_CAP_UNKNOWN, - .oob_data = false, - .auth_req = BTM_LE_AUTH_REQ_SC_MITM_BOND, - .max_key_size = BTM_BLE_MAX_KEY_SIZE, - .init_keys = SMP_BR_SEC_DEFAULT_KEY, - .resp_keys = SMP_BR_SEC_DEFAULT_KEY, + .io_cap = BTM_IO_CAP_UNKNOWN, + .oob_data = false, + .auth_req = BTM_LE_AUTH_REQ_SC_MITM_BOND, + .max_key_size = BTM_BLE_MAX_KEY_SIZE, + .init_keys = SMP_BR_SEC_DEFAULT_KEY, + .resp_keys = SMP_BR_SEC_DEFAULT_KEY, }; if (osi_property_get_bool(kPropertyCtkdDisableCsrkDistribution, false)) { @@ -1518,8 +1482,7 @@ static uint8_t btm_ble_br_keys_req(tBTM_SEC_DEV_REC* p_dev_rec, * Returns void * ******************************************************************************/ -void btm_ble_connected(const RawAddress& bda, uint16_t handle, - uint8_t /* enc_mode */, uint8_t role, +void btm_ble_connected(const RawAddress& bda, uint16_t handle, uint8_t /* enc_mode */, uint8_t role, tBLE_ADDR_TYPE addr_type, bool addr_matched, bool can_read_discoverable_characteristics) { tBTM_SEC_DEV_REC* p_dev_rec = btm_find_or_alloc_dev(bda); @@ -1528,11 +1491,11 @@ void btm_ble_connected(const RawAddress& bda, uint16_t handle, // TODO() Why is timestamp a counter ? p_dev_rec->timestamp = btm_sec_cb.dev_rec_count++; - if (is_ble_addr_type_known(addr_type)) + if (is_ble_addr_type_known(addr_type)) { p_dev_rec->ble.SetAddressType(addr_type); - else - log::warn( - "Please do not update device record from anonymous le advertisement"); + } else { + log::warn("Please do not update device record from anonymous le advertisement"); + } p_dev_rec->ble.pseudo_addr = bda; p_dev_rec->ble_hci_handle = handle; @@ -1570,8 +1533,7 @@ tBTM_STATUS btm_proc_smp_cback(tSMP_EVT event, const RawAddress& bd_addr, if (p_dev_rec != NULL) { switch (event) { case SMP_IO_CAP_REQ_EVT: - btm_ble_io_capabilities_req(p_dev_rec, - (tBTM_LE_IO_REQ*)&p_data->io_req); + btm_ble_io_capabilities_req(p_dev_rec, (tBTM_LE_IO_REQ*)&p_data->io_req); break; case SMP_BR_KEYS_REQ_EVT: @@ -1588,8 +1550,7 @@ tBTM_STATUS btm_proc_smp_cback(tSMP_EVT event, const RawAddress& bd_addr, case SMP_CONSENT_REQ_EVT: case SMP_SEC_REQUEST_EVT: - if (event == SMP_SEC_REQUEST_EVT && - btm_sec_cb.pairing_state != BTM_PAIR_STATE_IDLE) { + if (event == SMP_SEC_REQUEST_EVT && btm_sec_cb.pairing_state != BTM_PAIR_STATE_IDLE) { log::verbose("Ignoring SMP Security request"); break; } @@ -1604,10 +1565,9 @@ tBTM_STATUS btm_proc_smp_cback(tSMP_EVT event, const RawAddress& bd_addr, if (btm_sec_cb.api.p_le_callback) { /* the callback function implementation may change the IO * capability... */ - log::verbose("btm_sec_cb.api.p_le_callback=0x{}", - fmt::ptr(btm_sec_cb.api.p_le_callback)); - (*btm_sec_cb.api.p_le_callback)(static_cast(event), - bd_addr, (tBTM_LE_EVT_DATA*)p_data); + log::verbose("btm_sec_cb.api.p_le_callback=0x{}", fmt::ptr(btm_sec_cb.api.p_le_callback)); + (*btm_sec_cb.api.p_le_callback)(static_cast(event), bd_addr, + (tBTM_LE_EVT_DATA*)p_data); } if (event == SMP_COMPLT_EVT) { @@ -1616,18 +1576,15 @@ tBTM_STATUS btm_proc_smp_cback(tSMP_EVT event, const RawAddress& bd_addr, log::error("p_dev_rec is NULL"); return BTM_SUCCESS; } - log::verbose("before update sec_level=0x{:x} sec_flags=0x{:x}", - p_data->cmplt.sec_level, p_dev_rec->sec_rec.sec_flags); + log::verbose("before update sec_level=0x{:x} sec_flags=0x{:x}", p_data->cmplt.sec_level, + p_dev_rec->sec_rec.sec_flags); - res = (p_data->cmplt.reason == SMP_SUCCESS) ? BTM_SUCCESS - : BTM_ERR_PROCESSING; + res = (p_data->cmplt.reason == SMP_SUCCESS) ? BTM_SUCCESS : BTM_ERR_PROCESSING; - log::verbose( - "after update result={} sec_level=0x{:x} sec_flags=0x{:x}", res, - p_data->cmplt.sec_level, p_dev_rec->sec_rec.sec_flags); + log::verbose("after update result={} sec_level=0x{:x} sec_flags=0x{:x}", res, + p_data->cmplt.sec_level, p_dev_rec->sec_rec.sec_flags); - if (p_data->cmplt.is_pair_cancel && - btm_sec_cb.api.p_bond_cancel_cmpl_callback) { + if (p_data->cmplt.is_pair_cancel && btm_sec_cb.api.p_bond_cancel_cmpl_callback) { log::verbose("Pairing Cancel completed"); (*btm_sec_cb.api.p_bond_cancel_cmpl_callback)(BTM_SUCCESS); } @@ -1638,10 +1595,9 @@ tBTM_STATUS btm_proc_smp_cback(tSMP_EVT event, const RawAddress& bd_addr, } log::verbose( - "btm_sec_cb.pairing_state={:x} pairing_flags={:x} " - "pin_code_len={:x}", - btm_sec_cb.pairing_state, btm_sec_cb.pairing_flags, - btm_sec_cb.pin_code_len); + "btm_sec_cb.pairing_state={:x} pairing_flags={:x} " + "pin_code_len={:x}", + btm_sec_cb.pairing_state, btm_sec_cb.pairing_flags, btm_sec_cb.pin_code_len); /* Reset btm state only if the callback address matches pairing * address*/ @@ -1662,15 +1618,14 @@ tBTM_STATUS btm_proc_smp_cback(tSMP_EVT event, const RawAddress& bd_addr, // Reset the flags here if LE is not connected (over BR), // otherwise they would be reset on disconnected. log::debug( - "SMP over BR triggered by temporary bond has completed, " - "resetting the LK flags"); + "SMP over BR triggered by temporary bond has completed, " + "resetting the LK flags"); p_dev_rec->sec_rec.sec_flags &= ~(BTM_SEC_LE_LINK_KEY_KNOWN); p_dev_rec->sec_rec.ble_keys.key_type = BTM_LE_KEY_NONE; } } BD_NAME remote_name = {}; - if (BTM_GetRemoteDeviceName(p_dev_rec->ble.pseudo_addr, - remote_name) && + if (BTM_GetRemoteDeviceName(p_dev_rec->ble.pseudo_addr, remote_name) && interop_match_name(INTEROP_SUSPEND_ATT_TRAFFIC_DURING_PAIRING, (const char*)remote_name)) { log::debug("Notifying encryption cmpl delayed due to IOP match"); @@ -1683,10 +1638,9 @@ tBTM_STATUS btm_proc_smp_cback(tSMP_EVT event, const RawAddress& bd_addr, case SMP_LE_ADDR_ASSOC_EVT: if (btm_sec_cb.api.p_le_callback) { - log::verbose("btm_sec_cb.api.p_le_callback=0x{}", - fmt::ptr(btm_sec_cb.api.p_le_callback)); - (*btm_sec_cb.api.p_le_callback)(static_cast(event), - bd_addr, (tBTM_LE_EVT_DATA*)p_data); + log::verbose("btm_sec_cb.api.p_le_callback=0x{}", fmt::ptr(btm_sec_cb.api.p_le_callback)); + (*btm_sec_cb.api.p_le_callback)(static_cast(event), bd_addr, + (tBTM_LE_EVT_DATA*)p_data); } break; @@ -1704,8 +1658,7 @@ tBTM_STATUS btm_proc_smp_cback(tSMP_EVT event, const RawAddress& bd_addr, break; } } else { - log::warn("Unexpected event '{}' for unknown device.", - smp_evt_to_text(event)); + log::warn("Unexpected event '{}' for unknown device.", smp_evt_to_text(event)); } return BTM_SUCCESS; @@ -1727,8 +1680,8 @@ tBTM_STATUS btm_proc_smp_cback(tSMP_EVT event, const RawAddress& bd_addr, * Returns true if signing sucessul, otherwise false. * ******************************************************************************/ -bool BTM_BleDataSignature(const RawAddress& bd_addr, uint8_t* p_text, - uint16_t len, BLE_SIGNATURE signature) { +bool BTM_BleDataSignature(const RawAddress& bd_addr, uint8_t* p_text, uint16_t len, + BLE_SIGNATURE signature) { tBTM_SEC_DEV_REC* p_rec = btm_find_dev(bd_addr); if (p_rec == NULL) { @@ -1750,17 +1703,15 @@ bool BTM_BleDataSignature(const RawAddress& bd_addr, uint8_t* p_text, UINT32_TO_STREAM(pp, p_rec->sec_rec.ble_keys.local_counter); UINT32_TO_STREAM(p_mac, p_rec->sec_rec.ble_keys.local_counter); - crypto_toolbox::aes_cmac(p_rec->sec_rec.ble_keys.lcsrk, p_buf, - (uint16_t)(len + 4), BTM_CMAC_TLEN_SIZE, p_mac); + crypto_toolbox::aes_cmac(p_rec->sec_rec.ble_keys.lcsrk, p_buf, (uint16_t)(len + 4), + BTM_CMAC_TLEN_SIZE, p_mac); p_rec->sec_rec.increment_sign_counter(true); log::verbose("p_mac = {}", fmt::ptr(p_mac)); - log::verbose( - "p_mac[0]=0x{:02x} p_mac[1]=0x{:02x} p_mac[2]=0x{:02x} p_mac[3]=0x{:02x}", - *p_mac, *(p_mac + 1), *(p_mac + 2), *(p_mac + 3)); - log::verbose( - "p_mac[4]=0x{:02x} p_mac[5]=0x{:02x} p_mac[6]=0x{:02x} p_mac[7]=0x{:02x}", - *(p_mac + 4), *(p_mac + 5), *(p_mac + 6), *(p_mac + 7)); + log::verbose("p_mac[0]=0x{:02x} p_mac[1]=0x{:02x} p_mac[2]=0x{:02x} p_mac[3]=0x{:02x}", *p_mac, + *(p_mac + 1), *(p_mac + 2), *(p_mac + 3)); + log::verbose("p_mac[4]=0x{:02x} p_mac[5]=0x{:02x} p_mac[6]=0x{:02x} p_mac[7]=0x{:02x}", + *(p_mac + 4), *(p_mac + 5), *(p_mac + 6), *(p_mac + 7)); osi_free(p_buf); return true; } @@ -1780,25 +1731,22 @@ bool BTM_BleDataSignature(const RawAddress& bd_addr, uint8_t* p_text, * Returns true if signature verified correctly; otherwise false. * ******************************************************************************/ -bool BTM_BleVerifySignature(const RawAddress& bd_addr, uint8_t* p_orig, - uint16_t len, uint32_t counter, uint8_t* p_comp) { +bool BTM_BleVerifySignature(const RawAddress& bd_addr, uint8_t* p_orig, uint16_t len, + uint32_t counter, uint8_t* p_comp) { bool verified = false; tBTM_SEC_DEV_REC* p_rec = btm_find_dev(bd_addr); uint8_t p_mac[BTM_CMAC_TLEN_SIZE]; - if (p_rec == NULL || - (p_rec && !(p_rec->sec_rec.ble_keys.key_type & BTM_LE_KEY_PCSRK))) { + if (p_rec == NULL || (p_rec && !(p_rec->sec_rec.ble_keys.key_type & BTM_LE_KEY_PCSRK))) { log::error("can not verify signature for unknown device"); } else if (counter < p_rec->sec_rec.ble_keys.counter) { log::error("signature received with out dated sign counter"); } else if (p_orig == NULL) { log::error("No signature to verify"); } else { - log::verbose("rcv_cnt={} >= expected_cnt={}", counter, - p_rec->sec_rec.ble_keys.counter); + log::verbose("rcv_cnt={} >= expected_cnt={}", counter, p_rec->sec_rec.ble_keys.counter); - crypto_toolbox::aes_cmac(p_rec->sec_rec.ble_keys.pcsrk, p_orig, len, - BTM_CMAC_TLEN_SIZE, p_mac); + crypto_toolbox::aes_cmac(p_rec->sec_rec.ble_keys.pcsrk, p_orig, len, BTM_CMAC_TLEN_SIZE, p_mac); if (CRYPTO_memcmp(p_mac, p_comp, BTM_CMAC_TLEN_SIZE) == 0) { p_rec->sec_rec.increment_sign_counter(false); verified = true; @@ -1830,9 +1778,8 @@ void BTM_BleSirkConfirmDeviceReply(const RawAddress& bd_addr, uint8_t res) { return; } - BTM_LogHistory( - kBtmLogTag, bd_addr, "SIRK confirmation", - base::StringPrintf("status:%s", smp_status_text(res_smp).c_str())); + BTM_LogHistory(kBtmLogTag, bd_addr, "SIRK confirmation", + base::StringPrintf("status:%s", smp_status_text(res_smp).c_str())); SMP_SirkConfirmDeviceReply(bd_addr, res_smp); } @@ -1854,16 +1801,16 @@ static void btm_notify_new_key(uint8_t key_type) { case BTM_BLE_KEY_TYPE_ER: log::verbose("BTM_BLE_KEY_TYPE_ER"); - p_local_keys = - (tBTM_BLE_LOCAL_KEYS*)&btm_sec_cb.devcb.ble_encryption_key_value; + p_local_keys = (tBTM_BLE_LOCAL_KEYS*)&btm_sec_cb.devcb.ble_encryption_key_value; break; default: log::error("unknown key type: {}", key_type); break; } - if (p_local_keys != NULL) + if (p_local_keys != NULL) { (*btm_sec_cb.api.p_le_key_callback)(key_type, p_local_keys); + } } } @@ -1876,13 +1823,13 @@ static void btm_ble_reset_id_impl(const Octet16& rand1, const Octet16& rand2) { /* generate DHK= Eir({0x03, 0x00, 0x00 ...}) */ btm_sec_cb.devcb.id_keys.dhk = - crypto_toolbox::aes_128(btm_sec_cb.devcb.id_keys.ir, btm_ble_dhk_pt); + crypto_toolbox::aes_128(btm_sec_cb.devcb.id_keys.ir, btm_ble_dhk_pt); Octet16 btm_ble_irk_pt{}; btm_ble_irk_pt[0] = 0x01; /* IRK = D1(IR, 1) */ btm_sec_cb.devcb.id_keys.irk = - crypto_toolbox::aes_128(btm_sec_cb.devcb.id_keys.ir, btm_ble_irk_pt); + crypto_toolbox::aes_128(btm_sec_cb.devcb.id_keys.ir, btm_ble_irk_pt); btm_notify_new_key(BTM_BLE_KEY_TYPE_ID); @@ -1912,22 +1859,22 @@ void btm_ble_reset_id(void) { reset_id_data tmp; memcpy(tmp.rand1.data(), rand, BT_OCTET8_LEN); btsnd_hcic_ble_rand(base::Bind( - [](reset_id_data tmp, BT_OCTET8 rand) { - memcpy(tmp.rand1.data() + 8, rand, BT_OCTET8_LEN); - btsnd_hcic_ble_rand(base::Bind( - [](reset_id_data tmp, BT_OCTET8 rand) { - memcpy(tmp.rand2.data(), rand, BT_OCTET8_LEN); - btsnd_hcic_ble_rand(base::Bind( - [](reset_id_data tmp, BT_OCTET8 rand) { - memcpy(tmp.rand2.data() + 8, rand, BT_OCTET8_LEN); - // when all random numbers are ready, do the actual reset. - btm_ble_reset_id_impl(tmp.rand1, tmp.rand2); - }, - tmp)); - }, - tmp)); - }, - tmp)); + [](reset_id_data tmp, BT_OCTET8 rand) { + memcpy(tmp.rand1.data() + 8, rand, BT_OCTET8_LEN); + btsnd_hcic_ble_rand(base::Bind( + [](reset_id_data tmp, BT_OCTET8 rand) { + memcpy(tmp.rand2.data(), rand, BT_OCTET8_LEN); + btsnd_hcic_ble_rand(base::Bind( + [](reset_id_data tmp, BT_OCTET8 rand) { + memcpy(tmp.rand2.data() + 8, rand, BT_OCTET8_LEN); + // when all random numbers are ready, do the actual reset. + btm_ble_reset_id_impl(tmp.rand1, tmp.rand2); + }, + tmp)); + }, + tmp)); + }, + tmp)); })); } @@ -1945,8 +1892,7 @@ bool btm_ble_get_acl_remote_addr(uint16_t hci_handle, RawAddress& conn_addr, tBLE_ADDR_TYPE* p_addr_type) { tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev_by_handle(hci_handle); if (p_dev_rec == nullptr) { - log::warn("Unable to find security device record hci_handle:{}", - hci_handle); + log::warn("Unable to find security device record hci_handle:{}", hci_handle); // TODO Release acl resource return false; } @@ -2001,8 +1947,7 @@ bool BTM_BleIsLinkKeyKnown(const RawAddress address) { return p_dev_rec != nullptr && p_dev_rec->sec_rec.is_le_link_key_known(); } -std::optional BTM_BleGetIdentityAddress( - const RawAddress address) { +std::optional BTM_BleGetIdentityAddress(const RawAddress address) { tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(address); if (p_dev_rec == nullptr) { return std::nullopt; diff --git a/system/stack/btm/btm_ble_sec.h b/system/stack/btm/btm_ble_sec.h index fde20ea1f37..0351265162c 100644 --- a/system/stack/btm/btm_ble_sec.h +++ b/system/stack/btm/btm_ble_sec.h @@ -35,8 +35,7 @@ typedef enum : uint8_t { BTM_BLE_SEC_REQ_ACT_DISCARD = 3, } tBTM_BLE_SEC_REQ_ACT; -inline std::string btm_ble_sec_req_act_text( - const tBTM_BLE_SEC_REQ_ACT& action) { +inline std::string btm_ble_sec_req_act_text(const tBTM_BLE_SEC_REQ_ACT& action) { switch (action) { CASE_RETURN_TEXT(BTM_BLE_SEC_REQ_ACT_NONE); CASE_RETURN_TEXT(BTM_BLE_SEC_REQ_ACT_ENCRYPT); @@ -47,17 +46,14 @@ inline std::string btm_ble_sec_req_act_text( } } /* LE security function from btm_sec.cc */ -void btm_ble_link_sec_check(const RawAddress& bd_addr, - tBTM_LE_AUTH_REQ auth_req, +void btm_ble_link_sec_check(const RawAddress& bd_addr, tBTM_LE_AUTH_REQ auth_req, tBTM_BLE_SEC_REQ_ACT* p_sec_req_act); -void btm_ble_ltk_request_reply(const RawAddress& bda, bool use_stk, - const Octet16& stk); +void btm_ble_ltk_request_reply(const RawAddress& bda, bool use_stk, const Octet16& stk); tBTM_STATUS btm_proc_smp_cback(tSMP_EVT event, const RawAddress& bd_addr, const tSMP_EVT_DATA* p_data); -tBTM_STATUS btm_ble_set_encryption(const RawAddress& bd_addr, - tBTM_BLE_SEC_ACT sec_act, uint8_t link_role); -tBTM_STATUS btm_ble_start_encrypt(const RawAddress& bda, bool use_stk, - Octet16* p_stk); +tBTM_STATUS btm_ble_set_encryption(const RawAddress& bd_addr, tBTM_BLE_SEC_ACT sec_act, + uint8_t link_role); +tBTM_STATUS btm_ble_start_encrypt(const RawAddress& bda, bool use_stk, Octet16* p_stk); void btm_ble_link_encrypted(const RawAddress& bd_addr, uint8_t encr_enable); void btm_ble_reset_id(void); @@ -67,14 +63,11 @@ bool btm_ble_get_enc_key_type(const RawAddress& bd_addr, uint8_t* p_key_types); void btm_sec_save_le_key(const RawAddress& bd_addr, tBTM_LE_KEY_TYPE key_type, tBTM_LE_KEY_VALUE* p_keys, bool pass_to_application); -void btm_ble_update_sec_key_size(const RawAddress& bd_addr, - uint8_t enc_key_size); +void btm_ble_update_sec_key_size(const RawAddress& bd_addr, uint8_t enc_key_size); uint8_t btm_ble_read_sec_key_size(const RawAddress& bd_addr); -tBTM_STATUS btm_ble_start_sec_check(const RawAddress& bd_addr, uint16_t psm, - bool is_originator, - tBTM_SEC_CALLBACK* p_callback, - void* p_ref_data); +tBTM_STATUS btm_ble_start_sec_check(const RawAddress& bd_addr, uint16_t psm, bool is_originator, + tBTM_SEC_CALLBACK* p_callback, void* p_ref_data); namespace fmt { template <> diff --git a/system/stack/btm/btm_client_interface.cc b/system/stack/btm/btm_client_interface.cc index 648a51cf893..d65cdb1d8b8 100644 --- a/system/stack/btm/btm_client_interface.cc +++ b/system/stack/btm/btm_client_interface.cc @@ -24,119 +24,114 @@ #include "stack/include/btm_ble_api.h" struct btm_client_interface_t btm_client_interface = { - .lifecycle = - { - .BTM_PmRegister = ::BTM_PmRegister, - .ACL_RegisterClient = ::ACL_RegisterClient, - .ACL_UnregisterClient = ::ACL_UnregisterClient, - .btm_init = ::btm_init, - .btm_free = ::btm_free, - .btm_ble_init = ::btm_ble_init, - .btm_ble_free = ::btm_ble_free, - .BTM_reset_complete = ::BTM_reset_complete, - }, + .lifecycle = + { + .BTM_PmRegister = ::BTM_PmRegister, + .ACL_RegisterClient = ::ACL_RegisterClient, + .ACL_UnregisterClient = ::ACL_UnregisterClient, + .btm_init = ::btm_init, + .btm_free = ::btm_free, + .btm_ble_init = ::btm_ble_init, + .btm_ble_free = ::btm_ble_free, + .BTM_reset_complete = ::BTM_reset_complete, + }, - // Acl peer and lifecycle - .peer = - { - .BTM_IsAclConnectionUp = ::BTM_IsAclConnectionUp, - .BTM_ReadConnectedTransportAddress = - ::BTM_ReadConnectedTransportAddress, - .BTM_CancelRemoteDeviceName = ::BTM_CancelRemoteDeviceName, - .BTM_ReadRemoteDeviceName = ::BTM_ReadRemoteDeviceName, - .BTM_ReadRemoteFeatures = ::BTM_ReadRemoteFeatures, - .BTM_ReadDevInfo = ::BTM_ReadDevInfo, - .BTM_GetMaxPacketSize = ::BTM_GetMaxPacketSize, - .BTM_ReadRemoteVersion = ::BTM_ReadRemoteVersion, - .BTM_GetPeerDeviceTypeFromFeatures = - ::BTM_GetPeerDeviceTypeFromFeatures, - .BTM_RequestPeerSCA = ::BTM_RequestPeerSCA, - .BTM_GetPeerSCA = ::BTM_GetPeerSCA, - .BTM_IsPhy2mSupported = ::BTM_IsPhy2mSupported, - .BTM_GetHCIConnHandle = ::BTM_GetHCIConnHandle, - }, + // Acl peer and lifecycle + .peer = + { + .BTM_IsAclConnectionUp = ::BTM_IsAclConnectionUp, + .BTM_ReadConnectedTransportAddress = ::BTM_ReadConnectedTransportAddress, + .BTM_CancelRemoteDeviceName = ::BTM_CancelRemoteDeviceName, + .BTM_ReadRemoteDeviceName = ::BTM_ReadRemoteDeviceName, + .BTM_ReadRemoteFeatures = ::BTM_ReadRemoteFeatures, + .BTM_ReadDevInfo = ::BTM_ReadDevInfo, + .BTM_GetMaxPacketSize = ::BTM_GetMaxPacketSize, + .BTM_ReadRemoteVersion = ::BTM_ReadRemoteVersion, + .BTM_GetPeerDeviceTypeFromFeatures = ::BTM_GetPeerDeviceTypeFromFeatures, + .BTM_RequestPeerSCA = ::BTM_RequestPeerSCA, + .BTM_GetPeerSCA = ::BTM_GetPeerSCA, + .BTM_IsPhy2mSupported = ::BTM_IsPhy2mSupported, + .BTM_GetHCIConnHandle = ::BTM_GetHCIConnHandle, + }, - .link_policy = - { - .BTM_GetRole = ::BTM_GetRole, - .BTM_SetPowerMode = ::BTM_SetPowerMode, - .BTM_SetSsrParams = ::BTM_SetSsrParams, - .BTM_SwitchRoleToCentral = ::BTM_SwitchRoleToCentral, - .BTM_block_role_switch_for = ::BTM_block_role_switch_for, - .BTM_block_sniff_mode_for = ::BTM_block_sniff_mode_for, - .BTM_default_unblock_role_switch = - ::BTM_default_unblock_role_switch, - .BTM_unblock_role_switch_for = ::BTM_unblock_role_switch_for, - .BTM_unblock_sniff_mode_for = ::BTM_unblock_sniff_mode_for, - .BTM_WritePageTimeout = ::BTM_WritePageTimeout, - }, + .link_policy = + { + .BTM_GetRole = ::BTM_GetRole, + .BTM_SetPowerMode = ::BTM_SetPowerMode, + .BTM_SetSsrParams = ::BTM_SetSsrParams, + .BTM_SwitchRoleToCentral = ::BTM_SwitchRoleToCentral, + .BTM_block_role_switch_for = ::BTM_block_role_switch_for, + .BTM_block_sniff_mode_for = ::BTM_block_sniff_mode_for, + .BTM_default_unblock_role_switch = ::BTM_default_unblock_role_switch, + .BTM_unblock_role_switch_for = ::BTM_unblock_role_switch_for, + .BTM_unblock_sniff_mode_for = ::BTM_unblock_sniff_mode_for, + .BTM_WritePageTimeout = ::BTM_WritePageTimeout, + }, - .link_controller = - { - .BTM_GetLinkSuperTout = ::BTM_GetLinkSuperTout, - .BTM_ReadRSSI = ::BTM_ReadRSSI, - }, + .link_controller = + { + .BTM_GetLinkSuperTout = ::BTM_GetLinkSuperTout, + .BTM_ReadRSSI = ::BTM_ReadRSSI, + }, - .security = get_security_client_interface(), + .security = get_security_client_interface(), - .ble = - { - .BTM_BleGetEnergyInfo = ::BTM_BleGetEnergyInfo, - .BTM_BleObserve = ::BTM_BleObserve, - .BTM_SetBleDataLength = ::BTM_SetBleDataLength, - .BTM_BleReadControllerFeatures = ::BTM_BleReadControllerFeatures, - .BTM_BleSetPhy = ::BTM_BleSetPhy, - .BTM_BleSetPrefConnParams = ::BTM_BleSetPrefConnParams, - .BTM_UseLeLink = ::BTM_UseLeLink, - .BTM_IsRemoteVersionReceived = ::BTM_IsRemoteVersionReceived, - .BTM_SetConsolidationCallback = ::BTM_SetConsolidationCallback, - }, + .ble = + { + .BTM_BleGetEnergyInfo = ::BTM_BleGetEnergyInfo, + .BTM_BleObserve = ::BTM_BleObserve, + .BTM_SetBleDataLength = ::BTM_SetBleDataLength, + .BTM_BleReadControllerFeatures = ::BTM_BleReadControllerFeatures, + .BTM_BleSetPhy = ::BTM_BleSetPhy, + .BTM_BleSetPrefConnParams = ::BTM_BleSetPrefConnParams, + .BTM_UseLeLink = ::BTM_UseLeLink, + .BTM_IsRemoteVersionReceived = ::BTM_IsRemoteVersionReceived, + .BTM_SetConsolidationCallback = ::BTM_SetConsolidationCallback, + }, - .sco = - { - .BTM_CreateSco = ::BTM_CreateSco, - .BTM_RegForEScoEvts = ::BTM_RegForEScoEvts, - .BTM_RemoveSco = ::BTM_RemoveSco, - .BTM_WriteVoiceSettings = ::BTM_WriteVoiceSettings, - .BTM_EScoConnRsp = ::BTM_EScoConnRsp, - .BTM_GetNumScoLinks = ::BTM_GetNumScoLinks, - .BTM_SetEScoMode = ::BTM_SetEScoMode, - .BTM_GetScoDebugDump = ::BTM_GetScoDebugDump, - .BTM_IsScoActiveByBdaddr = ::BTM_IsScoActiveByBdaddr, - }, + .sco = + { + .BTM_CreateSco = ::BTM_CreateSco, + .BTM_RegForEScoEvts = ::BTM_RegForEScoEvts, + .BTM_RemoveSco = ::BTM_RemoveSco, + .BTM_WriteVoiceSettings = ::BTM_WriteVoiceSettings, + .BTM_EScoConnRsp = ::BTM_EScoConnRsp, + .BTM_GetNumScoLinks = ::BTM_GetNumScoLinks, + .BTM_SetEScoMode = ::BTM_SetEScoMode, + .BTM_GetScoDebugDump = ::BTM_GetScoDebugDump, + .BTM_IsScoActiveByBdaddr = ::BTM_IsScoActiveByBdaddr, + }, - .local = - { - .BTM_ReadLocalDeviceName = ::BTM_ReadLocalDeviceName, - .BTM_ReadLocalDeviceNameFromController = - ::BTM_ReadLocalDeviceNameFromController, - .BTM_SetLocalDeviceName = ::BTM_SetLocalDeviceName, - .BTM_SetDeviceClass = ::BTM_SetDeviceClass, - .BTM_IsDeviceUp = ::BTM_IsDeviceUp, - .BTM_ReadDeviceClass = ::BTM_ReadDeviceClass, - }, + .local = + { + .BTM_ReadLocalDeviceName = ::BTM_ReadLocalDeviceName, + .BTM_ReadLocalDeviceNameFromController = + ::BTM_ReadLocalDeviceNameFromController, + .BTM_SetLocalDeviceName = ::BTM_SetLocalDeviceName, + .BTM_SetDeviceClass = ::BTM_SetDeviceClass, + .BTM_IsDeviceUp = ::BTM_IsDeviceUp, + .BTM_ReadDeviceClass = ::BTM_ReadDeviceClass, + }, - .eir = - { - .BTM_WriteEIR = ::BTM_WriteEIR, - .BTM_GetEirSupportedServices = ::BTM_GetEirSupportedServices, - .BTM_GetEirUuidList = ::BTM_GetEirUuidList, - .BTM_AddEirService = ::BTM_AddEirService, - .BTM_RemoveEirService = ::BTM_RemoveEirService, - }, - .db = - { - .BTM_InqDbRead = ::BTM_InqDbRead, - .BTM_InqDbFirst = ::BTM_InqDbFirst, - .BTM_InqDbNext = ::BTM_InqDbNext, - .BTM_ClearInqDb = ::BTM_ClearInqDb, - }, - .vendor = - { - .BTM_VendorSpecificCommand = ::BTM_VendorSpecificCommand, - }, + .eir = + { + .BTM_WriteEIR = ::BTM_WriteEIR, + .BTM_GetEirSupportedServices = ::BTM_GetEirSupportedServices, + .BTM_GetEirUuidList = ::BTM_GetEirUuidList, + .BTM_AddEirService = ::BTM_AddEirService, + .BTM_RemoveEirService = ::BTM_RemoveEirService, + }, + .db = + { + .BTM_InqDbRead = ::BTM_InqDbRead, + .BTM_InqDbFirst = ::BTM_InqDbFirst, + .BTM_InqDbNext = ::BTM_InqDbNext, + .BTM_ClearInqDb = ::BTM_ClearInqDb, + }, + .vendor = + { + .BTM_VendorSpecificCommand = ::BTM_VendorSpecificCommand, + }, }; -struct btm_client_interface_t& get_btm_client_interface() { - return btm_client_interface; -} +struct btm_client_interface_t& get_btm_client_interface() { return btm_client_interface; } diff --git a/system/stack/btm/btm_dev.cc b/system/stack/btm/btm_dev.cc index c47d2932cf3..bf60acfbd5e 100644 --- a/system/stack/btm/btm_dev.cc +++ b/system/stack/btm/btm_dev.cc @@ -80,15 +80,15 @@ static void wipe_secrets_and_remove(tBTM_SEC_DEV_REC* p_dev_rec) { * Returns void * ******************************************************************************/ -void BTM_SecAddDevice(const RawAddress& bd_addr, DEV_CLASS dev_class, - LinkKey link_key, uint8_t key_type, uint8_t pin_length) { +void BTM_SecAddDevice(const RawAddress& bd_addr, DEV_CLASS dev_class, LinkKey link_key, + uint8_t key_type, uint8_t pin_length) { tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr); if (!p_dev_rec) { p_dev_rec = btm_sec_allocate_dev_rec(); log::info( - "Caching new record from config file device: {}, dev_class: 0x{:02x}, " - "link_key_type: 0x{:x}", - bd_addr, fmt::join(dev_class, ""), key_type); + "Caching new record from config file device: {}, dev_class: 0x{:02x}, " + "link_key_type: 0x{:x}", + bd_addr, fmt::join(dev_class, ""), key_type); p_dev_rec->bd_addr = bd_addr; p_dev_rec->hci_handle = @@ -99,9 +99,9 @@ void BTM_SecAddDevice(const RawAddress& bd_addr, DEV_CLASS dev_class, memset(&p_dev_rec->conn_params, 0xff, sizeof(tBTM_LE_CONN_PRAMS)); } else { log::info( - "Caching existing record from config file device: {}, dev_class: " - "0x{:02x}, link_key_type: 0x{:x}", - bd_addr, fmt::join(dev_class, ""), key_type); + "Caching existing record from config file device: {}, dev_class: " + "0x{:02x}, link_key_type: 0x{:x}", + bd_addr, fmt::join(dev_class, ""), key_type); /* "Bump" timestamp for existing record */ p_dev_rec->timestamp = btm_sec_cb.dev_rec_count++; @@ -115,7 +115,9 @@ void BTM_SecAddDevice(const RawAddress& bd_addr, DEV_CLASS dev_class, p_dev_rec->sec_rec.bond_type = BOND_TYPE_UNKNOWN; } - if (dev_class != kDevClassEmpty) p_dev_rec->dev_class = dev_class; + if (dev_class != kDevClassEmpty) { + p_dev_rec->dev_class = dev_class; + } memset(p_dev_rec->sec_bd_name, 0, sizeof(BD_NAME)); @@ -130,8 +132,7 @@ void BTM_SecAddDevice(const RawAddress& bd_addr, DEV_CLASS dev_class, key_type == BTM_LKEY_TYPE_AUTH_COMB_P_256) { // Set the flag if the link key was made by using either a 16 digit // pin or MITM. - p_dev_rec->sec_rec.sec_flags |= - BTM_SEC_16_DIGIT_PIN_AUTHED | BTM_SEC_LINK_KEY_AUTHED; + p_dev_rec->sec_rec.sec_flags |= BTM_SEC_16_DIGIT_PIN_AUTHED | BTM_SEC_LINK_KEY_AUTHED; } p_dev_rec->sec_rec.rmt_io_caps = BTM_IO_CAP_OUT; @@ -170,12 +171,9 @@ bool BTM_SecDeleteDevice(const RawAddress& bd_addr) { RawAddress bda = p_dev_rec->bd_addr; - log::info("Remove device {} from filter accept list before delete record", - bd_addr); - if (bluetooth::common::init_flags:: - use_unified_connection_manager_is_enabled()) { - bluetooth::connection::GetConnectionManager() - .stop_all_connections_to_device( + log::info("Remove device {} from filter accept list before delete record", bd_addr); + if (bluetooth::common::init_flags::use_unified_connection_manager_is_enabled()) { + bluetooth::connection::GetConnectionManager().stop_all_connections_to_device( bluetooth::connection::ResolveRawAddress(p_dev_rec->bd_addr)); } else { BTM_AcceptlistRemove(p_dev_rec->bd_addr); @@ -190,10 +188,10 @@ bool BTM_SecDeleteDevice(const RawAddress& bd_addr) { /* Tell controller to get rid of the link key, if it has one stored */ BTM_DeleteStoredLinkKey(&bda, NULL); log::info("{} complete", bd_addr); - BTM_LogHistory(kBtmLogTag, bd_addr, "Device removed", - base::StringPrintf("device_type:%s bond_type:%s", - DeviceTypeText(device_type).c_str(), - bond_type_text(bond_type).c_str())); + BTM_LogHistory( + kBtmLogTag, bd_addr, "Device removed", + base::StringPrintf("device_type:%s bond_type:%s", DeviceTypeText(device_type).c_str(), + bond_type_text(bond_type).c_str())); return true; } @@ -208,7 +206,9 @@ bool BTM_SecDeleteDevice(const RawAddress& bd_addr) { ******************************************************************************/ void BTM_SecClearSecurityFlags(const RawAddress& bd_addr) { tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr); - if (p_dev_rec == NULL) return; + if (p_dev_rec == NULL) { + return; + } p_dev_rec->sec_rec.sec_flags = 0; p_dev_rec->sec_rec.sec_state = tSECURITY_STATE::IDLE; @@ -230,9 +230,11 @@ const char* BTM_SecReadDevName(const RawAddress& bd_addr) { const tBTM_SEC_DEV_REC* p_srec; p_srec = btm_find_dev(bd_addr); - if (p_srec != NULL) p_name = (const char*)p_srec->sec_bd_name; + if (p_srec != NULL) { + p_name = (const char*)p_srec->sec_bd_name; + } - return (p_name); + return p_name; } /******************************************************************************* @@ -260,14 +262,15 @@ tBTM_SEC_DEV_REC* btm_sec_alloc_dev(const RawAddress& bd_addr) { p_dev_rec->dev_class = p_inq_info->results.dev_class; p_dev_rec->device_type = p_inq_info->results.device_type; - if (is_ble_addr_type_known(p_inq_info->results.ble_addr_type)) + if (is_ble_addr_type_known(p_inq_info->results.ble_addr_type)) { p_dev_rec->ble.SetAddressType(p_inq_info->results.ble_addr_type); - else - log::warn( - "Please do not update device record from anonymous le advertisement"); + } else { + log::warn("Please do not update device record from anonymous le advertisement"); + } - } else if (bd_addr == btm_sec_cb.connecting_bda) + } else if (bd_addr == btm_sec_cb.connecting_bda) { p_dev_rec->dev_class = btm_sec_cb.connecting_dc; + } /* update conn params, use default value for background connection params */ memset(&p_dev_rec->conn_params, 0xff, sizeof(tBTM_LE_CONN_PRAMS)); @@ -279,15 +282,16 @@ tBTM_SEC_DEV_REC* btm_sec_alloc_dev(const RawAddress& bd_addr) { p_dev_rec->hci_handle = get_btm_client_interface().peer.BTM_GetHCIConnHandle(bd_addr, BT_TRANSPORT_BR_EDR); - return (p_dev_rec); + return p_dev_rec; } static bool is_handle_equal(void* data, void* context) { tBTM_SEC_DEV_REC* p_dev_rec = static_cast(data); uint16_t* handle = static_cast(context); - if (p_dev_rec->hci_handle == *handle || p_dev_rec->ble_hci_handle == *handle) + if (p_dev_rec->hci_handle == *handle || p_dev_rec->ble_hci_handle == *handle) { return false; + } return true; } @@ -303,11 +307,14 @@ static bool is_handle_equal(void* data, void* context) { * ******************************************************************************/ tBTM_SEC_DEV_REC* btm_find_dev_by_handle(uint16_t handle) { - if (btm_sec_cb.sec_dev_rec == nullptr) return nullptr; + if (btm_sec_cb.sec_dev_rec == nullptr) { + return nullptr; + } - list_node_t* n = - list_foreach(btm_sec_cb.sec_dev_rec, is_handle_equal, &handle); - if (n) return static_cast(list_node(n)); + list_node_t* n = list_foreach(btm_sec_cb.sec_dev_rec, is_handle_equal, &handle); + if (n) { + return static_cast(list_node(n)); + } return NULL; } @@ -316,11 +323,17 @@ static bool is_address_equal(void* data, void* context) { tBTM_SEC_DEV_REC* p_dev_rec = static_cast(data); const RawAddress* bd_addr = ((RawAddress*)context); - if (p_dev_rec->bd_addr == *bd_addr) return false; + if (p_dev_rec->bd_addr == *bd_addr) { + return false; + } // If a LE random address is looking for device record - if (p_dev_rec->ble.pseudo_addr == *bd_addr) return false; + if (p_dev_rec->ble.pseudo_addr == *bd_addr) { + return false; + } - if (btm_ble_addr_resolvable(*bd_addr, p_dev_rec)) return false; + if (btm_ble_addr_resolvable(*bd_addr, p_dev_rec)) { + return false; + } return true; } @@ -335,18 +348,23 @@ static bool is_address_equal(void* data, void* context) { * ******************************************************************************/ tBTM_SEC_DEV_REC* btm_find_dev(const RawAddress& bd_addr) { - if (btm_sec_cb.sec_dev_rec == nullptr) return nullptr; + if (btm_sec_cb.sec_dev_rec == nullptr) { + return nullptr; + } - list_node_t* n = - list_foreach(btm_sec_cb.sec_dev_rec, is_address_equal, (void*)&bd_addr); - if (n) return static_cast(list_node(n)); + list_node_t* n = list_foreach(btm_sec_cb.sec_dev_rec, is_address_equal, (void*)&bd_addr); + if (n) { + return static_cast(list_node(n)); + } return NULL; } static bool has_lenc_and_address_is_equal(void* data, void* context) { tBTM_SEC_DEV_REC* p_dev_rec = static_cast(data); - if (!(p_dev_rec->sec_rec.ble_keys.key_type & BTM_LE_KEY_LENC)) return true; + if (!(p_dev_rec->sec_rec.ble_keys.key_type & BTM_LE_KEY_LENC)) { + return true; + } return is_address_equal(data, context); } @@ -362,11 +380,15 @@ static bool has_lenc_and_address_is_equal(void* data, void* context) { * ******************************************************************************/ tBTM_SEC_DEV_REC* btm_find_dev_with_lenc(const RawAddress& bd_addr) { - if (btm_sec_cb.sec_dev_rec == nullptr) return nullptr; + if (btm_sec_cb.sec_dev_rec == nullptr) { + return nullptr; + } - list_node_t* n = list_foreach(btm_sec_cb.sec_dev_rec, - has_lenc_and_address_is_equal, (void*)&bd_addr); - if (n) return static_cast(list_node(n)); + list_node_t* n = + list_foreach(btm_sec_cb.sec_dev_rec, has_lenc_and_address_is_equal, (void*)&bd_addr); + if (n) { + return static_cast(list_node(n)); + } return NULL; } @@ -387,13 +409,14 @@ void btm_consolidate_dev(tBTM_SEC_DEV_REC* p_target_rec) { list_node_t* end = list_end(btm_sec_cb.sec_dev_rec); list_node_t* node = list_begin(btm_sec_cb.sec_dev_rec); while (node != end) { - tBTM_SEC_DEV_REC* p_dev_rec = - static_cast(list_node(node)); + tBTM_SEC_DEV_REC* p_dev_rec = static_cast(list_node(node)); // we do list_remove in some cases, must grab next before removing node = list_next(node); - if (p_target_rec == p_dev_rec) continue; + if (p_target_rec == p_dev_rec) { + continue; + } if (p_dev_rec->bd_addr == p_target_rec->bd_addr) { memcpy(p_target_rec, p_dev_rec, sizeof(tBTM_SEC_DEV_REC)); @@ -406,7 +429,7 @@ void btm_consolidate_dev(tBTM_SEC_DEV_REC* p_target_rec) { p_target_rec->sec_rec.sec_flags |= temp_rec.sec_rec.sec_flags; p_target_rec->sec_rec.new_encryption_key_is_p256 = - temp_rec.sec_rec.new_encryption_key_is_p256; + temp_rec.sec_rec.new_encryption_key_is_p256; p_target_rec->sec_rec.bond_type = temp_rec.sec_rec.bond_type; /* remove the combined record */ @@ -430,9 +453,7 @@ void btm_consolidate_dev(tBTM_SEC_DEV_REC* p_target_rec) { static BTM_CONSOLIDATION_CB* btm_consolidate_cb = nullptr; -void BTM_SetConsolidationCallback(BTM_CONSOLIDATION_CB* cb) { - btm_consolidate_cb = cb; -} +void BTM_SetConsolidationCallback(BTM_CONSOLIDATION_CB* cb) { btm_consolidate_cb = cb; } /* combine security records of established LE connections after Classic pairing * succeeded. */ @@ -453,27 +474,27 @@ void btm_dev_consolidate_existing_connections(const RawAddress& bd_addr) { list_node_t* end = list_end(btm_sec_cb.sec_dev_rec); list_node_t* node = list_begin(btm_sec_cb.sec_dev_rec); while (node != end) { - tBTM_SEC_DEV_REC* p_dev_rec = - static_cast(list_node(node)); + tBTM_SEC_DEV_REC* p_dev_rec = static_cast(list_node(node)); // we do list_remove in some cases, must grab next before removing node = list_next(node); - if (p_target_rec == p_dev_rec) continue; + if (p_target_rec == p_dev_rec) { + continue; + } /* an RPA device entry is a duplicate of the target record */ if (btm_ble_addr_resolvable(p_dev_rec->bd_addr, p_target_rec)) { if (p_dev_rec->ble_hci_handle == HCI_INVALID_HANDLE) { - log::info("already disconnected - erasing entry {}", - p_dev_rec->bd_addr); + log::info("already disconnected - erasing entry {}", p_dev_rec->bd_addr); wipe_secrets_and_remove(p_dev_rec); continue; } log::info( - "Found existing LE connection to just bonded device on {} handle " - "0x{:04x}", - p_dev_rec->bd_addr, p_dev_rec->ble_hci_handle); + "Found existing LE connection to just bonded device on {} handle " + "0x{:04x}", + p_dev_rec->bd_addr, p_dev_rec->ble_hci_handle); RawAddress ble_conn_addr = p_dev_rec->bd_addr; p_target_rec->ble_hci_handle = p_dev_rec->ble_hci_handle; @@ -484,14 +505,15 @@ void btm_dev_consolidate_existing_connections(const RawAddress& bd_addr) { btm_acl_consolidate(bd_addr, ble_conn_addr); L2CA_Consolidate(bd_addr, ble_conn_addr); gatt_consolidate(bd_addr, ble_conn_addr); - if (btm_consolidate_cb) btm_consolidate_cb(bd_addr, ble_conn_addr); + if (btm_consolidate_cb) { + btm_consolidate_cb(bd_addr, ble_conn_addr); + } /* To avoid race conditions between central/peripheral starting encryption * at same time, initiate it just from central. */ if (L2CA_GetBleConnRole(ble_conn_addr) == HCI_ROLE_CENTRAL) { log::info("Will encrypt existing connection"); - BTM_SetEncryption(bd_addr, BT_TRANSPORT_LE, nullptr, nullptr, - BTM_BLE_SEC_ENCRYPT); + BTM_SetEncryption(bd_addr, BT_TRANSPORT_LE, nullptr, nullptr, BTM_BLE_SEC_ENCRYPT); } } } @@ -516,7 +538,7 @@ tBTM_SEC_DEV_REC* btm_find_or_alloc_dev(const RawAddress& bd_addr) { /* Allocate a new device record or reuse the oldest one */ p_dev_rec = btm_sec_alloc_dev(bd_addr); } - return (p_dev_rec); + return p_dev_rec; } /******************************************************************************* @@ -539,11 +561,10 @@ static tBTM_SEC_DEV_REC* btm_find_oldest_dev_rec(void) { list_node_t* end = list_end(btm_sec_cb.sec_dev_rec); for (list_node_t* node = list_begin(btm_sec_cb.sec_dev_rec); node != end; node = list_next(node)) { - tBTM_SEC_DEV_REC* p_dev_rec = - static_cast(list_node(node)); + tBTM_SEC_DEV_REC* p_dev_rec = static_cast(list_node(node)); - if ((p_dev_rec->sec_rec.sec_flags & - (BTM_SEC_LINK_KEY_KNOWN | BTM_SEC_LE_LINK_KEY_KNOWN)) == 0) { + if ((p_dev_rec->sec_rec.sec_flags & (BTM_SEC_LINK_KEY_KNOWN | BTM_SEC_LE_LINK_KEY_KNOWN)) == + 0) { // Device is not paired if (p_dev_rec->timestamp < ts_oldest) { p_oldest = p_dev_rec; @@ -559,7 +580,9 @@ static tBTM_SEC_DEV_REC* btm_find_oldest_dev_rec(void) { } // If we did not find any non-paired devices, use the oldest paired one... - if (ts_oldest == 0xFFFFFFFF) p_oldest = p_oldest_paired; + if (ts_oldest == 0xFFFFFFFF) { + p_oldest = p_oldest_paired; + } return p_oldest; } @@ -580,8 +603,7 @@ tBTM_SEC_DEV_REC* btm_sec_allocate_dev_rec(void) { tBTM_SEC_DEV_REC* p_dev_rec = NULL; if (btm_sec_cb.sec_dev_rec == nullptr) { - log::warn( - "Unable to allocate device record with destructed device record list"); + log::warn("Unable to allocate device record with destructed device record list"); return nullptr; } @@ -590,8 +612,7 @@ tBTM_SEC_DEV_REC* btm_sec_allocate_dev_rec(void) { wipe_secrets_and_remove(p_dev_rec); } - p_dev_rec = - static_cast(osi_calloc(sizeof(tBTM_SEC_DEV_REC))); + p_dev_rec = static_cast(osi_calloc(sizeof(tBTM_SEC_DEV_REC))); list_append(btm_sec_cb.sec_dev_rec, p_dev_rec); // Initialize defaults @@ -617,7 +638,9 @@ tBTM_SEC_DEV_REC* btm_sec_allocate_dev_rec(void) { tBTM_BOND_TYPE btm_get_bond_type_dev(const RawAddress& bd_addr) { tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr); - if (p_dev_rec == NULL) return BOND_TYPE_UNKNOWN; + if (p_dev_rec == NULL) { + return BOND_TYPE_UNKNOWN; + } return p_dev_rec->sec_rec.bond_type; } @@ -632,11 +655,12 @@ tBTM_BOND_TYPE btm_get_bond_type_dev(const RawAddress& bd_addr) { * Returns true on success, otherwise false * ******************************************************************************/ -bool btm_set_bond_type_dev(const RawAddress& bd_addr, - tBTM_BOND_TYPE bond_type) { +bool btm_set_bond_type_dev(const RawAddress& bd_addr, tBTM_BOND_TYPE bond_type) { tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr); - if (p_dev_rec == NULL) return false; + if (p_dev_rec == NULL) { + return false; + } p_dev_rec->sec_rec.bond_type = bond_type; return true; @@ -658,8 +682,7 @@ std::vector btm_get_sec_dev_rec() { list_node_t* end = list_end(btm_sec_cb.sec_dev_rec); for (list_node_t* node = list_begin(btm_sec_cb.sec_dev_rec); node != end; node = list_next(node)) { - tBTM_SEC_DEV_REC* p_dev_rec = - static_cast(list_node(node)); + tBTM_SEC_DEV_REC* p_dev_rec = static_cast(list_node(node)); result.push_back(p_dev_rec); } } @@ -702,13 +725,11 @@ bool BTM_Sec_AddressKnown(const RawAddress& address) { } // Public address, Random Static, or Random Non-Resolvable Address known - if (p_dev_rec->ble.AddressType() == BLE_ADDR_PUBLIC || - !BTM_BLE_IS_RESOLVE_BDA(address)) { + if (p_dev_rec->ble.AddressType() == BLE_ADDR_PUBLIC || !BTM_BLE_IS_RESOLVE_BDA(address)) { return true; } - log::warn("{}, the address type is 0x{:02x}", address, - p_dev_rec->ble.AddressType()); + log::warn("{}, the address type is 0x{:02x}", address, p_dev_rec->ble.AddressType()); // Only Resolvable Private Address (RPA) is known, we don't allow it into // the background connection procedure. @@ -719,15 +740,15 @@ const tBLE_BD_ADDR BTM_Sec_GetAddressWithType(const RawAddress& bd_addr) { tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr); if (p_dev_rec == nullptr || !p_dev_rec->is_device_type_has_ble()) { return { - .type = BLE_ADDR_PUBLIC, - .bda = bd_addr, + .type = BLE_ADDR_PUBLIC, + .bda = bd_addr, }; } if (p_dev_rec->ble.identity_address_with_type.bda.IsEmpty()) { return { - .type = p_dev_rec->ble.AddressType(), - .bda = bd_addr, + .type = p_dev_rec->ble.AddressType(), + .bda = bd_addr, }; } else { // Floss doesn't support LL Privacy (yet). To expedite ARC testing, always @@ -738,8 +759,8 @@ const tBLE_BD_ADDR BTM_Sec_GetAddressWithType(const RawAddress& bd_addr) { if (!p_dev_rec->ble.cur_rand_addr.IsEmpty() && btm_cb.ble_ctr_cb.privacy_mode < BTM_PRIVACY_1_2) { return { - .type = BLE_ADDR_RANDOM, - .bda = p_dev_rec->ble.cur_rand_addr, + .type = BLE_ADDR_RANDOM, + .bda = p_dev_rec->ble.cur_rand_addr, }; } #endif @@ -751,9 +772,7 @@ namespace bluetooth { namespace testing { namespace legacy { -void wipe_secrets_and_remove(tBTM_SEC_DEV_REC* p_dev_rec) { - ::wipe_secrets_and_remove(p_dev_rec); -} +void wipe_secrets_and_remove(tBTM_SEC_DEV_REC* p_dev_rec) { ::wipe_secrets_and_remove(p_dev_rec); } } // namespace legacy } // namespace testing diff --git a/system/stack/btm/btm_devctl.cc b/system/stack/btm/btm_devctl.cc index 0e3f8dd56ca..1c39ca3d27c 100644 --- a/system/stack/btm/btm_devctl.cc +++ b/system/stack/btm/btm_devctl.cc @@ -66,7 +66,7 @@ void btm_pm_reset(void); // TODO: Reevaluate this value in the context of timers with ms granularity #define BTM_DEV_NAME_REPLY_TIMEOUT_MS \ (2 * 1000) /* 2 seconds for name reply \ - */ + */ #define BTM_INFO_TIMEOUT 5 /* 5 seconds for info response */ @@ -92,9 +92,9 @@ void btm_dev_init() { btm_cb.devcb.read_local_name_timer = alarm_new("btm.read_local_name_timer"); btm_cb.devcb.read_rssi_timer = alarm_new("btm.read_rssi_timer"); btm_cb.devcb.read_failed_contact_counter_timer = - alarm_new("btm.read_failed_contact_counter_timer"); + alarm_new("btm.read_failed_contact_counter_timer"); btm_cb.devcb.read_automatic_flush_timeout_timer = - alarm_new("btm.read_automatic_flush_timeout_timer"); + alarm_new("btm.read_automatic_flush_timeout_timer"); btm_cb.devcb.read_tx_power_timer = alarm_new("btm.read_tx_power_timer"); } @@ -198,24 +198,19 @@ void BTM_reset_complete() { if (bluetooth::shim::GetController()->SupportsBle() && bluetooth::shim::GetController()->SupportsBlePrivacy() && bluetooth::shim::GetController()->GetLeResolvingListSize() > 0) { - btm_ble_resolving_list_init( - bluetooth::shim::GetController()->GetLeResolvingListSize()); + btm_ble_resolving_list_init(bluetooth::shim::GetController()->GetLeResolvingListSize()); /* set the default random private address timeout */ - btsnd_hcic_ble_set_rand_priv_addr_timeout( - btm_get_next_private_addrress_interval_ms() / 1000); + btsnd_hcic_ble_set_rand_priv_addr_timeout(btm_get_next_private_address_interval_ms() / 1000); } else { - log::info( - "Le Address Resolving list disabled due to lack of controller support"); + log::info("Le Address Resolving list disabled due to lack of controller support"); } if (bluetooth::shim::GetController()->SupportsBle()) { - l2c_link_processs_ble_num_bufs(bluetooth::shim::GetController() - ->GetLeBufferSize() - .total_num_le_packets_); + l2c_link_process_ble_num_bufs( + bluetooth::shim::GetController()->GetLeBufferSize().total_num_le_packets_); } - BTM_SetPinType(btm_sec_cb.cfg.pin_type, btm_sec_cb.cfg.pin_code, - btm_sec_cb.cfg.pin_code_len); + BTM_SetPinType(btm_sec_cb.cfg.pin_type, btm_sec_cb.cfg.pin_code, btm_sec_cb.cfg.pin_code_len); decode_controller_support(); } @@ -229,9 +224,7 @@ void BTM_reset_complete() { * Returns true if device is up, else false * ******************************************************************************/ -bool BTM_IsDeviceUp(void) { - return bluetooth::shim::GetController() != nullptr; -} +bool BTM_IsDeviceUp(void) { return bluetooth::shim::GetController() != nullptr; } /******************************************************************************* * @@ -245,7 +238,9 @@ bool BTM_IsDeviceUp(void) { static void btm_read_local_name_timeout(void* /* data */) { tBTM_CMPL_CB* p_cb = btm_cb.devcb.p_rln_cmpl_cb; btm_cb.devcb.p_rln_cmpl_cb = NULL; - if (p_cb) (*p_cb)((void*)NULL); + if (p_cb) { + (*p_cb)((void*)NULL); + } } static void decode_controller_support() { @@ -255,45 +250,51 @@ static void decode_controller_support() { if (bluetooth::shim::GetController()->SupportsSco()) { btm_cb.btm_sco_pkt_types_supported = ESCO_PKT_TYPES_MASK_HV1; - if (bluetooth::shim::GetController()->SupportsHv2Packets()) + if (bluetooth::shim::GetController()->SupportsHv2Packets()) { btm_cb.btm_sco_pkt_types_supported |= ESCO_PKT_TYPES_MASK_HV2; + } - if (bluetooth::shim::GetController()->SupportsHv3Packets()) + if (bluetooth::shim::GetController()->SupportsHv3Packets()) { btm_cb.btm_sco_pkt_types_supported |= ESCO_PKT_TYPES_MASK_HV3; + } } - if (bluetooth::shim::GetController()->SupportsEv3Packets()) + if (bluetooth::shim::GetController()->SupportsEv3Packets()) { btm_cb.btm_sco_pkt_types_supported |= ESCO_PKT_TYPES_MASK_EV3; + } - if (bluetooth::shim::GetController()->SupportsEv4Packets()) + if (bluetooth::shim::GetController()->SupportsEv4Packets()) { btm_cb.btm_sco_pkt_types_supported |= ESCO_PKT_TYPES_MASK_EV4; + } - if (bluetooth::shim::GetController()->SupportsEv5Packets()) + if (bluetooth::shim::GetController()->SupportsEv5Packets()) { btm_cb.btm_sco_pkt_types_supported |= ESCO_PKT_TYPES_MASK_EV5; + } if (btm_cb.btm_sco_pkt_types_supported & BTM_ESCO_LINK_ONLY_MASK) { btm_cb.sco_cb.esco_supported = true; /* Add in EDR related eSCO types */ if (bluetooth::shim::GetController()->SupportsEsco2mPhy()) { - if (!bluetooth::shim::GetController()->Supports3SlotEdrPackets()) + if (!bluetooth::shim::GetController()->Supports3SlotEdrPackets()) { btm_cb.btm_sco_pkt_types_supported |= ESCO_PKT_TYPES_MASK_NO_2_EV5; + } } else { btm_cb.btm_sco_pkt_types_supported |= - (ESCO_PKT_TYPES_MASK_NO_2_EV3 + ESCO_PKT_TYPES_MASK_NO_2_EV5); + (ESCO_PKT_TYPES_MASK_NO_2_EV3 + ESCO_PKT_TYPES_MASK_NO_2_EV5); } if (bluetooth::shim::GetController()->SupportsEsco3mPhy()) { - if (!bluetooth::shim::GetController()->Supports3SlotEdrPackets()) + if (!bluetooth::shim::GetController()->Supports3SlotEdrPackets()) { btm_cb.btm_sco_pkt_types_supported |= ESCO_PKT_TYPES_MASK_NO_3_EV5; + } } else { btm_cb.btm_sco_pkt_types_supported |= - (ESCO_PKT_TYPES_MASK_NO_3_EV3 + ESCO_PKT_TYPES_MASK_NO_3_EV5); + (ESCO_PKT_TYPES_MASK_NO_3_EV3 + ESCO_PKT_TYPES_MASK_NO_3_EV5); } } - log::verbose("Local supported SCO packet types: 0x{:04x}", - btm_cb.btm_sco_pkt_types_supported); + log::verbose("Local supported SCO packet types: 0x{:04x}", btm_cb.btm_sco_pkt_types_supported); BTM_acl_after_controller_started(); btm_sec_dev_reset(); @@ -310,8 +311,7 @@ static void decode_controller_support() { } } - l2cu_set_non_flushable_pbf( - bluetooth::shim::GetController()->SupportsNonFlushablePb()); + l2cu_set_non_flushable_pbf(bluetooth::shim::GetController()->SupportsNonFlushablePb()); BTM_EnableInterlacedPageScan(); BTM_EnableInterlacedInquiryScan(); } @@ -356,7 +356,7 @@ tBTM_STATUS BTM_SetLocalDeviceName(const char* p_name) { ******************************************************************************/ tBTM_STATUS BTM_ReadLocalDeviceName(const char** p_name) { *p_name = (const char*)btm_sec_cb.cfg.bd_name; - return (BTM_SUCCESS); + return BTM_SUCCESS; } /******************************************************************************* @@ -369,18 +369,18 @@ tBTM_STATUS BTM_ReadLocalDeviceName(const char** p_name) { * Returns BTM_CMD_STARTED if successful, otherwise an error * ******************************************************************************/ -tBTM_STATUS BTM_ReadLocalDeviceNameFromController( - tBTM_CMPL_CB* p_rln_cmpl_cback) { +tBTM_STATUS BTM_ReadLocalDeviceNameFromController(tBTM_CMPL_CB* p_rln_cmpl_cback) { /* Check if rln already in progress */ - if (btm_cb.devcb.p_rln_cmpl_cb) return (BTM_NO_RESOURCES); + if (btm_cb.devcb.p_rln_cmpl_cb) { + return BTM_NO_RESOURCES; + } /* Save callback */ btm_cb.devcb.p_rln_cmpl_cb = p_rln_cmpl_cback; btsnd_hcic_read_name(); - alarm_set_on_mloop(btm_cb.devcb.read_local_name_timer, - BTM_DEV_NAME_REPLY_TIMEOUT_MS, btm_read_local_name_timeout, - NULL); + alarm_set_on_mloop(btm_cb.devcb.read_local_name_timer, BTM_DEV_NAME_REPLY_TIMEOUT_MS, + btm_read_local_name_timeout, NULL); return BTM_CMD_STARTED; } @@ -407,10 +407,11 @@ void btm_read_local_name_complete(uint8_t* p, uint16_t /* evt_len */) { if (p_cb) { STREAM_TO_UINT8(status, p); - if (status == HCI_SUCCESS) + if (status == HCI_SUCCESS) { (*p_cb)(p); - else + } else { (*p_cb)(NULL); + } } } @@ -424,15 +425,19 @@ void btm_read_local_name_complete(uint8_t* p, uint16_t /* evt_len */) { * ******************************************************************************/ tBTM_STATUS BTM_SetDeviceClass(DEV_CLASS dev_class) { - if (btm_cb.devcb.dev_class == dev_class) return (BTM_SUCCESS); + if (btm_cb.devcb.dev_class == dev_class) { + return BTM_SUCCESS; + } btm_cb.devcb.dev_class = dev_class; - if (bluetooth::shim::GetController() == nullptr) return (BTM_DEV_RESET); + if (bluetooth::shim::GetController() == nullptr) { + return BTM_DEV_RESET; + } btsnd_hcic_write_dev_class(dev_class); - return (BTM_SUCCESS); + return BTM_SUCCESS; } /******************************************************************************* @@ -456,8 +461,8 @@ DEV_CLASS BTM_ReadDeviceClass(void) { return btm_cb.devcb.dev_class; } * Opcode will be OR'd with HCI_GRP_VENDOR_SPECIFIC. * ******************************************************************************/ -void BTM_VendorSpecificCommand(uint16_t opcode, uint8_t param_len, - uint8_t* p_param_buf, tBTM_VSC_CMPL_CB* p_cb) { +void BTM_VendorSpecificCommand(uint16_t opcode, uint8_t param_len, uint8_t* p_param_buf, + tBTM_VSC_CMPL_CB* p_cb) { log::verbose("BTM: Opcode: 0x{:04X}, ParamLen: {}.", opcode, param_len); /* Send the HCI command (opcode will be OR'd with HCI_GRP_VENDOR_SPECIFIC) */ @@ -516,8 +521,8 @@ tBTM_STATUS BTM_EnableTestMode(void) { /* set auto accept connection as this is needed during test mode */ /* Allocate a buffer to hold HCI command */ cond = HCI_DO_AUTO_ACCEPT_CONNECT; - btsnd_hcic_set_event_filter(HCI_FILTER_CONNECTION_SETUP, - HCI_FILTER_COND_NEW_DEVICE, &cond, sizeof(cond)); + btsnd_hcic_set_event_filter(HCI_FILTER_CONNECTION_SETUP, HCI_FILTER_COND_NEW_DEVICE, &cond, + sizeof(cond)); /* put device to connectable mode */ if (BTM_SetConnectability(BTM_CONNECTABLE) != BTM_SUCCESS) { @@ -534,7 +539,7 @@ tBTM_STATUS BTM_EnableTestMode(void) { /* Send the HCI command */ btsnd_hcic_enable_test_mode(); - return (BTM_SUCCESS); + return BTM_SUCCESS; } /******************************************************************************* @@ -550,20 +555,20 @@ tBTM_STATUS BTM_EnableTestMode(void) { * the results * ******************************************************************************/ -tBTM_STATUS BTM_DeleteStoredLinkKey(const RawAddress* bd_addr, - tBTM_CMPL_CB* p_cb) { +tBTM_STATUS BTM_DeleteStoredLinkKey(const RawAddress* bd_addr, tBTM_CMPL_CB* p_cb) { /* Read and Write STORED link key stems from a legacy use-case and is no * longer expected to be used. Disable explicitly for Floss and queue overall * deletion from Fluoride. */ #if !defined(TARGET_FLOSS) /* Check if the previous command is completed */ - if (btm_sec_cb.devcb.p_stored_link_key_cmpl_cb) return (BTM_BUSY); + if (btm_sec_cb.devcb.p_stored_link_key_cmpl_cb) { + return BTM_BUSY; + } bool delete_all_flag = !bd_addr; - log::verbose("BTM: BTM_DeleteStoredLinkKey: delete_all_flag: {}", - delete_all_flag); + log::verbose("BTM: BTM_DeleteStoredLinkKey: delete_all_flag: {}", delete_all_flag); btm_sec_cb.devcb.p_stored_link_key_cmpl_cb = p_cb; if (!bd_addr) { @@ -576,7 +581,7 @@ tBTM_STATUS BTM_DeleteStoredLinkKey(const RawAddress* bd_addr, } #endif - return (BTM_SUCCESS); + return BTM_SUCCESS; } /******************************************************************************* diff --git a/system/stack/btm/btm_inq.cc b/system/stack/btm/btm_inq.cc index 0e9c50495f3..1f795f9071b 100644 --- a/system/stack/btm/btm_inq.cc +++ b/system/stack/btm/btm_inq.cc @@ -94,13 +94,14 @@ constexpr char kBtmLogTag[] = "SCAN"; void btm_log_history_scan_mode(uint8_t scan_mode) { static uint8_t scan_mode_cached_ = 0xff; - if (scan_mode_cached_ == scan_mode) return; + if (scan_mode_cached_ == scan_mode) { + return; + } - BTM_LogHistory( - kBtmLogTag, RawAddress::kEmpty, "Classic updated", - base::StringPrintf("inquiry_scan_enable:%c page_scan_enable:%c", - (scan_mode & HCI_INQUIRY_SCAN_ENABLED) ? 'T' : 'F', - (scan_mode & HCI_PAGE_SCAN_ENABLED) ? 'T' : 'F')); + BTM_LogHistory(kBtmLogTag, RawAddress::kEmpty, "Classic updated", + base::StringPrintf("inquiry_scan_enable:%c page_scan_enable:%c", + (scan_mode & HCI_INQUIRY_SCAN_ENABLED) ? 'T' : 'F', + (scan_mode & HCI_PAGE_SCAN_ENABLED) ? 'T' : 'F')); scan_mode_cached_ = scan_mode; } @@ -120,8 +121,7 @@ uint16_t max_bd_entries_; /* Maximum number of entries that can be stored */ extern tBTM_CB btm_cb; void btm_inq_db_set_inq_by_rssi(void); void btm_inq_remote_name_timer_timeout(void* data); -tBTM_STATUS btm_ble_read_remote_name(const RawAddress& remote_bda, - tBTM_NAME_CMPL_CB* p_cb); +tBTM_STATUS btm_ble_read_remote_name(const RawAddress& remote_bda, tBTM_NAME_CMPL_CB* p_cb); bool btm_ble_cancel_remote_name(const RawAddress& remote_bda); tBTM_STATUS btm_ble_set_discoverability(uint16_t combined_mode); tBTM_STATUS btm_ble_set_connectability(uint16_t combined_mode); @@ -181,54 +181,50 @@ static const LAP general_inq_lap = {0x9e, 0x8b, 0x33}; static const LAP limited_inq_lap = {0x9e, 0x8b, 0x00}; const uint16_t BTM_EIR_UUID_LKUP_TBL[BTM_EIR_MAX_SERVICES] = { - UUID_SERVCLASS_SERVICE_DISCOVERY_SERVER, - /* UUID_SERVCLASS_BROWSE_GROUP_DESCRIPTOR, */ - /* UUID_SERVCLASS_PUBLIC_BROWSE_GROUP, */ - UUID_SERVCLASS_SERIAL_PORT, UUID_SERVCLASS_LAN_ACCESS_USING_PPP, - UUID_SERVCLASS_DIALUP_NETWORKING, UUID_SERVCLASS_IRMC_SYNC, - UUID_SERVCLASS_OBEX_OBJECT_PUSH, UUID_SERVCLASS_OBEX_FILE_TRANSFER, - UUID_SERVCLASS_IRMC_SYNC_COMMAND, UUID_SERVCLASS_HEADSET, - UUID_SERVCLASS_CORDLESS_TELEPHONY, UUID_SERVCLASS_AUDIO_SOURCE, - UUID_SERVCLASS_AUDIO_SINK, UUID_SERVCLASS_AV_REM_CTRL_TARGET, - /* UUID_SERVCLASS_ADV_AUDIO_DISTRIBUTION, */ - UUID_SERVCLASS_AV_REMOTE_CONTROL, - /* UUID_SERVCLASS_VIDEO_CONFERENCING, */ - UUID_SERVCLASS_INTERCOM, UUID_SERVCLASS_FAX, - UUID_SERVCLASS_HEADSET_AUDIO_GATEWAY, - /* UUID_SERVCLASS_WAP, */ - /* UUID_SERVCLASS_WAP_CLIENT, */ - UUID_SERVCLASS_PANU, UUID_SERVCLASS_NAP, UUID_SERVCLASS_GN, - UUID_SERVCLASS_DIRECT_PRINTING, - /* UUID_SERVCLASS_REFERENCE_PRINTING, */ - UUID_SERVCLASS_IMAGING, UUID_SERVCLASS_IMAGING_RESPONDER, - UUID_SERVCLASS_IMAGING_AUTO_ARCHIVE, UUID_SERVCLASS_IMAGING_REF_OBJECTS, - UUID_SERVCLASS_HF_HANDSFREE, UUID_SERVCLASS_AG_HANDSFREE, - UUID_SERVCLASS_DIR_PRT_REF_OBJ_SERVICE, - /* UUID_SERVCLASS_REFLECTED_UI, */ - UUID_SERVCLASS_BASIC_PRINTING, UUID_SERVCLASS_PRINTING_STATUS, - UUID_SERVCLASS_HUMAN_INTERFACE, UUID_SERVCLASS_CABLE_REPLACEMENT, - UUID_SERVCLASS_HCRP_PRINT, UUID_SERVCLASS_HCRP_SCAN, - /* UUID_SERVCLASS_COMMON_ISDN_ACCESS, */ - /* UUID_SERVCLASS_VIDEO_CONFERENCING_GW, */ - /* UUID_SERVCLASS_UDI_MT, */ - /* UUID_SERVCLASS_UDI_TA, */ - /* UUID_SERVCLASS_VCP, */ - UUID_SERVCLASS_SAP, UUID_SERVCLASS_PBAP_PCE, UUID_SERVCLASS_PBAP_PSE, - UUID_SERVCLASS_PHONE_ACCESS, UUID_SERVCLASS_HEADSET_HS, - UUID_SERVCLASS_PNP_INFORMATION, - /* UUID_SERVCLASS_GENERIC_NETWORKING, */ - /* UUID_SERVCLASS_GENERIC_FILETRANSFER, */ - /* UUID_SERVCLASS_GENERIC_AUDIO, */ - /* UUID_SERVCLASS_GENERIC_TELEPHONY, */ - /* UUID_SERVCLASS_UPNP_SERVICE, */ - /* UUID_SERVCLASS_UPNP_IP_SERVICE, */ - /* UUID_SERVCLASS_ESDP_UPNP_IP_PAN, */ - /* UUID_SERVCLASS_ESDP_UPNP_IP_LAP, */ - /* UUID_SERVCLASS_ESDP_UPNP_IP_L2CAP, */ - UUID_SERVCLASS_VIDEO_SOURCE, UUID_SERVCLASS_VIDEO_SINK, - /* UUID_SERVCLASS_VIDEO_DISTRIBUTION */ - UUID_SERVCLASS_MESSAGE_ACCESS, UUID_SERVCLASS_MESSAGE_NOTIFICATION, - UUID_SERVCLASS_HDP_SOURCE, UUID_SERVCLASS_HDP_SINK}; + UUID_SERVCLASS_SERVICE_DISCOVERY_SERVER, + /* UUID_SERVCLASS_BROWSE_GROUP_DESCRIPTOR, */ + /* UUID_SERVCLASS_PUBLIC_BROWSE_GROUP, */ + UUID_SERVCLASS_SERIAL_PORT, UUID_SERVCLASS_LAN_ACCESS_USING_PPP, + UUID_SERVCLASS_DIALUP_NETWORKING, UUID_SERVCLASS_IRMC_SYNC, UUID_SERVCLASS_OBEX_OBJECT_PUSH, + UUID_SERVCLASS_OBEX_FILE_TRANSFER, UUID_SERVCLASS_IRMC_SYNC_COMMAND, UUID_SERVCLASS_HEADSET, + UUID_SERVCLASS_CORDLESS_TELEPHONY, UUID_SERVCLASS_AUDIO_SOURCE, UUID_SERVCLASS_AUDIO_SINK, + UUID_SERVCLASS_AV_REM_CTRL_TARGET, + /* UUID_SERVCLASS_ADV_AUDIO_DISTRIBUTION, */ + UUID_SERVCLASS_AV_REMOTE_CONTROL, + /* UUID_SERVCLASS_VIDEO_CONFERENCING, */ + UUID_SERVCLASS_INTERCOM, UUID_SERVCLASS_FAX, UUID_SERVCLASS_HEADSET_AUDIO_GATEWAY, + /* UUID_SERVCLASS_WAP, */ + /* UUID_SERVCLASS_WAP_CLIENT, */ + UUID_SERVCLASS_PANU, UUID_SERVCLASS_NAP, UUID_SERVCLASS_GN, UUID_SERVCLASS_DIRECT_PRINTING, + /* UUID_SERVCLASS_REFERENCE_PRINTING, */ + UUID_SERVCLASS_IMAGING, UUID_SERVCLASS_IMAGING_RESPONDER, + UUID_SERVCLASS_IMAGING_AUTO_ARCHIVE, UUID_SERVCLASS_IMAGING_REF_OBJECTS, + UUID_SERVCLASS_HF_HANDSFREE, UUID_SERVCLASS_AG_HANDSFREE, + UUID_SERVCLASS_DIR_PRT_REF_OBJ_SERVICE, + /* UUID_SERVCLASS_REFLECTED_UI, */ + UUID_SERVCLASS_BASIC_PRINTING, UUID_SERVCLASS_PRINTING_STATUS, + UUID_SERVCLASS_HUMAN_INTERFACE, UUID_SERVCLASS_CABLE_REPLACEMENT, UUID_SERVCLASS_HCRP_PRINT, + UUID_SERVCLASS_HCRP_SCAN, + /* UUID_SERVCLASS_COMMON_ISDN_ACCESS, */ + /* UUID_SERVCLASS_VIDEO_CONFERENCING_GW, */ + /* UUID_SERVCLASS_UDI_MT, */ + /* UUID_SERVCLASS_UDI_TA, */ + /* UUID_SERVCLASS_VCP, */ + UUID_SERVCLASS_SAP, UUID_SERVCLASS_PBAP_PCE, UUID_SERVCLASS_PBAP_PSE, + UUID_SERVCLASS_PHONE_ACCESS, UUID_SERVCLASS_HEADSET_HS, UUID_SERVCLASS_PNP_INFORMATION, + /* UUID_SERVCLASS_GENERIC_NETWORKING, */ + /* UUID_SERVCLASS_GENERIC_FILETRANSFER, */ + /* UUID_SERVCLASS_GENERIC_AUDIO, */ + /* UUID_SERVCLASS_GENERIC_TELEPHONY, */ + /* UUID_SERVCLASS_UPNP_SERVICE, */ + /* UUID_SERVCLASS_UPNP_IP_SERVICE, */ + /* UUID_SERVCLASS_ESDP_UPNP_IP_PAN, */ + /* UUID_SERVCLASS_ESDP_UPNP_IP_LAP, */ + /* UUID_SERVCLASS_ESDP_UPNP_IP_L2CAP, */ + UUID_SERVCLASS_VIDEO_SOURCE, UUID_SERVCLASS_VIDEO_SINK, + /* UUID_SERVCLASS_VIDEO_DISTRIBUTION */ + UUID_SERVCLASS_MESSAGE_ACCESS, UUID_SERVCLASS_MESSAGE_NOTIFICATION, + UUID_SERVCLASS_HDP_SOURCE, UUID_SERVCLASS_HDP_SINK}; /******************************************************************************/ /* L O C A L F U N C T I O N P R O T O T Y P E S */ @@ -237,22 +233,17 @@ static void btm_clr_inq_db(const RawAddress* p_bda); static void btm_init_inq_result_flt(void); void btm_clr_inq_result_flt(void); static void btm_inq_rmt_name_failed_cancelled(void); -static tBTM_STATUS btm_initiate_rem_name(const RawAddress& remote_bda, - uint64_t timeout_ms, +static tBTM_STATUS btm_initiate_rem_name(const RawAddress& remote_bda, uint64_t timeout_ms, tBTM_NAME_CMPL_CB* p_cb); static uint8_t btm_convert_uuid_to_eir_service(uint16_t uuid16); void btm_set_eir_uuid(const uint8_t* p_eir, tBTM_INQ_RESULTS* p_results); -static const uint8_t* btm_eir_get_uuid_list(const uint8_t* p_eir, - size_t eir_len, uint8_t uuid_size, - uint8_t* p_num_uuid, - uint8_t* p_uuid_list_type); +static const uint8_t* btm_eir_get_uuid_list(const uint8_t* p_eir, size_t eir_len, uint8_t uuid_size, + uint8_t* p_num_uuid, uint8_t* p_uuid_list_type); static void btm_process_cancel_complete(tHCI_STATUS status, uint8_t mode); static void on_incoming_hci_event(bluetooth::hci::EventView event); -static bool is_inquery_by_rssi() { - return osi_property_get_bool(PROPERTY_INQ_BY_RSSI, false); -} +static bool is_inquery_by_rssi() { return osi_property_get_bool(PROPERTY_INQ_BY_RSSI, false); } /******************************************************************************* * * Function BTM_SetDiscoverability @@ -282,20 +273,20 @@ tBTM_STATUS BTM_SetDiscoverability(uint16_t inq_mode) { if (bluetooth::shim::GetController()->SupportsBle()) { if (btm_ble_set_discoverability((uint16_t)(inq_mode)) == BTM_SUCCESS) { btm_cb.btm_inq_vars.discoverable_mode &= (~BTM_BLE_DISCOVERABLE_MASK); - btm_cb.btm_inq_vars.discoverable_mode |= - (inq_mode & BTM_BLE_DISCOVERABLE_MASK); + btm_cb.btm_inq_vars.discoverable_mode |= (inq_mode & BTM_BLE_DISCOVERABLE_MASK); } } inq_mode &= ~BTM_BLE_DISCOVERABLE_MASK; /*** Check mode parameter ***/ - if (inq_mode > BTM_MAX_DISCOVERABLE) return (BTM_ILLEGAL_VALUE); + if (inq_mode > BTM_MAX_DISCOVERABLE) { + return BTM_ILLEGAL_VALUE; + } /* If the window and/or interval is '0', set to default values */ log::verbose("mode {} [NonDisc-0, Lim-1, Gen-2]", inq_mode); - (inq_mode != BTM_NON_DISCOVERABLE) - ? power_telemetry::GetInstance().LogInqScanStarted() - : power_telemetry::GetInstance().LogInqScanStopped(); + (inq_mode != BTM_NON_DISCOVERABLE) ? power_telemetry::GetInstance().LogInqScanStarted() + : power_telemetry::GetInstance().LogInqScanStopped(); /* Set the IAC if needed */ if (inq_mode != BTM_NON_DISCOVERABLE) { @@ -304,18 +295,17 @@ tBTM_STATUS BTM_SetDiscoverability(uint16_t inq_mode) { memcpy(temp_lap[0], limited_inq_lap, LAP_LEN); memcpy(temp_lap[1], general_inq_lap, LAP_LEN); - btsnd_hcic_write_cur_iac_lap(2, (LAP * const)temp_lap); + btsnd_hcic_write_cur_iac_lap(2, (LAP* const)temp_lap); } else { - btsnd_hcic_write_cur_iac_lap(1, (LAP * const) & general_inq_lap); + btsnd_hcic_write_cur_iac_lap(1, (LAP* const)&general_inq_lap); } scan_mode |= HCI_INQUIRY_SCAN_ENABLED; } - const uint16_t window = - osi_property_get_int32(PROPERTY_INQ_SCAN_WINDOW, BTM_DEFAULT_DISC_WINDOW); - const uint16_t interval = osi_property_get_int32(PROPERTY_INQ_SCAN_INTERVAL, - BTM_DEFAULT_DISC_INTERVAL); + const uint16_t window = osi_property_get_int32(PROPERTY_INQ_SCAN_WINDOW, BTM_DEFAULT_DISC_WINDOW); + const uint16_t interval = + osi_property_get_int32(PROPERTY_INQ_SCAN_INTERVAL, BTM_DEFAULT_DISC_INTERVAL); /* Send down the inquiry scan window and period if changed */ if ((window != btm_cb.btm_inq_vars.inq_scan_window) || @@ -325,8 +315,9 @@ tBTM_STATUS BTM_SetDiscoverability(uint16_t inq_mode) { btm_cb.btm_inq_vars.inq_scan_period = interval; } - if (btm_cb.btm_inq_vars.connectable_mode & BTM_CONNECTABLE_MASK) + if (btm_cb.btm_inq_vars.connectable_mode & BTM_CONNECTABLE_MASK) { scan_mode |= HCI_PAGE_SCAN_ENABLED; + } btm_log_history_scan_mode(scan_mode); btsnd_hcic_write_scan_enable(scan_mode); @@ -341,36 +332,33 @@ tBTM_STATUS BTM_SetDiscoverability(uint16_t inq_mode) { if (is_limited ^ cod_limited) { BTM_COD_MINOR_CLASS(minor, old_cod); BTM_COD_MAJOR_CLASS(major, old_cod); - if (is_limited) + if (is_limited) { service_class |= BTM_COD_SERVICE_LMTD_DISCOVER; - else + } else { service_class &= ~BTM_COD_SERVICE_LMTD_DISCOVER; + } FIELDS_TO_COD(cod, minor, major, service_class); (void)BTM_SetDeviceClass(cod); } - return (BTM_SUCCESS); + return BTM_SUCCESS; } void BTM_EnableInterlacedInquiryScan() { log::verbose(""); - uint16_t inq_scan_type = - osi_property_get_int32(PROPERTY_INQ_SCAN_TYPE, BTM_SCAN_TYPE_INTERLACED); + uint16_t inq_scan_type = osi_property_get_int32(PROPERTY_INQ_SCAN_TYPE, BTM_SCAN_TYPE_INTERLACED); if (!bluetooth::shim::GetController()->SupportsInterlacedInquiryScan() || inq_scan_type != BTM_SCAN_TYPE_INTERLACED || btm_cb.btm_inq_vars.inq_scan_type == BTM_SCAN_TYPE_INTERLACED) { log::warn( - "Unable to set interlaced inquiry scan controller_supported:%c " - "property_supported:%c already_in_mode:%c", - (bluetooth::shim::GetController()->SupportsInterlacedInquiryScan()) - ? 'T' - : 'F', - (inq_scan_type != BTM_SCAN_TYPE_INTERLACED) ? 'T' : 'F', - (btm_cb.btm_inq_vars.inq_scan_type == BTM_SCAN_TYPE_INTERLACED) ? 'T' - : 'F'); + "Unable to set interlaced inquiry scan controller_supported:%c " + "property_supported:%c already_in_mode:%c", + (bluetooth::shim::GetController()->SupportsInterlacedInquiryScan()) ? 'T' : 'F', + (inq_scan_type != BTM_SCAN_TYPE_INTERLACED) ? 'T' : 'F', + (btm_cb.btm_inq_vars.inq_scan_type == BTM_SCAN_TYPE_INTERLACED) ? 'T' : 'F'); return; } @@ -382,20 +370,17 @@ void BTM_EnableInterlacedPageScan() { log::verbose(""); uint16_t page_scan_type = - osi_property_get_int32(PROPERTY_PAGE_SCAN_TYPE, BTM_SCAN_TYPE_INTERLACED); + osi_property_get_int32(PROPERTY_PAGE_SCAN_TYPE, BTM_SCAN_TYPE_INTERLACED); if (!bluetooth::shim::GetController()->SupportsInterlacedInquiryScan() || page_scan_type != BTM_SCAN_TYPE_INTERLACED || btm_cb.btm_inq_vars.page_scan_type == BTM_SCAN_TYPE_INTERLACED) { log::warn( - "Unable to set interlaced page scan controller_supported:%c " - "property_supported:%c already_in_mode:%c", - (bluetooth::shim::GetController()->SupportsInterlacedInquiryScan()) - ? 'T' - : 'F', - (page_scan_type != BTM_SCAN_TYPE_INTERLACED) ? 'T' : 'F', - (btm_cb.btm_inq_vars.page_scan_type == BTM_SCAN_TYPE_INTERLACED) ? 'T' - : 'F'); + "Unable to set interlaced page scan controller_supported:%c " + "property_supported:%c already_in_mode:%c", + (bluetooth::shim::GetController()->SupportsInterlacedInquiryScan()) ? 'T' : 'F', + (page_scan_type != BTM_SCAN_TYPE_INTERLACED) ? 'T' : 'F', + (btm_cb.btm_inq_vars.page_scan_type == BTM_SCAN_TYPE_INTERLACED) ? 'T' : 'F'); return; } @@ -423,13 +408,16 @@ tBTM_STATUS BTM_SetInquiryMode(uint8_t mode) { if (mode == BTM_INQ_RESULT_STANDARD) { /* mandatory mode */ } else if (mode == BTM_INQ_RESULT_WITH_RSSI) { - if (!bluetooth::shim::GetController()->SupportsRssiWithInquiryResults()) - return (BTM_MODE_UNSUPPORTED); + if (!bluetooth::shim::GetController()->SupportsRssiWithInquiryResults()) { + return BTM_MODE_UNSUPPORTED; + } } else if (mode == BTM_INQ_RESULT_EXTENDED) { - if (!bluetooth::shim::GetController()->SupportsExtendedInquiryResponse()) - return (BTM_MODE_UNSUPPORTED); - } else - return (BTM_ILLEGAL_VALUE); + if (!bluetooth::shim::GetController()->SupportsExtendedInquiryResponse()) { + return BTM_MODE_UNSUPPORTED; + } + } else { + return BTM_ILLEGAL_VALUE; + } if (!get_btm_client_interface().local.BTM_IsDeviceUp()) { return BTM_WRONG_MODE; @@ -437,7 +425,7 @@ tBTM_STATUS BTM_SetInquiryMode(uint8_t mode) { btsnd_hcic_write_inquiry_mode(mode); - return (BTM_SUCCESS); + return BTM_SUCCESS; } /******************************************************************************* @@ -462,27 +450,27 @@ tBTM_STATUS BTM_SetConnectability(uint16_t page_mode) { return BTM_NO_RESOURCES; } btm_cb.btm_inq_vars.connectable_mode &= (~BTM_BLE_CONNECTABLE_MASK); - btm_cb.btm_inq_vars.connectable_mode |= - (page_mode & BTM_BLE_CONNECTABLE_MASK); + btm_cb.btm_inq_vars.connectable_mode |= (page_mode & BTM_BLE_CONNECTABLE_MASK); } page_mode &= ~BTM_BLE_CONNECTABLE_MASK; /*** Check mode parameter ***/ - if (page_mode != BTM_NON_CONNECTABLE && page_mode != BTM_CONNECTABLE) - return (BTM_ILLEGAL_VALUE); + if (page_mode != BTM_NON_CONNECTABLE && page_mode != BTM_CONNECTABLE) { + return BTM_ILLEGAL_VALUE; + } /*** Only check window and duration if mode is connectable ***/ if (page_mode == BTM_CONNECTABLE) { scan_mode |= HCI_PAGE_SCAN_ENABLED; } - const uint16_t window = osi_property_get_int32(PROPERTY_PAGE_SCAN_WINDOW, - BTM_DEFAULT_CONN_WINDOW); - const uint16_t interval = osi_property_get_int32(PROPERTY_PAGE_SCAN_INTERVAL, - BTM_DEFAULT_CONN_INTERVAL); + const uint16_t window = + osi_property_get_int32(PROPERTY_PAGE_SCAN_WINDOW, BTM_DEFAULT_CONN_WINDOW); + const uint16_t interval = + osi_property_get_int32(PROPERTY_PAGE_SCAN_INTERVAL, BTM_DEFAULT_CONN_INTERVAL); - log::verbose("mode={} [NonConn-0, Conn-1], page scan interval=({} * 0.625)ms", - page_mode, interval); + log::verbose("mode={} [NonConn-0, Conn-1], page scan interval=({} * 0.625)ms", page_mode, + interval); if ((window != btm_cb.btm_inq_vars.page_scan_window) || (interval != btm_cb.btm_inq_vars.page_scan_period)) { @@ -492,14 +480,15 @@ tBTM_STATUS BTM_SetConnectability(uint16_t page_mode) { } /* Keep the inquiry scan as previouosly set */ - if (btm_cb.btm_inq_vars.discoverable_mode & BTM_DISCOVERABLE_MASK) + if (btm_cb.btm_inq_vars.discoverable_mode & BTM_DISCOVERABLE_MASK) { scan_mode |= HCI_INQUIRY_SCAN_ENABLED; + } btm_log_history_scan_mode(scan_mode); btsnd_hcic_write_scan_enable(scan_mode); btm_cb.btm_inq_vars.connectable_mode &= (~BTM_CONNECTABLE_MASK); btm_cb.btm_inq_vars.connectable_mode |= page_mode; - return (BTM_SUCCESS); + return BTM_SUCCESS; } /******************************************************************************* @@ -516,7 +505,7 @@ tBTM_STATUS BTM_SetConnectability(uint16_t page_mode) { uint16_t BTM_IsInquiryActive(void) { log::verbose(""); - return (btm_cb.btm_inq_vars.inq_active); + return btm_cb.btm_inq_vars.inq_active; } /******************************************************************************* @@ -530,12 +519,13 @@ static void BTM_CancelLeScan() { if (!bluetooth::shim::is_classic_discovery_only_enabled()) { log::assert_that(get_btm_client_interface().local.BTM_IsDeviceUp(), "assert failed: BTM_IsDeviceUp()"); - if ((btm_cb.btm_inq_vars.inqparms.mode & BTM_BLE_GENERAL_INQUIRY) != 0) + if ((btm_cb.btm_inq_vars.inqparms.mode & BTM_BLE_GENERAL_INQUIRY) != 0) { btm_ble_stop_inquiry(); + } } else { log::info( - "Unable to cancel le scan as `is_classic_discovery_only_enabled` is " - "true"); + "Unable to cancel le scan as `is_classic_discovery_only_enabled` is " + "true"); } } @@ -553,31 +543,26 @@ void BTM_CancelInquiry(void) { "assert failed: BTM_IsDeviceUp()"); btm_cb.neighbor.inquiry_history_->Push({ - .status = tBTM_INQUIRY_CMPL::CANCELED, - .num_resp = btm_cb.btm_inq_vars.inq_cmpl_info.num_resp, - .resp_type = - { - btm_cb.btm_inq_vars.inq_cmpl_info - .resp_type[BTM_INQ_RESULT_STANDARD], - btm_cb.btm_inq_vars.inq_cmpl_info - .resp_type[BTM_INQ_RESULT_WITH_RSSI], - btm_cb.btm_inq_vars.inq_cmpl_info - .resp_type[BTM_INQ_RESULT_EXTENDED], - }, - .start_time_ms = btm_cb.neighbor.classic_inquiry.start_time_ms, + .status = tBTM_INQUIRY_CMPL::CANCELED, + .num_resp = btm_cb.btm_inq_vars.inq_cmpl_info.num_resp, + .resp_type = + { + btm_cb.btm_inq_vars.inq_cmpl_info.resp_type[BTM_INQ_RESULT_STANDARD], + btm_cb.btm_inq_vars.inq_cmpl_info.resp_type[BTM_INQ_RESULT_WITH_RSSI], + btm_cb.btm_inq_vars.inq_cmpl_info.resp_type[BTM_INQ_RESULT_EXTENDED], + }, + .start_time_ms = btm_cb.neighbor.classic_inquiry.start_time_ms, }); const auto duration_ms = timestamper_in_milliseconds.GetTimestamp() - btm_cb.neighbor.classic_inquiry.start_time_ms; BTM_LogHistory( - kBtmLogTag, RawAddress::kEmpty, "Classic inquiry canceled", - base::StringPrintf( - "duration_s:%6.3f results:%lu std:%u rssi:%u ext:%u", - duration_ms / 1000.0, btm_cb.neighbor.classic_inquiry.results, - btm_cb.btm_inq_vars.inq_cmpl_info.resp_type[BTM_INQ_RESULT_STANDARD], - btm_cb.btm_inq_vars.inq_cmpl_info.resp_type[BTM_INQ_RESULT_WITH_RSSI], - btm_cb.btm_inq_vars.inq_cmpl_info - .resp_type[BTM_INQ_RESULT_EXTENDED])); + kBtmLogTag, RawAddress::kEmpty, "Classic inquiry canceled", + base::StringPrintf("duration_s:%6.3f results:%lu std:%u rssi:%u ext:%u", + duration_ms / 1000.0, btm_cb.neighbor.classic_inquiry.results, + btm_cb.btm_inq_vars.inq_cmpl_info.resp_type[BTM_INQ_RESULT_STANDARD], + btm_cb.btm_inq_vars.inq_cmpl_info.resp_type[BTM_INQ_RESULT_WITH_RSSI], + btm_cb.btm_inq_vars.inq_cmpl_info.resp_type[BTM_INQ_RESULT_EXTENDED])); btm_cb.neighbor.classic_inquiry = {}; /* Only cancel if not in periodic mode, otherwise the caller should call @@ -585,17 +570,15 @@ void BTM_CancelInquiry(void) { if ((btm_cb.btm_inq_vars.inq_active & BTM_INQUIRY_ACTIVE_MASK) != 0) { btm_cb.btm_inq_vars.inq_active = BTM_INQUIRY_INACTIVE; btm_cb.btm_inq_vars.state = BTM_INQ_INACTIVE_STATE; - btm_cb.btm_inq_vars.p_inq_results_cb = - NULL; /* Do not notify caller anymore */ - btm_cb.btm_inq_vars.p_inq_cmpl_cb = NULL; /* Do not notify caller anymore */ + btm_cb.btm_inq_vars.p_inq_results_cb = NULL; /* Do not notify caller anymore */ + btm_cb.btm_inq_vars.p_inq_cmpl_cb = NULL; /* Do not notify caller anymore */ if ((btm_cb.btm_inq_vars.inqparms.mode & BTM_GENERAL_INQUIRY) != 0) { bluetooth::shim::GetHciLayer()->EnqueueCommand( - bluetooth::hci::InquiryCancelBuilder::Create(), - get_main_thread()->BindOnce( - [](bluetooth::hci::CommandCompleteView complete_view) { - bluetooth::hci::check_complete< - bluetooth::hci::InquiryCancelCompleteView>(complete_view); + bluetooth::hci::InquiryCancelBuilder::Create(), + get_main_thread()->BindOnce([](bluetooth::hci::CommandCompleteView complete_view) { + bluetooth::hci::check_complete( + complete_view); btm_process_cancel_complete(HCI_SUCCESS, BTM_GENERAL_INQUIRY); })); } @@ -637,8 +620,7 @@ static tBTM_STATUS BTM_StartLeScan() { btm_cb.btm_inq_vars.inqparms.mode &= ~BTM_BLE_GENERAL_INQUIRY; } } else { - log::info( - "init_flag: Skip le scan as classic inquiry only flag is set enabled"); + log::info("init_flag: Skip le scan as classic inquiry only flag is set enabled"); } return BTM_WRONG_MODE; } @@ -680,43 +662,38 @@ static tBTM_STATUS BTM_StartLeScan() { * BTM_WRONG_MODE if the device is not up. * ******************************************************************************/ -tBTM_STATUS BTM_StartInquiry(tBTM_INQ_RESULTS_CB* p_results_cb, - tBTM_CMPL_CB* p_cmpl_cb) { +tBTM_STATUS BTM_StartInquiry(tBTM_INQ_RESULTS_CB* p_results_cb, tBTM_CMPL_CB* p_cmpl_cb) { /* Only one active inquiry is allowed in this implementation. Also do not allow an inquiry if the inquiry filter is being updated */ if (btm_cb.btm_inq_vars.inq_active) { log::warn( - "Active device discovery already in progress inq_active:0x{:02x} " - "state:{} counter:{}", - btm_cb.btm_inq_vars.inq_active, btm_cb.btm_inq_vars.state, - btm_cb.btm_inq_vars.inq_counter); + "Active device discovery already in progress inq_active:0x{:02x} " + "state:{} counter:{}", + btm_cb.btm_inq_vars.inq_active, btm_cb.btm_inq_vars.state, + btm_cb.btm_inq_vars.inq_counter); btm_cb.neighbor.inquiry_history_->Push({ - .status = tBTM_INQUIRY_CMPL::NOT_STARTED, + .status = tBTM_INQUIRY_CMPL::NOT_STARTED, }); return BTM_BUSY; } if (btm_cb.btm_inq_vars.registered_for_hci_events == false) { bluetooth::shim::GetHciLayer()->RegisterEventHandler( - bluetooth::hci::EventCode::INQUIRY_COMPLETE, - get_main_thread()->Bind([](bluetooth::hci::EventView event) { - on_incoming_hci_event(event); - })); + bluetooth::hci::EventCode::INQUIRY_COMPLETE, + get_main_thread()->Bind( + [](bluetooth::hci::EventView event) { on_incoming_hci_event(event); })); bluetooth::shim::GetHciLayer()->RegisterEventHandler( - bluetooth::hci::EventCode::INQUIRY_RESULT, - get_main_thread()->Bind([](bluetooth::hci::EventView event) { - on_incoming_hci_event(event); - })); + bluetooth::hci::EventCode::INQUIRY_RESULT, + get_main_thread()->Bind( + [](bluetooth::hci::EventView event) { on_incoming_hci_event(event); })); bluetooth::shim::GetHciLayer()->RegisterEventHandler( - bluetooth::hci::EventCode::INQUIRY_RESULT_WITH_RSSI, - get_main_thread()->Bind([](bluetooth::hci::EventView event) { - on_incoming_hci_event(event); - })); + bluetooth::hci::EventCode::INQUIRY_RESULT_WITH_RSSI, + get_main_thread()->Bind( + [](bluetooth::hci::EventView event) { on_incoming_hci_event(event); })); bluetooth::shim::GetHciLayer()->RegisterEventHandler( - bluetooth::hci::EventCode::EXTENDED_INQUIRY_RESULT, - get_main_thread()->Bind([](bluetooth::hci::EventView event) { - on_incoming_hci_event(event); - })); + bluetooth::hci::EventCode::EXTENDED_INQUIRY_RESULT, + get_main_thread()->Bind( + [](bluetooth::hci::EventView event) { on_incoming_hci_event(event); })); btm_cb.btm_inq_vars.registered_for_hci_events = true; } @@ -725,26 +702,25 @@ tBTM_STATUS BTM_StartInquiry(tBTM_INQ_RESULTS_CB* p_results_cb, if (!get_btm_client_interface().local.BTM_IsDeviceUp()) { log::error("adapter is not up"); btm_cb.neighbor.inquiry_history_->Push({ - .status = tBTM_INQUIRY_CMPL::NOT_STARTED, + .status = tBTM_INQUIRY_CMPL::NOT_STARTED, }); return BTM_WRONG_MODE; } BTM_LogHistory(kBtmLogTag, RawAddress::kEmpty, "Classic inquiry started", - base::StringPrintf( - "%s", (btm_cb.neighbor.classic_inquiry.start_time_ms == 0) - ? "" - : "ERROR Already in progress")); + base::StringPrintf("%s", (btm_cb.neighbor.classic_inquiry.start_time_ms == 0) + ? "" + : "ERROR Already in progress")); - const uint8_t inq_length = osi_property_get_int32( - PROPERTY_INQ_LENGTH, BTIF_DM_DEFAULT_INQ_MAX_DURATION); + const uint8_t inq_length = + osi_property_get_int32(PROPERTY_INQ_LENGTH, BTIF_DM_DEFAULT_INQ_MAX_DURATION); /* Save the inquiry parameters to be used upon the completion of * setting/clearing the inquiry filter */ btm_cb.btm_inq_vars.inqparms = { - // tBTM_INQ_PARMS - .mode = BTM_GENERAL_INQUIRY | BTM_BLE_GENERAL_INQUIRY, - .duration = inq_length, + // tBTM_INQ_PARMS + .mode = BTM_GENERAL_INQUIRY | BTM_BLE_GENERAL_INQUIRY, + .duration = inq_length, }; /* Initialize the inquiry variables */ @@ -754,12 +730,11 @@ tBTM_STATUS BTM_StartInquiry(tBTM_INQ_RESULTS_CB* p_results_cb, btm_cb.btm_inq_vars.inq_cmpl_info = {}; /* Clear the results counter */ btm_cb.btm_inq_vars.inq_active = btm_cb.btm_inq_vars.inqparms.mode; btm_cb.neighbor.classic_inquiry = { - .start_time_ms = timestamper_in_milliseconds.GetTimestamp(), - .results = 0, + .start_time_ms = timestamper_in_milliseconds.GetTimestamp(), + .results = 0, }; - log::debug("Starting device discovery inq_active:0x{:02x}", - btm_cb.btm_inq_vars.inq_active); + log::debug("Starting device discovery inq_active:0x{:02x}", btm_cb.btm_inq_vars.inq_active); // Also do BLE scanning here if we aren't limiting discovery to classic only. // This path does not play nicely with GD BLE scanning and may cause issues @@ -775,16 +750,12 @@ tBTM_STATUS BTM_StartInquiry(tBTM_INQ_RESULTS_CB* p_results_cb, // TODO: Register for the inquiry interface and use that bluetooth::shim::GetHciLayer()->EnqueueCommand( - bluetooth::hci::InquiryBuilder::Create( - lap, btm_cb.btm_inq_vars.inqparms.duration, 0), - get_main_thread()->BindOnce( - [](bluetooth::hci::CommandStatusView status_view) { - log::assert_that(status_view.IsValid(), - "assert failed: status_view.IsValid()"); + bluetooth::hci::InquiryBuilder::Create(lap, btm_cb.btm_inq_vars.inqparms.duration, 0), + get_main_thread()->BindOnce([](bluetooth::hci::CommandStatusView status_view) { + log::assert_that(status_view.IsValid(), "assert failed: status_view.IsValid()"); auto status = status_view.GetStatus(); if (status == bluetooth::hci::ErrorCode::SUCCESS) { - BTIF_dm_report_inquiry_status_change( - tBTM_INQUIRY_STATE::BTM_INQUIRY_STARTED); + BTIF_dm_report_inquiry_status_change(tBTM_INQUIRY_STATE::BTM_INQUIRY_STARTED); } else { log::info("Inquiry failed to start status: {}", bluetooth::hci::ErrorCodeText(status)); @@ -829,8 +800,7 @@ tBTM_STATUS BTM_StartInquiry(tBTM_INQ_RESULTS_CB* p_results_cb, * ******************************************************************************/ #define BTM_EXT_RMT_NAME_TIMEOUT_MS (40 * 1000) /* 40 seconds */ -tBTM_STATUS BTM_ReadRemoteDeviceName(const RawAddress& remote_bda, - tBTM_NAME_CMPL_CB* p_cb, +tBTM_STATUS BTM_ReadRemoteDeviceName(const RawAddress& remote_bda, tBTM_NAME_CMPL_CB* p_cb, tBT_TRANSPORT transport) { log::verbose("bd addr {}", remote_bda); /* Use LE transport when LE is the only available option */ @@ -865,7 +835,7 @@ tBTM_STATUS BTM_CancelRemoteDeviceName(void) { /* Make sure there is not already one in progress */ if (!btm_cb.rnr.remname_active) { - return (BTM_WRONG_MODE); + return BTM_WRONG_MODE; } if (com::android::bluetooth::flags::rnr_store_device_type()) { @@ -884,7 +854,7 @@ tBTM_STATUS BTM_CancelRemoteDeviceName(void) { btm_process_remote_name(&btm_cb.rnr.remname_bda, nullptr, 0, HCI_ERR_UNSPECIFIED); } } - return (BTM_CMD_STARTED); + return BTM_CMD_STARTED; } /******************************************************************************* @@ -923,11 +893,13 @@ tBTM_INQ_INFO* BTM_InqDbFirst(void) { std::lock_guard lock(inq_db_lock_); tINQ_DB_ENT* p_ent = inq_db_; for (xx = 0; xx < BTM_INQ_DB_SIZE; xx++, p_ent++) { - if (p_ent->in_use) return (&p_ent->inq_info); + if (p_ent->in_use) { + return &p_ent->inq_info; + } } /* If here, no used entry found */ - return ((tBTM_INQ_INFO*)NULL); + return (tBTM_INQ_INFO*)NULL; } /******************************************************************************* @@ -947,18 +919,20 @@ tBTM_INQ_INFO* BTM_InqDbNext(tBTM_INQ_INFO* p_cur) { std::lock_guard lock(inq_db_lock_); if (p_cur) { - tINQ_DB_ENT* p_ent = - (tINQ_DB_ENT*)((uint8_t*)p_cur - offsetof(tINQ_DB_ENT, inq_info)); + tINQ_DB_ENT* p_ent = (tINQ_DB_ENT*)((uint8_t*)p_cur - offsetof(tINQ_DB_ENT, inq_info)); inx = (uint16_t)((p_ent - inq_db_) + 1); for (p_ent = &inq_db_[inx]; inx < BTM_INQ_DB_SIZE; inx++, p_ent++) { - if (p_ent->in_use) return (&p_ent->inq_info); + if (p_ent->in_use) { + return &p_ent->inq_info; + } } /* If here, more entries found */ - return ((tBTM_INQ_INFO*)NULL); - } else - return (BTM_InqDbFirst()); + return (tBTM_INQ_INFO*)NULL; + } else { + return BTM_InqDbFirst(); + } } /******************************************************************************* @@ -977,11 +951,13 @@ tBTM_INQ_INFO* BTM_InqDbNext(tBTM_INQ_INFO* p_cur) { ******************************************************************************/ tBTM_STATUS BTM_ClearInqDb(const RawAddress* p_bda) { /* If an inquiry or remote name is in progress return busy */ - if (btm_cb.btm_inq_vars.inq_active != BTM_INQUIRY_INACTIVE) return (BTM_BUSY); + if (btm_cb.btm_inq_vars.inq_active != BTM_INQUIRY_INACTIVE) { + return BTM_BUSY; + } btm_clr_inq_db(p_bda); - return (BTM_SUCCESS); + return BTM_SUCCESS; } /******************************************************************************* @@ -1002,10 +978,10 @@ void btm_clear_all_pending_le_entry(void) { for (xx = 0; xx < BTM_INQ_DB_SIZE; xx++, p_ent++) { /* mark all pending LE entry as unused if an LE only device has scan * response outstanding */ - if ((p_ent->in_use) && - (p_ent->inq_info.results.device_type == BT_DEVICE_TYPE_BLE) && - !p_ent->scan_rsp) + if ((p_ent->in_use) && (p_ent->inq_info.results.device_type == BT_DEVICE_TYPE_BLE) && + !p_ent->scan_rsp) { p_ent->in_use = false; + } } } @@ -1035,9 +1011,8 @@ void btm_inq_db_reset(void) { /* If an inquiry or periodic inquiry is active, reset the mode to inactive */ if (btm_cb.btm_inq_vars.inq_active != BTM_INQUIRY_INACTIVE) { - temp_inq_active = - btm_cb.btm_inq_vars.inq_active; /* Save so state can change BEFORE - callback is called */ + temp_inq_active = btm_cb.btm_inq_vars.inq_active; /* Save so state can change BEFORE + callback is called */ btm_cb.btm_inq_vars.inq_active = BTM_INQUIRY_INACTIVE; /* If not a periodic inquiry, the complete callback must be called to notify @@ -1099,8 +1074,8 @@ void btm_clr_inq_db(const RawAddress* p_bda) { uint16_t xx; #if (BTM_INQ_DEBUG == TRUE) - log::verbose("btm_clr_inq_db: inq_active:0x{:x} state:{}", - btm_cb.btm_inq_vars.inq_active, btm_cb.btm_inq_vars.state); + log::verbose("btm_clr_inq_db: inq_active:0x{:x} state:{}", btm_cb.btm_inq_vars.inq_active, + btm_cb.btm_inq_vars.state); #endif std::lock_guard lock(inq_db_lock_); tINQ_DB_ENT* p_ent = inq_db_; @@ -1167,12 +1142,14 @@ bool btm_inq_find_bdaddr(const RawAddress& p_bda) { uint16_t xx; /* Don't bother searching, database doesn't exist or periodic mode */ - if (!p_db) return (false); + if (!p_db) { + return false; + } for (xx = 0; xx < num_bd_entries_; xx++, p_db++) { - if (p_db->bd_addr == p_bda && - p_db->inq_count == btm_cb.btm_inq_vars.inq_counter) - return (true); + if (p_db->bd_addr == p_bda && p_db->inq_count == btm_cb.btm_inq_vars.inq_counter) { + return true; + } } if (xx < max_bd_entries_) { @@ -1182,7 +1159,7 @@ bool btm_inq_find_bdaddr(const RawAddress& p_bda) { } /* If here, New Entry */ - return (false); + return false; } /******************************************************************************* @@ -1201,12 +1178,13 @@ tINQ_DB_ENT* btm_inq_db_find(const RawAddress& p_bda) { tINQ_DB_ENT* p_ent = inq_db_; for (xx = 0; xx < BTM_INQ_DB_SIZE; xx++, p_ent++) { - if (p_ent->in_use && p_ent->inq_info.results.remote_bd_addr == p_bda) - return (p_ent); + if (p_ent->in_use && p_ent->inq_info.results.remote_bd_addr == p_bda) { + return p_ent; + } } /* If here, not found */ - return (NULL); + return NULL; } /******************************************************************************* @@ -1225,8 +1203,11 @@ tINQ_DB_ENT* btm_inq_db_new(const RawAddress& p_bda, bool is_ble) { uint32_t ot = 0xFFFFFFFF; int8_t i_rssi = 0; - if (is_ble) yy = BTM_INQ_DB_SIZE / 2; - else yy = 0; + if (is_ble) { + yy = BTM_INQ_DB_SIZE / 2; + } else { + yy = 0; + } std::lock_guard lock(inq_db_lock_); tINQ_DB_ENT* p_ent = &inq_db_[yy]; @@ -1238,7 +1219,7 @@ tINQ_DB_ENT* btm_inq_db_new(const RawAddress& p_bda, bool is_ble) { p_ent->inq_info.results.remote_bd_addr = p_bda; p_ent->in_use = true; - return (p_ent); + return p_ent; } if (is_inquery_by_rssi()) { @@ -1260,7 +1241,7 @@ tINQ_DB_ENT* btm_inq_db_new(const RawAddress& p_bda, bool is_ble) { p_old->inq_info.results.remote_bd_addr = p_bda; p_old->in_use = true; - return (p_old); + return p_old; } /******************************************************************************* @@ -1287,8 +1268,8 @@ static void btm_process_inq_results_standard(bluetooth::hci::EventView event) { uint16_t clock_offset; const uint8_t* p_eir_data = NULL; - log::debug("Received inquiry result inq_active:0x{:x} state:{}", - btm_cb.btm_inq_vars.inq_active, btm_cb.btm_inq_vars.state); + log::debug("Received inquiry result inq_active:0x{:x} state:{}", btm_cb.btm_inq_vars.inq_active, + btm_cb.btm_inq_vars.state); /* Only process the results if the BR inquiry is still active */ if (!(btm_cb.btm_inq_vars.inq_active & BTM_GENERAL_INQUIRY)) { @@ -1297,16 +1278,14 @@ static void btm_process_inq_results_standard(bluetooth::hci::EventView event) { } auto standard_view = bluetooth::hci::InquiryResultView::Create(event); - log::assert_that(standard_view.IsValid(), - "assert failed: standard_view.IsValid()"); + log::assert_that(standard_view.IsValid(), "assert failed: standard_view.IsValid()"); auto responses = standard_view.GetResponses(); btm_cb.neighbor.classic_inquiry.results += responses.size(); for (const auto& response : responses) { /* Extract inquiry results */ bda = bluetooth::ToRawAddress(response.bd_addr_); - page_scan_rep_mode = - static_cast(response.page_scan_repetition_mode_); + page_scan_rep_mode = static_cast(response.page_scan_repetition_mode_); page_scan_per_mode = 0; // reserved page_scan_mode = 0; // reserved @@ -1330,8 +1309,9 @@ static void btm_process_inq_results_standard(bluetooth::hci::EventView event) { the same inquiry. */ else if (p_i->inq_count == btm_cb.btm_inq_vars.inq_counter && - (p_i->inq_info.results.device_type == BT_DEVICE_TYPE_BREDR)) + (p_i->inq_info.results.device_type == BT_DEVICE_TYPE_BREDR)) { is_new = false; + } p_i->inq_info.results.rssi = BTM_INQ_RES_IGNORE_RSSI; @@ -1358,10 +1338,10 @@ static void btm_process_inq_results_standard(bluetooth::hci::EventView event) { if (p_i->inq_count != btm_cb.btm_inq_vars.inq_counter) { p_cur->device_type = BT_DEVICE_TYPE_BREDR; p_i->scan_rsp = false; - } else + } else { p_cur->device_type |= BT_DEVICE_TYPE_BREDR; - p_i->inq_count = - btm_cb.btm_inq_vars.inq_counter; /* Mark entry for current inquiry */ + } + p_i->inq_count = btm_cb.btm_inq_vars.inq_counter; /* Mark entry for current inquiry */ /* Initialize flag to false. This flag is set/used by application */ p_i->inq_info.appl_knows_rem_name = false; @@ -1372,8 +1352,7 @@ static void btm_process_inq_results_standard(bluetooth::hci::EventView event) { /* If a callback is registered, call it with the results */ if (p_inq_results_cb) { - (p_inq_results_cb)((tBTM_INQ_RESULTS*)p_cur, p_eir_data, - HCI_EXT_INQ_RESPONSE_LEN); + (p_inq_results_cb)((tBTM_INQ_RESULTS*)p_cur, p_eir_data, HCI_EXT_INQ_RESPONSE_LEN); } else { log::warn("No callback is registered for inquiry result"); } @@ -1408,8 +1387,8 @@ static void btm_process_inq_results_rssi(bluetooth::hci::EventView event) { uint16_t clock_offset; const uint8_t* p_eir_data = NULL; - log::debug("Received inquiry result inq_active:0x{:x} state:{}", - btm_cb.btm_inq_vars.inq_active, btm_cb.btm_inq_vars.state); + log::debug("Received inquiry result inq_active:0x{:x} state:{}", btm_cb.btm_inq_vars.inq_active, + btm_cb.btm_inq_vars.state); /* Only process the results if the BR inquiry is still active */ if (!(btm_cb.btm_inq_vars.inq_active & BTM_GENERAL_INQUIRY)) { @@ -1426,8 +1405,7 @@ static void btm_process_inq_results_rssi(bluetooth::hci::EventView event) { update = false; /* Extract inquiry results */ bda = bluetooth::ToRawAddress(response.address_); - page_scan_rep_mode = - static_cast(response.page_scan_repetition_mode_); + page_scan_rep_mode = static_cast(response.page_scan_repetition_mode_); page_scan_per_mode = 0; // reserved page_scan_mode = 0; // reserved @@ -1450,16 +1428,16 @@ static void btm_process_inq_results_rssi(bluetooth::hci::EventView event) { (i_rssi > p_i->inq_info.results.rssi || p_i->inq_info.results.rssi == 0 /* BR/EDR inquiry information update */ - || - (p_i->inq_info.results.device_type & BT_DEVICE_TYPE_BREDR) != 0)) { + || (p_i->inq_info.results.device_type & BT_DEVICE_TYPE_BREDR) != 0)) { p_cur = &p_i->inq_info.results; log::verbose("update RSSI new:{}, old:{}", i_rssi, p_cur->rssi); p_cur->rssi = i_rssi; update = true; } /* If no update needed continue with next response (if any) */ - else + else { continue; + } } /* If existing entry, use that, else get a new one (possibly reusing the @@ -1474,8 +1452,9 @@ static void btm_process_inq_results_rssi(bluetooth::hci::EventView event) { the same inquiry. */ else if (p_i->inq_count == btm_cb.btm_inq_vars.inq_counter && - (p_i->inq_info.results.device_type == BT_DEVICE_TYPE_BREDR)) + (p_i->inq_info.results.device_type == BT_DEVICE_TYPE_BREDR)) { is_new = false; + } /* keep updating RSSI to have latest value */ p_i->inq_info.results.rssi = (int8_t)rssi; @@ -1503,10 +1482,10 @@ static void btm_process_inq_results_rssi(bluetooth::hci::EventView event) { if (p_i->inq_count != btm_cb.btm_inq_vars.inq_counter) { p_cur->device_type = BT_DEVICE_TYPE_BREDR; p_i->scan_rsp = false; - } else + } else { p_cur->device_type |= BT_DEVICE_TYPE_BREDR; - p_i->inq_count = - btm_cb.btm_inq_vars.inq_counter; /* Mark entry for current inquiry */ + } + p_i->inq_count = btm_cb.btm_inq_vars.inq_counter; /* Mark entry for current inquiry */ /* Initialize flag to false. This flag is set/used by application */ p_i->inq_info.appl_knows_rem_name = false; @@ -1517,8 +1496,7 @@ static void btm_process_inq_results_rssi(bluetooth::hci::EventView event) { /* If a callback is registered, call it with the results */ if (p_inq_results_cb) { - (p_inq_results_cb)((tBTM_INQ_RESULTS*)p_cur, p_eir_data, - HCI_EXT_INQ_RESPONSE_LEN); + (p_inq_results_cb)((tBTM_INQ_RESULTS*)p_cur, p_eir_data, HCI_EXT_INQ_RESPONSE_LEN); } else { log::warn("No callback is registered for inquiry result"); } @@ -1552,8 +1530,8 @@ static void btm_process_inq_results_extended(bluetooth::hci::EventView event) { DEV_CLASS dc; uint16_t clock_offset; - log::debug("Received inquiry result inq_active:0x{:x} state:{}", - btm_cb.btm_inq_vars.inq_active, btm_cb.btm_inq_vars.state); + log::debug("Received inquiry result inq_active:0x{:x} state:{}", btm_cb.btm_inq_vars.inq_active, + btm_cb.btm_inq_vars.state); /* Only process the results if the BR inquiry is still active */ if (!(btm_cb.btm_inq_vars.inq_active & BTM_GENERAL_INQUIRY)) { @@ -1562,16 +1540,14 @@ static void btm_process_inq_results_extended(bluetooth::hci::EventView event) { } auto extended_view = bluetooth::hci::ExtendedInquiryResultView::Create(event); - log::assert_that(extended_view.IsValid(), - "assert failed: extended_view.IsValid()"); + log::assert_that(extended_view.IsValid(), "assert failed: extended_view.IsValid()"); btm_cb.neighbor.classic_inquiry.results++; { update = false; /* Extract inquiry results */ bda = bluetooth::ToRawAddress(extended_view.GetAddress()); - page_scan_rep_mode = - static_cast(extended_view.GetPageScanRepetitionMode()); + page_scan_rep_mode = static_cast(extended_view.GetPageScanRepetitionMode()); page_scan_per_mode = 0; // reserved dc[0] = extended_view.GetClassOfDevice().cod[2]; @@ -1592,8 +1568,7 @@ static void btm_process_inq_results_extended(bluetooth::hci::EventView event) { (i_rssi > p_i->inq_info.results.rssi || p_i->inq_info.results.rssi == 0 /* BR/EDR inquiry information update */ - || - (p_i->inq_info.results.device_type & BT_DEVICE_TYPE_BREDR) != 0)) { + || (p_i->inq_info.results.device_type & BT_DEVICE_TYPE_BREDR) != 0)) { p_cur = &p_i->inq_info.results; log::verbose("update RSSI new:{}, old:{}", i_rssi, p_cur->rssi); p_cur->rssi = i_rssi; @@ -1607,8 +1582,9 @@ static void btm_process_inq_results_extended(bluetooth::hci::EventView event) { update = true; } /* If no update needed continue with next response (if any) */ - else + else { return; + } } /* If existing entry, use that, else get a new one (possibly reusing the @@ -1625,8 +1601,9 @@ static void btm_process_inq_results_extended(bluetooth::hci::EventView event) { inquiry. */ else if (p_i->inq_count == btm_cb.btm_inq_vars.inq_counter && - (p_i->inq_info.results.device_type == BT_DEVICE_TYPE_BREDR)) + (p_i->inq_info.results.device_type == BT_DEVICE_TYPE_BREDR)) { is_new = false; + } /* keep updating RSSI to have latest value */ p_i->inq_info.results.rssi = (int8_t)rssi; @@ -1654,10 +1631,10 @@ static void btm_process_inq_results_extended(bluetooth::hci::EventView event) { if (p_i->inq_count != btm_cb.btm_inq_vars.inq_counter) { p_cur->device_type = BT_DEVICE_TYPE_BREDR; p_i->scan_rsp = false; - } else + } else { p_cur->device_type |= BT_DEVICE_TYPE_BREDR; - p_i->inq_count = - btm_cb.btm_inq_vars.inq_counter; /* Mark entry for current inquiry */ + } + p_i->inq_count = btm_cb.btm_inq_vars.inq_counter; /* Mark entry for current inquiry */ /* Initialize flag to false. This flag is set/used by application */ p_i->inq_info.appl_knows_rem_name = false; @@ -1680,16 +1657,14 @@ static void btm_process_inq_results_extended(bluetooth::hci::EventView event) { const uint8_t* p_eir_data = data.data(); { - memset(p_cur->eir_uuid, 0, - BTM_EIR_SERVICE_ARRAY_SIZE * (BTM_EIR_ARRAY_BITS / 8)); + memset(p_cur->eir_uuid, 0, BTM_EIR_SERVICE_ARRAY_SIZE * (BTM_EIR_ARRAY_BITS / 8)); /* set bit map of UUID list from received EIR */ btm_set_eir_uuid(p_eir_data, p_cur); } /* If a callback is registered, call it with the results */ if (p_inq_results_cb) { - (p_inq_results_cb)((tBTM_INQ_RESULTS*)p_cur, p_eir_data, - HCI_EXT_INQ_RESPONSE_LEN); + (p_inq_results_cb)((tBTM_INQ_RESULTS*)p_cur, p_eir_data, HCI_EXT_INQ_RESPONSE_LEN); } else { log::warn("No callback is registered for inquiry result"); } @@ -1716,8 +1691,8 @@ void btm_sort_inq_result(void) { tINQ_DB_ENT* p_tmp = (tINQ_DB_ENT*)osi_malloc(sizeof(tINQ_DB_ENT)); num_resp = (btm_cb.btm_inq_vars.inq_cmpl_info.num_resp < BTM_INQ_DB_SIZE) - ? btm_cb.btm_inq_vars.inq_cmpl_info.num_resp - : BTM_INQ_DB_SIZE; + ? btm_cb.btm_inq_vars.inq_cmpl_info.num_resp + : BTM_INQ_DB_SIZE; size = sizeof(tINQ_DB_ENT); for (xx = 0; xx < num_resp - 1; xx++, p_ent++) { @@ -1752,8 +1727,7 @@ void btm_process_inq_complete(tHCI_STATUS status, uint8_t mode) { btm_cb.btm_inq_vars.inqparms.mode &= ~(mode); const auto inq_active = btm_cb.btm_inq_vars.inq_active; - BTIF_dm_report_inquiry_status_change( - tBTM_INQUIRY_STATE::BTM_INQUIRY_COMPLETE); + BTIF_dm_report_inquiry_status_change(tBTM_INQUIRY_STATE::BTM_INQUIRY_COMPLETE); if (status != HCI_SUCCESS) { log::warn("Received unexpected hci status:{}", hci_error_code_text(status)); @@ -1780,42 +1754,33 @@ void btm_process_inq_complete(tHCI_STATUS status, uint8_t mode) { } if (btm_cb.btm_inq_vars.p_inq_cmpl_cb) { - (btm_cb.btm_inq_vars.p_inq_cmpl_cb)( - (tBTM_INQUIRY_CMPL*)&btm_cb.btm_inq_vars.inq_cmpl_info); + (btm_cb.btm_inq_vars.p_inq_cmpl_cb)((tBTM_INQUIRY_CMPL*)&btm_cb.btm_inq_vars.inq_cmpl_info); } else { log::warn("No callback to return inquiry result"); } btm_cb.neighbor.inquiry_history_->Push({ - .status = tBTM_INQUIRY_CMPL::TIMER_POPPED, - .num_resp = btm_cb.btm_inq_vars.inq_cmpl_info.num_resp, - .resp_type = - { - btm_cb.btm_inq_vars.inq_cmpl_info - .resp_type[BTM_INQ_RESULT_STANDARD], - btm_cb.btm_inq_vars.inq_cmpl_info - .resp_type[BTM_INQ_RESULT_WITH_RSSI], - btm_cb.btm_inq_vars.inq_cmpl_info - .resp_type[BTM_INQ_RESULT_EXTENDED], - }, - .start_time_ms = btm_cb.neighbor.classic_inquiry.start_time_ms, + .status = tBTM_INQUIRY_CMPL::TIMER_POPPED, + .num_resp = btm_cb.btm_inq_vars.inq_cmpl_info.num_resp, + .resp_type = + { + btm_cb.btm_inq_vars.inq_cmpl_info.resp_type[BTM_INQ_RESULT_STANDARD], + btm_cb.btm_inq_vars.inq_cmpl_info.resp_type[BTM_INQ_RESULT_WITH_RSSI], + btm_cb.btm_inq_vars.inq_cmpl_info.resp_type[BTM_INQ_RESULT_EXTENDED], + }, + .start_time_ms = btm_cb.neighbor.classic_inquiry.start_time_ms, }); const auto end_time_ms = timestamper_in_milliseconds.GetTimestamp(); - BTM_LogHistory( - kBtmLogTag, RawAddress::kEmpty, "Classic inquiry complete", - base::StringPrintf( - "duration_s:%6.3f results:%lu inq_active:0x%02x std:%u rssi:%u " - "ext:%u status:%s", - (end_time_ms - btm_cb.neighbor.classic_inquiry.start_time_ms) / - 1000.0, - btm_cb.neighbor.classic_inquiry.results, inq_active, - btm_cb.btm_inq_vars.inq_cmpl_info - .resp_type[BTM_INQ_RESULT_STANDARD], - btm_cb.btm_inq_vars.inq_cmpl_info - .resp_type[BTM_INQ_RESULT_WITH_RSSI], - btm_cb.btm_inq_vars.inq_cmpl_info - .resp_type[BTM_INQ_RESULT_EXTENDED], - hci_error_code_text(status).c_str())); + BTM_LogHistory(kBtmLogTag, RawAddress::kEmpty, "Classic inquiry complete", + base::StringPrintf( + "duration_s:%6.3f results:%lu inq_active:0x%02x std:%u rssi:%u " + "ext:%u status:%s", + (end_time_ms - btm_cb.neighbor.classic_inquiry.start_time_ms) / 1000.0, + btm_cb.neighbor.classic_inquiry.results, inq_active, + btm_cb.btm_inq_vars.inq_cmpl_info.resp_type[BTM_INQ_RESULT_STANDARD], + btm_cb.btm_inq_vars.inq_cmpl_info.resp_type[BTM_INQ_RESULT_WITH_RSSI], + btm_cb.btm_inq_vars.inq_cmpl_info.resp_type[BTM_INQ_RESULT_EXTENDED], + hci_error_code_text(status).c_str())); btm_cb.neighbor.classic_inquiry.start_time_ms = 0; /* Clear the results callback if set */ @@ -1824,9 +1789,8 @@ void btm_process_inq_complete(tHCI_STATUS status, uint8_t mode) { btm_cb.btm_inq_vars.p_inq_cmpl_cb = NULL; } else { - log::info( - "Inquiry params is not clear so not sending callback inq_parms:{}", - btm_cb.btm_inq_vars.inqparms.mode); + log::info("Inquiry params is not clear so not sending callback inq_parms:{}", + btm_cb.btm_inq_vars.inqparms.mode); } } else { log::error("Received inquiry complete when no inquiry was active"); @@ -1846,8 +1810,7 @@ void btm_process_inq_complete(tHCI_STATUS status, uint8_t mode) { * ******************************************************************************/ static void btm_process_cancel_complete(tHCI_STATUS status, uint8_t mode) { - BTIF_dm_report_inquiry_status_change( - tBTM_INQUIRY_STATE::BTM_INQUIRY_CANCELLED); + BTIF_dm_report_inquiry_status_change(tBTM_INQUIRY_STATE::BTM_INQUIRY_CANCELLED); btm_process_inq_complete(status, mode); } /******************************************************************************* @@ -1874,22 +1837,20 @@ static void btm_process_cancel_complete(tHCI_STATUS status, uint8_t mode) { * BTM_WRONG_MODE if the device is not up. * ******************************************************************************/ -tBTM_STATUS btm_initiate_rem_name(const RawAddress& remote_bda, - uint64_t timeout_ms, +tBTM_STATUS btm_initiate_rem_name(const RawAddress& remote_bda, uint64_t timeout_ms, tBTM_NAME_CMPL_CB* p_cb) { /*** Make sure the device is ready ***/ if (!get_btm_client_interface().local.BTM_IsDeviceUp()) { return BTM_WRONG_MODE; } if (btm_cb.rnr.remname_active) { - return (BTM_BUSY); + return BTM_BUSY; } else { /* If the database entry exists for the device, use its clock offset */ tINQ_DB_ENT* p_i = btm_inq_db_find(remote_bda); if (p_i && (p_i->inq_info.results.inq_result_type & BT_DEVICE_TYPE_BREDR)) { tBTM_INQ_INFO* p_cur = &p_i->inq_info; - uint16_t clock_offset = - p_cur->results.clock_offset | BTM_CLOCK_OFFSET_VALID; + uint16_t clock_offset = p_cur->results.clock_offset | BTM_CLOCK_OFFSET_VALID; int clock_offset_in_cfg = 0; if (0 == (p_cur->results.clock_offset & BTM_CLOCK_OFFSET_VALID)) { if (btif_get_device_clockoffset(remote_bda, &clock_offset_in_cfg)) { @@ -1897,27 +1858,24 @@ tBTM_STATUS btm_initiate_rem_name(const RawAddress& remote_bda, } } uint8_t page_scan_rep_mode = p_cur->results.page_scan_rep_mode; - if (com::android::bluetooth::flags:: - rnr_validate_page_scan_repetition_mode() && + if (com::android::bluetooth::flags::rnr_validate_page_scan_repetition_mode() && page_scan_rep_mode >= HCI_PAGE_SCAN_REP_MODE_RESERVED_START) { log::info( - "Invalid page scan repetition mode {} from remote_bda:{}, " - "fallback to R1", - page_scan_rep_mode, remote_bda); + "Invalid page scan repetition mode {} from remote_bda:{}, " + "fallback to R1", + page_scan_rep_mode, remote_bda); page_scan_rep_mode = HCI_PAGE_SCAN_REP_MODE_R1; } bluetooth::shim::ACL_RemoteNameRequest(remote_bda, page_scan_rep_mode, - p_cur->results.page_scan_mode, - clock_offset); + p_cur->results.page_scan_mode, clock_offset); } else { uint16_t clock_offset = 0; int clock_offset_in_cfg = 0; if (btif_get_device_clockoffset(remote_bda, &clock_offset_in_cfg)) { clock_offset = clock_offset_in_cfg; } - bluetooth::shim::ACL_RemoteNameRequest( - remote_bda, HCI_PAGE_SCAN_REP_MODE_R1, HCI_MANDATARY_PAGE_SCAN_MODE, - clock_offset); + bluetooth::shim::ACL_RemoteNameRequest(remote_bda, HCI_PAGE_SCAN_REP_MODE_R1, + HCI_MANDATARY_PAGE_SCAN_MODE, clock_offset); } btm_cb.rnr.p_remname_cmpl_cb = p_cb; @@ -1943,13 +1901,13 @@ tBTM_STATUS btm_initiate_rem_name(const RawAddress& remote_bda, * Returns void * ******************************************************************************/ -void btm_process_remote_name(const RawAddress* bda, const BD_NAME bdn, - uint16_t /* evt_len */, tHCI_STATUS hci_status) { +void btm_process_remote_name(const RawAddress* bda, const BD_NAME bdn, uint16_t /* evt_len */, + tHCI_STATUS hci_status) { tBTM_REMOTE_DEV_NAME rem_name = { - .status = BTM_BAD_VALUE_RET, - .bd_addr = bda ? *bda : RawAddress::kEmpty, - .remote_bd_name = {}, - .hci_status = hci_status, + .status = BTM_BAD_VALUE_RET, + .bd_addr = bda ? *bda : RawAddress::kEmpty, + .remote_bd_name = {}, + .hci_status = hci_status, }; bool on_le_link; @@ -1963,10 +1921,9 @@ void btm_process_remote_name(const RawAddress* bda, const BD_NAME bdn, * the active to false */ if (btm_cb.rnr.remname_active) { if (rem_name.bd_addr == RawAddress::kEmpty || rem_name.bd_addr == btm_cb.rnr.remname_bda) { - log::info( - "RNR received expected name bd_addr:{} hci_status:{} le_link:{}", - rem_name.bd_addr.ToRedactedStringForLogging(), - hci_status_code_text(hci_status), on_le_link); + log::info("RNR received expected name bd_addr:{} hci_status:{} le_link:{}", + rem_name.bd_addr.ToRedactedStringForLogging(), hci_status_code_text(hci_status), + on_le_link); if (on_le_link && hci_status == HCI_ERR_UNSPECIFIED) { btm_ble_cancel_remote_name(btm_cb.rnr.remname_bda); @@ -1995,11 +1952,13 @@ void btm_process_remote_name(const RawAddress* bda, const BD_NAME bdn, tBTM_NAME_CMPL_CB* p_cb = btm_cb.rnr.p_remname_cmpl_cb; btm_cb.rnr.p_remname_cmpl_cb = nullptr; - if (p_cb) (p_cb)(&rem_name); + if (p_cb) { + (p_cb)(&rem_name); + } } else { log::warn("RNR received UNKNOWN name bd_addr:{} hci_status:{} le_link:{}", - rem_name.bd_addr.ToRedactedStringForLogging(), - hci_status_code_text(hci_status), on_le_link); + rem_name.bd_addr.ToRedactedStringForLogging(), hci_status_code_text(hci_status), + on_le_link); } } else { log::info( @@ -2011,9 +1970,7 @@ void btm_process_remote_name(const RawAddress* bda, const BD_NAME bdn, } } -void btm_inq_remote_name_timer_timeout(void* /* data */) { - btm_inq_rmt_name_failed_cancelled(); -} +void btm_inq_remote_name_timer_timeout(void* /* data */) { btm_inq_rmt_name_failed_cancelled(); } /******************************************************************************* * @@ -2100,10 +2057,11 @@ bool BTM_HasEirService(const uint32_t* p_eir_uuid, uint16_t uuid16) { uint8_t service_id; service_id = btm_convert_uuid_to_eir_service(uuid16); - if (service_id < BTM_EIR_MAX_SERVICES) - return (BTM_EIR_HAS_SERVICE(p_eir_uuid, service_id)); - else - return (false); + if (service_id < BTM_EIR_MAX_SERVICES) { + return BTM_EIR_HAS_SERVICE(p_eir_uuid, service_id); + } else { + return false; + } } /******************************************************************************* @@ -2123,8 +2081,9 @@ void BTM_AddEirService(uint32_t* p_eir_uuid, uint16_t uuid16) { uint8_t service_id; service_id = btm_convert_uuid_to_eir_service(uuid16); - if (service_id < BTM_EIR_MAX_SERVICES) + if (service_id < BTM_EIR_MAX_SERVICES) { BTM_EIR_SET_SERVICE(p_eir_uuid, service_id); + } } /******************************************************************************* @@ -2144,8 +2103,9 @@ void BTM_RemoveEirService(uint32_t* p_eir_uuid, uint16_t uuid16) { uint8_t service_id; service_id = btm_convert_uuid_to_eir_service(uuid16); - if (service_id < BTM_EIR_MAX_SERVICES) + if (service_id < BTM_EIR_MAX_SERVICES) { BTM_EIR_CLR_SERVICE(p_eir_uuid, service_id); + } } /******************************************************************************* @@ -2164,15 +2124,13 @@ void BTM_RemoveEirService(uint32_t* p_eir_uuid, uint16_t uuid16) { * HCI_EIR_COMPLETE_16BITS_UUID_TYPE, otherwise * ******************************************************************************/ -uint8_t BTM_GetEirSupportedServices(uint32_t* p_eir_uuid, uint8_t** p, - uint8_t max_num_uuid16, +uint8_t BTM_GetEirSupportedServices(uint32_t* p_eir_uuid, uint8_t** p, uint8_t max_num_uuid16, uint8_t* p_num_uuid16) { uint8_t service_index; *p_num_uuid16 = 0; - for (service_index = 0; service_index < BTM_EIR_MAX_SERVICES; - service_index++) { + for (service_index = 0; service_index < BTM_EIR_MAX_SERVICES; service_index++) { if (BTM_EIR_HAS_SERVICE(p_eir_uuid, service_index)) { if (*p_num_uuid16 < max_num_uuid16) { UINT16_TO_STREAM(*p, BTM_EIR_UUID_LKUP_TBL[service_index]); @@ -2210,9 +2168,8 @@ uint8_t BTM_GetEirSupportedServices(uint32_t* p_eir_uuid, uint8_t** p, * HCI_EIR_MORE_128BITS_UUID_TYPE * ******************************************************************************/ -uint8_t BTM_GetEirUuidList(const uint8_t* p_eir, size_t eir_len, - uint8_t uuid_size, uint8_t* p_num_uuid, - uint8_t* p_uuid_list, uint8_t max_num_uuid) { +uint8_t BTM_GetEirUuidList(const uint8_t* p_eir, size_t eir_len, uint8_t uuid_size, + uint8_t* p_num_uuid, uint8_t* p_uuid_list, uint8_t max_num_uuid) { const uint8_t* p_uuid_data; uint8_t type; uint8_t yy, xx; @@ -2220,15 +2177,13 @@ uint8_t BTM_GetEirUuidList(const uint8_t* p_eir, size_t eir_len, uint32_t* p_uuid32 = (uint32_t*)p_uuid_list; char buff[Uuid::kNumBytes128 * 2 + 1]; - p_uuid_data = - btm_eir_get_uuid_list(p_eir, eir_len, uuid_size, p_num_uuid, &type); + p_uuid_data = btm_eir_get_uuid_list(p_eir, eir_len, uuid_size, p_num_uuid, &type); if (p_uuid_data == NULL) { return 0x00; } if (*p_num_uuid > max_num_uuid) { - log::warn("number of uuid in EIR = {}, size of uuid list = {}", *p_num_uuid, - max_num_uuid); + log::warn("number of uuid in EIR = {}, size of uuid list = {}", *p_num_uuid, max_num_uuid); *p_num_uuid = max_num_uuid; } @@ -2247,9 +2202,10 @@ uint8_t BTM_GetEirUuidList(const uint8_t* p_eir, size_t eir_len, } else if (uuid_size == Uuid::kNumBytes128) { for (yy = 0; yy < *p_num_uuid; yy++) { STREAM_TO_ARRAY16(p_uuid_list + yy * Uuid::kNumBytes128, p_uuid_data); - for (xx = 0; xx < Uuid::kNumBytes128; xx++) + for (xx = 0; xx < Uuid::kNumBytes128; xx++) { snprintf(buff + xx * 2, sizeof(buff) - xx * 2, "%02X", *(p_uuid_list + yy * Uuid::kNumBytes128 + xx)); + } log::verbose("0x{}", buff); } } @@ -2273,10 +2229,8 @@ uint8_t BTM_GetEirUuidList(const uint8_t* p_eir, size_t eir_len, * beginning of UUID list in EIR - otherwise * ******************************************************************************/ -static const uint8_t* btm_eir_get_uuid_list(const uint8_t* p_eir, - size_t eir_len, uint8_t uuid_size, - uint8_t* p_num_uuid, - uint8_t* p_uuid_list_type) { +static const uint8_t* btm_eir_get_uuid_list(const uint8_t* p_eir, size_t eir_len, uint8_t uuid_size, + uint8_t* p_num_uuid, uint8_t* p_uuid_list_type) { const uint8_t* p_uuid_data; uint8_t complete_type, more_type; uint8_t uuid_len; @@ -2300,11 +2254,9 @@ static const uint8_t* btm_eir_get_uuid_list(const uint8_t* p_eir, break; } - p_uuid_data = AdvertiseDataParser::GetFieldByType(p_eir, eir_len, - complete_type, &uuid_len); + p_uuid_data = AdvertiseDataParser::GetFieldByType(p_eir, eir_len, complete_type, &uuid_len); if (p_uuid_data == NULL) { - p_uuid_data = AdvertiseDataParser::GetFieldByType(p_eir, eir_len, more_type, - &uuid_len); + p_uuid_data = AdvertiseDataParser::GetFieldByType(p_eir, eir_len, more_type, &uuid_len); *p_uuid_list_type = more_type; } else { *p_uuid_list_type = complete_type; @@ -2327,11 +2279,10 @@ static const uint8_t* btm_eir_get_uuid_list(const uint8_t* p_eir, * UUID 16-bit - otherwise * ******************************************************************************/ -static uint16_t btm_convert_uuid_to_uuid16(const uint8_t* p_uuid, - uint8_t uuid_size) { - static const uint8_t base_uuid[Uuid::kNumBytes128] = { - 0xFB, 0x34, 0x9B, 0x5F, 0x80, 0x00, 0x00, 0x80, - 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; +static uint16_t btm_convert_uuid_to_uuid16(const uint8_t* p_uuid, uint8_t uuid_size) { + static const uint8_t base_uuid[Uuid::kNumBytes128] = {0xFB, 0x34, 0x9B, 0x5F, 0x80, 0x00, + 0x00, 0x80, 0x00, 0x10, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00}; uint16_t uuid16 = 0; uint32_t uuid32; bool is_base_uuid; @@ -2343,7 +2294,9 @@ static uint16_t btm_convert_uuid_to_uuid16(const uint8_t* p_uuid, break; case Uuid::kNumBytes32: STREAM_TO_UINT32(uuid32, p_uuid); - if (uuid32 < 0x10000) uuid16 = (uint16_t)uuid32; + if (uuid32 < 0x10000) { + uuid16 = (uint16_t)uuid32; + } break; case Uuid::kNumBytes128: /* See if we can compress the UUID down to 16 or 32bit UUIDs */ @@ -2355,8 +2308,7 @@ static uint16_t btm_convert_uuid_to_uuid16(const uint8_t* p_uuid, } } if (is_base_uuid) { - if ((p_uuid[Uuid::kNumBytes128 - 1] == 0) && - (p_uuid[Uuid::kNumBytes128 - 2] == 0)) { + if ((p_uuid[Uuid::kNumBytes128 - 1] == 0) && (p_uuid[Uuid::kNumBytes128 - 2] == 0)) { p_uuid += (Uuid::kNumBytes128 - 4); STREAM_TO_UINT16(uuid16, p_uuid); } @@ -2367,7 +2319,7 @@ static uint16_t btm_convert_uuid_to_uuid16(const uint8_t* p_uuid, break; } - return (uuid16); + return uuid16; } /******************************************************************************* @@ -2390,8 +2342,8 @@ void btm_set_eir_uuid(const uint8_t* p_eir, tBTM_INQ_RESULTS* p_results) { uint8_t yy; uint8_t type = HCI_EIR_MORE_16BITS_UUID_TYPE; - p_uuid_data = btm_eir_get_uuid_list(p_eir, HCI_EXT_INQ_RESPONSE_LEN, - Uuid::kNumBytes16, &num_uuid, &type); + p_uuid_data = btm_eir_get_uuid_list(p_eir, HCI_EXT_INQ_RESPONSE_LEN, Uuid::kNumBytes16, &num_uuid, + &type); if (type == HCI_EIR_COMPLETE_16BITS_UUID_TYPE) { p_results->eir_complete_list = true; @@ -2408,23 +2360,27 @@ void btm_set_eir_uuid(const uint8_t* p_eir, tBTM_INQ_RESULTS* p_results) { } } - p_uuid_data = btm_eir_get_uuid_list(p_eir, HCI_EXT_INQ_RESPONSE_LEN, - Uuid::kNumBytes32, &num_uuid, &type); + p_uuid_data = btm_eir_get_uuid_list(p_eir, HCI_EXT_INQ_RESPONSE_LEN, Uuid::kNumBytes32, &num_uuid, + &type); if (p_uuid_data) { for (yy = 0; yy < num_uuid; yy++) { uuid16 = btm_convert_uuid_to_uuid16(p_uuid_data, Uuid::kNumBytes32); p_uuid_data += Uuid::kNumBytes32; - if (uuid16) BTM_AddEirService(p_results->eir_uuid, uuid16); + if (uuid16) { + BTM_AddEirService(p_results->eir_uuid, uuid16); + } } } - p_uuid_data = btm_eir_get_uuid_list(p_eir, HCI_EXT_INQ_RESPONSE_LEN, - Uuid::kNumBytes128, &num_uuid, &type); + p_uuid_data = btm_eir_get_uuid_list(p_eir, HCI_EXT_INQ_RESPONSE_LEN, Uuid::kNumBytes128, + &num_uuid, &type); if (p_uuid_data) { for (yy = 0; yy < num_uuid; yy++) { uuid16 = btm_convert_uuid_to_uuid16(p_uuid_data, Uuid::kNumBytes128); p_uuid_data += Uuid::kNumBytes128; - if (uuid16) BTM_AddEirService(p_results->eir_uuid, uuid16); + if (uuid16) { + BTM_AddEirService(p_results->eir_uuid, uuid16); + } } } } @@ -2464,8 +2420,7 @@ static void on_incoming_hci_event(bluetooth::hci::EventView event) { btm_process_inq_results_extended(event); break; default: - log::warn("Dropping unhandled event: {}", - bluetooth::hci::EventCodeText(event_code)); + log::warn("Dropping unhandled event: {}", bluetooth::hci::EventCodeText(event_code)); } } diff --git a/system/stack/btm/btm_int_types.h b/system/stack/btm/btm_int_types.h index dafb7b2448e..2bf2daf2a74 100644 --- a/system/stack/btm/btm_int_types.h +++ b/system/stack/btm/btm_int_types.h @@ -43,26 +43,24 @@ extern bluetooth::common::TimestamperInMilliseconds timestamper_in_milliseconds; class TimestampedStringCircularBuffer : public bluetooth::common::TimestampedCircularBuffer { - public: +public: explicit TimestampedStringCircularBuffer(size_t size) : bluetooth::common::TimestampedCircularBuffer(size) {} void Push(const std::string& s) { - bluetooth::common::TimestampedCircularBuffer::Push( - s.substr(0, kMaxLogSize)); + bluetooth::common::TimestampedCircularBuffer::Push(s.substr(0, kMaxLogSize)); } template void Push(Args... args) { char buf[kMaxLogSize]; std::snprintf(buf, sizeof(buf), args...); - bluetooth::common::TimestampedCircularBuffer::Push( - std::string(buf)); + bluetooth::common::TimestampedCircularBuffer::Push(std::string(buf)); } }; /* Define a structure to hold all the BTM data -*/ + */ /* Define the Device Management control structure */ @@ -75,14 +73,13 @@ typedef struct tBTM_DEVCB { tBTM_CMPL_CB* p_rssi_cmpl_cb; /* Callback function to be called when */ /* read RSSI function completes */ - alarm_t* read_failed_contact_counter_timer; /* Read Failed Contact Counter */ - /* timer */ + alarm_t* read_failed_contact_counter_timer; /* Read Failed Contact Counter */ + /* timer */ tBTM_CMPL_CB* p_failed_contact_counter_cmpl_cb; /* Callback function to be */ /* called when read Failed Contact Counter function completes */ - alarm_t* - read_automatic_flush_timeout_timer; /* Read Automatic Flush Timeout */ - /* timer */ + alarm_t* read_automatic_flush_timeout_timer; /* Read Automatic Flush Timeout */ + /* timer */ tBTM_CMPL_CB* p_automatic_flush_timeout_cmpl_cb; /* Callback function to be */ /* called when read Automatic Flush Timeout function completes */ @@ -91,19 +88,16 @@ typedef struct tBTM_DEVCB { DEV_CLASS dev_class; /* Local device class */ - tBTM_CMPL_CB* - p_le_test_cmd_cmpl_cb; /* Callback function to be called when - LE test mode command has been sent successfully */ + tBTM_CMPL_CB* p_le_test_cmd_cmpl_cb; /* Callback function to be called when + LE test mode command has been sent successfully */ RawAddress read_tx_pwr_addr; /* read TX power target address */ void Init() { read_local_name_timer = alarm_new("btm.read_local_name_timer"); read_rssi_timer = alarm_new("btm.read_rssi_timer"); - read_failed_contact_counter_timer = - alarm_new("btm.read_failed_contact_counter_timer"); - read_automatic_flush_timeout_timer = - alarm_new("btm.read_automatic_flush_timeout_timer"); + read_failed_contact_counter_timer = alarm_new("btm.read_failed_contact_counter_timer"); + read_automatic_flush_timeout_timer = alarm_new("btm.read_automatic_flush_timeout_timer"); read_tx_power_timer = alarm_new("btm.read_tx_power_timer"); } @@ -127,7 +121,7 @@ typedef struct tBTM_CB { *****************************************************/ tBTM_BLE_CB ble_ctr_cb; - public: +public: tBTM_BLE_VSC_CB cmn_ble_vsc_cb; /* Packet types supported by the local device */ @@ -143,15 +137,14 @@ typedef struct tBTM_CB { *****************************************************/ tSCO_CB sco_cb; - uint16_t disc_handle{0}; /* for legacy devices */ - uint8_t disc_reason{0}; /* for legacy devices */ + uint16_t disc_handle{0}; /* for legacy devices */ + uint8_t disc_reason{0}; /* for legacy devices */ fixed_queue_t* sec_pending_q{nullptr}; /* pending sequrity requests in tBTM_SEC_QUEUE_ENTRY format */ #define BTM_CODEC_TYPE_MAX_RECORDS 32 - tBTM_BT_DYNAMIC_AUDIO_BUFFER_CB - dynamic_audio_buffer_cb[BTM_CODEC_TYPE_MAX_RECORDS]; + tBTM_BT_DYNAMIC_AUDIO_BUFFER_CB dynamic_audio_buffer_cb[BTM_CODEC_TYPE_MAX_RECORDS]; tACL_CB acl_cb_; @@ -162,11 +155,10 @@ typedef struct tBTM_CB { long long start_time_ms; unsigned long results; } classic_inquiry, le_scan, le_inquiry, le_observe, le_legacy_scan; - std::unique_ptr< - bluetooth::common::TimestampedCircularBuffer> - inquiry_history_ = std::make_unique< - bluetooth::common::TimestampedCircularBuffer>( - kMaxInquiryScanHistory); + std::unique_ptr> + inquiry_history_ = std::make_unique< + bluetooth::common::TimestampedCircularBuffer>( + kMaxInquiryScanHistory); } neighbor; bluetooth::rnr::RemoteNameRequest rnr; @@ -188,10 +180,8 @@ typedef struct tBTM_CB { sco_cb.Init(); /* SCO Database and Structures (If included) */ devcb.Init(); - history_ = std::make_shared( - kBtmLogHistoryBufferSize); - bluetooth::log::assert_that(history_ != nullptr, - "assert failed: history_ != nullptr"); + history_ = std::make_shared(kBtmLogHistoryBufferSize); + bluetooth::log::assert_that(history_ != nullptr, "assert failed: history_ != nullptr"); history_->Push(std::string("Initialized btm history")); } diff --git a/system/stack/btm/btm_iot_config.cc b/system/stack/btm/btm_iot_config.cc index c6ea9d8e4ee..8146f6824f1 100644 --- a/system/stack/btm/btm_iot_config.cc +++ b/system/stack/btm/btm_iot_config.cc @@ -48,33 +48,29 @@ void btm_iot_save_remote_properties(tACL_CONN* p_acl_cb) { // save remote name to iot conf file if (BTM_GetRemoteDeviceName(p_acl_cb->remote_addr, bd_name)) { std::string name_str{(char*)bd_name}; - DEVICE_IOT_CONFIG_ADDR_SET_STR(p_acl_cb->remote_addr, - IOT_CONF_KEY_REMOTE_NAME, name_str); + DEVICE_IOT_CONFIG_ADDR_SET_STR(p_acl_cb->remote_addr, IOT_CONF_KEY_REMOTE_NAME, name_str); } /* Try to retrieve cod from storage */ - BTIF_STORAGE_FILL_PROPERTY(&prop_name, BT_PROPERTY_CLASS_OF_DEVICE, - sizeof(cod), &cod); - if (btif_storage_get_remote_device_property(&p_acl_cb->remote_addr, - &prop_name) == BT_STATUS_SUCCESS) + BTIF_STORAGE_FILL_PROPERTY(&prop_name, BT_PROPERTY_CLASS_OF_DEVICE, sizeof(cod), &cod); + if (btif_storage_get_remote_device_property(&p_acl_cb->remote_addr, &prop_name) == + BT_STATUS_SUCCESS) { log::verbose("cod retrieved from storage is 0x{:06x}", cod); + } if (cod == 0) { log::verbose("cod is 0, set as unclassified"); cod = (0x1F) << 8; } - DEVICE_IOT_CONFIG_ADDR_SET_INT(p_acl_cb->remote_addr, IOT_CONF_KEY_DEVCLASS, - (int)cod); + DEVICE_IOT_CONFIG_ADDR_SET_INT(p_acl_cb->remote_addr, IOT_CONF_KEY_DEVCLASS, (int)cod); BTM_ReadDevInfo(p_acl_cb->remote_addr, &dev_type, &addr_type); // save remote dev type to iot conf file - DEVICE_IOT_CONFIG_ADDR_SET_INT(p_acl_cb->remote_addr, IOT_CONF_KEY_DEVTYPE, - (int)dev_type); + DEVICE_IOT_CONFIG_ADDR_SET_INT(p_acl_cb->remote_addr, IOT_CONF_KEY_DEVTYPE, (int)dev_type); // save remote addr type to iot conf file - DEVICE_IOT_CONFIG_ADDR_SET_INT(p_acl_cb->remote_addr, IOT_CONF_KEY_ADDRTYPE, - (int)addr_type); + DEVICE_IOT_CONFIG_ADDR_SET_INT(p_acl_cb->remote_addr, IOT_CONF_KEY_ADDRTYPE, (int)addr_type); // save default recorded value to iot conf file DEVICE_IOT_CONFIG_ADDR_SET_INT(p_acl_cb->remote_addr, IOT_CONF_KEY_RECORDED, @@ -91,8 +87,7 @@ void btm_iot_save_remote_properties(tACL_CONN* p_acl_cb) { * *******************************************************************************/ void btm_iot_save_remote_versions(tACL_CONN* p_acl_cb) { - DEVICE_IOT_CONFIG_ADDR_SET_INT(p_acl_cb->remote_addr, - IOT_CONF_KEY_MANUFACTURER, + DEVICE_IOT_CONFIG_ADDR_SET_INT(p_acl_cb->remote_addr, IOT_CONF_KEY_MANUFACTURER, p_acl_cb->remote_version_info.manufacturer); DEVICE_IOT_CONFIG_ADDR_SET_INT(p_acl_cb->remote_addr, IOT_CONF_KEY_LMPVER, p_acl_cb->remote_version_info.lmp_version); diff --git a/system/stack/btm/btm_iso.cc b/system/stack/btm/btm_iso.cc index e8eeec3a59b..53b92bccaf2 100644 --- a/system/stack/btm/btm_iso.cc +++ b/system/stack/btm/btm_iso.cc @@ -32,19 +32,19 @@ struct IsoManager::impl { impl(const IsoManager& iso_manager) : iso_manager_(iso_manager) {} void Start() { - log::assert_that(iso_impl_ == nullptr, - "assert failed: iso_impl_ == nullptr"); + log::assert_that(iso_impl_ == nullptr, "assert failed: iso_impl_ == nullptr"); iso_impl_ = std::make_unique(); } void Stop() { - log::assert_that(iso_impl_ != nullptr, - "assert failed: iso_impl_ != nullptr"); + log::assert_that(iso_impl_ != nullptr, "assert failed: iso_impl_ != nullptr"); iso_impl_.reset(); } void Dump(int fd) { - if (iso_impl_) iso_impl_->dump(fd); + if (iso_impl_) { + iso_impl_->dump(fd); + } } bool IsRunning() { return iso_impl_ ? true : false; } @@ -67,13 +67,11 @@ void IsoManager::RegisterOnIsoTrafficActiveCallback(void callback(bool)) const { pimpl_->iso_impl_->handle_register_on_iso_traffic_active_callback(callback); } -void IsoManager::CreateCig(uint8_t cig_id, - struct iso_manager::cig_create_params cig_params) { +void IsoManager::CreateCig(uint8_t cig_id, struct iso_manager::cig_create_params cig_params) { pimpl_->iso_impl_->create_cig(cig_id, std::move(cig_params)); } -void IsoManager::ReconfigureCig( - uint8_t cig_id, struct iso_manager::cig_create_params cig_params) { +void IsoManager::ReconfigureCig(uint8_t cig_id, struct iso_manager::cig_create_params cig_params) { pimpl_->iso_impl_->reconfigure_cig(cig_id, std::move(cig_params)); } @@ -81,8 +79,7 @@ void IsoManager::RemoveCig(uint8_t cig_id, bool force) { pimpl_->iso_impl_->remove_cig(cig_id, force); } -void IsoManager::EstablishCis( - struct iso_manager::cis_establish_params conn_params) { +void IsoManager::EstablishCis(struct iso_manager::cis_establish_params conn_params) { pimpl_->iso_impl_->establish_cis(std::move(conn_params)); } @@ -90,12 +87,10 @@ void IsoManager::DisconnectCis(uint16_t cis_handle, uint8_t reason) { pimpl_->iso_impl_->disconnect_cis(cis_handle, reason); } -int IsoManager::GetNumberOfActiveIso() { - return pimpl_->iso_impl_->get_number_of_active_iso(); -} +int IsoManager::GetNumberOfActiveIso() { return pimpl_->iso_impl_->get_number_of_active_iso(); } -void IsoManager::SetupIsoDataPath( - uint16_t iso_handle, struct iso_manager::iso_data_path_params path_params) { +void IsoManager::SetupIsoDataPath(uint16_t iso_handle, + struct iso_manager::iso_data_path_params path_params) { pimpl_->iso_impl_->setup_iso_data_path(iso_handle, std::move(path_params)); } @@ -107,54 +102,60 @@ void IsoManager::ReadIsoLinkQuality(uint16_t iso_handle) { pimpl_->iso_impl_->read_iso_link_quality(iso_handle); } -void IsoManager::SendIsoData(uint16_t iso_handle, const uint8_t* data, - uint16_t data_len) { +void IsoManager::SendIsoData(uint16_t iso_handle, const uint8_t* data, uint16_t data_len) { pimpl_->iso_impl_->send_iso_data(iso_handle, data, data_len); } -void IsoManager::CreateBig(uint8_t big_id, - struct iso_manager::big_create_params big_params) { +void IsoManager::CreateBig(uint8_t big_id, struct iso_manager::big_create_params big_params) { pimpl_->iso_impl_->create_big(big_id, std::move(big_params)); } void IsoManager::TerminateBig(uint8_t big_id, uint8_t reason) { - if (pimpl_->IsRunning()) + if (pimpl_->IsRunning()) { pimpl_->iso_impl_->terminate_big(big_id, reason); + } } void IsoManager::HandleIsoData(void* p_msg) { - if (pimpl_->IsRunning()) + if (pimpl_->IsRunning()) { pimpl_->iso_impl_->handle_iso_data(static_cast(p_msg)); + } } void IsoManager::HandleDisconnect(uint16_t handle, uint8_t reason) { - if (pimpl_->IsRunning()) + if (pimpl_->IsRunning()) { pimpl_->iso_impl_->disconnection_complete(handle, reason); + } } void IsoManager::HandleNumComplDataPkts(uint16_t handle, uint16_t credits) { - if (pimpl_->IsRunning()) + if (pimpl_->IsRunning()) { pimpl_->iso_impl_->handle_gd_num_completed_pkts(handle, credits); + } } -void IsoManager::HandleHciEvent(uint8_t sub_code, uint8_t* params, - uint16_t length) { - if (pimpl_->IsRunning()) +void IsoManager::HandleHciEvent(uint8_t sub_code, uint8_t* params, uint16_t length) { + if (pimpl_->IsRunning()) { pimpl_->iso_impl_->on_iso_event(sub_code, params, length); + } } void IsoManager::Start() { - if (!pimpl_->IsRunning()) + if (!pimpl_->IsRunning()) { pimpl_->Start(); + } } void IsoManager::Stop() { - if (pimpl_->IsRunning()) + if (pimpl_->IsRunning()) { pimpl_->Stop(); + } } void IsoManager::Dump(int fd) { - if (pimpl_->IsRunning()) pimpl_->Dump(fd); + if (pimpl_->IsRunning()) { + pimpl_->Dump(fd); + } } IsoManager::~IsoManager() = default; diff --git a/system/stack/btm/btm_iso_impl.h b/system/stack/btm/btm_iso_impl.h index 0b124e9e3ad..a4ee3694ac5 100644 --- a/system/stack/btm/btm_iso_impl.h +++ b/system/stack/btm/btm_iso_impl.h @@ -92,14 +92,10 @@ typedef iso_base iso_bis; struct iso_impl { iso_impl() { - iso_credits_ = shim::GetController() - ->GetControllerIsoBufferSize() - .total_num_le_packets_; - iso_buffer_size_ = shim::GetController() - ->GetControllerIsoBufferSize() - .le_data_packet_length_; - log::info("{} created, iso credits: {}, buffer size: {}.", fmt::ptr(this), - iso_credits_.load(), iso_buffer_size_); + iso_credits_ = shim::GetController()->GetControllerIsoBufferSize().total_num_le_packets_; + iso_buffer_size_ = shim::GetController()->GetControllerIsoBufferSize().le_data_packet_length_; + log::info("{} created, iso credits: {}, buffer size: {}.", fmt::ptr(this), iso_credits_.load(), + iso_buffer_size_); } ~iso_impl() { log::info("{} removed.", fmt::ptr(this)); } @@ -115,15 +111,12 @@ struct iso_impl { } void handle_register_on_iso_traffic_active_callback(void callback(bool)) { - log::assert_that(callback != nullptr, - "Invalid OnIsoTrafficActive callback"); - const std::lock_guard lock( - on_iso_traffic_active_callbacks_list_mutex_); + log::assert_that(callback != nullptr, "Invalid OnIsoTrafficActive callback"); + const std::lock_guard lock(on_iso_traffic_active_callbacks_list_mutex_); on_iso_traffic_active_callbacks_list_.push_back(callback); } - void on_set_cig_params(uint8_t cig_id, uint32_t sdu_itv_mtos, uint8_t* stream, - uint16_t len) { + void on_set_cig_params(uint8_t cig_id, uint32_t sdu_itv_mtos, uint8_t* stream, uint16_t len) { uint8_t cis_cnt; uint16_t conn_handle; cig_create_cmpl_evt evt; @@ -135,27 +128,25 @@ struct iso_impl { STREAM_TO_UINT8(evt.cig_id, stream); STREAM_TO_UINT8(cis_cnt, stream); - uint8_t evt_code = IsCigKnown(cig_id) ? kIsoEventCigOnReconfigureCmpl - : kIsoEventCigOnCreateCmpl; + uint8_t evt_code = + IsCigKnown(cig_id) ? kIsoEventCigOnReconfigureCmpl : kIsoEventCigOnCreateCmpl; - BTM_LogHistory( - kBtmLogTag, RawAddress::kEmpty, "CIG Create complete", - base::StringPrintf( - "cig_id:0x%02x, status: %s", evt.cig_id, - hci_status_code_text((tHCI_STATUS)(evt.status)).c_str())); + BTM_LogHistory(kBtmLogTag, RawAddress::kEmpty, "CIG Create complete", + base::StringPrintf("cig_id:0x%02x, status: %s", evt.cig_id, + hci_status_code_text((tHCI_STATUS)(evt.status)).c_str())); if (evt.status == HCI_SUCCESS) { - log::assert_that(len >= (3) + (cis_cnt * sizeof(uint16_t)), - "Invalid CIS count: {}", cis_cnt); + log::assert_that(len >= (3) + (cis_cnt * sizeof(uint16_t)), "Invalid CIS count: {}", cis_cnt); /* Remove entries for the reconfigured CIG */ if (evt_code == kIsoEventCigOnReconfigureCmpl) { auto cis_it = conn_hdl_to_cis_map_.cbegin(); while (cis_it != conn_hdl_to_cis_map_.cend()) { - if (cis_it->second->cig_id == evt.cig_id) + if (cis_it->second->cig_id == evt.cig_id) { cis_it = conn_hdl_to_cis_map_.erase(cis_it); - else + } else { ++cis_it; + } } } @@ -178,44 +169,37 @@ struct iso_impl { cig_callbacks_->OnCigEvent(evt_code, &evt); if (evt_code == kIsoEventCigOnCreateCmpl) { - const std::lock_guard lock( - on_iso_traffic_active_callbacks_list_mutex_); + const std::lock_guard lock(on_iso_traffic_active_callbacks_list_mutex_); for (auto callback : on_iso_traffic_active_callbacks_list_) { callback(true); } } } - void create_cig(uint8_t cig_id, - struct iso_manager::cig_create_params cig_params) { - log::assert_that(!IsCigKnown(cig_id), "Invalid cig - already exists: {}", - cig_id); + void create_cig(uint8_t cig_id, struct iso_manager::cig_create_params cig_params) { + log::assert_that(!IsCigKnown(cig_id), "Invalid cig - already exists: {}", cig_id); btsnd_hcic_set_cig_params( - cig_id, cig_params.sdu_itv_mtos, cig_params.sdu_itv_stom, - cig_params.sca, cig_params.packing, cig_params.framing, - cig_params.max_trans_lat_stom, cig_params.max_trans_lat_mtos, - cig_params.cis_cfgs.size(), cig_params.cis_cfgs.data(), - base::BindOnce(&iso_impl::on_set_cig_params, weak_factory_.GetWeakPtr(), - cig_id, cig_params.sdu_itv_mtos)); + cig_id, cig_params.sdu_itv_mtos, cig_params.sdu_itv_stom, cig_params.sca, + cig_params.packing, cig_params.framing, cig_params.max_trans_lat_stom, + cig_params.max_trans_lat_mtos, cig_params.cis_cfgs.size(), cig_params.cis_cfgs.data(), + base::BindOnce(&iso_impl::on_set_cig_params, weak_factory_.GetWeakPtr(), cig_id, + cig_params.sdu_itv_mtos)); - BTM_LogHistory( - kBtmLogTag, RawAddress::kEmpty, "CIG Create", - base::StringPrintf("cig_id:0x%02x, size: %d", cig_id, - static_cast(cig_params.cis_cfgs.size()))); + BTM_LogHistory(kBtmLogTag, RawAddress::kEmpty, "CIG Create", + base::StringPrintf("cig_id:0x%02x, size: %d", cig_id, + static_cast(cig_params.cis_cfgs.size()))); } - void reconfigure_cig(uint8_t cig_id, - struct iso_manager::cig_create_params cig_params) { + void reconfigure_cig(uint8_t cig_id, struct iso_manager::cig_create_params cig_params) { log::assert_that(IsCigKnown(cig_id), "No such cig: {}", cig_id); btsnd_hcic_set_cig_params( - cig_id, cig_params.sdu_itv_mtos, cig_params.sdu_itv_stom, - cig_params.sca, cig_params.packing, cig_params.framing, - cig_params.max_trans_lat_stom, cig_params.max_trans_lat_mtos, - cig_params.cis_cfgs.size(), cig_params.cis_cfgs.data(), - base::BindOnce(&iso_impl::on_set_cig_params, weak_factory_.GetWeakPtr(), - cig_id, cig_params.sdu_itv_mtos)); + cig_id, cig_params.sdu_itv_mtos, cig_params.sdu_itv_stom, cig_params.sca, + cig_params.packing, cig_params.framing, cig_params.max_trans_lat_stom, + cig_params.max_trans_lat_mtos, cig_params.cis_cfgs.size(), cig_params.cis_cfgs.data(), + base::BindOnce(&iso_impl::on_set_cig_params, weak_factory_.GetWeakPtr(), cig_id, + cig_params.sdu_itv_mtos)); } void on_remove_cig(uint8_t* stream, uint16_t len) { @@ -227,27 +211,25 @@ struct iso_impl { STREAM_TO_UINT8(evt.status, stream); STREAM_TO_UINT8(evt.cig_id, stream); - BTM_LogHistory( - kBtmLogTag, RawAddress::kEmpty, "CIG Remove complete", - base::StringPrintf( - "cig_id:0x%02x, status: %s", evt.cig_id, - hci_status_code_text((tHCI_STATUS)(evt.status)).c_str())); + BTM_LogHistory(kBtmLogTag, RawAddress::kEmpty, "CIG Remove complete", + base::StringPrintf("cig_id:0x%02x, status: %s", evt.cig_id, + hci_status_code_text((tHCI_STATUS)(evt.status)).c_str())); if (evt.status == HCI_SUCCESS) { auto cis_it = conn_hdl_to_cis_map_.cbegin(); while (cis_it != conn_hdl_to_cis_map_.cend()) { - if (cis_it->second->cig_id == evt.cig_id) + if (cis_it->second->cig_id == evt.cig_id) { cis_it = conn_hdl_to_cis_map_.erase(cis_it); - else + } else { ++cis_it; + } } } cig_callbacks_->OnCigEvent(kIsoEventCigOnRemoveCmpl, &evt); { - const std::lock_guard lock( - on_iso_traffic_active_callbacks_list_mutex_); + const std::lock_guard lock(on_iso_traffic_active_callbacks_list_mutex_); for (auto callback : on_iso_traffic_active_callbacks_list_) { callback(false); } @@ -261,15 +243,14 @@ struct iso_impl { log::warn("Forcing to remove CIG {}", cig_id); } - btsnd_hcic_remove_cig(cig_id, base::BindOnce(&iso_impl::on_remove_cig, - weak_factory_.GetWeakPtr())); + btsnd_hcic_remove_cig(cig_id, + base::BindOnce(&iso_impl::on_remove_cig, weak_factory_.GetWeakPtr())); BTM_LogHistory(kBtmLogTag, RawAddress::kEmpty, "CIG Remove", base::StringPrintf("cig_id:0x%02x (f:%d)", cig_id, force)); } - void on_status_establish_cis( - struct iso_manager::cis_establish_params conn_params, uint8_t* stream, - uint16_t len) { + void on_status_establish_cis(struct iso_manager::cis_establish_params conn_params, + uint8_t* stream, uint16_t len) { uint8_t status; log::assert_that(len == 2, "Invalid packet length: {}", len); @@ -281,8 +262,7 @@ struct iso_impl { if (status != HCI_SUCCESS) { auto cis = GetCisIfKnown(cis_param.cis_conn_handle); - log::assert_that(cis != nullptr, "No such cis: {}", - cis_param.cis_conn_handle); + log::assert_that(cis != nullptr, "No such cis: {}", cis_param.cis_conn_handle); evt.status = status; evt.cis_conn_hdl = cis_param.cis_conn_handle; @@ -290,12 +270,9 @@ struct iso_impl { cis->state_flags &= ~kStateFlagIsConnecting; cig_callbacks_->OnCisEvent(kIsoEventCisEstablishCmpl, &evt); - BTM_LogHistory( - kBtmLogTag, cis_hdl_to_addr[evt.cis_conn_hdl], - "Establish CIS failed ", - base::StringPrintf( - "handle:0x%04x, status: %s", evt.cis_conn_hdl, - hci_status_code_text((tHCI_STATUS)(status)).c_str())); + BTM_LogHistory(kBtmLogTag, cis_hdl_to_addr[evt.cis_conn_hdl], "Establish CIS failed ", + base::StringPrintf("handle:0x%04x, status: %s", evt.cis_conn_hdl, + hci_status_code_text((tHCI_STATUS)(status)).c_str())); cis_hdl_to_addr.erase(evt.cis_conn_hdl); } } @@ -305,12 +282,10 @@ struct iso_impl { for (auto& el : conn_params.conn_pairs) { auto cis = GetCisIfKnown(el.cis_conn_handle); log::assert_that(cis, "No such cis: {}", el.cis_conn_handle); - log::assert_that(!(cis->state_flags & - (kStateFlagIsConnected | kStateFlagIsConnecting)), + log::assert_that(!(cis->state_flags & (kStateFlagIsConnected | kStateFlagIsConnecting)), "cis: {} is already connected or connecting flags: {}, " "num of cis params: {}", - el.cis_conn_handle, cis->state_flags, - conn_params.conn_pairs.size()); + el.cis_conn_handle, cis->state_flags, conn_params.conn_pairs.size()); cis->state_flags |= kStateFlagIsConnecting; @@ -321,25 +296,22 @@ struct iso_impl { base::StringPrintf("handle:0x%04x", el.acl_conn_handle)); } } - btsnd_hcic_create_cis( - conn_params.conn_pairs.size(), conn_params.conn_pairs.data(), - base::BindOnce(&iso_impl::on_status_establish_cis, - weak_factory_.GetWeakPtr(), conn_params)); + btsnd_hcic_create_cis(conn_params.conn_pairs.size(), conn_params.conn_pairs.data(), + base::BindOnce(&iso_impl::on_status_establish_cis, + weak_factory_.GetWeakPtr(), conn_params)); } void disconnect_cis(uint16_t cis_handle, uint8_t reason) { auto cis = GetCisIfKnown(cis_handle); log::assert_that(cis, "No such cis: {}", cis_handle); - log::assert_that(cis->state_flags & kStateFlagIsConnected || - cis->state_flags & kStateFlagIsConnecting, - "Not connected"); - bluetooth::legacy::hci::GetInterface().Disconnect( - cis_handle, static_cast(reason)); + log::assert_that( + cis->state_flags & kStateFlagIsConnected || cis->state_flags & kStateFlagIsConnecting, + "Not connected"); + bluetooth::legacy::hci::GetInterface().Disconnect(cis_handle, static_cast(reason)); BTM_LogHistory(kBtmLogTag, cis_hdl_to_addr[cis_handle], "Disconnect CIS ", - base::StringPrintf( - "handle:0x%04x, reason:%s", cis_handle, - hci_reason_code_text((tHCI_REASON)(reason)).c_str())); + base::StringPrintf("handle:0x%04x, reason:%s", cis_handle, + hci_reason_code_text((tHCI_REASON)(reason)).c_str())); } int get_number_of_active_iso() { @@ -363,13 +335,13 @@ struct iso_impl { return; } - BTM_LogHistory(kBtmLogTag, cis_hdl_to_addr[conn_handle], - "Setup data path complete", - base::StringPrintf( - "handle:0x%04x, status:%s", conn_handle, - hci_status_code_text((tHCI_STATUS)(status)).c_str())); + BTM_LogHistory(kBtmLogTag, cis_hdl_to_addr[conn_handle], "Setup data path complete", + base::StringPrintf("handle:0x%04x, status:%s", conn_handle, + hci_status_code_text((tHCI_STATUS)(status)).c_str())); - if (status == HCI_SUCCESS) iso->state_flags |= kStateFlagHasDataPathSet; + if (status == HCI_SUCCESS) { + iso->state_flags |= kStateFlagHasDataPathSet; + } if (iso->state_flags & kStateFlagIsBroadcast) { log::assert_that(big_callbacks_ != nullptr, "Invalid BIG callbacks"); big_callbacks_->OnSetupIsoDataPath(status, conn_handle, iso->big_handle); @@ -379,30 +351,24 @@ struct iso_impl { } } - void setup_iso_data_path( - uint16_t conn_handle, - struct iso_manager::iso_data_path_params path_params) { + void setup_iso_data_path(uint16_t conn_handle, + struct iso_manager::iso_data_path_params path_params) { iso_base* iso = GetIsoIfKnown(conn_handle); log::assert_that(iso != nullptr, "No such iso connection: {}", conn_handle); if (!(iso->state_flags & kStateFlagIsBroadcast)) { - log::assert_that(iso->state_flags & kStateFlagIsConnected, - "CIS not established"); + log::assert_that(iso->state_flags & kStateFlagIsConnected, "CIS not established"); } btsnd_hcic_setup_iso_data_path( - conn_handle, path_params.data_path_dir, path_params.data_path_id, - path_params.codec_id_format, path_params.codec_id_company, - path_params.codec_id_vendor, path_params.controller_delay, - std::move(path_params.codec_conf), - base::BindOnce(&iso_impl::on_setup_iso_data_path, - weak_factory_.GetWeakPtr())); - BTM_LogHistory( - kBtmLogTag, cis_hdl_to_addr[conn_handle], "Setup data path", - base::StringPrintf( - "handle:0x%04x, dir:0x%02x, path_id:0x%02x, codec_id:0x%02x", conn_handle, path_params.data_path_dir, path_params.data_path_id, - path_params.codec_id_format)); + path_params.codec_id_format, path_params.codec_id_company, path_params.codec_id_vendor, + path_params.controller_delay, std::move(path_params.codec_conf), + base::BindOnce(&iso_impl::on_setup_iso_data_path, weak_factory_.GetWeakPtr())); + BTM_LogHistory(kBtmLogTag, cis_hdl_to_addr[conn_handle], "Setup data path", + base::StringPrintf("handle:0x%04x, dir:0x%02x, path_id:0x%02x, codec_id:0x%02x", + conn_handle, path_params.data_path_dir, + path_params.data_path_id, path_params.codec_id_format)); } void on_remove_iso_data_path(uint8_t* stream, uint16_t len) { @@ -424,13 +390,13 @@ struct iso_impl { return; } - BTM_LogHistory(kBtmLogTag, cis_hdl_to_addr[conn_handle], - "Remove data path complete", - base::StringPrintf( - "handle:0x%04x, status:%s", conn_handle, - hci_status_code_text((tHCI_STATUS)(status)).c_str())); + BTM_LogHistory(kBtmLogTag, cis_hdl_to_addr[conn_handle], "Remove data path complete", + base::StringPrintf("handle:0x%04x, status:%s", conn_handle, + hci_status_code_text((tHCI_STATUS)(status)).c_str())); - if (status == HCI_SUCCESS) iso->state_flags &= ~kStateFlagHasDataPathSet; + if (status == HCI_SUCCESS) { + iso->state_flags &= ~kStateFlagHasDataPathSet; + } if (iso->state_flags & kStateFlagIsBroadcast) { log::assert_that(big_callbacks_ != nullptr, "Invalid BIG callbacks"); @@ -443,20 +409,16 @@ struct iso_impl { void remove_iso_data_path(uint16_t iso_handle, uint8_t data_path_dir) { iso_base* iso = GetIsoIfKnown(iso_handle); - log::assert_that(iso != nullptr, "No such iso connection: {}", - loghex(iso_handle)); - log::assert_that((iso->state_flags & kStateFlagHasDataPathSet) == - kStateFlagHasDataPathSet, + log::assert_that(iso != nullptr, "No such iso connection: {}", loghex(iso_handle)); + log::assert_that((iso->state_flags & kStateFlagHasDataPathSet) == kStateFlagHasDataPathSet, "Data path not set"); btsnd_hcic_remove_iso_data_path( - iso_handle, data_path_dir, - base::BindOnce(&iso_impl::on_remove_iso_data_path, - weak_factory_.GetWeakPtr())); + iso_handle, data_path_dir, + base::BindOnce(&iso_impl::on_remove_iso_data_path, weak_factory_.GetWeakPtr())); BTM_LogHistory(kBtmLogTag, cis_hdl_to_addr[iso_handle], "Remove data path", - base::StringPrintf("handle:0x%04x, dir:0x%02x", iso_handle, - data_path_dir)); + base::StringPrintf("handle:0x%04x, dir:0x%02x", iso_handle, data_path_dir)); } void on_iso_link_quality_read(uint8_t* stream, uint16_t len) { @@ -503,9 +465,8 @@ struct iso_impl { log::assert_that(cig_callbacks_ != nullptr, "Invalid CIG callbacks"); cig_callbacks_->OnIsoLinkQualityRead( - conn_handle, iso->cig_id, txUnackedPackets, txFlushedPackets, - txLastSubeventPackets, retransmittedPackets, crcErrorPackets, - rxUnreceivedPackets, duplicatePackets); + conn_handle, iso->cig_id, txUnackedPackets, txFlushedPackets, txLastSubeventPackets, + retransmittedPackets, crcErrorPackets, rxUnreceivedPackets, duplicatePackets); } void read_iso_link_quality(uint16_t iso_handle) { @@ -515,13 +476,11 @@ struct iso_impl { return; } - btsnd_hcic_read_iso_link_quality( - iso_handle, base::BindOnce(&iso_impl::on_iso_link_quality_read, - weak_factory_.GetWeakPtr())); + btsnd_hcic_read_iso_link_quality(iso_handle, base::BindOnce(&iso_impl::on_iso_link_quality_read, + weak_factory_.GetWeakPtr())); } - BT_HDR* prepare_hci_packet(uint16_t iso_handle, uint16_t seq_nb, - uint16_t data_len) { + BT_HDR* prepare_hci_packet(uint16_t iso_handle, uint16_t seq_nb, uint16_t data_len) { /* Add 2 for packet seq., 2 for length */ uint16_t iso_data_load_len = data_len + 4; @@ -543,11 +502,9 @@ struct iso_impl { return packet; } - void send_iso_data(uint16_t iso_handle, const uint8_t* data, - uint16_t data_len) { + void send_iso_data(uint16_t iso_handle, const uint8_t* data, uint16_t data_len) { iso_base* iso = GetIsoIfKnown(iso_handle); - log::assert_that(iso != nullptr, "No such iso connection handle: {}", - loghex(iso_handle)); + log::assert_that(iso != nullptr, "No such iso connection handle: {}", loghex(iso_handle)); if (!(iso->state_flags & kStateFlagIsBroadcast)) { if (!(iso->state_flags & kStateFlagIsConnected)) { @@ -570,13 +527,10 @@ struct iso_impl { if (iso_credits_ == 0 || data_len > iso_buffer_size_) { iso->cr_stats.credits_underflow_bytes += data_len; iso->cr_stats.credits_underflow_count++; - iso->cr_stats.credits_last_underflow_us = - bluetooth::common::time_get_os_boottime_us(); + iso->cr_stats.credits_last_underflow_us = bluetooth::common::time_get_os_boottime_us(); - log::warn( - ", dropping ISO packet, len: {}, iso credits: {}, iso handle: 0x{:x}", - static_cast(data_len), static_cast(iso_credits_), - iso_handle); + log::warn(", dropping ISO packet, len: {}, iso credits: {}, iso handle: 0x{:x}", + static_cast(data_len), static_cast(iso_credits_), iso_handle); return; } @@ -602,11 +556,9 @@ struct iso_impl { auto cis = GetCisIfKnown(evt.cis_conn_hdl); log::assert_that(cis != nullptr, "No such cis: {}", evt.cis_conn_hdl); - BTM_LogHistory(kBtmLogTag, cis_hdl_to_addr[evt.cis_conn_hdl], - "CIS established event", - base::StringPrintf( - "cis_handle:0x%04x status:%s", evt.cis_conn_hdl, - hci_error_code_text((tHCI_STATUS)(evt.status)).c_str())); + BTM_LogHistory(kBtmLogTag, cis_hdl_to_addr[evt.cis_conn_hdl], "CIS established event", + base::StringPrintf("cis_handle:0x%04x status:%s", evt.cis_conn_hdl, + hci_error_code_text((tHCI_STATUS)(evt.status)).c_str())); STREAM_TO_UINT24(evt.cig_sync_delay, data); STREAM_TO_UINT24(evt.cis_sync_delay, data); @@ -638,23 +590,24 @@ struct iso_impl { void disconnection_complete(uint16_t handle, uint8_t reason) { /* Check if this is an ISO handle */ auto cis = GetCisIfKnown(handle); - if (cis == nullptr) return; + if (cis == nullptr) { + return; + } log::assert_that(cig_callbacks_ != nullptr, "Invalid CIG callbacks"); log::info("flags: {}", cis->state_flags); - BTM_LogHistory( - kBtmLogTag, cis_hdl_to_addr[handle], "CIS disconnected", - base::StringPrintf("cis_handle:0x%04x, reason:%s", handle, - hci_error_code_text((tHCI_REASON)(reason)).c_str())); + BTM_LogHistory(kBtmLogTag, cis_hdl_to_addr[handle], "CIS disconnected", + base::StringPrintf("cis_handle:0x%04x, reason:%s", handle, + hci_error_code_text((tHCI_REASON)(reason)).c_str())); cis_hdl_to_addr.erase(handle); if (cis->state_flags & kStateFlagIsConnected) { cis_disconnected_evt evt = { - .reason = reason, - .cig_id = cis->cig_id, - .cis_conn_hdl = handle, + .reason = reason, + .cig_id = cis->cig_id, + .cis_conn_hdl = handle, }; cig_callbacks_->OnCisEvent(kIsoEventCisDisconnected, &evt); @@ -708,8 +661,7 @@ struct iso_impl { log::assert_that(num_bis != 0, "Bis count is 0"); log::assert_that(len == (18 + num_bis * sizeof(uint16_t)), - "Invalid packet length: {}. Number of bis: {}", len, - num_bis); + "Invalid packet length: {}. Number of bis: {}", len, num_bis); for (auto i = 0; i < num_bis; ++i) { uint16_t conn_handle; @@ -731,8 +683,7 @@ struct iso_impl { big_callbacks_->OnBigEvent(kIsoEventBigOnCreateCmpl, &evt); { - const std::lock_guard lock( - on_iso_traffic_active_callbacks_list_mutex_); + const std::lock_guard lock(on_iso_traffic_active_callbacks_list_mutex_); for (auto callbacks : on_iso_traffic_active_callbacks_list_) { callbacks(true); } @@ -763,8 +714,7 @@ struct iso_impl { big_callbacks_->OnBigEvent(kIsoEventBigOnTerminateCmpl, &evt); { - const std::lock_guard lock( - on_iso_traffic_active_callbacks_list_mutex_); + const std::lock_guard lock(on_iso_traffic_active_callbacks_list_mutex_); for (auto callbacks : on_iso_traffic_active_callbacks_list_) { callbacks(false); } @@ -772,8 +722,7 @@ struct iso_impl { } void create_big(uint8_t big_id, struct big_create_params big_params) { - log::assert_that(!IsBigKnown(big_id), "Invalid big - already exists: {}", - big_id); + log::assert_that(!IsBigKnown(big_id), "Invalid big - already exists: {}", big_id); if (stack_config_get_interface()->get_pts_unencrypt_broadcast()) { log::info("Force create broadcst without encryption for PTS test"); @@ -782,11 +731,10 @@ struct iso_impl { } last_big_create_req_sdu_itv_ = big_params.sdu_itv; - btsnd_hcic_create_big( - big_id, big_params.adv_handle, big_params.num_bis, big_params.sdu_itv, - big_params.max_sdu_size, big_params.max_transport_latency, - big_params.rtn, big_params.phy, big_params.packing, big_params.framing, - big_params.enc, big_params.enc_code); + btsnd_hcic_create_big(big_id, big_params.adv_handle, big_params.num_bis, big_params.sdu_itv, + big_params.max_sdu_size, big_params.max_transport_latency, big_params.rtn, + big_params.phy, big_params.packing, big_params.framing, big_params.enc, + big_params.enc_code); } void terminate_big(uint8_t big_id, uint8_t reason) { @@ -825,10 +773,10 @@ struct iso_impl { cis_data_evt evt; uint16_t handle, seq_nb; - if (p_msg->len <= ((p_msg->layer_specific & BT_ISO_HDR_CONTAINS_TS) - ? kIsoHeaderWithTsLen - : kIsoHeaderWithoutTsLen)) + if (p_msg->len <= ((p_msg->layer_specific & BT_ISO_HDR_CONTAINS_TS) ? kIsoHeaderWithTsLen + : kIsoHeaderWithoutTsLen)) { return; + } log::assert_that(cig_callbacks_ != nullptr, "Invalid CIG callbacks"); @@ -856,8 +804,7 @@ struct iso_impl { evt.evt_lost = ((1 << 16) + seq_nb - expected_seq_nb) & 0xffff; if (evt.evt_lost > 0) { iso->evt_stats.evt_lost_count += evt.evt_lost; - iso->evt_stats.evt_last_lost_us = - bluetooth::common::time_get_os_boottime_us(); + iso->evt_stats.evt_last_lost_us = bluetooth::common::time_get_os_boottime_us(); log::warn("{} packets lost.", evt.evt_lost); iso->evt_stats.seq_nb_mismatch_count++; @@ -871,14 +818,12 @@ struct iso_impl { iso_cis* GetCisIfKnown(uint16_t cis_conn_handle) { auto cis_it = conn_hdl_to_cis_map_.find(cis_conn_handle); - return (cis_it != conn_hdl_to_cis_map_.end()) ? cis_it->second.get() - : nullptr; + return (cis_it != conn_hdl_to_cis_map_.end()) ? cis_it->second.get() : nullptr; } iso_bis* GetBisIfKnown(uint16_t bis_conn_handle) { auto bis_it = conn_hdl_to_bis_map_.find(bis_conn_handle); - return (bis_it != conn_hdl_to_bis_map_.end()) ? bis_it->second.get() - : nullptr; + return (bis_it != conn_hdl_to_bis_map_.end()) ? bis_it->second.get() : nullptr; } iso_base* GetIsoIfKnown(uint16_t iso_handle) { @@ -888,49 +833,40 @@ struct iso_impl { bool IsCigKnown(uint8_t cig_id) const { auto const cis_it = - std::find_if(conn_hdl_to_cis_map_.cbegin(), conn_hdl_to_cis_map_.cend(), - [&cig_id](auto& kv_pair) { - return (kv_pair.second->cig_id == cig_id); - }); - return (cis_it != conn_hdl_to_cis_map_.cend()); + std::find_if(conn_hdl_to_cis_map_.cbegin(), conn_hdl_to_cis_map_.cend(), + [&cig_id](auto& kv_pair) { return kv_pair.second->cig_id == cig_id; }); + return cis_it != conn_hdl_to_cis_map_.cend(); } bool IsBigKnown(uint8_t big_id) const { auto bis_it = - std::find_if(conn_hdl_to_bis_map_.cbegin(), conn_hdl_to_bis_map_.cend(), - [&big_id](auto& kv_pair) { - return (kv_pair.second->big_handle == big_id); - }); - return (bis_it != conn_hdl_to_bis_map_.cend()); + std::find_if(conn_hdl_to_bis_map_.cbegin(), conn_hdl_to_bis_map_.cend(), + [&big_id](auto& kv_pair) { return kv_pair.second->big_handle == big_id; }); + return bis_it != conn_hdl_to_bis_map_.cend(); } static void dump_credits_stats(int fd, const iso_base::credits_stats& stats) { uint64_t now_us = bluetooth::common::time_get_os_boottime_us(); dprintf(fd, " Credits Stats:\n"); - dprintf(fd, " Credits underflow (count): %zu\n", - stats.credits_underflow_count); - dprintf(fd, " Credits underflow (bytes): %zu\n", - stats.credits_underflow_bytes); - dprintf( - fd, " Last underflow time ago (ms): %llu\n", - (stats.credits_last_underflow_us > 0 - ? (unsigned long long)(now_us - stats.credits_last_underflow_us) / - 1000 - : 0llu)); + dprintf(fd, " Credits underflow (count): %zu\n", stats.credits_underflow_count); + dprintf(fd, " Credits underflow (bytes): %zu\n", stats.credits_underflow_bytes); + dprintf(fd, " Last underflow time ago (ms): %llu\n", + (stats.credits_last_underflow_us > 0 + ? (unsigned long long)(now_us - stats.credits_last_underflow_us) / 1000 + : 0llu)); } static void dump_event_stats(int fd, const iso_base::event_stats& stats) { uint64_t now_us = bluetooth::common::time_get_os_boottime_us(); dprintf(fd, " Event Stats:\n"); - dprintf(fd, " Sequence number mismatch (count): %zu\n", - stats.seq_nb_mismatch_count); + dprintf(fd, " Sequence number mismatch (count): %zu\n", stats.seq_nb_mismatch_count); dprintf(fd, " Event lost (count): %zu\n", stats.evt_lost_count); dprintf(fd, " Last event lost time ago (ms): %llu\n", (stats.evt_last_lost_us > 0 - ? (unsigned long long)(now_us - stats.evt_last_lost_us) / 1000 - : 0llu)); + ? (unsigned long long)(now_us - stats.evt_last_lost_us) / 1000 + : 0llu)); } void dump(int fd) const { @@ -939,17 +875,14 @@ struct iso_impl { dprintf(fd, " Available credits: %d\n", iso_credits_.load()); dprintf(fd, " Controller buffer size: %d\n", iso_buffer_size_); dprintf(fd, " Num of ISO traffic callbacks: %lu\n", - static_cast( - on_iso_traffic_active_callbacks_list_.size())); + static_cast(on_iso_traffic_active_callbacks_list_.size())); dprintf(fd, " CISes:\n"); for (auto const& cis_pair : conn_hdl_to_cis_map_) { dprintf(fd, " CIS Connection handle: %d\n", cis_pair.first); dprintf(fd, " CIG ID: %d\n", cis_pair.second->cig_id); - dprintf(fd, " Used Credits: %d\n", - cis_pair.second->used_credits.load()); + dprintf(fd, " Used Credits: %d\n", cis_pair.second->used_credits.load()); dprintf(fd, " SDU Interval: %d\n", cis_pair.second->sdu_itv); - dprintf(fd, " State Flags: 0x%02hx\n", - cis_pair.second->state_flags.load()); + dprintf(fd, " State Flags: 0x%02hx\n", cis_pair.second->state_flags.load()); dump_credits_stats(fd, cis_pair.second->cr_stats); dump_event_stats(fd, cis_pair.second->evt_stats); } @@ -957,11 +890,9 @@ struct iso_impl { for (auto const& cis_pair : conn_hdl_to_bis_map_) { dprintf(fd, " BIS Connection handle: %d\n", cis_pair.first); dprintf(fd, " BIG Handle: %d\n", cis_pair.second->big_handle); - dprintf(fd, " Used Credits: %d\n", - cis_pair.second->used_credits.load()); + dprintf(fd, " Used Credits: %d\n", cis_pair.second->used_credits.load()); dprintf(fd, " SDU Interval: %d\n", cis_pair.second->sdu_itv); - dprintf(fd, " State Flags: 0x%02hx\n", - cis_pair.second->state_flags.load()); + dprintf(fd, " State Flags: 0x%02hx\n", cis_pair.second->state_flags.load()); dump_credits_stats(fd, cis_pair.second->cr_stats); dump_event_stats(fd, cis_pair.second->evt_stats); } diff --git a/system/stack/btm/btm_main.cc b/system/stack/btm/btm_main.cc index 85bc7f5aac9..014e2e7ec6e 100644 --- a/system/stack/btm/btm_main.cc +++ b/system/stack/btm/btm_main.cc @@ -36,7 +36,7 @@ using namespace bluetooth; /* Global BTM control block structure -*/ + */ tBTM_CB btm_cb; /******************************************************************************* @@ -65,31 +65,28 @@ void btm_free(void) { constexpr size_t kMaxLogHistoryTagLength = 6; constexpr size_t kMaxLogHistoryMsgLength = 25; -static void btm_log_history(const std::string& tag, const char* addr, - const std::string& msg, const std::string& extra) { +static void btm_log_history(const std::string& tag, const char* addr, const std::string& msg, + const std::string& extra) { if (btm_cb.history_ == nullptr) { - log::error( - "BTM_LogHistory has not been constructed or already destroyed !"); + log::error("BTM_LogHistory has not been constructed or already destroyed !"); return; } - btm_cb.history_->Push( - "%-6s %-25s: %s %s", tag.substr(0, kMaxLogHistoryTagLength).c_str(), - msg.substr(0, kMaxLogHistoryMsgLength).c_str(), addr, extra.c_str()); + btm_cb.history_->Push("%-6s %-25s: %s %s", tag.substr(0, kMaxLogHistoryTagLength).c_str(), + msg.substr(0, kMaxLogHistoryMsgLength).c_str(), addr, extra.c_str()); } -void BTM_LogHistory(const std::string& tag, const RawAddress& bd_addr, - const std::string& msg, const std::string& extra) { +void BTM_LogHistory(const std::string& tag, const RawAddress& bd_addr, const std::string& msg, + const std::string& extra) { btm_log_history(tag, ADDRESS_TO_LOGGABLE_CSTR(bd_addr), msg, extra); } -void BTM_LogHistory(const std::string& tag, const RawAddress& bd_addr, - const std::string& msg) { +void BTM_LogHistory(const std::string& tag, const RawAddress& bd_addr, const std::string& msg) { BTM_LogHistory(tag, bd_addr, msg, std::string()); } -void BTM_LogHistory(const std::string& tag, const tBLE_BD_ADDR& ble_bd_addr, - const std::string& msg, const std::string& extra) { +void BTM_LogHistory(const std::string& tag, const tBLE_BD_ADDR& ble_bd_addr, const std::string& msg, + const std::string& extra) { btm_log_history(tag, ADDRESS_TO_LOGGABLE_CSTR(ble_bd_addr), msg, extra); } diff --git a/system/stack/btm/btm_sco.cc b/system/stack/btm/btm_sco.cc index ae409f70287..c5975bce6b9 100644 --- a/system/stack/btm/btm_sco.cc +++ b/system/stack/btm/btm_sco.cc @@ -70,7 +70,7 @@ constexpr bool kDefaultDisableEnhancedConnection = false; /* Sysprops for SCO connection. */ static const char kPropertyDisableEnhancedConnection[] = - "bluetooth.sco.disable_enhanced_connection"; + "bluetooth.sco.disable_enhanced_connection"; namespace { @@ -92,17 +92,14 @@ using bluetooth::legacy::hci::GetInterface; // forward declaration for dequeueing packets static void btm_route_sco_data(bluetooth::hci::ScoView valid_packet); -void btm_sco_conn_req(const RawAddress& bda, const DEV_CLASS& dev_class, - uint8_t link_type); +void btm_sco_conn_req(const RawAddress& bda, const DEV_CLASS& dev_class, uint8_t link_type); void btm_sco_on_disconnected(uint16_t hci_handle, tHCI_REASON reason); bool btm_sco_removed(uint16_t hci_handle, tHCI_REASON reason); namespace cpp { -bluetooth::common::BidiQueueEnd* hci_sco_queue_end = - nullptr; -static bluetooth::os::EnqueueBuffer* - pending_sco_data = nullptr; +bluetooth::common::BidiQueueEnd* + hci_sco_queue_end = nullptr; +static bluetooth::os::EnqueueBuffer* pending_sco_data = nullptr; static void sco_data_callback() { if (hci_sco_queue_end == nullptr) { @@ -114,39 +111,32 @@ static void sco_data_callback() { log::info("Dropping invalid packet of size {}", packet->size()); return; } - if (do_in_main_thread(FROM_HERE, base::Bind(&btm_route_sco_data, *packet)) != - BT_STATUS_SUCCESS) { + if (do_in_main_thread(FROM_HERE, base::Bind(&btm_route_sco_data, *packet)) != BT_STATUS_SUCCESS) { log::error("do_in_main_thread failed from sco_data_callback"); } } static void register_for_sco() { hci_sco_queue_end = bluetooth::shim::GetHciLayer()->GetScoQueueEnd(); - hci_sco_queue_end->RegisterDequeue( - bluetooth::shim::GetGdShimHandler(), - bluetooth::common::Bind(sco_data_callback)); + hci_sco_queue_end->RegisterDequeue(bluetooth::shim::GetGdShimHandler(), + bluetooth::common::Bind(sco_data_callback)); pending_sco_data = - new bluetooth::os::EnqueueBuffer( - hci_sco_queue_end); + new bluetooth::os::EnqueueBuffer(hci_sco_queue_end); // Register SCO for connection requests - bluetooth::shim::GetHciLayer()->RegisterForScoConnectionRequests( - get_main_thread()->Bind( + bluetooth::shim::GetHciLayer()->RegisterForScoConnectionRequests(get_main_thread()->Bind( [](bluetooth::hci::Address peer, bluetooth::hci::ClassOfDevice cod, bluetooth::hci::ConnectionRequestLinkType link_type) { auto peer_raw_address = bluetooth::ToRawAddress(peer); DEV_CLASS dev_class{cod.cod[0], cod.cod[1], cod.cod[2]}; if (link_type == bluetooth::hci::ConnectionRequestLinkType::ESCO) { - btm_sco_conn_req(peer_raw_address, dev_class, - android::bluetooth::LINK_TYPE_ESCO); + btm_sco_conn_req(peer_raw_address, dev_class, android::bluetooth::LINK_TYPE_ESCO); } else { - btm_sco_conn_req(peer_raw_address, dev_class, - android::bluetooth::LINK_TYPE_SCO); + btm_sco_conn_req(peer_raw_address, dev_class, android::bluetooth::LINK_TYPE_SCO); } })); // Register SCO for disconnect notifications bluetooth::shim::GetHciLayer()->RegisterForDisconnects( - get_main_thread()->Bind( - [](uint16_t handle, bluetooth::hci::ErrorCode error_code) { + get_main_thread()->Bind([](uint16_t handle, bluetooth::hci::ErrorCode error_code) { auto reason = static_cast(error_code); btm_sco_on_disconnected(handle, reason); btm_sco_removed(handle, reason); @@ -168,8 +158,8 @@ static void shut_down_sco() { void tSCO_CB::Init() { hfp_hal_interface::init(); - def_esco_parms = esco_parameters_for_codec( - ESCO_CODEC_CVSD_S3, hfp_hal_interface::get_offload_enabled()); + def_esco_parms = + esco_parameters_for_codec(ESCO_CODEC_CVSD_S3, hfp_hal_interface::get_offload_enabled()); cpp::register_for_sco(); } @@ -189,18 +179,16 @@ void tSCO_CB::Free() { #define BTM_ESCO_PKT_TYPE_MASK \ (ESCO_PKT_TYPES_MASK_HV1 | ESCO_PKT_TYPES_MASK_HV2 | ESCO_PKT_TYPES_MASK_HV3) -#define BTM_ESCO_2_SCO(escotype) \ - ((uint16_t)(((escotype)&BTM_ESCO_PKT_TYPE_MASK) << 5)) +#define BTM_ESCO_2_SCO(escotype) ((uint16_t)(((escotype) & BTM_ESCO_PKT_TYPE_MASK) << 5)) /* Define masks for supported and exception 2.0 SCO packet types */ -#define BTM_SCO_SUPPORTED_PKTS_MASK \ - (ESCO_PKT_TYPES_MASK_HV1 | ESCO_PKT_TYPES_MASK_HV2 | \ - ESCO_PKT_TYPES_MASK_HV3 | ESCO_PKT_TYPES_MASK_EV3 | \ - ESCO_PKT_TYPES_MASK_EV4 | ESCO_PKT_TYPES_MASK_EV5) +#define BTM_SCO_SUPPORTED_PKTS_MASK \ + (ESCO_PKT_TYPES_MASK_HV1 | ESCO_PKT_TYPES_MASK_HV2 | ESCO_PKT_TYPES_MASK_HV3 | \ + ESCO_PKT_TYPES_MASK_EV3 | ESCO_PKT_TYPES_MASK_EV4 | ESCO_PKT_TYPES_MASK_EV5) -#define BTM_SCO_EXCEPTION_PKTS_MASK \ - (ESCO_PKT_TYPES_MASK_NO_2_EV3 | ESCO_PKT_TYPES_MASK_NO_3_EV3 | \ - ESCO_PKT_TYPES_MASK_NO_2_EV5 | ESCO_PKT_TYPES_MASK_NO_3_EV5) +#define BTM_SCO_EXCEPTION_PKTS_MASK \ + (ESCO_PKT_TYPES_MASK_NO_2_EV3 | ESCO_PKT_TYPES_MASK_NO_3_EV3 | ESCO_PKT_TYPES_MASK_NO_2_EV5 | \ + ESCO_PKT_TYPES_MASK_NO_3_EV5) /* Buffer used for reading PCM data from audio server that will be encoded into * mSBC packet. The BTM_SCO_DATA_SIZE_MAX should be set to a number divisible by @@ -237,8 +225,9 @@ void incr_btm_pcm_buf_offset(size_t& offset, bool& mirror, size_t amount) { btm_pcm_buf_state btm_pcm_buf_status() { if (btm_pcm_buf_read_offset == btm_pcm_buf_write_offset) { - if (btm_pcm_buf_read_mirror == btm_pcm_buf_write_mirror) + if (btm_pcm_buf_read_mirror == btm_pcm_buf_write_mirror) { return DECODE_BUF_EMPTY; + } return DECODE_BUF_FULL; } return DECODE_BUF_PARTIAL; @@ -252,16 +241,14 @@ size_t btm_pcm_buf_data_len() { return BTM_SCO_DATA_SIZE_MAX; case DECODE_BUF_PARTIAL: default: - if (btm_pcm_buf_write_offset > btm_pcm_buf_read_offset) + if (btm_pcm_buf_write_offset > btm_pcm_buf_read_offset) { return btm_pcm_buf_write_offset - btm_pcm_buf_read_offset; - return BTM_SCO_DATA_SIZE_MAX - - (btm_pcm_buf_read_offset - btm_pcm_buf_write_offset); + } + return BTM_SCO_DATA_SIZE_MAX - (btm_pcm_buf_read_offset - btm_pcm_buf_write_offset); }; } -size_t btm_pcm_buf_avail_len() { - return BTM_SCO_DATA_SIZE_MAX - btm_pcm_buf_data_len(); -} +size_t btm_pcm_buf_avail_len() { return BTM_SCO_DATA_SIZE_MAX - btm_pcm_buf_data_len(); } size_t write_btm_pcm_buf(uint8_t* source, size_t amount) { if (btm_pcm_buf_avail_len() < amount) { @@ -272,21 +259,18 @@ size_t write_btm_pcm_buf(uint8_t* source, size_t amount) { if (bytes_remaining > amount) { std::copy(source, source + amount, btm_pcm_buf + btm_pcm_buf_write_offset); } else { - std::copy(source, source + bytes_remaining, - btm_pcm_buf + btm_pcm_buf_write_offset); + std::copy(source, source + bytes_remaining, btm_pcm_buf + btm_pcm_buf_write_offset); std::copy(source + bytes_remaining, source + amount, btm_pcm_buf); } - incr_btm_pcm_buf_offset(btm_pcm_buf_write_offset, btm_pcm_buf_write_mirror, - amount); + incr_btm_pcm_buf_offset(btm_pcm_buf_write_offset, btm_pcm_buf_write_mirror, amount); return amount; } /******************************************************************************/ /* L O C A L F U N C T I O N P R O T O T Y P E S */ /******************************************************************************/ -static tBTM_STATUS BTM_ChangeEScoLinkParms(uint16_t sco_inx, - tBTM_CHG_ESCO_PARAMS* p_parms); +static tBTM_STATUS BTM_ChangeEScoLinkParms(uint16_t sco_inx, tBTM_CHG_ESCO_PARAMS* p_parms); static uint16_t btm_sco_voice_settings_to_legacy(enh_esco_params_t* p_parms); @@ -306,20 +290,22 @@ static uint16_t btm_sco_voice_settings_to_legacy(enh_esco_params_t* p_parms); * Returns void * ******************************************************************************/ -static void btm_esco_conn_rsp(uint16_t sco_inx, uint8_t hci_status, - const RawAddress& bda, +static void btm_esco_conn_rsp(uint16_t sco_inx, uint8_t hci_status, const RawAddress& bda, enh_esco_params_t* p_parms) { tSCO_CONN* p_sco = NULL; - if (BTM_MAX_SCO_LINKS == 0) return; + if (BTM_MAX_SCO_LINKS == 0) { + return; + } - if (sco_inx < BTM_MAX_SCO_LINKS) p_sco = &btm_cb.sco_cb.sco_db[sco_inx]; + if (sco_inx < BTM_MAX_SCO_LINKS) { + p_sco = &btm_cb.sco_cb.sco_db[sco_inx]; + } /* Reject the connect request if refused by caller or wrong state */ if (hci_status != HCI_SUCCESS || p_sco == NULL) { if (p_sco) { - p_sco->state = (p_sco->state == SCO_ST_W4_CONN_RSP) ? SCO_ST_LISTENING - : SCO_ST_UNUSED; + p_sco->state = (p_sco->state == SCO_ST_W4_CONN_RSP) ? SCO_ST_LISTENING : SCO_ST_UNUSED; } if (!btm_cb.sco_cb.esco_supported) { btsnd_hcic_reject_conn(bda, hci_status); @@ -339,25 +325,23 @@ static void btm_esco_conn_rsp(uint16_t sco_inx, uint8_t hci_status, } /* Use Enhanced Synchronous commands if supported */ if (bluetooth::shim::GetController()->IsSupported( - bluetooth::hci::OpCode::ENHANCED_SETUP_SYNCHRONOUS_CONNECTION) && + bluetooth::hci::OpCode::ENHANCED_SETUP_SYNCHRONOUS_CONNECTION) && !osi_property_get_bool(kPropertyDisableEnhancedConnection, kDefaultDisableEnhancedConnection)) { log::verbose( - "txbw 0x{:x}, rxbw 0x{:x}, lat 0x{:x}, retrans 0x{:02x}, pkt " - "0x{:04x}, path {}", - p_setup->transmit_bandwidth, p_setup->receive_bandwidth, - p_setup->max_latency_ms, p_setup->retransmission_effort, - p_setup->packet_types, p_setup->input_data_path); + "txbw 0x{:x}, rxbw 0x{:x}, lat 0x{:x}, retrans 0x{:02x}, pkt " + "0x{:04x}, path {}", + p_setup->transmit_bandwidth, p_setup->receive_bandwidth, p_setup->max_latency_ms, + p_setup->retransmission_effort, p_setup->packet_types, p_setup->input_data_path); btsnd_hcic_enhanced_accept_synchronous_connection(bda, p_setup); } else { /* Use legacy command if enhanced SCO setup is not supported */ uint16_t voice_content_format = btm_sco_voice_settings_to_legacy(p_setup); - btsnd_hcic_accept_esco_conn( - bda, p_setup->transmit_bandwidth, p_setup->receive_bandwidth, - p_setup->max_latency_ms, voice_content_format, - p_setup->retransmission_effort, p_setup->packet_types); + btsnd_hcic_accept_esco_conn(bda, p_setup->transmit_bandwidth, p_setup->receive_bandwidth, + p_setup->max_latency_ms, voice_content_format, + p_setup->retransmission_effort, p_setup->packet_types); } } } @@ -390,8 +374,7 @@ static tSCO_CONN* btm_get_active_sco() { static void btm_route_sco_data(bluetooth::hci::ScoView valid_packet) { uint16_t handle = valid_packet.GetHandle(); if (handle > HCI_HANDLE_MAX) { - log::error("Dropping SCO data with invalid handle: 0x{:X} > 0x{:X},", - handle, HCI_HANDLE_MAX); + log::error("Dropping SCO data with invalid handle: 0x{:X} > 0x{:X},", handle, HCI_HANDLE_MAX); return; } @@ -401,8 +384,8 @@ static void btm_route_sco_data(bluetooth::hci::ScoView valid_packet) { return; } if (active_sco->hci_handle != handle) { - log::error("Dropping packet with handle(0x{:X}) != active handle(0x{:X})", - handle, active_sco->hci_handle); + log::error("Dropping packet with handle(0x{:X}) != active handle(0x{:X})", handle, + active_sco->hci_handle); return; } @@ -418,22 +401,23 @@ static void btm_route_sco_data(bluetooth::hci::ScoView valid_packet) { auto status = valid_packet.GetPacketStatusFlag(); if (status != bluetooth::hci::PacketStatusFlag::CORRECTLY_RECEIVED) { - log::debug("{} packet corrupted with status({})", codec, - PacketStatusFlagText(status)); + log::debug("{} packet corrupted with status({})", codec, PacketStatusFlagText(status)); } auto enqueue_packet = codec_type == BTM_SCO_CODEC_LC3 - ? &bluetooth::audio::sco::swb::enqueue_packet - : &bluetooth::audio::sco::wbs::enqueue_packet; - rc = enqueue_packet( - data, status != bluetooth::hci::PacketStatusFlag::CORRECTLY_RECEIVED); - if (!rc) log::debug("Failed to enqueue {} packet", codec); + ? &bluetooth::audio::sco::swb::enqueue_packet + : &bluetooth::audio::sco::wbs::enqueue_packet; + rc = enqueue_packet(data, status != bluetooth::hci::PacketStatusFlag::CORRECTLY_RECEIVED); + if (!rc) { + log::debug("Failed to enqueue {} packet", codec); + } while (rc) { - auto decode = codec_type == BTM_SCO_CODEC_LC3 - ? &bluetooth::audio::sco::swb::decode - : &bluetooth::audio::sco::wbs::decode; + auto decode = codec_type == BTM_SCO_CODEC_LC3 ? &bluetooth::audio::sco::swb::decode + : &bluetooth::audio::sco::wbs::decode; rc = decode(&decoded); - if (rc == 0) break; + if (rc == 0) { + break; + } written += bluetooth::audio::sco::write(decoded, rc); } @@ -459,64 +443,62 @@ static void btm_route_sco_data(bluetooth::hci::ScoView valid_packet) { if (read != to_read) { log::info( - "Requested to read {} bytes of {} data but got {} bytes of PCM " - "data from audio server: WriteOffset:{} ReadOffset:{}", - (unsigned long)to_read, codec, (unsigned long)read, - (unsigned long)btm_pcm_buf_write_offset, - (unsigned long)btm_pcm_buf_read_offset); - if (read == 0) break; + "Requested to read {} bytes of {} data but got {} bytes of PCM " + "data from audio server: WriteOffset:{} ReadOffset:{}", + (unsigned long)to_read, codec, (unsigned long)read, + (unsigned long)btm_pcm_buf_write_offset, (unsigned long)btm_pcm_buf_read_offset); + if (read == 0) { + break; + } } written -= read; } else { /* We don't break here so that we can still decode the data in the * buffer to spare the buffer space when the buffer is full */ - log::warn( - "Buffer is full when we try to read {} packet from audio server", - codec); + log::warn("Buffer is full when we try to read {} packet from audio server", codec); } - auto encode = codec_type == BTM_SCO_CODEC_LC3 - ? &bluetooth::audio::sco::swb::encode - : &bluetooth::audio::sco::wbs::encode; + auto encode = codec_type == BTM_SCO_CODEC_LC3 ? &bluetooth::audio::sco::swb::encode + : &bluetooth::audio::sco::wbs::encode; size_t data_len = btm_pcm_buf_data_len(); if (data_len) { // Copy all data to the packet_buf first and then call encode. - size_t bytes_remaining = - BTM_SCO_DATA_SIZE_MAX - btm_pcm_buf_read_offset; + size_t bytes_remaining = BTM_SCO_DATA_SIZE_MAX - btm_pcm_buf_read_offset; if (bytes_remaining > data_len) { std::copy(btm_pcm_buf + btm_pcm_buf_read_offset, - btm_pcm_buf + btm_pcm_buf_read_offset + data_len, - packet_buf); + btm_pcm_buf + btm_pcm_buf_read_offset + data_len, packet_buf); } else { - std::copy(btm_pcm_buf + btm_pcm_buf_read_offset, - btm_pcm_buf + BTM_SCO_DATA_SIZE_MAX, packet_buf); + std::copy(btm_pcm_buf + btm_pcm_buf_read_offset, btm_pcm_buf + BTM_SCO_DATA_SIZE_MAX, + packet_buf); std::copy(btm_pcm_buf, btm_pcm_buf + data_len - bytes_remaining, packet_buf + bytes_remaining); } rc = encode((int16_t*)packet_buf, data_len); - incr_btm_pcm_buf_offset(btm_pcm_buf_read_offset, - btm_pcm_buf_read_mirror, rc); + incr_btm_pcm_buf_offset(btm_pcm_buf_read_offset, btm_pcm_buf_read_mirror, rc); - if (!rc) + if (!rc) { log::debug( - "Failed to encode {} data starting at ReadOffset:{} to " - "WriteOffset:{}", - codec, (unsigned long)btm_pcm_buf_read_offset, - (unsigned long)btm_pcm_buf_write_offset); + "Failed to encode {} data starting at ReadOffset:{} to " + "WriteOffset:{}", + codec, (unsigned long)btm_pcm_buf_read_offset, + (unsigned long)btm_pcm_buf_write_offset); + } } /* Send all of the available SCO packets buffered in the queue */ while (1) { auto dequeue_packet = codec_type == BTM_SCO_CODEC_LC3 - ? &bluetooth::audio::sco::swb::dequeue_packet - : &bluetooth::audio::sco::wbs::dequeue_packet; + ? &bluetooth::audio::sco::swb::dequeue_packet + : &bluetooth::audio::sco::wbs::dequeue_packet; rc = dequeue_packet(&encoded); - if (!rc) break; + if (!rc) { + break; + } auto data = std::vector(encoded, encoded + rc); btm_send_sco_packet(std::move(data)); @@ -525,13 +507,11 @@ static void btm_route_sco_data(bluetooth::hci::ScoView valid_packet) { } else { while (written) { read = bluetooth::audio::sco::read( - btm_pcm_buf, - written < BTM_SCO_DATA_SIZE_MAX ? written : BTM_SCO_DATA_SIZE_MAX); + btm_pcm_buf, written < BTM_SCO_DATA_SIZE_MAX ? written : BTM_SCO_DATA_SIZE_MAX); if (read == 0) { - log::info("Failed to read {} bytes of PCM data from audio server", - (unsigned long)(written < BTM_SCO_DATA_SIZE_MAX - ? written - : BTM_SCO_DATA_SIZE_MAX)); + log::info( + "Failed to read {} bytes of PCM data from audio server", + (unsigned long)(written < BTM_SCO_DATA_SIZE_MAX ? written : BTM_SCO_DATA_SIZE_MAX)); break; } written -= read; @@ -551,21 +531,18 @@ void btm_send_sco_packet(std::vector data) { if (active_sco == nullptr || data.empty()) { return; } - log::assert_that(data.size() <= BTM_SCO_DATA_SIZE_MAX, - "Invalid SCO data size: {}", (unsigned long)data.size()); + log::assert_that(data.size() <= BTM_SCO_DATA_SIZE_MAX, "Invalid SCO data size: {}", + (unsigned long)data.size()); uint16_t handle_with_flags = active_sco->hci_handle; uint16_t handle = HCID_GET_HANDLE(handle_with_flags); - log::assert_that(handle <= HCI_HANDLE_MAX, - "Require handle <= 0x{:X}, but is 0x{:X}", HCI_HANDLE_MAX, - handle); + log::assert_that(handle <= HCI_HANDLE_MAX, "Require handle <= 0x{:X}, but is 0x{:X}", + HCI_HANDLE_MAX, handle); auto sco_packet = bluetooth::hci::ScoBuilder::Create( - handle, bluetooth::hci::PacketStatusFlag::CORRECTLY_RECEIVED, - std::move(data)); + handle, bluetooth::hci::PacketStatusFlag::CORRECTLY_RECEIVED, std::move(data)); - cpp::pending_sco_data->Enqueue(std::move(sco_packet), - bluetooth::shim::GetGdShimHandler()); + cpp::pending_sco_data->Enqueue(std::move(sco_packet), bluetooth::shim::GetGdShimHandler()); } /******************************************************************************* @@ -578,8 +555,7 @@ void btm_send_sco_packet(std::vector data) { * Returns void * ******************************************************************************/ -static tBTM_STATUS btm_send_connect_request(uint16_t acl_handle, - enh_esco_params_t* p_setup) { +static tBTM_STATUS btm_send_connect_request(uint16_t acl_handle, enh_esco_params_t* p_setup) { /* Send connect request depending on version of spec */ if (!btm_cb.sco_cb.esco_supported) { log::info("sending non-eSCO request for handle={}", unsigned(acl_handle)); @@ -591,14 +567,12 @@ static tBTM_STATUS btm_send_connect_request(uint16_t acl_handle, uint16_t saved_max_latency_ms = p_setup->max_latency_ms; uint16_t temp_packet_types = - (p_setup->packet_types & - static_cast(BTM_SCO_SUPPORTED_PKTS_MASK) & - btm_cb.btm_sco_pkt_types_supported); + (p_setup->packet_types & static_cast(BTM_SCO_SUPPORTED_PKTS_MASK) & + btm_cb.btm_sco_pkt_types_supported); /* OR in any exception packet types */ - temp_packet_types |= - ((p_setup->packet_types & BTM_SCO_EXCEPTION_PKTS_MASK) | - (btm_cb.btm_sco_pkt_types_supported & BTM_SCO_EXCEPTION_PKTS_MASK)); + temp_packet_types |= ((p_setup->packet_types & BTM_SCO_EXCEPTION_PKTS_MASK) | + (btm_cb.btm_sco_pkt_types_supported & BTM_SCO_EXCEPTION_PKTS_MASK)); /* Finally, remove EDR eSCO if the remote device doesn't support it */ /* UPF25: Only SCO was brought up in this case */ @@ -606,13 +580,11 @@ static tBTM_STATUS btm_send_connect_request(uint16_t acl_handle, if (bd_addr != RawAddress::kEmpty) { if (!btm_peer_supports_esco_2m_phy(bd_addr)) { log::verbose("BTM Remote does not support 2-EDR eSCO"); - temp_packet_types |= - (ESCO_PKT_TYPES_MASK_NO_2_EV3 | ESCO_PKT_TYPES_MASK_NO_2_EV5); + temp_packet_types |= (ESCO_PKT_TYPES_MASK_NO_2_EV3 | ESCO_PKT_TYPES_MASK_NO_2_EV5); } if (!btm_peer_supports_esco_3m_phy(bd_addr)) { log::verbose("BTM Remote does not support 3-EDR eSCO"); - temp_packet_types |= - (ESCO_PKT_TYPES_MASK_NO_3_EV3 | ESCO_PKT_TYPES_MASK_NO_3_EV5); + temp_packet_types |= (ESCO_PKT_TYPES_MASK_NO_3_EV3 | ESCO_PKT_TYPES_MASK_NO_3_EV5); } if (!btm_peer_supports_esco_ev3(bd_addr)) { log::verbose("BTM Remote does not support EV3 eSCO"); @@ -625,40 +597,38 @@ static tBTM_STATUS btm_send_connect_request(uint16_t acl_handle, /* Check to see if BR/EDR Secure Connections is being used ** If so, we cannot use SCO-only packet types (HFP 1.7) */ - const bool local_supports_sc = - bluetooth::shim::GetController()->SupportsSecureConnections(); - const bool remote_supports_sc = - BTM_PeerSupportsSecureConnections(bd_addr); + const bool local_supports_sc = bluetooth::shim::GetController()->SupportsSecureConnections(); + const bool remote_supports_sc = BTM_PeerSupportsSecureConnections(bd_addr); if (local_supports_sc && remote_supports_sc) { temp_packet_types &= ~(BTM_SCO_PKT_TYPE_MASK); if (temp_packet_types == 0) { log::error( - "SCO connection cannot support any packet types for " - "acl_handle:0x{:04x}", - acl_handle); + "SCO connection cannot support any packet types for " + "acl_handle:0x{:04x}", + acl_handle); return BTM_WRONG_MODE; } log::debug( - "Both local and remote controllers support SCO secure connections " - "handle:0x{:04x} pkt_types:0x{:04x}", - acl_handle, temp_packet_types); + "Both local and remote controllers support SCO secure connections " + "handle:0x{:04x} pkt_types:0x{:04x}", + acl_handle, temp_packet_types); } else if (!local_supports_sc && !remote_supports_sc) { log::debug( - "Both local and remote controllers do not support secure " - "connections for handle:0x{:04x}", - acl_handle); + "Both local and remote controllers do not support secure " + "connections for handle:0x{:04x}", + acl_handle); } else if (remote_supports_sc) { log::debug( - "Only remote controller supports secure connections for " - "handle:0x{:04x}", - acl_handle); + "Only remote controller supports secure connections for " + "handle:0x{:04x}", + acl_handle); } else { log::debug( - "Only local controller supports secure connections for " - "handle:0x{:04x}", - acl_handle); + "Only local controller supports secure connections for " + "handle:0x{:04x}", + acl_handle); } } else { log::error("Received SCO connect from unknown peer:{}", bd_addr); @@ -668,43 +638,37 @@ static tBTM_STATUS btm_send_connect_request(uint16_t acl_handle, /* Use Enhanced Synchronous commands if supported */ if (bluetooth::shim::GetController()->IsSupported( - bluetooth::hci::OpCode::ENHANCED_SETUP_SYNCHRONOUS_CONNECTION) && + bluetooth::hci::OpCode::ENHANCED_SETUP_SYNCHRONOUS_CONNECTION) && !osi_property_get_bool(kPropertyDisableEnhancedConnection, kDefaultDisableEnhancedConnection)) { - log::info("Sending enhanced SCO connect request over handle:0x{:04x}", - acl_handle); + log::info("Sending enhanced SCO connect request over handle:0x{:04x}", acl_handle); log::info( - "enhanced parameter list txbw=0x{:x}, rxbw=0x{}, latency_ms=0x{}, " - "retransmit_effort=0x{}, pkt_type=0x{}, path=0x{}", - unsigned(p_setup->transmit_bandwidth), - unsigned(p_setup->receive_bandwidth), - unsigned(p_setup->max_latency_ms), - unsigned(p_setup->retransmission_effort), - unsigned(p_setup->packet_types), unsigned(p_setup->input_data_path)); + "enhanced parameter list txbw=0x{:x}, rxbw=0x{}, latency_ms=0x{}, " + "retransmit_effort=0x{}, pkt_type=0x{}, path=0x{}", + unsigned(p_setup->transmit_bandwidth), unsigned(p_setup->receive_bandwidth), + unsigned(p_setup->max_latency_ms), unsigned(p_setup->retransmission_effort), + unsigned(p_setup->packet_types), unsigned(p_setup->input_data_path)); btsnd_hcic_enhanced_set_up_synchronous_connection(acl_handle, p_setup); p_setup->packet_types = saved_packet_types; p_setup->retransmission_effort = saved_retransmission_effort; p_setup->max_latency_ms = saved_max_latency_ms; } else { /* Use older command */ - log::info("Sending eSCO connect request over handle:0x{:04x}", - acl_handle); + log::info("Sending eSCO connect request over handle:0x{:04x}", acl_handle); uint16_t voice_content_format = btm_sco_voice_settings_to_legacy(p_setup); log::info( - "legacy parameter list txbw=0x{:x}, rxbw=0x{}, latency_ms=0x{}, " - "retransmit_effort=0x{}, voice_content_format=0x{}, pkt_type=0x{}", - unsigned(p_setup->transmit_bandwidth), - unsigned(p_setup->receive_bandwidth), - unsigned(p_setup->max_latency_ms), - unsigned(p_setup->retransmission_effort), - unsigned(voice_content_format), unsigned(p_setup->packet_types)); - btsnd_hcic_setup_esco_conn( - acl_handle, p_setup->transmit_bandwidth, p_setup->receive_bandwidth, - p_setup->max_latency_ms, voice_content_format, - p_setup->retransmission_effort, p_setup->packet_types); + "legacy parameter list txbw=0x{:x}, rxbw=0x{}, latency_ms=0x{}, " + "retransmit_effort=0x{}, voice_content_format=0x{}, pkt_type=0x{}", + unsigned(p_setup->transmit_bandwidth), unsigned(p_setup->receive_bandwidth), + unsigned(p_setup->max_latency_ms), unsigned(p_setup->retransmission_effort), + unsigned(voice_content_format), unsigned(p_setup->packet_types)); + btsnd_hcic_setup_esco_conn(acl_handle, p_setup->transmit_bandwidth, + p_setup->receive_bandwidth, p_setup->max_latency_ms, + voice_content_format, p_setup->retransmission_effort, + p_setup->packet_types); } } - return (BTM_CMD_STARTED); + return BTM_CMD_STARTED; } /******************************************************************************* @@ -727,9 +691,8 @@ static tBTM_STATUS btm_send_connect_request(uint16_t acl_handle, * with the sco index used for the connection. * ******************************************************************************/ -tBTM_STATUS BTM_CreateSco(const RawAddress* remote_bda, bool is_orig, - uint16_t pkt_types, uint16_t* p_sco_inx, - tBTM_SCO_CB* p_conn_cb, tBTM_SCO_CB* p_disc_cb) { +tBTM_STATUS BTM_CreateSco(const RawAddress* remote_bda, bool is_orig, uint16_t pkt_types, + uint16_t* p_sco_inx, tBTM_SCO_CB* p_conn_cb, tBTM_SCO_CB* p_disc_cb) { enh_esco_params_t* p_setup; tSCO_CONN* p = &btm_cb.sco_cb.sco_db[0]; uint16_t xx; @@ -761,8 +724,8 @@ tBTM_STATUS BTM_CreateSco(const RawAddress* remote_bda, bool is_orig, if (((p->state == SCO_ST_CONNECTING) || (p->state == SCO_ST_LISTENING) || (p->state == SCO_ST_PEND_UNPARK)) && (p->esco.data.bd_addr == *remote_bda)) { - log::error("a sco connection is already going on for {}, at state {}", - *remote_bda, unsigned(p->state)); + log::error("a sco connection is already going on for {}, at state {}", *remote_bda, + unsigned(p->state)); return BTM_BUSY; } } @@ -770,26 +733,22 @@ tBTM_STATUS BTM_CreateSco(const RawAddress* remote_bda, bool is_orig, /* Support only 1 wildcard BD address at a time */ for (xx = 0; xx < BTM_MAX_SCO_LINKS; xx++, p++) { if ((p->state == SCO_ST_LISTENING) && (!p->rem_bd_known)) { - log::error( - "remote_bda is null and not known and we are still listening"); + log::error("remote_bda is null and not known and we are still listening"); return BTM_BUSY; } } } /* Try to find an unused control block, and kick off the SCO establishment */ - for (xx = 0, p = &btm_cb.sco_cb.sco_db[0]; xx < BTM_MAX_SCO_LINKS; - xx++, p++) { + for (xx = 0, p = &btm_cb.sco_cb.sco_db[0]; xx < BTM_MAX_SCO_LINKS; xx++, p++) { if (p->state == SCO_ST_UNUSED) { if (remote_bda) { if (is_orig) { // can not create SCO link if in park mode tBTM_PM_STATE state; if (BTM_ReadPowerMode(*remote_bda, &state)) { - if (state == BTM_PM_ST_SNIFF || state == BTM_PM_ST_PARK || - state == BTM_PM_ST_PENDING) { - log::info("{} in sniff, park or pending mode {}", *remote_bda, - unsigned(state)); + if (state == BTM_PM_ST_SNIFF || state == BTM_PM_ST_PARK || state == BTM_PM_ST_PENDING) { + log::info("{} in sniff, park or pending mode {}", *remote_bda, unsigned(state)); if (!BTM_SetLinkPolicyActiveMode(*remote_bda)) { log::warn("Unable to set link policy active"); } @@ -801,22 +760,21 @@ tBTM_STATUS BTM_CreateSco(const RawAddress* remote_bda, bool is_orig, } p->esco.data.bd_addr = *remote_bda; p->rem_bd_known = true; - } else + } else { p->rem_bd_known = false; + } p_setup = &p->esco.setup; *p_setup = btm_cb.sco_cb.def_esco_parms; /* Determine the packet types */ - p_setup->packet_types = pkt_types & BTM_SCO_SUPPORTED_PKTS_MASK & - btm_cb.btm_sco_pkt_types_supported; + p_setup->packet_types = + pkt_types & BTM_SCO_SUPPORTED_PKTS_MASK & btm_cb.btm_sco_pkt_types_supported; /* OR in any exception packet types */ - if (bluetooth::shim::GetController() - ->GetLocalVersionInformation() - .hci_version_ >= bluetooth::hci::HciVersion::V_2_0) { - p_setup->packet_types |= - (pkt_types & BTM_SCO_EXCEPTION_PKTS_MASK) | - (btm_cb.btm_sco_pkt_types_supported & BTM_SCO_EXCEPTION_PKTS_MASK); + if (bluetooth::shim::GetController()->GetLocalVersionInformation().hci_version_ >= + bluetooth::hci::HciVersion::V_2_0) { + p_setup->packet_types |= (pkt_types & BTM_SCO_EXCEPTION_PKTS_MASK) | + (btm_cb.btm_sco_pkt_types_supported & BTM_SCO_EXCEPTION_PKTS_MASK); } p->p_conn_cb = p_conn_cb; @@ -829,23 +787,19 @@ tBTM_STATUS BTM_CreateSco(const RawAddress* remote_bda, bool is_orig, /* If role change is in progress, do not proceed with SCO setup * Wait till role change is complete */ if (!acl_is_switch_role_idle(*remote_bda, BT_TRANSPORT_BR_EDR)) { - log::verbose("Role Change is in progress for ACL handle 0x{:04x}", - acl_handle); + log::verbose("Role Change is in progress for ACL handle 0x{:04x}", acl_handle); p->state = SCO_ST_PEND_ROLECHANGE; } } } - if (p->state != SCO_ST_PEND_UNPARK && - p->state != SCO_ST_PEND_ROLECHANGE) { + if (p->state != SCO_ST_PEND_UNPARK && p->state != SCO_ST_PEND_ROLECHANGE) { if (is_orig) { - log::debug("Initiating (e)SCO link for ACL handle:0x{:04x}", - acl_handle); + log::debug("Initiating (e)SCO link for ACL handle:0x{:04x}", acl_handle); - if ((btm_send_connect_request(acl_handle, p_setup)) != - BTM_CMD_STARTED) { + if ((btm_send_connect_request(acl_handle, p_setup)) != BTM_CMD_STARTED) { log::error("failed to send connect request for {}", *remote_bda); - return (BTM_NO_RESOURCES); + return BTM_NO_RESOURCES; } p->state = SCO_ST_CONNECTING; @@ -858,9 +812,8 @@ tBTM_STATUS BTM_CreateSco(const RawAddress* remote_bda, bool is_orig, *p_sco_inx = xx; log::debug("SCO connection successfully requested"); if (p->state == SCO_ST_CONNECTING) { - BTM_LogHistory( - kBtmLogTag, *remote_bda, "Connecting", - base::StringPrintf("local initiated acl:0x%04x", acl_handle)); + BTM_LogHistory(kBtmLogTag, *remote_bda, "Connecting", + base::StringPrintf("local initiated acl:0x%04x", acl_handle)); } return BTM_CMD_STARTED; } @@ -889,15 +842,13 @@ void btm_sco_chk_pend_unpark(tHCI_STATUS hci_status, uint16_t hci_handle) { BT_TRANSPORT_BR_EDR); if ((p->state == SCO_ST_PEND_UNPARK) && (acl_handle == hci_handle)) { log::info( - "{} unparked, sending connection request, acl_handle={}, " - "hci_status={}", - p->esco.data.bd_addr, unsigned(acl_handle), unsigned(hci_status)); - if (btm_send_connect_request(acl_handle, &p->esco.setup) == - BTM_CMD_STARTED) { + "{} unparked, sending connection request, acl_handle={}, " + "hci_status={}", + p->esco.data.bd_addr, unsigned(acl_handle), unsigned(hci_status)); + if (btm_send_connect_request(acl_handle, &p->esco.setup) == BTM_CMD_STARTED) { p->state = SCO_ST_CONNECTING; } else { - log::error("failed to send connection request for {}", - p->esco.data.bd_addr); + log::error("failed to send connection request for {}", p->esco.data.bd_addr); } } } @@ -925,13 +876,12 @@ void btm_sco_chk_pend_rolechange(uint16_t hci_handle) { p->esco.data.bd_addr, BT_TRANSPORT_BR_EDR)) == hci_handle)) { - log::verbose( - "btm_sco_chk_pend_rolechange -> (e)SCO Link for ACL handle 0x{:04x}", - acl_handle); + log::verbose("btm_sco_chk_pend_rolechange -> (e)SCO Link for ACL handle 0x{:04x}", + acl_handle); - if ((btm_send_connect_request(acl_handle, &p->esco.setup)) == - BTM_CMD_STARTED) + if ((btm_send_connect_request(acl_handle, &p->esco.setup)) == BTM_CMD_STARTED) { p->state = SCO_ST_CONNECTING; + } } } } @@ -951,9 +901,9 @@ void btm_sco_disc_chk_pend_for_modechange(uint16_t hci_handle) { tSCO_CONN* p = &btm_cb.sco_cb.sco_db[0]; log::debug( - "Checking for SCO pending mode change events hci_handle:0x{:04x} " - "p->state:{}", - hci_handle, sco_state_text(p->state)); + "Checking for SCO pending mode change events hci_handle:0x{:04x} " + "p->state:{}", + hci_handle, sco_state_text(p->state)); for (uint16_t xx = 0; xx < BTM_MAX_SCO_LINKS; xx++, p++) { if ((p->state == SCO_ST_PEND_MODECHANGE) && @@ -979,24 +929,21 @@ void btm_sco_disc_chk_pend_for_modechange(uint16_t hci_handle) { * Returns void * ******************************************************************************/ -void btm_sco_conn_req(const RawAddress& bda, const DEV_CLASS& dev_class, - uint8_t link_type) { +void btm_sco_conn_req(const RawAddress& bda, const DEV_CLASS& dev_class, uint8_t link_type) { tSCO_CB* p_sco = &btm_cb.sco_cb; tSCO_CONN* p = &p_sco->sco_db[0]; tBTM_ESCO_CONN_REQ_EVT_DATA evt_data = {}; DEVICE_IOT_CONFIG_ADDR_INT_ADD_ONE(bda, IOT_CONF_KEY_HFP_SCO_CONN_COUNT); - for (uint16_t sco_index = 0; sco_index < BTM_MAX_SCO_LINKS; - sco_index++, p++) { + for (uint16_t sco_index = 0; sco_index < BTM_MAX_SCO_LINKS; sco_index++, p++) { /* * If the sco state is in the SCO_ST_CONNECTING state, we still need * to return accept sco to avoid race conditon for sco creation */ bool rem_bd_matches = p->rem_bd_known && p->esco.data.bd_addr == bda; if (((p->state == SCO_ST_CONNECTING) && rem_bd_matches) || - ((p->state == SCO_ST_LISTENING) && - (rem_bd_matches || !p->rem_bd_known))) { + ((p->state == SCO_ST_LISTENING) && (rem_bd_matches || !p->rem_bd_known))) { /* If this was a wildcard, it is not one any more */ p->rem_bd_known = true; p->esco.data.link_type = link_type; @@ -1008,15 +955,13 @@ void btm_sco_conn_req(const RawAddress& bda, const DEV_CLASS& dev_class, /* If requesting eSCO reject if default parameters are SCO only */ if ((link_type == BTM_LINK_TYPE_ESCO && !(p_sco->def_esco_parms.packet_types & BTM_ESCO_LINK_ONLY_MASK) && - ((p_sco->def_esco_parms.packet_types & - BTM_SCO_EXCEPTION_PKTS_MASK) == BTM_SCO_EXCEPTION_PKTS_MASK)) + ((p_sco->def_esco_parms.packet_types & BTM_SCO_EXCEPTION_PKTS_MASK) == + BTM_SCO_EXCEPTION_PKTS_MASK)) /* Reject request if SCO is desired but no SCO packets delected */ - || - (link_type == BTM_LINK_TYPE_SCO && - !(p_sco->def_esco_parms.packet_types & BTM_SCO_LINK_ONLY_MASK))) { - btm_esco_conn_rsp(sco_index, HCI_ERR_HOST_REJECT_RESOURCES, bda, - nullptr); + || (link_type == BTM_LINK_TYPE_SCO && + !(p_sco->def_esco_parms.packet_types & BTM_SCO_LINK_ONLY_MASK))) { + btm_esco_conn_rsp(sco_index, HCI_ERR_HOST_REJECT_RESOURCES, bda, nullptr); } else { /* Accept the request */ btm_esco_conn_rsp(sco_index, HCI_SUCCESS, bda, nullptr); @@ -1038,8 +983,7 @@ void btm_sco_conn_req(const RawAddress& bda, const DEV_CLASS& dev_class, /* If here, no one wants the SCO connection. Reject it */ log::warn("rejecting SCO for {}", bda); - btm_esco_conn_rsp(BTM_MAX_SCO_LINKS, HCI_ERR_HOST_REJECT_RESOURCES, bda, - nullptr); + btm_esco_conn_rsp(BTM_MAX_SCO_LINKS, HCI_ERR_HOST_REJECT_RESOURCES, bda, nullptr); } /******************************************************************************* @@ -1052,8 +996,7 @@ void btm_sco_conn_req(const RawAddress& bda, const DEV_CLASS& dev_class, * Returns void * ******************************************************************************/ -void btm_sco_connected(const RawAddress& bda, uint16_t hci_handle, - tBTM_ESCO_DATA* p_esco_data) { +void btm_sco_connected(const RawAddress& bda, uint16_t hci_handle, tBTM_ESCO_DATA* p_esco_data) { tSCO_CONN* p = &btm_cb.sco_cb.sco_db[0]; uint16_t xx; bool spt = false; @@ -1064,20 +1007,20 @@ void btm_sco_connected(const RawAddress& bda, uint16_t hci_handle, if (((p->state == SCO_ST_CONNECTING) || (p->state == SCO_ST_LISTENING) || (p->state == SCO_ST_W4_CONN_RSP)) && (p->rem_bd_known) && (p->esco.data.bd_addr == bda)) { - BTM_LogHistory( - kBtmLogTag, bda, "Connection created", - base::StringPrintf("sco_idx:%hu handle:0x%04x ", xx, hci_handle)); - power_telemetry::GetInstance().LogLinkDetails(hci_handle, bda, true, - false); + BTM_LogHistory(kBtmLogTag, bda, "Connection created", + base::StringPrintf("sco_idx:%hu handle:0x%04x ", xx, hci_handle)); + power_telemetry::GetInstance().LogLinkDetails(hci_handle, bda, true, false); - if (p->state == SCO_ST_LISTENING) spt = true; + if (p->state == SCO_ST_LISTENING) { + spt = true; + } p->state = SCO_ST_CONNECTED; p->hci_handle = hci_handle; - BTM_LogHistory(kBtmLogTag, bda, "Connection success", - base::StringPrintf("handle:0x%04x %s", hci_handle, - (spt) ? "listener" : "initiator")); + BTM_LogHistory( + kBtmLogTag, bda, "Connection success", + base::StringPrintf("handle:0x%04x %s", hci_handle, (spt) ? "listener" : "initiator")); log::debug("Connected SCO link handle:0x{:04x} peer:{}", hci_handle, bda); if (!btm_cb.sco_cb.esco_supported) { @@ -1091,26 +1034,25 @@ void btm_sco_connected(const RawAddress& bda, uint16_t hci_handle, BTM_ChangeEScoLinkParms(xx, &parms); } } else { - if (p_esco_data) p->esco.data = *p_esco_data; + if (p_esco_data) { + p->esco.data = *p_esco_data; + } } (*p->p_conn_cb)(xx); codec = hfp_hal_interface::esco_coding_to_codec( - p->esco.setup.transmit_coding_format.coding_format); - hfp_hal_interface::notify_sco_connection_change( - bda, /*is_connected=*/true, codec); + p->esco.setup.transmit_coding_format.coding_format); + hfp_hal_interface::notify_sco_connection_change(bda, /*is_connected=*/true, codec); /* In-band (non-offload) data path */ if (p->is_inband()) { const auto codec_type = p->get_codec_type(); - if (codec_type == BTM_SCO_CODEC_MSBC || - codec_type == BTM_SCO_CODEC_LC3) { + if (codec_type == BTM_SCO_CODEC_MSBC || codec_type == BTM_SCO_CODEC_LC3) { btm_pcm_buf_read_offset = 0; btm_pcm_buf_write_offset = 0; - auto init = codec_type == BTM_SCO_CODEC_LC3 - ? &bluetooth::audio::sco::swb::init - : &bluetooth::audio::sco::wbs::init; + auto init = codec_type == BTM_SCO_CODEC_LC3 ? &bluetooth::audio::sco::swb::init + : &bluetooth::audio::sco::wbs::init; init(hfp_hal_interface::get_packet_size(codec)); } @@ -1132,8 +1074,7 @@ void btm_sco_connected(const RawAddress& bda, uint16_t hci_handle, * Returns void * ******************************************************************************/ -void btm_sco_connection_failed(tHCI_STATUS hci_status, const RawAddress& bda, - uint16_t hci_handle, +void btm_sco_connection_failed(tHCI_STATUS hci_status, const RawAddress& bda, uint16_t hci_handle, tBTM_ESCO_DATA* /* p_esco_data */) { tSCO_CONN* p = &btm_cb.sco_cb.sco_db[0]; uint16_t xx; @@ -1141,12 +1082,11 @@ void btm_sco_connection_failed(tHCI_STATUS hci_status, const RawAddress& bda, for (xx = 0; xx < BTM_MAX_SCO_LINKS; xx++, p++) { if (((p->state == SCO_ST_CONNECTING) || (p->state == SCO_ST_LISTENING) || (p->state == SCO_ST_W4_CONN_RSP)) && - (p->rem_bd_known) && - (p->esco.data.bd_addr == bda || bda == RawAddress::kEmpty)) { + (p->rem_bd_known) && (p->esco.data.bd_addr == bda || bda == RawAddress::kEmpty)) { /* Report the error if originator, otherwise remain in Listen mode */ if (p->is_orig) { - log::debug("SCO initiating connection failed handle:0x{:04x} reason:{}", - hci_handle, hci_error_code_text(hci_status)); + log::debug("SCO initiating connection failed handle:0x{:04x} reason:{}", hci_handle, + hci_error_code_text(hci_status)); switch (hci_status) { case HCI_ERR_ROLE_SWITCH_PENDING: /* If role switch is pending, we need try again after role switch @@ -1161,31 +1101,26 @@ void btm_sco_connection_failed(tHCI_STATUS hci_status, const RawAddress& bda, p->state = SCO_ST_UNUSED; (*p->p_disc_cb)(xx); } - BTM_LogHistory( - kBtmLogTag, bda, "Connection failed", - base::StringPrintf( - "locally_initiated reason:%s", - hci_reason_code_text(static_cast(hci_status)) - .c_str())); + BTM_LogHistory(kBtmLogTag, bda, "Connection failed", + base::StringPrintf( + "locally_initiated reason:%s", + hci_reason_code_text(static_cast(hci_status)).c_str())); } else { - log::debug( - "SCO terminating connection failed handle:0x{:04x} reason:{}", - hci_handle, hci_error_code_text(hci_status)); + log::debug("SCO terminating connection failed handle:0x{:04x} reason:{}", hci_handle, + hci_error_code_text(hci_status)); if (p->state == SCO_ST_CONNECTING) { p->state = SCO_ST_UNUSED; (*p->p_disc_cb)(xx); } else { p->state = SCO_ST_LISTENING; - if (bda != RawAddress::kEmpty) - DEVICE_IOT_CONFIG_ADDR_INT_ADD_ONE( - bda, IOT_CONF_KEY_HFP_SCO_CONN_FAIL_COUNT); + if (bda != RawAddress::kEmpty) { + DEVICE_IOT_CONFIG_ADDR_INT_ADD_ONE(bda, IOT_CONF_KEY_HFP_SCO_CONN_FAIL_COUNT); + } } - BTM_LogHistory( - kBtmLogTag, bda, "Connection failed", - base::StringPrintf( - "remote_initiated reason:%s", - hci_reason_code_text(static_cast(hci_status)) - .c_str())); + BTM_LogHistory(kBtmLogTag, bda, "Connection failed", + base::StringPrintf( + "remote_initiated reason:%s", + hci_reason_code_text(static_cast(hci_status)).c_str())); } return; } @@ -1212,23 +1147,22 @@ tBTM_STATUS BTM_RemoveSco(uint16_t sco_inx) { } /* Validity check */ - if ((sco_inx >= BTM_MAX_SCO_LINKS) || (p->state == SCO_ST_UNUSED)) - return (BTM_UNKNOWN_ADDR); + if ((sco_inx >= BTM_MAX_SCO_LINKS) || (p->state == SCO_ST_UNUSED)) { + return BTM_UNKNOWN_ADDR; + } /* If no HCI handle, simply drop the connection and return */ if (p->hci_handle == HCI_INVALID_HANDLE || p->state == SCO_ST_PEND_UNPARK) { p->hci_handle = HCI_INVALID_HANDLE; p->state = SCO_ST_UNUSED; p->esco.p_esco_cback = NULL; /* Deregister the eSCO event callback */ - return (BTM_SUCCESS); + return BTM_SUCCESS; } - if (BTM_ReadPowerMode(p->esco.data.bd_addr, &state) && - (state == BTM_PM_ST_PENDING)) { - log::verbose("BTM_PM_ST_PENDING for ACL mapped with SCO Link 0x{:04x}", - p->hci_handle); + if (BTM_ReadPowerMode(p->esco.data.bd_addr, &state) && (state == BTM_PM_ST_PENDING)) { + log::verbose("BTM_PM_ST_PENDING for ACL mapped with SCO Link 0x{:04x}", p->hci_handle); p->state = SCO_ST_PEND_MODECHANGE; - return (BTM_CMD_STARTED); + return BTM_CMD_STARTED; } tSCO_STATE old_state = p->state; @@ -1236,13 +1170,11 @@ tBTM_STATUS BTM_RemoveSco(uint16_t sco_inx) { GetInterface().Disconnect(p->Handle(), HCI_ERR_PEER_USER); - log::debug("Disconnecting link sco_handle:0x{:04x} peer:{}", p->Handle(), - p->esco.data.bd_addr); - BTM_LogHistory( - kBtmLogTag, p->esco.data.bd_addr, "Disconnecting", - base::StringPrintf("local initiated handle:0x%04x previous_state:%s", - p->Handle(), sco_state_text(old_state).c_str())); - return (BTM_CMD_STARTED); + log::debug("Disconnecting link sco_handle:0x{:04x} peer:{}", p->Handle(), p->esco.data.bd_addr); + BTM_LogHistory(kBtmLogTag, p->esco.data.bd_addr, "Disconnecting", + base::StringPrintf("local initiated handle:0x%04x previous_state:%s", p->Handle(), + sco_state_text(old_state).c_str())); + return BTM_CMD_STARTED; } void BTM_RemoveSco(const RawAddress& bda) { @@ -1276,8 +1208,7 @@ bool btm_sco_removed(uint16_t hci_handle, tHCI_REASON reason) { for (xx = 0; xx < BTM_MAX_SCO_LINKS; xx++, p++) { if ((p->state != SCO_ST_UNUSED) && (p->state != SCO_ST_LISTENING) && (p->hci_handle == hci_handle)) { - power_telemetry::GetInstance().LogLinkDetails( - hci_handle, RawAddress::kEmpty, false, false); + power_telemetry::GetInstance().LogLinkDetails(hci_handle, RawAddress::kEmpty, false, false); RawAddress bda(p->esco.data.bd_addr); p->state = SCO_ST_UNUSED; p->hci_handle = HCI_INVALID_HANDLE; @@ -1286,9 +1217,9 @@ bool btm_sco_removed(uint16_t hci_handle, tHCI_REASON reason) { (*p->p_disc_cb)(xx); hfp_hal_interface::notify_sco_connection_change( - bda, /*is_connected=*/false, - hfp_hal_interface::esco_coding_to_codec( - p->esco.setup.transmit_coding_format.coding_format)); + bda, /*is_connected=*/false, + hfp_hal_interface::esco_coding_to_codec( + p->esco.setup.transmit_coding_format.coding_format)); log::debug("Disconnected SCO link handle:{} reason:{}", hci_handle, hci_reason_code_text(reason)); @@ -1312,8 +1243,8 @@ void btm_sco_on_disconnected(uint16_t hci_handle, tHCI_REASON reason) { } if (p_sco->state == SCO_ST_LISTENING) { - log::info("Connection is in listening state handle:0x{:04x} reason:{}", - hci_handle, hci_reason_code_text(reason)); + log::info("Connection is in listening state handle:0x{:04x} reason:{}", hci_handle, + hci_reason_code_text(reason)); return; } @@ -1324,42 +1255,39 @@ void btm_sco_on_disconnected(uint16_t hci_handle, tHCI_REASON reason) { p_sco->rem_bd_known = false; p_sco->esco.p_esco_cback = NULL; /* Deregister eSCO callback */ (*p_sco->p_disc_cb)(btm_cb.sco_cb.get_index(p_sco)); - log::debug("Disconnected SCO link handle:{} reason:{}", hci_handle, - hci_reason_code_text(reason)); + log::debug("Disconnected SCO link handle:{} reason:{}", hci_handle, hci_reason_code_text(reason)); BTM_LogHistory(kBtmLogTag, bd_addr, "Disconnected", base::StringPrintf("handle:0x%04x reason:%s", hci_handle, hci_reason_code_text(reason).c_str())); hfp_hal_interface::notify_sco_connection_change( - bd_addr, /*is_connected=*/false, - hfp_hal_interface::esco_coding_to_codec( - p_sco->esco.setup.transmit_coding_format.coding_format)); + bd_addr, /*is_connected=*/false, + hfp_hal_interface::esco_coding_to_codec( + p_sco->esco.setup.transmit_coding_format.coding_format)); if (p_sco->is_inband()) { const auto codec_type = p_sco->get_codec_type(); if (codec_type == BTM_SCO_CODEC_MSBC || codec_type == BTM_SCO_CODEC_LC3) { auto fill_plc_stats = codec_type == BTM_SCO_CODEC_LC3 - ? bluetooth::audio::sco::swb::fill_plc_stats - : bluetooth::audio::sco::wbs::fill_plc_stats; + ? bluetooth::audio::sco::swb::fill_plc_stats + : bluetooth::audio::sco::wbs::fill_plc_stats; int num_decoded_frames; double packet_loss_ratio; if (fill_plc_stats(&num_decoded_frames, &packet_loss_ratio)) { const int16_t codec_id = sco_codec_type_to_id(codec_type); const std::string codec = sco_codec_type_text(codec_type); - log_hfp_audio_packet_loss_stats(bd_addr, num_decoded_frames, - packet_loss_ratio, codec_id); + log_hfp_audio_packet_loss_stats(bd_addr, num_decoded_frames, packet_loss_ratio, codec_id); log::debug( - "Stopped SCO codec:{}, num_decoded_frames:{}, " - "packet_loss_ratio:{:f}", - codec, num_decoded_frames, packet_loss_ratio); + "Stopped SCO codec:{}, num_decoded_frames:{}, " + "packet_loss_ratio:{:f}", + codec, num_decoded_frames, packet_loss_ratio); } else { log::warn("Failed to get the packet loss stats"); } - auto cleanup = codec_type == BTM_SCO_CODEC_LC3 - ? bluetooth::audio::sco::swb::cleanup - : bluetooth::audio::sco::wbs::cleanup; + auto cleanup = codec_type == BTM_SCO_CODEC_LC3 ? bluetooth::audio::sco::swb::cleanup + : bluetooth::audio::sco::wbs::cleanup; cleanup(); } @@ -1410,10 +1338,11 @@ const RawAddress* BTM_ReadScoBdAddr(uint16_t sco_inx) { tSCO_CONN* p = &btm_cb.sco_cb.sco_db[sco_inx]; /* Validity check */ - if ((sco_inx < BTM_MAX_SCO_LINKS) && (p->rem_bd_known)) + if ((sco_inx < BTM_MAX_SCO_LINKS) && (p->rem_bd_known)) { return &(p->esco.data.bd_addr); - else - return (NULL); + } else { + return NULL; + } } /******************************************************************************* @@ -1440,22 +1369,19 @@ tBTM_STATUS BTM_SetEScoMode(enh_esco_params_t* p_parms) { if (btm_cb.sco_cb.esco_supported) { *p_def = *p_parms; log::debug( - "Setting eSCO mode parameters txbw:0x{:08x} rxbw:0x{:08x} " - "max_lat:0x{:04x} pkt:0x{:04x} rtx_effort:0x{:02x}", - p_def->transmit_bandwidth, p_def->receive_bandwidth, - p_def->max_latency_ms, p_def->packet_types, - p_def->retransmission_effort); + "Setting eSCO mode parameters txbw:0x{:08x} rxbw:0x{:08x} " + "max_lat:0x{:04x} pkt:0x{:04x} rtx_effort:0x{:02x}", + p_def->transmit_bandwidth, p_def->receive_bandwidth, p_def->max_latency_ms, + p_def->packet_types, p_def->retransmission_effort); } else { /* Load defaults for SCO only */ - *p_def = esco_parameters_for_codec( - SCO_CODEC_CVSD_D1, hfp_hal_interface::get_offload_enabled()); + *p_def = esco_parameters_for_codec(SCO_CODEC_CVSD_D1, hfp_hal_interface::get_offload_enabled()); log::warn("eSCO not supported so setting SCO parameters instead"); log::debug( - "Setting SCO mode parameters txbw:0x{:08x} rxbw:0x{:08x} " - "max_lat:0x{:04x} pkt:0x{:04x} rtx_effort:0x{:02x}", - p_def->transmit_bandwidth, p_def->receive_bandwidth, - p_def->max_latency_ms, p_def->packet_types, - p_def->retransmission_effort); + "Setting SCO mode parameters txbw:0x{:08x} rxbw:0x{:08x} " + "max_lat:0x{:04x} pkt:0x{:04x} rtx_effort:0x{:02x}", + p_def->transmit_bandwidth, p_def->receive_bandwidth, p_def->max_latency_ms, + p_def->packet_types, p_def->retransmission_effort); } return BTM_SUCCESS; } @@ -1475,23 +1401,21 @@ tBTM_STATUS BTM_SetEScoMode(enh_esco_params_t* p_parms) { * later or does not support eSCO. * ******************************************************************************/ -tBTM_STATUS BTM_RegForEScoEvts(uint16_t sco_inx, - tBTM_ESCO_CBACK* p_esco_cback) { +tBTM_STATUS BTM_RegForEScoEvts(uint16_t sco_inx, tBTM_ESCO_CBACK* p_esco_cback) { if (BTM_MAX_SCO_LINKS == 0) { return BTM_MODE_UNSUPPORTED; } if (!btm_cb.sco_cb.esco_supported) { btm_cb.sco_cb.sco_db[sco_inx].esco.p_esco_cback = NULL; - return (BTM_MODE_UNSUPPORTED); + return BTM_MODE_UNSUPPORTED; } - if (sco_inx < BTM_MAX_SCO_LINKS && - btm_cb.sco_cb.sco_db[sco_inx].state != SCO_ST_UNUSED) { + if (sco_inx < BTM_MAX_SCO_LINKS && btm_cb.sco_cb.sco_db[sco_inx].state != SCO_ST_UNUSED) { btm_cb.sco_cb.sco_db[sco_inx].esco.p_esco_cback = p_esco_cback; - return (BTM_SUCCESS); + return BTM_SUCCESS; } - return (BTM_ILLEGAL_VALUE); + return BTM_ILLEGAL_VALUE; } /******************************************************************************* @@ -1514,12 +1438,11 @@ tBTM_STATUS BTM_RegForEScoEvts(uint16_t sco_inx, * sco_inx. * ******************************************************************************/ -static tBTM_STATUS BTM_ChangeEScoLinkParms(uint16_t sco_inx, - tBTM_CHG_ESCO_PARAMS* p_parms) { +static tBTM_STATUS BTM_ChangeEScoLinkParms(uint16_t sco_inx, tBTM_CHG_ESCO_PARAMS* p_parms) { /* Make sure sco handle is valid and on an active link */ - if (sco_inx >= BTM_MAX_SCO_LINKS || - btm_cb.sco_cb.sco_db[sco_inx].state != SCO_ST_CONNECTED) - return (BTM_WRONG_MODE); + if (sco_inx >= BTM_MAX_SCO_LINKS || btm_cb.sco_cb.sco_db[sco_inx].state != SCO_ST_CONNECTED) { + return BTM_WRONG_MODE; + } tSCO_CONN* p_sco = &btm_cb.sco_cb.sco_db[sco_inx]; enh_esco_params_t* p_setup = &p_sco->esco.setup; @@ -1528,66 +1451,56 @@ static tBTM_STATUS BTM_ChangeEScoLinkParms(uint16_t sco_inx, uint16_t saved_packet_types = p_setup->packet_types; /* If SCO connection OR eSCO not supported just send change packet types */ - if (p_sco->esco.data.link_type == BTM_LINK_TYPE_SCO || - !btm_cb.sco_cb.esco_supported) { + if (p_sco->esco.data.link_type == BTM_LINK_TYPE_SCO || !btm_cb.sco_cb.esco_supported) { p_setup->packet_types = - p_parms->packet_types & - (btm_cb.btm_sco_pkt_types_supported & BTM_SCO_LINK_ONLY_MASK); + p_parms->packet_types & (btm_cb.btm_sco_pkt_types_supported & BTM_SCO_LINK_ONLY_MASK); - log::verbose("SCO Link for handle 0x{:04x}, pkt 0x{:04x}", - p_sco->hci_handle, p_setup->packet_types); + log::verbose("SCO Link for handle 0x{:04x}, pkt 0x{:04x}", p_sco->hci_handle, + p_setup->packet_types); - log::verbose("SCO Link for handle 0x{:04x}, pkt 0x{:04x}", - p_sco->hci_handle, p_setup->packet_types); + log::verbose("SCO Link for handle 0x{:04x}, pkt 0x{:04x}", p_sco->hci_handle, + p_setup->packet_types); - GetInterface().ChangeConnectionPacketType( - p_sco->hci_handle, BTM_ESCO_2_SCO(p_setup->packet_types)); + GetInterface().ChangeConnectionPacketType(p_sco->hci_handle, + BTM_ESCO_2_SCO(p_setup->packet_types)); } else /* eSCO is supported and the link type is eSCO */ { - uint16_t temp_packet_types = - (p_parms->packet_types & BTM_SCO_SUPPORTED_PKTS_MASK & - btm_cb.btm_sco_pkt_types_supported); + uint16_t temp_packet_types = (p_parms->packet_types & BTM_SCO_SUPPORTED_PKTS_MASK & + btm_cb.btm_sco_pkt_types_supported); /* OR in any exception packet types */ - temp_packet_types |= - ((p_parms->packet_types & BTM_SCO_EXCEPTION_PKTS_MASK) | - (btm_cb.btm_sco_pkt_types_supported & BTM_SCO_EXCEPTION_PKTS_MASK)); + temp_packet_types |= ((p_parms->packet_types & BTM_SCO_EXCEPTION_PKTS_MASK) | + (btm_cb.btm_sco_pkt_types_supported & BTM_SCO_EXCEPTION_PKTS_MASK)); p_setup->packet_types = temp_packet_types; log::verbose("-> eSCO Link for handle 0x{:04x}", p_sco->hci_handle); - log::verbose( - "txbw 0x{:x}, rxbw 0x{:x}, lat 0x{:x}, retrans 0x{:02x}, pkt 0x{:04x}", - p_setup->transmit_bandwidth, p_setup->receive_bandwidth, - p_parms->max_latency_ms, p_parms->retransmission_effort, - temp_packet_types); + log::verbose("txbw 0x{:x}, rxbw 0x{:x}, lat 0x{:x}, retrans 0x{:02x}, pkt 0x{:04x}", + p_setup->transmit_bandwidth, p_setup->receive_bandwidth, p_parms->max_latency_ms, + p_parms->retransmission_effort, temp_packet_types); /* Use Enhanced Synchronous commands if supported */ if (bluetooth::shim::GetController()->IsSupported( - bluetooth::hci::OpCode::ENHANCED_SETUP_SYNCHRONOUS_CONNECTION) && + bluetooth::hci::OpCode::ENHANCED_SETUP_SYNCHRONOUS_CONNECTION) && !osi_property_get_bool(kPropertyDisableEnhancedConnection, kDefaultDisableEnhancedConnection)) { - btsnd_hcic_enhanced_set_up_synchronous_connection(p_sco->hci_handle, - p_setup); + btsnd_hcic_enhanced_set_up_synchronous_connection(p_sco->hci_handle, p_setup); p_setup->packet_types = saved_packet_types; } else { /* Use older command */ uint16_t voice_content_format = btm_sco_voice_settings_to_legacy(p_setup); /* When changing an existing link, only change latency, retrans, and * pkts */ btsnd_hcic_setup_esco_conn(p_sco->hci_handle, p_setup->transmit_bandwidth, - p_setup->receive_bandwidth, - p_parms->max_latency_ms, voice_content_format, - p_parms->retransmission_effort, + p_setup->receive_bandwidth, p_parms->max_latency_ms, + voice_content_format, p_parms->retransmission_effort, p_setup->packet_types); } - log::verbose( - "txbw 0x{:x}, rxbw 0x{:x}, lat 0x{:x}, retrans 0x{:02x}, pkt 0x{:04x}", - p_setup->transmit_bandwidth, p_setup->receive_bandwidth, - p_parms->max_latency_ms, p_parms->retransmission_effort, - temp_packet_types); + log::verbose("txbw 0x{:x}, rxbw 0x{:x}, lat 0x{:x}, retrans 0x{:02x}, pkt 0x{:04x}", + p_setup->transmit_bandwidth, p_setup->receive_bandwidth, p_parms->max_latency_ms, + p_parms->retransmission_effort, temp_packet_types); } - return (BTM_CMD_STARTED); + return BTM_CMD_STARTED; } /******************************************************************************* @@ -1608,12 +1521,10 @@ static tBTM_STATUS BTM_ChangeEScoLinkParms(uint16_t sco_inx, * Returns void * ******************************************************************************/ -void BTM_EScoConnRsp(uint16_t sco_inx, tHCI_STATUS hci_status, - enh_esco_params_t* p_parms) { - if (sco_inx < BTM_MAX_SCO_LINKS && - btm_cb.sco_cb.sco_db[sco_inx].state == SCO_ST_W4_CONN_RSP) { - btm_esco_conn_rsp(sco_inx, hci_status, - btm_cb.sco_cb.sco_db[sco_inx].esco.data.bd_addr, p_parms); +void BTM_EScoConnRsp(uint16_t sco_inx, tHCI_STATUS hci_status, enh_esco_params_t* p_parms) { + if (sco_inx < BTM_MAX_SCO_LINKS && btm_cb.sco_cb.sco_db[sco_inx].state == SCO_ST_W4_CONN_RSP) { + btm_esco_conn_rsp(sco_inx, hci_status, btm_cb.sco_cb.sco_db[sco_inx].esco.data.bd_addr, + p_parms); } } @@ -1644,7 +1555,7 @@ uint8_t BTM_GetNumScoLinks(void) { break; } } - return (num_scos); + return num_scos; } /******************************************************************************* @@ -1664,10 +1575,10 @@ bool BTM_IsScoActiveByBdaddr(const RawAddress& remote_bda) { /* If any SCO is being established to the remote BD address, refuse this */ for (xx = 0; xx < BTM_MAX_SCO_LINKS; xx++, p++) { if (p->esco.data.bd_addr == remote_bda && p->state == SCO_ST_CONNECTED) { - return (true); + return true; } } - return (false); + return false; } /******************************************************************************* @@ -1716,11 +1627,11 @@ static uint16_t btm_sco_voice_settings_to_legacy(enh_esco_params_t* p_params) { /* Convert Input Coding Format: If no uLaw or aLAW then Linear will be used * (0) */ - if (p_params->input_coding_format.coding_format == ESCO_CODING_FORMAT_ULAW) + if (p_params->input_coding_format.coding_format == ESCO_CODING_FORMAT_ULAW) { voice_settings |= HCI_INP_CODING_U_LAW; - else if (p_params->input_coding_format.coding_format == - ESCO_CODING_FORMAT_ALAW) + } else if (p_params->input_coding_format.coding_format == ESCO_CODING_FORMAT_ALAW) { voice_settings |= HCI_INP_CODING_A_LAW; + } /* else default value of '0 is good 'Linear' */ /* Convert Input Data Format. Use 2's Compliment as the default */ @@ -1764,18 +1675,19 @@ static uint16_t btm_sco_voice_settings_to_legacy(enh_esco_params_t* p_params) { } /* Convert PCM payload MSB position (0000011100) */ - voice_settings |= (uint16_t)(((p_params->input_pcm_payload_msb_position & 0x7) - << HCI_INP_LINEAR_PCM_BIT_POS_OFFS)); + voice_settings |= (uint16_t)((p_params->input_pcm_payload_msb_position & 0x7) + << HCI_INP_LINEAR_PCM_BIT_POS_OFFS); /* Convert Input Sample Size (0000011100) */ - if (p_params->input_coded_data_size == 16) + if (p_params->input_coded_data_size == 16) { voice_settings |= HCI_INP_SAMPLE_SIZE_16BIT; - else /* Use 8 bit for all others */ + } else { /* Use 8 bit for all others */ voice_settings |= HCI_INP_SAMPLE_SIZE_8BIT; + } log::verbose("voice setting for legacy 0x{:03x}", voice_settings); - return (voice_settings); + return voice_settings; } /******************************************************************************* * @@ -1792,38 +1704,39 @@ tBTM_SCO_DEBUG_DUMP BTM_GetScoDebugDump() { tBTM_SCO_DEBUG_DUMP debug_dump = {}; debug_dump.is_active = active_sco != nullptr; - if (!debug_dump.is_active) return debug_dump; + if (!debug_dump.is_active) { + return debug_dump; + } tBTM_SCO_CODEC_TYPE codec_type = active_sco->get_codec_type(); debug_dump.codec_id = sco_codec_type_to_id(codec_type); - if (debug_dump.codec_id != - static_cast>( - tBTA_AG_UUID_CODEC::UUID_CODEC_MSBC) && - debug_dump.codec_id != - static_cast>( - tBTA_AG_UUID_CODEC::UUID_CODEC_LC3)) + if (debug_dump.codec_id != static_cast>( + tBTA_AG_UUID_CODEC::UUID_CODEC_MSBC) && + debug_dump.codec_id != static_cast>( + tBTA_AG_UUID_CODEC::UUID_CODEC_LC3)) { return debug_dump; + } auto fill_plc_stats = - debug_dump.codec_id == - static_cast>( - tBTA_AG_UUID_CODEC::UUID_CODEC_LC3) - ? &bluetooth::audio::sco::swb::fill_plc_stats - : &bluetooth::audio::sco::wbs::fill_plc_stats; - - if (!fill_plc_stats(&debug_dump.total_num_decoded_frames, - &debug_dump.pkt_loss_ratio)) + debug_dump.codec_id == static_cast>( + tBTA_AG_UUID_CODEC::UUID_CODEC_LC3) + ? &bluetooth::audio::sco::swb::fill_plc_stats + : &bluetooth::audio::sco::wbs::fill_plc_stats; + + if (!fill_plc_stats(&debug_dump.total_num_decoded_frames, &debug_dump.pkt_loss_ratio)) { return debug_dump; + } auto get_pkt_status = - debug_dump.codec_id == - static_cast>( - tBTA_AG_UUID_CODEC::UUID_CODEC_LC3) - ? &bluetooth::audio::sco::swb::get_pkt_status - : &bluetooth::audio::sco::wbs::get_pkt_status; + debug_dump.codec_id == static_cast>( + tBTA_AG_UUID_CODEC::UUID_CODEC_LC3) + ? &bluetooth::audio::sco::swb::get_pkt_status + : &bluetooth::audio::sco::wbs::get_pkt_status; tBTM_SCO_PKT_STATUS* pkt_status = get_pkt_status(); - if (pkt_status == nullptr) return debug_dump; + if (pkt_status == nullptr) { + return debug_dump; + } tBTM_SCO_PKT_STATUS_DATA* data = &debug_dump.latest_data; data->begin_ts_raw_us = pkt_status->begin_ts_raw_us(); diff --git a/system/stack/btm/btm_sco.h b/system/stack/btm/btm_sco.h index 7c34667d1c3..4b51ce7eb40 100644 --- a/system/stack/btm/btm_sco.h +++ b/system/stack/btm/btm_sco.h @@ -216,8 +216,7 @@ inline std::string sco_state_text(const tSCO_STATE& state) { CASE_RETURN_TEXT(SCO_ST_PEND_ROLECHANGE); CASE_RETURN_TEXT(SCO_ST_PEND_MODECHANGE); default: - return std::string("unknown_sco_state: ") + - std::to_string(static_cast(state)); + return std::string("unknown_sco_state: ") + std::to_string(static_cast(state)); } } @@ -236,12 +235,10 @@ typedef struct { tBTM_SCO_CB* p_disc_cb; /* Callback for when disconnect */ tSCO_STATE state; /* The state of the SCO link */ - uint16_t hci_handle; /* HCI Handle */ - public: + uint16_t hci_handle; /* HCI Handle */ +public: bool is_active() const { return state != SCO_ST_UNUSED; } - bool is_inband() const { - return esco.setup.input_data_path == ESCO_DATA_PATH_HCI; - } + bool is_inband() const { return esco.setup.input_data_path == ESCO_DATA_PATH_HCI; } tBTM_SCO_CODEC_TYPE get_codec_type() const { switch (esco.setup.coding_format) { case ESCO_CODING_FORMAT_CVSD: @@ -256,8 +253,8 @@ typedef struct { } uint16_t Handle() const { return hci_handle; } - bool is_orig; /* true if the originator */ - bool rem_bd_known; /* true if remote BD addr known */ + bool is_orig; /* true if the originator */ + bool rem_bd_known; /* true if remote BD addr known */ } tSCO_CONN; @@ -265,7 +262,7 @@ typedef struct { struct tSCO_CB { tSCO_CONN sco_db[BTM_MAX_SCO_LINKS]; enh_esco_params_t def_esco_parms; - bool esco_supported; /* true if 1.2 cntlr AND supports eSCO links */ + bool esco_supported; /* true if 1.2 cntlr AND supports eSCO links */ tSCO_CONN* get_sco_connection_from_index(uint16_t index) { return (index < kMaxScoLinks) ? (&sco_db[index]) : nullptr; @@ -286,8 +283,7 @@ struct tSCO_CB { void Free(); uint16_t get_index(const tSCO_CONN* p_sco) const { - bluetooth::log::assert_that(p_sco != nullptr, - "assert failed: p_sco != nullptr"); + bluetooth::log::assert_that(p_sco != nullptr, "assert failed: p_sco != nullptr"); const tSCO_CONN* p = sco_db; for (uint16_t xx = 0; xx < kMaxScoLinks; xx++, p++) { if (p_sco == p) { diff --git a/system/stack/btm/btm_sco_hci.cc b/system/stack/btm/btm_sco_hci.cc index ece61e1d4ea..6c2b0c540fe 100644 --- a/system/stack/btm/btm_sco_hci.cc +++ b/system/stack/btm/btm_sco_hci.cc @@ -48,12 +48,11 @@ #define BTM_MSBC_SAMPLE_SIZE 2 /* 2 bytes*/ #define BTM_MSBC_FS 120 /* Frame Size */ -#define BTM_PLC_WL 256 /* 16ms - Window Length for pattern matching */ -#define BTM_PLC_TL 64 /* 4ms - Template Length for matching */ -#define BTM_PLC_HL \ - (BTM_PLC_WL + BTM_MSBC_FS - 1) /* Length of History buffer required */ -#define BTM_PLC_SBCRL 36 /* SBC Reconvergence sample Length */ -#define BTM_PLC_OLAL 16 /* OverLap-Add Length */ +#define BTM_PLC_WL 256 /* 16ms - Window Length for pattern matching */ +#define BTM_PLC_TL 64 /* 4ms - Template Length for matching */ +#define BTM_PLC_HL (BTM_PLC_WL + BTM_MSBC_FS - 1) /* Length of History buffer required */ +#define BTM_PLC_SBCRL 36 /* SBC Reconvergence sample Length */ +#define BTM_PLC_OLAL 16 /* OverLap-Add Length */ /* Disable the PLC when there are more than threshold of lost packets in the * window */ @@ -77,8 +76,7 @@ void sco_data_cb(tUIPC_CH_ID, tUIPC_EVENT event) { * Read directly from media task from here on (keep callback for * connection events. */ - UIPC_Ioctl(*sco_uipc, UIPC_CH_ID_AV_AUDIO, UIPC_REG_REMOVE_ACTIVE_READSET, - NULL); + UIPC_Ioctl(*sco_uipc, UIPC_CH_ID_AV_AUDIO, UIPC_REG_REMOVE_ACTIVE_READSET, NULL); UIPC_Ioctl(*sco_uipc, UIPC_CH_ID_AV_AUDIO, UIPC_SET_READ_POLL_TMO, reinterpret_cast(SCO_DATA_READ_POLL_MS)); break; @@ -165,35 +163,31 @@ constexpr size_t btm_wbs_msbc_buffer_size[] = {BTM_MSBC_PKT_LEN, 360, 120, 0}; /* The pre-computed SCO packet per HFP 1.7 spec. This mSBC packet will be * decoded into all-zero input PCM. */ static const uint8_t btm_msbc_zero_packet[] = { - 0x01, 0x08, /* Mock H2 header */ - 0xad, 0x00, 0x00, 0xc5, 0x00, 0x00, 0x00, 0x00, 0x77, 0x6d, 0xb6, 0xdd, - 0xdb, 0x6d, 0xb7, 0x76, 0xdb, 0x6d, 0xdd, 0xb6, 0xdb, 0x77, 0x6d, 0xb6, - 0xdd, 0xdb, 0x6d, 0xb7, 0x76, 0xdb, 0x6d, 0xdd, 0xb6, 0xdb, 0x77, 0x6d, - 0xb6, 0xdd, 0xdb, 0x6d, 0xb7, 0x76, 0xdb, 0x6d, 0xdd, 0xb6, 0xdb, 0x77, - 0x6d, 0xb6, 0xdd, 0xdb, 0x6d, 0xb7, 0x76, 0xdb, 0x6c, - /* End of Audio Samples */ - 0x00 /* A padding byte defined by mSBC */}; + 0x01, 0x08, /* Mock H2 header */ + 0xad, 0x00, 0x00, 0xc5, 0x00, 0x00, 0x00, 0x00, 0x77, 0x6d, 0xb6, 0xdd, 0xdb, 0x6d, 0xb7, + 0x76, 0xdb, 0x6d, 0xdd, 0xb6, 0xdb, 0x77, 0x6d, 0xb6, 0xdd, 0xdb, 0x6d, 0xb7, 0x76, 0xdb, + 0x6d, 0xdd, 0xb6, 0xdb, 0x77, 0x6d, 0xb6, 0xdd, 0xdb, 0x6d, 0xb7, 0x76, 0xdb, 0x6d, 0xdd, + 0xb6, 0xdb, 0x77, 0x6d, 0xb6, 0xdd, 0xdb, 0x6d, 0xb7, 0x76, 0xdb, 0x6c, + /* End of Audio Samples */ + 0x00 /* A padding byte defined by mSBC */}; /* Raised Cosine table for OLA */ -static const float rcos[BTM_PLC_OLAL] = { - 0.99148655f, 0.96623611f, 0.92510857f, 0.86950446f, - 0.80131732f, 0.72286918f, 0.63683150f, 0.54613418f, - 0.45386582f, 0.36316850f, 0.27713082f, 0.19868268f, - 0.13049554f, 0.07489143f, 0.03376389f, 0.00851345f}; +static const float rcos[BTM_PLC_OLAL] = {0.99148655f, 0.96623611f, 0.92510857f, 0.86950446f, + 0.80131732f, 0.72286918f, 0.63683150f, 0.54613418f, + 0.45386582f, 0.36316850f, 0.27713082f, 0.19868268f, + 0.13049554f, 0.07489143f, 0.03376389f, 0.00851345f}; static int16_t f_to_s16(float input) { - return input > INT16_MAX ? INT16_MAX - : input < INT16_MIN ? INT16_MIN - : (int16_t)input; + return input > INT16_MAX ? INT16_MAX : input < INT16_MIN ? INT16_MIN : (int16_t)input; } /* This structure tracks the packet loss for last PLC_WINDOW_SIZE of packets */ struct tBTM_MSBC_BTM_PLC_WINDOW { bool loss_hist[BTM_PLC_WINDOW_SIZE]; /* The packet loss history of receiving packets.*/ - unsigned int idx; /* The index of the to be updated packet loss status. */ - unsigned int count; /* The count of lost packets in the window. */ + unsigned int idx; /* The index of the to be updated packet loss status. */ + unsigned int count; /* The count of lost packets in the window. */ - public: +public: void update_plc_state(bool is_packet_loss) { bool* curr = &loss_hist[idx]; if (is_packet_loss != *curr) { @@ -225,26 +219,25 @@ struct tBTM_MSBC_BTM_PLC_WINDOW { */ struct tBTM_MSBC_PLC { int16_t hist[BTM_PLC_HL + BTM_MSBC_FS + BTM_PLC_SBCRL + - BTM_PLC_OLAL]; /* The history buffer for receiving samples, we - also use it to buffer the processed - replacement samples */ - unsigned best_lag; /* The index of the best substitution samples in the - sample history */ - int handled_bad_frames; /* Number of bad frames handled since the last good - frame */ + BTM_PLC_OLAL]; /* The history buffer for receiving samples, we + also use it to buffer the processed + replacement samples */ + unsigned best_lag; /* The index of the best substitution samples in the + sample history */ + int handled_bad_frames; /* Number of bad frames handled since the last good + frame */ int16_t decoded_buffer[BTM_MSBC_FS]; /* Used for storing the samples from decoding the mSBC zero frame packet and also constructed frames */ - tBTM_MSBC_BTM_PLC_WINDOW* - pl_window; /* Used to monitor how many packets are bad within the recent - BTM_PLC_WINDOW_SIZE of packets. We use this to determine if - we want to disable the PLC temporarily */ + tBTM_MSBC_BTM_PLC_WINDOW* pl_window; /* Used to monitor how many packets are bad within the recent + BTM_PLC_WINDOW_SIZE of packets. We use this to determine + if we want to disable the PLC temporarily */ int num_decoded_frames; /* Number of total read mSBC frames. */ int num_lost_frames; /* Number of total lost mSBC frames. */ - void overlap_add(int16_t* output, float scaler_d, const int16_t* desc, - float scaler_a, const int16_t* asc) { + void overlap_add(int16_t* output, float scaler_d, const int16_t* desc, float scaler_a, + const int16_t* asc) { for (int i = 0; i < BTM_PLC_OLAL; i++) { output[i] = f_to_s16(scaler_d * desc[i] * rcos[i] + scaler_a * asc[i] * rcos[BTM_PLC_OLAL - 1 - i]); @@ -284,20 +277,26 @@ struct tBTM_MSBC_PLC { sum_y += abs(y[i]); } - if (sum_y == 0) return 1.2f; + if (sum_y == 0) { + return 1.2f; + } scaler = (float)sum_x / sum_y; return scaler > 1.2f ? 1.2f : scaler < 0.75f ? 0.75f : scaler; } - public: +public: void init() { - if (pl_window) osi_free(pl_window); + if (pl_window) { + osi_free(pl_window); + } pl_window = (tBTM_MSBC_BTM_PLC_WINDOW*)osi_calloc(sizeof(*pl_window)); } void deinit() { - if (pl_window) osi_free_and_reset((void**)&pl_window); + if (pl_window) { + osi_free_and_reset((void**)&pl_window); + } } int get_num_decoded_frames() { return num_decoded_frames; } @@ -314,8 +313,8 @@ struct tBTM_MSBC_PLC { /* mSBC codec is stateful, the history of signal would contribute to the * decode result decoded_buffer. This should never fail. */ - GetInterfaceToProfiles()->msbcCodec->decodePacket( - btm_msbc_zero_packet, decoded_buffer, sizeof(decoded_buffer)); + GetInterfaceToProfiles()->msbcCodec->decodePacket(btm_msbc_zero_packet, decoded_buffer, + sizeof(decoded_buffer)); /* The PLC algorithm is more likely to generate bad results that sound * robotic after severe packet losses happened. Only applying it when @@ -325,25 +324,22 @@ struct tBTM_MSBC_PLC { /* Finds the best matching samples and amplitude */ best_lag = pattern_match(hist) + BTM_PLC_TL; best_match_hist = &hist[best_lag]; - scaler = - amplitude_match(&hist[BTM_PLC_HL - BTM_MSBC_FS], best_match_hist); + scaler = amplitude_match(&hist[BTM_PLC_HL - BTM_MSBC_FS], best_match_hist); /* Constructs the substitution samples */ overlap_add(frame_head, 1.0, decoded_buffer, scaler, best_match_hist); - for (int i = BTM_PLC_OLAL; i < BTM_MSBC_FS; i++) + for (int i = BTM_PLC_OLAL; i < BTM_MSBC_FS; i++) { hist[BTM_PLC_HL + i] = f_to_s16(scaler * best_match_hist[i]); - overlap_add(&frame_head[BTM_MSBC_FS], scaler, - &best_match_hist[BTM_MSBC_FS], 1.0, + } + overlap_add(&frame_head[BTM_MSBC_FS], scaler, &best_match_hist[BTM_MSBC_FS], 1.0, &best_match_hist[BTM_MSBC_FS]); memmove(&frame_head[BTM_MSBC_FS + BTM_PLC_OLAL], - &best_match_hist[BTM_MSBC_FS + BTM_PLC_OLAL], - BTM_PLC_SBCRL * BTM_MSBC_SAMPLE_SIZE); + &best_match_hist[BTM_MSBC_FS + BTM_PLC_OLAL], BTM_PLC_SBCRL * BTM_MSBC_SAMPLE_SIZE); } else { /* Using the existing best lag and copy the following frames */ memmove(frame_head, &hist[best_lag], - (BTM_MSBC_FS + BTM_PLC_SBCRL + BTM_PLC_OLAL) * - BTM_MSBC_SAMPLE_SIZE); + (BTM_MSBC_FS + BTM_PLC_SBCRL + BTM_PLC_OLAL) * BTM_MSBC_SAMPLE_SIZE); } /* Copy the constructed frames to decoded buffer for caller to use */ std::copy(frame_head, &frame_head[BTM_MSBC_FS], decoded_buffer); @@ -356,10 +352,9 @@ struct tBTM_MSBC_PLC { * concealment result sounds more artificial and weird than simply writing * zeros and following samples. */ - std::copy(std::begin(decoded_buffer), std::end(decoded_buffer), - frame_head); - std::fill(&frame_head[BTM_MSBC_FS], - &frame_head[BTM_MSBC_FS + BTM_PLC_SBCRL + BTM_PLC_OLAL], 0); + std::copy(std::begin(decoded_buffer), std::end(decoded_buffer), frame_head); + std::fill(&frame_head[BTM_MSBC_FS], &frame_head[BTM_MSBC_FS + BTM_PLC_SBCRL + BTM_PLC_OLAL], + 0); /* No need to copy the frames as we'll use the decoded zero frames in the * decoded buffer as our concealment frames */ @@ -392,8 +387,7 @@ struct tBTM_MSBC_PLC { } /* Shift the history and update the good frame to the end of it */ - memmove(hist, &hist[BTM_MSBC_FS], - (BTM_PLC_HL - BTM_MSBC_FS) * BTM_MSBC_SAMPLE_SIZE); + memmove(hist, &hist[BTM_MSBC_FS], (BTM_PLC_HL - BTM_MSBC_FS) * BTM_MSBC_SAMPLE_SIZE); std::copy(input, &input[BTM_MSBC_FS], &hist[BTM_PLC_HL - BTM_MSBC_FS]); pl_window->update_plc_state(0); } @@ -402,7 +396,7 @@ struct tBTM_MSBC_PLC { /* Define the structure that contains mSBC data */ struct tBTM_MSBC_INFO { size_t packet_size; /* SCO mSBC packet size supported by lower layer */ - size_t buf_size; /* The size of the buffer, determined by the packet_size. */ + size_t buf_size; /* The size of the buffer, determined by the packet_size. */ uint8_t* packet_buf; /* Temporary buffer to store the data */ uint8_t* msbc_decode_buf; /* Buffer to store mSBC packets to decode */ @@ -430,7 +424,7 @@ struct tBTM_MSBC_INFO { the read pointer is currently located in the first or second half of the circular buffer */ - bool read_corrupted; /* If the current mSBC packet read is corrupted */ + bool read_corrupted; /* If the current mSBC packet read is corrupted */ uint8_t* msbc_encode_buf; /* Buffer to store the encoded SCO packets */ size_t encode_buf_wo; /* Write offset of the encode buffer */ @@ -440,13 +434,11 @@ struct tBTM_MSBC_INFO { uint8_t num_encoded_msbc_pkts; /* Number of the encoded mSBC packets */ - tBTM_MSBC_PLC* plc; /* PLC component to handle the packet loss of input */ + tBTM_MSBC_PLC* plc; /* PLC component to handle the packet loss of input */ tBTM_SCO_PKT_STATUS* pkt_status; /* Record of mSBC packet status */ - static size_t get_supported_packet_size(size_t pkt_size, - size_t* buffer_size) { + static size_t get_supported_packet_size(size_t pkt_size, size_t* buffer_size) { int i; - for (i = 0; btm_wbs_supported_pkt_size[i] != 0 && - btm_wbs_supported_pkt_size[i] != pkt_size; + for (i = 0; btm_wbs_supported_pkt_size[i] != 0 && btm_wbs_supported_pkt_size[i] != pkt_size; i++) ; /* In case of unsupported value, error log and fallback to @@ -471,7 +463,7 @@ struct tBTM_MSBC_INFO { return false; } - public: +public: size_t init(size_t pkt_size) { decode_buf_wo = 0; decode_buf_ro = 0; @@ -482,15 +474,23 @@ struct tBTM_MSBC_INFO { encode_buf_ro = 0; pkt_size = get_supported_packet_size(pkt_size, &buf_size); - if (pkt_size == packet_size) return packet_size; + if (pkt_size == packet_size) { + return packet_size; + } packet_size = pkt_size; - if (!packet_buf) packet_buf = (uint8_t*)osi_calloc(BTM_MSBC_PKT_LEN); + if (!packet_buf) { + packet_buf = (uint8_t*)osi_calloc(BTM_MSBC_PKT_LEN); + } - if (msbc_decode_buf) osi_free(msbc_decode_buf); + if (msbc_decode_buf) { + osi_free(msbc_decode_buf); + } msbc_decode_buf = (uint8_t*)osi_calloc(buf_size); - if (msbc_encode_buf) osi_free(msbc_encode_buf); + if (msbc_encode_buf) { + osi_free(msbc_encode_buf); + } msbc_encode_buf = (uint8_t*)osi_calloc(buf_size); if (plc) { @@ -500,7 +500,9 @@ struct tBTM_MSBC_INFO { plc = (tBTM_MSBC_PLC*)osi_calloc(sizeof(*plc)); plc->init(); - if (pkt_status) osi_free(pkt_status); + if (pkt_status) { + osi_free(pkt_status); + } pkt_status = (tBTM_SCO_PKT_STATUS*)osi_calloc(sizeof(*pkt_status)); pkt_status->init(); @@ -508,18 +510,25 @@ struct tBTM_MSBC_INFO { } void deinit() { - if (msbc_decode_buf) osi_free(msbc_decode_buf); - if (packet_buf) osi_free(packet_buf); - if (msbc_encode_buf) osi_free(msbc_encode_buf); + if (msbc_decode_buf) { + osi_free(msbc_decode_buf); + } + if (packet_buf) { + osi_free(packet_buf); + } + if (msbc_encode_buf) { + osi_free(msbc_encode_buf); + } if (plc) { plc->deinit(); osi_free_and_reset((void**)&plc); } - if (pkt_status) osi_free_and_reset((void**)&pkt_status); + if (pkt_status) { + osi_free_and_reset((void**)&pkt_status); + } } - void incr_buf_offset(size_t& offset, bool& mirror, size_t bsize, - size_t amount) { + void incr_buf_offset(size_t& offset, bool& mirror, size_t bsize, size_t amount) { if (bsize - offset > amount) { offset += amount; return; @@ -531,7 +540,9 @@ struct tBTM_MSBC_INFO { decode_buf_state decode_buf_status() { if (decode_buf_ro == decode_buf_wo) { - if (decode_buf_ro_mirror == decode_buf_wo_mirror) return DECODE_BUF_EMPTY; + if (decode_buf_ro_mirror == decode_buf_wo_mirror) { + return DECODE_BUF_EMPTY; + } return DECODE_BUF_FULL; } return DECODE_BUF_HALFFULL; @@ -545,7 +556,9 @@ struct tBTM_MSBC_INFO { return buf_size; case DECODE_BUF_HALFFULL: default: - if (decode_buf_wo > decode_buf_ro) return decode_buf_wo - decode_buf_ro; + if (decode_buf_wo > decode_buf_ro) { + return decode_buf_wo - decode_buf_ro; + } return buf_size - (decode_buf_ro - decode_buf_wo); }; } @@ -558,16 +571,15 @@ struct tBTM_MSBC_INFO { return; } - incr_buf_offset(decode_buf_ro, decode_buf_ro_mirror, buf_size, - BTM_MSBC_PKT_LEN); + incr_buf_offset(decode_buf_ro, decode_buf_ro_mirror, buf_size, BTM_MSBC_PKT_LEN); } size_t write(const std::vector& input) { if (input.size() > decode_buf_avail_len()) { log::warn( - "Cannot write input with size {} into decode_buf with {} empty " - "space.", - input.size(), decode_buf_avail_len()); + "Cannot write input with size {} into decode_buf with {} empty " + "space.", + input.size(), decode_buf_avail_len()); return 0; } @@ -576,12 +588,10 @@ struct tBTM_MSBC_INFO { } else { std::copy(input.begin(), input.begin() + buf_size - decode_buf_wo, msbc_decode_buf + decode_buf_wo); - std::copy(input.begin() + buf_size - decode_buf_wo, input.end(), - msbc_decode_buf); + std::copy(input.begin() + buf_size - decode_buf_wo, input.end(), msbc_decode_buf); } - incr_buf_offset(decode_buf_wo, decode_buf_wo_mirror, buf_size, - input.size()); + incr_buf_offset(decode_buf_wo, decode_buf_wo_mirror, buf_size, input.size()); return input.size(); } @@ -594,19 +604,15 @@ struct tBTM_MSBC_INFO { size_t rp = 0; size_t data_len = decode_buf_data_len(); while (rp < BTM_MSBC_PKT_LEN && data_len - rp >= BTM_MSBC_PKT_LEN) { - if ((msbc_decode_buf[(decode_buf_ro + rp) % buf_size] != - BTM_MSBC_H2_HEADER_0) || - (!verify_h2_header_seq_num( - msbc_decode_buf[(decode_buf_ro + rp + 1) % buf_size])) || - (msbc_decode_buf[(decode_buf_ro + rp + 2) % buf_size] != - BTM_MSBC_SYNC_WORD)) { + if ((msbc_decode_buf[(decode_buf_ro + rp) % buf_size] != BTM_MSBC_H2_HEADER_0) || + (!verify_h2_header_seq_num(msbc_decode_buf[(decode_buf_ro + rp + 1) % buf_size])) || + (msbc_decode_buf[(decode_buf_ro + rp + 2) % buf_size] != BTM_MSBC_SYNC_WORD)) { rp++; continue; } if (rp != 0) { - log::warn("Skipped {} bytes of mSBC data ahead of a valid mSBC frame", - (unsigned long)rp); + log::warn("Skipped {} bytes of mSBC data ahead of a valid mSBC frame", (unsigned long)rp); incr_buf_offset(decode_buf_ro, decode_buf_ro_mirror, buf_size, rp); } @@ -615,10 +621,8 @@ struct tBTM_MSBC_INFO { return &msbc_decode_buf[decode_buf_ro]; } - std::copy(msbc_decode_buf + decode_buf_ro, msbc_decode_buf + buf_size, - packet_buf); - std::copy(msbc_decode_buf, - msbc_decode_buf + BTM_MSBC_PKT_LEN - (buf_size - decode_buf_ro), + std::copy(msbc_decode_buf + decode_buf_ro, msbc_decode_buf + buf_size, packet_buf); + std::copy(msbc_decode_buf, msbc_decode_buf + BTM_MSBC_PKT_LEN - (buf_size - decode_buf_ro), packet_buf + (buf_size - decode_buf_ro)); return packet_buf; } @@ -646,7 +650,9 @@ struct tBTM_MSBC_INFO { } size_t mark_pkt_dequeued() { - if (encode_buf_wo - encode_buf_ro < packet_size) return 0; + if (encode_buf_wo - encode_buf_ro < packet_size) { + return 0; + } encode_buf_ro += packet_size; if (encode_buf_ro == encode_buf_wo) { @@ -684,21 +690,24 @@ size_t init(size_t pkt_size) { void cleanup() { GetInterfaceToProfiles()->msbcCodec->cleanup(); - if (msbc_info == nullptr) return; + if (msbc_info == nullptr) { + return; + } msbc_info->deinit(); osi_free_and_reset((void**)&msbc_info); } bool fill_plc_stats(int* num_decoded_frames, double* packet_loss_ratio) { - if (msbc_info == NULL || num_decoded_frames == NULL || - packet_loss_ratio == NULL) + if (msbc_info == NULL || num_decoded_frames == NULL || packet_loss_ratio == NULL) { return false; + } int decoded_frames = msbc_info->plc->get_num_decoded_frames(); int lost_frames = msbc_info->plc->get_num_lost_frames(); - if (decoded_frames <= 0 || lost_frames < 0 || lost_frames > decoded_frames) + if (decoded_frames <= 0 || lost_frames < 0 || lost_frames > decoded_frames) { return false; + } *num_decoded_frames = decoded_frames; *packet_loss_ratio = (double)lost_frames / decoded_frames; @@ -713,9 +722,9 @@ bool enqueue_packet(const std::vector& data, bool corrupted) { if (data.size() != msbc_info->packet_size) { log::warn( - "Ignoring the coming packet with size {} that is inconsistent with the " - "HAL reported packet size {}", - (unsigned long)data.size(), (unsigned long)msbc_info->packet_size); + "Ignoring the coming packet with size {} that is inconsistent with the " + "HAL reported packet size {}", + (unsigned long)data.size(), (unsigned long)msbc_info->packet_size); return false; } @@ -752,9 +761,8 @@ size_t decode(const uint8_t** out_data) { goto packet_loss; } - if (!GetInterfaceToProfiles()->msbcCodec->decodePacket( - frame_head, msbc_info->decoded_pcm_buf, - sizeof(msbc_info->decoded_pcm_buf))) { + if (!GetInterfaceToProfiles()->msbcCodec->decodePacket(frame_head, msbc_info->decoded_pcm_buf, + sizeof(msbc_info->decoded_pcm_buf))) { goto packet_loss; } @@ -793,12 +801,11 @@ size_t encode(int16_t* data, size_t len) { return 0; } - encoded_size = - GetInterfaceToProfiles()->msbcCodec->encodePacket(data, pkt_body); + encoded_size = GetInterfaceToProfiles()->msbcCodec->encodePacket(data, pkt_body); if (encoded_size != BTM_MSBC_PKT_FRAME_LEN) { log::warn("Encoding invalid packet size: {}", (unsigned long)encoded_size); - std::copy(&btm_msbc_zero_packet[BTM_MSBC_H2_HEADER_LEN], - std::end(btm_msbc_zero_packet), pkt_body); + std::copy(&btm_msbc_zero_packet[BTM_MSBC_H2_HEADER_LEN], std::end(btm_msbc_zero_packet), + pkt_body); } return BTM_MSBC_CODE_SIZE; @@ -852,7 +859,7 @@ constexpr size_t btm_swb_lc3_buffer_size[] = {BTM_LC3_PKT_LEN, 360, 120, 0}; /* Define the structure that contains LC3 data */ struct tBTM_LC3_INFO { size_t packet_size; /* SCO LC3 packet size supported by lower layer */ - size_t buf_size; /* The size of the buffer, determined by the packet_size. */ + size_t buf_size; /* The size of the buffer, determined by the packet_size. */ uint8_t* packet_buf; /* Temporary buffer to store the data */ uint8_t* lc3_decode_buf; /* Buffer to store LC3 packets to decode */ @@ -880,7 +887,7 @@ struct tBTM_LC3_INFO { the read pointer is currently located in the first or second half of the circular buffer */ - bool read_corrupted; /* If the current LC3 packet read is corrupted */ + bool read_corrupted; /* If the current LC3 packet read is corrupted */ uint8_t* lc3_encode_buf; /* Buffer to store the encoded SCO packets */ size_t encode_buf_wo; /* Write offset of the encode buffer */ @@ -892,11 +899,9 @@ struct tBTM_LC3_INFO { tBTM_SCO_PKT_STATUS* pkt_status; /* Record of LC3 packet status */ - static size_t get_supported_packet_size(size_t pkt_size, - size_t* buffer_size) { + static size_t get_supported_packet_size(size_t pkt_size, size_t* buffer_size) { int i; - for (i = 0; btm_swb_supported_pkt_size[i] != 0 && - btm_swb_supported_pkt_size[i] != pkt_size; + for (i = 0; btm_swb_supported_pkt_size[i] != 0 && btm_swb_supported_pkt_size[i] != pkt_size; i++) ; /* In case of unsupported value, error log and fallback to @@ -921,7 +926,7 @@ struct tBTM_LC3_INFO { return false; } - public: +public: size_t init(size_t pkt_size) { decode_buf_wo = 0; decode_buf_ro = 0; @@ -932,18 +937,28 @@ struct tBTM_LC3_INFO { encode_buf_ro = 0; pkt_size = get_supported_packet_size(pkt_size, &buf_size); - if (pkt_size == packet_size) return packet_size; + if (pkt_size == packet_size) { + return packet_size; + } packet_size = pkt_size; - if (!packet_buf) packet_buf = (uint8_t*)osi_calloc(BTM_LC3_PKT_LEN); + if (!packet_buf) { + packet_buf = (uint8_t*)osi_calloc(BTM_LC3_PKT_LEN); + } - if (lc3_decode_buf) osi_free(lc3_decode_buf); + if (lc3_decode_buf) { + osi_free(lc3_decode_buf); + } lc3_decode_buf = (uint8_t*)osi_calloc(buf_size); - if (lc3_encode_buf) osi_free(lc3_encode_buf); + if (lc3_encode_buf) { + osi_free(lc3_encode_buf); + } lc3_encode_buf = (uint8_t*)osi_calloc(buf_size); - if (pkt_status) osi_free(pkt_status); + if (pkt_status) { + osi_free(pkt_status); + } pkt_status = (tBTM_SCO_PKT_STATUS*)osi_calloc(sizeof(*pkt_status)); pkt_status->init(); @@ -951,14 +966,21 @@ struct tBTM_LC3_INFO { } void deinit() { - if (lc3_decode_buf) osi_free(lc3_decode_buf); - if (packet_buf) osi_free(packet_buf); - if (lc3_encode_buf) osi_free(lc3_encode_buf); - if (pkt_status) osi_free_and_reset((void**)&pkt_status); + if (lc3_decode_buf) { + osi_free(lc3_decode_buf); + } + if (packet_buf) { + osi_free(packet_buf); + } + if (lc3_encode_buf) { + osi_free(lc3_encode_buf); + } + if (pkt_status) { + osi_free_and_reset((void**)&pkt_status); + } } - void incr_buf_offset(size_t& offset, bool& mirror, size_t bsize, - size_t amount) { + void incr_buf_offset(size_t& offset, bool& mirror, size_t bsize, size_t amount) { if (bsize - offset > amount) { offset += amount; return; @@ -970,7 +992,9 @@ struct tBTM_LC3_INFO { decode_buf_state decode_buf_status() { if (decode_buf_ro == decode_buf_wo) { - if (decode_buf_ro_mirror == decode_buf_wo_mirror) return DECODE_BUF_EMPTY; + if (decode_buf_ro_mirror == decode_buf_wo_mirror) { + return DECODE_BUF_EMPTY; + } return DECODE_BUF_FULL; } return DECODE_BUF_HALFFULL; @@ -984,7 +1008,9 @@ struct tBTM_LC3_INFO { return buf_size; case DECODE_BUF_HALFFULL: default: - if (decode_buf_wo > decode_buf_ro) return decode_buf_wo - decode_buf_ro; + if (decode_buf_wo > decode_buf_ro) { + return decode_buf_wo - decode_buf_ro; + } return buf_size - (decode_buf_ro - decode_buf_wo); }; } @@ -1012,16 +1038,15 @@ struct tBTM_LC3_INFO { return; } - incr_buf_offset(decode_buf_ro, decode_buf_ro_mirror, buf_size, - BTM_LC3_PKT_LEN); + incr_buf_offset(decode_buf_ro, decode_buf_ro_mirror, buf_size, BTM_LC3_PKT_LEN); } size_t write(const std::vector& input) { if (input.size() > decode_buf_avail_len()) { log::warn( - "Cannot write input with size {} into decode_buf with {} empty " - "space.", - input.size(), decode_buf_avail_len()); + "Cannot write input with size {} into decode_buf with {} empty " + "space.", + input.size(), decode_buf_avail_len()); return 0; } @@ -1030,12 +1055,10 @@ struct tBTM_LC3_INFO { } else { std::copy(input.begin(), input.begin() + buf_size - decode_buf_wo, lc3_decode_buf + decode_buf_wo); - std::copy(input.begin() + buf_size - decode_buf_wo, input.end(), - lc3_decode_buf); + std::copy(input.begin() + buf_size - decode_buf_wo, input.end(), lc3_decode_buf); } - incr_buf_offset(decode_buf_wo, decode_buf_wo_mirror, buf_size, - input.size()); + incr_buf_offset(decode_buf_wo, decode_buf_wo_mirror, buf_size, input.size()); return input.size(); } @@ -1048,17 +1071,14 @@ struct tBTM_LC3_INFO { size_t rp = 0; size_t data_len = decode_buf_data_len(); while (rp < BTM_LC3_PKT_LEN && data_len - rp >= BTM_LC3_PKT_LEN) { - if ((lc3_decode_buf[(decode_buf_ro + rp) % buf_size] != - BTM_LC3_H2_HEADER_0) || - !verify_h2_header_seq_num( - lc3_decode_buf[(decode_buf_ro + rp + 1) % buf_size])) { + if ((lc3_decode_buf[(decode_buf_ro + rp) % buf_size] != BTM_LC3_H2_HEADER_0) || + !verify_h2_header_seq_num(lc3_decode_buf[(decode_buf_ro + rp + 1) % buf_size])) { rp++; continue; } if (rp != 0) { - log::warn("Skipped {} bytes of LC3 data ahead of a valid LC3 frame", - (unsigned long)rp); + log::warn("Skipped {} bytes of LC3 data ahead of a valid LC3 frame", (unsigned long)rp); incr_buf_offset(decode_buf_ro, decode_buf_ro_mirror, buf_size, rp); } @@ -1067,10 +1087,8 @@ struct tBTM_LC3_INFO { return &lc3_decode_buf[decode_buf_ro]; } - std::copy(lc3_decode_buf + decode_buf_ro, lc3_decode_buf + buf_size, - packet_buf); - std::copy(lc3_decode_buf, - lc3_decode_buf + BTM_LC3_PKT_LEN - (buf_size - decode_buf_ro), + std::copy(lc3_decode_buf + decode_buf_ro, lc3_decode_buf + buf_size, packet_buf); + std::copy(lc3_decode_buf, lc3_decode_buf + BTM_LC3_PKT_LEN - (buf_size - decode_buf_ro), packet_buf + (buf_size - decode_buf_ro)); return packet_buf; } @@ -1079,7 +1097,9 @@ struct tBTM_LC3_INFO { } size_t mark_pkt_dequeued() { - if (encode_buf_wo - encode_buf_ro < packet_size) return 0; + if (encode_buf_wo - encode_buf_ro < packet_size) { + return 0; + } encode_buf_ro += packet_size; if (encode_buf_ro == encode_buf_wo) { @@ -1125,19 +1145,22 @@ void cleanup() { decoded_frames = 0; lost_frames = 0; - if (lc3_info == nullptr) return; + if (lc3_info == nullptr) { + return; + } lc3_info->deinit(); osi_free_and_reset((void**)&lc3_info); } bool fill_plc_stats(int* num_decoded_frames, double* packet_loss_ratio) { - if (lc3_info == NULL || num_decoded_frames == NULL || - packet_loss_ratio == NULL) + if (lc3_info == NULL || num_decoded_frames == NULL || packet_loss_ratio == NULL) { return false; + } - if (decoded_frames <= 0 || lost_frames < 0 || lost_frames > decoded_frames) + if (decoded_frames <= 0 || lost_frames < 0 || lost_frames > decoded_frames) { return false; + } *num_decoded_frames = decoded_frames; *packet_loss_ratio = (double)lost_frames / decoded_frames; @@ -1152,9 +1175,9 @@ bool enqueue_packet(const std::vector& data, bool corrupted) { if (data.size() != lc3_info->packet_size) { log::warn( - "Ignoring the coming packet with size {} that is inconsistent with the " - "HAL reported packet size {}", - (unsigned long)data.size(), (unsigned long)lc3_info->packet_size); + "Ignoring the coming packet with size {} that is inconsistent with the " + "HAL reported packet size {}", + (unsigned long)data.size(), (unsigned long)lc3_info->packet_size); return false; } @@ -1186,7 +1209,7 @@ size_t decode(const uint8_t** out_data) { frame_head = lc3_info->find_lc3_pkt_head(); bool plc_conducted = !GetInterfaceToProfiles()->lc3Codec->decodePacket( - frame_head, lc3_info->decoded_pcm_buf, sizeof(lc3_info->decoded_pcm_buf)); + frame_head, lc3_info->decoded_pcm_buf, sizeof(lc3_info->decoded_pcm_buf)); lc3_info->pkt_status->update(plc_conducted); diff --git a/system/stack/btm/btm_sco_hfp_hal.cc b/system/stack/btm/btm_sco_hfp_hal.cc index acd72580c91..b07c8e2486f 100644 --- a/system/stack/btm/btm_sco_hfp_hal.cc +++ b/system/stack/btm/btm_sco_hfp_hal.cc @@ -34,13 +34,13 @@ std::vector cached_codecs; // offloaded defaults. void init() { bt_codec cvsd = { - .codec = codec::CVSD, - .data_path = ESCO_DATA_PATH_PCM, + .codec = codec::CVSD, + .data_path = ESCO_DATA_PATH_PCM, }; bt_codec msbc = { - .codec = codec::MSBC, - .data_path = ESCO_DATA_PATH_PCM, + .codec = codec::MSBC, + .data_path = ESCO_DATA_PATH_PCM, }; cached_codecs.clear(); @@ -49,16 +49,12 @@ void init() { } // This is not used in Android. -bool is_coding_format_supported(esco_coding_format_t /* coding_format */) { - return true; -} +bool is_coding_format_supported(esco_coding_format_t /* coding_format */) { return true; } // Android statically compiles WBS support. bool get_wbs_supported() { return true; } -bool get_swb_supported() { - return osi_property_get_bool("bluetooth.hfp.swb.supported", false); -} +bool get_swb_supported() { return osi_property_get_bool("bluetooth.hfp.swb.supported", false); } // Checks the supported codecs bt_codecs get_codec_capabilities(uint64_t codecs) { @@ -94,8 +90,8 @@ void set_codec_datapath(tBTA_AG_UUID_CODEC /* codec_uuid */) {} // No packet size limits on Android since it will be offloaded. size_t get_packet_size(int /* codec */) { return kDefaultPacketSize; } -void notify_sco_connection_change(RawAddress /* device */, - bool /* is_connected */, int /* codec */) { +void notify_sco_connection_change(RawAddress /* device */, bool /* is_connected */, + int /* codec */) { // Do nothing since this is handled by Android's audio hidl. } diff --git a/system/stack/btm/btm_sco_hfp_hal.h b/system/stack/btm/btm_sco_hfp_hal.h index 58cfc68e404..f2f14569a16 100644 --- a/system/stack/btm/btm_sco_hfp_hal.h +++ b/system/stack/btm/btm_sco_hfp_hal.h @@ -98,8 +98,7 @@ void set_codec_datapath(tBTA_AG_UUID_CODEC codec_uuid); size_t get_packet_size(int codec); // Notify the lower layer about SCO connection change. -void notify_sco_connection_change(RawAddress device, bool is_connected, - int codec); +void notify_sco_connection_change(RawAddress device, bool is_connected, int codec); // Update eSCO parameters void update_esco_parameters(enh_esco_params_t* p_parms); diff --git a/system/stack/btm/btm_sco_hfp_hal_linux.cc b/system/stack/btm/btm_sco_hfp_hal_linux.cc index 24dfbd2ed5f..75fd5e13ce8 100644 --- a/system/stack/btm/btm_sco_hfp_hal_linux.cc +++ b/system/stack/btm/btm_sco_hfp_hal_linux.cc @@ -93,7 +93,7 @@ void cache_codec_capabilities(struct mgmt_rp_get_codec_capabilities* rp) { // CVSD is mandatory in HFP. cached_codecs.push_back({ - .inner = {.codec = codec::CVSD}, + .inner = {.codec = codec::CVSD}, }); // No need to check GetLocalSupportedBrEdrCodecIds. Some legacy devices don't @@ -101,25 +101,23 @@ void cache_codec_capabilities(struct mgmt_rp_get_codec_capabilities* rp) { // reliable. if (rp->transparent_wbs_supported) { cached_codecs.push_back({ - .inner = {.codec = codec::MSBC_TRANSPARENT}, - .pkt_size = rp->wbs_pkt_len, + .inner = {.codec = codec::MSBC_TRANSPARENT}, + .pkt_size = rp->wbs_pkt_len, }); } - auto codecs = - bluetooth::shim::GetController()->GetLocalSupportedBrEdrCodecIds(); + auto codecs = bluetooth::shim::GetController()->GetLocalSupportedBrEdrCodecIds(); if (std::find(codecs.begin(), codecs.end(), kCodecMsbc) != codecs.end()) { offload_supported = true; cached_codecs.push_back({ - .inner = {.codec = codec::MSBC, .data_path = rp->hci_data_path_id}, - .pkt_size = rp->wbs_pkt_len, + .inner = {.codec = codec::MSBC, .data_path = rp->hci_data_path_id}, + .pkt_size = rp->wbs_pkt_len, }); } for (const auto& c : cached_codecs) { log::info("Caching HFP codec {}, data path {}, data len {}, pkt_size {}", - (uint64_t)c.inner.codec, c.inner.data_path, c.inner.data.size(), - c.pkt_size); + (uint64_t)c.inner.codec, c.inner.data_path, c.inner.data.size(), c.pkt_size); } } @@ -141,9 +139,9 @@ int btsocket_open_mgmt(uint16_t hci) { } struct sockaddr_hci addr = { - .hci_family = AF_BLUETOOTH, - .hci_dev = HCI_DEV_NONE, - .hci_channel = HCI_CHANNEL_CONTROL, + .hci_family = AF_BLUETOOTH, + .hci_dev = HCI_DEV_NONE, + .hci_channel = HCI_CHANNEL_CONTROL, }; int ret = bind(fd, (struct sockaddr*)&addr, sizeof(addr)); @@ -163,7 +161,7 @@ int mgmt_get_codec_capabilities(int fd, uint16_t hci) { ev.len = sizeof(struct mgmt_cp_get_codec_capabilities); struct mgmt_cp_get_codec_capabilities* cp = - reinterpret_cast(ev.data); + reinterpret_cast(ev.data); cp->hci_dev = hci; int ret; @@ -177,8 +175,7 @@ int mgmt_get_codec_capabilities(int fd, uint16_t hci) { if (ret > 0) { RETRY_ON_INTR(ret = write(fd, &ev, MGMT_PKT_HDR_SIZE + ev.len)); if (ret < 0) { - log::debug("Failed to call MGMT_OP_GET_SCO_CODEC_CAPABILITIES: {}", - -errno); + log::debug("Failed to call MGMT_OP_GET_SCO_CODEC_CAPABILITIES: {}", -errno); return -errno; }; break; @@ -206,13 +203,10 @@ int mgmt_get_codec_capabilities(int fd, uint16_t hci) { } if (ev.opcode == MGMT_EV_COMMAND_COMPLETE) { - struct mgmt_ev_cmd_complete* cc = - reinterpret_cast(ev.data); - if (cc->opcode == MGMT_OP_GET_SCO_CODEC_CAPABILITIES && - cc->status == 0) { + struct mgmt_ev_cmd_complete* cc = reinterpret_cast(ev.data); + if (cc->opcode == MGMT_OP_GET_SCO_CODEC_CAPABILITIES && cc->status == 0) { struct mgmt_rp_get_codec_capabilities* rp = - reinterpret_cast( - cc->data); + reinterpret_cast(cc->data); if (rp->hci_dev == hci) { cache_codec_capabilities(rp); return 0; @@ -238,15 +232,15 @@ struct mgmt_cp_notify_sco_connection_change { uint8_t codec; } __attribute__((packed)); -int mgmt_notify_sco_connection_change(int fd, int hci, RawAddress device, - bool is_connected, int codec) { +int mgmt_notify_sco_connection_change(int fd, int hci, RawAddress device, bool is_connected, + int codec) { struct mgmt_pkt ev; ev.opcode = MGMT_OP_NOTIFY_SCO_CONNECTION_CHANGE; ev.index = HCI_DEV_NONE; ev.len = sizeof(struct mgmt_cp_notify_sco_connection_change); struct mgmt_cp_notify_sco_connection_change* cp = - reinterpret_cast(ev.data); + reinterpret_cast(ev.data); cp->hci_dev = hci; cp->connected = is_connected; @@ -265,8 +259,7 @@ int mgmt_notify_sco_connection_change(int fd, int hci, RawAddress device, if (ret > 0) { RETRY_ON_INTR(ret = write(fd, &ev, MGMT_PKT_HDR_SIZE + ev.len)); if (ret < 0) { - log::error("Failed to call MGMT_OP_NOTIFY_SCO_CONNECTION_CHANGE: {}", - -errno); + log::error("Failed to call MGMT_OP_NOTIFY_SCO_CONNECTION_CHANGE: {}", -errno); return -errno; }; break; @@ -302,15 +295,13 @@ void init() { // Check if the specified coding format is supported by the adapter. bool is_coding_format_supported(esco_coding_format_t coding_format) { - if (coding_format != ESCO_CODING_FORMAT_TRANSPNT && - coding_format != ESCO_CODING_FORMAT_MSBC) { + if (coding_format != ESCO_CODING_FORMAT_TRANSPNT && coding_format != ESCO_CODING_FORMAT_MSBC) { log::warn("Unsupported coding format to query: {}", coding_format); return false; } for (cached_codec_info c : cached_codecs) { - if (c.inner.codec == MSBC_TRANSPARENT && - coding_format == ESCO_CODING_FORMAT_TRANSPNT) { + if (c.inner.codec == MSBC_TRANSPARENT && coding_format == ESCO_CODING_FORMAT_TRANSPNT) { return true; } if (c.inner.codec == MSBC && coding_format == ESCO_CODING_FORMAT_MSBC) { @@ -381,8 +372,7 @@ void set_codec_datapath(tBTA_AG_UUID_CODEC codec_uuid) { bt_codec* codec; uint8_t codec_id; - if (codec_uuid == tBTA_AG_UUID_CODEC::UUID_CODEC_LC3 && - get_offload_enabled()) { + if (codec_uuid == tBTA_AG_UUID_CODEC::UUID_CODEC_LC3 && get_offload_enabled()) { log::error("Offload path for LC3 is not implemented."); return; } @@ -398,26 +388,23 @@ void set_codec_datapath(tBTA_AG_UUID_CODEC codec_uuid) { codec_id = get_offload_enabled() ? codec::LC3 : codec::MSBC_TRANSPARENT; break; default: - log::warn("Unsupported codec ({}). Won't set datapath.", - bta_ag_uuid_codec_text(codec_uuid)); + log::warn("Unsupported codec ({}). Won't set datapath.", bta_ag_uuid_codec_text(codec_uuid)); return; } found = get_single_codec(codec_id, &codec); if (!found) { - log::error( - "Failed to find codec config for codec ({}). Won't set datapath.", - bta_ag_uuid_codec_text(codec_uuid)); + log::error("Failed to find codec config for codec ({}). Won't set datapath.", + bta_ag_uuid_codec_text(codec_uuid)); return; } - log::info("Configuring datapath for codec ({})", - bta_ag_uuid_codec_text(codec_uuid)); + log::info("Configuring datapath for codec ({})", bta_ag_uuid_codec_text(codec_uuid)); if (codec->codec == codec::MSBC && !get_offload_enabled()) { log::error( - "Tried to configure offload data path for format ({}) with offload " - "disabled. Won't set datapath.", - bta_ag_uuid_codec_text(codec_uuid)); + "Tried to configure offload data path for format ({}) with offload " + "disabled. Won't set datapath.", + bta_ag_uuid_codec_text(codec_uuid)); return; } @@ -434,10 +421,10 @@ void set_codec_datapath(tBTA_AG_UUID_CODEC codec_uuid) { break; } - GetInterface().ConfigureDataPath(hci_data_direction_t::CONTROLLER_TO_HOST, - OFFLOAD_DATAPATH, data); - GetInterface().ConfigureDataPath(hci_data_direction_t::HOST_TO_CONTROLLER, - OFFLOAD_DATAPATH, data); + GetInterface().ConfigureDataPath(hci_data_direction_t::CONTROLLER_TO_HOST, OFFLOAD_DATAPATH, + data); + GetInterface().ConfigureDataPath(hci_data_direction_t::HOST_TO_CONTROLLER, OFFLOAD_DATAPATH, + data); } } @@ -451,8 +438,7 @@ size_t get_packet_size(int codec) { return kDefaultPacketSize; } -void notify_sco_connection_change(RawAddress device, bool is_connected, - int codec) { +void notify_sco_connection_change(RawAddress device, bool is_connected, int codec) { int hci = bluetooth::common::InitFlags::GetAdapterIndex(); int fd = btsocket_open_mgmt(hci); if (fd < 0) { @@ -478,18 +464,17 @@ void notify_sco_connection_change(RawAddress device, bool is_connected, converted_codec = MGMT_SCO_CODEC_CVSD; } - int ret = mgmt_notify_sco_connection_change(fd, hci, device, is_connected, - converted_codec); + int ret = mgmt_notify_sco_connection_change(fd, hci, device, is_connected, converted_codec); if (ret) { log::error( - "Failed to notify HAL of connection change: hci {}, device {}, " - "connected {}, codec {}", - hci, device, is_connected, codec); + "Failed to notify HAL of connection change: hci {}, device {}, " + "connected {}, codec {}", + hci, device, is_connected, codec); } else { log::info( - "Notified HAL of connection change: hci {}, device {}, connected {}, " - "codec {}", - hci, device, is_connected, codec); + "Notified HAL of connection change: hci {}, device {}, connected {}, " + "codec {}", + hci, device, is_connected, codec); } close(fd); diff --git a/system/stack/btm/btm_sec.cc b/system/stack/btm/btm_sec.cc index 1c46c8321db..8b200c594b6 100644 --- a/system/stack/btm/btm_sec.cc +++ b/system/stack/btm/btm_sec.cc @@ -89,17 +89,15 @@ extern tBTM_CB btm_cb; #define BTM_SEC_MAX_COLLISION_DELAY (5000) #define BTM_SEC_START_AUTH_DELAY (200) -#define BTM_SEC_IS_SM4(sm) ((bool)(BTM_SM4_TRUE == ((sm)&BTM_SM4_TRUE))) -#define BTM_SEC_IS_SM4_LEGACY(sm) ((bool)(BTM_SM4_KNOWN == ((sm)&BTM_SM4_TRUE))) -#define BTM_SEC_IS_SM4_UNKNOWN(sm) \ - ((bool)(BTM_SM4_UNKNOWN == ((sm)&BTM_SM4_TRUE))) +#define BTM_SEC_IS_SM4(sm) ((bool)(BTM_SM4_TRUE == ((sm) & BTM_SM4_TRUE))) +#define BTM_SEC_IS_SM4_LEGACY(sm) ((bool)(BTM_SM4_KNOWN == ((sm) & BTM_SM4_TRUE))) +#define BTM_SEC_IS_SM4_UNKNOWN(sm) ((bool)(BTM_SM4_UNKNOWN == ((sm) & BTM_SM4_TRUE))) -#define BTM_SEC_LE_MASK \ - (BTM_SEC_LE_AUTHENTICATED | BTM_SEC_LE_ENCRYPTED | \ - BTM_SEC_LE_LINK_KEY_KNOWN | BTM_SEC_LE_LINK_KEY_AUTHED) +#define BTM_SEC_LE_MASK \ + (BTM_SEC_LE_AUTHENTICATED | BTM_SEC_LE_ENCRYPTED | BTM_SEC_LE_LINK_KEY_KNOWN | \ + BTM_SEC_LE_LINK_KEY_AUTHED) -bool btm_ble_init_pseudo_addr(tBTM_SEC_DEV_REC* p_dev_rec, - const RawAddress& new_pseudo_addr); +bool btm_ble_init_pseudo_addr(tBTM_SEC_DEV_REC* p_dev_rec, const RawAddress& new_pseudo_addr); void bta_dm_remove_device(const RawAddress& bd_addr); void bta_dm_remote_key_missing(const RawAddress bd_addr); void bta_dm_process_remove_device(const RawAddress& bd_addr); @@ -114,60 +112,52 @@ static void btm_sec_pairing_timeout(void* data); static tBTM_STATUS btm_sec_dd_create_conn(tBTM_SEC_DEV_REC* p_dev_rec); static void btm_sec_check_pending_reqs(void); -static bool btm_sec_queue_mx_request(const RawAddress& bd_addr, uint16_t psm, - bool is_orig, uint16_t security_required, - tBTM_SEC_CALLBACK* p_callback, +static bool btm_sec_queue_mx_request(const RawAddress& bd_addr, uint16_t psm, bool is_orig, + uint16_t security_required, tBTM_SEC_CALLBACK* p_callback, void* p_ref_data); static void btm_sec_bond_cancel_complete(void); static void btm_send_link_key_notif(tBTM_SEC_DEV_REC* p_dev_rec); static bool btm_sec_check_prefetch_pin(tBTM_SEC_DEV_REC* p_dev_rec); -static tBTM_STATUS btm_sec_send_hci_disconnect(tBTM_SEC_DEV_REC* p_dev_rec, - tHCI_STATUS reason, - uint16_t conn_handle, - std::string comment); +static tBTM_STATUS btm_sec_send_hci_disconnect(tBTM_SEC_DEV_REC* p_dev_rec, tHCI_STATUS reason, + uint16_t conn_handle, std::string comment); static bool btm_dev_authenticated(const tBTM_SEC_DEV_REC* p_dev_rec); static bool btm_dev_encrypted(const tBTM_SEC_DEV_REC* p_dev_rec); -static uint16_t btm_sec_set_serv_level4_flags(uint16_t cur_security, - bool is_originator); +static uint16_t btm_sec_set_serv_level4_flags(uint16_t cur_security, bool is_originator); -static void btm_sec_queue_encrypt_request(const RawAddress& bd_addr, - tBT_TRANSPORT transport, - tBTM_SEC_CALLBACK* p_callback, - void* p_ref_data, +static void btm_sec_queue_encrypt_request(const RawAddress& bd_addr, tBT_TRANSPORT transport, + tBTM_SEC_CALLBACK* p_callback, void* p_ref_data, tBTM_BLE_SEC_ACT sec_act); -static void btm_sec_check_pending_enc_req(tBTM_SEC_DEV_REC* p_dev_rec, - tBT_TRANSPORT transport, +static void btm_sec_check_pending_enc_req(tBTM_SEC_DEV_REC* p_dev_rec, tBT_TRANSPORT transport, uint8_t encr_enable); static bool btm_sec_use_smp_br_chnl(tBTM_SEC_DEV_REC* p_dev_rec); /* true - authenticated link key is possible */ static const bool btm_sec_io_map[BTM_IO_CAP_MAX][BTM_IO_CAP_MAX] = { - /* OUT, IO, IN, NONE */ - /* OUT */ {false, false, true, false}, - /* IO */ {false, true, true, false}, - /* IN */ {true, true, true, false}, - /* NONE */ {false, false, false, false}}; + /* OUT, IO, IN, NONE */ + /* OUT */ {false, false, true, false}, + /* IO */ {false, true, true, false}, + /* IN */ {true, true, true, false}, + /* NONE */ {false, false, false, false}}; /* BTM_IO_CAP_OUT 0 DisplayOnly */ /* BTM_IO_CAP_IO 1 DisplayYesNo */ /* BTM_IO_CAP_IN 2 KeyboardOnly */ /* BTM_IO_CAP_NONE 3 NoInputNoOutput */ -static void NotifyBondingChange(tBTM_SEC_DEV_REC& p_dev_rec, - tHCI_STATUS status) { +static void NotifyBondingChange(tBTM_SEC_DEV_REC& p_dev_rec, tHCI_STATUS status) { if (btm_sec_cb.api.p_auth_complete_callback != nullptr) { - (*btm_sec_cb.api.p_auth_complete_callback)( - p_dev_rec.bd_addr, p_dev_rec.dev_class, p_dev_rec.sec_bd_name, status); + (*btm_sec_cb.api.p_auth_complete_callback)(p_dev_rec.bd_addr, p_dev_rec.dev_class, + p_dev_rec.sec_bd_name, status); } } static bool concurrentPeerAuthIsEnabled() { // Was previously named BTM_DISABLE_CONCURRENT_PEER_AUTH. // Renamed to ENABLED for homogeneity with system properties - static const bool sCONCURRENT_PEER_AUTH_IS_ENABLED = osi_property_get_bool( - "bluetooth.btm.sec.concurrent_peer_auth.enabled", true); + static const bool sCONCURRENT_PEER_AUTH_IS_ENABLED = + osi_property_get_bool("bluetooth.btm.sec.concurrent_peer_auth.enabled", true); return sCONCURRENT_PEER_AUTH_IS_ENABLED; } @@ -179,7 +169,7 @@ static bool concurrentPeerAuthIsEnabled() { */ static bool handleUnexpectedEncryptionChange() { static const bool sHandleUnexpectedEncryptionChange = osi_property_get_bool( - "bluetooth.btm.sec.handle_unexpected_encryption_change.enabled", false); + "bluetooth.btm.sec.handle_unexpected_encryption_change.enabled", false); return sHandleUnexpectedEncryptionChange; } @@ -233,7 +223,9 @@ static bool is_sec_state_equal(void* data, void* context) { tBTM_SEC_DEV_REC* p_dev_rec = static_cast(data); tSECURITY_STATE* state = static_cast(context); - if (p_dev_rec->sec_rec.sec_state == *state) return false; + if (p_dev_rec->sec_rec.sec_state == *state) { + return false; + } return true; } @@ -249,9 +241,10 @@ static bool is_sec_state_equal(void* data, void* context) { * ******************************************************************************/ static tBTM_SEC_DEV_REC* btm_sec_find_dev_by_sec_state(tSECURITY_STATE state) { - list_node_t* n = - list_foreach(btm_sec_cb.sec_dev_rec, is_sec_state_equal, &state); - if (n) return static_cast(list_node(n)); + list_node_t* n = list_foreach(btm_sec_cb.sec_dev_rec, is_sec_state_equal, &state); + if (n) { + return static_cast(list_node(n)); + } return nullptr; } @@ -268,23 +261,26 @@ static tBTM_SEC_DEV_REC* btm_sec_find_dev_by_sec_state(tSECURITY_STATE state) { * Returns bool * ******************************************************************************/ -static bool btm_sec_is_device_sc_downgrade(uint16_t hci_handle, - bool secure_connections_supported) { - if (secure_connections_supported) return false; +static bool btm_sec_is_device_sc_downgrade(uint16_t hci_handle, bool secure_connections_supported) { + if (secure_connections_supported) { + return false; + } tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev_by_handle(hci_handle); - if (p_dev_rec == nullptr) return false; + if (p_dev_rec == nullptr) { + return false; + } uint8_t property_val = 0; - bt_property_t property = { - .type = BT_PROPERTY_REMOTE_SECURE_CONNECTIONS_SUPPORTED, - .len = sizeof(uint8_t), - .val = &property_val}; + bt_property_t property = {.type = BT_PROPERTY_REMOTE_SECURE_CONNECTIONS_SUPPORTED, + .len = sizeof(uint8_t), + .val = &property_val}; - bt_status_t cached = - btif_storage_get_remote_device_property(&p_dev_rec->bd_addr, &property); + bt_status_t cached = btif_storage_get_remote_device_property(&p_dev_rec->bd_addr, &property); - if (cached == BT_STATUS_FAIL) return false; + if (cached == BT_STATUS_FAIL) { + return false; + } return (bool)property_val; } @@ -300,13 +296,14 @@ static bool btm_sec_is_device_sc_downgrade(uint16_t hci_handle, static void btm_sec_store_device_sc_support(uint16_t hci_handle, bool secure_connections_supported) { tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev_by_handle(hci_handle); - if (p_dev_rec == nullptr) return; + if (p_dev_rec == nullptr) { + return; + } uint8_t property_val = (uint8_t)secure_connections_supported; - bt_property_t property = { - .type = BT_PROPERTY_REMOTE_SECURE_CONNECTIONS_SUPPORTED, - .len = sizeof(uint8_t), - .val = &property_val}; + bt_property_t property = {.type = BT_PROPERTY_REMOTE_SECURE_CONNECTIONS_SUPPORTED, + .len = sizeof(uint8_t), + .val = &property_val}; btif_storage_set_remote_device_property(&p_dev_rec->bd_addr, &property); } @@ -322,20 +319,22 @@ static void btm_sec_store_device_sc_support(uint16_t hci_handle, * Returns bool * ******************************************************************************/ -static bool btm_sec_is_session_key_size_downgrade(uint16_t hci_handle, - uint8_t key_size) { +static bool btm_sec_is_session_key_size_downgrade(uint16_t hci_handle, uint8_t key_size) { tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev_by_handle(hci_handle); - if (p_dev_rec == nullptr) return false; + if (p_dev_rec == nullptr) { + return false; + } uint8_t property_val = 0; bt_property_t property = {.type = BT_PROPERTY_REMOTE_MAX_SESSION_KEY_SIZE, .len = sizeof(uint8_t), .val = &property_val}; - bt_status_t cached = - btif_storage_get_remote_device_property(&p_dev_rec->bd_addr, &property); + bt_status_t cached = btif_storage_get_remote_device_property(&p_dev_rec->bd_addr, &property); - if (cached == BT_STATUS_FAIL) return false; + if (cached == BT_STATUS_FAIL) { + return false; + } return property_val > key_size; } @@ -347,10 +346,11 @@ static bool btm_sec_is_session_key_size_downgrade(uint16_t hci_handle, * Description Store the max session key size to disk, if possible. * ******************************************************************************/ -static void btm_sec_update_session_key_size(uint16_t hci_handle, - uint8_t key_size) { +static void btm_sec_update_session_key_size(uint16_t hci_handle, uint8_t key_size) { tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev_by_handle(hci_handle); - if (p_dev_rec == nullptr) return; + if (p_dev_rec == nullptr) { + return; + } uint8_t property_val = key_size; bt_property_t property = {.type = BT_PROPERTY_REMOTE_MAX_SESSION_KEY_SIZE, @@ -372,8 +372,7 @@ static void btm_sec_update_session_key_size(uint16_t hci_handle, * ******************************************************************************/ static bool access_secure_service_from_temp_bond(const tBTM_SEC_DEV_REC* p_dev_rec, - bool locally_initiated, - uint16_t security_req) { + bool locally_initiated, uint16_t security_req) { return !locally_initiated && (security_req & BTM_SEC_IN_AUTHENTICATE) && p_dev_rec->sec_rec.is_bond_type_temporary(); } @@ -391,8 +390,7 @@ static bool access_secure_service_from_temp_bond(const tBTM_SEC_DEV_REC* p_dev_r * ******************************************************************************/ bool BTM_SecRegister(const tBTM_APPL_INFO* p_cb_info) { - log::info("p_cb_info->p_le_callback == 0x{}", - fmt::ptr(p_cb_info->p_le_callback)); + log::info("p_cb_info->p_le_callback == 0x{}", fmt::ptr(p_cb_info->p_le_callback)); if (p_cb_info->p_le_callback) { log::verbose("SMP_Register( btm_proc_smp_cback )"); SMP_Register(btm_proc_smp_cback); @@ -406,10 +404,9 @@ bool BTM_SecRegister(const tBTM_APPL_INFO* p_cb_info) { } btm_sec_cb.api = *p_cb_info; - log::info("btm_sec_cb.api.p_le_callback = 0x{}", - fmt::ptr(btm_sec_cb.api.p_le_callback)); + log::info("btm_sec_cb.api.p_le_callback = 0x{}", fmt::ptr(btm_sec_cb.api.p_le_callback)); log::verbose("application registered"); - return (true); + return true; } bool BTM_IsEncrypted(const RawAddress& bd_addr, tBT_TRANSPORT transport) { @@ -434,8 +431,8 @@ bool BTM_CanReadDiscoverableCharacteristics(const RawAddress& bd_addr) { return p_dev_rec->can_read_discoverable; } else { log::error( - "BTM_CanReadDiscoverableCharacteristics invoked for an invalid " - "BD_ADDR"); + "BTM_CanReadDiscoverableCharacteristics invoked for an invalid " + "BD_ADDR"); return false; } } @@ -450,13 +447,11 @@ bool BTM_CanReadDiscoverableCharacteristics(const RawAddress& bd_addr) { * ******************************************************************************/ void BTM_SetPinType(uint8_t pin_type, PIN_CODE pin_code, uint8_t pin_code_len) { - log::verbose( - "BTM_SetPinType: pin type {} [variable-0, fixed-1], code {}, length {}", - pin_type, (char*)pin_code, pin_code_len); + log::verbose("BTM_SetPinType: pin type {} [variable-0, fixed-1], code {}, length {}", pin_type, + (char*)pin_code, pin_code_len); /* If device is not up security mode will be set as a part of startup */ - if ((btm_sec_cb.cfg.pin_type != pin_type) && - bluetooth::shim::GetController() != nullptr) { + if ((btm_sec_cb.cfg.pin_type != pin_type) && bluetooth::shim::GetController() != nullptr) { btsnd_hcic_write_pin_type(pin_type); } @@ -485,11 +480,11 @@ void BTM_SetPinType(uint8_t pin_type, PIN_CODE pin_code, uint8_t pin_code_len) { * Returns true if registered OK, else false * ******************************************************************************/ -bool BTM_SetSecurityLevel(bool is_originator, const char* p_name, - uint8_t service_id, uint16_t sec_level, uint16_t psm, - uint32_t mx_proto_id, uint32_t mx_chan_id) { - return btm_sec_cb.AddService(is_originator, p_name, service_id, sec_level, - psm, mx_proto_id, mx_chan_id); +bool BTM_SetSecurityLevel(bool is_originator, const char* p_name, uint8_t service_id, + uint16_t sec_level, uint16_t psm, uint32_t mx_proto_id, + uint32_t mx_chan_id) { + return btm_sec_cb.AddService(is_originator, p_name, service_id, sec_level, psm, mx_proto_id, + mx_chan_id); } /******************************************************************************* @@ -510,9 +505,7 @@ bool BTM_SetSecurityLevel(bool is_originator, const char* p_name, * Returns Number of records that were freed. * ******************************************************************************/ -uint8_t BTM_SecClrService(uint8_t service_id) { - return btm_sec_cb.RemoveServiceById(service_id); -} +uint8_t BTM_SecClrService(uint8_t service_id) { return btm_sec_cb.RemoveServiceById(service_id); } /******************************************************************************* * @@ -530,9 +523,7 @@ uint8_t BTM_SecClrService(uint8_t service_id) { * Returns Number of records that were freed. * ******************************************************************************/ -uint8_t BTM_SecClrServiceByPsm(uint16_t psm) { - return btm_sec_cb.RemoveServiceByPsm(psm); -} +uint8_t BTM_SecClrServiceByPsm(uint16_t psm) { return btm_sec_cb.RemoveServiceByPsm(psm); } /******************************************************************************* * @@ -549,15 +540,14 @@ uint8_t BTM_SecClrServiceByPsm(uint16_t psm) { * p_pin - pointer to array with the PIN Code * ******************************************************************************/ -void BTM_PINCodeReply(const RawAddress& bd_addr, tBTM_STATUS res, - uint8_t pin_len, uint8_t* p_pin) { +void BTM_PINCodeReply(const RawAddress& bd_addr, tBTM_STATUS res, uint8_t pin_len, uint8_t* p_pin) { tBTM_SEC_DEV_REC* p_dev_rec; log::verbose( - "BTM_PINCodeReply(): PairState: {} PairFlags: 0x{:02x} PinLen:{} " - "Result:{}", - tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state), - btm_sec_cb.pairing_flags, pin_len, res); + "BTM_PINCodeReply(): PairState: {} PairFlags: 0x{:02x} PinLen:{} " + "Result:{}", + tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state), btm_sec_cb.pairing_flags, + pin_len, res); /* If timeout already expired or has been canceled, ignore the reply */ if (btm_sec_cb.pairing_state != BTM_PAIR_STATE_WAIT_LOCAL_PIN) { @@ -576,8 +566,9 @@ void BTM_PINCodeReply(const RawAddress& bd_addr, tBTM_STATUS res, return; } - if ((pin_len > PIN_CODE_LEN) || (pin_len == 0) || (p_pin == NULL)) + if ((pin_len > PIN_CODE_LEN) || (pin_len == 0) || (p_pin == NULL)) { res = BTM_ILLEGAL_VALUE; + } if (res != BTM_SUCCESS) { /* if peer started dd OR we started dd and pre-fetch pin was not used send @@ -604,8 +595,7 @@ void BTM_PINCodeReply(const RawAddress& bd_addr, tBTM_STATUS res, } if ((btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD) && - (p_dev_rec->hci_handle == HCI_INVALID_HANDLE) && - (!btm_sec_cb.security_mode_changed)) { + (p_dev_rec->hci_handle == HCI_INVALID_HANDLE) && (!btm_sec_cb.security_mode_changed)) { /* This is start of the dedicated bonding if local device is 2.0 */ btm_sec_cb.pin_code_len = pin_len; memcpy(btm_sec_cb.pin_code, p_pin, pin_len); @@ -620,8 +610,8 @@ void BTM_PINCodeReply(const RawAddress& bd_addr, tBTM_STATUS res, /* before originating */ if (btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_REJECTED_CONNECT) { log::warn( - "BTM_PINCodeReply(): waiting HCI_Connection_Complete after rejected " - "incoming connection"); + "BTM_PINCodeReply(): waiting HCI_Connection_Complete after rejected " + "incoming connection"); /* we change state little bit early so btm_sec_connected() will originate * connection */ /* when existing ACL link is down completely */ @@ -630,8 +620,8 @@ void BTM_PINCodeReply(const RawAddress& bd_addr, tBTM_STATUS res, /* if we already accepted incoming connection from pairing device */ else if (p_dev_rec->sm4 & BTM_SM4_CONN_PEND) { log::warn( - "BTM_PINCodeReply(): link is connecting so wait pin code request " - "from peer"); + "BTM_PINCodeReply(): link is connecting so wait pin code request " + "from peer"); btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_WAIT_PIN_REQ); } else if (btm_sec_dd_create_conn(p_dev_rec) != BTM_CMD_STARTED) { btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_IDLE); @@ -660,8 +650,7 @@ void BTM_PINCodeReply(const RawAddress& bd_addr, tBTM_STATUS res, * * Note: After 2.1 parameters are not used and preserved here not to change API ******************************************************************************/ -tBTM_STATUS btm_sec_bond_by_transport(const RawAddress& bd_addr, - tBLE_ADDR_TYPE addr_type, +tBTM_STATUS btm_sec_bond_by_transport(const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type, tBT_TRANSPORT transport) { tBTM_SEC_DEV_REC* p_dev_rec; tBTM_STATUS status; @@ -671,37 +660,35 @@ tBTM_STATUS btm_sec_bond_by_transport(const RawAddress& bd_addr, if (btm_sec_cb.pairing_state != BTM_PAIR_STATE_IDLE) { log::error("BTM_SecBond: already busy in state: {}", tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state)); - return (BTM_WRONG_MODE); + return BTM_WRONG_MODE; } p_dev_rec = btm_find_or_alloc_dev(bd_addr); if (p_dev_rec == NULL) { log::error("No memory to allocate new p_dev_rec"); - return (BTM_NO_RESOURCES); + return BTM_NO_RESOURCES; } if (bluetooth::shim::GetController() == nullptr) { log::error("controller module is not ready"); - return (BTM_NO_RESOURCES); + return BTM_NO_RESOURCES; } log::verbose("before update sec_flags=0x{:x}", p_dev_rec->sec_rec.sec_flags); /* Finished if connection is active and already paired */ - if (((p_dev_rec->hci_handle != HCI_INVALID_HANDLE) && - transport == BT_TRANSPORT_BR_EDR && + if (((p_dev_rec->hci_handle != HCI_INVALID_HANDLE) && transport == BT_TRANSPORT_BR_EDR && (p_dev_rec->sec_rec.sec_flags & BTM_SEC_AUTHENTICATED)) || - ((p_dev_rec->ble_hci_handle != HCI_INVALID_HANDLE) && - transport == BT_TRANSPORT_LE && + ((p_dev_rec->ble_hci_handle != HCI_INVALID_HANDLE) && transport == BT_TRANSPORT_LE && (p_dev_rec->sec_rec.sec_flags & BTM_SEC_LE_AUTHENTICATED))) { log::warn("BTM_SecBond -> Already Paired"); - return (BTM_SUCCESS); + return BTM_SUCCESS; } /* Tell controller to get rid of the link key if it has one stored */ if ((BTM_DeleteStoredLinkKey(&bd_addr, NULL)) != BTM_SUCCESS) { log::error("Failed to delete stored link keys"); - return (BTM_NO_RESOURCES); + return BTM_NO_RESOURCES; } btm_sec_cb.pairing_bda = bd_addr; @@ -711,8 +698,7 @@ tBTM_STATUS btm_sec_bond_by_transport(const RawAddress& bd_addr, p_dev_rec->sec_rec.security_required = BTM_SEC_OUT_AUTHENTICATE; p_dev_rec->is_originator = true; - BTM_LogHistory(kBtmLogTag, bd_addr, "Bonding initiated", - bt_transport_text(transport)); + BTM_LogHistory(kBtmLogTag, bd_addr, "Bonding initiated", bt_transport_text(transport)); if (transport == BT_TRANSPORT_LE) { btm_ble_init_pseudo_addr(p_dev_rec, bd_addr); @@ -726,20 +712,19 @@ tBTM_STATUS btm_sec_bond_by_transport(const RawAddress& bd_addr, } btm_sec_cb.pairing_flags = 0; - return (BTM_NO_RESOURCES); + return BTM_NO_RESOURCES; } p_dev_rec->sec_rec.sec_flags &= - ~(BTM_SEC_LINK_KEY_KNOWN | BTM_SEC_AUTHENTICATED | BTM_SEC_ENCRYPTED | - BTM_SEC_ROLE_SWITCHED | BTM_SEC_LINK_KEY_AUTHED); + ~(BTM_SEC_LINK_KEY_KNOWN | BTM_SEC_AUTHENTICATED | BTM_SEC_ENCRYPTED | + BTM_SEC_ROLE_SWITCHED | BTM_SEC_LINK_KEY_AUTHED); log::verbose("after update sec_flags=0x{:x}", p_dev_rec->sec_rec.sec_flags); if (!bluetooth::shim::GetController()->SupportsSimplePairing()) { /* The special case when we authenticate keyboard. Set pin type to fixed */ /* It would be probably better to do it from the application, but it is */ /* complicated */ - if (((p_dev_rec->dev_class[1] & BTM_COD_MAJOR_CLASS_MASK) == - BTM_COD_MAJOR_PERIPHERAL) && + if (((p_dev_rec->dev_class[1] & BTM_COD_MAJOR_CLASS_MASK) == BTM_COD_MAJOR_PERIPHERAL) && (p_dev_rec->dev_class[2] & BTM_COD_MINOR_KEYBOARD) && (btm_sec_cb.cfg.pin_type != HCI_PIN_TYPE_FIXED)) { btm_sec_cb.pin_type_changed = true; @@ -747,32 +732,31 @@ tBTM_STATUS btm_sec_bond_by_transport(const RawAddress& bd_addr, } } - log::verbose("BTM_SecBond: Remote sm4: 0x{:x} HCI Handle: 0x{:04x}", - p_dev_rec->sm4, p_dev_rec->hci_handle); + log::verbose("BTM_SecBond: Remote sm4: 0x{:x} HCI Handle: 0x{:04x}", p_dev_rec->sm4, + p_dev_rec->hci_handle); /* If connection already exists... */ if (BTM_IsAclConnectionUpAndHandleValid(bd_addr, transport)) { - log::debug("An ACL connection currently exists peer:{} transport:{}", - bd_addr, bt_transport_text(transport)); + log::debug("An ACL connection currently exists peer:{} transport:{}", bd_addr, + bt_transport_text(transport)); btm_sec_wait_and_start_authentication(p_dev_rec); btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_WAIT_PIN_REQ); /* Mark lcb as bonding */ l2cu_update_lcb_4_bonding(bd_addr, true); - return (BTM_CMD_STARTED); + return BTM_CMD_STARTED; } - log::debug("An ACL connection does not currently exist peer:{} transport:{}", - bd_addr, bt_transport_text(transport)); + log::debug("An ACL connection does not currently exist peer:{} transport:{}", bd_addr, + bt_transport_text(transport)); - log::verbose("sec mode: {} sm4:x{:x}", btm_sec_cb.security_mode, - p_dev_rec->sm4); + log::verbose("sec mode: {} sm4:x{:x}", btm_sec_cb.security_mode, p_dev_rec->sm4); if (!bluetooth::shim::GetController()->SupportsSimplePairing() || (p_dev_rec->sm4 == BTM_SM4_KNOWN)) { if (btm_sec_check_prefetch_pin(p_dev_rec)) { - log::debug("Class of device used to check for pin peer:{} transport:{}", - bd_addr, bt_transport_text(transport)); - return (BTM_CMD_STARTED); + log::debug("Class of device used to check for pin peer:{} transport:{}", bd_addr, + bt_transport_text(transport)); + return BTM_CMD_STARTED; } } if ((btm_sec_cb.security_mode == BTM_SEC_MODE_SP || @@ -784,25 +768,23 @@ tBTM_STATUS btm_sec_bond_by_transport(const RawAddress& bd_addr, * -> RNR (to learn if peer is 2.1) * RNR when no ACL causes HCI_RMT_HOST_SUP_FEAT_NOTIFY_EVT */ btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_GET_REM_NAME); - status = get_btm_client_interface().peer.BTM_ReadRemoteDeviceName( - bd_addr, NULL, BT_TRANSPORT_BR_EDR); + status = get_btm_client_interface().peer.BTM_ReadRemoteDeviceName(bd_addr, NULL, + BT_TRANSPORT_BR_EDR); } else { /* We are accepting connection request from peer */ btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_WAIT_PIN_REQ); status = BTM_CMD_STARTED; } log::verbose("State:{} sm4: 0x{:x} sec_state:{}", - tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state), - p_dev_rec->sm4, p_dev_rec->sec_rec.sec_state); + tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state), p_dev_rec->sm4, + p_dev_rec->sec_rec.sec_state); } else { /* both local and peer are 2.1 */ status = btm_sec_dd_create_conn(p_dev_rec); } if (status != BTM_CMD_STARTED) { - log::error( - "BTM_ReadRemoteDeviceName or btm_sec_dd_create_conn error: 0x{:x}", - (int)status); + log::error("BTM_ReadRemoteDeviceName or btm_sec_dd_create_conn error: 0x{:x}", (int)status); btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_IDLE); } @@ -823,12 +805,10 @@ tBTM_STATUS btm_sec_bond_by_transport(const RawAddress& bd_addr, * Note: After 2.1 parameters are not used and preserved here not to change API ******************************************************************************/ tBTM_STATUS BTM_SecBond(const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type, - tBT_TRANSPORT transport, - tBT_DEVICE_TYPE /* device_type */) { + tBT_TRANSPORT transport, tBT_DEVICE_TYPE /* device_type */) { if (transport == BT_TRANSPORT_AUTO) { if (addr_type == BLE_ADDR_PUBLIC) { - transport = - BTM_UseLeLink(bd_addr) ? BT_TRANSPORT_LE : BT_TRANSPORT_BR_EDR; + transport = BTM_UseLeLink(bd_addr) ? BT_TRANSPORT_LE : BT_TRANSPORT_BR_EDR; } else { log::info("Forcing transport LE (was auto) because of the address type"); transport = BT_TRANSPORT_LE; @@ -839,8 +819,7 @@ tBTM_STATUS BTM_SecBond(const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type, BTM_ReadDevInfo(bd_addr, &dev_type, &addr_type); /* LE device, do SMP pairing */ if ((transport == BT_TRANSPORT_LE && (dev_type & BT_DEVICE_TYPE_BLE) == 0) || - (transport == BT_TRANSPORT_BR_EDR && - (dev_type & BT_DEVICE_TYPE_BREDR) == 0)) { + (transport == BT_TRANSPORT_BR_EDR && (dev_type & BT_DEVICE_TYPE_BREDR) == 0)) { log::warn("Requested transport and supported transport don't match"); if (!com::android::bluetooth::flags::pairing_on_unknown_transport()) { return BTM_ILLEGAL_ACTION; @@ -898,16 +877,16 @@ tBTM_STATUS BTM_SecBondCancel(const RawAddress& bd_addr) { /* If some other thread disconnecting, we do not send second command */ if ((p_dev_rec->sec_rec.sec_state == tSECURITY_STATE::DISCONNECTING) || (p_dev_rec->sec_rec.sec_state == tSECURITY_STATE::DISCONNECTING_BOTH)) { - return (BTM_CMD_STARTED); + return BTM_CMD_STARTED; } /* If the HCI link was set up by Bonding process */ - if (btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_DISC_WHEN_DONE) - return btm_sec_send_hci_disconnect( - p_dev_rec, HCI_ERR_PEER_USER, p_dev_rec->hci_handle, - "stack::btm::btm_sec::BTM_SecBondCancel"); - else + if (btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_DISC_WHEN_DONE) { + return btm_sec_send_hci_disconnect(p_dev_rec, HCI_ERR_PEER_USER, p_dev_rec->hci_handle, + "stack::btm::btm_sec::BTM_SecBondCancel"); + } else { l2cu_update_lcb_4_bonding(bd_addr, false); + } return BTM_NOT_AUTHORIZED; } else /*HCI link is not up */ @@ -918,8 +897,7 @@ tBTM_STATUS BTM_SecBondCancel(const RawAddress& bd_addr) { return BTM_CMD_STARTED; } if (btm_sec_cb.pairing_state == BTM_PAIR_STATE_GET_REM_NAME) { - if (get_btm_client_interface().peer.BTM_CancelRemoteDeviceName() != - BTM_SUCCESS) { + if (get_btm_client_interface().peer.BTM_CancelRemoteDeviceName() != BTM_SUCCESS) { log::warn("Unable to cancel RNR"); } btm_sec_cb.pairing_flags |= BTM_PAIR_FLAGS_WE_CANCEL_DD; @@ -949,8 +927,7 @@ tBTM_STATUS BTM_SecBondCancel(const RawAddress& bd_addr) { tBTM_LINK_KEY_TYPE BTM_SecGetDeviceLinkKeyType(const RawAddress& bd_addr) { tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr); - if ((p_dev_rec != NULL) && - (p_dev_rec->sec_rec.sec_flags & BTM_SEC_LINK_KEY_KNOWN)) { + if ((p_dev_rec != NULL) && (p_dev_rec->sec_rec.sec_flags & BTM_SEC_LINK_KEY_KNOWN)) { return p_dev_rec->sec_rec.link_key_type; } return BTM_LKEY_TYPE_IGNORE; @@ -982,8 +959,7 @@ tBTM_LINK_KEY_TYPE BTM_SecGetDeviceLinkKeyType(const RawAddress& bd_addr) { * BTM_MODE_UNSUPPORTED - if security manager not linked in. * ******************************************************************************/ -tBTM_STATUS BTM_SetEncryption(const RawAddress& bd_addr, - tBT_TRANSPORT transport, +tBTM_STATUS BTM_SetEncryption(const RawAddress& bd_addr, tBT_TRANSPORT transport, tBTM_SEC_CALLBACK* p_callback, void* p_ref_data, tBTM_BLE_SEC_ACT sec_act) { tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr); @@ -996,25 +972,23 @@ tBTM_STATUS BTM_SetEncryption(const RawAddress& bd_addr, case BT_TRANSPORT_BR_EDR: if (p_dev_rec->hci_handle == HCI_INVALID_HANDLE) { log::warn( - "Security Manager: BTM_SetEncryption not connected peer:{} " - "transport:{}", - bd_addr, bt_transport_text(transport)); + "Security Manager: BTM_SetEncryption not connected peer:{} " + "transport:{}", + bd_addr, bt_transport_text(transport)); if (p_callback) { - do_in_main_thread(FROM_HERE, - base::BindOnce(p_callback, bd_addr, transport, - p_ref_data, BTM_WRONG_MODE)); + do_in_main_thread(FROM_HERE, base::BindOnce(p_callback, bd_addr, transport, p_ref_data, + BTM_WRONG_MODE)); } return BTM_WRONG_MODE; } if (p_dev_rec->sec_rec.sec_flags & BTM_SEC_ENCRYPTED) { log::debug( - "Security Manager: BTM_SetEncryption already encrypted peer:{} " - "transport:{}", - bd_addr, bt_transport_text(transport)); + "Security Manager: BTM_SetEncryption already encrypted peer:{} " + "transport:{}", + bd_addr, bt_transport_text(transport)); if (p_callback) { - do_in_main_thread(FROM_HERE, - base::BindOnce(p_callback, bd_addr, transport, - p_ref_data, BTM_SUCCESS)); + do_in_main_thread(FROM_HERE, base::BindOnce(p_callback, bd_addr, transport, p_ref_data, + BTM_SUCCESS)); } return BTM_SUCCESS; } @@ -1023,25 +997,23 @@ tBTM_STATUS BTM_SetEncryption(const RawAddress& bd_addr, case BT_TRANSPORT_LE: if (p_dev_rec->ble_hci_handle == HCI_INVALID_HANDLE) { log::warn( - "Security Manager: BTM_SetEncryption not connected peer:{} " - "transport:{}", - bd_addr, bt_transport_text(transport)); + "Security Manager: BTM_SetEncryption not connected peer:{} " + "transport:{}", + bd_addr, bt_transport_text(transport)); if (p_callback) { - do_in_main_thread(FROM_HERE, - base::BindOnce(p_callback, bd_addr, transport, - p_ref_data, BTM_WRONG_MODE)); + do_in_main_thread(FROM_HERE, base::BindOnce(p_callback, bd_addr, transport, p_ref_data, + BTM_WRONG_MODE)); } return BTM_WRONG_MODE; } if (p_dev_rec->sec_rec.sec_flags & BTM_SEC_LE_ENCRYPTED) { log::debug( - "Security Manager: BTM_SetEncryption already encrypted peer:{} " - "transport:{}", - bd_addr, bt_transport_text(transport)); + "Security Manager: BTM_SetEncryption already encrypted peer:{} " + "transport:{}", + bd_addr, bt_transport_text(transport)); if (p_callback) { - do_in_main_thread(FROM_HERE, - base::BindOnce(p_callback, bd_addr, transport, - p_ref_data, BTM_SUCCESS)); + do_in_main_thread(FROM_HERE, base::BindOnce(p_callback, bd_addr, transport, p_ref_data, + BTM_SUCCESS)); } return BTM_SUCCESS; } @@ -1090,24 +1062,22 @@ tBTM_STATUS BTM_SetEncryption(const RawAddress& bd_addr, p_dev_rec->sec_rec.p_callback = p_callback; p_dev_rec->sec_rec.p_ref_data = p_ref_data; - p_dev_rec->sec_rec.security_required |= - (BTM_SEC_IN_AUTHENTICATE | BTM_SEC_IN_ENCRYPT); + p_dev_rec->sec_rec.security_required |= (BTM_SEC_IN_AUTHENTICATE | BTM_SEC_IN_ENCRYPT); p_dev_rec->is_originator = false; log::debug( - "Security Manager: BTM_SetEncryption classic_handle:0x{:04x} " - "ble_handle:0x{:04x} state:{} flags:0x{:x} required:0x{:x} " - "p_callback={:c}", - p_dev_rec->hci_handle, p_dev_rec->ble_hci_handle, - p_dev_rec->sec_rec.sec_state, p_dev_rec->sec_rec.sec_flags, - p_dev_rec->sec_rec.security_required, (p_callback) ? 'T' : 'F'); + "Security Manager: BTM_SetEncryption classic_handle:0x{:04x} " + "ble_handle:0x{:04x} state:{} flags:0x{:x} required:0x{:x} " + "p_callback={:c}", + p_dev_rec->hci_handle, p_dev_rec->ble_hci_handle, p_dev_rec->sec_rec.sec_state, + p_dev_rec->sec_rec.sec_flags, p_dev_rec->sec_rec.security_required, + (p_callback) ? 'T' : 'F'); tBTM_STATUS rc = BTM_SUCCESS; switch (transport) { case BT_TRANSPORT_LE: if (BTM_IsAclConnectionUp(bd_addr, BT_TRANSPORT_LE)) { - rc = btm_ble_set_encryption(bd_addr, sec_act, - L2CA_GetBleConnRole(bd_addr)); + rc = btm_ble_set_encryption(bd_addr, sec_act, L2CA_GetBleConnRole(bd_addr)); } else { rc = BTM_WRONG_MODE; log::warn("cannot call btm_ble_set_encryption, p is NULL"); @@ -1130,12 +1100,11 @@ tBTM_STATUS BTM_SetEncryption(const RawAddress& bd_addr, default: if (p_callback) { - log::debug("Executing encryption callback peer:{} transport:{}", - bd_addr, bt_transport_text(transport)); + log::debug("Executing encryption callback peer:{} transport:{}", bd_addr, + bt_transport_text(transport)); p_dev_rec->sec_rec.p_callback = nullptr; - do_in_main_thread(FROM_HERE, - base::BindOnce(p_callback, bd_addr, transport, - p_dev_rec->sec_rec.p_ref_data, rc)); + do_in_main_thread(FROM_HERE, base::BindOnce(p_callback, bd_addr, transport, + p_dev_rec->sec_rec.p_ref_data, rc)); } break; } @@ -1151,12 +1120,9 @@ bool BTM_SecIsSecurityPending(const RawAddress& bd_addr) { /******************************************************************************* * disconnect the ACL link, if it's not done yet. ******************************************************************************/ -static tBTM_STATUS btm_sec_send_hci_disconnect(tBTM_SEC_DEV_REC* p_dev_rec, - tHCI_STATUS reason, - uint16_t conn_handle, - std::string comment) { - const tSECURITY_STATE old_state = - static_cast(p_dev_rec->sec_rec.sec_state); +static tBTM_STATUS btm_sec_send_hci_disconnect(tBTM_SEC_DEV_REC* p_dev_rec, tHCI_STATUS reason, + uint16_t conn_handle, std::string comment) { + const tSECURITY_STATE old_state = static_cast(p_dev_rec->sec_rec.sec_state); const tBTM_STATUS status = BTM_CMD_STARTED; /* send HCI_Disconnect on a transport only once */ @@ -1212,16 +1178,13 @@ static tBTM_STATUS btm_sec_send_hci_disconnect(tBTM_SEC_DEV_REC* p_dev_rec, ******************************************************************************/ void BTM_ConfirmReqReply(tBTM_STATUS res, const RawAddress& bd_addr) { log::verbose("BTM_ConfirmReqReply() State: {} Res: {}", - tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state), - res); + tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state), res); /* If timeout already expired or has been canceled, ignore the reply */ if ((btm_sec_cb.pairing_state != BTM_PAIR_STATE_WAIT_NUMERIC_CONFIRM) || (btm_sec_cb.pairing_bda != bd_addr)) { - log::warn( - "Unexpected pairing confirm for {}, pairing_state: {}, pairing_bda: {}", - bd_addr, tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state), - btm_sec_cb.pairing_bda); + log::warn("Unexpected pairing confirm for {}, pairing_state: {}, pairing_bda: {}", bd_addr, + tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state), btm_sec_cb.pairing_bda); return; } @@ -1256,41 +1219,39 @@ void BTM_ConfirmReqReply(tBTM_STATUS res, const RawAddress& bd_addr) { * BTM_MAX_PASSKEY_VAL(999999(0xF423F)). * ******************************************************************************/ -void BTM_PasskeyReqReply(tBTM_STATUS res, const RawAddress& bd_addr, - uint32_t passkey) { +void BTM_PasskeyReqReply(tBTM_STATUS res, const RawAddress& bd_addr, uint32_t passkey) { log::verbose("BTM_PasskeyReqReply: State: {} res:{}", - tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state), - res); + tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state), res); - if ((btm_sec_cb.pairing_state == BTM_PAIR_STATE_IDLE) || - (btm_sec_cb.pairing_bda != bd_addr)) { + if ((btm_sec_cb.pairing_state == BTM_PAIR_STATE_IDLE) || (btm_sec_cb.pairing_bda != bd_addr)) { return; } /* If timeout already expired or has been canceled, ignore the reply */ - if ((btm_sec_cb.pairing_state == BTM_PAIR_STATE_WAIT_AUTH_COMPLETE) && - (res != BTM_SUCCESS)) { + if ((btm_sec_cb.pairing_state == BTM_PAIR_STATE_WAIT_AUTH_COMPLETE) && (res != BTM_SUCCESS)) { tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr); if (p_dev_rec != NULL) { acl_set_disconnect_reason(HCI_ERR_HOST_REJECT_SECURITY); - if (p_dev_rec->hci_handle != HCI_INVALID_HANDLE) - btm_sec_send_hci_disconnect( - p_dev_rec, HCI_ERR_AUTH_FAILURE, p_dev_rec->hci_handle, - "stack::btm::btm_sec::BTM_PasskeyReqReply Invalid handle"); - else + if (p_dev_rec->hci_handle != HCI_INVALID_HANDLE) { + btm_sec_send_hci_disconnect(p_dev_rec, HCI_ERR_AUTH_FAILURE, p_dev_rec->hci_handle, + "stack::btm::btm_sec::BTM_PasskeyReqReply Invalid handle"); + } else { BTM_SecBondCancel(bd_addr); + } - p_dev_rec->sec_rec.sec_flags &= - ~(BTM_SEC_LINK_KEY_AUTHED | BTM_SEC_LINK_KEY_KNOWN); + p_dev_rec->sec_rec.sec_flags &= ~(BTM_SEC_LINK_KEY_AUTHED | BTM_SEC_LINK_KEY_KNOWN); btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_IDLE); return; } - } else if (btm_sec_cb.pairing_state != BTM_PAIR_STATE_KEY_ENTRY) + } else if (btm_sec_cb.pairing_state != BTM_PAIR_STATE_KEY_ENTRY) { return; + } - if (passkey > BTM_MAX_PASSKEY_VAL) res = BTM_ILLEGAL_VALUE; + if (passkey > BTM_MAX_PASSKEY_VAL) { + res = BTM_ILLEGAL_VALUE; + } btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_WAIT_AUTH_COMPLETE); @@ -1334,14 +1295,15 @@ void BTM_ReadLocalOobData(void) { * r - simple pairing Randomizer C. * ******************************************************************************/ -void BTM_RemoteOobDataReply(tBTM_STATUS res, const RawAddress& bd_addr, - const Octet16& c, const Octet16& r) { - log::verbose("State: {} res: {}", - tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state), +void BTM_RemoteOobDataReply(tBTM_STATUS res, const RawAddress& bd_addr, const Octet16& c, + const Octet16& r) { + log::verbose("State: {} res: {}", tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state), res); /* If timeout already expired or has been canceled, ignore the reply */ - if (btm_sec_cb.pairing_state != BTM_PAIR_STATE_WAIT_LOCAL_OOB_RSP) return; + if (btm_sec_cb.pairing_state != BTM_PAIR_STATE_WAIT_LOCAL_OOB_RSP) { + return; + } btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_WAIT_AUTH_COMPLETE); @@ -1378,7 +1340,7 @@ bool BTM_PeerSupportsSecureConnections(const RawAddress& bd_addr) { return false; } - return (p_dev_rec->SupportsSecureConnections()); + return p_dev_rec->SupportsSecureConnections(); } /******************************************************************************* @@ -1437,8 +1399,7 @@ uint8_t BTM_GetSecurityMode() { return btm_sec_cb.security_mode; } * Returns bool * ******************************************************************************/ -static bool btm_sec_is_upgrade_possible(tBTM_SEC_DEV_REC* p_dev_rec, - bool is_originator) { +static bool btm_sec_is_upgrade_possible(tBTM_SEC_DEV_REC* p_dev_rec, bool is_originator) { uint16_t mtm_check = is_originator ? BTM_SEC_OUT_MITM : BTM_SEC_IN_MITM; bool is_possible = true; @@ -1449,15 +1410,12 @@ static bool btm_sec_is_upgrade_possible(tBTM_SEC_DEV_REC* p_dev_rec, ** Is a link key upgrade even possible? */ if ((p_dev_rec->sec_rec.security_required & mtm_check) /* needs MITM */ - && - ((p_dev_rec->sec_rec.link_key_type == BTM_LKEY_TYPE_UNAUTH_COMB) || - (p_dev_rec->sec_rec.link_key_type == BTM_LKEY_TYPE_UNAUTH_COMB_P_256)) + && ((p_dev_rec->sec_rec.link_key_type == BTM_LKEY_TYPE_UNAUTH_COMB) || + (p_dev_rec->sec_rec.link_key_type == BTM_LKEY_TYPE_UNAUTH_COMB_P_256)) /* has unauthenticated link key */ - && (p_dev_rec->sec_rec.rmt_io_caps < - BTM_IO_CAP_MAX) /* a valid peer IO cap */ - && (btm_sec_io_map[p_dev_rec->sec_rec.rmt_io_caps] - [btm_sec_cb.devcb.loc_io_caps])) + && (p_dev_rec->sec_rec.rmt_io_caps < BTM_IO_CAP_MAX) /* a valid peer IO cap */ + && (btm_sec_io_map[p_dev_rec->sec_rec.rmt_io_caps][btm_sec_cb.devcb.loc_io_caps])) /* authenticated link key is possible */ { @@ -1468,8 +1426,7 @@ static bool btm_sec_is_upgrade_possible(tBTM_SEC_DEV_REC* p_dev_rec, is_possible = true; } } - log::verbose("is_possible: {} sec_flags: 0x{:x}", is_possible, - p_dev_rec->sec_rec.sec_flags); + log::verbose("is_possible: {} sec_flags: 0x{:x}", is_possible, p_dev_rec->sec_rec.sec_flags); return is_possible; } @@ -1483,34 +1440,34 @@ static bool btm_sec_is_upgrade_possible(tBTM_SEC_DEV_REC* p_dev_rec, * Returns void * ******************************************************************************/ -static void btm_sec_check_upgrade(tBTM_SEC_DEV_REC* p_dev_rec, - bool is_originator) { +static void btm_sec_check_upgrade(tBTM_SEC_DEV_REC* p_dev_rec, bool is_originator) { log::verbose("verify whether the link key should be upgraded"); /* Only check if link key already exists */ - if (!(p_dev_rec->sec_rec.sec_flags & BTM_SEC_LINK_KEY_KNOWN)) return; + if (!(p_dev_rec->sec_rec.sec_flags & BTM_SEC_LINK_KEY_KNOWN)) { + return; + } if (btm_sec_is_upgrade_possible(p_dev_rec, is_originator)) { - log::verbose("need upgrade!! sec_flags:0x{:x}", - p_dev_rec->sec_rec.sec_flags); + log::verbose("need upgrade!! sec_flags:0x{:x}", p_dev_rec->sec_rec.sec_flags); /* if the application confirms the upgrade, set the upgrade bit */ p_dev_rec->sm4 |= BTM_SM4_UPGRADE; /* Clear the link key known to go through authentication/pairing again */ - p_dev_rec->sec_rec.sec_flags &= - ~(BTM_SEC_LINK_KEY_KNOWN | BTM_SEC_LINK_KEY_AUTHED); + p_dev_rec->sec_rec.sec_flags &= ~(BTM_SEC_LINK_KEY_KNOWN | BTM_SEC_LINK_KEY_AUTHED); p_dev_rec->sec_rec.sec_flags &= ~BTM_SEC_AUTHENTICATED; log::verbose("sec_flags:0x{:x}", p_dev_rec->sec_rec.sec_flags); } } -tBTM_STATUS btm_sec_l2cap_access_req_by_requirement( - const RawAddress& bd_addr, uint16_t security_required, bool is_originator, - tBTM_SEC_CALLBACK* p_callback, void* p_ref_data) { +tBTM_STATUS btm_sec_l2cap_access_req_by_requirement(const RawAddress& bd_addr, + uint16_t security_required, bool is_originator, + tBTM_SEC_CALLBACK* p_callback, + void* p_ref_data) { log::debug( - "Checking l2cap access requirements peer:{} security:0x{:x} " - "is_initiator:{}", - bd_addr, security_required, is_originator); + "Checking l2cap access requirements peer:{} security:0x{:x} " + "is_initiator:{}", + bd_addr, security_required, is_originator); tBTM_STATUS rc = BTM_SUCCESS; bool chk_acp_auth_done = false; @@ -1524,60 +1481,53 @@ tBTM_STATUS btm_sec_l2cap_access_req_by_requirement( get_btm_client_interface().peer.BTM_GetHCIConnHandle(bd_addr, BT_TRANSPORT_BR_EDR); if ((!is_originator) && (security_required & BTM_SEC_MODE4_LEVEL4)) { - bool local_supports_sc = - bluetooth::shim::GetController()->SupportsSecureConnections(); + bool local_supports_sc = bluetooth::shim::GetController()->SupportsSecureConnections(); /* acceptor receives L2CAP Channel Connect Request for Secure Connections * Only service */ if (!local_supports_sc || !p_dev_rec->SupportsSecureConnections()) { log::warn( - "Policy requires mode 4 level 4, but local_support_for_sc={}, " - "rmt_support_for_sc={}, failing connection", - local_supports_sc, p_dev_rec->SupportsSecureConnections()); + "Policy requires mode 4 level 4, but local_support_for_sc={}, " + "rmt_support_for_sc={}, failing connection", + local_supports_sc, p_dev_rec->SupportsSecureConnections()); if (p_callback) { - (*p_callback)(bd_addr, transport, (void*)p_ref_data, - BTM_MODE4_LEVEL4_NOT_SUPPORTED); + (*p_callback)(bd_addr, transport, (void*)p_ref_data, BTM_MODE4_LEVEL4_NOT_SUPPORTED); } - return (BTM_MODE4_LEVEL4_NOT_SUPPORTED); + return BTM_MODE4_LEVEL4_NOT_SUPPORTED; } } /* there are some devices (moto KRZR) which connects to several services at * the same time */ /* we will process one after another */ - if ((p_dev_rec->sec_rec.p_callback) || - (btm_sec_cb.pairing_state != BTM_PAIR_STATE_IDLE)) { + if ((p_dev_rec->sec_rec.p_callback) || (btm_sec_cb.pairing_state != BTM_PAIR_STATE_IDLE)) { log::debug("security_flags:x{:x}, sec_flags:x{:x}", security_required, p_dev_rec->sec_rec.sec_flags); rc = BTM_CMD_STARTED; - if ((btm_sec_cb.security_mode == BTM_SEC_MODE_SERVICE) || - (BTM_SM4_KNOWN == p_dev_rec->sm4) || + if ((btm_sec_cb.security_mode == BTM_SEC_MODE_SERVICE) || (BTM_SM4_KNOWN == p_dev_rec->sm4) || (BTM_SEC_IS_SM4(p_dev_rec->sm4) && (!btm_sec_is_upgrade_possible(p_dev_rec, is_originator)))) { /* legacy mode - local is legacy or local is lisbon/peer is legacy * or SM4 with no possibility of link key upgrade */ if (is_originator) { if (((security_required & BTM_SEC_OUT_FLAGS) == 0) || - ((((security_required & BTM_SEC_OUT_FLAGS) == - BTM_SEC_OUT_AUTHENTICATE) && - btm_dev_authenticated(p_dev_rec))) || - ((((security_required & BTM_SEC_OUT_FLAGS) == - (BTM_SEC_OUT_AUTHENTICATE | BTM_SEC_OUT_ENCRYPT)) && - btm_dev_encrypted(p_dev_rec)))) { + (((security_required & BTM_SEC_OUT_FLAGS) == BTM_SEC_OUT_AUTHENTICATE) && + btm_dev_authenticated(p_dev_rec)) || + (((security_required & BTM_SEC_OUT_FLAGS) == + (BTM_SEC_OUT_AUTHENTICATE | BTM_SEC_OUT_ENCRYPT)) && + btm_dev_encrypted(p_dev_rec))) { rc = BTM_SUCCESS; } } else { if (((security_required & BTM_SEC_IN_FLAGS) == 0) || - (((security_required & BTM_SEC_IN_FLAGS) == - BTM_SEC_IN_AUTHENTICATE) && + (((security_required & BTM_SEC_IN_FLAGS) == BTM_SEC_IN_AUTHENTICATE) && btm_dev_authenticated(p_dev_rec)) || (((security_required & BTM_SEC_IN_FLAGS) == (BTM_SEC_IN_AUTHENTICATE | BTM_SEC_IN_ENCRYPT)) && btm_dev_encrypted(p_dev_rec))) { // Check for 16 digits (or MITM) if (((security_required & BTM_SEC_IN_MIN_16_DIGIT_PIN) == 0) || - (((security_required & BTM_SEC_IN_MIN_16_DIGIT_PIN) == - BTM_SEC_IN_MIN_16_DIGIT_PIN) && + (((security_required & BTM_SEC_IN_MIN_16_DIGIT_PIN) == BTM_SEC_IN_MIN_16_DIGIT_PIN) && btm_dev_16_digit_authenticated(p_dev_rec))) { rc = BTM_SUCCESS; } @@ -1592,27 +1542,27 @@ tBTM_STATUS btm_sec_l2cap_access_req_by_requirement( if (rc == BTM_SUCCESS) { if (access_secure_service_from_temp_bond(p_dev_rec, is_originator, security_required)) { log::error( - "Trying to access a secure service from a temp bonding, " - "rejecting"); + "Trying to access a secure service from a temp bonding, " + "rejecting"); rc = BTM_FAILED_ON_SECURITY; } - if (p_callback) + if (p_callback) { (*p_callback)(bd_addr, transport, (void*)p_ref_data, rc); + } return rc; } } btm_sec_cb.sec_req_pending = true; - return (BTM_CMD_STARTED); + return BTM_CMD_STARTED; } /* Save the security requirements in case a pairing is needed */ p_dev_rec->sec_rec.required_security_flags_for_pairing = security_required; /* Modify security_required in btm_sec_l2cap_access_req for Lisbon */ - if (btm_sec_cb.security_mode == BTM_SEC_MODE_SP || - btm_sec_cb.security_mode == BTM_SEC_MODE_SC) { + if (btm_sec_cb.security_mode == BTM_SEC_MODE_SP || btm_sec_cb.security_mode == BTM_SEC_MODE_SC) { if (BTM_SEC_IS_SM4(p_dev_rec->sm4)) { if (is_originator) { /* SM4 to SM4 -> always encrypt */ @@ -1627,19 +1577,16 @@ tBTM_STATUS btm_sec_l2cap_access_req_by_requirement( } } else if (!(BTM_SM4_KNOWN & p_dev_rec->sm4)) { /* the remote features are not known yet */ - log::debug( - "Remote features have not yet been received sec_flags:0x{:02x} {}", - p_dev_rec->sec_rec.sec_flags, - (is_originator) ? "initiator" : "acceptor"); + log::debug("Remote features have not yet been received sec_flags:0x{:02x} {}", + p_dev_rec->sec_rec.sec_flags, (is_originator) ? "initiator" : "acceptor"); p_dev_rec->sm4 |= BTM_SM4_REQ_PEND; - return (BTM_CMD_STARTED); + return BTM_CMD_STARTED; } } - log::verbose("sm4:0x{:x}, sec_flags:0x{:x}, security_required:0x{:x} chk:{}", - p_dev_rec->sm4, p_dev_rec->sec_rec.sec_flags, security_required, - chk_acp_auth_done); + log::verbose("sm4:0x{:x}, sec_flags:0x{:x}, security_required:0x{:x} chk:{}", p_dev_rec->sm4, + p_dev_rec->sec_rec.sec_flags, security_required, chk_acp_auth_done); p_dev_rec->sec_rec.security_required = security_required; p_dev_rec->sec_rec.p_ref_data = p_ref_data; @@ -1647,10 +1594,10 @@ tBTM_STATUS btm_sec_l2cap_access_req_by_requirement( if (chk_acp_auth_done) { log::verbose( - "(SM4 to SM4) btm_sec_l2cap_access_req rspd. authenticated: x{:x}, " - "enc: x{:x}", - p_dev_rec->sec_rec.sec_flags & BTM_SEC_AUTHENTICATED, - p_dev_rec->sec_rec.sec_flags & BTM_SEC_ENCRYPTED); + "(SM4 to SM4) btm_sec_l2cap_access_req rspd. authenticated: x{:x}, " + "enc: x{:x}", + p_dev_rec->sec_rec.sec_flags & BTM_SEC_AUTHENTICATED, + p_dev_rec->sec_rec.sec_flags & BTM_SEC_ENCRYPTED); /* SM4, but we do not know for sure which level of security we need. * as long as we have a link key, it's OK */ if ((0 == (p_dev_rec->sec_rec.sec_flags & BTM_SEC_AUTHENTICATED)) || @@ -1661,8 +1608,7 @@ tBTM_STATUS btm_sec_l2cap_access_req_by_requirement( sequence because of data path issues. Delay this disconnect a little bit */ - log::info( - "peer should have initiated security process by now (SM4 to SM4)"); + log::info("peer should have initiated security process by now (SM4 to SM4)"); p_dev_rec->sec_rec.p_callback = p_callback; p_dev_rec->sec_rec.sec_state = tSECURITY_STATE::DELAY_FOR_ENC; (*p_callback)(bd_addr, transport, p_ref_data, rc); @@ -1682,8 +1628,7 @@ tBTM_STATUS btm_sec_l2cap_access_req_by_requirement( p_dev_rec->sm4 |= BTM_SM4_UPGRADE; } p_dev_rec->sec_rec.sec_flags &= - ~(BTM_SEC_LINK_KEY_KNOWN | BTM_SEC_LINK_KEY_AUTHED | - BTM_SEC_AUTHENTICATED); + ~(BTM_SEC_LINK_KEY_KNOWN | BTM_SEC_LINK_KEY_AUTHED | BTM_SEC_AUTHENTICATED); log::verbose("sec_flags:0x{:x}", p_dev_rec->sec_rec.sec_flags); } else { /* If we already have a link key to the connected peer, is it secure @@ -1694,13 +1639,13 @@ tBTM_STATUS btm_sec_l2cap_access_req_by_requirement( rc = btm_sec_execute_procedure(p_dev_rec); if (rc != BTM_CMD_STARTED) { - log::verbose("p_dev_rec={}, clearing callback. old p_callback={}", - fmt::ptr(p_dev_rec), fmt::ptr(p_dev_rec->sec_rec.p_callback)); + log::verbose("p_dev_rec={}, clearing callback. old p_callback={}", fmt::ptr(p_dev_rec), + fmt::ptr(p_dev_rec->sec_rec.p_callback)); p_dev_rec->sec_rec.p_callback = NULL; (*p_callback)(bd_addr, transport, p_dev_rec->sec_rec.p_ref_data, rc); } - return (rc); + return rc; } /******************************************************************************* @@ -1721,43 +1666,39 @@ tBTM_STATUS btm_sec_l2cap_access_req_by_requirement( * Returns tBTM_STATUS * ******************************************************************************/ -tBTM_STATUS btm_sec_l2cap_access_req(const RawAddress& bd_addr, uint16_t psm, - bool is_originator, - tBTM_SEC_CALLBACK* p_callback, - void* p_ref_data) { +tBTM_STATUS btm_sec_l2cap_access_req(const RawAddress& bd_addr, uint16_t psm, bool is_originator, + tBTM_SEC_CALLBACK* p_callback, void* p_ref_data) { // should check PSM range in LE connection oriented L2CAP connection constexpr tBT_TRANSPORT transport = BT_TRANSPORT_BR_EDR; log::debug("is_originator:{}, psm=0x{:04x}", is_originator, psm); // Find the service record for the PSM - tBTM_SEC_SERV_REC* p_serv_rec = - btm_sec_cb.find_first_serv_rec(is_originator, psm); + tBTM_SEC_SERV_REC* p_serv_rec = btm_sec_cb.find_first_serv_rec(is_originator, psm); // If there is no application registered with this PSM do not allow connection if (!p_serv_rec) { log::warn("PSM: 0x{:04x} no application registered", psm); (*p_callback)(bd_addr, transport, p_ref_data, BTM_MODE_UNSUPPORTED); - return (BTM_MODE_UNSUPPORTED); + return BTM_MODE_UNSUPPORTED; } /* Services level0 by default have no security */ if (psm == BT_PSM_SDP) { log::debug("No security required for SDP"); (*p_callback)(bd_addr, transport, p_ref_data, BTM_SUCCESS_NO_SECURITY); - return (BTM_SUCCESS); + return BTM_SUCCESS; } uint16_t security_required; if (btm_sec_cb.security_mode == BTM_SEC_MODE_SC) { - security_required = btm_sec_set_serv_level4_flags( - p_serv_rec->security_flags, is_originator); + security_required = btm_sec_set_serv_level4_flags(p_serv_rec->security_flags, is_originator); } else { security_required = p_serv_rec->security_flags; } - return btm_sec_l2cap_access_req_by_requirement( - bd_addr, security_required, is_originator, p_callback, p_ref_data); + return btm_sec_l2cap_access_req_by_requirement(bd_addr, security_required, is_originator, + p_callback, p_ref_data); } /******************************************************************************* @@ -1783,10 +1724,8 @@ tBTM_STATUS btm_sec_l2cap_access_req(const RawAddress& bd_addr, uint16_t psm, * Returns BTM_CMD_STARTED * ******************************************************************************/ -tBTM_STATUS btm_sec_mx_access_request(const RawAddress& bd_addr, - bool is_originator, - uint16_t security_required, - tBTM_SEC_CALLBACK* p_callback, +tBTM_STATUS btm_sec_mx_access_request(const RawAddress& bd_addr, bool is_originator, + uint16_t security_required, tBTM_SEC_CALLBACK* p_callback, void* p_ref_data) { tBTM_SEC_DEV_REC* p_dev_rec; tBTM_STATUS rc; @@ -1800,41 +1739,36 @@ tBTM_STATUS btm_sec_mx_access_request(const RawAddress& bd_addr, /* there are some devices (moto phone) which connects to several services at * the same time */ /* we will process one after another */ - if ((p_dev_rec->sec_rec.p_callback) || - (btm_sec_cb.pairing_state != BTM_PAIR_STATE_IDLE)) { + if ((p_dev_rec->sec_rec.p_callback) || (btm_sec_cb.pairing_state != BTM_PAIR_STATE_IDLE)) { log::debug("Pairing in progress pairing_state:{}", tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state)); rc = BTM_CMD_STARTED; - if ((btm_sec_cb.security_mode == BTM_SEC_MODE_SERVICE) || - (BTM_SM4_KNOWN == p_dev_rec->sm4) || + if ((btm_sec_cb.security_mode == BTM_SEC_MODE_SERVICE) || (BTM_SM4_KNOWN == p_dev_rec->sm4) || (BTM_SEC_IS_SM4(p_dev_rec->sm4) && (!btm_sec_is_upgrade_possible(p_dev_rec, is_originator)))) { /* legacy mode - local is legacy or local is lisbon/peer is legacy * or SM4 with no possibility of link key upgrade */ if (is_originator) { if (((security_required & BTM_SEC_OUT_FLAGS) == 0) || - ((((security_required & BTM_SEC_OUT_FLAGS) == - BTM_SEC_OUT_AUTHENTICATE) && - btm_dev_authenticated(p_dev_rec))) || - ((((security_required & BTM_SEC_OUT_FLAGS) == - (BTM_SEC_OUT_AUTHENTICATE | BTM_SEC_OUT_ENCRYPT)) && - btm_dev_encrypted(p_dev_rec)))) { + (((security_required & BTM_SEC_OUT_FLAGS) == BTM_SEC_OUT_AUTHENTICATE) && + btm_dev_authenticated(p_dev_rec)) || + (((security_required & BTM_SEC_OUT_FLAGS) == + (BTM_SEC_OUT_AUTHENTICATE | BTM_SEC_OUT_ENCRYPT)) && + btm_dev_encrypted(p_dev_rec))) { rc = BTM_SUCCESS; } } else { if (((security_required & BTM_SEC_IN_FLAGS) == 0) || - ((((security_required & BTM_SEC_IN_FLAGS) == - BTM_SEC_IN_AUTHENTICATE) && - btm_dev_authenticated(p_dev_rec))) || - ((((security_required & BTM_SEC_IN_FLAGS) == - (BTM_SEC_IN_AUTHENTICATE | BTM_SEC_IN_ENCRYPT)) && - btm_dev_encrypted(p_dev_rec)))) { + (((security_required & BTM_SEC_IN_FLAGS) == BTM_SEC_IN_AUTHENTICATE) && + btm_dev_authenticated(p_dev_rec)) || + (((security_required & BTM_SEC_IN_FLAGS) == + (BTM_SEC_IN_AUTHENTICATE | BTM_SEC_IN_ENCRYPT)) && + btm_dev_encrypted(p_dev_rec))) { // Check for 16 digits (or MITM) if (((security_required & BTM_SEC_IN_MIN_16_DIGIT_PIN) == 0) || - (((security_required & BTM_SEC_IN_MIN_16_DIGIT_PIN) == - BTM_SEC_IN_MIN_16_DIGIT_PIN) && + (((security_required & BTM_SEC_IN_MIN_16_DIGIT_PIN) == BTM_SEC_IN_MIN_16_DIGIT_PIN) && btm_dev_16_digit_authenticated(p_dev_rec))) { rc = BTM_SUCCESS; } @@ -1852,15 +1786,14 @@ tBTM_STATUS btm_sec_mx_access_request(const RawAddress& bd_addr, rc = BTM_CMD_STARTED; } if (rc == BTM_CMD_STARTED) { - btm_sec_queue_mx_request(bd_addr, BT_PSM_RFCOMM, is_originator, - security_required, p_callback, p_ref_data); + btm_sec_queue_mx_request(bd_addr, BT_PSM_RFCOMM, is_originator, security_required, p_callback, + p_ref_data); } else /* rc == BTM_SUCCESS */ { - if (access_secure_service_from_temp_bond(p_dev_rec, - is_originator, security_required)) { + if (access_secure_service_from_temp_bond(p_dev_rec, is_originator, security_required)) { log::error( - "Trying to access a secure rfcomm service from a temp bonding, " - "rejecting"); + "Trying to access a secure rfcomm service from a temp bonding, " + "rejecting"); rc = BTM_FAILED_ON_SECURITY; } if (p_callback) { @@ -1873,20 +1806,19 @@ tBTM_STATUS btm_sec_mx_access_request(const RawAddress& bd_addr, if ((!is_originator) && ((security_required & BTM_SEC_MODE4_LEVEL4) || (btm_sec_cb.security_mode == BTM_SEC_MODE_SC))) { - bool local_supports_sc = - bluetooth::shim::GetController()->SupportsSecureConnections(); + bool local_supports_sc = bluetooth::shim::GetController()->SupportsSecureConnections(); /* acceptor receives service connection establishment Request for */ /* Secure Connections Only service */ if (!(local_supports_sc) || !(p_dev_rec->SupportsSecureConnections())) { log::debug( - "Secure Connection only mode unsupported local_SC_support:{} " - "remote_SC_support:{}", - local_supports_sc, p_dev_rec->SupportsSecureConnections()); - if (p_callback) - (*p_callback)(bd_addr, transport, (void*)p_ref_data, - BTM_MODE4_LEVEL4_NOT_SUPPORTED); - - return (BTM_MODE4_LEVEL4_NOT_SUPPORTED); + "Secure Connection only mode unsupported local_SC_support:{} " + "remote_SC_support:{}", + local_supports_sc, p_dev_rec->SupportsSecureConnections()); + if (p_callback) { + (*p_callback)(bd_addr, transport, (void*)p_ref_data, BTM_MODE4_LEVEL4_NOT_SUPPORTED); + } + + return BTM_MODE4_LEVEL4_NOT_SUPPORTED; } } @@ -1900,8 +1832,7 @@ tBTM_STATUS btm_sec_mx_access_request(const RawAddress& bd_addr, p_dev_rec->sec_rec.required_security_flags_for_pairing = security_required; p_dev_rec->sec_rec.security_required = security_required; - if (btm_sec_cb.security_mode == BTM_SEC_MODE_SP || - btm_sec_cb.security_mode == BTM_SEC_MODE_SC) { + if (btm_sec_cb.security_mode == BTM_SEC_MODE_SP || btm_sec_cb.security_mode == BTM_SEC_MODE_SC) { if (BTM_SEC_IS_SM4(p_dev_rec->sm4)) { if ((p_dev_rec->sec_rec.security_required & BTM_SEC_MODE4_LEVEL4) && (p_dev_rec->sec_rec.link_key_type != BTM_LKEY_TYPE_AUTH_COMB_P_256)) { @@ -1912,8 +1843,7 @@ tBTM_STATUS btm_sec_mx_access_request(const RawAddress& bd_addr, } p_dev_rec->sec_rec.sec_flags &= - ~(BTM_SEC_LINK_KEY_KNOWN | BTM_SEC_LINK_KEY_AUTHED | - BTM_SEC_AUTHENTICATED); + ~(BTM_SEC_LINK_KEY_KNOWN | BTM_SEC_LINK_KEY_AUTHED | BTM_SEC_AUTHENTICATED); log::verbose("sec_flags:0x{:x}", p_dev_rec->sec_rec.sec_flags); } else { log::debug("Already have link key; checking if link key is sufficient"); @@ -1927,8 +1857,8 @@ tBTM_STATUS btm_sec_mx_access_request(const RawAddress& bd_addr, p_dev_rec->sec_rec.p_ref_data = p_ref_data; rc = btm_sec_execute_procedure(p_dev_rec); - log::debug("Started security procedure peer:{} btm_status:{}", - p_dev_rec->RemoteAddress(), btm_status_text(rc)); + log::debug("Started security procedure peer:{} btm_status:{}", p_dev_rec->RemoteAddress(), + btm_status_text(rc)); if (rc != BTM_CMD_STARTED) { if (p_callback) { p_dev_rec->sec_rec.p_callback = NULL; @@ -1955,8 +1885,7 @@ void btm_sec_conn_req(const RawAddress& bda, const DEV_CLASS dc) { if ((btm_sec_cb.pairing_state != BTM_PAIR_STATE_IDLE) && (btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD) && (btm_sec_cb.pairing_bda == bda)) { - log::verbose( - "Security Manager: reject connect request from bonding device"); + log::verbose("Security Manager: reject connect request from bonding device"); /* incoming connection from bonding device is rejected */ btm_sec_cb.pairing_flags |= BTM_PAIR_FLAGS_REJECTED_CONNECT; @@ -2001,12 +1930,15 @@ static void btm_sec_bond_cancel_complete(void) { * this function also needs to do proper clean up. */ p_dev_rec = btm_find_dev(btm_sec_cb.pairing_bda); - if (p_dev_rec != NULL) p_dev_rec->sec_rec.security_required = BTM_SEC_NONE; + if (p_dev_rec != NULL) { + p_dev_rec->sec_rec.security_required = BTM_SEC_NONE; + } btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_IDLE); /* Notify application that the cancel succeeded */ - if (btm_sec_cb.api.p_bond_cancel_cmpl_callback) + if (btm_sec_cb.api.p_bond_cancel_cmpl_callback) { btm_sec_cb.api.p_bond_cancel_cmpl_callback(BTM_SUCCESS); + } } } @@ -2023,15 +1955,13 @@ static void btm_sec_bond_cancel_complete(void) { ******************************************************************************/ void btm_create_conn_cancel_complete(uint8_t status, const RawAddress bd_addr) { log::verbose("btm_create_conn_cancel_complete(): in State: {} status:{}", - tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state), - status); + tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state), status); log_link_layer_connection_event( - &bd_addr, bluetooth::common::kUnknownConnectionHandle, - android::bluetooth::DIRECTION_OUTGOING, android::bluetooth::LINK_TYPE_ACL, - android::bluetooth::hci::CMD_CREATE_CONNECTION_CANCEL, - android::bluetooth::hci::EVT_COMMAND_COMPLETE, - android::bluetooth::hci::BLE_EVT_UNKNOWN, status, - android::bluetooth::hci::STATUS_UNKNOWN); + &bd_addr, bluetooth::common::kUnknownConnectionHandle, + android::bluetooth::DIRECTION_OUTGOING, android::bluetooth::LINK_TYPE_ACL, + android::bluetooth::hci::CMD_CREATE_CONNECTION_CANCEL, + android::bluetooth::hci::EVT_COMMAND_COMPLETE, android::bluetooth::hci::BLE_EVT_UNKNOWN, + status, android::bluetooth::hci::STATUS_UNKNOWN); /* if the create conn cancel cmd was issued by the bond cancel, ** the application needs to be notified that bond cancel succeeded @@ -2044,8 +1974,9 @@ void btm_create_conn_cancel_complete(uint8_t status, const RawAddress bd_addr) { case HCI_ERR_NO_CONNECTION: default: /* Notify application of the error */ - if (btm_sec_cb.api.p_bond_cancel_cmpl_callback) + if (btm_sec_cb.api.p_bond_cancel_cmpl_callback) { btm_sec_cb.api.p_bond_cancel_cmpl_callback(BTM_ERR_PROCESSING); + } break; } } @@ -2081,12 +2012,11 @@ void btm_sec_check_pending_reqs(void) { if (p_e->psm != 0) { log::verbose("PSM:0x{:04x} Is_Orig:{}", p_e->psm, p_e->is_orig); - btm_sec_mx_access_request(p_e->bd_addr, p_e->is_orig, - p_e->rfcomm_security_requirement, + btm_sec_mx_access_request(p_e->bd_addr, p_e->is_orig, p_e->rfcomm_security_requirement, p_e->p_callback, p_e->p_ref_data); } else { - BTM_SetEncryption(p_e->bd_addr, p_e->transport, p_e->p_callback, - p_e->p_ref_data, p_e->sec_act); + BTM_SetEncryption(p_e->bd_addr, p_e->transport, p_e->p_callback, p_e->p_ref_data, + p_e->sec_act); } } @@ -2112,10 +2042,10 @@ void btm_sec_dev_reset(void) { /* set the default IO capabilities */ btm_sec_cb.devcb.loc_io_caps = BTM_IO_CAP_IO; /* add mx service to use no security */ - BTM_SetSecurityLevel(false, "RFC_MUX", BTM_SEC_SERVICE_RFC_MUX, - BTM_SEC_NONE, BT_PSM_RFCOMM, BTM_SEC_PROTO_RFCOMM, 0); - BTM_SetSecurityLevel(true, "RFC_MUX", BTM_SEC_SERVICE_RFC_MUX, BTM_SEC_NONE, - BT_PSM_RFCOMM, BTM_SEC_PROTO_RFCOMM, 0); + BTM_SetSecurityLevel(false, "RFC_MUX", BTM_SEC_SERVICE_RFC_MUX, BTM_SEC_NONE, BT_PSM_RFCOMM, + BTM_SEC_PROTO_RFCOMM, 0); + BTM_SetSecurityLevel(true, "RFC_MUX", BTM_SEC_SERVICE_RFC_MUX, BTM_SEC_NONE, BT_PSM_RFCOMM, + BTM_SEC_PROTO_RFCOMM, 0); log::verbose("btm_sec_dev_reset sec mode: {}", btm_sec_cb.security_mode); } @@ -2134,7 +2064,9 @@ void btm_sec_dev_reset(void) { void btm_sec_abort_access_req(const RawAddress& bd_addr) { tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr); - if (!p_dev_rec) return; + if (!p_dev_rec) { + return; + } if ((p_dev_rec->sec_rec.sec_state != tSECURITY_STATE::AUTHORIZING) && (p_dev_rec->sec_rec.sec_state != tSECURITY_STATE::AUTHENTICATING)) { @@ -2143,8 +2075,8 @@ void btm_sec_abort_access_req(const RawAddress& bd_addr) { p_dev_rec->sec_rec.sec_state = tSECURITY_STATE::IDLE; - log::verbose("clearing callback. p_dev_rec={}, p_callback={}", - fmt::ptr(p_dev_rec), fmt::ptr(p_dev_rec->sec_rec.p_callback)); + log::verbose("clearing callback. p_dev_rec={}, p_callback={}", fmt::ptr(p_dev_rec), + fmt::ptr(p_dev_rec->sec_rec.p_callback)); p_dev_rec->sec_rec.p_callback = NULL; } @@ -2180,12 +2112,11 @@ static tBTM_STATUS btm_sec_dd_create_conn(tBTM_SEC_DEV_REC* p_dev_rec) { btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_WAIT_PIN_REQ); - return (BTM_CMD_STARTED); + return BTM_CMD_STARTED; } static void call_registered_rmt_name_callbacks(const RawAddress* p_bd_addr, - const DEV_CLASS& dev_class, - uint8_t* p_bd_name, + const DEV_CLASS& dev_class, uint8_t* p_bd_name, tHCI_STATUS status) { int i; @@ -2220,53 +2151,49 @@ static void call_registered_rmt_name_callbacks(const RawAddress* p_bd_addr, * Returns void * ******************************************************************************/ -void btm_sec_rmt_name_request_complete(const RawAddress* p_bd_addr, - const uint8_t* p_bd_name, +void btm_sec_rmt_name_request_complete(const RawAddress* p_bd_addr, const uint8_t* p_bd_name, tHCI_STATUS status) { log::info("btm_sec_rmt_name_request_complete for {}", p_bd_addr ? ADDRESS_TO_LOGGABLE_CSTR(*p_bd_addr) : "null"); - if ((!p_bd_addr && !BTM_IsAclConnectionUp(btm_sec_cb.connecting_bda, - BT_TRANSPORT_BR_EDR)) || + if ((!p_bd_addr && !BTM_IsAclConnectionUp(btm_sec_cb.connecting_bda, BT_TRANSPORT_BR_EDR)) || (p_bd_addr && !BTM_IsAclConnectionUp(*p_bd_addr, BT_TRANSPORT_BR_EDR))) { - log::warn( - "Remote read request complete with no underlying link connection"); + log::warn("Remote read request complete with no underlying link connection"); } /* If remote name request failed, p_bd_addr is null and we need to search */ /* based on state assuming that we are doing 1 at a time */ tBTM_SEC_DEV_REC* p_dev_rec = nullptr; - if (p_bd_addr) + if (p_bd_addr) { p_dev_rec = btm_find_dev(*p_bd_addr); - else { + } else { log::info( - "Remote read request complete with no address so searching device " - "database"); + "Remote read request complete with no address so searching device " + "database"); p_dev_rec = btm_sec_find_dev_by_sec_state(tSECURITY_STATE::GETTING_NAME); if (p_dev_rec) { p_bd_addr = &p_dev_rec->bd_addr; } } - if (!p_bd_name) p_bd_name = (const uint8_t*)kBtmBdNameEmpty; + if (!p_bd_name) { + p_bd_name = (const uint8_t*)kBtmBdNameEmpty; + } - BTM_LogHistory(kBtmLogTag, (p_bd_addr) ? *p_bd_addr : RawAddress::kEmpty, - "RNR complete", - base::StringPrintf("status:%s name:%s", - hci_error_code_text(status).c_str(), + BTM_LogHistory(kBtmLogTag, (p_bd_addr) ? *p_bd_addr : RawAddress::kEmpty, "RNR complete", + base::StringPrintf("status:%s name:%s", hci_error_code_text(status).c_str(), PRIVATE_NAME(p_bd_name))); if (p_dev_rec == nullptr) { log::debug( - "Remote read request complete for unknown device peer:{} " - "pairing_state:{} " - "status:{} name:{}", - (p_bd_addr) ? ADDRESS_TO_LOGGABLE_CSTR(*p_bd_addr) : "null", - tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state), - hci_status_code_text(status), reinterpret_cast(p_bd_name)); - - call_registered_rmt_name_callbacks(p_bd_addr, kDevClassEmpty, nullptr, - status); + "Remote read request complete for unknown device peer:{} " + "pairing_state:{} " + "status:{} name:{}", + (p_bd_addr) ? ADDRESS_TO_LOGGABLE_CSTR(*p_bd_addr) : "null", + tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state), + hci_status_code_text(status), reinterpret_cast(p_bd_name)); + + call_registered_rmt_name_callbacks(p_bd_addr, kDevClassEmpty, nullptr, status); return; } @@ -2275,23 +2202,22 @@ void btm_sec_rmt_name_request_complete(const RawAddress* p_bd_addr, if (status == HCI_SUCCESS) { log::debug( - "Remote read request complete for known device pairing_state:{} " - "name:{} sec_state:{}", - tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state), - reinterpret_cast(p_bd_name), - security_state_text(p_dev_rec->sec_rec.sec_state)); + "Remote read request complete for known device pairing_state:{} " + "name:{} sec_state:{}", + tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state), + reinterpret_cast(p_bd_name), + security_state_text(p_dev_rec->sec_rec.sec_state)); bd_name_copy(p_dev_rec->sec_bd_name, p_bd_name); p_dev_rec->sec_rec.sec_flags |= BTM_SEC_NAME_KNOWN; - log::verbose("setting BTM_SEC_NAME_KNOWN sec_flags:0x{:x}", - p_dev_rec->sec_rec.sec_flags); + log::verbose("setting BTM_SEC_NAME_KNOWN sec_flags:0x{:x}", p_dev_rec->sec_rec.sec_flags); } else { log::warn( - "Remote read request failed for known device pairing_state:{} " - "status:{} name:{} sec_state:{}", - tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state), - hci_status_code_text(status), reinterpret_cast(p_bd_name), - security_state_text(p_dev_rec->sec_rec.sec_state)); + "Remote read request failed for known device pairing_state:{} " + "status:{} name:{} sec_state:{}", + tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state), + hci_status_code_text(status), reinterpret_cast(p_bd_name), + security_state_text(p_dev_rec->sec_rec.sec_state)); /* Notify all clients waiting for name to be resolved even if it failed so * clients can continue */ @@ -2313,18 +2239,17 @@ void btm_sec_rmt_name_request_complete(const RawAddress* p_bd_addr, * ask now */ if ((btm_sec_cb.pairing_state == BTM_PAIR_STATE_WAIT_LOCAL_PIN) && (btm_sec_cb.pairing_bda == bd_addr)) { - log::verbose( - "delayed pin now being requested flags:0x{:x}, (p_pin_callback=0x{})", - btm_sec_cb.pairing_flags, fmt::ptr(btm_sec_cb.api.p_pin_callback)); + log::verbose("delayed pin now being requested flags:0x{:x}, (p_pin_callback=0x{})", + btm_sec_cb.pairing_flags, fmt::ptr(btm_sec_cb.api.p_pin_callback)); if ((btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_PIN_REQD) == 0 && btm_sec_cb.api.p_pin_callback) { log::verbose("calling pin_callback"); btm_sec_cb.pairing_flags |= BTM_PAIR_FLAGS_PIN_REQD; - (*btm_sec_cb.api.p_pin_callback)( - p_dev_rec->bd_addr, p_dev_rec->dev_class, p_dev_rec->sec_bd_name, - (p_dev_rec->sec_rec.required_security_flags_for_pairing & - BTM_SEC_IN_MIN_16_DIGIT_PIN)); + (*btm_sec_cb.api.p_pin_callback)(p_dev_rec->bd_addr, p_dev_rec->dev_class, + p_dev_rec->sec_bd_name, + (p_dev_rec->sec_rec.required_security_flags_for_pairing & + BTM_SEC_IN_MIN_16_DIGIT_PIN)); } /* Set the same state again to force the timer to be restarted */ @@ -2335,8 +2260,7 @@ void btm_sec_rmt_name_request_complete(const RawAddress* p_bd_addr, /* Check if we were delaying bonding because name was not resolved */ if (btm_sec_cb.pairing_state == BTM_PAIR_STATE_GET_REM_NAME) { if (btm_sec_cb.pairing_bda == bd_addr) { - log::verbose("continue bonding sm4: 0x{:04x}, status:0x{:x}", - p_dev_rec->sm4, status); + log::verbose("continue bonding sm4: 0x{:04x}, status:0x{:x}", p_dev_rec->sm4, status); if (btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_WE_CANCEL_DD) { btm_sec_bond_cancel_complete(); return; @@ -2355,13 +2279,13 @@ void btm_sec_rmt_name_request_complete(const RawAddress* p_bd_addr, * set.*/ /* If it is set, there may be a race condition */ log::verbose("IS_SM4_UNKNOWN Flags:0x{:04x}", btm_sec_cb.pairing_flags); - if ((btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_REJECTED_CONNECT) == 0) + if ((btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_REJECTED_CONNECT) == 0) { p_dev_rec->sm4 |= BTM_SM4_KNOWN; + } } - log::verbose("SM4 Value: {:x}, Legacy:{},IS SM4:{}, Unknown:{}", - p_dev_rec->sm4, BTM_SEC_IS_SM4_LEGACY(p_dev_rec->sm4), - BTM_SEC_IS_SM4(p_dev_rec->sm4), + log::verbose("SM4 Value: {:x}, Legacy:{},IS SM4:{}, Unknown:{}", p_dev_rec->sm4, + BTM_SEC_IS_SM4_LEGACY(p_dev_rec->sm4), BTM_SEC_IS_SM4(p_dev_rec->sm4), BTM_SEC_IS_SM4_UNKNOWN(p_dev_rec->sm4)); bool await_connection = true; @@ -2370,14 +2294,12 @@ void btm_sec_rmt_name_request_complete(const RawAddress* p_bd_addr, ** Else prefetch (btm_sec_check_prefetch_pin will do the prefetching if *needed) */ - if ((p_dev_rec->sm4 != BTM_SM4_KNOWN) || - !btm_sec_check_prefetch_pin(p_dev_rec)) { + if ((p_dev_rec->sm4 != BTM_SM4_KNOWN) || !btm_sec_check_prefetch_pin(p_dev_rec)) { /* if we rejected incoming connection request, we have to wait * HCI_Connection_Complete event */ /* before originating */ if (btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_REJECTED_CONNECT) { - log::warn( - "waiting HCI_Connection_Complete after rejecting connection"); + log::warn("waiting HCI_Connection_Complete after rejecting connection"); } /* Both we and the peer are 2.1 - continue to create connection */ else { @@ -2401,8 +2323,7 @@ void btm_sec_rmt_name_request_complete(const RawAddress* p_bd_addr, } else { log::warn("wrong BDA, retry with pairing BDA"); if (get_btm_client_interface().peer.BTM_ReadRemoteDeviceName( - btm_sec_cb.pairing_bda, NULL, BT_TRANSPORT_BR_EDR) != - BTM_CMD_STARTED) { + btm_sec_cb.pairing_bda, NULL, BT_TRANSPORT_BR_EDR) != BTM_CMD_STARTED) { log::error("failed to start remote name request"); NotifyBondingChange(*p_dev_rec, HCI_ERR_MEMORY_FULL); }; @@ -2414,7 +2335,9 @@ void btm_sec_rmt_name_request_complete(const RawAddress* p_bd_addr, */ if (p_dev_rec->sec_rec.link_key_not_sent) { /* If HCI connection complete has not arrived, wait for it */ - if (p_dev_rec->hci_handle == HCI_INVALID_HANDLE) return; + if (p_dev_rec->hci_handle == HCI_INVALID_HANDLE) { + return; + } p_dev_rec->sec_rec.link_key_not_sent = false; btm_send_link_key_notif(p_dev_rec); @@ -2449,7 +2372,9 @@ void btm_sec_rmt_name_request_complete(const RawAddress* p_bd_addr, tBTM_STATUS btm_status = btm_sec_execute_procedure(p_dev_rec); /* If result is pending reply from the user or from the device is pending */ - if (btm_status == BTM_CMD_STARTED) return; + if (btm_status == BTM_CMD_STARTED) { + return; + } /* There is no next procedure or start of procedure failed, notify the waiting * layer */ @@ -2466,25 +2391,23 @@ void btm_sec_rmt_name_request_complete(const RawAddress* p_bd_addr, * Returns void * ******************************************************************************/ -void btm_sec_rmt_host_support_feat_evt(const RawAddress bd_addr, - uint8_t features_0) { +void btm_sec_rmt_host_support_feat_evt(const RawAddress bd_addr, uint8_t features_0) { tBTM_SEC_DEV_REC* p_dev_rec; p_dev_rec = btm_find_or_alloc_dev(bd_addr); log::info("Got btm_sec_rmt_host_support_feat_evt from {}", bd_addr); - log::verbose("btm_sec_rmt_host_support_feat_evt sm4: 0x{:x} p[0]: 0x{:x}", - p_dev_rec->sm4, features_0); + log::verbose("btm_sec_rmt_host_support_feat_evt sm4: 0x{:x} p[0]: 0x{:x}", p_dev_rec->sm4, + features_0); if (BTM_SEC_IS_SM4_UNKNOWN(p_dev_rec->sm4)) { p_dev_rec->sm4 = BTM_SM4_KNOWN; if (HCI_SSP_HOST_SUPPORTED(&features_0)) { p_dev_rec->sm4 = BTM_SM4_TRUE; } - log::verbose( - "btm_sec_rmt_host_support_feat_evt sm4: 0x{:x} features[0]: 0x{:x}", - p_dev_rec->sm4, features_0); + log::verbose("btm_sec_rmt_host_support_feat_evt sm4: 0x{:x} features[0]: 0x{:x}", + p_dev_rec->sm4, features_0); } } @@ -2502,9 +2425,7 @@ void btm_sec_rmt_host_support_feat_evt(const RawAddress bd_addr, void btm_io_capabilities_req(RawAddress p) { if (btm_sec_is_a_bonded_dev(p)) { if (com::android::bluetooth::flags::key_missing_classic_device()) { - log::warn( - "Incoming bond request, but {} is already bonded (notifying user)", - p); + log::warn("Incoming bond request, but {} is already bonded (notifying user)", p); bta_dm_remote_key_missing(p); auto p_dev_rec = btm_find_dev(p); @@ -2521,11 +2442,10 @@ void btm_io_capabilities_req(RawAddress p) { tBTM_SEC_DEV_REC* p_dev_rec = btm_find_or_alloc_dev(p); - if ((btm_sec_cb.security_mode == BTM_SEC_MODE_SC) && - (!p_dev_rec->remote_feature_received)) { + if ((btm_sec_cb.security_mode == BTM_SEC_MODE_SC) && (!p_dev_rec->remote_feature_received)) { log::verbose( - "Device security mode is SC only.To continue need to know remote " - "features."); + "Device security mode is SC only.To continue need to know remote " + "features."); // ACL calls back to btm_sec_set_peer_sec_caps after it gets data p_dev_rec->remote_features_needed = true; @@ -2581,8 +2501,7 @@ void btm_io_capabilities_req(RawAddress p) { /* any other state is unexpected */ default: err_code = HCI_ERR_HOST_BUSY_PAIRING; - log::error("Unexpected Pairing state received {}", - btm_sec_cb.pairing_state); + log::error("Unexpected Pairing state received {}", btm_sec_cb.pairing_state); break; } @@ -2591,14 +2510,13 @@ void btm_io_capabilities_req(RawAddress p) { log::verbose("Pairing is not allowed -> fail pairing."); err_code = HCI_ERR_PAIRING_NOT_ALLOWED; } else if (btm_sec_cb.security_mode == BTM_SEC_MODE_SC) { - bool local_supports_sc = - bluetooth::shim::GetController()->SupportsSecureConnections(); + bool local_supports_sc = bluetooth::shim::GetController()->SupportsSecureConnections(); /* device in Secure Connections Only mode */ if (!(local_supports_sc) || !(p_dev_rec->SupportsSecureConnections())) { log::debug( - "SC only service, local_support_for_sc:{}, remote_support_for_sc:{} " - "-> fail pairing", - local_supports_sc, p_dev_rec->SupportsSecureConnections()); + "SC only service, local_support_for_sc:{}, remote_support_for_sc:{} " + "-> fail pairing", + local_supports_sc, p_dev_rec->SupportsSecureConnections()); err_code = HCI_ERR_PAIRING_NOT_ALLOWED; } } @@ -2614,17 +2532,15 @@ void btm_io_capabilities_req(RawAddress p) { /* local device initiated the pairing non-bonding -> use * required_security_flags_for_pairing */ if (!(btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD) && - (p_dev_rec->sec_rec.required_security_flags_for_pairing & - BTM_SEC_OUT_AUTHENTICATE)) { + (p_dev_rec->sec_rec.required_security_flags_for_pairing & BTM_SEC_OUT_AUTHENTICATE)) { if (btm_sec_cb.security_mode == BTM_SEC_MODE_SC) { /* SC only mode device requires MITM protection */ evt_data.auth_req = BTM_AUTH_SP_YES; } else { evt_data.auth_req = - (p_dev_rec->sec_rec.required_security_flags_for_pairing & - BTM_SEC_OUT_MITM) - ? BTM_AUTH_SP_YES - : BTM_AUTH_SP_NO; + (p_dev_rec->sec_rec.required_security_flags_for_pairing & BTM_SEC_OUT_MITM) + ? BTM_AUTH_SP_YES + : BTM_AUTH_SP_NO; } } } @@ -2648,21 +2564,18 @@ void btm_io_capabilities_req(RawAddress p) { evt_data.auth_req = BTM_AUTH_SPGB_YES; } else if (btm_sec_cb.api.p_sp_callback) { /* the callback function implementation may change the IO capability... */ - (*btm_sec_cb.api.p_sp_callback)(BTM_SP_IO_REQ_EVT, - (tBTM_SP_EVT_DATA*)&evt_data); + (*btm_sec_cb.api.p_sp_callback)(BTM_SP_IO_REQ_EVT, (tBTM_SP_EVT_DATA*)&evt_data); } - if ((btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD)) { - evt_data.auth_req = - (BTM_AUTH_DD_BOND | (evt_data.auth_req & BTM_AUTH_YN_BIT)); + if (btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD) { + evt_data.auth_req = (BTM_AUTH_DD_BOND | (evt_data.auth_req & BTM_AUTH_YN_BIT)); } if (btm_sec_cb.security_mode == BTM_SEC_MODE_SC) { /* At this moment we know that both sides are SC capable, device in */ /* SC only mode requires MITM for any service so let's set MITM bit */ evt_data.auth_req |= BTM_AUTH_YN_BIT; - log::verbose("for device in \"SC only\" mode set auth_req to 0x{:02x}", - evt_data.auth_req); + log::verbose("for device in \"SC only\" mode set auth_req to 0x{:02x}", evt_data.auth_req); } /* if the user does not indicate "reply later" by setting the oob_data to @@ -2673,11 +2586,11 @@ void btm_io_capabilities_req(RawAddress p) { btm_sec_cb.devcb.loc_io_caps = evt_data.io_cap; log::verbose("State: {} IO_CAP:{} oob_data:{} auth_req:{}", - tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state), - evt_data.io_cap, evt_data.oob_data, evt_data.auth_req); + tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state), evt_data.io_cap, + evt_data.oob_data, evt_data.auth_req); - btsnd_hcic_io_cap_req_reply(evt_data.bd_addr, evt_data.io_cap, - evt_data.oob_data, evt_data.auth_req); + btsnd_hcic_io_cap_req_reply(evt_data.bd_addr, evt_data.io_cap, evt_data.oob_data, + evt_data.auth_req); } /******************************************************************************* @@ -2708,15 +2621,14 @@ void btm_io_capabilities_rsp(const tBTM_SP_IO_RSP evt_data) { /* We must have a device record here. * Use the connecting device's CoD for the connection */ - if (evt_data.bd_addr == btm_sec_cb.connecting_bda) + if (evt_data.bd_addr == btm_sec_cb.connecting_bda) { p_dev_rec->dev_class = btm_sec_cb.connecting_dc; + } /* peer sets dedicated bonding bit and we did not initiate dedicated bonding */ - if (btm_sec_cb.pairing_state == - BTM_PAIR_STATE_INCOMING_SSP /* peer initiated bonding */ - && (evt_data.auth_req & - BTM_AUTH_DD_BOND)) /* and dedicated bonding bit is set */ + if (btm_sec_cb.pairing_state == BTM_PAIR_STATE_INCOMING_SSP /* peer initiated bonding */ + && (evt_data.auth_req & BTM_AUTH_DD_BOND)) /* and dedicated bonding bit is set */ { btm_sec_cb.pairing_flags |= BTM_PAIR_FLAGS_PEER_STARTED_DD; } @@ -2725,9 +2637,9 @@ void btm_io_capabilities_rsp(const tBTM_SP_IO_RSP evt_data) { p_dev_rec->sec_rec.rmt_io_caps = evt_data.io_cap; p_dev_rec->sec_rec.rmt_auth_req = evt_data.auth_req; - if (btm_sec_cb.api.p_sp_callback) - (*btm_sec_cb.api.p_sp_callback)(BTM_SP_IO_RSP_EVT, - (tBTM_SP_EVT_DATA*)&evt_data); + if (btm_sec_cb.api.p_sp_callback) { + (*btm_sec_cb.api.p_sp_callback)(BTM_SP_IO_RSP_EVT, (tBTM_SP_EVT_DATA*)&evt_data); + } } /******************************************************************************* @@ -2742,8 +2654,7 @@ void btm_io_capabilities_rsp(const tBTM_SP_IO_RSP evt_data) { * Returns void * ******************************************************************************/ -void btm_proc_sp_req_evt(tBTM_SP_EVT event, const RawAddress bda, - const uint32_t value) { +void btm_proc_sp_req_evt(tBTM_SP_EVT event, const RawAddress bda, const uint32_t value) { tBTM_STATUS status = BTM_ERR_PROCESSING; tBTM_SP_EVT_DATA evt_data; RawAddress& p_bda = evt_data.cfm_req.bd_addr; @@ -2754,8 +2665,7 @@ void btm_proc_sp_req_evt(tBTM_SP_EVT event, const RawAddress bda, tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state)); p_dev_rec = btm_find_dev(p_bda); - if ((p_dev_rec != NULL) && - (btm_sec_cb.pairing_state != BTM_PAIR_STATE_IDLE) && + if ((p_dev_rec != NULL) && (btm_sec_cb.pairing_state != BTM_PAIR_STATE_IDLE) && (btm_sec_cb.pairing_bda == p_bda)) { evt_data.cfm_req.bd_addr = p_dev_rec->bd_addr; evt_data.cfm_req.dev_class = p_dev_rec->dev_class; @@ -2777,8 +2687,8 @@ void btm_proc_sp_req_evt(tBTM_SP_EVT event, const RawAddress bda, if (btm_sec_cb.devcb.loc_io_caps == BTM_IO_CAP_IO) { if (p_dev_rec->sec_rec.rmt_io_caps == BTM_IO_CAP_UNKNOWN) { log::error( - "did not receive IO cap response prior to BTM_SP_CFM_REQ_EVT, " - "failing pairing request"); + "did not receive IO cap response prior to BTM_SP_CFM_REQ_EVT, " + "failing pairing request"); status = BTM_WRONG_MODE; BTM_ConfirmReqReply(status, p_bda); return; @@ -2791,7 +2701,7 @@ void btm_proc_sp_req_evt(tBTM_SP_EVT event, const RawAddress bda, (btm_sec_cb.devcb.loc_auth_req & BTM_AUTH_SP_YES))) { /* Use Numeric Comparison if * 1. Local IO capability is DisplayYesNo, - * 2. Remote IO capability is DisplayOnly or DiaplayYesNo, and + * 2. Remote IO capability is DisplayOnly or DisplayYesNo, and * 3. Either of the devices have requested authenticated link key */ evt_data.cfm_req.just_works = false; } @@ -2799,8 +2709,7 @@ void btm_proc_sp_req_evt(tBTM_SP_EVT event, const RawAddress bda, log::verbose("just_works:{}, io loc:{}, rmt:{}, auth loc:{}, rmt:{}", evt_data.cfm_req.just_works, btm_sec_cb.devcb.loc_io_caps, - p_dev_rec->sec_rec.rmt_io_caps, - btm_sec_cb.devcb.loc_auth_req, + p_dev_rec->sec_rec.rmt_io_caps, btm_sec_cb.devcb.loc_auth_req, p_dev_rec->sec_rec.rmt_auth_req); evt_data.cfm_req.loc_auth_req = btm_sec_cb.devcb.loc_auth_req; @@ -2843,8 +2752,7 @@ void btm_proc_sp_req_evt(tBTM_SP_EVT event, const RawAddress bda, if (event == BTM_SP_CFM_REQ_EVT) { log::verbose("calling BTM_ConfirmReqReply with status: {}", status); BTM_ConfirmReqReply(status, p_bda); - } else if (btm_sec_cb.devcb.loc_io_caps != BTM_IO_CAP_NONE && - event == BTM_SP_KEY_REQ_EVT) { + } else if (btm_sec_cb.devcb.loc_io_caps != BTM_IO_CAP_NONE && event == BTM_SP_KEY_REQ_EVT) { BTM_PasskeyReqReply(status, p_bda, 0); } return; @@ -2865,9 +2773,8 @@ void btm_proc_sp_req_evt(tBTM_SP_EVT event, const RawAddress bda, BTW (PC) is another story. */ p_dev_rec = btm_find_dev(p_bda); if (p_dev_rec != NULL) { - btm_sec_disconnect( - p_dev_rec->hci_handle, HCI_ERR_AUTH_FAILURE, - "stack::btm::btm_sec::btm_proc_sp_req_evt Security failure"); + btm_sec_disconnect(p_dev_rec->hci_handle, HCI_ERR_AUTH_FAILURE, + "stack::btm::btm_sec::btm_proc_sp_req_evt Security failure"); } } else if (btm_sec_cb.devcb.loc_io_caps != BTM_IO_CAP_NONE) { btsnd_hcic_user_passkey_neg_reply(p_bda); @@ -2894,10 +2801,9 @@ void btm_simple_pair_complete(const RawAddress bd_addr, uint8_t status) { return; } - log::verbose( - "btm_simple_pair_complete() Pair State: {} Status:{} sec_state: {}", - tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state), status, - p_dev_rec->sec_rec.sec_state); + log::verbose("btm_simple_pair_complete() Pair State: {} Status:{} sec_state: {}", + tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state), status, + p_dev_rec->sec_rec.sec_state); if (status == HCI_SUCCESS) { p_dev_rec->sec_rec.sec_flags |= BTM_SEC_AUTHENTICATED; @@ -2906,8 +2812,7 @@ void btm_simple_pair_complete(const RawAddress bd_addr, uint8_t status) { btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_WAIT_DISCONNECT); /* Change the timer to 1 second */ - alarm_set_on_mloop(btm_sec_cb.pairing_timer, BT_1SEC_TIMEOUT_MS, - btm_sec_pairing_timeout, NULL); + alarm_set_on_mloop(btm_sec_cb.pairing_timer, BT_1SEC_TIMEOUT_MS, btm_sec_pairing_timeout, NULL); } else if (btm_sec_cb.pairing_bda == bd_addr) { /* stop the timer */ alarm_cancel(btm_sec_cb.pairing_timer); @@ -2924,11 +2829,9 @@ void btm_simple_pair_complete(const RawAddress bd_addr, uint8_t status) { if (disc) { /* simple pairing failed */ /* Avoid sending disconnect on HCI_ERR_PEER_USER */ - if ((status != HCI_ERR_PEER_USER) && - (status != HCI_ERR_CONN_CAUSE_LOCAL_HOST)) { - btm_sec_send_hci_disconnect( - p_dev_rec, HCI_ERR_AUTH_FAILURE, p_dev_rec->hci_handle, - "stack::btm::btm_sec::btm_simple_pair_complete Auth fail"); + if ((status != HCI_ERR_PEER_USER) && (status != HCI_ERR_CONN_CAUSE_LOCAL_HOST)) { + btm_sec_send_hci_disconnect(p_dev_rec, HCI_ERR_AUTH_FAILURE, p_dev_rec->hci_handle, + "stack::btm::btm_sec::btm_simple_pair_complete Auth fail"); } } } @@ -2960,8 +2863,7 @@ void btm_rem_oob_req(const RawAddress bd_addr) { bd_name_copy(evt_data.bd_name, p_dev_rec->sec_bd_name); btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_WAIT_LOCAL_OOB_RSP); - if ((*btm_sec_cb.api.p_sp_callback)(BTM_SP_RMT_OOB_EVT, - (tBTM_SP_EVT_DATA*)&evt_data) == + if ((*btm_sec_cb.api.p_sp_callback)(BTM_SP_RMT_OOB_EVT, (tBTM_SP_EVT_DATA*)&evt_data) == BTM_NOT_AUTHORIZED) { BTM_RemoteOobDataReply(static_cast(true), p_bda, c, r); } @@ -3006,18 +2908,20 @@ void btm_read_local_oob_complete(const tBTM_SP_LOC_OOB evt_data) { static void btm_sec_auth_collision(uint16_t handle) { tBTM_SEC_DEV_REC* p_dev_rec; - if (!btm_sec_cb.collision_start_time) - btm_sec_cb.collision_start_time = - bluetooth::common::time_get_os_boottime_ms(); + if (!btm_sec_cb.collision_start_time) { + btm_sec_cb.collision_start_time = bluetooth::common::time_get_os_boottime_ms(); + } - if ((bluetooth::common::time_get_os_boottime_ms() - - btm_sec_cb.collision_start_time) < BTM_SEC_MAX_COLLISION_DELAY) { + if ((bluetooth::common::time_get_os_boottime_ms() - btm_sec_cb.collision_start_time) < + BTM_SEC_MAX_COLLISION_DELAY) { if (handle == HCI_INVALID_HANDLE) { p_dev_rec = btm_sec_find_dev_by_sec_state(tSECURITY_STATE::AUTHENTICATING); - if (p_dev_rec == NULL) + if (p_dev_rec == NULL) { p_dev_rec = btm_sec_find_dev_by_sec_state(tSECURITY_STATE::ENCRYPTING); - } else + } + } else { p_dev_rec = btm_find_dev_by_handle(handle); + } if (p_dev_rec != NULL) { log::verbose("btm_sec_auth_collision: state {} (retrying in a moment...)", @@ -3047,15 +2951,16 @@ static void btm_sec_auth_collision(uint16_t handle) { *****************************************************************************/ static bool btm_sec_auth_retry(uint16_t handle, uint8_t status) { tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev_by_handle(handle); - if (!p_dev_rec) return false; + if (!p_dev_rec) { + return false; + } /* keep the old sm4 flag and clear the retry bit in control block */ uint8_t old_sm4 = p_dev_rec->sm4; p_dev_rec->sm4 &= ~BTM_SM4_RETRY; - if ((btm_sec_cb.pairing_state == BTM_PAIR_STATE_IDLE) && - ((old_sm4 & BTM_SM4_RETRY) == 0) && (HCI_ERR_KEY_MISSING == status) && - BTM_SEC_IS_SM4(p_dev_rec->sm4)) { + if ((btm_sec_cb.pairing_state == BTM_PAIR_STATE_IDLE) && ((old_sm4 & BTM_SM4_RETRY) == 0) && + (HCI_ERR_KEY_MISSING == status) && BTM_SEC_IS_SM4(p_dev_rec->sm4)) { /* This retry for missing key is for Lisbon or later only. Legacy device do not need this. the controller will drive the retry automatically @@ -3064,8 +2969,8 @@ static bool btm_sec_auth_retry(uint16_t handle, uint8_t status) { btm_restore_mode(); p_dev_rec->sm4 |= BTM_SM4_RETRY; p_dev_rec->sec_rec.sec_flags &= ~BTM_SEC_LINK_KEY_KNOWN; - log::verbose("Retry for missing key sm4:x{:x} sec_flags:0x{:x}", - p_dev_rec->sm4, p_dev_rec->sec_rec.sec_flags); + log::verbose("Retry for missing key sm4:x{:x} sec_flags:0x{:x}", p_dev_rec->sm4, + p_dev_rec->sec_rec.sec_flags); /* With BRCM controller, we do not need to delete the stored link key in controller. @@ -3087,15 +2992,14 @@ void btm_sec_auth_complete(uint16_t handle, tHCI_STATUS status) { if (p_dev_rec) { log::verbose( - "Security Manager: in state: {}, handle: {}, status: {}, " - "dev->sec_rec.sec_state:{}, bda: {}, RName: {}", - tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state), handle, - status, p_dev_rec->sec_rec.sec_state, p_dev_rec->bd_addr, - reinterpret_cast(p_dev_rec->sec_bd_name)); + "Security Manager: in state: {}, handle: {}, status: {}, " + "dev->sec_rec.sec_state:{}, bda: {}, RName: {}", + tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state), handle, status, + p_dev_rec->sec_rec.sec_state, p_dev_rec->bd_addr, + reinterpret_cast(p_dev_rec->sec_bd_name)); } else { log::verbose("Security Manager: in state: {}, handle: {}, status: {}", - tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state), - handle, status); + tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state), handle, status); } /* For transaction collision we need to wait and repeat. There is no need */ @@ -3122,7 +3026,9 @@ void btm_sec_auth_complete(uint16_t handle, tHCI_STATUS status) { l2cu_start_post_bond_timer(p_dev_rec->hci_handle); } - if (!p_dev_rec) return; + if (!p_dev_rec) { + return; + } if (p_dev_rec->sec_rec.sec_state == tSECURITY_STATE::AUTHENTICATING) { p_dev_rec->sec_rec.sec_state = tSECURITY_STATE::IDLE; @@ -3135,8 +3041,7 @@ void btm_sec_auth_complete(uint16_t handle, tHCI_STATUS status) { * encrypted link, so device is correct. */ if ((status == HCI_ERR_COMMAND_DISALLOWED) && - ((p_dev_rec->sec_rec.sec_flags & - (BTM_SEC_AUTHENTICATED | BTM_SEC_ENCRYPTED)) == + ((p_dev_rec->sec_rec.sec_flags & (BTM_SEC_AUTHENTICATED | BTM_SEC_ENCRYPTED)) == (BTM_SEC_AUTHENTICATED | BTM_SEC_ENCRYPTED))) { status = HCI_SUCCESS; } @@ -3164,10 +3069,10 @@ void btm_sec_auth_complete(uint16_t handle, tHCI_STATUS status) { /* User probably Disabled the keyboard while it was asleap. Let them try */ if (btm_sec_cb.api.p_auth_complete_callback) { /* report the suthentication status */ - if ((old_state != BTM_PAIR_STATE_IDLE) || (status != HCI_SUCCESS)) - (*btm_sec_cb.api.p_auth_complete_callback)( - p_dev_rec->bd_addr, p_dev_rec->dev_class, p_dev_rec->sec_bd_name, - status); + if ((old_state != BTM_PAIR_STATE_IDLE) || (status != HCI_SUCCESS)) { + (*btm_sec_cb.api.p_auth_complete_callback)(p_dev_rec->bd_addr, p_dev_rec->dev_class, + p_dev_rec->sec_bd_name, status); + } } /* If this is a bonding procedure can disconnect the link now */ @@ -3175,11 +3080,11 @@ void btm_sec_auth_complete(uint16_t handle, tHCI_STATUS status) { p_dev_rec->sec_rec.security_required &= ~BTM_SEC_OUT_AUTHENTICATE; if (status != HCI_SUCCESS) { - if (((status != HCI_ERR_PEER_USER) && - (status != HCI_ERR_CONN_CAUSE_LOCAL_HOST))) + if ((status != HCI_ERR_PEER_USER) && (status != HCI_ERR_CONN_CAUSE_LOCAL_HOST)) { btm_sec_send_hci_disconnect( - p_dev_rec, HCI_ERR_PEER_USER, p_dev_rec->hci_handle, - "stack::btm::btm_sec::btm_sec_auth_retry Auth fail while bonding"); + p_dev_rec, HCI_ERR_PEER_USER, p_dev_rec->hci_handle, + "stack::btm::btm_sec::btm_sec_auth_retry Auth fail while bonding"); + } } else { BTM_LogHistory(kBtmLogTag, p_dev_rec->bd_addr, "Bonding completed", hci_error_code_text(status)); @@ -3189,13 +3094,12 @@ void btm_sec_auth_complete(uint16_t handle, tHCI_STATUS status) { if (role == HCI_ROLE_CENTRAL) { // Encryption is required to start SM over BR/EDR // indicate that this is encryption after authentication - BTM_SetEncryption(p_dev_rec->bd_addr, BT_TRANSPORT_BR_EDR, NULL, NULL, - BTM_BLE_SEC_NONE); + BTM_SetEncryption(p_dev_rec->bd_addr, BT_TRANSPORT_BR_EDR, NULL, NULL, BTM_BLE_SEC_NONE); } else if (p_dev_rec->IsLocallyInitiated()) { // Encryption will be set in role_changed callback log::info( - "auth completed in role=peripheral, try to switch role and " - "encrypt"); + "auth completed in role=peripheral, try to switch role and " + "encrypt"); BTM_SwitchRoleToCentral(p_dev_rec->RemoteAddress()); } @@ -3210,9 +3114,8 @@ void btm_sec_auth_complete(uint16_t handle, tHCI_STATUS status) { btm_sec_dev_rec_cback_event(p_dev_rec, BTM_ERR_PROCESSING, false); if (btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_DISC_WHEN_DONE) { - btm_sec_send_hci_disconnect( - p_dev_rec, HCI_ERR_AUTH_FAILURE, p_dev_rec->hci_handle, - "stack::btm::btm_sec::btm_sec_auth_retry Auth failed"); + btm_sec_send_hci_disconnect(p_dev_rec, HCI_ERR_AUTH_FAILURE, p_dev_rec->hci_handle, + "stack::btm::btm_sec::btm_sec_auth_retry Auth failed"); } return; } @@ -3230,8 +3133,9 @@ void btm_sec_auth_complete(uint16_t handle, tHCI_STATUS status) { /* If there is no next procedure, or procedure failed to start, notify the * caller */ - if (btm_status != BTM_CMD_STARTED) + if (btm_status != BTM_CMD_STARTED) { btm_sec_dev_rec_cback_event(p_dev_rec, btm_status, false); + } } /******************************************************************************* @@ -3244,14 +3148,12 @@ void btm_sec_auth_complete(uint16_t handle, tHCI_STATUS status) { * Returns void * ******************************************************************************/ -void btm_sec_encrypt_change(uint16_t handle, tHCI_STATUS status, - uint8_t encr_enable) { +void btm_sec_encrypt_change(uint16_t handle, tHCI_STATUS status, uint8_t encr_enable) { /* For transaction collision we need to wait and repeat. There is no need */ /* for random timeout because only peripheral should receive the result */ if ((status == HCI_ERR_LMP_ERR_TRANS_COLLISION) || (status == HCI_ERR_DIFF_TRANSACTION_COLLISION)) { - log::error("Encryption collision failed status:{}", - hci_error_code_text(status)); + log::error("Encryption collision failed status:{}", hci_error_code_text(status)); btm_sec_auth_collision(handle); return; } @@ -3260,27 +3162,25 @@ void btm_sec_encrypt_change(uint16_t handle, tHCI_STATUS status, tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev_by_handle(handle); if (p_dev_rec == nullptr) { log::warn( - "Received encryption change for unknown device handle:0x{:04x} " - "status:{} enable:0x{:x}", - handle, hci_status_code_text(status), encr_enable); + "Received encryption change for unknown device handle:0x{:04x} " + "status:{} enable:0x{:x}", + handle, hci_status_code_text(status), encr_enable); return; } const tBT_TRANSPORT transport = - BTM_IsBleConnection(handle) ? BT_TRANSPORT_LE : BT_TRANSPORT_BR_EDR; + BTM_IsBleConnection(handle) ? BT_TRANSPORT_LE : BT_TRANSPORT_BR_EDR; log::debug( - "Security Manager encryption change request hci_status:{} request:{} " - "state:{} sec_flags:0x{:x}", - hci_status_code_text(status), (encr_enable) ? "encrypt" : "unencrypt", - security_state_text(p_dev_rec->sec_rec.sec_state), - p_dev_rec->sec_rec.sec_flags); + "Security Manager encryption change request hci_status:{} request:{} " + "state:{} sec_flags:0x{:x}", + hci_status_code_text(status), (encr_enable) ? "encrypt" : "unencrypt", + security_state_text(p_dev_rec->sec_rec.sec_state), p_dev_rec->sec_rec.sec_flags); if (status == HCI_SUCCESS) { if (encr_enable) { if (p_dev_rec->hci_handle == handle) { // classic - p_dev_rec->sec_rec.sec_flags |= - (BTM_SEC_AUTHENTICATED | BTM_SEC_ENCRYPTED); + p_dev_rec->sec_rec.sec_flags |= (BTM_SEC_AUTHENTICATED | BTM_SEC_ENCRYPTED); if (p_dev_rec->sec_rec.pin_code_length >= 16 || p_dev_rec->sec_rec.link_key_type == BTM_LKEY_TYPE_AUTH_COMB || p_dev_rec->sec_rec.link_key_type == BTM_LKEY_TYPE_AUTH_COMB_P_256) { @@ -3293,53 +3193,47 @@ void btm_sec_encrypt_change(uint16_t handle, tHCI_STATUS status, } } else { log::error( - "Received encryption change for unknown device handle:0x{:04x} " - "status:{} enable:0x{:x}", - handle, hci_status_code_text(status), encr_enable); + "Received encryption change for unknown device handle:0x{:04x} " + "status:{} enable:0x{:x}", + handle, hci_status_code_text(status), encr_enable); } } else { - log::info( - "Encryption was not enabled locally resetting encryption state"); + log::info("Encryption was not enabled locally resetting encryption state"); /* It is possible that we decrypted the link to perform role switch */ /* mark link not to be encrypted, so that when we execute security next * time it will kick in again */ - if (p_dev_rec->hci_handle == handle) { // clasic + if (p_dev_rec->hci_handle == handle) { // classic p_dev_rec->sec_rec.sec_flags &= ~BTM_SEC_ENCRYPTED; } else if (p_dev_rec->ble_hci_handle == handle) { // BLE p_dev_rec->sec_rec.sec_flags &= ~BTM_SEC_LE_ENCRYPTED; } else { log::error( - "Received encryption change for unknown device handle:0x{:04x} " - "status:{} enable:0x{:x}", - handle, hci_status_code_text(status), encr_enable); + "Received encryption change for unknown device handle:0x{:04x} " + "status:{} enable:0x{:x}", + handle, hci_status_code_text(status), encr_enable); } } } - const bool is_encrypted = p_dev_rec->sec_rec.is_le_device_encrypted() || - p_dev_rec->sec_rec.is_device_encrypted(); + const bool is_encrypted = + p_dev_rec->sec_rec.is_le_device_encrypted() || p_dev_rec->sec_rec.is_device_encrypted(); BTM_LogHistory( - kBtmLogTag, - (transport == BT_TRANSPORT_LE) ? p_dev_rec->ble.pseudo_addr - : p_dev_rec->bd_addr, - (status == HCI_SUCCESS) ? "Encryption success" : "Encryption failed", - base::StringPrintf("status:%s transport:%s is_encrypted:%c", - hci_status_code_text(status).c_str(), - bt_transport_text(transport).c_str(), - is_encrypted ? 'T' : 'F')); - - log::debug("after update p_dev_rec->sec_rec.sec_flags=0x{:x}", - p_dev_rec->sec_rec.sec_flags); + kBtmLogTag, + (transport == BT_TRANSPORT_LE) ? p_dev_rec->ble.pseudo_addr : p_dev_rec->bd_addr, + (status == HCI_SUCCESS) ? "Encryption success" : "Encryption failed", + base::StringPrintf("status:%s transport:%s is_encrypted:%c", + hci_status_code_text(status).c_str(), + bt_transport_text(transport).c_str(), is_encrypted ? 'T' : 'F')); + + log::debug("after update p_dev_rec->sec_rec.sec_flags=0x{:x}", p_dev_rec->sec_rec.sec_flags); btm_sec_check_pending_enc_req(p_dev_rec, transport, encr_enable); if (transport == BT_TRANSPORT_LE) { if (status == HCI_ERR_KEY_MISSING || status == HCI_ERR_AUTH_FAILURE || status == HCI_ERR_ENCRY_MODE_NOT_ACCEPTABLE) { - if (com::android::bluetooth::flags:: - sec_dont_clear_keys_on_encryption_err()) { - log::error("{} encrypt failure status 0x{:x}", p_dev_rec->bd_addr, - status); + if (com::android::bluetooth::flags::sec_dont_clear_keys_on_encryption_err()) { + log::error("{} encrypt failure status 0x{:x}", p_dev_rec->bd_addr, status); } else { p_dev_rec->sec_rec.sec_flags &= ~(BTM_SEC_LE_LINK_KEY_KNOWN); p_dev_rec->sec_rec.ble_keys.key_type = BTM_LE_KEY_NONE; @@ -3360,11 +3254,9 @@ void btm_sec_encrypt_change(uint16_t handle, tHCI_STATUS status, p_dev_rec->sec_rec.enc_key_size = 16; } - log::debug("in new_encr_key_256 is {}", - p_dev_rec->sec_rec.new_encryption_key_is_p256); + log::debug("in new_encr_key_256 is {}", p_dev_rec->sec_rec.new_encryption_key_is_p256); - if ((status == HCI_SUCCESS) && encr_enable && - (p_dev_rec->hci_handle == handle)) { + if ((status == HCI_SUCCESS) && encr_enable && (p_dev_rec->hci_handle == handle)) { /* if BR key is temporary no need for LE LTK derivation */ bool derive_ltk = true; if (p_dev_rec->sec_rec.rmt_auth_req == BTM_AUTH_SP_NO && @@ -3395,8 +3287,7 @@ void btm_sec_encrypt_change(uint16_t handle, tHCI_STATUS status, if (!p_dev_rec->sec_rec.is_security_state_bredr_encrypting()) { if (tSECURITY_STATE::DELAY_FOR_ENC == p_dev_rec->sec_rec.sec_state) { p_dev_rec->sec_rec.sec_state = tSECURITY_STATE::IDLE; - log::verbose("clearing callback. p_dev_rec={}, p_callback={}", - fmt::ptr(p_dev_rec), + log::verbose("clearing callback. p_dev_rec={}, p_callback={}", fmt::ptr(p_dev_rec), fmt::ptr(p_dev_rec->sec_rec.p_callback)); p_dev_rec->sec_rec.p_callback = NULL; l2cu_resubmit_pending_sec_req(&p_dev_rec->bd_addr); @@ -3422,15 +3313,16 @@ void btm_sec_encrypt_change(uint16_t handle, tHCI_STATUS status, tBTM_STATUS btm_status = btm_sec_execute_procedure(p_dev_rec); /* If there is no next procedure, or procedure failed to start, notify the * caller */ - if (static_cast>(status) != - BTM_CMD_STARTED) + if (static_cast>(status) != BTM_CMD_STARTED) { btm_sec_dev_rec_cback_event(p_dev_rec, btm_status, false); + } } constexpr uint8_t MIN_KEY_SIZE = 7; -static void read_encryption_key_size_complete_after_encryption_change( - uint8_t status, uint16_t handle, uint8_t key_size) { +static void read_encryption_key_size_complete_after_encryption_change(uint8_t status, + uint16_t handle, + uint8_t key_size) { if (status == HCI_ERR_INSUFFCIENT_SECURITY) { /* If remote device stop the encryption before we call "Read Encryption Key * Size", we might receive Insufficient Security, which means that link is @@ -3448,36 +3340,31 @@ static void read_encryption_key_size_complete_after_encryption_change( } if (key_size < MIN_KEY_SIZE) { - log::error( - "encryption key too short, disconnecting. handle:0x{:x},key_size:{}", - handle, key_size); + log::error("encryption key too short, disconnecting. handle:0x{:x},key_size:{}", handle, + key_size); - acl_disconnect_from_handle( - handle, HCI_ERR_HOST_REJECT_SECURITY, - "stack::btu::btu_hcif::read_encryption_key_size_complete_after_" - "encryption_change Key Too Short"); + acl_disconnect_from_handle(handle, HCI_ERR_HOST_REJECT_SECURITY, + "stack::btu::btu_hcif::read_encryption_key_size_complete_after_" + "encryption_change Key Too Short"); return; } if (btm_sec_is_session_key_size_downgrade(handle, key_size)) { log::error( - "encryption key size lower than cached value, disconnecting. " - "handle: 0x{:x} attempted key size: {}", - handle, key_size); - acl_disconnect_from_handle( - handle, HCI_ERR_HOST_REJECT_SECURITY, - "stack::btu::btu_hcif::read_encryption_key_size_complete_after_" - "encryption_change Key Size Downgrade"); + "encryption key size lower than cached value, disconnecting. " + "handle: 0x{:x} attempted key size: {}", + handle, key_size); + acl_disconnect_from_handle(handle, HCI_ERR_HOST_REJECT_SECURITY, + "stack::btu::btu_hcif::read_encryption_key_size_complete_after_" + "encryption_change Key Size Downgrade"); return; } btm_sec_update_session_key_size(handle, key_size); // good key size - succeed - btm_acl_encrypt_change(handle, static_cast(status), - 1 /* enable */); - btm_sec_encrypt_change(handle, static_cast(status), - 1 /* enable */); + btm_acl_encrypt_change(handle, static_cast(status), 1 /* enable */); + btm_sec_encrypt_change(handle, static_cast(status), 1 /* enable */); } // TODO: Remove @@ -3492,25 +3379,20 @@ void smp_cancel_start_encryption_attempt(); * Returns void * ******************************************************************************/ -void btm_sec_encryption_change_evt(uint16_t handle, tHCI_STATUS status, - uint8_t encr_enable) { - if (status != HCI_SUCCESS || encr_enable == 0 || - BTM_IsBleConnection(handle) || +void btm_sec_encryption_change_evt(uint16_t handle, tHCI_STATUS status, uint8_t encr_enable) { + if (status != HCI_SUCCESS || encr_enable == 0 || BTM_IsBleConnection(handle) || !bluetooth::shim::GetController()->IsSupported( - bluetooth::hci::OpCode::READ_ENCRYPTION_KEY_SIZE)) { + bluetooth::hci::OpCode::READ_ENCRYPTION_KEY_SIZE)) { if (status == HCI_ERR_CONNECTION_TOUT) { smp_cancel_start_encryption_attempt(); return; } - btm_acl_encrypt_change(handle, static_cast(status), - encr_enable); - btm_sec_encrypt_change(handle, static_cast(status), - encr_enable); + btm_acl_encrypt_change(handle, static_cast(status), encr_enable); + btm_sec_encrypt_change(handle, static_cast(status), encr_enable); } else { btsnd_hcic_read_encryption_key_size( - handle, - base::Bind(&read_encryption_key_size_complete_after_encryption_change)); + handle, base::Bind(&read_encryption_key_size_complete_after_encryption_change)); } } /******************************************************************************* @@ -3549,18 +3431,17 @@ static void btm_sec_connect_after_reject_timeout(void* /* data */) { * Returns void * ******************************************************************************/ -void btm_sec_connected(const RawAddress& bda, uint16_t handle, - tHCI_STATUS status, uint8_t enc_mode, +void btm_sec_connected(const RawAddress& bda, uint16_t handle, tHCI_STATUS status, uint8_t enc_mode, tHCI_ROLE assigned_role) { uint8_t bit_shift = 0; tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bda); if (!p_dev_rec) { log::debug( - "Connected to new device state:{} handle:0x{:04x} status:{} " - "enc_mode:{} bda:{}", - tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state), handle, - hci_status_code_text(status), enc_mode, bda); + "Connected to new device state:{} handle:0x{:04x} status:{} " + "enc_mode:{} bda:{}", + tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state), handle, + hci_status_code_text(status), enc_mode, bda); if (status == HCI_SUCCESS) { p_dev_rec = btm_sec_alloc_dev(bda); @@ -3568,10 +3449,9 @@ void btm_sec_connected(const RawAddress& bda, uint16_t handle, } else { /* If the device matches with stored paring address * reset the paring state to idle */ - if ((btm_sec_cb.pairing_state != BTM_PAIR_STATE_IDLE) && - btm_sec_cb.pairing_bda == bda) { - log::warn("Connection failed during bonding attempt peer:{} reason:{}", - bda, hci_error_code_text(status)); + if ((btm_sec_cb.pairing_state != BTM_PAIR_STATE_IDLE) && btm_sec_cb.pairing_bda == bda) { + log::warn("Connection failed during bonding attempt peer:{} reason:{}", bda, + hci_error_code_text(status)); btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_IDLE); } @@ -3581,11 +3461,11 @@ void btm_sec_connected(const RawAddress& bda, uint16_t handle, } } else { log::debug( - "Connected to known device state:{} handle:0x{:04x} status:{} " - "enc_mode:{} bda:{} RName:{}", - tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state), handle, - hci_status_code_text(status), enc_mode, bda, - reinterpret_cast(p_dev_rec->sec_bd_name)); + "Connected to known device state:{} handle:0x{:04x} status:{} " + "enc_mode:{} bda:{} RName:{}", + tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state), handle, + hci_status_code_text(status), enc_mode, bda, + reinterpret_cast(p_dev_rec->sec_bd_name)); bit_shift = (handle == p_dev_rec->ble_hci_handle) ? 8 : 0; /* Update the timestamp for this device */ @@ -3597,11 +3477,10 @@ void btm_sec_connected(const RawAddress& bda, uint16_t handle, /* if incoming acl connection failed while pairing, then try to connect * and continue */ /* Motorola S9 disconnects without asking pin code */ - if ((status != HCI_SUCCESS) && - (btm_sec_cb.pairing_state == BTM_PAIR_STATE_WAIT_PIN_REQ)) { + if ((status != HCI_SUCCESS) && (btm_sec_cb.pairing_state == BTM_PAIR_STATE_WAIT_PIN_REQ)) { log::warn( - "Security Manager: btm_sec_connected: incoming connection failed " - "without asking PIN"); + "Security Manager: btm_sec_connected: incoming connection failed " + "without asking PIN"); p_dev_rec->sm4 &= ~BTM_SM4_CONN_PEND; if (p_dev_rec->sec_rec.sec_flags & BTM_SEC_NAME_KNOWN) { @@ -3617,8 +3496,7 @@ void btm_sec_connected(const RawAddress& bda, uint16_t handle, btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_GET_REM_NAME); if (get_btm_client_interface().peer.BTM_ReadRemoteDeviceName( - p_dev_rec->bd_addr, NULL, BT_TRANSPORT_BR_EDR) != - BTM_CMD_STARTED) { + p_dev_rec->bd_addr, NULL, BT_TRANSPORT_BR_EDR) != BTM_CMD_STARTED) { log::error("cannot read remote name"); btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_IDLE); } @@ -3643,16 +3521,16 @@ void btm_sec_connected(const RawAddress& bda, uint16_t handle, if ((status == HCI_ERR_HOST_REJECT_DEVICE) && (btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_REJECTED_CONNECT)) { log::warn( - "Security Manager: btm_sec_connected: HCI_Conn_Comp Flags:0x{:04x}, " - "sm4: 0x{:x}", - btm_sec_cb.pairing_flags, p_dev_rec->sm4); + "Security Manager: btm_sec_connected: HCI_Conn_Comp Flags:0x{:04x}, " + "sm4: 0x{:x}", + btm_sec_cb.pairing_flags, p_dev_rec->sm4); btm_sec_cb.pairing_flags &= ~BTM_PAIR_FLAGS_REJECTED_CONNECT; if (BTM_SEC_IS_SM4_UNKNOWN(p_dev_rec->sm4)) { /* Try again: RNR when no ACL causes HCI_RMT_HOST_SUP_FEAT_NOTIFY_EVT */ btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_GET_REM_NAME); if (get_btm_client_interface().peer.BTM_ReadRemoteDeviceName( - bda, NULL, BT_TRANSPORT_BR_EDR) != BTM_CMD_STARTED) { + bda, NULL, BT_TRANSPORT_BR_EDR) != BTM_CMD_STARTED) { log::error("cannot read remote name"); btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_IDLE); } @@ -3664,14 +3542,13 @@ void btm_sec_connected(const RawAddress& bda, uint16_t handle, /* Start timer with 0 to initiate connection with new LCB */ /* because L2CAP will delete current LCB with this event */ btm_sec_cb.p_collided_dev_rec = p_dev_rec; - alarm_set_on_mloop(btm_sec_cb.sec_collision_timer, 0, - btm_sec_connect_after_reject_timeout, NULL); + alarm_set_on_mloop(btm_sec_cb.sec_collision_timer, 0, btm_sec_connect_after_reject_timeout, + NULL); } return; } else if (status == HCI_ERR_CONNECTION_EXISTS) { /* wait for incoming connection without resetting pairing state */ - log::warn( - "Security Manager: btm_sec_connected: Wait for incoming connection"); + log::warn("Security Manager: btm_sec_connected: Wait for incoming connection"); return; } is_pairing_device = true; @@ -3686,9 +3563,8 @@ void btm_sec_connected(const RawAddress& bda, uint16_t handle, if (is_pairing_device) { p_dev_rec->sec_rec.security_required &= ~BTM_SEC_OUT_AUTHENTICATE; p_dev_rec->sec_rec.sec_flags &= - ~((BTM_SEC_LINK_KEY_KNOWN | BTM_SEC_LINK_KEY_AUTHED) << bit_shift); - log::verbose("security_required:{:x}", - p_dev_rec->sec_rec.security_required); + ~((BTM_SEC_LINK_KEY_KNOWN | BTM_SEC_LINK_KEY_AUTHED) << bit_shift); + log::verbose("security_required:{:x}", p_dev_rec->sec_rec.security_required); btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_IDLE); @@ -3702,14 +3578,12 @@ void btm_sec_connected(const RawAddress& bda, uint16_t handle, 3. Remote is SSP capable. */ else if ((p_dev_rec->sec_rec.link_key_type <= BTM_LKEY_TYPE_REMOTE_UNIT) && - (((status == HCI_ERR_AUTH_FAILURE) || - (status == HCI_ERR_KEY_MISSING) || - (status == HCI_ERR_HOST_REJECT_SECURITY) || - (status == HCI_ERR_PAIRING_NOT_ALLOWED) || - (status == HCI_ERR_UNIT_KEY_USED) || - (status == HCI_ERR_PAIRING_WITH_UNIT_KEY_NOT_SUPPORTED) || - (status == HCI_ERR_ENCRY_MODE_NOT_ACCEPTABLE) || - (status == HCI_ERR_REPEATED_ATTEMPTS)))) { + ((status == HCI_ERR_AUTH_FAILURE) || (status == HCI_ERR_KEY_MISSING) || + (status == HCI_ERR_HOST_REJECT_SECURITY) || (status == HCI_ERR_PAIRING_NOT_ALLOWED) || + (status == HCI_ERR_UNIT_KEY_USED) || + (status == HCI_ERR_PAIRING_WITH_UNIT_KEY_NOT_SUPPORTED) || + (status == HCI_ERR_ENCRY_MODE_NOT_ACCEPTABLE) || + (status == HCI_ERR_REPEATED_ATTEMPTS))) { p_dev_rec->sec_rec.security_required &= ~BTM_SEC_OUT_AUTHENTICATE; p_dev_rec->sec_rec.sec_flags &= ~(BTM_SEC_LE_LINK_KEY_KNOWN << bit_shift); @@ -3730,18 +3604,18 @@ void btm_sec_connected(const RawAddress& bda, uint16_t handle, if (!p_dev_rec) { /* Don't callback when device security record was removed */ log::debug( - "device security record associated with this bda has been removed! " - "bda={}, do not callback", - bda); + "device security record associated with this bda has been removed! " + "bda={}, do not callback", + bda); return; } - if (status == HCI_ERR_CONNECTION_TOUT || - status == HCI_ERR_LMP_RESPONSE_TIMEOUT || - status == HCI_ERR_UNSPECIFIED || status == HCI_ERR_PAGE_TIMEOUT) + if (status == HCI_ERR_CONNECTION_TOUT || status == HCI_ERR_LMP_RESPONSE_TIMEOUT || + status == HCI_ERR_UNSPECIFIED || status == HCI_ERR_PAGE_TIMEOUT) { btm_sec_dev_rec_cback_event(p_dev_rec, BTM_DEVICE_TIMEOUT, false); - else + } else { btm_sec_dev_rec_cback_event(p_dev_rec, BTM_ERR_PROCESSING, false); + } return; } @@ -3752,8 +3626,7 @@ void btm_sec_connected(const RawAddress& bda, uint16_t handle, * the authenticate requirement bit. Reset the pairing state machine * and inform l2cap if the directed bonding was initiated. */ - if (is_pairing_device && - (p_dev_rec->sec_rec.sec_flags & BTM_SEC_LINK_KEY_KNOWN)) { + if (is_pairing_device && (p_dev_rec->sec_rec.sec_flags & BTM_SEC_LINK_KEY_KNOWN)) { if (p_dev_rec->sec_rec.link_key_not_sent) { p_dev_rec->sec_rec.link_key_not_sent = false; btm_send_link_key_notif(p_dev_rec); @@ -3763,7 +3636,7 @@ void btm_sec_connected(const RawAddress& bda, uint16_t handle, /* remember flag before it is initialized */ const bool is_pair_flags_we_started_dd = - btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD; + btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD; btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_IDLE); if (is_pair_flags_we_started_dd) { @@ -3795,12 +3668,11 @@ void btm_sec_connected(const RawAddress& bda, uint16_t handle, /* authorization complete could have come after the connection is dropped */ /* and that would set wrong flag that link has been authorized already */ p_dev_rec->sec_rec.sec_flags &= - ~((BTM_SEC_AUTHENTICATED | BTM_SEC_ENCRYPTED | BTM_SEC_ROLE_SWITCHED) - << bit_shift); + ~((BTM_SEC_AUTHENTICATED | BTM_SEC_ENCRYPTED | BTM_SEC_ROLE_SWITCHED) << bit_shift); - if (enc_mode != HCI_ENCRYPT_MODE_DISABLED) - p_dev_rec->sec_rec.sec_flags |= - ((BTM_SEC_AUTHENTICATED | BTM_SEC_ENCRYPTED) << bit_shift); + if (enc_mode != HCI_ENCRYPT_MODE_DISABLED) { + p_dev_rec->sec_rec.sec_flags |= ((BTM_SEC_AUTHENTICATED | BTM_SEC_ENCRYPTED) << bit_shift); + } if (p_dev_rec->sec_rec.pin_code_length >= 16 || p_dev_rec->sec_rec.link_key_type == BTM_LKEY_TYPE_AUTH_COMB || @@ -3812,24 +3684,22 @@ void btm_sec_connected(const RawAddress& bda, uint16_t handle, /* the name, or if we are originator because some procedure can have */ /* been scheduled while connection was down */ log::debug("Is connection locally initiated:{}", p_dev_rec->is_originator); - if (!(p_dev_rec->sec_rec.sec_flags & BTM_SEC_NAME_KNOWN) || - p_dev_rec->is_originator) { + if (!(p_dev_rec->sec_rec.sec_flags & BTM_SEC_NAME_KNOWN) || p_dev_rec->is_originator) { tBTM_STATUS res = btm_sec_execute_procedure(p_dev_rec); - if (res != BTM_CMD_STARTED) + if (res != BTM_CMD_STARTED) { btm_sec_dev_rec_cback_event(p_dev_rec, res, false); + } } } -tBTM_STATUS btm_sec_disconnect(uint16_t handle, tHCI_STATUS reason, - std::string comment) { +tBTM_STATUS btm_sec_disconnect(uint16_t handle, tHCI_STATUS reason, std::string comment) { tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev_by_handle(handle); /* In some weird race condition we may not have a record */ if (!p_dev_rec) { - acl_disconnect_from_handle( - handle, reason, - "stack::btm::btm_sec::btm_sec_disconnect No security record"); - return (BTM_SUCCESS); + acl_disconnect_from_handle(handle, reason, + "stack::btm::btm_sec::btm_sec_disconnect No security record"); + return BTM_SUCCESS; } /* If we are in the process of bonding we need to tell client that auth failed @@ -3839,37 +3709,33 @@ tBTM_STATUS btm_sec_disconnect(uint16_t handle, tHCI_STATUS reason, (btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD)) { /* we are currently doing bonding. Link will be disconnected when done */ btm_sec_cb.pairing_flags |= BTM_PAIR_FLAGS_DISC_WHEN_DONE; - return (BTM_BUSY); + return BTM_BUSY; } return btm_sec_send_hci_disconnect(p_dev_rec, reason, handle, comment); } -void btm_sec_disconnected(uint16_t handle, tHCI_REASON reason, - std::string comment) { - if ((reason != HCI_ERR_CONN_CAUSE_LOCAL_HOST) && - (reason != HCI_ERR_PEER_USER) && (reason != HCI_ERR_REMOTE_POWER_OFF)) { +void btm_sec_disconnected(uint16_t handle, tHCI_REASON reason, std::string comment) { + if ((reason != HCI_ERR_CONN_CAUSE_LOCAL_HOST) && (reason != HCI_ERR_PEER_USER) && + (reason != HCI_ERR_REMOTE_POWER_OFF)) { log::warn("Got uncommon disconnection reason:{} handle:0x{:04x} comment:{}", hci_error_code_text(reason), handle, comment); } tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev_by_handle(handle); if (p_dev_rec == nullptr) { - log::warn("Got disconnect for unknown device record handle:0x{:04x}", - handle); + log::warn("Got disconnect for unknown device record handle:0x{:04x}", handle); return; } const tBT_TRANSPORT transport = - (handle == p_dev_rec->hci_handle) ? BT_TRANSPORT_BR_EDR : BT_TRANSPORT_LE; + (handle == p_dev_rec->hci_handle) ? BT_TRANSPORT_BR_EDR : BT_TRANSPORT_LE; bool pairing_transport_matches = true; - if (com::android::bluetooth::flags:: - cancel_pairing_only_on_disconnected_transport()) { - tBT_TRANSPORT pairing_transport = - (btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_LE_ACTIVE) == 0 - ? BT_TRANSPORT_BR_EDR - : BT_TRANSPORT_LE; + if (com::android::bluetooth::flags::cancel_pairing_only_on_disconnected_transport()) { + tBT_TRANSPORT pairing_transport = (btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_LE_ACTIVE) == 0 + ? BT_TRANSPORT_BR_EDR + : BT_TRANSPORT_LE; pairing_transport_matches = (transport == pairing_transport); } @@ -3880,10 +3746,8 @@ void btm_sec_disconnected(uint16_t handle, tHCI_REASON reason, */ const uint8_t old_pairing_flags = btm_sec_cb.pairing_flags; if (btm_sec_cb.pairing_state != BTM_PAIR_STATE_IDLE && - btm_sec_cb.pairing_bda == p_dev_rec->bd_addr && - pairing_transport_matches) { - log::debug("Disconnected while pairing process active handle:0x{:04x}", - handle); + btm_sec_cb.pairing_bda == p_dev_rec->bd_addr && pairing_transport_matches) { + log::debug("Disconnected while pairing process active handle:0x{:04x}", handle); btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_IDLE); p_dev_rec->sec_rec.sec_flags &= ~BTM_SEC_LINK_KEY_KNOWN; @@ -3897,8 +3761,7 @@ void btm_sec_disconnected(uint16_t handle, tHCI_REASON reason, } else if (old_pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD) { status = HCI_ERR_HOST_REJECT_SECURITY; } else { - DEVICE_IOT_CONFIG_ADDR_INT_ADD_ONE(p_dev_rec->bd_addr, - IOT_CONF_KEY_GAP_DISC_AUTHFAIL_COUNT); + DEVICE_IOT_CONFIG_ADDR_INT_ADD_ONE(p_dev_rec->bd_addr, IOT_CONF_KEY_GAP_DISC_AUTHFAIL_COUNT); } NotifyBondingChange(*p_dev_rec, status); @@ -3913,38 +3776,35 @@ void btm_sec_disconnected(uint16_t handle, tHCI_REASON reason, } log::debug( - "Disconnection complete device:{} name:{} state:{} reason:{} " - "sec_req:{:x}", - p_dev_rec->bd_addr, reinterpret_cast(p_dev_rec->sec_bd_name), - tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state), - hci_reason_code_text(reason), p_dev_rec->sec_rec.security_required); + "Disconnection complete device:{} name:{} state:{} reason:{} " + "sec_req:{:x}", + p_dev_rec->bd_addr, reinterpret_cast(p_dev_rec->sec_bd_name), + tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state), hci_reason_code_text(reason), + p_dev_rec->sec_rec.security_required); // TODO Should this be gated by the transport check below ? - btm_ble_update_mode_operation(HCI_ROLE_UNKNOWN, &p_dev_rec->bd_addr, - HCI_SUCCESS); + btm_ble_update_mode_operation(HCI_ROLE_UNKNOWN, &p_dev_rec->bd_addr, HCI_SUCCESS); /* see sec_flags processing in btm_acl_removed */ if (transport == BT_TRANSPORT_LE) { p_dev_rec->ble_hci_handle = HCI_INVALID_HANDLE; p_dev_rec->sec_rec.sec_flags &= - ~(BTM_SEC_LE_AUTHENTICATED | BTM_SEC_LE_ENCRYPTED | - BTM_SEC_ROLE_SWITCHED); + ~(BTM_SEC_LE_AUTHENTICATED | BTM_SEC_LE_ENCRYPTED | BTM_SEC_ROLE_SWITCHED); p_dev_rec->sec_rec.enc_key_size = 0; p_dev_rec->suggested_tx_octets = 0; if ((p_dev_rec->sec_rec.sec_flags & BTM_SEC_LE_LINK_KEY_KNOWN) == 0) { - p_dev_rec->sec_rec.sec_flags &= - ~(BTM_SEC_LE_LINK_KEY_AUTHED | BTM_SEC_LE_AUTHENTICATED); + p_dev_rec->sec_rec.sec_flags &= ~(BTM_SEC_LE_LINK_KEY_AUTHED | BTM_SEC_LE_AUTHENTICATED); } } else { p_dev_rec->hci_handle = HCI_INVALID_HANDLE; - p_dev_rec->sec_rec.sec_flags &= - ~(BTM_SEC_AUTHENTICATED | BTM_SEC_ENCRYPTED | BTM_SEC_ROLE_SWITCHED | - BTM_SEC_16_DIGIT_PIN_AUTHED); + p_dev_rec->sec_rec.sec_flags &= ~(BTM_SEC_AUTHENTICATED | BTM_SEC_ENCRYPTED | + BTM_SEC_ROLE_SWITCHED | BTM_SEC_16_DIGIT_PIN_AUTHED); // Remove temporary key. - if (p_dev_rec->sec_rec.bond_type == BOND_TYPE_TEMPORARY) + if (p_dev_rec->sec_rec.bond_type == BOND_TYPE_TEMPORARY) { p_dev_rec->sec_rec.sec_flags &= ~(BTM_SEC_LINK_KEY_KNOWN); + } } /* Some devices hardcode sample LTK value from spec, instead of generating @@ -3952,8 +3812,7 @@ void btm_sec_disconnected(uint16_t handle, tHCI_REASON reason, * disconnection. */ if (is_sample_ltk(p_dev_rec->sec_rec.ble_keys.pltk)) { - log::info("removing bond to device that used sample LTK: {}", - p_dev_rec->bd_addr); + log::info("removing bond to device that used sample LTK: {}", p_dev_rec->bd_addr); bta_dm_remove_device(p_dev_rec->bd_addr); return; @@ -3968,11 +3827,9 @@ void btm_sec_disconnected(uint16_t handle, tHCI_REASON reason, return; } - if (com::android::bluetooth::flags:: - cancel_pairing_only_on_disconnected_transport()) { + if (com::android::bluetooth::flags::cancel_pairing_only_on_disconnected_transport()) { if (btm_sec_cb.pairing_state != BTM_PAIR_STATE_IDLE && - btm_sec_cb.pairing_bda == p_dev_rec->bd_addr && - !pairing_transport_matches) { + btm_sec_cb.pairing_bda == p_dev_rec->bd_addr && !pairing_transport_matches) { log::debug("Disconnection on the other transport while pairing"); return; } @@ -3986,8 +3843,7 @@ void btm_sec_disconnected(uint16_t handle, tHCI_REASON reason, if ((p_dev_rec->sec_rec.sec_state == tSECURITY_STATE::AUTHENTICATING || p_dev_rec->sec_rec.sec_state == tSECURITY_STATE::ENCRYPTING) && transport != BT_TRANSPORT_BR_EDR) { - log::debug( - "Disconnection on the other transport while encrypting BR/EDR"); + log::debug("Disconnection on the other transport while encrypting BR/EDR"); return; } } @@ -4000,15 +3856,13 @@ void btm_sec_disconnected(uint16_t handle, tHCI_REASON reason, /* when the peer device time out the authentication before we do, this call back must be reset here */ p_dev_rec->sec_rec.p_callback = nullptr; - (*p_callback)(p_dev_rec->bd_addr, transport, p_dev_rec->sec_rec.p_ref_data, - BTM_ERR_PROCESSING); - log::debug("Cleaned up pending security state device:{} transport:{}", - p_dev_rec->bd_addr, bt_transport_text(transport)); + (*p_callback)(p_dev_rec->bd_addr, transport, p_dev_rec->sec_rec.p_ref_data, BTM_ERR_PROCESSING); + log::debug("Cleaned up pending security state device:{} transport:{}", p_dev_rec->bd_addr, + bt_transport_text(transport)); } } -void btm_sec_role_changed(tHCI_STATUS hci_status, const RawAddress& bd_addr, - tHCI_ROLE new_role) { +void btm_sec_role_changed(tHCI_STATUS hci_status, const RawAddress& bd_addr, tHCI_ROLE new_role) { tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr); if (p_dev_rec == nullptr || hci_status != HCI_SUCCESS) { @@ -4016,13 +3870,12 @@ void btm_sec_role_changed(tHCI_STATUS hci_status, const RawAddress& bd_addr, } if (new_role == HCI_ROLE_CENTRAL && btm_dev_authenticated(p_dev_rec) && !btm_dev_encrypted(p_dev_rec)) { - BTM_SetEncryption(p_dev_rec->bd_addr, BT_TRANSPORT_BR_EDR, NULL, NULL, - BTM_BLE_SEC_NONE); + BTM_SetEncryption(p_dev_rec->bd_addr, BT_TRANSPORT_BR_EDR, NULL, NULL, BTM_BLE_SEC_NONE); } } -static void read_encryption_key_size_complete_after_key_refresh( - uint8_t status, uint16_t handle, uint8_t key_size) { +static void read_encryption_key_size_complete_after_key_refresh(uint8_t status, uint16_t handle, + uint8_t key_size) { if (status == HCI_ERR_INSUFFCIENT_SECURITY) { /* If remote device stop the encryption before we call "Read Encryption Key * Size", we might receive Insufficient Security, which means that link is @@ -4033,15 +3886,13 @@ static void read_encryption_key_size_complete_after_key_refresh( if (status != HCI_SUCCESS) { log::info("disconnecting, status: 0x{:x}", status); - acl_disconnect_from_handle(handle, HCI_ERR_PEER_USER, - "stack::btu_hcif Key size fail"); + acl_disconnect_from_handle(handle, HCI_ERR_PEER_USER, "stack::btu_hcif Key size fail"); return; } if (key_size < MIN_KEY_SIZE) { - log::error( - "encryption key too short, disconnecting. handle: 0x{:x} key_size {}", - handle, key_size); + log::error("encryption key too short, disconnecting. handle: 0x{:x} key_size {}", handle, + key_size); acl_disconnect_from_handle(handle, HCI_ERR_HOST_REJECT_SECURITY, "stack::btu::btu_hcif::read_encryption_key_size_" @@ -4049,28 +3900,25 @@ static void read_encryption_key_size_complete_after_key_refresh( return; } - btm_sec_encrypt_change(handle, static_cast(status), - 1 /* enc_enable */); + btm_sec_encrypt_change(handle, static_cast(status), 1 /* enc_enable */); } -void btm_sec_encryption_key_refresh_complete(uint16_t handle, - tHCI_STATUS status) { +void btm_sec_encryption_key_refresh_complete(uint16_t handle, tHCI_STATUS status) { if (status != HCI_SUCCESS || BTM_IsBleConnection(handle) || // Skip encryption key size check when using set_min_encryption_key_size bluetooth::shim::GetController()->IsSupported( - bluetooth::hci::OpCode::SET_MIN_ENCRYPTION_KEY_SIZE)) { + bluetooth::hci::OpCode::SET_MIN_ENCRYPTION_KEY_SIZE)) { btm_sec_encrypt_change(handle, static_cast(status), (status == HCI_SUCCESS) ? 1 : 0); } else { btsnd_hcic_read_encryption_key_size( - handle, - base::Bind(&read_encryption_key_size_complete_after_key_refresh)); + handle, base::Bind(&read_encryption_key_size_complete_after_key_refresh)); } } /** This function is called when a new connection link key is generated */ -void btm_sec_link_key_notification(const RawAddress& p_bda, - const Octet16& link_key, uint8_t key_type) { +void btm_sec_link_key_notification(const RawAddress& p_bda, const Octet16& link_key, + uint8_t key_type) { tBTM_SEC_DEV_REC* p_dev_rec = btm_find_or_alloc_dev(p_bda); bool we_are_bonding = false; bool ltk_derived_lk = false; @@ -4078,16 +3926,16 @@ void btm_sec_link_key_notification(const RawAddress& p_bda, log::debug("New link key generated device:{} key_type:{}", p_bda, key_type); if ((key_type >= BTM_LTK_DERIVED_LKEY_OFFSET + BTM_LKEY_TYPE_COMBINATION) && - (key_type <= - BTM_LTK_DERIVED_LKEY_OFFSET + BTM_LKEY_TYPE_AUTH_COMB_P_256)) { + (key_type <= BTM_LTK_DERIVED_LKEY_OFFSET + BTM_LKEY_TYPE_AUTH_COMB_P_256)) { ltk_derived_lk = true; key_type -= BTM_LTK_DERIVED_LKEY_OFFSET; } /* If connection was made to do bonding restore link security if changed */ btm_restore_mode(); - if (key_type != BTM_LKEY_TYPE_CHANGED_COMB) + if (key_type != BTM_LKEY_TYPE_CHANGED_COMB) { p_dev_rec->sec_rec.link_key_type = key_type; + } p_dev_rec->sec_rec.sec_flags |= BTM_SEC_LINK_KEY_KNOWN; @@ -4106,35 +3954,32 @@ void btm_sec_link_key_notification(const RawAddress& p_bda, p_dev_rec->sec_rec.enc_key_size = 16; p_dev_rec->sec_rec.link_key = link_key; - if ((btm_sec_cb.pairing_state != BTM_PAIR_STATE_IDLE) && - (btm_sec_cb.pairing_bda == p_bda)) { - if (btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD) + if ((btm_sec_cb.pairing_state != BTM_PAIR_STATE_IDLE) && (btm_sec_cb.pairing_bda == p_bda)) { + if (btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD) { we_are_bonding = true; - else + } else { btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_IDLE); + } } /* save LTK derived LK no matter what */ if (ltk_derived_lk) { if (btm_sec_cb.api.p_link_key_callback) { - log::verbose("Save LTK derived LK (key_type = {})", - p_dev_rec->sec_rec.link_key_type); - (*btm_sec_cb.api.p_link_key_callback)( - p_bda, p_dev_rec->dev_class, p_dev_rec->sec_bd_name, link_key, - p_dev_rec->sec_rec.link_key_type, true /* is_ctkd */); + log::verbose("Save LTK derived LK (key_type = {})", p_dev_rec->sec_rec.link_key_type); + (*btm_sec_cb.api.p_link_key_callback)(p_bda, p_dev_rec->dev_class, p_dev_rec->sec_bd_name, + link_key, p_dev_rec->sec_rec.link_key_type, + true /* is_ctkd */); } } else { if ((p_dev_rec->sec_rec.link_key_type == BTM_LKEY_TYPE_UNAUTH_COMB_P_256) || (p_dev_rec->sec_rec.link_key_type == BTM_LKEY_TYPE_AUTH_COMB_P_256)) { p_dev_rec->sec_rec.new_encryption_key_is_p256 = true; - log::verbose("set new_encr_key_256 to {}", - p_dev_rec->sec_rec.new_encryption_key_is_p256); + log::verbose("set new_encr_key_256 to {}", p_dev_rec->sec_rec.new_encryption_key_is_p256); } } if (p_dev_rec->sec_rec.is_bond_type_persistent() && - (p_dev_rec->is_device_type_br_edr() || - p_dev_rec->is_device_type_dual_mode())) { + (p_dev_rec->is_device_type_br_edr() || p_dev_rec->is_device_type_dual_mode())) { btm_sec_store_device_sc_support(p_dev_rec->get_br_edr_hci_handle(), p_dev_rec->SupportsSecureConnections()); } @@ -4144,8 +3989,7 @@ void btm_sec_link_key_notification(const RawAddress& p_bda, /* resolved. Unless it is a HID Device and we really need to send all link * keys. */ if ((!(p_dev_rec->sec_rec.sec_flags & BTM_SEC_NAME_KNOWN) && - ((p_dev_rec->dev_class[1] & BTM_COD_MAJOR_CLASS_MASK) != - BTM_COD_MAJOR_PERIPHERAL)) && + ((p_dev_rec->dev_class[1] & BTM_COD_MAJOR_CLASS_MASK) != BTM_COD_MAJOR_PERIPHERAL)) && !ltk_derived_lk) { log::verbose("Delayed BDA: {}, Type: {}", p_bda, key_type); @@ -4173,13 +4017,13 @@ void btm_sec_link_key_notification(const RawAddress& p_bda, if (btm_sec_cb.api.p_link_key_callback) { if (ltk_derived_lk) { log::verbose( - "btm_sec_link_key_notification() LTK derived LK is saved already " - "(key_type = {})", - p_dev_rec->sec_rec.link_key_type); + "btm_sec_link_key_notification() LTK derived LK is saved already " + "(key_type = {})", + p_dev_rec->sec_rec.link_key_type); } else { - (*btm_sec_cb.api.p_link_key_callback)( - p_bda, p_dev_rec->dev_class, p_dev_rec->sec_bd_name, link_key, - p_dev_rec->sec_rec.link_key_type, false /* is_ctkd */); + (*btm_sec_cb.api.p_link_key_callback)(p_bda, p_dev_rec->dev_class, p_dev_rec->sec_bd_name, + link_key, p_dev_rec->sec_rec.link_key_type, + false /* is_ctkd */); } } } @@ -4203,12 +4047,11 @@ void btm_sec_link_key_request(const RawAddress bda) { } if ((btm_sec_cb.pairing_state == BTM_PAIR_STATE_WAIT_PIN_REQ) && - (btm_sec_cb.collision_start_time != 0) && - (btm_sec_cb.p_collided_dev_rec->bd_addr == bda)) { + (btm_sec_cb.collision_start_time != 0) && (btm_sec_cb.p_collided_dev_rec->bd_addr == bda)) { log::verbose( - "btm_sec_link_key_request() rejecting link key req State: {} " - "START_TIMEOUT : {}", - btm_sec_cb.pairing_state, btm_sec_cb.collision_start_time); + "btm_sec_link_key_request() rejecting link key req State: {} " + "START_TIMEOUT : {}", + btm_sec_cb.pairing_state, btm_sec_cb.collision_start_time); btsnd_hcic_link_key_neg_reply(bda); return; } @@ -4237,15 +4080,13 @@ void btm_sec_link_key_request(const RawAddress bda) { static void btm_sec_pairing_timeout(void* /* data */) { tBTM_SEC_CB* p_cb = &btm_sec_cb; tBTM_SEC_DEV_REC* p_dev_rec; - tBTM_AUTH_REQ auth_req = (btm_sec_cb.devcb.loc_io_caps == BTM_IO_CAP_NONE) - ? BTM_AUTH_AP_NO - : BTM_AUTH_AP_YES; + tBTM_AUTH_REQ auth_req = + (btm_sec_cb.devcb.loc_io_caps == BTM_IO_CAP_NONE) ? BTM_AUTH_AP_NO : BTM_AUTH_AP_YES; BD_NAME name; p_dev_rec = btm_find_dev(p_cb->pairing_bda); - log::verbose("State: {} Flags: {}", - tBTM_SEC_CB::btm_pair_state_descr(p_cb->pairing_state), + log::verbose("State: {} Flags: {}", tBTM_SEC_CB::btm_pair_state_descr(p_cb->pairing_state), p_cb->pairing_flags); switch (p_cb->pairing_state) { @@ -4254,17 +4095,19 @@ static void btm_sec_pairing_timeout(void* /* data */) { break; case BTM_PAIR_STATE_WAIT_LOCAL_PIN: - if ((btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_PRE_FETCH_PIN) == 0) + if ((btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_PRE_FETCH_PIN) == 0) { btsnd_hcic_pin_code_neg_reply(p_cb->pairing_bda); + } btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_IDLE); /* We need to notify the UI that no longer need the PIN */ if (btm_sec_cb.api.p_auth_complete_callback) { if (p_dev_rec == NULL) { name[0] = 0; - (*btm_sec_cb.api.p_auth_complete_callback)( - p_cb->pairing_bda, kDevClassEmpty, name, HCI_ERR_CONNECTION_TOUT); - } else + (*btm_sec_cb.api.p_auth_complete_callback)(p_cb->pairing_bda, kDevClassEmpty, name, + HCI_ERR_CONNECTION_TOUT); + } else { NotifyBondingChange(*p_dev_rec, HCI_ERR_CONNECTION_TOUT); + } } break; @@ -4283,8 +4126,7 @@ static void btm_sec_pairing_timeout(void* /* data */) { case BTM_PAIR_STATE_WAIT_LOCAL_IOCAPS: // TODO(optedoblivion): Inject OOB_DATA_PRESENT Flag - btsnd_hcic_io_cap_req_reply(p_cb->pairing_bda, - btm_sec_cb.devcb.loc_io_caps, BTM_OOB_NONE, + btsnd_hcic_io_cap_req_reply(p_cb->pairing_bda, btm_sec_cb.devcb.loc_io_caps, BTM_OOB_NONE, auth_req); btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_IDLE); break; @@ -4299,13 +4141,11 @@ static void btm_sec_pairing_timeout(void* /* data */) { * complete. * now it's time to tear down the ACL link*/ if (p_dev_rec == NULL) { - log::error("BTM_PAIR_STATE_WAIT_DISCONNECT unknown BDA: {}", - p_cb->pairing_bda); + log::error("BTM_PAIR_STATE_WAIT_DISCONNECT unknown BDA: {}", p_cb->pairing_bda); break; } - btm_sec_send_hci_disconnect( - p_dev_rec, HCI_ERR_AUTH_FAILURE, p_dev_rec->hci_handle, - "stack::btm::btm_sec::btm_sec_pairing_timeout"); + btm_sec_send_hci_disconnect(p_dev_rec, HCI_ERR_AUTH_FAILURE, p_dev_rec->hci_handle, + "stack::btm::btm_sec::btm_sec_pairing_timeout"); btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_IDLE); break; @@ -4317,8 +4157,8 @@ static void btm_sec_pairing_timeout(void* /* data */) { if (btm_sec_cb.api.p_auth_complete_callback) { if (p_dev_rec == NULL) { name[0] = 0; - (*btm_sec_cb.api.p_auth_complete_callback)( - p_cb->pairing_bda, kDevClassEmpty, name, HCI_ERR_CONNECTION_TOUT); + (*btm_sec_cb.api.p_auth_complete_callback)(p_cb->pairing_bda, kDevClassEmpty, name, + HCI_ERR_CONNECTION_TOUT); } else { NotifyBondingChange(*p_dev_rec, HCI_ERR_CONNECTION_TOUT); } @@ -4353,8 +4193,8 @@ void btm_sec_pin_code_request(const RawAddress p_bda) { log::debug("Controller requests PIN code device:{} state:{}", p_bda, tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state)); - RawAddress local_bd_addr = bluetooth::ToRawAddress( - bluetooth::shim::GetController()->GetMacAddress()); + RawAddress local_bd_addr = + bluetooth::ToRawAddress(bluetooth::shim::GetController()->GetMacAddress()); if (p_bda == local_bd_addr) { btsnd_hcic_pin_code_neg_reply(p_bda); return; @@ -4387,8 +4227,7 @@ void btm_sec_pin_code_request(const RawAddress p_bda) { if (!p_cb->pairing_disabled && (p_cb->cfg.pin_type == HCI_PIN_TYPE_FIXED)) { log::verbose("btm_sec_pin_code_request fixed pin replying"); btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_WAIT_AUTH_COMPLETE); - btsnd_hcic_pin_code_req_reply(p_bda, p_cb->cfg.pin_code_len, - p_cb->cfg.pin_code); + btsnd_hcic_pin_code_req_reply(p_bda, p_cb->cfg.pin_code_len, p_cb->cfg.pin_code); return; } @@ -4402,8 +4241,7 @@ void btm_sec_pin_code_request(const RawAddress p_bda) { /* We could have started connection after asking user for the PIN code */ if (btm_sec_cb.pin_code_len != 0) { log::verbose("btm_sec_pin_code_request bonding sending reply"); - btsnd_hcic_pin_code_req_reply(p_bda, btm_sec_cb.pin_code_len, - p_cb->pin_code); + btsnd_hcic_pin_code_req_reply(p_bda, btm_sec_cb.pin_code_len, p_cb->pin_code); /* Mark that we forwarded received from the user PIN code */ btm_sec_cb.pin_code_len = 0; @@ -4428,14 +4266,12 @@ void btm_sec_pin_code_request(const RawAddress p_bda) { be originator */ /* for keyboard bonding */ || (!p_dev_rec->IsLocallyInitiated() && - ((p_dev_rec->dev_class[1] & BTM_COD_MAJOR_CLASS_MASK) == - BTM_COD_MAJOR_PERIPHERAL) && + ((p_dev_rec->dev_class[1] & BTM_COD_MAJOR_CLASS_MASK) == BTM_COD_MAJOR_PERIPHERAL) && (p_dev_rec->dev_class[2] & BTM_COD_MINOR_KEYBOARD))) { log::warn( - "btm_sec_pin_code_request(): Pairing disabled:{}; PIN callback:{}, Dev " - "Rec:{}!", - p_cb->pairing_disabled, fmt::ptr(p_cb->api.p_pin_callback), - fmt::ptr(p_dev_rec)); + "btm_sec_pin_code_request(): Pairing disabled:{}; PIN callback:{}, Dev " + "Rec:{}!", + p_cb->pairing_disabled, fmt::ptr(p_cb->api.p_pin_callback), fmt::ptr(p_dev_rec)); btsnd_hcic_pin_code_neg_reply(p_bda); } @@ -4457,10 +4293,9 @@ void btm_sec_pin_code_request(const RawAddress p_bda) { btm_sec_cb.pairing_flags |= BTM_PAIR_FLAGS_PIN_REQD; if (p_cb->api.p_pin_callback) { - (*p_cb->api.p_pin_callback)( - p_bda, p_dev_rec->dev_class, p_dev_rec->sec_bd_name, - (p_dev_rec->sec_rec.required_security_flags_for_pairing & - BTM_SEC_IN_MIN_16_DIGIT_PIN)); + (*p_cb->api.p_pin_callback)(p_bda, p_dev_rec->dev_class, p_dev_rec->sec_bd_name, + (p_dev_rec->sec_rec.required_security_flags_for_pairing & + BTM_SEC_IN_MIN_16_DIGIT_PIN)); } } else { log::verbose("btm_sec_pin_code_request going for remote name"); @@ -4468,8 +4303,7 @@ void btm_sec_pin_code_request(const RawAddress p_bda) { /* We received PIN code request for the device with unknown name */ /* it is not user friendly just to ask for the PIN without name */ /* try to get name at first */ - bluetooth::shim::ACL_RemoteNameRequest(p_dev_rec->bd_addr, - HCI_PAGE_SCAN_REP_MODE_R1, + bluetooth::shim::ACL_RemoteNameRequest(p_dev_rec->bd_addr, HCI_PAGE_SCAN_REP_MODE_R1, HCI_MANDATARY_PAGE_SCAN_MODE, 0); } } @@ -4491,12 +4325,16 @@ void btm_sec_update_clock_offset(uint16_t handle, uint16_t clock_offset) { tBTM_INQ_INFO* p_inq_info; p_dev_rec = btm_find_dev_by_handle(handle); - if (p_dev_rec == NULL) return; + if (p_dev_rec == NULL) { + return; + } p_dev_rec->clock_offset = clock_offset | BTM_CLOCK_OFFSET_VALID; p_inq_info = BTM_InqDbRead(p_dev_rec->bd_addr); - if (p_inq_info == NULL) return; + if (p_inq_info == NULL) { + return; + } p_inq_info->results.clock_offset = clock_offset | BTM_CLOCK_OFFSET_VALID; } @@ -4522,18 +4360,16 @@ void btm_sec_update_clock_offset(uint16_t handle, uint16_t clock_offset) { ******************************************************************************/ tBTM_STATUS btm_sec_execute_procedure(tBTM_SEC_DEV_REC* p_dev_rec) { log::assert_that(p_dev_rec != nullptr, "assert failed: p_dev_rec != nullptr"); - log::debug( - "security_required:0x{:x} security_flags:0x{:x} security_state:{}[{}]", - p_dev_rec->sec_rec.security_required, p_dev_rec->sec_rec.sec_flags, - security_state_text( - static_cast(p_dev_rec->sec_rec.sec_state)), - p_dev_rec->sec_rec.sec_state); + log::debug("security_required:0x{:x} security_flags:0x{:x} security_state:{}[{}]", + p_dev_rec->sec_rec.security_required, p_dev_rec->sec_rec.sec_flags, + security_state_text(static_cast(p_dev_rec->sec_rec.sec_state)), + p_dev_rec->sec_rec.sec_state); if (p_dev_rec->sec_rec.sec_state != tSECURITY_STATE::IDLE && p_dev_rec->sec_rec.sec_state != tSECURITY_STATE::LE_ENCRYPTING) { log::info("No immediate action taken in busy state: {}", security_state_text(p_dev_rec->sec_rec.sec_state)); - return (BTM_CMD_STARTED); + return BTM_CMD_STARTED; } /* If any security is required, get the name first */ @@ -4542,9 +4378,9 @@ tBTM_STATUS btm_sec_execute_procedure(tBTM_SEC_DEV_REC* p_dev_rec) { log::debug("Security Manager: Start get name"); if (!btm_sec_start_get_name(p_dev_rec)) { log::warn("Unable to start remote name request"); - return (BTM_NO_RESOURCES); + return BTM_NO_RESOURCES; } - return (BTM_CMD_STARTED); + return BTM_CMD_STARTED; } /* If connection is not authenticated and authentication is required */ @@ -4561,8 +4397,7 @@ tBTM_STATUS btm_sec_execute_procedure(tBTM_SEC_DEV_REC* p_dev_rec) { start_auth = true; } } else { - if (p_dev_rec->sec_rec.security_required & - (BTM_SEC_IN_AUTHENTICATE | BTM_SEC_IN_ENCRYPT)) { + if (p_dev_rec->sec_rec.security_required & (BTM_SEC_IN_AUTHENTICATE | BTM_SEC_IN_ENCRYPT)) { log::debug("Incoming authentication/encryption Required"); start_auth = true; } @@ -4577,8 +4412,7 @@ tBTM_STATUS btm_sec_execute_procedure(tBTM_SEC_DEV_REC* p_dev_rec) { * authenticated connections, hence we cannot distinguish here. */ if (!p_dev_rec->IsLocallyInitiated()) { - if (p_dev_rec->sec_rec.security_required & - BTM_SEC_IN_MIN_16_DIGIT_PIN) { + if (p_dev_rec->sec_rec.security_required & BTM_SEC_IN_MIN_16_DIGIT_PIN) { log::debug("BTM_SEC_IN_MIN_16_DIGIT_PIN Required"); start_auth = true; } @@ -4602,15 +4436,13 @@ tBTM_STATUS btm_sec_execute_procedure(tBTM_SEC_DEV_REC* p_dev_rec) { if ((p_dev_rec->sec_rec.sec_flags & BTM_SEC_LINK_KEY_KNOWN) && (!(p_dev_rec->sec_rec.sec_flags & BTM_SEC_16_DIGIT_PIN_AUTHED) && (!p_dev_rec->IsLocallyInitiated() && - (p_dev_rec->sec_rec.security_required & - BTM_SEC_IN_MIN_16_DIGIT_PIN)))) { + (p_dev_rec->sec_rec.security_required & BTM_SEC_IN_MIN_16_DIGIT_PIN)))) { p_dev_rec->sec_rec.sec_flags &= - ~(BTM_SEC_LINK_KEY_KNOWN | BTM_SEC_LINK_KEY_AUTHED | - BTM_SEC_AUTHENTICATED); + ~(BTM_SEC_LINK_KEY_KNOWN | BTM_SEC_LINK_KEY_AUTHED | BTM_SEC_AUTHENTICATED); } btm_sec_wait_and_start_authentication(p_dev_rec); - return (BTM_CMD_STARTED); + return BTM_CMD_STARTED; } } @@ -4626,7 +4458,7 @@ tBTM_STATUS btm_sec_execute_procedure(tBTM_SEC_DEV_REC* p_dev_rec) { btsnd_hcic_set_conn_encrypt(p_dev_rec->hci_handle, true); p_dev_rec->sec_rec.sec_state = tSECURITY_STATE::ENCRYPTING; - return (BTM_CMD_STARTED); + return BTM_CMD_STARTED; } else { log::debug("Encryption not required"); } @@ -4634,28 +4466,25 @@ tBTM_STATUS btm_sec_execute_procedure(tBTM_SEC_DEV_REC* p_dev_rec) { if ((p_dev_rec->sec_rec.security_required & BTM_SEC_MODE4_LEVEL4) && (p_dev_rec->sec_rec.link_key_type != BTM_LKEY_TYPE_AUTH_COMB_P_256)) { log::verbose( - "Security Manager: SC only service, but link key type is 0x{:02x} " - "-security failure", - p_dev_rec->sec_rec.link_key_type); - return (BTM_FAILED_ON_SECURITY); + "Security Manager: SC only service, but link key type is 0x{:02x} " + "-security failure", + p_dev_rec->sec_rec.link_key_type); + return BTM_FAILED_ON_SECURITY; } - if (access_secure_service_from_temp_bond( - p_dev_rec, p_dev_rec->IsLocallyInitiated(), - p_dev_rec->sec_rec.security_required)) { - log::error( - "Trying to access a secure service from a temp bonding, rejecting"); - return (BTM_FAILED_ON_SECURITY); + if (access_secure_service_from_temp_bond(p_dev_rec, p_dev_rec->IsLocallyInitiated(), + p_dev_rec->sec_rec.security_required)) { + log::error("Trying to access a secure service from a temp bonding, rejecting"); + return BTM_FAILED_ON_SECURITY; } /* All required security procedures already established */ - p_dev_rec->sec_rec.security_required &= - ~(BTM_SEC_OUT_AUTHENTICATE | BTM_SEC_IN_AUTHENTICATE | - BTM_SEC_OUT_ENCRYPT | BTM_SEC_IN_ENCRYPT); + p_dev_rec->sec_rec.security_required &= ~(BTM_SEC_OUT_AUTHENTICATE | BTM_SEC_IN_AUTHENTICATE | + BTM_SEC_OUT_ENCRYPT | BTM_SEC_IN_ENCRYPT); log::verbose("Security Manager: access granted"); - return (BTM_SUCCESS); + return BTM_SUCCESS; } /******************************************************************************* @@ -4676,8 +4505,7 @@ static bool btm_sec_start_get_name(tBTM_SEC_DEV_REC* p_dev_rec) { /* 0 and NULL are as timeout and callback params because they are not used in * security get name case */ - bluetooth::shim::ACL_RemoteNameRequest(p_dev_rec->bd_addr, - HCI_PAGE_SCAN_REP_MODE_R1, + bluetooth::shim::ACL_RemoteNameRequest(p_dev_rec->bd_addr, HCI_PAGE_SCAN_REP_MODE_R1, HCI_MANDATARY_PAGE_SCAN_MODE, 0); return true; } @@ -4692,8 +4520,7 @@ static bool btm_sec_start_get_name(tBTM_SEC_DEV_REC* p_dev_rec) { ******************************************************************************/ static void btm_sec_wait_and_start_authentication(tBTM_SEC_DEV_REC* p_dev_rec) { auto addr = new RawAddress(p_dev_rec->bd_addr); - int32_t delay_auth = - osi_property_get_int32("bluetooth.btm.sec.delay_auth_ms.value", 0); + int32_t delay_auth = osi_property_get_int32("bluetooth.btm.sec.delay_auth_ms.value", 0); /* Overwrite the system-wide authentication delay if device-specific * interoperability delay is needed. */ @@ -4701,9 +4528,9 @@ static void btm_sec_wait_and_start_authentication(tBTM_SEC_DEV_REC* p_dev_rec) { delay_auth = BTM_SEC_START_AUTH_DELAY; } - bt_status_t status = do_in_main_thread_delayed( - FROM_HERE, base::Bind(&btm_sec_auth_timer_timeout, addr), - std::chrono::milliseconds(delay_auth)); + bt_status_t status = + do_in_main_thread_delayed(FROM_HERE, base::Bind(&btm_sec_auth_timer_timeout, addr), + std::chrono::milliseconds(delay_auth)); if (status != BT_STATUS_SUCCESS) { log::error("do_in_main_thread_delayed failed. directly calling"); btm_sec_auth_timer_timeout(addr); @@ -4727,8 +4554,7 @@ static void btm_sec_auth_timer_timeout(void* data) { log::info("device is already authenticated"); if (p_dev_rec->sec_rec.p_callback) { (*p_dev_rec->sec_rec.p_callback)(p_dev_rec->bd_addr, BT_TRANSPORT_BR_EDR, - p_dev_rec->sec_rec.p_ref_data, - BTM_SUCCESS); + p_dev_rec->sec_rec.p_ref_data, BTM_SUCCESS); } } else if (p_dev_rec->sec_rec.sec_state == tSECURITY_STATE::AUTHENTICATING) { log::info("device is in the process of authenticating"); @@ -4772,10 +4598,11 @@ static void btm_sec_collision_timeout(void* /* data */) { * ******************************************************************************/ static void btm_send_link_key_notif(tBTM_SEC_DEV_REC* p_dev_rec) { - if (btm_sec_cb.api.p_link_key_callback) - (*btm_sec_cb.api.p_link_key_callback)( - p_dev_rec->bd_addr, p_dev_rec->dev_class, p_dev_rec->sec_bd_name, - p_dev_rec->sec_rec.link_key, p_dev_rec->sec_rec.link_key_type, false); + if (btm_sec_cb.api.p_link_key_callback) { + (*btm_sec_cb.api.p_link_key_callback)(p_dev_rec->bd_addr, p_dev_rec->dev_class, + p_dev_rec->sec_bd_name, p_dev_rec->sec_rec.link_key, + p_dev_rec->sec_rec.link_key_type, false); + } } /******************************************************************************* @@ -4816,11 +4643,9 @@ void tBTM_SEC_CB::change_pairing_state(tBTM_PAIRING_STATE new_state) { tBTM_SEC_CB::btm_pair_state_descr(new_state), pairing_flags); if (pairing_state != new_state) { - BTM_LogHistory( - kBtmLogTag, btm_sec_cb.pairing_bda, "Pairing state changed", - base::StringPrintf("%s => %s", - tBTM_SEC_CB::btm_pair_state_descr(pairing_state), - tBTM_SEC_CB::btm_pair_state_descr(new_state))); + BTM_LogHistory(kBtmLogTag, btm_sec_cb.pairing_bda, "Pairing state changed", + base::StringPrintf("%s => %s", tBTM_SEC_CB::btm_pair_state_descr(pairing_state), + tBTM_SEC_CB::btm_pair_state_descr(new_state))); } pairing_state = new_state; @@ -4839,8 +4664,9 @@ void tBTM_SEC_CB::change_pairing_state(tBTM_PAIRING_STATE new_state) { pairing_bda = RawAddress::kAny; } else { /* If transitioning out of idle, mark the lcb as bonding */ - if (old_state == BTM_PAIR_STATE_IDLE) + if (old_state == BTM_PAIR_STATE_IDLE) { l2cu_update_lcb_4_bonding(pairing_bda, true); + } alarm_set_on_mloop(btm_sec_cb.pairing_timer, BTM_SEC_TIMEOUT_VALUE * 1000, btm_sec_pairing_timeout, NULL); @@ -4857,30 +4683,30 @@ void tBTM_SEC_CB::change_pairing_state(tBTM_PAIRING_STATE new_state) { const char* tBTM_SEC_CB::btm_pair_state_descr(tBTM_PAIRING_STATE state) { switch (state) { case BTM_PAIR_STATE_IDLE: - return ("IDLE"); + return "IDLE"; case BTM_PAIR_STATE_GET_REM_NAME: - return ("GET_REM_NAME"); + return "GET_REM_NAME"; case BTM_PAIR_STATE_WAIT_PIN_REQ: - return ("WAIT_PIN_REQ"); + return "WAIT_PIN_REQ"; case BTM_PAIR_STATE_WAIT_LOCAL_PIN: - return ("WAIT_LOCAL_PIN"); + return "WAIT_LOCAL_PIN"; case BTM_PAIR_STATE_WAIT_NUMERIC_CONFIRM: - return ("WAIT_NUM_CONFIRM"); + return "WAIT_NUM_CONFIRM"; case BTM_PAIR_STATE_KEY_ENTRY: - return ("KEY_ENTRY"); + return "KEY_ENTRY"; case BTM_PAIR_STATE_WAIT_LOCAL_OOB_RSP: - return ("WAIT_LOCAL_OOB_RSP"); + return "WAIT_LOCAL_OOB_RSP"; case BTM_PAIR_STATE_WAIT_LOCAL_IOCAPS: - return ("WAIT_LOCAL_IOCAPS"); + return "WAIT_LOCAL_IOCAPS"; case BTM_PAIR_STATE_INCOMING_SSP: - return ("INCOMING_SSP"); + return "INCOMING_SSP"; case BTM_PAIR_STATE_WAIT_AUTH_COMPLETE: - return ("WAIT_AUTH_COMPLETE"); + return "WAIT_AUTH_COMPLETE"; case BTM_PAIR_STATE_WAIT_DISCONNECT: - return ("WAIT_DISCONNECT"); + return "WAIT_DISCONNECT"; } - return ("???"); + return "???"; } /******************************************************************************* @@ -4893,8 +4719,8 @@ const char* tBTM_SEC_CB::btm_pair_state_descr(tBTM_PAIRING_STATE state) { * Parameters: void * ******************************************************************************/ -void btm_sec_dev_rec_cback_event(tBTM_SEC_DEV_REC* p_dev_rec, - tBTM_STATUS btm_status, bool is_le_transport) { +void btm_sec_dev_rec_cback_event(tBTM_SEC_DEV_REC* p_dev_rec, tBTM_STATUS btm_status, + bool is_le_transport) { log::assert_that(p_dev_rec != nullptr, "assert failed: p_dev_rec != nullptr"); log::debug("transport={}, btm_status={}", is_le_transport ? "le" : "classic", btm_status_text(btm_status)); @@ -4903,11 +4729,11 @@ void btm_sec_dev_rec_cback_event(tBTM_SEC_DEV_REC* p_dev_rec, p_dev_rec->sec_rec.p_callback = NULL; if (p_callback != nullptr) { if (is_le_transport) { - (*p_callback)(p_dev_rec->ble.pseudo_addr, BT_TRANSPORT_LE, - p_dev_rec->sec_rec.p_ref_data, btm_status); + (*p_callback)(p_dev_rec->ble.pseudo_addr, BT_TRANSPORT_LE, p_dev_rec->sec_rec.p_ref_data, + btm_status); } else { - (*p_callback)(p_dev_rec->bd_addr, BT_TRANSPORT_BR_EDR, - p_dev_rec->sec_rec.p_ref_data, btm_status); + (*p_callback)(p_dev_rec->bd_addr, BT_TRANSPORT_BR_EDR, p_dev_rec->sec_rec.p_ref_data, + btm_status); } } @@ -4917,7 +4743,7 @@ void btm_sec_dev_rec_cback_event(tBTM_SEC_DEV_REC* p_dev_rec, void btm_sec_cr_loc_oob_data_cback_event(const RawAddress& address, tSMP_LOC_OOB_DATA loc_oob_data) { tBTM_LE_EVT_DATA evt_data = { - .local_oob_data = loc_oob_data, + .local_oob_data = loc_oob_data, }; if (btm_sec_cb.api.p_le_callback) { (*btm_sec_cb.api.p_le_callback)(BTM_LE_SC_LOC_OOB_EVT, address, &evt_data); @@ -4931,12 +4757,10 @@ void btm_sec_cr_loc_oob_data_cback_event(const RawAddress& address, * Description Return state description for tracing * ******************************************************************************/ -static bool btm_sec_queue_mx_request(const RawAddress& bd_addr, uint16_t psm, - bool is_orig, uint16_t security_required, - tBTM_SEC_CALLBACK* p_callback, +static bool btm_sec_queue_mx_request(const RawAddress& bd_addr, uint16_t psm, bool is_orig, + uint16_t security_required, tBTM_SEC_CALLBACK* p_callback, void* p_ref_data) { - tBTM_SEC_QUEUE_ENTRY* p_e = - (tBTM_SEC_QUEUE_ENTRY*)osi_malloc(sizeof(tBTM_SEC_QUEUE_ENTRY)); + tBTM_SEC_QUEUE_ENTRY* p_e = (tBTM_SEC_QUEUE_ENTRY*)osi_malloc(sizeof(tBTM_SEC_QUEUE_ENTRY)); p_e->psm = psm; p_e->is_orig = is_orig; @@ -4947,8 +4771,8 @@ static bool btm_sec_queue_mx_request(const RawAddress& bd_addr, uint16_t psm, p_e->bd_addr = bd_addr; p_e->rfcomm_security_requirement = security_required; - log::verbose("PSM: 0x{:04x} Is_Orig: {} security_required: 0x{:x}", psm, - is_orig, security_required); + log::verbose("PSM: 0x{:04x} Is_Orig: {} security_required: 0x{:x}", psm, is_orig, + security_required); fixed_queue_enqueue(btm_sec_cb.sec_pending_q, p_e); @@ -4961,11 +4785,9 @@ static bool btm_sec_check_prefetch_pin(tBTM_SEC_DEV_REC* p_dev_rec) { bool rv = false; if ((major == BTM_COD_MAJOR_AUDIO) && - ((minor == BTM_COD_MINOR_CONFM_HANDSFREE) || - (minor == BTM_COD_MINOR_CAR_AUDIO))) { - log::verbose( - "Skipping pre-fetch PIN for carkit COD Major: 0x{:02x} Minor: 0x{:02x}", - major, minor); + ((minor == BTM_COD_MINOR_CONFM_HANDSFREE) || (minor == BTM_COD_MINOR_CAR_AUDIO))) { + log::verbose("Skipping pre-fetch PIN for carkit COD Major: 0x{:02x} Minor: 0x{:02x}", major, + minor); if (!btm_sec_cb.security_mode_changed) { btm_sec_cb.security_mode_changed = true; @@ -4983,12 +4805,13 @@ static bool btm_sec_check_prefetch_pin(tBTM_SEC_DEV_REC* p_dev_rec) { if (btm_sec_cb.api.p_pin_callback && ((btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_PIN_REQD) == 0)) { log::verbose("PIN code callback called"); - if (BTM_IsAclConnectionUp(p_dev_rec->bd_addr, BT_TRANSPORT_BR_EDR)) + if (BTM_IsAclConnectionUp(p_dev_rec->bd_addr, BT_TRANSPORT_BR_EDR)) { btm_sec_cb.pairing_flags |= BTM_PAIR_FLAGS_PIN_REQD; - (btm_sec_cb.api.p_pin_callback)( - p_dev_rec->bd_addr, p_dev_rec->dev_class, p_dev_rec->sec_bd_name, - (p_dev_rec->sec_rec.required_security_flags_for_pairing & - BTM_SEC_IN_MIN_16_DIGIT_PIN)); + } + (btm_sec_cb.api.p_pin_callback)(p_dev_rec->bd_addr, p_dev_rec->dev_class, + p_dev_rec->sec_bd_name, + (p_dev_rec->sec_rec.required_security_flags_for_pairing & + BTM_SEC_IN_MIN_16_DIGIT_PIN)); } } @@ -5006,13 +4829,10 @@ static bool btm_sec_check_prefetch_pin(tBTM_SEC_DEV_REC* p_dev_rec) { * process pending. * ******************************************************************************/ -static void btm_sec_queue_encrypt_request(const RawAddress& bd_addr, - tBT_TRANSPORT transport, - tBTM_SEC_CALLBACK* p_callback, - void* p_ref_data, +static void btm_sec_queue_encrypt_request(const RawAddress& bd_addr, tBT_TRANSPORT transport, + tBTM_SEC_CALLBACK* p_callback, void* p_ref_data, tBTM_BLE_SEC_ACT sec_act) { - tBTM_SEC_QUEUE_ENTRY* p_e = - (tBTM_SEC_QUEUE_ENTRY*)osi_malloc(sizeof(tBTM_SEC_QUEUE_ENTRY) + 1); + tBTM_SEC_QUEUE_ENTRY* p_e = (tBTM_SEC_QUEUE_ENTRY*)osi_malloc(sizeof(tBTM_SEC_QUEUE_ENTRY) + 1); p_e->psm = 0; /* if PSM 0, encryption request */ p_e->p_callback = p_callback; @@ -5033,10 +4853,11 @@ static void btm_sec_queue_encrypt_request(const RawAddress& bd_addr, * Returns void * ******************************************************************************/ -static void btm_sec_check_pending_enc_req(tBTM_SEC_DEV_REC* p_dev_rec, - tBT_TRANSPORT transport, +static void btm_sec_check_pending_enc_req(tBTM_SEC_DEV_REC* p_dev_rec, tBT_TRANSPORT transport, uint8_t encr_enable) { - if (fixed_queue_is_empty(btm_sec_cb.sec_pending_q)) return; + if (fixed_queue_is_empty(btm_sec_cb.sec_pending_q)) { + return; + } const tBTM_STATUS res = encr_enable ? BTM_SUCCESS : BTM_ERR_PROCESSING; list_t* list = fixed_queue_get_list(btm_sec_cb.sec_pending_q); @@ -5044,16 +4865,14 @@ static void btm_sec_check_pending_enc_req(tBTM_SEC_DEV_REC* p_dev_rec, tBTM_SEC_QUEUE_ENTRY* p_e = (tBTM_SEC_QUEUE_ENTRY*)list_node(node); node = list_next(node); - if (p_e->bd_addr == p_dev_rec->bd_addr && p_e->psm == 0 && - p_e->transport == transport) { + if (p_e->bd_addr == p_dev_rec->bd_addr && p_e->psm == 0 && p_e->transport == transport) { if (encr_enable == 0 || transport == BT_TRANSPORT_BR_EDR || - p_e->sec_act == BTM_BLE_SEC_ENCRYPT || - p_e->sec_act == BTM_BLE_SEC_ENCRYPT_NO_MITM || + p_e->sec_act == BTM_BLE_SEC_ENCRYPT || p_e->sec_act == BTM_BLE_SEC_ENCRYPT_NO_MITM || (p_e->sec_act == BTM_BLE_SEC_ENCRYPT_MITM && p_dev_rec->sec_rec.sec_flags & BTM_SEC_LE_AUTHENTICATED)) { - if (p_e->p_callback) - (*p_e->p_callback)(p_dev_rec->bd_addr, transport, p_e->p_ref_data, - res); + if (p_e->p_callback) { + (*p_e->p_callback)(p_dev_rec->bd_addr, transport, p_e->p_ref_data, res); + } fixed_queue_try_remove_from_queue(btm_sec_cb.sec_pending_q, (void*)p_e); osi_free(p_e); } @@ -5072,10 +4891,8 @@ static void btm_sec_check_pending_enc_req(tBTM_SEC_DEV_REC* p_dev_rec, * connections only mode. * ******************************************************************************/ -static uint16_t btm_sec_set_serv_level4_flags(uint16_t cur_security, - bool is_originator) { - uint16_t sec_level4_flags = - is_originator ? BTM_SEC_OUT_LEVEL4_FLAGS : BTM_SEC_IN_LEVEL4_FLAGS; +static uint16_t btm_sec_set_serv_level4_flags(uint16_t cur_security, bool is_originator) { + uint16_t sec_level4_flags = is_originator ? BTM_SEC_OUT_LEVEL4_FLAGS : BTM_SEC_IN_LEVEL4_FLAGS; return cur_security | sec_level4_flags; } @@ -5108,9 +4925,7 @@ void btm_sec_clear_ble_keys(tBTM_SEC_DEV_REC* p_dev_rec) { * Returns true - dev is bonded * ******************************************************************************/ -bool btm_sec_is_a_bonded_dev(const RawAddress& bda) { - return btm_sec_cb.IsDeviceBonded(bda); -} +bool btm_sec_is_a_bonded_dev(const RawAddress& bda) { return btm_sec_cb.IsDeviceBonded(bda); } /******************************************************************************* * @@ -5133,13 +4948,17 @@ static bool btm_sec_use_smp_br_chnl(tBTM_SEC_DEV_REC* p_dev_rec) { log::verbose("link_key_type = 0x{:x}", p_dev_rec->sec_rec.link_key_type); if ((p_dev_rec->sec_rec.link_key_type != BTM_LKEY_TYPE_UNAUTH_COMB_P_256) && - (p_dev_rec->sec_rec.link_key_type != BTM_LKEY_TYPE_AUTH_COMB_P_256)) + (p_dev_rec->sec_rec.link_key_type != BTM_LKEY_TYPE_AUTH_COMB_P_256)) { return false; + } - if (!L2CA_GetPeerFeatures(p_dev_rec->bd_addr, &ext_feat, chnl_mask)) + if (!L2CA_GetPeerFeatures(p_dev_rec->bd_addr, &ext_feat, chnl_mask)) { return false; + } - if (!(chnl_mask[0] & L2CAP_FIXED_CHNL_SMP_BR_BIT)) return false; + if (!(chnl_mask[0] & L2CAP_FIXED_CHNL_SMP_BR_BIT)) { + return false; + } return true; } @@ -5154,20 +4973,20 @@ static bool btm_sec_use_smp_br_chnl(tBTM_SEC_DEV_REC* p_dev_rec) { * Returns void * ******************************************************************************/ -void btm_sec_set_peer_sec_caps(uint16_t hci_handle, bool ssp_supported, - bool sc_supported, - bool hci_role_switch_supported, - bool br_edr_supported, bool le_supported) { +void btm_sec_set_peer_sec_caps(uint16_t hci_handle, bool ssp_supported, bool sc_supported, + bool hci_role_switch_supported, bool br_edr_supported, + bool le_supported) { tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev_by_handle(hci_handle); - if (p_dev_rec == nullptr) return; + if (p_dev_rec == nullptr) { + return; + } // Drop the connection here if the remote attempts to downgrade from Secure // Connections mode. if (btm_sec_is_device_sc_downgrade(hci_handle, sc_supported)) { acl_set_disconnect_reason(HCI_ERR_HOST_REJECT_SECURITY); - btm_sec_send_hci_disconnect( - p_dev_rec, HCI_ERR_AUTH_FAILURE, hci_handle, - "attempted to downgrade from Secure Connections mode"); + btm_sec_send_hci_disconnect(p_dev_rec, HCI_ERR_AUTH_FAILURE, hci_handle, + "attempted to downgrade from Secure Connections mode"); return; } @@ -5176,17 +4995,15 @@ void btm_sec_set_peer_sec_caps(uint16_t hci_handle, bool ssp_supported, uint8_t req_pend = (p_dev_rec->sm4 & BTM_SM4_REQ_PEND); - if (!(p_dev_rec->sec_rec.sec_flags & BTM_SEC_NAME_KNOWN) || - p_dev_rec->is_originator) { + if (!(p_dev_rec->sec_rec.sec_flags & BTM_SEC_NAME_KNOWN) || p_dev_rec->is_originator) { tBTM_STATUS btm_status = btm_sec_execute_procedure(p_dev_rec); if (btm_status != BTM_CMD_STARTED) { - log::warn("Security procedure not started! status:{}", - btm_status_text(btm_status)); + log::warn("Security procedure not started! status:{}", btm_status_text(btm_status)); btm_sec_dev_rec_cback_event(p_dev_rec, btm_status, false); } } - /* Store the Peer Security Capabilites (in SM4 and rmt_sec_caps) */ + /* Store the Peer Security Capabilities (in SM4 and rmt_sec_caps) */ if ((btm_sec_cb.security_mode == BTM_SEC_MODE_SP || btm_sec_cb.security_mode == BTM_SEC_MODE_SC) && ssp_supported) { @@ -5221,7 +5038,9 @@ DEV_CLASS btm_get_dev_class(const RawAddress& bda) { void BTM_update_version_info(const RawAddress& bd_addr, const remote_version_info& remote_version_info) { tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr); - if (p_dev_rec == NULL) return; + if (p_dev_rec == NULL) { + return; + } p_dev_rec->remote_version_info = remote_version_info; } diff --git a/system/stack/btm/btm_sec.h b/system/stack/btm/btm_sec.h index 4f617273e33..8ec45f7a4da 100644 --- a/system/stack/btm/btm_sec.h +++ b/system/stack/btm/btm_sec.h @@ -116,9 +116,9 @@ void BTM_SetPinType(uint8_t pin_type, PIN_CODE pin_code, uint8_t pin_code_len); * Returns true if registered OK, else false * ******************************************************************************/ -bool BTM_SetSecurityLevel(bool is_originator, const char* p_name, - uint8_t service_id, uint16_t sec_level, uint16_t psm, - uint32_t mx_proto_id, uint32_t mx_chan_id); +bool BTM_SetSecurityLevel(bool is_originator, const char* p_name, uint8_t service_id, + uint16_t sec_level, uint16_t psm, uint32_t mx_proto_id, + uint32_t mx_chan_id); /******************************************************************************* * @@ -173,8 +173,7 @@ uint8_t BTM_SecClrServiceByPsm(uint16_t psm); * p_pin - pointer to array with the PIN Code * ******************************************************************************/ -void BTM_PINCodeReply(const RawAddress& bd_addr, tBTM_STATUS res, - uint8_t pin_len, uint8_t* p_pin); +void BTM_PINCodeReply(const RawAddress& bd_addr, tBTM_STATUS res, uint8_t pin_len, uint8_t* p_pin); /******************************************************************************* * @@ -188,8 +187,7 @@ void BTM_PINCodeReply(const RawAddress& bd_addr, tBTM_STATUS res, * * Note: After 2.1 parameters are not used and preserved here not to change API ******************************************************************************/ -tBTM_STATUS btm_sec_bond_by_transport(const RawAddress& bd_addr, - tBLE_ADDR_TYPE addr_type, +tBTM_STATUS btm_sec_bond_by_transport(const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type, tBT_TRANSPORT transport); /******************************************************************************* @@ -265,8 +263,7 @@ tBTM_LINK_KEY_TYPE BTM_SecGetDeviceLinkKeyType(const RawAddress& bd_addr); * BTM_MODE_UNSUPPORTED - if security manager not linked in. * ******************************************************************************/ -tBTM_STATUS BTM_SetEncryption(const RawAddress& bd_addr, - tBT_TRANSPORT transport, +tBTM_STATUS BTM_SetEncryption(const RawAddress& bd_addr, tBT_TRANSPORT transport, tBTM_SEC_CALLBACK* p_callback, void* p_ref_data, tBTM_BLE_SEC_ACT sec_act); @@ -300,8 +297,7 @@ void BTM_ConfirmReqReply(tBTM_STATUS res, const RawAddress& bd_addr); * BTM_MAX_PASSKEY_VAL(999999(0xF423F)). * ******************************************************************************/ -void BTM_PasskeyReqReply(tBTM_STATUS res, const RawAddress& bd_addr, - uint32_t passkey); +void BTM_PasskeyReqReply(tBTM_STATUS res, const RawAddress& bd_addr, uint32_t passkey); /******************************************************************************* * @@ -325,8 +321,8 @@ void BTM_ReadLocalOobData(void); * r - simple pairing Randomizer C. * ******************************************************************************/ -void BTM_RemoteOobDataReply(tBTM_STATUS res, const RawAddress& bd_addr, - const Octet16& c, const Octet16& r); +void BTM_RemoteOobDataReply(tBTM_STATUS res, const RawAddress& bd_addr, const Octet16& c, + const Octet16& r); /******************************************************************************* * @@ -371,15 +367,14 @@ uint8_t BTM_GetSecurityMode(); * Returns tBTM_STATUS * ******************************************************************************/ -tBTM_STATUS btm_sec_l2cap_access_req(const RawAddress& bd_addr, uint16_t psm, - bool is_originator, - tBTM_SEC_CALLBACK* p_callback, - void* p_ref_data); +tBTM_STATUS btm_sec_l2cap_access_req(const RawAddress& bd_addr, uint16_t psm, bool is_originator, + tBTM_SEC_CALLBACK* p_callback, void* p_ref_data); // Allow enforcing security by specific requirement (from shim layer). -tBTM_STATUS btm_sec_l2cap_access_req_by_requirement( - const RawAddress& bd_addr, uint16_t security_required, bool is_originator, - tBTM_SEC_CALLBACK* p_callback, void* p_ref_data); +tBTM_STATUS btm_sec_l2cap_access_req_by_requirement(const RawAddress& bd_addr, + uint16_t security_required, bool is_originator, + tBTM_SEC_CALLBACK* p_callback, + void* p_ref_data); /******************************************************************************* * @@ -403,10 +398,8 @@ tBTM_STATUS btm_sec_l2cap_access_req_by_requirement( * Returns BTM_CMD_STARTED * ******************************************************************************/ -tBTM_STATUS btm_sec_mx_access_request(const RawAddress& bd_addr, - bool is_originator, - uint16_t security_requirement, - tBTM_SEC_CALLBACK* p_callback, +tBTM_STATUS btm_sec_mx_access_request(const RawAddress& bd_addr, bool is_originator, + uint16_t security_requirement, tBTM_SEC_CALLBACK* p_callback, void* p_ref_data); /******************************************************************************* @@ -432,8 +425,7 @@ void btm_sec_conn_req(const RawAddress& bda, const DEV_CLASS dc); * Returns void * ******************************************************************************/ -void btm_create_conn_cancel_complete(uint8_t status, const RawAddress bd_addr, - uint32_t value); +void btm_create_conn_cancel_complete(uint8_t status, const RawAddress bd_addr, uint32_t value); /******************************************************************************* * @@ -470,8 +462,7 @@ void btm_sec_abort_access_req(const RawAddress& bd_addr); * Returns void * ******************************************************************************/ -void btm_sec_rmt_name_request_complete(const RawAddress* p_bd_addr, - const uint8_t* p_bd_name, +void btm_sec_rmt_name_request_complete(const RawAddress* p_bd_addr, const uint8_t* p_bd_name, tHCI_STATUS status); /******************************************************************************* @@ -484,8 +475,7 @@ void btm_sec_rmt_name_request_complete(const RawAddress* p_bd_addr, * Returns void * ******************************************************************************/ -void btm_sec_rmt_host_support_feat_evt(const RawAddress bd_addr, - uint8_t features_0); +void btm_sec_rmt_host_support_feat_evt(const RawAddress bd_addr, uint8_t features_0); /******************************************************************************* * @@ -524,8 +514,7 @@ void btm_io_capabilities_rsp(const tBTM_SP_IO_RSP evt_data); * Returns void * ******************************************************************************/ -void btm_proc_sp_req_evt(tBTM_SP_EVT event, const RawAddress bda, - uint32_t value); +void btm_proc_sp_req_evt(tBTM_SP_EVT event, const RawAddress bda, uint32_t value); /******************************************************************************* * @@ -584,8 +573,7 @@ void btm_sec_auth_complete(uint16_t handle, tHCI_STATUS status); * Returns void * ******************************************************************************/ -void btm_sec_encryption_change_evt(uint16_t handle, tHCI_STATUS status, - uint8_t encr_enable); +void btm_sec_encryption_change_evt(uint16_t handle, tHCI_STATUS status, uint8_t encr_enable); /******************************************************************************* * @@ -597,8 +585,7 @@ void btm_sec_encryption_change_evt(uint16_t handle, tHCI_STATUS status, * Returns void * ******************************************************************************/ -void btm_sec_encrypt_change(uint16_t handle, tHCI_STATUS status, - uint8_t encr_enable); +void btm_sec_encrypt_change(uint16_t handle, tHCI_STATUS status, uint8_t encr_enable); /******************************************************************************* * @@ -610,8 +597,7 @@ void btm_sec_encrypt_change(uint16_t handle, tHCI_STATUS status, * Returns void * ******************************************************************************/ -void btm_sec_connected(const RawAddress& bda, uint16_t handle, - tHCI_STATUS status, uint8_t enc_mode, +void btm_sec_connected(const RawAddress& bda, uint16_t handle, tHCI_STATUS status, uint8_t enc_mode, tHCI_ROLE assigned_role = HCI_ROLE_PERIPHERAL); /******************************************************************************* @@ -623,8 +609,7 @@ void btm_sec_connected(const RawAddress& bda, uint16_t handle, * Returns btm status * ******************************************************************************/ -tBTM_STATUS btm_sec_disconnect(uint16_t handle, tHCI_STATUS reason, - std::string); +tBTM_STATUS btm_sec_disconnect(uint16_t handle, tHCI_STATUS reason, std::string); /******************************************************************************* * @@ -636,8 +621,7 @@ tBTM_STATUS btm_sec_disconnect(uint16_t handle, tHCI_STATUS reason, * Returns void * ******************************************************************************/ -void btm_sec_disconnected(uint16_t handle, tHCI_STATUS reason, - std::string comment); +void btm_sec_disconnected(uint16_t handle, tHCI_STATUS reason, std::string comment); /******************************************************************************* * @@ -649,16 +633,14 @@ void btm_sec_disconnected(uint16_t handle, tHCI_STATUS reason, * Returns void * ******************************************************************************/ -void btm_sec_role_changed(tHCI_STATUS hci_status, const RawAddress& bd_addr, - tHCI_ROLE new_role); +void btm_sec_role_changed(tHCI_STATUS hci_status, const RawAddress& bd_addr, tHCI_ROLE new_role); /** This function is called when a new connection link key is generated */ -void btm_sec_link_key_notification(const RawAddress& p_bda, - const Octet16& link_key, uint8_t key_type); +void btm_sec_link_key_notification(const RawAddress& p_bda, const Octet16& link_key, + uint8_t key_type); /** This function is called for each encryption key refresh complete event */ -void btm_sec_encryption_key_refresh_complete(uint16_t handle, - tHCI_STATUS status); +void btm_sec_encryption_key_refresh_complete(uint16_t handle, tHCI_STATUS status); /******************************************************************************* * @@ -740,10 +722,9 @@ bool btm_sec_is_a_bonded_dev(const RawAddress& bda); * Returns void * ******************************************************************************/ -void btm_sec_set_peer_sec_caps(uint16_t hci_handle, bool ssp_supported, - bool sc_supported, - bool hci_role_switch_supported, - bool br_edr_supported, bool le_supported); +void btm_sec_set_peer_sec_caps(uint16_t hci_handle, bool ssp_supported, bool sc_supported, + bool hci_role_switch_supported, bool br_edr_supported, + bool le_supported); /******************************************************************************* * @@ -754,8 +735,7 @@ void btm_sec_set_peer_sec_caps(uint16_t hci_handle, bool ssp_supported, * Returns void * ******************************************************************************/ -void btm_sec_cr_loc_oob_data_cback_event(const RawAddress& address, - tSMP_LOC_OOB_DATA loc_oob_data); +void btm_sec_cr_loc_oob_data_cback_event(const RawAddress& address, tSMP_LOC_OOB_DATA loc_oob_data); // Return DEV_CLASS of bda. If record doesn't exist, create one. DEV_CLASS btm_get_dev_class(const RawAddress& bda); diff --git a/system/stack/btm/btm_sec_cb.cc b/system/stack/btm/btm_sec_cb.cc index eab48e94307..3e87d19810a 100644 --- a/system/stack/btm/btm_sec_cb.cc +++ b/system/stack/btm/btm_sec_cb.cc @@ -81,9 +81,8 @@ void tBTM_SEC_CB::Free() { tBTM_SEC_CB btm_sec_cb; void BTM_Sec_Init() { - btm_sec_cb.Init(stack_config_get_interface()->get_pts_secure_only_mode() - ? BTM_SEC_MODE_SC - : BTM_SEC_MODE_SP); + btm_sec_cb.Init(stack_config_get_interface()->get_pts_secure_only_mode() ? BTM_SEC_MODE_SC + : BTM_SEC_MODE_SP); } void BTM_Sec_Free() { btm_sec_cb.Free(); } @@ -98,8 +97,7 @@ void BTM_Sec_Free() { btm_sec_cb.Free(); } * Returns Pointer to the record or NULL * ******************************************************************************/ -tBTM_SEC_SERV_REC* tBTM_SEC_CB::find_first_serv_rec(bool is_originator, - uint16_t psm) { +tBTM_SEC_SERV_REC* tBTM_SEC_CB::find_first_serv_rec(bool is_originator, uint16_t psm) { tBTM_SEC_SERV_REC* p_serv_rec = &sec_serv_rec[0]; int i; @@ -111,11 +109,11 @@ tBTM_SEC_SERV_REC* tBTM_SEC_CB::find_first_serv_rec(bool is_originator, /* otherwise, just find the first record with the specified PSM */ for (i = 0; i < BTM_SEC_MAX_SERVICE_RECORDS; i++, p_serv_rec++) { - if ((p_serv_rec->security_flags & BTM_SEC_IN_USE) && - (p_serv_rec->psm == psm)) - return (p_serv_rec); + if ((p_serv_rec->security_flags & BTM_SEC_IN_USE) && (p_serv_rec->psm == psm)) { + return p_serv_rec; + } } - return (NULL); + return NULL; } tBTM_SEC_REC* tBTM_SEC_CB::getSecRec(const RawAddress bd_addr) { @@ -126,8 +124,7 @@ tBTM_SEC_REC* tBTM_SEC_CB::getSecRec(const RawAddress bd_addr) { return nullptr; } -bool tBTM_SEC_CB::IsDeviceEncrypted(const RawAddress bd_addr, - tBT_TRANSPORT transport) { +bool tBTM_SEC_CB::IsDeviceEncrypted(const RawAddress bd_addr, tBT_TRANSPORT transport) { tBTM_SEC_REC* sec_rec = getSecRec(bd_addr); if (sec_rec) { if (transport == BT_TRANSPORT_BR_EDR) { @@ -143,8 +140,7 @@ bool tBTM_SEC_CB::IsDeviceEncrypted(const RawAddress bd_addr, return false; } -bool tBTM_SEC_CB::IsLinkKeyAuthenticated(const RawAddress bd_addr, - tBT_TRANSPORT transport) { +bool tBTM_SEC_CB::IsLinkKeyAuthenticated(const RawAddress bd_addr, tBT_TRANSPORT transport) { tBTM_SEC_REC* sec_rec = getSecRec(bd_addr); if (sec_rec) { if (transport == BT_TRANSPORT_BR_EDR) { @@ -160,8 +156,7 @@ bool tBTM_SEC_CB::IsLinkKeyAuthenticated(const RawAddress bd_addr, return false; } -bool tBTM_SEC_CB::IsDeviceAuthenticated(const RawAddress bd_addr, - tBT_TRANSPORT transport) { +bool tBTM_SEC_CB::IsDeviceAuthenticated(const RawAddress bd_addr, tBT_TRANSPORT transport) { tBTM_SEC_REC* sec_rec = getSecRec(bd_addr); if (sec_rec) { if (transport == BT_TRANSPORT_BR_EDR) { @@ -177,8 +172,7 @@ bool tBTM_SEC_CB::IsDeviceAuthenticated(const RawAddress bd_addr, return false; } -bool tBTM_SEC_CB::IsLinkKeyKnown(const RawAddress bd_addr, - tBT_TRANSPORT transport) { +bool tBTM_SEC_CB::IsLinkKeyKnown(const RawAddress bd_addr, tBT_TRANSPORT transport) { tBTM_SEC_REC* sec_rec = getSecRec(bd_addr); if (sec_rec) { if (transport == BT_TRANSPORT_BR_EDR) { @@ -198,20 +192,18 @@ bool tBTM_SEC_CB::IsDeviceBonded(const RawAddress bd_addr) { tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr); bool is_bonded = false; - if (p_dev_rec && ((p_dev_rec->sec_rec.ble_keys.key_type && - p_dev_rec->sec_rec.is_le_link_key_known()) || - p_dev_rec->sec_rec.is_link_key_known())) { + if (p_dev_rec && + ((p_dev_rec->sec_rec.ble_keys.key_type && p_dev_rec->sec_rec.is_le_link_key_known()) || + p_dev_rec->sec_rec.is_link_key_known())) { is_bonded = true; } - log::debug("Device record bonded check peer:{} is_bonded:{}", bd_addr, - is_bonded); + log::debug("Device record bonded check peer:{} is_bonded:{}", bd_addr, is_bonded); return is_bonded; } #define BTM_NO_AVAIL_SEC_SERVICES ((uint16_t)0xffff) -bool tBTM_SEC_CB::AddService(bool is_originator, const char* p_name, - uint8_t service_id, uint16_t sec_level, - uint16_t psm, uint32_t mx_proto_id, +bool tBTM_SEC_CB::AddService(bool is_originator, const char* p_name, uint8_t service_id, + uint16_t sec_level, uint16_t psm, uint32_t mx_proto_id, uint32_t mx_chan_id) { tBTM_SEC_SERV_REC* p_srec; uint16_t index; @@ -250,7 +242,7 @@ bool tBTM_SEC_CB::AddService(bool is_originator, const char* p_name, if (!record_allocated) { log::warn("Out of Service Records ({})", BTM_SEC_MAX_SERVICE_RECORDS); - return (record_allocated); + return record_allocated; } /* Process the request if service record is valid */ @@ -266,25 +258,28 @@ bool tBTM_SEC_CB::AddService(bool is_originator, const char* p_name, if (is_originator) { p_srec->orig_mx_chan_id = mx_chan_id; - strlcpy((char*)p_srec->orig_service_name, p_name, - BT_MAX_SERVICE_NAME_LEN + 1); + strlcpy((char*)p_srec->orig_service_name, p_name, BT_MAX_SERVICE_NAME_LEN + 1); /* clear out the old setting, just in case it exists */ { p_srec->security_flags &= - ~(BTM_SEC_OUT_ENCRYPT | BTM_SEC_OUT_AUTHENTICATE | BTM_SEC_OUT_MITM); + ~(BTM_SEC_OUT_ENCRYPT | BTM_SEC_OUT_AUTHENTICATE | BTM_SEC_OUT_MITM); } /* Parameter validation. Originator should not set requirements for * incoming connections */ - sec_level &= ~(BTM_SEC_IN_ENCRYPT | BTM_SEC_IN_AUTHENTICATE | - BTM_SEC_IN_MITM | BTM_SEC_IN_MIN_16_DIGIT_PIN); + sec_level &= ~(BTM_SEC_IN_ENCRYPT | BTM_SEC_IN_AUTHENTICATE | BTM_SEC_IN_MITM | + BTM_SEC_IN_MIN_16_DIGIT_PIN); if (security_mode == BTM_SEC_MODE_SP || security_mode == BTM_SEC_MODE_SC) { - if (sec_level & BTM_SEC_OUT_AUTHENTICATE) sec_level |= BTM_SEC_OUT_MITM; + if (sec_level & BTM_SEC_OUT_AUTHENTICATE) { + sec_level |= BTM_SEC_OUT_MITM; + } } /* Make sure the authenticate bit is set, when encrypt bit is set */ - if (sec_level & BTM_SEC_OUT_ENCRYPT) sec_level |= BTM_SEC_OUT_AUTHENTICATE; + if (sec_level & BTM_SEC_OUT_ENCRYPT) { + sec_level |= BTM_SEC_OUT_AUTHENTICATE; + } /* outgoing connections usually set the security level right before * the connection is initiated. @@ -292,37 +287,38 @@ bool tBTM_SEC_CB::AddService(bool is_originator, const char* p_name, p_out_serv = p_srec; } else { p_srec->term_mx_chan_id = mx_chan_id; - strlcpy((char*)p_srec->term_service_name, p_name, - BT_MAX_SERVICE_NAME_LEN + 1); + strlcpy((char*)p_srec->term_service_name, p_name, BT_MAX_SERVICE_NAME_LEN + 1); /* clear out the old setting, just in case it exists */ { - p_srec->security_flags &= - ~(BTM_SEC_IN_ENCRYPT | BTM_SEC_IN_AUTHENTICATE | BTM_SEC_IN_MITM | - BTM_SEC_IN_MIN_16_DIGIT_PIN); + p_srec->security_flags &= ~(BTM_SEC_IN_ENCRYPT | BTM_SEC_IN_AUTHENTICATE | BTM_SEC_IN_MITM | + BTM_SEC_IN_MIN_16_DIGIT_PIN); } /* Parameter validation. Acceptor should not set requirements for outgoing * connections */ - sec_level &= - ~(BTM_SEC_OUT_ENCRYPT | BTM_SEC_OUT_AUTHENTICATE | BTM_SEC_OUT_MITM); + sec_level &= ~(BTM_SEC_OUT_ENCRYPT | BTM_SEC_OUT_AUTHENTICATE | BTM_SEC_OUT_MITM); if (security_mode == BTM_SEC_MODE_SP || security_mode == BTM_SEC_MODE_SC) { - if (sec_level & BTM_SEC_IN_AUTHENTICATE) sec_level |= BTM_SEC_IN_MITM; + if (sec_level & BTM_SEC_IN_AUTHENTICATE) { + sec_level |= BTM_SEC_IN_MITM; + } } /* Make sure the authenticate bit is set, when encrypt bit is set */ - if (sec_level & BTM_SEC_IN_ENCRYPT) sec_level |= BTM_SEC_IN_AUTHENTICATE; + if (sec_level & BTM_SEC_IN_ENCRYPT) { + sec_level |= BTM_SEC_IN_AUTHENTICATE; + } } p_srec->security_flags |= (uint16_t)(sec_level | BTM_SEC_IN_USE); log::debug( - "[{}]: id:{}, is_orig:{} psm:0x{:04x} proto_id:{} chan_id:{} : " - "sec:0x{:x} service_name:[{}] (up to {} chars saved)", - index, service_id, is_originator, psm, mx_proto_id, mx_chan_id, - p_srec->security_flags, p_name, BT_MAX_SERVICE_NAME_LEN); + "[{}]: id:{}, is_orig:{} psm:0x{:04x} proto_id:{} chan_id:{} : " + "sec:0x{:x} service_name:[{}] (up to {} chars saved)", + index, service_id, is_originator, psm, mx_proto_id, mx_chan_id, p_srec->security_flags, + p_name, BT_MAX_SERVICE_NAME_LEN); - return (record_allocated); + return record_allocated; } uint8_t tBTM_SEC_CB::RemoveServiceById(uint8_t service_id) { @@ -332,15 +328,14 @@ uint8_t tBTM_SEC_CB::RemoveServiceById(uint8_t service_id) { for (i = 0; i < BTM_SEC_MAX_SERVICE_RECORDS; i++, p_srec++) { /* Delete services with specified name (if in use and not SDP) */ - if ((p_srec->security_flags & BTM_SEC_IN_USE) && - (p_srec->psm != BT_PSM_SDP) && + if ((p_srec->security_flags & BTM_SEC_IN_USE) && (p_srec->psm != BT_PSM_SDP) && (!service_id || (service_id == p_srec->service_id))) { log::verbose("BTM_SEC_CLR[{}]: id:{}", i, service_id); p_srec->security_flags = 0; num_freed++; } } - return (num_freed); + return num_freed; } uint8_t tBTM_SEC_CB::RemoveServiceByPsm(uint16_t psm) { @@ -358,5 +353,5 @@ uint8_t tBTM_SEC_CB::RemoveServiceByPsm(uint16_t psm) { } log::verbose("psm:0x{:x} num_freed:{}", psm, num_freed); - return (num_freed); + return num_freed; } diff --git a/system/stack/btm/btm_sec_cb.h b/system/stack/btm/btm_sec_cb.h index 0a827c1dc2d..0e3234c7ce6 100644 --- a/system/stack/btm/btm_sec_cb.h +++ b/system/stack/btm/btm_sec_cb.h @@ -30,7 +30,7 @@ #include "types/raw_address.h" class tBTM_SEC_CB { - public: +public: tBTM_CFG cfg; /* Device configuration */ /***************************************************** @@ -43,7 +43,7 @@ class tBTM_SEC_CB { uint16_t ediv{0}; /* received ediv value from LTK request */ uint8_t key_size{0}; - public: +public: /***************************************************** ** Security Management *****************************************************/ @@ -59,15 +59,14 @@ class tBTM_SEC_CB { bool pin_type_changed{false}; /* pin type changed during bonding */ bool sec_req_pending{false}; /* true if a request is pending */ - uint8_t pin_code_len{0}; /* for legacy devices */ - PIN_CODE pin_code; /* for legacy devices */ - tBTM_PAIRING_STATE pairing_state{ - BTM_PAIR_STATE_IDLE}; /* The current pairing state */ - uint8_t pairing_flags{0}; /* The current pairing flags */ - RawAddress pairing_bda; /* The device currently pairing */ - alarm_t* pairing_timer{nullptr}; /* Timer for pairing process */ - alarm_t* execution_wait_timer{nullptr}; /* To avoid concurrent auth request */ - list_t* sec_dev_rec{nullptr}; /* list of tBTM_SEC_DEV_REC */ + uint8_t pin_code_len{0}; /* for legacy devices */ + PIN_CODE pin_code; /* for legacy devices */ + tBTM_PAIRING_STATE pairing_state{BTM_PAIR_STATE_IDLE}; /* The current pairing state */ + uint8_t pairing_flags{0}; /* The current pairing flags */ + RawAddress pairing_bda; /* The device currently pairing */ + alarm_t* pairing_timer{nullptr}; /* Timer for pairing process */ + alarm_t* execution_wait_timer{nullptr}; /* To avoid concurrent auth request */ + list_t* sec_dev_rec{nullptr}; /* list of tBTM_SEC_DEV_REC */ tBTM_SEC_SERV_REC* p_out_serv{nullptr}; tBTM_MKEY_CALLBACK* mkey_cback{nullptr}; @@ -88,16 +87,14 @@ class tBTM_SEC_CB { bool IsDeviceBonded(const RawAddress bd_addr); bool IsDeviceEncrypted(const RawAddress bd_addr, tBT_TRANSPORT transport); bool IsDeviceAuthenticated(const RawAddress bd_addr, tBT_TRANSPORT transport); - bool IsLinkKeyAuthenticated(const RawAddress bd_addr, - tBT_TRANSPORT transport); + bool IsLinkKeyAuthenticated(const RawAddress bd_addr, tBT_TRANSPORT transport); bool IsLinkKeyKnown(const RawAddress bd_addr, tBT_TRANSPORT transport); tBTM_SEC_REC* getSecRec(const RawAddress bd_addr); - bool AddService(bool is_originator, const char* p_name, uint8_t service_id, - uint16_t sec_level, uint16_t psm, uint32_t mx_proto_id, - uint32_t mx_chan_id); + bool AddService(bool is_originator, const char* p_name, uint8_t service_id, uint16_t sec_level, + uint16_t psm, uint32_t mx_proto_id, uint32_t mx_chan_id); uint8_t RemoveServiceById(uint8_t service_id); uint8_t RemoveServiceByPsm(uint16_t psm); diff --git a/system/stack/btm/btm_sec_int_types.h b/system/stack/btm/btm_sec_int_types.h index 9f2b68f8ee1..8d960d63d36 100644 --- a/system/stack/btm/btm_sec_int_types.h +++ b/system/stack/btm/btm_sec_int_types.h @@ -31,47 +31,40 @@ * Local device configuration */ typedef struct { - BD_NAME bd_name; /* local Bluetooth device name */ - bool pin_type; /* true if PIN type is fixed */ - uint8_t pin_code_len; /* Bonding information */ - PIN_CODE pin_code; /* PIN CODE if pin type is fixed */ + BD_NAME bd_name; /* local Bluetooth device name */ + bool pin_type; /* true if PIN type is fixed */ + uint8_t pin_code_len; /* Bonding information */ + PIN_CODE pin_code; /* PIN CODE if pin type is fixed */ } tBTM_CFG; /* Pairing State */ enum tBTM_PAIRING_STATE : uint8_t { - BTM_PAIR_STATE_IDLE, /* Idle */ - BTM_PAIR_STATE_GET_REM_NAME, /* Getting the remote name (to check for SM4) */ - BTM_PAIR_STATE_WAIT_PIN_REQ, /* Started authentication, waiting for PIN req - (PIN is pre-fetched) */ + BTM_PAIR_STATE_IDLE, /* Idle */ + BTM_PAIR_STATE_GET_REM_NAME, /* Getting the remote name (to check for SM4) */ + BTM_PAIR_STATE_WAIT_PIN_REQ, /* Started authentication, waiting for PIN req + (PIN is pre-fetched) */ BTM_PAIR_STATE_WAIT_LOCAL_PIN, /* Waiting for local PIN code */ BTM_PAIR_STATE_WAIT_NUMERIC_CONFIRM, /* Waiting user 'yes' to numeric confirmation */ - BTM_PAIR_STATE_KEY_ENTRY, /* Key entry state (we are a keyboard) */ - BTM_PAIR_STATE_WAIT_LOCAL_OOB_RSP, /* Waiting for local response to peer OOB - data */ - BTM_PAIR_STATE_WAIT_LOCAL_IOCAPS, /* Waiting for local IO capabilities and OOB - data */ - BTM_PAIR_STATE_INCOMING_SSP, /* Incoming SSP (got peer IO caps when idle) */ - BTM_PAIR_STATE_WAIT_AUTH_COMPLETE, /* All done, waiting authentication - complete */ - BTM_PAIR_STATE_WAIT_DISCONNECT /* Waiting to disconnect the ACL */ + BTM_PAIR_STATE_KEY_ENTRY, /* Key entry state (we are a keyboard) */ + BTM_PAIR_STATE_WAIT_LOCAL_OOB_RSP, /* Waiting for local response to peer OOB + data */ + BTM_PAIR_STATE_WAIT_LOCAL_IOCAPS, /* Waiting for local IO capabilities and OOB + data */ + BTM_PAIR_STATE_INCOMING_SSP, /* Incoming SSP (got peer IO caps when idle) */ + BTM_PAIR_STATE_WAIT_AUTH_COMPLETE, /* All done, waiting authentication + complete */ + BTM_PAIR_STATE_WAIT_DISCONNECT /* Waiting to disconnect the ACL */ }; -#define BTM_PAIR_FLAGS_WE_STARTED_DD \ - 0x01 /* We want to do dedicated bonding */ -#define BTM_PAIR_FLAGS_PEER_STARTED_DD \ - 0x02 /* Peer initiated dedicated bonding */ -#define BTM_PAIR_FLAGS_DISC_WHEN_DONE 0x04 /* Disconnect when done */ -#define BTM_PAIR_FLAGS_PIN_REQD \ - 0x08 /* set this bit when pin_callback is called */ -#define BTM_PAIR_FLAGS_PRE_FETCH_PIN \ - 0x10 /* set this bit when pre-fetch pin */ -#define BTM_PAIR_FLAGS_REJECTED_CONNECT \ - 0x20 /* set this bit when rejected incoming connection */ -#define BTM_PAIR_FLAGS_WE_CANCEL_DD \ - 0x40 /* set this bit when cancelling a bonding procedure */ -#define BTM_PAIR_FLAGS_LE_ACTIVE \ - 0x80 /* use this bit when SMP pairing is active */ +#define BTM_PAIR_FLAGS_WE_STARTED_DD 0x01 /* We want to do dedicated bonding */ +#define BTM_PAIR_FLAGS_PEER_STARTED_DD 0x02 /* Peer initiated dedicated bonding */ +#define BTM_PAIR_FLAGS_DISC_WHEN_DONE 0x04 /* Disconnect when done */ +#define BTM_PAIR_FLAGS_PIN_REQD 0x08 /* set this bit when pin_callback is called */ +#define BTM_PAIR_FLAGS_PRE_FETCH_PIN 0x10 /* set this bit when pre-fetch pin */ +#define BTM_PAIR_FLAGS_REJECTED_CONNECT 0x20 /* set this bit when rejected incoming connection */ +#define BTM_PAIR_FLAGS_WE_CANCEL_DD 0x40 /* set this bit when cancelling a bonding procedure */ +#define BTM_PAIR_FLAGS_LE_ACTIVE 0x80 /* use this bit when SMP pairing is active */ typedef struct { bool is_mux; @@ -89,8 +82,7 @@ typedef struct { /* Define the Device Management control structure */ typedef struct tBTM_SEC_DEVCB { - tBTM_CMPL_CB* - p_stored_link_key_cmpl_cb; /* Read/Write/Delete stored link key */ + tBTM_CMPL_CB* p_stored_link_key_cmpl_cb; /* Read/Write/Delete stored link key */ tBTM_BLE_LOCAL_ID_KEYS id_keys; /* local BLE ID keys */ Octet16 ble_encryption_key_value; /* BLE encryption key */ diff --git a/system/stack/btm/btm_security_client_interface.cc b/system/stack/btm/btm_security_client_interface.cc index 167911785e4..9e7f6a822b5 100644 --- a/system/stack/btm/btm_security_client_interface.cc +++ b/system/stack/btm/btm_security_client_interface.cc @@ -42,41 +42,39 @@ static void BTM_SecConfirmReqReply(tBTM_STATUS res, tBT_TRANSPORT transport, } static SecurityClientInterface security = { - .BTM_Sec_Init = BTM_Sec_Init, - .BTM_Sec_Free = BTM_Sec_Free, - .BTM_SecRegister = BTM_SecRegister, + .BTM_Sec_Init = BTM_Sec_Init, + .BTM_Sec_Free = BTM_Sec_Free, + .BTM_SecRegister = BTM_SecRegister, - .BTM_BleLoadLocalKeys = BTM_BleLoadLocalKeys, + .BTM_BleLoadLocalKeys = BTM_BleLoadLocalKeys, - .BTM_SecAddDevice = BTM_SecAddDevice, - .BTM_SecAddBleDevice = BTM_SecAddBleDevice, - .BTM_SecDeleteDevice = BTM_SecDeleteDevice, - .BTM_SecAddBleKey = BTM_SecAddBleKey, - .BTM_SecClearSecurityFlags = BTM_SecClearSecurityFlags, - .BTM_SetEncryption = BTM_SetEncryption, - .BTM_IsEncrypted = BTM_IsEncrypted, - .BTM_SecIsSecurityPending = BTM_SecIsSecurityPending, - .BTM_IsLinkKeyKnown = BTM_IsLinkKeyKnown, + .BTM_SecAddDevice = BTM_SecAddDevice, + .BTM_SecAddBleDevice = BTM_SecAddBleDevice, + .BTM_SecDeleteDevice = BTM_SecDeleteDevice, + .BTM_SecAddBleKey = BTM_SecAddBleKey, + .BTM_SecClearSecurityFlags = BTM_SecClearSecurityFlags, + .BTM_SetEncryption = BTM_SetEncryption, + .BTM_IsEncrypted = BTM_IsEncrypted, + .BTM_SecIsSecurityPending = BTM_SecIsSecurityPending, + .BTM_IsLinkKeyKnown = BTM_IsLinkKeyKnown, - .BTM_SetSecurityLevel = BTM_SetSecurityLevel, - .BTM_SecClrService = BTM_SecClrService, - .BTM_SecClrServiceByPsm = BTM_SecClrServiceByPsm, + .BTM_SetSecurityLevel = BTM_SetSecurityLevel, + .BTM_SecClrService = BTM_SecClrService, + .BTM_SecClrServiceByPsm = BTM_SecClrServiceByPsm, - .BTM_SecBond = BTM_SecBond, - .BTM_SecBondCancel = BTM_SecBondCancel, - .BTM_RemoteOobDataReply = BTM_RemoteOobDataReply, - .BTM_PINCodeReply = BTM_PINCodeReply, - .BTM_SecConfirmReqReply = BTM_SecConfirmReqReply, - .BTM_BleSirkConfirmDeviceReply = BTM_BleSirkConfirmDeviceReply, - .BTM_BlePasskeyReply = BTM_BlePasskeyReply, + .BTM_SecBond = BTM_SecBond, + .BTM_SecBondCancel = BTM_SecBondCancel, + .BTM_RemoteOobDataReply = BTM_RemoteOobDataReply, + .BTM_PINCodeReply = BTM_PINCodeReply, + .BTM_SecConfirmReqReply = BTM_SecConfirmReqReply, + .BTM_BleSirkConfirmDeviceReply = BTM_BleSirkConfirmDeviceReply, + .BTM_BlePasskeyReply = BTM_BlePasskeyReply, - .BTM_GetSecurityMode = BTM_GetSecurityMode, + .BTM_GetSecurityMode = BTM_GetSecurityMode, - .BTM_SecReadDevName = BTM_SecReadDevName, - .BTM_SecAddRmtNameNotifyCallback = BTM_SecAddRmtNameNotifyCallback, - .BTM_SecDeleteRmtNameNotifyCallback = BTM_SecDeleteRmtNameNotifyCallback, + .BTM_SecReadDevName = BTM_SecReadDevName, + .BTM_SecAddRmtNameNotifyCallback = BTM_SecAddRmtNameNotifyCallback, + .BTM_SecDeleteRmtNameNotifyCallback = BTM_SecDeleteRmtNameNotifyCallback, }; -const SecurityClientInterface& get_security_client_interface() { - return security; -} +const SecurityClientInterface& get_security_client_interface() { return security; } diff --git a/system/stack/btm/hfp_lc3_decoder.cc b/system/stack/btm/hfp_lc3_decoder.cc index 264b796b83d..30e30d1ffc8 100644 --- a/system/stack/btm/hfp_lc3_decoder.cc +++ b/system/stack/btm/hfp_lc3_decoder.cc @@ -47,8 +47,7 @@ bool hfp_lc3_decoder_init() { const unsigned dec_size = lc3_decoder_size(dt_us, sr_pcm_hz); hfp_lc3_decoder_mem = osi_malloc(dec_size); - hfp_lc3_decoder = - lc3_setup_decoder(dt_us, sr_hz, sr_pcm_hz, hfp_lc3_decoder_mem); + hfp_lc3_decoder = lc3_setup_decoder(dt_us, sr_hz, sr_pcm_hz, hfp_lc3_decoder_mem); return true; } @@ -59,19 +58,16 @@ void hfp_lc3_decoder_cleanup() { } } -bool hfp_lc3_decoder_decode_packet(const uint8_t* i_buf, int16_t* o_buf, - size_t out_len) { +bool hfp_lc3_decoder_decode_packet(const uint8_t* i_buf, int16_t* o_buf, size_t out_len) { if (o_buf == nullptr || out_len < HFP_LC3_PCM_BYTES) { - log::error("Output buffer size {} is less than LC3 frame size {}", out_len, - HFP_LC3_PCM_BYTES); + log::error("Output buffer size {} is less than LC3 frame size {}", out_len, HFP_LC3_PCM_BYTES); return false; } const uint8_t* frame = i_buf ? i_buf + HFP_LC3_H2_HEADER_LEN : nullptr; /* Note this only fails when wrong parameters are supplied. */ - int rc = lc3_decode(hfp_lc3_decoder, frame, HFP_LC3_PKT_FRAME_LEN, - LC3_PCM_FORMAT_S16, o_buf, 1); + int rc = lc3_decode(hfp_lc3_decoder, frame, HFP_LC3_PKT_FRAME_LEN, LC3_PCM_FORMAT_S16, o_buf, 1); log::assert_that(rc == 0 || rc == 1, "assert failed: rc == 0 || rc == 1"); diff --git a/system/stack/btm/hfp_lc3_decoder_linux.cc b/system/stack/btm/hfp_lc3_decoder_linux.cc index 68674aa1c11..b30da4ff194 100644 --- a/system/stack/btm/hfp_lc3_decoder_linux.cc +++ b/system/stack/btm/hfp_lc3_decoder_linux.cc @@ -32,8 +32,7 @@ const int HFP_LC3_PKT_FRAME_LEN = 58; const int HFP_LC3_PCM_BYTES = 480; static mmc::CodecClient* client = nullptr; -static const uint8_t plc_buf[HFP_LC3_H2_HEADER_LEN + HFP_LC3_PKT_FRAME_LEN] = { - 0}; +static const uint8_t plc_buf[HFP_LC3_H2_HEADER_LEN + HFP_LC3_PKT_FRAME_LEN] = {0}; bool hfp_lc3_decoder_init() { hfp_lc3_decoder_cleanup(); @@ -70,11 +69,9 @@ void hfp_lc3_decoder_cleanup() { } } -bool hfp_lc3_decoder_decode_packet(const uint8_t* i_buf, int16_t* o_buf, - size_t out_len) { +bool hfp_lc3_decoder_decode_packet(const uint8_t* i_buf, int16_t* o_buf, size_t out_len) { if (o_buf == nullptr || out_len < HFP_LC3_PCM_BYTES) { - log::error("Output buffer size {} is less than LC3 frame size {}", out_len, - HFP_LC3_PCM_BYTES); + log::error("Output buffer size {} is less than LC3 frame size {}", out_len, HFP_LC3_PCM_BYTES); return false; } @@ -89,8 +86,7 @@ bool hfp_lc3_decoder_decode_packet(const uint8_t* i_buf, int16_t* o_buf, // One extra byte in the beginning to indicate whether PLC was conducted. uint8_t* o_packet = new uint8_t[out_len + 1]; - int rc = client->transcode((uint8_t*)frame, - HFP_LC3_PKT_FRAME_LEN + HFP_LC3_H2_HEADER_LEN, + int rc = client->transcode((uint8_t*)frame, HFP_LC3_PKT_FRAME_LEN + HFP_LC3_H2_HEADER_LEN, o_packet, out_len + 1); if (rc < 0) { diff --git a/system/stack/btm/hfp_lc3_encoder.cc b/system/stack/btm/hfp_lc3_encoder.cc index 4b1b4d05288..6e0cdb28df9 100644 --- a/system/stack/btm/hfp_lc3_encoder.cc +++ b/system/stack/btm/hfp_lc3_encoder.cc @@ -46,8 +46,7 @@ void hfp_lc3_encoder_init() { const unsigned enc_size = lc3_encoder_size(dt_us, sr_pcm_hz); hfp_lc3_encoder_mem = osi_malloc(enc_size); - hfp_lc3_encoder = - lc3_setup_encoder(dt_us, sr_hz, sr_pcm_hz, hfp_lc3_encoder_mem); + hfp_lc3_encoder = lc3_setup_encoder(dt_us, sr_hz, sr_pcm_hz, hfp_lc3_encoder_mem); } void hfp_lc3_encoder_cleanup() { @@ -63,8 +62,7 @@ uint32_t hfp_lc3_encode_frames(int16_t* input, uint8_t* output) { } /* Note this only fails when wrong parameters are supplied. */ - int rc = lc3_encode(hfp_lc3_encoder, LC3_PCM_FORMAT_S16, input, 1, - HFP_LC3_PKT_FRAME_LEN, output); + int rc = lc3_encode(hfp_lc3_encoder, LC3_PCM_FORMAT_S16, input, 1, HFP_LC3_PKT_FRAME_LEN, output); log::assert_that(rc == 0, "assert failed: rc == 0"); diff --git a/system/stack/btm/hfp_lc3_encoder_linux.cc b/system/stack/btm/hfp_lc3_encoder_linux.cc index 2385a2ffd84..448e6403c2a 100644 --- a/system/stack/btm/hfp_lc3_encoder_linux.cc +++ b/system/stack/btm/hfp_lc3_encoder_linux.cc @@ -74,8 +74,7 @@ uint32_t hfp_lc3_encode_frames(int16_t* input, uint8_t* output) { return 0; } - int rc = client->transcode((uint8_t*)input, HFP_LC3_PCM_BYTES, output, - HFP_LC3_PKT_FRAME_LEN); + int rc = client->transcode((uint8_t*)input, HFP_LC3_PCM_BYTES, output, HFP_LC3_PKT_FRAME_LEN); if (rc < 0) { log::warn("Encode failed with error message, {}", strerror(-rc)); diff --git a/system/stack/btm/hfp_msbc_decoder.cc b/system/stack/btm/hfp_msbc_decoder.cc index 7db1c0923da..334cf91f9f7 100644 --- a/system/stack/btm/hfp_msbc_decoder.cc +++ b/system/stack/btm/hfp_msbc_decoder.cc @@ -44,9 +44,9 @@ typedef struct { static tHFP_MSBC_DECODER hfp_msbc_decoder; bool hfp_msbc_decoder_init() { - OI_STATUS status = OI_CODEC_SBC_DecoderReset( - &hfp_msbc_decoder.decoder_context, hfp_msbc_decoder.context_data, - sizeof(hfp_msbc_decoder.context_data), 1, 1, false); + OI_STATUS status = OI_CODEC_SBC_DecoderReset(&hfp_msbc_decoder.decoder_context, + hfp_msbc_decoder.context_data, + sizeof(hfp_msbc_decoder.context_data), 1, 1, false); if (!OI_SUCCESS(status)) { log::error("OI_CODEC_SBC_DecoderReset failed with error code {}", status); return false; @@ -54,25 +54,20 @@ bool hfp_msbc_decoder_init() { status = OI_CODEC_SBC_DecoderConfigureMSbc(&hfp_msbc_decoder.decoder_context); if (!OI_SUCCESS(status)) { - log::error("OI_CODEC_SBC_DecoderConfigureMSbc failed with error code {}", - status); + log::error("OI_CODEC_SBC_DecoderConfigureMSbc failed with error code {}", status); return false; } return true; } -void hfp_msbc_decoder_cleanup(void) { - memset(&hfp_msbc_decoder, 0, sizeof(hfp_msbc_decoder)); -} +void hfp_msbc_decoder_cleanup(void) { memset(&hfp_msbc_decoder, 0, sizeof(hfp_msbc_decoder)); } // Get the HFP MSBC encoded maximum frame size -bool hfp_msbc_decoder_decode_packet(const uint8_t* i_buf, int16_t* o_buf, - size_t out_len) { +bool hfp_msbc_decoder_decode_packet(const uint8_t* i_buf, int16_t* o_buf, size_t out_len) { if (out_len < HFP_MSBC_PCM_BYTES) { - log::error( - "Output buffer's size {} is less than one complete mSBC frame {}", - (unsigned long)out_len, HFP_MSBC_PCM_BYTES); + log::error("Output buffer's size {} is less than one complete mSBC frame {}", + (unsigned long)out_len, HFP_MSBC_PCM_BYTES); return false; } @@ -83,8 +78,8 @@ bool hfp_msbc_decoder_decode_packet(const uint8_t* i_buf, int16_t* o_buf, oi_size = HFP_MSBC_PKT_LEN; out_avail = out_len; - OI_STATUS status = OI_CODEC_SBC_DecodeFrame( - &hfp_msbc_decoder.decoder_context, &oi_data, &oi_size, o_buf, &out_avail); + OI_STATUS status = OI_CODEC_SBC_DecodeFrame(&hfp_msbc_decoder.decoder_context, &oi_data, &oi_size, + o_buf, &out_avail); if (!OI_SUCCESS(status) || out_avail != HFP_MSBC_PCM_BYTES || oi_size != 0) { log::error("Decoding failure: {}, {}, {}", status, (unsigned long)out_avail, (unsigned long)oi_size); diff --git a/system/stack/btm/neighbor_inquiry.h b/system/stack/btm/neighbor_inquiry.h index 8c9669c5e32..bf511eb5a18 100644 --- a/system/stack/btm/neighbor_inquiry.h +++ b/system/stack/btm/neighbor_inquiry.h @@ -42,8 +42,7 @@ enum : uint16_t { BTM_BLE_LIMITED_DISCOVERABLE = 0x0100, BTM_BLE_GENERAL_DISCOVERABLE = 0x0200, BTM_BLE_MAX_DISCOVERABLE = BTM_BLE_GENERAL_DISCOVERABLE, - BTM_BLE_DISCOVERABLE_MASK = - (BTM_BLE_LIMITED_DISCOVERABLE | BTM_BLE_GENERAL_DISCOVERABLE), + BTM_BLE_DISCOVERABLE_MASK = (BTM_BLE_LIMITED_DISCOVERABLE | BTM_BLE_GENERAL_DISCOVERABLE), }; /* Connectable modes */ @@ -121,8 +120,8 @@ typedef struct { /* Callback function for notifications when the BTM gets inquiry response. * First param is inquiry results database, second is pointer of EIR. */ -typedef void(tBTM_INQ_RESULTS_CB)(tBTM_INQ_RESULTS* p_inq_results, - const uint8_t* p_eir, uint16_t eir_len); +typedef void(tBTM_INQ_RESULTS_CB)(tBTM_INQ_RESULTS* p_inq_results, const uint8_t* p_eir, + uint16_t eir_len); typedef struct { uint32_t inq_count; /* Used for determining if a response has already been */ @@ -152,12 +151,11 @@ typedef struct { typedef struct { uint64_t time_of_resp; - uint32_t - inq_count; /* "timestamps" the entry with a particular inquiry count */ - /* Used for determining if a response has already been */ - /* received for the current inquiry operation. (We do not */ - /* want to flood the caller with multiple responses from */ - /* the same device. */ + uint32_t inq_count; /* "timestamps" the entry with a particular inquiry count */ + /* Used for determining if a response has already been */ + /* received for the current inquiry operation. (We do not */ + /* want to flood the caller with multiple responses from */ + /* the same device. */ tBTM_INQ_INFO inq_info; bool in_use; bool scan_rsp; @@ -185,16 +183,14 @@ typedef struct { long long start_time_ms; } tBTM_INQUIRY_CMPL; -inline std::string btm_inquiry_cmpl_status_text( - const tBTM_INQUIRY_CMPL::STATUS& status) { +inline std::string btm_inquiry_cmpl_status_text(const tBTM_INQUIRY_CMPL::STATUS& status) { switch (status) { CASE_RETURN_TEXT(tBTM_INQUIRY_CMPL::CANCELED); CASE_RETURN_TEXT(tBTM_INQUIRY_CMPL::TIMER_POPPED); CASE_RETURN_TEXT(tBTM_INQUIRY_CMPL::NOT_STARTED); CASE_RETURN_TEXT(tBTM_INQUIRY_CMPL::SSP_ACTIVE); default: - return std::string("UNKNOWN[") + std::to_string(status) + - std::string("]"); + return std::string("UNKNOWN[") + std::to_string(status) + std::string("]"); } } @@ -215,9 +211,8 @@ struct tBTM_INQUIRY_VAR_ST { uint32_t inq_counter; /* Counter incremented each time an inquiry completes */ /* Used for determining whether or not duplicate devices */ /* have responded to the same inquiry */ - tBTM_INQ_PARMS inqparms; /* Contains the parameters for the current inquiry */ - tBTM_INQUIRY_CMPL - inq_cmpl_info; /* Status and number of responses from the last inquiry */ + tBTM_INQ_PARMS inqparms; /* Contains the parameters for the current inquiry */ + tBTM_INQUIRY_CMPL inq_cmpl_info; /* Status and number of responses from the last inquiry */ uint16_t per_min_delay; /* Current periodic minimum delay */ uint16_t per_max_delay; /* Current periodic maximum delay */ @@ -226,8 +221,7 @@ struct tBTM_INQUIRY_VAR_ST { Clear) */ #define BTM_INQ_INACTIVE_STATE 0 -#define BTM_INQ_ACTIVE_STATE \ - 3 /* Actual inquiry or periodic inquiry is in progress */ +#define BTM_INQ_ACTIVE_STATE 3 /* Actual inquiry or periodic inquiry is in progress */ uint8_t state; /* Current state that the inquiry process is in */ uint8_t inq_active; /* Bit Mask indicating type of inquiry is active */ @@ -270,6 +264,5 @@ tINQ_DB_ENT* btm_inq_db_find(const RawAddress& p_bda); namespace fmt { template <> -struct formatter - : enum_formatter {}; +struct formatter : enum_formatter {}; } // namespace fmt diff --git a/system/stack/btm/power_mode.h b/system/stack/btm/power_mode.h index e21162dfd65..402937c14cb 100644 --- a/system/stack/btm/power_mode.h +++ b/system/stack/btm/power_mode.h @@ -32,9 +32,9 @@ enum : uint8_t { BTM_PM_STS_HOLD = HCI_MODE_HOLD, // 0x01 BTM_PM_STS_SNIFF = HCI_MODE_SNIFF, // 0x02 BTM_PM_STS_PARK = HCI_MODE_PARK, // 0x03 - BTM_PM_STS_SSR, /* report the SSR parameters in HCI_SNIFF_SUB_RATE_EVT */ - BTM_PM_STS_PENDING, /* when waiting for status from controller */ - BTM_PM_STS_ERROR /* when HCI command status returns error */ + BTM_PM_STS_SSR, /* report the SSR parameters in HCI_SNIFF_SUB_RATE_EVT */ + BTM_PM_STS_PENDING, /* when waiting for status from controller */ + BTM_PM_STS_ERROR /* when HCI command status returns error */ }; typedef uint8_t tBTM_PM_STATUS; @@ -65,7 +65,7 @@ enum : uint8_t { BTM_PM_MD_HOLD = HCI_MODE_HOLD, // 0x01 BTM_PM_MD_SNIFF = HCI_MODE_SNIFF, // 0x02 BTM_PM_MD_PARK = HCI_MODE_PARK, // 0x03 - BTM_PM_MD_FORCE = 0x10, /* OR this to force ACL link to a certain mode */ + BTM_PM_MD_FORCE = 0x10, /* OR this to force ACL link to a certain mode */ BTM_PM_MD_UNKNOWN = 0xEF, }; @@ -118,8 +118,7 @@ typedef struct { tBTM_PM_MODE mode = BTM_PM_MD_ACTIVE; // 0 } tBTM_PM_PWR_MD; -typedef void(tBTM_PM_STATUS_CBACK)(const RawAddress& p_bda, - tBTM_PM_STATUS status, uint16_t value, +typedef void(tBTM_PM_STATUS_CBACK)(const RawAddress& p_bda, tBTM_PM_STATUS status, uint16_t value, tHCI_STATUS hci_status); #define BTM_CONTRL_UNKNOWN 0 @@ -158,8 +157,7 @@ typedef void(tBTM_PM_STATUS_CBACK)(const RawAddress& p_bda, typedef uint32_t tBTM_CONTRL_STATE; -inline void set_num_acl_active_to_ctrl_state(uint32_t num, - tBTM_CONTRL_STATE& ctrl_state) { +inline void set_num_acl_active_to_ctrl_state(uint32_t num, tBTM_CONTRL_STATE& ctrl_state) { if (num > BTM_CONTRL_NUM_ACL_CLASSIC_ACTIVE_MASK) { num = BTM_CONTRL_NUM_ACL_CLASSIC_ACTIVE_MASK; } @@ -167,35 +165,29 @@ inline void set_num_acl_active_to_ctrl_state(uint32_t num, << BTM_CONTRL_NUM_ACL_CLASSIC_ACTIVE_SHIFT); } -inline void set_num_acl_sniff_to_ctrl_state(uint32_t num, - tBTM_CONTRL_STATE& ctrl_state) { +inline void set_num_acl_sniff_to_ctrl_state(uint32_t num, tBTM_CONTRL_STATE& ctrl_state) { if (num > BTM_CONTRL_NUM_ACL_CLASSIC_SNIFF_MASK) { num = BTM_CONTRL_NUM_ACL_CLASSIC_SNIFF_MASK; } - ctrl_state |= ((num & BTM_CONTRL_NUM_ACL_CLASSIC_SNIFF_MASK) - << BTM_CONTRL_NUM_ACL_CLASSIC_SNIFF_SHIFT); + ctrl_state |= + ((num & BTM_CONTRL_NUM_ACL_CLASSIC_SNIFF_MASK) << BTM_CONTRL_NUM_ACL_CLASSIC_SNIFF_SHIFT); } -inline void set_num_acl_le_to_ctrl_state(uint32_t num, - tBTM_CONTRL_STATE& ctrl_state) { +inline void set_num_acl_le_to_ctrl_state(uint32_t num, tBTM_CONTRL_STATE& ctrl_state) { if (num > BTM_CONTRL_NUM_ACL_LE_MASK) { num = BTM_CONTRL_NUM_ACL_LE_MASK; } - ctrl_state |= - ((num & BTM_CONTRL_NUM_ACL_LE_MASK) << BTM_CONTRL_NUM_ACL_LE_SHIFT); + ctrl_state |= ((num & BTM_CONTRL_NUM_ACL_LE_MASK) << BTM_CONTRL_NUM_ACL_LE_SHIFT); } -inline void set_num_le_adv_to_ctrl_state(uint32_t num, - tBTM_CONTRL_STATE& ctrl_state) { +inline void set_num_le_adv_to_ctrl_state(uint32_t num, tBTM_CONTRL_STATE& ctrl_state) { if (num > BTM_CONTRL_NUM_LE_ADV_MASK) { num = BTM_CONTRL_NUM_LE_ADV_MASK; } - ctrl_state |= - ((num & BTM_CONTRL_NUM_LE_ADV_MASK) << BTM_CONTRL_NUM_LE_ADV_SHIFT); + ctrl_state |= ((num & BTM_CONTRL_NUM_LE_ADV_MASK) << BTM_CONTRL_NUM_LE_ADV_SHIFT); } -inline void set_le_scan_mode_to_ctrl_state(uint32_t duty_cycle, - tBTM_CONTRL_STATE& ctrl_state) { +inline void set_le_scan_mode_to_ctrl_state(uint32_t duty_cycle, tBTM_CONTRL_STATE& ctrl_state) { uint32_t scan_mode; if (duty_cycle == 0) { scan_mode = BTM_CONTRL_LE_SCAN_MODE_IDLE; @@ -208,8 +200,7 @@ inline void set_le_scan_mode_to_ctrl_state(uint32_t duty_cycle, } else { scan_mode = BTM_CONTRL_LE_SCAN_MODE_LOW_LATENCY; } - ctrl_state |= ((scan_mode & BTM_CONTRL_LE_SCAN_MODE_MASK) - << BTM_CONTRL_LE_SCAN_MODE_SHIFT); + ctrl_state |= ((scan_mode & BTM_CONTRL_LE_SCAN_MODE_MASK) << BTM_CONTRL_LE_SCAN_MODE_SHIFT); } /******************************************************************************* @@ -223,8 +214,7 @@ inline void set_le_scan_mode_to_ctrl_state(uint32_t duty_cycle, * BTM_ILLEGAL_VALUE * ******************************************************************************/ -tBTM_STATUS BTM_PmRegister(uint8_t mask, uint8_t* p_pm_id, - tBTM_PM_STATUS_CBACK* p_cb); +tBTM_STATUS BTM_PmRegister(uint8_t mask, uint8_t* p_pm_id, tBTM_PM_STATUS_CBACK* p_cb); // Notified by ACL that a new link is connected void BTM_PM_OnConnected(uint16_t handle, const RawAddress& remote_bda); @@ -265,8 +255,8 @@ bool BTM_SetLinkPolicyActiveMode(const RawAddress& remote_bda); * BTM_CMD_STORED if the command is stored * ******************************************************************************/ -tBTM_STATUS BTM_SetSsrParams(const RawAddress& remote_bda, uint16_t max_lat, - uint16_t min_rmt_to, uint16_t min_loc_to); +tBTM_STATUS BTM_SetSsrParams(const RawAddress& remote_bda, uint16_t max_lat, uint16_t min_rmt_to, + uint16_t min_loc_to); /******************************************************************************* * diff --git a/system/stack/btm/sco_pkt_status.h b/system/stack/btm/sco_pkt_status.h index a945cf1f5ef..32914bbf6f0 100644 --- a/system/stack/btm/sco_pkt_status.h +++ b/system/stack/btm/sco_pkt_status.h @@ -40,7 +40,7 @@ struct tBTM_SCO_PKT_STATUS { // The timestamp of the first bit of |data|'s last update. uint64_t ts; - public: +public: void init() { std::fill(std::begin(data), std::end(data), 0); size = BTM_PKT_STATUS_LEN * 8; @@ -96,7 +96,9 @@ struct tBTM_SCO_PKT_STATUS { } } - if (i % 8) oss << std::hex << std::setw(2) << std::setfill('0') << +(byte); + if (i % 8) { + oss << std::hex << std::setw(2) << std::setfill('0') << +(byte); + } return oss.str(); } @@ -108,7 +110,7 @@ struct tBTM_SCO_PKT_STATUS { for (int i = 0; i < len; ++i) { int j = (head + i) % size; - s += std::to_string(((data[j / 8] >> (j % 8)) & 1U)); + s += std::to_string((data[j / 8] >> (j % 8)) & 1U); } return s; diff --git a/system/stack/btm/security_device_record.h b/system/stack/btm/security_device_record.h index aafca253391..cbe43d90be5 100644 --- a/system/stack/btm/security_device_record.h +++ b/system/stack/btm/security_device_record.h @@ -54,13 +54,11 @@ typedef struct { #define BTM_SEC_OUT_FLAGS (BTM_SEC_OUT_AUTHENTICATE | BTM_SEC_OUT_ENCRYPT) #define BTM_SEC_IN_FLAGS (BTM_SEC_IN_AUTHENTICATE | BTM_SEC_IN_ENCRYPT) -#define BTM_SEC_OUT_LEVEL4_FLAGS \ - (BTM_SEC_OUT_AUTHENTICATE | BTM_SEC_OUT_ENCRYPT | BTM_SEC_OUT_MITM | \ - BTM_SEC_MODE4_LEVEL4) +#define BTM_SEC_OUT_LEVEL4_FLAGS \ + (BTM_SEC_OUT_AUTHENTICATE | BTM_SEC_OUT_ENCRYPT | BTM_SEC_OUT_MITM | BTM_SEC_MODE4_LEVEL4) -#define BTM_SEC_IN_LEVEL4_FLAGS \ - (BTM_SEC_IN_AUTHENTICATE | BTM_SEC_IN_ENCRYPT | BTM_SEC_IN_MITM | \ - BTM_SEC_MODE4_LEVEL4) +#define BTM_SEC_IN_LEVEL4_FLAGS \ + (BTM_SEC_IN_AUTHENTICATE | BTM_SEC_IN_ENCRYPT | BTM_SEC_IN_MITM | BTM_SEC_MODE4_LEVEL4) typedef struct { uint32_t mx_proto_id; /* Service runs over this multiplexer protocol */ uint32_t orig_mx_chan_id; /* Channel on the multiplexer protocol */ @@ -81,13 +79,13 @@ typedef struct { Octet16 lltk; /* local long term key */ Octet16 lcsrk; /* local SRK peer device used to secured sign local data */ - BT_OCTET8 rand; /* random vector for LTK generation */ - uint16_t ediv; /* LTK diversifier of this peripheral device */ - uint16_t div; /* local DIV to generate local LTK=d1(ER,DIV,0) and - CSRK=d1(ER,DIV,1) */ - uint8_t sec_level; /* local pairing security level */ - uint8_t key_size; /* key size of the LTK delivered to peer device */ - uint8_t srk_sec_level; /* security property of peer SRK for this device */ + BT_OCTET8 rand; /* random vector for LTK generation */ + uint16_t ediv; /* LTK diversifier of this peripheral device */ + uint16_t div; /* local DIV to generate local LTK=d1(ER,DIV,0) and + CSRK=d1(ER,DIV,1) */ + uint8_t sec_level; /* local pairing security level */ + uint8_t key_size; /* key size of the LTK delivered to peer device */ + uint8_t srk_sec_level; /* security property of peer SRK for this device */ uint8_t local_csrk_sec_level; /* security property of local CSRK for this device */ @@ -105,10 +103,10 @@ enum tBLE_RAND_ADDR_TYPE : uint8_t { }; class tBTM_BLE_ADDR_INFO { - public: +public: RawAddress pseudo_addr; /* LE pseudo address of the device if different from device address */ - public: +public: tBLE_ADDR_TYPE AddressType() const { return ble_addr_type_; } void SetAddressType(tBLE_ADDR_TYPE ble_addr_type) { if (is_ble_addr_type_known(ble_addr_type)) { @@ -127,7 +125,7 @@ class tBTM_BLE_ADDR_INFO { tBLE_RAND_ADDR_TYPE active_addr_type; - private: +private: tBLE_ADDR_TYPE ble_addr_type_; /* LE device type: public or random address */ }; @@ -193,12 +191,11 @@ typedef enum : uint8_t { BTM_SM4_UNKNOWN = 0x00, BTM_SM4_KNOWN = 0x10, BTM_SM4_TRUE = 0x11, - BTM_SM4_REQ_PEND = 0x08, /* set this bit when getting remote features */ - BTM_SM4_UPGRADE = 0x04, /* set this bit when upgrading link key */ - BTM_SM4_RETRY = 0x02, /* set this bit to retry on HCI_ERR_KEY_MISSING or \ - HCI_ERR_LMP_ERR_TRANS_COLLISION */ - BTM_SM4_DD_ACP = - 0x20, /* set this bit to indicate peer initiated dedicated bonding */ + BTM_SM4_REQ_PEND = 0x08, /* set this bit when getting remote features */ + BTM_SM4_UPGRADE = 0x04, /* set this bit when upgrading link key */ + BTM_SM4_RETRY = 0x02, /* set this bit to retry on HCI_ERR_KEY_MISSING or \ + HCI_ERR_LMP_ERR_TRANS_COLLISION */ + BTM_SM4_DD_ACP = 0x20, /* set this bit to indicate peer initiated dedicated bonding */ BTM_SM4_CONN_PEND = 0x40, /* set this bit to indicate accepting acl conn; to be cleared on \ btm_acl_created */ } tBTM_SM4_BIT; @@ -220,10 +217,10 @@ struct tBTM_SEC_REC { tBTM_SEC_CALLBACK* p_callback; void* p_ref_data; - bool link_key_not_sent; /* link key notification has not been sent waiting for - name */ - tBTM_IO_CAP rmt_io_caps; /* IO capability of the peer device */ - tBTM_AUTH_REQ rmt_auth_req; /* the auth_req flag as in the IO caps rsp evt */ + bool link_key_not_sent; /* link key notification has not been sent waiting for + name */ + tBTM_IO_CAP rmt_io_caps; /* IO capability of the peer device */ + tBTM_AUTH_REQ rmt_auth_req; /* the auth_req flag as in the IO caps rsp evt */ bool new_encryption_key_is_p256; /* Set to true when the newly generated LK ** is generated from P-256. ** Link encrypted with such LK can be used @@ -239,10 +236,8 @@ struct tBTM_SEC_REC { tBTM_BOND_TYPE bond_type; /* bond type */ - public: - bool is_device_authenticated() const { - return sec_flags & BTM_SEC_AUTHENTICATED; - } +public: + bool is_device_authenticated() const { return sec_flags & BTM_SEC_AUTHENTICATED; } void set_device_authenticated() { sec_flags |= BTM_SEC_AUTHENTICATED; } void reset_device_authenticated() { sec_flags &= ~BTM_SEC_AUTHENTICATED; } @@ -258,51 +253,31 @@ struct tBTM_SEC_REC { void set_link_key_known() { sec_flags |= BTM_SEC_LINK_KEY_KNOWN; } void reset_link_key_known() { sec_flags &= ~BTM_SEC_LINK_KEY_KNOWN; } - bool is_link_key_authenticated() const { - return sec_flags & BTM_SEC_LINK_KEY_AUTHED; - } + bool is_link_key_authenticated() const { return sec_flags & BTM_SEC_LINK_KEY_AUTHED; } void set_link_key_authenticated() { sec_flags |= BTM_SEC_LINK_KEY_AUTHED; } void reset_link_key_authenticated() { sec_flags &= ~BTM_SEC_LINK_KEY_AUTHED; } - bool is_le_device_authenticated() const { - return sec_flags & BTM_SEC_LE_AUTHENTICATED; - } + bool is_le_device_authenticated() const { return sec_flags & BTM_SEC_LE_AUTHENTICATED; } void set_le_device_authenticated() { sec_flags |= BTM_SEC_LE_AUTHENTICATED; } - void reset_le_device_authenticated() { - sec_flags &= ~BTM_SEC_LE_AUTHENTICATED; - } + void reset_le_device_authenticated() { sec_flags &= ~BTM_SEC_LE_AUTHENTICATED; } - bool is_le_device_encrypted() const { - return sec_flags & BTM_SEC_LE_ENCRYPTED; - } + bool is_le_device_encrypted() const { return sec_flags & BTM_SEC_LE_ENCRYPTED; } void set_le_device_encrypted() { sec_flags |= BTM_SEC_LE_ENCRYPTED; } void reset_le_device_encrypted() { sec_flags &= ~BTM_SEC_LE_ENCRYPTED; } - bool is_le_link_key_known() const { - return sec_flags & BTM_SEC_LE_LINK_KEY_KNOWN; - } + bool is_le_link_key_known() const { return sec_flags & BTM_SEC_LE_LINK_KEY_KNOWN; } void set_le_link_key_known() { sec_flags |= BTM_SEC_LE_LINK_KEY_KNOWN; } void reset_le_link_key_known() { sec_flags &= ~BTM_SEC_LE_LINK_KEY_KNOWN; } - bool is_le_link_key_authenticated() const { - return sec_flags & BTM_SEC_LE_LINK_KEY_AUTHED; - } - void set_le_link_key_authenticated() { - sec_flags |= BTM_SEC_LE_LINK_KEY_AUTHED; - } - void reset_le_link_key_authenticated() { - sec_flags &= ~BTM_SEC_LE_LINK_KEY_AUTHED; - } + bool is_le_link_key_authenticated() const { return sec_flags & BTM_SEC_LE_LINK_KEY_AUTHED; } + void set_le_link_key_authenticated() { sec_flags |= BTM_SEC_LE_LINK_KEY_AUTHED; } + void reset_le_link_key_authenticated() { sec_flags &= ~BTM_SEC_LE_LINK_KEY_AUTHED; } bool is_le_link_16_digit_key_authenticated() const { return sec_flags & BTM_SEC_16_DIGIT_PIN_AUTHED; } - void set_le_link_16_digit_key_authenticated() { - sec_flags |= BTM_SEC_16_DIGIT_PIN_AUTHED; - } - void reset_le_link_16_digit_key_authenticated() { - sec_flags &= ~BTM_SEC_16_DIGIT_PIN_AUTHED; - } + void set_le_link_16_digit_key_authenticated() { sec_flags |= BTM_SEC_16_DIGIT_PIN_AUTHED; } + void reset_le_link_16_digit_key_authenticated() { sec_flags &= ~BTM_SEC_16_DIGIT_PIN_AUTHED; } bool is_security_state_idle() const { return sec_state == tSECURITY_STATE::IDLE; } bool is_security_state_authenticating() const { @@ -315,8 +290,7 @@ struct tBTM_SEC_REC { return sec_state == tSECURITY_STATE::LE_ENCRYPTING; } bool is_security_state_encrypting() const { - return (is_security_state_bredr_encrypting() || - is_security_state_le_encrypting()); + return is_security_state_bredr_encrypting() || is_security_state_le_encrypting(); } bool is_security_state_getting_name() const { return sec_state == tSECURITY_STATE::GETTING_NAME; } bool is_security_state_authorizing() const { return sec_state == tSECURITY_STATE::AUTHORIZING; } @@ -337,12 +311,8 @@ struct tBTM_SEC_REC { } bool is_bond_type_unknown() const { return bond_type == BOND_TYPE_UNKNOWN; } - bool is_bond_type_persistent() const { - return bond_type == BOND_TYPE_PERSISTENT; - } - bool is_bond_type_temporary() const { - return bond_type == BOND_TYPE_TEMPORARY; - } + bool is_bond_type_persistent() const { return bond_type == BOND_TYPE_PERSISTENT; } + bool is_bond_type_temporary() const { return bond_type == BOND_TYPE_TEMPORARY; } uint8_t get_encryption_key_size() const { return enc_key_size; } @@ -350,32 +320,28 @@ struct tBTM_SEC_REC { std::string ToString() const { return base::StringPrintf( - "bredr_linkkey_known:%c,le_linkkey_known:%c," - "bond_type:%s," - "bredr_linkkey_type:%s," - "ble_enc_key_size:%d," - "bredr_authenticated:%c,le_authenticated:%c," - "16_digit_key_authenticated:%c," - "bredr_encrypted:%c,le_encrypted:%c", - is_link_key_known() ? 'T' : 'F', is_le_link_key_known() ? 'T' : 'F', - bond_type_text(bond_type).c_str(), - linkkey_type_text(link_key_type).c_str(), enc_key_size, - is_device_authenticated() ? 'T' : 'F', - is_le_device_authenticated() ? 'T' : 'F', - is_le_link_16_digit_key_authenticated() ? 'T' : 'F', - is_device_encrypted() ? 'T' : 'F', - is_le_device_encrypted() ? 'T' : 'F'); + "bredr_linkkey_known:%c,le_linkkey_known:%c," + "bond_type:%s," + "bredr_linkkey_type:%s," + "ble_enc_key_size:%d," + "bredr_authenticated:%c,le_authenticated:%c," + "16_digit_key_authenticated:%c," + "bredr_encrypted:%c,le_encrypted:%c", + is_link_key_known() ? 'T' : 'F', is_le_link_key_known() ? 'T' : 'F', + bond_type_text(bond_type).c_str(), linkkey_type_text(link_key_type).c_str(), + enc_key_size, is_device_authenticated() ? 'T' : 'F', + is_le_device_authenticated() ? 'T' : 'F', + is_le_link_16_digit_key_authenticated() ? 'T' : 'F', is_device_encrypted() ? 'T' : 'F', + is_le_device_encrypted() ? 'T' : 'F'); } }; class tBTM_SEC_DEV_REC { - public: +public: RawAddress RemoteAddress() const { return bd_addr; } /* Data length extension */ - void set_suggested_tx_octect(uint16_t octets) { - suggested_tx_octets = octets; - } + void set_suggested_tx_octect(uint16_t octets) { suggested_tx_octets = octets; } uint16_t get_suggested_tx_octets() const { return suggested_tx_octets; } bool IsLocallyInitiated() const { return is_originator; } @@ -383,46 +349,37 @@ class tBTM_SEC_DEV_REC { uint16_t get_br_edr_hci_handle() const { return hci_handle; } uint16_t get_ble_hci_handle() const { return ble_hci_handle; } - bool is_device_type_br_edr() const { - return device_type == BT_DEVICE_TYPE_BREDR; - } + bool is_device_type_br_edr() const { return device_type == BT_DEVICE_TYPE_BREDR; } bool is_device_type_ble() const { return device_type == BT_DEVICE_TYPE_BLE; } - bool is_device_type_dual_mode() const { - return device_type == BT_DEVICE_TYPE_DUMO; - } + bool is_device_type_dual_mode() const { return device_type == BT_DEVICE_TYPE_DUMO; } - bool is_device_type_has_ble() const { - return device_type & BT_DEVICE_TYPE_BLE; - } + bool is_device_type_has_ble() const { return device_type & BT_DEVICE_TYPE_BLE; } - bool SupportsSecureConnections() const { - return remote_supports_secure_connections; - } + bool SupportsSecureConnections() const { return remote_supports_secure_connections; } std::string ToString() const { return base::StringPrintf( - "%s %6s cod:%s remote_info:%-14s sm4:0x%02x SecureConn:%c name:\"%s\"" - "sec_prop:%s", - ADDRESS_TO_LOGGABLE_CSTR(bd_addr), DeviceTypeText(device_type).c_str(), - dev_class_text(dev_class).c_str(), - remote_version_info.ToString().c_str(), sm4, - (remote_supports_secure_connections) ? 'T' : 'F', - PRIVATE_NAME(sec_bd_name), sec_rec.ToString().c_str()); + "%s %6s cod:%s remote_info:%-14s sm4:0x%02x SecureConn:%c name:\"%s\"" + "sec_prop:%s", + ADDRESS_TO_LOGGABLE_CSTR(bd_addr), DeviceTypeText(device_type).c_str(), + dev_class_text(dev_class).c_str(), remote_version_info.ToString().c_str(), sm4, + (remote_supports_secure_connections) ? 'T' : 'F', PRIVATE_NAME(sec_bd_name), + sec_rec.ToString().c_str()); } - public: +public: RawAddress bd_addr; /* BD_ADDR of the device */ tBTM_BLE_ADDR_INFO ble; - BD_NAME sec_bd_name; /* User friendly name of the device. (may be - truncated to save space in dev_rec table) */ - DEV_CLASS dev_class; /* DEV_CLASS of the device */ + BD_NAME sec_bd_name; /* User friendly name of the device. (may be + truncated to save space in dev_rec table) */ + DEV_CLASS dev_class; /* DEV_CLASS of the device */ tBT_DEVICE_TYPE device_type; uint32_t timestamp; /* Timestamp of the last connection */ uint16_t hci_handle; /* Handle to BR/EDR ACL connection when exists */ uint16_t ble_hci_handle; /* use in DUMO connection */ - uint16_t suggested_tx_octets; /* Recently suggested tx octects for data length + uint16_t suggested_tx_octets; /* Recently suggested tx octets for data length extension */ uint16_t clock_offset; /* Latest known clock offset */ @@ -454,8 +411,7 @@ class tBTM_SEC_DEV_REC { namespace fmt { template <> -struct formatter - : string_formatter {}; +struct formatter : string_formatter {}; template <> struct formatter : enum_formatter {}; } // namespace fmt diff --git a/system/stack/btm/security_event_parser.cc b/system/stack/btm/security_event_parser.cc index 3e0dc4ab95b..4de55a16cb5 100644 --- a/system/stack/btm/security_event_parser.cc +++ b/system/stack/btm/security_event_parser.cc @@ -46,9 +46,8 @@ static void log_address_and_status(const Address& bda, EventCode event_code, uint16_t reason = android::bluetooth::hci::STATUS_UNKNOWN; uint16_t handle = bluetooth::common::kUnknownConnectionHandle; int64_t value = 0; - log_classic_pairing_event(ToRawAddress(bda), handle, cmd, - static_cast(event_code), status, reason, - value); + log_classic_pairing_event(ToRawAddress(bda), handle, cmd, static_cast(event_code), + status, reason, value); } static void log_address(const Address& bda, EventCode event_code) { uint32_t cmd = android::bluetooth::hci::CMD_UNKNOWN; @@ -56,14 +55,12 @@ static void log_address(const Address& bda, EventCode event_code) { uint16_t reason = android::bluetooth::hci::STATUS_UNKNOWN; uint16_t handle = bluetooth::common::kUnknownConnectionHandle; int64_t value = 0; - log_classic_pairing_event(ToRawAddress(bda), handle, cmd, - static_cast(event_code), status, reason, - value); + log_classic_pairing_event(ToRawAddress(bda), handle, cmd, static_cast(event_code), + status, reason, value); } static void parse_encryption_change(const EventView event) { auto change_opt = EncryptionChangeView::CreateOptional(event); - log::assert_that(change_opt.has_value(), - "assert failed: change_opt.has_value()"); + log::assert_that(change_opt.has_value(), "assert failed: change_opt.has_value()"); auto change = change_opt.value(); ErrorCode status = change.GetStatus(); @@ -72,53 +69,44 @@ static void parse_encryption_change(const EventView event) { btm_sec_encryption_change_evt(handle, static_cast(status), static_cast(encr_enable)); - log_classic_pairing_event(ToRawAddress(Address::kEmpty), handle, - android::bluetooth::hci::CMD_UNKNOWN, - static_cast(change.GetEventCode()), - static_cast(status), - android::bluetooth::hci::STATUS_UNKNOWN, 0); + log_classic_pairing_event( + ToRawAddress(Address::kEmpty), handle, android::bluetooth::hci::CMD_UNKNOWN, + static_cast(change.GetEventCode()), static_cast(status), + android::bluetooth::hci::STATUS_UNKNOWN, 0); } static void parse_change_connection_link_key_complete(const EventView event) { - auto complete_opt = - ChangeConnectionLinkKeyCompleteView::CreateOptional(event); - log::assert_that(complete_opt.has_value(), - "assert failed: complete_opt.has_value()"); + auto complete_opt = ChangeConnectionLinkKeyCompleteView::CreateOptional(event); + log::assert_that(complete_opt.has_value(), "assert failed: complete_opt.has_value()"); auto complete = complete_opt.value(); - log_classic_pairing_event(ToRawAddress(Address::kEmpty), - complete.GetConnectionHandle(), - android::bluetooth::hci::CMD_UNKNOWN, - static_cast(complete.GetEventCode()), - static_cast(complete.GetStatus()), - android::bluetooth::hci::STATUS_UNKNOWN, 0); + log_classic_pairing_event( + ToRawAddress(Address::kEmpty), complete.GetConnectionHandle(), + android::bluetooth::hci::CMD_UNKNOWN, static_cast(complete.GetEventCode()), + static_cast(complete.GetStatus()), android::bluetooth::hci::STATUS_UNKNOWN, 0); } static void parse_central_link_key_complete(const EventView event) { auto event_opt = CentralLinkKeyCompleteView::CreateOptional(event); - log::assert_that(event_opt.has_value(), - "assert failed: event_opt.has_value()"); + log::assert_that(event_opt.has_value(), "assert failed: event_opt.has_value()"); auto complete = event_opt.value(); log::info("Unhandled event: {}", EventCodeText(event.GetEventCode())); } static void parse_return_link_keys(const EventView event) { auto event_opt = ReturnLinkKeysView::CreateOptional(event); - log::assert_that(event_opt.has_value(), - "assert failed: event_opt.has_value()"); + log::assert_that(event_opt.has_value(), "assert failed: event_opt.has_value()"); auto view = event_opt.value(); log::info("Unhandled event: {}", EventCodeText(event.GetEventCode())); } static void parse_pin_code_request(const EventView event) { auto event_opt = PinCodeRequestView::CreateOptional(event); - log::assert_that(event_opt.has_value(), - "assert failed: event_opt.has_value()"); + log::assert_that(event_opt.has_value(), "assert failed: event_opt.has_value()"); auto request = event_opt.value(); btm_sec_pin_code_request(ToRawAddress(request.GetBdAddr())); } static void parse_link_key_request(const EventView event) { auto event_opt = LinkKeyRequestView::CreateOptional(event); - log::assert_that(event_opt.has_value(), - "assert failed: event_opt.has_value()"); + log::assert_that(event_opt.has_value(), "assert failed: event_opt.has_value()"); auto request = event_opt.value(); btm_sec_link_key_request(ToRawAddress(request.GetBdAddr())); @@ -126,29 +114,24 @@ static void parse_link_key_request(const EventView event) { } static void parse_link_key_notification(const EventView event) { auto event_opt = LinkKeyNotificationView::CreateOptional(event); - log::assert_that(event_opt.has_value(), - "assert failed: event_opt.has_value()"); + log::assert_that(event_opt.has_value(), "assert failed: event_opt.has_value()"); auto notification = event_opt.value(); - btm_sec_link_key_notification( - ToRawAddress(notification.GetBdAddr()), notification.GetLinkKey(), - static_cast(notification.GetKeyType())); + btm_sec_link_key_notification(ToRawAddress(notification.GetBdAddr()), notification.GetLinkKey(), + static_cast(notification.GetKeyType())); log_address(notification.GetBdAddr(), event.GetEventCode()); } static void parse_encryption_key_refresh_complete(const EventView event) { auto event_opt = EncryptionKeyRefreshCompleteView::CreateOptional(event); - log::assert_that(event_opt.has_value(), - "assert failed: event_opt.has_value()"); + log::assert_that(event_opt.has_value(), "assert failed: event_opt.has_value()"); auto refresh = event_opt.value(); - btm_sec_encryption_key_refresh_complete( - refresh.GetConnectionHandle(), - static_cast(refresh.GetStatus())); + btm_sec_encryption_key_refresh_complete(refresh.GetConnectionHandle(), + static_cast(refresh.GetStatus())); } static void parse_io_capabilities_req(const EventView event) { auto event_opt = IoCapabilityRequestView::CreateOptional(event); - log::assert_that(event_opt.has_value(), - "assert failed: event_opt.has_value()"); + log::assert_that(event_opt.has_value(), "assert failed: event_opt.has_value()"); auto request = event_opt.value(); RawAddress peer = ToRawAddress(request.GetBdAddr()); @@ -158,16 +141,14 @@ static void parse_io_capabilities_req(const EventView event) { } static void parse_io_capabilities_rsp(const EventView event) { auto response_opt = IoCapabilityResponseView::CreateOptional(event); - log::assert_that(response_opt.has_value(), - "assert failed: response_opt.has_value()"); + log::assert_that(response_opt.has_value(), "assert failed: response_opt.has_value()"); auto response = response_opt.value(); tBTM_SP_IO_RSP evt_data{ - .bd_addr = ToRawAddress(response.GetBdAddr()), - .io_cap = static_cast(response.GetIoCapability()), - .oob_data = static_cast(response.GetOobDataPresent()), - .auth_req = - static_cast(response.GetAuthenticationRequirements()), + .bd_addr = ToRawAddress(response.GetBdAddr()), + .io_cap = static_cast(response.GetIoCapability()), + .oob_data = static_cast(response.GetOobDataPresent()), + .auth_req = static_cast(response.GetAuthenticationRequirements()), }; btm_io_capabilities_rsp(evt_data); @@ -175,8 +156,7 @@ static void parse_io_capabilities_rsp(const EventView event) { } static void parse_remote_oob_data_request(const EventView event) { auto event_opt = RemoteOobDataRequestView::CreateOptional(event); - log::assert_that(event_opt.has_value(), - "assert failed: event_opt.has_value()"); + log::assert_that(event_opt.has_value(), "assert failed: event_opt.has_value()"); auto request = event_opt.value(); btm_rem_oob_req(ToRawAddress(request.GetBdAddr())); @@ -184,30 +164,25 @@ static void parse_remote_oob_data_request(const EventView event) { } static void parse_simple_pairing_complete(const EventView event) { auto event_opt = SimplePairingCompleteView::CreateOptional(event); - log::assert_that(event_opt.has_value(), - "assert failed: event_opt.has_value()"); + log::assert_that(event_opt.has_value(), "assert failed: event_opt.has_value()"); auto complete = event_opt.value(); btm_simple_pair_complete(ToRawAddress(complete.GetBdAddr()), static_cast(complete.GetStatus())); - log_address_and_status(complete.GetBdAddr(), event.GetEventCode(), - complete.GetStatus()); + log_address_and_status(complete.GetBdAddr(), event.GetEventCode(), complete.GetStatus()); } static void parse_user_passkey_notification(const EventView event) { auto event_opt = UserPasskeyNotificationView::CreateOptional(event); - log::assert_that(event_opt.has_value(), - "assert failed: event_opt.has_value()"); + log::assert_that(event_opt.has_value(), "assert failed: event_opt.has_value()"); auto notification = event_opt.value(); - btm_proc_sp_req_evt(BTM_SP_KEY_NOTIF_EVT, - ToRawAddress(notification.GetBdAddr()), + btm_proc_sp_req_evt(BTM_SP_KEY_NOTIF_EVT, ToRawAddress(notification.GetBdAddr()), notification.GetPasskey()); log_address(notification.GetBdAddr(), event.GetEventCode()); } static void parse_keypress_notification(const EventView event) { auto event_opt = KeypressNotificationView::CreateOptional(event); - log::assert_that(event_opt.has_value(), - "assert failed: event_opt.has_value()"); + log::assert_that(event_opt.has_value(), "assert failed: event_opt.has_value()"); auto notification = event_opt.value(); log::info("Unhandled event: {}", EventCodeText(event.GetEventCode())); @@ -215,8 +190,7 @@ static void parse_keypress_notification(const EventView event) { } static void parse_user_confirmation_request(const EventView event) { auto event_opt = UserConfirmationRequestView::CreateOptional(event); - log::assert_that(event_opt.has_value(), - "assert failed: event_opt.has_value()"); + log::assert_that(event_opt.has_value(), "assert failed: event_opt.has_value()"); auto request = event_opt.value(); btm_proc_sp_req_evt(BTM_SP_CFM_REQ_EVT, ToRawAddress(request.GetBdAddr()), @@ -225,8 +199,7 @@ static void parse_user_confirmation_request(const EventView event) { } static void parse_user_passkey_request(const EventView event) { auto event_opt = UserPasskeyRequestView::CreateOptional(event); - log::assert_that(event_opt.has_value(), - "assert failed: event_opt.has_value()"); + log::assert_that(event_opt.has_value(), "assert failed: event_opt.has_value()"); auto request = event_opt.value(); btm_proc_sp_req_evt(BTM_SP_KEY_REQ_EVT, ToRawAddress(request.GetBdAddr()), diff --git a/system/stack/btm/security_event_parser.h b/system/stack/btm/security_event_parser.h index f29e3724e6b..fba1697d8d4 100644 --- a/system/stack/btm/security_event_parser.h +++ b/system/stack/btm/security_event_parser.h @@ -21,7 +21,7 @@ namespace bluetooth::stack::btm { class SecurityEventParser { - public: +public: SecurityEventParser() = default; virtual ~SecurityEventParser() = default; void OnSecurityEvent(bluetooth::hci::EventView event); diff --git a/system/stack/btu/btu_hcif.cc b/system/stack/btu/btu_hcif.cc index 94543783349..68653974cc2 100644 --- a/system/stack/btu/btu_hcif.cc +++ b/system/stack/btu/btu_hcif.cc @@ -69,9 +69,9 @@ using namespace bluetooth; using base::Location; using bluetooth::hci::IsoManager; -bool BTM_BLE_IS_RESOLVE_BDA(const RawAddress& x); // TODO remove -void BTA_sys_signal_hw_error(); // TODO remove -void smp_cancel_start_encryption_attempt(); // TODO remove +bool BTM_BLE_IS_RESOLVE_BDA(const RawAddress& x); // TODO remove +void BTA_sys_signal_hw_error(); // TODO remove +void smp_cancel_start_encryption_attempt(); // TODO remove void acl_disconnect_from_handle(uint16_t handle, tHCI_STATUS reason, std::string comment); // TODO remove @@ -80,11 +80,9 @@ void acl_disconnect_from_handle(uint16_t handle, tHCI_STATUS reason, /******************************************************************************/ static void btu_hcif_authentication_comp_evt(uint8_t* p); static void btu_hcif_encryption_change_evt(uint8_t* p); -static void btu_hcif_read_rmt_ext_features_comp_evt(uint8_t* p, - uint8_t evt_len); +static void btu_hcif_read_rmt_ext_features_comp_evt(uint8_t* p, uint8_t evt_len); static void btu_hcif_command_complete_evt(BT_HDR* response, void* context); -static void btu_hcif_command_status_evt(uint8_t status, BT_HDR* command, - void* context); +static void btu_hcif_command_status_evt(uint8_t status, BT_HDR* command, void* context); static void btu_hcif_mode_change_evt(uint8_t* p); static void btu_hcif_link_key_notification_evt(const uint8_t* p); static void btu_hcif_read_clock_off_comp_evt(uint8_t* p); @@ -100,12 +98,9 @@ static void btu_hcif_proc_sp_req_evt(tBTM_SP_EVT event, const uint8_t* p); static void btu_hcif_rem_oob_req(const uint8_t* p); static void btu_hcif_simple_pair_complete(const uint8_t* p); static void btu_hcif_proc_sp_req_evt(const tBTM_SP_EVT event, const uint8_t* p); -static void btu_hcif_create_conn_cancel_complete(const uint8_t* p, - uint16_t evt_len); -static void btu_hcif_read_local_oob_complete(const uint8_t* p, - uint16_t evt_len); -static void btu_hcif_read_local_oob_extended_complete(const uint8_t* p, - uint16_t evt_len); +static void btu_hcif_create_conn_cancel_complete(const uint8_t* p, uint16_t evt_len); +static void btu_hcif_read_local_oob_complete(const uint8_t* p, uint16_t evt_len); +static void btu_hcif_read_local_oob_extended_complete(const uint8_t* p, uint16_t evt_len); /* Simple Pairing Events */ static void btu_hcif_io_cap_request_evt(const uint8_t* p); @@ -119,8 +114,7 @@ static void btu_hcif_encryption_key_refresh_cmpl_evt(uint8_t* p); * @param evt_code event code * @param p_event pointer to event parameter, skipping paremter length */ -static void btu_hcif_log_event_metrics(uint8_t evt_code, - const uint8_t* p_event) { +static void btu_hcif_log_event_metrics(uint8_t evt_code, const uint8_t* p_event) { uint32_t cmd = android::bluetooth::hci::CMD_UNKNOWN; uint16_t status = android::bluetooth::hci::STATUS_UNKNOWN; uint16_t reason = android::bluetooth::hci::STATUS_UNKNOWN; @@ -139,30 +133,26 @@ static void btu_hcif_log_event_metrics(uint8_t evt_code, case HCI_KEYPRESS_NOTIFY_EVT: case HCI_REMOTE_OOB_DATA_REQUEST_EVT: STREAM_TO_BDADDR(bda, p_event); - log_classic_pairing_event(bda, handle, cmd, evt_code, status, reason, - value); + log_classic_pairing_event(bda, handle, cmd, evt_code, status, reason, value); break; case HCI_SIMPLE_PAIRING_COMPLETE_EVT: case HCI_RMT_NAME_REQUEST_COMP_EVT: STREAM_TO_UINT8(status, p_event); STREAM_TO_BDADDR(bda, p_event); - log_classic_pairing_event(bda, handle, cmd, evt_code, status, reason, - value); + log_classic_pairing_event(bda, handle, cmd, evt_code, status, reason, value); break; case HCI_AUTHENTICATION_COMP_EVT: STREAM_TO_UINT8(status, p_event); STREAM_TO_UINT16(handle, p_event); handle = HCID_GET_HANDLE(handle); - log_classic_pairing_event(bda, handle, cmd, evt_code, status, reason, - value); + log_classic_pairing_event(bda, handle, cmd, evt_code, status, reason, value); break; case HCI_ENCRYPTION_CHANGE_EVT: { uint8_t encryption_enabled; STREAM_TO_UINT8(status, p_event); STREAM_TO_UINT16(handle, p_event); STREAM_TO_UINT8(encryption_enabled, p_event); - log_classic_pairing_event(bda, handle, cmd, evt_code, status, reason, - encryption_enabled); + log_classic_pairing_event(bda, handle, cmd, evt_code, status, reason, encryption_enabled); break; } case HCI_ESCO_CONNECTION_COMP_EVT: { @@ -172,19 +162,18 @@ static void btu_hcif_log_event_metrics(uint8_t evt_code, STREAM_TO_BDADDR(bda, p_event); STREAM_TO_UINT8(link_type, p_event); handle = HCID_GET_HANDLE(handle); - log_link_layer_connection_event( - &bda, handle, android::bluetooth::DIRECTION_UNKNOWN, link_type, cmd, - evt_code, android::bluetooth::hci::BLE_EVT_UNKNOWN, status, reason); + log_link_layer_connection_event(&bda, handle, android::bluetooth::DIRECTION_UNKNOWN, + link_type, cmd, evt_code, + android::bluetooth::hci::BLE_EVT_UNKNOWN, status, reason); break; } case HCI_ESCO_CONNECTION_CHANGED_EVT: { STREAM_TO_UINT8(status, p_event); STREAM_TO_UINT16(handle, p_event); handle = HCID_GET_HANDLE(handle); - log_link_layer_connection_event( - nullptr, handle, android::bluetooth::DIRECTION_UNKNOWN, - android::bluetooth::LINK_TYPE_UNKNOWN, cmd, evt_code, - android::bluetooth::hci::BLE_EVT_UNKNOWN, status, reason); + log_link_layer_connection_event(nullptr, handle, android::bluetooth::DIRECTION_UNKNOWN, + android::bluetooth::LINK_TYPE_UNKNOWN, cmd, evt_code, + android::bluetooth::hci::BLE_EVT_UNKNOWN, status, reason); break; } // Ignore these events @@ -193,14 +182,14 @@ static void btu_hcif_log_event_metrics(uint8_t evt_code, case HCI_VENDOR_SPECIFIC_EVT: break; - case HCI_CONNECTION_COMP_EVT: // EventCode::CONNECTION_COMPLETE + case HCI_CONNECTION_COMP_EVT: // EventCode::CONNECTION_COMPLETE case HCI_CONNECTION_REQUEST_EVT: // EventCode::CONNECTION_REQUEST case HCI_DISCONNECTION_COMP_EVT: // EventCode::DISCONNECTION_COMPLETE default: log::error( - "Unexpectedly received event_code:0x{:02x} that should not be " - "handled here", - evt_code); + "Unexpectedly received event_code:0x{:02x} that should not be " + "handled here", + evt_code); break; } } @@ -224,8 +213,7 @@ void btu_hcif_process_event(uint8_t /* controller_id */, const BT_HDR* p_msg) { // validate event size if (hci_evt_len < hci_event_parameters_minimum_length[hci_evt_code]) { - log::warn("evt:0x{:2X}, malformed event of size {}", hci_evt_code, - hci_evt_len); + log::warn("evt:0x{:2X}, malformed event of size {}", hci_evt_code, hci_evt_len); return; } @@ -246,13 +234,13 @@ void btu_hcif_process_event(uint8_t /* controller_id */, const BT_HDR* p_msg) { break; case HCI_COMMAND_COMPLETE_EVT: log::error( - "should not have received a command complete event. Someone didn't " - "go through the hci transmit_command function."); + "should not have received a command complete event. Someone didn't " + "go through the hci transmit_command function."); break; case HCI_COMMAND_STATUS_EVT: log::error( - "should not have received a command status event. Someone didn't go " - "through the hci transmit_command function."); + "should not have received a command status event. Someone didn't go " + "through the hci transmit_command function."); break; case HCI_MODE_CHANGE_EVT: btu_hcif_mode_change_evt(p); @@ -325,15 +313,14 @@ void btu_hcif_process_event(uint8_t /* controller_id */, const BT_HDR* p_msg) { case HCI_BLE_CIS_REQ_EVT: case HCI_BLE_BIG_SYNC_EST_EVT: case HCI_BLE_BIG_SYNC_LOST_EVT: - IsoManager::GetInstance()->HandleHciEvent(ble_sub_code, p, - ble_evt_len); + IsoManager::GetInstance()->HandleHciEvent(ble_sub_code, p, ble_evt_len); break; default: log::error( - "Unexpectedly received LE sub_event_code:0x{:02x} that should " - "not be handled here", - ble_sub_code); + "Unexpectedly received LE sub_event_code:0x{:02x} that should " + "not be handled here", + ble_sub_code); break; } } break; @@ -341,25 +328,24 @@ void btu_hcif_process_event(uint8_t /* controller_id */, const BT_HDR* p_msg) { // Events now captured by gd::hci_layer module case HCI_VENDOR_SPECIFIC_EVT: case HCI_HARDWARE_ERROR_EVT: - case HCI_NUM_COMPL_DATA_PKTS_EVT: // EventCode::NUMBER_OF_COMPLETED_PACKETS - case HCI_CONNECTION_COMP_EVT: // EventCode::CONNECTION_COMPLETE + case HCI_NUM_COMPL_DATA_PKTS_EVT: // EventCode::NUMBER_OF_COMPLETED_PACKETS + case HCI_CONNECTION_COMP_EVT: // EventCode::CONNECTION_COMPLETE case HCI_CONNECTION_REQUEST_EVT: // EventCode::CONNECTION_REQUEST case HCI_READ_RMT_FEATURES_COMP_EVT: // EventCode::READ_REMOTE_SUPPORTED_FEATURES_COMPLETE - case HCI_READ_RMT_VERSION_COMP_EVT: // EventCode::READ_REMOTE_VERSION_INFORMATION_COMPLETE - case HCI_ROLE_CHANGE_EVT: // EventCode::ROLE_CHANGE - case HCI_DISCONNECTION_COMP_EVT: // EventCode::DISCONNECTION_COMPLETE - case HCI_RMT_NAME_REQUEST_COMP_EVT: // EventCode::REMOTE_NAME_REQUEST_COMPLETE + case HCI_READ_RMT_VERSION_COMP_EVT: // EventCode::READ_REMOTE_VERSION_INFORMATION_COMPLETE + case HCI_ROLE_CHANGE_EVT: // EventCode::ROLE_CHANGE + case HCI_DISCONNECTION_COMP_EVT: // EventCode::DISCONNECTION_COMPLETE + case HCI_RMT_NAME_REQUEST_COMP_EVT: // EventCode::REMOTE_NAME_REQUEST_COMPLETE default: log::error( - "Unexpectedly received event_code:0x{:02x} that should not be " - "handled here", - hci_evt_code); + "Unexpectedly received event_code:0x{:02x} that should not be " + "handled here", + hci_evt_code); break; } } -static void btu_hcif_log_command_metrics(uint16_t opcode, const uint8_t* p_cmd, - uint16_t cmd_status, +static void btu_hcif_log_command_metrics(uint16_t opcode, const uint8_t* p_cmd, uint16_t cmd_status, bool is_cmd_status) { static uint16_t kUnknownBleEvt = android::bluetooth::hci::BLE_EVT_UNKNOWN; @@ -378,46 +364,42 @@ static void btu_hcif_log_command_metrics(uint16_t opcode, const uint8_t* p_cmd, case HCI_CREATE_CONNECTION_CANCEL: STREAM_TO_BDADDR(bd_addr, p_cmd); log_link_layer_connection_event( - &bd_addr, bluetooth::common::kUnknownConnectionHandle, - android::bluetooth::DIRECTION_OUTGOING, - android::bluetooth::LINK_TYPE_ACL, opcode, hci_event, kUnknownBleEvt, - cmd_status, android::bluetooth::hci::STATUS_UNKNOWN); + &bd_addr, bluetooth::common::kUnknownConnectionHandle, + android::bluetooth::DIRECTION_OUTGOING, android::bluetooth::LINK_TYPE_ACL, opcode, + hci_event, kUnknownBleEvt, cmd_status, android::bluetooth::hci::STATUS_UNKNOWN); break; case HCI_DISCONNECT: STREAM_TO_UINT16(handle, p_cmd); STREAM_TO_UINT8(reason, p_cmd); - log_link_layer_connection_event( - nullptr, handle, android::bluetooth::DIRECTION_UNKNOWN, - android::bluetooth::LINK_TYPE_UNKNOWN, opcode, hci_event, - kUnknownBleEvt, cmd_status, reason); + log_link_layer_connection_event(nullptr, handle, android::bluetooth::DIRECTION_UNKNOWN, + android::bluetooth::LINK_TYPE_UNKNOWN, opcode, hci_event, + kUnknownBleEvt, cmd_status, reason); break; case HCI_SETUP_ESCO_CONNECTION: case HCI_ENH_SETUP_ESCO_CONNECTION: STREAM_TO_UINT16(handle, p_cmd); - log_link_layer_connection_event( - nullptr, handle, android::bluetooth::DIRECTION_OUTGOING, - android::bluetooth::LINK_TYPE_UNKNOWN, opcode, hci_event, - kUnknownBleEvt, cmd_status, android::bluetooth::hci::STATUS_UNKNOWN); + log_link_layer_connection_event(nullptr, handle, android::bluetooth::DIRECTION_OUTGOING, + android::bluetooth::LINK_TYPE_UNKNOWN, opcode, hci_event, + kUnknownBleEvt, cmd_status, + android::bluetooth::hci::STATUS_UNKNOWN); break; case HCI_ACCEPT_CONNECTION_REQUEST: case HCI_ACCEPT_ESCO_CONNECTION: case HCI_ENH_ACCEPT_ESCO_CONNECTION: STREAM_TO_BDADDR(bd_addr, p_cmd); log_link_layer_connection_event( - &bd_addr, bluetooth::common::kUnknownConnectionHandle, - android::bluetooth::DIRECTION_INCOMING, - android::bluetooth::LINK_TYPE_UNKNOWN, opcode, hci_event, - kUnknownBleEvt, cmd_status, android::bluetooth::hci::STATUS_UNKNOWN); + &bd_addr, bluetooth::common::kUnknownConnectionHandle, + android::bluetooth::DIRECTION_INCOMING, android::bluetooth::LINK_TYPE_UNKNOWN, opcode, + hci_event, kUnknownBleEvt, cmd_status, android::bluetooth::hci::STATUS_UNKNOWN); break; case HCI_REJECT_CONNECTION_REQUEST: case HCI_REJECT_ESCO_CONNECTION: STREAM_TO_BDADDR(bd_addr, p_cmd); STREAM_TO_UINT8(reason, p_cmd); - log_link_layer_connection_event( - &bd_addr, bluetooth::common::kUnknownConnectionHandle, - android::bluetooth::DIRECTION_INCOMING, - android::bluetooth::LINK_TYPE_UNKNOWN, opcode, hci_event, - kUnknownBleEvt, cmd_status, reason); + log_link_layer_connection_event(&bd_addr, bluetooth::common::kUnknownConnectionHandle, + android::bluetooth::DIRECTION_INCOMING, + android::bluetooth::LINK_TYPE_UNKNOWN, opcode, hci_event, + kUnknownBleEvt, cmd_status, reason); break; // BLE Commands @@ -433,26 +415,21 @@ static void btu_hcif_log_command_metrics(uint16_t opcode, const uint8_t* p_cmd, const RawAddress* bd_addr_p = nullptr; if (initiator_filter_policy == 0x00) { bd_addr_p = &bd_addr; - if (peer_address_type == BLE_ADDR_PUBLIC_ID || - peer_address_type == BLE_ADDR_RANDOM_ID) { + if (peer_address_type == BLE_ADDR_PUBLIC_ID || peer_address_type == BLE_ADDR_RANDOM_ID) { // if identity address is not matched, this address is invalid - if (!btm_identity_addr_to_random_pseudo(&bd_addr, &peer_address_type, - false)) { + if (!btm_identity_addr_to_random_pseudo(&bd_addr, &peer_address_type, false)) { bd_addr_p = nullptr; } } } - if (initiator_filter_policy == 0x00 || - (cmd_status != HCI_SUCCESS && !is_cmd_status)) { + if (initiator_filter_policy == 0x00 || (cmd_status != HCI_SUCCESS && !is_cmd_status)) { // Selectively log to avoid log spam due to acceptlist connections: // - When doing non-acceptlist connection // - When there is an error in command status log_link_layer_connection_event( - bd_addr_p, bluetooth::common::kUnknownConnectionHandle, - android::bluetooth::DIRECTION_OUTGOING, - android::bluetooth::LINK_TYPE_ACL, opcode, hci_event, - kUnknownBleEvt, cmd_status, - android::bluetooth::hci::STATUS_UNKNOWN); + bd_addr_p, bluetooth::common::kUnknownConnectionHandle, + android::bluetooth::DIRECTION_OUTGOING, android::bluetooth::LINK_TYPE_ACL, opcode, + hci_event, kUnknownBleEvt, cmd_status, android::bluetooth::hci::STATUS_UNKNOWN); } break; } @@ -470,17 +447,14 @@ static void btu_hcif_log_command_metrics(uint16_t opcode, const uint8_t* p_cmd, // if identity address is not matched, this should be a static address btm_identity_addr_to_random_pseudo(&bd_addr, &peer_addr_type, false); } - if (initiator_filter_policy == 0x00 || - (cmd_status != HCI_SUCCESS && !is_cmd_status)) { + if (initiator_filter_policy == 0x00 || (cmd_status != HCI_SUCCESS && !is_cmd_status)) { // Selectively log to avoid log spam due to acceptlist connections: // - When doing non-acceptlist connection // - When there is an error in command status log_link_layer_connection_event( - bd_addr_p, bluetooth::common::kUnknownConnectionHandle, - android::bluetooth::DIRECTION_OUTGOING, - android::bluetooth::LINK_TYPE_ACL, opcode, hci_event, - kUnknownBleEvt, cmd_status, - android::bluetooth::hci::STATUS_UNKNOWN); + bd_addr_p, bluetooth::common::kUnknownConnectionHandle, + android::bluetooth::DIRECTION_OUTGOING, android::bluetooth::LINK_TYPE_ACL, opcode, + hci_event, kUnknownBleEvt, cmd_status, android::bluetooth::hci::STATUS_UNKNOWN); } break; } @@ -488,61 +462,53 @@ static void btu_hcif_log_command_metrics(uint16_t opcode, const uint8_t* p_cmd, if (cmd_status != HCI_SUCCESS && !is_cmd_status) { // Only log errors to prevent log spam due to acceptlist connections log_link_layer_connection_event( - nullptr, bluetooth::common::kUnknownConnectionHandle, - android::bluetooth::DIRECTION_OUTGOING, - android::bluetooth::LINK_TYPE_ACL, opcode, hci_event, - kUnknownBleEvt, cmd_status, - android::bluetooth::hci::STATUS_UNKNOWN); + nullptr, bluetooth::common::kUnknownConnectionHandle, + android::bluetooth::DIRECTION_OUTGOING, android::bluetooth::LINK_TYPE_ACL, opcode, + hci_event, kUnknownBleEvt, cmd_status, android::bluetooth::hci::STATUS_UNKNOWN); } break; case HCI_READ_LOCAL_OOB_DATA: case HCI_READ_LOCAL_OOB_EXTENDED_DATA: - log_classic_pairing_event(RawAddress::kEmpty, - bluetooth::common::kUnknownConnectionHandle, + log_classic_pairing_event(RawAddress::kEmpty, bluetooth::common::kUnknownConnectionHandle, opcode, hci_event, cmd_status, android::bluetooth::hci::STATUS_UNKNOWN, 0); break; case HCI_WRITE_SIMPLE_PAIRING_MODE: { uint8_t simple_pairing_mode; STREAM_TO_UINT8(simple_pairing_mode, p_cmd); - log_classic_pairing_event( - RawAddress::kEmpty, bluetooth::common::kUnknownConnectionHandle, - opcode, hci_event, cmd_status, - android::bluetooth::hci::STATUS_UNKNOWN, simple_pairing_mode); + log_classic_pairing_event(RawAddress::kEmpty, bluetooth::common::kUnknownConnectionHandle, + opcode, hci_event, cmd_status, + android::bluetooth::hci::STATUS_UNKNOWN, simple_pairing_mode); break; } case HCI_WRITE_SECURE_CONNS_SUPPORT: { uint8_t secure_conn_host_support; STREAM_TO_UINT8(secure_conn_host_support, p_cmd); - log_classic_pairing_event( - RawAddress::kEmpty, bluetooth::common::kUnknownConnectionHandle, - opcode, hci_event, cmd_status, - android::bluetooth::hci::STATUS_UNKNOWN, secure_conn_host_support); + log_classic_pairing_event(RawAddress::kEmpty, bluetooth::common::kUnknownConnectionHandle, + opcode, hci_event, cmd_status, + android::bluetooth::hci::STATUS_UNKNOWN, secure_conn_host_support); break; } case HCI_AUTHENTICATION_REQUESTED: STREAM_TO_UINT16(handle, p_cmd); - log_classic_pairing_event(RawAddress::kEmpty, handle, opcode, hci_event, - cmd_status, + log_classic_pairing_event(RawAddress::kEmpty, handle, opcode, hci_event, cmd_status, android::bluetooth::hci::STATUS_UNKNOWN, 0); break; case HCI_SET_CONN_ENCRYPTION: { STREAM_TO_UINT16(handle, p_cmd); uint8_t encryption_enable; STREAM_TO_UINT8(encryption_enable, p_cmd); - log_classic_pairing_event( - RawAddress::kEmpty, handle, opcode, hci_event, cmd_status, - android::bluetooth::hci::STATUS_UNKNOWN, encryption_enable); + log_classic_pairing_event(RawAddress::kEmpty, handle, opcode, hci_event, cmd_status, + android::bluetooth::hci::STATUS_UNKNOWN, encryption_enable); break; } case HCI_DELETE_STORED_LINK_KEY: { uint8_t delete_all_flag; STREAM_TO_BDADDR(bd_addr, p_cmd); STREAM_TO_UINT8(delete_all_flag, p_cmd); - log_classic_pairing_event( - bd_addr, bluetooth::common::kUnknownConnectionHandle, opcode, - hci_event, cmd_status, android::bluetooth::hci::STATUS_UNKNOWN, - delete_all_flag); + log_classic_pairing_event(bd_addr, bluetooth::common::kUnknownConnectionHandle, opcode, + hci_event, cmd_status, android::bluetooth::hci::STATUS_UNKNOWN, + delete_all_flag); break; } case HCI_RMT_NAME_REQUEST: @@ -557,16 +523,14 @@ static void btu_hcif_log_command_metrics(uint16_t opcode, const uint8_t* p_cmd, case HCI_REM_OOB_DATA_REQ_REPLY: case HCI_REM_OOB_DATA_REQ_NEG_REPLY: STREAM_TO_BDADDR(bd_addr, p_cmd); - log_classic_pairing_event( - bd_addr, bluetooth::common::kUnknownConnectionHandle, opcode, - hci_event, cmd_status, android::bluetooth::hci::STATUS_UNKNOWN, 0); + log_classic_pairing_event(bd_addr, bluetooth::common::kUnknownConnectionHandle, opcode, + hci_event, cmd_status, android::bluetooth::hci::STATUS_UNKNOWN, 0); break; case HCI_IO_CAP_REQ_NEG_REPLY: STREAM_TO_BDADDR(bd_addr, p_cmd); STREAM_TO_UINT8(reason, p_cmd); - log_classic_pairing_event(bd_addr, - bluetooth::common::kUnknownConnectionHandle, - opcode, hci_event, cmd_status, reason, 0); + log_classic_pairing_event(bd_addr, bluetooth::common::kUnknownConnectionHandle, opcode, + hci_event, cmd_status, reason, 0); break; } } @@ -582,7 +546,9 @@ static void btu_hcif_log_command_metrics(uint16_t opcode, const uint8_t* p_cmd, * ******************************************************************************/ void btu_hcif_send_cmd(uint8_t /* controller_id */, const BT_HDR* p_buf) { - if (!p_buf) return; + if (!p_buf) { + return; + } uint16_t opcode; const uint8_t* stream = p_buf->data + p_buf->offset; @@ -591,15 +557,14 @@ void btu_hcif_send_cmd(uint8_t /* controller_id */, const BT_HDR* p_buf) { // Skip parameter length before logging stream++; - btu_hcif_log_command_metrics(opcode, stream, - android::bluetooth::hci::STATUS_UNKNOWN, false); + btu_hcif_log_command_metrics(opcode, stream, android::bluetooth::hci::STATUS_UNKNOWN, false); - bluetooth::shim::hci_layer_get_interface()->transmit_command( - p_buf, btu_hcif_command_complete_evt, btu_hcif_command_status_evt, NULL); + bluetooth::shim::hci_layer_get_interface()->transmit_command(p_buf, btu_hcif_command_complete_evt, + btu_hcif_command_status_evt, NULL); } -using hci_cmd_cb = base::OnceCallback; +using hci_cmd_cb = base::OnceCallback; struct cmd_with_cb_data { hci_cmd_cb cb; @@ -622,8 +587,7 @@ void cmd_with_cb_data_cleanup(cmd_with_cb_data* cb_wrapper) { * @param p_return_params pointer to returned parameter after parameter length * field */ -static void btu_hcif_log_command_complete_metrics( - uint16_t opcode, const uint8_t* p_return_params) { +static void btu_hcif_log_command_complete_metrics(uint16_t opcode, const uint8_t* p_return_params) { uint16_t status = android::bluetooth::hci::STATUS_UNKNOWN; uint16_t reason = android::bluetooth::hci::STATUS_UNKNOWN; uint16_t hci_event = android::bluetooth::hci::EVT_COMMAND_COMPLETE; @@ -635,8 +599,7 @@ static void btu_hcif_log_command_complete_metrics( case HCI_WRITE_SIMPLE_PAIRING_MODE: case HCI_WRITE_SECURE_CONNS_SUPPORT: STREAM_TO_UINT8(status, p_return_params); - log_classic_pairing_event(RawAddress::kEmpty, - bluetooth::common::kUnknownConnectionHandle, + log_classic_pairing_event(RawAddress::kEmpty, bluetooth::common::kUnknownConnectionHandle, opcode, hci_event, status, reason, 0); break; case HCI_READ_ENCR_KEY_SIZE: { @@ -645,8 +608,8 @@ static void btu_hcif_log_command_complete_metrics( STREAM_TO_UINT8(status, p_return_params); STREAM_TO_UINT16(handle, p_return_params); STREAM_TO_UINT8(key_size, p_return_params); - log_classic_pairing_event(RawAddress::kEmpty, handle, opcode, hci_event, - status, reason, key_size); + log_classic_pairing_event(RawAddress::kEmpty, handle, opcode, hci_event, status, reason, + key_size); break; } case HCI_LINK_KEY_REQUEST_REPLY: @@ -661,15 +624,13 @@ static void btu_hcif_log_command_complete_metrics( case HCI_REM_OOB_DATA_REQ_NEG_REPLY: STREAM_TO_UINT8(status, p_return_params); STREAM_TO_BDADDR(bd_addr, p_return_params); - log_classic_pairing_event(bd_addr, - bluetooth::common::kUnknownConnectionHandle, - opcode, hci_event, status, reason, 0); + log_classic_pairing_event(bd_addr, bluetooth::common::kUnknownConnectionHandle, opcode, + hci_event, status, reason, 0); break; } } -static void btu_hcif_command_complete_evt_with_cb_on_task(BT_HDR* event, - void* context) { +static void btu_hcif_command_complete_evt_with_cb_on_task(BT_HDR* event, void* context) { command_opcode_t opcode; // 2 for event header: event code (1) + parameter length (1) // 1 for num_hci_pkt command credit @@ -690,15 +651,12 @@ static void btu_hcif_command_complete_evt_with_cb_on_task(BT_HDR* event, osi_free(event); } -static void btu_hcif_command_complete_evt_with_cb(BT_HDR* response, - void* context) { - do_in_main_thread( - FROM_HERE, base::BindOnce(btu_hcif_command_complete_evt_with_cb_on_task, - response, context)); +static void btu_hcif_command_complete_evt_with_cb(BT_HDR* response, void* context) { + do_in_main_thread(FROM_HERE, base::BindOnce(btu_hcif_command_complete_evt_with_cb_on_task, + response, context)); } -static void btu_hcif_command_status_evt_with_cb_on_task(uint8_t status, - BT_HDR* event, +static void btu_hcif_command_status_evt_with_cb_on_task(uint8_t status, BT_HDR* event, void* context) { command_opcode_t opcode; uint8_t* stream = event->data + event->offset; @@ -720,24 +678,21 @@ static void btu_hcif_command_status_evt_with_cb_on_task(uint8_t status, osi_free(event); } -static void btu_hcif_command_status_evt_with_cb(uint8_t status, BT_HDR* command, - void* context) { +static void btu_hcif_command_status_evt_with_cb(uint8_t status, BT_HDR* command, void* context) { // Command is pending, we report only error. if (!status) { osi_free(command); return; } - do_in_main_thread(FROM_HERE, - base::BindOnce(btu_hcif_command_status_evt_with_cb_on_task, - status, command, context)); + do_in_main_thread(FROM_HERE, base::BindOnce(btu_hcif_command_status_evt_with_cb_on_task, status, + command, context)); } /* This function is called to send commands to the Host Controller. |cb| is * called when command status event is called with error code, or when the * command complete event is received. */ -void btu_hcif_send_cmd_with_cb(const base::Location& posted_from, - uint16_t opcode, uint8_t* params, +void btu_hcif_send_cmd_with_cb(const base::Location& posted_from, uint16_t opcode, uint8_t* params, uint8_t params_len, hci_cmd_cb cb) { BT_HDR* p = (BT_HDR*)osi_malloc(HCI_CMD_BUF_SIZE); uint8_t* pp = (uint8_t*)(p + 1); @@ -751,19 +706,17 @@ void btu_hcif_send_cmd_with_cb(const base::Location& posted_from, memcpy(pp, params, params_len); } - btu_hcif_log_command_metrics(opcode, pp, - android::bluetooth::hci::STATUS_UNKNOWN, false); + btu_hcif_log_command_metrics(opcode, pp, android::bluetooth::hci::STATUS_UNKNOWN, false); - cmd_with_cb_data* cb_wrapper = - (cmd_with_cb_data*)osi_malloc(sizeof(cmd_with_cb_data)); + cmd_with_cb_data* cb_wrapper = (cmd_with_cb_data*)osi_malloc(sizeof(cmd_with_cb_data)); cmd_with_cb_data_init(cb_wrapper); cb_wrapper->cb = std::move(cb); cb_wrapper->posted_from = posted_from; bluetooth::shim::hci_layer_get_interface()->transmit_command( - p, btu_hcif_command_complete_evt_with_cb, - btu_hcif_command_status_evt_with_cb, (void*)cb_wrapper); + p, btu_hcif_command_complete_evt_with_cb, btu_hcif_command_status_evt_with_cb, + (void*)cb_wrapper); } /******************************************************************************* @@ -803,8 +756,7 @@ static void btu_hcif_encryption_change_evt(uint8_t* p) { STREAM_TO_UINT16(handle, p); STREAM_TO_UINT8(encr_enable, p); - btm_sec_encryption_change_evt(handle, static_cast(status), - encr_enable); + btm_sec_encryption_change_evt(handle, static_cast(status), encr_enable); } /******************************************************************************* @@ -816,17 +768,16 @@ static void btu_hcif_encryption_change_evt(uint8_t* p) { * Returns void * ******************************************************************************/ -static void btu_hcif_read_rmt_ext_features_comp_evt(uint8_t* p, - uint8_t evt_len) { +static void btu_hcif_read_rmt_ext_features_comp_evt(uint8_t* p, uint8_t evt_len) { uint8_t* p_cur = p; uint8_t status; uint16_t handle; STREAM_TO_UINT8(status, p_cur); - if (status == HCI_SUCCESS) + if (status == HCI_SUCCESS) { btm_read_remote_ext_features_complete_raw(p, evt_len); - else { + } else { STREAM_TO_UINT16(handle, p_cur); btm_read_remote_ext_features_failed(status, handle); } @@ -867,8 +818,7 @@ static void btu_hcif_esco_connection_comp_evt(const uint8_t* p) { handle, HCI_HANDLE_MAX); btm_sco_connected(bda, handle, &data); } else { - btm_sco_connection_failed(static_cast(status), bda, handle, - &data); + btm_sco_connection_failed(static_cast(status), bda, handle, &data); } } @@ -909,8 +859,7 @@ static void btu_hcif_esco_connection_chg_evt(uint8_t* p) { * Returns void * ******************************************************************************/ -static void btu_hcif_hdl_command_complete(uint16_t opcode, uint8_t* p, - uint16_t evt_len) { +static void btu_hcif_hdl_command_complete(uint16_t opcode, uint8_t* p, uint16_t evt_len) { switch (opcode) { case HCI_SET_EVENT_FILTER: break; @@ -993,7 +942,7 @@ static void btu_hcif_hdl_command_complete(uint16_t opcode, uint8_t* p, // Explicitly handled command complete events case HCI_BLE_READ_RESOLVABLE_ADDR_LOCAL: case HCI_BLE_SET_ADDR_RESOLUTION_ENABLE: - case HCI_BLE_SET_RAND_PRIV_ADDR_TIMOUT: + case HCI_BLE_SET_RAND_PRIV_ADDR_TIMEOUT: case HCI_WRITE_CLASS_OF_DEVICE: case HCI_WRITE_DEF_POLICY_SETTINGS: case HCI_WRITE_EXT_INQ_RESPONSE: @@ -1009,9 +958,7 @@ static void btu_hcif_hdl_command_complete(uint16_t opcode, uint8_t* p, break; default: - log::error( - "Command complete for opcode:0x{:02x} should not be handled here", - opcode); + log::error("Command complete for opcode:0x{:02x} should not be handled here", opcode); break; } } @@ -1041,11 +988,8 @@ static void btu_hcif_command_complete_evt_on_task(BT_HDR* event) { osi_free(event); } -static void btu_hcif_command_complete_evt(BT_HDR* response, - void* /* context */) { - do_in_main_thread( - FROM_HERE, - base::BindOnce(btu_hcif_command_complete_evt_on_task, response)); +static void btu_hcif_command_complete_evt(BT_HDR* response, void* /* context */) { + do_in_main_thread(FROM_HERE, base::BindOnce(btu_hcif_command_complete_evt_on_task, response)); } /******************************************************************************* @@ -1057,8 +1001,7 @@ static void btu_hcif_command_complete_evt(BT_HDR* response, * Returns void * ******************************************************************************/ -static void btu_hcif_hdl_command_status(uint16_t opcode, uint8_t status, - const uint8_t* p_cmd) { +static void btu_hcif_hdl_command_status(uint16_t opcode, uint8_t status, const uint8_t* p_cmd) { log::assert_that(p_cmd != nullptr, "Null command for opcode 0x{:x}", opcode); p_cmd++; // Skip parameter total length @@ -1138,21 +1081,21 @@ static void btu_hcif_hdl_command_status(uint16_t opcode, uint8_t status, case HCI_READ_RMT_CLOCK_OFFSET: // 0x041f case HCI_CHANGE_CONN_PACKET_TYPE: // 0x040f if (hci_status != HCI_SUCCESS) { - log::warn("Received bad command status for opcode:0x{:02x} status:{}", - opcode, hci_status_code_text(hci_status)); + log::warn("Received bad command status for opcode:0x{:02x} status:{}", opcode, + hci_status_code_text(hci_status)); } break; default: log::error( - "Command status for opcode:0x{:02x} should not be handled here " - "status:{}", - opcode, hci_status_code_text(hci_status)); + "Command status for opcode:0x{:02x} should not be handled here " + "status:{}", + opcode, hci_status_code_text(hci_status)); } } -void bluetooth::legacy::testing::btu_hcif_hdl_command_status( - uint16_t opcode, uint8_t status, const uint8_t* p_cmd) { +void bluetooth::legacy::testing::btu_hcif_hdl_command_status(uint16_t opcode, uint8_t status, + const uint8_t* p_cmd) { ::btu_hcif_hdl_command_status(opcode, status, p_cmd); } @@ -1178,11 +1121,9 @@ static void btu_hcif_command_status_evt_on_task(uint8_t status, BT_HDR* event) { osi_free(event); } -static void btu_hcif_command_status_evt(uint8_t status, BT_HDR* command, - void* /* context */) { - do_in_main_thread( - FROM_HERE, - base::BindOnce(btu_hcif_command_status_evt_on_task, status, command)); +static void btu_hcif_command_status_evt(uint8_t status, BT_HDR* command, void* /* context */) { + do_in_main_thread(FROM_HERE, + base::BindOnce(btu_hcif_command_status_evt_on_task, status, command)); } /******************************************************************************* @@ -1304,8 +1245,7 @@ err_out: log::error("bogus event packet, too short"); } -void btu_hcif_read_local_oob_extended_complete(const uint8_t* p, - uint16_t evt_len) { +void btu_hcif_read_local_oob_extended_complete(const uint8_t* p, uint16_t evt_len) { if (evt_len < 64 + 1) { log::error("Invalid event length: {}", evt_len); return; @@ -1365,7 +1305,9 @@ static void btu_hcif_read_clock_off_comp_evt(uint8_t* p) { STREAM_TO_UINT8(status, p); /* If failed to get clock offset just drop the result */ - if (status != HCI_SUCCESS) return; + if (status != HCI_SUCCESS) { + return; + } STREAM_TO_UINT16(handle, p); STREAM_TO_UINT16(clock_offset, p); @@ -1428,8 +1370,7 @@ static void btu_hcif_encryption_key_refresh_cmpl_evt(uint8_t* p) { STREAM_TO_UINT8(status, p); STREAM_TO_UINT16(handle, p); - btm_sec_encryption_key_refresh_complete(handle, - static_cast(status)); + btm_sec_encryption_key_refresh_complete(handle, static_cast(status)); } /********************************************** diff --git a/system/stack/btu/main_thread.cc b/system/stack/btu/main_thread.cc index b6ba58cc9cd..0668223a0a0 100644 --- a/system/stack/btu/main_thread.cc +++ b/system/stack/btu/main_thread.cc @@ -35,12 +35,9 @@ using namespace bluetooth; static MessageLoopThread main_thread("bt_main_thread"); bluetooth::common::MessageLoopThread* get_main_thread() { return &main_thread; } -bluetooth::common::PostableContext* get_main() { - return main_thread.Postable(); -} +bluetooth::common::PostableContext* get_main() { return main_thread.Postable(); } -bt_status_t do_in_main_thread(const base::Location& from_here, - base::OnceClosure task) { +bt_status_t do_in_main_thread(const base::Location& from_here, base::OnceClosure task) { if (!main_thread.DoInThread(from_here, std::move(task))) { log::error("failed from {}", from_here.ToString()); return BT_STATUS_JNI_THREAD_ATTACH_ERROR; @@ -48,8 +45,7 @@ bt_status_t do_in_main_thread(const base::Location& from_here, return BT_STATUS_SUCCESS; } -bt_status_t do_in_main_thread_delayed(const base::Location& from_here, - base::OnceClosure task, +bt_status_t do_in_main_thread_delayed(const base::Location& from_here, base::OnceClosure task, std::chrono::microseconds delay) { if (!main_thread.DoInThreadDelayed(from_here, std::move(task), delay)) { log::error("failed from {}", from_here.ToString()); @@ -62,12 +58,11 @@ static void do_post_on_bt_main(BtMainClosure closure) { closure(); } void post_on_bt_main(BtMainClosure closure) { log::assert_that( - do_in_main_thread( - FROM_HERE, base::BindOnce(do_post_on_bt_main, std::move(closure))) == - BT_STATUS_SUCCESS, - "assert failed: do_in_main_thread(FROM_HERE, " - "base::BindOnce(do_post_on_bt_main, std::move(closure))) == " - "BT_STATUS_SUCCESS"); + do_in_main_thread(FROM_HERE, base::BindOnce(do_post_on_bt_main, std::move(closure))) == + BT_STATUS_SUCCESS, + "assert failed: do_in_main_thread(FROM_HERE, " + "base::BindOnce(do_post_on_bt_main, std::move(closure))) == " + "BT_STATUS_SUCCESS"); } void main_thread_start_up() { diff --git a/system/stack/eatt/eatt.cc b/system/stack/eatt/eatt.cc index 8a959c4ffb0..e45990a2294 100644 --- a/system/stack/eatt/eatt.cc +++ b/system/stack/eatt/eatt.cc @@ -70,50 +70,56 @@ struct EattExtension::impl { return instance->pimpl_->eatt_impl_.get(); } - static void eatt_connect_ind(const RawAddress& bda, - std::vector& lcids, uint16_t psm, + static void eatt_connect_ind(const RawAddress& bda, std::vector& lcids, uint16_t psm, uint16_t peer_mtu, uint8_t identifier) { auto p_eatt_impl = GetImplInstance(); - if (p_eatt_impl) - p_eatt_impl->eatt_l2cap_connect_ind(bda, lcids, psm, peer_mtu, - identifier); + if (p_eatt_impl) { + p_eatt_impl->eatt_l2cap_connect_ind(bda, lcids, psm, peer_mtu, identifier); + } } - static void eatt_connect_cfm(const RawAddress& bda, uint16_t lcid, - uint16_t peer_mtu, uint16_t result) { + static void eatt_connect_cfm(const RawAddress& bda, uint16_t lcid, uint16_t peer_mtu, + uint16_t result) { auto p_eatt_impl = GetImplInstance(); - if (p_eatt_impl) + if (p_eatt_impl) { p_eatt_impl->eatt_l2cap_connect_cfm(bda, lcid, peer_mtu, result); + } } - static void eatt_reconfig_completed(const RawAddress& bda, uint16_t lcid, - bool is_local_cfg, + static void eatt_reconfig_completed(const RawAddress& bda, uint16_t lcid, bool is_local_cfg, tL2CAP_LE_CFG_INFO* p_cfg) { auto p_eatt_impl = GetImplInstance(); - if (p_eatt_impl) - p_eatt_impl->eatt_l2cap_reconfig_completed(bda, lcid, is_local_cfg, - p_cfg); + if (p_eatt_impl) { + p_eatt_impl->eatt_l2cap_reconfig_completed(bda, lcid, is_local_cfg, p_cfg); + } } static void eatt_collision_ind(const RawAddress& bd_addr) { auto p_eatt_impl = GetImplInstance(); - if (p_eatt_impl) p_eatt_impl->eatt_l2cap_collision_ind(bd_addr); + if (p_eatt_impl) { + p_eatt_impl->eatt_l2cap_collision_ind(bd_addr); + } } static void eatt_error_cb(uint16_t lcid, uint16_t reason) { auto p_eatt_impl = GetImplInstance(); - if (p_eatt_impl) p_eatt_impl->eatt_l2cap_error_cb(lcid, reason); + if (p_eatt_impl) { + p_eatt_impl->eatt_l2cap_error_cb(lcid, reason); + } } static void eatt_disconnect_ind(uint16_t lcid, bool please_confirm) { auto p_eatt_impl = GetImplInstance(); - if (p_eatt_impl) + if (p_eatt_impl) { p_eatt_impl->eatt_l2cap_disconnect_ind(lcid, please_confirm); + } } static void eatt_data_ind(uint16_t lcid, BT_HDR* data_p) { auto p_eatt_impl = GetImplInstance(); - if (p_eatt_impl) p_eatt_impl->eatt_l2cap_data_ind(lcid, data_p); + if (p_eatt_impl) { + p_eatt_impl->eatt_l2cap_data_ind(lcid, data_p); + } } std::unique_ptr eatt_impl_; @@ -122,7 +128,9 @@ struct EattExtension::impl { void EattExtension::AddFromStorage(const RawAddress& bd_addr) { eatt_impl* p_eatt_impl = EattExtension::impl::GetImplInstance(); - if (p_eatt_impl) p_eatt_impl->add_from_storage(bd_addr); + if (p_eatt_impl) { + p_eatt_impl->add_from_storage(bd_addr); + } } EattExtension::EattExtension() : pimpl_(std::make_unique()) {} @@ -131,39 +139,32 @@ bool EattExtension::IsEattSupportedByPeer(const RawAddress& bd_addr) { return pimpl_->eatt_impl_->is_eatt_supported_by_peer(bd_addr); } -void EattExtension::Connect(const RawAddress& bd_addr) { - pimpl_->eatt_impl_->connect(bd_addr); -} +void EattExtension::Connect(const RawAddress& bd_addr) { pimpl_->eatt_impl_->connect(bd_addr); } void EattExtension::Disconnect(const RawAddress& bd_addr, uint16_t cid) { pimpl_->eatt_impl_->disconnect(bd_addr, cid); } -void EattExtension::Reconfigure(const RawAddress& bd_addr, uint16_t cid, - uint16_t mtu) { +void EattExtension::Reconfigure(const RawAddress& bd_addr, uint16_t cid, uint16_t mtu) { pimpl_->eatt_impl_->reconfigure(bd_addr, cid, mtu); } void EattExtension::ReconfigureAll(const RawAddress& bd_addr, uint16_t mtu) { pimpl_->eatt_impl_->reconfigure_all(bd_addr, mtu); } -EattChannel* EattExtension::FindEattChannelByCid(const RawAddress& bd_addr, - uint16_t cid) { +EattChannel* EattExtension::FindEattChannelByCid(const RawAddress& bd_addr, uint16_t cid) { return pimpl_->eatt_impl_->find_eatt_channel_by_cid(bd_addr, cid); } -EattChannel* EattExtension::FindEattChannelByTransId(const RawAddress& bd_addr, - uint32_t trans_id) { +EattChannel* EattExtension::FindEattChannelByTransId(const RawAddress& bd_addr, uint32_t trans_id) { return pimpl_->eatt_impl_->find_eatt_channel_by_transid(bd_addr, trans_id); } -bool EattExtension::IsIndicationPending(const RawAddress& bd_addr, - uint16_t indication_handle) { +bool EattExtension::IsIndicationPending(const RawAddress& bd_addr, uint16_t indication_handle) { return pimpl_->eatt_impl_->is_indication_pending(bd_addr, indication_handle); } -EattChannel* EattExtension::GetChannelAvailableForIndication( - const RawAddress& bd_addr) { +EattChannel* EattExtension::GetChannelAvailableForIndication(const RawAddress& bd_addr) { return pimpl_->eatt_impl_->get_channel_available_for_indication(bd_addr); } @@ -175,35 +176,29 @@ bool EattExtension::IsOutstandingMsgInSendQueue(const RawAddress& bd_addr) { return pimpl_->eatt_impl_->is_outstanding_msg_in_send_queue(bd_addr); } -EattChannel* EattExtension::GetChannelWithQueuedDataToSend( - const RawAddress& bd_addr) { +EattChannel* EattExtension::GetChannelWithQueuedDataToSend(const RawAddress& bd_addr) { return pimpl_->eatt_impl_->get_channel_with_queued_data(bd_addr); } -EattChannel* EattExtension::GetChannelAvailableForClientRequest( - const RawAddress& bd_addr) { +EattChannel* EattExtension::GetChannelAvailableForClientRequest(const RawAddress& bd_addr) { return pimpl_->eatt_impl_->get_channel_available_for_client_request(bd_addr); } /* Start stop GATT indication timer per CID */ -void EattExtension::StartIndicationConfirmationTimer(const RawAddress& bd_addr, - uint16_t cid) { +void EattExtension::StartIndicationConfirmationTimer(const RawAddress& bd_addr, uint16_t cid) { pimpl_->eatt_impl_->start_indication_confirm_timer(bd_addr, cid); } -void EattExtension::StopIndicationConfirmationTimer(const RawAddress& bd_addr, - uint16_t cid) { +void EattExtension::StopIndicationConfirmationTimer(const RawAddress& bd_addr, uint16_t cid) { pimpl_->eatt_impl_->stop_indication_confirm_timer(bd_addr, cid); } /* Start stop application indication timeout */ -void EattExtension::StartAppIndicationTimer(const RawAddress& bd_addr, - uint16_t cid) { +void EattExtension::StartAppIndicationTimer(const RawAddress& bd_addr, uint16_t cid) { pimpl_->eatt_impl_->start_app_indication_timer(bd_addr, cid); } -void EattExtension::StopAppIndicationTimer(const RawAddress& bd_addr, - uint16_t cid) { +void EattExtension::StopAppIndicationTimer(const RawAddress& bd_addr, uint16_t cid) { pimpl_->eatt_impl_->stop_app_indication_timer(bd_addr, cid); } diff --git a/system/stack/eatt/eatt.h b/system/stack/eatt/eatt.h index 62bf2482066..9a46f362916 100644 --- a/system/stack/eatt/eatt.h +++ b/system/stack/eatt/eatt.h @@ -26,7 +26,7 @@ #define EATT_MIN_MTU_MPS (64) #define EATT_DEFAULT_MTU (256) -#define EATT_MAX_TX_MTU (1024) +#define EATT_MAX_TX_MTU (1024) #define EATT_ALL_CIDS (0xFFFF) namespace bluetooth { @@ -40,7 +40,7 @@ enum class EattChannelState : uint8_t { }; class EattChannel { - public: +public: /* Pointer to EattDevice */ RawAddress bda_; uint16_t cid_; @@ -50,7 +50,7 @@ class EattChannel { /* Used to keep server commands */ tGATT_SR_CMD server_outstanding_cmd_; - /* Used to veryfy indication confirmation*/ + /* Used to verify indication confirmation*/ uint16_t indicate_handle_; /* local app confirm to indication timer */ alarm_t* ind_ack_timer_; @@ -86,12 +86,10 @@ class EattChannel { if (state == EattChannelState::EATT_CHANNEL_OPENED) { memset(&server_outstanding_cmd_, 0, sizeof(tGATT_SR_CMD)); char name[64]; - sprintf(name, "eatt_ind_ack_timer_%s_cid_0x%04x", - ADDRESS_TO_LOGGABLE_CSTR(bda_), cid_); + sprintf(name, "eatt_ind_ack_timer_%s_cid_0x%04x", ADDRESS_TO_LOGGABLE_CSTR(bda_), cid_); ind_ack_timer_ = alarm_new(name); - sprintf(name, "eatt_ind_conf_timer_%s_cid_0x%04x", - ADDRESS_TO_LOGGABLE_CSTR(bda_), cid_); + sprintf(name, "eatt_ind_conf_timer_%s_cid_0x%04x", ADDRESS_TO_LOGGABLE_CSTR(bda_), cid_); ind_confirmation_timer_ = alarm_new(name); } } @@ -105,7 +103,7 @@ class EattChannel { /* Interface class */ class EattExtension { - public: +public: EattExtension(); EattExtension(const EattExtension&) = delete; EattExtension& operator=(const EattExtension&) = delete; @@ -139,8 +137,7 @@ class EattExtension { * @param bd_addr peer device address * @param cid remote channel id (EATT_ALL_CIDS for all) */ - virtual void Disconnect(const RawAddress& bd_addr, - uint16_t cid = EATT_ALL_CIDS); + virtual void Disconnect(const RawAddress& bd_addr, uint16_t cid = EATT_ALL_CIDS); /** * Reconfigure EATT channel for give CID @@ -149,8 +146,7 @@ class EattExtension { * @param cid channel id * @param mtu new maximum transmit unit available of local device */ - virtual void Reconfigure(const RawAddress& bd_addr, uint16_t cid, - uint16_t mtu); + virtual void Reconfigure(const RawAddress& bd_addr, uint16_t cid, uint16_t mtu); /** * Reconfigure all EATT channels to peer device. @@ -170,8 +166,7 @@ class EattExtension { * * @return Eatt Channel instance. */ - virtual EattChannel* FindEattChannelByCid(const RawAddress& bd_addr, - uint16_t cid); + virtual EattChannel* FindEattChannelByCid(const RawAddress& bd_addr, uint16_t cid); /** * Find EATT channel by transaction id. @@ -181,8 +176,7 @@ class EattExtension { * * @return pointer to EATT channel. */ - virtual EattChannel* FindEattChannelByTransId(const RawAddress& bd_addr, - uint32_t trans_id); + virtual EattChannel* FindEattChannelByTransId(const RawAddress& bd_addr, uint32_t trans_id); /** * Check if EATT channel on given handle is waiting for a indication @@ -193,8 +187,7 @@ class EattExtension { * * @return true if confirmation is pending false otherwise */ - virtual bool IsIndicationPending(const RawAddress& bd_addr, - uint16_t indication_handle); + virtual bool IsIndicationPending(const RawAddress& bd_addr, uint16_t indication_handle); /** * Get EATT channel available for indication. @@ -203,8 +196,7 @@ class EattExtension { * * @return pointer to EATT channel. */ - virtual EattChannel* GetChannelAvailableForIndication( - const RawAddress& bd_addr); + virtual EattChannel* GetChannelAvailableForIndication(const RawAddress& bd_addr); /** * Free Resources. @@ -231,8 +223,7 @@ class EattExtension { * * @return pointer to EATT channel. */ - virtual EattChannel* GetChannelWithQueuedDataToSend( - const RawAddress& bd_addr); + virtual EattChannel* GetChannelWithQueuedDataToSend(const RawAddress& bd_addr); /** * Get EATT channel available to send GATT request. @@ -241,8 +232,7 @@ class EattExtension { * * @return pointer to EATT channel. */ - virtual EattChannel* GetChannelAvailableForClientRequest( - const RawAddress& bd_addr); + virtual EattChannel* GetChannelAvailableForClientRequest(const RawAddress& bd_addr); /** * Start GATT indication timer per CID. @@ -250,8 +240,7 @@ class EattExtension { * @param bd_addr peer device address * @param cid channel id */ - virtual void StartIndicationConfirmationTimer(const RawAddress& bd_addr, - uint16_t cid); + virtual void StartIndicationConfirmationTimer(const RawAddress& bd_addr, uint16_t cid); /** * Stop GATT indication timer per CID. @@ -259,8 +248,7 @@ class EattExtension { * @param bd_addr peer device address * @param cid channel id */ - virtual void StopIndicationConfirmationTimer(const RawAddress& bd_addr, - uint16_t cid); + virtual void StopIndicationConfirmationTimer(const RawAddress& bd_addr, uint16_t cid); /** * Start application time for incoming indication on given CID @@ -288,7 +276,7 @@ class EattExtension { */ void Stop(); - private: +private: struct impl; std::unique_ptr pimpl_; }; diff --git a/system/stack/eatt/eatt_impl.h b/system/stack/eatt/eatt_impl.h index 60964143c98..bc0d58617d9 100644 --- a/system/stack/eatt/eatt_impl.h +++ b/system/stack/eatt/eatt_impl.h @@ -42,7 +42,7 @@ namespace eatt { #define BLE_GATT_SVR_SUP_FEAT_EATT_BITMASK 0x01 class eatt_device { - public: +public: RawAddress bda_; uint16_t rx_mtu_; uint16_t rx_mps_; @@ -70,42 +70,45 @@ struct eatt_impl { default_mtu_ = EATT_DEFAULT_MTU; max_mps_ = EATT_MIN_MTU_MPS; psm_ = BT_PSM_EATT; - }; + } ~eatt_impl() = default; eatt_device* find_device_by_cid(uint16_t lcid) { /* This works only because Android CIDs are unique across the ACL * connections */ - auto iter = find_if(devices_.begin(), devices_.end(), - [&lcid](const eatt_device& ed) { - auto it = ed.eatt_channels.find(lcid); - return it != ed.eatt_channels.end(); - }); + auto iter = find_if(devices_.begin(), devices_.end(), [&lcid](const eatt_device& ed) { + auto it = ed.eatt_channels.find(lcid); + return it != ed.eatt_channels.end(); + }); return (iter == devices_.end()) ? nullptr : &(*iter); } EattChannel* find_channel_by_cid(uint16_t lcid) { eatt_device* eatt_dev = find_device_by_cid(lcid); - if (!eatt_dev) return nullptr; + if (!eatt_dev) { + return nullptr; + } auto it = eatt_dev->eatt_channels.find(lcid); return (it == eatt_dev->eatt_channels.end()) ? nullptr : it->second.get(); } bool is_channel_connection_pending(eatt_device* eatt_dev) { - for (const std::pair>& el : - eatt_dev->eatt_channels) { - if (el.second->state_ == EattChannelState::EATT_CHANNEL_PENDING) + for (const std::pair>& el : eatt_dev->eatt_channels) { + if (el.second->state_ == EattChannelState::EATT_CHANNEL_PENDING) { return true; + } } return false; } EattChannel* find_channel_by_cid(const RawAddress& bdaddr, uint16_t lcid) { eatt_device* eatt_dev = find_device_by_address(bdaddr); - if (!eatt_dev) return nullptr; + if (!eatt_dev) { + return nullptr; + } auto it = eatt_dev->eatt_channels.find(lcid); return (it == eatt_dev->eatt_channels.end()) ? nullptr : it->second.get(); @@ -114,27 +117,28 @@ struct eatt_impl { void remove_channel_by_cid(eatt_device* eatt_dev, uint16_t lcid) { auto channel = eatt_dev->eatt_channels[lcid]; if (!channel->cl_cmd_q_.empty()) { - log::warn("Channel {:c}, for device {} is not empty on disconnection.", - lcid, channel->bda_); + log::warn("Channel {:c}, for device {} is not empty on disconnection.", lcid, channel->bda_); channel->cl_cmd_q_.clear(); } eatt_dev->eatt_channels.erase(lcid); - if (eatt_dev->eatt_channels.size() == 0) eatt_dev->eatt_tcb_ = NULL; + if (eatt_dev->eatt_channels.size() == 0) { + eatt_dev->eatt_tcb_ = NULL; + } } void remove_channel_by_cid(uint16_t lcid) { eatt_device* eatt_dev = find_device_by_cid(lcid); - if (!eatt_dev) return; + if (!eatt_dev) { + return; + } remove_channel_by_cid(eatt_dev, lcid); } - bool eatt_l2cap_connect_ind_common(const RawAddress& bda, - std::vector& lcids, - uint16_t /* psm */, uint16_t peer_mtu, - uint8_t identifier) { + bool eatt_l2cap_connect_ind_common(const RawAddress& bda, std::vector& lcids, + uint16_t /* psm */, uint16_t peer_mtu, uint8_t identifier) { /* The assumption is that L2CAP layer already check parameters etc. * Get our capabilities and accept all the channels. */ @@ -149,26 +153,22 @@ struct eatt_impl { eatt_dev = add_eatt_device(bda); } - uint16_t max_mps = - shim::GetController()->GetLeBufferSize().le_data_packet_length_; + uint16_t max_mps = shim::GetController()->GetLeBufferSize().le_data_packet_length_; tL2CAP_LE_CFG_INFO local_coc_cfg = { - .result = L2CAP_LE_RESULT_CONN_OK, - .mtu = eatt_dev->rx_mtu_, - .mps = eatt_dev->rx_mps_ < max_mps ? eatt_dev->rx_mps_ : max_mps, - .credits = L2CA_LeCreditDefault(), + .result = L2CAP_LE_RESULT_CONN_OK, + .mtu = eatt_dev->rx_mtu_, + .mps = eatt_dev->rx_mps_ < max_mps ? eatt_dev->rx_mps_ : max_mps, + .credits = L2CA_LeCreditDefault(), }; - if (!L2CA_ConnectCreditBasedRsp(bda, identifier, lcids, L2CAP_CONN_OK, - &local_coc_cfg)) { - log::warn("Unable to respond L2CAP le_coc credit indication peer:{}", - bda); + if (!L2CA_ConnectCreditBasedRsp(bda, identifier, lcids, L2CAP_CONN_OK, &local_coc_cfg)) { + log::warn("Unable to respond L2CAP le_coc credit indication peer:{}", bda); return false; } if (!eatt_dev->eatt_tcb_) { - eatt_dev->eatt_tcb_ = - gatt_find_tcb_by_addr(eatt_dev->bda_, BT_TRANSPORT_LE); + eatt_dev->eatt_tcb_ = gatt_find_tcb_by_addr(eatt_dev->bda_, BT_TRANSPORT_LE); log::assert_that(eatt_dev->eatt_tcb_ != nullptr, "assert failed: eatt_dev->eatt_tcb_ != nullptr"); } @@ -177,8 +177,7 @@ struct eatt_impl { EattChannel* channel = find_eatt_channel_by_cid(bda, cid); log::assert_that(channel == nullptr, "assert failed: channel == nullptr"); - auto chan = std::make_shared(eatt_dev->bda_, cid, peer_mtu, - eatt_dev->rx_mtu_); + auto chan = std::make_shared(eatt_dev->bda_, cid, peer_mtu, eatt_dev->rx_mtu_); eatt_dev->eatt_channels.insert({cid, chan}); chan->EattChannelSetState(EattChannelState::EATT_CHANNEL_OPENED); @@ -191,11 +190,9 @@ struct eatt_impl { } /* This is for the L2CAP ECoC Testing. */ - void upper_tester_send_data_if_needed(const RawAddress& bda, - uint16_t cid = 0) { + void upper_tester_send_data_if_needed(const RawAddress& bda, uint16_t cid = 0) { eatt_device* eatt_dev = find_device_by_address(bda); - auto num_of_sdu = - stack_config_get_interface()->get_pts_l2cap_ecoc_send_num_of_sdu(); + auto num_of_sdu = stack_config_get_interface()->get_pts_l2cap_ecoc_send_num_of_sdu(); log::info("device {}, num: {}", eatt_dev->bda_, num_of_sdu); if (num_of_sdu <= 0) { @@ -207,8 +204,7 @@ struct eatt_impl { auto chan = find_channel_by_cid(cid); mtu = chan->tx_mtu_; } else { - for (const std::pair>& el : - eatt_dev->eatt_channels) { + for (const std::pair>& el : eatt_dev->eatt_channels) { if (el.second->state_ == EattChannelState::EATT_CHANNEL_OPENED) { cid = el.first; mtu = el.second->tx_mtu_; @@ -228,8 +224,7 @@ struct eatt_impl { p_buf->len = mtu; auto status = L2CA_DataWrite(cid, p_buf); - log::info("Data num: {} sent with status {}", i, - static_cast(status)); + log::info("Data num: {} sent with status {}", i, static_cast(status)); } } @@ -246,34 +241,27 @@ struct eatt_impl { } void upper_tester_delay_connect(const RawAddress& bda, int timeout_ms) { - bt_status_t status = do_in_main_thread_delayed( - FROM_HERE, - base::BindOnce(&eatt_impl::upper_tester_delay_connect_cb, - weak_factory_.GetWeakPtr(), bda), - std::chrono::milliseconds(timeout_ms)); - - log::info("Scheduled peripheral connect eatt for device with status: {}", - (int)status); + bt_status_t status = + do_in_main_thread_delayed(FROM_HERE, + base::BindOnce(&eatt_impl::upper_tester_delay_connect_cb, + weak_factory_.GetWeakPtr(), bda), + std::chrono::milliseconds(timeout_ms)); + + log::info("Scheduled peripheral connect eatt for device with status: {}", (int)status); } - void upper_tester_l2cap_connect_ind(const RawAddress& bda, - std::vector& lcids, - uint16_t psm, uint16_t peer_mtu, - uint8_t identifier) { + void upper_tester_l2cap_connect_ind(const RawAddress& bda, std::vector& lcids, + uint16_t psm, uint16_t peer_mtu, uint8_t identifier) { /* This is just for L2CAP PTS test cases*/ - auto min_key_size = - stack_config_get_interface()->get_pts_l2cap_ecoc_min_key_size(); + auto min_key_size = stack_config_get_interface()->get_pts_l2cap_ecoc_min_key_size(); if (min_key_size > 0 && (min_key_size >= 7 && min_key_size <= 16)) { auto key_size = btm_ble_read_sec_key_size(bda); if (key_size < min_key_size) { std::vector empty; - log::error("Insufficient key size ({}<{}) for device {}", key_size, - min_key_size, bda); - if (!L2CA_ConnectCreditBasedRsp( - bda, identifier, empty, - L2CAP_LE_RESULT_INSUFFICIENT_ENCRYP_KEY_SIZE, nullptr)) { - log::warn("Unable to respond L2CAP le_coc credit indication peer:{}", - bda); + log::error("Insufficient key size ({}<{}) for device {}", key_size, min_key_size, bda); + if (!L2CA_ConnectCreditBasedRsp(bda, identifier, empty, + L2CAP_LE_RESULT_INSUFFICIENT_ENCRYP_KEY_SIZE, nullptr)) { + log::warn("Unable to respond L2CAP le_coc credit indication peer:{}", bda); } return; } @@ -287,8 +275,7 @@ struct eatt_impl { /* Android let Central to create EATT (PTS initiates EATT). Some PTS test * cases wants Android to do it anyway (Android initiates EATT). */ - if (stack_config_get_interface() - ->get_pts_eatt_peripheral_collision_support()) { + if (stack_config_get_interface()->get_pts_eatt_peripheral_collision_support()) { upper_tester_delay_connect(bda, 500); return; } @@ -297,22 +284,19 @@ struct eatt_impl { if (stack_config_get_interface()->get_pts_l2cap_ecoc_reconfigure()) { bt_status_t status = do_in_main_thread_delayed( - FROM_HERE, - base::BindOnce(&eatt_impl::reconfigure_all, - weak_factory_.GetWeakPtr(), bda, 300), - std::chrono::seconds(4)); + FROM_HERE, + base::BindOnce(&eatt_impl::reconfigure_all, weak_factory_.GetWeakPtr(), bda, 300), + std::chrono::seconds(4)); log::info("Scheduled ECOC reconfiguration with status: {}", (int)status); } } - void eatt_l2cap_connect_ind(const RawAddress& bda, - std::vector& lcids, uint16_t psm, + void eatt_l2cap_connect_ind(const RawAddress& bda, std::vector& lcids, uint16_t psm, uint16_t peer_mtu, uint8_t identifier) { log::info("Device {}, num of cids: {}, psm 0x{:04x}, peer_mtu {}", bda, static_cast(lcids.size()), psm, peer_mtu); - if (!stack_config_get_interface() - ->get_pts_connect_eatt_before_encryption() && + if (!stack_config_get_interface()->get_pts_connect_eatt_before_encryption() && !BTM_IsEncrypted(bda, BT_TRANSPORT_LE)) { /* If Link is not encrypted, we shall not accept EATT channel creation. */ std::vector empty; @@ -321,18 +305,15 @@ struct eatt_impl { result = L2CAP_LE_RESULT_INSUFFICIENT_ENCRYP; } log::error("ACL to device {} is unencrypted.", bda); - if (!L2CA_ConnectCreditBasedRsp(bda, identifier, empty, result, - nullptr)) { - log::warn("Unable to respond L2CAP le_coc credit indication peer:{}", - bda); + if (!L2CA_ConnectCreditBasedRsp(bda, identifier, empty, result, nullptr)) { + log::warn("Unable to respond L2CAP le_coc credit indication peer:{}", bda); } return; } if (stack_config_get_interface()->get_pts_l2cap_ecoc_upper_tester()) { log::info("Upper tester for the L2CAP ECoC enabled"); - return upper_tester_l2cap_connect_ind(bda, lcids, psm, peer_mtu, - identifier); + return upper_tester_l2cap_connect_ind(bda, lcids, psm, peer_mtu, identifier); } eatt_l2cap_connect_ind_common(bda, lcids, psm, peer_mtu, identifier); @@ -347,17 +328,14 @@ struct eatt_impl { * Android proceed its own EATT creation. How to handle it is described * here: BT Core 5.3, Volume 3, Part G, 5.4 */ - log::info( - "EATT collision detected. If we are Central we will retry right away"); + log::info("EATT collision detected. If we are Central we will retry right away"); eatt_dev->collision = false; uint8_t role = L2CA_GetBleConnRole(eatt_dev->bda_); if (role == HCI_ROLE_CENTRAL) { - log::info("Retrying EATT setup due to previous collision for device {}", - eatt_dev->bda_); + log::info("Retrying EATT setup due to previous collision for device {}", eatt_dev->bda_); connect_eatt_wrap(eatt_dev); - } else if (stack_config_get_interface() - ->get_pts_eatt_peripheral_collision_support()) { + } else if (stack_config_get_interface()->get_pts_eatt_peripheral_collision_support()) { /* This is only for the PTS. Android does not setup EATT when is a * peripheral. */ @@ -374,21 +352,18 @@ struct eatt_impl { } if (stack_config_get_interface()->get_pts_l2cap_ecoc_connect_remaining() && - (static_cast(eatt_dev->eatt_channels.size()) < - L2CAP_CREDIT_BASED_MAX_CIDS)) { + (static_cast(eatt_dev->eatt_channels.size()) < L2CAP_CREDIT_BASED_MAX_CIDS)) { log::info("Connecting remaining channels {}", - L2CAP_CREDIT_BASED_MAX_CIDS - - static_cast(eatt_dev->eatt_channels.size())); + L2CAP_CREDIT_BASED_MAX_CIDS - static_cast(eatt_dev->eatt_channels.size())); upper_tester_delay_connect(eatt_dev->bda_, 1000); return; } upper_tester_send_data_if_needed(eatt_dev->bda_); } - void eatt_l2cap_connect_cfm(const RawAddress& bda, uint16_t lcid, - uint16_t peer_mtu, uint16_t result) { - log::info("bda: {} cid: {}peer mtu: {} result {}", bda, lcid, peer_mtu, - result); + void eatt_l2cap_connect_cfm(const RawAddress& bda, uint16_t lcid, uint16_t peer_mtu, + uint16_t result) { + log::info("bda: {} cid: {}peer mtu: {} result {}", bda, lcid, peer_mtu, result); eatt_device* eatt_dev = find_device_by_address(bda); if (!eatt_dev) { @@ -429,37 +404,37 @@ struct eatt_impl { } } - void eatt_l2cap_reconfig_completed(const RawAddress& bda, uint16_t lcid, - bool is_local_cfg, + void eatt_l2cap_reconfig_completed(const RawAddress& bda, uint16_t lcid, bool is_local_cfg, tL2CAP_LE_CFG_INFO* p_cfg) { log::info("lcid: 0x{:x} local cfg?: {}", lcid, is_local_cfg); EattChannel* channel = find_channel_by_cid(bda, lcid); - if (!channel) return; + if (!channel) { + return; + } // regardless of success result, we have finished reconfiguration channel->EattChannelSetState(EattChannelState::EATT_CHANNEL_OPENED); if (p_cfg->result != L2CAP_CFG_OK) { - log::info("reconfig failed lcid: 0x{:x} result: 0x{:x}", lcid, - p_cfg->result); + log::info("reconfig failed lcid: 0x{:x} result: 0x{:x}", lcid, p_cfg->result); return; } /* On this layer we don't care about mps as this is handled in L2CAP layer */ - if (is_local_cfg) + if (is_local_cfg) { channel->rx_mtu_ = p_cfg->mtu; - else + } else { channel->EattChannelSetTxMTU(p_cfg->mtu); + } if (stack_config_get_interface()->get_pts_l2cap_ecoc_reconfigure()) { /* Upper tester for L2CAP - schedule sending data */ - do_in_main_thread_delayed( - FROM_HERE, - base::BindOnce(&eatt_impl::upper_tester_send_data_if_needed, - weak_factory_.GetWeakPtr(), bda, lcid), - std::chrono::seconds(1)); + do_in_main_thread_delayed(FROM_HERE, + base::BindOnce(&eatt_impl::upper_tester_send_data_if_needed, + weak_factory_.GetWeakPtr(), bda, lcid), + std::chrono::seconds(1)); } } @@ -484,19 +459,17 @@ struct eatt_impl { eatt_device* eatt_dev = find_device_by_address(channel->bda_); switch (channel->state_) { case EattChannelState::EATT_CHANNEL_PENDING: - log::warn("Channel for cid: 0x{:x} is not extablished, reason: 0x{:x}", - lcid, reason); + log::warn("Channel for cid: 0x{:x} is not extablished, reason: 0x{:x}", lcid, reason); remove_channel_by_cid(eatt_dev, lcid); break; case EattChannelState::EATT_CHANNEL_RECONFIGURING: /* Just go back to open state */ - log::error("Reconfig failed fo cid: 0x{:x}, reason: 0x{:x}", lcid, - reason); + log::error("Reconfig failed fo cid: 0x{:x}, reason: 0x{:x}", lcid, reason); channel->EattChannelSetState(EattChannelState::EATT_CHANNEL_OPENED); break; default: - log::error("cid: 0x{:x}, reason: 0x{:x}, invalid state: {}", lcid, - reason, static_cast(channel->state_)); + log::error("cid: 0x{:x}, reason: 0x{:x}, invalid state: {}", lcid, reason, + static_cast(channel->state_)); break; } @@ -540,9 +513,8 @@ struct eatt_impl { } eatt_device* find_device_by_address(const RawAddress& bd_addr) { - auto iter = find_if( - devices_.begin(), devices_.end(), - [&bd_addr](const eatt_device& ed) { return ed.bda_ == bd_addr; }); + auto iter = find_if(devices_.begin(), devices_.end(), + [&bd_addr](const eatt_device& ed) { return ed.bda_ == bd_addr; }); return iter == devices_.end() ? nullptr : &(*iter); } @@ -554,54 +526,47 @@ struct eatt_impl { } void connect_eatt_wrap(eatt_device* eatt_dev) { - if (stack_config_get_interface() - ->get_pts_eatt_peripheral_collision_support()) { + if (stack_config_get_interface()->get_pts_eatt_peripheral_collision_support()) { /* For PTS case, lets assume we support only 5 channels */ - log::info("Number of existing channels {}", - (int)eatt_dev->eatt_channels.size()); - connect_eatt(eatt_dev, L2CAP_CREDIT_BASED_MAX_CIDS - - (int)eatt_dev->eatt_channels.size()); + log::info("Number of existing channels {}", (int)eatt_dev->eatt_channels.size()); + connect_eatt(eatt_dev, L2CAP_CREDIT_BASED_MAX_CIDS - (int)eatt_dev->eatt_channels.size()); return; } connect_eatt(eatt_dev); } - void connect_eatt(eatt_device* eatt_dev, - uint8_t num_of_channels = L2CAP_CREDIT_BASED_MAX_CIDS) { + void connect_eatt(eatt_device* eatt_dev, uint8_t num_of_channels = L2CAP_CREDIT_BASED_MAX_CIDS) { /* Let us use maximum possible mps */ - if (eatt_dev->rx_mps_ == EATT_MIN_MTU_MPS) - eatt_dev->rx_mps_ = - shim::GetController()->GetLeBufferSize().le_data_packet_length_; + if (eatt_dev->rx_mps_ == EATT_MIN_MTU_MPS) { + eatt_dev->rx_mps_ = shim::GetController()->GetLeBufferSize().le_data_packet_length_; + } tL2CAP_LE_CFG_INFO local_coc_cfg = { - .result = L2CAP_LE_RESULT_CONN_OK, - .mtu = eatt_dev->rx_mtu_, - .mps = eatt_dev->rx_mps_, - .credits = L2CA_LeCreditDefault(), - .number_of_channels = num_of_channels, + .result = L2CAP_LE_RESULT_CONN_OK, + .mtu = eatt_dev->rx_mtu_, + .mps = eatt_dev->rx_mps_, + .credits = L2CA_LeCreditDefault(), + .number_of_channels = num_of_channels, }; - log::info("Connecting device {}, cnt count {}", eatt_dev->bda_, - num_of_channels); + log::info("Connecting device {}, cnt count {}", eatt_dev->bda_, num_of_channels); /* Warning! CIDs in Android are unique across the ACL connections */ std::vector connecting_cids = - L2CA_ConnectCreditBasedReq(psm_, eatt_dev->bda_, &local_coc_cfg); + L2CA_ConnectCreditBasedReq(psm_, eatt_dev->bda_, &local_coc_cfg); if (connecting_cids.size() == 0) { log::error("Unable to get cid"); return; } - log::info("Successfully sent CoC request, number of channel: {}", - connecting_cids.size()); + log::info("Successfully sent CoC request, number of channel: {}", connecting_cids.size()); for (uint16_t cid : connecting_cids) { log::info("\t cid: 0x{:x}", cid); - auto chan = std::make_shared(eatt_dev->bda_, cid, 0, - eatt_dev->rx_mtu_); + auto chan = std::make_shared(eatt_dev->bda_, cid, 0, eatt_dev->rx_mtu_); eatt_dev->eatt_channels.insert({cid, chan}); } @@ -610,88 +575,85 @@ struct eatt_impl { return; } - eatt_dev->eatt_tcb_ = - gatt_find_tcb_by_addr(eatt_dev->bda_, BT_TRANSPORT_LE); + eatt_dev->eatt_tcb_ = gatt_find_tcb_by_addr(eatt_dev->bda_, BT_TRANSPORT_LE); log::assert_that(eatt_dev->eatt_tcb_ != nullptr, "assert failed: eatt_dev->eatt_tcb_ != nullptr"); } - EattChannel* find_eatt_channel_by_cid(const RawAddress& bd_addr, - uint16_t cid) { + EattChannel* find_eatt_channel_by_cid(const RawAddress& bd_addr, uint16_t cid) { eatt_device* eatt_dev = find_device_by_address(bd_addr); - if (!eatt_dev) return nullptr; + if (!eatt_dev) { + return nullptr; + } - auto iter = find_if( - eatt_dev->eatt_channels.begin(), eatt_dev->eatt_channels.end(), - [&cid](const std::pair>& el) { - return el.first == cid; - }); + auto iter = find_if(eatt_dev->eatt_channels.begin(), eatt_dev->eatt_channels.end(), + [&cid](const std::pair>& el) { + return el.first == cid; + }); return iter == eatt_dev->eatt_channels.end() ? nullptr : iter->second.get(); } - EattChannel* find_eatt_channel_by_transid(const RawAddress& bd_addr, - uint32_t trans_id) { + EattChannel* find_eatt_channel_by_transid(const RawAddress& bd_addr, uint32_t trans_id) { eatt_device* eatt_dev = find_device_by_address(bd_addr); - if (!eatt_dev) return nullptr; + if (!eatt_dev) { + return nullptr; + } - auto iter = find_if( - eatt_dev->eatt_channels.begin(), eatt_dev->eatt_channels.end(), - [&trans_id]( - const std::pair>& el) { - return el.second->server_outstanding_cmd_.trans_id == trans_id; - }); + auto iter = find_if(eatt_dev->eatt_channels.begin(), eatt_dev->eatt_channels.end(), + [&trans_id](const std::pair>& el) { + return el.second->server_outstanding_cmd_.trans_id == trans_id; + }); return iter == eatt_dev->eatt_channels.end() ? nullptr : iter->second.get(); } - bool is_indication_pending(const RawAddress& bd_addr, - uint16_t indication_handle) { + bool is_indication_pending(const RawAddress& bd_addr, uint16_t indication_handle) { eatt_device* eatt_dev = find_device_by_address(bd_addr); - if (!eatt_dev) return false; + if (!eatt_dev) { + return false; + } auto iter = find_if( - eatt_dev->eatt_channels.begin(), eatt_dev->eatt_channels.end(), - [&indication_handle]( - const std::pair>& el) { - return el.second->indicate_handle_ == indication_handle; - }); + eatt_dev->eatt_channels.begin(), eatt_dev->eatt_channels.end(), + [&indication_handle](const std::pair>& el) { + return el.second->indicate_handle_ == indication_handle; + }); - return (iter != eatt_dev->eatt_channels.end()); - }; + return iter != eatt_dev->eatt_channels.end(); + } EattChannel* get_channel_available_for_indication(const RawAddress& bd_addr) { eatt_device* eatt_dev = find_device_by_address(bd_addr); - auto iter = find_if( - eatt_dev->eatt_channels.begin(), eatt_dev->eatt_channels.end(), - [](const std::pair>& el) { - return el.second->state_ == EattChannelState::EATT_CHANNEL_OPENED && - !GATT_HANDLE_IS_VALID(el.second->indicate_handle_); - }); - - return (iter == eatt_dev->eatt_channels.end()) ? nullptr - : iter->second.get(); - }; - - EattChannel* get_channel_available_for_client_request( - const RawAddress& bd_addr) { + auto iter = find_if(eatt_dev->eatt_channels.begin(), eatt_dev->eatt_channels.end(), + [](const std::pair>& el) { + return el.second->state_ == EattChannelState::EATT_CHANNEL_OPENED && + !GATT_HANDLE_IS_VALID(el.second->indicate_handle_); + }); + + return (iter == eatt_dev->eatt_channels.end()) ? nullptr : iter->second.get(); + } + + EattChannel* get_channel_available_for_client_request(const RawAddress& bd_addr) { eatt_device* eatt_dev = find_device_by_address(bd_addr); - if (!eatt_dev) return nullptr; + if (!eatt_dev) { + return nullptr; + } - auto iter = find_if( - eatt_dev->eatt_channels.begin(), eatt_dev->eatt_channels.end(), - [](const std::pair>& el) { - return el.second->state_ == EattChannelState::EATT_CHANNEL_OPENED && - el.second->cl_cmd_q_.empty(); - }); - - return (iter == eatt_dev->eatt_channels.end()) ? nullptr - : iter->second.get(); + auto iter = find_if(eatt_dev->eatt_channels.begin(), eatt_dev->eatt_channels.end(), + [](const std::pair>& el) { + return el.second->state_ == EattChannelState::EATT_CHANNEL_OPENED && + el.second->cl_cmd_q_.empty(); + }); + + return (iter == eatt_dev->eatt_channels.end()) ? nullptr : iter->second.get(); } void free_gatt_resources(const RawAddress& bd_addr) { eatt_device* eatt_dev = find_device_by_address(bd_addr); - if (!eatt_dev) return; + if (!eatt_dev) { + return; + } auto iter = eatt_dev->eatt_channels.begin(); while (iter != eatt_dev->eatt_channels.end()) { @@ -705,33 +667,38 @@ struct eatt_impl { bool is_outstanding_msg_in_send_queue(const RawAddress& bd_addr) { eatt_device* eatt_dev = find_device_by_address(bd_addr); - if (!eatt_dev) return false; + if (!eatt_dev) { + return false; + } - auto iter = find_if( - eatt_dev->eatt_channels.begin(), eatt_dev->eatt_channels.end(), - [](const std::pair>& el) { - if (el.second->cl_cmd_q_.empty()) return false; - - tGATT_CMD_Q& cmd = el.second->cl_cmd_q_.front(); - return cmd.to_send; - }); - return (iter != eatt_dev->eatt_channels.end()); + auto iter = find_if(eatt_dev->eatt_channels.begin(), eatt_dev->eatt_channels.end(), + [](const std::pair>& el) { + if (el.second->cl_cmd_q_.empty()) { + return false; + } + + tGATT_CMD_Q& cmd = el.second->cl_cmd_q_.front(); + return cmd.to_send; + }); + return iter != eatt_dev->eatt_channels.end(); } EattChannel* get_channel_with_queued_data(const RawAddress& bd_addr) { eatt_device* eatt_dev = find_device_by_address(bd_addr); - if (!eatt_dev) return nullptr; + if (!eatt_dev) { + return nullptr; + } - auto iter = find_if( - eatt_dev->eatt_channels.begin(), eatt_dev->eatt_channels.end(), - [](const std::pair>& el) { - if (el.second->cl_cmd_q_.empty()) return false; - - tGATT_CMD_Q& cmd = el.second->cl_cmd_q_.front(); - return cmd.to_send; - }); - return (iter == eatt_dev->eatt_channels.end()) ? nullptr - : iter->second.get(); + auto iter = find_if(eatt_dev->eatt_channels.begin(), eatt_dev->eatt_channels.end(), + [](const std::pair>& el) { + if (el.second->cl_cmd_q_.empty()) { + return false; + } + + tGATT_CMD_Q& cmd = el.second->cl_cmd_q_.front(); + return cmd.to_send; + }); + return (iter == eatt_dev->eatt_channels.end()) ? nullptr : iter->second.get(); } static void eatt_ind_ack_timeout(void* data) { @@ -757,8 +724,7 @@ struct eatt_impl { return; } - alarm_set_on_mloop(channel->ind_confirmation_timer_, - GATT_WAIT_FOR_RSP_TIMEOUT_MS, + alarm_set_on_mloop(channel->ind_confirmation_timer_, GATT_WAIT_FOR_RSP_TIMEOUT_MS, eatt_ind_confirmation_timeout, channel); } @@ -779,8 +745,8 @@ struct eatt_impl { return; } - alarm_set_on_mloop(channel->ind_ack_timer_, GATT_WAIT_FOR_RSP_TIMEOUT_MS, - eatt_ind_ack_timeout, channel); + alarm_set_on_mloop(channel->ind_ack_timer_, GATT_WAIT_FOR_RSP_TIMEOUT_MS, eatt_ind_ack_timeout, + channel); } void stop_app_indication_timer(const RawAddress& bd_addr, uint16_t cid) { @@ -814,13 +780,10 @@ struct eatt_impl { std::vector cids = {cid}; tL2CAP_LE_CFG_INFO cfg = { - .result = L2CAP_LE_RESULT_CONN_OK, - .mtu = new_mtu, - .mps = eatt_dev->rx_mps_}; + .result = L2CAP_LE_RESULT_CONN_OK, .mtu = new_mtu, .mps = eatt_dev->rx_mps_}; if (!L2CA_ReconfigCreditBasedConnsReq(eatt_dev->bda_, cids, &cfg)) { - log::error("Could not start reconfig cid: 0x{:x} or device {}", cid, - bd_addr); + log::error("Could not start reconfig cid: 0x{:x} or device {}", cid, bd_addr); return; } @@ -856,9 +819,7 @@ struct eatt_impl { } tL2CAP_LE_CFG_INFO cfg = { - .result = L2CAP_LE_RESULT_CONN_OK, - .mtu = new_mtu, - .mps = eatt_dev->rx_mps_}; + .result = L2CAP_LE_RESULT_CONN_OK, .mtu = new_mtu, .mps = eatt_dev->rx_mps_}; if (!L2CA_ReconfigCreditBasedConnsReq(eatt_dev->bda_, cids, &cfg)) { log::error("Could not start reconfig for device {}", bd_addr); @@ -866,17 +827,17 @@ struct eatt_impl { } for (auto& channel : eatt_dev->eatt_channels) { - channel.second->EattChannelSetState( - EattChannelState::EATT_CHANNEL_RECONFIGURING); + channel.second->EattChannelSetState(EattChannelState::EATT_CHANNEL_RECONFIGURING); } } - void supported_features_cb(uint8_t role, const RawAddress& bd_addr, - uint8_t features) { + void supported_features_cb(uint8_t role, const RawAddress& bd_addr, uint8_t features) { bool is_eatt_supported = features & BLE_GATT_SVR_SUP_FEAT_EATT_BITMASK; log::info("{} is_eatt_supported = {}", bd_addr, int(is_eatt_supported)); - if (!is_eatt_supported) return; + if (!is_eatt_supported) { + return; + } eatt_device* eatt_dev = this->find_device_by_address(bd_addr); if (!eatt_dev) { @@ -942,16 +903,11 @@ struct eatt_impl { eatt_dev->collision = false; } - void upper_tester_connect(const RawAddress& bd_addr, eatt_device* eatt_dev, - uint8_t role) { - log::info( - "L2CAP Upper tester enabled, {} ({}), role: {}({})", bd_addr, - fmt::ptr(eatt_dev), - role == HCI_ROLE_CENTRAL ? "HCI_ROLE_CENTRAL" : "HCI_ROLE_PERIPHERAL", - role); + void upper_tester_connect(const RawAddress& bd_addr, eatt_device* eatt_dev, uint8_t role) { + log::info("L2CAP Upper tester enabled, {} ({}), role: {}({})", bd_addr, fmt::ptr(eatt_dev), + role == HCI_ROLE_CENTRAL ? "HCI_ROLE_CENTRAL" : "HCI_ROLE_PERIPHERAL", role); - auto num_of_chan = - stack_config_get_interface()->get_pts_l2cap_ecoc_initial_chan_cnt(); + auto num_of_chan = stack_config_get_interface()->get_pts_l2cap_ecoc_initial_chan_cnt(); if (num_of_chan <= 0) { num_of_chan = L2CAP_CREDIT_BASED_MAX_CIDS; } @@ -960,7 +916,9 @@ struct eatt_impl { if (stack_config_get_interface()->get_pts_connect_eatt_unconditionally()) { /* Normally eatt_dev exist only if EATT is supported by remote device. * Here it is created unconditionally */ - if (eatt_dev == nullptr) eatt_dev = add_eatt_device(bd_addr); + if (eatt_dev == nullptr) { + eatt_dev = add_eatt_device(bd_addr); + } /* For PTS just start connecting EATT right away */ connect_eatt(eatt_dev, num_of_chan); return; @@ -972,9 +930,8 @@ struct eatt_impl { } /* If we don't know yet, read GATT server supported features. */ - if (gatt_cl_read_sr_supp_feat_req( - bd_addr, base::BindOnce(&eatt_impl::supported_features_cb, - weak_factory_.GetWeakPtr(), role)) == + if (gatt_cl_read_sr_supp_feat_req(bd_addr, base::BindOnce(&eatt_impl::supported_features_cb, + weak_factory_.GetWeakPtr(), role)) == false) { log::info("Read server supported features failed for device {}", bd_addr); } @@ -994,8 +951,7 @@ struct eatt_impl { return; } - log::info("Device {}, role {}", bd_addr, - role == HCI_ROLE_CENTRAL ? "central" : "peripheral"); + log::info("Device {}, role {}", bd_addr, role == HCI_ROLE_CENTRAL ? "central" : "peripheral"); if (eatt_dev) { /* We are reconnecting device we know that support EATT. @@ -1004,8 +960,7 @@ struct eatt_impl { log::info("Known device, connect eCoC"); if (role != HCI_ROLE_CENTRAL) { - log::info( - "EATT Should be connected by the central. Let's wait for it."); + log::info("EATT Should be connected by the central. Let's wait for it."); return; } @@ -1013,7 +968,9 @@ struct eatt_impl { return; } - if (role != HCI_ROLE_CENTRAL) return; + if (role != HCI_ROLE_CENTRAL) { + return; + } if (gatt_profile_get_eatt_support(bd_addr)) { log::debug("Eatt is supported for device {}", bd_addr); @@ -1022,9 +979,8 @@ struct eatt_impl { } /* If we don't know yet, read GATT server supported features. */ - if (gatt_cl_read_sr_supp_feat_req( - bd_addr, base::BindOnce(&eatt_impl::supported_features_cb, - weak_factory_.GetWeakPtr(), role)) == + if (gatt_cl_read_sr_supp_feat_req(bd_addr, base::BindOnce(&eatt_impl::supported_features_cb, + weak_factory_.GetWeakPtr(), role)) == false) { log::info("Read server supported features failed for device {}", bd_addr); } @@ -1035,7 +991,9 @@ struct eatt_impl { log::info("restoring: {}", bd_addr); - if (!eatt_dev) add_eatt_device(bd_addr); + if (!eatt_dev) { + add_eatt_device(bd_addr); + } } }; diff --git a/system/stack/fuzzers/avrc_fuzzer.cc b/system/stack/fuzzers/avrc_fuzzer.cc index 69c58bcc4b3..21662d28b41 100644 --- a/system/stack/fuzzers/avrc_fuzzer.cc +++ b/system/stack/fuzzers/avrc_fuzzer.cc @@ -55,10 +55,9 @@ constexpr uint8_t kDummyRemoteAddr[] = {0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC}; static tL2CAP_APPL_INFO avct_appl, avct_br_appl; class FakeBtStack { - public: +public: FakeBtStack() { - test::mock::stack_l2cap_api::L2CA_DataWrite.body = [](uint16_t cid, - BT_HDR* hdr) { + test::mock::stack_l2cap_api::L2CA_DataWrite.body = [](uint16_t cid, BT_HDR* hdr) { log::assert_that(cid == kDummyCid, "assert failed: cid == kDummyCid"); ConsumeData((const uint8_t*)hdr, hdr->offset + hdr->len); osi_free(hdr); @@ -69,25 +68,24 @@ class FakeBtStack { return true; }; test::mock::stack_l2cap_api::L2CA_ConnectReqWithSecurity.body = - [](uint16_t psm, const RawAddress& p_bd_addr, uint16_t sec_level) { - log::assert_that(p_bd_addr == kDummyRemoteAddr, - "assert failed: p_bd_addr == kDummyRemoteAddr"); - return kDummyCid; - }; + [](uint16_t psm, const RawAddress& p_bd_addr, uint16_t sec_level) { + log::assert_that(p_bd_addr == kDummyRemoteAddr, + "assert failed: p_bd_addr == kDummyRemoteAddr"); + return kDummyCid; + }; test::mock::stack_l2cap_api::L2CA_RegisterWithSecurity.body = - [](uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info, bool enable_snoop, - tL2CAP_ERTM_INFO* p_ertm_info, uint16_t my_mtu, - uint16_t required_remote_mtu, uint16_t sec_level) { - log::assert_that( - psm == AVCT_PSM || psm == AVCT_BR_PSM, - "assert failed: psm == AVCT_PSM || psm == AVCT_BR_PSM"); - if (psm == AVCT_PSM) { - avct_appl = p_cb_info; - } else if (psm == AVCT_BR_PSM) { - avct_br_appl = p_cb_info; - } - return psm; - }; + [](uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info, bool enable_snoop, + tL2CAP_ERTM_INFO* p_ertm_info, uint16_t my_mtu, uint16_t required_remote_mtu, + uint16_t sec_level) { + log::assert_that(psm == AVCT_PSM || psm == AVCT_BR_PSM, + "assert failed: psm == AVCT_PSM || psm == AVCT_BR_PSM"); + if (psm == AVCT_PSM) { + avct_appl = p_cb_info; + } else if (psm == AVCT_BR_PSM) { + avct_br_appl = p_cb_info; + } + return psm; + }; test::mock::stack_l2cap_api::L2CA_Deregister.body = [](uint16_t psm) {}; } @@ -101,7 +99,7 @@ class FakeBtStack { }; class Fakes { - public: +public: test::fake::FakeOsi fake_osi; FakeBtStack fake_stack; }; @@ -128,11 +126,9 @@ std::optional nap() { return false; } } // namespace android #endif -static void ctrl_cb(uint8_t handle, uint8_t event, uint16_t result, - const RawAddress* peer_addr) {} +static void ctrl_cb(uint8_t handle, uint8_t event, uint16_t result, const RawAddress* peer_addr) {} -static void msg_cb(uint8_t handle, uint8_t label, uint8_t opcode, - tAVRC_MSG* p_msg) { +static void msg_cb(uint8_t handle, uint8_t label, uint8_t opcode, tAVRC_MSG* p_msg) { uint8_t scratch_buf[512]; tAVRC_STS status; @@ -184,10 +180,10 @@ static void Fuzz(const uint8_t* data, size_t size) { tL2CAP_APPL_INFO* appl_info = is_br ? &avct_br_appl : &avct_appl; tAVRC_CONN_CB ccb = { - .ctrl_cback = base::Bind(ctrl_cb), - .msg_cback = base::Bind(msg_cb), - .conn = (uint8_t)(is_initiator ? AVCT_INT : AVCT_ACP), - .control = (uint8_t)(is_controller ? AVCT_CONTROL : AVCT_TARGET), + .ctrl_cback = base::Bind(ctrl_cb), + .msg_cback = base::Bind(msg_cb), + .conn = (uint8_t)(is_initiator ? AVCT_INT : AVCT_ACP), + .control = (uint8_t)(is_controller ? AVCT_CONTROL : AVCT_TARGET), }; appl_info->pL2CA_ConnectInd_Cb(kDummyRemoteAddr, kDummyCid, 0, kDummyId); diff --git a/system/stack/fuzzers/bnep_fuzzer.cc b/system/stack/fuzzers/bnep_fuzzer.cc index 34ec0fb1182..905e2b5fdfc 100644 --- a/system/stack/fuzzers/bnep_fuzzer.cc +++ b/system/stack/fuzzers/bnep_fuzzer.cc @@ -38,45 +38,39 @@ namespace { constexpr uint16_t kDummyCid = 0x1234; constexpr uint8_t kDummyId = 0x77; constexpr uint8_t kDummyRemoteAddr[] = {0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC}; -constexpr uint8_t kDummySrcUuid[] = {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, - 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, - 0xcc, 0xdd, 0xee, 0xff}; -constexpr uint8_t kDummyDstUuid[] = {0x00, 0x00, 0x00, 0x00, 0x22, 0x22, - 0x22, 0x22, 0x33, 0x33, 0x55, 0x55, - 0x55, 0x55, 0x55, 0x59}; +constexpr uint8_t kDummySrcUuid[] = {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, + 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff}; +constexpr uint8_t kDummyDstUuid[] = {0x00, 0x00, 0x00, 0x00, 0x22, 0x22, 0x22, 0x22, + 0x33, 0x33, 0x55, 0x55, 0x55, 0x55, 0x55, 0x59}; // Set up default callback structure static tL2CAP_APPL_INFO appl_info; class FakeBtStack { - public: +public: FakeBtStack() { - test::mock::stack_l2cap_api::L2CA_DataWrite.body = [](uint16_t cid, - BT_HDR* p_data) { - bluetooth::log::assert_that(cid == kDummyCid, - "assert failed: cid == kDummyCid"); + test::mock::stack_l2cap_api::L2CA_DataWrite.body = [](uint16_t cid, BT_HDR* p_data) { + bluetooth::log::assert_that(cid == kDummyCid, "assert failed: cid == kDummyCid"); osi_free(p_data); return tL2CAP_DW_RESULT::SUCCESS; }; test::mock::stack_l2cap_api::L2CA_DisconnectReq.body = [](uint16_t cid) { - bluetooth::log::assert_that(cid == kDummyCid, - "assert failed: cid == kDummyCid"); + bluetooth::log::assert_that(cid == kDummyCid, "assert failed: cid == kDummyCid"); return true; }; test::mock::stack_l2cap_api::L2CA_ConnectReqWithSecurity.body = - [](uint16_t psm, const RawAddress& p_bd_addr, uint16_t sec_level) { - bluetooth::log::assert_that( - p_bd_addr == kDummyRemoteAddr, - "assert failed: p_bd_addr == kDummyRemoteAddr"); - return kDummyCid; - }; + [](uint16_t psm, const RawAddress& p_bd_addr, uint16_t sec_level) { + bluetooth::log::assert_that(p_bd_addr == kDummyRemoteAddr, + "assert failed: p_bd_addr == kDummyRemoteAddr"); + return kDummyCid; + }; test::mock::stack_l2cap_api::L2CA_RegisterWithSecurity.body = - [](uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info, bool enable_snoop, - tL2CAP_ERTM_INFO* p_ertm_info, uint16_t my_mtu, - uint16_t required_remote_mtu, uint16_t sec_level) { - appl_info = p_cb_info; - return psm; - }; + [](uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info, bool enable_snoop, + tL2CAP_ERTM_INFO* p_ertm_info, uint16_t my_mtu, uint16_t required_remote_mtu, + uint16_t sec_level) { + appl_info = p_cb_info; + return psm; + }; test::mock::stack_l2cap_api::L2CA_Deregister.body = [](uint16_t psm) {}; } @@ -90,7 +84,7 @@ class FakeBtStack { }; class Fakes { - public: +public: test::fake::FakeOsi fake_osi; FakeBtStack fake_stack; }; @@ -107,26 +101,21 @@ static void ConsumeData(const uint8_t* data, size_t size) { static void Fuzz(const uint8_t* data, size_t size) { tBNEP_REGISTER reg = { - .p_conn_ind_cb = - [](uint16_t handle, const RawAddress& bd_addr, - const bluetooth::Uuid& remote_uuid, - const bluetooth::Uuid& local_uuid, - bool is_role_change) { BNEP_ConnectResp(handle, BNEP_SUCCESS); }, - .p_conn_state_cb = [](uint16_t handle, const RawAddress& rem_bda, - tBNEP_RESULT result, bool is_role_change) {}, - .p_data_ind_cb = [](uint16_t handle, const RawAddress& src, - const RawAddress& dst, uint16_t protocol, - uint8_t* p_data, uint16_t len, - bool fw_ext_present) { ConsumeData(p_data, len); }, - .p_tx_data_flow_cb = [](uint16_t handle, tBNEP_RESULT event) {}, - .p_filter_ind_cb = - [](uint16_t handle, bool indication, tBNEP_RESULT result, - uint16_t num_filters, - uint8_t* p_filters) { ConsumeData(p_filters, num_filters); }, - .p_mfilter_ind_cb = - [](uint16_t handle, bool indication, tBNEP_RESULT result, - uint16_t num_mfilters, - uint8_t* p_mfilters) { ConsumeData(p_mfilters, num_mfilters); }, + .p_conn_ind_cb = [](uint16_t handle, const RawAddress& bd_addr, + const bluetooth::Uuid& remote_uuid, const bluetooth::Uuid& local_uuid, + bool is_role_change) { BNEP_ConnectResp(handle, BNEP_SUCCESS); }, + .p_conn_state_cb = [](uint16_t handle, const RawAddress& rem_bda, tBNEP_RESULT result, + bool is_role_change) {}, + .p_data_ind_cb = [](uint16_t handle, const RawAddress& src, const RawAddress& dst, + uint16_t protocol, uint8_t* p_data, uint16_t len, + bool fw_ext_present) { ConsumeData(p_data, len); }, + .p_tx_data_flow_cb = [](uint16_t handle, tBNEP_RESULT event) {}, + .p_filter_ind_cb = [](uint16_t handle, bool indication, tBNEP_RESULT result, + uint16_t num_filters, + uint8_t* p_filters) { ConsumeData(p_filters, num_filters); }, + .p_mfilter_ind_cb = [](uint16_t handle, bool indication, tBNEP_RESULT result, + uint16_t num_mfilters, + uint8_t* p_mfilters) { ConsumeData(p_mfilters, num_mfilters); }, }; BNEP_Init(); diff --git a/system/stack/fuzzers/gatt_fuzzer.cc b/system/stack/fuzzers/gatt_fuzzer.cc index a5a1c6aa96c..85dbadf2f09 100644 --- a/system/stack/fuzzers/gatt_fuzzer.cc +++ b/system/stack/fuzzers/gatt_fuzzer.cc @@ -33,14 +33,12 @@ #include "test/mock/mock_stack_l2cap_ble.h" using bluetooth::Uuid; -bt_status_t do_in_main_thread(base::Location const&, - base::OnceCallback) { +bt_status_t do_in_main_thread(base::Location const&, base::OnceCallback) { // this is not properly mocked, so we use abort to catch if this is used in // any test cases abort(); } -bt_status_t do_in_main_thread_delayed(base::Location const&, - base::OnceCallback, +bt_status_t do_in_main_thread_delayed(base::Location const&, base::OnceCallback, std::chrono::microseconds) { // this is not properly mocked, so we use abort to catch if this is used in // any test cases @@ -64,58 +62,56 @@ tL2CAP_APPL_INFO appl_info; tBTM_SEC_DEV_REC btm_sec_dev_rec; class FakeBtStack { - public: +public: FakeBtStack() { test::mock::stack_btm_dev::btm_find_dev.body = [](const RawAddress&) { return &btm_sec_dev_rec; }; - test::mock::stack_l2cap_ble::L2CA_GetBleConnRole.body = - [](const RawAddress&) { return HCI_ROLE_CENTRAL; }; - - test::mock::stack_l2cap_api::L2CA_SetIdleTimeoutByBdAddr.body = - [](const RawAddress&, uint16_t, uint8_t) { return true; }; - test::mock::stack_l2cap_api::L2CA_RemoveFixedChnl.body = - [](uint16_t lcid, const RawAddress&) { - bluetooth::log::assert_that(lcid == L2CAP_ATT_CID, - "assert failed: lcid == L2CAP_ATT_CID"); - return true; - }; - test::mock::stack_l2cap_api::L2CA_ConnectFixedChnl.body = - [](uint16_t, const RawAddress&) { return true; }; - test::mock::stack_l2cap_api::L2CA_DataWrite.body = [](uint16_t lcid, - BT_HDR* hdr) { - osi_free(hdr); - return tL2CAP_DW_RESULT::SUCCESS; + test::mock::stack_l2cap_ble::L2CA_GetBleConnRole.body = [](const RawAddress&) { + return HCI_ROLE_CENTRAL; + }; + + test::mock::stack_l2cap_api::L2CA_SetIdleTimeoutByBdAddr.body = [](const RawAddress&, uint16_t, + uint8_t) { return true; }; + test::mock::stack_l2cap_api::L2CA_RemoveFixedChnl.body = [](uint16_t lcid, const RawAddress&) { + bluetooth::log::assert_that(lcid == L2CAP_ATT_CID, "assert failed: lcid == L2CAP_ATT_CID"); + return true; }; - test::mock::stack_l2cap_api::L2CA_DisconnectReq.body = [](uint16_t) { + test::mock::stack_l2cap_api::L2CA_ConnectFixedChnl.body = [](uint16_t, const RawAddress&) { return true; }; + test::mock::stack_l2cap_api::L2CA_DataWrite.body = [](uint16_t lcid, BT_HDR* hdr) { + osi_free(hdr); + return tL2CAP_DW_RESULT::SUCCESS; + }; + test::mock::stack_l2cap_api::L2CA_DisconnectReq.body = [](uint16_t) { return true; }; test::mock::stack_l2cap_api::L2CA_SendFixedChnlData.body = - [](uint16_t cid, const RawAddress& addr, BT_HDR* hdr) { - osi_free(hdr); - return tL2CAP_DW_RESULT::SUCCESS; - }; + [](uint16_t cid, const RawAddress& addr, BT_HDR* hdr) { + osi_free(hdr); + return tL2CAP_DW_RESULT::SUCCESS; + }; test::mock::stack_l2cap_api::L2CA_RegisterFixedChannel.body = - [](uint16_t fixed_cid, tL2CAP_FIXED_CHNL_REG* p_freg) { - fixed_chnl_reg = *p_freg; - return true; - }; + [](uint16_t fixed_cid, tL2CAP_FIXED_CHNL_REG* p_freg) { + fixed_chnl_reg = *p_freg; + return true; + }; test::mock::stack_l2cap_api::L2CA_RegisterWithSecurity.body = - [](uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info, bool enable_snoop, - tL2CAP_ERTM_INFO* p_ertm_info, uint16_t my_mtu, - uint16_t required_remote_mtu, uint16_t sec_level) { - appl_info = p_cb_info; - return psm; - }; + [](uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info, bool enable_snoop, + tL2CAP_ERTM_INFO* p_ertm_info, uint16_t my_mtu, uint16_t required_remote_mtu, + uint16_t sec_level) { + appl_info = p_cb_info; + return psm; + }; test::mock::stack_l2cap_api::L2CA_RegisterLECoc.body = - [](uint16_t psm, const tL2CAP_APPL_INFO& p_fixed_chnl_reg, - uint16_t sec_level, tL2CAP_LE_CFG_INFO cfg) { return psm; }; + [](uint16_t psm, const tL2CAP_APPL_INFO& p_fixed_chnl_reg, uint16_t sec_level, + tL2CAP_LE_CFG_INFO cfg) { return psm; }; - test::mock::stack_l2cap_api::L2CA_SetIdleTimeoutByBdAddr.body = - [](const RawAddress&, uint16_t, uint8_t) { return true; }; - test::mock::stack_l2cap_api::L2CA_SetLeGattTimeout.body = - [](const RawAddress&, uint16_t) { return true; }; + test::mock::stack_l2cap_api::L2CA_SetIdleTimeoutByBdAddr.body = [](const RawAddress&, uint16_t, + uint8_t) { return true; }; + test::mock::stack_l2cap_api::L2CA_SetLeGattTimeout.body = [](const RawAddress&, uint16_t) { + return true; + }; } ~FakeBtStack() { @@ -137,7 +133,7 @@ class FakeBtStack { }; class Fakes { - public: +public: test::fake::FakeOsi fake_osi; FakeBtStack fake_stack; }; @@ -159,20 +155,18 @@ static void GattInit() { Uuid app_uuid = Uuid::From128BitBE(tmp); tGATT_CBACK gap_cback = { - .p_conn_cb = [](tGATT_IF, const RawAddress&, uint16_t conn_id, - bool connected, tGATT_DISCONN_REASON, - tBT_TRANSPORT) { s_ConnId = conn_id; }, - .p_cmpl_cb = [](uint16_t, tGATTC_OPTYPE, tGATT_STATUS, - tGATT_CL_COMPLETE*) {}, - .p_disc_res_cb = nullptr, - .p_disc_cmpl_cb = nullptr, - .p_req_cb = [](uint16_t conn_id, uint32_t trans_id, tGATTS_REQ_TYPE type, - tGATTS_DATA* p_data) {}, - .p_enc_cmpl_cb = nullptr, - .p_congestion_cb = nullptr, - .p_phy_update_cb = nullptr, - .p_conn_update_cb = nullptr, - .p_subrate_chg_cb = nullptr, + .p_conn_cb = [](tGATT_IF, const RawAddress&, uint16_t conn_id, bool connected, + tGATT_DISCONN_REASON, tBT_TRANSPORT) { s_ConnId = conn_id; }, + .p_cmpl_cb = [](uint16_t, tGATTC_OPTYPE, tGATT_STATUS, tGATT_CL_COMPLETE*) {}, + .p_disc_res_cb = nullptr, + .p_disc_cmpl_cb = nullptr, + .p_req_cb = [](uint16_t conn_id, uint32_t trans_id, tGATTS_REQ_TYPE type, + tGATTS_DATA* p_data) {}, + .p_enc_cmpl_cb = nullptr, + .p_congestion_cb = nullptr, + .p_phy_update_cb = nullptr, + .p_conn_update_cb = nullptr, + .p_subrate_chg_cb = nullptr, }; s_AppIf = GATT_Register(app_uuid, "Gap", &gap_cback, false); @@ -183,9 +177,9 @@ static void ServerInit() { GattInit(); tGATT_APPL_INFO appl_info = { - .p_nv_save_callback = [](bool, tGATTS_HNDL_RANGE*) {}, - .p_srv_chg_callback = [](tGATTS_SRV_CHG_CMD, tGATTS_SRV_CHG_REQ*, - tGATTS_SRV_CHG_RSP*) { return true; }, + .p_nv_save_callback = [](bool, tGATTS_HNDL_RANGE*) {}, + .p_srv_chg_callback = [](tGATTS_SRV_CHG_CMD, tGATTS_SRV_CHG_REQ*, + tGATTS_SRV_CHG_RSP*) { return true; }, }; (void)GATTS_NVRegister(&appl_info); @@ -194,27 +188,25 @@ static void ServerInit() { Uuid icon_uuid = Uuid::From16Bit(GATT_UUID_GAP_ICON); Uuid addr_res_uuid = Uuid::From16Bit(GATT_UUID_GAP_CENTRAL_ADDR_RESOL); - btgatt_db_element_t service[] = { - { - .uuid = svc_uuid, - .type = BTGATT_DB_PRIMARY_SERVICE, - }, - {.uuid = name_uuid, - .type = BTGATT_DB_CHARACTERISTIC, - .properties = GATT_CHAR_PROP_BIT_READ, - .permissions = GATT_PERM_READ_IF_ENCRYPTED_OR_DISCOVERABLE}, - {.uuid = icon_uuid, - .type = BTGATT_DB_CHARACTERISTIC, - .properties = GATT_CHAR_PROP_BIT_READ, - .permissions = GATT_PERM_READ}, - {.uuid = addr_res_uuid, - .type = BTGATT_DB_CHARACTERISTIC, - .properties = GATT_CHAR_PROP_BIT_READ, - .permissions = GATT_PERM_READ}}; + btgatt_db_element_t service[] = {{ + .uuid = svc_uuid, + .type = BTGATT_DB_PRIMARY_SERVICE, + }, + {.uuid = name_uuid, + .type = BTGATT_DB_CHARACTERISTIC, + .properties = GATT_CHAR_PROP_BIT_READ, + .permissions = GATT_PERM_READ_IF_ENCRYPTED_OR_DISCOVERABLE}, + {.uuid = icon_uuid, + .type = BTGATT_DB_CHARACTERISTIC, + .properties = GATT_CHAR_PROP_BIT_READ, + .permissions = GATT_PERM_READ}, + {.uuid = addr_res_uuid, + .type = BTGATT_DB_CHARACTERISTIC, + .properties = GATT_CHAR_PROP_BIT_READ, + .permissions = GATT_PERM_READ}}; /* Add a GAP service */ - (void)GATTS_AddService(s_AppIf, service, - sizeof(service) / sizeof(btgatt_db_element_t)); + (void)GATTS_AddService(s_AppIf, service, sizeof(service) / sizeof(btgatt_db_element_t)); } static void ServerCleanup() { @@ -224,8 +216,7 @@ static void ServerCleanup() { static void FuzzAsServer(FuzzedDataProvider& fdp) { ServerInit(); - fixed_chnl_reg.pL2CA_FixedConn_Cb(L2CAP_ATT_CID, kDummyAddr, true, 0, - BT_TRANSPORT_LE); + fixed_chnl_reg.pL2CA_FixedConn_Cb(L2CAP_ATT_CID, kDummyAddr, true, 0, BT_TRANSPORT_LE); while (fdp.remaining_bytes() > 0) { auto size = fdp.ConsumeIntegralInRange(0, kMaxPacketSize); @@ -241,8 +232,7 @@ static void FuzzAsServer(FuzzedDataProvider& fdp) { static void ClientInit() { GattInit(); - (void)GATT_Connect(s_AppIf, kDummyAddr, BTM_BLE_DIRECT_CONNECTION, - BT_TRANSPORT_LE, false); + (void)GATT_Connect(s_AppIf, kDummyAddr, BTM_BLE_DIRECT_CONNECTION, BT_TRANSPORT_LE, false); } static void ClientCleanup() { @@ -253,8 +243,7 @@ static void ClientCleanup() { static void FuzzAsClient(FuzzedDataProvider& fdp) { ClientInit(); - fixed_chnl_reg.pL2CA_FixedConn_Cb(L2CAP_ATT_CID, kDummyAddr, true, 0, - BT_TRANSPORT_LE); + fixed_chnl_reg.pL2CA_FixedConn_Cb(L2CAP_ATT_CID, kDummyAddr, true, 0, BT_TRANSPORT_LE); while (fdp.remaining_bytes() > 0) { auto op = fdp.ConsumeIntegral(); @@ -265,27 +254,24 @@ static void FuzzAsClient(FuzzedDataProvider& fdp) { break; } case GATTC_OPTYPE_DISCOVERY: { - auto type = (tGATT_DISC_TYPE)fdp.ConsumeIntegralInRange( - 0, GATT_DISC_MAX); + auto type = (tGATT_DISC_TYPE)fdp.ConsumeIntegralInRange(0, GATT_DISC_MAX); uint16_t start = fdp.ConsumeIntegral(); uint16_t end = fdp.ConsumeIntegral(); (void)GATTC_Discover(s_ConnId, type, start, end); break; } case GATTC_OPTYPE_READ: { - auto type = (tGATT_READ_TYPE)fdp.ConsumeIntegralInRange( - 0, GATT_READ_MAX); + auto type = (tGATT_READ_TYPE)fdp.ConsumeIntegralInRange(0, GATT_READ_MAX); tGATT_READ_PARAM param = {}; fdp.ConsumeData(¶m, sizeof(param)); (void)GATTC_Read(s_ConnId, type, ¶m); break; } case GATTC_OPTYPE_WRITE: { - auto type = (tGATT_WRITE_TYPE)fdp.ConsumeIntegralInRange( - 0, GATT_WRITE_PREPARE + 1); + auto type = + (tGATT_WRITE_TYPE)fdp.ConsumeIntegralInRange(0, GATT_WRITE_PREPARE + 1); tGATT_VALUE value = {}; - value.len = - fdp.ConsumeIntegralInRange(0, sizeof(value.value)); + value.len = fdp.ConsumeIntegralInRange(0, sizeof(value.value)); value.len = fdp.ConsumeData(&value.value, value.len); (void)GATTC_Write(s_ConnId, type, &value); break; @@ -306,8 +292,7 @@ static void FuzzAsClient(FuzzedDataProvider& fdp) { fixed_chnl_reg.pL2CA_FixedData_Cb(L2CAP_ATT_CID, kDummyAddr, hdr); } - fixed_chnl_reg.pL2CA_FixedConn_Cb(L2CAP_ATT_CID, kDummyAddr, false, 0, - BT_TRANSPORT_LE); + fixed_chnl_reg.pL2CA_FixedConn_Cb(L2CAP_ATT_CID, kDummyAddr, false, 0, BT_TRANSPORT_LE); ClientCleanup(); } diff --git a/system/stack/fuzzers/l2cap_fuzzer.cc b/system/stack/fuzzers/l2cap_fuzzer.cc index 90d63d42886..6ec3cf65a9d 100644 --- a/system/stack/fuzzers/l2cap_fuzzer.cc +++ b/system/stack/fuzzers/l2cap_fuzzer.cc @@ -55,14 +55,12 @@ static void ConsumeData(const uint8_t* data, size_t size) { tBTM_CB btm_cb; -bt_status_t do_in_main_thread(base::Location const&, - base::OnceCallback) { +bt_status_t do_in_main_thread(base::Location const&, base::OnceCallback) { // this is not properly mocked, so we use abort to catch if this is used in // any test cases abort(); } -bt_status_t do_in_main_thread_delayed(base::Location const&, - base::OnceCallback, +bt_status_t do_in_main_thread_delayed(base::Location const&, base::OnceCallback, std::chrono::microseconds) { // this is not properly mocked, so we use abort to catch if this is used in // any test cases @@ -73,8 +71,8 @@ bluetooth::common::PostableContext* get_main() { return nullptr; } namespace bluetooth { namespace os { -uint32_t GetSystemPropertyUint32Base(const std::string& property, - uint32_t default_value, int base) { +uint32_t GetSystemPropertyUint32Base(const std::string& property, uint32_t default_value, + int base) { return default_value; } } // namespace os @@ -91,40 +89,37 @@ void SnoopLogger::AddRfcommL2capChannel(uint16_t, uint16_t, uint16_t) {} void SnoopLogger::ClearL2capAcceptlist(uint16_t, uint16_t, uint16_t) {} void SnoopLogger::RemoveA2dpMediaChannel(uint16_t, uint16_t) {} void SnoopLogger::SetL2capChannelClose(uint16_t, uint16_t, uint16_t) {} -void SnoopLogger::SetL2capChannelOpen(uint16_t, uint16_t, uint16_t, uint16_t, - bool) {} +void SnoopLogger::SetL2capChannelOpen(uint16_t, uint16_t, uint16_t, uint16_t, bool) {} } // namespace hal } // namespace bluetooth namespace { class FakeBtStack { - public: +public: FakeBtStack() { test::mock::stack_btm_devctl::BTM_IsDeviceUp.body = []() { return true; }; - test::mock::stack_acl::acl_create_le_connection.body = - [](const RawAddress& bd_addr) { return true; }; - test::mock::stack_acl::acl_send_data_packet_br_edr.body = - [](const RawAddress& bd_addr, BT_HDR* hdr) { - ConsumeData((const uint8_t*)hdr, hdr->offset + hdr->len); - osi_free(hdr); - }; - test::mock::stack_acl::acl_send_data_packet_ble.body = - [](const RawAddress& bd_addr, BT_HDR* hdr) { - ConsumeData((const uint8_t*)hdr, hdr->offset + hdr->len); - osi_free(hdr); - }; - - GetInterfaceToProfiles()->profileSpecific_HACK->GetHearingAidDeviceCount = - []() { return 1; }; - - ON_CALL(controller_, GetLeSuggestedDefaultDataLength) - .WillByDefault(Return(512)); + test::mock::stack_acl::acl_create_le_connection.body = [](const RawAddress& bd_addr) { + return true; + }; + test::mock::stack_acl::acl_send_data_packet_br_edr.body = [](const RawAddress& bd_addr, + BT_HDR* hdr) { + ConsumeData((const uint8_t*)hdr, hdr->offset + hdr->len); + osi_free(hdr); + }; + test::mock::stack_acl::acl_send_data_packet_ble.body = [](const RawAddress& bd_addr, + BT_HDR* hdr) { + ConsumeData((const uint8_t*)hdr, hdr->offset + hdr->len); + osi_free(hdr); + }; + + GetInterfaceToProfiles()->profileSpecific_HACK->GetHearingAidDeviceCount = []() { return 1; }; + + ON_CALL(controller_, GetLeSuggestedDefaultDataLength).WillByDefault(Return(512)); bluetooth::hci::LeBufferSize iso_size; iso_size.le_data_packet_length_ = 512; iso_size.total_num_le_packets_ = 6; - ON_CALL(controller_, GetControllerIsoBufferSize) - .WillByDefault(Return(iso_size)); + ON_CALL(controller_, GetControllerIsoBufferSize).WillByDefault(Return(iso_size)); bluetooth::hci::LeBufferSize le_size; le_size.le_data_packet_length_ = 512; le_size.total_num_le_packets_ = 6; @@ -145,7 +140,7 @@ class FakeBtStack { }; class Fakes { - public: +public: test::fake::FakeOsi fake_osi; FakeBtStack fake_stack; }; @@ -163,8 +158,7 @@ constexpr uint16_t kSmpBrHndl = 0x0222; constexpr uint16_t kNumClassicAclBuffer = 100; constexpr uint16_t kNumLeAclBuffer = 100; -void l2c_link_hci_conn_comp(tHCI_STATUS status, uint16_t handle, - const RawAddress& p_bda); +void l2c_link_hci_conn_comp(tHCI_STATUS status, uint16_t handle, const RawAddress& p_bda); static void Fuzz(const uint8_t* data, size_t size) { memset(&btm_cb, 0, sizeof(btm_cb)); @@ -172,70 +166,60 @@ static void Fuzz(const uint8_t* data, size_t size) { l2c_init(); l2c_link_init(kNumClassicAclBuffer); - l2c_link_processs_ble_num_bufs(kNumLeAclBuffer); + l2c_link_process_ble_num_bufs(kNumLeAclBuffer); tL2CAP_FIXED_CHNL_REG reg = { - .pL2CA_FixedConn_Cb = [](uint16_t, const RawAddress&, bool, uint16_t, - tBT_TRANSPORT) {}, - .pL2CA_FixedData_Cb = - [](uint16_t, const RawAddress&, BT_HDR* hdr) { - ConsumeData((const uint8_t*)hdr, hdr->offset + hdr->len); - }, - .pL2CA_FixedCong_Cb = [](const RawAddress&, bool) {}, - .default_idle_tout = 1000, + .pL2CA_FixedConn_Cb = [](uint16_t, const RawAddress&, bool, uint16_t, tBT_TRANSPORT) {}, + .pL2CA_FixedData_Cb = + [](uint16_t, const RawAddress&, BT_HDR* hdr) { + ConsumeData((const uint8_t*)hdr, hdr->offset + hdr->len); + }, + .pL2CA_FixedCong_Cb = [](const RawAddress&, bool) {}, + .default_idle_tout = 1000, }; tL2CAP_APPL_INFO appl_info = { - .pL2CA_ConnectInd_Cb = [](const RawAddress&, uint16_t, uint16_t, - uint8_t) {}, - .pL2CA_ConnectCfm_Cb = [](uint16_t, uint16_t) {}, - .pL2CA_ConfigInd_Cb = [](uint16_t, tL2CAP_CFG_INFO*) {}, - .pL2CA_ConfigCfm_Cb = [](uint16_t, uint16_t, tL2CAP_CFG_INFO*) {}, - .pL2CA_DisconnectInd_Cb = [](uint16_t, bool) {}, - .pL2CA_DisconnectCfm_Cb = [](uint16_t, uint16_t) {}, - .pL2CA_DataInd_Cb = - [](uint16_t, BT_HDR* hdr) { - ConsumeData((const uint8_t*)hdr, hdr->offset + hdr->len); - }, - .pL2CA_CongestionStatus_Cb = [](uint16_t, bool) {}, - .pL2CA_TxComplete_Cb = [](uint16_t, uint16_t) {}, - .pL2CA_Error_Cb = [](uint16_t, uint16_t) {}, - .pL2CA_CreditBasedConnectInd_Cb = [](const RawAddress&, - std::vector&, uint16_t, - uint16_t, uint8_t) {}, - .pL2CA_CreditBasedConnectCfm_Cb = [](const RawAddress&, uint16_t, - uint16_t, uint16_t) {}, - .pL2CA_CreditBasedReconfigCompleted_Cb = [](const RawAddress&, uint16_t, - bool, tL2CAP_LE_CFG_INFO*) {}, - .pL2CA_CreditBasedCollisionInd_Cb = [](const RawAddress&) {}, + .pL2CA_ConnectInd_Cb = [](const RawAddress&, uint16_t, uint16_t, uint8_t) {}, + .pL2CA_ConnectCfm_Cb = [](uint16_t, uint16_t) {}, + .pL2CA_ConfigInd_Cb = [](uint16_t, tL2CAP_CFG_INFO*) {}, + .pL2CA_ConfigCfm_Cb = [](uint16_t, uint16_t, tL2CAP_CFG_INFO*) {}, + .pL2CA_DisconnectInd_Cb = [](uint16_t, bool) {}, + .pL2CA_DisconnectCfm_Cb = [](uint16_t, uint16_t) {}, + .pL2CA_DataInd_Cb = + [](uint16_t, BT_HDR* hdr) { + ConsumeData((const uint8_t*)hdr, hdr->offset + hdr->len); + }, + .pL2CA_CongestionStatus_Cb = [](uint16_t, bool) {}, + .pL2CA_TxComplete_Cb = [](uint16_t, uint16_t) {}, + .pL2CA_Error_Cb = [](uint16_t, uint16_t) {}, + .pL2CA_CreditBasedConnectInd_Cb = [](const RawAddress&, std::vector&, uint16_t, + uint16_t, uint8_t) {}, + .pL2CA_CreditBasedConnectCfm_Cb = [](const RawAddress&, uint16_t, uint16_t, uint16_t) {}, + .pL2CA_CreditBasedReconfigCompleted_Cb = [](const RawAddress&, uint16_t, bool, + tL2CAP_LE_CFG_INFO*) {}, + .pL2CA_CreditBasedCollisionInd_Cb = [](const RawAddress&) {}, }; - log::assert_that( - L2CA_RegisterWithSecurity(BT_PSM_ATT, appl_info, false, nullptr, - L2CAP_MTU_SIZE, 0, BTM_SEC_NONE), - "assert failed: L2CA_RegisterWithSecurity(BT_PSM_ATT, appl_info, " - "false, nullptr, L2CAP_MTU_SIZE, 0, BTM_SEC_NONE)"); + log::assert_that(L2CA_RegisterWithSecurity(BT_PSM_ATT, appl_info, false, nullptr, L2CAP_MTU_SIZE, + 0, BTM_SEC_NONE), + "assert failed: L2CA_RegisterWithSecurity(BT_PSM_ATT, appl_info, " + "false, nullptr, L2CAP_MTU_SIZE, 0, BTM_SEC_NONE)"); log::assert_that(L2CA_RegisterLECoc(BT_PSM_EATT, appl_info, BTM_SEC_NONE, {}), "assert failed: L2CA_RegisterLECoc(BT_PSM_EATT, appl_info, " "BTM_SEC_NONE, {{}})"); + log::assert_that(L2CA_RegisterFixedChannel(L2CAP_ATT_CID, ®), + "assert failed: L2CA_RegisterFixedChannel(L2CAP_ATT_CID, ®)"); + log::assert_that(L2CA_ConnectFixedChnl(L2CAP_ATT_CID, kAttAddr), + "assert failed: L2CA_ConnectFixedChnl(L2CAP_ATT_CID, kAttAddr)"); log::assert_that( - L2CA_RegisterFixedChannel(L2CAP_ATT_CID, ®), - "assert failed: L2CA_RegisterFixedChannel(L2CAP_ATT_CID, ®)"); - log::assert_that( - L2CA_ConnectFixedChnl(L2CAP_ATT_CID, kAttAddr), - "assert failed: L2CA_ConnectFixedChnl(L2CAP_ATT_CID, kAttAddr)"); - log::assert_that( - l2cble_conn_comp(kAttHndl, HCI_ROLE_CENTRAL, kAttAddr, BLE_ADDR_PUBLIC, - 100, 100, 100), - "assert failed: l2cble_conn_comp(kAttHndl, HCI_ROLE_CENTRAL, kAttAddr, " - "BLE_ADDR_PUBLIC, 100, 100, 100)"); - - log::assert_that( - L2CA_RegisterFixedChannel(L2CAP_SMP_BR_CID, ®), - "assert failed: L2CA_RegisterFixedChannel(L2CAP_SMP_BR_CID, ®)"); - log::assert_that( - L2CA_ConnectFixedChnl(L2CAP_SMP_BR_CID, kSmpBrAddr), - "assert failed: L2CA_ConnectFixedChnl(L2CAP_SMP_BR_CID, kSmpBrAddr)"); + l2cble_conn_comp(kAttHndl, HCI_ROLE_CENTRAL, kAttAddr, BLE_ADDR_PUBLIC, 100, 100, 100), + "assert failed: l2cble_conn_comp(kAttHndl, HCI_ROLE_CENTRAL, kAttAddr, " + "BLE_ADDR_PUBLIC, 100, 100, 100)"); + + log::assert_that(L2CA_RegisterFixedChannel(L2CAP_SMP_BR_CID, ®), + "assert failed: L2CA_RegisterFixedChannel(L2CAP_SMP_BR_CID, ®)"); + log::assert_that(L2CA_ConnectFixedChnl(L2CAP_SMP_BR_CID, kSmpBrAddr), + "assert failed: L2CA_ConnectFixedChnl(L2CAP_SMP_BR_CID, kSmpBrAddr)"); l2c_link_hci_conn_comp(HCI_SUCCESS, kSmpBrHndl, kSmpBrAddr); auto att_cid = L2CA_ConnectReq(BT_PSM_ATT, kAttAddr); @@ -251,8 +235,7 @@ static void Fuzz(const uint8_t* data, size_t size) { constexpr uint16_t kMinPacketSize = 4 + L2CAP_PKT_OVERHEAD; constexpr uint16_t kMaxPacketSize = 1024; for (;;) { - auto size = - fdp.ConsumeIntegralInRange(kMinPacketSize, kMaxPacketSize); + auto size = fdp.ConsumeIntegralInRange(kMinPacketSize, kMaxPacketSize); auto bytes = fdp.ConsumeBytes(size); if (bytes.size() < kMinPacketSize) { break; diff --git a/system/stack/fuzzers/rfcomm_fuzzer.cc b/system/stack/fuzzers/rfcomm_fuzzer.cc index 90a62937603..9885ba076f7 100644 --- a/system/stack/fuzzers/rfcomm_fuzzer.cc +++ b/system/stack/fuzzers/rfcomm_fuzzer.cc @@ -42,8 +42,7 @@ namespace hal { class SnoopLogger; void SnoopLogger::AcceptlistRfcommDlci(uint16_t, uint16_t, uint8_t) {} -void SnoopLogger::SetRfcommPortOpen(uint16_t, uint16_t, uint8_t, uint16_t, - bool) {} +void SnoopLogger::SetRfcommPortOpen(uint16_t, uint16_t, uint8_t, uint16_t, bool) {} void SnoopLogger::SetRfcommPortClose(uint16_t, uint16_t, uint8_t, uint16_t) {} } // namespace hal @@ -71,26 +70,23 @@ void port_event_cback(uint32_t code, uint16_t port_handle) { } class FakeBtStack { - public: +public: FakeBtStack() { - test::mock::stack_l2cap_api::L2CA_DataWrite.body = [](uint16_t lcid, - BT_HDR* hdr) { + test::mock::stack_l2cap_api::L2CA_DataWrite.body = [](uint16_t lcid, BT_HDR* hdr) { osi_free(hdr); return tL2CAP_DW_RESULT::SUCCESS; }; test::mock::stack_l2cap_api::L2CA_ConnectReq.body = - [](uint16_t psm, const RawAddress& raw_address) { return kDummyCID; }; + [](uint16_t psm, const RawAddress& raw_address) { return kDummyCID; }; - test::mock::stack_l2cap_api::L2CA_DisconnectReq.body = [](uint16_t) { - return true; - }; + test::mock::stack_l2cap_api::L2CA_DisconnectReq.body = [](uint16_t) { return true; }; test::mock::stack_l2cap_api::L2CA_Register.body = - [](uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info, bool enable_snoop, - tL2CAP_ERTM_INFO* p_ertm_info, uint16_t my_mtu, - uint16_t required_remote_mtu, uint16_t sec_level) { - appl_info = p_cb_info; - return psm; - }; + [](uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info, bool enable_snoop, + tL2CAP_ERTM_INFO* p_ertm_info, uint16_t my_mtu, uint16_t required_remote_mtu, + uint16_t sec_level) { + appl_info = p_cb_info; + return psm; + }; } ~FakeBtStack() { @@ -102,16 +98,14 @@ class FakeBtStack { }; class Fakes { - public: +public: test::fake::FakeOsi fake_osi; FakeBtStack fake_stack; }; } // namespace -static int Cleanup(uint16_t* server_handle) { - return RFCOMM_RemoveServer(*server_handle); -} +static int Cleanup(uint16_t* server_handle) { return RFCOMM_RemoveServer(*server_handle); } static int ServerInit(FuzzedDataProvider* fdp, uint16_t* server_handle) { RFCOMM_Init(); @@ -120,13 +114,12 @@ static int ServerInit(FuzzedDataProvider* fdp, uint16_t* server_handle) { auto scn = fdp->ConsumeIntegral(); auto uuid = fdp->ConsumeIntegral(); - int status = RFCOMM_CreateConnectionWithSecurity( - uuid, scn, true, mtu, kDummyAddr, server_handle, port_mgmt_cback, 0); + int status = RFCOMM_CreateConnectionWithSecurity(uuid, scn, true, mtu, kDummyAddr, server_handle, + port_mgmt_cback, 0); if (status != PORT_SUCCESS) { return status; } - status = PORT_SetEventMaskAndCallback(*server_handle, PORT_EV_RXCHAR, - port_event_cback); + status = PORT_SetEventMaskAndCallback(*server_handle, PORT_EV_RXCHAR, port_event_cback); return status; } @@ -147,8 +140,7 @@ static void FuzzAsServer(FuzzedDataProvider* fdp) { while (fdp->remaining_bytes() > 0) { auto size = fdp->ConsumeIntegralInRange(0, kMaxPacketSize); auto bytes = fdp->ConsumeBytes(size); - BT_HDR* hdr = - reinterpret_cast(osi_calloc(sizeof(BT_HDR) + bytes.size())); + BT_HDR* hdr = reinterpret_cast(osi_calloc(sizeof(BT_HDR) + bytes.size())); hdr->len = bytes.size(); std::copy(bytes.cbegin(), bytes.cend(), hdr->data); appl_info.pL2CA_DataInd_Cb(kDummyCID, hdr); @@ -167,13 +159,12 @@ static int ClientInit(FuzzedDataProvider* fdp, uint16_t* client_handle) { auto scn = fdp->ConsumeIntegral(); auto uuid = fdp->ConsumeIntegral(); - int status = RFCOMM_CreateConnectionWithSecurity( - uuid, scn, false, mtu, kDummyAddr, client_handle, port_mgmt_cback, 0); + int status = RFCOMM_CreateConnectionWithSecurity(uuid, scn, false, mtu, kDummyAddr, client_handle, + port_mgmt_cback, 0); if (status != PORT_SUCCESS) { return status; } - status = PORT_SetEventMaskAndCallback(*client_handle, PORT_EV_RXCHAR, - port_event_cback); + status = PORT_SetEventMaskAndCallback(*client_handle, PORT_EV_RXCHAR, port_event_cback); return status; } @@ -196,8 +187,7 @@ static void FuzzAsClient(FuzzedDataProvider* fdp) { while (fdp->remaining_bytes() > 0) { auto size = fdp->ConsumeIntegralInRange(0, kMaxPacketSize); auto bytes = fdp->ConsumeBytes(size); - BT_HDR* hdr = - reinterpret_cast(osi_calloc(sizeof(BT_HDR) + bytes.size())); + BT_HDR* hdr = reinterpret_cast(osi_calloc(sizeof(BT_HDR) + bytes.size())); hdr->len = bytes.size(); std::copy(bytes.cbegin(), bytes.cend(), hdr->data); appl_info.pL2CA_DataInd_Cb(kDummyCID, hdr); diff --git a/system/stack/fuzzers/sdp_fuzzer.cc b/system/stack/fuzzers/sdp_fuzzer.cc index 4d607aa350b..65203658242 100644 --- a/system/stack/fuzzers/sdp_fuzzer.cc +++ b/system/stack/fuzzers/sdp_fuzzer.cc @@ -42,67 +42,55 @@ constexpr uint8_t kDummyAddr[] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66}; // Set up default callback structure tL2CAP_APPL_INFO cb_info = { - .pL2CA_ConnectInd_Cb = [](const RawAddress& bd_addr, uint16_t lcid, - uint16_t psm, - uint8_t id) {}, // tL2CA_CONNECT_IND_CB - .pL2CA_ConnectCfm_Cb = [](uint16_t lcid, - uint16_t result) {}, // tL2CA_CONNECT_CFM_CB - .pL2CA_ConfigInd_Cb = [](uint16_t lcid, - tL2CAP_CFG_INFO* p_cfg) {}, // tL2CA_CONFIG_IND_CB - .pL2CA_ConfigCfm_Cb = [](uint16_t lcid, uint16_t initiator, - tL2CAP_CFG_INFO* p_cfg) {}, // tL2CA_CONFIG_CFM_CB - .pL2CA_DisconnectInd_Cb = - [](uint16_t lcid, bool should_ack) {}, // tL2CA_DISCONNECT_IND_CB - .pL2CA_DisconnectCfm_Cb = - [](uint16_t lcid, uint16_t result) {}, // tL2CA_DISCONNECT_CFM_CB - .pL2CA_DataInd_Cb = [](uint16_t lcid, - BT_HDR* data) {}, // tL2CA_DATA_IND_CB - .pL2CA_CongestionStatus_Cb = - [](uint16_t lcid, bool is_congested) {}, // tL2CA_CONGESTION_STATUS_CB - .pL2CA_TxComplete_Cb = [](uint16_t lcid, - uint16_t num_sdu) {}, // tL2CA_TX_COMPLETE_CB - .pL2CA_Error_Cb = [](uint16_t lcid, - uint16_t error_type) {}, // tL2CA_ERROR_CB - .pL2CA_CreditBasedConnectInd_Cb = - [](const RawAddress& bdaddr, std::vector& lcids, uint16_t psm, - uint16_t peer_mtu, - uint8_t identifier) {}, // tL2CA_CREDIT_BASED_CONNECT_IND_CB - .pL2CA_CreditBasedConnectCfm_Cb = - [](const RawAddress& bdaddr, uint16_t lcid, uint16_t peer_mtu, - uint16_t result) {}, // tL2CA_CREDIT_BASED_CONNECT_CFM_CB - .pL2CA_CreditBasedReconfigCompleted_Cb = - [](const RawAddress& bdaddr, uint16_t lcid, bool is_local_cfg, - tL2CAP_LE_CFG_INFO* p_cfg) { - }, // tL2CA_CREDIT_BASED_RECONFIG_COMPLETED_CB - .pL2CA_CreditBasedCollisionInd_Cb = - [](const RawAddress& bdaddr) {}, // tL2CA_CREDIT_BASED_COLLISION_IND_CB + .pL2CA_ConnectInd_Cb = [](const RawAddress& bd_addr, uint16_t lcid, uint16_t psm, + uint8_t id) {}, // tL2CA_CONNECT_IND_CB + .pL2CA_ConnectCfm_Cb = [](uint16_t lcid, uint16_t result) {}, // tL2CA_CONNECT_CFM_CB + .pL2CA_ConfigInd_Cb = [](uint16_t lcid, tL2CAP_CFG_INFO* p_cfg) {}, // tL2CA_CONFIG_IND_CB + .pL2CA_ConfigCfm_Cb = [](uint16_t lcid, uint16_t initiator, + tL2CAP_CFG_INFO* p_cfg) {}, // tL2CA_CONFIG_CFM_CB + .pL2CA_DisconnectInd_Cb = [](uint16_t lcid, bool should_ack) {}, // tL2CA_DISCONNECT_IND_CB + .pL2CA_DisconnectCfm_Cb = [](uint16_t lcid, uint16_t result) {}, // tL2CA_DISCONNECT_CFM_CB + .pL2CA_DataInd_Cb = [](uint16_t lcid, BT_HDR* data) {}, // tL2CA_DATA_IND_CB + .pL2CA_CongestionStatus_Cb = [](uint16_t lcid, + bool is_congested) {}, // tL2CA_CONGESTION_STATUS_CB + .pL2CA_TxComplete_Cb = [](uint16_t lcid, uint16_t num_sdu) {}, // tL2CA_TX_COMPLETE_CB + .pL2CA_Error_Cb = [](uint16_t lcid, uint16_t error_type) {}, // tL2CA_ERROR_CB + .pL2CA_CreditBasedConnectInd_Cb = + [](const RawAddress& bdaddr, std::vector& lcids, uint16_t psm, + uint16_t peer_mtu, uint8_t identifier) {}, // tL2CA_CREDIT_BASED_CONNECT_IND_CB + .pL2CA_CreditBasedConnectCfm_Cb = + [](const RawAddress& bdaddr, uint16_t lcid, uint16_t peer_mtu, uint16_t result) { + }, // tL2CA_CREDIT_BASED_CONNECT_CFM_CB + .pL2CA_CreditBasedReconfigCompleted_Cb = + [](const RawAddress& bdaddr, uint16_t lcid, bool is_local_cfg, + tL2CAP_LE_CFG_INFO* p_cfg) {}, // tL2CA_CREDIT_BASED_RECONFIG_COMPLETED_CB + .pL2CA_CreditBasedCollisionInd_Cb = + [](const RawAddress& bdaddr) {}, // tL2CA_CREDIT_BASED_COLLISION_IND_CB }; class FakeL2cap { - public: +public: FakeL2cap() { test::mock::stack_l2cap_api::L2CA_ConnectReq.body = - [](uint16_t psm, const RawAddress& raw_address) { return kDummyCID; }; + [](uint16_t psm, const RawAddress& raw_address) { return kDummyCID; }; test::mock::stack_l2cap_api::L2CA_ConnectReqWithSecurity.body = - [](uint16_t psm, const RawAddress& p_bd_addr, uint16_t sec_level) { - return L2CA_ConnectReq(psm, p_bd_addr); - }; - test::mock::stack_l2cap_api::L2CA_DataWrite.body = - [](uint16_t cid, BT_HDR* p_data) -> tL2CAP_DW_RESULT { + [](uint16_t psm, const RawAddress& p_bd_addr, uint16_t sec_level) { + return L2CA_ConnectReq(psm, p_bd_addr); + }; + test::mock::stack_l2cap_api::L2CA_DataWrite.body = [](uint16_t cid, + BT_HDR* p_data) -> tL2CAP_DW_RESULT { auto len = p_data->len; osi_free(p_data); return tL2CAP_DW_RESULT::SUCCESS; }; - test::mock::stack_l2cap_api::L2CA_DisconnectReq.body = [](uint16_t lcid) { - return true; - }; + test::mock::stack_l2cap_api::L2CA_DisconnectReq.body = [](uint16_t lcid) { return true; }; test::mock::stack_l2cap_api::L2CA_RegisterWithSecurity.body = - [](uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info, bool enable_snoop, - tL2CAP_ERTM_INFO* p_ertm_info, uint16_t my_mtu, - uint16_t required_remote_mtu, uint16_t sec_level) { - cb_info = p_cb_info; - return psm; - }; + [](uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info, bool enable_snoop, + tL2CAP_ERTM_INFO* p_ertm_info, uint16_t my_mtu, uint16_t required_remote_mtu, + uint16_t sec_level) { + cb_info = p_cb_info; + return psm; + }; } ~FakeL2cap() { @@ -115,22 +103,22 @@ class FakeL2cap { }; class FakeBtifConfig { - public: +public: FakeBtifConfig() { - test::mock::btif_config::btif_config_set_bin.body = - [](const std::string&, const std::string&, const uint8_t*, size_t) { - // This function is not properly mocked. The abort here allows us to - // catch any cases using this mock. - abort(); - return true; - }; - test::mock::btif_config::btif_config_set_int.body = - [](const std::string& section, const std::string& key, int value) { - // This function is not properly mocked. The abort here allows us to - // catch any cases using this mock. - abort(); - return true; - }; + test::mock::btif_config::btif_config_set_bin.body = [](const std::string&, const std::string&, + const uint8_t*, size_t) { + // This function is not properly mocked. The abort here allows us to + // catch any cases using this mock. + abort(); + return true; + }; + test::mock::btif_config::btif_config_set_int.body = [](const std::string& section, + const std::string& key, int value) { + // This function is not properly mocked. The abort here allows us to + // catch any cases using this mock. + abort(); + return true; + }; } ~FakeBtifConfig() { @@ -140,7 +128,7 @@ class FakeBtifConfig { }; class Fakes { - public: +public: test::fake::FakeOsi fake_osi; FakeL2cap fake_l2cap; FakeBtifConfig fake_btif_config; @@ -157,8 +145,7 @@ static void FuzzAsServer(FuzzedDataProvider& fdp) { auto handle = SDP_CreateRecord(); auto attr_num = fdp.ConsumeIntegralInRange(0, 10); for (uint8_t s = 0; s < attr_num; s++) { - auto id = (i == 0) ? ATTR_ID_BT_PROFILE_DESC_LIST - : fdp.ConsumeIntegral(); + auto id = (i == 0) ? ATTR_ID_BT_PROFILE_DESC_LIST : fdp.ConsumeIntegral(); auto type = fdp.ConsumeIntegral(); auto len = fdp.ConsumeIntegralInRange(1, 512); auto data = fdp.ConsumeBytes(len); @@ -172,8 +159,7 @@ static void FuzzAsServer(FuzzedDataProvider& fdp) { } } - cb_info.pL2CA_ConnectInd_Cb(RawAddress(kDummyAddr), kDummyCID, kDummyPSM, - kDummyID); + cb_info.pL2CA_ConnectInd_Cb(RawAddress(kDummyAddr), kDummyCID, kDummyPSM, kDummyID); tL2CAP_CFG_INFO cfg = {}; cb_info.pL2CA_ConfigCfm_Cb(kDummyCID, 0, &cfg); @@ -192,40 +178,34 @@ static void FuzzAsServer(FuzzedDataProvider& fdp) { } static void FuzzAsClient(FuzzedDataProvider& fdp) { - std::shared_ptr p_db( - (tSDP_DISCOVERY_DB*)malloc(SDP_DB_SIZE), free); + std::shared_ptr p_db((tSDP_DISCOVERY_DB*)malloc(SDP_DB_SIZE), free); std::vector init_uuids; std::vector init_attrs; sdp_init(); - uint8_t num_uuid = - fdp.ConsumeIntegralInRange(0, SDP_MAX_UUID_FILTERS); - uint8_t num_attr = - fdp.ConsumeIntegralInRange(0, SDP_MAX_ATTR_FILTERS); + uint8_t num_uuid = fdp.ConsumeIntegralInRange(0, SDP_MAX_UUID_FILTERS); + uint8_t num_attr = fdp.ConsumeIntegralInRange(0, SDP_MAX_ATTR_FILTERS); for (uint8_t i = 0; i < num_uuid; i++) { - init_uuids.push_back( - bluetooth::Uuid::From16Bit(fdp.ConsumeIntegral())); + init_uuids.push_back(bluetooth::Uuid::From16Bit(fdp.ConsumeIntegral())); } for (uint8_t i = 0; i < num_attr; i++) { init_attrs.push_back(fdp.ConsumeIntegral()); } - SDP_InitDiscoveryDb(p_db.get(), SDP_DB_SIZE, init_uuids.size(), - init_uuids.data(), init_attrs.size(), init_attrs.data()); + SDP_InitDiscoveryDb(p_db.get(), SDP_DB_SIZE, init_uuids.size(), init_uuids.data(), + init_attrs.size(), init_attrs.data()); bool is_di_discover = fdp.ConsumeBool(); if (is_di_discover) { - SDP_ServiceSearchRequest( - kDummyAddr, p_db.get(), - [](const RawAddress& bd_addr, tSDP_RESULT result) {}); + SDP_ServiceSearchRequest(kDummyAddr, p_db.get(), + [](const RawAddress& bd_addr, tSDP_RESULT result) {}); } else { - SDP_ServiceSearchAttributeRequest( - kDummyAddr, p_db.get(), - [](const RawAddress& bd_addr, tSDP_RESULT result) {}); + SDP_ServiceSearchAttributeRequest(kDummyAddr, p_db.get(), + [](const RawAddress& bd_addr, tSDP_RESULT result) {}); } cb_info.pL2CA_ConnectCfm_Cb(kDummyCID, L2CAP_CONN_OK); diff --git a/system/stack/fuzzers/smp_fuzzer.cc b/system/stack/fuzzers/smp_fuzzer.cc index 96302f408a1..e79ab313c8f 100644 --- a/system/stack/fuzzers/smp_fuzzer.cc +++ b/system/stack/fuzzers/smp_fuzzer.cc @@ -34,9 +34,7 @@ bluetooth::common::MessageLoopThread* main_thread_ptr = nullptr; -bluetooth::common::MessageLoopThread* get_main_thread() { - return main_thread_ptr; -} +bluetooth::common::MessageLoopThread* get_main_thread() { return main_thread_ptr; } namespace { #define SDP_DB_SIZE 0x10000 @@ -46,69 +44,65 @@ constexpr uint8_t kDummyRemoteAddr[] = {0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC}; // Set up default callback structure tL2CAP_FIXED_CHNL_REG fixed_chnl_reg = { - .pL2CA_FixedConn_Cb = [](uint16_t, const RawAddress&, bool, uint16_t, - tBT_TRANSPORT) {}, - .pL2CA_FixedData_Cb = [](uint16_t, const RawAddress&, BT_HDR*) {}, + .pL2CA_FixedConn_Cb = [](uint16_t, const RawAddress&, bool, uint16_t, tBT_TRANSPORT) {}, + .pL2CA_FixedData_Cb = [](uint16_t, const RawAddress&, BT_HDR*) {}, }; tL2CAP_FIXED_CHNL_REG fixed_chnl_br_reg = { - .pL2CA_FixedConn_Cb = [](uint16_t, const RawAddress&, bool, uint16_t, - tBT_TRANSPORT) {}, - .pL2CA_FixedData_Cb = [](uint16_t, const RawAddress&, BT_HDR*) {}, + .pL2CA_FixedConn_Cb = [](uint16_t, const RawAddress&, bool, uint16_t, tBT_TRANSPORT) {}, + .pL2CA_FixedData_Cb = [](uint16_t, const RawAddress&, BT_HDR*) {}, }; tBTM_SEC_DEV_REC dev_rec; bool is_peripheral; class FakeBtStack { - public: +public: FakeBtStack() { test::mock::stack_acl::BTM_ReadConnectionAddr.body = - [](const RawAddress& remote_bda, RawAddress& local_conn_addr, - tBLE_ADDR_TYPE* p_addr_type, bool ota_address) { - local_conn_addr = kDummyAddr; - *p_addr_type = BLE_ADDR_PUBLIC; - }; + [](const RawAddress& remote_bda, RawAddress& local_conn_addr, + tBLE_ADDR_TYPE* p_addr_type, bool ota_address) { + local_conn_addr = kDummyAddr; + *p_addr_type = BLE_ADDR_PUBLIC; + }; test::mock::stack_acl::BTM_ReadRemoteConnectionAddr.body = - [](const RawAddress& pseudo_addr, RawAddress& conn_addr, - tBLE_ADDR_TYPE* p_addr_type, bool ota_address) { - conn_addr = kDummyRemoteAddr; - *p_addr_type = BLE_ADDR_PUBLIC; - return true; - }; - test::mock::stack_btm_dev::btm_find_dev.body = [](const RawAddress&) { - return &dev_rec; + [](const RawAddress& pseudo_addr, RawAddress& conn_addr, tBLE_ADDR_TYPE* p_addr_type, + bool ota_address) { + conn_addr = kDummyRemoteAddr; + *p_addr_type = BLE_ADDR_PUBLIC; + return true; + }; + test::mock::stack_btm_dev::btm_find_dev.body = [](const RawAddress&) { return &dev_rec; }; + + test::mock::stack_l2cap_ble::L2CA_GetBleConnRole.body = [](const RawAddress&) { + return is_peripheral ? HCI_ROLE_PERIPHERAL : HCI_ROLE_CENTRAL; }; - test::mock::stack_l2cap_ble::L2CA_GetBleConnRole.body = - [](const RawAddress&) { - return is_peripheral ? HCI_ROLE_PERIPHERAL : HCI_ROLE_CENTRAL; - }; - - test::mock::stack_l2cap_api::L2CA_SetIdleTimeoutByBdAddr.body = - [](const RawAddress&, uint16_t, uint8_t) { return true; }; - test::mock::stack_l2cap_api::L2CA_RemoveFixedChnl.body = - [](uint16_t, const RawAddress&) { return true; }; - test::mock::stack_l2cap_api::L2CA_ConnectFixedChnl.body = - [](uint16_t, const RawAddress&) { return true; }; + test::mock::stack_l2cap_api::L2CA_SetIdleTimeoutByBdAddr.body = [](const RawAddress&, uint16_t, + uint8_t) { return true; }; + test::mock::stack_l2cap_api::L2CA_RemoveFixedChnl.body = [](uint16_t, const RawAddress&) { + return true; + }; + test::mock::stack_l2cap_api::L2CA_ConnectFixedChnl.body = [](uint16_t, const RawAddress&) { + return true; + }; test::mock::stack_l2cap_api::L2CA_SendFixedChnlData.body = - [](uint16_t cid, const RawAddress& addr, BT_HDR* hdr) { - osi_free(hdr); - return tL2CAP_DW_RESULT::SUCCESS; - }; + [](uint16_t cid, const RawAddress& addr, BT_HDR* hdr) { + osi_free(hdr); + return tL2CAP_DW_RESULT::SUCCESS; + }; test::mock::stack_l2cap_api::L2CA_RegisterFixedChannel.body = - [](uint16_t fixed_cid, tL2CAP_FIXED_CHNL_REG* p_freg) { - if (fixed_cid == L2CAP_SMP_CID) { - fixed_chnl_reg = *p_freg; - } else if (fixed_cid == L2CAP_SMP_BR_CID) { - fixed_chnl_br_reg = *p_freg; - } else { - abort(); - } - return true; - }; - main_thread_ptr = - new bluetooth::common::MessageLoopThread("smp_fuzz_main_thread"); + [](uint16_t fixed_cid, tL2CAP_FIXED_CHNL_REG* p_freg) { + if (fixed_cid == L2CAP_SMP_CID) { + fixed_chnl_reg = *p_freg; + } else if (fixed_cid == L2CAP_SMP_BR_CID) { + fixed_chnl_br_reg = *p_freg; + } else { + abort(); + } + return true; + }; + main_thread_ptr = new bluetooth::common::MessageLoopThread("smp_fuzz_main_thread"); main_thread_ptr->StartUp(); } @@ -132,7 +126,7 @@ class FakeBtStack { }; class Fakes { - public: +public: test::fake::FakeOsi fake_osi; FakeBtStack fake_stack; }; @@ -143,8 +137,7 @@ uint8_t oob_data[] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF, 0x00}; tSMP_IO_REQ io_req = {}; -tBTM_STATUS smp_callback(tSMP_EVT event, const RawAddress& bd_addr, - const tSMP_EVT_DATA* p_data) { +tBTM_STATUS smp_callback(tSMP_EVT event, const RawAddress& bd_addr, const tSMP_EVT_DATA* p_data) { switch (event) { case SMP_IO_CAP_REQ_EVT: case SMP_BR_KEYS_REQ_EVT: { @@ -196,12 +189,16 @@ void Fuzz(const uint8_t* data, size_t size) { cid = L2CAP_SMP_BR_CID; chnl_reg = &fixed_chnl_br_reg; transport = BT_TRANSPORT_BR_EDR; - if (is_initiator) SMP_BR_PairWith(kDummyAddr); + if (is_initiator) { + SMP_BR_PairWith(kDummyAddr); + } } else { cid = L2CAP_SMP_CID; chnl_reg = &fixed_chnl_reg; transport = BT_TRANSPORT_LE; - if (is_initiator) SMP_Pair(kDummyAddr); + if (is_initiator) { + SMP_Pair(kDummyAddr); + } } // Simulating connection establaishing event diff --git a/system/stack/gap/gap_ble.cc b/system/stack/gap/gap_ble.cc index eb48f2fe6e8..7619107d3f3 100644 --- a/system/stack/gap/gap_ble.cc +++ b/system/stack/gap/gap_ble.cc @@ -59,24 +59,22 @@ typedef struct { tGAP_BLE_ATTR_VALUE attr_value; } tGAP_ATTR; -void server_attr_request_cback(uint16_t, uint32_t, tGATTS_REQ_TYPE, - tGATTS_DATA*); -void client_connect_cback(tGATT_IF, const RawAddress&, uint16_t, bool, - tGATT_DISCONN_REASON, tBT_TRANSPORT); -void client_cmpl_cback(uint16_t, tGATTC_OPTYPE, tGATT_STATUS, - tGATT_CL_COMPLETE*); +void server_attr_request_cback(uint16_t, uint32_t, tGATTS_REQ_TYPE, tGATTS_DATA*); +void client_connect_cback(tGATT_IF, const RawAddress&, uint16_t, bool, tGATT_DISCONN_REASON, + tBT_TRANSPORT); +void client_cmpl_cback(uint16_t, tGATTC_OPTYPE, tGATT_STATUS, tGATT_CL_COMPLETE*); tGATT_CBACK gap_cback = { - .p_conn_cb = client_connect_cback, - .p_cmpl_cb = client_cmpl_cback, - .p_disc_res_cb = nullptr, - .p_disc_cmpl_cb = nullptr, - .p_req_cb = server_attr_request_cback, - .p_enc_cmpl_cb = nullptr, - .p_congestion_cb = nullptr, - .p_phy_update_cb = nullptr, - .p_conn_update_cb = nullptr, - .p_subrate_chg_cb = nullptr, + .p_conn_cb = client_connect_cback, + .p_cmpl_cb = client_cmpl_cback, + .p_disc_res_cb = nullptr, + .p_disc_cmpl_cb = nullptr, + .p_req_cb = server_attr_request_cback, + .p_enc_cmpl_cb = nullptr, + .p_congestion_cb = nullptr, + .p_phy_update_cb = nullptr, + .p_conn_update_cb = nullptr, + .p_subrate_chg_cb = nullptr, }; constexpr int GAP_CHAR_DEV_NAME_SIZE = BD_NAME_LEN; @@ -87,18 +85,24 @@ std::vector gap_clcbs; std::array gatt_attr; tGATT_IF gatt_if; -/** returns LCB with macthing bd address, or nullptr */ +/** returns LCB with matching bd address, or nullptr */ tGAP_CLCB* find_clcb_by_bd_addr(const RawAddress& bda) { - for (auto& cb : gap_clcbs) - if (cb.bda == bda) return &cb; + for (auto& cb : gap_clcbs) { + if (cb.bda == bda) { + return &cb; + } + } return nullptr; } -/** returns LCB with macthing connection ID, or nullptr if not found */ +/** returns LCB with matching connection ID, or nullptr if not found */ tGAP_CLCB* ble_find_clcb_by_conn_id(uint16_t conn_id) { - for (auto& cb : gap_clcbs) - if (cb.connected && cb.conn_id == conn_id) return &cb; + for (auto& cb : gap_clcbs) { + if (cb.connected && cb.conn_id == conn_id) { + return &cb; + } + } return nullptr; } @@ -126,8 +130,7 @@ void clcb_dealloc(tGAP_CLCB& clcb) { } /** GAP Attributes Database Request callback */ -tGATT_STATUS read_attr_value(uint16_t handle, tGATT_VALUE* p_value, - bool is_long) { +tGATT_STATUS read_attr_value(uint16_t handle, tGATT_VALUE* p_value, bool is_long) { uint8_t* p = p_value->value; uint16_t offset = p_value->offset; uint8_t* p_dev_name = NULL; @@ -135,23 +138,25 @@ tGATT_STATUS read_attr_value(uint16_t handle, tGATT_VALUE* p_value, for (const tGAP_ATTR& db_attr : gatt_attr) { const tGAP_BLE_ATTR_VALUE& attr_value = db_attr.attr_value; if (handle == db_attr.handle) { - if (db_attr.uuid != GATT_UUID_GAP_DEVICE_NAME && is_long) + if (db_attr.uuid != GATT_UUID_GAP_DEVICE_NAME && is_long) { return GATT_NOT_LONG; + } switch (db_attr.uuid) { case GATT_UUID_GAP_DEVICE_NAME: - if (get_btm_client_interface().local.BTM_ReadLocalDeviceName( - (const char**)&p_dev_name) != BTM_SUCCESS) { + if (get_btm_client_interface().local.BTM_ReadLocalDeviceName((const char**)&p_dev_name) != + BTM_SUCCESS) { log::warn("Unable to read local device name"); }; - if (strlen((char*)p_dev_name) > GATT_MAX_ATTR_LEN) + if (strlen((char*)p_dev_name) > GATT_MAX_ATTR_LEN) { p_value->len = GATT_MAX_ATTR_LEN; - else + } else { p_value->len = (uint16_t)strlen((char*)p_dev_name); + } - if (offset > p_value->len) + if (offset > p_value->len) { return GATT_INVALID_OFFSET; - else { + } else { p_value->len -= offset; p_dev_name += offset; ARRAY_TO_STREAM(p, p_dev_name, p_value->len); @@ -184,9 +189,10 @@ tGATT_STATUS read_attr_value(uint16_t handle, tGATT_VALUE* p_value, } /** GAP Attributes Database Read/Read Blob Request process */ -tGATT_STATUS proc_read(tGATTS_REQ_TYPE, tGATT_READ_REQ* p_data, - tGATTS_RSP* p_rsp) { - if (p_data->is_long) p_rsp->attr_value.offset = p_data->offset; +tGATT_STATUS proc_read(tGATTS_REQ_TYPE, tGATT_READ_REQ* p_data, tGATTS_RSP* p_rsp) { + if (p_data->is_long) { + p_rsp->attr_value.offset = p_data->offset; + } p_rsp->attr_value.handle = p_data->handle; @@ -195,15 +201,18 @@ tGATT_STATUS proc_read(tGATTS_REQ_TYPE, tGATT_READ_REQ* p_data, /** GAP ATT server process a write request */ tGATT_STATUS proc_write_req(tGATTS_REQ_TYPE, tGATT_WRITE_REQ* p_data) { - for (const auto& db_addr : gatt_attr) - if (p_data->handle == db_addr.handle) return GATT_WRITE_NOT_PERMIT; + for (const auto& db_addr : gatt_attr) { + if (p_data->handle == db_addr.handle) { + return GATT_WRITE_NOT_PERMIT; + } + } return GATT_NOT_FOUND; } /** GAP ATT server attribute access request callback */ -void server_attr_request_cback(uint16_t conn_id, uint32_t trans_id, - tGATTS_REQ_TYPE type, tGATTS_DATA* p_data) { +void server_attr_request_cback(uint16_t conn_id, uint32_t trans_id, tGATTS_REQ_TYPE type, + tGATTS_DATA* p_data) { tGATT_STATUS status = GATT_INVALID_PDU; bool ignore = false; @@ -218,7 +227,9 @@ void server_attr_request_cback(uint16_t conn_id, uint32_t trans_id, case GATTS_REQ_TYPE_WRITE_CHARACTERISTIC: case GATTS_REQ_TYPE_WRITE_DESCRIPTOR: - if (!p_data->write_req.need_rsp) ignore = true; + if (!p_data->write_req.need_rsp) { + ignore = true; + } status = proc_write_req(type, &p_data->write_req); break; @@ -298,9 +309,8 @@ void cl_op_cmpl(tGAP_CLCB& clcb, bool status, uint16_t len, uint8_t* p_name) { } /** Client connection callback */ -void client_connect_cback(tGATT_IF, const RawAddress& bda, uint16_t conn_id, - bool connected, tGATT_DISCONN_REASON /* reason */, - tBT_TRANSPORT) { +void client_connect_cback(tGATT_IF, const RawAddress& bda, uint16_t conn_id, bool connected, + tGATT_DISCONN_REASON /* reason */, tBT_TRANSPORT) { tGAP_CLCB* p_clcb = find_clcb_by_bd_addr(bda); if (p_clcb == NULL) { log::info("No active GAP service found for peer:{} callback:{}", bda, @@ -332,12 +342,16 @@ void client_cmpl_cback(uint16_t conn_id, tGATTC_OPTYPE op, tGATT_STATUS status, uint16_t len; uint8_t* pp; - if (p_clcb == NULL) return; + if (p_clcb == NULL) { + return; + } op_type = p_clcb->cl_op_uuid; /* Currently we only issue read commands */ - if (op != GATTC_OPTYPE_READ) return; + if (op != GATTC_OPTYPE_READ) { + return; + } if (status != GATT_SUCCESS) { cl_op_cmpl(*p_clcb, false, 0, NULL); @@ -360,7 +374,9 @@ void client_cmpl_cback(uint16_t conn_id, tGATTC_OPTYPE op, tGATT_STATUS status, case GATT_UUID_GAP_DEVICE_NAME: len = (uint16_t)strlen((char*)pp); - if (len > GAP_CHAR_DEV_NAME_SIZE) len = GAP_CHAR_DEV_NAME_SIZE; + if (len > GAP_CHAR_DEV_NAME_SIZE) { + len = GAP_CHAR_DEV_NAME_SIZE; + } cl_op_cmpl(*p_clcb, true, len, pp); break; @@ -372,28 +388,31 @@ void client_cmpl_cback(uint16_t conn_id, tGATTC_OPTYPE op, tGATT_STATUS status, bool accept_client_operation(const RawAddress& peer_bda, uint16_t uuid, tGAP_BLE_CMPL_CBACK* p_cback) { - if (p_cback == NULL && uuid != GATT_UUID_GAP_PREF_CONN_PARAM) return false; + if (p_cback == NULL && uuid != GATT_UUID_GAP_PREF_CONN_PARAM) { + return false; + } tGAP_CLCB* p_clcb = find_clcb_by_bd_addr(peer_bda); if (p_clcb == NULL) { p_clcb = clcb_alloc(peer_bda); } - if (GATT_GetConnIdIfConnected(gatt_if, peer_bda, &p_clcb->conn_id, - BT_TRANSPORT_LE)) + if (GATT_GetConnIdIfConnected(gatt_if, peer_bda, &p_clcb->conn_id, BT_TRANSPORT_LE)) { p_clcb->connected = true; + } - if (!GATT_Connect(gatt_if, p_clcb->bda, BTM_BLE_DIRECT_CONNECTION, - BT_TRANSPORT_LE, true)) + if (!GATT_Connect(gatt_if, p_clcb->bda, BTM_BLE_DIRECT_CONNECTION, BT_TRANSPORT_LE, true)) { return false; + } /* enqueue the request */ p_clcb->requests.push({.uuid = uuid, .p_cback = p_cback}); - if (p_clcb->connected && p_clcb->cl_op_uuid == 0) + if (p_clcb->connected && p_clcb->cl_op_uuid == 0) { return send_cl_read_request(*p_clcb); - else /* wait for connection up or pending operation to finish */ + } else { /* wait for connection up or pending operation to finish */ return true; + } } } // namespace @@ -423,35 +442,33 @@ void gap_attr_db_init(void) { Uuid icon_uuid = Uuid::From16Bit(GATT_UUID_GAP_ICON); Uuid addr_res_uuid = Uuid::From16Bit(GATT_UUID_GAP_CENTRAL_ADDR_RESOL); - btgatt_db_element_t service[] = { - { - .uuid = svc_uuid, - .type = BTGATT_DB_PRIMARY_SERVICE, - }, - {.uuid = name_uuid, - .type = BTGATT_DB_CHARACTERISTIC, - .properties = GATT_CHAR_PROP_BIT_READ, - .permissions = GATT_PERM_READ_IF_ENCRYPTED_OR_DISCOVERABLE}, - {.uuid = icon_uuid, - .type = BTGATT_DB_CHARACTERISTIC, - .properties = GATT_CHAR_PROP_BIT_READ, - .permissions = GATT_PERM_READ}, - {.uuid = addr_res_uuid, - .type = BTGATT_DB_CHARACTERISTIC, - .properties = GATT_CHAR_PROP_BIT_READ, - .permissions = GATT_PERM_READ} + btgatt_db_element_t service[] = {{ + .uuid = svc_uuid, + .type = BTGATT_DB_PRIMARY_SERVICE, + }, + {.uuid = name_uuid, + .type = BTGATT_DB_CHARACTERISTIC, + .properties = GATT_CHAR_PROP_BIT_READ, + .permissions = GATT_PERM_READ_IF_ENCRYPTED_OR_DISCOVERABLE}, + {.uuid = icon_uuid, + .type = BTGATT_DB_CHARACTERISTIC, + .properties = GATT_CHAR_PROP_BIT_READ, + .permissions = GATT_PERM_READ}, + {.uuid = addr_res_uuid, + .type = BTGATT_DB_CHARACTERISTIC, + .properties = GATT_CHAR_PROP_BIT_READ, + .permissions = GATT_PERM_READ} #if (BTM_PERIPHERAL_ENABLED == TRUE) /* Only needed for peripheral testing */ - , - {.uuid = Uuid::From16Bit(GATT_UUID_GAP_PREF_CONN_PARAM), - .type = BTGATT_DB_CHARACTERISTIC, - .properties = GATT_CHAR_PROP_BIT_READ, - .permissions = GATT_PERM_READ} + , + {.uuid = Uuid::From16Bit(GATT_UUID_GAP_PREF_CONN_PARAM), + .type = BTGATT_DB_CHARACTERISTIC, + .properties = GATT_CHAR_PROP_BIT_READ, + .permissions = GATT_PERM_READ} #endif }; /* Add a GAP service */ - if (GATTS_AddService(gatt_if, service, - sizeof(service) / sizeof(btgatt_db_element_t)) != + if (GATTS_AddService(gatt_if, service, sizeof(service) / sizeof(btgatt_db_element_t)) != GATT_SERVICE_STARTED) { log::warn("Unable to add GATT services gatt_if:{}", gatt_if); } @@ -472,8 +489,7 @@ void gap_attr_db_init(void) { gatt_attr[3].attr_value.conn_param.int_max = GAP_PREFER_CONN_INT_MAX; /* 6 */ gatt_attr[3].attr_value.conn_param.int_min = GAP_PREFER_CONN_INT_MIN; /* 0 */ gatt_attr[3].attr_value.conn_param.latency = GAP_PREFER_CONN_LATENCY; /* 0 */ - gatt_attr[3].attr_value.conn_param.sp_tout = - GAP_PREFER_CONN_SP_TOUT; /* 2000 */ + gatt_attr[3].attr_value.conn_param.sp_tout = GAP_PREFER_CONN_SP_TOUT; /* 2000 */ gatt_attr[3].handle = service[4].attribute_handle; #endif } @@ -494,14 +510,13 @@ void GAP_BleAttrDBUpdate(uint16_t attr_uuid, tGAP_BLE_ATTR_VALUE* p_value) { break; case GATT_UUID_GAP_PREF_CONN_PARAM: - memcpy((void*)&db_attr.attr_value.conn_param, - (const void*)&p_value->conn_param, + memcpy((void*)&db_attr.attr_value.conn_param, (const void*)&p_value->conn_param, sizeof(tGAP_BLE_PREF_PARAM)); break; case GATT_UUID_GAP_DEVICE_NAME: if (get_btm_client_interface().local.BTM_SetLocalDeviceName( - (const char*)p_value->p_dev_name) != BTM_SUCCESS) { + (const char*)p_value->p_dev_name) != BTM_SUCCESS) { log::warn("Unable to set local name"); } break; @@ -541,8 +556,7 @@ bool GAP_BleReadPeerPrefConnParams(const RawAddress& peer_bda) { * Returns true if request accepted * ******************************************************************************/ -bool GAP_BleReadPeerDevName(const RawAddress& peer_bda, - tGAP_BLE_CMPL_CBACK* p_cback) { +bool GAP_BleReadPeerDevName(const RawAddress& peer_bda, tGAP_BLE_CMPL_CBACK* p_cback) { return accept_client_operation(peer_bda, GATT_UUID_GAP_DEVICE_NAME, p_cback); } @@ -572,5 +586,5 @@ bool GAP_BleCancelReadPeerDevName(const RawAddress& peer_bda) { cl_op_cmpl(*p_clcb, false, 0, NULL); - return (true); + return true; } diff --git a/system/stack/gap/gap_conn.cc b/system/stack/gap/gap_conn.cc index fd434792528..653e721477b 100644 --- a/system/stack/gap/gap_conn.cc +++ b/system/stack/gap/gap_conn.cc @@ -87,12 +87,11 @@ tGAP_CONN conn; /******************************************************************************/ /* L O C A L F U N C T I O N P R O T O T Y P E S */ /******************************************************************************/ -static void gap_connect_ind(const RawAddress& bd_addr, uint16_t l2cap_cid, - uint16_t psm, uint8_t l2cap_id); +static void gap_connect_ind(const RawAddress& bd_addr, uint16_t l2cap_cid, uint16_t psm, + uint8_t l2cap_id); static void gap_connect_cfm(uint16_t l2cap_cid, uint16_t result); static void gap_config_ind(uint16_t l2cap_cid, tL2CAP_CFG_INFO* p_cfg); -static void gap_config_cfm(uint16_t l2cap_cid, uint16_t result, - tL2CAP_CFG_INFO* p_cfg); +static void gap_config_cfm(uint16_t l2cap_cid, uint16_t result, tL2CAP_CFG_INFO* p_cfg); static void gap_disconnect_ind(uint16_t l2cap_cid, bool ack_needed); static void gap_data_ind(uint16_t l2cap_cid, BT_HDR* p_msg); static void gap_congestion_ind(uint16_t lcid, bool is_congested); @@ -165,17 +164,18 @@ void gap_conn_init(void) { * GAP_INVALID_HANDLE * ******************************************************************************/ -uint16_t GAP_ConnOpen(const char* /* p_serv_name */, uint8_t service_id, - bool is_server, const RawAddress* p_rem_bda, uint16_t psm, - uint16_t le_mps, tL2CAP_CFG_INFO* p_cfg, - tL2CAP_ERTM_INFO* ertm_info, uint16_t security, +uint16_t GAP_ConnOpen(const char* /* p_serv_name */, uint8_t service_id, bool is_server, + const RawAddress* p_rem_bda, uint16_t psm, uint16_t le_mps, + tL2CAP_CFG_INFO* p_cfg, tL2CAP_ERTM_INFO* ertm_info, uint16_t security, tGAP_CONN_CALLBACK* p_cb, tBT_TRANSPORT transport) { tGAP_CCB* p_ccb; uint16_t cid; /* Allocate a new CCB. Return if none available. */ p_ccb = gap_allocate_ccb(); - if (p_ccb == NULL) return (GAP_INVALID_HANDLE); + if (p_ccb == NULL) { + return GAP_INVALID_HANDLE; + } /* update the transport */ p_ccb->transport = transport; @@ -186,34 +186,35 @@ uint16_t GAP_ConnOpen(const char* /* p_serv_name */, uint8_t service_id, /* If caller specified a BD address, save it */ if (p_rem_bda) { /* the bd addr is not RawAddress::kAny, then a bd address was specified */ - if (*p_rem_bda != RawAddress::kAny) p_ccb->rem_addr_specified = true; + if (*p_rem_bda != RawAddress::kAny) { + p_ccb->rem_addr_specified = true; + } p_ccb->rem_dev_address = *p_rem_bda; } else if (!is_server) { - /* remore addr is not specified and is not a server -> bad */ + /* remote addr is not specified and is not a server -> bad */ gap_release_ccb(p_ccb); - return (GAP_INVALID_HANDLE); + return GAP_INVALID_HANDLE; } /* A client MUST have specified a bd addr to connect with */ if (!p_ccb->rem_addr_specified && !is_server) { gap_release_ccb(p_ccb); - log::error( - "GAP ERROR: Client must specify a remote BD ADDR to connect to!"); - return (GAP_INVALID_HANDLE); + log::error("GAP ERROR: Client must specify a remote BD ADDR to connect to!"); + return GAP_INVALID_HANDLE; } /* Check if configuration was specified */ - if (p_cfg) p_ccb->cfg = *p_cfg; + if (p_cfg) { + p_ccb->cfg = *p_cfg; + } /* Configure L2CAP COC, if transport is LE */ if (transport == BT_TRANSPORT_LE) { p_ccb->local_coc_cfg.credits = L2CA_LeCreditDefault(); p_ccb->local_coc_cfg.mtu = p_cfg->mtu; - uint16_t max_mps = bluetooth::shim::GetController() - ->GetLeBufferSize() - .le_data_packet_length_; + uint16_t max_mps = bluetooth::shim::GetController()->GetLeBufferSize().le_data_packet_length_; if (le_mps > max_mps) { log::info("Limiting MPS to one buffer size - {}", max_mps); le_mps = max_mps; @@ -224,10 +225,11 @@ uint16_t GAP_ConnOpen(const char* /* p_serv_name */, uint8_t service_id, p_ccb->p_callback = p_cb; /* If originator, use a dynamic PSM */ - if (!is_server) + if (!is_server) { conn.reg_info.pL2CA_ConnectInd_Cb = NULL; - else + } else { conn.reg_info.pL2CA_ConnectInd_Cb = gap_connect_ind; + } /* Fill in eL2CAP parameter data */ if (p_ccb->cfg.fcr_present) { @@ -240,31 +242,28 @@ uint16_t GAP_ConnOpen(const char* /* p_serv_name */, uint8_t service_id, /* Register the PSM with L2CAP */ if (transport == BT_TRANSPORT_BR_EDR) { - p_ccb->psm = L2CA_RegisterWithSecurity( - psm, conn.reg_info, false /* enable_snoop */, &p_ccb->ertm_info, - L2CAP_SDU_LENGTH_MAX, 0, security); + p_ccb->psm = L2CA_RegisterWithSecurity(psm, conn.reg_info, false /* enable_snoop */, + &p_ccb->ertm_info, L2CAP_SDU_LENGTH_MAX, 0, security); if (p_ccb->psm == 0) { log::error("Failure registering PSM 0x{:04x}", psm); gap_release_ccb(p_ccb); - return (GAP_INVALID_HANDLE); + return GAP_INVALID_HANDLE; } } if (transport == BT_TRANSPORT_LE) { - p_ccb->psm = - L2CA_RegisterLECoc(psm, conn.reg_info, security, p_ccb->local_coc_cfg); + p_ccb->psm = L2CA_RegisterLECoc(psm, conn.reg_info, security, p_ccb->local_coc_cfg); if (p_ccb->psm == 0) { log::error("Failure registering PSM 0x{:04x}", psm); gap_release_ccb(p_ccb); - return (GAP_INVALID_HANDLE); + return GAP_INVALID_HANDLE; } } if (is_server) { - p_ccb->con_flags |= - GAP_CCB_FLAGS_SEC_DONE; /* assume btm/l2cap would handle it */ + p_ccb->con_flags |= GAP_CCB_FLAGS_SEC_DONE; /* assume btm/l2cap would handle it */ p_ccb->con_state = GAP_CCB_STATE_LISTENING; - return (p_ccb->gap_handle); + return p_ccb->gap_handle; } else { /* We are the originator of this connection */ p_ccb->con_flags = GAP_CCB_FLAGS_IS_ORIG; @@ -274,29 +273,29 @@ uint16_t GAP_ConnOpen(const char* /* p_serv_name */, uint8_t service_id, p_ccb->con_state = GAP_CCB_STATE_CONN_SETUP; /* mark security done flag, when security is not required */ - if ((security & (BTM_SEC_OUT_AUTHENTICATE | BTM_SEC_OUT_ENCRYPT)) == 0) + if ((security & (BTM_SEC_OUT_AUTHENTICATE | BTM_SEC_OUT_ENCRYPT)) == 0) { p_ccb->con_flags |= GAP_CCB_FLAGS_SEC_DONE; + } /* Check if L2CAP started the connection process */ if (p_rem_bda && (transport == BT_TRANSPORT_BR_EDR)) { cid = L2CA_ConnectReqWithSecurity(p_ccb->psm, *p_rem_bda, security); if (cid != 0) { p_ccb->connection_id = cid; - return (p_ccb->gap_handle); + return p_ccb->gap_handle; } } if (p_rem_bda && (transport == BT_TRANSPORT_LE)) { - cid = L2CA_ConnectLECocReq(p_ccb->psm, *p_rem_bda, &p_ccb->local_coc_cfg, - security); + cid = L2CA_ConnectLECocReq(p_ccb->psm, *p_rem_bda, &p_ccb->local_coc_cfg, security); if (cid != 0) { p_ccb->connection_id = cid; - return (p_ccb->gap_handle); + return p_ccb->gap_handle; } } gap_release_ccb(p_ccb); - return (GAP_INVALID_HANDLE); + return GAP_INVALID_HANDLE; } } @@ -333,10 +332,10 @@ uint16_t GAP_ConnClose(uint16_t gap_handle) { gap_release_ccb(p_ccb); - return (BT_PASS); + return BT_PASS; } - return (GAP_ERR_BAD_HANDLE); + return GAP_ERR_BAD_HANDLE; } /******************************************************************************* @@ -356,23 +355,27 @@ uint16_t GAP_ConnClose(uint16_t gap_handle) { * GAP_NO_DATA_AVAIL - no data available * ******************************************************************************/ -uint16_t GAP_ConnReadData(uint16_t gap_handle, uint8_t* p_data, - uint16_t max_len, uint16_t* p_len) { +uint16_t GAP_ConnReadData(uint16_t gap_handle, uint8_t* p_data, uint16_t max_len, uint16_t* p_len) { tGAP_CCB* p_ccb = gap_find_ccb_by_handle(gap_handle); uint16_t copy_len; - if (!p_ccb) return (GAP_ERR_BAD_HANDLE); + if (!p_ccb) { + return GAP_ERR_BAD_HANDLE; + } *p_len = 0; - if (fixed_queue_is_empty(p_ccb->rx_queue)) return (GAP_NO_DATA_AVAIL); + if (fixed_queue_is_empty(p_ccb->rx_queue)) { + return GAP_NO_DATA_AVAIL; + } mutex_global_lock(); while (max_len) { - BT_HDR* p_buf = - static_cast(fixed_queue_try_peek_first(p_ccb->rx_queue)); - if (p_buf == NULL) break; + BT_HDR* p_buf = static_cast(fixed_queue_try_peek_first(p_ccb->rx_queue)); + if (p_buf == NULL) { + break; + } copy_len = (p_buf->len > max_len) ? max_len : p_buf->len; max_len -= copy_len; @@ -394,7 +397,7 @@ uint16_t GAP_ConnReadData(uint16_t gap_handle, uint8_t* p_data, mutex_global_unlock(); - return (BT_PASS); + return BT_PASS; } /******************************************************************************* @@ -418,18 +421,22 @@ int GAP_GetRxQueueCnt(uint16_t handle, uint32_t* p_rx_queue_count) { if (p_ccb->con_state == GAP_CCB_STATE_CONNECTED) { *p_rx_queue_count = p_ccb->rx_queue_size; - } else + } else { rc = GAP_INVALID_HANDLE; - } else + } + } else { rc = GAP_INVALID_HANDLE; + } - return (rc); + return rc; } /* Try to write the queued data to l2ca. Return true on success, or if queue is - * congested. False if error occured when writing. */ + * congested. False if error occurred when writing. */ static bool gap_try_write_queued_data(tGAP_CCB* p_ccb) { - if (p_ccb->is_congested) return true; + if (p_ccb->is_congested) { + return true; + } /* Send the buffer through L2CAP */ BT_HDR* p_buf; @@ -444,8 +451,9 @@ static bool gap_try_write_queued_data(tGAP_CCB* p_ccb) { if (status == tL2CAP_DW_RESULT::CONGESTED) { p_ccb->is_congested = true; return true; - } else if (status != tL2CAP_DW_RESULT::SUCCESS) + } else if (status != tL2CAP_DW_RESULT::SUCCESS) { return false; + } } return true; } @@ -487,9 +495,11 @@ uint16_t GAP_ConnWriteData(uint16_t gap_handle, BT_HDR* msg) { fixed_queue_enqueue(p_ccb->tx_queue, msg); - if (!gap_try_write_queued_data(p_ccb)) return GAP_ERR_BAD_STATE; + if (!gap_try_write_queued_data(p_ccb)) { + return GAP_ERR_BAD_STATE; + } - return (BT_PASS); + return BT_PASS; } /******************************************************************************* @@ -531,9 +541,11 @@ uint16_t GAP_ConnGetRemMtuSize(uint16_t gap_handle) { tGAP_CCB* p_ccb; p_ccb = gap_find_ccb_by_handle(gap_handle); - if (p_ccb == NULL) return (0); + if (p_ccb == NULL) { + return 0; + } - return (p_ccb->rem_mtu_size); + return p_ccb->rem_mtu_size; } /******************************************************************************* @@ -552,9 +564,11 @@ uint16_t GAP_ConnGetL2CAPCid(uint16_t gap_handle) { tGAP_CCB* p_ccb; p_ccb = gap_find_ccb_by_handle(gap_handle); - if (p_ccb == NULL) return (0); + if (p_ccb == NULL) { + return 0; + } - return (p_ccb->connection_id); + return p_ccb->connection_id; } /******************************************************************************* @@ -569,7 +583,9 @@ uint16_t GAP_ConnGetL2CAPCid(uint16_t gap_handle) { ******************************************************************************/ void gap_tx_complete_ind(uint16_t l2cap_cid, uint16_t sdu_sent) { tGAP_CCB* p_ccb = gap_find_ccb_by_cid(l2cap_cid); - if (p_ccb == NULL) return; + if (p_ccb == NULL) { + return; + } if ((p_ccb->con_state == GAP_CCB_STATE_CONNECTED) && (sdu_sent == 0xFFFF)) { p_ccb->p_callback(p_ccb->gap_handle, GAP_EVT_TX_EMPTY, nullptr); @@ -587,42 +603,41 @@ void gap_tx_complete_ind(uint16_t l2cap_cid, uint16_t sdu_sent) { * Returns void * ******************************************************************************/ -static void gap_connect_ind(const RawAddress& bd_addr, uint16_t l2cap_cid, - uint16_t psm, uint8_t /* l2cap_id */) { +static void gap_connect_ind(const RawAddress& bd_addr, uint16_t l2cap_cid, uint16_t psm, + uint8_t /* l2cap_id */) { uint16_t xx; tGAP_CCB* p_ccb; /* See if we have a CCB listening for the connection */ for (xx = 0, p_ccb = conn.ccb_pool; xx < GAP_MAX_CONNECTIONS; xx++, p_ccb++) { if ((p_ccb->con_state == GAP_CCB_STATE_LISTENING) && (p_ccb->psm == psm) && - (!p_ccb->rem_addr_specified || (bd_addr == p_ccb->rem_dev_address))) + (!p_ccb->rem_addr_specified || (bd_addr == p_ccb->rem_dev_address))) { break; + } } if (xx == GAP_MAX_CONNECTIONS) { log::warn("*******"); - log::warn( - "WARNING: GAP Conn Indication for Unexpected Bd Addr...Disconnecting"); + log::warn("WARNING: GAP Conn Indication for Unexpected Bd Addr...Disconnecting"); log::warn("*******"); /* Disconnect because it is an unexpected connection */ if (BTM_UseLeLink(bd_addr)) { if (!L2CA_DisconnectLECocReq(l2cap_cid)) { - log::warn("Unable to request L2CAP disconnect le_coc peer:{} cid:{}", - bd_addr, l2cap_cid); + log::warn("Unable to request L2CAP disconnect le_coc peer:{} cid:{}", bd_addr, l2cap_cid); } } else { if (!L2CA_DisconnectReq(l2cap_cid)) { - log::warn("Unable to request L2CAP disconnect le_coc peer:{} cid:{}", - bd_addr, l2cap_cid); + log::warn("Unable to request L2CAP disconnect le_coc peer:{} cid:{}", bd_addr, l2cap_cid); } } return; } /* Transition to the next appropriate state, waiting for config setup. */ - if (p_ccb->transport == BT_TRANSPORT_BR_EDR) + if (p_ccb->transport == BT_TRANSPORT_BR_EDR) { p_ccb->con_state = GAP_CCB_STATE_CFG_SETUP; + } /* Save the BD Address and Channel ID. */ p_ccb->rem_dev_address = bd_addr; @@ -631,8 +646,8 @@ static void gap_connect_ind(const RawAddress& bd_addr, uint16_t l2cap_cid, if (p_ccb->transport == BT_TRANSPORT_LE) { /* get the remote coc configuration */ if (!L2CA_GetPeerLECocConfig(l2cap_cid, &p_ccb->peer_coc_cfg)) { - log::warn("Unable to get L2CAP peer le_coc config peer:{} cid:{}", - p_ccb->rem_dev_address, l2cap_cid); + log::warn("Unable to get L2CAP peer le_coc config peer:{} cid:{}", p_ccb->rem_dev_address, + l2cap_cid); } p_ccb->rem_mtu_size = p_ccb->peer_coc_cfg.mtu; @@ -682,22 +697,27 @@ static void gap_checks_con_flags(tGAP_CCB* p_ccb) { * ******************************************************************************/ static void gap_sec_check_complete(tGAP_CCB* p_ccb) { - if (p_ccb->con_state == GAP_CCB_STATE_IDLE) return; + if (p_ccb->con_state == GAP_CCB_STATE_IDLE) { + return; + } p_ccb->con_flags |= GAP_CCB_FLAGS_SEC_DONE; gap_checks_con_flags(p_ccb); } static void gap_on_l2cap_error(uint16_t l2cap_cid, uint16_t result) { tGAP_CCB* p_ccb = gap_find_ccb_by_cid(l2cap_cid); - if (p_ccb == nullptr) return; + if (p_ccb == nullptr) { + return; + } /* Propagate the l2cap result upward */ tGAP_CB_DATA cb_data; cb_data.l2cap_result = result; /* Tell the user if there is a callback */ - if (p_ccb->p_callback) + if (p_ccb->p_callback) { (*p_ccb->p_callback)(p_ccb->gap_handle, GAP_EVT_CONN_CLOSED, &cb_data); + } gap_release_ccb(p_ccb); } @@ -718,19 +738,19 @@ static void gap_connect_cfm(uint16_t l2cap_cid, uint16_t result) { /* Find CCB based on CID */ p_ccb = gap_find_ccb_by_cid(l2cap_cid); - if (p_ccb == NULL) return; + if (p_ccb == NULL) { + return; + } /* initiate security process, if needed */ - if ((p_ccb->con_flags & GAP_CCB_FLAGS_SEC_DONE) == 0 && - p_ccb->transport != BT_TRANSPORT_LE) { + if ((p_ccb->con_flags & GAP_CCB_FLAGS_SEC_DONE) == 0 && p_ccb->transport != BT_TRANSPORT_LE) { // Assume security check is done by L2cap gap_sec_check_complete(p_ccb); } /* If the connection response contains success status, then */ /* Transition to the next state and startup the timer. */ - if ((result == L2CAP_CONN_OK) && - (p_ccb->con_state == GAP_CCB_STATE_CONN_SETUP)) { + if ((result == L2CAP_CONN_OK) && (p_ccb->con_state == GAP_CCB_STATE_CONN_SETUP)) { if (p_ccb->transport == BT_TRANSPORT_BR_EDR) { p_ccb->con_state = GAP_CCB_STATE_CFG_SETUP; } @@ -738,8 +758,8 @@ static void gap_connect_cfm(uint16_t l2cap_cid, uint16_t result) { if (p_ccb->transport == BT_TRANSPORT_LE) { /* get the remote coc configuration */ if (!L2CA_GetPeerLECocConfig(l2cap_cid, &p_ccb->peer_coc_cfg)) { - log::warn("Unable to get L2CAP peer le_coc config peer:{} cid:{}", - p_ccb->rem_dev_address, l2cap_cid); + log::warn("Unable to get L2CAP peer le_coc config peer:{} cid:{}", p_ccb->rem_dev_address, + l2cap_cid); } p_ccb->rem_mtu_size = p_ccb->peer_coc_cfg.mtu; @@ -768,15 +788,16 @@ static void gap_config_ind(uint16_t l2cap_cid, tL2CAP_CFG_INFO* p_cfg) { /* Find CCB based on CID */ p_ccb = gap_find_ccb_by_cid(l2cap_cid); - if (p_ccb == NULL) return; + if (p_ccb == NULL) { + return; + } /* Remember the remote MTU size */ if (!p_cfg->mtu_present) { p_ccb->rem_mtu_size = L2CAP_DEFAULT_MTU; } else { if (p_ccb->cfg.fcr.mode == L2CAP_FCR_ERTM_MODE) { - local_mtu_size = - BT_DEFAULT_BUFFER_SIZE - sizeof(BT_HDR) - L2CAP_MIN_OFFSET; + local_mtu_size = BT_DEFAULT_BUFFER_SIZE - sizeof(BT_HDR) - L2CAP_MIN_OFFSET; } else { local_mtu_size = L2CAP_MTU_SIZE; } @@ -798,15 +819,16 @@ static void gap_config_ind(uint16_t l2cap_cid, tL2CAP_CFG_INFO* p_cfg) { * Returns void * ******************************************************************************/ -static void gap_config_cfm(uint16_t l2cap_cid, uint16_t /* initiator */, - tL2CAP_CFG_INFO* p_cfg) { +static void gap_config_cfm(uint16_t l2cap_cid, uint16_t /* initiator */, tL2CAP_CFG_INFO* p_cfg) { gap_config_ind(l2cap_cid, p_cfg); tGAP_CCB* p_ccb; /* Find CCB based on CID */ p_ccb = gap_find_ccb_by_cid(l2cap_cid); - if (p_ccb == NULL) return; + if (p_ccb == NULL) { + return; + } p_ccb->con_flags |= GAP_CCB_FLAGS_MY_CFG_DONE; p_ccb->con_flags |= GAP_CCB_FLAGS_HIS_CFG_DONE; @@ -828,7 +850,9 @@ static void gap_disconnect_ind(uint16_t l2cap_cid, bool /* ack_needed */) { /* Find CCB based on CID */ p_ccb = gap_find_ccb_by_cid(l2cap_cid); - if (p_ccb == NULL) return; + if (p_ccb == NULL) { + return; + } p_ccb->p_callback(p_ccb->gap_handle, GAP_EVT_CONN_CLOSED, nullptr); gap_release_ccb(p_ccb); @@ -876,14 +900,14 @@ static void gap_data_ind(uint16_t l2cap_cid, BT_HDR* p_msg) { ******************************************************************************/ static void gap_congestion_ind(uint16_t lcid, bool is_congested) { tGAP_CCB* p_ccb = gap_find_ccb_by_cid(lcid); /* Find CCB based on CID */ - if (!p_ccb) return; + if (!p_ccb) { + return; + } p_ccb->is_congested = is_congested; - p_ccb->p_callback( - p_ccb->gap_handle, - (is_congested) ? GAP_EVT_CONN_CONGESTED : GAP_EVT_CONN_UNCONGESTED, - nullptr); + p_ccb->p_callback(p_ccb->gap_handle, + (is_congested) ? GAP_EVT_CONN_CONGESTED : GAP_EVT_CONN_UNCONGESTED, nullptr); gap_try_write_queued_data(p_ccb); } @@ -904,13 +928,13 @@ static tGAP_CCB* gap_find_ccb_by_cid(uint16_t cid) { /* Look through each connection control block */ for (xx = 0, p_ccb = conn.ccb_pool; xx < GAP_MAX_CONNECTIONS; xx++, p_ccb++) { - if ((p_ccb->con_state != GAP_CCB_STATE_IDLE) && - (p_ccb->connection_id == cid)) - return (p_ccb); + if ((p_ccb->con_state != GAP_CCB_STATE_IDLE) && (p_ccb->connection_id == cid)) { + return p_ccb; + } } /* If here, not found */ - return (NULL); + return NULL; } /******************************************************************************* @@ -930,11 +954,13 @@ static tGAP_CCB* gap_find_ccb_by_handle(uint16_t handle) { if (handle < GAP_MAX_CONNECTIONS) { p_ccb = &conn.ccb_pool[handle]; - if (p_ccb->con_state != GAP_CCB_STATE_IDLE) return (p_ccb); + if (p_ccb->con_state != GAP_CCB_STATE_IDLE) { + return p_ccb; + } } /* If here, handle points to invalid connection */ - return (NULL); + return NULL; } /******************************************************************************* @@ -960,12 +986,12 @@ static tGAP_CCB* gap_allocate_ccb(void) { p_ccb->gap_handle = xx; p_ccb->rem_mtu_size = L2CAP_MTU_SIZE; - return (p_ccb); + return p_ccb; } } /* If here, no free CCB found */ - return (NULL); + return NULL; } /******************************************************************************* @@ -981,13 +1007,15 @@ static void gap_release_ccb(tGAP_CCB* p_ccb) { /* Drop any buffers we may be holding */ p_ccb->rx_queue_size = 0; - while (!fixed_queue_is_empty(p_ccb->rx_queue)) + while (!fixed_queue_is_empty(p_ccb->rx_queue)) { osi_free(fixed_queue_try_dequeue(p_ccb->rx_queue)); + } fixed_queue_free(p_ccb->rx_queue, NULL); p_ccb->rx_queue = NULL; - while (!fixed_queue_is_empty(p_ccb->tx_queue)) + while (!fixed_queue_is_empty(p_ccb->tx_queue)) { osi_free(fixed_queue_try_dequeue(p_ccb->tx_queue)); + } fixed_queue_free(p_ccb->tx_queue, NULL); p_ccb->tx_queue = NULL; @@ -996,16 +1024,19 @@ static void gap_release_ccb(tGAP_CCB* p_ccb) { /* If no-one else is using the PSM, deregister from L2CAP */ tGAP_CCB* p_ccb_local = conn.ccb_pool; for (uint16_t i = 0; i < GAP_MAX_CONNECTIONS; i++, p_ccb_local++) { - if ((p_ccb_local->con_state != GAP_CCB_STATE_IDLE) && - (p_ccb_local->psm == p_ccb->psm)) { + if ((p_ccb_local->con_state != GAP_CCB_STATE_IDLE) && (p_ccb_local->psm == p_ccb->psm)) { return; } } /* Free the security record for this PSM */ BTM_SecClrServiceByPsm(p_ccb->psm); - if (p_ccb->transport == BT_TRANSPORT_BR_EDR) L2CA_Deregister(p_ccb->psm); - if (p_ccb->transport == BT_TRANSPORT_LE) L2CA_DeregisterLECoc(p_ccb->psm); + if (p_ccb->transport == BT_TRANSPORT_BR_EDR) { + L2CA_Deregister(p_ccb->psm); + } + if (p_ccb->transport == BT_TRANSPORT_LE) { + L2CA_DeregisterLECoc(p_ccb->psm); + } } void gap_attr_db_init(void); diff --git a/system/stack/gatt/att_protocol.cc b/system/stack/gatt/att_protocol.cc index f1892128bfd..d5f524420a1 100644 --- a/system/stack/gatt/att_protocol.cc +++ b/system/stack/gatt/att_protocol.cc @@ -55,8 +55,7 @@ using namespace bluetooth; ******************************************************************************/ static BT_HDR* attp_build_mtu_cmd(uint8_t op_code, uint16_t rx_mtu) { uint8_t* p; - BT_HDR* p_buf = - (BT_HDR*)osi_malloc(sizeof(BT_HDR) + GATT_HDR_SIZE + L2CAP_MIN_OFFSET); + BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + GATT_HDR_SIZE + L2CAP_MIN_OFFSET); p = (uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET; UINT8_TO_STREAM(p, op_code); @@ -105,8 +104,7 @@ static BT_HDR* attp_build_exec_write_cmd(uint8_t op_code, uint8_t flag) { * Returns None. * ******************************************************************************/ -static BT_HDR* attp_build_err_cmd(uint8_t cmd_code, uint16_t err_handle, - uint8_t reason) { +static BT_HDR* attp_build_err_cmd(uint8_t cmd_code, uint16_t err_handle, uint8_t reason) { uint8_t* p; BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + L2CAP_MIN_OFFSET + 5); @@ -132,13 +130,11 @@ static BT_HDR* attp_build_err_cmd(uint8_t cmd_code, uint16_t err_handle, * Returns None. * ******************************************************************************/ -static BT_HDR* attp_build_browse_cmd(uint8_t op_code, uint16_t s_hdl, - uint16_t e_hdl, +static BT_HDR* attp_build_browse_cmd(uint8_t op_code, uint16_t s_hdl, uint16_t e_hdl, const bluetooth::Uuid& uuid) { const size_t payload_size = - (GATT_OP_CODE_SIZE) + (GATT_START_END_HANDLE_SIZE) + (Uuid::kNumBytes128); - BT_HDR* p_buf = - (BT_HDR*)osi_malloc(sizeof(BT_HDR) + payload_size + L2CAP_MIN_OFFSET); + (GATT_OP_CODE_SIZE) + (GATT_START_END_HANDLE_SIZE) + (Uuid::kNumBytes128); + BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + payload_size + L2CAP_MIN_OFFSET); uint8_t* p = (uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET; /* Describe the built message location and size */ @@ -162,8 +158,8 @@ static BT_HDR* attp_build_browse_cmd(uint8_t op_code, uint16_t s_hdl, * Returns pointer to the command buffer. * ******************************************************************************/ -static BT_HDR* attp_build_read_by_type_value_cmd( - uint16_t payload_size, tGATT_FIND_TYPE_VALUE* p_value_type) { +static BT_HDR* attp_build_read_by_type_value_cmd(uint16_t payload_size, + tGATT_FIND_TYPE_VALUE* p_value_type) { uint8_t* p; uint16_t len = p_value_type->value_len; BT_HDR* p_buf = nullptr; @@ -172,8 +168,7 @@ static BT_HDR* attp_build_read_by_type_value_cmd( return nullptr; } - p_buf = - (BT_HDR*)osi_malloc(sizeof(BT_HDR) + payload_size + L2CAP_MIN_OFFSET); + p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + payload_size + L2CAP_MIN_OFFSET); p = (uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET; p_buf->offset = L2CAP_MIN_OFFSET; @@ -185,8 +180,9 @@ static BT_HDR* attp_build_read_by_type_value_cmd( p_buf->len += gatt_build_uuid_to_stream(&p, p_value_type->uuid); - if (p_value_type->value_len + p_buf->len > payload_size) + if (p_value_type->value_len + p_buf->len > payload_size) { len = payload_size - p_buf->len; + } memcpy(p, p_value_type->value, len); p_buf->len += len; @@ -232,8 +228,7 @@ static BT_HDR* attp_build_read_multi_cmd(uint8_t op_code, uint16_t payload_size, * Returns None. * ******************************************************************************/ -static BT_HDR* attp_build_handle_cmd(uint8_t op_code, uint16_t handle, - uint16_t offset) { +static BT_HDR* attp_build_handle_cmd(uint8_t op_code, uint16_t handle, uint16_t offset) { uint8_t* p; BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + 5 + L2CAP_MIN_OFFSET); @@ -285,9 +280,8 @@ static BT_HDR* attp_build_opcode_cmd(uint8_t op_code) { * Returns None. * ******************************************************************************/ -static BT_HDR* attp_build_value_cmd(uint16_t payload_size, uint8_t op_code, - uint16_t handle, uint16_t offset, - uint16_t len, uint8_t* p_data) { +static BT_HDR* attp_build_value_cmd(uint16_t payload_size, uint8_t op_code, uint16_t handle, + uint16_t offset, uint16_t len, uint8_t* p_data) { uint8_t *p, *pp, *p_pair_len; size_t pair_len; size_t size_now = 1; @@ -301,8 +295,7 @@ static BT_HDR* attp_build_value_cmd(uint16_t payload_size, uint8_t op_code, } \ } while (false) - BT_HDR* p_buf = - (BT_HDR*)osi_malloc(sizeof(BT_HDR) + payload_size + L2CAP_MIN_OFFSET); + BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + payload_size + L2CAP_MIN_OFFSET); p = pp = (uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET; @@ -371,8 +364,7 @@ static BT_HDR* attp_build_value_cmd(uint16_t payload_size, uint8_t op_code, * Description Send message to L2CAP. * ******************************************************************************/ -tGATT_STATUS attp_send_msg_to_l2cap(tGATT_TCB& tcb, uint16_t lcid, - BT_HDR* p_toL2CAP) { +tGATT_STATUS attp_send_msg_to_l2cap(tGATT_TCB& tcb, uint16_t lcid, BT_HDR* p_toL2CAP) { tL2CAP_DW_RESULT l2cap_ret; if (lcid == L2CAP_ATT_CID) { @@ -399,34 +391,30 @@ BT_HDR* attp_build_sr_msg(tGATT_TCB& tcb, uint8_t op_code, tGATT_SR_MSG* p_msg, uint16_t offset = 0; if (payload_size == 0) { - log::error( - "Cannot send response (op: 0x{:02x}) due to payload size = 0, {}", - op_code, tcb.peer_bda); + log::error("Cannot send response (op: 0x{:02x}) due to payload size = 0, {}", op_code, + tcb.peer_bda); return nullptr; } switch (op_code) { case GATT_RSP_READ_BLOB: case GATT_RSP_PREPARE_WRITE: - log::verbose( - "ATT_RSP_READ_BLOB/GATT_RSP_PREPARE_WRITE: len = {} offset = {}", - p_msg->attr_value.len, p_msg->attr_value.offset); + log::verbose("ATT_RSP_READ_BLOB/GATT_RSP_PREPARE_WRITE: len = {} offset = {}", + p_msg->attr_value.len, p_msg->attr_value.offset); offset = p_msg->attr_value.offset; FALLTHROUGH_INTENDED; /* FALLTHROUGH */ case GATT_RSP_READ_BY_TYPE: case GATT_RSP_READ: case GATT_HANDLE_VALUE_NOTIF: case GATT_HANDLE_VALUE_IND: - return attp_build_value_cmd( - payload_size, op_code, p_msg->attr_value.handle, offset, - p_msg->attr_value.len, p_msg->attr_value.value); + return attp_build_value_cmd(payload_size, op_code, p_msg->attr_value.handle, offset, + p_msg->attr_value.len, p_msg->attr_value.value); case GATT_RSP_WRITE: return attp_build_opcode_cmd(op_code); case GATT_RSP_ERROR: - return attp_build_err_cmd(p_msg->error.cmd_code, p_msg->error.handle, - p_msg->error.reason); + return attp_build_err_cmd(p_msg->error.cmd_code, p_msg->error.handle, p_msg->error.reason); case GATT_RSP_EXEC_WRITE: return attp_build_exec_write_cmd(op_code, 0); @@ -476,31 +464,27 @@ tGATT_STATUS attp_send_sr_msg(tGATT_TCB& tcb, uint16_t cid, BT_HDR* p_msg) { * GATT_ERROR if command sending failure * ******************************************************************************/ -static tGATT_STATUS attp_cl_send_cmd(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, - uint8_t cmd_code, BT_HDR* p_cmd) { +static tGATT_STATUS attp_cl_send_cmd(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, uint8_t cmd_code, + BT_HDR* p_cmd) { cmd_code &= ~GATT_AUTH_SIGN_MASK; - if (gatt_tcb_is_cid_busy(tcb, p_clcb->cid) && - cmd_code != GATT_HANDLE_VALUE_CONF) { + if (gatt_tcb_is_cid_busy(tcb, p_clcb->cid) && cmd_code != GATT_HANDLE_VALUE_CONF) { if (gatt_cmd_enq(tcb, p_clcb, true, cmd_code, p_cmd)) { - log::debug("Enqueued ATT command {} conn_id=0x{:04x}, cid={}", - fmt::ptr(p_clcb), p_clcb->conn_id, p_clcb->cid); + log::debug("Enqueued ATT command {} conn_id=0x{:04x}, cid={}", fmt::ptr(p_clcb), + p_clcb->conn_id, p_clcb->cid); return GATT_CMD_STARTED; } - log::error("{}, cid 0x{:02x} already disconnected", tcb.peer_bda, - p_clcb->cid); + log::error("{}, cid 0x{:02x} already disconnected", tcb.peer_bda, p_clcb->cid); return GATT_INTERNAL_ERROR; } - log::debug( - "Sending ATT command to l2cap cid:0x{:04x} eatt_channels:{} transport:{}", - p_clcb->cid, tcb.eatt, bt_transport_text(tcb.transport)); + log::debug("Sending ATT command to l2cap cid:0x{:04x} eatt_channels:{} transport:{}", p_clcb->cid, + tcb.eatt, bt_transport_text(tcb.transport)); tGATT_STATUS att_ret = attp_send_msg_to_l2cap(tcb, p_clcb->cid, p_cmd); if (att_ret != GATT_CONGESTED && att_ret != GATT_SUCCESS) { - log::warn( - "Unable to send ATT command to l2cap layer {} conn_id=0x{:04x}, cid={}", - fmt::ptr(p_clcb), p_clcb->conn_id, p_clcb->cid); + log::warn("Unable to send ATT command to l2cap layer {} conn_id=0x{:04x}, cid={}", + fmt::ptr(p_clcb), p_clcb->conn_id, p_clcb->cid); return GATT_INTERNAL_ERROR; } @@ -508,13 +492,12 @@ static tGATT_STATUS attp_cl_send_cmd(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, return att_ret; } - log::debug("Starting ATT response timer {} conn_id=0x{:04x}, cid={}", - fmt::ptr(p_clcb), p_clcb->conn_id, p_clcb->cid); + log::debug("Starting ATT response timer {} conn_id=0x{:04x}, cid={}", fmt::ptr(p_clcb), + p_clcb->conn_id, p_clcb->cid); gatt_start_rsp_timer(p_clcb); if (!gatt_cmd_enq(tcb, p_clcb, false, cmd_code, NULL)) { - log::error( - "Could not queue sent request. {}, cid 0x{:02x} already disconnected", - tcb.peer_bda, p_clcb->cid); + log::error("Could not queue sent request. {}, cid 0x{:02x} already disconnected", tcb.peer_bda, + p_clcb->cid); return GATT_INTERNAL_ERROR; } @@ -539,7 +522,9 @@ tGATT_STATUS attp_send_cl_confirmation_msg(tGATT_TCB& tcb, uint16_t cid) { BT_HDR* p_cmd = NULL; p_cmd = attp_build_opcode_cmd(GATT_HANDLE_VALUE_CONF); - if (p_cmd == NULL) return GATT_NO_RESOURCES; + if (p_cmd == NULL) { + return GATT_NO_RESOURCES; + } /* no pending request or value confirmation */ tGATT_STATUS att_ret = attp_send_msg_to_l2cap(tcb, cid, p_cmd); @@ -566,8 +551,8 @@ tGATT_STATUS attp_send_cl_confirmation_msg(tGATT_TCB& tcb, uint16_t cid) { * * ******************************************************************************/ -tGATT_STATUS attp_send_cl_msg(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, - uint8_t op_code, tGATT_CL_MSG* p_msg) { +tGATT_STATUS attp_send_cl_msg(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, uint8_t op_code, + tGATT_CL_MSG* p_msg) { BT_HDR* p_cmd = NULL; uint16_t offset = 0, handle; @@ -578,17 +563,15 @@ tGATT_STATUS attp_send_cl_msg(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, uint16_t payload_size = gatt_tcb_get_payload_size(tcb, p_clcb->cid); if (payload_size == 0) { - log::error("Cannot send request (op: 0x{:02x}) due to payload size = 0, {}", - op_code, tcb.peer_bda); + log::error("Cannot send request (op: 0x{:02x}) due to payload size = 0, {}", op_code, + tcb.peer_bda); return GATT_NO_RESOURCES; } switch (op_code) { case GATT_REQ_MTU: if (p_msg->mtu > GATT_MAX_MTU_SIZE) { - log::warn( - "GATT message MTU is larger than max GATT MTU size op_code:{}", - op_code); + log::warn("GATT message MTU is larger than max GATT MTU size op_code:{}", op_code); return GATT_ILLEGAL_PARAMETER; } p_cmd = attp_build_mtu_cmd(GATT_REQ_MTU, p_msg->mtu); @@ -604,16 +587,15 @@ tGATT_STATUS attp_send_cl_msg(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, return GATT_ILLEGAL_PARAMETER; } - p_cmd = attp_build_browse_cmd(op_code, p_msg->browse.s_handle, - p_msg->browse.e_handle, p_msg->browse.uuid); + p_cmd = attp_build_browse_cmd(op_code, p_msg->browse.s_handle, p_msg->browse.e_handle, + p_msg->browse.uuid); break; case GATT_REQ_READ_BLOB: offset = p_msg->read_blob.offset; FALLTHROUGH_INTENDED; /* FALLTHROUGH */ case GATT_REQ_READ: - handle = - (op_code == GATT_REQ_READ) ? p_msg->handle : p_msg->read_blob.handle; + handle = (op_code == GATT_REQ_READ) ? p_msg->handle : p_msg->read_blob.handle; /* handle checking */ if (!GATT_HANDLE_IS_VALID(handle)) { log::warn("GATT message has invalid handle op_code:{}", op_code); @@ -634,9 +616,8 @@ tGATT_STATUS attp_send_cl_msg(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, return GATT_ILLEGAL_PARAMETER; } - p_cmd = attp_build_value_cmd( - payload_size, op_code, p_msg->attr_value.handle, offset, - p_msg->attr_value.len, p_msg->attr_value.value); + p_cmd = attp_build_value_cmd(payload_size, op_code, p_msg->attr_value.handle, offset, + p_msg->attr_value.len, p_msg->attr_value.value); break; case GATT_REQ_EXEC_WRITE: @@ -644,14 +625,12 @@ tGATT_STATUS attp_send_cl_msg(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, break; case GATT_REQ_FIND_TYPE_VALUE: - p_cmd = attp_build_read_by_type_value_cmd(payload_size, - &p_msg->find_type_value); + p_cmd = attp_build_read_by_type_value_cmd(payload_size, &p_msg->find_type_value); break; case GATT_REQ_READ_MULTI: case GATT_REQ_READ_MULTI_VAR: - p_cmd = attp_build_read_multi_cmd(op_code, payload_size, - p_msg->read_multi.num_handles, + p_cmd = attp_build_read_multi_cmd(op_code, payload_size, p_msg->read_multi.num_handles, p_msg->read_multi.handles); break; @@ -660,9 +639,7 @@ tGATT_STATUS attp_send_cl_msg(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, } if (p_cmd == NULL) { - log::warn( - "Unable to build proper GATT message to send to peer device op_code:{}", - op_code); + log::warn("Unable to build proper GATT message to send to peer device op_code:{}", op_code); return GATT_NO_RESOURCES; } @@ -672,11 +649,9 @@ tGATT_STATUS attp_send_cl_msg(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, namespace bluetooth { namespace legacy { namespace testing { -BT_HDR* attp_build_value_cmd(uint16_t payload_size, uint8_t op_code, - uint16_t handle, uint16_t offset, uint16_t len, - uint8_t* p_data) { - return ::attp_build_value_cmd(payload_size, op_code, handle, offset, len, - p_data); +BT_HDR* attp_build_value_cmd(uint16_t payload_size, uint8_t op_code, uint16_t handle, + uint16_t offset, uint16_t len, uint8_t* p_data) { + return ::attp_build_value_cmd(payload_size, op_code, handle, offset, len, p_data); } } // namespace testing } // namespace legacy diff --git a/system/stack/gatt/connection_manager.cc b/system/stack/gatt/connection_manager.cc index cb360b41ad1..3a955d8987d 100644 --- a/system/stack/gatt/connection_manager.cc +++ b/system/stack/gatt/connection_manager.cc @@ -58,8 +58,8 @@ static void alarm_closure_cb(void* p) { } // Periodic alarms are not supported, because we clean up data in callback -void alarm_set_closure(const base::Location& posted_from, alarm_t* alarm, - uint64_t interval_ms, base::OnceClosure user_task) { +void alarm_set_closure(const base::Location& posted_from, alarm_t* alarm, uint64_t interval_ms, + base::OnceClosure user_task) { closure_data* data = new closure_data; data->posted_from = posted_from; data->user_task = std::move(user_task); @@ -86,27 +86,22 @@ namespace { std::map bgconn_dev; int num_of_targeted_announcements_users(void) { - return std::count_if( - bgconn_dev.begin(), bgconn_dev.end(), [](const auto& pair) { - return (!pair.second.is_in_accept_list && - !pair.second.doing_targeted_announcements_conn.empty()); - }); + return std::count_if(bgconn_dev.begin(), bgconn_dev.end(), [](const auto& pair) { + return !pair.second.is_in_accept_list && !pair.second.doing_targeted_announcements_conn.empty(); + }); } bool is_anyone_interested_to_use_accept_list( - const std::map::iterator it) { + const std::map::iterator it) { if (!it->second.doing_targeted_announcements_conn.empty()) { - return (!it->second.doing_direct_conn.empty()); + return !it->second.doing_direct_conn.empty(); } - return (!it->second.doing_bg_conn.empty() || - !it->second.doing_direct_conn.empty()); + return !it->second.doing_bg_conn.empty() || !it->second.doing_direct_conn.empty(); } -bool is_anyone_connecting( - const std::map::iterator it) { - return (!it->second.doing_bg_conn.empty() || - !it->second.doing_direct_conn.empty() || - !it->second.doing_targeted_announcements_conn.empty()); +bool is_anyone_connecting(const std::map::iterator it) { + return !it->second.doing_bg_conn.empty() || !it->second.doing_direct_conn.empty() || + !it->second.doing_targeted_announcements_conn.empty(); } } // namespace @@ -116,8 +111,7 @@ bool is_anyone_connecting( std::set get_apps_connecting_to(const RawAddress& address) { log::debug("address={}", address); auto it = bgconn_dev.find(address); - return (it != bgconn_dev.end()) ? it->second.doing_bg_conn - : std::set(); + return (it != bgconn_dev.end()) ? it->second.doing_bg_conn : std::set(); } bool IsTargetedAnnouncement(const uint8_t* p_eir, uint16_t eir_len) { @@ -125,9 +119,9 @@ bool IsTargetedAnnouncement(const uint8_t* p_eir, uint16_t eir_len) { uint8_t service_data_len = 0; while ((p_service_data = AdvertiseDataParser::GetFieldByType( - p_service_data + service_data_len, - eir_len - (p_service_data - p_eir) - service_data_len, - BTM_BLE_AD_TYPE_SERVICE_DATA_TYPE, &service_data_len))) { + p_service_data + service_data_len, + eir_len - (p_service_data - p_eir) - service_data_len, + BTM_BLE_AD_TYPE_SERVICE_DATA_TYPE, &service_data_len))) { uint16_t uuid; uint8_t announcement_type; const uint8_t* p_tmp = p_service_data; @@ -152,16 +146,13 @@ bool IsTargetedAnnouncement(const uint8_t* p_eir, uint16_t eir_len) { return false; } -static void schedule_direct_connect_add(uint8_t app_id, - const RawAddress& address); +static void schedule_direct_connect_add(uint8_t app_id, const RawAddress& address); -static void target_announcement_observe_results_cb(tBTM_INQ_RESULTS* p_inq, - const uint8_t* p_eir, +static void target_announcement_observe_results_cb(tBTM_INQ_RESULTS* p_inq, const uint8_t* p_eir, uint16_t eir_len) { auto addr = p_inq->remote_bd_addr; auto it = bgconn_dev.find(addr); - if (it == bgconn_dev.end() || - it->second.doing_targeted_announcements_conn.empty()) { + if (it == bgconn_dev.end() || it->second.doing_targeted_announcements_conn.empty()) { return; } @@ -188,20 +179,17 @@ static void target_announcement_observe_results_cb(tBTM_INQ_RESULTS* p_inq, auto app_id = *(it->second.doing_targeted_announcements_conn.begin()); /* If scan is ongoing lets stop it */ - do_in_main_thread(FROM_HERE, - base::BindOnce(schedule_direct_connect_add, app_id, addr)); + do_in_main_thread(FROM_HERE, base::BindOnce(schedule_direct_connect_add, app_id, addr)); } void target_announcements_filtering_set(bool enable) { log::debug("enable {}", enable); - BTM_LogHistory(kBtmLogTag, RawAddress::kEmpty, - (enable ? "Start filtering" : "Stop filtering")); + BTM_LogHistory(kBtmLogTag, RawAddress::kEmpty, (enable ? "Start filtering" : "Stop filtering")); /* Safe to call as if there is no support for filtering, this call will be * ignored. */ bluetooth::shim::set_target_announcements_filter(enable); - BTM_BleTargetAnnouncementObserve(enable, - target_announcement_observe_results_cb); + BTM_BleTargetAnnouncementObserve(enable, target_announcement_observe_results_cb); } /** Add a device to the background connection list for targeted announcements. @@ -209,8 +197,7 @@ void target_announcements_filtering_set(bool enable) { * true if device added to the list, or already in list, * false otherwise */ -bool background_connect_targeted_announcement_add(tAPP_ID app_id, - const RawAddress& address) { +bool background_connect_targeted_announcement_add(tAPP_ID app_id, const RawAddress& address) { log::info("app_id={}, address={}", static_cast(app_id), address); bool disable_accept_list = false; @@ -219,28 +206,21 @@ bool background_connect_targeted_announcement_add(tAPP_ID app_id, if (it != bgconn_dev.end()) { // check if filtering already enabled if (it->second.doing_targeted_announcements_conn.count(app_id)) { - log::info( - "app_id={}, already doing targeted announcement filtering to " - "address={}", - static_cast(app_id), address); + log::info("app_id={}, already doing targeted announcement filtering to address={}", + static_cast(app_id), address); return true; } - bool targeted_filtering_enabled = - !it->second.doing_targeted_announcements_conn.empty(); + bool targeted_filtering_enabled = !it->second.doing_targeted_announcements_conn.empty(); // Check if connecting if (!it->second.doing_direct_conn.empty()) { - log::info("app_id={}, address={}, already in direct connection", - static_cast(app_id), address); + log::info("app_id={}, address={}, already in direct connection", static_cast(app_id), + address); - } else if (!targeted_filtering_enabled && - !it->second.doing_bg_conn.empty()) { + } else if (!targeted_filtering_enabled && !it->second.doing_bg_conn.empty()) { // device is already in the acceptlist so we would have to remove it - log::info( - "already doing background connection to address={}. Need to disable " - "it.", - address); + log::info("already doing background connection to address={}. Need to disable it.", address); disable_accept_list = true; } } @@ -279,12 +259,11 @@ bool background_connect_add(uint8_t app_id, const RawAddress& address) { // Already in acceptlist ? if (it->second.is_in_accept_list) { - log::debug("app_id={}, address={}, already in accept list", - static_cast(app_id), address); + log::debug("app_id={}, address={}, already in accept list", static_cast(app_id), + address); in_acceptlist = true; } else { - is_targeted_announcement_enabled = - !it->second.doing_targeted_announcements_conn.empty(); + is_targeted_announcement_enabled = !it->second.doing_targeted_announcements_conn.empty(); } } @@ -336,25 +315,23 @@ bool background_connect_remove(uint8_t app_id, const RawAddress& address) { bool accept_list_enabled = it->second.is_in_accept_list; auto num_of_targeted_announcements_before_remove = - it->second.doing_targeted_announcements_conn.size(); + it->second.doing_targeted_announcements_conn.size(); bool removed_from_bg_conn = (it->second.doing_bg_conn.erase(app_id) > 0); - bool removed_from_ta = - (it->second.doing_targeted_announcements_conn.erase(app_id) > 0); + bool removed_from_ta = (it->second.doing_targeted_announcements_conn.erase(app_id) > 0); if (!removed_from_bg_conn && !removed_from_ta) { log::warn("Failed to remove background connection app {} for address {}", static_cast(app_id), address); return false; } - if (removed_from_ta && - it->second.doing_targeted_announcements_conn.size() == 0) { + if (removed_from_ta && it->second.doing_targeted_announcements_conn.size() == 0) { BTM_LogHistory(kBtmLogTag, address, "Ignore connection from"); } if (is_anyone_connecting(it)) { - log::debug("some device is still connecting, app_id={}, address={}", - static_cast(app_id), address); + log::debug("some device is still connecting, app_id={}, address={}", static_cast(app_id), + address); /* Check which method should be used now.*/ if (!accept_list_enabled) { /* Accept list was not used */ @@ -413,8 +390,7 @@ void on_app_deregistered(uint8_t app_id) { } } -static void remove_all_clients_with_pending_connections( - const RawAddress& address) { +static void remove_all_clients_with_pending_connections(const RawAddress& address) { log::debug("address={}", address); auto it = bgconn_dev.find(address); while (it != bgconn_dev.end() && !it->second.doing_direct_conn.empty()) { @@ -463,15 +439,13 @@ bool direct_connect_add(uint8_t app_id, const RawAddress& address) { if (it != bgconn_dev.end()) { // app already trying to connect to this particular device if (it->second.doing_direct_conn.count(app_id)) { - log::info("direct connect attempt from app_id=0x{:x} already in progress", - app_id); + log::info("direct connect attempt from app_id=0x{:x} already in progress", app_id); return false; } // are we already in the acceptlist ? if (it->second.is_in_accept_list) { - log::warn("Background connection attempt already in progress app_id={:x}", - app_id); + log::warn("Background connection attempt already in progress app_id={:x}", app_id); in_acceptlist = true; } } @@ -487,28 +461,23 @@ bool direct_connect_add(uint8_t app_id, const RawAddress& address) { // Setup a timer alarm_t* timeout = alarm_new("wl_conn_params_30s"); - alarm_set_closure( - FROM_HERE, timeout, DIRECT_CONNECT_TIMEOUT, - base::BindOnce(&wl_direct_connect_timeout_cb, app_id, address)); + alarm_set_closure(FROM_HERE, timeout, DIRECT_CONNECT_TIMEOUT, + base::BindOnce(&wl_direct_connect_timeout_cb, app_id, address)); - bgconn_dev[address].doing_direct_conn.emplace( - app_id, unique_alarm_ptr(timeout, &alarm_free)); + bgconn_dev[address].doing_direct_conn.emplace(app_id, unique_alarm_ptr(timeout, &alarm_free)); return true; } -static void schedule_direct_connect_add(uint8_t app_id, - const RawAddress& address) { +static void schedule_direct_connect_add(uint8_t app_id, const RawAddress& address) { direct_connect_add(app_id, address); } -bool direct_connect_remove(uint8_t app_id, const RawAddress& address, - bool connection_timeout) { +bool direct_connect_remove(uint8_t app_id, const RawAddress& address, bool connection_timeout) { log::debug("app_id={}, address={}", static_cast(app_id), address); auto it = bgconn_dev.find(address); if (it == bgconn_dev.end()) { - log::warn("Unable to find background connection to remove peer:{}", - address); + log::warn("Unable to find background connection to remove peer:{}", address); return false; } @@ -519,8 +488,7 @@ bool direct_connect_remove(uint8_t app_id, const RawAddress& address, } /* Let see if the device was connected due to Target Announcements.*/ - bool is_targeted_announcement_enabled = - !it->second.doing_targeted_announcements_conn.empty(); + bool is_targeted_announcement_enabled = !it->second.doing_targeted_announcements_conn.empty(); // this will free the alarm it->second.doing_direct_conn.erase(app_it); @@ -532,10 +500,7 @@ bool direct_connect_remove(uint8_t app_id, const RawAddress& address, * the allow list. */ if (!BTM_AcceptlistAdd(address)) { - log::warn( - "Failed to re-add device {} to accept list after connection " - "timeout", - address); + log::warn("Failed to re-add device {} to accept list after connection timeout", address); } } return true; diff --git a/system/stack/gatt/connection_manager.h b/system/stack/gatt/connection_manager.h index 07dfa3ebfa5..fe564e9099c 100644 --- a/system/stack/gatt/connection_manager.h +++ b/system/stack/gatt/connection_manager.h @@ -37,8 +37,7 @@ namespace connection_manager { using tAPP_ID = uint8_t; /* for background connection */ -bool background_connect_targeted_announcement_add(tAPP_ID app_id, - const RawAddress& address); +bool background_connect_targeted_announcement_add(tAPP_ID app_id, const RawAddress& address); bool background_connect_add(tAPP_ID app_id, const RawAddress& address); bool background_connect_remove(tAPP_ID app_id, const RawAddress& address); bool remove_unconditional(const RawAddress& address); diff --git a/system/stack/gatt/gatt_api.cc b/system/stack/gatt/gatt_api.cc index b98aa2e5e2b..adfe28d97b9 100644 --- a/system/stack/gatt/gatt_api.cc +++ b/system/stack/gatt/gatt_api.cc @@ -63,7 +63,9 @@ tGATT_HDL_LIST_ELEM& gatt_add_an_item_to_list(uint16_t s_handle) { auto lst_ptr = gatt_cb.hdl_list_info; auto it = lst_ptr->begin(); for (; it != lst_ptr->end(); it++) { - if (s_handle > it->asgn_range.s_handle) break; + if (s_handle > it->asgn_range.s_handle) { + break; + } } auto rit = lst_ptr->emplace(it); @@ -103,20 +105,21 @@ static uint16_t compute_service_size(btgatt_db_element_t* service, int count) { int db_size = 0; btgatt_db_element_t* el = service; - for (int i = 0; i < count; i++, el++) - if (el->type == BTGATT_DB_PRIMARY_SERVICE || - el->type == BTGATT_DB_SECONDARY_SERVICE || - el->type == BTGATT_DB_DESCRIPTOR || - el->type == BTGATT_DB_INCLUDED_SERVICE) { + for (int i = 0; i < count; i++, el++) { + if (el->type == BTGATT_DB_PRIMARY_SERVICE || el->type == BTGATT_DB_SECONDARY_SERVICE || + el->type == BTGATT_DB_DESCRIPTOR || el->type == BTGATT_DB_INCLUDED_SERVICE) { db_size += 1; } else if (el->type == BTGATT_DB_CHARACTERISTIC) { db_size += 2; // if present, Characteristic Extended Properties takes one handle - if (el->properties & GATT_CHAR_PROP_BIT_EXT_PROP) db_size++; + if (el->properties & GATT_CHAR_PROP_BIT_EXT_PROP) { + db_size++; + } } else { log::error("Unknown element type: {}", el->type); } + } return db_size; } @@ -147,7 +150,9 @@ static void gatt_update_for_database_change() { uint8_t i = 0; for (i = 0; i < GATT_MAX_PHY_CHANNEL; i++) { tGATT_TCB& tcb = gatt_cb.tcb[i]; - if (tcb.in_use) gatt_sr_update_cl_status(tcb, /* chg_aware= */ false); + if (tcb.in_use) { + gatt_sr_update_cl_status(tcb, /* chg_aware= */ false); + } } } @@ -166,8 +171,7 @@ static void gatt_update_for_database_change() { * on error error status is returned. * ******************************************************************************/ -tGATT_STATUS GATTS_AddService(tGATT_IF gatt_if, btgatt_db_element_t* service, - int count) { +tGATT_STATUS GATTS_AddService(tGATT_IF gatt_if, btgatt_db_element_t* service, int count) { uint16_t s_hdl = 0; bool save_hdl = false; tGATT_REG* p_reg = gatt_get_regcb(gatt_if); @@ -199,8 +203,9 @@ tGATT_STATUS GATTS_AddService(tGATT_IF gatt_if, btgatt_db_element_t* service, s_hdl = gatt_cb.hdl_list_info->front().asgn_range.e_handle + 1; } - if (s_hdl < gatt_cb.hdl_cfg.app_start_hdl) + if (s_hdl < gatt_cb.hdl_cfg.app_start_hdl) { s_hdl = gatt_cb.hdl_cfg.app_start_hdl; + } save_hdl = true; } @@ -219,16 +224,16 @@ tGATT_STATUS GATTS_AddService(tGATT_IF gatt_if, btgatt_db_element_t* service, list.asgn_range.is_primary = is_pri; if (save_hdl) { - if (gatt_cb.cb_info.p_nv_save_callback) + if (gatt_cb.cb_info.p_nv_save_callback) { (*gatt_cb.cb_info.p_nv_save_callback)(true, &list.asgn_range); + } } gatts_init_service_db(list.svc_db, svc_uuid, is_pri, s_hdl, num_handles); - log::verbose( - "handles needed={}, s_hdl=0x{:x}, e_hdl=0x{:x}, uuid={}, is_primary={}", - num_handles, list.asgn_range.s_handle, list.asgn_range.e_handle, - list.asgn_range.svc_uuid, list.asgn_range.is_primary); + log::verbose("handles needed={}, s_hdl=0x{:x}, e_hdl=0x{:x}, uuid={}, is_primary={}", num_handles, + list.asgn_range.s_handle, list.asgn_range.e_handle, list.asgn_range.svc_uuid, + list.asgn_range.is_primary); service->attribute_handle = s_hdl; @@ -242,21 +247,21 @@ tGATT_STATUS GATTS_AddService(tGATT_IF gatt_if, btgatt_db_element_t* service, !(el->permissions & GATT_WRITE_SIGNED_PERM)) || ((el->permissions & GATT_WRITE_SIGNED_PERM) && !(el->properties & GATT_CHAR_PROP_BIT_AUTH))) { - log::verbose("Invalid configuration property=0x{:x}, perm=0x{:x}", - el->properties, el->permissions); + log::verbose("Invalid configuration property=0x{:x}, perm=0x{:x}", el->properties, + el->permissions); return GATT_INTERNAL_ERROR; } if (is_gatt_attr_type(uuid)) { log::error( - "attempt to add characteristic with UUID equal to GATT Attribute " - "Type {}", - uuid); + "attempt to add characteristic with UUID equal to GATT Attribute " + "Type {}", + uuid); return GATT_INTERNAL_ERROR; } - el->attribute_handle = gatts_add_characteristic( - list.svc_db, el->permissions, el->properties, uuid); + el->attribute_handle = + gatts_add_characteristic(list.svc_db, el->permissions, el->properties, uuid); // add characteristic extended properties descriptor if needed if (el->properties & GATT_CHAR_PROP_BIT_EXT_PROP) { @@ -266,14 +271,13 @@ tGATT_STATUS GATTS_AddService(tGATT_IF gatt_if, btgatt_db_element_t* service, } else if (el->type == BTGATT_DB_DESCRIPTOR) { if (is_gatt_attr_type(uuid)) { log::error( - "attempt to add descriptor with UUID equal to GATT Attribute Type " - "{}", - uuid); + "attempt to add descriptor with UUID equal to GATT Attribute Type " + "{}", + uuid); return GATT_INTERNAL_ERROR; } - el->attribute_handle = - gatts_add_char_descr(list.svc_db, el->permissions, uuid); + el->attribute_handle = gatts_add_char_descr(list.svc_db, el->permissions, uuid); } else if (el->type == BTGATT_DB_INCLUDED_SERVICE) { tGATT_HDL_LIST_ELEM* p_incl_decl; p_incl_decl = gatt_find_hdl_buffer_by_handle(el->attribute_handle); @@ -283,8 +287,8 @@ tGATT_STATUS GATTS_AddService(tGATT_IF gatt_if, btgatt_db_element_t* service, } el->attribute_handle = gatts_add_included_service( - list.svc_db, p_incl_decl->asgn_range.s_handle, - p_incl_decl->asgn_range.e_handle, p_incl_decl->asgn_range.svc_uuid); + list.svc_db, p_incl_decl->asgn_range.s_handle, p_incl_decl->asgn_range.e_handle, + p_incl_decl->asgn_range.svc_uuid); } } @@ -296,7 +300,9 @@ tGATT_STATUS GATTS_AddService(tGATT_IF gatt_if, btgatt_db_element_t* service, auto lst_ptr = gatt_cb.srv_list_info; auto it = lst_ptr->begin(); for (; it != lst_ptr->end(); it++) { - if (list.asgn_range.s_handle < it->s_hdl) break; + if (list.asgn_range.s_handle < it->s_hdl) { + break; + } } auto rit = lst_ptr->emplace(it); @@ -308,8 +314,7 @@ tGATT_STATUS GATTS_AddService(tGATT_IF gatt_if, btgatt_db_element_t* service, elem.is_primary = list.asgn_range.is_primary; elem.app_uuid = list.asgn_range.app_uuid128; - elem.type = list.asgn_range.is_primary ? GATT_UUID_PRI_SERVICE - : GATT_UUID_SEC_SERVICE; + elem.type = list.asgn_range.is_primary ? GATT_UUID_PRI_SERVICE : GATT_UUID_SEC_SERVICE; if (elem.type == GATT_UUID_PRI_SERVICE && gatt_cb.over_br_enabled) { Uuid* p_uuid = gatts_get_service_uuid(elem.p_db); @@ -325,9 +330,8 @@ tGATT_STATUS GATTS_AddService(tGATT_IF gatt_if, btgatt_db_element_t* service, gatt_update_last_srv_info(); - log::verbose( - "allocated el s_hdl=0x{:x}, e_hdl=0x{:x}, type=0x{:x}, sdp_hdl=0x{:x}", - elem.s_hdl, elem.e_hdl, elem.type, elem.sdp_handle); + log::verbose("allocated el s_hdl=0x{:x}, e_hdl=0x{:x}, type=0x{:x}, sdp_hdl=0x{:x}", elem.s_hdl, + elem.e_hdl, elem.type, elem.sdp_handle); gatt_update_for_database_change(); gatt_proc_srv_chg(); @@ -335,13 +339,12 @@ tGATT_STATUS GATTS_AddService(tGATT_IF gatt_if, btgatt_db_element_t* service, return GATT_SERVICE_STARTED; } -bool is_active_service(const Uuid& app_uuid128, Uuid* p_svc_uuid, - uint16_t start_handle) { +bool is_active_service(const Uuid& app_uuid128, Uuid* p_svc_uuid, uint16_t start_handle) { for (auto& info : *gatt_cb.srv_list_info) { Uuid* p_this_uuid = gatts_get_service_uuid(info.p_db); - if (p_this_uuid && app_uuid128 == info.app_uuid && - *p_svc_uuid == *p_this_uuid && (start_handle == info.s_hdl)) { + if (p_this_uuid && app_uuid128 == info.app_uuid && *p_svc_uuid == *p_this_uuid && + (start_handle == info.s_hdl)) { log::error("Active Service Found: {}", *p_svc_uuid); return true; } @@ -363,8 +366,7 @@ bool is_active_service(const Uuid& app_uuid128, Uuid* p_svc_uuid, * was not found. * ******************************************************************************/ -bool GATTS_DeleteService(tGATT_IF gatt_if, Uuid* p_svc_uuid, - uint16_t svc_inst) { +bool GATTS_DeleteService(tGATT_IF gatt_if, Uuid* p_svc_uuid, uint16_t svc_inst) { log::verbose(""); tGATT_REG* p_reg = gatt_get_regcb(gatt_if); @@ -373,8 +375,7 @@ bool GATTS_DeleteService(tGATT_IF gatt_if, Uuid* p_svc_uuid, return false; } - auto it = - gatt_find_hdl_buffer_by_app_id(p_reg->app_uuid128, p_svc_uuid, svc_inst); + auto it = gatt_find_hdl_buffer_by_app_id(p_reg->app_uuid128, p_svc_uuid, svc_inst); if (it == gatt_cb.hdl_list_info->end()) { log::error("No Service found"); return false; @@ -387,12 +388,13 @@ bool GATTS_DeleteService(tGATT_IF gatt_if, Uuid* p_svc_uuid, gatt_update_for_database_change(); gatt_proc_srv_chg(); - log::verbose("released handles s_hdl=0x{:x}, e_hdl=0x{:x}", - it->asgn_range.s_handle, it->asgn_range.e_handle); + log::verbose("released handles s_hdl=0x{:x}, e_hdl=0x{:x}", it->asgn_range.s_handle, + it->asgn_range.e_handle); if ((it->asgn_range.s_handle >= gatt_cb.hdl_cfg.app_start_hdl) && - gatt_cb.cb_info.p_nv_save_callback) + gatt_cb.cb_info.p_nv_save_callback) { (*gatt_cb.cb_info.p_nv_save_callback)(false, &it->asgn_range); + } gatt_cb.hdl_list_info->erase(it); return true; @@ -443,8 +445,8 @@ void GATTS_StopService(uint16_t service_handle) { * code. * ******************************************************************************/ -tGATT_STATUS GATTS_HandleValueIndication(uint16_t conn_id, uint16_t attr_handle, - uint16_t val_len, uint8_t* p_val) { +tGATT_STATUS GATTS_HandleValueIndication(uint16_t conn_id, uint16_t attr_handle, uint16_t val_len, + uint8_t* p_val) { tGATT_IF gatt_if = GATT_GET_GATT_IF(conn_id); uint8_t tcb_idx = GATT_GET_TCB_IDX(conn_id); tGATT_REG* p_reg = gatt_get_regcb(gatt_if); @@ -456,7 +458,9 @@ tGATT_STATUS GATTS_HandleValueIndication(uint16_t conn_id, uint16_t attr_handle, return (tGATT_STATUS)GATT_INVALID_CONN_ID; } - if (!GATT_HANDLE_IS_VALID(attr_handle)) return GATT_ILLEGAL_PARAMETER; + if (!GATT_HANDLE_IS_VALID(attr_handle)) { + return GATT_ILLEGAL_PARAMETER; + } tGATT_VALUE indication; indication.conn_id = conn_id; @@ -468,8 +472,8 @@ tGATT_STATUS GATTS_HandleValueIndication(uint16_t conn_id, uint16_t attr_handle, uint16_t* indicate_handle_p = NULL; uint16_t cid; - if (!gatt_tcb_get_cid_available_for_indication(p_tcb, p_reg->eatt_support, - &indicate_handle_p, &cid)) { + if (!gatt_tcb_get_cid_available_for_indication(p_tcb, p_reg->eatt_support, &indicate_handle_p, + &cid)) { log::verbose("Add a pending indication"); gatt_add_pending_ind(p_tcb, &indication); return GATT_SUCCESS; @@ -479,9 +483,10 @@ tGATT_STATUS GATTS_HandleValueIndication(uint16_t conn_id, uint16_t attr_handle, gatt_sr_msg.attr_value = indication; uint16_t payload_size = gatt_tcb_get_payload_size(*p_tcb, cid); - BT_HDR* p_msg = attp_build_sr_msg(*p_tcb, GATT_HANDLE_VALUE_IND, &gatt_sr_msg, - payload_size); - if (!p_msg) return GATT_NO_RESOURCES; + BT_HDR* p_msg = attp_build_sr_msg(*p_tcb, GATT_HANDLE_VALUE_IND, &gatt_sr_msg, payload_size); + if (!p_msg) { + return GATT_NO_RESOURCES; + } tGATT_STATUS cmd_status = attp_send_sr_msg(*p_tcb, cid, p_msg); if (cmd_status == GATT_SUCCESS || cmd_status == GATT_CONGESTED) { @@ -493,7 +498,7 @@ tGATT_STATUS GATTS_HandleValueIndication(uint16_t conn_id, uint16_t attr_handle, #if (GATT_UPPER_TESTER_MULT_VARIABLE_LENGTH_NOTIF == TRUE) static tGATT_STATUS GATTS_HandleMultipleValueNotification( - tGATT_TCB* p_tcb, std::vector gatt_notif_vector) { + tGATT_TCB* p_tcb, std::vector gatt_notif_vector) { log::info(""); uint16_t cid = gatt_tcb_get_att_cid(*p_tcb, true /* eatt support */); @@ -501,8 +506,7 @@ static tGATT_STATUS GATTS_HandleMultipleValueNotification( /* TODO Handle too big packet size here. Not needed now for testing. */ /* Just build the message. */ - BT_HDR* p_buf = - (BT_HDR*)osi_malloc(sizeof(BT_HDR) + payload_size + L2CAP_MIN_OFFSET); + BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + payload_size + L2CAP_MIN_OFFSET); uint8_t* p = (uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET; UINT8_TO_STREAM(p, GATT_HANDLE_MULTI_VALUE_NOTIF); @@ -538,9 +542,8 @@ static tGATT_STATUS GATTS_HandleMultipleValueNotification( * Returns GATT_SUCCESS if successfully sent; otherwise error code. * ******************************************************************************/ -tGATT_STATUS GATTS_HandleValueNotification(uint16_t conn_id, - uint16_t attr_handle, - uint16_t val_len, uint8_t* p_val) { +tGATT_STATUS GATTS_HandleValueNotification(uint16_t conn_id, uint16_t attr_handle, uint16_t val_len, + uint8_t* p_val) { tGATT_VALUE notif; tGATT_IF gatt_if = GATT_GET_GATT_IF(conn_id); uint8_t tcb_idx = GATT_GET_TCB_IDX(conn_id); @@ -595,8 +598,7 @@ tGATT_STATUS GATTS_HandleValueNotification(uint16_t conn_id, return GATTS_HandleMultipleValueNotification(p_tcb, gatt_notif_vector); } - log::error("PTS Mode: Invalid tcb_idx: {}, cached_tcb_idx: {}", tcb_idx, - cached_tcb_idx); + log::error("PTS Mode: Invalid tcb_idx: {}, cached_tcb_idx: {}", tcb_idx, cached_tcb_idx); } #endif @@ -612,8 +614,7 @@ tGATT_STATUS GATTS_HandleValueNotification(uint16_t conn_id, uint16_t cid = gatt_tcb_get_att_cid(*p_tcb, p_reg->eatt_support); uint16_t payload_size = gatt_tcb_get_payload_size(*p_tcb, cid); - BT_HDR* p_buf = attp_build_sr_msg(*p_tcb, GATT_HANDLE_VALUE_NOTIF, - &gatt_sr_msg, payload_size); + BT_HDR* p_buf = attp_build_sr_msg(*p_tcb, GATT_HANDLE_VALUE_NOTIF, &gatt_sr_msg, payload_size); if (p_buf != NULL) { cmd_sent = attp_send_sr_msg(*p_tcb, cid, p_buf); @@ -637,15 +638,15 @@ tGATT_STATUS GATTS_HandleValueNotification(uint16_t conn_id, * Returns GATT_SUCCESS if successfully sent; otherwise error code. * ******************************************************************************/ -tGATT_STATUS GATTS_SendRsp(uint16_t conn_id, uint32_t trans_id, - tGATT_STATUS status, tGATTS_RSP* p_msg) { +tGATT_STATUS GATTS_SendRsp(uint16_t conn_id, uint32_t trans_id, tGATT_STATUS status, + tGATTS_RSP* p_msg) { tGATT_IF gatt_if = GATT_GET_GATT_IF(conn_id); uint8_t tcb_idx = GATT_GET_TCB_IDX(conn_id); tGATT_REG* p_reg = gatt_get_regcb(gatt_if); tGATT_TCB* p_tcb = gatt_get_tcb_by_idx(tcb_idx); - log::verbose("conn_id=0x{:x}, trans_id=0x{:x}, status=0x{:x}", conn_id, - trans_id, static_cast(status)); + log::verbose("conn_id=0x{:x}, trans_id=0x{:x}, status=0x{:x}", conn_id, trans_id, + static_cast(status)); if ((p_reg == NULL) || (p_tcb == NULL)) { log::error("Unknown conn_id=0x{:x}", conn_id); @@ -656,12 +657,12 @@ tGATT_STATUS GATTS_SendRsp(uint16_t conn_id, uint32_t trans_id, if (!sr_res_p) { log::error("conn_id=0x{:x} waiting for other op_code", conn_id); - return (GATT_WRONG_STATE); + return GATT_WRONG_STATE; } /* Process App response */ - return gatt_sr_process_app_rsp(*p_tcb, gatt_if, trans_id, sr_res_p->op_code, - status, p_msg, sr_res_p); + return gatt_sr_process_app_rsp(*p_tcb, gatt_if, trans_id, sr_res_p->op_code, status, p_msg, + sr_res_p); } /******************************************************************************/ @@ -695,10 +696,9 @@ tGATT_STATUS GATTC_ConfigureMTU(uint16_t conn_id, uint16_t mtu) { if ((p_tcb == NULL) || (p_reg == NULL) || (mtu < GATT_DEF_BLE_MTU_SIZE) || (mtu > GATT_MAX_MTU_SIZE)) { log::warn( - "Unable to configure ATT mtu size illegal parameter conn_id:{} mtu:{} " - "tcb:{} reg:{}", - conn_id, mtu, (p_tcb == nullptr) ? "BAD" : "ok", - (p_reg == nullptr) ? "BAD" : "ok"); + "Unable to configure ATT mtu size illegal parameter conn_id:{} mtu:{} " + "tcb:{} reg:{}", + conn_id, mtu, (p_tcb == nullptr) ? "BAD" : "ok", (p_reg == nullptr) ? "BAD" : "ok"); return GATT_ILLEGAL_PARAMETER; } @@ -725,11 +725,10 @@ tGATT_STATUS GATTC_ConfigureMTU(uint16_t conn_id, uint16_t mtu) { * default MTU in the request. */ gatt_cl_msg.mtu = gatt_get_local_mtu(); - log::info("Configuring ATT mtu size conn_id:{} mtu:{} user mtu {}", conn_id, - gatt_cl_msg.mtu, mtu); + log::info("Configuring ATT mtu size conn_id:{} mtu:{} user mtu {}", conn_id, gatt_cl_msg.mtu, + mtu); - auto result = - attp_send_cl_msg(*p_clcb->p_tcb, p_clcb, GATT_REQ_MTU, &gatt_cl_msg); + auto result = attp_send_cl_msg(*p_clcb->p_tcb, p_clcb, GATT_REQ_MTU, &gatt_cl_msg); if (result == GATT_SUCCESS) { p_clcb->p_tcb->pending_user_mtu_exchange_value = mtu; } @@ -763,8 +762,7 @@ tGATT_STATUS GATTC_ConfigureMTU(uint16_t conn_id, uint16_t mtu) { * ******************************************************************************/ tGATTC_TryMtuRequestResult GATTC_TryMtuRequest(const RawAddress& remote_bda, - tBT_TRANSPORT transport, - uint16_t conn_id, + tBT_TRANSPORT transport, uint16_t conn_id, uint16_t* current_mtu) { log::info("{} conn_id=0x{:04x}", remote_bda, conn_id); *current_mtu = GATT_DEF_BLE_MTU_SIZE; @@ -812,8 +810,7 @@ tGATTC_TryMtuRequestResult GATTC_TryMtuRequest(const RawAddress& remote_bda, * user_mtu: user request mtu * ******************************************************************************/ -void GATTC_UpdateUserAttMtuIfNeeded(const RawAddress& remote_bda, - tBT_TRANSPORT transport, +void GATTC_UpdateUserAttMtuIfNeeded(const RawAddress& remote_bda, tBT_TRANSPORT transport, uint16_t user_mtu) { log::info("{}, mtu={}", remote_bda, user_mtu); tGATT_TCB* p_tcb = gatt_find_tcb_by_addr(remote_bda, transport); @@ -822,8 +819,8 @@ void GATTC_UpdateUserAttMtuIfNeeded(const RawAddress& remote_bda, return; } - log::info("{}, current mtu: {}, max_user_mtu:{}, user_mtu: {}", remote_bda, - p_tcb->payload_size, p_tcb->max_user_mtu, user_mtu); + log::info("{}, current mtu: {}, max_user_mtu:{}, user_mtu: {}", remote_bda, p_tcb->payload_size, + p_tcb->max_user_mtu, user_mtu); if (p_tcb->payload_size < user_mtu) { log::info("User requested more than what GATT can handle. Trim it."); @@ -839,7 +836,7 @@ void GATTC_UpdateUserAttMtuIfNeeded(const RawAddress& remote_bda, } std::list GATTC_GetAndRemoveListOfConnIdsWaitingForMtuRequest( - const RawAddress& remote_bda) { + const RawAddress& remote_bda) { std::list result = std::list(); tGATT_TCB* p_tcb = gatt_find_tcb_by_addr(remote_bda, BT_TRANSPORT_LE); @@ -867,37 +864,34 @@ std::list GATTC_GetAndRemoveListOfConnIdsWaitingForMtuRequest( * Returns GATT_SUCCESS if command received/sent successfully. * ******************************************************************************/ -tGATT_STATUS GATTC_Discover(uint16_t conn_id, tGATT_DISC_TYPE disc_type, - uint16_t start_handle, uint16_t end_handle, - const Uuid& uuid) { +tGATT_STATUS GATTC_Discover(uint16_t conn_id, tGATT_DISC_TYPE disc_type, uint16_t start_handle, + uint16_t end_handle, const Uuid& uuid) { tGATT_IF gatt_if = GATT_GET_GATT_IF(conn_id); uint8_t tcb_idx = GATT_GET_TCB_IDX(conn_id); tGATT_TCB* p_tcb = gatt_get_tcb_by_idx(tcb_idx); tGATT_REG* p_reg = gatt_get_regcb(gatt_if); if ((p_tcb == NULL) || (p_reg == NULL) || (disc_type >= GATT_DISC_MAX)) { - log::error("Illegal param: disc_type={} conn_id=0x{:x}", disc_type, - conn_id); + log::error("Illegal param: disc_type={} conn_id=0x{:x}", disc_type, conn_id); return GATT_ILLEGAL_PARAMETER; } - if (!GATT_HANDLE_IS_VALID(start_handle) || - !GATT_HANDLE_IS_VALID(end_handle) || + if (!GATT_HANDLE_IS_VALID(start_handle) || !GATT_HANDLE_IS_VALID(end_handle) || /* search by type does not have a valid UUID param */ (disc_type == GATT_DISC_SRVC_BY_UUID && uuid.IsEmpty())) { log::warn( - "Illegal parameter conn_id=0x{:x}, disc_type={}, s_handle=0x{:x}, " - "e_handle=0x{:x}", - conn_id, disc_type, start_handle, end_handle); + "Illegal parameter conn_id=0x{:x}, disc_type={}, s_handle=0x{:x}, " + "e_handle=0x{:x}", + conn_id, disc_type, start_handle, end_handle); return GATT_ILLEGAL_PARAMETER; } tGATT_CLCB* p_clcb = gatt_clcb_alloc(conn_id); if (!p_clcb) { log::warn( - "No resources conn_id=0x{:x}, disc_type={}, s_handle=0x{:x}, " - "e_handle=0x{:x}", - conn_id, disc_type, start_handle, end_handle); + "No resources conn_id=0x{:x}, disc_type={}, s_handle=0x{:x}, " + "e_handle=0x{:x}", + conn_id, disc_type, start_handle, end_handle); return GATT_NO_RESOURCES; } @@ -907,17 +901,16 @@ tGATT_STATUS GATTC_Discover(uint16_t conn_id, tGATT_DISC_TYPE disc_type, p_clcb->e_handle = end_handle; p_clcb->uuid = uuid; - log::info("conn_id=0x{:x}, disc_type={}, s_handle=0x{:x}, e_handle=0x{:x}", - conn_id, disc_type, start_handle, end_handle); + log::info("conn_id=0x{:x}, disc_type={}, s_handle=0x{:x}, e_handle=0x{:x}", conn_id, disc_type, + start_handle, end_handle); gatt_act_discovery(p_clcb); return GATT_SUCCESS; } -tGATT_STATUS GATTC_Discover(uint16_t conn_id, tGATT_DISC_TYPE disc_type, - uint16_t start_handle, uint16_t end_handle) { - return GATTC_Discover(conn_id, disc_type, start_handle, end_handle, - Uuid::kEmpty); +tGATT_STATUS GATTC_Discover(uint16_t conn_id, tGATT_DISC_TYPE disc_type, uint16_t start_handle, + uint16_t end_handle) { + return GATTC_Discover(conn_id, disc_type, start_handle, end_handle, Uuid::kEmpty); } /******************************************************************************* @@ -934,8 +927,7 @@ tGATT_STATUS GATTC_Discover(uint16_t conn_id, tGATT_DISC_TYPE disc_type, * Returns GATT_SUCCESS if command started successfully. * ******************************************************************************/ -tGATT_STATUS GATTC_Read(uint16_t conn_id, tGATT_READ_TYPE type, - tGATT_READ_PARAM* p_read) { +tGATT_STATUS GATTC_Read(uint16_t conn_id, tGATT_READ_TYPE type, tGATT_READ_PARAM* p_read) { tGATT_IF gatt_if = GATT_GET_GATT_IF(conn_id); uint8_t tcb_idx = GATT_GET_TCB_IDX(conn_id); tGATT_TCB* p_tcb = gatt_get_tcb_by_idx(tcb_idx); @@ -954,7 +946,9 @@ tGATT_STATUS GATTC_Read(uint16_t conn_id, tGATT_READ_TYPE type, } tGATT_CLCB* p_clcb = gatt_clcb_alloc(conn_id); - if (!p_clcb) return GATT_NO_RESOURCES; + if (!p_clcb) { + return GATT_NO_RESOURCES; + } p_clcb->operation = GATTC_OPTYPE_READ; p_clcb->op_subtype = type; @@ -973,8 +967,7 @@ tGATT_STATUS GATTC_Read(uint16_t conn_id, tGATT_READ_TYPE type, case GATT_READ_MULTIPLE_VAR_LEN: { p_clcb->s_handle = 0; /* copy multiple handles in CB */ - tGATT_READ_MULTI* p_read_multi = - (tGATT_READ_MULTI*)osi_malloc(sizeof(tGATT_READ_MULTI)); + tGATT_READ_MULTI* p_read_multi = (tGATT_READ_MULTI*)osi_malloc(sizeof(tGATT_READ_MULTI)); p_clcb->p_attr_buf = (uint8_t*)p_read_multi; memcpy(p_read_multi, &p_read->read_multiple, sizeof(tGATT_READ_MULTI)); break; @@ -991,8 +984,7 @@ tGATT_STATUS GATTC_Read(uint16_t conn_id, tGATT_READ_TYPE type, } else if (cached_tcb_idx == tcb_idx) { log::info("Upper tester: Read multiple - second read"); cached_tcb_idx = -1; - tGATT_READ_MULTI* p_read_multi = - (tGATT_READ_MULTI*)osi_malloc(sizeof(tGATT_READ_MULTI)); + tGATT_READ_MULTI* p_read_multi = (tGATT_READ_MULTI*)osi_malloc(sizeof(tGATT_READ_MULTI)); p_read_multi->num_handles = 2; p_read_multi->handles[0] = cached_read_handle; p_read_multi->handles[1] = p_read->by_handle.handle; @@ -1022,8 +1014,9 @@ tGATT_STATUS GATTC_Read(uint16_t conn_id, tGATT_READ_TYPE type, } /* start security check */ - if (gatt_security_check_start(p_clcb)) + if (gatt_security_check_start(p_clcb)) { p_tcb->pending_enc_clcb.push_back(p_clcb); + } return GATT_SUCCESS; } @@ -1041,22 +1034,22 @@ tGATT_STATUS GATTC_Read(uint16_t conn_id, tGATT_READ_TYPE type, * Returns GATT_SUCCESS if command started successfully. * ******************************************************************************/ -tGATT_STATUS GATTC_Write(uint16_t conn_id, tGATT_WRITE_TYPE type, - tGATT_VALUE* p_write) { +tGATT_STATUS GATTC_Write(uint16_t conn_id, tGATT_WRITE_TYPE type, tGATT_VALUE* p_write) { tGATT_IF gatt_if = GATT_GET_GATT_IF(conn_id); uint8_t tcb_idx = GATT_GET_TCB_IDX(conn_id); tGATT_TCB* p_tcb = gatt_get_tcb_by_idx(tcb_idx); tGATT_REG* p_reg = gatt_get_regcb(gatt_if); if ((p_tcb == NULL) || (p_reg == NULL) || (p_write == NULL) || - ((type != GATT_WRITE) && (type != GATT_WRITE_PREPARE) && - (type != GATT_WRITE_NO_RSP))) { + ((type != GATT_WRITE) && (type != GATT_WRITE_PREPARE) && (type != GATT_WRITE_NO_RSP))) { log::error("Illegal param: conn_id=0x{:x}, type=0x{:x}", conn_id, type); return GATT_ILLEGAL_PARAMETER; } tGATT_CLCB* p_clcb = gatt_clcb_alloc(conn_id); - if (!p_clcb) return GATT_NO_RESOURCES; + if (!p_clcb) { + return GATT_NO_RESOURCES; + } p_clcb->operation = GATTC_OPTYPE_WRITE; p_clcb->op_subtype = type; @@ -1071,8 +1064,9 @@ tGATT_STATUS GATTC_Write(uint16_t conn_id, tGATT_WRITE_TYPE type, p->offset = 0; } - if (gatt_security_check_start(p_clcb)) + if (gatt_security_check_start(p_clcb)) { p_tcb->pending_enc_clcb.push_back(p_clcb); + } return GATT_SUCCESS; } @@ -1104,11 +1098,12 @@ tGATT_STATUS GATTC_ExecuteWrite(uint16_t conn_id, bool is_execute) { } tGATT_CLCB* p_clcb = gatt_clcb_alloc(conn_id); - if (!p_clcb) return GATT_NO_RESOURCES; + if (!p_clcb) { + return GATT_NO_RESOURCES; + } p_clcb->operation = GATTC_OPTYPE_EXE_WRITE; - tGATT_EXEC_FLAG flag = - is_execute ? GATT_PREP_WRITE_EXEC : GATT_PREP_WRITE_CANCEL; + tGATT_EXEC_FLAG flag = is_execute ? GATT_PREP_WRITE_EXEC : GATT_PREP_WRITE_CANCEL; gatt_send_queue_write_cancel(*p_clcb->p_tcb, p_clcb, flag); return GATT_SUCCESS; } @@ -1136,13 +1131,11 @@ tGATT_STATUS GATTC_SendHandleValueConfirm(uint16_t conn_id, uint16_t cid) { } if (p_tcb->ind_count == 0) { - log::info("conn_id: 0x{:04x} ignored not waiting for indication ack", - conn_id); + log::info("conn_id: 0x{:04x} ignored not waiting for indication ack", conn_id); return GATT_SUCCESS; } - log::info("Received confirmation, ind_count= {}, sending confirmation", - p_tcb->ind_count); + log::info("Received confirmation, ind_count= {}, sending confirmation", p_tcb->ind_count); /* Just wait for first confirmation.*/ p_tcb->ind_count = 0; @@ -1176,8 +1169,8 @@ tGATT_STATUS GATTC_SendHandleValueConfirm(uint16_t conn_id, uint16_t cid) { * Returns void * ******************************************************************************/ -void GATT_SetIdleTimeout(const RawAddress& bd_addr, uint16_t idle_tout, - tBT_TRANSPORT transport, bool is_active) { +void GATT_SetIdleTimeout(const RawAddress& bd_addr, uint16_t idle_tout, tBT_TRANSPORT transport, + bool is_active) { bool status = false; tGATT_TCB* p_tcb = gatt_find_tcb_by_addr(bd_addr, transport); @@ -1189,17 +1182,16 @@ void GATT_SetIdleTimeout(const RawAddress& bd_addr, uint16_t idle_tout, } if (idle_tout == GATT_LINK_IDLE_TIMEOUT_WHEN_NO_APP) { - if (!L2CA_SetIdleTimeoutByBdAddr(p_tcb->peer_bda, - GATT_LINK_IDLE_TIMEOUT_WHEN_NO_APP, + if (!L2CA_SetIdleTimeoutByBdAddr(p_tcb->peer_bda, GATT_LINK_IDLE_TIMEOUT_WHEN_NO_APP, BT_TRANSPORT_LE)) { - log::warn("Unable to set L2CAP link idle timeout peer:{} transport:{}", - p_tcb->peer_bda, bt_transport_text(transport)); + log::warn("Unable to set L2CAP link idle timeout peer:{} transport:{}", p_tcb->peer_bda, + bt_transport_text(transport)); } } } - log::info("idle_timeout={}, is_active={}, status={} (1-OK 0-not performed)", - idle_tout, is_active, status); + log::info("idle_timeout={}, is_active={}, status={} (1-OK 0-not performed)", idle_tout, is_active, + status); } /******************************************************************************* @@ -1217,17 +1209,15 @@ void GATT_SetIdleTimeout(const RawAddress& bd_addr, uint16_t idle_tout, * with GATT * ******************************************************************************/ -tGATT_IF GATT_Register(const Uuid& app_uuid128, const std::string& name, - tGATT_CBACK* p_cb_info, bool eatt_support) { +tGATT_IF GATT_Register(const Uuid& app_uuid128, const std::string& name, tGATT_CBACK* p_cb_info, + bool eatt_support) { tGATT_REG* p_reg; uint8_t i_gatt_if = 0; tGATT_IF gatt_if = 0; - for (i_gatt_if = 0, p_reg = gatt_cb.cl_rcb; i_gatt_if < GATT_MAX_APPS; - i_gatt_if++, p_reg++) { + for (i_gatt_if = 0, p_reg = gatt_cb.cl_rcb; i_gatt_if < GATT_MAX_APPS; i_gatt_if++, p_reg++) { if (p_reg->in_use && p_reg->app_uuid128 == app_uuid128) { - log::error("Application already registered, uuid={}", - app_uuid128.ToString()); + log::error("Application already registered, uuid={}", app_uuid128.ToString()); return 0; } } @@ -1237,8 +1227,7 @@ tGATT_IF GATT_Register(const Uuid& app_uuid128, const std::string& name, eatt_support = true; } - for (i_gatt_if = 0, p_reg = gatt_cb.cl_rcb; i_gatt_if < GATT_MAX_APPS; - i_gatt_if++, p_reg++) { + for (i_gatt_if = 0, p_reg = gatt_cb.cl_rcb; i_gatt_if < GATT_MAX_APPS; i_gatt_if++, p_reg++) { if (!p_reg->in_use) { *p_reg = {}; i_gatt_if++; /* one based number */ @@ -1254,8 +1243,7 @@ tGATT_IF GATT_Register(const Uuid& app_uuid128, const std::string& name, } } - log::error("Unable to register GATT client, MAX client reached: {}", - GATT_MAX_APPS); + log::error("Unable to register GATT client, MAX client reached: {}", GATT_MAX_APPS); return 0; } @@ -1285,8 +1273,7 @@ void GATT_Deregister(tGATT_IF gatt_if) { other application deregistration need to be performed in an orderly fashion no check for now */ - for (auto it = gatt_cb.srv_list_info->begin(); - it != gatt_cb.srv_list_info->end();) { + for (auto it = gatt_cb.srv_list_info->begin(); it != gatt_cb.srv_list_info->end();) { if (it->gatt_if == gatt_if) { GATTS_StopService(it++->s_hdl); } else { @@ -1302,16 +1289,16 @@ void GATT_Deregister(tGATT_IF gatt_if) { tGATT_TCB* p_tcb; int i; for (i = 0, p_tcb = gatt_cb.tcb; i < GATT_MAX_PHY_CHANNEL; i++, p_tcb++) { - if (!p_tcb->in_use) continue; + if (!p_tcb->in_use) { + continue; + } if (gatt_get_ch_state(p_tcb) != GATT_CH_CLOSE) { gatt_update_app_use_link_flag(gatt_if, p_tcb, false, true); } - for (auto clcb_it = gatt_cb.clcb_queue.begin(); - clcb_it != gatt_cb.clcb_queue.end();) { - if ((clcb_it->p_reg->gatt_if == gatt_if) && - (clcb_it->p_tcb->tcb_idx == p_tcb->tcb_idx)) { + for (auto clcb_it = gatt_cb.clcb_queue.begin(); clcb_it != gatt_cb.clcb_queue.end();) { + if ((clcb_it->p_reg->gatt_if == gatt_if) && (clcb_it->p_tcb->tcb_idx == p_tcb->tcb_idx)) { alarm_cancel(clcb_it->gatt_rsp_timer_ent); gatt_clcb_invalidate(p_tcb, &(*clcb_it)); clcb_it = gatt_cb.clcb_queue.erase(clcb_it); @@ -1321,8 +1308,7 @@ void GATT_Deregister(tGATT_IF gatt_if) { } } - if (bluetooth::common::init_flags:: - use_unified_connection_manager_is_enabled()) { + if (bluetooth::common::init_flags::use_unified_connection_manager_is_enabled()) { bluetooth::connection::GetConnectionManager().remove_client(gatt_if); } else { connection_manager::on_app_deregistered(gatt_if); @@ -1357,16 +1343,13 @@ void GATT_StartIf(tGATT_IF gatt_if) { p_reg = gatt_get_regcb(gatt_if); if (p_reg != NULL) { start_idx = 0; - while ( - gatt_find_the_connected_bda(start_idx, bda, &found_idx, &transport)) { + while (gatt_find_the_connected_bda(start_idx, bda, &found_idx, &transport)) { p_tcb = gatt_find_tcb_by_addr(bda, transport); - log::info("GATT interface {} already has connected device {}", gatt_if, - bda); + log::info("GATT interface {} already has connected device {}", gatt_if, bda); if (p_reg->app_cb.p_conn_cb && p_tcb) { conn_id = GATT_CREATE_CONN_ID(p_tcb->tcb_idx, gatt_if); log::info("Invoking callback with connection id {}", conn_id); - (*p_reg->app_cb.p_conn_cb)(gatt_if, bda, conn_id, true, GATT_CONN_OK, - transport); + (*p_reg->app_cb.p_conn_cb)(gatt_if, bda, conn_id, true, GATT_CONN_OK, transport); } else { log::info("Skipping callback as none is registered"); } @@ -1391,18 +1374,15 @@ void GATT_StartIf(tGATT_IF gatt_if) { * failure. * ******************************************************************************/ -bool GATT_Connect(tGATT_IF gatt_if, const RawAddress& bd_addr, - tBTM_BLE_CONN_TYPE connection_type, tBT_TRANSPORT transport, - bool opportunistic) { +bool GATT_Connect(tGATT_IF gatt_if, const RawAddress& bd_addr, tBTM_BLE_CONN_TYPE connection_type, + tBT_TRANSPORT transport, bool opportunistic) { constexpr uint8_t kPhyLe1M = 0x01; // From the old controller shim. uint8_t phy = kPhyLe1M; - return GATT_Connect(gatt_if, bd_addr, connection_type, transport, - opportunistic, phy); + return GATT_Connect(gatt_if, bd_addr, connection_type, transport, opportunistic, phy); } -bool GATT_Connect(tGATT_IF gatt_if, const RawAddress& bd_addr, - tBLE_ADDR_TYPE addr_type, tBTM_BLE_CONN_TYPE connection_type, - tBT_TRANSPORT transport, bool opportunistic, +bool GATT_Connect(tGATT_IF gatt_if, const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type, + tBTM_BLE_CONN_TYPE connection_type, tBT_TRANSPORT transport, bool opportunistic, uint8_t initiating_phys) { /* Make sure app is registered */ tGATT_REG* p_reg = gatt_get_regcb(gatt_if); @@ -1414,8 +1394,7 @@ bool GATT_Connect(tGATT_IF gatt_if, const RawAddress& bd_addr, bool is_direct = (connection_type == BTM_BLE_DIRECT_CONNECTION); if (!is_direct && transport != BT_TRANSPORT_LE) { - log::warn("Unsupported transport for background connection gatt_if={}", - gatt_if); + log::warn("Unsupported transport for background connection gatt_if={}", gatt_if); return false; } @@ -1426,45 +1405,37 @@ bool GATT_Connect(tGATT_IF gatt_if, const RawAddress& bd_addr, bool ret = false; if (is_direct) { - log::debug("Starting direct connect gatt_if={} address={}", gatt_if, - bd_addr); + log::debug("Starting direct connect gatt_if={} address={}", gatt_if, bd_addr); bool tcb_exist = !!gatt_find_tcb_by_addr(bd_addr, transport); - if (!com::android::bluetooth::flags::gatt_reconnect_on_bt_on_fix() || - tcb_exist) { + if (!com::android::bluetooth::flags::gatt_reconnect_on_bt_on_fix() || tcb_exist) { /* Consider to remove gatt_act_connect at all */ - ret = gatt_act_connect(p_reg, bd_addr, addr_type, transport, - initiating_phys); + ret = gatt_act_connect(p_reg, bd_addr, addr_type, transport, initiating_phys); } else { log::verbose("Connecting without tcb address: {}", bd_addr); if (p_reg->direct_connect_request.count(bd_addr) == 0) { p_reg->direct_connect_request.insert(bd_addr); } else { - log::warn("{} already added to gatt_if {} direct conn list", bd_addr, - gatt_if); + log::warn("{} already added to gatt_if {} direct conn list", bd_addr, gatt_if); } ret = acl_create_le_connection_with_id(gatt_if, bd_addr, addr_type); } } else { - log::debug("Starting background connect gatt_if={} address={}", gatt_if, - bd_addr); + log::debug("Starting background connect gatt_if={} address={}", gatt_if, bd_addr); if (!BTM_Sec_AddressKnown(bd_addr)) { // RPA can rotate, causing address to "expire" in the background // connection list. RPA is allowed for direct connect, as such request // times out after 30 seconds - log::warn("Unable to add RPA {} to background connection gatt_if={}", - bd_addr, gatt_if); + log::warn("Unable to add RPA {} to background connection gatt_if={}", bd_addr, gatt_if); ret = false; } else { log::debug("Adding to background connect to device:{}", bd_addr); - if (bluetooth::common::init_flags:: - use_unified_connection_manager_is_enabled()) { + if (bluetooth::common::init_flags::use_unified_connection_manager_is_enabled()) { if (connection_type == BTM_BLE_BKG_CONNECT_ALLOW_LIST) { - bluetooth::connection::GetConnectionManager() - .add_background_connection( + bluetooth::connection::GetConnectionManager().add_background_connection( gatt_if, bluetooth::connection::ResolveRawAddress(bd_addr)); ret = true; // TODO(aryarahul): error handling } else { @@ -1474,9 +1445,7 @@ bool GATT_Connect(tGATT_IF gatt_if, const RawAddress& bd_addr, if (connection_type == BTM_BLE_BKG_CONNECT_ALLOW_LIST) { ret = connection_manager::background_connect_add(gatt_if, bd_addr); } else { - ret = - connection_manager::background_connect_targeted_announcement_add( - gatt_if, bd_addr); + ret = connection_manager::background_connect_targeted_announcement_add(gatt_if, bd_addr); } } } @@ -1498,20 +1467,17 @@ bool GATT_Connect(tGATT_IF gatt_if, const RawAddress& bd_addr, return ret; } -bool GATT_Connect(tGATT_IF gatt_if, const RawAddress& bd_addr, - tBLE_ADDR_TYPE addr_type, tBTM_BLE_CONN_TYPE connection_type, - tBT_TRANSPORT transport, bool opportunistic) { +bool GATT_Connect(tGATT_IF gatt_if, const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type, + tBTM_BLE_CONN_TYPE connection_type, tBT_TRANSPORT transport, bool opportunistic) { constexpr uint8_t kPhyLe1M = 0x01; // From the old controller shim. uint8_t phy = kPhyLe1M; - return GATT_Connect(gatt_if, bd_addr, addr_type, connection_type, transport, - opportunistic, phy); + return GATT_Connect(gatt_if, bd_addr, addr_type, connection_type, transport, opportunistic, phy); } -bool GATT_Connect(tGATT_IF gatt_if, const RawAddress& bd_addr, - tBTM_BLE_CONN_TYPE connection_type, tBT_TRANSPORT transport, - bool opportunistic, uint8_t initiating_phys) { - return GATT_Connect(gatt_if, bd_addr, BLE_ADDR_PUBLIC, connection_type, - transport, opportunistic, initiating_phys); +bool GATT_Connect(tGATT_IF gatt_if, const RawAddress& bd_addr, tBTM_BLE_CONN_TYPE connection_type, + tBT_TRANSPORT transport, bool opportunistic, uint8_t initiating_phys) { + return GATT_Connect(gatt_if, bd_addr, BLE_ADDR_PUBLIC, connection_type, transport, opportunistic, + initiating_phys); } /******************************************************************************* @@ -1529,8 +1495,7 @@ bool GATT_Connect(tGATT_IF gatt_if, const RawAddress& bd_addr, * Returns true if the connection started; false otherwise. * ******************************************************************************/ -bool GATT_CancelConnect(tGATT_IF gatt_if, const RawAddress& bd_addr, - bool is_direct) { +bool GATT_CancelConnect(tGATT_IF gatt_if, const RawAddress& bd_addr, bool is_direct) { log::info("gatt_if:{}, address: {}, direct:{}", gatt_if, bd_addr, is_direct); tGATT_REG* p_reg; @@ -1553,8 +1518,7 @@ bool GATT_CancelConnect(tGATT_IF gatt_if, const RawAddress& bd_addr, /* only LE connection can be cancelled */ tGATT_TCB* p_tcb = gatt_find_tcb_by_addr(bd_addr, BT_TRANSPORT_LE); if (p_tcb && !p_tcb->app_hold_link.empty()) { - for (auto it = p_tcb->app_hold_link.begin(); - it != p_tcb->app_hold_link.end();) { + for (auto it = p_tcb->app_hold_link.begin(); it != p_tcb->app_hold_link.end();) { auto next = std::next(it); // gatt_cancel_open modifies the app_hold_link. gatt_cancel_open(*it, bd_addr); @@ -1563,15 +1527,12 @@ bool GATT_CancelConnect(tGATT_IF gatt_if, const RawAddress& bd_addr, } } - if (bluetooth::common::init_flags:: - use_unified_connection_manager_is_enabled()) { - bluetooth::connection::GetConnectionManager() - .stop_all_connections_to_device( + if (bluetooth::common::init_flags::use_unified_connection_manager_is_enabled()) { + bluetooth::connection::GetConnectionManager().stop_all_connections_to_device( bluetooth::connection::ResolveRawAddress(bd_addr)); } else { if (!connection_manager::remove_unconditional(bd_addr)) { - log::error( - "no app associated with the bg device for unconditional removal"); + log::error("no app associated with the bg device for unconditional removal"); return false; } } @@ -1620,8 +1581,8 @@ tGATT_STATUS GATT_Disconnect(uint16_t conn_id) { * Returns true the logical link information is found for conn_id * ******************************************************************************/ -bool GATT_GetConnectionInfor(uint16_t conn_id, tGATT_IF* p_gatt_if, - RawAddress& bd_addr, tBT_TRANSPORT* p_transport) { +bool GATT_GetConnectionInfor(uint16_t conn_id, tGATT_IF* p_gatt_if, RawAddress& bd_addr, + tBT_TRANSPORT* p_transport) { tGATT_IF gatt_if = GATT_GET_GATT_IF(conn_id); tGATT_REG* p_reg = gatt_get_regcb(gatt_if); uint8_t tcb_idx = GATT_GET_TCB_IDX(conn_id); @@ -1629,7 +1590,9 @@ bool GATT_GetConnectionInfor(uint16_t conn_id, tGATT_IF* p_gatt_if, log::verbose("conn_id=0x{:x}", conn_id); - if (!p_tcb || !p_reg) return false; + if (!p_tcb || !p_reg) { + return false; + } bd_addr = p_tcb->peer_bda; *p_gatt_if = gatt_if; @@ -1652,8 +1615,8 @@ bool GATT_GetConnectionInfor(uint16_t conn_id, tGATT_IF* p_gatt_if, * Returns true the logical link is connected * ******************************************************************************/ -bool GATT_GetConnIdIfConnected(tGATT_IF gatt_if, const RawAddress& bd_addr, - uint16_t* p_conn_id, tBT_TRANSPORT transport) { +bool GATT_GetConnIdIfConnected(tGATT_IF gatt_if, const RawAddress& bd_addr, uint16_t* p_conn_id, + tBT_TRANSPORT transport) { tGATT_REG* p_reg = gatt_get_regcb(gatt_if); tGATT_TCB* p_tcb = gatt_find_tcb_by_addr(bd_addr, transport); bool status = false; @@ -1676,8 +1639,8 @@ static void gatt_bonded_check_add_address(const RawAddress& bda) { std::optional OVERRIDE_GATT_LOAD_BONDED = std::nullopt; static bool gatt_load_bonded_is_enabled() { - static const bool sGATT_LOAD_BONDED = bluetooth::os::GetSystemPropertyBool( - "bluetooth.gatt.load_bonded.enabled", false); + static const bool sGATT_LOAD_BONDED = + bluetooth::os::GetSystemPropertyBool("bluetooth.gatt.load_bonded.enabled", false); if (OVERRIDE_GATT_LOAD_BONDED.has_value()) { return OVERRIDE_GATT_LOAD_BONDED.value(); } diff --git a/system/stack/gatt/gatt_attr.cc b/system/stack/gatt/gatt_attr.cc index c9f175170be..d93ae51be18 100644 --- a/system/stack/gatt/gatt_attr.cc +++ b/system/stack/gatt/gatt_attr.cc @@ -53,10 +53,9 @@ using namespace bluetooth; #define BLE_GATT_CL_ANDROID_SUP_FEAT \ (BLE_GATT_CL_SUP_FEAT_EATT_BITMASK | BLE_GATT_CL_SUP_FEAT_MULTI_NOTIF_BITMASK) -using gatt_sr_supported_feat_cb = - base::OnceCallback; -using gatt_sirk_cb = base::OnceCallback; +using gatt_sr_supported_feat_cb = base::OnceCallback; +using gatt_sirk_cb = base::OnceCallback; typedef struct { uint16_t op_uuid; @@ -66,50 +65,43 @@ typedef struct { static std::map> OngoingOps; -static void gatt_request_cback(uint16_t conn_id, uint32_t trans_id, - uint8_t op_code, tGATTS_DATA* p_data); -static void gatt_connect_cback(tGATT_IF /* gatt_if */, const RawAddress& bda, - uint16_t conn_id, bool connected, - tGATT_DISCONN_REASON reason, +static void gatt_request_cback(uint16_t conn_id, uint32_t trans_id, uint8_t op_code, + tGATTS_DATA* p_data); +static void gatt_connect_cback(tGATT_IF /* gatt_if */, const RawAddress& bda, uint16_t conn_id, + bool connected, tGATT_DISCONN_REASON reason, tBT_TRANSPORT transport); static void gatt_disc_res_cback(uint16_t conn_id, tGATT_DISC_TYPE disc_type, tGATT_DISC_RES* p_data); -static void gatt_disc_cmpl_cback(uint16_t conn_id, tGATT_DISC_TYPE disc_type, - tGATT_STATUS status); -static void gatt_cl_op_cmpl_cback(uint16_t conn_id, tGATTC_OPTYPE op, - tGATT_STATUS status, +static void gatt_disc_cmpl_cback(uint16_t conn_id, tGATT_DISC_TYPE disc_type, tGATT_STATUS status); +static void gatt_cl_op_cmpl_cback(uint16_t conn_id, tGATTC_OPTYPE op, tGATT_STATUS status, tGATT_CL_COMPLETE* p_data); static void gatt_cl_start_config_ccc(tGATT_PROFILE_CLCB* p_clcb); static bool gatt_sr_is_robust_caching_enabled(); -static bool read_sr_supported_feat_req( - uint16_t conn_id, base::OnceCallback cb); -static bool read_sr_sirk_req( - uint16_t conn_id, - base::OnceCallback - cb); - -static tGATT_STATUS gatt_sr_read_db_hash(uint16_t conn_id, - tGATT_VALUE* p_value); -static tGATT_STATUS gatt_sr_read_cl_supp_feat(uint16_t conn_id, - tGATT_VALUE* p_value); -static tGATT_STATUS gatt_sr_write_cl_supp_feat(uint16_t conn_id, - tGATT_WRITE_REQ* p_data); +static bool read_sr_supported_feat_req(uint16_t conn_id, + base::OnceCallback cb); +static bool read_sr_sirk_req(uint16_t conn_id, + base::OnceCallback + cb); + +static tGATT_STATUS gatt_sr_read_db_hash(uint16_t conn_id, tGATT_VALUE* p_value); +static tGATT_STATUS gatt_sr_read_cl_supp_feat(uint16_t conn_id, tGATT_VALUE* p_value); +static tGATT_STATUS gatt_sr_write_cl_supp_feat(uint16_t conn_id, tGATT_WRITE_REQ* p_data); static tGATT_CBACK gatt_profile_cback = { - .p_conn_cb = gatt_connect_cback, - .p_cmpl_cb = gatt_cl_op_cmpl_cback, - .p_disc_res_cb = gatt_disc_res_cback, - .p_disc_cmpl_cb = gatt_disc_cmpl_cback, - .p_req_cb = gatt_request_cback, - .p_enc_cmpl_cb = nullptr, - .p_congestion_cb = nullptr, - .p_phy_update_cb = nullptr, - .p_conn_update_cb = nullptr, - .p_subrate_chg_cb = nullptr, + .p_conn_cb = gatt_connect_cback, + .p_cmpl_cb = gatt_cl_op_cmpl_cback, + .p_disc_res_cb = gatt_disc_res_cback, + .p_disc_cmpl_cb = gatt_disc_cmpl_cback, + .p_req_cb = gatt_request_cback, + .p_enc_cmpl_cb = nullptr, + .p_congestion_cb = nullptr, + .p_phy_update_cb = nullptr, + .p_conn_update_cb = nullptr, + .p_subrate_chg_cb = nullptr, }; /******************************************************************************* @@ -123,20 +115,18 @@ static tGATT_CBACK gatt_profile_cback = { ******************************************************************************/ uint16_t gatt_profile_find_conn_id_by_bd_addr(const RawAddress& remote_bda) { uint16_t conn_id = GATT_INVALID_CONN_ID; - if (!GATT_GetConnIdIfConnected(gatt_cb.gatt_if, remote_bda, &conn_id, - BT_TRANSPORT_LE)) { + if (!GATT_GetConnIdIfConnected(gatt_cb.gatt_if, remote_bda, &conn_id, BT_TRANSPORT_LE)) { log::warn( - "Unable to get GATT connection id if connected peer:{} gatt_if:{} " - "transport:{}", - remote_bda, gatt_cb.gatt_if, bt_transport_text(BT_TRANSPORT_LE)); + "Unable to get GATT connection id if connected peer:{} gatt_if:{} " + "transport:{}", + remote_bda, gatt_cb.gatt_if, bt_transport_text(BT_TRANSPORT_LE)); } if (conn_id == GATT_INVALID_CONN_ID) { - if (!GATT_GetConnIdIfConnected(gatt_cb.gatt_if, remote_bda, &conn_id, - BT_TRANSPORT_BR_EDR)) { + if (!GATT_GetConnIdIfConnected(gatt_cb.gatt_if, remote_bda, &conn_id, BT_TRANSPORT_BR_EDR)) { log::warn( - "Unable to get GATT connection id if connected peer:{} gatt_if:{} " - "transport:{}", - remote_bda, gatt_cb.gatt_if, bt_transport_text(BT_TRANSPORT_BR_EDR)); + "Unable to get GATT connection id if connected peer:{} gatt_if:{} " + "transport:{}", + remote_bda, gatt_cb.gatt_if, bt_transport_text(BT_TRANSPORT_BR_EDR)); } } return conn_id; @@ -155,9 +145,10 @@ static tGATT_PROFILE_CLCB* gatt_profile_find_clcb_by_conn_id(uint16_t conn_id) { uint8_t i_clcb; tGATT_PROFILE_CLCB* p_clcb = NULL; - for (i_clcb = 0, p_clcb = gatt_cb.profile_clcb; i_clcb < GATT_MAX_APPS; - i_clcb++, p_clcb++) { - if (p_clcb->in_use && p_clcb->conn_id == conn_id) return p_clcb; + for (i_clcb = 0, p_clcb = gatt_cb.profile_clcb; i_clcb < GATT_MAX_APPS; i_clcb++, p_clcb++) { + if (p_clcb->in_use && p_clcb->conn_id == conn_id) { + return p_clcb; + } } return NULL; @@ -172,16 +163,16 @@ static tGATT_PROFILE_CLCB* gatt_profile_find_clcb_by_conn_id(uint16_t conn_id) { * Returns Pointer to the found link conenction control block. * ******************************************************************************/ -static tGATT_PROFILE_CLCB* gatt_profile_find_clcb_by_bd_addr( - const RawAddress& bda, tBT_TRANSPORT transport) { +static tGATT_PROFILE_CLCB* gatt_profile_find_clcb_by_bd_addr(const RawAddress& bda, + tBT_TRANSPORT transport) { uint8_t i_clcb; tGATT_PROFILE_CLCB* p_clcb = NULL; - for (i_clcb = 0, p_clcb = gatt_cb.profile_clcb; i_clcb < GATT_MAX_APPS; - i_clcb++, p_clcb++) { + for (i_clcb = 0, p_clcb = gatt_cb.profile_clcb; i_clcb < GATT_MAX_APPS; i_clcb++, p_clcb++) { if (p_clcb->in_use && p_clcb->transport == transport && p_clcb->connected && - p_clcb->bda == bda) + p_clcb->bda == bda) { return p_clcb; + } } return NULL; @@ -198,14 +189,12 @@ static tGATT_PROFILE_CLCB* gatt_profile_find_clcb_by_bd_addr( * block. * ******************************************************************************/ -tGATT_PROFILE_CLCB* gatt_profile_clcb_alloc(uint16_t conn_id, - const RawAddress& bda, +tGATT_PROFILE_CLCB* gatt_profile_clcb_alloc(uint16_t conn_id, const RawAddress& bda, tBT_TRANSPORT tranport) { uint8_t i_clcb = 0; tGATT_PROFILE_CLCB* p_clcb = NULL; - for (i_clcb = 0, p_clcb = gatt_cb.profile_clcb; i_clcb < GATT_MAX_APPS; - i_clcb++, p_clcb++) { + for (i_clcb = 0, p_clcb = gatt_cb.profile_clcb; i_clcb < GATT_MAX_APPS; i_clcb++, p_clcb++) { if (!p_clcb->in_use) { p_clcb->in_use = true; p_clcb->conn_id = conn_id; @@ -215,7 +204,9 @@ tGATT_PROFILE_CLCB* gatt_profile_clcb_alloc(uint16_t conn_id, break; } } - if (i_clcb < GATT_MAX_APPS) return p_clcb; + if (i_clcb < GATT_MAX_APPS) { + return p_clcb; + } return NULL; } @@ -235,13 +226,15 @@ void gatt_profile_clcb_dealloc(tGATT_PROFILE_CLCB* p_clcb) { } /** GAP Attributes Database Request callback */ -tGATT_STATUS read_attr_value(uint16_t conn_id, uint16_t handle, - tGATT_VALUE* p_value, bool is_long) { +tGATT_STATUS read_attr_value(uint16_t conn_id, uint16_t handle, tGATT_VALUE* p_value, + bool is_long) { uint8_t* p = p_value->value; if (handle == gatt_cb.handle_sr_supported_feat) { /* GATT_UUID_SERVER_SUP_FEAT*/ - if (is_long) return GATT_NOT_LONG; + if (is_long) { + return GATT_NOT_LONG; + } UINT8_TO_STREAM(p, gatt_cb.gatt_svr_supported_feat_mask); p_value->len = sizeof(gatt_cb.gatt_svr_supported_feat_mask); @@ -250,14 +243,18 @@ tGATT_STATUS read_attr_value(uint16_t conn_id, uint16_t handle, if (handle == gatt_cb.handle_cl_supported_feat) { /*GATT_UUID_CLIENT_SUP_FEAT */ - if (is_long) return GATT_NOT_LONG; + if (is_long) { + return GATT_NOT_LONG; + } return gatt_sr_read_cl_supp_feat(conn_id, p_value); } if (handle == gatt_cb.handle_of_database_hash) { /* GATT_UUID_DATABASE_HASH */ - if (is_long) return GATT_NOT_LONG; + if (is_long) { + return GATT_NOT_LONG; + } return gatt_sr_read_db_hash(conn_id, p_value); } @@ -271,33 +268,40 @@ tGATT_STATUS read_attr_value(uint16_t conn_id, uint16_t handle, } /** GAP Attributes Database Read/Read Blob Request process */ -tGATT_STATUS proc_read_req(uint16_t conn_id, tGATTS_REQ_TYPE, - tGATT_READ_REQ* p_data, tGATTS_RSP* p_rsp) { - if (p_data->is_long) p_rsp->attr_value.offset = p_data->offset; +tGATT_STATUS proc_read_req(uint16_t conn_id, tGATTS_REQ_TYPE, tGATT_READ_REQ* p_data, + tGATTS_RSP* p_rsp) { + if (p_data->is_long) { + p_rsp->attr_value.offset = p_data->offset; + } p_rsp->attr_value.handle = p_data->handle; - return read_attr_value(conn_id, p_data->handle, &p_rsp->attr_value, - p_data->is_long); + return read_attr_value(conn_id, p_data->handle, &p_rsp->attr_value, p_data->is_long); } /** GAP ATT server process a write request */ -tGATT_STATUS proc_write_req(uint16_t conn_id, tGATTS_REQ_TYPE, - tGATT_WRITE_REQ* p_data) { +tGATT_STATUS proc_write_req(uint16_t conn_id, tGATTS_REQ_TYPE, tGATT_WRITE_REQ* p_data) { uint16_t handle = p_data->handle; /* GATT_UUID_SERVER_SUP_FEAT*/ - if (handle == gatt_cb.handle_sr_supported_feat) return GATT_WRITE_NOT_PERMIT; + if (handle == gatt_cb.handle_sr_supported_feat) { + return GATT_WRITE_NOT_PERMIT; + } /* GATT_UUID_CLIENT_SUP_FEAT*/ - if (handle == gatt_cb.handle_cl_supported_feat) + if (handle == gatt_cb.handle_cl_supported_feat) { return gatt_sr_write_cl_supp_feat(conn_id, p_data); + } /* GATT_UUID_DATABASE_HASH */ - if (handle == gatt_cb.handle_of_database_hash) return GATT_WRITE_NOT_PERMIT; + if (handle == gatt_cb.handle_of_database_hash) { + return GATT_WRITE_NOT_PERMIT; + } /* GATT_UUID_GATT_SRV_CHGD */ - if (handle == gatt_cb.handle_of_h_r) return GATT_WRITE_NOT_PERMIT; + if (handle == gatt_cb.handle_of_h_r) { + return GATT_WRITE_NOT_PERMIT; + } return GATT_NOT_FOUND; } @@ -311,8 +315,8 @@ tGATT_STATUS proc_write_req(uint16_t conn_id, tGATTS_REQ_TYPE, * Returns void. * ******************************************************************************/ -static void gatt_request_cback(uint16_t conn_id, uint32_t trans_id, - tGATTS_REQ_TYPE type, tGATTS_DATA* p_data) { +static void gatt_request_cback(uint16_t conn_id, uint32_t trans_id, tGATTS_REQ_TYPE type, + tGATTS_DATA* p_data) { tGATT_STATUS status = GATT_INVALID_PDU; tGATTS_RSP rsp_msg; bool rsp_needed = true; @@ -329,7 +333,9 @@ static void gatt_request_cback(uint16_t conn_id, uint32_t trans_id, case GATTS_REQ_TYPE_WRITE_DESCRIPTOR: case GATTS_REQ_TYPE_WRITE_EXEC: case GATT_CMD_WRITE: - if (!p_data->write_req.need_rsp) rsp_needed = false; + if (!p_data->write_req.need_rsp) { + rsp_needed = false; + } status = proc_write_req(conn_id, type, &p_data->write_req); break; @@ -360,12 +366,10 @@ static void gatt_request_cback(uint16_t conn_id, uint32_t trans_id, * Returns void * ******************************************************************************/ -static void gatt_connect_cback(tGATT_IF /* gatt_if */, const RawAddress& bda, - uint16_t conn_id, bool connected, - tGATT_DISCONN_REASON /* reason */, +static void gatt_connect_cback(tGATT_IF /* gatt_if */, const RawAddress& bda, uint16_t conn_id, + bool connected, tGATT_DISCONN_REASON /* reason */, tBT_TRANSPORT transport) { - log::verbose("from {} connected: {}, conn_id: 0x{:x}", bda, connected, - conn_id); + log::verbose("from {} connected: {}, conn_id: 0x{:x}", bda, connected, conn_id); // if the device is not trusted, remove data when the link is disconnected if (!connected && !btm_sec_is_a_bonded_dev(bda)) { @@ -374,9 +378,10 @@ static void gatt_connect_cback(tGATT_IF /* gatt_if */, const RawAddress& bda, btif_storage_remove_gatt_cl_db_hash(bda); } - tGATT_PROFILE_CLCB* p_clcb = - gatt_profile_find_clcb_by_bd_addr(bda, transport); - if (p_clcb == NULL) return; + tGATT_PROFILE_CLCB* p_clcb = gatt_profile_find_clcb_by_bd_addr(bda, transport); + if (p_clcb == NULL) { + return; + } if (connected) { p_clcb->conn_id = conn_id; @@ -406,8 +411,8 @@ void gatt_profile_db_init(void) { OngoingOps.clear(); /* Create a GATT profile service */ - gatt_cb.gatt_if = GATT_Register(Uuid::From128BitBE(tmp), "GattProfileDb", - &gatt_profile_cback, false); + gatt_cb.gatt_if = + GATT_Register(Uuid::From128BitBE(tmp), "GattProfileDb", &gatt_profile_cback, false); GATT_StartIf(gatt_cb.gatt_if); Uuid service_uuid = Uuid::From16Bit(UUID_SERVCLASS_GATT_SERVER); @@ -418,37 +423,36 @@ void gatt_profile_db_init(void) { Uuid database_hash_uuid = Uuid::From16Bit(GATT_UUID_DATABASE_HASH); btgatt_db_element_t service[] = { - { - .uuid = service_uuid, - .type = BTGATT_DB_PRIMARY_SERVICE, - }, - { - .uuid = srv_changed_char_uuid, - .type = BTGATT_DB_CHARACTERISTIC, - .properties = GATT_CHAR_PROP_BIT_INDICATE, - .permissions = 0, - }, - { - .uuid = svr_sup_feat_uuid, - .type = BTGATT_DB_CHARACTERISTIC, - .properties = GATT_CHAR_PROP_BIT_READ, - .permissions = GATT_PERM_READ, - }, - { - .uuid = cl_sup_feat_uuid, - .type = BTGATT_DB_CHARACTERISTIC, - .properties = GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_WRITE, - .permissions = GATT_PERM_READ | GATT_PERM_WRITE, - }, - { - .uuid = database_hash_uuid, - .type = BTGATT_DB_CHARACTERISTIC, - .properties = GATT_CHAR_PROP_BIT_READ, - .permissions = GATT_PERM_READ, - }}; - - if (GATTS_AddService(gatt_cb.gatt_if, service, - sizeof(service) / sizeof(btgatt_db_element_t)) != + { + .uuid = service_uuid, + .type = BTGATT_DB_PRIMARY_SERVICE, + }, + { + .uuid = srv_changed_char_uuid, + .type = BTGATT_DB_CHARACTERISTIC, + .properties = GATT_CHAR_PROP_BIT_INDICATE, + .permissions = 0, + }, + { + .uuid = svr_sup_feat_uuid, + .type = BTGATT_DB_CHARACTERISTIC, + .properties = GATT_CHAR_PROP_BIT_READ, + .permissions = GATT_PERM_READ, + }, + { + .uuid = cl_sup_feat_uuid, + .type = BTGATT_DB_CHARACTERISTIC, + .properties = GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_WRITE, + .permissions = GATT_PERM_READ | GATT_PERM_WRITE, + }, + { + .uuid = database_hash_uuid, + .type = BTGATT_DB_CHARACTERISTIC, + .properties = GATT_CHAR_PROP_BIT_READ, + .permissions = GATT_PERM_READ, + }}; + + if (GATTS_AddService(gatt_cb.gatt_if, service, sizeof(service) / sizeof(btgatt_db_element_t)) != GATT_SERVICE_STARTED) { log::warn("Unable to add GATT server service gatt_if:{}", gatt_cb.gatt_if); } @@ -478,7 +482,9 @@ static void gatt_disc_res_cback(uint16_t conn_id, tGATT_DISC_TYPE disc_type, tGATT_DISC_RES* p_data) { tGATT_PROFILE_CLCB* p_clcb = gatt_profile_find_clcb_by_conn_id(conn_id); - if (p_clcb == NULL) return; + if (p_clcb == NULL) { + return; + } switch (disc_type) { case GATT_DISC_SRVC_BY_UUID: /* stage 1 */ @@ -515,8 +521,7 @@ static void gatt_disc_res_cback(uint16_t conn_id, tGATT_DISC_TYPE disc_type, * Returns void * ******************************************************************************/ -static void gatt_disc_cmpl_cback(uint16_t conn_id, - tGATT_DISC_TYPE /* disc_type */, +static void gatt_disc_cmpl_cback(uint16_t conn_id, tGATT_DISC_TYPE /* disc_type */, tGATT_STATUS status) { tGATT_PROFILE_CLCB* p_clcb = gatt_profile_find_clcb_by_conn_id(conn_id); if (p_clcb == NULL) { @@ -529,8 +534,7 @@ static void gatt_disc_cmpl_cback(uint16_t conn_id, return; } if (p_clcb->ccc_result == 0) { - log::warn("Gatt discovery completed but connection was idle id:{}", - conn_id); + log::warn("Gatt discovery completed but connection was idle id:{}", conn_id); return; } @@ -558,8 +562,8 @@ static bool gatt_svc_read_cl_supp_feat_req(uint16_t conn_id) { gatt_op_cb_data cb_data; - cb_data.cb = base::BindOnce( - [](const RawAddress& /* bdaddr */, uint8_t /* support */) { return; }); + cb_data.cb = + base::BindOnce([](const RawAddress& /* bdaddr */, uint8_t /* support */) { return; }); cb_data.op_uuid = GATT_UUID_CLIENT_SUP_FEAT; OngoingOps[conn_id].emplace_back(std::move(cb_data)); @@ -594,13 +598,12 @@ static bool gatt_att_write_cl_supp_feat(uint16_t conn_id, uint16_t handle) { * Returns void * ******************************************************************************/ -static void gatt_cl_op_cmpl_cback(uint16_t conn_id, tGATTC_OPTYPE op, - tGATT_STATUS status, +static void gatt_cl_op_cmpl_cback(uint16_t conn_id, tGATTC_OPTYPE op, tGATT_STATUS status, tGATT_CL_COMPLETE* p_data) { auto iter = OngoingOps.find(conn_id); - log::verbose("opcode: 0x{:x} status: {} conn id: 0x{:x}", - static_cast(op), status, static_cast(conn_id)); + log::verbose("opcode: 0x{:x} status: {} conn id: 0x{:x}", static_cast(op), status, + static_cast(conn_id)); if (op != GATTC_OPTYPE_READ && op != GATTC_OPTYPE_WRITE) { log::verbose("Not interested in opcode {}", op); @@ -621,9 +624,8 @@ static void gatt_cl_op_cmpl_cback(uint16_t conn_id, tGATTC_OPTYPE op, log::debug("Write response from Service Changed CCC"); iter->second.pop_front(); /* Read server supported features here supported */ - read_sr_supported_feat_req( - conn_id, base::BindOnce([](const RawAddress& /* bdaddr */, - uint8_t /* support */) { return; })); + read_sr_supported_feat_req(conn_id, base::BindOnce([](const RawAddress& /* bdaddr */, + uint8_t /* support */) { return; })); } else { log::debug("Not interested in that write response"); } @@ -676,7 +678,7 @@ static void gatt_cl_op_cmpl_cback(uint16_t conn_id, tGATTC_OPTYPE op, } std::move(operation_callback_data.sirk_cb) - .Run(tcb.gatt_status, tcb.peer_bda, tcb.sirk_type, tcb.sirk); + .Run(tcb.gatt_status, tcb.peer_bda, tcb.sirk_type, tcb.sirk); break; } @@ -709,28 +711,23 @@ static void gatt_cl_start_config_ccc(tGATT_PROFILE_CLCB* p_clcb) { switch (p_clcb->ccc_stage) { case GATT_SVC_CHANGED_SERVICE: /* discover GATT service */ - if (GATTC_Discover(p_clcb->conn_id, GATT_DISC_SRVC_BY_UUID, 0x0001, - 0xffff, Uuid::From16Bit(UUID_SERVCLASS_GATT_SERVER)) != - GATT_SUCCESS) { - log::warn("Unable to discovery GATT client conn_id:{}", - p_clcb->conn_id); + if (GATTC_Discover(p_clcb->conn_id, GATT_DISC_SRVC_BY_UUID, 0x0001, 0xffff, + Uuid::From16Bit(UUID_SERVCLASS_GATT_SERVER)) != GATT_SUCCESS) { + log::warn("Unable to discovery GATT client conn_id:{}", p_clcb->conn_id); } break; case GATT_SVC_CHANGED_CHARACTERISTIC: /* discover service change char */ - if (GATTC_Discover( - p_clcb->conn_id, GATT_DISC_CHAR, 0x0001, p_clcb->e_handle, - Uuid::From16Bit(GATT_UUID_GATT_SRV_CHGD)) != GATT_SUCCESS) { - log::warn("Unable to discovery GATT client conn_id:{}", - p_clcb->conn_id); + if (GATTC_Discover(p_clcb->conn_id, GATT_DISC_CHAR, 0x0001, p_clcb->e_handle, + Uuid::From16Bit(GATT_UUID_GATT_SRV_CHGD)) != GATT_SUCCESS) { + log::warn("Unable to discovery GATT client conn_id:{}", p_clcb->conn_id); } break; case GATT_SVC_CHANGED_DESCRIPTOR: /* discover service change ccc */ - if (GATTC_Discover(p_clcb->conn_id, GATT_DISC_CHAR_DSCPT, - p_clcb->s_handle, p_clcb->e_handle) != GATT_SUCCESS) { - log::warn("Unable to discovery GATT client conn_id:{}", - p_clcb->conn_id); + if (GATTC_Discover(p_clcb->conn_id, GATT_DISC_CHAR_DSCPT, p_clcb->s_handle, + p_clcb->e_handle) != GATT_SUCCESS) { + log::warn("Unable to discovery GATT client conn_id:{}", p_clcb->conn_id); } break; @@ -741,15 +738,13 @@ static void gatt_cl_start_config_ccc(tGATT_PROFILE_CLCB* p_clcb) { ccc_value.handle = p_clcb->s_handle; ccc_value.len = 2; ccc_value.value[0] = GATT_CLT_CONFIG_INDICATION; - if (GATTC_Write(p_clcb->conn_id, GATT_WRITE, &ccc_value) != - GATT_SUCCESS) { - log::warn("Unable to write GATT client data conn_id:{}", - p_clcb->conn_id); + if (GATTC_Write(p_clcb->conn_id, GATT_WRITE, &ccc_value) != GATT_SUCCESS) { + log::warn("Unable to write GATT client data conn_id:{}", p_clcb->conn_id); } gatt_op_cb_data cb_data; - cb_data.cb = base::BindOnce([](const RawAddress& /* bdaddr */, - uint8_t /* support */) { return; }); + cb_data.cb = + base::BindOnce([](const RawAddress& /* bdaddr */, uint8_t /* support */) { return; }); cb_data.op_uuid = GATT_UUID_GATT_SRV_CHGD; OngoingOps[p_clcb->conn_id].emplace_back(std::move(cb_data)); @@ -767,34 +762,34 @@ static void gatt_cl_start_config_ccc(tGATT_PROFILE_CLCB* p_clcb) { * Returns none * ******************************************************************************/ -void GATT_ConfigServiceChangeCCC(const RawAddress& remote_bda, - bool /* enable */, tBT_TRANSPORT transport) { - tGATT_PROFILE_CLCB* p_clcb = - gatt_profile_find_clcb_by_bd_addr(remote_bda, transport); +void GATT_ConfigServiceChangeCCC(const RawAddress& remote_bda, bool /* enable */, + tBT_TRANSPORT transport) { + tGATT_PROFILE_CLCB* p_clcb = gatt_profile_find_clcb_by_bd_addr(remote_bda, transport); - if (p_clcb == NULL) + if (p_clcb == NULL) { p_clcb = gatt_profile_clcb_alloc(0, remote_bda, transport); + } - if (p_clcb == NULL) return; + if (p_clcb == NULL) { + return; + } - if (GATT_GetConnIdIfConnected(gatt_cb.gatt_if, remote_bda, &p_clcb->conn_id, - transport)) { + if (GATT_GetConnIdIfConnected(gatt_cb.gatt_if, remote_bda, &p_clcb->conn_id, transport)) { p_clcb->connected = true; } else { log::warn( - "Unable to get GATT connection id if connected peer:{} gatt_if:{} " - "transport:{}", - remote_bda, gatt_cb.gatt_if, bt_transport_text(BT_TRANSPORT_LE)); + "Unable to get GATT connection id if connected peer:{} gatt_if:{} " + "transport:{}", + remote_bda, gatt_cb.gatt_if, bt_transport_text(BT_TRANSPORT_LE)); } /* hold the link here */ - if (!GATT_Connect(gatt_cb.gatt_if, remote_bda, BTM_BLE_DIRECT_CONNECTION, - transport, true)) { + if (!GATT_Connect(gatt_cb.gatt_if, remote_bda, BTM_BLE_DIRECT_CONNECTION, transport, true)) { log::warn( - "Unable to connect GATT client gatt_if:{} peer:{} transport:{} " - "connection_tyoe:{} opporunistic:{}", - gatt_cb.gatt_if, remote_bda, bt_transport_text(transport), - "BTM_BLE_DIRECT_CONNECTION", true); + "Unable to connect GATT client gatt_if:{} peer:{} transport:{} " + "connection_tyoe:{} opporunistic:{}", + gatt_cb.gatt_if, remote_bda, bt_transport_text(transport), "BTM_BLE_DIRECT_CONNECTION", + true); } p_clcb->ccc_stage = GATT_SVC_CHANGED_CONNECTING; @@ -819,12 +814,13 @@ void GATT_ConfigServiceChangeCCC(const RawAddress& remote_bda, void gatt_cl_init_sr_status(tGATT_TCB& tcb) { tcb.sr_supp_feat = btif_storage_get_sr_supp_feat(tcb.peer_bda); - if (tcb.sr_supp_feat & BLE_GATT_SVR_SUP_FEAT_EATT_BITMASK) + if (tcb.sr_supp_feat & BLE_GATT_SVR_SUP_FEAT_EATT_BITMASK) { bluetooth::eatt::EattExtension::AddFromStorage(tcb.peer_bda); + } } -static bool read_sr_supported_feat_req( - uint16_t conn_id, base::OnceCallback cb) { +static bool read_sr_supported_feat_req(uint16_t conn_id, + base::OnceCallback cb) { tGATT_READ_PARAM param = {}; param.service.s_handle = 1; @@ -847,11 +843,10 @@ static bool read_sr_supported_feat_req( return true; } -static bool read_sr_sirk_req( - uint16_t conn_id, - base::OnceCallback - cb) { +static bool read_sr_sirk_req(uint16_t conn_id, + base::OnceCallback + cb) { tGATT_READ_PARAM param = {}; param.service.s_handle = 1; @@ -884,25 +879,27 @@ static bool read_sr_sirk_req( * Returns bool * ******************************************************************************/ -bool gatt_cl_read_sr_supp_feat_req( - const RawAddress& peer_bda, - base::OnceCallback cb) { +bool gatt_cl_read_sr_supp_feat_req(const RawAddress& peer_bda, + base::OnceCallback cb) { tGATT_PROFILE_CLCB* p_clcb; uint16_t conn_id; - if (!cb) return false; + if (!cb) { + return false; + } log::verbose("BDA: {} read gatt supported features", peer_bda); - if (!GATT_GetConnIdIfConnected(gatt_cb.gatt_if, peer_bda, &conn_id, - BT_TRANSPORT_LE)) { + if (!GATT_GetConnIdIfConnected(gatt_cb.gatt_if, peer_bda, &conn_id, BT_TRANSPORT_LE)) { log::warn( - "Unable to get GATT connection id if connected peer:{} gatt_if:{} " - "transport:{}", - peer_bda, gatt_cb.gatt_if, bt_transport_text(BT_TRANSPORT_LE)); + "Unable to get GATT connection id if connected peer:{} gatt_if:{} " + "transport:{}", + peer_bda, gatt_cb.gatt_if, bt_transport_text(BT_TRANSPORT_LE)); } - if (conn_id == GATT_INVALID_CONN_ID) return false; + if (conn_id == GATT_INVALID_CONN_ID) { + return false; + } p_clcb = gatt_profile_find_clcb_by_conn_id(conn_id); if (!p_clcb) { @@ -931,26 +928,28 @@ bool gatt_cl_read_sr_supp_feat_req( * Returns bool * ******************************************************************************/ -bool gatt_cl_read_sirk_req( - const RawAddress& peer_bda, - base::OnceCallback - cb) { +bool gatt_cl_read_sirk_req(const RawAddress& peer_bda, + base::OnceCallback + cb) { tGATT_PROFILE_CLCB* p_clcb; uint16_t conn_id; - if (!cb) return false; + if (!cb) { + return false; + } log::debug("BDA: {}, read SIRK", peer_bda); - if (!GATT_GetConnIdIfConnected(gatt_cb.gatt_if, peer_bda, &conn_id, - BT_TRANSPORT_LE)) { + if (!GATT_GetConnIdIfConnected(gatt_cb.gatt_if, peer_bda, &conn_id, BT_TRANSPORT_LE)) { log::warn( - "Unable to get GATT connection id if connected peer:{} gatt_if:{} " - "transport:{}", - peer_bda, gatt_cb.gatt_if, bt_transport_text(BT_TRANSPORT_LE)); + "Unable to get GATT connection id if connected peer:{} gatt_if:{} " + "transport:{}", + peer_bda, gatt_cb.gatt_if, bt_transport_text(BT_TRANSPORT_LE)); + } + if (conn_id == GATT_INVALID_CONN_ID) { + return false; } - if (conn_id == GATT_INVALID_CONN_ID) return false; p_clcb = gatt_profile_find_clcb_by_conn_id(conn_id); if (!p_clcb) { @@ -985,16 +984,17 @@ bool gatt_profile_get_eatt_support(const RawAddress& remote_bda) { log::verbose("BDA: {} read GATT support", remote_bda); - if (!GATT_GetConnIdIfConnected(gatt_cb.gatt_if, remote_bda, &conn_id, - BT_TRANSPORT_LE)) { + if (!GATT_GetConnIdIfConnected(gatt_cb.gatt_if, remote_bda, &conn_id, BT_TRANSPORT_LE)) { log::warn( - "Unable to get GATT connection id if connected peer:{} gatt_if:{} " - "transport:{}", - remote_bda, gatt_cb.gatt_if, bt_transport_text(BT_TRANSPORT_LE)); + "Unable to get GATT connection id if connected peer:{} gatt_if:{} " + "transport:{}", + remote_bda, gatt_cb.gatt_if, bt_transport_text(BT_TRANSPORT_LE)); } /* This read is important only when connected */ - if (conn_id == GATT_INVALID_CONN_ID) return false; + if (conn_id == GATT_INVALID_CONN_ID) { + return false; + } /* Get tcb info */ uint8_t tcb_idx = GATT_GET_TCB_IDX(conn_id); @@ -1026,8 +1026,10 @@ static bool gatt_sr_is_robust_caching_enabled() { ******************************************************************************/ static bool gatt_sr_is_cl_robust_caching_supported(tGATT_TCB& tcb) { // if robust caching is not enabled, should always return false - if (!gatt_sr_is_robust_caching_enabled()) return false; - return (tcb.cl_supp_feat & BLE_GATT_CL_SUP_FEAT_CACHING_BITMASK); + if (!gatt_sr_is_robust_caching_enabled()) { + return false; + } + return tcb.cl_supp_feat & BLE_GATT_CL_SUP_FEAT_CACHING_BITMASK; } /******************************************************************************* @@ -1041,7 +1043,7 @@ static bool gatt_sr_is_cl_robust_caching_supported(tGATT_TCB& tcb) { * ******************************************************************************/ bool gatt_sr_is_cl_multi_variable_len_notif_supported(tGATT_TCB& tcb) { - return (tcb.cl_supp_feat & BLE_GATT_CL_SUP_FEAT_MULTI_NOTIF_BITMASK); + return tcb.cl_supp_feat & BLE_GATT_CL_SUP_FEAT_MULTI_NOTIF_BITMASK; } /******************************************************************************* @@ -1055,7 +1057,9 @@ bool gatt_sr_is_cl_multi_variable_len_notif_supported(tGATT_TCB& tcb) { ******************************************************************************/ bool gatt_sr_is_cl_change_aware(tGATT_TCB& tcb) { // if robust caching is not supported, should always return true by default - if (!gatt_sr_is_cl_robust_caching_supported(tcb)) return true; + if (!gatt_sr_is_cl_robust_caching_supported(tcb)) { + return true; + } return tcb.is_robust_cache_change_aware; } @@ -1083,8 +1087,8 @@ void gatt_sr_init_cl_status(tGATT_TCB& tcb) { tcb.is_robust_cache_change_aware = true; } - log::info("bda={}, cl_supp_feat=0x{:x}, aware={}", tcb.peer_bda, - tcb.cl_supp_feat, tcb.is_robust_cache_change_aware); + log::info("bda={}, cl_supp_feat=0x{:x}, aware={}", tcb.peer_bda, tcb.cl_supp_feat, + tcb.is_robust_cache_change_aware); } /******************************************************************************* @@ -1098,7 +1102,9 @@ void gatt_sr_init_cl_status(tGATT_TCB& tcb) { ******************************************************************************/ void gatt_sr_update_cl_status(tGATT_TCB& tcb, bool chg_aware) { // if robust caching is not supported, do nothing - if (!gatt_sr_is_cl_robust_caching_supported(tcb)) return; + if (!gatt_sr_is_cl_robust_caching_supported(tcb)) { + return; + } // only when client status is changed from change-unaware to change-aware, we // can then store database hash into btif_storage @@ -1115,8 +1121,7 @@ void gatt_sr_update_cl_status(tGATT_TCB& tcb, bool chg_aware) { } /* handle request for reading database hash */ -static tGATT_STATUS gatt_sr_read_db_hash(uint16_t conn_id, - tGATT_VALUE* p_value) { +static tGATT_STATUS gatt_sr_read_db_hash(uint16_t conn_id, tGATT_VALUE* p_value) { log::info("conn_id=0x{:x}", conn_id); uint8_t* p = p_value->value; @@ -1131,8 +1136,7 @@ static tGATT_STATUS gatt_sr_read_db_hash(uint16_t conn_id, } /* handle request for reading client supported features */ -static tGATT_STATUS gatt_sr_read_cl_supp_feat(uint16_t conn_id, - tGATT_VALUE* p_value) { +static tGATT_STATUS gatt_sr_read_cl_supp_feat(uint16_t conn_id, tGATT_VALUE* p_value) { // Get tcb info uint8_t tcb_idx = GATT_GET_TCB_IDX(conn_id); tGATT_TCB& tcb = gatt_cb.tcb[tcb_idx]; @@ -1145,8 +1149,7 @@ static tGATT_STATUS gatt_sr_read_cl_supp_feat(uint16_t conn_id, } /* handle request for writing client supported features */ -static tGATT_STATUS gatt_sr_write_cl_supp_feat(uint16_t conn_id, - tGATT_WRITE_REQ* p_data) { +static tGATT_STATUS gatt_sr_write_cl_supp_feat(uint16_t conn_id, tGATT_WRITE_REQ* p_data) { std::list tmp; uint16_t len = p_data->len; uint8_t value, *p = p_data->value; @@ -1158,7 +1161,9 @@ static tGATT_STATUS gatt_sr_write_cl_supp_feat(uint16_t conn_id, } // Remove trailing zero octets while (!tmp.empty()) { - if (tmp.back() != 0x00) break; + if (tmp.back() != 0x00) { + break; + } tmp.pop_back(); } @@ -1190,8 +1195,7 @@ static tGATT_STATUS gatt_sr_write_cl_supp_feat(uint16_t conn_id, uint8_t val_xor = *it_old ^ *it_new; uint8_t val_and = val_xor & *it_new; if (val_and != val_xor) { - log::info("bit cannot be reset, conn_id=0x{:x}, bda={}", conn_id, - tcb.peer_bda); + log::info("bit cannot be reset, conn_id=0x{:x}, bda={}", conn_id, tcb.peer_bda); return GATT_VALUE_NOT_ALLOWED; } } @@ -1203,8 +1207,7 @@ static tGATT_STATUS gatt_sr_write_cl_supp_feat(uint16_t conn_id, if (!gatt_sr_is_robust_caching_enabled()) { // remove robust caching bit tcb.cl_supp_feat &= ~BLE_GATT_CL_SUP_FEAT_CACHING_BITMASK; - log::info("reset robust caching bit, conn_id=0x{:x}, bda={}", conn_id, - tcb.peer_bda); + log::info("reset robust caching bit, conn_id=0x{:x}, bda={}", conn_id, tcb.peer_bda); } // TODO(hylo): save data as byte array btif_storage_set_gatt_cl_supp_feat(tcb.peer_bda, tcb.cl_supp_feat); diff --git a/system/stack/gatt/gatt_auth.cc b/system/stack/gatt/gatt_auth.cc index c2e003a64b0..5d47fc15558 100644 --- a/system/stack/gatt/gatt_auth.cc +++ b/system/stack/gatt/gatt_auth.cc @@ -58,8 +58,7 @@ static bool gatt_sign_data(tGATT_CLCB* p_clcb) { /* do not need to mark channel securoty activity for data signing */ gatt_set_sec_act(p_clcb->p_tcb, GATT_SEC_OK); - p_data = - (uint8_t*)osi_malloc(p_attr->len + 3); /* 3 = 2 byte handle + opcode */ + p_data = (uint8_t*)osi_malloc(p_attr->len + 3); /* 3 = 2 byte handle + opcode */ p = p_data; UINT8_TO_STREAM(p, GATT_SIGN_CMD_WRITE); @@ -68,14 +67,14 @@ static bool gatt_sign_data(tGATT_CLCB* p_clcb) { /* sign data length should be attribulte value length plus 2B handle + 1B op * code */ - if ((payload_size - GATT_AUTH_SIGN_LEN - 3) < p_attr->len) + if ((payload_size - GATT_AUTH_SIGN_LEN - 3) < p_attr->len) { p_attr->len = payload_size - GATT_AUTH_SIGN_LEN - 3; + } p_signature = p_attr->value + p_attr->len; - if (BTM_BleDataSignature( - p_clcb->p_tcb->peer_bda, p_data, - (uint16_t)(p_attr->len + 3), /* 3 = 2 byte handle + opcode */ - p_signature)) { + if (BTM_BleDataSignature(p_clcb->p_tcb->peer_bda, p_data, + (uint16_t)(p_attr->len + 3), /* 3 = 2 byte handle + opcode */ + p_signature)) { p_attr->len += BTM_BLE_AUTH_SIGN_LEN; gatt_set_ch_state(p_clcb->p_tcb, GATT_CH_OPEN); gatt_act_write(p_clcb, GATT_SEC_SIGN_DATA); @@ -105,8 +104,7 @@ void gatt_verify_signature(tGATT_TCB& tcb, uint16_t cid, BT_HDR* p_buf) { uint32_t counter; if (p_buf->len < GATT_AUTH_SIGN_LEN + 4) { - log::error("Data length {} less than expected {}", p_buf->len, - GATT_AUTH_SIGN_LEN + 4); + log::error("Data length {} less than expected {}", p_buf->len, GATT_AUTH_SIGN_LEN + 4); return; } cmd_len = p_buf->len - GATT_AUTH_SIGN_LEN + 4; @@ -120,8 +118,7 @@ void gatt_verify_signature(tGATT_TCB& tcb, uint16_t cid, BT_HDR* p_buf) { } STREAM_TO_UINT8(op_code, p_orig); - gatt_server_handle_client_req(tcb, cid, op_code, (uint16_t)(p_buf->len - 1), - p_orig); + gatt_server_handle_client_req(tcb, cid, op_code, (uint16_t)(p_buf->len - 1), p_orig); } /******************************************************************************* * @@ -132,8 +129,7 @@ void gatt_verify_signature(tGATT_TCB& tcb, uint16_t cid, BT_HDR* p_buf) { * Returns void. * ******************************************************************************/ -static void gatt_sec_check_complete(bool sec_check_ok, tGATT_CLCB* p_clcb, - uint8_t sec_act) { +static void gatt_sec_check_complete(bool sec_check_ok, tGATT_CLCB* p_clcb, uint8_t sec_act) { if (p_clcb && p_clcb->p_tcb && p_clcb->p_tcb->pending_enc_clcb.empty()) { gatt_set_sec_act(p_clcb->p_tcb, GATT_SEC_NONE); } @@ -155,8 +151,8 @@ static void gatt_sec_check_complete(bool sec_check_ok, tGATT_CLCB* p_clcb, * Returns * ******************************************************************************/ -static void gatt_enc_cmpl_cback(RawAddress bd_addr, tBT_TRANSPORT transport, - void* /* p_ref_data */, tBTM_STATUS result) { +static void gatt_enc_cmpl_cback(RawAddress bd_addr, tBT_TRANSPORT transport, void* /* p_ref_data */, + tBTM_STATUS result) { log::verbose(""); tGATT_TCB* p_tcb = gatt_find_tcb_by_addr(bd_addr, transport); if (!p_tcb) { @@ -164,7 +160,9 @@ static void gatt_enc_cmpl_cback(RawAddress bd_addr, tBT_TRANSPORT transport, return; } - if (gatt_get_sec_act(p_tcb) == GATT_SEC_ENC_PENDING) return; + if (gatt_get_sec_act(p_tcb) == GATT_SEC_ENC_PENDING) { + return; + } if (p_tcb->pending_enc_clcb.empty()) { log::error("no operation waiting for encrypting"); @@ -192,8 +190,9 @@ static void gatt_enc_cmpl_cback(RawAddress bd_addr, tBT_TRANSPORT transport, while (!p_tcb->pending_enc_clcb.empty()) { tGATT_CLCB* p_clcb = p_tcb->pending_enc_clcb.front(); p_tcb->pending_enc_clcb.pop_front(); - if (p_clcb != NULL && gatt_security_check_start(p_clcb)) + if (p_clcb != NULL && gatt_security_check_start(p_clcb)) { new_pending_clcbs.push_back(p_clcb); + } } p_tcb->pending_enc_clcb = new_pending_clcbs; } @@ -217,8 +216,7 @@ void gatt_notify_enc_cmpl(const RawAddress& bd_addr) { for (uint8_t i = 0; i < GATT_MAX_APPS; i++) { if (gatt_cb.cl_rcb[i].in_use && gatt_cb.cl_rcb[i].app_cb.p_enc_cmpl_cb) { - (*gatt_cb.cl_rcb[i].app_cb.p_enc_cmpl_cb)(gatt_cb.cl_rcb[i].gatt_if, - bd_addr); + (*gatt_cb.cl_rcb[i].app_cb.p_enc_cmpl_cb)(gatt_cb.cl_rcb[i].gatt_if, bd_addr); } } @@ -229,8 +227,9 @@ void gatt_notify_enc_cmpl(const RawAddress& bd_addr) { while (!p_tcb->pending_enc_clcb.empty()) { tGATT_CLCB* p_clcb = p_tcb->pending_enc_clcb.front(); p_tcb->pending_enc_clcb.pop_front(); - if (p_clcb != NULL && gatt_security_check_start(p_clcb)) + if (p_clcb != NULL && gatt_security_check_start(p_clcb)) { new_pending_clcbs.push_back(p_clcb); + } } p_tcb->pending_enc_clcb = new_pending_clcbs; } @@ -279,30 +278,35 @@ tGATT_SEC_ACTION gatt_determine_sec_act(tGATT_CLCB* p_clcb) { uint8_t key_type; tBTM_BLE_SEC_REQ_ACT sec_act = BTM_BLE_SEC_REQ_ACT_NONE; - if (auth_req == GATT_AUTH_REQ_NONE) return act; + if (auth_req == GATT_AUTH_REQ_NONE) { + return act; + } btm_ble_link_sec_check(p_tcb->peer_bda, auth_req, &sec_act); /* if a encryption is pending, need to wait */ - if (sec_act == BTM_BLE_SEC_REQ_ACT_DISCARD && auth_req != GATT_AUTH_REQ_NONE) + if (sec_act == BTM_BLE_SEC_REQ_ACT_DISCARD && auth_req != GATT_AUTH_REQ_NONE) { return GATT_SEC_ENC_PENDING; + } - is_link_key_known = - BTM_IsLinkKeyKnown(p_tcb->peer_bda, p_clcb->p_tcb->transport); - is_link_encrypted = - BTM_IsEncrypted(p_tcb->peer_bda, p_clcb->p_tcb->transport); + is_link_key_known = BTM_IsLinkKeyKnown(p_tcb->peer_bda, p_clcb->p_tcb->transport); + is_link_encrypted = BTM_IsEncrypted(p_tcb->peer_bda, p_clcb->p_tcb->transport); is_key_mitm = BTM_IsLinkKeyAuthed(p_tcb->peer_bda, p_clcb->p_tcb->transport); /* first check link key upgrade required or not */ switch (auth_req) { case GATT_AUTH_REQ_MITM: case GATT_AUTH_REQ_SIGNED_MITM: - if (!is_key_mitm) act = GATT_SEC_ENCRYPT_MITM; + if (!is_key_mitm) { + act = GATT_SEC_ENCRYPT_MITM; + } break; case GATT_AUTH_REQ_NO_MITM: case GATT_AUTH_REQ_SIGNED_NO_MITM: - if (!is_link_key_known) act = GATT_SEC_ENCRYPT_NO_MITM; + if (!is_link_key_known) { + act = GATT_SEC_ENCRYPT_NO_MITM; + } break; default: break; @@ -311,17 +315,15 @@ tGATT_SEC_ACTION gatt_determine_sec_act(tGATT_CLCB* p_clcb) { /* now check link needs to be encrypted or not if the link key upgrade is not * required */ if (act == GATT_SEC_OK) { - if (p_tcb->transport == BT_TRANSPORT_LE && - (p_clcb->operation == GATTC_OPTYPE_WRITE) && + if (p_tcb->transport == BT_TRANSPORT_LE && (p_clcb->operation == GATTC_OPTYPE_WRITE) && (p_clcb->op_subtype == GATT_WRITE_NO_RSP)) { /* this is a write command request check data signing required or not */ if (!is_link_encrypted) { btm_ble_get_enc_key_type(p_tcb->peer_bda, &key_type); - if ((key_type & BTM_LE_KEY_LCSRK) && - ((auth_req == GATT_AUTH_REQ_SIGNED_NO_MITM) || - (auth_req == GATT_AUTH_REQ_SIGNED_MITM))) { + if ((key_type & BTM_LE_KEY_LCSRK) && ((auth_req == GATT_AUTH_REQ_SIGNED_NO_MITM) || + (auth_req == GATT_AUTH_REQ_SIGNED_MITM))) { act = GATT_SEC_SIGN_DATA; } else { act = GATT_SEC_ENCRYPT; @@ -403,7 +405,9 @@ bool gatt_security_check_start(tGATT_CLCB* p_clcb) { tGATT_SEC_ACTION gatt_sec_act = gatt_determine_sec_act(p_clcb); - if (sec_act_old == GATT_SEC_NONE) gatt_set_sec_act(p_tcb, gatt_sec_act); + if (sec_act_old == GATT_SEC_NONE) { + gatt_set_sec_act(p_tcb, gatt_sec_act); + } switch (gatt_sec_act) { case GATT_SEC_SIGN_DATA: @@ -417,9 +421,8 @@ bool gatt_security_check_start(tGATT_CLCB* p_clcb) { log::verbose("Encrypt now or key upgreade first"); tBTM_BLE_SEC_ACT btm_ble_sec_act; gatt_convert_sec_action(gatt_sec_act, &btm_ble_sec_act); - tBTM_STATUS btm_status = - BTM_SetEncryption(p_tcb->peer_bda, p_tcb->transport, - gatt_enc_cmpl_cback, NULL, btm_ble_sec_act); + tBTM_STATUS btm_status = BTM_SetEncryption(p_tcb->peer_bda, p_tcb->transport, + gatt_enc_cmpl_cback, NULL, btm_ble_sec_act); if ((btm_status != BTM_SUCCESS) && (btm_status != BTM_CMD_STARTED)) { log::error("BTM_SetEncryption failed btm_status={}", btm_status); gatt_set_sec_act(p_tcb, GATT_SEC_NONE); diff --git a/system/stack/gatt/gatt_cl.cc b/system/stack/gatt/gatt_cl.cc index 8f948b32de1..3975c920985 100644 --- a/system/stack/gatt/gatt_cl.cc +++ b/system/stack/gatt/gatt_cl.cc @@ -54,8 +54,8 @@ using namespace bluetooth; using bluetooth::Uuid; -using bluetooth::eatt::EattExtension; using bluetooth::eatt::EattChannel; +using bluetooth::eatt::EattExtension; /******************************************************************************* * G L O B A L G A T T D A T A * @@ -63,21 +63,21 @@ using bluetooth::eatt::EattChannel; void gatt_send_prepare_write(tGATT_TCB& tcb, tGATT_CLCB* p_clcb); uint8_t disc_type_to_att_opcode[GATT_DISC_MAX] = { - 0, - GATT_REQ_READ_BY_GRP_TYPE, /* GATT_DISC_SRVC_ALL = 1, */ - GATT_REQ_FIND_TYPE_VALUE, /* GATT_DISC_SRVC_BY_UUID, */ - GATT_REQ_READ_BY_TYPE, /* GATT_DISC_INC_SRVC, */ - GATT_REQ_READ_BY_TYPE, /* GATT_DISC_CHAR, */ - GATT_REQ_FIND_INFO /* GATT_DISC_CHAR_DSCPT, */ + 0, + GATT_REQ_READ_BY_GRP_TYPE, /* GATT_DISC_SRVC_ALL = 1, */ + GATT_REQ_FIND_TYPE_VALUE, /* GATT_DISC_SRVC_BY_UUID, */ + GATT_REQ_READ_BY_TYPE, /* GATT_DISC_INC_SRVC, */ + GATT_REQ_READ_BY_TYPE, /* GATT_DISC_CHAR, */ + GATT_REQ_FIND_INFO /* GATT_DISC_CHAR_DSCPT, */ }; uint16_t disc_type_to_uuid[GATT_DISC_MAX] = { - 0, /* reserved */ - GATT_UUID_PRI_SERVICE, /* DISC_SRVC_ALL */ - GATT_UUID_PRI_SERVICE, /* for DISC_SERVC_BY_UUID */ - GATT_UUID_INCLUDE_SERVICE, /* for DISC_INC_SRVC */ - GATT_UUID_CHAR_DECLARE, /* for DISC_CHAR */ - 0 /* no type filtering for DISC_CHAR_DSCPT */ + 0, /* reserved */ + GATT_UUID_PRI_SERVICE, /* DISC_SRVC_ALL */ + GATT_UUID_PRI_SERVICE, /* for DISC_SERVC_BY_UUID */ + GATT_UUID_INCLUDE_SERVICE, /* for DISC_INC_SRVC */ + GATT_UUID_CHAR_DECLARE, /* for DISC_CHAR */ + 0 /* no type filtering for DISC_CHAR_DSCPT */ }; /******************************************************************************* @@ -105,15 +105,12 @@ void gatt_act_discovery(tGATT_CLCB* p_clcb) { cl_req.browse.e_handle = p_clcb->e_handle; if (disc_type_to_uuid[p_clcb->op_subtype] != 0) { - cl_req.browse.uuid = - bluetooth::Uuid::From16Bit(disc_type_to_uuid[p_clcb->op_subtype]); + cl_req.browse.uuid = bluetooth::Uuid::From16Bit(disc_type_to_uuid[p_clcb->op_subtype]); } - if (p_clcb->op_subtype == - GATT_DISC_SRVC_BY_UUID) /* fill in the FindByTypeValue request info*/ + if (p_clcb->op_subtype == GATT_DISC_SRVC_BY_UUID) /* fill in the FindByTypeValue request info*/ { - cl_req.find_type_value.uuid = - bluetooth::Uuid::From16Bit(disc_type_to_uuid[p_clcb->op_subtype]); + cl_req.find_type_value.uuid = bluetooth::Uuid::From16Bit(disc_type_to_uuid[p_clcb->op_subtype]); cl_req.find_type_value.s_handle = p_clcb->s_handle; cl_req.find_type_value.e_handle = p_clcb->e_handle; @@ -124,12 +121,11 @@ void gatt_act_discovery(tGATT_CLCB* p_clcb) { UINT16_TO_STREAM(p, p_clcb->uuid.As16Bit()); } else if (size == Uuid::kNumBytes32) { /* if service type is 32 bits UUID, convert it now */ - memcpy(cl_req.find_type_value.value, p_clcb->uuid.To128BitLE().data(), - Uuid::kNumBytes128); + memcpy(cl_req.find_type_value.value, p_clcb->uuid.To128BitLE().data(), Uuid::kNumBytes128); cl_req.find_type_value.value_len = Uuid::kNumBytes128; - } else - memcpy(cl_req.find_type_value.value, p_clcb->uuid.To128BitLE().data(), - size); + } else { + memcpy(cl_req.find_type_value.value, p_clcb->uuid.To128BitLE().data(), size); + } } tGATT_STATUS st = attp_send_cl_msg(*p_clcb->p_tcb, p_clcb, op_code, &cl_req); @@ -162,9 +158,9 @@ void gatt_act_read(tGATT_CLCB* p_clcb, uint16_t offset) { op_code = GATT_REQ_READ_BY_TYPE; msg.browse.s_handle = p_clcb->s_handle; msg.browse.e_handle = p_clcb->e_handle; - if (p_clcb->op_subtype == GATT_READ_BY_TYPE) + if (p_clcb->op_subtype == GATT_READ_BY_TYPE) { msg.browse.uuid = p_clcb->uuid; - else { + } else { msg.browse.uuid = bluetooth::Uuid::From16Bit(GATT_UUID_CHAR_DECLARE); } break; @@ -175,13 +171,13 @@ void gatt_act_read(tGATT_CLCB* p_clcb, uint16_t offset) { op_code = GATT_REQ_READ; msg.handle = p_clcb->s_handle; } else { - if (!p_clcb->first_read_blob_after_read) + if (!p_clcb->first_read_blob_after_read) { p_clcb->first_read_blob_after_read = true; - else + } else { p_clcb->first_read_blob_after_read = false; + } - log::verbose("first_read_blob_after_read={}", - p_clcb->first_read_blob_after_read); + log::verbose("first_read_blob_after_read={}", p_clcb->first_read_blob_after_read); op_code = GATT_REQ_READ_BLOB; msg.read_blob.offset = offset; msg.read_blob.handle = p_clcb->s_handle; @@ -216,7 +212,9 @@ void gatt_act_read(tGATT_CLCB* p_clcb, uint16_t offset) { break; } - if (op_code != 0) rt = attp_send_cl_msg(tcb, p_clcb, op_code, &msg); + if (op_code != 0) { + rt = attp_send_cl_msg(tcb, p_clcb, op_code, &msg); + } if (op_code == 0 || (rt != GATT_SUCCESS && rt != GATT_CMD_STARTED)) { gatt_end_operation(p_clcb, rt, NULL); @@ -227,8 +225,7 @@ void gatt_act_read(tGATT_CLCB* p_clcb, uint16_t offset) { void gatt_act_write(tGATT_CLCB* p_clcb, uint8_t sec_act) { tGATT_TCB& tcb = *p_clcb->p_tcb; - log::assert_that(p_clcb->p_attr_buf != nullptr, - "assert failed: p_clcb->p_attr_buf != nullptr"); + log::assert_that(p_clcb->p_attr_buf != nullptr, "assert failed: p_clcb->p_attr_buf != nullptr"); tGATT_VALUE& attr = *((tGATT_VALUE*)p_clcb->p_attr_buf); uint16_t payload_size = gatt_tcb_get_payload_size(tcb, p_clcb->cid); @@ -236,14 +233,12 @@ void gatt_act_write(tGATT_CLCB* p_clcb, uint8_t sec_act) { switch (p_clcb->op_subtype) { case GATT_WRITE_NO_RSP: { p_clcb->s_handle = attr.handle; - uint8_t op_code = (sec_act == GATT_SEC_SIGN_DATA) ? GATT_SIGN_CMD_WRITE - : GATT_CMD_WRITE; - tGATT_STATUS rt = gatt_send_write_msg(tcb, p_clcb, op_code, attr.handle, - attr.len, 0, attr.value); + uint8_t op_code = (sec_act == GATT_SEC_SIGN_DATA) ? GATT_SIGN_CMD_WRITE : GATT_CMD_WRITE; + tGATT_STATUS rt = + gatt_send_write_msg(tcb, p_clcb, op_code, attr.handle, attr.len, 0, attr.value); if (rt != GATT_CMD_STARTED) { if (rt != GATT_SUCCESS) { - log::error("gatt_act_write() failed op_code=0x{:x} rt={}", op_code, - rt); + log::error("gatt_act_write() failed op_code=0x{:x} rt={}", op_code, rt); } gatt_end_operation(p_clcb, rt, NULL); } @@ -254,13 +249,11 @@ void gatt_act_write(tGATT_CLCB* p_clcb, uint8_t sec_act) { if (attr.len <= (payload_size - GATT_HDR_SIZE)) { p_clcb->s_handle = attr.handle; - tGATT_STATUS rt = gatt_send_write_msg( - tcb, p_clcb, GATT_REQ_WRITE, attr.handle, attr.len, 0, attr.value); - if (rt != GATT_SUCCESS && rt != GATT_CMD_STARTED && - rt != GATT_CONGESTED) { + tGATT_STATUS rt = gatt_send_write_msg(tcb, p_clcb, GATT_REQ_WRITE, attr.handle, attr.len, 0, + attr.value); + if (rt != GATT_SUCCESS && rt != GATT_CMD_STARTED && rt != GATT_CONGESTED) { if (rt != GATT_SUCCESS) { - log::error("gatt_act_write() failed op_code=0x{:x} rt={}", - GATT_REQ_WRITE, rt); + log::error("gatt_act_write() failed op_code=0x{:x} rt={}", GATT_REQ_WRITE, rt); } gatt_end_operation(p_clcb, rt, NULL); } @@ -290,8 +283,7 @@ void gatt_act_write(tGATT_CLCB* p_clcb, uint8_t sec_act) { * Returns void. * ******************************************************************************/ -void gatt_send_queue_write_cancel(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, - tGATT_EXEC_FLAG flag) { +void gatt_send_queue_write_cancel(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, tGATT_EXEC_FLAG flag) { tGATT_STATUS rt; log::verbose(""); @@ -313,8 +305,7 @@ void gatt_send_queue_write_cancel(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, * Returns true: write long is terminated; false keep sending. * ******************************************************************************/ -bool gatt_check_write_long_terminate(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, - tGATT_VALUE* p_rsp_value) { +bool gatt_check_write_long_terminate(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, tGATT_VALUE* p_rsp_value) { tGATT_VALUE* p_attr = (tGATT_VALUE*)p_clcb->p_attr_buf; bool terminate = false; tGATT_EXEC_FLAG flag = GATT_PREP_WRITE_EXEC; @@ -322,10 +313,8 @@ bool gatt_check_write_long_terminate(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, log::verbose(""); /* check the first write response status */ if (p_rsp_value != NULL) { - if (p_rsp_value->handle != p_attr->handle || - p_rsp_value->len != p_clcb->counter || - memcmp(p_rsp_value->value, p_attr->value + p_attr->offset, - p_rsp_value->len)) { + if (p_rsp_value->handle != p_attr->handle || p_rsp_value->len != p_clcb->counter || + memcmp(p_rsp_value->value, p_attr->value + p_attr->offset, p_rsp_value->len)) { /* data does not match */ p_clcb->status = GATT_ERROR; flag = GATT_PREP_WRITE_CANCEL; @@ -334,7 +323,9 @@ bool gatt_check_write_long_terminate(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, { p_clcb->status = GATT_SUCCESS; /* update write offset and check if end of attribute value */ - if ((p_attr->offset += p_rsp_value->len) >= p_attr->len) terminate = true; + if ((p_attr->offset += p_rsp_value->len) >= p_attr->len) { + terminate = true; + } } } if (terminate && p_clcb->op_subtype != GATT_WRITE_PREPARE) { @@ -352,9 +343,9 @@ void gatt_send_prepare_write(tGATT_TCB& tcb, tGATT_CLCB* p_clcb) { uint16_t to_send = p_attr->len - p_attr->offset; uint16_t payload_size = gatt_tcb_get_payload_size(tcb, p_clcb->cid); - if (to_send > (payload_size - - GATT_WRITE_LONG_HDR_SIZE)) /* 2 = uint16_t offset bytes */ + if (to_send > (payload_size - GATT_WRITE_LONG_HDR_SIZE)) { /* 2 = uint16_t offset bytes */ to_send = payload_size - GATT_WRITE_LONG_HDR_SIZE; + } p_clcb->s_handle = p_attr->handle; @@ -365,10 +356,10 @@ void gatt_send_prepare_write(tGATT_TCB& tcb, tGATT_CLCB* p_clcb) { log::verbose("offset =0x{:x} len={}", offset, to_send); - tGATT_STATUS rt = gatt_send_write_msg( - tcb, p_clcb, GATT_REQ_PREPARE_WRITE, p_attr->handle, to_send, /* length */ - offset, /* used as offset */ - p_attr->value + p_attr->offset); /* data */ + tGATT_STATUS rt = gatt_send_write_msg(tcb, p_clcb, GATT_REQ_PREPARE_WRITE, p_attr->handle, + to_send, /* length */ + offset, /* used as offset */ + p_attr->value + p_attr->offset); /* data */ /* remember the write long attribute length */ p_clcb->counter = to_send; @@ -388,16 +379,16 @@ void gatt_send_prepare_write(tGATT_TCB& tcb, tGATT_CLCB* p_clcb) { * Returns void * ******************************************************************************/ -void gatt_process_find_type_value_rsp(tGATT_TCB& /* tcb */, tGATT_CLCB* p_clcb, - uint16_t len, uint8_t* p_data) { +void gatt_process_find_type_value_rsp(tGATT_TCB& /* tcb */, tGATT_CLCB* p_clcb, uint16_t len, + uint8_t* p_data) { tGATT_DISC_RES result; uint8_t* p = p_data; log::verbose(""); /* unexpected response */ - if (p_clcb->operation != GATTC_OPTYPE_DISCOVERY || - p_clcb->op_subtype != GATT_DISC_SRVC_BY_UUID) + if (p_clcb->operation != GATTC_OPTYPE_DISCOVERY || p_clcb->op_subtype != GATT_DISC_SRVC_BY_UUID) { return; + } memset(&result, 0, sizeof(tGATT_DISC_RES)); result.type = bluetooth::Uuid::From16Bit(GATT_UUID_PRI_SERVICE); @@ -410,16 +401,15 @@ void gatt_process_find_type_value_rsp(tGATT_TCB& /* tcb */, tGATT_CLCB* p_clcb, len -= 4; - if (p_clcb->p_reg->app_cb.p_disc_res_cb) + if (p_clcb->p_reg->app_cb.p_disc_res_cb) { (*p_clcb->p_reg->app_cb.p_disc_res_cb)( - p_clcb->conn_id, static_cast(p_clcb->op_subtype), - &result); + p_clcb->conn_id, static_cast(p_clcb->op_subtype), &result); + } } /* last handle + 1 */ - p_clcb->s_handle = (result.value.group_value.e_handle == 0) - ? 0 - : (result.value.group_value.e_handle + 1); + p_clcb->s_handle = + (result.value.group_value.e_handle == 0) ? 0 : (result.value.group_value.e_handle + 1); /* initiate another request */ gatt_act_discovery(p_clcb); } @@ -434,9 +424,8 @@ void gatt_process_find_type_value_rsp(tGATT_TCB& /* tcb */, tGATT_CLCB* p_clcb, * Returns void * ******************************************************************************/ -void gatt_process_read_info_rsp(tGATT_TCB& /* tcb */, tGATT_CLCB* p_clcb, - uint8_t /* op_code */, uint16_t len, - uint8_t* p_data) { +void gatt_process_read_info_rsp(tGATT_TCB& /* tcb */, tGATT_CLCB* p_clcb, uint8_t /* op_code */, + uint16_t len, uint8_t* p_data) { tGATT_DISC_RES result; uint8_t *p = p_data, uuid_len = 0, type; @@ -446,32 +435,36 @@ void gatt_process_read_info_rsp(tGATT_TCB& /* tcb */, tGATT_CLCB* p_clcb, return; } /* unexpected response */ - if (p_clcb->operation != GATTC_OPTYPE_DISCOVERY || - p_clcb->op_subtype != GATT_DISC_CHAR_DSCPT) + if (p_clcb->operation != GATTC_OPTYPE_DISCOVERY || p_clcb->op_subtype != GATT_DISC_CHAR_DSCPT) { return; + } STREAM_TO_UINT8(type, p); len -= 1; - if (type == GATT_INFO_TYPE_PAIR_16) + if (type == GATT_INFO_TYPE_PAIR_16) { uuid_len = Uuid::kNumBytes16; - else if (type == GATT_INFO_TYPE_PAIR_128) + } else if (type == GATT_INFO_TYPE_PAIR_128) { uuid_len = Uuid::kNumBytes128; + } while (len >= uuid_len + 2) { STREAM_TO_UINT16(result.handle, p); if (uuid_len > 0) { - if (!gatt_parse_uuid_from_cmd(&result.type, uuid_len, &p)) break; - } else + if (!gatt_parse_uuid_from_cmd(&result.type, uuid_len, &p)) { + break; + } + } else { result.type = p_clcb->uuid; + } len -= (uuid_len + 2); - if (p_clcb->p_reg->app_cb.p_disc_res_cb) + if (p_clcb->p_reg->app_cb.p_disc_res_cb) { (*p_clcb->p_reg->app_cb.p_disc_res_cb)( - p_clcb->conn_id, static_cast(p_clcb->op_subtype), - &result); + p_clcb->conn_id, static_cast(p_clcb->op_subtype), &result); + } } p_clcb->s_handle = (result.handle == 0) ? 0 : (result.handle + 1); @@ -488,9 +481,8 @@ void gatt_process_read_info_rsp(tGATT_TCB& /* tcb */, tGATT_CLCB* p_clcb, * Returns void. * ******************************************************************************/ -void gatt_proc_disc_error_rsp(tGATT_TCB& /* tcb */, tGATT_CLCB* p_clcb, - uint8_t opcode, uint16_t /* handle */, - uint8_t reason) { +void gatt_proc_disc_error_rsp(tGATT_TCB& /* tcb */, tGATT_CLCB* p_clcb, uint8_t opcode, + uint16_t /* handle */, uint8_t reason) { tGATT_STATUS status = (tGATT_STATUS)reason; log::verbose("reason: {:02x} cmd_code {:04x}", reason, opcode); @@ -523,8 +515,7 @@ void gatt_proc_disc_error_rsp(tGATT_TCB& /* tcb */, tGATT_CLCB* p_clcb, * Returns void * ******************************************************************************/ -void gatt_process_error_rsp(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, - uint8_t /* op_code */, uint16_t len, +void gatt_process_error_rsp(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, uint8_t /* op_code */, uint16_t len, uint8_t* p_data) { uint8_t opcode, *p = p_data; uint8_t reason; @@ -551,24 +542,21 @@ void gatt_process_error_rsp(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, } if (p_clcb->operation == GATTC_OPTYPE_DISCOVERY) { - gatt_proc_disc_error_rsp(tcb, p_clcb, opcode, handle, - static_cast(reason)); + gatt_proc_disc_error_rsp(tcb, p_clcb, opcode, handle, static_cast(reason)); } else { - if ((p_clcb->operation == GATTC_OPTYPE_WRITE) && - (p_clcb->op_subtype == GATT_WRITE) && - (opcode == GATT_REQ_PREPARE_WRITE) && (p_attr) && - (handle == p_attr->handle)) { + if ((p_clcb->operation == GATTC_OPTYPE_WRITE) && (p_clcb->op_subtype == GATT_WRITE) && + (opcode == GATT_REQ_PREPARE_WRITE) && (p_attr) && (handle == p_attr->handle)) { p_clcb->status = static_cast(reason); gatt_send_queue_write_cancel(tcb, p_clcb, GATT_PREP_WRITE_CANCEL); } else if ((p_clcb->operation == GATTC_OPTYPE_READ) && ((p_clcb->op_subtype == GATT_READ_CHAR_VALUE_HDL) || (p_clcb->op_subtype == GATT_READ_BY_HANDLE)) && - (opcode == GATT_REQ_READ_BLOB) && - p_clcb->first_read_blob_after_read && + (opcode == GATT_REQ_READ_BLOB) && p_clcb->first_read_blob_after_read && (reason == GATT_NOT_LONG)) { gatt_end_operation(p_clcb, GATT_SUCCESS, (void*)p_clcb->p_attr_buf); - } else + } else { gatt_end_operation(p_clcb, static_cast(reason), NULL); + } } } /******************************************************************************* @@ -581,17 +569,16 @@ void gatt_process_error_rsp(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, * Returns void * ******************************************************************************/ -void gatt_process_prep_write_rsp(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, - uint8_t op_code, uint16_t len, +void gatt_process_prep_write_rsp(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, uint8_t op_code, uint16_t len, uint8_t* p_data) { uint8_t* p = p_data; tGATT_VALUE value = { - .conn_id = p_clcb->conn_id, .auth_req = GATT_AUTH_REQ_NONE, + .conn_id = p_clcb->conn_id, + .auth_req = GATT_AUTH_REQ_NONE, }; - log::verbose("value resp op_code = {} len = {}", gatt_dbg_op_name(op_code), - len); + log::verbose("value resp op_code = {} len = {}", gatt_dbg_op_name(op_code), len); if (len < GATT_PREP_WRITE_RSP_MIN_LEN || len > GATT_PREP_WRITE_RSP_MIN_LEN + sizeof(value.value)) { @@ -633,17 +620,16 @@ void gatt_process_prep_write_rsp(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, * Returns void * ******************************************************************************/ -void gatt_process_notification(tGATT_TCB& tcb, uint16_t cid, uint8_t op_code, - uint16_t len, uint8_t* p_data) { +void gatt_process_notification(tGATT_TCB& tcb, uint16_t cid, uint8_t op_code, uint16_t len, + uint8_t* p_data) { tGATT_VALUE value = {}; tGATT_REG* p_reg; uint16_t conn_id; tGATT_STATUS encrypt_status = {}; uint8_t* p = p_data; uint8_t i; - tGATTC_OPTYPE event = (op_code == GATT_HANDLE_VALUE_IND) - ? GATTC_OPTYPE_INDICATION - : GATTC_OPTYPE_NOTIFICATION; + tGATTC_OPTYPE event = + (op_code == GATT_HANDLE_VALUE_IND) ? GATTC_OPTYPE_INDICATION : GATTC_OPTYPE_NOTIFICATION; log::verbose(""); @@ -659,8 +645,9 @@ void gatt_process_notification(tGATT_TCB& tcb, uint16_t cid, uint8_t op_code, // Fail early if the GATT handle is not valid if (!GATT_HANDLE_IS_VALID(value.handle)) { /* illegal handle, send ack now */ - if (op_code == GATT_HANDLE_VALUE_IND) + if (op_code == GATT_HANDLE_VALUE_IND) { attp_send_cl_confirmation_msg(tcb, cid); + } return; } @@ -699,8 +686,7 @@ void gatt_process_notification(tGATT_TCB& tcb, uint16_t cid, uint8_t op_code, For now, just log the error reset the counter. Later we need to disconnect the link unconditionally. */ - log::error("rcv Ind. but ind_count={} (will reset ind_count)", - tcb.ind_count); + log::error("rcv Ind. but ind_count={} (will reset ind_count)", tcb.ind_count); } // Zero out the ind_count @@ -711,7 +697,9 @@ void gatt_process_notification(tGATT_TCB& tcb, uint16_t cid, uint8_t op_code, // Note: need to do the indication count and start timer first then do // callback for (i = 0, p_reg = gatt_cb.cl_rcb; i < GATT_MAX_APPS; i++, p_reg++) { - if (p_reg->in_use && p_reg->app_cb.p_cmpl_cb) tcb.ind_count++; + if (p_reg->in_use && p_reg->app_cb.p_cmpl_cb) { + tcb.ind_count++; + } } /* start a timer for app confirmation */ @@ -733,13 +721,14 @@ void gatt_process_notification(tGATT_TCB& tcb, uint16_t cid, uint8_t op_code, for (i = 0, p_reg = gatt_cb.cl_rcb; i < GATT_MAX_APPS; i++, p_reg++) { if (p_reg->in_use && p_reg->app_cb.p_cmpl_cb) { conn_id = GATT_CREATE_CONN_ID(tcb.tcb_idx, p_reg->gatt_if); - (*p_reg->app_cb.p_cmpl_cb)(conn_id, event, encrypt_status, - &gatt_cl_complete); + (*p_reg->app_cb.p_cmpl_cb)(conn_id, event, encrypt_status, &gatt_cl_complete); } } // If this is single value, then nothing is left to do - if (op_code != GATT_HANDLE_MULTI_VALUE_NOTIF) return; + if (op_code != GATT_HANDLE_MULTI_VALUE_NOTIF) { + return; + } // Need a signed type to check if the value is below 0 // as uint16_t doesn't have negatives so the negatives register as a number @@ -761,7 +750,7 @@ void gatt_process_notification(tGATT_TCB& tcb, uint16_t cid, uint8_t op_code, value.len = std::min((uint16_t)rem_len, value.len); if (value.len > sizeof(value.value)) { log::error("Unexpected value.len (>GATT_MAX_ATTR_LEN), stop"); - return ; + return; } STREAM_TO_ARRAY(value.value, p, value.len); // Accounting @@ -773,8 +762,7 @@ void gatt_process_notification(tGATT_TCB& tcb, uint16_t cid, uint8_t op_code, for (i = 0, p_reg = gatt_cb.cl_rcb; i < GATT_MAX_APPS; i++, p_reg++) { if (p_reg->in_use && p_reg->app_cb.p_cmpl_cb) { conn_id = GATT_CREATE_CONN_ID(tcb.tcb_idx, p_reg->gatt_if); - (*p_reg->app_cb.p_cmpl_cb)(conn_id, event, encrypt_status, - &gatt_cl_complete); + (*p_reg->app_cb.p_cmpl_cb)(conn_id, event, encrypt_status, &gatt_cl_complete); } } } @@ -791,9 +779,8 @@ void gatt_process_notification(tGATT_TCB& tcb, uint16_t cid, uint8_t op_code, * Returns void * ******************************************************************************/ -void gatt_process_read_by_type_rsp(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, - uint8_t op_code, uint16_t len, - uint8_t* p_data) { +void gatt_process_read_by_type_rsp(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, uint8_t op_code, + uint16_t len, uint8_t* p_data) { tGATT_DISC_RES result; tGATT_DISC_VALUE record_value; uint8_t *p = p_data, value_len, handle_len = 2; @@ -801,8 +788,9 @@ void gatt_process_read_by_type_rsp(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, /* discovery procedure and no callback function registered */ if (((!p_clcb->p_reg) || (!p_clcb->p_reg->app_cb.p_disc_res_cb)) && - (p_clcb->operation == GATTC_OPTYPE_DISCOVERY)) + (p_clcb->operation == GATTC_OPTYPE_DISCOVERY)) { return; + } if (len < GATT_READ_BY_TYPE_RSP_MIN_LEN) { log::error("Illegal ReadByType/ReadByGroupType Response length, discard"); @@ -816,14 +804,15 @@ void gatt_process_read_by_type_rsp(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, /* this is an error case that server's response containing a value length which is larger than MTU-2 or value_len > message total length -1 */ - log::error( - "Discard response op_code={} vale_len={} > (MTU-2={} or msg_len-1={})", - op_code, value_len, payload_size - 2, len - 1); + log::error("Discard response op_code={} vale_len={} > (MTU-2={} or msg_len-1={})", op_code, + value_len, payload_size - 2, len - 1); gatt_end_operation(p_clcb, GATT_ERROR, NULL); return; } - if (op_code == GATT_RSP_READ_BY_GRP_TYPE) handle_len = 4; + if (op_code == GATT_RSP_READ_BY_GRP_TYPE) { + handle_len = 4; + } value_len -= handle_len; /* subtract the handle pairs bytes */ len -= 1; @@ -840,12 +829,10 @@ void gatt_process_read_by_type_rsp(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, memset(&record_value, 0, sizeof(tGATT_DISC_VALUE)); result.handle = handle; - result.type = - bluetooth::Uuid::From16Bit(disc_type_to_uuid[p_clcb->op_subtype]); + result.type = bluetooth::Uuid::From16Bit(disc_type_to_uuid[p_clcb->op_subtype]); /* discover all services */ - if (p_clcb->operation == GATTC_OPTYPE_DISCOVERY && - p_clcb->op_subtype == GATT_DISC_SRVC_ALL && + if (p_clcb->operation == GATTC_OPTYPE_DISCOVERY && p_clcb->op_subtype == GATT_DISC_SRVC_ALL && op_code == GATT_RSP_READ_BY_GRP_TYPE) { STREAM_TO_UINT16(handle, p); @@ -854,8 +841,7 @@ void gatt_process_read_by_type_rsp(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, return; } else { record_value.group_value.e_handle = handle; - if (!gatt_parse_uuid_from_cmd(&record_value.group_value.service_type, - value_len, &p)) { + if (!gatt_parse_uuid_from_cmd(&record_value.group_value.service_type, value_len, &p)) { log::error("discover all service response parsing failure"); break; } @@ -881,34 +867,31 @@ void gatt_process_read_by_type_rsp(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, if (value_len == 6) { uint16_t tmp; STREAM_TO_UINT16(tmp, p); - record_value.incl_service.service_type = - bluetooth::Uuid::From16Bit(tmp); + record_value.incl_service.service_type = bluetooth::Uuid::From16Bit(tmp); } else if (value_len == 4) { p_clcb->s_handle = record_value.incl_service.s_handle; p_clcb->read_uuid128.wait_for_read_rsp = true; p_clcb->read_uuid128.next_disc_start_hdl = handle + 1; memcpy(&p_clcb->read_uuid128.result, &result, sizeof(result)); - memcpy(&p_clcb->read_uuid128.result.value, &record_value, - sizeof(result.value)); + memcpy(&p_clcb->read_uuid128.result.value, &record_value, sizeof(result.value)); p_clcb->op_subtype |= 0x90; gatt_act_read(p_clcb, 0); return; } else { - log::error("INCL_SRVC failed with invalid data value_len={}", - value_len); + log::error("INCL_SRVC failed with invalid data value_len={}", value_len); gatt_end_operation(p_clcb, GATT_INVALID_PDU, (void*)p); return; } } /* read by type */ - else if (p_clcb->operation == GATTC_OPTYPE_READ && - p_clcb->op_subtype == GATT_READ_BY_TYPE) { + else if (p_clcb->operation == GATTC_OPTYPE_READ && p_clcb->op_subtype == GATT_READ_BY_TYPE) { p_clcb->counter = len - 2; p_clcb->s_handle = handle; if (p_clcb->counter == (payload_size - 4)) { p_clcb->op_subtype = GATT_READ_BY_HANDLE; - if (!p_clcb->p_attr_buf) + if (!p_clcb->p_attr_buf) { p_clcb->p_attr_buf = (uint8_t*)osi_malloc(GATT_MAX_ATTR_LEN); + } if (p_clcb->counter <= GATT_MAX_ATTR_LEN) { memcpy(p_clcb->p_attr_buf, p, p_clcb->counter); gatt_act_read(p_clcb, p_clcb->counter); @@ -932,16 +915,15 @@ void gatt_process_read_by_type_rsp(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, gatt_end_operation(p_clcb, GATT_INVALID_HANDLE, NULL); return; } - if (!gatt_parse_uuid_from_cmd(&record_value.dclr_value.char_uuid, - (uint16_t)(value_len - 3), &p)) { + if (!gatt_parse_uuid_from_cmd(&record_value.dclr_value.char_uuid, (uint16_t)(value_len - 3), + &p)) { gatt_end_operation(p_clcb, GATT_SUCCESS, NULL); /* invalid format, and skip the result */ return; } /* UUID not matching */ - if (!p_clcb->uuid.IsEmpty() && - !record_value.dclr_value.char_uuid.IsEmpty() && + if (!p_clcb->uuid.IsEmpty() && !record_value.dclr_value.char_uuid.IsEmpty() && record_value.dclr_value.char_uuid != p_clcb->uuid) { len -= (value_len + 2); continue; /* skip the result, and look for next one */ @@ -964,11 +946,10 @@ void gatt_process_read_by_type_rsp(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, memcpy(&result.value, &record_value, sizeof(result.value)); /* send callback if is discover procedure */ - if (p_clcb->operation == GATTC_OPTYPE_DISCOVERY && - p_clcb->p_reg->app_cb.p_disc_res_cb) + if (p_clcb->operation == GATTC_OPTYPE_DISCOVERY && p_clcb->p_reg->app_cb.p_disc_res_cb) { (*p_clcb->p_reg->app_cb.p_disc_res_cb)( - p_clcb->conn_id, static_cast(p_clcb->op_subtype), - &result); + p_clcb->conn_id, static_cast(p_clcb->op_subtype), &result); + } } p_clcb->s_handle = (handle == 0) ? 0 : (handle + 1); @@ -992,8 +973,7 @@ void gatt_process_read_by_type_rsp(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, * Returns void * ******************************************************************************/ -void gatt_process_read_rsp(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, - uint8_t /* op_code */, uint16_t len, +void gatt_process_read_rsp(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, uint8_t /* op_code */, uint16_t len, uint8_t* p_data) { uint16_t offset = p_clcb->counter; uint8_t* p = p_data; @@ -1006,13 +986,15 @@ void gatt_process_read_rsp(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, gatt_end_operation(p_clcb, GATT_SUCCESS, (void*)p); } else { /* allocate GKI buffer holding up long attribute value */ - if (!p_clcb->p_attr_buf) + if (!p_clcb->p_attr_buf) { p_clcb->p_attr_buf = (uint8_t*)osi_malloc(GATT_MAX_ATTR_LEN); + } /* copy attribute value into cb buffer */ if (offset < GATT_MAX_ATTR_LEN) { - if ((len + offset) > GATT_MAX_ATTR_LEN) + if ((len + offset) > GATT_MAX_ATTR_LEN) { len = GATT_MAX_ATTR_LEN - offset; + } p_clcb->counter += len; @@ -1023,17 +1005,15 @@ void gatt_process_read_rsp(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, if (payload_size == p_clcb->read_req_current_mtu) { packet_is_full = (len == (payload_size - 1)); } else { - packet_is_full = (len == (p_clcb->read_req_current_mtu - 1) || - len == (payload_size - 1)); + packet_is_full = (len == (p_clcb->read_req_current_mtu - 1) || len == (payload_size - 1)); p_clcb->read_req_current_mtu = payload_size; } /* send next request if needed */ if (packet_is_full && (len + offset < GATT_MAX_ATTR_LEN)) { log::verbose( - "full pkt issue read blob for remaining bytes old offset={} " - "len={} new offset={}", - offset, len, p_clcb->counter); + "full pkt issue read blob for remaining bytes old offset={} len={} new offset={}", + offset, len, p_clcb->counter); gatt_act_read(p_clcb, p_clcb->counter); } else /* end of request, send callback */ { @@ -1041,25 +1021,23 @@ void gatt_process_read_rsp(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, } } else /* exception, should not happen */ { - log::error("attr offset = {} p_attr_buf = {}", offset, - fmt::ptr(p_clcb->p_attr_buf)); - gatt_end_operation(p_clcb, GATT_NO_RESOURCES, - (void*)p_clcb->p_attr_buf); + log::error("attr offset = {} p_attr_buf = {}", offset, fmt::ptr(p_clcb->p_attr_buf)); + gatt_end_operation(p_clcb, GATT_NO_RESOURCES, (void*)p_clcb->p_attr_buf); } } } else { - if (p_clcb->operation == GATTC_OPTYPE_DISCOVERY && - p_clcb->op_subtype == GATT_DISC_INC_SRVC && + if (p_clcb->operation == GATTC_OPTYPE_DISCOVERY && p_clcb->op_subtype == GATT_DISC_INC_SRVC && p_clcb->read_uuid128.wait_for_read_rsp) { p_clcb->s_handle = p_clcb->read_uuid128.next_disc_start_hdl; p_clcb->read_uuid128.wait_for_read_rsp = false; if (len == Uuid::kNumBytes128) { p_clcb->read_uuid128.result.value.incl_service.service_type = - bluetooth::Uuid::From128BitLE(p); - if (p_clcb->p_reg->app_cb.p_disc_res_cb) - (*p_clcb->p_reg->app_cb.p_disc_res_cb)( - p_clcb->conn_id, static_cast(p_clcb->op_subtype), - &p_clcb->read_uuid128.result); + bluetooth::Uuid::From128BitLE(p); + if (p_clcb->p_reg->app_cb.p_disc_res_cb) { + (*p_clcb->p_reg->app_cb.p_disc_res_cb)(p_clcb->conn_id, + static_cast(p_clcb->op_subtype), + &p_clcb->read_uuid128.result); + } gatt_act_discovery(p_clcb); } else { gatt_end_operation(p_clcb, GATT_INVALID_PDU, (void*)p); @@ -1078,9 +1056,7 @@ void gatt_process_read_rsp(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, * Returns void * ******************************************************************************/ -void gatt_process_handle_rsp(tGATT_CLCB* p_clcb) { - gatt_end_operation(p_clcb, GATT_SUCCESS, NULL); -} +void gatt_process_handle_rsp(tGATT_CLCB* p_clcb) { gatt_end_operation(p_clcb, GATT_SUCCESS, NULL); } /******************************************************************************* * * Function gatt_process_mtu_rsp @@ -1091,8 +1067,7 @@ void gatt_process_handle_rsp(tGATT_CLCB* p_clcb) { * Returns void * ******************************************************************************/ -void gatt_process_mtu_rsp(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, uint16_t len, - uint8_t* p_data) { +void gatt_process_mtu_rsp(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, uint16_t len, uint8_t* p_data) { uint16_t mtu; tGATT_STATUS status = GATT_SUCCESS; @@ -1102,8 +1077,8 @@ void gatt_process_mtu_rsp(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, uint16_t len, } else { STREAM_TO_UINT16(mtu, p_data); - log::info("Local pending MTU {}, Remote ({}) MTU {}", - tcb.pending_user_mtu_exchange_value, tcb.peer_bda, mtu); + log::info("Local pending MTU {}, Remote ({}) MTU {}", tcb.pending_user_mtu_exchange_value, + tcb.peer_bda, mtu); /* Aim for default as we did in the request */ if (mtu < GATT_DEF_BLE_MTU_SIZE) { @@ -1112,14 +1087,12 @@ void gatt_process_mtu_rsp(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, uint16_t len, tcb.payload_size = std::min(mtu, (uint16_t)(gatt_get_local_mtu())); } - bluetooth::shim::arbiter::GetArbiter().OnIncomingMtuResp(tcb.tcb_idx, - tcb.payload_size); + bluetooth::shim::arbiter::GetArbiter().OnIncomingMtuResp(tcb.tcb_idx, tcb.payload_size); /* This is just to track the biggest MTU requested by the user. * This value will be used in the BTM_SetBleDataLength */ if (tcb.pending_user_mtu_exchange_value > tcb.max_user_mtu) { - tcb.max_user_mtu = - std::min(tcb.pending_user_mtu_exchange_value, tcb.payload_size); + tcb.max_user_mtu = std::min(tcb.pending_user_mtu_exchange_value, tcb.payload_size); } else if (tcb.pending_user_mtu_exchange_value == 0) { tcb.max_user_mtu = tcb.payload_size; } @@ -1155,15 +1128,13 @@ uint8_t gatt_cmd_to_rsp_code(uint8_t cmd_code) { bool gatt_cl_send_next_cmd_inq(tGATT_TCB& tcb) { std::deque* cl_cmd_q = nullptr; - while ( - gatt_is_outstanding_msg_in_att_send_queue(tcb) || - EattExtension::GetInstance()->IsOutstandingMsgInSendQueue(tcb.peer_bda)) { + while (gatt_is_outstanding_msg_in_att_send_queue(tcb) || + EattExtension::GetInstance()->IsOutstandingMsgInSendQueue(tcb.peer_bda)) { if (gatt_is_outstanding_msg_in_att_send_queue(tcb)) { cl_cmd_q = &tcb.cl_cmd_q; } else { EattChannel* channel = - EattExtension::GetInstance()->GetChannelWithQueuedDataToSend( - tcb.peer_bda); + EattExtension::GetInstance()->GetChannelWithQueuedDataToSend(tcb.peer_bda); cl_cmd_q = &channel->cl_cmd_q_; } @@ -1193,7 +1164,9 @@ bool gatt_cl_send_next_cmd_inq(tGATT_TCB& tcb) { gatt_end_operation(p_clcb, att_ret, NULL); /* if no ack needed, keep sending */ - if (att_ret == GATT_SUCCESS) continue; + if (att_ret == GATT_SUCCESS) { + continue; + } return true; } @@ -1206,8 +1179,7 @@ bool gatt_cl_send_next_cmd_inq(tGATT_TCB& tcb) { } /** This function is called to handle the server response to client */ -void gatt_client_handle_server_rsp(tGATT_TCB& tcb, uint16_t cid, - uint8_t op_code, uint16_t len, +void gatt_client_handle_server_rsp(tGATT_TCB& tcb, uint16_t cid, uint8_t op_code, uint16_t len, uint8_t* p_data) { log::verbose("opcode: 0x{:x} cid{}", op_code, cid); @@ -1216,8 +1188,7 @@ void gatt_client_handle_server_rsp(tGATT_TCB& tcb, uint16_t cid, if (op_code == GATT_HANDLE_VALUE_IND || op_code == GATT_HANDLE_VALUE_NOTIF || op_code == GATT_HANDLE_MULTI_VALUE_NOTIF) { if (len >= payload_size) { - log::error("invalid indicate pkt size: {}, PDU size: {}", len + 1, - payload_size); + log::error("invalid indicate pkt size: {}, PDU size: {}", len + 1, payload_size); return; } @@ -1241,10 +1212,8 @@ void gatt_client_handle_server_rsp(tGATT_TCB& tcb, uint16_t cid, } if (rsp_code != op_code && op_code != GATT_RSP_ERROR) { - log::warn( - "ATT - Ignore wrong response. Receives ({:02x}) Request({:02x}) " - "Ignored", - op_code, rsp_code); + log::warn("ATT - Ignore wrong response. Receives ({:02x}) Request({:02x}) Ignored", op_code, + rsp_code); return; } @@ -1255,8 +1224,7 @@ void gatt_client_handle_server_rsp(tGATT_TCB& tcb, uint16_t cid, /* The message has to be smaller than the agreed MTU, len does not count * op_code */ if (len >= payload_size) { - log::error("invalid response pkt size: {}, PDU size: {}", len + 1, - payload_size); + log::error("invalid response pkt size: {}, PDU size: {}", len + 1, payload_size); gatt_end_operation(p_clcb, GATT_ERROR, NULL); } else { switch (op_code) { diff --git a/system/stack/gatt/gatt_db.cc b/system/stack/gatt/gatt_db.cc index 4f376509818..f15b0446631 100644 --- a/system/stack/gatt/gatt_db.cc +++ b/system/stack/gatt/gatt_db.cc @@ -38,17 +38,16 @@ using namespace bluetooth; /******************************************************************************* * L O C A L F U N C T I O N P R O T O T Y P E S * ******************************************************************************/ -static tGATT_ATTR& allocate_attr_in_db(tGATT_SVC_DB& db, const Uuid& uuid, - tGATT_PERM perm); -static tGATT_STATUS gatts_send_app_read_request( - tGATT_TCB& tcb, uint16_t cid, uint8_t op_code, uint16_t handle, - uint16_t offset, uint32_t trans_id, bt_gatt_db_attribute_type_t gatt_type); +static tGATT_ATTR& allocate_attr_in_db(tGATT_SVC_DB& db, const Uuid& uuid, tGATT_PERM perm); +static tGATT_STATUS gatts_send_app_read_request(tGATT_TCB& tcb, uint16_t cid, uint8_t op_code, + uint16_t handle, uint16_t offset, uint32_t trans_id, + bt_gatt_db_attribute_type_t gatt_type); /** * Initialize a memory space to be a service database. */ -void gatts_init_service_db(tGATT_SVC_DB& db, const Uuid& service_uuid, - bool is_pri, uint16_t s_hdl, uint16_t num_handle) { +void gatts_init_service_db(tGATT_SVC_DB& db, const Uuid& service_uuid, bool is_pri, uint16_t s_hdl, + uint16_t num_handle) { db.attr_list.reserve(num_handle); log::verbose("s_hdl= {} num_handle= {}", s_hdl, num_handle); @@ -58,8 +57,7 @@ void gatts_init_service_db(tGATT_SVC_DB& db, const Uuid& service_uuid, db.end_handle = s_hdl + num_handle; /* add service declration record */ - Uuid uuid = - Uuid::From16Bit(is_pri ? GATT_UUID_PRI_SERVICE : GATT_UUID_SEC_SERVICE); + Uuid uuid = Uuid::From16Bit(is_pri ? GATT_UUID_PRI_SERVICE : GATT_UUID_SEC_SERVICE); tGATT_ATTR& attr = allocate_attr_in_db(db, uuid, GATT_PERM_READ); attr.p_value.reset(new tGATT_ATTR_VALUE); attr.p_value->uuid = service_uuid; @@ -75,15 +73,13 @@ Uuid* gatts_get_service_uuid(tGATT_SVC_DB* p_db) { } /** Check attribute readability. Returns status of operation. */ -static tGATT_STATUS gatts_check_attr_readability(const tGATT_ATTR& attr, - uint16_t /* offset */, - bool read_long, - tGATT_SEC_FLAG sec_flag, +static tGATT_STATUS gatts_check_attr_readability(const tGATT_ATTR& attr, uint16_t /* offset */, + bool read_long, tGATT_SEC_FLAG sec_flag, uint8_t key_size) { uint16_t min_key_size; tGATT_PERM perm = attr.permission; - min_key_size = (((perm & GATT_ENCRYPT_KEY_SIZE_MASK) >> 12)); + min_key_size = ((perm & GATT_ENCRYPT_KEY_SIZE_MASK) >> 12); if (min_key_size != 0) { min_key_size += 6; } @@ -93,8 +89,7 @@ static tGATT_STATUS gatts_check_attr_readability(const tGATT_ATTR& attr, return GATT_READ_NOT_PERMIT; } - if ((perm & GATT_READ_AUTH_REQUIRED) && !sec_flag.is_link_key_known && - !sec_flag.is_encrypted) { + if ((perm & GATT_READ_AUTH_REQUIRED) && !sec_flag.is_link_key_known && !sec_flag.is_encrypted) { log::error("GATT_INSUF_AUTHENTICATION"); return GATT_INSUF_AUTHENTICATION; } @@ -109,8 +104,7 @@ static tGATT_STATUS gatts_check_attr_readability(const tGATT_ATTR& attr, return GATT_INSUF_ENCRYPTION; } - if ((perm & GATT_READ_ENCRYPTED_REQUIRED) && sec_flag.is_encrypted && - (key_size < min_key_size)) { + if ((perm & GATT_READ_ENCRYPTED_REQUIRED) && sec_flag.is_encrypted && (key_size < min_key_size)) { log::error("GATT_INSUF_KEY_SIZE"); return GATT_INSUF_KEY_SIZE; } @@ -167,18 +161,18 @@ static tGATT_STATUS gatts_check_attr_readability(const tGATT_ATTR& attr, * Returns status of operation. * ******************************************************************************/ -static tGATT_STATUS read_attr_value(tGATT_ATTR& attr16, uint16_t offset, - uint8_t** p_data, bool read_long, - uint16_t mtu, uint16_t* p_len, +static tGATT_STATUS read_attr_value(tGATT_ATTR& attr16, uint16_t offset, uint8_t** p_data, + bool read_long, uint16_t mtu, uint16_t* p_len, tGATT_SEC_FLAG sec_flag, uint8_t key_size) { uint8_t* p = *p_data; - log::verbose("uuid={} perm=0x{:02x} offset={} read_long={}", attr16.uuid, - attr16.permission, offset, read_long); + log::verbose("uuid={} perm=0x{:02x} offset={} read_long={}", attr16.uuid, attr16.permission, + offset, read_long); - tGATT_STATUS status = gatts_check_attr_readability(attr16, offset, read_long, - sec_flag, key_size); - if (status != GATT_SUCCESS) return status; + tGATT_STATUS status = gatts_check_attr_readability(attr16, offset, read_long, sec_flag, key_size); + if (status != GATT_SUCCESS) { + return status; + } if (!attr16.uuid.Is16Bit()) { /* characteristic description or characteristic value */ @@ -189,7 +183,9 @@ static tGATT_STATUS read_attr_value(tGATT_ATTR& attr16, uint16_t offset, if (uuid16 == GATT_UUID_PRI_SERVICE || uuid16 == GATT_UUID_SEC_SERVICE) { *p_len = gatt_build_uuid_to_stream_len(attr16.p_value->uuid); - if (mtu < *p_len) return GATT_NO_RESOURCES; + if (mtu < *p_len) { + return GATT_NO_RESOURCES; + } gatt_build_uuid_to_stream(&p, attr16.p_value->uuid); *p_data = p; @@ -201,7 +197,9 @@ static tGATT_STATUS read_attr_value(tGATT_ATTR& attr16, uint16_t offset, uint8_t val_len = val_attr->uuid.GetShortestRepresentationSize(); *p_len = (val_len == Uuid::kNumBytes16) ? 5 : 19; - if (mtu < *p_len) return GATT_NO_RESOURCES; + if (mtu < *p_len) { + return GATT_NO_RESOURCES; + } UINT8_TO_STREAM(p, attr16.p_value->char_decl.property); UINT16_TO_STREAM(p, attr16.p_value->char_decl.char_val_handle); @@ -218,12 +216,15 @@ static tGATT_STATUS read_attr_value(tGATT_ATTR& attr16, uint16_t offset, if (uuid16 == GATT_UUID_INCLUDE_SERVICE) { tGATT_INCL_SRVC& incl_handle = attr16.p_value->incl_handle; - if (incl_handle.service_type.Is16Bit()) + if (incl_handle.service_type.Is16Bit()) { *p_len = 6; - else + } else { *p_len = 4; + } - if (mtu < *p_len) return GATT_NO_RESOURCES; + if (mtu < *p_len) { + return GATT_NO_RESOURCES; + } UINT16_TO_STREAM(p, incl_handle.s_handle); UINT16_TO_STREAM(p, incl_handle.e_handle); @@ -238,8 +239,7 @@ static tGATT_STATUS read_attr_value(tGATT_ATTR& attr16, uint16_t offset, if (uuid16 == GATT_UUID_CHAR_EXT_PROP) { // sometimes this descriptor is added by users manually, we need to check if // the p_value is nullptr. - uint16_t char_ext_prop = - attr16.p_value ? attr16.p_value->char_ext_prop : 0x0000; + uint16_t char_ext_prop = attr16.p_value ? attr16.p_value->char_ext_prop : 0x0000; *p_len = 2; if (mtu < *p_len) { @@ -273,11 +273,12 @@ static tGATT_STATUS read_attr_value(tGATT_ATTR& attr16, uint16_t offset, * Returns Status of the operation. * ******************************************************************************/ -tGATT_STATUS gatts_db_read_attr_value_by_type( - tGATT_TCB& tcb, uint16_t cid, tGATT_SVC_DB* p_db, uint8_t op_code, - BT_HDR* p_rsp, uint16_t s_handle, uint16_t /* e_handle */, const Uuid& type, - uint16_t* p_len, tGATT_SEC_FLAG sec_flag, uint8_t key_size, - uint32_t trans_id, uint16_t* p_cur_handle) { +tGATT_STATUS gatts_db_read_attr_value_by_type(tGATT_TCB& tcb, uint16_t cid, tGATT_SVC_DB* p_db, + uint8_t op_code, BT_HDR* p_rsp, uint16_t s_handle, + uint16_t /* e_handle */, const Uuid& type, + uint16_t* p_len, tGATT_SEC_FLAG sec_flag, + uint8_t key_size, uint32_t trans_id, + uint16_t* p_cur_handle) { tGATT_STATUS status = GATT_NOT_FOUND; uint16_t len = 0; uint8_t* p = (uint8_t*)(p_rsp + 1) + p_rsp->len + L2CAP_MIN_OFFSET; @@ -292,17 +293,19 @@ tGATT_STATUS gatts_db_read_attr_value_by_type( UINT16_TO_STREAM(p, attr.handle); - status = read_attr_value(attr, 0, &p, false, (uint16_t)(*p_len - 2), - &len, sec_flag, key_size); + status = read_attr_value(attr, 0, &p, false, (uint16_t)(*p_len - 2), &len, sec_flag, + key_size); if (status == GATT_PENDING) { - status = gatts_send_app_read_request(tcb, cid, op_code, attr.handle, - 0, trans_id, attr.gatt_type); + status = gatts_send_app_read_request(tcb, cid, op_code, attr.handle, 0, trans_id, + attr.gatt_type); /* one callback at a time */ break; } else if (status == GATT_SUCCESS) { - if (p_rsp->offset == 0) p_rsp->offset = len + 2; + if (p_rsp->offset == 0) { + p_rsp->offset = len + 2; + } if (p_rsp->offset == len + 2) { p_rsp->len += (len + 2); @@ -332,12 +335,11 @@ tGATT_STATUS gatts_db_read_attr_value_by_type( * Returns Status of the operation. * */ -uint16_t gatts_add_included_service(tGATT_SVC_DB& db, uint16_t s_handle, - uint16_t e_handle, const Uuid& service) { +uint16_t gatts_add_included_service(tGATT_SVC_DB& db, uint16_t s_handle, uint16_t e_handle, + const Uuid& service) { Uuid uuid = Uuid::From16Bit(GATT_UUID_INCLUDE_SERVICE); - log::verbose("s_hdl=0x{:04x} e_hdl=0x{:04x} service uuid = {}", s_handle, - e_handle, service); + log::verbose("s_hdl=0x{:04x} e_hdl=0x{:04x} service uuid = {}", s_handle, e_handle, service); if (service.IsEmpty() || s_handle == 0 || e_handle == 0) { log::error("Illegal Params."); @@ -370,8 +372,7 @@ uint16_t gatts_add_included_service(tGATT_SVC_DB& db, uint16_t s_handle, * Returns Status of te operation. * ******************************************************************************/ -uint16_t gatts_add_characteristic(tGATT_SVC_DB& db, tGATT_PERM perm, - tGATT_CHAR_PROP property, +uint16_t gatts_add_characteristic(tGATT_SVC_DB& db, tGATT_PERM perm, tGATT_CHAR_PROP property, const Uuid& char_uuid) { Uuid uuid = Uuid::From16Bit(GATT_UUID_CHAR_DECLARE); @@ -400,8 +401,7 @@ uint16_t gatts_add_characteristic(tGATT_SVC_DB& db, tGATT_PERM perm, * Returns Status of the operation. * ******************************************************************************/ -uint16_t gatts_add_char_ext_prop_descr( - tGATT_SVC_DB& db, uint16_t extended_properties) { +uint16_t gatts_add_char_ext_prop_descr(tGATT_SVC_DB& db, uint16_t extended_properties) { Uuid descr_uuid = Uuid::From16Bit(GATT_UUID_CHAR_EXT_PROP); log::verbose("gatts_add_char_ext_prop_descr uuid={}", descr_uuid.ToString()); @@ -422,14 +422,13 @@ uint16_t gatts_add_char_ext_prop_descr( * * Parameter p_db: database pointer. * perm: characteristic descriptor permission type. - * char_dscp_tpye: the characteristic descriptor masks. + * char_dscp_type: the characteristic descriptor masks. * p_dscp_params: characteristic descriptors values. * * Returns Status of the operation. * ******************************************************************************/ -uint16_t gatts_add_char_descr(tGATT_SVC_DB& db, tGATT_PERM perm, - const Uuid& descr_uuid) { +uint16_t gatts_add_char_descr(tGATT_SVC_DB& db, tGATT_PERM perm, const Uuid& descr_uuid) { log::verbose("gatts_add_char_descr uuid={}", descr_uuid.ToString()); /* Add characteristic descriptors */ @@ -442,11 +441,17 @@ uint16_t gatts_add_char_descr(tGATT_SVC_DB& db, tGATT_PERM perm, /* Service Attribute Database Query Utility Functions */ /******************************************************************************/ tGATT_ATTR* find_attr_by_handle(tGATT_SVC_DB* p_db, uint16_t handle) { - if (!p_db) return nullptr; + if (!p_db) { + return nullptr; + } for (auto& attr : p_db->attr_list) { - if (attr.handle == handle) return &attr; - if (attr.handle > handle) return nullptr; + if (attr.handle == handle) { + return &attr; + } + if (attr.handle > handle) { + return nullptr; + } } return nullptr; @@ -471,22 +476,23 @@ tGATT_ATTR* find_attr_by_handle(tGATT_SVC_DB* p_db, uint16_t handle) { * Returns Status of operation. * ******************************************************************************/ -tGATT_STATUS gatts_read_attr_value_by_handle( - tGATT_TCB& tcb, uint16_t cid, tGATT_SVC_DB* p_db, uint8_t op_code, - uint16_t handle, uint16_t offset, uint8_t* p_value, uint16_t* p_len, - uint16_t mtu, tGATT_SEC_FLAG sec_flag, uint8_t key_size, - uint32_t trans_id) { +tGATT_STATUS gatts_read_attr_value_by_handle(tGATT_TCB& tcb, uint16_t cid, tGATT_SVC_DB* p_db, + uint8_t op_code, uint16_t handle, uint16_t offset, + uint8_t* p_value, uint16_t* p_len, uint16_t mtu, + tGATT_SEC_FLAG sec_flag, uint8_t key_size, + uint32_t trans_id) { tGATT_ATTR* p_attr = find_attr_by_handle(p_db, handle); - if (!p_attr) return GATT_NOT_FOUND; + if (!p_attr) { + return GATT_NOT_FOUND; + } uint8_t* pp = p_value; - tGATT_STATUS status = read_attr_value(*p_attr, offset, &pp, - (bool)(op_code == GATT_REQ_READ_BLOB), + tGATT_STATUS status = read_attr_value(*p_attr, offset, &pp, (bool)(op_code == GATT_REQ_READ_BLOB), mtu, p_len, sec_flag, key_size); if (status == GATT_PENDING) { - status = gatts_send_app_read_request(tcb, cid, op_code, p_attr->handle, - offset, trans_id, p_attr->gatt_type); + status = gatts_send_app_read_request(tcb, cid, op_code, p_attr->handle, offset, trans_id, + p_attr->gatt_type); } return status; } @@ -510,12 +516,12 @@ tGATT_STATUS gatts_read_attr_value_by_handle( * Returns Status of operation. * ******************************************************************************/ -tGATT_STATUS gatts_read_attr_perm_check(tGATT_SVC_DB* p_db, bool is_long, - uint16_t handle, - tGATT_SEC_FLAG sec_flag, - uint8_t key_size) { +tGATT_STATUS gatts_read_attr_perm_check(tGATT_SVC_DB* p_db, bool is_long, uint16_t handle, + tGATT_SEC_FLAG sec_flag, uint8_t key_size) { tGATT_ATTR* p_attr = find_attr_by_handle(p_db, handle); - if (!p_attr) return GATT_NOT_FOUND; + if (!p_attr) { + return GATT_NOT_FOUND; + } return gatts_check_attr_readability(*p_attr, 0, is_long, sec_flag, key_size); } @@ -538,27 +544,26 @@ tGATT_STATUS gatts_read_attr_perm_check(tGATT_SVC_DB* p_db, bool is_long, * Returns Status of the operation. * ******************************************************************************/ -tGATT_STATUS gatts_write_attr_perm_check(tGATT_SVC_DB* p_db, uint8_t op_code, - uint16_t handle, uint16_t offset, - uint8_t* p_data, uint16_t len, - tGATT_SEC_FLAG sec_flag, - uint8_t key_size) { - log::verbose("op_code=0x{:x} handle=0x{:04x} offset={} len={} key_size={}", - op_code, handle, offset, len, key_size); +tGATT_STATUS gatts_write_attr_perm_check(tGATT_SVC_DB* p_db, uint8_t op_code, uint16_t handle, + uint16_t offset, uint8_t* p_data, uint16_t len, + tGATT_SEC_FLAG sec_flag, uint8_t key_size) { + log::verbose("op_code=0x{:x} handle=0x{:04x} offset={} len={} key_size={}", op_code, handle, + offset, len, key_size); tGATT_ATTR* p_attr = find_attr_by_handle(p_db, handle); - if (!p_attr) return GATT_NOT_FOUND; + if (!p_attr) { + return GATT_NOT_FOUND; + } tGATT_PERM perm = p_attr->permission; - uint16_t min_key_size = (((perm & GATT_ENCRYPT_KEY_SIZE_MASK) >> 12)); + uint16_t min_key_size = ((perm & GATT_ENCRYPT_KEY_SIZE_MASK) >> 12); if (min_key_size != 0) { min_key_size += 6; } - log::verbose("p_attr->permission =0x{:04x} min_key_size==0x{:04x}", - p_attr->permission, min_key_size); + log::verbose("p_attr->permission =0x{:04x} min_key_size==0x{:04x}", p_attr->permission, + min_key_size); - if ((op_code == GATT_CMD_WRITE || op_code == GATT_REQ_WRITE) && - (perm & GATT_WRITE_SIGNED_PERM)) { + if ((op_code == GATT_CMD_WRITE || op_code == GATT_REQ_WRITE) && (perm & GATT_WRITE_SIGNED_PERM)) { /* use the rules for the mixed security see section 10.2.3*/ /* use security mode 1 level 2 when the following condition follows */ /* LE security mode 2 level 1 and LE security mode 1 level 2 */ @@ -567,11 +572,9 @@ tGATT_STATUS gatts_write_attr_perm_check(tGATT_SVC_DB* p_db, uint8_t op_code, } /* use security mode 1 level 3 when the following condition follows */ /* LE security mode 2 level 2 and security mode 1 and LE */ - else if (((perm & GATT_PERM_WRITE_SIGNED_MITM) && - (perm & GATT_PERM_WRITE_ENCRYPTED)) || + else if (((perm & GATT_PERM_WRITE_SIGNED_MITM) && (perm & GATT_PERM_WRITE_ENCRYPTED)) || /* LE security mode 2 and security mode 1 level 3 */ - ((perm & GATT_WRITE_SIGNED_PERM) && - (perm & GATT_PERM_WRITE_ENC_MITM))) { + ((perm & GATT_WRITE_SIGNED_PERM) && (perm & GATT_PERM_WRITE_ENC_MITM))) { perm = GATT_PERM_WRITE_ENC_MITM; } } @@ -592,8 +595,7 @@ tGATT_STATUS gatts_write_attr_perm_check(tGATT_SVC_DB* p_db, uint8_t op_code, else if ((perm & GATT_WRITE_AUTH_REQUIRED) && !sec_flag.is_link_key_known) { status = GATT_INSUF_AUTHENTICATION; log::error("GATT_INSUF_AUTHENTICATION"); - } else if ((perm & GATT_WRITE_MITM_REQUIRED) && - !sec_flag.is_link_key_authed) { + } else if ((perm & GATT_WRITE_MITM_REQUIRED) && !sec_flag.is_link_key_authed) { status = GATT_INSUF_AUTHENTICATION; log::error("GATT_INSUF_AUTHENTICATION: MITM required"); } else if ((perm & GATT_WRITE_ENCRYPTED_PERM) && !sec_flag.is_encrypted) { @@ -643,9 +645,8 @@ tGATT_STATUS gatts_write_attr_perm_check(tGATT_SVC_DB* p_db, uint8_t op_code, } /* these attribute does not allow write blob */ - if (p_attr->uuid.Is16Bit() && - (p_attr->uuid.As16Bit() == GATT_UUID_CHAR_CLIENT_CONFIG || - p_attr->uuid.As16Bit() == GATT_UUID_CHAR_SRVR_CONFIG)) { + if (p_attr->uuid.Is16Bit() && (p_attr->uuid.As16Bit() == GATT_UUID_CHAR_CLIENT_CONFIG || + p_attr->uuid.As16Bit() == GATT_UUID_CHAR_SRVR_CONFIG)) { if (op_code == GATT_REQ_PREPARE_WRITE && offset != 0) { /* does not allow write blob */ status = GATT_NOT_LONG; @@ -674,11 +675,10 @@ tGATT_STATUS gatts_write_attr_perm_check(tGATT_SVC_DB* p_db, uint8_t op_code, * Returns pointer to the newly allocated attribute. * */ -static tGATT_ATTR& allocate_attr_in_db(tGATT_SVC_DB& db, const Uuid& uuid, - tGATT_PERM perm) { +static tGATT_ATTR& allocate_attr_in_db(tGATT_SVC_DB& db, const Uuid& uuid, tGATT_PERM perm) { if (db.next_handle >= db.end_handle) { - log::fatal("wrong number of handles! handle_max = {}, next_handle = {}", - db.end_handle, db.next_handle); + log::fatal("wrong number of handles! handle_max = {}, next_handle = {}", db.end_handle, + db.next_handle); } db.attr_list.emplace_back(); @@ -698,9 +698,9 @@ static tGATT_ATTR& allocate_attr_in_db(tGATT_SVC_DB& db, const Uuid& uuid, * Returns status of operation. * ******************************************************************************/ -static tGATT_STATUS gatts_send_app_read_request( - tGATT_TCB& tcb, uint16_t cid, uint8_t op_code, uint16_t handle, - uint16_t offset, uint32_t trans_id, bt_gatt_db_attribute_type_t gatt_type) { +static tGATT_STATUS gatts_send_app_read_request(tGATT_TCB& tcb, uint16_t cid, uint8_t op_code, + uint16_t handle, uint16_t offset, uint32_t trans_id, + bt_gatt_db_attribute_type_t gatt_type) { tGATT_SRV_LIST_ELEM& el = *gatt_sr_find_i_rcb_by_handle(handle); uint16_t conn_id = GATT_CREATE_CONN_ID(tcb.tcb_idx, el.gatt_if); @@ -724,13 +724,13 @@ static tGATT_STATUS gatts_send_app_read_request( opcode = GATTS_REQ_TYPE_READ_CHARACTERISTIC; } else { log::error( - "Attempt to read attribute that's not tied with characteristic or " - "descriptor value."); + "Attempt to read attribute that's not tied with characteristic or descriptor value."); return GATT_ERROR; } gatt_sr_send_req_callback(conn_id, trans_id, opcode, &sr_data); return (tGATT_STATUS)GATT_PENDING; - } else + } else { return (tGATT_STATUS)GATT_BUSY; /* max pending command, application error */ + } } diff --git a/system/stack/gatt/gatt_int.h b/system/stack/gatt/gatt_int.h index 67cd5c9941e..79153437bc2 100644 --- a/system/stack/gatt/gatt_int.h +++ b/system/stack/gatt/gatt_int.h @@ -93,7 +93,7 @@ typedef struct { } tGATT_SEC_FLAG; /* Find Information Response Type -*/ + */ #define GATT_INFO_TYPE_PAIR_16 0x01 #define GATT_INFO_TYPE_PAIR_128 0x02 @@ -102,16 +102,15 @@ constexpr bool kGattDisconnected = !kGattConnected; /* GATT client FIND_TYPE_VALUE_Request data */ typedef struct { - bluetooth::Uuid uuid; /* type of attribute to be found */ - uint16_t s_handle; /* starting handle */ - uint16_t e_handle; /* ending handle */ - uint16_t value_len; /* length of the attribute value */ - uint8_t - value[GATT_MAX_MTU_SIZE]; /* pointer to the attribute value to be found */ + bluetooth::Uuid uuid; /* type of attribute to be found */ + uint16_t s_handle; /* starting handle */ + uint16_t e_handle; /* ending handle */ + uint16_t value_len; /* length of the attribute value */ + uint8_t value[GATT_MAX_MTU_SIZE]; /* pointer to the attribute value to be found */ } tGATT_FIND_TYPE_VALUE; /* client request message to ATT protocol -*/ + */ typedef union { tGATT_READ_BY_TYPE browse; /* read by type request */ tGATT_FIND_TYPE_VALUE find_type_value; /* find by type value */ @@ -133,7 +132,7 @@ typedef struct { } tGATT_ERROR; /* server response message to ATT protocol -*/ + */ typedef union { /* data type member event */ tGATT_VALUE attr_value; /* READ, HANDLE_VALUE_IND, PREPARE_WRITE */ @@ -144,14 +143,14 @@ typedef union { } tGATT_SR_MSG; /* Characteristic declaration attribute value -*/ + */ typedef struct { tGATT_CHAR_PROP property; uint16_t char_val_handle; } tGATT_CHAR_DECL; /* attribute value maintained in the server database -*/ + */ typedef union { bluetooth::Uuid uuid; /* service declaration */ tGATT_CHAR_DECL char_decl; /* characteristic declaration */ @@ -160,14 +159,14 @@ typedef union { } tGATT_ATTR_VALUE; /* Attribute UUID type -*/ + */ #define GATT_ATTR_UUID_TYPE_16 0 #define GATT_ATTR_UUID_TYPE_128 1 #define GATT_ATTR_UUID_TYPE_32 2 typedef uint8_t tGATT_ATTR_UUID_TYPE; /* 16 bits UUID Attribute in server database -*/ + */ typedef struct { std::unique_ptr p_value; tGATT_PERM permission; @@ -177,11 +176,11 @@ typedef struct { } tGATT_ATTR; /* Service Database definition -*/ + */ typedef struct { std::vector attr_list; /* pointer to the attributes */ - uint16_t end_handle; /* Last handle number */ - uint16_t next_handle; /* Next usable handle value */ + uint16_t end_handle; /* Last handle number */ + uint16_t next_handle; /* Next usable handle value */ } tGATT_SVC_DB; /* Data Structure used for GATT server */ @@ -280,13 +279,13 @@ typedef struct hdl_list_elem { /* A service registration information record consists of beginning and ending */ /* attribute handle, service UUID and a set of GATT server callback. */ typedef struct { - tGATT_SVC_DB* p_db; /* pointer to the service database */ + tGATT_SVC_DB* p_db; /* pointer to the service database */ bluetooth::Uuid app_uuid; /* application UUID */ - uint32_t sdp_handle; /* primamry service SDP handle */ - uint16_t type; /* service type UUID, primary or secondary */ - uint16_t s_hdl; /* service starting handle */ - uint16_t e_hdl; /* service ending handle */ - tGATT_IF gatt_if; /* this service is belong to which application */ + uint32_t sdp_handle; /* primamry service SDP handle */ + uint16_t type; /* service type UUID, primary or secondary */ + uint16_t s_hdl; /* service starting handle */ + uint16_t e_hdl; /* service ending handle */ + tGATT_IF gatt_if; /* this service is belong to which application */ bool is_primary; } tGATT_SRV_LIST_ELEM; @@ -347,8 +346,7 @@ typedef struct { /* logic channel */ typedef struct { - uint16_t - next_disc_start_hdl; /* starting handle for the next inc srvv discovery */ + uint16_t next_disc_start_hdl; /* starting handle for the next inc srvv discovery */ tGATT_DISC_RES result; bool wait_for_read_rsp; } tGATT_READ_INC_UUID128; @@ -358,10 +356,10 @@ struct tGATT_CLCB { uint8_t sccb_idx; uint8_t* p_attr_buf; /* attribute buffer for read multiple, prepare write */ bluetooth::Uuid uuid; - uint16_t conn_id; /* connection handle */ + uint16_t conn_id; /* connection handle */ uint16_t s_handle; /* starting handle of the active request */ uint16_t e_handle; /* ending handle of the active request */ - uint16_t counter; /* used as offset, attribute length, num of prepare write */ + uint16_t counter; /* used as offset, attribute length, num of prepare write */ uint16_t start_offset; tGATT_AUTH_REQ auth_req; /* authentication requirement */ tGATTC_OPTYPE operation; /* one logic channel can have one operation active */ @@ -406,9 +404,9 @@ typedef struct { tGATT_TCB tcb[GATT_MAX_PHY_CHANNEL]; fixed_queue_t* sign_op_queue; - uint16_t next_handle; /* next available handle */ + uint16_t next_handle; /* next available handle */ uint16_t last_service_handle; /* handle of last service */ - tGATT_SVC_CHG gattp_attr; /* GATT profile attribute service change */ + tGATT_SVC_CHG gattp_attr; /* GATT profile attribute service change */ tGATT_IF gatt_if; std::list* hdl_list_info; std::list* srv_list_info; @@ -432,12 +430,10 @@ typedef struct { #endif tGATT_PROFILE_CLCB profile_clcb[GATT_MAX_APPS]; - uint16_t - handle_of_h_r; /* Handle of the handles reused characteristic value */ + uint16_t handle_of_h_r; /* Handle of the handles reused characteristic value */ uint16_t handle_cl_supported_feat; uint16_t handle_sr_supported_feat; - uint8_t - gatt_svr_supported_feat_mask; /* Local supported features as a server */ + uint8_t gatt_svr_supported_feat_mask; /* Local supported features as a server */ /* Supported features as a client. To be written to remote device. * Note this is NOT a value of the characteristic with handle @@ -465,20 +461,17 @@ void gatt_set_err_rsp(bool enable, uint8_t req_op_code, uint8_t err_status); /* from gatt_main.cc */ bool gatt_disconnect(tGATT_TCB* p_tcb); -bool gatt_act_connect(tGATT_REG* p_reg, const RawAddress& bd_addr, - tBT_TRANSPORT transport, int8_t initiating_phys); -bool gatt_act_connect(tGATT_REG* p_reg, const RawAddress& bd_addr, - tBLE_ADDR_TYPE addr_type, tBT_TRANSPORT transport, +bool gatt_act_connect(tGATT_REG* p_reg, const RawAddress& bd_addr, tBT_TRANSPORT transport, int8_t initiating_phys); -bool gatt_connect(const RawAddress& rem_bda, tGATT_TCB* p_tcb, - tBT_TRANSPORT transport, uint8_t initiating_phys, - tGATT_IF gatt_if); -bool gatt_connect(const RawAddress& rem_bda, tGATT_TCB* p_tcb, - tBLE_ADDR_TYPE addr_type, tBT_TRANSPORT transport, +bool gatt_act_connect(tGATT_REG* p_reg, const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type, + tBT_TRANSPORT transport, int8_t initiating_phys); +bool gatt_connect(const RawAddress& rem_bda, tGATT_TCB* p_tcb, tBT_TRANSPORT transport, uint8_t initiating_phys, tGATT_IF gatt_if); +bool gatt_connect(const RawAddress& rem_bda, tGATT_TCB* p_tcb, tBLE_ADDR_TYPE addr_type, + tBT_TRANSPORT transport, uint8_t initiating_phys, tGATT_IF gatt_if); void gatt_data_process(tGATT_TCB& p_tcb, uint16_t cid, BT_HDR* p_buf); -void gatt_update_app_use_link_flag(tGATT_IF gatt_if, tGATT_TCB* p_tcb, - bool is_add, bool check_acl_link); +void gatt_update_app_use_link_flag(tGATT_IF gatt_if, tGATT_TCB* p_tcb, bool is_add, + bool check_acl_link); void gatt_profile_db_init(void); void gatt_set_ch_state(tGATT_TCB* p_tcb, tGATT_CH_STATE ch_state); @@ -494,14 +487,12 @@ uint16_t gatt_profile_find_conn_id_by_bd_addr(const RawAddress& bda); bool gatt_profile_get_eatt_support(const RawAddress& remote_bda); void gatt_cl_init_sr_status(tGATT_TCB& tcb); -bool gatt_cl_read_sr_supp_feat_req( - const RawAddress& peer_bda, - base::OnceCallback cb); -bool gatt_cl_read_sirk_req( - const RawAddress& peer_bda, - base::OnceCallback - cb); +bool gatt_cl_read_sr_supp_feat_req(const RawAddress& peer_bda, + base::OnceCallback cb); +bool gatt_cl_read_sirk_req(const RawAddress& peer_bda, + base::OnceCallback + cb); bool gatt_sr_is_cl_multi_variable_len_notif_supported(tGATT_TCB& tcb); bool gatt_sr_is_cl_change_aware(tGATT_TCB& tcb); @@ -510,21 +501,18 @@ void gatt_sr_update_cl_status(tGATT_TCB& tcb, bool chg_aware); /* Functions provided by att_protocol.cc */ tGATT_STATUS attp_send_cl_confirmation_msg(tGATT_TCB& tcb, uint16_t cid); -tGATT_STATUS attp_send_cl_msg(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, - uint8_t op_code, tGATT_CL_MSG* p_msg); +tGATT_STATUS attp_send_cl_msg(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, uint8_t op_code, + tGATT_CL_MSG* p_msg); BT_HDR* attp_build_sr_msg(tGATT_TCB& tcb, uint8_t op_code, tGATT_SR_MSG* p_msg, uint16_t payload_size); tGATT_STATUS attp_send_sr_msg(tGATT_TCB& tcb, uint16_t cid, BT_HDR* p_msg); -tGATT_STATUS attp_send_msg_to_l2cap(tGATT_TCB& tcb, uint16_t cid, - BT_HDR* p_toL2CAP); +tGATT_STATUS attp_send_msg_to_l2cap(tGATT_TCB& tcb, uint16_t cid, BT_HDR* p_toL2CAP); /* utility functions */ uint16_t gatt_get_local_mtu(void); char const* gatt_dbg_op_name(uint8_t op_code); -uint32_t gatt_add_sdp_record(const bluetooth::Uuid& uuid, uint16_t start_hdl, - uint16_t end_hdl); -bool gatt_parse_uuid_from_cmd(bluetooth::Uuid* p_uuid, uint16_t len, - uint8_t** p_data); +uint32_t gatt_add_sdp_record(const bluetooth::Uuid& uuid, uint16_t start_hdl, uint16_t end_hdl); +bool gatt_parse_uuid_from_cmd(bluetooth::Uuid* p_uuid, uint16_t len, uint8_t** p_data); uint8_t gatt_build_uuid_to_stream_len(const bluetooth::Uuid& uuid); uint8_t gatt_build_uuid_to_stream(uint8_t** p_dst, const bluetooth::Uuid& uuid); void gatt_sr_get_sec_info(const RawAddress& rem_bda, tBT_TRANSPORT transport, @@ -538,14 +526,13 @@ void gatt_indication_confirmation_timeout(void* data); void gatt_ind_ack_timeout(void* data); void gatt_start_ind_ack_timer(tGATT_TCB& tcb, uint16_t cid); void gatt_stop_ind_ack_timer(tGATT_TCB* p_tcb, uint16_t cid); -tGATT_STATUS gatt_send_error_rsp(tGATT_TCB& tcb, uint16_t cid, uint8_t err_code, - uint8_t op_code, uint16_t handle, bool deq); +tGATT_STATUS gatt_send_error_rsp(tGATT_TCB& tcb, uint16_t cid, uint8_t err_code, uint8_t op_code, + uint16_t handle, bool deq); bool gatt_is_srv_chg_ind_pending(tGATT_TCB* p_tcb); tGATTS_SRV_CHG* gatt_is_bda_in_the_srv_chg_clt_list(const RawAddress& bda); -bool gatt_find_the_connected_bda(uint8_t start_idx, RawAddress& bda, - uint8_t* p_found_idx, +bool gatt_find_the_connected_bda(uint8_t start_idx, RawAddress& bda, uint8_t* p_found_idx, tBT_TRANSPORT* p_transport); void gatt_set_srv_chg(void); void gatt_delete_dev_from_srv_chg_clt_list(const RawAddress& bd_addr); @@ -555,8 +542,7 @@ bool gatt_cl_send_next_cmd_inq(tGATT_TCB& tcb); /* reserved handle list */ std::list::iterator gatt_find_hdl_buffer_by_app_id( - const bluetooth::Uuid& app_uuid128, bluetooth::Uuid* p_svc_uuid, - uint16_t svc_inst); + const bluetooth::Uuid& app_uuid128, bluetooth::Uuid* p_svc_uuid, uint16_t svc_inst); tGATT_HDL_LIST_ELEM* gatt_find_hdl_buffer_by_handle(uint16_t handle); tGATTS_SRV_CHG* gatt_add_srv_chg_clt(tGATTS_SRV_CHG* p_srv_chg); @@ -564,25 +550,19 @@ tGATTS_SRV_CHG* gatt_add_srv_chg_clt(tGATTS_SRV_CHG* p_srv_chg); bool gatt_auto_connect_dev_remove(tGATT_IF gatt_if, const RawAddress& bd_addr); /* server function */ -std::list::iterator gatt_sr_find_i_rcb_by_handle( - uint16_t handle); -tGATT_STATUS gatt_sr_process_app_rsp(tGATT_TCB& tcb, tGATT_IF gatt_if, - uint32_t trans_id, uint8_t op_code, - tGATT_STATUS status, tGATTS_RSP* p_msg, +std::list::iterator gatt_sr_find_i_rcb_by_handle(uint16_t handle); +tGATT_STATUS gatt_sr_process_app_rsp(tGATT_TCB& tcb, tGATT_IF gatt_if, uint32_t trans_id, + uint8_t op_code, tGATT_STATUS status, tGATTS_RSP* p_msg, tGATT_SR_CMD* sr_res_p); -void gatt_server_handle_client_req(tGATT_TCB& p_tcb, uint16_t cid, - uint8_t op_code, uint16_t len, +void gatt_server_handle_client_req(tGATT_TCB& p_tcb, uint16_t cid, uint8_t op_code, uint16_t len, uint8_t* p_data); -void gatt_sr_send_req_callback(uint16_t conn_id, uint32_t trans_id, - uint8_t op_code, tGATTS_DATA* p_req_data); -uint32_t gatt_sr_enqueue_cmd(tGATT_TCB& tcb, uint16_t cid, uint8_t op_code, - uint16_t handle); +void gatt_sr_send_req_callback(uint16_t conn_id, uint32_t trans_id, uint8_t op_code, + tGATTS_DATA* p_req_data); +uint32_t gatt_sr_enqueue_cmd(tGATT_TCB& tcb, uint16_t cid, uint8_t op_code, uint16_t handle); bool gatt_cancel_open(tGATT_IF gatt_if, const RawAddress& bda); -void gatt_notify_phy_updated(tHCI_STATUS status, uint16_t handle, - uint8_t tx_phy, uint8_t rx_phy); -void gatt_notify_subrate_change(uint16_t handle, uint16_t subrate_factor, - uint16_t latency, uint16_t cont_num, - uint16_t timeout, uint8_t status); +void gatt_notify_phy_updated(tHCI_STATUS status, uint16_t handle, uint8_t tx_phy, uint8_t rx_phy); +void gatt_notify_subrate_change(uint16_t handle, uint16_t subrate_factor, uint16_t latency, + uint16_t cont_num, uint16_t timeout, uint8_t status); /* */ bool gatt_tcb_is_cid_busy(tGATT_TCB& tcb, uint16_t cid); @@ -591,19 +571,15 @@ tGATT_REG* gatt_get_regcb(tGATT_IF gatt_if); bool gatt_is_clcb_allocated(uint16_t conn_id); tGATT_CLCB* gatt_clcb_alloc(uint16_t conn_id); -bool gatt_tcb_get_cid_available_for_indication(tGATT_TCB* p_tcb, - bool eatt_support, - uint16_t** indicate_handle_p, - uint16_t* cid_p); -bool gatt_tcb_find_indicate_handle(tGATT_TCB& tcb, uint16_t cid, - uint16_t* indicated_handle_p); +bool gatt_tcb_get_cid_available_for_indication(tGATT_TCB* p_tcb, bool eatt_support, + uint16_t** indicate_handle_p, uint16_t* cid_p); +bool gatt_tcb_find_indicate_handle(tGATT_TCB& tcb, uint16_t cid, uint16_t* indicated_handle_p); uint16_t gatt_tcb_get_att_cid(tGATT_TCB& tcb, bool eatt_support); uint16_t gatt_tcb_get_payload_size(tGATT_TCB& tcb, uint16_t cid); void gatt_clcb_invalidate(tGATT_TCB* p_tcb, const tGATT_CLCB* p_clcb); uint16_t gatt_get_mtu(const RawAddress& bda, tBT_TRANSPORT transport); bool gatt_is_pending_mtu_exchange(tGATT_TCB* p_tcb); -void gatt_set_conn_id_waiting_for_mtu_exchange(tGATT_TCB* p_tcb, - uint16_t conn_id); +void gatt_set_conn_id_waiting_for_mtu_exchange(tGATT_TCB* p_tcb, uint16_t conn_id); void gatt_sr_copy_prep_cnt_to_cback_cnt(tGATT_TCB& p_tcb); bool gatt_sr_is_cback_cnt_zero(tGATT_TCB& p_tcb); @@ -613,24 +589,20 @@ void gatt_sr_reset_prep_cnt(tGATT_TCB& tcb); tGATT_SR_CMD* gatt_sr_get_cmd_by_trans_id(tGATT_TCB* p_tcb, uint32_t trans_id); tGATT_SR_CMD* gatt_sr_get_cmd_by_cid(tGATT_TCB& tcb, uint16_t cid); tGATT_READ_MULTI* gatt_sr_get_read_multi(tGATT_TCB& tcb, uint16_t cid); -void gatt_sr_update_cback_cnt(tGATT_TCB& p_tcb, uint16_t cid, tGATT_IF gatt_if, - bool is_inc, bool is_reset_first); -void gatt_sr_update_prep_cnt(tGATT_TCB& tcb, tGATT_IF gatt_if, bool is_inc, - bool is_reset_first); +void gatt_sr_update_cback_cnt(tGATT_TCB& p_tcb, uint16_t cid, tGATT_IF gatt_if, bool is_inc, + bool is_reset_first); +void gatt_sr_update_prep_cnt(tGATT_TCB& tcb, tGATT_IF gatt_if, bool is_inc, bool is_reset_first); tGATT_TCB* gatt_find_tcb_by_cid(uint16_t lcid); -tGATT_TCB* gatt_allocate_tcb_by_bdaddr(const RawAddress& bda, - tBT_TRANSPORT transport); +tGATT_TCB* gatt_allocate_tcb_by_bdaddr(const RawAddress& bda, tBT_TRANSPORT transport); tGATT_TCB* gatt_get_tcb_by_idx(uint8_t tcb_idx); -tGATT_TCB* gatt_find_tcb_by_addr(const RawAddress& bda, - tBT_TRANSPORT transport); +tGATT_TCB* gatt_find_tcb_by_addr(const RawAddress& bda, tBT_TRANSPORT transport); bool gatt_send_ble_burst_data(const RawAddress& remote_bda, BT_HDR* p_buf); /* GATT client functions */ void gatt_dequeue_sr_cmd(tGATT_TCB& tcb, uint16_t cid); -tGATT_STATUS gatt_send_write_msg(tGATT_TCB& p_tcb, tGATT_CLCB* p_clcb, - uint8_t op_code, uint16_t handle, uint16_t len, - uint16_t offset, uint8_t* p_data); +tGATT_STATUS gatt_send_write_msg(tGATT_TCB& p_tcb, tGATT_CLCB* p_clcb, uint8_t op_code, + uint16_t handle, uint16_t len, uint16_t offset, uint8_t* p_data); void gatt_cleanup_upon_disc(const RawAddress& bda, tGATT_DISCONN_REASON reason, tBT_TRANSPORT transport); void gatt_end_operation(tGATT_CLCB* p_clcb, tGATT_STATUS status, void* p_data); @@ -639,13 +611,10 @@ void gatt_act_discovery(tGATT_CLCB* p_clcb); void gatt_act_read(tGATT_CLCB* p_clcb, uint16_t offset); void gatt_act_write(tGATT_CLCB* p_clcb, uint8_t sec_act); tGATT_CLCB* gatt_cmd_dequeue(tGATT_TCB& tcb, uint16_t cid, uint8_t* p_opcode); -bool gatt_cmd_enq(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, bool to_send, - uint8_t op_code, BT_HDR* p_buf); -void gatt_client_handle_server_rsp(tGATT_TCB& tcb, uint16_t cid, - uint8_t op_code, uint16_t len, +bool gatt_cmd_enq(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, bool to_send, uint8_t op_code, BT_HDR* p_buf); +void gatt_client_handle_server_rsp(tGATT_TCB& tcb, uint16_t cid, uint8_t op_code, uint16_t len, uint8_t* p_data); -void gatt_send_queue_write_cancel(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, - tGATT_EXEC_FLAG flag); +void gatt_send_queue_write_cancel(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, tGATT_EXEC_FLAG flag); bool gatt_is_outstanding_msg_in_att_send_queue(const tGATT_TCB& tcb); /* gatt_auth.cc */ @@ -656,36 +625,30 @@ tGATT_SEC_ACTION gatt_get_sec_act(tGATT_TCB* p_tcb); void gatt_set_sec_act(tGATT_TCB* p_tcb, tGATT_SEC_ACTION sec_act); /* gatt_db.cc */ -void gatts_init_service_db(tGATT_SVC_DB& db, const bluetooth::Uuid& service, - bool is_pri, uint16_t s_hdl, uint16_t num_handle); -uint16_t gatts_add_included_service(tGATT_SVC_DB& db, uint16_t s_handle, - uint16_t e_handle, +void gatts_init_service_db(tGATT_SVC_DB& db, const bluetooth::Uuid& service, bool is_pri, + uint16_t s_hdl, uint16_t num_handle); +uint16_t gatts_add_included_service(tGATT_SVC_DB& db, uint16_t s_handle, uint16_t e_handle, const bluetooth::Uuid& service); -uint16_t gatts_add_characteristic(tGATT_SVC_DB& db, tGATT_PERM perm, - tGATT_CHAR_PROP property, +uint16_t gatts_add_characteristic(tGATT_SVC_DB& db, tGATT_PERM perm, tGATT_CHAR_PROP property, const bluetooth::Uuid& char_uuid); -uint16_t gatts_add_char_ext_prop_descr(tGATT_SVC_DB& db, - uint16_t extended_properties); -uint16_t gatts_add_char_descr(tGATT_SVC_DB& db, tGATT_PERM perm, - const bluetooth::Uuid& dscp_uuid); -tGATT_STATUS gatts_db_read_attr_value_by_type( - tGATT_TCB& tcb, uint16_t cid, tGATT_SVC_DB* p_db, uint8_t op_code, - BT_HDR* p_rsp, uint16_t s_handle, uint16_t e_handle, - const bluetooth::Uuid& type, uint16_t* p_len, tGATT_SEC_FLAG sec_flag, - uint8_t key_size, uint32_t trans_id, uint16_t* p_cur_handle); -tGATT_STATUS gatts_read_attr_value_by_handle( - tGATT_TCB& tcb, uint16_t cid, tGATT_SVC_DB* p_db, uint8_t op_code, - uint16_t handle, uint16_t offset, uint8_t* p_value, uint16_t* p_len, - uint16_t mtu, tGATT_SEC_FLAG sec_flag, uint8_t key_size, uint32_t trans_id); -tGATT_STATUS gatts_write_attr_perm_check(tGATT_SVC_DB* p_db, uint8_t op_code, - uint16_t handle, uint16_t offset, - uint8_t* p_data, uint16_t len, - tGATT_SEC_FLAG sec_flag, - uint8_t key_size); -tGATT_STATUS gatts_read_attr_perm_check(tGATT_SVC_DB* p_db, bool is_long, - uint16_t handle, - tGATT_SEC_FLAG sec_flag, - uint8_t key_size); +uint16_t gatts_add_char_ext_prop_descr(tGATT_SVC_DB& db, uint16_t extended_properties); +uint16_t gatts_add_char_descr(tGATT_SVC_DB& db, tGATT_PERM perm, const bluetooth::Uuid& dscp_uuid); +tGATT_STATUS gatts_db_read_attr_value_by_type(tGATT_TCB& tcb, uint16_t cid, tGATT_SVC_DB* p_db, + uint8_t op_code, BT_HDR* p_rsp, uint16_t s_handle, + uint16_t e_handle, const bluetooth::Uuid& type, + uint16_t* p_len, tGATT_SEC_FLAG sec_flag, + uint8_t key_size, uint32_t trans_id, + uint16_t* p_cur_handle); +tGATT_STATUS gatts_read_attr_value_by_handle(tGATT_TCB& tcb, uint16_t cid, tGATT_SVC_DB* p_db, + uint8_t op_code, uint16_t handle, uint16_t offset, + uint8_t* p_value, uint16_t* p_len, uint16_t mtu, + tGATT_SEC_FLAG sec_flag, uint8_t key_size, + uint32_t trans_id); +tGATT_STATUS gatts_write_attr_perm_check(tGATT_SVC_DB* p_db, uint8_t op_code, uint16_t handle, + uint16_t offset, uint8_t* p_data, uint16_t len, + tGATT_SEC_FLAG sec_flag, uint8_t key_size); +tGATT_STATUS gatts_read_attr_perm_check(tGATT_SVC_DB* p_db, bool is_long, uint16_t handle, + tGATT_SEC_FLAG sec_flag, uint8_t key_size); bluetooth::Uuid* gatts_get_service_uuid(tGATT_SVC_DB* p_db); /* gatt_sr_hash.cc */ diff --git a/system/stack/gatt/gatt_main.cc b/system/stack/gatt/gatt_main.cc index babce19aabc..88ef13fe011 100644 --- a/system/stack/gatt/gatt_main.cc +++ b/system/stack/gatt/gatt_main.cc @@ -58,23 +58,17 @@ using namespace bluetooth; /******************************************************************************/ /* L O C A L F U N C T I O N P R O T O T Y P E S */ /******************************************************************************/ -static void gatt_le_connect_cback(uint16_t chan, const RawAddress& bd_addr, - bool connected, uint16_t reason, - tBT_TRANSPORT transport); -static void gatt_le_data_ind(uint16_t chan, const RawAddress& bd_addr, - BT_HDR* p_buf); +static void gatt_le_connect_cback(uint16_t chan, const RawAddress& bd_addr, bool connected, + uint16_t reason, tBT_TRANSPORT transport); +static void gatt_le_data_ind(uint16_t chan, const RawAddress& bd_addr, BT_HDR* p_buf); static void gatt_le_cong_cback(const RawAddress& remote_bda, bool congest); -static void gatt_l2cif_connect_ind_cback(const RawAddress& bd_addr, - uint16_t l2cap_cid, uint16_t psm, - uint8_t l2cap_id); +static void gatt_l2cif_connect_ind_cback(const RawAddress& bd_addr, uint16_t l2cap_cid, + uint16_t psm, uint8_t l2cap_id); static void gatt_l2cif_connect_cfm_cback(uint16_t l2cap_cid, uint16_t result); -static void gatt_l2cif_config_ind_cback(uint16_t l2cap_cid, - tL2CAP_CFG_INFO* p_cfg); -static void gatt_l2cif_config_cfm_cback(uint16_t lcid, uint16_t result, - tL2CAP_CFG_INFO* p_cfg); -static void gatt_l2cif_disconnect_ind_cback(uint16_t l2cap_cid, - bool ack_needed); +static void gatt_l2cif_config_ind_cback(uint16_t l2cap_cid, tL2CAP_CFG_INFO* p_cfg); +static void gatt_l2cif_config_cfm_cback(uint16_t lcid, uint16_t result, tL2CAP_CFG_INFO* p_cfg); +static void gatt_l2cif_disconnect_ind_cback(uint16_t l2cap_cid, bool ack_needed); static void gatt_l2cif_disconnect(uint16_t l2cap_cid); static void gatt_l2cif_data_ind_cback(uint16_t l2cap_cid, BT_HDR* p_msg); static void gatt_send_conn_cback(tGATT_TCB* p_tcb); @@ -135,12 +129,11 @@ void gatt_init(void) { log::error("Unable to register L2CAP ATT fixed channel"); } - gatt_cb.over_br_enabled = - osi_property_get_bool("bluetooth.gatt.over_bredr.enabled", true); + gatt_cb.over_br_enabled = osi_property_get_bool("bluetooth.gatt.over_bredr.enabled", true); /* Now, register with L2CAP for ATT PSM over BR/EDR */ if (gatt_cb.over_br_enabled && - !L2CA_RegisterWithSecurity(BT_PSM_ATT, dyn_info, false /* enable_snoop */, - nullptr, GATT_MAX_MTU_SIZE, 0, BTM_SEC_NONE)) { + !L2CA_RegisterWithSecurity(BT_PSM_ATT, dyn_info, false /* enable_snoop */, nullptr, + GATT_MAX_MTU_SIZE, 0, BTM_SEC_NONE)) { log::error("ATT Dynamic Registration failed"); } @@ -190,8 +183,9 @@ void gatt_free(void) { fixed_queue_free(gatt_cb.tcb[i].sr_cmd.multi_rsp_q, NULL); gatt_cb.tcb[i].sr_cmd.multi_rsp_q = NULL; - if (gatt_cb.tcb[i].eatt) + if (gatt_cb.tcb[i].eatt) { EattExtension::GetInstance()->FreeGattResources(gatt_cb.tcb[i].peer_bda); + } } gatt_cb.hdl_list_info->clear(); @@ -216,15 +210,14 @@ void gatt_free(void) { * Returns true if connection is started, otherwise return false. * ******************************************************************************/ -bool gatt_connect(const RawAddress& rem_bda, tBLE_ADDR_TYPE addr_type, - tGATT_TCB* p_tcb, tBT_TRANSPORT transport, - uint8_t /* initiating_phys */, tGATT_IF gatt_if) { - if (gatt_get_ch_state(p_tcb) != GATT_CH_OPEN) +bool gatt_connect(const RawAddress& rem_bda, tBLE_ADDR_TYPE addr_type, tGATT_TCB* p_tcb, + tBT_TRANSPORT transport, uint8_t /* initiating_phys */, tGATT_IF gatt_if) { + if (gatt_get_ch_state(p_tcb) != GATT_CH_OPEN) { gatt_set_ch_state(p_tcb, GATT_CH_CONN); + } if (transport != BT_TRANSPORT_LE) { - p_tcb->att_lcid = - L2CA_ConnectReqWithSecurity(BT_PSM_ATT, rem_bda, BTM_SEC_NONE); + p_tcb->att_lcid = L2CA_ConnectReqWithSecurity(BT_PSM_ATT, rem_bda, BTM_SEC_NONE); return p_tcb->att_lcid != 0; } @@ -238,11 +231,9 @@ bool gatt_connect(const RawAddress& rem_bda, tBLE_ADDR_TYPE addr_type, return acl_create_le_connection_with_id(gatt_if, rem_bda, addr_type); } -bool gatt_connect(const RawAddress& rem_bda, tGATT_TCB* p_tcb, - tBT_TRANSPORT transport, uint8_t initiating_phys, - tGATT_IF gatt_if) { - return gatt_connect(rem_bda, BLE_ADDR_PUBLIC, p_tcb, transport, - initiating_phys, gatt_if); +bool gatt_connect(const RawAddress& rem_bda, tGATT_TCB* p_tcb, tBT_TRANSPORT transport, + uint8_t initiating_phys, tGATT_IF gatt_if) { + return gatt_connect(rem_bda, BLE_ADDR_PUBLIC, p_tcb, transport, initiating_phys, gatt_if); } /******************************************************************************* * @@ -274,31 +265,26 @@ bool gatt_disconnect(tGATT_TCB* p_tcb) { if (p_tcb->att_lcid == L2CAP_ATT_CID) { if (ch_state == GATT_CH_OPEN) { if (!L2CA_RemoveFixedChnl(L2CAP_ATT_CID, p_tcb->peer_bda)) { - log::warn("Unable to remove L2CAP ATT fixed channel peer:{}", - p_tcb->peer_bda); + log::warn("Unable to remove L2CAP ATT fixed channel peer:{}", p_tcb->peer_bda); } gatt_set_ch_state(p_tcb, GATT_CH_CLOSING); } else { - if (bluetooth::common::init_flags:: - use_unified_connection_manager_is_enabled()) { + if (bluetooth::common::init_flags::use_unified_connection_manager_is_enabled()) { // TODO(aryarahul): this might not be necessary now that the connection // manager handles GATT client closure correctly in GATT_Deregister - bluetooth::connection::GetConnectionManager() - .stop_all_connections_to_device( + bluetooth::connection::GetConnectionManager().stop_all_connections_to_device( bluetooth::connection::ResolveRawAddress(p_tcb->peer_bda)); } else { - if (!connection_manager::direct_connect_remove(CONN_MGR_ID_L2CAP, - p_tcb->peer_bda)) { + if (!connection_manager::direct_connect_remove(CONN_MGR_ID_L2CAP, p_tcb->peer_bda)) { BTM_AcceptlistRemove(p_tcb->peer_bda); log::info( - "GATT connection manager has no record but removed filter " - "acceptlist gatt_if:{} peer:{}", - static_cast(CONN_MGR_ID_L2CAP), p_tcb->peer_bda); + "GATT connection manager has no record but removed filter " + "acceptlist gatt_if:{} peer:{}", + static_cast(CONN_MGR_ID_L2CAP), p_tcb->peer_bda); } } - gatt_cleanup_upon_disc(p_tcb->peer_bda, GATT_CONN_TERMINATE_LOCAL_HOST, - p_tcb->transport); + gatt_cleanup_upon_disc(p_tcb->peer_bda, GATT_CONN_TERMINATE_LOCAL_HOST, p_tcb->transport); } } else { if ((ch_state == GATT_CH_OPEN) || (ch_state == GATT_CH_CFG)) { @@ -321,10 +307,8 @@ bool gatt_disconnect(tGATT_TCB* p_tcb) { * when it already exists, false otherwise. * ******************************************************************************/ -static bool gatt_update_app_hold_link_status(tGATT_IF gatt_if, tGATT_TCB* p_tcb, - bool is_add) { - log::debug("gatt_if={}, is_add={}, peer_bda={}", gatt_if, is_add, - p_tcb->peer_bda); +static bool gatt_update_app_hold_link_status(tGATT_IF gatt_if, tGATT_TCB* p_tcb, bool is_add) { + log::debug("gatt_if={}, is_add={}, peer_bda={}", gatt_if, is_add, p_tcb->peer_bda); auto& holders = p_tcb->app_hold_link; if (is_add) { @@ -358,10 +342,9 @@ static bool gatt_update_app_hold_link_status(tGATT_IF gatt_if, tGATT_TCB* p_tcb, * Returns void. * ******************************************************************************/ -void gatt_update_app_use_link_flag(tGATT_IF gatt_if, tGATT_TCB* p_tcb, - bool is_add, bool check_acl_link) { - log::debug("gatt_if={}, is_add={} chk_link={}", gatt_if, is_add, - check_acl_link); +void gatt_update_app_use_link_flag(tGATT_IF gatt_if, tGATT_TCB* p_tcb, bool is_add, + bool check_acl_link) { + log::debug("gatt_if={}, is_add={} chk_link={}", gatt_if, is_add, check_acl_link); if (!p_tcb) { log::warn("p_tcb is null"); @@ -387,11 +370,10 @@ void gatt_update_app_use_link_flag(tGATT_IF gatt_if, tGATT_TCB* p_tcb, if (p_tcb->att_lcid == L2CAP_ATT_CID && is_valid_handle) { log::info("disable link idle timer for {}", p_tcb->peer_bda); /* acl link is connected disable the idle timeout */ - GATT_SetIdleTimeout(p_tcb->peer_bda, GATT_LINK_NO_IDLE_TIMEOUT, - p_tcb->transport, true /* is_active */); + GATT_SetIdleTimeout(p_tcb->peer_bda, GATT_LINK_NO_IDLE_TIMEOUT, p_tcb->transport, + true /* is_active */); } else { - log::info("invalid handle {} or dynamic CID {}", is_valid_handle, - p_tcb->att_lcid); + log::info("invalid handle {} or dynamic CID {}", is_valid_handle, p_tcb->att_lcid); } } else { if (p_tcb->app_hold_link.empty()) { @@ -403,11 +385,11 @@ void gatt_update_app_use_link_flag(tGATT_IF gatt_if, tGATT_TCB* p_tcb, /* for fixed channel, set the timeout value to GATT_LINK_IDLE_TIMEOUT_WHEN_NO_APP seconds */ log::info( - "GATT fixed channel is no longer useful, start link idle timer for " - "{} seconds", - GATT_LINK_IDLE_TIMEOUT_WHEN_NO_APP); - GATT_SetIdleTimeout(p_tcb->peer_bda, GATT_LINK_IDLE_TIMEOUT_WHEN_NO_APP, - p_tcb->transport, false /* is_active */); + "GATT fixed channel is no longer useful, start link idle timer for " + "{} seconds", + GATT_LINK_IDLE_TIMEOUT_WHEN_NO_APP); + GATT_SetIdleTimeout(p_tcb->peer_bda, GATT_LINK_IDLE_TIMEOUT_WHEN_NO_APP, p_tcb->transport, + false /* is_active */); } else { // disconnect the dynamic channel log::info("disconnect GATT dynamic channel"); @@ -420,20 +402,17 @@ void gatt_update_app_use_link_flag(tGATT_IF gatt_if, tGATT_TCB* p_tcb, } /** GATT connection initiation */ -bool gatt_act_connect(tGATT_REG* p_reg, const RawAddress& bd_addr, - tBLE_ADDR_TYPE addr_type, tBT_TRANSPORT transport, - int8_t initiating_phys) { - log::verbose("address:{}, transport:{}", bd_addr, - bt_transport_text(transport)); +bool gatt_act_connect(tGATT_REG* p_reg, const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type, + tBT_TRANSPORT transport, int8_t initiating_phys) { + log::verbose("address:{}, transport:{}", bd_addr, bt_transport_text(transport)); tGATT_TCB* p_tcb = gatt_find_tcb_by_addr(bd_addr, transport); if (p_tcb != NULL) { /* before link down, another app try to open a GATT connection */ uint8_t st = gatt_get_ch_state(p_tcb); - if (st == GATT_CH_OPEN && p_tcb->app_hold_link.empty() && - transport == BT_TRANSPORT_LE) { - if (!gatt_connect(bd_addr, addr_type, p_tcb, transport, initiating_phys, - p_reg->gatt_if)) + if (st == GATT_CH_OPEN && p_tcb->app_hold_link.empty() && transport == BT_TRANSPORT_LE) { + if (!gatt_connect(bd_addr, addr_type, p_tcb, transport, initiating_phys, p_reg->gatt_if)) { return false; + } } else if (st == GATT_CH_CLOSING) { log::info("Must finish disconnection before new connection"); /* need to complete the closing first */ @@ -449,8 +428,7 @@ bool gatt_act_connect(tGATT_REG* p_reg, const RawAddress& bd_addr, return false; } - if (!gatt_connect(bd_addr, addr_type, p_tcb, transport, initiating_phys, - p_reg->gatt_if)) { + if (!gatt_connect(bd_addr, addr_type, p_tcb, transport, initiating_phys, p_reg->gatt_if)) { log::error("gatt_connect failed"); fixed_queue_free(p_tcb->pending_ind_q, NULL); *p_tcb = tGATT_TCB(); @@ -460,10 +438,9 @@ bool gatt_act_connect(tGATT_REG* p_reg, const RawAddress& bd_addr, return true; } -bool gatt_act_connect(tGATT_REG* p_reg, const RawAddress& bd_addr, - tBT_TRANSPORT transport, int8_t initiating_phys) { - return gatt_act_connect(p_reg, bd_addr, BLE_ADDR_PUBLIC, transport, - initiating_phys); +bool gatt_act_connect(tGATT_REG* p_reg, const RawAddress& bd_addr, tBT_TRANSPORT transport, + int8_t initiating_phys) { + return gatt_act_connect(p_reg, bd_addr, BLE_ADDR_PUBLIC, transport, initiating_phys); } namespace connection_manager { @@ -479,8 +456,7 @@ void on_connection_timed_out(uint8_t /* app_id */, const RawAddress& address) { /** This callback function is called by L2CAP to indicate that the ATT fixed * channel for LE is connected (conn = true)/disconnected (conn = false). */ -static void gatt_le_connect_cback(uint16_t /* chan */, - const RawAddress& bd_addr, bool connected, +static void gatt_le_connect_cback(uint16_t /* chan */, const RawAddress& bd_addr, bool connected, uint16_t reason, tBT_TRANSPORT transport) { tGATT_TCB* p_tcb = gatt_find_tcb_by_addr(bd_addr, transport); bool check_srv_chg = false; @@ -498,16 +474,16 @@ static void gatt_le_connect_cback(uint16_t /* chan */, if (p_srv_chg_clt != NULL) { check_srv_chg = true; } else { - if (btm_sec_is_a_bonded_dev(bd_addr)) + if (btm_sec_is_a_bonded_dev(bd_addr)) { gatt_add_a_bonded_dev_for_srv_chg(bd_addr); + } } if (!connected) { if (p_tcb != nullptr) { bluetooth::shim::arbiter::GetArbiter().OnLeDisconnect(p_tcb->tcb_idx); } - gatt_cleanup_upon_disc(bd_addr, static_cast(reason), - transport); + gatt_cleanup_upon_disc(bd_addr, static_cast(reason), transport); return; } @@ -521,7 +497,9 @@ static void gatt_le_connect_cback(uint16_t /* chan */, gatt_send_conn_cback(p_tcb); } - if (check_srv_chg) gatt_chk_srv_chg(p_srv_chg_clt); + if (check_srv_chg) { + gatt_chk_srv_chg(p_srv_chg_clt); + } } /* this is incoming connection or background connection callback */ @@ -529,10 +507,8 @@ static void gatt_le_connect_cback(uint16_t /* chan */, p_tcb = gatt_allocate_tcb_by_bdaddr(bd_addr, BT_TRANSPORT_LE); if (!p_tcb) { log::error("CCB max out, no resources"); - if (com::android::bluetooth::flags:: - gatt_drop_acl_on_out_of_resources_fix()) { - log::error("Disconnecting address:{} due to out of resources.", - bd_addr); + if (com::android::bluetooth::flags::gatt_drop_acl_on_out_of_resources_fix()) { + log::error("Disconnecting address:{} due to out of resources.", bd_addr); // When single FIXED channel cannot be created, there is no reason to // keep the link btm_remove_acl(bd_addr, transport); @@ -552,18 +528,15 @@ static void gatt_le_connect_cback(uint16_t /* chan */, } } - auto advertising_set = - bluetooth::shim::ACL_GetAdvertisingSetConnectedTo(bd_addr); + auto advertising_set = bluetooth::shim::ACL_GetAdvertisingSetConnectedTo(bd_addr); if (advertising_set.has_value()) { - bluetooth::shim::arbiter::GetArbiter().OnLeConnect(p_tcb->tcb_idx, - advertising_set.value()); + bluetooth::shim::arbiter::GetArbiter().OnLeConnect(p_tcb->tcb_idx, advertising_set.value()); } - bool device_le_audio_capable = - com::android::bluetooth::flags::read_model_num_fix() - ? is_le_audio_capable_during_service_discovery(bd_addr) - : is_device_le_audio_capable(bd_addr); + bool device_le_audio_capable = com::android::bluetooth::flags::read_model_num_fix() + ? is_le_audio_capable_during_service_discovery(bd_addr) + : is_device_le_audio_capable(bd_addr); if (device_le_audio_capable) { log::info("Read model name for le audio capable device"); if (!check_cached_model_name(bd_addr)) { @@ -584,18 +557,16 @@ static void gatt_le_connect_cback(uint16_t /* chan */, bool check_cached_model_name(const RawAddress& bd_addr) { bt_property_t prop; bt_bdname_t model_name; - BTIF_STORAGE_FILL_PROPERTY(&prop, BT_PROPERTY_REMOTE_MODEL_NUM, - sizeof(model_name), &model_name); + BTIF_STORAGE_FILL_PROPERTY(&prop, BT_PROPERTY_REMOTE_MODEL_NUM, sizeof(model_name), &model_name); - if (btif_storage_get_remote_device_property(&bd_addr, &prop) != - BT_STATUS_SUCCESS || + if (btif_storage_get_remote_device_property(&bd_addr, &prop) != BT_STATUS_SUCCESS || prop.len == 0) { log::info("Device {} no cached model name", bd_addr); return false; } - GetInterfaceToProfiles()->events->invoke_remote_device_properties_cb( - BT_STATUS_SUCCESS, bd_addr, 1, &prop); + GetInterfaceToProfiles()->events->invoke_remote_device_properties_cb(BT_STATUS_SUCCESS, bd_addr, + 1, &prop); return true; } @@ -616,8 +587,8 @@ static void read_dis_cback(const RawAddress& bd_addr, tDIS_VALUE* p_dis_value) { log::info("Device {}, model name: {}", bd_addr, (char*)prop.val); btif_storage_set_remote_device_property(&bd_addr, &prop); - GetInterfaceToProfiles()->events->invoke_remote_device_properties_cb( - BT_STATUS_SUCCESS, bd_addr, 1, &prop); + GetInterfaceToProfiles()->events->invoke_remote_device_properties_cb(BT_STATUS_SUCCESS, + bd_addr, 1, &prop); } } } else { @@ -646,17 +617,17 @@ static void gatt_channel_congestion(tGATT_TCB* p_tcb, bool congested) { } } -void gatt_notify_phy_updated(tHCI_STATUS status, uint16_t handle, - uint8_t tx_phy, uint8_t rx_phy) { +void gatt_notify_phy_updated(tHCI_STATUS status, uint16_t handle, uint8_t tx_phy, uint8_t rx_phy) { tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev_by_handle(handle); if (!p_dev_rec) { log::warn("No Device Found!"); return; } - tGATT_TCB* p_tcb = - gatt_find_tcb_by_addr(p_dev_rec->ble.pseudo_addr, BT_TRANSPORT_LE); - if (!p_tcb) return; + tGATT_TCB* p_tcb = gatt_find_tcb_by_addr(p_dev_rec->ble.pseudo_addr, BT_TRANSPORT_LE); + if (!p_tcb) { + return; + } // TODO: Clean up this status conversion. tGATT_STATUS gatt_status = static_cast(status); @@ -665,50 +636,48 @@ void gatt_notify_phy_updated(tHCI_STATUS status, uint16_t handle, tGATT_REG* p_reg = &gatt_cb.cl_rcb[i]; if (p_reg->in_use && p_reg->app_cb.p_phy_update_cb) { uint16_t conn_id = GATT_CREATE_CONN_ID(p_tcb->tcb_idx, p_reg->gatt_if); - (*p_reg->app_cb.p_phy_update_cb)(p_reg->gatt_if, conn_id, tx_phy, rx_phy, - gatt_status); + (*p_reg->app_cb.p_phy_update_cb)(p_reg->gatt_if, conn_id, tx_phy, rx_phy, gatt_status); } } } -void gatt_notify_conn_update(const RawAddress& remote, uint16_t interval, - uint16_t latency, uint16_t timeout, - tHCI_STATUS status) { +void gatt_notify_conn_update(const RawAddress& remote, uint16_t interval, uint16_t latency, + uint16_t timeout, tHCI_STATUS status) { tGATT_TCB* p_tcb = gatt_find_tcb_by_addr(remote, BT_TRANSPORT_LE); - if (!p_tcb) return; + if (!p_tcb) { + return; + } for (int i = 0; i < GATT_MAX_APPS; i++) { tGATT_REG* p_reg = &gatt_cb.cl_rcb[i]; if (p_reg->in_use && p_reg->app_cb.p_conn_update_cb) { uint16_t conn_id = GATT_CREATE_CONN_ID(p_tcb->tcb_idx, p_reg->gatt_if); - (*p_reg->app_cb.p_conn_update_cb)(p_reg->gatt_if, conn_id, interval, - latency, timeout, + (*p_reg->app_cb.p_conn_update_cb)(p_reg->gatt_if, conn_id, interval, latency, timeout, static_cast(status)); } } } -void gatt_notify_subrate_change(uint16_t handle, uint16_t subrate_factor, - uint16_t latency, uint16_t cont_num, - uint16_t timeout, uint8_t status) { +void gatt_notify_subrate_change(uint16_t handle, uint16_t subrate_factor, uint16_t latency, + uint16_t cont_num, uint16_t timeout, uint8_t status) { tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev_by_handle(handle); if (!p_dev_rec) { log::warn("No Device Found!"); return; } - tGATT_TCB* p_tcb = - gatt_find_tcb_by_addr(p_dev_rec->ble.pseudo_addr, BT_TRANSPORT_LE); - if (!p_tcb) return; + tGATT_TCB* p_tcb = gatt_find_tcb_by_addr(p_dev_rec->ble.pseudo_addr, BT_TRANSPORT_LE); + if (!p_tcb) { + return; + } for (int i = 0; i < GATT_MAX_APPS; i++) { tGATT_REG* p_reg = &gatt_cb.cl_rcb[i]; if (p_reg->in_use && p_reg->app_cb.p_subrate_chg_cb) { uint16_t conn_id = GATT_CREATE_CONN_ID(p_tcb->tcb_idx, p_reg->gatt_if); - (*p_reg->app_cb.p_subrate_chg_cb)(p_reg->gatt_if, conn_id, subrate_factor, - latency, cont_num, timeout, - static_cast(status)); + (*p_reg->app_cb.p_subrate_chg_cb)(p_reg->gatt_if, conn_id, subrate_factor, latency, cont_num, + timeout, static_cast(status)); } } } @@ -717,10 +686,12 @@ void gatt_notify_subrate_change(uint16_t handle, uint16_t subrate_factor, */ static void gatt_le_cong_cback(const RawAddress& remote_bda, bool congested) { tGATT_TCB* p_tcb = gatt_find_tcb_by_addr(remote_bda, BT_TRANSPORT_LE); - if (!p_tcb) return; + if (!p_tcb) { + return; + } /* if uncongested, check to see if there is any more pending data */ - gatt_channel_congestion(p_tcb, congested); + gatt_channel_congestion(p_tcb, congested); } /******************************************************************************* @@ -739,21 +710,20 @@ static void gatt_le_cong_cback(const RawAddress& remote_bda, bool congested) { * Returns void * ******************************************************************************/ -static void gatt_le_data_ind(uint16_t /* chan */, const RawAddress& bd_addr, - BT_HDR* p_buf) { +static void gatt_le_data_ind(uint16_t /* chan */, const RawAddress& bd_addr, BT_HDR* p_buf) { /* Find CCB based on bd addr */ tGATT_TCB* p_tcb = gatt_find_tcb_by_addr(bd_addr, BT_TRANSPORT_LE); if (p_tcb) { - auto decision = bluetooth::shim::arbiter::GetArbiter().InterceptAttPacket( - p_tcb->tcb_idx, p_buf); + auto decision = + bluetooth::shim::arbiter::GetArbiter().InterceptAttPacket(p_tcb->tcb_idx, p_buf); if (decision == bluetooth::shim::arbiter::InterceptAction::DROP) { // do nothing, just free it at the end } else if (gatt_get_ch_state(p_tcb) < GATT_CH_OPEN) { - log::warn("ATT - Ignored L2CAP data while in state: {}", - gatt_get_ch_state(p_tcb)); - } else + log::warn("ATT - Ignored L2CAP data while in state: {}", gatt_get_ch_state(p_tcb)); + } else { gatt_data_process(*p_tcb, L2CAP_ATT_CID, p_buf); + } } osi_free(p_buf); @@ -770,9 +740,8 @@ static void gatt_le_data_ind(uint16_t /* chan */, const RawAddress& bd_addr, * Returns void * ******************************************************************************/ -static void gatt_l2cif_connect_ind_cback(const RawAddress& bd_addr, - uint16_t lcid, uint16_t /* psm */, - uint8_t /* id */) { +static void gatt_l2cif_connect_ind_cback(const RawAddress& bd_addr, uint16_t lcid, + uint16_t /* psm */, uint8_t /* id */) { uint8_t result = L2CAP_CONN_OK; log::info("Connection indication cid = {}", lcid); @@ -784,8 +753,9 @@ static void gatt_l2cif_connect_ind_cback(const RawAddress& bd_addr, if (p_tcb == NULL) { /* no tcb available, reject L2CAP connection */ result = L2CAP_CONN_NO_RESOURCES; - } else + } else { p_tcb->att_lcid = lcid; + } } else /* existing connection , reject it */ { @@ -806,10 +776,11 @@ static void gatt_l2cif_connect_ind_cback(const RawAddress& bd_addr, static void gatt_on_l2cap_error(uint16_t lcid, uint16_t /* result */) { tGATT_TCB* p_tcb = gatt_find_tcb_by_cid(lcid); - if (p_tcb == nullptr) return; + if (p_tcb == nullptr) { + return; + } if (gatt_get_ch_state(p_tcb) == GATT_CH_CONN) { - gatt_cleanup_upon_disc(p_tcb->peer_bda, GATT_CONN_L2C_FAILURE, - BT_TRANSPORT_BR_EDR); + gatt_cleanup_upon_disc(p_tcb->peer_bda, GATT_CONN_L2C_FAILURE, BT_TRANSPORT_BR_EDR); } else { gatt_l2cif_disconnect(lcid); } @@ -821,10 +792,12 @@ static void gatt_l2cif_connect_cfm_cback(uint16_t lcid, uint16_t result) { /* look up clcb for this channel */ p_tcb = gatt_find_tcb_by_cid(lcid); - if (!p_tcb) return; + if (!p_tcb) { + return; + } - log::verbose("result: {} ch_state: {}, lcid:0x{:x}", result, - gatt_get_ch_state(p_tcb), p_tcb->att_lcid); + log::verbose("result: {} ch_state: {}, lcid:0x{:x}", result, gatt_get_ch_state(p_tcb), + p_tcb->att_lcid); if (gatt_get_ch_state(p_tcb) == GATT_CH_CONN && result == L2CAP_CONN_OK) { gatt_set_ch_state(p_tcb, GATT_CH_CFG); @@ -834,26 +807,29 @@ static void gatt_l2cif_connect_cfm_cback(uint16_t lcid, uint16_t result) { } /** This is the L2CAP config confirm callback function */ -void gatt_l2cif_config_cfm_cback(uint16_t lcid, uint16_t /* initiator */, - tL2CAP_CFG_INFO* p_cfg) { +void gatt_l2cif_config_cfm_cback(uint16_t lcid, uint16_t /* initiator */, tL2CAP_CFG_INFO* p_cfg) { gatt_l2cif_config_ind_cback(lcid, p_cfg); /* look up clcb for this channel */ tGATT_TCB* p_tcb = gatt_find_tcb_by_cid(lcid); - if (!p_tcb) return; + if (!p_tcb) { + return; + } /* if in incorrect state */ - if (gatt_get_ch_state(p_tcb) != GATT_CH_CFG) return; + if (gatt_get_ch_state(p_tcb) != GATT_CH_CFG) { + return; + } gatt_set_ch_state(p_tcb, GATT_CH_OPEN); - tGATTS_SRV_CHG* p_srv_chg_clt = - gatt_is_bda_in_the_srv_chg_clt_list(p_tcb->peer_bda); + tGATTS_SRV_CHG* p_srv_chg_clt = gatt_is_bda_in_the_srv_chg_clt_list(p_tcb->peer_bda); if (p_srv_chg_clt != NULL) { gatt_chk_srv_chg(p_srv_chg_clt); } else { - if (btm_sec_is_a_bonded_dev(p_tcb->peer_bda)) + if (btm_sec_is_a_bonded_dev(p_tcb->peer_bda)) { gatt_add_a_bonded_dev_for_srv_chg(p_tcb->peer_bda); + } } /* send callback */ @@ -864,28 +840,33 @@ void gatt_l2cif_config_cfm_cback(uint16_t lcid, uint16_t /* initiator */, void gatt_l2cif_config_ind_cback(uint16_t lcid, tL2CAP_CFG_INFO* p_cfg) { /* look up clcb for this channel */ tGATT_TCB* p_tcb = gatt_find_tcb_by_cid(lcid); - if (!p_tcb) return; + if (!p_tcb) { + return; + } /* GATT uses the smaller of our MTU and peer's MTU */ - if (p_cfg->mtu_present && p_cfg->mtu < L2CAP_DEFAULT_MTU) + if (p_cfg->mtu_present && p_cfg->mtu < L2CAP_DEFAULT_MTU) { p_tcb->payload_size = p_cfg->mtu; - else + } else { p_tcb->payload_size = L2CAP_DEFAULT_MTU; + } } /** This is the L2CAP disconnect indication callback function */ void gatt_l2cif_disconnect_ind_cback(uint16_t lcid, bool /* ack_needed */) { /* look up clcb for this channel */ tGATT_TCB* p_tcb = gatt_find_tcb_by_cid(lcid); - if (!p_tcb) return; + if (!p_tcb) { + return; + } if (gatt_is_bda_in_the_srv_chg_clt_list(p_tcb->peer_bda) == NULL) { - if (btm_sec_is_a_bonded_dev(p_tcb->peer_bda)) + if (btm_sec_is_a_bonded_dev(p_tcb->peer_bda)) { gatt_add_a_bonded_dev_for_srv_chg(p_tcb->peer_bda); + } } /* send disconnect callback */ - gatt_cleanup_upon_disc(p_tcb->peer_bda, GATT_CONN_TERMINATE_PEER_USER, - BT_TRANSPORT_BR_EDR); + gatt_cleanup_upon_disc(p_tcb->peer_bda, GATT_CONN_TERMINATE_PEER_USER, BT_TRANSPORT_BR_EDR); } static void gatt_l2cif_disconnect(uint16_t lcid) { @@ -895,16 +876,18 @@ static void gatt_l2cif_disconnect(uint16_t lcid) { /* look up clcb for this channel */ tGATT_TCB* p_tcb = gatt_find_tcb_by_cid(lcid); - if (!p_tcb) return; + if (!p_tcb) { + return; + } /* If the device is not in the service changed client list, add it... */ if (gatt_is_bda_in_the_srv_chg_clt_list(p_tcb->peer_bda) == NULL) { - if (btm_sec_is_a_bonded_dev(p_tcb->peer_bda)) + if (btm_sec_is_a_bonded_dev(p_tcb->peer_bda)) { gatt_add_a_bonded_dev_for_srv_chg(p_tcb->peer_bda); + } } - gatt_cleanup_upon_disc(p_tcb->peer_bda, GATT_CONN_TERMINATE_LOCAL_HOST, - BT_TRANSPORT_BR_EDR); + gatt_cleanup_upon_disc(p_tcb->peer_bda, GATT_CONN_TERMINATE_LOCAL_HOST, BT_TRANSPORT_BR_EDR); } /** This is the L2CAP data indication callback function */ @@ -935,8 +918,7 @@ static void gatt_send_conn_cback(tGATT_TCB* p_tcb) { uint16_t conn_id; std::set apps = {}; - if (bluetooth::common::init_flags:: - use_unified_connection_manager_is_enabled()) { + if (bluetooth::common::init_flags::use_unified_connection_manager_is_enabled()) { // TODO(aryarahul): this should be done via callbacks passed into the // connection manager apps = {}; @@ -946,32 +928,32 @@ static void gatt_send_conn_cback(tGATT_TCB* p_tcb) { /* notifying all applications for the connection up event */ for (i = 0, p_reg = gatt_cb.cl_rcb; i < GATT_MAX_APPS; i++, p_reg++) { - if (!p_reg->in_use) continue; + if (!p_reg->in_use) { + continue; + } - if (apps.find(p_reg->gatt_if) != apps.end()) + if (apps.find(p_reg->gatt_if) != apps.end()) { gatt_update_app_use_link_flag(p_reg->gatt_if, p_tcb, true, true); + } if (com::android::bluetooth::flags::gatt_reconnect_on_bt_on_fix()) { if (p_reg->direct_connect_request.count(p_tcb->peer_bda) > 0) { gatt_update_app_use_link_flag(p_reg->gatt_if, p_tcb, true, true); - log::info( - "Removing device {} from the direct connect list of gatt_if {}", - p_tcb->peer_bda, p_reg->gatt_if); + log::info("Removing device {} from the direct connect list of gatt_if {}", p_tcb->peer_bda, + p_reg->gatt_if); p_reg->direct_connect_request.erase(p_tcb->peer_bda); } } if (p_reg->app_cb.p_conn_cb) { conn_id = GATT_CREATE_CONN_ID(p_tcb->tcb_idx, p_reg->gatt_if); - (*p_reg->app_cb.p_conn_cb)(p_reg->gatt_if, p_tcb->peer_bda, conn_id, - kGattConnected, GATT_CONN_OK, - p_tcb->transport); + (*p_reg->app_cb.p_conn_cb)(p_reg->gatt_if, p_tcb->peer_bda, conn_id, kGattConnected, + GATT_CONN_OK, p_tcb->transport); } } /* Remove the direct connection */ - if (!bluetooth::common::init_flags:: - use_unified_connection_manager_is_enabled()) { + if (!bluetooth::common::init_flags::use_unified_connection_manager_is_enabled()) { connection_manager::on_connection_complete(p_tcb->peer_bda); } @@ -979,18 +961,20 @@ static void gatt_send_conn_cback(tGATT_TCB* p_tcb) { if (!p_tcb->app_hold_link.empty()) { /* disable idle timeout if one or more clients are holding the link * disable the idle timer */ - GATT_SetIdleTimeout(p_tcb->peer_bda, GATT_LINK_NO_IDLE_TIMEOUT, - p_tcb->transport, true /* is_active */); + GATT_SetIdleTimeout(p_tcb->peer_bda, GATT_LINK_NO_IDLE_TIMEOUT, p_tcb->transport, + true /* is_active */); } else { - GATT_SetIdleTimeout(p_tcb->peer_bda, GATT_LINK_IDLE_TIMEOUT_WHEN_NO_APP, - p_tcb->transport, false /* is_active */); + GATT_SetIdleTimeout(p_tcb->peer_bda, GATT_LINK_IDLE_TIMEOUT_WHEN_NO_APP, p_tcb->transport, + false /* is_active */); } } } void gatt_consolidate(const RawAddress& identity_addr, const RawAddress& rpa) { tGATT_TCB* p_tcb = gatt_find_tcb_by_addr(rpa, BT_TRANSPORT_LE); - if (p_tcb == NULL) return; + if (p_tcb == NULL) { + return; + } log::info("consolidate {} -> {}", rpa, identity_addr); p_tcb->peer_bda = identity_addr; @@ -1042,10 +1026,11 @@ void gatt_data_process(tGATT_TCB& tcb, uint16_t cid, BT_HDR* p_buf) { gatt_verify_signature(tcb, cid, p_buf); } else { /* message from client */ - if ((op_code % 2) == 0) + if ((op_code % 2) == 0) { gatt_server_handle_client_req(tcb, cid, op_code, msg_len, p); - else + } else { gatt_client_handle_server_rsp(tcb, cid, op_code, msg_len, p); + } } } @@ -1056,28 +1041,30 @@ void gatt_add_a_bonded_dev_for_srv_chg(const RawAddress& bda) { srv_chg_clt.bda = bda; srv_chg_clt.srv_changed = false; - if (!gatt_add_srv_chg_clt(&srv_chg_clt)) return; + if (!gatt_add_srv_chg_clt(&srv_chg_clt)) { + return; + } req.srv_chg.bda = bda; req.srv_chg.srv_changed = false; - if (gatt_cb.cb_info.p_srv_chg_callback) - (*gatt_cb.cb_info.p_srv_chg_callback)(GATTS_SRV_CHG_CMD_ADD_CLIENT, &req, - NULL); + if (gatt_cb.cb_info.p_srv_chg_callback) { + (*gatt_cb.cb_info.p_srv_chg_callback)(GATTS_SRV_CHG_CMD_ADD_CLIENT, &req, NULL); + } } /** This function is called to send a service changed indication to the * specified bd address */ void gatt_send_srv_chg_ind(const RawAddress& peer_bda) { - static const uint16_t sGATT_DEFAULT_START_HANDLE = - (uint16_t)osi_property_get_int32( - "bluetooth.gatt.default_start_handle_for_srvc_change.value", - GATT_GATT_START_HANDLE); + static const uint16_t sGATT_DEFAULT_START_HANDLE = (uint16_t)osi_property_get_int32( + "bluetooth.gatt.default_start_handle_for_srvc_change.value", GATT_GATT_START_HANDLE); static const uint16_t sGATT_LAST_HANDLE = (uint16_t)osi_property_get_int32( - "bluetooth.gatt.last_handle_for_srvc_change.value", 0xFFFF); + "bluetooth.gatt.last_handle_for_srvc_change.value", 0xFFFF); log::verbose(""); - if (!gatt_cb.handle_of_h_r) return; + if (!gatt_cb.handle_of_h_r) { + return; + } uint16_t conn_id = gatt_profile_find_conn_id_by_bd_addr(peer_bda); if (conn_id == GATT_INVALID_CONN_ID) { @@ -1089,11 +1076,9 @@ void gatt_send_srv_chg_ind(const RawAddress& peer_bda) { uint8_t* p = handle_range; UINT16_TO_STREAM(p, sGATT_DEFAULT_START_HANDLE); UINT16_TO_STREAM(p, sGATT_LAST_HANDLE); - if (GATTS_HandleValueIndication(conn_id, gatt_cb.handle_of_h_r, - GATT_SIZE_OF_SRV_CHG_HNDL_RANGE, + if (GATTS_HandleValueIndication(conn_id, gatt_cb.handle_of_h_r, GATT_SIZE_OF_SRV_CHG_HNDL_RANGE, handle_range) != GATT_SUCCESS) { - log::warn("Unable to handle GATT service value indication conn_id:{}", - conn_id); + log::warn("Unable to handle GATT service value indication conn_id:{}", conn_id); } } @@ -1119,18 +1104,19 @@ void gatt_init_srv_chg(void) { return; } - bool status = (*gatt_cb.cb_info.p_srv_chg_callback)( - GATTS_SRV_CHG_CMD_READ_NUM_CLENTS, NULL, &rsp); + bool status = + (*gatt_cb.cb_info.p_srv_chg_callback)(GATTS_SRV_CHG_CMD_READ_NUM_CLENTS, NULL, &rsp); - if (!(status && rsp.num_clients)) return; + if (!(status && rsp.num_clients)) { + return; + } log::verbose("num_srv_chg_clt_clients={}", rsp.num_clients); uint8_t num_clients = rsp.num_clients; uint8_t i = 1; /* use one based index */ while ((i <= num_clients) && status) { req.client_read_index = i; - status = (*gatt_cb.cb_info.p_srv_chg_callback)(GATTS_SRV_CHG_CMD_READ_CLENT, - &req, &rsp); + status = (*gatt_cb.cb_info.p_srv_chg_callback)(GATTS_SRV_CHG_CMD_READ_CLENT, &req, &rsp); if (status) { memcpy(&srv_chg_clt, &rsp.srv_chg, sizeof(tGATTS_SRV_CHG)); if (gatt_add_srv_chg_clt(&srv_chg_clt) == NULL) { @@ -1150,7 +1136,9 @@ void gatt_proc_srv_chg(void) { log::verbose(""); - if (!gatt_cb.cb_info.p_srv_chg_callback || !gatt_cb.handle_of_h_r) return; + if (!gatt_cb.cb_info.p_srv_chg_callback || !gatt_cb.handle_of_h_r) { + return; + } gatt_set_srv_chg(); uint8_t start_idx = 0; @@ -1166,16 +1154,16 @@ void gatt_proc_srv_chg(void) { // Some LE GATT clients don't respond to service changed indications. char remote_name[BD_NAME_LEN] = ""; - if (send_indication && - btif_storage_get_stored_remote_name(bda, remote_name)) { - if (interop_match_name(INTEROP_GATTC_NO_SERVICE_CHANGED_IND, - remote_name)) { + if (send_indication && btif_storage_get_stored_remote_name(bda, remote_name)) { + if (interop_match_name(INTEROP_GATTC_NO_SERVICE_CHANGED_IND, remote_name)) { log::verbose("discard srv chg - interop matched {}", remote_name); send_indication = false; } } - if (send_indication) gatt_send_srv_chg_ind(bda); + if (send_indication) { + gatt_send_srv_chg_ind(bda); + } start_idx = ++found_idx; } @@ -1183,16 +1171,19 @@ void gatt_proc_srv_chg(void) { /** This function set the ch_state in tcb */ void gatt_set_ch_state(tGATT_TCB* p_tcb, tGATT_CH_STATE ch_state) { - if (!p_tcb) return; + if (!p_tcb) { + return; + } - log::verbose("old={} new=0x{:x}", p_tcb->ch_state, - static_cast(ch_state)); + log::verbose("old={} new=0x{:x}", p_tcb->ch_state, static_cast(ch_state)); p_tcb->ch_state = ch_state; } /** This function get the ch_state in tcb */ tGATT_CH_STATE gatt_get_ch_state(tGATT_TCB* p_tcb) { - if (!p_tcb) return GATT_CH_CLOSE; + if (!p_tcb) { + return GATT_CH_CLOSE; + } log::verbose("gatt_get_ch_state: ch_state={}", p_tcb->ch_state); return p_tcb->ch_state; diff --git a/system/stack/gatt/gatt_sr.cc b/system/stack/gatt/gatt_sr.cc index 9c40fedb7d6..6506ec47fa4 100644 --- a/system/stack/gatt/gatt_sr.cc +++ b/system/stack/gatt/gatt_sr.cc @@ -43,8 +43,8 @@ #define L2CAP_PKT_OVERHEAD 4 using bluetooth::Uuid; -using bluetooth::eatt::EattExtension; using bluetooth::eatt::EattChannel; +using bluetooth::eatt::EattExtension; using namespace bluetooth; /******************************************************************************* @@ -57,15 +57,13 @@ using namespace bluetooth; * Returns void * ******************************************************************************/ -uint32_t gatt_sr_enqueue_cmd(tGATT_TCB& tcb, uint16_t cid, uint8_t op_code, - uint16_t handle) { +uint32_t gatt_sr_enqueue_cmd(tGATT_TCB& tcb, uint16_t cid, uint8_t op_code, uint16_t handle) { tGATT_SR_CMD* p_cmd; if (cid == tcb.att_lcid) { p_cmd = &tcb.sr_cmd; } else { - EattChannel* channel = - EattExtension::GetInstance()->FindEattChannelByCid(tcb.peer_bda, cid); + EattChannel* channel = EattExtension::GetInstance()->FindEattChannelByCid(tcb.peer_bda, cid); if (channel == nullptr) { log::warn("{}, cid 0x{:02x} already disconnected", tcb.peer_bda, cid); return 0; @@ -78,11 +76,10 @@ uint32_t gatt_sr_enqueue_cmd(tGATT_TCB& tcb, uint16_t cid, uint8_t op_code, p_cmd->cid = cid; - if ((p_cmd->op_code == 0) || - (op_code == GATT_HANDLE_VALUE_CONF)) /* no pending request */ + if ((p_cmd->op_code == 0) || (op_code == GATT_HANDLE_VALUE_CONF)) /* no pending request */ { - if (op_code == GATT_CMD_WRITE || op_code == GATT_SIGN_CMD_WRITE || - op_code == GATT_REQ_MTU || op_code == GATT_HANDLE_VALUE_CONF) { + if (op_code == GATT_CMD_WRITE || op_code == GATT_SIGN_CMD_WRITE || op_code == GATT_REQ_MTU || + op_code == GATT_HANDLE_VALUE_CONF) { trans_id = ++tcb.trans_id; } else { p_cmd->trans_id = ++tcb.trans_id; @@ -107,16 +104,17 @@ uint32_t gatt_sr_enqueue_cmd(tGATT_TCB& tcb, uint16_t cid, uint8_t op_code, * ******************************************************************************/ bool gatt_sr_cmd_empty(tGATT_TCB& tcb, uint16_t cid) { - if (cid == tcb.att_lcid) return (tcb.sr_cmd.op_code == 0); + if (cid == tcb.att_lcid) { + return tcb.sr_cmd.op_code == 0; + } - EattChannel* channel = - EattExtension::GetInstance()->FindEattChannelByCid(tcb.peer_bda, cid); + EattChannel* channel = EattExtension::GetInstance()->FindEattChannelByCid(tcb.peer_bda, cid); if (channel == nullptr) { log::warn("{}, cid 0x{:02x} already disconnected", tcb.peer_bda, cid); return false; } - return (channel->server_outstanding_cmd_.op_code == 0); + return channel->server_outstanding_cmd_.op_code == 0; } /******************************************************************************* @@ -134,8 +132,7 @@ void gatt_dequeue_sr_cmd(tGATT_TCB& tcb, uint16_t cid) { if (cid == tcb.att_lcid) { p_cmd = &tcb.sr_cmd; } else { - EattChannel* channel = - EattExtension::GetInstance()->FindEattChannelByCid(tcb.peer_bda, cid); + EattChannel* channel = EattExtension::GetInstance()->FindEattChannelByCid(tcb.peer_bda, cid); if (channel == nullptr) { log::warn("{}, cid 0x{:02x} already disconnected", tcb.peer_bda, cid); return; @@ -146,12 +143,14 @@ void gatt_dequeue_sr_cmd(tGATT_TCB& tcb, uint16_t cid) { /* Double check in case any buffers are queued */ log::verbose("gatt_dequeue_sr_cmd cid: 0x{:x}", cid); - if (p_cmd->p_rsp_msg) + if (p_cmd->p_rsp_msg) { log::error("free tcb.sr_cmd.p_rsp_msg = {}", fmt::ptr(p_cmd->p_rsp_msg)); + } osi_free_and_reset((void**)&p_cmd->p_rsp_msg); - while (!fixed_queue_is_empty(p_cmd->multi_rsp_q)) + while (!fixed_queue_is_empty(p_cmd->multi_rsp_q)) { osi_free(fixed_queue_try_dequeue(p_cmd->multi_rsp_q)); + } fixed_queue_free(p_cmd->multi_rsp_q, NULL); memset(p_cmd, 0, sizeof(tGATT_SR_CMD)); } @@ -168,28 +167,32 @@ static void build_read_multi_rsp(tGATT_SR_CMD* p_cmd, uint16_t mtu) { p = (uint8_t*)(p_buf + 1) + p_buf->offset; /* First byte in the response is the opcode */ - if (p_cmd->multi_req.variable_len) + if (p_cmd->multi_req.variable_len) { *p++ = GATT_RSP_READ_MULTI_VAR; - else + } else { *p++ = GATT_RSP_READ_MULTI; + } p_buf->len = 1; - /* Now walk through the buffers putting the data into the response in order - */ + // Now walk through the buffers putting the data into the response in order list_t* list = NULL; const list_node_t* node = NULL; - if (!fixed_queue_is_empty(p_cmd->multi_rsp_q)) + if (!fixed_queue_is_empty(p_cmd->multi_rsp_q)) { list = fixed_queue_get_list(p_cmd->multi_rsp_q); + } for (ii = 0; ii < p_cmd->multi_req.num_handles; ii++) { tGATTS_RSP* p_rsp = NULL; if (list != NULL) { - if (ii == 0) + if (ii == 0) { node = list_begin(list); - else + } else { node = list_next(node); - if (node != list_end(list)) p_rsp = (tGATTS_RSP*)list_node(node); + } + if (node != list_end(list)) { + p_rsp = (tGATTS_RSP*)list_node(node); + } } if (p_rsp != NULL) { @@ -203,7 +206,7 @@ static void build_read_multi_rsp(tGATT_SR_CMD* p_cmd, uint16_t mtu) { break; } - len = std::min((size_t) p_rsp->attr_value.len, mtu - total_len); + len = std::min((size_t)p_rsp->attr_value.len, mtu - total_len); if (len == 0) { log::verbose("Buffer space not enough for this data item, skipping"); @@ -212,24 +215,25 @@ static void build_read_multi_rsp(tGATT_SR_CMD* p_cmd, uint16_t mtu) { if (len < p_rsp->attr_value.len) { is_overflow = true; - log::verbose("multi read overflow available len={} val_len={}", len, - p_rsp->attr_value.len); + log::verbose("multi read overflow available len={} val_len={}", len, p_rsp->attr_value.len); } if (p_cmd->multi_req.variable_len) { - UINT16_TO_STREAM(p, (uint16_t) len); + UINT16_TO_STREAM(p, (uint16_t)len); p_buf->len += 2; } if (p_rsp->attr_value.handle == p_cmd->multi_req.handles[ii]) { - ARRAY_TO_STREAM(p, p_rsp->attr_value.value, (uint16_t) len); - p_buf->len += (uint16_t) len; + ARRAY_TO_STREAM(p, p_rsp->attr_value.value, (uint16_t)len); + p_buf->len += (uint16_t)len; } else { p_cmd->status = GATT_NOT_FOUND; break; } - if (is_overflow) break; + if (is_overflow) { + break; + } } else { p_cmd->status = GATT_NOT_FOUND; @@ -260,12 +264,13 @@ static void build_read_multi_rsp(tGATT_SR_CMD* p_cmd, uint16_t mtu) { * Returns bool if all replies have been received * ******************************************************************************/ -static bool process_read_multi_rsp(tGATT_SR_CMD* p_cmd, tGATT_STATUS status, - tGATTS_RSP* p_msg, uint16_t mtu) { +static bool process_read_multi_rsp(tGATT_SR_CMD* p_cmd, tGATT_STATUS status, tGATTS_RSP* p_msg, + uint16_t mtu) { log::verbose("status={} mtu={}", status, mtu); - if (p_cmd->multi_rsp_q == NULL) + if (p_cmd->multi_rsp_q == NULL) { p_cmd->multi_rsp_q = fixed_queue_new(SIZE_MAX); + } /* Enqueue the response */ BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(tGATTS_RSP)); @@ -275,21 +280,20 @@ static bool process_read_multi_rsp(tGATT_SR_CMD* p_cmd, tGATT_STATUS status, p_cmd->status = status; if (status == GATT_SUCCESS) { log::verbose("Multi read count={} num_hdls={} variable={}", - fixed_queue_length(p_cmd->multi_rsp_q), - p_cmd->multi_req.num_handles, p_cmd->multi_req.variable_len); + fixed_queue_length(p_cmd->multi_rsp_q), p_cmd->multi_req.num_handles, + p_cmd->multi_req.variable_len); /* Wait till we get all the responses */ - if (fixed_queue_length(p_cmd->multi_rsp_q) == - p_cmd->multi_req.num_handles) { + if (fixed_queue_length(p_cmd->multi_rsp_q) == p_cmd->multi_req.num_handles) { build_read_multi_rsp(p_cmd, mtu); - return (true); + return true; } } else /* any handle read exception occurs, return error */ { - return (true); + return true; } /* If here, still waiting */ - return (false); + return false; } /******************************************************************************* @@ -302,9 +306,8 @@ static bool process_read_multi_rsp(tGATT_SR_CMD* p_cmd, tGATT_STATUS status, * Returns void * ******************************************************************************/ -tGATT_STATUS gatt_sr_process_app_rsp(tGATT_TCB& tcb, tGATT_IF gatt_if, - uint32_t /* trans_id */, uint8_t op_code, - tGATT_STATUS status, tGATTS_RSP* p_msg, +tGATT_STATUS gatt_sr_process_app_rsp(tGATT_TCB& tcb, tGATT_IF gatt_if, uint32_t /* trans_id */, + uint8_t op_code, tGATT_STATUS status, tGATTS_RSP* p_msg, tGATT_SR_CMD* sr_res_p) { tGATT_STATUS ret_code = GATT_SUCCESS; uint16_t payload_size = gatt_tcb_get_payload_size(tcb, sr_res_p->cid); @@ -313,24 +316,26 @@ tGATT_STATUS gatt_sr_process_app_rsp(tGATT_TCB& tcb, tGATT_IF gatt_if, gatt_sr_update_cback_cnt(tcb, sr_res_p->cid, gatt_if, false, false); - if ((op_code == GATT_REQ_READ_MULTI) || - (op_code == GATT_REQ_READ_MULTI_VAR)) { + if ((op_code == GATT_REQ_READ_MULTI) || (op_code == GATT_REQ_READ_MULTI_VAR)) { /* If no error and still waiting, just return */ - if (!process_read_multi_rsp(sr_res_p, status, p_msg, payload_size)) - return (GATT_SUCCESS); + if (!process_read_multi_rsp(sr_res_p, status, p_msg, payload_size)) { + return GATT_SUCCESS; + } } else { - if (op_code == GATT_REQ_PREPARE_WRITE && status == GATT_SUCCESS) + if (op_code == GATT_REQ_PREPARE_WRITE && status == GATT_SUCCESS) { gatt_sr_update_prep_cnt(tcb, gatt_if, true, false); + } - if (op_code == GATT_REQ_EXEC_WRITE && status != GATT_SUCCESS) + if (op_code == GATT_REQ_EXEC_WRITE && status != GATT_SUCCESS) { gatt_sr_reset_cback_cnt(tcb, sr_res_p->cid); + } sr_res_p->status = status; if (gatt_sr_is_cback_cnt_zero(tcb) && status == GATT_SUCCESS) { if (sr_res_p->p_rsp_msg == NULL) { - sr_res_p->p_rsp_msg = attp_build_sr_msg( - tcb, (uint8_t)(op_code + 1), (tGATT_SR_MSG*)p_msg, payload_size); + sr_res_p->p_rsp_msg = + attp_build_sr_msg(tcb, (uint8_t)(op_code + 1), (tGATT_SR_MSG*)p_msg, payload_size); } else { log::error("Exception!!! already has respond message"); } @@ -341,8 +346,7 @@ tGATT_STATUS gatt_sr_process_app_rsp(tGATT_TCB& tcb, tGATT_IF gatt_if, ret_code = attp_send_sr_msg(tcb, sr_res_p->cid, sr_res_p->p_rsp_msg); sr_res_p->p_rsp_msg = NULL; } else { - ret_code = gatt_send_error_rsp(tcb, sr_res_p->cid, status, op_code, - sr_res_p->handle, false); + ret_code = gatt_send_error_rsp(tcb, sr_res_p->cid, status, op_code, sr_res_p->handle, false); } gatt_dequeue_sr_cmd(tcb, sr_res_p->cid); @@ -363,8 +367,8 @@ tGATT_STATUS gatt_sr_process_app_rsp(tGATT_TCB& tcb, tGATT_IF gatt_if, * Returns void * ******************************************************************************/ -void gatt_process_exec_write_req(tGATT_TCB& tcb, uint16_t cid, uint8_t op_code, - uint16_t len, uint8_t* p_data) { +void gatt_process_exec_write_req(tGATT_TCB& tcb, uint16_t cid, uint8_t op_code, uint16_t len, + uint8_t* p_data) { uint8_t *p = p_data, flag, i = 0; uint32_t trans_id = 0; tGATT_IF gatt_if; @@ -372,12 +376,10 @@ void gatt_process_exec_write_req(tGATT_TCB& tcb, uint16_t cid, uint8_t op_code, #if (GATT_CONFORMANCE_TESTING == TRUE) if (gatt_cb.enable_err_rsp && gatt_cb.req_op_code == op_code) { - log::verbose( - "Conformance tst: forced err rspv for Execute Write: error status={}", - gatt_cb.err_status); + log::verbose("Conformance tst: forced err rspv for Execute Write: error status={}", + gatt_cb.err_status); - gatt_send_error_rsp(tcb, cid, gatt_cb.err_status, gatt_cb.req_op_code, - gatt_cb.handle, false); + gatt_send_error_rsp(tcb, cid, gatt_cb.err_status, gatt_cb.req_op_code, gatt_cb.handle, false); return; } @@ -385,8 +387,7 @@ void gatt_process_exec_write_req(tGATT_TCB& tcb, uint16_t cid, uint8_t op_code, if (len < sizeof(flag)) { log::error("invalid length"); - gatt_send_error_rsp(tcb, cid, GATT_INVALID_PDU, GATT_REQ_EXEC_WRITE, 0, - false); + gatt_send_error_rsp(tcb, cid, GATT_INVALID_PDU, GATT_REQ_EXEC_WRITE, 0, false); return; } @@ -406,8 +407,7 @@ void gatt_process_exec_write_req(tGATT_TCB& tcb, uint16_t cid, uint8_t op_code, conn_id = GATT_CREATE_CONN_ID(tcb.tcb_idx, gatt_if); tGATTS_DATA gatts_data; gatts_data.exec_write = flag; - gatt_sr_send_req_callback(conn_id, trans_id, GATTS_REQ_TYPE_WRITE_EXEC, - &gatts_data); + gatt_sr_send_req_callback(conn_id, trans_id, GATTS_REQ_TYPE_WRITE_EXEC, &gatts_data); tcb.prep_cnt[i] = 0; } } @@ -428,8 +428,8 @@ void gatt_process_exec_write_req(tGATT_TCB& tcb, uint16_t cid, uint8_t op_code, * Returns void * ******************************************************************************/ -void gatt_process_read_multi_req(tGATT_TCB& tcb, uint16_t cid, uint8_t op_code, - uint16_t len, uint8_t* p_data) { +void gatt_process_read_multi_req(tGATT_TCB& tcb, uint16_t cid, uint8_t op_code, uint16_t len, + uint8_t* p_data) { uint32_t trans_id; uint16_t handle = 0, ll = len; uint8_t* p = p_data; @@ -450,14 +450,12 @@ void gatt_process_read_multi_req(tGATT_TCB& tcb, uint16_t cid, uint8_t op_code, #if (GATT_CONFORMANCE_TESTING == TRUE) if (gatt_cb.enable_err_rsp && gatt_cb.req_op_code == op_code) { - log::verbose( - "Conformance tst: forced err rspvofr ReadMultiple: error status={}", - gatt_cb.err_status); + log::verbose("Conformance tst: forced err rspvofr ReadMultiple: error status={}", + gatt_cb.err_status); STREAM_TO_UINT16(handle, p); - gatt_send_error_rsp(tcb, cid, gatt_cb.err_status, gatt_cb.req_op_code, - handle, false); + gatt_send_error_rsp(tcb, cid, gatt_cb.err_status, gatt_cb.req_op_code, handle, false); return; } @@ -471,8 +469,7 @@ void gatt_process_read_multi_req(tGATT_TCB& tcb, uint16_t cid, uint8_t op_code, multi_req->handles[multi_req->num_handles++] = handle; /* check read permission */ - err = gatts_read_attr_perm_check(it->p_db, false, handle, sec_flag, - key_size); + err = gatts_read_attr_perm_check(it->p_db, false, handle, sec_flag, key_size); if (err != GATT_SUCCESS) { log::verbose("read permission denied : 0x{:02x}", err); break; @@ -489,20 +486,20 @@ void gatt_process_read_multi_req(tGATT_TCB& tcb, uint16_t cid, uint8_t op_code, log::error("max attribute handle reached in ReadMultiple Request."); } - if (multi_req->num_handles == 0) err = GATT_INVALID_HANDLE; + if (multi_req->num_handles == 0) { + err = GATT_INVALID_HANDLE; + } if (err == GATT_SUCCESS) { trans_id = gatt_sr_enqueue_cmd(tcb, cid, op_code, multi_req->handles[0]); if (trans_id != 0) { tGATT_SR_CMD* sr_cmd_p = gatt_sr_get_cmd_by_cid(tcb, cid); if (sr_cmd_p == nullptr) { - log::error( - "Could not send response on CID were request arrived. {}, 0x{:02x}", - tcb.peer_bda, cid); + log::error("Could not send response on CID were request arrived. {}, 0x{:02x}", + tcb.peer_bda, cid); return; } - gatt_sr_reset_cback_cnt(tcb, - cid); /* read multiple use multi_rsp_q's count*/ + gatt_sr_reset_cback_cnt(tcb, cid); /* read multiple use multi_rsp_q's count*/ for (ll = 0; ll < multi_req->num_handles; ll++) { tGATTS_RSP* p_msg = (tGATTS_RSP*)osi_calloc(sizeof(tGATTS_RSP)); @@ -510,26 +507,27 @@ void gatt_process_read_multi_req(tGATT_TCB& tcb, uint16_t cid, uint8_t op_code, auto it = gatt_sr_find_i_rcb_by_handle(handle); p_msg->attr_value.handle = handle; - err = gatts_read_attr_value_by_handle( - tcb, cid, it->p_db, op_code, handle, 0, p_msg->attr_value.value, - &p_msg->attr_value.len, GATT_MAX_ATTR_LEN, sec_flag, key_size, - trans_id); + err = gatts_read_attr_value_by_handle(tcb, cid, it->p_db, op_code, handle, 0, + p_msg->attr_value.value, &p_msg->attr_value.len, + GATT_MAX_ATTR_LEN, sec_flag, key_size, trans_id); if (err == GATT_SUCCESS) { - gatt_sr_process_app_rsp(tcb, it->gatt_if, trans_id, op_code, - GATT_SUCCESS, p_msg, sr_cmd_p); + gatt_sr_process_app_rsp(tcb, it->gatt_if, trans_id, op_code, GATT_SUCCESS, p_msg, + sr_cmd_p); } /* either not using or done using the buffer, release it now */ osi_free(p_msg); } - } else + } else { err = GATT_NO_RESOURCES; + } } /* in theroy BUSY is not possible(should already been checked), protected * check */ - if (err != GATT_SUCCESS && err != GATT_PENDING && err != GATT_BUSY) + if (err != GATT_SUCCESS && err != GATT_PENDING && err != GATT_BUSY) { gatt_send_error_rsp(tcb, cid, err, op_code, handle, false); + } } /******************************************************************************* @@ -537,14 +535,14 @@ void gatt_process_read_multi_req(tGATT_TCB& tcb, uint16_t cid, uint8_t op_code, * Function gatt_build_primary_service_rsp * * Description Primamry service request processed internally. Theretically - * only deal with ReadByTypeVAlue and ReadByGroupType. + * only deal with ReadByTypeValue and ReadByGroupType. * * Returns void * ******************************************************************************/ -static tGATT_STATUS gatt_build_primary_service_rsp( - BT_HDR* p_msg, tGATT_TCB& tcb, uint16_t cid, uint8_t op_code, - uint16_t s_hdl, uint16_t e_hdl, uint8_t* /* p_data */, const Uuid& value) { +static tGATT_STATUS gatt_build_primary_service_rsp(BT_HDR* p_msg, tGATT_TCB& tcb, uint16_t cid, + uint8_t op_code, uint16_t s_hdl, uint16_t e_hdl, + uint8_t* /* p_data */, const Uuid& value) { tGATT_STATUS status = GATT_NOT_FOUND; uint8_t handle_len = 4; @@ -553,16 +551,18 @@ static tGATT_STATUS gatt_build_primary_service_rsp( uint16_t payload_size = gatt_tcb_get_payload_size(tcb, cid); for (tGATT_SRV_LIST_ELEM& el : *gatt_cb.srv_list_info) { - if (el.s_hdl < s_hdl || el.s_hdl > e_hdl || - el.type != GATT_UUID_PRI_SERVICE) { + if (el.s_hdl < s_hdl || el.s_hdl > e_hdl || el.type != GATT_UUID_PRI_SERVICE) { continue; } Uuid* p_uuid = gatts_get_service_uuid(el.p_db); - if (!p_uuid) continue; + if (!p_uuid) { + continue; + } - if (op_code == GATT_REQ_READ_BY_GRP_TYPE) + if (op_code == GATT_REQ_READ_BY_GRP_TYPE) { handle_len = 4 + gatt_build_uuid_to_stream_len(*p_uuid); + } /* get the length byte in the repsonse */ if (p_msg->offset == 0) { @@ -576,17 +576,17 @@ static tGATT_STATUS gatt_build_primary_service_rsp( } } - if (p_msg->len + p_msg->offset > payload_size || - handle_len != p_msg->offset) { + if (p_msg->len + p_msg->offset > payload_size || handle_len != p_msg->offset) { break; } - if (op_code == GATT_REQ_FIND_TYPE_VALUE && value != *p_uuid) continue; + if (op_code == GATT_REQ_FIND_TYPE_VALUE && value != *p_uuid) { + continue; + } UINT16_TO_STREAM(p, el.s_hdl); - if (gatt_cb.last_service_handle && - gatt_cb.last_service_handle == el.s_hdl) { + if (gatt_cb.last_service_handle && gatt_cb.last_service_handle == el.s_hdl) { log::verbose("Use 0xFFFF for the last primary attribute"); /* see GATT ERRATA 4065, 4063, ATT ERRATA 4062 */ UINT16_TO_STREAM(p, 0xFFFF); @@ -594,8 +594,9 @@ static tGATT_STATUS gatt_build_primary_service_rsp( UINT16_TO_STREAM(p, el.e_hdl); } - if (op_code == GATT_REQ_READ_BY_GRP_TYPE) + if (op_code == GATT_REQ_READ_BY_GRP_TYPE) { gatt_build_uuid_to_stream(&p, *p_uuid); + } status = GATT_SUCCESS; p_msg->len += p_msg->offset; @@ -611,39 +612,44 @@ static tGATT_STATUS gatt_build_primary_service_rsp( * Returns true: if data filled sucessfully. * false: packet full, or format mismatch. */ -static tGATT_STATUS gatt_build_find_info_rsp(tGATT_SRV_LIST_ELEM& el, - BT_HDR* p_msg, uint16_t& len, +static tGATT_STATUS gatt_build_find_info_rsp(tGATT_SRV_LIST_ELEM& el, BT_HDR* p_msg, uint16_t& len, uint16_t s_hdl, uint16_t e_hdl) { uint8_t info_pair_len[2] = {4, 18}; - if (!el.p_db) return GATT_NOT_FOUND; + if (!el.p_db) { + return GATT_NOT_FOUND; + } /* check the attribute database */ uint8_t* p = (uint8_t*)(p_msg + 1) + L2CAP_MIN_OFFSET + p_msg->len; for (auto& attr : el.p_db->attr_list) { - if (attr.handle > e_hdl) break; + if (attr.handle > e_hdl) { + break; + } - if (attr.handle < s_hdl) continue; + if (attr.handle < s_hdl) { + continue; + } uint8_t uuid_len = attr.uuid.GetShortestRepresentationSize(); - if (p_msg->offset == 0) - p_msg->offset = (uuid_len == Uuid::kNumBytes16) ? GATT_INFO_TYPE_PAIR_16 - : GATT_INFO_TYPE_PAIR_128; + if (p_msg->offset == 0) { + p_msg->offset = + (uuid_len == Uuid::kNumBytes16) ? GATT_INFO_TYPE_PAIR_16 : GATT_INFO_TYPE_PAIR_128; + } - if (len < info_pair_len[p_msg->offset - 1]) return GATT_NO_RESOURCES; + if (len < info_pair_len[p_msg->offset - 1]) { + return GATT_NO_RESOURCES; + } - if (p_msg->offset == GATT_INFO_TYPE_PAIR_16 && - uuid_len == Uuid::kNumBytes16) { + if (p_msg->offset == GATT_INFO_TYPE_PAIR_16 && uuid_len == Uuid::kNumBytes16) { UINT16_TO_STREAM(p, attr.handle); UINT16_TO_STREAM(p, attr.uuid.As16Bit()); - } else if (p_msg->offset == GATT_INFO_TYPE_PAIR_128 && - uuid_len == Uuid::kNumBytes128) { + } else if (p_msg->offset == GATT_INFO_TYPE_PAIR_128 && uuid_len == Uuid::kNumBytes128) { UINT16_TO_STREAM(p, attr.handle); ARRAY_TO_STREAM(p, attr.uuid.To128BitLE(), (int)Uuid::kNumBytes128); - } else if (p_msg->offset == GATT_INFO_TYPE_PAIR_128 && - uuid_len == Uuid::kNumBytes32) { + } else if (p_msg->offset == GATT_INFO_TYPE_PAIR_128 && uuid_len == Uuid::kNumBytes32) { UINT16_TO_STREAM(p, attr.handle); ARRAY_TO_STREAM(p, attr.uuid.To128BitLE(), (int)Uuid::kNumBytes128); } else { @@ -659,31 +665,33 @@ static tGATT_STATUS gatt_build_find_info_rsp(tGATT_SRV_LIST_ELEM& el, return GATT_NOT_FOUND; } -static tGATT_STATUS read_handles(uint16_t& len, uint8_t*& p, uint16_t& s_hdl, - uint16_t& e_hdl) { - if (len < 4) return GATT_INVALID_PDU; +static tGATT_STATUS read_handles(uint16_t& len, uint8_t*& p, uint16_t& s_hdl, uint16_t& e_hdl) { + if (len < 4) { + return GATT_INVALID_PDU; + } /* obtain starting handle, and ending handle */ STREAM_TO_UINT16(s_hdl, p); STREAM_TO_UINT16(e_hdl, p); len -= 4; - if (s_hdl > e_hdl || !GATT_HANDLE_IS_VALID(s_hdl) || - !GATT_HANDLE_IS_VALID(e_hdl)) { + if (s_hdl > e_hdl || !GATT_HANDLE_IS_VALID(s_hdl) || !GATT_HANDLE_IS_VALID(e_hdl)) { return GATT_INVALID_HANDLE; } return GATT_SUCCESS; } -static tGATT_STATUS gatts_validate_packet_format(uint8_t op_code, uint16_t& len, - uint8_t*& p, Uuid* p_uuid, - uint16_t& s_hdl, - uint16_t& e_hdl) { +static tGATT_STATUS gatts_validate_packet_format(uint8_t op_code, uint16_t& len, uint8_t*& p, + Uuid* p_uuid, uint16_t& s_hdl, uint16_t& e_hdl) { tGATT_STATUS ret = read_handles(len, p, s_hdl, e_hdl); - if (ret != GATT_SUCCESS) return ret; + if (ret != GATT_SUCCESS) { + return ret; + } - if (len < 2) return GATT_INVALID_PDU; + if (len < 2) { + return GATT_INVALID_PDU; + } /* parse uuid now */ log::assert_that(p_uuid != nullptr, "assert failed: p_uuid != nullptr"); @@ -708,14 +716,12 @@ static tGATT_STATUS gatts_validate_packet_format(uint8_t op_code, uint16_t& len, * Returns void * ******************************************************************************/ -void gatts_process_primary_service_req(tGATT_TCB& tcb, uint16_t cid, - uint8_t op_code, uint16_t len, +void gatts_process_primary_service_req(tGATT_TCB& tcb, uint16_t cid, uint8_t op_code, uint16_t len, uint8_t* p_data) { uint16_t s_hdl = 0, e_hdl = 0; Uuid uuid = Uuid::kEmpty; - uint8_t reason = - gatts_validate_packet_format(op_code, len, p_data, &uuid, s_hdl, e_hdl); + uint8_t reason = gatts_validate_packet_format(op_code, len, p_data, &uuid, s_hdl, e_hdl); if (reason != GATT_SUCCESS) { gatt_send_error_rsp(tcb, cid, reason, op_code, s_hdl, false); return; @@ -723,8 +729,7 @@ void gatts_process_primary_service_req(tGATT_TCB& tcb, uint16_t cid, if (uuid != Uuid::From16Bit(GATT_UUID_PRI_SERVICE)) { if (op_code == GATT_REQ_READ_BY_GRP_TYPE) { - gatt_send_error_rsp(tcb, cid, GATT_UNSUPPORT_GRP_TYPE, op_code, s_hdl, - false); + gatt_send_error_rsp(tcb, cid, GATT_UNSUPPORT_GRP_TYPE, op_code, s_hdl, false); log::verbose("unexpected ReadByGrpType Group: {}", uuid.ToString()); return; } @@ -745,11 +750,9 @@ void gatts_process_primary_service_req(tGATT_TCB& tcb, uint16_t cid, uint16_t payload_size = gatt_tcb_get_payload_size(tcb, cid); - uint16_t msg_len = - (uint16_t)(sizeof(BT_HDR) + payload_size + L2CAP_MIN_OFFSET); + uint16_t msg_len = (uint16_t)(sizeof(BT_HDR) + payload_size + L2CAP_MIN_OFFSET); BT_HDR* p_msg = (BT_HDR*)osi_calloc(msg_len); - reason = gatt_build_primary_service_rsp(p_msg, tcb, cid, op_code, s_hdl, - e_hdl, p_data, value); + reason = gatt_build_primary_service_rsp(p_msg, tcb, cid, op_code, s_hdl, e_hdl, p_data, value); if (reason != GATT_SUCCESS) { osi_free(p_msg); gatt_send_error_rsp(tcb, cid, reason, op_code, s_hdl, false); @@ -769,8 +772,7 @@ void gatts_process_primary_service_req(tGATT_TCB& tcb, uint16_t cid, * Returns void * ******************************************************************************/ -static void gatts_process_find_info(tGATT_TCB& tcb, uint16_t cid, - uint8_t op_code, uint16_t len, +static void gatts_process_find_info(tGATT_TCB& tcb, uint16_t cid, uint8_t op_code, uint16_t len, uint8_t* p_data) { uint16_t s_hdl = 0, e_hdl = 0; uint8_t reason = read_handles(len, p_data, s_hdl, e_hdl); @@ -780,8 +782,7 @@ static void gatts_process_find_info(tGATT_TCB& tcb, uint16_t cid, } uint16_t payload_size = gatt_tcb_get_payload_size(tcb, cid); - uint16_t buf_len = - (uint16_t)(sizeof(BT_HDR) + payload_size + L2CAP_MIN_OFFSET); + uint16_t buf_len = (uint16_t)(sizeof(BT_HDR) + payload_size + L2CAP_MIN_OFFSET); BT_HDR* p_msg = (BT_HDR*)osi_calloc(buf_len); reason = GATT_NOT_FOUND; @@ -809,8 +810,9 @@ static void gatts_process_find_info(tGATT_TCB& tcb, uint16_t cid, if (reason != GATT_SUCCESS) { osi_free(p_msg); gatt_send_error_rsp(tcb, cid, reason, op_code, s_hdl, false); - } else + } else { attp_send_sr_msg(tcb, cid, p_msg); + } } /******************************************************************************* @@ -823,12 +825,10 @@ static void gatts_process_find_info(tGATT_TCB& tcb, uint16_t cid, * Returns void * ******************************************************************************/ -static void gatts_process_mtu_req(tGATT_TCB& tcb, uint16_t cid, uint16_t len, - uint8_t* p_data) { +static void gatts_process_mtu_req(tGATT_TCB& tcb, uint16_t cid, uint16_t len, uint8_t* p_data) { /* BR/EDR conenction, send error response */ if (cid != L2CAP_ATT_CID) { - gatt_send_error_rsp(tcb, cid, GATT_REQ_NOT_SUPPORTED, GATT_REQ_MTU, 0, - false); + gatt_send_error_rsp(tcb, cid, GATT_REQ_NOT_SUPPORTED, GATT_REQ_MTU, 0, false); return; } @@ -853,26 +853,23 @@ static void gatts_process_mtu_req(tGATT_TCB& tcb, uint16_t cid, uint16_t len, /* Always say to remote our default MTU. */ gatt_sr_msg.mtu = gatt_get_local_mtu(); - log::info("MTU {} request from remote ({}), resulted MTU {}", mtu, - tcb.peer_bda, tcb.payload_size); + log::info("MTU {} request from remote ({}), resulted MTU {}", mtu, tcb.peer_bda, + tcb.payload_size); BTM_SetBleDataLength(tcb.peer_bda, tcb.payload_size + L2CAP_PKT_OVERHEAD); - BT_HDR* p_buf = - attp_build_sr_msg(tcb, GATT_RSP_MTU, &gatt_sr_msg, GATT_DEF_BLE_MTU_SIZE); + BT_HDR* p_buf = attp_build_sr_msg(tcb, GATT_RSP_MTU, &gatt_sr_msg, GATT_DEF_BLE_MTU_SIZE); attp_send_sr_msg(tcb, cid, p_buf); - bluetooth::shim::arbiter::GetArbiter().OnIncomingMtuReq(tcb.tcb_idx, - tcb.payload_size); + bluetooth::shim::arbiter::GetArbiter().OnIncomingMtuReq(tcb.tcb_idx, tcb.payload_size); tGATTS_DATA gatts_data; gatts_data.mtu = tcb.payload_size; - /* Notify all registered applicaiton with new MTU size. Us a transaction ID */ - /* of 0, as no response is allowed from applcations */ + /* Notify all registered application with new MTU size. Us a transaction ID */ + /* of 0, as no response is allowed from application */ for (int i = 0; i < GATT_MAX_APPS; i++) { if (gatt_cb.cl_rcb[i].in_use) { - uint16_t conn_id = - GATT_CREATE_CONN_ID(tcb.tcb_idx, gatt_cb.cl_rcb[i].gatt_if); + uint16_t conn_id = GATT_CREATE_CONN_ID(tcb.tcb_idx, gatt_cb.cl_rcb[i].gatt_if); gatt_sr_send_req_callback(conn_id, 0, GATTS_REQ_TYPE_MTU, &gatts_data); } } @@ -893,22 +890,18 @@ static void gatts_process_mtu_req(tGATT_TCB& tcb, uint16_t cid, uint16_t len, * Returns void * ******************************************************************************/ -static void gatts_process_read_by_type_req(tGATT_TCB& tcb, uint16_t cid, - uint8_t op_code, uint16_t len, - uint8_t* p_data) { +static void gatts_process_read_by_type_req(tGATT_TCB& tcb, uint16_t cid, uint8_t op_code, + uint16_t len, uint8_t* p_data) { Uuid uuid = Uuid::kEmpty; uint16_t s_hdl = 0, e_hdl = 0, err_hdl = 0; - tGATT_STATUS reason = - gatts_validate_packet_format(op_code, len, p_data, &uuid, s_hdl, e_hdl); + tGATT_STATUS reason = gatts_validate_packet_format(op_code, len, p_data, &uuid, s_hdl, e_hdl); #if (GATT_CONFORMANCE_TESTING == TRUE) if (gatt_cb.enable_err_rsp && gatt_cb.req_op_code == op_code) { - log::verbose( - "Conformance tst: forced err rsp for ReadByType: error status={}", - gatt_cb.err_status); + log::verbose("Conformance tst: forced err rsp for ReadByType: error status={}", + gatt_cb.err_status); - gatt_send_error_rsp(tcb, cid, gatt_cb.err_status, gatt_cb.req_op_code, - s_hdl, false); + gatt_send_error_rsp(tcb, cid, gatt_cb.err_status, gatt_cb.req_op_code, s_hdl, false); return; } @@ -937,12 +930,14 @@ static void gatts_process_read_by_type_req(tGATT_TCB& tcb, uint16_t cid, uint8_t key_size; gatt_sr_get_sec_info(tcb.peer_bda, tcb.transport, &sec_flag, &key_size); - tGATT_STATUS ret = gatts_db_read_attr_value_by_type( - tcb, cid, el.p_db, op_code, p_msg, s_hdl, e_hdl, uuid, &buf_len, - sec_flag, key_size, 0, &err_hdl); + tGATT_STATUS ret = + gatts_db_read_attr_value_by_type(tcb, cid, el.p_db, op_code, p_msg, s_hdl, e_hdl, + uuid, &buf_len, sec_flag, key_size, 0, &err_hdl); if (ret != GATT_NOT_FOUND) { reason = ret; - if (ret == GATT_NO_RESOURCES) reason = GATT_SUCCESS; + if (ret == GATT_NO_RESOURCES) { + reason = GATT_SUCCESS; + } } if (ret != GATT_SUCCESS && ret != GATT_NOT_FOUND) { @@ -959,8 +954,9 @@ static void gatts_process_read_by_type_req(tGATT_TCB& tcb, uint16_t cid, /* in theroy BUSY is not possible(should already been checked), protected * check */ - if (reason != GATT_PENDING && reason != GATT_BUSY) + if (reason != GATT_PENDING && reason != GATT_BUSY) { gatt_send_error_rsp(tcb, cid, reason, op_code, s_hdl, false); + } return; } @@ -971,10 +967,8 @@ static void gatts_process_read_by_type_req(tGATT_TCB& tcb, uint16_t cid, /** * This function is called to process the write request from client. */ -static void gatts_process_write_req(tGATT_TCB& tcb, uint16_t cid, - tGATT_SRV_LIST_ELEM& el, uint16_t handle, - uint8_t op_code, uint16_t len, - uint8_t* p_data, +static void gatts_process_write_req(tGATT_TCB& tcb, uint16_t cid, tGATT_SRV_LIST_ELEM& el, + uint16_t handle, uint8_t op_code, uint16_t len, uint8_t* p_data, bt_gatt_db_attribute_type_t gatt_type) { tGATTS_DATA sr_data; uint32_t trans_id; @@ -988,9 +982,7 @@ static void gatts_process_write_req(tGATT_TCB& tcb, uint16_t cid, switch (op_code) { case GATT_REQ_PREPARE_WRITE: if (len < 2 || p == nullptr) { - log::error( - "Prepare write request was invalid - missing offset, sending error " - "response"); + log::error("Prepare write request was invalid - missing offset, sending error response"); gatt_send_error_rsp(tcb, cid, GATT_INVALID_PDU, op_code, handle, false); return; } @@ -1006,10 +998,13 @@ static void gatts_process_write_req(tGATT_TCB& tcb, uint16_t cid, FALLTHROUGH_INTENDED; /* FALLTHROUGH */ case GATT_CMD_WRITE: case GATT_REQ_WRITE: - if (op_code == GATT_REQ_WRITE || op_code == GATT_REQ_PREPARE_WRITE) + if (op_code == GATT_REQ_WRITE || op_code == GATT_REQ_PREPARE_WRITE) { sr_data.write_req.need_rsp = true; + } sr_data.write_req.handle = handle; - if (len > GATT_MAX_ATTR_LEN) len = GATT_MAX_ATTR_LEN; + if (len > GATT_MAX_ATTR_LEN) { + len = GATT_MAX_ATTR_LEN; + } sr_data.write_req.len = len; if (len != 0 && p != nullptr) { memcpy(sr_data.write_req.value, p, len); @@ -1019,8 +1014,7 @@ static void gatts_process_write_req(tGATT_TCB& tcb, uint16_t cid, gatt_sr_get_sec_info(tcb.peer_bda, tcb.transport, &sec_flag, &key_size); - status = gatts_write_attr_perm_check(el.p_db, op_code, handle, - sr_data.write_req.offset, p, len, + status = gatts_write_attr_perm_check(el.p_db, op_code, handle, sr_data.write_req.offset, p, len, sec_flag, key_size); if (status == GATT_SUCCESS) { @@ -1035,8 +1029,8 @@ static void gatts_process_write_req(tGATT_TCB& tcb, uint16_t cid, opcode = GATTS_REQ_TYPE_WRITE_CHARACTERISTIC; } else { log::error( - "Attempt to write attribute that's not tied with " - "characteristic or descriptor value."); + "Attempt to write attribute that's not tied with " + "characteristic or descriptor value."); status = GATT_ERROR; } @@ -1062,9 +1056,8 @@ static void gatts_process_write_req(tGATT_TCB& tcb, uint16_t cid, /** * This function is called to process the read request from client. */ -static void gatts_process_read_req(tGATT_TCB& tcb, uint16_t cid, - tGATT_SRV_LIST_ELEM& el, uint8_t op_code, - uint16_t handle, uint16_t len, +static void gatts_process_read_req(tGATT_TCB& tcb, uint16_t cid, tGATT_SRV_LIST_ELEM& el, + uint8_t op_code, uint16_t handle, uint16_t len, uint8_t* p_data) { uint16_t payload_size = gatt_tcb_get_payload_size(tcb, cid); @@ -1080,7 +1073,9 @@ static void gatts_process_read_req(tGATT_TCB& tcb, uint16_t cid, BT_HDR* p_msg = (BT_HDR*)osi_calloc(buf_len); - if (op_code == GATT_REQ_READ_BLOB) STREAM_TO_UINT16(offset, p_data); + if (op_code == GATT_REQ_READ_BLOB) { + STREAM_TO_UINT16(offset, p_data); + } uint8_t* p = (uint8_t*)(p_msg + 1) + L2CAP_MIN_OFFSET; *p++ = op_code + 1; @@ -1092,9 +1087,9 @@ static void gatts_process_read_req(tGATT_TCB& tcb, uint16_t cid, gatt_sr_get_sec_info(tcb.peer_bda, tcb.transport, &sec_flag, &key_size); uint16_t value_len = 0; - tGATT_STATUS reason = gatts_read_attr_value_by_handle( - tcb, cid, el.p_db, op_code, handle, offset, p, &value_len, - (uint16_t)buf_len, sec_flag, key_size, 0); + tGATT_STATUS reason = + gatts_read_attr_value_by_handle(tcb, cid, el.p_db, op_code, handle, offset, p, &value_len, + (uint16_t)buf_len, sec_flag, key_size, 0); p_msg->len += value_len; if (reason != GATT_SUCCESS) { @@ -1102,8 +1097,9 @@ static void gatts_process_read_req(tGATT_TCB& tcb, uint16_t cid, /* in theory BUSY is not possible(should already been checked), protected * check */ - if (reason != GATT_PENDING && reason != GATT_BUSY) + if (reason != GATT_PENDING && reason != GATT_BUSY) { gatt_send_error_rsp(tcb, cid, reason, op_code, handle, false); + } return; } @@ -1121,8 +1117,8 @@ static void gatts_process_read_req(tGATT_TCB& tcb, uint16_t cid, * Returns void * ******************************************************************************/ -void gatts_process_attribute_req(tGATT_TCB& tcb, uint16_t cid, uint8_t op_code, - uint16_t len, uint8_t* p_data) { +void gatts_process_attribute_req(tGATT_TCB& tcb, uint16_t cid, uint8_t op_code, uint16_t len, + uint8_t* p_data) { uint16_t handle = 0; uint8_t* p = p_data; tGATT_STATUS status = GATT_INVALID_HANDLE; @@ -1138,11 +1134,9 @@ void gatts_process_attribute_req(tGATT_TCB& tcb, uint16_t cid, uint8_t op_code, #if (GATT_CONFORMANCE_TESTING == TRUE) gatt_cb.handle = handle; if (gatt_cb.enable_err_rsp && gatt_cb.req_op_code == op_code) { - log::verbose("Conformance tst: forced err rsp: error status={}", - gatt_cb.err_status); + log::verbose("Conformance tst: forced err rsp: error status={}", gatt_cb.err_status); - gatt_send_error_rsp(tcb, cid, gatt_cb.err_status, cid, gatt_cb.req_op_code, - handle, false); + gatt_send_error_rsp(tcb, cid, gatt_cb.err_status, cid, gatt_cb.req_op_code, handle, false); return; } @@ -1163,8 +1157,7 @@ void gatts_process_attribute_req(tGATT_TCB& tcb, uint16_t cid, uint8_t op_code, case GATT_CMD_WRITE: case GATT_SIGN_CMD_WRITE: case GATT_REQ_PREPARE_WRITE: - gatts_process_write_req(tcb, cid, el, handle, op_code, len, p, - attr.gatt_type); + gatts_process_write_req(tcb, cid, el, handle, op_code, len, p, attr.gatt_type); break; default: break; @@ -1178,9 +1171,9 @@ void gatts_process_attribute_req(tGATT_TCB& tcb, uint16_t cid, uint8_t op_code, } } - if (status != GATT_SUCCESS && op_code != GATT_CMD_WRITE && - op_code != GATT_SIGN_CMD_WRITE) + if (status != GATT_SUCCESS && op_code != GATT_CMD_WRITE && op_code != GATT_SIGN_CMD_WRITE) { gatt_send_error_rsp(tcb, cid, status, op_code, handle, false); + } } /******************************************************************************* @@ -1203,9 +1196,9 @@ void gatts_proc_srv_chg_ind_ack(tGATT_TCB tcb) { log::verbose("NV update set srv chg = false"); p_buf->srv_changed = false; memcpy(&req.srv_chg, p_buf, sizeof(tGATTS_SRV_CHG)); - if (gatt_cb.cb_info.p_srv_chg_callback) - (*gatt_cb.cb_info.p_srv_chg_callback)(GATTS_SRV_CHG_CMD_UPDATE_CLIENT, - &req, NULL); + if (gatt_cb.cb_info.p_srv_chg_callback) { + (*gatt_cb.cb_info.p_srv_chg_callback)(GATTS_SRV_CHG_CMD_UPDATE_CLIENT, &req, NULL); + } } } @@ -1222,13 +1215,11 @@ void gatts_proc_srv_chg_ind_ack(tGATT_TCB tcb) { static void gatts_chk_pending_ind(tGATT_TCB& tcb) { log::verbose(""); - tGATT_VALUE* p_buf = - (tGATT_VALUE*)fixed_queue_try_peek_first(tcb.pending_ind_q); + tGATT_VALUE* p_buf = (tGATT_VALUE*)fixed_queue_try_peek_first(tcb.pending_ind_q); if (p_buf != NULL) { - if (GATTS_HandleValueIndication(p_buf->conn_id, p_buf->handle, p_buf->len, - p_buf->value) != GATT_SUCCESS) { - log::warn("Unable to send GATT server handle value conn_id:{}", - p_buf->conn_id); + if (GATTS_HandleValueIndication(p_buf->conn_id, p_buf->handle, p_buf->len, p_buf->value) != + GATT_SUCCESS) { + log::warn("Unable to send GATT server handle value conn_id:{}", p_buf->conn_id); } osi_free(fixed_queue_try_remove_from_queue(tcb.pending_ind_q, p_buf)); } @@ -1292,17 +1283,17 @@ void gatts_process_value_conf(tGATT_TCB& tcb, uint16_t cid, uint8_t op_code) { if (el.s_hdl <= handle && el.e_hdl >= handle) { uint32_t trans_id = gatt_sr_enqueue_cmd(tcb, cid, op_code, handle); uint16_t conn_id = GATT_CREATE_CONN_ID(tcb.tcb_idx, el.gatt_if); - gatt_sr_send_req_callback(conn_id, trans_id, GATTS_REQ_TYPE_CONF, - &gatts_data); + gatt_sr_send_req_callback(conn_id, trans_id, GATTS_REQ_TYPE_CONF, &gatts_data); } } } } -static bool gatts_process_db_out_of_sync(tGATT_TCB& tcb, uint16_t cid, - uint8_t op_code, uint16_t len, - uint8_t* p_data) { - if (gatt_sr_is_cl_change_aware(tcb)) return false; +static bool gatts_process_db_out_of_sync(tGATT_TCB& tcb, uint16_t cid, uint8_t op_code, + uint16_t len, uint8_t* p_data) { + if (gatt_sr_is_cl_change_aware(tcb)) { + return false; + } // default value bool should_ignore = true; @@ -1314,12 +1305,11 @@ static bool gatts_process_db_out_of_sync(tGATT_TCB& tcb, uint16_t cid, Uuid uuid = Uuid::kEmpty; uint16_t s_hdl = 0, e_hdl = 0; uint16_t db_hash_handle = gatt_cb.handle_of_database_hash; - tGATT_STATUS reason = gatts_validate_packet_format(op_code, len, p_data, - &uuid, s_hdl, e_hdl); - if (reason == GATT_SUCCESS && - (s_hdl <= db_hash_handle && db_hash_handle <= e_hdl) && - (uuid == Uuid::From16Bit(GATT_UUID_DATABASE_HASH))) + tGATT_STATUS reason = gatts_validate_packet_format(op_code, len, p_data, &uuid, s_hdl, e_hdl); + if (reason == GATT_SUCCESS && (s_hdl <= db_hash_handle && db_hash_handle <= e_hdl) && + (uuid == Uuid::From16Bit(GATT_UUID_DATABASE_HASH))) { should_ignore = false; + } } break; case GATT_REQ_READ: { @@ -1335,8 +1325,9 @@ static bool gatts_process_db_out_of_sync(tGATT_TCB& tcb, uint16_t cid, len -= 2; } - if (status == GATT_SUCCESS && handle == gatt_cb.handle_of_database_hash) + if (status == GATT_SUCCESS && handle == gatt_cb.handle_of_database_hash) { should_ignore = false; + } } break; case GATT_REQ_READ_BY_GRP_TYPE: /* discover primary services */ @@ -1361,11 +1352,10 @@ static bool gatts_process_db_out_of_sync(tGATT_TCB& tcb, uint16_t cid, if (should_ignore) { if (should_rsp) { - gatt_send_error_rsp(tcb, cid, GATT_DATABASE_OUT_OF_SYNC, op_code, 0x0000, - false); + gatt_send_error_rsp(tcb, cid, GATT_DATABASE_OUT_OF_SYNC, op_code, 0x0000, false); } - log::info("database out of sync, device={}, op_code=0x{:x}, should_rsp={}", - tcb.peer_bda, (uint16_t)op_code, should_rsp); + log::info("database out of sync, device={}, op_code=0x{:x}, should_rsp={}", tcb.peer_bda, + (uint16_t)op_code, should_rsp); gatt_sr_update_cl_status(tcb, /* chg_aware= */ should_rsp); } @@ -1373,11 +1363,12 @@ static bool gatts_process_db_out_of_sync(tGATT_TCB& tcb, uint16_t cid, } /** This function is called to handle the client requests to server */ -void gatt_server_handle_client_req(tGATT_TCB& tcb, uint16_t cid, - uint8_t op_code, uint16_t len, +void gatt_server_handle_client_req(tGATT_TCB& tcb, uint16_t cid, uint8_t op_code, uint16_t len, uint8_t* p_data) { /* there is pending command, discard this one */ - if (!gatt_sr_cmd_empty(tcb, cid) && op_code != GATT_HANDLE_VALUE_CONF) return; + if (!gatt_sr_cmd_empty(tcb, cid) && op_code != GATT_HANDLE_VALUE_CONF) { + return; + } /* the size of the message may not be bigger than the local max PDU size*/ /* The message has to be smaller than the agreed MTU, len does not include op @@ -1385,8 +1376,7 @@ void gatt_server_handle_client_req(tGATT_TCB& tcb, uint16_t cid, uint16_t payload_size = gatt_tcb_get_payload_size(tcb, cid); if (len >= payload_size) { - log::error("server receive invalid PDU size:{} pdu size:{}", len + 1, - payload_size); + log::error("server receive invalid PDU size:{} pdu size:{}", len + 1, payload_size); /* for invalid request expecting response, send it now */ if (op_code != GATT_CMD_WRITE && op_code != GATT_SIGN_CMD_WRITE && op_code != GATT_HANDLE_VALUE_CONF) { @@ -1395,7 +1385,9 @@ void gatt_server_handle_client_req(tGATT_TCB& tcb, uint16_t cid, /* otherwise, ignore the pkt */ } else { // handle database out of sync - if (gatts_process_db_out_of_sync(tcb, cid, op_code, len, p_data)) return; + if (gatts_process_db_out_of_sync(tcb, cid, op_code, len, p_data)) { + return; + } switch (op_code) { case GATT_REQ_READ_BY_GRP_TYPE: /* discover primary services */ diff --git a/system/stack/gatt/gatt_sr_hash.cc b/system/stack/gatt/gatt_sr_hash.cc index 2610380c6d8..9c7719a09dd 100644 --- a/system/stack/gatt/gatt_sr_hash.cc +++ b/system/stack/gatt/gatt_sr_hash.cc @@ -40,7 +40,7 @@ static size_t calculate_database_info_size(std::list* lst_p attr_it->uuid == Uuid::From16Bit(GATT_UUID_SEC_SERVICE)) { // Service declaration (Handle + Type + Value) len += 4 + gatt_build_uuid_to_stream_len(attr_it->p_value->uuid); - } else if (attr_it->uuid == Uuid::From16Bit(GATT_UUID_INCLUDE_SERVICE)){ + } else if (attr_it->uuid == Uuid::From16Bit(GATT_UUID_INCLUDE_SERVICE)) { // Included service declaration (Handle + Type + Value) len += 8 + gatt_build_uuid_to_stream_len(attr_it->p_value->incl_handle.service_type); } else if (attr_it->uuid == Uuid::From16Bit(GATT_UUID_CHAR_DECLARE)) { @@ -80,7 +80,7 @@ static void fill_database_info(std::list* lst_ptr, uint8_t* } gatt_build_uuid_to_stream(&p_data, attr_it->p_value->uuid); - } else if (attr_it->uuid == Uuid::From16Bit(GATT_UUID_INCLUDE_SERVICE)){ + } else if (attr_it->uuid == Uuid::From16Bit(GATT_UUID_INCLUDE_SERVICE)) { // Included service declaration UINT16_TO_STREAM(p_data, attr_it->handle); UINT16_TO_STREAM(p_data, GATT_UUID_INCLUDE_SERVICE); @@ -109,9 +109,7 @@ static void fill_database_info(std::list* lst_ptr, uint8_t* // Descriptor UINT16_TO_STREAM(p_data, attr_it->handle); UINT16_TO_STREAM(p_data, attr_it->uuid.As16Bit()); - UINT16_TO_STREAM(p_data, attr_it->p_value - ? attr_it->p_value->char_ext_prop - : 0x0000); + UINT16_TO_STREAM(p_data, attr_it->p_value ? attr_it->p_value->char_ext_prop : 0x0000); } } } @@ -124,8 +122,7 @@ Octet16 gatts_calculate_database_hash(std::list* lst_ptr) { fill_database_info(lst_ptr, serialized.data()); std::reverse(serialized.begin(), serialized.end()); - Octet16 db_hash = crypto_toolbox::aes_cmac(Octet16{0}, serialized.data(), - serialized.size()); + Octet16 db_hash = crypto_toolbox::aes_cmac(Octet16{0}, serialized.data(), serialized.size()); log::info("hash={}", base::HexEncode(db_hash.data(), db_hash.size())); return db_hash; diff --git a/system/stack/gatt/gatt_utils.cc b/system/stack/gatt/gatt_utils.cc index ab3ca17197f..cb96c542b20 100644 --- a/system/stack/gatt/gatt_utils.cc +++ b/system/stack/gatt/gatt_utils.cc @@ -99,19 +99,18 @@ const char* const op_code_name[] = {"UNKNOWN", uint16_t gatt_get_local_mtu(void) { /* Default ATT MTU must not be greater than GATT_MAX_MTU_SIZE, nor smaller * than GATT_DEF_BLE_MTU_SIZE */ - static const uint16_t ATT_MTU_DEFAULT = - std::max(std::min(bluetooth::common::init_flags::get_att_mtu_default(), - GATT_MAX_MTU_SIZE), - GATT_DEF_BLE_MTU_SIZE); + static const uint16_t ATT_MTU_DEFAULT = std::max( + std::min(bluetooth::common::init_flags::get_att_mtu_default(), GATT_MAX_MTU_SIZE), + GATT_DEF_BLE_MTU_SIZE); return ATT_MTU_DEFAULT; } uint16_t gatt_get_max_phy_channel() { - static const uint16_t MAX_PHY_CHANNEL = std::min( - std::max(osi_property_get_int32( - "bluetooth.core.le.max_number_of_concurrent_connections", 0), - GATT_MAX_PHY_CHANNEL_FLOOR), - GATT_MAX_PHY_CHANNEL); + static const uint16_t MAX_PHY_CHANNEL = + std::min(std::max(osi_property_get_int32( + "bluetooth.core.le.max_number_of_concurrent_connections", 0), + GATT_MAX_PHY_CHANNEL_FLOOR), + GATT_MAX_PHY_CHANNEL); return MAX_PHY_CHANNEL; } @@ -127,11 +126,14 @@ uint16_t gatt_get_max_phy_channel() { void gatt_free_pending_ind(tGATT_TCB* p_tcb) { log::verbose(""); - if (p_tcb->pending_ind_q == NULL) return; + if (p_tcb->pending_ind_q == NULL) { + return; + } /* release all queued indications */ - while (!fixed_queue_is_empty(p_tcb->pending_ind_q)) + while (!fixed_queue_is_empty(p_tcb->pending_ind_q)) { osi_free(fixed_queue_try_dequeue(p_tcb->pending_ind_q)); + } fixed_queue_free(p_tcb->pending_ind_q, NULL); p_tcb->pending_ind_q = NULL; } @@ -154,8 +156,7 @@ void gatt_delete_dev_from_srv_chg_clt_list(const RawAddress& bd_addr) { /* delete from NV */ tGATTS_SRV_CHG_REQ req; req.srv_chg.bda = bd_addr; - (*gatt_cb.cb_info.p_srv_chg_callback)(GATTS_SRV_CHG_CMD_REMOVE_CLIENT, - &req, NULL); + (*gatt_cb.cb_info.p_srv_chg_callback)(GATTS_SRV_CHG_CMD_REMOVE_CLIENT, &req, NULL); } osi_free(fixed_queue_try_remove_from_queue(gatt_cb.srv_chg_clt_q, p_buf)); } @@ -173,11 +174,12 @@ void gatt_delete_dev_from_srv_chg_clt_list(const RawAddress& bd_addr) { void gatt_set_srv_chg(void) { log::verbose(""); - if (fixed_queue_is_empty(gatt_cb.srv_chg_clt_q)) return; + if (fixed_queue_is_empty(gatt_cb.srv_chg_clt_q)) { + return; + } list_t* list = fixed_queue_get_list(gatt_cb.srv_chg_clt_q); - for (const list_node_t* node = list_begin(list); node != list_end(list); - node = list_next(node)) { + for (const list_node_t* node = list_begin(list); node != list_end(list); node = list_next(node)) { log::verbose("found a srv_chg clt"); tGATTS_SRV_CHG* p_buf = (tGATTS_SRV_CHG*)list_node(node); @@ -186,9 +188,9 @@ void gatt_set_srv_chg(void) { p_buf->srv_changed = true; tGATTS_SRV_CHG_REQ req; memcpy(&req.srv_chg, p_buf, sizeof(tGATTS_SRV_CHG)); - if (gatt_cb.cb_info.p_srv_chg_callback) - (*gatt_cb.cb_info.p_srv_chg_callback)(GATTS_SRV_CHG_CMD_UPDATE_CLIENT, - &req, NULL); + if (gatt_cb.cb_info.p_srv_chg_callback) { + (*gatt_cb.cb_info.p_srv_chg_callback)(GATTS_SRV_CHG_CMD_UPDATE_CLIENT, &req, NULL); + } } } } @@ -229,7 +231,9 @@ tGATTS_SRV_CHG* gatt_add_srv_chg_clt(tGATTS_SRV_CHG* p_srv_chg) { */ tGATT_HDL_LIST_ELEM* gatt_find_hdl_buffer_by_handle(uint16_t handle) { for (auto& elem : *gatt_cb.hdl_list_info) { - if (elem.asgn_range.s_handle == handle) return &elem; + if (elem.asgn_range.s_handle == handle) { + return &elem; + } } return nullptr; @@ -242,13 +246,13 @@ tGATT_HDL_LIST_ELEM* gatt_find_hdl_buffer_by_handle(uint16_t handle) { * Returns Pointer to the buffer, NULL no buffer available * ******************************************************************************/ -std::list::iterator gatt_find_hdl_buffer_by_app_id( - const Uuid& app_uuid128, Uuid* p_svc_uuid, uint16_t start_handle) { +std::list::iterator gatt_find_hdl_buffer_by_app_id(const Uuid& app_uuid128, + Uuid* p_svc_uuid, + uint16_t start_handle) { auto end_it = gatt_cb.hdl_list_info->end(); auto it = gatt_cb.hdl_list_info->begin(); for (; it != end_it; it++) { - if (app_uuid128 == it->asgn_range.app_uuid128 && - *p_svc_uuid == it->asgn_range.svc_uuid && + if (app_uuid128 == it->asgn_range.app_uuid128 && *p_svc_uuid == it->asgn_range.svc_uuid && (start_handle == it->asgn_range.s_handle)) { return it; } @@ -282,8 +286,7 @@ void gatt_free_srvc_db_buffer_app_id(const Uuid& app_id) { * Returns true if found * ******************************************************************************/ -bool gatt_find_the_connected_bda(uint8_t start_idx, RawAddress& bda, - uint8_t* p_found_idx, +bool gatt_find_the_connected_bda(uint8_t start_idx, RawAddress& bda, uint8_t* p_found_idx, tBT_TRANSPORT* p_transport) { uint8_t i; bool found = false; @@ -316,17 +319,21 @@ bool gatt_find_the_connected_bda(uint8_t start_idx, RawAddress& bda, bool gatt_is_srv_chg_ind_pending(tGATT_TCB* p_tcb) { log::verbose("is_queue_empty={}", fixed_queue_is_empty(p_tcb->pending_ind_q)); - if (p_tcb->indicate_handle == gatt_cb.handle_of_h_r) return true; + if (p_tcb->indicate_handle == gatt_cb.handle_of_h_r) { + return true; + } - if (p_tcb->eatt && EattExtension::GetInstance()->IsIndicationPending( - p_tcb->peer_bda, gatt_cb.handle_of_h_r)) + if (p_tcb->eatt && + EattExtension::GetInstance()->IsIndicationPending(p_tcb->peer_bda, gatt_cb.handle_of_h_r)) { return true; + } - if (fixed_queue_is_empty(p_tcb->pending_ind_q)) return false; + if (fixed_queue_is_empty(p_tcb->pending_ind_q)) { + return false; + } list_t* list = fixed_queue_get_list(p_tcb->pending_ind_q); - for (const list_node_t* node = list_begin(list); node != list_end(list); - node = list_next(node)) { + for (const list_node_t* node = list_begin(list); node != list_end(list); node = list_next(node)) { tGATT_VALUE* p_buf = (tGATT_VALUE*)list_node(node); if (p_buf->handle == gatt_cb.handle_of_h_r) { return true; @@ -349,11 +356,12 @@ bool gatt_is_srv_chg_ind_pending(tGATT_TCB* p_tcb) { tGATTS_SRV_CHG* gatt_is_bda_in_the_srv_chg_clt_list(const RawAddress& bda) { log::verbose("{}", bda); - if (fixed_queue_is_empty(gatt_cb.srv_chg_clt_q)) return NULL; + if (fixed_queue_is_empty(gatt_cb.srv_chg_clt_q)) { + return NULL; + } list_t* list = fixed_queue_get_list(gatt_cb.srv_chg_clt_q); - for (const list_node_t* node = list_begin(list); node != list_end(list); - node = list_next(node)) { + for (const list_node_t* node = list_begin(list); node != list_end(list); node = list_next(node)) { tGATTS_SRV_CHG* p_buf = (tGATTS_SRV_CHG*)list_node(node); if (bda == p_buf->bda) { log::verbose("bda is in the srv chg clt list"); @@ -395,13 +403,11 @@ bool gatt_is_bda_connected(const RawAddress& bda) { * Returns GATT_INDEX_INVALID if not found. Otherwise index to the tcb. * ******************************************************************************/ -uint8_t gatt_find_i_tcb_by_addr(const RawAddress& bda, - tBT_TRANSPORT transport) { +uint8_t gatt_find_i_tcb_by_addr(const RawAddress& bda, tBT_TRANSPORT transport) { uint8_t i = 0; for (; i < gatt_get_max_phy_channel(); i++) { - if (gatt_cb.tcb[i].peer_bda == bda && - gatt_cb.tcb[i].transport == transport) { + if (gatt_cb.tcb[i].peer_bda == bda && gatt_cb.tcb[i].transport == transport) { return i; } } @@ -420,8 +426,9 @@ uint8_t gatt_find_i_tcb_by_addr(const RawAddress& bda, tGATT_TCB* gatt_get_tcb_by_idx(uint8_t tcb_idx) { tGATT_TCB* p_tcb = NULL; - if ((tcb_idx < gatt_get_max_phy_channel()) && gatt_cb.tcb[tcb_idx].in_use) + if ((tcb_idx < gatt_get_max_phy_channel()) && gatt_cb.tcb[tcb_idx].in_use) { p_tcb = &gatt_cb.tcb[tcb_idx]; + } return p_tcb; } @@ -435,13 +442,14 @@ tGATT_TCB* gatt_get_tcb_by_idx(uint8_t tcb_idx) { * Returns NULL if not found. Otherwise index to the tcb. * ******************************************************************************/ -tGATT_TCB* gatt_find_tcb_by_addr(const RawAddress& bda, - tBT_TRANSPORT transport) { +tGATT_TCB* gatt_find_tcb_by_addr(const RawAddress& bda, tBT_TRANSPORT transport) { tGATT_TCB* p_tcb = nullptr; uint8_t i = 0; i = gatt_find_i_tcb_by_addr(bda, transport); - if (i != GATT_INDEX_INVALID) p_tcb = &gatt_cb.tcb[i]; + if (i != GATT_INDEX_INVALID) { + p_tcb = &gatt_cb.tcb[i]; + } return p_tcb; } @@ -472,8 +480,8 @@ void gatt_tcb_dump(int fd) { } } - dprintf(fd, "TCB (GATT_MAX_PHY_CHANNEL: %d) in_use: %d\n%s\n", - gatt_get_max_phy_channel(), in_use_cnt, stream.str().c_str()); + dprintf(fd, "TCB (GATT_MAX_PHY_CHANNEL: %d) in_use: %d\n%s\n", gatt_get_max_phy_channel(), + in_use_cnt, stream.str().c_str()); } /******************************************************************************* @@ -485,16 +493,19 @@ void gatt_tcb_dump(int fd) { * Returns GATT_INDEX_INVALID if not found. Otherwise index to the tcb. * ******************************************************************************/ -tGATT_TCB* gatt_allocate_tcb_by_bdaddr(const RawAddress& bda, - tBT_TRANSPORT transport) { +tGATT_TCB* gatt_allocate_tcb_by_bdaddr(const RawAddress& bda, tBT_TRANSPORT transport) { /* search for existing tcb with matching bda */ uint8_t j = gatt_find_i_tcb_by_addr(bda, transport); - if (j != GATT_INDEX_INVALID) return &gatt_cb.tcb[j]; + if (j != GATT_INDEX_INVALID) { + return &gatt_cb.tcb[j]; + } /* find free tcb */ for (int i = 0; i < gatt_get_max_phy_channel(); i++) { tGATT_TCB* p_tcb = &gatt_cb.tcb[i]; - if (p_tcb->in_use) continue; + if (p_tcb->in_use) { + continue; + } *p_tcb = tGATT_TCB(); @@ -520,7 +531,9 @@ tGATT_TCB* gatt_allocate_tcb_by_bdaddr(const RawAddress& bda, uint16_t gatt_get_mtu(const RawAddress& bda, tBT_TRANSPORT transport) { tGATT_TCB* p_tcb = gatt_find_tcb_by_addr(bda, transport); - if (!p_tcb) return 0; + if (!p_tcb) { + return 0; + } return p_tcb->payload_size; } @@ -529,8 +542,7 @@ bool gatt_is_pending_mtu_exchange(tGATT_TCB* p_tcb) { return p_tcb->pending_user_mtu_exchange_value != 0; } -void gatt_set_conn_id_waiting_for_mtu_exchange(tGATT_TCB* p_tcb, - uint16_t conn_id) { +void gatt_set_conn_id_waiting_for_mtu_exchange(tGATT_TCB* p_tcb, uint16_t conn_id) { auto it = std::find(p_tcb->conn_ids_waiting_for_mtu_exchange.begin(), p_tcb->conn_ids_waiting_for_mtu_exchange.end(), conn_id); if (it == p_tcb->conn_ids_waiting_for_mtu_exchange.end()) { @@ -572,8 +584,7 @@ uint8_t gatt_build_uuid_to_stream(uint8_t** p_dst, const Uuid& uuid) { return len; } -bool gatt_parse_uuid_from_cmd(Uuid* p_uuid_rec, uint16_t uuid_size, - uint8_t** p_data) { +bool gatt_parse_uuid_from_cmd(Uuid* p_uuid_rec, uint16_t uuid_size, uint8_t** p_data) { bool ret = true; uint8_t* p_uuid = *p_data; @@ -598,12 +609,14 @@ bool gatt_parse_uuid_from_cmd(Uuid* p_uuid_rec, uint16_t uuid_size, return false; case 0: default: - if (uuid_size != 0) ret = false; + if (uuid_size != 0) { + ret = false; + } log::warn("invalid uuid size"); break; } - return (ret); + return ret; } /******************************************************************************* @@ -618,8 +631,7 @@ bool gatt_parse_uuid_from_cmd(Uuid* p_uuid_rec, uint16_t uuid_size, void gatt_start_rsp_timer(tGATT_CLCB* p_clcb) { uint64_t timeout_ms = GATT_WAIT_FOR_RSP_TIMEOUT_MS; - if (p_clcb->operation == GATTC_OPTYPE_DISCOVERY && - p_clcb->op_subtype == GATT_DISC_SRVC_ALL) { + if (p_clcb->operation == GATTC_OPTYPE_DISCOVERY && p_clcb->op_subtype == GATT_DISC_SRVC_ALL) { timeout_ms = GATT_WAIT_FOR_DISC_RSP_TIMEOUT_MS; } @@ -628,8 +640,7 @@ void gatt_start_rsp_timer(tGATT_CLCB* p_clcb) { if (p_clcb->gatt_rsp_timer_ent == NULL) { p_clcb->gatt_rsp_timer_ent = alarm_new("gatt.gatt_rsp_timer_ent"); } - alarm_set_on_mloop(p_clcb->gatt_rsp_timer_ent, timeout_ms, gatt_rsp_timeout, - p_clcb); + alarm_set_on_mloop(p_clcb->gatt_rsp_timer_ent, timeout_ms, gatt_rsp_timeout, p_clcb); } /******************************************************************************* @@ -641,9 +652,7 @@ void gatt_start_rsp_timer(tGATT_CLCB* p_clcb) { * Returns void * ******************************************************************************/ -void gatt_stop_rsp_timer(tGATT_CLCB* p_clcb) { - alarm_cancel(p_clcb->gatt_rsp_timer_ent); -} +void gatt_stop_rsp_timer(tGATT_CLCB* p_clcb) { alarm_cancel(p_clcb->gatt_rsp_timer_ent); } /******************************************************************************* * @@ -656,12 +665,12 @@ void gatt_stop_rsp_timer(tGATT_CLCB* p_clcb) { ******************************************************************************/ void gatt_start_conf_timer(tGATT_TCB* p_tcb, uint16_t cid) { /* start notification cache timer */ - if (p_tcb->eatt && cid != L2CAP_ATT_CID) - EattExtension::GetInstance()->StartIndicationConfirmationTimer( - p_tcb->peer_bda, cid); - else + if (p_tcb->eatt && cid != L2CAP_ATT_CID) { + EattExtension::GetInstance()->StartIndicationConfirmationTimer(p_tcb->peer_bda, cid); + } else { alarm_set_on_mloop(p_tcb->conf_timer, GATT_WAIT_FOR_RSP_TIMEOUT_MS, gatt_indication_confirmation_timeout, p_tcb); + } } /******************************************************************************* @@ -675,11 +684,11 @@ void gatt_start_conf_timer(tGATT_TCB* p_tcb, uint16_t cid) { ******************************************************************************/ void gatt_stop_conf_timer(tGATT_TCB& tcb, uint16_t cid) { /* start notification cache timer */ - if (tcb.eatt && cid != L2CAP_ATT_CID) - EattExtension::GetInstance()->StopIndicationConfirmationTimer(tcb.peer_bda, - cid); - else + if (tcb.eatt && cid != L2CAP_ATT_CID) { + EattExtension::GetInstance()->StopIndicationConfirmationTimer(tcb.peer_bda, cid); + } else { alarm_cancel(tcb.conf_timer); + } } /******************************************************************************* @@ -693,11 +702,11 @@ void gatt_stop_conf_timer(tGATT_TCB& tcb, uint16_t cid) { ******************************************************************************/ void gatt_start_ind_ack_timer(tGATT_TCB& tcb, uint16_t cid) { /* start notification cache timer */ - if (tcb.eatt && cid != L2CAP_ATT_CID) + if (tcb.eatt && cid != L2CAP_ATT_CID) { EattExtension::GetInstance()->StartAppIndicationTimer(tcb.peer_bda, cid); - else - alarm_set_on_mloop(tcb.ind_ack_timer, GATT_WAIT_FOR_RSP_TIMEOUT_MS, - gatt_ind_ack_timeout, &tcb); + } else { + alarm_set_on_mloop(tcb.ind_ack_timer, GATT_WAIT_FOR_RSP_TIMEOUT_MS, gatt_ind_ack_timeout, &tcb); + } } /******************************************************************************* @@ -734,8 +743,7 @@ void gatt_rsp_timeout(void* data) { log::warn("clcb is already deleted"); return; } - if (p_clcb->operation == GATTC_OPTYPE_DISCOVERY && - p_clcb->op_subtype == GATT_DISC_SRVC_ALL && + if (p_clcb->operation == GATTC_OPTYPE_DISCOVERY && p_clcb->op_subtype == GATT_DISC_SRVC_ALL && p_clcb->retry_count < GATT_REQ_RETRY_LIMIT) { uint8_t rsp_code; log::warn("retry discovery primary service"); @@ -748,12 +756,11 @@ void gatt_rsp_timeout(void* data) { } } - auto eatt_channel = EattExtension::GetInstance()->FindEattChannelByCid( - p_clcb->p_tcb->peer_bda, p_clcb->cid); + auto eatt_channel = + EattExtension::GetInstance()->FindEattChannelByCid(p_clcb->p_tcb->peer_bda, p_clcb->cid); if (eatt_channel) { log::warn("disconnecting EATT cid: {}", p_clcb->cid); - EattExtension::GetInstance()->Disconnect(p_clcb->p_tcb->peer_bda, - p_clcb->cid); + EattExtension::GetInstance()->Disconnect(p_clcb->p_tcb->peer_bda, p_clcb->cid); } else { log::warn("disconnecting GATT..."); gatt_disconnect(p_clcb->p_tcb); @@ -789,8 +796,8 @@ void gatt_indication_confirmation_timeout(void* data) { * to devices that register for it. */ log::warn( - "Service Changed notification timed out in 30 seconds, assuming " - "server-only remote, not disconnecting"); + "Service Changed notification timed out in 30 seconds, assuming " + "server-only remote, not disconnecting"); gatts_proc_srv_chg_ind_ack(*p_tcb); return; } @@ -827,8 +834,7 @@ void gatt_ind_ack_timeout(void* data) { * the service. * ******************************************************************************/ -std::list::iterator gatt_sr_find_i_rcb_by_handle( - uint16_t handle) { +std::list::iterator gatt_sr_find_i_rcb_by_handle(uint16_t handle) { auto it = gatt_cb.srv_list_info->begin(); for (; it != gatt_cb.srv_list_info->end(); it++) { @@ -856,8 +862,7 @@ void gatt_sr_get_sec_info(const RawAddress& rem_bda, tBT_TRANSPORT transport, flags.is_link_key_known = BTM_IsLinkKeyKnown(rem_bda, transport); flags.is_link_key_authed = BTM_IsLinkKeyAuthed(rem_bda, transport); flags.is_encrypted = BTM_IsEncrypted(rem_bda, transport); - flags.can_read_discoverable_characteristics = - BTM_CanReadDiscoverableCharacteristics(rem_bda); + flags.can_read_discoverable_characteristics = BTM_CanReadDiscoverableCharacteristics(rem_bda); *p_key_size = btm_ble_read_sec_key_size(rem_bda); *p_sec_flag = flags; @@ -872,8 +877,8 @@ void gatt_sr_get_sec_info(const RawAddress& rem_bda, tBT_TRANSPORT transport, * Returns void * ******************************************************************************/ -void gatt_sr_send_req_callback(uint16_t conn_id, uint32_t trans_id, - tGATTS_REQ_TYPE type, tGATTS_DATA* p_data) { +void gatt_sr_send_req_callback(uint16_t conn_id, uint32_t trans_id, tGATTS_REQ_TYPE type, + tGATTS_DATA* p_data) { tGATT_IF gatt_if = GATT_GET_GATT_IF(conn_id); tGATT_REG* p_reg = gatt_get_regcb(gatt_if); @@ -898,8 +903,8 @@ void gatt_sr_send_req_callback(uint16_t conn_id, uint32_t trans_id, * Returns void * ******************************************************************************/ -tGATT_STATUS gatt_send_error_rsp(tGATT_TCB& tcb, uint16_t cid, uint8_t err_code, - uint8_t op_code, uint16_t handle, bool deq) { +tGATT_STATUS gatt_send_error_rsp(tGATT_TCB& tcb, uint16_t cid, uint8_t err_code, uint8_t op_code, + uint16_t handle, bool deq) { tGATT_STATUS status; BT_HDR* p_buf; @@ -912,10 +917,13 @@ tGATT_STATUS gatt_send_error_rsp(tGATT_TCB& tcb, uint16_t cid, uint8_t err_code, p_buf = attp_build_sr_msg(tcb, GATT_RSP_ERROR, &msg, payload_size); if (p_buf != NULL) { status = attp_send_sr_msg(tcb, cid, p_buf); - } else + } else { status = GATT_INSUF_RESOURCE; + } - if (deq) gatt_dequeue_sr_cmd(tcb, cid); + if (deq) { + gatt_dequeue_sr_cmd(tcb, cid); + } return status; } @@ -929,21 +937,21 @@ tGATT_STATUS gatt_send_error_rsp(tGATT_TCB& tcb, uint16_t cid, uint8_t err_code, * Returns 0 if error else sdp handle for the record. * ******************************************************************************/ -uint32_t gatt_add_sdp_record(const Uuid& uuid, uint16_t start_hdl, - uint16_t end_hdl) { +uint32_t gatt_add_sdp_record(const Uuid& uuid, uint16_t start_hdl, uint16_t end_hdl) { uint8_t buff[60]; uint8_t* p = buff; log::verbose("s_hdl=0x{:x} s_hdl=0x{:x}", start_hdl, end_hdl); uint32_t sdp_handle = get_legacy_stack_sdp_api()->handle.SDP_CreateRecord(); - if (sdp_handle == 0) return 0; + if (sdp_handle == 0) { + return 0; + } switch (uuid.GetShortestRepresentationSize()) { case Uuid::kNumBytes16: { uint16_t tmp = uuid.As16Bit(); - if (!get_legacy_stack_sdp_api()->handle.SDP_AddServiceClassIdList( - sdp_handle, 1, &tmp)) { + if (!get_legacy_stack_sdp_api()->handle.SDP_AddServiceClassIdList(sdp_handle, 1, &tmp)) { log::warn("Unable to add SDP attribute for 16 bit uuid"); } break; @@ -954,10 +962,9 @@ uint32_t gatt_add_sdp_record(const Uuid& uuid, uint16_t start_hdl, uint32_t tmp = uuid.As32Bit(); UINT32_TO_BE_STREAM(p, tmp); if (!get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - sdp_handle, ATTR_ID_SERVICE_CLASS_ID_LIST, DATA_ELE_SEQ_DESC_TYPE, - (uint32_t)(p - buff), buff)) { - log::warn("Unable to add SDP attribute for 32 bit uuid handle:{}", - sdp_handle); + sdp_handle, ATTR_ID_SERVICE_CLASS_ID_LIST, DATA_ELE_SEQ_DESC_TYPE, + (uint32_t)(p - buff), buff)) { + log::warn("Unable to add SDP attribute for 32 bit uuid handle:{}", sdp_handle); } break; } @@ -966,10 +973,9 @@ uint32_t gatt_add_sdp_record(const Uuid& uuid, uint16_t start_hdl, UINT8_TO_BE_STREAM(p, (UUID_DESC_TYPE << 3) | SIZE_SIXTEEN_BYTES); ARRAY_TO_BE_STREAM(p, uuid.To128BitBE().data(), (int)Uuid::kNumBytes128); if (!get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - sdp_handle, ATTR_ID_SERVICE_CLASS_ID_LIST, DATA_ELE_SEQ_DESC_TYPE, - (uint32_t)(p - buff), buff)) { - log::warn("Unable to add SDP attribute for 128 bit uuid handle:{}", - sdp_handle); + sdp_handle, ATTR_ID_SERVICE_CLASS_ID_LIST, DATA_ELE_SEQ_DESC_TYPE, + (uint32_t)(p - buff), buff)) { + log::warn("Unable to add SDP attribute for 128 bit uuid handle:{}", sdp_handle); } break; } @@ -984,19 +990,18 @@ uint32_t gatt_add_sdp_record(const Uuid& uuid, uint16_t start_hdl, proto_elem_list[1].params[0] = start_hdl; proto_elem_list[1].params[1] = end_hdl; - if (!get_legacy_stack_sdp_api()->handle.SDP_AddProtocolList( - sdp_handle, 2, proto_elem_list)) { + if (!get_legacy_stack_sdp_api()->handle.SDP_AddProtocolList(sdp_handle, 2, proto_elem_list)) { log::warn("Unable to add SDP protocol list for l2cap and att"); } /* Make the service browseable */ uint16_t list = UUID_SERVCLASS_PUBLIC_BROWSE_GROUP; - if (!get_legacy_stack_sdp_api()->handle.SDP_AddUuidSequence( - sdp_handle, ATTR_ID_BROWSE_GROUP_LIST, 1, &list)) { + if (!get_legacy_stack_sdp_api()->handle.SDP_AddUuidSequence(sdp_handle, ATTR_ID_BROWSE_GROUP_LIST, + 1, &list)) { log::warn("Unable to add SDP uuid sequence public browse group"); } - return (sdp_handle); + return sdp_handle; } #if GATT_CONFORMANCE_TESTING == TRUE @@ -1010,8 +1015,7 @@ uint32_t gatt_add_sdp_record(const Uuid& uuid, uint16_t start_hdl, * ******************************************************************************/ void gatt_set_err_rsp(bool enable, uint8_t req_op_code, uint8_t err_status) { - log::verbose("enable={} op_code={}, err_status={}", enable, req_op_code, - err_status); + log::verbose("enable={} op_code={}, err_status={}", enable, req_op_code, err_status); gatt_cb.enable_err_rsp = enable; gatt_cb.req_op_code = req_op_code; gatt_cb.err_status = err_status; @@ -1058,10 +1062,11 @@ tGATT_REG* gatt_get_regcb(tGATT_IF gatt_if) { ******************************************************************************/ bool gatt_tcb_is_cid_busy(tGATT_TCB& tcb, uint16_t cid) { - if (cid == tcb.att_lcid) return !tcb.cl_cmd_q.empty(); + if (cid == tcb.att_lcid) { + return !tcb.cl_cmd_q.empty(); + } - EattChannel* channel = - EattExtension::GetInstance()->FindEattChannelByCid(tcb.peer_bda, cid); + EattChannel* channel = EattExtension::GetInstance()->FindEattChannelByCid(tcb.peer_bda, cid); if (channel == nullptr) { log::warn("{}, cid 0x{:02x} already disconnected", tcb.peer_bda, cid); return false; @@ -1108,14 +1113,11 @@ tGATT_CLCB* gatt_clcb_alloc(uint16_t conn_id) { * confirmation, false otherwise * ******************************************************************************/ -bool gatt_tcb_get_cid_available_for_indication(tGATT_TCB* p_tcb, - bool eatt_support, - uint16_t** indicated_handle_p, - uint16_t* cid_p) { +bool gatt_tcb_get_cid_available_for_indication(tGATT_TCB* p_tcb, bool eatt_support, + uint16_t** indicated_handle_p, uint16_t* cid_p) { if (p_tcb->eatt && eatt_support) { EattChannel* channel = - EattExtension::GetInstance()->GetChannelAvailableForIndication( - p_tcb->peer_bda); + EattExtension::GetInstance()->GetChannelAvailableForIndication(p_tcb->peer_bda); if (channel) { *indicated_handle_p = &channel->indicate_handle_; *cid_p = channel->cid_; @@ -1141,8 +1143,7 @@ bool gatt_tcb_get_cid_available_for_indication(tGATT_TCB* p_tcb, * Returns true when indication handle found, false otherwise * ******************************************************************************/ -bool gatt_tcb_find_indicate_handle(tGATT_TCB& tcb, uint16_t cid, - uint16_t* indicated_handle_p) { +bool gatt_tcb_find_indicate_handle(tGATT_TCB& tcb, uint16_t cid, uint16_t* indicated_handle_p) { if (cid == tcb.att_lcid) { *indicated_handle_p = tcb.indicate_handle; tcb.indicate_handle = 0; @@ -1150,8 +1151,7 @@ bool gatt_tcb_find_indicate_handle(tGATT_TCB& tcb, uint16_t cid, } if (tcb.eatt) { - EattChannel* channel = - EattExtension::GetInstance()->FindEattChannelByCid(tcb.peer_bda, cid); + EattChannel* channel = EattExtension::GetInstance()->FindEattChannelByCid(tcb.peer_bda, cid); if (channel) { *indicated_handle_p = channel->indicate_handle_; channel->indicate_handle_ = 0; @@ -1175,8 +1175,7 @@ bool gatt_tcb_find_indicate_handle(tGATT_TCB& tcb, uint16_t cid, uint16_t gatt_tcb_get_att_cid(tGATT_TCB& tcb, bool eatt_support) { if (eatt_support && tcb.eatt) { EattChannel* channel = - EattExtension::GetInstance()->GetChannelAvailableForClientRequest( - tcb.peer_bda); + EattExtension::GetInstance()->GetChannelAvailableForClientRequest(tcb.peer_bda); if (channel) { return channel->cid_; } @@ -1194,10 +1193,11 @@ uint16_t gatt_tcb_get_att_cid(tGATT_TCB& tcb, bool eatt_support) { * ******************************************************************************/ uint16_t gatt_tcb_get_payload_size(tGATT_TCB& tcb, uint16_t cid) { - if (!tcb.eatt || (cid == tcb.att_lcid)) return tcb.payload_size; + if (!tcb.eatt || (cid == tcb.att_lcid)) { + return tcb.payload_size; + } - EattChannel* channel = - EattExtension::GetInstance()->FindEattChannelByCid(tcb.peer_bda, cid); + EattChannel* channel = EattExtension::GetInstance()->FindEattChannelByCid(tcb.peer_bda, cid); if (channel == nullptr) { log::warn("{}, cid 0x{:02x} already disconnected", tcb.peer_bda, cid); return 0; @@ -1221,8 +1221,8 @@ static void gatt_clcb_dealloc(tGATT_CLCB* p_clcb) { if (p_clcb) { alarm_free(p_clcb->gatt_rsp_timer_ent); gatt_clcb_invalidate(p_clcb->p_tcb, p_clcb); - for (auto clcb_it = gatt_cb.clcb_queue.begin(); - clcb_it != gatt_cb.clcb_queue.end(); clcb_it++) { + for (auto clcb_it = gatt_cb.clcb_queue.begin(); clcb_it != gatt_cb.clcb_queue.end(); + clcb_it++) { if (&(*clcb_it) == p_clcb) { gatt_cb.clcb_queue.erase(clcb_it); return; @@ -1247,9 +1247,8 @@ void gatt_clcb_invalidate(tGATT_TCB* p_tcb, const tGATT_CLCB* p_clcb) { if (!p_tcb->pending_enc_clcb.empty()) { for (size_t i = 0; i < p_tcb->pending_enc_clcb.size(); i++) { if (p_tcb->pending_enc_clcb.at(i) == p_clcb) { - log::warn( - "Removing clcb ({}) for conn id=0x{:04x} from pending_enc_clcb", - fmt::ptr(p_clcb), p_clcb->conn_id); + log::warn("Removing clcb ({}) for conn id=0x{:04x} from pending_enc_clcb", fmt::ptr(p_clcb), + p_clcb->conn_id); p_tcb->pending_enc_clcb.at(i) = NULL; break; } @@ -1259,8 +1258,7 @@ void gatt_clcb_invalidate(tGATT_TCB* p_tcb, const tGATT_CLCB* p_clcb) { if (cid == p_tcb->att_lcid) { cl_cmd_q_p = &p_tcb->cl_cmd_q; } else { - EattChannel* channel = EattExtension::GetInstance()->FindEattChannelByCid( - p_tcb->peer_bda, cid); + EattChannel* channel = EattExtension::GetInstance()->FindEattChannelByCid(p_tcb->peer_bda, cid); if (channel == nullptr) { log::warn("{}, cid 0x{:02x} already disconnected", p_tcb->peer_bda, cid); return; @@ -1282,15 +1280,14 @@ void gatt_clcb_invalidate(tGATT_TCB* p_tcb, const tGATT_CLCB* p_clcb) { if (iter->to_send) { /* If command was not send, just remove the entire element */ cl_cmd_q_p->erase(iter); - log::warn("Removing scheduled clcb ({}) for conn_id=0x{:04x}", - fmt::ptr(p_clcb), p_clcb->conn_id); + log::warn("Removing scheduled clcb ({}) for conn_id=0x{:04x}", fmt::ptr(p_clcb), + p_clcb->conn_id); } else { /* If command has been sent, just invalidate p_clcb pointer for proper * response handling */ iter->p_clcb = NULL; - log::warn( - "Invalidating clcb ({}) for already sent request on conn_id=0x{:04x}", - fmt::ptr(p_clcb), p_clcb->conn_id); + log::warn("Invalidating clcb ({}) for already sent request on conn_id=0x{:04x}", + fmt::ptr(p_clcb), p_clcb->conn_id); } } /******************************************************************************* @@ -1308,10 +1305,9 @@ tGATT_TCB* gatt_find_tcb_by_cid(uint16_t lcid) { tGATT_TCB* p_tcb = NULL; for (xx = 0; xx < gatt_get_max_phy_channel(); xx++) { - if (gatt_cb.tcb[xx].in_use && - ((gatt_cb.tcb[xx].att_lcid == lcid) || - ((EattExtension::GetInstance()->FindEattChannelByCid( - gatt_cb.tcb[xx].peer_bda, lcid) != nullptr)))) { + if (gatt_cb.tcb[xx].in_use && ((gatt_cb.tcb[xx].att_lcid == lcid) || + (EattExtension::GetInstance()->FindEattChannelByCid( + gatt_cb.tcb[xx].peer_bda, lcid) != nullptr))) { p_tcb = &gatt_cb.tcb[xx]; break; } @@ -1329,13 +1325,19 @@ void gatt_sr_copy_prep_cnt_to_cback_cnt(tGATT_TCB& tcb) { /* Get outstanding server command pointer by the transaction id */ tGATT_SR_CMD* gatt_sr_get_cmd_by_trans_id(tGATT_TCB* p_tcb, uint32_t trans_id) { - if (p_tcb->sr_cmd.trans_id == trans_id) return &p_tcb->sr_cmd; + if (p_tcb->sr_cmd.trans_id == trans_id) { + return &p_tcb->sr_cmd; + } - if (!p_tcb->eatt) return nullptr; + if (!p_tcb->eatt) { + return nullptr; + } - EattChannel* channel = EattExtension::GetInstance()->FindEattChannelByTransId( - p_tcb->peer_bda, trans_id); - if (!channel) return nullptr; + EattChannel* channel = + EattExtension::GetInstance()->FindEattChannelByTransId(p_tcb->peer_bda, trans_id); + if (!channel) { + return nullptr; + } return &channel->server_outstanding_cmd_; } @@ -1389,8 +1391,7 @@ void gatt_sr_reset_cback_cnt(tGATT_TCB& tcb, uint16_t cid) { if (cid == tcb.att_lcid) { tcb.sr_cmd.cback_cnt[i] = 0; } else { - EattChannel* channel = - EattExtension::GetInstance()->FindEattChannelByCid(tcb.peer_bda, cid); + EattChannel* channel = EattExtension::GetInstance()->FindEattChannelByCid(tcb.peer_bda, cid); if (channel == nullptr) { log::warn("{}, cid 0x{:02x} already disconnected", tcb.peer_bda, cid); return; @@ -1423,8 +1424,7 @@ tGATT_SR_CMD* gatt_sr_get_cmd_by_cid(tGATT_TCB& tcb, uint16_t cid) { if (cid == tcb.att_lcid) { sr_cmd_p = &tcb.sr_cmd; } else { - EattChannel* channel = - EattExtension::GetInstance()->FindEattChannelByCid(tcb.peer_bda, cid); + EattChannel* channel = EattExtension::GetInstance()->FindEattChannelByCid(tcb.peer_bda, cid); if (channel == nullptr) { log::warn("{}, cid 0x{:02x} already disconnected", tcb.peer_bda, cid); return nullptr; @@ -1444,8 +1444,7 @@ tGATT_READ_MULTI* gatt_sr_get_read_multi(tGATT_TCB& tcb, uint16_t cid) { if (cid == tcb.att_lcid) { read_multi_p = &tcb.sr_cmd.multi_req; } else { - EattChannel* channel = - EattExtension::GetInstance()->FindEattChannelByCid(tcb.peer_bda, cid); + EattChannel* channel = EattExtension::GetInstance()->FindEattChannelByCid(tcb.peer_bda, cid); if (channel == nullptr) { log::warn("{}, cid 0x{:02x} already disconnected", tcb.peer_bda, cid); return nullptr; @@ -1460,21 +1459,20 @@ tGATT_READ_MULTI* gatt_sr_get_read_multi(tGATT_TCB& tcb, uint16_t cid) { * * Function gatt_sr_update_cback_cnt * - * Description Update the teh applicaiton callback count + * Description Update the application callback count * * Returns None * ******************************************************************************/ -void gatt_sr_update_cback_cnt(tGATT_TCB& tcb, uint16_t cid, tGATT_IF gatt_if, - bool is_inc, bool is_reset_first) { +void gatt_sr_update_cback_cnt(tGATT_TCB& tcb, uint16_t cid, tGATT_IF gatt_if, bool is_inc, + bool is_reset_first) { uint8_t idx = ((uint8_t)gatt_if) - 1; tGATT_SR_CMD* sr_cmd_p; if (cid == tcb.att_lcid) { sr_cmd_p = &tcb.sr_cmd; } else { - EattChannel* channel = - EattExtension::GetInstance()->FindEattChannelByCid(tcb.peer_bda, cid); + EattChannel* channel = EattExtension::GetInstance()->FindEattChannelByCid(tcb.peer_bda, cid); if (channel == nullptr) { log::warn("{}, cid 0x{:02x} already disconnected", tcb.peer_bda, cid); return; @@ -1498,17 +1496,16 @@ void gatt_sr_update_cback_cnt(tGATT_TCB& tcb, uint16_t cid, tGATT_IF gatt_if, * * Function gatt_sr_update_prep_cnt * - * Description Update the teh prepare write request count + * Description Update the prepare write request count * * Returns None * ******************************************************************************/ -void gatt_sr_update_prep_cnt(tGATT_TCB& tcb, tGATT_IF gatt_if, bool is_inc, - bool is_reset_first) { +void gatt_sr_update_prep_cnt(tGATT_TCB& tcb, tGATT_IF gatt_if, bool is_inc, bool is_reset_first) { uint8_t idx = ((uint8_t)gatt_if) - 1; - log::verbose("tcb idx={} gatt_if={} is_inc={} is_reset_first={}", tcb.tcb_idx, - gatt_if, is_inc, is_reset_first); + log::verbose("tcb idx={} gatt_if={} is_inc={} is_reset_first={}", tcb.tcb_idx, gatt_if, is_inc, + is_reset_first); if (is_reset_first) { gatt_sr_reset_prep_cnt(tcb); @@ -1542,8 +1539,7 @@ bool gatt_cancel_open(tGATT_IF gatt_if, const RawAddress& bda) { return true; } - log::warn("Unable to cancel open for unknown connection gatt_if:{} peer:{}", - gatt_if, bda); + log::warn("Unable to cancel open for unknown connection gatt_if:{} peer:{}", gatt_if, bda); return true; } @@ -1555,17 +1551,14 @@ bool gatt_cancel_open(tGATT_IF gatt_if, const RawAddress& bda) { gatt_update_app_use_link_flag(gatt_if, p_tcb, false, false); if (p_tcb->app_hold_link.empty()) { - log::debug( - "Client reference count is zero disconnecting device gatt_if:{} " - "peer:{}", - gatt_if, bda); + log::debug("Client reference count is zero disconnecting device gatt_if:{} peer:{}", gatt_if, + bda); gatt_disconnect(p_tcb); } - if (bluetooth::common::init_flags:: - use_unified_connection_manager_is_enabled()) { + if (bluetooth::common::init_flags::use_unified_connection_manager_is_enabled()) { bluetooth::connection::GetConnectionManager().stop_direct_connection( - gatt_if, bluetooth::connection::ResolveRawAddress(bda)); + gatt_if, bluetooth::connection::ResolveRawAddress(bda)); } else { if (!connection_manager::direct_connect_remove(gatt_if, bda)) { if (!connection_manager::is_background_connection(bda)) { @@ -1574,14 +1567,14 @@ bool gatt_cancel_open(tGATT_IF gatt_if, const RawAddress& bda) { BTM_AcceptlistRemove(bda); } log::info( - "Gatt connection manager has no background record but removed " - "filter acceptlist gatt_if:{} peer:{}", - gatt_if, bda); + "Gatt connection manager has no background record but removed " + "filter acceptlist gatt_if:{} peer:{}", + gatt_if, bda); } else { log::info( - "Gatt connection manager maintains a background record preserving " - "filter acceptlist gatt_if:{} peer:{}", - gatt_if, bda); + "Gatt connection manager maintains a background record preserving " + "filter acceptlist gatt_if:{} peer:{}", + gatt_if, bda); } } } @@ -1590,8 +1583,8 @@ bool gatt_cancel_open(tGATT_IF gatt_if, const RawAddress& bda) { } /** Enqueue this command */ -bool gatt_cmd_enq(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, bool to_send, - uint8_t op_code, BT_HDR* p_buf) { +bool gatt_cmd_enq(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, bool to_send, uint8_t op_code, + BT_HDR* p_buf) { tGATT_CMD_Q cmd; cmd.to_send = to_send; /* waiting to be sent */ cmd.op_code = op_code; @@ -1602,8 +1595,8 @@ bool gatt_cmd_enq(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, bool to_send, if (p_clcb->cid == tcb.att_lcid) { tcb.cl_cmd_q.push_back(cmd); } else { - EattChannel* channel = EattExtension::GetInstance()->FindEattChannelByCid( - tcb.peer_bda, cmd.cid); + EattChannel* channel = + EattExtension::GetInstance()->FindEattChannelByCid(tcb.peer_bda, cmd.cid); if (channel == nullptr) { log::warn("{}, cid 0x{:02x} already disconnected", tcb.peer_bda, cmd.cid); return false; @@ -1621,8 +1614,7 @@ tGATT_CLCB* gatt_cmd_dequeue(tGATT_TCB& tcb, uint16_t cid, uint8_t* p_op_code) { if (cid == tcb.att_lcid) { cl_cmd_q_p = &tcb.cl_cmd_q; } else { - EattChannel* channel = - EattExtension::GetInstance()->FindEattChannelByCid(tcb.peer_bda, cid); + EattChannel* channel = EattExtension::GetInstance()->FindEattChannelByCid(tcb.peer_bda, cid); if (channel == nullptr) { log::warn("{}, cid 0x{:02x} already disconnected", tcb.peer_bda, cid); return nullptr; @@ -1631,7 +1623,9 @@ tGATT_CLCB* gatt_cmd_dequeue(tGATT_TCB& tcb, uint16_t cid, uint8_t* p_op_code) { cl_cmd_q_p = &channel->cl_cmd_q_; } - if (cl_cmd_q_p->empty()) return nullptr; + if (cl_cmd_q_p->empty()) { + return nullptr; + } tGATT_CMD_Q cmd = cl_cmd_q_p->front(); tGATT_CLCB* p_clcb = cmd.p_clcb; @@ -1641,8 +1635,7 @@ tGATT_CLCB* gatt_cmd_dequeue(tGATT_TCB& tcb, uint16_t cid, uint8_t* p_op_code) { * peer, device p_clcb will be null. */ if (p_clcb && p_clcb->cid != cid) { - log::warn("CID does not match ({}!={}), conn_id=0x{:04x}", p_clcb->cid, cid, - p_clcb->conn_id); + log::warn("CID does not match ({}!={}), conn_id=0x{:04x}", p_clcb->cid, cid, p_clcb->conn_id); } cl_cmd_q_p->pop_front(); @@ -1651,9 +1644,8 @@ tGATT_CLCB* gatt_cmd_dequeue(tGATT_TCB& tcb, uint16_t cid, uint8_t* p_op_code) { } /** Send out the ATT message for write */ -tGATT_STATUS gatt_send_write_msg(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, - uint8_t op_code, uint16_t handle, uint16_t len, - uint16_t offset, uint8_t* p_data) { +tGATT_STATUS gatt_send_write_msg(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, uint8_t op_code, + uint16_t handle, uint16_t len, uint16_t offset, uint8_t* p_data) { tGATT_CL_MSG msg; msg.attr_value.handle = handle; msg.attr_value.len = len; @@ -1674,7 +1666,7 @@ tGATT_STATUS gatt_send_write_msg(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, * ******************************************************************************/ bool gatt_is_outstanding_msg_in_att_send_queue(const tGATT_TCB& tcb) { - return (!tcb.cl_cmd_q.empty() && (tcb.cl_cmd_q.front()).to_send); + return !tcb.cl_cmd_q.empty() && (tcb.cl_cmd_q.front()).to_send; } /******************************************************************************* * @@ -1688,17 +1680,15 @@ bool gatt_is_outstanding_msg_in_att_send_queue(const tGATT_TCB& tcb) { ******************************************************************************/ void gatt_end_operation(tGATT_CLCB* p_clcb, tGATT_STATUS status, void* p_data) { tGATT_CL_COMPLETE cb_data; - tGATT_CMPL_CBACK* p_cmpl_cb = - (p_clcb->p_reg) ? p_clcb->p_reg->app_cb.p_cmpl_cb : NULL; + tGATT_CMPL_CBACK* p_cmpl_cb = (p_clcb->p_reg) ? p_clcb->p_reg->app_cb.p_cmpl_cb : NULL; tGATTC_OPTYPE op = p_clcb->operation; tGATT_DISC_TYPE disc_type = GATT_DISC_MAX; tGATT_DISC_CMPL_CB* p_disc_cmpl_cb = - (p_clcb->p_reg) ? p_clcb->p_reg->app_cb.p_disc_cmpl_cb : NULL; + (p_clcb->p_reg) ? p_clcb->p_reg->app_cb.p_disc_cmpl_cb : NULL; uint16_t conn_id; uint8_t operation; - log::verbose("status={} op={} subtype={}", status, p_clcb->operation, - p_clcb->op_subtype); + log::verbose("status={} op={} subtype={}", status, p_clcb->operation, p_clcb->op_subtype); memset(&cb_data.att_value, 0, sizeof(tGATT_VALUE)); if (p_cmpl_cb != NULL && p_clcb->operation != 0) { @@ -1711,8 +1701,9 @@ void gatt_end_operation(tGATT_CLCB* p_clcb, tGATT_STATUS status, void* p_data) { cb_data.att_value.len = GATT_MAX_ATTR_LEN; } - if (p_data && p_clcb->counter) + if (p_data && p_clcb->counter) { memcpy(cb_data.att_value.value, p_data, cb_data.att_value.len); + } } if (p_clcb->operation == GATTC_OPTYPE_WRITE) { @@ -1727,8 +1718,9 @@ void gatt_end_operation(tGATT_CLCB* p_clcb, tGATT_STATUS status, void* p_data) { } } - if (p_clcb->operation == GATTC_OPTYPE_CONFIG) + if (p_clcb->operation == GATTC_OPTYPE_CONFIG) { cb_data.mtu = p_clcb->p_tcb->payload_size; + } if (p_clcb->operation == GATTC_OPTYPE_DISCOVERY) { disc_type = static_cast(p_clcb->op_subtype); @@ -1743,13 +1735,14 @@ void gatt_end_operation(tGATT_CLCB* p_clcb, tGATT_STATUS status, void* p_data) { gatt_clcb_dealloc(p_clcb); - if (p_disc_cmpl_cb && (op == GATTC_OPTYPE_DISCOVERY)) + if (p_disc_cmpl_cb && (op == GATTC_OPTYPE_DISCOVERY)) { (*p_disc_cmpl_cb)(conn_id, disc_type, status); - else if (p_cmpl_cb && op) + } else if (p_cmpl_cb && op) { (*p_cmpl_cb)(conn_id, op, status, &cb_data); - else + } else { log::warn("not sent out op={} p_disc_cmpl_cb:{} p_cmpl_cb:{}", operation, fmt::ptr(p_disc_cmpl_cb), fmt::ptr(p_cmpl_cb)); + } } static void gatt_le_disconnect_complete_notify_user(const RawAddress& bda, @@ -1761,17 +1754,15 @@ static void gatt_le_disconnect_complete_notify_user(const RawAddress& bda, tGATT_REG* p_reg = &gatt_cb.cl_rcb[i]; if (p_reg->in_use && p_reg->app_cb.p_conn_cb) { uint16_t conn_id = - p_tcb ? GATT_CREATE_CONN_ID(p_tcb->tcb_idx, p_reg->gatt_if) - : GATT_INVALID_CONN_ID; - (*p_reg->app_cb.p_conn_cb)(p_reg->gatt_if, bda, conn_id, - kGattDisconnected, reason, transport); + p_tcb ? GATT_CREATE_CONN_ID(p_tcb->tcb_idx, p_reg->gatt_if) : GATT_INVALID_CONN_ID; + (*p_reg->app_cb.p_conn_cb)(p_reg->gatt_if, bda, conn_id, kGattDisconnected, reason, + transport); } if (com::android::bluetooth::flags::gatt_reconnect_on_bt_on_fix()) { if (p_reg->direct_connect_request.count(bda) > 0) { - log::info( - "Removing device {} from the direct connect list of gatt_if {}", - bda, p_reg->gatt_if); + log::info("Removing device {} from the direct connect list of gatt_if {}", bda, + p_reg->gatt_if); p_reg->direct_connect_request.erase(bda); } } @@ -1786,16 +1777,13 @@ void gatt_cleanup_upon_disc(const RawAddress& bda, tGATT_DISCONN_REASON reason, tGATT_TCB* p_tcb = gatt_find_tcb_by_addr(bda, transport); if (!p_tcb) { if (!com::android::bluetooth::flags::gatt_reconnect_on_bt_on_fix()) { - log::error( - "Disconnect for unknown connection bd_addr:{} reason:{} transport:{}", - bda, gatt_disconnection_reason_text(reason), - bt_transport_text(transport)); + log::error("Disconnect for unknown connection bd_addr:{} reason:{} transport:{}", bda, + gatt_disconnection_reason_text(reason), bt_transport_text(transport)); return; } log::info("Connection timeout bd_addr:{} reason:{} transport:{}", bda, - gatt_disconnection_reason_text(reason), - bt_transport_text(transport)); + gatt_disconnection_reason_text(reason), bt_transport_text(transport)); /* Notify about timeout on direct connect */ gatt_le_disconnect_complete_notify_user(bda, reason, transport); @@ -1807,8 +1795,7 @@ void gatt_cleanup_upon_disc(const RawAddress& bda, tGATT_DISCONN_REASON reason, /* Notify EATT about disconnection. */ EattExtension::GetInstance()->Disconnect(p_tcb->peer_bda); - for (auto clcb_it = gatt_cb.clcb_queue.begin(); - clcb_it != gatt_cb.clcb_queue.end();) { + for (auto clcb_it = gatt_cb.clcb_queue.begin(); clcb_it != gatt_cb.clcb_queue.end();) { if (clcb_it->p_tcb != p_tcb) { ++clcb_it; continue; @@ -1863,21 +1850,23 @@ char const* gatt_dbg_op_name(uint8_t op_code) { } #define ARR_SIZE(a) (sizeof(a) / sizeof(a[0])) - if (pseduo_op_code_idx < ARR_SIZE(op_code_name)) + if (pseduo_op_code_idx < ARR_SIZE(op_code_name)) { return op_code_name[pseduo_op_code_idx]; - else + } else { return "Op Code Exceed Max"; + } #undef ARR_SIZE } /** Remove the application interface for the specified background device */ bool gatt_auto_connect_dev_remove(tGATT_IF gatt_if, const RawAddress& bd_addr) { tGATT_TCB* p_tcb = gatt_find_tcb_by_addr(bd_addr, BT_TRANSPORT_LE); - if (p_tcb) gatt_update_app_use_link_flag(gatt_if, p_tcb, false, false); - if (bluetooth::common::init_flags:: - use_unified_connection_manager_is_enabled()) { + if (p_tcb) { + gatt_update_app_use_link_flag(gatt_if, p_tcb, false, false); + } + if (bluetooth::common::init_flags::use_unified_connection_manager_is_enabled()) { bluetooth::connection::GetConnectionManager().remove_background_connection( - gatt_if, bluetooth::connection::ResolveRawAddress(bd_addr)); + gatt_if, bluetooth::connection::ResolveRawAddress(bd_addr)); // TODO(aryarahul): handle failure case return true; } else { diff --git a/system/stack/hcic/hciblecmds.cc b/system/stack/hcic/hciblecmds.cc index ea5ce1f61a2..10d283af906 100644 --- a/system/stack/hcic/hciblecmds.cc +++ b/system/stack/hcic/hciblecmds.cc @@ -69,8 +69,7 @@ #define HCIC_BLE_RAND_DI_SIZE 8 #define HCIC_BLE_ENCRYPT_KEY_SIZE 16 -#define HCIC_PARAM_SIZE_BLE_START_ENC \ - (4 + HCIC_BLE_RAND_DI_SIZE + HCIC_BLE_ENCRYPT_KEY_SIZE) +#define HCIC_PARAM_SIZE_BLE_START_ENC (4 + HCIC_BLE_RAND_DI_SIZE + HCIC_BLE_ENCRYPT_KEY_SIZE) #define HCIC_PARAM_SIZE_LTK_REQ_REPLY (2 + HCIC_BLE_ENCRYPT_KEY_SIZE) #define HCIC_PARAM_SIZE_LTK_REQ_NEG_REPLY 2 #define HCIC_BLE_CHNL_MAP_SIZE 5 @@ -84,7 +83,7 @@ #define HCIC_PARAM_SIZE_BLE_READ_RESOLVABLE_ADDR_PEER 7 #define HCIC_PARAM_SIZE_BLE_READ_RESOLVABLE_ADDR_LOCAL 7 #define HCIC_PARAM_SIZE_BLE_SET_ADDR_RESOLUTION_ENABLE 1 -#define HCIC_PARAM_SIZE_BLE_SET_RAND_PRIV_ADDR_TIMOUT 2 +#define HCIC_PARAM_SIZE_BLE_SET_RAND_PRIV_ADDR_TIMEOUT 2 #define HCIC_PARAM_SIZE_BLE_READ_PHY 2 #define HCIC_PARAM_SIZE_BLE_SET_DEFAULT_PHY 3 @@ -111,12 +110,9 @@ #define HCIC_PARAM_SIZE_SET_PERIODIC_ADVERTISING_SYNC_TRANSFER_PARAMS 8 #define HCIC_PARAM_SIZE_SET_DEFAULT_PERIODIC_ADVERTISING_SYNC_TRANSFER_PARAMS 8 -void btsnd_hcic_ble_write_adv_params(uint16_t adv_int_min, uint16_t adv_int_max, - uint8_t adv_type, - tBLE_ADDR_TYPE addr_type_own, - tBLE_ADDR_TYPE addr_type_dir, - const RawAddress& direct_bda, - uint8_t channel_map, +void btsnd_hcic_ble_write_adv_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type, + tBLE_ADDR_TYPE addr_type_own, tBLE_ADDR_TYPE addr_type_dir, + const RawAddress& direct_bda, uint8_t channel_map, uint8_t adv_filter_policy) { BT_HDR* p = (BT_HDR*)osi_malloc(HCI_CMD_BUF_SIZE); uint8_t* pp = (uint8_t*)(p + 1); @@ -164,8 +160,9 @@ void btsnd_hcic_ble_set_adv_data(uint8_t data_len, uint8_t* p_data) { memset(pp, 0, HCIC_PARAM_SIZE_BLE_WRITE_ADV_DATA); if (p_data != NULL && data_len > 0) { - if (data_len > HCIC_PARAM_SIZE_BLE_WRITE_ADV_DATA) + if (data_len > HCIC_PARAM_SIZE_BLE_WRITE_ADV_DATA) { data_len = HCIC_PARAM_SIZE_BLE_WRITE_ADV_DATA; + } UINT8_TO_STREAM(pp, data_len); @@ -188,9 +185,8 @@ void btsnd_hcic_ble_set_adv_enable(uint8_t adv_enable) { btu_hcif_send_cmd(LOCAL_BR_EDR_CONTROLLER_ID, p); } -void btsnd_hcic_ble_set_scan_params(uint8_t scan_type, uint16_t scan_int, - uint16_t scan_win, uint8_t addr_type_own, - uint8_t scan_filter_policy) { +void btsnd_hcic_ble_set_scan_params(uint8_t scan_type, uint16_t scan_int, uint16_t scan_win, + uint8_t addr_type_own, uint8_t scan_filter_policy) { BT_HDR* p = (BT_HDR*)osi_malloc(HCI_CMD_BUF_SIZE); uint8_t* pp = (uint8_t*)(p + 1); @@ -241,21 +237,19 @@ void btsnd_hcic_ble_read_remote_feat(uint16_t handle) { } void btsnd_hcic_ble_rand(base::Callback cb) { - btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_BLE_RAND, nullptr, 0, - base::Bind( - [](base::Callback cb, - uint8_t* param, uint16_t /* param_len */) { - bluetooth::log::assert_that( - param[0] == 0, - "LE Rand return status must be zero"); - cb.Run(param + 1 /* skip status */); - }, - std::move(cb))); -} - -void btsnd_hcic_ble_start_enc(uint16_t handle, - uint8_t rand[HCIC_BLE_RAND_DI_SIZE], - uint16_t ediv, const Octet16& ltk) { + btu_hcif_send_cmd_with_cb( + FROM_HERE, HCI_BLE_RAND, nullptr, 0, + base::Bind( + [](base::Callback cb, uint8_t* param, uint16_t /* param_len */) { + bluetooth::log::assert_that(param[0] == 0, + "LE Rand return status must be zero"); + cb.Run(param + 1 /* skip status */); + }, + std::move(cb))); +} + +void btsnd_hcic_ble_start_enc(uint16_t handle, uint8_t rand[HCIC_BLE_RAND_DI_SIZE], uint16_t ediv, + const Octet16& ltk) { BT_HDR* p = (BT_HDR*)osi_malloc(HCI_CMD_BUF_SIZE); uint8_t* pp = (uint8_t*)(p + 1); @@ -319,8 +313,7 @@ void btsnd_hcic_ble_receiver_test(uint8_t rx_freq) { btu_hcif_send_cmd(LOCAL_BR_EDR_CONTROLLER_ID, p); } -void btsnd_hcic_ble_transmitter_test(uint8_t tx_freq, uint8_t test_data_len, - uint8_t payload) { +void btsnd_hcic_ble_transmitter_test(uint8_t tx_freq, uint8_t test_data_len, uint8_t payload) { BT_HDR* p = (BT_HDR*)osi_malloc(HCI_CMD_BUF_SIZE); uint8_t* pp = (uint8_t*)(p + 1); @@ -350,8 +343,7 @@ void btsnd_hcic_ble_test_end(void) { btu_hcif_send_cmd(LOCAL_BR_EDR_CONTROLLER_ID, p); } -void btsnd_hcic_ble_read_resolvable_addr_peer(uint8_t addr_type_peer, - const RawAddress& bda_peer) { +void btsnd_hcic_ble_read_resolvable_addr_peer(uint8_t addr_type_peer, const RawAddress& bda_peer) { BT_HDR* p = (BT_HDR*)osi_malloc(HCI_CMD_BUF_SIZE); uint8_t* pp = (uint8_t*)(p + 1); @@ -366,22 +358,21 @@ void btsnd_hcic_ble_read_resolvable_addr_peer(uint8_t addr_type_peer, btu_hcif_send_cmd(LOCAL_BR_EDR_CONTROLLER_ID, p); } -void btsnd_hcic_ble_set_rand_priv_addr_timeout(uint16_t rpa_timout) { +void btsnd_hcic_ble_set_rand_priv_addr_timeout(uint16_t rpa_timeout) { BT_HDR* p = (BT_HDR*)osi_malloc(HCI_CMD_BUF_SIZE); uint8_t* pp = (uint8_t*)(p + 1); - p->len = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_BLE_SET_RAND_PRIV_ADDR_TIMOUT; + p->len = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_BLE_SET_RAND_PRIV_ADDR_TIMEOUT; p->offset = 0; - UINT16_TO_STREAM(pp, HCI_BLE_SET_RAND_PRIV_ADDR_TIMOUT); - UINT8_TO_STREAM(pp, HCIC_PARAM_SIZE_BLE_SET_RAND_PRIV_ADDR_TIMOUT); - UINT16_TO_STREAM(pp, rpa_timout); + UINT16_TO_STREAM(pp, HCI_BLE_SET_RAND_PRIV_ADDR_TIMEOUT); + UINT8_TO_STREAM(pp, HCIC_PARAM_SIZE_BLE_SET_RAND_PRIV_ADDR_TIMEOUT); + UINT16_TO_STREAM(pp, rpa_timeout); btu_hcif_send_cmd(LOCAL_BR_EDR_CONTROLLER_ID, p); } -void btsnd_hcic_ble_set_data_length(uint16_t conn_handle, uint16_t tx_octets, - uint16_t tx_time) { +void btsnd_hcic_ble_set_data_length(uint16_t conn_handle, uint16_t tx_octets, uint16_t tx_time) { BT_HDR* p = (BT_HDR*)osi_malloc(HCI_CMD_BUF_SIZE); uint8_t* pp = (uint8_t*)(p + 1); @@ -399,14 +390,12 @@ void btsnd_hcic_ble_set_data_length(uint16_t conn_handle, uint16_t tx_octets, } void btsnd_hcic_ble_set_extended_scan_params(uint8_t own_address_type, - uint8_t scanning_filter_policy, - uint8_t scanning_phys, + uint8_t scanning_filter_policy, uint8_t scanning_phys, scanning_phy_cfg* phy_cfg) { BT_HDR* p = (BT_HDR*)osi_malloc(HCI_CMD_BUF_SIZE); uint8_t* pp = (uint8_t*)(p + 1); - int phy_cnt = - std::bitset::digits>(scanning_phys).count(); + int phy_cnt = std::bitset::digits>(scanning_phys).count(); uint16_t param_len = 3 + (5 * phy_cnt); p->len = HCIC_PREAMBLE_SIZE + param_len; @@ -428,10 +417,8 @@ void btsnd_hcic_ble_set_extended_scan_params(uint8_t own_address_type, btu_hcif_send_cmd(LOCAL_BR_EDR_CONTROLLER_ID, p); } -void btsnd_hcic_ble_set_extended_scan_enable(uint8_t enable, - uint8_t filter_duplicates, - uint16_t duration, - uint16_t period) { +void btsnd_hcic_ble_set_extended_scan_enable(uint8_t enable, uint8_t filter_duplicates, + uint16_t duration, uint16_t period) { BT_HDR* p = (BT_HDR*)osi_malloc(HCI_CMD_BUF_SIZE); uint8_t* pp = (uint8_t*)(p + 1); @@ -450,11 +437,11 @@ void btsnd_hcic_ble_set_extended_scan_enable(uint8_t enable, btu_hcif_send_cmd(LOCAL_BR_EDR_CONTROLLER_ID, p); } -void btsnd_hcic_set_cig_params( - uint8_t cig_id, uint32_t sdu_itv_mtos, uint32_t sdu_itv_stom, uint8_t sca, - uint8_t packing, uint8_t framing, uint16_t max_trans_lat_stom, - uint16_t max_trans_lat_mtos, uint8_t cis_cnt, const EXT_CIS_CFG* cis_cfg, - base::OnceCallback cb) { +void btsnd_hcic_set_cig_params(uint8_t cig_id, uint32_t sdu_itv_mtos, uint32_t sdu_itv_stom, + uint8_t sca, uint8_t packing, uint8_t framing, + uint16_t max_trans_lat_stom, uint16_t max_trans_lat_mtos, + uint8_t cis_cnt, const EXT_CIS_CFG* cis_cfg, + base::OnceCallback cb) { const int params_len = 15 + cis_cnt * 9; uint8_t param[params_len]; uint8_t* pp = param; @@ -479,8 +466,7 @@ void btsnd_hcic_set_cig_params( UINT8_TO_STREAM(pp, cis_cfg[i].rtn_stom); } - btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_LE_SET_CIG_PARAMS, param, params_len, - std::move(cb)); + btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_LE_SET_CIG_PARAMS, param, params_len, std::move(cb)); } void btsnd_hcic_create_cis(uint8_t num_cis, const EXT_CIS_CREATE_CFG* cis_cfg, @@ -496,20 +482,17 @@ void btsnd_hcic_create_cis(uint8_t num_cis, const EXT_CIS_CREATE_CFG* cis_cfg, UINT16_TO_STREAM(pp, cis_cfg[i].acl_conn_handle); } - btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_LE_CREATE_CIS, param, params_len, - std::move(cb)); + btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_LE_CREATE_CIS, param, params_len, std::move(cb)); } -void btsnd_hcic_remove_cig(uint8_t cig_id, - base::OnceCallback cb) { +void btsnd_hcic_remove_cig(uint8_t cig_id, base::OnceCallback cb) { const int params_len = 1; uint8_t param[params_len]; uint8_t* pp = param; UINT8_TO_STREAM(pp, cig_id); - btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_LE_REMOVE_CIG, param, params_len, - std::move(cb)); + btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_LE_REMOVE_CIG, param, params_len, std::move(cb)); } void btsnd_hcic_req_peer_sca(uint16_t conn_handle) { @@ -527,11 +510,9 @@ void btsnd_hcic_req_peer_sca(uint16_t conn_handle) { btu_hcif_send_cmd(LOCAL_BR_EDR_CONTROLLER_ID, p); } -void btsnd_hcic_create_big(uint8_t big_handle, uint8_t adv_handle, - uint8_t num_bis, uint32_t sdu_itv, - uint16_t max_sdu_size, uint16_t transport_latency, - uint8_t rtn, uint8_t phy, uint8_t packing, - uint8_t framing, uint8_t enc, +void btsnd_hcic_create_big(uint8_t big_handle, uint8_t adv_handle, uint8_t num_bis, + uint32_t sdu_itv, uint16_t max_sdu_size, uint16_t transport_latency, + uint8_t rtn, uint8_t phy, uint8_t packing, uint8_t framing, uint8_t enc, std::array bcst_code) { BT_HDR* p = (BT_HDR*)osi_malloc(HCI_CMD_BUF_SIZE); uint8_t* pp = (uint8_t*)(p + 1); @@ -578,12 +559,11 @@ void btsnd_hcic_term_big(uint8_t big_handle, uint8_t reason) { btu_hcif_send_cmd(LOCAL_BR_EDR_CONTROLLER_ID, p); } -void btsnd_hcic_setup_iso_data_path( - uint16_t iso_handle, uint8_t data_path_dir, uint8_t data_path_id, - uint8_t codec_id_format, uint16_t codec_id_company, - uint16_t codec_id_vendor, uint32_t controller_delay, - std::vector codec_conf, - base::OnceCallback cb) { +void btsnd_hcic_setup_iso_data_path(uint16_t iso_handle, uint8_t data_path_dir, + uint8_t data_path_id, uint8_t codec_id_format, + uint16_t codec_id_company, uint16_t codec_id_vendor, + uint32_t controller_delay, std::vector codec_conf, + base::OnceCallback cb) { const int params_len = 13 + codec_conf.size(); uint8_t param[params_len]; uint8_t* pp = param; @@ -598,13 +578,12 @@ void btsnd_hcic_setup_iso_data_path( UINT8_TO_STREAM(pp, codec_conf.size()); ARRAY_TO_STREAM(pp, codec_conf.data(), static_cast(codec_conf.size())); - btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_LE_SETUP_ISO_DATA_PATH, param, - params_len, std::move(cb)); + btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_LE_SETUP_ISO_DATA_PATH, param, params_len, + std::move(cb)); } -void btsnd_hcic_remove_iso_data_path( - uint16_t iso_handle, uint8_t data_path_dir, - base::OnceCallback cb) { +void btsnd_hcic_remove_iso_data_path(uint16_t iso_handle, uint8_t data_path_dir, + base::OnceCallback cb) { const int params_len = 3; uint8_t param[params_len]; uint8_t* pp = param; @@ -612,31 +591,30 @@ void btsnd_hcic_remove_iso_data_path( UINT16_TO_STREAM(pp, iso_handle); UINT8_TO_STREAM(pp, data_path_dir); - btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_LE_REMOVE_ISO_DATA_PATH, param, - params_len, std::move(cb)); + btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_LE_REMOVE_ISO_DATA_PATH, param, params_len, + std::move(cb)); } -void btsnd_hcic_read_iso_link_quality( - uint16_t iso_handle, base::OnceCallback cb) { +void btsnd_hcic_read_iso_link_quality(uint16_t iso_handle, + base::OnceCallback cb) { const int params_len = 2; uint8_t param[params_len]; uint8_t* pp = param; UINT16_TO_STREAM(pp, iso_handle); - btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_LE_READ_ISO_LINK_QUALITY, param, - params_len, std::move(cb)); + btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_LE_READ_ISO_LINK_QUALITY, param, params_len, + std::move(cb)); } -void btsnd_hcic_ble_periodic_advertising_create_sync( - uint8_t options, uint8_t adv_sid, uint8_t adv_addr_type, - const RawAddress& adv_addr, uint16_t skip_num, uint16_t sync_timeout, - uint8_t sync_cte_type) { +void btsnd_hcic_ble_periodic_advertising_create_sync(uint8_t options, uint8_t adv_sid, + uint8_t adv_addr_type, + const RawAddress& adv_addr, uint16_t skip_num, + uint16_t sync_timeout, uint8_t sync_cte_type) { BT_HDR* p = (BT_HDR*)osi_malloc(HCI_CMD_BUF_SIZE); uint8_t* pp = (uint8_t*)(p + 1); - p->len = - HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_PERIODIC_ADVERTISING_CREATE_SYNC; + p->len = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_PERIODIC_ADVERTISING_CREATE_SYNC; p->offset = 0; UINT16_TO_STREAM(pp, HCI_BLE_PERIODIC_ADVERTISING_CREATE_SYNC); @@ -653,27 +631,25 @@ void btsnd_hcic_ble_periodic_advertising_create_sync( } void btsnd_hcic_ble_periodic_advertising_create_sync_cancel( - base::OnceCallback cb) { - btu_hcif_send_cmd_with_cb( - FROM_HERE, HCI_BLE_PERIODIC_ADVERTISING_CREATE_SYNC_CANCEL, nullptr, - HCIC_PARAM_SIZE_PERIODIC_ADVERTISING_CREATE_SYNC_CANCEL, std::move(cb)); + base::OnceCallback cb) { + btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_BLE_PERIODIC_ADVERTISING_CREATE_SYNC_CANCEL, nullptr, + HCIC_PARAM_SIZE_PERIODIC_ADVERTISING_CREATE_SYNC_CANCEL, std::move(cb)); } void btsnd_hcic_ble_periodic_advertising_terminate_sync( - uint16_t sync_handle, base::OnceCallback cb) { + uint16_t sync_handle, base::OnceCallback cb) { uint8_t param[HCIC_PARAM_SIZE_PERIODIC_ADVERTISING_TERMINATE_SYNC]; uint8_t* pp = param; UINT16_TO_STREAM(pp, sync_handle); - btu_hcif_send_cmd_with_cb( - FROM_HERE, HCI_BLE_PERIODIC_ADVERTISING_TERMINATE_SYNC, param, - HCIC_PARAM_SIZE_PERIODIC_ADVERTISING_TERMINATE_SYNC, std::move(cb)); + btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_BLE_PERIODIC_ADVERTISING_TERMINATE_SYNC, param, + HCIC_PARAM_SIZE_PERIODIC_ADVERTISING_TERMINATE_SYNC, std::move(cb)); } void btsnd_hci_ble_add_device_to_periodic_advertiser_list( - uint8_t adv_addr_type, const RawAddress& adv_addr, uint8_t adv_sid, - base::OnceCallback cb) { + uint8_t adv_addr_type, const RawAddress& adv_addr, uint8_t adv_sid, + base::OnceCallback cb) { uint8_t param[HCIC_PARAM_SIZE_ADD_DEVICE_TO_PERIODIC_ADVERTISER_LIST]; uint8_t* pp = param; @@ -681,14 +657,13 @@ void btsnd_hci_ble_add_device_to_periodic_advertiser_list( BDADDR_TO_STREAM(pp, adv_addr); UINT8_TO_STREAM(pp, adv_sid); - btu_hcif_send_cmd_with_cb( - FROM_HERE, HCI_BLE_ADD_DEVICE_TO_PERIODIC_ADVERTISER_LIST, param, - HCIC_PARAM_SIZE_ADD_DEVICE_TO_PERIODIC_ADVERTISER_LIST, std::move(cb)); + btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_BLE_ADD_DEVICE_TO_PERIODIC_ADVERTISER_LIST, param, + HCIC_PARAM_SIZE_ADD_DEVICE_TO_PERIODIC_ADVERTISER_LIST, std::move(cb)); } void btsnd_hci_ble_remove_device_from_periodic_advertiser_list( - uint8_t adv_addr_type, const RawAddress& adv_addr, uint8_t adv_sid, - base::OnceCallback cb) { + uint8_t adv_addr_type, const RawAddress& adv_addr, uint8_t adv_sid, + base::OnceCallback cb) { uint8_t param[HCIC_PARAM_SIZE_REMOVE_DEVICE_FROM_PERIODIC_ADVERTISER_LIST]; uint8_t* pp = param; @@ -696,36 +671,31 @@ void btsnd_hci_ble_remove_device_from_periodic_advertiser_list( BDADDR_TO_STREAM(pp, adv_addr); UINT8_TO_STREAM(pp, adv_sid); - btu_hcif_send_cmd_with_cb( - FROM_HERE, HCI_BLE_REMOVE_DEVICE_FROM_PERIODIC_ADVERTISER_LIST, param, - HCIC_PARAM_SIZE_REMOVE_DEVICE_FROM_PERIODIC_ADVERTISER_LIST, - std::move(cb)); + btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_BLE_REMOVE_DEVICE_FROM_PERIODIC_ADVERTISER_LIST, param, + HCIC_PARAM_SIZE_REMOVE_DEVICE_FROM_PERIODIC_ADVERTISER_LIST, + std::move(cb)); } -void btsnd_hci_ble_clear_periodic_advertiser_list( - base::OnceCallback cb) { - btu_hcif_send_cmd_with_cb( - FROM_HERE, HCI_BLE_CLEAR_PERIODIC_ADVERTISER_LIST, nullptr, - HCIC_PARAM_SIZE_CLEAR_PERIODIC_ADVERTISER_LIST, std::move(cb)); +void btsnd_hci_ble_clear_periodic_advertiser_list(base::OnceCallback cb) { + btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_BLE_CLEAR_PERIODIC_ADVERTISER_LIST, nullptr, + HCIC_PARAM_SIZE_CLEAR_PERIODIC_ADVERTISER_LIST, std::move(cb)); } void btsnd_hcic_ble_set_periodic_advertising_receive_enable( - uint16_t sync_handle, bool enable, - base::OnceCallback cb) { + uint16_t sync_handle, bool enable, base::OnceCallback cb) { uint8_t param[HCIC_PARAM_SIZE_SET_PERIODIC_ADVERTISING_RECEIVE_ENABLE]; uint8_t* pp = param; UINT16_TO_STREAM(pp, sync_handle); UINT8_TO_STREAM(pp, (enable ? 0x01 : 0x00)); - btu_hcif_send_cmd_with_cb( - FROM_HERE, HCI_LE_SET_PERIODIC_ADVERTISING_RECEIVE_ENABLE, param, - HCIC_PARAM_SIZE_SET_PERIODIC_ADVERTISING_RECEIVE_ENABLE, std::move(cb)); + btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_LE_SET_PERIODIC_ADVERTISING_RECEIVE_ENABLE, param, + HCIC_PARAM_SIZE_SET_PERIODIC_ADVERTISING_RECEIVE_ENABLE, std::move(cb)); } void btsnd_hcic_ble_periodic_advertising_sync_transfer( - uint16_t conn_handle, uint16_t service_data, uint16_t sync_handle, - base::OnceCallback cb) { + uint16_t conn_handle, uint16_t service_data, uint16_t sync_handle, + base::OnceCallback cb) { uint8_t param[HCIC_PARAM_SIZE_PERIODIC_ADVERTISING_SYNC_TRANSFER]; uint8_t* pp = param; @@ -733,14 +703,13 @@ void btsnd_hcic_ble_periodic_advertising_sync_transfer( UINT16_TO_STREAM(pp, service_data); UINT16_TO_STREAM(pp, sync_handle); - btu_hcif_send_cmd_with_cb( - FROM_HERE, HCI_LE_PERIODIC_ADVERTISING_SYNC_TRANSFER, param, - HCIC_PARAM_SIZE_PERIODIC_ADVERTISING_SYNC_TRANSFER, std::move(cb)); + btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_LE_PERIODIC_ADVERTISING_SYNC_TRANSFER, param, + HCIC_PARAM_SIZE_PERIODIC_ADVERTISING_SYNC_TRANSFER, std::move(cb)); } void btsnd_hcic_ble_periodic_advertising_set_info_transfer( - uint16_t conn_handle, uint16_t service_data, uint8_t adv_handle, - base::OnceCallback cb) { + uint16_t conn_handle, uint16_t service_data, uint8_t adv_handle, + base::OnceCallback cb) { uint8_t param[HCIC_PARAM_SIZE_PERIODIC_ADVERTISING_SET_INFO_TRANSFER]; uint8_t* pp = param; @@ -748,14 +717,13 @@ void btsnd_hcic_ble_periodic_advertising_set_info_transfer( UINT16_TO_STREAM(pp, service_data); UINT8_TO_STREAM(pp, adv_handle); - btu_hcif_send_cmd_with_cb( - FROM_HERE, HCI_LE_PERIODIC_ADVERTISING_SET_INFO_TRANSFER, param, - HCIC_PARAM_SIZE_PERIODIC_ADVERTISING_SET_INFO_TRANSFER, std::move(cb)); + btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_LE_PERIODIC_ADVERTISING_SET_INFO_TRANSFER, param, + HCIC_PARAM_SIZE_PERIODIC_ADVERTISING_SET_INFO_TRANSFER, std::move(cb)); } void btsnd_hcic_ble_set_periodic_advertising_sync_transfer_params( - uint16_t conn_handle, uint8_t mode, uint16_t skip, uint16_t sync_timeout, - uint8_t cte_type, base::OnceCallback cb) { + uint16_t conn_handle, uint8_t mode, uint16_t skip, uint16_t sync_timeout, uint8_t cte_type, + base::OnceCallback cb) { uint8_t param[HCIC_PARAM_SIZE_SET_PERIODIC_ADVERTISING_SYNC_TRANSFER_PARAMS]; uint8_t* pp = param; @@ -765,17 +733,15 @@ void btsnd_hcic_ble_set_periodic_advertising_sync_transfer_params( UINT16_TO_STREAM(pp, sync_timeout); UINT8_TO_STREAM(pp, cte_type); - btu_hcif_send_cmd_with_cb( - FROM_HERE, HCI_LE_SET_PERIODIC_ADVERTISING_SYNC_TRANSFER_PARAM, param, - HCIC_PARAM_SIZE_SET_PERIODIC_ADVERTISING_SYNC_TRANSFER_PARAMS, - std::move(cb)); + btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_LE_SET_PERIODIC_ADVERTISING_SYNC_TRANSFER_PARAM, param, + HCIC_PARAM_SIZE_SET_PERIODIC_ADVERTISING_SYNC_TRANSFER_PARAMS, + std::move(cb)); } void btsnd_hcic_ble_set_default_periodic_advertising_sync_transfer_params( - uint16_t conn_handle, uint8_t mode, uint16_t skip, uint16_t sync_timeout, - uint8_t cte_type, base::OnceCallback cb) { - uint8_t param - [HCIC_PARAM_SIZE_SET_DEFAULT_PERIODIC_ADVERTISING_SYNC_TRANSFER_PARAMS]; + uint16_t conn_handle, uint8_t mode, uint16_t skip, uint16_t sync_timeout, uint8_t cte_type, + base::OnceCallback cb) { + uint8_t param[HCIC_PARAM_SIZE_SET_DEFAULT_PERIODIC_ADVERTISING_SYNC_TRANSFER_PARAMS]; uint8_t* pp = param; UINT16_TO_STREAM(pp, conn_handle); @@ -785,8 +751,6 @@ void btsnd_hcic_ble_set_default_periodic_advertising_sync_transfer_params( UINT8_TO_STREAM(pp, cte_type); btu_hcif_send_cmd_with_cb( - FROM_HERE, HCI_LE_SET_DEFAULT_PERIODIC_ADVERTISING_SYNC_TRANSFER_PARAM, - param, - HCIC_PARAM_SIZE_SET_DEFAULT_PERIODIC_ADVERTISING_SYNC_TRANSFER_PARAMS, - std::move(cb)); + FROM_HERE, HCI_LE_SET_DEFAULT_PERIODIC_ADVERTISING_SYNC_TRANSFER_PARAM, param, + HCIC_PARAM_SIZE_SET_DEFAULT_PERIODIC_ADVERTISING_SYNC_TRANSFER_PARAMS, std::move(cb)); } diff --git a/system/stack/hcic/hcicmds.cc b/system/stack/hcic/hcicmds.cc index d0a13653452..4183df86c26 100644 --- a/system/stack/hcic/hcicmds.cc +++ b/system/stack/hcic/hcicmds.cc @@ -444,8 +444,7 @@ #define HCIC_BLE_RAND_DI_SIZE 8 #define HCIC_BLE_ENCRYPT_KEY_SIZE 16 -#define HCIC_PARAM_SIZE_BLE_START_ENC \ - (4 + HCIC_BLE_RAND_DI_SIZE + HCIC_BLE_ENCRYPT_KEY_SIZE) +#define HCIC_PARAM_SIZE_BLE_START_ENC (4 + HCIC_BLE_RAND_DI_SIZE + HCIC_BLE_ENCRYPT_KEY_SIZE) #define HCIC_PARAM_SIZE_LTK_REQ_REPLY (2 + HCIC_BLE_ENCRYPT_KEY_SIZE) #define HCIC_PARAM_SIZE_LTK_REQ_NEG_REPLY 2 #define HCIC_BLE_CHNL_MAP_SIZE 5 @@ -459,7 +458,7 @@ #define HCIC_PARAM_SIZE_BLE_READ_RESOLVABLE_ADDR_PEER 7 #define HCIC_PARAM_SIZE_BLE_READ_RESOLVABLE_ADDR_LOCAL 7 #define HCIC_PARAM_SIZE_BLE_SET_ADDR_RESOLUTION_ENABLE 1 -#define HCIC_PARAM_SIZE_BLE_SET_RAND_PRIV_ADDR_TIMOUT 2 +#define HCIC_PARAM_SIZE_BLE_SET_RAND_PRIV_ADDR_TIMEOUT 2 #define HCIC_PARAM_SIZE_BLE_READ_PHY 2 #define HCIC_PARAM_SIZE_BLE_SET_DEFAULT_PHY 3 @@ -535,8 +534,7 @@ void btsnd_hcic_reject_conn(const RawAddress& dest, uint8_t reason) { btu_hcif_send_cmd(LOCAL_BR_EDR_CONTROLLER_ID, p); } -void btsnd_hcic_link_key_req_reply(const RawAddress& bd_addr, - const LinkKey& link_key) { +void btsnd_hcic_link_key_req_reply(const RawAddress& bd_addr, const LinkKey& link_key) { BT_HDR* p = (BT_HDR*)osi_malloc(HCI_CMD_BUF_SIZE); uint8_t* pp = (uint8_t*)(p + 1); @@ -567,8 +565,8 @@ void btsnd_hcic_link_key_neg_reply(const RawAddress& bd_addr) { btu_hcif_send_cmd(LOCAL_BR_EDR_CONTROLLER_ID, p); } -void btsnd_hcic_pin_code_req_reply(const RawAddress& bd_addr, - uint8_t pin_code_len, PIN_CODE pin_code) { +void btsnd_hcic_pin_code_req_reply(const RawAddress& bd_addr, uint8_t pin_code_len, + PIN_CODE pin_code) { BT_HDR* p = (BT_HDR*)osi_malloc(HCI_CMD_BUF_SIZE); uint8_t* pp = (uint8_t*)(p + 1); int i; @@ -582,9 +580,13 @@ void btsnd_hcic_pin_code_req_reply(const RawAddress& bd_addr, BDADDR_TO_STREAM(pp, bd_addr); UINT8_TO_STREAM(pp, pin_code_len); - for (i = 0; i < pin_code_len; i++) *pp++ = *pin_code++; + for (i = 0; i < pin_code_len; i++) { + *pp++ = *pin_code++; + } - for (; i < PIN_CODE_LEN; i++) *pp++ = 0; + for (; i < PIN_CODE_LEN; i++) { + *pp++ = 0; + } btu_hcif_send_cmd(LOCAL_BR_EDR_CONTROLLER_ID, p); } @@ -698,8 +700,7 @@ void btsnd_hcic_read_rmt_clk_offset(uint16_t handle) { } void btsnd_hcic_setup_esco_conn(uint16_t handle, uint32_t transmit_bandwidth, - uint32_t receive_bandwidth, - uint16_t max_latency, uint16_t voice, + uint32_t receive_bandwidth, uint16_t max_latency, uint16_t voice, uint8_t retrans_effort, uint16_t packet_types) { BT_HDR* p = (BT_HDR*)osi_malloc(HCI_CMD_BUF_SIZE); uint8_t* pp = (uint8_t*)(p + 1); @@ -721,11 +722,9 @@ void btsnd_hcic_setup_esco_conn(uint16_t handle, uint32_t transmit_bandwidth, btu_hcif_send_cmd(LOCAL_BR_EDR_CONTROLLER_ID, p); } -void btsnd_hcic_accept_esco_conn(const RawAddress& bd_addr, - uint32_t transmit_bandwidth, - uint32_t receive_bandwidth, - uint16_t max_latency, uint16_t content_fmt, - uint8_t retrans_effort, +void btsnd_hcic_accept_esco_conn(const RawAddress& bd_addr, uint32_t transmit_bandwidth, + uint32_t receive_bandwidth, uint16_t max_latency, + uint16_t content_fmt, uint8_t retrans_effort, uint16_t packet_types) { BT_HDR* p = (BT_HDR*)osi_malloc(HCI_CMD_BUF_SIZE); uint8_t* pp = (uint8_t*)(p + 1); @@ -763,8 +762,7 @@ void btsnd_hcic_reject_esco_conn(const RawAddress& bd_addr, uint8_t reason) { btu_hcif_send_cmd(LOCAL_BR_EDR_CONTROLLER_ID, p); } -void btsnd_hcic_hold_mode(uint16_t handle, uint16_t max_hold_period, - uint16_t min_hold_period) { +void btsnd_hcic_hold_mode(uint16_t handle, uint16_t max_hold_period, uint16_t min_hold_period) { BT_HDR* p = (BT_HDR*)osi_malloc(HCI_CMD_BUF_SIZE); uint8_t* pp = (uint8_t*)(p + 1); @@ -781,9 +779,8 @@ void btsnd_hcic_hold_mode(uint16_t handle, uint16_t max_hold_period, btu_hcif_send_cmd(LOCAL_BR_EDR_CONTROLLER_ID, p); } -void btsnd_hcic_sniff_mode(uint16_t handle, uint16_t max_sniff_period, - uint16_t min_sniff_period, uint16_t sniff_attempt, - uint16_t sniff_timeout) { +void btsnd_hcic_sniff_mode(uint16_t handle, uint16_t max_sniff_period, uint16_t min_sniff_period, + uint16_t sniff_attempt, uint16_t sniff_timeout) { BT_HDR* p = (BT_HDR*)osi_malloc(HCI_CMD_BUF_SIZE); uint8_t* pp = (uint8_t*)(p + 1); @@ -895,8 +892,8 @@ void btsnd_hcic_write_def_policy_set(uint16_t settings) { btu_hcif_send_cmd(LOCAL_BR_EDR_CONTROLLER_ID, p); } -void btsnd_hcic_set_event_filter(uint8_t filt_type, uint8_t filt_cond_type, - uint8_t* filt_cond, uint8_t filt_cond_len) { +void btsnd_hcic_set_event_filter(uint8_t filt_type, uint8_t filt_cond_type, uint8_t* filt_cond, + uint8_t filt_cond_len) { BT_HDR* p = (BT_HDR*)osi_malloc(HCI_CMD_BUF_SIZE); uint8_t* pp = (uint8_t*)(p + 1); @@ -925,7 +922,9 @@ void btsnd_hcic_set_event_filter(uint8_t filt_type, uint8_t filt_cond_type, filt_cond_len -= BD_ADDR_LEN; } - if (filt_cond_len) ARRAY_TO_STREAM(pp, filt_cond, filt_cond_len); + if (filt_cond_len) { + ARRAY_TO_STREAM(pp, filt_cond, filt_cond_len); + } } else { p->len = (uint16_t)(HCIC_PREAMBLE_SIZE + 1); UINT8_TO_STREAM(pp, 1); @@ -951,8 +950,7 @@ void btsnd_hcic_write_pin_type(uint8_t type) { btu_hcif_send_cmd(LOCAL_BR_EDR_CONTROLLER_ID, p); } -void btsnd_hcic_delete_stored_key(const RawAddress& bd_addr, - bool delete_all_flag) { +void btsnd_hcic_delete_stored_key(const RawAddress& bd_addr, bool delete_all_flag) { BT_HDR* p = (BT_HDR*)osi_malloc(HCI_CMD_BUF_SIZE); uint8_t* pp = (uint8_t*)(p + 1); @@ -1148,7 +1146,9 @@ void btsnd_hcic_write_cur_iac_lap(uint8_t num_cur_iac, LAP* const iac_lap) { UINT8_TO_STREAM(pp, num_cur_iac); - for (int i = 0; i < num_cur_iac; i++) LAP_TO_STREAM(pp, iac_lap[i]); + for (int i = 0; i < num_cur_iac; i++) { + LAP_TO_STREAM(pp, iac_lap[i]); + } btu_hcif_send_cmd(LOCAL_BR_EDR_CONTROLLER_ID, p); } @@ -1156,8 +1156,7 @@ void btsnd_hcic_write_cur_iac_lap(uint8_t num_cur_iac, LAP* const iac_lap) { /****************************************** * Lisbon Features ******************************************/ -void btsnd_hcic_sniff_sub_rate(uint16_t handle, uint16_t max_lat, - uint16_t min_remote_lat, +void btsnd_hcic_sniff_sub_rate(uint16_t handle, uint16_t max_lat, uint16_t min_remote_lat, uint16_t min_local_lat) { BT_HDR* p = (BT_HDR*)osi_malloc(HCI_CMD_BUF_SIZE); uint8_t* pp = (uint8_t*)(p + 1); @@ -1192,8 +1191,8 @@ void btsnd_hcic_write_ext_inquiry_response(void* buffer, uint8_t fec_req) { btu_hcif_send_cmd(LOCAL_BR_EDR_CONTROLLER_ID, p); } -void btsnd_hcic_io_cap_req_reply(const RawAddress& bd_addr, uint8_t capability, - uint8_t oob_present, uint8_t auth_req) { +void btsnd_hcic_io_cap_req_reply(const RawAddress& bd_addr, uint8_t capability, uint8_t oob_present, + uint8_t auth_req) { BT_HDR* p = (BT_HDR*)osi_malloc(HCI_CMD_BUF_SIZE); uint8_t* pp = (uint8_t*)(p + 1); @@ -1211,8 +1210,8 @@ void btsnd_hcic_io_cap_req_reply(const RawAddress& bd_addr, uint8_t capability, btu_hcif_send_cmd(LOCAL_BR_EDR_CONTROLLER_ID, p); } -void btsnd_hcic_enhanced_set_up_synchronous_connection( - uint16_t conn_handle, enh_esco_params_t* p_params) { +void btsnd_hcic_enhanced_set_up_synchronous_connection(uint16_t conn_handle, + enh_esco_params_t* p_params) { BT_HDR* p = (BT_HDR*)osi_malloc(HCI_CMD_BUF_SIZE); uint8_t* pp = (uint8_t*)(p + 1); @@ -1227,12 +1226,10 @@ void btsnd_hcic_enhanced_set_up_synchronous_connection( UINT32_TO_STREAM(pp, p_params->receive_bandwidth); UINT8_TO_STREAM(pp, p_params->transmit_coding_format.coding_format); UINT16_TO_STREAM(pp, p_params->transmit_coding_format.company_id); - UINT16_TO_STREAM(pp, - p_params->transmit_coding_format.vendor_specific_codec_id); + UINT16_TO_STREAM(pp, p_params->transmit_coding_format.vendor_specific_codec_id); UINT8_TO_STREAM(pp, p_params->receive_coding_format.coding_format); UINT16_TO_STREAM(pp, p_params->receive_coding_format.company_id); - UINT16_TO_STREAM(pp, - p_params->receive_coding_format.vendor_specific_codec_id); + UINT16_TO_STREAM(pp, p_params->receive_coding_format.vendor_specific_codec_id); UINT16_TO_STREAM(pp, p_params->transmit_codec_frame_size); UINT16_TO_STREAM(pp, p_params->receive_codec_frame_size); UINT32_TO_STREAM(pp, p_params->input_bandwidth); @@ -1260,8 +1257,8 @@ void btsnd_hcic_enhanced_set_up_synchronous_connection( btu_hcif_send_cmd(LOCAL_BR_EDR_CONTROLLER_ID, p); } -void btsnd_hcic_enhanced_accept_synchronous_connection( - const RawAddress& bd_addr, enh_esco_params_t* p_params) { +void btsnd_hcic_enhanced_accept_synchronous_connection(const RawAddress& bd_addr, + enh_esco_params_t* p_params) { BT_HDR* p = (BT_HDR*)osi_malloc(HCI_CMD_BUF_SIZE); uint8_t* pp = (uint8_t*)(p + 1); @@ -1276,12 +1273,10 @@ void btsnd_hcic_enhanced_accept_synchronous_connection( UINT32_TO_STREAM(pp, p_params->receive_bandwidth); UINT8_TO_STREAM(pp, p_params->transmit_coding_format.coding_format); UINT16_TO_STREAM(pp, p_params->transmit_coding_format.company_id); - UINT16_TO_STREAM(pp, - p_params->transmit_coding_format.vendor_specific_codec_id); + UINT16_TO_STREAM(pp, p_params->transmit_coding_format.vendor_specific_codec_id); UINT8_TO_STREAM(pp, p_params->receive_coding_format.coding_format); UINT16_TO_STREAM(pp, p_params->receive_coding_format.company_id); - UINT16_TO_STREAM(pp, - p_params->receive_coding_format.vendor_specific_codec_id); + UINT16_TO_STREAM(pp, p_params->receive_coding_format.vendor_specific_codec_id); UINT16_TO_STREAM(pp, p_params->transmit_codec_frame_size); UINT16_TO_STREAM(pp, p_params->receive_codec_frame_size); UINT32_TO_STREAM(pp, p_params->input_bandwidth); @@ -1309,8 +1304,7 @@ void btsnd_hcic_enhanced_accept_synchronous_connection( btu_hcif_send_cmd(LOCAL_BR_EDR_CONTROLLER_ID, p); } -void btsnd_hcic_io_cap_req_neg_reply(const RawAddress& bd_addr, - uint8_t err_code) { +void btsnd_hcic_io_cap_req_neg_reply(const RawAddress& bd_addr, uint8_t err_code) { BT_HDR* p = (BT_HDR*)osi_malloc(HCI_CMD_BUF_SIZE); uint8_t* pp = (uint8_t*)(p + 1); @@ -1405,8 +1399,7 @@ void btsnd_hcic_user_passkey_neg_reply(const RawAddress& bd_addr) { btu_hcif_send_cmd(LOCAL_BR_EDR_CONTROLLER_ID, p); } -void btsnd_hcic_rem_oob_reply(const RawAddress& bd_addr, const Octet16& c, - const Octet16& r) { +void btsnd_hcic_rem_oob_reply(const RawAddress& bd_addr, const Octet16& c, const Octet16& r) { BT_HDR* p = (BT_HDR*)osi_malloc(HCI_CMD_BUF_SIZE); uint8_t* pp = (uint8_t*)(p + 1); @@ -1459,9 +1452,8 @@ void btsnd_hcic_read_rssi(uint16_t handle) { btu_hcif_send_cmd(LOCAL_BR_EDR_CONTROLLER_ID, p); } -static void read_encryption_key_size_complete( - ReadEncKeySizeCb cb, uint8_t* return_parameters, - uint16_t /* return_parameters_length */) { +static void read_encryption_key_size_complete(ReadEncKeySizeCb cb, uint8_t* return_parameters, + uint16_t /* return_parameters_length */) { uint8_t status; uint16_t handle; uint8_t key_size; @@ -1557,9 +1549,8 @@ void btsnd_hcic_write_pagescan_type(uint8_t type) { btu_hcif_send_cmd(LOCAL_BR_EDR_CONTROLLER_ID, p); } -static void btsnd_hcic_vendor_spec_complete(tBTM_VSC_CMPL_CB* p_vsc_cplt_cback, - uint16_t opcode, uint8_t* data, - uint16_t len) { +static void btsnd_hcic_vendor_spec_complete(tBTM_VSC_CMPL_CB* p_vsc_cplt_cback, uint16_t opcode, + uint8_t* data, uint16_t len) { /* If there was a callback address for vcs complete, call it */ if (p_vsc_cplt_cback) { tBTM_VSC_CMPL vcs_cplt_params; @@ -1575,14 +1566,12 @@ void btsnd_hcic_vendor_spec_cmd(uint16_t opcode, uint8_t len, uint8_t* p_data, tBTM_VSC_CMPL_CB* p_cmd_cplt_cback) { uint16_t v_opcode = HCI_GRP_VENDOR_SPECIFIC | opcode; - btu_hcif_send_cmd_with_cb( - FROM_HERE, v_opcode, p_data, len, - base::BindOnce(&btsnd_hcic_vendor_spec_complete, - base::Unretained(p_cmd_cplt_cback), v_opcode)); + btu_hcif_send_cmd_with_cb(FROM_HERE, v_opcode, p_data, len, + base::BindOnce(&btsnd_hcic_vendor_spec_complete, + base::Unretained(p_cmd_cplt_cback), v_opcode)); } -void btsnd_hcic_configure_data_path(hci_data_direction_t data_path_direction, - uint8_t data_path_id, +void btsnd_hcic_configure_data_path(hci_data_direction_t data_path_direction, uint8_t data_path_id, std::vector vendor_config) { BT_HDR* p = (BT_HDR*)osi_malloc(HCI_CMD_BUF_SIZE); uint8_t* pp = (uint8_t*)(p + 1); @@ -1607,18 +1596,15 @@ class InterfaceImpl : public Interface { void Disconnect(uint16_t handle, uint8_t reason) const override { btsnd_hcic_disconnect(handle, reason); } - void ChangeConnectionPacketType(uint16_t handle, - uint16_t packet_types) const override { + void ChangeConnectionPacketType(uint16_t handle, uint16_t packet_types) const override { btsnd_hcic_change_conn_type(handle, packet_types); } void StartRoleSwitch(const RawAddress& bd_addr, uint8_t role) const override { btsnd_hcic_switch_role(bd_addr, role); } - void ConfigureDataPath(hci_data_direction_t data_path_direction, - uint8_t data_path_id, + void ConfigureDataPath(hci_data_direction_t data_path_direction, uint8_t data_path_id, std::vector vendor_config) const override { - btsnd_hcic_configure_data_path(data_path_direction, data_path_id, - vendor_config); + btsnd_hcic_configure_data_path(data_path_direction, data_path_id, vendor_config); } }; diff --git a/system/stack/hid/hid_conn.h b/system/stack/hid/hid_conn.h index 562525e5d14..77d0fa61323 100644 --- a/system/stack/hid/hid_conn.h +++ b/system/stack/hid/hid_conn.h @@ -42,7 +42,7 @@ typedef enum : uint8_t { } tHID_CONN_STATE; /* Define the HID Connection Block -*/ + */ typedef struct hid_conn { tHID_CONN_STATE conn_state; diff --git a/system/stack/hid/hidd_api.cc b/system/stack/hid/hidd_api.cc index 3669a804662..01957c2134e 100644 --- a/system/stack/hid/hidd_api.cc +++ b/system/stack/hid/hidd_api.cc @@ -79,22 +79,20 @@ tHID_STATUS HID_DevRegister(tHID_DEV_HOST_CALLBACK* host_cback) { log::verbose(""); if (hd_cb.reg_flag) { - log_counter_metrics( - android::bluetooth::CodePathCounterKeyEnum::HIDD_ERR_ALREADY_REGISTERED, - 1); + log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum::HIDD_ERR_ALREADY_REGISTERED, 1); return HID_ERR_ALREADY_REGISTERED; } if (host_cback == NULL) { - log_counter_metrics( - android::bluetooth::CodePathCounterKeyEnum::HIDD_ERR_HOST_CALLBACK_NULL, - 1); + log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum::HIDD_ERR_HOST_CALLBACK_NULL, 1); return HID_ERR_INVALID_PARAM; } /* Register with L2CAP */ st = hidd_conn_reg(); - if (st != HID_SUCCESS) return st; + if (st != HID_SUCCESS) { + return st; + } hd_cb.callback = host_cback; hd_cb.reg_flag = TRUE; @@ -104,7 +102,7 @@ tHID_STATUS HID_DevRegister(tHID_DEV_HOST_CALLBACK* host_cback) { hd_cb.pending_data = NULL; } - return (HID_SUCCESS); + return HID_SUCCESS; } /******************************************************************************* @@ -120,17 +118,16 @@ tHID_STATUS HID_DevDeregister(void) { log::verbose(""); if (!hd_cb.reg_flag) { - log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum:: - HIDD_ERR_NOT_REGISTERED_AT_DEREGISTER, - 1); - return (HID_ERR_NOT_REGISTERED); + log_counter_metrics( + android::bluetooth::CodePathCounterKeyEnum::HIDD_ERR_NOT_REGISTERED_AT_DEREGISTER, 1); + return HID_ERR_NOT_REGISTERED; } hidd_conn_dereg(); hd_cb.reg_flag = FALSE; - return (HID_SUCCESS); + return HID_SUCCESS; } /******************************************************************************* @@ -142,9 +139,8 @@ tHID_STATUS HID_DevDeregister(void) { * Returns tHID_STATUS * ******************************************************************************/ -tHID_STATUS HID_DevAddRecord(uint32_t handle, char* p_name, char* p_description, - char* p_provider, uint16_t subclass, - uint16_t desc_len, uint8_t* p_desc_data) { +tHID_STATUS HID_DevAddRecord(uint32_t handle, char* p_name, char* p_description, char* p_provider, + uint16_t subclass, uint16_t desc_len, uint8_t* p_desc_data) { bool result = TRUE; log::verbose(""); @@ -152,8 +148,7 @@ tHID_STATUS HID_DevAddRecord(uint32_t handle, char* p_name, char* p_description, // Service Class ID List if (result) { uint16_t uuid = UUID_SERVCLASS_HUMAN_INTERFACE; - result &= get_legacy_stack_sdp_api()->handle.SDP_AddServiceClassIdList( - handle, 1, &uuid); + result &= get_legacy_stack_sdp_api()->handle.SDP_AddServiceClassIdList(handle, 1, &uuid); } // Protocol Descriptor List @@ -167,15 +162,13 @@ tHID_STATUS HID_DevAddRecord(uint32_t handle, char* p_name, char* p_description, proto_list[1].protocol_uuid = UUID_PROTOCOL_HIDP; proto_list[1].num_params = 0; - result &= get_legacy_stack_sdp_api()->handle.SDP_AddProtocolList( - handle, 2, proto_list); + result &= get_legacy_stack_sdp_api()->handle.SDP_AddProtocolList(handle, 2, proto_list); } // Language Base Attribute ID List if (result) { result &= get_legacy_stack_sdp_api()->handle.SDP_AddLanguageBaseAttrIDList( - handle, LANG_ID_CODE_ENGLISH, LANG_ID_CHAR_ENCODE_UTF8, - LANGUAGE_BASE_ID); + handle, LANG_ID_CODE_ENGLISH, LANG_ID_CHAR_ENCODE_UTF8, LANGUAGE_BASE_ID); } // Additional Protocol Descriptor List @@ -189,8 +182,8 @@ tHID_STATUS HID_DevAddRecord(uint32_t handle, char* p_name, char* p_description, add_proto_list.list_elem[1].protocol_uuid = UUID_PROTOCOL_HIDP; add_proto_list.list_elem[1].num_params = 0; - result &= get_legacy_stack_sdp_api()->handle.SDP_AddAdditionProtoLists( - handle, 1, &add_proto_list); + result &= get_legacy_stack_sdp_api()->handle.SDP_AddAdditionProtoLists(handle, 1, + &add_proto_list); } // Service Name (O) @@ -202,16 +195,16 @@ tHID_STATUS HID_DevAddRecord(uint32_t handle, char* p_name, char* p_description, const char* provider_name = p_provider; result &= get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - handle, ATTR_ID_SERVICE_NAME, TEXT_STR_DESC_TYPE, strlen(srv_name) + 1, - (uint8_t*)srv_name); + handle, ATTR_ID_SERVICE_NAME, TEXT_STR_DESC_TYPE, strlen(srv_name) + 1, + (uint8_t*)srv_name); result &= get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - handle, ATTR_ID_SERVICE_DESCRIPTION, TEXT_STR_DESC_TYPE, - strlen(srv_desc) + 1, (uint8_t*)srv_desc); + handle, ATTR_ID_SERVICE_DESCRIPTION, TEXT_STR_DESC_TYPE, strlen(srv_desc) + 1, + (uint8_t*)srv_desc); result &= get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - handle, ATTR_ID_PROVIDER_NAME, TEXT_STR_DESC_TYPE, - strlen(provider_name) + 1, (uint8_t*)provider_name); + handle, ATTR_ID_PROVIDER_NAME, TEXT_STR_DESC_TYPE, strlen(provider_name) + 1, + (uint8_t*)provider_name); } // Bluetooth Profile Descriptor List @@ -219,8 +212,8 @@ tHID_STATUS HID_DevAddRecord(uint32_t handle, char* p_name, char* p_description, const uint16_t profile_uuid = UUID_SERVCLASS_HUMAN_INTERFACE; const uint16_t version = 0x0100; - result &= get_legacy_stack_sdp_api()->handle.SDP_AddProfileDescriptorList( - handle, profile_uuid, version); + result &= get_legacy_stack_sdp_api()->handle.SDP_AddProfileDescriptorList(handle, profile_uuid, + version); } // HID Parser Version @@ -238,28 +231,24 @@ tHID_STATUS HID_DevAddRecord(uint32_t handle, char* p_name, char* p_description, p = (uint8_t*)&temp; UINT16_TO_BE_STREAM(p, rel_num); result &= get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - handle, ATTR_ID_HID_DEVICE_RELNUM, UINT_DESC_TYPE, 2, (uint8_t*)&temp); + handle, ATTR_ID_HID_DEVICE_RELNUM, UINT_DESC_TYPE, 2, (uint8_t*)&temp); p = (uint8_t*)&temp; UINT16_TO_BE_STREAM(p, parser_version); result &= get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - handle, ATTR_ID_HID_PARSER_VERSION, UINT_DESC_TYPE, 2, (uint8_t*)&temp); + handle, ATTR_ID_HID_PARSER_VERSION, UINT_DESC_TYPE, 2, (uint8_t*)&temp); result &= get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - handle, ATTR_ID_HID_DEVICE_SUBCLASS, UINT_DESC_TYPE, 1, - (uint8_t*)&dev_subclass); + handle, ATTR_ID_HID_DEVICE_SUBCLASS, UINT_DESC_TYPE, 1, (uint8_t*)&dev_subclass); result &= get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - handle, ATTR_ID_HID_COUNTRY_CODE, UINT_DESC_TYPE, 1, - (uint8_t*)&country_code); + handle, ATTR_ID_HID_COUNTRY_CODE, UINT_DESC_TYPE, 1, (uint8_t*)&country_code); result &= get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - handle, ATTR_ID_HID_VIRTUAL_CABLE, BOOLEAN_DESC_TYPE, 1, - (uint8_t*)&bool_true); + handle, ATTR_ID_HID_VIRTUAL_CABLE, BOOLEAN_DESC_TYPE, 1, (uint8_t*)&bool_true); result &= get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - handle, ATTR_ID_HID_RECONNECT_INITIATE, BOOLEAN_DESC_TYPE, 1, - (uint8_t*)&bool_true); + handle, ATTR_ID_HID_RECONNECT_INITIATE, BOOLEAN_DESC_TYPE, 1, (uint8_t*)&bool_true); { static uint8_t cdt = 0x22; @@ -267,12 +256,10 @@ tHID_STATUS HID_DevAddRecord(uint32_t handle, char* p_name, char* p_description, uint8_t seq_len = 4 + desc_len; if (desc_len > HIDD_APP_DESCRIPTOR_LEN) { - log::error("descriptor length = {}, larger than max {}", desc_len, - HIDD_APP_DESCRIPTOR_LEN); - log_counter_metrics( - android::bluetooth::CodePathCounterKeyEnum:: - HIDD_ERR_NOT_REGISTERED_DUE_TO_DESCRIPTOR_LENGTH, - 1); + log::error("descriptor length = {}, larger than max {}", desc_len, HIDD_APP_DESCRIPTOR_LEN); + log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum:: + HIDD_ERR_NOT_REGISTERED_DUE_TO_DESCRIPTOR_LENGTH, + 1); return HID_ERR_NOT_REGISTERED; }; @@ -280,10 +267,9 @@ tHID_STATUS HID_DevAddRecord(uint32_t handle, char* p_name, char* p_description, if (p_buf == NULL) { log::error("Buffer allocation failure for size = 2048"); - log_counter_metrics( - android::bluetooth::CodePathCounterKeyEnum:: - HIDD_ERR_NOT_REGISTERED_DUE_TO_BUFFER_ALLOCATION, - 1); + log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum:: + HIDD_ERR_NOT_REGISTERED_DUE_TO_BUFFER_ALLOCATION, + 1); return HID_ERR_NOT_REGISTERED; } @@ -301,8 +287,7 @@ tHID_STATUS HID_DevAddRecord(uint32_t handle, char* p_name, char* p_description, ARRAY_TO_BE_STREAM(p, p_desc_data, (int)desc_len); result &= get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - handle, ATTR_ID_HID_DESCRIPTOR_LIST, DATA_ELE_SEQ_DESC_TYPE, - p - p_buf, p_buf); + handle, ATTR_ID_HID_DESCRIPTOR_LIST, DATA_ELE_SEQ_DESC_TYPE, p - p_buf, p_buf); osi_free(p_buf); } @@ -319,43 +304,36 @@ tHID_STATUS HID_DevAddRecord(uint32_t handle, char* p_name, char* p_description, UINT8_TO_BE_STREAM(p, (UINT_DESC_TYPE << 3) | SIZE_TWO_BYTES); UINT16_TO_BE_STREAM(p, LANGUAGE_BASE_ID); result &= get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - handle, ATTR_ID_HID_LANGUAGE_ID_BASE, DATA_ELE_SEQ_DESC_TYPE, - p - lang_buf, lang_buf); + handle, ATTR_ID_HID_LANGUAGE_ID_BASE, DATA_ELE_SEQ_DESC_TYPE, p - lang_buf, lang_buf); } result &= get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - handle, ATTR_ID_HID_BATTERY_POWER, BOOLEAN_DESC_TYPE, 1, - (uint8_t*)&bool_true); + handle, ATTR_ID_HID_BATTERY_POWER, BOOLEAN_DESC_TYPE, 1, (uint8_t*)&bool_true); result &= get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - handle, ATTR_ID_HID_REMOTE_WAKE, BOOLEAN_DESC_TYPE, 1, - (uint8_t*)&bool_false); + handle, ATTR_ID_HID_REMOTE_WAKE, BOOLEAN_DESC_TYPE, 1, (uint8_t*)&bool_false); result &= get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - handle, ATTR_ID_HID_NORMALLY_CONNECTABLE, BOOLEAN_DESC_TYPE, 1, - (uint8_t*)&bool_true); + handle, ATTR_ID_HID_NORMALLY_CONNECTABLE, BOOLEAN_DESC_TYPE, 1, (uint8_t*)&bool_true); result &= get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - handle, ATTR_ID_HID_BOOT_DEVICE, BOOLEAN_DESC_TYPE, 1, - (uint8_t*)&bool_true); + handle, ATTR_ID_HID_BOOT_DEVICE, BOOLEAN_DESC_TYPE, 1, (uint8_t*)&bool_true); p = (uint8_t*)&temp; UINT16_TO_BE_STREAM(p, prof_ver); result &= get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - handle, ATTR_ID_HID_PROFILE_VERSION, UINT_DESC_TYPE, 2, - (uint8_t*)&temp); + handle, ATTR_ID_HID_PROFILE_VERSION, UINT_DESC_TYPE, 2, (uint8_t*)&temp); } if (result) { uint16_t browse_group = UUID_SERVCLASS_PUBLIC_BROWSE_GROUP; result &= get_legacy_stack_sdp_api()->handle.SDP_AddUuidSequence( - handle, ATTR_ID_BROWSE_GROUP_LIST, 1, &browse_group); + handle, ATTR_ID_BROWSE_GROUP_LIST, 1, &browse_group); } if (!result) { log::error("failed to complete SDP record"); - log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum:: - HIDD_ERR_NOT_REGISTERED_AT_SDP, + log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum::HIDD_ERR_NOT_REGISTERED_AT_SDP, 1); return HID_ERR_NOT_REGISTERED; } @@ -372,23 +350,21 @@ tHID_STATUS HID_DevAddRecord(uint32_t handle, char* p_name, char* p_description, * Returns tHID_STATUS * ******************************************************************************/ -tHID_STATUS HID_DevSendReport(uint8_t channel, uint8_t type, uint8_t id, - uint16_t len, uint8_t* p_data) { +tHID_STATUS HID_DevSendReport(uint8_t channel, uint8_t type, uint8_t id, uint16_t len, + uint8_t* p_data) { log::verbose("channel={} type={} id={} len={}", channel, type, id, len); if (channel == HID_CHANNEL_CTRL) { - return hidd_conn_send_data(HID_CHANNEL_CTRL, HID_TRANS_DATA, type, id, len, - p_data); + return hidd_conn_send_data(HID_CHANNEL_CTRL, HID_TRANS_DATA, type, id, len, p_data); } if (channel == HID_CHANNEL_INTR && type == HID_PAR_REP_TYPE_INPUT) { // on INTR we can only send INPUT - return hidd_conn_send_data(HID_CHANNEL_INTR, HID_TRANS_DATA, - HID_PAR_REP_TYPE_INPUT, id, len, p_data); + return hidd_conn_send_data(HID_CHANNEL_INTR, HID_TRANS_DATA, HID_PAR_REP_TYPE_INPUT, id, len, + p_data); } - log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum:: - HIDD_ERR_INVALID_PARAM_SEND_REPORT, - 1); + log_counter_metrics( + android::bluetooth::CodePathCounterKeyEnum::HIDD_ERR_INVALID_PARAM_SEND_REPORT, 1); return HID_ERR_INVALID_PARAM; } @@ -455,22 +431,19 @@ tHID_STATUS HID_DevUnplugDevice(const RawAddress& addr) { ******************************************************************************/ tHID_STATUS HID_DevConnect(void) { if (!hd_cb.reg_flag) { - log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum:: - HIDD_ERR_NOT_REGISTERED_AT_CONNECT, - 1); + log_counter_metrics( + android::bluetooth::CodePathCounterKeyEnum::HIDD_ERR_NOT_REGISTERED_AT_CONNECT, 1); return HID_ERR_NOT_REGISTERED; } if (!hd_cb.device.in_use) { - log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum:: - HIDD_ERR_DEVICE_NOT_IN_USE_AT_CONNECT, - 1); + log_counter_metrics( + android::bluetooth::CodePathCounterKeyEnum::HIDD_ERR_DEVICE_NOT_IN_USE_AT_CONNECT, 1); return HID_ERR_INVALID_PARAM; } if (hd_cb.device.state != HIDD_DEV_NO_CONN) { - log_counter_metrics( - android::bluetooth::CodePathCounterKeyEnum::HIDD_ERR_ALREADY_CONN, 1); + log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum::HIDD_ERR_ALREADY_CONN, 1); return HID_ERR_ALREADY_CONN; } @@ -488,16 +461,15 @@ tHID_STATUS HID_DevConnect(void) { ******************************************************************************/ tHID_STATUS HID_DevDisconnect(void) { if (!hd_cb.reg_flag) { - log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum:: - HIDD_ERR_NOT_REGISTERED_AT_DISCONNECT, - 1); + log_counter_metrics( + android::bluetooth::CodePathCounterKeyEnum::HIDD_ERR_NOT_REGISTERED_AT_DISCONNECT, 1); return HID_ERR_NOT_REGISTERED; } if (!hd_cb.device.in_use) { - log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum:: - HIDD_ERR_DEVICE_NOT_IN_USE_AT_DISCONNECT, - 1); + log_counter_metrics( + android::bluetooth::CodePathCounterKeyEnum::HIDD_ERR_DEVICE_NOT_IN_USE_AT_DISCONNECT, + 1); return HID_ERR_INVALID_PARAM; } @@ -506,16 +478,12 @@ tHID_STATUS HID_DevDisconnect(void) { if (hd_cb.device.conn.conn_state != HID_CONN_STATE_UNUSED) { tHID_STATUS ret = hidd_conn_disconnect(); hd_cb.device.conn.conn_state = HID_CONN_STATE_UNUSED; - hd_cb.callback(hd_cb.device.addr, HID_DHOST_EVT_CLOSE, - HID_ERR_DISCONNECTING, NULL); - log_counter_metrics( - android::bluetooth::CodePathCounterKeyEnum::HIDD_ERR_DISCONNECTING, - 1); + hd_cb.callback(hd_cb.device.addr, HID_DHOST_EVT_CLOSE, HID_ERR_DISCONNECTING, NULL); + log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum::HIDD_ERR_DISCONNECTING, 1); return ret; } - log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum:: - HIDD_ERR_NO_CONNECTION_AT_DISCONNECT, - 1); + log_counter_metrics( + android::bluetooth::CodePathCounterKeyEnum::HIDD_ERR_NO_CONNECTION_AT_DISCONNECT, 1); return HID_ERR_NO_CONNECTION; } @@ -566,8 +534,7 @@ tHID_STATUS HID_DevReportError(uint8_t error) { break; } - return hidd_conn_send_data(0, HID_TRANS_HANDSHAKE, handshake_param, 0, 0, - NULL); + return hidd_conn_send_data(0, HID_TRANS_HANDSHAKE, handshake_param, 0, 0, NULL); } /******************************************************************************* @@ -585,9 +552,8 @@ tHID_STATUS HID_DevGetDevice(RawAddress* addr) { if (hd_cb.device.in_use) { *addr = hd_cb.device.addr; } else { - log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum:: - HIDD_ERR_NOT_REGISTERED_AT_GET_DEVICE, - 1); + log_counter_metrics( + android::bluetooth::CodePathCounterKeyEnum::HIDD_ERR_NOT_REGISTERED_AT_GET_DEVICE, 1); return HID_ERR_NOT_REGISTERED; } @@ -604,9 +570,8 @@ tHID_STATUS HID_DevGetDevice(RawAddress* addr) { * ******************************************************************************/ tHID_STATUS HID_DevSetIncomingQos(uint8_t service_type, uint32_t token_rate, - uint32_t token_bucket_size, - uint32_t peak_bandwidth, uint32_t latency, - uint32_t delay_variation) { + uint32_t token_bucket_size, uint32_t peak_bandwidth, + uint32_t latency, uint32_t delay_variation) { log::verbose(""); hd_cb.use_in_qos = TRUE; @@ -631,9 +596,8 @@ tHID_STATUS HID_DevSetIncomingQos(uint8_t service_type, uint32_t token_rate, * ******************************************************************************/ tHID_STATUS HID_DevSetOutgoingQos(uint8_t service_type, uint32_t token_rate, - uint32_t token_bucket_size, - uint32_t peak_bandwidth, uint32_t latency, - uint32_t delay_variation) { + uint32_t token_bucket_size, uint32_t peak_bandwidth, + uint32_t latency, uint32_t delay_variation) { log::verbose(""); hd_cb.l2cap_intr_cfg.qos_present = TRUE; diff --git a/system/stack/hid/hidd_conn.cc b/system/stack/hid/hidd_conn.cc index 1b96262d7a3..2a1521cf922 100644 --- a/system/stack/hid/hidd_conn.cc +++ b/system/stack/hid/hidd_conn.cc @@ -41,12 +41,11 @@ using namespace bluetooth; -static void hidd_l2cif_connect_ind(const RawAddress& bd_addr, uint16_t cid, - uint16_t psm, uint8_t id); +static void hidd_l2cif_connect_ind(const RawAddress& bd_addr, uint16_t cid, uint16_t psm, + uint8_t id); static void hidd_l2cif_connect_cfm(uint16_t cid, uint16_t result); static void hidd_l2cif_config_ind(uint16_t cid, tL2CAP_CFG_INFO* p_cfg); -static void hidd_l2cif_config_cfm(uint16_t cid, uint16_t result, - tL2CAP_CFG_INFO* p_cfg); +static void hidd_l2cif_config_cfm(uint16_t cid, uint16_t result, tL2CAP_CFG_INFO* p_cfg); static void hidd_l2cif_disconnect_ind(uint16_t cid, bool ack_needed); static void hidd_l2cif_disconnect(uint16_t cid); static void hidd_l2cif_data_ind(uint16_t cid, BT_HDR* p_msg); @@ -88,8 +87,7 @@ static void hidd_check_config_done() { // send outstanding data on intr if (hd_cb.pending_data) { - if (L2CA_DataWrite(p_hcon->intr_cid, hd_cb.pending_data) != - tL2CAP_DW_RESULT::SUCCESS) { + if (L2CA_DataWrite(p_hcon->intr_cid, hd_cb.pending_data) != tL2CAP_DW_RESULT::SUCCESS) { log::warn("Unable to write L2CAP data cid:{} len:{}", p_hcon->intr_cid, hd_cb.pending_data->len); } @@ -107,8 +105,8 @@ static void hidd_check_config_done() { * Returns void * ******************************************************************************/ -static void hidd_l2cif_connect_ind(const RawAddress& bd_addr, uint16_t cid, - uint16_t psm, uint8_t id) { +static void hidd_l2cif_connect_ind(const RawAddress& bd_addr, uint16_t cid, uint16_t psm, + uint8_t id) { tHID_DEV_DEV_CTB* p_dev; bool accept = TRUE; // accept by default @@ -136,8 +134,7 @@ static void hidd_l2cif_connect_ind(const RawAddress& bd_addr, uint16_t cid, if (p_hcon->conn_state != HID_CONN_STATE_CONNECTING_INTR) { accept = FALSE; - log::warn("incoming INTR in invalid state ({}), rejecting", - p_hcon->conn_state); + log::warn("incoming INTR in invalid state ({}), rejecting", p_hcon->conn_state); } break; @@ -145,8 +142,7 @@ static void hidd_l2cif_connect_ind(const RawAddress& bd_addr, uint16_t cid, case HID_PSM_CONTROL: if (p_hcon->conn_state != HID_CONN_STATE_UNUSED) { accept = FALSE; - log::warn("incoming CTRL in invalid state ({}), rejecting", - p_hcon->conn_state); + log::warn("incoming CTRL in invalid state ({}), rejecting", p_hcon->conn_state); } break; @@ -190,8 +186,8 @@ static void hidd_on_l2cap_error(uint16_t lcid, uint16_t result) { hidd_conn_disconnect(); // NOTE that the client doesn't care about error code - hd_cb.callback(hd_cb.device.addr, HID_DHOST_EVT_CLOSE, - HID_L2CAP_CONN_FAIL | (uint32_t)result, NULL); + hd_cb.callback(hd_cb.device.addr, HID_DHOST_EVT_CLOSE, HID_L2CAP_CONN_FAIL | (uint32_t)result, + NULL); } /******************************************************************************* @@ -214,10 +210,8 @@ static void hidd_l2cif_connect_cfm(uint16_t cid, uint16_t result) { } if (!(p_hcon->conn_flags & HID_CONN_FLAGS_IS_ORIG) || - ((cid == p_hcon->ctrl_cid) && - (p_hcon->conn_state != HID_CONN_STATE_CONNECTING_CTRL)) || - ((cid == p_hcon->intr_cid) && - (p_hcon->conn_state != HID_CONN_STATE_CONNECTING_INTR))) { + ((cid == p_hcon->ctrl_cid) && (p_hcon->conn_state != HID_CONN_STATE_CONNECTING_CTRL)) || + ((cid == p_hcon->intr_cid) && (p_hcon->conn_state != HID_CONN_STATE_CONNECTING_INTR))) { log::warn("unexpected"); return; } @@ -257,10 +251,11 @@ static void hidd_l2cif_config_ind(uint16_t cid, tL2CAP_CFG_INFO* p_cfg) { return; } - if ((!p_cfg->mtu_present) || (p_cfg->mtu > HID_DEV_MTU_SIZE)) + if ((!p_cfg->mtu_present) || (p_cfg->mtu > HID_DEV_MTU_SIZE)) { p_hcon->rem_mtu_size = HID_DEV_MTU_SIZE; - else + } else { p_hcon->rem_mtu_size = p_cfg->mtu; + } } /******************************************************************************* @@ -272,8 +267,7 @@ static void hidd_l2cif_config_ind(uint16_t cid, tL2CAP_CFG_INFO* p_cfg) { * Returns void * ******************************************************************************/ -static void hidd_l2cif_config_cfm(uint16_t cid, uint16_t initiator, - tL2CAP_CFG_INFO* p_cfg) { +static void hidd_l2cif_config_cfm(uint16_t cid, uint16_t initiator, tL2CAP_CFG_INFO* p_cfg) { hidd_l2cif_config_ind(cid, p_cfg); log::verbose("cid={:04x}", cid); @@ -290,17 +284,15 @@ static void hidd_l2cif_config_cfm(uint16_t cid, uint16_t initiator, if (p_hcon->conn_flags & HID_CONN_FLAGS_IS_ORIG) { p_hcon->disc_reason = HID_L2CAP_CONN_FAIL; if ((p_hcon->intr_cid = L2CA_ConnectReqWithSecurity( - HID_PSM_INTERRUPT, hd_cb.device.addr, - BTA_SEC_AUTHENTICATE | BTA_SEC_ENCRYPT)) == 0) { + HID_PSM_INTERRUPT, hd_cb.device.addr, BTA_SEC_AUTHENTICATE | BTA_SEC_ENCRYPT)) == + 0) { hidd_conn_disconnect(); p_hcon->conn_state = HID_CONN_STATE_UNUSED; log::warn("could not start L2CAP connection for INTR"); - hd_cb.callback(hd_cb.device.addr, HID_DHOST_EVT_CLOSE, - HID_ERR_L2CAP_FAILED, NULL); - log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum:: - HIDD_ERR_L2CAP_NOT_STARTED_INCOMING, - 1); + hd_cb.callback(hd_cb.device.addr, HID_DHOST_EVT_CLOSE, HID_ERR_L2CAP_FAILED, NULL); + log_counter_metrics( + android::bluetooth::CodePathCounterKeyEnum::HIDD_ERR_L2CAP_NOT_STARTED_INCOMING, 1); return; } else { p_hcon->conn_state = HID_CONN_STATE_CONNECTING_INTR; @@ -333,10 +325,11 @@ static void hidd_l2cif_disconnect_ind(uint16_t cid, bool ack_needed) { p_hcon->conn_state = HID_CONN_STATE_DISCONNECTING; - if (cid == p_hcon->ctrl_cid) + if (cid == p_hcon->ctrl_cid) { p_hcon->ctrl_cid = 0; - else + } else { p_hcon->intr_cid = 0; + } if ((p_hcon->ctrl_cid == 0) && (p_hcon->intr_cid == 0)) { log::verbose("INTR and CTRL disconnected"); @@ -350,8 +343,7 @@ static void hidd_l2cif_disconnect_ind(uint16_t cid, bool ack_needed) { hd_cb.device.state = HIDD_DEV_NO_CONN; p_hcon->conn_state = HID_CONN_STATE_UNUSED; - hd_cb.callback(hd_cb.device.addr, HID_DHOST_EVT_CLOSE, p_hcon->disc_reason, - NULL); + hd_cb.callback(hd_cb.device.addr, HID_DHOST_EVT_CLOSE, p_hcon->disc_reason, NULL); } } @@ -389,12 +381,10 @@ static void hidd_l2cif_disconnect(uint16_t cid) { p_hcon->conn_state = HID_CONN_STATE_UNUSED; if (hd_cb.pending_vc_unplug) { - hd_cb.callback(hd_cb.device.addr, HID_DHOST_EVT_VC_UNPLUG, - p_hcon->disc_reason, NULL); + hd_cb.callback(hd_cb.device.addr, HID_DHOST_EVT_VC_UNPLUG, p_hcon->disc_reason, NULL); hd_cb.pending_vc_unplug = FALSE; } else { - hd_cb.callback(hd_cb.device.addr, HID_DHOST_EVT_CLOSE, - p_hcon->disc_reason, NULL); + hd_cb.callback(hd_cb.device.addr, HID_DHOST_EVT_CLOSE, p_hcon->disc_reason, NULL); } } } @@ -483,9 +473,8 @@ static void hidd_l2cif_data_ind(uint16_t cid, BT_HDR* p_msg) { break; case HID_TRANS_GET_IDLE: - hidd_conn_send_data(HID_CHANNEL_CTRL, HID_TRANS_DATA, - HID_PAR_REP_TYPE_OTHER, hd_cb.device.idle_time, 0, - NULL); + hidd_conn_send_data(HID_CHANNEL_CTRL, HID_TRANS_DATA, HID_PAR_REP_TYPE_OTHER, + hd_cb.device.idle_time, 0, NULL); osi_free(p_msg); break; @@ -497,35 +486,30 @@ static void hidd_l2cif_data_ind(uint16_t cid, BT_HDR* p_msg) { hd_cb.device.idle_time = p_data[1]; log::verbose("idle_time = {}", hd_cb.device.idle_time); if (hd_cb.device.idle_time) { - log::warn("idle_time of {} ms not supported by HID Device", - hd_cb.device.idle_time * 4); + log::warn("idle_time of {} ms not supported by HID Device", hd_cb.device.idle_time * 4); err = TRUE; } } if (!err) { - hidd_conn_send_data(0, HID_TRANS_HANDSHAKE, - HID_PAR_HANDSHAKE_RSP_SUCCESS, 0, 0, NULL); + hidd_conn_send_data(0, HID_TRANS_HANDSHAKE, HID_PAR_HANDSHAKE_RSP_SUCCESS, 0, 0, NULL); } else { - hidd_conn_send_data(0, HID_TRANS_HANDSHAKE, - HID_PAR_HANDSHAKE_RSP_ERR_INVALID_PARAM, 0, 0, + hidd_conn_send_data(0, HID_TRANS_HANDSHAKE, HID_PAR_HANDSHAKE_RSP_ERR_INVALID_PARAM, 0, 0, NULL); } osi_free(p_msg); break; case HID_TRANS_GET_PROTOCOL: - hidd_conn_send_data(HID_CHANNEL_CTRL, HID_TRANS_DATA, - HID_PAR_REP_TYPE_OTHER, !hd_cb.device.boot_mode, 0, - NULL); + hidd_conn_send_data(HID_CHANNEL_CTRL, HID_TRANS_DATA, HID_PAR_REP_TYPE_OTHER, + !hd_cb.device.boot_mode, 0, NULL); osi_free(p_msg); break; case HID_TRANS_SET_PROTOCOL: hd_cb.device.boot_mode = !(param & HID_PAR_PROTOCOL_MASK); - hd_cb.callback(hd_cb.device.addr, HID_DHOST_EVT_SET_PROTOCOL, - param & HID_PAR_PROTOCOL_MASK, NULL); - hidd_conn_send_data(0, HID_TRANS_HANDSHAKE, HID_PAR_HANDSHAKE_RSP_SUCCESS, - 0, 0, NULL); + hd_cb.callback(hd_cb.device.addr, HID_DHOST_EVT_SET_PROTOCOL, param & HID_PAR_PROTOCOL_MASK, + NULL); + hidd_conn_send_data(0, HID_TRANS_HANDSHAKE, HID_PAR_HANDSHAKE_RSP_SUCCESS, 0, 0, NULL); osi_free(p_msg); break; @@ -536,8 +520,7 @@ static void hidd_l2cif_data_ind(uint16_t cid, BT_HDR* p_msg) { break; case HID_PAR_CONTROL_EXIT_SUSPEND: - hd_cb.callback(hd_cb.device.addr, HID_DHOST_EVT_EXIT_SUSPEND, 0, - NULL); + hd_cb.callback(hd_cb.device.addr, HID_DHOST_EVT_EXIT_SUSPEND, 0, NULL); break; case HID_PAR_CONTROL_VIRTUAL_CABLE_UNPLUG: @@ -554,8 +537,7 @@ static void hidd_l2cif_data_ind(uint16_t cid, BT_HDR* p_msg) { case HID_TRANS_DATA: default: log::warn("got unsupported msg ({})", msg_type); - hidd_conn_send_data(0, HID_TRANS_HANDSHAKE, - HID_PAR_HANDSHAKE_RSP_ERR_UNSUPPORTED_REQ, 0, 0, + hidd_conn_send_data(0, HID_TRANS_HANDSHAKE, HID_PAR_HANDSHAKE_RSP_ERR_UNSUPPORTED_REQ, 0, 0, NULL); osi_free(p_msg); break; @@ -582,28 +564,24 @@ tHID_STATUS hidd_conn_reg(void) { hd_cb.l2cap_intr_cfg.mtu_present = TRUE; hd_cb.l2cap_intr_cfg.mtu = HID_DEV_MTU_SIZE; - if (!L2CA_RegisterWithSecurity( - HID_PSM_CONTROL, dev_reg_info, false /* enable_snoop */, nullptr, - HID_DEV_MTU_SIZE, 0, BTA_SEC_AUTHENTICATE | BTA_SEC_ENCRYPT)) { + if (!L2CA_RegisterWithSecurity(HID_PSM_CONTROL, dev_reg_info, false /* enable_snoop */, nullptr, + HID_DEV_MTU_SIZE, 0, BTA_SEC_AUTHENTICATE | BTA_SEC_ENCRYPT)) { log::error("HID Control (device) registration failed"); - log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum:: - HIDD_ERR_L2CAP_FAILED_CONTROL, + log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum::HIDD_ERR_L2CAP_FAILED_CONTROL, 1); - return (HID_ERR_L2CAP_FAILED); + return HID_ERR_L2CAP_FAILED; } - if (!L2CA_RegisterWithSecurity( - HID_PSM_INTERRUPT, dev_reg_info, false /* enable_snoop */, nullptr, - HID_DEV_MTU_SIZE, 0, BTA_SEC_AUTHENTICATE | BTA_SEC_ENCRYPT)) { + if (!L2CA_RegisterWithSecurity(HID_PSM_INTERRUPT, dev_reg_info, false /* enable_snoop */, nullptr, + HID_DEV_MTU_SIZE, 0, BTA_SEC_AUTHENTICATE | BTA_SEC_ENCRYPT)) { L2CA_Deregister(HID_PSM_CONTROL); log::error("HID Interrupt (device) registration failed"); - log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum:: - HIDD_ERR_L2CAP_FAILED_INTERRUPT, + log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum::HIDD_ERR_L2CAP_FAILED_INTERRUPT, 1); - return (HID_ERR_L2CAP_FAILED); + return HID_ERR_L2CAP_FAILED; } - return (HID_SUCCESS); + return HID_SUCCESS; } /******************************************************************************* @@ -638,18 +616,15 @@ tHID_STATUS hidd_conn_initiate(void) { if (!p_dev->in_use) { log::warn("no virtual cable established"); - log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum:: - HIDD_ERR_NOT_REGISTERED_AT_INITIATE, - 1); - return (HID_ERR_NOT_REGISTERED); + log_counter_metrics( + android::bluetooth::CodePathCounterKeyEnum::HIDD_ERR_NOT_REGISTERED_AT_INITIATE, 1); + return HID_ERR_NOT_REGISTERED; } if (p_dev->conn.conn_state != HID_CONN_STATE_UNUSED) { log::warn("connection already in progress"); - log_counter_metrics( - android::bluetooth::CodePathCounterKeyEnum::HIDD_ERR_CONN_IN_PROCESS, - 1); - return (HID_ERR_CONN_IN_PROCESS); + log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum::HIDD_ERR_CONN_IN_PROCESS, 1); + return HID_ERR_CONN_IN_PROCESS; } p_dev->conn.ctrl_cid = 0; @@ -660,19 +635,16 @@ tHID_STATUS hidd_conn_initiate(void) { /* Check if L2CAP started the connection process */ if ((p_dev->conn.ctrl_cid = L2CA_ConnectReqWithSecurity( - HID_PSM_CONTROL, p_dev->addr, - BTA_SEC_AUTHENTICATE | BTA_SEC_ENCRYPT)) == 0) { + HID_PSM_CONTROL, p_dev->addr, BTA_SEC_AUTHENTICATE | BTA_SEC_ENCRYPT)) == 0) { log::warn("could not start L2CAP connection"); - hd_cb.callback(hd_cb.device.addr, HID_DHOST_EVT_CLOSE, HID_ERR_L2CAP_FAILED, - NULL); - log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum:: - HIDD_ERR_L2CAP_FAILED_INITIATE, + hd_cb.callback(hd_cb.device.addr, HID_DHOST_EVT_CLOSE, HID_ERR_L2CAP_FAILED, NULL); + log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum::HIDD_ERR_L2CAP_FAILED_INITIATE, 1); } else { p_dev->conn.conn_state = HID_CONN_STATE_CONNECTING_CTRL; } - return (HID_SUCCESS); + return HID_SUCCESS; } /******************************************************************************* @@ -700,10 +672,9 @@ tHID_STATUS hidd_conn_disconnect(void) { /* Set l2cap idle timeout to 0 (so ACL link is disconnected * immediately after last channel is closed) */ - if (!L2CA_SetIdleTimeoutByBdAddr(hd_cb.device.addr, 0, - BT_TRANSPORT_BR_EDR)) { - log::warn("Unable to set L2CAP idle timeout peer:{} transport:{}", - hd_cb.device.addr, BT_TRANSPORT_BR_EDR); + if (!L2CA_SetIdleTimeoutByBdAddr(hd_cb.device.addr, 0, BT_TRANSPORT_BR_EDR)) { + log::warn("Unable to set L2CAP idle timeout peer:{} transport:{}", hd_cb.device.addr, + BT_TRANSPORT_BR_EDR); } if (p_hcon->intr_cid) { @@ -716,7 +687,7 @@ tHID_STATUS hidd_conn_disconnect(void) { p_hcon->conn_state = HID_CONN_STATE_UNUSED; } - return (HID_SUCCESS); + return HID_SUCCESS; } /******************************************************************************* @@ -728,9 +699,8 @@ tHID_STATUS hidd_conn_disconnect(void) { * Returns tHID_STATUS * ******************************************************************************/ -tHID_STATUS hidd_conn_send_data(uint8_t channel, uint8_t msg_type, - uint8_t param, uint8_t data, uint16_t len, - uint8_t* p_data) { +tHID_STATUS hidd_conn_send_data(uint8_t channel, uint8_t msg_type, uint8_t param, uint8_t data, + uint16_t len, uint8_t* p_data) { BT_HDR* p_buf; uint8_t* p_out; uint16_t cid; @@ -741,9 +711,8 @@ tHID_STATUS hidd_conn_send_data(uint8_t channel, uint8_t msg_type, tHID_CONN* p_hcon = &hd_cb.device.conn; if (p_hcon->conn_flags & HID_CONN_FLAGS_CONGESTED) { - log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum:: - HIDD_ERR_CONGESTED_AT_FLAG_CHECK, - 1); + log_counter_metrics( + android::bluetooth::CodePathCounterKeyEnum::HIDD_ERR_CONGESTED_AT_FLAG_CHECK, 1); return HID_ERR_CONGESTED; } @@ -763,17 +732,14 @@ tHID_STATUS hidd_conn_send_data(uint8_t channel, uint8_t msg_type, } break; default: - log_counter_metrics( - android::bluetooth::CodePathCounterKeyEnum::HIDD_ERR_INVALID_PARAM, - 1); - return (HID_ERR_INVALID_PARAM); + log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum::HIDD_ERR_INVALID_PARAM, 1); + return HID_ERR_INVALID_PARAM; } p_buf = (BT_HDR*)osi_malloc(buf_size); if (p_buf == NULL) { - log_counter_metrics( - android::bluetooth::CodePathCounterKeyEnum::HIDD_ERR_NO_RESOURCES, 1); - return (HID_ERR_NO_RESOURCES); + log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum::HIDD_ERR_NO_RESOURCES, 1); + return HID_ERR_NO_RESOURCES; } p_buf->offset = L2CAP_MIN_OFFSET; @@ -814,20 +780,18 @@ tHID_STATUS hidd_conn_send_data(uint8_t channel, uint8_t msg_type, return HID_SUCCESS; } - log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum:: - HIDD_ERR_NO_CONNECTION_AT_SEND_DATA, - 1); + log_counter_metrics( + android::bluetooth::CodePathCounterKeyEnum::HIDD_ERR_NO_CONNECTION_AT_SEND_DATA, 1); return HID_ERR_NO_CONNECTION; } log::verbose("report sent"); if (L2CA_DataWrite(cid, p_buf) == tL2CAP_DW_RESULT::FAILED) { - log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum:: - HIDD_ERR_CONGESTED_AT_DATA_WRITE, - 1); - return (HID_ERR_CONGESTED); + log_counter_metrics( + android::bluetooth::CodePathCounterKeyEnum::HIDD_ERR_CONGESTED_AT_DATA_WRITE, 1); + return HID_ERR_CONGESTED; } - return (HID_SUCCESS); + return HID_SUCCESS; } diff --git a/system/stack/hid/hidd_int.h b/system/stack/hid/hidd_int.h index 2d862afcdf6..c00b938cb2e 100644 --- a/system/stack/hid/hidd_int.h +++ b/system/stack/hid/hidd_int.h @@ -72,9 +72,8 @@ tHID_STATUS hidd_conn_reg(void); void hidd_conn_dereg(void); tHID_STATUS hidd_conn_initiate(void); tHID_STATUS hidd_conn_disconnect(void); -tHID_STATUS hidd_conn_send_data(uint8_t channel, uint8_t msg_type, - uint8_t param, uint8_t data, uint16_t len, - uint8_t* p_data); +tHID_STATUS hidd_conn_send_data(uint8_t channel, uint8_t msg_type, uint8_t param, uint8_t data, + uint16_t len, uint8_t* p_data); #ifdef __cplusplus extern "C" { diff --git a/system/stack/hid/hidh_api.cc b/system/stack/hid/hidh_api.cc index 79b9c4868c3..7090a837dc0 100644 --- a/system/stack/hid/hidh_api.cc +++ b/system/stack/hid/hidh_api.cc @@ -49,8 +49,7 @@ using bluetooth::Uuid; tHID_HOST_CTB hh_cb; -static void hidh_search_callback(const RawAddress& bd_addr, - tSDP_RESULT sdp_result); +static void hidh_search_callback(const RawAddress& bd_addr, tSDP_RESULT sdp_result); /******************************************************************************* * @@ -61,43 +60,37 @@ static void hidh_search_callback(const RawAddress& bd_addr, * Returns tHID_STATUS * ******************************************************************************/ -tHID_STATUS HID_HostGetSDPRecord(const RawAddress& addr, - tSDP_DISCOVERY_DB* p_db, uint32_t db_len, +tHID_STATUS HID_HostGetSDPRecord(const RawAddress& addr, tSDP_DISCOVERY_DB* p_db, uint32_t db_len, tHID_HOST_SDP_CALLBACK* sdp_cback) { if (hh_cb.sdp_busy) { - log_counter_metrics( - android::bluetooth::CodePathCounterKeyEnum::HIDH_ERR_SDP_BUSY, 1); + log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum::HIDH_ERR_SDP_BUSY, 1); return HID_ERR_SDP_BUSY; } hh_cb.p_sdp_db = p_db; Uuid uuid_list = Uuid::From16Bit(UUID_SERVCLASS_HUMAN_INTERFACE); - if (!get_legacy_stack_sdp_api()->service.SDP_InitDiscoveryDb( - p_db, db_len, 1, &uuid_list, 0, NULL)) { + if (!get_legacy_stack_sdp_api()->service.SDP_InitDiscoveryDb(p_db, db_len, 1, &uuid_list, 0, + NULL)) { log::warn("Unable to initialize SDP service discovery db peer:{}", addr); }; - if (get_legacy_stack_sdp_api()->service.SDP_ServiceSearchRequest( - addr, p_db, hidh_search_callback)) { + if (get_legacy_stack_sdp_api()->service.SDP_ServiceSearchRequest(addr, p_db, + hidh_search_callback)) { hh_cb.sdp_cback = sdp_cback; hh_cb.sdp_busy = true; return HID_SUCCESS; } else { log::warn("Unable to start SDP service search request peer:{}", addr); - log_counter_metrics( - android::bluetooth::CodePathCounterKeyEnum::HIDH_ERR_NO_RESOURCES_SDP, - 1); + log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum::HIDH_ERR_NO_RESOURCES_SDP, 1); return HID_ERR_NO_RESOURCES; } } -void hidh_get_str_attr(tSDP_DISC_REC* p_rec, uint16_t attr_id, uint16_t max_len, - char* str) { +void hidh_get_str_attr(tSDP_DISC_REC* p_rec, uint16_t attr_id, uint16_t max_len, char* str) { tSDP_DISC_ATTR* p_attr; uint16_t name_len; - p_attr = - get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec(p_rec, attr_id); + p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec(p_rec, attr_id); if (p_attr != NULL) { if (SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == TEXT_STR_DESC_TYPE) { name_len = SDP_DISC_ATTR_LEN(p_attr->attr_len_type); @@ -112,19 +105,18 @@ void hidh_get_str_attr(tSDP_DISC_REC* p_rec, uint16_t attr_id, uint16_t max_len, str[0] = '\0'; log::error("attr type not str!!"); } - } else + } else { str[0] = '\0'; + } } -static void hidh_search_callback(const RawAddress& /* bd_addr */, - tSDP_RESULT sdp_result) { +static void hidh_search_callback(const RawAddress& /* bd_addr */, tSDP_RESULT sdp_result) { tSDP_DISCOVERY_DB* p_db = hh_cb.p_sdp_db; tSDP_DISC_REC* p_rec; tSDP_DISC_ATTR *p_attr, *p_subattr1, *p_subattr2, *p_repdesc; tHID_DEV_SDP_INFO* p_nvi = &hh_cb.sdp_rec; uint16_t attr_mask = 0; - hh_cb.sdp_busy = false; if (sdp_result != SDP_SUCCESS) { @@ -133,8 +125,7 @@ static void hidh_search_callback(const RawAddress& /* bd_addr */, } Uuid hid_uuid = Uuid::From16Bit(UUID_SERVCLASS_HUMAN_INTERFACE); - p_rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceUUIDInDb(p_db, hid_uuid, - NULL); + p_rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceUUIDInDb(p_db, hid_uuid, NULL); if (p_rec == NULL) { hh_cb.sdp_cback(HID_SDP_NO_SERV_UUID, 0, NULL); return; @@ -144,11 +135,10 @@ static void hidh_search_callback(const RawAddress& /* bd_addr */, /* First, verify the mandatory fields we care about */ if (((p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - p_rec, ATTR_ID_HID_DESCRIPTOR_LIST)) == NULL) || + p_rec, ATTR_ID_HID_DESCRIPTOR_LIST)) == NULL) || (SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) != DATA_ELE_SEQ_DESC_TYPE) || ((p_subattr1 = p_attr->attr_value.v.p_sub_attr) == NULL) || - (SDP_DISC_ATTR_TYPE(p_subattr1->attr_len_type) != - DATA_ELE_SEQ_DESC_TYPE) || + (SDP_DISC_ATTR_TYPE(p_subattr1->attr_len_type) != DATA_ELE_SEQ_DESC_TYPE) || ((p_subattr2 = p_subattr1->attr_value.v.p_sub_attr) == NULL) || ((p_repdesc = p_subattr2->p_next_attr) == NULL) || (SDP_DISC_ATTR_TYPE(p_repdesc->attr_len_type) != TEXT_STR_DESC_TYPE)) { @@ -157,95 +147,87 @@ static void hidh_search_callback(const RawAddress& /* bd_addr */, } p_nvi->dscp_info.dl_len = SDP_DISC_ATTR_LEN(p_repdesc->attr_len_type); - if (p_nvi->dscp_info.dl_len != 0) + if (p_nvi->dscp_info.dl_len != 0) { p_nvi->dscp_info.dsc_list = (uint8_t*)&p_repdesc->attr_value; + } if (((p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - p_rec, ATTR_ID_HID_VIRTUAL_CABLE)) != NULL) && + p_rec, ATTR_ID_HID_VIRTUAL_CABLE)) != NULL) && SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == BOOLEAN_DESC_TYPE && - SDP_DISC_ATTR_LEN(p_attr->attr_len_type) >= 1 && - (p_attr->attr_value.v.u8)) { + SDP_DISC_ATTR_LEN(p_attr->attr_len_type) >= 1 && (p_attr->attr_value.v.u8)) { attr_mask |= HID_VIRTUAL_CABLE; } if (((p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - p_rec, ATTR_ID_HID_RECONNECT_INITIATE)) != NULL) && + p_rec, ATTR_ID_HID_RECONNECT_INITIATE)) != NULL) && SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == BOOLEAN_DESC_TYPE && - SDP_DISC_ATTR_LEN(p_attr->attr_len_type) >= 1 && - (p_attr->attr_value.v.u8)) { + SDP_DISC_ATTR_LEN(p_attr->attr_len_type) >= 1 && (p_attr->attr_value.v.u8)) { attr_mask |= HID_RECONN_INIT; } if (((p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - p_rec, ATTR_ID_HID_NORMALLY_CONNECTABLE)) != NULL) && + p_rec, ATTR_ID_HID_NORMALLY_CONNECTABLE)) != NULL) && SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == BOOLEAN_DESC_TYPE && - SDP_DISC_ATTR_LEN(p_attr->attr_len_type) >= 1 && - (p_attr->attr_value.v.u8)) { + SDP_DISC_ATTR_LEN(p_attr->attr_len_type) >= 1 && (p_attr->attr_value.v.u8)) { attr_mask |= HID_NORMALLY_CONNECTABLE; } // this attribute is deprecated, should we still keep it? if (((p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - p_rec, ATTR_ID_HID_SDP_DISABLE)) != NULL) && + p_rec, ATTR_ID_HID_SDP_DISABLE)) != NULL) && SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == BOOLEAN_DESC_TYPE && - SDP_DISC_ATTR_LEN(p_attr->attr_len_type) >= 1 && - (p_attr->attr_value.v.u8)) { + SDP_DISC_ATTR_LEN(p_attr->attr_len_type) >= 1 && (p_attr->attr_value.v.u8)) { attr_mask |= HID_SDP_DISABLE; } if (((p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - p_rec, ATTR_ID_HID_BATTERY_POWER)) != NULL) && + p_rec, ATTR_ID_HID_BATTERY_POWER)) != NULL) && SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == BOOLEAN_DESC_TYPE && - SDP_DISC_ATTR_LEN(p_attr->attr_len_type) >= 1 && - (p_attr->attr_value.v.u8)) { + SDP_DISC_ATTR_LEN(p_attr->attr_len_type) >= 1 && (p_attr->attr_value.v.u8)) { attr_mask |= HID_BATTERY_POWER; } if (((p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - p_rec, ATTR_ID_HID_REMOTE_WAKE)) != NULL) && + p_rec, ATTR_ID_HID_REMOTE_WAKE)) != NULL) && SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == BOOLEAN_DESC_TYPE && - SDP_DISC_ATTR_LEN(p_attr->attr_len_type) >= 1 && - (p_attr->attr_value.v.u8)) { + SDP_DISC_ATTR_LEN(p_attr->attr_len_type) >= 1 && (p_attr->attr_value.v.u8)) { attr_mask |= HID_REMOTE_WAKE; } - hidh_get_str_attr(p_rec, ATTR_ID_SERVICE_NAME, HID_MAX_SVC_NAME_LEN, - p_nvi->svc_name); - hidh_get_str_attr(p_rec, ATTR_ID_SERVICE_DESCRIPTION, HID_MAX_SVC_DESCR_LEN, - p_nvi->svc_descr); - hidh_get_str_attr(p_rec, ATTR_ID_PROVIDER_NAME, HID_MAX_PROV_NAME_LEN, - p_nvi->prov_name); + hidh_get_str_attr(p_rec, ATTR_ID_SERVICE_NAME, HID_MAX_SVC_NAME_LEN, p_nvi->svc_name); + hidh_get_str_attr(p_rec, ATTR_ID_SERVICE_DESCRIPTION, HID_MAX_SVC_DESCR_LEN, p_nvi->svc_descr); + hidh_get_str_attr(p_rec, ATTR_ID_PROVIDER_NAME, HID_MAX_PROV_NAME_LEN, p_nvi->prov_name); if (((p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - p_rec, ATTR_ID_HID_DEVICE_RELNUM)) != NULL) && + p_rec, ATTR_ID_HID_DEVICE_RELNUM)) != NULL) && SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == UINT_DESC_TYPE && SDP_DISC_ATTR_LEN(p_attr->attr_len_type) >= 2) { p_nvi->rel_num = p_attr->attr_value.v.u16; } if (((p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - p_rec, ATTR_ID_HID_COUNTRY_CODE)) != NULL) && + p_rec, ATTR_ID_HID_COUNTRY_CODE)) != NULL) && SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == UINT_DESC_TYPE && SDP_DISC_ATTR_LEN(p_attr->attr_len_type) >= 1) { p_nvi->ctry_code = p_attr->attr_value.v.u8; } if (((p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - p_rec, ATTR_ID_HID_DEVICE_SUBCLASS)) != NULL) && + p_rec, ATTR_ID_HID_DEVICE_SUBCLASS)) != NULL) && SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == UINT_DESC_TYPE && SDP_DISC_ATTR_LEN(p_attr->attr_len_type) >= 1) { p_nvi->sub_class = p_attr->attr_value.v.u8; } if (((p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - p_rec, ATTR_ID_HID_PARSER_VERSION)) != NULL) && + p_rec, ATTR_ID_HID_PARSER_VERSION)) != NULL) && SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == UINT_DESC_TYPE && SDP_DISC_ATTR_LEN(p_attr->attr_len_type) >= 2) { p_nvi->hpars_ver = p_attr->attr_value.v.u16; } if (((p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - p_rec, ATTR_ID_HID_LINK_SUPERVISION_TO)) != NULL) && + p_rec, ATTR_ID_HID_LINK_SUPERVISION_TO)) != NULL) && SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == UINT_DESC_TYPE && SDP_DISC_ATTR_LEN(p_attr->attr_len_type) >= 2) { attr_mask |= HID_SUP_TOUT_AVLBL; @@ -253,22 +235,24 @@ static void hidh_search_callback(const RawAddress& /* bd_addr */, } if (((p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - p_rec, ATTR_ID_HID_SSR_HOST_MAX_LAT)) != NULL) && + p_rec, ATTR_ID_HID_SSR_HOST_MAX_LAT)) != NULL) && SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == UINT_DESC_TYPE && SDP_DISC_ATTR_LEN(p_attr->attr_len_type) >= 2) { attr_mask |= HID_SSR_MAX_LATENCY; p_nvi->ssr_max_latency = p_attr->attr_value.v.u16; - } else + } else { p_nvi->ssr_max_latency = HID_SSR_PARAM_INVALID; + } if (((p_attr = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - p_rec, ATTR_ID_HID_SSR_HOST_MIN_TOUT)) != NULL) && + p_rec, ATTR_ID_HID_SSR_HOST_MIN_TOUT)) != NULL) && SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == UINT_DESC_TYPE && SDP_DISC_ATTR_LEN(p_attr->attr_len_type) >= 2) { attr_mask |= HID_SSR_MIN_TOUT; p_nvi->ssr_min_tout = p_attr->attr_value.v.u16; - } else + } else { p_nvi->ssr_min_tout = HID_SSR_PARAM_INVALID; + } hh_cb.sdp_rec.p_sdp_layer_rec = p_rec; hh_cb.sdp_cback(SDP_SUCCESS, attr_mask, &hh_cb.sdp_rec); @@ -284,9 +268,7 @@ static void hidh_search_callback(const RawAddress& /* bd_addr */, * Returns void * ******************************************************************************/ -void HID_HostInit(void) { - memset(&hh_cb, 0, sizeof(tHID_HOST_CTB)); -} +void HID_HostInit(void) { memset(&hh_cb, 0, sizeof(tHID_HOST_CTB)); } /******************************************************************************* * @@ -301,16 +283,13 @@ tHID_STATUS HID_HostRegister(tHID_HOST_DEV_CALLBACK* dev_cback) { tHID_STATUS st; if (hh_cb.reg_flag) { - log_counter_metrics( - android::bluetooth::CodePathCounterKeyEnum::HIDH_ERR_ALREADY_REGISTERED, - 1); + log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum::HIDH_ERR_ALREADY_REGISTERED, 1); return HID_ERR_ALREADY_REGISTERED; } if (dev_cback == NULL) { - log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum:: - HIDH_ERR_INVALID_PARAM_AT_HOST_REGISTER, - 1); + log_counter_metrics( + android::bluetooth::CodePathCounterKeyEnum::HIDH_ERR_INVALID_PARAM_AT_HOST_REGISTER, 1); return HID_ERR_INVALID_PARAM; } @@ -324,10 +303,9 @@ tHID_STATUS HID_HostRegister(tHID_HOST_DEV_CALLBACK* dev_cback) { hh_cb.reg_flag = true; for (size_t i = 0; i < HID_HOST_MAX_DEVICES; i++) { - hh_cb.devices[i].conn.process_repage_timer = - alarm_new("hid_devices_conn.process_repage_timer"); + hh_cb.devices[i].conn.process_repage_timer = alarm_new("hid_devices_conn.process_repage_timer"); } - return (HID_SUCCESS); + return HID_SUCCESS; } /******************************************************************************* @@ -342,7 +320,9 @@ tHID_STATUS HID_HostRegister(tHID_HOST_DEV_CALLBACK* dev_cback) { tHID_STATUS HID_HostDeregister(void) { uint8_t i; - if (!hh_cb.reg_flag) return (HID_ERR_NOT_REGISTERED); + if (!hh_cb.reg_flag) { + return HID_ERR_NOT_REGISTERED; + } for (i = 0; i < HID_HOST_MAX_DEVICES; i++) { HID_HostRemoveDev(i); @@ -353,7 +333,7 @@ tHID_STATUS HID_HostDeregister(void) { hidh_conn_dereg(); hh_cb.reg_flag = false; - return (HID_SUCCESS); + return HID_SUCCESS; } /******************************************************************************* @@ -369,7 +349,7 @@ tHID_STATUS HID_HostDeregister(void) { bool HID_HostSDPDisable(const RawAddress& addr) { for (int i = 0; i < HID_HOST_MAX_DEVICES; i++) { if (hh_cb.devices[i].in_use && (hh_cb.devices[i].addr == addr)) { - return (hh_cb.devices[i].attr_mask & HID_SDP_DISABLE); + return hh_cb.devices[i].attr_mask & HID_SDP_DISABLE; } } return false; @@ -384,26 +364,30 @@ bool HID_HostSDPDisable(const RawAddress& addr) { * Returns tHID_STATUS * ******************************************************************************/ -tHID_STATUS HID_HostAddDev(const RawAddress& addr, uint16_t attr_mask, - uint8_t* handle) { +tHID_STATUS HID_HostAddDev(const RawAddress& addr, uint16_t attr_mask, uint8_t* handle) { int i; /* Find an entry for this device in hh_cb.devices array */ - if (!hh_cb.reg_flag) return (HID_ERR_NOT_REGISTERED); + if (!hh_cb.reg_flag) { + return HID_ERR_NOT_REGISTERED; + } for (i = 0; i < HID_HOST_MAX_DEVICES; i++) { - if ((hh_cb.devices[i].in_use) && addr == hh_cb.devices[i].addr) break; + if ((hh_cb.devices[i].in_use) && addr == hh_cb.devices[i].addr) { + break; + } } if (i == HID_HOST_MAX_DEVICES) { for (i = 0; i < HID_HOST_MAX_DEVICES; i++) { - if (!hh_cb.devices[i].in_use) break; + if (!hh_cb.devices[i].in_use) { + break; + } } } if (i == HID_HOST_MAX_DEVICES) { - log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum:: - HIDH_ERR_NO_RESOURCES_ADD_DEVICE, - 1); + log_counter_metrics( + android::bluetooth::CodePathCounterKeyEnum::HIDH_ERR_NO_RESOURCES_ADD_DEVICE, 1); return HID_ERR_NO_RESOURCES; } @@ -418,7 +402,7 @@ tHID_STATUS HID_HostAddDev(const RawAddress& addr, uint16_t attr_mask, *handle = i; - return (HID_SUCCESS); + return HID_SUCCESS; } /******************************************************************************* @@ -432,21 +416,21 @@ tHID_STATUS HID_HostAddDev(const RawAddress& addr, uint16_t attr_mask, * ******************************************************************************/ tHID_STATUS HID_HostRemoveDev(uint8_t dev_handle) { - if (!hh_cb.reg_flag) return (HID_ERR_NOT_REGISTERED); + if (!hh_cb.reg_flag) { + return HID_ERR_NOT_REGISTERED; + } - if ((dev_handle >= HID_HOST_MAX_DEVICES) || - (!hh_cb.devices[dev_handle].in_use)) { - log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum:: - HIDH_ERR_INVALID_PARAM_AT_HOST_REMOVE_DEV, - 1); + if ((dev_handle >= HID_HOST_MAX_DEVICES) || (!hh_cb.devices[dev_handle].in_use)) { + log_counter_metrics( + android::bluetooth::CodePathCounterKeyEnum::HIDH_ERR_INVALID_PARAM_AT_HOST_REMOVE_DEV, + 1); return HID_ERR_INVALID_PARAM; } HID_HostCloseDev(dev_handle); hh_cb.devices[dev_handle].in_use = false; hh_cb.devices[dev_handle].conn.conn_state = HID_CONN_STATE_UNUSED; - hh_cb.devices[dev_handle].conn.ctrl_cid = - hh_cb.devices[dev_handle].conn.intr_cid = 0; + hh_cb.devices[dev_handle].conn.ctrl_cid = hh_cb.devices[dev_handle].conn.intr_cid = 0; hh_cb.devices[dev_handle].attr_mask = 0; return HID_SUCCESS; } @@ -462,19 +446,18 @@ tHID_STATUS HID_HostRemoveDev(uint8_t dev_handle) { * ******************************************************************************/ tHID_STATUS HID_HostOpenDev(uint8_t dev_handle) { - if (!hh_cb.reg_flag) return (HID_ERR_NOT_REGISTERED); + if (!hh_cb.reg_flag) { + return HID_ERR_NOT_REGISTERED; + } - if ((dev_handle >= HID_HOST_MAX_DEVICES) || - (!hh_cb.devices[dev_handle].in_use)) { - log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum:: - HIDH_ERR_INVALID_PARAM_AT_HOST_OPEN_DEV, - 1); + if ((dev_handle >= HID_HOST_MAX_DEVICES) || (!hh_cb.devices[dev_handle].in_use)) { + log_counter_metrics( + android::bluetooth::CodePathCounterKeyEnum::HIDH_ERR_INVALID_PARAM_AT_HOST_OPEN_DEV, 1); return HID_ERR_INVALID_PARAM; } if (hh_cb.devices[dev_handle].state != HID_DEV_NO_CONN) { - log_counter_metrics( - android::bluetooth::CodePathCounterKeyEnum::HIDH_ERR_ALREADY_CONN, 1); + log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum::HIDH_ERR_ALREADY_CONN, 1); return HID_ERR_ALREADY_CONN; } @@ -494,8 +477,8 @@ tHID_STATUS HID_HostOpenDev(uint8_t dev_handle) { * Returns void * ******************************************************************************/ -tHID_STATUS HID_HostWriteDev(uint8_t dev_handle, uint8_t t_type, uint8_t param, - uint16_t data, uint8_t report_id, BT_HDR* pbuf) { +tHID_STATUS HID_HostWriteDev(uint8_t dev_handle, uint8_t t_type, uint8_t param, uint16_t data, + uint8_t report_id, BT_HDR* pbuf) { tHID_STATUS status = HID_SUCCESS; if (!hh_cb.reg_flag) { @@ -503,28 +486,27 @@ tHID_STATUS HID_HostWriteDev(uint8_t dev_handle, uint8_t t_type, uint8_t param, status = HID_ERR_NOT_REGISTERED; } - if ((dev_handle >= HID_HOST_MAX_DEVICES) || - (!hh_cb.devices[dev_handle].in_use)) { + if ((dev_handle >= HID_HOST_MAX_DEVICES) || (!hh_cb.devices[dev_handle].in_use)) { log::error("HID_ERR_INVALID_PARAM"); - log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum:: - HIDH_ERR_INVALID_PARAM_AT_HOST_WRITE_DEV, - 1); + log_counter_metrics( + android::bluetooth::CodePathCounterKeyEnum::HIDH_ERR_INVALID_PARAM_AT_HOST_WRITE_DEV, + 1); status = HID_ERR_INVALID_PARAM; } else if (hh_cb.devices[dev_handle].state != HID_DEV_CONNECTED) { log::error("HID_ERR_NO_CONNECTION dev_handle {}", dev_handle); - log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum:: - HIDH_ERR_NO_CONNECTION_AT_HOST_WRITE_DEV, - 1); + log_counter_metrics( + android::bluetooth::CodePathCounterKeyEnum::HIDH_ERR_NO_CONNECTION_AT_HOST_WRITE_DEV, + 1); status = HID_ERR_NO_CONNECTION; } - if (status != HID_SUCCESS) + if (status != HID_SUCCESS) { osi_free(pbuf); - else - status = - hidh_conn_snd_data(dev_handle, t_type, param, data, report_id, pbuf); + } else { + status = hidh_conn_snd_data(dev_handle, t_type, param, data, report_id, pbuf); + } return status; } @@ -539,20 +521,21 @@ tHID_STATUS HID_HostWriteDev(uint8_t dev_handle, uint8_t t_type, uint8_t param, * ******************************************************************************/ tHID_STATUS HID_HostCloseDev(uint8_t dev_handle) { - if (!hh_cb.reg_flag) return (HID_ERR_NOT_REGISTERED); + if (!hh_cb.reg_flag) { + return HID_ERR_NOT_REGISTERED; + } - if ((dev_handle >= HID_HOST_MAX_DEVICES) || - (!hh_cb.devices[dev_handle].in_use)) { - log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum:: - HIDH_ERR_INVALID_PARAM_AT_HOST_CLOSE_DEV, - 1); + if ((dev_handle >= HID_HOST_MAX_DEVICES) || (!hh_cb.devices[dev_handle].in_use)) { + log_counter_metrics( + android::bluetooth::CodePathCounterKeyEnum::HIDH_ERR_INVALID_PARAM_AT_HOST_CLOSE_DEV, + 1); return HID_ERR_INVALID_PARAM; } if (hh_cb.devices[dev_handle].state != HID_DEV_CONNECTED) { - log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum:: - HIDH_ERR_NO_CONNECTION_AT_HOST_CLOSE_DEV, - 1); + log_counter_metrics( + android::bluetooth::CodePathCounterKeyEnum::HIDH_ERR_NO_CONNECTION_AT_HOST_CLOSE_DEV, + 1); return HID_ERR_NO_CONNECTION; } diff --git a/system/stack/hid/hidh_conn.cc b/system/stack/hid/hidh_conn.cc index d4d3de523d3..68a3961727e 100644 --- a/system/stack/hid/hidh_conn.cc +++ b/system/stack/hid/hidh_conn.cc @@ -49,7 +49,7 @@ using namespace bluetooth; namespace { constexpr char kBtmLogTag[] = "HIDH"; constexpr uint8_t kHID_HOST_MAX_DEVICES = HID_HOST_MAX_DEVICES; -} +} // namespace static uint8_t find_conn_by_cid(uint16_t cid); static void hidh_conn_retry(uint8_t dhandle); @@ -57,13 +57,11 @@ static void hidh_conn_retry(uint8_t dhandle); /******************************************************************************/ /* L O C A L F U N C T I O N P R O T O T Y P E S */ /******************************************************************************/ -static void hidh_l2cif_connect_ind(const RawAddress& bd_addr, - uint16_t l2cap_cid, uint16_t psm, +static void hidh_l2cif_connect_ind(const RawAddress& bd_addr, uint16_t l2cap_cid, uint16_t psm, uint8_t l2cap_id); static void hidh_l2cif_connect_cfm(uint16_t l2cap_cid, uint16_t result); static void hidh_l2cif_config_ind(uint16_t l2cap_cid, tL2CAP_CFG_INFO* p_cfg); -static void hidh_l2cif_config_cfm(uint16_t l2cap_cid, uint16_t result, - tL2CAP_CFG_INFO* p_cfg); +static void hidh_l2cif_config_cfm(uint16_t l2cap_cid, uint16_t result, tL2CAP_CFG_INFO* p_cfg); static void hidh_l2cif_disconnect_ind(uint16_t l2cap_cid, bool ack_needed); static void hidh_l2cif_data_ind(uint16_t l2cap_cid, BT_HDR* p_msg); static void hidh_l2cif_disconnect(uint16_t l2cap_cid); @@ -71,19 +69,19 @@ static void hidh_l2cif_cong_ind(uint16_t l2cap_cid, bool congested); static void hidh_on_l2cap_error(uint16_t l2cap_cid, uint16_t result); static const tL2CAP_APPL_INFO hst_reg_info = { - .pL2CA_ConnectInd_Cb = hidh_l2cif_connect_ind, - .pL2CA_ConnectCfm_Cb = hidh_l2cif_connect_cfm, - .pL2CA_ConfigInd_Cb = hidh_l2cif_config_ind, - .pL2CA_ConfigCfm_Cb = hidh_l2cif_config_cfm, - .pL2CA_DisconnectInd_Cb = hidh_l2cif_disconnect_ind, - .pL2CA_DataInd_Cb = hidh_l2cif_data_ind, - .pL2CA_CongestionStatus_Cb = hidh_l2cif_cong_ind, - .pL2CA_TxComplete_Cb = nullptr, - .pL2CA_Error_Cb = hidh_on_l2cap_error, - .pL2CA_CreditBasedConnectInd_Cb = nullptr, - .pL2CA_CreditBasedConnectCfm_Cb = nullptr, - .pL2CA_CreditBasedReconfigCompleted_Cb = nullptr, - .pL2CA_CreditBasedCollisionInd_Cb = nullptr, + .pL2CA_ConnectInd_Cb = hidh_l2cif_connect_ind, + .pL2CA_ConnectCfm_Cb = hidh_l2cif_connect_cfm, + .pL2CA_ConfigInd_Cb = hidh_l2cif_config_ind, + .pL2CA_ConfigCfm_Cb = hidh_l2cif_config_cfm, + .pL2CA_DisconnectInd_Cb = hidh_l2cif_disconnect_ind, + .pL2CA_DataInd_Cb = hidh_l2cif_data_ind, + .pL2CA_CongestionStatus_Cb = hidh_l2cif_cong_ind, + .pL2CA_TxComplete_Cb = nullptr, + .pL2CA_Error_Cb = hidh_on_l2cap_error, + .pL2CA_CreditBasedConnectInd_Cb = nullptr, + .pL2CA_CreditBasedConnectCfm_Cb = nullptr, + .pL2CA_CreditBasedReconfigCompleted_Cb = nullptr, + .pL2CA_CreditBasedCollisionInd_Cb = nullptr, }; static void hidh_try_repage(uint8_t dhandle); @@ -106,24 +104,22 @@ tHID_STATUS hidh_conn_reg(void) { hh_cb.l2cap_cfg.mtu = HID_HOST_MTU; /* Now, register with L2CAP */ - if (!L2CA_RegisterWithSecurity( - HID_PSM_CONTROL, hst_reg_info, false /* enable_snoop */, nullptr, - HID_HOST_MTU, 0, BTA_SEC_AUTHENTICATE | BTA_SEC_ENCRYPT)) { + if (!L2CA_RegisterWithSecurity(HID_PSM_CONTROL, hst_reg_info, false /* enable_snoop */, nullptr, + HID_HOST_MTU, 0, BTA_SEC_AUTHENTICATE | BTA_SEC_ENCRYPT)) { log::error("HID-Host Control Registration failed"); - log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum:: - HIDH_ERR_L2CAP_FAILED_AT_REGISTER_CONTROL, - 1); - return (HID_ERR_L2CAP_FAILED); - } - if (!L2CA_RegisterWithSecurity( - HID_PSM_INTERRUPT, hst_reg_info, false /* enable_snoop */, nullptr, - HID_HOST_MTU, 0, BTA_SEC_AUTHENTICATE | BTA_SEC_ENCRYPT)) { + log_counter_metrics( + android::bluetooth::CodePathCounterKeyEnum::HIDH_ERR_L2CAP_FAILED_AT_REGISTER_CONTROL, + 1); + return HID_ERR_L2CAP_FAILED; + } + if (!L2CA_RegisterWithSecurity(HID_PSM_INTERRUPT, hst_reg_info, false /* enable_snoop */, nullptr, + HID_HOST_MTU, 0, BTA_SEC_AUTHENTICATE | BTA_SEC_ENCRYPT)) { L2CA_Deregister(HID_PSM_CONTROL); log::error("HID-Host Interrupt Registration failed"); - log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum:: - HIDH_ERR_L2CAP_FAILED_AT_REGISTER_INTERRUPT, - 1); - return (HID_ERR_L2CAP_FAILED); + log_counter_metrics( + android::bluetooth::CodePathCounterKeyEnum::HIDH_ERR_L2CAP_FAILED_AT_REGISTER_INTERRUPT, + 1); + return HID_ERR_L2CAP_FAILED; } for (xx = 0; xx < kHID_HOST_MAX_DEVICES; xx++) { @@ -131,7 +127,7 @@ tHID_STATUS hidh_conn_reg(void) { hh_cb.devices[xx].conn.conn_state = HID_CONN_STATE_UNUSED; } - return (HID_SUCCESS); + return HID_SUCCESS; } /******************************************************************************* @@ -151,19 +147,17 @@ tHID_STATUS hidh_conn_disconnect(uint8_t dhandle) { /* Set l2cap idle timeout to 0 (so ACL link is disconnected * immediately after last channel is closed) */ - if (!L2CA_SetIdleTimeoutByBdAddr(hh_cb.devices[dhandle].addr, 0, - BT_TRANSPORT_BR_EDR)) { - log::warn("Unable to set L2CAP idle timeout peer:{}", - hh_cb.devices[dhandle].addr); + if (!L2CA_SetIdleTimeoutByBdAddr(hh_cb.devices[dhandle].addr, 0, BT_TRANSPORT_BR_EDR)) { + log::warn("Unable to set L2CAP idle timeout peer:{}", hh_cb.devices[dhandle].addr); } /* Disconnect both interrupt and control channels */ - if (p_hcon->intr_cid) + if (p_hcon->intr_cid) { hidh_l2cif_disconnect(p_hcon->intr_cid); - else if (p_hcon->ctrl_cid) + } else if (p_hcon->ctrl_cid) { hidh_l2cif_disconnect(p_hcon->ctrl_cid); + } - BTM_LogHistory(kBtmLogTag, hh_cb.devices[dhandle].addr, "Disconnecting", - "local initiated"); + BTM_LogHistory(kBtmLogTag, hh_cb.devices[dhandle].addr, "Disconnecting", "local initiated"); } else { p_hcon->conn_state = HID_CONN_STATE_UNUSED; } @@ -181,20 +175,17 @@ tHID_STATUS hidh_conn_disconnect(uint8_t dhandle) { * Returns void * ******************************************************************************/ -static void hidh_l2cif_connect_ind(const RawAddress& bd_addr, - uint16_t l2cap_cid, uint16_t psm, +static void hidh_l2cif_connect_ind(const RawAddress& bd_addr, uint16_t l2cap_cid, uint16_t psm, uint8_t l2cap_id) { bool bAccept = true; uint8_t i = kHID_HOST_MAX_DEVICES; - log::verbose("HID-Host Rcvd L2CAP conn ind, PSM: 0x{:04x} CID 0x{:x}", psm, - l2cap_cid); + log::verbose("HID-Host Rcvd L2CAP conn ind, PSM: 0x{:04x} CID 0x{:x}", psm, l2cap_cid); /* always add incoming connection device into HID database by default */ if (HID_HostAddDev(bd_addr, HID_SEC_REQUIRED, &i) != HID_SUCCESS) { if (!L2CA_DisconnectReq(l2cap_cid)) { - log::warn("Unable to send L2CAP disconnect request peer:{} cid:{}", - bd_addr, l2cap_cid); + log::warn("Unable to send L2CAP disconnect request peer:{} cid:{}", bd_addr, l2cap_cid); } return; } @@ -202,10 +193,9 @@ static void hidh_l2cif_connect_ind(const RawAddress& bd_addr, tHID_CONN* p_hcon = &hh_cb.devices[i].conn; BTM_LogHistory( - kBtmLogTag, hh_cb.devices[i].addr, "Connect request", - base::StringPrintf("%s state:%s", - (psm == HID_PSM_CONTROL) ? "control" : "interrupt", - hid_conn::state_text(p_hcon->conn_state).c_str())); + kBtmLogTag, hh_cb.devices[i].addr, "Connect request", + base::StringPrintf("%s state:%s", (psm == HID_PSM_CONTROL) ? "control" : "interrupt", + hid_conn::state_text(p_hcon->conn_state).c_str())); /* Check we are in the correct state for this */ if (psm == HID_PSM_INTERRUPT) { @@ -214,8 +204,7 @@ static void hidh_l2cif_connect_ind(const RawAddress& bd_addr, bAccept = false; } if (p_hcon->conn_state != HID_CONN_STATE_CONNECTING_INTR) { - log::warn("HID-Host Rcvd INTR L2CAP conn ind, wrong state: {}", - p_hcon->conn_state); + log::warn("HID-Host Rcvd INTR L2CAP conn ind, wrong state: {}", p_hcon->conn_state); bAccept = false; } } else /* CTRL channel */ @@ -225,8 +214,7 @@ static void hidh_l2cif_connect_ind(const RawAddress& bd_addr, p_hcon->conn_state = HID_CONN_STATE_UNUSED; #else if (p_hcon->conn_state != HID_CONN_STATE_UNUSED) { - log::warn("HID-Host - Rcvd CTL L2CAP conn ind, wrong state: {}", - p_hcon->conn_state); + log::warn("HID-Host - Rcvd CTL L2CAP conn ind, wrong state: {}", p_hcon->conn_state); bAccept = false; } #endif @@ -234,8 +222,7 @@ static void hidh_l2cif_connect_ind(const RawAddress& bd_addr, if (!bAccept) { if (!L2CA_DisconnectReq(l2cap_cid)) { - log::warn("Unable to send L2CAP disconnect request peer:{} cid:{}", - bd_addr, l2cap_cid); + log::warn("Unable to send L2CAP disconnect request peer:{} cid:{}", bd_addr, l2cap_cid); } return; } @@ -257,9 +244,9 @@ static void hidh_l2cif_connect_ind(const RawAddress& bd_addr, p_hcon->intr_cid = l2cap_cid; log::verbose( - "HID-Host Rcvd L2CAP conn ind, sent config req, PSM: 0x{:04x} CID " - "0x{:x}", - psm, l2cap_cid); + "HID-Host Rcvd L2CAP conn ind, sent config req, PSM: 0x{:04x} CID " + "0x{:x}", + psm, l2cap_cid); } static void hidh_process_repage_timer_timeout(void* data) { @@ -284,15 +271,14 @@ static void hidh_try_repage(uint8_t dhandle) { device = &hh_cb.devices[dhandle]; device->conn_tries++; - hh_cb.callback(dhandle, device->addr, HID_HDEV_EVT_RETRYING, - device->conn_tries, NULL); + hh_cb.callback(dhandle, device->addr, HID_HDEV_EVT_RETRYING, device->conn_tries, NULL); } static void hidh_on_l2cap_error(uint16_t l2cap_cid, uint16_t result) { auto dhandle = find_conn_by_cid(l2cap_cid); if (dhandle == kHID_HOST_MAX_DEVICES) { - log::warn("Received error for unknown device cid:0x{:04x} reason:{}", - l2cap_cid, hci_reason_code_text(to_hci_reason_code(result))); + log::warn("Received error for unknown device cid:0x{:04x} reason:{}", l2cap_cid, + hci_reason_code_text(to_hci_reason_code(result))); return; } @@ -308,13 +294,11 @@ static void hidh_on_l2cap_error(uint16_t l2cap_cid, uint16_t result) { #endif { uint32_t reason = HID_L2CAP_CONN_FAIL | (uint32_t)result; - hh_cb.callback(dhandle, hh_cb.devices[dhandle].addr, HID_HDEV_EVT_CLOSE, - reason, NULL); + hh_cb.callback(dhandle, hh_cb.devices[dhandle].addr, HID_HDEV_EVT_CLOSE, reason, NULL); } } else { uint32_t reason = HID_L2CAP_CFG_FAIL | (uint32_t)result; - hh_cb.callback(dhandle, hh_cb.devices[dhandle].addr, HID_HDEV_EVT_CLOSE, - reason, NULL); + hh_cb.callback(dhandle, hh_cb.devices[dhandle].addr, HID_HDEV_EVT_CLOSE, reason, NULL); } } @@ -341,10 +325,8 @@ static void hidh_l2cif_connect_cfm(uint16_t l2cap_cid, uint16_t result) { } if ((p_hcon == NULL) || (!(p_hcon->conn_flags & HID_CONN_FLAGS_IS_ORIG)) || - ((l2cap_cid == p_hcon->ctrl_cid) && - (p_hcon->conn_state != HID_CONN_STATE_CONNECTING_CTRL)) || - ((l2cap_cid == p_hcon->intr_cid) && - (p_hcon->conn_state != HID_CONN_STATE_CONNECTING_INTR) && + ((l2cap_cid == p_hcon->ctrl_cid) && (p_hcon->conn_state != HID_CONN_STATE_CONNECTING_CTRL)) || + ((l2cap_cid == p_hcon->intr_cid) && (p_hcon->conn_state != HID_CONN_STATE_CONNECTING_INTR) && (p_hcon->conn_state != HID_CONN_STATE_DISCONNECTING))) { log::warn("HID-Host Rcvd unexpected conn cnf, CID 0x{:x}", l2cap_cid); return; @@ -368,10 +350,9 @@ static void hidh_l2cif_connect_cfm(uint16_t l2cap_cid, uint16_t result) { p_hcon->conn_state = HID_CONN_STATE_CONFIG; } BTM_LogHistory( - kBtmLogTag, hh_cb.devices[dhandle].addr, "Configuring", - base::StringPrintf("control:0x%04x interrupt:0x%04x state:%s", - p_hcon->ctrl_cid, p_hcon->intr_cid, - hid_conn::state_text(p_hcon->conn_state).c_str())); + kBtmLogTag, hh_cb.devices[dhandle].addr, "Configuring", + base::StringPrintf("control:0x%04x interrupt:0x%04x state:%s", p_hcon->ctrl_cid, + p_hcon->intr_cid, hid_conn::state_text(p_hcon->conn_state).c_str())); return; } @@ -403,10 +384,11 @@ static void hidh_l2cif_config_ind(uint16_t l2cap_cid, tL2CAP_CFG_INFO* p_cfg) { log::verbose("HID-Host Rcvd cfg ind, sent cfg cfm, CID: 0x{:x}", l2cap_cid); /* Remember the remote MTU size */ - if ((!p_cfg->mtu_present) || (p_cfg->mtu > HID_HOST_MTU)) + if ((!p_cfg->mtu_present) || (p_cfg->mtu > HID_HOST_MTU)) { p_hcon->rem_mtu_size = HID_HOST_MTU; - else + } else { p_hcon->rem_mtu_size = p_cfg->mtu; + } } /******************************************************************************* @@ -419,8 +401,7 @@ static void hidh_l2cif_config_ind(uint16_t l2cap_cid, tL2CAP_CFG_INFO* p_cfg) { * Returns void * ******************************************************************************/ -static void hidh_l2cif_config_cfm(uint16_t l2cap_cid, uint16_t initiator, - tL2CAP_CFG_INFO* p_cfg) { +static void hidh_l2cif_config_cfm(uint16_t l2cap_cid, uint16_t initiator, tL2CAP_CFG_INFO* p_cfg) { hidh_l2cif_config_ind(l2cap_cid, p_cfg); uint8_t dhandle; @@ -431,7 +412,9 @@ static void hidh_l2cif_config_cfm(uint16_t l2cap_cid, uint16_t initiator, /* Find CCB based on CID */ dhandle = find_conn_by_cid(l2cap_cid); - if (dhandle < kHID_HOST_MAX_DEVICES) p_hcon = &hh_cb.devices[dhandle].conn; + if (dhandle < kHID_HOST_MAX_DEVICES) { + p_hcon = &hh_cb.devices[dhandle].conn; + } if (p_hcon == NULL) { log::warn("HID-Host Rcvd L2CAP cfg ind, unknown CID: 0x{:x}", l2cap_cid); @@ -445,24 +428,21 @@ static void hidh_l2cif_config_cfm(uint16_t l2cap_cid, uint16_t initiator, CLOSE_EVT: Connection Attempt was made but failed */ - p_hcon->intr_cid = L2CA_ConnectReqWithSecurity( - HID_PSM_INTERRUPT, hh_cb.devices[dhandle].addr, - BTA_SEC_AUTHENTICATE | BTA_SEC_ENCRYPT); + p_hcon->intr_cid = L2CA_ConnectReqWithSecurity(HID_PSM_INTERRUPT, hh_cb.devices[dhandle].addr, + BTA_SEC_AUTHENTICATE | BTA_SEC_ENCRYPT); if (p_hcon->intr_cid == 0) { log::warn("HID-Host INTR Originate failed"); reason = HID_L2CAP_REQ_FAIL; p_hcon->conn_state = HID_CONN_STATE_UNUSED; BTM_LogHistory(kBtmLogTag, hh_cb.devices[dhandle].addr, "Failed"); hidh_conn_disconnect(dhandle); - hh_cb.callback(dhandle, hh_cb.devices[dhandle].addr, HID_HDEV_EVT_CLOSE, - reason, NULL); + hh_cb.callback(dhandle, hh_cb.devices[dhandle].addr, HID_HDEV_EVT_CLOSE, reason, NULL); return; } else { /* Transition to the next appropriate state, waiting for connection * confirm on interrupt channel. */ p_hcon->conn_state = HID_CONN_STATE_CONNECTING_INTR; - BTM_LogHistory(kBtmLogTag, hh_cb.devices[dhandle].addr, "Connecting", - "interrupt channel"); + BTM_LogHistory(kBtmLogTag, hh_cb.devices[dhandle].addr, "Connecting", "interrupt channel"); } } } @@ -475,13 +455,11 @@ static void hidh_l2cif_config_cfm(uint16_t l2cap_cid, uint16_t initiator, p_hcon->disc_reason = HID_SUCCESS; hh_cb.devices[dhandle].state = HID_DEV_CONNECTED; - hh_cb.callback(dhandle, hh_cb.devices[dhandle].addr, HID_HDEV_EVT_OPEN, 0, - NULL); + hh_cb.callback(dhandle, hh_cb.devices[dhandle].addr, HID_HDEV_EVT_OPEN, 0, NULL); BTM_LogHistory( - kBtmLogTag, hh_cb.devices[dhandle].addr, "Connected", - base::StringPrintf("control:0x%04x interrupt:0x%04x state:%s", - p_hcon->ctrl_cid, p_hcon->intr_cid, - hid_conn::state_text(p_hcon->conn_state).c_str())); + kBtmLogTag, hh_cb.devices[dhandle].addr, "Connected", + base::StringPrintf("control:0x%04x interrupt:0x%04x state:%s", p_hcon->ctrl_cid, + p_hcon->intr_cid, hid_conn::state_text(p_hcon->conn_state).c_str())); } } @@ -503,7 +481,9 @@ static void hidh_l2cif_disconnect_ind(uint16_t l2cap_cid, bool ack_needed) { /* Find CCB based on CID */ dhandle = find_conn_by_cid(l2cap_cid); - if (dhandle < kHID_HOST_MAX_DEVICES) p_hcon = &hh_cb.devices[dhandle].conn; + if (dhandle < kHID_HOST_MAX_DEVICES) { + p_hcon = &hh_cb.devices[dhandle].conn; + } if (p_hcon == NULL) { log::warn("HID-Host Rcvd L2CAP disc, unknown CID: 0x{:x}", l2cap_cid); @@ -513,35 +493,33 @@ static void hidh_l2cif_disconnect_ind(uint16_t l2cap_cid, bool ack_needed) { log::verbose("HID-Host Rcvd L2CAP disc, CID: 0x{:x}", l2cap_cid); p_hcon->conn_state = HID_CONN_STATE_DISCONNECTING; - BTM_LogHistory( - kBtmLogTag, hh_cb.devices[dhandle].addr, "Disconnecting", - base::StringPrintf("%s channel", (l2cap_cid == p_hcon->ctrl_cid) - ? "control" - : "interrupt")); + BTM_LogHistory(kBtmLogTag, hh_cb.devices[dhandle].addr, "Disconnecting", + base::StringPrintf("%s channel", + (l2cap_cid == p_hcon->ctrl_cid) ? "control" : "interrupt")); - if (l2cap_cid == p_hcon->ctrl_cid) + if (l2cap_cid == p_hcon->ctrl_cid) { p_hcon->ctrl_cid = 0; - else + } else { p_hcon->intr_cid = 0; + } if ((p_hcon->ctrl_cid == 0) && (p_hcon->intr_cid == 0)) { hh_cb.devices[dhandle].state = HID_DEV_NO_CONN; p_hcon->conn_state = HID_CONN_STATE_UNUSED; - if (!ack_needed) disc_res = btm_get_acl_disc_reason_code(); + if (!ack_needed) { + disc_res = btm_get_acl_disc_reason_code(); + } #if (HID_HOST_MAX_CONN_RETRY > 0) - if ((disc_res == HCI_ERR_CONNECTION_TOUT || - disc_res == HCI_ERR_UNSPECIFIED) && + if ((disc_res == HCI_ERR_CONNECTION_TOUT || disc_res == HCI_ERR_UNSPECIFIED) && (!(hh_cb.devices[dhandle].attr_mask & HID_RECONN_INIT)) && (hh_cb.devices[dhandle].attr_mask & HID_NORMALLY_CONNECTABLE)) { hh_cb.devices[dhandle].conn_tries = 0; uint64_t interval_ms = HID_HOST_REPAGE_WIN * 1000; - alarm_set_on_mloop(hh_cb.devices[dhandle].conn.process_repage_timer, - interval_ms, hidh_process_repage_timer_timeout, - UINT_TO_PTR(dhandle)); - hh_cb.callback(dhandle, hh_cb.devices[dhandle].addr, HID_HDEV_EVT_CLOSE, - disc_res, NULL); + alarm_set_on_mloop(hh_cb.devices[dhandle].conn.process_repage_timer, interval_ms, + hidh_process_repage_timer_timeout, UINT_TO_PTR(dhandle)); + hh_cb.callback(dhandle, hh_cb.devices[dhandle].addr, HID_HDEV_EVT_CLOSE, disc_res, NULL); } else #endif { @@ -550,22 +528,18 @@ static void hidh_l2cif_disconnect_ind(uint16_t l2cap_cid, bool ack_needed) { /* If we got baseband sent HCI_DISCONNECT_COMPLETE_EVT due to security * failure, then set reason to HID_ERR_AUTH_FAILED */ - if ((disc_res == HCI_ERR_AUTH_FAILURE) || - (disc_res == HCI_ERR_KEY_MISSING) || - (disc_res == HCI_ERR_HOST_REJECT_SECURITY) || - (disc_res == HCI_ERR_PAIRING_NOT_ALLOWED) || + if ((disc_res == HCI_ERR_AUTH_FAILURE) || (disc_res == HCI_ERR_KEY_MISSING) || + (disc_res == HCI_ERR_HOST_REJECT_SECURITY) || (disc_res == HCI_ERR_PAIRING_NOT_ALLOWED) || (disc_res == HCI_ERR_UNIT_KEY_USED) || (disc_res == HCI_ERR_PAIRING_WITH_UNIT_KEY_NOT_SUPPORTED) || (disc_res == HCI_ERR_ENCRY_MODE_NOT_ACCEPTABLE) || (disc_res == HCI_ERR_REPEATED_ATTEMPTS)) { - log_counter_metrics( - android::bluetooth::CodePathCounterKeyEnum::HIDH_ERR_AUTH_FAILED, - 1); + log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum::HIDH_ERR_AUTH_FAILED, 1); hid_close_evt_reason = HID_ERR_AUTH_FAILED; } - hh_cb.callback(dhandle, hh_cb.devices[dhandle].addr, HID_HDEV_EVT_CLOSE, - hid_close_evt_reason, NULL); + hh_cb.callback(dhandle, hh_cb.devices[dhandle].addr, HID_HDEV_EVT_CLOSE, hid_close_evt_reason, + NULL); } } } @@ -590,8 +564,7 @@ static void hidh_l2cif_disconnect(uint16_t l2cap_cid) { if (p_hcon->ctrl_cid) { log::verbose("HID-Host Initiating L2CAP Ctrl disconnection"); if (!L2CA_DisconnectReq(p_hcon->ctrl_cid)) { - log::warn("Unable to send L2CAP disconnect request cid:{}", - p_hcon->ctrl_cid); + log::warn("Unable to send L2CAP disconnect request cid:{}", p_hcon->ctrl_cid); } p_hcon->ctrl_cid = 0; } @@ -601,8 +574,8 @@ static void hidh_l2cif_disconnect(uint16_t l2cap_cid) { hh_cb.devices[dhandle].state = HID_DEV_NO_CONN; p_hcon->conn_state = HID_CONN_STATE_UNUSED; BTM_LogHistory(kBtmLogTag, hh_cb.devices[dhandle].addr, "Disconnected"); - hh_cb.callback(dhandle, hh_cb.devices[dhandle].addr, HID_HDEV_EVT_CLOSE, - p_hcon->disc_reason, NULL); + hh_cb.callback(dhandle, hh_cb.devices[dhandle].addr, HID_HDEV_EVT_CLOSE, p_hcon->disc_reason, + NULL); } } @@ -621,20 +594,21 @@ static void hidh_l2cif_cong_ind(uint16_t l2cap_cid, bool congested) { /* Find CCB based on CID */ dhandle = find_conn_by_cid(l2cap_cid); - if (dhandle < kHID_HOST_MAX_DEVICES) p_hcon = &hh_cb.devices[dhandle].conn; + if (dhandle < kHID_HOST_MAX_DEVICES) { + p_hcon = &hh_cb.devices[dhandle].conn; + } if (p_hcon == NULL) { - log::warn("HID-Host Rcvd L2CAP congestion status, unknown CID: 0x{:x}", - l2cap_cid); + log::warn("HID-Host Rcvd L2CAP congestion status, unknown CID: 0x{:x}", l2cap_cid); return; } - log::verbose("HID-Host Rcvd L2CAP congestion status, CID: 0x{:x} Cong: {}", - l2cap_cid, congested); + log::verbose("HID-Host Rcvd L2CAP congestion status, CID: 0x{:x} Cong: {}", l2cap_cid, + congested); - if (congested) + if (congested) { p_hcon->conn_flags |= HID_CONN_FLAGS_CONGESTED; - else { + } else { p_hcon->conn_flags &= ~HID_CONN_FLAGS_CONGESTED; } } @@ -665,7 +639,9 @@ static void hidh_l2cif_data_ind(uint16_t l2cap_cid, BT_HDR* p_msg) { /* Find CCB based on CID */ dhandle = find_conn_by_cid(l2cap_cid); - if (dhandle < kHID_HOST_MAX_DEVICES) p_hcon = &hh_cb.devices[dhandle].conn; + if (dhandle < kHID_HOST_MAX_DEVICES) { + p_hcon = &hh_cb.devices[dhandle].conn; + } if (p_hcon == NULL) { log::warn("HID-Host Rcvd L2CAP data, unknown CID: 0x{:x}", l2cap_cid); @@ -690,8 +666,7 @@ static void hidh_l2cif_data_ind(uint16_t l2cap_cid, BT_HDR* p_msg) { switch (ttype) { case HID_TRANS_HANDSHAKE: - hh_cb.callback(dhandle, hh_cb.devices[dhandle].addr, - HID_HDEV_EVT_HANDSHAKE, param, NULL); + hh_cb.callback(dhandle, hh_cb.devices[dhandle].addr, HID_HDEV_EVT_HANDSHAKE, param, NULL); osi_free(p_msg); break; @@ -700,8 +675,7 @@ static void hidh_l2cif_data_ind(uint16_t l2cap_cid, BT_HDR* p_msg) { case HID_PAR_CONTROL_VIRTUAL_CABLE_UNPLUG: hidh_conn_disconnect(dhandle); /* Device is unplugging from us. Tell USB */ - hh_cb.callback(dhandle, hh_cb.devices[dhandle].addr, - HID_HDEV_EVT_VC_UNPLUG, 0, NULL); + hh_cb.callback(dhandle, hh_cb.devices[dhandle].addr, HID_HDEV_EVT_VC_UNPLUG, 0, NULL); break; default: @@ -711,19 +685,15 @@ static void hidh_l2cif_data_ind(uint16_t l2cap_cid, BT_HDR* p_msg) { break; case HID_TRANS_DATA: - evt = (hh_cb.devices[dhandle].conn.intr_cid == l2cap_cid) - ? HID_HDEV_EVT_INTR_DATA - : HID_HDEV_EVT_CTRL_DATA; - hh_cb.callback(dhandle, hh_cb.devices[dhandle].addr, evt, rep_type, - p_msg); + evt = (hh_cb.devices[dhandle].conn.intr_cid == l2cap_cid) ? HID_HDEV_EVT_INTR_DATA + : HID_HDEV_EVT_CTRL_DATA; + hh_cb.callback(dhandle, hh_cb.devices[dhandle].addr, evt, rep_type, p_msg); break; case HID_TRANS_DATAC: - evt = (hh_cb.devices[dhandle].conn.intr_cid == l2cap_cid) - ? HID_HDEV_EVT_INTR_DATC - : HID_HDEV_EVT_CTRL_DATC; - hh_cb.callback(dhandle, hh_cb.devices[dhandle].addr, evt, rep_type, - p_msg); + evt = (hh_cb.devices[dhandle].conn.intr_cid == l2cap_cid) ? HID_HDEV_EVT_INTR_DATC + : HID_HDEV_EVT_CTRL_DATC; + hh_cb.callback(dhandle, hh_cb.devices[dhandle].addr, evt, rep_type, p_msg); break; default: @@ -741,9 +711,8 @@ static void hidh_l2cif_data_ind(uint16_t l2cap_cid, BT_HDR* p_msg) { * Returns tHID_STATUS * ******************************************************************************/ -tHID_STATUS hidh_conn_snd_data(uint8_t dhandle, uint8_t trans_type, - uint8_t param, uint16_t data, uint8_t report_id, - BT_HDR* buf) { +tHID_STATUS hidh_conn_snd_data(uint8_t dhandle, uint8_t trans_type, uint8_t param, uint16_t data, + uint8_t report_id, BT_HDR* buf) { tHID_CONN* p_hcon = &hh_cb.devices[dhandle].conn; BT_HDR* p_buf; uint8_t* p_out; @@ -755,20 +724,17 @@ tHID_STATUS hidh_conn_snd_data(uint8_t dhandle, uint8_t trans_type, uint8_t use_data = 0; bool blank_datc = false; - if (!BTM_IsAclConnectionUp(hh_cb.devices[dhandle].addr, - BT_TRANSPORT_BR_EDR)) { + if (!BTM_IsAclConnectionUp(hh_cb.devices[dhandle].addr, BT_TRANSPORT_BR_EDR)) { osi_free(buf); - log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum:: - HIDH_ERR_NO_CONNECTION_AT_SEND_DATA, - 1); + log_counter_metrics( + android::bluetooth::CodePathCounterKeyEnum::HIDH_ERR_NO_CONNECTION_AT_SEND_DATA, 1); return HID_ERR_NO_CONNECTION; } if (p_hcon->conn_flags & HID_CONN_FLAGS_CONGESTED) { osi_free(buf); - log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum:: - HIDH_ERR_CONGESTED_AT_FLAG_CHECK, - 1); + log_counter_metrics( + android::bluetooth::CodePathCounterKeyEnum::HIDH_ERR_CONGESTED_AT_FLAG_CHECK, 1); return HID_ERR_CONGESTED; } @@ -788,16 +754,16 @@ tHID_STATUS hidh_conn_snd_data(uint8_t dhandle, uint8_t trans_type, buf_size = HID_INTERRUPT_BUF_SIZE; break; default: - log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum:: - HIDH_ERR_INVALID_PARAM_AT_SEND_DATA, - 1); - return (HID_ERR_INVALID_PARAM); + log_counter_metrics( + android::bluetooth::CodePathCounterKeyEnum::HIDH_ERR_INVALID_PARAM_AT_SEND_DATA, 1); + return HID_ERR_INVALID_PARAM; } - if (trans_type == HID_TRANS_SET_IDLE) + if (trans_type == HID_TRANS_SET_IDLE) { use_data = 1; - else if ((trans_type == HID_TRANS_GET_REPORT) && (param & 0x08)) + } else if ((trans_type == HID_TRANS_GET_REPORT) && (param & 0x08)) { use_data = 2; + } do { if (buf == NULL || blank_datc) { @@ -808,7 +774,7 @@ tHID_STATUS hidh_conn_snd_data(uint8_t dhandle, uint8_t trans_type, data_size = 0; bytes_copied = 0; blank_datc = false; - } else if ((buf->len > (p_hcon->rem_mtu_size - 1))) { + } else if (buf->len > (p_hcon->rem_mtu_size - 1)) { p_buf = (BT_HDR*)osi_malloc(buf_size); p_buf->offset = L2CAP_MIN_OFFSET; @@ -849,22 +815,21 @@ tHID_STATUS hidh_conn_snd_data(uint8_t dhandle, uint8_t trans_type, /* Send the buffer through L2CAP */ if ((p_hcon->conn_flags & HID_CONN_FLAGS_CONGESTED) || (L2CA_DataWrite(cid, p_buf) == tL2CAP_DW_RESULT::FAILED)) { - log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum:: - HIDH_ERR_CONGESTED_AT_SEND_DATA, - 1); - return (HID_ERR_CONGESTED); + log_counter_metrics( + android::bluetooth::CodePathCounterKeyEnum::HIDH_ERR_CONGESTED_AT_SEND_DATA, 1); + return HID_ERR_CONGESTED; } - if (data_size) + if (data_size) { trans_type = HID_TRANS_DATAC; - else if (bytes_copied == (p_hcon->rem_mtu_size - 1)) { + } else if (bytes_copied == (p_hcon->rem_mtu_size - 1)) { trans_type = HID_TRANS_DATAC; blank_datc = true; } } while ((data_size != 0) || blank_datc); - return (HID_SUCCESS); + return HID_SUCCESS; } /******************************************************************************* * @@ -880,40 +845,35 @@ tHID_STATUS hidh_conn_initiate(uint8_t dhandle) { tHID_HOST_DEV_CTB* p_dev = &hh_cb.devices[dhandle]; if (p_dev->conn.conn_state != HID_CONN_STATE_UNUSED) { - log_counter_metrics( - android::bluetooth::CodePathCounterKeyEnum::HIDH_ERR_CONN_IN_PROCESS, - 1); - return (HID_ERR_CONN_IN_PROCESS); + log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum::HIDH_ERR_CONN_IN_PROCESS, 1); + return HID_ERR_CONN_IN_PROCESS; } p_dev->conn.ctrl_cid = 0; p_dev->conn.intr_cid = 0; - p_dev->conn.disc_reason = - HID_L2CAP_CONN_FAIL; /* Reset initial reason for CLOSE_EVT: Connection - Attempt was made but failed */ + p_dev->conn.disc_reason = HID_L2CAP_CONN_FAIL; /* Reset initial reason for CLOSE_EVT: Connection + Attempt was made but failed */ /* We are the originator of this connection */ p_dev->conn.conn_flags = HID_CONN_FLAGS_IS_ORIG; /* Check if L2CAP started the connection process */ - p_dev->conn.ctrl_cid = L2CA_ConnectReqWithSecurity( - HID_PSM_CONTROL, p_dev->addr, BTA_SEC_AUTHENTICATE | BTA_SEC_ENCRYPT); + p_dev->conn.ctrl_cid = L2CA_ConnectReqWithSecurity(HID_PSM_CONTROL, p_dev->addr, + BTA_SEC_AUTHENTICATE | BTA_SEC_ENCRYPT); if (p_dev->conn.ctrl_cid == 0) { log::warn("HID-Host Originate failed"); - hh_cb.callback(dhandle, hh_cb.devices[dhandle].addr, HID_HDEV_EVT_CLOSE, - HID_ERR_L2CAP_FAILED, NULL); - log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum:: - HIDH_ERR_L2CAP_FAILED_AT_INITIATE, - 1); + hh_cb.callback(dhandle, hh_cb.devices[dhandle].addr, HID_HDEV_EVT_CLOSE, HID_ERR_L2CAP_FAILED, + NULL); + log_counter_metrics( + android::bluetooth::CodePathCounterKeyEnum::HIDH_ERR_L2CAP_FAILED_AT_INITIATE, 1); } else { /* Transition to the next appropriate state, waiting for connection confirm * on control channel. */ p_dev->conn.conn_state = HID_CONN_STATE_CONNECTING_CTRL; - BTM_LogHistory(kBtmLogTag, hh_cb.devices[dhandle].addr, "Connecting", - "control channel"); + BTM_LogHistory(kBtmLogTag, hh_cb.devices[dhandle].addr, "Connecting", "control channel"); } - return (HID_SUCCESS); + return HID_SUCCESS; } /******************************************************************************* @@ -932,12 +892,12 @@ static uint8_t find_conn_by_cid(uint16_t cid) { for (xx = 0; xx < kHID_HOST_MAX_DEVICES; xx++) { if ((hh_cb.devices[xx].in_use) && (hh_cb.devices[xx].conn.conn_state != HID_CONN_STATE_UNUSED) && - ((hh_cb.devices[xx].conn.ctrl_cid == cid) || - (hh_cb.devices[xx].conn.intr_cid == cid))) + ((hh_cb.devices[xx].conn.ctrl_cid == cid) || (hh_cb.devices[xx].conn.intr_cid == cid))) { break; + } } - return (xx); + return xx; } void hidh_conn_dereg(void) { diff --git a/system/stack/hid/hidh_int.h b/system/stack/hid/hidh_int.h index 5a19834e627..ae2d017b51e 100644 --- a/system/stack/hid/hidh_int.h +++ b/system/stack/hid/hidh_int.h @@ -63,9 +63,8 @@ typedef struct host_ctb { bool reg_flag; } tHID_HOST_CTB; -tHID_STATUS hidh_conn_snd_data(uint8_t dhandle, uint8_t trans_type, - uint8_t param, uint16_t data, uint8_t rpt_id, - BT_HDR* buf); +tHID_STATUS hidh_conn_snd_data(uint8_t dhandle, uint8_t trans_type, uint8_t param, uint16_t data, + uint8_t rpt_id, BT_HDR* buf); tHID_STATUS hidh_conn_reg(void); void hidh_conn_dereg(void); tHID_STATUS hidh_conn_disconnect(uint8_t dhandle); diff --git a/system/stack/include/a2dp_aac.h b/system/stack/include/a2dp_aac.h index 1b0311af53f..b6b44e45b48 100644 --- a/system/stack/include/a2dp_aac.h +++ b/system/stack/include/a2dp_aac.h @@ -30,42 +30,39 @@ #include "stack/include/bt_hdr.h" class A2dpCodecConfigAacBase : public A2dpCodecConfig { - protected: - A2dpCodecConfigAacBase(btav_a2dp_codec_index_t codec_index, - const std::string& name, - btav_a2dp_codec_priority_t codec_priority, - bool is_source) +protected: + A2dpCodecConfigAacBase(btav_a2dp_codec_index_t codec_index, const std::string& name, + btav_a2dp_codec_priority_t codec_priority, bool is_source) : A2dpCodecConfig(codec_index, A2DP_CODEC_ID_AAC, name, codec_priority), is_source_(is_source) {} bool setCodecConfig(const uint8_t* p_peer_codec_info, bool is_capability, uint8_t* p_result_codec_config) override; - bool setPeerCodecCapabilities( - const uint8_t* p_peer_codec_capabilities) override; + bool setPeerCodecCapabilities(const uint8_t* p_peer_codec_capabilities) override; - private: +private: bool is_source_; // True if local is Source }; class A2dpCodecConfigAacSource : public A2dpCodecConfigAacBase { - public: +public: A2dpCodecConfigAacSource(btav_a2dp_codec_priority_t codec_priority); virtual ~A2dpCodecConfigAacSource(); bool init() override; - private: +private: bool useRtpHeaderMarkerBit() const override; void debug_codec_dump(int fd) override; }; class A2dpCodecConfigAacSink : public A2dpCodecConfigAacBase { - public: +public: A2dpCodecConfigAacSink(btav_a2dp_codec_priority_t codec_priority); virtual ~A2dpCodecConfigAacSink(); bool init() override; - private: +private: bool useRtpHeaderMarkerBit() const override; }; @@ -114,8 +111,7 @@ bool A2DP_IsPeerSourceCodecSupportedAac(const uint8_t* p_codec_info); // enabled. |p_codec_info| contains information about the codec capabilities. // Returns true if the A2DP data packets should contain RTP header, otherwise // false. -bool A2DP_UsesRtpHeaderAac(bool content_protection_enabled, - const uint8_t* p_codec_info); +bool A2DP_UsesRtpHeaderAac(bool content_protection_enabled, const uint8_t* p_codec_info); // Gets the A2DP AAC codec name for a given |p_codec_info|. const char* A2DP_CodecNameAac(const uint8_t* p_codec_info); @@ -123,15 +119,13 @@ const char* A2DP_CodecNameAac(const uint8_t* p_codec_info); // Checks whether two A2DP AAC codecs |p_codec_info_a| and |p_codec_info_b| // have the same type. // Returns true if the two codecs have the same type, otherwise false. -bool A2DP_CodecTypeEqualsAac(const uint8_t* p_codec_info_a, - const uint8_t* p_codec_info_b); +bool A2DP_CodecTypeEqualsAac(const uint8_t* p_codec_info_a, const uint8_t* p_codec_info_b); // Checks whether two A2DP AAC codecs |p_codec_info_a| and |p_codec_info_b| // are exactly the same. // Returns true if the two codecs are exactly the same, otherwise false. // If the codec type is not AAC, the return value is false. -bool A2DP_CodecEqualsAac(const uint8_t* p_codec_info_a, - const uint8_t* p_codec_info_b); +bool A2DP_CodecEqualsAac(const uint8_t* p_codec_info_a, const uint8_t* p_codec_info_b); // Gets the track sample rate value for the A2DP AAC codec. // |p_codec_info| is a pointer to the AAC codec_info to decode. @@ -199,8 +193,8 @@ int A2DP_ComputeMaxBitRateAac(const uint8_t* p_codec_info, uint16_t mtu); // |p_data| contains the audio data. // The timestamp is stored in |p_timestamp|. // Returns true on success, otherwise false. -bool A2DP_GetPacketTimestampAac(const uint8_t* p_codec_info, - const uint8_t* p_data, uint32_t* p_timestamp); +bool A2DP_GetPacketTimestampAac(const uint8_t* p_codec_info, const uint8_t* p_data, + uint32_t* p_timestamp); // Builds A2DP AAC codec header for audio data. // |p_codec_info| contains the codec information. @@ -220,16 +214,14 @@ std::string A2DP_CodecInfoStringAac(const uint8_t* p_codec_info); // |p_codec_info| contains the codec information. // Returns the A2DP AAC encoder interface if the |p_codec_info| is valid and // supported, otherwise NULL. -const tA2DP_ENCODER_INTERFACE* A2DP_GetEncoderInterfaceAac( - const uint8_t* p_codec_info); +const tA2DP_ENCODER_INTERFACE* A2DP_GetEncoderInterfaceAac(const uint8_t* p_codec_info); // Gets the current A2DP AAC decoder interface that can be used to decode // received A2DP packets - see |tA2DP_DECODER_INTERFACE|. // |p_codec_info| contains the codec information. // Returns the A2DP AAC decoder interface if the |p_codec_info| is valid and // supported, otherwise NULL. -const tA2DP_DECODER_INTERFACE* A2DP_GetDecoderInterfaceAac( - const uint8_t* p_codec_info); +const tA2DP_DECODER_INTERFACE* A2DP_GetDecoderInterfaceAac(const uint8_t* p_codec_info); // Adjusts the A2DP AAC codec, based on local support and Bluetooth // specification. diff --git a/system/stack/include/a2dp_api.h b/system/stack/include/a2dp_api.h index e6be61cc9d2..d5ca12571d8 100644 --- a/system/stack/include/a2dp_api.h +++ b/system/stack/include/a2dp_api.h @@ -85,8 +85,8 @@ typedef struct { } tA2DP_Service; /* This is the callback to notify the result of the SDP discovery process. */ -using tA2DP_FIND_CBACK = base::Callback; +using tA2DP_FIND_CBACK = + base::Callback; /***************************************************************************** * external function declarations @@ -121,9 +121,8 @@ using tA2DP_FIND_CBACK = base::Callback& codec_priorities); @@ -309,9 +302,7 @@ class A2dpCodecs { // Gets the codec config that is currently selected. // Returns the codec config that is currently selected, or nullptr if // no codec is selected. - A2dpCodecConfig* getCurrentCodecConfig() const { - return current_codec_config_; - } + A2dpCodecConfig* getCurrentCodecConfig() const { return current_codec_config_; } // Selects the codec config. // /!\ Must only be used with offloaded codecs. @@ -321,14 +312,10 @@ class A2dpCodecs { } // Gets the list of Source codecs ordered by priority: higher priority first. - const std::list orderedSourceCodecs() const { - return ordered_source_codecs_; - } + const std::list orderedSourceCodecs() const { return ordered_source_codecs_; } // Gets the list of Sink codecs ordered by priority: higher priority first. - const std::list orderedSinkCodecs() const { - return ordered_sink_codecs_; - } + const std::list orderedSinkCodecs() const { return ordered_sink_codecs_; } // Sets the A2DP Source-to-Sink codec configuration to be used // with a peer Sink device. @@ -366,15 +353,13 @@ class A2dpCodecs { // The result codec configuration is stored in |p_result_codec_config|. // Returns true on success, othewise false. bool setCodecConfig(const uint8_t* p_peer_codec_info, bool is_capability, - uint8_t* p_result_codec_config, - bool select_current_codec); + uint8_t* p_result_codec_config, bool select_current_codec); // Sets the A2DP Sink codec configuration to be used with a peer Source // device. // [See setCodecConfig() for description] bool setSinkCodecConfig(const uint8_t* p_peer_codec_info, bool is_capability, - uint8_t* p_result_codec_config, - bool select_current_codec); + uint8_t* p_result_codec_config, bool select_current_codec); // Sets the user prefered codec configuration. // |codec_user_config| contains the preferred codec configuration. @@ -391,9 +376,8 @@ class A2dpCodecs { // Returns true on success, otherwise false. bool setCodecUserConfig(const btav_a2dp_codec_config_t& codec_user_config, const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params, - const uint8_t* p_peer_sink_capabilities, - uint8_t* p_result_codec_config, bool* p_restart_input, - bool* p_restart_output, bool* p_config_updated); + const uint8_t* p_peer_sink_capabilities, uint8_t* p_result_codec_config, + bool* p_restart_input, bool* p_restart_output, bool* p_config_updated); // Sets the Audio HAL selected audio feeding parameters. // Those parameters are applied only to the currently selected codec. @@ -409,8 +393,7 @@ class A2dpCodecs { // Returns true on success, otherwise false. bool setCodecAudioConfig(const btav_a2dp_codec_config_t& codec_audio_config, const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params, - const uint8_t* p_peer_sink_capabilities, - uint8_t* p_result_codec_config, + const uint8_t* p_peer_sink_capabilities, uint8_t* p_result_codec_config, bool* p_restart_output, bool* p_config_updated); // Sets the Over-The-Air preferred codec configuration. @@ -454,29 +437,28 @@ class A2dpCodecs { // and the remote device are stored in |p_codecs_selectable_capabilities|. // Returns true on success, otherwise false. bool getCodecConfigAndCapabilities( - btav_a2dp_codec_config_t* p_codec_config, - std::vector* p_codecs_local_capabilities, - std::vector* p_codecs_selectable_capabilities); + btav_a2dp_codec_config_t* p_codec_config, + std::vector* p_codecs_local_capabilities, + std::vector* p_codecs_selectable_capabilities); // Dumps codec-related information. // The information is written in user-friendly form to file descriptor |fd|. void debug_codec_dump(int fd); - private: +private: struct CompareBtBdaddr { bool operator()(const RawAddress& lhs, const RawAddress& rhs) const { - return (memcmp(&lhs, &rhs, sizeof(lhs)) < 0); + return memcmp(&lhs, &rhs, sizeof(lhs)) < 0; } }; typedef std::map IndexedCodecs; std::recursive_mutex codec_mutex_; A2dpCodecConfig* current_codec_config_; // Currently selected codec - std::map - codec_priorities_; + std::map codec_priorities_; - IndexedCodecs indexed_codecs_; // The codecs indexed by codec index - IndexedCodecs disabled_codecs_; // The disabled codecs + IndexedCodecs indexed_codecs_; // The codecs indexed by codec index + IndexedCodecs disabled_codecs_; // The disabled codecs // A2DP Source codecs ordered by priority std::list ordered_source_codecs_; @@ -510,8 +492,7 @@ typedef uint32_t (*a2dp_source_read_callback_t)(uint8_t* p_buf, uint32_t len); // |num_bytes| is the number of audio bytes in |p_buf| - it is used for // delay reporting. // Returns true if the packet was enqueued, otherwise false. -typedef bool (*a2dp_source_enqueue_callback_t)(BT_HDR* p_buf, size_t frames_n, - uint32_t num_bytes); +typedef bool (*a2dp_source_enqueue_callback_t)(BT_HDR* p_buf, size_t frames_n, uint32_t num_bytes); // // A2DP encoder callbacks interface. @@ -560,7 +541,7 @@ typedef void (*decoded_data_callback_t)(uint8_t* buf, uint32_t len); // A2DP decoder callbacks interface. // typedef struct { - // Initialize the decoder. Can be called multiple times, will reinitalize. + // Initialize the decoder. Can be called multiple times, will reinitialize. bool (*decoder_init)(decoded_data_callback_t decode_callback); // Cleanup the A2DP decoder. @@ -635,8 +616,7 @@ void A2DP_InitDefaultCodec(uint8_t* p_codec_info); // enabled. |p_codec_info| contains information about the codec capabilities. // Returns true if the A2DP data packets should contain RTP header, otherwise // false. -bool A2DP_UsesRtpHeader(bool content_protection_enabled, - const uint8_t* p_codec_info); +bool A2DP_UsesRtpHeader(bool content_protection_enabled, const uint8_t* p_codec_info); // Gets the |AVDT_MEDIA_TYPE_*| media type from the codec capability // in |p_codec_info|. @@ -649,15 +629,13 @@ const char* A2DP_CodecName(const uint8_t* p_codec_info); // the same type. // Returns true if the two codecs have the same type, otherwise false. // If the codec type is not recognized, the return value is false. -bool A2DP_CodecTypeEquals(const uint8_t* p_codec_info_a, - const uint8_t* p_codec_info_b); +bool A2DP_CodecTypeEquals(const uint8_t* p_codec_info_a, const uint8_t* p_codec_info_b); // Checks whether two A2DP codecs p_codec_info_a| and |p_codec_info_b| are // exactly the same. // Returns true if the two codecs are exactly the same, otherwise false. // If the codec type is not recognized, the return value is false. -bool A2DP_CodecEquals(const uint8_t* p_codec_info_a, - const uint8_t* p_codec_info_b); +bool A2DP_CodecEquals(const uint8_t* p_codec_info_a, const uint8_t* p_codec_info_b); // Gets the track sample rate value for the A2DP codec. // |p_codec_info| is a pointer to the codec_info to decode. @@ -697,24 +675,21 @@ bool A2DP_GetPacketTimestamp(const uint8_t* p_codec_info, const uint8_t* p_data, // |p_buf| contains the audio data. // |frames_per_packet| is the number of frames in this packet. // Returns true on success, otherwise false. -bool A2DP_BuildCodecHeader(const uint8_t* p_codec_info, BT_HDR* p_buf, - uint16_t frames_per_packet); +bool A2DP_BuildCodecHeader(const uint8_t* p_codec_info, BT_HDR* p_buf, uint16_t frames_per_packet); // Gets the A2DP encoder interface that can be used to encode and prepare // A2DP packets for transmission - see |tA2DP_ENCODER_INTERFACE|. // |p_codec_info| contains the codec information. // Returns the A2DP encoder interface if the |p_codec_info| is valid and // supported, otherwise NULL. -const tA2DP_ENCODER_INTERFACE* A2DP_GetEncoderInterface( - const uint8_t* p_codec_info); +const tA2DP_ENCODER_INTERFACE* A2DP_GetEncoderInterface(const uint8_t* p_codec_info); // Gets the A2DP decoder interface that can be used to decode received A2DP // packets - see |tA2DP_DECODER_INTERFACE|. // |p_codec_info| contains the codec information. // Returns the A2DP decoder interface if the |p_codec_info| is valid and // supported, otherwise NULL. -const tA2DP_DECODER_INTERFACE* A2DP_GetDecoderInterface( - const uint8_t* p_codec_info); +const tA2DP_DECODER_INTERFACE* A2DP_GetDecoderInterface(const uint8_t* p_codec_info); // Adjusts the A2DP codec, based on local support and Bluetooth specification. // |p_codec_info| contains the codec information to adjust. @@ -738,8 +713,7 @@ const char* A2DP_CodecIndexStr(btav_a2dp_codec_index_t codec_index); // configuration entry pointed by |p_cfg|. The selected codec is defined // by |codec_index|. // Returns true on success, otherwise false. -bool A2DP_InitCodecConfig(btav_a2dp_codec_index_t codec_index, - AvdtpSepConfig* p_cfg); +bool A2DP_InitCodecConfig(btav_a2dp_codec_index_t codec_index, AvdtpSepConfig* p_cfg); // Gets the A2DP effective frame size that each encoded media frame should not // exceed this value. @@ -758,27 +732,27 @@ std::string A2DP_CodecInfoString(const uint8_t* p_codec_info); // Use NOLINT to suppress missing parentheses warnings around bitmask. #define DEFINE_ENUM_FLAG_OPERATORS(bitmask) \ extern "C++" { \ - inline constexpr bitmask operator&(bitmask X, bitmask Y) { /* NOLINT */ \ + inline constexpr bitmask operator&(bitmask X, bitmask Y) { /* NOLINT */ \ return static_cast(static_cast(X) & static_cast(Y)); \ } \ - inline constexpr bitmask operator|(bitmask X, bitmask Y) { /* NOLINT */ \ + inline constexpr bitmask operator|(bitmask X, bitmask Y) { /* NOLINT */ \ return static_cast(static_cast(X) | static_cast(Y)); \ } \ - inline constexpr bitmask operator^(bitmask X, bitmask Y) { /* NOLINT */ \ + inline constexpr bitmask operator^(bitmask X, bitmask Y) { /* NOLINT */ \ return static_cast(static_cast(X) ^ static_cast(Y)); \ } \ - inline constexpr bitmask operator~(bitmask X) { /* NOLINT */ \ + inline constexpr bitmask operator~(bitmask X) { /* NOLINT */ \ return static_cast(~static_cast(X)); \ } \ - inline bitmask& operator&=(bitmask& X, bitmask Y) { /* NOLINT */ \ + inline bitmask& operator&=(bitmask& X, bitmask Y) { /* NOLINT */ \ X = X & Y; \ return X; \ } \ - inline bitmask& operator|=(bitmask& X, bitmask Y) { /* NOLINT */ \ + inline bitmask& operator|=(bitmask& X, bitmask Y) { /* NOLINT */ \ X = X | Y; \ return X; \ } \ - inline bitmask& operator^=(bitmask& X, bitmask Y) { /* NOLINT */ \ + inline bitmask& operator^=(bitmask& X, bitmask Y) { /* NOLINT */ \ X = X ^ Y; \ return X; \ } \ diff --git a/system/stack/include/a2dp_ext.h b/system/stack/include/a2dp_ext.h index efff7cdbef2..3c4eddca9a6 100644 --- a/system/stack/include/a2dp_ext.h +++ b/system/stack/include/a2dp_ext.h @@ -28,15 +28,14 @@ /// The codec priority is always the lowest, so that software codecs /// can be picked over offloaded codecs. class A2dpCodecConfigExt : public A2dpCodecConfig { - public: +public: A2dpCodecConfigExt(btav_a2dp_codec_index_t codec_index, bool is_source); bool init() override { return false; } bool useRtpHeaderMarkerBit() const override { return false; } bool setCodecConfig(const uint8_t* p_peer_codec_info, bool is_capability, uint8_t* p_result_codec_config) override; - bool setPeerCodecCapabilities( - const uint8_t* p_peer_codec_capabilities) override; + bool setPeerCodecCapabilities(const uint8_t* p_peer_codec_capabilities) override; const std::vector& getVendorCodecParameters() const { return vendor_specific_parameters_; @@ -53,7 +52,7 @@ class A2dpCodecConfigExt : public A2dpCodecConfig { vendor_specific_parameters_ = vendor_specific_parameters; } - private: +private: [[maybe_unused]] bool is_source_; // True if local is Source std::vector vendor_specific_parameters_; }; @@ -62,5 +61,4 @@ class A2dpCodecConfigExt : public A2dpCodecConfig { // The A2DP source path always sets up the encoder interface, // whether the codec encoding is offloaded or not. // |p_codec_info| contains the codec information. -const tA2DP_ENCODER_INTERFACE* A2DP_GetEncoderInterfaceExt( - const uint8_t* p_codec_info); +const tA2DP_ENCODER_INTERFACE* A2DP_GetEncoderInterfaceExt(const uint8_t* p_codec_info); diff --git a/system/stack/include/a2dp_sbc.h b/system/stack/include/a2dp_sbc.h index 60997c629c6..f85813e8b94 100644 --- a/system/stack/include/a2dp_sbc.h +++ b/system/stack/include/a2dp_sbc.h @@ -31,42 +31,39 @@ #include "stack/include/bt_hdr.h" class A2dpCodecConfigSbcBase : public A2dpCodecConfig { - protected: - A2dpCodecConfigSbcBase(btav_a2dp_codec_index_t codec_index, - const std::string& name, - btav_a2dp_codec_priority_t codec_priority, - bool is_source) +protected: + A2dpCodecConfigSbcBase(btav_a2dp_codec_index_t codec_index, const std::string& name, + btav_a2dp_codec_priority_t codec_priority, bool is_source) : A2dpCodecConfig(codec_index, A2DP_CODEC_ID_SBC, name, codec_priority), is_source_(is_source) {} bool setCodecConfig(const uint8_t* p_peer_codec_info, bool is_capability, uint8_t* p_result_codec_config) override; - bool setPeerCodecCapabilities( - const uint8_t* p_peer_codec_capabilities) override; + bool setPeerCodecCapabilities(const uint8_t* p_peer_codec_capabilities) override; - private: +private: bool is_source_; // True if local is Source }; class A2dpCodecConfigSbcSource : public A2dpCodecConfigSbcBase { - public: +public: A2dpCodecConfigSbcSource(btav_a2dp_codec_priority_t codec_priority); virtual ~A2dpCodecConfigSbcSource(); bool init() override; - private: +private: bool useRtpHeaderMarkerBit() const override; void debug_codec_dump(int fd) override; }; class A2dpCodecConfigSbcSink : public A2dpCodecConfigSbcBase { - public: +public: A2dpCodecConfigSbcSink(btav_a2dp_codec_priority_t codec_priority); virtual ~A2dpCodecConfigSbcSink(); bool init() override; - private: +private: bool useRtpHeaderMarkerBit() const override; }; @@ -120,15 +117,13 @@ const char* A2DP_CodecNameSbc(const uint8_t* p_codec_info); // Checks whether two A2DP SBC codecs |p_codec_info_a| and |p_codec_info_b| // have the same type. // Returns true if the two codecs have the same type, otherwise false. -bool A2DP_CodecTypeEqualsSbc(const uint8_t* p_codec_info_a, - const uint8_t* p_codec_info_b); +bool A2DP_CodecTypeEqualsSbc(const uint8_t* p_codec_info_a, const uint8_t* p_codec_info_b); // Checks whether two A2DP SBC codecs |p_codec_info_a| and |p_codec_info_b| // are exactly the same. // Returns true if the two codecs are exactly the same, otherwise false. // If the codec type is not SBC, the return value is false. -bool A2DP_CodecEqualsSbc(const uint8_t* p_codec_info_a, - const uint8_t* p_codec_info_b); +bool A2DP_CodecEqualsSbc(const uint8_t* p_codec_info_a, const uint8_t* p_codec_info_b); // Gets the track sample rate value for the A2DP SBC codec. // |p_codec_info| is a pointer to the SBC codec_info to decode. @@ -207,8 +202,8 @@ int A2DP_GetSinkTrackChannelTypeSbc(const uint8_t* p_codec_info); // |p_data| contains the audio data. // The timestamp is stored in |p_timestamp|. // Returns true on success, otherwise false. -bool A2DP_GetPacketTimestampSbc(const uint8_t* p_codec_info, - const uint8_t* p_data, uint32_t* p_timestamp); +bool A2DP_GetPacketTimestampSbc(const uint8_t* p_codec_info, const uint8_t* p_data, + uint32_t* p_timestamp); // Builds A2DP SBC codec header for audio data. // |p_codec_info| contains the codec information. @@ -228,16 +223,14 @@ std::string A2DP_CodecInfoStringSbc(const uint8_t* p_codec_info); // |p_codec_info| contains the codec information. // Returns the A2DP SBC encoder interface if the |p_codec_info| is valid and // supported, otherwise NULL. -const tA2DP_ENCODER_INTERFACE* A2DP_GetEncoderInterfaceSbc( - const uint8_t* p_codec_info); +const tA2DP_ENCODER_INTERFACE* A2DP_GetEncoderInterfaceSbc(const uint8_t* p_codec_info); // Gets the A2DP SBC decoder interface that can be used to decode received A2DP // packets - see |tA2DP_DECODER_INTERFACE|. // |p_codec_info| contains the codec information. // Returns the A2DP SBC decoder interface if the |p_codec_info| is valid and // supported, otherwise NULL. -const tA2DP_DECODER_INTERFACE* A2DP_GetDecoderInterfaceSbc( - const uint8_t* p_codec_info); +const tA2DP_DECODER_INTERFACE* A2DP_GetDecoderInterfaceSbc(const uint8_t* p_codec_info); // Adjusts the A2DP SBC codec, based on local support and Bluetooth // specification. diff --git a/system/stack/include/a2dp_sbc_up_sample.h b/system/stack/include/a2dp_sbc_up_sample.h index ac83961f2da..4c9ceb16df2 100644 --- a/system/stack/include/a2dp_sbc_up_sample.h +++ b/system/stack/include/a2dp_sbc_up_sample.h @@ -41,8 +41,7 @@ * Returns none * ******************************************************************************/ -void a2dp_sbc_init_up_sample(uint32_t src_sps, uint32_t dst_sps, uint8_t bits, - uint8_t n_channels); +void a2dp_sbc_init_up_sample(uint32_t src_sps, uint32_t dst_sps, uint8_t bits, uint8_t n_channels); /******************************************************************************* * @@ -70,8 +69,8 @@ void a2dp_sbc_init_up_sample(uint32_t src_sps, uint32_t dst_sps, uint8_t bits, * The number of bytes used in p_src (in *p_ret) * ******************************************************************************/ -int a2dp_sbc_up_sample(void* p_src, void* p_dst, uint32_t src_samples, - uint32_t dst_samples, uint32_t* p_ret); +int a2dp_sbc_up_sample(void* p_src, void* p_dst, uint32_t src_samples, uint32_t dst_samples, + uint32_t* p_ret); /******************************************************************************* * @@ -92,8 +91,8 @@ int a2dp_sbc_up_sample(void* p_src, void* p_dst, uint32_t src_samples, * The number of bytes used in p_src (in *p_ret) * ******************************************************************************/ -int a2dp_sbc_up_sample_16s(void* p_src, void* p_dst, uint32_t src_samples, - uint32_t dst_samples, uint32_t* p_ret); +int a2dp_sbc_up_sample_16s(void* p_src, void* p_dst, uint32_t src_samples, uint32_t dst_samples, + uint32_t* p_ret); /******************************************************************************* * @@ -114,8 +113,8 @@ int a2dp_sbc_up_sample_16s(void* p_src, void* p_dst, uint32_t src_samples, * The number of bytes used in p_src (in *p_ret) * ******************************************************************************/ -int a2dp_sbc_up_sample_16m(void* p_src, void* p_dst, uint32_t src_samples, - uint32_t dst_samples, uint32_t* p_ret); +int a2dp_sbc_up_sample_16m(void* p_src, void* p_dst, uint32_t src_samples, uint32_t dst_samples, + uint32_t* p_ret); /******************************************************************************* * @@ -136,8 +135,8 @@ int a2dp_sbc_up_sample_16m(void* p_src, void* p_dst, uint32_t src_samples, * The number of bytes used in p_src (in *p_ret) * ******************************************************************************/ -int a2dp_sbc_up_sample_8s(void* p_src, void* p_dst, uint32_t src_samples, - uint32_t dst_samples, uint32_t* p_ret); +int a2dp_sbc_up_sample_8s(void* p_src, void* p_dst, uint32_t src_samples, uint32_t dst_samples, + uint32_t* p_ret); /******************************************************************************* * @@ -157,7 +156,7 @@ int a2dp_sbc_up_sample_8s(void* p_src, void* p_dst, uint32_t src_samples, * The number of bytes used in p_src (in *p_ret) * ******************************************************************************/ -int a2dp_sbc_up_sample_8m(void* p_src, void* p_dst, uint32_t src_samples, - uint32_t dst_samples, uint32_t* p_ret); +int a2dp_sbc_up_sample_8m(void* p_src, void* p_dst, uint32_t src_samples, uint32_t dst_samples, + uint32_t* p_ret); #endif // A2DP_SBC_UP_SAMPLE_H diff --git a/system/stack/include/a2dp_vendor.h b/system/stack/include/a2dp_vendor.h index b8bf9de3760..1b8677ed4d5 100644 --- a/system/stack/include/a2dp_vendor.h +++ b/system/stack/include/a2dp_vendor.h @@ -104,8 +104,7 @@ uint16_t A2DP_VendorCodecGetCodecId(const uint8_t* p_codec_info); // enabled. |p_codec_info| contains information about the codec capabilities. // Returns true if the A2DP vendor-specific data packets should contain RTP // header, otherwise false. -bool A2DP_VendorUsesRtpHeader(bool content_protection_enabled, - const uint8_t* p_codec_info); +bool A2DP_VendorUsesRtpHeader(bool content_protection_enabled, const uint8_t* p_codec_info); // Gets the A2DP vendor-specific codec name for a given |p_codec_info|. const char* A2DP_VendorCodecName(const uint8_t* p_codec_info); @@ -114,15 +113,13 @@ const char* A2DP_VendorCodecName(const uint8_t* p_codec_info); // |p_codec_info_b| have the same type. // Returns true if the two codecs have the same type, otherwise false. // If the codec type is not recognized, the return value is false. -bool A2DP_VendorCodecTypeEquals(const uint8_t* p_codec_info_a, - const uint8_t* p_codec_info_b); +bool A2DP_VendorCodecTypeEquals(const uint8_t* p_codec_info_a, const uint8_t* p_codec_info_b); // Checks whether two A2DP vendor-specific codecs |p_codec_info_a| and // |p_codec_info_b| are exactly the same. // Returns true if the two codecs are exactly the same, otherwise false. // If the codec type is not recognized, the return value is false. -bool A2DP_VendorCodecEquals(const uint8_t* p_codec_info_a, - const uint8_t* p_codec_info_b); +bool A2DP_VendorCodecEquals(const uint8_t* p_codec_info_a, const uint8_t* p_codec_info_b); // Gets the track sample rate value for the A2DP vendor-specific codec. // |p_codec_info| is a pointer to the vendor-specific codec_info to decode. @@ -160,8 +157,7 @@ int A2DP_VendorGetSinkTrackChannelType(const uint8_t* p_codec_info); // |p_data| contains the audio data. // The timestamp is stored in |p_timestamp|. // Returns true on success, otherwise false. -bool A2DP_VendorGetPacketTimestamp(const uint8_t* p_codec_info, - const uint8_t* p_data, +bool A2DP_VendorGetPacketTimestamp(const uint8_t* p_codec_info, const uint8_t* p_data, uint32_t* p_timestamp); // Builds A2DP vendor-specific codec header for audio data. @@ -177,16 +173,14 @@ bool A2DP_VendorBuildCodecHeader(const uint8_t* p_codec_info, BT_HDR* p_buf, // |p_codec_info| contains the codec information. // Returns the A2DP vendor encoder interface if the |p_codec_info| is valid and // supported, otherwise NULL. -const tA2DP_ENCODER_INTERFACE* A2DP_VendorGetEncoderInterface( - const uint8_t* p_codec_info); +const tA2DP_ENCODER_INTERFACE* A2DP_VendorGetEncoderInterface(const uint8_t* p_codec_info); // Gets the current A2DP vendor decoder interface that can be used to decode // received A2DP packets - see |tA2DP_DECODER_INTERFACE|. // |p_codec_info| contains the codec information. // Returns the A2DP vendor decoder interface if the |p_codec_info| is valid and // supported, otherwise NULL. -const tA2DP_DECODER_INTERFACE* A2DP_VendorGetDecoderInterface( - const uint8_t* p_codec_info); +const tA2DP_DECODER_INTERFACE* A2DP_VendorGetDecoderInterface(const uint8_t* p_codec_info); // Adjusts the A2DP vendor-specific codec, based on local support and Bluetooth // specification. @@ -197,8 +191,7 @@ bool A2DP_VendorAdjustCodec(uint8_t* p_codec_info); // Gets the A2DP vendor Source codec index for a given |p_codec_info|. // Returns the corresponding |btav_a2dp_codec_index_t| on success, // otherwise |BTAV_A2DP_CODEC_INDEX_MAX|. -btav_a2dp_codec_index_t A2DP_VendorSourceCodecIndex( - const uint8_t* p_codec_info); +btav_a2dp_codec_index_t A2DP_VendorSourceCodecIndex(const uint8_t* p_codec_info); // Gets the A2DP vendor Sink codec index for a given |p_codec_info|. // Returns the corresponding |btav_a2dp_codec_index_t| on success, @@ -212,8 +205,7 @@ const char* A2DP_VendorCodecIndexStr(btav_a2dp_codec_index_t codec_index); // configuration entry pointed by |p_cfg|. The selected codec is defined by // |codec_index|. // Returns true on success, otherwise false. -bool A2DP_VendorInitCodecConfig(btav_a2dp_codec_index_t codec_index, - AvdtpSepConfig* p_cfg); +bool A2DP_VendorInitCodecConfig(btav_a2dp_codec_index_t codec_index, AvdtpSepConfig* p_cfg); // Decodes A2DP vendor codec info into a human readable string. // |p_codec_info| is a pointer to the codec_info to decode. diff --git a/system/stack/include/a2dp_vendor_aptx.h b/system/stack/include/a2dp_vendor_aptx.h index 4dc34e10912..b6df34f70bf 100644 --- a/system/stack/include/a2dp_vendor_aptx.h +++ b/system/stack/include/a2dp_vendor_aptx.h @@ -31,17 +31,16 @@ #include "stack/include/bt_hdr.h" class A2dpCodecConfigAptx : public A2dpCodecConfig { - public: +public: A2dpCodecConfigAptx(btav_a2dp_codec_priority_t codec_priority); virtual ~A2dpCodecConfigAptx(); bool init() override; bool setCodecConfig(const uint8_t* p_peer_codec_info, bool is_capability, uint8_t* p_result_codec_config) override; - bool setPeerCodecCapabilities( - const uint8_t* p_peer_codec_capabilities) override; + bool setPeerCodecCapabilities(const uint8_t* p_peer_codec_capabilities) override; - private: +private: bool useRtpHeaderMarkerBit() const override; void debug_codec_dump(int fd) override; }; @@ -65,8 +64,7 @@ bool A2DP_IsVendorPeerSinkCodecValidAptx(const uint8_t* p_codec_info); // enabled. |p_codec_info| contains information about the codec capabilities. // Returns true if the A2DP data packets should contain RTP header, otherwise // false. -bool A2DP_VendorUsesRtpHeaderAptx(bool content_protection_enabled, - const uint8_t* p_codec_info); +bool A2DP_VendorUsesRtpHeaderAptx(bool content_protection_enabled, const uint8_t* p_codec_info); // Gets the A2DP aptX codec name for a given |p_codec_info|. const char* A2DP_VendorCodecNameAptx(const uint8_t* p_codec_info); @@ -74,15 +72,13 @@ const char* A2DP_VendorCodecNameAptx(const uint8_t* p_codec_info); // Checks whether two A2DP aptX codecs |p_codec_info_a| and |p_codec_info_b| // have the same type. // Returns true if the two codecs have the same type, otherwise false. -bool A2DP_VendorCodecTypeEqualsAptx(const uint8_t* p_codec_info_a, - const uint8_t* p_codec_info_b); +bool A2DP_VendorCodecTypeEqualsAptx(const uint8_t* p_codec_info_a, const uint8_t* p_codec_info_b); // Checks whether two A2DP aptX codecs |p_codec_info_a| and |p_codec_info_b| // are exactly the same. // Returns true if the two codecs are exactly the same, otherwise false. // If the codec type is not aptX, the return value is false. -bool A2DP_VendorCodecEqualsAptx(const uint8_t* p_codec_info_a, - const uint8_t* p_codec_info_b); +bool A2DP_VendorCodecEqualsAptx(const uint8_t* p_codec_info_a, const uint8_t* p_codec_info_b); // Gets the track sample rate value for the A2DP aptX codec. // |p_codec_info| is a pointer to the aptX codec_info to decode. @@ -113,8 +109,7 @@ int A2DP_VendorGetTrackChannelCountAptx(const uint8_t* p_codec_info); // |p_data| contains the audio data. // The timestamp is stored in |p_timestamp|. // Returns true on success, otherwise false. -bool A2DP_VendorGetPacketTimestampAptx(const uint8_t* p_codec_info, - const uint8_t* p_data, +bool A2DP_VendorGetPacketTimestampAptx(const uint8_t* p_codec_info, const uint8_t* p_data, uint32_t* p_timestamp); // Builds A2DP aptX codec header for audio data. @@ -135,8 +130,7 @@ std::string A2DP_VendorCodecInfoStringAptx(const uint8_t* p_codec_info); // |p_codec_info| contains the codec information. // Returns the A2DP aptX encoder interface if the |p_codec_info| is valid and // supported, otherwise NULL. -const tA2DP_ENCODER_INTERFACE* A2DP_VendorGetEncoderInterfaceAptx( - const uint8_t* p_codec_info); +const tA2DP_ENCODER_INTERFACE* A2DP_VendorGetEncoderInterfaceAptx(const uint8_t* p_codec_info); // Adjusts the A2DP aptX codec, based on local support and Bluetooth // specification. @@ -147,8 +141,7 @@ bool A2DP_VendorAdjustCodecAptx(uint8_t* p_codec_info); // Gets the A2DP aptX Source codec index for a given |p_codec_info|. // Returns the corresponding |btav_a2dp_codec_index_t| on success, // otherwise |BTAV_A2DP_CODEC_INDEX_MAX|. -btav_a2dp_codec_index_t A2DP_VendorSourceCodecIndexAptx( - const uint8_t* p_codec_info); +btav_a2dp_codec_index_t A2DP_VendorSourceCodecIndexAptx(const uint8_t* p_codec_info); // Gets the A2DP aptX Source codec name. const char* A2DP_VendorCodecIndexStrAptx(void); diff --git a/system/stack/include/a2dp_vendor_aptx_encoder.h b/system/stack/include/a2dp_vendor_aptx_encoder.h index 499597337dd..c5479265883 100644 --- a/system/stack/include/a2dp_vendor_aptx_encoder.h +++ b/system/stack/include/a2dp_vendor_aptx_encoder.h @@ -39,11 +39,10 @@ void A2DP_VendorUnloadEncoderAptx(void); // The current A2DP codec config is in |a2dp_codec_config|. // |read_callback| is the callback for reading the input audio data. // |enqueue_callback| is the callback for enqueueing the encoded audio data. -void a2dp_vendor_aptx_encoder_init( - const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params, - A2dpCodecConfig* a2dp_codec_config, - a2dp_source_read_callback_t read_callback, - a2dp_source_enqueue_callback_t enqueue_callback); +void a2dp_vendor_aptx_encoder_init(const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params, + A2dpCodecConfig* a2dp_codec_config, + a2dp_source_read_callback_t read_callback, + a2dp_source_enqueue_callback_t enqueue_callback); // Cleanup the A2DP aptX encoder. void a2dp_vendor_aptx_encoder_cleanup(void); @@ -66,8 +65,7 @@ void a2dp_vendor_aptx_send_frames(uint64_t timestamp_us); typedef int (*tAPTX_ENCODER_INIT)(void* state, short endian); -typedef int (*tAPTX_ENCODER_ENCODE_STEREO)(void* state, void* pcmL, void* pcmR, - void* buffer); +typedef int (*tAPTX_ENCODER_ENCODE_STEREO)(void* state, void* pcmL, void* pcmR, void* buffer); typedef int (*tAPTX_ENCODER_SIZEOF_PARAMS)(void); diff --git a/system/stack/include/a2dp_vendor_aptx_hd.h b/system/stack/include/a2dp_vendor_aptx_hd.h index d8363a77685..80c7365a55d 100644 --- a/system/stack/include/a2dp_vendor_aptx_hd.h +++ b/system/stack/include/a2dp_vendor_aptx_hd.h @@ -31,17 +31,16 @@ #include "stack/include/bt_hdr.h" class A2dpCodecConfigAptxHd : public A2dpCodecConfig { - public: +public: A2dpCodecConfigAptxHd(btav_a2dp_codec_priority_t codec_priority); virtual ~A2dpCodecConfigAptxHd(); bool init() override; bool setCodecConfig(const uint8_t* p_peer_codec_info, bool is_capability, uint8_t* p_result_codec_config) override; - bool setPeerCodecCapabilities( - const uint8_t* p_peer_codec_capabilities) override; + bool setPeerCodecCapabilities(const uint8_t* p_peer_codec_capabilities) override; - private: +private: bool useRtpHeaderMarkerBit() const override; void debug_codec_dump(int fd) override; }; @@ -65,8 +64,7 @@ bool A2DP_IsVendorPeerSinkCodecValidAptxHd(const uint8_t* p_codec_info); // enabled. |p_codec_info| contains information about the codec capabilities. // Returns true if the A2DP data packets should contain RTP header, otherwise // false. -bool A2DP_VendorUsesRtpHeaderAptxHd(bool content_protection_enabled, - const uint8_t* p_codec_info); +bool A2DP_VendorUsesRtpHeaderAptxHd(bool content_protection_enabled, const uint8_t* p_codec_info); // Gets the A2DP aptX-HD codec name for a given |p_codec_info|. const char* A2DP_VendorCodecNameAptxHd(const uint8_t* p_codec_info); @@ -74,15 +72,13 @@ const char* A2DP_VendorCodecNameAptxHd(const uint8_t* p_codec_info); // Checks whether two A2DP aptX-HD codecs |p_codec_info_a| and |p_codec_info_b| // have the same type. // Returns true if the two codecs have the same type, otherwise false. -bool A2DP_VendorCodecTypeEqualsAptxHd(const uint8_t* p_codec_info_a, - const uint8_t* p_codec_info_b); +bool A2DP_VendorCodecTypeEqualsAptxHd(const uint8_t* p_codec_info_a, const uint8_t* p_codec_info_b); // Checks whether two A2DP aptX-HD codecs |p_codec_info_a| and |p_codec_info_b| // are exactly the same. // Returns true if the two codecs are exactly the same, otherwise false. // If the codec type is not aptX-HD, the return value is false. -bool A2DP_VendorCodecEqualsAptxHd(const uint8_t* p_codec_info_a, - const uint8_t* p_codec_info_b); +bool A2DP_VendorCodecEqualsAptxHd(const uint8_t* p_codec_info_a, const uint8_t* p_codec_info_b); // Gets the track sample rate value for the A2DP aptX-HD codec. // |p_codec_info| is a pointer to the aptX-HD codec_info to decode. @@ -113,8 +109,7 @@ int A2DP_VendorGetTrackChannelCountAptxHd(const uint8_t* p_codec_info); // |p_data| contains the audio data. // The timestamp is stored in |p_timestamp|. // Returns true on success, otherwise false. -bool A2DP_VendorGetPacketTimestampAptxHd(const uint8_t* p_codec_info, - const uint8_t* p_data, +bool A2DP_VendorGetPacketTimestampAptxHd(const uint8_t* p_codec_info, const uint8_t* p_data, uint32_t* p_timestamp); // Builds A2DP aptX-HD codec header for audio data. @@ -122,8 +117,7 @@ bool A2DP_VendorGetPacketTimestampAptxHd(const uint8_t* p_codec_info, // |p_buf| contains the audio data. // |frames_per_packet| is the number of frames in this packet. // Returns true on success, otherwise false. -bool A2DP_VendorBuildCodecHeaderAptxHd(const uint8_t* p_codec_info, - BT_HDR* p_buf, +bool A2DP_VendorBuildCodecHeaderAptxHd(const uint8_t* p_codec_info, BT_HDR* p_buf, uint16_t frames_per_packet); // Decodes A2DP aptX-HD codec info into a human readable string. @@ -136,8 +130,7 @@ std::string A2DP_VendorCodecInfoStringAptxHd(const uint8_t* p_codec_info); // |p_codec_info| contains the codec information. // Returns the A2DP aptX-HD encoder interface if the |p_codec_info| is valid // and supported, otherwise NULL. -const tA2DP_ENCODER_INTERFACE* A2DP_VendorGetEncoderInterfaceAptxHd( - const uint8_t* p_codec_info); +const tA2DP_ENCODER_INTERFACE* A2DP_VendorGetEncoderInterfaceAptxHd(const uint8_t* p_codec_info); // Adjusts the A2DP aptX-HD codec, based on local support and Bluetooth // specification. @@ -148,8 +141,7 @@ bool A2DP_VendorAdjustCodecAptxHd(uint8_t* p_codec_info); // Gets the A2DP aptX-HD Source codec index for a given |p_codec_info|. // Returns the corresponding |btav_a2dp_codec_index_t| on success, // otherwise |BTAV_A2DP_CODEC_INDEX_MAX|. -btav_a2dp_codec_index_t A2DP_VendorSourceCodecIndexAptxHd( - const uint8_t* p_codec_info); +btav_a2dp_codec_index_t A2DP_VendorSourceCodecIndexAptxHd(const uint8_t* p_codec_info); // Gets the A2DP aptX-HD Source codec name. const char* A2DP_VendorCodecIndexStrAptxHd(void); diff --git a/system/stack/include/a2dp_vendor_aptx_hd_encoder.h b/system/stack/include/a2dp_vendor_aptx_hd_encoder.h index 5258aa39a75..54b86ad5815 100644 --- a/system/stack/include/a2dp_vendor_aptx_hd_encoder.h +++ b/system/stack/include/a2dp_vendor_aptx_hd_encoder.h @@ -36,11 +36,10 @@ void A2DP_VendorUnloadEncoderAptxHd(void); // The current A2DP codec config is in |a2dp_codec_config|. // |read_callback| is the callback for reading the input audio data. // |enqueue_callback| is the callback for enqueueing the encoded audio data. -void a2dp_vendor_aptx_hd_encoder_init( - const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params, - A2dpCodecConfig* a2dp_codec_config, - a2dp_source_read_callback_t read_callback, - a2dp_source_enqueue_callback_t enqueue_callback); +void a2dp_vendor_aptx_hd_encoder_init(const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params, + A2dpCodecConfig* a2dp_codec_config, + a2dp_source_read_callback_t read_callback, + a2dp_source_enqueue_callback_t enqueue_callback); // Cleanup the A2DP aptX-HD encoder. void a2dp_vendor_aptx_hd_encoder_cleanup(void); @@ -63,8 +62,7 @@ void a2dp_vendor_aptx_hd_send_frames(uint64_t timestamp_us); typedef int (*tAPTX_HD_ENCODER_INIT)(void* state, short endian); -typedef int (*tAPTX_HD_ENCODER_ENCODE_STEREO)(void* state, void* pcmL, - void* pcmR, void* buffer); +typedef int (*tAPTX_HD_ENCODER_ENCODE_STEREO)(void* state, void* pcmL, void* pcmR, void* buffer); typedef int (*tAPTX_HD_ENCODER_SIZEOF_PARAMS)(void); diff --git a/system/stack/include/a2dp_vendor_ldac.h b/system/stack/include/a2dp_vendor_ldac.h index b28faa90aba..5c36ec2c551 100644 --- a/system/stack/include/a2dp_vendor_ldac.h +++ b/system/stack/include/a2dp_vendor_ldac.h @@ -31,42 +31,39 @@ #include "stack/include/bt_hdr.h" class A2dpCodecConfigLdacBase : public A2dpCodecConfig { - protected: - A2dpCodecConfigLdacBase(btav_a2dp_codec_index_t codec_index, - const std::string& name, - btav_a2dp_codec_priority_t codec_priority, - bool is_source) +protected: + A2dpCodecConfigLdacBase(btav_a2dp_codec_index_t codec_index, const std::string& name, + btav_a2dp_codec_priority_t codec_priority, bool is_source) : A2dpCodecConfig(codec_index, A2DP_CODEC_ID_LDAC, name, codec_priority), is_source_(is_source) {} bool setCodecConfig(const uint8_t* p_peer_codec_info, bool is_capability, uint8_t* p_result_codec_config) override; - bool setPeerCodecCapabilities( - const uint8_t* p_peer_codec_capabilities) override; + bool setPeerCodecCapabilities(const uint8_t* p_peer_codec_capabilities) override; - private: +private: [[maybe_unused]] bool is_source_; // True if local is Source }; class A2dpCodecConfigLdacSource : public A2dpCodecConfigLdacBase { - public: +public: A2dpCodecConfigLdacSource(btav_a2dp_codec_priority_t codec_priority); virtual ~A2dpCodecConfigLdacSource(); bool init() override; - private: +private: bool useRtpHeaderMarkerBit() const override; void debug_codec_dump(int fd) override; }; class A2dpCodecConfigLdacSink : public A2dpCodecConfigLdacBase { - public: +public: A2dpCodecConfigLdacSink(btav_a2dp_codec_priority_t codec_priority); virtual ~A2dpCodecConfigLdacSink(); bool init() override; - private: +private: bool useRtpHeaderMarkerBit() const override; }; @@ -116,8 +113,7 @@ bool A2DP_IsPeerSourceCodecSupportedLdac(const uint8_t* p_codec_info); // enabled. |p_codec_info| contains information about the codec capabilities. // Returns true if the A2DP data packets should contain RTP header, otherwise // false. -bool A2DP_VendorUsesRtpHeaderLdac(bool content_protection_enabled, - const uint8_t* p_codec_info); +bool A2DP_VendorUsesRtpHeaderLdac(bool content_protection_enabled, const uint8_t* p_codec_info); // Gets the A2DP LDAC codec name for a given |p_codec_info|. const char* A2DP_VendorCodecNameLdac(const uint8_t* p_codec_info); @@ -125,15 +121,13 @@ const char* A2DP_VendorCodecNameLdac(const uint8_t* p_codec_info); // Checks whether two A2DP LDAC codecs |p_codec_info_a| and |p_codec_info_b| // have the same type. // Returns true if the two codecs have the same type, otherwise false. -bool A2DP_VendorCodecTypeEqualsLdac(const uint8_t* p_codec_info_a, - const uint8_t* p_codec_info_b); +bool A2DP_VendorCodecTypeEqualsLdac(const uint8_t* p_codec_info_a, const uint8_t* p_codec_info_b); // Checks whether two A2DP LDAC codecs |p_codec_info_a| and |p_codec_info_b| // are exactly the same. // Returns true if the two codecs are exactly the same, otherwise false. // If the codec type is not LDAC, the return value is false. -bool A2DP_VendorCodecEqualsLdac(const uint8_t* p_codec_info_a, - const uint8_t* p_codec_info_b); +bool A2DP_VendorCodecEqualsLdac(const uint8_t* p_codec_info_a, const uint8_t* p_codec_info_b); // Gets the track sample rate value for the A2DP LDAC codec. // |p_codec_info| is a pointer to the LDAC codec_info to decode. @@ -178,8 +172,7 @@ int A2DP_VendorGetChannelModeCodeLdac(const uint8_t* p_codec_info); // |p_data| contains the audio data. // The timestamp is stored in |p_timestamp|. // Returns true on success, otherwise false. -bool A2DP_VendorGetPacketTimestampLdac(const uint8_t* p_codec_info, - const uint8_t* p_data, +bool A2DP_VendorGetPacketTimestampLdac(const uint8_t* p_codec_info, const uint8_t* p_data, uint32_t* p_timestamp); // Builds A2DP LDAC codec header for audio data. @@ -200,16 +193,14 @@ std::string A2DP_VendorCodecInfoStringLdac(const uint8_t* p_codec_info); // |p_codec_info| contains the codec information. // Returns the A2DP LDAC encoder interface if the |p_codec_info| is valid and // supported, otherwise NULL. -const tA2DP_ENCODER_INTERFACE* A2DP_VendorGetEncoderInterfaceLdac( - const uint8_t* p_codec_info); +const tA2DP_ENCODER_INTERFACE* A2DP_VendorGetEncoderInterfaceLdac(const uint8_t* p_codec_info); // Gets the current A2DP LDAC decoder interface that can be used to decode // received A2DP packets - see |tA2DP_DECODER_INTERFACE|. // |p_codec_info| contains the codec information. // Returns the A2DP LDAC decoder interface if the |p_codec_info| is valid and // supported, otherwise NULL. -const tA2DP_DECODER_INTERFACE* A2DP_VendorGetDecoderInterfaceLdac( - const uint8_t* p_codec_info); +const tA2DP_DECODER_INTERFACE* A2DP_VendorGetDecoderInterfaceLdac(const uint8_t* p_codec_info); // Adjusts the A2DP LDAC codec, based on local support and Bluetooth // specification. @@ -220,14 +211,12 @@ bool A2DP_VendorAdjustCodecLdac(uint8_t* p_codec_info); // Gets the A2DP LDAC Source codec index for a given |p_codec_info|. // Returns the corresponding |btav_a2dp_codec_index_t| on success, // otherwise |BTAV_A2DP_CODEC_INDEX_MAX|. -btav_a2dp_codec_index_t A2DP_VendorSourceCodecIndexLdac( - const uint8_t* p_codec_info); +btav_a2dp_codec_index_t A2DP_VendorSourceCodecIndexLdac(const uint8_t* p_codec_info); // Gets the A2DP LDAC Sink codec index for a given |p_codec_info|. // Returns the corresponding |btav_a2dp_codec_index_t| on success, // otherwise |BTAV_A2DP_CODEC_INDEX_MAX|. -btav_a2dp_codec_index_t A2DP_VendorSinkCodecIndexLdac( - const uint8_t* p_codec_info); +btav_a2dp_codec_index_t A2DP_VendorSinkCodecIndexLdac(const uint8_t* p_codec_info); // Gets the A2DP LDAC Source codec name. const char* A2DP_VendorCodecIndexStrLdac(void); diff --git a/system/stack/include/a2dp_vendor_ldac_encoder.h b/system/stack/include/a2dp_vendor_ldac_encoder.h index 2a5a81fc586..4d0bff6cc76 100644 --- a/system/stack/include/a2dp_vendor_ldac_encoder.h +++ b/system/stack/include/a2dp_vendor_ldac_encoder.h @@ -38,11 +38,10 @@ void A2DP_VendorUnloadEncoderLdac(void); // The current A2DP codec config is in |a2dp_codec_config|. // |read_callback| is the callback for reading the input audio data. // |enqueue_callback| is the callback for enqueueing the encoded audio data. -void a2dp_vendor_ldac_encoder_init( - const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params, - A2dpCodecConfig* a2dp_codec_config, - a2dp_source_read_callback_t read_callback, - a2dp_source_enqueue_callback_t enqueue_callback); +void a2dp_vendor_ldac_encoder_init(const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params, + A2dpCodecConfig* a2dp_codec_config, + a2dp_source_read_callback_t read_callback, + a2dp_source_enqueue_callback_t enqueue_callback); // Cleanup the A2DP LDAC encoder. void a2dp_vendor_ldac_encoder_cleanup(void); diff --git a/system/stack/include/a2dp_vendor_opus.h b/system/stack/include/a2dp_vendor_opus.h index 897c593ceda..9a32187a41b 100644 --- a/system/stack/include/a2dp_vendor_opus.h +++ b/system/stack/include/a2dp_vendor_opus.h @@ -26,51 +26,48 @@ #include "avdt_api.h" class A2dpCodecConfigOpusBase : public A2dpCodecConfig { - protected: - A2dpCodecConfigOpusBase(btav_a2dp_codec_index_t codec_index, - const std::string& name, - btav_a2dp_codec_priority_t codec_priority, - bool is_source) +protected: + A2dpCodecConfigOpusBase(btav_a2dp_codec_index_t codec_index, const std::string& name, + btav_a2dp_codec_priority_t codec_priority, bool is_source) : A2dpCodecConfig(codec_index, A2DP_CODEC_ID_OPUS, name, codec_priority), is_source_(is_source) {} bool setCodecConfig(const uint8_t* p_peer_codec_info, bool is_capability, uint8_t* p_result_codec_config) override; - bool setPeerCodecCapabilities( - const uint8_t* p_peer_codec_capabilities) override; + bool setPeerCodecCapabilities(const uint8_t* p_peer_codec_capabilities) override; - private: +private: [[maybe_unused]] bool is_source_; // True if local is Source }; class A2dpCodecConfigOpusSource : public A2dpCodecConfigOpusBase { - public: +public: A2dpCodecConfigOpusSource(btav_a2dp_codec_priority_t codec_priority); virtual ~A2dpCodecConfigOpusSource(); bool init() override; uint64_t encoderIntervalMs() const; - private: +private: bool useRtpHeaderMarkerBit() const override; - bool updateEncoderUserConfig( - const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params, - bool* p_restart_input, bool* p_restart_output, bool* p_config_updated); + bool updateEncoderUserConfig(const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params, + bool* p_restart_input, bool* p_restart_output, + bool* p_config_updated); void debug_codec_dump(int fd) override; }; class A2dpCodecConfigOpusSink : public A2dpCodecConfigOpusBase { - public: +public: A2dpCodecConfigOpusSink(btav_a2dp_codec_priority_t codec_priority); virtual ~A2dpCodecConfigOpusSink(); bool init() override; uint64_t encoderIntervalMs() const; - private: +private: bool useRtpHeaderMarkerBit() const override; - bool updateEncoderUserConfig( - const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params, - bool* p_restart_input, bool* p_restart_output, bool* p_config_updated); + bool updateEncoderUserConfig(const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params, + bool* p_restart_input, bool* p_restart_output, + bool* p_config_updated); }; // Checks whether the codec capabilities contain a valid A2DP Opus Source @@ -119,8 +116,7 @@ bool A2DP_IsPeerSourceCodecSupportedOpus(const uint8_t* p_codec_info); // enabled. |p_codec_info| contains information about the codec capabilities. // Returns true if the A2DP data packets should contain RTP header, otherwise // false. -bool A2DP_VendorUsesRtpHeaderOpus(bool content_protection_enabled, - const uint8_t* p_codec_info); +bool A2DP_VendorUsesRtpHeaderOpus(bool content_protection_enabled, const uint8_t* p_codec_info); // Gets the A2DP Opus codec name for a given |p_codec_info|. const char* A2DP_VendorCodecNameOpus(const uint8_t* p_codec_info); @@ -128,15 +124,13 @@ const char* A2DP_VendorCodecNameOpus(const uint8_t* p_codec_info); // Checks whether two A2DP Opus codecs |p_codec_info_a| and |p_codec_info_b| // have the same type. // Returns true if the two codecs have the same type, otherwise false. -bool A2DP_VendorCodecTypeEqualsOpus(const uint8_t* p_codec_info_a, - const uint8_t* p_codec_info_b); +bool A2DP_VendorCodecTypeEqualsOpus(const uint8_t* p_codec_info_a, const uint8_t* p_codec_info_b); // Checks whether two A2DP Opus codecs |p_codec_info_a| and |p_codec_info_b| // are exactly the same. // Returns true if the two codecs are exactly the same, otherwise false. // If the codec type is not Opus, the return value is false. -bool A2DP_VendorCodecEqualsOpus(const uint8_t* p_codec_info_a, - const uint8_t* p_codec_info_b); +bool A2DP_VendorCodecEqualsOpus(const uint8_t* p_codec_info_a, const uint8_t* p_codec_info_b); // Gets the track sample rate value for the A2DP Opus codec. // |p_codec_info| is a pointer to the Opus codec_info to decode. @@ -187,8 +181,7 @@ int A2DP_VendorGetFrameSizeOpus(const uint8_t* p_codec_info); // |p_data| contains the audio data. // The timestamp is stored in |p_timestamp|. // Returns true on success, otherwise false. -bool A2DP_VendorGetPacketTimestampOpus(const uint8_t* p_codec_info, - const uint8_t* p_data, +bool A2DP_VendorGetPacketTimestampOpus(const uint8_t* p_codec_info, const uint8_t* p_data, uint32_t* p_timestamp); // Builds A2DP Opus codec header for audio data. @@ -209,16 +202,14 @@ std::string A2DP_VendorCodecInfoStringOpus(const uint8_t* p_codec_info); // |p_codec_info| contains the codec information. // Returns the A2DP Opus encoder interface if the |p_codec_info| is valid and // supported, otherwise NULL. -const tA2DP_ENCODER_INTERFACE* A2DP_VendorGetEncoderInterfaceOpus( - const uint8_t* p_codec_info); +const tA2DP_ENCODER_INTERFACE* A2DP_VendorGetEncoderInterfaceOpus(const uint8_t* p_codec_info); // Gets the current A2DP Opus decoder interface that can be used to decode // received A2DP packets - see |tA2DP_DECODER_INTERFACE|. // |p_codec_info| contains the codec information. // Returns the A2DP Opus decoder interface if the |p_codec_info| is valid and // supported, otherwise NULL. -const tA2DP_DECODER_INTERFACE* A2DP_VendorGetDecoderInterfaceOpus( - const uint8_t* p_codec_info); +const tA2DP_DECODER_INTERFACE* A2DP_VendorGetDecoderInterfaceOpus(const uint8_t* p_codec_info); // Adjusts the A2DP Opus codec, based on local support and Bluetooth // specification. @@ -229,14 +220,12 @@ bool A2DP_VendorAdjustCodecOpus(uint8_t* p_codec_info); // Gets the A2DP Opus Source codec index for a given |p_codec_info|. // Returns the corresponding |btav_a2dp_codec_index_t| on success, // otherwise |BTAV_A2DP_CODEC_INDEX_MAX|. -btav_a2dp_codec_index_t A2DP_VendorSourceCodecIndexOpus( - const uint8_t* p_codec_info); +btav_a2dp_codec_index_t A2DP_VendorSourceCodecIndexOpus(const uint8_t* p_codec_info); // Gets the A2DP Opus Sink codec index for a given |p_codec_info|. // Returns the corresponding |btav_a2dp_codec_index_t| on success, // otherwise |BTAV_A2DP_CODEC_INDEX_MAX|. -btav_a2dp_codec_index_t A2DP_VendorSinkCodecIndexOpus( - const uint8_t* p_codec_info); +btav_a2dp_codec_index_t A2DP_VendorSinkCodecIndexOpus(const uint8_t* p_codec_info); // Gets the A2DP Opus Source codec name. const char* A2DP_VendorCodecIndexStrOpus(void); diff --git a/system/stack/include/a2dp_vendor_opus_encoder.h b/system/stack/include/a2dp_vendor_opus_encoder.h index 0f88265f1f9..44197c0e105 100644 --- a/system/stack/include/a2dp_vendor_opus_encoder.h +++ b/system/stack/include/a2dp_vendor_opus_encoder.h @@ -28,11 +28,10 @@ // The current A2DP codec config is in |a2dp_codec_config|. // |read_callback| is the callback for reading the input audio data. // |enqueue_callback| is the callback for enqueueing the encoded audio data. -void a2dp_vendor_opus_encoder_init( - const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params, - A2dpCodecConfig* a2dp_codec_config, - a2dp_source_read_callback_t read_callback, - a2dp_source_enqueue_callback_t enqueue_callback); +void a2dp_vendor_opus_encoder_init(const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params, + A2dpCodecConfig* a2dp_codec_config, + a2dp_source_read_callback_t read_callback, + a2dp_source_enqueue_callback_t enqueue_callback); // Cleanup the A2DP Opus encoder. void a2dp_vendor_opus_encoder_cleanup(void); diff --git a/system/stack/include/acl_api.h b/system/stack/include/acl_api.h index f891f9623ff..850c396647f 100644 --- a/system/stack/include/acl_api.h +++ b/system/stack/include/acl_api.h @@ -54,8 +54,7 @@ void BTM_acl_after_controller_started(); * Returns BTM_CMD_STARTED if successfully initiated, otherwise error * ******************************************************************************/ -tBTM_STATUS BTM_SetLinkSuperTout(const RawAddress& remote_bda, - uint16_t timeout); +tBTM_STATUS BTM_SetLinkSuperTout(const RawAddress& remote_bda, uint16_t timeout); /******************************************************************************* * * Function BTM_GetLinkSuperTout @@ -65,8 +64,7 @@ tBTM_STATUS BTM_SetLinkSuperTout(const RawAddress& remote_bda, * Returns status of the operation * ******************************************************************************/ -tBTM_STATUS BTM_GetLinkSuperTout(const RawAddress& remote_bda, - uint16_t* p_timeout); +tBTM_STATUS BTM_GetLinkSuperTout(const RawAddress& remote_bda, uint16_t* p_timeout); /******************************************************************************* * @@ -79,11 +77,9 @@ tBTM_STATUS BTM_GetLinkSuperTout(const RawAddress& remote_bda, * Returns true if connection is up, else false. * ******************************************************************************/ -bool BTM_IsAclConnectionUp(const RawAddress& remote_bda, - tBT_TRANSPORT transport); +bool BTM_IsAclConnectionUp(const RawAddress& remote_bda, tBT_TRANSPORT transport); -bool BTM_IsAclConnectionUpAndHandleValid(const RawAddress& remote_bda, - tBT_TRANSPORT transport); +bool BTM_IsAclConnectionUpAndHandleValid(const RawAddress& remote_bda, tBT_TRANSPORT transport); /******************************************************************************* * @@ -148,8 +144,7 @@ tBTM_STATUS BTM_ReadRSSI(const RawAddress& remote_bda, tBTM_CMPL_CB* p_cb); * BTM_BUSY if command is already in progress * ******************************************************************************/ -tBTM_STATUS BTM_ReadFailedContactCounter(const RawAddress& remote_bda, - tBTM_CMPL_CB* p_cb); +tBTM_STATUS BTM_ReadFailedContactCounter(const RawAddress& remote_bda, tBTM_CMPL_CB* p_cb); /******************************************************************************* * @@ -167,8 +162,8 @@ tBTM_STATUS BTM_ReadFailedContactCounter(const RawAddress& remote_bda, * BTM_BUSY if command is already in progress * ******************************************************************************/ -tBTM_STATUS BTM_ReadTxPower(const RawAddress& remote_bda, - tBT_TRANSPORT transport, tBTM_CMPL_CB* p_cb); +tBTM_STATUS BTM_ReadTxPower(const RawAddress& remote_bda, tBT_TRANSPORT transport, + tBTM_CMPL_CB* p_cb); /******************************************************************************* * @@ -182,8 +177,7 @@ tBTM_STATUS BTM_ReadTxPower(const RawAddress& remote_bda, ******************************************************************************/ uint16_t BTM_GetNumAclLinks(void); -void btm_set_packet_types_from_address(const RawAddress& bda, - uint16_t pkt_types); +void btm_set_packet_types_from_address(const RawAddress& bda, uint16_t pkt_types); #define BLE_RESOLVE_ADDR_MASK 0xc0 #define BLE_RESOLVE_ADDR_MSB 0x40 @@ -191,27 +185,22 @@ void btm_set_packet_types_from_address(const RawAddress& bda, bool BTM_BLE_IS_RESOLVE_BDA(const RawAddress& x); bool acl_refresh_remote_address(const RawAddress& identity_address, - tBLE_ADDR_TYPE identity_address_type, - const RawAddress& remote_bda, - tBLE_RAND_ADDR_TYPE rra_type, - const RawAddress& rpa); + tBLE_ADDR_TYPE identity_address_type, const RawAddress& remote_bda, + tBLE_RAND_ADDR_TYPE rra_type, const RawAddress& rpa); -void btm_establish_continue_from_address(const RawAddress& remote_bda, - tBT_TRANSPORT transport); +void btm_establish_continue_from_address(const RawAddress& remote_bda, tBT_TRANSPORT transport); -bool acl_peer_supports_ble_connection_parameters_request( - const RawAddress& remote_bda); -void acl_ble_connection_parameters_request( - uint16_t handle, uint16_t conn_int_min, uint16_t conn_int_max, - uint16_t conn_latency, uint16_t conn_timeout, uint16_t min_ce_len, - uint16_t max_ce_len); +bool acl_peer_supports_ble_connection_parameters_request(const RawAddress& remote_bda); +void acl_ble_connection_parameters_request(uint16_t handle, uint16_t conn_int_min, + uint16_t conn_int_max, uint16_t conn_latency, + uint16_t conn_timeout, uint16_t min_ce_len, + uint16_t max_ce_len); bool acl_peer_supports_ble_packet_extension(uint16_t hci_handle); bool acl_peer_supports_ble_2m_phy(uint16_t hci_handle); bool acl_peer_supports_ble_coded_phy(uint16_t hci_handle); -bool acl_is_switch_role_idle(const RawAddress& bd_addr, - tBT_TRANSPORT transport); +bool acl_is_switch_role_idle(const RawAddress& bd_addr, tBT_TRANSPORT transport); bool acl_peer_supports_ble_packet_extension(uint16_t hci_handle); @@ -224,10 +213,8 @@ bool acl_peer_supports_ble_packet_extension(uint16_t hci_handle); * Returns void * ******************************************************************************/ -void BTM_ReadConnectionAddr(const RawAddress& remote_bda, - RawAddress& local_conn_addr, - tBLE_ADDR_TYPE* p_addr_type, - bool ota_address = false); +void BTM_ReadConnectionAddr(const RawAddress& remote_bda, RawAddress& local_conn_addr, + tBLE_ADDR_TYPE* p_addr_type, bool ota_address = false); /******************************************************************************* * @@ -255,11 +242,9 @@ bool acl_is_role_switch_allowed(); uint16_t acl_get_supported_packet_types(); -bool acl_set_peer_le_features_from_handle(uint16_t hci_handle, - const uint8_t* p); +bool acl_set_peer_le_features_from_handle(uint16_t hci_handle, const uint8_t* p); -tBTM_STATUS btm_read_power_mode_state(const RawAddress& remote_bda, - tBTM_PM_STATE* pmState); +tBTM_STATUS btm_read_power_mode_state(const RawAddress& remote_bda, tBTM_PM_STATE* pmState); void btm_acl_notif_conn_collision(const RawAddress& bda); @@ -284,25 +269,22 @@ void btm_acl_notif_conn_collision(const RawAddress& bda); ******************************************************************************/ bool BTM_ReadPowerMode(const RawAddress& remote_bda, tBTM_PM_MODE* p_mode); -void btm_acl_created(const RawAddress& bda, uint16_t hci_handle, - tHCI_ROLE link_role, tBT_TRANSPORT transport); +void btm_acl_created(const RawAddress& bda, uint16_t hci_handle, tHCI_ROLE link_role, + tBT_TRANSPORT transport); -void btm_acl_create_failed(const RawAddress& bda, tBT_TRANSPORT transport, - tHCI_STATUS reason); +void btm_acl_create_failed(const RawAddress& bda, tBT_TRANSPORT transport, tHCI_STATUS reason); void btm_acl_removed(uint16_t handle); void btm_acl_flush(uint16_t handle); -void acl_disconnect_from_handle(uint16_t handle, tHCI_STATUS reason, - std::string comment); +void acl_disconnect_from_handle(uint16_t handle, tHCI_STATUS reason, std::string comment); void acl_disconnect_after_role_switch(uint16_t conn_handle, tHCI_STATUS reason, std::string comment); bool acl_peer_supports_sniff_subrating(const RawAddress& remote_bda); bool acl_peer_supports_ble_connection_subrating(const RawAddress& remote_bda); -bool acl_peer_supports_ble_connection_subrating_host( - const RawAddress& remote_bda); +bool acl_peer_supports_ble_connection_subrating_host(const RawAddress& remote_bda); uint8_t btm_handle_to_acl_index(uint16_t hci_handle); @@ -316,5 +298,4 @@ void btm_acl_device_down(void); void ACL_RegisterClient(struct acl_client_callback_s* callbacks); void ACL_UnregisterClient(struct acl_client_callback_s* callbacks); -void btm_acl_consolidate(const RawAddress& identity_addr, - const RawAddress& rpa); +void btm_acl_consolidate(const RawAddress& identity_addr, const RawAddress& rpa); diff --git a/system/stack/include/acl_client_callbacks.h b/system/stack/include/acl_client_callbacks.h index 36e028728fd..74628cb17eb 100644 --- a/system/stack/include/acl_client_callbacks.h +++ b/system/stack/include/acl_client_callbacks.h @@ -17,16 +17,15 @@ #pragma once #include + #include "stack/include/hci_error_code.h" #include "types/bt_transport.h" #include "types/hci_role.h" #include "types/raw_address.h" struct acl_client_callback_s { - virtual void on_acl_link_down(const RawAddress bd_addr, - tBT_TRANSPORT transport) = 0; - virtual void on_acl_link_up(const RawAddress bd_addr, - tBT_TRANSPORT transport) = 0; + virtual void on_acl_link_down(const RawAddress bd_addr, tBT_TRANSPORT transport) = 0; + virtual void on_acl_link_up(const RawAddress bd_addr, tBT_TRANSPORT transport) = 0; virtual void on_acl_remote_features_complete(const RawAddress bd_addr) = 0; virtual void on_acl_role_change(const RawAddress bd_addr, hci_role_t new_role, tHCI_STATUS hci_status) = 0; diff --git a/system/stack/include/acl_hci_link_interface.h b/system/stack/include/acl_hci_link_interface.h index 34354901540..561d56ad900 100644 --- a/system/stack/include/acl_hci_link_interface.h +++ b/system/stack/include/acl_hci_link_interface.h @@ -29,34 +29,27 @@ // This header contains functions for HCIF-Acl Management to invoke // -void btm_connection_request(const RawAddress& bda, - const bluetooth::hci::ClassOfDevice& cod); -void btm_acl_connected(const RawAddress& bda, uint16_t handle, - tHCI_STATUS status, uint8_t enc_mode); -void on_acl_br_edr_connected(const RawAddress& bda, uint16_t handle, - uint8_t enc_mode, bool locally_initiated); -void on_acl_br_edr_failed(const RawAddress& bda, tHCI_STATUS status, - bool locally_initiated); -void btm_acl_disconnected(tHCI_STATUS status, uint16_t handle, - tHCI_STATUS reason); -void btm_acl_role_changed(tHCI_STATUS hci_status, const RawAddress& bd_addr, - tHCI_ROLE new_role); -void btm_rejectlist_role_change_device(const RawAddress& bd_addr, - uint8_t hci_status); +void btm_connection_request(const RawAddress& bda, const bluetooth::hci::ClassOfDevice& cod); +void btm_acl_connected(const RawAddress& bda, uint16_t handle, tHCI_STATUS status, + uint8_t enc_mode); +void on_acl_br_edr_connected(const RawAddress& bda, uint16_t handle, uint8_t enc_mode, + bool locally_initiated); +void on_acl_br_edr_failed(const RawAddress& bda, tHCI_STATUS status, bool locally_initiated); +void btm_acl_disconnected(tHCI_STATUS status, uint16_t handle, tHCI_STATUS reason); +void btm_acl_role_changed(tHCI_STATUS hci_status, const RawAddress& bd_addr, tHCI_ROLE new_role); +void btm_rejectlist_role_change_device(const RawAddress& bd_addr, uint8_t hci_status); void btm_pm_proc_cmd_status(tHCI_STATUS status); -void btm_pm_proc_mode_change(tHCI_STATUS hci_status, uint16_t hci_handle, - tHCI_MODE mode, uint16_t interval); +void btm_pm_proc_mode_change(tHCI_STATUS hci_status, uint16_t hci_handle, tHCI_MODE mode, + uint16_t interval); void btm_pm_proc_ssr_evt(uint8_t* p, uint16_t evt_len); void btm_read_automatic_flush_timeout_complete(uint8_t* p); void btm_read_failed_contact_counter_complete(uint8_t* p); void btm_read_remote_ext_features_complete_raw(uint8_t* p, uint8_t evt_len); -void btm_read_remote_ext_features_complete(uint16_t handle, uint8_t page_num, - uint8_t max_page, uint8_t* features); +void btm_read_remote_ext_features_complete(uint16_t handle, uint8_t page_num, uint8_t max_page, + uint8_t* features); void btm_read_remote_ext_features_failed(uint8_t status, uint16_t handle); -void btm_read_remote_version_complete(tHCI_STATUS status, uint16_t handle, - uint8_t lmp_version, - uint16_t manufacturer, - uint16_t lmp_subversion); +void btm_read_remote_version_complete(tHCI_STATUS status, uint16_t handle, uint8_t lmp_version, + uint16_t manufacturer, uint16_t lmp_subversion); void btm_read_rssi_complete(uint8_t* p, uint16_t evt_len); void btm_read_tx_power_complete(uint8_t* p, uint16_t evt_len, bool is_ble); @@ -65,13 +58,10 @@ void acl_packets_completed(uint16_t handle, uint16_t num_packets); void acl_process_supported_features(uint16_t handle, uint64_t features); void acl_process_extended_features(uint16_t handle, uint8_t current_page_number, uint8_t max_page_number, uint64_t features); -void btm_pm_on_mode_change(tHCI_STATUS status, uint16_t handle, - tHCI_MODE current_mode, uint16_t interval); +void btm_pm_on_mode_change(tHCI_STATUS status, uint16_t handle, tHCI_MODE current_mode, + uint16_t interval); void btm_pm_on_sniff_subrating(tHCI_STATUS status, uint16_t handle, - uint16_t maximum_transmit_latency, - uint16_t maximum_receive_latency, - uint16_t minimum_remote_timeout, - uint16_t minimum_local_timeout); + uint16_t maximum_transmit_latency, uint16_t maximum_receive_latency, + uint16_t minimum_remote_timeout, uint16_t minimum_local_timeout); -void acl_cache_role(const RawAddress& bd_addr, tHCI_ROLE new_role, - bool overwrite_cache); +void acl_cache_role(const RawAddress& bd_addr, tHCI_ROLE new_role, bool overwrite_cache); diff --git a/system/stack/include/advertise_data_parser.h b/system/stack/include/advertise_data_parser.h index 1ed896c6c09..e1ea9cd8896 100644 --- a/system/stack/include/advertise_data_parser.h +++ b/system/stack/include/advertise_data_parser.h @@ -23,20 +23,18 @@ #include // Scan Response data from Traxxas -static constexpr std::array trx_quirk{ - {0x14, 0x09, 0x54, 0xFF, 0xFF, 0x20, 0x42, 0x4C, 0x45, 0x05, 0x12, 0xFF, - 0x00, 0xE8, 0x03, 0x02, 0x0A, 0x00}}; +static constexpr std::array trx_quirk{{0x14, 0x09, 0x54, 0xFF, 0xFF, 0x20, 0x42, 0x4C, + 0x45, 0x05, 0x12, 0xFF, 0x00, 0xE8, 0x03, 0x02, + 0x0A, 0x00}}; class AdvertiseDataParser { // Return true if the packet is malformed, but should be considered valid for // compatibility with already existing devices - static bool MalformedPacketQuirk(const std::vector& ad, - size_t position) { + static bool MalformedPacketQuirk(const std::vector& ad, size_t position) { auto data_start = ad.begin() + position; // Traxxas - bad name length - if ((ad.size() - position) >= 18 && - std::equal(data_start, data_start + 3, trx_quirk.begin()) && + if ((ad.size() - position) >= 18 && std::equal(data_start, data_start + 3, trx_quirk.begin()) && std::equal(data_start + 5, data_start + 11, trx_quirk.begin() + 5) && std::equal(data_start + 12, data_start + 18, trx_quirk.begin() + 12)) { return true; @@ -45,7 +43,7 @@ class AdvertiseDataParser { return false; } - public: +public: static void RemoveTrailingZeros(std::vector& ad) { size_t position = 0; @@ -86,7 +84,9 @@ class AdvertiseDataParser { // end of advertisement. If this is the case, treat the packet as valid. if (len == 0) { for (size_t i = position + 1; i < ad_len; i++) { - if (ad[i] != 0) return false; + if (ad[i] != 0) { + return false; + } } return true; } @@ -94,7 +94,9 @@ class AdvertiseDataParser { // If the length of the current field would exceed the total data length, // then the data is badly formatted. if (position + len >= ad_len) { - if (MalformedPacketQuirk(ad, position)) return true; + if (MalformedPacketQuirk(ad, position)) { + return true; + } return false; } @@ -109,15 +111,19 @@ class AdvertiseDataParser { * This function returns a pointer inside the |ad| array of length |ad_len| * where a field of |type| is located, together with its length in |p_length| */ - static const uint8_t* GetFieldByType(const uint8_t* ad, size_t ad_len, - uint8_t type, uint8_t* p_length) { + static const uint8_t* GetFieldByType(const uint8_t* ad, size_t ad_len, uint8_t type, + uint8_t* p_length) { size_t position = 0; while (position != ad_len) { uint8_t len = ad[position]; - if (len == 0) break; - if (position + len >= ad_len) break; + if (len == 0) { + break; + } + if (position + len >= ad_len) { + break; + } uint8_t adv_type = ad[position + 1]; @@ -138,8 +144,8 @@ class AdvertiseDataParser { * This function returns a pointer inside the |adv| where a field of |type| is * located, together with it' length in |p_length| */ - static const uint8_t* GetFieldByType(std::vector const& ad, - uint8_t type, uint8_t* p_length) { + static const uint8_t* GetFieldByType(std::vector const& ad, uint8_t type, + uint8_t* p_length) { return GetFieldByType(ad.data(), ad.size(), type, p_length); } }; diff --git a/system/stack/include/avct_api.h b/system/stack/include/avct_api.h index 220ac679faf..0ac2399b937 100644 --- a/system/stack/include/avct_api.h +++ b/system/stack/include/avct_api.h @@ -64,7 +64,7 @@ /* Message offset. The number of bytes needed by the protocol stack for the * protocol headers of an AVCTP message packet. -*/ + */ #define AVCT_MSG_OFFSET 15 #define AVCT_BROWSE_OFFSET 17 /* the default offset for browsing channel */ @@ -109,8 +109,7 @@ typedef void(tAVCT_CTRL_CBACK)(uint8_t handle, uint8_t event, uint16_t result, /* Message callback function */ /* p_pkt->layer_specific is AVCT_DATA_CTRL or AVCT_DATA_BROWSE */ -typedef void(tAVCT_MSG_CBACK)(uint8_t handle, uint8_t label, uint8_t cr, - BT_HDR* p_pkt); +typedef void(tAVCT_MSG_CBACK)(uint8_t handle, uint8_t label, uint8_t cr, BT_HDR* p_pkt); /* Structure used by AVCT_CreateConn. */ typedef struct { @@ -174,8 +173,7 @@ void AVCT_Deregister(void); * Returns AVCT_SUCCESS if successful, otherwise error. * ******************************************************************************/ -uint16_t AVCT_CreateConn(uint8_t* p_handle, tAVCT_CC* p_cc, - const RawAddress& peer_addr); +uint16_t AVCT_CreateConn(uint8_t* p_handle, tAVCT_CC* p_cc, const RawAddress& peer_addr); /******************************************************************************* * diff --git a/system/stack/include/avdt_api.h b/system/stack/include/avdt_api.h index 4df6cc5631e..3a587965748 100644 --- a/system/stack/include/avdt_api.h +++ b/system/stack/include/avdt_api.h @@ -56,8 +56,8 @@ typedef enum : uint16_t { } tAVDT_RESULT; inline tAVDT_RESULT ToAvdtResult(uint16_t result) { - bluetooth::log::assert_that(result <= AVDT_WRITE_FAIL, - "Unable to convert illegal result:{}", result); + bluetooth::log::assert_that(result <= AVDT_WRITE_FAIL, "Unable to convert illegal result:{}", + result); return static_cast(result); } @@ -89,14 +89,14 @@ inline std::string avdt_result_text(const tAVDT_RESULT& result) { /* The number of bytes needed by the protocol stack for the protocol headers * of a media packet. This is the size of the media packet header, the * L2CAP packet header and HCI header. -*/ + */ #define AVDT_MEDIA_OFFSET 23 /* The marker bit is used by the application to mark significant events such * as frame boundaries in the data stream. This constant is used to check or * set the marker bit in the m_pt parameter of an AVDT_WriteReq() * or AVDT_DATA_IND_EVT. -*/ + */ #define AVDT_MARKER_SET 0x80 #define MAX_2MBPS_AVDTP_MTU 663 // 2DH5 MTU=679, -12 for AVDTP, -4 for L2CAP @@ -141,7 +141,7 @@ typedef uint8_t AVDT_REPORT_TYPE; /* Protocol service capabilities. This indicates the protocol service * capabilities of a stream endpoint. This value is a mask. * Multiple values can be combined with a bitwise OR. -*/ + */ #define AVDT_PSC_TRANS (1 << 1) /* Media transport */ #define AVDT_PSC_REPORT (1 << 2) /* Reporting */ #define AVDT_PSC_RECOV (1 << 3) /* Recovery */ @@ -155,7 +155,7 @@ typedef uint8_t AVDT_REPORT_TYPE; /* Header compression capabilities. This indicates the header compression * capabilities. This value is a mask. Multiple values can be combined * with a bitwise OR. -*/ + */ #define AVDT_HDRCMP_MEDIA (1 << 5) /* Available for media packets */ #define AVDT_HDRCMP_RECOV (1 << 6) /* Available for recovery packets */ #define AVDT_HDRCMP_BACKCH (1 << 7) /* Back channel supported */ @@ -165,7 +165,7 @@ typedef uint8_t AVDT_REPORT_TYPE; /* Application service category. This indicates the application * service category. -*/ + */ #define AVDT_ASC_PROTECT 4 /* Content protection */ #define AVDT_ASC_CODEC 7 /* Codec */ @@ -187,7 +187,7 @@ typedef uint8_t AVDT_REPORT_TYPE; * and their appropriate use can be found in the AVDTP and GAVDP specifications. * These error codes are unrelated to the result values returned by the * AVDTP API functions. -*/ + */ /* Bad packet header format */ #define AVDT_ERR_HEADER 0x01 /* Bad packet length */ @@ -243,7 +243,7 @@ typedef uint8_t AVDT_REPORT_TYPE; /* Additional error codes. This indicates error codes used by AVDTP * in addition to the ones defined in the specifications. -*/ + */ #define AVDT_ERR_CONNECT 0x07 /* Connection failed. */ #define AVDT_ERR_TIMEOUT 0x08 /* Response timeout. */ @@ -281,18 +281,17 @@ typedef uint8_t AVDT_REPORT_TYPE; ****************************************************************************/ typedef struct { - uint32_t ntp_sec; /* NTP time: seconds relative to 0h UTC on 1 January 1900 */ + uint32_t ntp_sec; /* NTP time: seconds relative to 0h UTC on 1 January 1900 */ uint32_t ntp_frac; /* NTP time: the fractional part */ uint32_t rtp_time; /* timestamp in RTP header */ uint32_t pkt_count; /* sender's packet count: since starting transmission - * up until the time this SR packet was generated. */ + * up until the time this SR packet was generated. */ uint32_t octet_count; /* sender's octet count: same comment */ } tAVDT_SENDER_INFO; typedef struct { - uint8_t frag_lost; /* fraction lost since last RR */ - uint32_t - packet_lost; /* cumulative number of packets lost since the beginning */ + uint8_t frag_lost; /* fraction lost since last RR */ + uint32_t packet_lost; /* cumulative number of packets lost since the beginning */ uint32_t seq_num_rcvd; /* extended highest sequence number received */ uint32_t jitter; /* interarrival jitter */ uint32_t lsr; /* last SR timestamp */ @@ -309,13 +308,8 @@ typedef union { * AVDTP Registration Control Block. */ class AvdtpRcb { - public: - AvdtpRcb() - : ctrl_mtu(0), - ret_tout(0), - sig_tout(0), - idle_tout(0), - scb_index(0) {} +public: + AvdtpRcb() : ctrl_mtu(0), ret_tout(0), sig_tout(0), idle_tout(0), scb_index(0) {} AvdtpRcb& operator=(const AvdtpRcb&) = default; void Reset() { @@ -335,7 +329,7 @@ class AvdtpRcb { /* This structure contains the SEP information. This information is * transferred during the discovery procedure. -*/ + */ typedef struct { bool in_use; /* true if stream is currently in use */ uint8_t seid; /* Stream endpoint identifier */ @@ -347,7 +341,7 @@ typedef struct { * AVDTP SEP Configuration. */ class AvdtpSepConfig { - public: +public: AvdtpSepConfig() : codec_info{}, protect_info{}, @@ -374,19 +368,18 @@ class AvdtpSepConfig { uint8_t codec_info[AVDT_CODEC_SIZE]; /* Codec capabilities array */ uint8_t protect_info[AVDT_PROTECT_SIZE]; /* Content protection capabilities */ - uint8_t num_codec; /* Number of media codec information elements */ - uint8_t num_protect; /* Number of content protection information elements */ - uint16_t psc_mask; /* Protocol service capabilities mask */ - uint8_t recov_type; /* Recovery type */ - uint8_t recov_mrws; /* Maximum recovery window size */ - uint8_t recov_mnmp; /* Recovery maximum number of media packets */ - uint8_t hdrcmp_mask; /* Header compression capabilities */ + uint8_t num_codec; /* Number of media codec information elements */ + uint8_t num_protect; /* Number of content protection information elements */ + uint16_t psc_mask; /* Protocol service capabilities mask */ + uint8_t recov_type; /* Recovery type */ + uint8_t recov_mrws; /* Maximum recovery window size */ + uint8_t recov_mnmp; /* Recovery maximum number of media packets */ + uint8_t hdrcmp_mask; /* Header compression capabilities */ }; /* Header structure for callback event parameters. */ typedef struct { - uint8_t - err_code; /* Zero if operation succeeded; nonzero if operation failed */ + uint8_t err_code; /* Zero if operation succeeded; nonzero if operation failed */ uint8_t err_param; /* Error parameter included for some events */ uint8_t label; /* Transaction label */ uint8_t seid; /* For internal use only */ @@ -396,17 +389,17 @@ typedef struct { /* This data structure is associated with the AVDT_GETCAP_CFM_EVT, * AVDT_RECONFIG_IND_EVT, and AVDT_RECONFIG_CFM_EVT. -*/ + */ typedef struct { - tAVDT_EVT_HDR hdr; /* Event header */ + tAVDT_EVT_HDR hdr; /* Event header */ AvdtpSepConfig* p_cfg; /* Pointer to configuration for this SEP */ } tAVDT_CONFIG; /* This data structure is associated with the AVDT_CONFIG_IND_EVT. */ typedef struct { - tAVDT_EVT_HDR hdr; /* Event header */ + tAVDT_EVT_HDR hdr; /* Event header */ AvdtpSepConfig* p_cfg; /* Pointer to configuration for this SEP */ - uint8_t int_seid; /* Stream endpoint ID of stream initiating the operation */ + uint8_t int_seid; /* Stream endpoint ID of stream initiating the operation */ } tAVDT_SETCONFIG; /* This data structure is associated with the AVDT_OPEN_IND_EVT and @@ -419,7 +412,7 @@ typedef struct { /* This data structure is associated with the AVDT_SECURITY_IND_EVT * and AVDT_SECURITY_CFM_EVT. -*/ + */ typedef struct { tAVDT_EVT_HDR hdr; /* Event header */ uint8_t* p_data; /* Pointer to security data */ @@ -464,31 +457,29 @@ typedef union { * to the application. This function is required for all registered stream * endpoints and for the AVDT_DiscoverReq() and AVDT_GetCapReq() functions. * -*/ -typedef void(tAVDT_CTRL_CBACK)(uint8_t handle, const RawAddress& bd_addr, - uint8_t event, tAVDT_CTRL* p_data, - uint8_t scb_index); + */ +typedef void(tAVDT_CTRL_CBACK)(uint8_t handle, const RawAddress& bd_addr, uint8_t event, + tAVDT_CTRL* p_data, uint8_t scb_index); /* This is the data callback function. It is executed when AVDTP has a media * packet ready for the application. This function is required for SNK * endpoints and not applicable for SRC endpoints. -*/ -typedef void(tAVDT_SINK_DATA_CBACK)(uint8_t handle, BT_HDR* p_pkt, - uint32_t time_stamp, uint8_t m_pt); + */ +typedef void(tAVDT_SINK_DATA_CBACK)(uint8_t handle, BT_HDR* p_pkt, uint32_t time_stamp, + uint8_t m_pt); /* This is the report callback function. It is executed when AVDTP has a * reporting packet ready for the application. This function is required for * streams created with AVDT_PSC_REPORT. -*/ -typedef void(tAVDT_REPORT_CBACK)(uint8_t handle, AVDT_REPORT_TYPE type, - tAVDT_REPORT_DATA* p_data); + */ +typedef void(tAVDT_REPORT_CBACK)(uint8_t handle, AVDT_REPORT_TYPE type, tAVDT_REPORT_DATA* p_data); /** * AVDTP Stream Configuration. * The information is used when a stream is created. */ class AvdtpStreamConfig { - public: +public: // // Non-supported protocol command messages // @@ -521,15 +512,15 @@ class AvdtpStreamConfig { nsc_mask = 0; } - AvdtpSepConfig cfg; // SEP configuration - tAVDT_CTRL_CBACK* p_avdt_ctrl_cback; // Control callback function - uint8_t scb_index; // The index to the bta_av_cb.p_scb[] entry + AvdtpSepConfig cfg; // SEP configuration + tAVDT_CTRL_CBACK* p_avdt_ctrl_cback; // Control callback function + uint8_t scb_index; // The index to the bta_av_cb.p_scb[] entry tAVDT_SINK_DATA_CBACK* p_sink_data_cback; // Sink data callback function tAVDT_REPORT_CBACK* p_report_cback; // Report callback function - uint16_t mtu; // The L2CAP MTU of the transport channel - uint8_t tsep; // SEP type - uint8_t media_type; // Media type: AVDT_MEDIA_TYPE_* - uint16_t nsc_mask; // Nonsupported protocol command messages + uint16_t mtu; // The L2CAP MTU of the transport channel + uint8_t tsep; // SEP type + uint8_t media_type; // Media type: AVDT_MEDIA_TYPE_* + uint16_t nsc_mask; // Nonsupported protocol command messages }; /* AVDT data option mask is used in the write request */ @@ -644,8 +635,7 @@ uint16_t AVDT_RemoveStream(uint8_t handle); * ******************************************************************************/ uint16_t AVDT_DiscoverReq(const RawAddress& bd_addr, uint8_t channel_index, - tAVDT_SEP_INFO* p_sep_info, uint8_t max_seps, - tAVDT_CTRL_CBACK* p_cback); + tAVDT_SEP_INFO* p_sep_info, uint8_t max_seps, tAVDT_CTRL_CBACK* p_cback); /******************************************************************************* * @@ -671,9 +661,8 @@ uint16_t AVDT_DiscoverReq(const RawAddress& bd_addr, uint8_t channel_index, * Returns AVDT_SUCCESS if successful, otherwise error. * ******************************************************************************/ -uint16_t AVDT_GetCapReq(const RawAddress& bd_addr, uint8_t channel_index, - uint8_t seid, AvdtpSepConfig* p_cfg, - tAVDT_CTRL_CBACK* p_cback, bool get_all_cap); +uint16_t AVDT_GetCapReq(const RawAddress& bd_addr, uint8_t channel_index, uint8_t seid, + AvdtpSepConfig* p_cfg, tAVDT_CTRL_CBACK* p_cback, bool get_all_cap); /******************************************************************************* * @@ -702,9 +691,8 @@ uint16_t AVDT_DelayReport(uint8_t handle, uint8_t seid, uint16_t delay); * Returns AVDT_SUCCESS if successful, otherwise error. * ******************************************************************************/ -uint16_t AVDT_OpenReq(uint8_t handle, const RawAddress& bd_addr, - uint8_t channel_index, uint8_t seid, - AvdtpSepConfig* p_cfg); +uint16_t AVDT_OpenReq(uint8_t handle, const RawAddress& bd_addr, uint8_t channel_index, + uint8_t seid, AvdtpSepConfig* p_cfg); /******************************************************************************* * @@ -718,8 +706,7 @@ uint16_t AVDT_OpenReq(uint8_t handle, const RawAddress& bd_addr, * Returns AVDT_SUCCESS if successful, otherwise error. * ******************************************************************************/ -uint16_t AVDT_ConfigRsp(uint8_t handle, uint8_t label, uint8_t error_code, - uint8_t category); +uint16_t AVDT_ConfigRsp(uint8_t handle, uint8_t label, uint8_t error_code, uint8_t category); /******************************************************************************* * @@ -820,8 +807,8 @@ uint16_t AVDT_SecurityReq(uint8_t handle, uint8_t* p_data, uint16_t len); * Returns AVDT_SUCCESS if successful, otherwise error. * ******************************************************************************/ -uint16_t AVDT_SecurityRsp(uint8_t handle, uint8_t label, uint8_t error_code, - uint8_t* p_data, uint16_t len); +uint16_t AVDT_SecurityRsp(uint8_t handle, uint8_t label, uint8_t error_code, uint8_t* p_data, + uint16_t len); /******************************************************************************* * @@ -859,8 +846,8 @@ uint16_t AVDT_SecurityRsp(uint8_t handle, uint8_t label, uint8_t error_code, * Returns AVDT_SUCCESS if successful, otherwise error. * ******************************************************************************/ -uint16_t AVDT_WriteReqOpt(uint8_t handle, BT_HDR* p_pkt, uint32_t time_stamp, - uint8_t m_pt, tAVDT_DATA_OPT_MASK opt); +uint16_t AVDT_WriteReqOpt(uint8_t handle, BT_HDR* p_pkt, uint32_t time_stamp, uint8_t m_pt, + tAVDT_DATA_OPT_MASK opt); /******************************************************************************* * @@ -892,8 +879,7 @@ uint16_t AVDT_ConnectReq(const RawAddress& bd_addr, uint8_t channel_index, * Returns AVDT_SUCCESS if successful, otherwise error. * ******************************************************************************/ -uint16_t AVDT_DisconnectReq(const RawAddress& bd_addr, - tAVDT_CTRL_CBACK* p_cback); +uint16_t AVDT_DisconnectReq(const RawAddress& bd_addr, tAVDT_CTRL_CBACK* p_cback); /******************************************************************************* * diff --git a/system/stack/include/avdtc_api.h b/system/stack/include/avdtc_api.h index b510190688a..a782b4e03f0 100644 --- a/system/stack/include/avdtc_api.h +++ b/system/stack/include/avdtc_api.h @@ -72,8 +72,8 @@ typedef union { tAVDT_MULTI suspend_ind; } tAVDTC_CTRL; -typedef void tAVDTC_CTRL_CBACK(uint8_t handle, const RawAddress& bd_addr, - uint8_t event, tAVDTC_CTRL* p_data); +typedef void tAVDTC_CTRL_CBACK(uint8_t handle, const RawAddress& bd_addr, uint8_t event, + tAVDTC_CTRL* p_data); /******************************************************************************* * @@ -97,8 +97,8 @@ void AVDTC_Init(tAVDTC_CTRL_CBACK* p_cback); * Returns void * ******************************************************************************/ -void AVDTC_DiscoverRsp(const RawAddress& bd_addr, uint8_t label, - tAVDT_SEP_INFO sep_info[], uint8_t num_seps); +void AVDTC_DiscoverRsp(const RawAddress& bd_addr, uint8_t label, tAVDT_SEP_INFO sep_info[], + uint8_t num_seps); /******************************************************************************* * @@ -109,8 +109,7 @@ void AVDTC_DiscoverRsp(const RawAddress& bd_addr, uint8_t label, * Returns void * ******************************************************************************/ -void AVDTC_GetCapRsp(const RawAddress& bd_addr, uint8_t label, - AvdtpSepConfig* p_cap); +void AVDTC_GetCapRsp(const RawAddress& bd_addr, uint8_t label, AvdtpSepConfig* p_cap); /******************************************************************************* * @@ -121,8 +120,7 @@ void AVDTC_GetCapRsp(const RawAddress& bd_addr, uint8_t label, * Returns void * ******************************************************************************/ -void AVDTC_GetAllCapRsp(const RawAddress& bd_addr, uint8_t label, - AvdtpSepConfig* p_cap); +void AVDTC_GetAllCapRsp(const RawAddress& bd_addr, uint8_t label, AvdtpSepConfig* p_cap); /******************************************************************************* * @@ -232,7 +230,7 @@ void AVDTC_AbortRsp(uint8_t handle, uint8_t label); * Returns void * ******************************************************************************/ -void AVDTC_Rej(uint8_t handle, const RawAddress& bd_addr, uint8_t cmd, - uint8_t label, uint8_t err_code, uint8_t err_param); +void AVDTC_Rej(uint8_t handle, const RawAddress& bd_addr, uint8_t cmd, uint8_t label, + uint8_t err_code, uint8_t err_param); #endif /* AVDT_CAPI_H */ diff --git a/system/stack/include/avrc_api.h b/system/stack/include/avrc_api.h index 8aa6f500fe6..0f4496b30e6 100644 --- a/system/stack/include/avrc_api.h +++ b/system/stack/include/avrc_api.h @@ -92,8 +92,8 @@ #define AVRC_UNCONG_IND_EVT 3 /* AVRC_BROWSE_OPEN_IND_EVT event is sent when the browse channel is -* successfully opened. -* This eventis sent in response to an AVRC_Open() or AVRC_OpenBrowse() . */ + * successfully opened. + * This eventis sent in response to an AVRC_Open() or AVRC_OpenBrowse() . */ #define AVRC_BROWSE_OPEN_IND_EVT 4 /* AVRC_BROWSE_CLOSE_IND_EVT event is sent when a browse channel is closed. @@ -146,8 +146,7 @@ /* Configurable dynamic avrcp version enable key*/ #ifndef AVRC_DYNAMIC_AVRCP_ENABLE_PROPERTY -#define AVRC_DYNAMIC_AVRCP_ENABLE_PROPERTY \ - "persist.bluetooth.dynamic_avrcp.enable" +#define AVRC_DYNAMIC_AVRCP_ENABLE_PROPERTY "persist.bluetooth.dynamic_avrcp.enable" #endif /* Supported categories */ @@ -217,16 +216,15 @@ using tAVRC_FIND_CBACK = base::Callback; /* This is the control callback function. This function passes events * listed in Table 20 to the application. */ -using tAVRC_CTRL_CBACK = - base::Callback; +using tAVRC_CTRL_CBACK = base::Callback; /* This is the message callback function. It is executed when AVCTP has * a message packet ready for the application. The implementation of this * callback function must copy the tAVRC_MSG structure passed to it as it * is not guaranteed to remain after the callback function exits. */ -using tAVRC_MSG_CBACK = base::Callback; +using tAVRC_MSG_CBACK = + base::Callback; typedef struct { tAVRC_CTRL_CBACK ctrl_cback; /* application control callback */ @@ -319,9 +317,8 @@ uint16_t AVRC_GetProfileVersion(); * *****************************************************************************/ uint16_t AVRC_AddRecord(uint16_t service_uuid, const char* p_service_name, - const char* p_provider_name, uint16_t categories, - uint32_t sdp_handle, bool browse_supported, - uint16_t profile_version, uint16_t cover_art_psm); + const char* p_provider_name, uint16_t categories, uint32_t sdp_handle, + bool browse_supported, uint16_t profile_version, uint16_t cover_art_psm); /******************************************************************************* * @@ -378,8 +375,7 @@ uint16_t AVRC_RemoveRecord(uint32_t sdp_handle); * *****************************************************************************/ uint16_t AVRC_FindService(uint16_t service_uuid, const RawAddress& bd_addr, - tAVRC_SDP_DB_PARAMS* p_db, - const tAVRC_FIND_CBACK& cback); + tAVRC_SDP_DB_PARAMS* p_db, const tAVRC_FIND_CBACK& cback); /****************************************************************************** * @@ -429,8 +425,7 @@ uint16_t AVRC_FindService(uint16_t service_uuid, const RawAddress& bd_addr, * the connection. * *****************************************************************************/ -uint16_t AVRC_Open(uint8_t* p_handle, tAVRC_CONN_CB* p_ccb, - const RawAddress& peer_addr); +uint16_t AVRC_Open(uint8_t* p_handle, tAVRC_CONN_CB* p_ccb, const RawAddress& peer_addr); /****************************************************************************** * @@ -501,8 +496,8 @@ uint16_t AVRC_CloseBrowse(uint8_t handle); * AVRC_BAD_HANDLE if handle is invalid. * *****************************************************************************/ -uint16_t AVRC_MsgReq(uint8_t handle, uint8_t label, uint8_t ctype, - BT_HDR* p_pkt, bool is_new_avrcp); +uint16_t AVRC_MsgReq(uint8_t handle, uint8_t label, uint8_t ctype, BT_HDR* p_pkt, + bool is_new_avrcp); /****************************************************************************** * @@ -720,8 +715,8 @@ tAVRC_STS AVRC_Ctrl_ParsCommand(tAVRC_MSG* p_msg, tAVRC_COMMAND* p_result); * Otherwise, the error code defined by AVRCP 1.4 * ******************************************************************************/ -tAVRC_STS AVRC_ParsCommand(tAVRC_MSG* p_msg, tAVRC_COMMAND* p_result, - uint8_t* p_buf, uint16_t buf_len); +tAVRC_STS AVRC_ParsCommand(tAVRC_MSG* p_msg, tAVRC_COMMAND* p_result, uint8_t* p_buf, + uint16_t buf_len); /******************************************************************************* * @@ -734,8 +729,8 @@ tAVRC_STS AVRC_ParsCommand(tAVRC_MSG* p_msg, tAVRC_COMMAND* p_result, * Otherwise, the error code defined by AVRCP 1.4 * ******************************************************************************/ -tAVRC_STS AVRC_ParsResponse(tAVRC_MSG* p_msg, tAVRC_RESPONSE* p_result, - uint8_t* p_buf, uint16_t buf_len); +tAVRC_STS AVRC_ParsResponse(tAVRC_MSG* p_msg, tAVRC_RESPONSE* p_result, uint8_t* p_buf, + uint16_t buf_len); /******************************************************************************* * @@ -748,8 +743,8 @@ tAVRC_STS AVRC_ParsResponse(tAVRC_MSG* p_msg, tAVRC_RESPONSE* p_result, * Otherwise, the error code defined by AVRCP 1.4 * ******************************************************************************/ -tAVRC_STS AVRC_Ctrl_ParsResponse(tAVRC_MSG* p_msg, tAVRC_RESPONSE* p_result, - uint8_t* p_buf, uint16_t* buf_len); +tAVRC_STS AVRC_Ctrl_ParsResponse(tAVRC_MSG* p_msg, tAVRC_RESPONSE* p_result, uint8_t* p_buf, + uint16_t* buf_len); /******************************************************************************* * @@ -775,8 +770,7 @@ tAVRC_STS AVRC_BldCommand(tAVRC_COMMAND* p_cmd, BT_HDR** pp_pkt); * Otherwise, the error code. * ******************************************************************************/ -tAVRC_STS AVRC_BldResponse(uint8_t handle, tAVRC_RESPONSE* p_rsp, - BT_HDR** pp_pkt); +tAVRC_STS AVRC_BldResponse(uint8_t handle, tAVRC_RESPONSE* p_rsp, BT_HDR** pp_pkt); /************************************************************************** * diff --git a/system/stack/include/avrc_defs.h b/system/stack/include/avrc_defs.h index ca9fd7ea5e9..edf9981ab41 100644 --- a/system/stack/include/avrc_defs.h +++ b/system/stack/include/avrc_defs.h @@ -68,7 +68,7 @@ or doesn't implement the specified subunit */ #define AVRC_RSP_ACCEPT \ 9 /* The target executed or is executing the command \ - */ + */ #define AVRC_RSP_REJ \ 10 /* The target implements the command specified by the \ opcode but cannot respond because the current state \ @@ -118,21 +118,20 @@ #define AVRC_OP_INVALID 0xFE /* invalid one */ /* Company ID's -*/ + */ #define AVRC_CO_BLUETOOTH_SIG 0x00FFFFFF #define AVRC_CO_WIDCOMM 0x00000361 #define AVRC_CO_BROADCOM 0x00001018 #define AVRC_CO_GOOGLE 0x00DAA119 -#define AVRC_CO_METADATA \ - 0x00001958 /* Unique COMPANY ID for Metadata messages */ +#define AVRC_CO_METADATA 0x00001958 /* Unique COMPANY ID for Metadata messages */ /* State flag for Passthrough commands -*/ + */ #define AVRC_STATE_PRESS 0 #define AVRC_STATE_RELEASE 1 /* Operation ID list for Passthrough commands -*/ + */ #define AVRC_ID_SELECT 0x00 /* select */ #define AVRC_ID_UP 0x01 /* up */ #define AVRC_ID_DOWN 0x02 /* down */ @@ -197,7 +196,7 @@ ****************************************************************************/ /* Define the Metadata Packet types -*/ + */ #define AVRC_PKT_SINGLE 0 #define AVRC_PKT_START 1 #define AVRC_PKT_CONTINUE 2 @@ -314,14 +313,14 @@ typedef enum : uint8_t { typedef uint8_t tAVRC_STS; /* Define the Capability IDs -*/ + */ #define AVRC_CAP_COMPANY_ID 0x02 #define AVRC_CAP_EVENTS_SUPPORTED 0x03 #define AVRC_COMPANY_ID_LEN 3 #define AVRC_CAPABILITY_OFFSET 2 /* Define the Player Application Settings IDs -*/ + */ #define AVRC_PLAYER_SETTING_EQUALIZER 0x01 #define AVRC_PLAYER_SETTING_REPEAT 0x02 #define AVRC_PLAYER_SETTING_SHUFFLE 0x03 @@ -330,7 +329,7 @@ typedef uint8_t tAVRC_STS; #define AVRC_PLAYER_SETTING_HIGH_MENU_EXT 0xff /* Define the possible values of the Player Application Settings -*/ + */ #define AVRC_PLAYER_VAL_OFF 0x01 #define AVRC_PLAYER_VAL_ON 0x02 #define AVRC_PLAYER_VAL_SINGLE_REPEAT 0x02 @@ -342,7 +341,7 @@ typedef uint8_t tAVRC_STS; #define AVRC_PLAYER_VAL_GROUP_SCAN 0x03 /* Define the possible values of Battery Status PDU -*/ + */ #define AVRC_BATTERY_STATUS_NORMAL 0x00 #define AVRC_BATTERY_STATUS_WARNING 0x01 #define AVRC_BATTERY_STATUS_CRITICAL 0x02 @@ -354,7 +353,7 @@ typedef uint8_t tAVRC_BATTERY_STATUS; #define AVRC_CHAR_SET_SIZE 2 /* Define the Media Attribute IDs -*/ + */ #define AVRC_MEDIA_ATTR_ID_TITLE 0x00000001 #define AVRC_MEDIA_ATTR_ID_ARTIST 0x00000002 #define AVRC_MEDIA_ATTR_ID_ALBUM 0x00000003 @@ -366,7 +365,7 @@ typedef uint8_t tAVRC_BATTERY_STATUS; #define AVRC_MAX_NUM_MEDIA_ATTR_ID 8 /* Define the possible values of play state -*/ + */ #define AVRC_PLAYSTATE_RESP_MSG_SIZE 9 #define AVRC_PLAYSTATE_STOPPED 0x00 /* Stopped */ #define AVRC_PLAYSTATE_PLAYING 0x01 /* Playing */ @@ -377,7 +376,7 @@ typedef uint8_t tAVRC_BATTERY_STATUS; typedef uint8_t tAVRC_PLAYSTATE; /* Define the events that can be registered for notifications -*/ + */ #define AVRC_EVT_INVALID 0x00 #define AVRC_EVT_PLAY_STATUS_CHANGE 0x01 #define AVRC_EVT_TRACK_CHANGE 0x02 @@ -405,7 +404,7 @@ typedef uint8_t tAVRC_PLAYSTATE; #define AVRC_MAX_VOLUME 0x7F /* Define the possible values of system status -*/ + */ #define AVRC_SYSTEMSTATE_PWR_ON 0x00 #define AVRC_SYSTEMSTATE_PWR_OFF 0x01 #define AVRC_SYSTEMSTATE_PWR_UNPLUGGED 0x02 @@ -476,8 +475,7 @@ typedef uint8_t tAVRC_UID[AVRC_UID_SIZE]; #define AVRC_PF_SELECT_BIT_NO 0 #define AVRC_PF_SELECT_MASK 0x01 #define AVRC_PF_SELECT_OFF 0 -#define AVRC_PF_SELECT_SUPPORTED(x) \ - ((x)[AVRC_PF_SELECT_OFF] & AVRC_PF_SELECT_MASK) +#define AVRC_PF_SELECT_SUPPORTED(x) ((x)[AVRC_PF_SELECT_OFF] & AVRC_PF_SELECT_MASK) #define AVRC_PF_UP_BIT_NO 1 #define AVRC_PF_UP_MASK 0x02 @@ -502,38 +500,32 @@ typedef uint8_t tAVRC_UID[AVRC_UID_SIZE]; #define AVRC_PF_RIGHTUP_BIT_NO 5 #define AVRC_PF_RIGHTUP_MASK 0x20 #define AVRC_PF_RIGHTUP_OFF 0 -#define AVRC_PF_RIGHTUP_SUPPORTED(x) \ - ((x)[AVRC_PF_RIGHTUP_OFF] & AVRC_PF_RIGHTUP_MASK) +#define AVRC_PF_RIGHTUP_SUPPORTED(x) ((x)[AVRC_PF_RIGHTUP_OFF] & AVRC_PF_RIGHTUP_MASK) #define AVRC_PF_RIGHTDOWN_BIT_NO 6 #define AVRC_PF_RIGHTDOWN_MASK 0x40 #define AVRC_PF_RIGHTDOWN_OFF 0 -#define AVRC_PF_RIGHTDOWN_SUPPORTED(x) \ - ((x)[AVRC_PF_RIGHTDOWN_OFF] & AVRC_PF_RIGHTDOWN_MASK) +#define AVRC_PF_RIGHTDOWN_SUPPORTED(x) ((x)[AVRC_PF_RIGHTDOWN_OFF] & AVRC_PF_RIGHTDOWN_MASK) #define AVRC_PF_LEFTUP_BIT_NO 7 #define AVRC_PF_LEFTUP_MASK 0x80 #define AVRC_PF_LEFTUP_OFF 0 -#define AVRC_PF_LEFTUP_SUPPORTED(x) \ - ((x)[AVRC_PF_LEFTUP_OFF] & AVRC_PF_LEFTUP_MASK) +#define AVRC_PF_LEFTUP_SUPPORTED(x) ((x)[AVRC_PF_LEFTUP_OFF] & AVRC_PF_LEFTUP_MASK) #define AVRC_PF_LEFTDOWN_BIT_NO 8 #define AVRC_PF_LEFTDOWN_MASK 0x01 #define AVRC_PF_LEFTDOWN_OFF 1 -#define AVRC_PF_LEFTDOWN_SUPPORTED(x) \ - ((x)[AVRC_PF_LEFTDOWN_OFF] & AVRC_PF_LEFTDOWN_MASK) +#define AVRC_PF_LEFTDOWN_SUPPORTED(x) ((x)[AVRC_PF_LEFTDOWN_OFF] & AVRC_PF_LEFTDOWN_MASK) #define AVRC_PF_ROOT_MENU_BIT_NO 9 #define AVRC_PF_ROOT_MENU_MASK 0x02 #define AVRC_PF_ROOT_MENU_OFF 1 -#define AVRC_PF_ROOT_MENU_SUPPORTED(x) \ - ((x)[AVRC_PF_ROOT_MENU_OFF] & AVRC_PF_ROOT_MENU_MASK) +#define AVRC_PF_ROOT_MENU_SUPPORTED(x) ((x)[AVRC_PF_ROOT_MENU_OFF] & AVRC_PF_ROOT_MENU_MASK) #define AVRC_PF_SETUP_MENU_BIT_NO 10 #define AVRC_PF_SETUP_MENU_MASK 0x04 #define AVRC_PF_SETUP_MENU_OFF 1 -#define AVRC_PF_SETUP_MENU_SUPPORTED(x) \ - ((x)[AVRC_PF_SETUP_MENU_OFF] & AVRC_PF_SETUP_MENU_MASK) +#define AVRC_PF_SETUP_MENU_SUPPORTED(x) ((x)[AVRC_PF_SETUP_MENU_OFF] & AVRC_PF_SETUP_MENU_MASK) #define AVRC_PF_CONTENTS_MENU_BIT_NO 11 #define AVRC_PF_CONTENTS_MENU_MASK 0x08 @@ -620,38 +612,32 @@ typedef uint8_t tAVRC_UID[AVRC_UID_SIZE]; #define AVRC_PF_CHNL_UP_BIT_NO 27 #define AVRC_PF_CHNL_UP_MASK 0x08 #define AVRC_PF_CHNL_UP_OFF 3 -#define AVRC_PF_CHNL_UP_SUPPORTED(x) \ - ((x)[AVRC_PF_CHNL_UP_OFF] & AVRC_PF_CHNL_UP_MASK) +#define AVRC_PF_CHNL_UP_SUPPORTED(x) ((x)[AVRC_PF_CHNL_UP_OFF] & AVRC_PF_CHNL_UP_MASK) #define AVRC_PF_CHNL_DOWN_BIT_NO 28 #define AVRC_PF_CHNL_DOWN_MASK 0x10 #define AVRC_PF_CHNL_DOWN_OFF 3 -#define AVRC_PF_CHNL_DOWN_SUPPORTED(x) \ - ((x)[AVRC_PF_CHNL_DOWN_OFF] & AVRC_PF_CHNL_DOWN_MASK) +#define AVRC_PF_CHNL_DOWN_SUPPORTED(x) ((x)[AVRC_PF_CHNL_DOWN_OFF] & AVRC_PF_CHNL_DOWN_MASK) #define AVRC_PF_PREV_CHNL_BIT_NO 29 #define AVRC_PF_PREV_CHNL_MASK 0x20 #define AVRC_PF_PREV_CHNL_OFF 3 -#define AVRC_PF_PREV_CHNL_SUPPORTED(x) \ - ((x)[AVRC_PF_PREV_CHNL_OFF] & AVRC_PF_PREV_CHNL_MASK) +#define AVRC_PF_PREV_CHNL_SUPPORTED(x) ((x)[AVRC_PF_PREV_CHNL_OFF] & AVRC_PF_PREV_CHNL_MASK) #define AVRC_PF_SOUND_SEL_BIT_NO 30 #define AVRC_PF_SOUND_SEL_MASK 0x40 #define AVRC_PF_SOUND_SEL_OFF 3 -#define AVRC_PF_SOUND_SEL_SUPPORTED(x) \ - ((x)[AVRC_PF_SOUND_SEL_OFF] & AVRC_PF_SOUND_SEL_MASK) +#define AVRC_PF_SOUND_SEL_SUPPORTED(x) ((x)[AVRC_PF_SOUND_SEL_OFF] & AVRC_PF_SOUND_SEL_MASK) #define AVRC_PF_INPUT_SEL_BIT_NO 31 #define AVRC_PF_INPUT_SEL_MASK 0x80 #define AVRC_PF_INPUT_SEL_OFF 3 -#define AVRC_PF_INPUT_SEL_SUPPORTED(x) \ - ((x)[AVRC_PF_INPUT_SEL_OFF] & AVRC_PF_INPUT_SEL_MASK) +#define AVRC_PF_INPUT_SEL_SUPPORTED(x) ((x)[AVRC_PF_INPUT_SEL_OFF] & AVRC_PF_INPUT_SEL_MASK) #define AVRC_PF_DISP_INFO_BIT_NO 32 #define AVRC_PF_DISP_INFO_MASK 0x01 #define AVRC_PF_DISP_INFO_OFF 4 -#define AVRC_PF_DISP_INFO_SUPPORTED(x) \ - ((x)[AVRC_PF_DISP_INFO_OFF] & AVRC_PF_DISP_INFO_MASK) +#define AVRC_PF_DISP_INFO_SUPPORTED(x) ((x)[AVRC_PF_DISP_INFO_OFF] & AVRC_PF_DISP_INFO_MASK) #define AVRC_PF_HELP_BIT_NO 33 #define AVRC_PF_HELP_MASK 0x02 @@ -661,14 +647,12 @@ typedef uint8_t tAVRC_UID[AVRC_UID_SIZE]; #define AVRC_PF_PAGE_UP_BIT_NO 34 #define AVRC_PF_PAGE_UP_MASK 0x04 #define AVRC_PF_PAGE_UP_OFF 4 -#define AVRC_PF_PAGE_UP_SUPPORTED(x) \ - ((x)[AVRC_PF_PAGE_UP_OFF] & AVRC_PF_PAGE_UP_MASK) +#define AVRC_PF_PAGE_UP_SUPPORTED(x) ((x)[AVRC_PF_PAGE_UP_OFF] & AVRC_PF_PAGE_UP_MASK) #define AVRC_PF_PAGE_DOWN_BIT_NO 35 #define AVRC_PF_PAGE_DOWN_MASK 0x08 #define AVRC_PF_PAGE_DOWN_OFF 4 -#define AVRC_PF_PAGE_DOWN_SUPPORTED(x) \ - ((x)[AVRC_PF_PAGE_DOWN_OFF] & AVRC_PF_PAGE_DOWN_MASK) +#define AVRC_PF_PAGE_DOWN_SUPPORTED(x) ((x)[AVRC_PF_PAGE_DOWN_OFF] & AVRC_PF_PAGE_DOWN_MASK) #define AVRC_PF_POWER_BIT_NO 36 #define AVRC_PF_POWER_MASK 0x10 @@ -678,14 +662,12 @@ typedef uint8_t tAVRC_UID[AVRC_UID_SIZE]; #define AVRC_PF_VOL_UP_BIT_NO 37 #define AVRC_PF_VOL_UP_MASK 0x20 #define AVRC_PF_VOL_UP_OFF 4 -#define AVRC_PF_VOL_UP_SUPPORTED(x) \ - ((x)[AVRC_PF_VOL_UP_OFF] & AVRC_PF_VOL_UP_MASK) +#define AVRC_PF_VOL_UP_SUPPORTED(x) ((x)[AVRC_PF_VOL_UP_OFF] & AVRC_PF_VOL_UP_MASK) #define AVRC_PF_VOL_DOWN_BIT_NO 38 #define AVRC_PF_VOL_DOWN_MASK 0x40 #define AVRC_PF_VOL_DOWN_OFF 4 -#define AVRC_PF_VOL_DOWN_SUPPORTED(x) \ - ((x)[AVRC_PF_VOL_DOWN_OFF] & AVRC_PF_VOL_DOWN_MASK) +#define AVRC_PF_VOL_DOWN_SUPPORTED(x) ((x)[AVRC_PF_VOL_DOWN_OFF] & AVRC_PF_VOL_DOWN_MASK) #define AVRC_PF_MUTE_BIT_NO 39 #define AVRC_PF_MUTE_MASK 0x80 @@ -710,20 +692,17 @@ typedef uint8_t tAVRC_UID[AVRC_UID_SIZE]; #define AVRC_PF_RECORD_BIT_NO 43 #define AVRC_PF_RECORD_MASK 0x08 #define AVRC_PF_RECORD_OFF 5 -#define AVRC_PF_RECORD_SUPPORTED(x) \ - ((x)[AVRC_PF_RECORD_OFF] & AVRC_PF_RECORD_MASK) +#define AVRC_PF_RECORD_SUPPORTED(x) ((x)[AVRC_PF_RECORD_OFF] & AVRC_PF_RECORD_MASK) #define AVRC_PF_REWIND_BIT_NO 44 #define AVRC_PF_REWIND_MASK 0x10 #define AVRC_PF_REWIND_OFF 5 -#define AVRC_PF_REWIND_SUPPORTED(x) \ - ((x)[AVRC_PF_REWIND_OFF] & AVRC_PF_REWIND_MASK) +#define AVRC_PF_REWIND_SUPPORTED(x) ((x)[AVRC_PF_REWIND_OFF] & AVRC_PF_REWIND_MASK) #define AVRC_PF_FAST_FWD_BIT_NO 45 #define AVRC_PF_FAST_FWD_MASK 0x20 #define AVRC_PF_FAST_FWD_OFF 5 -#define AVRC_PF_FAST_FWD_SUPPORTED(x) \ - ((x)[AVRC_PF_FAST_FWD_OFF] & AVRC_PF_FAST_FWD_MASK) +#define AVRC_PF_FAST_FWD_SUPPORTED(x) ((x)[AVRC_PF_FAST_FWD_OFF] & AVRC_PF_FAST_FWD_MASK) #define AVRC_PF_EJECT_BIT_NO 46 #define AVRC_PF_EJECT_MASK 0x40 @@ -733,14 +712,12 @@ typedef uint8_t tAVRC_UID[AVRC_UID_SIZE]; #define AVRC_PF_FORWARD_BIT_NO 47 #define AVRC_PF_FORWARD_MASK 0x80 #define AVRC_PF_FORWARD_OFF 5 -#define AVRC_PF_FORWARD_SUPPORTED(x) \ - ((x)[AVRC_PF_FORWARD_OFF] & AVRC_PF_FORWARD_MASK) +#define AVRC_PF_FORWARD_SUPPORTED(x) ((x)[AVRC_PF_FORWARD_OFF] & AVRC_PF_FORWARD_MASK) #define AVRC_PF_BACKWARD_BIT_NO 48 #define AVRC_PF_BACKWARD_MASK 0x01 #define AVRC_PF_BACKWARD_OFF 6 -#define AVRC_PF_BACKWARD_SUPPORTED(x) \ - ((x)[AVRC_PF_BACKWARD_OFF] & AVRC_PF_BACKWARD_MASK) +#define AVRC_PF_BACKWARD_SUPPORTED(x) ((x)[AVRC_PF_BACKWARD_OFF] & AVRC_PF_BACKWARD_MASK) #define AVRC_PF_ANGLE_BIT_NO 49 #define AVRC_PF_ANGLE_MASK 0x02 @@ -750,8 +727,7 @@ typedef uint8_t tAVRC_UID[AVRC_UID_SIZE]; #define AVRC_PF_SUBPICTURE_BIT_NO 50 #define AVRC_PF_SUBPICTURE_MASK 0x04 #define AVRC_PF_SUBPICTURE_OFF 6 -#define AVRC_PF_SUBPICTURE_SUPPORTED(x) \ - ((x)[AVRC_PF_SUBPICTURE_OFF] & AVRC_PF_SUBPICTURE_MASK) +#define AVRC_PF_SUBPICTURE_SUPPORTED(x) ((x)[AVRC_PF_SUBPICTURE_OFF] & AVRC_PF_SUBPICTURE_MASK) #define AVRC_PF_F1_BIT_NO 51 #define AVRC_PF_F1_MASK 0x08 @@ -782,62 +758,54 @@ typedef uint8_t tAVRC_UID[AVRC_UID_SIZE]; #define AVRC_PF_VENDOR_BIT_NO 56 #define AVRC_PF_VENDOR_MASK 0x01 #define AVRC_PF_VENDOR_OFF 7 -#define AVRC_PF_VENDOR_SUPPORTED(x) \ - ((x)[AVRC_PF_VENDOR_OFF] & AVRC_PF_VENDOR_MASK) +#define AVRC_PF_VENDOR_SUPPORTED(x) ((x)[AVRC_PF_VENDOR_OFF] & AVRC_PF_VENDOR_MASK) /* Basic Group Navigation. This overrules the SDP entry as it is set per * player.7 */ #define AVRC_PF_GROUP_NAVI_BIT_NO 57 #define AVRC_PF_GROUP_NAVI_MASK 0x02 #define AVRC_PF_GROUP_NAVI_OFF 7 -#define AVRC_PF_GROUP_NAVI_SUPPORTED(x) \ - ((x)[AVRC_PF_GROUP_NAVI_OFF] & AVRC_PF_GROUP_NAVI_MASK) +#define AVRC_PF_GROUP_NAVI_SUPPORTED(x) ((x)[AVRC_PF_GROUP_NAVI_OFF] & AVRC_PF_GROUP_NAVI_MASK) /* Advanced Control Player. This bit is set if the player supports at least * AVRCP 1.4. */ #define AVRC_PF_ADV_CTRL_BIT_NO 58 #define AVRC_PF_ADV_CTRL_MASK 0x04 #define AVRC_PF_ADV_CTRL_OFF 7 -#define AVRC_PF_ADV_CTRL_SUPPORTED(x) \ - ((x)[AVRC_PF_ADV_CTRL_OFF] & AVRC_PF_ADV_CTRL_MASK) +#define AVRC_PF_ADV_CTRL_SUPPORTED(x) ((x)[AVRC_PF_ADV_CTRL_OFF] & AVRC_PF_ADV_CTRL_MASK) /* Browsing. This bit is set if the player supports browsing. */ #define AVRC_PF_BROWSE_BIT_NO 59 #define AVRC_PF_BROWSE_MASK 0x08 #define AVRC_PF_BROWSE_OFF 7 -#define AVRC_PF_BROWSE_SUPPORTED(x) \ - ((x)[AVRC_PF_BROWSE_OFF] & AVRC_PF_BROWSE_MASK) +#define AVRC_PF_BROWSE_SUPPORTED(x) ((x)[AVRC_PF_BROWSE_OFF] & AVRC_PF_BROWSE_MASK) /* Searching. This bit is set if the player supports searching. */ #define AVRC_PF_SEARCH_BIT_NO 60 #define AVRC_PF_SEARCH_MASK 0x10 #define AVRC_PF_SEARCH_OFF 7 -#define AVRC_PF_SEARCH_SUPPORTED(x) \ - ((x)[AVRC_PF_SEARCH_OFF] & AVRC_PF_SEARCH_MASK) +#define AVRC_PF_SEARCH_SUPPORTED(x) ((x)[AVRC_PF_SEARCH_OFF] & AVRC_PF_SEARCH_MASK) /* AddToNowPlaying. This bit is set if the player supports the AddToNowPlaying * command. */ #define AVRC_PF_ADD2NOWPLAY_BIT_NO 61 #define AVRC_PF_ADD2NOWPLAY_MASK 0x20 #define AVRC_PF_ADD2NOWPLAY_OFF 7 -#define AVRC_PF_ADD2NOWPLAY_SUPPORTED(x) \ - ((x)[AVRC_PF_ADD2NOWPLAY_OFF] & AVRC_PF_ADD2NOWPLAY_MASK) +#define AVRC_PF_ADD2NOWPLAY_SUPPORTED(x) ((x)[AVRC_PF_ADD2NOWPLAY_OFF] & AVRC_PF_ADD2NOWPLAY_MASK) /* UIDs unique in player browse tree. This bit is set if the player is able to * maintain unique UIDs across the player browse tree. */ #define AVRC_PF_UID_UNIQUE_BIT_NO 62 #define AVRC_PF_UID_UNIQUE_MASK 0x40 #define AVRC_PF_UID_UNIQUE_OFF 7 -#define AVRC_PF_UID_UNIQUE_SUPPORTED(x) \ - ((x)[AVRC_PF_UID_UNIQUE_OFF] & AVRC_PF_UID_UNIQUE_MASK) +#define AVRC_PF_UID_UNIQUE_SUPPORTED(x) ((x)[AVRC_PF_UID_UNIQUE_OFF] & AVRC_PF_UID_UNIQUE_MASK) /* OnlyBrowsableWhenAddressed. This bit is set if the player is only able to be * browsed when it is set as the Addressed Player. */ #define AVRC_PF_BR_WH_ADDR_BIT_NO 63 #define AVRC_PF_BR_WH_ADDR_MASK 0x80 #define AVRC_PF_BR_WH_ADDR_OFF 7 -#define AVRC_PF_BR_WH_ADDR_SUPPORTED(x) \ - ((x)[AVRC_PF_BR_WH_ADDR_OFF] & AVRC_PF_BR_WH_ADDR_MASK) +#define AVRC_PF_BR_WH_ADDR_SUPPORTED(x) ((x)[AVRC_PF_BR_WH_ADDR_OFF] & AVRC_PF_BR_WH_ADDR_MASK) /* OnlySearchableWhenAddressed. This bit is set if the player is only able to * be searched when it is set as the Addressed player. */ @@ -852,16 +820,14 @@ typedef uint8_t tAVRC_UID[AVRC_UID_SIZE]; #define AVRC_PF_NOW_PLAY_BIT_NO 65 #define AVRC_PF_NOW_PLAY_MASK 0x02 #define AVRC_PF_NOW_PLAY_OFF 8 -#define AVRC_PF_NOW_PLAY_SUPPORTED(x) \ - ((x)[AVRC_PF_NOW_PLAY_OFF] & AVRC_PF_NOW_PLAY_MASK) +#define AVRC_PF_NOW_PLAY_SUPPORTED(x) ((x)[AVRC_PF_NOW_PLAY_OFF] & AVRC_PF_NOW_PLAY_MASK) /* UIDPersistency. This bit is set if the Player is able to persist UID values * between AVRCP Browse Reconnect */ #define AVRC_PF_UID_PERSIST_BIT_NO 66 #define AVRC_PF_UID_PERSIST_MASK 0x04 #define AVRC_PF_UID_PERSIST_OFF 8 -#define AVRC_PF_UID_PERSIST_SUPPORTED(x) \ - ((x)[AVRC_PF_UID_PERSIST_OFF] & AVRC_PF_UID_PERSIST_MASK) +#define AVRC_PF_UID_PERSIST_SUPPORTED(x) ((x)[AVRC_PF_UID_PERSIST_OFF] & AVRC_PF_UID_PERSIST_MASK) /* NumberOfItems. This bit is set if player supports the GetTotalNumberOfItems * browsing command. */ @@ -881,10 +847,10 @@ This structure contains the header parameters of an AV/C message. typedef struct { uint8_t ctype; /* Command type. */ uint8_t subunit_type; /* Subunit type. */ - uint8_t subunit_id; /* Subunit ID. This value is typically ignored in AVRCP, - * except for VENDOR DEPENDENT messages when the value is - * vendor-dependent. Value range is 0-7. */ - uint8_t opcode; /* Op Code (passthrough, vendor, etc) */ + uint8_t subunit_id; /* Subunit ID. This value is typically ignored in AVRCP, + * except for VENDOR DEPENDENT messages when the value is + * vendor-dependent. Value range is 0-7. */ + uint8_t opcode; /* Op Code (passthrough, vendor, etc) */ } tAVRC_HDR; /* This structure contains a UNIT INFO message. */ @@ -939,8 +905,8 @@ typedef struct { * hdr.subunit_id Unused. */ uint8_t* p_browse_data; /* Pointer to data. */ uint16_t browse_len; /* Length in bytes of data. */ - BT_HDR* p_browse_pkt; /* The GKI buffer received. Set to NULL, if the callback - function wants to keep the buffer */ + BT_HDR* p_browse_pkt; /* The GKI buffer received. Set to NULL, if the callback + function wants to keep the buffer */ } tAVRC_MSG_BROWSE; /* This is a union of all message type structures. */ @@ -954,33 +920,23 @@ typedef union { } tAVRC_MSG; /* macros */ -#define AVRC_IS_VALID_CAP_ID(a) \ - ((((a) == AVRC_CAP_COMPANY_ID) || ((a) == AVRC_CAP_EVENTS_SUPPORTED)) \ - ? true \ - : false) - -#define AVRC_IS_VALID_EVENT_ID(a) \ - ((((a) >= AVRC_EVT_PLAY_STATUS_CHANGE) && ((a) <= AVRC_EVT_VOLUME_CHANGE)) \ - ? true \ - : false) - -#define AVRC_IS_VALID_ATTRIBUTE(a) \ - ((((((a) > 0) && (a) <= AVRC_PLAYER_SETTING_SCAN)) || \ - ((a) >= AVRC_PLAYER_SETTING_LOW_MENU_EXT)) \ - ? true \ - : false) - -#define AVRC_IS_VALID_MEDIA_ATTRIBUTE(a) \ - (((a) >= AVRC_MEDIA_ATTR_ID_TITLE) && \ - ((a) <= AVRC_MAX_NUM_MEDIA_ATTR_ID) \ - ? true \ - : false) - -#define AVRC_IS_VALID_BATTERY_STATUS(a) \ - (((a) <= AVRC_BATTERY_STATUS_FULL_CHARGE) ? true : false) - -#define AVRC_IS_VALID_SYSTEM_STATUS(a) \ - (((a) <= AVRC_SYSTEMSTATE_PWR_UNPLUGGED) ? true : false) +#define AVRC_IS_VALID_CAP_ID(a) \ + ((((a) == AVRC_CAP_COMPANY_ID) || ((a) == AVRC_CAP_EVENTS_SUPPORTED)) ? true : false) + +#define AVRC_IS_VALID_EVENT_ID(a) \ + ((((a) >= AVRC_EVT_PLAY_STATUS_CHANGE) && ((a) <= AVRC_EVT_VOLUME_CHANGE)) ? true : false) + +#define AVRC_IS_VALID_ATTRIBUTE(a) \ + ((((((a) > 0) && (a) <= AVRC_PLAYER_SETTING_SCAN)) || ((a) >= AVRC_PLAYER_SETTING_LOW_MENU_EXT)) \ + ? true \ + : false) + +#define AVRC_IS_VALID_MEDIA_ATTRIBUTE(a) \ + (((a) >= AVRC_MEDIA_ATTR_ID_TITLE) && ((a) <= AVRC_MAX_NUM_MEDIA_ATTR_ID) ? true : false) + +#define AVRC_IS_VALID_BATTERY_STATUS(a) (((a) <= AVRC_BATTERY_STATUS_FULL_CHARGE) ? true : false) + +#define AVRC_IS_VALID_SYSTEM_STATUS(a) (((a) <= AVRC_SYSTEMSTATE_PWR_UNPLUGGED) ? true : false) #define AVRC_IS_VALID_GROUP(a) (((a) <= AVRC_PDU_PREV_GROUP) ? true : false) @@ -1048,16 +1004,16 @@ typedef struct { typedef uint8_t tAVRC_FEATURE_MASK[AVRC_FEATURE_MASK_SIZE]; typedef struct { - uint16_t player_id; /* A unique identifier for this media player.*/ - uint8_t major_type; /* Use AVRC_MJ_TYPE_AUDIO, AVRC_MJ_TYPE_VIDEO, - AVRC_MJ_TYPE_BC_AUDIO, or AVRC_MJ_TYPE_BC_VIDEO.*/ - uint32_t sub_type; /* Use AVRC_SUB_TYPE_NONE, AVRC_SUB_TYPE_AUDIO_BOOK, or - AVRC_SUB_TYPE_PODCAST*/ - uint8_t play_status; /* Use AVRC_PLAYSTATE_STOPPED, AVRC_PLAYSTATE_PLAYING, - AVRC_PLAYSTATE_PAUSED, AVRC_PLAYSTATE_FWD_SEEK, - AVRC_PLAYSTATE_REV_SEEK, or AVRC_PLAYSTATE_ERROR*/ + uint16_t player_id; /* A unique identifier for this media player.*/ + uint8_t major_type; /* Use AVRC_MJ_TYPE_AUDIO, AVRC_MJ_TYPE_VIDEO, + AVRC_MJ_TYPE_BC_AUDIO, or AVRC_MJ_TYPE_BC_VIDEO.*/ + uint32_t sub_type; /* Use AVRC_SUB_TYPE_NONE, AVRC_SUB_TYPE_AUDIO_BOOK, or + AVRC_SUB_TYPE_PODCAST*/ + uint8_t play_status; /* Use AVRC_PLAYSTATE_STOPPED, AVRC_PLAYSTATE_PLAYING, + AVRC_PLAYSTATE_PAUSED, AVRC_PLAYSTATE_FWD_SEEK, + AVRC_PLAYSTATE_REV_SEEK, or AVRC_PLAYSTATE_ERROR*/ tAVRC_FEATURE_MASK features; /* Supported feature bit mask*/ - tAVRC_FULL_NAME name; /* The player name, name length and character set id.*/ + tAVRC_FULL_NAME name; /* The player name, name length and character set id.*/ } tAVRC_ITEM_PLAYER; typedef struct { @@ -1071,26 +1027,23 @@ typedef struct { } tAVRC_ITEM_FOLDER; typedef struct { - uint32_t - attr_id; /* Use AVRC_MEDIA_ATTR_ID_TITLE, AVRC_MEDIA_ATTR_ID_ARTIST, - AVRC_MEDIA_ATTR_ID_ALBUM, - AVRC_MEDIA_ATTR_ID_TRACK_NUM, AVRC_MEDIA_ATTR_ID_NUM_TRACKS, - AVRC_MEDIA_ATTR_ID_GENRE, AVRC_MEDIA_ATTR_ID_PLAYING_TIME */ - tAVRC_FULL_NAME - name; /* The attribute value, value length and character set id. */ + uint32_t attr_id; /* Use AVRC_MEDIA_ATTR_ID_TITLE, AVRC_MEDIA_ATTR_ID_ARTIST, + AVRC_MEDIA_ATTR_ID_ALBUM, + AVRC_MEDIA_ATTR_ID_TRACK_NUM, AVRC_MEDIA_ATTR_ID_NUM_TRACKS, + AVRC_MEDIA_ATTR_ID_GENRE, AVRC_MEDIA_ATTR_ID_PLAYING_TIME */ + tAVRC_FULL_NAME name; /* The attribute value, value length and character set id. */ } tAVRC_ATTR_ENTRY; typedef struct { - tAVRC_UID uid; /* The uid of this media element item */ - uint8_t type; /* Use AVRC_MEDIA_TYPE_AUDIO or AVRC_MEDIA_TYPE_VIDEO. */ - tAVRC_FULL_NAME name; /* The media name, name length and character set id. */ - uint8_t attr_count; /* The number of attributes in p_attr_list */ + tAVRC_UID uid; /* The uid of this media element item */ + uint8_t type; /* Use AVRC_MEDIA_TYPE_AUDIO or AVRC_MEDIA_TYPE_VIDEO. */ + tAVRC_FULL_NAME name; /* The media name, name length and character set id. */ + uint8_t attr_count; /* The number of attributes in p_attr_list */ tAVRC_ATTR_ENTRY* p_attr_list; /* Attribute entry list. */ } tAVRC_ITEM_MEDIA; typedef struct { - uint8_t - item_type; /* AVRC_ITEM_PLAYER, AVRC_ITEM_FOLDER, or AVRC_ITEM_MEDIA */ + uint8_t item_type; /* AVRC_ITEM_PLAYER, AVRC_ITEM_FOLDER, or AVRC_ITEM_MEDIA */ union { tAVRC_ITEM_PLAYER player; /* The properties of a media player item.*/ tAVRC_ITEM_FOLDER folder; /* The properties of a folder item.*/ diff --git a/system/stack/include/ble_acl_interface.h b/system/stack/include/ble_acl_interface.h index c5b6be85eca..c9d76c3bfec 100644 --- a/system/stack/include/ble_acl_interface.h +++ b/system/stack/include/ble_acl_interface.h @@ -23,28 +23,23 @@ #include "types/hci_role.h" #include "types/raw_address.h" -void acl_ble_enhanced_connection_complete( - const tBLE_BD_ADDR& address_with_type, uint16_t handle, tHCI_ROLE role, - bool match, uint16_t conn_interval, uint16_t conn_latency, - uint16_t conn_timeout, const RawAddress& local_rpa, - const RawAddress& peer_rpa, tBLE_ADDR_TYPE peer_addr_type, - bool can_read_discoverable_characteristics); +void acl_ble_enhanced_connection_complete(const tBLE_BD_ADDR& address_with_type, uint16_t handle, + tHCI_ROLE role, bool match, uint16_t conn_interval, + uint16_t conn_latency, uint16_t conn_timeout, + const RawAddress& local_rpa, const RawAddress& peer_rpa, + tBLE_ADDR_TYPE peer_addr_type, + bool can_read_discoverable_characteristics); void acl_ble_enhanced_connection_complete_from_shim( - const tBLE_BD_ADDR& address_with_type, uint16_t handle, tHCI_ROLE role, - uint16_t conn_interval, uint16_t conn_latency, uint16_t conn_timeout, - const RawAddress& local_rpa, const RawAddress& peer_rpa, - tBLE_ADDR_TYPE peer_addr_type, bool can_read_discoverable_characteristics); -void acl_ble_connection_fail(const tBLE_BD_ADDR& address_with_type, - uint16_t handle, bool enhanced, + const tBLE_BD_ADDR& address_with_type, uint16_t handle, tHCI_ROLE role, + uint16_t conn_interval, uint16_t conn_latency, uint16_t conn_timeout, + const RawAddress& local_rpa, const RawAddress& peer_rpa, tBLE_ADDR_TYPE peer_addr_type, + bool can_read_discoverable_characteristics); +void acl_ble_connection_fail(const tBLE_BD_ADDR& address_with_type, uint16_t handle, bool enhanced, tHCI_STATUS status); -void acl_ble_update_event_received(tHCI_STATUS status, uint16_t handle, - uint16_t interval, uint16_t latency, - uint16_t timeout); -void acl_ble_update_request_event_received(uint16_t handle, - uint16_t interval_min, - uint16_t interval_max, - uint16_t latency, uint16_t timeout); -void acl_ble_data_length_change_event(uint16_t handle, uint16_t max_tx_octets, - uint16_t max_tx_time, - uint16_t max_rx_octets, - uint16_t max_rx_time); +void acl_ble_update_event_received(tHCI_STATUS status, uint16_t handle, uint16_t interval, + uint16_t latency, uint16_t timeout); +void acl_ble_update_request_event_received(uint16_t handle, uint16_t interval_min, + uint16_t interval_max, uint16_t latency, + uint16_t timeout); +void acl_ble_data_length_change_event(uint16_t handle, uint16_t max_tx_octets, uint16_t max_tx_time, + uint16_t max_rx_octets, uint16_t max_rx_time); diff --git a/system/stack/include/ble_hci_link_interface.h b/system/stack/include/ble_hci_link_interface.h index cedc7cb2d9d..068368bfb6d 100644 --- a/system/stack/include/ble_hci_link_interface.h +++ b/system/stack/include/ble_hci_link_interface.h @@ -26,8 +26,7 @@ void btm_ble_read_remote_features_complete(uint8_t* p, uint8_t length); void btm_ble_write_adv_enable_complete(uint8_t* p, uint16_t evt_len); void btm_ble_ltk_request(uint16_t handle, uint8_t rand[8], uint16_t ediv); void btm_ble_test_command_complete(uint8_t* p); -void btm_ble_read_resolving_list_entry_complete(const uint8_t* p, - uint16_t evt_len); +void btm_ble_read_resolving_list_entry_complete(const uint8_t* p, uint16_t evt_len); void btm_ble_remove_resolving_list_entry_complete(uint8_t* p, uint16_t evt_len); void btm_ble_add_resolving_list_entry_complete(uint8_t* p, uint16_t evt_len); void btm_ble_clear_resolving_list_complete(uint8_t* p, uint16_t evt_len); diff --git a/system/stack/include/ble_scanner.h b/system/stack/include/ble_scanner.h index bd2011a63b6..82d532ab086 100644 --- a/system/stack/include/ble_scanner.h +++ b/system/stack/include/ble_scanner.h @@ -25,8 +25,7 @@ #include "btm_ble_api.h" using status_cb = base::Callback; -using handle_cb = - base::Callback; +using handle_cb = base::Callback; // methods we expose to c code: void btm_ble_scanner_cleanup(void); @@ -35,7 +34,7 @@ void btm_ble_scanner_init(); class BleScannerHciInterface; class BleScanningManager { - public: +public: virtual ~BleScanningManager() = default; static void Initialize(BleScannerHciInterface* interface); @@ -43,37 +42,26 @@ class BleScanningManager { static bool IsInitialized(); static base::WeakPtr Get(); - virtual void PeriodicScanStart(uint8_t options, uint8_t set_id, - uint8_t adv_addr_type, + virtual void PeriodicScanStart(uint8_t options, uint8_t set_id, uint8_t adv_addr_type, const RawAddress& adv_addr, uint16_t skip_num, - uint16_t sync_timeout, - uint8_t sync_cte_type) = 0; + uint16_t sync_timeout, uint8_t sync_cte_type) = 0; virtual void PeriodicScanCancelStart(/*status_cb command_complete*/) = 0; virtual void PeriodicScanTerminate(uint16_t sync_handle/*, status_cb command_complete*/) = 0; - virtual void PeriodicAdvSyncTransfer(const RawAddress& bd_addr, - uint16_t service_data, - uint16_t sync_handle, - handle_cb command_complete) = 0; - virtual void PeriodicAdvSetInfoTransfer(const RawAddress& bd_addr, - uint16_t service_data, - uint8_t adv_handle, - handle_cb command_complete) = 0; - virtual void SetPeriodicAdvSyncTransferParams(const RawAddress& bd_addr, - uint8_t mode, uint16_t skip, - uint16_t sync_timeout, - uint8_t cte_type, - bool set_defaults, + virtual void PeriodicAdvSyncTransfer(const RawAddress& bd_addr, uint16_t service_data, + uint16_t sync_handle, handle_cb command_complete) = 0; + virtual void PeriodicAdvSetInfoTransfer(const RawAddress& bd_addr, uint16_t service_data, + uint8_t adv_handle, handle_cb command_complete) = 0; + virtual void SetPeriodicAdvSyncTransferParams(const RawAddress& bd_addr, uint8_t mode, + uint16_t skip, uint16_t sync_timeout, + uint8_t cte_type, bool set_defaults, status_cb command_complete) = 0; - virtual void OnPeriodicScanResult(uint16_t sync_handle, uint8_t tx_power, - int8_t rssi, uint8_t cte_type, - uint8_t pkt_data_status, - uint8_t pkt_data_len, + virtual void OnPeriodicScanResult(uint16_t sync_handle, uint8_t tx_power, int8_t rssi, + uint8_t cte_type, uint8_t pkt_data_status, uint8_t pkt_data_len, const uint8_t* pkt_data) = 0; - virtual void OnPeriodicScanEstablished(uint8_t status, uint16_t sync_handle, - uint8_t set_id, uint8_t adv_addr_type, - const RawAddress& adv_addr, + virtual void OnPeriodicScanEstablished(uint8_t status, uint16_t sync_handle, uint8_t set_id, + uint8_t adv_addr_type, const RawAddress& adv_addr, uint8_t adv_phy, uint16_t adv_interval, uint8_t adv_clock_accuracy) = 0; virtual void OnPeriodicScanLost(uint16_t sync_handle) = 0; diff --git a/system/stack/include/bnep_api.h b/system/stack/include/bnep_api.h index c02adf237d3..48ed80ab22d 100644 --- a/system/stack/include/bnep_api.h +++ b/system/stack/include/bnep_api.h @@ -40,7 +40,7 @@ * sending BNEP packets. Note, we are currently not sending * extension headers, but may in the future, so allow * space for them -*/ + */ #define BNEP_MINIMUM_OFFSET (15 + L2CAP_MIN_OFFSET) #define BNEP_INVALID_HANDLE 0xFFFF @@ -49,12 +49,12 @@ ****************************************************************************/ /* Define the result codes from BNEP -*/ + */ enum { BNEP_SUCCESS, /* Success */ BNEP_CONN_DISCONNECTED, /* Connection terminated */ BNEP_NO_RESOURCES, /* No resources */ - BNEP_MTU_EXCEDED, /* Attempt to write long data */ + BNEP_MTU_EXCEEDED, /* Attempt to write long data */ BNEP_INVALID_OFFSET, /* Insufficient offset in GKI buffer */ BNEP_CONN_FAILED, /* Connection failed */ BNEP_CONN_FAILED_CFG, /* Connection failed cos of config */ @@ -85,20 +85,19 @@ typedef uint8_t tBNEP_RESULT; * BNEP_SUCCESS indicates connection is success * All values are used to indicate the reason for failure * Flag to indicate if it is just a role change -*/ -typedef void(tBNEP_CONN_STATE_CB)(uint16_t handle, const RawAddress& rem_bda, - tBNEP_RESULT result, bool is_role_change); + */ +typedef void(tBNEP_CONN_STATE_CB)(uint16_t handle, const RawAddress& rem_bda, tBNEP_RESULT result, + bool is_role_change); /* Connection indication callback prototype. Parameters are * BD Address of remote, remote UUID and local UUID * and flag to indicate role change and handle to the connection * When BNEP calls this function profile should * use BNEP_ConnectResp call to accept or reject the request -*/ + */ typedef void(tBNEP_CONNECT_IND_CB)(uint16_t handle, const RawAddress& bd_addr, const bluetooth::Uuid& remote_uuid, - const bluetooth::Uuid& local_uuid, - bool is_role_change); + const bluetooth::Uuid& local_uuid, bool is_role_change); /* Data buffer received indication callback prototype. Parameters are * Handle to the connection @@ -109,9 +108,8 @@ typedef void(tBNEP_CONNECT_IND_CB)(uint16_t handle, const RawAddress& bd_addr, * Flag to indicate whether extension headers to be forwarded are * present */ -typedef void(tBNEP_DATA_BUF_CB)(uint16_t handle, const RawAddress& src, - const RawAddress& dst, uint16_t protocol, - BT_HDR* p_buf, bool fw_ext_present); +typedef void(tBNEP_DATA_BUF_CB)(uint16_t handle, const RawAddress& src, const RawAddress& dst, + uint16_t protocol, BT_HDR* p_buf, bool fw_ext_present); /* Data received indication callback prototype. Parameters are * Handle to the connection @@ -123,15 +121,14 @@ typedef void(tBNEP_DATA_BUF_CB)(uint16_t handle, const RawAddress& src, * Flag to indicate whether extension headers to be forwarded are * present */ -typedef void(tBNEP_DATA_IND_CB)(uint16_t handle, const RawAddress& src, - const RawAddress& dst, uint16_t protocol, - uint8_t* p_data, uint16_t len, +typedef void(tBNEP_DATA_IND_CB)(uint16_t handle, const RawAddress& src, const RawAddress& dst, + uint16_t protocol, uint8_t* p_data, uint16_t len, bool fw_ext_present); /* Flow control callback for TX data. Parameters are * Handle to the connection * Event flow status -*/ + */ typedef void(tBNEP_TX_DATA_FLOW_CB)(uint16_t handle, tBNEP_RESULT event); /* Filters received indication callback prototype. Parameters are @@ -146,10 +143,9 @@ typedef void(tBNEP_TX_DATA_FLOW_CB)(uint16_t handle, tBNEP_RESULT event); * They will be present in big endian order. First * two bytes will be starting of the first range and * next two bytes will be ending of the range. -*/ -typedef void(tBNEP_FILTER_IND_CB)(uint16_t handle, bool indication, - tBNEP_RESULT result, uint16_t num_filters, - uint8_t* p_filters); + */ +typedef void(tBNEP_FILTER_IND_CB)(uint16_t handle, bool indication, tBNEP_RESULT result, + uint16_t num_filters, uint8_t* p_filters); /* Multicast Filters received indication callback prototype. Parameters are * Handle to the connection @@ -162,22 +158,19 @@ typedef void(tBNEP_FILTER_IND_CB)(uint16_t handle, bool indication, * of start of the range and end of the range. * First six bytes will be starting of the first range and * next six bytes will be ending of the range. -*/ -typedef void(tBNEP_MFILTER_IND_CB)(uint16_t handle, bool indication, - tBNEP_RESULT result, uint16_t num_mfilters, - uint8_t* p_mfilters); + */ +typedef void(tBNEP_MFILTER_IND_CB)(uint16_t handle, bool indication, tBNEP_RESULT result, + uint16_t num_mfilters, uint8_t* p_mfilters); /* This is the structure used by profile to register with BNEP */ typedef struct { - tBNEP_CONNECT_IND_CB* p_conn_ind_cb; /* To indicate the conn request */ - tBNEP_CONN_STATE_CB* p_conn_state_cb; /* To indicate conn state change */ - tBNEP_DATA_IND_CB* p_data_ind_cb; /* To pass the data received */ - tBNEP_DATA_BUF_CB* p_data_buf_cb; /* To pass the data buffer received */ + tBNEP_CONNECT_IND_CB* p_conn_ind_cb; /* To indicate the conn request */ + tBNEP_CONN_STATE_CB* p_conn_state_cb; /* To indicate conn state change */ + tBNEP_DATA_IND_CB* p_data_ind_cb; /* To pass the data received */ + tBNEP_DATA_BUF_CB* p_data_buf_cb; /* To pass the data buffer received */ tBNEP_TX_DATA_FLOW_CB* p_tx_data_flow_cb; /* data flow callback */ - tBNEP_FILTER_IND_CB* - p_filter_ind_cb; /* To indicate that peer set protocol filters */ - tBNEP_MFILTER_IND_CB* - p_mfilter_ind_cb; /* To indicate that peer set mcast filters */ + tBNEP_FILTER_IND_CB* p_filter_ind_cb; /* To indicate that peer set protocol filters */ + tBNEP_MFILTER_IND_CB* p_mfilter_ind_cb; /* To indicate that peer set mcast filters */ } tBNEP_REGISTER; @@ -231,24 +224,22 @@ void BNEP_Deregister(void); * BNEP_NO_RESOURCES if no resources * ******************************************************************************/ -tBNEP_RESULT BNEP_Connect(const RawAddress& p_rem_bda, - const bluetooth::Uuid& src_uuid, - const bluetooth::Uuid& dst_uuid, uint16_t* p_handle, - uint32_t mx_chan_id); +tBNEP_RESULT BNEP_Connect(const RawAddress& p_rem_bda, const bluetooth::Uuid& src_uuid, + const bluetooth::Uuid& dst_uuid, uint16_t* p_handle, uint32_t mx_chan_id); /******************************************************************************* * * Function BNEP_ConnectResp * - * Description This function is called in responce to connection indication + * Description This function is called in response to connection indication * * * Parameters: handle - handle given in the connection indication - * resp - responce for the connection indication + * resp - response for the connection indication * * Returns BNEP_SUCCESS if connection started * BNEP_WRONG_HANDLE if the connection is not found - * BNEP_WRONG_STATE if the responce is not expected + * BNEP_WRONG_STATE if the response is not expected * ******************************************************************************/ tBNEP_RESULT BNEP_ConnectResp(uint16_t handle, tBNEP_RESULT resp); @@ -282,16 +273,15 @@ tBNEP_RESULT BNEP_Disconnect(uint16_t handle); *BD Addr) fw_ext_present - forwarded extensions present * * Returns: BNEP_WRONG_HANDLE - if passed handle is not valid - * BNEP_MTU_EXCEDED - If the data length is greater + * BNEP_MTU_EXCEEDED - If the data length is greater * than MTU * BNEP_IGNORE_CMD - If the packet is filtered out * BNEP_Q_SIZE_EXCEEDED - If the Tx Q is full * BNEP_SUCCESS - If written successfully * ******************************************************************************/ -tBNEP_RESULT BNEP_WriteBuf(uint16_t handle, const RawAddress& dest_addr, - BT_HDR* p_buf, uint16_t protocol, - const RawAddress& src_addr, bool fw_ext_present); +tBNEP_RESULT BNEP_WriteBuf(uint16_t handle, const RawAddress& dest_addr, BT_HDR* p_buf, + uint16_t protocol, const RawAddress& src_addr, bool fw_ext_present); /******************************************************************************* * @@ -308,7 +298,7 @@ tBNEP_RESULT BNEP_WriteBuf(uint16_t handle, const RawAddress& dest_addr, *BD Addr) fw_ext_present - forwarded extensions present * * Returns: BNEP_WRONG_HANDLE - if passed handle is not valid - * BNEP_MTU_EXCEDED - If the data length is greater than + * BNEP_MTU_EXCEEDED - If the data length is greater than * the MTU * BNEP_IGNORE_CMD - If the packet is filtered out * BNEP_Q_SIZE_EXCEEDED - If the Tx Q is full @@ -316,9 +306,8 @@ tBNEP_RESULT BNEP_WriteBuf(uint16_t handle, const RawAddress& dest_addr, * BNEP_SUCCESS - If written successfully * ******************************************************************************/ -tBNEP_RESULT BNEP_Write(uint16_t handle, const RawAddress& dest_addr, - uint8_t* p_data, uint16_t len, uint16_t protocol, - const RawAddress& src_addr, bool fw_ext_present); +tBNEP_RESULT BNEP_Write(uint16_t handle, const RawAddress& dest_addr, uint8_t* p_data, uint16_t len, + uint16_t protocol, const RawAddress& src_addr, bool fw_ext_present); /******************************************************************************* * @@ -339,8 +328,7 @@ tBNEP_RESULT BNEP_Write(uint16_t handle, const RawAddress& dest_addr, * BNEP_SUCCESS - if request sent successfully * ******************************************************************************/ -tBNEP_RESULT BNEP_SetProtocolFilters(uint16_t handle, uint16_t num_filters, - uint16_t* p_start_array, +tBNEP_RESULT BNEP_SetProtocolFilters(uint16_t handle, uint16_t num_filters, uint16_t* p_start_array, uint16_t* p_end_array); /******************************************************************************* @@ -365,8 +353,7 @@ tBNEP_RESULT BNEP_SetProtocolFilters(uint16_t handle, uint16_t num_filters, * BNEP_SUCCESS - if request sent successfully * ******************************************************************************/ -tBNEP_RESULT BNEP_SetMulticastFilters(uint16_t handle, uint16_t num_filters, - uint8_t* p_start_array, +tBNEP_RESULT BNEP_SetMulticastFilters(uint16_t handle, uint16_t num_filters, uint8_t* p_start_array, uint8_t* p_end_array); /******************************************************************************* diff --git a/system/stack/include/bt_dev_class.h b/system/stack/include/bt_dev_class.h index a552ed19a31..1455f66fd22 100644 --- a/system/stack/include/bt_dev_class.h +++ b/system/stack/include/bt_dev_class.h @@ -99,8 +99,8 @@ inline constexpr DEV_CLASS kDevClassEmpty = {}; #define BTM_COD_SERVICE_CLASS_LO_B 0x00E0 #define BTM_COD_SERVICE_CLASS_MASK 0xFFE0 -inline constexpr DEV_CLASS kDevClassUnclassified = { - 0x00, BTM_COD_MAJOR_UNCLASSIFIED, BTM_COD_MINOR_UNCLASSIFIED}; +inline constexpr DEV_CLASS kDevClassUnclassified = {0x00, BTM_COD_MAJOR_UNCLASSIFIED, + BTM_COD_MINOR_UNCLASSIFIED}; /* class of device field macros */ #define BTM_COD_MINOR_CLASS(u8, pd) \ @@ -115,11 +115,11 @@ inline constexpr DEV_CLASS kDevClassUnclassified = { } /* to set the fields (assumes that format type is always 0) */ -#define FIELDS_TO_COD(pd, mn, mj, sv) \ - { \ - (pd)[2] = mn; \ - (pd)[1] = (mj) + ((sv)&BTM_COD_SERVICE_CLASS_LO_B); \ - (pd)[0] = (sv) >> 8; \ +#define FIELDS_TO_COD(pd, mn, mj, sv) \ + { \ + (pd)[2] = mn; \ + (pd)[1] = (mj) + ((sv) & BTM_COD_SERVICE_CLASS_LO_B); \ + (pd)[0] = (sv) >> 8; \ } inline std::string dev_class_text(const DEV_CLASS& dev_class) { @@ -140,9 +140,10 @@ inline std::string dev_class_text(const DEV_CLASS& dev_class) { *(p)++ = (a)[kDevClassLength - 1 - ijk]; \ } -#define STREAM_TO_DEVCLASS(a, p) \ - { \ - size_t ijk; \ - uint8_t* _pa = a.data() + kDevClassLength - 1; \ - for (ijk = 0; ijk < kDevClassLength; ijk++) *_pa-- = *(p)++; \ +#define STREAM_TO_DEVCLASS(a, p) \ + { \ + size_t ijk; \ + uint8_t* _pa = a.data() + kDevClassLength - 1; \ + for (ijk = 0; ijk < kDevClassLength; ijk++) \ + *_pa-- = *(p)++; \ } diff --git a/system/stack/include/bt_name.h b/system/stack/include/bt_name.h index 4a922240016..92801d07e74 100644 --- a/system/stack/include/bt_name.h +++ b/system/stack/include/bt_name.h @@ -29,23 +29,19 @@ constexpr size_t kBdNameLength = static_cast(BD_NAME_LEN); constexpr uint8_t kBdNameDelim = (uint8_t)NULL; inline size_t bd_name_copy(BD_NAME bd_name_dest, const BD_NAME bd_name_src) { - return strlcpy(reinterpret_cast(bd_name_dest), - reinterpret_cast(bd_name_src), kBdNameLength + 1); + return strlcpy(reinterpret_cast(bd_name_dest), reinterpret_cast(bd_name_src), + kBdNameLength + 1); } inline void bd_name_clear(BD_NAME bd_name) { *bd_name = {0}; } -inline bool bd_name_is_empty(const BD_NAME bd_name) { - return bd_name[0] == '\0'; -} +inline bool bd_name_is_empty(const BD_NAME bd_name) { return bd_name[0] == '\0'; } -inline void bd_name_from_char_pointer(BD_NAME bd_name_dest, - const char* bd_name_char) { +inline void bd_name_from_char_pointer(BD_NAME bd_name_dest, const char* bd_name_char) { if (bd_name_char == nullptr) { bd_name_clear(bd_name_dest); return; } - size_t src_len = strlcpy(reinterpret_cast(bd_name_dest), bd_name_char, - sizeof(BD_NAME)); + size_t src_len = strlcpy(reinterpret_cast(bd_name_dest), bd_name_char, sizeof(BD_NAME)); if (src_len < sizeof(BD_NAME) - 1) { /* Zero the remaining destination memory */ memset(bd_name_dest + src_len, 0, sizeof(BD_NAME) - src_len); @@ -53,6 +49,5 @@ inline void bd_name_from_char_pointer(BD_NAME bd_name_dest, } inline bool bd_name_is_equal(const BD_NAME bd_name1, const BD_NAME bd_name2) { return memcmp(reinterpret_cast(const_cast(bd_name1)), - reinterpret_cast(const_cast(bd_name2)), - kBdNameLength + 1) == 0; + reinterpret_cast(const_cast(bd_name2)), kBdNameLength + 1) == 0; } diff --git a/system/stack/include/bt_psm_types.h b/system/stack/include/bt_psm_types.h index 414734b273e..908270fa5f1 100644 --- a/system/stack/include/bt_psm_types.h +++ b/system/stack/include/bt_psm_types.h @@ -37,8 +37,8 @@ enum tBT_PSM : uint16_t { BT_PSM_AVCTP = 0x0017, BT_PSM_AVDTP = 0x0019, BT_PSM_AVCTP_13 = 0x001B, /* Advanced Control - Browsing */ - BT_PSM_UDI_CP = 0x001D, /* Unrestricted Digital Information Profile C-Plane */ - BT_PSM_ATT = 0x001F, /* Attribute Protocol */ + BT_PSM_UDI_CP = 0x001D, /* Unrestricted Digital Information Profile C-Plane */ + BT_PSM_ATT = 0x001F, /* Attribute Protocol */ BT_PSM_EATT = 0x0027, /* We will not allocate a PSM in the reserved range to 3rd party apps */ diff --git a/system/stack/include/bt_types.h b/system/stack/include/bt_types.h index b5850e4f9b2..b1145cf3256 100644 --- a/system/stack/include/bt_types.h +++ b/system/stack/include/bt_types.h @@ -108,15 +108,17 @@ { *(p)++ = (uint8_t)(u8); } #define INT8_TO_STREAM(p, u8) \ { *(p)++ = (int8_t)(u8); } -#define ARRAY16_TO_STREAM(p, a) \ - { \ - int ijk; \ - for (ijk = 0; ijk < 16; ijk++) *(p)++ = (uint8_t)(a)[15 - ijk]; \ +#define ARRAY16_TO_STREAM(p, a) \ + { \ + int ijk; \ + for (ijk = 0; ijk < 16; ijk++) \ + *(p)++ = (uint8_t)(a)[15 - ijk]; \ } -#define ARRAY8_TO_STREAM(p, a) \ - { \ - int ijk; \ - for (ijk = 0; ijk < 8; ijk++) *(p)++ = (uint8_t)(a)[7 - ijk]; \ +#define ARRAY8_TO_STREAM(p, a) \ + { \ + int ijk; \ + for (ijk = 0; ijk < 8; ijk++) \ + *(p)++ = (uint8_t)(a)[7 - ijk]; \ } #define LAP_TO_STREAM(p, a) \ { \ @@ -124,15 +126,16 @@ for (ijk = 0; ijk < LAP_LEN; ijk++) \ *(p)++ = (uint8_t)(a)[LAP_LEN - 1 - ijk]; \ } -#define ARRAY_TO_STREAM(p, a, len) \ - { \ - int ijk; \ - for (ijk = 0; ijk < (len); ijk++) *(p)++ = (uint8_t)(a)[ijk]; \ +#define ARRAY_TO_STREAM(p, a, len) \ + { \ + int ijk; \ + for (ijk = 0; ijk < (len); ijk++) \ + *(p)++ = (uint8_t)(a)[ijk]; \ } -#define STREAM_TO_INT8(u8, p) \ - { \ - (u8) = (*((int8_t*)(p))); \ - (p) += 1; \ +#define STREAM_TO_INT8(u8, p) \ + { \ + (u8) = (*((int8_t*)(p))); \ + (p) += 1; \ } #define STREAM_TO_UINT8(u8, p) \ { \ @@ -150,46 +153,46 @@ ((((uint32_t)(*((p) + 2)))) << 16)); \ (p) += 3; \ } -#define STREAM_TO_UINT32(u32, p) \ - { \ - (u32) = (((uint32_t)(*(p))) + ((((uint32_t)(*((p) + 1)))) << 8) + \ - ((((uint32_t)(*((p) + 2)))) << 16) + \ - ((((uint32_t)(*((p) + 3)))) << 24)); \ - (p) += 4; \ +#define STREAM_TO_UINT32(u32, p) \ + { \ + (u32) = (((uint32_t)(*(p))) + ((((uint32_t)(*((p) + 1)))) << 8) + \ + ((((uint32_t)(*((p) + 2)))) << 16) + ((((uint32_t)(*((p) + 3)))) << 24)); \ + (p) += 4; \ } -#define STREAM_TO_UINT64(u64, p) \ - { \ - (u64) = (((uint64_t)(*(p))) + ((((uint64_t)(*((p) + 1)))) << 8) + \ - ((((uint64_t)(*((p) + 2)))) << 16) + \ - ((((uint64_t)(*((p) + 3)))) << 24) + \ - ((((uint64_t)(*((p) + 4)))) << 32) + \ - ((((uint64_t)(*((p) + 5)))) << 40) + \ - ((((uint64_t)(*((p) + 6)))) << 48) + \ - ((((uint64_t)(*((p) + 7)))) << 56)); \ - (p) += 8; \ +#define STREAM_TO_UINT64(u64, p) \ + { \ + (u64) = (((uint64_t)(*(p))) + ((((uint64_t)(*((p) + 1)))) << 8) + \ + ((((uint64_t)(*((p) + 2)))) << 16) + ((((uint64_t)(*((p) + 3)))) << 24) + \ + ((((uint64_t)(*((p) + 4)))) << 32) + ((((uint64_t)(*((p) + 5)))) << 40) + \ + ((((uint64_t)(*((p) + 6)))) << 48) + ((((uint64_t)(*((p) + 7)))) << 56)); \ + (p) += 8; \ } -#define STREAM_TO_ARRAY16(a, p) \ - { \ - int ijk; \ - uint8_t* _pa = (uint8_t*)(a) + 15; \ - for (ijk = 0; ijk < 16; ijk++) *_pa-- = *(p)++; \ +#define STREAM_TO_ARRAY16(a, p) \ + { \ + int ijk; \ + uint8_t* _pa = (uint8_t*)(a) + 15; \ + for (ijk = 0; ijk < 16; ijk++) \ + *_pa-- = *(p)++; \ } -#define STREAM_TO_ARRAY8(a, p) \ - { \ - int ijk; \ - uint8_t* _pa = (uint8_t*)(a) + 7; \ - for (ijk = 0; ijk < 8; ijk++) *_pa-- = *(p)++; \ +#define STREAM_TO_ARRAY8(a, p) \ + { \ + int ijk; \ + uint8_t* _pa = (uint8_t*)(a) + 7; \ + for (ijk = 0; ijk < 8; ijk++) \ + *_pa-- = *(p)++; \ } -#define STREAM_TO_LAP(a, p) \ - { \ - int ijk; \ - uint8_t* plap = (uint8_t*)(a) + LAP_LEN - 1; \ - for (ijk = 0; ijk < LAP_LEN; ijk++) *plap-- = *(p)++; \ +#define STREAM_TO_LAP(a, p) \ + { \ + int ijk; \ + uint8_t* plap = (uint8_t*)(a) + LAP_LEN - 1; \ + for (ijk = 0; ijk < LAP_LEN; ijk++) \ + *plap-- = *(p)++; \ } -#define STREAM_TO_ARRAY(a, p, len) \ - { \ - int ijk; \ - for (ijk = 0; ijk < (len); ijk++) ((uint8_t*)(a))[ijk] = *(p)++; \ +#define STREAM_TO_ARRAY(a, p, len) \ + { \ + int ijk; \ + for (ijk = 0; ijk < (len); ijk++) \ + ((uint8_t*)(a))[ijk] = *(p)++; \ } #define STREAM_SKIP_UINT8(p) \ do { \ @@ -227,10 +230,11 @@ } #define UINT8_TO_BE_STREAM(p, u8) \ { *(p)++ = (uint8_t)(u8); } -#define ARRAY_TO_BE_STREAM(p, a, len) \ - { \ - int ijk; \ - for (ijk = 0; ijk < (len); ijk++) *(p)++ = (uint8_t)(a)[ijk]; \ +#define ARRAY_TO_BE_STREAM(p, a, len) \ + { \ + int ijk; \ + for (ijk = 0; ijk < (len); ijk++) \ + *(p)++ = (uint8_t)(a)[ijk]; \ } #define BE_STREAM_TO_UINT8(u8, p) \ { \ @@ -242,11 +246,10 @@ (u16) = (uint16_t)(((uint16_t)(*(p)) << 8) + (uint16_t)(*((p) + 1))); \ (p) += 2; \ } -#define BE_STREAM_TO_UINT24(u32, p) \ - { \ - (u32) = (((uint32_t)(*((p) + 2))) + ((uint32_t)(*((p) + 1)) << 8) + \ - ((uint32_t)(*(p)) << 16)); \ - (p) += 3; \ +#define BE_STREAM_TO_UINT24(u32, p) \ + { \ + (u32) = (((uint32_t)(*((p) + 2))) + ((uint32_t)(*((p) + 1)) << 8) + ((uint32_t)(*(p)) << 16)); \ + (p) += 3; \ } #define BE_STREAM_TO_UINT32(u32, p) \ { \ @@ -262,10 +265,11 @@ ((uint64_t)(*((p) + 1)) << 48) + ((uint64_t)(*(p)) << 56)); \ (p) += 8; \ } -#define BE_STREAM_TO_ARRAY(p, a, len) \ - { \ - int ijk; \ - for (ijk = 0; ijk < (len); ijk++) ((uint8_t*)(a))[ijk] = *(p)++; \ +#define BE_STREAM_TO_ARRAY(p, a, len) \ + { \ + int ijk; \ + for (ijk = 0; ijk < (len); ijk++) \ + ((uint8_t*)(a))[ijk] = *(p)++; \ } /******************************************************************************* diff --git a/system/stack/include/bt_uuid16.h b/system/stack/include/bt_uuid16.h index 4449363bfe4..1e31f1b87bc 100644 --- a/system/stack/include/bt_uuid16.h +++ b/system/stack/include/bt_uuid16.h @@ -88,11 +88,9 @@ #define UUID_SERVCLASS_PBAP_PCE 0X112E /* Phonebook Access - PCE */ #define UUID_SERVCLASS_PBAP_PSE 0X112F /* Phonebook Access - PSE */ #define UUID_SERVCLASS_PHONE_ACCESS 0x1130 -#define UUID_SERVCLASS_HEADSET_HS 0x1131 /* Headset - HS, from HSP v1.2 */ -#define UUID_SERVCLASS_MPS_PROFILE \ - 0x113A /* Multi-Profile Specification - Profile */ -#define UUID_SERVCLASS_MPS_SC \ - 0x113B /* Multi-Profile Specification - Service Class */ +#define UUID_SERVCLASS_HEADSET_HS 0x1131 /* Headset - HS, from HSP v1.2 */ +#define UUID_SERVCLASS_MPS_PROFILE 0x113A /* Multi-Profile Specification - Profile */ +#define UUID_SERVCLASS_MPS_SC 0x113B /* Multi-Profile Specification - Service Class */ #define UUID_SERVCLASS_PNP_INFORMATION 0X1200 /* Device Identification */ #define UUID_SERVCLASS_GENERIC_NETWORKING 0X1201 #define UUID_SERVCLASS_GENERIC_FILETRANSFER 0X1202 @@ -109,13 +107,12 @@ #define UUID_SERVCLASS_VIDEO_SINK 0X1304 #define UUID_SERVCLASS_VIDEO_DISTRIBUTION 0X1305 -#define UUID_SERVCLASS_HDP_PROFILE 0X1400 /* Health Device profile (HDP) */ -#define UUID_SERVCLASS_HDP_SOURCE 0X1401 /* Health Device profile (HDP) */ -#define UUID_SERVCLASS_HDP_SINK 0X1402 /* Health Device profile (HDP) */ -#define UUID_SERVCLASS_MAP_PROFILE 0X1134 /* MAP profile */ -#define UUID_SERVCLASS_MESSAGE_ACCESS 0X1132 /* Message Access Service */ -#define UUID_SERVCLASS_MESSAGE_NOTIFICATION \ - 0X1133 /* Message Notification Service */ +#define UUID_SERVCLASS_HDP_PROFILE 0X1400 /* Health Device profile (HDP) */ +#define UUID_SERVCLASS_HDP_SOURCE 0X1401 /* Health Device profile (HDP) */ +#define UUID_SERVCLASS_HDP_SINK 0X1402 /* Health Device profile (HDP) */ +#define UUID_SERVCLASS_MAP_PROFILE 0X1134 /* MAP profile */ +#define UUID_SERVCLASS_MESSAGE_ACCESS 0X1132 /* Message Access Service */ +#define UUID_SERVCLASS_MESSAGE_NOTIFICATION 0X1133 /* Message Notification Service */ #define UUID_SERVCLASS_GAP_SERVER 0x1800 #define UUID_SERVCLASS_GATT_SERVER 0x1801 @@ -125,8 +122,7 @@ #define UUID_SERVCLASS_VOLUME_CONTROL_SERVER 0x1844 #define UUID_SERVCLASS_GMCS_SERVER 0x1849 /* Generic Media Control Service */ -#define UUID_SERVCLASS_GTBS_SERVER \ - 0x184c /* Generic Telephony Bearer \ - Service*/ -#define UUID_SERVCLASS_TMAS_SERVER \ - 0x1855 /* Telephone and Media Audio Service */ +#define UUID_SERVCLASS_GTBS_SERVER \ + 0x184c /* Generic Telephony Bearer \ + Service*/ +#define UUID_SERVCLASS_TMAS_SERVER 0x1855 /* Telephone and Media Audio Service */ diff --git a/system/stack/include/btm_api.h b/system/stack/include/btm_api.h index 62d6bb38f15..c54abd70610 100644 --- a/system/stack/include/btm_api.h +++ b/system/stack/include/btm_api.h @@ -109,8 +109,7 @@ void BTM_reset_complete(); * Returns BTM_CMD_STARTED if successful, otherwise an error * ******************************************************************************/ -[[nodiscard]] tBTM_STATUS BTM_ReadLocalDeviceNameFromController( - tBTM_CMPL_CB* p_rln_cmpl_cback); +[[nodiscard]] tBTM_STATUS BTM_ReadLocalDeviceNameFromController(tBTM_CMPL_CB* p_rln_cmpl_cback); /******************************************************************************* * @@ -130,8 +129,8 @@ void BTM_reset_complete(); * Description Send a vendor specific HCI command to the controller. * ******************************************************************************/ -void BTM_VendorSpecificCommand(uint16_t opcode, uint8_t param_len, - uint8_t* p_param_buf, tBTM_VSC_CMPL_CB* p_cb); +void BTM_VendorSpecificCommand(uint16_t opcode, uint8_t param_len, uint8_t* p_param_buf, + tBTM_VSC_CMPL_CB* p_cb); /******************************************************************************* * @@ -235,10 +234,8 @@ void BTM_WriteVoiceSettings(uint16_t settings); * Returns true if data valid, false otherwise * ******************************************************************************/ -[[nodiscard]] bool BTM_ReadRemoteVersion(const RawAddress& addr, - uint8_t* lmp_version, - uint16_t* manufacturer, - uint16_t* lmp_sub_version); +[[nodiscard]] bool BTM_ReadRemoteVersion(const RawAddress& addr, uint8_t* lmp_version, + uint16_t* manufacturer, uint16_t* lmp_sub_version); /******************************************************************************* * @@ -331,11 +328,9 @@ void BTM_WriteVoiceSettings(uint16_t settings); * with the sco index used for the connection. * ******************************************************************************/ -[[nodiscard]] tBTM_STATUS BTM_CreateSco(const RawAddress* remote_bda, - bool is_orig, uint16_t pkt_types, - uint16_t* p_sco_inx, - tBTM_SCO_CB* p_conn_cb, - tBTM_SCO_CB* p_disc_cb); +[[nodiscard]] tBTM_STATUS BTM_CreateSco(const RawAddress* remote_bda, bool is_orig, + uint16_t pkt_types, uint16_t* p_sco_inx, + tBTM_SCO_CB* p_conn_cb, tBTM_SCO_CB* p_disc_cb); /******************************************************************************* * @@ -389,8 +384,7 @@ void BTM_RemoveSco(const RawAddress& bda); * BTM_ILLEGAL_VALUE if there is an illegal sco_inx * ******************************************************************************/ -[[nodiscard]] tBTM_STATUS BTM_RegForEScoEvts(uint16_t sco_inx, - tBTM_ESCO_CBACK* p_esco_cback); +[[nodiscard]] tBTM_STATUS BTM_RegForEScoEvts(uint16_t sco_inx, tBTM_ESCO_CBACK* p_esco_cback); /******************************************************************************* * @@ -410,8 +404,7 @@ void BTM_RemoveSco(const RawAddress& bda); * Returns void * ******************************************************************************/ -void BTM_EScoConnRsp(uint16_t sco_inx, tHCI_STATUS hci_status, - enh_esco_params_t* p_parms); +void BTM_EScoConnRsp(uint16_t sco_inx, tHCI_STATUS hci_status, enh_esco_params_t* p_parms); /******************************************************************************* * @@ -451,8 +444,7 @@ void BTM_EScoConnRsp(uint16_t sco_inx, tHCI_STATUS hci_status, * BT_DEVICE_TYPE_BLE if only BLE transport is supported. * ******************************************************************************/ -[[nodiscard]] tBT_DEVICE_TYPE BTM_GetPeerDeviceTypeFromFeatures( - const RawAddress& bd_addr); +[[nodiscard]] tBT_DEVICE_TYPE BTM_GetPeerDeviceTypeFromFeatures(const RawAddress& bd_addr); /******************************************************************************* * @@ -464,8 +456,7 @@ void BTM_EScoConnRsp(uint16_t sco_inx, tHCI_STATUS hci_status, * Returns the handle of the connection, or 0xFFFF if none. * ******************************************************************************/ -[[nodiscard]] uint16_t BTM_GetHCIConnHandle(const RawAddress& remote_bda, - tBT_TRANSPORT transport); +[[nodiscard]] uint16_t BTM_GetHCIConnHandle(const RawAddress& remote_bda, tBT_TRANSPORT transport); /******************************************************************************* * @@ -476,8 +467,7 @@ void BTM_EScoConnRsp(uint16_t sco_inx, tHCI_STATUS hci_status, * Returns True when PHY 2M supported false otherwise * ******************************************************************************/ -[[nodiscard]] bool BTM_IsPhy2mSupported(const RawAddress& remote_bda, - tBT_TRANSPORT transport); +[[nodiscard]] bool BTM_IsPhy2mSupported(const RawAddress& remote_bda, tBT_TRANSPORT transport); /******************************************************************************* * @@ -499,8 +489,7 @@ void BTM_RequestPeerSCA(const RawAddress& remote_bda, tBT_TRANSPORT transport); * is not supported by peer device or ACL does not exist * ******************************************************************************/ -[[nodiscard]] uint8_t BTM_GetPeerSCA(const RawAddress& remote_bda, - tBT_TRANSPORT transport); +[[nodiscard]] uint8_t BTM_GetPeerSCA(const RawAddress& remote_bda, tBT_TRANSPORT transport); /******************************************************************************* * @@ -530,8 +519,7 @@ void BTM_RequestPeerSCA(const RawAddress& remote_bda, tBT_TRANSPORT transport); * false - if not found * ******************************************************************************/ -[[nodiscard]] bool BTM_HasEirService(const uint32_t* p_eir_uuid, - uint16_t uuid16); +[[nodiscard]] bool BTM_HasEirService(const uint32_t* p_eir_uuid, uint16_t uuid16); /******************************************************************************* * @@ -579,10 +567,8 @@ void BTM_RemoveEirService(uint32_t* p_eir_uuid, uint16_t uuid16); * HCI_EIR_COMPLETE_16BITS_UUID_TYPE, otherwise * ******************************************************************************/ -[[nodiscard]] uint8_t BTM_GetEirSupportedServices(uint32_t* p_eir_uuid, - uint8_t** p, - uint8_t max_num_uuid16, - uint8_t* p_num_uuid16); +[[nodiscard]] uint8_t BTM_GetEirSupportedServices(uint32_t* p_eir_uuid, uint8_t** p, + uint8_t max_num_uuid16, uint8_t* p_num_uuid16); /******************************************************************************* * @@ -607,9 +593,8 @@ void BTM_RemoveEirService(uint32_t* p_eir_uuid, uint16_t uuid16); * HCI_EIR_MORE_128BITS_UUID_TYPE * ******************************************************************************/ -[[nodiscard]] uint8_t BTM_GetEirUuidList(const uint8_t* p_eir, size_t eir_len, - uint8_t uuid_size, uint8_t* p_num_uuid, - uint8_t* p_uuid_list, +[[nodiscard]] uint8_t BTM_GetEirUuidList(const uint8_t* p_eir, size_t eir_len, uint8_t uuid_size, + uint8_t* p_num_uuid, uint8_t* p_uuid_list, uint8_t max_num_uuid); [[nodiscard]] bool BTM_IsScoActiveByBdaddr(const RawAddress& remote_bda); @@ -617,8 +602,7 @@ void BTM_RemoveEirService(uint32_t* p_eir_uuid, uint16_t uuid16); /* Read maximum data packet that can be sent over current connection */ [[nodiscard]] uint16_t BTM_GetMaxPacketSize(const RawAddress& addr); -typedef void(BTM_CONSOLIDATION_CB)(const RawAddress& identity_addr, - const RawAddress& rpa); +typedef void(BTM_CONSOLIDATION_CB)(const RawAddress& identity_addr, const RawAddress& rpa); void BTM_SetConsolidationCallback(BTM_CONSOLIDATION_CB* cb); #endif /* BTM_API_H */ diff --git a/system/stack/include/btm_api_types.h b/system/stack/include/btm_api_types.h index 00a7dcd4cba..3f167bb8ceb 100644 --- a/system/stack/include/btm_api_types.h +++ b/system/stack/include/btm_api_types.h @@ -178,13 +178,13 @@ inline uint16_t sco_codec_type_to_id(tBTM_SCO_CODEC_TYPE codec_type) { switch (codec_type) { case BTM_SCO_CODEC_CVSD: return static_cast>( - tBTA_AG_UUID_CODEC::UUID_CODEC_CVSD); + tBTA_AG_UUID_CODEC::UUID_CODEC_CVSD); case BTM_SCO_CODEC_MSBC: return static_cast>( - tBTA_AG_UUID_CODEC::UUID_CODEC_MSBC); + tBTA_AG_UUID_CODEC::UUID_CODEC_MSBC); case BTM_SCO_CODEC_LC3: return static_cast>( - tBTA_AG_UUID_CODEC::UUID_CODEC_LC3); + tBTA_AG_UUID_CODEC::UUID_CODEC_LC3); default: return 0; } @@ -197,9 +197,8 @@ inline std::string bta_ag_uuid_codec_text(const tBTA_AG_UUID_CODEC result) { CASE_RETURN_TEXT(tBTA_AG_UUID_CODEC::UUID_CODEC_MSBC); CASE_RETURN_TEXT(tBTA_AG_UUID_CODEC::UUID_CODEC_LC3); default: - return fmt::format( - "UNKNOWN Codec with id {}", - static_cast>(result)); + return fmt::format("UNKNOWN Codec with id {}", + static_cast>(result)); } } #endif // BTM_API_TYPES_H diff --git a/system/stack/include/btm_ble_addr.h b/system/stack/include/btm_ble_addr.h index ddb9675079c..016f68c2c62 100644 --- a/system/stack/include/btm_ble_addr.h +++ b/system/stack/include/btm_ble_addr.h @@ -31,8 +31,7 @@ * Returns true is updated; false otherwise. * ******************************************************************************/ -bool btm_ble_init_pseudo_addr(tBTM_SEC_DEV_REC* p_dev_rec, - const RawAddress& new_pseudo_addr); +bool btm_ble_init_pseudo_addr(tBTM_SEC_DEV_REC* p_dev_rec, const RawAddress& new_pseudo_addr); /******************************************************************************* * @@ -42,12 +41,11 @@ bool btm_ble_init_pseudo_addr(tBTM_SEC_DEV_REC* p_dev_rec, * address in security database. * ******************************************************************************/ -bool btm_identity_addr_to_random_pseudo(RawAddress* bd_addr, - tBLE_ADDR_TYPE* p_addr_type, +bool btm_identity_addr_to_random_pseudo(RawAddress* bd_addr, tBLE_ADDR_TYPE* p_addr_type, bool refresh); -bool btm_identity_addr_to_random_pseudo_from_address_with_type( - tBLE_BD_ADDR* address_with_type, bool refresh); +bool btm_identity_addr_to_random_pseudo_from_address_with_type(tBLE_BD_ADDR* address_with_type, + bool refresh); bool maybe_resolve_address(RawAddress* bda, tBLE_ADDR_TYPE* bda_type); diff --git a/system/stack/include/btm_ble_api.h b/system/stack/include/btm_ble_api.h index 868569563c2..849511952f1 100644 --- a/system/stack/include/btm_ble_api.h +++ b/system/stack/include/btm_ble_api.h @@ -68,8 +68,7 @@ void BTM_BleGetVendorCapabilities(tBTM_BLE_VSC_CB* p_cmn_vsc_cb); * Returns void * ******************************************************************************/ -void BTM_BleGetDynamicAudioBuffer( - tBTM_BT_DYNAMIC_AUDIO_BUFFER_CB* p_dynamic_audio_buffer_cb); +void BTM_BleGetDynamicAudioBuffer(tBTM_BT_DYNAMIC_AUDIO_BUFFER_CB* p_dynamic_audio_buffer_cb); /******************************************************************************* * @@ -88,10 +87,8 @@ void BTM_BleGetDynamicAudioBuffer( * Returns void * ******************************************************************************/ -tBTM_STATUS BTM_BleObserve(bool start, uint8_t duration, - tBTM_INQ_RESULTS_CB* p_results_cb, - tBTM_CMPL_CB* p_cmpl_cb, - bool low_latency_scan = false); +tBTM_STATUS BTM_BleObserve(bool start, uint8_t duration, tBTM_INQ_RESULTS_CB* p_results_cb, + tBTM_CMPL_CB* p_cmpl_cb, bool low_latency_scan = false); /******************************************************************************* * @@ -110,8 +107,7 @@ tBTM_STATUS BTM_BleObserve(bool start, uint8_t duration, * Returns void * ******************************************************************************/ -void BTM_BleOpportunisticObserve(bool enable, - tBTM_INQ_RESULTS_CB* p_results_cb); +void BTM_BleOpportunisticObserve(bool enable, tBTM_INQ_RESULTS_CB* p_results_cb); /******************************************************************************* * @@ -127,8 +123,7 @@ void BTM_BleOpportunisticObserve(bool enable, * Returns void * ******************************************************************************/ -void BTM_BleTargetAnnouncementObserve(bool enable, - tBTM_INQ_RESULTS_CB* p_results_cb); +void BTM_BleTargetAnnouncementObserve(bool enable, tBTM_INQ_RESULTS_CB* p_results_cb); /******************************************************************************* * @@ -151,11 +146,8 @@ bool BTM_IsBleConnection(uint16_t conn_handle); * Returns void * ******************************************************************************/ -bool BTM_ReadRemoteConnectionAddr(const RawAddress& pseudo_addr, - RawAddress& conn_addr, - tBLE_ADDR_TYPE* p_addr_type, - bool ota_address); - +bool BTM_ReadRemoteConnectionAddr(const RawAddress& pseudo_addr, RawAddress& conn_addr, + tBLE_ADDR_TYPE* p_addr_type, bool ota_address); #include "stack/btm/btm_ble_bgconn.h" @@ -178,8 +170,7 @@ bool BTM_ReadRemoteConnectionAddr(const RawAddress& pseudo_addr, * ******************************************************************************/ void BTM_BleSetPrefConnParams(const RawAddress& bd_addr, uint16_t min_conn_int, - uint16_t max_conn_int, - uint16_t peripheral_latency, + uint16_t max_conn_int, uint16_t peripheral_latency, uint16_t supervision_tout); /****************************************************************************** @@ -237,8 +228,7 @@ bool BTM_GetRemoteDeviceName(const RawAddress& bda, BD_NAME bd_name); * Return true if an active link is identified; false otherwise * ******************************************************************************/ -bool BTM_ReadConnectedTransportAddress(RawAddress* remote_bda, - tBT_TRANSPORT transport); +bool BTM_ReadConnectedTransportAddress(RawAddress* remote_bda, tBT_TRANSPORT transport); /******************************************************************************* * @@ -265,8 +255,7 @@ void BTM_BleReceiverTest(uint8_t rx_freq, tBTM_CMPL_CB* p_cmd_cmpl_cback); * p_cmd_cmpl_cback - Command Complete callback * ******************************************************************************/ -void BTM_BleTransmitterTest(uint8_t tx_freq, uint8_t test_data_len, - uint8_t packet_payload, +void BTM_BleTransmitterTest(uint8_t tx_freq, uint8_t test_data_len, uint8_t packet_payload, tBTM_CMPL_CB* p_cmd_cmpl_cback); /******************************************************************************* @@ -299,10 +288,9 @@ bool BTM_UseLeLink(const RawAddress& bd_addr); * condition. * ******************************************************************************/ -void BTM_BleAdvFilterParamSetup( - tBTM_BLE_SCAN_COND_OP action, tBTM_BLE_PF_FILT_INDEX filt_index, - std::unique_ptr p_filt_params, - tBTM_BLE_PF_PARAM_CB cb); +void BTM_BleAdvFilterParamSetup(tBTM_BLE_SCAN_COND_OP action, tBTM_BLE_PF_FILT_INDEX filt_index, + std::unique_ptr p_filt_params, + tBTM_BLE_PF_PARAM_CB cb); /******************************************************************************* * @@ -326,8 +314,7 @@ tBTM_STATUS BTM_BleGetEnergyInfo(tBTM_BLE_ENERGY_INFO_CBACK* p_ener_cback); * Returns BTM_SUCCESS if success; otherwise failed. * ******************************************************************************/ -tBTM_STATUS BTM_SetBleDataLength(const RawAddress& bd_addr, - uint16_t tx_pdu_length); +tBTM_STATUS BTM_SetBleDataLength(const RawAddress& bd_addr, uint16_t tx_pdu_length); /******************************************************************************* * @@ -339,9 +326,8 @@ tBTM_STATUS BTM_SetBleDataLength(const RawAddress& bd_addr, * Returns BTM_SUCCESS if success; otherwise failed. * ******************************************************************************/ -void BTM_BleReadPhy( - const RawAddress& bd_addr, - base::Callback cb); +void BTM_BleReadPhy(const RawAddress& bd_addr, + base::Callback cb); /******************************************************************************* * @@ -370,24 +356,20 @@ bool btm_ble_get_acl_remote_addr(uint16_t hci_handle, RawAddress& conn_addr, tBLE_ADDR_TYPE* p_addr_type); using StartSyncCb = base::Callback; -using SyncReportCb = base::Callback /*data*/)>; + uint8_t /*status*/, uint16_t /*sync_handle*/, uint8_t /*advertising_sid*/, + uint8_t /*address_type*/, RawAddress /*address*/, uint8_t /*phy*/, uint16_t /*interval*/)>; +using SyncReportCb = + base::Callback /*data*/)>; using SyncLostCb = base::Callback; using BigInfoReportCb = base::Callback; -void btm_ble_periodic_adv_sync_established(uint8_t status, uint16_t sync_handle, - uint8_t adv_sid, - uint8_t address_type, - const RawAddress& addr, uint8_t phy, - uint16_t interval, +void btm_ble_periodic_adv_sync_established(uint8_t status, uint16_t sync_handle, uint8_t adv_sid, + uint8_t address_type, const RawAddress& addr, + uint8_t phy, uint16_t interval, uint8_t adv_clock_accuracy); -void btm_ble_periodic_adv_report(uint16_t sync_handle, uint8_t tx_power, - int8_t rssi, uint8_t cte_type, - uint8_t data_status, uint8_t data_len, +void btm_ble_periodic_adv_report(uint16_t sync_handle, uint8_t tx_power, int8_t rssi, + uint8_t cte_type, uint8_t data_status, uint8_t data_len, const uint8_t* periodic_data); void btm_ble_periodic_adv_sync_lost(uint16_t sync_handle); diff --git a/system/stack/include/btm_ble_api_types.h b/system/stack/include/btm_ble_api_types.h index c40fd6c4f42..1e23a9050e6 100644 --- a/system/stack/include/btm_ble_api_types.h +++ b/system/stack/include/btm_ble_api_types.h @@ -203,9 +203,8 @@ typedef uint8_t tBTM_BLE_SFP; #define BTM_BLE_CONN_INT_MIN_HEARINGAID 0x0010 #endif -#define BTM_CMAC_TLEN_SIZE 8 /* 64 bits */ -#define BTM_BLE_AUTH_SIGN_LEN \ - 12 /* BLE data signature length 8 Bytes + 4 bytes counter*/ +#define BTM_CMAC_TLEN_SIZE 8 /* 64 bits */ +#define BTM_BLE_AUTH_SIGN_LEN 12 /* BLE data signature length 8 Bytes + 4 bytes counter*/ typedef uint8_t BLE_SIGNATURE[BTM_BLE_AUTH_SIGN_LEN]; /* Device address */ #ifndef BTM_BLE_HOST_SUPPORT @@ -283,7 +282,7 @@ typedef struct { /* General callback function for notifying an application that a synchronous * BTM function is complete. The pointer contains the address of any returned * data. -*/ + */ typedef void(tBTM_RAND_ENC_CB)(tBTM_RAND_ENC* p1); /* ADV data flag bit definition used for BTM_BLE_AD_TYPE_FLAG */ @@ -298,9 +297,9 @@ typedef void(tBTM_RAND_ENC_CB)(tBTM_RAND_ENC* p1); #define BTM_BLE_AD_BIT_FLAGS (0x00000001 << 1) #define BTM_BLE_AD_TYPE_FLAG HCI_EIR_FLAGS_TYPE /* 0x01 */ -#define BTM_BLE_AD_TYPE_16SRV_CMPL \ - HCI_EIR_COMPLETE_16BITS_UUID_TYPE /* 0x03 \ - */ +#define BTM_BLE_AD_TYPE_16SRV_CMPL \ + HCI_EIR_COMPLETE_16BITS_UUID_TYPE /* 0x03 \ + */ #define BTM_BLE_AD_TYPE_SERVICE_DATA_TYPE HCI_EIR_SERVICE_DATA_TYPE /* 0x16 */ #define BTM_BLE_AD_TYPE_APPEARANCE 0x19 #define BTM_BLE_AD_TYPE_RSI HCI_EIR_RSI_TYPE /* 0x2E */ @@ -313,8 +312,8 @@ typedef void(tBTM_RAND_ENC_CB)(tBTM_RAND_ENC* p1); /* Preferred maximum number of microseconds that the local Controller should use to transmit a single Link Layer Data Channel PDU. */ -#define BTM_BLE_DATA_TX_TIME_MAX_LEGACY 0x0848 -#define BTM_BLE_DATA_TX_TIME_MAX 0x4290 +#define BTM_BLE_DATA_TX_TIME_MAX_LEGACY 0x0848 +#define BTM_BLE_DATA_TX_TIME_MAX 0x4290 /* adv tx power in dBm */ typedef struct { @@ -365,8 +364,8 @@ typedef enum : uint8_t { typedef void(tBTM_BLE_SCAN_THRESHOLD_CBACK)(tBTM_BLE_REF_VALUE ref_value); using tBTM_BLE_SCAN_REP_CBACK = - base::Callback)>; + base::Callback)>; #ifndef BTM_BLE_BATCH_SCAN_MAX #define BTM_BLE_BATCH_SCAN_MAX 5 @@ -435,26 +434,22 @@ typedef uint8_t tBTM_BLE_PF_LOGIC_TYPE; typedef uint8_t tBTM_BLE_PF_FILT_INDEX; -enum { - BTM_BLE_SCAN_COND_ADD, - BTM_BLE_SCAN_COND_DELETE, - BTM_BLE_SCAN_COND_CLEAR = 2 -}; +enum { BTM_BLE_SCAN_COND_ADD, BTM_BLE_SCAN_COND_DELETE, BTM_BLE_SCAN_COND_CLEAR = 2 }; typedef uint8_t tBTM_BLE_SCAN_COND_OP; /* BLE adv payload filtering config complete callback */ -using tBTM_BLE_PF_CFG_CBACK = base::Callback; +using tBTM_BLE_PF_CFG_CBACK = + base::Callback; /* BLE adv payload filtering status setup complete callback */ -using tBTM_BLE_PF_STATUS_CBACK = base::Callback; +using tBTM_BLE_PF_STATUS_CBACK = + base::Callback; /* BLE adv payload filtering param setup complete callback */ -using tBTM_BLE_PF_PARAM_CB = base::Callback; +using tBTM_BLE_PF_PARAM_CB = + base::Callback; #ifndef BTM_CS_IRK_LIST_MAX #define BTM_CS_IRK_LIST_MAX 0x20 @@ -490,8 +485,7 @@ typedef struct { typedef btgatt_track_adv_info_t tBTM_BLE_TRACK_ADV_DATA; -typedef void(tBTM_BLE_TRACK_ADV_CBACK)( - tBTM_BLE_TRACK_ADV_DATA* p_track_adv_data); +typedef void(tBTM_BLE_TRACK_ADV_CBACK)(tBTM_BLE_TRACK_ADV_DATA* p_track_adv_data); typedef struct { tBTM_BLE_REF_VALUE ref_value; @@ -503,11 +497,9 @@ typedef uint32_t tBTM_BLE_RX_TIME_MS; typedef uint32_t tBTM_BLE_IDLE_TIME_MS; typedef uint32_t tBTM_BLE_ENERGY_USED; -typedef void(tBTM_BLE_ENERGY_INFO_CBACK)(tBTM_BLE_TX_TIME_MS tx_time, - tBTM_BLE_RX_TIME_MS rx_time, +typedef void(tBTM_BLE_ENERGY_INFO_CBACK)(tBTM_BLE_TX_TIME_MS tx_time, tBTM_BLE_RX_TIME_MS rx_time, tBTM_BLE_IDLE_TIME_MS idle_time, - tBTM_BLE_ENERGY_USED energy_used, - tHCI_STATUS status); + tBTM_BLE_ENERGY_USED energy_used, tHCI_STATUS status); typedef struct { tBTM_BLE_ENERGY_INFO_CBACK* p_ener_cback; diff --git a/system/stack/include/btm_ble_privacy.h b/system/stack/include/btm_ble_privacy.h index 7fccf097235..479c8d547f8 100644 --- a/system/stack/include/btm_ble_privacy.h +++ b/system/stack/include/btm_ble_privacy.h @@ -23,14 +23,12 @@ void btm_ble_resolving_list_init(uint8_t max_irk_list_sz); void btm_ble_refresh_peer_resolvable_private_addr(const RawAddress& pseudo_bda, - const RawAddress& rra, - tBLE_RAND_ADDR_TYPE type); + const RawAddress& rra, tBLE_RAND_ADDR_TYPE type); bool btm_ble_read_resolving_list_entry(tBTM_SEC_DEV_REC* p_dev_rec); -bool btm_ble_addr_resolvable(const RawAddress& rpa, - tBTM_SEC_DEV_REC* p_dev_rec); +bool btm_ble_addr_resolvable(const RawAddress& rpa, tBTM_SEC_DEV_REC* p_dev_rec); void btm_ble_resolving_list_load_dev(tBTM_SEC_DEV_REC& p_dev_rec); void btm_ble_resolving_list_remove_dev(tBTM_SEC_DEV_REC* p_dev_rec); -uint64_t btm_get_next_private_addrress_interval_ms(); +uint64_t btm_get_next_private_address_interval_ms(); diff --git a/system/stack/include/btm_ble_sec_api.h b/system/stack/include/btm_ble_sec_api.h index f3481a0d14a..6af16a9eb20 100644 --- a/system/stack/include/btm_ble_sec_api.h +++ b/system/stack/include/btm_ble_sec_api.h @@ -56,7 +56,7 @@ void BTM_SecAddBleDevice(const RawAddress& bd_addr, tBT_DEVICE_TYPE dev_type, * Parameters: bd_addr - BD address of the peer * p_le_key - LE key values. * key_type - LE SMP key type. -* + * ******************************************************************************/ void BTM_SecAddBleKey(const RawAddress& bd_addr, tBTM_LE_KEY_VALUE* p_le_key, tBTM_LE_KEY_TYPE key_type); @@ -101,8 +101,7 @@ void BTM_SecurityGrant(const RawAddress& bd_addr, uint8_t res); * BTM_MAX_PASSKEY_VAL(999999(0xF423F)). * ******************************************************************************/ -void BTM_BlePasskeyReply(const RawAddress& bd_addr, uint8_t res, - uint32_t passkey); +void BTM_BlePasskeyReply(const RawAddress& bd_addr, uint8_t res, uint32_t passkey); /******************************************************************************* * @@ -130,8 +129,7 @@ void BTM_BleConfirmReply(const RawAddress& bd_addr, uint8_t res); * p_data - simple pairing Randomizer C. * ******************************************************************************/ -void BTM_BleOobDataReply(const RawAddress& bd_addr, uint8_t res, uint8_t len, - uint8_t* p_data); +void BTM_BleOobDataReply(const RawAddress& bd_addr, uint8_t res, uint8_t len, uint8_t* p_data); /******************************************************************************* * @@ -146,8 +144,7 @@ void BTM_BleOobDataReply(const RawAddress& bd_addr, uint8_t res, uint8_t len, * p_r - pointer to Randomizer. * ******************************************************************************/ -void BTM_BleSecureConnectionOobDataReply(const RawAddress& bd_addr, - uint8_t* p_c, uint8_t* p_r); +void BTM_BleSecureConnectionOobDataReply(const RawAddress& bd_addr, uint8_t* p_c, uint8_t* p_r); /******************************************************************************* * @@ -165,8 +162,8 @@ void BTM_BleSecureConnectionOobDataReply(const RawAddress& bd_addr, * Returns true if signing sucessul, otherwise false. * ******************************************************************************/ -bool BTM_BleDataSignature(const RawAddress& bd_addr, uint8_t* p_text, - uint16_t len, BLE_SIGNATURE signature); +bool BTM_BleDataSignature(const RawAddress& bd_addr, uint8_t* p_text, uint16_t len, + BLE_SIGNATURE signature); /******************************************************************************* * @@ -183,10 +180,8 @@ bool BTM_BleDataSignature(const RawAddress& bd_addr, uint8_t* p_text, * Returns true if signature verified correctly; otherwise false. * ******************************************************************************/ -bool BTM_BleVerifySignature(const RawAddress& bd_addr, uint8_t* p_orig, - uint16_t len, uint32_t counter, uint8_t* p_comp); - - +bool BTM_BleVerifySignature(const RawAddress& bd_addr, uint8_t* p_orig, uint16_t len, + uint32_t counter, uint8_t* p_comp); /******************************************************************************* * @@ -198,7 +193,7 @@ bool BTM_BleVerifySignature(const RawAddress& bd_addr, uint8_t* p_orig, * BTM_BLE_KEY_TYPE_ER * or BTM_BLE_KEY_TYPE_COUNTER. * p_key: pointer to the key. -* + * * Returns non2. * ******************************************************************************/ diff --git a/system/stack/include/btm_ble_sec_api_types.h b/system/stack/include/btm_ble_sec_api_types.h index dd1f919b11c..4540877b828 100644 --- a/system/stack/include/btm_ble_sec_api_types.h +++ b/system/stack/include/btm_ble_sec_api_types.h @@ -19,6 +19,7 @@ #pragma once #include + #include "stack/include/bt_octets.h" #include "stack/include/btm_sec_api_types.h" @@ -115,6 +116,4 @@ typedef union { /* New LE identity key for local device. */ -typedef void(tBTM_LE_KEY_CALLBACK)(uint8_t key_type, - tBTM_BLE_LOCAL_KEYS* p_key); - +typedef void(tBTM_LE_KEY_CALLBACK)(uint8_t key_type, tBTM_BLE_LOCAL_KEYS* p_key); diff --git a/system/stack/include/btm_client_interface.h b/system/stack/include/btm_client_interface.h index ae5c01267d5..ebd5304c80e 100644 --- a/system/stack/include/btm_client_interface.h +++ b/system/stack/include/btm_client_interface.h @@ -46,29 +46,22 @@ struct btm_client_interface_t { // Acl peer and lifecycle struct { - [[nodiscard]] bool (*BTM_IsAclConnectionUp)(const RawAddress& bd_addr, - tBT_TRANSPORT transport); - [[nodiscard]] bool (*BTM_ReadConnectedTransportAddress)( - RawAddress* bd_addr, tBT_TRANSPORT transport); + [[nodiscard]] bool (*BTM_IsAclConnectionUp)(const RawAddress& bd_addr, tBT_TRANSPORT transport); + [[nodiscard]] bool (*BTM_ReadConnectedTransportAddress)(RawAddress* bd_addr, + tBT_TRANSPORT transport); [[nodiscard]] tBTM_STATUS (*BTM_CancelRemoteDeviceName)(void); - [[nodiscard]] tBTM_STATUS (*BTM_ReadRemoteDeviceName)( - const RawAddress& bd_addr, tBTM_NAME_CMPL_CB* p_cb, - tBT_TRANSPORT transport); + [[nodiscard]] tBTM_STATUS (*BTM_ReadRemoteDeviceName)(const RawAddress& bd_addr, + tBTM_NAME_CMPL_CB* p_cb, + tBT_TRANSPORT transport); [[nodiscard]] uint8_t* (*BTM_ReadRemoteFeatures)(const RawAddress&); - void (*BTM_ReadDevInfo)(const RawAddress& bd_addr, - tBT_DEVICE_TYPE* p_dev_type, + void (*BTM_ReadDevInfo)(const RawAddress& bd_addr, tBT_DEVICE_TYPE* p_dev_type, tBLE_ADDR_TYPE* p_addr_type); [[nodiscard]] uint16_t (*BTM_GetMaxPacketSize)(const RawAddress& bd_addr); - [[nodiscard]] bool (*BTM_ReadRemoteVersion)(const RawAddress& addr, - uint8_t* lmp_version, - uint16_t* manufacturer, - uint16_t* lmp_sub_version); - [[nodiscard]] tBT_DEVICE_TYPE (*BTM_GetPeerDeviceTypeFromFeatures)( - const RawAddress& bd_addr); - void (*BTM_RequestPeerSCA)(const RawAddress& remote_bda, - tBT_TRANSPORT transport); - [[nodiscard]] uint8_t (*BTM_GetPeerSCA)(const RawAddress& remote_bda, - tBT_TRANSPORT transport); + [[nodiscard]] bool (*BTM_ReadRemoteVersion)(const RawAddress& addr, uint8_t* lmp_version, + uint16_t* manufacturer, uint16_t* lmp_sub_version); + [[nodiscard]] tBT_DEVICE_TYPE (*BTM_GetPeerDeviceTypeFromFeatures)(const RawAddress& bd_addr); + void (*BTM_RequestPeerSCA)(const RawAddress& remote_bda, tBT_TRANSPORT transport); + [[nodiscard]] uint8_t (*BTM_GetPeerSCA)(const RawAddress& remote_bda, tBT_TRANSPORT transport); [[nodiscard]] bool (*BTM_IsPhy2mSupported)(const RawAddress& remote_bda, tBT_TRANSPORT transport); [[nodiscard]] uint16_t (*BTM_GetHCIConnHandle)(const RawAddress& bd_addr, @@ -76,17 +69,12 @@ struct btm_client_interface_t { } peer; struct { - [[nodiscard]] tBTM_STATUS (*BTM_GetRole)(const RawAddress& remote_bd_addr, - tHCI_ROLE* p_role); - [[nodiscard]] tBTM_STATUS (*BTM_SetPowerMode)(uint8_t pm_id, - const RawAddress& bd_addr, + [[nodiscard]] tBTM_STATUS (*BTM_GetRole)(const RawAddress& remote_bd_addr, tHCI_ROLE* p_role); + [[nodiscard]] tBTM_STATUS (*BTM_SetPowerMode)(uint8_t pm_id, const RawAddress& bd_addr, const tBTM_PM_PWR_MD* p_mode); - [[nodiscard]] tBTM_STATUS (*BTM_SetSsrParams)(const RawAddress& bd_addr, - uint16_t max_lat, - uint16_t min_rmt_to, - uint16_t min_loc_to); - [[nodiscard]] tBTM_STATUS (*BTM_SwitchRoleToCentral)( - const RawAddress& remote_bd_addr); + [[nodiscard]] tBTM_STATUS (*BTM_SetSsrParams)(const RawAddress& bd_addr, uint16_t max_lat, + uint16_t min_rmt_to, uint16_t min_loc_to); + [[nodiscard]] tBTM_STATUS (*BTM_SwitchRoleToCentral)(const RawAddress& remote_bd_addr); void (*BTM_block_role_switch_for)(const RawAddress& peer_addr); void (*BTM_block_sniff_mode_for)(const RawAddress& peer_addr); void (*BTM_default_unblock_role_switch)(); @@ -98,46 +86,37 @@ struct btm_client_interface_t { struct { [[nodiscard]] tBTM_STATUS (*BTM_GetLinkSuperTout)(const RawAddress& bd_addr, uint16_t* p_timeout); - [[nodiscard]] tBTM_STATUS (*BTM_ReadRSSI)(const RawAddress& bd_addr, - tBTM_CMPL_CB* p_cb); + [[nodiscard]] tBTM_STATUS (*BTM_ReadRSSI)(const RawAddress& bd_addr, tBTM_CMPL_CB* p_cb); } link_controller; SecurityClientInterface security; struct { - [[nodiscard]] tBTM_STATUS (*BTM_BleGetEnergyInfo)( - tBTM_BLE_ENERGY_INFO_CBACK* callback); - [[nodiscard]] tBTM_STATUS (*BTM_BleObserve)( - bool start, uint8_t duration, tBTM_INQ_RESULTS_CB* p_results_cb, - tBTM_CMPL_CB* p_cmpl_cb, bool low_latency_scan); + [[nodiscard]] tBTM_STATUS (*BTM_BleGetEnergyInfo)(tBTM_BLE_ENERGY_INFO_CBACK* callback); + [[nodiscard]] tBTM_STATUS (*BTM_BleObserve)(bool start, uint8_t duration, + tBTM_INQ_RESULTS_CB* p_results_cb, + tBTM_CMPL_CB* p_cmpl_cb, bool low_latency_scan); [[nodiscard]] tBTM_STATUS (*BTM_SetBleDataLength)(const RawAddress& bd_addr, uint16_t tx_pdu_length); - void (*BTM_BleReadControllerFeatures)( - tBTM_BLE_CTRL_FEATURES_CBACK* p_vsc_cback); - void (*BTM_BleSetPhy)(const RawAddress& bd_addr, uint8_t tx_phys, - uint8_t rx_phys, uint16_t phy_options); - void (*BTM_BleSetPrefConnParams)(const RawAddress& bd_addr, - uint16_t min_conn_int, - uint16_t max_conn_int, - uint16_t peripheral_latency, + void (*BTM_BleReadControllerFeatures)(tBTM_BLE_CTRL_FEATURES_CBACK* p_vsc_cback); + void (*BTM_BleSetPhy)(const RawAddress& bd_addr, uint8_t tx_phys, uint8_t rx_phys, + uint16_t phy_options); + void (*BTM_BleSetPrefConnParams)(const RawAddress& bd_addr, uint16_t min_conn_int, + uint16_t max_conn_int, uint16_t peripheral_latency, uint16_t supervision_tout); [[nodiscard]] bool (*BTM_UseLeLink)(const RawAddress& bd_addr); - [[nodiscard]] bool (*BTM_IsRemoteVersionReceived)( - const RawAddress& remote_bda); + [[nodiscard]] bool (*BTM_IsRemoteVersionReceived)(const RawAddress& remote_bda); void (*BTM_SetConsolidationCallback)(BTM_CONSOLIDATION_CB* cb); } ble; struct { - [[nodiscard]] tBTM_STATUS (*BTM_CreateSco)(const RawAddress* bd_addr, - bool is_orig, uint16_t pkt_types, - uint16_t* p_sco_inx, - tBTM_SCO_CB* p_conn_cb, - tBTM_SCO_CB* p_disc_cb); - [[nodiscard]] tBTM_STATUS (*BTM_RegForEScoEvts)( - uint16_t sco_inx, tBTM_ESCO_CBACK* p_esco_cback); + [[nodiscard]] tBTM_STATUS (*BTM_CreateSco)(const RawAddress* bd_addr, bool is_orig, + uint16_t pkt_types, uint16_t* p_sco_inx, + tBTM_SCO_CB* p_conn_cb, tBTM_SCO_CB* p_disc_cb); + [[nodiscard]] tBTM_STATUS (*BTM_RegForEScoEvts)(uint16_t sco_inx, + tBTM_ESCO_CBACK* p_esco_cback); [[nodiscard]] tBTM_STATUS (*BTM_RemoveSco)(uint16_t sco_inx); void (*BTM_WriteVoiceSettings)(uint16_t settings); - void (*BTM_EScoConnRsp)(uint16_t sco_inx, tHCI_STATUS hci_status, - enh_esco_params_t* p_parms); + void (*BTM_EScoConnRsp)(uint16_t sco_inx, tHCI_STATUS hci_status, enh_esco_params_t* p_parms); [[nodiscard]] uint8_t (*BTM_GetNumScoLinks)(); [[nodiscard]] tBTM_STATUS (*BTM_SetEScoMode)(enh_esco_params_t* p_parms); [[nodiscard]] tBTM_SCO_DEBUG_DUMP (*BTM_GetScoDebugDump)(void); @@ -147,7 +126,7 @@ struct btm_client_interface_t { struct { [[nodiscard]] tBTM_STATUS (*BTM_ReadLocalDeviceName)(const char** p_name); [[nodiscard]] tBTM_STATUS (*BTM_ReadLocalDeviceNameFromController)( - tBTM_CMPL_CB* p_rln_cmpl_cback); + tBTM_CMPL_CB* p_rln_cmpl_cback); [[nodiscard]] tBTM_STATUS (*BTM_SetLocalDeviceName)(const char* p_name); [[nodiscard]] tBTM_STATUS (*BTM_SetDeviceClass)(DEV_CLASS dev_class); [[nodiscard]] bool (*BTM_IsDeviceUp)(); @@ -156,13 +135,12 @@ struct btm_client_interface_t { struct { [[nodiscard]] tBTM_STATUS (*BTM_WriteEIR)(BT_HDR* p_buff); - [[nodiscard]] uint8_t (*BTM_GetEirSupportedServices)(uint32_t* p_eir_uuid, - uint8_t** p, + [[nodiscard]] uint8_t (*BTM_GetEirSupportedServices)(uint32_t* p_eir_uuid, uint8_t** p, uint8_t max_num_uuid16, uint8_t* p_num_uuid16); - [[nodiscard]] uint8_t (*BTM_GetEirUuidList)( - const uint8_t* p_eir, size_t eir_len, uint8_t uuid_size, - uint8_t* p_num_uuid, uint8_t* p_uuid_list, uint8_t max_num_uuid); + [[nodiscard]] uint8_t (*BTM_GetEirUuidList)(const uint8_t* p_eir, size_t eir_len, + uint8_t uuid_size, uint8_t* p_num_uuid, + uint8_t* p_uuid_list, uint8_t max_num_uuid); void (*BTM_AddEirService)(uint32_t* p_eir_uuid, uint16_t uuid16); void (*BTM_RemoveEirService)(uint32_t* p_eir_uuid, uint16_t uuid16); } eir; @@ -175,8 +153,7 @@ struct btm_client_interface_t { } db; struct { - void (*BTM_VendorSpecificCommand)(uint16_t opcode, uint8_t param_len, - uint8_t* p_param_buf, + void (*BTM_VendorSpecificCommand)(uint16_t opcode, uint8_t param_len, uint8_t* p_param_buf, tBTM_VSC_CMPL_CB* p_cb); } vendor; }; diff --git a/system/stack/include/btm_iso_api.h b/system/stack/include/btm_iso_api.h index 7e968e9d31d..4012695755a 100644 --- a/system/stack/include/btm_iso_api.h +++ b/system/stack/include/btm_iso_api.h @@ -29,15 +29,12 @@ namespace hci { namespace iso_manager { struct CigCallbacks { virtual ~CigCallbacks() = default; - virtual void OnSetupIsoDataPath(uint8_t status, uint16_t conn_handle, - uint8_t cig_id) = 0; - virtual void OnRemoveIsoDataPath(uint8_t status, uint16_t conn_handle, - uint8_t cig_id) = 0; - virtual void OnIsoLinkQualityRead( - uint8_t conn_handle, uint8_t cig_id, uint32_t txUnackedPackets, - uint32_t txFlushedPackets, uint32_t txLastSubeventPackets, - uint32_t retransmittedPackets, uint32_t crcErrorPackets, - uint32_t rxUnreceivedPackets, uint32_t duplicatePackets) = 0; + virtual void OnSetupIsoDataPath(uint8_t status, uint16_t conn_handle, uint8_t cig_id) = 0; + virtual void OnRemoveIsoDataPath(uint8_t status, uint16_t conn_handle, uint8_t cig_id) = 0; + virtual void OnIsoLinkQualityRead(uint8_t conn_handle, uint8_t cig_id, uint32_t txUnackedPackets, + uint32_t txFlushedPackets, uint32_t txLastSubeventPackets, + uint32_t retransmittedPackets, uint32_t crcErrorPackets, + uint32_t rxUnreceivedPackets, uint32_t duplicatePackets) = 0; virtual void OnCisEvent(uint8_t event, void* data) = 0; virtual void OnCigEvent(uint8_t event, void* data) = 0; @@ -45,17 +42,15 @@ struct CigCallbacks { struct BigCallbacks { virtual ~BigCallbacks() = default; - virtual void OnSetupIsoDataPath(uint8_t status, uint16_t conn_handle, - uint8_t big_id) = 0; - virtual void OnRemoveIsoDataPath(uint8_t status, uint16_t conn_handle, - uint8_t big_id) = 0; + virtual void OnSetupIsoDataPath(uint8_t status, uint16_t conn_handle, uint8_t big_id) = 0; + virtual void OnRemoveIsoDataPath(uint8_t status, uint16_t conn_handle, uint8_t big_id) = 0; virtual void OnBigEvent(uint8_t event, void* data) = 0; }; } // namespace iso_manager class IsoManager { - public: +public: IsoManager(); IsoManager(const IsoManager&) = delete; IsoManager& operator=(const IsoManager&) = delete; @@ -95,8 +90,7 @@ class IsoManager { * @param cig_id connected isochronous group id * @param cig_params CIG parameters */ - virtual void CreateCig(uint8_t cig_id, - struct iso_manager::cig_create_params cig_params); + virtual void CreateCig(uint8_t cig_id, struct iso_manager::cig_create_params cig_params); /** * Reconfigures connected isochronous group (CIG) according to given params. @@ -104,8 +98,7 @@ class IsoManager { * @param cig_id connected isochronous group id * @param cig_params CIG parameters */ - virtual void ReconfigureCig(uint8_t cig_id, - struct iso_manager::cig_create_params cig_params); + virtual void ReconfigureCig(uint8_t cig_id, struct iso_manager::cig_create_params cig_params); /** * Initiates removing of connected isochronous group (CIG). @@ -120,8 +113,7 @@ class IsoManager { * * @param conn_params A set of cis and acl connection handles */ - virtual void EstablishCis( - struct iso_manager::cis_establish_params conn_params); + virtual void EstablishCis(struct iso_manager::cis_establish_params conn_params); /** * Initiates disconnection of connected isochronous stream (CIS). @@ -138,9 +130,8 @@ class IsoManager { * @param conn_handle handle of BIS or CIS connection * @param path_params iso data path parameters */ - virtual void SetupIsoDataPath( - uint16_t conn_handle, - struct iso_manager::iso_data_path_params path_params); + virtual void SetupIsoDataPath(uint16_t conn_handle, + struct iso_manager::iso_data_path_params path_params); /** * Initiates removal of isochronous data path for connected isochronous @@ -166,8 +157,7 @@ class IsoManager { * @param data data buffer. The ownership of data is not being transferred. * @param data_len data buffer length */ - virtual void SendIsoData(uint16_t conn_handle, const uint8_t* data, - uint16_t data_len); + virtual void SendIsoData(uint16_t conn_handle, const uint8_t* data, uint16_t data_len); /** * Creates the Broadcast Isochronous Group @@ -175,8 +165,7 @@ class IsoManager { * @param big_id host assigned BIG identifier * @param big_params BIG parameters */ - virtual void CreateBig(uint8_t big_id, - struct iso_manager::big_create_params big_params); + virtual void CreateBig(uint8_t big_id, struct iso_manager::big_create_params big_params); /** * Terminates the Broadcast Isochronous Group @@ -223,8 +212,7 @@ class IsoManager { * not being transferred * @param length event packet buffer length */ - virtual void HandleHciEvent(uint8_t sub_code, uint8_t* params, - uint16_t length); + virtual void HandleHciEvent(uint8_t sub_code, uint8_t* params, uint16_t length); /** * Return the current number of ISO channels @@ -246,7 +234,7 @@ class IsoManager { */ void Dump(int fd); - private: +private: struct impl; std::unique_ptr pimpl_; }; diff --git a/system/stack/include/btm_log_history.h b/system/stack/include/btm_log_history.h index e9f1e0bb138..5c957483d33 100644 --- a/system/stack/include/btm_log_history.h +++ b/system/stack/include/btm_log_history.h @@ -21,11 +21,9 @@ #include "types/ble_address_with_type.h" #include "types/raw_address.h" -void BTM_LogHistory(const std::string& tag, const RawAddress& addr, - const std::string& msg); -void BTM_LogHistory(const std::string& tag, const RawAddress& addr, - const std::string& msg, const std::string& extra); -void BTM_LogHistory(const std::string& tag, const tBLE_BD_ADDR& addr, - const std::string& msg); -void BTM_LogHistory(const std::string& tag, const tBLE_BD_ADDR& addr, - const std::string& msg, const std::string& extra); +void BTM_LogHistory(const std::string& tag, const RawAddress& addr, const std::string& msg); +void BTM_LogHistory(const std::string& tag, const RawAddress& addr, const std::string& msg, + const std::string& extra); +void BTM_LogHistory(const std::string& tag, const tBLE_BD_ADDR& addr, const std::string& msg); +void BTM_LogHistory(const std::string& tag, const tBLE_BD_ADDR& addr, const std::string& msg, + const std::string& extra); diff --git a/system/stack/include/btm_sec_api.h b/system/stack/include/btm_sec_api.h index 51b50902c10..fcfdd44448e 100644 --- a/system/stack/include/btm_sec_api.h +++ b/system/stack/include/btm_sec_api.h @@ -43,8 +43,8 @@ * Returns void * ******************************************************************************/ -void BTM_SecAddDevice(const RawAddress& bd_addr, const DEV_CLASS dev_class, - LinkKey link_key, uint8_t key_type, uint8_t pin_length); +void BTM_SecAddDevice(const RawAddress& bd_addr, const DEV_CLASS dev_class, LinkKey link_key, + uint8_t key_type, uint8_t pin_length); /** Free resources associated with the device associated with |bd_addr| address. * @@ -92,8 +92,7 @@ bool btm_sec_is_a_bonded_dev(const RawAddress& bda); * the results * ******************************************************************************/ -tBTM_STATUS BTM_DeleteStoredLinkKey(const RawAddress* bd_addr, - tBTM_CMPL_CB* p_cb); +tBTM_STATUS BTM_DeleteStoredLinkKey(const RawAddress* bd_addr, tBTM_CMPL_CB* p_cb); /******************************************************************************* * diff --git a/system/stack/include/btm_sec_api_types.h b/system/stack/include/btm_sec_api_types.h index 1a52d46591f..6b21574ed1e 100644 --- a/system/stack/include/btm_sec_api_types.h +++ b/system/stack/include/btm_sec_api_types.h @@ -99,7 +99,7 @@ enum : uint16_t { }; /* Security Flags [bit mask] (BTM_GetSecurityFlags) -*/ + */ #define BTM_SEC_FLAG_AUTHENTICATED 0x02 #define BTM_SEC_FLAG_ENCRYPTED 0x04 #define BTM_SEC_FLAG_LKEY_KNOWN 0x10 @@ -107,7 +107,7 @@ enum : uint16_t { /* Link Key types used to generate the new link key. * returned in link key notification callback function -*/ + */ #define BTM_LKEY_TYPE_COMBINATION HCI_LKEY_TYPE_COMBINATION #define BTM_LKEY_TYPE_REMOTE_UNIT HCI_LKEY_TYPE_REMOTE_UNIT #define BTM_LKEY_TYPE_DEBUG_COMB HCI_LKEY_TYPE_DEBUG_COMB @@ -300,21 +300,20 @@ typedef struct { /* data type for BTM_SP_IO_RSP_EVT */ typedef struct { - RawAddress bd_addr; /* peer address */ - tBTM_IO_CAP io_cap; /* peer IO capabilities */ - tBTM_OOB_DATA - oob_data; /* OOB data present at peer device for the local device */ + RawAddress bd_addr; /* peer address */ + tBTM_IO_CAP io_cap; /* peer IO capabilities */ + tBTM_OOB_DATA oob_data; /* OOB data present at peer device for the local device */ tBTM_AUTH_REQ auth_req; /* Authentication required for peer device */ } tBTM_SP_IO_RSP; /* data type for BTM_SP_CFM_REQ_EVT */ typedef struct { - RawAddress bd_addr; /* peer address */ - DEV_CLASS dev_class; /* peer CoD */ - BD_NAME bd_name; /* peer device name */ - uint32_t num_val; /* the numeric value for comparison. If just_works, do not - show this number to UI */ - bool just_works; /* true, if "Just Works" association model */ + RawAddress bd_addr; /* peer address */ + DEV_CLASS dev_class; /* peer CoD */ + BD_NAME bd_name; /* peer device name */ + uint32_t num_val; /* the numeric value for comparison. If just_works, do not + show this number to UI */ + bool just_works; /* true, if "Just Works" association model */ tBTM_AUTH_REQ loc_auth_req; /* Authentication required for local device */ tBTM_AUTH_REQ rmt_auth_req; /* Authentication required for peer device */ tBTM_IO_CAP loc_io_caps; /* IO Capabilities of the local device */ @@ -323,17 +322,17 @@ typedef struct { /* data type for BTM_SP_KEY_REQ_EVT */ typedef struct { - RawAddress bd_addr; /* peer address */ - DEV_CLASS dev_class; /* peer CoD */ - BD_NAME bd_name; /* peer device name */ + RawAddress bd_addr; /* peer address */ + DEV_CLASS dev_class; /* peer CoD */ + BD_NAME bd_name; /* peer device name */ } tBTM_SP_KEY_REQ; /* data type for BTM_SP_KEY_NOTIF_EVT */ typedef struct { - RawAddress bd_addr; /* peer address */ - DEV_CLASS dev_class; /* peer CoD */ - BD_NAME bd_name; /* peer device name */ - uint32_t passkey; /* passkey */ + RawAddress bd_addr; /* peer address */ + DEV_CLASS dev_class; /* peer CoD */ + BD_NAME bd_name; /* peer device name */ + uint32_t passkey; /* passkey */ } tBTM_SP_KEY_NOTIF; /* data type for BTM_SP_LOC_OOB_EVT */ @@ -347,9 +346,9 @@ typedef struct { /* data type for BTM_SP_RMT_OOB_EVT */ typedef struct { - RawAddress bd_addr; /* peer address */ - DEV_CLASS dev_class; /* peer CoD */ - BD_NAME bd_name; /* peer device name */ + RawAddress bd_addr; /* peer address */ + DEV_CLASS dev_class; /* peer CoD */ + BD_NAME bd_name; /* peer device name */ } tBTM_SP_RMT_OOB; typedef union { @@ -364,12 +363,10 @@ typedef union { /* Simple Pairing Events. Called by the stack when Simple Pairing related * events occur. -*/ -typedef tBTM_STATUS(tBTM_SP_CALLBACK)(tBTM_SP_EVT event, - tBTM_SP_EVT_DATA* p_data); + */ +typedef tBTM_STATUS(tBTM_SP_CALLBACK)(tBTM_SP_EVT event, tBTM_SP_EVT_DATA* p_data); -typedef void(tBTM_MKEY_CALLBACK)(const RawAddress& bd_addr, uint8_t status, - uint8_t key_flag); +typedef void(tBTM_MKEY_CALLBACK)(const RawAddress& bd_addr, uint8_t status, uint8_t key_flag); /* Encryption enabled/disabled complete: Optionally passed with * BTM_SetEncryption. @@ -377,15 +374,15 @@ typedef void(tBTM_MKEY_CALLBACK)(const RawAddress& bd_addr, uint8_t status, * BD Address of remote * optional data passed in by BTM_SetEncryption * tBTM_STATUS - result of the operation -*/ -typedef void(tBTM_SEC_CALLBACK)(RawAddress bd_addr, tBT_TRANSPORT transport, - void* p_ref_data, tBTM_STATUS result); + */ +typedef void(tBTM_SEC_CALLBACK)(RawAddress bd_addr, tBT_TRANSPORT transport, void* p_ref_data, + tBTM_STATUS result); typedef tBTM_SEC_CALLBACK tBTM_SEC_CALLBACK; /* Bond Cancel complete. Parameters are * Result of the cancel operation * -*/ + */ typedef void(tBTM_BOND_CANCEL_CMPL_CALLBACK)(tBTM_STATUS result); typedef enum : uint8_t { diff --git a/system/stack/include/btm_status.h b/system/stack/include/btm_status.h index cc0c822764e..25acb325c9f 100644 --- a/system/stack/include/btm_status.h +++ b/system/stack/include/btm_status.h @@ -24,26 +24,26 @@ /* BTM application return status codes */ enum : uint8_t { - BTM_SUCCESS = 0, /* 0 Command succeeded */ - BTM_CMD_STARTED, /* 1 Command started OK. */ - BTM_BUSY, /* 2 Device busy with another command */ - BTM_NO_RESOURCES, /* 3 No resources to issue command */ - BTM_MODE_UNSUPPORTED, /* 4 Request for 1 or more unsupported modes */ - BTM_ILLEGAL_VALUE, /* 5 Illegal parameter value */ - BTM_WRONG_MODE, /* 6 Device in wrong mode for request */ - BTM_UNKNOWN_ADDR, /* 7 Unknown remote BD address */ - BTM_DEVICE_TIMEOUT, /* 8 Device timeout */ - BTM_BAD_VALUE_RET, /* 9 A bad value was received from HCI */ - BTM_ERR_PROCESSING, /* 10 Generic error */ - BTM_NOT_AUTHORIZED, /* 11 Authorization failed */ - BTM_DEV_RESET, /* 12 Device has been reset */ - BTM_CMD_STORED, /* 13 request is stored in control block */ - BTM_ILLEGAL_ACTION, /* 14 state machine gets illegal command */ - BTM_DELAY_CHECK, /* 15 delay the check on encryption */ - BTM_SCO_BAD_LENGTH, /* 16 Bad SCO over HCI data length */ - BTM_SUCCESS_NO_SECURITY, /* 17 security passed, no security set */ - BTM_FAILED_ON_SECURITY, /* 18 security failed */ - BTM_REPEATED_ATTEMPTS, /* 19 repeated attempts for LE security requests */ + BTM_SUCCESS = 0, /* 0 Command succeeded */ + BTM_CMD_STARTED, /* 1 Command started OK. */ + BTM_BUSY, /* 2 Device busy with another command */ + BTM_NO_RESOURCES, /* 3 No resources to issue command */ + BTM_MODE_UNSUPPORTED, /* 4 Request for 1 or more unsupported modes */ + BTM_ILLEGAL_VALUE, /* 5 Illegal parameter value */ + BTM_WRONG_MODE, /* 6 Device in wrong mode for request */ + BTM_UNKNOWN_ADDR, /* 7 Unknown remote BD address */ + BTM_DEVICE_TIMEOUT, /* 8 Device timeout */ + BTM_BAD_VALUE_RET, /* 9 A bad value was received from HCI */ + BTM_ERR_PROCESSING, /* 10 Generic error */ + BTM_NOT_AUTHORIZED, /* 11 Authorization failed */ + BTM_DEV_RESET, /* 12 Device has been reset */ + BTM_CMD_STORED, /* 13 request is stored in control block */ + BTM_ILLEGAL_ACTION, /* 14 state machine gets illegal command */ + BTM_DELAY_CHECK, /* 15 delay the check on encryption */ + BTM_SCO_BAD_LENGTH, /* 16 Bad SCO over HCI data length */ + BTM_SUCCESS_NO_SECURITY, /* 17 security passed, no security set */ + BTM_FAILED_ON_SECURITY, /* 18 security failed */ + BTM_REPEATED_ATTEMPTS, /* 19 repeated attempts for LE security requests */ BTM_MODE4_LEVEL4_NOT_SUPPORTED, /* 20 Secure Connections Only Mode can't be supported */ BTM_DEV_RESTRICT_LISTED, /* 21 The device is restrict listed */ @@ -57,12 +57,12 @@ enum : uint8_t { }; typedef uint8_t tBTM_STATUS; -inline uint8_t btm_status_value(const tBTM_STATUS& status) { - return static_cast(status); -} +inline uint8_t btm_status_value(const tBTM_STATUS& status) { return static_cast(status); } inline tBTM_STATUS to_btm_status(const uint8_t& value) { - if (value >= BTM_MAX_STATUS_VALUE) return BTM_UNDEFINED; + if (value >= BTM_MAX_STATUS_VALUE) { + return BTM_UNDEFINED; + } return static_cast(value); } diff --git a/system/stack/include/btu_hcif.h b/system/stack/include/btu_hcif.h index 5c7fc702e51..162e41ef592 100644 --- a/system/stack/include/btu_hcif.h +++ b/system/stack/include/btu_hcif.h @@ -28,11 +28,8 @@ */ void btu_hcif_process_event(uint8_t controller_id, const BT_HDR* p_buf); void btu_hcif_send_cmd(uint8_t controller_id, const BT_HDR* p_msg); -void btu_hcif_send_cmd_with_cb(const base::Location& posted_from, - uint16_t opcode, uint8_t* params, - uint8_t params_len, - base::OnceCallback cb); +void btu_hcif_send_cmd_with_cb(const base::Location& posted_from, uint16_t opcode, uint8_t* params, + uint8_t params_len, base::OnceCallback cb); namespace bluetooth::legacy::testing { -void btu_hcif_hdl_command_status(uint16_t opcode, uint8_t status, - const uint8_t* p_cmd); +void btu_hcif_hdl_command_status(uint16_t opcode, uint8_t status, const uint8_t* p_cmd); } // namespace bluetooth::legacy::testing \ No newline at end of file diff --git a/system/stack/include/gap_api.h b/system/stack/include/gap_api.h index 05773ed6f0b..ccc22b9305a 100644 --- a/system/stack/include/gap_api.h +++ b/system/stack/include/gap_api.h @@ -89,9 +89,8 @@ union tGAP_CB_DATA { ****************************************************************************/ /* * Callback function for connection services -*/ -typedef void(tGAP_CONN_CALLBACK)(uint16_t gap_handle, uint16_t event, - tGAP_CB_DATA* data); + */ +typedef void(tGAP_CONN_CALLBACK)(uint16_t gap_handle, uint16_t event, tGAP_CB_DATA* data); typedef struct { uint16_t int_min; @@ -109,8 +108,8 @@ typedef union { } tGAP_BLE_ATTR_VALUE; -typedef void(tGAP_BLE_CMPL_CBACK)(bool status, const RawAddress& addr, - uint16_t length, char* p_name); +typedef void(tGAP_BLE_CMPL_CBACK)(bool status, const RawAddress& addr, uint16_t length, + char* p_name); /***************************************************************************** * External Function Declarations @@ -128,10 +127,9 @@ typedef void(tGAP_BLE_CMPL_CBACK)(bool status, const RawAddress& addr, * GAP_INVALID_HANDLE * ******************************************************************************/ -uint16_t GAP_ConnOpen(const char* p_serv_name, uint8_t service_id, - bool is_server, const RawAddress* p_rem_bda, uint16_t psm, - uint16_t le_mps, tL2CAP_CFG_INFO* p_cfg, - tL2CAP_ERTM_INFO* ertm_info, uint16_t security, +uint16_t GAP_ConnOpen(const char* p_serv_name, uint8_t service_id, bool is_server, + const RawAddress* p_rem_bda, uint16_t psm, uint16_t le_mps, + tL2CAP_CFG_INFO* p_cfg, tL2CAP_ERTM_INFO* ertm_info, uint16_t security, tGAP_CONN_CALLBACK* p_cb, tBT_TRANSPORT transport); /******************************************************************************* @@ -159,8 +157,7 @@ uint16_t GAP_ConnClose(uint16_t gap_handle); * GAP_NO_DATA_AVAIL - no data available * ******************************************************************************/ -uint16_t GAP_ConnReadData(uint16_t gap_handle, uint8_t* p_data, - uint16_t max_len, uint16_t* p_len); +uint16_t GAP_ConnReadData(uint16_t gap_handle, uint8_t* p_data, uint16_t max_len, uint16_t* p_len); /******************************************************************************* * @@ -276,8 +273,7 @@ bool GAP_BleReadPeerPrefConnParams(const RawAddress& peer_bda); * Returns true if request accepted * ******************************************************************************/ -bool GAP_BleReadPeerDevName(const RawAddress& peer_bda, - tGAP_BLE_CMPL_CBACK* p_cback); +bool GAP_BleReadPeerDevName(const RawAddress& peer_bda, tGAP_BLE_CMPL_CBACK* p_cback); /******************************************************************************* * diff --git a/system/stack/include/gatt_api.h b/system/stack/include/gatt_api.h index c2e6bf2f2cf..892047b6307 100644 --- a/system/stack/include/gatt_api.h +++ b/system/stack/include/gatt_api.h @@ -282,8 +282,7 @@ typedef enum : uint16_t { } tGATT_DISCONN_REASON; -inline std::string gatt_disconnection_reason_text( - const tGATT_DISCONN_REASON& reason) { +inline std::string gatt_disconnection_reason_text(const tGATT_DISCONN_REASON& reason) { switch (reason) { CASE_RETURN_TEXT(GATT_CONN_OK); CASE_RETURN_TEXT(GATT_CONN_L2C_FAILURE); @@ -300,21 +299,21 @@ inline std::string gatt_disconnection_reason_text( } /* MAX GATT MTU size -*/ + */ #ifndef GATT_MAX_MTU_SIZE #define GATT_MAX_MTU_SIZE 517 #endif /* default GATT MTU size over LE link -*/ + */ #define GATT_DEF_BLE_MTU_SIZE 23 /* invalid connection ID -*/ + */ #define GATT_INVALID_CONN_ID 0xFFFF /* GATT notification caching timer, default to be three seconds -*/ + */ #ifndef GATTC_NOTIF_TIMEOUT #define GATTC_NOTIF_TIMEOUT 3 #endif @@ -324,15 +323,15 @@ inline std::string gatt_disconnection_reason_text( ****************************************************************************/ /* Attribute permissions -*/ -#define GATT_PERM_READ (1 << 0) /* bit 0 */ -#define GATT_PERM_READ_ENCRYPTED (1 << 1) /* bit 1 */ -#define GATT_PERM_READ_ENC_MITM (1 << 2) /* bit 2 */ -#define GATT_PERM_WRITE (1 << 4) /* bit 4 */ -#define GATT_PERM_WRITE_ENCRYPTED (1 << 5) /* bit 5 */ -#define GATT_PERM_WRITE_ENC_MITM (1 << 6) /* bit 6 */ -#define GATT_PERM_WRITE_SIGNED (1 << 7) /* bit 7 */ -#define GATT_PERM_WRITE_SIGNED_MITM (1 << 8) /* bit 8 */ + */ +#define GATT_PERM_READ (1 << 0) /* bit 0 */ +#define GATT_PERM_READ_ENCRYPTED (1 << 1) /* bit 1 */ +#define GATT_PERM_READ_ENC_MITM (1 << 2) /* bit 2 */ +#define GATT_PERM_WRITE (1 << 4) /* bit 4 */ +#define GATT_PERM_WRITE_ENCRYPTED (1 << 5) /* bit 5 */ +#define GATT_PERM_WRITE_ENC_MITM (1 << 6) /* bit 6 */ +#define GATT_PERM_WRITE_SIGNED (1 << 7) /* bit 7 */ +#define GATT_PERM_WRITE_SIGNED_MITM (1 << 8) /* bit 8 */ #define GATT_PERM_READ_IF_ENCRYPTED_OR_DISCOVERABLE (1 << 9) /* bit 9 */ typedef uint16_t tGATT_PERM; @@ -344,27 +343,22 @@ typedef uint16_t tGATT_PERM; GATT_PERM_READ_IF_ENCRYPTED_OR_DISCOVERABLE) #define GATT_READ_AUTH_REQUIRED (GATT_PERM_READ_ENCRYPTED) #define GATT_READ_MITM_REQUIRED (GATT_PERM_READ_ENC_MITM) -#define GATT_READ_ENCRYPTED_REQUIRED \ - (GATT_PERM_READ_ENCRYPTED | GATT_PERM_READ_ENC_MITM) +#define GATT_READ_ENCRYPTED_REQUIRED (GATT_PERM_READ_ENCRYPTED | GATT_PERM_READ_ENC_MITM) #define GATT_WRITE_ALLOWED \ (GATT_PERM_WRITE | GATT_PERM_WRITE_ENCRYPTED | GATT_PERM_WRITE_ENC_MITM | \ GATT_PERM_WRITE_SIGNED | GATT_PERM_WRITE_SIGNED_MITM) -#define GATT_WRITE_AUTH_REQUIRED \ - (GATT_PERM_WRITE_ENCRYPTED | GATT_PERM_WRITE_SIGNED) +#define GATT_WRITE_AUTH_REQUIRED (GATT_PERM_WRITE_ENCRYPTED | GATT_PERM_WRITE_SIGNED) -#define GATT_WRITE_MITM_REQUIRED \ - (GATT_PERM_WRITE_ENC_MITM | GATT_PERM_WRITE_SIGNED_MITM) +#define GATT_WRITE_MITM_REQUIRED (GATT_PERM_WRITE_ENC_MITM | GATT_PERM_WRITE_SIGNED_MITM) -#define GATT_WRITE_ENCRYPTED_PERM \ - (GATT_PERM_WRITE_ENCRYPTED | GATT_PERM_WRITE_ENC_MITM) +#define GATT_WRITE_ENCRYPTED_PERM (GATT_PERM_WRITE_ENCRYPTED | GATT_PERM_WRITE_ENC_MITM) -#define GATT_WRITE_SIGNED_PERM \ - (GATT_PERM_WRITE_SIGNED | GATT_PERM_WRITE_SIGNED_MITM) +#define GATT_WRITE_SIGNED_PERM (GATT_PERM_WRITE_SIGNED | GATT_PERM_WRITE_SIGNED_MITM) /* Characteristic properties -*/ + */ #define GATT_CHAR_PROP_BIT_BROADCAST (1 << 0) #define GATT_CHAR_PROP_BIT_READ (1 << 1) #define GATT_CHAR_PROP_BIT_WRITE_NR (1 << 2) @@ -376,7 +370,7 @@ typedef uint16_t tGATT_PERM; typedef uint8_t tGATT_CHAR_PROP; /* Format of the value of a characteristic. enumeration type -*/ + */ enum { GATT_FORMAT_RES, /* rfu */ GATT_FORMAT_BOOL, /* 0x01 boolean */ @@ -411,7 +405,7 @@ enum { typedef uint8_t tGATT_FORMAT; /* Characteristic Presentation Format Descriptor value -*/ + */ typedef struct { uint16_t unit; /* as UUIUD defined by SIG */ uint16_t descr; /* as UUID as defined by SIG */ @@ -421,7 +415,7 @@ typedef struct { } tGATT_CHAR_PRES; /* Characteristic Report reference Descriptor format -*/ + */ typedef struct { uint8_t rpt_id; /* report ID */ uint8_t rpt_type; /* report type */ @@ -436,7 +430,7 @@ typedef struct { } tGATT_VALID_RANGE; /* Characteristic Aggregate Format attribute value -*/ + */ #define GATT_AGGR_HANDLE_NUM_MAX 10 typedef struct { uint8_t num_handle; @@ -444,33 +438,33 @@ typedef struct { } tGATT_CHAR_AGGRE; /* Characteristic descriptor: Extended Properties value -*/ + */ /* permits reliable writes of the Characteristic Value */ #define GATT_CHAR_BIT_REL_WRITE 0x0001 /* permits writes to the characteristic descriptor */ #define GATT_CHAR_BIT_WRITE_AUX 0x0002 /* characteristic descriptor: client configuration value -*/ + */ #define GATT_CLT_CONFIG_NONE 0x0000 #define GATT_CLT_CONFIG_NOTIFICATION 0x0001 #define GATT_CLT_CONFIG_INDICATION 0x0002 /* characteristic descriptor: server configuration value -*/ + */ #define GATT_SVR_CONFIG_NONE 0x0000 #define GATT_SVR_CONFIG_BROADCAST 0x0001 typedef uint16_t tGATT_SVR_CHAR_CONFIG; /* Characteristic descriptor: Extended Properties value -*/ + */ /* permits reliable writes of the Characteristic Value */ #define GATT_CHAR_BIT_REL_WRITE 0x0001 /* permits writes to the characteristic descriptor */ #define GATT_CHAR_BIT_WRITE_AUX 0x0002 /* authentication requirement -*/ + */ #define GATT_AUTH_REQ_NONE 0 #define GATT_AUTH_REQ_NO_MITM 1 /* unauthenticated encryption */ #define GATT_AUTH_REQ_MITM 2 /* authenticated encryption */ @@ -479,20 +473,20 @@ typedef uint16_t tGATT_SVR_CHAR_CONFIG; typedef uint8_t tGATT_AUTH_REQ; /* Attribute Value structure -*/ + */ typedef struct { uint16_t conn_id; - uint16_t handle; /* attribute handle */ - uint16_t offset; /* attribute value offset, if no offset is needed for the - command, ignore it */ - uint16_t len; /* length of attribute value */ + uint16_t handle; /* attribute handle */ + uint16_t offset; /* attribute value offset, if no offset is needed for the + command, ignore it */ + uint16_t len; /* length of attribute value */ tGATT_AUTH_REQ auth_req; /* authentication request */ uint8_t value[GATT_MAX_ATTR_LEN]; /* the actual attribute value */ } tGATT_VALUE; /* Union of the event data which is used in the server respond API to carry the * server response information -*/ + */ typedef union { /* data type member event */ tGATT_VALUE attr_value; /* READ, HANDLE_VALUE_IND, PREPARE_WRITE */ @@ -510,21 +504,19 @@ typedef struct { uint16_t handle; uint16_t offset; bool is_long; - bt_gatt_db_attribute_type_t - gatt_type; /* are we writing characteristic or descriptor */ + bt_gatt_db_attribute_type_t gatt_type; /* are we writing characteristic or descriptor */ } tGATT_READ_REQ; /* write request data */ typedef struct { - uint16_t handle; /* attribute handle */ - uint16_t offset; /* attribute value offset, if no offset is needed for the - command, ignore it */ - uint16_t len; /* length of attribute value */ - uint8_t value[GATT_MAX_ATTR_LEN]; /* the actual attribute value */ - bool need_rsp; /* need write response */ - bool is_prep; /* is prepare write */ - bt_gatt_db_attribute_type_t - gatt_type; /* are we writing characteristic or descriptor */ + uint16_t handle; /* attribute handle */ + uint16_t offset; /* attribute value offset, if no offset is needed for the + command, ignore it */ + uint16_t len; /* length of attribute value */ + uint8_t value[GATT_MAX_ATTR_LEN]; /* the actual attribute value */ + bool need_rsp; /* need write response */ + bool is_prep; /* is prepare write */ + bt_gatt_db_attribute_type_t gatt_type; /* are we writing characteristic or descriptor */ } tGATT_WRITE_REQ; /* callback data for server access request from client */ @@ -553,20 +545,20 @@ enum { typedef uint8_t tGATTS_REQ_TYPE; /* Client Used Data Structure -*/ + */ /* definition of different discovery types */ typedef enum : uint8_t { GATT_DISC_SRVC_ALL = 1, /* discover all services */ GATT_DISC_SRVC_BY_UUID, /* discover service of a special type */ GATT_DISC_INC_SRVC, /* discover the included service within a service */ - GATT_DISC_CHAR, /* discover characteristics of a service with/without type - requirement */ - GATT_DISC_CHAR_DSCPT, /* discover characteristic descriptors of a character */ - GATT_DISC_MAX /* maximum discover type */ + GATT_DISC_CHAR, /* discover characteristics of a service with/without type + requirement */ + GATT_DISC_CHAR_DSCPT, /* discover characteristic descriptors of a character */ + GATT_DISC_MAX /* maximum discover type */ } tGATT_DISC_TYPE; /* GATT read type enumeration -*/ + */ enum { GATT_READ_BY_TYPE = 1, GATT_READ_BY_HANDLE, @@ -579,7 +571,7 @@ enum { typedef uint8_t tGATT_READ_TYPE; /* Read By Type Request (GATT_READ_BY_TYPE) Data -*/ + */ typedef struct { tGATT_AUTH_REQ auth_req; uint16_t s_handle; @@ -588,9 +580,8 @@ typedef struct { } tGATT_READ_BY_TYPE; /* GATT_READ_MULTIPLE request data -*/ -#define GATT_MAX_READ_MULTI_HANDLES \ - 10 /* Max attributes to read in one request */ + */ +#define GATT_MAX_READ_MULTI_HANDLES 10 /* Max attributes to read in one request */ typedef struct { tGATT_AUTH_REQ auth_req; uint16_t num_handles; /* number of handles to read */ @@ -612,7 +603,7 @@ typedef struct { } tGATT_READ_PARTIAL; /* Read Request Data -*/ + */ typedef union { tGATT_READ_BY_TYPE service; tGATT_READ_BY_TYPE char_type; /* characteristic type */ @@ -626,7 +617,7 @@ enum { GATT_WRITE_NO_RSP = 1, GATT_WRITE, GATT_WRITE_PREPARE }; typedef uint8_t tGATT_WRITE_TYPE; /* Client Operation Complete Callback Data -*/ + */ typedef union { tGATT_VALUE att_value; uint16_t mtu; @@ -635,7 +626,7 @@ typedef union { } tGATT_CL_COMPLETE; /* GATT client operation type, used in client callback function -*/ + */ typedef enum : uint8_t { GATTC_OPTYPE_NONE = 0, GATTC_OPTYPE_DISCOVERY = 1, @@ -648,7 +639,7 @@ typedef enum : uint8_t { } tGATTC_OPTYPE; /* characteristic declaration -*/ + */ typedef struct { tGATT_CHAR_PROP char_prop; /* characteristic properties */ uint16_t val_handle; /* characteristic value attribute handle */ @@ -656,18 +647,18 @@ typedef struct { } tGATT_CHAR_DCLR_VAL; /* primary service group data -*/ + */ typedef struct { - uint16_t e_handle; /* ending handle of the group */ + uint16_t e_handle; /* ending handle of the group */ bluetooth::Uuid service_type; /* group type */ } tGATT_GROUP_VALUE; /* included service attribute value -*/ + */ typedef struct { bluetooth::Uuid service_type; /* included service UUID */ - uint16_t s_handle; /* starting handle */ - uint16_t e_handle; /* ending handle */ + uint16_t s_handle; /* starting handle */ + uint16_t e_handle; /* ending handle */ } tGATT_INCL_SRVC; typedef union { @@ -680,13 +671,12 @@ typedef union { uint16_t handle; /* When used with GATT_DISC_INC_SRVC type discovery result, it is the included service starting handle.*/ - tGATT_CHAR_DCLR_VAL - dclr_value; /* Characteristic declaration value. - This field is used with GATT_DISC_CHAR type discovery.*/ + tGATT_CHAR_DCLR_VAL dclr_value; /* Characteristic declaration value. + This field is used with GATT_DISC_CHAR type discovery.*/ } tGATT_DISC_VALUE; /* discover result record -*/ + */ typedef struct { bluetooth::Uuid type; uint16_t handle; @@ -705,23 +695,21 @@ typedef void(tGATT_DISC_RES_CB)(uint16_t conn_id, tGATT_DISC_TYPE disc_type, tGATT_DISC_RES* p_data); /* discover complete callback function */ -typedef void(tGATT_DISC_CMPL_CB)(uint16_t conn_id, tGATT_DISC_TYPE disc_type, - tGATT_STATUS status); +typedef void(tGATT_DISC_CMPL_CB)(uint16_t conn_id, tGATT_DISC_TYPE disc_type, tGATT_STATUS status); /* Define a callback function for when read/write/disc/config operation is * completed. */ -typedef void(tGATT_CMPL_CBACK)(uint16_t conn_id, tGATTC_OPTYPE op, - tGATT_STATUS status, tGATT_CL_COMPLETE* p_data); +typedef void(tGATT_CMPL_CBACK)(uint16_t conn_id, tGATTC_OPTYPE op, tGATT_STATUS status, + tGATT_CL_COMPLETE* p_data); /* Define a callback function when an initialized connection is established. */ -typedef void(tGATT_CONN_CBACK)(tGATT_IF gatt_if, const RawAddress& bda, - uint16_t conn_id, bool connected, - tGATT_DISCONN_REASON reason, +typedef void(tGATT_CONN_CBACK)(tGATT_IF gatt_if, const RawAddress& bda, uint16_t conn_id, + bool connected, tGATT_DISCONN_REASON reason, tBT_TRANSPORT transport); /* attribute request callback for ATT server */ -typedef void(tGATT_REQ_CBACK)(uint16_t conn_id, uint32_t trans_id, - tGATTS_REQ_TYPE type, tGATTS_DATA* p_data); +typedef void(tGATT_REQ_CBACK)(uint16_t conn_id, uint32_t trans_id, tGATTS_REQ_TYPE type, + tGATTS_DATA* p_data); /* channel congestion/uncongestion callback */ typedef void(tGATT_CONGESTION_CBACK)(uint16_t conn_id, bool congested); @@ -730,25 +718,22 @@ typedef void(tGATT_CONGESTION_CBACK)(uint16_t conn_id, bool congested); typedef void(tGATT_ENC_CMPL_CB)(tGATT_IF gatt_if, const RawAddress& bda); /* Define a callback function when phy is updated. */ -typedef void(tGATT_PHY_UPDATE_CB)(tGATT_IF gatt_if, uint16_t conn_id, - uint8_t tx_phy, uint8_t rx_phy, - tGATT_STATUS status); +typedef void(tGATT_PHY_UPDATE_CB)(tGATT_IF gatt_if, uint16_t conn_id, uint8_t tx_phy, + uint8_t rx_phy, tGATT_STATUS status); /* Define a callback function when connection parameters are updated */ -typedef void(tGATT_CONN_UPDATE_CB)(tGATT_IF gatt_if, uint16_t conn_id, - uint16_t interval, uint16_t latency, - uint16_t timeout, tGATT_STATUS status); +typedef void(tGATT_CONN_UPDATE_CB)(tGATT_IF gatt_if, uint16_t conn_id, uint16_t interval, + uint16_t latency, uint16_t timeout, tGATT_STATUS status); /* Define a callback function when subrate change event is received */ -typedef void(tGATT_SUBRATE_CHG_CB)(tGATT_IF gatt_if, uint16_t conn_id, - uint16_t subrate_factor, uint16_t latency, - uint16_t cont_num, uint16_t timeout, +typedef void(tGATT_SUBRATE_CHG_CB)(tGATT_IF gatt_if, uint16_t conn_id, uint16_t subrate_factor, + uint16_t latency, uint16_t cont_num, uint16_t timeout, tGATT_STATUS status); /* Define the structure that applications use to register with * GATT. This structure includes callback functions. All functions * MUST be provided. -*/ + */ typedef struct { tGATT_CONN_CBACK* p_conn_cb{nullptr}; tGATT_CMPL_CBACK* p_cmpl_cb{nullptr}; @@ -797,10 +782,8 @@ typedef union { /* Attribute server handle ranges NV storage callback functions */ -typedef void(tGATTS_NV_SAVE_CBACK)(bool is_saved, - tGATTS_HNDL_RANGE* p_hndl_range); -typedef bool(tGATTS_NV_SRV_CHG_CBACK)(tGATTS_SRV_CHG_CMD cmd, - tGATTS_SRV_CHG_REQ* p_req, +typedef void(tGATTS_NV_SAVE_CBACK)(bool is_saved, tGATTS_HNDL_RANGE* p_hndl_range); +typedef bool(tGATTS_NV_SRV_CHG_CBACK)(tGATTS_SRV_CHG_CMD cmd, tGATTS_SRV_CHG_REQ* p_req, tGATTS_SRV_CHG_RSP* p_rsp); typedef struct { @@ -852,8 +835,7 @@ typedef struct { * on error error status is returned. * ******************************************************************************/ -[[nodiscard]] tGATT_STATUS GATTS_AddService(tGATT_IF gatt_if, - btgatt_db_element_t* service, +[[nodiscard]] tGATT_STATUS GATTS_AddService(tGATT_IF gatt_if, btgatt_db_element_t* service, int count); /******************************************************************************* @@ -870,8 +852,7 @@ typedef struct { * Returns true if operation succeed, else false * ******************************************************************************/ -[[nodiscard]] bool GATTS_DeleteService(tGATT_IF gatt_if, - bluetooth::Uuid* p_svc_uuid, +[[nodiscard]] bool GATTS_DeleteService(tGATT_IF gatt_if, bluetooth::Uuid* p_svc_uuid, uint16_t svc_inst); /******************************************************************************* @@ -903,10 +884,8 @@ void GATTS_StopService(uint16_t service_handle); * code. * ******************************************************************************/ -[[nodiscard]] tGATT_STATUS GATTS_HandleValueIndication(uint16_t conn_id, - uint16_t attr_handle, - uint16_t val_len, - uint8_t* p_val); +[[nodiscard]] tGATT_STATUS GATTS_HandleValueIndication(uint16_t conn_id, uint16_t attr_handle, + uint16_t val_len, uint8_t* p_val); /******************************************************************************* * @@ -923,10 +902,8 @@ void GATTS_StopService(uint16_t service_handle); * Returns GATT_SUCCESS if successfully sent; otherwise error code. * ******************************************************************************/ -[[nodiscard]] tGATT_STATUS GATTS_HandleValueNotification(uint16_t conn_id, - uint16_t attr_handle, - uint16_t val_len, - uint8_t* p_val); +[[nodiscard]] tGATT_STATUS GATTS_HandleValueNotification(uint16_t conn_id, uint16_t attr_handle, + uint16_t val_len, uint8_t* p_val); /******************************************************************************* * @@ -942,8 +919,7 @@ void GATTS_StopService(uint16_t service_handle); * Returns GATT_SUCCESS if successfully sent; otherwise error code. * ******************************************************************************/ -[[nodiscard]] tGATT_STATUS GATTS_SendRsp(uint16_t conn_id, uint32_t trans_id, - tGATT_STATUS status, +[[nodiscard]] tGATT_STATUS GATTS_SendRsp(uint16_t conn_id, uint32_t trans_id, tGATT_STATUS status, tGATTS_RSP* p_msg); /******************************************************************************/ @@ -978,8 +954,8 @@ void GATTS_StopService(uint16_t service_handle); * user_mtu: user request mtu * ******************************************************************************/ -void GATTC_UpdateUserAttMtuIfNeeded(const RawAddress& remote_bda, - tBT_TRANSPORT transport, uint16_t user_mtu); +void GATTC_UpdateUserAttMtuIfNeeded(const RawAddress& remote_bda, tBT_TRANSPORT transport, + uint16_t user_mtu); /****************************************************************************** * @@ -1007,13 +983,13 @@ void GATTC_UpdateUserAttMtuIfNeeded(const RawAddress& remote_bda, * Exchange. Conn_id is stored for result. * ******************************************************************************/ -[[nodiscard]] tGATTC_TryMtuRequestResult GATTC_TryMtuRequest( - const RawAddress& remote_bda, tBT_TRANSPORT transport, uint16_t conn_id, - uint16_t* current_mtu); +[[nodiscard]] tGATTC_TryMtuRequestResult GATTC_TryMtuRequest(const RawAddress& remote_bda, + tBT_TRANSPORT transport, + uint16_t conn_id, + uint16_t* current_mtu); -[[nodiscard]] std::list -GATTC_GetAndRemoveListOfConnIdsWaitingForMtuRequest( - const RawAddress& remote_bda); +[[nodiscard]] std::list GATTC_GetAndRemoveListOfConnIdsWaitingForMtuRequest( + const RawAddress& remote_bda); /******************************************************************************* * * Function GATTC_Discover @@ -1030,15 +1006,11 @@ GATTC_GetAndRemoveListOfConnIdsWaitingForMtuRequest( * Returns GATT_SUCCESS if command received/sent successfully. * ******************************************************************************/ -[[nodiscard]] tGATT_STATUS GATTC_Discover(uint16_t conn_id, - tGATT_DISC_TYPE disc_type, - uint16_t start_handle, - uint16_t end_handle, +[[nodiscard]] tGATT_STATUS GATTC_Discover(uint16_t conn_id, tGATT_DISC_TYPE disc_type, + uint16_t start_handle, uint16_t end_handle, const bluetooth::Uuid& uuid); -[[nodiscard]] tGATT_STATUS GATTC_Discover(uint16_t conn_id, - tGATT_DISC_TYPE disc_type, - uint16_t start_handle, - uint16_t end_handle); +[[nodiscard]] tGATT_STATUS GATTC_Discover(uint16_t conn_id, tGATT_DISC_TYPE disc_type, + uint16_t start_handle, uint16_t end_handle); /******************************************************************************* * @@ -1088,8 +1060,7 @@ GATTC_GetAndRemoveListOfConnIdsWaitingForMtuRequest( * Returns GATT_SUCCESS if command started successfully. * ******************************************************************************/ -[[nodiscard]] tGATT_STATUS GATTC_ExecuteWrite(uint16_t conn_id, - bool is_execute); +[[nodiscard]] tGATT_STATUS GATTC_ExecuteWrite(uint16_t conn_id, bool is_execute); /******************************************************************************* * @@ -1104,8 +1075,7 @@ GATTC_GetAndRemoveListOfConnIdsWaitingForMtuRequest( * Returns GATT_SUCCESS if command started successfully. * ******************************************************************************/ -[[nodiscard]] tGATT_STATUS GATTC_SendHandleValueConfirm(uint16_t conn_id, - uint16_t handle); +[[nodiscard]] tGATT_STATUS GATTC_SendHandleValueConfirm(uint16_t conn_id, uint16_t handle); /******************************************************************************* * @@ -1126,8 +1096,8 @@ GATTC_GetAndRemoveListOfConnIdsWaitingForMtuRequest( * Returns void * ******************************************************************************/ -void GATT_SetIdleTimeout(const RawAddress& bd_addr, uint16_t idle_tout, - tBT_TRANSPORT transport, bool is_active); +void GATT_SetIdleTimeout(const RawAddress& bd_addr, uint16_t idle_tout, tBT_TRANSPORT transport, + bool is_active); /******************************************************************************* * @@ -1144,8 +1114,7 @@ void GATT_SetIdleTimeout(const RawAddress& bd_addr, uint16_t idle_tout, * with GATT * ******************************************************************************/ -[[nodiscard]] tGATT_IF GATT_Register(const bluetooth::Uuid& p_app_uuid128, - const std::string& name, +[[nodiscard]] tGATT_IF GATT_Register(const bluetooth::Uuid& p_app_uuid128, const std::string& name, tGATT_CBACK* p_cb_info, bool eatt_support); /******************************************************************************* @@ -1197,19 +1166,16 @@ void GATT_StartIf(tGATT_IF gatt_if); * ******************************************************************************/ [[nodiscard]] bool GATT_Connect(tGATT_IF gatt_if, const RawAddress& bd_addr, - tBTM_BLE_CONN_TYPE connection_type, - tBT_TRANSPORT transport, bool opportunistic); + tBTM_BLE_CONN_TYPE connection_type, tBT_TRANSPORT transport, + bool opportunistic); [[nodiscard]] bool GATT_Connect(tGATT_IF gatt_if, const RawAddress& bd_addr, - tBTM_BLE_CONN_TYPE connection_type, - tBT_TRANSPORT transport, bool opportunistic, - uint8_t initiating_phys); + tBTM_BLE_CONN_TYPE connection_type, tBT_TRANSPORT transport, + bool opportunistic, uint8_t initiating_phys); [[nodiscard]] bool GATT_Connect(tGATT_IF gatt_if, const RawAddress& bd_addr, - tBLE_ADDR_TYPE addr_type, - tBTM_BLE_CONN_TYPE connection_type, + tBLE_ADDR_TYPE addr_type, tBTM_BLE_CONN_TYPE connection_type, tBT_TRANSPORT transport, bool opportunistic); [[nodiscard]] bool GATT_Connect(tGATT_IF gatt_if, const RawAddress& bd_addr, - tBLE_ADDR_TYPE addr_type, - tBTM_BLE_CONN_TYPE connection_type, + tBLE_ADDR_TYPE addr_type, tBTM_BLE_CONN_TYPE connection_type, tBT_TRANSPORT transport, bool opportunistic, uint8_t initiating_phys); @@ -1230,9 +1196,7 @@ void GATT_StartIf(tGATT_IF gatt_if); * Returns true if connection started; else false * ******************************************************************************/ -[[nodiscard]] bool GATT_CancelConnect(tGATT_IF gatt_if, - const RawAddress& bd_addr, - bool is_direct); +[[nodiscard]] bool GATT_CancelConnect(tGATT_IF gatt_if, const RawAddress& bd_addr, bool is_direct); /******************************************************************************* * @@ -1263,10 +1227,8 @@ void GATT_StartIf(tGATT_IF gatt_if); * Returns true the logical link information is found for conn_id * ******************************************************************************/ -[[nodiscard]] bool GATT_GetConnectionInfor(uint16_t conn_id, - tGATT_IF* p_gatt_if, - RawAddress& bd_addr, - tBT_TRANSPORT* p_transport); +[[nodiscard]] bool GATT_GetConnectionInfor(uint16_t conn_id, tGATT_IF* p_gatt_if, + RawAddress& bd_addr, tBT_TRANSPORT* p_transport); /******************************************************************************* * @@ -1284,10 +1246,8 @@ void GATT_StartIf(tGATT_IF gatt_if); * Returns true the logical link is connected * ******************************************************************************/ -[[nodiscard]] bool GATT_GetConnIdIfConnected(tGATT_IF gatt_if, - const RawAddress& bd_addr, - uint16_t* p_conn_id, - tBT_TRANSPORT transport); +[[nodiscard]] bool GATT_GetConnIdIfConnected(tGATT_IF gatt_if, const RawAddress& bd_addr, + uint16_t* p_conn_id, tBT_TRANSPORT transport); /******************************************************************************* * @@ -1323,8 +1283,7 @@ namespace fmt { template <> struct formatter : enum_formatter {}; template <> -struct formatter : enum_formatter { -}; +struct formatter : enum_formatter {}; template <> struct formatter : enum_formatter {}; template <> diff --git a/system/stack/include/hci_error_code.h b/system/stack/include/hci_error_code.h index af6c3528177..fff15c1f353 100644 --- a/system/stack/include/hci_error_code.h +++ b/system/stack/include/hci_error_code.h @@ -135,17 +135,23 @@ inline std::string hci_reason_code_text(const tHCI_REASON& reason_code) { // Conversion from raw packet value inline tHCI_ERROR_CODE to_hci_error_code(const uint8_t& error_code) { - if (error_code > _HCI_ERR_MAX_ERR) return HCI_ERR_UNDEFINED; + if (error_code > _HCI_ERR_MAX_ERR) { + return HCI_ERR_UNDEFINED; + } return static_cast(error_code); } inline tHCI_STATUS to_hci_status_code(const uint8_t& status_code) { - if (status_code > _HCI_ERR_MAX_ERR) return HCI_ERR_UNDEFINED; + if (status_code > _HCI_ERR_MAX_ERR) { + return HCI_ERR_UNDEFINED; + } return static_cast(status_code); } inline tHCI_REASON to_hci_reason_code(const uint8_t& reason_code) { - if (reason_code > _HCI_ERR_MAX_ERR) return HCI_ERR_UNDEFINED; + if (reason_code > _HCI_ERR_MAX_ERR) { + return HCI_ERR_UNDEFINED; + } return static_cast(reason_code); } diff --git a/system/stack/include/hci_evt_length.h b/system/stack/include/hci_evt_length.h index 8f8e661c212..fa53703bc4a 100644 --- a/system/stack/include/hci_evt_length.h +++ b/system/stack/include/hci_evt_length.h @@ -22,262 +22,262 @@ * Definitions for HCI Event Parameter Minimum Length */ static const uint8_t hci_event_parameters_minimum_length[] = { - 0, // 0x00 - N/A - 1, // 0x01 - HCI_Inquiry_Complete Event - 15, // 0x02 - HCI_Inquiry_Result Event (Num_Responses = 1) - 11, // 0x03 - HCI_Connection_Complete Event - 10, // 0x04 - HCI_Connection_Request Event - 4, // 0x05 - HCI_Disconnection_Complete Event - 3, // 0x06 - HCI_Authentication_Complete Event - 255, // 0x07 - HCI_Remote_Name_Request_Complete Event - 4, // 0x08 - HCI_Encryption_Change Event - 3, // 0x09 - HCI_Change_Connection_Link_Key_Complete Event - 4, // 0x0A - HCI_Central_Link_Key_Complete Event - 11, // 0x0B - HCI_Read_Remote_Supported_Features_Complete Event - 8, // 0x0C - HCI_Read_Remote_Version_Information_Complete Event - 21, // 0x0D - HCI_QoS_Setup_Complete Event - 3, // 0x0E - HCI_Command_Complete Event (Depends on command) - 4, // 0x0F - HCI_Command_Status Event - 1, // 0x10 - HCI_Hardware_Error Event - 2, // 0x11 - HCI_Flush_Occurred Event - 8, // 0x12 - HCI_Role_Change Event - 5, // 0x13 - HCI_Number_Of_Completed_Packets Event (Num_Handles = 1) - 6, // 0x14 - HCI_Mode_Change Event - 23, // 0x15 - HCI_Return_Link_Keys Event (Num_Keys = 1) - 6, // 0x16 - HCI_PIN_Code_Request Event - 6, // 0x17 - HCI_Link_Key_Request Event - 23, // 0x18 - HCI_Link_Key_Notification Event - 3, // 0x19 - HCI_Loopback_Command Event (Depends on command) - 1, // 0x1A - HCI_Data_Buffer_Overflow Event - 3, // 0x1B - HCI_Max_Slots_Change Event - 5, // 0x1C - HCI_Read_Clock_Offset_Complete Event - 5, // 0x1D - HCI_Connection_Packet_Type_Changed Event - 2, // 0x1E - HCI_QoS_Violation Event - 7, // 0x1F - HCI_Page_Scan_Mode_Change Event (Deprecated) - 7, // 0x20 - HCI_Page_Scan_Repetition_Mode_Change Event - 22, // 0x21 - HCI_Flow_Specification_Complet Event - 15, // 0x22 - HCI_Inquiry_Result_with_RSSI Event (Num_Responses = 1) - 13, // 0x23 - HCI_Read_Remote_Extended_Features_Complete Event - 0, // 0x24 - N/A - 0, // 0x25 - N/A - 0, // 0x26 - N/A - 0, // 0x27 - N/A - 0, // 0x28 - N/A - 0, // 0x29 - N/A - 0, // 0x2A - N/A - 0, // 0x2B - N/A - 17, // 0x2C - HCI_Synchronous_Connection_Complete Event - 9, // 0x2D - HCI_Synchronous_Connection_Changed Event - 11, // 0x2E - HCI_Sniff_Subrating Event - 255, // 0x2F - HCI_Extended_Inquiry_Result Event - 3, // 0x30 - HCI_Encryption_Key_Refresh_Complete Event - 6, // 0x31 - HCI_IO_Capability_Request Event - 9, // 0x32 - HCI_IO_Capability_Response Event - 10, // 0x33 - HCI_User_Confirmation_Request Event - 6, // 0x34 - HCI_User_Passkey_Request Event - 6, // 0x35 - HCI_Remote_OOB_Data_Request Event - 7, // 0x36 - HCI_Simple_Pairing_Complete Event - 0, // 0x37 - N/A - 4, // 0x38 - HCI_Link_Supervision_Timeout_Changed Event - 2, // 0x39 - HCI_Enhanced_Flush_Complete Event - 0, // 0x3A - N/A - 10, // 0x3B - HCI_User_Passkey_Notification Event - 7, // 0x3C - HCI_Keypress_Notification Event - 14, // 0x3D - HCI_Remote_Host_Supported_Features_Notification Event - 1, // 0x3E - LE Meta event - 0, // 0x3F - N/A - 2, // 0x40 - HCI_Physical_Link_Complete Event - 1, // 0x41 - HCI_Channel_Selected Event - 3, // 0x42 - HCI_Disconnection_Physical_Link_Complete Event - 2, // 0x43 - HCI_Physical_Link_Loss_Early_Warning Event - 1, // 0x44 - HCI_Physical_Link_Recovery Event - 5, // 0x45 - HCI_Logical_Link_Complete Event - 4, // 0x46 - HCI_Disconnection_Logical_Link_Complete Event - 3, // 0x47 - HCI_Flow_Spec_Modify_Complete Event - 9, // 0x48 - HCI_Number_Of_Completed_Data_Blocks Event (Num_Handles = 1) - 2, // 0x49 - HCI_AMP_Start_Test Event - 2, // 0x4A - HCI_AMP_Test_End Event - 18, // 0x4B - HCI_AMP_Receiver_Report Event - 3, // 0x4C - HCI_Short_Range_Mode_Change_Complete Event - 2, // 0x4D - HCI_AMP_Status_Change Event - 9, // 0x4E - HCI_Triggered_Clock_Capture Event - 1, // 0x4F - HCI_Synchronization_Train_Complete Event - 29, // 0x50 - HCI_Synchronization_Train_Received Event - 18, // 0x51 - HCI_Connectionless_Peripheral_Broadcast_Receive Event - // (Data_Length = 0) - 7, // 0x52 - HCI_Connectionless_Peripheral_Broadcast_Timeout Event - 7, // 0x53 - HCI_Truncated_Page_Complete Event - 0, // 0x54 - HCI_Peripheral_Page_Response_Timeout Event - 10, // 0x55 - HCI_Connectionless_Peripheral_Broadcast_Channel_Map_Change - // Event - 4, // 0x56 - HCI_Inquiry_Response_Notification Event - 2, // 0x57 - HCI_Authenticated_Payload_Timeout_Expired Event - 8, // 0x58 - HCI_SAM_Status_Change Event - 0, // 0x59 - N/A - 0, // 0x5A - N/A - 0, // 0x5B - N/A - 0, // 0x5C - N/A - 0, // 0x5D - N/A - 0, // 0x5E - N/A - 0, // 0x5F - N/A - 0, // 0x60 - N/A - 0, // 0x61 - N/A - 0, // 0x62 - N/A - 0, // 0x63 - N/A - 0, // 0x64 - N/A - 0, // 0x65 - N/A - 0, // 0x66 - N/A - 0, // 0x67 - N/A - 0, // 0x68 - N/A - 0, // 0x69 - N/A - 0, // 0x6A - N/A - 0, // 0x6B - N/A - 0, // 0x6C - N/A - 0, // 0x6D - N/A - 0, // 0x6E - N/A - 0, // 0x6F - N/A - 0, // 0x70 - N/A - 0, // 0x71 - N/A - 0, // 0x72 - N/A - 0, // 0x73 - N/A - 0, // 0x74 - N/A - 0, // 0x75 - N/A - 0, // 0x76 - N/A - 0, // 0x77 - N/A - 0, // 0x78 - N/A - 0, // 0x79 - N/A - 0, // 0x7A - N/A - 0, // 0x7B - N/A - 0, // 0x7C - N/A - 0, // 0x7D - N/A - 0, // 0x7E - N/A - 0, // 0x7F - N/A - 0, // 0x80 - N/A - 0, // 0x81 - N/A - 0, // 0x82 - N/A - 0, // 0x83 - N/A - 0, // 0x84 - N/A - 0, // 0x85 - N/A - 0, // 0x86 - N/A - 0, // 0x87 - N/A - 0, // 0x88 - N/A - 0, // 0x89 - N/A - 0, // 0x8A - N/A - 0, // 0x8B - N/A - 0, // 0x8C - N/A - 0, // 0x8D - N/A - 0, // 0x8E - N/A - 0, // 0x8F - N/A - 0, // 0x90 - N/A - 0, // 0x91 - N/A - 0, // 0x92 - N/A - 0, // 0x93 - N/A - 0, // 0x94 - N/A - 0, // 0x95 - N/A - 0, // 0x96 - N/A - 0, // 0x97 - N/A - 0, // 0x98 - N/A - 0, // 0x99 - N/A - 0, // 0x9A - N/A - 0, // 0x9B - N/A - 0, // 0x9C - N/A - 0, // 0x9D - N/A - 0, // 0x9E - N/A - 0, // 0x9F - N/A - 0, // 0xA0 - N/A - 0, // 0xA1 - N/A - 0, // 0xA2 - N/A - 0, // 0xA3 - N/A - 0, // 0xA4 - N/A - 0, // 0xA5 - N/A - 0, // 0xA6 - N/A - 0, // 0xA7 - N/A - 0, // 0xA8 - N/A - 0, // 0xA9 - N/A - 0, // 0xAA - N/A - 0, // 0xAB - N/A - 0, // 0xAC - N/A - 0, // 0xAD - N/A - 0, // 0xAE - N/A - 0, // 0xAF - N/A - 0, // 0xB0 - N/A - 0, // 0xB1 - N/A - 0, // 0xB2 - N/A - 0, // 0xB3 - N/A - 0, // 0xB4 - N/A - 0, // 0xB5 - N/A - 0, // 0xB6 - N/A - 0, // 0xB7 - N/A - 0, // 0xB8 - N/A - 0, // 0xB9 - N/A - 0, // 0xBA - N/A - 0, // 0xBB - N/A - 0, // 0xBC - N/A - 0, // 0xBD - N/A - 0, // 0xBE - N/A - 0, // 0xBF - N/A - 0, // 0xC0 - N/A - 0, // 0xC1 - N/A - 0, // 0xC2 - N/A - 0, // 0xC3 - N/A - 0, // 0xC4 - N/A - 0, // 0xC5 - N/A - 0, // 0xC6 - N/A - 0, // 0xC7 - N/A - 0, // 0xC8 - N/A - 0, // 0xC9 - N/A - 0, // 0xCA - N/A - 0, // 0xCB - N/A - 0, // 0xCC - N/A - 0, // 0xCD - N/A - 0, // 0xCE - N/A - 0, // 0xCF - N/A - 0, // 0xD0 - N/A - 0, // 0xD1 - N/A - 0, // 0xD2 - N/A - 0, // 0xD3 - N/A - 0, // 0xD4 - N/A - 0, // 0xD5 - N/A - 0, // 0xD6 - N/A - 0, // 0xD7 - N/A - 0, // 0xD8 - N/A - 0, // 0xD9 - N/A - 0, // 0xDA - N/A - 0, // 0xDB - N/A - 0, // 0xDC - N/A - 0, // 0xDD - N/A - 0, // 0xDE - N/A - 0, // 0xDF - N/A - 0, // 0xE0 - N/A - 0, // 0xE1 - N/A - 0, // 0xE2 - N/A - 0, // 0xE3 - N/A - 0, // 0xE4 - N/A - 0, // 0xE5 - N/A - 0, // 0xE6 - N/A - 0, // 0xE7 - N/A - 0, // 0xE8 - N/A - 0, // 0xE9 - N/A - 0, // 0xEA - N/A - 0, // 0xEB - N/A - 0, // 0xEC - N/A - 0, // 0xED - N/A - 0, // 0xEE - N/A - 0, // 0xEF - N/A - 0, // 0xF0 - N/A - 0, // 0xF1 - N/A - 0, // 0xF2 - N/A - 0, // 0xF3 - N/A - 0, // 0xF4 - N/A - 0, // 0xF5 - N/A - 0, // 0xF6 - N/A - 0, // 0xF7 - N/A - 0, // 0xF8 - N/A - 0, // 0xF9 - N/A - 0, // 0xFA - N/A - 0, // 0xFB - N/A - 0, // 0xFC - N/A - 0, // 0xFD - N/A - 0, // 0xFE - N/A - 0, // 0xFF - HCI_Vendor_Specific Event + 0, // 0x00 - N/A + 1, // 0x01 - HCI_Inquiry_Complete Event + 15, // 0x02 - HCI_Inquiry_Result Event (Num_Responses = 1) + 11, // 0x03 - HCI_Connection_Complete Event + 10, // 0x04 - HCI_Connection_Request Event + 4, // 0x05 - HCI_Disconnection_Complete Event + 3, // 0x06 - HCI_Authentication_Complete Event + 255, // 0x07 - HCI_Remote_Name_Request_Complete Event + 4, // 0x08 - HCI_Encryption_Change Event + 3, // 0x09 - HCI_Change_Connection_Link_Key_Complete Event + 4, // 0x0A - HCI_Central_Link_Key_Complete Event + 11, // 0x0B - HCI_Read_Remote_Supported_Features_Complete Event + 8, // 0x0C - HCI_Read_Remote_Version_Information_Complete Event + 21, // 0x0D - HCI_QoS_Setup_Complete Event + 3, // 0x0E - HCI_Command_Complete Event (Depends on command) + 4, // 0x0F - HCI_Command_Status Event + 1, // 0x10 - HCI_Hardware_Error Event + 2, // 0x11 - HCI_Flush_Occurred Event + 8, // 0x12 - HCI_Role_Change Event + 5, // 0x13 - HCI_Number_Of_Completed_Packets Event (Num_Handles = 1) + 6, // 0x14 - HCI_Mode_Change Event + 23, // 0x15 - HCI_Return_Link_Keys Event (Num_Keys = 1) + 6, // 0x16 - HCI_PIN_Code_Request Event + 6, // 0x17 - HCI_Link_Key_Request Event + 23, // 0x18 - HCI_Link_Key_Notification Event + 3, // 0x19 - HCI_Loopback_Command Event (Depends on command) + 1, // 0x1A - HCI_Data_Buffer_Overflow Event + 3, // 0x1B - HCI_Max_Slots_Change Event + 5, // 0x1C - HCI_Read_Clock_Offset_Complete Event + 5, // 0x1D - HCI_Connection_Packet_Type_Changed Event + 2, // 0x1E - HCI_QoS_Violation Event + 7, // 0x1F - HCI_Page_Scan_Mode_Change Event (Deprecated) + 7, // 0x20 - HCI_Page_Scan_Repetition_Mode_Change Event + 22, // 0x21 - HCI_Flow_Specification_Complet Event + 15, // 0x22 - HCI_Inquiry_Result_with_RSSI Event (Num_Responses = 1) + 13, // 0x23 - HCI_Read_Remote_Extended_Features_Complete Event + 0, // 0x24 - N/A + 0, // 0x25 - N/A + 0, // 0x26 - N/A + 0, // 0x27 - N/A + 0, // 0x28 - N/A + 0, // 0x29 - N/A + 0, // 0x2A - N/A + 0, // 0x2B - N/A + 17, // 0x2C - HCI_Synchronous_Connection_Complete Event + 9, // 0x2D - HCI_Synchronous_Connection_Changed Event + 11, // 0x2E - HCI_Sniff_Subrating Event + 255, // 0x2F - HCI_Extended_Inquiry_Result Event + 3, // 0x30 - HCI_Encryption_Key_Refresh_Complete Event + 6, // 0x31 - HCI_IO_Capability_Request Event + 9, // 0x32 - HCI_IO_Capability_Response Event + 10, // 0x33 - HCI_User_Confirmation_Request Event + 6, // 0x34 - HCI_User_Passkey_Request Event + 6, // 0x35 - HCI_Remote_OOB_Data_Request Event + 7, // 0x36 - HCI_Simple_Pairing_Complete Event + 0, // 0x37 - N/A + 4, // 0x38 - HCI_Link_Supervision_Timeout_Changed Event + 2, // 0x39 - HCI_Enhanced_Flush_Complete Event + 0, // 0x3A - N/A + 10, // 0x3B - HCI_User_Passkey_Notification Event + 7, // 0x3C - HCI_Keypress_Notification Event + 14, // 0x3D - HCI_Remote_Host_Supported_Features_Notification Event + 1, // 0x3E - LE Meta event + 0, // 0x3F - N/A + 2, // 0x40 - HCI_Physical_Link_Complete Event + 1, // 0x41 - HCI_Channel_Selected Event + 3, // 0x42 - HCI_Disconnection_Physical_Link_Complete Event + 2, // 0x43 - HCI_Physical_Link_Loss_Early_Warning Event + 1, // 0x44 - HCI_Physical_Link_Recovery Event + 5, // 0x45 - HCI_Logical_Link_Complete Event + 4, // 0x46 - HCI_Disconnection_Logical_Link_Complete Event + 3, // 0x47 - HCI_Flow_Spec_Modify_Complete Event + 9, // 0x48 - HCI_Number_Of_Completed_Data_Blocks Event (Num_Handles = 1) + 2, // 0x49 - HCI_AMP_Start_Test Event + 2, // 0x4A - HCI_AMP_Test_End Event + 18, // 0x4B - HCI_AMP_Receiver_Report Event + 3, // 0x4C - HCI_Short_Range_Mode_Change_Complete Event + 2, // 0x4D - HCI_AMP_Status_Change Event + 9, // 0x4E - HCI_Triggered_Clock_Capture Event + 1, // 0x4F - HCI_Synchronization_Train_Complete Event + 29, // 0x50 - HCI_Synchronization_Train_Received Event + 18, // 0x51 - HCI_Connectionless_Peripheral_Broadcast_Receive Event + // (Data_Length = 0) + 7, // 0x52 - HCI_Connectionless_Peripheral_Broadcast_Timeout Event + 7, // 0x53 - HCI_Truncated_Page_Complete Event + 0, // 0x54 - HCI_Peripheral_Page_Response_Timeout Event + 10, // 0x55 - HCI_Connectionless_Peripheral_Broadcast_Channel_Map_Change + // Event + 4, // 0x56 - HCI_Inquiry_Response_Notification Event + 2, // 0x57 - HCI_Authenticated_Payload_Timeout_Expired Event + 8, // 0x58 - HCI_SAM_Status_Change Event + 0, // 0x59 - N/A + 0, // 0x5A - N/A + 0, // 0x5B - N/A + 0, // 0x5C - N/A + 0, // 0x5D - N/A + 0, // 0x5E - N/A + 0, // 0x5F - N/A + 0, // 0x60 - N/A + 0, // 0x61 - N/A + 0, // 0x62 - N/A + 0, // 0x63 - N/A + 0, // 0x64 - N/A + 0, // 0x65 - N/A + 0, // 0x66 - N/A + 0, // 0x67 - N/A + 0, // 0x68 - N/A + 0, // 0x69 - N/A + 0, // 0x6A - N/A + 0, // 0x6B - N/A + 0, // 0x6C - N/A + 0, // 0x6D - N/A + 0, // 0x6E - N/A + 0, // 0x6F - N/A + 0, // 0x70 - N/A + 0, // 0x71 - N/A + 0, // 0x72 - N/A + 0, // 0x73 - N/A + 0, // 0x74 - N/A + 0, // 0x75 - N/A + 0, // 0x76 - N/A + 0, // 0x77 - N/A + 0, // 0x78 - N/A + 0, // 0x79 - N/A + 0, // 0x7A - N/A + 0, // 0x7B - N/A + 0, // 0x7C - N/A + 0, // 0x7D - N/A + 0, // 0x7E - N/A + 0, // 0x7F - N/A + 0, // 0x80 - N/A + 0, // 0x81 - N/A + 0, // 0x82 - N/A + 0, // 0x83 - N/A + 0, // 0x84 - N/A + 0, // 0x85 - N/A + 0, // 0x86 - N/A + 0, // 0x87 - N/A + 0, // 0x88 - N/A + 0, // 0x89 - N/A + 0, // 0x8A - N/A + 0, // 0x8B - N/A + 0, // 0x8C - N/A + 0, // 0x8D - N/A + 0, // 0x8E - N/A + 0, // 0x8F - N/A + 0, // 0x90 - N/A + 0, // 0x91 - N/A + 0, // 0x92 - N/A + 0, // 0x93 - N/A + 0, // 0x94 - N/A + 0, // 0x95 - N/A + 0, // 0x96 - N/A + 0, // 0x97 - N/A + 0, // 0x98 - N/A + 0, // 0x99 - N/A + 0, // 0x9A - N/A + 0, // 0x9B - N/A + 0, // 0x9C - N/A + 0, // 0x9D - N/A + 0, // 0x9E - N/A + 0, // 0x9F - N/A + 0, // 0xA0 - N/A + 0, // 0xA1 - N/A + 0, // 0xA2 - N/A + 0, // 0xA3 - N/A + 0, // 0xA4 - N/A + 0, // 0xA5 - N/A + 0, // 0xA6 - N/A + 0, // 0xA7 - N/A + 0, // 0xA8 - N/A + 0, // 0xA9 - N/A + 0, // 0xAA - N/A + 0, // 0xAB - N/A + 0, // 0xAC - N/A + 0, // 0xAD - N/A + 0, // 0xAE - N/A + 0, // 0xAF - N/A + 0, // 0xB0 - N/A + 0, // 0xB1 - N/A + 0, // 0xB2 - N/A + 0, // 0xB3 - N/A + 0, // 0xB4 - N/A + 0, // 0xB5 - N/A + 0, // 0xB6 - N/A + 0, // 0xB7 - N/A + 0, // 0xB8 - N/A + 0, // 0xB9 - N/A + 0, // 0xBA - N/A + 0, // 0xBB - N/A + 0, // 0xBC - N/A + 0, // 0xBD - N/A + 0, // 0xBE - N/A + 0, // 0xBF - N/A + 0, // 0xC0 - N/A + 0, // 0xC1 - N/A + 0, // 0xC2 - N/A + 0, // 0xC3 - N/A + 0, // 0xC4 - N/A + 0, // 0xC5 - N/A + 0, // 0xC6 - N/A + 0, // 0xC7 - N/A + 0, // 0xC8 - N/A + 0, // 0xC9 - N/A + 0, // 0xCA - N/A + 0, // 0xCB - N/A + 0, // 0xCC - N/A + 0, // 0xCD - N/A + 0, // 0xCE - N/A + 0, // 0xCF - N/A + 0, // 0xD0 - N/A + 0, // 0xD1 - N/A + 0, // 0xD2 - N/A + 0, // 0xD3 - N/A + 0, // 0xD4 - N/A + 0, // 0xD5 - N/A + 0, // 0xD6 - N/A + 0, // 0xD7 - N/A + 0, // 0xD8 - N/A + 0, // 0xD9 - N/A + 0, // 0xDA - N/A + 0, // 0xDB - N/A + 0, // 0xDC - N/A + 0, // 0xDD - N/A + 0, // 0xDE - N/A + 0, // 0xDF - N/A + 0, // 0xE0 - N/A + 0, // 0xE1 - N/A + 0, // 0xE2 - N/A + 0, // 0xE3 - N/A + 0, // 0xE4 - N/A + 0, // 0xE5 - N/A + 0, // 0xE6 - N/A + 0, // 0xE7 - N/A + 0, // 0xE8 - N/A + 0, // 0xE9 - N/A + 0, // 0xEA - N/A + 0, // 0xEB - N/A + 0, // 0xEC - N/A + 0, // 0xED - N/A + 0, // 0xEE - N/A + 0, // 0xEF - N/A + 0, // 0xF0 - N/A + 0, // 0xF1 - N/A + 0, // 0xF2 - N/A + 0, // 0xF3 - N/A + 0, // 0xF4 - N/A + 0, // 0xF5 - N/A + 0, // 0xF6 - N/A + 0, // 0xF7 - N/A + 0, // 0xF8 - N/A + 0, // 0xF9 - N/A + 0, // 0xFA - N/A + 0, // 0xFB - N/A + 0, // 0xFC - N/A + 0, // 0xFD - N/A + 0, // 0xFE - N/A + 0, // 0xFF - HCI_Vendor_Specific Event }; diff --git a/system/stack/include/hcidefs.h b/system/stack/include/hcidefs.h index eac97c3c62f..e874d9fa917 100644 --- a/system/stack/include/hcidefs.h +++ b/system/stack/include/hcidefs.h @@ -34,20 +34,20 @@ /* * Definitions for HCI groups -*/ + */ #define HCI_GRP_LINK_CONTROL_CMDS (0x01 << 10) /* 0x0400 */ #define HCI_GRP_LINK_POLICY_CMDS (0x02 << 10) /* 0x0800 */ #define HCI_GRP_HOST_CONT_BASEBAND_CMDS (0x03 << 10) /* 0x0C00 */ #define HCI_GRP_INFORMATIONAL_PARAMS (0x04 << 10) /* 0x1000 */ #define HCI_GRP_STATUS_PARAMS (0x05 << 10) /* 0x1400 */ #define HCI_GRP_TESTING_CMDS (0x06 << 10) /* 0x1800 */ -#define HCI_GRP_BLE_CMDS (0x08 << 10) /* 0x2000 (LE Commands) */ +#define HCI_GRP_BLE_CMDS (0x08 << 10) /* 0x2000 (LE Commands) */ #define HCI_GRP_VENDOR_SPECIFIC (0x3F << 10) /* 0xFC00 */ /* * Definitions for Link Control Commands -*/ + */ /* Following opcode is used only in command complete event for flow control */ #define HCI_COMMAND_NONE 0x0000 @@ -155,28 +155,23 @@ #define HCI_WRITE_PAGESCAN_CFG (0x001C | HCI_GRP_HOST_CONT_BASEBAND_CMDS) #define HCI_READ_INQUIRYSCAN_CFG (0x001D | HCI_GRP_HOST_CONT_BASEBAND_CMDS) #define HCI_WRITE_INQUIRYSCAN_CFG (0x001E | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_READ_AUTHENTICATION_ENABLE \ - (0x001F | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_WRITE_AUTHENTICATION_ENABLE \ - (0x0020 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) +#define HCI_READ_AUTHENTICATION_ENABLE (0x001F | HCI_GRP_HOST_CONT_BASEBAND_CMDS) +#define HCI_WRITE_AUTHENTICATION_ENABLE (0x0020 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) #define HCI_READ_ENCRYPTION_MODE (0x0021 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) #define HCI_WRITE_ENCRYPTION_MODE (0x0022 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) #define HCI_READ_CLASS_OF_DEVICE (0x0023 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) #define HCI_WRITE_CLASS_OF_DEVICE (0x0024 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) #define HCI_READ_VOICE_SETTINGS (0x0025 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) #define HCI_WRITE_VOICE_SETTINGS (0x0026 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_READ_AUTOMATIC_FLUSH_TIMEOUT \ - (0x0027 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_WRITE_AUTOMATIC_FLUSH_TIMEOUT \ - (0x0028 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) +#define HCI_READ_AUTOMATIC_FLUSH_TIMEOUT (0x0027 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) +#define HCI_WRITE_AUTOMATIC_FLUSH_TIMEOUT (0x0028 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) #define HCI_READ_NUM_BCAST_REXMITS (0x0029 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) #define HCI_WRITE_NUM_BCAST_REXMITS (0x002A | HCI_GRP_HOST_CONT_BASEBAND_CMDS) #define HCI_READ_HOLD_MODE_ACTIVITY (0x002B | HCI_GRP_HOST_CONT_BASEBAND_CMDS) #define HCI_WRITE_HOLD_MODE_ACTIVITY (0x002C | HCI_GRP_HOST_CONT_BASEBAND_CMDS) #define HCI_READ_TRANSMIT_POWER_LEVEL (0x002D | HCI_GRP_HOST_CONT_BASEBAND_CMDS) #define HCI_READ_SCO_FLOW_CTRL_ENABLE (0x002E | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_WRITE_SCO_FLOW_CTRL_ENABLE \ - (0x002F | HCI_GRP_HOST_CONT_BASEBAND_CMDS) +#define HCI_WRITE_SCO_FLOW_CTRL_ENABLE (0x002F | HCI_GRP_HOST_CONT_BASEBAND_CMDS) #define HCI_SET_HC_TO_HOST_FLOW_CTRL (0x0031 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) #define HCI_HOST_BUFFER_SIZE (0x0033 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) #define HCI_HOST_NUM_PACKETS_DONE (0x0035 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) @@ -186,8 +181,7 @@ #define HCI_READ_CURRENT_IAC_LAP (0x0039 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) #define HCI_WRITE_CURRENT_IAC_LAP (0x003A | HCI_GRP_HOST_CONT_BASEBAND_CMDS) #define HCI_READ_PAGESCAN_PERIOD_MODE (0x003B | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_WRITE_PAGESCAN_PERIOD_MODE \ - (0x003C | HCI_GRP_HOST_CONT_BASEBAND_CMDS) +#define HCI_WRITE_PAGESCAN_PERIOD_MODE (0x003C | HCI_GRP_HOST_CONT_BASEBAND_CMDS) #define HCI_READ_PAGESCAN_MODE (0x003D | HCI_GRP_HOST_CONT_BASEBAND_CMDS) #define HCI_WRITE_PAGESCAN_MODE (0x003E | HCI_GRP_HOST_CONT_BASEBAND_CMDS) #define HCI_SET_AFH_CHANNELS (0x003F | HCI_GRP_HOST_CONT_BASEBAND_CMDS) @@ -212,14 +206,11 @@ #define HCI_WRITE_ERRONEOUS_DATA_RPT (0x005B | HCI_GRP_HOST_CONT_BASEBAND_CMDS) #define HCI_ENHANCED_FLUSH (0x005F | HCI_GRP_HOST_CONT_BASEBAND_CMDS) #define HCI_SEND_KEYPRESS_NOTIF (0x0060 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_READ_LOCAL_OOB_EXTENDED_DATA \ - (0x007D | HCI_GRP_HOST_CONT_BASEBAND_CMDS) +#define HCI_READ_LOCAL_OOB_EXTENDED_DATA (0x007D | HCI_GRP_HOST_CONT_BASEBAND_CMDS) /* AMP HCI */ -#define HCI_READ_LOGICAL_LINK_ACCEPT_TIMEOUT \ - (0x0061 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_WRITE_LOGICAL_LINK_ACCEPT_TIMEOUT \ - (0x0062 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) +#define HCI_READ_LOGICAL_LINK_ACCEPT_TIMEOUT (0x0061 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) +#define HCI_WRITE_LOGICAL_LINK_ACCEPT_TIMEOUT (0x0062 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) #define HCI_SET_EVENT_MASK_PAGE_2 (0x0063 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) #define HCI_READ_LOCATION_DATA (0x0064 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) #define HCI_WRITE_LOCATION_DATA (0x0065 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) @@ -233,16 +224,12 @@ #define HCI_WRITE_LE_HOST_SUPPORT (0x006D | HCI_GRP_HOST_CONT_BASEBAND_CMDS) /* MWS coexistence */ -#define HCI_SET_MWS_CHANNEL_PARAMETERS \ - (0x006E | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_SET_EXTERNAL_FRAME_CONFIGURATION \ - (0x006F | HCI_GRP_HOST_CONT_BASEBAND_CMDS) +#define HCI_SET_MWS_CHANNEL_PARAMETERS (0x006E | HCI_GRP_HOST_CONT_BASEBAND_CMDS) +#define HCI_SET_EXTERNAL_FRAME_CONFIGURATION (0x006F | HCI_GRP_HOST_CONT_BASEBAND_CMDS) #define HCI_SET_MWS_SIGNALING (0x0070 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) #define HCI_SET_MWS_TRANSPORT_LAYER (0x0071 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_SET_MWS_SCAN_FREQUENCY_TABLE \ - (0x0072 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_SET_MWS_PATTERN_CONFIGURATION \ - (0x0073 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) +#define HCI_SET_MWS_SCAN_FREQUENCY_TABLE (0x0072 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) +#define HCI_SET_MWS_PATTERN_CONFIGURATION (0x0073 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) /* Connectionless Broadcast */ #define HCI_SET_RESERVED_LT_ADDR (0x0074 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) @@ -252,8 +239,7 @@ #define HCI_WRITE_SYNC_TRAIN_PARAM (0x0078 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) #define HCI_READ_SECURE_CONNS_SUPPORT (0x0079 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) -#define HCI_WRITE_SECURE_CONNS_SUPPORT \ - (0x007A | HCI_GRP_HOST_CONT_BASEBAND_CMDS) +#define HCI_WRITE_SECURE_CONNS_SUPPORT (0x007A | HCI_GRP_HOST_CONT_BASEBAND_CMDS) #define HCI_CONFIGURE_DATA_PATH (0x0083 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) #define HCI_CONT_BASEBAND_CMDS_FIRST HCI_SET_EVENT_MASK #define HCI_CONT_BASEBAND_CMDS_LAST HCI_READ_SYNC_TRAIN_PARAM @@ -357,7 +343,7 @@ #define HCI_BLE_READ_RESOLVABLE_ADDR_PEER (0x002B | HCI_GRP_BLE_CMDS) #define HCI_BLE_READ_RESOLVABLE_ADDR_LOCAL (0x002C | HCI_GRP_BLE_CMDS) #define HCI_BLE_SET_ADDR_RESOLUTION_ENABLE (0x002D | HCI_GRP_BLE_CMDS) -#define HCI_BLE_SET_RAND_PRIV_ADDR_TIMOUT (0x002E | HCI_GRP_BLE_CMDS) +#define HCI_BLE_SET_RAND_PRIV_ADDR_TIMEOUT (0x002E | HCI_GRP_BLE_CMDS) #define HCI_BLE_READ_MAXIMUM_DATA_LENGTH (0x002F | HCI_GRP_BLE_CMDS) #define HCI_BLE_READ_PHY (0x0030 | HCI_GRP_BLE_CMDS) #define HCI_BLE_SET_DEFAULT_PHY (0x0031 | HCI_GRP_BLE_CMDS) @@ -370,8 +356,7 @@ #define HCI_LE_SET_EXT_ADVERTISING_SCAN_RESP (0x38 | HCI_GRP_BLE_CMDS) #define HCI_LE_SET_EXT_ADVERTISING_ENABLE (0x39 | HCI_GRP_BLE_CMDS) #define HCI_LE_READ_MAXIMUM_ADVERTISING_DATA_LENGTH (0x003A | HCI_GRP_BLE_CMDS) -#define HCI_LE_READ_NUMBER_OF_SUPPORTED_ADVERTISING_SETS \ - (0x003B | HCI_GRP_BLE_CMDS) +#define HCI_LE_READ_NUMBER_OF_SUPPORTED_ADVERTISING_SETS (0x003B | HCI_GRP_BLE_CMDS) #define HCI_LE_REMOVE_ADVERTISING_SET (0x003C | HCI_GRP_BLE_CMDS) #define HCI_LE_CLEAR_ADVERTISING_SETS (0x003D | HCI_GRP_BLE_CMDS) #define HCI_LE_SET_PERIODIC_ADVERTISING_PARAM (0x003E | HCI_GRP_BLE_CMDS) @@ -381,29 +366,21 @@ #define HCI_LE_SET_EXTENDED_SCAN_ENABLE (0x0042 | HCI_GRP_BLE_CMDS) #define HCI_LE_EXTENDED_CREATE_CONNECTION (0x0043 | HCI_GRP_BLE_CMDS) #define HCI_BLE_PERIODIC_ADVERTISING_CREATE_SYNC (0x0044 | HCI_GRP_BLE_CMDS) -#define HCI_BLE_PERIODIC_ADVERTISING_CREATE_SYNC_CANCEL \ - (0x0045 | HCI_GRP_BLE_CMDS) -#define HCI_BLE_PERIODIC_ADVERTISING_TERMINATE_SYNC \ - (0x0046 | HCI_GRP_BLE_CMDS) -#define HCI_BLE_ADD_DEVICE_TO_PERIODIC_ADVERTISER_LIST \ - (0x0047 | HCI_GRP_BLE_CMDS) -#define HCI_BLE_REMOVE_DEVICE_FROM_PERIODIC_ADVERTISER_LIST \ - (0x0048 | HCI_GRP_BLE_CMDS) +#define HCI_BLE_PERIODIC_ADVERTISING_CREATE_SYNC_CANCEL (0x0045 | HCI_GRP_BLE_CMDS) +#define HCI_BLE_PERIODIC_ADVERTISING_TERMINATE_SYNC (0x0046 | HCI_GRP_BLE_CMDS) +#define HCI_BLE_ADD_DEVICE_TO_PERIODIC_ADVERTISER_LIST (0x0047 | HCI_GRP_BLE_CMDS) +#define HCI_BLE_REMOVE_DEVICE_FROM_PERIODIC_ADVERTISER_LIST (0x0048 | HCI_GRP_BLE_CMDS) #define HCI_BLE_CLEAR_PERIODIC_ADVERTISER_LIST (0x0049 | HCI_GRP_BLE_CMDS) #define HCI_BLE_READ_PERIODIC_ADVERTISER_LIST_SIZE (0x004A | HCI_GRP_BLE_CMDS) #define HCI_BLE_READ_TRANSMIT_POWER (0x004B | HCI_GRP_BLE_CMDS) #define HCI_BLE_READ_RF_COMPENS_POWER (0x004C | HCI_GRP_BLE_CMDS) #define HCI_BLE_WRITE_RF_COMPENS_POWER (0x004D | HCI_GRP_BLE_CMDS) #define HCI_BLE_SET_PRIVACY_MODE (0x004E | HCI_GRP_BLE_CMDS) -#define HCI_LE_SET_PERIODIC_ADVERTISING_RECEIVE_ENABLE \ - (0x0059 | HCI_GRP_BLE_CMDS) +#define HCI_LE_SET_PERIODIC_ADVERTISING_RECEIVE_ENABLE (0x0059 | HCI_GRP_BLE_CMDS) #define HCI_LE_PERIODIC_ADVERTISING_SYNC_TRANSFER (0x005A | HCI_GRP_BLE_CMDS) -#define HCI_LE_PERIODIC_ADVERTISING_SET_INFO_TRANSFER \ - (0x005B | HCI_GRP_BLE_CMDS) -#define HCI_LE_SET_PERIODIC_ADVERTISING_SYNC_TRANSFER_PARAM \ - (0x005C | HCI_GRP_BLE_CMDS) -#define HCI_LE_SET_DEFAULT_PERIODIC_ADVERTISING_SYNC_TRANSFER_PARAM \ - (0x005D | HCI_GRP_BLE_CMDS) +#define HCI_LE_PERIODIC_ADVERTISING_SET_INFO_TRANSFER (0x005B | HCI_GRP_BLE_CMDS) +#define HCI_LE_SET_PERIODIC_ADVERTISING_SYNC_TRANSFER_PARAM (0x005C | HCI_GRP_BLE_CMDS) +#define HCI_LE_SET_DEFAULT_PERIODIC_ADVERTISING_SYNC_TRANSFER_PARAM (0x005D | HCI_GRP_BLE_CMDS) #define HCI_BLE_READ_BUFFER_SIZE_V2 (0x0060 | HCI_GRP_BLE_CMDS) #define HCI_LE_SET_HOST_FEATURE (0x0074 | HCI_GRP_BLE_CMDS) @@ -532,7 +509,7 @@ constexpr uint8_t HCI_LE_STATES_INIT_CENTRAL_PERIPHERAL_BIT = 41; /* * Definitions for HCI Events -*/ + */ #define HCI_INQUIRY_COMP_EVT 0x01 #define HCI_INQUIRY_RESULT_EVT 0x02 #define HCI_CONNECTION_COMP_EVT 0x03 @@ -599,12 +576,12 @@ constexpr uint8_t HCI_LE_STATES_INIT_CENTRAL_PERIPHERAL_BIT = 41; #define HCI_BLE_DIRECT_ADV_EVT 0x0b #define HCI_BLE_PHY_UPDATE_COMPLETE_EVT 0x0c #define HCI_LE_EXTENDED_ADVERTISING_REPORT_EVT 0x0D -#define HCI_BLE_PERIODIC_ADV_SYNC_EST_EVT 0x0E -#define HCI_BLE_PERIODIC_ADV_REPORT_EVT 0x0F -#define HCI_BLE_PERIODIC_ADV_SYNC_LOST_EVT 0x10 -#define HCI_BLE_SCAN_TIMEOUT_EVT 0x11 +#define HCI_BLE_PERIODIC_ADV_SYNC_EST_EVT 0x0E +#define HCI_BLE_PERIODIC_ADV_REPORT_EVT 0x0F +#define HCI_BLE_PERIODIC_ADV_SYNC_LOST_EVT 0x10 +#define HCI_BLE_SCAN_TIMEOUT_EVT 0x11 #define HCI_LE_ADVERTISING_SET_TERMINATED_EVT 0x12 -#define HCI_BLE_SCAN_REQ_RX_EVT 0x13 +#define HCI_BLE_SCAN_REQ_RX_EVT 0x13 #define HCI_BLE_CIS_EST_EVT 0x19 #define HCI_BLE_CIS_REQ_EVT 0x1a #define HCI_BLE_CREATE_BIG_CPL_EVT 0x1b @@ -621,7 +598,7 @@ constexpr uint8_t HCI_LE_STATES_INIT_CENTRAL_PERIPHERAL_BIT = 41; /* * Definitions for HCI enable event -*/ + */ #define HCI_INQUIRY_RESULT_EV(p) (*((uint32_t*)(p)) & 0x00000002) #define HCI_CONNECTION_COMPLETE_EV(p) (*((uint32_t*)(p)) & 0x00000004) #define HCI_CONNECTION_REQUEST_EV(p) (*((uint32_t*)(p)) & 0x00000008) @@ -680,7 +657,7 @@ constexpr uint8_t HCI_LE_STATES_INIT_CENTRAL_PERIPHERAL_BIT = 41; /* * Definitions for packet type masks (BT1.2 and BT2.0 definitions) -*/ + */ typedef enum : uint16_t { HCI_PKT_TYPES_MASK_NO_2_DH1 = 0x0002, HCI_PKT_TYPES_MASK_NO_3_DH1 = 0x0004, @@ -701,7 +678,7 @@ typedef enum : uint16_t { /* * Define parameters to allow role switch during create connection -*/ + */ #define HCI_CR_CONN_NOT_ALLOW_SWITCH 0x00 #define HCI_CR_CONN_ALLOW_SWITCH 0x01 @@ -767,13 +744,13 @@ typedef enum : uint16_t { #define HCI_DEF_PAGESCAN_INTERVAL 0x0800 /* 1.28 sec */ /* Parameter for pagescan window is passed to LC and is kept in slots */ -#define HCI_DEF_PAGESCAN_WINDOW 0x12 /* 11.25 ms */ +#define HCI_DEF_PAGESCAN_WINDOW 0x12 /* 11.25 ms */ /* Inquiryscan timer definitions in 0.625 ms */ #define HCI_DEF_INQUIRYSCAN_INTERVAL 0x1000 /* 2.56 sec */ /* Parameter for inquiryscan window is passed to LC and is kept in slots */ -#define HCI_DEF_INQUIRYSCAN_WINDOW 0x12 /* 11.25 ms */ +#define HCI_DEF_INQUIRYSCAN_WINDOW 0x12 /* 11.25 ms */ /* Encryption modes */ typedef enum : uint8_t { @@ -803,15 +780,15 @@ typedef enum : uint8_t { #define HCI_AIR_CODING_FORMAT_MASK 0x0003 /* 0000000011 */ /* default 0001100000 */ -#define HCI_DEFAULT_VOICE_SETTINGS \ - (HCI_INP_CODING_LINEAR | HCI_INP_DATA_FMT_2S_COMPLEMENT | \ - HCI_INP_SAMPLE_SIZE_16BIT | HCI_AIR_CODING_FORMAT_CVSD) +#define HCI_DEFAULT_VOICE_SETTINGS \ + (HCI_INP_CODING_LINEAR | HCI_INP_DATA_FMT_2S_COMPLEMENT | HCI_INP_SAMPLE_SIZE_16BIT | \ + HCI_AIR_CODING_FORMAT_CVSD) /* Retransmit timer definitions in 0.625 */ #define HCI_MAX_AUTOMATIC_FLUSH_TIMEOUT 0x07FF /* Default Link Supervision timeoout */ -#define HCI_DEFAULT_INACT_TOUT 0x7D00 /* BR/EDR (20 seconds) */ +#define HCI_DEFAULT_INACT_TOUT 0x7D00 /* BR/EDR (20 seconds) */ /* Read transmit power level parameter */ #define HCI_READ_CURRENT 0x00 @@ -839,12 +816,12 @@ typedef enum : uint8_t { /* Define the preamble length for all HCI Commands. * This is 2-bytes for opcode and 1 byte for length -*/ + */ #define HCIC_PREAMBLE_SIZE 3 /* Define the preamble length for all HCI Events * This is 1-byte for opcode and 1 byte for length -*/ + */ #define HCIE_PREAMBLE_SIZE 2 // Packet boundary flags @@ -870,11 +847,9 @@ union HciDataPreamble { *data++ = ((raw.word0) & 0xff); *data++ = (((raw.word0) >> 8) & 0xff); *data++ = ((raw.word1) & 0xff); - *data++ = (((raw.word1 >> 8)) & 0xff); - } - bool IsFlushable() const { - return bits.boundary == kHCI_FIRST_AUTOMATICALLY_FLUSHABLE; + *data++ = ((raw.word1 >> 8) & 0xff); } + bool IsFlushable() const { return bits.boundary == kHCI_FIRST_AUTOMATICALLY_FLUSHABLE; } void SetFlushable() { bits.boundary = kHCI_FIRST_AUTOMATICALLY_FLUSHABLE; } }; #define HCI_DATA_PREAMBLE_SIZE sizeof(HciDataPreamble) @@ -939,7 +914,7 @@ typedef struct { /* * Define packet size -*/ + */ #define HCI_DM1_PACKET_SIZE 17 #define HCI_DH1_PACKET_SIZE 27 #define HCI_DM3_PACKET_SIZE 121 @@ -1027,7 +1002,7 @@ typedef struct { /* This feature is causing frequent link drops when doing call switch with * certain av/hfp headsets */ // TODO: move the disabling somewhere else -#define HCI_NON_FLUSHABLE_PB_SUPPORTED(x) (0) //((x)[6] & 0x40) +#define HCI_NON_FLUSHABLE_PB_SUPPORTED(x) (0) // ((x)[6] & 0x40) #define HCI_LINK_SUP_TO_EVT_SUPPORTED(x) ((x)[7] & 0x01) #define HCI_INQ_RESP_TX_SUPPORTED(x) ((x)[7] & 0x02) #define HCI_LMP_EXTENDED_SUPPORTED(x) ((x)[7] & 0x80) diff --git a/system/stack/include/hcimsgs.h b/system/stack/include/hcimsgs.h index 7ff2b50f64b..8e4d00534e0 100644 --- a/system/stack/include/hcimsgs.h +++ b/system/stack/include/hcimsgs.h @@ -42,14 +42,11 @@ enum hci_data_direction_t { /* Disconnect */ namespace bluetooth::legacy::hci { class Interface { - public: +public: virtual void Disconnect(uint16_t handle, uint8_t reason) const = 0; - virtual void ChangeConnectionPacketType(uint16_t handle, - uint16_t packet_types) const = 0; - virtual void StartRoleSwitch(const RawAddress& bd_addr, - uint8_t role) const = 0; - virtual void ConfigureDataPath(hci_data_direction_t data_path_direction, - uint8_t data_path_id, + virtual void ChangeConnectionPacketType(uint16_t handle, uint16_t packet_types) const = 0; + virtual void StartRoleSwitch(const RawAddress& bd_addr, uint8_t role) const = 0; + virtual void ConfigureDataPath(hci_data_direction_t data_path_direction, uint8_t data_path_id, std::vector vendor_config) const = 0; virtual ~Interface() = default; }; @@ -67,15 +64,14 @@ void btsnd_hcic_create_conn_cancel(const RawAddress& dest); void btsnd_hcic_reject_conn(const RawAddress& bd_addr, uint8_t reason); /* Link Key Request Reply */ -void btsnd_hcic_link_key_req_reply(const RawAddress& bd_addr, - const LinkKey& link_key); +void btsnd_hcic_link_key_req_reply(const RawAddress& bd_addr, const LinkKey& link_key); /* Link Key Request Neg Reply */ void btsnd_hcic_link_key_neg_reply(const RawAddress& bd_addr); /* PIN Code Request Reply */ -void btsnd_hcic_pin_code_req_reply(const RawAddress& bd_addr, - uint8_t pin_code_len, PIN_CODE pin_code); +void btsnd_hcic_pin_code_req_reply(const RawAddress& bd_addr, uint8_t pin_code_len, + PIN_CODE pin_code); /* Link Key Request Neg Reply */ void btsnd_hcic_pin_code_neg_reply(const RawAddress& bd_addr); @@ -92,29 +88,25 @@ void btsnd_hcic_set_conn_encrypt(uint16_t handle, bool enable); /* Remote Extended Features */ void btsnd_hcic_rmt_ext_features(uint16_t handle, uint8_t page_num); -void btsnd_hcic_rmt_ver_req(uint16_t handle); /* Remote Version Info Request */ +void btsnd_hcic_rmt_ver_req(uint16_t handle); /* Remote Version Info Request */ void btsnd_hcic_read_rmt_clk_offset(uint16_t handle); /* Remote Clock Offset */ void btsnd_hcic_setup_esco_conn(uint16_t handle, uint32_t transmit_bandwidth, - uint32_t receive_bandwidth, - uint16_t max_latency, uint16_t voice, + uint32_t receive_bandwidth, uint16_t max_latency, uint16_t voice, uint8_t retrans_effort, uint16_t packet_types); -void btsnd_hcic_accept_esco_conn(const RawAddress& bd_addr, - uint32_t transmit_bandwidth, - uint32_t receive_bandwidth, - uint16_t max_latency, uint16_t content_fmt, - uint8_t retrans_effort, uint16_t packet_types); +void btsnd_hcic_accept_esco_conn(const RawAddress& bd_addr, uint32_t transmit_bandwidth, + uint32_t receive_bandwidth, uint16_t max_latency, + uint16_t content_fmt, uint8_t retrans_effort, + uint16_t packet_types); void btsnd_hcic_reject_esco_conn(const RawAddress& bd_addr, uint8_t reason); /* Hold Mode */ -void btsnd_hcic_hold_mode(uint16_t handle, uint16_t max_hold_period, - uint16_t min_hold_period); +void btsnd_hcic_hold_mode(uint16_t handle, uint16_t max_hold_period, uint16_t min_hold_period); /* Hold Mode */ /* Sniff Mode */ -void btsnd_hcic_sniff_mode(uint16_t handle, uint16_t max_sniff_period, - uint16_t min_sniff_period, uint16_t sniff_attempt, - uint16_t sniff_timeout); +void btsnd_hcic_sniff_mode(uint16_t handle, uint16_t max_sniff_period, uint16_t min_sniff_period, + uint16_t sniff_attempt, uint16_t sniff_timeout); /* Exit Sniff Mode */ void btsnd_hcic_exit_sniff_mode(uint16_t handle); @@ -136,18 +128,17 @@ void btsnd_hcic_write_def_policy_set(uint16_t settings); * Lisbon Features ******************************************/ /* Sniff Subrating */ -void btsnd_hcic_sniff_sub_rate(uint16_t handle, uint16_t max_lat, - uint16_t min_remote_lat, uint16_t min_local_lat); +void btsnd_hcic_sniff_sub_rate(uint16_t handle, uint16_t max_lat, uint16_t min_remote_lat, + uint16_t min_local_lat); /* Sniff Subrating */ /* Extended Inquiry Response */ void btsnd_hcic_write_ext_inquiry_response(void* buffer, uint8_t fec_req); /* IO Capabilities Response */ -void btsnd_hcic_io_cap_req_reply(const RawAddress& bd_addr, uint8_t capability, - uint8_t oob_present, uint8_t auth_req); +void btsnd_hcic_io_cap_req_reply(const RawAddress& bd_addr, uint8_t capability, uint8_t oob_present, + uint8_t auth_req); /* IO Capabilities Req Neg Reply */ -void btsnd_hcic_io_cap_req_neg_reply(const RawAddress& bd_addr, - uint8_t err_code); +void btsnd_hcic_io_cap_req_neg_reply(const RawAddress& bd_addr, uint8_t err_code); /* Read Local OOB Data */ void btsnd_hcic_read_local_oob_data(void); @@ -161,8 +152,7 @@ void btsnd_hcic_user_passkey_reply(const RawAddress& bd_addr, uint32_t value); void btsnd_hcic_user_passkey_neg_reply(const RawAddress& bd_addr); /* Remote OOB Data Request Reply */ -void btsnd_hcic_rem_oob_reply(const RawAddress& bd_addr, const Octet16& c, - const Octet16& r); +void btsnd_hcic_rem_oob_reply(const RawAddress& bd_addr, const Octet16& c, const Octet16& r); /* Remote OOB Data Request Negative Reply */ void btsnd_hcic_rem_oob_neg_reply(const RawAddress& bd_addr); @@ -172,15 +162,12 @@ void btsnd_hcic_read_default_erroneous_data_rpt(void); /**** end of Simple Pairing Commands ****/ -extern void btsnd_hcic_set_event_filter(uint8_t filt_type, - uint8_t filt_cond_type, - uint8_t* filt_cond, - uint8_t filt_cond_len); +extern void btsnd_hcic_set_event_filter(uint8_t filt_type, uint8_t filt_cond_type, + uint8_t* filt_cond, uint8_t filt_cond_len); /* Set Event Filter */ /* Delete Stored Key */ -void btsnd_hcic_delete_stored_key(const RawAddress& bd_addr, - bool delete_all_flag); +void btsnd_hcic_delete_stored_key(const RawAddress& bd_addr, bool delete_all_flag); /* Delete Stored Key */ #define HCIC_PARAM_SIZE_READ_CMD 0 @@ -192,51 +179,49 @@ void btsnd_hcic_delete_stored_key(const RawAddress& bd_addr, void btsnd_hcic_write_pin_type(uint8_t type); /* Write PIN Type */ void btsnd_hcic_write_auto_accept(uint8_t flag); /* Write Auto Accept */ void btsnd_hcic_read_name(void); /* Read Local Name */ -void btsnd_hcic_write_page_tout(uint16_t timeout); /* Write Page Timout */ +void btsnd_hcic_write_page_tout(uint16_t timeout); /* Write Page Timeout */ void btsnd_hcic_write_scan_enable(uint8_t flag); /* Write Scan Enable */ -void btsnd_hcic_write_pagescan_cfg( - uint16_t interval, uint16_t window); /* Write Page Scan Activity */ +void btsnd_hcic_write_pagescan_cfg(uint16_t interval, + uint16_t window); /* Write Page Scan Activity */ /* Write Page Scan Activity */ /* Write Inquiry Scan Activity */ void btsnd_hcic_write_inqscan_cfg(uint16_t interval, uint16_t window); /* Write Inquiry Scan Activity */ -void btsnd_hcic_write_auth_enable( - uint8_t flag); /* Write Authentication Enable */ -void btsnd_hcic_write_dev_class(DEV_CLASS dev); /* Write Class of Device */ +void btsnd_hcic_write_auth_enable(uint8_t flag); /* Write Authentication Enable */ +void btsnd_hcic_write_dev_class(DEV_CLASS dev); /* Write Class of Device */ void btsnd_hcic_write_voice_settings(uint16_t flags); /* Write Voice Settings */ -void btsnd_hcic_write_auto_flush_tout( - uint16_t handle, uint16_t timeout); /* Write Retransmit Timout */ +void btsnd_hcic_write_auto_flush_tout(uint16_t handle, + uint16_t timeout); /* Write Retransmit Timeout */ -void btsnd_hcic_read_tx_power(uint16_t handle, - uint8_t type); /* Read Tx Power */ +void btsnd_hcic_read_tx_power(uint16_t handle, uint8_t type); /* Read Tx Power */ /* Write Link Supervision Timeout */ void btsnd_hcic_write_link_super_tout(uint16_t handle, uint16_t timeout); /* Write Link Supervision Timeout */ -void btsnd_hcic_write_cur_iac_lap( - uint8_t num_cur_iac, LAP* const iac_lap); /* Write Current IAC LAP */ +void btsnd_hcic_write_cur_iac_lap(uint8_t num_cur_iac, + LAP* const iac_lap); /* Write Current IAC LAP */ /* Write Current IAC LAP */ void btsnd_hcic_read_rssi(uint16_t handle); /* Read RSSI */ using ReadEncKeySizeCb = base::OnceCallback; void btsnd_hcic_read_encryption_key_size(uint16_t handle, ReadEncKeySizeCb cb); void btsnd_hcic_read_failed_contact_counter(uint16_t handle); -void btsnd_hcic_enable_test_mode(void); /* Enable Device Under Test Mode */ +void btsnd_hcic_enable_test_mode(void); /* Enable Device Under Test Mode */ void btsnd_hcic_write_pagescan_type(uint8_t type); /* Write Page Scan Type */ void btsnd_hcic_write_inqscan_type(uint8_t type); /* Write Inquiry Scan Type */ void btsnd_hcic_write_inquiry_mode(uint8_t type); /* Write Inquiry Mode */ /* Enhanced setup SCO connection (CSA2) */ -void btsnd_hcic_enhanced_set_up_synchronous_connection( - uint16_t conn_handle, enh_esco_params_t* p_parms); +void btsnd_hcic_enhanced_set_up_synchronous_connection(uint16_t conn_handle, + enh_esco_params_t* p_parms); /* Enhanced accept SCO connection request (CSA2) */ -void btsnd_hcic_enhanced_accept_synchronous_connection( - const RawAddress& bd_addr, enh_esco_params_t* p_parms); +void btsnd_hcic_enhanced_accept_synchronous_connection(const RawAddress& bd_addr, + enh_esco_params_t* p_parms); #define HCI_DATA_HANDLE_MASK 0x0FFF #define HCI_DATA_PKT_STATUS_MASK 0x3000 @@ -245,14 +230,12 @@ void btsnd_hcic_enhanced_accept_synchronous_connection( (uint16_t)((*((uint8_t*)((p) + 1) + (p)->offset) + \ (*((uint8_t*)((p) + 1) + (p)->offset + 1) << 8))) -#define HCID_GET_HANDLE(u16) (uint16_t)((u16)&HCI_DATA_HANDLE_MASK) -#define HCID_GET_PKT_STATUS(u16) \ - (uint16_t)(((u16)&HCI_DATA_PKT_STATUS_MASK) >> 12) +#define HCID_GET_HANDLE(u16) (uint16_t)((u16) & HCI_DATA_HANDLE_MASK) +#define HCID_GET_PKT_STATUS(u16) (uint16_t)(((u16) & HCI_DATA_PKT_STATUS_MASK) >> 12) #define HCI_DATA_EVENT_MASK 3 #define HCI_DATA_EVENT_OFFSET 12 -#define HCID_GET_EVENT(u16) \ - (uint8_t)(((u16) >> HCI_DATA_EVENT_OFFSET) & HCI_DATA_EVENT_MASK) +#define HCID_GET_EVENT(u16) (uint8_t)(((u16) >> HCI_DATA_EVENT_OFFSET) & HCI_DATA_EVENT_MASK) void btsnd_hcic_vendor_spec_cmd(uint16_t opcode, uint8_t len, uint8_t* p_data, tBTM_VSC_CMPL_CB* p_cmd_cplt_cback); @@ -271,12 +254,9 @@ void btsnd_hcic_vendor_spec_cmd(uint16_t opcode, uint8_t len, uint8_t* p_data, /* ULP HCI command */ void btsnd_hcic_ble_set_local_used_feat(uint8_t feat_set[8]); -void btsnd_hcic_ble_write_adv_params(uint16_t adv_int_min, uint16_t adv_int_max, - uint8_t adv_type, - tBLE_ADDR_TYPE addr_type_own, - tBLE_ADDR_TYPE addr_type_dir, - const RawAddress& direct_bda, - uint8_t channel_map, +void btsnd_hcic_ble_write_adv_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type, + tBLE_ADDR_TYPE addr_type_own, tBLE_ADDR_TYPE addr_type_dir, + const RawAddress& direct_bda, uint8_t channel_map, uint8_t adv_filter_policy); void btsnd_hcic_ble_read_adv_chnl_tx_power(void); @@ -285,9 +265,8 @@ void btsnd_hcic_ble_set_adv_data(uint8_t data_len, uint8_t* p_data); void btsnd_hcic_ble_set_adv_enable(uint8_t adv_enable); -void btsnd_hcic_ble_set_scan_params(uint8_t scan_type, uint16_t scan_int, - uint16_t scan_win, uint8_t addr_type, - uint8_t scan_filter_policy); +void btsnd_hcic_ble_set_scan_params(uint8_t scan_type, uint16_t scan_int, uint16_t scan_win, + uint8_t addr_type, uint8_t scan_filter_policy); void btsnd_hcic_ble_set_scan_enable(uint8_t scan_enable, uint8_t duplicate); @@ -297,9 +276,8 @@ void btsnd_hcic_ble_read_remote_feat(uint16_t handle); void btsnd_hcic_ble_rand(base::Callback cb); -void btsnd_hcic_ble_start_enc(uint16_t handle, - uint8_t rand[HCIC_BLE_RAND_DI_SIZE], - uint16_t ediv, const Octet16& ltk); +void btsnd_hcic_ble_start_enc(uint16_t handle, uint8_t rand[HCIC_BLE_RAND_DI_SIZE], uint16_t ediv, + const Octet16& ltk); void btsnd_hcic_ble_ltk_req_reply(uint16_t handle, const Octet16& ltk); @@ -309,12 +287,10 @@ void btsnd_hcic_ble_read_supported_states(void); void btsnd_hcic_ble_receiver_test(uint8_t rx_freq); -void btsnd_hcic_ble_transmitter_test(uint8_t tx_freq, uint8_t test_data_len, - uint8_t payload); +void btsnd_hcic_ble_transmitter_test(uint8_t tx_freq, uint8_t test_data_len, uint8_t payload); void btsnd_hcic_ble_test_end(void); -void btsnd_hcic_ble_set_data_length(uint16_t conn_handle, uint16_t tx_octets, - uint16_t tx_time); +void btsnd_hcic_ble_set_data_length(uint16_t conn_handle, uint16_t tx_octets, uint16_t tx_time); struct scanning_phy_cfg { uint8_t scan_type; @@ -323,14 +299,11 @@ struct scanning_phy_cfg { }; void btsnd_hcic_ble_set_extended_scan_params(uint8_t own_address_type, - uint8_t scanning_filter_policy, - uint8_t scanning_phys, + uint8_t scanning_filter_policy, uint8_t scanning_phys, scanning_phy_cfg* phy_cfg); -void btsnd_hcic_ble_set_extended_scan_enable(uint8_t enable, - uint8_t filter_duplicates, - uint16_t duration, - uint16_t period); +void btsnd_hcic_ble_set_extended_scan_enable(uint8_t enable, uint8_t filter_duplicates, + uint16_t duration, uint16_t period); struct EXT_CONN_PHY_CFG { uint16_t scan_int; @@ -343,15 +316,13 @@ struct EXT_CONN_PHY_CFG { uint16_t max_ce_len; }; -void btsnd_hcic_ble_read_resolvable_addr_peer(uint8_t addr_type_peer, - const RawAddress& bda_peer); +void btsnd_hcic_ble_read_resolvable_addr_peer(uint8_t addr_type_peer, const RawAddress& bda_peer); -void btsnd_hcic_ble_set_rand_priv_addr_timeout(uint16_t rpa_timout); +void btsnd_hcic_ble_set_rand_priv_addr_timeout(uint16_t rpa_timeout); void btsnd_hcic_read_authenticated_payload_tout(uint16_t handle); -void btsnd_hcic_write_authenticated_payload_tout(uint16_t handle, - uint16_t timeout); +void btsnd_hcic_write_authenticated_payload_tout(uint16_t handle, uint16_t timeout); struct EXT_CIS_CFG { uint8_t cis_id; @@ -363,12 +334,10 @@ struct EXT_CIS_CFG { uint8_t rtn_stom; }; -void btsnd_hcic_set_cig_params(uint8_t cig_id, uint32_t sdu_itv_mtos, - uint32_t sdu_itv_stom, uint8_t sca, - uint8_t packing, uint8_t framing, - uint16_t max_trans_lat_stom, - uint16_t max_trans_lat_mtos, uint8_t cis_cnt, - const EXT_CIS_CFG* cis_cfg, +void btsnd_hcic_set_cig_params(uint8_t cig_id, uint32_t sdu_itv_mtos, uint32_t sdu_itv_stom, + uint8_t sca, uint8_t packing, uint8_t framing, + uint16_t max_trans_lat_stom, uint16_t max_trans_lat_mtos, + uint8_t cis_cnt, const EXT_CIS_CFG* cis_cfg, base::OnceCallback cb); struct EXT_CIS_TEST_CFG { @@ -389,82 +358,73 @@ struct EXT_CIS_CREATE_CFG { uint16_t acl_conn_handle; }; -void btsnd_hcic_create_cis(uint8_t num_cis, - const EXT_CIS_CREATE_CFG* cis_create_cfg, +void btsnd_hcic_create_cis(uint8_t num_cis, const EXT_CIS_CREATE_CFG* cis_create_cfg, base::OnceCallback cb); -void btsnd_hcic_remove_cig(uint8_t cig_id, - base::OnceCallback cb); +void btsnd_hcic_remove_cig(uint8_t cig_id, base::OnceCallback cb); void btsnd_hcic_req_peer_sca(uint16_t conn_handle); -void btsnd_hcic_create_big(uint8_t big_handle, uint8_t adv_handle, - uint8_t num_bis, uint32_t sdu_itv, - uint16_t max_sdu_size, uint16_t max_trans_lat, - uint8_t rtn, uint8_t phy, uint8_t packing, - uint8_t framing, uint8_t enc, +void btsnd_hcic_create_big(uint8_t big_handle, uint8_t adv_handle, uint8_t num_bis, + uint32_t sdu_itv, uint16_t max_sdu_size, uint16_t max_trans_lat, + uint8_t rtn, uint8_t phy, uint8_t packing, uint8_t framing, uint8_t enc, std::array bcst_code); void btsnd_hcic_term_big(uint8_t big_handle, uint8_t reason); -void btsnd_hcic_setup_iso_data_path( - uint16_t iso_handle, uint8_t data_path_dir, uint8_t data_path_id, - uint8_t codec_id_format, uint16_t codec_id_company, - uint16_t codec_id_vendor, uint32_t controller_delay, - std::vector codec_conf, - base::OnceCallback cb); +void btsnd_hcic_setup_iso_data_path(uint16_t iso_handle, uint8_t data_path_dir, + uint8_t data_path_id, uint8_t codec_id_format, + uint16_t codec_id_company, uint16_t codec_id_vendor, + uint32_t controller_delay, std::vector codec_conf, + base::OnceCallback cb); -void btsnd_hcic_remove_iso_data_path( - uint16_t iso_handle, uint8_t data_path_dir, - base::OnceCallback cb); +void btsnd_hcic_remove_iso_data_path(uint16_t iso_handle, uint8_t data_path_dir, + base::OnceCallback cb); -void btsnd_hcic_read_iso_link_quality( - uint16_t iso_handle, base::OnceCallback cb); +void btsnd_hcic_read_iso_link_quality(uint16_t iso_handle, + base::OnceCallback cb); -void btsnd_hcic_ble_periodic_advertising_create_sync( - uint8_t options, uint8_t adv_sid, uint8_t adv_addr_type, - const RawAddress& adv_addr, uint16_t skip_num, uint16_t sync_timeout, - uint8_t sync_cte_type); +void btsnd_hcic_ble_periodic_advertising_create_sync(uint8_t options, uint8_t adv_sid, + uint8_t adv_addr_type, + const RawAddress& adv_addr, uint16_t skip_num, + uint16_t sync_timeout, uint8_t sync_cte_type); void btsnd_hcic_ble_periodic_advertising_create_sync_cancel( - base::OnceCallback cb); + base::OnceCallback cb); void btsnd_hcic_ble_periodic_advertising_terminate_sync( - uint16_t sync_handle, base::OnceCallback cb); + uint16_t sync_handle, base::OnceCallback cb); void btsnd_hci_ble_add_device_to_periodic_advertiser_list( - uint8_t adv_addr_type, const RawAddress& adv_addr, uint8_t adv_sid, - base::OnceCallback cb); + uint8_t adv_addr_type, const RawAddress& adv_addr, uint8_t adv_sid, + base::OnceCallback cb); void btsnd_hci_ble_remove_device_from_periodic_advertiser_list( - uint8_t adv_addr_type, const RawAddress& adv_addr, uint8_t adv_sid, - base::OnceCallback cb); + uint8_t adv_addr_type, const RawAddress& adv_addr, uint8_t adv_sid, + base::OnceCallback cb); -void btsnd_hci_ble_clear_periodic_advertiser_list( - base::OnceCallback cb); +void btsnd_hci_ble_clear_periodic_advertiser_list(base::OnceCallback cb); void btsnd_hcic_ble_set_periodic_advertising_receive_enable( - uint16_t sync_handle, bool enable, - base::OnceCallback cb); + uint16_t sync_handle, bool enable, base::OnceCallback cb); void btsnd_hcic_ble_periodic_advertising_sync_transfer( - uint16_t conn_handle, uint16_t service_data, uint16_t sync_handle, - base::OnceCallback cb); + uint16_t conn_handle, uint16_t service_data, uint16_t sync_handle, + base::OnceCallback cb); void btsnd_hcic_ble_periodic_advertising_set_info_transfer( - uint16_t conn_handle, uint16_t service_data, uint8_t adv_handle, - base::OnceCallback cb); + uint16_t conn_handle, uint16_t service_data, uint8_t adv_handle, + base::OnceCallback cb); void btsnd_hcic_ble_set_periodic_advertising_sync_transfer_params( - uint16_t conn_handle, uint8_t mode, uint16_t skip, uint16_t sync_timeout, - uint8_t cte_type, base::OnceCallback cb); + uint16_t conn_handle, uint8_t mode, uint16_t skip, uint16_t sync_timeout, uint8_t cte_type, + base::OnceCallback cb); void btsnd_hcic_ble_set_default_periodic_advertising_sync_transfer_params( - uint16_t conn_handle, uint8_t mode, uint16_t skip, uint16_t sync_timeout, - uint8_t cte_type, base::OnceCallback cb); + uint16_t conn_handle, uint8_t mode, uint16_t skip, uint16_t sync_timeout, uint8_t cte_type, + base::OnceCallback cb); -void btsnd_hcic_configure_data_path(hci_data_direction_t data_path_direction, - uint8_t data_path_id, +void btsnd_hcic_configure_data_path(hci_data_direction_t data_path_direction, uint8_t data_path_id, std::vector vendor_config); #endif diff --git a/system/stack/include/hfp_lc3_decoder.h b/system/stack/include/hfp_lc3_decoder.h index 82a6168e63e..22953410f05 100644 --- a/system/stack/include/hfp_lc3_decoder.h +++ b/system/stack/include/hfp_lc3_decoder.h @@ -33,7 +33,6 @@ void hfp_lc3_decoder_cleanup(); // Decodes |i_buf| into |o_buf| with size |out_len| in bytes. |i_buf| should // point to a complete LC3 packet with 60 bytes of data including the header, // otherwise PLC will be conducted. -bool hfp_lc3_decoder_decode_packet(const uint8_t* i_buf, int16_t* o_buf, - size_t out_len); +bool hfp_lc3_decoder_decode_packet(const uint8_t* i_buf, int16_t* o_buf, size_t out_len); #endif // HFP_LC3_DECODER_H diff --git a/system/stack/include/hfp_msbc_decoder.h b/system/stack/include/hfp_msbc_decoder.h index 8a128adda24..4c5b9b66db6 100644 --- a/system/stack/include/hfp_msbc_decoder.h +++ b/system/stack/include/hfp_msbc_decoder.h @@ -32,7 +32,6 @@ void hfp_msbc_decoder_cleanup(void); // Decodes |i_buf| into |o_buf| with size |out_len| in bytes. |i_buf| should // point to a complete mSBC packet with 60 bytes of data including the header. -bool hfp_msbc_decoder_decode_packet(const uint8_t* i_buf, int16_t* o_buf, - size_t out_len); +bool hfp_msbc_decoder_decode_packet(const uint8_t* i_buf, int16_t* o_buf, size_t out_len); #endif // HFP_MSBC_DECODER_H diff --git a/system/stack/include/hidd_api.h b/system/stack/include/hidd_api.h index 8a642daa648..c74c806ea57 100644 --- a/system/stack/include/hidd_api.h +++ b/system/stack/include/hidd_api.h @@ -51,8 +51,8 @@ enum { HID_DHOST_EVT_SUSPEND, HID_DHOST_EVT_EXIT_SUSPEND, }; -typedef void(tHID_DEV_HOST_CALLBACK)(const RawAddress& bd_addr, uint8_t event, - uint32_t data, BT_HDR* p_buf); +typedef void(tHID_DEV_HOST_CALLBACK)(const RawAddress& bd_addr, uint8_t event, uint32_t data, + BT_HDR* p_buf); /***************************************************************************** * External Function Declarations @@ -103,9 +103,8 @@ tHID_STATUS HID_DevDeregister(void); * Returns tHID_STATUS * ******************************************************************************/ -tHID_STATUS HID_DevAddRecord(uint32_t handle, char* p_name, char* p_description, - char* p_provider, uint16_t subclass, - uint16_t desc_len, uint8_t* p_desc_data); +tHID_STATUS HID_DevAddRecord(uint32_t handle, char* p_name, char* p_description, char* p_provider, + uint16_t subclass, uint16_t desc_len, uint8_t* p_desc_data); /******************************************************************************* * @@ -116,8 +115,8 @@ tHID_STATUS HID_DevAddRecord(uint32_t handle, char* p_name, char* p_description, * Returns tHID_STATUS * ******************************************************************************/ -tHID_STATUS HID_DevSendReport(uint8_t channel, uint8_t type, uint8_t id, - uint16_t len, uint8_t* p_data); +tHID_STATUS HID_DevSendReport(uint8_t channel, uint8_t type, uint8_t id, uint16_t len, + uint8_t* p_data); /******************************************************************************* * @@ -217,9 +216,8 @@ tHID_STATUS HID_DevGetDevice(RawAddress* addr); * ******************************************************************************/ tHID_STATUS HID_DevSetIncomingQos(uint8_t service_type, uint32_t token_rate, - uint32_t token_bucket_size, - uint32_t peak_bandwidth, uint32_t latency, - uint32_t delay_variation); + uint32_t token_bucket_size, uint32_t peak_bandwidth, + uint32_t latency, uint32_t delay_variation); /******************************************************************************* * @@ -231,9 +229,8 @@ tHID_STATUS HID_DevSetIncomingQos(uint8_t service_type, uint32_t token_rate, * ******************************************************************************/ tHID_STATUS HID_DevSetOutgoingQos(uint8_t service_type, uint32_t token_rate, - uint32_t token_bucket_size, - uint32_t peak_bandwidth, uint32_t latency, - uint32_t delay_variation); + uint32_t token_bucket_size, uint32_t peak_bandwidth, + uint32_t latency, uint32_t delay_variation); #ifdef __cplusplus } diff --git a/system/stack/include/hiddefs.h b/system/stack/include/hiddefs.h index 3f051fcde1e..4e8743d94d5 100644 --- a/system/stack/include/hiddefs.h +++ b/system/stack/include/hiddefs.h @@ -33,7 +33,7 @@ #include "stack/include/sdp_api.h" /* * tHID_STATUS: HID result codes, returned by HID and device and host functions. -*/ + */ typedef enum : uint8_t { HID_SUCCESS = 0, HID_ERR_NOT_REGISTERED, @@ -84,14 +84,12 @@ inline std::string hid_status_text(const tHID_STATUS& status) { } } -#define HID_L2CAP_CONN_FAIL \ - (0x0100) /* Connection Attempt was made but failed */ -#define HID_L2CAP_REQ_FAIL (0x0200) /* L2CAP_ConnectReq API failed */ -#define HID_L2CAP_CFG_FAIL \ - (0x0400) /* L2CAP Configuration was rejected by peer */ +#define HID_L2CAP_CONN_FAIL (0x0100) /* Connection Attempt was made but failed */ +#define HID_L2CAP_REQ_FAIL (0x0200) /* L2CAP_ConnectReq API failed */ +#define HID_L2CAP_CFG_FAIL (0x0400) /* L2CAP Configuration was rejected by peer */ /* Define the HID transaction types -*/ + */ #define HID_TRANS_HANDSHAKE (0) #define HID_TRANS_CONTROL (1) #define HID_TRANS_GET_REPORT (4) @@ -104,11 +102,11 @@ inline std::string hid_status_text(const tHID_STATUS& status) { #define HID_TRANS_DATAC (11) #define HID_GET_TRANS_FROM_HDR(x) (((x) >> 4) & 0x0f) -#define HID_GET_PARAM_FROM_HDR(x) ((x)&0x0f) -#define HID_BUILD_HDR(t, p) (uint8_t)(((t) << 4) | ((p)&0x0f)) +#define HID_GET_PARAM_FROM_HDR(x) ((x) & 0x0f) +#define HID_BUILD_HDR(t, p) (uint8_t)(((t) << 4) | ((p) & 0x0f)) /* Parameters for Handshake -*/ + */ #define HID_PAR_HANDSHAKE_RSP_SUCCESS (0) #define HID_PAR_HANDSHAKE_RSP_NOT_READY (1) #define HID_PAR_HANDSHAKE_RSP_ERR_INVALID_REP_ID (2) @@ -118,7 +116,7 @@ inline std::string hid_status_text(const tHID_STATUS& status) { #define HID_PAR_HANDSHAKE_RSP_ERR_FATAL (15) /* Parameters for Control -*/ + */ #define HID_PAR_CONTROL_NOP (0) #define HID_PAR_CONTROL_HARD_RESET (1) #define HID_PAR_CONTROL_SOFT_RESET (2) @@ -127,7 +125,7 @@ inline std::string hid_status_text(const tHID_STATUS& status) { #define HID_PAR_CONTROL_VIRTUAL_CABLE_UNPLUG (5) /* Different report types in get, set, data -*/ + */ #define HID_PAR_REP_TYPE_MASK (0x03) #define HID_PAR_REP_TYPE_OTHER (0x00) #define HID_PAR_REP_TYPE_INPUT (0x01) @@ -135,13 +133,13 @@ inline std::string hid_status_text(const tHID_STATUS& status) { #define HID_PAR_REP_TYPE_FEATURE (0x03) /* Parameters for Get Report -*/ + */ /* Buffer size in two bytes after Report ID */ #define HID_PAR_GET_REP_BUFSIZE_FOLLOWS (0x08) /* Parameters for Protocol Type -*/ + */ #define HID_PAR_PROTOCOL_MASK (0x01) #define HID_PAR_PROTOCOL_REPORT (0x01) #define HID_PAR_PROTOCOL_BOOT_MODE (0x00) @@ -149,7 +147,7 @@ inline std::string hid_status_text(const tHID_STATUS& status) { #define HID_PAR_REP_TYPE_MASK (0x03) /* Descriptor types in the SDP record -*/ + */ #define HID_SDP_DESCRIPTOR_REPORT (0x22) #define HID_SDP_DESCRIPTOR_PHYSICAL (0x23) @@ -170,12 +168,11 @@ typedef struct sdp_info { uint16_t hpars_ver; /*HID Parser Version.*/ uint16_t ssr_max_latency; /* HIDSSRHostMaxLatency value, if HID_SSR_PARAM_INVALID not used*/ - uint16_t - ssr_min_tout; /* HIDSSRHostMinTimeout value, if HID_SSR_PARAM_INVALID not - used* */ - uint8_t sub_class; /*Device Subclass.*/ - uint8_t ctry_code; /*Country Code.*/ - uint16_t sup_timeout; /* Supervisory Timeout */ + uint16_t ssr_min_tout; /* HIDSSRHostMinTimeout value, if HID_SSR_PARAM_INVALID not + used* */ + uint8_t sub_class; /*Device Subclass.*/ + uint8_t ctry_code; /*Country Code.*/ + uint16_t sup_timeout; /* Supervisory Timeout */ tHID_DEV_DSCP_INFO dscp_info; /* Descriptor list and Report list to be set in the SDP record. diff --git a/system/stack/include/hidh_api.h b/system/stack/include/hidh_api.h index b2f0b162fec..0173a615d8b 100644 --- a/system/stack/include/hidh_api.h +++ b/system/stack/include/hidh_api.h @@ -79,11 +79,10 @@ enum { HID_HDEV_EVT_HANDSHAKE, HID_HDEV_EVT_VC_UNPLUG }; -typedef void(tHID_HOST_DEV_CALLBACK)( - uint8_t dev_handle, const RawAddress& addr, - uint8_t event, /* Event from HID-DEVICE. */ - uint32_t data, /* Integer data corresponding to the event.*/ - BT_HDR* p_buf); /* Pointer data corresponding to the event. */ +typedef void(tHID_HOST_DEV_CALLBACK)(uint8_t dev_handle, const RawAddress& addr, + uint8_t event, /* Event from HID-DEVICE. */ + uint32_t data, /* Integer data corresponding to the event.*/ + BT_HDR* p_buf); /* Pointer data corresponding to the event. */ /***************************************************************************** * External Function Declarations @@ -98,8 +97,7 @@ typedef void(tHID_HOST_DEV_CALLBACK)( * Returns tHID_STATUS * ******************************************************************************/ -tHID_STATUS HID_HostGetSDPRecord(const RawAddress& addr, - tSDP_DISCOVERY_DB* p_db, uint32_t db_len, +tHID_STATUS HID_HostGetSDPRecord(const RawAddress& addr, tSDP_DISCOVERY_DB* p_db, uint32_t db_len, tHID_HOST_SDP_CALLBACK* sdp_cback); /******************************************************************************* @@ -145,8 +143,7 @@ bool HID_HostSDPDisable(const RawAddress& addr); * Returns tHID_STATUS * ******************************************************************************/ -tHID_STATUS HID_HostAddDev(const RawAddress& addr, uint16_t attr_mask, - uint8_t* handle); +tHID_STATUS HID_HostAddDev(const RawAddress& addr, uint16_t attr_mask, uint8_t* handle); /******************************************************************************* * @@ -181,8 +178,8 @@ tHID_STATUS HID_HostOpenDev(uint8_t dev_handle); * Returns void * ******************************************************************************/ -tHID_STATUS HID_HostWriteDev(uint8_t dev_handle, uint8_t t_type, uint8_t param, - uint16_t data, uint8_t report_id, BT_HDR* pbuf); +tHID_STATUS HID_HostWriteDev(uint8_t dev_handle, uint8_t t_type, uint8_t param, uint16_t data, + uint8_t report_id, BT_HDR* pbuf); /******************************************************************************* * diff --git a/system/stack/include/inq_hci_link_interface.h b/system/stack/include/inq_hci_link_interface.h index 2bac09462d1..075485a6b23 100644 --- a/system/stack/include/inq_hci_link_interface.h +++ b/system/stack/include/inq_hci_link_interface.h @@ -24,8 +24,8 @@ #include "stack/include/hci_error_code.h" #include "types/raw_address.h" -void btm_process_remote_name(const RawAddress* bda, const BD_NAME name, - uint16_t evt_len, tHCI_STATUS hci_status); +void btm_process_remote_name(const RawAddress* bda, const BD_NAME name, uint16_t evt_len, + tHCI_STATUS hci_status); void btm_process_inq_complete(tHCI_STATUS status, uint8_t mode); diff --git a/system/stack/include/l2c_api.h b/system/stack/include/l2c_api.h index 458d6910513..6f5b5a6acc0 100644 --- a/system/stack/include/l2c_api.h +++ b/system/stack/include/l2c_api.h @@ -47,8 +47,7 @@ #define L2CAP_MIN_OFFSET 13 /* plus control(2), SDU length(2) */ #define L2CAP_LCC_SDU_LENGTH 2 -#define L2CAP_LCC_OFFSET \ - (L2CAP_MIN_OFFSET + L2CAP_LCC_SDU_LENGTH) /* plus SDU length(2) */ +#define L2CAP_LCC_OFFSET (L2CAP_MIN_OFFSET + L2CAP_LCC_SDU_LENGTH) /* plus SDU length(2) */ #define L2CAP_FCS_LENGTH 2 @@ -98,15 +97,14 @@ typedef uint8_t tL2CAP_CHNL_DATA_RATE; #define L2CAP_FCR_CHAN_OPT_BASIC (1 << L2CAP_FCR_BASIC_MODE) #define L2CAP_FCR_CHAN_OPT_ERTM (1 << L2CAP_FCR_ERTM_MODE) -#define L2CAP_FCR_CHAN_OPT_ALL_MASK \ - (L2CAP_FCR_CHAN_OPT_BASIC | L2CAP_FCR_CHAN_OPT_ERTM) +#define L2CAP_FCR_CHAN_OPT_ALL_MASK (L2CAP_FCR_CHAN_OPT_BASIC | L2CAP_FCR_CHAN_OPT_ERTM) /* Validity check for PSM. PSM values must be odd. Also, all PSM values must * be assigned such that the least significant bit of the most sigificant * octet equals zero. */ -#define L2C_INVALID_PSM(psm) (((psm)&0x0101) != 0x0001) -#define L2C_IS_VALID_PSM(psm) (((psm)&0x0101) == 0x0001) +#define L2C_INVALID_PSM(psm) (((psm) & 0x0101) != 0x0001) +#define L2C_IS_VALID_PSM(psm) (((psm) & 0x0101) == 0x0001) #define L2C_IS_VALID_LE_PSM(psm) (((psm) > 0x0000) && ((psm) < 0x0100)) #define L2CAP_NO_IDLE_TIMEOUT 0xFFFF @@ -131,12 +129,12 @@ struct tL2CAP_FCR_OPTS { /* default options for ERTM mode */ constexpr tL2CAP_FCR_OPTS kDefaultErtmOptions = { - L2CAP_FCR_ERTM_MODE, - 10, /* Tx window size */ - 20, /* Maximum transmissions before disconnecting */ - 2000, /* Retransmission timeout (2 secs) */ - 12000, /* Monitor timeout (12 secs) */ - 1010 /* MPS segment size */ + L2CAP_FCR_ERTM_MODE, + 10, /* Tx window size */ + 20, /* Maximum transmissions before disconnecting */ + 2000, /* Retransmission timeout (2 secs) */ + 12000, /* Monitor timeout (12 secs) */ + 1010 /* MPS segment size */ }; struct FLOW_SPEC { @@ -216,8 +214,7 @@ struct tL2CAP_LE_CFG_INFO { * PSM that the remote wants to connect to * Identifier that the remote sent */ -typedef void(tL2CA_CONNECT_IND_CB)(const RawAddress&, uint16_t, uint16_t, - uint8_t); +typedef void(tL2CA_CONNECT_IND_CB)(const RawAddress&, uint16_t, uint16_t, uint8_t); /* Connection confirmation callback prototype. Parameters are * Local CID @@ -294,9 +291,8 @@ typedef void(tL2CA_ERROR_CB)(uint16_t, uint16_t); * Identifier that the remote sent */ typedef void(tL2CA_CREDIT_BASED_CONNECT_IND_CB)(const RawAddress& bdaddr, - std::vector& lcids, - uint16_t psm, uint16_t peer_mtu, - uint8_t identifier); + std::vector& lcids, uint16_t psm, + uint16_t peer_mtu, uint8_t identifier); /* Collision Indication callback prototype. Used to notify upper layer that * remote devices sent Credit Based Connection Request but it was rejected due @@ -312,10 +308,8 @@ typedef void(tL2CA_CREDIT_BASED_COLLISION_IND_CB)(const RawAddress& bdaddr); * Peer MTU * Result - 0 = connected, non-zero means CID is not connected */ -typedef void(tL2CA_CREDIT_BASED_CONNECT_CFM_CB)(const RawAddress& bdaddr, - uint16_t lcid, - uint16_t peer_mtu, - uint16_t result); +typedef void(tL2CA_CREDIT_BASED_CONNECT_CFM_CB)(const RawAddress& bdaddr, uint16_t lcid, + uint16_t peer_mtu, uint16_t result); /* Credit based reconfiguration confirm callback prototype. Parameters are * BD Address of remote @@ -323,9 +317,9 @@ typedef void(tL2CA_CREDIT_BASED_CONNECT_CFM_CB)(const RawAddress& bdaddr, * Flag indicating if this is local or peer configuration * Pointer to configuration info */ -typedef void(tL2CA_CREDIT_BASED_RECONFIG_COMPLETED_CB)( - const RawAddress& bdaddr, uint16_t lcid, bool is_local_cfg, - tL2CAP_LE_CFG_INFO* p_cfg); +typedef void(tL2CA_CREDIT_BASED_RECONFIG_COMPLETED_CB)(const RawAddress& bdaddr, uint16_t lcid, + bool is_local_cfg, + tL2CAP_LE_CFG_INFO* p_cfg); /* Define the structure that applications use to register with * L2CAP. This structure includes callback functions. All functions @@ -345,8 +339,7 @@ struct tL2CAP_APPL_INFO { tL2CA_ERROR_CB* pL2CA_Error_Cb; tL2CA_CREDIT_BASED_CONNECT_IND_CB* pL2CA_CreditBasedConnectInd_Cb; tL2CA_CREDIT_BASED_CONNECT_CFM_CB* pL2CA_CreditBasedConnectCfm_Cb; - tL2CA_CREDIT_BASED_RECONFIG_COMPLETED_CB* - pL2CA_CreditBasedReconfigCompleted_Cb; + tL2CA_CREDIT_BASED_RECONFIG_COMPLETED_CB* pL2CA_CreditBasedReconfigCompleted_Cb; tL2CA_CREDIT_BASED_COLLISION_IND_CB* pL2CA_CreditBasedCollisionInd_Cb; }; @@ -362,10 +355,10 @@ struct tL2CAP_ERTM_INFO { ****************************************************************************/ // Also does security for you -[[nodiscard]] uint16_t L2CA_RegisterWithSecurity( - uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info, bool enable_snoop, - tL2CAP_ERTM_INFO* p_ertm_info, uint16_t my_mtu, - uint16_t required_remote_mtu, uint16_t sec_level); +[[nodiscard]] uint16_t L2CA_RegisterWithSecurity(uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info, + bool enable_snoop, tL2CAP_ERTM_INFO* p_ertm_info, + uint16_t my_mtu, uint16_t required_remote_mtu, + uint16_t sec_level); /******************************************************************************* * @@ -381,10 +374,10 @@ struct tL2CAP_ERTM_INFO { * BTM_SetSecurityLevel(). * ******************************************************************************/ -[[nodiscard]] uint16_t L2CA_Register( - uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info, bool enable_snoop, - tL2CAP_ERTM_INFO* p_ertm_info, uint16_t my_mtu, - uint16_t required_remote_mtu, uint16_t sec_level); +[[nodiscard]] uint16_t L2CA_Register(uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info, + bool enable_snoop, tL2CAP_ERTM_INFO* p_ertm_info, + uint16_t my_mtu, uint16_t required_remote_mtu, + uint16_t sec_level); /******************************************************************************* * @@ -421,8 +414,7 @@ void L2CA_Deregister(uint16_t psm); ******************************************************************************/ void L2CA_FreeLePSM(uint16_t psm); -[[nodiscard]] uint16_t L2CA_ConnectReqWithSecurity(uint16_t psm, - const RawAddress& p_bd_addr, +[[nodiscard]] uint16_t L2CA_ConnectReqWithSecurity(uint16_t psm, const RawAddress& p_bd_addr, uint16_t sec_level); /******************************************************************************* * @@ -437,8 +429,7 @@ void L2CA_FreeLePSM(uint16_t psm); * Returns the CID of the connection, or 0 if it failed to start * ******************************************************************************/ -[[nodiscard]] uint16_t L2CA_ConnectReq(uint16_t psm, - const RawAddress& p_bd_addr); +[[nodiscard]] uint16_t L2CA_ConnectReq(uint16_t psm, const RawAddress& p_bd_addr); /******************************************************************************* * @@ -454,10 +445,8 @@ void L2CA_FreeLePSM(uint16_t psm); * and BTM_SetSecurityLevel(). * ******************************************************************************/ -[[nodiscard]] uint16_t L2CA_RegisterLECoc(uint16_t psm, - const tL2CAP_APPL_INFO& p_cb_info, - uint16_t sec_level, - tL2CAP_LE_CFG_INFO cfg); +[[nodiscard]] uint16_t L2CA_RegisterLECoc(uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info, + uint16_t sec_level, tL2CAP_LE_CFG_INFO cfg); /******************************************************************************* * @@ -483,10 +472,8 @@ void L2CA_DeregisterLECoc(uint16_t psm); * Returns the CID of the connection, or 0 if it failed to start * ******************************************************************************/ -[[nodiscard]] uint16_t L2CA_ConnectLECocReq(uint16_t psm, - const RawAddress& p_bd_addr, - tL2CAP_LE_CFG_INFO* p_cfg, - uint16_t sec_level); +[[nodiscard]] uint16_t L2CA_ConnectLECocReq(uint16_t psm, const RawAddress& p_bd_addr, + tL2CAP_LE_CFG_INFO* p_cfg, uint16_t sec_level); /******************************************************************************* * @@ -497,8 +484,7 @@ void L2CA_DeregisterLECoc(uint16_t psm); * Return value: true if peer is connected * ******************************************************************************/ -[[nodiscard]] bool L2CA_GetPeerLECocConfig(uint16_t lcid, - tL2CAP_LE_CFG_INFO* peer_cfg); +[[nodiscard]] bool L2CA_GetPeerLECocConfig(uint16_t lcid, tL2CAP_LE_CFG_INFO* peer_cfg); /******************************************************************************* * @@ -510,8 +496,7 @@ void L2CA_DeregisterLECoc(uint16_t psm); * Return value: Number of the peer current credit * ******************************************************************************/ -[[nodiscard]] uint16_t L2CA_GetPeerLECocCredit(const RawAddress& bd_addr, - uint16_t lcid); +[[nodiscard]] uint16_t L2CA_GetPeerLECocCredit(const RawAddress& bd_addr, uint16_t lcid); /******************************************************************************* * @@ -522,9 +507,9 @@ void L2CA_DeregisterLECoc(uint16_t psm); * Return value: true if peer is connected * ******************************************************************************/ -[[nodiscard]] bool L2CA_ReconfigCreditBasedConnsReq( - const RawAddress& bd_addr, std::vector& lcids, - tL2CAP_LE_CFG_INFO* p_cfg); +[[nodiscard]] bool L2CA_ReconfigCreditBasedConnsReq(const RawAddress& bd_addr, + std::vector& lcids, + tL2CAP_LE_CFG_INFO* p_cfg); /******************************************************************************* * @@ -539,8 +524,9 @@ void L2CA_DeregisterLECoc(uint16_t psm); * ******************************************************************************/ -[[nodiscard]] std::vector L2CA_ConnectCreditBasedReq( - uint16_t psm, const RawAddress& p_bd_addr, tL2CAP_LE_CFG_INFO* p_cfg); +[[nodiscard]] std::vector L2CA_ConnectCreditBasedReq(uint16_t psm, + const RawAddress& p_bd_addr, + tL2CAP_LE_CFG_INFO* p_cfg); /******************************************************************************* * @@ -553,10 +539,9 @@ void L2CA_DeregisterLECoc(uint16_t psm); * ******************************************************************************/ -[[nodiscard]] bool L2CA_ConnectCreditBasedRsp( - const RawAddress& p_bd_addr, uint8_t id, - std::vector& accepted_lcids, uint16_t result, - tL2CAP_LE_CFG_INFO* p_cfg); +[[nodiscard]] bool L2CA_ConnectCreditBasedRsp(const RawAddress& p_bd_addr, uint8_t id, + std::vector& accepted_lcids, + uint16_t result, tL2CAP_LE_CFG_INFO* p_cfg); /******************************************************************************* * * Function L2CA_DisconnectReq @@ -585,8 +570,7 @@ void L2CA_DeregisterLECoc(uint16_t psm); ******************************************************************************/ [[nodiscard]] tL2CAP_DW_RESULT L2CA_DataWrite(uint16_t cid, BT_HDR* p_data); -[[nodiscard]] tL2CAP_DW_RESULT L2CA_LECocDataWrite(uint16_t cid, - BT_HDR* p_data); +[[nodiscard]] tL2CAP_DW_RESULT L2CA_LECocDataWrite(uint16_t cid, BT_HDR* p_data); /******************************************************************************* * @@ -624,8 +608,7 @@ void L2CA_DeregisterLECoc(uint16_t psm); * NOTE This timeout applies to all logical channels active on the * ACL link. ******************************************************************************/ -[[nodiscard]] bool L2CA_SetIdleTimeoutByBdAddr(const RawAddress& bd_addr, - uint16_t timeout, +[[nodiscard]] bool L2CA_SetIdleTimeoutByBdAddr(const RawAddress& bd_addr, uint16_t timeout, tBT_TRANSPORT transport); /******************************************************************************* @@ -653,8 +636,7 @@ void L2CA_DeregisterLECoc(uint16_t psm); * Returns true if a valid channel, else false * ******************************************************************************/ -[[nodiscard]] bool L2CA_UseLatencyMode(const RawAddress& bd_addr, - bool use_latency_mode); +[[nodiscard]] bool L2CA_UseLatencyMode(const RawAddress& bd_addr, bool use_latency_mode); /******************************************************************************* * @@ -667,8 +649,7 @@ void L2CA_DeregisterLECoc(uint16_t psm); * Returns true if a valid channel, else false * ******************************************************************************/ -[[nodiscard]] bool L2CA_SetAclPriority(const RawAddress& bd_addr, - tL2CAP_PRIORITY priority); +[[nodiscard]] bool L2CA_SetAclPriority(const RawAddress& bd_addr, tL2CAP_PRIORITY priority); /******************************************************************************* * @@ -679,8 +660,7 @@ void L2CA_DeregisterLECoc(uint16_t psm); * Returns true if a valid channel, else false * ******************************************************************************/ -[[nodiscard]] bool L2CA_SetAclLatency(const RawAddress& bd_addr, - tL2CAP_LATENCY latency); +[[nodiscard]] bool L2CA_SetAclLatency(const RawAddress& bd_addr, tL2CAP_LATENCY latency); /******************************************************************************* * @@ -691,8 +671,7 @@ void L2CA_DeregisterLECoc(uint16_t psm); * Returns true if a valid channel, else false * ******************************************************************************/ -[[nodiscard]] bool L2CA_SetTxPriority(uint16_t cid, - tL2CAP_CHNL_PRIORITY priority); +[[nodiscard]] bool L2CA_SetTxPriority(uint16_t cid, tL2CAP_CHNL_PRIORITY priority); /******************************************************************************* * @@ -718,8 +697,7 @@ void L2CA_DeregisterLECoc(uint16_t psm); * Return value: true if peer is connected * ******************************************************************************/ -[[nodiscard]] bool L2CA_GetPeerFeatures(const RawAddress& bd_addr, - uint32_t* p_ext_feat, +[[nodiscard]] bool L2CA_GetPeerFeatures(const RawAddress& bd_addr, uint32_t* p_ext_feat, uint8_t* p_chnl_mask); /******************************************************************************* @@ -735,8 +713,7 @@ void L2CA_DeregisterLECoc(uint16_t psm); * Reason for connection failure * transport : physical transport, BR/EDR or LE */ -typedef void(tL2CA_FIXED_CHNL_CB)(uint16_t, const RawAddress&, bool, uint16_t, - tBT_TRANSPORT); +typedef void(tL2CA_FIXED_CHNL_CB)(uint16_t, const RawAddress&, bool, uint16_t, tBT_TRANSPORT); /* Signalling data received. Parameters are * channel @@ -761,8 +738,7 @@ struct tL2CAP_FIXED_CHNL_REG { tL2CA_FIXED_CONGESTION_STATUS_CB* pL2CA_FixedCong_Cb; uint16_t default_idle_tout; - tL2CA_TX_COMPLETE_CB* - pL2CA_FixedTxComplete_Cb; /* fixed channel tx complete callback */ + tL2CA_TX_COMPLETE_CB* pL2CA_FixedTxComplete_Cb; /* fixed channel tx complete callback */ }; /******************************************************************************* @@ -777,8 +753,7 @@ struct tL2CAP_FIXED_CHNL_REG { * Return value: true if registered OK * ******************************************************************************/ -[[nodiscard]] bool L2CA_RegisterFixedChannel(uint16_t fixed_cid, - tL2CAP_FIXED_CHNL_REG* p_freg); +[[nodiscard]] bool L2CA_RegisterFixedChannel(uint16_t fixed_cid, tL2CAP_FIXED_CHNL_REG* p_freg); /******************************************************************************* * @@ -792,8 +767,7 @@ struct tL2CAP_FIXED_CHNL_REG { * Return value: true if connection started * ******************************************************************************/ -[[nodiscard]] bool L2CA_ConnectFixedChnl(uint16_t fixed_cid, - const RawAddress& bd_addr); +[[nodiscard]] bool L2CA_ConnectFixedChnl(uint16_t fixed_cid, const RawAddress& bd_addr); /******************************************************************************* * @@ -809,8 +783,7 @@ struct tL2CAP_FIXED_CHNL_REG { * tL2CAP_DW_RESULT::L2CAP_DW_FAILED, if error * ******************************************************************************/ -[[nodiscard]] tL2CAP_DW_RESULT L2CA_SendFixedChnlData(uint16_t fixed_cid, - const RawAddress& rem_bda, +[[nodiscard]] tL2CAP_DW_RESULT L2CA_SendFixedChnlData(uint16_t fixed_cid, const RawAddress& rem_bda, BT_HDR* p_buf); /******************************************************************************* @@ -826,8 +799,7 @@ struct tL2CAP_FIXED_CHNL_REG { * Return value: true if channel removed * ******************************************************************************/ -[[nodiscard]] bool L2CA_RemoveFixedChnl(uint16_t fixed_cid, - const RawAddress& rem_bda); +[[nodiscard]] bool L2CA_RemoveFixedChnl(uint16_t fixed_cid, const RawAddress& rem_bda); /******************************************************************************* * @@ -846,30 +818,25 @@ struct tL2CAP_FIXED_CHNL_REG { * Returns true if command succeeded, false if failed * ******************************************************************************/ -[[nodiscard]] bool L2CA_SetLeGattTimeout(const RawAddress& rem_bda, - uint16_t idle_tout); +[[nodiscard]] bool L2CA_SetLeGattTimeout(const RawAddress& rem_bda, uint16_t idle_tout); [[nodiscard]] bool L2CA_MarkLeLinkAsActive(const RawAddress& rem_bda); -[[nodiscard]] bool L2CA_UpdateBleConnParams(const RawAddress& rem_bda, - uint16_t min_int, uint16_t max_int, - uint16_t latency, uint16_t timeout, - uint16_t min_ce_len, - uint16_t max_ce_len); +[[nodiscard]] bool L2CA_UpdateBleConnParams(const RawAddress& rem_bda, uint16_t min_int, + uint16_t max_int, uint16_t latency, uint16_t timeout, + uint16_t min_ce_len, uint16_t max_ce_len); /* When called with lock=true, LE connection parameters will be locked on * fastest value, and we won't accept request to change it from remote. When * called with lock=false, parameters are relaxed. */ -void L2CA_LockBleConnParamsForServiceDiscovery(const RawAddress& rem_bda, - bool lock); +void L2CA_LockBleConnParamsForServiceDiscovery(const RawAddress& rem_bda, bool lock); /* When called with lock=true, LE connection parameters will be locked on * fastest value, and we won't accept request to change it from remote. When * called with lock=false, parameters are relaxed. */ -void L2CA_LockBleConnParamsForProfileConnection(const RawAddress& rem_bda, - bool lock); +void L2CA_LockBleConnParamsForProfileConnection(const RawAddress& rem_bda, bool lock); /******************************************************************************* * @@ -883,8 +850,7 @@ void L2CA_LockBleConnParamsForProfileConnection(const RawAddress& rem_bda, void L2CA_Consolidate(const RawAddress& identity_addr, const RawAddress& rpa); [[nodiscard]] tHCI_ROLE L2CA_GetBleConnRole(const RawAddress& bd_addr); -void L2CA_AdjustConnectionIntervals(uint16_t* min_interval, - uint16_t* max_interval, +void L2CA_AdjustConnectionIntervals(uint16_t* min_interval, uint16_t* max_interval, uint16_t floor_interval); void L2CA_SetEcosystemBaseInterval(uint32_t base_interval); @@ -892,8 +858,7 @@ void L2CA_SetEcosystemBaseInterval(uint32_t base_interval); /** * Check whether an ACL or LE link to the remote device is established */ -[[nodiscard]] bool L2CA_IsLinkEstablished(const RawAddress& bd_addr, - tBT_TRANSPORT transport); +[[nodiscard]] bool L2CA_IsLinkEstablished(const RawAddress& bd_addr, tBT_TRANSPORT transport); /******************************************************************************* * @@ -906,9 +871,8 @@ void L2CA_SetEcosystemBaseInterval(uint32_t base_interval); * Return value: void * ******************************************************************************/ -void L2CA_SetDefaultSubrate(uint16_t subrate_min, uint16_t subrate_max, - uint16_t max_latency, uint16_t cont_num, - uint16_t timeout); +void L2CA_SetDefaultSubrate(uint16_t subrate_min, uint16_t subrate_max, uint16_t max_latency, + uint16_t cont_num, uint16_t timeout); /******************************************************************************* * @@ -921,11 +885,9 @@ void L2CA_SetDefaultSubrate(uint16_t subrate_min, uint16_t subrate_max, * Return value: true if update started * ******************************************************************************/ -[[nodiscard]] bool L2CA_SubrateRequest(const RawAddress& rem_bda, - uint16_t subrate_min, - uint16_t subrate_max, - uint16_t max_latency, uint16_t cont_num, - uint16_t timeout); +[[nodiscard]] bool L2CA_SubrateRequest(const RawAddress& rem_bda, uint16_t subrate_min, + uint16_t subrate_max, uint16_t max_latency, + uint16_t cont_num, uint16_t timeout); /******************************************************************************* ** @@ -958,8 +920,7 @@ void L2CA_SetMediaStreamChannel(uint16_t local_media_cid, bool status); ** Returns bool ** *******************************************************************************/ -[[nodiscard]] bool L2CA_isMediaChannel(uint16_t handle, uint16_t channel_id, - bool is_local_cid); +[[nodiscard]] bool L2CA_isMediaChannel(uint16_t handle, uint16_t channel_id, bool is_local_cid); namespace fmt { template <> diff --git a/system/stack/include/l2cap_acl_interface.h b/system/stack/include/l2cap_acl_interface.h index 0bb5d1778b6..cb779da519c 100644 --- a/system/stack/include/l2cap_acl_interface.h +++ b/system/stack/include/l2cap_acl_interface.h @@ -31,8 +31,7 @@ bool acl_create_le_connection_with_id(uint8_t id, const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type); void acl_send_data_packet_br_edr(const RawAddress& bd_addr, BT_HDR* p_buf); void acl_send_data_packet_ble(const RawAddress& bd_addr, BT_HDR* p_buf); -void acl_write_automatic_flush_timeout(const RawAddress& bd_addr, - uint16_t flush_timeout); +void acl_write_automatic_flush_timeout(const RawAddress& bd_addr, uint16_t flush_timeout); // ACL data received from HCI-ACL void l2c_rcv_acl_data(BT_HDR* p_msg); diff --git a/system/stack/include/l2cap_controller_interface.h b/system/stack/include/l2cap_controller_interface.h index 1bea9d82b5f..cda836ca673 100644 --- a/system/stack/include/l2cap_controller_interface.h +++ b/system/stack/include/l2cap_controller_interface.h @@ -24,6 +24,6 @@ void l2cu_set_non_flushable_pbf(bool is_supported); void l2c_link_init(const uint16_t acl_buffer_count_classic); -void l2c_link_processs_ble_num_bufs(uint16_t num_lm_acl_bufs); +void l2c_link_process_ble_num_bufs(uint16_t num_lm_acl_bufs); void l2cu_device_reset(void); diff --git a/system/stack/include/l2cap_hci_link_interface.h b/system/stack/include/l2cap_hci_link_interface.h index 3815e3cd073..978aadade57 100644 --- a/system/stack/include/l2cap_hci_link_interface.h +++ b/system/stack/include/l2cap_hci_link_interface.h @@ -28,23 +28,18 @@ bool l2c_link_hci_disc_comp(uint16_t handle, tHCI_REASON reason); -void l2c_link_role_changed(const RawAddress* bd_addr, tHCI_ROLE role, - tHCI_STATUS hci_status); +void l2c_link_role_changed(const RawAddress* bd_addr, tHCI_ROLE role, tHCI_STATUS hci_status); -bool l2cble_conn_comp(uint16_t handle, tHCI_ROLE role, const RawAddress& bda, - tBLE_ADDR_TYPE type, uint16_t conn_interval, - uint16_t conn_latency, uint16_t conn_timeout); +bool l2cble_conn_comp(uint16_t handle, tHCI_ROLE role, const RawAddress& bda, tBLE_ADDR_TYPE type, + uint16_t conn_interval, uint16_t conn_latency, uint16_t conn_timeout); -void l2cble_process_conn_update_evt(uint16_t handle, uint8_t status, - uint16_t interval, uint16_t latency, - uint16_t timeout); +void l2cble_process_conn_update_evt(uint16_t handle, uint8_t status, uint16_t interval, + uint16_t latency, uint16_t timeout); void l2cble_process_rc_param_request_evt(uint16_t handle, uint16_t interval_min, - uint16_t interval_max, - uint16_t latency, uint16_t timeout); + uint16_t interval_max, uint16_t latency, uint16_t timeout); -void l2cble_process_data_length_change_event(uint16_t handle, - uint16_t tx_data_len, +void l2cble_process_data_length_change_event(uint16_t handle, uint16_t tx_data_len, uint16_t rx_data_len); // Notify to L2cap layer that ACL data or remote version is received @@ -52,9 +47,8 @@ void l2cble_notify_le_connection(const RawAddress& bda); void l2cble_use_preferred_conn_params(const RawAddress& bda); -void l2cble_process_rc_param_request_evt(uint16_t handle, uint16_t int_min, - uint16_t int_max, uint16_t latency, - uint16_t timeout); +void l2cble_process_rc_param_request_evt(uint16_t handle, uint16_t int_min, uint16_t int_max, + uint16_t latency, uint16_t timeout); // Invoked when HCI mode is changed to HCI_MODE_ACTIVE or HCI_MODE_SNIFF void l2c_OnHciModeChangeSendPendingPackets(RawAddress remote); diff --git a/system/stack/include/l2cdefs.h b/system/stack/include/l2cdefs.h index a0aad238218..fb14fe15bd7 100644 --- a/system/stack/include/l2cdefs.h +++ b/system/stack/include/l2cdefs.h @@ -28,7 +28,7 @@ #include "macros.h" /* L2CAP command codes -*/ + */ #define L2CAP_CMD_REJECT 0x01 #define L2CAP_CMD_CONN_REQ 0x02 #define L2CAP_CMD_CONN_RSP 0x03 @@ -54,7 +54,7 @@ #define L2CAP_CMD_CREDIT_BASED_RECONFIG_RES 0x1A /* Define some packet and header lengths -*/ + */ /* Length and CID */ #define L2CAP_PKT_OVERHEAD 4 /* Cmd code, Id and length */ @@ -103,7 +103,7 @@ #define L2CAP_CMD_CREDIT_BASED_RECONFIG_RES_LEN 2 /* Define the packet boundary flags -*/ + */ #define L2CAP_PKT_START_NON_FLUSHABLE 0 #define L2CAP_PKT_START 2 #define L2CAP_PKT_CONTINUE 1 @@ -180,8 +180,7 @@ inline std::string l2cap_result_code_text(const tL2CAP_CONN& result) { CASE_RETURN_TEXT(L2CAP_CONN_UNACCEPTABLE_PARAMETERS); CASE_RETURN_TEXT(L2CAP_CONN_INVALID_PARAMETERS); default: - return std::string("UNKNOWN[") + std::to_string(result) + - std::string("]"); + return std::string("UNKNOWN[") + std::to_string(result) + std::string("]"); } } @@ -210,8 +209,7 @@ static inline std::string l2cap_command_code_text(uint8_t cmd) { CASE_RETURN_TEXT(L2CAP_CMD_CREDIT_BASED_RECONFIG_REQ); CASE_RETURN_TEXT(L2CAP_CMD_CREDIT_BASED_RECONFIG_RES); default: - return std::string("UNKNOWN L2CAP CMD[") + std::to_string(cmd) + - std::string("]"); + return std::string("UNKNOWN L2CAP CMD[") + std::to_string(cmd) + std::string("]"); } } @@ -219,8 +217,7 @@ inline tL2CAP_CONN to_l2cap_result_code(uint16_t result) { return static_cast(result); } -inline std::string l2cap_le_result_code_text( - const tL2CAP_LE_RESULT_CODE& code) { +inline std::string l2cap_le_result_code_text(const tL2CAP_LE_RESULT_CODE& code) { switch (code) { case L2CAP_LE_RESULT_CONN_OK: return std::string("le connection success"); @@ -255,13 +252,13 @@ inline std::string l2cap_le_result_code_text( #define L2CAP_RECONFIG_UNACCAPTED_PARAM 4 /* Define the L2CAP command reject reason codes -*/ + */ #define L2CAP_CMD_REJ_NOT_UNDERSTOOD 0 #define L2CAP_CMD_REJ_MTU_EXCEEDED 1 #define L2CAP_CMD_REJ_INVALID_CID 2 /* L2CAP Predefined CIDs -*/ + */ enum tL2CAP_CID_FIXED : uint16_t { L2CAP_SIGNALLING_CID = 1, L2CAP_CONNECTIONLESS_CID = 2, @@ -308,7 +305,7 @@ inline std::string l2cap_cid_fixed_text(const tL2CAP_CID_FIXED& cid) { #define L2CAP_FIXED_CHNL_SMP_BR_BIT (1 << L2CAP_SMP_BR_CID) /* Define the L2CAP configuration result codes -*/ + */ enum tL2CAP_CFG_RESULT : uint16_t { L2CAP_CFG_OK = 0, L2CAP_CFG_UNACCEPTABLE_PARAMS = 1, @@ -318,7 +315,7 @@ enum tL2CAP_CFG_RESULT : uint16_t { }; /* Define the L2CAP configuration option types -*/ + */ #define L2CAP_CFG_TYPE_MTU 0x01 #define L2CAP_CFG_TYPE_FLUSH_TOUT 0x02 #define L2CAP_CFG_TYPE_QOS 0x03 @@ -335,17 +332,16 @@ enum tL2CAP_CFG_RESULT : uint16_t { #define L2CAP_CFG_OPTION_OVERHEAD 2 /* Type and length */ /* Configuration Cmd/Rsp Flags mask -*/ + */ #define L2CAP_CFG_FLAGS_MASK_CONT 0x0001 /* Flags mask: Continuation */ /* FCS Check Option values -*/ + */ #define L2CAP_CFG_FCS_BYPASS 0 /* Bypass the FCS in streaming or ERTM modes */ -#define L2CAP_CFG_FCS_USE \ - 1 /* Use the FCS in streaming or ERTM modes [default] */ +#define L2CAP_CFG_FCS_USE 1 /* Use the FCS in streaming or ERTM modes [default] */ /* Default values for configuration -*/ + */ #define L2CAP_NO_AUTOMATIC_FLUSH 0xFFFF #define L2CAP_DEFAULT_MTU (672) @@ -357,17 +353,17 @@ enum tL2CAP_CFG_RESULT : uint16_t { #define L2CAP_DEFAULT_DELAY 0xFFFFFFFF /* Define the L2CAP disconnect result codes -*/ + */ #define L2CAP_DISC_OK 0 #define L2CAP_DISC_TIMEOUT 0xEEEE /* Define the L2CAP info resp result codes -*/ + */ #define L2CAP_INFO_RESP_RESULT_SUCCESS 0 #define L2CAP_INFO_RESP_RESULT_NOT_SUPPORTED 1 /* Define the info-type fields of information request & response -*/ + */ #define L2CAP_CONNLESS_MTU_INFO_TYPE 0x0001 /* Used in Information Req/Response */ #define L2CAP_EXTENDED_FEATURES_INFO_TYPE 0x0002 @@ -382,7 +378,7 @@ enum tL2CAP_CFG_RESULT : uint16_t { #define L2CAP_FIXED_CHNL_ARRAY_SIZE 8 /* Extended features mask bits -*/ + */ /* Enhanced retransmission mode */ #define L2CAP_EXTFEA_ENH_RETRANS 0x00000008 /* Streaming Mode */ @@ -421,9 +417,8 @@ enum tL2CAP_CFG_RESULT : uint16_t { #define L2CAP_SDU_LEN_OFFSET 2 /* SDU length offset is 2 bytes */ #define L2CAP_EXT_CONTROL_OVERHEAD 4 /* Extended Control Field */ /* length(2), channel(2), control(4), SDU length(2) FCS(2) */ -#define L2CAP_MAX_HEADER_FCS \ - (L2CAP_PKT_OVERHEAD + L2CAP_EXT_CONTROL_OVERHEAD + L2CAP_SDU_LEN_OVERHEAD + \ - L2CAP_FCS_LEN) +#define L2CAP_MAX_HEADER_FCS \ + (L2CAP_PKT_OVERHEAD + L2CAP_EXT_CONTROL_OVERHEAD + L2CAP_SDU_LEN_OVERHEAD + L2CAP_FCS_LEN) /* TODO: This value can probably be optimized per transport, and per L2CAP * socket type, but this should not bring any big performance improvements. For @@ -435,7 +430,7 @@ enum tL2CAP_CFG_RESULT : uint16_t { constexpr uint16_t L2CAP_SDU_LENGTH_LE_MAX = 0xffff; /* SAR bits in the control word -*/ + */ /* Control word to begin with for unsegmented PDU*/ #define L2CAP_FCR_UNSEG_SDU 0x0000 /* ...for Starting PDU of a semented SDU */ diff --git a/system/stack/include/ldacBT_bco_for_fluoride.h b/system/stack/include/ldacBT_bco_for_fluoride.h index 3d9e548d193..9275814cad3 100644 --- a/system/stack/include/ldacBT_bco_for_fluoride.h +++ b/system/stack/include/ldacBT_bco_for_fluoride.h @@ -51,8 +51,7 @@ typedef void (*decoded_data_callback_t)(uint8_t* buf, uint32_t len); * Return value * HANDLE_LDAC_BCO for success, NULL for failure. */ -LDAC_BCO_API HANDLE_LDAC_BCO -ldac_BCO_init(decoded_data_callback_t decode_callback); +LDAC_BCO_API HANDLE_LDAC_BCO ldac_BCO_init(decoded_data_callback_t decode_callback); /* End LDAC BCO. * - Release of LDAC BCO handle. @@ -87,8 +86,7 @@ LDAC_BCO_API int32_t ldac_BCO_cleanup(HANDLE_LDAC_BCO hLdacBco); * The function ldac_BCO_init() shall be called before calling this * function. */ -LDAC_BCO_API int32_t ldac_BCO_decode_packet(HANDLE_LDAC_BCO hLdacBco, - void* data, int32_t length); +LDAC_BCO_API int32_t ldac_BCO_decode_packet(HANDLE_LDAC_BCO hLdacBco, void* data, int32_t length); /* Start decoding process. * - Start or resume decoder thread. @@ -141,10 +139,8 @@ LDAC_BCO_API int32_t ldac_BCO_suspend(HANDLE_LDAC_BCO hLdacBco); * The function ldac_BCO_init() shall be called before calling this * function. */ -LDAC_BCO_API int32_t ldac_BCO_configure(HANDLE_LDAC_BCO hLdacBco, - int32_t sample_rate, - int32_t bits_per_sample, - int32_t channel_mode); +LDAC_BCO_API int32_t ldac_BCO_configure(HANDLE_LDAC_BCO hLdacBco, int32_t sample_rate, + int32_t bits_per_sample, int32_t channel_mode); #ifdef __cplusplus } diff --git a/system/stack/include/main_thread.h b/system/stack/include/main_thread.h index b8725d279f9..04c93dffe77 100644 --- a/system/stack/include/main_thread.h +++ b/system/stack/include/main_thread.h @@ -29,10 +29,8 @@ using BtMainClosure = std::function; bluetooth::common::MessageLoopThread* get_main_thread(); bluetooth::common::PostableContext* get_main(); -bt_status_t do_in_main_thread(const base::Location& from_here, - base::OnceClosure task); -bt_status_t do_in_main_thread_delayed(const base::Location& from_here, - base::OnceClosure task, +bt_status_t do_in_main_thread(const base::Location& from_here, base::OnceClosure task); +bt_status_t do_in_main_thread_delayed(const base::Location& from_here, base::OnceClosure task, std::chrono::microseconds delay); void post_on_bt_main(BtMainClosure closure); void main_thread_start_up(); diff --git a/system/stack/include/pan_api.h b/system/stack/include/pan_api.h index 6af1fdef6d9..677ab4494a8 100644 --- a/system/stack/include/pan_api.h +++ b/system/stack/include/pan_api.h @@ -42,13 +42,13 @@ * sending PAN packets. Note, we are currently not sending * extension headers, but may in the future, so allow * space for them -*/ + */ #define PAN_MINIMUM_OFFSET BNEP_MINIMUM_OFFSET /* * The handle is passed from BNEP to PAN. The same handle is used * between PAN and application as well -*/ + */ #define PAN_INVALID_HANDLE BNEP_INVALID_HANDLE /* Bit map for PAN roles */ @@ -58,8 +58,7 @@ typedef uint8_t tPAN_ROLE; inline const std::string pan_role_to_text(const tPAN_ROLE& role) { - return base::StringPrintf("%c%c%c[0x%x]", - (role & PAN_ROLE_CLIENT) ? 'C' : '.', + return base::StringPrintf("%c%c%c[0x%x]", (role & PAN_ROLE_CLIENT) ? 'C' : '.', (role & PAN_ROLE_GROUP) ? 'G' : '.', (role & PAN_ROLE_NAP_SERVER) ? 'N' : '.', role); } @@ -70,33 +69,27 @@ inline const std::string pan_role_to_text(const tPAN_ROLE& role) { /* Define the result codes from PAN */ typedef enum : uint8_t { - PAN_SUCCESS, /* Success */ - PAN_DISCONNECTED = BNEP_CONN_DISCONNECTED, /* Connection terminated */ - PAN_CONN_FAILED = BNEP_CONN_FAILED, /* Connection failed */ - PAN_NO_RESOURCES = BNEP_NO_RESOURCES, /* No resources */ - PAN_MTU_EXCEDED = BNEP_MTU_EXCEDED, /* Attempt to write long data */ - PAN_INVALID_OFFSET = - BNEP_INVALID_OFFSET, /* Insufficient offset in GKI buffer */ - PAN_CONN_FAILED_CFG = - BNEP_CONN_FAILED_CFG, /* Connection failed cos of config */ - PAN_INVALID_SRC_ROLE = - BNEP_CONN_FAILED_SRC_UUID, /* Connection failed wrong source UUID */ - PAN_INVALID_DST_ROLE = - BNEP_CONN_FAILED_DST_UUID, /* Connection failed wrong destination UUID */ - PAN_CONN_FAILED_UUID_SIZE = - BNEP_CONN_FAILED_UUID_SIZE, /* Connection failed wrong size UUID */ - PAN_Q_SIZE_EXCEEDED = BNEP_Q_SIZE_EXCEEDED, /* Too many buffers to dest */ - PAN_TOO_MANY_FILTERS = - BNEP_TOO_MANY_FILTERS, /* Too many local filters specified */ - PAN_SET_FILTER_FAIL = BNEP_SET_FILTER_FAIL, /* Set Filter failed */ - PAN_WRONG_HANDLE = BNEP_WRONG_HANDLE, /* Wrong handle for the connection */ - PAN_WRONG_STATE = BNEP_WRONG_STATE, /* Connection is in wrong state */ - PAN_SECURITY_FAIL = BNEP_SECURITY_FAIL, /* Failed because of security */ - PAN_IGNORE_CMD = BNEP_IGNORE_CMD, /* To ignore the rcvd command */ - PAN_TX_FLOW_ON = BNEP_TX_FLOW_ON, /* tx data flow enabled */ - PAN_TX_FLOW_OFF = BNEP_TX_FLOW_OFF, /* tx data flow disabled */ - PAN_FAILURE = 19, /* Failure */ - PAN_HOTSPOT_DISABLED = 20, /* Hotspot disabled */ + PAN_SUCCESS, /* Success */ + PAN_DISCONNECTED = BNEP_CONN_DISCONNECTED, /* Connection terminated */ + PAN_CONN_FAILED = BNEP_CONN_FAILED, /* Connection failed */ + PAN_NO_RESOURCES = BNEP_NO_RESOURCES, /* No resources */ + PAN_MTU_EXCEEDED = BNEP_MTU_EXCEEDED, /* Attempt to write long data */ + PAN_INVALID_OFFSET = BNEP_INVALID_OFFSET, /* Insufficient offset in GKI buffer */ + PAN_CONN_FAILED_CFG = BNEP_CONN_FAILED_CFG, /* Connection failed cos of config */ + PAN_INVALID_SRC_ROLE = BNEP_CONN_FAILED_SRC_UUID, /* Connection failed wrong source UUID */ + PAN_INVALID_DST_ROLE = BNEP_CONN_FAILED_DST_UUID, /* Connection failed wrong destination UUID */ + PAN_CONN_FAILED_UUID_SIZE = BNEP_CONN_FAILED_UUID_SIZE, /* Connection failed wrong size UUID */ + PAN_Q_SIZE_EXCEEDED = BNEP_Q_SIZE_EXCEEDED, /* Too many buffers to dest */ + PAN_TOO_MANY_FILTERS = BNEP_TOO_MANY_FILTERS, /* Too many local filters specified */ + PAN_SET_FILTER_FAIL = BNEP_SET_FILTER_FAIL, /* Set Filter failed */ + PAN_WRONG_HANDLE = BNEP_WRONG_HANDLE, /* Wrong handle for the connection */ + PAN_WRONG_STATE = BNEP_WRONG_STATE, /* Connection is in wrong state */ + PAN_SECURITY_FAIL = BNEP_SECURITY_FAIL, /* Failed because of security */ + PAN_IGNORE_CMD = BNEP_IGNORE_CMD, /* To ignore the rcvd command */ + PAN_TX_FLOW_ON = BNEP_TX_FLOW_ON, /* tx data flow enabled */ + PAN_TX_FLOW_OFF = BNEP_TX_FLOW_OFF, /* tx data flow disabled */ + PAN_FAILURE = 19, /* Failure */ + PAN_HOTSPOT_DISABLED = 20, /* Hotspot disabled */ } tPAN_RESULT; inline const std::string pan_result_text(const tPAN_RESULT& result) { @@ -105,7 +98,7 @@ inline const std::string pan_result_text(const tPAN_RESULT& result) { CASE_RETURN_TEXT(PAN_DISCONNECTED); CASE_RETURN_TEXT(PAN_CONN_FAILED); CASE_RETURN_TEXT(PAN_NO_RESOURCES); - CASE_RETURN_TEXT(PAN_MTU_EXCEDED); + CASE_RETURN_TEXT(PAN_MTU_EXCEEDED); CASE_RETURN_TEXT(PAN_INVALID_OFFSET); CASE_RETURN_TEXT(PAN_CONN_FAILED_CFG); CASE_RETURN_TEXT(PAN_INVALID_SRC_ROLE); @@ -134,16 +127,15 @@ inline const std::string pan_result_text(const tPAN_RESULT& result) { /* This is call back function used to report connection status * to the application. The second parameter true means * to create the bridge and false means to remove it. -*/ -typedef void(tPAN_CONN_STATE_CB)(uint16_t handle, const RawAddress& bd_addr, - tPAN_RESULT state, bool is_role_change, - uint8_t src_role, uint8_t dst_role); + */ +typedef void(tPAN_CONN_STATE_CB)(uint16_t handle, const RawAddress& bd_addr, tPAN_RESULT state, + bool is_role_change, uint8_t src_role, uint8_t dst_role); /* This is call back function used to create bridge for the * Connected device. The parameter "state" indicates * whether to create the bridge or remove it. true means * to create the bridge and false means to remove it. -*/ + */ typedef void(tPAN_BRIDGE_REQ_CB)(const RawAddress& bd_addr, bool state); /* Data received indication callback prototype. Parameters are @@ -156,10 +148,9 @@ typedef void(tPAN_BRIDGE_REQ_CB)(const RawAddress& bd_addr, bool state); * Flag used to indicate to forward on LAN * false - Use it for internal stack * true - Send it across the ethernet as well -*/ -typedef void(tPAN_DATA_IND_CB)(uint16_t handle, const RawAddress& src, - const RawAddress& dst, uint16_t protocol, - uint8_t* p_data, uint16_t len, bool ext, + */ +typedef void(tPAN_DATA_IND_CB)(uint16_t handle, const RawAddress& src, const RawAddress& dst, + uint16_t protocol, uint8_t* p_data, uint16_t len, bool ext, bool forward); /* Data buffer received indication callback prototype. Parameters are @@ -171,15 +162,14 @@ typedef void(tPAN_DATA_IND_CB)(uint16_t handle, const RawAddress& src, * Flag used to indicate to forward on LAN * false - Use it for internal stack * true - Send it across the ethernet as well -*/ -typedef void(tPAN_DATA_BUF_IND_CB)(uint16_t handle, const RawAddress& src, - const RawAddress& dst, uint16_t protocol, - BT_HDR* p_buf, bool ext, bool forward); + */ +typedef void(tPAN_DATA_BUF_IND_CB)(uint16_t handle, const RawAddress& src, const RawAddress& dst, + uint16_t protocol, BT_HDR* p_buf, bool ext, bool forward); /* Flow control callback for TX data. Parameters are * Handle to the connection * Event flow status -*/ + */ typedef void(tPAN_TX_DATA_FLOW_CB)(uint16_t handle, tPAN_RESULT event); /* Filters received indication callback prototype. Parameters are @@ -194,10 +184,9 @@ typedef void(tPAN_TX_DATA_FLOW_CB)(uint16_t handle, tPAN_RESULT event); * They will be present in big endian order. First * two bytes will be starting of the first range and * next two bytes will be ending of the range. -*/ -typedef void(tPAN_FILTER_IND_CB)(uint16_t handle, bool indication, - tPAN_RESULT result, uint16_t num_filters, - uint8_t* p_filters); + */ +typedef void(tPAN_FILTER_IND_CB)(uint16_t handle, bool indication, tPAN_RESULT result, + uint16_t num_filters, uint8_t* p_filters); /* Multicast Filters received indication callback prototype. Parameters are * Handle to the connection @@ -210,24 +199,20 @@ typedef void(tPAN_FILTER_IND_CB)(uint16_t handle, bool indication, * of start of the range and end of the range. * First six bytes will be starting of the first range and * next six bytes will be ending of the range. -*/ -typedef void(tPAN_MFILTER_IND_CB)(uint16_t handle, bool indication, - tPAN_RESULT result, uint16_t num_mfilters, - uint8_t* p_mfilters); + */ +typedef void(tPAN_MFILTER_IND_CB)(uint16_t handle, bool indication, tPAN_RESULT result, + uint16_t num_mfilters, uint8_t* p_mfilters); /* This structure is used to register with PAN profile * It is passed as a parameter to PAN_Register call. -*/ + */ typedef struct { - tPAN_CONN_STATE_CB* pan_conn_state_cb; /* Connection state callback */ - tPAN_BRIDGE_REQ_CB* pan_bridge_req_cb; /* Bridge request callback */ - tPAN_DATA_IND_CB* pan_data_ind_cb; /* Data indication callback */ - tPAN_DATA_BUF_IND_CB* - pan_data_buf_ind_cb; /* Data buffer indication callback */ - tPAN_FILTER_IND_CB* - pan_pfilt_ind_cb; /* protocol filter indication callback */ - tPAN_MFILTER_IND_CB* - pan_mfilt_ind_cb; /* multicast filter indication callback */ + tPAN_CONN_STATE_CB* pan_conn_state_cb; /* Connection state callback */ + tPAN_BRIDGE_REQ_CB* pan_bridge_req_cb; /* Bridge request callback */ + tPAN_DATA_IND_CB* pan_data_ind_cb; /* Data indication callback */ + tPAN_DATA_BUF_IND_CB* pan_data_buf_ind_cb; /* Data buffer indication callback */ + tPAN_FILTER_IND_CB* pan_pfilt_ind_cb; /* protocol filter indication callback */ + tPAN_MFILTER_IND_CB* pan_mfilt_ind_cb; /* multicast filter indication callback */ tPAN_TX_DATA_FLOW_CB* pan_tx_data_flow_cb; /* data flow callback */ } tPAN_REGISTER; @@ -289,8 +274,7 @@ void PAN_Deregister(void); * PAN_FAILURE - if the role is not valid * ******************************************************************************/ -tPAN_RESULT PAN_SetRole(uint8_t role, std::string user_name, - std::string nap_name); +tPAN_RESULT PAN_SetRole(uint8_t role, std::string user_name, std::string nap_name); /******************************************************************************* * @@ -307,15 +291,15 @@ tPAN_RESULT PAN_SetRole(uint8_t role, std::string user_name, * *handle - Pointer for returning Handle to the connection * * Returns PAN_SUCCESS - if the connection is initiated successfully - * PAN_NO_RESOURCES - resources are not sufficent + * PAN_NO_RESOURCES - resources are not sufficient * PAN_FAILURE - if the connection cannot be initiated * this can be because of the combination of * src and dst roles may not be valid or * allowed at that point of time * ******************************************************************************/ -tPAN_RESULT PAN_Connect(const RawAddress& rem_bda, tPAN_ROLE src_role, - tPAN_ROLE dst_role, uint16_t* handle); +tPAN_RESULT PAN_Connect(const RawAddress& rem_bda, tPAN_ROLE src_role, tPAN_ROLE dst_role, + uint16_t* handle); /******************************************************************************* * @@ -355,9 +339,8 @@ tPAN_RESULT PAN_Disconnect(uint16_t handle); * there is an error in sending data * ******************************************************************************/ -tPAN_RESULT PAN_Write(uint16_t handle, const RawAddress& dst, - const RawAddress& src, uint16_t protocol, uint8_t* p_data, - uint16_t len, bool ext); +tPAN_RESULT PAN_Write(uint16_t handle, const RawAddress& dst, const RawAddress& src, + uint16_t protocol, uint8_t* p_data, uint16_t len, bool ext); /******************************************************************************* * @@ -381,9 +364,8 @@ tPAN_RESULT PAN_Write(uint16_t handle, const RawAddress& dst, * there is an error in sending data * ******************************************************************************/ -tPAN_RESULT PAN_WriteBuf(uint16_t handle, const RawAddress& dst, - const RawAddress& src, uint16_t protocol, - BT_HDR* p_buf, bool ext); +tPAN_RESULT PAN_WriteBuf(uint16_t handle, const RawAddress& dst, const RawAddress& src, + uint16_t protocol, BT_HDR* p_buf, bool ext); /******************************************************************************* * @@ -401,8 +383,7 @@ tPAN_RESULT PAN_WriteBuf(uint16_t handle, const RawAddress& dst, * PAN_FAILURE if connection not found or error in setting * ******************************************************************************/ -tPAN_RESULT PAN_SetProtocolFilters(uint16_t handle, uint16_t num_filters, - uint16_t* p_start_array, +tPAN_RESULT PAN_SetProtocolFilters(uint16_t handle, uint16_t num_filters, uint16_t* p_start_array, uint16_t* p_end_array); /******************************************************************************* @@ -424,8 +405,7 @@ tPAN_RESULT PAN_SetProtocolFilters(uint16_t handle, uint16_t num_filters, * ******************************************************************************/ tPAN_RESULT PAN_SetMulticastFilters(uint16_t handle, uint16_t num_mcast_filters, - uint8_t* p_start_array, - uint8_t* p_end_array); + uint8_t* p_start_array, uint8_t* p_end_array); /******************************************************************************* * diff --git a/system/stack/include/port_api.h b/system/stack/include/port_api.h index 682d755d241..5f37d7f49d6 100644 --- a/system/stack/include/port_api.h +++ b/system/stack/include/port_api.h @@ -37,7 +37,7 @@ /* * Define port settings structure send from the application in the * set settings request, or to the application in the set settings indication. -*/ + */ typedef struct { #define PORT_BAUD_RATE_9600 0x03 @@ -76,21 +76,19 @@ typedef struct { /* * Define the callback function prototypes. Parameters are specific * to each event and are described bellow -*/ -typedef int(tPORT_DATA_CALLBACK)(uint16_t port_handle, void* p_data, - uint16_t len); + */ +typedef int(tPORT_DATA_CALLBACK)(uint16_t port_handle, void* p_data, uint16_t len); #define DATA_CO_CALLBACK_TYPE_INCOMING 1 #define DATA_CO_CALLBACK_TYPE_OUTGOING_SIZE 2 #define DATA_CO_CALLBACK_TYPE_OUTGOING 3 -typedef int(tPORT_DATA_CO_CALLBACK)(uint16_t port_handle, uint8_t* p_buf, - uint16_t len, int type); +typedef int(tPORT_DATA_CO_CALLBACK)(uint16_t port_handle, uint8_t* p_buf, uint16_t len, int type); typedef void(tPORT_CALLBACK)(uint32_t code, uint16_t port_handle); /* * Define events that registered application can receive in the callback -*/ + */ #define PORT_EV_RXCHAR 0x00000001 /* Any Character received */ #define PORT_EV_RXFLAG 0x00000002 /* Received certain character */ @@ -118,7 +116,7 @@ typedef void(tPORT_CALLBACK)(uint32_t code, uint16_t port_handle); /* * Define port result codes -*/ + */ typedef enum { PORT_SUCCESS = 0, PORT_UNKNOWN_ERROR = 1, @@ -187,8 +185,7 @@ template <> struct formatter : enum_formatter {}; } // namespace fmt -typedef void(tPORT_MGMT_CALLBACK)(const tPORT_RESULT code, - uint16_t port_handle); +typedef void(tPORT_MGMT_CALLBACK)(const tPORT_RESULT code, uint16_t port_handle); /***************************************************************************** * External Function Declarations @@ -225,10 +222,11 @@ typedef void(tPORT_MGMT_CALLBACK)(const tPORT_RESULT code, * (scn * 2 + 1) dlci. * ******************************************************************************/ -[[nodiscard]] int RFCOMM_CreateConnectionWithSecurity( - uint16_t uuid, uint8_t scn, bool is_server, uint16_t mtu, - const RawAddress& bd_addr, uint16_t* p_handle, - tPORT_MGMT_CALLBACK* p_mgmt_callback, uint16_t sec_mask); +[[nodiscard]] int RFCOMM_CreateConnectionWithSecurity(uint16_t uuid, uint8_t scn, bool is_server, + uint16_t mtu, const RawAddress& bd_addr, + uint16_t* p_handle, + tPORT_MGMT_CALLBACK* p_mgmt_callback, + uint16_t sec_mask); /******************************************************************************* * @@ -250,10 +248,10 @@ typedef void(tPORT_MGMT_CALLBACK)(const tPORT_RESULT code, * frames * ******************************************************************************/ -[[nodiscard]] int RFCOMM_ControlReqFromBTSOCK( - uint8_t dlci, const RawAddress& bd_addr, uint8_t modem_signal, - uint8_t break_signal, uint8_t discard_buffers, uint8_t break_signal_seq, - bool fc); +[[nodiscard]] int RFCOMM_ControlReqFromBTSOCK(uint8_t dlci, const RawAddress& bd_addr, + uint8_t modem_signal, uint8_t break_signal, + uint8_t discard_buffers, uint8_t break_signal_seq, + bool fc); /******************************************************************************* * @@ -291,8 +289,7 @@ typedef void(tPORT_MGMT_CALLBACK)(const tPORT_RESULT code, * specified in the mask occurs. * ******************************************************************************/ -[[nodiscard]] int PORT_SetEventMaskAndCallback(uint16_t port_handle, - uint32_t mask, +[[nodiscard]] int PORT_SetEventMaskAndCallback(uint16_t port_handle, uint32_t mask, tPORT_CALLBACK* p_port_cb); /******************************************************************************* @@ -307,8 +304,7 @@ typedef void(tPORT_MGMT_CALLBACK)(const tPORT_RESULT code, ******************************************************************************/ [[nodiscard]] int PORT_ClearKeepHandleFlag(uint16_t port_handle); -[[nodiscard]] int PORT_SetDataCOCallback(uint16_t port_handle, - tPORT_DATA_CO_CALLBACK* p_port_cb); +[[nodiscard]] int PORT_SetDataCOCallback(uint16_t port_handle, tPORT_DATA_CO_CALLBACK* p_port_cb); /******************************************************************************* * * Function PORT_CheckConnection @@ -321,8 +317,7 @@ typedef void(tPORT_MGMT_CALLBACK)(const tPORT_RESULT code, * p_lcid - OUT L2CAP's LCID * ******************************************************************************/ -[[nodiscard]] int PORT_CheckConnection(uint16_t handle, RawAddress* bd_addr, - uint16_t* p_lcid); +[[nodiscard]] int PORT_CheckConnection(uint16_t handle, RawAddress* bd_addr, uint16_t* p_lcid); /******************************************************************************* * @@ -387,20 +382,17 @@ typedef void(tPORT_MGMT_CALLBACK)(const tPORT_RESULT code, /* * Define default initial local modem signals state after connection established -*/ -#define PORT_OBEX_DEFAULT_SIGNAL_STATE \ - (PORT_DTRDSR_ON | PORT_CTSRTS_ON | PORT_DCD_ON) -#define PORT_SPP_DEFAULT_SIGNAL_STATE \ - (PORT_DTRDSR_ON | PORT_CTSRTS_ON | PORT_DCD_ON) -#define PORT_PPP_DEFAULT_SIGNAL_STATE \ - (PORT_DTRDSR_ON | PORT_CTSRTS_ON | PORT_DCD_ON) + */ +#define PORT_OBEX_DEFAULT_SIGNAL_STATE (PORT_DTRDSR_ON | PORT_CTSRTS_ON | PORT_DCD_ON) +#define PORT_SPP_DEFAULT_SIGNAL_STATE (PORT_DTRDSR_ON | PORT_CTSRTS_ON | PORT_DCD_ON) +#define PORT_PPP_DEFAULT_SIGNAL_STATE (PORT_DTRDSR_ON | PORT_CTSRTS_ON | PORT_DCD_ON) #define PORT_DUN_DEFAULT_SIGNAL_STATE (PORT_DTRDSR_ON | PORT_CTSRTS_ON) -#define PORT_ERR_BREAK 0x01 /* Break condition occured on the peer device */ +#define PORT_ERR_BREAK 0x01 /* Break condition occurred on the peer device */ #define PORT_ERR_OVERRUN 0x02 /* Overrun is reported by peer device */ #define PORT_ERR_FRAME 0x04 /* Framing error reported by peer device */ -#define PORT_ERR_RXOVER 0x08 /* Input queue overflow occured */ -#define PORT_ERR_TXFULL 0x10 /* Output queue overflow occured */ +#define PORT_ERR_RXOVER 0x08 /* Input queue overflow occurred */ +#define PORT_ERR_TXFULL 0x10 /* Output queue overflow occurred */ /******************************************************************************* * @@ -416,8 +408,7 @@ typedef void(tPORT_MGMT_CALLBACK)(const tPORT_RESULT code, * p_len - Byte count received * ******************************************************************************/ -[[nodiscard]] int PORT_ReadData(uint16_t handle, char* p_data, uint16_t max_len, - uint16_t* p_len); +[[nodiscard]] int PORT_ReadData(uint16_t handle, char* p_data, uint16_t max_len, uint16_t* p_len); /******************************************************************************* * @@ -432,8 +423,8 @@ typedef void(tPORT_MGMT_CALLBACK)(const tPORT_RESULT code, * p_len - Bytes written * ******************************************************************************/ -[[nodiscard]] int PORT_WriteData(uint16_t handle, const char* p_data, - uint16_t max_len, uint16_t* p_len); +[[nodiscard]] int PORT_WriteData(uint16_t handle, const char* p_data, uint16_t max_len, + uint16_t* p_len); /******************************************************************************* * diff --git a/system/stack/include/profiles_api.h b/system/stack/include/profiles_api.h index f533deb6dc7..47b3c9d463a 100644 --- a/system/stack/include/profiles_api.h +++ b/system/stack/include/profiles_api.h @@ -25,6 +25,6 @@ #define BT_PASS 0 /* Used for general successful function returns */ /*** Port entity passes back 8 bit errors; will use upper byte offset ***/ -#define GAP_ERR_GRP 0x0100 /* base offset for GAP profile */ +#define GAP_ERR_GRP 0x0100 /* base offset for GAP profile */ #endif /* PROFILES_API_H */ diff --git a/system/stack/include/rfcdefs.h b/system/stack/include/rfcdefs.h index e3e287b2d94..7c5249c6ecc 100644 --- a/system/stack/include/rfcdefs.h +++ b/system/stack/include/rfcdefs.h @@ -31,24 +31,23 @@ /* * If nothing is negotiated MTU should be 127 -*/ + */ #define RFCOMM_DEFAULT_MTU 127 /* * Define used by RFCOMM TS frame types -*/ + */ #define RFCOMM_SABME 0x2F // Start Asynchronous Balanced Mode (startup command) -#define RFCOMM_UA 0x63 // Unnumbered Acknowledgement (response when connected) -#define RFCOMM_DM \ - 0x0F // Disconnected Mode (response to a command when disconnected) -#define RFCOMM_DISC 0x43 // Disconnect (disconnect command) -#define RFCOMM_UIH 0xEF // Unnumbered Information with Header check +#define RFCOMM_UA 0x63 // Unnumbered Acknowledgement (response when connected) +#define RFCOMM_DM 0x0F // Disconnected Mode (response to a command when disconnected) +#define RFCOMM_DISC 0x43 // Disconnect (disconnect command) +#define RFCOMM_UIH 0xEF // Unnumbered Information with Header check /* * Defenitions for the TS control frames -*/ + */ #define RFCOMM_CTRL_FRAME_LEN 3 -#define RFCOMM_MIN_OFFSET 5 /* ctrl 2 , len 1 or 2 bytes, credit 1 byte */ +#define RFCOMM_MIN_OFFSET 5 /* ctrl 2 , len 1 or 2 bytes, credit 1 byte */ #define RFCOMM_DATA_OVERHEAD (RFCOMM_MIN_OFFSET + 1) /* add 1 for checksum */ #define RFCOMM_EA 1 @@ -71,10 +70,11 @@ #define RFCOMM_PARSE_CTRL_FIELD(ea, cr, dlci, p_data) \ { \ - (ea) = *(p_data)&RFCOMM_EA; \ - (cr) = (*(p_data)&RFCOMM_CR_MASK) >> RFCOMM_SHIFT_CR; \ + (ea) = *(p_data) & RFCOMM_EA; \ + (cr) = (*(p_data) & RFCOMM_CR_MASK) >> RFCOMM_SHIFT_CR; \ (dlci) = *(p_data)++ >> RFCOMM_SHIFT_DLCI; \ - if (!(ea)) (dlci) += *(p_data)++ << RFCOMM_SHIFT_DLCI2; \ + if (!(ea)) \ + (dlci) += *(p_data)++ << RFCOMM_SHIFT_DLCI2; \ } #define RFCOMM_FORMAT_CTRL_FIELD(p_data, ea, cr, dlci) \ @@ -92,11 +92,9 @@ (pf) = (*(p_data)++ & RFCOMM_PF_MASK) >> RFCOMM_PF_OFFSET; \ } -#define RFCOMM_FRAME_IS_CMD(initiator, cr) \ - (((initiator) && !(cr)) || (!(initiator) && (cr))) +#define RFCOMM_FRAME_IS_CMD(initiator, cr) (((initiator) && !(cr)) || (!(initiator) && (cr))) -#define RFCOMM_FRAME_IS_RSP(initiator, cr) \ - (((initiator) && (cr)) || (!(initiator) && !(cr))) +#define RFCOMM_FRAME_IS_RSP(initiator, cr) (((initiator) && (cr)) || (!(initiator) && !(cr))) #define RFCOMM_CR(initiator, is_command) \ ((((initiator) && (is_command)) || (!(initiator) && !(is_command))) << 1) @@ -105,8 +103,7 @@ #define RFCOMM_MAX_DLCI 61 -#define RFCOMM_VALID_DLCI(dlci) \ - (((dlci) == 0) || (((dlci) >= 2) && ((dlci) <= RFCOMM_MAX_DLCI))) +#define RFCOMM_VALID_DLCI(dlci) (((dlci) == 0) || (((dlci) >= 2) && ((dlci) <= RFCOMM_MAX_DLCI))) /* Port Negotiation (PN) */ #define RFCOMM_PN_DLCI_MASK 0x3F @@ -210,7 +207,7 @@ /* * Define RFCOMM Multiplexer message types -*/ + */ #define RFCOMM_MX_PN 0x80 #define RFCOMM_MX_PN_LEN 8 diff --git a/system/stack/include/sco_hci_link_interface.h b/system/stack/include/sco_hci_link_interface.h index 25bd332724b..f74bef4262f 100644 --- a/system/stack/include/sco_hci_link_interface.h +++ b/system/stack/include/sco_hci_link_interface.h @@ -27,17 +27,12 @@ struct tBTM_ESCO_DATA; void btm_sco_chk_pend_unpark(tHCI_STATUS hci_status, uint16_t hci_handle); -void btm_sco_conn_req(const RawAddress& bda, const DEV_CLASS& dev_class, - uint8_t link_type); -void btm_sco_connected(const RawAddress& bda, uint16_t hci_handle, - tBTM_ESCO_DATA* p_esco_data); -void btm_sco_connection_failed(tHCI_STATUS hci_status, const RawAddress& bda, - uint16_t hci_handle, +void btm_sco_conn_req(const RawAddress& bda, const DEV_CLASS& dev_class, uint8_t link_type); +void btm_sco_connected(const RawAddress& bda, uint16_t hci_handle, tBTM_ESCO_DATA* p_esco_data); +void btm_sco_connection_failed(tHCI_STATUS hci_status, const RawAddress& bda, uint16_t hci_handle, tBTM_ESCO_DATA* p_esco_data); bool btm_sco_removed(uint16_t hci_handle, tHCI_REASON reason); void btm_sco_on_disconnected(uint16_t hci_handle, tHCI_REASON reason); -void btm_sco_on_esco_connect_request(const RawAddress&, - const bluetooth::hci::ClassOfDevice&); -void btm_sco_on_sco_connect_request(const RawAddress&, - const bluetooth::hci::ClassOfDevice&); +void btm_sco_on_esco_connect_request(const RawAddress&, const bluetooth::hci::ClassOfDevice&); +void btm_sco_on_sco_connect_request(const RawAddress&, const bluetooth::hci::ClassOfDevice&); diff --git a/system/stack/include/sdp_api.h b/system/stack/include/sdp_api.h index f857f1bed34..6b9ffa01886 100644 --- a/system/stack/include/sdp_api.h +++ b/system/stack/include/sdp_api.h @@ -58,9 +58,8 @@ struct tSdpApi { Returns true if successful, false if one or more parameters are bad ******************************************************************************/ - [[nodiscard]] bool (*SDP_InitDiscoveryDb)(tSDP_DISCOVERY_DB*, uint32_t, - uint16_t, const bluetooth::Uuid*, - uint16_t, const uint16_t*); + [[nodiscard]] bool (*SDP_InitDiscoveryDb)(tSDP_DISCOVERY_DB*, uint32_t, uint16_t, + const bluetooth::Uuid*, uint16_t, const uint16_t*); /******************************************************************************* @@ -90,8 +89,7 @@ struct tSdpApi { Returns true if discovery started, false if failed. ******************************************************************************/ - [[nodiscard]] bool (*SDP_ServiceSearchRequest)(const RawAddress&, - tSDP_DISCOVERY_DB*, + [[nodiscard]] bool (*SDP_ServiceSearchRequest)(const RawAddress&, tSDP_DISCOVERY_DB*, tSDP_DISC_CMPL_CB*); /******************************************************************************* @@ -112,8 +110,7 @@ struct tSdpApi { Returns true if discovery started, false if failed. ******************************************************************************/ - [[nodiscard]] bool (*SDP_ServiceSearchAttributeRequest)(const RawAddress&, - tSDP_DISCOVERY_DB*, + [[nodiscard]] bool (*SDP_ServiceSearchAttributeRequest)(const RawAddress&, tSDP_DISCOVERY_DB*, tSDP_DISC_CMPL_CB*); /******************************************************************************* @@ -137,8 +134,8 @@ struct tSdpApi { ******************************************************************************/ [[nodiscard]] bool (*SDP_ServiceSearchAttributeRequest2)( - const RawAddress&, tSDP_DISCOVERY_DB*, - base::RepeatingCallback complete_callback); + const RawAddress&, tSDP_DISCOVERY_DB*, + base::RepeatingCallback complete_callback); } service; struct { @@ -159,8 +156,8 @@ struct tSdpApi { Returns Pointer to record containing service class, or NULL ******************************************************************************/ - [[nodiscard]] tSDP_DISC_REC* (*SDP_FindServiceInDb)( - const tSDP_DISCOVERY_DB*, uint16_t, tSDP_DISC_REC*); + [[nodiscard]] tSDP_DISC_REC* (*SDP_FindServiceInDb)(const tSDP_DISCOVERY_DB*, uint16_t, + tSDP_DISC_REC*); /******************************************************************************* @@ -183,8 +180,8 @@ struct tSdpApi { Returns Pointer to record containing service class, or NULL ******************************************************************************/ - [[nodiscard]] tSDP_DISC_REC* (*SDP_FindServiceUUIDInDb)( - const tSDP_DISCOVERY_DB*, const bluetooth::Uuid&, tSDP_DISC_REC*); + [[nodiscard]] tSDP_DISC_REC* (*SDP_FindServiceUUIDInDb)(const tSDP_DISCOVERY_DB*, + const bluetooth::Uuid&, tSDP_DISC_REC*); /******************************************************************************* @@ -202,8 +199,8 @@ struct tSdpApi { Returns Pointer to record containing service class, or NULL ******************************************************************************/ - [[nodiscard]] tSDP_DISC_REC* (*SDP_FindServiceInDb_128bit)( - const tSDP_DISCOVERY_DB*, tSDP_DISC_REC*); + [[nodiscard]] tSDP_DISC_REC* (*SDP_FindServiceInDb_128bit)(const tSDP_DISCOVERY_DB*, + tSDP_DISC_REC*); } db; struct { @@ -222,8 +219,7 @@ struct tSdpApi { Returns Pointer to matching attribute entry, or NULL ******************************************************************************/ - [[nodiscard]] tSDP_DISC_ATTR* (*SDP_FindAttributeInRec)( - const tSDP_DISC_REC*, uint16_t); + [[nodiscard]] tSDP_DISC_ATTR* (*SDP_FindAttributeInRec)(const tSDP_DISC_REC*, uint16_t); /******************************************************************************* @@ -238,8 +234,7 @@ struct tSdpApi { Returns true if found, otherwise false. ******************************************************************************/ - [[nodiscard]] bool (*SDP_FindServiceUUIDInRec_128bit)(const tSDP_DISC_REC*, - bluetooth::Uuid*); + [[nodiscard]] bool (*SDP_FindServiceUUIDInRec_128bit)(const tSDP_DISC_REC*, bluetooth::Uuid*); /******************************************************************************* @@ -256,8 +251,7 @@ struct tSdpApi { If found, the passed protocol list element is filled in. ******************************************************************************/ - [[nodiscard]] bool (*SDP_FindProtocolListElemInRec)(const tSDP_DISC_REC*, - uint16_t, + [[nodiscard]] bool (*SDP_FindProtocolListElemInRec)(const tSDP_DISC_REC*, uint16_t, tSDP_PROTOCOL_ELEM*); /******************************************************************************* @@ -276,8 +270,7 @@ struct tSdpApi { Returns true if found, false if not ******************************************************************************/ - [[nodiscard]] bool (*SDP_FindProfileVersionInRec)(const tSDP_DISC_REC*, - uint16_t, uint16_t*); + [[nodiscard]] bool (*SDP_FindProfileVersionInRec)(const tSDP_DISC_REC*, uint16_t, uint16_t*); /******************************************************************************* @@ -305,7 +298,7 @@ struct tSdpApi { Description This function is called to create a record in the database. This would be through the SDP database - maintenance API. The record is created empty, teh + maintenance API. The record is created empty, the application should then call "add_attribute" *to add the record's attributes. @@ -350,9 +343,8 @@ struct tSdpApi { Returns true if added OK, else false ******************************************************************************/ - [[nodiscard]] bool (*SDP_AddAttribute)(uint32_t handle, uint16_t attr_id, - uint8_t attr_type, uint32_t attr_len, - uint8_t* p_val); + [[nodiscard]] bool (*SDP_AddAttribute)(uint32_t handle, uint16_t attr_id, uint8_t attr_type, + uint32_t attr_len, uint8_t* p_val); /******************************************************************************* @@ -375,9 +367,8 @@ struct tSdpApi { Returns true if added OK, else false ******************************************************************************/ - [[nodiscard]] bool (*SDP_AddSequence)(uint32_t handle, uint16_t attr_id, - uint16_t num_elem, uint8_t type[], - uint8_t len[], uint8_t* p_val[]); + [[nodiscard]] bool (*SDP_AddSequence)(uint32_t handle, uint16_t attr_id, uint16_t num_elem, + uint8_t type[], uint8_t len[], uint8_t* p_val[]); /******************************************************************************* @@ -396,8 +387,7 @@ struct tSdpApi { Returns true if added OK, else false ******************************************************************************/ - [[nodiscard]] bool (*SDP_AddUuidSequence)(uint32_t handle, uint16_t attr_id, - uint16_t num_uuids, + [[nodiscard]] bool (*SDP_AddUuidSequence)(uint32_t handle, uint16_t attr_id, uint16_t num_uuids, uint16_t* p_uuids); /******************************************************************************* @@ -416,8 +406,7 @@ struct tSdpApi { Returns true if added OK, else false ******************************************************************************/ - [[nodiscard]] bool (*SDP_AddProtocolList)(uint32_t handle, - uint16_t num_elem, + [[nodiscard]] bool (*SDP_AddProtocolList)(uint32_t handle, uint16_t num_elem, tSDP_PROTOCOL_ELEM* p_elem_list); /******************************************************************************* @@ -436,8 +425,8 @@ struct tSdpApi { Returns true if added OK, else false ******************************************************************************/ - [[nodiscard]] bool (*SDP_AddAdditionProtoLists)( - uint32_t handle, uint16_t num_elem, tSDP_PROTO_LIST_ELEM* p_proto_list); + [[nodiscard]] bool (*SDP_AddAdditionProtoLists)(uint32_t handle, uint16_t num_elem, + tSDP_PROTO_LIST_ELEM* p_proto_list); /******************************************************************************* @@ -455,8 +444,7 @@ struct tSdpApi { Returns true if added OK, else false ******************************************************************************/ - [[nodiscard]] bool (*SDP_AddProfileDescriptorList)(uint32_t handle, - uint16_t profile_uuid, + [[nodiscard]] bool (*SDP_AddProfileDescriptorList)(uint32_t handle, uint16_t profile_uuid, uint16_t version); /******************************************************************************* @@ -476,10 +464,8 @@ struct tSdpApi { Returns true if added OK, else false ******************************************************************************/ - [[nodiscard]] bool (*SDP_AddLanguageBaseAttrIDList)(uint32_t handle, - uint16_t lang, - uint16_t char_enc, - uint16_t base_id); + [[nodiscard]] bool (*SDP_AddLanguageBaseAttrIDList)(uint32_t handle, uint16_t lang, + uint16_t char_enc, uint16_t base_id); /******************************************************************************* @@ -497,8 +483,7 @@ struct tSdpApi { Returns true if added OK, else false ******************************************************************************/ - [[nodiscard]] bool (*SDP_AddServiceClassIdList)(uint32_t handle, - uint16_t num_services, + [[nodiscard]] bool (*SDP_AddServiceClassIdList)(uint32_t handle, uint16_t num_services, uint16_t* p_service_uuids); } handle; @@ -519,8 +504,8 @@ struct tSdpApi { error ******************************************************************************/ - [[nodiscard]] uint16_t (*SDP_SetLocalDiRecord)( - const tSDP_DI_RECORD* device_info, uint32_t* p_handle); + [[nodiscard]] uint16_t (*SDP_SetLocalDiRecord)(const tSDP_DI_RECORD* device_info, + uint32_t* p_handle); /******************************************************************************* @@ -540,8 +525,7 @@ struct tSdpApi { ******************************************************************************/ [[nodiscard]] tSDP_STATUS (*SDP_DiDiscover)(const RawAddress& remote_device, - tSDP_DISCOVERY_DB* p_db, - uint32_t len, + tSDP_DISCOVERY_DB* p_db, uint32_t len, tSDP_DISC_CMPL_CB* p_cb); /******************************************************************************* @@ -586,8 +570,7 @@ const struct tSdpApi* get_legacy_stack_sdp_api(); struct tLegacyStackSdbCallback { void(tSDP_DISC_CMPL_CB)(const RawAddress& bd_addr, tSDP_RESULT result); - void(tSDP_DISC_CMPL_CB2)(const RawAddress& bd_addr, tSDP_RESULT result, - const void* user_data); + void(tSDP_DISC_CMPL_CB2)(const RawAddress& bd_addr, tSDP_RESULT result, const void* user_data); }; } // namespace sdp diff --git a/system/stack/include/sdpdefs.h b/system/stack/include/sdpdefs.h index a0dba34ede3..600bd44fb45 100644 --- a/system/stack/include/sdpdefs.h +++ b/system/stack/include/sdpdefs.h @@ -32,7 +32,7 @@ #include "macros.h" /* Define the service attribute IDs. -*/ + */ #define ATTR_ID_SERVICE_RECORD_HDL 0x0000 #define ATTR_ID_SERVICE_CLASS_ID_LIST 0x0001 #define ATTR_ID_SERVICE_RECORD_STATE 0x0002 @@ -51,7 +51,7 @@ #define ATTR_ID_PROVIDER_NAME (LANGUAGE_BASE_ID + 0x0002) /* Device Identification (DI) -*/ + */ #define ATTR_ID_SPECIFICATION_ID 0x0200 #define ATTR_ID_VENDOR_ID 0x0201 #define ATTR_ID_PRODUCT_ID 0x0202 @@ -69,7 +69,7 @@ #define ATTR_ID_FAX_CLASS_1_SUPPORT 0x0302 #define ATTR_ID_REMOTE_AUDIO_VOLUME_CONTROL 0x0302 #define ATTR_ID_SUPPORTED_FORMATS_LIST 0x0303 -#define ATTR_ID_SUPPORTED_FEATURES 0x0311 /* HFP, BIP */ +#define ATTR_ID_SUPPORTED_FEATURES 0x0311 /* HFP, BIP */ #define ATTR_ID_SUPPORTED_REPOSITORIES 0x0314 /* Phone book access Profile */ #define ATTR_ID_MAS_INSTANCE_ID 0x0315 /* MAP profile */ #define ATTR_ID_SUPPORTED_MSG_TYPE 0x0316 /* MAP profile */ @@ -127,7 +127,7 @@ inline std::string sdp_attr_id_text(const unsigned& id) { } /* Define all the 'Descriptor Type' values. -*/ + */ enum : unsigned { NIL_DESC_TYPE = 0, UINT_DESC_TYPE = 1, @@ -157,7 +157,7 @@ inline std::string sdp_attr_type_text(const unsigned& type) { } /* Define all the "Descriptor Size" values. -*/ + */ enum : unsigned { SIZE_ONE_BYTE = 0, SIZE_TWO_BYTES = 1, diff --git a/system/stack/include/sec_hci_link_interface.h b/system/stack/include/sec_hci_link_interface.h index 4b07e84f21e..eb142adfa40 100644 --- a/system/stack/include/sec_hci_link_interface.h +++ b/system/stack/include/sec_hci_link_interface.h @@ -28,26 +28,20 @@ void btm_create_conn_cancel_complete(uint8_t status, const RawAddress bd_addr); void btm_io_capabilities_req(RawAddress p); void btm_io_capabilities_rsp(const tBTM_SP_IO_RSP evt_data); -void btm_proc_sp_req_evt(tBTM_SP_EVT event, const RawAddress bda, - uint32_t value); +void btm_proc_sp_req_evt(tBTM_SP_EVT event, const RawAddress bda, uint32_t value); void btm_read_local_oob_complete(const tBTM_SP_LOC_OOB evt_data); void btm_rem_oob_req(const RawAddress bd_addr); void btm_sec_auth_complete(uint16_t handle, tHCI_STATUS status); void btm_sec_disconnected(uint16_t handle, tHCI_STATUS reason, std::string); -void btm_sec_encrypt_change(uint16_t handle, tHCI_STATUS status, - uint8_t encr_enable); -void btm_sec_encryption_change_evt(uint16_t handle, tHCI_STATUS status, - uint8_t encr_enable); -void btm_sec_encryption_key_refresh_complete(uint16_t handle, - tHCI_STATUS status); -void btm_sec_link_key_notification(const RawAddress& p_bda, - const Octet16& link_key, uint8_t key_type); +void btm_sec_encrypt_change(uint16_t handle, tHCI_STATUS status, uint8_t encr_enable); +void btm_sec_encryption_change_evt(uint16_t handle, tHCI_STATUS status, uint8_t encr_enable); +void btm_sec_encryption_key_refresh_complete(uint16_t handle, tHCI_STATUS status); +void btm_sec_link_key_notification(const RawAddress& p_bda, const Octet16& link_key, + uint8_t key_type); void btm_sec_link_key_request(const RawAddress bda); void btm_sec_pin_code_request(const RawAddress p_bda); -void btm_sec_rmt_host_support_feat_evt(const RawAddress bd_addr, - uint8_t features_0); -void btm_sec_rmt_name_request_complete(const RawAddress* bd_addr, - const uint8_t* bd_name, +void btm_sec_rmt_host_support_feat_evt(const RawAddress bd_addr, uint8_t features_0); +void btm_sec_rmt_name_request_complete(const RawAddress* bd_addr, const uint8_t* bd_name, tHCI_STATUS status); void btm_sec_update_clock_offset(uint16_t handle, uint16_t clock_offset); void btm_simple_pair_complete(const RawAddress bd_addr, uint8_t status); diff --git a/system/stack/include/security_client_callbacks.h b/system/stack/include/security_client_callbacks.h index d082332cd1b..67190a769e8 100644 --- a/system/stack/include/security_client_callbacks.h +++ b/system/stack/include/security_client_callbacks.h @@ -41,26 +41,23 @@ typedef uint8_t(tBTM_AUTHORIZE_CALLBACK)(uint8_t service_id); * BD Name of remote * Flag indicating the minimum pin code length to be 16 digits */ -typedef uint8_t(tBTM_PIN_CALLBACK)(const RawAddress& bd_addr, - DEV_CLASS dev_class, const BD_NAME bd_name, - bool min_16_digit); +typedef uint8_t(tBTM_PIN_CALLBACK)(const RawAddress& bd_addr, DEV_CLASS dev_class, + const BD_NAME bd_name, bool min_16_digit); /* New Link Key for the connection. Parameters are * BD Address of remote * Link Key * Key Type: Combination, Local Unit, or Remote Unit */ -typedef uint8_t(tBTM_LINK_KEY_CALLBACK)(const RawAddress& bd_addr, - DEV_CLASS dev_class, BD_NAME bd_name, - const LinkKey& key, uint8_t key_type, +typedef uint8_t(tBTM_LINK_KEY_CALLBACK)(const RawAddress& bd_addr, DEV_CLASS dev_class, + BD_NAME bd_name, const LinkKey& key, uint8_t key_type, bool is_ctkd); /* Remote Name Resolved. Parameters are * BD Address of remote * BD Name of remote */ -typedef void(tBTM_RMT_NAME_CALLBACK)(const RawAddress& bd_addr, DEV_CLASS dc, - BD_NAME bd_name); +typedef void(tBTM_RMT_NAME_CALLBACK)(const RawAddress& bd_addr, DEV_CLASS dc, BD_NAME bd_name); /* Authentication complete for the connection. Parameters are * BD Address of remote @@ -68,9 +65,8 @@ typedef void(tBTM_RMT_NAME_CALLBACK)(const RawAddress& bd_addr, DEV_CLASS dc, * BD Name of remote * */ -typedef void(tBTM_AUTH_COMPLETE_CALLBACK)(const RawAddress& bd_addr, - DEV_CLASS dev_class, BD_NAME bd_name, - tHCI_REASON reason); +typedef void(tBTM_AUTH_COMPLETE_CALLBACK)(const RawAddress& bd_addr, DEV_CLASS dev_class, + BD_NAME bd_name, tHCI_REASON reason); /* Request SIRK verification for found member. Parameters are * BD Address of remote @@ -97,54 +93,46 @@ typedef struct { void (*BTM_BleLoadLocalKeys)(uint8_t key_type, tBTM_BLE_LOCAL_KEYS* p_key); // Update/Query in-memory device records - void (*BTM_SecAddDevice)(const RawAddress& bd_addr, const DEV_CLASS dev_class, - LinkKey link_key, uint8_t key_type, - uint8_t pin_length); - void (*BTM_SecAddBleDevice)(const RawAddress& bd_addr, - tBT_DEVICE_TYPE dev_type, + void (*BTM_SecAddDevice)(const RawAddress& bd_addr, const DEV_CLASS dev_class, LinkKey link_key, + uint8_t key_type, uint8_t pin_length); + void (*BTM_SecAddBleDevice)(const RawAddress& bd_addr, tBT_DEVICE_TYPE dev_type, tBLE_ADDR_TYPE addr_type); bool (*BTM_SecDeleteDevice)(const RawAddress& bd_addr); - void (*BTM_SecAddBleKey)(const RawAddress& bd_addr, - tBTM_LE_KEY_VALUE* p_le_key, + void (*BTM_SecAddBleKey)(const RawAddress& bd_addr, tBTM_LE_KEY_VALUE* p_le_key, tBTM_LE_KEY_TYPE key_type); void (*BTM_SecClearSecurityFlags)(const RawAddress& bd_addr); - tBTM_STATUS (*BTM_SetEncryption)(const RawAddress& bd_addr, - tBT_TRANSPORT transport, - tBTM_SEC_CALLBACK* p_callback, - void* p_ref_data, tBTM_BLE_SEC_ACT sec_act); + tBTM_STATUS (*BTM_SetEncryption)(const RawAddress& bd_addr, tBT_TRANSPORT transport, + tBTM_SEC_CALLBACK* p_callback, void* p_ref_data, + tBTM_BLE_SEC_ACT sec_act); bool (*BTM_IsEncrypted)(const RawAddress& bd_addr, tBT_TRANSPORT transport); bool (*BTM_SecIsSecurityPending)(const RawAddress& bd_addr); - bool (*BTM_IsLinkKeyKnown)(const RawAddress& bd_addr, - tBT_TRANSPORT transport); + bool (*BTM_IsLinkKeyKnown)(const RawAddress& bd_addr, tBT_TRANSPORT transport); // Secure service management - bool (*BTM_SetSecurityLevel)(bool is_originator, const char* p_name, - uint8_t service_id, uint16_t sec_level, - uint16_t psm, uint32_t mx_proto_id, + bool (*BTM_SetSecurityLevel)(bool is_originator, const char* p_name, uint8_t service_id, + uint16_t sec_level, uint16_t psm, uint32_t mx_proto_id, uint32_t mx_chan_id); uint8_t (*BTM_SecClrService)(uint8_t service_id); uint8_t (*BTM_SecClrServiceByPsm)(uint16_t psm); // Pairing related APIs - tBTM_STATUS (*BTM_SecBond)(const RawAddress& bd_addr, - tBLE_ADDR_TYPE addr_type, tBT_TRANSPORT transport, - tBT_DEVICE_TYPE device_type); + tBTM_STATUS (*BTM_SecBond)(const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type, + tBT_TRANSPORT transport, tBT_DEVICE_TYPE device_type); tBTM_STATUS (*BTM_SecBondCancel)(const RawAddress& bd_addr); - void (*BTM_RemoteOobDataReply)(tBTM_STATUS res, const RawAddress& bd_addr, - const Octet16& c, const Octet16& r); - void (*BTM_PINCodeReply)(const RawAddress& bd_addr, tBTM_STATUS res, - uint8_t pin_len, uint8_t* p_pin); + void (*BTM_RemoteOobDataReply)(tBTM_STATUS res, const RawAddress& bd_addr, const Octet16& c, + const Octet16& r); + void (*BTM_PINCodeReply)(const RawAddress& bd_addr, tBTM_STATUS res, uint8_t pin_len, + uint8_t* p_pin); void (*BTM_SecConfirmReqReply)(tBTM_STATUS res, tBT_TRANSPORT transport, const RawAddress bd_addr); void (*BTM_BleSirkConfirmDeviceReply)(const RawAddress& bd_addr, uint8_t res); - void (*BTM_BlePasskeyReply)(const RawAddress& bd_addr, uint8_t res, - uint32_t passkey); + void (*BTM_BlePasskeyReply)(const RawAddress& bd_addr, uint8_t res, uint32_t passkey); // other misc APIs uint8_t (*BTM_GetSecurityMode)(); @@ -153,8 +141,7 @@ typedef struct { // TODO: remove them from this structure const char* (*BTM_SecReadDevName)(const RawAddress& bd_addr); bool (*BTM_SecAddRmtNameNotifyCallback)(tBTM_RMT_NAME_CALLBACK* p_callback); - bool (*BTM_SecDeleteRmtNameNotifyCallback)( - tBTM_RMT_NAME_CALLBACK* p_callback); + bool (*BTM_SecDeleteRmtNameNotifyCallback)(tBTM_RMT_NAME_CALLBACK* p_callback); } SecurityClientInterface; const SecurityClientInterface& get_security_client_interface(); diff --git a/system/stack/include/smp_api.h b/system/stack/include/smp_api.h index 5d0b8101a80..b9eeee4ff6b 100644 --- a/system/stack/include/smp_api.h +++ b/system/stack/include/smp_api.h @@ -150,8 +150,7 @@ void SMP_ConfirmReply(const RawAddress& bd_addr, uint8_t res); * p_data - SM Randomizer C. * ******************************************************************************/ -void SMP_OobDataReply(const RawAddress& bd_addr, tSMP_STATUS res, uint8_t len, - uint8_t* p_data); +void SMP_OobDataReply(const RawAddress& bd_addr, tSMP_STATUS res, uint8_t len, uint8_t* p_data); /******************************************************************************* * diff --git a/system/stack/include/smp_api_types.h b/system/stack/include/smp_api_types.h index 8ab40c15992..b6a128ba8d8 100644 --- a/system/stack/include/smp_api_types.h +++ b/system/stack/include/smp_api_types.h @@ -103,7 +103,7 @@ typedef enum : uint8_t { enum : uint8_t { SMP_AUTH_NO_BOND = 0x00, /* no MITM, No Bonding, encryption only */ - SMP_AUTH_NB_ENC_ONLY = 0x00, //(SMP_AUTH_MASK | BTM_AUTH_SP_NO) + SMP_AUTH_NB_ENC_ONLY = 0x00, // (SMP_AUTH_MASK | BTM_AUTH_SP_NO) SMP_AUTH_BOND = (1u << 0), SMP_AUTH_UNUSED = (1u << 1), /* SMP Authentication requirement */ @@ -113,9 +113,8 @@ enum : uint8_t { SMP_H7_SUPPORT_BIT = (1u << 5), }; -#define SMP_AUTH_MASK \ - (SMP_AUTH_BOND | SMP_AUTH_YN_BIT | SMP_SC_SUPPORT_BIT | SMP_KP_SUPPORT_BIT | \ - SMP_H7_SUPPORT_BIT) +#define SMP_AUTH_MASK \ + (SMP_AUTH_BOND | SMP_AUTH_YN_BIT | SMP_SC_SUPPORT_BIT | SMP_KP_SUPPORT_BIT | SMP_H7_SUPPORT_BIT) /* Secure Connections, no MITM, no Bonding */ #define SMP_AUTH_SC_ENC_ONLY (SMP_H7_SUPPORT_BIT | SMP_SC_SUPPORT_BIT) @@ -146,12 +145,11 @@ enum tSMP_KEYS_BITMASK : uint8_t { typedef uint8_t tSMP_KEYS; constexpr tSMP_KEYS SMP_BR_SEC_DEFAULT_KEY = - (SMP_SEC_KEY_TYPE_ENC | SMP_SEC_KEY_TYPE_ID | SMP_SEC_KEY_TYPE_CSRK); + (SMP_SEC_KEY_TYPE_ENC | SMP_SEC_KEY_TYPE_ID | SMP_SEC_KEY_TYPE_CSRK); /* default security key distribution value */ constexpr tSMP_KEYS SMP_SEC_DEFAULT_KEY = - (SMP_SEC_KEY_TYPE_ENC | SMP_SEC_KEY_TYPE_ID | SMP_SEC_KEY_TYPE_CSRK | - SMP_SEC_KEY_TYPE_LK); + (SMP_SEC_KEY_TYPE_ENC | SMP_SEC_KEY_TYPE_ID | SMP_SEC_KEY_TYPE_CSRK | SMP_SEC_KEY_TYPE_LK); #define SMP_SC_KEY_OUT_OF_RANGE 5 /* out of range */ typedef uint8_t tSMP_SC_KEY_TYPE; diff --git a/system/stack/include/smp_status.h b/system/stack/include/smp_status.h index b3ef27f8191..dce8778b8a2 100644 --- a/system/stack/include/smp_status.h +++ b/system/stack/include/smp_status.h @@ -60,7 +60,7 @@ typedef enum : uint8_t { SMP_CONN_TOUT = (SMP_MAX_FAIL_RSN_PER_SPEC + 0x0B), /* 0x19 */ SMP_SIRK_DEVICE_INVALID = (SMP_MAX_FAIL_RSN_PER_SPEC + 0x0C), /* 0x1a */ - SMP_USER_CANCELLED = (SMP_MAX_FAIL_RSN_PER_SPEC + 0x0D), /* 0x1b */ + SMP_USER_CANCELLED = (SMP_MAX_FAIL_RSN_PER_SPEC + 0x0D), /* 0x1b */ } tSMP_STATUS; inline std::string smp_status_text(const tSMP_STATUS& status) { diff --git a/system/stack/include/srvc_api.h b/system/stack/include/srvc_api.h index 8d79f998aab..d991568e3f6 100644 --- a/system/stack/include/srvc_api.h +++ b/system/stack/include/srvc_api.h @@ -164,7 +164,6 @@ tDIS_STATUS DIS_SrUpdate(tDIS_ATTR_BIT dis_attr_bit, tDIS_ATTR* p_info); * Returns void * ******************************************************************************/ -bool DIS_ReadDISInfo(const RawAddress& peer_bda, tDIS_READ_CBACK* p_cback, - tDIS_ATTR_MASK mask); +bool DIS_ReadDISInfo(const RawAddress& peer_bda, tDIS_READ_CBACK* p_cback, tDIS_ATTR_MASK mask); #endif diff --git a/system/stack/include/stack_metrics_logging.h b/system/stack/include/stack_metrics_logging.h index b8b8179f7c2..74fe79b7828 100644 --- a/system/stack/include/stack_metrics_logging.h +++ b/system/stack/include/stack_metrics_logging.h @@ -23,41 +23,33 @@ #include "types/raw_address.h" -void log_classic_pairing_event(const RawAddress& address, uint16_t handle, - uint32_t hci_cmd, uint16_t hci_event, - uint16_t cmd_status, uint16_t reason_code, +void log_classic_pairing_event(const RawAddress& address, uint16_t handle, uint32_t hci_cmd, + uint16_t hci_event, uint16_t cmd_status, uint16_t reason_code, int64_t event_value); -void log_link_layer_connection_event( - const RawAddress* address, uint32_t connection_handle, - android::bluetooth::DirectionEnum direction, uint16_t link_type, - uint32_t hci_cmd, uint16_t hci_event, uint16_t hci_ble_event, - uint16_t cmd_status, uint16_t reason_code); +void log_link_layer_connection_event(const RawAddress* address, uint32_t connection_handle, + android::bluetooth::DirectionEnum direction, + uint16_t link_type, uint32_t hci_cmd, uint16_t hci_event, + uint16_t hci_ble_event, uint16_t cmd_status, + uint16_t reason_code); void log_smp_pairing_event(const RawAddress& address, uint16_t smp_cmd, - android::bluetooth::DirectionEnum direction, - uint16_t smp_fail_reason); + android::bluetooth::DirectionEnum direction, uint16_t smp_fail_reason); -void log_sdp_attribute(const RawAddress& address, uint16_t protocol_uuid, - uint16_t attribute_id, size_t attribute_size, - const char* attribute_value); +void log_sdp_attribute(const RawAddress& address, uint16_t protocol_uuid, uint16_t attribute_id, + size_t attribute_size, const char* attribute_value); void log_manufacturer_info(const RawAddress& address, android::bluetooth::AddressTypeEnum address_type, android::bluetooth::DeviceInfoSrcEnum source_type, - const std::string& source_name, - const std::string& manufacturer, - const std::string& model, - const std::string& hardware_version, + const std::string& source_name, const std::string& manufacturer, + const std::string& model, const std::string& hardware_version, const std::string& software_version); -void log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum key, - int64_t value); +void log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum key, int64_t value); -void log_hfp_audio_packet_loss_stats(const RawAddress& address, - int num_decoded_frames, - double packet_loss_ratio, - uint16_t codec_type); +void log_hfp_audio_packet_loss_stats(const RawAddress& address, int num_decoded_frames, + double packet_loss_ratio, uint16_t codec_type); -void log_mmc_transcode_rtt_stats(int maximum_rtt, double mean_rtt, - int num_requests, int codec_type); +void log_mmc_transcode_rtt_stats(int maximum_rtt, double mean_rtt, int num_requests, + int codec_type); diff --git a/system/stack/l2cap/l2c_api.cc b/system/stack/l2cap/l2c_api.cc index d7a8df416c9..e77a398669b 100644 --- a/system/stack/l2cap/l2c_api.cc +++ b/system/stack/l2cap/l2c_api.cc @@ -60,19 +60,19 @@ extern fixed_queue_t* btu_general_alarm_queue; tL2C_AVDT_CHANNEL_INFO av_media_channels[MAX_ACTIVE_AVDT_CONN]; tBT_TRANSPORT l2c_get_transport_from_fixed_cid(uint16_t fixed_cid) { - if (fixed_cid >= L2CAP_ATT_CID && fixed_cid <= L2CAP_SMP_CID) + if (fixed_cid >= L2CAP_ATT_CID && fixed_cid <= L2CAP_SMP_CID) { return BT_TRANSPORT_LE; + } return BT_TRANSPORT_BR_EDR; } -uint16_t L2CA_RegisterWithSecurity( - uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info, bool enable_snoop, - tL2CAP_ERTM_INFO* p_ertm_info, uint16_t my_mtu, - uint16_t required_remote_mtu, uint16_t sec_level) { - auto ret = L2CA_Register(psm, p_cb_info, enable_snoop, p_ertm_info, my_mtu, - required_remote_mtu, sec_level); - get_btm_client_interface().security.BTM_SetSecurityLevel( - false, "", 0, sec_level, psm, 0, 0); +uint16_t L2CA_RegisterWithSecurity(uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info, + bool enable_snoop, tL2CAP_ERTM_INFO* p_ertm_info, + uint16_t my_mtu, uint16_t required_remote_mtu, + uint16_t sec_level) { + auto ret = L2CA_Register(psm, p_cb_info, enable_snoop, p_ertm_info, my_mtu, required_remote_mtu, + sec_level); + get_btm_client_interface().security.BTM_SetSecurityLevel(false, "", 0, sec_level, psm, 0, 0); return ret; } @@ -111,9 +111,8 @@ static const bool enforce_assert = check_l2cap_credit(); * L2CA_ErtmConnectReq() and L2CA_Deregister() * ******************************************************************************/ -uint16_t L2CA_Register(uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info, - bool enable_snoop, tL2CAP_ERTM_INFO* p_ertm_info, - uint16_t my_mtu, uint16_t required_remote_mtu, +uint16_t L2CA_Register(uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info, bool enable_snoop, + tL2CAP_ERTM_INFO* p_ertm_info, uint16_t my_mtu, uint16_t required_remote_mtu, uint16_t /* sec_level */) { const bool config_cfm_cb = (p_cb_info.pL2CA_ConfigCfm_Cb != nullptr); const bool config_ind_cb = (p_cb_info.pL2CA_ConfigInd_Cb != nullptr); @@ -130,16 +129,16 @@ uint16_t L2CA_Register(uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info, */ if (!config_cfm_cb || !data_ind_cb || !disconnect_ind_cb) { log::error( - "L2CAP - no cb registering PSM: 0x{:04x} cfg_cfm:{} cfg_ind:{} " - "data_ind:{} discon_int:{}", - psm, config_cfm_cb, config_ind_cb, data_ind_cb, disconnect_ind_cb); - return (0); + "L2CAP - no cb registering PSM: 0x{:04x} cfg_cfm:{} cfg_ind:{} " + "data_ind:{} discon_int:{}", + psm, config_cfm_cb, config_ind_cb, data_ind_cb, disconnect_ind_cb); + return 0; } /* Verify PSM is valid */ if (L2C_INVALID_PSM(psm)) { log::error("L2CAP - invalid PSM value, PSM: 0x{:04x}", psm); - return (0); + return 0; } /* Check if this is a registration for an outgoing-only connection to */ @@ -147,7 +146,9 @@ uint16_t L2CA_Register(uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info, if ((psm >= 0x1001) && (p_cb_info.pL2CA_ConnectInd_Cb == NULL)) { for (vpsm = 0x1002; vpsm < 0x8000; vpsm += 2) { p_rcb = l2cu_find_rcb_by_psm(vpsm); - if (p_rcb == NULL) break; + if (p_rcb == NULL) { + break; + } } log::debug("L2CAP - Real PSM: 0x{:04x} Virtual PSM: 0x{:04x}", psm, vpsm); @@ -158,9 +159,8 @@ uint16_t L2CA_Register(uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info, if (p_rcb == NULL) { p_rcb = l2cu_allocate_rcb(vpsm); if (p_rcb == NULL) { - log::warn("L2CAP - no RCB available, PSM: 0x{:04x} vPSM: 0x{:04x}", psm, - vpsm); - return (0); + log::warn("L2CAP - no RCB available, PSM: 0x{:04x} vPSM: 0x{:04x}", psm, vpsm); + return 0; } } @@ -168,14 +168,11 @@ uint16_t L2CA_Register(uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info, p_rcb->log_packets = enable_snoop; p_rcb->api = p_cb_info; p_rcb->real_psm = psm; - p_rcb->ertm_info = p_ertm_info == nullptr - ? tL2CAP_ERTM_INFO{L2CAP_FCR_BASIC_MODE} - : *p_ertm_info; + p_rcb->ertm_info = p_ertm_info == nullptr ? tL2CAP_ERTM_INFO{L2CAP_FCR_BASIC_MODE} : *p_ertm_info; p_rcb->my_mtu = my_mtu; - p_rcb->required_remote_mtu = - std::max(required_remote_mtu, L2CAP_MIN_MTU); + p_rcb->required_remote_mtu = std::max(required_remote_mtu, L2CAP_MIN_MTU); - return (vpsm); + return vpsm; } /******************************************************************************* @@ -206,9 +203,8 @@ void L2CA_Deregister(uint16_t psm) { continue; } - if ((p_ccb->in_use) && - ((p_ccb->chnl_state == CST_W4_L2CAP_DISCONNECT_RSP) || - (p_ccb->chnl_state == CST_W4_L2CA_DISCONNECT_RSP))) { + if ((p_ccb->in_use) && ((p_ccb->chnl_state == CST_W4_L2CAP_DISCONNECT_RSP) || + (p_ccb->chnl_state == CST_W4_L2CA_DISCONNECT_RSP))) { continue; } @@ -265,7 +261,7 @@ uint16_t L2CA_AllocateLePSM(void) { } l2cb.le_dyn_psm = psm; - return (psm); + return psm; } /******************************************************************************* @@ -293,8 +289,7 @@ void L2CA_FreeLePSM(uint16_t psm) { uint16_t L2CA_ConnectReqWithSecurity(uint16_t psm, const RawAddress& p_bd_addr, uint16_t sec_level) { - get_btm_client_interface().security.BTM_SetSecurityLevel( - true, "", 0, sec_level, psm, 0, 0); + get_btm_client_interface().security.BTM_SetSecurityLevel(true, "", 0, sec_level, psm, 0, 0); return L2CA_ConnectReq(psm, p_bd_addr); } @@ -334,8 +329,7 @@ uint16_t L2CA_ConnectReq(uint16_t psm, const RawAddress& p_bd_addr) { p_lcb = l2cu_allocate_lcb(p_bd_addr, false, BT_TRANSPORT_BR_EDR); /* currently use BR/EDR for ERTM mode l2cap connection */ if (p_lcb == nullptr) { - log::warn("connection not started for PSM=0x{:x}, p_lcb={}", psm, - fmt::ptr(p_lcb)); + log::warn("connection not started for PSM=0x{:x}, p_lcb={}", psm, fmt::ptr(p_lcb)); return 0; } l2cu_create_conn_br_edr(p_lcb); @@ -369,8 +363,8 @@ uint16_t L2CA_ConnectReq(uint16_t psm, const RawAddress& p_bd_addr) { p_lcb->p_pending_ccb = p_ccb; } - log::verbose("L2CAP - L2CA_conn_req(psm: 0x{:04x}) returned CID: 0x{:04x}", - psm, p_ccb->local_cid); + log::verbose("L2CAP - L2CA_conn_req(psm: 0x{:04x}) returned CID: 0x{:04x}", psm, + p_ccb->local_cid); /* Return the local CID as our handle */ return p_ccb->local_cid; @@ -390,13 +384,12 @@ uint16_t L2CA_ConnectReq(uint16_t psm, const RawAddress& p_bd_addr) { * and L2CA_DeregisterLECoc() * ******************************************************************************/ -uint16_t L2CA_RegisterLECoc(uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info, - uint16_t sec_level, tL2CAP_LE_CFG_INFO cfg) { +uint16_t L2CA_RegisterLECoc(uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info, uint16_t sec_level, + tL2CAP_LE_CFG_INFO cfg) { if (p_cb_info.pL2CA_ConnectInd_Cb != nullptr || psm < LE_DYNAMIC_PSM_START) { // If we register LE COC for outgoing connection only, don't register with // BTM_Sec, because it's handled by L2CA_ConnectLECocReq. - get_btm_client_interface().security.BTM_SetSecurityLevel( - false, "", 0, sec_level, psm, 0, 0); + get_btm_client_interface().security.BTM_SetSecurityLevel(false, "", 0, sec_level, psm, 0, 0); } /* Verify that the required callback info has been filled in @@ -420,8 +413,7 @@ uint16_t L2CA_RegisterLECoc(uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info, /* Check if this is a registration for an outgoing-only connection to */ /* a dynamic PSM. If so, allocate a "virtual" PSM for the app to use. */ - if ((psm >= LE_DYNAMIC_PSM_START) && - (p_cb_info.pL2CA_ConnectInd_Cb == NULL)) { + if ((psm >= LE_DYNAMIC_PSM_START) && (p_cb_info.pL2CA_ConnectInd_Cb == NULL)) { vpsm = L2CA_AllocateLePSM(); if (vpsm == 0) { log::error("Out of free BLE PSM"); @@ -437,8 +429,7 @@ uint16_t L2CA_RegisterLECoc(uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info, log::debug("Allocate rcp for Virtual PSM: 0x{:04x}", vpsm); p_rcb = l2cu_allocate_ble_rcb(vpsm); if (p_rcb == NULL) { - log::warn("No BLE RCB available, PSM: 0x{:04x} vPSM: 0x{:04x}", psm, - vpsm); + log::warn("No BLE RCB available, PSM: 0x{:04x} vPSM: 0x{:04x}", psm, vpsm); return 0; } } @@ -472,17 +463,23 @@ void L2CA_DeregisterLECoc(uint16_t psm) { tL2C_LCB* p_lcb = &l2cb.lcb_pool[0]; for (int i = 0; i < MAX_L2CAP_LINKS; i++, p_lcb++) { - if (!p_lcb->in_use || p_lcb->transport != BT_TRANSPORT_LE) continue; + if (!p_lcb->in_use || p_lcb->transport != BT_TRANSPORT_LE) { + continue; + } tL2C_CCB* p_ccb = p_lcb->ccb_queue.p_first_ccb; - if ((p_ccb == NULL) || (p_lcb->link_state == LST_DISCONNECTING)) continue; + if ((p_ccb == NULL) || (p_lcb->link_state == LST_DISCONNECTING)) { + continue; + } if (p_ccb->in_use && (p_ccb->chnl_state == CST_W4_L2CAP_DISCONNECT_RSP || - p_ccb->chnl_state == CST_W4_L2CA_DISCONNECT_RSP)) + p_ccb->chnl_state == CST_W4_L2CA_DISCONNECT_RSP)) { continue; + } - if (p_ccb->p_rcb == p_rcb) + if (p_ccb->p_rcb == p_rcb) { l2c_csm_execute(p_ccb, L2CEVT_L2CA_DISCONNECT_REQ, NULL); + } } l2cu_release_ble_rcb(p_rcb); @@ -505,10 +502,9 @@ void L2CA_DeregisterLECoc(uint16_t psm) { * Returns the CID of the connection, or 0 if it failed to start * ******************************************************************************/ -uint16_t L2CA_ConnectLECocReq(uint16_t psm, const RawAddress& p_bd_addr, - tL2CAP_LE_CFG_INFO* p_cfg, uint16_t sec_level) { - get_btm_client_interface().security.BTM_SetSecurityLevel( - true, "", 0, sec_level, psm, 0, 0); +uint16_t L2CA_ConnectLECocReq(uint16_t psm, const RawAddress& p_bd_addr, tL2CAP_LE_CFG_INFO* p_cfg, + uint16_t sec_level) { + get_btm_client_interface().security.BTM_SetSecurityLevel(true, "", 0, sec_level, psm, 0, 0); log::verbose("BDA: {} PSM: 0x{:04x}", p_bd_addr, psm); @@ -533,8 +529,7 @@ uint16_t L2CA_ConnectLECocReq(uint16_t psm, const RawAddress& p_bd_addr, if ((p_lcb == NULL) /* currently use BR/EDR for ERTM mode l2cap connection */ || (!l2cu_create_conn_le(p_lcb))) { - log::warn("conn not started for PSM: 0x{:04x} p_lcb: 0x{}", psm, - fmt::ptr(p_lcb)); + log::warn("conn not started for PSM: 0x{:04x} p_lcb: 0x{}", psm, fmt::ptr(p_lcb)); return 0; } } @@ -563,9 +558,8 @@ uint16_t L2CA_ConnectLECocReq(uint16_t psm, const RawAddress& p_bd_addr, log::verbose("LE Link is up"); // post this asynchronously to avoid out-of-order callback invocation // should this operation fail - do_in_main_thread( - FROM_HERE, base::BindOnce(&l2c_csm_execute, base::Unretained(p_ccb), - L2CEVT_L2CA_CONNECT_REQ, nullptr)); + do_in_main_thread(FROM_HERE, base::BindOnce(&l2c_csm_execute, base::Unretained(p_ccb), + L2CEVT_L2CA_CONNECT_REQ, nullptr)); } } @@ -610,8 +604,9 @@ bool L2CA_GetPeerLECocConfig(uint16_t lcid, tL2CAP_LE_CFG_INFO* peer_cfg) { return false; } - if (peer_cfg != NULL) + if (peer_cfg != NULL) { memcpy(peer_cfg, &p_ccb->peer_conn_cfg, sizeof(tL2CAP_LE_CFG_INFO)); + } return true; } @@ -661,10 +656,9 @@ uint16_t L2CA_GetPeerLECocCredit(const RawAddress& bd_addr, uint16_t lcid) { * ******************************************************************************/ bool L2CA_ConnectCreditBasedRsp(const RawAddress& p_bd_addr, uint8_t id, - std::vector& accepted_lcids, - uint16_t result, tL2CAP_LE_CFG_INFO* p_cfg) { - log::verbose("BDA: {} num of cids: {} Result: {}", p_bd_addr, - int(accepted_lcids.size()), result); + std::vector& accepted_lcids, uint16_t result, + tL2CAP_LE_CFG_INFO* p_cfg) { + log::verbose("BDA: {} num of cids: {} Result: {}", p_bd_addr, int(accepted_lcids.size()), result); /* First, find the link control block */ tL2C_LCB* p_lcb = l2cu_find_lcb_by_bd_addr(p_bd_addr, BT_TRANSPORT_LE); @@ -710,8 +704,7 @@ bool L2CA_ConnectCreditBasedRsp(const RawAddress& p_bd_addr, uint8_t id, if (accepted_lcids.size() > 0) { l2c_csm_execute(p_ccb, L2CEVT_L2CA_CREDIT_BASED_CONNECT_RSP, &conn_info); } else { - l2c_csm_execute(p_ccb, L2CEVT_L2CA_CREDIT_BASED_CONNECT_RSP_NEG, - &conn_info); + l2c_csm_execute(p_ccb, L2CEVT_L2CA_CREDIT_BASED_CONNECT_RSP_NEG, &conn_info); } return true; @@ -730,8 +723,7 @@ bool L2CA_ConnectCreditBasedRsp(const RawAddress& p_bd_addr, uint8_t id, * ******************************************************************************/ -std::vector L2CA_ConnectCreditBasedReq(uint16_t psm, - const RawAddress& p_bd_addr, +std::vector L2CA_ConnectCreditBasedReq(uint16_t psm, const RawAddress& p_bd_addr, tL2CAP_LE_CFG_INFO* p_cfg) { log::verbose("BDA: {} PSM: 0x{:04x}", p_bd_addr, psm); @@ -778,15 +770,13 @@ std::vector L2CA_ConnectCreditBasedReq(uint16_t psm, tL2C_CCB* p_ccb_primary; /* Make sure user set proper value for number of cids */ - if (p_cfg->number_of_channels > L2CAP_CREDIT_BASED_MAX_CIDS || - p_cfg->number_of_channels == 0) { + if (p_cfg->number_of_channels > L2CAP_CREDIT_BASED_MAX_CIDS || p_cfg->number_of_channels == 0) { p_cfg->number_of_channels = L2CAP_CREDIT_BASED_MAX_CIDS; } for (int i = 0; i < p_cfg->number_of_channels; i++) { /* Allocate a channel control block */ - tL2C_CCB* p_ccb = - l2cu_allocate_ccb(p_lcb, 0, psm == BT_PSM_EATT /* is_eatt */); + tL2C_CCB* p_ccb = l2cu_allocate_ccb(p_lcb, 0, psm == BT_PSM_EATT /* is_eatt */); if (p_ccb == NULL) { if (i == 0) { log::warn("no CCB, PSM: 0x{:04x}", psm); @@ -815,14 +805,14 @@ std::vector L2CA_ConnectCreditBasedReq(uint16_t psm, allocated_cids.push_back(p_ccb->local_cid); } - for (int i = 0; i < (int)(allocated_cids.size()); i++) + for (int i = 0; i < (int)(allocated_cids.size()); i++) { p_lcb->pending_ecoc_connection_cids[i] = allocated_cids[i]; + } p_lcb->pending_ecoc_conn_cnt = (uint16_t)(allocated_cids.size()); l2c_csm_execute(p_ccb_primary, L2CEVT_L2CA_CREDIT_BASED_CONNECT_REQ, NULL); - log::verbose("(psm: 0x{:04x}) returned CID: 0x{:04x}", psm, - p_ccb_primary->local_cid); + log::verbose("(psm: 0x{:04x}) returned CID: 0x{:04x}", psm, p_ccb_primary->local_cid); return allocated_cids; } @@ -840,8 +830,7 @@ std::vector L2CA_ConnectCreditBasedReq(uint16_t psm, * ******************************************************************************/ -bool L2CA_ReconfigCreditBasedConnsReq(const RawAddress& /* bda */, - std::vector& lcids, +bool L2CA_ReconfigCreditBasedConnsReq(const RawAddress& /* bda */, std::vector& lcids, tL2CAP_LE_CFG_INFO* p_cfg) { tL2C_CCB* p_ccb; @@ -849,7 +838,7 @@ bool L2CA_ReconfigCreditBasedConnsReq(const RawAddress& /* bda */, if (lcids.empty()) { log::warn("L2CAP - empty lcids"); - return (false); + return false; } for (uint16_t cid : lcids) { @@ -857,13 +846,12 @@ bool L2CA_ReconfigCreditBasedConnsReq(const RawAddress& /* bda */, if (!p_ccb) { log::warn("L2CAP - no CCB for L2CA_cfg_req, CID: {}", cid); - return (false); + return false; } - if ((p_ccb->local_conn_cfg.mtu > p_cfg->mtu) || - (p_ccb->local_conn_cfg.mps > p_cfg->mps)) { + if ((p_ccb->local_conn_cfg.mtu > p_cfg->mtu) || (p_ccb->local_conn_cfg.mps > p_cfg->mps)) { log::warn("L2CAP - MPS or MTU reduction, CID: {}", cid); - return (false); + return false; } } @@ -878,7 +866,7 @@ bool L2CA_ReconfigCreditBasedConnsReq(const RawAddress& /* bda */, p_ccb = l2cu_find_ccb_by_cid(NULL, cid); if (!p_ccb) { log::error("Missing cid? {}", int(cid)); - return (false); + return false; } p_ccb->reconfig_started = true; } @@ -889,16 +877,17 @@ bool L2CA_ReconfigCreditBasedConnsReq(const RawAddress& /* bda */, * p_ccb. In the p_lcp we store configuration and cid in which context we are * doing reconfiguration. */ - for (p_ccb = p_lcb->ccb_queue.p_first_ccb; p_ccb; p_ccb = p_ccb->p_next_ccb) + for (p_ccb = p_lcb->ccb_queue.p_first_ccb; p_ccb; p_ccb = p_ccb->p_next_ccb) { if ((p_ccb->in_use) && (p_ccb->ecoc) && (p_ccb->reconfig_started)) { p_ccb->p_lcb->pending_ecoc_reconfig_cfg = *p_cfg; p_ccb->p_lcb->pending_ecoc_reconfig_cnt = lcids.size(); break; } + } l2c_csm_execute(p_ccb, L2CEVT_L2CA_CREDIT_BASED_RECONFIG_REQ, p_cfg); - return (true); + return true; } /******************************************************************************* @@ -917,14 +906,14 @@ bool L2CA_DisconnectReq(uint16_t cid) { p_ccb = l2cu_find_ccb_by_cid(NULL, cid); if (p_ccb == NULL) { log::warn("L2CAP - no CCB for L2CA_disc_req, CID: {}", cid); - return (false); + return false; } log::debug("L2CAP Local disconnect request CID: 0x{:04x}", cid); l2c_csm_execute(p_ccb, L2CEVT_L2CA_DISCONNECT_REQ, NULL); - return (true); + return true; } bool L2CA_DisconnectLECocReq(uint16_t cid) { return L2CA_DisconnectReq(cid); } @@ -983,9 +972,12 @@ bool L2CA_SetIdleTimeoutByBdAddr(const RawAddress& bd_addr, uint16_t timeout, if ((p_lcb) && (p_lcb->in_use) && (p_lcb->link_state == LST_CONNECTED)) { p_lcb->idle_timeout = timeout; - if (!p_lcb->ccb_queue.p_first_ccb) l2cu_no_dynamic_ccbs(p_lcb); - } else + if (!p_lcb->ccb_queue.p_first_ccb) { + l2cu_no_dynamic_ccbs(p_lcb); + } + } else { return false; + } } else { int xx; tL2C_LCB* p_lcb = &l2cb.lcb_pool[0]; @@ -994,7 +986,9 @@ bool L2CA_SetIdleTimeoutByBdAddr(const RawAddress& bd_addr, uint16_t timeout, if ((p_lcb->in_use) && (p_lcb->link_state == LST_CONNECTED)) { p_lcb->idle_timeout = timeout; - if (!p_lcb->ccb_queue.p_first_ccb) l2cu_no_dynamic_ccbs(p_lcb); + if (!p_lcb->ccb_queue.p_first_ccb) { + l2cu_no_dynamic_ccbs(p_lcb); + } } } } @@ -1036,7 +1030,7 @@ bool L2CA_UseLatencyMode(const RawAddress& bd_addr, bool use_latency_mode) { ******************************************************************************/ bool L2CA_SetAclPriority(const RawAddress& bd_addr, tL2CAP_PRIORITY priority) { log::verbose("BDA: {}, priority: {}", bd_addr, priority); - return (l2cu_set_acl_priority(bd_addr, priority, false)); + return l2cu_set_acl_priority(bd_addr, priority, false); } /******************************************************************************* @@ -1065,21 +1059,20 @@ bool L2CA_SetAclLatency(const RawAddress& bd_addr, tL2CAP_LATENCY latency) { bool L2CA_SetTxPriority(uint16_t cid, tL2CAP_CHNL_PRIORITY priority) { tL2C_CCB* p_ccb; - log::verbose("L2CA_SetTxPriority() CID: 0x{:04x}, priority:{}", cid, - priority); + log::verbose("L2CA_SetTxPriority() CID: 0x{:04x}, priority:{}", cid, priority); /* Find the channel control block. We don't know the link it is on. */ p_ccb = l2cu_find_ccb_by_cid(NULL, cid); if (p_ccb == NULL) { log::warn("L2CAP - no CCB for L2CA_SetTxPriority, CID: {}", cid); - return (false); + return false; } /* it will update the order of CCB in LCB by priority and update round robin * service variables */ l2cu_change_pri_ccb(p_ccb, priority); - return (true); + return true; } /******************************************************************************* @@ -1094,8 +1087,7 @@ bool L2CA_SetTxPriority(uint16_t cid, tL2CAP_CHNL_PRIORITY priority) { * Return value: true if peer is connected * ******************************************************************************/ -bool L2CA_GetPeerFeatures(const RawAddress& bd_addr, uint32_t* p_ext_feat, - uint8_t* p_chnl_mask) { +bool L2CA_GetPeerFeatures(const RawAddress& bd_addr, uint32_t* p_ext_feat, uint8_t* p_chnl_mask) { tL2C_LCB* p_lcb; /* We must already have a link to the remote */ @@ -1105,8 +1097,8 @@ bool L2CA_GetPeerFeatures(const RawAddress& bd_addr, uint32_t* p_ext_feat, return false; } - log::verbose("BDA: {} ExtFea: 0x{:08x} Chnl_Mask[0]: 0x{:02x}", bd_addr, - p_lcb->peer_ext_fea, p_lcb->peer_chnl_mask[0]); + log::verbose("BDA: {} ExtFea: 0x{:08x} Chnl_Mask[0]: 0x{:02x}", bd_addr, p_lcb->peer_ext_fea, + p_lcb->peer_chnl_mask[0]); *p_ext_feat = p_lcb->peer_ext_fea; @@ -1148,10 +1140,8 @@ static std::string fixed_channel_text(const uint16_t& fixed_cid) { } } -bool L2CA_RegisterFixedChannel(uint16_t fixed_cid, - tL2CAP_FIXED_CHNL_REG* p_freg) { - if ((fixed_cid < L2CAP_FIRST_FIXED_CHNL) || - (fixed_cid > L2CAP_LAST_FIXED_CHNL)) { +bool L2CA_RegisterFixedChannel(uint16_t fixed_cid, tL2CAP_FIXED_CHNL_REG* p_freg) { + if ((fixed_cid < L2CAP_FIRST_FIXED_CHNL) || (fixed_cid > L2CAP_LAST_FIXED_CHNL)) { log::error("Invalid fixed CID: 0x{:04x}", fixed_cid); return false; } @@ -1180,22 +1170,21 @@ bool L2CA_ConnectFixedChnl(uint16_t fixed_cid, const RawAddress& rem_bda) { log::debug("fixed_cid:0x{:04x}", fixed_cid); // Check CID is valid and registered - if ((fixed_cid < L2CAP_FIRST_FIXED_CHNL) || - (fixed_cid > L2CAP_LAST_FIXED_CHNL) || - (l2cb.fixed_reg[fixed_cid - L2CAP_FIRST_FIXED_CHNL].pL2CA_FixedData_Cb == - NULL)) { + if ((fixed_cid < L2CAP_FIRST_FIXED_CHNL) || (fixed_cid > L2CAP_LAST_FIXED_CHNL) || + (l2cb.fixed_reg[fixed_cid - L2CAP_FIRST_FIXED_CHNL].pL2CA_FixedData_Cb == NULL)) { log::error("Invalid fixed_cid:0x{:04x}", fixed_cid); - return (false); + return false; } // Fail if BT is not yet up if (!get_btm_client_interface().local.BTM_IsDeviceUp()) { log::warn("Bt controller is not ready fixed_cid:0x{:04x}", fixed_cid); - return (false); + return false; } - if (fixed_cid >= L2CAP_ATT_CID && fixed_cid <= L2CAP_SMP_CID) + if (fixed_cid >= L2CAP_ATT_CID && fixed_cid <= L2CAP_SMP_CID) { transport = BT_TRANSPORT_LE; + } tL2C_BLE_FIXED_CHNLS_MASK peer_channel_mask; @@ -1205,10 +1194,11 @@ bool L2CA_ConnectFixedChnl(uint16_t fixed_cid, const RawAddress& rem_bda) { // Fixed channels are mandatory on LE transports so ignore the received // channel mask and use the locally cached LE channel mask. - if (transport == BT_TRANSPORT_LE) + if (transport == BT_TRANSPORT_LE) { peer_channel_mask = l2cb.l2c_ble_fixed_chnls_mask; - else + } else { peer_channel_mask = p_lcb->peer_chnl_mask[0]; + } // Check for supported channel if (!(peer_channel_mask & (1 << fixed_cid))) { @@ -1218,40 +1208,33 @@ bool L2CA_ConnectFixedChnl(uint16_t fixed_cid, const RawAddress& rem_bda) { // Get a CCB and link the lcb to it if (!l2cu_initialize_fixed_ccb(p_lcb, fixed_cid)) { - log::warn("Unable to allocate fixed channel resource fixed_cid:0x{:04x}", - fixed_cid); + log::warn("Unable to allocate fixed channel resource fixed_cid:0x{:04x}", fixed_cid); return false; } // racing with disconnecting, queue the connection request if (p_lcb->link_state == LST_DISCONNECTING) { - log::debug( - "Link is disconnecting so deferring connection fixed_cid:0x{:04x}", - fixed_cid); + log::debug("Link is disconnecting so deferring connection fixed_cid:0x{:04x}", fixed_cid); /* Save ccb so it can be started after disconnect is finished */ - p_lcb->p_pending_ccb = - p_lcb->p_fixed_ccbs[fixed_cid - L2CAP_FIRST_FIXED_CHNL]; + p_lcb->p_pending_ccb = p_lcb->p_fixed_ccbs[fixed_cid - L2CAP_FIRST_FIXED_CHNL]; return true; } (*l2cb.fixed_reg[fixed_cid - L2CAP_FIRST_FIXED_CHNL].pL2CA_FixedConn_Cb)( - fixed_cid, p_lcb->remote_bd_addr, true, 0, p_lcb->transport); + fixed_cid, p_lcb->remote_bd_addr, true, 0, p_lcb->transport); return true; } // No link. Get an LCB and start link establishment p_lcb = l2cu_allocate_lcb(rem_bda, false, transport); if (p_lcb == NULL) { - log::warn( - "Unable to allocate link resource for connection fixed_cid:0x{:04x}", - fixed_cid); + log::warn("Unable to allocate link resource for connection fixed_cid:0x{:04x}", fixed_cid); return false; } // Get a CCB and link the lcb to it if (!l2cu_initialize_fixed_ccb(p_lcb, fixed_cid)) { - log::warn("Unable to allocate fixed channel resource fixed_cid:0x{:04x}", - fixed_cid); + log::warn("Unable to allocate fixed channel resource fixed_cid:0x{:04x}", fixed_cid); l2cu_release_lcb(p_lcb); return false; } @@ -1259,9 +1242,7 @@ bool L2CA_ConnectFixedChnl(uint16_t fixed_cid, const RawAddress& rem_bda) { if (transport == BT_TRANSPORT_LE) { bool ret = l2cu_create_conn_le(p_lcb); if (!ret) { - log::warn( - "Unable to create fixed channel le connection fixed_cid:0x{:04x}", - fixed_cid); + log::warn("Unable to create fixed channel le connection fixed_cid:0x{:04x}", fixed_cid); l2cu_release_lcb(p_lcb); return false; } @@ -1285,51 +1266,49 @@ bool L2CA_ConnectFixedChnl(uint16_t fixed_cid, const RawAddress& rem_bda) { * tL2CAP_DW_RESULT::L2CAP_DW_FAILED, if error * ******************************************************************************/ -tL2CAP_DW_RESULT L2CA_SendFixedChnlData(uint16_t fixed_cid, - const RawAddress& rem_bda, +tL2CAP_DW_RESULT L2CA_SendFixedChnlData(uint16_t fixed_cid, const RawAddress& rem_bda, BT_HDR* p_buf) { tL2C_LCB* p_lcb; tBT_TRANSPORT transport = BT_TRANSPORT_BR_EDR; - if (fixed_cid >= L2CAP_ATT_CID && fixed_cid <= L2CAP_SMP_CID) + if (fixed_cid >= L2CAP_ATT_CID && fixed_cid <= L2CAP_SMP_CID) { transport = BT_TRANSPORT_LE; + } - if ((fixed_cid < L2CAP_FIRST_FIXED_CHNL) || - (fixed_cid > L2CAP_LAST_FIXED_CHNL) || - (l2cb.fixed_reg[fixed_cid - L2CAP_FIRST_FIXED_CHNL].pL2CA_FixedData_Cb == - NULL)) { + if ((fixed_cid < L2CAP_FIRST_FIXED_CHNL) || (fixed_cid > L2CAP_LAST_FIXED_CHNL) || + (l2cb.fixed_reg[fixed_cid - L2CAP_FIRST_FIXED_CHNL].pL2CA_FixedData_Cb == NULL)) { log::warn("No service registered or invalid CID: 0x{:04x}", fixed_cid); osi_free(p_buf); - return (tL2CAP_DW_RESULT::FAILED); + return tL2CAP_DW_RESULT::FAILED; } if (!get_btm_client_interface().local.BTM_IsDeviceUp()) { log::warn("Controller is not ready CID: 0x{:04x}", fixed_cid); osi_free(p_buf); - return (tL2CAP_DW_RESULT::FAILED); + return tL2CAP_DW_RESULT::FAILED; } p_lcb = l2cu_find_lcb_by_bd_addr(rem_bda, transport); if (p_lcb == NULL || p_lcb->link_state == LST_DISCONNECTING) { /* if link is disconnecting, also report data sending failure */ - log::warn("Link is disconnecting or does not exist CID: 0x{:04x}", - fixed_cid); + log::warn("Link is disconnecting or does not exist CID: 0x{:04x}", fixed_cid); osi_free(p_buf); - return (tL2CAP_DW_RESULT::FAILED); + return tL2CAP_DW_RESULT::FAILED; } tL2C_BLE_FIXED_CHNLS_MASK peer_channel_mask; // Select peer channels mask to use depending on transport - if (transport == BT_TRANSPORT_LE) + if (transport == BT_TRANSPORT_LE) { peer_channel_mask = l2cb.l2c_ble_fixed_chnls_mask; - else + } else { peer_channel_mask = p_lcb->peer_chnl_mask[0]; + } if ((peer_channel_mask & (1 << fixed_cid)) == 0) { log::warn("Peer does not support fixed channel CID: 0x{:04x}", fixed_cid); osi_free(p_buf); - return (tL2CAP_DW_RESULT::FAILED); + return tL2CAP_DW_RESULT::FAILED; } p_buf->event = 0; @@ -1339,42 +1318,39 @@ tL2CAP_DW_RESULT L2CA_SendFixedChnlData(uint16_t fixed_cid, if (!l2cu_initialize_fixed_ccb(p_lcb, fixed_cid)) { log::warn("No channel control block found for CID: 0x{:4x}", fixed_cid); osi_free(p_buf); - return (tL2CAP_DW_RESULT::FAILED); + return tL2CAP_DW_RESULT::FAILED; } } if (p_lcb->p_fixed_ccbs[fixed_cid - L2CAP_FIRST_FIXED_CHNL]->cong_sent) { log::warn( - "Unable to send data due to congestion CID: 0x{:04x} " - "xmit_hold_q.count: {} buff_quota: {}", - fixed_cid, - fixed_queue_length( - p_lcb->p_fixed_ccbs[fixed_cid - L2CAP_FIRST_FIXED_CHNL] - ->xmit_hold_q), - p_lcb->p_fixed_ccbs[fixed_cid - L2CAP_FIRST_FIXED_CHNL]->buff_quota); + "Unable to send data due to congestion CID: 0x{:04x} " + "xmit_hold_q.count: {} buff_quota: {}", + fixed_cid, + fixed_queue_length( + p_lcb->p_fixed_ccbs[fixed_cid - L2CAP_FIRST_FIXED_CHNL]->xmit_hold_q), + p_lcb->p_fixed_ccbs[fixed_cid - L2CAP_FIRST_FIXED_CHNL]->buff_quota); osi_free(p_buf); - return (tL2CAP_DW_RESULT::FAILED); + return tL2CAP_DW_RESULT::FAILED; } log::debug("Enqueued data for CID: 0x{:04x} len:{}", fixed_cid, p_buf->len); - l2c_enqueue_peer_data(p_lcb->p_fixed_ccbs[fixed_cid - L2CAP_FIRST_FIXED_CHNL], - p_buf); + l2c_enqueue_peer_data(p_lcb->p_fixed_ccbs[fixed_cid - L2CAP_FIRST_FIXED_CHNL], p_buf); l2c_link_check_send_pkts(p_lcb, 0, NULL); // If there is no dynamic CCB on the link, restart the idle timer each time // something is sent - if (p_lcb->in_use && p_lcb->link_state == LST_CONNECTED && - !p_lcb->ccb_queue.p_first_ccb) { + if (p_lcb->in_use && p_lcb->link_state == LST_CONNECTED && !p_lcb->ccb_queue.p_first_ccb) { l2cu_no_dynamic_ccbs(p_lcb); } if (p_lcb->p_fixed_ccbs[fixed_cid - L2CAP_FIRST_FIXED_CHNL]->cong_sent) { log::debug("Link congested for CID: 0x{:04x}", fixed_cid); - return (tL2CAP_DW_RESULT::CONGESTED); + return tL2CAP_DW_RESULT::CONGESTED; } - return (tL2CAP_DW_RESULT::SUCCESS); + return tL2CAP_DW_RESULT::SUCCESS; } /******************************************************************************* @@ -1396,24 +1372,22 @@ bool L2CA_RemoveFixedChnl(uint16_t fixed_cid, const RawAddress& rem_bda) { tBT_TRANSPORT transport = BT_TRANSPORT_BR_EDR; /* Check CID is valid and registered */ - if ((fixed_cid < L2CAP_FIRST_FIXED_CHNL) || - (fixed_cid > L2CAP_LAST_FIXED_CHNL) || - (l2cb.fixed_reg[fixed_cid - L2CAP_FIRST_FIXED_CHNL].pL2CA_FixedData_Cb == - NULL)) { + if ((fixed_cid < L2CAP_FIRST_FIXED_CHNL) || (fixed_cid > L2CAP_LAST_FIXED_CHNL) || + (l2cb.fixed_reg[fixed_cid - L2CAP_FIRST_FIXED_CHNL].pL2CA_FixedData_Cb == NULL)) { log::error("L2CA_RemoveFixedChnl() Invalid CID: 0x{:04x}", fixed_cid); - return (false); + return false; } - if (fixed_cid >= L2CAP_ATT_CID && fixed_cid <= L2CAP_SMP_CID) + if (fixed_cid >= L2CAP_ATT_CID && fixed_cid <= L2CAP_SMP_CID) { transport = BT_TRANSPORT_LE; + } /* Is a fixed channel connected to the remote BDA ?*/ p_lcb = l2cu_find_lcb_by_bd_addr(rem_bda, transport); - if (((p_lcb) == NULL) || - (!p_lcb->p_fixed_ccbs[fixed_cid - L2CAP_FIRST_FIXED_CHNL])) { + if (((p_lcb) == NULL) || (!p_lcb->p_fixed_ccbs[fixed_cid - L2CAP_FIRST_FIXED_CHNL])) { log::warn("BDA: {} CID: 0x{:04x} not connected", rem_bda, fixed_cid); - return (false); + return false; } log::verbose("BDA: {} CID: 0x{:04x}", rem_bda, fixed_cid); @@ -1431,12 +1405,13 @@ bool L2CA_RemoveFixedChnl(uint16_t fixed_cid, const RawAddress& rem_bda) { // immediate re-connection for service discovery. // Some devices do not do auto advertising when link is dropped, thus fail // the second connection and service discovery. - if ((fixed_cid == L2CAP_ATT_CID) && !p_lcb->ccb_queue.p_first_ccb) + if ((fixed_cid == L2CAP_ATT_CID) && !p_lcb->ccb_queue.p_first_ccb) { p_lcb->idle_timeout = 0; + } l2cu_release_ccb(p_ccb); - return (true); + return true; } /******************************************************************************* @@ -1459,17 +1434,14 @@ bool L2CA_SetLeGattTimeout(const RawAddress& rem_bda, uint16_t idle_tout) { /* Is a fixed channel connected to the remote BDA ?*/ tL2C_LCB* p_lcb = l2cu_find_lcb_by_bd_addr(rem_bda, BT_TRANSPORT_LE); - if (((p_lcb) == NULL) || - (!p_lcb->p_fixed_ccbs[kAttCid - L2CAP_FIRST_FIXED_CHNL])) { + if (((p_lcb) == NULL) || (!p_lcb->p_fixed_ccbs[kAttCid - L2CAP_FIRST_FIXED_CHNL])) { log::warn("BDA: {} CID: 0x{:04x} not connected", rem_bda, kAttCid); - return (false); + return false; } - p_lcb->p_fixed_ccbs[kAttCid - L2CAP_FIRST_FIXED_CHNL]->fixed_chnl_idle_tout = - idle_tout; + p_lcb->p_fixed_ccbs[kAttCid - L2CAP_FIRST_FIXED_CHNL]->fixed_chnl_idle_tout = idle_tout; - if (p_lcb->in_use && p_lcb->link_state == LST_CONNECTED && - !p_lcb->ccb_queue.p_first_ccb) { + if (p_lcb->in_use && p_lcb->link_state == LST_CONNECTED && !p_lcb->ccb_queue.p_first_ccb) { /* If there are no dynamic CCBs, (re)start the idle timer in case we changed * it */ l2cu_no_dynamic_ccbs(p_lcb); @@ -1527,15 +1499,14 @@ bool L2CA_SetChnlFlushability(uint16_t cid, bool is_flushable) { p_ccb = l2cu_find_ccb_by_cid(NULL, cid); if (p_ccb == NULL) { log::warn("L2CAP - no CCB for L2CA_SetChnlFlushability, CID: {}", cid); - return (false); + return false; } p_ccb->is_flushable = is_flushable; - log::verbose("L2CA_SetChnlFlushability() CID: 0x{:04x} is_flushable: {}", - cid, is_flushable); + log::verbose("L2CA_SetChnlFlushability() CID: 0x{:04x} is_flushable: {}", cid, is_flushable); - return (true); + return true; } /******************************************************************************* @@ -1560,18 +1531,17 @@ uint16_t L2CA_FlushChannel(uint16_t lcid, uint16_t num_to_flush) { p_ccb = l2cu_find_ccb_by_cid(NULL, lcid); if (!p_ccb || (p_ccb->p_lcb == NULL)) { - log::warn("L2CA_FlushChannel() abnormally returning 0 CID: 0x{:04x}", - lcid); - return (0); + log::warn("L2CA_FlushChannel() abnormally returning 0 CID: 0x{:04x}", lcid); + return 0; } p_lcb = p_ccb->p_lcb; if (num_to_flush != L2CAP_FLUSH_CHANS_GET) { log::verbose( - "L2CA_FlushChannel (FLUSH) CID: 0x{:04x} NumToFlush: {} QC: {} " - "pFirst: 0x{}", - lcid, num_to_flush, fixed_queue_length(p_ccb->xmit_hold_q), - fmt::ptr(fixed_queue_try_peek_first(p_ccb->xmit_hold_q))); + "L2CA_FlushChannel (FLUSH) CID: 0x{:04x} NumToFlush: {} QC: {} " + "pFirst: 0x{}", + lcid, num_to_flush, fixed_queue_length(p_ccb->xmit_hold_q), + fmt::ptr(fixed_queue_try_peek_first(p_ccb->xmit_hold_q))); } else { log::verbose("L2CA_FlushChannel (QUERY) CID: 0x{:04x}", lcid); } @@ -1579,8 +1549,7 @@ uint16_t L2CA_FlushChannel(uint16_t lcid, uint16_t num_to_flush) { /* Cannot flush eRTM buffers once they have a sequence number */ if (p_ccb->peer_cfg.fcr.mode != L2CAP_FCR_ERTM_MODE) { // Don't need send enhanced_flush to controller if it is LE transport. - if (p_lcb->transport != BT_TRANSPORT_LE && - num_to_flush != L2CAP_FLUSH_CHANS_GET) { + if (p_lcb->transport != BT_TRANSPORT_LE && num_to_flush != L2CAP_FLUSH_CHANS_GET) { /* If the controller supports enhanced flush, flush the data queued at the * controller */ if (bluetooth::shim::GetController()->SupportsNonFlushablePb() && @@ -1615,32 +1584,33 @@ uint16_t L2CA_FlushChannel(uint16_t lcid, uint16_t num_to_flush) { } /* If app needs to track all packets, call it */ - if ((p_ccb->p_rcb) && (p_ccb->p_rcb->api.pL2CA_TxComplete_Cb) && - (num_flushed2)) + if ((p_ccb->p_rcb) && (p_ccb->p_rcb->api.pL2CA_TxComplete_Cb) && (num_flushed2)) { (*p_ccb->p_rcb->api.pL2CA_TxComplete_Cb)(p_ccb->local_cid, num_flushed2); + } /* Now count how many are left */ for (const list_node_t* node = list_begin(p_lcb->link_xmit_data_q); node != list_end(p_lcb->link_xmit_data_q); node = list_next(node)) { BT_HDR* p_buf = (BT_HDR*)list_node(node); - if (p_buf->event == lcid) num_left++; + if (p_buf->event == lcid) { + num_left++; + } } /* Add in the number in the CCB xmit queue */ num_left += fixed_queue_length(p_ccb->xmit_hold_q); /* Return the local number of buffers left for the CID */ - log::verbose("L2CA_FlushChannel() flushed: {} + {}, num_left: {}", - num_flushed1, num_flushed2, num_left); + log::verbose("L2CA_FlushChannel() flushed: {} + {}, num_left: {}", num_flushed1, num_flushed2, + num_left); /* If we were congested, and now we are not, tell the app */ l2cu_check_channel_congestion(p_ccb); - return (num_left); + return num_left; } -bool L2CA_IsLinkEstablished(const RawAddress& bd_addr, - tBT_TRANSPORT transport) { +bool L2CA_IsLinkEstablished(const RawAddress& bd_addr, tBT_TRANSPORT transport) { return l2cu_find_lcb_by_bd_addr(bd_addr, transport) != nullptr; } @@ -1672,8 +1642,7 @@ void L2CA_SetMediaStreamChannel(uint16_t local_media_cid, bool status) { return; } - log::debug("local_media_cid={}, status={}", local_media_cid, - status ? "add" : "remove"); + log::debug("local_media_cid={}, status={}", local_media_cid, status ? "add" : "remove"); if (status) { for (i = 0; i < MAX_ACTIVE_AVDT_CONN; i++) { @@ -1688,49 +1657,40 @@ void L2CA_SetMediaStreamChannel(uint16_t local_media_cid, bool status) { return; } - av_media_channels[set_channel].p_ccb = - l2cu_find_ccb_by_cid(NULL, local_media_cid); + av_media_channels[set_channel].p_ccb = l2cu_find_ccb_by_cid(NULL, local_media_cid); - if (!av_media_channels[set_channel].p_ccb || - !av_media_channels[set_channel].p_ccb->p_lcb) { + if (!av_media_channels[set_channel].p_ccb || !av_media_channels[set_channel].p_ccb->p_lcb) { return; } av_media_channels[set_channel].local_cid = local_media_cid; - snoop_logger->AddA2dpMediaChannel( - av_media_channels[set_channel].p_ccb->p_lcb->Handle(), - av_media_channels[set_channel].local_cid, - av_media_channels[set_channel].p_ccb->remote_cid); + snoop_logger->AddA2dpMediaChannel(av_media_channels[set_channel].p_ccb->p_lcb->Handle(), + av_media_channels[set_channel].local_cid, + av_media_channels[set_channel].p_ccb->remote_cid); - log::verbose( - "Set A2DP media snoop filtering for local_cid: {}, remote_cid: {}", - local_media_cid, av_media_channels[set_channel].p_ccb->remote_cid); + log::verbose("Set A2DP media snoop filtering for local_cid: {}, remote_cid: {}", + local_media_cid, av_media_channels[set_channel].p_ccb->remote_cid); } else { for (i = 0; i < MAX_ACTIVE_AVDT_CONN; i++) { - if (av_media_channels[i].is_active && - av_media_channels[i].local_cid == local_media_cid) { + if (av_media_channels[i].is_active && av_media_channels[i].local_cid == local_media_cid) { set_channel = i; break; } } if (set_channel < 0) { - log::error("The channel {} not found in active media channels", - local_media_cid); + log::error("The channel {} not found in active media channels", local_media_cid); return; } - if (!av_media_channels[set_channel].p_ccb || - !av_media_channels[set_channel].p_ccb->p_lcb) { + if (!av_media_channels[set_channel].p_ccb || !av_media_channels[set_channel].p_ccb->p_lcb) { return; } - snoop_logger->RemoveA2dpMediaChannel( - av_media_channels[set_channel].p_ccb->p_lcb->Handle(), - av_media_channels[set_channel].local_cid); + snoop_logger->RemoveA2dpMediaChannel(av_media_channels[set_channel].p_ccb->p_lcb->Handle(), + av_media_channels[set_channel].local_cid); - log::verbose("Reset A2DP media snoop filtering for local_cid: {}", - local_media_cid); + log::verbose("Reset A2DP media snoop filtering for local_cid: {}", local_media_cid); } av_media_channels[set_channel].is_active = status; @@ -1751,8 +1711,7 @@ void L2CA_SetMediaStreamChannel(uint16_t local_media_cid, bool status) { ** Returns bool ** *******************************************************************************/ -bool L2CA_isMediaChannel(uint16_t handle, uint16_t channel_id, - bool is_local_cid) { +bool L2CA_isMediaChannel(uint16_t handle, uint16_t channel_id, bool is_local_cid) { int i; bool ret = false; @@ -1761,10 +1720,8 @@ bool L2CA_isMediaChannel(uint16_t handle, uint16_t channel_id, if (!av_media_channels[i].p_ccb || !av_media_channels[i].p_ccb->p_lcb) { continue; } - if (((!is_local_cid && - channel_id == av_media_channels[i].p_ccb->remote_cid) || - (is_local_cid && - channel_id == av_media_channels[i].p_ccb->local_cid)) && + if (((!is_local_cid && channel_id == av_media_channels[i].p_ccb->remote_cid) || + (is_local_cid && channel_id == av_media_channels[i].p_ccb->local_cid)) && handle == av_media_channels[i].p_ccb->p_lcb->Handle()) { ret = true; break; @@ -1783,17 +1740,17 @@ void L2CA_Dumpsys(int fd) { LOG_DUMPSYS_TITLE(fd, DUMPSYS_TAG); for (int i = 0; i < MAX_L2CAP_LINKS; i++) { const tL2C_LCB& lcb = l2cb.lcb_pool[i]; - if (!lcb.in_use) continue; + if (!lcb.in_use) { + continue; + } LOG_DUMPSYS(fd, "link_state:%s", link_state_text(lcb.link_state).c_str()); LOG_DUMPSYS(fd, "handle:0x%04x", lcb.Handle()); const tL2C_CCB* ccb = lcb.ccb_queue.p_first_ccb; while (ccb != nullptr) { - LOG_DUMPSYS( - fd, " active channel lcid:0x%04x rcid:0x%04x is_ecoc:%s in_use:%s", - ccb->local_cid, ccb->remote_cid, - ccb->ecoc ? "true" : "false", - ccb->in_use ? "true" : "false"); + LOG_DUMPSYS(fd, " active channel lcid:0x%04x rcid:0x%04x is_ecoc:%s in_use:%s", + ccb->local_cid, ccb->remote_cid, ccb->ecoc ? "true" : "false", + ccb->in_use ? "true" : "false"); ccb = ccb->p_next_ccb; } } diff --git a/system/stack/l2cap/l2c_ble.cc b/system/stack/l2cap/l2c_ble.cc index e642ef325b1..bbf13d53c40 100644 --- a/system/stack/l2cap/l2c_ble.cc +++ b/system/stack/l2cap/l2c_ble.cc @@ -92,7 +92,7 @@ hci_role_t L2CA_GetBleConnRole(const RawAddress& bd_addr) { * * Function l2cble_notify_le_connection * - * Description This function notifiy the l2cap connection to the app layer + * Description This function notify the l2cap connection to the app layer * * Returns none * @@ -104,8 +104,7 @@ void l2cble_notify_le_connection(const RawAddress& bda) { return; } - if (BTM_IsAclConnectionUp(bda, BT_TRANSPORT_LE) && - p_lcb->link_state != LST_CONNECTED) { + if (BTM_IsAclConnectionUp(bda, BT_TRANSPORT_LE) && p_lcb->link_state != LST_CONNECTED) { /* update link status */ // TODO Move this back into acl layer btm_establish_continue_from_address(bda, BT_TRANSPORT_LE); @@ -115,18 +114,18 @@ void l2cble_notify_le_connection(const RawAddress& bda) { } /* For all channels, send the event through their FSMs */ - for (tL2C_CCB* p_ccb = p_lcb->ccb_queue.p_first_ccb; p_ccb; - p_ccb = p_ccb->p_next_ccb) { - if (p_ccb->chnl_state == CST_CLOSED) + for (tL2C_CCB* p_ccb = p_lcb->ccb_queue.p_first_ccb; p_ccb; p_ccb = p_ccb->p_next_ccb) { + if (p_ccb->chnl_state == CST_CLOSED) { l2c_csm_execute(p_ccb, L2CEVT_LP_CONNECT_CFM, NULL); + } } } /** This function is called when an HCI Connection Complete event is received. */ bool l2cble_conn_comp(uint16_t handle, tHCI_ROLE role, const RawAddress& bda, - tBLE_ADDR_TYPE /* type */, uint16_t conn_interval, - uint16_t conn_latency, uint16_t conn_timeout) { + tBLE_ADDR_TYPE /* type */, uint16_t conn_interval, uint16_t conn_latency, + uint16_t conn_timeout) { // role == HCI_ROLE_CENTRAL => scanner completed connection // role == HCI_ROLE_PERIPHERAL => advertiser completed connection @@ -148,12 +147,14 @@ bool l2cble_conn_comp(uint16_t handle, tHCI_ROLE role, const RawAddress& bda, p_lcb->link_state = LST_CONNECTING; } else if (role == HCI_ROLE_CENTRAL && p_lcb->link_state != LST_CONNECTING) { log::error( - "Received le acl connection as role central but not in connecting " - "state"); + "Received le acl connection as role central but not in connecting " + "state"); return false; } - if (role == HCI_ROLE_CENTRAL) alarm_cancel(p_lcb->l2c_lcb_timer); + if (role == HCI_ROLE_CENTRAL) { + alarm_cancel(p_lcb->l2c_lcb_timer); + } /* Save the handle */ l2cu_set_lcb_handle(*p_lcb, handle); @@ -184,13 +185,11 @@ bool l2cble_conn_comp(uint16_t handle, tHCI_ROLE role, const RawAddress& bda, p_lcb->cont_num = 0; p_lcb->supervision_tout = 0; - p_lcb->peer_chnl_mask[0] = L2CAP_FIXED_CHNL_ATT_BIT | - L2CAP_FIXED_CHNL_BLE_SIG_BIT | - L2CAP_FIXED_CHNL_SMP_BIT; + p_lcb->peer_chnl_mask[0] = + L2CAP_FIXED_CHNL_ATT_BIT | L2CAP_FIXED_CHNL_BLE_SIG_BIT | L2CAP_FIXED_CHNL_SMP_BIT; if (role == HCI_ROLE_PERIPHERAL) { - if (!bluetooth::shim::GetController() - ->SupportsBlePeripheralInitiatedFeaturesExchange()) { + if (!bluetooth::shim::GetController()->SupportsBlePeripheralInitiatedFeaturesExchange()) { p_lcb->link_state = LST_CONNECTED; l2cu_process_fixed_chnl_resp(p_lcb); } @@ -208,14 +207,12 @@ bool l2cble_conn_comp(uint16_t handle, tHCI_ROLE role, const RawAddress& bda, * Returns void * ******************************************************************************/ -static void l2cble_handle_connect_rsp_neg(tL2C_LCB* p_lcb, - tL2C_CONN_INFO* con_info) { +static void l2cble_handle_connect_rsp_neg(tL2C_LCB* p_lcb, tL2C_CONN_INFO* con_info) { tL2C_CCB* temp_p_ccb = NULL; for (int i = 0; i < p_lcb->pending_ecoc_conn_cnt; i++) { uint16_t cid = p_lcb->pending_ecoc_connection_cids[i]; temp_p_ccb = l2cu_find_ccb_by_cid(p_lcb, cid); - l2c_csm_execute(temp_p_ccb, L2CEVT_L2CAP_CREDIT_BASED_CONNECT_RSP_NEG, - con_info); + l2c_csm_execute(temp_p_ccb, L2CEVT_L2CAP_CREDIT_BASED_CONNECT_RSP_NEG, con_info); } p_lcb->pending_ecoc_conn_cnt = 0; @@ -257,8 +254,8 @@ void l2cble_process_sig_cmd(tL2C_LCB* p_lcb, uint8_t* p, uint16_t pkt_len) { /* Check command length does not exceed packet length */ if ((p + cmd_len) > p_pkt_end) { - log::warn("L2CAP - LE - format error, pkt_len: {} cmd_len: {} code: {}", - pkt_len, cmd_len, cmd_code); + log::warn("L2CAP - LE - format error, pkt_len: {} cmd_len: {} code: {}", pkt_len, cmd_len, + cmd_code); return; } @@ -268,15 +265,14 @@ void l2cble_process_sig_cmd(tL2C_LCB* p_lcb, uint8_t* p, uint16_t pkt_len) { if (p + 2 > p_pkt_end) { log::error( - "invalid L2CAP_CMD_REJECT packet, not containing enough data for " - "`reason` field"); + "invalid L2CAP_CMD_REJECT packet, not containing enough data for " + "`reason` field"); return; } STREAM_TO_UINT16(reason, p); - if (reason == L2CAP_CMD_REJ_NOT_UNDERSTOOD && - p_lcb->pending_ecoc_conn_cnt > 0) { + if (reason == L2CAP_CMD_REJ_NOT_UNDERSTOOD && p_lcb->pending_ecoc_conn_cnt > 0) { con_info.l2cap_result = L2CAP_LE_RESULT_NO_PSM; l2cble_handle_connect_rsp_neg(p_lcb, &con_info); } @@ -302,19 +298,16 @@ void l2cble_process_sig_cmd(tL2C_LCB* p_lcb, uint8_t* p, uint16_t pkt_len) { /* If we are a central, the peripheral wants to update the parameters */ if (p_lcb->IsLinkRoleCentral()) { L2CA_AdjustConnectionIntervals( - &min_interval, &max_interval, - osi_property_get_int32("bluetooth.core.le.min_connection_interval", - BTM_BLE_CONN_INT_MIN_LIMIT)); - - if (min_interval < BTM_BLE_CONN_INT_MIN || - min_interval > BTM_BLE_CONN_INT_MAX || - max_interval < BTM_BLE_CONN_INT_MIN || - max_interval > BTM_BLE_CONN_INT_MAX || + &min_interval, &max_interval, + osi_property_get_int32("bluetooth.core.le.min_connection_interval", + BTM_BLE_CONN_INT_MIN_LIMIT)); + + if (min_interval < BTM_BLE_CONN_INT_MIN || min_interval > BTM_BLE_CONN_INT_MAX || + max_interval < BTM_BLE_CONN_INT_MIN || max_interval > BTM_BLE_CONN_INT_MAX || latency > BTM_BLE_CONN_LATENCY_MAX || /*(timeout >= max_interval && latency > (timeout * 10/(max_interval - * 1.25) - 1)) ||*/ - timeout < BTM_BLE_CONN_SUP_TOUT_MIN || - timeout > BTM_BLE_CONN_SUP_TOUT_MAX || + * 1.25) - 1)) ||*/ + timeout < BTM_BLE_CONN_SUP_TOUT_MIN || timeout > BTM_BLE_CONN_SUP_TOUT_MAX || max_interval < min_interval) { l2cu_send_peer_ble_par_rsp(p_lcb, L2CAP_CFG_UNACCEPTABLE_PARAMS, id); } else { @@ -328,9 +321,9 @@ void l2cble_process_sig_cmd(tL2C_LCB* p_lcb, uint8_t* p, uint16_t pkt_len) { l2cble_start_conn_update(p_lcb); } - } else - l2cu_send_peer_cmd_reject(p_lcb, L2CAP_CMD_REJ_NOT_UNDERSTOOD, id, 0, - 0); + } else { + l2cu_send_peer_cmd_reject(p_lcb, L2CAP_CMD_REJ_NOT_UNDERSTOOD, id, 0, 0); + } break; case L2CAP_CMD_BLE_UPDATE_RSP: @@ -351,53 +344,45 @@ void l2cble_process_sig_cmd(tL2C_LCB* p_lcb, uint8_t* p, uint16_t pkt_len) { /* Check how many channels remote side wants. */ num_of_channels = (p_pkt_end - p) / sizeof(uint16_t); if (num_of_channels > L2CAP_CREDIT_BASED_MAX_CIDS) { - log::warn("L2CAP - invalid number of channels requested: {}", - num_of_channels); - l2cu_reject_credit_based_conn_req(p_lcb, id, - L2CAP_CREDIT_BASED_MAX_CIDS, + log::warn("L2CAP - invalid number of channels requested: {}", num_of_channels); + l2cu_reject_credit_based_conn_req(p_lcb, id, L2CAP_CREDIT_BASED_MAX_CIDS, L2CAP_LE_RESULT_INVALID_PARAMETERS); return; } log::debug( - "Recv L2CAP_CMD_CREDIT_BASED_CONN_REQ with mtu = {}, mps = {}, " - "initial credit = {}num_of_channels = {}", - mtu, mps, initial_credit, num_of_channels); + "Recv L2CAP_CMD_CREDIT_BASED_CONN_REQ with mtu = {}, mps = {}, " + "initial credit = {}num_of_channels = {}", + mtu, mps, initial_credit, num_of_channels); /* Check PSM Support */ p_rcb = l2cu_find_ble_rcb_by_psm(con_info.psm); if (p_rcb == NULL) { - log::warn("L2CAP - rcvd conn req for unknown PSM: 0x{:04x}", - con_info.psm); - l2cu_reject_credit_based_conn_req(p_lcb, id, num_of_channels, - L2CAP_LE_RESULT_NO_PSM); + log::warn("L2CAP - rcvd conn req for unknown PSM: 0x{:04x}", con_info.psm); + l2cu_reject_credit_based_conn_req(p_lcb, id, num_of_channels, L2CAP_LE_RESULT_NO_PSM); return; } if (p_lcb->pending_ecoc_conn_cnt > 0) { log::warn("L2CAP - L2CAP_CMD_CREDIT_BASED_CONN_REQ collision:"); - if (p_rcb->api.pL2CA_CreditBasedCollisionInd_Cb && - con_info.psm == BT_PSM_EATT) { + if (p_rcb->api.pL2CA_CreditBasedCollisionInd_Cb && con_info.psm == BT_PSM_EATT) { (*p_rcb->api.pL2CA_CreditBasedCollisionInd_Cb)(p_lcb->remote_bd_addr); } - l2cu_reject_credit_based_conn_req(p_lcb, id, num_of_channels, - L2CAP_LE_RESULT_NO_RESOURCES); + l2cu_reject_credit_based_conn_req(p_lcb, id, num_of_channels, L2CAP_LE_RESULT_NO_RESOURCES); return; } p_lcb->pending_ecoc_conn_cnt = num_of_channels; if (!p_rcb->api.pL2CA_CreditBasedConnectInd_Cb) { - log::warn("L2CAP - rcvd conn req for outgoing-only connection PSM: {}", - con_info.psm); - l2cu_reject_credit_based_conn_req(p_lcb, id, num_of_channels, - L2CAP_CONN_NO_PSM); + log::warn("L2CAP - rcvd conn req for outgoing-only connection PSM: {}", con_info.psm); + l2cu_reject_credit_based_conn_req(p_lcb, id, num_of_channels, L2CAP_CONN_NO_PSM); return; } /* validate the parameters */ - if (mtu < L2CAP_CREDIT_BASED_MIN_MTU || - mps < L2CAP_CREDIT_BASED_MIN_MPS || mps > L2CAP_LE_MAX_MPS) { + if (mtu < L2CAP_CREDIT_BASED_MIN_MTU || mps < L2CAP_CREDIT_BASED_MIN_MPS || + mps > L2CAP_LE_MAX_MPS) { log::error("L2CAP don't like the params"); l2cu_reject_credit_based_conn_req(p_lcb, id, num_of_channels, L2CAP_LE_RESULT_INVALID_PARAMETERS); @@ -412,12 +397,10 @@ void l2cble_process_sig_cmd(tL2C_LCB* p_lcb, uint8_t* p, uint16_t pkt_len) { if (temp_p_ccb) { log::warn("L2CAP - rcvd conn req for duplicated cid: 0x{:04x}", rcid); p_lcb->pending_ecoc_connection_cids[i] = 0; - p_lcb->pending_l2cap_result = - L2CAP_LE_RESULT_SOURCE_CID_ALREADY_ALLOCATED; + p_lcb->pending_l2cap_result = L2CAP_LE_RESULT_SOURCE_CID_ALREADY_ALLOCATED; } else { /* Allocate a ccb for this.*/ - temp_p_ccb = l2cu_allocate_ccb( - p_lcb, 0, con_info.psm == BT_PSM_EATT /* is_eatt */); + temp_p_ccb = l2cu_allocate_ccb(p_lcb, 0, con_info.psm == BT_PSM_EATT /* is_eatt */); if (temp_p_ccb == NULL) { log::error("L2CAP - unable to allocate CCB"); p_lcb->pending_ecoc_connection_cids[i] = 0; @@ -447,9 +430,8 @@ void l2cble_process_sig_cmd(tL2C_LCB* p_lcb, uint8_t* p, uint16_t pkt_len) { if (!lead_cid_set) { p_ccb = temp_p_ccb; p_ccb->local_conn_cfg.mtu = L2CAP_SDU_LENGTH_LE_MAX; - p_ccb->local_conn_cfg.mps = bluetooth::shim::GetController() - ->GetLeBufferSize() - .le_data_packet_length_; + p_ccb->local_conn_cfg.mps = + bluetooth::shim::GetController()->GetLeBufferSize().le_data_packet_length_; p_lcb->pending_lead_cid = p_ccb->local_cid; lead_cid_set = true; } @@ -458,8 +440,7 @@ void l2cble_process_sig_cmd(tL2C_LCB* p_lcb, uint8_t* p, uint16_t pkt_len) { if (!lead_cid_set) { log::error("L2CAP - unable to allocate CCB"); - l2cu_reject_credit_based_conn_req(p_lcb, id, num_of_channels, - p_lcb->pending_l2cap_result); + l2cu_reject_credit_based_conn_req(p_lcb, id, num_of_channels, p_lcb->pending_l2cap_result); return; } @@ -499,8 +480,7 @@ void l2cble_process_sig_cmd(tL2C_LCB* p_lcb, uint8_t* p, uint16_t pkt_len) { * all the channels has been rejected */ if (con_info.l2cap_result == L2CAP_LE_RESULT_NO_PSM || - con_info.l2cap_result == - L2CAP_LE_RESULT_INSUFFICIENT_AUTHENTICATION || + con_info.l2cap_result == L2CAP_LE_RESULT_INSUFFICIENT_AUTHENTICATION || con_info.l2cap_result == L2CAP_LE_RESULT_INSUFFICIENT_ENCRYP || con_info.l2cap_result == L2CAP_LE_RESULT_INSUFFICIENT_AUTHORIZATION || con_info.l2cap_result == L2CAP_LE_RESULT_UNACCEPTABLE_PARAMETERS || @@ -511,8 +491,8 @@ void l2cble_process_sig_cmd(tL2C_LCB* p_lcb, uint8_t* p, uint16_t pkt_len) { } /* validate the parameters */ - if (mtu < L2CAP_CREDIT_BASED_MIN_MTU || - mps < L2CAP_CREDIT_BASED_MIN_MPS || mps > L2CAP_LE_MAX_MPS) { + if (mtu < L2CAP_CREDIT_BASED_MIN_MTU || mps < L2CAP_CREDIT_BASED_MIN_MPS || + mps > L2CAP_LE_MAX_MPS) { log::error("L2CAP - invalid params"); con_info.l2cap_result = L2CAP_LE_RESULT_INVALID_PARAMETERS; l2cble_handle_connect_rsp_neg(p_lcb, &con_info); @@ -524,16 +504,16 @@ void l2cble_process_sig_cmd(tL2C_LCB* p_lcb, uint8_t* p, uint16_t pkt_len) { num_of_channels = (p_pkt_end - p) / sizeof(uint16_t); if (num_of_channels != p_lcb->pending_ecoc_conn_cnt) { log::error( - "Incorrect response.expected num of channels = {} received num of " - "channels = {}", - num_of_channels, p_lcb->pending_ecoc_conn_cnt); + "Incorrect response.expected num of channels = {} received num of " + "channels = {}", + num_of_channels, p_lcb->pending_ecoc_conn_cnt); return; } log::verbose( - "mtu = {}, mps = {}, initial_credit = {}, con_info.l2cap_result = " - "{} num_of_channels = {}", - mtu, mps, initial_credit, con_info.l2cap_result, num_of_channels); + "mtu = {}, mps = {}, initial_credit = {}, con_info.l2cap_result = " + "{} num_of_channels = {}", + mtu, mps, initial_credit, con_info.l2cap_result, num_of_channels); con_info.peer_mtu = mtu; @@ -541,10 +521,8 @@ void l2cble_process_sig_cmd(tL2C_LCB* p_lcb, uint8_t* p, uint16_t pkt_len) { * needed in the callback. */ p_lcb->pending_ecoc_conn_cnt = 0; uint16_t cids[L2CAP_CREDIT_BASED_MAX_CIDS]; - std::copy_n(p_lcb->pending_ecoc_connection_cids, - L2CAP_CREDIT_BASED_MAX_CIDS, cids); - std::fill_n(p_lcb->pending_ecoc_connection_cids, - L2CAP_CREDIT_BASED_MAX_CIDS, 0); + std::copy_n(p_lcb->pending_ecoc_connection_cids, L2CAP_CREDIT_BASED_MAX_CIDS, cids); + std::fill_n(p_lcb->pending_ecoc_connection_cids, L2CAP_CREDIT_BASED_MAX_CIDS, 0); for (int i = 0; i < num_of_channels; i++) { uint16_t cid = cids[i]; @@ -557,17 +535,15 @@ void l2cble_process_sig_cmd(tL2C_LCB* p_lcb, uint8_t* p, uint16_t pkt_len) { temp_p_ccb = l2cu_find_ccb_by_remote_cid(p_lcb, rcid); if (temp_p_ccb != nullptr) { log::error( - "Already Allocated Destination cid. rcid = {} send " - "peer_disc_req", - rcid); + "Already Allocated Destination cid. rcid = {} send " + "peer_disc_req", + rcid); l2cu_send_peer_disc_req(temp_p_ccb); temp_p_ccb = l2cu_find_ccb_by_cid(p_lcb, cid); con_info.l2cap_result = L2CAP_LE_RESULT_UNACCEPTABLE_PARAMETERS; - l2c_csm_execute(temp_p_ccb, - L2CEVT_L2CAP_CREDIT_BASED_CONNECT_RSP_NEG, - &con_info); + l2c_csm_execute(temp_p_ccb, L2CEVT_L2CAP_CREDIT_BASED_CONNECT_RSP_NEG, &con_info); continue; } } @@ -575,15 +551,13 @@ void l2cble_process_sig_cmd(tL2C_LCB* p_lcb, uint8_t* p, uint16_t pkt_len) { temp_p_ccb = l2cu_find_ccb_by_cid(p_lcb, cid); temp_p_ccb->remote_cid = rcid; - log::verbose("local cid = {} remote cid = {}", cid, - temp_p_ccb->remote_cid); + log::verbose("local cid = {} remote cid = {}", cid, temp_p_ccb->remote_cid); /* Check if peer accepted channel, if not release the one not * created */ if (temp_p_ccb->remote_cid == 0) { - l2c_csm_execute(temp_p_ccb, L2CEVT_L2CAP_CREDIT_BASED_CONNECT_RSP_NEG, - &con_info); + l2c_csm_execute(temp_p_ccb, L2CEVT_L2CAP_CREDIT_BASED_CONNECT_RSP_NEG, &con_info); } else { temp_p_ccb->tx_mps = mps; temp_p_ccb->ble_sdu = NULL; @@ -594,8 +568,7 @@ void l2cble_process_sig_cmd(tL2C_LCB* p_lcb, uint8_t* p, uint16_t pkt_len) { temp_p_ccb->peer_conn_cfg.mps = mps; temp_p_ccb->peer_conn_cfg.credits = initial_credit; - l2c_csm_execute(temp_p_ccb, L2CEVT_L2CAP_CREDIT_BASED_CONNECT_RSP, - &con_info); + l2c_csm_execute(temp_p_ccb, L2CEVT_L2CAP_CREDIT_BASED_CONNECT_RSP, &con_info); } } @@ -610,8 +583,8 @@ void l2cble_process_sig_cmd(tL2C_LCB* p_lcb, uint8_t* p, uint16_t pkt_len) { STREAM_TO_UINT16(mps, p); /* validate the parameters */ - if (mtu < L2CAP_CREDIT_BASED_MIN_MTU || - mps < L2CAP_CREDIT_BASED_MIN_MPS || mps > L2CAP_LE_MAX_MPS) { + if (mtu < L2CAP_CREDIT_BASED_MIN_MTU || mps < L2CAP_CREDIT_BASED_MIN_MPS || + mps > L2CAP_LE_MAX_MPS) { log::error("L2CAP - invalid params"); l2cu_send_ble_reconfig_rsp(p_lcb, id, L2CAP_RECONFIG_UNACCAPTED_PARAM); return; @@ -621,36 +594,31 @@ void l2cble_process_sig_cmd(tL2C_LCB* p_lcb, uint8_t* p, uint16_t pkt_len) { num_of_channels = (p_pkt_end - p) / sizeof(uint16_t); log::verbose( - "Recv L2CAP_CMD_CREDIT_BASED_RECONFIG_REQ with mtu = {}, mps = {}, " - "num_of_channels = {}", - mtu, mps, num_of_channels); + "Recv L2CAP_CMD_CREDIT_BASED_RECONFIG_REQ with mtu = {}, mps = {}, " + "num_of_channels = {}", + mtu, mps, num_of_channels); uint8_t* p_tmp = p; for (int i = 0; i < num_of_channels; i++) { STREAM_TO_UINT16(rcid, p_tmp); p_ccb = l2cu_find_ccb_by_remote_cid(p_lcb, rcid); if (!p_ccb) { - log::warn("L2CAP - rcvd config req for non existing cid: 0x{:04x}", - rcid); + log::warn("L2CAP - rcvd config req for non existing cid: 0x{:04x}", rcid); l2cu_send_ble_reconfig_rsp(p_lcb, id, L2CAP_RECONFIG_INVALID_DCID); return; } if (p_ccb->peer_conn_cfg.mtu > mtu) { - log::warn( - "L2CAP - rcvd config req mtu reduction new mtu < mtu ({} < {})", - mtu, p_ccb->peer_conn_cfg.mtu); - l2cu_send_ble_reconfig_rsp(p_lcb, id, - L2CAP_RECONFIG_REDUCTION_MTU_NO_ALLOWED); + log::warn("L2CAP - rcvd config req mtu reduction new mtu < mtu ({} < {})", mtu, + p_ccb->peer_conn_cfg.mtu); + l2cu_send_ble_reconfig_rsp(p_lcb, id, L2CAP_RECONFIG_REDUCTION_MTU_NO_ALLOWED); return; } if (p_ccb->peer_conn_cfg.mps > mps && num_of_channels > 1) { - log::warn( - "L2CAP - rcvd config req mps reduction new mps < mps ({} < {})", - mtu, p_ccb->peer_conn_cfg.mtu); - l2cu_send_ble_reconfig_rsp(p_lcb, id, - L2CAP_RECONFIG_REDUCTION_MPS_NO_ALLOWED); + log::warn("L2CAP - rcvd config req mps reduction new mps < mps ({} < {})", mtu, + p_ccb->peer_conn_cfg.mtu); + l2cu_send_ble_reconfig_rsp(p_lcb, id, L2CAP_RECONFIG_REDUCTION_MPS_NO_ALLOWED); return; } } @@ -684,9 +652,7 @@ void l2cble_process_sig_cmd(tL2C_LCB* p_lcb, uint8_t* p, uint16_t pkt_len) { } STREAM_TO_UINT16(result, p); - log::verbose( - "Recv L2CAP_CMD_CREDIT_BASED_RECONFIG_RES for result = 0x{:04x}", - result); + log::verbose("Recv L2CAP_CMD_CREDIT_BASED_RECONFIG_RES for result = 0x{:04x}", result); p_lcb->pending_ecoc_reconfig_cfg.result = result; @@ -722,37 +688,32 @@ void l2cble_process_sig_cmd(tL2C_LCB* p_lcb, uint8_t* p, uint16_t pkt_len) { STREAM_TO_UINT16(initial_credit, p); log::verbose( - "Recv L2CAP_CMD_BLE_CREDIT_BASED_CONN_REQ with mtu = {}, mps = {}, " - "initial credit = {}", - mtu, mps, initial_credit); + "Recv L2CAP_CMD_BLE_CREDIT_BASED_CONN_REQ with mtu = {}, mps = {}, " + "initial credit = {}", + mtu, mps, initial_credit); p_ccb = l2cu_find_ccb_by_remote_cid(p_lcb, rcid); if (p_ccb) { log::warn("L2CAP - rcvd conn req for duplicated cid: 0x{:04x}", rcid); - l2cu_reject_ble_coc_connection( - p_lcb, id, L2CAP_LE_RESULT_SOURCE_CID_ALREADY_ALLOCATED); + l2cu_reject_ble_coc_connection(p_lcb, id, L2CAP_LE_RESULT_SOURCE_CID_ALREADY_ALLOCATED); break; } p_rcb = l2cu_find_ble_rcb_by_psm(con_info.psm); if (p_rcb == NULL) { - log::warn("L2CAP - rcvd conn req for unknown PSM: 0x{:04x}", - con_info.psm); + log::warn("L2CAP - rcvd conn req for unknown PSM: 0x{:04x}", con_info.psm); l2cu_reject_ble_coc_connection(p_lcb, id, L2CAP_LE_RESULT_NO_PSM); break; } else { if (!p_rcb->api.pL2CA_ConnectInd_Cb) { - log::warn( - "L2CAP - rcvd conn req for outgoing-only connection PSM: {}", - con_info.psm); + log::warn("L2CAP - rcvd conn req for outgoing-only connection PSM: {}", con_info.psm); l2cu_reject_ble_coc_connection(p_lcb, id, L2CAP_CONN_NO_PSM); break; } } /* Allocate a ccb for this.*/ - p_ccb = l2cu_allocate_ccb(p_lcb, 0, - con_info.psm == BT_PSM_EATT /* is_eatt */); + p_ccb = l2cu_allocate_ccb(p_lcb, 0, con_info.psm == BT_PSM_EATT /* is_eatt */); if (p_ccb == NULL) { log::error("L2CAP - unable to allocate CCB"); l2cu_reject_ble_connection(p_ccb, id, L2CAP_CONN_NO_RESOURCES); @@ -760,8 +721,7 @@ void l2cble_process_sig_cmd(tL2C_LCB* p_lcb, uint8_t* p, uint16_t pkt_len) { } /* validate the parameters */ - if (mtu < L2CAP_LE_MIN_MTU || mps < L2CAP_LE_MIN_MPS || - mps > L2CAP_LE_MAX_MPS) { + if (mtu < L2CAP_LE_MIN_MTU || mps < L2CAP_LE_MIN_MPS || mps > L2CAP_LE_MAX_MPS) { log::error("L2CAP do not like the params"); l2cu_reject_ble_connection(p_ccb, id, L2CAP_CONN_NO_RESOURCES); break; @@ -772,9 +732,8 @@ void l2cble_process_sig_cmd(tL2C_LCB* p_lcb, uint8_t* p, uint16_t pkt_len) { p_ccb->remote_cid = rcid; p_ccb->local_conn_cfg.mtu = L2CAP_SDU_LENGTH_LE_MAX; - p_ccb->local_conn_cfg.mps = bluetooth::shim::GetController() - ->GetLeBufferSize() - .le_data_packet_length_; + p_ccb->local_conn_cfg.mps = + bluetooth::shim::GetController()->GetLeBufferSize().le_data_packet_length_; p_ccb->local_conn_cfg.credits = L2CA_LeCreditDefault(); p_ccb->remote_credit_count = L2CA_LeCreditDefault(); @@ -818,11 +777,10 @@ void l2cble_process_sig_cmd(tL2C_LCB* p_lcb, uint8_t* p, uint16_t pkt_len) { con_info.remote_cid = p_ccb->remote_cid; log::verbose( - "remote_cid = {}, mtu = {}, mps = {}, initial_credit = {}, " - "con_info.l2cap_result = {}", - p_ccb->remote_cid, p_ccb->peer_conn_cfg.mtu, - p_ccb->peer_conn_cfg.mps, p_ccb->peer_conn_cfg.credits, - con_info.l2cap_result); + "remote_cid = {}, mtu = {}, mps = {}, initial_credit = {}, " + "con_info.l2cap_result = {}", + p_ccb->remote_cid, p_ccb->peer_conn_cfg.mtu, p_ccb->peer_conn_cfg.mps, + p_ccb->peer_conn_cfg.credits, con_info.l2cap_result); /* validate the parameters */ if (p_ccb->peer_conn_cfg.mtu < L2CAP_LE_MIN_MTU || @@ -840,10 +798,11 @@ void l2cble_process_sig_cmd(tL2C_LCB* p_lcb, uint8_t* p, uint16_t pkt_len) { p_ccb->is_first_seg = true; p_ccb->peer_cfg.fcr.mode = L2CAP_FCR_LE_COC_MODE; - if (con_info.l2cap_result == L2CAP_LE_RESULT_CONN_OK) + if (con_info.l2cap_result == L2CAP_LE_RESULT_CONN_OK) { l2c_csm_execute(p_ccb, L2CEVT_L2CAP_CONNECT_RSP, &con_info); - else + } else { l2c_csm_execute(p_ccb, L2CEVT_L2CAP_CONNECT_RSP_NEG, &con_info); + } } else { log::verbose("I DO NOT remember the connection req"); con_info.l2cap_result = L2CAP_LE_RESULT_INVALID_SOURCE_CID; @@ -882,8 +841,9 @@ void l2cble_process_sig_cmd(tL2C_LCB* p_lcb, uint8_t* p, uint16_t pkt_len) { p_ccb->remote_id = id; l2c_csm_execute(p_ccb, L2CEVT_L2CAP_DISCONNECT_REQ, NULL); } - } else + } else { l2cu_send_peer_cmd_reject(p_lcb, L2CAP_CMD_REJ_INVALID_CID, id, 0, 0); + } break; @@ -897,8 +857,9 @@ void l2cble_process_sig_cmd(tL2C_LCB* p_lcb, uint8_t* p, uint16_t pkt_len) { p_ccb = l2cu_find_ccb_by_cid(p_lcb, lcid); if (p_ccb != NULL) { - if ((p_ccb->remote_cid == rcid) && (p_ccb->local_id == id)) + if ((p_ccb->remote_cid == rcid) && (p_ccb->local_id == id)) { l2c_csm_execute(p_ccb, L2CEVT_L2CAP_DISCONNECT_RSP, NULL); + } } break; @@ -920,14 +881,14 @@ bool l2cble_create_conn(tL2C_LCB* p_lcb) { // TODO: we should not need this timer at all, the connection failure should // be reported from lower layer - alarm_set_on_mloop(p_lcb->l2c_lcb_timer, L2CAP_BLE_LINK_CONNECT_TIMEOUT_MS, - l2c_lcb_timer_timeout, p_lcb); + alarm_set_on_mloop(p_lcb->l2c_lcb_timer, L2CAP_BLE_LINK_CONNECT_TIMEOUT_MS, l2c_lcb_timer_timeout, + p_lcb); return true; } /******************************************************************************* * - * Function l2c_link_processs_ble_num_bufs + * Function l2c_link_process_ble_num_bufs * * Description This function is called when a "controller buffer size" * event is first received from the controller. It updates @@ -936,7 +897,7 @@ bool l2cble_create_conn(tL2C_LCB* p_lcb) { * Returns void * ******************************************************************************/ -void l2c_link_processs_ble_num_bufs(uint16_t num_lm_ble_bufs) { +void l2c_link_process_ble_num_bufs(uint16_t num_lm_ble_bufs) { if (num_lm_ble_bufs == 0) { num_lm_ble_bufs = L2C_DEF_NUM_BLE_BUF_SHARED; l2cb.num_lm_acl_bufs -= L2C_DEF_NUM_BLE_BUF_SHARED; @@ -980,23 +941,23 @@ void l2c_ble_link_adjust_allocation(void) { /* First, count the links */ for (yy = 0, p_lcb = &l2cb.lcb_pool[0]; yy < MAX_L2CAP_LINKS; yy++, p_lcb++) { if (p_lcb->in_use && p_lcb->transport == BT_TRANSPORT_LE) { - if (p_lcb->acl_priority == L2CAP_PRIORITY_HIGH) + if (p_lcb->acl_priority == L2CAP_PRIORITY_HIGH) { num_hipri_links++; - else + } else { num_lowpri_links++; + } } } /* now adjust high priority link quota */ low_quota = num_lowpri_links ? 1 : 0; - while ((num_hipri_links * high_pri_link_quota + low_quota) > - controller_xmit_quota) + while ((num_hipri_links * high_pri_link_quota + low_quota) > controller_xmit_quota) { high_pri_link_quota--; + } /* Work out the xmit quota and buffer quota high and low priorities */ hi_quota = num_hipri_links * high_pri_link_quota; - low_quota = - (hi_quota < controller_xmit_quota) ? controller_xmit_quota - hi_quota : 1; + low_quota = (hi_quota < controller_xmit_quota) ? controller_xmit_quota - hi_quota : 1; /* Work out and save the HCI xmit quota for each low priority link */ @@ -1019,10 +980,9 @@ void l2c_ble_link_adjust_allocation(void) { qq = qq_remainder = 0; } log::verbose( - "l2c_ble_link_adjust_allocation num_hipri: {} num_lowpri: {} " - "low_quota: {} round_robin_quota: {} qq: {}", - num_hipri_links, num_lowpri_links, low_quota, l2cb.ble_round_robin_quota, - qq); + "l2c_ble_link_adjust_allocation num_hipri: {} num_lowpri: {} " + "low_quota: {} round_robin_quota: {} qq: {}", + num_hipri_links, num_lowpri_links, low_quota, l2cb.ble_round_robin_quota, qq); /* Now, assign the quotas to each link */ for (yy = 0, p_lcb = &l2cb.lcb_pool[0]; yy < MAX_L2CAP_LINKS; yy++, p_lcb++) { @@ -1035,8 +995,9 @@ void l2c_ble_link_adjust_allocation(void) { /* if sent_not_acked is added into round_robin_unacked then do not add * it again */ /* l2cap keeps updating sent_not_acked for exiting from round robin */ - if ((p_lcb->link_xmit_quota > 0) && (qq == 0)) + if ((p_lcb->link_xmit_quota > 0) && (qq == 0)) { l2cb.ble_round_robin_unacked += p_lcb->sent_not_acked; + } p_lcb->link_xmit_quota = qq; if (qq_remainder > 0) { @@ -1045,9 +1006,8 @@ void l2c_ble_link_adjust_allocation(void) { } } - log::verbose( - "l2c_ble_link_adjust_allocation LCB {} Priority: {} XmitQuota: {}", - yy, p_lcb->acl_priority, p_lcb->link_xmit_quota); + log::verbose("l2c_ble_link_adjust_allocation LCB {} Priority: {} XmitQuota: {}", yy, + p_lcb->acl_priority, p_lcb->link_xmit_quota); log::verbose("SentNotAcked: {} RRUnacked: {}", p_lcb->sent_not_acked, l2cb.round_robin_unacked); @@ -1055,11 +1015,9 @@ void l2c_ble_link_adjust_allocation(void) { /* There is a special case where we have readjusted the link quotas and */ /* this link may have sent anything but some other link sent packets so */ /* so we may need a timer to kick off this link's transmissions. */ - if ((p_lcb->link_state == LST_CONNECTED) && - (!list_is_empty(p_lcb->link_xmit_data_q)) && + if ((p_lcb->link_state == LST_CONNECTED) && (!list_is_empty(p_lcb->link_xmit_data_q)) && (p_lcb->sent_not_acked < p_lcb->link_xmit_quota)) { - alarm_set_on_mloop(p_lcb->l2c_lcb_timer, - L2CAP_LINK_FLOW_CONTROL_TIMEOUT_MS, + alarm_set_on_mloop(p_lcb->l2c_lcb_timer, L2CAP_LINK_FLOW_CONTROL_TIMEOUT_MS, l2c_lcb_timer_timeout, p_lcb); } } @@ -1082,21 +1040,27 @@ void l2cble_update_data_length(tL2C_LCB* p_lcb) { log::verbose(""); /* See if we have a link control block for the connection */ - if (p_lcb == NULL) return; + if (p_lcb == NULL) { + return; + } for (i = 0; i < L2CAP_NUM_FIXED_CHNLS; i++) { if (i + L2CAP_FIRST_FIXED_CHNL != L2CAP_BLE_SIGNALLING_CID) { if ((p_lcb->p_fixed_ccbs[i] != NULL) && - (tx_mtu < (p_lcb->p_fixed_ccbs[i]->tx_data_len + L2CAP_PKT_OVERHEAD))) + (tx_mtu < (p_lcb->p_fixed_ccbs[i]->tx_data_len + L2CAP_PKT_OVERHEAD))) { tx_mtu = p_lcb->p_fixed_ccbs[i]->tx_data_len + L2CAP_PKT_OVERHEAD; + } } } - if (tx_mtu > BTM_BLE_DATA_SIZE_MAX) tx_mtu = BTM_BLE_DATA_SIZE_MAX; + if (tx_mtu > BTM_BLE_DATA_SIZE_MAX) { + tx_mtu = BTM_BLE_DATA_SIZE_MAX; + } /* update TX data length if changed */ - if (p_lcb->tx_data_len != tx_mtu) + if (p_lcb->tx_data_len != tx_mtu) { BTM_SetBleDataLength(p_lcb->remote_bd_addr, tx_mtu); + } } /******************************************************************************* @@ -1109,41 +1073,37 @@ void l2cble_update_data_length(tL2C_LCB* p_lcb) { * ******************************************************************************/ static bool is_legal_tx_data_len(const uint16_t& tx_data_len) { - return (tx_data_len >= 0x001B && tx_data_len <= 0x00FB); + return tx_data_len >= 0x001B && tx_data_len <= 0x00FB; } -void l2cble_process_data_length_change_event(uint16_t handle, - uint16_t tx_data_len, +void l2cble_process_data_length_change_event(uint16_t handle, uint16_t tx_data_len, uint16_t /* rx_data_len */) { tL2C_LCB* p_lcb = l2cu_find_lcb_by_handle(handle); if (p_lcb == nullptr) { - log::warn( - "Received data length change event for unknown ACL handle:0x{:04x}", - handle); + log::warn("Received data length change event for unknown ACL handle:0x{:04x}", handle); return; } if (is_legal_tx_data_len(tx_data_len)) { if (p_lcb->tx_data_len != tx_data_len) { log::debug( - "Received data length change event for device:{} tx_data_len:{} => " - "{}", - p_lcb->remote_bd_addr, p_lcb->tx_data_len, tx_data_len); + "Received data length change event for device:{} tx_data_len:{} => " + "{}", + p_lcb->remote_bd_addr, p_lcb->tx_data_len, tx_data_len); BTM_LogHistory(kBtmLogTag, p_lcb->remote_bd_addr, "LE Data length change", - base::StringPrintf("tx_octets:%hu => %hu", - p_lcb->tx_data_len, tx_data_len)); + base::StringPrintf("tx_octets:%hu => %hu", p_lcb->tx_data_len, tx_data_len)); p_lcb->tx_data_len = tx_data_len; } else { log::debug( - "Received duplicated data length change event for device:{} " - "tx_data_len:{}", - p_lcb->remote_bd_addr, tx_data_len); + "Received duplicated data length change event for device:{} " + "tx_data_len:{}", + p_lcb->remote_bd_addr, tx_data_len); } } else { log::warn( - "Received illegal data length change event for device:{} " - "tx_data_len:{}", - p_lcb->remote_bd_addr, tx_data_len); + "Received illegal data length change event for device:{} " + "tx_data_len:{}", + p_lcb->remote_bd_addr, tx_data_len); } /* ignore rx_data len for now */ } @@ -1159,7 +1119,9 @@ void l2cble_process_data_length_change_event(uint16_t handle, * ******************************************************************************/ void l2cble_credit_based_conn_req(tL2C_CCB* p_ccb) { - if (!p_ccb) return; + if (!p_ccb) { + return; + } if (p_ccb->p_lcb && p_ccb->p_lcb->transport != BT_TRANSPORT_LE) { log::warn("LE link doesn't exist"); @@ -1185,7 +1147,9 @@ void l2cble_credit_based_conn_req(tL2C_CCB* p_ccb) { * ******************************************************************************/ void l2cble_credit_based_conn_res(tL2C_CCB* p_ccb, uint16_t result) { - if (!p_ccb) return; + if (!p_ccb) { + return; + } if (p_ccb->p_lcb && p_ccb->p_lcb->transport != BT_TRANSPORT_LE) { log::warn("LE link doesn't exist"); @@ -1207,7 +1171,9 @@ void l2cble_credit_based_conn_res(tL2C_CCB* p_ccb, uint16_t result) { * ******************************************************************************/ void l2cble_send_flow_control_credit(tL2C_CCB* p_ccb, uint16_t credit_value) { - if (!p_ccb) return; + if (!p_ccb) { + return; + } if (p_ccb->p_lcb && p_ccb->p_lcb->transport != BT_TRANSPORT_LE) { log::warn("LE link doesn't exist"); @@ -1230,7 +1196,9 @@ void l2cble_send_flow_control_credit(tL2C_CCB* p_ccb, uint16_t credit_value) { ******************************************************************************/ void l2cble_send_peer_disc_req(tL2C_CCB* p_ccb) { log::verbose(""); - if (!p_ccb) return; + if (!p_ccb) { + return; + } if (p_ccb->p_lcb && p_ccb->p_lcb->transport != BT_TRANSPORT_LE) { log::warn("LE link doesn't exist"); @@ -1251,8 +1219,8 @@ void l2cble_send_peer_disc_req(tL2C_CCB* p_ccb) { * Returns void * ******************************************************************************/ -void l2cble_sec_comp(RawAddress bda, tBT_TRANSPORT transport, - void* /* p_ref_data */, tBTM_STATUS status) { +void l2cble_sec_comp(RawAddress bda, tBT_TRANSPORT transport, void* /* p_ref_data */, + tBTM_STATUS status) { tL2C_LCB* p_lcb = l2cu_find_lcb_by_bd_addr(bda, BT_TRANSPORT_LE); tL2CAP_SEC_DATA* p_buf = NULL; uint8_t sec_act; @@ -1277,17 +1245,14 @@ void l2cble_sec_comp(RawAddress bda, tBT_TRANSPORT transport, osi_free(p_buf); } else { if (sec_act == BTM_SEC_ENCRYPT_MITM) { - if (BTM_IsLinkKeyAuthed(bda, transport)) - (*(p_buf->p_callback))(bda, BT_TRANSPORT_LE, p_buf->p_ref_data, - status); - else { + if (BTM_IsLinkKeyAuthed(bda, transport)) { + (*(p_buf->p_callback))(bda, BT_TRANSPORT_LE, p_buf->p_ref_data, status); + } else { log::verbose("MITM Protection Not present"); - (*(p_buf->p_callback))(bda, BT_TRANSPORT_LE, p_buf->p_ref_data, - BTM_FAILED_ON_SECURITY); + (*(p_buf->p_callback))(bda, BT_TRANSPORT_LE, p_buf->p_ref_data, BTM_FAILED_ON_SECURITY); } } else { - log::verbose("MITM Protection not required sec_act = {}", - p_lcb->sec_act); + log::verbose("MITM Protection not required sec_act = {}", p_lcb->sec_act); (*(p_buf->p_callback))(bda, BT_TRANSPORT_LE, p_buf->p_ref_data, status); } @@ -1304,10 +1269,9 @@ void l2cble_sec_comp(RawAddress bda, tBT_TRANSPORT transport, if (status != BTM_SUCCESS) { (*(p_buf->p_callback))(bda, BT_TRANSPORT_LE, p_buf->p_ref_data, status); osi_free(p_buf); - } - else { - l2ble_sec_access_req(bda, p_buf->psm, p_buf->is_originator, - p_buf->p_callback, p_buf->p_ref_data); + } else { + l2ble_sec_access_req(bda, p_buf->psm, p_buf->is_originator, p_buf->p_callback, + p_buf->p_ref_data); osi_free(p_buf); break; @@ -1325,9 +1289,8 @@ void l2cble_sec_comp(RawAddress bda, tBT_TRANSPORT transport, * Returns Returns - L2CAP LE Connection Response Result Code. * ******************************************************************************/ -tL2CAP_LE_RESULT_CODE l2ble_sec_access_req(const RawAddress& bd_addr, - uint16_t psm, bool is_originator, - tBTM_SEC_CALLBACK* p_callback, +tL2CAP_LE_RESULT_CODE l2ble_sec_access_req(const RawAddress& bd_addr, uint16_t psm, + bool is_originator, tBTM_SEC_CALLBACK* p_callback, void* p_ref_data) { tL2C_LCB* p_lcb = NULL; @@ -1344,8 +1307,7 @@ tL2CAP_LE_RESULT_CODE l2ble_sec_access_req(const RawAddress& bd_addr, return L2CAP_LE_RESULT_NO_RESOURCES; } - tL2CAP_SEC_DATA* p_buf = - (tL2CAP_SEC_DATA*)osi_malloc((uint16_t)sizeof(tL2CAP_SEC_DATA)); + tL2CAP_SEC_DATA* p_buf = (tL2CAP_SEC_DATA*)osi_malloc((uint16_t)sizeof(tL2CAP_SEC_DATA)); if (!p_buf) { log::error("No resources for connection"); p_callback(bd_addr, BT_TRANSPORT_LE, p_ref_data, BTM_NO_RESOURCES); @@ -1357,8 +1319,8 @@ tL2CAP_LE_RESULT_CODE l2ble_sec_access_req(const RawAddress& bd_addr, p_buf->p_callback = p_callback; p_buf->p_ref_data = p_ref_data; fixed_queue_enqueue(p_lcb->le_sec_pending_q, p_buf); - tBTM_STATUS result = btm_ble_start_sec_check(bd_addr, psm, is_originator, - &l2cble_sec_comp, p_ref_data); + tBTM_STATUS result = + btm_ble_start_sec_check(bd_addr, psm, is_originator, &l2cble_sec_comp, p_ref_data); switch (result) { case BTM_SUCCESS: @@ -1383,33 +1345,29 @@ tL2CAP_LE_RESULT_CODE l2ble_sec_access_req(const RawAddress& bd_addr, * constraints. For example, when there is at least one Hearing Aid device * bonded, the minimum interval is raised. On return, min_interval and * max_interval are updated. */ -void L2CA_AdjustConnectionIntervals(uint16_t* min_interval, - uint16_t* max_interval, +void L2CA_AdjustConnectionIntervals(uint16_t* min_interval, uint16_t* max_interval, uint16_t floor_interval) { // Allow for customization by systemprops for mainline uint16_t phone_min_interval = floor_interval; #ifdef __ANDROID__ phone_min_interval = - android::sysprop::BluetoothProperties::getGapLeConnMinLimit().value_or( - floor_interval); + android::sysprop::BluetoothProperties::getGapLeConnMinLimit().value_or(floor_interval); #else - phone_min_interval = (uint16_t)osi_property_get_int32( - "bluetooth.core.gap.le.conn.min.limit", (int32_t)floor_interval); + phone_min_interval = (uint16_t)osi_property_get_int32("bluetooth.core.gap.le.conn.min.limit", + (int32_t)floor_interval); #endif - if (GetInterfaceToProfiles() - ->profileSpecific_HACK->GetHearingAidDeviceCount()) { + if (GetInterfaceToProfiles()->profileSpecific_HACK->GetHearingAidDeviceCount()) { // When there are bonded Hearing Aid devices, we will constrained this // minimum interval. phone_min_interval = BTM_BLE_CONN_INT_MIN_HEARINGAID; - log::verbose("Have Hearing Aids. Min. interval is set to {}", - phone_min_interval); + log::verbose("Have Hearing Aids. Min. interval is set to {}", phone_min_interval); } if (!com::android::bluetooth::flags::l2cap_le_do_not_adjust_min_interval() && *min_interval < phone_min_interval) { - log::verbose("requested min_interval={} too small. Set to {}", - *min_interval, phone_min_interval); + log::verbose("requested min_interval={} too small. Set to {}", *min_interval, + phone_min_interval); *min_interval = phone_min_interval; } @@ -1418,8 +1376,8 @@ void L2CA_AdjustConnectionIntervals(uint16_t* min_interval, // to remain established. // In other words, this is a workaround for certain peripherals. if (*max_interval < phone_min_interval) { - log::verbose("requested max_interval={} too small. Set to {}", - *max_interval, phone_min_interval); + log::verbose("requested max_interval={} too small. Set to {}", *max_interval, + phone_min_interval); *max_interval = phone_min_interval; } } @@ -1431,33 +1389,29 @@ void L2CA_SetEcosystemBaseInterval(uint32_t base_interval) { log::info("base_interval: {}ms", base_interval); bluetooth::shim::GetHciLayer()->EnqueueCommand( - bluetooth::hci::SetEcosystemBaseIntervalBuilder::Create(base_interval), - get_main_thread()->BindOnce([](bluetooth::hci::CommandCompleteView view) { - ASSERT(view.IsValid()); - auto status_view = - bluetooth::hci::SetEcosystemBaseIntervalCompleteView::Create( - bluetooth::hci::SetEcosystemBaseIntervalCompleteView::Create( - view)); - ASSERT(status_view.IsValid()); - - if (status_view.GetStatus() != bluetooth::hci::ErrorCode::SUCCESS) { - log::warn("Set Ecosystem Base Interval status {}", - ErrorCodeText(status_view.GetStatus())); - return; - } - })); - - if (com::android::bluetooth::flags:: - l2cap_update_existing_conn_interval_with_base_interval() && + bluetooth::hci::SetEcosystemBaseIntervalBuilder::Create(base_interval), + get_main_thread()->BindOnce([](bluetooth::hci::CommandCompleteView view) { + ASSERT(view.IsValid()); + auto status_view = bluetooth::hci::SetEcosystemBaseIntervalCompleteView::Create( + bluetooth::hci::SetEcosystemBaseIntervalCompleteView::Create(view)); + ASSERT(status_view.IsValid()); + + if (status_view.GetStatus() != bluetooth::hci::ErrorCode::SUCCESS) { + log::warn("Set Ecosystem Base Interval status {}", + ErrorCodeText(status_view.GetStatus())); + return; + } + })); + + if (com::android::bluetooth::flags::l2cap_update_existing_conn_interval_with_base_interval() && base_interval != 0) { tL2C_LCB* p_lcb = &l2cb.lcb_pool[0]; for (int i = 0; i < MAX_L2CAP_LINKS; i++, p_lcb++) { if ((p_lcb->in_use) && p_lcb->transport == BT_TRANSPORT_LE) { - bool ret = L2CA_UpdateBleConnParams( - p_lcb->remote_bd_addr, p_lcb->min_interval, p_lcb->max_interval, - p_lcb->latency, p_lcb->timeout, p_lcb->min_ce_len, - p_lcb->max_ce_len); + bool ret = L2CA_UpdateBleConnParams(p_lcb->remote_bd_addr, p_lcb->min_interval, + p_lcb->max_interval, p_lcb->latency, p_lcb->timeout, + p_lcb->min_ce_len, p_lcb->max_ce_len); } } } diff --git a/system/stack/l2cap/l2c_ble_conn_params.cc b/system/stack/l2cap/l2c_ble_conn_params.cc index 490daf04480..60369357741 100644 --- a/system/stack/l2cap/l2c_ble_conn_params.cc +++ b/system/stack/l2cap/l2c_ble_conn_params.cc @@ -58,9 +58,8 @@ static void l2cble_start_subrate_change(tL2C_LCB* p_lcb); * Return value: true if update started * ******************************************************************************/ -bool L2CA_UpdateBleConnParams(const RawAddress& rem_bda, uint16_t min_int, - uint16_t max_int, uint16_t latency, - uint16_t timeout, uint16_t min_ce_len, +bool L2CA_UpdateBleConnParams(const RawAddress& rem_bda, uint16_t min_int, uint16_t max_int, + uint16_t latency, uint16_t timeout, uint16_t min_ce_len, uint16_t max_ce_len) { tL2C_LCB* p_lcb; @@ -70,17 +69,16 @@ bool L2CA_UpdateBleConnParams(const RawAddress& rem_bda, uint16_t min_int, /* If we do not have one, create one and accept the connection. */ if (!p_lcb || !BTM_IsAclConnectionUp(rem_bda, BT_TRANSPORT_LE)) { log::warn("- unknown BD_ADDR {}", rem_bda); - return (false); + return false; } if (p_lcb->transport != BT_TRANSPORT_LE) { log::warn("- BD_ADDR {} not LE", rem_bda); - return (false); + return false; } - log::verbose( - "BD_ADDR={}, min_int={}, max_int={}, min_ce_len={}, max_ce_len={}", - rem_bda, min_int, max_int, min_ce_len, max_ce_len); + log::verbose("BD_ADDR={}, min_int={}, max_int={}, min_ce_len={}, max_ce_len={}", rem_bda, min_int, + max_int, min_ce_len, max_ce_len); p_lcb->min_interval = min_int; p_lcb->max_interval = max_int; @@ -92,7 +90,7 @@ bool L2CA_UpdateBleConnParams(const RawAddress& rem_bda, uint16_t min_int, l2cble_start_conn_update(p_lcb); - return (true); + return true; } static bool l2c_enable_update_ble_conn_params(tL2C_LCB* p_lcb, bool enable); @@ -101,9 +99,10 @@ static bool l2c_enable_update_ble_conn_params(tL2C_LCB* p_lcb, bool enable); * fastest value, and we won't accept request to change it from remote. When * called with lock=false, parameters are relaxed. */ -void L2CA_LockBleConnParamsForServiceDiscovery(const RawAddress& rem_bda, - bool lock) { - if (stack_config_get_interface()->get_pts_conn_updates_disabled()) return; +void L2CA_LockBleConnParamsForServiceDiscovery(const RawAddress& rem_bda, bool lock) { + if (stack_config_get_interface()->get_pts_conn_updates_disabled()) { + return; + } tL2C_LCB* p_lcb = l2cu_find_lcb_by_bd_addr(rem_bda, BT_TRANSPORT_LE); if (!p_lcb) { @@ -117,8 +116,7 @@ void L2CA_LockBleConnParamsForServiceDiscovery(const RawAddress& rem_bda, } if (lock == p_lcb->conn_update_blocked_by_service_discovery) { - log::warn("{} service discovery already locked/unlocked conn params: {}", - rem_bda, lock); + log::warn("{} service discovery already locked/unlocked conn params: {}", rem_bda, lock); return; } @@ -129,8 +127,7 @@ void L2CA_LockBleConnParamsForServiceDiscovery(const RawAddress& rem_bda, return; } - log::info("{} Locking/unlocking conn params for service discovery: {}", - rem_bda, lock); + log::info("{} Locking/unlocking conn params for service discovery: {}", rem_bda, lock); l2c_enable_update_ble_conn_params(p_lcb, !lock); } @@ -138,9 +135,10 @@ void L2CA_LockBleConnParamsForServiceDiscovery(const RawAddress& rem_bda, * fastest value, and we won't accept request to change it from remote. When * called with lock=false, parameters are relaxed. */ -void L2CA_LockBleConnParamsForProfileConnection(const RawAddress& rem_bda, - bool lock) { - if (stack_config_get_interface()->get_pts_conn_updates_disabled()) return; +void L2CA_LockBleConnParamsForProfileConnection(const RawAddress& rem_bda, bool lock) { + if (stack_config_get_interface()->get_pts_conn_updates_disabled()) { + return; + } tL2C_LCB* p_lcb = l2cu_find_lcb_by_bd_addr(rem_bda, BT_TRANSPORT_LE); if (!p_lcb) { @@ -154,27 +152,24 @@ void L2CA_LockBleConnParamsForProfileConnection(const RawAddress& rem_bda, } if (lock == p_lcb->conn_update_blocked_by_profile_connection) { - log::info("{} audio setup already locked/unlocked conn params: {}", rem_bda, - lock); + log::info("{} audio setup already locked/unlocked conn params: {}", rem_bda, lock); return; } p_lcb->conn_update_blocked_by_profile_connection = lock; if (p_lcb->conn_update_blocked_by_service_discovery) { - log::info("{} conn params stay locked because of service discovery", - rem_bda); + log::info("{} conn params stay locked because of service discovery", rem_bda); return; } - log::info("{} Locking/unlocking conn params for audio setup: {}", rem_bda, - lock); + log::info("{} Locking/unlocking conn params for audio setup: {}", rem_bda, lock); l2c_enable_update_ble_conn_params(p_lcb, !lock); } static bool l2c_enable_update_ble_conn_params(tL2C_LCB* p_lcb, bool enable) { - log::debug("{} enable {} current upd state 0x{:02x}", p_lcb->remote_bd_addr, - enable, p_lcb->conn_update_mask); + log::debug("{} enable {} current upd state 0x{:02x}", p_lcb->remote_bd_addr, enable, + p_lcb->conn_update_mask); if (enable) { p_lcb->conn_update_mask &= ~L2C_BLE_CONN_UPDATE_DISABLE; @@ -186,7 +181,7 @@ static bool l2c_enable_update_ble_conn_params(tL2C_LCB* p_lcb, bool enable) { l2cble_start_conn_update(p_lcb); - return (true); + return true; } /******************************************************************************* @@ -228,25 +223,21 @@ void l2cble_start_conn_update(tL2C_LCB* p_lcb) { /* use 7.5 ms as fast connection parameter, 0 peripheral latency */ min_conn_int = max_conn_int = BTM_BLE_CONN_INT_MIN; - L2CA_AdjustConnectionIntervals(&min_conn_int, &max_conn_int, - BTM_BLE_CONN_INT_MIN); + L2CA_AdjustConnectionIntervals(&min_conn_int, &max_conn_int, BTM_BLE_CONN_INT_MIN); peripheral_latency = BTM_BLE_CONN_PERIPHERAL_LATENCY_DEF; supervision_tout = BTM_BLE_CONN_TIMEOUT_DEF; /* if both side 4.1, or we are central device, send HCI command */ if (p_lcb->IsLinkRoleCentral() || - (bluetooth::shim::GetController() - ->SupportsBleConnectionParametersRequest() && - acl_peer_supports_ble_connection_parameters_request( - p_lcb->remote_bd_addr))) { - acl_ble_connection_parameters_request(p_lcb->Handle(), min_conn_int, - max_conn_int, peripheral_latency, - supervision_tout, 0, 0); + (bluetooth::shim::GetController()->SupportsBleConnectionParametersRequest() && + acl_peer_supports_ble_connection_parameters_request(p_lcb->remote_bd_addr))) { + acl_ble_connection_parameters_request(p_lcb->Handle(), min_conn_int, max_conn_int, + peripheral_latency, supervision_tout, 0, 0); p_lcb->conn_update_mask |= L2C_BLE_UPDATE_PENDING; } else { - l2cu_send_peer_ble_par_req(p_lcb, min_conn_int, max_conn_int, - peripheral_latency, supervision_tout); + l2cu_send_peer_ble_par_req(p_lcb, min_conn_int, max_conn_int, peripheral_latency, + supervision_tout); } p_lcb->conn_update_mask &= ~L2C_BLE_NOT_DEFAULT_PARAM; p_lcb->conn_update_mask |= L2C_BLE_NEW_CONN_PARAM; @@ -256,18 +247,14 @@ void l2cble_start_conn_update(tL2C_LCB* p_lcb) { if (p_lcb->conn_update_mask & L2C_BLE_NEW_CONN_PARAM) { /* if both side 4.1, or we are central device, send HCI command */ if (p_lcb->IsLinkRoleCentral() || - (bluetooth::shim::GetController() - ->SupportsBleConnectionParametersRequest() && - acl_peer_supports_ble_connection_parameters_request( - p_lcb->remote_bd_addr))) { - acl_ble_connection_parameters_request( - p_lcb->Handle(), p_lcb->min_interval, p_lcb->max_interval, - p_lcb->latency, p_lcb->timeout, p_lcb->min_ce_len, - p_lcb->max_ce_len); + (bluetooth::shim::GetController()->SupportsBleConnectionParametersRequest() && + acl_peer_supports_ble_connection_parameters_request(p_lcb->remote_bd_addr))) { + acl_ble_connection_parameters_request(p_lcb->Handle(), p_lcb->min_interval, + p_lcb->max_interval, p_lcb->latency, p_lcb->timeout, + p_lcb->min_ce_len, p_lcb->max_ce_len); p_lcb->conn_update_mask |= L2C_BLE_UPDATE_PENDING; } else { - l2cu_send_peer_ble_par_req(p_lcb, p_lcb->min_interval, - p_lcb->max_interval, p_lcb->latency, + l2cu_send_peer_ble_par_req(p_lcb, p_lcb->min_interval, p_lcb->max_interval, p_lcb->latency, p_lcb->timeout); } p_lcb->conn_update_mask &= ~L2C_BLE_NEW_CONN_PARAM; @@ -287,10 +274,8 @@ void l2cble_start_conn_update(tL2C_LCB* p_lcb) { * Returns void * ******************************************************************************/ -void l2cble_process_conn_update_evt(uint16_t handle, uint8_t status, - uint16_t /* interval */, - uint16_t /* latency */, - uint16_t /* timeout */) { +void l2cble_process_conn_update_evt(uint16_t handle, uint8_t status, uint16_t /* interval */, + uint16_t /* latency */, uint16_t /* timeout */) { log::verbose(""); /* See if we have a link control block for the remote device */ @@ -310,8 +295,8 @@ void l2cble_process_conn_update_evt(uint16_t handle, uint8_t status, l2cble_start_subrate_change(p_lcb); - log::verbose("conn_update_mask={} , subrate_req_mask={}", - p_lcb->conn_update_mask, p_lcb->subrate_req_mask); + log::verbose("conn_update_mask={} , subrate_req_mask={}", p_lcb->conn_update_mask, + p_lcb->subrate_req_mask); } /******************************************************************************* @@ -323,9 +308,8 @@ void l2cble_process_conn_update_evt(uint16_t handle, uint8_t status, * Returns void * ******************************************************************************/ -void l2cble_process_rc_param_request_evt(uint16_t handle, uint16_t int_min, - uint16_t int_max, uint16_t latency, - uint16_t timeout) { +void l2cble_process_rc_param_request_evt(uint16_t handle, uint16_t int_min, uint16_t int_max, + uint16_t latency, uint16_t timeout) { tL2C_LCB* p_lcb = l2cu_find_lcb_by_handle(handle); if (!p_lcb) { log::warn("No link to update connection parameter"); @@ -340,21 +324,19 @@ void l2cble_process_rc_param_request_evt(uint16_t handle, uint16_t int_min, /* if update is enabled, always accept connection parameter update */ if ((p_lcb->conn_update_mask & L2C_BLE_CONN_UPDATE_DISABLE) == 0) { shim::GetHciLayer()->EnqueueCommand( - hci::LeRemoteConnectionParameterRequestReplyBuilder::Create( - handle, int_min, int_max, latency, timeout, 0, 0), - get_main()->BindOnce( - hci::check_complete< - hci::LeRemoteConnectionParameterRequestReplyCompleteView>)); + hci::LeRemoteConnectionParameterRequestReplyBuilder::Create(handle, int_min, int_max, + latency, timeout, 0, 0), + get_main()->BindOnce( + hci::check_complete)); } else { log::verbose("L2CAP - LE - update currently disabled"); p_lcb->conn_update_mask |= L2C_BLE_NEW_CONN_PARAM; shim::GetHciLayer()->EnqueueCommand( - hci::LeRemoteConnectionParameterRequestNegativeReplyBuilder::Create( - handle, hci::ErrorCode::UNACCEPTABLE_CONNECTION_PARAMETERS), - get_main()->BindOnce( - hci::check_complete< - hci:: - LeRemoteConnectionParameterRequestNegativeReplyCompleteView>)); + hci::LeRemoteConnectionParameterRequestNegativeReplyBuilder::Create( + handle, hci::ErrorCode::UNACCEPTABLE_CONNECTION_PARAMETERS), + get_main()->BindOnce( + hci::check_complete< + hci::LeRemoteConnectionParameterRequestNegativeReplyCompleteView>)); } } @@ -377,23 +359,21 @@ void l2cble_use_preferred_conn_params(const RawAddress& bda) { (p_lcb->latency > p_dev_rec->conn_params.peripheral_latency) || (p_lcb->timeout > p_dev_rec->conn_params.supervision_tout))) { log::verbose( - "HANDLE={} min_conn_int={} max_conn_int={} peripheral_latency={} " - "supervision_tout={}", - p_lcb->Handle(), p_dev_rec->conn_params.min_conn_int, - p_dev_rec->conn_params.max_conn_int, - p_dev_rec->conn_params.peripheral_latency, - p_dev_rec->conn_params.supervision_tout); + "HANDLE={} min_conn_int={} max_conn_int={} peripheral_latency={} " + "supervision_tout={}", + p_lcb->Handle(), p_dev_rec->conn_params.min_conn_int, + p_dev_rec->conn_params.max_conn_int, p_dev_rec->conn_params.peripheral_latency, + p_dev_rec->conn_params.supervision_tout); p_lcb->min_interval = p_dev_rec->conn_params.min_conn_int; p_lcb->max_interval = p_dev_rec->conn_params.max_conn_int; p_lcb->timeout = p_dev_rec->conn_params.supervision_tout; p_lcb->latency = p_dev_rec->conn_params.peripheral_latency; - acl_ble_connection_parameters_request( - p_lcb->Handle(), p_dev_rec->conn_params.min_conn_int, - p_dev_rec->conn_params.max_conn_int, - p_dev_rec->conn_params.peripheral_latency, - p_dev_rec->conn_params.supervision_tout, 0, 0); + acl_ble_connection_parameters_request(p_lcb->Handle(), p_dev_rec->conn_params.min_conn_int, + p_dev_rec->conn_params.max_conn_int, + p_dev_rec->conn_params.peripheral_latency, + p_dev_rec->conn_params.supervision_tout, 0, 0); } } @@ -417,8 +397,8 @@ static void l2cble_start_subrate_change(tL2C_LCB* p_lcb) { btm_find_or_alloc_dev(p_lcb->remote_bd_addr); - log::verbose("subrate_req_mask={} conn_update_mask={}", - p_lcb->subrate_req_mask, p_lcb->conn_update_mask); + log::verbose("subrate_req_mask={} conn_update_mask={}", p_lcb->subrate_req_mask, + p_lcb->conn_update_mask); if (p_lcb->subrate_req_mask & L2C_BLE_SUBRATE_REQ_PENDING) { log::verbose("returning L2C_BLE_SUBRATE_REQ_PENDING"); @@ -442,19 +422,19 @@ static void l2cble_start_subrate_change(tL2C_LCB* p_lcb) { !acl_peer_supports_ble_connection_subrating(p_lcb->remote_bd_addr) || !acl_peer_supports_ble_connection_subrating_host(p_lcb->remote_bd_addr)) { log::verbose( - "returning L2C_BLE_NEW_SUBRATE_PARAM local_host_sup={}, " - "local_conn_subrarte_sup={}, peer_subrate_sup={}, peer_host_sup={}", - bluetooth::shim::GetController()->SupportsBleConnectionSubratingHost(), - bluetooth::shim::GetController()->SupportsBleConnectionSubrating(), - acl_peer_supports_ble_connection_subrating(p_lcb->remote_bd_addr), - acl_peer_supports_ble_connection_subrating_host(p_lcb->remote_bd_addr)); + "returning L2C_BLE_NEW_SUBRATE_PARAM local_host_sup={}, " + "local_conn_subrarte_sup={}, peer_subrate_sup={}, peer_host_sup={}", + bluetooth::shim::GetController()->SupportsBleConnectionSubratingHost(), + bluetooth::shim::GetController()->SupportsBleConnectionSubrating(), + acl_peer_supports_ble_connection_subrating(p_lcb->remote_bd_addr), + acl_peer_supports_ble_connection_subrating_host(p_lcb->remote_bd_addr)); return; } log::verbose("Sending HCI cmd for subrate req"); - bluetooth::shim::ACL_LeSubrateRequest( - p_lcb->Handle(), p_lcb->subrate_min, p_lcb->subrate_max, - p_lcb->max_latency, p_lcb->cont_num, p_lcb->supervision_tout); + bluetooth::shim::ACL_LeSubrateRequest(p_lcb->Handle(), p_lcb->subrate_min, p_lcb->subrate_max, + p_lcb->max_latency, p_lcb->cont_num, + p_lcb->supervision_tout); p_lcb->subrate_req_mask |= L2C_BLE_SUBRATE_REQ_PENDING; p_lcb->subrate_req_mask &= ~L2C_BLE_NEW_SUBRATE_PARAM; @@ -472,15 +452,13 @@ static void l2cble_start_subrate_change(tL2C_LCB* p_lcb) { * Return value: void * ******************************************************************************/ -void L2CA_SetDefaultSubrate(uint16_t subrate_min, uint16_t subrate_max, - uint16_t max_latency, uint16_t cont_num, - uint16_t timeout) { - log::verbose( - "subrate_min={}, subrate_max={}, max_latency={}, cont_num={}, timeout={}", - subrate_min, subrate_max, max_latency, cont_num, timeout); +void L2CA_SetDefaultSubrate(uint16_t subrate_min, uint16_t subrate_max, uint16_t max_latency, + uint16_t cont_num, uint16_t timeout) { + log::verbose("subrate_min={}, subrate_max={}, max_latency={}, cont_num={}, timeout={}", + subrate_min, subrate_max, max_latency, cont_num, timeout); - bluetooth::shim::ACL_LeSetDefaultSubrate(subrate_min, subrate_max, - max_latency, cont_num, timeout); + bluetooth::shim::ACL_LeSetDefaultSubrate(subrate_min, subrate_max, max_latency, cont_num, + timeout); } /******************************************************************************* @@ -494,9 +472,8 @@ void L2CA_SetDefaultSubrate(uint16_t subrate_min, uint16_t subrate_max, * Return value: true if update started * ******************************************************************************/ -bool L2CA_SubrateRequest(const RawAddress& rem_bda, uint16_t subrate_min, - uint16_t subrate_max, uint16_t max_latency, - uint16_t cont_num, uint16_t timeout) { +bool L2CA_SubrateRequest(const RawAddress& rem_bda, uint16_t subrate_min, uint16_t subrate_max, + uint16_t max_latency, uint16_t cont_num, uint16_t timeout) { tL2C_LCB* p_lcb; /* See if we have a link control block for the remote device */ @@ -505,18 +482,18 @@ bool L2CA_SubrateRequest(const RawAddress& rem_bda, uint16_t subrate_min, /* If we don't have one, create one and accept the connection. */ if (!p_lcb || !BTM_IsAclConnectionUp(rem_bda, BT_TRANSPORT_LE)) { log::warn("unknown BD_ADDR {}", rem_bda); - return (false); + return false; } if (p_lcb->transport != BT_TRANSPORT_LE) { log::warn("BD_ADDR {} not LE", rem_bda); - return (false); + return false; } log::verbose( - "BD_ADDR={}, subrate_min={}, subrate_max={}, max_latency={}, " - "cont_num={}, timeout={}", - rem_bda, subrate_min, subrate_max, max_latency, cont_num, timeout); + "BD_ADDR={}, subrate_min={}, subrate_max={}, max_latency={}, " + "cont_num={}, timeout={}", + rem_bda, subrate_min, subrate_max, max_latency, cont_num, timeout); p_lcb->subrate_min = subrate_min; p_lcb->subrate_max = subrate_max; @@ -527,7 +504,7 @@ bool L2CA_SubrateRequest(const RawAddress& rem_bda, uint16_t subrate_min, l2cble_start_subrate_change(p_lcb); - return (true); + return true; } /******************************************************************************* @@ -550,8 +527,7 @@ bool L2CA_SubrateRequest(const RawAddress& rem_bda, uint16_t subrate_min, ******************************************************************************/ void l2cble_process_subrate_change_evt(uint16_t handle, uint8_t status, uint16_t /* subrate_factor */, - uint16_t /* peripheral_latency */, - uint16_t /* cont_num */, + uint16_t /* peripheral_latency */, uint16_t /* cont_num */, uint16_t /* timeout */) { log::verbose(""); @@ -572,6 +548,6 @@ void l2cble_process_subrate_change_evt(uint16_t handle, uint8_t status, l2cble_start_subrate_change(p_lcb); - log::verbose("conn_update_mask={} , subrate_req_mask={}", - p_lcb->conn_update_mask, p_lcb->subrate_req_mask); + log::verbose("conn_update_mask={} , subrate_req_mask={}", p_lcb->conn_update_mask, + p_lcb->subrate_req_mask); } diff --git a/system/stack/l2cap/l2c_csm.cc b/system/stack/l2cap/l2c_csm.cc index 8ace353a83b..13401528c6b 100644 --- a/system/stack/l2cap/l2c_csm.cc +++ b/system/stack/l2cap/l2c_csm.cc @@ -49,20 +49,14 @@ using namespace bluetooth; /* L O C A L F U N C T I O N P R O T O T Y P E S */ /******************************************************************************/ static void l2c_csm_closed(tL2C_CCB* p_ccb, tL2CEVT event, void* p_data); -static void l2c_csm_orig_w4_sec_comp(tL2C_CCB* p_ccb, tL2CEVT event, - void* p_data); -static void l2c_csm_term_w4_sec_comp(tL2C_CCB* p_ccb, tL2CEVT event, - void* p_data); -static void l2c_csm_w4_l2cap_connect_rsp(tL2C_CCB* p_ccb, tL2CEVT event, - void* p_data); -static void l2c_csm_w4_l2ca_connect_rsp(tL2C_CCB* p_ccb, tL2CEVT event, - void* p_data); +static void l2c_csm_orig_w4_sec_comp(tL2C_CCB* p_ccb, tL2CEVT event, void* p_data); +static void l2c_csm_term_w4_sec_comp(tL2C_CCB* p_ccb, tL2CEVT event, void* p_data); +static void l2c_csm_w4_l2cap_connect_rsp(tL2C_CCB* p_ccb, tL2CEVT event, void* p_data); +static void l2c_csm_w4_l2ca_connect_rsp(tL2C_CCB* p_ccb, tL2CEVT event, void* p_data); static void l2c_csm_config(tL2C_CCB* p_ccb, tL2CEVT event, void* p_data); static void l2c_csm_open(tL2C_CCB* p_ccb, tL2CEVT event, void* p_data); -static void l2c_csm_w4_l2cap_disconnect_rsp(tL2C_CCB* p_ccb, tL2CEVT event, - void* p_data); -static void l2c_csm_w4_l2ca_disconnect_rsp(tL2C_CCB* p_ccb, tL2CEVT event, - void* p_data); +static void l2c_csm_w4_l2cap_disconnect_rsp(tL2C_CCB* p_ccb, tL2CEVT event, void* p_data); +static void l2c_csm_w4_l2ca_disconnect_rsp(tL2C_CCB* p_ccb, tL2CEVT event, void* p_data); static const char* l2c_csm_get_event_name(tL2CEVT event); @@ -104,20 +98,18 @@ static void l2c_csm_indicate_connection_open(tL2C_CCB* p_ccb) { (*p_ccb->p_rcb->api.pL2CA_ConnectCfm_Cb)(p_ccb->local_cid, L2CAP_CONN_OK); } else { if (*p_ccb->p_rcb->api.pL2CA_ConnectInd_Cb) { - (*p_ccb->p_rcb->api.pL2CA_ConnectInd_Cb)( - p_ccb->p_lcb->remote_bd_addr, p_ccb->local_cid, p_ccb->p_rcb->psm, - p_ccb->remote_id); + (*p_ccb->p_rcb->api.pL2CA_ConnectInd_Cb)(p_ccb->p_lcb->remote_bd_addr, p_ccb->local_cid, + p_ccb->p_rcb->psm, p_ccb->remote_id); } else { log::warn("pL2CA_ConnectInd_Cb is null"); } } if (p_ccb->chnl_state == CST_OPEN && !p_ccb->p_lcb->is_transport_ble()) { - (*p_ccb->p_rcb->api.pL2CA_ConfigCfm_Cb)( - p_ccb->local_cid, p_ccb->connection_initiator, &p_ccb->peer_cfg); + (*p_ccb->p_rcb->api.pL2CA_ConfigCfm_Cb)(p_ccb->local_cid, p_ccb->connection_initiator, + &p_ccb->peer_cfg); } power_telemetry::GetInstance().LogChannelConnected( - p_ccb->p_rcb->psm, p_ccb->local_cid, p_ccb->remote_id, - p_ccb->p_lcb->remote_bd_addr); + p_ccb->p_rcb->psm, p_ccb->local_cid, p_ccb->remote_id, p_ccb->p_lcb->remote_bd_addr); } /******************************************************************************* @@ -143,9 +135,8 @@ void l2c_csm_execute(tL2C_CCB* p_ccb, tL2CEVT event, void* p_data) { // Log all but data events if (event != L2CEVT_L2CAP_DATA && event != L2CEVT_L2CA_DATA_READ && event != L2CEVT_L2CA_DATA_WRITE) { - log::info("Enter CSM, chnl_state:{} [{}], event:{} [{}]", - channel_state_text(p_ccb->chnl_state), p_ccb->chnl_state, - l2c_csm_get_event_name(event), event); + log::info("Enter CSM, chnl_state:{} [{}], event:{} [{}]", channel_state_text(p_ccb->chnl_state), + p_ccb->chnl_state, l2c_csm_get_event_name(event), event); } switch (p_ccb->chnl_state) { @@ -208,8 +199,8 @@ static void l2c_csm_closed(tL2C_CCB* p_ccb, tL2CEVT event, void* p_data) { tL2CA_DISCONNECT_IND_CB* disconnect_ind; if (p_ccb->p_rcb == NULL) { - log::error("LCID: 0x{:04x} st: CLOSED evt: {} p_rcb == NULL", - p_ccb->local_cid, l2c_csm_get_event_name(event)); + log::error("LCID: 0x{:04x} st: CLOSED evt: {} p_rcb == NULL", p_ccb->local_cid, + l2c_csm_get_event_name(event)); return; } @@ -220,8 +211,7 @@ static void l2c_csm_closed(tL2C_CCB* p_ccb, tL2CEVT event, void* p_data) { switch (event) { case L2CEVT_LP_DISCONNECT_IND: /* Link was disconnected */ - log::debug("Calling Disconnect_Ind_Cb(), CID: 0x{:04x} No Conf Needed", - p_ccb->local_cid); + log::debug("Calling Disconnect_Ind_Cb(), CID: 0x{:04x} No Conf Needed", p_ccb->local_cid); l2cu_release_ccb(p_ccb); (*disconnect_ind)(local_cid, false); break; @@ -229,13 +219,12 @@ static void l2c_csm_closed(tL2C_CCB* p_ccb, tL2CEVT event, void* p_data) { case L2CEVT_LP_CONNECT_CFM: /* Link came up */ if (p_ccb->p_lcb->transport == BT_TRANSPORT_LE) { p_ccb->chnl_state = CST_ORIG_W4_SEC_COMP; - l2ble_sec_access_req(p_ccb->p_lcb->remote_bd_addr, p_ccb->p_rcb->psm, - true, &l2c_link_sec_comp, p_ccb); + l2ble_sec_access_req(p_ccb->p_lcb->remote_bd_addr, p_ccb->p_rcb->psm, true, + &l2c_link_sec_comp, p_ccb); } else { p_ccb->chnl_state = CST_ORIG_W4_SEC_COMP; - btm_sec_l2cap_access_req(p_ccb->p_lcb->remote_bd_addr, - p_ccb->p_rcb->psm, true, &l2c_link_sec_comp, - p_ccb); + btm_sec_l2cap_access_req(p_ccb->p_lcb->remote_bd_addr, p_ccb->p_rcb->psm, true, + &l2c_link_sec_comp, p_ccb); } break; @@ -244,12 +233,9 @@ static void l2c_csm_closed(tL2C_CCB* p_ccb, tL2CEVT event, void* p_data) { btm_acl_notif_conn_collision(p_ccb->p_lcb->remote_bd_addr); } else { l2cu_release_ccb(p_ccb); - (*p_ccb->p_rcb->api.pL2CA_Error_Cb)(local_cid, - L2CAP_CONN_ACL_CONNECTION_FAILED); + (*p_ccb->p_rcb->api.pL2CA_Error_Cb)(local_cid, L2CAP_CONN_ACL_CONNECTION_FAILED); bluetooth::shim::CountCounterMetrics( - android::bluetooth::CodePathCounterKeyEnum:: - L2CAP_CONNECT_CONFIRM_NEG, - 1); + android::bluetooth::CodePathCounterKeyEnum::L2CAP_CONNECT_CONFIRM_NEG, 1); } break; @@ -257,17 +243,16 @@ static void l2c_csm_closed(tL2C_CCB* p_ccb, tL2CEVT event, void* p_data) { case L2CEVT_L2CA_CONNECT_REQ: if (p_ccb->p_lcb->transport == BT_TRANSPORT_LE) { p_ccb->chnl_state = CST_ORIG_W4_SEC_COMP; - l2ble_sec_access_req(p_ccb->p_lcb->remote_bd_addr, p_ccb->p_rcb->psm, - true, &l2c_link_sec_comp, p_ccb); + l2ble_sec_access_req(p_ccb->p_lcb->remote_bd_addr, p_ccb->p_rcb->psm, true, + &l2c_link_sec_comp, p_ccb); } else { if (!BTM_SetLinkPolicyActiveMode(p_ccb->p_lcb->remote_bd_addr)) { log::warn("Unable to set link policy active"); } /* If sec access does not result in started SEC_COM or COMP_NEG are * already processed */ - if (btm_sec_l2cap_access_req( - p_ccb->p_lcb->remote_bd_addr, p_ccb->p_rcb->psm, true, - &l2c_link_sec_comp, p_ccb) == BTM_CMD_STARTED) { + if (btm_sec_l2cap_access_req(p_ccb->p_lcb->remote_bd_addr, p_ccb->p_rcb->psm, true, + &l2c_link_sec_comp, p_ccb) == BTM_CMD_STARTED) { p_ccb->chnl_state = CST_ORIG_W4_SEC_COMP; } } @@ -282,16 +267,13 @@ static void l2c_csm_closed(tL2C_CCB* p_ccb, tL2CEVT event, void* p_data) { /* Need to have at least one compatible channel to continue */ if (!l2c_fcr_chk_chan_modes(p_ccb)) { l2cu_release_ccb(p_ccb); - (*p_ccb->p_rcb->api.pL2CA_Error_Cb)(local_cid, - L2CAP_CONN_OTHER_ERROR); - bluetooth::shim::CountCounterMetrics( - android::bluetooth::CodePathCounterKeyEnum:: - L2CAP_NO_COMPATIBLE_CHANNEL_AT_CSM_CLOSED, - 1); + (*p_ccb->p_rcb->api.pL2CA_Error_Cb)(local_cid, L2CAP_CONN_OTHER_ERROR); + bluetooth::shim::CountCounterMetrics(android::bluetooth::CodePathCounterKeyEnum:: + L2CAP_NO_COMPATIBLE_CHANNEL_AT_CSM_CLOSED, + 1); } else { l2cu_send_peer_connect_req(p_ccb); - alarm_set_on_mloop(p_ccb->l2c_ccb_timer, - L2CAP_CHNL_CONNECT_TIMEOUT_MS, + alarm_set_on_mloop(p_ccb->l2c_ccb_timer, L2CAP_CHNL_CONNECT_TIMEOUT_MS, l2c_ccb_timer_timeout, p_ccb); } } @@ -299,12 +281,9 @@ static void l2c_csm_closed(tL2C_CCB* p_ccb, tL2CEVT event, void* p_data) { case L2CEVT_SEC_COMP_NEG: /* something is really bad with security */ l2cu_release_ccb(p_ccb); - (*p_ccb->p_rcb->api.pL2CA_Error_Cb)( - local_cid, L2CAP_CONN_CLIENT_SECURITY_CLEARANCE_FAILED); + (*p_ccb->p_rcb->api.pL2CA_Error_Cb)(local_cid, L2CAP_CONN_CLIENT_SECURITY_CLEARANCE_FAILED); bluetooth::shim::CountCounterMetrics( - android::bluetooth::CodePathCounterKeyEnum:: - L2CAP_SECURITY_NEG_AT_CSM_CLOSED, - 1); + android::bluetooth::CodePathCounterKeyEnum::L2CAP_SECURITY_NEG_AT_CSM_CLOSED, 1); break; case L2CEVT_L2CAP_CREDIT_BASED_CONNECT_REQ: /* Peer connect request */ @@ -316,8 +295,7 @@ static void l2c_csm_closed(tL2C_CCB* p_ccb, tL2CEVT event, void* p_data) { if (p_ccb->p_lcb->transport == BT_TRANSPORT_LE) { p_ccb->chnl_state = CST_TERM_W4_SEC_COMP; tL2CAP_LE_RESULT_CODE result = l2ble_sec_access_req( - p_ccb->p_lcb->remote_bd_addr, p_ccb->p_rcb->psm, false, - &l2c_link_sec_comp, p_ccb); + p_ccb->p_lcb->remote_bd_addr, p_ccb->p_rcb->psm, false, &l2c_link_sec_comp, p_ccb); switch (result) { case L2CAP_LE_RESULT_INSUFFICIENT_AUTHORIZATION: @@ -341,15 +319,13 @@ static void l2c_csm_closed(tL2C_CCB* p_ccb, tL2CEVT event, void* p_data) { log::warn("Unable to set link policy active"); } p_ccb->chnl_state = CST_TERM_W4_SEC_COMP; - auto status = btm_sec_l2cap_access_req(p_ccb->p_lcb->remote_bd_addr, - p_ccb->p_rcb->psm, false, - &l2c_link_sec_comp, p_ccb); + auto status = btm_sec_l2cap_access_req(p_ccb->p_lcb->remote_bd_addr, p_ccb->p_rcb->psm, + false, &l2c_link_sec_comp, p_ccb); if (status == BTM_CMD_STARTED) { // started the security process, tell the peer to set a longer timer l2cu_send_peer_connect_rsp(p_ccb, L2CAP_CONN_PENDING, 0); } else { - log::info("Check security for psm 0x{:04x}, status {}", - p_ccb->p_rcb->psm, status); + log::info("Check security for psm 0x{:04x}, status {}", p_ccb->p_rcb->psm, status); } } break; @@ -358,9 +334,7 @@ static void l2c_csm_closed(tL2C_CCB* p_ccb, tL2CEVT event, void* p_data) { l2cu_release_ccb(p_ccb); (*p_ccb->p_rcb->api.pL2CA_Error_Cb)(local_cid, L2CAP_CONN_OTHER_ERROR); bluetooth::shim::CountCounterMetrics( - android::bluetooth::CodePathCounterKeyEnum:: - L2CAP_TIMEOUT_AT_CSM_CLOSED, - 1); + android::bluetooth::CodePathCounterKeyEnum::L2CAP_TIMEOUT_AT_CSM_CLOSED, 1); break; case L2CEVT_L2CAP_DATA: /* Peer data packet rcvd */ @@ -375,9 +349,8 @@ static void l2c_csm_closed(tL2C_CCB* p_ccb, tL2CEVT event, void* p_data) { default: log::error("Handling unexpected event:{}", l2c_csm_get_event_name(event)); } - log::verbose("Exit chnl_state={} [{}], event={} [{}]", - channel_state_text(p_ccb->chnl_state), p_ccb->chnl_state, - l2c_csm_get_event_name(event), event); + log::verbose("Exit chnl_state={} [{}], event={} [{}]", channel_state_text(p_ccb->chnl_state), + p_ccb->chnl_state, l2c_csm_get_event_name(event), event); } /******************************************************************************* @@ -390,22 +363,17 @@ static void l2c_csm_closed(tL2C_CCB* p_ccb, tL2CEVT event, void* p_data) { * Returns void * ******************************************************************************/ -static void l2c_csm_orig_w4_sec_comp(tL2C_CCB* p_ccb, tL2CEVT event, - void* p_data) { - tL2CA_DISCONNECT_IND_CB* disconnect_ind = - p_ccb->p_rcb->api.pL2CA_DisconnectInd_Cb; +static void l2c_csm_orig_w4_sec_comp(tL2C_CCB* p_ccb, tL2CEVT event, void* p_data) { + tL2CA_DISCONNECT_IND_CB* disconnect_ind = p_ccb->p_rcb->api.pL2CA_DisconnectInd_Cb; uint16_t local_cid = p_ccb->local_cid; log::debug("{} - LCID: 0x{:04x} st: ORIG_W4_SEC_COMP evt: {}", - ((p_ccb->p_lcb) && (p_ccb->p_lcb->transport == BT_TRANSPORT_LE)) - ? "LE " - : "", + ((p_ccb->p_lcb) && (p_ccb->p_lcb->transport == BT_TRANSPORT_LE)) ? "LE " : "", p_ccb->local_cid, l2c_csm_get_event_name(event)); switch (event) { case L2CEVT_LP_DISCONNECT_IND: /* Link was disconnected */ - log::debug("Calling Disconnect_Ind_Cb(), CID: 0x{:04x} No Conf Needed", - p_ccb->local_cid); + log::debug("Calling Disconnect_Ind_Cb(), CID: 0x{:04x} No Conf Needed", p_ccb->local_cid); l2cu_release_ccb(p_ccb); (*disconnect_ind)(local_cid, false); break; @@ -413,12 +381,11 @@ static void l2c_csm_orig_w4_sec_comp(tL2C_CCB* p_ccb, tL2CEVT event, case L2CEVT_SEC_RE_SEND_CMD: /* BTM has enough info to proceed */ case L2CEVT_LP_CONNECT_CFM: /* Link came up */ if (p_ccb->p_lcb->transport == BT_TRANSPORT_LE) { - l2ble_sec_access_req(p_ccb->p_lcb->remote_bd_addr, p_ccb->p_rcb->psm, - false, &l2c_link_sec_comp, p_ccb); + l2ble_sec_access_req(p_ccb->p_lcb->remote_bd_addr, p_ccb->p_rcb->psm, false, + &l2c_link_sec_comp, p_ccb); } else { - btm_sec_l2cap_access_req(p_ccb->p_lcb->remote_bd_addr, - p_ccb->p_rcb->psm, true, &l2c_link_sec_comp, - p_ccb); + btm_sec_l2cap_access_req(p_ccb->p_lcb->remote_bd_addr, p_ccb->p_rcb->psm, true, + &l2c_link_sec_comp, p_ccb); } break; @@ -435,15 +402,12 @@ static void l2c_csm_orig_w4_sec_comp(tL2C_CCB* p_ccb, tL2CEVT event, /* Need to have at least one compatible channel to continue */ if (!l2c_fcr_chk_chan_modes(p_ccb)) { l2cu_release_ccb(p_ccb); - (*p_ccb->p_rcb->api.pL2CA_Error_Cb)(local_cid, - L2CAP_CONN_OTHER_ERROR); - bluetooth::shim::CountCounterMetrics( - android::bluetooth::CodePathCounterKeyEnum:: - L2CAP_NO_COMPATIBLE_CHANNEL_AT_W4_SEC, - 1); + (*p_ccb->p_rcb->api.pL2CA_Error_Cb)(local_cid, L2CAP_CONN_OTHER_ERROR); + bluetooth::shim::CountCounterMetrics(android::bluetooth::CodePathCounterKeyEnum:: + L2CAP_NO_COMPATIBLE_CHANNEL_AT_W4_SEC, + 1); } else { - alarm_set_on_mloop(p_ccb->l2c_ccb_timer, - L2CAP_CHNL_CONNECT_TIMEOUT_MS, + alarm_set_on_mloop(p_ccb->l2c_ccb_timer, L2CAP_CHNL_CONNECT_TIMEOUT_MS, l2c_ccb_timer_timeout, p_ccb); l2cu_send_peer_connect_req(p_ccb); /* Start Connection */ } @@ -460,12 +424,9 @@ static void l2c_csm_orig_w4_sec_comp(tL2C_CCB* p_ccb, tL2CEVT event, } l2cu_release_ccb(p_ccb); - (*p_ccb->p_rcb->api.pL2CA_Error_Cb)( - local_cid, L2CAP_CONN_CLIENT_SECURITY_CLEARANCE_FAILED); + (*p_ccb->p_rcb->api.pL2CA_Error_Cb)(local_cid, L2CAP_CONN_CLIENT_SECURITY_CLEARANCE_FAILED); bluetooth::shim::CountCounterMetrics( - android::bluetooth::CodePathCounterKeyEnum:: - L2CAP_SECURITY_NEG_AT_W4_SEC, - 1); + android::bluetooth::CodePathCounterKeyEnum::L2CAP_SECURITY_NEG_AT_W4_SEC, 1); break; case L2CEVT_L2CA_DATA_WRITE: /* Upper layer data to send */ @@ -483,9 +444,8 @@ static void l2c_csm_orig_w4_sec_comp(tL2C_CCB* p_ccb, tL2CEVT event, default: log::error("Handling unexpected event:{}", l2c_csm_get_event_name(event)); } - log::verbose("Exit chnl_state={} [{}], event={} [{}]", - channel_state_text(p_ccb->chnl_state), p_ccb->chnl_state, - l2c_csm_get_event_name(event), event); + log::verbose("Exit chnl_state={} [{}], event={} [{}]", channel_state_text(p_ccb->chnl_state), + p_ccb->chnl_state, l2c_csm_get_event_name(event), event); } /******************************************************************************* @@ -498,8 +458,7 @@ static void l2c_csm_orig_w4_sec_comp(tL2C_CCB* p_ccb, tL2CEVT event, * Returns void * ******************************************************************************/ -static void l2c_csm_term_w4_sec_comp(tL2C_CCB* p_ccb, tL2CEVT event, - void* p_data) { +static void l2c_csm_term_w4_sec_comp(tL2C_CCB* p_ccb, tL2CEVT event, void* p_data) { log::debug("LCID: 0x{:04x} st: TERM_W4_SEC_COMP evt: {}", p_ccb->local_cid, l2c_csm_get_event_name(event)); @@ -535,16 +494,17 @@ static void l2c_csm_term_w4_sec_comp(tL2C_CCB* p_ccb, tL2CEVT event, std::vector pending_cids; for (int i = 0; i < p_ccb->p_lcb->pending_ecoc_conn_cnt; i++) { uint16_t cid = p_ccb->p_lcb->pending_ecoc_connection_cids[i]; - if (cid != 0) pending_cids.push_back(cid); + if (cid != 0) { + pending_cids.push_back(cid); + } } (*p_ccb->p_rcb->api.pL2CA_CreditBasedConnectInd_Cb)( - p_ccb->p_lcb->remote_bd_addr, pending_cids, p_ccb->p_rcb->psm, - p_ccb->peer_conn_cfg.mtu, p_ccb->remote_id); + p_ccb->p_lcb->remote_bd_addr, pending_cids, p_ccb->p_rcb->psm, + p_ccb->peer_conn_cfg.mtu, p_ccb->remote_id); } else { /* Handle BLE CoC */ - log::debug("Calling Connect_Ind_Cb(), CID: 0x{:04x}", - p_ccb->local_cid); + log::debug("Calling Connect_Ind_Cb(), CID: 0x{:04x}", p_ccb->local_cid); l2c_csm_send_connect_rsp(p_ccb); l2c_csm_indicate_connection_open(p_ccb); } @@ -575,16 +535,15 @@ static void l2c_csm_term_w4_sec_comp(tL2C_CCB* p_ccb, tL2CEVT event, if (((tL2C_CONN_INFO*)p_data)->status == BTM_DELAY_CHECK) { /* start a timer - encryption change not received before L2CAP connect * req */ - alarm_set_on_mloop(p_ccb->l2c_ccb_timer, - L2CAP_DELAY_CHECK_SM4_TIMEOUT_MS, + alarm_set_on_mloop(p_ccb->l2c_ccb_timer, L2CAP_DELAY_CHECK_SM4_TIMEOUT_MS, l2c_ccb_timer_timeout, p_ccb); } else { - if (p_ccb->p_lcb->transport == BT_TRANSPORT_LE) - l2cu_reject_ble_connection( - p_ccb, p_ccb->remote_id, - L2CAP_LE_RESULT_INSUFFICIENT_AUTHENTICATION); - else + if (p_ccb->p_lcb->transport == BT_TRANSPORT_LE) { + l2cu_reject_ble_connection(p_ccb, p_ccb->remote_id, + L2CAP_LE_RESULT_INSUFFICIENT_AUTHENTICATION); + } else { l2cu_send_peer_connect_rsp(p_ccb, L2CAP_CONN_SECURITY_BLOCK, 0); + } l2cu_release_ccb(p_ccb); } break; @@ -599,8 +558,7 @@ static void l2c_csm_term_w4_sec_comp(tL2C_CCB* p_ccb, tL2CEVT event, break; case L2CEVT_L2CAP_DISCONNECT_REQ: /* Peer disconnected request */ - l2cu_send_peer_disc_rsp(p_ccb->p_lcb, p_ccb->remote_id, p_ccb->local_cid, - p_ccb->remote_cid); + l2cu_send_peer_disc_rsp(p_ccb->p_lcb, p_ccb->remote_id, p_ccb->local_cid, p_ccb->remote_cid); /* Tell security manager to abort */ btm_sec_abort_access_req(p_ccb->p_lcb->remote_bd_addr); @@ -610,22 +568,20 @@ static void l2c_csm_term_w4_sec_comp(tL2C_CCB* p_ccb, tL2CEVT event, case L2CEVT_TIMEOUT: /* SM4 related. */ - acl_disconnect_from_handle( - p_ccb->p_lcb->Handle(), HCI_ERR_AUTH_FAILURE, - "stack::l2cap::l2c_csm::l2c_csm_term_w4_sec_comp Event timeout"); + acl_disconnect_from_handle(p_ccb->p_lcb->Handle(), HCI_ERR_AUTH_FAILURE, + "stack::l2cap::l2c_csm::l2c_csm_term_w4_sec_comp Event timeout"); break; case L2CEVT_SEC_RE_SEND_CMD: /* BTM has enough info to proceed */ - btm_sec_l2cap_access_req(p_ccb->p_lcb->remote_bd_addr, p_ccb->p_rcb->psm, - false, &l2c_link_sec_comp, p_ccb); + btm_sec_l2cap_access_req(p_ccb->p_lcb->remote_bd_addr, p_ccb->p_rcb->psm, false, + &l2c_link_sec_comp, p_ccb); break; default: log::error("Handling unexpected event:{}", l2c_csm_get_event_name(event)); } - log::verbose("Exit chnl_state={} [{}], event={} [{}]", - channel_state_text(p_ccb->chnl_state), p_ccb->chnl_state, - l2c_csm_get_event_name(event), event); + log::verbose("Exit chnl_state={} [{}], event={} [{}]", channel_state_text(p_ccb->chnl_state), + p_ccb->chnl_state, l2c_csm_get_event_name(event), event); } /******************************************************************************* @@ -638,13 +594,11 @@ static void l2c_csm_term_w4_sec_comp(tL2C_CCB* p_ccb, tL2CEVT event, * Returns void * ******************************************************************************/ -static void l2c_csm_w4_l2cap_connect_rsp(tL2C_CCB* p_ccb, tL2CEVT event, - void* p_data) { +static void l2c_csm_w4_l2cap_connect_rsp(tL2C_CCB* p_ccb, tL2CEVT event, void* p_data) { tL2C_CONN_INFO* p_ci = (tL2C_CONN_INFO*)p_data; - tL2CA_DISCONNECT_IND_CB* disconnect_ind = - p_ccb->p_rcb->api.pL2CA_DisconnectInd_Cb; + tL2CA_DISCONNECT_IND_CB* disconnect_ind = p_ccb->p_rcb->api.pL2CA_DisconnectInd_Cb; tL2CA_CREDIT_BASED_CONNECT_CFM_CB* credit_based_connect_cfm = - p_ccb->p_rcb->api.pL2CA_CreditBasedConnectCfm_Cb; + p_ccb->p_rcb->api.pL2CA_CreditBasedConnectCfm_Cb; uint16_t local_cid = p_ccb->local_cid; tL2C_LCB* p_lcb = p_ccb->p_lcb; @@ -660,8 +614,7 @@ static void l2c_csm_w4_l2cap_connect_rsp(tL2C_CCB* p_ccb, tL2CEVT event, p_ccb->chnl_state = CST_CLOSED; if ((p_ccb->flags & CCB_FLAG_NO_RETRY) || !p_data || (*((uint8_t*)p_data) != HCI_ERR_PEER_USER)) { - log::debug("Calling Disconnect_Ind_Cb(), CID: 0x{:04x} No Conf Needed", - p_ccb->local_cid); + log::debug("Calling Disconnect_Ind_Cb(), CID: 0x{:04x} No Conf Needed", p_ccb->local_cid); l2cu_release_ccb(p_ccb); (*disconnect_ind)(local_cid, false); } @@ -680,56 +633,50 @@ static void l2c_csm_w4_l2cap_connect_rsp(tL2C_CCB* p_ccb, tL2CEVT event, l2c_csm_execute(p_ccb, L2CEVT_L2CA_CONNECT_RSP, NULL); } else { p_ccb->chnl_state = CST_CONFIG; - alarm_set_on_mloop(p_ccb->l2c_ccb_timer, L2CAP_CHNL_CFG_TIMEOUT_MS, - l2c_ccb_timer_timeout, p_ccb); + alarm_set_on_mloop(p_ccb->l2c_ccb_timer, L2CAP_CHNL_CFG_TIMEOUT_MS, l2c_ccb_timer_timeout, + p_ccb); } - log::debug("Calling Connect_Cfm_Cb(), CID: 0x{:04x}, Success", - p_ccb->local_cid); + log::debug("Calling Connect_Cfm_Cb(), CID: 0x{:04x}, Success", p_ccb->local_cid); l2c_csm_send_config_req(p_ccb); break; case L2CEVT_L2CAP_CONNECT_RSP_PND: /* Got peer connect pending */ p_ccb->remote_cid = p_ci->remote_cid; - alarm_set_on_mloop(p_ccb->l2c_ccb_timer, - L2CAP_CHNL_CONNECT_EXT_TIMEOUT_MS, + alarm_set_on_mloop(p_ccb->l2c_ccb_timer, L2CAP_CHNL_CONNECT_EXT_TIMEOUT_MS, l2c_ccb_timer_timeout, p_ccb); break; case L2CEVT_L2CAP_CREDIT_BASED_CONNECT_RSP: alarm_cancel(p_ccb->l2c_ccb_timer); p_ccb->chnl_state = CST_OPEN; - log::debug("Calling credit_based_connect_cfm(),cid {}, result 0x{:04x}", - p_ccb->local_cid, L2CAP_CONN_OK); + log::debug("Calling credit_based_connect_cfm(),cid {}, result 0x{:04x}", p_ccb->local_cid, + L2CAP_CONN_OK); - (*credit_based_connect_cfm)(p_lcb->remote_bd_addr, p_ccb->local_cid, - p_ci->peer_mtu, L2CAP_CONN_OK); + (*credit_based_connect_cfm)(p_lcb->remote_bd_addr, p_ccb->local_cid, p_ci->peer_mtu, + L2CAP_CONN_OK); break; case L2CEVT_L2CAP_CREDIT_BASED_CONNECT_RSP_NEG: - log::debug("Calling pL2CA_Error_Cb(),cid {}, result 0x{:04x}", local_cid, - p_ci->l2cap_result); + log::debug("Calling pL2CA_Error_Cb(),cid {}, result 0x{:04x}", local_cid, p_ci->l2cap_result); (*p_ccb->p_rcb->api.pL2CA_Error_Cb)(local_cid, p_ci->l2cap_result); bluetooth::shim::CountCounterMetrics( - android::bluetooth::CodePathCounterKeyEnum:: - L2CAP_CREDIT_BASED_CONNECT_RSP_NEG, - 1); + android::bluetooth::CodePathCounterKeyEnum::L2CAP_CREDIT_BASED_CONNECT_RSP_NEG, 1); l2cu_release_ccb(p_ccb); break; case L2CEVT_L2CAP_CONNECT_RSP_NEG: /* Peer rejected connection */ - log::warn("L2CAP connection rejected, lcid=0x{:x}, reason=0x{:x}", - p_ccb->local_cid, p_ci->l2cap_result); + log::warn("L2CAP connection rejected, lcid=0x{:x}, reason=0x{:x}", p_ccb->local_cid, + p_ci->l2cap_result); l2cu_release_ccb(p_ccb); if (p_lcb->transport == BT_TRANSPORT_LE) { - (*p_ccb->p_rcb->api.pL2CA_Error_Cb)( - local_cid, le_result_to_l2c_conn(p_ci->l2cap_result)); + (*p_ccb->p_rcb->api.pL2CA_Error_Cb)(local_cid, le_result_to_l2c_conn(p_ci->l2cap_result)); } else { (*p_ccb->p_rcb->api.pL2CA_Error_Cb)(local_cid, L2CAP_CONN_OTHER_ERROR); } bluetooth::shim::CountCounterMetrics( - android::bluetooth::CodePathCounterKeyEnum::L2CAP_CONNECT_RSP_NEG, 1); + android::bluetooth::CodePathCounterKeyEnum::L2CAP_CONNECT_RSP_NEG, 1); break; case L2CEVT_TIMEOUT: @@ -740,26 +687,21 @@ static void l2c_csm_w4_l2cap_connect_rsp(tL2C_CCB* p_ccb, tL2CEVT event, uint16_t cid = p_lcb->pending_ecoc_connection_cids[i]; tL2C_CCB* temp_p_ccb = l2cu_find_ccb_by_cid(p_lcb, cid); log::warn("lcid= 0x{:x}", cid); - (*p_ccb->p_rcb->api.pL2CA_Error_Cb)(p_ccb->local_cid, - L2CAP_CONN_TIMEOUT); + (*p_ccb->p_rcb->api.pL2CA_Error_Cb)(p_ccb->local_cid, L2CAP_CONN_TIMEOUT); bluetooth::shim::CountCounterMetrics( - android::bluetooth::CodePathCounterKeyEnum:: - L2CAP_TIMEOUT_AT_CONNECT_RSP, - 1); + android::bluetooth::CodePathCounterKeyEnum::L2CAP_TIMEOUT_AT_CONNECT_RSP, 1); l2cu_release_ccb(temp_p_ccb); } p_lcb->pending_ecoc_conn_cnt = 0; - memset(p_lcb->pending_ecoc_connection_cids, 0, - L2CAP_CREDIT_BASED_MAX_CIDS); + memset(p_lcb->pending_ecoc_connection_cids, 0, L2CAP_CREDIT_BASED_MAX_CIDS); } else { log::warn("lcid= 0x{:x}", p_ccb->local_cid); l2cu_release_ccb(p_ccb); (*p_ccb->p_rcb->api.pL2CA_Error_Cb)(local_cid, L2CAP_CONN_OTHER_ERROR); bluetooth::shim::CountCounterMetrics( - android::bluetooth::CodePathCounterKeyEnum:: - L2CAP_CONN_OTHER_ERROR_AT_CONNECT_RSP, - 1); + android::bluetooth::CodePathCounterKeyEnum::L2CAP_CONN_OTHER_ERROR_AT_CONNECT_RSP, + 1); } break; @@ -768,12 +710,10 @@ static void l2c_csm_w4_l2cap_connect_rsp(tL2C_CCB* p_ccb, tL2CEVT event, if (p_ccb->remote_cid != 0) { l2cu_send_peer_disc_req(p_ccb); p_ccb->chnl_state = CST_W4_L2CAP_DISCONNECT_RSP; - alarm_set_on_mloop(p_ccb->l2c_ccb_timer, - L2CAP_CHNL_DISCONNECT_TIMEOUT_MS, + alarm_set_on_mloop(p_ccb->l2c_ccb_timer, L2CAP_CHNL_DISCONNECT_TIMEOUT_MS, l2c_ccb_timer_timeout, p_ccb); } else { - tL2CA_DISCONNECT_CFM_CB* disconnect_cfm = - p_ccb->p_rcb->api.pL2CA_DisconnectCfm_Cb; + tL2CA_DISCONNECT_CFM_CB* disconnect_cfm = p_ccb->p_rcb->api.pL2CA_DisconnectCfm_Cb; l2cu_release_ccb(p_ccb); if (disconnect_cfm != nullptr) { (*disconnect_cfm)(local_cid, L2CAP_CONN_NO_LINK); @@ -792,9 +732,8 @@ static void l2c_csm_w4_l2cap_connect_rsp(tL2C_CCB* p_ccb, tL2CEVT event, l2cu_release_ccb(p_ccb); (*p_ccb->p_rcb->api.pL2CA_Error_Cb)(local_cid, L2CAP_CONN_OTHER_ERROR); bluetooth::shim::CountCounterMetrics( - android::bluetooth::CodePathCounterKeyEnum:: - L2CAP_INFO_NO_COMPATIBLE_CHANNEL_AT_RSP, - 1); + android::bluetooth::CodePathCounterKeyEnum::L2CAP_INFO_NO_COMPATIBLE_CHANNEL_AT_RSP, + 1); } else { /* We have feature info, so now send peer connect request */ alarm_set_on_mloop(p_ccb->l2c_ccb_timer, L2CAP_CHNL_CONNECT_TIMEOUT_MS, @@ -806,9 +745,8 @@ static void l2c_csm_w4_l2cap_connect_rsp(tL2C_CCB* p_ccb, tL2CEVT event, default: log::error("Handling unexpected event:{}", l2c_csm_get_event_name(event)); } - log::verbose("Exit chnl_state={} [{}], event={} [{}]", - channel_state_text(p_ccb->chnl_state), p_ccb->chnl_state, - l2c_csm_get_event_name(event), event); + log::verbose("Exit chnl_state={} [{}], event={} [{}]", channel_state_text(p_ccb->chnl_state), + p_ccb->chnl_state, l2c_csm_get_event_name(event), event); } /******************************************************************************* @@ -821,12 +759,10 @@ static void l2c_csm_w4_l2cap_connect_rsp(tL2C_CCB* p_ccb, tL2CEVT event, * Returns void * ******************************************************************************/ -static void l2c_csm_w4_l2ca_connect_rsp(tL2C_CCB* p_ccb, tL2CEVT event, - void* p_data) { +static void l2c_csm_w4_l2ca_connect_rsp(tL2C_CCB* p_ccb, tL2CEVT event, void* p_data) { tL2C_CONN_INFO* p_ci; tL2C_LCB* p_lcb = p_ccb->p_lcb; - tL2CA_DISCONNECT_IND_CB* disconnect_ind = - p_ccb->p_rcb->api.pL2CA_DisconnectInd_Cb; + tL2CA_DISCONNECT_IND_CB* disconnect_ind = p_ccb->p_rcb->api.pL2CA_DisconnectInd_Cb; uint16_t local_cid = p_ccb->local_cid; log::debug("LCID: 0x{:04x} st: W4_L2CA_CON_RSP evt: {}", p_ccb->local_cid, @@ -834,8 +770,7 @@ static void l2c_csm_w4_l2ca_connect_rsp(tL2C_CCB* p_ccb, tL2CEVT event, switch (event) { case L2CEVT_LP_DISCONNECT_IND: /* Link was disconnected */ - log::debug("Calling Disconnect_Ind_Cb(), CID: 0x{:04x} No Conf Needed", - p_ccb->local_cid); + log::debug("Calling Disconnect_Ind_Cb(), CID: 0x{:04x} No Conf Needed", p_ccb->local_cid); l2cu_release_ccb(p_ccb); (*disconnect_ind)(local_cid, false); break; @@ -846,8 +781,7 @@ static void l2c_csm_w4_l2ca_connect_rsp(tL2C_CCB* p_ccb, tL2CEVT event, log::warn("LE link doesn't exist"); return; } - l2cu_send_peer_credit_based_conn_res(p_ccb, p_ci->lcids, - p_ci->l2cap_result); + l2cu_send_peer_credit_based_conn_res(p_ccb, p_ci->lcids, p_ci->l2cap_result); alarm_cancel(p_ccb->l2c_ccb_timer); for (int i = 0; i < p_lcb->pending_ecoc_conn_cnt; i++) { @@ -865,16 +799,12 @@ static void l2c_csm_w4_l2ca_connect_rsp(tL2C_CCB* p_ccb, tL2CEVT event, } else { l2cu_release_ccb(temp_p_ccb); } - } - else { - log::warn( - "temp_p_ccb is NULL, pending_ecoc_connection_cids[{}] is {}", i, - cid); + } else { + log::warn("temp_p_ccb is NULL, pending_ecoc_connection_cids[{}] is {}", i, cid); } } p_lcb->pending_ecoc_conn_cnt = 0; - memset(p_lcb->pending_ecoc_connection_cids, 0, - L2CAP_CREDIT_BASED_MAX_CIDS); + memset(p_lcb->pending_ecoc_connection_cids, 0, L2CAP_CREDIT_BASED_MAX_CIDS); break; case L2CEVT_L2CA_CONNECT_RSP: @@ -895,16 +825,14 @@ static void l2c_csm_w4_l2ca_connect_rsp(tL2C_CCB* p_ccb, tL2CEVT event, log::debug("Sending connection ok for BR_EDR"); l2cu_send_peer_connect_rsp(p_ccb, L2CAP_CONN_OK, 0); p_ccb->chnl_state = CST_CONFIG; - alarm_set_on_mloop(p_ccb->l2c_ccb_timer, L2CAP_CHNL_CFG_TIMEOUT_MS, - l2c_ccb_timer_timeout, p_ccb); + alarm_set_on_mloop(p_ccb->l2c_ccb_timer, L2CAP_CHNL_CFG_TIMEOUT_MS, l2c_ccb_timer_timeout, + p_ccb); } else { /* If pending, stay in same state and start extended timer */ - log::debug("Sending connection result {} and status {}", - p_ci->l2cap_result, p_ci->l2cap_status); - l2cu_send_peer_connect_rsp(p_ccb, p_ci->l2cap_result, - p_ci->l2cap_status); - alarm_set_on_mloop(p_ccb->l2c_ccb_timer, - L2CAP_CHNL_CONNECT_EXT_TIMEOUT_MS, + log::debug("Sending connection result {} and status {}", p_ci->l2cap_result, + p_ci->l2cap_status); + l2cu_send_peer_connect_rsp(p_ccb, p_ci->l2cap_result, p_ci->l2cap_status); + alarm_set_on_mloop(p_ccb->l2c_ccb_timer, L2CAP_CHNL_CONNECT_EXT_TIMEOUT_MS, l2c_ccb_timer_timeout, p_ccb); } } @@ -915,8 +843,7 @@ static void l2c_csm_w4_l2ca_connect_rsp(tL2C_CCB* p_ccb, tL2CEVT event, alarm_cancel(p_ccb->l2c_ccb_timer); if (p_lcb != nullptr) { if (p_lcb->transport == BT_TRANSPORT_LE) { - l2cu_send_peer_credit_based_conn_res(p_ccb, p_ci->lcids, - p_ci->l2cap_result); + l2cu_send_peer_credit_based_conn_res(p_ccb, p_ci->lcids, p_ci->l2cap_result); } for (int i = 0; i < p_lcb->pending_ecoc_conn_cnt; i++) { uint16_t cid = p_lcb->pending_ecoc_connection_cids[i]; @@ -925,24 +852,22 @@ static void l2c_csm_w4_l2ca_connect_rsp(tL2C_CCB* p_ccb, tL2CEVT event, } p_lcb->pending_ecoc_conn_cnt = 0; - memset(p_lcb->pending_ecoc_connection_cids, 0, - L2CAP_CREDIT_BASED_MAX_CIDS); + memset(p_lcb->pending_ecoc_connection_cids, 0, L2CAP_CREDIT_BASED_MAX_CIDS); } break; case L2CEVT_L2CA_CONNECT_RSP_NEG: p_ci = (tL2C_CONN_INFO*)p_data; - if (p_ccb->p_lcb->transport == BT_TRANSPORT_LE) + if (p_ccb->p_lcb->transport == BT_TRANSPORT_LE) { l2cble_credit_based_conn_res(p_ccb, p_ci->l2cap_result); - else - l2cu_send_peer_connect_rsp(p_ccb, p_ci->l2cap_result, - p_ci->l2cap_status); + } else { + l2cu_send_peer_connect_rsp(p_ccb, p_ci->l2cap_result, p_ci->l2cap_status); + } l2cu_release_ccb(p_ccb); break; case L2CEVT_TIMEOUT: l2cu_send_peer_connect_rsp(p_ccb, L2CAP_CONN_NO_PSM, 0); - log::debug("Calling Disconnect_Ind_Cb(), CID: 0x{:04x} No Conf Needed", - p_ccb->local_cid); + log::debug("Calling Disconnect_Ind_Cb(), CID: 0x{:04x} No Conf Needed", p_ccb->local_cid); l2cu_release_ccb(p_ccb); (*disconnect_ind)(local_cid, false); break; @@ -961,8 +886,8 @@ static void l2c_csm_w4_l2ca_connect_rsp(tL2C_CCB* p_ccb, tL2CEVT event, case L2CEVT_L2CAP_INFO_RSP: /* We have feature info, so now give the upper layer connect IND */ - alarm_set_on_mloop(p_ccb->l2c_ccb_timer, L2CAP_CHNL_CONNECT_TIMEOUT_MS, - l2c_ccb_timer_timeout, p_ccb); + alarm_set_on_mloop(p_ccb->l2c_ccb_timer, L2CAP_CHNL_CONNECT_TIMEOUT_MS, l2c_ccb_timer_timeout, + p_ccb); log::debug("Calling Connect_Ind_Cb(), CID: 0x{:04x}", p_ccb->local_cid); l2c_csm_send_connect_rsp(p_ccb); @@ -971,9 +896,8 @@ static void l2c_csm_w4_l2ca_connect_rsp(tL2C_CCB* p_ccb, tL2CEVT event, default: log::error("Handling unexpected event:{}", l2c_csm_get_event_name(event)); } - log::verbose("Exit chnl_state={} [{}], event={} [{}]", - channel_state_text(p_ccb->chnl_state), p_ccb->chnl_state, - l2c_csm_get_event_name(event), event); + log::verbose("Exit chnl_state={} [{}], event={} [{}]", channel_state_text(p_ccb->chnl_state), + p_ccb->chnl_state, l2c_csm_get_event_name(event), event); } /******************************************************************************* @@ -988,8 +912,7 @@ static void l2c_csm_w4_l2ca_connect_rsp(tL2C_CCB* p_ccb, tL2CEVT event, ******************************************************************************/ static void l2c_csm_config(tL2C_CCB* p_ccb, tL2CEVT event, void* p_data) { tL2CAP_CFG_INFO* p_cfg = (tL2CAP_CFG_INFO*)p_data; - tL2CA_DISCONNECT_IND_CB* disconnect_ind = - p_ccb->p_rcb->api.pL2CA_DisconnectInd_Cb; + tL2CA_DISCONNECT_IND_CB* disconnect_ind = p_ccb->p_rcb->api.pL2CA_DisconnectInd_Cb; uint16_t local_cid = p_ccb->local_cid; uint8_t cfg_result; tL2C_LCB* p_lcb = p_ccb->p_lcb; @@ -1001,8 +924,7 @@ static void l2c_csm_config(tL2C_CCB* p_ccb, tL2CEVT event, void* p_data) { switch (event) { case L2CEVT_LP_DISCONNECT_IND: /* Link was disconnected */ - log::debug("Calling Disconnect_Ind_Cb(), CID: 0x{:04x} No Conf Needed", - p_ccb->local_cid); + log::debug("Calling Disconnect_Ind_Cb(), CID: 0x{:04x} No Conf Needed", p_ccb->local_cid); l2cu_release_ccb(p_ccb); (*disconnect_ind)(local_cid, false); break; @@ -1011,30 +933,25 @@ static void l2c_csm_config(tL2C_CCB* p_ccb, tL2CEVT event, void* p_data) { /* For ecoc reconfig is handled below in l2c_ble. In case of success * let us notify upper layer about the reconfig */ - log::debug("Calling LeReconfigCompleted_Cb(), CID: 0x{:04x}", - p_ccb->local_cid); + log::debug("Calling LeReconfigCompleted_Cb(), CID: 0x{:04x}", p_ccb->local_cid); - (*p_ccb->p_rcb->api.pL2CA_CreditBasedReconfigCompleted_Cb)( - p_lcb->remote_bd_addr, p_ccb->local_cid, false, p_le_cfg); + (*p_ccb->p_rcb->api.pL2CA_CreditBasedReconfigCompleted_Cb)(p_lcb->remote_bd_addr, + p_ccb->local_cid, false, p_le_cfg); break; case L2CEVT_L2CAP_CONFIG_REQ: /* Peer config request */ cfg_result = l2cu_process_peer_cfg_req(p_ccb, p_cfg); if (cfg_result == L2CAP_PEER_CFG_OK) { - log::debug("Calling Config_Req_Cb(), CID: 0x{:04x}, C-bit {}", - p_ccb->local_cid, p_cfg->flags & L2CAP_CFG_FLAGS_MASK_CONT); - l2c_csm_send_config_rsp_ok(p_ccb, - p_cfg->flags & L2CAP_CFG_FLAGS_MASK_CONT); + log::debug("Calling Config_Req_Cb(), CID: 0x{:04x}, C-bit {}", p_ccb->local_cid, + p_cfg->flags & L2CAP_CFG_FLAGS_MASK_CONT); + l2c_csm_send_config_rsp_ok(p_ccb, p_cfg->flags & L2CAP_CFG_FLAGS_MASK_CONT); if (p_ccb->config_done & OB_CFG_DONE) { if (p_ccb->remote_config_rsp_result == L2CAP_CFG_OK) { l2c_csm_indicate_connection_open(p_ccb); } else { if (p_ccb->connection_initiator == L2CAP_INITIATOR_LOCAL) { - (*p_ccb->p_rcb->api.pL2CA_Error_Cb)(p_ccb->local_cid, - L2CAP_CFG_FAILED_NO_REASON); + (*p_ccb->p_rcb->api.pL2CA_Error_Cb)(p_ccb->local_cid, L2CAP_CFG_FAILED_NO_REASON); bluetooth::shim::CountCounterMetrics( - android::bluetooth::CodePathCounterKeyEnum:: - L2CAP_CONFIG_REQ_FAILURE, - 1); + android::bluetooth::CodePathCounterKeyEnum::L2CAP_CONFIG_REQ_FAILURE, 1); } } } @@ -1057,14 +974,14 @@ static void l2c_csm_config(tL2C_CCB* p_ccb, tL2CEVT event, void* p_data) { log::debug("Calling Config_Rsp_Cb(), CID: 0x{:04x}", p_ccb->local_cid); - p_ccb->p_rcb->api.pL2CA_CreditBasedReconfigCompleted_Cb( - p_lcb->remote_bd_addr, p_ccb->local_cid, true, p_le_cfg); + p_ccb->p_rcb->api.pL2CA_CreditBasedReconfigCompleted_Cb(p_lcb->remote_bd_addr, + p_ccb->local_cid, true, p_le_cfg); break; case L2CEVT_L2CAP_CONFIG_RSP: /* Peer config response */ l2cu_process_peer_cfg_rsp(p_ccb, p_cfg); - /* TBD: When config options grow beyong minimum MTU (48 bytes) + /* TBD: When config options grow beyond minimum MTU (48 bytes) * logic needs to be added to handle responses with * continuation bit set in flags field. * 1. Send additional config request out until C-bit is cleared in @@ -1077,9 +994,9 @@ static void l2c_csm_config(tL2C_CCB* p_ccb, tL2CEVT event, void* p_data) { if (p_ccb->our_cfg.fcr.mode != p_ccb->peer_cfg.fcr.mode) { l2cu_send_peer_disc_req(p_ccb); log::warn( - "Calling Disconnect_Ind_Cb(Incompatible CFG), CID: 0x{:04x} No " - "Conf Needed", - p_ccb->local_cid); + "Calling Disconnect_Ind_Cb(Incompatible CFG), CID: 0x{:04x} No " + "Conf Needed", + p_ccb->local_cid); l2cu_release_ccb(p_ccb); (*disconnect_ind)(local_cid, false); break; @@ -1091,7 +1008,9 @@ static void l2c_csm_config(tL2C_CCB* p_ccb, tL2CEVT event, void* p_data) { alarm_cancel(p_ccb->l2c_ccb_timer); /* If using eRTM and waiting for an ACK, restart the ACK timer */ - if (p_ccb->fcrb.wait_ack) l2c_fcr_start_timer(p_ccb); + if (p_ccb->fcrb.wait_ack) { + l2c_fcr_start_timer(p_ccb); + } /* ** check p_ccb->our_cfg.fcr.mon_tout and @@ -1100,8 +1019,7 @@ static void l2c_csm_config(tL2C_CCB* p_ccb, tL2CEVT event, void* p_data) { *renegotiation */ if ((p_ccb->our_cfg.fcr.mode == L2CAP_FCR_ERTM_MODE) && - ((p_ccb->our_cfg.fcr.mon_tout == 0) || - (p_ccb->our_cfg.fcr.rtrans_tout))) { + ((p_ccb->our_cfg.fcr.mon_tout == 0) || (p_ccb->our_cfg.fcr.rtrans_tout))) { l2c_fcr_adj_monitor_retran_timeout(p_ccb); } @@ -1114,9 +1032,8 @@ static void l2c_csm_config(tL2C_CCB* p_ccb, tL2CEVT event, void* p_data) { if (p_ccb->config_done & RECONFIG_FLAG) { // Notify only once bluetooth::shim::GetSnoopLogger()->SetL2capChannelOpen( - p_ccb->p_lcb->Handle(), p_ccb->local_cid, p_ccb->remote_cid, - p_ccb->p_rcb->psm, - p_ccb->peer_cfg.fcr.mode != L2CAP_FCR_BASIC_MODE); + p_ccb->p_lcb->Handle(), p_ccb->local_cid, p_ccb->remote_cid, p_ccb->p_rcb->psm, + p_ccb->peer_cfg.fcr.mode != L2CAP_FCR_BASIC_MODE); } log::debug("Calling Config_Rsp_Cb(), CID: 0x{:04x}", p_ccb->local_cid); @@ -1132,14 +1049,12 @@ static void l2c_csm_config(tL2C_CCB* p_ccb, tL2CEVT event, void* p_data) { /* If failure was channel mode try to renegotiate */ if (!l2c_fcr_renegotiate_chan(p_ccb, p_cfg)) { - log::debug("Calling Config_Rsp_Cb(), CID: 0x{:04x}, Failure: {}", - p_ccb->local_cid, p_cfg->result); + log::debug("Calling Config_Rsp_Cb(), CID: 0x{:04x}, Failure: {}", p_ccb->local_cid, + p_cfg->result); if (p_ccb->connection_initiator == L2CAP_INITIATOR_LOCAL) { - (*p_ccb->p_rcb->api.pL2CA_Error_Cb)(p_ccb->local_cid, - L2CAP_CFG_FAILED_NO_REASON); + (*p_ccb->p_rcb->api.pL2CA_Error_Cb)(p_ccb->local_cid, L2CAP_CFG_FAILED_NO_REASON); bluetooth::shim::CountCounterMetrics( - android::bluetooth::CodePathCounterKeyEnum::L2CAP_CONFIG_RSP_NEG, - 1); + android::bluetooth::CodePathCounterKeyEnum::L2CAP_CONFIG_RSP_NEG, 1); } } break; @@ -1148,22 +1063,21 @@ static void l2c_csm_config(tL2C_CCB* p_ccb, tL2CEVT event, void* p_data) { alarm_set_on_mloop(p_ccb->l2c_ccb_timer, L2CAP_CHNL_DISCONNECT_TIMEOUT_MS, l2c_ccb_timer_timeout, p_ccb); p_ccb->chnl_state = CST_W4_L2CA_DISCONNECT_RSP; - log::debug("Calling Disconnect_Ind_Cb(), CID: 0x{:04x} Conf Needed", - p_ccb->local_cid); + log::debug("Calling Disconnect_Ind_Cb(), CID: 0x{:04x} Conf Needed", p_ccb->local_cid); (*p_ccb->p_rcb->api.pL2CA_DisconnectInd_Cb)(p_ccb->local_cid, true); l2c_csm_send_disconnect_rsp(p_ccb); break; case L2CEVT_L2CA_CREDIT_BASED_RECONFIG_REQ: l2cu_send_credit_based_reconfig_req(p_ccb, (tL2CAP_LE_CFG_INFO*)p_data); - alarm_set_on_mloop(p_ccb->l2c_ccb_timer, L2CAP_CHNL_CFG_TIMEOUT_MS, - l2c_ccb_timer_timeout, p_ccb); + alarm_set_on_mloop(p_ccb->l2c_ccb_timer, L2CAP_CHNL_CFG_TIMEOUT_MS, l2c_ccb_timer_timeout, + p_ccb); break; case L2CEVT_L2CA_CONFIG_REQ: /* Upper layer config req */ l2cu_process_our_cfg_req(p_ccb, p_cfg); l2cu_send_peer_config_req(p_ccb, p_cfg); - alarm_set_on_mloop(p_ccb->l2c_ccb_timer, L2CAP_CHNL_CFG_TIMEOUT_MS, - l2c_ccb_timer_timeout, p_ccb); + alarm_set_on_mloop(p_ccb->l2c_ccb_timer, L2CAP_CHNL_CFG_TIMEOUT_MS, l2c_ccb_timer_timeout, + p_ccb); break; case L2CEVT_L2CA_CONFIG_RSP: /* Upper layer config rsp */ @@ -1176,9 +1090,9 @@ static void l2c_csm_config(tL2C_CCB* p_ccb, tL2CEVT event, void* p_data) { if (p_ccb->our_cfg.fcr.mode != p_ccb->peer_cfg.fcr.mode) { l2cu_send_peer_disc_req(p_ccb); log::warn( - "Calling Disconnect_Ind_Cb(Incompatible CFG), CID: 0x{:04x} No " - "Conf Needed", - p_ccb->local_cid); + "Calling Disconnect_Ind_Cb(Incompatible CFG), CID: 0x{:04x} No " + "Conf Needed", + p_ccb->local_cid); l2cu_release_ccb(p_ccb); (*disconnect_ind)(local_cid, false); break; @@ -1193,19 +1107,19 @@ static void l2c_csm_config(tL2C_CCB* p_ccb, tL2CEVT event, void* p_data) { l2cu_send_peer_config_rsp(p_ccb, p_cfg); /* If using eRTM and waiting for an ACK, restart the ACK timer */ - if (p_ccb->fcrb.wait_ack) l2c_fcr_start_timer(p_ccb); + if (p_ccb->fcrb.wait_ack) { + l2c_fcr_start_timer(p_ccb); + } if (p_ccb->config_done & RECONFIG_FLAG) { // Notify only once bluetooth::shim::GetSnoopLogger()->SetL2capChannelOpen( - p_ccb->p_lcb->Handle(), p_ccb->local_cid, p_ccb->remote_cid, - p_ccb->p_rcb->psm, - p_ccb->peer_cfg.fcr.mode != L2CAP_FCR_BASIC_MODE); + p_ccb->p_lcb->Handle(), p_ccb->local_cid, p_ccb->remote_cid, p_ccb->p_rcb->psm, + p_ccb->peer_cfg.fcr.mode != L2CAP_FCR_BASIC_MODE); } /* See if we can forward anything on the hold queue */ - if ((p_ccb->chnl_state == CST_OPEN) && - (!fixed_queue_is_empty(p_ccb->xmit_hold_q))) { + if ((p_ccb->chnl_state == CST_OPEN) && (!fixed_queue_is_empty(p_ccb->xmit_hold_q))) { l2c_link_check_send_pkts(p_ccb->p_lcb, 0, NULL); } break; @@ -1219,31 +1133,33 @@ static void l2c_csm_config(tL2C_CCB* p_ccb, tL2CEVT event, void* p_data) { case L2CEVT_L2CAP_DATA: /* Peer data packet rcvd */ log::debug("Calling DataInd_Cb(), CID: 0x{:04x}", p_ccb->local_cid); - if (p_ccb->local_cid >= L2CAP_FIRST_FIXED_CHNL && - p_ccb->local_cid <= L2CAP_LAST_FIXED_CHNL) { + if (p_ccb->local_cid >= L2CAP_FIRST_FIXED_CHNL && p_ccb->local_cid <= L2CAP_LAST_FIXED_CHNL) { if (p_ccb->local_cid < L2CAP_BASE_APPL_CID) { - if (l2cb.fixed_reg[p_ccb->local_cid - L2CAP_FIRST_FIXED_CHNL] - .pL2CA_FixedData_Cb != nullptr) { + if (l2cb.fixed_reg[p_ccb->local_cid - L2CAP_FIRST_FIXED_CHNL].pL2CA_FixedData_Cb != + nullptr) { p_ccb->metrics.rx(static_cast(p_data)->len); - (*l2cb.fixed_reg[p_ccb->local_cid - L2CAP_FIRST_FIXED_CHNL] - .pL2CA_FixedData_Cb)(p_ccb->local_cid, - p_ccb->p_lcb->remote_bd_addr, - (BT_HDR*)p_data); + (*l2cb.fixed_reg[p_ccb->local_cid - L2CAP_FIRST_FIXED_CHNL].pL2CA_FixedData_Cb)( + p_ccb->local_cid, p_ccb->p_lcb->remote_bd_addr, (BT_HDR*)p_data); } else { - if (p_data != nullptr) osi_free_and_reset(&p_data); + if (p_data != nullptr) { + osi_free_and_reset(&p_data); + } } break; } } - if (p_data) p_ccb->metrics.rx(static_cast(p_data)->len); + if (p_data) { + p_ccb->metrics.rx(static_cast(p_data)->len); + } (*p_ccb->p_rcb->api.pL2CA_DataInd_Cb)(p_ccb->local_cid, (BT_HDR*)p_data); break; case L2CEVT_L2CA_DATA_WRITE: /* Upper layer data to send */ - if (p_ccb->config_done & OB_CFG_DONE) + if (p_ccb->config_done & OB_CFG_DONE) { l2c_enqueue_peer_data(p_ccb, (BT_HDR*)p_data); - else + } else { osi_free(p_data); + } break; case L2CEVT_TIMEOUT: @@ -1251,30 +1167,26 @@ static void l2c_csm_config(tL2C_CCB* p_ccb, tL2CEVT event, void* p_data) { for (temp_p_ccb = p_lcb->ccb_queue.p_first_ccb; temp_p_ccb; temp_p_ccb = temp_p_ccb->p_next_ccb) { if ((temp_p_ccb->in_use) && (temp_p_ccb->reconfig_started)) { - (*temp_p_ccb->p_rcb->api.pL2CA_DisconnectInd_Cb)( - temp_p_ccb->local_cid, false); + (*temp_p_ccb->p_rcb->api.pL2CA_DisconnectInd_Cb)(temp_p_ccb->local_cid, false); l2cu_release_ccb(temp_p_ccb); } } - acl_disconnect_from_handle( - p_ccb->p_lcb->Handle(), HCI_ERR_CONN_CAUSE_LOCAL_HOST, - "stack::l2cap::l2c_csm::l2c_csm_config timeout"); + acl_disconnect_from_handle(p_ccb->p_lcb->Handle(), HCI_ERR_CONN_CAUSE_LOCAL_HOST, + "stack::l2cap::l2c_csm::l2c_csm_config timeout"); return; } l2cu_send_peer_disc_req(p_ccb); - log::debug("Calling Disconnect_Ind_Cb(), CID: 0x{:04x} No Conf Needed", - p_ccb->local_cid); + log::debug("Calling Disconnect_Ind_Cb(), CID: 0x{:04x} No Conf Needed", p_ccb->local_cid); l2cu_release_ccb(p_ccb); (*disconnect_ind)(local_cid, false); break; default: log::error("Handling unexpected event:{}", l2c_csm_get_event_name(event)); } - log::verbose("Exit chnl_state={} [{}], event={} [{}]", - channel_state_text(p_ccb->chnl_state), p_ccb->chnl_state, - l2c_csm_get_event_name(event), event); + log::verbose("Exit chnl_state={} [{}], event={} [{}]", channel_state_text(p_ccb->chnl_state), + p_ccb->chnl_state, l2c_csm_get_event_name(event), event); } /******************************************************************************* @@ -1301,14 +1213,13 @@ static void l2c_csm_open(tL2C_CCB* p_ccb, tL2CEVT event, void* p_data) { switch (event) { case L2CEVT_LP_DISCONNECT_IND: /* Link was disconnected */ - log::debug("Calling Disconnect_Ind_Cb(), CID: 0x{:04x} No Conf Needed", - p_ccb->local_cid); + log::debug("Calling Disconnect_Ind_Cb(), CID: 0x{:04x} No Conf Needed", p_ccb->local_cid); power_telemetry::GetInstance().LogChannelDisconnected( - p_ccb->p_rcb->psm, p_ccb->local_cid, p_ccb->remote_id, - p_ccb->p_lcb->remote_bd_addr); + p_ccb->p_rcb->psm, p_ccb->local_cid, p_ccb->remote_id, p_ccb->p_lcb->remote_bd_addr); l2cu_release_ccb(p_ccb); - if (p_ccb->p_rcb) + if (p_ccb->p_rcb) { (*p_ccb->p_rcb->api.pL2CA_DisconnectInd_Cb)(local_cid, false); + } break; case L2CEVT_L2CAP_CREDIT_BASED_RECONFIG_REQ: @@ -1316,10 +1227,9 @@ static void l2c_csm_open(tL2C_CCB* p_ccb, tL2CEVT event, void* p_data) { * let us notify upper layer about the reconfig */ if (p_le_cfg) { - log::debug("Calling LeReconfigCompleted_Cb(), CID: 0x{:04x}", - p_ccb->local_cid); + log::debug("Calling LeReconfigCompleted_Cb(), CID: 0x{:04x}", p_ccb->local_cid); (*p_ccb->p_rcb->api.pL2CA_CreditBasedReconfigCompleted_Cb)( - p_ccb->p_lcb->remote_bd_addr, p_ccb->local_cid, false, p_le_cfg); + p_ccb->p_lcb->remote_bd_addr, p_ccb->local_cid, false, p_le_cfg); } break; @@ -1335,15 +1245,14 @@ static void l2c_csm_open(tL2C_CCB* p_ccb, tL2CEVT event, void* p_data) { p_ccb->peer_cfg.qos_present = false; p_ccb->config_done &= ~IB_CFG_DONE; - alarm_set_on_mloop(p_ccb->l2c_ccb_timer, L2CAP_CHNL_CFG_TIMEOUT_MS, - l2c_ccb_timer_timeout, p_ccb); + alarm_set_on_mloop(p_ccb->l2c_ccb_timer, L2CAP_CHNL_CFG_TIMEOUT_MS, l2c_ccb_timer_timeout, + p_ccb); if (p_cfg) { cfg_result = l2cu_process_peer_cfg_req(p_ccb, p_cfg); } if (cfg_result == L2CAP_PEER_CFG_OK) { (*p_ccb->p_rcb->api.pL2CA_ConfigInd_Cb)(p_ccb->local_cid, p_cfg); - l2c_csm_send_config_rsp_ok(p_ccb, - p_cfg->flags & L2CAP_CFG_FLAGS_MASK_CONT); + l2c_csm_send_config_rsp_ok(p_ccb, p_cfg->flags & L2CAP_CFG_FLAGS_MASK_CONT); } /* Error in config parameters: reset state and config flag */ @@ -1372,11 +1281,9 @@ static void l2c_csm_open(tL2C_CCB* p_ccb, tL2CEVT event, void* p_data) { p_ccb->chnl_state = CST_W4_L2CA_DISCONNECT_RSP; alarm_set_on_mloop(p_ccb->l2c_ccb_timer, L2CAP_CHNL_DISCONNECT_TIMEOUT_MS, l2c_ccb_timer_timeout, p_ccb); - log::debug("Calling Disconnect_Ind_Cb(), CID: 0x{:04x} Conf Needed", - p_ccb->local_cid); + log::debug("Calling Disconnect_Ind_Cb(), CID: 0x{:04x} Conf Needed", p_ccb->local_cid); power_telemetry::GetInstance().LogChannelDisconnected( - p_ccb->p_rcb->psm, p_ccb->local_cid, p_ccb->remote_id, - p_ccb->p_lcb->remote_bd_addr); + p_ccb->p_rcb->psm, p_ccb->local_cid, p_ccb->remote_id, p_ccb->p_lcb->remote_bd_addr); (*p_ccb->p_rcb->api.pL2CA_DisconnectInd_Cb)(p_ccb->local_cid, true); l2c_csm_send_disconnect_rsp(p_ccb); break; @@ -1386,13 +1293,12 @@ static void l2c_csm_open(tL2C_CCB* p_ccb, tL2CEVT event, void* p_data) { uint16_t package_len = ((BT_HDR*)p_data)->len; if (p_ccb->p_rcb->api.pL2CA_DataInd_Cb) { p_ccb->metrics.rx(static_cast(p_data)->len); - (*p_ccb->p_rcb->api.pL2CA_DataInd_Cb)(p_ccb->local_cid, - (BT_HDR*)p_data); + (*p_ccb->p_rcb->api.pL2CA_DataInd_Cb)(p_ccb->local_cid, (BT_HDR*)p_data); } - power_telemetry::GetInstance().LogRxBytes( - p_ccb->p_rcb->psm, p_ccb->local_cid, p_ccb->remote_id, - p_ccb->p_lcb->remote_bd_addr, package_len); + power_telemetry::GetInstance().LogRxBytes(p_ccb->p_rcb->psm, p_ccb->local_cid, + p_ccb->remote_id, p_ccb->p_lcb->remote_bd_addr, + package_len); } break; @@ -1404,12 +1310,12 @@ static void l2c_csm_open(tL2C_CCB* p_ccb, tL2CEVT event, void* p_data) { } } power_telemetry::GetInstance().LogChannelDisconnected( - p_ccb->p_rcb->psm, p_ccb->local_cid, p_ccb->remote_id, - p_ccb->p_lcb->remote_bd_addr); - if (p_ccb->p_lcb->transport == BT_TRANSPORT_LE) + p_ccb->p_rcb->psm, p_ccb->local_cid, p_ccb->remote_id, p_ccb->p_lcb->remote_bd_addr); + if (p_ccb->p_lcb->transport == BT_TRANSPORT_LE) { l2cble_send_peer_disc_req(p_ccb); - else + } else { l2cu_send_peer_disc_req(p_ccb); + } p_ccb->chnl_state = CST_W4_L2CAP_DISCONNECT_RSP; alarm_set_on_mloop(p_ccb->l2c_ccb_timer, L2CAP_CHNL_DISCONNECT_TIMEOUT_MS, @@ -1421,9 +1327,9 @@ static void l2c_csm_open(tL2C_CCB* p_ccb, tL2CEVT event, void* p_data) { uint16_t package_len = ((BT_HDR*)p_data)->len; l2c_enqueue_peer_data(p_ccb, (BT_HDR*)p_data); l2c_link_check_send_pkts(p_ccb->p_lcb, 0, NULL); - power_telemetry::GetInstance().LogTxBytes( - p_ccb->p_rcb->psm, p_ccb->local_cid, p_ccb->remote_id, - p_ccb->p_lcb->remote_bd_addr, package_len); + power_telemetry::GetInstance().LogTxBytes(p_ccb->p_rcb->psm, p_ccb->local_cid, + p_ccb->remote_id, p_ccb->p_lcb->remote_bd_addr, + package_len); } break; @@ -1434,22 +1340,23 @@ static void l2c_csm_open(tL2C_CCB* p_ccb, tL2CEVT event, void* p_data) { if (p_data) { l2cu_send_credit_based_reconfig_req(p_ccb, (tL2CAP_LE_CFG_INFO*)p_data); - alarm_set_on_mloop(p_ccb->l2c_ccb_timer, L2CAP_CHNL_CFG_TIMEOUT_MS, - l2c_ccb_timer_timeout, p_ccb); + alarm_set_on_mloop(p_ccb->l2c_ccb_timer, L2CAP_CHNL_CFG_TIMEOUT_MS, l2c_ccb_timer_timeout, + p_ccb); } break; case L2CEVT_L2CA_CONFIG_REQ: /* Upper layer config req */ log::error( - "Dropping L2CAP re-config request because there is no usage and " - "should not be invoked"); + "Dropping L2CAP re-config request because there is no usage and " + "should not be invoked"); break; case L2CEVT_TIMEOUT: /* Process the monitor/retransmission time-outs in flow control/retrans * mode */ - if (p_ccb->peer_cfg.fcr.mode == L2CAP_FCR_ERTM_MODE) + if (p_ccb->peer_cfg.fcr.mode == L2CAP_FCR_ERTM_MODE) { l2c_fcr_proc_tout(p_ccb); + } break; case L2CEVT_ACK_TIMEOUT: @@ -1482,9 +1389,8 @@ static void l2c_csm_open(tL2C_CCB* p_ccb, tL2CEVT event, void* p_data) { default: log::error("Handling unexpected event:{}", l2c_csm_get_event_name(event)); } - log::verbose("Exit chnl_state={} [{}], event={} [{}]", - channel_state_text(p_ccb->chnl_state), p_ccb->chnl_state, - l2c_csm_get_event_name(event), event); + log::verbose("Exit chnl_state={} [{}], event={} [{}]", channel_state_text(p_ccb->chnl_state), + p_ccb->chnl_state, l2c_csm_get_event_name(event), event); } /******************************************************************************* @@ -1497,10 +1403,8 @@ static void l2c_csm_open(tL2C_CCB* p_ccb, tL2CEVT event, void* p_data) { * Returns void * ******************************************************************************/ -static void l2c_csm_w4_l2cap_disconnect_rsp(tL2C_CCB* p_ccb, tL2CEVT event, - void* p_data) { - tL2CA_DISCONNECT_CFM_CB* disconnect_cfm = - p_ccb->p_rcb->api.pL2CA_DisconnectCfm_Cb; +static void l2c_csm_w4_l2cap_disconnect_rsp(tL2C_CCB* p_ccb, tL2CEVT event, void* p_data) { + tL2CA_DISCONNECT_CFM_CB* disconnect_cfm = p_ccb->p_rcb->api.pL2CA_DisconnectCfm_Cb; uint16_t local_cid = p_ccb->local_cid; log::debug("LCID: 0x{:04x} st: W4_L2CAP_DISC_RSP evt: {}", p_ccb->local_cid, @@ -1515,8 +1419,7 @@ static void l2c_csm_w4_l2cap_disconnect_rsp(tL2C_CCB* p_ccb, tL2CEVT event, break; case L2CEVT_L2CAP_DISCONNECT_REQ: /* Peer disconnect request */ - l2cu_send_peer_disc_rsp(p_ccb->p_lcb, p_ccb->remote_id, p_ccb->local_cid, - p_ccb->remote_cid); + l2cu_send_peer_disc_rsp(p_ccb->p_lcb, p_ccb->remote_id, p_ccb->local_cid, p_ccb->remote_cid); l2cu_release_ccb(p_ccb); if (disconnect_cfm != nullptr) { (*disconnect_cfm)(local_cid, L2CAP_DISC_OK); @@ -1539,9 +1442,8 @@ static void l2c_csm_w4_l2cap_disconnect_rsp(tL2C_CCB* p_ccb, tL2CEVT event, default: log::error("Handling unexpected event:{}", l2c_csm_get_event_name(event)); } - log::verbose("Exit chnl_state={} [{}], event={} [{}]", - channel_state_text(p_ccb->chnl_state), p_ccb->chnl_state, - l2c_csm_get_event_name(event), event); + log::verbose("Exit chnl_state={} [{}], event={} [{}]", channel_state_text(p_ccb->chnl_state), + p_ccb->chnl_state, l2c_csm_get_event_name(event), event); } /******************************************************************************* @@ -1554,10 +1456,8 @@ static void l2c_csm_w4_l2cap_disconnect_rsp(tL2C_CCB* p_ccb, tL2CEVT event, * Returns void * ******************************************************************************/ -static void l2c_csm_w4_l2ca_disconnect_rsp(tL2C_CCB* p_ccb, tL2CEVT event, - void* p_data) { - tL2CA_DISCONNECT_IND_CB* disconnect_ind = - p_ccb->p_rcb->api.pL2CA_DisconnectInd_Cb; +static void l2c_csm_w4_l2ca_disconnect_rsp(tL2C_CCB* p_ccb, tL2CEVT event, void* p_data) { + tL2CA_DISCONNECT_IND_CB* disconnect_ind = p_ccb->p_rcb->api.pL2CA_DisconnectInd_Cb; uint16_t local_cid = p_ccb->local_cid; log::debug("LCID: 0x{:04x} st: W4_L2CA_DISC_RSP evt: {}", p_ccb->local_cid, @@ -1565,25 +1465,21 @@ static void l2c_csm_w4_l2ca_disconnect_rsp(tL2C_CCB* p_ccb, tL2CEVT event, switch (event) { case L2CEVT_LP_DISCONNECT_IND: /* Link was disconnected */ - log::debug("Calling Disconnect_Ind_Cb(), CID: 0x{:04x} No Conf Needed", - p_ccb->local_cid); + log::debug("Calling Disconnect_Ind_Cb(), CID: 0x{:04x} No Conf Needed", p_ccb->local_cid); l2cu_release_ccb(p_ccb); (*disconnect_ind)(local_cid, false); break; case L2CEVT_TIMEOUT: - l2cu_send_peer_disc_rsp(p_ccb->p_lcb, p_ccb->remote_id, p_ccb->local_cid, - p_ccb->remote_cid); - log::debug("Calling Disconnect_Ind_Cb(), CID: 0x{:04x} No Conf Needed", - p_ccb->local_cid); + l2cu_send_peer_disc_rsp(p_ccb->p_lcb, p_ccb->remote_id, p_ccb->local_cid, p_ccb->remote_cid); + log::debug("Calling Disconnect_Ind_Cb(), CID: 0x{:04x} No Conf Needed", p_ccb->local_cid); l2cu_release_ccb(p_ccb); (*disconnect_ind)(local_cid, false); break; case L2CEVT_L2CA_DISCONNECT_REQ: /* Upper disconnect request */ case L2CEVT_L2CA_DISCONNECT_RSP: /* Upper disconnect response */ - l2cu_send_peer_disc_rsp(p_ccb->p_lcb, p_ccb->remote_id, p_ccb->local_cid, - p_ccb->remote_cid); + l2cu_send_peer_disc_rsp(p_ccb->p_lcb, p_ccb->remote_id, p_ccb->local_cid, p_ccb->remote_cid); l2cu_release_ccb(p_ccb); break; @@ -1594,9 +1490,8 @@ static void l2c_csm_w4_l2ca_disconnect_rsp(tL2C_CCB* p_ccb, tL2CEVT event, default: log::error("Handling unexpected event:{}", l2c_csm_get_event_name(event)); } - log::verbose("Exit chnl_state={} [{}], event={} [{}]", - channel_state_text(p_ccb->chnl_state), p_ccb->chnl_state, - l2c_csm_get_event_name(event), event); + log::verbose("Exit chnl_state={} [{}], event={} [{}]", channel_state_text(p_ccb->chnl_state), + p_ccb->chnl_state, l2c_csm_get_event_name(event), event); } /******************************************************************************* @@ -1613,101 +1508,101 @@ static void l2c_csm_w4_l2ca_disconnect_rsp(tL2C_CCB* p_ccb, tL2CEVT event, static const char* l2c_csm_get_event_name(tL2CEVT event) { switch (event) { case L2CEVT_LP_CONNECT_CFM: /* Lower layer connect confirm */ - return ("LOWER_LAYER_CONNECT_CFM"); + return "LOWER_LAYER_CONNECT_CFM"; case L2CEVT_LP_CONNECT_CFM_NEG: /* Lower layer connect confirm (failed) */ - return ("LOWER_LAYER_CONNECT_CFM_NEG"); + return "LOWER_LAYER_CONNECT_CFM_NEG"; case L2CEVT_LP_CONNECT_IND: /* Lower layer connect indication */ - return ("LOWER_LAYER_CONNECT_IND"); + return "LOWER_LAYER_CONNECT_IND"; case L2CEVT_LP_DISCONNECT_IND: /* Lower layer disconnect indication */ - return ("LOWER_LAYER_DISCONNECT_IND"); + return "LOWER_LAYER_DISCONNECT_IND"; case L2CEVT_SEC_COMP: /* Security cleared successfully */ - return ("SECURITY_COMPLETE"); + return "SECURITY_COMPLETE"; case L2CEVT_SEC_COMP_NEG: /* Security procedure failed */ - return ("SECURITY_COMPLETE_NEG"); + return "SECURITY_COMPLETE_NEG"; case L2CEVT_L2CAP_CONNECT_REQ: /* Peer connection request */ - return ("PEER_CONNECT_REQ"); + return "PEER_CONNECT_REQ"; case L2CEVT_L2CAP_CONNECT_RSP: /* Peer connection response */ - return ("PEER_CONNECT_RSP"); + return "PEER_CONNECT_RSP"; case L2CEVT_L2CAP_CONNECT_RSP_PND: /* Peer connection response pending */ - return ("PEER_CONNECT_RSP_PND"); + return "PEER_CONNECT_RSP_PND"; case L2CEVT_L2CAP_CONNECT_RSP_NEG: /* Peer connection response (failed) */ - return ("PEER_CONNECT_RSP_NEG"); + return "PEER_CONNECT_RSP_NEG"; case L2CEVT_L2CAP_CONFIG_REQ: /* Peer configuration request */ - return ("PEER_CONFIG_REQ"); + return "PEER_CONFIG_REQ"; case L2CEVT_L2CAP_CONFIG_RSP: /* Peer configuration response */ - return ("PEER_CONFIG_RSP"); + return "PEER_CONFIG_RSP"; case L2CEVT_L2CAP_CONFIG_RSP_NEG: /* Peer configuration response (failed) */ - return ("PEER_CONFIG_RSP_NEG"); + return "PEER_CONFIG_RSP_NEG"; case L2CEVT_L2CAP_DISCONNECT_REQ: /* Peer disconnect request */ - return ("PEER_DISCONNECT_REQ"); + return "PEER_DISCONNECT_REQ"; case L2CEVT_L2CAP_DISCONNECT_RSP: /* Peer disconnect response */ - return ("PEER_DISCONNECT_RSP"); + return "PEER_DISCONNECT_RSP"; case L2CEVT_L2CAP_DATA: /* Peer data */ - return ("PEER_DATA"); + return "PEER_DATA"; case L2CEVT_L2CA_CONNECT_REQ: /* Upper layer connect request */ - return ("UPPER_LAYER_CONNECT_REQ"); + return "UPPER_LAYER_CONNECT_REQ"; case L2CEVT_L2CA_CONNECT_RSP: /* Upper layer connect response */ - return ("UPPER_LAYER_CONNECT_RSP"); + return "UPPER_LAYER_CONNECT_RSP"; case L2CEVT_L2CA_CONNECT_RSP_NEG: /* Upper layer connect response (failed)*/ - return ("UPPER_LAYER_CONNECT_RSP_NEG"); + return "UPPER_LAYER_CONNECT_RSP_NEG"; case L2CEVT_L2CA_CONFIG_REQ: /* Upper layer config request */ - return ("UPPER_LAYER_CONFIG_REQ"); + return "UPPER_LAYER_CONFIG_REQ"; case L2CEVT_L2CA_CONFIG_RSP: /* Upper layer config response */ - return ("UPPER_LAYER_CONFIG_RSP"); + return "UPPER_LAYER_CONFIG_RSP"; case L2CEVT_L2CA_DISCONNECT_REQ: /* Upper layer disconnect request */ - return ("UPPER_LAYER_DISCONNECT_REQ"); + return "UPPER_LAYER_DISCONNECT_REQ"; case L2CEVT_L2CA_DISCONNECT_RSP: /* Upper layer disconnect response */ - return ("UPPER_LAYER_DISCONNECT_RSP"); + return "UPPER_LAYER_DISCONNECT_RSP"; case L2CEVT_L2CA_DATA_READ: /* Upper layer data read */ - return ("UPPER_LAYER_DATA_READ"); + return "UPPER_LAYER_DATA_READ"; case L2CEVT_L2CA_DATA_WRITE: /* Upper layer data write */ - return ("UPPER_LAYER_DATA_WRITE"); + return "UPPER_LAYER_DATA_WRITE"; case L2CEVT_TIMEOUT: /* Timeout */ - return ("TIMEOUT"); + return "TIMEOUT"; case L2CEVT_SEC_RE_SEND_CMD: - return ("SEC_RE_SEND_CMD"); + return "SEC_RE_SEND_CMD"; case L2CEVT_L2CAP_INFO_RSP: /* Peer information response */ - return ("L2CEVT_L2CAP_INFO_RSP"); + return "L2CEVT_L2CAP_INFO_RSP"; case L2CEVT_ACK_TIMEOUT: - return ("L2CEVT_ACK_TIMEOUT"); + return "L2CEVT_ACK_TIMEOUT"; case L2CEVT_L2CA_SEND_FLOW_CONTROL_CREDIT: /* Upper layer send credit packet */ - return ("SEND_FLOW_CONTROL_CREDIT"); + return "SEND_FLOW_CONTROL_CREDIT"; case L2CEVT_L2CA_CREDIT_BASED_CONNECT_REQ: /* Upper layer credit based connect request */ - return ("SEND_CREDIT_BASED_CONNECT_REQ"); + return "SEND_CREDIT_BASED_CONNECT_REQ"; case L2CEVT_L2CA_CREDIT_BASED_CONNECT_RSP: /* Upper layer credit based connect response */ - return ("SEND_CREDIT_BASED_CONNECT_RSP"); + return "SEND_CREDIT_BASED_CONNECT_RSP"; case L2CEVT_L2CA_CREDIT_BASED_CONNECT_RSP_NEG: /* Upper layer credit based connect response (failed)*/ - return ("SEND_CREDIT_BASED_CONNECT_RSP_NEG"); + return "SEND_CREDIT_BASED_CONNECT_RSP_NEG"; case L2CEVT_L2CA_CREDIT_BASED_RECONFIG_REQ: /* Upper layer credit based reconfig request */ - return ("SEND_CREDIT_BASED_RECONFIG_REQ"); + return "SEND_CREDIT_BASED_RECONFIG_REQ"; case L2CEVT_L2CAP_RECV_FLOW_CONTROL_CREDIT: /* Peer send credit packet */ - return ("RECV_FLOW_CONTROL_CREDIT"); + return "RECV_FLOW_CONTROL_CREDIT"; case L2CEVT_L2CAP_CREDIT_BASED_CONNECT_REQ: /* Peer send credit based connect request */ - return ("RECV_CREDIT_BASED_CONNECT_REQ"); + return "RECV_CREDIT_BASED_CONNECT_REQ"; case L2CEVT_L2CAP_CREDIT_BASED_CONNECT_RSP: /* Peer send credit based connect response */ - return ("RECV_CREDIT_BASED_CONNECT_RSP"); + return "RECV_CREDIT_BASED_CONNECT_RSP"; case L2CEVT_L2CAP_CREDIT_BASED_CONNECT_RSP_NEG: /* Peer send reject credit based connect response */ - return ("RECV_CREDIT_BASED_CONNECT_RSP_NEG"); + return "RECV_CREDIT_BASED_CONNECT_RSP_NEG"; case L2CEVT_L2CAP_CREDIT_BASED_RECONFIG_REQ: /* Peer send credit based reconfig request */ - return ("RECV_CREDIT_BASED_RECONFIG_REQ"); + return "RECV_CREDIT_BASED_RECONFIG_REQ"; case L2CEVT_L2CAP_CREDIT_BASED_RECONFIG_RSP: /* Peer send credit based reconfig response */ - return ("RECV_CREDIT_BASED_RECONFIG_RSP"); + return "RECV_CREDIT_BASED_RECONFIG_RSP"; default: - return ("???? UNKNOWN EVENT"); + return "???? UNKNOWN EVENT"; } } @@ -1748,10 +1643,9 @@ void l2c_enqueue_peer_data(tL2C_CCB* p_ccb, BT_HDR* p_buf) { if (p_ccb->xmit_hold_q == NULL) { log::error( - "empty queue: p_ccb = {} p_ccb->in_use = {} p_ccb->chnl_state = {} " - "p_ccb->local_cid = {} p_ccb->remote_cid = {}", - fmt::ptr(p_ccb), p_ccb->in_use, p_ccb->chnl_state, p_ccb->local_cid, - p_ccb->remote_cid); + "empty queue: p_ccb = {} p_ccb->in_use = {} p_ccb->chnl_state = {} " + "p_ccb->local_cid = {} p_ccb->remote_cid = {}", + fmt::ptr(p_ccb), p_ccb->in_use, p_ccb->chnl_state, p_ccb->local_cid, p_ccb->remote_cid); } else { fixed_queue_enqueue(p_ccb->xmit_hold_q, p_buf); } @@ -1766,5 +1660,7 @@ void l2c_enqueue_peer_data(tL2C_CCB* p_ccb, BT_HDR* p_buf) { } /* if we are doing a round robin scheduling, set the flag */ - if (p_ccb->p_lcb->link_xmit_quota == 0) l2cb.check_round_robin = true; + if (p_ccb->p_lcb->link_xmit_quota == 0) { + l2cb.check_round_robin = true; + } } diff --git a/system/stack/l2cap/l2c_fcr.cc b/system/stack/l2cap/l2c_fcr.cc index ea9829c9333..8b4dc0cb1f7 100644 --- a/system/stack/l2cap/l2c_fcr.cc +++ b/system/stack/l2cap/l2c_fcr.cc @@ -45,55 +45,46 @@ using namespace bluetooth; /* this is the minimal offset required by OBX to process incoming packets */ static const uint16_t OBX_BUF_MIN_OFFSET = 4; -static const char* SAR_types[] = {"Unsegmented", "Start", "End", - "Continuation"}; +static const char* SAR_types[] = {"Unsegmented", "Start", "End", "Continuation"}; static const char* SUP_types[] = {"RR", "REJ", "RNR", "SREJ"}; /* Look-up table for the CRC calculation */ static const unsigned short crctab[256] = { - 0x0000, 0xc0c1, 0xc181, 0x0140, 0xc301, 0x03c0, 0x0280, 0xc241, 0xc601, - 0x06c0, 0x0780, 0xc741, 0x0500, 0xc5c1, 0xc481, 0x0440, 0xcc01, 0x0cc0, - 0x0d80, 0xcd41, 0x0f00, 0xcfc1, 0xce81, 0x0e40, 0x0a00, 0xcac1, 0xcb81, - 0x0b40, 0xc901, 0x09c0, 0x0880, 0xc841, 0xd801, 0x18c0, 0x1980, 0xd941, - 0x1b00, 0xdbc1, 0xda81, 0x1a40, 0x1e00, 0xdec1, 0xdf81, 0x1f40, 0xdd01, - 0x1dc0, 0x1c80, 0xdc41, 0x1400, 0xd4c1, 0xd581, 0x1540, 0xd701, 0x17c0, - 0x1680, 0xd641, 0xd201, 0x12c0, 0x1380, 0xd341, 0x1100, 0xd1c1, 0xd081, - 0x1040, 0xf001, 0x30c0, 0x3180, 0xf141, 0x3300, 0xf3c1, 0xf281, 0x3240, - 0x3600, 0xf6c1, 0xf781, 0x3740, 0xf501, 0x35c0, 0x3480, 0xf441, 0x3c00, - 0xfcc1, 0xfd81, 0x3d40, 0xff01, 0x3fc0, 0x3e80, 0xfe41, 0xfa01, 0x3ac0, - 0x3b80, 0xfb41, 0x3900, 0xf9c1, 0xf881, 0x3840, 0x2800, 0xe8c1, 0xe981, - 0x2940, 0xeb01, 0x2bc0, 0x2a80, 0xea41, 0xee01, 0x2ec0, 0x2f80, 0xef41, - 0x2d00, 0xedc1, 0xec81, 0x2c40, 0xe401, 0x24c0, 0x2580, 0xe541, 0x2700, - 0xe7c1, 0xe681, 0x2640, 0x2200, 0xe2c1, 0xe381, 0x2340, 0xe101, 0x21c0, - 0x2080, 0xe041, 0xa001, 0x60c0, 0x6180, 0xa141, 0x6300, 0xa3c1, 0xa281, - 0x6240, 0x6600, 0xa6c1, 0xa781, 0x6740, 0xa501, 0x65c0, 0x6480, 0xa441, - 0x6c00, 0xacc1, 0xad81, 0x6d40, 0xaf01, 0x6fc0, 0x6e80, 0xae41, 0xaa01, - 0x6ac0, 0x6b80, 0xab41, 0x6900, 0xa9c1, 0xa881, 0x6840, 0x7800, 0xb8c1, - 0xb981, 0x7940, 0xbb01, 0x7bc0, 0x7a80, 0xba41, 0xbe01, 0x7ec0, 0x7f80, - 0xbf41, 0x7d00, 0xbdc1, 0xbc81, 0x7c40, 0xb401, 0x74c0, 0x7580, 0xb541, - 0x7700, 0xb7c1, 0xb681, 0x7640, 0x7200, 0xb2c1, 0xb381, 0x7340, 0xb101, - 0x71c0, 0x7080, 0xb041, 0x5000, 0x90c1, 0x9181, 0x5140, 0x9301, 0x53c0, - 0x5280, 0x9241, 0x9601, 0x56c0, 0x5780, 0x9741, 0x5500, 0x95c1, 0x9481, - 0x5440, 0x9c01, 0x5cc0, 0x5d80, 0x9d41, 0x5f00, 0x9fc1, 0x9e81, 0x5e40, - 0x5a00, 0x9ac1, 0x9b81, 0x5b40, 0x9901, 0x59c0, 0x5880, 0x9841, 0x8801, - 0x48c0, 0x4980, 0x8941, 0x4b00, 0x8bc1, 0x8a81, 0x4a40, 0x4e00, 0x8ec1, - 0x8f81, 0x4f40, 0x8d01, 0x4dc0, 0x4c80, 0x8c41, 0x4400, 0x84c1, 0x8581, - 0x4540, 0x8701, 0x47c0, 0x4680, 0x8641, 0x8201, 0x42c0, 0x4380, 0x8341, - 0x4100, 0x81c1, 0x8081, 0x4040, + 0x0000, 0xc0c1, 0xc181, 0x0140, 0xc301, 0x03c0, 0x0280, 0xc241, 0xc601, 0x06c0, 0x0780, + 0xc741, 0x0500, 0xc5c1, 0xc481, 0x0440, 0xcc01, 0x0cc0, 0x0d80, 0xcd41, 0x0f00, 0xcfc1, + 0xce81, 0x0e40, 0x0a00, 0xcac1, 0xcb81, 0x0b40, 0xc901, 0x09c0, 0x0880, 0xc841, 0xd801, + 0x18c0, 0x1980, 0xd941, 0x1b00, 0xdbc1, 0xda81, 0x1a40, 0x1e00, 0xdec1, 0xdf81, 0x1f40, + 0xdd01, 0x1dc0, 0x1c80, 0xdc41, 0x1400, 0xd4c1, 0xd581, 0x1540, 0xd701, 0x17c0, 0x1680, + 0xd641, 0xd201, 0x12c0, 0x1380, 0xd341, 0x1100, 0xd1c1, 0xd081, 0x1040, 0xf001, 0x30c0, + 0x3180, 0xf141, 0x3300, 0xf3c1, 0xf281, 0x3240, 0x3600, 0xf6c1, 0xf781, 0x3740, 0xf501, + 0x35c0, 0x3480, 0xf441, 0x3c00, 0xfcc1, 0xfd81, 0x3d40, 0xff01, 0x3fc0, 0x3e80, 0xfe41, + 0xfa01, 0x3ac0, 0x3b80, 0xfb41, 0x3900, 0xf9c1, 0xf881, 0x3840, 0x2800, 0xe8c1, 0xe981, + 0x2940, 0xeb01, 0x2bc0, 0x2a80, 0xea41, 0xee01, 0x2ec0, 0x2f80, 0xef41, 0x2d00, 0xedc1, + 0xec81, 0x2c40, 0xe401, 0x24c0, 0x2580, 0xe541, 0x2700, 0xe7c1, 0xe681, 0x2640, 0x2200, + 0xe2c1, 0xe381, 0x2340, 0xe101, 0x21c0, 0x2080, 0xe041, 0xa001, 0x60c0, 0x6180, 0xa141, + 0x6300, 0xa3c1, 0xa281, 0x6240, 0x6600, 0xa6c1, 0xa781, 0x6740, 0xa501, 0x65c0, 0x6480, + 0xa441, 0x6c00, 0xacc1, 0xad81, 0x6d40, 0xaf01, 0x6fc0, 0x6e80, 0xae41, 0xaa01, 0x6ac0, + 0x6b80, 0xab41, 0x6900, 0xa9c1, 0xa881, 0x6840, 0x7800, 0xb8c1, 0xb981, 0x7940, 0xbb01, + 0x7bc0, 0x7a80, 0xba41, 0xbe01, 0x7ec0, 0x7f80, 0xbf41, 0x7d00, 0xbdc1, 0xbc81, 0x7c40, + 0xb401, 0x74c0, 0x7580, 0xb541, 0x7700, 0xb7c1, 0xb681, 0x7640, 0x7200, 0xb2c1, 0xb381, + 0x7340, 0xb101, 0x71c0, 0x7080, 0xb041, 0x5000, 0x90c1, 0x9181, 0x5140, 0x9301, 0x53c0, + 0x5280, 0x9241, 0x9601, 0x56c0, 0x5780, 0x9741, 0x5500, 0x95c1, 0x9481, 0x5440, 0x9c01, + 0x5cc0, 0x5d80, 0x9d41, 0x5f00, 0x9fc1, 0x9e81, 0x5e40, 0x5a00, 0x9ac1, 0x9b81, 0x5b40, + 0x9901, 0x59c0, 0x5880, 0x9841, 0x8801, 0x48c0, 0x4980, 0x8941, 0x4b00, 0x8bc1, 0x8a81, + 0x4a40, 0x4e00, 0x8ec1, 0x8f81, 0x4f40, 0x8d01, 0x4dc0, 0x4c80, 0x8c41, 0x4400, 0x84c1, + 0x8581, 0x4540, 0x8701, 0x47c0, 0x4680, 0x8641, 0x8201, 0x42c0, 0x4380, 0x8341, 0x4100, + 0x81c1, 0x8081, 0x4040, }; /******************************************************************************* * Static local functions -*/ + */ static bool process_reqseq(tL2C_CCB* p_ccb, uint16_t ctrl_word); static void process_s_frame(tL2C_CCB* p_ccb, BT_HDR* p_buf, uint16_t ctrl_word); -static void process_i_frame(tL2C_CCB* p_ccb, BT_HDR* p_buf, uint16_t ctrl_word, - bool delay_ack); +static void process_i_frame(tL2C_CCB* p_ccb, BT_HDR* p_buf, uint16_t ctrl_word, bool delay_ack); static bool retransmit_i_frames(tL2C_CCB* p_ccb, uint8_t tx_seq); -static void prepare_I_frame(tL2C_CCB* p_ccb, BT_HDR* p_buf, - bool is_retransmission); -static bool do_sar_reassembly(tL2C_CCB* p_ccb, BT_HDR* p_buf, - uint16_t ctrl_word); +static void prepare_I_frame(tL2C_CCB* p_ccb, BT_HDR* p_buf, bool is_retransmission); +static bool do_sar_reassembly(tL2C_CCB* p_ccb, BT_HDR* p_buf, uint16_t ctrl_word); /******************************************************************************* * @@ -104,8 +95,7 @@ static bool do_sar_reassembly(tL2C_CCB* p_ccb, BT_HDR* p_buf, * Returns CRC * ******************************************************************************/ -static unsigned short l2c_fcr_updcrc(unsigned short icrc, unsigned char* icp, - int icnt) { +static unsigned short l2c_fcr_updcrc(unsigned short icrc, unsigned char* icp, int icnt) { unsigned short crc = icrc; unsigned char* cp = icp; int cnt = icnt; @@ -114,7 +104,7 @@ static unsigned short l2c_fcr_updcrc(unsigned short icrc, unsigned char* icp, crc = ((crc >> 8) & 0xff) ^ crctab[(crc & 0xff) ^ *cp++]; } - return (crc); + return crc; } /******************************************************************************* @@ -129,7 +119,7 @@ static unsigned short l2c_fcr_updcrc(unsigned short icrc, unsigned char* icp, static uint16_t l2c_fcr_tx_get_fcs(BT_HDR* p_buf) { uint8_t* p = ((uint8_t*)(p_buf + 1)) + p_buf->offset; - return (l2c_fcr_updcrc(L2CAP_FCR_INIT_CRC, p, p_buf->len)); + return l2c_fcr_updcrc(L2CAP_FCR_INIT_CRC, p, p_buf->len); } /******************************************************************************* @@ -147,8 +137,7 @@ static uint16_t l2c_fcr_rx_get_fcs(BT_HDR* p_buf) { /* offset points past the L2CAP header, but the CRC check includes it */ p -= L2CAP_PKT_OVERHEAD; - return ( - l2c_fcr_updcrc(L2CAP_FCR_INIT_CRC, p, p_buf->len + L2CAP_PKT_OVERHEAD)); + return l2c_fcr_updcrc(L2CAP_FCR_INIT_CRC, p, p_buf->len + L2CAP_PKT_OVERHEAD); } /******************************************************************************* @@ -173,8 +162,7 @@ void l2c_fcr_start_timer(tL2C_CCB* p_ccb) { /* Only start a timer that was not started */ if (!alarm_is_scheduled(p_ccb->fcrb.mon_retrans_timer)) { - alarm_set_on_mloop(p_ccb->fcrb.mon_retrans_timer, tout, - l2c_ccb_timer_timeout, p_ccb); + alarm_set_on_mloop(p_ccb->fcrb.mon_retrans_timer, tout, l2c_ccb_timer_timeout, p_ccb); } } @@ -235,8 +223,7 @@ void l2c_fcr_cleanup(tL2C_CCB* p_ccb) { * Returns pointer to new buffer * ******************************************************************************/ -BT_HDR* l2c_fcr_clone_buf(BT_HDR* p_buf, uint16_t new_offset, - uint16_t no_of_bytes) { +BT_HDR* l2c_fcr_clone_buf(BT_HDR* p_buf, uint16_t new_offset, uint16_t no_of_bytes) { log::assert_that(p_buf != NULL, "assert failed: p_buf != NULL"); /* * NOTE: We allocate extra L2CAP_FCS_LEN octets, in case we need to put @@ -247,10 +234,10 @@ BT_HDR* l2c_fcr_clone_buf(BT_HDR* p_buf, uint16_t new_offset, p_buf2->offset = new_offset; p_buf2->len = no_of_bytes; - memcpy(((uint8_t*)(p_buf2 + 1)) + p_buf2->offset, - ((uint8_t*)(p_buf + 1)) + p_buf->offset, no_of_bytes); + memcpy(((uint8_t*)(p_buf2 + 1)) + p_buf2->offset, ((uint8_t*)(p_buf + 1)) + p_buf->offset, + no_of_bytes); - return (p_buf2); + return p_buf2; } /******************************************************************************* @@ -267,12 +254,11 @@ bool l2c_fcr_is_flow_controlled(tL2C_CCB* p_ccb) { if (p_ccb->peer_cfg.fcr.mode == L2CAP_FCR_ERTM_MODE) { /* Check if remote side flowed us off or the transmit window is full */ if ((p_ccb->fcrb.remote_busy) || - (fixed_queue_length(p_ccb->fcrb.waiting_for_ack_q) >= - p_ccb->peer_cfg.fcr.tx_win_sz)) { - return (true); + (fixed_queue_length(p_ccb->fcrb.waiting_for_ack_q) >= p_ccb->peer_cfg.fcr.tx_win_sz)) { + return true; } } - return (false); + return false; } /******************************************************************************* @@ -286,8 +272,7 @@ bool l2c_fcr_is_flow_controlled(tL2C_CCB* p_ccb) { * Returns - * ******************************************************************************/ -static void prepare_I_frame(tL2C_CCB* p_ccb, BT_HDR* p_buf, - bool is_retransmission) { +static void prepare_I_frame(tL2C_CCB* p_ccb, BT_HDR* p_buf, bool is_retransmission) { log::assert_that(p_ccb != NULL, "assert failed: p_ccb != NULL"); log::assert_that(p_buf != NULL, "assert failed: p_buf != NULL"); tL2C_FCRB* p_fcrb = &p_ccb->fcrb; @@ -306,16 +291,17 @@ static void prepare_I_frame(tL2C_CCB* p_ccb, BT_HDR* p_buf, ctrl_word &= ~(L2CAP_FCR_REQ_SEQ_BITS + L2CAP_FCR_F_BIT); } else { - ctrl_word = p_buf->layer_specific & L2CAP_FCR_SEG_BITS; /* SAR bits */ - ctrl_word |= - (p_fcrb->next_tx_seq << L2CAP_FCR_TX_SEQ_BITS_SHIFT); /* Tx Seq */ + ctrl_word = p_buf->layer_specific & L2CAP_FCR_SEG_BITS; /* SAR bits */ + ctrl_word |= (p_fcrb->next_tx_seq << L2CAP_FCR_TX_SEQ_BITS_SHIFT); /* Tx Seq */ p_fcrb->next_tx_seq = (p_fcrb->next_tx_seq + 1) & L2CAP_FCR_SEQ_MODULO; } /* Set the F-bit and reqseq only if using re-transmission mode */ if (p_ccb->peer_cfg.fcr.mode == L2CAP_FCR_ERTM_MODE) { - if (set_f_bit) ctrl_word |= L2CAP_FCR_F_BIT; + if (set_f_bit) { + ctrl_word |= L2CAP_FCR_F_BIT; + } ctrl_word |= (p_fcrb->next_seq_expected) << L2CAP_FCR_REQ_SEQ_BITS_SHIFT; @@ -350,27 +336,28 @@ static void prepare_I_frame(tL2C_CCB* p_ccb, BT_HDR* p_buf, if (is_retransmission) { log::verbose( - "L2CAP eRTM ReTx I-frame CID: 0x{:04x} Len: {} SAR: {} TxSeq: {} " - "ReqSeq: {} F: {}", - p_ccb->local_cid, p_buf->len, - SAR_types[(ctrl_word & L2CAP_FCR_SAR_BITS) >> L2CAP_FCR_SAR_BITS_SHIFT], - (ctrl_word & L2CAP_FCR_TX_SEQ_BITS) >> L2CAP_FCR_TX_SEQ_BITS_SHIFT, - (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT, - (ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT); + "L2CAP eRTM ReTx I-frame CID: 0x{:04x} Len: {} SAR: {} TxSeq: {} " + "ReqSeq: {} F: {}", + p_ccb->local_cid, p_buf->len, + SAR_types[(ctrl_word & L2CAP_FCR_SAR_BITS) >> L2CAP_FCR_SAR_BITS_SHIFT], + (ctrl_word & L2CAP_FCR_TX_SEQ_BITS) >> L2CAP_FCR_TX_SEQ_BITS_SHIFT, + (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT, + (ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT); } else { log::verbose( - "L2CAP eRTM Tx I-frame CID: 0x{:04x} Len: {} SAR: {:<12s} TxSeq: {} " - " ReqSeq: {} F: {}", - p_ccb->local_cid, p_buf->len, - SAR_types[(ctrl_word & L2CAP_FCR_SAR_BITS) >> L2CAP_FCR_SAR_BITS_SHIFT], - (ctrl_word & L2CAP_FCR_TX_SEQ_BITS) >> L2CAP_FCR_TX_SEQ_BITS_SHIFT, - (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT, - (ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT); + "L2CAP eRTM Tx I-frame CID: 0x{:04x} Len: {} SAR: {:<12s} TxSeq: {} " + " ReqSeq: {} F: {}", + p_ccb->local_cid, p_buf->len, + SAR_types[(ctrl_word & L2CAP_FCR_SAR_BITS) >> L2CAP_FCR_SAR_BITS_SHIFT], + (ctrl_word & L2CAP_FCR_TX_SEQ_BITS) >> L2CAP_FCR_TX_SEQ_BITS_SHIFT, + (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT, + (ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT); } /* Start the retransmission timer if not already running */ - if (p_ccb->peer_cfg.fcr.mode == L2CAP_FCR_ERTM_MODE) + if (p_ccb->peer_cfg.fcr.mode == L2CAP_FCR_ERTM_MODE) { l2c_fcr_start_timer(p_ccb); + } } /******************************************************************************* @@ -382,14 +369,15 @@ static void prepare_I_frame(tL2C_CCB* p_ccb, BT_HDR* p_buf, * Returns - * ******************************************************************************/ -void l2c_fcr_send_S_frame(tL2C_CCB* p_ccb, uint16_t function_code, - uint16_t pf_bit) { +void l2c_fcr_send_S_frame(tL2C_CCB* p_ccb, uint16_t function_code, uint16_t pf_bit) { log::assert_that(p_ccb != NULL, "assert failed: p_ccb != NULL"); uint8_t* p; uint16_t ctrl_word; uint16_t fcs; - if ((!p_ccb->in_use) || (p_ccb->chnl_state != CST_OPEN)) return; + if ((!p_ccb->in_use) || (p_ccb->chnl_state != CST_OPEN)) { + return; + } if (pf_bit == L2CAP_FCR_P_BIT) { p_ccb->fcrb.wait_ack = true; @@ -428,23 +416,23 @@ void l2c_fcr_send_S_frame(tL2C_CCB* p_ccb, uint16_t function_code, if ((((ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT) == 1) || (((ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT) == 3)) { log::warn( - "L2CAP eRTM Tx S-frame CID: 0x{:04x} ctrlword: 0x{:04x} Type: {} " - "ReqSeq: {} P: {} F: {}", - p_ccb->local_cid, ctrl_word, - SUP_types[(ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT], - (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT, - (ctrl_word & L2CAP_FCR_P_BIT) >> L2CAP_FCR_P_BIT_SHIFT, - (ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT); + "L2CAP eRTM Tx S-frame CID: 0x{:04x} ctrlword: 0x{:04x} Type: {} " + "ReqSeq: {} P: {} F: {}", + p_ccb->local_cid, ctrl_word, + SUP_types[(ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT], + (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT, + (ctrl_word & L2CAP_FCR_P_BIT) >> L2CAP_FCR_P_BIT_SHIFT, + (ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT); log::warn("Buf Len: {}", p_buf->len); } else { log::verbose( - "L2CAP eRTM Tx S-frame CID: 0x{:04x} ctrlword: 0x{:04x} Type: {} " - "ReqSeq: {} P: {} F: {}", - p_ccb->local_cid, ctrl_word, - SUP_types[(ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT], - (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT, - (ctrl_word & L2CAP_FCR_P_BIT) >> L2CAP_FCR_P_BIT_SHIFT, - (ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT); + "L2CAP eRTM Tx S-frame CID: 0x{:04x} ctrlword: 0x{:04x} Type: {} " + "ReqSeq: {} P: {} F: {}", + p_ccb->local_cid, ctrl_word, + SUP_types[(ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT], + (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT, + (ctrl_word & L2CAP_FCR_P_BIT) >> L2CAP_FCR_P_BIT_SHIFT, + (ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT); log::verbose("Buf Len: {}", p_buf->len); } @@ -478,8 +466,7 @@ void l2c_fcr_proc_pdu(tL2C_CCB* p_ccb, BT_HDR* p_buf) { min_pdu_len = (uint16_t)(L2CAP_FCS_LEN + L2CAP_FCR_OVERHEAD); if (p_buf->len < min_pdu_len) { - log::warn("Rx L2CAP PDU: CID: 0x{:04x} Len too short: {}", - p_ccb->local_cid, p_buf->len); + log::warn("Rx L2CAP PDU: CID: 0x{:04x} Len too short: {}", p_ccb->local_cid, p_buf->len); osi_free(p_buf); return; } @@ -493,40 +480,40 @@ void l2c_fcr_proc_pdu(tL2C_CCB* p_ccb, BT_HDR* p_buf) { (((ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT) == 3)) { /* REJ or SREJ */ log::warn( - "L2CAP eRTM Rx S-frame: cid: 0x{:04x} Len: {} Type: {} ReqSeq: {} " - " P: {} F: {}", - p_ccb->local_cid, p_buf->len, - SUP_types[(ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT], - (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT, - (ctrl_word & L2CAP_FCR_P_BIT) >> L2CAP_FCR_P_BIT_SHIFT, - (ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT); + "L2CAP eRTM Rx S-frame: cid: 0x{:04x} Len: {} Type: {} ReqSeq: {} " + " P: {} F: {}", + p_ccb->local_cid, p_buf->len, + SUP_types[(ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT], + (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT, + (ctrl_word & L2CAP_FCR_P_BIT) >> L2CAP_FCR_P_BIT_SHIFT, + (ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT); } else { log::verbose( - "L2CAP eRTM Rx S-frame: cid: 0x{:04x} Len: {} Type: {} ReqSeq: {} " - " P: {} F: {}", - p_ccb->local_cid, p_buf->len, - SUP_types[(ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT], - (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT, - (ctrl_word & L2CAP_FCR_P_BIT) >> L2CAP_FCR_P_BIT_SHIFT, - (ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT); + "L2CAP eRTM Rx S-frame: cid: 0x{:04x} Len: {} Type: {} ReqSeq: {} " + " P: {} F: {}", + p_ccb->local_cid, p_buf->len, + SUP_types[(ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT], + (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT, + (ctrl_word & L2CAP_FCR_P_BIT) >> L2CAP_FCR_P_BIT_SHIFT, + (ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT); } } else { log::verbose( - "L2CAP eRTM Rx I-frame: cid: 0x{:04x} Len: {} SAR: {:<12s} TxSeq: " - "{} ReqSeq: {} F: {}", - p_ccb->local_cid, p_buf->len, - SAR_types[(ctrl_word & L2CAP_FCR_SAR_BITS) >> L2CAP_FCR_SAR_BITS_SHIFT], - (ctrl_word & L2CAP_FCR_TX_SEQ_BITS) >> L2CAP_FCR_TX_SEQ_BITS_SHIFT, - (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT, - (ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT); + "L2CAP eRTM Rx I-frame: cid: 0x{:04x} Len: {} SAR: {:<12s} TxSeq: " + "{} ReqSeq: {} F: {}", + p_ccb->local_cid, p_buf->len, + SAR_types[(ctrl_word & L2CAP_FCR_SAR_BITS) >> L2CAP_FCR_SAR_BITS_SHIFT], + (ctrl_word & L2CAP_FCR_TX_SEQ_BITS) >> L2CAP_FCR_TX_SEQ_BITS_SHIFT, + (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT, + (ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT); } log::verbose( - "eRTM Rx Nxt_tx_seq {}, Lst_rx_ack {}, Nxt_seq_exp {}, Lst_ack_snt {}, " - "wt_q.cnt {}, tries {}", - p_ccb->fcrb.next_tx_seq, p_ccb->fcrb.last_rx_ack, - p_ccb->fcrb.next_seq_expected, p_ccb->fcrb.last_ack_sent, - fixed_queue_length(p_ccb->fcrb.waiting_for_ack_q), p_ccb->fcrb.num_tries); + "eRTM Rx Nxt_tx_seq {}, Lst_rx_ack {}, Nxt_seq_exp {}, Lst_ack_snt {}, " + "wt_q.cnt {}, tries {}", + p_ccb->fcrb.next_tx_seq, p_ccb->fcrb.last_rx_ack, p_ccb->fcrb.next_seq_expected, + p_ccb->fcrb.last_ack_sent, fixed_queue_length(p_ccb->fcrb.waiting_for_ack_q), + p_ccb->fcrb.num_tries); /* Verify FCS if using */ p = ((uint8_t*)(p_buf + 1)) + p_buf->offset + p_buf->len - L2CAP_FCS_LEN; @@ -553,12 +540,12 @@ void l2c_fcr_proc_pdu(tL2C_CCB* p_ccb, BT_HDR* p_buf) { if (p_ccb->fcrb.wait_ack) { /* If final bit not set, ignore the frame unless it is a polled S-frame */ if (!(ctrl_word & L2CAP_FCR_F_BIT)) { - if ((ctrl_word & L2CAP_FCR_P_BIT) && - (ctrl_word & L2CAP_FCR_S_FRAME_BIT)) { - if (p_ccb->fcrb.srej_sent) + if ((ctrl_word & L2CAP_FCR_P_BIT) && (ctrl_word & L2CAP_FCR_S_FRAME_BIT)) { + if (p_ccb->fcrb.srej_sent) { l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_SREJ, L2CAP_FCR_F_BIT); - else + } else { l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_RR, L2CAP_FCR_F_BIT); + } /* Got a poll while in wait_ack state, so re-start our timer with * 1-second */ @@ -568,8 +555,8 @@ void l2c_fcr_proc_pdu(tL2C_CCB* p_ccb, BT_HDR* p_buf) { * final, */ /* then it speeds up recovery significantly if we poll it back soon * after its poll. */ - alarm_set_on_mloop(p_ccb->fcrb.mon_retrans_timer, BT_1SEC_TIMEOUT_MS, - l2c_ccb_timer_timeout, p_ccb); + alarm_set_on_mloop(p_ccb->fcrb.mon_retrans_timer, BT_1SEC_TIMEOUT_MS, l2c_ccb_timer_timeout, + p_ccb); } osi_free(p_buf); return; @@ -578,10 +565,13 @@ void l2c_fcr_proc_pdu(tL2C_CCB* p_ccb, BT_HDR* p_buf) { p_ccb->fcrb.wait_ack = false; /* P and F are mutually exclusive */ - if (ctrl_word & L2CAP_FCR_S_FRAME_BIT) ctrl_word &= ~L2CAP_FCR_P_BIT; + if (ctrl_word & L2CAP_FCR_S_FRAME_BIT) { + ctrl_word &= ~L2CAP_FCR_P_BIT; + } - if (fixed_queue_is_empty(p_ccb->fcrb.waiting_for_ack_q)) + if (fixed_queue_is_empty(p_ccb->fcrb.waiting_for_ack_q)) { p_ccb->fcrb.num_tries = 0; + } l2c_fcr_stop_timer(p_ccb); } else { @@ -596,19 +586,21 @@ void l2c_fcr_proc_pdu(tL2C_CCB* p_ccb, BT_HDR* p_buf) { } /* Process based on whether it is an S-frame or an I-frame */ - if (ctrl_word & L2CAP_FCR_S_FRAME_BIT) + if (ctrl_word & L2CAP_FCR_S_FRAME_BIT) { process_s_frame(p_ccb, p_buf, ctrl_word); - else + } else { process_i_frame(p_ccb, p_buf, ctrl_word, false); + } /* Return if the channel got disconnected by a bad packet or max * retransmissions */ - if ((!p_ccb->in_use) || (p_ccb->chnl_state != CST_OPEN)) return; + if ((!p_ccb->in_use) || (p_ccb->chnl_state != CST_OPEN)) { + return; + } /* If we have some buffers held while doing SREJ, and SREJ has cleared, * process them now */ - if ((!p_ccb->fcrb.srej_sent) && - (!fixed_queue_is_empty(p_ccb->fcrb.srej_rcv_hold_q))) { + if ((!p_ccb->fcrb.srej_sent) && (!fixed_queue_is_empty(p_ccb->fcrb.srej_rcv_hold_q))) { fixed_queue_t* temp_q = p_ccb->fcrb.srej_rcv_hold_q; p_ccb->fcrb.srej_rcv_hold_q = fixed_queue_new(SIZE_MAX); @@ -620,17 +612,18 @@ void l2c_fcr_proc_pdu(tL2C_CCB* p_ccb, BT_HDR* p_buf) { STREAM_TO_UINT16(ctrl_word, p); log::verbose( - "l2c_fcr_proc_pdu() CID: 0x{:04x} Process Buffer from SREJ_Hold_Q " - " TxSeq: {} Expected_Seq: {}", - p_ccb->local_cid, - (ctrl_word & L2CAP_FCR_TX_SEQ_BITS) >> L2CAP_FCR_TX_SEQ_BITS_SHIFT, - p_ccb->fcrb.next_seq_expected); + "l2c_fcr_proc_pdu() CID: 0x{:04x} Process Buffer from SREJ_Hold_Q " + " TxSeq: {} Expected_Seq: {}", + p_ccb->local_cid, + (ctrl_word & L2CAP_FCR_TX_SEQ_BITS) >> L2CAP_FCR_TX_SEQ_BITS_SHIFT, + p_ccb->fcrb.next_seq_expected); /* Process the SREJ held I-frame, but do not send an RR for each * individual frame */ process_i_frame(p_ccb, p_buf, ctrl_word, true); - } else + } else { osi_free(p_buf); + } /* If more frames were lost during SREJ, send a REJ */ if (p_ccb->fcrb.rej_after_srej) { @@ -644,20 +637,19 @@ void l2c_fcr_proc_pdu(tL2C_CCB* p_ccb, BT_HDR* p_buf) { /* Now, if needed, send one RR for the whole held queue */ if ((!p_ccb->fcrb.rej_sent) && (!p_ccb->fcrb.srej_sent) && - (p_ccb->fcrb.next_seq_expected != p_ccb->fcrb.last_ack_sent)) + (p_ccb->fcrb.next_seq_expected != p_ccb->fcrb.last_ack_sent)) { l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_RR, 0); - else { + } else { log::verbose( - "l2c_fcr_proc_pdu() not sending RR CID: 0x{:04x} local_busy:{} " - "rej_sent:{} srej_sent:{} Expected_Seq:{} Last_Ack:{}", - p_ccb->local_cid, 0, p_ccb->fcrb.rej_sent, p_ccb->fcrb.srej_sent, - p_ccb->fcrb.next_seq_expected, p_ccb->fcrb.last_ack_sent); + "l2c_fcr_proc_pdu() not sending RR CID: 0x{:04x} local_busy:{} " + "rej_sent:{} srej_sent:{} Expected_Seq:{} Last_Ack:{}", + p_ccb->local_cid, 0, p_ccb->fcrb.rej_sent, p_ccb->fcrb.srej_sent, + p_ccb->fcrb.next_seq_expected, p_ccb->fcrb.last_ack_sent); } } /* If a window has opened, check if we can send any more packets */ - if ((!fixed_queue_is_empty(p_ccb->fcrb.retrans_q) || - !fixed_queue_is_empty(p_ccb->xmit_hold_q)) && + if ((!fixed_queue_is_empty(p_ccb->fcrb.retrans_q) || !fixed_queue_is_empty(p_ccb->xmit_hold_q)) && (!p_ccb->fcrb.wait_ack) && (!l2c_fcr_is_flow_controlled(p_ccb))) { l2c_link_check_send_pkts(p_ccb->p_lcb, 0, NULL); } @@ -682,8 +674,8 @@ void l2c_lcc_proc_pdu(tL2C_CCB* p_ccb, BT_HDR* p_buf) { /* Buffer length should not exceed local mps */ if (p_buf->len > p_ccb->local_conn_cfg.mps) { - log::error("buffer length={} exceeds local mps={}. Drop and disconnect.", - p_buf->len, p_ccb->local_conn_cfg.mps); + log::error("buffer length={} exceeds local mps={}. Drop and disconnect.", p_buf->len, + p_ccb->local_conn_cfg.mps); /* Discard the buffer and disconnect*/ osi_free(p_buf); @@ -702,8 +694,8 @@ void l2c_lcc_proc_pdu(tL2C_CCB* p_ccb, BT_HDR* p_buf) { /* Check the SDU Length with local MTU size */ if (sdu_length > p_ccb->local_conn_cfg.mtu) { - log::error("sdu length={} exceeds local mtu={}. Drop and disconnect.", - sdu_length, p_ccb->local_conn_cfg.mtu); + log::error("sdu length={} exceeds local mtu={}. Drop and disconnect.", sdu_length, + p_ccb->local_conn_cfg.mtu); /* Discard the buffer and disconnect*/ osi_free(p_buf); l2cu_disconnect_chnl(p_ccb); @@ -782,10 +774,10 @@ void l2c_lcc_proc_pdu(tL2C_CCB* p_ccb, BT_HDR* p_buf) { void l2c_fcr_proc_tout(tL2C_CCB* p_ccb) { log::assert_that(p_ccb != NULL, "assert failed: p_ccb != NULL"); log::verbose( - "l2c_fcr_proc_tout: CID: 0x{:04x} num_tries: {} (max: {}) wait_ack: " - "{} ack_q_count: {}", - p_ccb->local_cid, p_ccb->fcrb.num_tries, p_ccb->peer_cfg.fcr.max_transmit, - p_ccb->fcrb.wait_ack, fixed_queue_length(p_ccb->fcrb.waiting_for_ack_q)); + "l2c_fcr_proc_tout: CID: 0x{:04x} num_tries: {} (max: {}) wait_ack: " + "{} ack_q_count: {}", + p_ccb->local_cid, p_ccb->fcrb.num_tries, p_ccb->peer_cfg.fcr.max_transmit, + p_ccb->fcrb.wait_ack, fixed_queue_length(p_ccb->fcrb.waiting_for_ack_q)); if ((p_ccb->peer_cfg.fcr.max_transmit != 0) && (++p_ccb->fcrb.num_tries > p_ccb->peer_cfg.fcr.max_transmit)) { @@ -809,10 +801,10 @@ void l2c_fcr_proc_tout(tL2C_CCB* p_ccb) { void l2c_fcr_proc_ack_tout(tL2C_CCB* p_ccb) { log::assert_that(p_ccb != NULL, "assert failed: p_ccb != NULL"); log::verbose( - "l2c_fcr_proc_ack_tout: CID: 0x{:04x} State: {} Wack:{} Rq:{} " - "Acked:{}", - p_ccb->local_cid, p_ccb->chnl_state, p_ccb->fcrb.wait_ack, - p_ccb->fcrb.next_seq_expected, p_ccb->fcrb.last_ack_sent); + "l2c_fcr_proc_ack_tout: CID: 0x{:04x} State: {} Wack:{} Rq:{} " + "Acked:{}", + p_ccb->local_cid, p_ccb->chnl_state, p_ccb->fcrb.wait_ack, p_ccb->fcrb.next_seq_expected, + p_ccb->fcrb.last_ack_sent); if ((p_ccb->chnl_state == CST_OPEN) && (!p_ccb->fcrb.wait_ack) && (p_ccb->fcrb.last_ack_sent != p_ccb->fcrb.next_seq_expected)) { @@ -839,19 +831,18 @@ static bool process_reqseq(tL2C_CCB* p_ccb, uint16_t ctrl_word) { /* Receive sequence number does not ack anything for SREJ with P-bit set to * zero */ if ((ctrl_word & L2CAP_FCR_S_FRAME_BIT) && - ((ctrl_word & L2CAP_FCR_SUP_BITS) == - (L2CAP_FCR_SUP_SREJ << L2CAP_FCR_SUP_SHIFT)) && + ((ctrl_word & L2CAP_FCR_SUP_BITS) == (L2CAP_FCR_SUP_SREJ << L2CAP_FCR_SUP_SHIFT)) && ((ctrl_word & L2CAP_FCR_P_BIT) == 0)) { /* If anything still waiting for ack, restart the timer if it was stopped */ - if (!fixed_queue_is_empty(p_fcrb->waiting_for_ack_q)) + if (!fixed_queue_is_empty(p_fcrb->waiting_for_ack_q)) { l2c_fcr_start_timer(p_ccb); + } - return (true); + return true; } /* Extract the receive sequence number from the control word */ - req_seq = - (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT; + req_seq = (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT; num_bufs_acked = (req_seq - p_fcrb->last_rx_ack) & L2CAP_FCR_SEQ_MODULO; @@ -859,13 +850,12 @@ static bool process_reqseq(tL2C_CCB* p_ccb, uint16_t ctrl_word) { if (num_bufs_acked > fixed_queue_length(p_fcrb->waiting_for_ack_q)) { /* The channel is closed if ReqSeq is not in range */ log::warn( - "L2CAP eRTM Frame BAD Req_Seq - ctrl_word: 0x{:04x} req_seq 0x{:02x} " - "last_rx_ack: 0x{:02x} QCount: {}", - ctrl_word, req_seq, p_fcrb->last_rx_ack, - fixed_queue_length(p_fcrb->waiting_for_ack_q)); + "L2CAP eRTM Frame BAD Req_Seq - ctrl_word: 0x{:04x} req_seq 0x{:02x} " + "last_rx_ack: 0x{:02x} QCount: {}", + ctrl_word, req_seq, p_fcrb->last_rx_ack, fixed_queue_length(p_fcrb->waiting_for_ack_q)); l2cu_disconnect_chnl(p_ccb); - return (false); + return false; } p_fcrb->last_rx_ack = req_seq; @@ -877,37 +867,38 @@ static bool process_reqseq(tL2C_CCB* p_ccb, uint16_t ctrl_word) { full_sdus_xmitted = 0; for (xx = 0; xx < num_bufs_acked; xx++) { - BT_HDR* p_tmp = - (BT_HDR*)fixed_queue_try_dequeue(p_fcrb->waiting_for_ack_q); + BT_HDR* p_tmp = (BT_HDR*)fixed_queue_try_dequeue(p_fcrb->waiting_for_ack_q); ls = p_tmp->layer_specific & L2CAP_FCR_SAR_BITS; - if ((ls == L2CAP_FCR_UNSEG_SDU) || (ls == L2CAP_FCR_END_SDU)) + if ((ls == L2CAP_FCR_UNSEG_SDU) || (ls == L2CAP_FCR_END_SDU)) { full_sdus_xmitted++; + } osi_free(p_tmp); } /* If we are still in a wait_ack state, do not mess with the timer */ - if (!p_ccb->fcrb.wait_ack) l2c_fcr_stop_timer(p_ccb); + if (!p_ccb->fcrb.wait_ack) { + l2c_fcr_stop_timer(p_ccb); + } /* Check if we need to call the "packet_sent" callback */ - if ((p_ccb->p_rcb) && (p_ccb->p_rcb->api.pL2CA_TxComplete_Cb) && - (full_sdus_xmitted)) { + if ((p_ccb->p_rcb) && (p_ccb->p_rcb->api.pL2CA_TxComplete_Cb) && (full_sdus_xmitted)) { /* Special case for eRTM, if all packets sent, send 0xFFFF */ if (fixed_queue_is_empty(p_fcrb->waiting_for_ack_q) && fixed_queue_is_empty(p_ccb->xmit_hold_q)) { full_sdus_xmitted = 0xFFFF; } - (*p_ccb->p_rcb->api.pL2CA_TxComplete_Cb)(p_ccb->local_cid, - full_sdus_xmitted); + (*p_ccb->p_rcb->api.pL2CA_TxComplete_Cb)(p_ccb->local_cid, full_sdus_xmitted); } } /* If anything still waiting for ack, restart the timer if it was stopped */ - if (!fixed_queue_is_empty(p_fcrb->waiting_for_ack_q)) + if (!fixed_queue_is_empty(p_fcrb->waiting_for_ack_q)) { l2c_fcr_start_timer(p_ccb); - return (true); + } + return true; } /******************************************************************************* @@ -919,14 +910,12 @@ static bool process_reqseq(tL2C_CCB* p_ccb, uint16_t ctrl_word) { * Returns - * ******************************************************************************/ -static void process_s_frame(tL2C_CCB* p_ccb, BT_HDR* p_buf, - uint16_t ctrl_word) { +static void process_s_frame(tL2C_CCB* p_ccb, BT_HDR* p_buf, uint16_t ctrl_word) { log::assert_that(p_ccb != NULL, "assert failed: p_ccb != NULL"); log::assert_that(p_buf != NULL, "assert failed: p_buf != NULL"); tL2C_FCRB* p_fcrb = &p_ccb->fcrb; - uint16_t s_frame_type = - (ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT; + uint16_t s_frame_type = (ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT; bool remote_was_busy; bool all_ok = true; @@ -934,11 +923,11 @@ static void process_s_frame(tL2C_CCB* p_ccb, BT_HDR* p_buf, log::warn("Incorrect S-frame Length ({})", p_buf->len); } - log::verbose("process_s_frame ctrl_word 0x{:04x} fcrb_remote_busy:{}", - ctrl_word, p_fcrb->remote_busy); + log::verbose("process_s_frame ctrl_word 0x{:04x} fcrb_remote_busy:{}", ctrl_word, + p_fcrb->remote_busy); if (ctrl_word & L2CAP_FCR_P_BIT) { - p_fcrb->rej_sent = false; /* After checkpoint, we can send anoher REJ */ + p_fcrb->rej_sent = false; /* After checkpoint, we can send another REJ */ p_fcrb->send_f_rsp = true; /* Set a flag in case an I-frame is pending */ } @@ -947,8 +936,9 @@ static void process_s_frame(tL2C_CCB* p_ccb, BT_HDR* p_buf, remote_was_busy = p_fcrb->remote_busy; p_fcrb->remote_busy = false; - if ((ctrl_word & L2CAP_FCR_F_BIT) || (remote_was_busy)) + if ((ctrl_word & L2CAP_FCR_F_BIT) || (remote_was_busy)) { all_ok = retransmit_i_frames(p_ccb, L2C_FCR_RETX_ALL_PKTS); + } break; case L2CAP_FCR_SUP_REJ: @@ -963,9 +953,8 @@ static void process_s_frame(tL2C_CCB* p_ccb, BT_HDR* p_buf, case L2CAP_FCR_SUP_SREJ: p_fcrb->remote_busy = false; - all_ok = retransmit_i_frames( - p_ccb, (uint8_t)((ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> - L2CAP_FCR_REQ_SEQ_BITS_SHIFT)); + all_ok = retransmit_i_frames(p_ccb, (uint8_t)((ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> + L2CAP_FCR_REQ_SEQ_BITS_SHIFT)); break; } @@ -973,10 +962,11 @@ static void process_s_frame(tL2C_CCB* p_ccb, BT_HDR* p_buf, /* If polled, we need to respond with F-bit. Note, we may have sent a * I-frame with the F-bit */ if (p_fcrb->send_f_rsp) { - if (p_fcrb->srej_sent) + if (p_fcrb->srej_sent) { l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_SREJ, L2CAP_FCR_F_BIT); - else + } else { l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_RR, L2CAP_FCR_F_BIT); + } p_fcrb->send_f_rsp = false; } @@ -996,8 +986,7 @@ static void process_s_frame(tL2C_CCB* p_ccb, BT_HDR* p_buf, * Returns - * ******************************************************************************/ -static void process_i_frame(tL2C_CCB* p_ccb, BT_HDR* p_buf, uint16_t ctrl_word, - bool delay_ack) { +static void process_i_frame(tL2C_CCB* p_ccb, BT_HDR* p_buf, uint16_t ctrl_word, bool delay_ack) { log::assert_that(p_ccb != NULL, "assert failed: p_ccb != NULL"); log::assert_that(p_buf != NULL, "assert failed: p_buf != NULL"); @@ -1024,61 +1013,54 @@ static void process_i_frame(tL2C_CCB* p_ccb, BT_HDR* p_buf, uint16_t ctrl_word, if (num_lost >= p_ccb->our_cfg.fcr.tx_win_sz) { /* Duplicate - simply drop it */ log::warn( - "process_i_frame() Dropping Duplicate Frame tx_seq:{} ExpectedTxSeq " - "{}", - tx_seq, p_fcrb->next_seq_expected); + "process_i_frame() Dropping Duplicate Frame tx_seq:{} ExpectedTxSeq " + "{}", + tx_seq, p_fcrb->next_seq_expected); osi_free(p_buf); } else { log::warn( - "process_i_frame() CID: 0x{:04x} Lost: {} tx_seq:{} ExpTxSeq {} " - "Rej: {} SRej: {}", - p_ccb->local_cid, num_lost, tx_seq, p_fcrb->next_seq_expected, - p_fcrb->rej_sent, p_fcrb->srej_sent); + "process_i_frame() CID: 0x{:04x} Lost: {} tx_seq:{} ExpTxSeq {} " + "Rej: {} SRej: {}", + p_ccb->local_cid, num_lost, tx_seq, p_fcrb->next_seq_expected, p_fcrb->rej_sent, + p_fcrb->srej_sent); if (p_fcrb->srej_sent) { /* If SREJ sent, save the frame for later processing as long as it is in * sequence */ - next_srej = - (((BT_HDR*)fixed_queue_try_peek_last(p_fcrb->srej_rcv_hold_q)) - ->layer_specific + - 1) & - L2CAP_FCR_SEQ_MODULO; + next_srej = (((BT_HDR*)fixed_queue_try_peek_last(p_fcrb->srej_rcv_hold_q))->layer_specific + + 1) & + L2CAP_FCR_SEQ_MODULO; if ((tx_seq == next_srej) && - (fixed_queue_length(p_fcrb->srej_rcv_hold_q) < - p_ccb->our_cfg.fcr.tx_win_sz)) { + (fixed_queue_length(p_fcrb->srej_rcv_hold_q) < p_ccb->our_cfg.fcr.tx_win_sz)) { log::verbose( - "process_i_frame() Lost: {} tx_seq:{} ExpTxSeq {} Rej: {} " - "SRej1", - num_lost, tx_seq, p_fcrb->next_seq_expected, p_fcrb->rej_sent); + "process_i_frame() Lost: {} tx_seq:{} ExpTxSeq {} Rej: {} " + "SRej1", + num_lost, tx_seq, p_fcrb->next_seq_expected, p_fcrb->rej_sent); p_buf->layer_specific = tx_seq; fixed_queue_enqueue(p_fcrb->srej_rcv_hold_q, p_buf); } else { log::warn( - "process_i_frame() CID: 0x{:04x} frame dropped in Srej Sent " - "next_srej:{} hold_q.count:{} win_sz:{}", - p_ccb->local_cid, next_srej, - fixed_queue_length(p_fcrb->srej_rcv_hold_q), - p_ccb->our_cfg.fcr.tx_win_sz); + "process_i_frame() CID: 0x{:04x} frame dropped in Srej Sent " + "next_srej:{} hold_q.count:{} win_sz:{}", + p_ccb->local_cid, next_srej, fixed_queue_length(p_fcrb->srej_rcv_hold_q), + p_ccb->our_cfg.fcr.tx_win_sz); p_fcrb->rej_after_srej = true; osi_free(p_buf); } } else if (p_fcrb->rej_sent) { log::warn( - "process_i_frame() CID: 0x{:04x} Lost: {} tx_seq:{} ExpTxSeq {} " - " Rej: 1 SRej: {}", - p_ccb->local_cid, num_lost, tx_seq, p_fcrb->next_seq_expected, - p_fcrb->srej_sent); + "process_i_frame() CID: 0x{:04x} Lost: {} tx_seq:{} ExpTxSeq {} " + " Rej: 1 SRej: {}", + p_ccb->local_cid, num_lost, tx_seq, p_fcrb->next_seq_expected, p_fcrb->srej_sent); /* If REJ sent, just drop the frame */ osi_free(p_buf); } else { - log::verbose( - "process_i_frame() CID: 0x{:04x} tx_seq:{} ExpTxSeq {} Rej: {}", - p_ccb->local_cid, tx_seq, p_fcrb->next_seq_expected, - p_fcrb->rej_sent); + log::verbose("process_i_frame() CID: 0x{:04x} tx_seq:{} ExpTxSeq {} Rej: {}", + p_ccb->local_cid, tx_seq, p_fcrb->next_seq_expected, p_fcrb->rej_sent); /* If only one lost, we will send SREJ, otherwise we will send REJ */ if (num_lost > 1) { @@ -1088,10 +1070,9 @@ static void process_i_frame(tL2C_CCB* p_ccb, BT_HDR* p_buf, uint16_t ctrl_word, } else { if (!fixed_queue_is_empty(p_fcrb->srej_rcv_hold_q)) { log::error( - "process_i_frame() CID: 0x{:04x} sending SREJ tx_seq:{} " - "hold_q.count:{}", - p_ccb->local_cid, tx_seq, - fixed_queue_length(p_fcrb->srej_rcv_hold_q)); + "process_i_frame() CID: 0x{:04x} sending SREJ tx_seq:{} " + "hold_q.count:{}", + p_ccb->local_cid, tx_seq, fixed_queue_length(p_fcrb->srej_rcv_hold_q)); } p_buf->layer_specific = tx_seq; fixed_queue_enqueue(p_fcrb->srej_rcv_hold_q, p_buf); @@ -1104,8 +1085,7 @@ static void process_i_frame(tL2C_CCB* p_ccb, BT_HDR* p_buf, uint16_t ctrl_word, return; } - /* Seq number is the next expected. Clear possible reject exception in case it - * occured */ + /* Seq number is the next expected. Clear possible reject exception in case it occurred */ p_fcrb->rej_sent = p_fcrb->srej_sent = false; /* Adjust the next_seq, so that if the upper layer sends more data in the @@ -1115,18 +1095,18 @@ static void process_i_frame(tL2C_CCB* p_ccb, BT_HDR* p_buf, uint16_t ctrl_word, /* If any SAR problem in eRTM mode, spec says disconnect. */ if (!do_sar_reassembly(p_ccb, p_buf, ctrl_word)) { - log::warn("process_i_frame() CID: 0x{:04x} reassembly failed", - p_ccb->local_cid); + log::warn("process_i_frame() CID: 0x{:04x} reassembly failed", p_ccb->local_cid); l2cu_disconnect_chnl(p_ccb); return; } /* RR optimization - if peer can still send us more, then start an ACK timer */ - num_to_ack = (p_fcrb->next_seq_expected - p_fcrb->last_ack_sent) & - L2CAP_FCR_SEQ_MODULO; + num_to_ack = (p_fcrb->next_seq_expected - p_fcrb->last_ack_sent) & L2CAP_FCR_SEQ_MODULO; - if (num_to_ack < p_ccb->fcrb.max_held_acks) delay_ack = true; + if (num_to_ack < p_ccb->fcrb.max_held_acks) { + delay_ack = true; + } /* We should neve never ack frame if we are not in OPEN state */ if ((num_to_ack != 0) && p_ccb->in_use && (p_ccb->chnl_state == CST_OPEN)) { @@ -1138,8 +1118,7 @@ static void process_i_frame(tL2C_CCB* p_ccb, BT_HDR* p_buf, uint16_t ctrl_word, alarm_set_on_mloop(p_ccb->fcrb.ack_timer, L2CAP_FCR_ACK_TIMEOUT_MS, l2c_fcrb_ack_timer_timeout, p_ccb); } - } else if ((fixed_queue_is_empty(p_ccb->xmit_hold_q) || - l2c_fcr_is_flow_controlled(p_ccb)) && + } else if ((fixed_queue_is_empty(p_ccb->xmit_hold_q) || l2c_fcr_is_flow_controlled(p_ccb)) && fixed_queue_is_empty(p_ccb->fcrb.srej_rcv_hold_q)) { l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_RR, 0); } @@ -1155,8 +1134,7 @@ static void process_i_frame(tL2C_CCB* p_ccb, BT_HDR* p_buf, uint16_t ctrl_word, * Returns true if all OK, else false * ******************************************************************************/ -static bool do_sar_reassembly(tL2C_CCB* p_ccb, BT_HDR* p_buf, - uint16_t ctrl_word) { +static bool do_sar_reassembly(tL2C_CCB* p_ccb, BT_HDR* p_buf, uint16_t ctrl_word) { log::assert_that(p_ccb != NULL, "assert failed: p_ccb != NULL"); log::assert_that(p_buf != NULL, "assert failed: p_buf != NULL"); @@ -1169,15 +1147,14 @@ static bool do_sar_reassembly(tL2C_CCB* p_ccb, BT_HDR* p_buf, if ((sar_type == L2CAP_FCR_UNSEG_SDU) || (sar_type == L2CAP_FCR_START_SDU)) { if (p_fcrb->p_rx_sdu != NULL) { log::warn( - "SAR - got unexpected unsegmented or start SDU Expected len: {} " - "Got so far: {}", - p_fcrb->rx_sdu_len, p_fcrb->p_rx_sdu->len); + "SAR - got unexpected unsegmented or start SDU Expected len: {} " + "Got so far: {}", + p_fcrb->rx_sdu_len, p_fcrb->p_rx_sdu->len); packet_ok = false; } /* Check the length of the packet */ - if ((sar_type == L2CAP_FCR_START_SDU) && - (p_buf->len < L2CAP_SDU_LEN_OVERHEAD)) { + if ((sar_type == L2CAP_FCR_START_SDU) && (p_buf->len < L2CAP_SDU_LEN_OVERHEAD)) { log::warn("SAR start packet too short: {}", p_buf->len); packet_ok = false; } @@ -1199,12 +1176,11 @@ static bool do_sar_reassembly(tL2C_CCB* p_ccb, BT_HDR* p_buf, p_buf->len -= 2; if (p_fcrb->rx_sdu_len > p_ccb->max_rx_mtu) { - log::warn("SAR - SDU len: {} larger than MTU: {}", p_fcrb->rx_sdu_len, - p_ccb->max_rx_mtu); + log::warn("SAR - SDU len: {} larger than MTU: {}", p_fcrb->rx_sdu_len, p_ccb->max_rx_mtu); packet_ok = false; } else { - p_fcrb->p_rx_sdu = (BT_HDR*)osi_malloc( - BT_HDR_SIZE + OBX_BUF_MIN_OFFSET + p_fcrb->rx_sdu_len); + p_fcrb->p_rx_sdu = + (BT_HDR*)osi_malloc(BT_HDR_SIZE + OBX_BUF_MIN_OFFSET + p_fcrb->rx_sdu_len); p_fcrb->p_rx_sdu->offset = OBX_BUF_MIN_OFFSET; p_fcrb->p_rx_sdu->len = 0; } @@ -1212,18 +1188,17 @@ static bool do_sar_reassembly(tL2C_CCB* p_ccb, BT_HDR* p_buf, if (packet_ok) { if ((p_fcrb->p_rx_sdu->len + p_buf->len) > p_fcrb->rx_sdu_len) { - log::error("SAR - SDU len exceeded Type: {} Lengths: {} {} {}", - sar_type, p_fcrb->p_rx_sdu->len, p_buf->len, - p_fcrb->rx_sdu_len); + log::error("SAR - SDU len exceeded Type: {} Lengths: {} {} {}", sar_type, + p_fcrb->p_rx_sdu->len, p_buf->len, p_fcrb->rx_sdu_len); packet_ok = false; } else if ((sar_type == L2CAP_FCR_END_SDU) && ((p_fcrb->p_rx_sdu->len + p_buf->len) != p_fcrb->rx_sdu_len)) { - log::warn("SAR - SDU end rcvd but SDU incomplete: {} {} {}", - p_fcrb->p_rx_sdu->len, p_buf->len, p_fcrb->rx_sdu_len); + log::warn("SAR - SDU end rcvd but SDU incomplete: {} {} {}", p_fcrb->p_rx_sdu->len, + p_buf->len, p_fcrb->rx_sdu_len); packet_ok = false; } else { memcpy(((uint8_t*)(p_fcrb->p_rx_sdu + 1)) + p_fcrb->p_rx_sdu->offset + - p_fcrb->p_rx_sdu->len, + p_fcrb->p_rx_sdu->len, p, p_buf->len); p_fcrb->p_rx_sdu->len += p_buf->len; @@ -1243,18 +1218,17 @@ static bool do_sar_reassembly(tL2C_CCB* p_ccb, BT_HDR* p_buf, osi_free(p_buf); } else if (p_buf != NULL) { if (p_ccb->local_cid < L2CAP_BASE_APPL_CID && - (p_ccb->local_cid >= L2CAP_FIRST_FIXED_CHNL && - p_ccb->local_cid <= L2CAP_LAST_FIXED_CHNL)) { - if (l2cb.fixed_reg[p_ccb->local_cid - L2CAP_FIRST_FIXED_CHNL] - .pL2CA_FixedData_Cb) - (*l2cb.fixed_reg[p_ccb->local_cid - L2CAP_FIRST_FIXED_CHNL] - .pL2CA_FixedData_Cb)(p_ccb->local_cid, - p_ccb->p_lcb->remote_bd_addr, p_buf); - } else + (p_ccb->local_cid >= L2CAP_FIRST_FIXED_CHNL && p_ccb->local_cid <= L2CAP_LAST_FIXED_CHNL)) { + if (l2cb.fixed_reg[p_ccb->local_cid - L2CAP_FIRST_FIXED_CHNL].pL2CA_FixedData_Cb) { + (*l2cb.fixed_reg[p_ccb->local_cid - L2CAP_FIRST_FIXED_CHNL].pL2CA_FixedData_Cb)( + p_ccb->local_cid, p_ccb->p_lcb->remote_bd_addr, p_buf); + } + } else { l2c_csm_execute(p_ccb, L2CEVT_L2CAP_DATA, p_buf); + } } - return (packet_ok); + return packet_ok; } /******************************************************************************* @@ -1278,14 +1252,13 @@ static bool retransmit_i_frames(tL2C_CCB* p_ccb, uint8_t tx_seq) { (p_ccb->peer_cfg.fcr.max_transmit != 0) && (p_ccb->fcrb.num_tries >= p_ccb->peer_cfg.fcr.max_transmit)) { log::verbose( - "Max Tries Exceeded: (last_acq: {} CID: 0x{:04x} num_tries: {} " - "(max: {}) ack_q_count: {}", - p_ccb->fcrb.last_rx_ack, p_ccb->local_cid, p_ccb->fcrb.num_tries, - p_ccb->peer_cfg.fcr.max_transmit, - fixed_queue_length(p_ccb->fcrb.waiting_for_ack_q)); + "Max Tries Exceeded: (last_acq: {} CID: 0x{:04x} num_tries: {} " + "(max: {}) ack_q_count: {}", + p_ccb->fcrb.last_rx_ack, p_ccb->local_cid, p_ccb->fcrb.num_tries, + p_ccb->peer_cfg.fcr.max_transmit, fixed_queue_length(p_ccb->fcrb.waiting_for_ack_q)); l2cu_disconnect_chnl(p_ccb); - return (false); + return false; } /* tx_seq indicates whether to retransmit a specific sequence or all (if == @@ -1298,7 +1271,7 @@ static bool retransmit_i_frames(tL2C_CCB* p_ccb, uint8_t tx_seq) { } if (tx_seq != L2C_FCR_RETX_ALL_PKTS) { /* If sending only one, the sequence number tells us which one. Look for it. - */ + */ if (list_ack != NULL) { for (; node_ack != list_end(list_ack); node_ack = list_next(node_ack)) { p_buf = (BT_HDR*)list_node(node_ack); @@ -1307,20 +1280,20 @@ static bool retransmit_i_frames(tL2C_CCB* p_ccb, uint8_t tx_seq) { STREAM_TO_UINT16(ctrl_word, p); - buf_seq = - (ctrl_word & L2CAP_FCR_TX_SEQ_BITS) >> L2CAP_FCR_TX_SEQ_BITS_SHIFT; + buf_seq = (ctrl_word & L2CAP_FCR_TX_SEQ_BITS) >> L2CAP_FCR_TX_SEQ_BITS_SHIFT; - log::verbose("retransmit_i_frames() cur seq: {} looking for: {}", - buf_seq, tx_seq); + log::verbose("retransmit_i_frames() cur seq: {} looking for: {}", buf_seq, tx_seq); - if (tx_seq == buf_seq) break; + if (tx_seq == buf_seq) { + break; + } } } if (!p_buf) { log::error("retransmit_i_frames() UNKNOWN seq: {} q_count: {}", tx_seq, fixed_queue_length(p_ccb->fcrb.waiting_for_ack_q)); - return (true); + return true; } } else { // Iterate though list and flush the amount requested from @@ -1338,10 +1311,13 @@ static bool retransmit_i_frames(tL2C_CCB* p_ccb, uint8_t tx_seq) { } /* Also flush our retransmission queue */ - while (!fixed_queue_is_empty(p_ccb->fcrb.retrans_q)) + while (!fixed_queue_is_empty(p_ccb->fcrb.retrans_q)) { osi_free(fixed_queue_try_dequeue(p_ccb->fcrb.retrans_q)); + } - if (list_ack != NULL) node_ack = list_begin(list_ack); + if (list_ack != NULL) { + node_ack = list_begin(list_ack); + } } if (list_ack != NULL) { @@ -1356,7 +1332,9 @@ static bool retransmit_i_frames(tL2C_CCB* p_ccb, uint8_t tx_seq) { fixed_queue_enqueue(p_ccb->fcrb.retrans_q, p_buf2); } - if ((tx_seq != L2C_FCR_RETX_ALL_PKTS) || (p_buf2 == NULL)) break; + if ((tx_seq != L2C_FCR_RETX_ALL_PKTS) || (p_buf2 == NULL)) { + break; + } } } @@ -1367,7 +1345,7 @@ static bool retransmit_i_frames(tL2C_CCB* p_ccb, uint8_t tx_seq) { l2c_fcr_start_timer(p_ccb); } - return (true); + return true; } /******************************************************************************* @@ -1379,20 +1357,19 @@ static bool retransmit_i_frames(tL2C_CCB* p_ccb, uint8_t tx_seq) { * Returns pointer to buffer with segment or NULL * ******************************************************************************/ -BT_HDR* l2c_fcr_get_next_xmit_sdu_seg(tL2C_CCB* p_ccb, - uint16_t max_packet_length) { +BT_HDR* l2c_fcr_get_next_xmit_sdu_seg(tL2C_CCB* p_ccb, uint16_t max_packet_length) { log::assert_that(p_ccb != NULL, "assert failed: p_ccb != NULL"); - bool first_seg = false, /* The segment is the first part of data */ - mid_seg = false, /* The segment is the middle part of data */ - last_seg = false; /* The segment is the last part of data */ + bool first_seg = false, /* The segment is the first part of data */ + mid_seg = false, /* The segment is the middle part of data */ + last_seg = false; /* The segment is the last part of data */ uint16_t sdu_len = 0; BT_HDR *p_buf, *p_xmit; uint8_t* p; uint16_t max_pdu = p_ccb->tx_mps /* Needed? - L2CAP_MAX_HEADER_FCS*/; /* If there is anything in the retransmit queue, that goes first - */ + */ p_buf = (BT_HDR*)fixed_queue_try_dequeue(p_ccb->fcrb.retrans_q); if (p_buf != NULL) { /* Update Rx Seq and FCS if we acked some packets while this one was queued @@ -1401,7 +1378,7 @@ BT_HDR* l2c_fcr_get_next_xmit_sdu_seg(tL2C_CCB* p_ccb, p_buf->event = p_ccb->local_cid; - return (p_buf); + return p_buf; } /* For BD/EDR controller, max_packet_length is set to 0 */ @@ -1420,12 +1397,12 @@ BT_HDR* l2c_fcr_get_next_xmit_sdu_seg(tL2C_CCB* p_ccb, if (p_buf->event == 0) { first_seg = true; sdu_len = p_buf->len; - } else + } else { mid_seg = true; + } /* Get a new buffer and copy the data that can be sent in a PDU */ - p_xmit = l2c_fcr_clone_buf(p_buf, L2CAP_MIN_OFFSET + L2CAP_SDU_LEN_OFFSET, - max_pdu); + p_xmit = l2c_fcr_clone_buf(p_buf, L2CAP_MIN_OFFSET + L2CAP_SDU_LEN_OFFSET, max_pdu); if (p_xmit != NULL) { p_buf->event = p_ccb->local_cid; @@ -1439,15 +1416,16 @@ BT_HDR* l2c_fcr_get_next_xmit_sdu_seg(tL2C_CCB* p_ccb, } else /* Should never happen if the application has configured buffers correctly */ { - log::error("L2CAP - cannot get buffer for segmentation, max_pdu: {}", - max_pdu); - return (NULL); + log::error("L2CAP - cannot get buffer for segmentation, max_pdu: {}", max_pdu); + return NULL; } } else /* Use the original buffer if no segmentation, or the last segment */ { p_xmit = (BT_HDR*)fixed_queue_try_dequeue(p_ccb->xmit_hold_q); - if (p_xmit->event != 0) last_seg = true; + if (p_xmit->event != 0) { + last_seg = true; + } p_xmit->event = p_ccb->local_cid; } @@ -1481,30 +1459,29 @@ BT_HDR* l2c_fcr_get_next_xmit_sdu_seg(tL2C_CCB* p_ccb, p_xmit->layer_specific |= L2CAP_FCR_START_SDU; first_seg = false; - } else if (mid_seg) + } else if (mid_seg) { p_xmit->layer_specific |= L2CAP_FCR_CONT_SDU; - else if (last_seg) + } else if (last_seg) { p_xmit->layer_specific |= L2CAP_FCR_END_SDU; - else + } else { p_xmit->layer_specific |= L2CAP_FCR_UNSEG_SDU; + } prepare_I_frame(p_ccb, p_xmit, false); if (p_ccb->peer_cfg.fcr.mode == L2CAP_FCR_ERTM_MODE) { - BT_HDR* p_wack = - l2c_fcr_clone_buf(p_xmit, HCI_DATA_PREAMBLE_SIZE, p_xmit->len); + BT_HDR* p_wack = l2c_fcr_clone_buf(p_xmit, HCI_DATA_PREAMBLE_SIZE, p_xmit->len); if (!p_wack) { - log::error( - "L2CAP - no buffer for xmit cloning, CID: 0x{:04x} Length: {}", - p_ccb->local_cid, p_xmit->len); + log::error("L2CAP - no buffer for xmit cloning, CID: 0x{:04x} Length: {}", p_ccb->local_cid, + p_xmit->len); /* We will not save the FCS in case we reconfigure and change options */ p_xmit->len -= L2CAP_FCS_LEN; /* Pretend we sent it and it got lost */ fixed_queue_enqueue(p_ccb->fcrb.waiting_for_ack_q, p_xmit); - return (NULL); + return NULL; } else { /* We will not save the FCS in case we reconfigure and change options */ p_wack->len -= L2CAP_FCS_LEN; @@ -1512,31 +1489,27 @@ BT_HDR* l2c_fcr_get_next_xmit_sdu_seg(tL2C_CCB* p_ccb, p_wack->layer_specific = p_xmit->layer_specific; fixed_queue_enqueue(p_ccb->fcrb.waiting_for_ack_q, p_wack); } - } - return (p_xmit); + return p_xmit; } /** Get the next PDU to transmit for LE connection oriented channel. Returns * pointer to buffer with PDU. |last_piece_of_sdu| will be set to true, if * returned PDU is last piece from this SDU.*/ -BT_HDR* l2c_lcc_get_next_xmit_sdu_seg(tL2C_CCB* p_ccb, - bool* last_piece_of_sdu) { +BT_HDR* l2c_lcc_get_next_xmit_sdu_seg(tL2C_CCB* p_ccb, bool* last_piece_of_sdu) { uint16_t max_pdu = p_ccb->peer_conn_cfg.mps - 4 /* Length and CID */; BT_HDR* p_buf = (BT_HDR*)fixed_queue_try_peek_first(p_ccb->xmit_hold_q); bool first_pdu = (p_buf->event == 0) ? true : false; - uint16_t no_of_bytes_to_send = std::min( - p_buf->len, - (uint16_t)(first_pdu ? (max_pdu - L2CAP_LCC_SDU_LENGTH) : max_pdu)); + uint16_t no_of_bytes_to_send = + std::min(p_buf->len, (uint16_t)(first_pdu ? (max_pdu - L2CAP_LCC_SDU_LENGTH) : max_pdu)); bool last_pdu = (no_of_bytes_to_send == p_buf->len); /* Get a new buffer and copy the data that can be sent in a PDU */ - BT_HDR* p_xmit = - l2c_fcr_clone_buf(p_buf, first_pdu ? L2CAP_LCC_OFFSET : L2CAP_MIN_OFFSET, - no_of_bytes_to_send); + BT_HDR* p_xmit = l2c_fcr_clone_buf(p_buf, first_pdu ? L2CAP_LCC_OFFSET : L2CAP_MIN_OFFSET, + no_of_bytes_to_send); p_buf->event = p_ccb->local_cid; p_xmit->event = p_ccb->local_cid; @@ -1554,7 +1527,9 @@ BT_HDR* l2c_lcc_get_next_xmit_sdu_seg(tL2C_CCB* p_ccb, /* copy PBF setting */ p_xmit->layer_specific = p_buf->layer_specific; - if (last_piece_of_sdu) *last_piece_of_sdu = last_pdu; + if (last_piece_of_sdu) { + *last_piece_of_sdu = last_pdu; + } if (last_pdu) { p_buf = (BT_HDR*)fixed_queue_try_dequeue(p_ccb->xmit_hold_q); @@ -1571,7 +1546,7 @@ BT_HDR* l2c_lcc_get_next_xmit_sdu_seg(tL2C_CCB* p_ccb, /* Note: if FCS has to be included then the length is recalculated later */ UINT16_TO_STREAM(p, p_xmit->len - L2CAP_PKT_OVERHEAD); UINT16_TO_STREAM(p, p_ccb->remote_cid); - return (p_xmit); + return p_xmit; } /******************************************************************************* @@ -1637,9 +1612,8 @@ void l2c_fcr_adj_monitor_retran_timeout(tL2C_CCB* p_ccb) { p_ccb->our_cfg.fcr.rtrans_tout = 0; } - log::verbose( - "l2c_fcr_adj_monitor_retran_timeout: mon_tout:{}, rtrans_tout:{}", - p_ccb->our_cfg.fcr.mon_tout, p_ccb->our_cfg.fcr.rtrans_tout); + log::verbose("l2c_fcr_adj_monitor_retran_timeout: mon_tout:{}, rtrans_tout:{}", + p_ccb->our_cfg.fcr.mon_tout, p_ccb->our_cfg.fcr.rtrans_tout); } } /******************************************************************************* @@ -1668,8 +1642,8 @@ void l2c_fcr_adj_our_rsp_options(tL2C_CCB* p_ccb, tL2CAP_CFG_INFO* p_cfg) { * adjust it. For now, respond with our own tx_wnd_sz. */ /* Note: peer is not guaranteed to obey our adjustment */ if (p_ccb->peer_cfg.fcr.tx_win_sz > p_ccb->our_cfg.fcr.tx_win_sz) { - log::verbose("adjusting requested tx_win_sz from {} to {}", - p_ccb->peer_cfg.fcr.tx_win_sz, p_ccb->our_cfg.fcr.tx_win_sz); + log::verbose("adjusting requested tx_win_sz from {} to {}", p_ccb->peer_cfg.fcr.tx_win_sz, + p_ccb->our_cfg.fcr.tx_win_sz); p_ccb->peer_cfg.fcr.tx_win_sz = p_ccb->our_cfg.fcr.tx_win_sz; } @@ -1703,8 +1677,9 @@ bool l2c_fcr_renegotiate_chan(tL2C_CCB* p_ccb, tL2CAP_CFG_INFO* p_cfg) { /* Skip if this is a reconfiguration from OPEN STATE or if FCR is not returned */ - if (!p_cfg->fcr_present || (p_ccb->config_done & RECONFIG_FLAG)) - return (false); + if (!p_cfg->fcr_present || (p_ccb->config_done & RECONFIG_FLAG)) { + return false; + } /* Only retry if there are more channel options to try */ if (p_cfg->result == L2CAP_CFG_UNACCEPTABLE_PARAMS) { @@ -1750,21 +1725,21 @@ bool l2c_fcr_renegotiate_chan(tL2C_CCB* p_ccb, tL2CAP_CFG_INFO* p_cfg) { l2cu_process_our_cfg_req(p_ccb, &p_ccb->our_cfg); l2cu_send_peer_config_req(p_ccb, &p_ccb->our_cfg); - alarm_set_on_mloop(p_ccb->l2c_ccb_timer, L2CAP_CHNL_CFG_TIMEOUT_MS, - l2c_ccb_timer_timeout, p_ccb); - return (true); + alarm_set_on_mloop(p_ccb->l2c_ccb_timer, L2CAP_CHNL_CFG_TIMEOUT_MS, l2c_ccb_timer_timeout, + p_ccb); + return true; } } } /* Disconnect if the channels do not match */ if (p_ccb->our_cfg.fcr.mode != peer_mode) { - log::warn("L2C CFG: Channels incompatible (local {}, peer {})", - p_ccb->our_cfg.fcr.mode, peer_mode); + log::warn("L2C CFG: Channels incompatible (local {}, peer {})", p_ccb->our_cfg.fcr.mode, + peer_mode); l2cu_disconnect_chnl(p_ccb); } - return (false); + return false; } /******************************************************************************* @@ -1785,14 +1760,13 @@ uint8_t l2c_fcr_process_peer_cfg_req(tL2C_CCB* p_ccb, tL2CAP_CFG_INFO* p_cfg) { uint16_t max_retrans_size; uint8_t fcr_ok = L2CAP_PEER_CFG_OK; - p_ccb->p_lcb->w4_info_rsp = - false; /* Handles T61x SonyEricsson Bug in Info Request */ + p_ccb->p_lcb->w4_info_rsp = false; /* Handles T61x SonyEricsson Bug in Info Request */ log::verbose( - "l2c_fcr_process_peer_cfg_req() CFG fcr_present:{} fcr.mode:{} CCB FCR " - "mode:{} preferred: {}", - p_cfg->fcr_present, p_cfg->fcr.mode, p_ccb->our_cfg.fcr.mode, - p_ccb->p_rcb->ertm_info.preferred_mode); + "l2c_fcr_process_peer_cfg_req() CFG fcr_present:{} fcr.mode:{} CCB FCR " + "mode:{} preferred: {}", + p_cfg->fcr_present, p_cfg->fcr.mode, p_ccb->our_cfg.fcr.mode, + p_ccb->p_rcb->ertm_info.preferred_mode); /* Need to negotiate if our modes are not the same */ if (p_cfg->fcr.mode != p_ccb->p_rcb->ertm_info.preferred_mode) { @@ -1816,8 +1790,7 @@ uint8_t l2c_fcr_process_peer_cfg_req(tL2C_CCB* p_ccb, tL2CAP_CFG_INFO* p_cfg) { p_cfg->fcr.mode = L2CAP_FCR_BASIC_MODE; p_cfg->fcr.max_transmit = p_cfg->fcr.tx_win_sz = 0; p_cfg->fcr.rtrans_tout = p_cfg->fcr.mon_tout = p_cfg->fcr.mps = 0; - p_ccb->our_cfg.fcr.rtrans_tout = p_ccb->our_cfg.fcr.mon_tout = - p_ccb->our_cfg.fcr.mps = 0; + p_ccb->our_cfg.fcr.rtrans_tout = p_ccb->our_cfg.fcr.mon_tout = p_ccb->our_cfg.fcr.mps = 0; fcr_ok = L2CAP_PEER_CFG_UNACCEPTABLE; } } @@ -1835,9 +1808,8 @@ uint8_t l2c_fcr_process_peer_cfg_req(tL2C_CCB* p_ccb, tL2CAP_CFG_INFO* p_cfg) { p_ccb->peer_cfg.fcs = p_cfg->fcs; } - max_retrans_size = BT_DEFAULT_BUFFER_SIZE - sizeof(BT_HDR) - - L2CAP_MIN_OFFSET - L2CAP_SDU_LEN_OFFSET - - L2CAP_FCS_LEN; + max_retrans_size = BT_DEFAULT_BUFFER_SIZE - sizeof(BT_HDR) - L2CAP_MIN_OFFSET - + L2CAP_SDU_LEN_OFFSET - L2CAP_FCS_LEN; /* Ensure the MPS is not bigger than the MTU */ if ((p_cfg->fcr.mps == 0) || (p_cfg->fcr.mps > p_ccb->peer_cfg.mtu)) { @@ -1847,8 +1819,7 @@ uint8_t l2c_fcr_process_peer_cfg_req(tL2C_CCB* p_ccb, tL2CAP_CFG_INFO* p_cfg) { /* Ensure the MPS is not bigger than our retransmission buffer */ if (p_cfg->fcr.mps > max_retrans_size) { - log::verbose("CFG: Overriding MPS to {} (orig {})", max_retrans_size, - p_cfg->fcr.mps); + log::verbose("CFG: Overriding MPS to {} (orig {})", max_retrans_size, p_cfg->fcr.mps); p_cfg->fcr.mps = max_retrans_size; p_ccb->out_cfg_fcr_present = true; @@ -1865,11 +1836,12 @@ uint8_t l2c_fcr_process_peer_cfg_req(tL2C_CCB* p_ccb, tL2CAP_CFG_INFO* p_cfg) { } else if (fcr_ok == L2CAP_PEER_CFG_UNACCEPTABLE) { /* Allow peer only one retry for mode */ - if (p_ccb->peer_cfg_already_rejected) + if (p_ccb->peer_cfg_already_rejected) { fcr_ok = L2CAP_PEER_CFG_DISCONNECT; - else + } else { p_ccb->peer_cfg_already_rejected = true; + } } - return (fcr_ok); + return fcr_ok; } diff --git a/system/stack/l2cap/l2c_int.h b/system/stack/l2cap/l2c_int.h index 3ca114b4d31..05dc9bcb540 100644 --- a/system/stack/l2cap/l2c_int.h +++ b/system/stack/l2cap/l2c_int.h @@ -70,7 +70,7 @@ constexpr uint16_t L2CAP_CREDIT_BASED_MIN_MPS = 64; /* Define the possible L2CAP channel states. The names of * the states may seem a bit strange, but they are taken from * the Bluetooth specification. -*/ + */ typedef enum { CST_CLOSED, /* Channel is in closed state */ CST_ORIG_W4_SEC_COMP, /* Originator waits security clearence */ @@ -100,7 +100,7 @@ inline std::string channel_state_text(const tL2C_CHNL_STATE& state) { } /* Define the possible L2CAP link states -*/ + */ typedef enum { LST_DISCONNECTED, LST_CONNECT_HOLDING, @@ -132,7 +132,7 @@ inline std::string link_state_text(const tL2C_LINK_STATE& state) { /* Define input events to the L2CAP link and channel state machines. The names * of the events may seem a bit strange, but they are taken from * the Bluetooth specification. -*/ + */ typedef enum : uint16_t { /* Lower layer */ L2CEVT_LP_CONNECT_CFM = 0, /* connect confirm */ @@ -179,17 +179,12 @@ typedef enum : uint16_t { L2CEVT_L2CA_SEND_FLOW_CONTROL_CREDIT = 35, /* Upper layer credit packet \ */ /* Peer credit based connection */ - L2CEVT_L2CAP_RECV_FLOW_CONTROL_CREDIT = 36, /* credit packet */ - L2CEVT_L2CAP_CREDIT_BASED_CONNECT_REQ = - 37, /* credit based connection request */ - L2CEVT_L2CAP_CREDIT_BASED_CONNECT_RSP = - 38, /* accepted credit based connection */ - L2CEVT_L2CAP_CREDIT_BASED_CONNECT_RSP_NEG = - 39, /* rejected credit based connection */ - L2CEVT_L2CAP_CREDIT_BASED_RECONFIG_REQ = - 40, /* credit based reconfig request*/ - L2CEVT_L2CAP_CREDIT_BASED_RECONFIG_RSP = - 41, /* credit based reconfig response */ + L2CEVT_L2CAP_RECV_FLOW_CONTROL_CREDIT = 36, /* credit packet */ + L2CEVT_L2CAP_CREDIT_BASED_CONNECT_REQ = 37, /* credit based connection request */ + L2CEVT_L2CAP_CREDIT_BASED_CONNECT_RSP = 38, /* accepted credit based connection */ + L2CEVT_L2CAP_CREDIT_BASED_CONNECT_RSP_NEG = 39, /* rejected credit based connection */ + L2CEVT_L2CAP_CREDIT_BASED_RECONFIG_REQ = 40, /* credit based reconfig request*/ + L2CEVT_L2CAP_CREDIT_BASED_RECONFIG_RSP = 41, /* credit based reconfig response */ /* Upper layer credit based connection */ L2CEVT_L2CA_CREDIT_BASED_CONNECT_REQ = 42, /* connect request */ @@ -235,12 +230,11 @@ struct tL2C_FCRB { bool send_f_rsp; /* We need to send an F-bit response */ - uint16_t rx_sdu_len; /* Length of the SDU being received */ - BT_HDR* p_rx_sdu; /* Buffer holding the SDU being received */ - fixed_queue_t* - waiting_for_ack_q; /* Buffers sent and waiting for peer to ack */ - fixed_queue_t* srej_rcv_hold_q; /* Buffers rcvd but held pending SREJ rsp */ - fixed_queue_t* retrans_q; /* Buffers being retransmitted */ + uint16_t rx_sdu_len; /* Length of the SDU being received */ + BT_HDR* p_rx_sdu; /* Buffer holding the SDU being received */ + fixed_queue_t* waiting_for_ack_q; /* Buffers sent and waiting for peer to ack */ + fixed_queue_t* srej_rcv_hold_q; /* Buffers rcvd but held pending SREJ rsp */ + fixed_queue_t* retrans_q; /* Buffers being retransmitted */ alarm_t* ack_timer; /* Timer delaying RR */ alarm_t* mon_retrans_timer; /* Timer Monitor or Retransmission */ @@ -277,37 +271,35 @@ struct tL2C_LCB; * blocks between the same two Bluetooth devices (i.e. on the same link). * Each CCB has unique local and remote CIDs. All channel control blocks on * the same physical link and are chained together. -*/ + */ struct tL2C_CCB { - bool in_use; /* true when in use, false when not */ - tL2C_CHNL_STATE chnl_state; /* Channel state */ - tL2CAP_LE_CFG_INFO - local_conn_cfg; /* Our config for ble conn oriented channel */ - tL2CAP_LE_CFG_INFO - peer_conn_cfg; /* Peer device config ble conn oriented channel */ - bool is_first_seg; /* Dtermine whether the received packet is the first - segment or not */ - BT_HDR* ble_sdu; /* Buffer for storing unassembled sdu*/ - uint16_t ble_sdu_length; /* Length of unassembled sdu length*/ - tL2C_CCB* p_next_ccb; /* Next CCB in the chain */ - tL2C_CCB* p_prev_ccb; /* Previous CCB in the chain */ - tL2C_LCB* p_lcb; /* Link this CCB is assigned to */ + bool in_use; /* true when in use, false when not */ + tL2C_CHNL_STATE chnl_state; /* Channel state */ + tL2CAP_LE_CFG_INFO local_conn_cfg; /* Our config for ble conn oriented channel */ + tL2CAP_LE_CFG_INFO peer_conn_cfg; /* Peer device config ble conn oriented channel */ + bool is_first_seg; /* Dtermine whether the received packet is the first + segment or not */ + BT_HDR* ble_sdu; /* Buffer for storing unassembled sdu*/ + uint16_t ble_sdu_length; /* Length of unassembled sdu length*/ + tL2C_CCB* p_next_ccb; /* Next CCB in the chain */ + tL2C_CCB* p_prev_ccb; /* Previous CCB in the chain */ + tL2C_LCB* p_lcb; /* Link this CCB is assigned to */ uint16_t local_cid; /* Local CID */ uint16_t remote_cid; /* Remote CID */ alarm_t* l2c_ccb_timer; /* CCB Timer Entry */ - tL2C_RCB* p_rcb; /* Registration CB for this Channel */ + tL2C_RCB* p_rcb; /* Registration CB for this Channel */ #define IB_CFG_DONE 0x01 #define OB_CFG_DONE 0x02 #define RECONFIG_FLAG 0x04 /* True after initial configuration */ - uint8_t config_done; /* Configuration flag word */ + uint8_t config_done; /* Configuration flag word */ uint16_t remote_config_rsp_result; /* The config rsp result from remote */ - uint8_t local_id; /* Transaction ID for local trans */ - uint8_t remote_id; /* Transaction ID for local */ + uint8_t local_id; /* Transaction ID for local trans */ + uint8_t remote_id; /* Transaction ID for local */ #define CCB_FLAG_NO_RETRY 0x01 /* no more retry */ #define CCB_FLAG_SENT_PENDING 0x02 /* already sent pending response */ @@ -315,8 +307,8 @@ struct tL2C_CCB { bool connection_initiator; /* true if we sent ConnectReq */ - tL2CAP_CFG_INFO our_cfg; /* Our saved configuration options */ - tL2CAP_CFG_INFO peer_cfg; /* Peer's saved configuration options */ + tL2CAP_CFG_INFO our_cfg; /* Our saved configuration options */ + tL2CAP_CFG_INFO peer_cfg; /* Peer's saved configuration options */ fixed_queue_t* xmit_hold_q; /* Transmit data hold queue */ bool cong_sent; /* Set when congested status sent */ @@ -333,8 +325,8 @@ struct tL2C_CCB { uint16_t max_rx_mtu; uint8_t fcr_cfg_tries; /* Max number of negotiation attempts */ bool peer_cfg_already_rejected; /* If mode rejected once, set to true */ - bool out_cfg_fcr_present; /* true if cfg response should include fcr options - */ + bool out_cfg_fcr_present; /* true if cfg response should include fcr options + */ bool is_flushable; /* true if channel is flushable */ @@ -373,17 +365,15 @@ struct tL2C_CCB { /*********************************************************************** * Define a queue of linked CCBs. -*/ + */ struct tL2C_CCB_Q { tL2C_CCB* p_first_ccb; /* The first channel in this queue */ tL2C_CCB* p_last_ccb; /* The last channel in this queue */ }; /* Round-Robin service for the same priority channels */ -#define L2CAP_NUM_CHNL_PRIORITY \ - 3 /* Total number of priority group (high, medium, low)*/ -#define L2CAP_CHNL_PRIORITY_WEIGHT \ - 5 /* weight per priority for burst transmission quota */ +#define L2CAP_NUM_CHNL_PRIORITY 3 /* Total number of priority group (high, medium, low)*/ +#define L2CAP_CHNL_PRIORITY_WEIGHT 5 /* weight per priority for burst transmission quota */ #define L2CAP_GET_PRIORITY_QUOTA(pri) \ ((L2CAP_NUM_CHNL_PRIORITY - (pri)) * L2CAP_CHNL_PRIORITY_WEIGHT) @@ -413,7 +403,7 @@ enum tCONN_UPDATE_MASK : uint8_t { /* Define a link control block. There is one link control block between * this device and any other device (i.e. BD ADDR). -*/ + */ struct tL2C_LCB { bool in_use; /* true when in use, false when not */ tL2C_LINK_STATE link_state; @@ -426,38 +416,36 @@ struct tL2C_LCB { // backwards compatibility we never do a link timeout. bool with_active_local_clients{false}; - private: +private: uint16_t handle_; /* The handle used with LM */ friend void l2cu_set_lcb_handle(tL2C_LCB& p_lcb, uint16_t handle); void SetHandle(uint16_t handle) { handle_ = handle; } - public: +public: uint16_t Handle() const { return handle_; } void InvalidateHandle() { handle_ = HCI_INVALID_HANDLE; } tL2C_CCB_Q ccb_queue; /* Queue of CCBs on this LCB */ - tL2C_CCB* p_pending_ccb; /* ccb of waiting channel during link disconnect */ - alarm_t* info_resp_timer; /* Timer entry for info resp timeout evt */ + tL2C_CCB* p_pending_ccb; /* ccb of waiting channel during link disconnect */ + alarm_t* info_resp_timer; /* Timer entry for info resp timeout evt */ RawAddress remote_bd_addr; /* The BD address of the remote */ - private: +private: tHCI_ROLE link_role_{HCI_ROLE_CENTRAL}; /* Central or peripheral */ - public: +public: tHCI_ROLE LinkRole() const { return link_role_; } bool IsLinkRoleCentral() const { return link_role_ == HCI_ROLE_CENTRAL; } - bool IsLinkRolePeripheral() const { - return link_role_ == HCI_ROLE_PERIPHERAL; - } + bool IsLinkRolePeripheral() const { return link_role_ == HCI_ROLE_PERIPHERAL; } void SetLinkRoleAsCentral() { link_role_ = HCI_ROLE_CENTRAL; } void SetLinkRoleAsPeripheral() { link_role_ = HCI_ROLE_PERIPHERAL; } - uint8_t signal_id; /* Signalling channel id */ - uint8_t cur_echo_id; /* Current id value for echo request */ - uint16_t idle_timeout; /* Idle timeout */ - private: - bool is_bonding_{false}; /* True - link active only for bonding */ - public: + uint8_t signal_id; /* Signalling channel id */ + uint8_t cur_echo_id; /* Current id value for echo request */ + uint16_t idle_timeout; /* Idle timeout */ +private: + bool is_bonding_{false}; /* True - link active only for bonding */ +public: bool IsBonding() const { return is_bonding_; } void SetBonding() { is_bonding_ = true; } void ResetBonding() { is_bonding_ = false; } @@ -465,24 +453,23 @@ struct tL2C_LCB { uint16_t link_xmit_quota; /* Num outstanding pkts allowed */ bool is_round_robin_scheduling() const { return link_xmit_quota == 0; } - uint16_t sent_not_acked; /* Num packets sent but not acked */ + uint16_t sent_not_acked; /* Num packets sent but not acked */ void update_outstanding_packets(uint16_t packets_acked) { - if (sent_not_acked > packets_acked) + if (sent_not_acked > packets_acked) { sent_not_acked -= packets_acked; - else + } else { sent_not_acked = 0; + } } - bool w4_info_rsp; /* true when info request is active */ - uint32_t peer_ext_fea; /* Peer's extended features mask */ - list_t* link_xmit_data_q; /* Link transmit data buffer queue */ + bool w4_info_rsp; /* true when info request is active */ + uint32_t peer_ext_fea; /* Peer's extended features mask */ + list_t* link_xmit_data_q; /* Link transmit data buffer queue */ uint8_t peer_chnl_mask[L2CAP_FIXED_CHNL_ARRAY_SIZE]; tL2CAP_PRIORITY acl_priority; - bool is_normal_priority() const { - return acl_priority == L2CAP_PRIORITY_NORMAL; - } + bool is_normal_priority() const { return acl_priority == L2CAP_PRIORITY_NORMAL; } bool is_high_priority() const { return acl_priority == L2CAP_PRIORITY_HIGH; } bool set_priority(tL2CAP_PRIORITY priority) { if (acl_priority != priority) { @@ -507,20 +494,18 @@ struct tL2C_LCB { tL2C_CCB* p_fixed_ccbs[L2CAP_NUM_FIXED_CHNLS]; - private: +private: tHCI_REASON disc_reason_{HCI_ERR_UNDEFINED}; - public: +public: tHCI_REASON DisconnectReason() const { return disc_reason_; } - void SetDisconnectReason(tHCI_REASON disc_reason) { - disc_reason_ = disc_reason; - } + void SetDisconnectReason(tHCI_REASON disc_reason) { disc_reason_ = disc_reason; } tBT_TRANSPORT transport; bool is_transport_br_edr() const { return transport == BT_TRANSPORT_BR_EDR; } bool is_transport_ble() const { return transport == BT_TRANSPORT_LE; } - uint16_t tx_data_len; /* tx data length used in data length extension */ + uint16_t tx_data_len; /* tx data length used in data length extension */ fixed_queue_t* le_sec_pending_q; /* LE coc channels waiting for security check completion */ uint8_t sec_act; @@ -580,7 +565,7 @@ struct tL2C_LCB { }; /* Define the L2CAP control structure -*/ + */ struct tL2C_CB { uint16_t controller_xmit_window; /* Total ACL window for all links */ @@ -590,13 +575,14 @@ struct tL2C_CB { return round_robin_unacked < round_robin_quota; } void update_outstanding_classic_packets(uint16_t num_packets_acked) { - if (round_robin_unacked > num_packets_acked) + if (round_robin_unacked > num_packets_acked) { round_robin_unacked -= num_packets_acked; - else + } else { round_robin_unacked = 0; + } } - bool check_round_robin; /* Do a round robin check */ + bool check_round_robin; /* Do a round robin check */ bool is_cong_cback_context; @@ -611,8 +597,8 @@ struct tL2C_CB { uint16_t num_lm_acl_bufs; /* # of ACL buffers on controller */ uint16_t idle_timeout; /* Idle timeout */ - tL2C_LCB* p_cur_hcit_lcb; /* Current HCI Transport buffer */ - uint16_t num_used_lcbs; /* Number of active link control blocks */ + tL2C_LCB* p_cur_hcit_lcb; /* Current HCI Transport buffer */ + uint16_t num_used_lcbs; /* Number of active link control blocks */ uint16_t non_flushable_pbf; /* L2CAP_PKT_START_NON_FLUSHABLE if controller supports */ @@ -622,45 +608,45 @@ struct tL2C_CB { uint32_t test_info_resp; /* Conformance testing needs a dynamic response */ #endif - tL2CAP_FIXED_CHNL_REG - fixed_reg[L2CAP_NUM_FIXED_CHNLS]; /* Reg info for fixed channels */ + tL2CAP_FIXED_CHNL_REG fixed_reg[L2CAP_NUM_FIXED_CHNLS]; /* Reg info for fixed channels */ - uint16_t num_ble_links_active; /* Number of LE links active */ - uint16_t controller_le_xmit_window; /* Total ACL window for all links */ + uint16_t num_ble_links_active; /* Number of LE links active */ + uint16_t controller_le_xmit_window; /* Total ACL window for all links */ tL2C_BLE_FIXED_CHNLS_MASK l2c_ble_fixed_chnls_mask; // LE fixed channels mask - uint16_t num_lm_ble_bufs; /* # of ACL buffers on controller */ - uint16_t ble_round_robin_quota; /* Round-robin link quota */ - uint16_t ble_round_robin_unacked; /* Round-robin unacked */ + uint16_t num_lm_ble_bufs; /* # of ACL buffers on controller */ + uint16_t ble_round_robin_quota; /* Round-robin link quota */ + uint16_t ble_round_robin_unacked; /* Round-robin unacked */ bool is_ble_round_robin_quota_available() const { return ble_round_robin_unacked < ble_round_robin_quota; } void update_outstanding_le_packets(uint16_t num_packets_acked) { - if (ble_round_robin_unacked > num_packets_acked) + if (ble_round_robin_unacked > num_packets_acked) { ble_round_robin_unacked -= num_packets_acked; - else + } else { ble_round_robin_unacked = 0; + } } - bool ble_check_round_robin; /* Do a round robin check */ + bool ble_check_round_robin; /* Do a round robin check */ tL2C_RCB ble_rcb_pool[BLE_MAX_L2CAP_CLIENTS]; /* Registration info pool */ - uint16_t le_dyn_psm; /* Next LE dynamic PSM value to try to assign */ + uint16_t le_dyn_psm; /* Next LE dynamic PSM value to try to assign */ bool le_dyn_psm_assigned[LE_DYNAMIC_PSM_RANGE]; /* Table of assigned LE PSM */ }; /* Define a structure that contains the information about a connection. * This structure is used to pass between functions, and not all the * fields will always be filled in. -*/ + */ struct tL2C_CONN_INFO { - RawAddress bd_addr; /* Remote BD address */ - uint8_t status; /* Connection status */ - uint16_t psm; /* PSM of the connection */ - uint16_t l2cap_result; /* L2CAP result */ - uint16_t l2cap_status; /* L2CAP status */ - uint16_t remote_cid; /* Remote CID */ + RawAddress bd_addr; /* Remote BD address */ + uint8_t status; /* Connection status */ + uint16_t psm; /* PSM of the connection */ + uint16_t l2cap_result; /* L2CAP result */ + uint16_t l2cap_status; /* L2CAP status */ + uint16_t remote_cid; /* Remote CID */ std::vector lcids; /* Used when credit based is used*/ - uint16_t peer_mtu; /* Peer MTU */ + uint16_t peer_mtu; /* Peer MTU */ }; struct tL2C_AVDT_CHANNEL_INFO { @@ -680,21 +666,21 @@ struct tL2C_TX_COMPLETE_CB_INFO { }; /* The offset in a buffer that L2CAP will use when building commands. -*/ + */ #define L2CAP_SEND_CMD_OFFSET 0 /* Number of ACL buffers to use for high priority channel -*/ + */ #define L2CAP_HIGH_PRI_MIN_XMIT_QUOTA_A (L2CAP_HIGH_PRI_MIN_XMIT_QUOTA) /* L2CAP global data *********************************** -*/ + */ extern tL2C_CB l2cb; /* Functions provided by l2c_main.cc *********************************** -*/ + */ void l2c_receive_hold_timer_timeout(void* data); void l2c_ccb_timer_timeout(void* data); @@ -703,11 +689,9 @@ void l2c_fcrb_ack_timer_timeout(void* data); tL2CAP_DW_RESULT l2c_data_write(uint16_t cid, BT_HDR* p_data, uint16_t flag); void l2c_acl_flush(uint16_t handle); -tL2C_LCB* l2cu_allocate_lcb(const RawAddress& p_bd_addr, bool is_bonding, - tBT_TRANSPORT transport); +tL2C_LCB* l2cu_allocate_lcb(const RawAddress& p_bd_addr, bool is_bonding, tBT_TRANSPORT transport); void l2cu_release_lcb(tL2C_LCB* p_lcb); -tL2C_LCB* l2cu_find_lcb_by_bd_addr(const RawAddress& p_bd_addr, - tBT_TRANSPORT transport); +tL2C_LCB* l2cu_find_lcb_by_bd_addr(const RawAddress& p_bd_addr, tBT_TRANSPORT transport); tL2C_LCB* l2cu_find_lcb_by_handle(uint16_t handle); bool l2cu_set_acl_priority(const RawAddress& bd_addr, tL2CAP_PRIORITY priority, @@ -718,30 +702,26 @@ void l2cu_enqueue_ccb(tL2C_CCB* p_ccb); void l2cu_dequeue_ccb(tL2C_CCB* p_ccb); void l2cu_change_pri_ccb(tL2C_CCB* p_ccb, tL2CAP_CHNL_PRIORITY priority); -tL2C_CCB* l2cu_allocate_ccb(tL2C_LCB* p_lcb, uint16_t cid, - bool is_eatt = false); +tL2C_CCB* l2cu_allocate_ccb(tL2C_LCB* p_lcb, uint16_t cid, bool is_eatt = false); void l2cu_release_ccb(tL2C_CCB* p_ccb); tL2C_CCB* l2cu_find_ccb_by_cid(tL2C_LCB* p_lcb, uint16_t local_cid); tL2C_CCB* l2cu_find_ccb_by_remote_cid(tL2C_LCB* p_lcb, uint16_t remote_cid); bool l2c_is_cmd_rejected(uint8_t cmd_code, uint8_t id, tL2C_LCB* p_lcb); -void l2cu_send_peer_cmd_reject(tL2C_LCB* p_lcb, uint16_t reason, uint8_t rem_id, - uint16_t p1, uint16_t p2); +void l2cu_send_peer_cmd_reject(tL2C_LCB* p_lcb, uint16_t reason, uint8_t rem_id, uint16_t p1, + uint16_t p2); void l2cu_send_peer_connect_req(tL2C_CCB* p_ccb); -void l2cu_send_peer_connect_rsp(tL2C_CCB* p_ccb, uint16_t result, - uint16_t status); +void l2cu_send_peer_connect_rsp(tL2C_CCB* p_ccb, uint16_t result, uint16_t status); void l2cu_send_peer_config_req(tL2C_CCB* p_ccb, tL2CAP_CFG_INFO* p_cfg); void l2cu_send_peer_config_rsp(tL2C_CCB* p_ccb, tL2CAP_CFG_INFO* p_cfg); -void l2cu_send_peer_config_rej(tL2C_CCB* p_ccb, uint8_t* p_data, - uint16_t data_len, uint16_t rej_len); +void l2cu_send_peer_config_rej(tL2C_CCB* p_ccb, uint8_t* p_data, uint16_t data_len, + uint16_t rej_len); void l2cu_send_peer_disc_req(tL2C_CCB* p_ccb); -void l2cu_send_peer_disc_rsp(tL2C_LCB* p_lcb, uint8_t remote_id, - uint16_t local_cid, uint16_t remote_cid); -void l2cu_send_peer_echo_rsp(tL2C_LCB* p_lcb, uint8_t id, uint8_t* p_data, - uint16_t data_len); +void l2cu_send_peer_disc_rsp(tL2C_LCB* p_lcb, uint8_t remote_id, uint16_t local_cid, + uint16_t remote_cid); +void l2cu_send_peer_echo_rsp(tL2C_LCB* p_lcb, uint8_t id, uint8_t* p_data, uint16_t data_len); void l2cu_send_peer_info_rsp(tL2C_LCB* p_lcb, uint8_t id, uint16_t info_type); -void l2cu_reject_connection(tL2C_LCB* p_lcb, uint16_t remote_cid, - uint8_t rem_id, uint16_t result); +void l2cu_reject_connection(tL2C_LCB* p_lcb, uint16_t remote_cid, uint8_t rem_id, uint16_t result); void l2cu_send_peer_info_req(tL2C_LCB* p_lcb, uint16_t info_type); void l2cu_set_acl_hci_header(BT_HDR* p_buf, tL2C_CCB* p_ccb); void l2cu_check_channel_congestion(tL2C_CCB* p_ccb); @@ -749,33 +729,24 @@ void l2cu_disconnect_chnl(tL2C_CCB* p_ccb); void l2cu_tx_complete(tL2C_TX_COMPLETE_CB_INFO* p_cbi); -void l2cu_send_peer_ble_par_req(tL2C_LCB* p_lcb, uint16_t min_int, - uint16_t max_int, uint16_t latency, - uint16_t timeout); -void l2cu_send_peer_ble_par_rsp(tL2C_LCB* p_lcb, uint16_t reason, - uint8_t rem_id); -void l2cu_reject_ble_connection(tL2C_CCB* p_ccb, uint8_t rem_id, - uint16_t result); -void l2cu_reject_credit_based_conn_req(tL2C_LCB* p_lcb, uint8_t rem_id, - uint8_t num_of_channels, +void l2cu_send_peer_ble_par_req(tL2C_LCB* p_lcb, uint16_t min_int, uint16_t max_int, + uint16_t latency, uint16_t timeout); +void l2cu_send_peer_ble_par_rsp(tL2C_LCB* p_lcb, uint16_t reason, uint8_t rem_id); +void l2cu_reject_ble_connection(tL2C_CCB* p_ccb, uint8_t rem_id, uint16_t result); +void l2cu_reject_credit_based_conn_req(tL2C_LCB* p_lcb, uint8_t rem_id, uint8_t num_of_channels, uint16_t result); -void l2cu_reject_ble_coc_connection(tL2C_LCB* p_lcb, uint8_t rem_id, - uint16_t result); +void l2cu_reject_ble_coc_connection(tL2C_LCB* p_lcb, uint8_t rem_id, uint16_t result); void l2cu_send_peer_ble_credit_based_conn_res(tL2C_CCB* p_ccb, uint16_t result); -void l2cu_send_peer_credit_based_conn_res(tL2C_CCB* p_ccb, - std::vector& accepted_lcids, +void l2cu_send_peer_credit_based_conn_res(tL2C_CCB* p_ccb, std::vector& accepted_lcids, uint16_t result); void l2cu_send_peer_ble_credit_based_conn_req(tL2C_CCB* p_ccb); void l2cu_send_peer_credit_based_conn_req(tL2C_CCB* p_ccb); -void l2cu_send_ble_reconfig_rsp(tL2C_LCB* p_lcb, uint8_t rem_id, - uint16_t result); -void l2cu_send_credit_based_reconfig_req(tL2C_CCB* p_ccb, - tL2CAP_LE_CFG_INFO* p_data); +void l2cu_send_ble_reconfig_rsp(tL2C_LCB* p_lcb, uint8_t rem_id, uint16_t result); +void l2cu_send_credit_based_reconfig_req(tL2C_CCB* p_ccb, tL2CAP_LE_CFG_INFO* p_data); -void l2cu_send_peer_ble_flow_control_credit(tL2C_CCB* p_ccb, - uint16_t credit_value); +void l2cu_send_peer_ble_flow_control_credit(tL2C_CCB* p_ccb, uint16_t credit_value); void l2cu_send_peer_ble_credit_based_disconn_req(tL2C_CCB* p_ccb); bool l2cu_initialize_fixed_ccb(tL2C_LCB* p_lcb, uint16_t fixed_cid); @@ -786,7 +757,7 @@ uint16_t le_result_to_l2c_conn(uint16_t result); /* Functions provided for Broadcom Aware *************************************** -*/ + */ tL2C_RCB* l2cu_allocate_rcb(uint16_t psm); tL2C_RCB* l2cu_find_rcb_by_psm(uint16_t psm); @@ -810,15 +781,14 @@ void l2cu_adjust_out_mps(tL2C_CCB* p_ccb); /* Functions provided by l2c_link.cc *********************************** -*/ + */ void l2c_link_timeout(tL2C_LCB* p_lcb); void l2c_info_resp_timer_timeout(void* data); -void l2c_link_check_send_pkts(tL2C_LCB* p_lcb, uint16_t local_cid, - BT_HDR* p_buf); +void l2c_link_check_send_pkts(tL2C_LCB* p_lcb, uint16_t local_cid, BT_HDR* p_buf); void l2c_link_adjust_allocation(void); -void l2c_link_sec_comp(RawAddress p_bda, tBT_TRANSPORT transport, - void* p_ref_data, tBTM_STATUS status); +void l2c_link_sec_comp(RawAddress p_bda, tBT_TRANSPORT transport, void* p_ref_data, + tBTM_STATUS status); void l2c_link_adjust_chnl_allocation(void); #if (L2CAP_CONFORMANCE_TESTING == TRUE) @@ -828,25 +798,22 @@ void l2cu_set_info_rsp_mask(uint32_t mask); /* Functions provided by l2c_csm.cc *********************************** -*/ + */ void l2c_csm_execute(tL2C_CCB* p_ccb, tL2CEVT event, void* p_data); void l2c_enqueue_peer_data(tL2C_CCB* p_ccb, BT_HDR* p_buf); /* Functions provided by l2c_fcr.cc *********************************** -*/ + */ void l2c_fcr_cleanup(tL2C_CCB* p_ccb); void l2c_fcr_proc_pdu(tL2C_CCB* p_ccb, BT_HDR* p_buf); void l2c_fcr_proc_tout(tL2C_CCB* p_ccb); void l2c_fcr_proc_ack_tout(tL2C_CCB* p_ccb); -void l2c_fcr_send_S_frame(tL2C_CCB* p_ccb, uint16_t function_code, - uint16_t pf_bit); -BT_HDR* l2c_fcr_clone_buf(BT_HDR* p_buf, uint16_t new_offset, - uint16_t no_of_bytes); +void l2c_fcr_send_S_frame(tL2C_CCB* p_ccb, uint16_t function_code, uint16_t pf_bit); +BT_HDR* l2c_fcr_clone_buf(BT_HDR* p_buf, uint16_t new_offset, uint16_t no_of_bytes); bool l2c_fcr_is_flow_controlled(tL2C_CCB* p_ccb); -BT_HDR* l2c_fcr_get_next_xmit_sdu_seg(tL2C_CCB* p_ccb, - uint16_t max_packet_length); +BT_HDR* l2c_fcr_get_next_xmit_sdu_seg(tL2C_CCB* p_ccb, uint16_t max_packet_length); void l2c_fcr_start_timer(tL2C_CCB* p_ccb); void l2c_lcc_proc_pdu(tL2C_CCB* p_ccb, BT_HDR* p_buf); BT_HDR* l2c_lcc_get_next_xmit_sdu_seg(tL2C_CCB* p_ccb, bool* last_piece_of_sdu); @@ -862,7 +829,7 @@ void l2c_fcr_stop_timer(tL2C_CCB* p_ccb); /* Functions provided by l2c_ble.cc *********************************** -*/ + */ bool l2cble_create_conn(tL2C_LCB* p_lcb); void l2cble_process_sig_cmd(tL2C_LCB* p_lcb, uint8_t* p, uint16_t pkt_len); void l2c_ble_link_adjust_allocation(void); @@ -871,19 +838,17 @@ void l2cble_credit_based_conn_req(tL2C_CCB* p_ccb); void l2cble_credit_based_conn_res(tL2C_CCB* p_ccb, uint16_t result); void l2cble_send_peer_disc_req(tL2C_CCB* p_ccb); void l2cble_send_flow_control_credit(tL2C_CCB* p_ccb, uint16_t credit_value); -tL2CAP_LE_RESULT_CODE l2ble_sec_access_req(const RawAddress& bd_addr, - uint16_t psm, bool is_originator, - tBTM_SEC_CALLBACK* p_callback, +tL2CAP_LE_RESULT_CODE l2ble_sec_access_req(const RawAddress& bd_addr, uint16_t psm, + bool is_originator, tBTM_SEC_CALLBACK* p_callback, void* p_ref_data); void l2cble_update_data_length(tL2C_LCB* p_lcb); void l2cu_process_fixed_disc_cback(tL2C_LCB* p_lcb); -void l2cble_process_subrate_change_evt(uint16_t handle, uint8_t status, - uint16_t subrate_factor, - uint16_t peripheral_latency, - uint16_t cont_num, uint16_t timeout); +void l2cble_process_subrate_change_evt(uint16_t handle, uint8_t status, uint16_t subrate_factor, + uint16_t peripheral_latency, uint16_t cont_num, + uint16_t timeout); namespace fmt { template <> diff --git a/system/stack/l2cap/l2c_link.cc b/system/stack/l2cap/l2c_link.cc index 835789b622c..2da58a77daa 100644 --- a/system/stack/l2cap/l2c_link.cc +++ b/system/stack/l2cap/l2c_link.cc @@ -51,21 +51,17 @@ using namespace bluetooth; extern tBTM_CB btm_cb; bool BTM_ReadPowerMode(const RawAddress& remote_bda, tBTM_PM_MODE* p_mode); -tBTM_STATUS btm_sec_disconnect(uint16_t handle, tHCI_STATUS reason, - std::string); -void btm_acl_created(const RawAddress& bda, uint16_t hci_handle, - uint8_t link_role, tBT_TRANSPORT transport); +tBTM_STATUS btm_sec_disconnect(uint16_t handle, tHCI_STATUS reason, std::string); +void btm_acl_created(const RawAddress& bda, uint16_t hci_handle, uint8_t link_role, + tBT_TRANSPORT transport); void btm_acl_removed(uint16_t handle); void btm_ble_decrement_link_topology_mask(uint8_t link_role); void btm_sco_acl_removed(const RawAddress* bda); -static void l2c_link_send_to_lower(tL2C_LCB* p_lcb, BT_HDR* p_buf, - tL2C_TX_COMPLETE_CB_INFO* p_cbi); -static BT_HDR* l2cu_get_next_buffer_to_send(tL2C_LCB* p_lcb, - tL2C_TX_COMPLETE_CB_INFO* p_cbi); +static void l2c_link_send_to_lower(tL2C_LCB* p_lcb, BT_HDR* p_buf, tL2C_TX_COMPLETE_CB_INFO* p_cbi); +static BT_HDR* l2cu_get_next_buffer_to_send(tL2C_LCB* p_lcb, tL2C_TX_COMPLETE_CB_INFO* p_cbi); -void l2c_link_hci_conn_comp(tHCI_STATUS status, uint16_t handle, - const RawAddress& p_bda) { +void l2c_link_hci_conn_comp(tHCI_STATUS status, uint16_t handle, const RawAddress& p_bda) { tL2C_CONN_INFO ci; tL2C_LCB* p_lcb; tL2C_CCB* p_ccb; @@ -89,16 +85,14 @@ void l2c_link_hci_conn_comp(tHCI_STATUS status, uint16_t handle, p_lcb->link_state = LST_CONNECTING; } - if ((p_lcb->link_state == LST_CONNECTED) && - (status == HCI_ERR_CONNECTION_EXISTS)) { + if ((p_lcb->link_state == LST_CONNECTED) && (status == HCI_ERR_CONNECTION_EXISTS)) { log::warn("Connection already exists handle:0x{:04x}", handle); return; } else if (p_lcb->link_state != LST_CONNECTING) { log::error( - "Link received unexpected connection complete state:{} status:{} " - "handle:0x{:04x}", - link_state_text(p_lcb->link_state), hci_error_code_text(status), - p_lcb->Handle()); + "Link received unexpected connection complete state:{} status:{} " + "handle:0x{:04x}", + link_state_text(p_lcb->link_state), hci_error_code_text(status), p_lcb->Handle()); if (status != HCI_SUCCESS) { log::error("Disconnecting..."); l2c_link_hci_disc_comp(p_lcb->Handle(), status); @@ -118,27 +112,26 @@ void l2c_link_hci_conn_comp(tHCI_STATUS status, uint16_t handle, if (p_lcb->IsBonding()) { log::debug("Link is dedicated bonding handle:0x{:04x}", p_lcb->Handle()); - if (l2cu_start_post_bond_timer(handle)) return; + if (l2cu_start_post_bond_timer(handle)) { + return; + } } alarm_cancel(p_lcb->l2c_lcb_timer); /* For all channels, send the event through their FSMs */ - for (p_ccb = p_lcb->ccb_queue.p_first_ccb; p_ccb; - p_ccb = p_ccb->p_next_ccb) { + for (p_ccb = p_lcb->ccb_queue.p_first_ccb; p_ccb; p_ccb = p_ccb->p_next_ccb) { l2c_csm_execute(p_ccb, L2CEVT_LP_CONNECT_CFM, &ci); } if (!p_lcb->ccb_queue.p_first_ccb) { uint64_t timeout_ms = L2CAP_LINK_STARTUP_TOUT * 1000; - alarm_set_on_mloop(p_lcb->l2c_lcb_timer, timeout_ms, - l2c_lcb_timer_timeout, p_lcb); + alarm_set_on_mloop(p_lcb->l2c_lcb_timer, timeout_ms, l2c_lcb_timer_timeout, p_lcb); } } /* Max number of acl connections. */ /* If there's an lcb disconnecting set this one to holding */ - else if ((ci.status == HCI_ERR_MAX_NUM_OF_CONNECTIONS) && - l2cu_lcb_disconnecting()) { + else if ((ci.status == HCI_ERR_MAX_NUM_OF_CONNECTIONS) && l2cu_lcb_disconnecting()) { log::warn("Delaying connection as reached max number of links:{}", HCI_ERR_MAX_NUM_OF_CONNECTIONS); p_lcb->link_state = LST_CONNECT_HOLDING; @@ -161,9 +154,9 @@ void l2c_link_hci_conn_comp(tHCI_STATUS status, uint16_t handle, hci_error_code_text(status)); p_lcb->SetDisconnectReason(status); /* Release the LCB */ - if (p_lcb->ccb_queue.p_first_ccb == NULL) + if (p_lcb->ccb_queue.p_first_ccb == NULL) { l2cu_release_lcb(p_lcb); - else /* there are any CCBs remaining */ + } else /* there are any CCBs remaining */ { if (ci.status == HCI_ERR_CONNECTION_EXISTS) { /* we are in collision situation, wait for connecttion request from @@ -186,15 +179,15 @@ void l2c_link_hci_conn_comp(tHCI_STATUS status, uint16_t handle, * Returns void * ******************************************************************************/ -void l2c_link_sec_comp(RawAddress p_bda, tBT_TRANSPORT transport, - void* p_ref_data, tBTM_STATUS status) { +void l2c_link_sec_comp(RawAddress p_bda, tBT_TRANSPORT transport, void* p_ref_data, + tBTM_STATUS status) { tL2C_CONN_INFO ci; tL2C_LCB* p_lcb; tL2C_CCB* p_ccb; tL2C_CCB* p_next_ccb; - log::debug("btm_status={}, BD_ADDR={}, transport={}", btm_status_text(status), - p_bda, bt_transport_text(transport)); + log::debug("btm_status={}, BD_ADDR={}, transport={}", btm_status_text(status), p_bda, + bt_transport_text(transport)); if (status == BTM_SUCCESS_NO_SECURITY) { status = BTM_SUCCESS; @@ -234,8 +227,7 @@ void l2c_link_sec_comp(RawAddress p_bda, tBT_TRANSPORT transport, case BTM_DELAY_CHECK: /* start a timer - encryption change not received before L2CAP connect * req */ - alarm_set_on_mloop(p_ccb->l2c_ccb_timer, - L2CAP_DELAY_CHECK_SM4_TIMEOUT_MS, + alarm_set_on_mloop(p_ccb->l2c_ccb_timer, L2CAP_DELAY_CHECK_SM4_TIMEOUT_MS, l2c_ccb_timer_timeout, p_ccb); return; @@ -257,8 +249,7 @@ void l2c_link_sec_comp(RawAddress p_bda, tBT_TRANSPORT transport, case BTM_DELAY_CHECK: /* start a timer - encryption change not received before L2CAP * connect req */ - alarm_set_on_mloop(p_ccb->l2c_ccb_timer, - L2CAP_DELAY_CHECK_SM4_TIMEOUT_MS, + alarm_set_on_mloop(p_ccb->l2c_ccb_timer, L2CAP_DELAY_CHECK_SM4_TIMEOUT_MS, l2c_ccb_timer_timeout, p_ccb); return; @@ -282,15 +273,17 @@ void l2c_link_sec_comp(RawAddress p_bda, tBT_TRANSPORT transport, *******************************************************************************/ static void l2c_link_iot_store_disc_reason(RawAddress& bda, uint8_t reason) { const char* disc_keys[] = { - IOT_CONF_KEY_GAP_DISC_CONNTIMEOUT_COUNT, + IOT_CONF_KEY_GAP_DISC_CONNTIMEOUT_COUNT, }; const uint8_t disc_reasons[] = { - HCI_ERR_CONNECTION_TOUT, + HCI_ERR_CONNECTION_TOUT, }; int i = 0; int num = sizeof(disc_keys) / sizeof(disc_keys[0]); - if (reason == (uint8_t)-1) return; + if (reason == (uint8_t)-1) { + return; + } DEVICE_IOT_CONFIG_ADDR_INT_ADD_ONE(bda, IOT_CONF_KEY_GAP_DISC_COUNT); for (i = 0; i < num; i++) { @@ -329,8 +322,9 @@ bool l2c_link_hci_disc_comp(uint16_t handle, tHCI_REASON reason) { p_lcb->link_state = LST_DISCONNECTING; /* Check for BLE and handle that differently */ - if (p_lcb->transport == BT_TRANSPORT_LE) + if (p_lcb->transport == BT_TRANSPORT_LE) { btm_ble_decrement_link_topology_mask(p_lcb->LinkRole()); + } /* Link is disconnected. For all channels, send the event through */ /* their FSMs. The CCBs should remove themselves from the LCB */ for (p_ccb = p_lcb->ccb_queue.p_first_ccb; p_ccb;) { @@ -348,9 +342,10 @@ bool l2c_link_hci_disc_comp(uint16_t handle, tHCI_REASON reason) { p_ccb = pn; } - if (p_lcb->transport == BT_TRANSPORT_BR_EDR) + if (p_lcb->transport == BT_TRANSPORT_BR_EDR) { /* Tell SCO management to drop any SCOs on this ACL */ btm_sco_acl_removed(&p_lcb->remote_bd_addr); + } /* If waiting for disconnect and reconnect is pending start the reconnect now @@ -361,8 +356,7 @@ bool l2c_link_hci_disc_comp(uint16_t handle, tHCI_REASON reason) { log::debug("l2c_link_hci_disc_comp: Restarting pending ACL request"); /* Release any held buffers */ while (!list_is_empty(p_lcb->link_xmit_data_q)) { - BT_HDR* p_buf = - static_cast(list_front(p_lcb->link_xmit_data_q)); + BT_HDR* p_buf = static_cast(list_front(p_lcb->link_xmit_data_q)); list_remove(p_lcb->link_xmit_data_q, p_buf); osi_free(p_buf); } @@ -376,14 +370,13 @@ bool l2c_link_hci_disc_comp(uint16_t handle, tHCI_REASON reason) { here */ int xx; for (xx = 0; xx < L2CAP_NUM_FIXED_CHNLS; xx++) { - if (p_lcb->p_fixed_ccbs[xx] && - p_lcb->p_fixed_ccbs[xx] != p_lcb->p_pending_ccb) { + if (p_lcb->p_fixed_ccbs[xx] && p_lcb->p_fixed_ccbs[xx] != p_lcb->p_pending_ccb) { l2cu_release_ccb(p_lcb->p_fixed_ccbs[xx]); p_lcb->p_fixed_ccbs[xx] = NULL; - (*l2cb.fixed_reg[xx].pL2CA_FixedConn_Cb)( - xx + L2CAP_FIRST_FIXED_CHNL, p_lcb->remote_bd_addr, false, - p_lcb->DisconnectReason(), p_lcb->transport); + (*l2cb.fixed_reg[xx].pL2CA_FixedConn_Cb)(xx + L2CAP_FIRST_FIXED_CHNL, + p_lcb->remote_bd_addr, false, + p_lcb->DisconnectReason(), p_lcb->transport); } } /* Cleanup connection state to avoid race conditions because @@ -392,8 +385,9 @@ bool l2c_link_hci_disc_comp(uint16_t handle, tHCI_REASON reason) { p_lcb->InvalidateHandle(); } if (p_lcb->transport == BT_TRANSPORT_LE) { - if (l2cu_create_conn_le(p_lcb)) + if (l2cu_create_conn_le(p_lcb)) { lcb_is_free = false; /* still using this lcb */ + } } else { l2cu_create_conn_br_edr(p_lcb); lcb_is_free = false; /* still using this lcb */ @@ -403,12 +397,13 @@ bool l2c_link_hci_disc_comp(uint16_t handle, tHCI_REASON reason) { p_lcb->p_pending_ccb = NULL; /* Release the LCB */ - if (lcb_is_free) l2cu_release_lcb(p_lcb); + if (lcb_is_free) { + l2cu_release_lcb(p_lcb); + } } /* Now that we have a free acl connection, see if any lcbs are pending */ - if (lcb_is_free && - ((p_lcb = l2cu_find_lcb_by_state(LST_CONNECT_HOLDING)) != NULL)) { + if (lcb_is_free && ((p_lcb = l2cu_find_lcb_by_state(LST_CONNECT_HOLDING)) != NULL)) { /* we found one-- create a connection */ l2cu_create_conn_br_edr(p_lcb); } @@ -434,10 +429,8 @@ void l2c_link_timeout(tL2C_LCB* p_lcb) { /* If link was connecting or disconnecting, clear all channels and drop the * LCB */ - if ((p_lcb->link_state == LST_CONNECTING_WAIT_SWITCH) || - (p_lcb->link_state == LST_CONNECTING) || - (p_lcb->link_state == LST_CONNECT_HOLDING) || - (p_lcb->link_state == LST_DISCONNECTING)) { + if ((p_lcb->link_state == LST_CONNECTING_WAIT_SWITCH) || (p_lcb->link_state == LST_CONNECTING) || + (p_lcb->link_state == LST_CONNECT_HOLDING) || (p_lcb->link_state == LST_DISCONNECTING)) { p_lcb->p_pending_ccb = NULL; /* For all channels, send a disconnect indication event through */ @@ -462,9 +455,8 @@ void l2c_link_timeout(tL2C_LCB* p_lcb) { bool start_timeout = true; log::warn("TODO: Remove this callback into bcm_sec_disconnect"); - rc = btm_sec_disconnect( - p_lcb->Handle(), HCI_ERR_PEER_USER, - "stack::l2cap::l2c_link::l2c_link_timeout All channels closed"); + rc = btm_sec_disconnect(p_lcb->Handle(), HCI_ERR_PEER_USER, + "stack::l2cap::l2c_link::l2c_link_timeout All channels closed"); if (rc == BTM_CMD_STORED) { /* Security Manager will take care of disconnecting, state will be @@ -495,8 +487,7 @@ void l2c_link_timeout(tL2C_LCB* p_lcb) { } if (start_timeout) { - alarm_set_on_mloop(p_lcb->l2c_lcb_timer, timeout_ms, - l2c_lcb_timer_timeout, p_lcb); + alarm_set_on_mloop(p_lcb->l2c_lcb_timer, timeout_ms, l2c_lcb_timer_timeout, p_lcb); } } else { /* Check in case we were flow controlled */ @@ -523,12 +514,10 @@ void l2c_info_resp_timer_timeout(void* data) { * allowed */ if (p_lcb->w4_info_rsp) { /* If waiting for security complete, restart the info response timer */ - for (p_ccb = p_lcb->ccb_queue.p_first_ccb; p_ccb; - p_ccb = p_ccb->p_next_ccb) { + for (p_ccb = p_lcb->ccb_queue.p_first_ccb; p_ccb; p_ccb = p_ccb->p_next_ccb) { if ((p_ccb->chnl_state == CST_ORIG_W4_SEC_COMP) || (p_ccb->chnl_state == CST_TERM_W4_SEC_COMP)) { - alarm_set_on_mloop(p_lcb->info_resp_timer, - L2CAP_WAIT_INFO_RSP_TIMEOUT_MS, + alarm_set_on_mloop(p_lcb->info_resp_timer, L2CAP_WAIT_INFO_RSP_TIMEOUT_MS, l2c_info_resp_timer_timeout, p_lcb); return; } @@ -537,15 +526,13 @@ void l2c_info_resp_timer_timeout(void* data) { p_lcb->w4_info_rsp = false; /* If link is in process of being brought up */ - if ((p_lcb->link_state != LST_DISCONNECTED) && - (p_lcb->link_state != LST_DISCONNECTING)) { + if ((p_lcb->link_state != LST_DISCONNECTED) && (p_lcb->link_state != LST_DISCONNECTING)) { /* Notify active channels that peer info is finished */ if (p_lcb->ccb_queue.p_first_ccb) { ci.status = HCI_SUCCESS; ci.bd_addr = p_lcb->remote_bd_addr; - for (p_ccb = p_lcb->ccb_queue.p_first_ccb; p_ccb; - p_ccb = p_ccb->p_next_ccb) { + for (p_ccb = p_lcb->ccb_queue.p_first_ccb; p_ccb; p_ccb = p_ccb->p_next_ccb) { l2c_csm_execute(p_ccb, L2CEVT_L2CAP_INFO_RSP, &ci); } } @@ -576,8 +563,7 @@ void l2c_link_adjust_allocation(void) { uint16_t num_hipri_links = 0; uint16_t controller_xmit_quota = l2cb.num_lm_acl_bufs; uint16_t high_pri_link_quota = L2CAP_HIGH_PRI_MIN_XMIT_QUOTA_A; - bool is_share_buffer = - (l2cb.num_lm_ble_bufs == L2C_DEF_NUM_BLE_BUF_SHARED) ? true : false; + bool is_share_buffer = (l2cb.num_lm_ble_bufs == L2C_DEF_NUM_BLE_BUF_SHARED) ? true : false; /* If no links active, reset buffer quotas and controller buffers */ if (l2cb.num_used_lcbs == 0) { @@ -588,25 +574,24 @@ void l2c_link_adjust_allocation(void) { /* First, count the links */ for (yy = 0, p_lcb = &l2cb.lcb_pool[0]; yy < MAX_L2CAP_LINKS; yy++, p_lcb++) { - if (p_lcb->in_use && - (is_share_buffer || p_lcb->transport != BT_TRANSPORT_LE)) { - if (p_lcb->acl_priority == L2CAP_PRIORITY_HIGH) + if (p_lcb->in_use && (is_share_buffer || p_lcb->transport != BT_TRANSPORT_LE)) { + if (p_lcb->acl_priority == L2CAP_PRIORITY_HIGH) { num_hipri_links++; - else + } else { num_lowpri_links++; + } } } /* now adjust high priority link quota */ low_quota = num_lowpri_links ? 1 : 0; - while ((num_hipri_links * high_pri_link_quota + low_quota) > - controller_xmit_quota) + while ((num_hipri_links * high_pri_link_quota + low_quota) > controller_xmit_quota) { high_pri_link_quota--; + } /* Work out the xmit quota and buffer quota high and low priorities */ hi_quota = num_hipri_links * high_pri_link_quota; - low_quota = - (hi_quota < controller_xmit_quota) ? controller_xmit_quota - hi_quota : 1; + low_quota = (hi_quota < controller_xmit_quota) ? controller_xmit_quota - hi_quota : 1; /* Work out and save the HCI xmit quota for each low priority link */ @@ -630,14 +615,13 @@ void l2c_link_adjust_allocation(void) { } log::debug( - "l2c_link_adjust_allocation num_hipri: {} num_lowpri: {} low_quota: " - "{} round_robin_quota: {} qq: {}", - num_hipri_links, num_lowpri_links, low_quota, l2cb.round_robin_quota, qq); + "l2c_link_adjust_allocation num_hipri: {} num_lowpri: {} low_quota: " + "{} round_robin_quota: {} qq: {}", + num_hipri_links, num_lowpri_links, low_quota, l2cb.round_robin_quota, qq); /* Now, assign the quotas to each link */ for (yy = 0, p_lcb = &l2cb.lcb_pool[0]; yy < MAX_L2CAP_LINKS; yy++, p_lcb++) { - if (p_lcb->in_use && - (is_share_buffer || p_lcb->transport != BT_TRANSPORT_LE)) { + if (p_lcb->in_use && (is_share_buffer || p_lcb->transport != BT_TRANSPORT_LE)) { if (p_lcb->acl_priority == L2CAP_PRIORITY_HIGH) { p_lcb->link_xmit_quota = high_pri_link_quota; } else { @@ -646,8 +630,9 @@ void l2c_link_adjust_allocation(void) { /* if sent_not_acked is added into round_robin_unacked then don't add it * again */ /* l2cap keeps updating sent_not_acked for exiting from round robin */ - if ((p_lcb->link_xmit_quota > 0) && (qq == 0)) + if ((p_lcb->link_xmit_quota > 0) && (qq == 0)) { l2cb.round_robin_unacked += p_lcb->sent_not_acked; + } p_lcb->link_xmit_quota = qq; if (qq_remainder > 0) { @@ -656,9 +641,8 @@ void l2c_link_adjust_allocation(void) { } } - log::debug( - "l2c_link_adjust_allocation LCB {} Priority: {} XmitQuota: {}", yy, - p_lcb->acl_priority, p_lcb->link_xmit_quota); + log::debug("l2c_link_adjust_allocation LCB {} Priority: {} XmitQuota: {}", yy, + p_lcb->acl_priority, p_lcb->link_xmit_quota); log::debug("SentNotAcked: {} RRUnacked: {}", p_lcb->sent_not_acked, l2cb.round_robin_unacked); @@ -666,11 +650,9 @@ void l2c_link_adjust_allocation(void) { /* There is a special case where we have readjusted the link quotas and */ /* this link may have sent anything but some other link sent packets so */ /* so we may need a timer to kick off this link's transmissions. */ - if ((p_lcb->link_state == LST_CONNECTED) && - (!list_is_empty(p_lcb->link_xmit_data_q)) && + if ((p_lcb->link_state == LST_CONNECTED) && (!list_is_empty(p_lcb->link_xmit_data_q)) && (p_lcb->sent_not_acked < p_lcb->link_xmit_quota)) { - alarm_set_on_mloop(p_lcb->l2c_lcb_timer, - L2CAP_LINK_FLOW_CONTROL_TIMEOUT_MS, + alarm_set_on_mloop(p_lcb->l2c_lcb_timer, L2CAP_LINK_FLOW_CONTROL_TIMEOUT_MS, l2c_lcb_timer_timeout, p_lcb); } } @@ -696,15 +678,17 @@ void l2c_link_adjust_chnl_allocation(void) { for (uint8_t xx = 0; xx < MAX_L2CAP_CHANNELS; xx++) { tL2C_CCB* p_ccb = l2cb.ccb_pool + xx; - if (!p_ccb->in_use) continue; + if (!p_ccb->in_use) { + continue; + } tL2CAP_CHNL_DATA_RATE data_rate = p_ccb->tx_data_rate + p_ccb->rx_data_rate; p_ccb->buff_quota = L2CAP_CBB_DEFAULT_DATA_RATE_BUFF_QUOTA * data_rate; log::debug( - "CID:0x{:04x} FCR Mode:{} Priority:{} TxDataRate:{} RxDataRate:{} " - "Quota:{}", - p_ccb->local_cid, p_ccb->peer_cfg.fcr.mode, p_ccb->ccb_priority, - p_ccb->tx_data_rate, p_ccb->rx_data_rate, p_ccb->buff_quota); + "CID:0x{:04x} FCR Mode:{} Priority:{} TxDataRate:{} RxDataRate:{} " + "Quota:{}", + p_ccb->local_cid, p_ccb->peer_cfg.fcr.mode, p_ccb->ccb_priority, p_ccb->tx_data_rate, + p_ccb->rx_data_rate, p_ccb->buff_quota); /* quota may be change so check congestion */ l2cu_check_channel_congestion(p_ccb); @@ -726,8 +710,7 @@ void l2c_link_init(const uint16_t acl_buffer_count_classic) { * Returns void * ******************************************************************************/ -void l2c_link_role_changed(const RawAddress* bd_addr, tHCI_ROLE new_role, - tHCI_STATUS hci_status) { +void l2c_link_role_changed(const RawAddress* bd_addr, tHCI_ROLE new_role, tHCI_STATUS hci_status) { /* Make sure not called from HCI Command Status (bd_addr and new_role are * invalid) */ if (bd_addr != nullptr) { @@ -741,8 +724,9 @@ void l2c_link_role_changed(const RawAddress* bd_addr, tHCI_ROLE new_role, } /* Reset high priority link if needed */ - if (hci_status == HCI_SUCCESS) + if (hci_status == HCI_SUCCESS) { l2cu_set_acl_priority(*bd_addr, p_lcb->acl_priority, true); + } } } @@ -791,13 +775,14 @@ static bool l2c_link_check_power_mode(tL2C_LCB* p_lcb) { bool need_to_active = false; // Return false as LM modes are applicable for BREDR transport - if (p_lcb->is_transport_ble()) return false; + if (p_lcb->is_transport_ble()) { + return false; + } /* * We only switch park to active only if we have unsent packets */ if (list_is_empty(p_lcb->link_xmit_data_q)) { - for (tL2C_CCB* p_ccb = p_lcb->ccb_queue.p_first_ccb; p_ccb; - p_ccb = p_ccb->p_next_ccb) { + for (tL2C_CCB* p_ccb = p_lcb->ccb_queue.p_first_ccb; p_ccb; p_ccb = p_ccb->p_next_ccb) { if (!fixed_queue_is_empty(p_ccb->xmit_hold_q)) { need_to_active = true; break; @@ -832,8 +817,7 @@ static bool l2c_link_check_power_mode(tL2C_LCB* p_lcb) { * Returns void * ******************************************************************************/ -void l2c_link_check_send_pkts(tL2C_LCB* p_lcb, uint16_t local_cid, - BT_HDR* p_buf) { +void l2c_link_check_send_pkts(tL2C_LCB* p_lcb, uint16_t local_cid, BT_HDR* p_buf) { bool single_write = false; /* Save the channel ID for faster counting */ @@ -847,10 +831,11 @@ void l2c_link_check_send_pkts(tL2C_LCB* p_lcb, uint16_t local_cid, list_append(p_lcb->link_xmit_data_q, p_buf); if (p_lcb->link_xmit_quota == 0) { - if (p_lcb->transport == BT_TRANSPORT_LE) + if (p_lcb->transport == BT_TRANSPORT_LE) { l2cb.ble_check_round_robin = true; - else + } else { l2cb.check_round_robin = true; + } } } @@ -877,7 +862,9 @@ void l2c_link_check_send_pkts(tL2C_LCB* p_lcb, uint16_t local_cid, /* Loop through, starting at the next */ for (int xx = 0; xx < MAX_L2CAP_LINKS; xx++, p_lcb++) { /* Check for wraparound */ - if (p_lcb == &l2cb.lcb_pool[MAX_L2CAP_LINKS]) p_lcb = &l2cb.lcb_pool[0]; + if (p_lcb == &l2cb.lcb_pool[MAX_L2CAP_LINKS]) { + p_lcb = &l2cb.lcb_pool[0]; + } /* If controller window is full, nothing to do */ if (((l2cb.controller_xmit_window == 0 || @@ -897,8 +884,7 @@ void l2c_link_check_send_pkts(tL2C_LCB* p_lcb, uint16_t local_cid, } /* See if we can send anything from the Link Queue */ - if (p_lcb->link_xmit_data_q != NULL && - !list_is_empty(p_lcb->link_xmit_data_q)) { + if (p_lcb->link_xmit_data_q != NULL && !list_is_empty(p_lcb->link_xmit_data_q)) { log::verbose("Sending to lower layer"); p_buf = (BT_HDR*)list_front(p_lcb->link_xmit_data_q); list_remove(p_lcb->link_xmit_data_q, p_buf); @@ -921,39 +907,35 @@ void l2c_link_check_send_pkts(tL2C_LCB* p_lcb, uint16_t local_cid, } /* If we finished without using up our quota, no need for a safety check */ - if ((l2cb.controller_xmit_window > 0) && - (l2cb.round_robin_unacked < l2cb.round_robin_quota) && - (p_lcb->transport == BT_TRANSPORT_BR_EDR)) + if ((l2cb.controller_xmit_window > 0) && (l2cb.round_robin_unacked < l2cb.round_robin_quota) && + (p_lcb->transport == BT_TRANSPORT_BR_EDR)) { l2cb.check_round_robin = false; + } if ((l2cb.controller_le_xmit_window > 0) && (l2cb.ble_round_robin_unacked < l2cb.ble_round_robin_quota) && - (p_lcb->transport == BT_TRANSPORT_LE)) + (p_lcb->transport == BT_TRANSPORT_LE)) { l2cb.ble_check_round_robin = false; + } } else /* if this is not round-robin service */ { /* link_state or power mode not ready, can't send anything else */ - if ((p_lcb->link_state != LST_CONNECTED) || - (l2c_link_check_power_mode(p_lcb))) { + if ((p_lcb->link_state != LST_CONNECTED) || (l2c_link_check_power_mode(p_lcb))) { log::warn("Can't send, link state: {} not LST_CONNECTED or power mode BTM_PM_STS_PENDING", p_lcb->link_state); return; } log::verbose( - "Direct send, transport={}, xmit_window={}, le_xmit_window={}, " - "sent_not_acked={}, link_xmit_quota={}", - p_lcb->transport, l2cb.controller_xmit_window, - l2cb.controller_le_xmit_window, p_lcb->sent_not_acked, - p_lcb->link_xmit_quota); + "Direct send, transport={}, xmit_window={}, le_xmit_window={}, " + "sent_not_acked={}, link_xmit_quota={}", + p_lcb->transport, l2cb.controller_xmit_window, l2cb.controller_le_xmit_window, + p_lcb->sent_not_acked, p_lcb->link_xmit_quota); /* See if we can send anything from the link queue */ - while (((l2cb.controller_xmit_window != 0 && - (p_lcb->transport == BT_TRANSPORT_BR_EDR)) || - (l2cb.controller_le_xmit_window != 0 && - (p_lcb->transport == BT_TRANSPORT_LE))) && + while (((l2cb.controller_xmit_window != 0 && (p_lcb->transport == BT_TRANSPORT_BR_EDR)) || + (l2cb.controller_le_xmit_window != 0 && (p_lcb->transport == BT_TRANSPORT_LE))) && (p_lcb->sent_not_acked < p_lcb->link_xmit_quota)) { - if ((p_lcb->link_xmit_data_q == NULL) || - list_is_empty(p_lcb->link_xmit_data_q)) { + if ((p_lcb->link_xmit_data_q == NULL) || list_is_empty(p_lcb->link_xmit_data_q)) { log::verbose("No transmit data, skipping"); break; } @@ -966,10 +948,8 @@ void l2c_link_check_send_pkts(tL2C_LCB* p_lcb, uint16_t local_cid, if (!single_write) { /* See if we can send anything for any channel */ log::verbose("Trying to send other data when single_write is false"); - while (((l2cb.controller_xmit_window != 0 && - (p_lcb->transport == BT_TRANSPORT_BR_EDR)) || - (l2cb.controller_le_xmit_window != 0 && - (p_lcb->transport == BT_TRANSPORT_LE))) && + while (((l2cb.controller_xmit_window != 0 && (p_lcb->transport == BT_TRANSPORT_BR_EDR)) || + (l2cb.controller_le_xmit_window != 0 && (p_lcb->transport == BT_TRANSPORT_LE))) && (p_lcb->sent_not_acked < p_lcb->link_xmit_quota)) { tL2C_TX_COMPLETE_CB_INFO cbi = {}; p_buf = l2cu_get_next_buffer_to_send(p_lcb, &cbi); @@ -985,11 +965,9 @@ void l2c_link_check_send_pkts(tL2C_LCB* p_lcb, uint16_t local_cid, /* There is a special case where we have readjusted the link quotas and */ /* this link may have sent anything but some other link sent packets so */ /* so we may need a timer to kick off this link's transmissions. */ - if ((p_lcb->link_xmit_data_q != NULL) && - (!list_is_empty(p_lcb->link_xmit_data_q)) && + if ((p_lcb->link_xmit_data_q != NULL) && (!list_is_empty(p_lcb->link_xmit_data_q)) && (p_lcb->sent_not_acked < p_lcb->link_xmit_quota)) { - alarm_set_on_mloop(p_lcb->l2c_lcb_timer, - L2CAP_LINK_FLOW_CONTROL_TIMEOUT_MS, + alarm_set_on_mloop(p_lcb->l2c_lcb_timer, L2CAP_LINK_FLOW_CONTROL_TIMEOUT_MS, l2c_lcb_timer_timeout, p_lcb); } } @@ -1000,8 +978,7 @@ void l2c_OnHciModeChangeSendPendingPackets(RawAddress remote) { if (p_lcb != NULL) { /* There might be any pending packets due to SNIFF or PENDING state */ /* Trigger L2C to start transmission of the pending packets. */ - log::verbose( - "btm mode change to active; check l2c_link for outgoing packets"); + log::verbose("btm mode change to active; check l2c_link for outgoing packets"); l2c_link_check_send_pkts(p_lcb, 0, NULL); } } @@ -1024,10 +1001,9 @@ static void l2c_link_send_to_lower_br_edr(tL2C_LCB* p_lcb, BT_HDR* p_buf) { l2cb.controller_xmit_window--; acl_send_data_packet_br_edr(p_lcb->remote_bd_addr, p_buf); - log::verbose( - "TotalWin={},Hndl=0x{:x},Quota={},Unack={},RRQuota={},RRUnack={}", - l2cb.controller_xmit_window, p_lcb->Handle(), p_lcb->link_xmit_quota, - p_lcb->sent_not_acked, l2cb.round_robin_quota, l2cb.round_robin_unacked); + log::verbose("TotalWin={},Hndl=0x{:x},Quota={},Unack={},RRQuota={},RRUnack={}", + l2cb.controller_xmit_window, p_lcb->Handle(), p_lcb->link_xmit_quota, + p_lcb->sent_not_acked, l2cb.round_robin_quota, l2cb.round_robin_unacked); } static void l2c_link_send_to_lower_ble(tL2C_LCB* p_lcb, BT_HDR* p_buf) { @@ -1042,9 +1018,8 @@ static void l2c_link_send_to_lower_ble(tL2C_LCB* p_lcb, BT_HDR* p_buf) { acl_send_data_packet_ble(p_lcb->remote_bd_addr, p_buf); log::debug("TotalWin={},Hndl=0x{:x},Quota={},Unack={},RRQuota={},RRUnack={}", - l2cb.controller_le_xmit_window, p_lcb->Handle(), - p_lcb->link_xmit_quota, p_lcb->sent_not_acked, - l2cb.ble_round_robin_quota, l2cb.ble_round_robin_unacked); + l2cb.controller_le_xmit_window, p_lcb->Handle(), p_lcb->link_xmit_quota, + p_lcb->sent_not_acked, l2cb.ble_round_robin_quota, l2cb.ble_round_robin_unacked); } static void l2c_link_send_to_lower(tL2C_LCB* p_lcb, BT_HDR* p_buf, @@ -1054,7 +1029,9 @@ static void l2c_link_send_to_lower(tL2C_LCB* p_lcb, BT_HDR* p_buf, } else { l2c_link_send_to_lower_ble(p_lcb, p_buf); } - if (p_cbi) l2cu_tx_complete(p_cbi); + if (p_cbi) { + l2cu_tx_complete(p_cbi); + } } void l2c_packets_completed(uint16_t handle, uint16_t num_sent) { @@ -1067,13 +1044,15 @@ void l2c_packets_completed(uint16_t handle, uint16_t num_sent) { switch (p_lcb->transport) { case BT_TRANSPORT_BR_EDR: l2cb.controller_xmit_window += num_sent; - if (p_lcb->is_round_robin_scheduling()) + if (p_lcb->is_round_robin_scheduling()) { l2cb.update_outstanding_classic_packets(num_sent); + } break; case BT_TRANSPORT_LE: l2cb.controller_le_xmit_window += num_sent; - if (p_lcb->is_round_robin_scheduling()) + if (p_lcb->is_round_robin_scheduling()) { l2cb.update_outstanding_le_packets(num_sent); + } break; default: log::error("Unknown transport received:{}", p_lcb->transport); @@ -1085,13 +1064,12 @@ void l2c_packets_completed(uint16_t handle, uint16_t num_sent) { if (p_lcb->is_high_priority()) { switch (p_lcb->transport) { case BT_TRANSPORT_LE: - if (l2cb.ble_check_round_robin && - l2cb.is_ble_round_robin_quota_available()) + if (l2cb.ble_check_round_robin && l2cb.is_ble_round_robin_quota_available()) { l2c_link_check_send_pkts(NULL, 0, NULL); + } break; case BT_TRANSPORT_BR_EDR: - if (l2cb.check_round_robin && - l2cb.is_classic_round_robin_quota_available()) { + if (l2cb.check_round_robin && l2cb.is_classic_round_robin_quota_available()) { l2c_link_check_send_pkts(NULL, 0, NULL); } break; @@ -1122,15 +1100,13 @@ void l2c_link_segments_xmitted(BT_HDR* p_msg) { /* Find the LCB based on the handle */ tL2C_LCB* p_lcb = l2cu_find_lcb_by_handle(handle); if (p_lcb == nullptr) { - log::warn("Received segment complete for unknown connection handle:{}", - handle); + log::warn("Received segment complete for unknown connection handle:{}", handle); osi_free(p_msg); return; } if (p_lcb->link_state != LST_CONNECTED) { - log::info("Received segment complete for unconnected connection handle:{}:", - handle); + log::info("Received segment complete for unconnected connection handle:{}:", handle); osi_free(p_msg); return; } @@ -1144,15 +1120,13 @@ void l2c_link_segments_xmitted(BT_HDR* p_msg) { tBTM_STATUS l2cu_ConnectAclForSecurity(const RawAddress& bd_addr) { tL2C_LCB* p_lcb = l2cu_find_lcb_by_bd_addr(bd_addr, BT_TRANSPORT_BR_EDR); - if (p_lcb && (p_lcb->link_state == LST_CONNECTED || - p_lcb->link_state == LST_CONNECTING)) { + if (p_lcb && (p_lcb->link_state == LST_CONNECTED || p_lcb->link_state == LST_CONNECTING)) { log::warn("Connection already exists"); return BTM_CMD_STARTED; } /* Make sure an L2cap link control block is available */ - if (!p_lcb && - (p_lcb = l2cu_allocate_lcb(bd_addr, true, BT_TRANSPORT_BR_EDR)) == NULL) { + if (!p_lcb && (p_lcb = l2cu_allocate_lcb(bd_addr, true, BT_TRANSPORT_BR_EDR)) == NULL) { log::warn("failed allocate LCB for {}", bd_addr); return BTM_NO_RESOURCES; } @@ -1186,8 +1160,7 @@ tL2C_CCB* l2cu_get_next_channel_in_rr(tL2C_LCB* p_lcb) { for (i = 0; (i < L2CAP_NUM_CHNL_PRIORITY) && (!p_serve_ccb); i++) { /* scan all channel within serving priority group until finding a channel to * serve */ - for (j = 0; (j < p_lcb->rr_serv[p_lcb->rr_pri].num_ccb) && (!p_serve_ccb); - j++) { + for (j = 0; (j < p_lcb->rr_serv[p_lcb->rr_pri].num_ccb) && (!p_serve_ccb); j++) { /* scaning from next serving channel */ p_ccb = p_lcb->rr_serv[p_lcb->rr_pri].p_serve_ccb; @@ -1196,43 +1169,51 @@ tL2C_CCB* l2cu_get_next_channel_in_rr(tL2C_LCB* p_lcb) { return NULL; } - log::verbose("RR scan pri={}, lcid=0x{:04x}, q_cout={}", - p_ccb->ccb_priority, p_ccb->local_cid, - fixed_queue_length(p_ccb->xmit_hold_q)); + log::verbose("RR scan pri={}, lcid=0x{:04x}, q_cout={}", p_ccb->ccb_priority, + p_ccb->local_cid, fixed_queue_length(p_ccb->xmit_hold_q)); /* store the next serving channel */ /* this channel is the last channel of its priority group */ - if ((p_ccb->p_next_ccb == NULL) || - (p_ccb->p_next_ccb->ccb_priority != p_ccb->ccb_priority)) { + if ((p_ccb->p_next_ccb == NULL) || (p_ccb->p_next_ccb->ccb_priority != p_ccb->ccb_priority)) { /* next serving channel is set to the first channel in the group */ - p_lcb->rr_serv[p_lcb->rr_pri].p_serve_ccb = - p_lcb->rr_serv[p_lcb->rr_pri].p_first_ccb; + p_lcb->rr_serv[p_lcb->rr_pri].p_serve_ccb = p_lcb->rr_serv[p_lcb->rr_pri].p_first_ccb; } else { /* next serving channel is set to the next channel in the group */ p_lcb->rr_serv[p_lcb->rr_pri].p_serve_ccb = p_ccb->p_next_ccb; } - if (p_ccb->chnl_state != CST_OPEN) continue; + if (p_ccb->chnl_state != CST_OPEN) { + continue; + } if (p_ccb->p_lcb->transport == BT_TRANSPORT_LE) { log::debug("Connection oriented channel"); - if (fixed_queue_is_empty(p_ccb->xmit_hold_q)) continue; + if (fixed_queue_is_empty(p_ccb->xmit_hold_q)) { + continue; + } } else { /* eL2CAP option in use */ if (p_ccb->peer_cfg.fcr.mode != L2CAP_FCR_BASIC_MODE) { - if (p_ccb->fcrb.wait_ack || p_ccb->fcrb.remote_busy) continue; + if (p_ccb->fcrb.wait_ack || p_ccb->fcrb.remote_busy) { + continue; + } if (fixed_queue_is_empty(p_ccb->fcrb.retrans_q)) { - if (fixed_queue_is_empty(p_ccb->xmit_hold_q)) continue; + if (fixed_queue_is_empty(p_ccb->xmit_hold_q)) { + continue; + } /* If in eRTM mode, check for window closure */ if ((p_ccb->peer_cfg.fcr.mode == L2CAP_FCR_ERTM_MODE) && - (l2c_fcr_is_flow_controlled(p_ccb))) + (l2c_fcr_is_flow_controlled(p_ccb))) { continue; + } } } else { - if (fixed_queue_is_empty(p_ccb->xmit_hold_q)) continue; + if (fixed_queue_is_empty(p_ccb->xmit_hold_q)) { + continue; + } } } @@ -1248,16 +1229,13 @@ tL2C_CCB* l2cu_get_next_channel_in_rr(tL2C_LCB* p_lcb) { /* serve next priority group */ p_lcb->rr_pri = (p_lcb->rr_pri + 1) % L2CAP_NUM_CHNL_PRIORITY; /* initialize its quota */ - p_lcb->rr_serv[p_lcb->rr_pri].quota = - L2CAP_GET_PRIORITY_QUOTA(p_lcb->rr_pri); + p_lcb->rr_serv[p_lcb->rr_pri].quota = L2CAP_GET_PRIORITY_QUOTA(p_lcb->rr_pri); } } if (p_serve_ccb) { - log::verbose("RR service pri={}, quota={}, lcid=0x{:04x}", - p_serve_ccb->ccb_priority, - p_lcb->rr_serv[p_serve_ccb->ccb_priority].quota, - p_serve_ccb->local_cid); + log::verbose("RR service pri={}, quota={}, lcid=0x{:04x}", p_serve_ccb->ccb_priority, + p_lcb->rr_serv[p_serve_ccb->ccb_priority].quota, p_serve_ccb->local_cid); } return p_serve_ccb; @@ -1273,8 +1251,7 @@ tL2C_CCB* l2cu_get_next_channel_in_rr(tL2C_LCB* p_lcb) { * Returns pointer to buffer or NULL * ******************************************************************************/ -BT_HDR* l2cu_get_next_buffer_to_send(tL2C_LCB* p_lcb, - tL2C_TX_COMPLETE_CB_INFO* p_cbi) { +BT_HDR* l2cu_get_next_buffer_to_send(tL2C_LCB* p_lcb, tL2C_TX_COMPLETE_CB_INFO* p_cbi) { tL2C_CCB* p_ccb; BT_HDR* p_buf; @@ -1285,34 +1262,41 @@ BT_HDR* l2cu_get_next_buffer_to_send(tL2C_LCB* p_lcb, for (xx = 0; xx < L2CAP_NUM_FIXED_CHNLS; xx++) { p_ccb = p_lcb->p_fixed_ccbs[xx]; - if (p_ccb == NULL) continue; + if (p_ccb == NULL) { + continue; + } /* eL2CAP option in use */ if (p_ccb->peer_cfg.fcr.mode != L2CAP_FCR_BASIC_MODE) { - if (p_ccb->fcrb.wait_ack || p_ccb->fcrb.remote_busy) continue; + if (p_ccb->fcrb.wait_ack || p_ccb->fcrb.remote_busy) { + continue; + } /* No more checks needed if sending from the reatransmit queue */ if (fixed_queue_is_empty(p_ccb->fcrb.retrans_q)) { - if (fixed_queue_is_empty(p_ccb->xmit_hold_q)) continue; + if (fixed_queue_is_empty(p_ccb->xmit_hold_q)) { + continue; + } /* If in eRTM mode, check for window closure */ if ((p_ccb->peer_cfg.fcr.mode == L2CAP_FCR_ERTM_MODE) && - (l2c_fcr_is_flow_controlled(p_ccb))) + (l2c_fcr_is_flow_controlled(p_ccb))) { continue; + } } p_buf = l2c_fcr_get_next_xmit_sdu_seg(p_ccb, 0); if (p_buf != NULL) { l2cu_check_channel_congestion(p_ccb); l2cu_set_acl_hci_header(p_buf, p_ccb); - return (p_buf); + return p_buf; } } else { if (!fixed_queue_is_empty(p_ccb->xmit_hold_q)) { p_buf = (BT_HDR*)fixed_queue_try_dequeue(p_ccb->xmit_hold_q); if (NULL == p_buf) { log::error("No data to be sent"); - return (NULL); + return NULL; } /* Prepare callback info for TX completion */ @@ -1322,7 +1306,7 @@ BT_HDR* l2cu_get_next_buffer_to_send(tL2C_LCB* p_lcb, l2cu_check_channel_congestion(p_ccb); l2cu_set_acl_hci_header(p_buf, p_ccb); - return (p_buf); + return p_buf; } } } @@ -1331,7 +1315,9 @@ BT_HDR* l2cu_get_next_buffer_to_send(tL2C_LCB* p_lcb, p_ccb = l2cu_get_next_channel_in_rr(p_lcb); /* Return if no buffer */ - if (p_ccb == NULL) return (NULL); + if (p_ccb == NULL) { + return NULL; + } if (p_ccb->p_lcb->transport == BT_TRANSPORT_LE) { /* Check credits */ @@ -1352,23 +1338,26 @@ BT_HDR* l2cu_get_next_buffer_to_send(tL2C_LCB* p_lcb, } else { if (p_ccb->peer_cfg.fcr.mode != L2CAP_FCR_BASIC_MODE) { p_buf = l2c_fcr_get_next_xmit_sdu_seg(p_ccb, 0); - if (p_buf == NULL) return (NULL); + if (p_buf == NULL) { + return NULL; + } } else { p_buf = (BT_HDR*)fixed_queue_try_dequeue(p_ccb->xmit_hold_q); if (NULL == p_buf) { log::error("#2: No data to be sent"); - return (NULL); + return NULL; } } } if (p_ccb->p_rcb && p_ccb->p_rcb->api.pL2CA_TxComplete_Cb && - (p_ccb->peer_cfg.fcr.mode != L2CAP_FCR_ERTM_MODE)) + (p_ccb->peer_cfg.fcr.mode != L2CAP_FCR_ERTM_MODE)) { (*p_ccb->p_rcb->api.pL2CA_TxComplete_Cb)(p_ccb->local_cid, 1); + } l2cu_check_channel_congestion(p_ccb); l2cu_set_acl_hci_header(p_buf, p_ccb); - return (p_buf); + return p_buf; } diff --git a/system/stack/l2cap/l2c_main.cc b/system/stack/l2cap/l2c_main.cc index ba851c38d5e..ac4d63ec515 100644 --- a/system/stack/l2cap/l2c_main.cc +++ b/system/stack/l2cap/l2c_main.cc @@ -97,8 +97,8 @@ void l2c_rcv_acl_data(BT_HDR* p_msg) { /* Find the LCB based on the handle */ tL2C_LCB* p_lcb = l2cu_find_lcb_by_handle(handle); if (!p_lcb) { - log::error("L2CAP - rcvd ACL for unknown handle:{} ls:{} cid:{}", handle, - p_msg->layer_specific, rcv_cid); + log::error("L2CAP - rcvd ACL for unknown handle:{} ls:{} cid:{}", handle, p_msg->layer_specific, + rcv_cid); osi_free(p_msg); return; } @@ -108,8 +108,7 @@ void l2c_rcv_acl_data(BT_HDR* p_msg) { /* for BLE channel, always notify connection when ACL data received on the * link */ - if (p_lcb && p_lcb->transport == BT_TRANSPORT_LE && - p_lcb->link_state != LST_DISCONNECTING) { + if (p_lcb && p_lcb->transport == BT_TRANSPORT_LE && p_lcb->link_state != LST_DISCONNECTING) { /* only process fixed channel data as channel open indication when link is * not in disconnecting mode */ l2cble_notify_le_connection(p_lcb->remote_bd_addr); @@ -130,8 +129,7 @@ void l2c_rcv_acl_data(BT_HDR* p_msg) { p_msg->offset += L2CAP_PKT_OVERHEAD; if (l2cap_len != p_msg->len) { - log::warn("L2CAP - bad length in pkt. Exp: {} Act: {}", l2cap_len, - p_msg->len); + log::warn("L2CAP - bad length in pkt. Exp: {} Act: {}", l2cap_len, p_msg->len); osi_free(p_msg); return; } @@ -155,10 +153,8 @@ void l2c_rcv_acl_data(BT_HDR* p_msg) { return; } - if ((rcv_cid >= L2CAP_FIRST_FIXED_CHNL) && - (rcv_cid <= L2CAP_LAST_FIXED_CHNL) && - (l2cb.fixed_reg[rcv_cid - L2CAP_FIRST_FIXED_CHNL].pL2CA_FixedData_Cb != - NULL)) { + if ((rcv_cid >= L2CAP_FIRST_FIXED_CHNL) && (rcv_cid <= L2CAP_LAST_FIXED_CHNL) && + (l2cb.fixed_reg[rcv_cid - L2CAP_FIRST_FIXED_CHNL].pL2CA_FixedData_Cb != NULL)) { /* only process fixed channel data when link is open or wait for data * indication */ if (!p_lcb || p_lcb->link_state == LST_DISCONNECTING || @@ -171,11 +167,12 @@ void l2c_rcv_acl_data(BT_HDR* p_msg) { p_ccb = p_lcb->p_fixed_ccbs[rcv_cid - L2CAP_FIRST_FIXED_CHNL]; p_ccb->metrics.rx(p_msg->len); - if (p_ccb->peer_cfg.fcr.mode != L2CAP_FCR_BASIC_MODE) + if (p_ccb->peer_cfg.fcr.mode != L2CAP_FCR_BASIC_MODE) { l2c_fcr_proc_pdu(p_ccb, p_msg); - else + } else { (*l2cb.fixed_reg[rcv_cid - L2CAP_FIRST_FIXED_CHNL].pL2CA_FixedData_Cb)( - rcv_cid, p_lcb->remote_bd_addr, p_msg); + rcv_cid, p_lcb->remote_bd_addr, p_msg); + } return; } @@ -200,14 +197,15 @@ void l2c_rcv_acl_data(BT_HDR* p_msg) { } } else { /* Basic mode packets go straight to the state machine */ - if (p_ccb->peer_cfg.fcr.mode == L2CAP_FCR_BASIC_MODE) + if (p_ccb->peer_cfg.fcr.mode == L2CAP_FCR_BASIC_MODE) { l2c_csm_execute(p_ccb, L2CEVT_L2CAP_DATA, p_msg); - else { + } else { /* eRTM or streaming mode, so we need to validate states first */ - if ((p_ccb->chnl_state == CST_OPEN) || (p_ccb->chnl_state == CST_CONFIG)) + if ((p_ccb->chnl_state == CST_OPEN) || (p_ccb->chnl_state == CST_CONFIG)) { l2c_fcr_proc_pdu(p_ccb, p_msg); - else + } else { osi_free(p_msg); + } } } } @@ -241,8 +239,7 @@ static void process_l2cap_cmd(tL2C_LCB* p_lcb, uint8_t* p, uint16_t pkt_len) { * will be ignored. Here we simply mark the bad packet and decide which cmd * ID to reject later */ pkt_size_rej = true; - log::warn("Signaling pkt_len={} exceeds MTU size {}", pkt_len, - L2CAP_DEFAULT_MTU); + log::warn("Signaling pkt_len={} exceeds MTU size {}", pkt_len, L2CAP_DEFAULT_MTU); } uint8_t* p_next_cmd = p; @@ -261,11 +258,10 @@ static void process_l2cap_cmd(tL2C_LCB* p_lcb, uint8_t* p, uint16_t pkt_len) { /* Reject to the previous endpoint if reliable channel is being used. * This is required in L2CAP/COS/CED/BI-02-C */ if (!first_cmd && - (cfg_info.fcr.mode == L2CAP_FCR_BASIC_MODE || - cfg_info.fcr.mode == L2CAP_FCR_ERTM_MODE) && - p != p_pkt_end) - l2cu_send_peer_cmd_reject(p_lcb, L2CAP_CMD_REJ_NOT_UNDERSTOOD, last_id, - 0, 0); + (cfg_info.fcr.mode == L2CAP_FCR_BASIC_MODE || cfg_info.fcr.mode == L2CAP_FCR_ERTM_MODE) && + p != p_pkt_end) { + l2cu_send_peer_cmd_reject(p_lcb, L2CAP_CMD_REJ_NOT_UNDERSTOOD, last_id, 0, 0); + } break; } @@ -279,8 +275,7 @@ static void process_l2cap_cmd(tL2C_LCB* p_lcb, uint8_t* p, uint16_t pkt_len) { first_cmd = false; if (cmd_len > BT_SMALL_BUFFER_SIZE) { - log::warn("Command size {} exceeds limit {}", cmd_len, - BT_SMALL_BUFFER_SIZE); + log::warn("Command size {} exceeds limit {}", cmd_len, BT_SMALL_BUFFER_SIZE); l2cu_send_peer_cmd_reject(p_lcb, L2CAP_CMD_REJ_MTU_EXCEEDED, id, 0, 0); return; } @@ -288,13 +283,11 @@ static void process_l2cap_cmd(tL2C_LCB* p_lcb, uint8_t* p, uint16_t pkt_len) { /* Check command length does not exceed packet length */ p_next_cmd = p + cmd_len; if (p_next_cmd > p_pkt_end) { - log::warn("cmd_len > pkt_len, pkt_len={}, cmd_len={}, code={}", pkt_len, - cmd_len, cmd_code); + log::warn("cmd_len > pkt_len, pkt_len={}, cmd_len={}, code={}", pkt_len, cmd_len, cmd_code); break; } - log::debug("cmd: {}, id:{}, cmd_len:{}", l2cap_command_code_text(cmd_code), - id, cmd_len); + log::debug("cmd: {}, id:{}, cmd_len:{}", l2cap_command_code_text(cmd_code), id, cmd_len); /* Bad L2CAP packet length, look for cmd to reject */ if (pkt_size_rej) { @@ -337,9 +330,7 @@ static void process_l2cap_cmd(tL2C_LCB* p_lcb, uint8_t* p, uint16_t pkt_len) { STREAM_TO_UINT16(rcid, p); STREAM_TO_UINT16(lcid, p); - log::warn( - "Rejected due to invalid CID, LCID: 0x{:04x} RCID: 0x{:04x}", - lcid, rcid); + log::warn("Rejected due to invalid CID, LCID: 0x{:04x} RCID: 0x{:04x}", lcid, rcid); /* Remote CID invalid. Treat as a disconnect */ tL2C_CCB* p_ccb = l2cu_find_ccb_by_cid(p_lcb, lcid); @@ -351,8 +342,7 @@ static void process_l2cap_cmd(tL2C_LCB* p_lcb, uint8_t* p, uint16_t pkt_len) { } /* SonyEricsson Info request Bug workaround (Continue connection) */ - else if (rej_reason == L2CAP_CMD_REJ_NOT_UNDERSTOOD && - p_lcb->w4_info_rsp) { + else if (rej_reason == L2CAP_CMD_REJ_NOT_UNDERSTOOD && p_lcb->w4_info_rsp) { alarm_cancel(p_lcb->info_resp_timer); p_lcb->w4_info_rsp = false; @@ -361,8 +351,7 @@ static void process_l2cap_cmd(tL2C_LCB* p_lcb, uint8_t* p, uint16_t pkt_len) { ci.bd_addr = p_lcb->remote_bd_addr; /* For all channels, send the event through their FSMs */ - for (tL2C_CCB* p_ccb = p_lcb->ccb_queue.p_first_ccb; p_ccb; - p_ccb = p_ccb->p_next_ccb) { + for (tL2C_CCB* p_ccb = p_lcb->ccb_queue.p_first_ccb; p_ccb; p_ccb = p_ccb->p_next_ccb) { l2c_csm_execute(p_ccb, L2CEVT_L2CAP_INFO_RSP, &ci); } } @@ -383,8 +372,7 @@ static void process_l2cap_cmd(tL2C_LCB* p_lcb, uint8_t* p, uint16_t pkt_len) { break; } else { if (!p_rcb->api.pL2CA_ConnectInd_Cb) { - log::warn("Rcvd conn req for outgoing-only connection PSM: {}", - con_info.psm); + log::warn("Rcvd conn req for outgoing-only connection PSM: {}", con_info.psm); l2cu_reject_connection(p_lcb, rcid, id, L2CAP_CONN_NO_PSM); break; } @@ -402,10 +390,10 @@ static void process_l2cap_cmd(tL2C_LCB* p_lcb, uint8_t* p, uint16_t pkt_len) { if (p_rcb->psm == BT_PSM_RFCOMM) { bluetooth::shim::GetSnoopLogger()->AddRfcommL2capChannel( - p_lcb->Handle(), p_ccb->local_cid, p_ccb->remote_cid); + p_lcb->Handle(), p_ccb->local_cid, p_ccb->remote_cid); } else if (p_rcb->log_packets) { bluetooth::shim::GetSnoopLogger()->AcceptlistL2capChannel( - p_lcb->Handle(), p_ccb->local_cid, p_ccb->remote_cid); + p_lcb->Handle(), p_ccb->local_cid, p_ccb->remote_cid); } l2c_csm_execute(p_ccb, L2CEVT_L2CAP_CONNECT_REQ, &con_info); @@ -425,8 +413,7 @@ static void process_l2cap_cmd(tL2C_LCB* p_lcb, uint8_t* p, uint16_t pkt_len) { tL2C_CCB* p_ccb = l2cu_find_ccb_by_cid(p_lcb, lcid); if (!p_ccb) { - log::warn("no CCB for conn rsp, LCID: {} RCID: {}", lcid, - con_info.remote_cid); + log::warn("no CCB for conn rsp, LCID: {} RCID: {}", lcid, con_info.remote_cid); break; } if (p_ccb->local_id != id) { @@ -444,10 +431,10 @@ static void process_l2cap_cmd(tL2C_LCB* p_lcb, uint8_t* p, uint16_t pkt_len) { p_rcb = p_ccb->p_rcb; if (p_rcb->psm == BT_PSM_RFCOMM) { bluetooth::shim::GetSnoopLogger()->AddRfcommL2capChannel( - p_lcb->Handle(), p_ccb->local_cid, p_ccb->remote_cid); + p_lcb->Handle(), p_ccb->local_cid, p_ccb->remote_cid); } else if (p_rcb->log_packets) { bluetooth::shim::GetSnoopLogger()->AcceptlistL2capChannel( - p_lcb->Handle(), p_ccb->local_cid, p_ccb->remote_cid); + p_lcb->Handle(), p_ccb->local_cid, p_ccb->remote_cid); } } @@ -469,9 +456,8 @@ static void process_l2cap_cmd(tL2C_LCB* p_lcb, uint8_t* p, uint16_t pkt_len) { uint8_t* p_cfg_start = p; - cfg_info.flush_to_present = cfg_info.mtu_present = - cfg_info.qos_present = cfg_info.fcr_present = cfg_info.fcs_present = - false; + cfg_info.flush_to_present = cfg_info.mtu_present = cfg_info.qos_present = + cfg_info.fcr_present = cfg_info.fcs_present = false; while (p < p_cfg_end) { uint8_t cfg_code, cfg_len; @@ -568,7 +554,9 @@ static void process_l2cap_cmd(tL2C_LCB* p_lcb, uint8_t* p, uint16_t pkt_len) { default: /* sanity check option length */ if ((cfg_len + L2CAP_CFG_OPTION_OVERHEAD) <= cmd_len) { - if (p + cfg_len > p_next_cmd) return; + if (p + cfg_len > p_next_cmd) { + return; + } p += cfg_len; if ((cfg_code & 0x80) == 0) { cfg_rej_len += cfg_len + L2CAP_CFG_OPTION_OVERHEAD; @@ -588,9 +576,8 @@ static void process_l2cap_cmd(tL2C_LCB* p_lcb, uint8_t* p, uint16_t pkt_len) { if (p_ccb) { p_ccb->remote_id = id; if (cfg_rej) { - l2cu_send_peer_config_rej( - p_ccb, p_cfg_start, (uint16_t)(cmd_len - L2CAP_CONFIG_REQ_LEN), - cfg_rej_len); + l2cu_send_peer_config_rej(p_ccb, p_cfg_start, + (uint16_t)(cmd_len - L2CAP_CONFIG_REQ_LEN), cfg_rej_len); } else { l2c_csm_execute(p_ccb, L2CEVT_L2CAP_CONFIG_REQ, &cfg_info); } @@ -612,9 +599,8 @@ static void process_l2cap_cmd(tL2C_LCB* p_lcb, uint8_t* p, uint16_t pkt_len) { STREAM_TO_UINT16(cfg_info.flags, p); STREAM_TO_UINT16(cfg_info.result, p); - cfg_info.flush_to_present = cfg_info.mtu_present = - cfg_info.qos_present = cfg_info.fcr_present = cfg_info.fcs_present = - false; + cfg_info.flush_to_present = cfg_info.mtu_present = cfg_info.qos_present = + cfg_info.fcr_present = cfg_info.fcs_present = false; while (p < p_cfg_end) { uint8_t cfg_code, cfg_len; @@ -730,8 +716,9 @@ static void process_l2cap_cmd(tL2C_LCB* p_lcb, uint8_t* p, uint16_t pkt_len) { p_ccb->remote_id = id; l2c_csm_execute(p_ccb, L2CEVT_L2CAP_DISCONNECT_REQ, &con_info); } - } else + } else { l2cu_send_peer_disc_rsp(p_lcb, id, lcid, rcid); + } break; } @@ -814,8 +801,7 @@ static void process_l2cap_cmd(tL2C_LCB* p_lcb, uint8_t* p, uint16_t pkt_len) { tL2C_CONN_INFO ci; ci.status = HCI_SUCCESS; ci.bd_addr = p_lcb->remote_bd_addr; - for (tL2C_CCB* p_ccb = p_lcb->ccb_queue.p_first_ccb; p_ccb; - p_ccb = p_ccb->p_next_ccb) { + for (tL2C_CCB* p_ccb = p_lcb->ccb_queue.p_first_ccb; p_ccb; p_ccb = p_ccb->p_next_ccb) { l2c_csm_execute(p_ccb, L2CEVT_L2CAP_INFO_RSP, &ci); } } @@ -823,8 +809,7 @@ static void process_l2cap_cmd(tL2C_LCB* p_lcb, uint8_t* p, uint16_t pkt_len) { default: log::warn("Bad cmd code: {}", cmd_code); - l2cu_send_peer_cmd_reject(p_lcb, L2CAP_CMD_REJ_NOT_UNDERSTOOD, id, 0, - 0); + l2cu_send_peer_cmd_reject(p_lcb, L2CAP_CMD_REJ_NOT_UNDERSTOOD, id, 0, 0); return; } } @@ -869,9 +854,8 @@ void l2c_init(void) { /* Number of ACL buffers to use for high priority channel */ - l2cb.l2c_ble_fixed_chnls_mask = L2CAP_FIXED_CHNL_ATT_BIT | - L2CAP_FIXED_CHNL_BLE_SIG_BIT | - L2CAP_FIXED_CHNL_SMP_BIT; + l2cb.l2c_ble_fixed_chnls_mask = + L2CAP_FIXED_CHNL_ATT_BIT | L2CAP_FIXED_CHNL_BLE_SIG_BIT | L2CAP_FIXED_CHNL_SMP_BIT; } void l2c_free(void) {} @@ -913,24 +897,25 @@ tL2CAP_DW_RESULT l2c_data_write(uint16_t cid, BT_HDR* p_data, uint16_t flags) { if (!p_ccb) { log::warn("L2CAP - no CCB for L2CA_DataWrite, CID: {}", cid); osi_free(p_data); - return (tL2CAP_DW_RESULT::FAILED); + return tL2CAP_DW_RESULT::FAILED; } /* Sending message bigger than mtu size of peer is a violation of protocol */ uint16_t mtu; - if (p_ccb->p_lcb->transport == BT_TRANSPORT_LE) + if (p_ccb->p_lcb->transport == BT_TRANSPORT_LE) { mtu = p_ccb->peer_conn_cfg.mtu; - else + } else { mtu = p_ccb->peer_cfg.mtu; + } if (p_data->len > mtu) { log::warn( - "L2CAP - CID: 0x{:04x} cannot send message bigger than peer's mtu " - "size: len={} mtu={}", - cid, p_data->len, mtu); + "L2CAP - CID: 0x{:04x} cannot send message bigger than peer's mtu " + "size: len={} mtu={}", + cid, p_data->len, mtu); osi_free(p_data); - return (tL2CAP_DW_RESULT::FAILED); + return tL2CAP_DW_RESULT::FAILED; } /* channel based, packet based flushable or non-flushable */ @@ -939,18 +924,19 @@ tL2CAP_DW_RESULT l2c_data_write(uint16_t cid, BT_HDR* p_data, uint16_t flags) { /* If already congested, do not accept any more packets */ if (p_ccb->cong_sent) { log::error( - "L2CAP - CID: 0x{:04x} cannot send, already congested " - "xmit_hold_q.count: {} buff_quota: {}", - p_ccb->local_cid, fixed_queue_length(p_ccb->xmit_hold_q), - p_ccb->buff_quota); + "L2CAP - CID: 0x{:04x} cannot send, already congested " + "xmit_hold_q.count: {} buff_quota: {}", + p_ccb->local_cid, fixed_queue_length(p_ccb->xmit_hold_q), p_ccb->buff_quota); osi_free(p_data); - return (tL2CAP_DW_RESULT::FAILED); + return tL2CAP_DW_RESULT::FAILED; } l2c_csm_execute(p_ccb, L2CEVT_L2CA_DATA_WRITE, p_data); - if (p_ccb->cong_sent) return (tL2CAP_DW_RESULT::CONGESTED); + if (p_ccb->cong_sent) { + return tL2CAP_DW_RESULT::CONGESTED; + } - return (tL2CAP_DW_RESULT::SUCCESS); + return tL2CAP_DW_RESULT::SUCCESS; } diff --git a/system/stack/l2cap/l2c_utils.cc b/system/stack/l2cap/l2c_utils.cc index ae55f9159ac..8bb1c325c4a 100644 --- a/system/stack/l2cap/l2c_utils.cc +++ b/system/stack/l2cap/l2c_utils.cc @@ -48,7 +48,7 @@ using namespace bluetooth; -tL2C_CCB* l2cu_get_next_channel_in_rr(tL2C_LCB* p_lcb); // TODO Move +tL2C_CCB* l2cu_get_next_channel_in_rr(tL2C_LCB* p_lcb); // TODO Move /******************************************************************************* * @@ -59,8 +59,7 @@ tL2C_CCB* l2cu_get_next_channel_in_rr(tL2C_LCB* p_lcb); // TODO Move * Returns LCB address or NULL if none found * ******************************************************************************/ -tL2C_LCB* l2cu_allocate_lcb(const RawAddress& p_bd_addr, bool is_bonding, - tBT_TRANSPORT transport) { +tL2C_LCB* l2cu_allocate_lcb(const RawAddress& p_bd_addr, bool is_bonding, tBT_TRANSPORT transport) { int xx; tL2C_LCB* p_lcb = &l2cb.lcb_pool[0]; @@ -86,8 +85,7 @@ tL2C_LCB* l2cu_allocate_lcb(const RawAddress& p_bd_addr, bool is_bonding, p_lcb->ResetBonding(); } p_lcb->transport = transport; - p_lcb->tx_data_len = - bluetooth::shim::GetController()->GetLeSuggestedDefaultDataLength(); + p_lcb->tx_data_len = bluetooth::shim::GetController()->GetLeSuggestedDefaultDataLength(); p_lcb->le_sec_pending_q = fixed_queue_new(SIZE_MAX); if (transport == BT_TRANSPORT_LE) { @@ -98,18 +96,17 @@ tL2C_LCB* l2cu_allocate_lcb(const RawAddress& p_bd_addr, bool is_bonding, l2c_link_adjust_allocation(); } p_lcb->link_xmit_data_q = list_new(NULL); - return (p_lcb); + return p_lcb; } } /* If here, no free LCB found */ - return (NULL); + return NULL; } void l2cu_set_lcb_handle(tL2C_LCB& p_lcb, uint16_t handle) { if (p_lcb.Handle() != HCI_INVALID_HANDLE) { - log::warn("Should not replace active handle:{} with new handle:{}", - p_lcb.Handle(), handle); + log::warn("Should not replace active handle:{} with new handle:{}", p_lcb.Handle(), handle); } p_lcb.SetHandle(handle); } @@ -159,8 +156,9 @@ void l2cu_release_lcb(tL2C_LCB* p_lcb) { alarm_free(p_lcb->info_resp_timer); p_lcb->info_resp_timer = NULL; - if (p_lcb->transport == BT_TRANSPORT_BR_EDR) /* Release all SCO links */ + if (p_lcb->transport == BT_TRANSPORT_BR_EDR) { /* Release all SCO links */ BTM_RemoveSco(p_lcb->remote_bd_addr); + } if (p_lcb->sent_not_acked > 0) { if (p_lcb->transport == BT_TRANSPORT_LE) { @@ -179,15 +177,14 @@ void l2cu_release_lcb(tL2C_LCB* p_lcb) { l2cu_process_fixed_disc_cback(p_lcb); /* Ensure no CCBs left on this LCB */ - for (p_ccb = p_lcb->ccb_queue.p_first_ccb; p_ccb; - p_ccb = p_lcb->ccb_queue.p_first_ccb) { + for (p_ccb = p_lcb->ccb_queue.p_first_ccb; p_ccb; p_ccb = p_lcb->ccb_queue.p_first_ccb) { l2cu_release_ccb(p_ccb); } /* Tell BTM Acl management the link was removed */ - if ((p_lcb->link_state == LST_CONNECTED) || - (p_lcb->link_state == LST_DISCONNECTING)) + if ((p_lcb->link_state == LST_CONNECTED) || (p_lcb->link_state == LST_DISCONNECTING)) { btm_acl_removed(p_lcb->Handle()); + } /* Release any held buffers */ if (p_lcb->link_xmit_data_q) { @@ -202,11 +199,15 @@ void l2cu_release_lcb(tL2C_LCB* p_lcb) { /* Re-adjust flow control windows make sure it does not go negative */ if (p_lcb->transport == BT_TRANSPORT_LE) { - if (l2cb.num_ble_links_active >= 1) l2cb.num_ble_links_active--; + if (l2cb.num_ble_links_active >= 1) { + l2cb.num_ble_links_active--; + } l2c_ble_link_adjust_allocation(); } else { - if (l2cb.num_used_lcbs >= 1) l2cb.num_used_lcbs--; + if (l2cb.num_used_lcbs >= 1) { + l2cb.num_used_lcbs--; + } l2c_link_adjust_allocation(); } @@ -214,11 +215,11 @@ void l2cu_release_lcb(tL2C_LCB* p_lcb) { /* Check and release all the LE COC connections waiting for security */ if (p_lcb->le_sec_pending_q) { while (!fixed_queue_is_empty(p_lcb->le_sec_pending_q)) { - tL2CAP_SEC_DATA* p_buf = - (tL2CAP_SEC_DATA*)fixed_queue_try_dequeue(p_lcb->le_sec_pending_q); - if (p_buf->p_callback) - p_buf->p_callback(p_lcb->remote_bd_addr, p_lcb->transport, - p_buf->p_ref_data, BTM_DEV_RESET); + tL2CAP_SEC_DATA* p_buf = (tL2CAP_SEC_DATA*)fixed_queue_try_dequeue(p_lcb->le_sec_pending_q); + if (p_buf->p_callback) { + p_buf->p_callback(p_lcb->remote_bd_addr, p_lcb->transport, p_buf->p_ref_data, + BTM_DEV_RESET); + } osi_free(p_buf); } fixed_queue_free(p_lcb->le_sec_pending_q, NULL); @@ -236,20 +237,18 @@ void l2cu_release_lcb(tL2C_LCB* p_lcb) { * Returns pointer to matched LCB, or NULL if no match * ******************************************************************************/ -tL2C_LCB* l2cu_find_lcb_by_bd_addr(const RawAddress& p_bd_addr, - tBT_TRANSPORT transport) { +tL2C_LCB* l2cu_find_lcb_by_bd_addr(const RawAddress& p_bd_addr, tBT_TRANSPORT transport) { int xx; tL2C_LCB* p_lcb = &l2cb.lcb_pool[0]; for (xx = 0; xx < MAX_L2CAP_LINKS; xx++, p_lcb++) { - if ((p_lcb->in_use) && p_lcb->transport == transport && - (p_lcb->remote_bd_addr == p_bd_addr)) { - return (p_lcb); + if ((p_lcb->in_use) && p_lcb->transport == transport && (p_lcb->remote_bd_addr == p_bd_addr)) { + return p_lcb; } } /* If here, no match found */ - return (NULL); + return NULL; } /******************************************************************************* @@ -275,8 +274,7 @@ bool l2c_is_cmd_rejected(uint8_t cmd_code, uint8_t signal_id, tL2C_LCB* p_lcb) { case L2CAP_CMD_AMP_CONN_REQ: case L2CAP_CMD_AMP_MOVE_REQ: case L2CAP_CMD_BLE_UPDATE_REQ: - l2cu_send_peer_cmd_reject(p_lcb, L2CAP_CMD_REJ_MTU_EXCEEDED, signal_id, - L2CAP_DEFAULT_MTU, 0); + l2cu_send_peer_cmd_reject(p_lcb, L2CAP_CMD_REJ_MTU_EXCEEDED, signal_id, L2CAP_DEFAULT_MTU, 0); log::warn("Dumping first Command ({})", cmd_code); return true; @@ -294,20 +292,18 @@ bool l2c_is_cmd_rejected(uint8_t cmd_code, uint8_t signal_id, tL2C_LCB* p_lcb) { * Returns Pointer to allocated packet or NULL if no resources * ******************************************************************************/ -BT_HDR* l2cu_build_header(tL2C_LCB* p_lcb, uint16_t len, uint8_t cmd, - uint8_t signal_id) { +BT_HDR* l2cu_build_header(tL2C_LCB* p_lcb, uint16_t len, uint8_t cmd, uint8_t signal_id) { BT_HDR* p_buf = (BT_HDR*)osi_malloc(L2CAP_CMD_BUF_SIZE); uint8_t* p; p_buf->offset = L2CAP_SEND_CMD_OFFSET; - p_buf->len = - len + HCI_DATA_PREAMBLE_SIZE + L2CAP_PKT_OVERHEAD + L2CAP_CMD_OVERHEAD; + p_buf->len = len + HCI_DATA_PREAMBLE_SIZE + L2CAP_PKT_OVERHEAD + L2CAP_CMD_OVERHEAD; p = (uint8_t*)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET; /* Put in HCI header - handle + pkt boundary */ if (p_lcb->transport == BT_TRANSPORT_LE) { - UINT16_TO_STREAM(p, (p_lcb->Handle() | (L2CAP_PKT_START_NON_FLUSHABLE - << L2CAP_PKT_TYPE_SHIFT))); + UINT16_TO_STREAM(p, + (p_lcb->Handle() | (L2CAP_PKT_START_NON_FLUSHABLE << L2CAP_PKT_TYPE_SHIFT))); } else { UINT16_TO_STREAM(p, p_lcb->Handle() | l2cb.non_flushable_pbf); } @@ -326,7 +322,7 @@ BT_HDR* l2cu_build_header(tL2C_LCB* p_lcb, uint16_t len, uint8_t cmd, UINT8_TO_STREAM(p, signal_id); UINT16_TO_STREAM(p, len); - return (p_buf); + return p_buf; } /******************************************************************************* @@ -355,35 +351,40 @@ void l2cu_adj_id(tL2C_LCB* p_lcb) { * Returns void * ******************************************************************************/ -void l2cu_send_peer_cmd_reject(tL2C_LCB* p_lcb, uint16_t reason, uint8_t rem_id, - uint16_t p1, uint16_t p2) { +void l2cu_send_peer_cmd_reject(tL2C_LCB* p_lcb, uint16_t reason, uint8_t rem_id, uint16_t p1, + uint16_t p2) { uint16_t param_len; BT_HDR* p_buf; uint8_t* p; /* Put in L2CAP packet header */ - if (reason == L2CAP_CMD_REJ_MTU_EXCEEDED) + if (reason == L2CAP_CMD_REJ_MTU_EXCEEDED) { param_len = 2; - else if (reason == L2CAP_CMD_REJ_INVALID_CID) + } else if (reason == L2CAP_CMD_REJ_INVALID_CID) { param_len = 4; - else + } else { param_len = 0; + } - p_buf = l2cu_build_header(p_lcb, (uint16_t)(L2CAP_CMD_REJECT_LEN + param_len), - L2CAP_CMD_REJECT, rem_id); + p_buf = l2cu_build_header(p_lcb, (uint16_t)(L2CAP_CMD_REJECT_LEN + param_len), L2CAP_CMD_REJECT, + rem_id); if (p_buf == NULL) { log::warn("L2CAP - no buffer cmd_rej"); return; } - p = (uint8_t*)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + - L2CAP_PKT_OVERHEAD + L2CAP_CMD_OVERHEAD; + p = (uint8_t*)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + L2CAP_PKT_OVERHEAD + + L2CAP_CMD_OVERHEAD; UINT16_TO_STREAM(p, reason); - if (param_len >= 2) UINT16_TO_STREAM(p, p1); + if (param_len >= 2) { + UINT16_TO_STREAM(p, p1); + } - if (param_len >= 4) UINT16_TO_STREAM(p, p2); + if (param_len >= 4) { + UINT16_TO_STREAM(p, p2); + } l2c_link_check_send_pkts(p_lcb, 0, p_buf); } @@ -408,15 +409,14 @@ void l2cu_send_peer_connect_req(tL2C_CCB* p_ccb) { p_ccb->local_id = p_ccb->p_lcb->signal_id; - p_buf = l2cu_build_header(p_ccb->p_lcb, L2CAP_CONN_REQ_LEN, - L2CAP_CMD_CONN_REQ, p_ccb->local_id); + p_buf = l2cu_build_header(p_ccb->p_lcb, L2CAP_CONN_REQ_LEN, L2CAP_CMD_CONN_REQ, p_ccb->local_id); if (p_buf == NULL) { log::warn("L2CAP - no buffer for conn_req"); return; } - p = (uint8_t*)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + - L2CAP_PKT_OVERHEAD + L2CAP_CMD_OVERHEAD; + p = (uint8_t*)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + L2CAP_PKT_OVERHEAD + + L2CAP_CMD_OVERHEAD; UINT16_TO_STREAM(p, p_ccb->p_rcb->real_psm); UINT16_TO_STREAM(p, p_ccb->local_cid); @@ -434,8 +434,7 @@ void l2cu_send_peer_connect_req(tL2C_CCB* p_ccb) { * Returns void * ******************************************************************************/ -void l2cu_send_peer_connect_rsp(tL2C_CCB* p_ccb, uint16_t result, - uint16_t status) { +void l2cu_send_peer_connect_rsp(tL2C_CCB* p_ccb, uint16_t result, uint16_t status) { if (result == L2CAP_CONN_PENDING) { /* if we already sent pending response */ if (p_ccb->flags & CCB_FLAG_SENT_PENDING) { @@ -446,15 +445,15 @@ void l2cu_send_peer_connect_rsp(tL2C_CCB* p_ccb, uint16_t result, } } - BT_HDR* p_buf = l2cu_build_header(p_ccb->p_lcb, L2CAP_CONN_RSP_LEN, - L2CAP_CMD_CONN_RSP, p_ccb->remote_id); + BT_HDR* p_buf = + l2cu_build_header(p_ccb->p_lcb, L2CAP_CONN_RSP_LEN, L2CAP_CMD_CONN_RSP, p_ccb->remote_id); if (p_buf == nullptr) { log::warn("no buffer for conn_rsp"); return; } - uint8_t* p = (uint8_t*)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + - HCI_DATA_PREAMBLE_SIZE + L2CAP_PKT_OVERHEAD + L2CAP_CMD_OVERHEAD; + uint8_t* p = (uint8_t*)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + + L2CAP_PKT_OVERHEAD + L2CAP_CMD_OVERHEAD; UINT16_TO_STREAM(p, p_ccb->local_cid); UINT16_TO_STREAM(p, p_ccb->remote_cid); @@ -475,20 +474,18 @@ void l2cu_send_peer_connect_rsp(tL2C_CCB* p_ccb, uint16_t result, * Returns void * ******************************************************************************/ -void l2cu_reject_connection(tL2C_LCB* p_lcb, uint16_t remote_cid, - uint8_t rem_id, uint16_t result) { +void l2cu_reject_connection(tL2C_LCB* p_lcb, uint16_t remote_cid, uint8_t rem_id, uint16_t result) { BT_HDR* p_buf; uint8_t* p; - p_buf = - l2cu_build_header(p_lcb, L2CAP_CONN_RSP_LEN, L2CAP_CMD_CONN_RSP, rem_id); + p_buf = l2cu_build_header(p_lcb, L2CAP_CONN_RSP_LEN, L2CAP_CMD_CONN_RSP, rem_id); if (p_buf == NULL) { log::warn("L2CAP - no buffer for conn_req"); return; } - p = (uint8_t*)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + - L2CAP_PKT_OVERHEAD + L2CAP_CMD_OVERHEAD; + p = (uint8_t*)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + L2CAP_PKT_OVERHEAD + + L2CAP_CMD_OVERHEAD; UINT16_TO_STREAM(p, 0); /* Local CID of 0 */ UINT16_TO_STREAM(p, remote_cid); @@ -508,8 +505,7 @@ void l2cu_reject_connection(tL2C_LCB* p_lcb, uint16_t remote_cid, * Returns void * ******************************************************************************/ -void l2cu_send_credit_based_reconfig_req(tL2C_CCB* p_ccb, - tL2CAP_LE_CFG_INFO* p_cfg) { +void l2cu_send_credit_based_reconfig_req(tL2C_CCB* p_ccb, tL2CAP_LE_CFG_INFO* p_cfg) { BT_HDR* p_buf; uint16_t cmd_len; uint8_t* p; @@ -525,15 +521,14 @@ void l2cu_send_credit_based_reconfig_req(tL2C_CCB* p_ccb, p_ccb->local_id = p_lcb->signal_id; - p_buf = l2cu_build_header(p_lcb, cmd_len, L2CAP_CMD_CREDIT_BASED_RECONFIG_REQ, - p_lcb->signal_id); + p_buf = l2cu_build_header(p_lcb, cmd_len, L2CAP_CMD_CREDIT_BASED_RECONFIG_REQ, p_lcb->signal_id); if (p_buf == NULL) { log::warn("l2cu_send_reconfig_req - no buffer"); return; } - p = (uint8_t*)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + - L2CAP_PKT_OVERHEAD + L2CAP_CMD_OVERHEAD; + p = (uint8_t*)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + L2CAP_PKT_OVERHEAD + + L2CAP_CMD_OVERHEAD; log::verbose("l2cu_send_reconfig_req number of cids: {} mtu:{} mps:{}", p_lcb->pending_ecoc_reconfig_cnt, p_cfg->mtu, p_cfg->mps); @@ -541,11 +536,10 @@ void l2cu_send_credit_based_reconfig_req(tL2C_CCB* p_ccb, UINT16_TO_STREAM(p, p_cfg->mtu); UINT16_TO_STREAM(p, p_cfg->mps); - for (p_ccb_temp = p_lcb->ccb_queue.p_first_ccb; p_ccb_temp; - p_ccb_temp = p_ccb_temp->p_next_ccb) { - if ((p_ccb_temp->in_use) && (p_ccb_temp->ecoc) && - (p_ccb_temp->reconfig_started)) + for (p_ccb_temp = p_lcb->ccb_queue.p_first_ccb; p_ccb_temp; p_ccb_temp = p_ccb_temp->p_next_ccb) { + if ((p_ccb_temp->in_use) && (p_ccb_temp->ecoc) && (p_ccb_temp->reconfig_started)) { UINT16_TO_STREAM(p, p_ccb_temp->local_cid); + } } l2c_link_check_send_pkts(p_lcb, 0, p_buf); @@ -572,29 +566,34 @@ void l2cu_send_peer_config_req(tL2C_CCB* p_ccb, tL2CAP_CFG_INFO* p_cfg) { p_ccb->local_id = p_ccb->p_lcb->signal_id; - if (p_cfg->mtu_present) + if (p_cfg->mtu_present) { cfg_len += L2CAP_CFG_MTU_OPTION_LEN + L2CAP_CFG_OPTION_OVERHEAD; - if (p_cfg->flush_to_present) + } + if (p_cfg->flush_to_present) { cfg_len += L2CAP_CFG_FLUSH_OPTION_LEN + L2CAP_CFG_OPTION_OVERHEAD; - if (p_cfg->qos_present) + } + if (p_cfg->qos_present) { cfg_len += L2CAP_CFG_QOS_OPTION_LEN + L2CAP_CFG_OPTION_OVERHEAD; - if (p_cfg->fcr_present) + } + if (p_cfg->fcr_present) { cfg_len += L2CAP_CFG_FCR_OPTION_LEN + L2CAP_CFG_OPTION_OVERHEAD; - if (p_cfg->fcs_present) + } + if (p_cfg->fcs_present) { cfg_len += L2CAP_CFG_FCS_OPTION_LEN + L2CAP_CFG_OPTION_OVERHEAD; - if (p_cfg->ext_flow_spec_present) + } + if (p_cfg->ext_flow_spec_present) { cfg_len += L2CAP_CFG_EXT_FLOW_OPTION_LEN + L2CAP_CFG_OPTION_OVERHEAD; + } - p_buf = l2cu_build_header(p_ccb->p_lcb, - (uint16_t)(L2CAP_CONFIG_REQ_LEN + cfg_len), + p_buf = l2cu_build_header(p_ccb->p_lcb, (uint16_t)(L2CAP_CONFIG_REQ_LEN + cfg_len), L2CAP_CMD_CONFIG_REQ, p_ccb->local_id); if (p_buf == NULL) { log::warn("L2CAP - no buffer for conn_req"); return; } - p = (uint8_t*)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + - L2CAP_PKT_OVERHEAD + L2CAP_CMD_OVERHEAD; + p = (uint8_t*)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + L2CAP_PKT_OVERHEAD + + L2CAP_CMD_OVERHEAD; UINT16_TO_STREAM(p, p_ccb->remote_cid); UINT16_TO_STREAM(p, p_cfg->flags); /* Flags (continuation) */ @@ -668,31 +667,34 @@ void l2cu_send_peer_config_rsp(tL2C_CCB* p_ccb, tL2CAP_CFG_INFO* p_cfg) { uint8_t* p; /* Create an identifier for this packet */ - if (p_cfg->mtu_present) + if (p_cfg->mtu_present) { cfg_len += L2CAP_CFG_MTU_OPTION_LEN + L2CAP_CFG_OPTION_OVERHEAD; - if (p_cfg->flush_to_present) + } + if (p_cfg->flush_to_present) { cfg_len += L2CAP_CFG_FLUSH_OPTION_LEN + L2CAP_CFG_OPTION_OVERHEAD; - if (p_cfg->qos_present) + } + if (p_cfg->qos_present) { cfg_len += L2CAP_CFG_QOS_OPTION_LEN + L2CAP_CFG_OPTION_OVERHEAD; - if (p_cfg->fcr_present) + } + if (p_cfg->fcr_present) { cfg_len += L2CAP_CFG_FCR_OPTION_LEN + L2CAP_CFG_OPTION_OVERHEAD; - if (p_cfg->ext_flow_spec_present) + } + if (p_cfg->ext_flow_spec_present) { cfg_len += L2CAP_CFG_EXT_FLOW_OPTION_LEN + L2CAP_CFG_OPTION_OVERHEAD; + } - p_buf = l2cu_build_header(p_ccb->p_lcb, - (uint16_t)(L2CAP_CONFIG_RSP_LEN + cfg_len), + p_buf = l2cu_build_header(p_ccb->p_lcb, (uint16_t)(L2CAP_CONFIG_RSP_LEN + cfg_len), L2CAP_CMD_CONFIG_RSP, p_ccb->remote_id); if (p_buf == NULL) { log::warn("L2CAP - no buffer for conn_req"); return; } - p = (uint8_t*)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + - L2CAP_PKT_OVERHEAD + L2CAP_CMD_OVERHEAD; + p = (uint8_t*)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + L2CAP_PKT_OVERHEAD + + L2CAP_CMD_OVERHEAD; UINT16_TO_STREAM(p, p_ccb->remote_cid); - UINT16_TO_STREAM(p, - p_cfg->flags); /* Flags (continuation) Must match request */ + UINT16_TO_STREAM(p, p_cfg->flags); /* Flags (continuation) Must match request */ UINT16_TO_STREAM(p, p_cfg->result); /* Now, put the options */ @@ -752,17 +754,16 @@ void l2cu_send_peer_config_rsp(tL2C_CCB* p_ccb, tL2CAP_CFG_INFO* p_cfg) { * Returns void * ******************************************************************************/ -void l2cu_send_peer_config_rej(tL2C_CCB* p_ccb, uint8_t* p_data, - uint16_t data_len, uint16_t rej_len) { +void l2cu_send_peer_config_rej(tL2C_CCB* p_ccb, uint8_t* p_data, uint16_t data_len, + uint16_t rej_len) { uint16_t len, cfg_len, buf_space, len1; uint8_t *p, *p_hci_len, *p_data_end; uint8_t cfg_code; - log::verbose("l2cu_send_peer_config_rej: data_len={}, rej_len={}", data_len, - rej_len); + log::verbose("l2cu_send_peer_config_rej: data_len={}, rej_len={}", data_len, rej_len); - len = BT_HDR_SIZE + HCI_DATA_PREAMBLE_SIZE + L2CAP_PKT_OVERHEAD + - L2CAP_CMD_OVERHEAD + L2CAP_CONFIG_RSP_LEN; + len = BT_HDR_SIZE + HCI_DATA_PREAMBLE_SIZE + L2CAP_PKT_OVERHEAD + L2CAP_CMD_OVERHEAD + + L2CAP_CONFIG_RSP_LEN; len1 = 0xFFFF - len; if (rej_len > len1) { log::error("L2CAP - cfg_rej pkt size exceeds buffer design max limit."); @@ -773,13 +774,12 @@ void l2cu_send_peer_config_rej(tL2C_CCB* p_ccb, uint8_t* p_data, p_buf->offset = L2CAP_SEND_CMD_OFFSET; p = (uint8_t*)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET; -/* Put in HCI header - handle + pkt boundary */ + /* Put in HCI header - handle + pkt boundary */ if (bluetooth::shim::GetController()->SupportsNonFlushablePb()) { - UINT16_TO_STREAM(p, (p_ccb->p_lcb->Handle() | (L2CAP_PKT_START_NON_FLUSHABLE - << L2CAP_PKT_TYPE_SHIFT))); + UINT16_TO_STREAM( + p, (p_ccb->p_lcb->Handle() | (L2CAP_PKT_START_NON_FLUSHABLE << L2CAP_PKT_TYPE_SHIFT))); } else { - UINT16_TO_STREAM(p, (p_ccb->p_lcb->Handle() | - (L2CAP_PKT_START << L2CAP_PKT_TYPE_SHIFT))); + UINT16_TO_STREAM(p, (p_ccb->p_lcb->Handle() | (L2CAP_PKT_START << L2CAP_PKT_TYPE_SHIFT))); } /* Remember the HCI header length position, and save space for it */ @@ -880,15 +880,14 @@ void l2cu_send_peer_disc_req(tL2C_CCB* p_ccb) { p_ccb->local_id = p_ccb->p_lcb->signal_id; - p_buf = l2cu_build_header(p_ccb->p_lcb, L2CAP_DISC_REQ_LEN, - L2CAP_CMD_DISC_REQ, p_ccb->local_id); + p_buf = l2cu_build_header(p_ccb->p_lcb, L2CAP_DISC_REQ_LEN, L2CAP_CMD_DISC_REQ, p_ccb->local_id); if (p_buf == NULL) { log::warn("L2CAP - no buffer for disc_req"); return; } - p = (uint8_t*)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + - L2CAP_PKT_OVERHEAD + L2CAP_CMD_OVERHEAD; + p = (uint8_t*)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + L2CAP_PKT_OVERHEAD + + L2CAP_CMD_OVERHEAD; UINT16_TO_STREAM(p, p_ccb->remote_cid); UINT16_TO_STREAM(p, p_ccb->local_cid); @@ -897,8 +896,7 @@ void l2cu_send_peer_disc_req(tL2C_CCB* p_ccb) { layer checks that all buffers are sent before disconnecting. */ if (p_ccb->peer_cfg.fcr.mode == L2CAP_FCR_BASIC_MODE) { - while ((p_buf2 = (BT_HDR*)fixed_queue_try_dequeue(p_ccb->xmit_hold_q)) != - NULL) { + while ((p_buf2 = (BT_HDR*)fixed_queue_try_dequeue(p_ccb->xmit_hold_q)) != NULL) { l2cu_set_acl_hci_header(p_buf2, p_ccb); l2c_link_check_send_pkts(p_ccb->p_lcb, p_ccb->local_cid, p_buf2); } @@ -921,20 +919,19 @@ void l2cu_send_peer_disc_req(tL2C_CCB* p_ccb) { * Returns void * ******************************************************************************/ -void l2cu_send_peer_disc_rsp(tL2C_LCB* p_lcb, uint8_t remote_id, - uint16_t local_cid, uint16_t remote_cid) { +void l2cu_send_peer_disc_rsp(tL2C_LCB* p_lcb, uint8_t remote_id, uint16_t local_cid, + uint16_t remote_cid) { BT_HDR* p_buf; uint8_t* p; - p_buf = l2cu_build_header(p_lcb, L2CAP_DISC_RSP_LEN, L2CAP_CMD_DISC_RSP, - remote_id); + p_buf = l2cu_build_header(p_lcb, L2CAP_DISC_RSP_LEN, L2CAP_CMD_DISC_RSP, remote_id); if (p_buf == NULL) { log::warn("L2CAP - no buffer for disc_rsp"); return; } - p = (uint8_t*)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + - L2CAP_PKT_OVERHEAD + L2CAP_CMD_OVERHEAD; + p = (uint8_t*)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + L2CAP_PKT_OVERHEAD + + L2CAP_CMD_OVERHEAD; UINT16_TO_STREAM(p, local_cid); UINT16_TO_STREAM(p, remote_cid); @@ -952,8 +949,8 @@ void l2cu_send_peer_disc_rsp(tL2C_LCB* p_lcb, uint8_t remote_id, * Returns void * ******************************************************************************/ -void l2cu_send_peer_echo_rsp(tL2C_LCB* p_lcb, uint8_t signal_id, - uint8_t* p_data, uint16_t data_len) { +void l2cu_send_peer_echo_rsp(tL2C_LCB* p_lcb, uint8_t signal_id, uint8_t* p_data, + uint16_t data_len) { BT_HDR* p_buf; uint8_t* p; uint16_t maxlen; @@ -963,34 +960,32 @@ void l2cu_send_peer_echo_rsp(tL2C_LCB* p_lcb, uint8_t signal_id, /* Dump this request since it is illegal */ log::warn("L2CAP ignoring duplicate echo request ({})", signal_id); return; - } else + } else { p_lcb->cur_echo_id = signal_id; + } constexpr int kHciDataPreambleSize = 4; - uint16_t acl_data_size = - bluetooth::shim::GetController()->GetAclPacketLength(); + uint16_t acl_data_size = bluetooth::shim::GetController()->GetAclPacketLength(); uint16_t acl_packet_size = - bluetooth::shim::GetController()->GetAclPacketLength() + - kHciDataPreambleSize; + bluetooth::shim::GetController()->GetAclPacketLength() + kHciDataPreambleSize; /* Don't return data if it does not fit in ACL and L2CAP MTU */ - maxlen = (L2CAP_CMD_BUF_SIZE > acl_packet_size) - ? acl_data_size - : (uint16_t)L2CAP_CMD_BUF_SIZE; - maxlen -= - (uint16_t)(BT_HDR_SIZE + HCI_DATA_PREAMBLE_SIZE + L2CAP_PKT_OVERHEAD + - L2CAP_CMD_OVERHEAD + L2CAP_ECHO_RSP_LEN); + maxlen = (L2CAP_CMD_BUF_SIZE > acl_packet_size) ? acl_data_size : (uint16_t)L2CAP_CMD_BUF_SIZE; + maxlen -= (uint16_t)(BT_HDR_SIZE + HCI_DATA_PREAMBLE_SIZE + L2CAP_PKT_OVERHEAD + + L2CAP_CMD_OVERHEAD + L2CAP_ECHO_RSP_LEN); - if (data_len > maxlen) data_len = 0; + if (data_len > maxlen) { + data_len = 0; + } - p_buf = l2cu_build_header(p_lcb, (uint16_t)(L2CAP_ECHO_RSP_LEN + data_len), - L2CAP_CMD_ECHO_RSP, signal_id); + p_buf = l2cu_build_header(p_lcb, (uint16_t)(L2CAP_ECHO_RSP_LEN + data_len), L2CAP_CMD_ECHO_RSP, + signal_id); if (p_buf == NULL) { log::warn("L2CAP - no buffer for echo_rsp"); return; } - p = (uint8_t*)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + - L2CAP_PKT_OVERHEAD + L2CAP_CMD_OVERHEAD; + p = (uint8_t*)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + L2CAP_PKT_OVERHEAD + + L2CAP_CMD_OVERHEAD; if (data_len) { ARRAY_TO_STREAM(p, p_data, data_len); @@ -1024,8 +1019,8 @@ void l2cu_send_peer_info_req(tL2C_LCB* p_lcb, uint16_t info_type) { log::verbose("l2cu_send_peer_info_req: type 0x{:04x}", info_type); - p = (uint8_t*)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + - L2CAP_PKT_OVERHEAD + L2CAP_CMD_OVERHEAD; + p = (uint8_t*)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + L2CAP_PKT_OVERHEAD + + L2CAP_CMD_OVERHEAD; UINT16_TO_STREAM(p, info_type); @@ -1046,8 +1041,7 @@ void l2cu_send_peer_info_req(tL2C_LCB* p_lcb, uint16_t info_type) { * Returns void * ******************************************************************************/ -void l2cu_send_peer_info_rsp(tL2C_LCB* p_lcb, uint8_t remote_id, - uint16_t info_type) { +void l2cu_send_peer_info_rsp(tL2C_LCB* p_lcb, uint8_t remote_id, uint16_t info_type) { BT_HDR* p_buf; uint8_t* p; uint16_t len = L2CAP_INFO_RSP_LEN; @@ -1055,16 +1049,14 @@ void l2cu_send_peer_info_rsp(tL2C_LCB* p_lcb, uint8_t remote_id, #if (L2CAP_CONFORMANCE_TESTING == TRUE) if ((info_type == L2CAP_EXTENDED_FEATURES_INFO_TYPE) && (l2cb.test_info_resp & - (L2CAP_EXTFEA_ENH_RETRANS | L2CAP_EXTFEA_STREAM_MODE | - L2CAP_EXTFEA_NO_CRC | L2CAP_EXTFEA_EXT_FLOW_SPEC | - L2CAP_EXTFEA_FIXED_CHNLS | L2CAP_EXTFEA_EXT_WINDOW | + (L2CAP_EXTFEA_ENH_RETRANS | L2CAP_EXTFEA_STREAM_MODE | L2CAP_EXTFEA_NO_CRC | + L2CAP_EXTFEA_EXT_FLOW_SPEC | L2CAP_EXTFEA_FIXED_CHNLS | L2CAP_EXTFEA_EXT_WINDOW | L2CAP_EXTFEA_UCD_RECEPTION))) #else if ((info_type == L2CAP_EXTENDED_FEATURES_INFO_TYPE) && (L2CAP_EXTFEA_SUPPORTED_MASK & - (L2CAP_EXTFEA_ENH_RETRANS | L2CAP_EXTFEA_STREAM_MODE | - L2CAP_EXTFEA_NO_CRC | L2CAP_EXTFEA_FIXED_CHNLS | - L2CAP_EXTFEA_UCD_RECEPTION)) != 0) + (L2CAP_EXTFEA_ENH_RETRANS | L2CAP_EXTFEA_STREAM_MODE | L2CAP_EXTFEA_NO_CRC | + L2CAP_EXTFEA_FIXED_CHNLS | L2CAP_EXTFEA_UCD_RECEPTION)) != 0) #endif { len += L2CAP_EXTENDED_FEATURES_ARRAY_SIZE; @@ -1080,21 +1072,19 @@ void l2cu_send_peer_info_rsp(tL2C_LCB* p_lcb, uint8_t remote_id, return; } - p = (uint8_t*)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + - L2CAP_PKT_OVERHEAD + L2CAP_CMD_OVERHEAD; + p = (uint8_t*)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + L2CAP_PKT_OVERHEAD + + L2CAP_CMD_OVERHEAD; UINT16_TO_STREAM(p, info_type); #if (L2CAP_CONFORMANCE_TESTING == TRUE) if ((info_type == L2CAP_EXTENDED_FEATURES_INFO_TYPE) && (l2cb.test_info_resp & - (L2CAP_EXTFEA_ENH_RETRANS | L2CAP_EXTFEA_STREAM_MODE | - L2CAP_EXTFEA_UCD_RECEPTION))) + (L2CAP_EXTFEA_ENH_RETRANS | L2CAP_EXTFEA_STREAM_MODE | L2CAP_EXTFEA_UCD_RECEPTION))) #else if ((info_type == L2CAP_EXTENDED_FEATURES_INFO_TYPE) && (L2CAP_EXTFEA_SUPPORTED_MASK & - (L2CAP_EXTFEA_ENH_RETRANS | L2CAP_EXTFEA_STREAM_MODE | - L2CAP_EXTFEA_UCD_RECEPTION)) != 0) + (L2CAP_EXTFEA_ENH_RETRANS | L2CAP_EXTFEA_STREAM_MODE | L2CAP_EXTFEA_UCD_RECEPTION)) != 0) #endif { UINT16_TO_STREAM(p, L2CAP_INFO_RESP_RESULT_SUCCESS); @@ -1105,8 +1095,7 @@ void l2cu_send_peer_info_rsp(tL2C_LCB* p_lcb, uint8_t remote_id, #if (L2CAP_CONFORMANCE_TESTING == TRUE) UINT32_TO_STREAM(p, l2cb.test_info_resp); #else - UINT32_TO_STREAM(p, - L2CAP_EXTFEA_SUPPORTED_MASK | L2CAP_EXTFEA_FIXED_CHNLS); + UINT32_TO_STREAM(p, L2CAP_EXTFEA_SUPPORTED_MASK | L2CAP_EXTFEA_FIXED_CHNLS); #endif } } else if (info_type == L2CAP_FIXED_CHANNELS_INFO_TYPE) { @@ -1115,8 +1104,9 @@ void l2cu_send_peer_info_rsp(tL2C_LCB* p_lcb, uint8_t remote_id, p[0] = L2CAP_FIXED_CHNL_SIG_BIT; - if (L2CAP_EXTFEA_SUPPORTED_MASK & L2CAP_EXTFEA_UCD_RECEPTION) + if (L2CAP_EXTFEA_SUPPORTED_MASK & L2CAP_EXTFEA_UCD_RECEPTION) { p[0] |= L2CAP_FIXED_CHNL_CNCTLESS_BIT; + } { int xx; @@ -1124,20 +1114,20 @@ void l2cu_send_peer_info_rsp(tL2C_LCB* p_lcb, uint8_t remote_id, for (xx = 0; xx < L2CAP_NUM_FIXED_CHNLS; xx++) { /* Skip fixed channels not used on BR/EDR-ACL link */ if ((xx >= L2CAP_ATT_CID - L2CAP_FIRST_FIXED_CHNL) && - (xx <= L2CAP_SMP_CID - L2CAP_FIRST_FIXED_CHNL)) + (xx <= L2CAP_SMP_CID - L2CAP_FIRST_FIXED_CHNL)) { continue; + } - if (l2cb.fixed_reg[xx].pL2CA_FixedConn_Cb != NULL) - p[(xx + L2CAP_FIRST_FIXED_CHNL) / 8] |= - 1 << ((xx + L2CAP_FIRST_FIXED_CHNL) % 8); + if (l2cb.fixed_reg[xx].pL2CA_FixedConn_Cb != NULL) { + p[(xx + L2CAP_FIRST_FIXED_CHNL) / 8] |= 1 << ((xx + L2CAP_FIRST_FIXED_CHNL) % 8); + } } } } else if (info_type == L2CAP_CONNLESS_MTU_INFO_TYPE) { UINT16_TO_STREAM(p, L2CAP_INFO_RESP_RESULT_SUCCESS); UINT16_TO_STREAM(p, L2CAP_MTU_SIZE); } else { - UINT16_TO_STREAM( - p, L2CAP_INFO_RESP_RESULT_NOT_SUPPORTED); /* 'not supported' */ + UINT16_TO_STREAM(p, L2CAP_INFO_RESP_RESULT_NOT_SUPPORTED); /* 'not supported' */ } l2c_link_check_send_pkts(p_lcb, 0, p_buf); @@ -1158,12 +1148,14 @@ void l2cu_enqueue_ccb(tL2C_CCB* p_ccb) { tL2C_CCB_Q* p_q = NULL; /* Find out which queue the channel is on - */ - if (p_ccb->p_lcb != NULL) p_q = &p_ccb->p_lcb->ccb_queue; + */ + if (p_ccb->p_lcb != NULL) { + p_q = &p_ccb->p_lcb->ccb_queue; + } if ((!p_ccb->in_use) || (p_q == NULL)) { - log::error("CID: 0x{:04x} ERROR in_use: {} p_lcb: {}", p_ccb->local_cid, - p_ccb->in_use, fmt::ptr(p_ccb->p_lcb)); + log::error("CID: 0x{:04x} ERROR in_use: {} p_lcb: {}", p_ccb->local_cid, p_ccb->in_use, + fmt::ptr(p_ccb->p_lcb)); return; } @@ -1182,10 +1174,11 @@ void l2cu_enqueue_ccb(tL2C_CCB* p_ccb) { * priority */ if (p_ccb->ccb_priority < p_ccb1->ccb_priority) { /* Are we at the head of the queue ? */ - if (p_ccb1 == p_q->p_first_ccb) + if (p_ccb1 == p_q->p_first_ccb) { p_q->p_first_ccb = p_ccb; - else + } else { p_ccb1->p_prev_ccb->p_next_ccb = p_ccb; + } p_ccb->p_next_ccb = p_ccb1; p_ccb->p_prev_ccb = p_ccb1->p_prev_ccb; @@ -1217,7 +1210,7 @@ void l2cu_enqueue_ccb(tL2C_CCB* p_ccb) { p_ccb->p_lcb->rr_serv[p_ccb->ccb_priority].p_serve_ccb = p_ccb; /* Initialize quota of this priority group based on its priority */ p_ccb->p_lcb->rr_serv[p_ccb->ccb_priority].quota = - L2CAP_GET_PRIORITY_QUOTA(p_ccb->ccb_priority); + L2CAP_GET_PRIORITY_QUOTA(p_ccb->ccb_priority); } /* increase number of channels in this group */ p_ccb->p_lcb->rr_serv[p_ccb->ccb_priority].num_ccb++; @@ -1239,15 +1232,17 @@ void l2cu_dequeue_ccb(tL2C_CCB* p_ccb) { log::verbose("l2cu_dequeue_ccb CID: 0x{:04x}", p_ccb->local_cid); /* Find out which queue the channel is on - */ - if (p_ccb->p_lcb != NULL) p_q = &p_ccb->p_lcb->ccb_queue; + */ + if (p_ccb->p_lcb != NULL) { + p_q = &p_ccb->p_lcb->ccb_queue; + } if ((!p_ccb->in_use) || (p_q == NULL) || (p_q->p_first_ccb == NULL)) { log::error( - "l2cu_dequeue_ccb CID: 0x{:04x} ERROR in_use: {} p_lcb: 0x{} p_q: " - "0x{} p_q->p_first_ccb: 0x{}", - p_ccb->local_cid, p_ccb->in_use, fmt::ptr(p_ccb->p_lcb), fmt::ptr(p_q), - fmt::ptr(p_q ? p_q->p_first_ccb : 0)); + "l2cu_dequeue_ccb CID: 0x{:04x} ERROR in_use: {} p_lcb: 0x{} p_q: " + "0x{} p_q->p_first_ccb: 0x{}", + p_ccb->local_cid, p_ccb->in_use, fmt::ptr(p_ccb->p_lcb), fmt::ptr(p_q), + fmt::ptr(p_q ? p_q->p_first_ccb : 0)); return; } @@ -1263,14 +1258,13 @@ void l2cu_dequeue_ccb(tL2C_CCB* p_ccb) { } else { /* if it is the first channel of this group */ if (p_ccb->p_lcb->rr_serv[p_ccb->ccb_priority].p_first_ccb == p_ccb) { - p_ccb->p_lcb->rr_serv[p_ccb->ccb_priority].p_first_ccb = - p_ccb->p_next_ccb; + p_ccb->p_lcb->rr_serv[p_ccb->ccb_priority].p_first_ccb = p_ccb->p_next_ccb; } /* if it is the next serving channel of this group */ if (p_ccb->p_lcb->rr_serv[p_ccb->ccb_priority].p_serve_ccb == p_ccb) { /* simply, start serving from the first channel */ p_ccb->p_lcb->rr_serv[p_ccb->ccb_priority].p_serve_ccb = - p_ccb->p_lcb->rr_serv[p_ccb->ccb_priority].p_first_ccb; + p_ccb->p_lcb->rr_serv[p_ccb->ccb_priority].p_first_ccb; } } } @@ -1279,10 +1273,11 @@ void l2cu_dequeue_ccb(tL2C_CCB* p_ccb) { /* We are removing the first in a queue */ p_q->p_first_ccb = p_ccb->p_next_ccb; - if (p_q->p_first_ccb) + if (p_q->p_first_ccb) { p_q->p_first_ccb->p_prev_ccb = NULL; - else + } else { p_q->p_last_ccb = NULL; + } } else if (p_ccb == p_q->p_last_ccb) { /* We are removing the last in a queue */ p_q->p_last_ccb = p_ccb->p_prev_ccb; @@ -1316,8 +1311,7 @@ void l2cu_change_pri_ccb(tL2C_CCB* p_ccb, tL2CAP_CHNL_PRIORITY priority) { p_ccb->ccb_priority = priority; l2cu_enqueue_ccb(p_ccb); - } - else { + } else { /* If CCB is the only guy on the queue, no need to re-enqueue */ /* update only round robin service data */ p_ccb->p_lcb->rr_serv[p_ccb->ccb_priority].num_ccb = 0; @@ -1329,7 +1323,7 @@ void l2cu_change_pri_ccb(tL2C_CCB* p_ccb, tL2CAP_CHNL_PRIORITY priority) { p_ccb->p_lcb->rr_serv[p_ccb->ccb_priority].p_first_ccb = p_ccb; p_ccb->p_lcb->rr_serv[p_ccb->ccb_priority].p_serve_ccb = p_ccb; p_ccb->p_lcb->rr_serv[p_ccb->ccb_priority].quota = - L2CAP_GET_PRIORITY_QUOTA(p_ccb->ccb_priority); + L2CAP_GET_PRIORITY_QUOTA(p_ccb->ccb_priority); p_ccb->p_lcb->rr_serv[p_ccb->ccb_priority].num_ccb = 1; } } @@ -1365,8 +1359,7 @@ tL2C_CCB* l2cu_allocate_ccb(tL2C_LCB* p_lcb, uint16_t cid, bool is_eatt) { if (p_ccb == l2cb.p_free_ccb_first) { l2cb.p_free_ccb_first = p_ccb->p_next_ccb; } else { - for (p_prev = l2cb.p_free_ccb_first; p_prev != nullptr; - p_prev = p_prev->p_next_ccb) { + for (p_prev = l2cb.p_free_ccb_first; p_prev != nullptr; p_prev = p_prev->p_next_ccb) { if (p_prev->p_next_ccb == p_ccb) { p_prev->p_next_ccb = p_ccb->p_next_ccb; @@ -1397,7 +1390,9 @@ tL2C_CCB* l2cu_allocate_ccb(tL2C_LCB* p_lcb, uint16_t cid, bool is_eatt) { /* Set priority then insert ccb into LCB queue (if we have an LCB) */ p_ccb->ccb_priority = L2CAP_CHNL_PRIORITY_LOW; - if (p_lcb) l2cu_enqueue_ccb(p_ccb); + if (p_lcb) { + l2cu_enqueue_ccb(p_ccb); + } /* Put in default values for configuration */ memset(&p_ccb->our_cfg, 0, sizeof(tL2CAP_CFG_INFO)); @@ -1406,18 +1401,14 @@ tL2C_CCB* l2cu_allocate_ccb(tL2C_LCB* p_lcb, uint16_t cid, bool is_eatt) { /* Put in default values for local/peer configurations */ p_ccb->our_cfg.flush_to = p_ccb->peer_cfg.flush_to = L2CAP_NO_AUTOMATIC_FLUSH; p_ccb->our_cfg.mtu = p_ccb->peer_cfg.mtu = L2CAP_DEFAULT_MTU; - p_ccb->our_cfg.qos.service_type = p_ccb->peer_cfg.qos.service_type = - L2CAP_DEFAULT_SERV_TYPE; - p_ccb->our_cfg.qos.token_rate = p_ccb->peer_cfg.qos.token_rate = - L2CAP_DEFAULT_TOKEN_RATE; + p_ccb->our_cfg.qos.service_type = p_ccb->peer_cfg.qos.service_type = L2CAP_DEFAULT_SERV_TYPE; + p_ccb->our_cfg.qos.token_rate = p_ccb->peer_cfg.qos.token_rate = L2CAP_DEFAULT_TOKEN_RATE; p_ccb->our_cfg.qos.token_bucket_size = p_ccb->peer_cfg.qos.token_bucket_size = - L2CAP_DEFAULT_BUCKET_SIZE; + L2CAP_DEFAULT_BUCKET_SIZE; p_ccb->our_cfg.qos.peak_bandwidth = p_ccb->peer_cfg.qos.peak_bandwidth = - L2CAP_DEFAULT_PEAK_BANDWIDTH; - p_ccb->our_cfg.qos.latency = p_ccb->peer_cfg.qos.latency = - L2CAP_DEFAULT_LATENCY; - p_ccb->our_cfg.qos.delay_variation = p_ccb->peer_cfg.qos.delay_variation = - L2CAP_DEFAULT_DELAY; + L2CAP_DEFAULT_PEAK_BANDWIDTH; + p_ccb->our_cfg.qos.latency = p_ccb->peer_cfg.qos.latency = L2CAP_DEFAULT_LATENCY; + p_ccb->our_cfg.qos.delay_variation = p_ccb->peer_cfg.qos.delay_variation = L2CAP_DEFAULT_DELAY; p_ccb->peer_cfg_already_rejected = false; p_ccb->fcr_cfg_tries = L2CAP_MAX_FCR_CFG_TRIES; @@ -1426,14 +1417,14 @@ tL2C_CCB* l2cu_allocate_ccb(tL2C_LCB* p_lcb, uint16_t cid, bool is_eatt) { p_ccb->fcrb.ack_timer = alarm_new("l2c_fcrb.ack_timer"); /* CSP408639 Fix: When L2CAP send amp move channel request or receive - * L2CEVT_AMP_MOVE_REQ do following sequence. Send channel move - * request -> Stop retrans/monitor timer -> Change channel state to + * L2CEVT_AMP_MOVE_REQ do following sequence. Send channel move + * request -> Stop retrans/monitor timer -> Change channel state to * CST_AMP_MOVING. */ alarm_free(p_ccb->fcrb.mon_retrans_timer); p_ccb->fcrb.mon_retrans_timer = alarm_new("l2c_fcrb.mon_retrans_timer"); - p_ccb->max_rx_mtu = BT_DEFAULT_BUFFER_SIZE - - (L2CAP_MIN_OFFSET + L2CAP_SDU_LEN_OFFSET + L2CAP_FCS_LEN); + p_ccb->max_rx_mtu = + BT_DEFAULT_BUFFER_SIZE - (L2CAP_MIN_OFFSET + L2CAP_SDU_LEN_OFFSET + L2CAP_FCS_LEN); p_ccb->tx_mps = BT_DEFAULT_BUFFER_SIZE - 32; p_ccb->xmit_hold_q = fixed_queue_new(SIZE_MAX); @@ -1500,8 +1491,7 @@ bool l2cu_start_post_bond_timer(uint16_t handle) { /* Only start timer if no control blocks allocated */ if (p_lcb->ccb_queue.p_first_ccb != nullptr) { - log::debug( - "Unable to start post bond timer with existing dynamic channels"); + log::debug("Unable to start post bond timer with existing dynamic channels"); return false; } @@ -1514,13 +1504,12 @@ bool l2cu_start_post_bond_timer(uint16_t handle) { if (p_lcb->idle_timeout == 0) { acl_disconnect_from_handle( - p_lcb->Handle(), HCI_ERR_PEER_USER, - "stack::l2cap::l2c_utils::l2cu_start_post_bond_timer Idle timeout"); + p_lcb->Handle(), HCI_ERR_PEER_USER, + "stack::l2cap::l2c_utils::l2cu_start_post_bond_timer Idle timeout"); p_lcb->link_state = LST_DISCONNECTING; timeout_ms = L2CAP_LINK_DISCONNECT_TIMEOUT_MS; } - alarm_set_on_mloop(p_lcb->l2c_lcb_timer, timeout_ms, - l2c_lcb_timer_timeout, p_lcb); + alarm_set_on_mloop(p_lcb->l2c_lcb_timer, timeout_ms, l2c_lcb_timer_timeout, p_lcb); log::debug("Started link IDLE timeout_ms:{}", (unsigned long)timeout_ms); return true; } break; @@ -1548,20 +1537,21 @@ void l2cu_release_ccb(tL2C_CCB* p_ccb) { tL2C_LCB* p_lcb = p_ccb->p_lcb; tL2C_RCB* p_rcb = p_ccb->p_rcb; - log::verbose("l2cu_release_ccb: cid 0x{:04x} in_use: {}", p_ccb->local_cid, - p_ccb->in_use); + log::verbose("l2cu_release_ccb: cid 0x{:04x} in_use: {}", p_ccb->local_cid, p_ccb->in_use); /* If already released, could be race condition */ - if (!p_ccb->in_use) return; + if (!p_ccb->in_use) { + return; + } if (p_rcb && p_lcb && p_ccb->chnl_state >= CST_OPEN) { - bluetooth::shim::GetSnoopLogger()->SetL2capChannelClose( - p_ccb->p_lcb->Handle(), p_ccb->local_cid, p_ccb->remote_cid); + bluetooth::shim::GetSnoopLogger()->SetL2capChannelClose(p_ccb->p_lcb->Handle(), + p_ccb->local_cid, p_ccb->remote_cid); } if (p_lcb) { - bluetooth::shim::GetSnoopLogger()->ClearL2capAcceptlist( - p_lcb->Handle(), p_ccb->local_cid, p_ccb->remote_cid); + bluetooth::shim::GetSnoopLogger()->ClearL2capAcceptlist(p_lcb->Handle(), p_ccb->local_cid, + p_ccb->remote_cid); } if (p_rcb && (p_rcb->psm != p_rcb->real_psm)) { @@ -1578,7 +1568,7 @@ void l2cu_release_ccb(tL2C_CCB* p_ccb) { l2c_fcr_cleanup(p_ccb); /* Channel may not be assigned to any LCB if it was just pre-reserved */ - if ((p_lcb) && ((p_ccb->local_cid >= L2CAP_BASE_APPL_CID))) { + if ((p_lcb) && (p_ccb->local_cid >= L2CAP_BASE_APPL_CID)) { l2cu_dequeue_ccb(p_ccb); /* Delink the CCB from the LCB */ @@ -1610,9 +1600,9 @@ void l2cu_release_ccb(tL2C_CCB* p_ccb) { if (!p_lcb->ccb_queue.p_first_ccb) { // Closing a security channel on LE device should not start connection // timeout - if (p_lcb->transport == BT_TRANSPORT_LE && - p_ccb->local_cid == L2CAP_SMP_CID) + if (p_lcb->transport == BT_TRANSPORT_LE && p_ccb->local_cid == L2CAP_SMP_CID) { return; + } l2cu_no_dynamic_ccbs(p_lcb); } else { @@ -1621,8 +1611,7 @@ void l2cu_release_ccb(tL2C_CCB* p_ccb) { } } else if (p_lcb->link_state == LST_CONNECTING) { if (!p_lcb->ccb_queue.p_first_ccb) { - if (p_lcb->transport == BT_TRANSPORT_LE && - p_ccb->local_cid == L2CAP_ATT_CID) { + if (p_lcb->transport == BT_TRANSPORT_LE && p_ccb->local_cid == L2CAP_ATT_CID) { log::warn("disconnecting the LE link"); l2cu_no_dynamic_ccbs(p_lcb); } @@ -1648,12 +1637,15 @@ tL2C_CCB* l2cu_find_ccb_by_remote_cid(tL2C_LCB* p_lcb, uint16_t remote_cid) { if (!p_lcb) { return NULL; } else { - for (p_ccb = p_lcb->ccb_queue.p_first_ccb; p_ccb; p_ccb = p_ccb->p_next_ccb) - if ((p_ccb->in_use) && (p_ccb->remote_cid == remote_cid)) return (p_ccb); + for (p_ccb = p_lcb->ccb_queue.p_first_ccb; p_ccb; p_ccb = p_ccb->p_next_ccb) { + if ((p_ccb->in_use) && (p_ccb->remote_cid == remote_cid)) { + return p_ccb; + } + } } /* If here, no match found */ - return (NULL); + return NULL; } /******************************************************************************* @@ -1674,12 +1666,12 @@ tL2C_RCB* l2cu_allocate_rcb(uint16_t psm) { if (!p_rcb->in_use) { p_rcb->in_use = true; p_rcb->psm = psm; - return (p_rcb); + return p_rcb; } } /* If here, no free RCB found */ - return (NULL); + return NULL; } /******************************************************************************* @@ -1700,12 +1692,12 @@ tL2C_RCB* l2cu_allocate_ble_rcb(uint16_t psm) { if (!p_rcb->in_use) { p_rcb->in_use = true; p_rcb->psm = psm; - return (p_rcb); + return p_rcb; } } /* If here, no free RCB found */ - return (NULL); + return NULL; } /******************************************************************************* @@ -1750,8 +1742,7 @@ void l2cu_disconnect_chnl(tL2C_CCB* p_ccb) { uint16_t local_cid = p_ccb->local_cid; if (local_cid >= L2CAP_BASE_APPL_CID) { - tL2CA_DISCONNECT_IND_CB* p_disc_cb = - p_ccb->p_rcb->api.pL2CA_DisconnectInd_Cb; + tL2CA_DISCONNECT_IND_CB* p_disc_cb = p_ccb->p_rcb->api.pL2CA_DisconnectInd_Cb; log::warn("L2CAP - disconnect_chnl CID: 0x{:04x}", local_cid); @@ -1781,11 +1772,13 @@ tL2C_RCB* l2cu_find_rcb_by_psm(uint16_t psm) { uint16_t xx; for (xx = 0; xx < MAX_L2CAP_CLIENTS; xx++, p_rcb++) { - if ((p_rcb->in_use) && (p_rcb->psm == psm)) return (p_rcb); + if ((p_rcb->in_use) && (p_rcb->psm == psm)) { + return p_rcb; + } } /* If here, no match found */ - return (NULL); + return NULL; } /******************************************************************************* @@ -1803,11 +1796,13 @@ tL2C_RCB* l2cu_find_ble_rcb_by_psm(uint16_t psm) { uint16_t xx; for (xx = 0; xx < BLE_MAX_L2CAP_CLIENTS; xx++, p_rcb++) { - if ((p_rcb->in_use) && (p_rcb->psm == psm)) return (p_rcb); + if ((p_rcb->in_use) && (p_rcb->psm == psm)) { + return p_rcb; + } } /* If here, no match found */ - return (NULL); + return NULL; } /******************************************************************************* @@ -1838,10 +1833,12 @@ uint8_t l2cu_process_peer_cfg_req(tL2C_CCB* p_ccb, tL2CAP_CFG_INFO* p_cfg) { bool fcr_ok = true; uint8_t fcr_status; uint16_t required_remote_mtu = - std::max(L2CAP_MIN_MTU, p_ccb->p_rcb->required_remote_mtu); + std::max(L2CAP_MIN_MTU, p_ccb->p_rcb->required_remote_mtu); /* Ignore FCR parameters for basic mode */ - if (!p_cfg->fcr_present) p_cfg->fcr.mode = L2CAP_FCR_BASIC_MODE; + if (!p_cfg->fcr_present) { + p_cfg->fcr.mode = L2CAP_FCR_BASIC_MODE; + } if (!p_cfg->mtu_present && required_remote_mtu > L2CAP_DEFAULT_MTU) { // We reject if we have a MTU requirement higher than default MTU @@ -1851,8 +1848,9 @@ uint8_t l2cu_process_peer_cfg_req(tL2C_CCB* p_ccb, tL2CAP_CFG_INFO* p_cfg) { /* Make sure MTU is at least the minimum */ if (p_cfg->mtu >= required_remote_mtu) { /* In basic mode, limit the MTU to our buffer size */ - if ((!p_cfg->fcr_present) && (p_cfg->mtu > L2CAP_MTU_SIZE)) + if ((!p_cfg->fcr_present) && (p_cfg->mtu > L2CAP_MTU_SIZE)) { p_cfg->mtu = L2CAP_MTU_SIZE; + } /* Save the accepted value in case of renegotiation */ p_ccb->peer_cfg.mtu = p_cfg->mtu; @@ -1881,8 +1879,7 @@ uint8_t l2cu_process_peer_cfg_req(tL2C_CCB* p_ccb, tL2CAP_CFG_INFO* p_cfg) { } } /* Reload flush_to from a previously accepted config request */ - else if (p_ccb->peer_cfg.flush_to_present && - !(p_ccb->config_done & IB_CFG_DONE)) { + else if (p_ccb->peer_cfg.flush_to_present && !(p_ccb->config_done & IB_CFG_DONE)) { p_cfg->flush_to_present = true; p_cfg->flush_to = p_ccb->peer_cfg.flush_to; } @@ -1913,7 +1910,7 @@ uint8_t l2cu_process_peer_cfg_req(tL2C_CCB* p_ccb, tL2CAP_CFG_INFO* p_cfg) { p_cfg->result = L2CAP_CFG_FAILED_NO_REASON; p_cfg->mtu_present = p_cfg->qos_present = p_cfg->flush_to_present = 0; - return (L2CAP_PEER_CFG_DISCONNECT); + return L2CAP_PEER_CFG_DISCONNECT; } fcr_ok = (fcr_status == L2CAP_PEER_CFG_OK); @@ -1921,16 +1918,24 @@ uint8_t l2cu_process_peer_cfg_req(tL2C_CCB* p_ccb, tL2CAP_CFG_INFO* p_cfg) { /* Return any unacceptable parameters */ if (mtu_ok && flush_to_ok && qos_type_ok && fcr_ok) { l2cu_adjust_out_mps(p_ccb); - return (L2CAP_PEER_CFG_OK); + return L2CAP_PEER_CFG_OK; } else { p_cfg->result = L2CAP_CFG_UNACCEPTABLE_PARAMS; - if (mtu_ok) p_cfg->mtu_present = false; - if (flush_to_ok) p_cfg->flush_to_present = false; - if (qos_type_ok) p_cfg->qos_present = false; - if (fcr_ok) p_cfg->fcr_present = false; + if (mtu_ok) { + p_cfg->mtu_present = false; + } + if (flush_to_ok) { + p_cfg->flush_to_present = false; + } + if (qos_type_ok) { + p_cfg->qos_present = false; + } + if (fcr_ok) { + p_cfg->fcr_present = false; + } - return (L2CAP_PEER_CFG_UNACCEPTABLE); + return L2CAP_PEER_CFG_UNACCEPTABLE; } } @@ -1948,8 +1953,9 @@ uint8_t l2cu_process_peer_cfg_req(tL2C_CCB* p_ccb, tL2CAP_CFG_INFO* p_cfg) { void l2cu_process_peer_cfg_rsp(tL2C_CCB* p_ccb, tL2CAP_CFG_INFO* p_cfg) { /* If we wanted QoS and the peer sends us a positive response with QoS, use * his values */ - if ((p_cfg->qos_present) && (p_ccb->our_cfg.qos_present)) + if ((p_cfg->qos_present) && (p_ccb->our_cfg.qos_present)) { p_ccb->our_cfg.qos = p_cfg->qos; + } if (p_cfg->fcr_present) { /* Save the retransmission and monitor timeout values */ @@ -1960,16 +1966,16 @@ void l2cu_process_peer_cfg_rsp(tL2C_CCB* p_ccb, tL2CAP_CFG_INFO* p_cfg) { /* Calculate the max number of packets for which we can delay sending an ack */ - if (p_cfg->fcr.tx_win_sz < p_ccb->our_cfg.fcr.tx_win_sz) + if (p_cfg->fcr.tx_win_sz < p_ccb->our_cfg.fcr.tx_win_sz) { p_ccb->fcrb.max_held_acks = p_cfg->fcr.tx_win_sz / 3; - else + } else { p_ccb->fcrb.max_held_acks = p_ccb->our_cfg.fcr.tx_win_sz / 3; + } log::verbose( - "l2cu_process_peer_cfg_rsp(): peer tx_win_sz: {}, our tx_win_sz: {}, " - "max_held_acks: {}", - p_cfg->fcr.tx_win_sz, p_ccb->our_cfg.fcr.tx_win_sz, - p_ccb->fcrb.max_held_acks); + "l2cu_process_peer_cfg_rsp(): peer tx_win_sz: {}, our tx_win_sz: {}, " + "max_held_acks: {}", + p_cfg->fcr.tx_win_sz, p_ccb->our_cfg.fcr.tx_win_sz, p_ccb->fcrb.max_held_acks); } } @@ -1993,9 +1999,9 @@ void l2cu_process_our_cfg_req(tL2C_CCB* p_ccb, tL2CAP_CFG_INFO* p_cfg) { if (p_cfg->fcr_present) { /* Override FCR options if attempting streaming or basic */ - if (p_cfg->fcr.mode == L2CAP_FCR_BASIC_MODE) + if (p_cfg->fcr.mode == L2CAP_FCR_BASIC_MODE) { memset(&p_cfg->fcr, 0, sizeof(tL2CAP_FCR_OPTS)); - else { + } else { /* On BR/EDR, timer values are zero in config request */ /* On class 2 AMP, timer value in config request shall be non-0 processing * time */ @@ -2033,10 +2039,11 @@ void l2cu_process_our_cfg_req(tL2C_CCB* p_ccb, tL2CAP_CFG_INFO* p_cfg) { void l2cu_process_our_cfg_rsp(tL2C_CCB* p_ccb, tL2CAP_CFG_INFO* p_cfg) { /* If peer wants QoS, we are allowed to change the values in a positive * response */ - if ((p_cfg->qos_present) && (p_ccb->peer_cfg.qos_present)) + if ((p_cfg->qos_present) && (p_ccb->peer_cfg.qos_present)) { p_ccb->peer_cfg.qos = p_cfg->qos; - else + } else { p_cfg->qos_present = false; + } l2c_fcr_adj_our_rsp_options(p_ccb, p_cfg); } @@ -2065,15 +2072,17 @@ void l2cu_device_reset(void) { /* This function initiates an acl connection to a LE device. * Returns true if request started successfully, false otherwise. */ bool l2cu_create_conn_le(tL2C_LCB* p_lcb) { - if (!bluetooth::shim::GetController()->SupportsBle()) return false; + if (!bluetooth::shim::GetController()->SupportsBle()) { + return false; + } p_lcb->transport = BT_TRANSPORT_LE; - return (l2cble_create_conn(p_lcb)); + return l2cble_create_conn(p_lcb); } /* This function initiates an acl connection to a Classic device via HCI. */ void l2cu_create_conn_br_edr(tL2C_LCB* p_lcb) { const bool controller_supports_role_switch = - bluetooth::shim::GetController()->SupportsRoleSwitch(); + bluetooth::shim::GetController()->SupportsRoleSwitch(); /* While creating a new classic connection, check check all the other * active connections where we are not SCO nor central. @@ -2082,13 +2091,19 @@ void l2cu_create_conn_br_edr(tL2C_LCB* p_lcb) { */ tL2C_LCB* p_lcb_cur = &l2cb.lcb_pool[0]; for (uint8_t xx = 0; xx < MAX_L2CAP_LINKS; xx++, p_lcb_cur++) { - if (p_lcb_cur == p_lcb) continue; - if (!p_lcb_cur->in_use) continue; + if (p_lcb_cur == p_lcb) { + continue; + } + if (!p_lcb_cur->in_use) { + continue; + } if (BTM_IsScoActiveByBdaddr(p_lcb_cur->remote_bd_addr)) { log::verbose("Central peripheral switch not allowed when SCO active"); continue; } - if (p_lcb->IsLinkRoleCentral()) continue; + if (p_lcb->IsLinkRoleCentral()) { + continue; + } /* The LMP_switch_req shall be sent only if the ACL logical transport is in active mode, when encryption is disabled, and all synchronous logical transports on the same physical link are disabled." */ @@ -2100,10 +2115,8 @@ void l2cu_create_conn_br_edr(tL2C_LCB* p_lcb) { p_lcb->link_state = LST_CONNECTING_WAIT_SWITCH; p_lcb->SetLinkRoleAsCentral(); - if (BTM_SwitchRoleToCentral(p_lcb_cur->remote_bd_addr) == - BTM_CMD_STARTED) { - alarm_set_on_mloop(p_lcb->l2c_lcb_timer, - L2CAP_LINK_ROLE_SWITCH_TIMEOUT_MS, + if (BTM_SwitchRoleToCentral(p_lcb_cur->remote_bd_addr) == BTM_CMD_STARTED) { + alarm_set_on_mloop(p_lcb->l2c_lcb_timer, L2CAP_LINK_ROLE_SWITCH_TIMEOUT_MS, l2c_lcb_timer_timeout, p_lcb); return; } @@ -2146,8 +2159,8 @@ uint8_t l2cu_get_num_hi_priority(void) { void l2cu_create_conn_after_switch(tL2C_LCB* p_lcb) { bluetooth::shim::ACL_CreateClassicConnection(p_lcb->remote_bd_addr); - alarm_set_on_mloop(p_lcb->l2c_lcb_timer, L2CAP_LINK_CONNECT_TIMEOUT_MS, - l2c_lcb_timer_timeout, p_lcb); + alarm_set_on_mloop(p_lcb->l2c_lcb_timer, L2CAP_LINK_CONNECT_TIMEOUT_MS, l2c_lcb_timer_timeout, + p_lcb); } /******************************************************************************* @@ -2166,12 +2179,12 @@ tL2C_LCB* l2cu_find_lcb_by_state(tL2C_LINK_STATE state) { for (i = 0; i < MAX_L2CAP_LINKS; i++, p_lcb++) { if ((p_lcb->in_use) && (p_lcb->link_state == state)) { - return (p_lcb); + return p_lcb; } } /* If here, no match found */ - return (NULL); + return NULL; } /******************************************************************************* @@ -2197,8 +2210,7 @@ bool l2cu_lcb_disconnecting(void) { for (i = 0; i < MAX_L2CAP_LINKS; i++, p_lcb++) { if (p_lcb->in_use) { /* no ccbs on lcb, or lcb is in disconnecting state */ - if ((!p_lcb->ccb_queue.p_first_ccb) || - (p_lcb->link_state == LST_DISCONNECTING)) { + if ((!p_lcb->ccb_queue.p_first_ccb) || (p_lcb->link_state == LST_DISCONNECTING)) { status = true; break; } @@ -2206,9 +2218,8 @@ bool l2cu_lcb_disconnecting(void) { else if (p_lcb->ccb_queue.p_first_ccb == p_lcb->ccb_queue.p_last_ccb) { p_ccb = p_lcb->ccb_queue.p_first_ccb; - if ((p_ccb->in_use) && - ((p_ccb->chnl_state == CST_W4_L2CAP_DISCONNECT_RSP) || - (p_ccb->chnl_state == CST_W4_L2CA_DISCONNECT_RSP))) { + if ((p_ccb->in_use) && ((p_ccb->chnl_state == CST_W4_L2CAP_DISCONNECT_RSP) || + (p_ccb->chnl_state == CST_W4_L2CA_DISCONNECT_RSP))) { status = true; break; } @@ -2229,13 +2240,11 @@ bool l2cu_lcb_disconnecting(void) { * ******************************************************************************/ -static void l2cu_set_acl_priority_latency_brcm(tL2C_LCB* p_lcb, - tL2CAP_PRIORITY priority) { +static void l2cu_set_acl_priority_latency_brcm(tL2C_LCB* p_lcb, tL2CAP_PRIORITY priority) { uint8_t vs_param; if (priority == L2CAP_PRIORITY_HIGH) { // priority to high, if using latency mode check preset latency - if (p_lcb->use_latency_mode && - p_lcb->preset_acl_latency == L2CAP_LATENCY_LOW) { + if (p_lcb->use_latency_mode && p_lcb->preset_acl_latency == L2CAP_LATENCY_LOW) { log::info("Set ACL priority: High Priority and Low Latency Mode"); vs_param = HCI_BRCM_ACL_HIGH_PRIORITY_LOW_LATENCY; p_lcb->set_latency(L2CAP_LATENCY_LOW); @@ -2256,8 +2265,7 @@ static void l2cu_set_acl_priority_latency_brcm(tL2C_LCB* p_lcb, UINT8_TO_STREAM(pp, vs_param); get_btm_client_interface().vendor.BTM_VendorSpecificCommand( - HCI_BRCM_SET_ACL_PRIORITY, HCI_BRCM_ACL_PRIORITY_PARAM_SIZE, command, - NULL); + HCI_BRCM_SET_ACL_PRIORITY, HCI_BRCM_ACL_PRIORITY_PARAM_SIZE, command, NULL); } /******************************************************************************* @@ -2271,13 +2279,11 @@ static void l2cu_set_acl_priority_latency_brcm(tL2C_LCB* p_lcb, * ******************************************************************************/ -static void l2cu_set_acl_priority_latency_syna(tL2C_LCB* p_lcb, - tL2CAP_PRIORITY priority) { +static void l2cu_set_acl_priority_latency_syna(tL2C_LCB* p_lcb, tL2CAP_PRIORITY priority) { uint8_t vs_param; if (priority == L2CAP_PRIORITY_HIGH) { // priority to high, if using latency mode check preset latency - if (p_lcb->use_latency_mode && - p_lcb->preset_acl_latency == L2CAP_LATENCY_LOW) { + if (p_lcb->use_latency_mode && p_lcb->preset_acl_latency == L2CAP_LATENCY_LOW) { log::info("Set ACL priority: High Priority and Low Latency Mode"); vs_param = HCI_SYNA_ACL_HIGH_PRIORITY_LOW_LATENCY; p_lcb->set_latency(L2CAP_LATENCY_LOW); @@ -2298,8 +2304,7 @@ static void l2cu_set_acl_priority_latency_syna(tL2C_LCB* p_lcb, UINT8_TO_STREAM(pp, vs_param); get_btm_client_interface().vendor.BTM_VendorSpecificCommand( - HCI_SYNA_SET_ACL_PRIORITY, HCI_SYNA_ACL_PRIORITY_PARAM_SIZE, command, - NULL); + HCI_SYNA_SET_ACL_PRIORITY, HCI_SYNA_ACL_PRIORITY_PARAM_SIZE, command, NULL); } /******************************************************************************* @@ -2312,8 +2317,7 @@ static void l2cu_set_acl_priority_latency_syna(tL2C_LCB* p_lcb, * ******************************************************************************/ -static void l2cu_set_acl_priority_unisoc(tL2C_LCB* p_lcb, - tL2CAP_PRIORITY priority) { +static void l2cu_set_acl_priority_unisoc(tL2C_LCB* p_lcb, tL2CAP_PRIORITY priority) { uint8_t vs_param; if (priority == L2CAP_PRIORITY_HIGH) { // priority to high @@ -2331,8 +2335,7 @@ static void l2cu_set_acl_priority_unisoc(tL2C_LCB* p_lcb, UINT8_TO_STREAM(pp, vs_param); get_btm_client_interface().vendor.BTM_VendorSpecificCommand( - HCI_UNISOC_SET_ACL_PRIORITY, HCI_UNISOC_ACL_PRIORITY_PARAM_SIZE, command, - NULL); + HCI_UNISOC_SET_ACL_PRIORITY, HCI_UNISOC_ACL_PRIORITY_PARAM_SIZE, command, NULL); } /******************************************************************************* @@ -2357,7 +2360,7 @@ bool l2cu_set_acl_priority(const RawAddress& bd_addr, tL2CAP_PRIORITY priority, p_lcb = l2cu_find_lcb_by_bd_addr(bd_addr, BT_TRANSPORT_BR_EDR); if (p_lcb == NULL) { log::warn("L2CAP - no LCB for L2CA_SetAclPriority"); - return (false); + return false; } /* Link priority is set if: @@ -2367,9 +2370,7 @@ bool l2cu_set_acl_priority(const RawAddress& bd_addr, tL2CAP_PRIORITY priority, (reset_after_rs && p_lcb->acl_priority == L2CAP_PRIORITY_HIGH)) { #ifndef TARGET_FLOSS /* Use vendor specific commands to set the link priority */ - switch (bluetooth::shim::GetController() - ->GetLocalVersionInformation() - .manufacturer_name_) { + switch (bluetooth::shim::GetController()->GetLocalVersionInformation().manufacturer_name_) { case LMP_COMPID_BROADCOM: l2cu_set_acl_priority_latency_brcm(p_lcb, priority); break; @@ -2394,7 +2395,7 @@ bool l2cu_set_acl_priority(const RawAddress& bd_addr, tL2CAP_PRIORITY priority, p_lcb->acl_priority = priority; l2c_link_adjust_allocation(); } - return (true); + return true; } /******************************************************************************* @@ -2408,20 +2409,17 @@ bool l2cu_set_acl_priority(const RawAddress& bd_addr, tL2CAP_PRIORITY priority, ******************************************************************************/ static void l2cu_set_acl_latency_brcm(tL2C_LCB* p_lcb, tL2CAP_LATENCY latency) { - log::info("Set ACL latency: {}", - latency == L2CAP_LATENCY_LOW ? "Low Latancy" : "Normal Latency"); + log::info("Set ACL latency: {}", latency == L2CAP_LATENCY_LOW ? "Low Latancy" : "Normal Latency"); uint8_t command[HCI_BRCM_ACL_PRIORITY_PARAM_SIZE]; uint8_t* pp = command; - uint8_t vs_param = latency == L2CAP_LATENCY_LOW - ? HCI_BRCM_ACL_HIGH_PRIORITY_LOW_LATENCY - : HCI_BRCM_ACL_HIGH_PRIORITY; + uint8_t vs_param = latency == L2CAP_LATENCY_LOW ? HCI_BRCM_ACL_HIGH_PRIORITY_LOW_LATENCY + : HCI_BRCM_ACL_HIGH_PRIORITY; UINT16_TO_STREAM(pp, p_lcb->Handle()); UINT8_TO_STREAM(pp, vs_param); get_btm_client_interface().vendor.BTM_VendorSpecificCommand( - HCI_BRCM_SET_ACL_PRIORITY, HCI_BRCM_ACL_PRIORITY_PARAM_SIZE, command, - NULL); + HCI_BRCM_SET_ACL_PRIORITY, HCI_BRCM_ACL_PRIORITY_PARAM_SIZE, command, NULL); } /******************************************************************************* @@ -2435,20 +2433,17 @@ static void l2cu_set_acl_latency_brcm(tL2C_LCB* p_lcb, tL2CAP_LATENCY latency) { ******************************************************************************/ static void l2cu_set_acl_latency_syna(tL2C_LCB* p_lcb, tL2CAP_LATENCY latency) { - log::info("Set ACL latency: {}", - latency == L2CAP_LATENCY_LOW ? "Low Latancy" : "Normal Latency"); + log::info("Set ACL latency: {}", latency == L2CAP_LATENCY_LOW ? "Low Latancy" : "Normal Latency"); uint8_t command[HCI_SYNA_ACL_PRIORITY_PARAM_SIZE]; uint8_t* pp = command; - uint8_t vs_param = latency == L2CAP_LATENCY_LOW - ? HCI_SYNA_ACL_HIGH_PRIORITY_LOW_LATENCY - : HCI_SYNA_ACL_HIGH_PRIORITY; + uint8_t vs_param = latency == L2CAP_LATENCY_LOW ? HCI_SYNA_ACL_HIGH_PRIORITY_LOW_LATENCY + : HCI_SYNA_ACL_HIGH_PRIORITY; UINT16_TO_STREAM(pp, p_lcb->Handle()); UINT8_TO_STREAM(pp, vs_param); get_btm_client_interface().vendor.BTM_VendorSpecificCommand( - HCI_SYNA_SET_ACL_PRIORITY, HCI_SYNA_ACL_PRIORITY_PARAM_SIZE, command, - NULL); + HCI_SYNA_SET_ACL_PRIORITY, HCI_SYNA_ACL_PRIORITY_PARAM_SIZE, command, NULL); } /******************************************************************************* @@ -2462,23 +2457,20 @@ static void l2cu_set_acl_latency_syna(tL2C_LCB* p_lcb, tL2CAP_LATENCY latency) { ******************************************************************************/ static void l2cu_set_acl_latency_mtk(tL2CAP_LATENCY latency) { - log::info("Set ACL latency: {}", - latency == L2CAP_LATENCY_LOW ? "Low Latancy" : "Normal Latency"); + log::info("Set ACL latency: {}", latency == L2CAP_LATENCY_LOW ? "Low Latancy" : "Normal Latency"); uint8_t command[HCI_MTK_ACL_PRIORITY_PARAM_SIZE]; uint8_t* pp = command; - uint8_t vs_param = latency == L2CAP_LATENCY_LOW - ? HCI_MTK_ACL_HIGH_PRIORITY - : HCI_MTK_ACL_NORMAL_PRIORITY; + uint8_t vs_param = + latency == L2CAP_LATENCY_LOW ? HCI_MTK_ACL_HIGH_PRIORITY : HCI_MTK_ACL_NORMAL_PRIORITY; UINT8_TO_STREAM(pp, vs_param); UINT8_TO_STREAM(pp, 0); - UINT16_TO_STREAM(pp, 0); //reserved bytes + UINT16_TO_STREAM(pp, 0); // reserved bytes get_btm_client_interface().vendor.BTM_VendorSpecificCommand( - HCI_MTK_SET_ACL_PRIORITY, HCI_MTK_ACL_PRIORITY_PARAM_SIZE, command, NULL); + HCI_MTK_SET_ACL_PRIORITY, HCI_MTK_ACL_PRIORITY_PARAM_SIZE, command, NULL); } - /******************************************************************************* * * Function l2cu_set_acl_latency @@ -2500,11 +2492,8 @@ bool l2cu_set_acl_latency(const RawAddress& bd_addr, tL2CAP_LATENCY latency) { return false; } /* only change controller's latency when stream using latency mode */ - if (p_lcb->use_latency_mode && p_lcb->is_high_priority() && - latency != p_lcb->acl_latency) { - switch (bluetooth::shim::GetController() - ->GetLocalVersionInformation() - .manufacturer_name_) { + if (p_lcb->use_latency_mode && p_lcb->is_high_priority() && latency != p_lcb->acl_latency) { + switch (bluetooth::shim::GetController()->GetLocalVersionInformation().manufacturer_name_) { case LMP_COMPID_BROADCOM: l2cu_set_acl_latency_brcm(p_lcb, latency); break; @@ -2539,11 +2528,11 @@ bool l2cu_set_acl_latency(const RawAddress& bd_addr, tL2CAP_LATENCY latency) { * ******************************************************************************/ void l2cu_set_non_flushable_pbf(bool is_supported) { - if (is_supported) - l2cb.non_flushable_pbf = - (L2CAP_PKT_START_NON_FLUSHABLE << L2CAP_PKT_TYPE_SHIFT); - else + if (is_supported) { + l2cb.non_flushable_pbf = (L2CAP_PKT_START_NON_FLUSHABLE << L2CAP_PKT_TYPE_SHIFT); + } else { l2cb.non_flushable_pbf = (L2CAP_PKT_START << L2CAP_PKT_TYPE_SHIFT); + } } /******************************************************************************* @@ -2580,8 +2569,7 @@ void l2cu_resubmit_pending_sec_req(const RawAddress* p_bda) { } } else { /* No BDA pasesed in, so check all links */ - for (xx = 0, p_lcb = &l2cb.lcb_pool[0]; xx < MAX_L2CAP_LINKS; - xx++, p_lcb++) { + for (xx = 0, p_lcb = &l2cb.lcb_pool[0]; xx < MAX_L2CAP_LINKS; xx++, p_lcb++) { if (p_lcb->in_use) { /* For all channels, send the event through their FSMs */ for (p_ccb = p_lcb->ccb_queue.p_first_ccb; p_ccb; p_ccb = p_next_ccb) { @@ -2620,18 +2608,17 @@ void l2cu_adjust_out_mps(tL2C_CCB* p_ccb) { uint16_t packet_size; /* on the tx side MTU is selected based on packet size of the controller */ - packet_size = get_btm_client_interface().peer.BTM_GetMaxPacketSize( - p_ccb->p_lcb->remote_bd_addr); + packet_size = get_btm_client_interface().peer.BTM_GetMaxPacketSize(p_ccb->p_lcb->remote_bd_addr); - if (packet_size <= (L2CAP_PKT_OVERHEAD + L2CAP_FCR_OVERHEAD + - L2CAP_SDU_LEN_OVERHEAD + L2CAP_FCS_LEN)) { + if (packet_size <= + (L2CAP_PKT_OVERHEAD + L2CAP_FCR_OVERHEAD + L2CAP_SDU_LEN_OVERHEAD + L2CAP_FCS_LEN)) { /* something is very wrong */ - log::error("l2cu_adjust_out_mps bad packet size: {} will use MPS: {}", - packet_size, p_ccb->peer_cfg.fcr.mps); + log::error("l2cu_adjust_out_mps bad packet size: {} will use MPS: {}", packet_size, + p_ccb->peer_cfg.fcr.mps); p_ccb->tx_mps = p_ccb->peer_cfg.fcr.mps; } else { - packet_size -= (L2CAP_PKT_OVERHEAD + L2CAP_FCR_OVERHEAD + - L2CAP_SDU_LEN_OVERHEAD + L2CAP_FCS_LEN); + packet_size -= + (L2CAP_PKT_OVERHEAD + L2CAP_FCR_OVERHEAD + L2CAP_SDU_LEN_OVERHEAD + L2CAP_FCS_LEN); /* We try to negotiate MTU that each packet can be split into whole number of max packets. For example if link is 1.2 max packet size is 339 @@ -2644,15 +2631,16 @@ void l2cu_adjust_out_mps(tL2C_CCB* p_ccb) { For EDR 2.0 packet size is 1027. So we better send RFCOMM packet as 1 3DH5 packet 1 * 1027 = 1027. Minus 4 bytes L2CAP header 1023. */ - if (p_ccb->peer_cfg.fcr.mps >= packet_size) + if (p_ccb->peer_cfg.fcr.mps >= packet_size) { p_ccb->tx_mps = p_ccb->peer_cfg.fcr.mps / packet_size * packet_size; - else + } else { p_ccb->tx_mps = p_ccb->peer_cfg.fcr.mps; + } log::verbose( - "l2cu_adjust_out_mps use {} Based on peer_cfg.fcr.mps: {} " - "packet_size: {}", - p_ccb->tx_mps, p_ccb->peer_cfg.fcr.mps, packet_size); + "l2cu_adjust_out_mps use {} Based on peer_cfg.fcr.mps: {} " + "packet_size: {}", + p_ccb->tx_mps, p_ccb->peer_cfg.fcr.mps, packet_size); } } @@ -2675,18 +2663,19 @@ bool l2cu_initialize_fixed_ccb(tL2C_LCB* p_lcb, uint16_t fixed_cid) { * NOTE: The "in_use" check is needed to ignore leftover entries * that have been already released by l2cu_release_ccb(). */ - return (true); + return true; } p_ccb = l2cu_allocate_ccb(NULL, 0); - if (p_ccb == NULL) return (false); + if (p_ccb == NULL) { + return false; + } if (p_lcb->link_state == LST_DISCONNECTED) { alarm_cancel(p_lcb->l2c_lcb_timer); } else { - log::warn( - "Unable to cancel link control block for link connection to device {}", - p_lcb->remote_bd_addr); + log::warn("Unable to cancel link control block for link connection to device {}", + p_lcb->remote_bd_addr); } /* Set CID for the connection */ @@ -2700,12 +2689,14 @@ bool l2cu_initialize_fixed_ccb(tL2C_LCB* p_lcb, uint16_t fixed_cid) { p_ccb->p_lcb = p_lcb; /* There is no configuration, so if the link is up, the channel is up */ - if (p_lcb->link_state == LST_CONNECTED) p_ccb->chnl_state = CST_OPEN; + if (p_lcb->link_state == LST_CONNECTED) { + p_ccb->chnl_state = CST_OPEN; + } /* Set the default idle timeout value to use */ p_ccb->fixed_chnl_idle_tout = - l2cb.fixed_reg[fixed_cid - L2CAP_FIRST_FIXED_CHNL].default_idle_tout; - return (true); + l2cb.fixed_reg[fixed_cid - L2CAP_FIRST_FIXED_CHNL].default_idle_tout; + return true; } /******************************************************************************* @@ -2730,8 +2721,7 @@ void l2cu_no_dynamic_ccbs(tL2C_LCB* p_lcb) { for (xx = 0; xx < L2CAP_NUM_FIXED_CHNLS; xx++) { if ((p_lcb->p_fixed_ccbs[xx] != NULL) && (p_lcb->p_fixed_ccbs[xx]->fixed_chnl_idle_tout * 1000 > timeout_ms)) { - if (p_lcb->p_fixed_ccbs[xx]->fixed_chnl_idle_tout == - L2CAP_NO_IDLE_TIMEOUT) { + if (p_lcb->p_fixed_ccbs[xx]->fixed_chnl_idle_tout == L2CAP_NO_IDLE_TIMEOUT) { log::verbose("NO IDLE timeout set for fixed cid 0x{:04x}", p_lcb->p_fixed_ccbs[xx]->local_cid); start_timeout = false; @@ -2741,7 +2731,9 @@ void l2cu_no_dynamic_ccbs(tL2C_LCB* p_lcb) { } /* If the link is pairing, do not mess with the timeouts */ - if (p_lcb->IsBonding()) return; + if (p_lcb->IsBonding()) { + return; + } log::verbose("l2cu_no_dynamic_ccbs() with_active_local_clients={}", p_lcb->with_active_local_clients); @@ -2756,9 +2748,8 @@ void l2cu_no_dynamic_ccbs(tL2C_LCB* p_lcb) { if (timeout_ms == 0) { log::verbose("l2cu_no_dynamic_ccbs() IDLE timer 0, disconnecting link"); - rc = btm_sec_disconnect( - p_lcb->Handle(), HCI_ERR_PEER_USER, - "stack::l2cap::l2c_utils::l2cu_no_dynamic_ccbs Idle timer popped"); + rc = btm_sec_disconnect(p_lcb->Handle(), HCI_ERR_PEER_USER, + "stack::l2cap::l2c_utils::l2cu_no_dynamic_ccbs Idle timer popped"); if (rc == BTM_CMD_STARTED) { l2cu_process_fixed_disc_cback(p_lcb); p_lcb->link_state = LST_DISCONNECTING; @@ -2771,8 +2762,8 @@ void l2cu_no_dynamic_ccbs(tL2C_LCB* p_lcb) { start_timeout = false; } else if (p_lcb->IsBonding()) { acl_disconnect_from_handle( - p_lcb->Handle(), HCI_ERR_PEER_USER, - "stack::l2cap::l2c_utils::l2cu_no_dynamic_ccbs Bonding no traffic"); + p_lcb->Handle(), HCI_ERR_PEER_USER, + "stack::l2cap::l2c_utils::l2cu_no_dynamic_ccbs Bonding no traffic"); l2cu_process_fixed_disc_cback(p_lcb); p_lcb->link_state = LST_DISCONNECTING; timeout_ms = L2CAP_LINK_DISCONNECT_TIMEOUT_MS; @@ -2783,8 +2774,7 @@ void l2cu_no_dynamic_ccbs(tL2C_LCB* p_lcb) { } if (start_timeout) { - alarm_set_on_mloop(p_lcb->l2c_lcb_timer, timeout_ms, l2c_lcb_timer_timeout, - p_lcb); + alarm_set_on_mloop(p_lcb->l2c_lcb_timer, timeout_ms, l2c_lcb_timer_timeout, p_lcb); log::debug("Started link IDLE timeout_ms:{}", (unsigned long)timeout_ms); } else { alarm_cancel(p_lcb->l2c_lcb_timer); @@ -2803,11 +2793,11 @@ void l2cu_no_dynamic_ccbs(tL2C_LCB* p_lcb) { void l2cu_process_fixed_chnl_resp(tL2C_LCB* p_lcb) { if (p_lcb->transport == BT_TRANSPORT_BR_EDR) { /* ignore all not assigned BR/EDR channels */ - p_lcb->peer_chnl_mask[0] &= - (L2CAP_FIXED_CHNL_SIG_BIT | L2CAP_FIXED_CHNL_CNCTLESS_BIT | - L2CAP_FIXED_CHNL_SMP_BR_BIT); - } else + p_lcb->peer_chnl_mask[0] &= (L2CAP_FIXED_CHNL_SIG_BIT | L2CAP_FIXED_CHNL_CNCTLESS_BIT | + L2CAP_FIXED_CHNL_SMP_BR_BIT); + } else { p_lcb->peer_chnl_mask[0] = l2cb.l2c_ble_fixed_chnls_mask; + } /* Tell all registered fixed channels about the connection */ for (int xx = 0; xx < L2CAP_NUM_FIXED_CHNLS; xx++) { @@ -2816,25 +2806,29 @@ void l2cu_process_fixed_chnl_resp(tL2C_LCB* p_lcb) { /* See BT Spec Ver 5.0 | Vol 3, Part A 2.1 table 2.1 and 2.2 */ /* skip sending LE fix channel callbacks on BR/EDR links */ - if (p_lcb->transport == BT_TRANSPORT_BR_EDR && - channel_id >= L2CAP_ATT_CID && channel_id <= L2CAP_SMP_CID) + if (p_lcb->transport == BT_TRANSPORT_BR_EDR && channel_id >= L2CAP_ATT_CID && + channel_id <= L2CAP_SMP_CID) { continue; + } /* skip sending BR fix channel callbacks on LE links */ - if (p_lcb->transport == BT_TRANSPORT_LE && channel_id == L2CAP_SMP_BR_CID) + if (p_lcb->transport == BT_TRANSPORT_LE && channel_id == L2CAP_SMP_BR_CID) { continue; + } - if (!l2cb.fixed_reg[xx].pL2CA_FixedConn_Cb) continue; + if (!l2cb.fixed_reg[xx].pL2CA_FixedConn_Cb) { + continue; + } if (p_lcb->peer_chnl_mask[(channel_id) / 8] & (1 << ((channel_id) % 8))) { - if (p_lcb->p_fixed_ccbs[xx]) + if (p_lcb->p_fixed_ccbs[xx]) { p_lcb->p_fixed_ccbs[xx]->chnl_state = CST_OPEN; - (*l2cb.fixed_reg[xx].pL2CA_FixedConn_Cb)( - channel_id, p_lcb->remote_bd_addr, true, 0, p_lcb->transport); + } + (*l2cb.fixed_reg[xx].pL2CA_FixedConn_Cb)(channel_id, p_lcb->remote_bd_addr, true, 0, + p_lcb->transport); } else { - (*l2cb.fixed_reg[xx].pL2CA_FixedConn_Cb)( - channel_id, p_lcb->remote_bd_addr, false, p_lcb->DisconnectReason(), - p_lcb->transport); + (*l2cb.fixed_reg[xx].pL2CA_FixedConn_Cb)(channel_id, p_lcb->remote_bd_addr, false, + p_lcb->DisconnectReason(), p_lcb->transport); if (p_lcb->p_fixed_ccbs[xx]) { l2cu_release_ccb(p_lcb->p_fixed_ccbs[xx]); @@ -2855,12 +2849,13 @@ void l2cu_process_fixed_chnl_resp(tL2C_LCB* p_lcb) { * ******************************************************************************/ void l2cu_process_fixed_disc_cback(tL2C_LCB* p_lcb) { - /* Select peer channels mask to use depending on transport */ uint8_t peer_channel_mask = p_lcb->peer_chnl_mask[0]; // For LE, reset the stored peer channel mask - if (p_lcb->transport == BT_TRANSPORT_LE) p_lcb->peer_chnl_mask[0] = 0; + if (p_lcb->transport == BT_TRANSPORT_LE) { + p_lcb->peer_chnl_mask[0] = 0; + } for (int xx = 0; xx < L2CAP_NUM_FIXED_CHNLS; xx++) { if (p_lcb->p_fixed_ccbs[xx]) { @@ -2869,15 +2864,15 @@ void l2cu_process_fixed_disc_cback(tL2C_LCB* p_lcb) { p_l2c_chnl_ctrl_block = p_lcb->p_fixed_ccbs[xx]; p_lcb->p_fixed_ccbs[xx] = NULL; l2cu_release_ccb(p_l2c_chnl_ctrl_block); - (*l2cb.fixed_reg[xx].pL2CA_FixedConn_Cb)( - xx + L2CAP_FIRST_FIXED_CHNL, p_lcb->remote_bd_addr, false, - p_lcb->DisconnectReason(), p_lcb->transport); + (*l2cb.fixed_reg[xx].pL2CA_FixedConn_Cb)(xx + L2CAP_FIRST_FIXED_CHNL, p_lcb->remote_bd_addr, + false, p_lcb->DisconnectReason(), + p_lcb->transport); } } else if ((peer_channel_mask & (1 << (xx + L2CAP_FIRST_FIXED_CHNL))) && - (l2cb.fixed_reg[xx].pL2CA_FixedConn_Cb != NULL)) - (*l2cb.fixed_reg[xx].pL2CA_FixedConn_Cb)( - xx + L2CAP_FIRST_FIXED_CHNL, p_lcb->remote_bd_addr, false, - p_lcb->DisconnectReason(), p_lcb->transport); + (l2cb.fixed_reg[xx].pL2CA_FixedConn_Cb != NULL)) { + (*l2cb.fixed_reg[xx].pL2CA_FixedConn_Cb)(xx + L2CAP_FIRST_FIXED_CHNL, p_lcb->remote_bd_addr, + false, p_lcb->DisconnectReason(), p_lcb->transport); + } } } @@ -2891,9 +2886,8 @@ void l2cu_process_fixed_disc_cback(tL2C_LCB* p_lcb) { * Returns void * ******************************************************************************/ -void l2cu_send_peer_ble_par_req(tL2C_LCB* p_lcb, uint16_t min_int, - uint16_t max_int, uint16_t latency, - uint16_t timeout) { +void l2cu_send_peer_ble_par_req(tL2C_LCB* p_lcb, uint16_t min_int, uint16_t max_int, + uint16_t latency, uint16_t timeout) { BT_HDR* p_buf; uint8_t* p; @@ -2901,15 +2895,15 @@ void l2cu_send_peer_ble_par_req(tL2C_LCB* p_lcb, uint16_t min_int, p_lcb->signal_id++; l2cu_adj_id(p_lcb); - p_buf = l2cu_build_header(p_lcb, L2CAP_CMD_BLE_UPD_REQ_LEN, - L2CAP_CMD_BLE_UPDATE_REQ, p_lcb->signal_id); + p_buf = l2cu_build_header(p_lcb, L2CAP_CMD_BLE_UPD_REQ_LEN, L2CAP_CMD_BLE_UPDATE_REQ, + p_lcb->signal_id); if (p_buf == NULL) { log::warn("l2cu_send_peer_ble_par_req - no buffer"); return; } - p = (uint8_t*)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + - L2CAP_PKT_OVERHEAD + L2CAP_CMD_OVERHEAD; + p = (uint8_t*)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + L2CAP_PKT_OVERHEAD + + L2CAP_CMD_OVERHEAD; UINT16_TO_STREAM(p, min_int); UINT16_TO_STREAM(p, max_int); @@ -2929,20 +2923,18 @@ void l2cu_send_peer_ble_par_req(tL2C_LCB* p_lcb, uint16_t min_int, * Returns void * ******************************************************************************/ -void l2cu_send_peer_ble_par_rsp(tL2C_LCB* p_lcb, uint16_t reason, - uint8_t rem_id) { +void l2cu_send_peer_ble_par_rsp(tL2C_LCB* p_lcb, uint16_t reason, uint8_t rem_id) { BT_HDR* p_buf; uint8_t* p; - p_buf = l2cu_build_header(p_lcb, L2CAP_CMD_BLE_UPD_RSP_LEN, - L2CAP_CMD_BLE_UPDATE_RSP, rem_id); + p_buf = l2cu_build_header(p_lcb, L2CAP_CMD_BLE_UPD_RSP_LEN, L2CAP_CMD_BLE_UPDATE_RSP, rem_id); if (p_buf == NULL) { log::warn("l2cu_send_peer_ble_par_rsp - no buffer"); return; } - p = (uint8_t*)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + - L2CAP_PKT_OVERHEAD + L2CAP_CMD_OVERHEAD; + p = (uint8_t*)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + L2CAP_PKT_OVERHEAD + + L2CAP_CMD_OVERHEAD; UINT16_TO_STREAM(p, reason); @@ -2967,7 +2959,9 @@ void l2cu_send_peer_ble_credit_based_conn_req(tL2C_CCB* p_ccb) { uint16_t mps; uint16_t initial_credit; - if (!p_ccb) return; + if (!p_ccb) { + return; + } p_lcb = p_ccb->p_lcb; /* Create an identifier for this packet */ @@ -2976,25 +2970,24 @@ void l2cu_send_peer_ble_credit_based_conn_req(tL2C_CCB* p_ccb) { p_ccb->local_id = p_ccb->p_lcb->signal_id; - p_buf = - l2cu_build_header(p_lcb, L2CAP_CMD_BLE_CREDIT_BASED_CONN_REQ_LEN, - L2CAP_CMD_BLE_CREDIT_BASED_CONN_REQ, p_lcb->signal_id); + p_buf = l2cu_build_header(p_lcb, L2CAP_CMD_BLE_CREDIT_BASED_CONN_REQ_LEN, + L2CAP_CMD_BLE_CREDIT_BASED_CONN_REQ, p_lcb->signal_id); if (p_buf == NULL) { log::warn("l2cu_send_peer_ble_credit_based_conn_req - no buffer"); return; } - p = (uint8_t*)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + - L2CAP_PKT_OVERHEAD + L2CAP_CMD_OVERHEAD; + p = (uint8_t*)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + L2CAP_PKT_OVERHEAD + + L2CAP_CMD_OVERHEAD; mtu = p_ccb->local_conn_cfg.mtu; mps = p_ccb->local_conn_cfg.mps; initial_credit = p_ccb->local_conn_cfg.credits; log::verbose( - "l2cu_send_peer_ble_credit_based_conn_req PSM:0x{:04x} local_cid:{} " - "mtu:{} mps:{} initial_credit:{}", - p_ccb->p_rcb->real_psm, p_ccb->local_cid, mtu, mps, initial_credit); + "l2cu_send_peer_ble_credit_based_conn_req PSM:0x{:04x} local_cid:{} " + "mtu:{} mps:{} initial_credit:{}", + p_ccb->p_rcb->real_psm, p_ccb->local_cid, mtu, mps, initial_credit); UINT16_TO_STREAM(p, p_ccb->p_rcb->real_psm); UINT16_TO_STREAM(p, p_ccb->local_cid); @@ -3023,7 +3016,9 @@ void l2cu_send_peer_credit_based_conn_req(tL2C_CCB* p_ccb) { uint16_t mps; uint16_t initial_credit; - if (!p_ccb) return; + if (!p_ccb) { + return; + } p_lcb = p_ccb->p_lcb; @@ -3033,25 +3028,23 @@ void l2cu_send_peer_credit_based_conn_req(tL2C_CCB* p_ccb) { p_ccb->local_id = p_lcb->signal_id; - p_buf = l2cu_build_header(p_lcb, - L2CAP_CMD_CREDIT_BASED_CONN_REQ_MIN_LEN + - 2 * p_lcb->pending_ecoc_conn_cnt, - L2CAP_CMD_CREDIT_BASED_CONN_REQ, p_ccb->local_id); + p_buf = l2cu_build_header( + p_lcb, L2CAP_CMD_CREDIT_BASED_CONN_REQ_MIN_LEN + 2 * p_lcb->pending_ecoc_conn_cnt, + L2CAP_CMD_CREDIT_BASED_CONN_REQ, p_ccb->local_id); if (p_buf == NULL) { log::warn("no buffer"); return; } - p = (uint8_t*)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + - L2CAP_PKT_OVERHEAD + L2CAP_CMD_OVERHEAD; + p = (uint8_t*)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + L2CAP_PKT_OVERHEAD + + L2CAP_CMD_OVERHEAD; mtu = p_ccb->local_conn_cfg.mtu; mps = p_ccb->local_conn_cfg.mps; initial_credit = p_ccb->local_conn_cfg.credits; - log::verbose("PSM:0x{:04x} mtu:{} mps:{} initial_credit:{}, cids_cnt {}", - p_ccb->p_rcb->real_psm, mtu, mps, initial_credit, - p_lcb->pending_ecoc_conn_cnt); + log::verbose("PSM:0x{:04x} mtu:{} mps:{} initial_credit:{}, cids_cnt {}", p_ccb->p_rcb->real_psm, + mtu, mps, initial_credit, p_lcb->pending_ecoc_conn_cnt); UINT16_TO_STREAM(p, p_ccb->p_rcb->real_psm); UINT16_TO_STREAM(p, mtu); @@ -3078,8 +3071,7 @@ void l2cu_send_peer_credit_based_conn_req(tL2C_CCB* p_ccb) { * Returns void * ******************************************************************************/ -void l2cu_reject_ble_coc_connection(tL2C_LCB* p_lcb, uint8_t rem_id, - uint16_t result) { +void l2cu_reject_ble_coc_connection(tL2C_LCB* p_lcb, uint8_t rem_id, uint16_t result) { BT_HDR* p_buf; uint8_t* p; @@ -3090,8 +3082,8 @@ void l2cu_reject_ble_coc_connection(tL2C_LCB* p_lcb, uint8_t rem_id, return; } - p = (uint8_t*)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + - L2CAP_PKT_OVERHEAD + L2CAP_CMD_OVERHEAD; + p = (uint8_t*)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + L2CAP_PKT_OVERHEAD + + L2CAP_CMD_OVERHEAD; UINT16_TO_STREAM(p, 0); /* Local CID of 0 */ UINT16_TO_STREAM(p, 0); /* MTU */ @@ -3112,28 +3104,25 @@ void l2cu_reject_ble_coc_connection(tL2C_LCB* p_lcb, uint8_t rem_id, * Returns void * ******************************************************************************/ -void l2cu_reject_credit_based_conn_req(tL2C_LCB* p_lcb, uint8_t rem_id, - uint8_t num_of_channels, +void l2cu_reject_credit_based_conn_req(tL2C_LCB* p_lcb, uint8_t rem_id, uint8_t num_of_channels, uint16_t result) { BT_HDR* p_buf; uint8_t* p; - uint8_t rsp_len = L2CAP_CMD_CREDIT_BASED_CONN_RES_MIN_LEN + - sizeof(uint16_t) * num_of_channels; + uint8_t rsp_len = L2CAP_CMD_CREDIT_BASED_CONN_RES_MIN_LEN + sizeof(uint16_t) * num_of_channels; - p_buf = l2cu_build_header(p_lcb, rsp_len, L2CAP_CMD_CREDIT_BASED_CONN_RES, - rem_id); + p_buf = l2cu_build_header(p_lcb, rsp_len, L2CAP_CMD_CREDIT_BASED_CONN_RES, rem_id); if (p_buf == NULL) { log::warn("l2cu_reject_credit_based_conn_req - no buffer"); return; } - p = (uint8_t*)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + - L2CAP_PKT_OVERHEAD + L2CAP_CMD_OVERHEAD; + p = (uint8_t*)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + L2CAP_PKT_OVERHEAD + + L2CAP_CMD_OVERHEAD; memset(p, 0, rsp_len); UINT16_TO_STREAM(p, L2CAP_CREDIT_BASED_MIN_MTU); /* dummy MTU to satisy PTS */ UINT16_TO_STREAM(p, L2CAP_CREDIT_BASED_MIN_MPS); /* dummy MPS to satisy PTS*/ - UINT16_TO_STREAM(p, 1); /* dummy initial credit to satisy PTS */ + UINT16_TO_STREAM(p, 1); /* dummy initial credit to satisy PTS */ UINT16_TO_STREAM(p, result); l2c_link_check_send_pkts(p_lcb, 0, p_buf); @@ -3150,8 +3139,7 @@ void l2cu_reject_credit_based_conn_req(tL2C_LCB* p_lcb, uint8_t rem_id, * Returns void * ******************************************************************************/ -void l2cu_send_peer_credit_based_conn_res(tL2C_CCB* p_ccb, - std::vector& accepted_cids, +void l2cu_send_peer_credit_based_conn_res(tL2C_CCB* p_ccb, std::vector& accepted_cids, uint16_t result) { BT_HDR* p_buf; uint8_t* p; @@ -3160,15 +3148,15 @@ void l2cu_send_peer_credit_based_conn_res(tL2C_CCB* p_ccb, uint8_t rsp_len = L2CAP_CMD_CREDIT_BASED_CONN_RES_MIN_LEN + p_ccb->p_lcb->pending_ecoc_conn_cnt * sizeof(uint16_t); - p_buf = l2cu_build_header(p_ccb->p_lcb, rsp_len, - L2CAP_CMD_CREDIT_BASED_CONN_RES, p_ccb->remote_id); + p_buf = l2cu_build_header(p_ccb->p_lcb, rsp_len, L2CAP_CMD_CREDIT_BASED_CONN_RES, + p_ccb->remote_id); if (p_buf == NULL) { log::warn("no buffer"); return; } - p = (uint8_t*)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + - L2CAP_PKT_OVERHEAD + L2CAP_CMD_OVERHEAD; + p = (uint8_t*)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + L2CAP_PKT_OVERHEAD + + L2CAP_CMD_OVERHEAD; memset(p, 0, rsp_len); UINT16_TO_STREAM(p, p_ccb->local_conn_cfg.mtu); /* MTU */ @@ -3219,13 +3207,13 @@ void l2cu_send_peer_credit_based_conn_res(tL2C_CCB* p_ccb, * Returns void * ******************************************************************************/ -void l2cu_reject_ble_connection(tL2C_CCB* p_ccb, uint8_t rem_id, - uint16_t result) { - if (p_ccb->ecoc) - l2cu_reject_credit_based_conn_req( - p_ccb->p_lcb, rem_id, p_ccb->p_lcb->pending_ecoc_conn_cnt, result); - else +void l2cu_reject_ble_connection(tL2C_CCB* p_ccb, uint8_t rem_id, uint16_t result) { + if (p_ccb->ecoc) { + l2cu_reject_credit_based_conn_req(p_ccb->p_lcb, rem_id, p_ccb->p_lcb->pending_ecoc_conn_cnt, + result); + } else { l2cu_reject_ble_coc_connection(p_ccb->p_lcb, rem_id, result); + } } /******************************************************************************* @@ -3240,8 +3228,7 @@ void l2cu_reject_ble_connection(tL2C_CCB* p_ccb, uint8_t rem_id, * ******************************************************************************/ -void l2cu_send_ble_reconfig_rsp(tL2C_LCB* p_lcb, uint8_t rem_id, - uint16_t result) { +void l2cu_send_ble_reconfig_rsp(tL2C_LCB* p_lcb, uint8_t rem_id, uint16_t result) { BT_HDR* p_buf; uint8_t* p; @@ -3254,8 +3241,8 @@ void l2cu_send_ble_reconfig_rsp(tL2C_LCB* p_lcb, uint8_t rem_id, return; } - p = (uint8_t*)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + - L2CAP_PKT_OVERHEAD + L2CAP_CMD_OVERHEAD; + p = (uint8_t*)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + L2CAP_PKT_OVERHEAD + + L2CAP_CMD_OVERHEAD; memset(p, 0, L2CAP_CMD_CREDIT_BASED_RECONFIG_RES_LEN); UINT16_TO_STREAM(p, result); @@ -3274,22 +3261,20 @@ void l2cu_send_ble_reconfig_rsp(tL2C_LCB* p_lcb, uint8_t rem_id, * Returns void * ******************************************************************************/ -void l2cu_send_peer_ble_credit_based_conn_res(tL2C_CCB* p_ccb, - uint16_t result) { +void l2cu_send_peer_ble_credit_based_conn_res(tL2C_CCB* p_ccb, uint16_t result) { BT_HDR* p_buf; uint8_t* p; log::verbose("l2cu_send_peer_ble_credit_based_conn_res"); - p_buf = - l2cu_build_header(p_ccb->p_lcb, L2CAP_CMD_BLE_CREDIT_BASED_CONN_RES_LEN, - L2CAP_CMD_BLE_CREDIT_BASED_CONN_RES, p_ccb->remote_id); + p_buf = l2cu_build_header(p_ccb->p_lcb, L2CAP_CMD_BLE_CREDIT_BASED_CONN_RES_LEN, + L2CAP_CMD_BLE_CREDIT_BASED_CONN_RES, p_ccb->remote_id); if (p_buf == NULL) { log::warn("l2cu_send_peer_ble_credit_based_conn_res - no buffer"); return; } - p = (uint8_t*)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + - L2CAP_PKT_OVERHEAD + L2CAP_CMD_OVERHEAD; + p = (uint8_t*)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + L2CAP_PKT_OVERHEAD + + L2CAP_CMD_OVERHEAD; UINT16_TO_STREAM(p, p_ccb->local_cid); /* Local CID */ UINT16_TO_STREAM(p, p_ccb->local_conn_cfg.mtu); /* MTU */ @@ -3310,13 +3295,14 @@ void l2cu_send_peer_ble_credit_based_conn_res(tL2C_CCB* p_ccb, * Returns void * ******************************************************************************/ -void l2cu_send_peer_ble_flow_control_credit(tL2C_CCB* p_ccb, - uint16_t credit_value) { +void l2cu_send_peer_ble_flow_control_credit(tL2C_CCB* p_ccb, uint16_t credit_value) { BT_HDR* p_buf; uint8_t* p; tL2C_LCB* p_lcb = NULL; - if (!p_ccb) return; + if (!p_ccb) { + return; + } p_lcb = p_ccb->p_lcb; /* Create an identifier for this packet */ @@ -3332,8 +3318,8 @@ void l2cu_send_peer_ble_flow_control_credit(tL2C_CCB* p_ccb, return; } - p = (uint8_t*)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + - L2CAP_PKT_OVERHEAD + L2CAP_CMD_OVERHEAD; + p = (uint8_t*)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + L2CAP_PKT_OVERHEAD + + L2CAP_CMD_OVERHEAD; UINT16_TO_STREAM(p, p_ccb->local_cid); UINT16_TO_STREAM(p, credit_value); @@ -3357,7 +3343,9 @@ void l2cu_send_peer_ble_credit_based_disconn_req(tL2C_CCB* p_ccb) { tL2C_LCB* p_lcb = NULL; log::verbose(""); - if (!p_ccb) return; + if (!p_ccb) { + return; + } p_lcb = p_ccb->p_lcb; /* Create an identifier for this packet */ @@ -3365,15 +3353,14 @@ void l2cu_send_peer_ble_credit_based_disconn_req(tL2C_CCB* p_ccb) { l2cu_adj_id(p_ccb->p_lcb); p_ccb->local_id = p_ccb->p_lcb->signal_id; - p_buf = l2cu_build_header(p_lcb, L2CAP_DISC_REQ_LEN, L2CAP_CMD_DISC_REQ, - p_lcb->signal_id); + p_buf = l2cu_build_header(p_lcb, L2CAP_DISC_REQ_LEN, L2CAP_CMD_DISC_REQ, p_lcb->signal_id); if (p_buf == NULL) { log::warn("l2cu_send_peer_ble_credit_based_disconn_req - no buffer"); return; } - p = (uint8_t*)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + - L2CAP_PKT_OVERHEAD + L2CAP_CMD_OVERHEAD; + p = (uint8_t*)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE + L2CAP_PKT_OVERHEAD + + L2CAP_CMD_OVERHEAD; UINT16_TO_STREAM(p, p_ccb->remote_cid); UINT16_TO_STREAM(p, p_ccb->local_cid); @@ -3401,12 +3388,12 @@ tL2C_LCB* l2cu_find_lcb_by_handle(uint16_t handle) { for (xx = 0; xx < MAX_L2CAP_LINKS; xx++, p_lcb++) { if ((p_lcb->in_use) && (p_lcb->Handle() == handle)) { - return (p_lcb); + return p_lcb; } } /* If here, no match found */ - return (NULL); + return NULL; } /******************************************************************************* @@ -3426,7 +3413,9 @@ tL2C_CCB* l2cu_find_ccb_by_cid(tL2C_LCB* p_lcb, uint16_t local_cid) { /* find the associated CCB by "index" */ local_cid -= L2CAP_BASE_APPL_CID; - if (local_cid >= MAX_L2CAP_CHANNELS) return NULL; + if (local_cid >= MAX_L2CAP_CHANNELS) { + return NULL; + } p_ccb = l2cb.ccb_pool + local_cid; @@ -3439,11 +3428,13 @@ tL2C_CCB* l2cu_find_ccb_by_cid(tL2C_LCB* p_lcb, uint16_t local_cid) { p_ccb = NULL; } } - return (p_ccb); + return p_ccb; } void l2cu_tx_complete(tL2C_TX_COMPLETE_CB_INFO* p_cbi) { - if (p_cbi->cb != NULL) p_cbi->cb(p_cbi->local_cid, p_cbi->num_sdu); + if (p_cbi->cb != NULL) { + p_cbi->cb(p_cbi->local_cid, p_cbi->num_sdu); + } } /****************************************************************************** @@ -3463,12 +3454,11 @@ void l2cu_set_acl_hci_header(BT_HDR* p_buf, tL2C_CCB* p_ccb) { p = (uint8_t*)(p_buf + 1) + p_buf->offset - HCI_DATA_PREAMBLE_SIZE; if (p_ccb->p_lcb->transport == BT_TRANSPORT_LE) { - UINT16_TO_STREAM(p, p_ccb->p_lcb->Handle() | (L2CAP_PKT_START_NON_FLUSHABLE - << L2CAP_PKT_TYPE_SHIFT)); + UINT16_TO_STREAM( + p, p_ccb->p_lcb->Handle() | (L2CAP_PKT_START_NON_FLUSHABLE << L2CAP_PKT_TYPE_SHIFT)); - uint16_t acl_data_size = bluetooth::shim::GetController() - ->GetLeBufferSize() - .le_data_packet_length_; + uint16_t acl_data_size = + bluetooth::shim::GetController()->GetLeBufferSize().le_data_packet_length_; /* The HCI transport will segment the buffers. */ if (p_buf->len > acl_data_size) { UINT16_TO_STREAM(p, acl_data_size); @@ -3476,17 +3466,14 @@ void l2cu_set_acl_hci_header(BT_HDR* p_buf, tL2C_CCB* p_ccb) { UINT16_TO_STREAM(p, p_buf->len); } } else { - if (((p_buf->layer_specific & L2CAP_FLUSHABLE_MASK) == - L2CAP_FLUSHABLE_CH_BASED) && + if (((p_buf->layer_specific & L2CAP_FLUSHABLE_MASK) == L2CAP_FLUSHABLE_CH_BASED) && (p_ccb->is_flushable)) { - UINT16_TO_STREAM(p, p_ccb->p_lcb->Handle() | - (L2CAP_PKT_START << L2CAP_PKT_TYPE_SHIFT)); + UINT16_TO_STREAM(p, p_ccb->p_lcb->Handle() | (L2CAP_PKT_START << L2CAP_PKT_TYPE_SHIFT)); } else { UINT16_TO_STREAM(p, p_ccb->p_lcb->Handle() | l2cb.non_flushable_pbf); } - uint16_t acl_data_size = - bluetooth::shim::GetController()->GetAclPacketLength(); + uint16_t acl_data_size = bluetooth::shim::GetController()->GetAclPacketLength(); /* The HCI transport will segment the buffers. */ if (p_buf->len > acl_data_size) { UINT16_TO_STREAM(p, acl_data_size); @@ -3498,30 +3485,31 @@ void l2cu_set_acl_hci_header(BT_HDR* p_buf, tL2C_CCB* p_ccb) { p_buf->len += HCI_DATA_PREAMBLE_SIZE; } -static void send_congestion_status_to_all_clients(tL2C_CCB* p_ccb, - bool status) { +static void send_congestion_status_to_all_clients(tL2C_CCB* p_ccb, bool status) { p_ccb->cong_sent = status; if (p_ccb->p_rcb && p_ccb->p_rcb->api.pL2CA_CongestionStatus_Cb) { log::verbose( - "L2CAP - Calling CongestionStatus_Cb ({}), CID: 0x{:04x} " - "xmit_hold_q.count: {} buff_quota: {}", - status, p_ccb->local_cid, fixed_queue_length(p_ccb->xmit_hold_q), - p_ccb->buff_quota); + "L2CAP - Calling CongestionStatus_Cb ({}), CID: 0x{:04x} " + "xmit_hold_q.count: {} buff_quota: {}", + status, p_ccb->local_cid, fixed_queue_length(p_ccb->xmit_hold_q), p_ccb->buff_quota); /* Prevent recursive calling */ - if (status == false) l2cb.is_cong_cback_context = true; + if (status == false) { + l2cb.is_cong_cback_context = true; + } (*p_ccb->p_rcb->api.pL2CA_CongestionStatus_Cb)(p_ccb->local_cid, status); - if (status == false) l2cb.is_cong_cback_context = false; - } - else { + if (status == false) { + l2cb.is_cong_cback_context = false; + } + } else { for (uint8_t xx = 0; xx < L2CAP_NUM_FIXED_CHNLS; xx++) { if (p_ccb->p_lcb->p_fixed_ccbs[xx] == p_ccb) { - if (l2cb.fixed_reg[xx].pL2CA_FixedCong_Cb != NULL) - (*l2cb.fixed_reg[xx].pL2CA_FixedCong_Cb)(p_ccb->p_lcb->remote_bd_addr, - status); + if (l2cb.fixed_reg[xx].pL2CA_FixedCong_Cb != NULL) { + (*l2cb.fixed_reg[xx].pL2CA_FixedCong_Cb)(p_ccb->p_lcb->remote_bd_addr, status); + } break; } } @@ -3532,18 +3520,22 @@ static void send_congestion_status_to_all_clients(tL2C_CCB* p_ccb, void l2cu_check_channel_congestion(tL2C_CCB* p_ccb) { /* If the CCB queue limit is subject to a quota, check for congestion if this * channel has outgoing traffic */ - if (p_ccb->buff_quota == 0) return; + if (p_ccb->buff_quota == 0) { + return; + } size_t q_count = fixed_queue_length(p_ccb->xmit_hold_q); if (p_ccb->cong_sent) { /* if channel was congested, but is not congested now, tell the app */ - if (q_count <= (p_ccb->buff_quota / 2)) + if (q_count <= (p_ccb->buff_quota / 2)) { send_congestion_status_to_all_clients(p_ccb, false); + } } else { /* if channel was not congested, but is congested now, tell the app */ - if (q_count > p_ccb->buff_quota) + if (q_count > p_ccb->buff_quota) { send_congestion_status_to_all_clients(p_ccb, true); + } } } @@ -3557,7 +3549,7 @@ void l2cu_check_channel_congestion(tL2C_CCB* p_ccb) { * false if p_ccb is null or is released. * ******************************************************************************/ -bool l2cu_is_ccb_active(tL2C_CCB* p_ccb) { return (p_ccb && p_ccb->in_use); } +bool l2cu_is_ccb_active(tL2C_CCB* p_ccb) { return p_ccb && p_ccb->in_use; } /******************************************************************************* * diff --git a/system/stack/metrics/stack_metrics_logging.cc b/system/stack/metrics/stack_metrics_logging.cc index 8c29ae93dcf..68846827f47 100644 --- a/system/stack/metrics/stack_metrics_logging.cc +++ b/system/stack/metrics/stack_metrics_logging.cc @@ -14,76 +14,66 @@ * limitations under the License. */ +#include "stack/include/stack_metrics_logging.h" + #include #include #include "common/metrics.h" #include "main/shim/metrics_api.h" #include "main/shim/shim.h" -#include "stack/include/stack_metrics_logging.h" #include "types/raw_address.h" -void log_classic_pairing_event(const RawAddress& address, uint16_t handle, - uint32_t hci_cmd, uint16_t hci_event, - uint16_t cmd_status, uint16_t reason_code, +void log_classic_pairing_event(const RawAddress& address, uint16_t handle, uint32_t hci_cmd, + uint16_t hci_event, uint16_t cmd_status, uint16_t reason_code, int64_t event_value) { - bluetooth::shim::LogMetricClassicPairingEvent(address, handle, hci_cmd, - hci_event, cmd_status, + bluetooth::shim::LogMetricClassicPairingEvent(address, handle, hci_cmd, hci_event, cmd_status, reason_code, event_value); } -void log_link_layer_connection_event( - const RawAddress* address, uint32_t connection_handle, - android::bluetooth::DirectionEnum direction, uint16_t link_type, - uint32_t hci_cmd, uint16_t hci_event, uint16_t hci_ble_event, - uint16_t cmd_status, uint16_t reason_code) { - bluetooth::shim::LogMetricLinkLayerConnectionEvent( - address, connection_handle, direction, link_type, hci_cmd, hci_event, - hci_ble_event, cmd_status, reason_code); +void log_link_layer_connection_event(const RawAddress* address, uint32_t connection_handle, + android::bluetooth::DirectionEnum direction, + uint16_t link_type, uint32_t hci_cmd, uint16_t hci_event, + uint16_t hci_ble_event, uint16_t cmd_status, + uint16_t reason_code) { + bluetooth::shim::LogMetricLinkLayerConnectionEvent(address, connection_handle, direction, + link_type, hci_cmd, hci_event, hci_ble_event, + cmd_status, reason_code); } void log_smp_pairing_event(const RawAddress& address, uint16_t smp_cmd, - android::bluetooth::DirectionEnum direction, - uint16_t smp_fail_reason) { - bluetooth::shim::LogMetricSmpPairingEvent(address, smp_cmd, direction, - smp_fail_reason); + android::bluetooth::DirectionEnum direction, uint16_t smp_fail_reason) { + bluetooth::shim::LogMetricSmpPairingEvent(address, smp_cmd, direction, smp_fail_reason); } -void log_sdp_attribute(const RawAddress& address, uint16_t protocol_uuid, - uint16_t attribute_id, size_t attribute_size, - const char* attribute_value) { - bluetooth::shim::LogMetricSdpAttribute(address, protocol_uuid, attribute_id, - attribute_size, attribute_value); +void log_sdp_attribute(const RawAddress& address, uint16_t protocol_uuid, uint16_t attribute_id, + size_t attribute_size, const char* attribute_value) { + bluetooth::shim::LogMetricSdpAttribute(address, protocol_uuid, attribute_id, attribute_size, + attribute_value); } void log_manufacturer_info(const RawAddress& address, android::bluetooth::AddressTypeEnum address_type, android::bluetooth::DeviceInfoSrcEnum source_type, - const std::string& source_name, - const std::string& manufacturer, - const std::string& model, - const std::string& hardware_version, + const std::string& source_name, const std::string& manufacturer, + const std::string& model, const std::string& hardware_version, const std::string& software_version) { - bluetooth::shim::LogMetricManufacturerInfo( - address, address_type, source_type, source_name, manufacturer, model, - hardware_version, software_version); + bluetooth::shim::LogMetricManufacturerInfo(address, address_type, source_type, source_name, + manufacturer, model, hardware_version, + software_version); } -void log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum key, - int64_t value) { +void log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum key, int64_t value) { bluetooth::shim::CountCounterMetrics(key, value); } -void log_hfp_audio_packet_loss_stats(const RawAddress& address, - int num_decoded_frames, - double packet_loss_ratio, - uint16_t codec_type) { - bluetooth::shim::LogMetricHfpPacketLossStats(address, num_decoded_frames, - packet_loss_ratio, codec_type); +void log_hfp_audio_packet_loss_stats(const RawAddress& address, int num_decoded_frames, + double packet_loss_ratio, uint16_t codec_type) { + bluetooth::shim::LogMetricHfpPacketLossStats(address, num_decoded_frames, packet_loss_ratio, + codec_type); } -void log_mmc_transcode_rtt_stats(int maximum_rtt, double mean_rtt, - int num_requests, int codec_type) { - bluetooth::shim::LogMetricMmcTranscodeRttStats(maximum_rtt, mean_rtt, - num_requests, codec_type); +void log_mmc_transcode_rtt_stats(int maximum_rtt, double mean_rtt, int num_requests, + int codec_type) { + bluetooth::shim::LogMetricMmcTranscodeRttStats(maximum_rtt, mean_rtt, num_requests, codec_type); } diff --git a/system/stack/mmc/codec_client/codec_client.cc b/system/stack/mmc/codec_client/codec_client.cc index 5b18f6d3006..24b39e24550 100644 --- a/system/stack/mmc/codec_client/codec_client.cc +++ b/system/stack/mmc/codec_client/codec_client.cc @@ -77,8 +77,8 @@ CodecClient::CodecClient() { } // Get proxy to send DBus method call. - codec_manager_ = bus_->GetObjectProxy(mmc::kMmcServiceName, - dbus::ObjectPath(mmc::kMmcServicePath)); + codec_manager_ = + bus_->GetObjectProxy(mmc::kMmcServiceName, dbus::ObjectPath(mmc::kMmcServicePath)); if (!codec_manager_) { log::error("Failed to get object proxy"); return; @@ -87,7 +87,9 @@ CodecClient::CodecClient() { CodecClient::~CodecClient() { cleanup(); - if (bus_) bus_->ShutdownAndBlock(); + if (bus_) { + bus_->ShutdownAndBlock(); + } } int CodecClient::init(const ConfigParam config) { @@ -96,8 +98,7 @@ int CodecClient::init(const ConfigParam config) { // Set up record logger. record_logger_ = std::make_unique(CodecId(config)); - dbus::MethodCall method_call(mmc::kMmcServiceInterface, - mmc::kCodecInitMethod); + dbus::MethodCall method_call(mmc::kMmcServiceInterface, mmc::kCodecInitMethod); dbus::MessageWriter writer(&method_call); mmc::CodecInitRequest request; @@ -108,14 +109,13 @@ int CodecClient::init(const ConfigParam config) { } std::unique_ptr dbus_response = - codec_manager_ - ->CallMethodAndBlock(&method_call, - dbus::ObjectProxy::TIMEOUT_USE_DEFAULT) + codec_manager_ + ->CallMethodAndBlock(&method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT) // TODO(b/297976471): remove the build flag once libchrome uprev is done. #if BASE_VER >= 1170299 - .value_or(nullptr) + .value_or(nullptr) #endif - ; + ; if (!dbus_response) { log::error("CodecInit failed"); @@ -148,12 +148,10 @@ int CodecClient::init(const ConfigParam config) { struct sockaddr_un addr = {}; addr.sun_family = AF_UNIX; - strncpy(addr.sun_path, response.socket_token().c_str(), - sizeof(addr.sun_path) - 1); + strncpy(addr.sun_path, response.socket_token().c_str(), sizeof(addr.sun_path) - 1); // Connect to socket for transcoding. - int rc = - connect(skt_fd_, (struct sockaddr*)&addr, sizeof(struct sockaddr_un)); + int rc = connect(skt_fd_, (struct sockaddr*)&addr, sizeof(struct sockaddr_un)); if (rc < 0) { log::error("Failed to connect socket: {}", strerror(errno)); return -errno; @@ -174,18 +172,16 @@ void CodecClient::cleanup() { record_logger_.release(); } - dbus::MethodCall method_call(mmc::kMmcServiceInterface, - mmc::kCodecCleanUpMethod); + dbus::MethodCall method_call(mmc::kMmcServiceInterface, mmc::kCodecCleanUpMethod); std::unique_ptr dbus_response = - codec_manager_ - ->CallMethodAndBlock(&method_call, - dbus::ObjectProxy::TIMEOUT_USE_DEFAULT) + codec_manager_ + ->CallMethodAndBlock(&method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT) // TODO(b/297976471): remove the build flag once libchrome uprev is done. #if BASE_VER >= 1170299 - .value_or(nullptr) + .value_or(nullptr) #endif - ; + ; if (!dbus_response) { log::warn("CodecCleanUp failed"); @@ -193,8 +189,7 @@ void CodecClient::cleanup() { return; } -int CodecClient::transcode(uint8_t* i_buf, int i_len, uint8_t* o_buf, - int o_len) { +int CodecClient::transcode(uint8_t* i_buf, int i_len, uint8_t* o_buf, int o_len) { // Start Timer base::ElapsedTimer timer; diff --git a/system/stack/mmc/codec_client/codec_client.h b/system/stack/mmc/codec_client/codec_client.h index 2882b558adf..c01644c6911 100644 --- a/system/stack/mmc/codec_client/codec_client.h +++ b/system/stack/mmc/codec_client/codec_client.h @@ -31,7 +31,7 @@ namespace mmc { // Implementation of MmcInterface. // CodecClient serves as proxy of MMC codec service. class CodecClient : public MmcInterface { - public: +public: // Connects to DBus. explicit CodecClient(); @@ -60,7 +60,7 @@ class CodecClient : public MmcInterface { // Negative errno on error, otherwise. int transcode(uint8_t* i_buf, int i_len, uint8_t* o_buf, int o_len) override; - private: +private: int skt_fd_; dbus::ObjectProxy* codec_manager_; // Owned by the Bus object. scoped_refptr bus_; diff --git a/system/stack/mmc/codec_server/a2dp_aac_mmc_encoder.cc b/system/stack/mmc/codec_server/a2dp_aac_mmc_encoder.cc index 8e159f7652d..24ac4edb51e 100644 --- a/system/stack/mmc/codec_server/a2dp_aac_mmc_encoder.cc +++ b/system/stack/mmc/codec_server/a2dp_aac_mmc_encoder.cc @@ -37,13 +37,13 @@ using namespace bluetooth; const int A2DP_AAC_HEADER_LEN = 9; const int A2DP_AAC_MAX_LEN_REPR = 4; const int A2DP_AAC_MAX_PREFIX_SIZE = - AVDT_MEDIA_HDR_SIZE + A2DP_AAC_HEADER_LEN + A2DP_AAC_MAX_LEN_REPR; + AVDT_MEDIA_HDR_SIZE + A2DP_AAC_HEADER_LEN + A2DP_AAC_MAX_LEN_REPR; constexpr uint8_t A2DP_AAC_HEADER_44100[A2DP_AAC_HEADER_LEN] = { - 0x47, 0xfc, 0x00, 0x00, 0xb0, 0x90, 0x80, 0x03, 0x00, + 0x47, 0xfc, 0x00, 0x00, 0xb0, 0x90, 0x80, 0x03, 0x00, }; constexpr uint8_t A2DP_AAC_HEADER_48000[A2DP_AAC_HEADER_LEN] = { - 0x47, 0xfc, 0x00, 0x00, 0xb0, 0x8c, 0x80, 0x03, 0x00, + 0x47, 0xfc, 0x00, 0x00, 0xb0, 0x8c, 0x80, 0x03, 0x00, }; } // namespace @@ -113,8 +113,7 @@ void A2dpAacEncoder::cleanup() { } } -int A2dpAacEncoder::transcode(uint8_t* i_buf, int i_len, uint8_t* o_buf, - int o_len) { +int A2dpAacEncoder::transcode(uint8_t* i_buf, int i_len, uint8_t* o_buf, int o_len) { int rc; AVFrame* frame = av_frame_alloc(); @@ -205,8 +204,8 @@ int A2dpAacEncoder::transcode(uint8_t* i_buf, int i_len, uint8_t* o_buf, uint8_t* dst = o_buf; - const uint8_t* header = avctx_->sample_rate == 44100 ? A2DP_AAC_HEADER_44100 - : A2DP_AAC_HEADER_48000; + const uint8_t* header = + avctx_->sample_rate == 44100 ? A2DP_AAC_HEADER_44100 : A2DP_AAC_HEADER_48000; std::copy(header, header + A2DP_AAC_HEADER_LEN, dst); @@ -219,7 +218,7 @@ int A2dpAacEncoder::transcode(uint8_t* i_buf, int i_len, uint8_t* o_buf, log::warn("Dropped pkt: size={}, cap={}", pkt->size, cap); } static uint8_t silent_frame[7] = { - 0x06, 0x21, 0x10, 0x04, 0x60, 0x8c, 0x1c, + 0x06, 0x21, 0x10, 0x04, 0x60, 0x8c, 0x1c, }; std::copy(silent_frame, std::end(silent_frame), dst); dst += sizeof(silent_frame); diff --git a/system/stack/mmc/codec_server/a2dp_aac_mmc_encoder.h b/system/stack/mmc/codec_server/a2dp_aac_mmc_encoder.h index f88f136188a..8f8d6f8b134 100644 --- a/system/stack/mmc/codec_server/a2dp_aac_mmc_encoder.h +++ b/system/stack/mmc/codec_server/a2dp_aac_mmc_encoder.h @@ -29,7 +29,7 @@ namespace mmc { // Implementation of MmcInterface. // A2dpAacEncoder wraps FFmpeg encode libraries. class A2dpAacEncoder : public MmcInterface { - public: +public: explicit A2dpAacEncoder(); ~A2dpAacEncoder(); @@ -54,7 +54,7 @@ class A2dpAacEncoder : public MmcInterface { // Negative errno on error, otherwise. int transcode(uint8_t* i_buf, int i_len, uint8_t* o_buf, int o_len) override; - private: +private: AVCodecContext* avctx_; AacEncoderParam param_; }; diff --git a/system/stack/mmc/codec_server/hfp_lc3_mmc_decoder.cc b/system/stack/mmc/codec_server/hfp_lc3_mmc_decoder.cc index 37ae4a3794f..aad075ef15b 100644 --- a/system/stack/mmc/codec_server/hfp_lc3_mmc_decoder.cc +++ b/system/stack/mmc/codec_server/hfp_lc3_mmc_decoder.cc @@ -47,8 +47,7 @@ int HfpLc3Decoder::init(ConfigParam config) { hfp_lc3_decoder_mem_ = osi_malloc(dec_size); - hfp_lc3_decoder_ = - lc3_setup_decoder(dt_us, sr_hz, sr_pcm_hz, hfp_lc3_decoder_mem_); + hfp_lc3_decoder_ = lc3_setup_decoder(dt_us, sr_hz, sr_pcm_hz, hfp_lc3_decoder_mem_); if (hfp_lc3_decoder_ == nullptr) { log::error("Wrong parameters provided"); @@ -65,29 +64,28 @@ void HfpLc3Decoder::cleanup() { } } -int HfpLc3Decoder::transcode(uint8_t* i_buf, int i_len, uint8_t* o_buf, - int o_len) { +int HfpLc3Decoder::transcode(uint8_t* i_buf, int i_len, uint8_t* o_buf, int o_len) { if (o_buf == nullptr || o_len < HFP_LC3_PCM_BYTES + 1) { log::error("Output buffer size is less than LC3 frame size"); return -EINVAL; } // Check header to decide whether it's PLC. - uint8_t* in_frame = - (i_buf[0] || i_buf[1]) ? i_buf + HFP_LC3_H2_HEADER_LEN : nullptr; + uint8_t* in_frame = (i_buf[0] || i_buf[1]) ? i_buf + HFP_LC3_H2_HEADER_LEN : nullptr; // First byte is reserved to indicate PLC. uint8_t* out_frame = o_buf + 1; /* Note this only fails when wrong parameters are supplied. */ - int rc = lc3_decode(hfp_lc3_decoder_, in_frame, HFP_LC3_PKT_FRAME_LEN, - MapLc3PcmFmt(param_.fmt()), out_frame, param_.stride()); + int rc = lc3_decode(hfp_lc3_decoder_, in_frame, HFP_LC3_PKT_FRAME_LEN, MapLc3PcmFmt(param_.fmt()), + out_frame, param_.stride()); if (rc != 0 && rc != 1) { log::warn("Wrong decode parameters"); std::fill(o_buf, o_buf + o_len, 0); - } else + } else { o_buf[0] = rc; + } return HFP_LC3_PCM_BYTES + 1; } diff --git a/system/stack/mmc/codec_server/hfp_lc3_mmc_decoder.h b/system/stack/mmc/codec_server/hfp_lc3_mmc_decoder.h index 27b83e95b5d..bf3ba8d9a71 100644 --- a/system/stack/mmc/codec_server/hfp_lc3_mmc_decoder.h +++ b/system/stack/mmc/codec_server/hfp_lc3_mmc_decoder.h @@ -27,7 +27,7 @@ namespace mmc { // Implementation of MmcInterface. // HfpLc3Decoder wraps lc3 decode libraries. class HfpLc3Decoder : public MmcInterface { - public: +public: explicit HfpLc3Decoder(); ~HfpLc3Decoder(); @@ -52,7 +52,7 @@ class HfpLc3Decoder : public MmcInterface { // Negative errno on error, otherwise. int transcode(uint8_t* i_buf, int i_len, uint8_t* o_buf, int o_len) override; - private: +private: void* hfp_lc3_decoder_mem_; lc3_decoder_t hfp_lc3_decoder_; Lc3Param param_; diff --git a/system/stack/mmc/codec_server/hfp_lc3_mmc_encoder.cc b/system/stack/mmc/codec_server/hfp_lc3_mmc_encoder.cc index 6694294a2e9..960f4c91c78 100644 --- a/system/stack/mmc/codec_server/hfp_lc3_mmc_encoder.cc +++ b/system/stack/mmc/codec_server/hfp_lc3_mmc_encoder.cc @@ -49,8 +49,7 @@ int HfpLc3Encoder::init(ConfigParam config) { hfp_lc3_encoder_mem_ = osi_malloc(enc_size); - hfp_lc3_encoder_ = - lc3_setup_encoder(dt_us, sr_hz, sr_pcm_hz, hfp_lc3_encoder_mem_); + hfp_lc3_encoder_ = lc3_setup_encoder(dt_us, sr_hz, sr_pcm_hz, hfp_lc3_encoder_mem_); if (hfp_lc3_encoder_ == nullptr) { log::error("Wrong parameters provided"); @@ -67,16 +66,15 @@ void HfpLc3Encoder::cleanup() { } } -int HfpLc3Encoder::transcode(uint8_t* i_buf, int i_len, uint8_t* o_buf, - int o_len) { +int HfpLc3Encoder::transcode(uint8_t* i_buf, int i_len, uint8_t* o_buf, int o_len) { if (i_buf == nullptr || o_buf == nullptr) { log::error("Buffer is null"); return -EINVAL; } /* Note this only fails when wrong parameters are supplied. */ - int rc = lc3_encode(hfp_lc3_encoder_, MapLc3PcmFmt(param_.fmt()), i_buf, - param_.stride(), HFP_LC3_PKT_FRAME_LEN, o_buf); + int rc = lc3_encode(hfp_lc3_encoder_, MapLc3PcmFmt(param_.fmt()), i_buf, param_.stride(), + HFP_LC3_PKT_FRAME_LEN, o_buf); if (rc != 0) { log::warn("Wrong encode parameters"); diff --git a/system/stack/mmc/codec_server/hfp_lc3_mmc_encoder.h b/system/stack/mmc/codec_server/hfp_lc3_mmc_encoder.h index b9e66da70ec..710978e393d 100644 --- a/system/stack/mmc/codec_server/hfp_lc3_mmc_encoder.h +++ b/system/stack/mmc/codec_server/hfp_lc3_mmc_encoder.h @@ -27,7 +27,7 @@ namespace mmc { // Implementation of MmcInterface. // HfpLc3Encoder wraps lc3 encode libraries. class HfpLc3Encoder : public MmcInterface { - public: +public: explicit HfpLc3Encoder(); ~HfpLc3Encoder(); @@ -52,7 +52,7 @@ class HfpLc3Encoder : public MmcInterface { // Negative errno on error, otherwise. int transcode(uint8_t* i_buf, int i_len, uint8_t* o_buf, int o_len) override; - private: +private: void* hfp_lc3_encoder_mem_; lc3_encoder_t hfp_lc3_encoder_; Lc3Param param_; diff --git a/system/stack/mmc/codec_server/lc3_utils.h b/system/stack/mmc/codec_server/lc3_utils.h index f6eec6a0621..5ceaa04aebb 100644 --- a/system/stack/mmc/codec_server/lc3_utils.h +++ b/system/stack/mmc/codec_server/lc3_utils.h @@ -37,8 +37,7 @@ inline lc3_pcm_format MapLc3PcmFmt(Lc3Param_PcmFmt fmt) { case Lc3Param::kLc3PcmFormatS24: return LC3_PCM_FORMAT_S24; default: - bluetooth::log::info( - "No corresponding LC3 PCM format, return `LC3_PCM_FORMAT_S16`."); + bluetooth::log::info("No corresponding LC3 PCM format, return `LC3_PCM_FORMAT_S16`."); return LC3_PCM_FORMAT_S16; } } diff --git a/system/stack/mmc/daemon/service.cc b/system/stack/mmc/daemon/service.cc index 9962962bdc6..d2dee226d2d 100644 --- a/system/stack/mmc/daemon/service.cc +++ b/system/stack/mmc/daemon/service.cc @@ -49,8 +49,7 @@ namespace { using namespace bluetooth; // Task that would run on the thread. -void StartSocketListener(int fd, struct sockaddr_un addr, - std::promise task_ended, +void StartSocketListener(int fd, struct sockaddr_un addr, std::promise task_ended, std::unique_ptr codec_server) { socklen_t addr_size = sizeof(struct sockaddr_un); int client_fd = accept(fd, (struct sockaddr*)&addr, &addr_size); @@ -85,16 +84,15 @@ void StartSocketListener(int fd, struct sockaddr_un addr, break; } - int i_data_len = - recv(client_fd, i_buf.data(), kMaximumBufferSize, MSG_NOSIGNAL); + int i_data_len = recv(client_fd, i_buf.data(), kMaximumBufferSize, MSG_NOSIGNAL); if (i_data_len <= 0) { log::error("Failed to recv data: {}", strerror(errno)); break; } // Start transcode. - int o_data_len = codec_server->transcode(i_buf.data(), i_data_len, - o_buf.data(), kMaximumBufferSize); + int o_data_len = + codec_server->transcode(i_buf.data(), i_data_len, o_buf.data(), kMaximumBufferSize); if (o_data_len < 0) { log::error("Failed to transcode: {}", strerror(-o_data_len)); break; @@ -117,8 +115,7 @@ void StartSocketListener(int fd, struct sockaddr_un addr, } // namespace Service::Service(base::OnceClosure shutdown_callback) - : shutdown_callback_(std::move(shutdown_callback)), - weak_ptr_factory_(this) {} + : shutdown_callback_(std::move(shutdown_callback)), weak_ptr_factory_(this) {} bool Service::Init() { // Set up the dbus service. @@ -137,25 +134,23 @@ bool Service::Init() { return false; } - using ServiceMethod = void (Service::*)(dbus::MethodCall*, - dbus::ExportedObject::ResponseSender); + using ServiceMethod = void (Service::*)(dbus::MethodCall*, dbus::ExportedObject::ResponseSender); const std::map kServiceMethods = { - {kCodecInitMethod, &Service::CodecInit}, - {kCodecCleanUpMethod, &Service::CodecCleanUp}, + {kCodecInitMethod, &Service::CodecInit}, + {kCodecCleanUpMethod, &Service::CodecCleanUp}, }; for (const auto& iter : kServiceMethods) { bool ret = exported_object_->ExportMethodAndBlock( - kMmcServiceInterface, iter.first, - base::BindRepeating(iter.second, weak_ptr_factory_.GetWeakPtr())); + kMmcServiceInterface, iter.first, + base::BindRepeating(iter.second, weak_ptr_factory_.GetWeakPtr())); if (!ret) { log::error("Failed to export method: {}", iter.first); return false; } } - if (!bus_->RequestOwnershipAndBlock(kMmcServiceName, - dbus::Bus::REQUIRE_PRIMARY)) { + if (!bus_->RequestOwnershipAndBlock(kMmcServiceName, dbus::Bus::REQUIRE_PRIMARY)) { log::error("Failed to take ownership of {}", kMmcServiceName); return false; } @@ -174,14 +169,13 @@ void Service::CodecInit(dbus::MethodCall* method_call, if (!reader.PopArrayOfBytesAsProto(&request)) { std::move(sender).Run(dbus::ErrorResponse::FromMethodCall( - method_call, kMmcServiceError, - "Unable to parse CodecInitRequest from message")); + method_call, kMmcServiceError, "Unable to parse CodecInitRequest from message")); return; } if (!request.has_config()) { - std::move(sender).Run(dbus::ErrorResponse::FromMethodCall( - method_call, kMmcServiceError, "'Config Param' must be set")); + std::move(sender).Run(dbus::ErrorResponse::FromMethodCall(method_call, kMmcServiceError, + "'Config Param' must be set")); return; } @@ -198,43 +192,41 @@ void Service::CodecInit(dbus::MethodCall* method_call, } #endif else { - std::move(sender).Run(dbus::ErrorResponse::FromMethodCall( - method_call, kMmcServiceError, "Codec type must be specified")); + std::move(sender).Run(dbus::ErrorResponse::FromMethodCall(method_call, kMmcServiceError, + "Codec type must be specified")); return; } int frame_size = codec_server->init(request.config()); if (frame_size < 0) { std::move(sender).Run(dbus::ErrorResponse::FromMethodCall( - method_call, kMmcServiceError, - "Init codec server failed: " + std::string(strerror(-frame_size)))); + method_call, kMmcServiceError, + "Init codec server failed: " + std::string(strerror(-frame_size)))); return; } response.set_input_frame_size(frame_size); // Generate socket name for client. std::string socket_path = - std::string(kMmcSocketName) + base::UnguessableToken::Create().ToString(); + std::string(kMmcSocketName) + base::UnguessableToken::Create().ToString(); response.set_socket_token(socket_path); int skt_fd = socket(AF_UNIX, SOCK_SEQPACKET, 0); if (skt_fd < 0) { std::move(sender).Run(dbus::ErrorResponse::FromMethodCall( - method_call, kMmcServiceError, - "Create socket failed: " + std::string(strerror(errno)))); + method_call, kMmcServiceError, + "Create socket failed: " + std::string(strerror(errno)))); return; } struct sockaddr_un addr = {}; addr.sun_family = AF_UNIX; - strncpy(addr.sun_path, response.socket_token().c_str(), - sizeof(addr.sun_path) - 1); + strncpy(addr.sun_path, response.socket_token().c_str(), sizeof(addr.sun_path) - 1); unlink(addr.sun_path); if (bind(skt_fd, (struct sockaddr*)&addr, sizeof(struct sockaddr_un)) == -1) { std::move(sender).Run(dbus::ErrorResponse::FromMethodCall( - method_call, kMmcServiceError, - "Bind socket failed: " + std::string(strerror(errno)))); + method_call, kMmcServiceError, "Bind socket failed: " + std::string(strerror(errno)))); return; } @@ -242,22 +234,21 @@ void Service::CodecInit(dbus::MethodCall* method_call, int rc = chmod(addr.sun_path, 0770); if (rc < 0) { std::move(sender).Run(dbus::ErrorResponse::FromMethodCall( - method_call, kMmcServiceError, - "Chmod socket failed: " + std::string(strerror(errno)))); + method_call, kMmcServiceError, "Chmod socket failed: " + std::string(strerror(errno)))); return; } if (listen(skt_fd, kClientMaximum) == -1) { std::move(sender).Run(dbus::ErrorResponse::FromMethodCall( - method_call, kMmcServiceError, - "Listen socket failed: " + std::string(strerror(errno)))); + method_call, kMmcServiceError, + "Listen socket failed: " + std::string(strerror(errno)))); return; } // Create a thread and pass codec server and socket fd to it. if (!StartWorkerThread(skt_fd, std::move(addr), std::move(codec_server))) { - std::move(sender).Run(dbus::ErrorResponse::FromMethodCall( - method_call, kMmcServiceError, "No free thread available")); + std::move(sender).Run(dbus::ErrorResponse::FromMethodCall(method_call, kMmcServiceError, + "No free thread available")); return; } @@ -278,9 +269,9 @@ bool Service::StartWorkerThread(int fd, struct sockaddr_un addr, std::unique_ptr codec_server) { // Each thread has its associated future to indicate task completion. std::promise task_ended; - thread_pool_.push_back(std::make_pair( - std::make_unique(kWorkerThreadName), - std::make_unique>(task_ended.get_future()))); + thread_pool_.push_back( + std::make_pair(std::make_unique(kWorkerThreadName), + std::make_unique>(task_ended.get_future()))); // Start up thread and assign task to it. thread_pool_.back().first->StartUp(); @@ -296,9 +287,8 @@ bool Service::StartWorkerThread(int fd, struct sockaddr_un addr, } if (!thread_pool_.back().first->DoInThread( - FROM_HERE, - base::BindOnce(&StartSocketListener, fd, std::move(addr), - std::move(task_ended), std::move(codec_server)))) { + FROM_HERE, base::BindOnce(&StartSocketListener, fd, std::move(addr), + std::move(task_ended), std::move(codec_server)))) { log::error("Failed to run task"); return false; } @@ -308,8 +298,8 @@ bool Service::StartWorkerThread(int fd, struct sockaddr_un addr, void Service::RemoveIdleThread() { for (auto thread = thread_pool_.begin(); thread != thread_pool_.end();) { - if (thread->second->wait_for(std::chrono::milliseconds( - kThreadCheckTimeout)) == std::future_status::ready) { + if (thread->second->wait_for(std::chrono::milliseconds(kThreadCheckTimeout)) == + std::future_status::ready) { // The task is over, close the thread and remove it from the thread pool. thread->first->ShutDown(); thread = thread_pool_.erase(thread); diff --git a/system/stack/mmc/daemon/service.h b/system/stack/mmc/daemon/service.h index 129161e9174..c1b66ba0373 100644 --- a/system/stack/mmc/daemon/service.h +++ b/system/stack/mmc/daemon/service.h @@ -35,7 +35,7 @@ namespace mmc { class Service final { - public: +public: explicit Service(base::OnceClosure shutdown_callback); // Service is neither copyable nor movable. @@ -45,7 +45,7 @@ class Service final { // Connects to DBus and exports methods for client to call. bool Init(); - private: +private: /* DBus Methods */ // Main thread creates a codec server instance and a socket, // and calls |StartWorkerThread| to let one thread start listening on the @@ -56,16 +56,14 @@ class Service final { // Response: // |CodecInitResponse|, if |CodecInit| succeeded. // ErrorResponse, otherwise. - void CodecInit(dbus::MethodCall* method_call, - dbus::ExportedObject::ResponseSender sender); + void CodecInit(dbus::MethodCall* method_call, dbus::ExportedObject::ResponseSender sender); // Main thread removes idle threads from the thread poll. // // No input message needed. // Response: // dbus::Response, implying |CodecCleanUp| finished. - void CodecCleanUp(dbus::MethodCall* method_call, - dbus::ExportedObject::ResponseSender sender); + void CodecCleanUp(dbus::MethodCall* method_call, dbus::ExportedObject::ResponseSender sender); /* Thread Management*/ // Adds a thread to the thread pool and makes it listen on the socket fd. @@ -82,7 +80,7 @@ class Service final { std::vector, std::unique_ptr>>> - thread_pool_; + thread_pool_; base::WeakPtrFactory weak_ptr_factory_; }; diff --git a/system/stack/mmc/main.cc b/system/stack/mmc/main.cc index c2f808b47d2..75de58852e5 100644 --- a/system/stack/mmc/main.cc +++ b/system/stack/mmc/main.cc @@ -42,10 +42,10 @@ const int kSyslogCritical = LOG_CRIT; #undef LOG_CRIT } // namespace -static bool MessageHandler(int severity, const char* file, int line, - size_t message_start, const std::string& message) { - const auto str = base::StringPrintf("%s:%d - %s", file, line, - message.substr(message_start).c_str()); +static bool MessageHandler(int severity, const char* file, int line, size_t message_start, + const std::string& message) { + const auto str = + base::StringPrintf("%s:%d - %s", file, line, message.substr(message_start).c_str()); switch (severity) { case logging::LOGGING_INFO: @@ -71,7 +71,9 @@ static bool MessageHandler(int severity, const char* file, int line, syslog(severity, "%s", str.c_str()); - if (severity == kSyslogCritical) abort(); + if (severity == kSyslogCritical) { + abort(); + } return true; } @@ -79,8 +81,7 @@ static bool MessageHandler(int severity, const char* file, int line, int main(int argc, char* argv[]) { // Set up syslog to stderr. logging::LoggingSettings settings; - settings.logging_dest = - logging::LOG_TO_SYSTEM_DEBUG_LOG | logging::LOG_TO_STDERR; + settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG | logging::LOG_TO_STDERR; logging::SetLogItems(false, false, false, false); logging::InitLogging(settings); logging::SetLogMessageHandler(MessageHandler); @@ -97,8 +98,7 @@ int main(int argc, char* argv[]) { base::RunLoop run_loop; auto service = std::make_unique(run_loop.QuitClosure()); - bluetooth::log::assert_that(service->Init(), - "assert failed: service->Init()"); + bluetooth::log::assert_that(service->Init(), "assert failed: service->Init()"); run_loop.Run(); diff --git a/system/stack/mmc/metrics/mmc_rtt_logger.cc b/system/stack/mmc/metrics/mmc_rtt_logger.cc index aef9cf31dbe..761d825b447 100644 --- a/system/stack/mmc/metrics/mmc_rtt_logger.cc +++ b/system/stack/mmc/metrics/mmc_rtt_logger.cc @@ -30,7 +30,9 @@ MmcRttLogger::MmcRttLogger(int codec_type) MmcRttLogger::~MmcRttLogger() {} void MmcRttLogger::RecordRtt(int64_t elapsed_time) { - if (elapsed_time <= 0) return; + if (elapsed_time <= 0) { + return; + } num_requests_ += 1; rtt_sum_ += elapsed_time; maximum_rtt_ = std::max(maximum_rtt_, elapsed_time); @@ -38,9 +40,10 @@ void MmcRttLogger::RecordRtt(int64_t elapsed_time) { } void MmcRttLogger::UploadTranscodeRttStatics() { - if (num_requests_ == 0) return; - log_mmc_transcode_rtt_stats(maximum_rtt_, rtt_sum_ / num_requests_, - num_requests_, codec_type_); + if (num_requests_ == 0) { + return; + } + log_mmc_transcode_rtt_stats(maximum_rtt_, rtt_sum_ / num_requests_, num_requests_, codec_type_); num_requests_ = 0; rtt_sum_ = 0; maximum_rtt_ = 0; diff --git a/system/stack/mmc/metrics/mmc_rtt_logger.h b/system/stack/mmc/metrics/mmc_rtt_logger.h index 1987c20004c..0106c522cd4 100644 --- a/system/stack/mmc/metrics/mmc_rtt_logger.h +++ b/system/stack/mmc/metrics/mmc_rtt_logger.h @@ -25,7 +25,7 @@ namespace mmc { // MmcRttLogger computes and uploads below rtt stats: // Maximum rtt, mean rtt, num requests, codec type. class MmcRttLogger { - public: +public: explicit MmcRttLogger(int codec_type); ~MmcRttLogger(); @@ -41,7 +41,7 @@ class MmcRttLogger { // and clears the record. Empty record will be ignored. void UploadTranscodeRttStatics(); - private: +private: int codec_type_; int64_t num_requests_; double rtt_sum_; // for computing mean rtt diff --git a/system/stack/mmc/mmc_interface/mmc_interface.h b/system/stack/mmc/mmc_interface/mmc_interface.h index a6c35f0c6cb..29c40659904 100644 --- a/system/stack/mmc/mmc_interface/mmc_interface.h +++ b/system/stack/mmc/mmc_interface/mmc_interface.h @@ -25,7 +25,7 @@ namespace mmc { // An abstract interface representing either an encoder or a decoder. class MmcInterface { - public: +public: virtual ~MmcInterface() = default; // Builds and configures the encoder/decoder instance. @@ -43,8 +43,7 @@ class MmcInterface { // Returns: // Transcoded data length, if transcode succeeded. // Negative errno on error, otherwise. - virtual int transcode(uint8_t* i_buf, int i_len, uint8_t* o_buf, - int o_len) = 0; + virtual int transcode(uint8_t* i_buf, int i_len, uint8_t* o_buf, int o_len) = 0; }; } // namespace mmc diff --git a/system/stack/mmc/test/hfp_lc3_mmc_decoder_test.cc b/system/stack/mmc/test/hfp_lc3_mmc_decoder_test.cc index 605fef4c4f7..692ecb92f4b 100644 --- a/system/stack/mmc/test/hfp_lc3_mmc_decoder_test.cc +++ b/system/stack/mmc/test/hfp_lc3_mmc_decoder_test.cc @@ -41,8 +41,8 @@ const uint8_t kInputBuf[kInputLen] = {0}; static uint8_t kOutputBuf[kOutputLen] = {0}; class HfpLc3DecoderTest : public Test { - public: - protected: +public: +protected: void SetUp() override { reset_mock_function_count_map(); decoder_ = std::make_unique(); @@ -52,17 +52,15 @@ class HfpLc3DecoderTest : public Test { }; class HfpLc3DecoderWithInitTest : public HfpLc3DecoderTest { - public: - protected: +public: +protected: void SetUp() override { test::mock::osi_allocator::osi_malloc.body = [&](size_t size) { this->lc3_decoder_ = new struct lc3_decoder; return (void*)this->lc3_decoder_; }; test::mock::embdrv_lc3::lc3_setup_decoder.body = - [this](int dt_us, int sr_hz, int sr_pcm_hz, void* mem) { - return this->lc3_decoder_; - }; + [this](int dt_us, int sr_hz, int sr_pcm_hz, void* mem) { return this->lc3_decoder_; }; test::mock::osi_allocator::osi_free_and_reset.body = [&](void** p_ptr) { delete this->lc3_decoder_; lc3_decoder_ = nullptr; @@ -100,8 +98,8 @@ TEST_F(HfpLc3DecoderTest, InitWrongConfig) { *config.mutable_hfp_lc3_decoder_param() = mmc::Lc3Param(); // lc3_setup_decoder failed due to wrong parameters (returned nullptr). - test::mock::embdrv_lc3::lc3_setup_decoder.body = - [](int dt_us, int sr_hz, int sr_pcm_hz, void* mem) { return nullptr; }; + test::mock::embdrv_lc3::lc3_setup_decoder.body = [](int dt_us, int sr_hz, int sr_pcm_hz, + void* mem) { return nullptr; }; int ret = decoder_->init(config); EXPECT_EQ(ret, -EINVAL); @@ -117,9 +115,7 @@ TEST_F(HfpLc3DecoderTest, InitSuccess) { // lc3_setup_decoder returns decoder instance pointer. struct lc3_decoder lc3_decoder; test::mock::embdrv_lc3::lc3_setup_decoder.body = - [&lc3_decoder](int dt_us, int sr_hz, int sr_pcm_hz, void* mem) { - return &lc3_decoder; - }; + [&lc3_decoder](int dt_us, int sr_hz, int sr_pcm_hz, void* mem) { return &lc3_decoder; }; int ret = decoder_->init(config); EXPECT_EQ(ret, mmc::HFP_LC3_PKT_FRAME_LEN); @@ -144,8 +140,7 @@ TEST_F(HfpLc3DecoderWithInitTest, TranscodeWrongParam) { // lc3_decode failed (returned value neither zero nor one). test::mock::embdrv_lc3::lc3_decode.return_value = -1; - int ret = decoder_->transcode((uint8_t*)kInputBuf, kInputLen, kOutputBuf, - kOutputLen); + int ret = decoder_->transcode((uint8_t*)kInputBuf, kInputLen, kOutputBuf, kOutputLen); EXPECT_EQ(ret, mmc::HFP_LC3_PCM_BYTES + 1); EXPECT_THAT(kOutputBuf, Each(0)); EXPECT_EQ(get_func_call_count("lc3_decode"), 1); @@ -157,8 +152,7 @@ TEST_F(HfpLc3DecoderWithInitTest, TranscodePLC) { // lc3_decode conducted PLC (return one). test::mock::embdrv_lc3::lc3_decode.return_value = 1; - int ret = decoder_->transcode((uint8_t*)kInputBuf, kInputLen, kOutputBuf, - kOutputLen); + int ret = decoder_->transcode((uint8_t*)kInputBuf, kInputLen, kOutputBuf, kOutputLen); EXPECT_EQ(ret, mmc::HFP_LC3_PCM_BYTES + 1); EXPECT_EQ(kOutputBuf[0], 1); EXPECT_EQ(get_func_call_count("lc3_decode"), 1); @@ -170,8 +164,7 @@ TEST_F(HfpLc3DecoderWithInitTest, TranscodeSuccess) { // lc3_decode succeeded (return zero value). test::mock::embdrv_lc3::lc3_decode.return_value = 0; - int ret = decoder_->transcode((uint8_t*)kInputBuf, kInputLen, kOutputBuf, - kOutputLen); + int ret = decoder_->transcode((uint8_t*)kInputBuf, kInputLen, kOutputBuf, kOutputLen); EXPECT_EQ(ret, mmc::HFP_LC3_PCM_BYTES + 1); EXPECT_EQ(kOutputBuf[0], 0); EXPECT_THAT(kOutputBuf, Contains(Ne(0))); diff --git a/system/stack/mmc/test/hfp_lc3_mmc_encoder_test.cc b/system/stack/mmc/test/hfp_lc3_mmc_encoder_test.cc index f1791a3b7bd..2745edaac33 100644 --- a/system/stack/mmc/test/hfp_lc3_mmc_encoder_test.cc +++ b/system/stack/mmc/test/hfp_lc3_mmc_encoder_test.cc @@ -41,8 +41,8 @@ const uint8_t kInputBuf[kInputLen] = {0}; static uint8_t kOutputBuf[kOutputLen] = {0}; class HfpLc3EncoderTest : public Test { - public: - protected: +public: +protected: void SetUp() override { reset_mock_function_count_map(); encoder_ = std::make_unique(); @@ -52,17 +52,15 @@ class HfpLc3EncoderTest : public Test { }; class HfpLc3EncoderWithInitTest : public HfpLc3EncoderTest { - public: - protected: +public: +protected: void SetUp() override { test::mock::osi_allocator::osi_malloc.body = [&](size_t size) { this->lc3_encoder_ = new struct lc3_encoder; return (void*)this->lc3_encoder_; }; test::mock::embdrv_lc3::lc3_setup_encoder.body = - [this](int dt_us, int sr_hz, int sr_pcm_hz, void* mem) { - return this->lc3_encoder_; - }; + [this](int dt_us, int sr_hz, int sr_pcm_hz, void* mem) { return this->lc3_encoder_; }; test::mock::osi_allocator::osi_free_and_reset.body = [&](void** p_ptr) { delete this->lc3_encoder_; lc3_encoder_ = nullptr; @@ -100,8 +98,8 @@ TEST_F(HfpLc3EncoderTest, InitWrongConfig) { *config.mutable_hfp_lc3_encoder_param() = mmc::Lc3Param(); // lc3_setup_encoder failed due to wrong parameters (returned nullptr). - test::mock::embdrv_lc3::lc3_setup_encoder.body = - [](int dt_us, int sr_hz, int sr_pcm_hz, void* mem) { return nullptr; }; + test::mock::embdrv_lc3::lc3_setup_encoder.body = [](int dt_us, int sr_hz, int sr_pcm_hz, + void* mem) { return nullptr; }; int ret = encoder_->init(config); EXPECT_EQ(ret, -EINVAL); @@ -117,9 +115,7 @@ TEST_F(HfpLc3EncoderTest, InitSuccess) { // lc3_setup_encoder returns encoder instance pointer. struct lc3_encoder lc3_encoder; test::mock::embdrv_lc3::lc3_setup_encoder.body = - [&lc3_encoder](int dt_us, int sr_hz, int sr_pcm_hz, void* mem) { - return &lc3_encoder; - }; + [&lc3_encoder](int dt_us, int sr_hz, int sr_pcm_hz, void* mem) { return &lc3_encoder; }; int ret = encoder_->init(config); EXPECT_EQ(ret, mmc::HFP_LC3_PCM_BYTES); @@ -149,8 +145,7 @@ TEST_F(HfpLc3EncoderWithInitTest, TranscodeWrongParam) { // lc3_encode failed (returned non-zero value). test::mock::embdrv_lc3::lc3_encode.return_value = 1; - int ret = encoder_->transcode((uint8_t*)kInputBuf, kInputLen, kOutputBuf, - kOutputLen); + int ret = encoder_->transcode((uint8_t*)kInputBuf, kInputLen, kOutputBuf, kOutputLen); EXPECT_EQ(ret, mmc::HFP_LC3_PKT_FRAME_LEN); EXPECT_THAT(kOutputBuf, Each(0)); EXPECT_EQ(get_func_call_count("lc3_encode"), 1); @@ -162,8 +157,7 @@ TEST_F(HfpLc3EncoderWithInitTest, TranscodeSuccess) { // lc3_encode succeeded (return zero value). test::mock::embdrv_lc3::lc3_encode.return_value = 0; - int ret = encoder_->transcode((uint8_t*)kInputBuf, kInputLen, kOutputBuf, - kOutputLen); + int ret = encoder_->transcode((uint8_t*)kInputBuf, kInputLen, kOutputBuf, kOutputLen); EXPECT_EQ(ret, mmc::HFP_LC3_PKT_FRAME_LEN); EXPECT_THAT(kOutputBuf, Contains(Ne(0))); EXPECT_EQ(get_func_call_count("lc3_encode"), 1); diff --git a/system/stack/mmc/test/mock/mock_embdrv_lc3.cc b/system/stack/mmc/test/mock/mock_embdrv_lc3.cc index ff7d5c60841..f085bc1a5dd 100644 --- a/system/stack/mmc/test/mock/mock_embdrv_lc3.cc +++ b/system/stack/mmc/test/mock/mock_embdrv_lc3.cc @@ -73,11 +73,10 @@ struct lc3_encoder* lc3_setup_encoder::return_value = nullptr; } // namespace test // Mocked functions, if any -int lc3_decode(struct lc3_decoder* decoder, const void* in, int nbytes, - enum lc3_pcm_format fmt, void* pcm, int stride) { +int lc3_decode(struct lc3_decoder* decoder, const void* in, int nbytes, enum lc3_pcm_format fmt, + void* pcm, int stride) { inc_func_call_count(__func__); - return test::mock::embdrv_lc3::lc3_decode(decoder, in, nbytes, fmt, pcm, - stride); + return test::mock::embdrv_lc3::lc3_decode(decoder, in, nbytes, fmt, pcm, stride); } unsigned lc3_decoder_size(int dt_us, int sr_hz) { inc_func_call_count(__func__); @@ -87,11 +86,10 @@ int lc3_delay_samples(int dt_us, int sr_hz) { inc_func_call_count(__func__); return test::mock::embdrv_lc3::lc3_delay_samples(dt_us, sr_hz); } -int lc3_encode(struct lc3_encoder* encoder, enum lc3_pcm_format fmt, - const void* pcm, int stride, int nbytes, void* out) { +int lc3_encode(struct lc3_encoder* encoder, enum lc3_pcm_format fmt, const void* pcm, int stride, + int nbytes, void* out) { inc_func_call_count(__func__); - return test::mock::embdrv_lc3::lc3_encode(encoder, fmt, pcm, stride, nbytes, - out); + return test::mock::embdrv_lc3::lc3_encode(encoder, fmt, pcm, stride, nbytes, out); } unsigned lc3_encoder_size(int dt_us, int sr_hz) { inc_func_call_count(__func__); @@ -109,17 +107,13 @@ int lc3_resolve_bitrate(int dt_us, int nbytes) { inc_func_call_count(__func__); return test::mock::embdrv_lc3::lc3_resolve_bitrate(dt_us, nbytes); } -struct lc3_decoder* lc3_setup_decoder(int dt_us, int sr_hz, int sr_pcm_hz, - void* mem) { +struct lc3_decoder* lc3_setup_decoder(int dt_us, int sr_hz, int sr_pcm_hz, void* mem) { inc_func_call_count(__func__); - return test::mock::embdrv_lc3::lc3_setup_decoder(dt_us, sr_hz, sr_pcm_hz, - mem); + return test::mock::embdrv_lc3::lc3_setup_decoder(dt_us, sr_hz, sr_pcm_hz, mem); } -struct lc3_encoder* lc3_setup_encoder(int dt_us, int sr_hz, int sr_pcm_hz, - void* mem) { +struct lc3_encoder* lc3_setup_encoder(int dt_us, int sr_hz, int sr_pcm_hz, void* mem) { inc_func_call_count(__func__); - return test::mock::embdrv_lc3::lc3_setup_encoder(dt_us, sr_hz, sr_pcm_hz, - mem); + return test::mock::embdrv_lc3::lc3_setup_encoder(dt_us, sr_hz, sr_pcm_hz, mem); } // Mocked functions complete // END mockcify generation diff --git a/system/stack/mmc/test/mock/mock_embdrv_lc3.h b/system/stack/mmc/test/mock/mock_embdrv_lc3.h index 8e7bfcfe80f..d360d78c914 100644 --- a/system/stack/mmc/test/mock/mock_embdrv_lc3.h +++ b/system/stack/mmc/test/mock/mock_embdrv_lc3.h @@ -42,13 +42,12 @@ struct lc3_decode { static int return_value; std::function - body{[](struct lc3_decoder* decoder, const void* in, int nbytes, - enum lc3_pcm_format fmt, void* pcm, - int stride) { return return_value; }}; - int operator()(struct lc3_decoder* decoder, const void* in, int nbytes, - enum lc3_pcm_format fmt, void* pcm, int stride) { + body{[](struct lc3_decoder* decoder, const void* in, int nbytes, enum lc3_pcm_format fmt, + void* pcm, int stride) { return return_value; }}; + int operator()(struct lc3_decoder* decoder, const void* in, int nbytes, enum lc3_pcm_format fmt, + void* pcm, int stride) { return body(decoder, in, nbytes, fmt, pcm, stride); - }; + } }; extern struct lc3_decode lc3_decode; @@ -58,8 +57,8 @@ extern struct lc3_decode lc3_decode; struct lc3_decoder_size { static unsigned return_value; std::function body{ - [](int dt_us, int sr_hz) { return return_value; }}; - unsigned operator()(int dt_us, int sr_hz) { return body(dt_us, sr_hz); }; + [](int dt_us, int sr_hz) { return return_value; }}; + unsigned operator()(int dt_us, int sr_hz) { return body(dt_us, sr_hz); } }; extern struct lc3_decoder_size lc3_decoder_size; @@ -68,9 +67,8 @@ extern struct lc3_decoder_size lc3_decoder_size; // Return: int struct lc3_delay_samples { static int return_value; - std::function body{ - [](int dt_us, int sr_hz) { return return_value; }}; - int operator()(int dt_us, int sr_hz) { return body(dt_us, sr_hz); }; + std::function body{[](int dt_us, int sr_hz) { return return_value; }}; + int operator()(int dt_us, int sr_hz) { return body(dt_us, sr_hz); } }; extern struct lc3_delay_samples lc3_delay_samples; @@ -79,15 +77,14 @@ extern struct lc3_delay_samples lc3_delay_samples; // pcm, int stride, int nbytes, void* out Return: int struct lc3_encode { static int return_value; - std::function - body{[](struct lc3_encoder* encoder, enum lc3_pcm_format fmt, - const void* pcm, int stride, int nbytes, - void* out) { return return_value; }}; - int operator()(struct lc3_encoder* encoder, enum lc3_pcm_format fmt, - const void* pcm, int stride, int nbytes, void* out) { + std::function + body{[](struct lc3_encoder* encoder, enum lc3_pcm_format fmt, const void* pcm, int stride, + int nbytes, void* out) { return return_value; }}; + int operator()(struct lc3_encoder* encoder, enum lc3_pcm_format fmt, const void* pcm, int stride, + int nbytes, void* out) { return body(encoder, fmt, pcm, stride, nbytes, out); - }; + } }; extern struct lc3_encode lc3_encode; @@ -97,8 +94,8 @@ extern struct lc3_encode lc3_encode; struct lc3_encoder_size { static unsigned return_value; std::function body{ - [](int dt_us, int sr_hz) { return return_value; }}; - unsigned operator()(int dt_us, int sr_hz) { return body(dt_us, sr_hz); }; + [](int dt_us, int sr_hz) { return return_value; }}; + unsigned operator()(int dt_us, int sr_hz) { return body(dt_us, sr_hz); } }; extern struct lc3_encoder_size lc3_encoder_size; @@ -108,8 +105,8 @@ extern struct lc3_encoder_size lc3_encoder_size; struct lc3_frame_bytes { static int return_value; std::function body{ - [](int dt_us, int bitrate) { return return_value; }}; - int operator()(int dt_us, int bitrate) { return body(dt_us, bitrate); }; + [](int dt_us, int bitrate) { return return_value; }}; + int operator()(int dt_us, int bitrate) { return body(dt_us, bitrate); } }; extern struct lc3_frame_bytes lc3_frame_bytes; @@ -118,9 +115,8 @@ extern struct lc3_frame_bytes lc3_frame_bytes; // Return: int struct lc3_frame_samples { static int return_value; - std::function body{ - [](int dt_us, int sr_hz) { return return_value; }}; - int operator()(int dt_us, int sr_hz) { return body(dt_us, sr_hz); }; + std::function body{[](int dt_us, int sr_hz) { return return_value; }}; + int operator()(int dt_us, int sr_hz) { return body(dt_us, sr_hz); } }; extern struct lc3_frame_samples lc3_frame_samples; @@ -130,8 +126,8 @@ extern struct lc3_frame_samples lc3_frame_samples; struct lc3_resolve_bitrate { static int return_value; std::function body{ - [](int dt_us, int nbytes) { return return_value; }}; - int operator()(int dt_us, int nbytes) { return body(dt_us, nbytes); }; + [](int dt_us, int nbytes) { return return_value; }}; + int operator()(int dt_us, int nbytes) { return body(dt_us, nbytes); } }; extern struct lc3_resolve_bitrate lc3_resolve_bitrate; @@ -140,15 +136,11 @@ extern struct lc3_resolve_bitrate lc3_resolve_bitrate; // Return: struct lc3_decoder* struct lc3_setup_decoder { static struct lc3_decoder* return_value; - std::function - body{[](int dt_us, int sr_hz, int sr_pcm_hz, void* mem) { - return return_value; - }}; - struct lc3_decoder* operator()(int dt_us, int sr_hz, int sr_pcm_hz, - void* mem) { + std::function body{ + [](int dt_us, int sr_hz, int sr_pcm_hz, void* mem) { return return_value; }}; + struct lc3_decoder* operator()(int dt_us, int sr_hz, int sr_pcm_hz, void* mem) { return body(dt_us, sr_hz, sr_pcm_hz, mem); - }; + } }; extern struct lc3_setup_decoder lc3_setup_decoder; @@ -157,15 +149,11 @@ extern struct lc3_setup_decoder lc3_setup_decoder; // Return: struct lc3_encoder* struct lc3_setup_encoder { static struct lc3_encoder* return_value; - std::function - body{[](int dt_us, int sr_hz, int sr_pcm_hz, void* mem) { - return return_value; - }}; - struct lc3_encoder* operator()(int dt_us, int sr_hz, int sr_pcm_hz, - void* mem) { + std::function body{ + [](int dt_us, int sr_hz, int sr_pcm_hz, void* mem) { return return_value; }}; + struct lc3_encoder* operator()(int dt_us, int sr_hz, int sr_pcm_hz, void* mem) { return body(dt_us, sr_hz, sr_pcm_hz, mem); - }; + } }; extern struct lc3_setup_encoder lc3_setup_encoder; diff --git a/system/stack/pan/pan_api.cc b/system/stack/pan/pan_api.cc index 73d9b2d9027..b3ca583b09f 100644 --- a/system/stack/pan/pan_api.cc +++ b/system/stack/pan/pan_api.cc @@ -75,7 +75,9 @@ extern std::string nap_service_name; /* Service name for NAP role */ * ******************************************************************************/ void PAN_Register(tPAN_REGISTER* p_register) { - if (!p_register) return; + if (!p_register) { + return; + } pan_register_with_bnep(); @@ -138,8 +140,7 @@ void PAN_Deregister(void) { * PAN_FAILURE - if the role is not valid * ******************************************************************************/ -tPAN_RESULT PAN_SetRole(uint8_t role, std::string p_user_name, - std::string p_nap_name) { +tPAN_RESULT PAN_SetRole(uint8_t role, std::string p_user_name, std::string p_nap_name) { /* Check if it is a shutdown request */ if (role == PAN_ROLE_INACTIVE) { pan_close_all_connections(); @@ -152,8 +153,7 @@ tPAN_RESULT PAN_SetRole(uint8_t role, std::string p_user_name, const char* p_desc; /* If the role is not a valid combination reject it */ - if ((!(role & (PAN_ROLE_CLIENT | PAN_ROLE_NAP_SERVER))) && - role != PAN_ROLE_INACTIVE) { + if ((!(role & (PAN_ROLE_CLIENT | PAN_ROLE_NAP_SERVER))) && role != PAN_ROLE_INACTIVE) { log::error("PAN role {} is invalid", role); return PAN_FAILURE; } @@ -168,22 +168,21 @@ tPAN_RESULT PAN_SetRole(uint8_t role, std::string p_user_name, log::verbose("PAN_SetRole() called with role 0x{:x}", role); if (role & PAN_ROLE_NAP_SERVER) { /* Check the service name */ - if (p_nap_name.empty()) + if (p_nap_name.empty()) { p_nap_name = std::string(PAN_NAP_DEFAULT_SERVICE_NAME); + } /* Registering for NAP service with SDP */ p_desc = PAN_NAP_DEFAULT_DESCRIPTION; if (pan_cb.pan_nap_sdp_handle != 0) { - if (!get_legacy_stack_sdp_api()->handle.SDP_DeleteRecord( - pan_cb.pan_nap_sdp_handle)) { - log::warn("Unable to delete SDP record handle:{}", - pan_cb.pan_nap_sdp_handle); + if (!get_legacy_stack_sdp_api()->handle.SDP_DeleteRecord(pan_cb.pan_nap_sdp_handle)) { + log::warn("Unable to delete SDP record handle:{}", pan_cb.pan_nap_sdp_handle); } } pan_cb.pan_nap_sdp_handle = - pan_register_with_sdp(UUID_SERVCLASS_NAP, p_nap_name.c_str(), p_desc); + pan_register_with_sdp(UUID_SERVCLASS_NAP, p_nap_name.c_str(), p_desc); bta_sys_add_uuid(UUID_SERVCLASS_NAP); nap_service_name = p_nap_name; } @@ -191,10 +190,8 @@ tPAN_RESULT PAN_SetRole(uint8_t role, std::string p_user_name, */ else if (pan_cb.role & PAN_ROLE_NAP_SERVER) { if (pan_cb.pan_nap_sdp_handle != 0) { - if (!get_legacy_stack_sdp_api()->handle.SDP_DeleteRecord( - pan_cb.pan_nap_sdp_handle)) { - log::warn("Unable to delete SDP record handle:{}", - pan_cb.pan_nap_sdp_handle); + if (!get_legacy_stack_sdp_api()->handle.SDP_DeleteRecord(pan_cb.pan_nap_sdp_handle)) { + log::warn("Unable to delete SDP record handle:{}", pan_cb.pan_nap_sdp_handle); } pan_cb.pan_nap_sdp_handle = 0; bta_sys_remove_uuid(UUID_SERVCLASS_NAP); @@ -204,20 +201,20 @@ tPAN_RESULT PAN_SetRole(uint8_t role, std::string p_user_name, if (role & PAN_ROLE_CLIENT) { /* Check the service name */ - if (p_user_name.empty()) p_user_name = PAN_PANU_DEFAULT_SERVICE_NAME; + if (p_user_name.empty()) { + p_user_name = PAN_PANU_DEFAULT_SERVICE_NAME; + } /* Registering for PANU service with SDP */ p_desc = PAN_PANU_DEFAULT_DESCRIPTION; if (pan_cb.pan_user_sdp_handle != 0) { - if (!get_legacy_stack_sdp_api()->handle.SDP_DeleteRecord( - pan_cb.pan_user_sdp_handle)) { - log::warn("Unable to delete SDP record handle:{}", - pan_cb.pan_user_sdp_handle); + if (!get_legacy_stack_sdp_api()->handle.SDP_DeleteRecord(pan_cb.pan_user_sdp_handle)) { + log::warn("Unable to delete SDP record handle:{}", pan_cb.pan_user_sdp_handle); } } pan_cb.pan_user_sdp_handle = - pan_register_with_sdp(UUID_SERVCLASS_PANU, p_user_name.c_str(), p_desc); + pan_register_with_sdp(UUID_SERVCLASS_PANU, p_user_name.c_str(), p_desc); bta_sys_add_uuid(UUID_SERVCLASS_PANU); user_service_name = p_user_name; } @@ -225,10 +222,8 @@ tPAN_RESULT PAN_SetRole(uint8_t role, std::string p_user_name, */ else if (pan_cb.role & PAN_ROLE_CLIENT) { if (pan_cb.pan_user_sdp_handle != 0) { - if (get_legacy_stack_sdp_api()->handle.SDP_DeleteRecord( - pan_cb.pan_user_sdp_handle)) { - log::warn("Unable to delete SDP record handle:{}", - pan_cb.pan_user_sdp_handle); + if (get_legacy_stack_sdp_api()->handle.SDP_DeleteRecord(pan_cb.pan_user_sdp_handle)) { + log::warn("Unable to delete SDP record handle:{}", pan_cb.pan_user_sdp_handle); } pan_cb.pan_user_sdp_handle = 0; bta_sys_remove_uuid(UUID_SERVCLASS_PANU); @@ -267,8 +262,8 @@ tPAN_RESULT PAN_SetRole(uint8_t role, std::string p_user_name, * allowed at that point of time * ******************************************************************************/ -tPAN_RESULT PAN_Connect(const RawAddress& rem_bda, tPAN_ROLE src_role, - tPAN_ROLE dst_role, uint16_t* handle) { +tPAN_RESULT PAN_Connect(const RawAddress& rem_bda, tPAN_ROLE src_role, tPAN_ROLE dst_role, + uint16_t* handle) { uint32_t mx_chan_id; /* @@ -286,8 +281,7 @@ tPAN_RESULT PAN_Connect(const RawAddress& rem_bda, tPAN_ROLE src_role, /* Validate the parameters before proceeding */ if ((src_role != PAN_ROLE_CLIENT && src_role != PAN_ROLE_NAP_SERVER) || (dst_role != PAN_ROLE_CLIENT && dst_role != PAN_ROLE_NAP_SERVER)) { - log::error("Either source {} or destination role {} is invalid", src_role, - dst_role); + log::error("Either source {} or destination role {} is invalid", src_role, dst_role); return PAN_FAILURE; } @@ -304,8 +298,8 @@ tPAN_RESULT PAN_Connect(const RawAddress& rem_bda, tPAN_ROLE src_role, ** another connection in PANU role */ log::error( - "Cannot make PANU connections when there are more than one " - "connection"); + "Cannot make PANU connections when there are more than one " + "connection"); return PAN_INVALID_SRC_ROLE; } @@ -330,13 +324,14 @@ tPAN_RESULT PAN_Connect(const RawAddress& rem_bda, tPAN_ROLE src_role, } /* The role combination is not valid */ else { - log::error("Source {} and Destination roles {} are not valid combination", - src_role, dst_role); + log::error("Source {} and Destination roles {} are not valid combination", src_role, dst_role); return PAN_FAILURE; } /* Allocate control block and initiate connection */ - if (!pcb) pcb = pan_allocate_pcb(rem_bda, BNEP_INVALID_HANDLE); + if (!pcb) { + pcb = pan_allocate_pcb(rem_bda, BNEP_INVALID_HANDLE); + } if (!pcb) { log::error("PAN Connection failed because of no resources"); return PAN_NO_RESOURCES; @@ -347,9 +342,10 @@ tPAN_RESULT PAN_Connect(const RawAddress& rem_bda, tPAN_ROLE src_role, pan_cb.num_conns++; } else if (pcb->con_state == PAN_STATE_CONNECTED) { pcb->con_flags |= PAN_FLAGS_CONN_COMPLETED; - } else + } else { /* PAN connection is still in progress */ return PAN_WRONG_STATE; + } pcb->con_state = PAN_STATE_CONN_START; pcb->prv_src_uuid = pcb->src_uuid; @@ -358,9 +354,8 @@ tPAN_RESULT PAN_Connect(const RawAddress& rem_bda, tPAN_ROLE src_role, pcb->src_uuid = src_uuid; pcb->dst_uuid = dst_uuid; - tBNEP_RESULT ret = - BNEP_Connect(rem_bda, Uuid::From16Bit(src_uuid), - Uuid::From16Bit(dst_uuid), &(pcb->handle), mx_chan_id); + tBNEP_RESULT ret = BNEP_Connect(rem_bda, Uuid::From16Bit(src_uuid), Uuid::From16Bit(dst_uuid), + &(pcb->handle), mx_chan_id); if (ret != BNEP_SUCCESS) { pan_release_pcb(pcb); return (tPAN_RESULT)ret; @@ -399,10 +394,13 @@ tPAN_RESULT PAN_Disconnect(uint16_t handle) { } result = BNEP_Disconnect(pcb->handle); - if (pcb->con_state != PAN_STATE_IDLE) pan_cb.num_conns--; + if (pcb->con_state != PAN_STATE_IDLE) { + pan_cb.num_conns--; + } - if (pan_cb.pan_bridge_req_cb && pcb->src_uuid == UUID_SERVCLASS_NAP) + if (pan_cb.pan_bridge_req_cb && pcb->src_uuid == UUID_SERVCLASS_NAP) { (*pan_cb.pan_bridge_req_cb)(pcb->rem_bda, false); + } BTM_LogHistory(kBtmLogTag, pcb->rem_bda, "Disconnect"); @@ -440,9 +438,8 @@ tPAN_RESULT PAN_Disconnect(uint16_t handle) { * there is an error in sending data * ******************************************************************************/ -tPAN_RESULT PAN_Write(uint16_t handle, const RawAddress& dst, - const RawAddress& src, uint16_t protocol, uint8_t* p_data, - uint16_t len, bool ext) { +tPAN_RESULT PAN_Write(uint16_t handle, const RawAddress& dst, const RawAddress& src, + uint16_t protocol, uint8_t* p_data, uint16_t len, bool ext) { if (pan_cb.role == PAN_ROLE_INACTIVE || !pan_cb.num_conns) { log::error("PAN is not active, data write failed."); return PAN_FAILURE; @@ -455,8 +452,9 @@ tPAN_RESULT PAN_Write(uint16_t handle, const RawAddress& dst, if (dst.address[0] & 0x01) { int i; for (i = 0; i < MAX_PAN_CONNS; ++i) { - if (pan_cb.pcb[i].con_state == PAN_STATE_CONNECTED) + if (pan_cb.pcb[i].con_state == PAN_STATE_CONNECTED) { BNEP_Write(pan_cb.pcb[i].handle, dst, p_data, len, protocol, src, ext); + } } return PAN_SUCCESS; } @@ -464,8 +462,7 @@ tPAN_RESULT PAN_Write(uint16_t handle, const RawAddress& dst, BT_HDR* buffer = (BT_HDR*)osi_malloc(PAN_BUF_SIZE); buffer->len = len; buffer->offset = PAN_MINIMUM_OFFSET; - memcpy((uint8_t*)buffer + sizeof(BT_HDR) + buffer->offset, p_data, - buffer->len); + memcpy((uint8_t*)buffer + sizeof(BT_HDR) + buffer->offset, p_data, buffer->len); return PAN_WriteBuf(handle, dst, src, protocol, buffer, ext); } @@ -493,9 +490,8 @@ tPAN_RESULT PAN_Write(uint16_t handle, const RawAddress& dst, * there is an error in sending data * ******************************************************************************/ -tPAN_RESULT PAN_WriteBuf(uint16_t handle, const RawAddress& dst, - const RawAddress& src, uint16_t protocol, - BT_HDR* p_buf, bool ext) { +tPAN_RESULT PAN_WriteBuf(uint16_t handle, const RawAddress& dst, const RawAddress& src, + uint16_t protocol, BT_HDR* p_buf, bool ext) { tPAN_CONN* pcb; uint16_t i; tBNEP_RESULT result; @@ -510,9 +506,9 @@ tPAN_RESULT PAN_WriteBuf(uint16_t handle, const RawAddress& dst, if (dst.address[0] & 0x01) { uint8_t* data = (uint8_t*)p_buf + sizeof(BT_HDR) + p_buf->offset; for (i = 0; i < MAX_PAN_CONNS; ++i) { - if (pan_cb.pcb[i].con_state == PAN_STATE_CONNECTED) - BNEP_Write(pan_cb.pcb[i].handle, dst, data, p_buf->len, protocol, src, - ext); + if (pan_cb.pcb[i].con_state == PAN_STATE_CONNECTED) { + BNEP_Write(pan_cb.pcb[i].handle, dst, data, p_buf->len, protocol, src, ext); + } } osi_free(p_buf); return PAN_SUCCESS; @@ -523,8 +519,9 @@ tPAN_RESULT PAN_WriteBuf(uint16_t handle, const RawAddress& dst, /* Data write is on PANU connection */ for (i = 0; i < MAX_PAN_CONNS; i++) { if (pan_cb.pcb[i].con_state == PAN_STATE_CONNECTED && - pan_cb.pcb[i].src_uuid == UUID_SERVCLASS_PANU) + pan_cb.pcb[i].src_uuid == UUID_SERVCLASS_PANU) { break; + } } if (i == MAX_PAN_CONNS) { @@ -533,8 +530,7 @@ tPAN_RESULT PAN_WriteBuf(uint16_t handle, const RawAddress& dst, return PAN_FAILURE; } - result = - BNEP_WriteBuf(pan_cb.pcb[i].handle, dst, p_buf, protocol, src, ext); + result = BNEP_WriteBuf(pan_cb.pcb[i].handle, dst, p_buf, protocol, src, ext); if (result == BNEP_IGNORE_CMD) { log::verbose("PAN ignored data write for PANU connection"); return (tPAN_RESULT)result; @@ -601,8 +597,7 @@ tPAN_RESULT PAN_WriteBuf(uint16_t handle, const RawAddress& dst, * PAN_FAILURE if connection not found or error in setting * ******************************************************************************/ -tPAN_RESULT PAN_SetProtocolFilters(uint16_t handle, uint16_t num_filters, - uint16_t* p_start_array, +tPAN_RESULT PAN_SetProtocolFilters(uint16_t handle, uint16_t num_filters, uint16_t* p_start_array, uint16_t* p_end_array) { tPAN_CONN* pcb; @@ -613,8 +608,8 @@ tPAN_RESULT PAN_SetProtocolFilters(uint16_t handle, uint16_t num_filters, return PAN_FAILURE; } - tBNEP_RESULT result = BNEP_SetProtocolFilters(pcb->handle, num_filters, - p_start_array, p_end_array); + tBNEP_RESULT result = + BNEP_SetProtocolFilters(pcb->handle, num_filters, p_start_array, p_end_array); if (result != BNEP_SUCCESS) { log::error("PAN failed to set protocol filters for handle {}", handle); return (tPAN_RESULT)result; @@ -641,8 +636,7 @@ tPAN_RESULT PAN_SetProtocolFilters(uint16_t handle, uint16_t num_filters, * ******************************************************************************/ tPAN_RESULT PAN_SetMulticastFilters(uint16_t handle, uint16_t num_mcast_filters, - uint8_t* p_start_array, - uint8_t* p_end_array) { + uint8_t* p_start_array, uint8_t* p_end_array) { tPAN_CONN* pcb; /* Check if the connection exists */ @@ -652,8 +646,8 @@ tPAN_RESULT PAN_SetMulticastFilters(uint16_t handle, uint16_t num_mcast_filters, return PAN_FAILURE; } - tBNEP_RESULT result = BNEP_SetMulticastFilters(pcb->handle, num_mcast_filters, - p_start_array, p_end_array); + tBNEP_RESULT result = + BNEP_SetMulticastFilters(pcb->handle, num_mcast_filters, p_start_array, p_end_array); if (result != BNEP_SUCCESS) { log::error("PAN failed to set multicast filters for handle {}", handle); return (tPAN_RESULT)result; @@ -674,45 +668,43 @@ tPAN_RESULT PAN_SetMulticastFilters(uint16_t handle, uint16_t num_mcast_filters, * Returns none * ******************************************************************************/ -void PAN_Init(void) { - memset(&pan_cb, 0, sizeof(tPAN_CB)); -} +void PAN_Init(void) { memset(&pan_cb, 0, sizeof(tPAN_CB)); } #define DUMPSYS_TAG "shim::legacy::pan" void PAN_Dumpsys(int fd) { LOG_DUMPSYS_TITLE(fd, DUMPSYS_TAG); - LOG_DUMPSYS(fd, "Connections:%hhu roles configured:%s current:%s previous:%s", - pan_cb.num_conns, pan_role_to_text(pan_cb.role).c_str(), - pan_role_to_text(pan_cb.active_role).c_str(), + LOG_DUMPSYS(fd, "Connections:%hhu roles configured:%s current:%s previous:%s", pan_cb.num_conns, + pan_role_to_text(pan_cb.role).c_str(), pan_role_to_text(pan_cb.active_role).c_str(), pan_role_to_text(pan_cb.prv_active_role).c_str()); - if (!user_service_name.empty()) + if (!user_service_name.empty()) { LOG_DUMPSYS(fd, "service_name_user:\"%s\"", user_service_name.c_str()); - if (!gn_service_name.empty()) + } + if (!gn_service_name.empty()) { LOG_DUMPSYS(fd, "service_name_gn:\"%s\"", gn_service_name.c_str()); - if (!nap_service_name.empty()) + } + if (!nap_service_name.empty()) { LOG_DUMPSYS(fd, "service_name_nap:\"%s\"", nap_service_name.c_str()); + } const tPAN_CONN* pcb = &pan_cb.pcb[0]; for (int i = 0; i < MAX_PAN_CONNS; i++, pcb++) { - if (pcb->con_state == PAN_STATE_IDLE) continue; + if (pcb->con_state == PAN_STATE_IDLE) { + continue; + } LOG_DUMPSYS(fd, " Id:%d peer:%s", i, ADDRESS_TO_LOGGABLE_CSTR(pcb->rem_bda)); - LOG_DUMPSYS( - fd, - " rx_packets:%-5lu rx_octets:%-8lu rx_errors:%-5lu rx_drops:%-5lu", - (unsigned long)pcb->read.packets, (unsigned long)pcb->read.octets, - (unsigned long)pcb->read.errors, (unsigned long)pcb->read.drops); - LOG_DUMPSYS( - fd, - " tx_packets:%-5lu tx_octets:%-8lu tx_errors:%-5lu tx_drops:%-5lu", - (unsigned long)pcb->write.packets, (unsigned long)pcb->write.octets, - (unsigned long)pcb->write.errors, (unsigned long)pcb->write.drops); + LOG_DUMPSYS(fd, " rx_packets:%-5lu rx_octets:%-8lu rx_errors:%-5lu rx_drops:%-5lu", + (unsigned long)pcb->read.packets, (unsigned long)pcb->read.octets, + (unsigned long)pcb->read.errors, (unsigned long)pcb->read.drops); + LOG_DUMPSYS(fd, " tx_packets:%-5lu tx_octets:%-8lu tx_errors:%-5lu tx_drops:%-5lu", + (unsigned long)pcb->write.packets, (unsigned long)pcb->write.octets, + (unsigned long)pcb->write.errors, (unsigned long)pcb->write.drops); LOG_DUMPSYS(fd, " src_uuid:0x%04x[prev:0x%04x] dst_uuid:0x%04x[prev:0x%04x] " "bad_pkts:%hu", - pcb->src_uuid, pcb->dst_uuid, pcb->prv_src_uuid, - pcb->prv_dst_uuid, pcb->bad_pkts_rcvd); + pcb->src_uuid, pcb->dst_uuid, pcb->prv_src_uuid, pcb->prv_dst_uuid, + pcb->bad_pkts_rcvd); } } #undef DUMPSYS_TAG diff --git a/system/stack/pan/pan_int.h b/system/stack/pan/pan_int.h index b73eae77c63..6a65cdf5ad8 100644 --- a/system/stack/pan/pan_int.h +++ b/system/stack/pan/pan_int.h @@ -89,10 +89,8 @@ typedef struct { tPAN_BRIDGE_REQ_CB* pan_bridge_req_cb; tPAN_DATA_IND_CB* pan_data_ind_cb; tPAN_DATA_BUF_IND_CB* pan_data_buf_ind_cb; - tPAN_FILTER_IND_CB* - pan_pfilt_ind_cb; /* protocol filter indication callback */ - tPAN_MFILTER_IND_CB* - pan_mfilt_ind_cb; /* multicast filter indication callback */ + tPAN_FILTER_IND_CB* pan_pfilt_ind_cb; /* protocol filter indication callback */ + tPAN_MFILTER_IND_CB* pan_mfilt_ind_cb; /* multicast filter indication callback */ tPAN_TX_DATA_FLOW_CB* pan_tx_data_flow_cb; char* user_service_name; @@ -110,23 +108,18 @@ extern tPAN_CB pan_cb; /******************************************************************************/ void pan_register_with_bnep(void); -void pan_conn_ind_cb(uint16_t handle, const RawAddress& p_bda, - const bluetooth::Uuid& remote_uuid, +void pan_conn_ind_cb(uint16_t handle, const RawAddress& p_bda, const bluetooth::Uuid& remote_uuid, const bluetooth::Uuid& local_uuid, bool is_role_change); -void pan_connect_state_cb(uint16_t handle, const RawAddress& rem_bda, - tBNEP_RESULT result, bool is_role_change); -void pan_data_buf_ind_cb(uint16_t handle, const RawAddress& src, - const RawAddress& dst, uint16_t protocol, - BT_HDR* p_buf, bool ext); +void pan_connect_state_cb(uint16_t handle, const RawAddress& rem_bda, tBNEP_RESULT result, + bool is_role_change); +void pan_data_buf_ind_cb(uint16_t handle, const RawAddress& src, const RawAddress& dst, + uint16_t protocol, BT_HDR* p_buf, bool ext); void pan_tx_data_flow_cb(uint16_t handle, tBNEP_RESULT event); -void pan_proto_filt_ind_cb(uint16_t handle, bool indication, - tBNEP_RESULT result, uint16_t num_filters, - uint8_t* p_filters); -void pan_mcast_filt_ind_cb(uint16_t handle, bool indication, - tBNEP_RESULT result, uint16_t num_filters, - uint8_t* p_filters); -uint32_t pan_register_with_sdp(uint16_t uuid, const char* p_name, - const char* p_desc); +void pan_proto_filt_ind_cb(uint16_t handle, bool indication, tBNEP_RESULT result, + uint16_t num_filters, uint8_t* p_filters); +void pan_mcast_filt_ind_cb(uint16_t handle, bool indication, tBNEP_RESULT result, + uint16_t num_filters, uint8_t* p_filters); +uint32_t pan_register_with_sdp(uint16_t uuid, const char* p_name, const char* p_desc); tPAN_CONN* pan_allocate_pcb(const RawAddress& p_bda, uint16_t handle); tPAN_CONN* pan_get_pcb_by_handle(uint16_t handle); tPAN_CONN* pan_get_pcb_by_addr(const RawAddress& p_bda); diff --git a/system/stack/pan/pan_main.cc b/system/stack/pan/pan_main.cc index f9f855a8fbf..88b433ed81d 100644 --- a/system/stack/pan/pan_main.cc +++ b/system/stack/pan/pan_main.cc @@ -92,9 +92,8 @@ void pan_register_with_bnep(void) { * Returns none * ******************************************************************************/ -void pan_conn_ind_cb(uint16_t handle, const RawAddress& p_bda, - const Uuid& remote_uuid, const Uuid& local_uuid, - bool is_role_change) { +void pan_conn_ind_cb(uint16_t handle, const RawAddress& p_bda, const Uuid& remote_uuid, + const Uuid& local_uuid, bool is_role_change) { /* If we are in GN or NAP role and have one or more active connections and the * received connection is for user role reject it. If we are in user role with * one connection active reject the connection. Allocate PCB and store the @@ -116,15 +115,11 @@ void pan_conn_ind_cb(uint16_t handle, const RawAddress& p_bda, uint16_t remote_uuid16 = remote_uuid.As16Bit(); uint16_t local_uuid16 = local_uuid.As16Bit(); - log::verbose( - "handle {}, current role {}, dst uuid 0x{:x}, src uuid 0x{:x}, role " - "change {}", - handle, pan_cb.role, local_uuid16, remote_uuid16, - is_role_change ? "YES" : "NO"); + log::verbose("handle {}, current role {}, dst uuid 0x{:x}, src uuid 0x{:x}, role change {}", + handle, pan_cb.role, local_uuid16, remote_uuid16, is_role_change ? "YES" : "NO"); /* Check if the source UUID is a valid one */ - if (remote_uuid16 != UUID_SERVCLASS_PANU && - remote_uuid16 != UUID_SERVCLASS_NAP && + if (remote_uuid16 != UUID_SERVCLASS_PANU && remote_uuid16 != UUID_SERVCLASS_NAP && remote_uuid16 != UUID_SERVCLASS_GN) { log::error("Src UUID 0x{:x} is not valid", remote_uuid16); BNEP_ConnectResp(handle, BNEP_CONN_FAILED_SRC_UUID); @@ -132,23 +127,19 @@ void pan_conn_ind_cb(uint16_t handle, const RawAddress& p_bda, } /* Check if the destination UUID is a valid one */ - if (local_uuid16 != UUID_SERVCLASS_PANU && - local_uuid16 != UUID_SERVCLASS_NAP && local_uuid16 != UUID_SERVCLASS_GN) { + if (local_uuid16 != UUID_SERVCLASS_PANU && local_uuid16 != UUID_SERVCLASS_NAP && + local_uuid16 != UUID_SERVCLASS_GN) { log::error("Dst UUID 0x{:x} is not valid", local_uuid16); BNEP_ConnectResp(handle, BNEP_CONN_FAILED_DST_UUID); return; } /* Check if currently we support the destination role requested */ - if (((!(pan_cb.role & UUID_SERVCLASS_PANU)) && - local_uuid16 == UUID_SERVCLASS_PANU) || - ((!(pan_cb.role & UUID_SERVCLASS_GN)) && - local_uuid16 == UUID_SERVCLASS_GN) || - ((!(pan_cb.role & UUID_SERVCLASS_NAP)) && - local_uuid16 == UUID_SERVCLASS_NAP)) { - log::error( - "PAN Connection failed because of unsupported destination UUID 0x{:x}", - local_uuid16); + if (((!(pan_cb.role & UUID_SERVCLASS_PANU)) && local_uuid16 == UUID_SERVCLASS_PANU) || + ((!(pan_cb.role & UUID_SERVCLASS_GN)) && local_uuid16 == UUID_SERVCLASS_GN) || + ((!(pan_cb.role & UUID_SERVCLASS_NAP)) && local_uuid16 == UUID_SERVCLASS_NAP)) { + log::error("PAN Connection failed because of unsupported destination UUID 0x{:x}", + local_uuid16); BNEP_ConnectResp(handle, BNEP_CONN_FAILED_DST_UUID); return; } @@ -162,7 +153,9 @@ void pan_conn_ind_cb(uint16_t handle, const RawAddress& p_bda, switch (remote_uuid16) { case UUID_SERVCLASS_NAP: case UUID_SERVCLASS_GN: - if (local_uuid16 == UUID_SERVCLASS_PANU) is_valid_interaction = true; + if (local_uuid16 == UUID_SERVCLASS_PANU) { + is_valid_interaction = true; + } break; case UUID_SERVCLASS_PANU: is_valid_interaction = true; @@ -172,25 +165,25 @@ void pan_conn_ind_cb(uint16_t handle, const RawAddress& p_bda, * Explicitly disable connections to the local PANU if the remote is * not PANU. */ - if ((local_uuid16 == UUID_SERVCLASS_PANU) && - (remote_uuid16 != UUID_SERVCLASS_PANU)) { + if ((local_uuid16 == UUID_SERVCLASS_PANU) && (remote_uuid16 != UUID_SERVCLASS_PANU)) { is_valid_interaction = false; } if (!is_valid_interaction) { log::error( - "PAN Connection failed because of invalid PAN profile roles " - "interaction: Remote UUID 0x{:x} Local UUID 0x{:x}", - remote_uuid16, local_uuid16); + "PAN Connection failed because of invalid PAN profile roles " + "interaction: Remote UUID 0x{:x} Local UUID 0x{:x}", + remote_uuid16, local_uuid16); BNEP_ConnectResp(handle, BNEP_CONN_FAILED_SRC_UUID); return; } uint8_t req_role; /* Requested destination role is */ - if (local_uuid16 == UUID_SERVCLASS_PANU) + if (local_uuid16 == UUID_SERVCLASS_PANU) { req_role = PAN_ROLE_CLIENT; - else + } else { req_role = PAN_ROLE_NAP_SERVER; + } /* If the connection indication is for the existing connection ** Check if the new destination role is acceptable @@ -199,28 +192,25 @@ void pan_conn_ind_cb(uint16_t handle, const RawAddress& p_bda, if (pcb) { if (pan_cb.num_conns > 1 && local_uuid16 == UUID_SERVCLASS_PANU) { /* There are connections other than this one - ** so we cann't accept PANU role. Reject + ** so we can't accept PANU role. Reject */ - log::error( - "Dst UUID should be either GN or NAP only because there are other " - "connections"); + log::error("Dst UUID should be either GN or NAP only because there are other connections"); BNEP_ConnectResp(handle, BNEP_CONN_FAILED_DST_UUID); return; } /* If it is already in connected state check for bridging status */ if (pcb->con_state == PAN_STATE_CONNECTED) { - log::verbose("PAN Role changing New Src 0x{:x} Dst 0x{:x}", remote_uuid16, - local_uuid16); + log::verbose("PAN Role changing New Src 0x{:x} Dst 0x{:x}", remote_uuid16, local_uuid16); pcb->prv_src_uuid = pcb->src_uuid; pcb->prv_dst_uuid = pcb->dst_uuid; - if (pcb->src_uuid == UUID_SERVCLASS_NAP && - local_uuid16 != UUID_SERVCLASS_NAP) { + if (pcb->src_uuid == UUID_SERVCLASS_NAP && local_uuid16 != UUID_SERVCLASS_NAP) { /* Remove bridging */ - if (pan_cb.pan_bridge_req_cb) + if (pan_cb.pan_bridge_req_cb) { (*pan_cb.pan_bridge_req_cb)(pcb->rem_bda, false); + } } } /* Set the latest active PAN role */ @@ -234,8 +224,8 @@ void pan_conn_ind_cb(uint16_t handle, const RawAddress& p_bda, ** we already have a connection then reject the request. ** If we have a connection in PANU role then reject it */ - if (pan_cb.num_conns && (local_uuid16 == UUID_SERVCLASS_PANU || - pan_cb.active_role == PAN_ROLE_CLIENT)) { + if (pan_cb.num_conns && + (local_uuid16 == UUID_SERVCLASS_PANU || pan_cb.active_role == PAN_ROLE_CLIENT)) { log::error("PAN already have a connection and can't be user"); BNEP_ConnectResp(handle, BNEP_CONN_FAILED_DST_UUID); return; @@ -282,13 +272,12 @@ void pan_conn_ind_cb(uint16_t handle, const RawAddress& p_bda, * Returns none * ******************************************************************************/ -void pan_connect_state_cb(uint16_t handle, const RawAddress& /* rem_bda */, - tBNEP_RESULT result, bool is_role_change) { +void pan_connect_state_cb(uint16_t handle, const RawAddress& /* rem_bda */, tBNEP_RESULT result, + bool is_role_change) { tPAN_CONN* pcb; uint8_t peer_role; - log::verbose("pan_connect_state_cb - for handle {}, result {}", handle, - result); + log::verbose("pan_connect_state_cb - for handle {}, result {}", handle, result); pcb = pan_get_pcb_by_handle(handle); if (!pcb) { log::error("PAN State change indication for wrong handle {}", handle); @@ -298,14 +287,13 @@ void pan_connect_state_cb(uint16_t handle, const RawAddress& /* rem_bda */, /* If the connection is getting terminated remove bridging */ if (result != BNEP_SUCCESS) { /* Inform the application that connection is down */ - if (pan_cb.pan_conn_state_cb) - (*pan_cb.pan_conn_state_cb)(pcb->handle, pcb->rem_bda, - (tPAN_RESULT)result, is_role_change, + if (pan_cb.pan_conn_state_cb) { + (*pan_cb.pan_conn_state_cb)(pcb->handle, pcb->rem_bda, (tPAN_RESULT)result, is_role_change, PAN_ROLE_INACTIVE, PAN_ROLE_INACTIVE); + } /* Check if this failure is for role change only */ - if (pcb->con_state != PAN_STATE_CONNECTED && - (pcb->con_flags & PAN_FLAGS_CONN_COMPLETED)) { + if (pcb->con_state != PAN_STATE_CONNECTED && (pcb->con_flags & PAN_FLAGS_CONN_COMPLETED)) { /* restore the original values */ log::verbose("restoring the connection state to active"); pcb->con_state = PAN_STATE_CONNECTED; @@ -315,16 +303,18 @@ void pan_connect_state_cb(uint16_t handle, const RawAddress& /* rem_bda */, pcb->dst_uuid = pcb->prv_dst_uuid; pan_cb.active_role = pan_cb.prv_active_role; - if ((pcb->src_uuid == UUID_SERVCLASS_NAP) && pan_cb.pan_bridge_req_cb) + if ((pcb->src_uuid == UUID_SERVCLASS_NAP) && pan_cb.pan_bridge_req_cb) { (*pan_cb.pan_bridge_req_cb)(pcb->rem_bda, true); + } return; } if (pcb->con_state == PAN_STATE_CONNECTED) { /* If the connections destination role is NAP remove bridging */ - if ((pcb->src_uuid == UUID_SERVCLASS_NAP) && pan_cb.pan_bridge_req_cb) + if ((pcb->src_uuid == UUID_SERVCLASS_NAP) && pan_cb.pan_bridge_req_cb) { (*pan_cb.pan_bridge_req_cb)(pcb->rem_bda, false); + } } pan_cb.num_conns--; @@ -333,22 +323,25 @@ void pan_connect_state_cb(uint16_t handle, const RawAddress& /* rem_bda */, } /* Requested destination role is */ - if (pcb->src_uuid == UUID_SERVCLASS_PANU) + if (pcb->src_uuid == UUID_SERVCLASS_PANU) { pan_cb.active_role = PAN_ROLE_CLIENT; - else + } else { pan_cb.active_role = PAN_ROLE_NAP_SERVER; + } - if (pcb->dst_uuid == UUID_SERVCLASS_PANU) + if (pcb->dst_uuid == UUID_SERVCLASS_PANU) { peer_role = PAN_ROLE_CLIENT; - else + } else { peer_role = PAN_ROLE_NAP_SERVER; + } pcb->con_state = PAN_STATE_CONNECTED; /* Inform the application that connection is down */ - if (pan_cb.pan_conn_state_cb) - (*pan_cb.pan_conn_state_cb)(pcb->handle, pcb->rem_bda, PAN_SUCCESS, - is_role_change, pan_cb.active_role, peer_role); + if (pan_cb.pan_conn_state_cb) { + (*pan_cb.pan_conn_state_cb)(pcb->handle, pcb->rem_bda, PAN_SUCCESS, is_role_change, + pan_cb.active_role, peer_role); + } /* Create bridge if the destination role is NAP */ if (pan_cb.pan_bridge_req_cb && pcb->src_uuid == UUID_SERVCLASS_NAP) { @@ -377,9 +370,8 @@ void pan_connect_state_cb(uint16_t handle, const RawAddress& /* rem_bda */, * Returns none * ******************************************************************************/ -void pan_data_buf_ind_cb(uint16_t handle, const RawAddress& src, - const RawAddress& dst, uint16_t protocol, - BT_HDR* p_buf, bool ext) { +void pan_data_buf_ind_cb(uint16_t handle, const RawAddress& src, const RawAddress& dst, + uint16_t protocol, BT_HDR* p_buf, bool ext) { tPAN_CONN *pcb, *dst_pcb; tBNEP_RESULT result; uint16_t i, len; @@ -395,8 +387,7 @@ void pan_data_buf_ind_cb(uint16_t handle, const RawAddress& src, } if (pcb->con_state != PAN_STATE_CONNECTED) { - log::error("PAN Data indication in wrong state {} for handle {}", - pcb->con_state, handle); + log::error("PAN Data indication in wrong state {} for handle {}", pcb->con_state, handle); pcb->read.drops++; osi_free(p_buf); return; @@ -408,36 +399,32 @@ void pan_data_buf_ind_cb(uint16_t handle, const RawAddress& src, pcb->read.octets += len; pcb->read.packets++; - log::verbose( - "pan_data_buf_ind_cb - for handle {}, protocol 0x{:x}, length {}, ext {}", - handle, protocol, len, ext); + log::verbose("pan_data_buf_ind_cb - for handle {}, protocol 0x{:x}, length {}, ext {}", handle, + protocol, len, ext); - if (pcb->src_uuid == UUID_SERVCLASS_NAP) + if (pcb->src_uuid == UUID_SERVCLASS_NAP) { forward = true; - else + } else { forward = false; + } /* Check if it is broadcast or multicast packet */ if (pcb->src_uuid != UUID_SERVCLASS_PANU) { if (dst.address[0] & 0x01) { - log::verbose( - "PAN received broadcast packet on handle {}, src uuid 0x{:x}", handle, - pcb->src_uuid); + log::verbose("PAN received broadcast packet on handle {}, src uuid 0x{:x}", handle, + pcb->src_uuid); for (i = 0; i < MAX_PAN_CONNS; i++) { - if (pan_cb.pcb[i].con_state == PAN_STATE_CONNECTED && - pan_cb.pcb[i].handle != handle && + if (pan_cb.pcb[i].con_state == PAN_STATE_CONNECTED && pan_cb.pcb[i].handle != handle && pcb->src_uuid == pan_cb.pcb[i].src_uuid) { - BNEP_Write(pan_cb.pcb[i].handle, dst, p_data, len, protocol, src, - ext); + BNEP_Write(pan_cb.pcb[i].handle, dst, p_data, len, protocol, src, ext); } } - if (pan_cb.pan_data_buf_ind_cb) - (*pan_cb.pan_data_buf_ind_cb)(pcb->handle, src, dst, protocol, p_buf, - ext, forward); - else if (pan_cb.pan_data_ind_cb) - (*pan_cb.pan_data_ind_cb)(pcb->handle, src, dst, protocol, p_data, len, - ext, forward); + if (pan_cb.pan_data_buf_ind_cb) { + (*pan_cb.pan_data_buf_ind_cb)(pcb->handle, src, dst, protocol, p_buf, ext, forward); + } else if (pan_cb.pan_data_ind_cb) { + (*pan_cb.pan_data_ind_cb)(pcb->handle, src, dst, protocol, p_data, len, ext, forward); + } osi_free(p_buf); return; @@ -446,15 +433,13 @@ void pan_data_buf_ind_cb(uint16_t handle, const RawAddress& src, /* Check if it is for any other PAN connection */ dst_pcb = pan_get_pcb_by_addr(dst); if (dst_pcb) { - log::verbose( - "destination PANU found on handle {} and sending data, len: {}", - dst_pcb->handle, len); - - result = - BNEP_Write(dst_pcb->handle, dst, p_data, len, protocol, src, ext); - if (result != BNEP_SUCCESS && result != BNEP_IGNORE_CMD) - log::error("Failed to write data for PAN connection handle {}", - dst_pcb->handle); + log::verbose("destination PANU found on handle {} and sending data, len: {}", dst_pcb->handle, + len); + + result = BNEP_Write(dst_pcb->handle, dst, p_data, len, protocol, src, ext); + if (result != BNEP_SUCCESS && result != BNEP_IGNORE_CMD) { + log::error("Failed to write data for PAN connection handle {}", dst_pcb->handle); + } pcb->read.errors++; osi_free(p_buf); return; @@ -462,12 +447,11 @@ void pan_data_buf_ind_cb(uint16_t handle, const RawAddress& src, } /* Send it over the LAN or give it to host software */ - if (pan_cb.pan_data_buf_ind_cb) - (*pan_cb.pan_data_buf_ind_cb)(pcb->handle, src, dst, protocol, p_buf, ext, - forward); - else if (pan_cb.pan_data_ind_cb) - (*pan_cb.pan_data_ind_cb)(pcb->handle, src, dst, protocol, p_data, len, ext, - forward); + if (pan_cb.pan_data_buf_ind_cb) { + (*pan_cb.pan_data_buf_ind_cb)(pcb->handle, src, dst, protocol, p_buf, ext, forward); + } else if (pan_cb.pan_data_ind_cb) { + (*pan_cb.pan_data_ind_cb)(pcb->handle, src, dst, protocol, p_data, len, ext, forward); + } osi_free(p_buf); return; } @@ -486,8 +470,9 @@ void pan_data_buf_ind_cb(uint16_t handle, const RawAddress& src, * ******************************************************************************/ void pan_tx_data_flow_cb(uint16_t handle, tBNEP_RESULT result) { - if (pan_cb.pan_tx_data_flow_cb) + if (pan_cb.pan_tx_data_flow_cb) { (*pan_cb.pan_tx_data_flow_cb)(handle, (tPAN_RESULT)result); + } return; } @@ -513,17 +498,14 @@ void pan_tx_data_flow_cb(uint16_t handle, tBNEP_RESULT result) { * Returns none * ******************************************************************************/ -void pan_proto_filt_ind_cb(uint16_t handle, bool indication, - tBNEP_RESULT result, uint16_t num_filters, - uint8_t* p_filters) { - log::verbose( - "pan_proto_filt_ind_cb - called for handle {} with ind {}, result {}, " - "num {}", - handle, indication, result, num_filters); - - if (pan_cb.pan_pfilt_ind_cb) - (*pan_cb.pan_pfilt_ind_cb)(handle, indication, (tPAN_RESULT)result, - num_filters, p_filters); +void pan_proto_filt_ind_cb(uint16_t handle, bool indication, tBNEP_RESULT result, + uint16_t num_filters, uint8_t* p_filters) { + log::verbose("pan_proto_filt_ind_cb - called for handle {} with ind {}, result {}, num {}", + handle, indication, result, num_filters); + + if (pan_cb.pan_pfilt_ind_cb) { + (*pan_cb.pan_pfilt_ind_cb)(handle, indication, (tPAN_RESULT)result, num_filters, p_filters); + } } /******************************************************************************* @@ -547,15 +529,12 @@ void pan_proto_filt_ind_cb(uint16_t handle, bool indication, * Returns none * ******************************************************************************/ -void pan_mcast_filt_ind_cb(uint16_t handle, bool indication, - tBNEP_RESULT result, uint16_t num_filters, - uint8_t* p_filters) { - log::verbose( - "pan_mcast_filt_ind_cb - called for handle {} with ind {}, result {}, " - "num {}", - handle, indication, result, num_filters); - - if (pan_cb.pan_mfilt_ind_cb) - (*pan_cb.pan_mfilt_ind_cb)(handle, indication, (tPAN_RESULT)result, - num_filters, p_filters); +void pan_mcast_filt_ind_cb(uint16_t handle, bool indication, tBNEP_RESULT result, + uint16_t num_filters, uint8_t* p_filters) { + log::verbose("pan_mcast_filt_ind_cb - called for handle {} with ind {}, result {}, num {}", + handle, indication, result, num_filters); + + if (pan_cb.pan_mfilt_ind_cb) { + (*pan_cb.pan_mfilt_ind_cb)(handle, indication, (tPAN_RESULT)result, num_filters, p_filters); + } } diff --git a/system/stack/pan/pan_utils.cc b/system/stack/pan/pan_utils.cc index 100fc15bbf3..eda89c4bed7 100644 --- a/system/stack/pan/pan_utils.cc +++ b/system/stack/pan/pan_utils.cc @@ -42,19 +42,23 @@ using namespace bluetooth; using namespace bluetooth::legacy::stack::sdp; static const uint8_t pan_proto_elem_data[] = { - 0x35, 0x18, /* data element sequence of length 0x18 bytes */ - 0x35, 0x06, /* data element sequence for L2CAP descriptor */ - 0x19, 0x01, 0x00, /* UUID for L2CAP - 0x0100 */ - 0x09, 0x00, 0x0F, /* PSM for BNEP - 0x000F */ - 0x35, 0x0E, /* data element seqence for BNEP descriptor */ - 0x19, 0x00, 0x0F, /* UUID for BNEP - 0x000F */ - 0x09, 0x01, - 0x00, /* BNEP specific parameter 0 -- Version of BNEP = version 1 = 0x0001 - */ - 0x35, - 0x06, /* BNEP specific parameter 1 -- Supported network packet type list */ - 0x09, 0x08, 0x00, /* network packet type IPv4 = 0x0800 */ - 0x09, 0x08, 0x06 /* network packet type ARP = 0x0806 */ + 0x35, 0x18, /* data element sequence of length 0x18 bytes */ + 0x35, 0x06, /* data element sequence for L2CAP descriptor */ + 0x19, 0x01, + 0x00, /* UUID for L2CAP - 0x0100 */ + 0x09, 0x00, + 0x0F, /* PSM for BNEP - 0x000F */ + 0x35, 0x0E, /* data element seqence for BNEP descriptor */ + 0x19, 0x00, + 0x0F, /* UUID for BNEP - 0x000F */ + 0x09, 0x01, + 0x00, /* BNEP specific parameter 0 -- Version of BNEP = version 1 = 0x0001 + */ + 0x35, 0x06, /* BNEP specific parameter 1 -- Supported network packet type list */ + 0x09, 0x08, + 0x00, /* network packet type IPv4 = 0x0800 */ + 0x09, 0x08, + 0x06 /* network packet type ARP = 0x0806 */ }; /******************************************************************************* @@ -66,8 +70,7 @@ static const uint8_t pan_proto_elem_data[] = { * Returns * ******************************************************************************/ -uint32_t pan_register_with_sdp(uint16_t uuid, const char* p_name, - const char* p_desc) { +uint32_t pan_register_with_sdp(uint16_t uuid, const char* p_name, const char* p_desc) { uint32_t sdp_handle; uint16_t browse_list = UUID_SERVCLASS_PUBLIC_BROWSE_GROUP; uint16_t security = 0; @@ -82,44 +85,41 @@ uint32_t pan_register_with_sdp(uint16_t uuid, const char* p_name, } /* Service Class ID List */ - if (!get_legacy_stack_sdp_api()->handle.SDP_AddServiceClassIdList(sdp_handle, - 1, &uuid)) { + if (!get_legacy_stack_sdp_api()->handle.SDP_AddServiceClassIdList(sdp_handle, 1, &uuid)) { log::warn("Unable to add SDP class id list handle:{}", sdp_handle); } /* Add protocol element sequence from the constant string */ - if (!get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - sdp_handle, ATTR_ID_PROTOCOL_DESC_LIST, DATA_ELE_SEQ_DESC_TYPE, - proto_len, (uint8_t*)(pan_proto_elem_data + 2))) { + if (!get_legacy_stack_sdp_api()->handle.SDP_AddAttribute(sdp_handle, ATTR_ID_PROTOCOL_DESC_LIST, + DATA_ELE_SEQ_DESC_TYPE, proto_len, + (uint8_t*)(pan_proto_elem_data + 2))) { log::warn("Unable to add SDP PAN profile attribute handle:{}", sdp_handle); } /* Language base */ if (!get_legacy_stack_sdp_api()->handle.SDP_AddLanguageBaseAttrIDList( - sdp_handle, LANG_ID_CODE_ENGLISH, LANG_ID_CHAR_ENCODE_UTF8, - LANGUAGE_BASE_ID)) { + sdp_handle, LANG_ID_CODE_ENGLISH, LANG_ID_CHAR_ENCODE_UTF8, LANGUAGE_BASE_ID)) { log::warn("Unable to add SDP language base attribute"); } /* Profile descriptor list */ - if (!get_legacy_stack_sdp_api()->handle.SDP_AddProfileDescriptorList( - sdp_handle, uuid, PAN_PROFILE_VERSION)) { + if (!get_legacy_stack_sdp_api()->handle.SDP_AddProfileDescriptorList(sdp_handle, uuid, + PAN_PROFILE_VERSION)) { log::warn("Unable to add SDP PAN profile version"); } /* Service Name */ if (!get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - sdp_handle, ATTR_ID_SERVICE_NAME, TEXT_STR_DESC_TYPE, - (uint8_t)(strlen(p_name) + 1), (uint8_t*)p_name)) { + sdp_handle, ATTR_ID_SERVICE_NAME, TEXT_STR_DESC_TYPE, (uint8_t)(strlen(p_name) + 1), + (uint8_t*)p_name)) { log::warn("Unable to add SDP service name attribute handle:{}", sdp_handle); } /* Service description */ if (!get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - sdp_handle, ATTR_ID_SERVICE_DESCRIPTION, TEXT_STR_DESC_TYPE, - (uint8_t)(strlen(p_desc) + 1), (uint8_t*)p_desc)) { - log::warn("Unable to add SDP service description attribute handle:{}", - sdp_handle); + sdp_handle, ATTR_ID_SERVICE_DESCRIPTION, TEXT_STR_DESC_TYPE, + (uint8_t)(strlen(p_desc) + 1), (uint8_t*)p_desc)) { + log::warn("Unable to add SDP service description attribute handle:{}", sdp_handle); } /* Security description */ @@ -128,10 +128,8 @@ uint32_t pan_register_with_sdp(uint16_t uuid, const char* p_name, UINT16_TO_BE_FIELD(&security, 0x0001); } if (!get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - sdp_handle, ATTR_ID_SECURITY_DESCRIPTION, UINT_DESC_TYPE, 2, - (uint8_t*)&security)) { - log::warn("Unable to add SDP security description attribute handle:{}", - sdp_handle); + sdp_handle, ATTR_ID_SECURITY_DESCRIPTION, UINT_DESC_TYPE, 2, (uint8_t*)&security)) { + log::warn("Unable to add SDP security description attribute handle:{}", sdp_handle); } if (uuid == UUID_SERVCLASS_NAP) { @@ -142,28 +140,24 @@ uint32_t pan_register_with_sdp(uint16_t uuid, const char* p_name, /* Net access type. */ p = array; UINT16_TO_BE_STREAM(p, NetAccessType); - if (!get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - sdp_handle, ATTR_ID_NET_ACCESS_TYPE, UINT_DESC_TYPE, 2, array)) { - log::warn("Unable to add SDP attribute net access type handle:{}", - sdp_handle); + if (!get_legacy_stack_sdp_api()->handle.SDP_AddAttribute(sdp_handle, ATTR_ID_NET_ACCESS_TYPE, + UINT_DESC_TYPE, 2, array)) { + log::warn("Unable to add SDP attribute net access type handle:{}", sdp_handle); } /* Net access rate. */ p = array; UINT32_TO_BE_STREAM(p, NetAccessRate); if (!get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - sdp_handle, ATTR_ID_MAX_NET_ACCESS_RATE, UINT_DESC_TYPE, 4, - array)) { - log::warn("Unable to add SDP attribute net access rate handle:{}", - sdp_handle); + sdp_handle, ATTR_ID_MAX_NET_ACCESS_RATE, UINT_DESC_TYPE, 4, array)) { + log::warn("Unable to add SDP attribute net access rate handle:{}", sdp_handle); } } /* Make the service browsable */ - if (!get_legacy_stack_sdp_api()->handle.SDP_AddUuidSequence( - sdp_handle, ATTR_ID_BROWSE_GROUP_LIST, 1, &browse_list)) { - log::warn("Unable to add SDP uuid sequence browse group list handle:{}", - sdp_handle); + if (!get_legacy_stack_sdp_api()->handle.SDP_AddUuidSequence(sdp_handle, ATTR_ID_BROWSE_GROUP_LIST, + 1, &browse_list)) { + log::warn("Unable to add SDP uuid sequence browse group list handle:{}", sdp_handle); } return sdp_handle; @@ -182,15 +176,15 @@ tPAN_CONN* pan_allocate_pcb(const RawAddress& p_bda, uint16_t handle) { uint16_t i; for (i = 0; i < MAX_PAN_CONNS; i++) { - if (pan_cb.pcb[i].con_state != PAN_STATE_IDLE && - pan_cb.pcb[i].handle == handle) + if (pan_cb.pcb[i].con_state != PAN_STATE_IDLE && pan_cb.pcb[i].handle == handle) { return NULL; + } } for (i = 0; i < MAX_PAN_CONNS; i++) { - if (pan_cb.pcb[i].con_state != PAN_STATE_IDLE && - pan_cb.pcb[i].rem_bda == p_bda) + if (pan_cb.pcb[i].con_state != PAN_STATE_IDLE && pan_cb.pcb[i].rem_bda == p_bda) { return NULL; + } } for (i = 0; i < MAX_PAN_CONNS; i++) { @@ -217,9 +211,9 @@ tPAN_CONN* pan_get_pcb_by_handle(uint16_t handle) { uint16_t i; for (i = 0; i < MAX_PAN_CONNS; i++) { - if (pan_cb.pcb[i].con_state != PAN_STATE_IDLE && - pan_cb.pcb[i].handle == handle) + if (pan_cb.pcb[i].con_state != PAN_STATE_IDLE && pan_cb.pcb[i].handle == handle) { return &(pan_cb.pcb[i]); + } } return NULL; @@ -238,9 +232,13 @@ tPAN_CONN* pan_get_pcb_by_addr(const RawAddress& p_bda) { uint16_t i; for (i = 0; i < MAX_PAN_CONNS; i++) { - if (pan_cb.pcb[i].con_state == PAN_STATE_IDLE) continue; + if (pan_cb.pcb[i].con_state == PAN_STATE_IDLE) { + continue; + } - if (pan_cb.pcb[i].rem_bda == p_bda) return &(pan_cb.pcb[i]); + if (pan_cb.pcb[i].rem_bda == p_bda) { + return &(pan_cb.pcb[i]); + } /* if (pan_cb.pcb[i].mfilter_present && @@ -306,12 +304,12 @@ void pan_dump_status(void) { uint16_t i; tPAN_CONN* p_pcb; - log::verbose("PAN role {:x}, active role {}, num_conns {}", pan_cb.role, - pan_cb.active_role, pan_cb.num_conns); + log::verbose("PAN role {:x}, active role {}, num_conns {}", pan_cb.role, pan_cb.active_role, + pan_cb.num_conns); for (i = 0, p_pcb = pan_cb.pcb; i < MAX_PAN_CONNS; i++, p_pcb++) { - log::verbose("{} state:{}, handle:{}, src{}, BD:{}", i, p_pcb->con_state, - p_pcb->handle, p_pcb->src_uuid, p_pcb->rem_bda); + log::verbose("{} state:{}, handle:{}, src{}, BD:{}", i, p_pcb->con_state, p_pcb->handle, + p_pcb->src_uuid, p_pcb->rem_bda); } #endif } diff --git a/system/stack/rfcomm/port_api.cc b/system/stack/rfcomm/port_api.cc index aa36f155535..6937421175c 100644 --- a/system/stack/rfcomm/port_api.cc +++ b/system/stack/rfcomm/port_api.cc @@ -108,20 +108,16 @@ const char kBtmLogTag[] = "RFCOMM"; * (scn * 2 + 1) dlci. * ******************************************************************************/ -int RFCOMM_CreateConnectionWithSecurity(uint16_t uuid, uint8_t scn, - bool is_server, uint16_t mtu, - const RawAddress& bd_addr, - uint16_t* p_handle, - tPORT_MGMT_CALLBACK* p_mgmt_callback, - uint16_t sec_mask) { +int RFCOMM_CreateConnectionWithSecurity(uint16_t uuid, uint8_t scn, bool is_server, uint16_t mtu, + const RawAddress& bd_addr, uint16_t* p_handle, + tPORT_MGMT_CALLBACK* p_mgmt_callback, uint16_t sec_mask) { *p_handle = 0; if ((scn == 0) || (scn > RFCOMM_MAX_SCN)) { // Server Channel Number (SCN) should be in range [1, 30] - log::error( - "Invalid SCN, bd_addr={}, scn={}, is_server={}, mtu={}, uuid=0x{:x}", - bd_addr, static_cast(scn), is_server, static_cast(mtu), uuid); - return (PORT_INVALID_SCN); + log::error("Invalid SCN, bd_addr={}, scn={}, is_server={}, mtu={}, uuid=0x{:x}", bd_addr, + static_cast(scn), is_server, static_cast(mtu), uuid); + return PORT_INVALID_SCN; } // For client that originates connection on the existing none initiator @@ -143,15 +139,13 @@ int RFCOMM_CreateConnectionWithSecurity(uint16_t uuid, uint8_t scn, // if existing port is also a client port, error out if (!p_port->is_server) { log::error( - "already at opened state {}, RFC_state={}, MCB_state={}, " - "bd_addr={}, scn={}, is_server={}, mtu={}, uuid=0x{:x}, dlci={}, " - "p_mcb={}, port={}", - static_cast(p_port->state), - static_cast(p_port->rfc.state), - p_port->rfc.p_mcb ? p_port->rfc.p_mcb->state : 0, bd_addr, scn, - is_server, mtu, uuid, dlci, fmt::ptr(p_mcb), p_port->handle); + "already at opened state {}, RFC_state={}, MCB_state={}, " + "bd_addr={}, scn={}, is_server={}, mtu={}, uuid=0x{:x}, dlci={}, p_mcb={}, port={}", + static_cast(p_port->state), static_cast(p_port->rfc.state), + p_port->rfc.p_mcb ? p_port->rfc.p_mcb->state : 0, bd_addr, scn, is_server, mtu, + uuid, dlci, fmt::ptr(p_mcb), p_port->handle); *p_handle = p_port->handle; - return (PORT_ALREADY_OPENED); + return PORT_ALREADY_OPENED; } } } @@ -159,10 +153,8 @@ int RFCOMM_CreateConnectionWithSecurity(uint16_t uuid, uint8_t scn, // On the server side, always allocate a new port. p_port = port_allocate_port(dlci, bd_addr); if (p_port == nullptr) { - log::error( - "no resources, bd_addr={}, scn={}, is_server={}, mtu={}, uuid=0x{:x}, " - "dlci={}", - bd_addr, scn, is_server, mtu, uuid, dlci); + log::error("no resources, bd_addr={}, scn={}, is_server={}, mtu={}, uuid=0x{:x}, dlci={}", + bd_addr, scn, is_server, mtu, uuid, dlci); return PORT_NO_RESOURCES; } p_port->sec_mask = sec_mask; @@ -184,8 +176,7 @@ int RFCOMM_CreateConnectionWithSecurity(uint16_t uuid, uint8_t scn, p_port->default_signal_state = PORT_DUN_DEFAULT_SIGNAL_STATE; break; default: - p_port->default_signal_state = - (PORT_DTRDSR_ON | PORT_CTSRTS_ON | PORT_DCD_ON); + p_port->default_signal_state = (PORT_DTRDSR_ON | PORT_CTSRTS_ON | PORT_DCD_ON); break; } @@ -221,22 +212,21 @@ int RFCOMM_CreateConnectionWithSecurity(uint16_t uuid, uint8_t scn, p_port->bd_addr = bd_addr; log::info( - "bd_addr={}, scn={}, is_server={}, mtu={}, uuid=0x{:x}, dlci={}, " - "signal_state=0x{:x}, p_port={}", - bd_addr, scn, is_server, mtu, uuid, dlci, p_port->default_signal_state, - fmt::ptr(p_port)); + "bd_addr={}, scn={}, is_server={}, mtu={}, uuid=0x{:x}, dlci={}, " + "signal_state=0x{:x}, p_port={}", + bd_addr, scn, is_server, mtu, uuid, dlci, p_port->default_signal_state, fmt::ptr(p_port)); // If this is not initiator of the connection need to just wait if (p_port->is_server) { - BTM_LogHistory(kBtmLogTag, bd_addr, "Server started", - base::StringPrintf("handle:%hu scn:%hhu dlci:%hhu mtu:%hu", - *p_handle, scn, dlci, mtu)); - return (PORT_SUCCESS); + BTM_LogHistory( + kBtmLogTag, bd_addr, "Server started", + base::StringPrintf("handle:%hu scn:%hhu dlci:%hhu mtu:%hu", *p_handle, scn, dlci, mtu)); + return PORT_SUCCESS; } - BTM_LogHistory(kBtmLogTag, bd_addr, "Connection opened", - base::StringPrintf("handle:%hu scn:%hhu dlci:%hhu mtu:%hu", - *p_handle, scn, dlci, mtu)); + BTM_LogHistory( + kBtmLogTag, bd_addr, "Connection opened", + base::StringPrintf("handle:%hu scn:%hhu dlci:%hhu mtu:%hu", *p_handle, scn, dlci, mtu)); // Open will be continued after security checks are passed return port_open_continue(p_port); @@ -262,9 +252,8 @@ int RFCOMM_CreateConnectionWithSecurity(uint16_t uuid, uint8_t scn, * frames * ******************************************************************************/ -int RFCOMM_ControlReqFromBTSOCK(uint8_t dlci, const RawAddress& bd_addr, - uint8_t modem_signal, uint8_t break_signal, - uint8_t discard_buffers, +int RFCOMM_ControlReqFromBTSOCK(uint8_t dlci, const RawAddress& bd_addr, uint8_t modem_signal, + uint8_t break_signal, uint8_t discard_buffers, uint8_t break_signal_seq, bool fc) { tRFC_MCB* p_mcb = port_find_mcb(bd_addr); if (!p_mcb) { @@ -306,27 +295,26 @@ int RFCOMM_RemoveConnection(uint16_t handle) { tPORT* p_port = get_port_from_handle(handle); if (p_port == nullptr) { log::error("Unable to get RFCOMM port control block bad handle:{}", handle); - return (PORT_BAD_HANDLE); + return PORT_BAD_HANDLE; } if (!p_port->in_use || (p_port->state == PORT_CONNECTION_STATE_CLOSED)) { log::verbose("RFCOMM_RemoveConnection() Not opened:{}", handle); - return (PORT_SUCCESS); + return PORT_SUCCESS; } const RawAddress bd_addr = - (p_port->rfc.p_mcb) ? (p_port->rfc.p_mcb->bd_addr) : (RawAddress::kEmpty); + (p_port->rfc.p_mcb) ? (p_port->rfc.p_mcb->bd_addr) : (RawAddress::kEmpty); BTM_LogHistory( - kBtmLogTag, bd_addr, "Connection closed", - base::StringPrintf("handle:%hu scn:%hhu dlci:%hhu is_server:%s", handle, - p_port->scn, p_port->dlci, - p_port->is_server ? "true" : "false")); + kBtmLogTag, bd_addr, "Connection closed", + base::StringPrintf("handle:%hu scn:%hhu dlci:%hhu is_server:%s", handle, p_port->scn, + p_port->dlci, p_port->is_server ? "true" : "false")); p_port->state = PORT_CONNECTION_STATE_CLOSING; port_start_close(p_port); - return (PORT_SUCCESS); + return PORT_SUCCESS; } /******************************************************************************* @@ -342,7 +330,7 @@ int RFCOMM_RemoveServer(uint16_t handle) { tPORT* p_port = get_port_from_handle(handle); if (p_port == nullptr) { log::error("Unable to get RFCOMM port control block bad handle:{}", handle); - return (PORT_BAD_HANDLE); + return PORT_BAD_HANDLE; } /* Do not report any events to the client any more. */ @@ -350,17 +338,16 @@ int RFCOMM_RemoveServer(uint16_t handle) { if (!p_port->in_use || (p_port->state == PORT_CONNECTION_STATE_CLOSED)) { log::debug("handle {} not opened", handle); - return (PORT_SUCCESS); + return PORT_SUCCESS; } log::info("handle={}", handle); const RawAddress bd_addr = - (p_port->rfc.p_mcb) ? (p_port->rfc.p_mcb->bd_addr) : (RawAddress::kEmpty); + (p_port->rfc.p_mcb) ? (p_port->rfc.p_mcb->bd_addr) : (RawAddress::kEmpty); BTM_LogHistory( - kBtmLogTag, bd_addr, "Server stopped", - base::StringPrintf("handle:%hu scn:%hhu dlci:%hhu is_server:%s", handle, - p_port->scn, p_port->dlci, - p_port->is_server ? "true" : "false")); + kBtmLogTag, bd_addr, "Server stopped", + base::StringPrintf("handle:%hu scn:%hhu dlci:%hhu is_server:%s", handle, p_port->scn, + p_port->dlci, p_port->is_server ? "true" : "false")); /* this port will be deallocated after closing */ p_port->keep_port_handle = false; @@ -368,26 +355,25 @@ int RFCOMM_RemoveServer(uint16_t handle) { port_start_close(p_port); - return (PORT_SUCCESS); + return PORT_SUCCESS; } -int PORT_SetEventMaskAndCallback(uint16_t handle, uint32_t mask, - tPORT_CALLBACK* p_port_cb) { +int PORT_SetEventMaskAndCallback(uint16_t handle, uint32_t mask, tPORT_CALLBACK* p_port_cb) { log::verbose("PORT_SetEventMask() handle:{} mask:0x{:x}", handle, mask); tPORT* p_port = get_port_from_handle(handle); if (p_port == nullptr) { log::error("Unable to get RFCOMM port control block bad handle:{}", handle); - return (PORT_BAD_HANDLE); + return PORT_BAD_HANDLE; } if (!p_port->in_use || (p_port->state == PORT_CONNECTION_STATE_CLOSED)) { - return (PORT_NOT_OPENED); + return PORT_NOT_OPENED; } p_port->ev_mask = mask; p_port->p_callback = p_port_cb; - return (PORT_SUCCESS); + return PORT_SUCCESS; } /******************************************************************************* @@ -404,10 +390,10 @@ int PORT_ClearKeepHandleFlag(uint16_t handle) { tPORT* p_port = get_port_from_handle(handle); if (p_port == nullptr) { log::error("Unable to get RFCOMM port control block bad handle:{}", handle); - return (PORT_BAD_HANDLE); + return PORT_BAD_HANDLE; } p_port->keep_port_handle = 0; - return (PORT_SUCCESS); + return PORT_SUCCESS; } /******************************************************************************* @@ -424,21 +410,20 @@ int PORT_ClearKeepHandleFlag(uint16_t handle) { * ******************************************************************************/ int PORT_SetDataCOCallback(uint16_t handle, tPORT_DATA_CO_CALLBACK* p_port_cb) { - log::verbose("PORT_SetDataCOCallback() handle:{} cb 0x{}", handle, - fmt::ptr(p_port_cb)); + log::verbose("PORT_SetDataCOCallback() handle:{} cb 0x{}", handle, fmt::ptr(p_port_cb)); tPORT* p_port = get_port_from_handle(handle); if (p_port == nullptr) { log::error("Unable to get RFCOMM port control block bad handle:{}", handle); - return (PORT_BAD_HANDLE); + return PORT_BAD_HANDLE; } if (!p_port->in_use || (p_port->state == PORT_CONNECTION_STATE_CLOSED)) { - return (PORT_NOT_OPENED); + return PORT_NOT_OPENED; } p_port->p_data_co_callback = p_port_cb; - return (PORT_SUCCESS); + return PORT_SUCCESS; } /******************************************************************************* @@ -453,33 +438,31 @@ int PORT_SetDataCOCallback(uint16_t handle, tPORT_DATA_CO_CALLBACK* p_port_cb) { * p_lcid - OUT L2CAP's LCID * ******************************************************************************/ -int PORT_CheckConnection(uint16_t handle, RawAddress* bd_addr, - uint16_t* p_lcid) { +int PORT_CheckConnection(uint16_t handle, RawAddress* bd_addr, uint16_t* p_lcid) { tPORT* p_port = get_port_from_handle(handle); if (p_port == nullptr) { log::error("Unable to get RFCOMM port control block bad handle:{}", handle); - return (PORT_BAD_HANDLE); + return PORT_BAD_HANDLE; } - log::verbose( - "handle={}, in_use={}, port_state={}, p_mcb={}, peer_ready={}, " - "rfc_state={}", - handle, p_port->in_use, p_port->state, fmt::ptr(p_port->rfc.p_mcb), - p_port->rfc.p_mcb ? p_port->rfc.p_mcb->peer_ready : -1, - p_port->rfc.state); + log::verbose("handle={}, in_use={}, port_state={}, p_mcb={}, peer_ready={}, rfc_state={}", handle, + p_port->in_use, p_port->state, fmt::ptr(p_port->rfc.p_mcb), + p_port->rfc.p_mcb ? p_port->rfc.p_mcb->peer_ready : -1, p_port->rfc.state); if (!p_port->in_use || (p_port->state == PORT_CONNECTION_STATE_CLOSED)) { - return (PORT_NOT_OPENED); + return PORT_NOT_OPENED; } if (!p_port->rfc.p_mcb || !p_port->rfc.p_mcb->peer_ready || (p_port->rfc.state != RFC_STATE_OPENED)) { - return (PORT_LINE_ERR); + return PORT_LINE_ERR; } *bd_addr = p_port->rfc.p_mcb->bd_addr; - if (p_lcid) *p_lcid = p_port->rfc.p_mcb->lcid; + if (p_lcid) { + *p_lcid = p_port->rfc.p_mcb->lcid; + } - return (PORT_SUCCESS); + return PORT_SUCCESS; } /******************************************************************************* @@ -510,22 +493,18 @@ bool PORT_IsOpening(RawAddress* bd_addr) { if ((multiplexer_cb.state > RFC_MX_STATE_IDLE) && (multiplexer_cb.state < RFC_MX_STATE_CONNECTED)) { *bd_addr = multiplexer_cb.bd_addr; - log::info( - "Found a rfc_mcb in the middle of opening a port, returning true"); + log::info("Found a rfc_mcb in the middle of opening a port, returning true"); return true; } if (multiplexer_cb.state == RFC_MX_STATE_CONNECTED) { const tPORT* p_port = get_port_from_mcb(&multiplexer_cb); log::info("RFC_MX_STATE_CONNECTED, found_port={}, tRFC_PORT_STATE={}", - (p_port != nullptr) ? "T" : "F", - (p_port != nullptr) ? p_port->rfc.state : 0); + (p_port != nullptr) ? "T" : "F", (p_port != nullptr) ? p_port->rfc.state : 0); if ((p_port == nullptr) || (p_port->rfc.state < RFC_STATE_OPENED)) { /* Port is not established yet. */ *bd_addr = multiplexer_cb.bd_addr; - log::info( - "In RFC_MX_STATE_CONNECTED but port is not established yet, " - "returning true"); + log::info("In RFC_MX_STATE_CONNECTED but port is not established yet, returning true"); return true; } } @@ -554,19 +533,18 @@ int PORT_SetState(uint16_t handle, tPORT_STATE* p_settings) { tPORT* p_port = get_port_from_handle(handle); if (p_port == nullptr) { log::error("Unable to get RFCOMM port control block bad handle:{}", handle); - return (PORT_BAD_HANDLE); + return PORT_BAD_HANDLE; } if (!p_port->in_use || (p_port->state == PORT_CONNECTION_STATE_CLOSED)) { - return (PORT_NOT_OPENED); + return PORT_NOT_OPENED; } if (p_port->line_status) { - return (PORT_LINE_ERR); + return PORT_LINE_ERR; } - log::verbose("PORT_SetState() handle:{} FC_TYPE:0x{:x}", handle, - p_settings->fc_type); + log::verbose("PORT_SetState() handle:{} FC_TYPE:0x{:x}", handle, p_settings->fc_type); baud_rate = p_port->user_port_pars.baud_rate; p_port->user_port_pars = *p_settings; @@ -575,7 +553,7 @@ int PORT_SetState(uint16_t handle, tPORT_STATE* p_settings) { if (baud_rate != p_settings->baud_rate) { port_start_par_neg(p_port); } - return (PORT_SUCCESS); + return PORT_SUCCESS; } /******************************************************************************* @@ -596,19 +574,19 @@ int PORT_GetState(uint16_t handle, tPORT_STATE* p_settings) { tPORT* p_port = get_port_from_handle(handle); if (p_port == nullptr) { log::error("Unable to get RFCOMM port control block bad handle:{}", handle); - return (PORT_BAD_HANDLE); + return PORT_BAD_HANDLE; } if (!p_port->in_use || (p_port->state == PORT_CONNECTION_STATE_CLOSED)) { - return (PORT_NOT_OPENED); + return PORT_NOT_OPENED; } if (p_port->line_status) { - return (PORT_LINE_ERR); + return PORT_LINE_ERR; } *p_settings = p_port->user_port_pars; - return (PORT_SUCCESS); + return PORT_SUCCESS; } /******************************************************************************* @@ -634,15 +612,15 @@ int PORT_FlowControl_MaxCredit(uint16_t handle, bool enable) { tPORT* p_port = get_port_from_handle(handle); if (p_port == nullptr) { log::error("Unable to get RFCOMM port control block bad handle:{}", handle); - return (PORT_BAD_HANDLE); + return PORT_BAD_HANDLE; } if (!p_port->in_use || (p_port->state == PORT_CONNECTION_STATE_CLOSED)) { - return (PORT_NOT_OPENED); + return PORT_NOT_OPENED; } if (!p_port->rfc.p_mcb) { - return (PORT_NOT_OPENED); + return PORT_NOT_OPENED; } p_port->rx.user_fc = !enable; @@ -657,7 +635,9 @@ int PORT_FlowControl_MaxCredit(uint16_t handle, bool enable) { /* FC is set if user is set or peer is set */ p_port->local_ctrl.fc = (p_port->rx.user_fc | p_port->rx.peer_fc); - if (p_port->local_ctrl.fc != old_fc) port_start_control(p_port); + if (p_port->local_ctrl.fc != old_fc) { + port_start_control(p_port); + } } /* Need to take care of the case when we could not deliver events */ @@ -674,7 +654,7 @@ int PORT_FlowControl_MaxCredit(uint16_t handle, bool enable) { p_port->p_callback(events, p_port->handle); } } - return (PORT_SUCCESS); + return PORT_SUCCESS; } /******************************************************************************* @@ -690,8 +670,7 @@ int PORT_FlowControl_MaxCredit(uint16_t handle, bool enable) { * p_len - Byte count received * ******************************************************************************/ -int PORT_ReadData(uint16_t handle, char* p_data, uint16_t max_len, - uint16_t* p_len) { +int PORT_ReadData(uint16_t handle, char* p_data, uint16_t max_len, uint16_t* p_len) { BT_HDR* p_buf; uint16_t count; @@ -703,11 +682,11 @@ int PORT_ReadData(uint16_t handle, char* p_data, uint16_t max_len, tPORT* p_port = get_port_from_handle(handle); if (p_port == nullptr) { log::error("Unable to get RFCOMM port control block bad handle:{}", handle); - return (PORT_BAD_HANDLE); + return PORT_BAD_HANDLE; } if (!p_port->in_use || (p_port->state == PORT_CONNECTION_STATE_CLOSED)) { - return (PORT_NOT_OPENED); + return PORT_NOT_OPENED; } if (p_port->state == PORT_CONNECTION_STATE_OPENING) { @@ -715,19 +694,21 @@ int PORT_ReadData(uint16_t handle, char* p_data, uint16_t max_len, } if (p_port->line_status) { - return (PORT_LINE_ERR); + return PORT_LINE_ERR; } if (fixed_queue_is_empty(p_port->rx.queue)) { log::warn("Read on empty input queue"); - return (PORT_SUCCESS); + return PORT_SUCCESS; } count = 0; while (max_len) { p_buf = (BT_HDR*)fixed_queue_try_peek_first(p_port->rx.queue); - if (p_buf == NULL) break; + if (p_buf == NULL) { + break; + } if (p_buf->len > max_len) { memcpy(p_data, (uint8_t*)(p_buf + 1) + p_buf->offset, max_len); @@ -766,18 +747,17 @@ int PORT_ReadData(uint16_t handle, char* p_data, uint16_t max_len, } if (*p_len == 1) { - log::verbose("PORT_ReadData queue:{} returned:{} {:x}", - p_port->rx.queue_size, *p_len, p_data[0]); + log::verbose("PORT_ReadData queue:{} returned:{} {:x}", p_port->rx.queue_size, *p_len, + p_data[0]); } else { - log::verbose("PORT_ReadData queue:{} returned:{}", p_port->rx.queue_size, - *p_len); + log::verbose("PORT_ReadData queue:{} returned:{}", p_port->rx.queue_size, *p_len); } /* If rfcomm suspended traffic from the peer based on the rx_queue_size */ /* check if it can be resumed now */ port_flow_control_peer(p_port, true, count); - return (PORT_SUCCESS); + return PORT_SUCCESS; } /******************************************************************************* @@ -796,14 +776,13 @@ static int port_write(tPORT* p_port, BT_HDR* p_buf) { * opened */ if (p_port->is_server && (p_port->rfc.state != RFC_STATE_OPENED)) { osi_free(p_buf); - return (PORT_CLOSED); + return PORT_CLOSED; } /* Keep the data in pending queue if peer does not allow data, or */ /* Peer is not ready or Port is not yet opened or initial port control */ /* command has not been sent */ - if (p_port->tx.peer_fc || !p_port->rfc.p_mcb || - !p_port->rfc.p_mcb->peer_ready || + if (p_port->tx.peer_fc || !p_port->rfc.p_mcb || !p_port->rfc.p_mcb->peer_ready || (p_port->rfc.state != RFC_STATE_OPENED) || ((p_port->port_ctrl & (PORT_CTRL_REQ_SENT | PORT_CTRL_IND_RECEIVED)) != (PORT_CTRL_REQ_SENT | PORT_CTRL_IND_RECEIVED))) { @@ -813,27 +792,28 @@ static int port_write(tPORT* p_port, BT_HDR* p_buf) { osi_free(p_buf); - if ((p_port->p_callback != NULL) && (p_port->ev_mask & PORT_EV_ERR)) + if ((p_port->p_callback != NULL) && (p_port->ev_mask & PORT_EV_ERR)) { p_port->p_callback(PORT_EV_ERR, p_port->handle); + } - return (PORT_TX_FULL); + return PORT_TX_FULL; } log::verbose( - "PORT_Write : Data is enqued. flow disabled {} peer_ready {} state {} " - "ctrl_state {:x}", - p_port->tx.peer_fc, p_port->rfc.p_mcb && p_port->rfc.p_mcb->peer_ready, - p_port->rfc.state, p_port->port_ctrl); + "PORT_Write : Data is enqueued. flow disabled {} peer_ready {} state {} ctrl_state " + "{:x}", + p_port->tx.peer_fc, p_port->rfc.p_mcb && p_port->rfc.p_mcb->peer_ready, + p_port->rfc.state, p_port->port_ctrl); fixed_queue_enqueue(p_port->tx.queue, p_buf); p_port->tx.queue_size += p_buf->len; - return (PORT_CMD_PENDING); + return PORT_CMD_PENDING; } else { log::verbose("PORT_Write : Data is being sent"); RFCOMM_DataReq(p_port->rfc.p_mcb, p_port->dlci, p_buf); - return (PORT_SUCCESS); + return PORT_SUCCESS; } } @@ -861,30 +841,29 @@ int PORT_WriteDataCO(uint16_t handle, int* p_len) { tPORT* p_port = get_port_from_handle(handle); if (p_port == nullptr) { log::error("Unable to get RFCOMM port control block bad handle:{}", handle); - return (PORT_BAD_HANDLE); + return PORT_BAD_HANDLE; } if (!p_port->in_use || (p_port->state == PORT_CONNECTION_STATE_CLOSED)) { log::warn("PORT_WriteDataByFd() no port state:{}", p_port->state); - return (PORT_NOT_OPENED); + return PORT_NOT_OPENED; } if (!p_port->peer_mtu) { log::error("PORT_WriteDataByFd() peer_mtu:{}", p_port->peer_mtu); - return (PORT_UNKNOWN_ERROR); + return PORT_UNKNOWN_ERROR; } int available = 0; // if(ioctl(fd, FIONREAD, &available) < 0) - if (!p_port->p_data_co_callback(handle, (uint8_t*)&available, - sizeof(available), + if (!p_port->p_data_co_callback(handle, (uint8_t*)&available, sizeof(available), DATA_CO_CALLBACK_TYPE_OUTGOING_SIZE)) { - log::error( - "p_data_co_callback DATA_CO_CALLBACK_TYPE_INCOMING_SIZE failed, " - "available:{}", - available); - return (PORT_UNKNOWN_ERROR); + log::error("p_data_co_callback DATA_CO_CALLBACK_TYPE_INCOMING_SIZE failed, available:{}", + available); + return PORT_UNKNOWN_ERROR; + } + if (available == 0) { + return PORT_SUCCESS; } - if (available == 0) return PORT_SUCCESS; /* Length for each buffer is the smaller of GKI buffer, peer MTU, or max_len */ length = RFCOMM_DATA_BUF_SIZE - @@ -895,22 +874,18 @@ int PORT_WriteDataCO(uint16_t handle, int* p_len) { mutex_global_lock(); p_buf = (BT_HDR*)fixed_queue_try_peek_last(p_port->tx.queue); - if ((p_buf != NULL) && - (((int)p_buf->len + available) <= (int)p_port->peer_mtu) && + if ((p_buf != NULL) && (((int)p_buf->len + available) <= (int)p_port->peer_mtu) && (((int)p_buf->len + available) <= (int)length)) { // if(recv(fd, (uint8_t *)(p_buf + 1) + p_buf->offset + p_buf->len, // available, 0) != available) - if (!p_port->p_data_co_callback( - handle, (uint8_t*)(p_buf + 1) + p_buf->offset + p_buf->len, - available, DATA_CO_CALLBACK_TYPE_OUTGOING)) + if (!p_port->p_data_co_callback(handle, (uint8_t*)(p_buf + 1) + p_buf->offset + p_buf->len, + available, DATA_CO_CALLBACK_TYPE_OUTGOING)) { - log::error( - "p_data_co_callback DATA_CO_CALLBACK_TYPE_OUTGOING failed, " - "available:{}", - available); + log::error("p_data_co_callback DATA_CO_CALLBACK_TYPE_OUTGOING failed, available:{}", + available); mutex_global_unlock(); - return (PORT_UNKNOWN_ERROR); + return PORT_UNKNOWN_ERROR; } // memcpy ((uint8_t *)(p_buf + 1) + p_buf->offset + p_buf->len, p_data, // max_len); @@ -921,7 +896,7 @@ int PORT_WriteDataCO(uint16_t handle, int* p_len) { mutex_global_unlock(); - return (PORT_SUCCESS); + return PORT_SUCCESS; } mutex_global_unlock(); @@ -936,10 +911,8 @@ int PORT_WriteDataCO(uint16_t handle, int* p_len) { (fixed_queue_length(p_port->tx.queue) > PORT_TX_BUF_HIGH_WM)) { port_flow_control_user(p_port); event |= PORT_EV_FC; - log::verbose( - "tx queue is full,tx.queue_size:{},tx.queue.count:{},available:{}", - p_port->tx.queue_size, fixed_queue_length(p_port->tx.queue), - available); + log::verbose("tx queue is full,tx.queue_size:{},tx.queue.count:{},available:{}", + p_port->tx.queue_size, fixed_queue_length(p_port->tx.queue), available); break; } @@ -948,21 +921,22 @@ int PORT_WriteDataCO(uint16_t handle, int* p_len) { p_buf->offset = L2CAP_MIN_OFFSET + RFCOMM_MIN_OFFSET; p_buf->layer_specific = handle; - if (p_port->peer_mtu < length) length = p_port->peer_mtu; - if (available < (int)length) length = (uint16_t)available; + if (p_port->peer_mtu < length) { + length = p_port->peer_mtu; + } + if (available < (int)length) { + length = (uint16_t)available; + } p_buf->len = length; p_buf->event = BT_EVT_TO_BTU_SP_DATA; // memcpy ((uint8_t *)(p_buf + 1) + p_buf->offset, p_data, length); // if(recv(fd, (uint8_t *)(p_buf + 1) + p_buf->offset, (int)length, 0) != // (int)length) - if (!p_port->p_data_co_callback(handle, - (uint8_t*)(p_buf + 1) + p_buf->offset, - length, DATA_CO_CALLBACK_TYPE_OUTGOING)) { - log::error( - "p_data_co_callback DATA_CO_CALLBACK_TYPE_OUTGOING failed, length:{}", - length); - return (PORT_UNKNOWN_ERROR); + if (!p_port->p_data_co_callback(handle, (uint8_t*)(p_buf + 1) + p_buf->offset, length, + DATA_CO_CALLBACK_TYPE_OUTGOING)) { + log::error("p_data_co_callback DATA_CO_CALLBACK_TYPE_OUTGOING failed, length:{}", length); + return PORT_UNKNOWN_ERROR; } log::verbose("PORT_WriteData {} bytes", length); @@ -972,23 +946,30 @@ int PORT_WriteDataCO(uint16_t handle, int* p_len) { /* If queue went below the threashold need to send flow control */ event |= port_flow_control_user(p_port); - if (rc == PORT_SUCCESS) event |= PORT_EV_TXCHAR; + if (rc == PORT_SUCCESS) { + event |= PORT_EV_TXCHAR; + } - if ((rc != PORT_SUCCESS) && (rc != PORT_CMD_PENDING)) break; + if ((rc != PORT_SUCCESS) && (rc != PORT_CMD_PENDING)) { + break; + } *p_len += length; available -= (int)length; } - if (!available && (rc != PORT_CMD_PENDING) && (rc != PORT_TX_QUEUE_DISABLED)) + if (!available && (rc != PORT_CMD_PENDING) && (rc != PORT_TX_QUEUE_DISABLED)) { event |= PORT_EV_TXEMPTY; + } /* Mask out all events that are not of interest to user */ event &= p_port->ev_mask; /* Send event to the application */ - if (p_port->p_callback && event) (p_port->p_callback)(event, p_port->handle); + if (p_port->p_callback && event) { + (p_port->p_callback)(event, p_port->handle); + } - return (PORT_SUCCESS); + return PORT_SUCCESS; } /******************************************************************************* @@ -1004,8 +985,7 @@ int PORT_WriteDataCO(uint16_t handle, int* p_len) { * p_len - Byte count received * ******************************************************************************/ -int PORT_WriteData(uint16_t handle, const char* p_data, uint16_t max_len, - uint16_t* p_len) { +int PORT_WriteData(uint16_t handle, const char* p_data, uint16_t max_len, uint16_t* p_len) { BT_HDR* p_buf; uint32_t event = 0; int rc = 0; @@ -1018,12 +998,12 @@ int PORT_WriteData(uint16_t handle, const char* p_data, uint16_t max_len, tPORT* p_port = get_port_from_handle(handle); if (p_port == nullptr) { log::error("Unable to get RFCOMM port control block bad handle:{}", handle); - return (PORT_BAD_HANDLE); + return PORT_BAD_HANDLE; } if (!p_port->in_use || (p_port->state == PORT_CONNECTION_STATE_CLOSED)) { log::warn("PORT_WriteData() no port state:{}", p_port->state); - return (PORT_NOT_OPENED); + return PORT_NOT_OPENED; } if (p_port->state == PORT_CONNECTION_STATE_OPENING) { @@ -1032,7 +1012,7 @@ int PORT_WriteData(uint16_t handle, const char* p_data, uint16_t max_len, if (!max_len || !p_port->peer_mtu) { log::error("PORT_WriteData() peer_mtu:{}", p_port->peer_mtu); - return (PORT_UNKNOWN_ERROR); + return PORT_UNKNOWN_ERROR; } /* Length for each buffer is the smaller of GKI buffer, peer MTU, or max_len @@ -1055,7 +1035,7 @@ int PORT_WriteData(uint16_t handle, const char* p_data, uint16_t max_len, mutex_global_unlock(); - return (PORT_SUCCESS); + return PORT_SUCCESS; } mutex_global_unlock(); @@ -1063,16 +1043,21 @@ int PORT_WriteData(uint16_t handle, const char* p_data, uint16_t max_len, while (max_len) { /* if we're over buffer high water mark, we're done */ if ((p_port->tx.queue_size > PORT_TX_HIGH_WM) || - (fixed_queue_length(p_port->tx.queue) > PORT_TX_BUF_HIGH_WM)) + (fixed_queue_length(p_port->tx.queue) > PORT_TX_BUF_HIGH_WM)) { break; + } /* continue with rfcomm data write */ p_buf = (BT_HDR*)osi_malloc(RFCOMM_DATA_BUF_SIZE); p_buf->offset = L2CAP_MIN_OFFSET + RFCOMM_MIN_OFFSET; p_buf->layer_specific = handle; - if (p_port->peer_mtu < length) length = p_port->peer_mtu; - if (max_len < length) length = max_len; + if (p_port->peer_mtu < length) { + length = p_port->peer_mtu; + } + if (max_len < length) { + length = max_len; + } p_buf->len = length; p_buf->event = BT_EVT_TO_BTU_SP_DATA; @@ -1085,24 +1070,31 @@ int PORT_WriteData(uint16_t handle, const char* p_data, uint16_t max_len, /* If queue went below the threashold need to send flow control */ event |= port_flow_control_user(p_port); - if (rc == PORT_SUCCESS) event |= PORT_EV_TXCHAR; + if (rc == PORT_SUCCESS) { + event |= PORT_EV_TXCHAR; + } - if ((rc != PORT_SUCCESS) && (rc != PORT_CMD_PENDING)) break; + if ((rc != PORT_SUCCESS) && (rc != PORT_CMD_PENDING)) { + break; + } *p_len += length; max_len -= length; p_data += length; } - if (!max_len && (rc != PORT_CMD_PENDING) && (rc != PORT_TX_QUEUE_DISABLED)) + if (!max_len && (rc != PORT_CMD_PENDING) && (rc != PORT_TX_QUEUE_DISABLED)) { event |= PORT_EV_TXEMPTY; + } /* Mask out all events that are not of interest to user */ event &= p_port->ev_mask; /* Send event to the application */ - if (p_port->p_callback && event) (p_port->p_callback)(event, p_port->handle); + if (p_port->p_callback && event) { + (p_port->p_callback)(event, p_port->handle); + } - return (PORT_SUCCESS); + return PORT_SUCCESS; } /******************************************************************************* @@ -1153,8 +1145,8 @@ int PORT_GetSecurityMask(uint16_t handle, uint16_t* sec_mask) { tPORT* p_port = get_port_from_handle(handle); if (p_port == nullptr) { log::error("Unable to get RFCOMM port control block bad handle:{}", handle); - return (PORT_BAD_HANDLE); + return PORT_BAD_HANDLE; } *sec_mask = p_port->sec_mask; - return (PORT_SUCCESS); + return PORT_SUCCESS; } diff --git a/system/stack/rfcomm/port_int.h b/system/stack/rfcomm/port_int.h index a554e46c36e..08a524ab344 100644 --- a/system/stack/rfcomm/port_int.h +++ b/system/stack/rfcomm/port_int.h @@ -39,25 +39,25 @@ /* * Flow control configuration values for the mux -*/ + */ #define PORT_FC_UNDEFINED 0 /* mux flow control mechanism not defined yet */ #define PORT_FC_TS710 1 /* use TS 07.10 flow control */ #define PORT_FC_CREDIT 2 /* use RFCOMM credit based flow control */ /* * Define Port Data Transfere control block -*/ + */ typedef struct { - fixed_queue_t* queue; /* Queue of buffers waiting to be sent */ - bool peer_fc; /* true if flow control is set based on peer's request */ - bool user_fc; /* true if flow control is set based on user's request */ + fixed_queue_t* queue; /* Queue of buffers waiting to be sent */ + bool peer_fc; /* true if flow control is set based on peer's request */ + bool user_fc; /* true if flow control is set based on user's request */ uint32_t queue_size; /* Number of data bytes in the queue */ tPORT_CALLBACK* p_callback; /* Address of the callback function */ } tPORT_DATA; /* * Port control structure used to pass modem info -*/ + */ typedef struct { #define MODEM_SIGNAL_DTRDSR 0x01 #define MODEM_SIGNAL_RTSCTS 0x02 @@ -80,34 +80,32 @@ typedef struct { /* * RFCOMM multiplexer Control Block -*/ + */ typedef struct { - alarm_t* mcb_timer = nullptr; /* MCB timer */ - fixed_queue_t* cmd_q = nullptr; /* Queue for command messages on this mux */ + alarm_t* mcb_timer = nullptr; /* MCB timer */ + fixed_queue_t* cmd_q = nullptr; /* Queue for command messages on this mux */ uint8_t port_handles[RFCOMM_MAX_DLCI + 1]; /* Array for quick access to */ /* port handles based on dlci */ - RawAddress bd_addr = - RawAddress::kEmpty; /* BD ADDR of the peer if initiator */ - uint16_t lcid; /* Local cid used for this channel */ - uint16_t peer_l2cap_mtu; /* Max frame that can be sent to peer L2CAP */ - tRFC_MX_STATE state; /* Current multiplexer channel state */ - uint8_t is_initiator; /* true if this side sends SABME (dlci=0) */ - bool restart_required; /* true if has to restart channel after disc */ - bool peer_ready; /* True if other side can accept frames */ - uint8_t flow; /* flow control mechanism for this mux */ - bool l2cap_congested; /* true if L2CAP is congested */ - bool is_disc_initiator; /* true if initiated disc of port */ - uint16_t - pending_lcid; /* store LCID for incoming connection while connecting */ - bool pending_configure_complete; /* true if confiquration of the pending - connection was completed*/ - tL2CAP_CFG_INFO pending_cfg_info = {}; /* store configure info for incoming - connection while connecting */ + RawAddress bd_addr = RawAddress::kEmpty; /* BD ADDR of the peer if initiator */ + uint16_t lcid; /* Local cid used for this channel */ + uint16_t peer_l2cap_mtu; /* Max frame that can be sent to peer L2CAP */ + tRFC_MX_STATE state; /* Current multiplexer channel state */ + uint8_t is_initiator; /* true if this side sends SABME (dlci=0) */ + bool restart_required; /* true if has to restart channel after disc */ + bool peer_ready; /* True if other side can accept frames */ + uint8_t flow; /* flow control mechanism for this mux */ + bool l2cap_congested; /* true if L2CAP is congested */ + bool is_disc_initiator; /* true if initiated disc of port */ + uint16_t pending_lcid; /* store LCID for incoming connection while connecting */ + bool pending_configure_complete; /* true if confiquration of the pending + connection was completed*/ + tL2CAP_CFG_INFO pending_cfg_info = {}; /* store configure info for incoming + connection while connecting */ } tRFC_MCB; /* * RFCOMM Port Connection Control Block -*/ + */ typedef struct { uint8_t state; /* Current state of the connection */ @@ -131,8 +129,7 @@ typedef enum : uint8_t { PORT_CONNECTION_STATE_CLOSING = 3, } tPORT_CONNECTION_STATE; -inline std::string port_connection_state_text( - const tPORT_CONNECTION_STATE& state) { +inline std::string port_connection_state_text(const tPORT_CONNECTION_STATE& state) { switch (state) { CASE_RETURN_STRING(PORT_CONNECTION_STATE_CLOSED); CASE_RETURN_STRING(PORT_CONNECTION_STATE_OPENING); @@ -146,16 +143,15 @@ inline std::string port_connection_state_text( namespace fmt { template <> -struct formatter - : enum_formatter {}; +struct formatter : enum_formatter {}; } // namespace fmt /* * Define control block containing information about PORT connection -*/ + */ typedef struct { uint8_t handle; // Starting from 1, unique for this object - bool in_use; /* True when structure is allocated */ + bool in_use; /* True when structure is allocated */ tPORT_CONNECTION_STATE state; /* State of the application */ @@ -163,8 +159,8 @@ typedef struct { uint16_t uuid; /* Service UUID */ RawAddress bd_addr; /* BD ADDR of the device for the multiplexer channel */ - bool is_server; /* true if the server application */ - uint8_t dlci; /* DLCI of the connection */ + bool is_server; /* true if the server application */ + uint8_t dlci; /* DLCI of the connection */ uint8_t line_status; /* Line status as reported by peer */ @@ -193,19 +189,15 @@ typedef struct { tRFC_PORT rfc; /* RFCOMM port control block */ - uint32_t ev_mask; /* Event mask for the callback */ - tPORT_CALLBACK* p_callback; /* Pointer to users callback function */ - tPORT_MGMT_CALLBACK* - p_mgmt_callback; /* Callback function to receive connection up/down */ - tPORT_DATA_CALLBACK* - p_data_callback; /* Callback function to receive data indications */ - tPORT_DATA_CO_CALLBACK* - p_data_co_callback; /* Callback function with callouts and flowctrl */ - uint16_t credit_tx; /* Flow control credits for tx path */ - uint16_t credit_rx; /* Flow control credits for rx path, this is */ - /* number of buffers peer is allowed to sent */ - uint16_t - credit_rx_max; /* Max number of credits we will allow this guy to sent */ + uint32_t ev_mask; /* Event mask for the callback */ + tPORT_CALLBACK* p_callback; /* Pointer to users callback function */ + tPORT_MGMT_CALLBACK* p_mgmt_callback; /* Callback function to receive connection up/down */ + tPORT_DATA_CALLBACK* p_data_callback; /* Callback function to receive data indications */ + tPORT_DATA_CO_CALLBACK* p_data_co_callback; /* Callback function with callouts and flowctrl */ + uint16_t credit_tx; /* Flow control credits for tx path */ + uint16_t credit_rx; /* Flow control credits for rx path, this is */ + /* number of buffers peer is allowed to sent */ + uint16_t credit_rx_max; /* Max number of credits we will allow this guy to sent */ uint16_t credit_rx_low; /* Number of credits when we send credit update */ uint16_t rx_buf_critical; /* port receive queue critical watermark level */ bool keep_port_handle; /* true if port is not deallocated when closing */ @@ -216,7 +208,7 @@ typedef struct { } tPORT; /* Define the PORT/RFCOMM control structure -*/ + */ typedef struct { tPORT port[MAX_RFC_PORTS]; /* Port info pool */ tRFC_MCB rfc_mcb[MAX_BD_CONNECTIONS]; /* RFCOMM bd_connections pool */ @@ -224,7 +216,7 @@ typedef struct { /* * Functions provided by the port_utils.cc -*/ + */ tPORT* port_allocate_port(uint8_t dlci, const RawAddress& bd_addr); void port_set_defaults(tPORT* p_port); void port_select_mtu(tPORT* p_port); @@ -233,14 +225,13 @@ tPORT* port_find_mcb_dlci_port(tRFC_MCB* p_mcb, uint8_t dlci); tRFC_MCB* port_find_mcb(const RawAddress& bd_addr); tPORT* port_find_dlci_port(uint8_t dlci); tPORT* port_find_port(uint8_t dlci, const RawAddress& bd_addr); -uint32_t port_get_signal_changes(tPORT* p_port, uint8_t old_signals, - uint8_t signal); +uint32_t port_get_signal_changes(tPORT* p_port, uint8_t old_signals, uint8_t signal); uint32_t port_flow_control_user(tPORT* p_port); void port_flow_control_peer(tPORT* p_port, bool enable, uint16_t count); /* * Functions provided by the port_rfc.cc -*/ + */ int port_open_continue(tPORT* p_port); void port_start_port_open(tPORT* p_port); void port_start_par_neg(tPORT* p_port); diff --git a/system/stack/rfcomm/port_rfc.cc b/system/stack/rfcomm/port_rfc.cc index fa10cbd686b..b94aff9f305 100644 --- a/system/stack/rfcomm/port_rfc.cc +++ b/system/stack/rfcomm/port_rfc.cc @@ -49,7 +49,7 @@ using namespace bluetooth; /* * Local function definitions -*/ + */ uint32_t port_rfc_send_tx_data(tPORT* p_port); void port_rfc_closed(tPORT* p_port, uint8_t res); void port_get_credits(tPORT* p_port, uint8_t k); @@ -72,7 +72,7 @@ int port_open_continue(tPORT* p_port) { if (p_mcb == nullptr) { log::warn("port_open_continue no mx channel"); port_release_port(p_port); - return (PORT_NO_RESOURCES); + return PORT_NO_RESOURCES; } p_port->rfc.p_mcb = p_mcb; @@ -85,8 +85,8 @@ int port_open_continue(tPORT* p_port) { switch (p_mcb->state) { case RFC_MX_STATE_CONNECTED: RFCOMM_ParameterNegotiationRequest(p_mcb, p_port->dlci, p_port->mtu); - log::verbose("Multiplexer already connected peer:{} state:{} cid:{}", - p_port->bd_addr, p_mcb->state, p_mcb->lcid); + log::verbose("Multiplexer already connected peer:{} state:{} cid:{}", p_port->bd_addr, + p_mcb->state, p_mcb->lcid); break; case RFC_MX_STATE_IDLE: @@ -95,18 +95,18 @@ int port_open_continue(tPORT* p_port) { // In RFC_MX_STATE_DISC_WAIT_UA state, MX state machine will recreate // connection after disconnecting is completed RFCOMM_StartReq(p_mcb); - log::verbose("Starting multiplexer connect peer:{} state:{} cid:{}", - p_port->bd_addr, p_mcb->state, p_mcb->lcid); + log::verbose("Starting multiplexer connect peer:{} state:{} cid:{}", p_port->bd_addr, + p_mcb->state, p_mcb->lcid); break; default: // MX state machine ignores RFC_MX_EVENT_START_REQ in these states // When it enters RFC_MX_STATE_CONNECTED, it will check any opening ports - log::verbose("Ignoring RFC_MX_EVENT_START_REQ peer:{} state:{} cid:{}", - p_port->bd_addr, p_mcb->state, p_mcb->lcid); + log::verbose("Ignoring RFC_MX_EVENT_START_REQ peer:{} state:{} cid:{}", p_port->bd_addr, + p_mcb->state, p_mcb->lcid); break; } - return (PORT_SUCCESS); + return PORT_SUCCESS; } /******************************************************************************* @@ -120,7 +120,9 @@ int port_open_continue(tPORT* p_port) { void port_start_control(tPORT* p_port) { tRFC_MCB* p_mcb = p_port->rfc.p_mcb; - if (p_mcb == NULL) return; + if (p_mcb == NULL) { + return; + } RFCOMM_ControlReq(p_mcb, p_port->dlci, &p_port->local_ctrl); } @@ -136,10 +138,11 @@ void port_start_control(tPORT* p_port) { void port_start_par_neg(tPORT* p_port) { tRFC_MCB* p_mcb = p_port->rfc.p_mcb; - if (p_mcb == NULL) return; + if (p_mcb == NULL) { + return; + } - RFCOMM_PortParameterNegotiationRequest(p_mcb, p_port->dlci, - &p_port->user_port_pars); + RFCOMM_PortParameterNegotiationRequest(p_mcb, p_port->dlci, &p_port->user_port_pars); } /******************************************************************************* @@ -160,18 +163,21 @@ void port_start_close(tPORT* p_port) { p_port->line_status |= LINE_STATUS_FAILED; old_signals = p_port->peer_ctrl.modem_signal; - p_port->peer_ctrl.modem_signal &= - ~(PORT_DTRDSR_ON | PORT_CTSRTS_ON | PORT_DCD_ON); + p_port->peer_ctrl.modem_signal &= ~(PORT_DTRDSR_ON | PORT_CTSRTS_ON | PORT_DCD_ON); - events |= port_get_signal_changes(p_port, old_signals, - p_port->peer_ctrl.modem_signal); + events |= port_get_signal_changes(p_port, old_signals, p_port->peer_ctrl.modem_signal); - if (p_port->ev_mask & PORT_EV_CONNECT_ERR) events |= PORT_EV_CONNECT_ERR; + if (p_port->ev_mask & PORT_EV_CONNECT_ERR) { + events |= PORT_EV_CONNECT_ERR; + } - if (p_port->ev_mask & PORT_EV_ERR) events |= PORT_EV_ERR; + if (p_port->ev_mask & PORT_EV_ERR) { + events |= PORT_EV_ERR; + } - if ((p_port->p_callback != NULL) && events) + if ((p_port->p_callback != NULL) && events) { p_port->p_callback(events, p_port->handle); + } /* Check if RFCOMM side has been closed while the message was queued */ if ((p_mcb == NULL) || (p_port->rfc.state == RFC_STATE_CLOSED)) { @@ -179,9 +185,7 @@ void port_start_close(tPORT* p_port) { * clear tPort */ if (p_port->p_mgmt_callback) { p_port->p_mgmt_callback(PORT_CLOSED, p_port->handle); - log_counter_metrics( - android::bluetooth::CodePathCounterKeyEnum::RFCOMM_PORT_START_CLOSE, - 1); + log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum::RFCOMM_PORT_START_CLOSE, 1); } port_release_port(p_port); @@ -214,8 +218,7 @@ void PORT_StartCnf(tRFC_MCB* p_mcb, uint16_t result) { log::verbose("dlci {}", p_port->dlci); RFCOMM_ParameterNegotiationRequest(p_mcb, p_port->dlci, p_port->mtu); } else { - log::warn("Unable start configuration dlci:{} result:{}", p_port->dlci, - result); + log::warn("Unable start configuration dlci:{} result:{}", p_port->dlci, result); rfc_release_multiplexer_channel(p_mcb); @@ -226,9 +229,8 @@ void PORT_StartCnf(tRFC_MCB* p_mcb, uint16_t result) { if (p_port->p_mgmt_callback) { p_port->p_mgmt_callback(PORT_START_FAILED, p_port->handle); - log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum:: - RFCOMM_PORT_START_CNF_FAILED, - 1); + log_counter_metrics( + android::bluetooth::CodePathCounterKeyEnum::RFCOMM_PORT_START_CNF_FAILED, 1); } port_release_port(p_port); } @@ -261,8 +263,7 @@ void PORT_StartInd(tRFC_MCB* p_mcb) { p_port = &rfc_cb.port.port[0]; for (i = 0; i < MAX_RFC_PORTS; i++, p_port++) { if ((p_port->rfc.p_mcb == NULL) || (p_port->rfc.p_mcb == p_mcb)) { - log::verbose("PORT_StartInd, RFCOMM_StartRsp RFCOMM_SUCCESS: p_mcb:{}", - fmt::ptr(p_mcb)); + log::verbose("PORT_StartInd, RFCOMM_StartRsp RFCOMM_SUCCESS: p_mcb:{}", fmt::ptr(p_mcb)); RFCOMM_StartRsp(p_mcb, RFCOMM_SUCCESS); return; } @@ -280,17 +281,15 @@ void PORT_StartInd(tRFC_MCB* p_mcb) { * Otherwise save the MTU size supported by the peer. * ******************************************************************************/ -void PORT_ParNegInd(tRFC_MCB* p_mcb, uint8_t dlci, uint16_t mtu, uint8_t cl, - uint8_t k) { +void PORT_ParNegInd(tRFC_MCB* p_mcb, uint8_t dlci, uint16_t mtu, uint8_t cl, uint8_t k) { log::verbose("bd_addr={}, dlci={}, mtu={}", p_mcb->bd_addr, dlci, mtu); tPORT* p_port = port_find_mcb_dlci_port(p_mcb, dlci); if (!p_port) { /* This can be a first request for this port */ p_port = port_find_dlci_port(dlci); if (!p_port) { - log::error( - "Disconnect RFCOMM, port not found, dlci={}, p_mcb={}, bd_addr={}", - dlci, fmt::ptr(p_mcb), p_mcb->bd_addr); + log::error("Disconnect RFCOMM, port not found, dlci={}, p_mcb={}, bd_addr={}", dlci, + fmt::ptr(p_mcb), p_mcb->bd_addr); /* If the port cannot be opened, send a DM. Per Errata 1205 */ rfc_send_dm(p_mcb, dlci, false); /* check if this is the last port open, some headsets have @@ -298,8 +297,7 @@ void PORT_ParNegInd(tRFC_MCB* p_mcb, uint8_t dlci, uint16_t mtu, uint8_t cl, rfc_check_mcb_active(p_mcb); return; } - log::verbose("port_handles[dlci:{}]:{}->{}", dlci, - p_mcb->port_handles[dlci], p_port->handle); + log::verbose("port_handles[dlci:{}]:{}->{}", dlci, p_mcb->port_handles[dlci], p_port->handle); p_mcb->port_handles[dlci] = p_port->handle; } @@ -345,8 +343,7 @@ void PORT_ParNegInd(tRFC_MCB* p_mcb, uint8_t dlci, uint16_t mtu, uint8_t cl, /* Set convergence layer and number of credits (k) */ our_cl = RFCOMM_PN_CONV_LAYER_CBFC_R; - our_k = (p_port->credit_rx_max < RFCOMM_K_MAX) ? p_port->credit_rx_max - : RFCOMM_K_MAX; + our_k = (p_port->credit_rx_max < RFCOMM_K_MAX) ? p_port->credit_rx_max : RFCOMM_K_MAX; p_port->credit_rx = our_k; } else { /* must not be using credit based flow control; use TS 7.10 */ @@ -367,8 +364,7 @@ void PORT_ParNegInd(tRFC_MCB* p_mcb, uint8_t dlci, uint16_t mtu, uint8_t cl, * procedure send EstablishRequest to continue. * ******************************************************************************/ -void PORT_ParNegCnf(tRFC_MCB* p_mcb, uint8_t dlci, uint16_t mtu, uint8_t cl, - uint8_t k) { +void PORT_ParNegCnf(tRFC_MCB* p_mcb, uint8_t dlci, uint16_t mtu, uint8_t cl, uint8_t k) { log::verbose("PORT_ParNegCnf dlci:{} mtu:{} cl: {} k: {}", dlci, mtu, cl, k); tPORT* p_port = port_find_mcb_dlci_port(p_mcb, dlci); if (!p_port) { @@ -399,8 +395,9 @@ void PORT_ParNegCnf(tRFC_MCB* p_mcb, uint8_t dlci, uint16_t mtu, uint8_t cl, port_get_credits(p_port, k); } - if (p_port->state == PORT_CONNECTION_STATE_OPENING) + if (p_port->state == PORT_CONNECTION_STATE_OPENING) { RFCOMM_DlcEstablishReq(p_mcb, p_port->dlci, p_port->mtu); + } } /******************************************************************************* @@ -419,8 +416,8 @@ void PORT_ParNegCnf(tRFC_MCB* p_mcb, uint8_t dlci, uint16_t mtu, uint8_t cl, void PORT_DlcEstablishInd(tRFC_MCB* p_mcb, uint8_t dlci, uint16_t mtu) { tPORT* p_port = port_find_mcb_dlci_port(p_mcb, dlci); - log::verbose("p_mcb:{}, dlci:{} mtu:{}i, p_port:{}, bd_addr:{}", - fmt::ptr(p_mcb), dlci, mtu, fmt::ptr(p_port), p_mcb->bd_addr); + log::verbose("p_mcb:{}, dlci:{} mtu:{}i, p_port:{}, bd_addr:{}", fmt::ptr(p_mcb), dlci, mtu, + fmt::ptr(p_port), p_mcb->bd_addr); if (!p_port) { /* This can be a first request for this port */ @@ -433,7 +430,9 @@ void PORT_DlcEstablishInd(tRFC_MCB* p_mcb, uint8_t dlci, uint16_t mtu) { } /* If L2CAP's mtu less then RFCOMM's take it */ - if (mtu && (mtu < p_port->peer_mtu)) p_port->peer_mtu = mtu; + if (mtu && (mtu < p_port->peer_mtu)) { + p_port->peer_mtu = mtu; + } /* If there was an inactivity timer running for MCB stop it */ rfc_timer_stop(p_mcb); @@ -442,13 +441,13 @@ void PORT_DlcEstablishInd(tRFC_MCB* p_mcb, uint8_t dlci, uint16_t mtu) { /* This is the server side. If application wants to know when connection */ /* is established, thats the place */ - if (p_port->p_callback && (p_port->ev_mask & PORT_EV_CONNECTED)) + if (p_port->p_callback && (p_port->ev_mask & PORT_EV_CONNECTED)) { (p_port->p_callback)(PORT_EV_CONNECTED, p_port->handle); + } if (p_port->p_mgmt_callback) { p_port->p_mgmt_callback(PORT_SUCCESS, p_port->handle); - log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum:: - RFCOMM_CONNECTION_SUCCESS_IND, + log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum::RFCOMM_CONNECTION_SUCCESS_IND, 1); } @@ -465,50 +464,48 @@ void PORT_DlcEstablishInd(tRFC_MCB* p_mcb, uint8_t dlci, uint16_t mtu) { * successful. * ******************************************************************************/ -void PORT_DlcEstablishCnf(tRFC_MCB* p_mcb, uint8_t dlci, uint16_t mtu, - uint16_t result) { +void PORT_DlcEstablishCnf(tRFC_MCB* p_mcb, uint8_t dlci, uint16_t mtu, uint16_t result) { tPORT* p_port = port_find_mcb_dlci_port(p_mcb, dlci); - log::verbose("PORT_DlcEstablishCnf dlci:{} mtu:{} result:{}", dlci, mtu, - result); + log::verbose("PORT_DlcEstablishCnf dlci:{} mtu:{} result:{}", dlci, mtu, result); - if (!p_port) return; + if (!p_port) { + return; + } if (result != RFCOMM_SUCCESS) { - log::warn("Unable to establish configuration dlci:{} result:{}", dlci, - result); + log::warn("Unable to establish configuration dlci:{} result:{}", dlci, result); port_rfc_closed(p_port, PORT_START_FAILED); - log_counter_metrics( - android::bluetooth::CodePathCounterKeyEnum::RFCOMM_PORT_START_FAILED, - 1); + log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum::RFCOMM_PORT_START_FAILED, 1); return; } /* If L2CAP's mtu less then RFCOMM's take it */ - if (mtu && (mtu < p_port->peer_mtu)) p_port->peer_mtu = mtu; + if (mtu && (mtu < p_port->peer_mtu)) { + p_port->peer_mtu = mtu; + } /* If there was an inactivity timer running for MCB stop it */ rfc_timer_stop(p_mcb); - if (p_port->p_callback && (p_port->ev_mask & PORT_EV_CONNECTED)) + if (p_port->p_callback && (p_port->ev_mask & PORT_EV_CONNECTED)) { (p_port->p_callback)(PORT_EV_CONNECTED, p_port->handle); + } if (p_port->p_mgmt_callback) { p_port->p_mgmt_callback(PORT_SUCCESS, p_port->handle); - log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum:: - RFCOMM_CONNECTION_SUCCESS_CNF, + log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum::RFCOMM_CONNECTION_SUCCESS_CNF, 1); } p_port->state = PORT_CONNECTION_STATE_OPENED; /* RPN is required only if we want to tell DTE how the port should be opened */ - if ((p_port->uuid == UUID_SERVCLASS_DIALUP_NETWORKING) || - (p_port->uuid == UUID_SERVCLASS_FAX)) - RFCOMM_PortParameterNegotiationRequest(p_port->rfc.p_mcb, p_port->dlci, - NULL); - else + if ((p_port->uuid == UUID_SERVCLASS_DIALUP_NETWORKING) || (p_port->uuid == UUID_SERVCLASS_FAX)) { + RFCOMM_PortParameterNegotiationRequest(p_port->rfc.p_mcb, p_port->dlci, NULL); + } else { RFCOMM_ControlReq(p_port->rfc.p_mcb, p_port->dlci, &p_port->local_ctrl); + } } /******************************************************************************* @@ -522,8 +519,7 @@ void PORT_DlcEstablishCnf(tRFC_MCB* p_mcb, uint8_t dlci, uint16_t mtu, * allocated before meaning that application already made open. * ******************************************************************************/ -void PORT_PortNegInd(tRFC_MCB* p_mcb, uint8_t dlci, tPORT_STATE* p_pars, - uint16_t param_mask) { +void PORT_PortNegInd(tRFC_MCB* p_mcb, uint8_t dlci, tPORT_STATE* p_pars, uint16_t param_mask) { tPORT* p_port = port_find_mcb_dlci_port(p_mcb, dlci); log::verbose("PORT_PortNegInd"); @@ -551,8 +547,7 @@ void PORT_PortNegInd(tRFC_MCB* p_mcb, uint8_t dlci, tPORT_STATE* p_pars, * state for the port. Propagate change to the user. * ******************************************************************************/ -void PORT_PortNegCnf(tRFC_MCB* p_mcb, uint8_t dlci, tPORT_STATE* /* p_pars */, - uint16_t result) { +void PORT_PortNegCnf(tRFC_MCB* p_mcb, uint8_t dlci, tPORT_STATE* /* p_pars */, uint16_t result) { tPORT* p_port = port_find_mcb_dlci_port(p_mcb, dlci); log::verbose("PORT_PortNegCnf"); @@ -567,8 +562,7 @@ void PORT_PortNegCnf(tRFC_MCB* p_mcb, uint8_t dlci, tPORT_STATE* /* p_pars */, RFCOMM_DlcReleaseReq(p_mcb, p_port->dlci); port_rfc_closed(p_port, PORT_PORT_NEG_FAILED); - log_counter_metrics( - android::bluetooth::CodePathCounterKeyEnum::RFCOMM_PORT_NEG_FAILED, 1); + log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum::RFCOMM_PORT_NEG_FAILED, 1); return; } @@ -594,7 +588,9 @@ void PORT_ControlInd(tRFC_MCB* p_mcb, uint8_t dlci, tPORT_CTRL* p_pars) { log::verbose("PORT_ControlInd"); - if (!p_port) return; + if (!p_port) { + return; + } old_signals = p_port->peer_ctrl.modem_signal; @@ -617,11 +613,15 @@ void PORT_ControlInd(tRFC_MCB* p_mcb, uint8_t dlci, tPORT_CTRL* p_pars) { p_port->port_ctrl |= (PORT_CTRL_IND_RECEIVED | PORT_CTRL_IND_RESPONDED); - if (p_pars->break_signal) event |= (PORT_EV_BREAK & p_port->ev_mask); + if (p_pars->break_signal) { + event |= (PORT_EV_BREAK & p_port->ev_mask); + } /* execute call back function only if the application is registered for events */ - if (event && p_port->p_callback) (p_port->p_callback)(event, p_port->handle); + if (event && p_port->p_callback) { + (p_port->p_callback)(event, p_port->handle); + } log::verbose("PORT_ControlInd DTR_DSR : {}, RTS_CTS : {}, RI : {}, DCD : {}", (p_port->peer_ctrl.modem_signal & MODEM_SIGNAL_DTRDSR) ? 1 : 0, @@ -644,13 +644,16 @@ void PORT_ControlCnf(tRFC_MCB* p_mcb, uint8_t dlci, tPORT_CTRL* /* p_pars */) { log::verbose("PORT_ControlCnf"); - if (!p_port) return; + if (!p_port) { + return; + } if (!(p_port->port_ctrl & PORT_CTRL_REQ_CONFIRMED)) { p_port->port_ctrl |= PORT_CTRL_REQ_CONFIRMED; - if (p_port->port_ctrl & PORT_CTRL_IND_RECEIVED) + if (p_port->port_ctrl & PORT_CTRL_IND_RECEIVED) { event = (p_port->ev_mask & PORT_EV_CONNECTED); + } } if (p_port->port_ctrl & PORT_CTRL_IND_RECEIVED) { @@ -659,7 +662,9 @@ void PORT_ControlCnf(tRFC_MCB* p_mcb, uint8_t dlci, tPORT_CTRL* /* p_pars */) { /* execute call back function only if the application is registered for events */ - if (event && p_port->p_callback) (p_port->p_callback)(event, p_port->handle); + if (event && p_port->p_callback) { + (p_port->p_callback)(event, p_port->handle); + } } /******************************************************************************* @@ -676,18 +681,27 @@ void PORT_LineStatusInd(tRFC_MCB* p_mcb, uint8_t dlci, uint8_t line_status) { log::verbose("PORT_LineStatusInd"); - if (!p_port) return; + if (!p_port) { + return; + } p_port->line_status |= line_status; - if (line_status & PORT_ERR_OVERRUN) event |= PORT_EV_OVERRUN; + if (line_status & PORT_ERR_OVERRUN) { + event |= PORT_EV_OVERRUN; + } - if (line_status & PORT_ERR_BREAK) event |= PORT_EV_BREAK; + if (line_status & PORT_ERR_BREAK) { + event |= PORT_EV_BREAK; + } - if (line_status & ~(PORT_ERR_OVERRUN | PORT_ERR_BREAK)) event |= PORT_EV_ERR; + if (line_status & ~(PORT_ERR_OVERRUN | PORT_ERR_BREAK)) { + event |= PORT_EV_ERR; + } - if ((p_port->p_callback != NULL) && (p_port->ev_mask & event)) + if ((p_port->p_callback != NULL) && (p_port->ev_mask & event)) { p_port->p_callback((p_port->ev_mask & event), p_port->handle); + } } /******************************************************************************* @@ -701,10 +715,11 @@ void PORT_LineStatusInd(tRFC_MCB* p_mcb, uint8_t dlci, uint8_t line_status) { void PORT_DlcReleaseInd(tRFC_MCB* p_mcb, uint8_t dlci) { log::verbose("dlci:{}, bd_addr:{}", dlci, p_mcb->bd_addr); tPORT* p_port = port_find_mcb_dlci_port(p_mcb, dlci); - if (!p_port) return; + if (!p_port) { + return; + } port_rfc_closed(p_port, PORT_CLOSED); - log_counter_metrics( - android::bluetooth::CodePathCounterKeyEnum::RFCOMM_PORT_CLOSED, 1); + log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum::RFCOMM_PORT_CLOSED, 1); } /******************************************************************************* @@ -725,9 +740,8 @@ void PORT_CloseInd(tRFC_MCB* p_mcb) { for (i = 0; i < MAX_RFC_PORTS; i++, p_port++) { if (p_port->rfc.p_mcb == p_mcb) { port_rfc_closed(p_port, PORT_PEER_CONNECTION_FAILED); - log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum:: - RFCOMM_PORT_PEER_CONNECTION_FAILED, - 1); + log_counter_metrics( + android::bluetooth::CodePathCounterKeyEnum::RFCOMM_PORT_PEER_CONNECTION_FAILED, 1); } } rfc_release_multiplexer_channel(p_mcb); @@ -751,9 +765,7 @@ void PORT_TimeOutCloseMux(tRFC_MCB* p_mcb) { for (i = 0; i < MAX_RFC_PORTS; i++, p_port++) { if (p_port->rfc.p_mcb == p_mcb) { port_rfc_closed(p_port, PORT_PEER_TIMEOUT); - log_counter_metrics( - android::bluetooth::CodePathCounterKeyEnum::RFCOMM_PORT_PEER_TIMEOUT, - 1); + log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum::RFCOMM_PORT_PEER_TIMEOUT, 1); } } } @@ -773,8 +785,8 @@ void PORT_DataInd(tRFC_MCB* p_mcb, uint8_t dlci, BT_HDR* p_buf) { uint8_t* p; int i; - log::verbose("PORT_DataInd with data length {}, p_mcb:{},p_port:{},dlci:{}", - p_buf->len, fmt::ptr(p_mcb), fmt::ptr(p_port), dlci); + log::verbose("PORT_DataInd with data length {}, p_mcb:{},p_port:{},dlci:{}", p_buf->len, + fmt::ptr(p_mcb), fmt::ptr(p_port), dlci); if (!p_port) { osi_free(p_buf); return; @@ -796,8 +808,7 @@ void PORT_DataInd(tRFC_MCB* p_mcb, uint8_t dlci, BT_HDR* p_buf) { if (p_port->p_data_callback) { /* Another packet is delivered to user. Send credits to peer if required */ port_flow_control_peer(p_port, true, 1); - p_port->p_data_callback(p_port->handle, - (uint8_t*)(p_buf + 1) + p_buf->offset, p_buf->len); + p_port->p_data_callback(p_port->handle, (uint8_t*)(p_buf + 1) + p_buf->offset, p_buf->len); osi_free(p_buf); return; } @@ -811,10 +822,8 @@ void PORT_DataInd(tRFC_MCB* p_mcb, uint8_t dlci, BT_HDR* p_buf) { } /* If user registered to receive notification when a particular byte is */ /* received we mast check all received bytes */ - if (((rx_char1 = p_port->user_port_pars.rx_char1) != 0) && - (p_port->ev_mask & PORT_EV_RXFLAG)) { - for (i = 0, p = (uint8_t*)(p_buf + 1) + p_buf->offset; i < p_buf->len; - i++) { + if (((rx_char1 = p_port->user_port_pars.rx_char1) != 0) && (p_port->ev_mask & PORT_EV_RXFLAG)) { + for (i = 0, p = (uint8_t*)(p_buf + 1) + p_buf->offset; i < p_buf->len; i++) { if (*p++ == rx_char1) { events |= PORT_EV_RXFLAG; break; @@ -845,7 +854,9 @@ void PORT_DataInd(tRFC_MCB* p_mcb, uint8_t dlci, BT_HDR* p_buf) { /* Mask out all events that are not of interest to user */ events &= p_port->ev_mask; - if (p_port->p_callback && events) p_port->p_callback(events, p_port->handle); + if (p_port->p_callback && events) { + p_port->p_callback(events, p_port->handle); + } } /******************************************************************************* @@ -867,7 +878,9 @@ void PORT_FlowInd(tRFC_MCB* p_mcb, uint8_t dlci, bool enable_data) { p_mcb->peer_ready = enable_data; } else { p_port = port_find_mcb_dlci_port(p_mcb, dlci); - if (p_port == NULL) return; + if (p_port == NULL) { + return; + } p_port->tx.peer_fc = !enable_data; } @@ -877,8 +890,9 @@ void PORT_FlowInd(tRFC_MCB* p_mcb, uint8_t dlci, bool enable_data) { if (dlci == 0) { p_port = &rfc_cb.port.port[i]; if (!p_port->in_use || (p_port->rfc.p_mcb != p_mcb) || - (p_port->rfc.state != RFC_STATE_OPENED)) + (p_port->rfc.state != RFC_STATE_OPENED)) { continue; + } } events = 0; @@ -892,11 +906,14 @@ void PORT_FlowInd(tRFC_MCB* p_mcb, uint8_t dlci, bool enable_data) { events &= p_port->ev_mask; /* Send event to the application */ - if (p_port->p_callback && events) + if (p_port->p_callback && events) { (p_port->p_callback)(events, p_port->handle); + } /* If DLCI is not 0 event applies to one port only */ - if (dlci != 0) break; + if (dlci != 0) { + break; + } } } @@ -914,8 +931,7 @@ uint32_t port_rfc_send_tx_data(tPORT* p_port) { /* if there is data to be sent */ if (p_port->tx.queue_size > 0) { /* while the rfcomm peer is not flow controlling us, and peer is ready */ - while (!p_port->tx.peer_fc && p_port->rfc.p_mcb && - p_port->rfc.p_mcb->peer_ready) { + while (!p_port->tx.peer_fc && p_port->rfc.p_mcb && p_port->rfc.p_mcb->peer_ready) { /* get data from tx queue and send it */ mutex_global_lock(); @@ -925,8 +941,7 @@ uint32_t port_rfc_send_tx_data(tPORT* p_port) { mutex_global_unlock(); - log::verbose("Sending RFCOMM_DataReq tx.queue_size={}", - p_port->tx.queue_size); + log::verbose("Sending RFCOMM_DataReq tx.queue_size={}", p_port->tx.queue_size); RFCOMM_DataReq(p_port->rfc.p_mcb, p_port->dlci, p_buf); @@ -948,7 +963,7 @@ uint32_t port_rfc_send_tx_data(tPORT* p_port) { /* If we flow controlled user based on the queue size enable data again */ events |= port_flow_control_user(p_port); } - return (events & p_port->ev_mask); + return events & p_port->ev_mask; } /******************************************************************************* @@ -994,8 +1009,8 @@ void port_rfc_closed(tPORT* p_port, uint8_t res) { ccb = l2cu_find_ccb_by_cid(nullptr, lcid); if (ccb) { - bluetooth::shim::GetSnoopLogger()->SetRfcommPortClose( - ccb->p_lcb->Handle(), lcid, p_port->dlci, p_port->uuid); + bluetooth::shim::GetSnoopLogger()->SetRfcommPortClose(ccb->p_lcb->Handle(), lcid, + p_port->dlci, p_port->uuid); } } @@ -1005,31 +1020,34 @@ void port_rfc_closed(tPORT* p_port, uint8_t res) { old_signals = p_port->peer_ctrl.modem_signal; - p_port->peer_ctrl.modem_signal &= - ~(PORT_DTRDSR_ON | PORT_CTSRTS_ON | PORT_DCD_ON); + p_port->peer_ctrl.modem_signal &= ~(PORT_DTRDSR_ON | PORT_CTSRTS_ON | PORT_DCD_ON); - events |= port_get_signal_changes(p_port, old_signals, - p_port->peer_ctrl.modem_signal); + events |= port_get_signal_changes(p_port, old_signals, p_port->peer_ctrl.modem_signal); - if (p_port->ev_mask & PORT_EV_CONNECT_ERR) events |= PORT_EV_CONNECT_ERR; + if (p_port->ev_mask & PORT_EV_CONNECT_ERR) { + events |= PORT_EV_CONNECT_ERR; + } } - if ((p_port->p_callback != NULL) && events) + if ((p_port->p_callback != NULL) && events) { p_port->p_callback(events, p_port->handle); + } if (p_port->p_mgmt_callback) { uint32_t res2 = res; - if (res2 >= PORT_ERR_MAX) res2 = PORT_ERR_MAX; + if (res2 >= PORT_ERR_MAX) { + res2 = PORT_ERR_MAX; + } p_port->p_mgmt_callback(static_cast(res2), p_port->handle); } p_port->rfc.state = RFC_STATE_CLOSED; log::info( - "RFCOMM connection closed, index={}, state={}, reason={}[{}], " - "UUID=0x{:x}, bd_addr={}, is_server={}", - p_port->handle, p_port->state, PORT_GetResultString(res), res, - p_port->uuid, p_port->bd_addr, p_port->is_server); + "RFCOMM connection closed, index={}, state={}, reason={}[{}], " + "UUID=0x{:x}, bd_addr={}, is_server={}", + p_port->handle, p_port->state, PORT_GetResultString(res), res, p_port->uuid, + p_port->bd_addr, p_port->is_server); port_release_port(p_port); } @@ -1046,5 +1064,7 @@ void port_rfc_closed(tPORT* p_port, uint8_t res) { ******************************************************************************/ void port_get_credits(tPORT* p_port, uint8_t k) { p_port->credit_tx = k; - if (p_port->credit_tx == 0) p_port->tx.peer_fc = true; + if (p_port->credit_tx == 0) { + p_port->tx.peer_fc = true; + } } diff --git a/system/stack/rfcomm/port_utils.cc b/system/stack/rfcomm/port_utils.cc index 9b8e76f5d73..97f3dc84b58 100644 --- a/system/stack/rfcomm/port_utils.cc +++ b/system/stack/rfcomm/port_utils.cc @@ -42,15 +42,15 @@ using namespace bluetooth; static const tPORT_STATE default_port_pars = { - PORT_BAUD_RATE_9600, - PORT_8_BITS, - PORT_ONESTOPBIT, - PORT_PARITY_NO, - PORT_ODD_PARITY, - PORT_FC_OFF, - 0, /* No rx_char */ - PORT_XON_DC1, - PORT_XOFF_DC3, + PORT_BAUD_RATE_9600, + PORT_8_BITS, + PORT_ONESTOPBIT, + PORT_PARITY_NO, + PORT_ODD_PARITY, + PORT_FC_OFF, + 0, /* No rx_char */ + PORT_XON_DC1, + PORT_XOFF_DC3, }; /******************************************************************************* @@ -68,8 +68,7 @@ static const tPORT_STATE default_port_pars = { tPORT* port_allocate_port(uint8_t dlci, const RawAddress& bd_addr) { uint8_t port_index = rfc_cb.rfc.last_port_index + static_cast(1); // Loop at most MAX_RFC_PORTS items - for (int loop_counter = 0; loop_counter < MAX_RFC_PORTS; - loop_counter++, port_index++) { + for (int loop_counter = 0; loop_counter < MAX_RFC_PORTS; loop_counter++, port_index++) { if (port_index >= MAX_RFC_PORTS) { port_index = 0; } @@ -86,9 +85,8 @@ tPORT* port_allocate_port(uint8_t dlci, const RawAddress& bd_addr) { p_port->dlci = dlci; p_port->bd_addr = bd_addr; rfc_cb.rfc.last_port_index = port_index; - log::verbose( - "rfc_cb.port.port[{}]:{} chosen, last_port_index:{}, bd_addr={}", - port_index, fmt::ptr(p_port), rfc_cb.rfc.last_port_index, bd_addr); + log::verbose("rfc_cb.port.port[{}]:{} chosen, last_port_index:{}, bd_addr={}", port_index, + fmt::ptr(p_port), rfc_cb.rfc.last_port_index, bd_addr); return p_port; } } @@ -144,8 +142,7 @@ void port_select_mtu(tPORT* p_port) { /* Will select MTU only if application did not setup something */ if (p_port->mtu == 0) { /* find packet size which connection supports */ - packet_size = - get_btm_client_interface().peer.BTM_GetMaxPacketSize(p_port->bd_addr); + packet_size = get_btm_client_interface().peer.BTM_GetMaxPacketSize(p_port->bd_addr); if (packet_size == 0) { /* something is very wrong */ log::warn("bad packet size 0 for{}", p_port->bd_addr); @@ -165,8 +162,7 @@ void port_select_mtu(tPORT* p_port) { 1 * 1027 = 1027. Minus 4 bytes L2CAP header 1023. Minus RFCOMM 6 bytes header overhead 1017 */ if ((L2CAP_MTU_SIZE + L2CAP_PKT_OVERHEAD) >= packet_size) { - p_port->mtu = ((L2CAP_MTU_SIZE + L2CAP_PKT_OVERHEAD) / packet_size * - packet_size) - + p_port->mtu = ((L2CAP_MTU_SIZE + L2CAP_PKT_OVERHEAD) / packet_size * packet_size) - RFCOMM_DATA_OVERHEAD - L2CAP_PKT_OVERHEAD; log::verbose("selected {} based on connection speed", p_port->mtu); } else { @@ -178,17 +174,19 @@ void port_select_mtu(tPORT* p_port) { log::verbose("application selected {}", p_port->mtu); } p_port->credit_rx_max = (PORT_RX_HIGH_WM / p_port->mtu); - if (p_port->credit_rx_max > PORT_RX_BUF_HIGH_WM) + if (p_port->credit_rx_max > PORT_RX_BUF_HIGH_WM) { p_port->credit_rx_max = PORT_RX_BUF_HIGH_WM; + } p_port->credit_rx_low = (PORT_RX_LOW_WM / p_port->mtu); - if (p_port->credit_rx_low > PORT_RX_BUF_LOW_WM) + if (p_port->credit_rx_low > PORT_RX_BUF_LOW_WM) { p_port->credit_rx_low = PORT_RX_BUF_LOW_WM; + } p_port->rx_buf_critical = (PORT_RX_CRITICAL_WM / p_port->mtu); - if (p_port->rx_buf_critical > PORT_RX_BUF_CRITICAL_WM) + if (p_port->rx_buf_critical > PORT_RX_BUF_CRITICAL_WM) { p_port->rx_buf_critical = PORT_RX_BUF_CRITICAL_WM; - log::verbose("credit_rx_max {}, credit_rx_low {}, rx_buf_critical {}", - p_port->credit_rx_max, p_port->credit_rx_low, - p_port->rx_buf_critical); + } + log::verbose("credit_rx_max {}, credit_rx_low {}, rx_buf_critical {}", p_port->credit_rx_max, + p_port->credit_rx_low, p_port->rx_buf_critical); } /******************************************************************************* @@ -201,19 +199,17 @@ void port_select_mtu(tPORT* p_port) { * ******************************************************************************/ void port_release_port(tPORT* p_port) { - log::verbose("p_port: {} state: {} keep_handle: {}", fmt::ptr(p_port), - p_port->rfc.state, p_port->keep_port_handle); + log::verbose("p_port: {} state: {} keep_handle: {}", fmt::ptr(p_port), p_port->rfc.state, + p_port->keep_port_handle); mutex_global_lock(); BT_HDR* p_buf; - while ((p_buf = (BT_HDR*)fixed_queue_try_dequeue(p_port->rx.queue)) != - nullptr) { + while ((p_buf = (BT_HDR*)fixed_queue_try_dequeue(p_port->rx.queue)) != nullptr) { osi_free(p_buf); } p_port->rx.queue_size = 0; - while ((p_buf = (BT_HDR*)fixed_queue_try_dequeue(p_port->tx.queue)) != - nullptr) { + while ((p_buf = (BT_HDR*)fixed_queue_try_dequeue(p_port->tx.queue)) != nullptr) { osi_free(p_buf); } p_port->tx.queue_size = 0; @@ -258,7 +254,9 @@ void port_release_port(tPORT* p_port) { p_port->state = PORT_CONNECTION_STATE_OPENING; p_port->rfc.p_mcb = nullptr; - if (p_port->is_server) p_port->dlci &= 0xfe; + if (p_port->is_server) { + p_port->dlci &= 0xfe; + } p_port->local_ctrl.modem_signal = p_port->default_signal_state; p_port->bd_addr = RawAddress::kAny; @@ -282,8 +280,7 @@ tRFC_MCB* port_find_mcb(const RawAddress& bd_addr) { for (tRFC_MCB& mcb : rfc_cb.port.rfc_mcb) { if ((mcb.state != RFC_MX_STATE_IDLE) && (mcb.bd_addr == bd_addr)) { /* Multiplexer channel found do not change anything */ - log::verbose("found, bd_addr:{}, rfc_mcb:{}, lcid:0x{:x}", bd_addr, - fmt::ptr(&mcb), mcb.lcid); + log::verbose("found, bd_addr:{}, rfc_mcb:{}, lcid:0x{:x}", bd_addr, fmt::ptr(&mcb), mcb.lcid); return &mcb; } } @@ -310,16 +307,14 @@ tPORT* port_find_mcb_dlci_port(tRFC_MCB* p_mcb, uint8_t dlci) { } if (dlci > RFCOMM_MAX_DLCI) { - log::warn("DLCI {} is too large, bd_addr={}, p_mcb={}", dlci, - p_mcb->bd_addr, fmt::ptr(p_mcb)); + log::warn("DLCI {} is too large, bd_addr={}, p_mcb={}", dlci, p_mcb->bd_addr, fmt::ptr(p_mcb)); return nullptr; } uint8_t handle = p_mcb->port_handles[dlci]; if (handle == 0) { - log::info( - "Cannot find allocated RFCOMM app port for DLCI {} on {}, p_mcb={}", - dlci, p_mcb->bd_addr, fmt::ptr(p_mcb)); + log::info("Cannot find allocated RFCOMM app port for DLCI {} on {}, p_mcb={}", dlci, + p_mcb->bd_addr, fmt::ptr(p_mcb)); return nullptr; } return &rfc_cb.port.port[handle - 1]; @@ -383,21 +378,23 @@ uint32_t port_flow_control_user(tPORT* p_port) { /* Flow control to the user can be caused by flow controlling by the peer */ /* (FlowInd, or flow control by the peer RFCOMM (Fcon) or internally if */ /* tx_queue is full */ - bool fc = p_port->tx.peer_fc || !p_port->rfc.p_mcb || - !p_port->rfc.p_mcb->peer_ready || + bool fc = p_port->tx.peer_fc || !p_port->rfc.p_mcb || !p_port->rfc.p_mcb->peer_ready || (p_port->tx.queue_size > PORT_TX_HIGH_WM) || (fixed_queue_length(p_port->tx.queue) > PORT_TX_BUF_HIGH_WM); - if (p_port->tx.user_fc == fc) return (0); + if (p_port->tx.user_fc == fc) { + return 0; + } p_port->tx.user_fc = fc; - if (fc) + if (fc) { event = PORT_EV_FC; - else + } else { event = PORT_EV_FC | PORT_EV_FCS; + } - return (event); + return event; } /******************************************************************************* @@ -409,32 +406,39 @@ uint32_t port_flow_control_user(tPORT* p_port) { * Returns event mask to be returned to the application * ******************************************************************************/ -uint32_t port_get_signal_changes(tPORT* p_port, uint8_t old_signals, - uint8_t signal) { +uint32_t port_get_signal_changes(tPORT* p_port, uint8_t old_signals, uint8_t signal) { uint8_t changed_signals = (signal ^ old_signals); uint32_t events = 0; if (changed_signals & PORT_DTRDSR_ON) { events |= PORT_EV_DSR; - if (signal & PORT_DTRDSR_ON) events |= PORT_EV_DSRS; + if (signal & PORT_DTRDSR_ON) { + events |= PORT_EV_DSRS; + } } if (changed_signals & PORT_CTSRTS_ON) { events |= PORT_EV_CTS; - if (signal & PORT_CTSRTS_ON) events |= PORT_EV_CTSS; + if (signal & PORT_CTSRTS_ON) { + events |= PORT_EV_CTSS; + } } - if (changed_signals & PORT_RING_ON) events |= PORT_EV_RING; + if (changed_signals & PORT_RING_ON) { + events |= PORT_EV_RING; + } if (changed_signals & PORT_DCD_ON) { events |= PORT_EV_RLSD; - if (signal & PORT_DCD_ON) events |= PORT_EV_RLSDS; + if (signal & PORT_DCD_ON) { + events |= PORT_EV_RLSDS; + } } - return (p_port->ev_mask & events); + return p_port->ev_mask & events; } /******************************************************************************* @@ -449,7 +453,9 @@ uint32_t port_get_signal_changes(tPORT* p_port, uint8_t old_signals, * ******************************************************************************/ void port_flow_control_peer(tPORT* p_port, bool enable, uint16_t count) { - if (!p_port->rfc.p_mcb) return; + if (!p_port->rfc.p_mcb) { + return; + } /* If using credit based flow control */ if (p_port->rfc.p_mcb->flow == PORT_FC_CREDIT) { @@ -498,8 +504,9 @@ void port_flow_control_peer(tPORT* p_port, bool enable, uint16_t count) { p_port->rx.peer_fc = false; /* If user did not force flow control allow traffic now */ - if (!p_port->rx.user_fc) + if (!p_port->rx.user_fc) { RFCOMM_FlowReq(p_port->rfc.p_mcb, p_port->dlci, true); + } } } /* else want to disable flow from peer */ diff --git a/system/stack/rfcomm/rfc_int.h b/system/stack/rfcomm/rfc_int.h index f223ccf6dd5..5be534ab450 100644 --- a/system/stack/rfcomm/rfc_int.h +++ b/system/stack/rfcomm/rfc_int.h @@ -39,14 +39,14 @@ /* * Define RFCOMM result codes -*/ + */ #define RFCOMM_SUCCESS 0 #define RFCOMM_ERROR 1 #define RFCOMM_SECURITY_ERR 112 /* * Define max and min RFCOMM MTU (N1) -*/ + */ #define RFCOMM_MIN_MTU 23 #define RFCOMM_MAX_MTU 32767 @@ -54,24 +54,20 @@ void RFCOMM_StartReq(tRFC_MCB* p_mcb); void RFCOMM_StartRsp(tRFC_MCB* p_mcb, uint16_t result); void RFCOMM_DlcEstablishReq(tRFC_MCB* p_mcb, uint8_t dlci, uint16_t mtu); -void RFCOMM_DlcEstablishRsp(tRFC_MCB* p_mcb, uint8_t dlci, uint16_t mtu, - uint16_t result); +void RFCOMM_DlcEstablishRsp(tRFC_MCB* p_mcb, uint8_t dlci, uint16_t mtu, uint16_t result); void RFCOMM_DataReq(tRFC_MCB* p_mcb, uint8_t dlci, BT_HDR* p_buf); void RFCOMM_DlcReleaseReq(tRFC_MCB* p_mcb, uint8_t dlci); -void RFCOMM_ParameterNegotiationRequest(tRFC_MCB* p_mcb, uint8_t dlci, - uint16_t mtu); -void RFCOMM_ParameterNegotiationResponse(tRFC_MCB* p_mcb, uint8_t dlci, - uint16_t mtu, uint8_t cl, uint8_t k); +void RFCOMM_ParameterNegotiationRequest(tRFC_MCB* p_mcb, uint8_t dlci, uint16_t mtu); +void RFCOMM_ParameterNegotiationResponse(tRFC_MCB* p_mcb, uint8_t dlci, uint16_t mtu, uint8_t cl, + uint8_t k); void RFCOMM_FlowReq(tRFC_MCB* p_mcb, uint8_t dlci, bool state); -void RFCOMM_PortParameterNegotiationRequest(tRFC_MCB* p_mcb, uint8_t dlci, - tPORT_STATE* p_pars); -void RFCOMM_PortParameterNegotiationResponse(tRFC_MCB* p_mcb, uint8_t dlci, - tPORT_STATE* p_pars, +void RFCOMM_PortParameterNegotiationRequest(tRFC_MCB* p_mcb, uint8_t dlci, tPORT_STATE* p_pars); +void RFCOMM_PortParameterNegotiationResponse(tRFC_MCB* p_mcb, uint8_t dlci, tPORT_STATE* p_pars, uint16_t param_mask); void RFCOMM_ControlReq(tRFC_MCB* p_mcb, uint8_t dlci, tPORT_CTRL* p_pars); @@ -80,7 +76,7 @@ void RFCOMM_ControlRsp(tRFC_MCB* p_mcb, uint8_t dlci, tPORT_CTRL* p_pars); void RFCOMM_LineStatusReq(tRFC_MCB* p_mcb, uint8_t dlci, uint8_t line_status); /* * Define logical struct used for sending and decoding MX frames -*/ + */ typedef struct { uint8_t dlci; uint8_t type; @@ -154,13 +150,13 @@ typedef struct { #define RFCOMM_CONN_TIMEOUT 120 /* Define RFComm control block -*/ + */ typedef struct { MX_FRAME rx_frame; tL2CAP_APPL_INFO reg_info; /* L2CAP Registration info */ - bool peer_rx_disabled; /* If true peer sent FCOFF */ - uint8_t last_mux; /* Last mux allocated */ + bool peer_rx_disabled; /* If true peer sent FCOFF */ + uint8_t last_mux; /* Last mux allocated */ uint8_t last_port_index; // Index of last port allocated in rfc_cb.port } tRFCOMM_CB; @@ -205,13 +201,12 @@ void rfc_mx_sm_execute(tRFC_MCB* p_mcb, tRFC_MX_EVENT event, void* p_data); /* * Functions provided by the rfc_port_fsm.cc -*/ + */ void rfc_port_sm_execute(tPORT* p_port, tRFC_PORT_EVENT event, void* p_data); void rfc_process_pn(tRFC_MCB* p_rfc_mcb, bool is_command, MX_FRAME* p_frame); void rfc_process_msc(tRFC_MCB* p_rfc_mcb, bool is_command, MX_FRAME* p_frame); -void rfc_process_rpn(tRFC_MCB* p_rfc_mcb, bool is_command, bool is_request, - MX_FRAME* p_frame); +void rfc_process_rpn(tRFC_MCB* p_rfc_mcb, bool is_command, bool is_request, MX_FRAME* p_frame); void rfc_process_rls(tRFC_MCB* p_rfc_mcb, bool is_command, MX_FRAME* p_frame); void rfc_process_nsc(tRFC_MCB* p_rfc_mcb, MX_FRAME* p_frame); void rfc_process_test_rsp(tRFC_MCB* p_rfc_mcb, BT_HDR* p_buf); @@ -223,9 +218,8 @@ void rfc_on_l2cap_error(uint16_t lcid, uint16_t result); /* * Functions provided by the rfc_utils.cc -*/ -tRFC_MCB* rfc_alloc_multiplexer_channel(const RawAddress& bd_addr, - bool is_initiator); + */ +tRFC_MCB* rfc_alloc_multiplexer_channel(const RawAddress& bd_addr, bool is_initiator); void rfc_release_multiplexer_channel(tRFC_MCB* p_rfc_mcb); void rfc_timer_start(tRFC_MCB* p_rfc_mcb, uint16_t timeout); void rfc_timer_stop(tRFC_MCB* p_rfc_mcb); @@ -237,35 +231,32 @@ tRFC_MCB* rfc_find_lcid_mcb(uint16_t lcid); void rfc_save_lcid_mcb(tRFC_MCB* p_rfc_mcb, uint16_t lcid); void rfc_check_mcb_active(tRFC_MCB* p_mcb); void rfc_port_closed(tPORT* p_port); -void rfc_sec_check_complete(RawAddress bd_addr, tBT_TRANSPORT transport, - void* p_ref_data, tBTM_STATUS res); +void rfc_sec_check_complete(RawAddress bd_addr, tBT_TRANSPORT transport, void* p_ref_data, + tBTM_STATUS res); void rfc_inc_credit(tPORT* p_port, uint8_t credit); void rfc_dec_credit(tPORT* p_port); void rfc_check_send_cmd(tRFC_MCB* p_mcb, BT_HDR* p_buf); /* * Functions provided by the rfc_ts_frames.cc -*/ + */ void rfc_send_sabme(tRFC_MCB* p_rfc_mcb, uint8_t dlci); void rfc_send_ua(tRFC_MCB* p_rfc_mcb, uint8_t dlci); void rfc_send_dm(tRFC_MCB* p_rfc_mcb, uint8_t dlci, bool pf); void rfc_send_disc(tRFC_MCB* p_rfc_mcb, uint8_t dlci); -void rfc_send_pn(tRFC_MCB* p_mcb, uint8_t dlci, bool is_command, uint16_t mtu, - uint8_t cl, uint8_t k); +void rfc_send_pn(tRFC_MCB* p_mcb, uint8_t dlci, bool is_command, uint16_t mtu, uint8_t cl, + uint8_t k); void rfc_send_test(tRFC_MCB* p_rfc_mcb, bool is_command, BT_HDR* p_buf); -void rfc_send_msc(tRFC_MCB* p_mcb, uint8_t dlci, bool is_command, - tPORT_CTRL* p_pars); -void rfc_send_rls(tRFC_MCB* p_mcb, uint8_t dlci, bool is_command, - uint8_t status); -void rfc_send_rpn(tRFC_MCB* p_mcb, uint8_t dlci, bool is_command, - tPORT_STATE* p_pars, uint16_t mask); +void rfc_send_msc(tRFC_MCB* p_mcb, uint8_t dlci, bool is_command, tPORT_CTRL* p_pars); +void rfc_send_rls(tRFC_MCB* p_mcb, uint8_t dlci, bool is_command, uint8_t status); +void rfc_send_rpn(tRFC_MCB* p_mcb, uint8_t dlci, bool is_command, tPORT_STATE* p_pars, + uint16_t mask); void rfc_send_fcon(tRFC_MCB* p_mcb, bool is_command); void rfc_send_fcoff(tRFC_MCB* p_mcb, bool is_command); void rfc_send_buf_uih(tRFC_MCB* p_rfc_mcb, uint8_t dlci, BT_HDR* p_buf); void rfc_send_credit(tRFC_MCB* p_mcb, uint8_t dlci, uint8_t credit); void rfc_process_mx_message(tRFC_MCB* p_rfc_mcb, BT_HDR* p_buf); -tRFC_EVENT rfc_parse_data(tRFC_MCB* p_rfc_mcb, MX_FRAME* p_frame, - BT_HDR* p_buf); +tRFC_EVENT rfc_parse_data(tRFC_MCB* p_rfc_mcb, MX_FRAME* p_frame, BT_HDR* p_buf); /* Call back functions from RFCOMM */ void rfcomm_l2cap_if_init(void); @@ -277,24 +268,19 @@ void PORT_CloseInd(tRFC_MCB* p_mcb); void PORT_TimeOutCloseMux(tRFC_MCB* p_mcb); void PORT_DlcEstablishInd(tRFC_MCB* p_mcb, uint8_t dlci, uint16_t mtu); -void PORT_DlcEstablishCnf(tRFC_MCB* p_mcb, uint8_t dlci, uint16_t mtu, - uint16_t result); +void PORT_DlcEstablishCnf(tRFC_MCB* p_mcb, uint8_t dlci, uint16_t mtu, uint16_t result); void PORT_DataInd(tRFC_MCB* p_mcb, uint8_t dlci, BT_HDR* p_buf); void PORT_DlcReleaseInd(tRFC_MCB* p_mcb, uint8_t dlci); -void PORT_ParNegInd(tRFC_MCB* p_mcb, uint8_t dlci, uint16_t mtu, uint8_t cl, - uint8_t k); -void PORT_ParNegCnf(tRFC_MCB* p_mcb, uint8_t dlci, uint16_t mtu, uint8_t cl, - uint8_t k); +void PORT_ParNegInd(tRFC_MCB* p_mcb, uint8_t dlci, uint16_t mtu, uint8_t cl, uint8_t k); +void PORT_ParNegCnf(tRFC_MCB* p_mcb, uint8_t dlci, uint16_t mtu, uint8_t cl, uint8_t k); void PORT_FlowInd(tRFC_MCB* p_mcb, uint8_t dlci, bool fc); -void PORT_PortNegInd(tRFC_MCB* p_mcb, uint8_t dlci, tPORT_STATE* p_pars, - uint16_t param_mask); -void PORT_PortNegCnf(tRFC_MCB* p_mcb, uint8_t dlci, tPORT_STATE* p_pars, - uint16_t result); +void PORT_PortNegInd(tRFC_MCB* p_mcb, uint8_t dlci, tPORT_STATE* p_pars, uint16_t param_mask); +void PORT_PortNegCnf(tRFC_MCB* p_mcb, uint8_t dlci, tPORT_STATE* p_pars, uint16_t result); void PORT_ControlInd(tRFC_MCB* p_mcb, uint8_t dlci, tPORT_CTRL* p_pars); void PORT_ControlCnf(tRFC_MCB* p_mcb, uint8_t dlci, tPORT_CTRL* p_pars); diff --git a/system/stack/rfcomm/rfc_l2cap_if.cc b/system/stack/rfcomm/rfc_l2cap_if.cc index 4a944fbd76a..2527abec750 100644 --- a/system/stack/rfcomm/rfc_l2cap_if.cc +++ b/system/stack/rfcomm/rfc_l2cap_if.cc @@ -42,13 +42,11 @@ using namespace bluetooth; /* * Define Callback functions to be called by L2CAP -*/ -static void RFCOMM_ConnectInd(const RawAddress& bd_addr, uint16_t lcid, - uint16_t psm, uint8_t id); + */ +static void RFCOMM_ConnectInd(const RawAddress& bd_addr, uint16_t lcid, uint16_t psm, uint8_t id); static void RFCOMM_ConnectCnf(uint16_t lcid, uint16_t err); static void RFCOMM_ConfigInd(uint16_t lcid, tL2CAP_CFG_INFO* p_cfg); -static void RFCOMM_ConfigCnf(uint16_t lcid, uint16_t result, - tL2CAP_CFG_INFO* p_cfg); +static void RFCOMM_ConfigCnf(uint16_t lcid, uint16_t result, tL2CAP_CFG_INFO* p_cfg); static void RFCOMM_DisconnectInd(uint16_t lcid, bool is_clear); static void RFCOMM_BufDataInd(uint16_t lcid, BT_HDR* p_buf); static void RFCOMM_CongestionStatusInd(uint16_t lcid, bool is_congested); @@ -74,10 +72,9 @@ void rfcomm_l2cap_if_init(void) { p_l2c->pL2CA_TxComplete_Cb = NULL; p_l2c->pL2CA_Error_Cb = rfc_on_l2cap_error; - if (!L2CA_Register(BT_PSM_RFCOMM, rfc_cb.rfc.reg_info, - true /* enable_snoop */, nullptr, L2CAP_MTU_SIZE, 0, 0)) { - log::error("Unable to register with L2CAP profile RFCOMM psm:{}", - BT_PSM_RFCOMM); + if (!L2CA_Register(BT_PSM_RFCOMM, rfc_cb.rfc.reg_info, true /* enable_snoop */, nullptr, + L2CAP_MTU_SIZE, 0, 0)) { + log::error("Unable to register with L2CAP profile RFCOMM psm:{}", BT_PSM_RFCOMM); } } @@ -90,8 +87,7 @@ void rfcomm_l2cap_if_init(void) { * block and dispatch the event to it. * ******************************************************************************/ -void RFCOMM_ConnectInd(const RawAddress& bd_addr, uint16_t lcid, - uint16_t /* psm */, uint8_t id) { +void RFCOMM_ConnectInd(const RawAddress& bd_addr, uint16_t lcid, uint16_t /* psm */, uint8_t id) { tRFC_MCB* p_mcb = rfc_alloc_multiplexer_channel(bd_addr, false); if ((p_mcb) && (p_mcb->state != RFC_MX_STATE_IDLE)) { @@ -105,13 +101,11 @@ void RFCOMM_ConnectInd(const RawAddress& bd_addr, uint16_t lcid, /* if timeout, local device disconnects outgoing connection and continues * as acceptor */ log::verbose( - "RFCOMM_ConnectInd start timer for collision, initiator's " - "LCID(0x{:x}), acceptor's LCID(0x{:x})", - p_mcb->lcid, p_mcb->pending_lcid); + "RFCOMM_ConnectInd start timer for collision, initiator's " + "LCID(0x{:x}), acceptor's LCID(0x{:x})", + p_mcb->lcid, p_mcb->pending_lcid); - rfc_timer_start( - p_mcb, - (uint16_t)(bluetooth::common::time_get_os_boottime_ms() % 10 + 2)); + rfc_timer_start(p_mcb, (uint16_t)(bluetooth::common::time_get_os_boottime_ms() % 10 + 2)); return; } else { /* we cannot accept connection request from peer at this state */ @@ -157,14 +151,13 @@ void RFCOMM_ConnectCnf(uint16_t lcid, uint16_t result) { if (result != L2CAP_CONN_OK) { return; } else { - log::verbose("RFCOMM_ConnectCnf peer gave up pending LCID(0x{:x})", - p_mcb->pending_lcid); + log::verbose("RFCOMM_ConnectCnf peer gave up pending LCID(0x{:x})", p_mcb->pending_lcid); /* Peer gave up its connection request, make sure cleaning up L2CAP * channel */ if (!L2CA_DisconnectReq(p_mcb->pending_lcid)) { - log::warn("Unable to send L2CAP disconnect request peer:{} cid:{}", - p_mcb->bd_addr, p_mcb->lcid); + log::warn("Unable to send L2CAP disconnect request peer:{} cid:{}", p_mcb->bd_addr, + p_mcb->lcid); } p_mcb->pending_lcid = 0; @@ -219,8 +212,7 @@ void RFCOMM_ConfigInd(uint16_t lcid, tL2CAP_CFG_INFO* p_cfg) { * event to the FSM. * ******************************************************************************/ -void RFCOMM_ConfigCnf(uint16_t lcid, uint16_t /* initiator */, - tL2CAP_CFG_INFO* p_cfg) { +void RFCOMM_ConfigCnf(uint16_t lcid, uint16_t /* initiator */, tL2CAP_CFG_INFO* p_cfg) { RFCOMM_ConfigInd(lcid, p_cfg); tRFC_MCB* p_mcb = rfc_find_lcid_mcb(lcid); @@ -274,15 +266,14 @@ void RFCOMM_BufDataInd(uint16_t lcid, BT_HDR* p_buf) { /* If the frame did not pass validation just ignore it */ if (event == RFC_EVENT_BAD_FRAME) { - log::warn("Bad RFCOMM frame from lcid=0x{:x}, bd_addr={}, p_mcb={}", lcid, - p_mcb->bd_addr, fmt::ptr(p_mcb)); + log::warn("Bad RFCOMM frame from lcid=0x{:x}, bd_addr={}, p_mcb={}", lcid, p_mcb->bd_addr, + fmt::ptr(p_mcb)); osi_free(p_buf); return; } if (rfc_cb.rfc.rx_frame.dlci == RFCOMM_MX_DLCI) { - log::verbose("handle multiplexer event {}, p_mcb={}", event, - fmt::ptr(p_mcb)); + log::verbose("handle multiplexer event {}, p_mcb={}", event, fmt::ptr(p_mcb)); /* Take special care of the Multiplexer Control Messages */ if (event == RFC_EVENT_UIH) { rfc_process_mx_message(p_mcb, p_buf); @@ -300,12 +291,12 @@ void RFCOMM_BufDataInd(uint16_t lcid, BT_HDR* p_buf) { if (p_port == nullptr || !p_port->rfc.p_mcb) { /* If this is a SABME on new port, check if any app is waiting for it */ if (event != RFC_EVENT_SABME) { - log::warn("no for none-SABME event, lcid=0x{:x}, bd_addr={}, p_mcb={}", - lcid, p_mcb->bd_addr, fmt::ptr(p_mcb)); + log::warn("no for none-SABME event, lcid=0x{:x}, bd_addr={}, p_mcb={}", lcid, p_mcb->bd_addr, + fmt::ptr(p_mcb)); if ((p_mcb->is_initiator && !rfc_cb.rfc.rx_frame.cr) || (!p_mcb->is_initiator && rfc_cb.rfc.rx_frame.cr)) { - log::error("Disconnecting RFCOMM, lcid=0x{:x}, bd_addr={}, p_mcb={}", - lcid, p_mcb->bd_addr, fmt::ptr(p_mcb)); + log::error("Disconnecting RFCOMM, lcid=0x{:x}, bd_addr={}, p_mcb={}", lcid, p_mcb->bd_addr, + fmt::ptr(p_mcb)); rfc_send_dm(p_mcb, rfc_cb.rfc.rx_frame.dlci, rfc_cb.rfc.rx_frame.pf); } osi_free(p_buf); @@ -315,17 +306,15 @@ void RFCOMM_BufDataInd(uint16_t lcid, BT_HDR* p_buf) { p_port = port_find_dlci_port(rfc_cb.rfc.rx_frame.dlci); if (p_port == nullptr) { log::error( - "Disconnecting RFCOMM, no port for dlci {}, lcid=0x{:x}, bd_addr={}, " - "p_mcb={}", - rfc_cb.rfc.rx_frame.dlci, lcid, p_mcb->bd_addr, fmt::ptr(p_mcb)); + "Disconnecting RFCOMM, no port for dlci {}, lcid=0x{:x}, bd_addr={}, " + "p_mcb={}", + rfc_cb.rfc.rx_frame.dlci, lcid, p_mcb->bd_addr, fmt::ptr(p_mcb)); rfc_send_dm(p_mcb, rfc_cb.rfc.rx_frame.dlci, true); osi_free(p_buf); return; } - log::verbose("port_handles[dlci={}]:{}->{}, p_mcb={}", - rfc_cb.rfc.rx_frame.dlci, - p_mcb->port_handles[rfc_cb.rfc.rx_frame.dlci], p_port->handle, - fmt::ptr(p_mcb)); + log::verbose("port_handles[dlci={}]:{}->{}, p_mcb={}", rfc_cb.rfc.rx_frame.dlci, + p_mcb->port_handles[rfc_cb.rfc.rx_frame.dlci], p_port->handle, fmt::ptr(p_mcb)); p_mcb->port_handles[rfc_cb.rfc.rx_frame.dlci] = p_port->handle; p_port->rfc.p_mcb = p_mcb; } @@ -380,8 +369,7 @@ tRFC_MCB* rfc_find_lcid_mcb(uint16_t lcid) { tRFC_MCB* p_mcb = rfc_lcid_mcb[lcid]; if (p_mcb != nullptr) { if (p_mcb->lcid != lcid) { - log::warn("LCID reused lcid=:0x{:x}, current_lcid=0x{:x}", lcid, - p_mcb->lcid); + log::warn("LCID reused lcid=:0x{:x}, current_lcid=0x{:x}", lcid, p_mcb->lcid); return nullptr; } } diff --git a/system/stack/rfcomm/rfc_mx_fsm.cc b/system/stack/rfcomm/rfc_mx_fsm.cc index 71ae56f9ac7..17e82ef0917 100644 --- a/system/stack/rfcomm/rfc_mx_fsm.cc +++ b/system/stack/rfcomm/rfc_mx_fsm.cc @@ -43,20 +43,13 @@ using namespace bluetooth; /******************************************************************************/ /* L O C A L F U N C T I O N P R O T O T Y P E S */ /******************************************************************************/ -static void rfc_mx_sm_state_idle(tRFC_MCB* p_mcb, tRFC_MX_EVENT event, - void* p_data); -static void rfc_mx_sm_state_wait_conn_cnf(tRFC_MCB* p_mcb, tRFC_MX_EVENT event, - void* p_data); -static void rfc_mx_sm_state_configure(tRFC_MCB* p_mcb, tRFC_MX_EVENT event, - void* p_data); -static void rfc_mx_sm_sabme_wait_ua(tRFC_MCB* p_mcb, tRFC_MX_EVENT event, - void* p_data); -static void rfc_mx_sm_state_wait_sabme(tRFC_MCB* p_mcb, tRFC_MX_EVENT event, - void* p_data); -static void rfc_mx_sm_state_connected(tRFC_MCB* p_mcb, tRFC_MX_EVENT event, - void* p_data); -static void rfc_mx_sm_state_disc_wait_ua(tRFC_MCB* p_mcb, tRFC_MX_EVENT event, - void* p_data); +static void rfc_mx_sm_state_idle(tRFC_MCB* p_mcb, tRFC_MX_EVENT event, void* p_data); +static void rfc_mx_sm_state_wait_conn_cnf(tRFC_MCB* p_mcb, tRFC_MX_EVENT event, void* p_data); +static void rfc_mx_sm_state_configure(tRFC_MCB* p_mcb, tRFC_MX_EVENT event, void* p_data); +static void rfc_mx_sm_sabme_wait_ua(tRFC_MCB* p_mcb, tRFC_MX_EVENT event, void* p_data); +static void rfc_mx_sm_state_wait_sabme(tRFC_MCB* p_mcb, tRFC_MX_EVENT event, void* p_data); +static void rfc_mx_sm_state_connected(tRFC_MCB* p_mcb, tRFC_MX_EVENT event, void* p_data); +static void rfc_mx_sm_state_disc_wait_ua(tRFC_MCB* p_mcb, tRFC_MX_EVENT event, void* p_data); static void rfc_mx_conf_ind(tRFC_MCB* p_mcb, tL2CAP_CFG_INFO* p_cfg); static void rfc_mx_conf_cnf(tRFC_MCB* p_mcb, uint16_t result); @@ -107,8 +100,7 @@ void rfc_mx_sm_execute(tRFC_MCB* p_mcb, tRFC_MX_EVENT event, void* p_data) { break; default: - log::error("Received unexpected event:{} in state:{}", event, - p_mcb->state); + log::error("Received unexpected event:{} in state:{}", event, p_mcb->state); } } @@ -123,8 +115,7 @@ void rfc_mx_sm_execute(tRFC_MCB* p_mcb, tRFC_MX_EVENT event, void* p_data) { * Returns void * ******************************************************************************/ -void rfc_mx_sm_state_idle(tRFC_MCB* p_mcb, tRFC_MX_EVENT event, - void* /* p_data */) { +void rfc_mx_sm_state_idle(tRFC_MCB* p_mcb, tRFC_MX_EVENT event, void* /* p_data */) { switch (event) { case RFC_MX_EVENT_START_REQ: { /* Initialize L2CAP MTU */ @@ -185,8 +176,7 @@ void rfc_mx_sm_state_idle(tRFC_MCB* p_mcb, tRFC_MX_EVENT event, * Returns void * ******************************************************************************/ -void rfc_mx_sm_state_wait_conn_cnf(tRFC_MCB* p_mcb, tRFC_MX_EVENT event, - void* p_data) { +void rfc_mx_sm_state_wait_conn_cnf(tRFC_MCB* p_mcb, tRFC_MX_EVENT event, void* p_data) { log::verbose("evt {}", event); switch (event) { case RFC_MX_EVENT_START_REQ: @@ -218,8 +208,8 @@ void rfc_mx_sm_state_wait_conn_cnf(tRFC_MCB* p_mcb, tRFC_MX_EVENT event, case RFC_MX_EVENT_TIMEOUT: p_mcb->state = RFC_MX_STATE_IDLE; if (!L2CA_DisconnectReq(p_mcb->lcid)) { - log::warn("Unable to send L2CAP disonnect request peer:{} cid:{}", - p_mcb->bd_addr, p_mcb->lcid); + log::warn("Unable to send L2CAP disconnect request peer:{} cid:{}", p_mcb->bd_addr, + p_mcb->lcid); }; /* we gave up outgoing connection request then try peer's request */ @@ -227,10 +217,8 @@ void rfc_mx_sm_state_wait_conn_cnf(tRFC_MCB* p_mcb, tRFC_MX_EVENT event, uint16_t i; uint8_t handle; - log::verbose( - "RFCOMM MX retry as acceptor in collision case - evt:{} in " - "state:{}", - event, p_mcb->state); + log::verbose("RFCOMM MX retry as acceptor in collision case - evt:{} in state:{}", event, + p_mcb->state); rfc_save_lcid_mcb(NULL, p_mcb->lcid); p_mcb->lcid = p_mcb->pending_lcid; @@ -245,8 +233,7 @@ void rfc_mx_sm_state_wait_conn_cnf(tRFC_MCB* p_mcb, tRFC_MX_EVENT event, p_mcb->port_handles[i] = 0; p_mcb->port_handles[i + 1] = handle; rfc_cb.port.port[handle - 1].dlci += 1; - log::verbose("RFCOMM MX - DLCI:{} -> {}", i, - rfc_cb.port.port[handle - 1].dlci); + log::verbose("RFCOMM MX - DLCI:{} -> {}", i, rfc_cb.port.port[handle - 1].dlci); } } @@ -256,8 +243,7 @@ void rfc_mx_sm_state_wait_conn_cnf(tRFC_MCB* p_mcb, tRFC_MX_EVENT event, } return; default: - log::error("Received unexpected event:{} in state:{}", event, - p_mcb->state); + log::error("Received unexpected event:{} in state:{}", event, p_mcb->state); } log::verbose("RFCOMM MX ignored - evt:{} in state:{}", event, p_mcb->state); } @@ -272,8 +258,7 @@ void rfc_mx_sm_state_wait_conn_cnf(tRFC_MCB* p_mcb, tRFC_MX_EVENT event, * Returns void * ******************************************************************************/ -void rfc_mx_sm_state_configure(tRFC_MCB* p_mcb, tRFC_MX_EVENT event, - void* p_data) { +void rfc_mx_sm_state_configure(tRFC_MCB* p_mcb, tRFC_MX_EVENT event, void* p_data) { log::verbose("event {}", event); switch (event) { case RFC_MX_EVENT_START_REQ: @@ -299,15 +284,14 @@ void rfc_mx_sm_state_configure(tRFC_MCB* p_mcb, tRFC_MX_EVENT event, log::error("L2CAP configuration timeout for {}", p_mcb->bd_addr); p_mcb->state = RFC_MX_STATE_IDLE; if (!L2CA_DisconnectReq(p_mcb->lcid)) { - log::warn("Unable to send L2CAP disonnect request peer:{} cid:{}", - p_mcb->bd_addr, p_mcb->lcid); + log::warn("Unable to send L2CAP disconnect request peer:{} cid:{}", p_mcb->bd_addr, + p_mcb->lcid); }; PORT_StartCnf(p_mcb, RFCOMM_ERROR); return; default: - log::error("Received unexpected event:{} in state:{}", event, - p_mcb->state); + log::error("Received unexpected event:{} in state:{}", event, p_mcb->state); } log::verbose("RFCOMM MX ignored - evt:{} in state:{}", event, p_mcb->state); } @@ -322,8 +306,7 @@ void rfc_mx_sm_state_configure(tRFC_MCB* p_mcb, tRFC_MX_EVENT event, * Returns void * ******************************************************************************/ -void rfc_mx_sm_sabme_wait_ua(tRFC_MCB* p_mcb, tRFC_MX_EVENT event, - void* /* p_data */) { +void rfc_mx_sm_sabme_wait_ua(tRFC_MCB* p_mcb, tRFC_MX_EVENT event, void* /* p_data */) { log::verbose("event {}", event); switch (event) { case RFC_MX_EVENT_START_REQ: @@ -331,16 +314,16 @@ void rfc_mx_sm_sabme_wait_ua(tRFC_MCB* p_mcb, tRFC_MX_EVENT event, log::error("Mx error state {} event {}", p_mcb->state, event); return; - /* workaround: we don't support reconfig */ - /* commented out until we support reconfig - case RFC_MX_EVENT_CONF_IND: - rfc_mx_conf_ind (p_mcb, (tL2CAP_CFG_INFO *)p_data); - return; + /* workaround: we don't support reconfig */ + /* commented out until we support reconfig + case RFC_MX_EVENT_CONF_IND: + rfc_mx_conf_ind (p_mcb, (tL2CAP_CFG_INFO *)p_data); + return; - case RFC_MX_EVENT_CONF_CNF: - rfc_mx_conf_cnf (p_mcb, (tL2CAP_CFG_INFO *)p_data); - return; - */ + case RFC_MX_EVENT_CONF_CNF: + rfc_mx_conf_cnf (p_mcb, (tL2CAP_CFG_INFO *)p_data); + return; + */ case RFC_MX_EVENT_DISC_IND: p_mcb->state = RFC_MX_STATE_IDLE; @@ -365,15 +348,14 @@ void rfc_mx_sm_sabme_wait_ua(tRFC_MCB* p_mcb, tRFC_MX_EVENT event, case RFC_MX_EVENT_TIMEOUT: p_mcb->state = RFC_MX_STATE_IDLE; if (!L2CA_DisconnectReq(p_mcb->lcid)) { - log::warn("Unable to send L2CAP disonnect request peer:{} cid:{}", - p_mcb->bd_addr, p_mcb->lcid); + log::warn("Unable to send L2CAP disconnect request peer:{} cid:{}", p_mcb->bd_addr, + p_mcb->lcid); }; PORT_StartCnf(p_mcb, RFCOMM_ERROR); return; default: - log::error("Received unexpected event:{} in state:{}", event, - p_mcb->state); + log::error("Received unexpected event:{} in state:{}", event, p_mcb->state); } log::verbose("RFCOMM MX ignored - evt:{} in state:{}", event, p_mcb->state); } @@ -388,8 +370,7 @@ void rfc_mx_sm_sabme_wait_ua(tRFC_MCB* p_mcb, tRFC_MX_EVENT event, * Returns void * ******************************************************************************/ -void rfc_mx_sm_state_wait_sabme(tRFC_MCB* p_mcb, tRFC_MX_EVENT event, - void* p_data) { +void rfc_mx_sm_state_wait_sabme(tRFC_MCB* p_mcb, tRFC_MX_EVENT event, void* p_data) { log::verbose("event {}", event); switch (event) { case RFC_MX_EVENT_DISC_IND: @@ -417,9 +398,9 @@ void rfc_mx_sm_state_wait_sabme(tRFC_MCB* p_mcb, tRFC_MX_EVENT event, return; case RFC_MX_EVENT_START_RSP: - if (*((uint16_t*)p_data) != RFCOMM_SUCCESS) + if (*((uint16_t*)p_data) != RFCOMM_SUCCESS) { rfc_send_dm(p_mcb, RFCOMM_MX_DLCI, true); - else { + } else { rfc_send_ua(p_mcb, RFCOMM_MX_DLCI); p_mcb->state = RFC_MX_STATE_CONNECTED; @@ -433,8 +414,8 @@ void rfc_mx_sm_state_wait_sabme(tRFC_MCB* p_mcb, tRFC_MX_EVENT event, case RFC_MX_EVENT_TIMEOUT: p_mcb->state = RFC_MX_STATE_IDLE; if (!L2CA_DisconnectReq(p_mcb->lcid)) { - log::warn("Unable to send L2CAP disonnect request peer:{} cid:{}", - p_mcb->bd_addr, p_mcb->lcid); + log::warn("Unable to send L2CAP disconnect request peer:{} cid:{}", p_mcb->bd_addr, + p_mcb->lcid); }; PORT_CloseInd(p_mcb); @@ -456,8 +437,7 @@ void rfc_mx_sm_state_wait_sabme(tRFC_MCB* p_mcb, tRFC_MX_EVENT event, * Returns void * ******************************************************************************/ -void rfc_mx_sm_state_connected(tRFC_MCB* p_mcb, tRFC_MX_EVENT event, - void* /* p_data */) { +void rfc_mx_sm_state_connected(tRFC_MCB* p_mcb, tRFC_MX_EVENT event, void* /* p_data */) { log::verbose("event {}", event); switch (event) { @@ -479,16 +459,15 @@ void rfc_mx_sm_state_connected(tRFC_MCB* p_mcb, tRFC_MX_EVENT event, rfc_send_ua(p_mcb, RFCOMM_MX_DLCI); if (p_mcb->is_initiator) { if (!L2CA_DisconnectReq(p_mcb->lcid)) { - log::warn("Unable to send L2CAP disonnect request peer:{} cid:{}", - p_mcb->bd_addr, p_mcb->lcid); + log::warn("Unable to send L2CAP disconnect request peer:{} cid:{}", p_mcb->bd_addr, + p_mcb->lcid); }; } /* notify all ports that connection is gone */ PORT_CloseInd(p_mcb); return; default: - log::error("Received unexpected event:{} in state:{}", event, - p_mcb->state); + log::error("Received unexpected event:{} in state:{}", event, p_mcb->state); } log::verbose("RFCOMM MX ignored - evt:{} in state:{}", event, p_mcb->state); } @@ -503,8 +482,7 @@ void rfc_mx_sm_state_connected(tRFC_MCB* p_mcb, tRFC_MX_EVENT event, * Returns void * ******************************************************************************/ -void rfc_mx_sm_state_disc_wait_ua(tRFC_MCB* p_mcb, tRFC_MX_EVENT event, - void* p_data) { +void rfc_mx_sm_state_disc_wait_ua(tRFC_MCB* p_mcb, tRFC_MX_EVENT event, void* p_data) { BT_HDR* p_buf; log::verbose("event {}", event); @@ -513,8 +491,8 @@ void rfc_mx_sm_state_disc_wait_ua(tRFC_MCB* p_mcb, tRFC_MX_EVENT event, case RFC_MX_EVENT_DM: case RFC_MX_EVENT_TIMEOUT: if (!L2CA_DisconnectReq(p_mcb->lcid)) { - log::warn("Unable to send L2CAP disonnect request peer:{} cid:{}", - p_mcb->bd_addr, p_mcb->lcid); + log::warn("Unable to send L2CAP disconnect request peer:{} cid:{}", p_mcb->bd_addr, + p_mcb->lcid); }; if (p_mcb->restart_required) { @@ -531,8 +509,9 @@ void rfc_mx_sm_state_disc_wait_ua(tRFC_MCB* p_mcb, tRFC_MX_EVENT event, rfc_save_lcid_mcb(p_mcb, p_mcb->lcid); /* clean up before reuse it */ - while ((p_buf = (BT_HDR*)fixed_queue_try_dequeue(p_mcb->cmd_q)) != NULL) + while ((p_buf = (BT_HDR*)fixed_queue_try_dequeue(p_mcb->cmd_q)) != NULL) { osi_free(p_buf); + } rfc_timer_start(p_mcb, RFC_MCB_INIT_INACT_TIMER); @@ -569,23 +548,23 @@ void rfc_mx_sm_state_disc_wait_ua(tRFC_MCB* p_mcb, tRFC_MX_EVENT event, case RFC_MX_EVENT_QOS_VIOLATION_IND: break; default: - log::error("Received unexpected event:{} in state:{}", event, - p_mcb->state); + log::error("Received unexpected event:{} in state:{}", event, p_mcb->state); } log::verbose("RFCOMM MX ignored - evt:{} in state:{}", event, p_mcb->state); } void rfc_on_l2cap_error(uint16_t lcid, uint16_t result) { tRFC_MCB* p_mcb = rfc_find_lcid_mcb(lcid); - if (p_mcb == nullptr) return; + if (p_mcb == nullptr) { + return; + } if (result & L2CAP_CONN_INTERNAL_MASK) { /* if peer rejects our connect request but peer's connect request is pending */ if (p_mcb->pending_lcid) { - log::verbose( - "RFCOMM_ConnectCnf retry as acceptor on pending LCID(0x{:x})", - p_mcb->pending_lcid); + log::verbose("RFCOMM_ConnectCnf retry as acceptor on pending LCID(0x{:x})", + p_mcb->pending_lcid); /* remove mcb from mapping table */ rfc_save_lcid_mcb(NULL, p_mcb->lcid); @@ -613,8 +592,7 @@ void rfc_on_l2cap_error(uint16_t lcid, uint16_t result) { log::info("Configuration of the pending connection was completed"); p_mcb->pending_configure_complete = false; uintptr_t result_as_ptr = L2CAP_CFG_OK; - rfc_mx_sm_execute(p_mcb, RFC_MX_EVENT_CONF_IND, - &p_mcb->pending_cfg_info); + rfc_mx_sm_execute(p_mcb, RFC_MX_EVENT_CONF_IND, &p_mcb->pending_cfg_info); rfc_mx_sm_execute(p_mcb, RFC_MX_EVENT_CONF_CNF, (void*)result_as_ptr); } return; @@ -625,12 +603,11 @@ void rfc_on_l2cap_error(uint16_t lcid, uint16_t result) { } else if (result == L2CAP_CFG_FAILED_NO_REASON) { log::error("failed to configure L2CAP for {}", p_mcb->bd_addr); if (p_mcb->is_initiator) { - log::error("disconnect L2CAP due to config failure for {}", - p_mcb->bd_addr); + log::error("disconnect L2CAP due to config failure for {}", p_mcb->bd_addr); PORT_StartCnf(p_mcb, result); if (!L2CA_DisconnectReq(p_mcb->lcid)) { - log::warn("Unable to send L2CAP disonnect request peer:{} cid:{}", - p_mcb->bd_addr, p_mcb->lcid); + log::warn("Unable to send L2CAP disconnect request peer:{} cid:{}", p_mcb->bd_addr, + p_mcb->lcid); }; } rfc_release_multiplexer_channel(p_mcb); @@ -655,10 +632,9 @@ static void rfc_mx_conf_cnf(tRFC_MCB* p_mcb, uint16_t /* result */) { rfc_timer_start(p_mcb, RFC_T1_TIMEOUT); } else { p_mcb->state = RFC_MX_STATE_WAIT_SABME; - rfc_timer_start( - p_mcb, RFCOMM_CONN_TIMEOUT); /* - increased from T2=20 to CONN=120 - to allow the user more than 10 sec to type in the - pin which can be e.g. 16 digits */ + rfc_timer_start(p_mcb, RFCOMM_CONN_TIMEOUT); /* - increased from T2=20 to CONN=120 + to allow the user more than 10 sec to type in the + pin which can be e.g. 16 digits */ } } } diff --git a/system/stack/rfcomm/rfc_port_fsm.cc b/system/stack/rfcomm/rfc_port_fsm.cc index 324f3d4f556..191b815407a 100644 --- a/system/stack/rfcomm/rfc_port_fsm.cc +++ b/system/stack/rfcomm/rfc_port_fsm.cc @@ -43,27 +43,19 @@ using namespace bluetooth; static const std::set uuid_logging_acceptlist = { - UUID_SERVCLASS_HEADSET_AUDIO_GATEWAY, - UUID_SERVCLASS_AG_HANDSFREE, + UUID_SERVCLASS_HEADSET_AUDIO_GATEWAY, + UUID_SERVCLASS_AG_HANDSFREE, }; /******************************************************************************/ /* L O C A L F U N C T I O N P R O T O T Y P E S */ /******************************************************************************/ -static void rfc_port_sm_state_closed(tPORT* p_port, tRFC_PORT_EVENT event, - void* p_data); -static void rfc_port_sm_sabme_wait_ua(tPORT* p_port, tRFC_PORT_EVENT event, - void* p_data); -static void rfc_port_sm_opened(tPORT* p_port, tRFC_PORT_EVENT event, - void* p_data); -static void rfc_port_sm_orig_wait_sec_check(tPORT* p_port, - tRFC_PORT_EVENT event, - void* p_data); -static void rfc_port_sm_term_wait_sec_check(tPORT* p_port, - tRFC_PORT_EVENT event, - void* p_data); -static void rfc_port_sm_disc_wait_ua(tPORT* p_port, tRFC_PORT_EVENT event, - void* p_data); +static void rfc_port_sm_state_closed(tPORT* p_port, tRFC_PORT_EVENT event, void* p_data); +static void rfc_port_sm_sabme_wait_ua(tPORT* p_port, tRFC_PORT_EVENT event, void* p_data); +static void rfc_port_sm_opened(tPORT* p_port, tRFC_PORT_EVENT event, void* p_data); +static void rfc_port_sm_orig_wait_sec_check(tPORT* p_port, tRFC_PORT_EVENT event, void* p_data); +static void rfc_port_sm_term_wait_sec_check(tPORT* p_port, tRFC_PORT_EVENT event, void* p_data); +static void rfc_port_sm_disc_wait_ua(tPORT* p_port, tRFC_PORT_EVENT event, void* p_data); static void rfc_port_uplink_data(tPORT* p_port, BT_HDR* p_buf); @@ -84,8 +76,8 @@ void rfc_port_sm_execute(tPORT* p_port, tRFC_PORT_EVENT event, void* p_data) { // logs for state RFC_STATE_OPENED handled in rfc_port_sm_opened() if (p_port->rfc.state != RFC_STATE_OPENED) { - log::info("bd_addr:{}, index:{}, state:{}, event:{}", p_port->bd_addr, - p_port->handle, p_port->rfc.state, event); + log::info("bd_addr:{}, index:{}, state:{}, event:{}", p_port->bd_addr, p_port->handle, + p_port->rfc.state, event); } switch (p_port->rfc.state) { case RFC_STATE_CLOSED: @@ -125,14 +117,12 @@ void rfc_port_sm_execute(tPORT* p_port, tRFC_PORT_EVENT event, void* p_data) { * Returns void * ******************************************************************************/ -void rfc_port_sm_state_closed(tPORT* p_port, tRFC_PORT_EVENT event, - void* p_data) { +void rfc_port_sm_state_closed(tPORT* p_port, tRFC_PORT_EVENT event, void* p_data) { switch (event) { case RFC_PORT_EVENT_OPEN: p_port->rfc.state = RFC_STATE_ORIG_WAIT_SEC_CHECK; - btm_sec_mx_access_request(p_port->rfc.p_mcb->bd_addr, true, - p_port->sec_mask, &rfc_sec_check_complete, - p_port); + btm_sec_mx_access_request(p_port->rfc.p_mcb->bd_addr, true, p_port->sec_mask, + &rfc_sec_check_complete, p_port); return; case RFC_PORT_EVENT_CLOSE: @@ -152,9 +142,8 @@ void rfc_port_sm_state_closed(tPORT* p_port, tRFC_PORT_EVENT event, /* Open will be continued after security checks are passed */ p_port->rfc.state = RFC_STATE_TERM_WAIT_SEC_CHECK; - btm_sec_mx_access_request(p_port->rfc.p_mcb->bd_addr, false, - p_port->sec_mask, &rfc_sec_check_complete, - p_port); + btm_sec_mx_access_request(p_port->rfc.p_mcb->bd_addr, false, p_port->sec_mask, + &rfc_sec_check_complete, p_port); return; case RFC_PORT_EVENT_UA: @@ -179,8 +168,7 @@ void rfc_port_sm_state_closed(tPORT* p_port, tRFC_PORT_EVENT event, log::error("Port error state {} event {}", p_port->rfc.state, event); return; default: - log::error("Received unexpected event:{} in state:{}", event, - p_port->rfc.state); + log::error("Received unexpected event:{} in state:{}", event, p_port->rfc.state); } log::warn("Port state closed Event ignored {}", event); @@ -197,8 +185,7 @@ void rfc_port_sm_state_closed(tPORT* p_port, tRFC_PORT_EVENT event, * Returns void * ******************************************************************************/ -void rfc_port_sm_sabme_wait_ua(tPORT* p_port, tRFC_PORT_EVENT event, - void* p_data) { +void rfc_port_sm_sabme_wait_ua(tPORT* p_port, tRFC_PORT_EVENT event, void* p_data) { switch (event) { case RFC_PORT_EVENT_OPEN: case RFC_PORT_EVENT_ESTABLISH_RSP: @@ -225,14 +212,12 @@ void rfc_port_sm_sabme_wait_ua(tPORT* p_port, tRFC_PORT_EVENT event, rfc_port_timer_stop(p_port); p_port->rfc.state = RFC_STATE_OPENED; - if (uuid_logging_acceptlist.find(p_port->uuid) != - uuid_logging_acceptlist.end()) { + if (uuid_logging_acceptlist.find(p_port->uuid) != uuid_logging_acceptlist.end()) { // Find Channel Control Block by Channel ID - tL2C_CCB* p_ccb = - l2cu_find_ccb_by_cid(nullptr, p_port->rfc.p_mcb->lcid); + tL2C_CCB* p_ccb = l2cu_find_ccb_by_cid(nullptr, p_port->rfc.p_mcb->lcid); if (p_ccb) { bluetooth::shim::GetSnoopLogger()->AcceptlistRfcommDlci( - p_ccb->p_lcb->Handle(), p_port->rfc.p_mcb->lcid, p_port->dlci); + p_ccb->p_lcb->Handle(), p_port->rfc.p_mcb->lcid, p_port->dlci); } } if (p_port->rfc.p_mcb) { @@ -244,28 +229,28 @@ void rfc_port_sm_sabme_wait_ua(tPORT* p_port, tRFC_PORT_EVENT event, if (ccb) { bluetooth::shim::GetSnoopLogger()->SetRfcommPortOpen( - ccb->p_lcb->Handle(), lcid, p_port->dlci, p_port->uuid, - p_port->rfc.p_mcb->flow == PORT_FC_CREDIT); + ccb->p_lcb->Handle(), lcid, p_port->dlci, p_port->uuid, + p_port->rfc.p_mcb->flow == PORT_FC_CREDIT); } } - PORT_DlcEstablishCnf(p_port->rfc.p_mcb, p_port->dlci, - p_port->rfc.p_mcb->peer_l2cap_mtu, RFCOMM_SUCCESS); + PORT_DlcEstablishCnf(p_port->rfc.p_mcb, p_port->dlci, p_port->rfc.p_mcb->peer_l2cap_mtu, + RFCOMM_SUCCESS); return; case RFC_PORT_EVENT_DM: log::warn("RFC_EVENT_DM, index={}", p_port->handle); p_port->rfc.p_mcb->is_disc_initiator = true; - PORT_DlcEstablishCnf(p_port->rfc.p_mcb, p_port->dlci, - p_port->rfc.p_mcb->peer_l2cap_mtu, RFCOMM_ERROR); + PORT_DlcEstablishCnf(p_port->rfc.p_mcb, p_port->dlci, p_port->rfc.p_mcb->peer_l2cap_mtu, + RFCOMM_ERROR); rfc_port_closed(p_port); return; case RFC_PORT_EVENT_DISC: log::warn("RFC_EVENT_DISC, index={}", p_port->handle); rfc_send_ua(p_port->rfc.p_mcb, p_port->dlci); - PORT_DlcEstablishCnf(p_port->rfc.p_mcb, p_port->dlci, - p_port->rfc.p_mcb->peer_l2cap_mtu, RFCOMM_ERROR); + PORT_DlcEstablishCnf(p_port->rfc.p_mcb, p_port->dlci, p_port->rfc.p_mcb->peer_l2cap_mtu, + RFCOMM_ERROR); rfc_port_closed(p_port); return; @@ -280,12 +265,11 @@ void rfc_port_sm_sabme_wait_ua(tPORT* p_port, tRFC_PORT_EVENT event, case RFC_PORT_EVENT_TIMEOUT: p_port->rfc.state = RFC_STATE_CLOSED; - PORT_DlcEstablishCnf(p_port->rfc.p_mcb, p_port->dlci, - p_port->rfc.p_mcb->peer_l2cap_mtu, RFCOMM_ERROR); + PORT_DlcEstablishCnf(p_port->rfc.p_mcb, p_port->dlci, p_port->rfc.p_mcb->peer_l2cap_mtu, + RFCOMM_ERROR); return; default: - log::error("Received unexpected event:{} in state:{}", event, - p_port->rfc.state); + log::error("Received unexpected event:{} in state:{}", event, p_port->rfc.state); } log::warn("Port state sabme_wait_ua Event ignored {}", event); } @@ -302,8 +286,7 @@ void rfc_port_sm_sabme_wait_ua(tPORT* p_port, tRFC_PORT_EVENT event, * Returns void * ******************************************************************************/ -void rfc_port_sm_term_wait_sec_check(tPORT* p_port, tRFC_PORT_EVENT event, - void* p_data) { +void rfc_port_sm_term_wait_sec_check(tPORT* p_port, tRFC_PORT_EVENT event, void* p_data) { switch (event) { case RFC_PORT_EVENT_SEC_COMPLETE: if (*((uint8_t*)p_data) != BTM_SUCCESS) { @@ -315,8 +298,7 @@ void rfc_port_sm_term_wait_sec_check(tPORT* p_port, tRFC_PORT_EVENT event, port_rfc_closed(p_port, PORT_SEC_FAILED); } } else { - PORT_DlcEstablishInd(p_port->rfc.p_mcb, p_port->dlci, - p_port->rfc.p_mcb->peer_l2cap_mtu); + PORT_DlcEstablishInd(p_port->rfc.p_mcb, p_port->dlci, p_port->rfc.p_mcb->peer_l2cap_mtu); } return; @@ -354,20 +336,19 @@ void rfc_port_sm_term_wait_sec_check(tPORT* p_port, tRFC_PORT_EVENT event, case RFC_PORT_EVENT_ESTABLISH_RSP: if (*((uint8_t*)p_data) != RFCOMM_SUCCESS) { - if (p_port->rfc.p_mcb) + if (p_port->rfc.p_mcb) { rfc_send_dm(p_port->rfc.p_mcb, p_port->dlci, true); + } } else { rfc_send_ua(p_port->rfc.p_mcb, p_port->dlci); p_port->rfc.state = RFC_STATE_OPENED; - if (uuid_logging_acceptlist.find(p_port->uuid) != - uuid_logging_acceptlist.end()) { + if (uuid_logging_acceptlist.find(p_port->uuid) != uuid_logging_acceptlist.end()) { // Find Channel Control Block by Channel ID - tL2C_CCB* p_ccb = - l2cu_find_ccb_by_cid(nullptr, p_port->rfc.p_mcb->lcid); + tL2C_CCB* p_ccb = l2cu_find_ccb_by_cid(nullptr, p_port->rfc.p_mcb->lcid); if (p_ccb) { bluetooth::shim::GetSnoopLogger()->AcceptlistRfcommDlci( - p_ccb->p_lcb->Handle(), p_port->rfc.p_mcb->lcid, p_port->dlci); + p_ccb->p_lcb->Handle(), p_port->rfc.p_mcb->lcid, p_port->dlci); } } if (p_port->rfc.p_mcb) { @@ -379,15 +360,14 @@ void rfc_port_sm_term_wait_sec_check(tPORT* p_port, tRFC_PORT_EVENT event, if (ccb) { bluetooth::shim::GetSnoopLogger()->SetRfcommPortOpen( - ccb->p_lcb->Handle(), lcid, p_port->dlci, p_port->uuid, - p_port->rfc.p_mcb->flow == PORT_FC_CREDIT); + ccb->p_lcb->Handle(), lcid, p_port->dlci, p_port->uuid, + p_port->rfc.p_mcb->flow == PORT_FC_CREDIT); } } } return; default: - log::error("Received unexpected event:{} in state:{}", event, - p_port->rfc.state); + log::error("Received unexpected event:{} in state:{}", event, p_port->rfc.state); } log::warn("Port state term_wait_sec_check Event ignored {}", event); } @@ -403,16 +383,14 @@ void rfc_port_sm_term_wait_sec_check(tPORT* p_port, tRFC_PORT_EVENT event, * Returns void * ******************************************************************************/ -void rfc_port_sm_orig_wait_sec_check(tPORT* p_port, tRFC_PORT_EVENT event, - void* p_data) { +void rfc_port_sm_orig_wait_sec_check(tPORT* p_port, tRFC_PORT_EVENT event, void* p_data) { switch (event) { case RFC_PORT_EVENT_SEC_COMPLETE: if (*((uint8_t*)p_data) != BTM_SUCCESS) { - log::error("RFC_PORT_EVENT_SEC_COMPLETE, index={}, result={}", - p_port->handle, *((uint8_t*)p_data)); + log::error("RFC_PORT_EVENT_SEC_COMPLETE, index={}, result={}", p_port->handle, + *((uint8_t*)p_data)); p_port->rfc.p_mcb->is_disc_initiator = true; - PORT_DlcEstablishCnf(p_port->rfc.p_mcb, p_port->dlci, 0, - RFCOMM_SECURITY_ERR); + PORT_DlcEstablishCnf(p_port->rfc.p_mcb, p_port->dlci, 0, RFCOMM_SECURITY_ERR); rfc_port_closed(p_port); return; } @@ -441,8 +419,7 @@ void rfc_port_sm_orig_wait_sec_check(tPORT* p_port, tRFC_PORT_EVENT event, osi_free(p_data); return; default: - log::error("Received unexpected event:{} in state:{}", event, - p_port->rfc.state); + log::error("Received unexpected event:{} in state:{}", event, p_port->rfc.state); } log::warn("Port state orig_wait_sec_check Event ignored {}", event); } @@ -460,13 +437,13 @@ void rfc_port_sm_orig_wait_sec_check(tPORT* p_port, tRFC_PORT_EVENT event, void rfc_port_sm_opened(tPORT* p_port, tRFC_PORT_EVENT event, void* p_data) { switch (event) { case RFC_PORT_EVENT_OPEN: - log::error("RFC_PORT_EVENT_OPEN bd_addr:{} handle:{} dlci:{} scn:{}", - p_port->bd_addr, p_port->handle, p_port->dlci, p_port->scn); + log::error("RFC_PORT_EVENT_OPEN bd_addr:{} handle:{} dlci:{} scn:{}", p_port->bd_addr, + p_port->handle, p_port->dlci, p_port->scn); return; case RFC_PORT_EVENT_CLOSE: - log::info("RFC_PORT_EVENT_CLOSE bd_addr:{}, handle:{} dlci:{} scn:{}", - p_port->bd_addr, p_port->handle, p_port->dlci, p_port->scn); + log::info("RFC_PORT_EVENT_CLOSE bd_addr:{}, handle:{} dlci:{} scn:{}", p_port->bd_addr, + p_port->handle, p_port->dlci, p_port->scn); rfc_port_timer_start(p_port, RFC_DISC_TIMEOUT); rfc_send_disc(p_port->rfc.p_mcb, p_port->dlci); p_port->rfc.expected_rsp = 0; @@ -474,8 +451,8 @@ void rfc_port_sm_opened(tPORT* p_port, tRFC_PORT_EVENT event, void* p_data) { return; case RFC_PORT_EVENT_CLEAR: - log::warn("RFC_PORT_EVENT_CLEAR bd_addr:{} handle:{} dlci:{} scn:{}", - p_port->bd_addr, p_port->handle, p_port->dlci, p_port->scn); + log::warn("RFC_PORT_EVENT_CLEAR bd_addr:{} handle:{} dlci:{} scn:{}", p_port->bd_addr, + p_port->handle, p_port->dlci, p_port->scn); rfc_port_closed(p_port); return; @@ -485,14 +462,12 @@ void rfc_port_sm_opened(tPORT* p_port, tRFC_PORT_EVENT event, void* p_data) { /* There might be an initial case when we reduced rx_max and credit_rx is * still */ /* bigger. Make sure that we do not send 255 */ - log::verbose("RFC_PORT_EVENT_DATA bd_addr:{} handle:{} dlci:{} scn:{}", - p_port->bd_addr, p_port->handle, p_port->dlci, p_port->scn); + log::verbose("RFC_PORT_EVENT_DATA bd_addr:{} handle:{} dlci:{} scn:{}", p_port->bd_addr, + p_port->handle, p_port->dlci, p_port->scn); if ((p_port->rfc.p_mcb->flow == PORT_FC_CREDIT) && - (((BT_HDR*)p_data)->len < p_port->peer_mtu) && - (!p_port->rx.user_fc) && + (((BT_HDR*)p_data)->len < p_port->peer_mtu) && (!p_port->rx.user_fc) && (p_port->credit_rx_max > p_port->credit_rx)) { - ((BT_HDR*)p_data)->layer_specific = - (uint8_t)(p_port->credit_rx_max - p_port->credit_rx); + ((BT_HDR*)p_data)->layer_specific = (uint8_t)(p_port->credit_rx_max - p_port->credit_rx); p_port->credit_rx = p_port->credit_rx_max; } else { ((BT_HDR*)p_data)->layer_specific = 0; @@ -502,26 +477,26 @@ void rfc_port_sm_opened(tPORT* p_port, tRFC_PORT_EVENT event, void* p_data) { return; case RFC_PORT_EVENT_UA: - log::verbose("RFC_PORT_EVENT_UA bd_addr:{} handle:{} dlci:{} scn:{}", - p_port->bd_addr, p_port->handle, p_port->dlci, p_port->scn); + log::verbose("RFC_PORT_EVENT_UA bd_addr:{} handle:{} dlci:{} scn:{}", p_port->bd_addr, + p_port->handle, p_port->dlci, p_port->scn); return; case RFC_PORT_EVENT_SABME: - log::verbose("RFC_PORT_EVENT_SABME bd_addr:{} handle:{} dlci:{} scn:{}", - p_port->bd_addr, p_port->handle, p_port->dlci, p_port->scn); + log::verbose("RFC_PORT_EVENT_SABME bd_addr:{} handle:{} dlci:{} scn:{}", p_port->bd_addr, + p_port->handle, p_port->dlci, p_port->scn); rfc_send_ua(p_port->rfc.p_mcb, p_port->dlci); return; case RFC_PORT_EVENT_DM: - log::info("RFC_EVENT_DM bd_addr:{} handle:{} dlci:{} scn:{}", - p_port->bd_addr, p_port->handle, p_port->dlci, p_port->scn); + log::info("RFC_EVENT_DM bd_addr:{} handle:{} dlci:{} scn:{}", p_port->bd_addr, p_port->handle, + p_port->dlci, p_port->scn); PORT_DlcReleaseInd(p_port->rfc.p_mcb, p_port->dlci); rfc_port_closed(p_port); return; case RFC_PORT_EVENT_DISC: - log::info("RFC_PORT_EVENT_DISC bd_addr:{} handle:{} dlci:{} scn:{}", - p_port->bd_addr, p_port->handle, p_port->dlci, p_port->scn); + log::info("RFC_PORT_EVENT_DISC bd_addr:{} handle:{} dlci:{} scn:{}", p_port->bd_addr, + p_port->handle, p_port->dlci, p_port->scn); p_port->rfc.state = RFC_STATE_CLOSED; rfc_send_ua(p_port->rfc.p_mcb, p_port->dlci); if (!fixed_queue_is_empty(p_port->rx.queue)) { @@ -534,23 +509,23 @@ void rfc_port_sm_opened(tPORT* p_port, tRFC_PORT_EVENT event, void* p_data) { return; case RFC_PORT_EVENT_UIH: - log::verbose("RFC_PORT_EVENT_UIH bd_addr:{}, handle:{} dlci:{} scn:{}", - p_port->bd_addr, p_port->handle, p_port->dlci, p_port->scn); + log::verbose("RFC_PORT_EVENT_UIH bd_addr:{}, handle:{} dlci:{} scn:{}", p_port->bd_addr, + p_port->handle, p_port->dlci, p_port->scn); rfc_port_uplink_data(p_port, (BT_HDR*)p_data); return; case RFC_PORT_EVENT_TIMEOUT: PORT_TimeOutCloseMux(p_port->rfc.p_mcb); - log::error("RFC_PORT_EVENT_TIMEOUT bd_addr:{} handle:{} dlci:{} scn:{}", - p_port->bd_addr, p_port->handle, p_port->dlci, p_port->scn); + log::error("RFC_PORT_EVENT_TIMEOUT bd_addr:{} handle:{} dlci:{} scn:{}", p_port->bd_addr, + p_port->handle, p_port->dlci, p_port->scn); return; default: break; } log::error("Received unexpected event:{} bd_addr:{} handle:{} dlci:{} scn:{}", - rfcomm_port_event_text(event), p_port->bd_addr, p_port->handle, - p_port->dlci, p_port->scn); + rfcomm_port_event_text(event), p_port->bd_addr, p_port->handle, p_port->dlci, + p_port->scn); } /******************************************************************************* @@ -563,8 +538,7 @@ void rfc_port_sm_opened(tPORT* p_port, tRFC_PORT_EVENT event, void* p_data) { * Returns void * ******************************************************************************/ -void rfc_port_sm_disc_wait_ua(tPORT* p_port, tRFC_PORT_EVENT event, - void* p_data) { +void rfc_port_sm_disc_wait_ua(tPORT* p_port, tRFC_PORT_EVENT event, void* p_data) { switch (event) { case RFC_PORT_EVENT_OPEN: case RFC_PORT_EVENT_ESTABLISH_RSP: @@ -585,8 +559,7 @@ void rfc_port_sm_disc_wait_ua(tPORT* p_port, tRFC_PORT_EVENT event, FALLTHROUGH_INTENDED; /* FALLTHROUGH */ case RFC_PORT_EVENT_DM: - log::warn("RFC_EVENT_DM|RFC_EVENT_UA[{}], index={}", event, - p_port->handle); + log::warn("RFC_EVENT_DM|RFC_EVENT_UA[{}], index={}", event, p_port->handle); rfc_port_closed(p_port); return; @@ -608,8 +581,7 @@ void rfc_port_sm_disc_wait_ua(tPORT* p_port, tRFC_PORT_EVENT event, rfc_port_closed(p_port); return; default: - log::error("Received unexpected event:{} in state:{}", event, - p_port->rfc.state); + log::error("Received unexpected event:{} in state:{}", event, p_port->rfc.state); } log::warn("Port state disc_wait_ua Event ignored {}", event); @@ -635,18 +607,16 @@ void rfc_port_uplink_data(tPORT* p_port, BT_HDR* p_buf) { * ******************************************************************************/ void rfc_process_pn(tRFC_MCB* p_mcb, bool is_command, MX_FRAME* p_frame) { - log::verbose("is_initiator={}, is_cmd={}, state={}, bd_addr={}", - p_mcb->is_initiator, is_command, p_mcb->state, p_mcb->bd_addr); + log::verbose("is_initiator={}, is_cmd={}, state={}, bd_addr={}", p_mcb->is_initiator, is_command, + p_mcb->state, p_mcb->bd_addr); uint8_t dlci = p_frame->dlci; if (is_command) { /* Ignore if Multiplexer is being shut down */ if (p_mcb->state != RFC_MX_STATE_DISC_WAIT_UA) { - PORT_ParNegInd(p_mcb, dlci, p_frame->u.pn.mtu, p_frame->u.pn.conv_layer, - p_frame->u.pn.k); + PORT_ParNegInd(p_mcb, dlci, p_frame->u.pn.mtu, p_frame->u.pn.conv_layer, p_frame->u.pn.k); } else { - log::warn("MX PN while disconnecting, bd_addr={}, p_mcb={}", - p_mcb->bd_addr, fmt::ptr(p_mcb)); + log::warn("MX PN while disconnecting, bd_addr={}, p_mcb={}", p_mcb->bd_addr, fmt::ptr(p_mcb)); rfc_send_dm(p_mcb, dlci, false); } @@ -655,8 +625,8 @@ void rfc_process_pn(tRFC_MCB* p_mcb, bool is_command, MX_FRAME* p_frame) { /* If we are not awaiting response just ignore it */ tPORT* p_port = port_find_mcb_dlci_port(p_mcb, dlci); if ((p_port == nullptr) || !(p_port->rfc.expected_rsp & RFC_RSP_PN)) { - log::warn(": Ignore unwanted response, p_mcb={}, bd_addr={}, dlci={}", - fmt::ptr(p_mcb), p_mcb->bd_addr, dlci); + log::warn(": Ignore unwanted response, p_mcb={}, bd_addr={}, dlci={}", fmt::ptr(p_mcb), + p_mcb->bd_addr, dlci); return; } @@ -664,8 +634,7 @@ void rfc_process_pn(tRFC_MCB* p_mcb, bool is_command, MX_FRAME* p_frame) { rfc_port_timer_stop(p_port); - PORT_ParNegCnf(p_mcb, dlci, p_frame->u.pn.mtu, p_frame->u.pn.conv_layer, - p_frame->u.pn.k); + PORT_ParNegCnf(p_mcb, dlci, p_frame->u.pn.mtu, p_frame->u.pn.conv_layer, p_frame->u.pn.k); } /******************************************************************************* @@ -676,8 +645,7 @@ void rfc_process_pn(tRFC_MCB* p_mcb, bool is_command, MX_FRAME* p_frame) { * command/response. Pass command to the user. * ******************************************************************************/ -void rfc_process_rpn(tRFC_MCB* p_mcb, bool is_command, bool is_request, - MX_FRAME* p_frame) { +void rfc_process_rpn(tRFC_MCB* p_mcb, bool is_command, bool is_request, MX_FRAME* p_frame) { tPORT_STATE port_pars; tPORT* p_port; @@ -688,8 +656,7 @@ void rfc_process_rpn(tRFC_MCB* p_mcb, bool is_command, bool is_request, memset(&port_pars, 0, sizeof(tPORT_STATE)); rfc_set_port_state(&port_pars, p_frame); - PORT_PortNegInd(p_mcb, p_frame->dlci, &port_pars, - p_frame->u.rpn.param_mask); + PORT_PortNegInd(p_mcb, p_frame->dlci, &port_pars, p_frame->u.rpn.param_mask); } return; } @@ -705,15 +672,13 @@ void rfc_process_rpn(tRFC_MCB* p_mcb, bool is_command, bool is_request, rfc_set_port_state(&port_pars, p_frame); if (is_command) { - PORT_PortNegInd(p_mcb, p_frame->dlci, &port_pars, - p_frame->u.rpn.param_mask); + PORT_PortNegInd(p_mcb, p_frame->dlci, &port_pars, p_frame->u.rpn.param_mask); return; } /* If we are not awaiting response just ignore it */ p_port = port_find_mcb_dlci_port(p_mcb, p_frame->dlci); - if ((p_port == nullptr) || - !(p_port->rfc.expected_rsp & (RFC_RSP_RPN | RFC_RSP_RPN_REPLY))) { + if ((p_port == nullptr) || !(p_port->rfc.expected_rsp & (RFC_RSP_RPN | RFC_RSP_RPN_REPLY))) { log::warn("ignore DLC parameter negotiation as we are not waiting for any"); return; } @@ -727,16 +692,13 @@ void rfc_process_rpn(tRFC_MCB* p_mcb, bool is_command, bool is_request, p_port->peer_port_pars = port_pars; - if ((port_pars.fc_type == - (RFCOMM_FC_RTR_ON_INPUT | RFCOMM_FC_RTR_ON_OUTPUT)) || - (port_pars.fc_type == - (RFCOMM_FC_RTC_ON_INPUT | RFCOMM_FC_RTC_ON_OUTPUT))) { + if ((port_pars.fc_type == (RFCOMM_FC_RTR_ON_INPUT | RFCOMM_FC_RTR_ON_OUTPUT)) || + (port_pars.fc_type == (RFCOMM_FC_RTC_ON_INPUT | RFCOMM_FC_RTC_ON_OUTPUT))) { /* This is satisfactory port parameters. Set mask as it was Ok */ p_frame->u.rpn.param_mask = RFCOMM_RPN_PM_MASK; } else { /* Current peer parameters are not good, try to fix them */ - p_port->peer_port_pars.fc_type = - (RFCOMM_FC_RTR_ON_INPUT | RFCOMM_FC_RTR_ON_OUTPUT); + p_port->peer_port_pars.fc_type = (RFCOMM_FC_RTR_ON_INPUT | RFCOMM_FC_RTR_ON_OUTPUT); p_port->rfc.expected_rsp |= RFC_RSP_RPN; rfc_send_rpn(p_mcb, p_frame->dlci, true, &p_port->peer_port_pars, @@ -744,15 +706,14 @@ void rfc_process_rpn(tRFC_MCB* p_mcb, bool is_command, bool is_request, rfc_port_timer_start(p_port, RFC_T2_TIMEOUT); return; } - } else + } else { p_port->rfc.expected_rsp &= ~RFC_RSP_RPN; + } /* Check if all suggested parameters were accepted */ - if (((p_frame->u.rpn.param_mask & - (RFCOMM_RPN_PM_RTR_ON_INPUT | RFCOMM_RPN_PM_RTR_ON_OUTPUT)) == + if (((p_frame->u.rpn.param_mask & (RFCOMM_RPN_PM_RTR_ON_INPUT | RFCOMM_RPN_PM_RTR_ON_OUTPUT)) == (RFCOMM_RPN_PM_RTR_ON_INPUT | RFCOMM_RPN_PM_RTR_ON_OUTPUT)) || - ((p_frame->u.rpn.param_mask & - (RFCOMM_RPN_PM_RTC_ON_INPUT | RFCOMM_RPN_PM_RTC_ON_OUTPUT)) == + ((p_frame->u.rpn.param_mask & (RFCOMM_RPN_PM_RTC_ON_INPUT | RFCOMM_RPN_PM_RTC_ON_OUTPUT)) == (RFCOMM_RPN_PM_RTC_ON_INPUT | RFCOMM_RPN_PM_RTC_ON_OUTPUT))) { PORT_PortNegCnf(p_mcb, p_port->dlci, &port_pars, RFCOMM_SUCCESS); return; @@ -761,11 +722,9 @@ void rfc_process_rpn(tRFC_MCB* p_mcb, bool is_command, bool is_request, /* If we were proposing RTR flow control try RTC flow control */ /* If we were proposing RTC flow control try no flow control */ /* otherwise drop the connection */ - if (p_port->peer_port_pars.fc_type == - (RFCOMM_FC_RTR_ON_INPUT | RFCOMM_FC_RTR_ON_OUTPUT)) { + if (p_port->peer_port_pars.fc_type == (RFCOMM_FC_RTR_ON_INPUT | RFCOMM_FC_RTR_ON_OUTPUT)) { /* Current peer parameters are not good, try to fix them */ - p_port->peer_port_pars.fc_type = - (RFCOMM_FC_RTC_ON_INPUT | RFCOMM_FC_RTC_ON_OUTPUT); + p_port->peer_port_pars.fc_type = (RFCOMM_FC_RTC_ON_INPUT | RFCOMM_FC_RTC_ON_OUTPUT); p_port->rfc.expected_rsp |= RFC_RSP_RPN; @@ -776,8 +735,7 @@ void rfc_process_rpn(tRFC_MCB* p_mcb, bool is_command, bool is_request, } /* Other side does not support flow control */ - if (p_port->peer_port_pars.fc_type == - (RFCOMM_FC_RTC_ON_INPUT | RFCOMM_FC_RTC_ON_OUTPUT)) { + if (p_port->peer_port_pars.fc_type == (RFCOMM_FC_RTC_ON_INPUT | RFCOMM_FC_RTC_ON_OUTPUT)) { p_port->peer_port_pars.fc_type = RFCOMM_FC_OFF; PORT_PortNegCnf(p_mcb, p_port->dlci, &port_pars, RFCOMM_SUCCESS); } @@ -798,22 +756,31 @@ void rfc_process_msc(tRFC_MCB* p_mcb, bool is_command, MX_FRAME* p_frame) { bool new_peer_fc = false; p_port = port_find_mcb_dlci_port(p_mcb, p_frame->dlci); - if (p_port == NULL) return; + if (p_port == NULL) { + return; + } pars.modem_signal = 0; - if (modem_signals & RFCOMM_MSC_RTC) pars.modem_signal |= MODEM_SIGNAL_DTRDSR; + if (modem_signals & RFCOMM_MSC_RTC) { + pars.modem_signal |= MODEM_SIGNAL_DTRDSR; + } - if (modem_signals & RFCOMM_MSC_RTR) pars.modem_signal |= MODEM_SIGNAL_RTSCTS; + if (modem_signals & RFCOMM_MSC_RTR) { + pars.modem_signal |= MODEM_SIGNAL_RTSCTS; + } - if (modem_signals & RFCOMM_MSC_IC) pars.modem_signal |= MODEM_SIGNAL_RI; + if (modem_signals & RFCOMM_MSC_IC) { + pars.modem_signal |= MODEM_SIGNAL_RI; + } - if (modem_signals & RFCOMM_MSC_DV) pars.modem_signal |= MODEM_SIGNAL_DCD; + if (modem_signals & RFCOMM_MSC_DV) { + pars.modem_signal |= MODEM_SIGNAL_DCD; + } pars.fc = ((modem_signals & RFCOMM_MSC_FC) == RFCOMM_MSC_FC); - pars.break_signal = - (p_frame->u.msc.break_present) ? p_frame->u.msc.break_duration : 0; + pars.break_signal = (p_frame->u.msc.break_present) ? p_frame->u.msc.break_duration : 0; pars.discard_buffers = 0; pars.break_signal_seq = RFCOMM_CTRL_BREAK_IN_SEQ; /* this is default */ @@ -825,8 +792,9 @@ void rfc_process_msc(tRFC_MCB* p_mcb, bool is_command, MX_FRAME* p_frame) { /* Spec 1.1 indicates that only FC bit is used for flow control */ p_port->peer_ctrl.fc = new_peer_fc = pars.fc; - if (new_peer_fc != p_port->tx.peer_fc) + if (new_peer_fc != p_port->tx.peer_fc) { PORT_FlowInd(p_mcb, p_frame->dlci, (bool)!new_peer_fc); + } } PORT_ControlInd(p_mcb, p_frame->dlci, &pars); @@ -835,7 +803,9 @@ void rfc_process_msc(tRFC_MCB* p_mcb, bool is_command, MX_FRAME* p_frame) { } /* If we are not awaiting response just ignore it */ - if (!(p_port->rfc.expected_rsp & RFC_RSP_MSC)) return; + if (!(p_port->rfc.expected_rsp & RFC_RSP_MSC)) { + return; + } p_port->rfc.expected_rsp &= ~RFC_RSP_MSC; @@ -862,7 +832,9 @@ void rfc_process_rls(tRFC_MCB* p_mcb, bool is_command, MX_FRAME* p_frame) { p_port = port_find_mcb_dlci_port(p_mcb, p_frame->dlci); /* If we are not awaiting response just ignore it */ - if (!p_port || !(p_port->rfc.expected_rsp & RFC_RSP_RLS)) return; + if (!p_port || !(p_port->rfc.expected_rsp & RFC_RSP_RLS)) { + return; + } p_port->rfc.expected_rsp &= ~RFC_RSP_RLS; @@ -887,9 +859,7 @@ void rfc_process_nsc(tRFC_MCB* /* p_mcb */, MX_FRAME* /* p_frame */) {} * reply to it. Otherwise pass response to the user. * ******************************************************************************/ -void rfc_process_test_rsp(tRFC_MCB* /* p_mcb */, BT_HDR* p_buf) { - osi_free(p_buf); -} +void rfc_process_test_rsp(tRFC_MCB* /* p_mcb */, BT_HDR* p_buf) { osi_free(p_buf); } /******************************************************************************* * @@ -905,7 +875,9 @@ void rfc_process_fcon(tRFC_MCB* p_mcb, bool is_command) { rfc_send_fcon(p_mcb, false); - if (!p_mcb->l2cap_congested) PORT_FlowInd(p_mcb, 0, true); + if (!p_mcb->l2cap_congested) { + PORT_FlowInd(p_mcb, 0, true); + } } } @@ -921,7 +893,9 @@ void rfc_process_fcoff(tRFC_MCB* p_mcb, bool is_command) { if (is_command) { rfc_cb.rfc.peer_rx_disabled = true; - if (!p_mcb->l2cap_congested) PORT_FlowInd(p_mcb, 0, false); + if (!p_mcb->l2cap_congested) { + PORT_FlowInd(p_mcb, 0, false); + } rfc_send_fcoff(p_mcb, false); } @@ -956,23 +930,31 @@ void rfc_process_l2cap_congestion(tRFC_MCB* p_mcb, bool is_congested) { ******************************************************************************/ void rfc_set_port_state(tPORT_STATE* port_pars, MX_FRAME* p_frame) { - if (p_frame->u.rpn.param_mask & RFCOMM_RPN_PM_BIT_RATE) + if (p_frame->u.rpn.param_mask & RFCOMM_RPN_PM_BIT_RATE) { port_pars->baud_rate = p_frame->u.rpn.baud_rate; - if (p_frame->u.rpn.param_mask & RFCOMM_RPN_PM_DATA_BITS) + } + if (p_frame->u.rpn.param_mask & RFCOMM_RPN_PM_DATA_BITS) { port_pars->byte_size = p_frame->u.rpn.byte_size; - if (p_frame->u.rpn.param_mask & RFCOMM_RPN_PM_STOP_BITS) + } + if (p_frame->u.rpn.param_mask & RFCOMM_RPN_PM_STOP_BITS) { port_pars->stop_bits = p_frame->u.rpn.stop_bits; - if (p_frame->u.rpn.param_mask & RFCOMM_RPN_PM_PARITY) + } + if (p_frame->u.rpn.param_mask & RFCOMM_RPN_PM_PARITY) { port_pars->parity = p_frame->u.rpn.parity; - if (p_frame->u.rpn.param_mask & RFCOMM_RPN_PM_PARITY_TYPE) + } + if (p_frame->u.rpn.param_mask & RFCOMM_RPN_PM_PARITY_TYPE) { port_pars->parity_type = p_frame->u.rpn.parity_type; + } if (p_frame->u.rpn.param_mask & (RFCOMM_RPN_PM_XONXOFF_ON_INPUT | RFCOMM_RPN_PM_XONXOFF_ON_OUTPUT | - RFCOMM_RPN_PM_RTR_ON_INPUT | RFCOMM_RPN_PM_RTR_ON_OUTPUT | - RFCOMM_RPN_PM_RTC_ON_INPUT | RFCOMM_RPN_PM_RTC_ON_OUTPUT)) + RFCOMM_RPN_PM_RTR_ON_INPUT | RFCOMM_RPN_PM_RTR_ON_OUTPUT | RFCOMM_RPN_PM_RTC_ON_INPUT | + RFCOMM_RPN_PM_RTC_ON_OUTPUT)) { port_pars->fc_type = p_frame->u.rpn.fc_type; - if (p_frame->u.rpn.param_mask & RFCOMM_RPN_PM_XON_CHAR) + } + if (p_frame->u.rpn.param_mask & RFCOMM_RPN_PM_XON_CHAR) { port_pars->xon_char = p_frame->u.rpn.xon_char; - if (p_frame->u.rpn.param_mask & RFCOMM_RPN_PM_XOFF_CHAR) + } + if (p_frame->u.rpn.param_mask & RFCOMM_RPN_PM_XOFF_CHAR) { port_pars->xoff_char = p_frame->u.rpn.xoff_char; + } } diff --git a/system/stack/rfcomm/rfc_port_if.cc b/system/stack/rfcomm/rfc_port_if.cc index 51ff786f499..0a124d62a82 100644 --- a/system/stack/rfcomm/rfc_port_if.cc +++ b/system/stack/rfcomm/rfc_port_if.cc @@ -50,9 +50,7 @@ std::unordered_map rfc_lcid_mcb; * start event to the state machine. * ******************************************************************************/ -void RFCOMM_StartReq(tRFC_MCB* p_mcb) { - rfc_mx_sm_execute(p_mcb, RFC_MX_EVENT_START_REQ, nullptr); -} +void RFCOMM_StartReq(tRFC_MCB* p_mcb) { rfc_mx_sm_execute(p_mcb, RFC_MX_EVENT_START_REQ, nullptr); } /******************************************************************************* * @@ -101,8 +99,7 @@ void RFCOMM_DlcEstablishReq(tRFC_MCB* p_mcb, uint8_t dlci, uint16_t /* mtu */) { * acks Establish Indication. * ******************************************************************************/ -void RFCOMM_DlcEstablishRsp(tRFC_MCB* p_mcb, uint8_t dlci, uint16_t /* mtu */, - uint16_t result) { +void RFCOMM_DlcEstablishRsp(tRFC_MCB* p_mcb, uint8_t dlci, uint16_t /* mtu */, uint16_t result) { if ((p_mcb->state != RFC_MX_STATE_CONNECTED) && (result == RFCOMM_SUCCESS)) { PORT_DlcReleaseInd(p_mcb, dlci); return; @@ -127,8 +124,7 @@ void RFCOMM_DlcEstablishRsp(tRFC_MCB* p_mcb, uint8_t dlci, uint16_t /* mtu */, * block. * ******************************************************************************/ -void RFCOMM_ParameterNegotiationRequest(tRFC_MCB* p_mcb, uint8_t dlci, - uint16_t mtu) { +void RFCOMM_ParameterNegotiationRequest(tRFC_MCB* p_mcb, uint8_t dlci, uint16_t mtu) { uint8_t flow; uint8_t cl; uint8_t k; @@ -153,8 +149,7 @@ void RFCOMM_ParameterNegotiationRequest(tRFC_MCB* p_mcb, uint8_t dlci, /* Set convergence layer and number of credits (k) */ if (flow == PORT_FC_CREDIT) { cl = RFCOMM_PN_CONV_LAYER_CBFC_I; - k = (p_port->credit_rx_max < RFCOMM_K_MAX) ? p_port->credit_rx_max - : RFCOMM_K_MAX; + k = (p_port->credit_rx_max < RFCOMM_K_MAX) ? p_port->credit_rx_max : RFCOMM_K_MAX; p_port->credit_rx = k; } else { cl = RFCOMM_PN_CONV_LAYER_TYPE_1; @@ -177,9 +172,11 @@ void RFCOMM_ParameterNegotiationRequest(tRFC_MCB* p_mcb, uint8_t dlci, * DLC parameter negotiation. * ******************************************************************************/ -void RFCOMM_ParameterNegotiationResponse(tRFC_MCB* p_mcb, uint8_t dlci, - uint16_t mtu, uint8_t cl, uint8_t k) { - if (p_mcb->state != RFC_MX_STATE_CONNECTED) return; +void RFCOMM_ParameterNegotiationResponse(tRFC_MCB* p_mcb, uint8_t dlci, uint16_t mtu, uint8_t cl, + uint8_t k) { + if (p_mcb->state != RFC_MX_STATE_CONNECTED) { + return; + } /* Send Parameter Negotiation Response UIH frame */ rfc_send_pn(p_mcb, dlci, false, mtu, cl, k); @@ -196,8 +193,7 @@ void RFCOMM_ParameterNegotiationResponse(tRFC_MCB* p_mcb, uint8_t dlci, * control block. * ******************************************************************************/ -void RFCOMM_PortParameterNegotiationRequest(tRFC_MCB* p_mcb, uint8_t dlci, - tPORT_STATE* p_pars) { +void RFCOMM_PortParameterNegotiationRequest(tRFC_MCB* p_mcb, uint8_t dlci, tPORT_STATE* p_pars) { if (p_mcb->state != RFC_MX_STATE_CONNECTED) { PORT_PortNegCnf(p_mcb, dlci, nullptr, RFCOMM_ERROR); return; @@ -210,10 +206,11 @@ void RFCOMM_PortParameterNegotiationRequest(tRFC_MCB* p_mcb, uint8_t dlci, } /* Send Parameter Negotiation Command UIH frame */ - if (!p_pars) + if (!p_pars) { p_port->rfc.expected_rsp |= RFC_RSP_RPN_REPLY; - else + } else { p_port->rfc.expected_rsp |= RFC_RSP_RPN; + } rfc_send_rpn(p_mcb, dlci, true, p_pars, RFCOMM_RPN_PM_MASK); rfc_port_timer_start(p_port, RFC_T2_TIMEOUT); @@ -227,10 +224,11 @@ void RFCOMM_PortParameterNegotiationRequest(tRFC_MCB* p_mcb, uint8_t dlci, * Port parameters negotiation. * ******************************************************************************/ -void RFCOMM_PortParameterNegotiationResponse(tRFC_MCB* p_mcb, uint8_t dlci, - tPORT_STATE* p_pars, +void RFCOMM_PortParameterNegotiationResponse(tRFC_MCB* p_mcb, uint8_t dlci, tPORT_STATE* p_pars, uint16_t param_mask) { - if (p_mcb->state != RFC_MX_STATE_CONNECTED) return; + if (p_mcb->state != RFC_MX_STATE_CONNECTED) { + return; + } rfc_send_rpn(p_mcb, dlci, false, p_pars, param_mask); } @@ -250,9 +248,9 @@ void RFCOMM_ControlReq(tRFC_MCB* p_mcb, uint8_t dlci, tPORT_CTRL* p_pars) { return; } - if ((p_port->state != PORT_CONNECTION_STATE_OPENED) || - (p_port->rfc.state != RFC_STATE_OPENED)) + if ((p_port->state != PORT_CONNECTION_STATE_OPENED) || (p_port->rfc.state != RFC_STATE_OPENED)) { return; + } p_port->port_ctrl |= PORT_CTRL_REQ_SENT; @@ -278,9 +276,9 @@ void RFCOMM_FlowReq(tRFC_MCB* p_mcb, uint8_t dlci, bool enable) { return; } - if ((p_port->state != PORT_CONNECTION_STATE_OPENED) || - (p_port->rfc.state != RFC_STATE_OPENED)) + if ((p_port->state != PORT_CONNECTION_STATE_OPENED) || (p_port->rfc.state != RFC_STATE_OPENED)) { return; + } p_port->local_ctrl.fc = !enable; @@ -305,9 +303,9 @@ void RFCOMM_LineStatusReq(tRFC_MCB* p_mcb, uint8_t dlci, uint8_t status) { return; } - if ((p_port->state != PORT_CONNECTION_STATE_OPENED) || - (p_port->rfc.state != RFC_STATE_OPENED)) + if ((p_port->state != PORT_CONNECTION_STATE_OPENED) || (p_port->rfc.state != RFC_STATE_OPENED)) { return; + } p_port->rfc.expected_rsp |= RFC_RSP_RLS; @@ -323,8 +321,7 @@ void RFCOMM_LineStatusReq(tRFC_MCB* p_mcb, uint8_t dlci, uint8_t status) { * ******************************************************************************/ void RFCOMM_DlcReleaseReq(tRFC_MCB* p_mcb, uint8_t dlci) { - rfc_port_sm_execute(port_find_mcb_dlci_port(p_mcb, dlci), - RFC_PORT_EVENT_CLOSE, nullptr); + rfc_port_sm_execute(port_find_mcb_dlci_port(p_mcb, dlci), RFC_PORT_EVENT_CLOSE, nullptr); } /******************************************************************************* @@ -335,6 +332,5 @@ void RFCOMM_DlcReleaseReq(tRFC_MCB* p_mcb, uint8_t dlci) { * ******************************************************************************/ void RFCOMM_DataReq(tRFC_MCB* p_mcb, uint8_t dlci, BT_HDR* p_buf) { - rfc_port_sm_execute(port_find_mcb_dlci_port(p_mcb, dlci), RFC_PORT_EVENT_DATA, - p_buf); + rfc_port_sm_execute(port_find_mcb_dlci_port(p_mcb, dlci), RFC_PORT_EVENT_DATA, p_buf); } diff --git a/system/stack/rfcomm/rfc_ts_frames.cc b/system/stack/rfcomm/rfc_ts_frames.cc index 068dd022d6c..e73bab5cf6f 100644 --- a/system/stack/rfcomm/rfc_ts_frames.cc +++ b/system/stack/rfcomm/rfc_ts_frames.cc @@ -59,8 +59,7 @@ void rfc_send_sabme(tRFC_MCB* p_mcb, uint8_t dlci) { *p_data++ = RFCOMM_SABME | RFCOMM_PF; *p_data++ = RFCOMM_EA | 0; - *p_data = - RFCOMM_SABME_FCS((uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET, cr, dlci); + *p_data = RFCOMM_SABME_FCS((uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET, cr, dlci); p_buf->len = 4; @@ -202,8 +201,8 @@ void rfc_send_buf_uih(tRFC_MCB* p_mcb, uint8_t dlci, BT_HDR* p_buf) { rfc_check_send_cmd(p_mcb, p_buf); } else { if (L2CA_DataWrite(p_mcb->lcid, p_buf) != tL2CAP_DW_RESULT::SUCCESS) { - log::warn("Unable to write L2CAP data peer:{} cid:{} len:{}", - p_mcb->bd_addr, p_mcb->lcid, p_buf->len); + log::warn("Unable to write L2CAP data peer:{} cid:{} len:{}", p_mcb->bd_addr, p_mcb->lcid, + p_buf->len); } } } @@ -215,8 +214,8 @@ void rfc_send_buf_uih(tRFC_MCB* p_mcb, uint8_t dlci, BT_HDR* p_buf) { * Description This function sends DLC Parameters Negotiation Frame. * ******************************************************************************/ -void rfc_send_pn(tRFC_MCB* p_mcb, uint8_t dlci, bool is_command, uint16_t mtu, - uint8_t cl, uint8_t k) { +void rfc_send_pn(tRFC_MCB* p_mcb, uint8_t dlci, bool is_command, uint16_t mtu, uint8_t cl, + uint8_t k) { uint8_t* p_data; BT_HDR* p_buf = (BT_HDR*)osi_malloc(RFCOMM_CMD_BUF_SIZE); @@ -230,10 +229,10 @@ void rfc_send_pn(tRFC_MCB* p_mcb, uint8_t dlci, bool is_command, uint16_t mtu, *p_data++ = RFCOMM_PN_FRAM_TYPE_UIH | cl; /* It appeared that we need to reply with the same priority bits as we - *received. - ** We will use the fact that we reply in the same context so rx_frame can - *still be used. - */ + *received. + ** We will use the fact that we reply in the same context so rx_frame can + *still be used. + */ if (is_command) { *p_data++ = RFCOMM_PN_PRIORITY_0; } else { @@ -304,8 +303,7 @@ void rfc_send_fcoff(tRFC_MCB* p_mcb, bool is_command) { * Description This function sends Modem Status Command Frame. * ******************************************************************************/ -void rfc_send_msc(tRFC_MCB* p_mcb, uint8_t dlci, bool is_command, - tPORT_CTRL* p_pars) { +void rfc_send_msc(tRFC_MCB* p_mcb, uint8_t dlci, bool is_command, tPORT_CTRL* p_pars) { uint8_t* p_data; uint8_t signals; uint8_t break_duration; @@ -318,10 +316,11 @@ void rfc_send_msc(tRFC_MCB* p_mcb, uint8_t dlci, bool is_command, p_buf->offset = L2CAP_MIN_OFFSET + RFCOMM_CTRL_FRAME_LEN; p_data = (uint8_t*)(p_buf + 1) + p_buf->offset; - if (break_duration) + if (break_duration) { len = RFCOMM_MX_MSC_LEN_WITH_BREAK; - else + } else { len = RFCOMM_MX_MSC_LEN_NO_BREAK; + } *p_data++ = RFCOMM_EA | RFCOMM_I_CR(is_command) | RFCOMM_MX_MSC; *p_data++ = RFCOMM_EA | (len << 1); @@ -334,8 +333,8 @@ void rfc_send_msc(tRFC_MCB* p_mcb, uint8_t dlci, bool is_command, ((signals & MODEM_SIGNAL_DCD) ? RFCOMM_MSC_DV : 0); if (break_duration) { - *p_data++ = RFCOMM_EA | RFCOMM_MSC_BREAK_PRESENT_MASK | - (break_duration << RFCOMM_MSC_SHIFT_BREAK); + *p_data++ = + RFCOMM_EA | RFCOMM_MSC_BREAK_PRESENT_MASK | (break_duration << RFCOMM_MSC_SHIFT_BREAK); } /* Total length is sizeof MSC data + mx header 2 */ @@ -351,8 +350,7 @@ void rfc_send_msc(tRFC_MCB* p_mcb, uint8_t dlci, bool is_command, * Description This function sends Remote Line Status Command Frame. * ******************************************************************************/ -void rfc_send_rls(tRFC_MCB* p_mcb, uint8_t dlci, bool is_command, - uint8_t status) { +void rfc_send_rls(tRFC_MCB* p_mcb, uint8_t dlci, bool is_command, uint8_t status) { uint8_t* p_data; BT_HDR* p_buf = (BT_HDR*)osi_malloc(RFCOMM_CMD_BUF_SIZE); @@ -388,8 +386,7 @@ void rfc_send_nsc(tRFC_MCB* p_mcb) { *p_data++ = RFCOMM_EA | RFCOMM_I_CR(false) | RFCOMM_MX_NSC; *p_data++ = RFCOMM_EA | (RFCOMM_MX_NSC_LEN << 1); - *p_data++ = rfc_cb.rfc.rx_frame.ea | - (rfc_cb.rfc.rx_frame.cr << RFCOMM_SHIFT_CR) | + *p_data++ = rfc_cb.rfc.rx_frame.ea | (rfc_cb.rfc.rx_frame.cr << RFCOMM_SHIFT_CR) | rfc_cb.rfc.rx_frame.type; /* Total length is sizeof NSC data + mx header 2 */ @@ -405,8 +402,8 @@ void rfc_send_nsc(tRFC_MCB* p_mcb) { * Description This function sends Remote Port Negotiation Command * ******************************************************************************/ -void rfc_send_rpn(tRFC_MCB* p_mcb, uint8_t dlci, bool is_command, - tPORT_STATE* p_pars, uint16_t mask) { +void rfc_send_rpn(tRFC_MCB* p_mcb, uint8_t dlci, bool is_command, tPORT_STATE* p_pars, + uint16_t mask) { uint8_t* p_data; BT_HDR* p_buf = (BT_HDR*)osi_malloc(RFCOMM_CMD_BUF_SIZE); @@ -454,17 +451,17 @@ void rfc_send_test(tRFC_MCB* p_mcb, bool is_command, BT_HDR* p_buf) { /* Shift buffer to give space for header */ if (p_buf->offset < (L2CAP_MIN_OFFSET + RFCOMM_MIN_OFFSET + 2)) { uint8_t* p_src = (uint8_t*)(p_buf + 1) + p_buf->offset + p_buf->len - 1; - BT_HDR* p_new_buf = - (BT_HDR*)osi_malloc(p_buf->len + (L2CAP_MIN_OFFSET + RFCOMM_MIN_OFFSET + - 2 + sizeof(BT_HDR) + 1)); + BT_HDR* p_new_buf = (BT_HDR*)osi_malloc( + p_buf->len + (L2CAP_MIN_OFFSET + RFCOMM_MIN_OFFSET + 2 + sizeof(BT_HDR) + 1)); p_new_buf->offset = L2CAP_MIN_OFFSET + RFCOMM_MIN_OFFSET + 2; p_new_buf->len = p_buf->len; - uint8_t* p_dest = - (uint8_t*)(p_new_buf + 1) + p_new_buf->offset + p_new_buf->len - 1; + uint8_t* p_dest = (uint8_t*)(p_new_buf + 1) + p_new_buf->offset + p_new_buf->len - 1; - for (uint16_t xx = 0; xx < p_buf->len; xx++) *p_dest-- = *p_src--; + for (uint16_t xx = 0; xx < p_buf->len; xx++) { + *p_dest-- = *p_src--; + } osi_free(p_buf); p_buf = p_new_buf; @@ -523,13 +520,13 @@ tRFC_EVENT rfc_parse_data(tRFC_MCB* p_mcb, MX_FRAME* p_frame, BT_HDR* p_buf) { if (p_buf->len < RFCOMM_CTRL_FRAME_LEN) { log::error("Bad Length1: {}", p_buf->len); - return (RFC_EVENT_BAD_FRAME); + return RFC_EVENT_BAD_FRAME; } RFCOMM_PARSE_CTRL_FIELD(ead, p_frame->cr, p_frame->dlci, p_data); if (!ead) { log::error("Bad Address(EA must be 1)"); - return (RFC_EVENT_BAD_FRAME); + return RFC_EVENT_BAD_FRAME; } RFCOMM_PARSE_TYPE_FIELD(p_frame->type, p_frame->pf, p_data); @@ -565,7 +562,7 @@ tRFC_EVENT rfc_parse_data(tRFC_MCB* p_mcb, MX_FRAME* p_frame, BT_HDR* p_buf) { if (p_buf->len != len) { log::error("Bad Length2 {} {}", p_buf->len, len); - return (RFC_EVENT_BAD_FRAME); + return RFC_EVENT_BAD_FRAME; } fcs = *(p_data + len); @@ -576,58 +573,62 @@ tRFC_EVENT rfc_parse_data(tRFC_MCB* p_mcb, MX_FRAME* p_frame, BT_HDR* p_buf) { /* notification to the sender */ switch (p_frame->type) { case RFCOMM_SABME: - if (RFCOMM_FRAME_IS_RSP(p_mcb->is_initiator, p_frame->cr) || - !p_frame->pf || len || !RFCOMM_VALID_DLCI(p_frame->dlci) || + if (RFCOMM_FRAME_IS_RSP(p_mcb->is_initiator, p_frame->cr) || !p_frame->pf || len || + !RFCOMM_VALID_DLCI(p_frame->dlci) || !rfc_check_fcs(RFCOMM_CTRL_FRAME_LEN, p_start, fcs)) { log::error("Bad SABME"); - return (RFC_EVENT_BAD_FRAME); - } else - return (RFC_EVENT_SABME); + return RFC_EVENT_BAD_FRAME; + } else { + return RFC_EVENT_SABME; + } case RFCOMM_UA: - if (RFCOMM_FRAME_IS_CMD(p_mcb->is_initiator, p_frame->cr) || - !p_frame->pf || len || !RFCOMM_VALID_DLCI(p_frame->dlci) || + if (RFCOMM_FRAME_IS_CMD(p_mcb->is_initiator, p_frame->cr) || !p_frame->pf || len || + !RFCOMM_VALID_DLCI(p_frame->dlci) || !rfc_check_fcs(RFCOMM_CTRL_FRAME_LEN, p_start, fcs)) { log::error("Bad UA"); - return (RFC_EVENT_BAD_FRAME); - } else - return (RFC_EVENT_UA); + return RFC_EVENT_BAD_FRAME; + } else { + return RFC_EVENT_UA; + } case RFCOMM_DM: if (RFCOMM_FRAME_IS_CMD(p_mcb->is_initiator, p_frame->cr) || len || !RFCOMM_VALID_DLCI(p_frame->dlci) || !rfc_check_fcs(RFCOMM_CTRL_FRAME_LEN, p_start, fcs)) { log::error("Bad DM"); - return (RFC_EVENT_BAD_FRAME); - } else - return (RFC_EVENT_DM); + return RFC_EVENT_BAD_FRAME; + } else { + return RFC_EVENT_DM; + } case RFCOMM_DISC: - if (RFCOMM_FRAME_IS_RSP(p_mcb->is_initiator, p_frame->cr) || - !p_frame->pf || len || !RFCOMM_VALID_DLCI(p_frame->dlci) || + if (RFCOMM_FRAME_IS_RSP(p_mcb->is_initiator, p_frame->cr) || !p_frame->pf || len || + !RFCOMM_VALID_DLCI(p_frame->dlci) || !rfc_check_fcs(RFCOMM_CTRL_FRAME_LEN, p_start, fcs)) { log::error("Bad DISC"); - return (RFC_EVENT_BAD_FRAME); - } else - return (RFC_EVENT_DISC); + return RFC_EVENT_BAD_FRAME; + } else { + return RFC_EVENT_DISC; + } case RFCOMM_UIH: if (!RFCOMM_VALID_DLCI(p_frame->dlci)) { log::error("Bad UIH - invalid DLCI"); - return (RFC_EVENT_BAD_FRAME); + return RFC_EVENT_BAD_FRAME; } else if (!rfc_check_fcs(2, p_start, fcs)) { log::error("Bad UIH - FCS"); - return (RFC_EVENT_BAD_FRAME); + return RFC_EVENT_BAD_FRAME; } else if (RFCOMM_FRAME_IS_RSP(p_mcb->is_initiator, p_frame->cr)) { /* we assume that this is ok to allow bad implementations to work */ log::error("Bad UIH - response"); - return (RFC_EVENT_UIH); + return RFC_EVENT_UIH; } else { - return (RFC_EVENT_UIH); + return RFC_EVENT_UIH; } } - return (RFC_EVENT_BAD_FRAME); + return RFC_EVENT_BAD_FRAME; } /******************************************************************************* @@ -654,8 +655,8 @@ void rfc_process_mx_message(tRFC_MCB* p_mcb, BT_HDR* p_buf) { p_rx_frame->type = *p_data++ & ~(RFCOMM_CR_MASK | RFCOMM_EA_MASK); if (!p_rx_frame->ea || !length) { - log::error("Invalid MX frame ea={}, len={}, bd_addr={}", p_rx_frame->ea, - length, p_mcb->bd_addr); + log::error("Invalid MX frame ea={}, len={}, bd_addr={}", p_rx_frame->ea, length, + p_mcb->bd_addr); osi_free(p_buf); return; } @@ -680,8 +681,7 @@ void rfc_process_mx_message(tRFC_MCB* p_mcb, BT_HDR* p_buf) { } if (mx_len != length) { - log::error("Bad MX frame, p_mcb={}, bd_addr={}", fmt::ptr(p_mcb), - p_mcb->bd_addr); + log::error("Bad MX frame, p_mcb={}, bd_addr={}", fmt::ptr(p_mcb), p_mcb->bd_addr); osi_free(p_buf); return; } @@ -690,8 +690,7 @@ void rfc_process_mx_message(tRFC_MCB* p_mcb, BT_HDR* p_buf) { switch (p_rx_frame->type) { case RFCOMM_MX_PN: if (length != RFCOMM_MX_PN_LEN) { - log::error("Invalid PN length, p_mcb={}, bd_addr={}", fmt::ptr(p_mcb), - p_mcb->bd_addr); + log::error("Invalid PN length, p_mcb={}, bd_addr={}", fmt::ptr(p_mcb), p_mcb->bd_addr); break; } @@ -706,10 +705,8 @@ void rfc_process_mx_message(tRFC_MCB* p_mcb, BT_HDR* p_buf) { p_rx_frame->u.pn.k = *p_data++ & RFCOMM_PN_K_MASK; if (!p_rx_frame->dlci || !RFCOMM_VALID_DLCI(p_rx_frame->dlci) || - (p_rx_frame->u.pn.mtu < RFCOMM_MIN_MTU) || - (p_rx_frame->u.pn.mtu > RFCOMM_MAX_MTU)) { - log::error("Bad PN frame, p_mcb={}, bd_addr={}", fmt::ptr(p_mcb), - p_mcb->bd_addr); + (p_rx_frame->u.pn.mtu < RFCOMM_MIN_MTU) || (p_rx_frame->u.pn.mtu > RFCOMM_MAX_MTU)) { + log::error("Bad PN frame, p_mcb={}, bd_addr={}", fmt::ptr(p_mcb), p_mcb->bd_addr); break; } @@ -719,7 +716,9 @@ void rfc_process_mx_message(tRFC_MCB* p_mcb, BT_HDR* p_buf) { return; case RFCOMM_MX_TEST: - if (!length) break; + if (!length) { + break; + } p_rx_frame->u.test.p_data = p_data; p_rx_frame->u.test.data_len = length; @@ -727,14 +726,17 @@ void rfc_process_mx_message(tRFC_MCB* p_mcb, BT_HDR* p_buf) { p_buf->offset += 2; p_buf->len -= 2; - if (is_command) + if (is_command) { rfc_send_test(p_mcb, false, p_buf); - else + } else { rfc_process_test_rsp(p_mcb, p_buf); + } return; case RFCOMM_MX_FCON: - if (length != RFCOMM_MX_FCON_LEN) break; + if (length != RFCOMM_MX_FCON_LEN) { + break; + } osi_free(p_buf); @@ -742,7 +744,9 @@ void rfc_process_mx_message(tRFC_MCB* p_mcb, BT_HDR* p_buf) { return; case RFCOMM_MX_FCOFF: - if (length != RFCOMM_MX_FCOFF_LEN) break; + if (length != RFCOMM_MX_FCOFF_LEN) { + break; + } osi_free(p_buf); @@ -750,8 +754,7 @@ void rfc_process_mx_message(tRFC_MCB* p_mcb, BT_HDR* p_buf) { return; case RFCOMM_MX_MSC: - if (length != RFCOMM_MX_MSC_LEN_WITH_BREAK && - length != RFCOMM_MX_MSC_LEN_NO_BREAK) { + if (length != RFCOMM_MX_MSC_LEN_WITH_BREAK && length != RFCOMM_MX_MSC_LEN_NO_BREAK) { log::error("Illegal MX MSC Frame len:{}", length); osi_free(p_buf); return; @@ -760,8 +763,7 @@ void rfc_process_mx_message(tRFC_MCB* p_mcb, BT_HDR* p_buf) { cr = (*p_data & RFCOMM_CR_MASK) >> RFCOMM_SHIFT_CR; p_rx_frame->dlci = *p_data++ >> RFCOMM_SHIFT_DLCI; - if (!ea || !cr || !p_rx_frame->dlci || - !RFCOMM_VALID_DLCI(p_rx_frame->dlci)) { + if (!ea || !cr || !p_rx_frame->dlci || !RFCOMM_VALID_DLCI(p_rx_frame->dlci)) { log::error("Bad MSC frame"); break; } @@ -769,10 +771,9 @@ void rfc_process_mx_message(tRFC_MCB* p_mcb, BT_HDR* p_buf) { p_rx_frame->u.msc.signals = *p_data++; if (mx_len == RFCOMM_MX_MSC_LEN_WITH_BREAK) { - p_rx_frame->u.msc.break_present = - *p_data & RFCOMM_MSC_BREAK_PRESENT_MASK; + p_rx_frame->u.msc.break_present = *p_data & RFCOMM_MSC_BREAK_PRESENT_MASK; p_rx_frame->u.msc.break_duration = - (*p_data & RFCOMM_MSC_BREAK_MASK) >> RFCOMM_MSC_SHIFT_BREAK; + (*p_data & RFCOMM_MSC_BREAK_MASK) >> RFCOMM_MSC_SHIFT_BREAK; } else { p_rx_frame->u.msc.break_present = false; p_rx_frame->u.msc.break_duration = 0; @@ -783,7 +784,9 @@ void rfc_process_mx_message(tRFC_MCB* p_mcb, BT_HDR* p_buf) { return; case RFCOMM_MX_NSC: - if ((length != RFCOMM_MX_NSC_LEN) || !is_command) break; + if ((length != RFCOMM_MX_NSC_LEN) || !is_command) { + break; + } p_rx_frame->u.nsc.ea = *p_data & RFCOMM_EA; p_rx_frame->u.nsc.cr = (*p_data & RFCOMM_CR_MASK) >> RFCOMM_SHIFT_CR; @@ -795,15 +798,15 @@ void rfc_process_mx_message(tRFC_MCB* p_mcb, BT_HDR* p_buf) { return; case RFCOMM_MX_RPN: - if ((length != RFCOMM_MX_RPN_REQ_LEN) && (length != RFCOMM_MX_RPN_LEN)) + if ((length != RFCOMM_MX_RPN_REQ_LEN) && (length != RFCOMM_MX_RPN_LEN)) { break; + } ea = *p_data & RFCOMM_EA; cr = (*p_data & RFCOMM_CR_MASK) >> RFCOMM_SHIFT_CR; p_rx_frame->dlci = *p_data++ >> RFCOMM_SHIFT_DLCI; - if (!ea || !cr || !p_rx_frame->dlci || - !RFCOMM_VALID_DLCI(p_rx_frame->dlci)) { + if (!ea || !cr || !p_rx_frame->dlci || !RFCOMM_VALID_DLCI(p_rx_frame->dlci)) { log::error("Bad RPN frame"); break; } @@ -812,30 +815,27 @@ void rfc_process_mx_message(tRFC_MCB* p_mcb, BT_HDR* p_buf) { if (!p_rx_frame->u.rpn.is_request) { p_rx_frame->u.rpn.baud_rate = *p_data++; - p_rx_frame->u.rpn.byte_size = - (*p_data >> RFCOMM_RPN_BITS_SHIFT) & RFCOMM_RPN_BITS_MASK; + p_rx_frame->u.rpn.byte_size = (*p_data >> RFCOMM_RPN_BITS_SHIFT) & RFCOMM_RPN_BITS_MASK; p_rx_frame->u.rpn.stop_bits = - (*p_data >> RFCOMM_RPN_STOP_BITS_SHIFT) & RFCOMM_RPN_STOP_BITS_MASK; - p_rx_frame->u.rpn.parity = - (*p_data >> RFCOMM_RPN_PARITY_SHIFT) & RFCOMM_RPN_PARITY_MASK; + (*p_data >> RFCOMM_RPN_STOP_BITS_SHIFT) & RFCOMM_RPN_STOP_BITS_MASK; + p_rx_frame->u.rpn.parity = (*p_data >> RFCOMM_RPN_PARITY_SHIFT) & RFCOMM_RPN_PARITY_MASK; p_rx_frame->u.rpn.parity_type = - (*p_data++ >> RFCOMM_RPN_PARITY_TYPE_SHIFT) & - RFCOMM_RPN_PARITY_TYPE_MASK; + (*p_data++ >> RFCOMM_RPN_PARITY_TYPE_SHIFT) & RFCOMM_RPN_PARITY_TYPE_MASK; p_rx_frame->u.rpn.fc_type = *p_data++ & RFCOMM_FC_MASK; p_rx_frame->u.rpn.xon_char = *p_data++; p_rx_frame->u.rpn.xoff_char = *p_data++; - p_rx_frame->u.rpn.param_mask = - (*p_data + (*(p_data + 1) << 8)) & RFCOMM_RPN_PM_MASK; + p_rx_frame->u.rpn.param_mask = (*p_data + (*(p_data + 1) << 8)) & RFCOMM_RPN_PM_MASK; } osi_free(p_buf); - rfc_process_rpn(p_mcb, is_command, p_rx_frame->u.rpn.is_request, - p_rx_frame); + rfc_process_rpn(p_mcb, is_command, p_rx_frame->u.rpn.is_request, p_rx_frame); return; case RFCOMM_MX_RLS: - if (length != RFCOMM_MX_RLS_LEN) break; + if (length != RFCOMM_MX_RLS_LEN) { + break; + } ea = *p_data & RFCOMM_EA; cr = (*p_data & RFCOMM_CR_MASK) >> RFCOMM_SHIFT_CR; @@ -843,8 +843,7 @@ void rfc_process_mx_message(tRFC_MCB* p_mcb, BT_HDR* p_buf) { p_rx_frame->dlci = *p_data++ >> RFCOMM_SHIFT_DLCI; p_rx_frame->u.rls.line_status = (*p_data & ~0x01); - if (!ea || !cr || !p_rx_frame->dlci || - !RFCOMM_VALID_DLCI(p_rx_frame->dlci)) { + if (!ea || !cr || !p_rx_frame->dlci || !RFCOMM_VALID_DLCI(p_rx_frame->dlci)) { log::error("Bad RPN frame"); break; } @@ -857,5 +856,7 @@ void rfc_process_mx_message(tRFC_MCB* p_mcb, BT_HDR* p_buf) { osi_free(p_buf); - if (is_command) rfc_send_nsc(p_mcb); + if (is_command) { + rfc_send_nsc(p_mcb); + } } diff --git a/system/stack/rfcomm/rfc_utils.cc b/system/stack/rfcomm/rfc_utils.cc index 06da90fb13f..b86fed3b53d 100644 --- a/system/stack/rfcomm/rfc_utils.cc +++ b/system/stack/rfcomm/rfc_utils.cc @@ -46,33 +46,29 @@ using namespace bluetooth; * (GSM 07.10 TS 101 369 V6.3.0) ******************************************************************************/ static const uint8_t rfc_crctable[] = { - 0x00, 0x91, 0xE3, 0x72, 0x07, 0x96, 0xE4, 0x75, 0x0E, 0x9F, 0xED, - 0x7C, 0x09, 0x98, 0xEA, 0x7B, 0x1C, 0x8D, 0xFF, 0x6E, 0x1B, 0x8A, - 0xF8, 0x69, 0x12, 0x83, 0xF1, 0x60, 0x15, 0x84, 0xF6, 0x67, 0x38, - 0xA9, 0xDB, 0x4A, 0x3F, 0xAE, 0xDC, 0x4D, 0x36, 0xA7, 0xD5, 0x44, - 0x31, 0xA0, 0xD2, 0x43, 0x24, 0xB5, 0xC7, 0x56, 0x23, 0xB2, 0xC0, - 0x51, 0x2A, 0xBB, 0xC9, 0x58, 0x2D, 0xBC, 0xCE, 0x5F, - - 0x70, 0xE1, 0x93, 0x02, 0x77, 0xE6, 0x94, 0x05, 0x7E, 0xEF, 0x9D, - 0x0C, 0x79, 0xE8, 0x9A, 0x0B, 0x6C, 0xFD, 0x8F, 0x1E, 0x6B, 0xFA, - 0x88, 0x19, 0x62, 0xF3, 0x81, 0x10, 0x65, 0xF4, 0x86, 0x17, 0x48, - 0xD9, 0xAB, 0x3A, 0x4F, 0xDE, 0xAC, 0x3D, 0x46, 0xD7, 0xA5, 0x34, - 0x41, 0xD0, 0xA2, 0x33, 0x54, 0xC5, 0xB7, 0x26, 0x53, 0xC2, 0xB0, - 0x21, 0x5A, 0xCB, 0xB9, 0x28, 0x5D, 0xCC, 0xBE, 0x2F, - - 0xE0, 0x71, 0x03, 0x92, 0xE7, 0x76, 0x04, 0x95, 0xEE, 0x7F, 0x0D, - 0x9C, 0xE9, 0x78, 0x0A, 0x9B, 0xFC, 0x6D, 0x1F, 0x8E, 0xFB, 0x6A, - 0x18, 0x89, 0xF2, 0x63, 0x11, 0x80, 0xF5, 0x64, 0x16, 0x87, 0xD8, - 0x49, 0x3B, 0xAA, 0xDF, 0x4E, 0x3C, 0xAD, 0xD6, 0x47, 0x35, 0xA4, - 0xD1, 0x40, 0x32, 0xA3, 0xC4, 0x55, 0x27, 0xB6, 0xC3, 0x52, 0x20, - 0xB1, 0xCA, 0x5B, 0x29, 0xB8, 0xCD, 0x5C, 0x2E, 0xBF, - - 0x90, 0x01, 0x73, 0xE2, 0x97, 0x06, 0x74, 0xE5, 0x9E, 0x0F, 0x7D, - 0xEC, 0x99, 0x08, 0x7A, 0xEB, 0x8C, 0x1D, 0x6F, 0xFE, 0x8B, 0x1A, - 0x68, 0xF9, 0x82, 0x13, 0x61, 0xF0, 0x85, 0x14, 0x66, 0xF7, 0xA8, - 0x39, 0x4B, 0xDA, 0xAF, 0x3E, 0x4C, 0xDD, 0xA6, 0x37, 0x45, 0xD4, - 0xA1, 0x30, 0x42, 0xD3, 0xB4, 0x25, 0x57, 0xC6, 0xB3, 0x22, 0x50, - 0xC1, 0xBA, 0x2B, 0x59, 0xC8, 0xBD, 0x2C, 0x5E, 0xCF}; + 0x00, 0x91, 0xE3, 0x72, 0x07, 0x96, 0xE4, 0x75, 0x0E, 0x9F, 0xED, 0x7C, 0x09, + 0x98, 0xEA, 0x7B, 0x1C, 0x8D, 0xFF, 0x6E, 0x1B, 0x8A, 0xF8, 0x69, 0x12, 0x83, + 0xF1, 0x60, 0x15, 0x84, 0xF6, 0x67, 0x38, 0xA9, 0xDB, 0x4A, 0x3F, 0xAE, 0xDC, + 0x4D, 0x36, 0xA7, 0xD5, 0x44, 0x31, 0xA0, 0xD2, 0x43, 0x24, 0xB5, 0xC7, 0x56, + 0x23, 0xB2, 0xC0, 0x51, 0x2A, 0xBB, 0xC9, 0x58, 0x2D, 0xBC, 0xCE, 0x5F, + + 0x70, 0xE1, 0x93, 0x02, 0x77, 0xE6, 0x94, 0x05, 0x7E, 0xEF, 0x9D, 0x0C, 0x79, + 0xE8, 0x9A, 0x0B, 0x6C, 0xFD, 0x8F, 0x1E, 0x6B, 0xFA, 0x88, 0x19, 0x62, 0xF3, + 0x81, 0x10, 0x65, 0xF4, 0x86, 0x17, 0x48, 0xD9, 0xAB, 0x3A, 0x4F, 0xDE, 0xAC, + 0x3D, 0x46, 0xD7, 0xA5, 0x34, 0x41, 0xD0, 0xA2, 0x33, 0x54, 0xC5, 0xB7, 0x26, + 0x53, 0xC2, 0xB0, 0x21, 0x5A, 0xCB, 0xB9, 0x28, 0x5D, 0xCC, 0xBE, 0x2F, + + 0xE0, 0x71, 0x03, 0x92, 0xE7, 0x76, 0x04, 0x95, 0xEE, 0x7F, 0x0D, 0x9C, 0xE9, + 0x78, 0x0A, 0x9B, 0xFC, 0x6D, 0x1F, 0x8E, 0xFB, 0x6A, 0x18, 0x89, 0xF2, 0x63, + 0x11, 0x80, 0xF5, 0x64, 0x16, 0x87, 0xD8, 0x49, 0x3B, 0xAA, 0xDF, 0x4E, 0x3C, + 0xAD, 0xD6, 0x47, 0x35, 0xA4, 0xD1, 0x40, 0x32, 0xA3, 0xC4, 0x55, 0x27, 0xB6, + 0xC3, 0x52, 0x20, 0xB1, 0xCA, 0x5B, 0x29, 0xB8, 0xCD, 0x5C, 0x2E, 0xBF, + + 0x90, 0x01, 0x73, 0xE2, 0x97, 0x06, 0x74, 0xE5, 0x9E, 0x0F, 0x7D, 0xEC, 0x99, + 0x08, 0x7A, 0xEB, 0x8C, 0x1D, 0x6F, 0xFE, 0x8B, 0x1A, 0x68, 0xF9, 0x82, 0x13, + 0x61, 0xF0, 0x85, 0x14, 0x66, 0xF7, 0xA8, 0x39, 0x4B, 0xDA, 0xAF, 0x3E, 0x4C, + 0xDD, 0xA6, 0x37, 0x45, 0xD4, 0xA1, 0x30, 0x42, 0xD3, 0xB4, 0x25, 0x57, 0xC6, + 0xB3, 0x22, 0x50, 0xC1, 0xBA, 0x2B, 0x59, 0xC8, 0xBD, 0x2C, 0x5E, 0xCF}; /******************************************************************************* * @@ -93,7 +89,7 @@ uint8_t rfc_calc_fcs(uint16_t len, uint8_t* p) { } /* Ones compliment */ - return (0xFF - fcs); + return 0xFF - fcs; } /******************************************************************************* @@ -119,7 +115,7 @@ bool rfc_check_fcs(uint16_t len, uint8_t* p, uint8_t received_fcs) { fcs = rfc_crctable[fcs ^ received_fcs]; /*0xCF is the reversed order of 11110011.*/ - return (fcs == 0xCF); + return fcs == 0xCF; } /******************************************************************************* @@ -130,34 +126,35 @@ bool rfc_check_fcs(uint16_t len, uint8_t* p, uint8_t received_fcs) { * the address. * ******************************************************************************/ -tRFC_MCB* rfc_alloc_multiplexer_channel(const RawAddress& bd_addr, - bool is_initiator) { +tRFC_MCB* rfc_alloc_multiplexer_channel(const RawAddress& bd_addr, bool is_initiator) { int i, j; tRFC_MCB* p_mcb = NULL; log::verbose("bd_addr:{}, is_initiator:{}", bd_addr, is_initiator); for (i = 0; i < MAX_BD_CONNECTIONS; i++) { - log::verbose("rfc_cb.port.rfc_mcb[{}] - state:{}, bd_addr:{}", i, - rfc_cb.port.rfc_mcb[i].state, rfc_cb.port.rfc_mcb[i].bd_addr); + log::verbose("rfc_cb.port.rfc_mcb[{}] - state:{}, bd_addr:{}", i, rfc_cb.port.rfc_mcb[i].state, + rfc_cb.port.rfc_mcb[i].bd_addr); if ((rfc_cb.port.rfc_mcb[i].state != RFC_MX_STATE_IDLE) && rfc_cb.port.rfc_mcb[i].bd_addr == bd_addr) { /* Multiplexer channel found do not change anything */ /* If there was an inactivity timer running stop it now */ - if (rfc_cb.port.rfc_mcb[i].state == RFC_MX_STATE_CONNECTED) + if (rfc_cb.port.rfc_mcb[i].state == RFC_MX_STATE_CONNECTED) { rfc_timer_stop(&rfc_cb.port.rfc_mcb[i]); + } log::verbose( - "rfc_alloc_multiplexer_channel:is_initiator:{}, found, state:{}, " - "p_mcb:{}", - is_initiator, rfc_cb.port.rfc_mcb[i].state, - fmt::ptr(&rfc_cb.port.rfc_mcb[i])); - return (&rfc_cb.port.rfc_mcb[i]); + "rfc_alloc_multiplexer_channel:is_initiator:{}, found, state:{}, " + "p_mcb:{}", + is_initiator, rfc_cb.port.rfc_mcb[i].state, fmt::ptr(&rfc_cb.port.rfc_mcb[i])); + return &rfc_cb.port.rfc_mcb[i]; } } /* connection with bd_addr does not exist */ for (i = 0, j = rfc_cb.rfc.last_mux + 1; i < MAX_BD_CONNECTIONS; i++, j++) { - if (j >= MAX_BD_CONNECTIONS) j = 0; + if (j >= MAX_BD_CONNECTIONS) { + j = 0; + } p_mcb = &rfc_cb.port.rfc_mcb[j]; if (rfc_cb.port.rfc_mcb[j].state == RFC_MX_STATE_IDLE) { @@ -167,9 +164,9 @@ tRFC_MCB* rfc_alloc_multiplexer_channel(const RawAddress& bd_addr, memset(p_mcb, 0, sizeof(tRFC_MCB)); p_mcb->bd_addr = bd_addr; log::verbose( - "rfc_alloc_multiplexer_channel:is_initiator:{}, create new p_mcb:{}, " - "index:{}", - is_initiator, fmt::ptr(&rfc_cb.port.rfc_mcb[j]), j); + "rfc_alloc_multiplexer_channel:is_initiator:{}, create new p_mcb:{}, " + "index:{}", + is_initiator, fmt::ptr(&rfc_cb.port.rfc_mcb[j]), j); p_mcb->mcb_timer = alarm_new("rfcomm_mcb.mcb_timer"); p_mcb->cmd_q = fixed_queue_new(SIZE_MAX); @@ -179,10 +176,10 @@ tRFC_MCB* rfc_alloc_multiplexer_channel(const RawAddress& bd_addr, rfc_timer_start(p_mcb, RFC_MCB_INIT_INACT_TIMER); rfc_cb.rfc.last_mux = (uint8_t)j; - return (p_mcb); + return p_mcb; } } - return (NULL); + return NULL; } /******************************************************************************* @@ -198,8 +195,9 @@ void rfc_release_multiplexer_channel(tRFC_MCB* p_mcb) { /* Remove the MCB from the ports */ for (int i = 0; i < MAX_RFC_PORTS; i++) { - if (rfc_cb.port.port[i].rfc.p_mcb == p_mcb) + if (rfc_cb.port.port[i].rfc.p_mcb == p_mcb) { rfc_cb.port.port[i].rfc.p_mcb = NULL; + } } rfc_timer_stop(p_mcb); @@ -222,8 +220,7 @@ void rfc_timer_start(tRFC_MCB* p_mcb, uint16_t timeout) { log::verbose("- timeout:{} seconds", timeout); uint64_t interval_ms = timeout * 1000; - alarm_set_on_mloop(p_mcb->mcb_timer, interval_ms, rfcomm_mcb_timer_timeout, - p_mcb); + alarm_set_on_mloop(p_mcb->mcb_timer, interval_ms, rfcomm_mcb_timer_timeout, p_mcb); } /******************************************************************************* @@ -250,8 +247,7 @@ void rfc_port_timer_start(tPORT* p_port, uint16_t timeout) { log::verbose("- timeout:{} seconds", timeout); uint64_t interval_ms = timeout * 1000; - alarm_set_on_mloop(p_port->rfc.port_timer, interval_ms, - rfcomm_port_timer_timeout, p_port); + alarm_set_on_mloop(p_port->rfc.port_timer, interval_ms, rfcomm_port_timer_timeout, p_port); } /******************************************************************************* @@ -291,8 +287,9 @@ void rfc_check_mcb_active(tRFC_MCB* p_mcb) { if (p_mcb->is_disc_initiator) { p_mcb->is_disc_initiator = false; rfc_mx_sm_execute(p_mcb, RFC_MX_EVENT_CLOSE_REQ, NULL); - } else + } else { rfc_timer_start(p_mcb, RFC_MCB_RELEASE_INACT_TIMER); + } } void rfcomm_port_timer_timeout(void* data) { @@ -317,18 +314,16 @@ void rfcomm_mcb_timer_timeout(void* data) { * Returns void * ******************************************************************************/ -void rfc_sec_check_complete(RawAddress /* bd_addr */, - tBT_TRANSPORT /* transport */, void* p_ref_data, - tBTM_STATUS res) { - log::assert_that(p_ref_data != nullptr, - "assert failed: p_ref_data != nullptr"); +void rfc_sec_check_complete(RawAddress /* bd_addr */, tBT_TRANSPORT /* transport */, + void* p_ref_data, tBTM_STATUS res) { + log::assert_that(p_ref_data != nullptr, "assert failed: p_ref_data != nullptr"); tPORT* p_port = (tPORT*)p_ref_data; /* Verify that PORT is still waiting for Security to complete */ - if (!p_port->in_use || - ((p_port->rfc.state != RFC_STATE_ORIG_WAIT_SEC_CHECK) && - (p_port->rfc.state != RFC_STATE_TERM_WAIT_SEC_CHECK))) + if (!p_port->in_use || ((p_port->rfc.state != RFC_STATE_ORIG_WAIT_SEC_CHECK) && + (p_port->rfc.state != RFC_STATE_TERM_WAIT_SEC_CHECK))) { return; + } rfc_port_sm_execute((tPORT*)p_ref_data, RFC_PORT_EVENT_SEC_COMPLETE, &res); } @@ -378,7 +373,9 @@ void rfc_inc_credit(tPORT* p_port, uint8_t credit) { log::verbose("rfc_inc_credit:{}", p_port->credit_tx); - if (p_port->tx.peer_fc) PORT_FlowInd(p_port->rfc.p_mcb, p_port->dlci, true); + if (p_port->tx.peer_fc) { + PORT_FlowInd(p_port->rfc.p_mcb, p_port->dlci, true); + } } } @@ -395,9 +392,13 @@ void rfc_inc_credit(tPORT* p_port, uint8_t credit) { ******************************************************************************/ void rfc_dec_credit(tPORT* p_port) { if (p_port->rfc.p_mcb->flow == PORT_FC_CREDIT) { - if (p_port->credit_tx > 0) p_port->credit_tx--; + if (p_port->credit_tx > 0) { + p_port->credit_tx--; + } - if (p_port->credit_tx == 0) p_port->tx.peer_fc = true; + if (p_port->credit_tx == 0) { + p_port->tx.peer_fc = true; + } } } @@ -415,9 +416,8 @@ void rfc_check_send_cmd(tRFC_MCB* p_mcb, BT_HDR* p_buf) { /* if passed a buffer queue it */ if (p_buf != NULL) { if (p_mcb->cmd_q == NULL) { - log::error("empty queue: p_mcb = {} p_mcb->lcid = {} cached p_mcb = {}", - fmt::ptr(p_mcb), p_mcb->lcid, - fmt::ptr(rfc_find_lcid_mcb(p_mcb->lcid))); + log::error("empty queue: p_mcb = {} p_mcb->lcid = {} cached p_mcb = {}", fmt::ptr(p_mcb), + p_mcb->lcid, fmt::ptr(rfc_find_lcid_mcb(p_mcb->lcid))); } fixed_queue_enqueue(p_mcb->cmd_q, p_buf); } @@ -425,10 +425,12 @@ void rfc_check_send_cmd(tRFC_MCB* p_mcb, BT_HDR* p_buf) { /* handle queue if L2CAP not congested */ while (!p_mcb->l2cap_congested) { BT_HDR* p = (BT_HDR*)fixed_queue_try_dequeue(p_mcb->cmd_q); - if (p == NULL) break; + if (p == NULL) { + break; + } if (L2CA_DataWrite(p_mcb->lcid, p) != tL2CAP_DW_RESULT::SUCCESS) { - log::warn("Unable to write L2CAP data peer:{} cid:{} len:{}", - p_mcb->bd_addr, p_mcb->lcid, p->len); + log::warn("Unable to write L2CAP data peer:{} cid:{} len:{}", p_mcb->bd_addr, p_mcb->lcid, + p->len); } } } diff --git a/system/stack/rnr/remote_name_request.h b/system/stack/rnr/remote_name_request.h index 44e6fac241d..165d1dccd9e 100644 --- a/system/stack/rnr/remote_name_request.h +++ b/system/stack/rnr/remote_name_request.h @@ -37,14 +37,13 @@ namespace bluetooth { namespace rnr { class RemoteNameRequest { - public: +public: tBTM_NAME_CMPL_CB* p_remname_cmpl_cb{nullptr}; alarm_t* remote_name_timer{nullptr}; - RawAddress remname_bda{}; /* Name of bd addr for active remote name request */ - bool remname_active{ - false}; /* State of a remote name request by external API */ + RawAddress remname_bda{}; /* Name of bd addr for active remote name request */ + bool remname_active{false}; /* State of a remote name request by external API */ tBT_DEVICE_TYPE remname_dev_type{ - BT_DEVICE_TYPE_UNKNOWN}; /* Whether it's LE or BREDR name request */ + BT_DEVICE_TYPE_UNKNOWN}; /* Whether it's LE or BREDR name request */ #define BTM_SEC_MAX_RMT_NAME_CALLBACKS 2 tBTM_RMT_NAME_CALLBACK* p_rmt_name_callback[BTM_SEC_MAX_RMT_NAME_CALLBACKS]{nullptr, nullptr}; }; diff --git a/system/stack/sdp/internal/sdp_api.h b/system/stack/sdp/internal/sdp_api.h index 8dd935f8411..ad34eade635 100644 --- a/system/stack/sdp/internal/sdp_api.h +++ b/system/stack/sdp/internal/sdp_api.h @@ -37,9 +37,9 @@ * Returns true if successful, false if one or more parameters are bad * ******************************************************************************/ -bool SDP_InitDiscoveryDb(tSDP_DISCOVERY_DB* p_db, uint32_t len, - uint16_t num_uuid, const bluetooth::Uuid* p_uuid_list, - uint16_t num_attr, const uint16_t* p_attr_list); +bool SDP_InitDiscoveryDb(tSDP_DISCOVERY_DB* p_db, uint32_t len, uint16_t num_uuid, + const bluetooth::Uuid* p_uuid_list, uint16_t num_attr, + const uint16_t* p_attr_list); /******************************************************************************* * @@ -62,8 +62,8 @@ bool SDP_CancelServiceSearch(const tSDP_DISCOVERY_DB* p_db); * Returns true if discovery started, false if failed. * ******************************************************************************/ -bool SDP_ServiceSearchRequest(const RawAddress& p_bd_addr, - tSDP_DISCOVERY_DB* p_db, tSDP_DISC_CMPL_CB* p_cb); +bool SDP_ServiceSearchRequest(const RawAddress& p_bd_addr, tSDP_DISCOVERY_DB* p_db, + tSDP_DISC_CMPL_CB* p_cb); /******************************************************************************* * @@ -78,8 +78,7 @@ bool SDP_ServiceSearchRequest(const RawAddress& p_bd_addr, * Returns true if discovery started, false if failed. * ******************************************************************************/ -bool SDP_ServiceSearchAttributeRequest(const RawAddress& p_bd_addr, - tSDP_DISCOVERY_DB* p_db, +bool SDP_ServiceSearchAttributeRequest(const RawAddress& p_bd_addr, tSDP_DISCOVERY_DB* p_db, tSDP_DISC_CMPL_CB* p_cb); /******************************************************************************* @@ -97,8 +96,8 @@ bool SDP_ServiceSearchAttributeRequest(const RawAddress& p_bd_addr, * ******************************************************************************/ bool SDP_ServiceSearchAttributeRequest2( - const RawAddress& p_bd_addr, tSDP_DISCOVERY_DB* p_db, - base::RepeatingCallback complete_callback); + const RawAddress& p_bd_addr, tSDP_DISCOVERY_DB* p_db, + base::RepeatingCallback complete_callback); /* API of utilities to find data in the local discovery database */ @@ -112,8 +111,7 @@ bool SDP_ServiceSearchAttributeRequest2( * Returns Pointer to matching attribute entry, or NULL * ******************************************************************************/ -tSDP_DISC_ATTR* SDP_FindAttributeInRec(const tSDP_DISC_REC* p_rec, - uint16_t attr_id); +tSDP_DISC_ATTR* SDP_FindAttributeInRec(const tSDP_DISC_REC* p_rec, uint16_t attr_id); /******************************************************************************* * @@ -127,8 +125,7 @@ tSDP_DISC_ATTR* SDP_FindAttributeInRec(const tSDP_DISC_REC* p_rec, * Returns Pointer to record containing service class, or NULL * ******************************************************************************/ -tSDP_DISC_REC* SDP_FindServiceInDb(const tSDP_DISCOVERY_DB* p_db, - uint16_t service_uuid, +tSDP_DISC_REC* SDP_FindServiceInDb(const tSDP_DISCOVERY_DB* p_db, uint16_t service_uuid, tSDP_DISC_REC* p_start_rec); /******************************************************************************* @@ -147,8 +144,7 @@ tSDP_DISC_REC* SDP_FindServiceInDb(const tSDP_DISCOVERY_DB* p_db, * Returns Pointer to record containing service class, or NULL * ******************************************************************************/ -tSDP_DISC_REC* SDP_FindServiceUUIDInDb(const tSDP_DISCOVERY_DB* p_db, - const bluetooth::Uuid& uuid, +tSDP_DISC_REC* SDP_FindServiceUUIDInDb(const tSDP_DISCOVERY_DB* p_db, const bluetooth::Uuid& uuid, tSDP_DISC_REC* p_start_rec); /******************************************************************************* @@ -164,8 +160,7 @@ tSDP_DISC_REC* SDP_FindServiceUUIDInDb(const tSDP_DISCOVERY_DB* p_db, * Returns true if found, otherwise false. * ******************************************************************************/ -bool SDP_FindServiceUUIDInRec_128bit(const tSDP_DISC_REC* p_rec, - bluetooth::Uuid* p_uuid); +bool SDP_FindServiceUUIDInRec_128bit(const tSDP_DISC_REC* p_rec, bluetooth::Uuid* p_uuid); /******************************************************************************* * @@ -180,8 +175,7 @@ bool SDP_FindServiceUUIDInRec_128bit(const tSDP_DISC_REC* p_rec, * Returns true if found, otherwise false. * ******************************************************************************/ -bool SDP_FindServiceUUIDInRec(const tSDP_DISC_REC* p_rec, - bluetooth::Uuid* p_uuid); +bool SDP_FindServiceUUIDInRec(const tSDP_DISC_REC* p_rec, bluetooth::Uuid* p_uuid); /******************************************************************************* * @@ -209,8 +203,7 @@ tSDP_DISC_REC* SDP_FindServiceInDb_128bit(const tSDP_DISCOVERY_DB* p_db, * If found, the passed protocol list element is filled in. * ******************************************************************************/ -bool SDP_FindProtocolListElemInRec(const tSDP_DISC_REC* p_rec, - uint16_t layer_uuid, +bool SDP_FindProtocolListElemInRec(const tSDP_DISC_REC* p_rec, uint16_t layer_uuid, tSDP_PROTOCOL_ELEM* p_elem); /******************************************************************************* @@ -227,8 +220,8 @@ bool SDP_FindProtocolListElemInRec(const tSDP_DISC_REC* p_rec, * passed in are filled in. * ******************************************************************************/ -bool SDP_FindProfileVersionInRec(const tSDP_DISC_REC* p_rec, - uint16_t profile_uuid, uint16_t* p_version); +bool SDP_FindProfileVersionInRec(const tSDP_DISC_REC* p_rec, uint16_t profile_uuid, + uint16_t* p_version); /* API into SDP for local service database updates */ @@ -275,8 +268,8 @@ bool SDP_DeleteRecord(uint32_t handle); * Returns true if added OK, else false * ******************************************************************************/ -bool SDP_AddAttribute(uint32_t handle, uint16_t attr_id, uint8_t attr_type, - uint32_t attr_len, uint8_t* p_val); +bool SDP_AddAttribute(uint32_t handle, uint16_t attr_id, uint8_t attr_type, uint32_t attr_len, + uint8_t* p_val); /******************************************************************************* * @@ -292,8 +285,8 @@ bool SDP_AddAttribute(uint32_t handle, uint16_t attr_id, uint8_t attr_type, * Returns true if added OK, else false * ******************************************************************************/ -bool SDP_AddSequence(uint32_t handle, uint16_t attr_id, uint16_t num_elem, - uint8_t type[], uint8_t len[], uint8_t* p_val[]); +bool SDP_AddSequence(uint32_t handle, uint16_t attr_id, uint16_t num_elem, uint8_t type[], + uint8_t len[], uint8_t* p_val[]); /******************************************************************************* * @@ -307,8 +300,7 @@ bool SDP_AddSequence(uint32_t handle, uint16_t attr_id, uint16_t num_elem, * Returns true if added OK, else false * ******************************************************************************/ -bool SDP_AddUuidSequence(uint32_t handle, uint16_t attr_id, uint16_t num_uuids, - uint16_t* p_uuids); +bool SDP_AddUuidSequence(uint32_t handle, uint16_t attr_id, uint16_t num_uuids, uint16_t* p_uuids); /******************************************************************************* * @@ -322,8 +314,7 @@ bool SDP_AddUuidSequence(uint32_t handle, uint16_t attr_id, uint16_t num_uuids, * Returns true if added OK, else false * ******************************************************************************/ -bool SDP_AddProtocolList(uint32_t handle, uint16_t num_elem, - tSDP_PROTOCOL_ELEM* p_elem_list); +bool SDP_AddProtocolList(uint32_t handle, uint16_t num_elem, tSDP_PROTOCOL_ELEM* p_elem_list); /******************************************************************************* * @@ -352,8 +343,7 @@ bool SDP_AddAdditionProtoLists(uint32_t handle, uint16_t num_elem, * Returns true if added OK, else false * ******************************************************************************/ -bool SDP_AddProfileDescriptorList(uint32_t handle, uint16_t profile_uuid, - uint16_t version); +bool SDP_AddProfileDescriptorList(uint32_t handle, uint16_t profile_uuid, uint16_t version); /******************************************************************************* * @@ -367,8 +357,8 @@ bool SDP_AddProfileDescriptorList(uint32_t handle, uint16_t profile_uuid, * Returns true if added OK, else false * ******************************************************************************/ -bool SDP_AddLanguageBaseAttrIDList(uint32_t handle, uint16_t lang, - uint16_t char_enc, uint16_t base_id); +bool SDP_AddLanguageBaseAttrIDList(uint32_t handle, uint16_t lang, uint16_t char_enc, + uint16_t base_id); /******************************************************************************* * @@ -382,8 +372,7 @@ bool SDP_AddLanguageBaseAttrIDList(uint32_t handle, uint16_t lang, * Returns true if added OK, else false * ******************************************************************************/ -bool SDP_AddServiceClassIdList(uint32_t handle, uint16_t num_services, - uint16_t* p_service_uuids); +bool SDP_AddServiceClassIdList(uint32_t handle, uint16_t num_services, uint16_t* p_service_uuids); /* Device Identification APIs */ @@ -396,8 +385,7 @@ bool SDP_AddServiceClassIdList(uint32_t handle, uint16_t num_services, * Returns Returns SDP_SUCCESS if record added successfully, else error * ******************************************************************************/ -uint16_t SDP_SetLocalDiRecord(const tSDP_DI_RECORD* device_info, - uint32_t* p_handle); +uint16_t SDP_SetLocalDiRecord(const tSDP_DI_RECORD* device_info, uint32_t* p_handle); /******************************************************************************* * @@ -408,8 +396,7 @@ uint16_t SDP_SetLocalDiRecord(const tSDP_DI_RECORD* device_info, * Returns SDP_SUCCESS if query started successfully, else error * ******************************************************************************/ -tSDP_STATUS SDP_DiDiscover(const RawAddress& remote_device, - tSDP_DISCOVERY_DB* p_db, uint32_t len, +tSDP_STATUS SDP_DiDiscover(const RawAddress& remote_device, tSDP_DISCOVERY_DB* p_db, uint32_t len, tSDP_DISC_CMPL_CB* p_cb); /******************************************************************************* @@ -433,6 +420,5 @@ uint8_t SDP_GetNumDiRecords(const tSDP_DISCOVERY_DB* p_db); * Returns SDP_SUCCESS if record retrieved, else error * ******************************************************************************/ -uint16_t SDP_GetDiRecord(uint8_t getRecordIndex, - tSDP_DI_GET_RECORD* device_info, +uint16_t SDP_GetDiRecord(uint8_t getRecordIndex, tSDP_DI_GET_RECORD* device_info, const tSDP_DISCOVERY_DB* p_db); diff --git a/system/stack/sdp/sdp_api.cc b/system/stack/sdp/sdp_api.cc index b19652e0bc1..0ffa420aa6d 100644 --- a/system/stack/sdp/sdp_api.cc +++ b/system/stack/sdp/sdp_api.cc @@ -67,20 +67,17 @@ using namespace bluetooth; * false if one or more parameters are bad * ******************************************************************************/ -bool SDP_InitDiscoveryDb(tSDP_DISCOVERY_DB* p_db, uint32_t len, - uint16_t num_uuid, const Uuid* p_uuid_list, - uint16_t num_attr, const uint16_t* p_attr_list) { +bool SDP_InitDiscoveryDb(tSDP_DISCOVERY_DB* p_db, uint32_t len, uint16_t num_uuid, + const Uuid* p_uuid_list, uint16_t num_attr, const uint16_t* p_attr_list) { uint16_t xx; /* verify the parameters */ - if (p_db == NULL || (sizeof(tSDP_DISCOVERY_DB) > len) || - num_attr > SDP_MAX_ATTR_FILTERS || num_uuid > SDP_MAX_UUID_FILTERS) { - log::error( - "SDP_InitDiscoveryDb Illegal param: p_db {}, len {}, num_uuid {}, " - "num_attr {}", - fmt::ptr(p_db), len, num_uuid, num_attr); - - return (false); + if (p_db == NULL || (sizeof(tSDP_DISCOVERY_DB) > len) || num_attr > SDP_MAX_ATTR_FILTERS || + num_uuid > SDP_MAX_UUID_FILTERS) { + log::error("SDP_InitDiscoveryDb Illegal param: p_db {}, len {}, num_uuid {}, num_attr {}", + fmt::ptr(p_db), len, num_uuid, num_attr); + + return false; } memset(p_db, 0, (size_t)len); @@ -90,17 +87,21 @@ bool SDP_InitDiscoveryDb(tSDP_DISCOVERY_DB* p_db, uint32_t len, p_db->p_first_rec = NULL; p_db->p_free_mem = (uint8_t*)(p_db + 1); - for (xx = 0; xx < num_uuid; xx++) p_db->uuid_filters[xx] = *p_uuid_list++; + for (xx = 0; xx < num_uuid; xx++) { + p_db->uuid_filters[xx] = *p_uuid_list++; + } p_db->num_uuid_filters = num_uuid; - for (xx = 0; xx < num_attr; xx++) p_db->attr_filters[xx] = *p_attr_list++; + for (xx = 0; xx < num_attr; xx++) { + p_db->attr_filters[xx] = *p_attr_list++; + } /* sort attributes */ sdpu_sort_attr_list(num_attr, p_db); p_db->num_attr_filters = num_attr; - return (true); + return true; } /******************************************************************************* @@ -115,11 +116,13 @@ bool SDP_InitDiscoveryDb(tSDP_DISCOVERY_DB* p_db, uint32_t len, ******************************************************************************/ bool SDP_CancelServiceSearch(const tSDP_DISCOVERY_DB* p_db) { tCONN_CB* p_ccb = sdpu_find_ccb_by_db(p_db); - if (!p_ccb) return (false); + if (!p_ccb) { + return false; + } sdp_disconnect(p_ccb, SDP_CANCEL); p_ccb->disc_state = SDP_DISC_WAIT_CANCEL; - return (true); + return true; } /******************************************************************************* @@ -131,21 +134,22 @@ bool SDP_CancelServiceSearch(const tSDP_DISCOVERY_DB* p_db) { * Returns true if discovery started, false if failed. * ******************************************************************************/ -bool SDP_ServiceSearchRequest(const RawAddress& bd_addr, - tSDP_DISCOVERY_DB* p_db, +bool SDP_ServiceSearchRequest(const RawAddress& bd_addr, tSDP_DISCOVERY_DB* p_db, tSDP_DISC_CMPL_CB* p_cb) { tCONN_CB* p_ccb; /* Specific BD address */ p_ccb = sdp_conn_originate(bd_addr); - if (!p_ccb) return (false); + if (!p_ccb) { + return false; + } p_ccb->disc_state = SDP_DISC_WAIT_CONN; p_ccb->p_db = p_db; p_ccb->p_cb = p_cb; - return (true); + return true; } /******************************************************************************* @@ -162,15 +166,16 @@ bool SDP_ServiceSearchRequest(const RawAddress& bd_addr, * Returns true if discovery started, false if failed. * ******************************************************************************/ -bool SDP_ServiceSearchAttributeRequest(const RawAddress& bd_addr, - tSDP_DISCOVERY_DB* p_db, +bool SDP_ServiceSearchAttributeRequest(const RawAddress& bd_addr, tSDP_DISCOVERY_DB* p_db, tSDP_DISC_CMPL_CB* p_cb) { tCONN_CB* p_ccb; /* Specific BD address */ p_ccb = sdp_conn_originate(bd_addr); - if (!p_ccb) return (false); + if (!p_ccb) { + return false; + } p_ccb->disc_state = SDP_DISC_WAIT_CONN; p_ccb->p_db = p_db; @@ -178,7 +183,7 @@ bool SDP_ServiceSearchAttributeRequest(const RawAddress& bd_addr, p_ccb->is_attr_search = true; - return (true); + return true; } /******************************************************************************* * @@ -195,14 +200,16 @@ bool SDP_ServiceSearchAttributeRequest(const RawAddress& bd_addr, * ******************************************************************************/ bool SDP_ServiceSearchAttributeRequest2( - const RawAddress& bd_addr, tSDP_DISCOVERY_DB* p_db, - base::RepeatingCallback complete_callback) { + const RawAddress& bd_addr, tSDP_DISCOVERY_DB* p_db, + base::RepeatingCallback complete_callback) { tCONN_CB* p_ccb; /* Specific BD address */ p_ccb = sdp_conn_originate(bd_addr); - if (!p_ccb) return (false); + if (!p_ccb) { + return false; + } p_ccb->disc_state = SDP_DISC_WAIT_CONN; p_ccb->p_db = p_db; @@ -210,7 +217,7 @@ bool SDP_ServiceSearchAttributeRequest2( p_ccb->is_attr_search = true; - return (true); + return true; } /******************************************************************************* @@ -223,19 +230,20 @@ bool SDP_ServiceSearchAttributeRequest2( * Returns Pointer to matching attribute entry, or NULL * ******************************************************************************/ -tSDP_DISC_ATTR* SDP_FindAttributeInRec(const tSDP_DISC_REC* p_rec, - uint16_t attr_id) { +tSDP_DISC_ATTR* SDP_FindAttributeInRec(const tSDP_DISC_REC* p_rec, uint16_t attr_id) { tSDP_DISC_ATTR* p_attr; p_attr = p_rec->p_first_attr; while (p_attr) { - if (p_attr->attr_id == attr_id) return (p_attr); + if (p_attr->attr_id == attr_id) { + return p_attr; + } p_attr = p_attr->p_next_attr; } /* If here, no matching attribute found */ - return (NULL); + return NULL; } /******************************************************************************* @@ -259,20 +267,17 @@ bool SDP_FindServiceUUIDInRec(const tSDP_DISC_REC* p_rec, Uuid* p_uuid) { while (p_attr) { if ((p_attr->attr_id == ATTR_ID_SERVICE_CLASS_ID_LIST) && (SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == DATA_ELE_SEQ_DESC_TYPE)) { - for (p_sattr = p_attr->attr_value.v.p_sub_attr; p_sattr; - p_sattr = p_sattr->p_next_attr) { + for (p_sattr = p_attr->attr_value.v.p_sub_attr; p_sattr; p_sattr = p_sattr->p_next_attr) { if (SDP_DISC_ATTR_TYPE(p_sattr->attr_len_type) == UUID_DESC_TYPE) { if (SDP_DISC_ATTR_LEN(p_sattr->attr_len_type) == Uuid::kNumBytes16) { *p_uuid = Uuid::From16Bit(p_sattr->attr_value.v.u16); - } else if (SDP_DISC_ATTR_LEN(p_sattr->attr_len_type) == - Uuid::kNumBytes128) { + } else if (SDP_DISC_ATTR_LEN(p_sattr->attr_len_type) == Uuid::kNumBytes128) { *p_uuid = Uuid::From128BitBE(p_sattr->attr_value.v.array); - } else if (SDP_DISC_ATTR_LEN(p_sattr->attr_len_type) == - Uuid::kNumBytes32) { + } else if (SDP_DISC_ATTR_LEN(p_sattr->attr_len_type) == Uuid::kNumBytes32) { *p_uuid = Uuid::From32Bit(p_sattr->attr_value.v.u32); } - return (true); + return true; } /* Checking for Toyota G Block Car Kit: @@ -280,18 +285,16 @@ bool SDP_FindServiceUUIDInRec(const tSDP_DISC_REC* p_rec, Uuid* p_uuid) { ** where the UUID is suppose to be!!! */ else { - if (SDP_DISC_ATTR_TYPE(p_sattr->attr_len_type) == - DATA_ELE_SEQ_DESC_TYPE) { + if (SDP_DISC_ATTR_TYPE(p_sattr->attr_len_type) == DATA_ELE_SEQ_DESC_TYPE) { /* Look through data element sequence until no more UUIDs */ - for (p_extra_sattr = p_sattr->attr_value.v.p_sub_attr; - p_extra_sattr; p_extra_sattr = p_extra_sattr->p_next_attr) { + for (p_extra_sattr = p_sattr->attr_value.v.p_sub_attr; p_extra_sattr; + p_extra_sattr = p_extra_sattr->p_next_attr) { /* Increment past this to see if the next attribut is UUID */ - if ((SDP_DISC_ATTR_TYPE(p_extra_sattr->attr_len_type) == - UUID_DESC_TYPE) + if ((SDP_DISC_ATTR_TYPE(p_extra_sattr->attr_len_type) == UUID_DESC_TYPE) /* only support 16 bits UUID for now */ && (SDP_DISC_ATTR_LEN(p_extra_sattr->attr_len_type) == 2)) { *p_uuid = Uuid::From16Bit(p_extra_sattr->attr_value.v.u16); - return (true); + return true; } } } @@ -303,7 +306,7 @@ bool SDP_FindServiceUUIDInRec(const tSDP_DISC_REC* p_rec, Uuid* p_uuid) { /* only support 16 bits UUID for now */ && (SDP_DISC_ATTR_LEN(p_attr->attr_len_type) == 2)) { *p_uuid = Uuid::From16Bit(p_attr->attr_value.v.u16); - return (true); + return true; } } p_attr = p_attr->p_next_attr; @@ -336,7 +339,7 @@ bool SDP_FindServiceUUIDInRec_128bit(const tSDP_DISC_REC* p_rec, Uuid* p_uuid) { if (SDP_DISC_ATTR_LEN(p_sattr->attr_len_type) == 16) { *p_uuid = Uuid::From128BitBE(p_sattr->attr_value.v.array); } - return (true); + return true; } p_sattr = p_sattr->p_next_attr; @@ -347,7 +350,7 @@ bool SDP_FindServiceUUIDInRec_128bit(const tSDP_DISC_REC* p_rec, Uuid* p_uuid) { /* only support 128 bits UUID for now */ && (SDP_DISC_ATTR_LEN(p_attr->attr_len_type) == 16)) { *p_uuid = Uuid::From128BitBE(p_attr->attr_value.v.array); - return (true); + return true; } } p_attr = p_attr->p_next_attr; @@ -367,50 +370,47 @@ bool SDP_FindServiceUUIDInRec_128bit(const tSDP_DISC_REC* p_rec, Uuid* p_uuid) { * Returns Pointer to record containing service class, or NULL * ******************************************************************************/ -tSDP_DISC_REC* SDP_FindServiceInDb(const tSDP_DISCOVERY_DB* p_db, - uint16_t service_uuid, +tSDP_DISC_REC* SDP_FindServiceInDb(const tSDP_DISCOVERY_DB* p_db, uint16_t service_uuid, tSDP_DISC_REC* p_start_rec) { tSDP_DISC_REC* p_rec; tSDP_DISC_ATTR *p_attr, *p_sattr, *p_extra_sattr; /* Must have a valid database */ - if (p_db == NULL) return (NULL); + if (p_db == NULL) { + return NULL; + } - if (!p_start_rec) + if (!p_start_rec) { p_rec = p_db->p_first_rec; - else + } else { p_rec = p_start_rec->p_next_rec; + } while (p_rec) { p_attr = p_rec->p_first_attr; while (p_attr) { if ((p_attr->attr_id == ATTR_ID_SERVICE_CLASS_ID_LIST) && - (SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == - DATA_ELE_SEQ_DESC_TYPE)) { - for (p_sattr = p_attr->attr_value.v.p_sub_attr; p_sattr; - p_sattr = p_sattr->p_next_attr) { + (SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == DATA_ELE_SEQ_DESC_TYPE)) { + for (p_sattr = p_attr->attr_value.v.p_sub_attr; p_sattr; p_sattr = p_sattr->p_next_attr) { if ((SDP_DISC_ATTR_TYPE(p_sattr->attr_len_type) == UUID_DESC_TYPE) && (SDP_DISC_ATTR_LEN(p_sattr->attr_len_type) == 2)) { - log::verbose( - "SDP_FindServiceInDb - p_sattr value = 0x{:x} serviceuuid = " - "0x{:x}", - p_sattr->attr_value.v.u16, service_uuid); + log::verbose("SDP_FindServiceInDb - p_sattr value = 0x{:x} serviceuuid = 0x{:x}", + p_sattr->attr_value.v.u16, service_uuid); if (service_uuid == UUID_SERVCLASS_HDP_PROFILE) { if ((p_sattr->attr_value.v.u16 == UUID_SERVCLASS_HDP_SOURCE) || (p_sattr->attr_value.v.u16 == UUID_SERVCLASS_HDP_SINK)) { log::verbose("SDP_FindServiceInDb found HDP source or sink\n"); - return (p_rec); + return p_rec; } } } if (SDP_DISC_ATTR_TYPE(p_sattr->attr_len_type) == UUID_DESC_TYPE && - (service_uuid == 0 || - (SDP_DISC_ATTR_LEN(p_sattr->attr_len_type) == 2 && - p_sattr->attr_value.v.u16 == service_uuid))) + (service_uuid == 0 || (SDP_DISC_ATTR_LEN(p_sattr->attr_len_type) == 2 && + p_sattr->attr_value.v.u16 == service_uuid))) /* for a specific uuid, or any one */ { - return (p_rec); + return p_rec; } /* Checking for Toyota G Block Car Kit: @@ -418,19 +418,16 @@ tSDP_DISC_REC* SDP_FindServiceInDb(const tSDP_DISCOVERY_DB* p_db, ** where the UUID is suppose to be!!! */ else { - if (SDP_DISC_ATTR_TYPE(p_sattr->attr_len_type) == - DATA_ELE_SEQ_DESC_TYPE) { + if (SDP_DISC_ATTR_TYPE(p_sattr->attr_len_type) == DATA_ELE_SEQ_DESC_TYPE) { /* Look through data element sequence until no more UUIDs */ - for (p_extra_sattr = p_sattr->attr_value.v.p_sub_attr; - p_extra_sattr; p_extra_sattr = p_extra_sattr->p_next_attr) { + for (p_extra_sattr = p_sattr->attr_value.v.p_sub_attr; p_extra_sattr; + p_extra_sattr = p_extra_sattr->p_next_attr) { /* Increment past this to see if the next attribut is UUID */ - if ((SDP_DISC_ATTR_TYPE(p_extra_sattr->attr_len_type) == - UUID_DESC_TYPE) && + if ((SDP_DISC_ATTR_TYPE(p_extra_sattr->attr_len_type) == UUID_DESC_TYPE) && (SDP_DISC_ATTR_LEN(p_extra_sattr->attr_len_type) == 2) /* for a specific uuid, or any one */ - && ((p_extra_sattr->attr_value.v.u16 == service_uuid) || - (service_uuid == 0))) { - return (p_rec); + && ((p_extra_sattr->attr_value.v.u16 == service_uuid) || (service_uuid == 0))) { + return p_rec; } } } @@ -441,9 +438,9 @@ tSDP_DISC_REC* SDP_FindServiceInDb(const tSDP_DISCOVERY_DB* p_db, if ((SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == UUID_DESC_TYPE) && (SDP_DISC_ATTR_LEN(p_attr->attr_len_type) == 2) /* find a specific UUID or anyone */ - && - ((p_attr->attr_value.v.u16 == service_uuid) || service_uuid == 0)) - return (p_rec); + && ((p_attr->attr_value.v.u16 == service_uuid) || service_uuid == 0)) { + return p_rec; + } } p_attr = p_attr->p_next_attr; @@ -452,7 +449,7 @@ tSDP_DISC_REC* SDP_FindServiceInDb(const tSDP_DISCOVERY_DB* p_db, p_rec = p_rec->p_next_rec; } /* If here, no matching UUID found */ - return (NULL); + return NULL; } /******************************************************************************* @@ -476,31 +473,33 @@ tSDP_DISC_REC* SDP_FindServiceInDb_128bit(const tSDP_DISCOVERY_DB* p_db, tSDP_DISC_ATTR *p_attr, *p_sattr; /* Must have a valid database */ - if (p_db == NULL) return (NULL); + if (p_db == NULL) { + return NULL; + } - if (!p_start_rec) + if (!p_start_rec) { p_rec = p_db->p_first_rec; - else + } else { p_rec = p_start_rec->p_next_rec; + } while (p_rec) { p_attr = p_rec->p_first_attr; while (p_attr) { if ((p_attr->attr_id == ATTR_ID_SERVICE_CLASS_ID_LIST) && - (SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == - DATA_ELE_SEQ_DESC_TYPE)) { - for (p_sattr = p_attr->attr_value.v.p_sub_attr; p_sattr; - p_sattr = p_sattr->p_next_attr) { + (SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == DATA_ELE_SEQ_DESC_TYPE)) { + for (p_sattr = p_attr->attr_value.v.p_sub_attr; p_sattr; p_sattr = p_sattr->p_next_attr) { if ((SDP_DISC_ATTR_TYPE(p_sattr->attr_len_type) == UUID_DESC_TYPE) && (SDP_DISC_ATTR_LEN(p_sattr->attr_len_type) == 16)) { - return (p_rec); + return p_rec; } } break; } else if (p_attr->attr_id == ATTR_ID_SERVICE_ID) { if ((SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == UUID_DESC_TYPE) && - (SDP_DISC_ATTR_LEN(p_attr->attr_len_type) == 16)) - return (p_rec); + (SDP_DISC_ATTR_LEN(p_attr->attr_len_type) == 16)) { + return p_rec; + } } p_attr = p_attr->p_next_attr; @@ -509,7 +508,7 @@ tSDP_DISC_REC* SDP_FindServiceInDb_128bit(const tSDP_DISCOVERY_DB* p_db, p_rec = p_rec->p_next_rec; } /* If here, no matching UUID found */ - return (NULL); + return NULL; } /******************************************************************************* @@ -528,36 +527,40 @@ tSDP_DISC_REC* SDP_FindServiceInDb_128bit(const tSDP_DISCOVERY_DB* p_db, * Returns Pointer to record containing service class, or NULL * ******************************************************************************/ -tSDP_DISC_REC* SDP_FindServiceUUIDInDb(const tSDP_DISCOVERY_DB* p_db, - const Uuid& uuid, +tSDP_DISC_REC* SDP_FindServiceUUIDInDb(const tSDP_DISCOVERY_DB* p_db, const Uuid& uuid, tSDP_DISC_REC* p_start_rec) { tSDP_DISC_REC* p_rec; tSDP_DISC_ATTR *p_attr, *p_sattr; /* Must have a valid database */ - if (p_db == NULL) return (NULL); + if (p_db == NULL) { + return NULL; + } - if (!p_start_rec) + if (!p_start_rec) { p_rec = p_db->p_first_rec; - else + } else { p_rec = p_start_rec->p_next_rec; + } while (p_rec) { p_attr = p_rec->p_first_attr; while (p_attr) { if ((p_attr->attr_id == ATTR_ID_SERVICE_CLASS_ID_LIST) && - (SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == - DATA_ELE_SEQ_DESC_TYPE)) { - for (p_sattr = p_attr->attr_value.v.p_sub_attr; p_sattr; - p_sattr = p_sattr->p_next_attr) { + (SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == DATA_ELE_SEQ_DESC_TYPE)) { + for (p_sattr = p_attr->attr_value.v.p_sub_attr; p_sattr; p_sattr = p_sattr->p_next_attr) { if (SDP_DISC_ATTR_TYPE(p_sattr->attr_len_type) == UUID_DESC_TYPE) { - if (sdpu_compare_uuid_with_attr(uuid, p_sattr)) return (p_rec); + if (sdpu_compare_uuid_with_attr(uuid, p_sattr)) { + return p_rec; + } } } break; } else if (p_attr->attr_id == ATTR_ID_SERVICE_ID) { if (SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == UUID_DESC_TYPE) { - if (sdpu_compare_uuid_with_attr(uuid, p_attr)) return (p_rec); + if (sdpu_compare_uuid_with_attr(uuid, p_attr)) { + return p_rec; + } } } @@ -567,7 +570,7 @@ tSDP_DISC_REC* SDP_FindServiceUUIDInDb(const tSDP_DISCOVERY_DB* p_db, p_rec = p_rec->p_next_rec; } /* If here, no matching UUID found */ - return (NULL); + return NULL; } /******************************************************************************* @@ -580,21 +583,19 @@ tSDP_DISC_REC* SDP_FindServiceUUIDInDb(const tSDP_DISCOVERY_DB* p_db, * If found, the passed protocol list element is filled in. * ******************************************************************************/ -static bool sdp_fill_proto_elem(const tSDP_DISC_ATTR* p_attr, - uint16_t layer_uuid, +static bool sdp_fill_proto_elem(const tSDP_DISC_ATTR* p_attr, uint16_t layer_uuid, tSDP_PROTOCOL_ELEM* p_elem) { tSDP_DISC_ATTR* p_sattr; /* Walk through the protocol descriptor list */ - for (p_attr = p_attr->attr_value.v.p_sub_attr; p_attr; - p_attr = p_attr->p_next_attr) { + for (p_attr = p_attr->attr_value.v.p_sub_attr; p_attr; p_attr = p_attr->p_next_attr) { /* Safety check - each entry should itself be a sequence */ - if (SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) != DATA_ELE_SEQ_DESC_TYPE) - return (false); + if (SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) != DATA_ELE_SEQ_DESC_TYPE) { + return false; + } /* Now, see if the entry contains the layer we are interested in */ - for (p_sattr = p_attr->attr_value.v.p_sub_attr; p_sattr; - p_sattr = p_sattr->p_next_attr) { + for (p_sattr = p_attr->attr_value.v.p_sub_attr; p_sattr; p_sattr = p_sattr->p_next_attr) { /* LOG_VERBOSE ("SDP - p_sattr 0x%x, layer_uuid:0x%x, u16:0x%x####", p_sattr, layer_uuid, p_sattr->attr_value.v.u16); */ @@ -606,24 +607,27 @@ static bool sdp_fill_proto_elem(const tSDP_DISC_ATTR* p_attr, p_elem->num_params = 0; /* Store the parameters, if any */ - for (p_sattr = p_sattr->p_next_attr; p_sattr; - p_sattr = p_sattr->p_next_attr) { - if (SDP_DISC_ATTR_TYPE(p_sattr->attr_len_type) != UINT_DESC_TYPE) + for (p_sattr = p_sattr->p_next_attr; p_sattr; p_sattr = p_sattr->p_next_attr) { + if (SDP_DISC_ATTR_TYPE(p_sattr->attr_len_type) != UINT_DESC_TYPE) { break; + } - if (SDP_DISC_ATTR_LEN(p_sattr->attr_len_type) == 2) + if (SDP_DISC_ATTR_LEN(p_sattr->attr_len_type) == 2) { p_elem->params[p_elem->num_params++] = p_sattr->attr_value.v.u16; - else + } else { p_elem->params[p_elem->num_params++] = p_sattr->attr_value.v.u8; + } - if (p_elem->num_params >= SDP_MAX_PROTOCOL_PARAMS) break; + if (p_elem->num_params >= SDP_MAX_PROTOCOL_PARAMS) { + break; + } } - return (true); + return true; } } } - return (false); + return false; } /******************************************************************************* @@ -637,8 +641,7 @@ static bool sdp_fill_proto_elem(const tSDP_DISC_ATTR* p_attr, * If found, the passed protocol list element is filled in. * ******************************************************************************/ -bool SDP_FindProtocolListElemInRec(const tSDP_DISC_REC* p_rec, - uint16_t layer_uuid, +bool SDP_FindProtocolListElemInRec(const tSDP_DISC_REC* p_rec, uint16_t layer_uuid, tSDP_PROTOCOL_ELEM* p_elem) { tSDP_DISC_ATTR* p_attr; @@ -652,7 +655,7 @@ bool SDP_FindProtocolListElemInRec(const tSDP_DISC_REC* p_rec, p_attr = p_attr->p_next_attr; } /* If here, no match found */ - return (false); + return false; } /******************************************************************************* @@ -669,8 +672,8 @@ bool SDP_FindProtocolListElemInRec(const tSDP_DISC_REC* p_rec, * passed in are filled in. * ******************************************************************************/ -bool SDP_FindProfileVersionInRec(const tSDP_DISC_REC* p_rec, - uint16_t profile_uuid, uint16_t* p_version) { +bool SDP_FindProfileVersionInRec(const tSDP_DISC_REC* p_rec, uint16_t profile_uuid, + uint16_t* p_version) { tSDP_DISC_ATTR *p_attr, *p_sattr; p_attr = p_rec->p_first_attr; @@ -679,16 +682,15 @@ bool SDP_FindProfileVersionInRec(const tSDP_DISC_REC* p_rec, if ((p_attr->attr_id == ATTR_ID_BT_PROFILE_DESC_LIST) && (SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) == DATA_ELE_SEQ_DESC_TYPE)) { /* Walk through the protocol descriptor list */ - for (p_attr = p_attr->attr_value.v.p_sub_attr; p_attr; - p_attr = p_attr->p_next_attr) { + for (p_attr = p_attr->attr_value.v.p_sub_attr; p_attr; p_attr = p_attr->p_next_attr) { /* Safety check - each entry should itself be a sequence */ - if (SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) != DATA_ELE_SEQ_DESC_TYPE) - return (false); + if (SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) != DATA_ELE_SEQ_DESC_TYPE) { + return false; + } /* Now, see if the entry contains the profile UUID we are interested in */ - for (p_sattr = p_attr->attr_value.v.p_sub_attr; p_sattr; - p_sattr = p_sattr->p_next_attr) { + for (p_sattr = p_attr->attr_value.v.p_sub_attr; p_sattr; p_sattr = p_sattr->p_next_attr) { if ((SDP_DISC_ATTR_TYPE(p_sattr->attr_len_type) == UUID_DESC_TYPE) && (SDP_DISC_ATTR_LEN(p_sattr->attr_len_type) == 2) /* <- This is bytes, not size code! */ @@ -698,28 +700,28 @@ bool SDP_FindProfileVersionInRec(const tSDP_DISC_REC* p_rec, * size 2 bytes) */ p_sattr = p_sattr->p_next_attr; - if ((SDP_DISC_ATTR_TYPE(p_sattr->attr_len_type) == - UINT_DESC_TYPE) && + if ((SDP_DISC_ATTR_TYPE(p_sattr->attr_len_type) == UINT_DESC_TYPE) && (SDP_DISC_ATTR_LEN(p_sattr->attr_len_type) == 2)) { /* The high order 8 bits is the major number, low order is the * minor number (big endian) */ *p_version = p_sattr->attr_value.v.u16; - return (true); - } else - return (false); /* The type and/or size was not valid for the - profile list version */ + return true; + } else { + return false; /* The type and/or size was not valid for the + profile list version */ + } } } } - return (false); + return false; } p_attr = p_attr->p_next_attr; } /* If here, no match found */ - return (false); + return false; } /******************************************************************************* @@ -735,8 +737,7 @@ bool SDP_FindProfileVersionInRec(const tSDP_DISC_REC* p_rec, * Returns SDP_SUCCESS if query started successfully, else error * ******************************************************************************/ -tSDP_STATUS SDP_DiDiscover(const RawAddress& remote_device, - tSDP_DISCOVERY_DB* p_db, uint32_t len, +tSDP_STATUS SDP_DiDiscover(const RawAddress& remote_device, tSDP_DISCOVERY_DB* p_db, uint32_t len, tSDP_DISC_CMPL_CB* p_cb) { tSDP_STATUS result = SDP_DI_DISC_FAILED; uint16_t num_uuids = 1; @@ -745,9 +746,11 @@ tSDP_STATUS SDP_DiDiscover(const RawAddress& remote_device, /* build uuid for db init */ Uuid init_uuid = Uuid::From16Bit(di_uuid); - if (SDP_InitDiscoveryDb(p_db, len, num_uuids, &init_uuid, 0, NULL)) - if (SDP_ServiceSearchRequest(remote_device, p_db, p_cb)) + if (SDP_InitDiscoveryDb(p_db, len, num_uuids, &init_uuid, 0, NULL)) { + if (SDP_ServiceSearchRequest(remote_device, p_db, p_cb)) { result = SDP_SUCCESS; + } + } return result; } @@ -766,9 +769,10 @@ uint8_t SDP_GetNumDiRecords(const tSDP_DISCOVERY_DB* p_db) { tSDP_DISC_REC* p_curr_record = NULL; do { - p_curr_record = SDP_FindServiceInDb(p_db, UUID_SERVCLASS_PNP_INFORMATION, - p_curr_record); - if (p_curr_record) num_records++; + p_curr_record = SDP_FindServiceInDb(p_db, UUID_SERVCLASS_PNP_INFORMATION, p_curr_record); + if (p_curr_record) { + num_records++; + } } while (p_curr_record); return num_records; @@ -784,11 +788,11 @@ uint8_t SDP_GetNumDiRecords(const tSDP_DISCOVERY_DB* p_db) { * Returns none * ******************************************************************************/ -static void SDP_AttrStringCopy(char* dst, const tSDP_DISC_ATTR* p_attr, - uint16_t dst_size, +static void SDP_AttrStringCopy(char* dst, const tSDP_DISC_ATTR* p_attr, uint16_t dst_size, uint8_t expected_type) { - if (dst == NULL) + if (dst == NULL) { return; + } dst[0] = '\0'; @@ -820,8 +824,7 @@ static void SDP_AttrStringCopy(char* dst, const tSDP_DISC_ATTR* p_attr, * Returns SDP_SUCCESS if record retrieved, else error * ******************************************************************************/ -uint16_t SDP_GetDiRecord(uint8_t get_record_index, - tSDP_DI_GET_RECORD* p_device_info, +uint16_t SDP_GetDiRecord(uint8_t get_record_index, tSDP_DI_GET_RECORD* p_device_info, const tSDP_DISCOVERY_DB* p_db) { uint16_t result = SDP_NO_DI_RECORD_FOUND; uint8_t curr_record_index = 1; @@ -830,8 +833,7 @@ uint16_t SDP_GetDiRecord(uint8_t get_record_index, /* find the requested SDP record in the discovery database */ do { - p_curr_record = SDP_FindServiceInDb(p_db, UUID_SERVCLASS_PNP_INFORMATION, - p_curr_record); + p_curr_record = SDP_FindServiceInDb(p_db, UUID_SERVCLASS_PNP_INFORMATION, p_curr_record); if (p_curr_record) { if (curr_record_index++ == get_record_index) { result = SDP_SUCCESS; @@ -846,72 +848,67 @@ uint16_t SDP_GetDiRecord(uint8_t get_record_index, /* ClientExecutableURL is optional */ p_curr_attr = SDP_FindAttributeInRec(p_curr_record, ATTR_ID_CLIENT_EXE_URL); - SDP_AttrStringCopy(p_device_info->rec.client_executable_url, p_curr_attr, - SDP_MAX_ATTR_LEN, URL_DESC_TYPE); + SDP_AttrStringCopy(p_device_info->rec.client_executable_url, p_curr_attr, SDP_MAX_ATTR_LEN, + URL_DESC_TYPE); /* Service Description is optional */ /* 5.1.16 ServiceDescription attribute */ - p_curr_attr = - SDP_FindAttributeInRec(p_curr_record, ATTR_ID_SERVICE_DESCRIPTION); - SDP_AttrStringCopy(p_device_info->rec.service_description, p_curr_attr, - SDP_MAX_ATTR_LEN, TEXT_STR_DESC_TYPE); + p_curr_attr = SDP_FindAttributeInRec(p_curr_record, ATTR_ID_SERVICE_DESCRIPTION); + SDP_AttrStringCopy(p_device_info->rec.service_description, p_curr_attr, SDP_MAX_ATTR_LEN, + TEXT_STR_DESC_TYPE); /* DocumentationURL is optional */ - p_curr_attr = - SDP_FindAttributeInRec(p_curr_record, ATTR_ID_DOCUMENTATION_URL); - SDP_AttrStringCopy(p_device_info->rec.documentation_url, p_curr_attr, - SDP_MAX_ATTR_LEN, URL_DESC_TYPE); - - p_curr_attr = - SDP_FindAttributeInRec(p_curr_record, ATTR_ID_SPECIFICATION_ID); - if (p_curr_attr && - SDP_DISC_ATTR_TYPE(p_curr_attr->attr_len_type) == UINT_DESC_TYPE && - SDP_DISC_ATTR_LEN(p_curr_attr->attr_len_type) >= 2) + p_curr_attr = SDP_FindAttributeInRec(p_curr_record, ATTR_ID_DOCUMENTATION_URL); + SDP_AttrStringCopy(p_device_info->rec.documentation_url, p_curr_attr, SDP_MAX_ATTR_LEN, + URL_DESC_TYPE); + + p_curr_attr = SDP_FindAttributeInRec(p_curr_record, ATTR_ID_SPECIFICATION_ID); + if (p_curr_attr && SDP_DISC_ATTR_TYPE(p_curr_attr->attr_len_type) == UINT_DESC_TYPE && + SDP_DISC_ATTR_LEN(p_curr_attr->attr_len_type) >= 2) { p_device_info->spec_id = p_curr_attr->attr_value.v.u16; - else + } else { result = SDP_ERR_ATTR_NOT_PRESENT; + } p_curr_attr = SDP_FindAttributeInRec(p_curr_record, ATTR_ID_VENDOR_ID); - if (p_curr_attr && - SDP_DISC_ATTR_TYPE(p_curr_attr->attr_len_type) == UINT_DESC_TYPE && - SDP_DISC_ATTR_LEN(p_curr_attr->attr_len_type) >= 2) + if (p_curr_attr && SDP_DISC_ATTR_TYPE(p_curr_attr->attr_len_type) == UINT_DESC_TYPE && + SDP_DISC_ATTR_LEN(p_curr_attr->attr_len_type) >= 2) { p_device_info->rec.vendor = p_curr_attr->attr_value.v.u16; - else + } else { result = SDP_ERR_ATTR_NOT_PRESENT; + } - p_curr_attr = - SDP_FindAttributeInRec(p_curr_record, ATTR_ID_VENDOR_ID_SOURCE); - if (p_curr_attr && - SDP_DISC_ATTR_TYPE(p_curr_attr->attr_len_type) == UINT_DESC_TYPE && - SDP_DISC_ATTR_LEN(p_curr_attr->attr_len_type) >= 2) + p_curr_attr = SDP_FindAttributeInRec(p_curr_record, ATTR_ID_VENDOR_ID_SOURCE); + if (p_curr_attr && SDP_DISC_ATTR_TYPE(p_curr_attr->attr_len_type) == UINT_DESC_TYPE && + SDP_DISC_ATTR_LEN(p_curr_attr->attr_len_type) >= 2) { p_device_info->rec.vendor_id_source = p_curr_attr->attr_value.v.u16; - else + } else { result = SDP_ERR_ATTR_NOT_PRESENT; + } p_curr_attr = SDP_FindAttributeInRec(p_curr_record, ATTR_ID_PRODUCT_ID); - if (p_curr_attr && - SDP_DISC_ATTR_TYPE(p_curr_attr->attr_len_type) == UINT_DESC_TYPE && - SDP_DISC_ATTR_LEN(p_curr_attr->attr_len_type) >= 2) + if (p_curr_attr && SDP_DISC_ATTR_TYPE(p_curr_attr->attr_len_type) == UINT_DESC_TYPE && + SDP_DISC_ATTR_LEN(p_curr_attr->attr_len_type) >= 2) { p_device_info->rec.product = p_curr_attr->attr_value.v.u16; - else + } else { result = SDP_ERR_ATTR_NOT_PRESENT; + } - p_curr_attr = - SDP_FindAttributeInRec(p_curr_record, ATTR_ID_PRODUCT_VERSION); - if (p_curr_attr && - SDP_DISC_ATTR_TYPE(p_curr_attr->attr_len_type) == UINT_DESC_TYPE && - SDP_DISC_ATTR_LEN(p_curr_attr->attr_len_type) >= 2) + p_curr_attr = SDP_FindAttributeInRec(p_curr_record, ATTR_ID_PRODUCT_VERSION); + if (p_curr_attr && SDP_DISC_ATTR_TYPE(p_curr_attr->attr_len_type) == UINT_DESC_TYPE && + SDP_DISC_ATTR_LEN(p_curr_attr->attr_len_type) >= 2) { p_device_info->rec.version = p_curr_attr->attr_value.v.u16; - else + } else { result = SDP_ERR_ATTR_NOT_PRESENT; + } p_curr_attr = SDP_FindAttributeInRec(p_curr_record, ATTR_ID_PRIMARY_RECORD); - if (p_curr_attr && - SDP_DISC_ATTR_TYPE(p_curr_attr->attr_len_type) == BOOLEAN_DESC_TYPE && - SDP_DISC_ATTR_LEN(p_curr_attr->attr_len_type) >= 1) + if (p_curr_attr && SDP_DISC_ATTR_TYPE(p_curr_attr->attr_len_type) == BOOLEAN_DESC_TYPE && + SDP_DISC_ATTR_LEN(p_curr_attr->attr_len_type) >= 1) { p_device_info->rec.primary_record = (bool)p_curr_attr->attr_value.v.u8; - else + } else { result = SDP_ERR_ATTR_NOT_PRESENT; + } } return result; @@ -932,8 +929,7 @@ uint16_t SDP_GetDiRecord(uint8_t get_record_index, * Returns Returns SDP_SUCCESS if record added successfully, else error * ******************************************************************************/ -uint16_t SDP_SetLocalDiRecord(const tSDP_DI_RECORD* p_device_info, - uint32_t* p_handle) { +uint16_t SDP_SetLocalDiRecord(const tSDP_DI_RECORD* p_device_info, uint32_t* p_handle) { uint16_t result = SDP_SUCCESS; uint32_t handle; uint16_t di_uuid = UUID_SERVCLASS_PNP_INFORMATION; @@ -943,68 +939,71 @@ uint16_t SDP_SetLocalDiRecord(const tSDP_DI_RECORD* p_device_info, uint8_t u8; *p_handle = 0; - if (p_device_info == NULL) return SDP_ILLEGAL_PARAMETER; + if (p_device_info == NULL) { + return SDP_ILLEGAL_PARAMETER; + } /* if record is to be primary record, get handle to replace old primary */ - if (p_device_info->primary_record && sdp_cb.server_db.di_primary_handle) + if (p_device_info->primary_record && sdp_cb.server_db.di_primary_handle) { handle = sdp_cb.server_db.di_primary_handle; - else { + } else { handle = SDP_CreateRecord(); - if (handle == 0) return SDP_NO_RESOURCES; + if (handle == 0) { + return SDP_NO_RESOURCES; + } } *p_handle = handle; /* build the SDP entry */ /* Add the UUID to the Service Class ID List */ - if (!(SDP_AddServiceClassIdList(handle, 1, &di_uuid))) + if (!(SDP_AddServiceClassIdList(handle, 1, &di_uuid))) { result = SDP_DI_REG_FAILED; + } /* mandatory */ if (result == SDP_SUCCESS) { p_temp = temp_u16; UINT16_TO_BE_STREAM(p_temp, di_specid); - if (!(SDP_AddAttribute(handle, ATTR_ID_SPECIFICATION_ID, UINT_DESC_TYPE, - sizeof(di_specid), temp_u16))) + if (!(SDP_AddAttribute(handle, ATTR_ID_SPECIFICATION_ID, UINT_DESC_TYPE, sizeof(di_specid), + temp_u16))) { result = SDP_DI_REG_FAILED; + } } /* optional - if string is null, do not add attribute */ if (result == SDP_SUCCESS) { if (p_device_info->client_executable_url[0] != '\0') { - if (!((strlen(p_device_info->client_executable_url) + 1 <= - SDP_MAX_ATTR_LEN) && - SDP_AddAttribute( - handle, ATTR_ID_CLIENT_EXE_URL, URL_DESC_TYPE, - (uint32_t)(strlen(p_device_info->client_executable_url) + 1), - (uint8_t*)p_device_info->client_executable_url))) + if (!((strlen(p_device_info->client_executable_url) + 1 <= SDP_MAX_ATTR_LEN) && + SDP_AddAttribute(handle, ATTR_ID_CLIENT_EXE_URL, URL_DESC_TYPE, + (uint32_t)(strlen(p_device_info->client_executable_url) + 1), + (uint8_t*)p_device_info->client_executable_url))) { result = SDP_DI_REG_FAILED; + } } } /* optional - if string is null, do not add attribute */ if (result == SDP_SUCCESS) { if (p_device_info->service_description[0] != '\0') { - if (!((strlen(p_device_info->service_description) + 1 <= - SDP_MAX_ATTR_LEN) && - SDP_AddAttribute( - handle, ATTR_ID_SERVICE_DESCRIPTION, TEXT_STR_DESC_TYPE, - (uint32_t)(strlen(p_device_info->service_description) + 1), - (uint8_t*)p_device_info->service_description))) + if (!((strlen(p_device_info->service_description) + 1 <= SDP_MAX_ATTR_LEN) && + SDP_AddAttribute(handle, ATTR_ID_SERVICE_DESCRIPTION, TEXT_STR_DESC_TYPE, + (uint32_t)(strlen(p_device_info->service_description) + 1), + (uint8_t*)p_device_info->service_description))) { result = SDP_DI_REG_FAILED; + } } } /* optional - if string is null, do not add attribute */ if (result == SDP_SUCCESS) { if (p_device_info->documentation_url[0] != '\0') { - if (!((strlen(p_device_info->documentation_url) + 1 <= - SDP_MAX_ATTR_LEN) && - SDP_AddAttribute( - handle, ATTR_ID_DOCUMENTATION_URL, URL_DESC_TYPE, - (uint32_t)(strlen(p_device_info->documentation_url) + 1), - (uint8_t*)p_device_info->documentation_url))) + if (!((strlen(p_device_info->documentation_url) + 1 <= SDP_MAX_ATTR_LEN) && + SDP_AddAttribute(handle, ATTR_ID_DOCUMENTATION_URL, URL_DESC_TYPE, + (uint32_t)(strlen(p_device_info->documentation_url) + 1), + (uint8_t*)p_device_info->documentation_url))) { result = SDP_DI_REG_FAILED; + } } } @@ -1012,9 +1011,10 @@ uint16_t SDP_SetLocalDiRecord(const tSDP_DI_RECORD* p_device_info, if (result == SDP_SUCCESS) { p_temp = temp_u16; UINT16_TO_BE_STREAM(p_temp, p_device_info->vendor); - if (!(SDP_AddAttribute(handle, ATTR_ID_VENDOR_ID, UINT_DESC_TYPE, - sizeof(p_device_info->vendor), temp_u16))) + if (!(SDP_AddAttribute(handle, ATTR_ID_VENDOR_ID, UINT_DESC_TYPE, sizeof(p_device_info->vendor), + temp_u16))) { result = SDP_DI_REG_FAILED; + } } /* mandatory */ @@ -1022,8 +1022,9 @@ uint16_t SDP_SetLocalDiRecord(const tSDP_DI_RECORD* p_device_info, p_temp = temp_u16; UINT16_TO_BE_STREAM(p_temp, p_device_info->product); if (!(SDP_AddAttribute(handle, ATTR_ID_PRODUCT_ID, UINT_DESC_TYPE, - sizeof(p_device_info->product), temp_u16))) + sizeof(p_device_info->product), temp_u16))) { result = SDP_DI_REG_FAILED; + } } /* mandatory */ @@ -1031,16 +1032,17 @@ uint16_t SDP_SetLocalDiRecord(const tSDP_DI_RECORD* p_device_info, p_temp = temp_u16; UINT16_TO_BE_STREAM(p_temp, p_device_info->version); if (!(SDP_AddAttribute(handle, ATTR_ID_PRODUCT_VERSION, UINT_DESC_TYPE, - sizeof(p_device_info->version), temp_u16))) + sizeof(p_device_info->version), temp_u16))) { result = SDP_DI_REG_FAILED; + } } /* mandatory */ if (result == SDP_SUCCESS) { u8 = (uint8_t)p_device_info->primary_record; - if (!(SDP_AddAttribute(handle, ATTR_ID_PRIMARY_RECORD, BOOLEAN_DESC_TYPE, 1, - &u8))) + if (!(SDP_AddAttribute(handle, ATTR_ID_PRIMARY_RECORD, BOOLEAN_DESC_TYPE, 1, &u8))) { result = SDP_DI_REG_FAILED; + } } /* mandatory */ @@ -1048,65 +1050,64 @@ uint16_t SDP_SetLocalDiRecord(const tSDP_DI_RECORD* p_device_info, p_temp = temp_u16; UINT16_TO_BE_STREAM(p_temp, p_device_info->vendor_id_source); if (!(SDP_AddAttribute(handle, ATTR_ID_VENDOR_ID_SOURCE, UINT_DESC_TYPE, - sizeof(p_device_info->vendor_id_source), temp_u16))) + sizeof(p_device_info->vendor_id_source), temp_u16))) { result = SDP_DI_REG_FAILED; + } } - if (result != SDP_SUCCESS) + if (result != SDP_SUCCESS) { SDP_DeleteRecord(handle); - else if (p_device_info->primary_record) + } else if (p_device_info->primary_record) { sdp_cb.server_db.di_primary_handle = handle; + } return result; } namespace { bluetooth::legacy::stack::sdp::tSdpApi api_ = { - .service = - { - .SDP_InitDiscoveryDb = ::SDP_InitDiscoveryDb, - .SDP_CancelServiceSearch = ::SDP_CancelServiceSearch, - .SDP_ServiceSearchRequest = ::SDP_ServiceSearchRequest, - .SDP_ServiceSearchAttributeRequest = - ::SDP_ServiceSearchAttributeRequest, - .SDP_ServiceSearchAttributeRequest2 = - ::SDP_ServiceSearchAttributeRequest2, - }, - .db = - { - .SDP_FindServiceInDb = ::SDP_FindServiceInDb, - .SDP_FindServiceUUIDInDb = ::SDP_FindServiceUUIDInDb, - .SDP_FindServiceInDb_128bit = ::SDP_FindServiceInDb_128bit, - }, - .record = - { - .SDP_FindAttributeInRec = ::SDP_FindAttributeInRec, - .SDP_FindServiceUUIDInRec_128bit = - ::SDP_FindServiceUUIDInRec_128bit, - .SDP_FindProtocolListElemInRec = ::SDP_FindProtocolListElemInRec, - .SDP_FindProfileVersionInRec = ::SDP_FindProfileVersionInRec, - .SDP_FindServiceUUIDInRec = ::SDP_FindServiceUUIDInRec, - }, - .handle = - { - .SDP_CreateRecord = ::SDP_CreateRecord, - .SDP_DeleteRecord = ::SDP_DeleteRecord, - .SDP_AddAttribute = ::SDP_AddAttribute, - .SDP_AddSequence = ::SDP_AddSequence, - .SDP_AddUuidSequence = ::SDP_AddUuidSequence, - .SDP_AddProtocolList = ::SDP_AddProtocolList, - .SDP_AddAdditionProtoLists = ::SDP_AddAdditionProtoLists, - .SDP_AddProfileDescriptorList = ::SDP_AddProfileDescriptorList, - .SDP_AddLanguageBaseAttrIDList = ::SDP_AddLanguageBaseAttrIDList, - .SDP_AddServiceClassIdList = ::SDP_AddServiceClassIdList, - }, - .device_id = - { - .SDP_SetLocalDiRecord = ::SDP_SetLocalDiRecord, - .SDP_DiDiscover = ::SDP_DiDiscover, - .SDP_GetNumDiRecords = ::SDP_GetNumDiRecords, - .SDP_GetDiRecord = ::SDP_GetDiRecord, - }, + .service = + { + .SDP_InitDiscoveryDb = ::SDP_InitDiscoveryDb, + .SDP_CancelServiceSearch = ::SDP_CancelServiceSearch, + .SDP_ServiceSearchRequest = ::SDP_ServiceSearchRequest, + .SDP_ServiceSearchAttributeRequest = ::SDP_ServiceSearchAttributeRequest, + .SDP_ServiceSearchAttributeRequest2 = ::SDP_ServiceSearchAttributeRequest2, + }, + .db = + { + .SDP_FindServiceInDb = ::SDP_FindServiceInDb, + .SDP_FindServiceUUIDInDb = ::SDP_FindServiceUUIDInDb, + .SDP_FindServiceInDb_128bit = ::SDP_FindServiceInDb_128bit, + }, + .record = + { + .SDP_FindAttributeInRec = ::SDP_FindAttributeInRec, + .SDP_FindServiceUUIDInRec_128bit = ::SDP_FindServiceUUIDInRec_128bit, + .SDP_FindProtocolListElemInRec = ::SDP_FindProtocolListElemInRec, + .SDP_FindProfileVersionInRec = ::SDP_FindProfileVersionInRec, + .SDP_FindServiceUUIDInRec = ::SDP_FindServiceUUIDInRec, + }, + .handle = + { + .SDP_CreateRecord = ::SDP_CreateRecord, + .SDP_DeleteRecord = ::SDP_DeleteRecord, + .SDP_AddAttribute = ::SDP_AddAttribute, + .SDP_AddSequence = ::SDP_AddSequence, + .SDP_AddUuidSequence = ::SDP_AddUuidSequence, + .SDP_AddProtocolList = ::SDP_AddProtocolList, + .SDP_AddAdditionProtoLists = ::SDP_AddAdditionProtoLists, + .SDP_AddProfileDescriptorList = ::SDP_AddProfileDescriptorList, + .SDP_AddLanguageBaseAttrIDList = ::SDP_AddLanguageBaseAttrIDList, + .SDP_AddServiceClassIdList = ::SDP_AddServiceClassIdList, + }, + .device_id = + { + .SDP_SetLocalDiRecord = ::SDP_SetLocalDiRecord, + .SDP_DiDiscover = ::SDP_DiDiscover, + .SDP_GetNumDiRecords = ::SDP_GetNumDiRecords, + .SDP_GetDiRecord = ::SDP_GetDiRecord, + }, }; } // namespace diff --git a/system/stack/sdp/sdp_db.cc b/system/stack/sdp/sdp_db.cc index 2b8039800c6..efe9e0ca5f9 100644 --- a/system/stack/sdp/sdp_db.cc +++ b/system/stack/sdp/sdp_db.cc @@ -50,15 +50,16 @@ using namespace bluetooth; * Returns true if found, else false * ******************************************************************************/ -static bool find_uuid_in_seq(uint8_t* p, uint32_t seq_len, - const uint8_t* p_uuid, uint16_t uuid_len, +static bool find_uuid_in_seq(uint8_t* p, uint32_t seq_len, const uint8_t* p_uuid, uint16_t uuid_len, int nest_level) { uint8_t* p_end = p + seq_len; uint8_t type; uint32_t len; /* A little safety check to avoid excessive recursion */ - if (nest_level > 3) return (false); + if (nest_level > 3) { + return false; + } while (p < p_end) { type = *p++; @@ -69,16 +70,19 @@ static bool find_uuid_in_seq(uint8_t* p, uint32_t seq_len, } type = type >> 3; if (type == UUID_DESC_TYPE) { - if (sdpu_compare_uuid_arrays(p, len, p_uuid, uuid_len)) return (true); + if (sdpu_compare_uuid_arrays(p, len, p_uuid, uuid_len)) { + return true; + } } else if (type == DATA_ELE_SEQ_DESC_TYPE) { - if (find_uuid_in_seq(p, len, p_uuid, uuid_len, nest_level + 1)) - return (true); + if (find_uuid_in_seq(p, len, p_uuid, uuid_len, nest_level + 1)) { + return true; + } } p = p + len; } /* If here, failed to match */ - return (false); + return false; } /******************************************************************************* @@ -92,18 +96,18 @@ static bool find_uuid_in_seq(uint8_t* p, uint32_t seq_len, * Returns Pointer to the record, or NULL if not found. * ******************************************************************************/ -const tSDP_RECORD* sdp_db_service_search(const tSDP_RECORD* p_rec, - const tSDP_UUID_SEQ* p_seq) { +const tSDP_RECORD* sdp_db_service_search(const tSDP_RECORD* p_rec, const tSDP_UUID_SEQ* p_seq) { uint16_t xx, yy; const tSDP_ATTRIBUTE* p_attr; tSDP_RECORD* p_end = &sdp_cb.server_db.record[sdp_cb.server_db.num_records]; /* If NULL, start at the beginning, else start at the first specified record */ - if (!p_rec) + if (!p_rec) { p_rec = &sdp_cb.server_db.record[0]; - else + } else { p_rec++; + } /* Look through the records. The spec says that a match occurs if */ /* the record contains all the passed UUIDs in it. */ @@ -114,25 +118,30 @@ const tSDP_RECORD* sdp_db_service_search(const tSDP_RECORD* p_rec, if (p_attr->type == UUID_DESC_TYPE) { if (sdpu_compare_uuid_arrays(p_attr->value_ptr, p_attr->len, &p_seq->uuid_entry[yy].value[0], - p_seq->uuid_entry[yy].len)) + p_seq->uuid_entry[yy].len)) { break; + } } else if (p_attr->type == DATA_ELE_SEQ_DESC_TYPE) { - if (find_uuid_in_seq(p_attr->value_ptr, p_attr->len, - &p_seq->uuid_entry[yy].value[0], - p_seq->uuid_entry[yy].len, 0)) + if (find_uuid_in_seq(p_attr->value_ptr, p_attr->len, &p_seq->uuid_entry[yy].value[0], + p_seq->uuid_entry[yy].len, 0)) { break; + } } } /* If any UUID was not found, on to the next record */ - if (xx == p_rec->num_attributes) break; + if (xx == p_rec->num_attributes) { + break; + } } /* If every UUID was found in the record, return the record */ - if (yy == p_seq->num_uids) return (p_rec); + if (yy == p_seq->num_uids) { + return p_rec; + } } /* If here, no more records found */ - return (NULL); + return NULL; } /******************************************************************************* @@ -151,11 +160,13 @@ tSDP_RECORD* sdp_db_find_record(uint32_t handle) { /* Look through the records for the caller's handle */ for (p_rec = &sdp_cb.server_db.record[0]; p_rec < p_end; p_rec++) { - if (p_rec->record_handle == handle) return (p_rec); + if (p_rec->record_handle == handle) { + return p_rec; + } } /* Record with that handle not found. */ - return (NULL); + return NULL; } /******************************************************************************* @@ -170,20 +181,20 @@ tSDP_RECORD* sdp_db_find_record(uint32_t handle) { * Returns Pointer to the attribute, or NULL if not found. * ******************************************************************************/ -const tSDP_ATTRIBUTE* sdp_db_find_attr_in_rec(const tSDP_RECORD* p_rec, - uint16_t start_attr, +const tSDP_ATTRIBUTE* sdp_db_find_attr_in_rec(const tSDP_RECORD* p_rec, uint16_t start_attr, uint16_t end_attr) { const tSDP_ATTRIBUTE* p_at; uint16_t xx; /* Note that the attributes in a record are assumed to be in sorted order */ - for (xx = 0, p_at = &p_rec->attribute[0]; xx < p_rec->num_attributes; - xx++, p_at++) { - if ((p_at->id >= start_attr) && (p_at->id <= end_attr)) return (p_at); + for (xx = 0, p_at = &p_rec->attribute[0]; xx < p_rec->num_attributes; xx++, p_at++) { + if ((p_at->id >= start_attr) && (p_at->id <= end_attr)) { + return p_at; + } } /* No matching attribute found */ - return (NULL); + return NULL; } /******************************************************************************* @@ -196,8 +207,7 @@ const tSDP_ATTRIBUTE* sdp_db_find_attr_in_rec(const tSDP_RECORD* p_rec, * Returns the length of the data sequence * ******************************************************************************/ -static int sdp_compose_proto_list(uint8_t* p, uint16_t num_elem, - tSDP_PROTOCOL_ELEM* p_elem_list) { +static int sdp_compose_proto_list(uint8_t* p, uint16_t num_elem, tSDP_PROTOCOL_ELEM* p_elem_list) { uint16_t xx, yy, len; bool is_rfcomm_scn; uint8_t* p_head = p; @@ -217,10 +227,11 @@ static int sdp_compose_proto_list(uint8_t* p, uint16_t num_elem, UINT8_TO_BE_STREAM(p, (UUID_DESC_TYPE << 3) | SIZE_TWO_BYTES); UINT16_TO_BE_STREAM(p, p_elem_list->protocol_uuid); - if (p_elem_list->protocol_uuid == UUID_PROTOCOL_RFCOMM) + if (p_elem_list->protocol_uuid == UUID_PROTOCOL_RFCOMM) { is_rfcomm_scn = true; - else + } else { is_rfcomm_scn = false; + } for (yy = 0; yy < p_elem_list->num_params; yy++) { if (is_rfcomm_scn) { @@ -234,7 +245,7 @@ static int sdp_compose_proto_list(uint8_t* p, uint16_t num_elem, } } } - return (p - p_head); + return p - p_head; } /******************************************************************************* @@ -251,23 +262,21 @@ static int sdp_compose_proto_list(uint8_t* p, uint16_t num_elem, * Returns true if added OK, else false * ******************************************************************************/ -bool SDP_AddAttribute(uint32_t handle, uint16_t attr_id, uint8_t attr_type, - uint32_t attr_len, uint8_t* p_val) { +bool SDP_AddAttribute(uint32_t handle, uint16_t attr_id, uint8_t attr_type, uint32_t attr_len, + uint8_t* p_val) { uint16_t zz; tSDP_RECORD* p_rec = &sdp_cb.server_db.record[0]; if (p_val == nullptr) { log::warn("Trying to add attribute with p_val == nullptr, skipped"); - return (false); + return false; } // TODO(305066880): invoke would_log when implemented to check // if LOG_VERBOSE is displayed. if (true) { - if ((attr_type == UINT_DESC_TYPE) || - (attr_type == TWO_COMP_INT_DESC_TYPE) || - (attr_type == UUID_DESC_TYPE) || - (attr_type == DATA_ELE_SEQ_DESC_TYPE) || + if ((attr_type == UINT_DESC_TYPE) || (attr_type == TWO_COMP_INT_DESC_TYPE) || + (attr_type == UUID_DESC_TYPE) || (attr_type == DATA_ELE_SEQ_DESC_TYPE) || (attr_type == DATA_ELE_ALT_DESC_TYPE)) { #define MAX_ARR_LEN 200 // one extra byte for storing terminating zero byte @@ -276,36 +285,25 @@ bool SDP_AddAttribute(uint32_t handle, uint16_t attr_id, uint8_t attr_type, #undef MAX_ARR_LEN for (uint32_t i = 0; i < len; i++) { - snprintf(&num_array[i * 2], sizeof(num_array) - i * 2, "%02X", - (uint8_t)(p_val[i])); + snprintf(&num_array[i * 2], sizeof(num_array) - i * 2, "%02X", (uint8_t)(p_val[i])); } - log::verbose( - "SDP_AddAttribute: handle:{:X}, id:{:04X}, type:{}, len:{}, " - "p_val:{}, *p_val:{}", - handle, attr_id, attr_type, attr_len, fmt::ptr(p_val), num_array); + log::verbose("SDP_AddAttribute: handle:{:X}, id:{:04X}, type:{}, len:{}, p_val:{}, *p_val:{}", + handle, attr_id, attr_type, attr_len, fmt::ptr(p_val), num_array); } else if (attr_type == BOOLEAN_DESC_TYPE) { - log::verbose( - "SDP_AddAttribute: handle:{:X}, id:{:04X}, type:{}, len:{}, " - "p_val:{}, *p_val:{}", - handle, attr_id, attr_type, attr_len, fmt::ptr(p_val), *p_val); - } else if ((attr_type == TEXT_STR_DESC_TYPE) || - (attr_type == URL_DESC_TYPE)) { + log::verbose("SDP_AddAttribute: handle:{:X}, id:{:04X}, type:{}, len:{}, p_val:{}, *p_val:{}", + handle, attr_id, attr_type, attr_len, fmt::ptr(p_val), *p_val); + } else if ((attr_type == TEXT_STR_DESC_TYPE) || (attr_type == URL_DESC_TYPE)) { if (p_val[attr_len - 1] == '\0') { log::verbose( - "SDP_AddAttribute: handle:{:X}, id:{:04X}, type:{}, len:{}, " - "p_val:{}, *p_val:{}", - handle, attr_id, attr_type, attr_len, fmt::ptr(p_val), - (char*)p_val); + "SDP_AddAttribute: handle:{:X}, id:{:04X}, type:{}, len:{}, p_val:{}, *p_val:{}", + handle, attr_id, attr_type, attr_len, fmt::ptr(p_val), (char*)p_val); } else { - log::verbose( - "SDP_AddAttribute: handle:{:X}, id:{:04X}, type:{}, len:{}, " - "p_val:{}", - handle, attr_id, attr_type, attr_len, fmt::ptr(p_val)); + log::verbose("SDP_AddAttribute: handle:{:X}, id:{:04X}, type:{}, len:{}, p_val:{}", handle, + attr_id, attr_type, attr_len, fmt::ptr(p_val)); } } else { - log::verbose( - "SDP_AddAttribute: handle:{:X}, id:{:04X}, type:{}, len:{}, p_val:{}", - handle, attr_id, attr_type, attr_len, fmt::ptr(p_val)); + log::verbose("SDP_AddAttribute: handle:{:X}, id:{:04X}, type:{}, len:{}, p_val:{}", handle, + attr_id, attr_type, attr_len, fmt::ptr(p_val)); } } @@ -314,18 +312,15 @@ bool SDP_AddAttribute(uint32_t handle, uint16_t attr_id, uint8_t attr_type, if (p_rec->record_handle == handle) { // error out early, no need to look up if (p_rec->free_pad_ptr >= SDP_MAX_PAD_LEN) { - log::error( - "the free pad for SDP record with handle {} is full, skip adding " - "the attribute", - handle); - return (false); + log::error("the free pad for SDP record with handle {} is full, skip adding the attribute", + handle); + return false; } - return SDP_AddAttributeToRecord(p_rec, attr_id, attr_type, attr_len, - p_val); + return SDP_AddAttributeToRecord(p_rec, attr_id, attr_type, attr_len, p_val); } } - return (false); + return false; } /******************************************************************************* @@ -334,7 +329,7 @@ bool SDP_AddAttribute(uint32_t handle, uint16_t attr_id, uint8_t attr_type, * * Description This function is called to create a record in the database. * This would be through the SDP database maintenance API. The - * record is created empty, teh application should then call + * record is created empty, the application should then call * "add_attribute" to add the record's attributes. * * Returns Record handle if OK, else 0. @@ -351,10 +346,11 @@ uint32_t SDP_CreateRecord(void) { /* We will use a handle of the first unreserved handle plus last record ** number + 1 */ - if (p_db->num_records) + if (p_db->num_records) { handle = p_db->record[p_db->num_records - 1].record_handle + 1; - else + } else { handle = 0x10000; + } p_db->record[p_db->num_records].record_handle = handle; @@ -362,14 +358,13 @@ uint32_t SDP_CreateRecord(void) { log::verbose("SDP_CreateRecord ok, num_records:{}", p_db->num_records); /* Add the first attribute (the handle) automatically */ UINT32_TO_BE_FIELD(buf, handle); - SDP_AddAttribute(handle, ATTR_ID_SERVICE_RECORD_HDL, UINT_DESC_TYPE, 4, - buf); - - return (p_db->record[p_db->num_records - 1].record_handle); - } else - log::error("SDP_CreateRecord fail, exceed maximum records:{}", - SDP_MAX_RECORDS); - return (0); + SDP_AddAttribute(handle, ATTR_ID_SERVICE_RECORD_HDL, UINT_DESC_TYPE, 4, buf); + + return p_db->record[p_db->num_records - 1].record_handle; + } else { + log::error("SDP_CreateRecord fail, exceed maximum records:{}", SDP_MAX_RECORDS); + } + return 0; } /******************************************************************************* @@ -396,7 +391,7 @@ bool SDP_DeleteRecord(uint32_t handle) { /* require new DI record to be created in SDP_SetLocalDiRecord */ sdp_cb.server_db.di_primary_handle = 0; - return (true); + return true; } else { /* Find the record in the database */ for (xx = 0; xx < sdp_cb.server_db.num_records; xx++, p_rec++) { @@ -406,25 +401,25 @@ bool SDP_DeleteRecord(uint32_t handle) { *p_rec = *(p_rec + 1); /* Adjust the attribute value pointer for each attribute */ - for (zz = 0; zz < p_rec->num_attributes; zz++) + for (zz = 0; zz < p_rec->num_attributes; zz++) { p_rec->attribute[zz].value_ptr -= sizeof(tSDP_RECORD); + } } sdp_cb.server_db.num_records--; - log::verbose("SDP_DeleteRecord ok, num_records:{}", - sdp_cb.server_db.num_records); + log::verbose("SDP_DeleteRecord ok, num_records:{}", sdp_cb.server_db.num_records); /* if we're deleting the primary DI record, clear the */ /* value in the control block */ if (sdp_cb.server_db.di_primary_handle == handle) { sdp_cb.server_db.di_primary_handle = 0; } - return (true); + return true; } } } - return (false); + return false; } /******************************************************************************* @@ -441,9 +436,8 @@ bool SDP_DeleteRecord(uint32_t handle) { * Returns true if added OK, else false * ******************************************************************************/ -bool SDP_AddAttributeToRecord(tSDP_RECORD* p_rec, uint16_t attr_id, - uint8_t attr_type, uint32_t attr_len, - uint8_t* p_val) { +bool SDP_AddAttributeToRecord(tSDP_RECORD* p_rec, uint16_t attr_id, uint8_t attr_type, + uint32_t attr_len, uint8_t* p_val) { uint16_t xx, yy; tSDP_ATTRIBUTE* p_attr = &p_rec->attribute[0]; @@ -454,18 +448,23 @@ bool SDP_AddAttributeToRecord(tSDP_RECORD* p_rec, uint16_t attr_id, SDP_DeleteAttributeFromRecord(p_rec, attr_id); break; } - if (p_attr->id > attr_id) break; + if (p_attr->id > attr_id) { + break; + } } - if (p_rec->num_attributes >= SDP_MAX_REC_ATTR) return (false); + if (p_rec->num_attributes >= SDP_MAX_REC_ATTR) { + return false; + } /* If not found, see if we can allocate a new entry */ - if (xx == p_rec->num_attributes) + if (xx == p_rec->num_attributes) { p_attr = &p_rec->attribute[p_rec->num_attributes]; - else { + } else { /* Since the attributes are kept in sorted order, insert ours here */ - for (yy = p_rec->num_attributes; yy > xx; yy--) + for (yy = p_rec->num_attributes; yy > xx; yy--) { p_rec->attribute[yy] = p_rec->attribute[yy - 1]; + } } p_attr->id = attr_id; @@ -475,22 +474,22 @@ bool SDP_AddAttributeToRecord(tSDP_RECORD* p_rec, uint16_t attr_id, if (p_rec->free_pad_ptr + attr_len >= SDP_MAX_PAD_LEN) { if (p_rec->free_pad_ptr >= SDP_MAX_PAD_LEN) { log::error( - "SDP_AddAttributeToRecord failed: free pad {} equals or exceeds max " - "padding length {}", - p_rec->free_pad_ptr, SDP_MAX_PAD_LEN); - return (false); + "SDP_AddAttributeToRecord failed: free pad {} equals or exceeds max " + "padding length {}", + p_rec->free_pad_ptr, SDP_MAX_PAD_LEN); + return false; } /* do truncate only for text string type descriptor */ if (attr_type == TEXT_STR_DESC_TYPE) { - log::warn( - "SDP_AddAttributeToRecord: attr_len:{} too long. truncate to ({})", - attr_len, SDP_MAX_PAD_LEN - p_rec->free_pad_ptr); + log::warn("SDP_AddAttributeToRecord: attr_len:{} too long. truncate to ({})", attr_len, + SDP_MAX_PAD_LEN - p_rec->free_pad_ptr); attr_len = SDP_MAX_PAD_LEN - p_rec->free_pad_ptr; p_val[SDP_MAX_PAD_LEN - p_rec->free_pad_ptr - 1] = '\0'; - } else + } else { attr_len = 0; + } } if (attr_len > 0) { @@ -500,15 +499,13 @@ bool SDP_AddAttributeToRecord(tSDP_RECORD* p_rec, uint16_t attr_id, p_rec->free_pad_ptr += attr_len; } else if (attr_len == 0 && p_attr->len != 0) { /* if truncate to 0 length, simply don't add */ - log::error( - "SDP_AddAttributeToRecord fail, length exceed maximum: ID {}: " - "attr_len:{}", - attr_id, attr_len); + log::error("SDP_AddAttributeToRecord fail, length exceed maximum: ID {}: attr_len:{}", attr_id, + attr_len); p_attr->id = p_attr->type = p_attr->len = 0; - return (false); + return false; } p_rec->num_attributes++; - return (true); + return true; } /******************************************************************************* @@ -525,14 +522,13 @@ bool SDP_AddAttributeToRecord(tSDP_RECORD* p_rec, uint16_t attr_id, * Returns true if added OK, else false * ******************************************************************************/ -bool SDP_AddSequence(uint32_t handle, uint16_t attr_id, uint16_t num_elem, - uint8_t type[], uint8_t len[], uint8_t* p_val[]) { +bool SDP_AddSequence(uint32_t handle, uint16_t attr_id, uint16_t num_elem, uint8_t type[], + uint8_t len[], uint8_t* p_val[]) { uint16_t xx; uint8_t* p; uint8_t* p_head; bool result; - uint8_t* p_buff = - (uint8_t*)osi_malloc(sizeof(uint8_t) * SDP_MAX_ATTR_LEN * 2); + uint8_t* p_buff = (uint8_t*)osi_malloc(sizeof(uint8_t) * SDP_MAX_ATTR_LEN * 2); p = p_buff; @@ -571,14 +567,14 @@ bool SDP_AddSequence(uint32_t handle, uint16_t attr_id, uint16_t num_elem, log::error("SDP_AddSequence - too long(attribute is not added)!!"); osi_free(p_buff); return false; - } else - log::error("SDP_AddSequence - too long, add {} elements of {}", xx, - num_elem); + } else { + log::error("SDP_AddSequence - too long, add {} elements of {}", xx, num_elem); + } break; } } - result = SDP_AddAttribute(handle, attr_id, DATA_ELE_SEQ_DESC_TYPE, - (uint32_t)(p - p_buff), p_buff); + result = + SDP_AddAttribute(handle, attr_id, DATA_ELE_SEQ_DESC_TYPE, (uint32_t)(p - p_buff), p_buff); osi_free(p_buff); return result; } @@ -595,14 +591,12 @@ bool SDP_AddSequence(uint32_t handle, uint16_t attr_id, uint16_t num_elem, * Returns true if added OK, else false * ******************************************************************************/ -bool SDP_AddUuidSequence(uint32_t handle, uint16_t attr_id, uint16_t num_uuids, - uint16_t* p_uuids) { +bool SDP_AddUuidSequence(uint32_t handle, uint16_t attr_id, uint16_t num_uuids, uint16_t* p_uuids) { uint16_t xx; uint8_t* p; int32_t max_len = SDP_MAX_ATTR_LEN - 3; bool result; - uint8_t* p_buff = - (uint8_t*)osi_malloc(sizeof(uint8_t) * SDP_MAX_ATTR_LEN * 2); + uint8_t* p_buff = (uint8_t*)osi_malloc(sizeof(uint8_t) * SDP_MAX_ATTR_LEN * 2); p = p_buff; @@ -612,14 +606,13 @@ bool SDP_AddUuidSequence(uint32_t handle, uint16_t attr_id, uint16_t num_uuids, UINT16_TO_BE_STREAM(p, *p_uuids); if ((p - p_buff) > max_len) { - log::warn("SDP_AddUuidSequence - too long, add {} uuids of {}", xx, - num_uuids); + log::warn("SDP_AddUuidSequence - too long, add {} uuids of {}", xx, num_uuids); break; } } - result = SDP_AddAttribute(handle, attr_id, DATA_ELE_SEQ_DESC_TYPE, - (uint32_t)(p - p_buff), p_buff); + result = + SDP_AddAttribute(handle, attr_id, DATA_ELE_SEQ_DESC_TYPE, (uint32_t)(p - p_buff), p_buff); osi_free(p_buff); return result; } @@ -636,16 +629,14 @@ bool SDP_AddUuidSequence(uint32_t handle, uint16_t attr_id, uint16_t num_uuids, * Returns true if added OK, else false * ******************************************************************************/ -bool SDP_AddProtocolList(uint32_t handle, uint16_t num_elem, - tSDP_PROTOCOL_ELEM* p_elem_list) { +bool SDP_AddProtocolList(uint32_t handle, uint16_t num_elem, tSDP_PROTOCOL_ELEM* p_elem_list) { int offset; bool result; - uint8_t* p_buff = - (uint8_t*)osi_malloc(sizeof(uint8_t) * SDP_MAX_ATTR_LEN * 2); + uint8_t* p_buff = (uint8_t*)osi_malloc(sizeof(uint8_t) * SDP_MAX_ATTR_LEN * 2); offset = sdp_compose_proto_list(p_buff, num_elem, p_elem_list); - result = SDP_AddAttribute(handle, ATTR_ID_PROTOCOL_DESC_LIST, - DATA_ELE_SEQ_DESC_TYPE, (uint32_t)offset, p_buff); + result = SDP_AddAttribute(handle, ATTR_ID_PROTOCOL_DESC_LIST, DATA_ELE_SEQ_DESC_TYPE, + (uint32_t)offset, p_buff); osi_free(p_buff); return result; } @@ -669,8 +660,7 @@ bool SDP_AddAdditionProtoLists(uint32_t handle, uint16_t num_elem, uint8_t* p_len; int offset; bool result; - uint8_t* p_buff = - (uint8_t*)osi_malloc(sizeof(uint8_t) * SDP_MAX_ATTR_LEN * 2); + uint8_t* p_buff = (uint8_t*)osi_malloc(sizeof(uint8_t) * SDP_MAX_ATTR_LEN * 2); p = p_buff; @@ -679,15 +669,13 @@ bool SDP_AddAdditionProtoLists(uint32_t handle, uint16_t num_elem, UINT8_TO_BE_STREAM(p, (DATA_ELE_SEQ_DESC_TYPE << 3) | SIZE_IN_NEXT_BYTE); p_len = p++; - offset = sdp_compose_proto_list(p, p_proto_list->num_elems, - p_proto_list->list_elem); + offset = sdp_compose_proto_list(p, p_proto_list->num_elems, p_proto_list->list_elem); p += offset; *p_len = (uint8_t)(p - p_len - 1); } - result = - SDP_AddAttribute(handle, ATTR_ID_ADDITION_PROTO_DESC_LISTS, - DATA_ELE_SEQ_DESC_TYPE, (uint32_t)(p - p_buff), p_buff); + result = SDP_AddAttribute(handle, ATTR_ID_ADDITION_PROTO_DESC_LISTS, DATA_ELE_SEQ_DESC_TYPE, + (uint32_t)(p - p_buff), p_buff); osi_free(p_buff); return result; } @@ -704,8 +692,7 @@ bool SDP_AddAdditionProtoLists(uint32_t handle, uint16_t num_elem, * Returns true if added OK, else false * ******************************************************************************/ -bool SDP_AddProfileDescriptorList(uint32_t handle, uint16_t profile_uuid, - uint16_t version) { +bool SDP_AddProfileDescriptorList(uint32_t handle, uint16_t profile_uuid, uint16_t version) { uint8_t* p; bool result; uint8_t* p_buff = (uint8_t*)osi_malloc(sizeof(uint8_t) * SDP_MAX_ATTR_LEN); @@ -725,9 +712,8 @@ bool SDP_AddProfileDescriptorList(uint32_t handle, uint16_t profile_uuid, *p_buff = (uint8_t)((DATA_ELE_SEQ_DESC_TYPE << 3) | SIZE_IN_NEXT_BYTE); *(p_buff + 1) = (uint8_t)(p - (p_buff + 2)); - result = - SDP_AddAttribute(handle, ATTR_ID_BT_PROFILE_DESC_LIST, - DATA_ELE_SEQ_DESC_TYPE, (uint32_t)(p - p_buff), p_buff); + result = SDP_AddAttribute(handle, ATTR_ID_BT_PROFILE_DESC_LIST, DATA_ELE_SEQ_DESC_TYPE, + (uint32_t)(p - p_buff), p_buff); osi_free(p_buff); return result; } @@ -744,8 +730,7 @@ bool SDP_AddProfileDescriptorList(uint32_t handle, uint16_t profile_uuid, * Returns true if added OK, else false * ******************************************************************************/ -bool SDP_AddProfileDescriptorListToRecord(tSDP_RECORD* prec, - uint16_t profile_uuid, +bool SDP_AddProfileDescriptorListToRecord(tSDP_RECORD* prec, uint16_t profile_uuid, uint16_t version) { uint8_t* p; bool result; @@ -766,8 +751,7 @@ bool SDP_AddProfileDescriptorListToRecord(tSDP_RECORD* prec, *p_buff = (uint8_t)((DATA_ELE_SEQ_DESC_TYPE << 3) | SIZE_IN_NEXT_BYTE); *(p_buff + 1) = (uint8_t)(p - (p_buff + 2)); - result = SDP_AddAttributeToRecord(prec, ATTR_ID_BT_PROFILE_DESC_LIST, - DATA_ELE_SEQ_DESC_TYPE, + result = SDP_AddAttributeToRecord(prec, ATTR_ID_BT_PROFILE_DESC_LIST, DATA_ELE_SEQ_DESC_TYPE, (uint32_t)(p - p_buff), p_buff); osi_free(p_buff); return result; @@ -785,8 +769,8 @@ bool SDP_AddProfileDescriptorListToRecord(tSDP_RECORD* prec, * Returns true if added OK, else false * ******************************************************************************/ -bool SDP_AddLanguageBaseAttrIDList(uint32_t handle, uint16_t lang, - uint16_t char_enc, uint16_t base_id) { +bool SDP_AddLanguageBaseAttrIDList(uint32_t handle, uint16_t lang, uint16_t char_enc, + uint16_t base_id) { uint8_t* p; bool result; uint8_t* p_buff = (uint8_t*)osi_malloc(sizeof(uint8_t) * SDP_MAX_ATTR_LEN); @@ -804,9 +788,8 @@ bool SDP_AddLanguageBaseAttrIDList(uint32_t handle, uint16_t lang, UINT8_TO_BE_STREAM(p, (UINT_DESC_TYPE << 3) | SIZE_TWO_BYTES); UINT16_TO_BE_STREAM(p, base_id); - result = - SDP_AddAttribute(handle, ATTR_ID_LANGUAGE_BASE_ATTR_ID_LIST, - DATA_ELE_SEQ_DESC_TYPE, (uint32_t)(p - p_buff), p_buff); + result = SDP_AddAttribute(handle, ATTR_ID_LANGUAGE_BASE_ATTR_ID_LIST, DATA_ELE_SEQ_DESC_TYPE, + (uint32_t)(p - p_buff), p_buff); osi_free(p_buff); return result; } @@ -823,13 +806,11 @@ bool SDP_AddLanguageBaseAttrIDList(uint32_t handle, uint16_t lang, * Returns true if added OK, else false * ******************************************************************************/ -bool SDP_AddServiceClassIdList(uint32_t handle, uint16_t num_services, - uint16_t* p_service_uuids) { +bool SDP_AddServiceClassIdList(uint32_t handle, uint16_t num_services, uint16_t* p_service_uuids) { uint16_t xx; uint8_t* p; bool result; - uint8_t* p_buff = - (uint8_t*)osi_malloc(sizeof(uint8_t) * SDP_MAX_ATTR_LEN * 2); + uint8_t* p_buff = (uint8_t*)osi_malloc(sizeof(uint8_t) * SDP_MAX_ATTR_LEN * 2); p = p_buff; @@ -838,9 +819,8 @@ bool SDP_AddServiceClassIdList(uint32_t handle, uint16_t num_services, UINT16_TO_BE_STREAM(p, *p_service_uuids); } - result = - SDP_AddAttribute(handle, ATTR_ID_SERVICE_CLASS_ID_LIST, - DATA_ELE_SEQ_DESC_TYPE, (uint32_t)(p - p_buff), p_buff); + result = SDP_AddAttribute(handle, ATTR_ID_SERVICE_CLASS_ID_LIST, DATA_ELE_SEQ_DESC_TYPE, + (uint32_t)(p - p_buff), p_buff); osi_free(p_buff); return result; } @@ -871,31 +851,31 @@ bool SDP_DeleteAttributeFromRecord(tSDP_RECORD* p_rec, uint16_t attr_id) { if (len) { for (uint16_t zz = 0; zz < p_rec->num_attributes; zz++) { - if (p_rec->attribute[zz].value_ptr > pad_ptr) + if (p_rec->attribute[zz].value_ptr > pad_ptr) { p_rec->attribute[zz].value_ptr -= len; + } } } /* Found it. Shift everything up one */ p_rec->num_attributes--; - for (uint16_t zz = attribute_index; zz < p_rec->num_attributes; - zz++, p_attr++) { + for (uint16_t zz = attribute_index; zz < p_rec->num_attributes; zz++, p_attr++) { *p_attr = *(p_attr + 1); } /* adjust attribute values if needed */ if (len) { uint16_t last_attribute_to_adjust = - (p_rec->free_pad_ptr - ((pad_ptr + len) - &p_rec->attr_pad[0])); + (p_rec->free_pad_ptr - ((pad_ptr + len) - &p_rec->attr_pad[0])); for (uint16_t zz = 0; zz < last_attribute_to_adjust; zz++, pad_ptr++) { *pad_ptr = *(pad_ptr + len); } p_rec->free_pad_ptr -= len; } - return (true); + return true; } } /* If here, not found */ - return (false); + return false; } diff --git a/system/stack/sdp/sdp_discovery.cc b/system/stack/sdp/sdp_discovery.cc index b8dbaf832f7..d0dcfde6bde 100644 --- a/system/stack/sdp/sdp_discovery.cc +++ b/system/stack/sdp/sdp_discovery.cc @@ -55,14 +55,14 @@ using namespace bluetooth; * Returns Pointer to next byte in the output buffer. * ******************************************************************************/ -static uint8_t* sdpu_build_uuid_seq(uint8_t* p_out, uint16_t num_uuids, - Uuid* p_uuid_list, uint16_t& bytes_left) { +static uint8_t* sdpu_build_uuid_seq(uint8_t* p_out, uint16_t num_uuids, Uuid* p_uuid_list, + uint16_t& bytes_left) { uint16_t xx; uint8_t* p_len; if (bytes_left < 2) { DCHECK(0) << "SDP: No space for data element header"; - return (p_out); + return p_out; } /* First thing is the data element header */ @@ -94,8 +94,7 @@ static uint8_t* sdpu_build_uuid_seq(uint8_t* p_out, uint16_t num_uuids, UINT32_TO_BE_STREAM(p_out, p_uuid_list->As32Bit()); } else if (len == Uuid::kNumBytes128) { UINT8_TO_BE_STREAM(p_out, (UUID_DESC_TYPE << 3) | SIZE_SIXTEEN_BYTES); - ARRAY_TO_BE_STREAM(p_out, p_uuid_list->To128BitBE(), - (int)Uuid::kNumBytes128); + ARRAY_TO_BE_STREAM(p_out, p_uuid_list->To128BitBE(), (int)Uuid::kNumBytes128); } else { DCHECK(0) << "SDP: Passed UUID has invalid length " << len; } @@ -105,7 +104,7 @@ static uint8_t* sdpu_build_uuid_seq(uint8_t* p_out, uint16_t num_uuids, xx = (uint16_t)(p_out - p_len - 1); UINT8_TO_BE_STREAM(p_len, xx); - return (p_out); + return p_out; } /******************************************************************************* @@ -117,8 +116,7 @@ static uint8_t* sdpu_build_uuid_seq(uint8_t* p_out, uint16_t num_uuids, * Returns void * ******************************************************************************/ -static void sdp_snd_service_search_req(tCONN_CB* p_ccb, uint8_t cont_len, - uint8_t* p_cont) { +static void sdp_snd_service_search_req(tCONN_CB* p_ccb, uint8_t cont_len, uint8_t* p_cont) { uint8_t *p, *p_start, *p_param_len; BT_HDR* p_cmd = (BT_HDR*)osi_malloc(SDP_DATA_BUF_SIZE); uint16_t param_len; @@ -139,10 +137,10 @@ static void sdp_snd_service_search_req(tCONN_CB* p_ccb, uint8_t cont_len, /* Account for header size, max service record count and * continuation state */ - const uint16_t base_bytes = (sizeof(BT_HDR) + L2CAP_MIN_OFFSET + - 3u + /* service search request header */ - 2u + /* param len */ - 3u + ((p_cont) ? cont_len : 0)); + const uint16_t base_bytes = + (sizeof(BT_HDR) + L2CAP_MIN_OFFSET + 3u + /* service search request header */ + 2u + /* param len */ + 3u + ((p_cont) ? cont_len : 0)); if (base_bytes > bytes_left) { DCHECK(0) << "SDP: Overran SDP data buffer"; @@ -153,8 +151,7 @@ static void sdp_snd_service_search_req(tCONN_CB* p_ccb, uint8_t cont_len, bytes_left -= base_bytes; /* Build the UID sequence. */ - p = sdpu_build_uuid_seq(p, p_ccb->p_db->num_uuid_filters, - p_ccb->p_db->uuid_filters, bytes_left); + p = sdpu_build_uuid_seq(p, p_ccb->p_db->num_uuid_filters, p_ccb->p_db->uuid_filters, bytes_left); /* Set max service record count */ UINT16_TO_BE_STREAM(p, sdp_cb.max_recs_per_search); @@ -177,15 +174,13 @@ static void sdp_snd_service_search_req(tCONN_CB* p_ccb, uint8_t cont_len, /* Set the length of the SDP data in the buffer */ p_cmd->len = (uint16_t)(p - p_start); - if (L2CA_DataWrite(p_ccb->connection_id, p_cmd) != - tL2CAP_DW_RESULT::SUCCESS) { - log::warn("Unable to write L2CAP data peer:{} cid:{} len:{}", - p_ccb->device_address, p_ccb->connection_id, p_cmd->len); + if (L2CA_DataWrite(p_ccb->connection_id, p_cmd) != tL2CAP_DW_RESULT::SUCCESS) { + log::warn("Unable to write L2CAP data peer:{} cid:{} len:{}", p_ccb->device_address, + p_ccb->connection_id, p_cmd->len); } /* Start inactivity timer */ - alarm_set_on_mloop(p_ccb->sdp_conn_timer, SDP_INACT_TIMEOUT_MS, - sdp_conn_timer_timeout, p_ccb); + alarm_set_on_mloop(p_ccb->sdp_conn_timer, SDP_INACT_TIMEOUT_MS, sdp_conn_timer_timeout, p_ccb); } /******************************************************************************* @@ -255,7 +250,9 @@ tSDP_DISC_REC* add_record(tSDP_DISCOVERY_DB* p_db, const RawAddress& bd_addr) { tSDP_DISC_REC* p_rec; /* See if there is enough space in the database */ - if (p_db->mem_free < sizeof(tSDP_DISC_REC)) return (NULL); + if (p_db->mem_free < sizeof(tSDP_DISC_REC)) { + return NULL; + } p_rec = (tSDP_DISC_REC*)p_db->p_free_mem; p_db->p_free_mem += sizeof(tSDP_DISC_REC); @@ -267,17 +264,19 @@ tSDP_DISC_REC* add_record(tSDP_DISCOVERY_DB* p_db, const RawAddress& bd_addr) { p_rec->remote_bd_addr = bd_addr; /* Add the record to the end of chain */ - if (!p_db->p_first_rec) + if (!p_db->p_first_rec) { p_db->p_first_rec = p_rec; - else { + } else { tSDP_DISC_REC* p_rec1 = p_db->p_first_rec; - while (p_rec1->p_next_rec) p_rec1 = p_rec1->p_next_rec; + while (p_rec1->p_next_rec) { + p_rec1 = p_rec1->p_next_rec; + } p_rec1->p_next_rec = p_rec; } - return (p_rec); + return p_rec; } #define SDP_ADDITIONAL_LIST_MASK 0x80 @@ -291,9 +290,8 @@ tSDP_DISC_REC* add_record(tSDP_DISCOVERY_DB* p_db, const RawAddress& bd_addr) { * Returns pointer to next byte in data stream * ******************************************************************************/ -static uint8_t* add_attr(uint8_t* p, uint8_t* p_end, tSDP_DISCOVERY_DB* p_db, - tSDP_DISC_REC* p_rec, uint16_t attr_id, - tSDP_DISC_ATTR* p_parent_attr, uint8_t nest_level) { +static uint8_t* add_attr(uint8_t* p, uint8_t* p_end, tSDP_DISCOVERY_DB* p_db, tSDP_DISC_REC* p_rec, + uint16_t attr_id, tSDP_DISC_ATTR* p_parent_attr, uint8_t nest_level) { tSDP_DISC_ATTR* p_attr; uint32_t attr_len; uint32_t total_len; @@ -315,10 +313,11 @@ static uint8_t* add_attr(uint8_t* p, uint8_t* p_end, tSDP_DISCOVERY_DB* p_db, attr_type = (type >> 3) & 0x0f; /* See if there is enough space in the database */ - if (attr_len > 4) + if (attr_len > 4) { total_len = attr_len - 4 + (uint16_t)sizeof(tSDP_DISC_ATTR); - else + } else { total_len = sizeof(tSDP_DISC_ATTR); + } p_attr_end = p + attr_len; if (p_attr_end > p_end) { @@ -330,7 +329,9 @@ static uint8_t* add_attr(uint8_t* p, uint8_t* p_end, tSDP_DISCOVERY_DB* p_db, total_len = (total_len + 3) & ~3; /* See if there is enough space in the database */ - if (p_db->mem_free < total_len) return (NULL); + if (p_db->mem_free < total_len) { + return NULL; + } p_attr = (tSDP_DISC_ATTR*)p_db->p_free_mem; p_attr->attr_id = attr_id; @@ -342,9 +343,9 @@ static uint8_t* add_attr(uint8_t* p, uint8_t* p_end, tSDP_DISCOVERY_DB* p_db, case UINT_DESC_TYPE: if ((is_additional_list != 0) && (attr_len == 2)) { BE_STREAM_TO_UINT16(id, p); - if (id != ATTR_ID_PROTOCOL_DESC_LIST) + if (id != ATTR_ID_PROTOCOL_DESC_LIST) { p -= 2; - else { + } else { /* Reserve the memory for the attribute now, as we need to add * sub-attributes */ p_db->p_free_mem += sizeof(tSDP_DISC_ATTR); @@ -358,8 +359,8 @@ static uint8_t* add_attr(uint8_t* p, uint8_t* p_end, tSDP_DISCOVERY_DB* p_db, } /* Now, add the list entry */ - p = add_attr(p, p_end, p_db, p_rec, ATTR_ID_PROTOCOL_DESC_LIST, - p_attr, (uint8_t)(nest_level + 1)); + p = add_attr(p, p_end, p_db, p_rec, ATTR_ID_PROTOCOL_DESC_LIST, p_attr, + (uint8_t)(nest_level + 1)); break; } @@ -400,20 +401,17 @@ static uint8_t* add_attr(uint8_t* p, uint8_t* p_end, tSDP_DISCOVERY_DB* p_db, /* See if we can compress the UUID down to 16 or 32bit UUIDs */ if (sdpu_is_base_uuid(p)) { if ((p[0] == 0) && (p[1] == 0)) { - p_attr->attr_len_type = - (p_attr->attr_len_type & ~SDP_DISC_ATTR_LEN_MASK) | 2; + p_attr->attr_len_type = (p_attr->attr_len_type & ~SDP_DISC_ATTR_LEN_MASK) | 2; p += 2; BE_STREAM_TO_UINT16(p_attr->attr_value.v.u16, p); p += Uuid::kNumBytes128 - 4; } else { - p_attr->attr_len_type = - (p_attr->attr_len_type & ~SDP_DISC_ATTR_LEN_MASK) | 4; + p_attr->attr_len_type = (p_attr->attr_len_type & ~SDP_DISC_ATTR_LEN_MASK) | 4; BE_STREAM_TO_UINT32(p_attr->attr_value.v.u32, p); p += Uuid::kNumBytes128 - 4; } } else { - BE_STREAM_TO_ARRAY(p, p_attr->attr_value.v.array, - (int32_t)attr_len); + BE_STREAM_TO_ARRAY(p, p_attr->attr_value.v.array, (int32_t)attr_len); } break; default: @@ -435,17 +433,18 @@ static uint8_t* add_attr(uint8_t* p, uint8_t* p_end, tSDP_DISCOVERY_DB* p_db, log::error("SDP - attr nesting too deep"); return p_attr_end; } - if (is_additional_list != 0 || - attr_id == ATTR_ID_ADDITION_PROTO_DESC_LISTS) + if (is_additional_list != 0 || attr_id == ATTR_ID_ADDITION_PROTO_DESC_LISTS) { nest_level |= SDP_ADDITIONAL_LIST_MASK; + } /* LOG_VERBOSE ("SDP - attr nest level:0x%x(finish)", nest_level); */ while (p < p_attr_end) { /* Now, add the list entry */ - p = add_attr(p, p_end, p_db, p_rec, 0, p_attr, - (uint8_t)(nest_level + 1)); + p = add_attr(p, p_end, p_db, p_rec, 0, p_attr, (uint8_t)(nest_level + 1)); - if (!p) return (NULL); + if (!p) { + return NULL; + } } break; @@ -474,12 +473,14 @@ static uint8_t* add_attr(uint8_t* p, uint8_t* p_end, tSDP_DISCOVERY_DB* p_db, /* Add the attribute to the end of the chain */ if (!p_parent_attr) { - if (!p_rec->p_first_attr) + if (!p_rec->p_first_attr) { p_rec->p_first_attr = p_attr; - else { + } else { tSDP_DISC_ATTR* p_attr1 = p_rec->p_first_attr; - while (p_attr1->p_next_attr) p_attr1 = p_attr1->p_next_attr; + while (p_attr1->p_next_attr) { + p_attr1 = p_attr1->p_next_attr; + } p_attr1->p_next_attr = p_attr; } @@ -493,14 +494,16 @@ static uint8_t* add_attr(uint8_t* p, uint8_t* p_end, tSDP_DISCOVERY_DB* p_db, /* LOG_VERBOSE ("parent:0x%x(id:%d), ch1:0x%x(id:%d)", p_parent_attr, p_parent_attr->attr_id, p_attr1, p_attr1->attr_id); */ - while (p_attr1->p_next_attr) p_attr1 = p_attr1->p_next_attr; + while (p_attr1->p_next_attr) { + p_attr1 = p_attr1->p_next_attr; + } p_attr1->p_next_attr = p_attr; /* LOG_VERBOSE ("new ch:0x%x(id:%d)", p_attr, p_attr->attr_id); */ } } - return (p); + return p; } /******************************************************************************* @@ -523,19 +526,19 @@ static uint8_t* save_attr_seq(tCONN_CB* p_ccb, uint8_t* p, uint8_t* p_msg_end) { if ((type >> 3) != DATA_ELE_SEQ_DESC_TYPE) { log::warn("SDP - Wrong type: 0x{:02x} in attr_rsp", type); - return (NULL); + return NULL; } p = sdpu_get_len_from_type(p, p_msg_end, type, &seq_len); if (p == NULL || (p + seq_len) > p_msg_end) { log::warn("SDP - Bad len in attr_rsp {}", seq_len); - return (NULL); + return NULL; } /* Create a record */ p_rec = add_record(p_ccb->p_db, p_ccb->device_address); if (!p_rec) { log::warn("SDP - DB full add_record"); - return (NULL); + return NULL; } p_seq_end = p + seq_len; @@ -546,12 +549,11 @@ static uint8_t* save_attr_seq(tCONN_CB* p_ccb, uint8_t* p, uint8_t* p_msg_end) { p = sdpu_get_len_from_type(p, p_msg_end, type, &attr_len); if (p == NULL || (p + attr_len) > p_seq_end) { log::warn("Bad len in attr_rsp {}", attr_len); - return (NULL); + return NULL; } if (((type >> 3) != UINT_DESC_TYPE) || (attr_len != 2)) { - log::warn("SDP - Bad type: 0x{:02x} or len: {} in attr_rsp", type, - attr_len); - return (NULL); + log::warn("SDP - Bad type: 0x{:02x} or len: {} in attr_rsp", type, attr_len); + return NULL; } BE_STREAM_TO_UINT16(attr_id, p); @@ -560,11 +562,11 @@ static uint8_t* save_attr_seq(tCONN_CB* p_ccb, uint8_t* p, uint8_t* p_msg_end) { if (!p) { log::warn("SDP - DB full add_attr"); - return (NULL); + return NULL; } } - return (p); + return p; } /******************************************************************************* @@ -587,8 +589,7 @@ static void process_service_search_attr_rsp(tCONN_CB* p_ccb, uint8_t* p_reply, /* If p_reply is NULL, we were called for the initial read */ if (p_reply) { - if (p_reply + 4 /* transaction ID and length */ + sizeof(lists_byte_count) > - p_reply_end) { + if (p_reply + 4 /* transaction ID and length */ + sizeof(lists_byte_count) > p_reply_end) { sdp_disconnect(p_ccb, SDP_INVALID_PDU_SIZE); return; } @@ -610,8 +611,9 @@ static void process_service_search_attr_rsp(tCONN_CB* p_ccb, uint8_t* p_reply, return; } - if (p_ccb->rsp_list == NULL) + if (p_ccb->rsp_list == NULL) { p_ccb->rsp_list = (uint8_t*)osi_malloc(SDP_MAX_LIST_BYTE_COUNT); + } memcpy(&p_ccb->rsp_list[p_ccb->list_len], p_reply, lists_byte_count); p_ccb->list_len += lists_byte_count; p_reply += lists_byte_count; @@ -645,11 +647,11 @@ static void process_service_search_attr_rsp(tCONN_CB* p_ccb, uint8_t* p_reply, /* Account for header size, max service record count and * continuation state */ - const uint16_t base_bytes = (sizeof(BT_HDR) + L2CAP_MIN_OFFSET + - 3u + /* service search request header */ - 2u + /* param len */ - 3u + /* max service record count */ - ((p_reply) ? (*p_reply) : 0)); + const uint16_t base_bytes = + (sizeof(BT_HDR) + L2CAP_MIN_OFFSET + 3u + /* service search request header */ + 2u + /* param len */ + 3u + /* max service record count */ + ((p_reply) ? (*p_reply) : 0)); if (base_bytes > bytes_left) { sdp_disconnect(p_ccb, SDP_INVALID_CONT_STATE); @@ -659,18 +661,18 @@ static void process_service_search_attr_rsp(tCONN_CB* p_ccb, uint8_t* p_reply, bytes_left -= base_bytes; /* Build the UID sequence. */ - p = sdpu_build_uuid_seq(p, p_ccb->p_db->num_uuid_filters, - p_ccb->p_db->uuid_filters, bytes_left); + p = sdpu_build_uuid_seq(p, p_ccb->p_db->num_uuid_filters, p_ccb->p_db->uuid_filters, + bytes_left); /* Max attribute byte count */ UINT16_TO_BE_STREAM(p, sdp_cb.max_attr_list_size); /* If no attribute filters, build a wildcard attribute sequence */ - if (p_ccb->p_db->num_attr_filters) - p = sdpu_build_attrib_seq(p, p_ccb->p_db->attr_filters, - p_ccb->p_db->num_attr_filters); - else + if (p_ccb->p_db->num_attr_filters) { + p = sdpu_build_attrib_seq(p, p_ccb->p_db->attr_filters, p_ccb->p_db->num_attr_filters); + } else { p = sdpu_build_attrib_seq(p, NULL, 0); + } /* No continuation for first request */ if (p_reply) { @@ -678,8 +680,9 @@ static void process_service_search_attr_rsp(tCONN_CB* p_ccb, uint8_t* p_reply, memcpy(p, p_reply, *p_reply + 1); p += *p_reply + 1; } - } else + } else { UINT8_TO_BE_STREAM(p, 0); + } /* Go back and put the parameter length into the buffer */ param_len = p - p_param_len - 2; @@ -688,22 +691,20 @@ static void process_service_search_attr_rsp(tCONN_CB* p_ccb, uint8_t* p_reply, /* Set the length of the SDP data in the buffer */ p_msg->len = p - p_start; - if (L2CA_DataWrite(p_ccb->connection_id, p_msg) != - tL2CAP_DW_RESULT::SUCCESS) { - log::warn("Unable to write L2CAP data peer:{} cid:{} len:{}", - p_ccb->device_address, p_ccb->connection_id, p_msg->len); + if (L2CA_DataWrite(p_ccb->connection_id, p_msg) != tL2CAP_DW_RESULT::SUCCESS) { + log::warn("Unable to write L2CAP data peer:{} cid:{} len:{}", p_ccb->device_address, + p_ccb->connection_id, p_msg->len); } /* Start inactivity timer */ - alarm_set_on_mloop(p_ccb->sdp_conn_timer, SDP_INACT_TIMEOUT_MS, - sdp_conn_timer_timeout, p_ccb); + alarm_set_on_mloop(p_ccb->sdp_conn_timer, SDP_INACT_TIMEOUT_MS, sdp_conn_timer_timeout, p_ccb); return; } -/*******************************************************************/ -/* We now have the full response, which is a sequence of sequences */ -/*******************************************************************/ + /*******************************************************************/ + /* We now have the full response, which is a sequence of sequences */ + /*******************************************************************/ if (!sdp_copy_raw_data(p_ccb, true)) { log::error("sdp_copy_raw_data failed"); @@ -757,16 +758,14 @@ static void process_service_search_attr_rsp(tCONN_CB* p_ccb, uint8_t* p_reply, * Returns void * ******************************************************************************/ -static void process_service_attr_rsp(tCONN_CB* p_ccb, uint8_t* p_reply, - uint8_t* p_reply_end) { +static void process_service_attr_rsp(tCONN_CB* p_ccb, uint8_t* p_reply, uint8_t* p_reply_end) { uint8_t *p_start, *p_param_len; uint16_t param_len, list_byte_count; bool cont_request_needed = false; /* If p_reply is NULL, we were called after the records handles were read */ if (p_reply) { - if (p_reply + 4 /* transaction ID and length */ + sizeof(list_byte_count) > - p_reply_end) { + if (p_reply + 4 /* transaction ID and length */ + sizeof(list_byte_count) > p_reply_end) { sdp_disconnect(p_ccb, SDP_INVALID_PDU_SIZE); return; } @@ -788,8 +787,9 @@ static void process_service_attr_rsp(tCONN_CB* p_ccb, uint8_t* p_reply, return; } - if (p_ccb->rsp_list == NULL) + if (p_ccb->rsp_list == NULL) { p_ccb->rsp_list = (uint8_t*)osi_malloc(SDP_MAX_LIST_BYTE_COUNT); + } memcpy(&p_ccb->rsp_list[p_ccb->list_len], p_reply, list_byte_count); p_ccb->list_len += list_byte_count; p_reply += list_byte_count; @@ -808,8 +808,7 @@ static void process_service_attr_rsp(tCONN_CB* p_ccb, uint8_t* p_reply, } /* Save the response in the database. Stop on any error */ - if (!save_attr_seq(p_ccb, &p_ccb->rsp_list[0], - &p_ccb->rsp_list[p_ccb->list_len])) { + if (!save_attr_seq(p_ccb, &p_ccb->rsp_list[0], &p_ccb->rsp_list[p_ccb->list_len])) { sdp_disconnect(p_ccb, SDP_DB_FULL); return; } @@ -841,11 +840,11 @@ static void process_service_attr_rsp(tCONN_CB* p_ccb, uint8_t* p_reply, UINT16_TO_BE_STREAM(p, sdp_cb.max_attr_list_size); /* If no attribute filters, build a wildcard attribute sequence */ - if (p_ccb->p_db->num_attr_filters) - p = sdpu_build_attrib_seq(p, p_ccb->p_db->attr_filters, - p_ccb->p_db->num_attr_filters); - else + if (p_ccb->p_db->num_attr_filters) { + p = sdpu_build_attrib_seq(p, p_ccb->p_db->attr_filters, p_ccb->p_db->num_attr_filters); + } else { p = sdpu_build_attrib_seq(p, NULL, 0); + } /* Was this a continuation request ? */ if (cont_request_needed) { @@ -853,8 +852,9 @@ static void process_service_attr_rsp(tCONN_CB* p_ccb, uint8_t* p_reply, memcpy(p, p_reply, *p_reply + 1); p += *p_reply + 1; } - } else + } else { UINT8_TO_BE_STREAM(p, 0); + } /* Go back and put the parameter length into the buffer */ param_len = (uint16_t)(p - p_param_len - 2); @@ -863,15 +863,13 @@ static void process_service_attr_rsp(tCONN_CB* p_ccb, uint8_t* p_reply, /* Set the length of the SDP data in the buffer */ p_msg->len = (uint16_t)(p - p_start); - if (L2CA_DataWrite(p_ccb->connection_id, p_msg) != - tL2CAP_DW_RESULT::SUCCESS) { - log::warn("Unable to write L2CAP data peer:{} cid:{} len:{}", - p_ccb->device_address, p_ccb->connection_id, p_msg->len); + if (L2CA_DataWrite(p_ccb->connection_id, p_msg) != tL2CAP_DW_RESULT::SUCCESS) { + log::warn("Unable to write L2CAP data peer:{} cid:{} len:{}", p_ccb->device_address, + p_ccb->connection_id, p_msg->len); } /* Start inactivity timer */ - alarm_set_on_mloop(p_ccb->sdp_conn_timer, SDP_INACT_TIMEOUT_MS, - sdp_conn_timer_timeout, p_ccb); + alarm_set_on_mloop(p_ccb->sdp_conn_timer, SDP_INACT_TIMEOUT_MS, sdp_conn_timer_timeout, p_ccb); } else { sdpu_log_attribute_metrics(p_ccb->device_address, p_ccb->p_db); sdp_disconnect(p_ccb, SDP_SUCCESS); @@ -889,8 +887,7 @@ static void process_service_attr_rsp(tCONN_CB* p_ccb, uint8_t* p_reply, * Returns void * ******************************************************************************/ -static void process_service_search_rsp(tCONN_CB* p_ccb, uint8_t* p_reply, - uint8_t* p_reply_end) { +static void process_service_search_rsp(tCONN_CB* p_ccb, uint8_t* p_reply, uint8_t* p_reply_end) { uint16_t xx; uint16_t total, cur_handles, orig; uint8_t cont_len; @@ -913,17 +910,21 @@ static void process_service_search_rsp(tCONN_CB* p_ccb, uint8_t* p_reply, } /* Save the handles that match. We will can only process a certain number. */ - if (total > sdp_cb.max_recs_per_search) total = sdp_cb.max_recs_per_search; - if (p_ccb->num_handles > sdp_cb.max_recs_per_search) + if (total > sdp_cb.max_recs_per_search) { + total = sdp_cb.max_recs_per_search; + } + if (p_ccb->num_handles > sdp_cb.max_recs_per_search) { p_ccb->num_handles = sdp_cb.max_recs_per_search; + } if (p_reply + ((p_ccb->num_handles - orig) * 4) + 1 > p_reply_end) { sdp_disconnect(p_ccb, SDP_GENERIC_ERROR); return; } - for (xx = orig; xx < p_ccb->num_handles; xx++) + for (xx = orig; xx < p_ccb->num_handles; xx++) { BE_STREAM_TO_UINT32(p_ccb->handles[xx], p_reply); + } BE_STREAM_TO_UINT8(cont_len, p_reply); if (cont_len != 0) { diff --git a/system/stack/sdp/sdp_discovery_db.h b/system/stack/sdp/sdp_discovery_db.h index ac727df406e..2e71c7c9347 100644 --- a/system/stack/sdp/sdp_discovery_db.h +++ b/system/stack/sdp/sdp_discovery_db.h @@ -27,7 +27,7 @@ /* Masks for attr_value field of tSDP_DISC_ATTR */ #define SDP_DISC_ATTR_LEN_MASK 0x0FFF #define SDP_DISC_ATTR_TYPE(len_type) ((len_type) >> 12) -#define SDP_DISC_ATTR_LEN(len_type) ((len_type)&SDP_DISC_ATTR_LEN_MASK) +#define SDP_DISC_ATTR_LEN(len_type) ((len_type) & SDP_DISC_ATTR_LEN_MASK) #define SDP_MAX_LIST_ELEMS 3 @@ -61,16 +61,15 @@ typedef struct t_sdp_disc_rec { } tSDP_DISC_REC; typedef struct { - uint32_t mem_size; /* Memory size of the DB */ - uint32_t mem_free; /* Memory still available */ - tSDP_DISC_REC* p_first_rec; /* Addr of first record in DB */ - uint16_t num_uuid_filters; /* Number of UUIds to filter */ + uint32_t mem_size; /* Memory size of the DB */ + uint32_t mem_free; /* Memory still available */ + tSDP_DISC_REC* p_first_rec; /* Addr of first record in DB */ + uint16_t num_uuid_filters; /* Number of UUIds to filter */ bluetooth::Uuid uuid_filters[SDP_MAX_UUID_FILTERS]; /* UUIDs to filter */ - uint16_t num_attr_filters; /* Number of attribute filters */ - uint16_t attr_filters[SDP_MAX_ATTR_FILTERS]; /* Attributes to filter */ - uint8_t* p_free_mem; /* Pointer to free memory */ - uint8_t* - raw_data; /* Received record from server. allocated/released by client */ + uint16_t num_attr_filters; /* Number of attribute filters */ + uint16_t attr_filters[SDP_MAX_ATTR_FILTERS]; /* Attributes to filter */ + uint8_t* p_free_mem; /* Pointer to free memory */ + uint8_t* raw_data; /* Received record from server. allocated/released by client */ uint32_t raw_size; /* size of raw_data */ uint32_t raw_used; /* length of raw_data used */ } tSDP_DISCOVERY_DB; diff --git a/system/stack/sdp/sdp_main.cc b/system/stack/sdp/sdp_main.cc index f7aad629d14..24dbabe9fa0 100644 --- a/system/stack/sdp/sdp_main.cc +++ b/system/stack/sdp/sdp_main.cc @@ -56,10 +56,12 @@ tSDP_CB sdp_cb; * Returns void * ******************************************************************************/ -static void sdp_connect_ind(const RawAddress& bd_addr, uint16_t l2cap_cid, - uint16_t /* psm */, uint8_t /* l2cap_id */) { +static void sdp_connect_ind(const RawAddress& bd_addr, uint16_t l2cap_cid, uint16_t /* psm */, + uint8_t /* l2cap_id */) { tCONN_CB* p_ccb = sdpu_allocate_ccb(); - if (p_ccb == NULL) return; + if (p_ccb == NULL) { + return; + } /* Transition to the next appropriate state, waiting for config setup. */ p_ccb->con_state = tSDP_STATE::CFG_SETUP; @@ -71,7 +73,9 @@ static void sdp_connect_ind(const RawAddress& bd_addr, uint16_t l2cap_cid, static void sdp_on_l2cap_error(uint16_t l2cap_cid, uint16_t /* result */) { tCONN_CB* p_ccb = sdpu_find_ccb_by_cid(l2cap_cid); - if (p_ccb == nullptr) return; + if (p_ccb == nullptr) { + return; + } sdp_disconnect(p_ccb, SDP_CFG_FAILED); } @@ -98,8 +102,7 @@ static void sdp_connect_cfm(uint16_t l2cap_cid, uint16_t result) { /* If the connection response contains success status, then */ /* Transition to the next state and startup the timer. */ - if ((result == L2CAP_CONN_OK) && - (p_ccb->con_state == tSDP_STATE::CONN_SETUP)) { + if ((result == L2CAP_CONN_OK) && (p_ccb->con_state == tSDP_STATE::CONN_SETUP)) { p_ccb->con_state = tSDP_STATE::CFG_SETUP; } else { log::error("invoked with non OK status"); @@ -129,13 +132,13 @@ static void sdp_config_ind(uint16_t l2cap_cid, tL2CAP_CFG_INFO* p_cfg) { /* Remember the remote MTU size */ if (!p_cfg->mtu_present) { /* use min(L2CAP_DEFAULT_MTU,SDP_MTU_SIZE) for GKI buffer size reasons */ - p_ccb->rem_mtu_size = - (L2CAP_DEFAULT_MTU > SDP_MTU_SIZE) ? SDP_MTU_SIZE : L2CAP_DEFAULT_MTU; + p_ccb->rem_mtu_size = (L2CAP_DEFAULT_MTU > SDP_MTU_SIZE) ? SDP_MTU_SIZE : L2CAP_DEFAULT_MTU; } else { - if (p_cfg->mtu > SDP_MTU_SIZE) + if (p_cfg->mtu > SDP_MTU_SIZE) { p_ccb->rem_mtu_size = SDP_MTU_SIZE; - else + } else { p_ccb->rem_mtu_size = p_cfg->mtu; + } } log::verbose("SDP - Rcvd cfg ind, sent cfg cfm, CID: 0x{:x}", l2cap_cid); @@ -151,8 +154,7 @@ static void sdp_config_ind(uint16_t l2cap_cid, tL2CAP_CFG_INFO* p_cfg) { * Returns void * ******************************************************************************/ -static void sdp_config_cfm(uint16_t l2cap_cid, uint16_t /* initiator */, - tL2CAP_CFG_INFO* p_cfg) { +static void sdp_config_cfm(uint16_t l2cap_cid, uint16_t /* initiator */, tL2CAP_CFG_INFO* p_cfg) { sdp_config_ind(l2cap_cid, p_cfg); tCONN_CB* p_ccb; @@ -173,8 +175,7 @@ static void sdp_config_cfm(uint16_t l2cap_cid, uint16_t /* initiator */, sdp_disc_connected(p_ccb); } else { /* Start inactivity timer */ - alarm_set_on_mloop(p_ccb->sdp_conn_timer, SDP_INACT_TIMEOUT_MS, - sdp_conn_timer_timeout, p_ccb); + alarm_set_on_mloop(p_ccb->sdp_conn_timer, SDP_INACT_TIMEOUT_MS, sdp_conn_timer_timeout, p_ccb); } } @@ -200,7 +201,7 @@ static void sdp_disconnect_ind(uint16_t l2cap_cid, bool ack_needed) { tCONN_CB& ccb = *p_ccb; const tSDP_REASON reason = - (ccb.con_state == tSDP_STATE::CONNECTED) ? SDP_SUCCESS : SDP_CONN_FAILED; + (ccb.con_state == tSDP_STATE::CONNECTED) ? SDP_SUCCESS : SDP_CONN_FAILED; sdpu_callback(ccb, reason); if (ack_needed) { @@ -236,10 +237,11 @@ static void sdp_data_ind(uint16_t l2cap_cid, BT_HDR* p_msg) { p_ccb = sdpu_find_ccb_by_cid(l2cap_cid); if (p_ccb != NULL) { if (p_ccb->con_state == tSDP_STATE::CONNECTED) { - if (p_ccb->con_flags & SDP_FLAGS_IS_ORIG) + if (p_ccb->con_flags & SDP_FLAGS_IS_ORIG) { sdp_disc_server_rsp(p_ccb, p_msg); - else + } else { sdp_server_handle_client_req(p_ccb, p_msg); + } } else { log::warn("SDP - Ignored L2CAP data while in state: {}, CID: 0x{:x}", sdp_state_text(p_ccb->con_state), l2cap_cid); @@ -269,7 +271,7 @@ tCONN_CB* sdp_conn_originate(const RawAddress& bd_addr) { p_ccb = sdpu_allocate_ccb(); if (p_ccb == NULL) { log::warn("no spare CCB for peer {}", bd_addr); - return (NULL); + return NULL; } log::verbose("SDP - Originate started for peer {}", bd_addr); @@ -284,8 +286,7 @@ tCONN_CB* sdp_conn_originate(const RawAddress& bd_addr) { p_ccb->device_address = bd_addr; /* Transition to the next appropriate state, waiting for connection confirm */ - if (!bluetooth::common::init_flags::sdp_serialization_is_enabled() || - cid == 0) { + if (!bluetooth::common::init_flags::sdp_serialization_is_enabled() || cid == 0) { p_ccb->con_state = tSDP_STATE::CONN_SETUP; cid = L2CA_ConnectReqWithSecurity(BT_PSM_SDP, bd_addr, BTM_SEC_NONE); } else { @@ -297,10 +298,10 @@ tCONN_CB* sdp_conn_originate(const RawAddress& bd_addr) { if (cid == 0) { log::warn("SDP - Originate failed for peer {}", bd_addr); sdpu_release_ccb(*p_ccb); - return (NULL); + return NULL; } p_ccb->connection_id = cid; - return (p_ccb); + return p_ccb; } /******************************************************************************* @@ -325,8 +326,8 @@ void sdp_disconnect(tCONN_CB* p_ccb, tSDP_REASON reason) { return; } else { if (!L2CA_DisconnectReq(ccb.connection_id)) { - log::warn("Unable to disconnect L2CAP peer:{} cid:{}", - ccb.device_address, ccb.connection_id); + log::warn("Unable to disconnect L2CAP peer:{} cid:{}", ccb.device_address, + ccb.connection_id); } } } @@ -380,12 +381,11 @@ static void sdp_disconnect_cfm(uint16_t l2cap_cid, uint16_t /* result */) { void sdp_conn_timer_timeout(void* data) { tCONN_CB& ccb = *(tCONN_CB*)data; - log::verbose("SDP - CCB timeout in state: {} CID: 0x{:x}", - sdp_state_text(ccb.con_state), ccb.connection_id); + log::verbose("SDP - CCB timeout in state: {} CID: 0x{:x}", sdp_state_text(ccb.con_state), + ccb.connection_id); if (!L2CA_DisconnectReq(ccb.connection_id)) { - log::warn("Unable to disconnect L2CAP peer:{} cid:{}", ccb.device_address, - ccb.connection_id); + log::warn("Unable to disconnect L2CAP peer:{} cid:{}", ccb.device_address, ccb.connection_id); } sdpu_callback(ccb, SDP_CONN_FAILED); @@ -427,9 +427,8 @@ void sdp_init(void) { sdp_cb.reg_info.pL2CA_Error_Cb = sdp_on_l2cap_error; /* Now, register with L2CAP */ - if (!L2CA_RegisterWithSecurity(BT_PSM_SDP, sdp_cb.reg_info, - true /* enable_snoop */, nullptr, SDP_MTU_SIZE, - 0, BTM_SEC_NONE)) { + if (!L2CA_RegisterWithSecurity(BT_PSM_SDP, sdp_cb.reg_info, true /* enable_snoop */, nullptr, + SDP_MTU_SIZE, 0, BTM_SEC_NONE)) { log::error("SDP Registration failed"); } } diff --git a/system/stack/sdp/sdp_server.cc b/system/stack/sdp/sdp_server.cc index f7c68eec83f..351de1934eb 100644 --- a/system/stack/sdp/sdp_server.cc +++ b/system/stack/sdp/sdp_server.cc @@ -129,21 +129,18 @@ static tSDP_PSE_LOCAL_RECORD sdpPseLocalRecord; +***************************************************************************************/ bool sdp_dynamic_change_hfp_version(const tSDP_ATTRIBUTE* p_attr, const RawAddress& remote_address) { - if ((p_attr->id != ATTR_ID_BT_PROFILE_DESC_LIST) || - (p_attr->len < SDP_PROFILE_DESC_LENGTH)) { + if ((p_attr->id != ATTR_ID_BT_PROFILE_DESC_LIST) || (p_attr->len < SDP_PROFILE_DESC_LENGTH)) { return false; } /* As per current DB implementation UUID is condidered as 16 bit */ - if (((p_attr->value_ptr[3] << SDP_PROFILE_DESC_LENGTH) | - (p_attr->value_ptr[4])) != UUID_SERVCLASS_HF_HANDSFREE) { + if (((p_attr->value_ptr[3] << SDP_PROFILE_DESC_LENGTH) | (p_attr->value_ptr[4])) != + UUID_SERVCLASS_HF_HANDSFREE) { return false; } - bool is_allowlisted_1_7 = - interop_match_addr_or_name(INTEROP_HFP_1_7_ALLOWLIST, &remote_address, - &btif_storage_get_remote_device_property); - bool is_allowlisted_1_9 = - interop_match_addr_or_name(INTEROP_HFP_1_9_ALLOWLIST, &remote_address, - &btif_storage_get_remote_device_property); + bool is_allowlisted_1_7 = interop_match_addr_or_name(INTEROP_HFP_1_7_ALLOWLIST, &remote_address, + &btif_storage_get_remote_device_property); + bool is_allowlisted_1_9 = interop_match_addr_or_name(INTEROP_HFP_1_9_ALLOWLIST, &remote_address, + &btif_storage_get_remote_device_property); /* For PTS we should update AG's HFP version as 1.7 */ if (!(is_allowlisted_1_7) && !(is_allowlisted_1_9) && !(osi_property_get_bool("vendor.bt.pts.certification", false))) { @@ -154,8 +151,8 @@ bool sdp_dynamic_change_hfp_version(const tSDP_ATTRIBUTE* p_attr, } else { p_attr->value_ptr[PROFILE_VERSION_POSITION] = HFP_PROFILE_MINOR_VERSION_7; } - log::verbose("SDP Change HFP Version = {} for {}", - p_attr->value_ptr[PROFILE_VERSION_POSITION], remote_address); + log::verbose("SDP Change HFP Version = {} for {}", p_attr->value_ptr[PROFILE_VERSION_POSITION], + remote_address); return true; } /****************************************************************************** @@ -185,9 +182,8 @@ void hfp_fallback(bool& is_hfp_fallback, const tSDP_ATTRIBUTE* p_attr) { * Returns void * ******************************************************************************/ -static void process_service_search(tCONN_CB* p_ccb, uint16_t trans_num, - uint16_t param_len, uint8_t* p_req, - uint8_t* p_req_end) { +static void process_service_search(tCONN_CB* p_ccb, uint16_t trans_num, uint16_t param_len, + uint8_t* p_req, uint8_t* p_req_end) { uint16_t max_replies, cur_handles, rem_handles, cont_offset; tSDP_UUID_SEQ uid_seq; uint8_t *p_rsp, *p_rsp_start, *p_rsp_param_len; @@ -199,8 +195,7 @@ static void process_service_search(tCONN_CB* p_ccb, uint16_t trans_num, p_req = sdpu_extract_uid_seq(p_req, param_len, &uid_seq); if ((!p_req) || (!uid_seq.num_uids)) { - sdpu_build_n_send_error(p_ccb, trans_num, SDP_INVALID_REQ_SYNTAX, - SDP_TEXT_BAD_UUID_LIST); + sdpu_build_n_send_error(p_ccb, trans_num, SDP_INVALID_REQ_SYNTAX, SDP_TEXT_BAD_UUID_LIST); return; } @@ -212,41 +207,39 @@ static void process_service_search(tCONN_CB* p_ccb, uint16_t trans_num, } BE_STREAM_TO_UINT16(max_replies, p_req); - if (max_replies > SDP_MAX_RECORDS) max_replies = SDP_MAX_RECORDS; + if (max_replies > SDP_MAX_RECORDS) { + max_replies = SDP_MAX_RECORDS; + } /* Get a list of handles that match the UUIDs given to us */ for (num_rsp_handles = 0; num_rsp_handles < max_replies;) { p_rec = sdp_db_service_search(p_rec, &uid_seq); - if (p_rec) + if (p_rec) { rsp_handles[num_rsp_handles++] = p_rec->record_handle; - else + } else { break; + } } /* Check if this is a continuation request */ if (p_req + 1 > p_req_end) { - sdpu_build_n_send_error(p_ccb, trans_num, SDP_INVALID_CONT_STATE, - SDP_TEXT_BAD_CONT_LEN); + sdpu_build_n_send_error(p_ccb, trans_num, SDP_INVALID_CONT_STATE, SDP_TEXT_BAD_CONT_LEN); return; } if (*p_req) { - if (*p_req++ != SDP_CONTINUATION_LEN || - (p_req + sizeof(cont_offset) > p_req_end)) { - sdpu_build_n_send_error(p_ccb, trans_num, SDP_INVALID_CONT_STATE, - SDP_TEXT_BAD_CONT_LEN); + if (*p_req++ != SDP_CONTINUATION_LEN || (p_req + sizeof(cont_offset) > p_req_end)) { + sdpu_build_n_send_error(p_ccb, trans_num, SDP_INVALID_CONT_STATE, SDP_TEXT_BAD_CONT_LEN); return; } BE_STREAM_TO_UINT16(cont_offset, p_req); if (cont_offset != p_ccb->cont_offset || num_rsp_handles < cont_offset) { - sdpu_build_n_send_error(p_ccb, trans_num, SDP_INVALID_CONT_STATE, - SDP_TEXT_BAD_CONT_INX); + sdpu_build_n_send_error(p_ccb, trans_num, SDP_INVALID_CONT_STATE, SDP_TEXT_BAD_CONT_INX); return; } - rem_handles = - num_rsp_handles - cont_offset; /* extract the remaining handles */ + rem_handles = num_rsp_handles - cont_offset; /* extract the remaining handles */ } else { rem_handles = num_rsp_handles; cont_offset = 0; @@ -254,12 +247,11 @@ static void process_service_search(tCONN_CB* p_ccb, uint16_t trans_num, } /* Calculate how many handles will fit in one PDU */ - cur_handles = - (uint16_t)((p_ccb->rem_mtu_size - SDP_MAX_SERVICE_RSPHDR_LEN) / 4); + cur_handles = (uint16_t)((p_ccb->rem_mtu_size - SDP_MAX_SERVICE_RSPHDR_LEN) / 4); - if (rem_handles <= cur_handles) + if (rem_handles <= cur_handles) { cur_handles = rem_handles; - else /* Continuation is set */ + } else /* Continuation is set */ { p_ccb->cont_offset += cur_handles; is_cont = true; @@ -286,14 +278,16 @@ static void process_service_search(tCONN_CB* p_ccb, uint16_t trans_num, log::verbose("SDP Service Rsp: tothdl {}, curhdlr {}, start {}, end {}, cont {}", num_rsp_handles, cur_handles, cont_offset, cont_offset + cur_handles-1, is_cont); */ - for (xx = cont_offset; xx < cont_offset + cur_handles; xx++) + for (xx = cont_offset; xx < cont_offset + cur_handles; xx++) { UINT32_TO_BE_STREAM(p_rsp, rsp_handles[xx]); + } if (is_cont) { UINT8_TO_BE_STREAM(p_rsp, SDP_CONTINUATION_LEN); UINT16_TO_BE_STREAM(p_rsp, p_ccb->cont_offset); - } else + } else { UINT8_TO_BE_STREAM(p_rsp, 0); + } /* Go back and put the parameter length into the buffer */ rsp_param_len = p_rsp - p_rsp_param_len - 2; @@ -303,10 +297,9 @@ static void process_service_search(tCONN_CB* p_ccb, uint16_t trans_num, p_buf->len = p_rsp - p_rsp_start; /* Send the buffer through L2CAP */ - if (L2CA_DataWrite(p_ccb->connection_id, p_buf) != - tL2CAP_DW_RESULT::SUCCESS) { - log::warn("Unable to write L2CAP data peer:{} cid:{} len:{}", - p_ccb->device_address, p_ccb->connection_id, p_buf->len); + if (L2CA_DataWrite(p_ccb->connection_id, p_buf) != tL2CAP_DW_RESULT::SUCCESS) { + log::warn("Unable to write L2CAP data peer:{} cid:{} len:{}", p_ccb->device_address, + p_ccb->connection_id, p_buf->len); } } @@ -319,28 +312,23 @@ static void process_service_search(tCONN_CB* p_ccb, uint16_t trans_num, ** Returns BOOLEAN ** ***************************************************************************************/ -static bool is_device_in_allowlist_for_pbap(RawAddress remote_address, - bool check_for_1_2) { - if (!check_for_1_2 && - interop_match_addr_or_name(INTEROP_ADV_PBAP_VER_1_1, &remote_address, - &btif_storage_get_remote_device_property)) { +static bool is_device_in_allowlist_for_pbap(RawAddress remote_address, bool check_for_1_2) { + if (!check_for_1_2 && interop_match_addr_or_name(INTEROP_ADV_PBAP_VER_1_1, &remote_address, + &btif_storage_get_remote_device_property)) { log::verbose("device is in allowlist for pbap version < 1.2"); return true; } if (check_for_1_2) { if (btm_sec_is_a_bonded_dev(remote_address)) { - if (interop_match_addr_or_name( - INTEROP_ADV_PBAP_VER_1_2, &remote_address, - &btif_storage_get_remote_device_property)) { + if (interop_match_addr_or_name(INTEROP_ADV_PBAP_VER_1_2, &remote_address, + &btif_storage_get_remote_device_property)) { log::verbose("device is in allowlist for pbap version 1.2"); return true; } } else { const char* p_name = BTM_SecReadDevName(remote_address); - if ((p_name != NULL) && - interop_match_name(INTEROP_ADV_PBAP_VER_1_2, p_name)) { - log::verbose( - "device is not paired & in allowlist for pbap version 1.2"); + if ((p_name != NULL) && interop_match_name(INTEROP_ADV_PBAP_VER_1_2, p_name)) { + log::verbose("device is not paired & in allowlist for pbap version 1.2"); return true; } } @@ -363,25 +351,22 @@ static const tSDP_RECORD* sdp_upgrade_pse_record(const tSDP_RECORD* p_rec, static bool is_pbap_102_supported = FALSE; tSDP_ATTRIBUTE attr = p_rec->attribute[1]; if (!((attr.id == ATTR_ID_SERVICE_CLASS_ID_LIST) && - (((attr.value_ptr[1] << 8) | (attr.value_ptr[2])) == - UUID_SERVCLASS_PBAP_PSE))) { + (((attr.value_ptr[1] << 8) | (attr.value_ptr[2])) == UUID_SERVCLASS_PBAP_PSE))) { // Not a PBAP PSE Record return p_rec; } /* Check if remote supports PBAP 1.2 */ is_pbap_102_supported = btif_storage_is_pce_version_102(remote_address); - bool is_pbap_101_allowlisted = - is_device_in_allowlist_for_pbap(remote_address, false); - bool is_pbap_102_allowlisted = - is_device_in_allowlist_for_pbap(remote_address, true); + bool is_pbap_101_allowlisted = is_device_in_allowlist_for_pbap(remote_address, false); + bool is_pbap_102_allowlisted = is_device_in_allowlist_for_pbap(remote_address, true); bool running_pts = osi_property_get_bool(SDP_ENABLE_PTS_PBAP, false); log::verbose( - "remote BD Addr : {} is_pbap_102_supported : {} is_pbap_101_allowlisted " - "= {} is_pbap_102_allowlisted = {} running_pts = {}", - remote_address, is_pbap_102_supported, is_pbap_101_allowlisted, - is_pbap_102_allowlisted, running_pts); + "remote BD Addr : {} is_pbap_102_supported : {} is_pbap_101_allowlisted " + "= {} is_pbap_102_allowlisted = {} running_pts = {}", + remote_address, is_pbap_102_supported, is_pbap_101_allowlisted, is_pbap_102_allowlisted, + running_pts); if (is_pbap_101_allowlisted || (!is_pbap_102_supported && !is_pbap_102_allowlisted && !running_pts)) { @@ -397,31 +382,29 @@ static const tSDP_RECORD* sdp_upgrade_pse_record(const tSDP_RECORD* p_rec, /* Copying contents of the PBAP 1.1 PSE record to a new 1.2 record */ for (j = 0; j < p_rec->num_attributes; j++, p_attr++) { - SDP_AddAttributeToRecord(&pbap_102_sdp_rec, p_attr->id, p_attr->type, - p_attr->len, p_attr->value_ptr); + SDP_AddAttributeToRecord(&pbap_102_sdp_rec, p_attr->id, p_attr->type, p_attr->len, + p_attr->value_ptr); } /* Add supported repositories 1 byte */ - status &= SDP_AddAttributeToRecord( - &pbap_102_sdp_rec, ATTR_ID_SUPPORTED_REPOSITORIES, UINT_DESC_TYPE, - (uint32_t)1, (uint8_t*)&sdpPseLocalRecord.supported_repositories); + status &= SDP_AddAttributeToRecord(&pbap_102_sdp_rec, ATTR_ID_SUPPORTED_REPOSITORIES, + UINT_DESC_TYPE, (uint32_t)1, + (uint8_t*)&sdpPseLocalRecord.supported_repositories); /* Add in the Bluetooth Profile Descriptor List */ - status &= SDP_AddProfileDescriptorListToRecord( - &pbap_102_sdp_rec, UUID_SERVCLASS_PHONE_ACCESS, - sdpPseLocalRecord.profile_version); + status &= SDP_AddProfileDescriptorListToRecord(&pbap_102_sdp_rec, UUID_SERVCLASS_PHONE_ACCESS, + sdpPseLocalRecord.profile_version); /* Add PBAP 1.2 supported features 4 */ UINT32_TO_BE_STREAM(p_temp, sdpPseLocalRecord.supported_features); - status &= SDP_AddAttributeToRecord(&pbap_102_sdp_rec, - ATTR_ID_PBAP_SUPPORTED_FEATURES, + status &= SDP_AddAttributeToRecord(&pbap_102_sdp_rec, ATTR_ID_PBAP_SUPPORTED_FEATURES, UINT_DESC_TYPE, (uint32_t)4, temp); /* Add the L2CAP PSM */ p_temp = temp; // The macro modifies p_temp, hence rewind. UINT16_TO_BE_STREAM(p_temp, sdpPseLocalRecord.l2cap_psm); - status &= SDP_AddAttributeToRecord(&pbap_102_sdp_rec, ATTR_ID_GOEP_L2CAP_PSM, - UINT_DESC_TYPE, (uint32_t)2, temp); + status &= SDP_AddAttributeToRecord(&pbap_102_sdp_rec, ATTR_ID_GOEP_L2CAP_PSM, UINT_DESC_TYPE, + (uint32_t)2, temp); if (!status) { log::error("FAILED"); @@ -441,9 +424,8 @@ static const tSDP_RECORD* sdp_upgrade_pse_record(const tSDP_RECORD* p_rec, * Returns void * ******************************************************************************/ -static void process_service_attr_req(tCONN_CB* p_ccb, uint16_t trans_num, - uint16_t param_len, uint8_t* p_req, - uint8_t* p_req_end) { +static void process_service_attr_req(tCONN_CB* p_ccb, uint16_t trans_num, uint16_t param_len, + uint8_t* p_req, uint8_t* p_req_end) { uint16_t max_list_len, len_to_send, cont_offset; int16_t rem_len; tSDP_ATTR_SEQ attr_seq, attr_seq_sav; @@ -457,8 +439,7 @@ static void process_service_attr_req(tCONN_CB* p_ccb, uint16_t trans_num, uint16_t attr_len; if (p_req + sizeof(rec_handle) + sizeof(max_list_len) > p_req_end) { - sdpu_build_n_send_error(p_ccb, trans_num, SDP_INVALID_SERV_REC_HDL, - SDP_TEXT_BAD_HANDLE); + sdpu_build_n_send_error(p_ccb, trans_num, SDP_INVALID_SERV_REC_HDL, SDP_TEXT_BAD_HANDLE); return; } @@ -470,15 +451,14 @@ static void process_service_attr_req(tCONN_CB* p_ccb, uint16_t trans_num, BE_STREAM_TO_UINT16(max_list_len, p_req); param_len -= sizeof(max_list_len); - if (max_list_len > (p_ccb->rem_mtu_size - SDP_MAX_ATTR_RSPHDR_LEN)) + if (max_list_len > (p_ccb->rem_mtu_size - SDP_MAX_ATTR_RSPHDR_LEN)) { max_list_len = p_ccb->rem_mtu_size - SDP_MAX_ATTR_RSPHDR_LEN; + } p_req = sdpu_extract_attr_seq(p_req, param_len, &attr_seq); - if ((!p_req) || (!attr_seq.num_attr) || - (p_req + sizeof(uint8_t) > p_req_end)) { - sdpu_build_n_send_error(p_ccb, trans_num, SDP_INVALID_REQ_SYNTAX, - SDP_TEXT_BAD_ATTR_LIST); + if ((!p_req) || (!attr_seq.num_attr) || (p_req + sizeof(uint8_t) > p_req_end)) { + sdpu_build_n_send_error(p_ccb, trans_num, SDP_INVALID_REQ_SYNTAX, SDP_TEXT_BAD_ATTR_LIST); return; } @@ -487,8 +467,7 @@ static void process_service_attr_req(tCONN_CB* p_ccb, uint16_t trans_num, /* Find a record with the record handle */ p_rec = sdp_db_find_record(rec_handle); if (!p_rec) { - sdpu_build_n_send_error(p_ccb, trans_num, SDP_INVALID_SERV_REC_HDL, - SDP_TEXT_BAD_HANDLE); + sdpu_build_n_send_error(p_ccb, trans_num, SDP_INVALID_SERV_REC_HDL, SDP_TEXT_BAD_HANDLE); return; } @@ -497,8 +476,7 @@ static void process_service_attr_req(tCONN_CB* p_ccb, uint16_t trans_num, return; } - if (bluetooth::common::init_flags:: - pbap_pse_dynamic_version_upgrade_is_enabled()) { + if (bluetooth::common::init_flags::pbap_pse_dynamic_version_upgrade_is_enabled()) { p_rec = sdp_upgrade_pse_record(p_rec, p_ccb->device_address); } else { log::warn("PBAP PSE dynamic version upgrade is not enabled"); @@ -510,22 +488,18 @@ static void process_service_attr_req(tCONN_CB* p_ccb, uint16_t trans_num, /* Check if this is a continuation request */ if (p_req + 1 > p_req_end) { - sdpu_build_n_send_error(p_ccb, trans_num, SDP_INVALID_CONT_STATE, - SDP_TEXT_BAD_CONT_LEN); + sdpu_build_n_send_error(p_ccb, trans_num, SDP_INVALID_CONT_STATE, SDP_TEXT_BAD_CONT_LEN); return; } if (*p_req) { - if (*p_req++ != SDP_CONTINUATION_LEN || - (p_req + sizeof(cont_offset) > p_req_end)) { - sdpu_build_n_send_error(p_ccb, trans_num, SDP_INVALID_CONT_STATE, - SDP_TEXT_BAD_CONT_LEN); + if (*p_req++ != SDP_CONTINUATION_LEN || (p_req + sizeof(cont_offset) > p_req_end)) { + sdpu_build_n_send_error(p_ccb, trans_num, SDP_INVALID_CONT_STATE, SDP_TEXT_BAD_CONT_LEN); return; } BE_STREAM_TO_UINT16(cont_offset, p_req); if (cont_offset != p_ccb->cont_offset) { - sdpu_build_n_send_error(p_ccb, trans_num, SDP_INVALID_CONT_STATE, - SDP_TEXT_BAD_CONT_INX); + sdpu_build_n_send_error(p_ccb, trans_num, SDP_INVALID_CONT_STATE, SDP_TEXT_BAD_CONT_INX); return; } is_cont = true; @@ -533,7 +507,7 @@ static void process_service_attr_req(tCONN_CB* p_ccb, uint16_t trans_num, /* Initialise for continuation response */ p_rsp = &p_ccb->rsp_list[0]; attr_seq.attr_entry[p_ccb->cont_info.next_attr_index].start = - p_ccb->cont_info.next_attr_start_id; + p_ccb->cont_info.next_attr_start_id; } else { p_ccb->cont_offset = 0; p_rsp = &p_ccb->rsp_list[3]; /* Leave space for data elem descr */ @@ -548,10 +522,10 @@ static void process_service_attr_req(tCONN_CB* p_ccb, uint16_t trans_num, const tSDP_ATTRIBUTE* p_attr_service_id; const tSDP_ATTRIBUTE* p_attr_profile_desc_list_id; uint16_t avrc_sdp_version = 0; - p_attr_service_id = sdp_db_find_attr_in_rec( - p_rec, ATTR_ID_SERVICE_CLASS_ID_LIST, ATTR_ID_SERVICE_CLASS_ID_LIST); - p_attr_profile_desc_list_id = sdp_db_find_attr_in_rec( - p_rec, ATTR_ID_BT_PROFILE_DESC_LIST, ATTR_ID_BT_PROFILE_DESC_LIST); + p_attr_service_id = sdp_db_find_attr_in_rec(p_rec, ATTR_ID_SERVICE_CLASS_ID_LIST, + ATTR_ID_SERVICE_CLASS_ID_LIST); + p_attr_profile_desc_list_id = sdp_db_find_attr_in_rec(p_rec, ATTR_ID_BT_PROFILE_DESC_LIST, + ATTR_ID_BT_PROFILE_DESC_LIST); if (p_attr_service_id) { is_service_avrc_target = sdpu_is_service_id_avrc_target(p_attr_service_id); } @@ -563,18 +537,14 @@ static void process_service_attr_req(tCONN_CB* p_ccb, uint16_t trans_num, if (is_service_avrc_target) { sdpu_set_avrc_target_version(p_attr, &(p_ccb->device_address)); if (p_attr->id == ATTR_ID_SUPPORTED_FEATURES && - bluetooth::common::init_flags:: - dynamic_avrcp_version_enhancement_is_enabled()) { - avrc_sdp_version = sdpu_is_avrcp_profile_description_list( - p_attr_profile_desc_list_id); + bluetooth::common::init_flags::dynamic_avrcp_version_enhancement_is_enabled()) { + avrc_sdp_version = sdpu_is_avrcp_profile_description_list(p_attr_profile_desc_list_id); log::error("avrc_sdp_version in SDP records {:x}", avrc_sdp_version); - sdpu_set_avrc_target_features(p_attr, &(p_ccb->device_address), - avrc_sdp_version); + sdpu_set_avrc_target_features(p_attr, &(p_ccb->device_address), avrc_sdp_version); } } if (bluetooth::common::init_flags::hfp_dynamic_version_is_enabled()) { - is_hfp_fallback = - sdp_dynamic_change_hfp_version(p_attr, p_ccb->device_address); + is_hfp_fallback = sdp_dynamic_change_hfp_version(p_attr, p_ccb->device_address); } /* Check if attribute fits. Assume 3-byte value type/length */ rem_len = max_list_len - (int16_t)(p_rsp - &p_ccb->rsp_list[0]); @@ -591,37 +561,36 @@ static void process_service_attr_req(tCONN_CB* p_ccb, uint16_t trans_num, if (p_ccb->cont_info.attr_offset) { if (attr_len < p_ccb->cont_info.attr_offset) { log::error("offset is bigger than attribute length"); - sdpu_build_n_send_error(p_ccb, trans_num, SDP_INVALID_CONT_STATE, - SDP_TEXT_BAD_CONT_LEN); + sdpu_build_n_send_error(p_ccb, trans_num, SDP_INVALID_CONT_STATE, SDP_TEXT_BAD_CONT_LEN); return; } p_rsp = sdpu_build_partial_attrib_entry(p_rsp, p_attr, rem_len, &p_ccb->cont_info.attr_offset); /* If the partial attrib could not been fully added yet */ - if (p_ccb->cont_info.attr_offset != attr_len) + if (p_ccb->cont_info.attr_offset != attr_len) { break; - else /* If the partial attrib has been added in full by now */ + } else { /* If the partial attrib has been added in full by now */ p_ccb->cont_info.attr_offset = 0; /* reset attr_offset */ - } else if (rem_len < - attr_len) /* Not enough space for attr... so add partially */ + } + } else if (rem_len < attr_len) /* Not enough space for attr... so add partially */ { if (attr_len >= SDP_MAX_ATTR_LEN) { - log::error("SDP attr too big: max_list_len={},attr_len={}", - max_list_len, attr_len); + log::error("SDP attr too big: max_list_len={},attr_len={}", max_list_len, attr_len); sdpu_build_n_send_error(p_ccb, trans_num, SDP_NO_RESOURCES, NULL); return; } /* add the partial attribute if possible */ - p_rsp = sdpu_build_partial_attrib_entry( - p_rsp, p_attr, (uint16_t)rem_len, &p_ccb->cont_info.attr_offset); + p_rsp = sdpu_build_partial_attrib_entry(p_rsp, p_attr, (uint16_t)rem_len, + &p_ccb->cont_info.attr_offset); p_ccb->cont_info.next_attr_index = xx; p_ccb->cont_info.next_attr_start_id = p_attr->id; break; - } else /* build the whole attribute */ + } else { /* build the whole attribute */ p_rsp = sdpu_build_attrib_entry(p_rsp, p_attr); + } /* If doing a range, stick with this one till no more attributes found */ if (attr_seq.attr_entry[xx].start != attr_seq.attr_entry[xx].end) { @@ -640,7 +609,9 @@ static void process_service_attr_req(tCONN_CB* p_ccb, uint16_t trans_num, } /* If all the attributes have been accomodated in p_rsp, reset next_attr_index */ - if (xx == attr_seq.num_attr) p_ccb->cont_info.next_attr_index = 0; + if (xx == attr_seq.num_attr) { + p_ccb->cont_info.next_attr_index = 0; + } len_to_send = (uint16_t)(p_rsp - &p_ccb->rsp_list[0]); cont_offset = 0; @@ -649,15 +620,13 @@ static void process_service_attr_req(tCONN_CB* p_ccb, uint16_t trans_num, p_ccb->list_len = sdpu_get_attrib_seq_len(p_rec, &attr_seq_sav) + 3; /* Put in the sequence header (2 or 3 bytes) */ if (p_ccb->list_len > 255) { - p_ccb->rsp_list[0] = - (uint8_t)((DATA_ELE_SEQ_DESC_TYPE << 3) | SIZE_IN_NEXT_WORD); + p_ccb->rsp_list[0] = (uint8_t)((DATA_ELE_SEQ_DESC_TYPE << 3) | SIZE_IN_NEXT_WORD); p_ccb->rsp_list[1] = (uint8_t)((p_ccb->list_len - 3) >> 8); p_ccb->rsp_list[2] = (uint8_t)(p_ccb->list_len - 3); } else { cont_offset = 1; - p_ccb->rsp_list[1] = - (uint8_t)((DATA_ELE_SEQ_DESC_TYPE << 3) | SIZE_IN_NEXT_BYTE); + p_ccb->rsp_list[1] = (uint8_t)((DATA_ELE_SEQ_DESC_TYPE << 3) | SIZE_IN_NEXT_BYTE); p_ccb->rsp_list[2] = (uint8_t)(p_ccb->list_len - 3); p_ccb->list_len--; @@ -691,8 +660,9 @@ static void process_service_attr_req(tCONN_CB* p_ccb, uint16_t trans_num, UINT8_TO_BE_STREAM(p_rsp, SDP_CONTINUATION_LEN); UINT16_TO_BE_STREAM(p_rsp, p_ccb->cont_offset); - } else + } else { UINT8_TO_BE_STREAM(p_rsp, 0); + } /* Go back and put the parameter length into the buffer */ rsp_param_len = p_rsp - p_rsp_param_len - 2; @@ -702,10 +672,9 @@ static void process_service_attr_req(tCONN_CB* p_ccb, uint16_t trans_num, p_buf->len = p_rsp - p_rsp_start; /* Send the buffer through L2CAP */ - if (L2CA_DataWrite(p_ccb->connection_id, p_buf) != - tL2CAP_DW_RESULT::SUCCESS) { - log::warn("Unable to write L2CAP data peer:{} cid:{} len:{}", - p_ccb->device_address, p_ccb->connection_id, p_buf->len); + if (L2CA_DataWrite(p_ccb->connection_id, p_buf) != tL2CAP_DW_RESULT::SUCCESS) { + log::warn("Unable to write L2CAP data peer:{} cid:{} len:{}", p_ccb->device_address, + p_ccb->connection_id, p_buf->len); } } @@ -719,27 +688,26 @@ static void process_service_attr_req(tCONN_CB* p_ccb, uint16_t trans_num, ** Returns returns the length of denylisted attributes. ** ***************************************************************************************/ -static uint16_t sdp_pbap_pse_dynamic_attributes_len_update( - tCONN_CB* p_ccb, tSDP_ATTR_SEQ* attr_seq, tSDP_UUID_SEQ* uid_seq) { - if (!p_ccb || !attr_seq || !uid_seq) return 0; +static uint16_t sdp_pbap_pse_dynamic_attributes_len_update(tCONN_CB* p_ccb, tSDP_ATTR_SEQ* attr_seq, + tSDP_UUID_SEQ* uid_seq) { + if (!p_ccb || !attr_seq || !uid_seq) { + return 0; + } const tSDP_RECORD* p_rec; p_ccb->pse_dynamic_attributes_len = 0; // Check to validate if 1.2 record is getting sent - bool is_pbap_102_supported = - btif_storage_is_pce_version_102(p_ccb->device_address); - bool is_pbap_101_allowlisted = - is_device_in_allowlist_for_pbap(p_ccb->device_address, false); - bool is_pbap_102_allowlisted = - is_device_in_allowlist_for_pbap(p_ccb->device_address, true); + bool is_pbap_102_supported = btif_storage_is_pce_version_102(p_ccb->device_address); + bool is_pbap_101_allowlisted = is_device_in_allowlist_for_pbap(p_ccb->device_address, false); + bool is_pbap_102_allowlisted = is_device_in_allowlist_for_pbap(p_ccb->device_address, true); bool running_pts = osi_property_get_bool(SDP_ENABLE_PTS_PBAP, false); log::verbose( - "remote BD Addr : {} is_pbap_102_supported = {} is_pbap_101_allowlisted " - "= {} is_pbap_102_allowlisted = {} running_pts = {}", - p_ccb->device_address, is_pbap_102_supported, is_pbap_101_allowlisted, - is_pbap_102_allowlisted, running_pts); + "remote BD Addr : {} is_pbap_102_supported = {} is_pbap_101_allowlisted " + "= {} is_pbap_102_allowlisted = {} running_pts = {}", + p_ccb->device_address, is_pbap_102_supported, is_pbap_101_allowlisted, + is_pbap_102_allowlisted, running_pts); if (is_pbap_101_allowlisted || (!is_pbap_102_supported && !is_pbap_102_allowlisted && !running_pts)) { @@ -753,52 +721,48 @@ static uint16_t sdp_pbap_pse_dynamic_attributes_len_update( p_rec = (tSDP_RECORD*)sdp_db_service_search(p_rec, uid_seq)) { attr = p_rec->attribute[1]; if ((attr.id == ATTR_ID_SERVICE_CLASS_ID_LIST) && - (((attr.value_ptr[1] << 8) | (attr.value_ptr[2])) == - UUID_SERVCLASS_PBAP_PSE)) { + (((attr.value_ptr[1] << 8) | (attr.value_ptr[2])) == UUID_SERVCLASS_PBAP_PSE)) { // PBAP PSE Record p_rec = sdp_upgrade_pse_record(p_rec, p_ccb->device_address); log::verbose("response has PBAP PSE record for allowlist device"); int att_index; bool l2cap_psm_len_included = false, supp_attr_len_included = false; - for (xx = p_ccb->cont_info.next_attr_index; xx < attr_seq->num_attr; - xx++) { + for (xx = p_ccb->cont_info.next_attr_index; xx < attr_seq->num_attr; xx++) { log::verbose( - "xx = {} attr_seq->num_attr = {}, attr_seq->attr_entry[xx].start = " - "{} , attr_seq->attr_entry[xx].end = {}", - xx, attr_seq->num_attr, attr_seq->attr_entry[xx].start, - attr_seq->attr_entry[xx].end); + "xx = {} attr_seq->num_attr = {}, attr_seq->attr_entry[xx].start = " + "{} , attr_seq->attr_entry[xx].end = {}", + xx, attr_seq->num_attr, attr_seq->attr_entry[xx].start, + attr_seq->attr_entry[xx].end); for (att_index = 0; att_index < p_rec->num_attributes; att_index++) { tSDP_ATTRIBUTE cur_attr = p_rec->attribute[att_index]; - if (cur_attr.id == ATTR_ID_GOEP_L2CAP_PSM && - !l2cap_psm_len_included && + if (cur_attr.id == ATTR_ID_GOEP_L2CAP_PSM && !l2cap_psm_len_included && cur_attr.id >= attr_seq->attr_entry[xx].start && cur_attr.id <= attr_seq->attr_entry[xx].end) { l2cap_psm_len_included = true; p_ccb->pse_dynamic_attributes_len += PBAP_GOEP_L2CAP_PSM_LEN; - log::error( - "ATTR_ID_GOEP_L2CAP_PSM requested, need to change length by {}", - p_ccb->pse_dynamic_attributes_len); - } else if (cur_attr.id == ATTR_ID_PBAP_SUPPORTED_FEATURES && - !supp_attr_len_included && + log::error("ATTR_ID_GOEP_L2CAP_PSM requested, need to change length by {}", + p_ccb->pse_dynamic_attributes_len); + } else if (cur_attr.id == ATTR_ID_PBAP_SUPPORTED_FEATURES && !supp_attr_len_included && cur_attr.id >= attr_seq->attr_entry[xx].start && cur_attr.id <= attr_seq->attr_entry[xx].end) { supp_attr_len_included = true; p_ccb->pse_dynamic_attributes_len += PBAP_SUPP_FEA_LEN; log::verbose( - "ATTR_ID_PBAP_SUPPORTED_FEATURES requested, need to change " - "length by {}", - p_ccb->pse_dynamic_attributes_len); + "ATTR_ID_PBAP_SUPPORTED_FEATURES requested, need to change " + "length by {}", + p_ccb->pse_dynamic_attributes_len); } } - if (p_ccb->pse_dynamic_attributes_len == PBAP_1_2_BL_LEN) break; + if (p_ccb->pse_dynamic_attributes_len == PBAP_1_2_BL_LEN) { + break; + } } break; } } - log::verbose("pse_dynamic_attributes_len = {}", - p_ccb->pse_dynamic_attributes_len); + log::verbose("pse_dynamic_attributes_len = {}", p_ccb->pse_dynamic_attributes_len); return p_ccb->pse_dynamic_attributes_len; } @@ -814,9 +778,8 @@ static uint16_t sdp_pbap_pse_dynamic_attributes_len_update( * Returns void * ******************************************************************************/ -static void process_service_search_attr_req(tCONN_CB* p_ccb, uint16_t trans_num, - uint16_t param_len, uint8_t* p_req, - uint8_t* p_req_end) { +static void process_service_search_attr_req(tCONN_CB* p_ccb, uint16_t trans_num, uint16_t param_len, + uint8_t* p_req, uint8_t* p_req_end) { uint16_t max_list_len; int16_t rem_len; uint16_t len_to_send, cont_offset; @@ -835,26 +798,23 @@ static void process_service_search_attr_req(tCONN_CB* p_ccb, uint16_t trans_num, /* Extract the UUID sequence to search for */ p_req = sdpu_extract_uid_seq(p_req, param_len, &uid_seq); - if ((!p_req) || (!uid_seq.num_uids) || - (p_req + sizeof(uint16_t) > p_req_end)) { - sdpu_build_n_send_error(p_ccb, trans_num, SDP_INVALID_REQ_SYNTAX, - SDP_TEXT_BAD_UUID_LIST); + if ((!p_req) || (!uid_seq.num_uids) || (p_req + sizeof(uint16_t) > p_req_end)) { + sdpu_build_n_send_error(p_ccb, trans_num, SDP_INVALID_REQ_SYNTAX, SDP_TEXT_BAD_UUID_LIST); return; } /* Get the max list length we can send. Cap it at our max list length. */ BE_STREAM_TO_UINT16(max_list_len, p_req); - if (max_list_len > (p_ccb->rem_mtu_size - SDP_MAX_SERVATTR_RSPHDR_LEN)) + if (max_list_len > (p_ccb->rem_mtu_size - SDP_MAX_SERVATTR_RSPHDR_LEN)) { max_list_len = p_ccb->rem_mtu_size - SDP_MAX_SERVATTR_RSPHDR_LEN; + } param_len = static_cast(p_req_end - p_req); p_req = sdpu_extract_attr_seq(p_req, param_len, &attr_seq); - if ((!p_req) || (!attr_seq.num_attr) || - (p_req + sizeof(uint8_t) > p_req_end)) { - sdpu_build_n_send_error(p_ccb, trans_num, SDP_INVALID_REQ_SYNTAX, - SDP_TEXT_BAD_ATTR_LIST); + if ((!p_req) || (!attr_seq.num_attr) || (p_req + sizeof(uint8_t) > p_req_end)) { + sdpu_build_n_send_error(p_ccb, trans_num, SDP_INVALID_REQ_SYNTAX, SDP_TEXT_BAD_ATTR_LIST); return; } @@ -871,22 +831,18 @@ static void process_service_search_attr_req(tCONN_CB* p_ccb, uint16_t trans_num, /* Check if this is a continuation request */ if (p_req + 1 > p_req_end) { - sdpu_build_n_send_error(p_ccb, trans_num, SDP_INVALID_CONT_STATE, - SDP_TEXT_BAD_CONT_LEN); + sdpu_build_n_send_error(p_ccb, trans_num, SDP_INVALID_CONT_STATE, SDP_TEXT_BAD_CONT_LEN); return; } if (*p_req) { - if (*p_req++ != SDP_CONTINUATION_LEN || - (p_req + sizeof(uint16_t) > p_req_end)) { - sdpu_build_n_send_error(p_ccb, trans_num, SDP_INVALID_CONT_STATE, - SDP_TEXT_BAD_CONT_LEN); + if (*p_req++ != SDP_CONTINUATION_LEN || (p_req + sizeof(uint16_t) > p_req_end)) { + sdpu_build_n_send_error(p_ccb, trans_num, SDP_INVALID_CONT_STATE, SDP_TEXT_BAD_CONT_LEN); return; } BE_STREAM_TO_UINT16(cont_offset, p_req); if (cont_offset != p_ccb->cont_offset) { - sdpu_build_n_send_error(p_ccb, trans_num, SDP_INVALID_CONT_STATE, - SDP_TEXT_BAD_CONT_INX); + sdpu_build_n_send_error(p_ccb, trans_num, SDP_INVALID_CONT_STATE, SDP_TEXT_BAD_CONT_INX); return; } is_cont = true; @@ -894,7 +850,7 @@ static void process_service_search_attr_req(tCONN_CB* p_ccb, uint16_t trans_num, /* Initialise for continuation response */ p_rsp = &p_ccb->rsp_list[0]; attr_seq.attr_entry[p_ccb->cont_info.next_attr_index].start = - p_ccb->cont_info.next_attr_start_id; + p_ccb->cont_info.next_attr_start_id; } else { p_ccb->cont_offset = 0; p_rsp = &p_ccb->rsp_list[3]; /* Leave space for data elem descr */ @@ -907,12 +863,11 @@ static void process_service_search_attr_req(tCONN_CB* p_ccb, uint16_t trans_num, } /* Get a list of handles that match the UUIDs given to us */ - for (p_rec = sdp_db_service_search(p_ccb->cont_info.prev_sdp_rec, &uid_seq); - p_rec; p_rec = sdp_db_service_search(p_rec, &uid_seq)) { + for (p_rec = sdp_db_service_search(p_ccb->cont_info.prev_sdp_rec, &uid_seq); p_rec; + p_rec = sdp_db_service_search(p_rec, &uid_seq)) { /* Store the actual record pointer which would be reused later */ p_prev_rec = (tSDP_RECORD*)p_rec; - if (bluetooth::common::init_flags:: - pbap_pse_dynamic_version_upgrade_is_enabled()) { + if (bluetooth::common::init_flags::pbap_pse_dynamic_version_upgrade_is_enabled()) { p_rec = sdp_upgrade_pse_record(p_rec, p_ccb->device_address); } else { log::warn("PBAP PSE dynamic version upgrade is not enabled"); @@ -936,13 +891,12 @@ static void process_service_search_attr_req(tCONN_CB* p_ccb, uint16_t trans_num, const tSDP_ATTRIBUTE* p_attr_service_id; const tSDP_ATTRIBUTE* p_attr_profile_desc_list_id; uint16_t avrc_sdp_version = 0; - p_attr_service_id = sdp_db_find_attr_in_rec( - p_rec, ATTR_ID_SERVICE_CLASS_ID_LIST, ATTR_ID_SERVICE_CLASS_ID_LIST); - p_attr_profile_desc_list_id = sdp_db_find_attr_in_rec( - p_rec, ATTR_ID_BT_PROFILE_DESC_LIST, ATTR_ID_BT_PROFILE_DESC_LIST); + p_attr_service_id = sdp_db_find_attr_in_rec(p_rec, ATTR_ID_SERVICE_CLASS_ID_LIST, + ATTR_ID_SERVICE_CLASS_ID_LIST); + p_attr_profile_desc_list_id = sdp_db_find_attr_in_rec(p_rec, ATTR_ID_BT_PROFILE_DESC_LIST, + ATTR_ID_BT_PROFILE_DESC_LIST); if (p_attr_service_id) { - is_service_avrc_target = - sdpu_is_service_id_avrc_target(p_attr_service_id); + is_service_avrc_target = sdpu_is_service_id_avrc_target(p_attr_service_id); } /* Get a list of handles that match the UUIDs given to us */ for (xx = p_ccb->cont_info.next_attr_index; xx < attr_seq.num_attr; xx++) { @@ -953,20 +907,15 @@ static void process_service_search_attr_req(tCONN_CB* p_ccb, uint16_t trans_num, if (is_service_avrc_target) { sdpu_set_avrc_target_version(p_attr, &(p_ccb->device_address)); if (p_attr->id == ATTR_ID_SUPPORTED_FEATURES && - bluetooth::common::init_flags:: - dynamic_avrcp_version_enhancement_is_enabled() && - p_attr_profile_desc_list_id != nullptr) { - avrc_sdp_version = sdpu_is_avrcp_profile_description_list( - p_attr_profile_desc_list_id); - log::error("avrc_sdp_version in SDP records {:x}", - avrc_sdp_version); - sdpu_set_avrc_target_features(p_attr, &(p_ccb->device_address), - avrc_sdp_version); + bluetooth::common::init_flags::dynamic_avrcp_version_enhancement_is_enabled() && + p_attr_profile_desc_list_id != nullptr) { + avrc_sdp_version = sdpu_is_avrcp_profile_description_list(p_attr_profile_desc_list_id); + log::error("avrc_sdp_version in SDP records {:x}", avrc_sdp_version); + sdpu_set_avrc_target_features(p_attr, &(p_ccb->device_address), avrc_sdp_version); } } if (bluetooth::common::init_flags::hfp_dynamic_version_is_enabled()) { - is_hfp_fallback = - sdp_dynamic_change_hfp_version(p_attr, p_ccb->device_address); + is_hfp_fallback = sdp_dynamic_change_hfp_version(p_attr, p_ccb->device_address); } /* Check if attribute fits. Assume 3-byte value type/length */ rem_len = max_list_len - (int16_t)(p_rsp - &p_ccb->rsp_list[0]); @@ -988,35 +937,35 @@ static void process_service_search_attr_req(tCONN_CB* p_ccb, uint16_t trans_num, SDP_TEXT_BAD_CONT_LEN); return; } - p_rsp = sdpu_build_partial_attrib_entry( - p_rsp, p_attr, rem_len, &p_ccb->cont_info.attr_offset); + p_rsp = sdpu_build_partial_attrib_entry(p_rsp, p_attr, rem_len, + &p_ccb->cont_info.attr_offset); /* If the partial attrib could not been fully added yet */ if (p_ccb->cont_info.attr_offset != attr_len) { maxxed_out = true; break; - } else /* If the partial attrib has been added in full by now */ + } else { /* If the partial attrib has been added in full by now */ p_ccb->cont_info.attr_offset = 0; /* reset attr_offset */ - } else if (rem_len < - attr_len) /* Not enough space for attr... so add partially */ + } + } else if (rem_len < attr_len) /* Not enough space for attr... so add partially */ { if (attr_len >= SDP_MAX_ATTR_LEN) { - log::error("SDP attr too big: max_list_len={},attr_len={}", - max_list_len, attr_len); + log::error("SDP attr too big: max_list_len={},attr_len={}", max_list_len, attr_len); sdpu_build_n_send_error(p_ccb, trans_num, SDP_NO_RESOURCES, NULL); return; } /* add the partial attribute if possible */ - p_rsp = sdpu_build_partial_attrib_entry( - p_rsp, p_attr, (uint16_t)rem_len, &p_ccb->cont_info.attr_offset); + p_rsp = sdpu_build_partial_attrib_entry(p_rsp, p_attr, (uint16_t)rem_len, + &p_ccb->cont_info.attr_offset); p_ccb->cont_info.next_attr_index = xx; p_ccb->cont_info.next_attr_start_id = p_attr->id; maxxed_out = true; break; - } else /* build the whole attribute */ + } else { /* build the whole attribute */ p_rsp = sdpu_build_attrib_entry(p_rsp, p_attr); + } /* If doing a range, stick with this one till no more attributes found */ @@ -1039,16 +988,20 @@ static void process_service_search_attr_req(tCONN_CB* p_ccb, uint16_t trans_num, if (!p_ccb->cont_info.last_attr_seq_desc_sent) { seq_len = sdpu_get_attrib_seq_len(p_rec, &attr_seq_sav); if (seq_len != 0) { - UINT8_TO_BE_STREAM(p_seq_start, - (DATA_ELE_SEQ_DESC_TYPE << 3) | SIZE_IN_NEXT_WORD); + UINT8_TO_BE_STREAM(p_seq_start, (DATA_ELE_SEQ_DESC_TYPE << 3) | SIZE_IN_NEXT_WORD); UINT16_TO_BE_STREAM(p_seq_start, seq_len); - if (maxxed_out) p_ccb->cont_info.last_attr_seq_desc_sent = true; - } else + if (maxxed_out) { + p_ccb->cont_info.last_attr_seq_desc_sent = true; + } + } else { p_rsp = p_seq_start; + } } - if (maxxed_out) break; + if (maxxed_out) { + break; + } /* Restore the attr_seq to look for in the next sdp record */ memcpy(&attr_seq, &attr_seq_sav, sizeof(tSDP_ATTR_SEQ)); @@ -1098,35 +1051,28 @@ static void process_service_search_attr_req(tCONN_CB* p_ccb, uint16_t trans_num, /* Get the length of denylisted attributes to be updated if device is * denylisted */ - if (bluetooth::common::init_flags:: - pbap_pse_dynamic_version_upgrade_is_enabled()) { + if (bluetooth::common::init_flags::pbap_pse_dynamic_version_upgrade_is_enabled()) { p_ccb->pse_dynamic_attributes_len = - sdp_pbap_pse_dynamic_attributes_len_update(p_ccb, &attr_seq_sav, - &uid_seq); + sdp_pbap_pse_dynamic_attributes_len_update(p_ccb, &attr_seq_sav, &uid_seq); } else { log::warn("PBAP PSE dynamic version upgrade is not enabled"); p_ccb->pse_dynamic_attributes_len = 0; } - log::verbose("p_ccb->list_len = {} pse_dynamic_attributes_len = {}", - p_ccb->list_len, p_ccb->pse_dynamic_attributes_len); + log::verbose("p_ccb->list_len = {} pse_dynamic_attributes_len = {}", p_ccb->list_len, + p_ccb->pse_dynamic_attributes_len); /* Put in the sequence header (2 or 3 bytes) */ if (p_ccb->list_len > 255) { - p_ccb->rsp_list[0] = - (uint8_t)((DATA_ELE_SEQ_DESC_TYPE << 3) | SIZE_IN_NEXT_WORD); + p_ccb->rsp_list[0] = (uint8_t)((DATA_ELE_SEQ_DESC_TYPE << 3) | SIZE_IN_NEXT_WORD); p_ccb->rsp_list[1] = - (uint8_t)((p_ccb->list_len - 3 + p_ccb->pse_dynamic_attributes_len) >> - 8); - p_ccb->rsp_list[2] = - (uint8_t)(p_ccb->list_len - 3 + p_ccb->pse_dynamic_attributes_len); + (uint8_t)((p_ccb->list_len - 3 + p_ccb->pse_dynamic_attributes_len) >> 8); + p_ccb->rsp_list[2] = (uint8_t)(p_ccb->list_len - 3 + p_ccb->pse_dynamic_attributes_len); } else { cont_offset = 1; - p_ccb->rsp_list[1] = - (uint8_t)((DATA_ELE_SEQ_DESC_TYPE << 3) | SIZE_IN_NEXT_BYTE); - p_ccb->rsp_list[2] = - (uint8_t)(p_ccb->list_len - 3 + p_ccb->pse_dynamic_attributes_len); + p_ccb->rsp_list[1] = (uint8_t)((DATA_ELE_SEQ_DESC_TYPE << 3) | SIZE_IN_NEXT_BYTE); + p_ccb->rsp_list[2] = (uint8_t)(p_ccb->list_len - 3 + p_ccb->pse_dynamic_attributes_len); p_ccb->list_len--; len_to_send--; @@ -1156,13 +1102,12 @@ static void process_service_search_attr_req(tCONN_CB* p_ccb, uint16_t trans_num, p_ccb->cont_offset += len_to_send; log::verbose( - "p_ccb->pse_dynamic_attributes_len {}, cont_offset = {}, p_ccb->list_len " - "= {}", - p_ccb->pse_dynamic_attributes_len, p_ccb->cont_offset, - p_ccb->list_len + p_ccb->pse_dynamic_attributes_len); + "p_ccb->pse_dynamic_attributes_len {}, cont_offset = {}, p_ccb->list_len " + "= {}", + p_ccb->pse_dynamic_attributes_len, p_ccb->cont_offset, + p_ccb->list_len + p_ccb->pse_dynamic_attributes_len); /* If anything left to send, continuation needed */ - if (p_ccb->cont_offset < - (p_ccb->list_len + p_ccb->pse_dynamic_attributes_len)) { + if (p_ccb->cont_offset < (p_ccb->list_len + p_ccb->pse_dynamic_attributes_len)) { is_cont = true; UINT8_TO_BE_STREAM(p_rsp, SDP_CONTINUATION_LEN); UINT16_TO_BE_STREAM(p_rsp, p_ccb->cont_offset); @@ -1181,10 +1126,9 @@ static void process_service_search_attr_req(tCONN_CB* p_ccb, uint16_t trans_num, p_buf->len = p_rsp - p_rsp_start; /* Send the buffer through L2CAP */ - if (L2CA_DataWrite(p_ccb->connection_id, p_buf) != - tL2CAP_DW_RESULT::SUCCESS) { - log::warn("Unable to write L2CAP data peer:{} cid:{} len:{}", - p_ccb->device_address, p_ccb->connection_id, p_buf->len); + if (L2CA_DataWrite(p_ccb->connection_id, p_buf) != tL2CAP_DW_RESULT::SUCCESS) { + log::warn("Unable to write L2CAP data peer:{} cid:{} len:{}", p_ccb->device_address, + p_ccb->connection_id, p_buf->len); } } @@ -1206,13 +1150,11 @@ void sdp_server_handle_client_req(tCONN_CB* p_ccb, BT_HDR* p_msg) { uint16_t trans_num, param_len; /* Start inactivity timer */ - alarm_set_on_mloop(p_ccb->sdp_conn_timer, SDP_INACT_TIMEOUT_MS, - sdp_conn_timer_timeout, p_ccb); + alarm_set_on_mloop(p_ccb->sdp_conn_timer, SDP_INACT_TIMEOUT_MS, sdp_conn_timer_timeout, p_ccb); if (p_req + sizeof(pdu_id) + sizeof(trans_num) > p_req_end) { trans_num = 0; - sdpu_build_n_send_error(p_ccb, trans_num, SDP_INVALID_REQ_SYNTAX, - SDP_TEXT_BAD_HEADER); + sdpu_build_n_send_error(p_ccb, trans_num, SDP_INVALID_REQ_SYNTAX, SDP_TEXT_BAD_HEADER); return; } @@ -1223,16 +1165,14 @@ void sdp_server_handle_client_req(tCONN_CB* p_ccb, BT_HDR* p_msg) { BE_STREAM_TO_UINT16(trans_num, p_req); if (p_req + sizeof(param_len) > p_req_end) { - sdpu_build_n_send_error(p_ccb, trans_num, SDP_INVALID_REQ_SYNTAX, - SDP_TEXT_BAD_HEADER); + sdpu_build_n_send_error(p_ccb, trans_num, SDP_INVALID_REQ_SYNTAX, SDP_TEXT_BAD_HEADER); return; } BE_STREAM_TO_UINT16(param_len, p_req); if ((p_req + param_len) != p_req_end) { - sdpu_build_n_send_error(p_ccb, trans_num, SDP_INVALID_PDU_SIZE, - SDP_TEXT_BAD_HEADER); + sdpu_build_n_send_error(p_ccb, trans_num, SDP_INVALID_PDU_SIZE, SDP_TEXT_BAD_HEADER); return; } @@ -1246,13 +1186,11 @@ void sdp_server_handle_client_req(tCONN_CB* p_ccb, BT_HDR* p_msg) { break; case SDP_PDU_SERVICE_SEARCH_ATTR_REQ: - process_service_search_attr_req(p_ccb, trans_num, param_len, p_req, - p_req_end); + process_service_search_attr_req(p_ccb, trans_num, param_len, p_req, p_req_end); break; default: - sdpu_build_n_send_error(p_ccb, trans_num, SDP_INVALID_REQ_SYNTAX, - SDP_TEXT_BAD_PDU); + sdpu_build_n_send_error(p_ccb, trans_num, SDP_INVALID_REQ_SYNTAX, SDP_TEXT_BAD_PDU); log::warn("SDP - server got unknown PDU: 0x{:x}", pdu_id); break; } @@ -1286,8 +1224,7 @@ void update_pce_entry_to_interop_database(RawAddress remote_addr) { ** ***************************************************************************************/ bool is_sdp_pbap_pce_disabled(RawAddress remote_address) { - if (interop_match_addr_or_name(INTEROP_DISABLE_PCE_SDP_AFTER_PAIRING, - &remote_address, + if (interop_match_addr_or_name(INTEROP_DISABLE_PCE_SDP_AFTER_PAIRING, &remote_address, &btif_storage_get_remote_device_property)) { log::verbose("device is denylisted for PCE SDP"); return true; @@ -1306,16 +1243,14 @@ bool is_sdp_pbap_pce_disabled(RawAddress remote_address) { ** Returns BOOLEAN ** ***************************************************************************************/ -void sdp_save_local_pse_record_attributes(int32_t rfcomm_channel_number, - int32_t l2cap_psm, - int32_t profile_version, - uint32_t supported_features, +void sdp_save_local_pse_record_attributes(int32_t rfcomm_channel_number, int32_t l2cap_psm, + int32_t profile_version, uint32_t supported_features, uint32_t supported_repositories) { log::warn( - "rfcomm_channel_number: 0x{:x}, l2cap_psm: 0x{:x} profile_version: " - "0x{:x}supported_features: 0x{:x} supported_repositories: 0x{:x}", - rfcomm_channel_number, l2cap_psm, profile_version, supported_features, - supported_repositories); + "rfcomm_channel_number: 0x{:x}, l2cap_psm: 0x{:x} profile_version: " + "0x{:x}supported_features: 0x{:x} supported_repositories: 0x{:x}", + rfcomm_channel_number, l2cap_psm, profile_version, supported_features, + supported_repositories); sdpPseLocalRecord.rfcomm_channel_number = rfcomm_channel_number; sdpPseLocalRecord.l2cap_psm = l2cap_psm; sdpPseLocalRecord.profile_version = profile_version; diff --git a/system/stack/sdp/sdp_utils.cc b/system/stack/sdp/sdp_utils.cc index d711d29a8dd..4ad8a02bc9e 100644 --- a/system/stack/sdp/sdp_utils.cc +++ b/system/stack/sdp/sdp_utils.cc @@ -60,14 +60,12 @@ using bluetooth::Uuid; using namespace bluetooth; -static const uint8_t sdp_base_uuid[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, - 0x5F, 0x9B, 0x34, 0xFB}; +static const uint8_t sdp_base_uuid[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, + 0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB}; template static std::array to_little_endian_array(T x) { - static_assert(std::is_integral::value, - "to_little_endian_array parameter must be integral."); + static_assert(std::is_integral::value, "to_little_endian_array parameter must be integral."); std::array array = {}; for (size_t i = 0; i < array.size(); i++) { array[i] = static_cast((x >> (8 * i)) & 0xFF); @@ -82,8 +80,7 @@ static std::array to_little_endian_array(T x) { * @param p_rec SDP record to search * @return a vector of pairs, empty if not found */ -static std::vector> sdpu_find_profile_version( - tSDP_DISC_REC* p_rec) { +static std::vector> sdpu_find_profile_version(tSDP_DISC_REC* p_rec) { std::vector> result; for (tSDP_DISC_ATTR* p_attr = p_rec->p_first_attr; p_attr != nullptr; p_attr = p_attr->p_next_attr) { @@ -93,18 +90,17 @@ static std::vector> sdpu_find_profile_version( continue; } // Walk through the protocol descriptor list - for (tSDP_DISC_ATTR* p_sattr = p_attr->attr_value.v.p_sub_attr; - p_sattr != nullptr; p_sattr = p_sattr->p_next_attr) { + for (tSDP_DISC_ATTR* p_sattr = p_attr->attr_value.v.p_sub_attr; p_sattr != nullptr; + p_sattr = p_sattr->p_next_attr) { // Safety check - each entry should itself be a sequence - if (SDP_DISC_ATTR_TYPE(p_sattr->attr_len_type) != - DATA_ELE_SEQ_DESC_TYPE) { + if (SDP_DISC_ATTR_TYPE(p_sattr->attr_len_type) != DATA_ELE_SEQ_DESC_TYPE) { log::warn("Descriptor type is not sequence: 0x{:x}", SDP_DISC_ATTR_TYPE(p_sattr->attr_len_type)); return std::vector>(); } // Now, see if the entry contains the profile UUID we are interested in - for (tSDP_DISC_ATTR* p_ssattr = p_sattr->attr_value.v.p_sub_attr; - p_ssattr != nullptr; p_ssattr = p_ssattr->p_next_attr) { + for (tSDP_DISC_ATTR* p_ssattr = p_sattr->attr_value.v.p_sub_attr; p_ssattr != nullptr; + p_ssattr = p_ssattr->p_next_attr) { if (SDP_DISC_ATTR_TYPE(p_ssattr->attr_len_type) != UUID_DESC_TYPE || SDP_DISC_ATTR_LEN(p_ssattr->attr_len_type) != 2) { continue; @@ -152,17 +148,13 @@ static uint16_t sdpu_find_most_specific_service_uuid(tSDP_DISC_REC* p_rec) { if (SDP_DISC_ATTR_TYPE(p_first_attr->attr_len_type) == UUID_DESC_TYPE && SDP_DISC_ATTR_LEN(p_first_attr->attr_len_type) == 2) { return p_first_attr->attr_value.v.u16; - } else if (SDP_DISC_ATTR_TYPE(p_first_attr->attr_len_type) == - DATA_ELE_SEQ_DESC_TYPE) { + } else if (SDP_DISC_ATTR_TYPE(p_first_attr->attr_len_type) == DATA_ELE_SEQ_DESC_TYPE) { // Workaround for Toyota G Block car kit: // It incorrectly puts an extra data element sequence in this attribute - for (tSDP_DISC_ATTR* p_extra_sattr = - p_first_attr->attr_value.v.p_sub_attr; - p_extra_sattr != nullptr; - p_extra_sattr = p_extra_sattr->p_next_attr) { + for (tSDP_DISC_ATTR* p_extra_sattr = p_first_attr->attr_value.v.p_sub_attr; + p_extra_sattr != nullptr; p_extra_sattr = p_extra_sattr->p_next_attr) { // Return the first UUID data element - if (SDP_DISC_ATTR_TYPE(p_extra_sattr->attr_len_type) == - UUID_DESC_TYPE && + if (SDP_DISC_ATTR_TYPE(p_extra_sattr->attr_len_type) == UUID_DESC_TYPE && SDP_DISC_ATTR_LEN(p_extra_sattr->attr_len_type) == 2) { return p_extra_sattr->attr_value.v.u16; } @@ -181,12 +173,10 @@ static uint16_t sdpu_find_most_specific_service_uuid(tSDP_DISC_REC* p_rec) { return 0; } -void sdpu_log_attribute_metrics(const RawAddress& bda, - tSDP_DISCOVERY_DB* p_db) { +void sdpu_log_attribute_metrics(const RawAddress& bda, tSDP_DISCOVERY_DB* p_db) { log::assert_that(p_db != nullptr, "assert failed: p_db != nullptr"); bool has_di_record = false; - for (tSDP_DISC_REC* p_rec = p_db->p_first_rec; p_rec != nullptr; - p_rec = p_rec->p_next_rec) { + for (tSDP_DISC_REC* p_rec = p_db->p_first_rec; p_rec != nullptr; p_rec = p_rec->p_next_rec) { uint16_t service_uuid = sdpu_find_most_specific_service_uuid(p_rec); if (service_uuid == 0) { log::info("skipping record without service uuid {}", bda); @@ -201,8 +191,8 @@ void sdpu_log_attribute_metrics(const RawAddress& bda, uint16_t profile_uuid = uuid_version_pair.first; uint16_t version = uuid_version_pair.second; auto version_array = to_little_endian_array(version); - log_sdp_attribute(bda, profile_uuid, ATTR_ID_BT_PROFILE_DESC_LIST, - version_array.size(), version_array.data()); + log_sdp_attribute(bda, profile_uuid, ATTR_ID_BT_PROFILE_DESC_LIST, version_array.size(), + version_array.data()); } // Log protocol version from Protocol Descriptor List uint16_t protocol_uuid = 0; @@ -223,13 +213,12 @@ void sdpu_log_attribute_metrics(const RawAddress& bda, } if (protocol_uuid != 0) { tSDP_PROTOCOL_ELEM protocol_elements = {}; - if (SDP_FindProtocolListElemInRec(p_rec, protocol_uuid, - &protocol_elements)) { + if (SDP_FindProtocolListElemInRec(p_rec, protocol_uuid, &protocol_elements)) { if (protocol_elements.num_params >= 1) { uint16_t version = protocol_elements.params[0]; auto version_array = to_little_endian_array(version); - log_sdp_attribute(bda, protocol_uuid, ATTR_ID_PROTOCOL_DESC_LIST, - version_array.size(), version_array.data()); + log_sdp_attribute(bda, protocol_uuid, ATTR_ID_PROTOCOL_DESC_LIST, version_array.size(), + version_array.data()); } } } @@ -242,47 +231,41 @@ void sdpu_log_attribute_metrics(const RawAddress& bda, case UUID_SERVCLASS_AV_REM_CTRL_TARGET: case UUID_SERVCLASS_AUDIO_SOURCE: case UUID_SERVCLASS_AUDIO_SINK: { - tSDP_DISC_ATTR* p_attr = - SDP_FindAttributeInRec(p_rec, ATTR_ID_SUPPORTED_FEATURES); - if (p_attr == nullptr || - SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) != UINT_DESC_TYPE || + tSDP_DISC_ATTR* p_attr = SDP_FindAttributeInRec(p_rec, ATTR_ID_SUPPORTED_FEATURES); + if (p_attr == nullptr || SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) != UINT_DESC_TYPE || SDP_DISC_ATTR_LEN(p_attr->attr_len_type) < 2) { break; } uint16_t supported_features = p_attr->attr_value.v.u16; auto version_array = to_little_endian_array(supported_features); - log_sdp_attribute(bda, service_uuid, ATTR_ID_SUPPORTED_FEATURES, - version_array.size(), version_array.data()); + log_sdp_attribute(bda, service_uuid, ATTR_ID_SUPPORTED_FEATURES, version_array.size(), + version_array.data()); break; } case UUID_SERVCLASS_MESSAGE_NOTIFICATION: case UUID_SERVCLASS_MESSAGE_ACCESS: { - tSDP_DISC_ATTR* p_attr = - SDP_FindAttributeInRec(p_rec, ATTR_ID_MAP_SUPPORTED_FEATURES); - if (p_attr == nullptr || - SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) != UINT_DESC_TYPE || + tSDP_DISC_ATTR* p_attr = SDP_FindAttributeInRec(p_rec, ATTR_ID_MAP_SUPPORTED_FEATURES); + if (p_attr == nullptr || SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) != UINT_DESC_TYPE || SDP_DISC_ATTR_LEN(p_attr->attr_len_type) < 4) { break; } uint32_t map_supported_features = p_attr->attr_value.v.u32; auto features_array = to_little_endian_array(map_supported_features); - log_sdp_attribute(bda, service_uuid, ATTR_ID_MAP_SUPPORTED_FEATURES, - features_array.size(), features_array.data()); + log_sdp_attribute(bda, service_uuid, ATTR_ID_MAP_SUPPORTED_FEATURES, features_array.size(), + features_array.data()); break; } case UUID_SERVCLASS_PBAP_PCE: case UUID_SERVCLASS_PBAP_PSE: { - tSDP_DISC_ATTR* p_attr = - SDP_FindAttributeInRec(p_rec, ATTR_ID_PBAP_SUPPORTED_FEATURES); - if (p_attr == nullptr || - SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) != UINT_DESC_TYPE || + tSDP_DISC_ATTR* p_attr = SDP_FindAttributeInRec(p_rec, ATTR_ID_PBAP_SUPPORTED_FEATURES); + if (p_attr == nullptr || SDP_DISC_ATTR_TYPE(p_attr->attr_len_type) != UINT_DESC_TYPE || SDP_DISC_ATTR_LEN(p_attr->attr_len_type) < 4) { break; } uint32_t pbap_supported_features = p_attr->attr_value.v.u32; auto features_array = to_little_endian_array(pbap_supported_features); - log_sdp_attribute(bda, service_uuid, ATTR_ID_PBAP_SUPPORTED_FEATURES, - features_array.size(), features_array.data()); + log_sdp_attribute(bda, service_uuid, ATTR_ID_PBAP_SUPPORTED_FEATURES, features_array.size(), + features_array.data()); break; } } @@ -295,26 +278,21 @@ void sdpu_log_attribute_metrics(const RawAddress& bda, tSDP_DI_GET_RECORD di_record = {}; if (SDP_GetDiRecord(1, &di_record, p_db) == SDP_SUCCESS) { auto version_array = to_little_endian_array(di_record.spec_id); - log_sdp_attribute(bda, UUID_SERVCLASS_PNP_INFORMATION, - ATTR_ID_SPECIFICATION_ID, version_array.size(), - version_array.data()); + log_sdp_attribute(bda, UUID_SERVCLASS_PNP_INFORMATION, ATTR_ID_SPECIFICATION_ID, + version_array.size(), version_array.data()); std::stringstream ss; // [N - native]::SDP::[DIP - Device ID Profile] ss << "N:SDP::DIP::" << loghex(di_record.rec.vendor_id_source); - log_manufacturer_info( - bda, android::bluetooth::AddressTypeEnum::ADDRESS_TYPE_PUBLIC, - android::bluetooth::DeviceInfoSrcEnum::DEVICE_INFO_INTERNAL, ss.str(), - loghex(di_record.rec.vendor), loghex(di_record.rec.product), - loghex(di_record.rec.version), ""); + log_manufacturer_info(bda, android::bluetooth::AddressTypeEnum::ADDRESS_TYPE_PUBLIC, + android::bluetooth::DeviceInfoSrcEnum::DEVICE_INFO_INTERNAL, ss.str(), + loghex(di_record.rec.vendor), loghex(di_record.rec.product), + loghex(di_record.rec.version), ""); std::string bda_string = bda.ToString(); // write manufacturer, model, HW version to config - btif_config_set_int(bda_string, BTIF_STORAGE_KEY_SDP_DI_MANUFACTURER, - di_record.rec.vendor); - btif_config_set_int(bda_string, BTIF_STORAGE_KEY_SDP_DI_MODEL, - di_record.rec.product); - btif_config_set_int(bda_string, BTIF_STORAGE_KEY_SDP_DI_HW_VERSION, - di_record.rec.version); + btif_config_set_int(bda_string, BTIF_STORAGE_KEY_SDP_DI_MANUFACTURER, di_record.rec.vendor); + btif_config_set_int(bda_string, BTIF_STORAGE_KEY_SDP_DI_MODEL, di_record.rec.product); + btif_config_set_int(bda_string, BTIF_STORAGE_KEY_SDP_DI_HW_VERSION, di_record.rec.version); btif_config_set_int(bda_string, BTIF_STORAGE_KEY_SDP_DI_VENDOR_ID_SRC, di_record.rec.vendor_id_source); } @@ -337,15 +315,14 @@ tCONN_CB* sdpu_find_ccb_by_cid(uint16_t cid) { /* Look through each connection control block */ for (xx = 0, p_ccb = sdp_cb.ccb; xx < SDP_MAX_CONNECTIONS; xx++, p_ccb++) { - if ((p_ccb->con_state != tSDP_STATE::IDLE) && - (p_ccb->con_state != tSDP_STATE::CONN_PEND) && + if ((p_ccb->con_state != tSDP_STATE::IDLE) && (p_ccb->con_state != tSDP_STATE::CONN_PEND) && (p_ccb->connection_id == cid)) { - return (p_ccb); + return p_ccb; } } /* If here, not found */ - return (NULL); + return NULL; } /******************************************************************************* @@ -365,12 +342,13 @@ tCONN_CB* sdpu_find_ccb_by_db(const tSDP_DISCOVERY_DB* p_db) { if (p_db) { /* Look through each connection control block */ for (xx = 0, p_ccb = sdp_cb.ccb; xx < SDP_MAX_CONNECTIONS; xx++, p_ccb++) { - if ((p_ccb->con_state != tSDP_STATE::IDLE) && (p_ccb->p_db == p_db)) - return (p_ccb); + if ((p_ccb->con_state != tSDP_STATE::IDLE) && (p_ccb->p_db == p_db)) { + return p_ccb; + } } } /* If here, not found */ - return (NULL); + return NULL; } /******************************************************************************* @@ -392,12 +370,12 @@ tCONN_CB* sdpu_allocate_ccb(void) { alarm_t* alarm = p_ccb->sdp_conn_timer; *p_ccb = {}; p_ccb->sdp_conn_timer = alarm; - return (p_ccb); + return p_ccb; } } /* If here, no free CCB found */ - return (NULL); + return NULL; } /******************************************************************************* @@ -435,7 +413,9 @@ void sdpu_release_ccb(tCONN_CB& ccb) { ccb.is_attr_search = false; /* Free the response buffer */ - if (ccb.rsp_list) log::verbose("releasing SDP rsp_list"); + if (ccb.rsp_list) { + log::verbose("releasing SDP rsp_list"); + } osi_free_and_reset((void**)&ccb.rsp_list); } @@ -460,8 +440,7 @@ uint16_t sdpu_get_active_ccb_cid(const RawAddress& bd_addr) { if ((p_ccb->con_state == tSDP_STATE::CONN_SETUP) || (p_ccb->con_state == tSDP_STATE::CFG_SETUP) || (p_ccb->con_state == tSDP_STATE::CONNECTED)) { - if (p_ccb->con_flags & SDP_FLAGS_IS_ORIG && - p_ccb->device_address == bd_addr) { + if (p_ccb->con_flags & SDP_FLAGS_IS_ORIG && p_ccb->device_address == bd_addr) { return p_ccb->connection_id; } } @@ -490,8 +469,7 @@ bool sdpu_process_pend_ccb_same_cid(tCONN_CB& ccb) { // Look through each connection control block for active sdp on given remote for (xx = 0, p_ccb = sdp_cb.ccb; xx < SDP_MAX_CONNECTIONS; xx++, p_ccb++) { if ((p_ccb->con_state == tSDP_STATE::CONN_PEND) && - (p_ccb->connection_id == ccb.connection_id) && - (p_ccb->con_flags & SDP_FLAGS_IS_ORIG)) { + (p_ccb->connection_id == ccb.connection_id) && (p_ccb->con_flags & SDP_FLAGS_IS_ORIG)) { p_ccb->con_state = tSDP_STATE::CONNECTED; sdp_disc_connected(p_ccb); return true; @@ -522,13 +500,11 @@ bool sdpu_process_pend_ccb_new_cid(tCONN_CB& ccb) { // Look through each ccb to replace the obsolete cid with a new one. for (xx = 0, p_ccb = sdp_cb.ccb; xx < SDP_MAX_CONNECTIONS; xx++, p_ccb++) { if ((p_ccb->con_state == tSDP_STATE::CONN_PEND) && - (p_ccb->connection_id == ccb.connection_id) && - (p_ccb->con_flags & SDP_FLAGS_IS_ORIG)) { + (p_ccb->connection_id == ccb.connection_id) && (p_ccb->con_flags & SDP_FLAGS_IS_ORIG)) { if (!new_conn) { // Only change state of the first ccb p_ccb->con_state = tSDP_STATE::CONN_SETUP; - new_cid = L2CA_ConnectReqWithSecurity(BT_PSM_SDP, p_ccb->device_address, - BTM_SEC_NONE); + new_cid = L2CA_ConnectReqWithSecurity(BT_PSM_SDP, p_ccb->device_address, BTM_SEC_NONE); new_conn = true; } // Check if L2CAP started the connection process @@ -562,8 +538,7 @@ void sdpu_clear_pend_ccb(tCONN_CB& ccb) { // Look through each connection control block for active sdp on given remote for (xx = 0, p_ccb = sdp_cb.ccb; xx < SDP_MAX_CONNECTIONS; xx++, p_ccb++) { if ((p_ccb->con_state == tSDP_STATE::CONN_PEND) && - (p_ccb->connection_id == ccb.connection_id) && - (p_ccb->con_flags & SDP_FLAGS_IS_ORIG)) { + (p_ccb->connection_id == ccb.connection_id) && (p_ccb->con_flags & SDP_FLAGS_IS_ORIG)) { sdpu_callback(*p_ccb, SDP_CONN_FAILED); sdpu_release_ccb(*p_ccb); } @@ -582,24 +557,22 @@ void sdpu_clear_pend_ccb(tCONN_CB& ccb) { * Returns Pointer to next byte in the output buffer. * ******************************************************************************/ -uint8_t* sdpu_build_attrib_seq(uint8_t* p_out, uint16_t* p_attr, - uint16_t num_attrs) { +uint8_t* sdpu_build_attrib_seq(uint8_t* p_out, uint16_t* p_attr, uint16_t num_attrs) { uint16_t xx; /* First thing is the data element header. See if the length fits 1 byte */ /* If no attributes, assume a 4-byte wildcard */ - if (!p_attr) + if (!p_attr) { xx = 5; - else + } else { xx = num_attrs * 3; + } if (xx > 255) { - UINT8_TO_BE_STREAM(p_out, - (DATA_ELE_SEQ_DESC_TYPE << 3) | SIZE_IN_NEXT_WORD); + UINT8_TO_BE_STREAM(p_out, (DATA_ELE_SEQ_DESC_TYPE << 3) | SIZE_IN_NEXT_WORD); UINT16_TO_BE_STREAM(p_out, xx); } else { - UINT8_TO_BE_STREAM(p_out, - (DATA_ELE_SEQ_DESC_TYPE << 3) | SIZE_IN_NEXT_BYTE); + UINT8_TO_BE_STREAM(p_out, (DATA_ELE_SEQ_DESC_TYPE << 3) | SIZE_IN_NEXT_BYTE); UINT8_TO_BE_STREAM(p_out, xx); } @@ -616,7 +589,7 @@ uint8_t* sdpu_build_attrib_seq(uint8_t* p_out, uint16_t* p_attr, } } - return (p_out); + return p_out; } /******************************************************************************* @@ -649,7 +622,7 @@ uint8_t* sdpu_build_attrib_entry(uint8_t* p_out, const tSDP_ATTRIBUTE* p_attr) { } else #endif /* 0xFFFF - 0xFF */ #if (SDP_MAX_ATTR_LEN > 0xFF) - if (p_attr->len > 0xFF) { + if (p_attr->len > 0xFF) { UINT8_TO_BE_STREAM(p_out, (p_attr->type << 3) | SIZE_IN_NEXT_WORD); UINT16_TO_BE_STREAM(p_out, p_attr->len); } else @@ -663,7 +636,7 @@ uint8_t* sdpu_build_attrib_entry(uint8_t* p_out, const tSDP_ATTRIBUTE* p_attr) { ARRAY_TO_BE_STREAM(p_out, p_attr->value_ptr, (int)p_attr->len); } - return (p_out); + return p_out; } /* Now, store the attribute value */ @@ -693,7 +666,7 @@ uint8_t* sdpu_build_attrib_entry(uint8_t* p_out, const tSDP_ATTRIBUTE* p_attr) { ARRAY_TO_BE_STREAM(p_out, p_attr->value_ptr, (int)p_attr->len); } - return (p_out); + return p_out; } /******************************************************************************* @@ -705,14 +678,14 @@ uint8_t* sdpu_build_attrib_entry(uint8_t* p_out, const tSDP_ATTRIBUTE* p_attr) { * Returns void * ******************************************************************************/ -void sdpu_build_n_send_error(tCONN_CB* p_ccb, uint16_t trans_num, - uint16_t error_code, char* p_error_text) { +void sdpu_build_n_send_error(tCONN_CB* p_ccb, uint16_t trans_num, uint16_t error_code, + char* p_error_text) { uint8_t *p_rsp, *p_rsp_start, *p_rsp_param_len; uint16_t rsp_param_len; BT_HDR* p_buf = (BT_HDR*)osi_malloc(SDP_DATA_BUF_SIZE); - log::warn("SDP - sdpu_build_n_send_error code: 0x{:x} CID: 0x{:x}", - error_code, p_ccb->connection_id); + log::warn("SDP - sdpu_build_n_send_error code: 0x{:x} CID: 0x{:x}", error_code, + p_ccb->connection_id); /* Send the packet to L2CAP */ p_buf->offset = L2CAP_MIN_OFFSET; @@ -728,8 +701,9 @@ void sdpu_build_n_send_error(tCONN_CB* p_ccb, uint16_t trans_num, UINT16_TO_BE_STREAM(p_rsp, error_code); /* Unplugfest example traces do not have any error text */ - if (p_error_text) + if (p_error_text) { ARRAY_TO_BE_STREAM(p_rsp, p_error_text, (int)strlen(p_error_text)); + } /* Go back and put the parameter length into the buffer */ rsp_param_len = p_rsp - p_rsp_param_len - 2; @@ -739,8 +713,7 @@ void sdpu_build_n_send_error(tCONN_CB* p_ccb, uint16_t trans_num, p_buf->len = p_rsp - p_rsp_start; /* Send the buffer through L2CAP */ - if (L2CA_DataWrite(p_ccb->connection_id, p_buf) != - tL2CAP_DW_RESULT::SUCCESS) { + if (L2CA_DataWrite(p_ccb->connection_id, p_buf) != tL2CAP_DW_RESULT::SUCCESS) { log::warn("Unable to write L2CAP data cid:{}", p_ccb->connection_id); } } @@ -755,8 +728,7 @@ void sdpu_build_n_send_error(tCONN_CB* p_ccb, uint16_t trans_num, * Returns Pointer to next byte in the input buffer after the sequence. * ******************************************************************************/ -uint8_t* sdpu_extract_uid_seq(uint8_t* p, uint16_t param_len, - tSDP_UUID_SEQ* p_seq) { +uint8_t* sdpu_extract_uid_seq(uint8_t* p, uint16_t param_len, tSDP_UUID_SEQ* p_seq) { uint8_t* p_seq_end; uint8_t descr, type, size; uint32_t seq_len, uuid_len; @@ -765,14 +737,18 @@ uint8_t* sdpu_extract_uid_seq(uint8_t* p, uint16_t param_len, p_seq->num_uids = 0; /* A UID sequence is composed of a bunch of UIDs. */ - if (sizeof(descr) > param_len) return (NULL); + if (sizeof(descr) > param_len) { + return NULL; + } param_len -= sizeof(descr); BE_STREAM_TO_UINT8(descr, p); type = descr >> 3; size = descr & 7; - if (type != DATA_ELE_SEQ_DESC_TYPE) return (NULL); + if (type != DATA_ELE_SEQ_DESC_TYPE) { + return NULL; + } switch (size) { case SIZE_TWO_BYTES: @@ -785,25 +761,33 @@ uint8_t* sdpu_extract_uid_seq(uint8_t* p, uint16_t param_len, seq_len = 16; break; case SIZE_IN_NEXT_BYTE: - if (sizeof(uint8_t) > param_len) return (NULL); + if (sizeof(uint8_t) > param_len) { + return NULL; + } param_len -= sizeof(uint8_t); BE_STREAM_TO_UINT8(seq_len, p); break; case SIZE_IN_NEXT_WORD: - if (sizeof(uint16_t) > param_len) return (NULL); + if (sizeof(uint16_t) > param_len) { + return NULL; + } param_len -= sizeof(uint16_t); BE_STREAM_TO_UINT16(seq_len, p); break; case SIZE_IN_NEXT_LONG: - if (sizeof(uint32_t) > param_len) return (NULL); + if (sizeof(uint32_t) > param_len) { + return NULL; + } param_len -= sizeof(uint32_t); BE_STREAM_TO_UINT32(seq_len, p); break; default: - return (NULL); + return NULL; } - if (seq_len > param_len) return (NULL); + if (seq_len > param_len) { + return NULL; + } p_seq_end = p + seq_len; @@ -813,7 +797,9 @@ uint8_t* sdpu_extract_uid_seq(uint8_t* p, uint16_t param_len, type = descr >> 3; size = descr & 7; - if (type != UUID_DESC_TYPE) return (NULL); + if (type != UUID_DESC_TYPE) { + return NULL; + } switch (size) { case SIZE_TWO_BYTES: @@ -826,38 +812,47 @@ uint8_t* sdpu_extract_uid_seq(uint8_t* p, uint16_t param_len, uuid_len = 16; break; case SIZE_IN_NEXT_BYTE: - if (p + sizeof(uint8_t) > p_seq_end) return NULL; + if (p + sizeof(uint8_t) > p_seq_end) { + return NULL; + } BE_STREAM_TO_UINT8(uuid_len, p); break; case SIZE_IN_NEXT_WORD: - if (p + sizeof(uint16_t) > p_seq_end) return NULL; + if (p + sizeof(uint16_t) > p_seq_end) { + return NULL; + } BE_STREAM_TO_UINT16(uuid_len, p); break; case SIZE_IN_NEXT_LONG: - if (p + sizeof(uint32_t) > p_seq_end) return NULL; + if (p + sizeof(uint32_t) > p_seq_end) { + return NULL; + } BE_STREAM_TO_UINT32(uuid_len, p); break; default: - return (NULL); + return NULL; } /* If UUID length is valid, copy it across */ - if (((uuid_len == 2) || (uuid_len == 4) || (uuid_len == 16)) && - (p + uuid_len <= p_seq_end)) { + if (((uuid_len == 2) || (uuid_len == 4) || (uuid_len == 16)) && (p + uuid_len <= p_seq_end)) { p_seq->uuid_entry[p_seq->num_uids].len = (uint16_t)uuid_len; - BE_STREAM_TO_ARRAY(p, p_seq->uuid_entry[p_seq->num_uids].value, - (int)uuid_len); + BE_STREAM_TO_ARRAY(p, p_seq->uuid_entry[p_seq->num_uids].value, (int)uuid_len); p_seq->num_uids++; - } else - return (NULL); + } else { + return NULL; + } /* We can only do so many */ - if (p_seq->num_uids >= MAX_UUIDS_PER_SEQ) return (NULL); + if (p_seq->num_uids >= MAX_UUIDS_PER_SEQ) { + return NULL; + } } - if (p != p_seq_end) return (NULL); + if (p != p_seq_end) { + return NULL; + } - return (p); + return p; } /******************************************************************************* @@ -870,8 +865,7 @@ uint8_t* sdpu_extract_uid_seq(uint8_t* p, uint16_t param_len, * Returns Pointer to next byte in the input buffer after the sequence. * ******************************************************************************/ -uint8_t* sdpu_extract_attr_seq(uint8_t* p, uint16_t param_len, - tSDP_ATTR_SEQ* p_seq) { +uint8_t* sdpu_extract_attr_seq(uint8_t* p, uint16_t param_len, tSDP_ATTR_SEQ* p_seq) { uint8_t* p_end_list; uint8_t descr, type, size; uint32_t list_len, attr_len; @@ -880,29 +874,39 @@ uint8_t* sdpu_extract_attr_seq(uint8_t* p, uint16_t param_len, p_seq->num_attr = 0; /* Get attribute sequence info */ - if (param_len < sizeof(descr)) return NULL; + if (param_len < sizeof(descr)) { + return NULL; + } param_len -= sizeof(descr); BE_STREAM_TO_UINT8(descr, p); type = descr >> 3; size = descr & 7; - if (type != DATA_ELE_SEQ_DESC_TYPE) return NULL; + if (type != DATA_ELE_SEQ_DESC_TYPE) { + return NULL; + } switch (size) { case SIZE_IN_NEXT_BYTE: - if (param_len < sizeof(uint8_t)) return NULL; + if (param_len < sizeof(uint8_t)) { + return NULL; + } param_len -= sizeof(uint8_t); BE_STREAM_TO_UINT8(list_len, p); break; case SIZE_IN_NEXT_WORD: - if (param_len < sizeof(uint16_t)) return NULL; + if (param_len < sizeof(uint16_t)) { + return NULL; + } param_len -= sizeof(uint16_t); BE_STREAM_TO_UINT16(list_len, p); break; case SIZE_IN_NEXT_LONG: - if (param_len < sizeof(uint32_t)) return NULL; + if (param_len < sizeof(uint32_t)) { + return NULL; + } param_len -= sizeof(uint32_t); BE_STREAM_TO_UINT32(list_len, p); break; @@ -911,7 +915,9 @@ uint8_t* sdpu_extract_attr_seq(uint8_t* p, uint16_t param_len, return NULL; } - if (list_len > param_len) return NULL; + if (list_len > param_len) { + return NULL; + } p_end_list = p + list_len; @@ -921,7 +927,9 @@ uint8_t* sdpu_extract_attr_seq(uint8_t* p, uint16_t param_len, type = descr >> 3; size = descr & 7; - if (type != UINT_DESC_TYPE) return NULL; + if (type != UINT_DESC_TYPE) { + return NULL; + } switch (size) { case SIZE_TWO_BYTES: @@ -931,15 +939,21 @@ uint8_t* sdpu_extract_attr_seq(uint8_t* p, uint16_t param_len, attr_len = 4; break; case SIZE_IN_NEXT_BYTE: - if (p + sizeof(uint8_t) > p_end_list) return NULL; + if (p + sizeof(uint8_t) > p_end_list) { + return NULL; + } BE_STREAM_TO_UINT8(attr_len, p); break; case SIZE_IN_NEXT_WORD: - if (p + sizeof(uint16_t) > p_end_list) return NULL; + if (p + sizeof(uint16_t) > p_end_list) { + return NULL; + } BE_STREAM_TO_UINT16(attr_len, p); break; case SIZE_IN_NEXT_LONG: - if (p + sizeof(uint32_t) > p_end_list) return NULL; + if (p + sizeof(uint32_t) > p_end_list) { + return NULL; + } BE_STREAM_TO_UINT32(attr_len, p); break; default: @@ -948,22 +962,26 @@ uint8_t* sdpu_extract_attr_seq(uint8_t* p, uint16_t param_len, } /* Attribute length must be 2-bytes or 4-bytes for a paired entry. */ - if (p + attr_len > p_end_list) return NULL; + if (p + attr_len > p_end_list) { + return NULL; + } if (attr_len == 2) { BE_STREAM_TO_UINT16(p_seq->attr_entry[p_seq->num_attr].start, p); - p_seq->attr_entry[p_seq->num_attr].end = - p_seq->attr_entry[p_seq->num_attr].start; + p_seq->attr_entry[p_seq->num_attr].end = p_seq->attr_entry[p_seq->num_attr].start; } else if (attr_len == 4) { BE_STREAM_TO_UINT16(p_seq->attr_entry[p_seq->num_attr].start, p); BE_STREAM_TO_UINT16(p_seq->attr_entry[p_seq->num_attr].end, p); - } else - return (NULL); + } else { + return NULL; + } /* We can only do so many */ - if (++p_seq->num_attr >= MAX_ATTR_PER_SEQ) return (NULL); + if (++p_seq->num_attr >= MAX_ATTR_PER_SEQ) { + return NULL; + } } - return (p); + return p; } /******************************************************************************* @@ -981,16 +999,14 @@ uint8_t* sdpu_extract_attr_seq(uint8_t* p, uint16_t param_len, * @return pointer to the start of the data or nullptr on failure * ******************************************************************************/ -uint8_t* sdpu_get_len_from_type(uint8_t* p, uint8_t* p_end, uint8_t type, - uint32_t* p_len) { +uint8_t* sdpu_get_len_from_type(uint8_t* p, uint8_t* p_end, uint8_t type, uint32_t* p_len) { uint8_t u8; uint16_t u16; uint32_t u32; switch (type & 7) { case SIZE_ONE_BYTE: - if (com::android::bluetooth::flags:: - stack_sdp_detect_nil_property_type()) { + if (com::android::bluetooth::flags::stack_sdp_detect_nil_property_type()) { // Return NIL type if appropriate *p_len = (type == 0) ? 0 : sizeof(uint8_t); } else { @@ -1035,7 +1051,7 @@ uint8_t* sdpu_get_len_from_type(uint8_t* p, uint8_t* p_end, uint8_t type, break; } - return (p); + return p; } /******************************************************************************* @@ -1051,11 +1067,14 @@ uint8_t* sdpu_get_len_from_type(uint8_t* p, uint8_t* p_end, uint8_t type, bool sdpu_is_base_uuid(uint8_t* p_uuid) { uint16_t xx; - for (xx = 4; xx < Uuid::kNumBytes128; xx++) - if (p_uuid[xx] != sdp_base_uuid[xx]) return (false); + for (xx = 4; xx < Uuid::kNumBytes128; xx++) { + if (p_uuid[xx] != sdp_base_uuid[xx]) { + return false; + } + } /* If here, matched */ - return (true); + return true; } /******************************************************************************* @@ -1070,8 +1089,8 @@ bool sdpu_is_base_uuid(uint8_t* p_uuid) { * Returns true if matched, else false * ******************************************************************************/ -bool sdpu_compare_uuid_arrays(const uint8_t* p_uuid1, uint32_t len1, - const uint8_t* p_uuid2, uint16_t len2) { +bool sdpu_compare_uuid_arrays(const uint8_t* p_uuid1, uint32_t len1, const uint8_t* p_uuid2, + uint16_t len2) { uint8_t nu1[Uuid::kNumBytes128]; uint8_t nu2[Uuid::kNumBytes128]; @@ -1083,47 +1102,51 @@ bool sdpu_compare_uuid_arrays(const uint8_t* p_uuid1, uint32_t len1, /* If lengths match, do a straight compare */ if (len1 == len2) { - if (len1 == 2) - return ((p_uuid1[0] == p_uuid2[0]) && (p_uuid1[1] == p_uuid2[1])); - if (len1 == 4) - return ((p_uuid1[0] == p_uuid2[0]) && (p_uuid1[1] == p_uuid2[1]) && - (p_uuid1[2] == p_uuid2[2]) && (p_uuid1[3] == p_uuid2[3])); - else - return (memcmp(p_uuid1, p_uuid2, (size_t)len1) == 0); + if (len1 == 2) { + return (p_uuid1[0] == p_uuid2[0]) && (p_uuid1[1] == p_uuid2[1]); + } + if (len1 == 4) { + return (p_uuid1[0] == p_uuid2[0]) && (p_uuid1[1] == p_uuid2[1]) && + (p_uuid1[2] == p_uuid2[2]) && (p_uuid1[3] == p_uuid2[3]); + } else { + return memcmp(p_uuid1, p_uuid2, (size_t)len1) == 0; + } } else if (len1 > len2) { /* If the len1 was 4-byte, (so len2 is 2-byte), compare on the fly */ if (len1 == 4) { - return ((p_uuid1[0] == 0) && (p_uuid1[1] == 0) && - (p_uuid1[2] == p_uuid2[0]) && (p_uuid1[3] == p_uuid2[1])); + return (p_uuid1[0] == 0) && (p_uuid1[1] == 0) && (p_uuid1[2] == p_uuid2[0]) && + (p_uuid1[3] == p_uuid2[1]); } else { /* Normalize UUIDs to 16-byte form, then compare. Len1 must be 16 */ memcpy(nu1, p_uuid1, Uuid::kNumBytes128); memcpy(nu2, sdp_base_uuid, Uuid::kNumBytes128); - if (len2 == 4) + if (len2 == 4) { memcpy(nu2, p_uuid2, len2); - else if (len2 == 2) + } else if (len2 == 2) { memcpy(nu2 + 2, p_uuid2, len2); + } - return (memcmp(nu1, nu2, Uuid::kNumBytes128) == 0); + return memcmp(nu1, nu2, Uuid::kNumBytes128) == 0; } } else { /* len2 is greater than len1 */ /* If the len2 was 4-byte, (so len1 is 2-byte), compare on the fly */ if (len2 == 4) { - return ((p_uuid2[0] == 0) && (p_uuid2[1] == 0) && - (p_uuid2[2] == p_uuid1[0]) && (p_uuid2[3] == p_uuid1[1])); + return (p_uuid2[0] == 0) && (p_uuid2[1] == 0) && (p_uuid2[2] == p_uuid1[0]) && + (p_uuid2[3] == p_uuid1[1]); } else { /* Normalize UUIDs to 16-byte form, then compare. Len1 must be 16 */ memcpy(nu2, p_uuid2, Uuid::kNumBytes128); memcpy(nu1, sdp_base_uuid, Uuid::kNumBytes128); - if (len1 == 4) + if (len1 == 4) { memcpy(nu1, p_uuid1, (size_t)len1); - else if (len1 == 2) + } else if (len1 == 2) { memcpy(nu1 + 2, p_uuid1, (size_t)len1); + } - return (memcmp(nu1, nu2, Uuid::kNumBytes128) == 0); + return memcmp(nu1, nu2, Uuid::kNumBytes128) == 0; } } } @@ -1151,7 +1174,7 @@ bool sdpu_compare_uuid_with_attr(const Uuid& uuid, tSDP_DISC_ATTR* p_attr) { return uuid.As16Bit() == p_attr->attr_value.v.u16; } else { log::error("invalid length for 16bit discovery attribute len:{}", len); - return (false); + return false; } } if (len == 4) { @@ -1159,20 +1182,21 @@ bool sdpu_compare_uuid_with_attr(const Uuid& uuid, tSDP_DISC_ATTR* p_attr) { return uuid.As32Bit() == p_attr->attr_value.v.u32; } else { log::error("invalid length for 32bit discovery attribute len:{}", len); - return (false); + return false; } } if (SDP_DISC_ATTR_LEN(p_attr->attr_len_type) != Uuid::kNumBytes128) { log::error("invalid length for 128bit discovery attribute len:{}", len); - return (false); + return false; } - if (memcmp(uuid.To128BitBE().data(), (void*)p_attr->attr_value.v.array, - Uuid::kNumBytes128) == 0) - return (true); + if (memcmp(uuid.To128BitBE().data(), (void*)p_attr->attr_value.v.array, Uuid::kNumBytes128) == + 0) { + return true; + } - return (false); + return false; } /******************************************************************************* @@ -1205,8 +1229,9 @@ void sdpu_sort_attr_list(uint16_t num_attr, tSDP_DISCOVERY_DB* p_db) { p_db->attr_filters[i + 1] = x; i = 0; - } else + } else { i++; + } } } @@ -1231,10 +1256,11 @@ uint16_t sdpu_get_list_len(tSDP_UUID_SEQ* uid_seq, tSDP_ATTR_SEQ* attr_seq) { len1 = sdpu_get_attrib_seq_len(p_rec, attr_seq); - if (len1 != 0) + if (len1 != 0) { len += len1; - else + } else { len -= 3; + } } return len; } @@ -1249,8 +1275,7 @@ uint16_t sdpu_get_list_len(tSDP_UUID_SEQ* uid_seq, tSDP_ATTR_SEQ* attr_seq) { * Returns void * ******************************************************************************/ -uint16_t sdpu_get_attrib_seq_len(const tSDP_RECORD* p_rec, - const tSDP_ATTR_SEQ* attr_seq) { +uint16_t sdpu_get_attrib_seq_len(const tSDP_RECORD* p_rec, const tSDP_ATTR_SEQ* attr_seq) { const tSDP_ATTRIBUTE* p_attr; uint16_t len1 = 0; uint16_t xx; @@ -1272,10 +1297,12 @@ uint16_t sdpu_get_attrib_seq_len(const tSDP_RECORD* p_rec, start_id = p_attr->id + 1; xx--; is_range = true; - } else + } else { is_range = false; - } else + } + } else { is_range = false; + } } return len1; } @@ -1305,7 +1332,7 @@ uint16_t sdpu_get_attrib_entry_len(const tSDP_ATTRIBUTE* p_attr) { } else #endif /* 0xFFFF - 0xFF */ #if (SDP_MAX_ATTR_LEN > 0xFF) - if (p_attr->len > 0xFF) { + if (p_attr->len > 0xFF) { len += 3; } else #endif /* 0xFF and less*/ @@ -1351,11 +1378,9 @@ uint16_t sdpu_get_attrib_entry_len(const tSDP_ATTRIBUTE* p_attr) { * offset is also updated * ******************************************************************************/ -uint8_t* sdpu_build_partial_attrib_entry(uint8_t* p_out, - const tSDP_ATTRIBUTE* p_attr, - uint16_t len, uint16_t* offset) { - uint8_t* p_attr_buff = - (uint8_t*)osi_malloc(sizeof(uint8_t) * SDP_MAX_ATTR_LEN); +uint8_t* sdpu_build_partial_attrib_entry(uint8_t* p_out, const tSDP_ATTRIBUTE* p_attr, uint16_t len, + uint16_t* offset) { + uint8_t* p_attr_buff = (uint8_t*)osi_malloc(sizeof(uint8_t) * SDP_MAX_ATTR_LEN); sdpu_build_attrib_entry(p_attr_buff, p_attr); uint16_t attr_len = sdpu_get_attrib_entry_len(p_attr); @@ -1365,8 +1390,7 @@ uint8_t* sdpu_build_partial_attrib_entry(uint8_t* p_out, len = SDP_MAX_ATTR_LEN; } - size_t len_to_copy = - ((attr_len - *offset) < len) ? (attr_len - *offset) : len; + size_t len_to_copy = ((attr_len - *offset) < len) ? (attr_len - *offset) : len; memcpy(p_out, &p_attr_buff[*offset], len_to_copy); p_out = &p_out[len_to_copy]; @@ -1451,9 +1475,8 @@ bool sdpu_is_service_id_avrc_target(const tSDP_ATTRIBUTE* p_attr) { * ******************************************************************************/ bool spdu_is_avrcp_version_valid(const uint16_t version) { - return version == AVRC_REV_1_0 || version == AVRC_REV_1_3 || - version == AVRC_REV_1_4 || version == AVRC_REV_1_5 || - version == AVRC_REV_1_6; + return version == AVRC_REV_1_0 || version == AVRC_REV_1_3 || version == AVRC_REV_1_4 || + version == AVRC_REV_1_5 || version == AVRC_REV_1_6; } /******************************************************************************* * @@ -1468,32 +1491,27 @@ bool spdu_is_avrcp_version_valid(const uint16_t version) { * Returns void * ******************************************************************************/ -void sdpu_set_avrc_target_version(const tSDP_ATTRIBUTE* p_attr, - const RawAddress* bdaddr) { +void sdpu_set_avrc_target_version(const tSDP_ATTRIBUTE* p_attr, const RawAddress* bdaddr) { // Check attribute is AVRCP profile description list and get AVRC Target // version uint16_t avrcp_version = sdpu_is_avrcp_profile_description_list(p_attr); log::info("SDP AVRCP DB Version {:x}", avrcp_version); if (avrcp_version == 0) { - log::info("Not AVRCP version attribute or version not valid for device {}", - *bdaddr); + log::info("Not AVRCP version attribute or version not valid for device {}", *bdaddr); return; } uint16_t dut_avrcp_version = - (bluetooth::common::init_flags:: - dynamic_avrcp_version_enhancement_is_enabled()) - ? GetInterfaceToProfiles() - ->profileSpecific_HACK->AVRC_GetProfileVersion() - : avrcp_version; + (bluetooth::common::init_flags::dynamic_avrcp_version_enhancement_is_enabled()) + ? GetInterfaceToProfiles()->profileSpecific_HACK->AVRC_GetProfileVersion() + : avrcp_version; log::info("Current DUT AVRCP Version {:x}", dut_avrcp_version); // Some remote devices will have interoperation issue when receive higher // AVRCP version. If those devices are in IOP database and our version higher // than device, we reply a lower version to them. uint16_t iop_version = 0; - if (dut_avrcp_version > AVRC_REV_1_4 && - interop_match_addr(INTEROP_AVRCP_1_4_ONLY, bdaddr)) { + if (dut_avrcp_version > AVRC_REV_1_4 && interop_match_addr(INTEROP_AVRCP_1_4_ONLY, bdaddr)) { iop_version = AVRC_REV_1_4; } else if (dut_avrcp_version > AVRC_REV_1_3 && interop_match_addr(INTEROP_AVRCP_1_3_ONLY, bdaddr)) { @@ -1501,10 +1519,8 @@ void sdpu_set_avrc_target_version(const tSDP_ATTRIBUTE* p_attr, } if (iop_version != 0) { - log::info( - "device={} is in IOP database. Reply AVRC Target version {:x} instead " - "of {:x}.", - *bdaddr, iop_version, avrcp_version); + log::info("device={} is in IOP database. Reply AVRC Target version {:x} instead of {:x}.", + *bdaddr, iop_version, avrcp_version); uint8_t* p_version = p_attr->value_ptr + 6; UINT16_TO_BE_FIELD(p_version, iop_version); return; @@ -1513,51 +1529,47 @@ void sdpu_set_avrc_target_version(const tSDP_ATTRIBUTE* p_attr, // Dynamic AVRCP version. If our version high than remote device's version, // reply version same as its. Otherwise, reply default version. if (!osi_property_get_bool(AVRC_DYNAMIC_AVRCP_ENABLE_PROPERTY, true)) { - log::info( - "Dynamic AVRCP version feature is not enabled, skipping this method"); + log::info("Dynamic AVRCP version feature is not enabled, skipping this method"); return; } // Read the remote device's AVRC Controller version from local storage uint16_t cached_version = 0; - size_t version_value_size = btif_config_get_bin_length( - bdaddr->ToString(), BTIF_STORAGE_KEY_AVRCP_CONTROLLER_VERSION); + size_t version_value_size = + btif_config_get_bin_length(bdaddr->ToString(), BTIF_STORAGE_KEY_AVRCP_CONTROLLER_VERSION); if (version_value_size != sizeof(cached_version)) { - log::error("cached value len wrong, bdaddr={}. Len is {} but should be {}.", - *bdaddr, version_value_size, sizeof(cached_version)); + log::error("cached value len wrong, bdaddr={}. Len is {} but should be {}.", *bdaddr, + version_value_size, sizeof(cached_version)); return; } - if (!btif_config_get_bin(bdaddr->ToString(), - BTIF_STORAGE_KEY_AVRCP_CONTROLLER_VERSION, + if (!btif_config_get_bin(bdaddr->ToString(), BTIF_STORAGE_KEY_AVRCP_CONTROLLER_VERSION, (uint8_t*)&cached_version, &version_value_size)) { log::info( - "no cached AVRC Controller version for {}. Reply default AVRC Target " - "version {:x}.DUT AVRC Target version {:x}.", - *bdaddr, avrcp_version, dut_avrcp_version); + "no cached AVRC Controller version for {}. Reply default AVRC Target " + "version {:x}.DUT AVRC Target version {:x}.", + *bdaddr, avrcp_version, dut_avrcp_version); return; } if (!spdu_is_avrcp_version_valid(cached_version)) { log::error( - "cached AVRC Controller version {:x} of {} is not valid. Reply default " - "AVRC Target version {:x}.", - cached_version, *bdaddr, avrcp_version); + "cached AVRC Controller version {:x} of {} is not valid. Reply default " + "AVRC Target version {:x}.", + cached_version, *bdaddr, avrcp_version); return; } - if (!bluetooth::common::init_flags:: - dynamic_avrcp_version_enhancement_is_enabled() && + if (!bluetooth::common::init_flags::dynamic_avrcp_version_enhancement_is_enabled() && dut_avrcp_version <= cached_version) { return; } - uint16_t negotiated_avrcp_version = - std::min(dut_avrcp_version, cached_version); + uint16_t negotiated_avrcp_version = std::min(dut_avrcp_version, cached_version); log::info( - "read cached AVRC Controller version {:x} of {}. DUT AVRC Target version " - "{:x}.Negotiated AVRCP version to update peer {:x}.", - cached_version, *bdaddr, dut_avrcp_version, negotiated_avrcp_version); + "read cached AVRC Controller version {:x} of {}. DUT AVRC Target version " + "{:x}.Negotiated AVRCP version to update peer {:x}.", + cached_version, *bdaddr, dut_avrcp_version, negotiated_avrcp_version); uint8_t* p_version = p_attr->value_ptr + 6; UINT16_TO_BE_FIELD(p_version, negotiated_avrcp_version); } @@ -1574,8 +1586,7 @@ void sdpu_set_avrc_target_version(const tSDP_ATTRIBUTE* p_attr, * Returns void * ******************************************************************************/ -void sdpu_set_avrc_target_features(const tSDP_ATTRIBUTE* p_attr, - const RawAddress* bdaddr, +void sdpu_set_avrc_target_features(const tSDP_ATTRIBUTE* p_attr, const RawAddress* bdaddr, uint16_t avrcp_version) { log::info("SDP AVRCP Version {:x}", avrcp_version); @@ -1593,62 +1604,50 @@ void sdpu_set_avrc_target_features(const tSDP_ATTRIBUTE* p_attr, // Dynamic AVRCP version. If our version high than remote device's version, // reply version same as its. Otherwise, reply default version. if (!osi_property_get_bool(AVRC_DYNAMIC_AVRCP_ENABLE_PROPERTY, false)) { - log::info( - "Dynamic AVRCP version feature is not enabled, skipping this method"); + log::info("Dynamic AVRCP version feature is not enabled, skipping this method"); return; } // Read the remote device's AVRC Controller version from local storage uint16_t avrcp_peer_features = 0; - size_t version_value_size = btif_config_get_bin_length( - bdaddr->ToString(), BTIF_STORAGE_KEY_AV_REM_CTRL_FEATURES); + size_t version_value_size = + btif_config_get_bin_length(bdaddr->ToString(), BTIF_STORAGE_KEY_AV_REM_CTRL_FEATURES); if (version_value_size != sizeof(avrcp_peer_features)) { - log::error("cached value len wrong, bdaddr={}. Len is {} but should be {}.", - *bdaddr, version_value_size, sizeof(avrcp_peer_features)); + log::error("cached value len wrong, bdaddr={}. Len is {} but should be {}.", *bdaddr, + version_value_size, sizeof(avrcp_peer_features)); return; } - if (!btif_config_get_bin( - bdaddr->ToString(), BTIF_STORAGE_KEY_AV_REM_CTRL_FEATURES, - (uint8_t*)&avrcp_peer_features, &version_value_size)) { + if (!btif_config_get_bin(bdaddr->ToString(), BTIF_STORAGE_KEY_AV_REM_CTRL_FEATURES, + (uint8_t*)&avrcp_peer_features, &version_value_size)) { log::error("Unable to fetch cached AVRC features"); return; } - bool browsing_supported = - ((AVRCP_FEAT_BRW_BIT & avrcp_peer_features) == AVRCP_FEAT_BRW_BIT); - bool coverart_supported = - ((AVRCP_FEAT_CA_BIT & avrcp_peer_features) == AVRCP_FEAT_CA_BIT); + bool browsing_supported = ((AVRCP_FEAT_BRW_BIT & avrcp_peer_features) == AVRCP_FEAT_BRW_BIT); + bool coverart_supported = ((AVRCP_FEAT_CA_BIT & avrcp_peer_features) == AVRCP_FEAT_CA_BIT); - log::info( - "SDP AVRCP DB Version 0x{:x}, browse supported {}, cover art supported " - "{}", - avrcp_peer_features, browsing_supported, coverart_supported); + log::info("SDP AVRCP DB Version 0x{:x}, browse supported {}, cover art supported {}", + avrcp_peer_features, browsing_supported, coverart_supported); if (avrcp_version < AVRC_REV_1_4 || !browsing_supported) { log::info("Reset Browsing Feature"); - p_attr->value_ptr[AVRCP_SUPPORTED_FEATURES_POSITION] &= - ~AVRCP_BROWSE_SUPPORT_BITMASK; - p_attr->value_ptr[AVRCP_SUPPORTED_FEATURES_POSITION] &= - ~AVRCP_MULTI_PLAYER_SUPPORT_BITMASK; + p_attr->value_ptr[AVRCP_SUPPORTED_FEATURES_POSITION] &= ~AVRCP_BROWSE_SUPPORT_BITMASK; + p_attr->value_ptr[AVRCP_SUPPORTED_FEATURES_POSITION] &= ~AVRCP_MULTI_PLAYER_SUPPORT_BITMASK; } if (avrcp_version < AVRC_REV_1_6 || !coverart_supported) { log::info("Reset CoverArt Feature"); - p_attr->value_ptr[AVRCP_SUPPORTED_FEATURES_POSITION - 1] &= - ~AVRCP_CA_SUPPORT_BITMASK; + p_attr->value_ptr[AVRCP_SUPPORTED_FEATURES_POSITION - 1] &= ~AVRCP_CA_SUPPORT_BITMASK; } if (avrcp_version >= AVRC_REV_1_4 && browsing_supported) { log::info("Set Browsing Feature"); - p_attr->value_ptr[AVRCP_SUPPORTED_FEATURES_POSITION] |= - AVRCP_BROWSE_SUPPORT_BITMASK; - p_attr->value_ptr[AVRCP_SUPPORTED_FEATURES_POSITION] |= - AVRCP_MULTI_PLAYER_SUPPORT_BITMASK; + p_attr->value_ptr[AVRCP_SUPPORTED_FEATURES_POSITION] |= AVRCP_BROWSE_SUPPORT_BITMASK; + p_attr->value_ptr[AVRCP_SUPPORTED_FEATURES_POSITION] |= AVRCP_MULTI_PLAYER_SUPPORT_BITMASK; } if (avrcp_version == AVRC_REV_1_6 && coverart_supported) { log::info("Set CoverArt Feature"); - p_attr->value_ptr[AVRCP_SUPPORTED_FEATURES_POSITION - 1] |= - AVRCP_CA_SUPPORT_BITMASK; + p_attr->value_ptr[AVRCP_SUPPORTED_FEATURES_POSITION - 1] |= AVRCP_CA_SUPPORT_BITMASK; } } diff --git a/system/stack/sdp/sdpint.h b/system/stack/sdp/sdpint.h index 417eee47d9a..7e8a77c47d7 100644 --- a/system/stack/sdp/sdpint.h +++ b/system/stack/sdp/sdpint.h @@ -109,23 +109,22 @@ typedef struct { /* Define the SDP database */ typedef struct { - uint32_t - di_primary_handle; /* Device ID Primary record or NULL if nonexistent */ + uint32_t di_primary_handle; /* Device ID Primary record or NULL if nonexistent */ uint16_t num_records; tSDP_RECORD record[SDP_MAX_RECORDS]; } tSDP_DB; /* Continuation information for the SDP server response */ typedef struct { - uint16_t next_attr_index; /* attr index for next continuation response */ - uint16_t next_attr_start_id; /* attr id to start with for the attr index in - next cont. response */ + uint16_t next_attr_index; /* attr index for next continuation response */ + uint16_t next_attr_start_id; /* attr id to start with for the attr index in + next cont. response */ const tSDP_RECORD* prev_sdp_rec; /* last sdp record that was completely sent in the response */ - bool last_attr_seq_desc_sent; /* whether attr seq length has been sent - previously */ - uint16_t attr_offset; /* offset within the attr to keep trak of partial - attributes in the responses */ + bool last_attr_seq_desc_sent; /* whether attr seq length has been sent + previously */ + uint16_t attr_offset; /* offset within the attr to keep trak of partial + attributes in the responses */ } tSDP_CONT_INFO; enum class tSDP_STATE : uint8_t { @@ -183,22 +182,20 @@ struct tCONN_CB { alarm_t* sdp_conn_timer; uint16_t rem_mtu_size; uint16_t connection_id; - uint16_t list_len; /* length of the response in the GKI buffer */ + uint16_t list_len; /* length of the response in the GKI buffer */ uint16_t pse_dynamic_attributes_len; /* length of the attributes need to be added in final sdp response len */ - uint8_t* rsp_list; /* pointer to GKI buffer holding response */ + uint8_t* rsp_list; /* pointer to GKI buffer holding response */ tSDP_DISCOVERY_DB* p_db; /* Database to save info into */ tSDP_DISC_CMPL_CB* p_cb; /* Callback for discovery done */ /* OnceCallback would be more appropriate, but it doesn't have copy * constructor, so won't compile with current memory management for control * blocks */ - base::RepeatingCallback - complete_callback; /* Callback for discovery */ - uint32_t - handles[SDP_MAX_DISC_SERVER_RECS]; /* Discovered server record handles */ - uint16_t num_handles; /* Number of server handles */ - uint16_t cur_handle; /* Current handle being processed */ + base::RepeatingCallback complete_callback; /* Callback for discovery */ + uint32_t handles[SDP_MAX_DISC_SERVER_RECS]; /* Discovered server record handles */ + uint16_t num_handles; /* Number of server handles */ + uint16_t cur_handle; /* Current handle being processed */ uint16_t transaction_id; uint16_t disconnect_reason; /* Disconnect reason */ @@ -210,7 +207,7 @@ struct tCONN_CB { the server response */ tCONN_CB() = default; - private: +private: tCONN_CB(const tCONN_CB&) = delete; }; @@ -256,47 +253,36 @@ tCONN_CB* sdpu_find_ccb_by_db(const tSDP_DISCOVERY_DB* p_db); tCONN_CB* sdpu_allocate_ccb(void); void sdpu_release_ccb(tCONN_CB& p_ccb); -uint8_t* sdpu_build_attrib_seq(uint8_t* p_out, uint16_t* p_attr, - uint16_t num_attrs); +uint8_t* sdpu_build_attrib_seq(uint8_t* p_out, uint16_t* p_attr, uint16_t num_attrs); uint8_t* sdpu_build_attrib_entry(uint8_t* p_out, const tSDP_ATTRIBUTE* p_attr); -void sdpu_build_n_send_error(tCONN_CB* p_ccb, uint16_t trans_num, - uint16_t error_code, char* p_error_text); +void sdpu_build_n_send_error(tCONN_CB* p_ccb, uint16_t trans_num, uint16_t error_code, + char* p_error_text); -uint8_t* sdpu_extract_attr_seq(uint8_t* p, uint16_t param_len, - tSDP_ATTR_SEQ* p_seq); -uint8_t* sdpu_extract_uid_seq(uint8_t* p, uint16_t param_len, - tSDP_UUID_SEQ* p_seq); +uint8_t* sdpu_extract_attr_seq(uint8_t* p, uint16_t param_len, tSDP_ATTR_SEQ* p_seq); +uint8_t* sdpu_extract_uid_seq(uint8_t* p, uint16_t param_len, tSDP_UUID_SEQ* p_seq); -uint8_t* sdpu_get_len_from_type(uint8_t* p, uint8_t* p_end, uint8_t type, - uint32_t* p_len); +uint8_t* sdpu_get_len_from_type(uint8_t* p, uint8_t* p_end, uint8_t type, uint32_t* p_len); bool sdpu_is_base_uuid(uint8_t* p_uuid); -bool sdpu_compare_uuid_arrays(const uint8_t* p_uuid1, uint32_t len1, - const uint8_t* p_uuid2, uint16_t len2); -bool sdpu_compare_uuid_with_attr(const bluetooth::Uuid& uuid, - tSDP_DISC_ATTR* p_attr); +bool sdpu_compare_uuid_arrays(const uint8_t* p_uuid1, uint32_t len1, const uint8_t* p_uuid2, + uint16_t len2); +bool sdpu_compare_uuid_with_attr(const bluetooth::Uuid& uuid, tSDP_DISC_ATTR* p_attr); void sdpu_sort_attr_list(uint16_t num_attr, tSDP_DISCOVERY_DB* p_db); uint16_t sdpu_get_list_len(tSDP_UUID_SEQ* uid_seq, tSDP_ATTR_SEQ* attr_seq); -uint16_t sdpu_get_attrib_seq_len(const tSDP_RECORD* p_rec, - const tSDP_ATTR_SEQ* attr_seq); +uint16_t sdpu_get_attrib_seq_len(const tSDP_RECORD* p_rec, const tSDP_ATTR_SEQ* attr_seq); uint16_t sdpu_get_attrib_entry_len(const tSDP_ATTRIBUTE* p_attr); -uint8_t* sdpu_build_partial_attrib_entry(uint8_t* p_out, - const tSDP_ATTRIBUTE* p_attr, - uint16_t len, uint16_t* offset); -bool SDP_AddAttributeToRecord(tSDP_RECORD* p_rec, uint16_t attr_id, - uint8_t attr_type, uint32_t attr_len, - uint8_t* p_val); -bool SDP_AddProfileDescriptorListToRecord(tSDP_RECORD* p_rec, - uint16_t profile_uuid, +uint8_t* sdpu_build_partial_attrib_entry(uint8_t* p_out, const tSDP_ATTRIBUTE* p_attr, uint16_t len, + uint16_t* offset); +bool SDP_AddAttributeToRecord(tSDP_RECORD* p_rec, uint16_t attr_id, uint8_t attr_type, + uint32_t attr_len, uint8_t* p_val); +bool SDP_AddProfileDescriptorListToRecord(tSDP_RECORD* p_rec, uint16_t profile_uuid, uint16_t version); bool SDP_DeleteAttributeFromRecord(tSDP_RECORD* p_rec, uint16_t attr_id); uint16_t sdpu_is_avrcp_profile_description_list(const tSDP_ATTRIBUTE* p_attr); bool sdpu_is_service_id_avrc_target(const tSDP_ATTRIBUTE* p_attr); bool spdu_is_avrcp_version_valid(const uint16_t version); -void sdpu_set_avrc_target_version(const tSDP_ATTRIBUTE* p_attr, - const RawAddress* bdaddr); -void sdpu_set_avrc_target_features(const tSDP_ATTRIBUTE* p_attr, - const RawAddress* bdaddr, +void sdpu_set_avrc_target_version(const tSDP_ATTRIBUTE* p_attr, const RawAddress* bdaddr); +void sdpu_set_avrc_target_features(const tSDP_ATTRIBUTE* p_attr, const RawAddress* bdaddr, uint16_t profile_version); uint16_t sdpu_get_active_ccb_cid(const RawAddress& bd_addr); bool sdpu_process_pend_ccb_same_cid(tCONN_CB& ccb); @@ -306,11 +292,9 @@ void sdpu_callback(tCONN_CB& ccb, tSDP_REASON reason); /* Functions provided by sdp_db.cc */ -const tSDP_RECORD* sdp_db_service_search(const tSDP_RECORD* p_rec, - const tSDP_UUID_SEQ* p_seq); +const tSDP_RECORD* sdp_db_service_search(const tSDP_RECORD* p_rec, const tSDP_UUID_SEQ* p_seq); tSDP_RECORD* sdp_db_find_record(uint32_t handle); -const tSDP_ATTRIBUTE* sdp_db_find_attr_in_rec(const tSDP_RECORD* p_rec, - uint16_t start_attr, +const tSDP_ATTRIBUTE* sdp_db_find_attr_in_rec(const tSDP_RECORD* p_rec, uint16_t start_attr, uint16_t end_attr); /* Functions provided by sdp_server.cc @@ -324,10 +308,8 @@ void sdp_disc_server_rsp(tCONN_CB* p_ccb, BT_HDR* p_msg); void update_pce_entry_to_interop_database(RawAddress remote_addr); bool is_sdp_pbap_pce_disabled(RawAddress remote_addr); -void sdp_save_local_pse_record_attributes(int32_t rfcomm_channel_number, - int32_t l2cap_psm, - int32_t profile_version, - uint32_t supported_features, +void sdp_save_local_pse_record_attributes(int32_t rfcomm_channel_number, int32_t l2cap_psm, + int32_t profile_version, uint32_t supported_features, uint32_t supported_repositories); size_t sdp_get_num_records(const tSDP_DISCOVERY_DB& db); diff --git a/system/stack/smp/p_256_ecc_pp.cc b/system/stack/smp/p_256_ecc_pp.cc index ec8616f4124..f84688a8e72 100644 --- a/system/stack/smp/p_256_ecc_pp.cc +++ b/system/stack/smp/p_256_ecc_pp.cc @@ -34,9 +34,7 @@ elliptic_curve_t curve_p256; static void p_256_init_point(Point* q) { memset(q, 0, sizeof(Point)); } -static void p_256_copy_point(Point* q, Point* p) { - memcpy(q, p, sizeof(Point)); -} +static void p_256_copy_point(Point* q, Point* p) { memcpy(q, p, sizeof(Point)); } // q=2q static void ECC_Double(Point* q, Point* p) { @@ -168,9 +166,9 @@ static void ECC_NAF(uint8_t* naf, uint32_t* NumNAF, uint32_t* k) { sign = (k[0] & 0x03); // 1 or 3 // k = k-naf[i] - if (sign == 1) + if (sign == 1) { k[0] = k[0] & 0xFFFFFFFE; - else { + } else { k[0] = k[0] + 1; if (k[0] == 0) // overflow { @@ -180,8 +178,9 @@ static void ECC_NAF(uint8_t* naf, uint32_t* NumNAF, uint32_t* k) { } while (k[j++] == 0); // overflow } } - } else + } else { sign = 0; + } multiprecision_rshift(k, k); naf[i / 4] |= (sign) << ((i % 4) * 2); diff --git a/system/stack/smp/p_256_ecc_pp.h b/system/stack/smp/p_256_ecc_pp.h index 4dff0a8590d..0f3b507a92b 100644 --- a/system/stack/smp/p_256_ecc_pp.h +++ b/system/stack/smp/p_256_ecc_pp.h @@ -26,6 +26,7 @@ #pragma once #include + #include "p_256_multprecision.h" typedef struct { diff --git a/system/stack/smp/p_256_multprecision.cc b/system/stack/smp/p_256_multprecision.cc index e0d63e549da..dc997d5554d 100644 --- a/system/stack/smp/p_256_multprecision.cc +++ b/system/stack/smp/p_256_multprecision.cc @@ -27,51 +27,70 @@ #include "p_256_ecc_pp.h" void multiprecision_init(uint32_t* c) { - for (uint32_t i = 0; i < KEY_LENGTH_DWORDS_P256; i++) c[i] = 0; + for (uint32_t i = 0; i < KEY_LENGTH_DWORDS_P256; i++) { + c[i] = 0; + } } void multiprecision_copy(uint32_t* c, uint32_t* a) { - for (uint32_t i = 0; i < KEY_LENGTH_DWORDS_P256; i++) c[i] = a[i]; + for (uint32_t i = 0; i < KEY_LENGTH_DWORDS_P256; i++) { + c[i] = a[i]; + } } int multiprecision_compare(uint32_t* a, uint32_t* b) { for (int i = KEY_LENGTH_DWORDS_P256 - 1; i >= 0; i--) { - if (a[i] > b[i]) return 1; - if (a[i] < b[i]) return -1; + if (a[i] > b[i]) { + return 1; + } + if (a[i] < b[i]) { + return -1; + } } return 0; } int multiprecision_iszero(uint32_t* a) { - for (uint32_t i = 0; i < KEY_LENGTH_DWORDS_P256; i++) - if (a[i]) return 0; + for (uint32_t i = 0; i < KEY_LENGTH_DWORDS_P256; i++) { + if (a[i]) { + return 0; + } + } return 1; } uint32_t multiprecision_dword_bits(uint32_t a) { uint32_t i; - for (i = 0; i < DWORD_BITS; i++, a >>= 1) - if (a == 0) break; + for (i = 0; i < DWORD_BITS; i++, a >>= 1) { + if (a == 0) { + break; + } + } return i; } uint32_t multiprecision_most_signdwords(uint32_t* a) { int i; - for (i = KEY_LENGTH_DWORDS_P256 - 1; i >= 0; i--) - if (a[i]) break; - return (i + 1); + for (i = KEY_LENGTH_DWORDS_P256 - 1; i >= 0; i--) { + if (a[i]) { + break; + } + } + return i + 1; } uint32_t multiprecision_most_signbits(uint32_t* a) { int aMostSignDWORDs; aMostSignDWORDs = multiprecision_most_signdwords(a); - if (aMostSignDWORDs == 0) return 0; + if (aMostSignDWORDs == 0) { + return 0; + } - return (((aMostSignDWORDs - 1) << DWORD_BITS_SHIFT) + - multiprecision_dword_bits(a[aMostSignDWORDs - 1])); + return ((aMostSignDWORDs - 1) << DWORD_BITS_SHIFT) + + multiprecision_dword_bits(a[aMostSignDWORDs - 1]); } uint32_t multiprecision_add(uint32_t* c, uint32_t* a, uint32_t* b) { @@ -168,7 +187,9 @@ void multiprecision_sub_mod(uint32_t* c, uint32_t* a, uint32_t* b) { uint32_t* modp = curve_p256.p; borrow = multiprecision_sub(c, a, b); - if (borrow) multiprecision_add(c, c, modp); + if (borrow) { + multiprecision_add(c, c, modp); + } } // c=a<= 0) multiprecision_sub(c, c, modp); + if (multiprecision_compare(c, modp) >= 0) { + multiprecision_sub(c, c, modp); + } } void multiprecision_inv_mod(uint32_t* aminus, uint32_t* u) { @@ -465,9 +488,9 @@ void multiprecision_inv_mod(uint32_t* aminus, uint32_t* u) { while (!(u[0] & 0x01)) // u is even { multiprecision_rshift(u, u); - if (!(A[0] & 0x01)) // A is even + if (!(A[0] & 0x01)) { // A is even multiprecision_rshift(A, A); - else { + } else { A[KEY_LENGTH_DWORDS_P256] = multiprecision_add(A, A, modp); // A =A+p multiprecision_rshift(A, A); A[KEY_LENGTH_DWORDS_P256 - 1] |= (A[KEY_LENGTH_DWORDS_P256] << 31); @@ -496,8 +519,9 @@ void multiprecision_inv_mod(uint32_t* aminus, uint32_t* u) { } } - if (multiprecision_compare(C, modp) >= 0) + if (multiprecision_compare(C, modp) >= 0) { multiprecision_sub(aminus, C, modp); - else + } else { multiprecision_copy(aminus, C); + } } diff --git a/system/stack/smp/p_256_multprecision.h b/system/stack/smp/p_256_multprecision.h index c0f9636258a..ff933400b13 100644 --- a/system/stack/smp/p_256_multprecision.h +++ b/system/stack/smp/p_256_multprecision.h @@ -47,7 +47,7 @@ void multiprecision_rshift(uint32_t* c, uint32_t* a); // c=a>>1, return carrier void multiprecision_lshift_mod(uint32_t* c, uint32_t* a); // c=a<role, recv, p_cb->local_i_key, p_cb->local_r_key); + log::verbose("before update role={} recv={} local_i_key=0x{:02x}, local_r_key=0x{:02x}", + p_cb->role, recv, p_cb->local_i_key, p_cb->local_r_key); if (((p_cb->sc_mode_required_by_peer) || (p_cb->smp_over_br)) && - ((key_type == SMP_SEC_KEY_TYPE_ENC) || - (key_type == SMP_SEC_KEY_TYPE_LK))) { + ((key_type == SMP_SEC_KEY_TYPE_ENC) || (key_type == SMP_SEC_KEY_TYPE_LK))) { /* in LE SC mode LTK, CSRK and BR/EDR LK are derived locally instead of ** being exchanged with the peer */ p_cb->local_i_key &= ~key_type; p_cb->local_r_key &= ~key_type; } else if (p_cb->role == HCI_ROLE_PERIPHERAL) { - if (recv) + if (recv) { p_cb->local_i_key &= ~key_type; - else + } else { p_cb->local_r_key &= ~key_type; + } } else { - if (recv) + if (recv) { p_cb->local_r_key &= ~key_type; - else + } else { p_cb->local_i_key &= ~key_type; + } } - log::verbose("updated local_i_key=0x{:02x}, local_r_key=0x{:02x}", - p_cb->local_i_key, p_cb->local_r_key); + log::verbose("updated local_i_key=0x{:02x}, local_r_key=0x{:02x}", p_cb->local_i_key, + p_cb->local_r_key); } /******************************************************************************* @@ -115,8 +113,7 @@ void smp_send_app_cback(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { tBTM_STATUS callback_rc; uint8_t remote_lmp_version = 0; - log::debug("addr:{} event:{}", p_cb->pairing_bda, - smp_evt_to_text(p_cb->cb_evt)); + log::debug("addr:{} event:{}", p_cb->pairing_bda, smp_evt_to_text(p_cb->cb_evt)); if (p_cb->p_callback && p_cb->cb_evt != 0) { switch (p_cb->cb_evt) { @@ -158,8 +155,7 @@ void smp_send_app_cback(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { break; } - callback_rc = - (*p_cb->p_callback)(p_cb->cb_evt, p_cb->pairing_bda, &cb_data); + callback_rc = (*p_cb->p_callback)(p_cb->cb_evt, p_cb->pairing_bda, &cb_data); if (callback_rc == BTM_SUCCESS) { switch (p_cb->cb_evt) { @@ -178,50 +174,47 @@ void smp_send_app_cback(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { } log::debug( - "Remote request IO capabilities precondition " - "auth_req:0x{:02x},io_cap:{} loc_oob_flag:{} loc_enc_size:{}, " - "local_i_key:0x{:02x}, local_r_key:0x{:02x}", - p_cb->loc_auth_req, p_cb->local_io_capability, p_cb->loc_oob_flag, - p_cb->loc_enc_size, p_cb->local_i_key, p_cb->local_r_key); + "Remote request IO capabilities precondition " + "auth_req:0x{:02x},io_cap:{} loc_oob_flag:{} loc_enc_size:{}, " + "local_i_key:0x{:02x}, local_r_key:0x{:02x}", + p_cb->loc_auth_req, p_cb->local_io_capability, p_cb->loc_oob_flag, + p_cb->loc_enc_size, p_cb->local_i_key, p_cb->local_r_key); p_cb->sc_only_mode_locally_required = - (p_cb->init_security_mode == BTM_SEC_MODE_SC) ? true : false; + (p_cb->init_security_mode == BTM_SEC_MODE_SC) ? true : false; /* just for PTS, force SC bit */ if (p_cb->sc_only_mode_locally_required) { p_cb->loc_auth_req |= SMP_SC_SUPPORT_BIT; } if (!get_btm_client_interface().peer.BTM_ReadRemoteVersion( - p_cb->pairing_bda, &remote_lmp_version, nullptr, nullptr)) { - log::warn("SMP Unable to determine remote_lmp_version:{}", - remote_lmp_version); + p_cb->pairing_bda, &remote_lmp_version, nullptr, nullptr)) { + log::warn("SMP Unable to determine remote_lmp_version:{}", remote_lmp_version); } if (!p_cb->sc_only_mode_locally_required && (!(p_cb->loc_auth_req & SMP_SC_SUPPORT_BIT) || - (remote_lmp_version && - remote_lmp_version < HCI_PROTO_VERSION_4_2) || + (remote_lmp_version && remote_lmp_version < HCI_PROTO_VERSION_4_2) || interop_match_addr(INTEROP_DISABLE_LE_SECURE_CONNECTIONS, (const RawAddress*)&p_cb->pairing_bda))) { log::debug( - "Setting SC, H7 and LinkKey bits to false to support legacy " - "device with lmp version:{}", - remote_lmp_version); + "Setting SC, H7 and LinkKey bits to false to support legacy " + "device with lmp version:{}", + remote_lmp_version); p_cb->loc_auth_req &= ~SMP_SC_SUPPORT_BIT; p_cb->loc_auth_req &= ~SMP_KP_SUPPORT_BIT; p_cb->local_i_key &= ~SMP_SEC_KEY_TYPE_LK; p_cb->local_r_key &= ~SMP_SEC_KEY_TYPE_LK; } - if (remote_lmp_version && - remote_lmp_version < HCI_PROTO_VERSION_5_0) { + if (remote_lmp_version && remote_lmp_version < HCI_PROTO_VERSION_5_0) { p_cb->loc_auth_req &= ~SMP_H7_SUPPORT_BIT; } log::debug( - "Remote request IO capabilities postcondition " - "auth_req:0x{:02x},local_i_key:0x{:02x}, local_r_key:0x{:02x}", - p_cb->loc_auth_req, p_cb->local_i_key, p_cb->local_r_key); + "Remote request IO capabilities postcondition " + "auth_req:0x{:02x},local_i_key:0x{:02x}, local_r_key:0x{:02x}", + p_cb->loc_auth_req, p_cb->local_i_key, p_cb->local_r_key); smp_sm_event(p_cb, SMP_IO_RSP_EVT, NULL); break; @@ -236,10 +229,9 @@ void smp_send_app_cback(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { p_cb->local_r_key &= ~SMP_SEC_KEY_TYPE_LK; log::debug( - "for SMP over BR max_key_size:0x{:02x}, local_i_key:0x{:02x}, " - "local_r_key:0x{:02x}, p_cb->loc_auth_req:0x{:02x}", - p_cb->loc_enc_size, p_cb->local_i_key, p_cb->local_r_key, - p_cb->loc_auth_req); + "for SMP over BR max_key_size:0x{:02x}, local_i_key:0x{:02x}, " + "local_r_key:0x{:02x}, p_cb->loc_auth_req:0x{:02x}", + p_cb->loc_enc_size, p_cb->local_i_key, p_cb->local_r_key, p_cb->loc_auth_req); smp_br_state_machine_event(p_cb, SMP_BR_KEYS_RSP_EVT, NULL); break; @@ -271,12 +263,10 @@ void smp_send_pair_fail(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { p_cb->status = p_data->status; p_cb->failure = p_data->status; - if (p_cb->status <= SMP_MAX_FAIL_RSN_PER_SPEC && - p_cb->status != SMP_SUCCESS) { + if (p_cb->status <= SMP_MAX_FAIL_RSN_PER_SPEC && p_cb->status != SMP_SUCCESS) { log::error("Pairing failed smp_status:{}", smp_status_text(p_cb->status)); BTM_LogHistory(kBtmLogTag, p_cb->pairing_bda, "Pairing failed", - base::StringPrintf("smp_status:%s", - smp_status_text(p_cb->status).c_str())); + base::StringPrintf("smp_status:%s", smp_status_text(p_cb->status).c_str())); smp_send_cmd(SMP_OPCODE_PAIRING_FAILED, p_cb); p_cb->wait_for_authorization_complete = true; } @@ -291,7 +281,9 @@ void smp_send_pair_req(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) { log::verbose("addr:{}", p_cb->pairing_bda); /* erase all keys when central sends pairing req*/ - if (p_dev_rec) btm_sec_clear_ble_keys(p_dev_rec); + if (p_dev_rec) { + btm_sec_clear_ble_keys(p_dev_rec); + } /* do not manipulate the key, let app decide, leave out to BTM to mandate key distribution for bonding case */ smp_send_cmd(SMP_OPCODE_PAIRING_REQ, p_cb); @@ -308,10 +300,11 @@ void smp_send_pair_rsp(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) { p_cb->local_r_key &= p_cb->peer_r_key; if (smp_send_cmd(SMP_OPCODE_PAIRING_RSP, p_cb)) { - if (p_cb->selected_association_model == SMP_MODEL_SEC_CONN_OOB) + if (p_cb->selected_association_model == SMP_MODEL_SEC_CONN_OOB) { smp_use_oob_private_key(p_cb, NULL); - else + } else { smp_decide_association_model(p_cb, NULL); + } } } @@ -383,18 +376,18 @@ void smp_send_enc_info(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) { /* save the DIV and key size information when acting as peripheral device */ tBTM_LE_KEY_VALUE le_key = { - .lenc_key = - { - .ltk = p_cb->ltk, - .div = p_cb->div, - .key_size = p_cb->loc_enc_size, - .sec_level = p_cb->sec_level, - }, + .lenc_key = + { + .ltk = p_cb->ltk, + .div = p_cb->div, + .key_size = p_cb->loc_enc_size, + .sec_level = p_cb->sec_level, + }, }; - if ((p_cb->peer_auth_req & SMP_AUTH_BOND) && - (p_cb->loc_auth_req & SMP_AUTH_BOND)) + if ((p_cb->peer_auth_req & SMP_AUTH_BOND) && (p_cb->loc_auth_req & SMP_AUTH_BOND)) { btm_sec_save_le_key(p_cb->pairing_bda, BTM_LE_KEY_LENC, &le_key, true); + } smp_key_distribution(p_cb, NULL); } @@ -409,9 +402,9 @@ void smp_send_id_info(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) { smp_send_cmd(SMP_OPCODE_IDENTITY_INFO, p_cb); smp_send_cmd(SMP_OPCODE_ID_ADDR, p_cb); - if ((p_cb->peer_auth_req & SMP_AUTH_BOND) && - (p_cb->loc_auth_req & SMP_AUTH_BOND)) + if ((p_cb->peer_auth_req & SMP_AUTH_BOND) && (p_cb->loc_auth_req & SMP_AUTH_BOND)) { btm_sec_save_le_key(p_cb->pairing_bda, BTM_LE_KEY_LID, nullptr, true); + } smp_key_distribution_by_transport(p_cb, NULL); } @@ -423,13 +416,13 @@ void smp_send_csrk_info(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) { if (smp_send_cmd(SMP_OPCODE_SIGN_INFO, p_cb)) { tBTM_LE_KEY_VALUE key = { - .lcsrk_key = - { - .counter = 0, /* initialize the local counter */ - .div = p_cb->div, - .sec_level = p_cb->sec_level, - .csrk = p_cb->csrk, - }, + .lcsrk_key = + { + .counter = 0, /* initialize the local counter */ + .div = p_cb->div, + .sec_level = p_cb->sec_level, + .csrk = p_cb->csrk, + }, }; btm_sec_save_le_key(p_cb->pairing_bda, BTM_LE_KEY_LCSRK, &key, true); } @@ -481,11 +474,10 @@ void smp_proc_sec_req(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { case BTM_BLE_SEC_REQ_ACT_PAIR: p_cb->sc_only_mode_locally_required = - (p_cb->init_security_mode == BTM_SEC_MODE_SC) ? true : false; + (p_cb->init_security_mode == BTM_SEC_MODE_SC) ? true : false; /* respond to non SC pairing request as failure in SC only mode */ - if (p_cb->sc_only_mode_locally_required && - (auth_req & SMP_SC_SUPPORT_BIT) == 0) { + if (p_cb->sc_only_mode_locally_required && (auth_req & SMP_SC_SUPPORT_BIT) == 0) { tSMP_INT_DATA smp_int_data; smp_int_data.status = SMP_PAIR_AUTH_FAIL; smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data); @@ -531,8 +523,7 @@ void smp_proc_pair_fail(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { log::verbose("addr:{}", p_cb->pairing_bda); if (p_cb->rcvd_cmd_len < 2) { - log::warn("rcvd_cmd_len {} too short: must be at least 2", - p_cb->rcvd_cmd_len); + log::warn("rcvd_cmd_len {} too short: must be at least 2", p_cb->rcvd_cmd_len); p_cb->status = SMP_INVALID_PARAMETERS; } else { p_cb->status = static_cast(p_data->p_data[0]); @@ -553,8 +544,9 @@ void smp_proc_pair_cmd(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { log::verbose("pairing_bda={}", p_cb->pairing_bda); /* erase all keys if it is peripheral proc pairing req */ - if (p_dev_rec && (p_cb->role == HCI_ROLE_PERIPHERAL)) + if (p_dev_rec && (p_cb->role == HCI_ROLE_PERIPHERAL)) { btm_sec_clear_ble_keys(p_dev_rec); + } p_cb->flags |= SMP_PAIR_FLAG_ENC_AFTER_PAIR; @@ -588,7 +580,9 @@ void smp_proc_pair_cmd(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { } // PTS Testing failure modes - if (pts_test_send_authentication_complete_failure(p_cb)) return; + if (pts_test_send_authentication_complete_failure(p_cb)) { + return; + } if (p_cb->role == HCI_ROLE_PERIPHERAL) { if (!(p_cb->flags & SMP_PAIR_FLAGS_WE_STARTED_DD)) { @@ -596,7 +590,7 @@ void smp_proc_pair_cmd(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { p_cb->local_i_key = p_cb->peer_i_key; p_cb->local_r_key = p_cb->peer_r_key; - p_cb->cb_evt = SMP_IO_CAP_REQ_EVT; + p_cb->cb_evt = SMP_IO_CAP_REQ_EVT; } else /* update local i/r key according to pairing request */ { /* pairing started with this side (peripheral) sending Security Request */ @@ -606,10 +600,8 @@ void smp_proc_pair_cmd(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { if (p_cb->sc_only_mode_locally_required && (!(p_cb->sc_mode_required_by_peer) || - (p_cb->selected_association_model == - SMP_MODEL_SEC_CONN_JUSTWORKS))) { - log::error( - "pairing failed - peripheral requires secure connection only mode"); + (p_cb->selected_association_model == SMP_MODEL_SEC_CONN_JUSTWORKS))) { + log::error("pairing failed - peripheral requires secure connection only mode"); tSMP_INT_DATA smp_int_data; smp_int_data.status = SMP_PAIR_AUTH_FAIL; smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data); @@ -617,7 +609,9 @@ void smp_proc_pair_cmd(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { } if (p_cb->selected_association_model == SMP_MODEL_SEC_CONN_OOB) { - if (smp_request_oob_data(p_cb)) return; + if (smp_request_oob_data(p_cb)) { + return; + } } else { smp_send_pair_rsp(p_cb, NULL); } @@ -630,8 +624,8 @@ void smp_proc_pair_cmd(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { (!(p_cb->sc_mode_required_by_peer) || (p_cb->selected_association_model == SMP_MODEL_SEC_CONN_JUSTWORKS))) { log::error( - "Central requires secure connection only mode but it can't be " - "provided -> Central fails pairing"); + "Central requires secure connection only mode but it can't be " + "provided -> Central fails pairing"); tSMP_INT_DATA smp_int_data; smp_int_data.status = SMP_PAIR_AUTH_FAIL; smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data); @@ -639,7 +633,9 @@ void smp_proc_pair_cmd(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { } if (p_cb->selected_association_model == SMP_MODEL_SEC_CONN_OOB) { - if (smp_request_oob_data(p_cb)) return; + if (smp_request_oob_data(p_cb)) { + return; + } } else { smp_decide_association_model(p_cb, NULL); } @@ -830,8 +826,7 @@ void smp_br_process_pairing_command(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { log::verbose("addr:{}", p_cb->pairing_bda); /* rejecting BR pairing request over non-SC BR link */ - if (!p_dev_rec->sec_rec.new_encryption_key_is_p256 && - p_cb->role == HCI_ROLE_PERIPHERAL) { + if (!p_dev_rec->sec_rec.new_encryption_key_is_p256 && p_cb->role == HCI_ROLE_PERIPHERAL) { tSMP_INT_DATA smp_int_data; smp_int_data.status = SMP_XTRANS_DERIVE_NOT_ALLOW; smp_br_state_machine_event(p_cb, SMP_BR_AUTH_CMPL_EVT, &smp_int_data); @@ -839,8 +834,9 @@ void smp_br_process_pairing_command(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { } /* erase all keys if it is peripheral proc pairing req*/ - if (p_dev_rec && (p_cb->role == HCI_ROLE_PERIPHERAL)) + if (p_dev_rec && (p_cb->role == HCI_ROLE_PERIPHERAL)) { btm_sec_clear_ble_keys(p_dev_rec); + } p_cb->flags |= SMP_PAIR_FLAG_ENC_AFTER_PAIR; @@ -878,8 +874,7 @@ void smp_br_process_pairing_command(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { } else { /* Central receives pairing response */ log::verbose( - "central rcvs valid PAIRING RESPONSE. Supposed to move to key " - "distribution phase."); + "central rcvs valid PAIRING RESPONSE. Supposed to move to key distribution phase."); } /* auth_req received via BR/EDR SM channel is set to 0, @@ -907,10 +902,9 @@ void smp_br_process_security_grant(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { * Description sets the SMP kes to be derived/distribute over BR/EDR transport * before starting the distribution/derivation ******************************************************************************/ -void smp_br_check_authorization_request(tSMP_CB* p_cb, - tSMP_INT_DATA* /* p_data */) { - log::verbose("rcvs i_keys=0x{:x} r_keys=0x{:x} (i-initiator r-responder)", - p_cb->local_i_key, p_cb->local_r_key); +void smp_br_check_authorization_request(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) { + log::verbose("rcvs i_keys=0x{:x} r_keys=0x{:x} (i-initiator r-responder)", p_cb->local_i_key, + p_cb->local_r_key); /* In LE SC mode LK field is ignored when BR/EDR transport is used */ p_cb->local_i_key &= ~SMP_SEC_KEY_TYPE_LK; @@ -923,22 +917,21 @@ void smp_br_check_authorization_request(tSMP_CB* p_cb, } /* Check if H7 function needs to be used for key derivation*/ - if ((p_cb->loc_auth_req & SMP_H7_SUPPORT_BIT) && - (p_cb->peer_auth_req & SMP_H7_SUPPORT_BIT)) { + if ((p_cb->loc_auth_req & SMP_H7_SUPPORT_BIT) && (p_cb->peer_auth_req & SMP_H7_SUPPORT_BIT)) { p_cb->key_derivation_h7_used = TRUE; } - log::verbose( - "use h7={}, i_keys=0x{:x} r_keys=0x{:x} (i-initiator r-responder)", - p_cb->key_derivation_h7_used, p_cb->local_i_key, p_cb->local_r_key); + log::verbose("use h7={}, i_keys=0x{:x} r_keys=0x{:x} (i-initiator r-responder)", + p_cb->key_derivation_h7_used, p_cb->local_i_key, p_cb->local_r_key); if (/*((p_cb->peer_auth_req & SMP_AUTH_BOND) || (p_cb->loc_auth_req & SMP_AUTH_BOND)) &&*/ - (p_cb->local_i_key || p_cb->local_r_key)) { + p_cb->local_i_key || p_cb->local_r_key) { smp_br_state_machine_event(p_cb, SMP_BR_BOND_REQ_EVT, NULL); /* if no peer key is expected, start central key distribution */ - if (p_cb->role == HCI_ROLE_CENTRAL && p_cb->local_r_key == 0) + if (p_cb->role == HCI_ROLE_CENTRAL && p_cb->local_r_key == 0) { smp_key_distribution_by_transport(p_cb, NULL); + } } else { tSMP_INT_DATA smp_int_data; smp_int_data.status = SMP_SUCCESS; @@ -952,11 +945,10 @@ void smp_br_check_authorization_request(tSMP_CB* p_cb, * used. ******************************************************************************/ void smp_br_select_next_key(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { - log::verbose("role={} (0-central) r_keys=0x{:x} i_keys=0x{:x}", p_cb->role, - p_cb->local_r_key, p_cb->local_i_key); + log::verbose("role={} (0-central) r_keys=0x{:x} i_keys=0x{:x}", p_cb->role, p_cb->local_r_key, + p_cb->local_i_key); - if (p_cb->role == HCI_ROLE_PERIPHERAL || - (!p_cb->local_r_key && p_cb->role == HCI_ROLE_CENTRAL)) { + if (p_cb->role == HCI_ROLE_PERIPHERAL || (!p_cb->local_r_key && p_cb->role == HCI_ROLE_CENTRAL)) { smp_key_pick_key(p_cb, p_data); } @@ -999,15 +991,14 @@ void smp_proc_central_id(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { log::verbose("addr:{}", p_cb->pairing_bda); if (p_cb->rcvd_cmd_len < 11) { // 1(Code) + 2(EDIV) + 8(Rand) - log::error("Invalid command length:{}, should be at least 11", - p_cb->rcvd_cmd_len); + log::error("Invalid command length:{}, should be at least 11", p_cb->rcvd_cmd_len); return; } smp_update_key_mask(p_cb, SMP_SEC_KEY_TYPE_ENC, true); tBTM_LE_KEY_VALUE le_key = { - .penc_key = {}, + .penc_key = {}, }; STREAM_TO_UINT16(le_key.penc_key.ediv, p); STREAM_TO_ARRAY(le_key.penc_key.rand, p, BT_OCTET8_LEN); @@ -1017,9 +1008,9 @@ void smp_proc_central_id(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { le_key.penc_key.sec_level = p_cb->sec_level; le_key.penc_key.key_size = p_cb->loc_enc_size; - if ((p_cb->peer_auth_req & SMP_AUTH_BOND) && - (p_cb->loc_auth_req & SMP_AUTH_BOND)) + if ((p_cb->peer_auth_req & SMP_AUTH_BOND) && (p_cb->loc_auth_req & SMP_AUTH_BOND)) { btm_sec_save_le_key(p_cb->pairing_bda, BTM_LE_KEY_PENC, &le_key, true); + } smp_key_distribution(p_cb, NULL); } @@ -1057,7 +1048,7 @@ void smp_proc_id_addr(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { smp_update_key_mask(p_cb, SMP_SEC_KEY_TYPE_ID, true); tBTM_LE_KEY_VALUE pid_key = { - .pid_key = {}, + .pid_key = {}, }; STREAM_TO_UINT8(pid_key.pid_key.identity_addr_type, p); @@ -1070,8 +1061,7 @@ void smp_proc_id_addr(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { p_cb->id_addr = pid_key.pid_key.identity_addr; /* store the ID key from peer device */ - if ((p_cb->peer_auth_req & SMP_AUTH_BOND) && - (p_cb->loc_auth_req & SMP_AUTH_BOND)) { + if ((p_cb->peer_auth_req & SMP_AUTH_BOND) && (p_cb->loc_auth_req & SMP_AUTH_BOND)) { btm_sec_save_le_key(p_cb->pairing_bda, BTM_LE_KEY_PID, &pid_key, true); p_cb->cb_evt = SMP_LE_ADDR_ASSOC_EVT; smp_send_app_cback(p_cb, NULL); @@ -1094,22 +1084,21 @@ void smp_proc_srk_info(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { /* save CSRK to security record */ tBTM_LE_KEY_VALUE le_key = { - .pcsrk_key = - { - .sec_level = p_cb->sec_level, - }, + .pcsrk_key = + { + .sec_level = p_cb->sec_level, + }, }; /* get peer CSRK */ - maybe_non_aligned_memcpy(le_key.pcsrk_key.csrk.data(), p_data->p_data, - OCTET16_LEN); + maybe_non_aligned_memcpy(le_key.pcsrk_key.csrk.data(), p_data->p_data, OCTET16_LEN); /* initialize the peer counter */ le_key.pcsrk_key.counter = 0; - if ((p_cb->peer_auth_req & SMP_AUTH_BOND) && - (p_cb->loc_auth_req & SMP_AUTH_BOND)) + if ((p_cb->peer_auth_req & SMP_AUTH_BOND) && (p_cb->loc_auth_req & SMP_AUTH_BOND)) { btm_sec_save_le_key(p_cb->pairing_bda, BTM_LE_KEY_PCSRK, &le_key, true); + } smp_key_distribution_by_transport(p_cb, NULL); } @@ -1122,12 +1111,13 @@ void smp_proc_compare(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { if (!memcmp(p_cb->rconfirm.data(), p_data->key.p_data, OCTET16_LEN)) { /* compare the max encryption key size, and save the smaller one for the * link */ - if (p_cb->peer_enc_size < p_cb->loc_enc_size) + if (p_cb->peer_enc_size < p_cb->loc_enc_size) { p_cb->loc_enc_size = p_cb->peer_enc_size; + } - if (p_cb->role == HCI_ROLE_PERIPHERAL) + if (p_cb->role == HCI_ROLE_PERIPHERAL) { smp_sm_event(p_cb, SMP_RAND_EVT, NULL); - else { + } else { /* central device always use received i/r key as keys to distribute */ p_cb->local_i_key = p_cb->peer_i_key; p_cb->local_r_key = p_cb->peer_r_key; @@ -1156,8 +1146,9 @@ void smp_proc_sl_key(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { } else if (key_type == SMP_KEY_TYPE_CFM) { smp_set_state(SMP_STATE_WAIT_CONFIRM); - if (p_cb->flags & SMP_PAIR_FLAGS_CMD_CONFIRM_RCVD) + if (p_cb->flags & SMP_PAIR_FLAGS_CMD_CONFIRM_RCVD) { smp_sm_event(p_cb, SMP_CONFIRM_EVT, NULL); + } } } @@ -1170,8 +1161,7 @@ void smp_start_enc(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { log::verbose("addr:{}", p_cb->pairing_bda); if (p_data != NULL) { - cmd = btm_ble_start_encrypt(p_cb->pairing_bda, true, - (Octet16*)p_data->key.p_data); + cmd = btm_ble_start_encrypt(p_cb->pairing_bda, true, (Octet16*)p_data->key.p_data); } else { cmd = btm_ble_start_encrypt(p_cb->pairing_bda, false, NULL); } @@ -1189,8 +1179,9 @@ void smp_start_enc(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { ******************************************************************************/ void smp_proc_discard(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) { log::verbose("addr:{}", p_cb->pairing_bda); - if (!(p_cb->flags & SMP_PAIR_FLAGS_WE_STARTED_DD)) + if (!(p_cb->flags & SMP_PAIR_FLAGS_WE_STARTED_DD)) { smp_reset_control_value(p_cb); + } } /******************************************************************************* @@ -1215,17 +1206,15 @@ void smp_sirk_verify(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { log::debug("addr:{}", p_cb->pairing_bda); if (p_data->status != SMP_SUCCESS) { - log::debug( - "Cancel device verification due to invalid status({}) while bonding.", - p_data->status); + log::debug("Cancel device verification due to invalid status({}) while bonding.", + p_data->status); tSMP_INT_DATA smp_int_data; smp_int_data.status = SMP_SIRK_DEVICE_INVALID; - BTM_LogHistory( - kBtmLogTag, p_cb->pairing_bda, "SIRK verification", - base::StringPrintf("Verification failed, smp_status:%s", - smp_status_text(smp_int_data.status).c_str())); + BTM_LogHistory(kBtmLogTag, p_cb->pairing_bda, "SIRK verification", + base::StringPrintf("Verification failed, smp_status:%s", + smp_status_text(smp_int_data.status).c_str())); smp_sm_event(p_cb, SMP_SIRK_DEVICE_VALID_EVT, &smp_int_data); @@ -1257,10 +1246,8 @@ void smp_sirk_verify(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { void smp_check_auth_req(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { uint8_t enc_enable = p_data->status; - log::verbose( - "rcvs enc_enable={} i_keys=0x{:x} r_keys=0x{:x} (i-initiator " - "r-responder)", - enc_enable, p_cb->local_i_key, p_cb->local_r_key); + log::verbose("rcvs enc_enable={} i_keys=0x{:x} r_keys=0x{:x} (i-initiator r-responder)", + enc_enable, p_cb->local_i_key, p_cb->local_r_key); if (enc_enable == 1) { if (p_cb->sc_mode_required_by_peer) { /* In LE SC mode LTK is used instead of STK and has to be always saved */ @@ -1285,13 +1272,12 @@ void smp_check_auth_req(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { p_cb->local_i_key &= ~SMP_SEC_KEY_TYPE_LK; p_cb->local_r_key &= ~SMP_SEC_KEY_TYPE_LK; } - log::verbose( - "rcvs upgrades:i_keys=0x{:x} r_keys=0x{:x} (i-initiator r-responder)", - p_cb->local_i_key, p_cb->local_r_key); + log::verbose("rcvs upgrades:i_keys=0x{:x} r_keys=0x{:x} (i-initiator r-responder)", + p_cb->local_i_key, p_cb->local_r_key); if (/*((p_cb->peer_auth_req & SMP_AUTH_BOND) || (p_cb->loc_auth_req & SMP_AUTH_BOND)) &&*/ - (p_cb->local_i_key || p_cb->local_r_key)) { + p_cb->local_i_key || p_cb->local_r_key) { smp_sm_event(p_cb, SMP_BOND_REQ_EVT, NULL); } else { tSMP_INT_DATA smp_int_data; @@ -1302,8 +1288,9 @@ void smp_check_auth_req(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { tSMP_INT_DATA smp_int_data; smp_int_data.status = enc_enable ? SMP_SUCCESS : SMP_ENC_FAIL; /* if failed for encryption after pairing, send callback */ - if (p_cb->flags & SMP_PAIR_FLAG_ENC_AFTER_PAIR) + if (p_cb->flags & SMP_PAIR_FLAG_ENC_AFTER_PAIR) { smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data); + } /* if enc failed for old security information */ /* if central device, clean up and abck to idle; peripheral device do * nothing */ @@ -1318,8 +1305,7 @@ void smp_check_auth_req(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { * Description Pick a key distribution function based on the key mask. ******************************************************************************/ void smp_key_pick_key(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { - uint8_t key_to_dist = (p_cb->role == HCI_ROLE_PERIPHERAL) ? p_cb->local_r_key - : p_cb->local_i_key; + uint8_t key_to_dist = (p_cb->role == HCI_ROLE_PERIPHERAL) ? p_cb->local_r_key : p_cb->local_i_key; uint8_t i = 0; log::verbose("key_to_dist=0x{:x}", key_to_dist); @@ -1339,11 +1325,10 @@ void smp_key_pick_key(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { * Description start key distribution if required. ******************************************************************************/ void smp_key_distribution(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { - log::verbose("role={} (0-central) r_keys=0x{:x} i_keys=0x{:x}", p_cb->role, - p_cb->local_r_key, p_cb->local_i_key); + log::verbose("role={} (0-central) r_keys=0x{:x} i_keys=0x{:x}", p_cb->role, p_cb->local_r_key, + p_cb->local_i_key); - if (p_cb->role == HCI_ROLE_PERIPHERAL || - (!p_cb->local_r_key && p_cb->role == HCI_ROLE_CENTRAL)) { + if (p_cb->role == HCI_ROLE_PERIPHERAL || (!p_cb->local_r_key && p_cb->role == HCI_ROLE_CENTRAL)) { smp_key_pick_key(p_cb, p_data); } @@ -1354,9 +1339,7 @@ void smp_key_distribution(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(p_cb->pairing_bda); if (!(p_dev_rec->sec_rec.sec_flags & BTM_SEC_LE_LINK_KEY_AUTHED) && (p_dev_rec->sec_rec.sec_flags & BTM_SEC_LINK_KEY_AUTHED)) { - log::verbose( - "BR key is higher security than existing LE keys, don't derive " - "LK from LTK"); + log::verbose("BR key is higher security than existing LE keys, don't derive LK from LTK"); } else { smp_derive_link_key_from_long_term_key(p_cb, NULL); } @@ -1373,8 +1356,7 @@ void smp_key_distribution(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { */ if (!alarm_is_scheduled(p_cb->delayed_auth_timer_ent)) { log::verbose("delaying auth complete"); - alarm_set_on_mloop(p_cb->delayed_auth_timer_ent, - SMP_DELAYED_AUTH_TIMEOUT_MS, + alarm_set_on_mloop(p_cb->delayed_auth_timer_ent, SMP_DELAYED_AUTH_TIMEOUT_MS, smp_delayed_auth_complete_timeout, NULL); } } else { @@ -1398,8 +1380,7 @@ void smp_decide_association_model(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) { switch (p_cb->selected_association_model) { case SMP_MODEL_ENCRYPTION_ONLY: /* TK = 0, go calculate Confirm */ - if (p_cb->role == HCI_ROLE_CENTRAL && - ((p_cb->peer_auth_req & SMP_AUTH_YN_BIT) != 0) && + if (p_cb->role == HCI_ROLE_CENTRAL && ((p_cb->peer_auth_req & SMP_AUTH_YN_BIT) != 0) && ((p_cb->loc_auth_req & SMP_AUTH_YN_BIT) == 0)) { log::error("IO capability does not meet authentication requirement"); smp_int_data.status = SMP_PAIR_AUTH_FAIL; @@ -1415,8 +1396,7 @@ void smp_decide_association_model(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) { smp_sm_event(p_cb, SMP_SC_DSPL_NC_EVT, NULL); } else { p_cb->sec_level = SMP_SEC_UNAUTHENTICATE; - log::verbose("p_cb->sec_level={} (SMP_SEC_UNAUTHENTICATE)", - p_cb->sec_level); + log::verbose("p_cb->sec_level={} (SMP_SEC_UNAUTHENTICATE)", p_cb->sec_level); tSMP_KEY key; key.key_type = SMP_KEY_TYPE_TK; @@ -1432,8 +1412,7 @@ void smp_decide_association_model(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) { case SMP_MODEL_PASSKEY: p_cb->sec_level = SMP_SEC_AUTHENTICATED; - log::verbose("p_cb->sec_level={}(SMP_SEC_AUTHENTICATED)", - p_cb->sec_level); + log::verbose("p_cb->sec_level={}(SMP_SEC_AUTHENTICATED)", p_cb->sec_level); p_cb->cb_evt = SMP_PASSKEY_REQ_EVT; int_evt = SMP_TK_REQ_EVT; @@ -1442,8 +1421,7 @@ void smp_decide_association_model(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) { case SMP_MODEL_OOB: log::error("Association Model=SMP_MODEL_OOB"); p_cb->sec_level = SMP_SEC_AUTHENTICATED; - log::verbose("p_cb->sec_level={}(SMP_SEC_AUTHENTICATED)", - p_cb->sec_level); + log::verbose("p_cb->sec_level={}(SMP_SEC_AUTHENTICATED)", p_cb->sec_level); p_cb->cb_evt = SMP_OOB_REQ_EVT; int_evt = SMP_TK_REQ_EVT; @@ -1479,7 +1457,9 @@ void smp_decide_association_model(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) { } log::verbose("sec_level={}", p_cb->sec_level); - if (int_evt) smp_sm_event(p_cb, int_evt, &smp_int_data); + if (int_evt) { + smp_sm_event(p_cb, int_evt, &smp_int_data); + } } /******************************************************************************* @@ -1501,8 +1481,8 @@ void smp_process_io_response(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) { (!(p_cb->sc_mode_required_by_peer) || (p_cb->selected_association_model == SMP_MODEL_SEC_CONN_JUSTWORKS))) { log::error( - "Peripheral requires secure connection only mode but it can't be " - "provided -> Peripheral fails pairing"); + "Peripheral requires secure connection only mode but it can't be " + "provided -> Peripheral fails pairing"); tSMP_INT_DATA smp_int_data; smp_int_data.status = SMP_PAIR_AUTH_FAIL; smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data); @@ -1536,7 +1516,9 @@ void smp_process_io_response(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) { break; case SMP_OOB_PRESENT: log::info("SMP_MODEL_SEC_CONN_OOB with SMP_OOB_PRESENT"); - if (smp_request_oob_data(p_cb)) return; + if (smp_request_oob_data(p_cb)) { + return; + } break; case SMP_OOB_UNKNOWN: log::warn("SMP_MODEL_SEC_CONN_OOB with SMP_OOB_UNKNOWN"); @@ -1548,7 +1530,9 @@ void smp_process_io_response(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) { } // PTS Testing failure modes - if (pts_test_send_authentication_complete_failure(p_cb)) return; + if (pts_test_send_authentication_complete_failure(p_cb)) { + return; + } smp_send_pair_rsp(p_cb, NULL); } @@ -1559,8 +1543,7 @@ void smp_process_io_response(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) { * Description process application keys response for a peripheral device * (BR/EDR transport). ******************************************************************************/ -void smp_br_process_peripheral_keys_response(tSMP_CB* p_cb, - tSMP_INT_DATA* /* p_data */) { +void smp_br_process_peripheral_keys_response(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) { smp_br_send_pair_response(p_cb, NULL); } @@ -1631,7 +1614,9 @@ void smp_both_have_public_keys(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) { smp_compute_dhkey(p_cb); /* on peripheral side invokes sending local public key to the peer */ - if (p_cb->role == HCI_ROLE_PERIPHERAL) smp_send_pair_public_key(p_cb, NULL); + if (p_cb->role == HCI_ROLE_PERIPHERAL) { + smp_send_pair_public_key(p_cb, NULL); + } smp_sm_event(p_cb, SMP_SC_DHKEY_CMPLT_EVT, NULL); } @@ -1643,14 +1628,12 @@ void smp_both_have_public_keys(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) { * to the peer messages appropriate for the role and association * model. ******************************************************************************/ -void smp_start_secure_connection_phase1(tSMP_CB* p_cb, - tSMP_INT_DATA* /* p_data */) { +void smp_start_secure_connection_phase1(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) { log::verbose("addr:{}", p_cb->pairing_bda); if (p_cb->selected_association_model == SMP_MODEL_SEC_CONN_JUSTWORKS) { p_cb->sec_level = SMP_SEC_UNAUTHENTICATE; - log::verbose("p_cb->sec_level={} (SMP_SEC_UNAUTHENTICATE)", - p_cb->sec_level); + log::verbose("p_cb->sec_level={} (SMP_SEC_UNAUTHENTICATE)", p_cb->sec_level); } else { p_cb->sec_level = SMP_SEC_AUTHENTICATED; log::verbose("p_cb->sec_level={} (SMP_SEC_AUTHENTICATED)", p_cb->sec_level); @@ -1677,8 +1660,7 @@ void smp_start_secure_connection_phase1(tSMP_CB* p_cb, smp_process_secure_connection_oob_data(p_cb, NULL); break; default: - log::error("Association Model={} is not used in LE SC", - p_cb->selected_association_model); + log::error("Association Model={} is not used in LE SC", p_cb->selected_association_model); break; } } @@ -1707,9 +1689,8 @@ void smp_process_local_nonce(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) { /* peripheral commitment is already received, send local nonce, wait * for remote nonce*/ log::verbose( - "central in assoc mode={} already rcvd peripheral commitment - " - "race condition", - p_cb->selected_association_model); + "central in assoc mode={} already rcvd peripheral commitment - race condition", + p_cb->selected_association_model); p_cb->flags &= ~SMP_PAIR_FLAG_HAVE_PEER_COMM; smp_send_rand(p_cb, NULL); smp_set_state(SMP_STATE_WAIT_NONCE); @@ -1739,8 +1720,7 @@ void smp_process_local_nonce(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) { smp_set_state(SMP_STATE_WAIT_NONCE); break; default: - log::error("Association Model={} is not used in LE SC", - p_cb->selected_association_model); + log::error("Association Model={} is not used in LE SC", p_cb->selected_association_model); break; } } @@ -1816,8 +1796,7 @@ void smp_process_peer_nonce(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) { break; case SMP_MODEL_SEC_CONN_PASSKEY_ENT: case SMP_MODEL_SEC_CONN_PASSKEY_DISP: - if (!smp_check_commitment(p_cb) && - p_cb->cert_failure != SMP_NUMERIC_COMPAR_FAIL) { + if (!smp_check_commitment(p_cb) && p_cb->cert_failure != SMP_NUMERIC_COMPAR_FAIL) { tSMP_INT_DATA smp_int_data; smp_int_data.status = SMP_CONFIRM_VALUE_ERR; p_cb->failure = SMP_CONFIRM_VALUE_ERR; @@ -1846,8 +1825,7 @@ void smp_process_peer_nonce(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) { smp_sm_event(p_cb, SMP_SC_PHASE1_CMPLT_EVT, NULL); break; default: - log::error("Association Model={} is not used in LE SC", - p_cb->selected_association_model); + log::error("Association Model={} is not used in LE SC", p_cb->selected_association_model); break; } } @@ -1860,8 +1838,7 @@ void smp_process_peer_nonce(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) { void smp_match_dhkey_checks(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { log::verbose("addr:{}", p_cb->pairing_bda); - if (memcmp(p_data->key.p_data, p_cb->remote_dhkey_check.data(), - OCTET16_LEN)) { + if (memcmp(p_data->key.p_data, p_cb->remote_dhkey_check.data(), OCTET16_LEN)) { log::warn("dhkey chcks do no match"); tSMP_INT_DATA smp_int_data; smp_int_data.status = SMP_DHKEY_CHK_FAIL; @@ -1872,8 +1849,9 @@ void smp_match_dhkey_checks(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { /* compare the max encryption key size, and save the smaller one for the link */ - if (p_cb->peer_enc_size < p_cb->loc_enc_size) + if (p_cb->peer_enc_size < p_cb->loc_enc_size) { p_cb->loc_enc_size = p_cb->peer_enc_size; + } if (p_cb->role == HCI_ROLE_PERIPHERAL) { smp_sm_event(p_cb, SMP_PAIR_DHKEY_CHCK_EVT, NULL); @@ -1892,8 +1870,7 @@ void smp_match_dhkey_checks(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { * * Note SM is supposed to be in the state SMP_STATE_SEC_CONN_PHS2_START. ******************************************************************************/ -void smp_move_to_secure_connections_phase2(tSMP_CB* p_cb, - tSMP_INT_DATA* /* p_data */) { +void smp_move_to_secure_connections_phase2(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) { log::verbose("addr:{}", p_cb->pairing_bda); smp_sm_event(p_cb, SMP_SC_PHASE1_CMPLT_EVT, NULL); } @@ -1907,12 +1884,12 @@ void smp_move_to_secure_connections_phase2(tSMP_CB* p_cb, *condition. It is supposed to be called after peripheral dhkey check is * calculated. ******************************************************************************/ -void smp_phase_2_dhkey_checks_are_present(tSMP_CB* p_cb, - tSMP_INT_DATA* /* p_data */) { +void smp_phase_2_dhkey_checks_are_present(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) { log::verbose("addr:{}", p_cb->pairing_bda); - if (p_cb->flags & SMP_PAIR_FLAG_HAVE_PEER_DHK_CHK) + if (p_cb->flags & SMP_PAIR_FLAG_HAVE_PEER_DHK_CHK) { smp_sm_event(p_cb, SMP_SC_2_DHCK_CHKS_PRES_EVT, NULL); + } } /******************************************************************************* @@ -1929,8 +1906,7 @@ void smp_wait_for_both_public_keys(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) { if ((p_cb->flags & SMP_PAIR_FLAG_HAVE_PEER_PUBL_KEY) && (p_cb->flags & SMP_PAIR_FLAG_HAVE_LOCAL_PUBL_KEY)) { if ((p_cb->role == HCI_ROLE_PERIPHERAL) && - ((p_cb->req_oob_type == SMP_OOB_LOCAL) || - (p_cb->req_oob_type == SMP_OOB_BOTH))) { + ((p_cb->req_oob_type == SMP_OOB_LOCAL) || (p_cb->req_oob_type == SMP_OOB_BOTH))) { smp_set_state(SMP_STATE_PUBLIC_KEY_EXCH); } smp_sm_event(p_cb, SMP_BOTH_PUBL_KEYS_RCVD_EVT, NULL); @@ -1959,8 +1935,7 @@ void smp_start_passkey_verification(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { * Function smp_process_secure_connection_oob_data * Description Processes local/peer SC OOB data received from somewhere. ******************************************************************************/ -void smp_process_secure_connection_oob_data(tSMP_CB* p_cb, - tSMP_INT_DATA* /* p_data */) { +void smp_process_secure_connection_oob_data(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) { log::verbose("addr:{}", p_cb->pairing_bda); tSMP_SC_OOB_DATA* p_sc_oob_data = &p_cb->sc_oob_data; @@ -1989,8 +1964,7 @@ void smp_process_secure_connection_oob_data(tSMP_CB* p_cb, if (p_cb->peer_oob_flag != SMP_OOB_PRESENT) { /* the peer doesn't have local randomiser */ - log::verbose( - "peer didn't receive local OOB data, set local randomizer to 0"); + log::verbose("peer didn't receive local OOB data, set local randomizer to 0"); p_cb->local_random = {0}; } } @@ -2009,8 +1983,7 @@ void smp_process_secure_connection_oob_data(tSMP_CB* p_cb, void smp_set_local_oob_keys(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) { log::verbose("addr:{}", p_cb->pairing_bda); - memcpy(p_cb->sc_oob_data.loc_oob_data.private_key_used, p_cb->private_key, - BT_OCTET32_LEN); + memcpy(p_cb->sc_oob_data.loc_oob_data.private_key_used, p_cb->private_key, BT_OCTET32_LEN); p_cb->sc_oob_data.loc_oob_data.publ_key_used = p_cb->loc_publ_key; smp_start_nonce_generation(p_cb); } @@ -2021,15 +1994,14 @@ void smp_set_local_oob_keys(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) { * sc_oob_data.loc_oob_data, passes sc_oob_data.loc_oob_data up * for safekeeping. ******************************************************************************/ -void smp_set_local_oob_random_commitment(tSMP_CB* p_cb, - tSMP_INT_DATA* /* p_data */) { +void smp_set_local_oob_random_commitment(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) { log::verbose("{}", p_cb->pairing_bda); p_cb->sc_oob_data.loc_oob_data.randomizer = p_cb->rand; p_cb->sc_oob_data.loc_oob_data.commitment = - crypto_toolbox::f4(p_cb->sc_oob_data.loc_oob_data.publ_key_used.x, - p_cb->sc_oob_data.loc_oob_data.publ_key_used.x, - p_cb->sc_oob_data.loc_oob_data.randomizer, 0); + crypto_toolbox::f4(p_cb->sc_oob_data.loc_oob_data.publ_key_used.x, + p_cb->sc_oob_data.loc_oob_data.publ_key_used.x, + p_cb->sc_oob_data.loc_oob_data.randomizer, 0); p_cb->sc_oob_data.loc_oob_data.present = true; @@ -2075,15 +2047,14 @@ void smp_link_encrypted(const RawAddress& bda, uint8_t encr_enable) { } tSMP_INT_DATA smp_int_data = { - // TODO This is not a tSMP_STATUS - .status = static_cast(encr_enable), + // TODO This is not a tSMP_STATUS + .status = static_cast(encr_enable), }; smp_sm_event(&smp_cb, SMP_ENCRYPTED_EVT, &smp_int_data); } else { - log::warn( - "SMP state machine busy so skipping encryption enable:{} device:{}", - encr_enable, bda); + log::warn("SMP state machine busy so skipping encryption enable:{} device:{}", encr_enable, + bda); } } @@ -2172,8 +2143,7 @@ void smp_set_derive_link_key(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) { * Returns void * ******************************************************************************/ -void smp_derive_link_key_from_long_term_key(tSMP_CB* p_cb, - tSMP_INT_DATA* /* p_data */) { +void smp_derive_link_key_from_long_term_key(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) { tSMP_STATUS status = SMP_PAIR_FAIL_UNKNOWN; log::verbose("addr:{}", p_cb->pairing_bda); @@ -2228,8 +2198,7 @@ void smp_br_process_link_key(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) { * Description depending on the transport used at the moment calls either * smp_key_distribution(...) or smp_br_key_distribution(...). ******************************************************************************/ -static void smp_key_distribution_by_transport(tSMP_CB* p_cb, - tSMP_INT_DATA* /* p_data */) { +static void smp_key_distribution_by_transport(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) { log::verbose("addr:{}", p_cb->pairing_bda); if (p_cb->smp_over_br) { smp_br_select_next_key(p_cb, NULL); diff --git a/system/stack/smp/smp_api.cc b/system/stack/smp/smp_api.cc index c1fe32344ea..2344a4f513d 100644 --- a/system/stack/smp/smp_api.cc +++ b/system/stack/smp/smp_api.cc @@ -67,7 +67,7 @@ bool SMP_Register(tSMP_CALLBACK* p_cback) { } smp_cb.p_callback = p_cback; - return (true); + return true; } /******************************************************************************* @@ -85,11 +85,11 @@ bool SMP_Register(tSMP_CALLBACK* p_cback) { tSMP_STATUS SMP_Pair(const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type) { tSMP_CB* p_cb = &smp_cb; - log::verbose("state={} br_state={} flag=0x{:x}, bd_addr={}", p_cb->state, - p_cb->br_state, p_cb->flags, bd_addr); + log::verbose("state={} br_state={} flag=0x{:x}, bd_addr={}", p_cb->state, p_cb->br_state, + p_cb->flags, bd_addr); - if (p_cb->state != SMP_STATE_IDLE || - p_cb->flags & SMP_PAIR_FLAGS_WE_STARTED_DD || p_cb->smp_over_br) { + if (p_cb->state != SMP_STATE_IDLE || p_cb->flags & SMP_PAIR_FLAGS_WE_STARTED_DD || + p_cb->smp_over_br) { /* pending security on going, reject this one */ return SMP_BUSY; } else { @@ -97,8 +97,8 @@ tSMP_STATUS SMP_Pair(const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type) { p_cb->pairing_bda = bd_addr; p_cb->pairing_ble_bd_addr = { - .type = addr_type, - .bda = bd_addr, + .type = addr_type, + .bda = bd_addr, }; if (!L2CA_ConnectFixedChnl(L2CAP_SMP_CID, bd_addr)) { tSMP_INT_DATA smp_int_data; @@ -113,9 +113,7 @@ tSMP_STATUS SMP_Pair(const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type) { } } -tSMP_STATUS SMP_Pair(const RawAddress& bd_addr) { - return SMP_Pair(bd_addr, BLE_ADDR_PUBLIC); -} +tSMP_STATUS SMP_Pair(const RawAddress& bd_addr) { return SMP_Pair(bd_addr, BLE_ADDR_PUBLIC); } /******************************************************************************* * @@ -133,8 +131,8 @@ tSMP_STATUS SMP_Pair(const RawAddress& bd_addr) { tSMP_STATUS SMP_BR_PairWith(const RawAddress& bd_addr) { tSMP_CB* p_cb = &smp_cb; - log::verbose("state={} br_state={} flag=0x{:x}, bd_addr={}", p_cb->state, - p_cb->br_state, p_cb->flags, bd_addr); + log::verbose("state={} br_state={} flag=0x{:x}, bd_addr={}", p_cb->state, p_cb->br_state, + p_cb->flags, bd_addr); if (p_cb->state != SMP_STATE_IDLE || p_cb->smp_over_br || p_cb->flags & SMP_PAIR_FLAGS_WE_STARTED_DD) { @@ -239,8 +237,8 @@ void SMP_SecurityGrant(const RawAddress& bd_addr, tSMP_STATUS res) { } if (smp_cb.smp_over_br) { - if (smp_cb.br_state != SMP_BR_STATE_WAIT_APP_RSP || - smp_cb.cb_evt != SMP_SEC_REQUEST_EVT || smp_cb.pairing_bda != bd_addr) { + if (smp_cb.br_state != SMP_BR_STATE_WAIT_APP_RSP || smp_cb.cb_evt != SMP_SEC_REQUEST_EVT || + smp_cb.pairing_bda != bd_addr) { return; } @@ -249,14 +247,14 @@ void SMP_SecurityGrant(const RawAddress& bd_addr, tSMP_STATUS res) { smp_cb.cb_evt = SMP_EVT_NONE; tSMP_INT_DATA smp_int_data; smp_int_data.status = res; - smp_br_state_machine_event(&smp_cb, SMP_BR_API_SEC_GRANT_EVT, - &smp_int_data); + smp_br_state_machine_event(&smp_cb, SMP_BR_API_SEC_GRANT_EVT, &smp_int_data); return; } - if (smp_cb.state != SMP_STATE_WAIT_APP_RSP || - smp_cb.cb_evt != SMP_SEC_REQUEST_EVT || smp_cb.pairing_bda != bd_addr) + if (smp_cb.state != SMP_STATE_WAIT_APP_RSP || smp_cb.cb_evt != SMP_SEC_REQUEST_EVT || + smp_cb.pairing_bda != bd_addr) { return; + } /* clear the SMP_SEC_REQUEST_EVT event after get grant */ /* avoid generate duplicate pair request */ smp_cb.cb_evt = SMP_EVT_NONE; @@ -280,8 +278,7 @@ void SMP_SecurityGrant(const RawAddress& bd_addr, tSMP_STATUS res) { * BTM_MAX_PASSKEY_VAL(999999(0xF423F)). * ******************************************************************************/ -void SMP_PasskeyReply(const RawAddress& bd_addr, uint8_t res, - uint32_t passkey) { +void SMP_PasskeyReply(const RawAddress& bd_addr, uint8_t res, uint32_t passkey) { tSMP_CB* p_cb = &smp_cb; log::verbose("Key:{} Result:{}", passkey, res); @@ -303,8 +300,7 @@ void SMP_PasskeyReply(const RawAddress& bd_addr, uint8_t res, tSMP_INT_DATA smp_int_data; smp_int_data.status = SMP_PASSKEY_ENTRY_FAIL; smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data); - } else if (p_cb->selected_association_model == - SMP_MODEL_SEC_CONN_PASSKEY_ENT) { + } else if (p_cb->selected_association_model == SMP_MODEL_SEC_CONN_PASSKEY_ENT) { tSMP_INT_DATA smp_int_data; smp_int_data.passkey = passkey; smp_sm_event(&smp_cb, SMP_SC_KEY_READY_EVT, &smp_int_data); @@ -364,23 +360,26 @@ void SMP_ConfirmReply(const RawAddress& bd_addr, uint8_t res) { * p_data - simple pairing Randomizer C. * ******************************************************************************/ -void SMP_OobDataReply(const RawAddress& /* bd_addr */, tSMP_STATUS res, - uint8_t len, uint8_t* p_data) { +void SMP_OobDataReply(const RawAddress& /* bd_addr */, tSMP_STATUS res, uint8_t len, + uint8_t* p_data) { tSMP_CB* p_cb = &smp_cb; tSMP_KEY key; log::verbose("State:{} res:{}", smp_cb.state, res); /* If timeout already expired or has been canceled, ignore the reply */ - if (p_cb->state != SMP_STATE_WAIT_APP_RSP || p_cb->cb_evt != SMP_OOB_REQ_EVT) + if (p_cb->state != SMP_STATE_WAIT_APP_RSP || p_cb->cb_evt != SMP_OOB_REQ_EVT) { return; + } if (res != SMP_SUCCESS || len == 0 || !p_data) { tSMP_INT_DATA smp_int_data; smp_int_data.status = SMP_OOB_FAIL; smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data); } else { - if (len > OCTET16_LEN) len = OCTET16_LEN; + if (len > OCTET16_LEN) { + len = OCTET16_LEN; + } memcpy(p_cb->tk.data(), p_data, len); @@ -415,22 +414,24 @@ void SMP_SecureConnectionOobDataReply(uint8_t* p_data) { return; } - log::verbose( - "req_oob_type:{}, loc_oob_data.present:{}, peer_oob_data.present:{}", - p_cb->req_oob_type, p_oob->loc_oob_data.present, - p_oob->peer_oob_data.present); + log::verbose("req_oob_type:{}, loc_oob_data.present:{}, peer_oob_data.present:{}", + p_cb->req_oob_type, p_oob->loc_oob_data.present, p_oob->peer_oob_data.present); - if (p_cb->state != SMP_STATE_WAIT_APP_RSP || - p_cb->cb_evt != SMP_SC_OOB_REQ_EVT) + if (p_cb->state != SMP_STATE_WAIT_APP_RSP || p_cb->cb_evt != SMP_SC_OOB_REQ_EVT) { return; + } bool data_missing = false; switch (p_cb->req_oob_type) { case SMP_OOB_PEER: - if (!p_oob->peer_oob_data.present) data_missing = true; + if (!p_oob->peer_oob_data.present) { + data_missing = true; + } break; case SMP_OOB_LOCAL: - if (!p_oob->loc_oob_data.present) data_missing = true; + if (!p_oob->loc_oob_data.present) { + data_missing = true; + } break; case SMP_OOB_BOTH: // Check for previous local OOB data in cache @@ -439,8 +440,9 @@ void SMP_SecureConnectionOobDataReply(uint8_t* p_data) { // [NOTICE]: Overridding data present here if the data exists so state // machine asks for it later p_oob->loc_oob_data.present = smp_has_local_oob_data(); - if (!p_oob->loc_oob_data.present || !p_oob->peer_oob_data.present) + if (!p_oob->loc_oob_data.present || !p_oob->peer_oob_data.present) { data_missing = true; + } break; default: log::verbose("Unexpected OOB data type requested. Fail OOB"); @@ -510,8 +512,7 @@ void SMP_SirkConfirmDeviceReply(const RawAddress& bd_addr, uint8_t res) { } if (bd_addr != p_cb->pairing_bda) { - log::warn("Wrong confirmation BD Addr: {} vs expected {}", bd_addr, - p_cb->pairing_bda); + log::warn("Wrong confirmation BD Addr: {} vs expected {}", bd_addr, p_cb->pairing_bda); return; } diff --git a/system/stack/smp/smp_br_main.cc b/system/stack/smp/smp_br_main.cc index 387ebef09a7..12ee3740112 100644 --- a/system/stack/smp/smp_br_main.cc +++ b/system/stack/smp/smp_br_main.cc @@ -27,24 +27,23 @@ using namespace bluetooth; const char* const smp_br_state_name[SMP_BR_STATE_MAX + 1] = { - "SMP_BR_STATE_IDLE", "SMP_BR_STATE_WAIT_APP_RSP", - "SMP_BR_STATE_PAIR_REQ_RSP", "SMP_BR_STATE_BOND_PENDING", - "SMP_BR_STATE_OUT_OF_RANGE"}; + "SMP_BR_STATE_IDLE", "SMP_BR_STATE_WAIT_APP_RSP", "SMP_BR_STATE_PAIR_REQ_RSP", + "SMP_BR_STATE_BOND_PENDING", "SMP_BR_STATE_OUT_OF_RANGE"}; const char* const smp_br_event_name[SMP_BR_MAX_EVT] = { - "BR_PAIRING_REQ_EVT", "BR_PAIRING_RSP_EVT", - "BR_CONFIRM_EVT", "BR_RAND_EVT", - "BR_PAIRING_FAILED_EVT", "BR_ENCRPTION_INFO_EVT", - "BR_CENTRAL_ID_EVT", "BR_ID_INFO_EVT", - "BR_ID_ADDR_EVT", "BR_SIGN_INFO_EVT", - "BR_SECURITY_REQ_EVT", "BR_PAIR_PUBLIC_KEY_EVT", - "BR_PAIR_DHKEY_CHCK_EVT", "BR_PAIR_KEYPR_NOTIF_EVT", - "BR_KEY_READY_EVT", "BR_ENCRYPTED_EVT", - "BR_L2CAP_CONN_EVT", "BR_L2CAP_DISCONN_EVT", - "BR_KEYS_RSP_EVT", "BR_API_SEC_GRANT_EVT", - "BR_TK_REQ_EVT", "BR_AUTH_CMPL_EVT", - "BR_ENC_REQ_EVT", "BR_BOND_REQ_EVT", - "BR_DISCARD_SEC_REQ_EVT", "BR_OUT_OF_RANGE_EVT"}; + "BR_PAIRING_REQ_EVT", "BR_PAIRING_RSP_EVT", + "BR_CONFIRM_EVT", "BR_RAND_EVT", + "BR_PAIRING_FAILED_EVT", "BR_ENCRPTION_INFO_EVT", + "BR_CENTRAL_ID_EVT", "BR_ID_INFO_EVT", + "BR_ID_ADDR_EVT", "BR_SIGN_INFO_EVT", + "BR_SECURITY_REQ_EVT", "BR_PAIR_PUBLIC_KEY_EVT", + "BR_PAIR_DHKEY_CHCK_EVT", "BR_PAIR_KEYPR_NOTIF_EVT", + "BR_KEY_READY_EVT", "BR_ENCRYPTED_EVT", + "BR_L2CAP_CONN_EVT", "BR_L2CAP_DISCONN_EVT", + "BR_KEYS_RSP_EVT", "BR_API_SEC_GRANT_EVT", + "BR_TK_REQ_EVT", "BR_AUTH_CMPL_EVT", + "BR_ENC_REQ_EVT", "BR_BOND_REQ_EVT", + "BR_DISCARD_SEC_REQ_EVT", "BR_OUT_OF_RANGE_EVT"}; const char* smp_get_br_event_name(tSMP_BR_EVENT event); const char* smp_get_br_state_name(tSMP_BR_STATE state); @@ -77,143 +76,136 @@ enum { }; static const tSMP_ACT smp_br_sm_action[] = { - smp_send_pair_req, /* SMP_SEND_PAIR_REQ */ - smp_br_send_pair_response, /* SMP_BR_SEND_PAIR_RSP */ - smp_send_pair_fail, /* SMP_SEND_PAIR_FAIL */ - smp_send_id_info, /* SMP_SEND_ID_INFO */ - smp_br_process_pairing_command, /* SMP_BR_PROC_PAIR_CMD */ - smp_proc_pair_fail, /* SMP_PROC_PAIR_FAIL */ - smp_proc_id_info, /* SMP_PROC_ID_INFO */ - smp_proc_id_addr, /* SMP_PROC_ID_ADDR */ - smp_proc_srk_info, /* SMP_PROC_SRK_INFO */ - smp_br_process_security_grant, /* SMP_BR_PROC_SEC_GRANT */ - smp_br_process_peripheral_keys_response, /* SMP_BR_PROC_SL_KEYS_RSP */ - smp_br_select_next_key, /* SMP_BR_KEY_DISTRIBUTION */ - smp_br_pairing_complete, /* SMP_BR_PAIRING_COMPLETE */ - smp_send_app_cback, /* SMP_SEND_APP_CBACK */ - smp_br_check_authorization_request, /* SMP_BR_CHECK_AUTH_REQ */ - smp_pair_terminate, /* SMP_PAIR_TERMINATE */ - smp_idle_terminate /* SMP_IDLE_TERMINATE */ + smp_send_pair_req, /* SMP_SEND_PAIR_REQ */ + smp_br_send_pair_response, /* SMP_BR_SEND_PAIR_RSP */ + smp_send_pair_fail, /* SMP_SEND_PAIR_FAIL */ + smp_send_id_info, /* SMP_SEND_ID_INFO */ + smp_br_process_pairing_command, /* SMP_BR_PROC_PAIR_CMD */ + smp_proc_pair_fail, /* SMP_PROC_PAIR_FAIL */ + smp_proc_id_info, /* SMP_PROC_ID_INFO */ + smp_proc_id_addr, /* SMP_PROC_ID_ADDR */ + smp_proc_srk_info, /* SMP_PROC_SRK_INFO */ + smp_br_process_security_grant, /* SMP_BR_PROC_SEC_GRANT */ + smp_br_process_peripheral_keys_response, /* SMP_BR_PROC_SL_KEYS_RSP */ + smp_br_select_next_key, /* SMP_BR_KEY_DISTRIBUTION */ + smp_br_pairing_complete, /* SMP_BR_PAIRING_COMPLETE */ + smp_send_app_cback, /* SMP_SEND_APP_CBACK */ + smp_br_check_authorization_request, /* SMP_BR_CHECK_AUTH_REQ */ + smp_pair_terminate, /* SMP_PAIR_TERMINATE */ + smp_idle_terminate /* SMP_IDLE_TERMINATE */ }; static const uint8_t smp_br_all_table[][SMP_BR_SM_NUM_COLS] = { - /* Event Action Next State */ - /* BR_PAIRING_FAILED */ - {SMP_PROC_PAIR_FAIL, SMP_BR_PAIRING_COMPLETE, SMP_BR_STATE_IDLE}, - /* BR_AUTH_CMPL */ - {SMP_SEND_PAIR_FAIL, SMP_BR_PAIRING_COMPLETE, SMP_BR_STATE_IDLE}, - /* BR_L2CAP_DISCONN */ - {SMP_PAIR_TERMINATE, SMP_BR_SM_NO_ACTION, SMP_BR_STATE_IDLE}}; + /* Event Action Next State */ + /* BR_PAIRING_FAILED */ + {SMP_PROC_PAIR_FAIL, SMP_BR_PAIRING_COMPLETE, SMP_BR_STATE_IDLE}, + /* BR_AUTH_CMPL */ + {SMP_SEND_PAIR_FAIL, SMP_BR_PAIRING_COMPLETE, SMP_BR_STATE_IDLE}, + /* BR_L2CAP_DISCONN */ + {SMP_PAIR_TERMINATE, SMP_BR_SM_NO_ACTION, SMP_BR_STATE_IDLE}}; /************ SMP Central FSM State/Event Indirection Table **************/ static const uint8_t smp_br_central_entry_map[][SMP_BR_STATE_MAX] = { - /* br_state name: Idle WaitApp Pair Bond - Rsp ReqRsp Pend */ - /* BR_PAIRING_REQ */ {0, 0, 0, 0}, - /* BR_PAIRING_RSP */ {0, 0, 1, 0}, - /* BR_CONFIRM */ {0, 0, 0, 0}, - /* BR_RAND */ {0, 0, 0, 0}, - /* BR_PAIRING_FAILED */ {0, 0x81, 0x81, 0}, - /* BR_ENCRPTION_INFO */ {0, 0, 0, 0}, - /* BR_CENTRAL_ID */ {0, 0, 0, 0}, - /* BR_ID_INFO */ {0, 0, 0, 1}, - /* BR_ID_ADDR */ {0, 0, 0, 2}, - /* BR_SIGN_INFO */ {0, 0, 0, 3}, - /* BR_SECURITY_REQ */ {0, 0, 0, 0}, - /* BR_PAIR_PUBLIC_KEY_EVT */ {0, 0, 0, 0}, - /* BR_PAIR_DHKEY_CHCK_EVT */ {0, 0, 0, 0}, - /* BR_PAIR_KEYPR_NOTIF_EVT */ {0, 0, 0, 0}, - /* BR_KEY_READY */ {0, 0, 0, 0}, - /* BR_ENCRYPTED */ {0, 0, 0, 0}, - /* BR_L2CAP_CONN */ {1, 0, 0, 0}, - /* BR_L2CAP_DISCONN */ {2, 0x83, 0x83, 0x83}, - /* BR_KEYS_RSP */ {0, 1, 0, 0}, - /* BR_API_SEC_GRANT */ {0, 0, 0, 0}, - /* BR_TK_REQ */ {0, 0, 0, 0}, - /* BR_AUTH_CMPL */ {0, 0x82, 0x82, 0x82}, - /* BR_ENC_REQ */ {0, 0, 0, 0}, - /* BR_BOND_REQ */ {0, 0, 2, 0}, - /* BR_DISCARD_SEC_REQ */ {0, 0, 0, 0}}; + /* br_state name: Idle WaitApp Pair Bond + Rsp ReqRsp Pend */ + /* BR_PAIRING_REQ */ {0, 0, 0, 0}, + /* BR_PAIRING_RSP */ {0, 0, 1, 0}, + /* BR_CONFIRM */ {0, 0, 0, 0}, + /* BR_RAND */ {0, 0, 0, 0}, + /* BR_PAIRING_FAILED */ {0, 0x81, 0x81, 0}, + /* BR_ENCRPTION_INFO */ {0, 0, 0, 0}, + /* BR_CENTRAL_ID */ {0, 0, 0, 0}, + /* BR_ID_INFO */ {0, 0, 0, 1}, + /* BR_ID_ADDR */ {0, 0, 0, 2}, + /* BR_SIGN_INFO */ {0, 0, 0, 3}, + /* BR_SECURITY_REQ */ {0, 0, 0, 0}, + /* BR_PAIR_PUBLIC_KEY_EVT */ {0, 0, 0, 0}, + /* BR_PAIR_DHKEY_CHCK_EVT */ {0, 0, 0, 0}, + /* BR_PAIR_KEYPR_NOTIF_EVT */ {0, 0, 0, 0}, + /* BR_KEY_READY */ {0, 0, 0, 0}, + /* BR_ENCRYPTED */ {0, 0, 0, 0}, + /* BR_L2CAP_CONN */ {1, 0, 0, 0}, + /* BR_L2CAP_DISCONN */ {2, 0x83, 0x83, 0x83}, + /* BR_KEYS_RSP */ {0, 1, 0, 0}, + /* BR_API_SEC_GRANT */ {0, 0, 0, 0}, + /* BR_TK_REQ */ {0, 0, 0, 0}, + /* BR_AUTH_CMPL */ {0, 0x82, 0x82, 0x82}, + /* BR_ENC_REQ */ {0, 0, 0, 0}, + /* BR_BOND_REQ */ {0, 0, 2, 0}, + /* BR_DISCARD_SEC_REQ */ {0, 0, 0, 0}}; static const uint8_t smp_br_central_idle_table[][SMP_BR_SM_NUM_COLS] = { - /* Event Action Next State */ - /* BR_L2CAP_CONN */ - {SMP_SEND_APP_CBACK, SMP_BR_SM_NO_ACTION, SMP_BR_STATE_WAIT_APP_RSP}, - /* BR_L2CAP_DISCONN */ - {SMP_IDLE_TERMINATE, SMP_BR_SM_NO_ACTION, SMP_BR_STATE_IDLE}}; - -static const uint8_t - smp_br_central_wait_appln_response_table[][SMP_BR_SM_NUM_COLS] = { + /* Event Action Next State */ + /* BR_L2CAP_CONN */ + {SMP_SEND_APP_CBACK, SMP_BR_SM_NO_ACTION, SMP_BR_STATE_WAIT_APP_RSP}, + /* BR_L2CAP_DISCONN */ + {SMP_IDLE_TERMINATE, SMP_BR_SM_NO_ACTION, SMP_BR_STATE_IDLE}}; + +static const uint8_t smp_br_central_wait_appln_response_table[][SMP_BR_SM_NUM_COLS] = { /* Event Action Next State */ /* BR_KEYS_RSP */ {SMP_SEND_PAIR_REQ, SMP_BR_SM_NO_ACTION, SMP_BR_STATE_PAIR_REQ_RSP}}; -static const uint8_t - smp_br_central_pair_request_response_table[][SMP_BR_SM_NUM_COLS] = { +static const uint8_t smp_br_central_pair_request_response_table[][SMP_BR_SM_NUM_COLS] = { /* Event Action Next State */ /* BR_PAIRING_RSP */ - {SMP_BR_PROC_PAIR_CMD, SMP_BR_CHECK_AUTH_REQ, - SMP_BR_STATE_PAIR_REQ_RSP}, + {SMP_BR_PROC_PAIR_CMD, SMP_BR_CHECK_AUTH_REQ, SMP_BR_STATE_PAIR_REQ_RSP}, /* BR_BOND_REQ */ {SMP_BR_SM_NO_ACTION, SMP_BR_SM_NO_ACTION, SMP_BR_STATE_BOND_PENDING}}; static const uint8_t smp_br_central_bond_pending_table[][SMP_BR_SM_NUM_COLS] = { - /* Event Action Next State */ - /* BR_ID_INFO */ - {SMP_PROC_ID_INFO, SMP_BR_SM_NO_ACTION, SMP_BR_STATE_BOND_PENDING}, - /* BR_ID_ADDR */ - {SMP_PROC_ID_ADDR, SMP_BR_SM_NO_ACTION, SMP_BR_STATE_BOND_PENDING}, - /* BR_SIGN_INFO */ - {SMP_PROC_SRK_INFO, SMP_BR_SM_NO_ACTION, SMP_BR_STATE_BOND_PENDING}}; + /* Event Action Next State */ + /* BR_ID_INFO */ + {SMP_PROC_ID_INFO, SMP_BR_SM_NO_ACTION, SMP_BR_STATE_BOND_PENDING}, + /* BR_ID_ADDR */ + {SMP_PROC_ID_ADDR, SMP_BR_SM_NO_ACTION, SMP_BR_STATE_BOND_PENDING}, + /* BR_SIGN_INFO */ + {SMP_PROC_SRK_INFO, SMP_BR_SM_NO_ACTION, SMP_BR_STATE_BOND_PENDING}}; static const uint8_t smp_br_peripheral_entry_map[][SMP_BR_STATE_MAX] = { - /* br_state name: Idle WaitApp Pair Bond - Rsp ReqRsp Pend */ - /* BR_PAIRING_REQ */ {1, 0, 0, 0}, - /* BR_PAIRING_RSP */ {0, 0, 0, 0}, - /* BR_CONFIRM */ {0, 0, 0, 0}, - /* BR_RAND */ {0, 0, 0, 0}, - /* BR_PAIRING_FAILED */ {0, 0x81, 0x81, 0x81}, - /* BR_ENCRPTION_INFO */ {0, 0, 0, 0}, - /* BR_CENTRAL_ID */ {0, 0, 0, 0}, - /* BR_ID_INFO */ {0, 0, 0, 1}, - /* BR_ID_ADDR */ {0, 0, 0, 2}, - /* BR_SIGN_INFO */ {0, 0, 0, 3}, - /* BR_SECURITY_REQ */ {0, 0, 0, 0}, - /* BR_PAIR_PUBLIC_KEY_EVT */ {0, 0, 0, 0}, - /* BR_PAIR_DHKEY_CHCK_EVT */ {0, 0, 0, 0}, - /* BR_PAIR_KEYPR_NOTIF_EVT */ {0, 0, 0, 0}, - /* BR_KEY_READY */ {0, 0, 0, 0}, - /* BR_ENCRYPTED */ {0, 0, 0, 0}, - /* BR_L2CAP_CONN */ {0, 0, 0, 0}, - /* BR_L2CAP_DISCONN */ {0, 0x83, 0x83, 0x83}, - /* BR_KEYS_RSP */ {0, 2, 0, 0}, - /* BR_API_SEC_GRANT */ {0, 1, 0, 0}, - /* BR_TK_REQ */ {0, 0, 0, 0}, - /* BR_AUTH_CMPL */ {0, 0x82, 0x82, 0x82}, - /* BR_ENC_REQ */ {0, 0, 0, 0}, - /* BR_BOND_REQ */ {0, 3, 0, 0}, - /* BR_DISCARD_SEC_REQ */ {0, 0, 0, 0}}; + /* br_state name: Idle WaitApp Pair Bond + Rsp ReqRsp Pend */ + /* BR_PAIRING_REQ */ {1, 0, 0, 0}, + /* BR_PAIRING_RSP */ {0, 0, 0, 0}, + /* BR_CONFIRM */ {0, 0, 0, 0}, + /* BR_RAND */ {0, 0, 0, 0}, + /* BR_PAIRING_FAILED */ {0, 0x81, 0x81, 0x81}, + /* BR_ENCRPTION_INFO */ {0, 0, 0, 0}, + /* BR_CENTRAL_ID */ {0, 0, 0, 0}, + /* BR_ID_INFO */ {0, 0, 0, 1}, + /* BR_ID_ADDR */ {0, 0, 0, 2}, + /* BR_SIGN_INFO */ {0, 0, 0, 3}, + /* BR_SECURITY_REQ */ {0, 0, 0, 0}, + /* BR_PAIR_PUBLIC_KEY_EVT */ {0, 0, 0, 0}, + /* BR_PAIR_DHKEY_CHCK_EVT */ {0, 0, 0, 0}, + /* BR_PAIR_KEYPR_NOTIF_EVT */ {0, 0, 0, 0}, + /* BR_KEY_READY */ {0, 0, 0, 0}, + /* BR_ENCRYPTED */ {0, 0, 0, 0}, + /* BR_L2CAP_CONN */ {0, 0, 0, 0}, + /* BR_L2CAP_DISCONN */ {0, 0x83, 0x83, 0x83}, + /* BR_KEYS_RSP */ {0, 2, 0, 0}, + /* BR_API_SEC_GRANT */ {0, 1, 0, 0}, + /* BR_TK_REQ */ {0, 0, 0, 0}, + /* BR_AUTH_CMPL */ {0, 0x82, 0x82, 0x82}, + /* BR_ENC_REQ */ {0, 0, 0, 0}, + /* BR_BOND_REQ */ {0, 3, 0, 0}, + /* BR_DISCARD_SEC_REQ */ {0, 0, 0, 0}}; static const uint8_t smp_br_peripheral_idle_table[][SMP_BR_SM_NUM_COLS] = { - /* Event Action Next State */ - /* BR_PAIRING_REQ */ - {SMP_BR_PROC_PAIR_CMD, SMP_SEND_APP_CBACK, SMP_BR_STATE_WAIT_APP_RSP}}; + /* Event Action Next State */ + /* BR_PAIRING_REQ */ + {SMP_BR_PROC_PAIR_CMD, SMP_SEND_APP_CBACK, SMP_BR_STATE_WAIT_APP_RSP}}; -static const uint8_t - smp_br_peripheral_wait_appln_response_table[][SMP_BR_SM_NUM_COLS] = { +static const uint8_t smp_br_peripheral_wait_appln_response_table[][SMP_BR_SM_NUM_COLS] = { /* Event Action Next State */ /* BR_API_SEC_GRANT */ {SMP_BR_PROC_SEC_GRANT, SMP_SEND_APP_CBACK, SMP_BR_STATE_WAIT_APP_RSP}, /* BR_KEYS_RSP */ - {SMP_BR_PROC_SL_KEYS_RSP, SMP_BR_CHECK_AUTH_REQ, - SMP_BR_STATE_WAIT_APP_RSP}, + {SMP_BR_PROC_SL_KEYS_RSP, SMP_BR_CHECK_AUTH_REQ, SMP_BR_STATE_WAIT_APP_RSP}, /* BR_BOND_REQ */ - {SMP_BR_KEY_DISTRIBUTION, SMP_BR_SM_NO_ACTION, - SMP_BR_STATE_BOND_PENDING}}; + {SMP_BR_KEY_DISTRIBUTION, SMP_BR_SM_NO_ACTION, SMP_BR_STATE_BOND_PENDING}}; -static const uint8_t - smp_br_peripheral_bond_pending_table[][SMP_BR_SM_NUM_COLS] = { +static const uint8_t smp_br_peripheral_bond_pending_table[][SMP_BR_SM_NUM_COLS] = { /* Event Action Next State */ /* BR_ID_INFO */ {SMP_PROC_ID_INFO, SMP_BR_SM_NO_ACTION, SMP_BR_STATE_BOND_PENDING}, @@ -223,24 +215,23 @@ static const uint8_t {SMP_PROC_SRK_INFO, SMP_BR_SM_NO_ACTION, SMP_BR_STATE_BOND_PENDING}}; static const tSMP_BR_SM_TBL smp_br_state_table[][2] = { - /* SMP_BR_STATE_IDLE */ - {smp_br_central_idle_table, smp_br_peripheral_idle_table}, + /* SMP_BR_STATE_IDLE */ + {smp_br_central_idle_table, smp_br_peripheral_idle_table}, - /* SMP_BR_STATE_WAIT_APP_RSP */ - {smp_br_central_wait_appln_response_table, - smp_br_peripheral_wait_appln_response_table}, + /* SMP_BR_STATE_WAIT_APP_RSP */ + {smp_br_central_wait_appln_response_table, smp_br_peripheral_wait_appln_response_table}, - /* SMP_BR_STATE_PAIR_REQ_RSP */ - {smp_br_central_pair_request_response_table, NULL}, + /* SMP_BR_STATE_PAIR_REQ_RSP */ + {smp_br_central_pair_request_response_table, NULL}, - /* SMP_BR_STATE_BOND_PENDING */ - {smp_br_central_bond_pending_table, smp_br_peripheral_bond_pending_table}, + /* SMP_BR_STATE_BOND_PENDING */ + {smp_br_central_bond_pending_table, smp_br_peripheral_bond_pending_table}, }; typedef const uint8_t (*tSMP_BR_ENTRY_TBL)[SMP_BR_STATE_MAX]; -static const tSMP_BR_ENTRY_TBL smp_br_entry_table[] = { - smp_br_central_entry_map, smp_br_peripheral_entry_map}; +static const tSMP_BR_ENTRY_TBL smp_br_entry_table[] = {smp_br_central_entry_map, + smp_br_peripheral_entry_map}; #define SMP_BR_ALL_TABLE_MASK 0x80 @@ -250,9 +241,8 @@ static const tSMP_BR_ENTRY_TBL smp_br_entry_table[] = { ******************************************************************************/ void smp_set_br_state(tSMP_BR_STATE br_state) { if (br_state < SMP_BR_STATE_MAX) { - log::verbose("BR_State change:{}({})==>{}({})", - smp_get_br_state_name(smp_cb.br_state), smp_cb.br_state, - smp_get_br_state_name(br_state), br_state); + log::verbose("BR_State change:{}({})==>{}({})", smp_get_br_state_name(smp_cb.br_state), + smp_cb.br_state, smp_get_br_state_name(br_state), br_state); smp_cb.br_state = br_state; } else { log::verbose("invalid br_state={}", br_state); @@ -272,7 +262,9 @@ tSMP_BR_STATE smp_get_br_state(void) { return smp_cb.br_state; } const char* smp_get_br_state_name(tSMP_BR_STATE br_state) { const char* p_str = smp_br_state_name[SMP_BR_STATE_MAX]; - if (br_state < SMP_BR_STATE_MAX) p_str = smp_br_state_name[br_state]; + if (br_state < SMP_BR_STATE_MAX) { + p_str = smp_br_state_name[br_state]; + } return p_str; } @@ -303,8 +295,7 @@ const char* smp_get_br_event_name(tSMP_BR_EVENT event) { * Returns void. * ******************************************************************************/ -void smp_br_state_machine_event(tSMP_CB* p_cb, tSMP_BR_EVENT event, - tSMP_INT_DATA* p_data) { +void smp_br_state_machine_event(tSMP_CB* p_cb, tSMP_BR_EVENT event, tSMP_INT_DATA* p_data) { tSMP_BR_STATE curr_state = p_cb->br_state; tSMP_BR_SM_TBL state_table; uint8_t action, entry; @@ -322,9 +313,9 @@ void smp_br_state_machine_event(tSMP_CB* p_cb, tSMP_BR_EVENT event, tSMP_BR_ENTRY_TBL entry_table = smp_br_entry_table[p_cb->role]; - log::debug("Role:{} State:[{}({})], Event:[{}({})]", - hci_role_text(p_cb->role), smp_get_br_state_name(p_cb->br_state), - p_cb->br_state, smp_get_br_event_name(event), event); + log::debug("Role:{} State:[{}({})], Event:[{}({})]", hci_role_text(p_cb->role), + smp_get_br_state_name(p_cb->br_state), p_cb->br_state, smp_get_br_event_name(event), + event); /* look up the state table for the current state */ /* lookup entry / w event & curr_state */ @@ -339,8 +330,7 @@ void smp_br_state_machine_event(tSMP_CB* p_cb, tSMP_BR_EVENT event, state_table = smp_br_state_table[curr_state][p_cb->role]; } } else { - log::verbose("Ignore event[{}({})] in state[{}({})]", - smp_get_br_event_name(event), event, + log::verbose("Ignore event[{}({})] in state[{}({})]", smp_get_br_event_name(event), event, smp_get_br_state_name(curr_state), curr_state); return; } diff --git a/system/stack/smp/smp_int.h b/system/stack/smp/smp_int.h index 773997922b7..2978212870e 100644 --- a/system/stack/smp/smp_int.h +++ b/system/stack/smp/smp_int.h @@ -257,27 +257,24 @@ typedef union { #define SMP_PAIR_FLAGS_PEER_STARTED_DD (1 << 1) #define SMP_PAIR_FLAGS_CMD_CONFIRM_RCVD (1 << SMP_OPCODE_CONFIRM) /* 1 << 3 */ #define SMP_PAIR_FLAG_ENC_AFTER_PAIR (1 << 4) -#define SMP_PAIR_FLAG_HAVE_PEER_DHK_CHK \ - (1 << 5) /* used on peripheral to resolve race condition */ -#define SMP_PAIR_FLAG_HAVE_PEER_PUBL_KEY \ - (1 << 6) /* used on peripheral to resolve race condition */ -#define SMP_PAIR_FLAG_HAVE_PEER_COMM \ - (1 << 7) /* used to resolve race condition */ +#define SMP_PAIR_FLAG_HAVE_PEER_DHK_CHK (1 << 5) // used on peripheral to resolve race condition +#define SMP_PAIR_FLAG_HAVE_PEER_PUBL_KEY (1 << 6) // used on peripheral to resolve race condition +#define SMP_PAIR_FLAG_HAVE_PEER_COMM (1 << 7) // used to resolve race condition #define SMP_PAIR_FLAG_HAVE_LOCAL_PUBL_KEY \ (1 << 8) /* used on peripheral to resolve race condition */ #define SMP_PAIR_FLAGS_CMD_CONFIRM_SENT (1 << 9) /* check if authentication requirement need MITM protection */ -#define SMP_NO_MITM_REQUIRED(x) (((x)&SMP_AUTH_YN_BIT) == 0) +#define SMP_NO_MITM_REQUIRED(x) (((x) & SMP_AUTH_YN_BIT) == 0) /* SMP control block */ class tSMP_CB { - public: +public: void init(uint8_t security_mode); void reset(); - public: +public: uint8_t init_security_mode{0}; tSMP_CALLBACK* p_callback; alarm_t* smp_rsp_timer_ent; @@ -330,8 +327,7 @@ class tSMP_CB { bool le_sc_kp_notif_is_used; tSMP_SC_KEY_TYPE local_keypress_notification; tSMP_SC_KEY_TYPE peer_keypress_notification; - uint8_t - round; /* authentication stage 1 round for passkey association model */ + uint8_t round; /* authentication stage 1 round for passkey association model */ uint32_t number_to_display; Octet16 mac_key; uint8_t peer_enc_size; @@ -372,8 +368,7 @@ tSMP_STATE smp_get_state(void); void smp_set_state(tSMP_STATE state); /* smp_br_main */ -void smp_br_state_machine_event(tSMP_CB* p_cb, tSMP_BR_EVENT event, - tSMP_INT_DATA* p_data); +void smp_br_state_machine_event(tSMP_CB* p_cb, tSMP_BR_EVENT event, tSMP_INT_DATA* p_data); tSMP_BR_STATE smp_get_br_state(void); void smp_set_br_state(tSMP_BR_STATE state); @@ -427,23 +422,19 @@ void smp_process_peer_nonce(tSMP_CB* p_cb, tSMP_INT_DATA* p_data); void smp_process_dhkey_check(tSMP_CB* p_cb, tSMP_INT_DATA* p_data); void smp_match_dhkey_checks(tSMP_CB* p_cb, tSMP_INT_DATA* p_data); void smp_process_keypress_notification(tSMP_CB* p_cb, tSMP_INT_DATA* p_data); -void smp_move_to_secure_connections_phase2(tSMP_CB* p_cb, - tSMP_INT_DATA* p_data); +void smp_move_to_secure_connections_phase2(tSMP_CB* p_cb, tSMP_INT_DATA* p_data); void smp_phase_2_dhkey_checks_are_present(tSMP_CB* p_cb, tSMP_INT_DATA* p_data); void smp_wait_for_both_public_keys(tSMP_CB* p_cb, tSMP_INT_DATA* p_data); void smp_start_passkey_verification(tSMP_CB* p_cb, tSMP_INT_DATA* p_data); -void smp_process_secure_connection_oob_data(tSMP_CB* p_cb, - tSMP_INT_DATA* p_data); +void smp_process_secure_connection_oob_data(tSMP_CB* p_cb, tSMP_INT_DATA* p_data); void smp_process_secure_connection_long_term_key(void); void smp_set_local_oob_keys(tSMP_CB* p_cb, tSMP_INT_DATA* p_data); void smp_set_local_oob_random_commitment(tSMP_CB* p_cb, tSMP_INT_DATA* p_data); void smp_set_derive_link_key(tSMP_CB* p_cb, tSMP_INT_DATA* p_data); -void smp_derive_link_key_from_long_term_key(tSMP_CB* p_cb, - tSMP_INT_DATA* p_data); +void smp_derive_link_key_from_long_term_key(tSMP_CB* p_cb, tSMP_INT_DATA* p_data); void smp_br_process_pairing_command(tSMP_CB* p_cb, tSMP_INT_DATA* p_data); void smp_br_process_security_grant(tSMP_CB* p_cb, tSMP_INT_DATA* p_data); -void smp_br_process_peripheral_keys_response(tSMP_CB* p_cb, - tSMP_INT_DATA* p_data); +void smp_br_process_peripheral_keys_response(tSMP_CB* p_cb, tSMP_INT_DATA* p_data); void smp_br_send_pair_response(tSMP_CB* p_cb, tSMP_INT_DATA* p_data); void smp_br_check_authorization_request(tSMP_CB* p_cb, tSMP_INT_DATA* p_data); void smp_br_select_next_key(tSMP_CB* p_cb, tSMP_INT_DATA* p_data); @@ -455,8 +446,8 @@ void smp_l2cap_if_init(void); void smp_data_ind(const RawAddress& bd_addr, BT_HDR* p_buf); /* smp_util.cc */ -void smp_log_metrics(const RawAddress& bd_addr, bool is_outgoing, - const uint8_t* p_buf, size_t buf_len, bool is_over_br); +void smp_log_metrics(const RawAddress& bd_addr, bool is_outgoing, const uint8_t* p_buf, + size_t buf_len, bool is_over_br); bool smp_send_cmd(uint8_t cmd_code, tSMP_CB* p_cb); void smp_reset_control_value(tSMP_CB* p_cb); void smp_proc_pairing_cmpl(tSMP_CB* p_cb); @@ -491,8 +482,7 @@ void smp_use_oob_private_key(tSMP_CB* p_cb, tSMP_INT_DATA* p_data); void smp_compute_dhkey(tSMP_CB* p_cb); void smp_calculate_local_commitment(tSMP_CB* p_cb); Octet16 smp_calculate_peer_commitment(tSMP_CB* p_cb); -void smp_calculate_numeric_comparison_display_number(tSMP_CB* p_cb, - tSMP_INT_DATA* p_data); +void smp_calculate_numeric_comparison_display_number(tSMP_CB* p_cb, tSMP_INT_DATA* p_data); void smp_calculate_local_dhkey_check(tSMP_CB* p_cb, tSMP_INT_DATA* p_data); void smp_calculate_peer_dhkey_check(tSMP_CB* p_cb, tSMP_INT_DATA* p_data); void smp_start_nonce_generation(tSMP_CB* p_cb); diff --git a/system/stack/smp/smp_keys.cc b/system/stack/smp/smp_keys.cc index 619ff13f1ca..7369ff0ccc7 100644 --- a/system/stack/smp/smp_keys.cc +++ b/system/stack/smp/smp_keys.cc @@ -79,23 +79,17 @@ static bool is_oob_data_empty(tSMP_LOC_OOB_DATA* data) { return memcmp(data, &empty_data, sizeof(tSMP_LOC_OOB_DATA)) == 0; } -bool smp_has_local_oob_data() { - return !is_oob_data_empty(&saved_local_oob_data); -} +bool smp_has_local_oob_data() { return !is_oob_data_empty(&saved_local_oob_data); } -void smp_debug_print_nbyte_little_endian(uint8_t* /* p */, - const char* /* key_name */, +void smp_debug_print_nbyte_little_endian(uint8_t* /* p */, const char* /* key_name */, uint8_t /* len */) {} -inline void smp_debug_print_nbyte_little_endian(const Octet16& p, - const char* key_name, +inline void smp_debug_print_nbyte_little_endian(const Octet16& p, const char* key_name, uint8_t len) { - smp_debug_print_nbyte_little_endian(const_cast(p.data()), key_name, - len); + smp_debug_print_nbyte_little_endian(const_cast(p.data()), key_name, len); } -void smp_debug_print_nbyte_big_endian(uint8_t* /* p */, - const char* /* key_name */, +void smp_debug_print_nbyte_big_endian(uint8_t* /* p */, const char* /* key_name */, uint8_t /* len */) {} /** This function is called to process a passkey. */ @@ -106,7 +100,9 @@ void smp_proc_passkey(tSMP_CB* p_cb, uint64_t rand) { log::verbose("addr:{}", p_cb->pairing_bda); /* truncate by maximum value */ - while (passkey > BTM_MAX_PASSKEY_VAL) passkey >>= 1; + while (passkey > BTM_MAX_PASSKEY_VAL) { + passkey >>= 1; + } /* save the TK */ p_cb->tk = {0}; @@ -114,10 +110,9 @@ void smp_proc_passkey(tSMP_CB* p_cb, uint64_t rand) { if (p_cb->p_callback) { tSMP_EVT_DATA smp_evt_data = { - .passkey = passkey, + .passkey = passkey, }; - (*p_cb->p_callback)(SMP_PASSKEY_NOTIF_EVT, p_cb->pairing_bda, - &smp_evt_data); + (*p_cb->p_callback)(SMP_PASSKEY_NOTIF_EVT, p_cb->pairing_bda, &smp_evt_data); } if (p_cb->selected_association_model == SMP_MODEL_SEC_CONN_PASSKEY_DISP) { @@ -209,11 +204,11 @@ void smp_generate_csrk(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) { } else { log::verbose("Generate DIV for CSRK"); send_ble_rand(BindOnce( - [](tSMP_CB* p_cb, uint64_t rand) { - uint16_t div = static_cast(rand); - smp_compute_csrk(div, p_cb); - }, - p_cb)); + [](tSMP_CB* p_cb, uint64_t rand) { + uint16_t div = static_cast(rand); + smp_compute_csrk(div, p_cb); + }, + p_cb)); } } @@ -260,8 +255,7 @@ void smp_concatenate_peer(tSMP_CB* p_cb, uint8_t** p_data, uint8_t op_code) { * Fill in values LSB first thus * p1 = iat' || rat' || preq || pres */ -Octet16 smp_gen_p1_4_confirm(tSMP_CB* p_cb, - tBLE_ADDR_TYPE remote_bd_addr_type) { +Octet16 smp_gen_p1_4_confirm(tSMP_CB* p_cb, tBLE_ADDR_TYPE remote_bd_addr_type) { log::verbose("pairing_addr:{}, rmt_addr_type:{}", p_cb->pairing_bda, AddressTypeText(remote_bd_addr_type)); Octet16 p1; @@ -285,8 +279,7 @@ Octet16 smp_gen_p1_4_confirm(tSMP_CB* p_cb, /* pres : Pairing Response (local) command */ smp_concatenate_local(p_cb, &p, SMP_OPCODE_PAIRING_RSP); } - smp_debug_print_nbyte_little_endian(p1, "p1 = iat' || rat' || preq || pres", - 16); + smp_debug_print_nbyte_little_endian(p1, "p1 = iat' || rat' || preq || pres", 16); return p1; } @@ -319,27 +312,24 @@ Octet16 smp_gen_p2_4_confirm(tSMP_CB* p_cb, const RawAddress& remote_bda) { /******************************************************************************* * - * Function smp_calculate_comfirm + * Function smp_calculate_confirm * * Description This function (c1) is called to calculate Confirm value. * * Returns tSMP_STATUS status of confirmation calculation * ******************************************************************************/ -tSMP_STATUS smp_calculate_comfirm(tSMP_CB* p_cb, const Octet16& rand, - Octet16* output) { +tSMP_STATUS smp_calculate_confirm(tSMP_CB* p_cb, const Octet16& rand, Octet16* output) { log::verbose("addr:{}", p_cb->pairing_bda); RawAddress remote_bda; tBLE_ADDR_TYPE remote_bd_addr_type = BLE_ADDR_PUBLIC; /* get remote connection specific bluetooth address */ - if (!BTM_ReadRemoteConnectionAddr(p_cb->pairing_bda, remote_bda, - &remote_bd_addr_type, true)) { + if (!BTM_ReadRemoteConnectionAddr(p_cb->pairing_bda, remote_bda, &remote_bd_addr_type, true)) { log::error("cannot obtain remote device address"); return SMP_PAIR_FAIL_UNKNOWN; } /* get local connection specific bluetooth address */ - BTM_ReadConnectionAddr(p_cb->pairing_bda, p_cb->local_bda, &p_cb->addr_type, - true); + BTM_ReadConnectionAddr(p_cb->pairing_bda, p_cb->local_bda, &p_cb->addr_type, true); /* generate p1 = pres || preq || rat' || iat' */ Octet16 p1 = smp_gen_p1_4_confirm(p_cb, remote_bd_addr_type); /* p1' = rand XOR p1 */ @@ -374,7 +364,7 @@ static void smp_generate_confirm(tSMP_CB* p_cb) { log::verbose("addr:{}", p_cb->pairing_bda); smp_debug_print_nbyte_little_endian(p_cb->rand.data(), "local_rand", 16); Octet16 output; - tSMP_STATUS status = smp_calculate_comfirm(p_cb, p_cb->rand, &output); + tSMP_STATUS status = smp_calculate_confirm(p_cb, p_cb->rand, &output); if (status != SMP_SUCCESS) { tSMP_INT_DATA smp_int_data; smp_int_data.status = status; @@ -383,8 +373,7 @@ static void smp_generate_confirm(tSMP_CB* p_cb) { } tSMP_KEY key; p_cb->confirm = output; - smp_debug_print_nbyte_little_endian(p_cb->confirm, "Local Confirm generated", - 16); + smp_debug_print_nbyte_little_endian(p_cb->confirm, "Local Confirm generated", 16); key.key_type = SMP_KEY_TYPE_CFM; key.p_data = output.data(); tSMP_INT_DATA smp_int_data; @@ -403,23 +392,22 @@ static void smp_generate_confirm(tSMP_CB* p_cb) { * Returns void * ******************************************************************************/ -void smp_generate_srand_mrand_confirm(tSMP_CB* p_cb, - tSMP_INT_DATA* /* p_data */) { +void smp_generate_srand_mrand_confirm(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) { log::verbose("addr:{}", p_cb->pairing_bda); /* generate MRand or SRand */ send_ble_rand(BindOnce( - [](tSMP_CB* p_cb, uint64_t rand) { - memcpy(p_cb->rand.data(), (uint8_t*)&rand, sizeof(uint64_t)); - /* generate 64 MSB of MRand or SRand */ - send_ble_rand(BindOnce( - [](tSMP_CB* p_cb, uint64_t rand) { - memcpy(p_cb->rand.data() + sizeof(uint64_t), (uint8_t*)&rand, - sizeof(uint64_t)); - smp_generate_confirm(p_cb); - }, - p_cb)); - }, - p_cb)); + [](tSMP_CB* p_cb, uint64_t rand) { + memcpy(p_cb->rand.data(), (uint8_t*)&rand, sizeof(uint64_t)); + /* generate 64 MSB of MRand or SRand */ + send_ble_rand(BindOnce( + [](tSMP_CB* p_cb, uint64_t rand) { + memcpy(p_cb->rand.data() + sizeof(uint64_t), (uint8_t*)&rand, + sizeof(uint64_t)); + smp_generate_confirm(p_cb); + }, + p_cb)); + }, + p_cb)); } /******************************************************************************* @@ -438,7 +426,7 @@ void smp_generate_compare(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) { log::verbose("addr:{}", p_cb->pairing_bda); smp_debug_print_nbyte_little_endian(p_cb->rrand, "peer rand", 16); Octet16 output; - tSMP_STATUS status = smp_calculate_comfirm(p_cb, p_cb->rrand, &output); + tSMP_STATUS status = smp_calculate_confirm(p_cb, p_cb->rrand, &output); if (status != SMP_SUCCESS) { tSMP_INT_DATA smp_int_data; smp_int_data.status = status; @@ -446,8 +434,7 @@ void smp_generate_compare(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) { return; } tSMP_KEY key; - smp_debug_print_nbyte_little_endian(output.data(), "Remote Confirm generated", - 16); + smp_debug_print_nbyte_little_endian(output.data(), "Remote Confirm generated", 16); key.key_type = SMP_KEY_TYPE_CMP; key.p_data = output.data(); tSMP_INT_DATA smp_int_data; @@ -563,11 +550,11 @@ void smp_generate_ltk(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) { /* generate MRand or SRand */ send_ble_rand(BindOnce( - [](tSMP_CB* p_cb, uint64_t rand) { - uint16_t div = static_cast(rand); - smp_generate_ltk_cont(div, p_cb); - }, - p_cb)); + [](tSMP_CB* p_cb, uint64_t rand) { + uint16_t div = static_cast(rand); + smp_generate_ltk_cont(div, p_cb); + }, + p_cb)); } } @@ -626,28 +613,27 @@ void smp_create_private_key(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) { } send_ble_rand(BindOnce( - [](tSMP_CB* p_cb, uint64_t rand) { - memcpy(p_cb->private_key, (uint8_t*)&rand, sizeof(uint64_t)); - send_ble_rand(BindOnce( - [](tSMP_CB* p_cb, uint64_t rand) { - memcpy(&p_cb->private_key[8], (uint8_t*)&rand, sizeof(uint64_t)); - send_ble_rand(BindOnce( - [](tSMP_CB* p_cb, uint64_t rand) { - memcpy(&p_cb->private_key[16], (uint8_t*)&rand, - sizeof(uint64_t)); - send_ble_rand(BindOnce( - [](tSMP_CB* p_cb, uint64_t rand) { - memcpy(&p_cb->private_key[24], (uint8_t*)&rand, - sizeof(uint64_t)); - smp_process_private_key(p_cb); - }, - p_cb)); - }, - p_cb)); - }, - p_cb)); - }, - p_cb)); + [](tSMP_CB* p_cb, uint64_t rand) { + memcpy(p_cb->private_key, (uint8_t*)&rand, sizeof(uint64_t)); + send_ble_rand(BindOnce( + [](tSMP_CB* p_cb, uint64_t rand) { + memcpy(&p_cb->private_key[8], (uint8_t*)&rand, sizeof(uint64_t)); + send_ble_rand(BindOnce( + [](tSMP_CB* p_cb, uint64_t rand) { + memcpy(&p_cb->private_key[16], (uint8_t*)&rand, sizeof(uint64_t)); + send_ble_rand(BindOnce( + [](tSMP_CB* p_cb, uint64_t rand) { + memcpy(&p_cb->private_key[24], (uint8_t*)&rand, + sizeof(uint64_t)); + smp_process_private_key(p_cb); + }, + p_cb)); + }, + p_cb)); + }, + p_cb)); + }, + p_cb)); } /******************************************************************************* @@ -696,8 +682,7 @@ void smp_use_oob_private_key(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) { log::info("OOB Association Model with no saved data present"); } - memcpy(p_cb->private_key, p_cb->sc_oob_data.loc_oob_data.private_key_used, - BT_OCTET32_LEN); + memcpy(p_cb->private_key, p_cb->sc_oob_data.loc_oob_data.private_key_used, BT_OCTET32_LEN); smp_process_private_key(p_cb); break; default: @@ -730,12 +715,9 @@ void smp_process_private_key(tSMP_CB* p_cb) { memcpy(p_cb->loc_publ_key.x, public_key.x, BT_OCTET32_LEN); memcpy(p_cb->loc_publ_key.y, public_key.y, BT_OCTET32_LEN); - smp_debug_print_nbyte_little_endian(p_cb->private_key, "private", - BT_OCTET32_LEN); - smp_debug_print_nbyte_little_endian(p_cb->loc_publ_key.x, "local public(x)", - BT_OCTET32_LEN); - smp_debug_print_nbyte_little_endian(p_cb->loc_publ_key.y, "local public(y)", - BT_OCTET32_LEN); + smp_debug_print_nbyte_little_endian(p_cb->private_key, "private", BT_OCTET32_LEN); + smp_debug_print_nbyte_little_endian(p_cb->loc_publ_key.x, "local public(x)", BT_OCTET32_LEN); + smp_debug_print_nbyte_little_endian(p_cb->loc_publ_key.y, "local public(y)", BT_OCTET32_LEN); p_cb->flags |= SMP_PAIR_FLAG_HAVE_LOCAL_PUBL_KEY; smp_sm_event(p_cb, SMP_LOC_PUBL_KEY_CRTD_EVT, NULL); } @@ -768,14 +750,10 @@ void smp_compute_dhkey(tSMP_CB* p_cb) { smp_debug_print_nbyte_little_endian(p_cb->dhkey, "Old DHKey", BT_OCTET32_LEN); - smp_debug_print_nbyte_little_endian(p_cb->private_key, "private", - BT_OCTET32_LEN); - smp_debug_print_nbyte_little_endian(p_cb->peer_publ_key.x, "rem public(x)", - BT_OCTET32_LEN); - smp_debug_print_nbyte_little_endian(p_cb->peer_publ_key.y, "rem public(y)", - BT_OCTET32_LEN); - smp_debug_print_nbyte_little_endian(p_cb->dhkey, "Reverted DHKey", - BT_OCTET32_LEN); + smp_debug_print_nbyte_little_endian(p_cb->private_key, "private", BT_OCTET32_LEN); + smp_debug_print_nbyte_little_endian(p_cb->peer_publ_key.x, "rem public(x)", BT_OCTET32_LEN); + smp_debug_print_nbyte_little_endian(p_cb->peer_publ_key.y, "rem public(y)", BT_OCTET32_LEN); + smp_debug_print_nbyte_little_endian(p_cb->dhkey, "Reverted DHKey", BT_OCTET32_LEN); } /** The function calculates and saves local commmitment in CB. */ @@ -787,30 +765,27 @@ void smp_calculate_local_commitment(tSMP_CB* p_cb) { switch (p_cb->selected_association_model) { case SMP_MODEL_SEC_CONN_JUSTWORKS: case SMP_MODEL_SEC_CONN_NUM_COMP: - if (p_cb->role == HCI_ROLE_CENTRAL) + if (p_cb->role == HCI_ROLE_CENTRAL) { log::warn( - "local commitment calc on central is not expected for Just " - "Works/Numeric Comparison models"); - p_cb->commitment = crypto_toolbox::f4( - p_cb->loc_publ_key.x, p_cb->peer_publ_key.x, p_cb->rand, 0); + "local commitment calc on central is not expected for Just " + "Works/Numeric Comparison models"); + } + p_cb->commitment = + crypto_toolbox::f4(p_cb->loc_publ_key.x, p_cb->peer_publ_key.x, p_cb->rand, 0); break; case SMP_MODEL_SEC_CONN_PASSKEY_ENT: case SMP_MODEL_SEC_CONN_PASSKEY_DISP: - random_input = - smp_calculate_random_input(p_cb->local_random.data(), p_cb->round); - p_cb->commitment = - crypto_toolbox::f4(p_cb->loc_publ_key.x, p_cb->peer_publ_key.x, - p_cb->rand, random_input); + random_input = smp_calculate_random_input(p_cb->local_random.data(), p_cb->round); + p_cb->commitment = crypto_toolbox::f4(p_cb->loc_publ_key.x, p_cb->peer_publ_key.x, p_cb->rand, + random_input); break; case SMP_MODEL_SEC_CONN_OOB: - log::warn( - "local commitment calc is expected for OOB model BEFORE pairing"); - p_cb->commitment = crypto_toolbox::f4( - p_cb->loc_publ_key.x, p_cb->loc_publ_key.x, p_cb->local_random, 0); + log::warn("local commitment calc is expected for OOB model BEFORE pairing"); + p_cb->commitment = + crypto_toolbox::f4(p_cb->loc_publ_key.x, p_cb->loc_publ_key.x, p_cb->local_random, 0); break; default: - log::error("Association Model={} is not used in LE SC", - p_cb->selected_association_model); + log::error("Association Model={} is not used in LE SC", p_cb->selected_association_model); return; } } @@ -824,26 +799,24 @@ Octet16 smp_calculate_peer_commitment(tSMP_CB* p_cb) { switch (p_cb->selected_association_model) { case SMP_MODEL_SEC_CONN_JUSTWORKS: case SMP_MODEL_SEC_CONN_NUM_COMP: - if (p_cb->role == HCI_ROLE_PERIPHERAL) + if (p_cb->role == HCI_ROLE_PERIPHERAL) { log::warn( - "peer commitment calc on peripheral is not expected for Just " - "Works/Numeric Comparison models"); - output = crypto_toolbox::f4(p_cb->peer_publ_key.x, p_cb->loc_publ_key.x, - p_cb->rrand, 0); + "peer commitment calc on peripheral is not expected for Just " + "Works/Numeric Comparison models"); + } + output = crypto_toolbox::f4(p_cb->peer_publ_key.x, p_cb->loc_publ_key.x, p_cb->rrand, 0); break; case SMP_MODEL_SEC_CONN_PASSKEY_ENT: case SMP_MODEL_SEC_CONN_PASSKEY_DISP: ri = smp_calculate_random_input(p_cb->peer_random.data(), p_cb->round); - output = crypto_toolbox::f4(p_cb->peer_publ_key.x, p_cb->loc_publ_key.x, - p_cb->rrand, ri); + output = crypto_toolbox::f4(p_cb->peer_publ_key.x, p_cb->loc_publ_key.x, p_cb->rrand, ri); break; case SMP_MODEL_SEC_CONN_OOB: - output = crypto_toolbox::f4(p_cb->peer_publ_key.x, p_cb->peer_publ_key.x, - p_cb->peer_random, 0); + output = crypto_toolbox::f4(p_cb->peer_publ_key.x, p_cb->peer_publ_key.x, p_cb->peer_random, + 0); break; default: - log::error("Association Model={} is not used in LE SC", - p_cb->selected_association_model); + log::error("Association Model={} is not used in LE SC", p_cb->selected_association_model); return output; } @@ -860,24 +833,22 @@ Octet16 smp_calculate_peer_commitment(tSMP_CB* p_cb) { * Returns void * ******************************************************************************/ -void smp_calculate_numeric_comparison_display_number( - tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) { +void smp_calculate_numeric_comparison_display_number(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) { log::verbose("addr:{}", p_cb->pairing_bda); if (p_cb->role == HCI_ROLE_CENTRAL) { - p_cb->number_to_display = crypto_toolbox::g2( - p_cb->loc_publ_key.x, p_cb->peer_publ_key.x, p_cb->rand, p_cb->rrand); + p_cb->number_to_display = crypto_toolbox::g2(p_cb->loc_publ_key.x, p_cb->peer_publ_key.x, + p_cb->rand, p_cb->rrand); } else { - p_cb->number_to_display = crypto_toolbox::g2( - p_cb->peer_publ_key.x, p_cb->loc_publ_key.x, p_cb->rrand, p_cb->rand); + p_cb->number_to_display = crypto_toolbox::g2(p_cb->peer_publ_key.x, p_cb->loc_publ_key.x, + p_cb->rrand, p_cb->rand); } if (p_cb->number_to_display >= (BTM_MAX_PASSKEY_VAL + 1)) { tSMP_INT_DATA smp_int_data; smp_int_data.status = SMP_PAIR_FAIL_UNKNOWN; p_cb->failure = SMP_PAIR_FAIL_UNKNOWN; - log::verbose("Number to display in numeric comparison={} too large", - p_cb->number_to_display); + log::verbose("Number to display in numeric comparison={} too large", p_cb->number_to_display); smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data); return; } @@ -902,8 +873,7 @@ void smp_calculate_numeric_comparison_display_number( * Returns void * ******************************************************************************/ -void smp_calculate_local_dhkey_check(tSMP_CB* p_cb, - tSMP_INT_DATA* /* p_data */) { +void smp_calculate_local_dhkey_check(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) { uint8_t iocap[3], a[7], b[7]; log::verbose("addr:{}", p_cb->pairing_bda); @@ -914,8 +884,8 @@ void smp_calculate_local_dhkey_check(tSMP_CB* p_cb, smp_collect_local_ble_address(a, p_cb); smp_collect_peer_ble_address(b, p_cb); - p_cb->dhkey_check = crypto_toolbox::f6(p_cb->mac_key, p_cb->rand, p_cb->rrand, - p_cb->peer_random, iocap, a, b); + p_cb->dhkey_check = crypto_toolbox::f6(p_cb->mac_key, p_cb->rand, p_cb->rrand, p_cb->peer_random, + iocap, a, b); } /******************************************************************************* @@ -927,8 +897,7 @@ void smp_calculate_local_dhkey_check(tSMP_CB* p_cb, * Returns void * ******************************************************************************/ -void smp_calculate_peer_dhkey_check(tSMP_CB* p_cb, - tSMP_INT_DATA* /* p_data */) { +void smp_calculate_peer_dhkey_check(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) { uint8_t iocap[3], a[7], b[7]; tSMP_KEY key; @@ -938,8 +907,8 @@ void smp_calculate_peer_dhkey_check(tSMP_CB* p_cb, smp_collect_local_ble_address(a, p_cb); smp_collect_peer_ble_address(b, p_cb); - Octet16 param_buf = crypto_toolbox::f6(p_cb->mac_key, p_cb->rrand, p_cb->rand, - p_cb->local_random, iocap, b, a); + Octet16 param_buf = crypto_toolbox::f6(p_cb->mac_key, p_cb->rrand, p_cb->rand, p_cb->local_random, + iocap, b, a); key.key_type = SMP_KEY_TYPE_PEER_DHK_CHCK; key.p_data = param_buf.data(); tSMP_INT_DATA smp_int_data; @@ -965,11 +934,9 @@ bool smp_calculate_link_key_from_long_term_key(tSMP_CB* p_cb) { log::verbose("addr:{}", p_cb->pairing_bda); if (p_cb->id_addr_rcvd && p_cb->id_addr_type == BLE_ADDR_PUBLIC) { - log::verbose( - "Use rcvd identity address as BD_ADDR of LK rcvd identity address"); + log::verbose("Use rcvd identity address as BD_ADDR of LK rcvd identity address"); bda_for_lk = p_cb->id_addr; - } else if ((BTM_ReadRemoteConnectionAddr(p_cb->pairing_bda, bda_for_lk, - &conn_addr_type, true)) && + } else if ((BTM_ReadRemoteConnectionAddr(p_cb->pairing_bda, bda_for_lk, &conn_addr_type, true)) && conn_addr_type == BLE_ADDR_PUBLIC) { log::verbose("Use rcvd connection address as BD_ADDR of LK"); } else { @@ -983,8 +950,7 @@ bool smp_calculate_link_key_from_long_term_key(tSMP_CB* p_cb) { return false; } - Octet16 link_key = - crypto_toolbox::ltk_to_link_key(p_cb->ltk, p_cb->key_derivation_h7_used); + Octet16 link_key = crypto_toolbox::ltk_to_link_key(p_cb->ltk, p_cb->key_derivation_h7_used); uint8_t link_key_type; if (p_cb->init_security_mode == BTM_SEC_MODE_SC) { @@ -992,19 +958,21 @@ bool smp_calculate_link_key_from_long_term_key(tSMP_CB* p_cb) { link_key_type = BTM_LKEY_TYPE_AUTH_COMB_P_256; } else if (bluetooth::shim::GetController()->SupportsSecureConnections()) { /* both transports are SC capable */ - if (p_cb->sec_level == SMP_SEC_AUTHENTICATED) + if (p_cb->sec_level == SMP_SEC_AUTHENTICATED) { link_key_type = BTM_LKEY_TYPE_AUTH_COMB_P_256; - else + } else { link_key_type = BTM_LKEY_TYPE_UNAUTH_COMB_P_256; + } } else if (p_cb->init_security_mode == BTM_SEC_MODE_SP) { /* BR/EDR transport is SSP capable */ - if (p_cb->sec_level == SMP_SEC_AUTHENTICATED) + if (p_cb->sec_level == SMP_SEC_AUTHENTICATED) { link_key_type = BTM_LKEY_TYPE_AUTH_COMB; - else + } else { link_key_type = BTM_LKEY_TYPE_UNAUTH_COMB; + } } else { - log::error("failed to update link_key. Sec Mode={}, sm4=0x{:02x}", - p_cb->init_security_mode, p_dev_rec->sm4); + log::error("failed to update link_key. Sec Mode={}, sm4=0x{:02x}", p_cb->init_security_mode, + p_dev_rec->sm4); return false; } @@ -1043,14 +1011,12 @@ bool smp_calculate_long_term_key_from_link_key(tSMP_CB* p_cb) { } Octet16 rev_link_key; - std::reverse_copy(p_dev_rec->sec_rec.link_key.begin(), - p_dev_rec->sec_rec.link_key.end(), rev_link_key.begin()); - p_cb->ltk = crypto_toolbox::link_key_to_ltk(rev_link_key, - p_cb->key_derivation_h7_used); - - p_cb->sec_level = (br_link_key_type == BTM_LKEY_TYPE_AUTH_COMB_P_256) - ? SMP_SEC_AUTHENTICATED - : SMP_SEC_UNAUTHENTICATE; + std::reverse_copy(p_dev_rec->sec_rec.link_key.begin(), p_dev_rec->sec_rec.link_key.end(), + rev_link_key.begin()); + p_cb->ltk = crypto_toolbox::link_key_to_ltk(rev_link_key, p_cb->key_derivation_h7_used); + + p_cb->sec_level = (br_link_key_type == BTM_LKEY_TYPE_AUTH_COMB_P_256) ? SMP_SEC_AUTHENTICATED + : SMP_SEC_UNAUTHENTICATE; return true; } @@ -1060,22 +1026,21 @@ bool smp_calculate_long_term_key_from_link_key(tSMP_CB* p_cb) { void smp_start_nonce_generation(tSMP_CB* p_cb) { log::verbose("start generating nonce"); send_ble_rand(BindOnce( - [](tSMP_CB* p_cb, uint64_t rand) { - memcpy(p_cb->rand.data(), (uint8_t*)&rand, sizeof(uint64_t)); - send_ble_rand(BindOnce( - [](tSMP_CB* p_cb, uint64_t rand) { - memcpy(p_cb->rand.data() + sizeof(uint64_t), (uint8_t*)&rand, - sizeof(uint64_t)); - log::verbose("round {}, done", p_cb->round); - /* notifies SM that it has new nonce. */ - smp_sm_event(p_cb, SMP_HAVE_LOC_NONCE_EVT, NULL); - }, - p_cb)); - }, - p_cb)); + [](tSMP_CB* p_cb, uint64_t rand) { + memcpy(p_cb->rand.data(), (uint8_t*)&rand, sizeof(uint64_t)); + send_ble_rand(BindOnce( + [](tSMP_CB* p_cb, uint64_t rand) { + memcpy(p_cb->rand.data() + sizeof(uint64_t), (uint8_t*)&rand, + sizeof(uint64_t)); + log::verbose("round {}, done", p_cb->round); + /* notifies SM that it has new nonce. */ + smp_sm_event(p_cb, SMP_HAVE_LOC_NONCE_EVT, NULL); + }, + p_cb)); + }, + p_cb)); } static void send_ble_rand(OnceCallback callback) { - bluetooth::shim::GetController()->LeRand( - get_main_thread()->BindOnce(std::move(callback))); + bluetooth::shim::GetController()->LeRand(get_main_thread()->BindOnce(std::move(callback))); } diff --git a/system/stack/smp/smp_l2c.cc b/system/stack/smp/smp_l2c.cc index 521cd15f646..f917545679c 100644 --- a/system/stack/smp/smp_l2c.cc +++ b/system/stack/smp/smp_l2c.cc @@ -41,17 +41,13 @@ using namespace bluetooth; static void smp_tx_complete_callback(uint16_t cid, uint16_t num_pkt); -static void smp_connect_callback(uint16_t channel, const RawAddress& bd_addr, - bool connected, uint16_t reason, - tBT_TRANSPORT transport); -static void smp_data_received(uint16_t channel, const RawAddress& bd_addr, - BT_HDR* p_buf); - -static void smp_br_connect_callback(uint16_t channel, const RawAddress& bd_addr, - bool connected, uint16_t reason, - tBT_TRANSPORT transport); -static void smp_br_data_received(uint16_t channel, const RawAddress& bd_addr, - BT_HDR* p_buf); +static void smp_connect_callback(uint16_t channel, const RawAddress& bd_addr, bool connected, + uint16_t reason, tBT_TRANSPORT transport); +static void smp_data_received(uint16_t channel, const RawAddress& bd_addr, BT_HDR* p_buf); + +static void smp_br_connect_callback(uint16_t channel, const RawAddress& bd_addr, bool connected, + uint16_t reason, tBT_TRANSPORT transport); +static void smp_br_data_received(uint16_t channel, const RawAddress& bd_addr, BT_HDR* p_buf); /******************************************************************************* * @@ -69,23 +65,19 @@ void smp_l2cap_if_init(void) { fixed_reg.pL2CA_FixedData_Cb = smp_data_received; fixed_reg.pL2CA_FixedTxComplete_Cb = smp_tx_complete_callback; - fixed_reg.pL2CA_FixedCong_Cb = - NULL; /* do not handle congestion on this channel */ - fixed_reg.default_idle_tout = - 60; /* set 60 seconds timeout, 0xffff default idle timeout */ + fixed_reg.pL2CA_FixedCong_Cb = NULL; /* do not handle congestion on this channel */ + fixed_reg.default_idle_tout = 60; /* set 60 seconds timeout, 0xffff default idle timeout */ if (!L2CA_RegisterFixedChannel(L2CAP_SMP_CID, &fixed_reg)) { - log::error("Unable to register with L2CAP fixed channel profile SMP psm:{}", - L2CAP_SMP_CID); + log::error("Unable to register with L2CAP fixed channel profile SMP psm:{}", L2CAP_SMP_CID); } fixed_reg.pL2CA_FixedConn_Cb = smp_br_connect_callback; fixed_reg.pL2CA_FixedData_Cb = smp_br_data_received; if (!L2CA_RegisterFixedChannel(L2CAP_SMP_BR_CID, &fixed_reg)) { - log::error( - "Unable to register with L2CAP fixed channel profile SMP_BR psm:{}", - L2CAP_SMP_BR_CID); + log::error("Unable to register with L2CAP fixed channel profile SMP_BR psm:{}", + L2CAP_SMP_BR_CID); } } @@ -98,15 +90,13 @@ void smp_l2cap_if_init(void) { * connected (conn = true)/disconnected (conn = false). * ******************************************************************************/ -static void smp_connect_callback(uint16_t /* channel */, - const RawAddress& bd_addr, bool connected, - uint16_t /* reason */, - tBT_TRANSPORT transport) { +static void smp_connect_callback(uint16_t /* channel */, const RawAddress& bd_addr, bool connected, + uint16_t /* reason */, tBT_TRANSPORT transport) { tSMP_CB* p_cb = &smp_cb; tSMP_INT_DATA int_data; - log::debug("bd_addr:{} transport:{}, connected:{}", bd_addr, - bt_transport_text(transport), connected); + log::debug("bd_addr:{} transport:{}, connected:{}", bd_addr, bt_transport_text(transport), + connected); if (bd_addr.IsEmpty()) { log::warn("empty address"); @@ -151,8 +141,7 @@ static void smp_connect_callback(uint16_t /* channel */, * Returns void * ******************************************************************************/ -static void smp_data_received(uint16_t channel, const RawAddress& bd_addr, - BT_HDR* p_buf) { +static void smp_data_received(uint16_t channel, const RawAddress& bd_addr, BT_HDR* p_buf) { tSMP_CB* p_cb = &smp_cb; uint8_t* p = (uint8_t*)(p_buf + 1) + p_buf->offset; uint8_t cmd; @@ -165,8 +154,7 @@ static void smp_data_received(uint16_t channel, const RawAddress& bd_addr, STREAM_TO_UINT8(cmd, p); - log::verbose("cmd={}[0x{:02x}]", - smp_opcode_text(static_cast(cmd)), cmd); + log::verbose("cmd={}[0x{:02x}]", smp_opcode_text(static_cast(cmd)), cmd); /* sanity check */ if ((SMP_OPCODE_MAX < cmd) || (SMP_OPCODE_MIN > cmd)) { @@ -177,8 +165,7 @@ static void smp_data_received(uint16_t channel, const RawAddress& bd_addr, /* reject the pairing request if there is an on-going SMP pairing */ if (SMP_OPCODE_PAIRING_REQ == cmd || SMP_OPCODE_SEC_REQ == cmd) { - if ((p_cb->state == SMP_STATE_IDLE) && - (p_cb->br_state == SMP_BR_STATE_IDLE) && + if ((p_cb->state == SMP_STATE_IDLE) && (p_cb->br_state == SMP_BR_STATE_IDLE) && !(p_cb->flags & SMP_PAIR_FLAGS_WE_STARTED_DD)) { p_cb->role = L2CA_GetBleConnRole(bd_addr); p_cb->pairing_bda = bd_addr; @@ -192,19 +179,16 @@ static void smp_data_received(uint16_t channel, const RawAddress& bd_addr, } if (bd_addr == p_cb->pairing_bda) { - alarm_set_on_mloop(p_cb->smp_rsp_timer_ent, SMP_WAIT_FOR_RSP_TIMEOUT_MS, - smp_rsp_timeout, NULL); + alarm_set_on_mloop(p_cb->smp_rsp_timer_ent, SMP_WAIT_FOR_RSP_TIMEOUT_MS, smp_rsp_timeout, NULL); - smp_log_metrics(p_cb->pairing_bda, false /* incoming */, - p_buf->data + p_buf->offset, p_buf->len, - false /* is_over_br */); + smp_log_metrics(p_cb->pairing_bda, false /* incoming */, p_buf->data + p_buf->offset, + p_buf->len, false /* is_over_br */); if (cmd == SMP_OPCODE_CONFIRM) { - log::verbose("peer_auth_req=0x{:02x}, loc_auth_req=0x{:02x}", - p_cb->peer_auth_req, p_cb->loc_auth_req); + log::verbose("peer_auth_req=0x{:02x}, loc_auth_req=0x{:02x}", p_cb->peer_auth_req, + p_cb->loc_auth_req); - if ((p_cb->peer_auth_req & SMP_SC_SUPPORT_BIT) && - (p_cb->loc_auth_req & SMP_SC_SUPPORT_BIT)) { + if ((p_cb->peer_auth_req & SMP_SC_SUPPORT_BIT) && (p_cb->loc_auth_req & SMP_SC_SUPPORT_BIT)) { cmd = SMP_OPCODE_PAIR_COMMITM; } } @@ -216,8 +200,7 @@ static void smp_data_received(uint16_t channel, const RawAddress& bd_addr, smp_sm_event(p_cb, static_cast(cmd), &smp_int_data); } else { if (!L2CA_RemoveFixedChnl(channel, bd_addr)) { - log::error("Unable to remove fixed channel peer:{} cid:{}", bd_addr, - channel); + log::error("Unable to remove fixed channel peer:{} cid:{}", bd_addr, channel); } } @@ -266,9 +249,8 @@ static void smp_tx_complete_callback(uint16_t cid, uint16_t num_pkt) { * connected (conn = true)/disconnected (conn = false). * ******************************************************************************/ -static void smp_br_connect_callback(uint16_t /* channel */, - const RawAddress& bd_addr, bool connected, - uint16_t /* reason */, +static void smp_br_connect_callback(uint16_t /* channel */, const RawAddress& bd_addr, + bool connected, uint16_t /* reason */, tBT_TRANSPORT transport) { tSMP_CB* p_cb = &smp_cb; tSMP_INT_DATA int_data; @@ -278,18 +260,18 @@ static void smp_br_connect_callback(uint16_t /* channel */, return; } - log::info("BDA:{} pairing_bda:{}, connected:{}", bd_addr, p_cb->pairing_bda, - connected); + log::info("BDA:{} pairing_bda:{}, connected:{}", bd_addr, p_cb->pairing_bda, connected); - if (bd_addr != p_cb->pairing_bda) return; + if (bd_addr != p_cb->pairing_bda) { + return; + } /* Check if we already finished SMP pairing over LE, and are waiting to * check if other side returns some errors. Connection/disconnection on * Classic transport shouldn't impact that. */ tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(p_cb->pairing_bda); - if ((smp_get_state() == SMP_STATE_BOND_PENDING || - smp_get_state() == SMP_STATE_IDLE) && + if ((smp_get_state() == SMP_STATE_BOND_PENDING || smp_get_state() == SMP_STATE_IDLE) && (p_dev_rec && p_dev_rec->sec_rec.is_link_key_known()) && alarm_is_scheduled(p_cb->delayed_auth_timer_ent)) { /* If we were to not return here, we would reset SMP control block, and @@ -314,8 +296,7 @@ static void smp_br_connect_callback(uint16_t /* channel */, } else { /* Disconnected while doing security */ if (p_cb->smp_over_br) { - log::debug( - "SMP over BR/EDR not supported, terminate the ongoing pairing"); + log::debug("SMP over BR/EDR not supported, terminate the ongoing pairing"); smp_br_state_machine_event(p_cb, SMP_BR_L2CAP_DISCONN_EVT, &int_data); } else { log::debug("SMP over BR/EDR not supported, continue the LE pairing"); @@ -333,8 +314,7 @@ static void smp_br_connect_callback(uint16_t /* channel */, * Returns void * ******************************************************************************/ -static void smp_br_data_received(uint16_t /* channel */, - const RawAddress& bd_addr, BT_HDR* p_buf) { +static void smp_br_data_received(uint16_t /* channel */, const RawAddress& bd_addr, BT_HDR* p_buf) { tSMP_CB* p_cb = &smp_cb; uint8_t* p = (uint8_t*)(p_buf + 1) + p_buf->offset; uint8_t cmd; @@ -347,8 +327,7 @@ static void smp_br_data_received(uint16_t /* channel */, } STREAM_TO_UINT8(cmd, p); - log::verbose("cmd={}[0x{:02x}]", - smp_opcode_text(static_cast(cmd)), cmd); + log::verbose("cmd={}[0x{:02x}]", smp_opcode_text(static_cast(cmd)), cmd); /* sanity check */ if ((SMP_OPCODE_MAX < cmd) || (SMP_OPCODE_MIN > cmd)) { @@ -359,8 +338,7 @@ static void smp_br_data_received(uint16_t /* channel */, /* reject the pairing request if there is an on-going SMP pairing */ if (SMP_OPCODE_PAIRING_REQ == cmd) { - if ((p_cb->state == SMP_STATE_IDLE) && - (p_cb->br_state == SMP_BR_STATE_IDLE)) { + if ((p_cb->state == SMP_STATE_IDLE) && (p_cb->br_state == SMP_BR_STATE_IDLE)) { p_cb->role = HCI_ROLE_PERIPHERAL; p_cb->smp_over_br = true; p_cb->pairing_bda = bd_addr; @@ -373,19 +351,16 @@ static void smp_br_data_received(uint16_t /* channel */, } if (bd_addr == p_cb->pairing_bda) { - alarm_set_on_mloop(p_cb->smp_rsp_timer_ent, SMP_WAIT_FOR_RSP_TIMEOUT_MS, - smp_rsp_timeout, NULL); + alarm_set_on_mloop(p_cb->smp_rsp_timer_ent, SMP_WAIT_FOR_RSP_TIMEOUT_MS, smp_rsp_timeout, NULL); - smp_log_metrics(p_cb->pairing_bda, false /* incoming */, - p_buf->data + p_buf->offset, p_buf->len, - true /* is_over_br */); + smp_log_metrics(p_cb->pairing_bda, false /* incoming */, p_buf->data + p_buf->offset, + p_buf->len, true /* is_over_br */); p_cb->rcvd_cmd_code = cmd; p_cb->rcvd_cmd_len = (uint8_t)p_buf->len; tSMP_INT_DATA smp_int_data; smp_int_data.p_data = p; - smp_br_state_machine_event(p_cb, static_cast(cmd), - &smp_int_data); + smp_br_state_machine_event(p_cb, static_cast(cmd), &smp_int_data); } osi_free(p_buf); diff --git a/system/stack/smp/smp_main.cc b/system/stack/smp/smp_main.cc index c4522650d76..faaa2567cb1 100644 --- a/system/stack/smp/smp_main.cc +++ b/system/stack/smp/smp_main.cc @@ -32,25 +32,24 @@ constexpr char kBtmLogTag[] = "SMP"; } -const char* const smp_state_name[] = { - "SMP_STATE_IDLE", - "SMP_STATE_WAIT_APP_RSP", - "SMP_STATE_SEC_REQ_PENDING", - "SMP_STATE_PAIR_REQ_RSP", - "SMP_STATE_WAIT_CONFIRM", - "SMP_STATE_CONFIRM", - "SMP_STATE_RAND", - "SMP_STATE_PUBLIC_KEY_EXCH", - "SMP_STATE_SEC_CONN_PHS1_START", - "SMP_STATE_WAIT_COMMITMENT", - "SMP_STATE_WAIT_NONCE", - "SMP_STATE_SEC_CONN_PHS2_START", - "SMP_STATE_WAIT_DHK_CHECK", - "SMP_STATE_DHK_CHECK", - "SMP_STATE_ENCRYPTION_PENDING", - "SMP_STATE_BOND_PENDING", - "SMP_STATE_CREATE_LOCAL_SEC_CONN_OOB_DATA", - "SMP_STATE_MAX"}; +const char* const smp_state_name[] = {"SMP_STATE_IDLE", + "SMP_STATE_WAIT_APP_RSP", + "SMP_STATE_SEC_REQ_PENDING", + "SMP_STATE_PAIR_REQ_RSP", + "SMP_STATE_WAIT_CONFIRM", + "SMP_STATE_CONFIRM", + "SMP_STATE_RAND", + "SMP_STATE_PUBLIC_KEY_EXCH", + "SMP_STATE_SEC_CONN_PHS1_START", + "SMP_STATE_WAIT_COMMITMENT", + "SMP_STATE_WAIT_NONCE", + "SMP_STATE_SEC_CONN_PHS2_START", + "SMP_STATE_WAIT_DHK_CHECK", + "SMP_STATE_DHK_CHECK", + "SMP_STATE_ENCRYPTION_PENDING", + "SMP_STATE_BOND_PENDING", + "SMP_STATE_CREATE_LOCAL_SEC_CONN_OOB_DATA", + "SMP_STATE_MAX"}; const char* const smp_event_name[] = {"PAIRING_REQ_EVT", "PAIRING_RSP_EVT", @@ -170,190 +169,185 @@ enum { SMP_SM_NO_ACTION }; -static const tSMP_ACT smp_sm_action[] = { - smp_proc_sec_req, - smp_send_pair_req, - smp_send_pair_rsp, - smp_send_confirm, - smp_send_pair_fail, - smp_send_rand, - smp_send_enc_info, - smp_send_id_info, - smp_send_ltk_reply, - smp_proc_pair_cmd, - smp_proc_pair_fail, - smp_proc_confirm, - smp_proc_rand, - smp_proc_enc_info, - smp_proc_central_id, - smp_proc_id_info, - smp_proc_id_addr, - smp_proc_srk_info, - smp_proc_sec_grant, - smp_proc_sl_key, - smp_proc_compare, - smp_process_io_response, - smp_generate_compare, - smp_generate_srand_mrand_confirm, - smp_generate_stk, - smp_key_distribution, - smp_start_enc, - smp_pairing_cmpl, - smp_decide_association_model, - smp_send_app_cback, - smp_check_auth_req, - smp_pair_terminate, - smp_enc_cmpl, - smp_sirk_verify, - smp_proc_discard, - smp_create_private_key, - smp_use_oob_private_key, - smp_send_pair_public_key, - smp_process_pairing_public_key, - smp_both_have_public_keys, - smp_start_secure_connection_phase1, - smp_process_local_nonce, - smp_send_commitment, - smp_process_pairing_commitment, - smp_process_peer_nonce, - smp_calculate_local_dhkey_check, - smp_send_dhkey_check, - smp_process_dhkey_check, - smp_calculate_peer_dhkey_check, - smp_match_dhkey_checks, - smp_calculate_numeric_comparison_display_number, - smp_move_to_secure_connections_phase2, - smp_phase_2_dhkey_checks_are_present, - smp_wait_for_both_public_keys, - smp_start_passkey_verification, - smp_send_keypress_notification, - smp_process_keypress_notification, - smp_process_secure_connection_oob_data, - smp_set_local_oob_keys, - smp_set_local_oob_random_commitment, - smp_idle_terminate}; +static const tSMP_ACT smp_sm_action[] = {smp_proc_sec_req, + smp_send_pair_req, + smp_send_pair_rsp, + smp_send_confirm, + smp_send_pair_fail, + smp_send_rand, + smp_send_enc_info, + smp_send_id_info, + smp_send_ltk_reply, + smp_proc_pair_cmd, + smp_proc_pair_fail, + smp_proc_confirm, + smp_proc_rand, + smp_proc_enc_info, + smp_proc_central_id, + smp_proc_id_info, + smp_proc_id_addr, + smp_proc_srk_info, + smp_proc_sec_grant, + smp_proc_sl_key, + smp_proc_compare, + smp_process_io_response, + smp_generate_compare, + smp_generate_srand_mrand_confirm, + smp_generate_stk, + smp_key_distribution, + smp_start_enc, + smp_pairing_cmpl, + smp_decide_association_model, + smp_send_app_cback, + smp_check_auth_req, + smp_pair_terminate, + smp_enc_cmpl, + smp_sirk_verify, + smp_proc_discard, + smp_create_private_key, + smp_use_oob_private_key, + smp_send_pair_public_key, + smp_process_pairing_public_key, + smp_both_have_public_keys, + smp_start_secure_connection_phase1, + smp_process_local_nonce, + smp_send_commitment, + smp_process_pairing_commitment, + smp_process_peer_nonce, + smp_calculate_local_dhkey_check, + smp_send_dhkey_check, + smp_process_dhkey_check, + smp_calculate_peer_dhkey_check, + smp_match_dhkey_checks, + smp_calculate_numeric_comparison_display_number, + smp_move_to_secure_connections_phase2, + smp_phase_2_dhkey_checks_are_present, + smp_wait_for_both_public_keys, + smp_start_passkey_verification, + smp_send_keypress_notification, + smp_process_keypress_notification, + smp_process_secure_connection_oob_data, + smp_set_local_oob_keys, + smp_set_local_oob_random_commitment, + smp_idle_terminate}; /************ SMP Central FSM State/Event Indirection Table **************/ static const uint8_t smp_central_entry_map[][SMP_STATE_MAX] = { - /* state name: */ - /* Idle, WaitApp Rsp, SecReq Pend, Pair ReqRsp, Wait Cfm, - Confirm, Rand, PublKey Exch, SCPhs1 Strt, Wait Cmtm, Wait Nonce, - SCPhs2 Strt, Wait DHKChk, DHKChk, Enc Pend, Bond Pend, CrLocSc OobData - */ - /* PAIR_REQ */ - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, - /* PAIR_RSP */ - {0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, - /* CONFIRM */ - {0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, - /* RAND */ - {0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0}, - /* PAIR_FAIL */ - {0, 0x81, 0, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, - 0x81, 0, 0x81, 0}, - /* ENC_INFO */ - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0}, - /* CENTRAL_ID */ - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0}, - /* ID_INFO */ - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0}, - /* ID_ADDR */ - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0}, - /* SIGN_INFO */ - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0}, - /* SEC_REQ */ - {2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, - /* PAIR_PUBLIC_KEY */ - {0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0}, - /* PAIR_DHKEY_CHCK */ - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0}, - /* PAIR_KEYPR_NOTIF */ - {0, 8, 0, 0, 0, 0, 0, 0, 5, 2, 0, 0, 0, 0, 0, 0, 0}, - /* PAIR_COMMITM */ - {0, 0, 0, 0, 0, 0, 0, 0, 6, 1, 0, 0, 0, 0, 0, 0, 0}, - /* KEY_READY */ - {0, 3, 0, 3, 1, 0, 2, 0, 4, 0, 0, 0, 0, 0, 1, 6, 0}, - /* ENC_CMPL */ - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0}, - /* L2C_CONN */ - {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, - /* L2C_DISC */ - {3, 0x83, 0, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, - 0x83, 0x83, 0x83, 0}, - /* IO_RSP */ - {0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, - /* SEC_GRANT */ - {0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, - /* TK_REQ */ - {0, 0, 0, 2, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0}, - /* AUTH_CMPL */ - {4, 0x82, 0, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, - 0x82, 0x82, 7, 0}, - /* ENC_REQ */ - {0, 4, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0}, - /* BOND_REQ */ - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0}, - /* DISCARD_SEC_REQ */ - {0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0}, - /* PUBL_KEY_EXCH_REQ */ - {0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, - /* LOC_PUBL_KEY_CRTD */ - {0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1}, - /* BOTH_PUBL_KEYS_RCVD */ - {0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0}, - /* SC_DHKEY_CMPLT */ - {0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0}, - /* HAVE_LOC_NONCE */ - {0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 2}, - /* SC_PHASE1_CMPLT */ - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0}, - /* SC_CALC_NC */ - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0}, - /* SC_DSPL_NC */ - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0}, - /* SC_NC_OK */ - {0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, - /* SC_2_DHCK_CHKS_PRES */ - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, - /* SC_KEY_READY */ - {0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0}, - /* KEYPR_NOTIF */ - {0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, - /* SC_OOB_DATA */ - {0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, - /* CR_LOC_SC_OOB_DATA */ - {5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, - /* SIRK_VERIFY */ - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x82, 0}, + /* state name: */ + /* Idle, WaitApp Rsp, SecReq Pend, Pair ReqRsp, Wait Cfm, + Confirm, Rand, PublKey Exch, SCPhs1 Strt, Wait Cmtm, Wait Nonce, + SCPhs2 Strt, Wait DHKChk, DHKChk, Enc Pend, Bond Pend, CrLocSc OobData + */ + /* PAIR_REQ */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, + /* PAIR_RSP */ + {0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, + /* CONFIRM */ + {0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, + /* RAND */ + {0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0}, + /* PAIR_FAIL */ + {0, 0x81, 0, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0, 0x81, 0}, + /* ENC_INFO */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0}, + /* CENTRAL_ID */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0}, + /* ID_INFO */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0}, + /* ID_ADDR */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0}, + /* SIGN_INFO */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0}, + /* SEC_REQ */ + {2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, + /* PAIR_PUBLIC_KEY */ + {0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0}, + /* PAIR_DHKEY_CHCK */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0}, + /* PAIR_KEYPR_NOTIF */ + {0, 8, 0, 0, 0, 0, 0, 0, 5, 2, 0, 0, 0, 0, 0, 0, 0}, + /* PAIR_COMMITM */ + {0, 0, 0, 0, 0, 0, 0, 0, 6, 1, 0, 0, 0, 0, 0, 0, 0}, + /* KEY_READY */ + {0, 3, 0, 3, 1, 0, 2, 0, 4, 0, 0, 0, 0, 0, 1, 6, 0}, + /* ENC_CMPL */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0}, + /* L2C_CONN */ + {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, + /* L2C_DISC */ + {3, 0x83, 0, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, + 0}, + /* IO_RSP */ + {0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, + /* SEC_GRANT */ + {0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, + /* TK_REQ */ + {0, 0, 0, 2, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0}, + /* AUTH_CMPL */ + {4, 0x82, 0, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 7, 0}, + /* ENC_REQ */ + {0, 4, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0}, + /* BOND_REQ */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0}, + /* DISCARD_SEC_REQ */ + {0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0}, + /* PUBL_KEY_EXCH_REQ */ + {0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, + /* LOC_PUBL_KEY_CRTD */ + {0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1}, + /* BOTH_PUBL_KEYS_RCVD */ + {0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0}, + /* SC_DHKEY_CMPLT */ + {0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0}, + /* HAVE_LOC_NONCE */ + {0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 2}, + /* SC_PHASE1_CMPLT */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0}, + /* SC_CALC_NC */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0}, + /* SC_DSPL_NC */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0}, + /* SC_NC_OK */ + {0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, + /* SC_2_DHCK_CHKS_PRES */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, + /* SC_KEY_READY */ + {0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0}, + /* KEYPR_NOTIF */ + {0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, + /* SC_OOB_DATA */ + {0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, + /* CR_LOC_SC_OOB_DATA */ + {5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, + /* SIRK_VERIFY */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x82, 0}, }; static const uint8_t smp_all_table[][SMP_SM_NUM_COLS] = { - /* Event Action Next State */ - /* PAIR_FAIL */ - {SMP_PROC_PAIR_FAIL, SMP_PAIRING_CMPL, SMP_STATE_IDLE}, - /* AUTH_CMPL */ - {SMP_SEND_PAIR_FAIL, SMP_PAIRING_CMPL, SMP_STATE_IDLE}, - /* L2C_DISC */ - {SMP_PAIR_TERMINATE, SMP_SM_NO_ACTION, SMP_STATE_IDLE}}; + /* Event Action Next State */ + /* PAIR_FAIL */ + {SMP_PROC_PAIR_FAIL, SMP_PAIRING_CMPL, SMP_STATE_IDLE}, + /* AUTH_CMPL */ + {SMP_SEND_PAIR_FAIL, SMP_PAIRING_CMPL, SMP_STATE_IDLE}, + /* L2C_DISC */ + {SMP_PAIR_TERMINATE, SMP_SM_NO_ACTION, SMP_STATE_IDLE}}; static const uint8_t smp_central_idle_table[][SMP_SM_NUM_COLS] = { - /* Event Action Next State */ - /* L2C_CONN */ - {SMP_SEND_APP_CBACK, SMP_SM_NO_ACTION, SMP_STATE_WAIT_APP_RSP}, - /* SEC_REQ */ - {SMP_PROC_SEC_REQ, SMP_SEND_APP_CBACK, SMP_STATE_WAIT_APP_RSP}, - /* L2C_DISC */ - {SMP_IDLE_TERMINATE, SMP_SM_NO_ACTION, SMP_STATE_IDLE}, - /* AUTH_CMPL */ - {SMP_PAIRING_CMPL, SMP_SM_NO_ACTION, SMP_STATE_IDLE}, - /* CR_LOC_SC_OOB_DATA */ - {SMP_CREATE_PRIVATE_KEY, SMP_SM_NO_ACTION, - SMP_STATE_CREATE_LOCAL_SEC_CONN_OOB_DATA} + /* Event Action Next State */ + /* L2C_CONN */ + {SMP_SEND_APP_CBACK, SMP_SM_NO_ACTION, SMP_STATE_WAIT_APP_RSP}, + /* SEC_REQ */ + {SMP_PROC_SEC_REQ, SMP_SEND_APP_CBACK, SMP_STATE_WAIT_APP_RSP}, + /* L2C_DISC */ + {SMP_IDLE_TERMINATE, SMP_SM_NO_ACTION, SMP_STATE_IDLE}, + /* AUTH_CMPL */ + {SMP_PAIRING_CMPL, SMP_SM_NO_ACTION, SMP_STATE_IDLE}, + /* CR_LOC_SC_OOB_DATA */ + {SMP_CREATE_PRIVATE_KEY, SMP_SM_NO_ACTION, SMP_STATE_CREATE_LOCAL_SEC_CONN_OOB_DATA} }; -static const uint8_t - smp_central_wait_for_app_response_table[][SMP_SM_NUM_COLS] = { +static const uint8_t smp_central_wait_for_app_response_table[][SMP_SM_NUM_COLS] = { /* Event Action Next State */ /* SEC_GRANT */ {SMP_PROC_SEC_GRANT, SMP_SEND_APP_CBACK, SMP_STATE_WAIT_APP_RSP}, @@ -371,23 +365,18 @@ static const uint8_t {SMP_PROC_DISCARD, SMP_SM_NO_ACTION, SMP_STATE_IDLE} /* user confirms NC 'OK', i.e. phase 1 is completed */ /* SC_NC_OK */, - {SMP_MOVE_TO_SEC_CONN_PHASE2, SMP_SM_NO_ACTION, - SMP_STATE_SEC_CONN_PHS2_START}, + {SMP_MOVE_TO_SEC_CONN_PHASE2, SMP_SM_NO_ACTION, SMP_STATE_SEC_CONN_PHS2_START}, /* user-provided passkey is rcvd */ /* SC_KEY_READY */ - {SMP_START_PASSKEY_VERIFICATION, SMP_SM_NO_ACTION, - SMP_STATE_SEC_CONN_PHS1_START}, + {SMP_START_PASSKEY_VERIFICATION, SMP_SM_NO_ACTION, SMP_STATE_SEC_CONN_PHS1_START}, /* PAIR_KEYPR_NOTIF */ - {SMP_PROCESS_KEYPRESS_NOTIFICATION, SMP_SEND_APP_CBACK, - SMP_STATE_WAIT_APP_RSP}, + {SMP_PROCESS_KEYPRESS_NOTIFICATION, SMP_SEND_APP_CBACK, SMP_STATE_WAIT_APP_RSP}, /* KEYPR_NOTIF */ - {SMP_SEND_KEYPRESS_NOTIFICATION, SMP_SM_NO_ACTION, - SMP_STATE_WAIT_APP_RSP}, + {SMP_SEND_KEYPRESS_NOTIFICATION, SMP_SM_NO_ACTION, SMP_STATE_WAIT_APP_RSP}, /* SC_OOB_DATA */ {SMP_USE_OOB_PRIVATE_KEY, SMP_SM_NO_ACTION, SMP_STATE_PUBLIC_KEY_EXCH}}; -static const uint8_t - smp_central_pair_request_response_table[][SMP_SM_NUM_COLS] = { +static const uint8_t smp_central_pair_request_response_table[][SMP_SM_NUM_COLS] = { /* Event Action Next State */ /* PAIR_RSP */ {SMP_PROC_PAIR_CMD, SMP_SM_NO_ACTION, SMP_STATE_PAIR_REQ_RSP}, @@ -401,44 +390,39 @@ static const uint8_t {SMP_CREATE_PRIVATE_KEY, SMP_SM_NO_ACTION, SMP_STATE_PUBLIC_KEY_EXCH}}; static const uint8_t smp_central_wait_for_confirm_table[][SMP_SM_NUM_COLS] = { - /* Event Action Next State */ - /* KEY_READY*/ - /* CONFIRM ready */ - {SMP_SEND_CONFIRM, SMP_SM_NO_ACTION, SMP_STATE_CONFIRM}}; + /* Event Action Next State */ + /* KEY_READY*/ + /* CONFIRM ready */ + {SMP_SEND_CONFIRM, SMP_SM_NO_ACTION, SMP_STATE_CONFIRM}}; static const uint8_t smp_central_confirm_table[][SMP_SM_NUM_COLS] = { - /* Event Action Next State */ - /* CONFIRM */ - {SMP_PROC_CONFIRM, SMP_SEND_RAND, SMP_STATE_RAND}}; + /* Event Action Next State */ + /* CONFIRM */ + {SMP_PROC_CONFIRM, SMP_SEND_RAND, SMP_STATE_RAND}}; static const uint8_t smp_central_rand_table[][SMP_SM_NUM_COLS] = { - /* Event Action Next State */ - /* RAND */ - {SMP_PROC_RAND, SMP_GENERATE_COMPARE, SMP_STATE_RAND}, - /* KEY_READY */ - {SMP_PROC_COMPARE, SMP_SM_NO_ACTION, SMP_STATE_RAND}, /* Compare ready */ - /* ENC_REQ */ - {SMP_GENERATE_STK, SMP_SM_NO_ACTION, SMP_STATE_ENCRYPTION_PENDING}}; - -static const uint8_t smp_central_public_key_exchange_table[][SMP_SM_NUM_COLS] = - { + /* Event Action Next State */ + /* RAND */ + {SMP_PROC_RAND, SMP_GENERATE_COMPARE, SMP_STATE_RAND}, + /* KEY_READY */ + {SMP_PROC_COMPARE, SMP_SM_NO_ACTION, SMP_STATE_RAND}, /* Compare ready */ + /* ENC_REQ */ + {SMP_GENERATE_STK, SMP_SM_NO_ACTION, SMP_STATE_ENCRYPTION_PENDING}}; + +static const uint8_t smp_central_public_key_exchange_table[][SMP_SM_NUM_COLS] = { /* Event Action Next State */ /* LOC_PUBL_KEY_CRTD */ {SMP_SEND_PAIR_PUBLIC_KEY, SMP_SM_NO_ACTION, SMP_STATE_PUBLIC_KEY_EXCH}, /* PAIR_PUBLIC_KEY */ - {SMP_PROCESS_PAIR_PUBLIC_KEY, SMP_SM_NO_ACTION, - SMP_STATE_PUBLIC_KEY_EXCH}, + {SMP_PROCESS_PAIR_PUBLIC_KEY, SMP_SM_NO_ACTION, SMP_STATE_PUBLIC_KEY_EXCH}, /* BOTH_PUBL_KEYS_RCVD */ - {SMP_HAVE_BOTH_PUBLIC_KEYS, SMP_SM_NO_ACTION, - SMP_STATE_SEC_CONN_PHS1_START}, + {SMP_HAVE_BOTH_PUBLIC_KEYS, SMP_SM_NO_ACTION, SMP_STATE_SEC_CONN_PHS1_START}, }; -static const uint8_t smp_central_sec_conn_phs1_start_table[][SMP_SM_NUM_COLS] = - { +static const uint8_t smp_central_sec_conn_phs1_start_table[][SMP_SM_NUM_COLS] = { /* Event Action Next State */ /* SC_DHKEY_CMPLT */ - {SMP_START_SEC_CONN_PHASE1, SMP_SM_NO_ACTION, - SMP_STATE_SEC_CONN_PHS1_START}, + {SMP_START_SEC_CONN_PHASE1, SMP_SM_NO_ACTION, SMP_STATE_SEC_CONN_PHS1_START}, /* HAVE_LOC_NONCE */ {SMP_PROCESS_LOCAL_NONCE, SMP_SM_NO_ACTION, SMP_STATE_WAIT_COMMITMENT}, /* TK_REQ */ @@ -447,212 +431,200 @@ static const uint8_t smp_central_sec_conn_phs1_start_table[][SMP_SM_NUM_COLS] = display,*/ /* It's time to start commitment calculation */ /* KEY_READY */ - {SMP_START_PASSKEY_VERIFICATION, SMP_SM_NO_ACTION, - SMP_STATE_SEC_CONN_PHS1_START}, + {SMP_START_PASSKEY_VERIFICATION, SMP_SM_NO_ACTION, SMP_STATE_SEC_CONN_PHS1_START}, /* PAIR_KEYPR_NOTIF */ - {SMP_PROCESS_KEYPRESS_NOTIFICATION, SMP_SEND_APP_CBACK, - SMP_STATE_SEC_CONN_PHS1_START}, + {SMP_PROCESS_KEYPRESS_NOTIFICATION, SMP_SEND_APP_CBACK, SMP_STATE_SEC_CONN_PHS1_START}, /* PAIR_COMMITM */ - {SMP_PROCESS_PAIRING_COMMITMENT, SMP_SM_NO_ACTION, - SMP_STATE_SEC_CONN_PHS1_START}, + {SMP_PROCESS_PAIRING_COMMITMENT, SMP_SM_NO_ACTION, SMP_STATE_SEC_CONN_PHS1_START}, }; static const uint8_t smp_central_wait_commitment_table[][SMP_SM_NUM_COLS] = { - /* Event Action Next State */ - /* PAIR_COMMITM */ - {SMP_PROCESS_PAIRING_COMMITMENT, SMP_SEND_RAND, SMP_STATE_WAIT_NONCE}, - /* PAIR_KEYPR_NOTIF */ - {SMP_PROCESS_KEYPRESS_NOTIFICATION, SMP_SEND_APP_CBACK, - SMP_STATE_WAIT_COMMITMENT}, + /* Event Action Next State */ + /* PAIR_COMMITM */ + {SMP_PROCESS_PAIRING_COMMITMENT, SMP_SEND_RAND, SMP_STATE_WAIT_NONCE}, + /* PAIR_KEYPR_NOTIF */ + {SMP_PROCESS_KEYPRESS_NOTIFICATION, SMP_SEND_APP_CBACK, SMP_STATE_WAIT_COMMITMENT}, }; static const uint8_t smp_central_wait_nonce_table[][SMP_SM_NUM_COLS] = { - /* Event Action Next State */ - /* peer nonce is received */ - /* RAND */ - {SMP_PROC_RAND, SMP_PROCESS_PEER_NONCE, SMP_STATE_SEC_CONN_PHS2_START}, - /* NC model, time to calculate number for NC */ - /* SC_CALC_NC */ - {SMP_CALCULATE_NUMERIC_COMPARISON_DISPLAY_NUMBER, SMP_SM_NO_ACTION, - SMP_STATE_WAIT_NONCE}, - /* NC model, time to display calculated number for NC to the user */ - /* SC_DSPL_NC */ - {SMP_SEND_APP_CBACK, SMP_SM_NO_ACTION, SMP_STATE_WAIT_APP_RSP}, + /* Event Action Next State */ + /* peer nonce is received */ + /* RAND */ + {SMP_PROC_RAND, SMP_PROCESS_PEER_NONCE, SMP_STATE_SEC_CONN_PHS2_START}, + /* NC model, time to calculate number for NC */ + /* SC_CALC_NC */ + {SMP_CALCULATE_NUMERIC_COMPARISON_DISPLAY_NUMBER, SMP_SM_NO_ACTION, SMP_STATE_WAIT_NONCE}, + /* NC model, time to display calculated number for NC to the user */ + /* SC_DSPL_NC */ + {SMP_SEND_APP_CBACK, SMP_SM_NO_ACTION, SMP_STATE_WAIT_APP_RSP}, }; -static const uint8_t smp_central_sec_conn_phs2_start_table[][SMP_SM_NUM_COLS] = - { +static const uint8_t smp_central_sec_conn_phs2_start_table[][SMP_SM_NUM_COLS] = { /* Event Action Next State */ /* SC_PHASE1_CMPLT */ - {SMP_CALCULATE_LOCAL_DHKEY_CHECK, SMP_SEND_DHKEY_CHECK, - SMP_STATE_WAIT_DHK_CHECK}, + {SMP_CALCULATE_LOCAL_DHKEY_CHECK, SMP_SEND_DHKEY_CHECK, SMP_STATE_WAIT_DHK_CHECK}, }; static const uint8_t smp_central_wait_dhk_check_table[][SMP_SM_NUM_COLS] = { - /* Event Action Next State */ - /* PAIR_DHKEY_CHCK */ - {SMP_PROCESS_DHKEY_CHECK, SMP_CALCULATE_PEER_DHKEY_CHECK, - SMP_STATE_DHK_CHECK}, + /* Event Action Next State */ + /* PAIR_DHKEY_CHCK */ + {SMP_PROCESS_DHKEY_CHECK, SMP_CALCULATE_PEER_DHKEY_CHECK, SMP_STATE_DHK_CHECK}, }; static const uint8_t smp_central_dhk_check_table[][SMP_SM_NUM_COLS] = { - /* Event Action Next State */ - /* locally calculated peer dhkey check is ready -> compare it withs DHKey - * Check - * actually received from peer */ - /* SC_KEY_READY */ - {SMP_MATCH_DHKEY_CHECKS, SMP_SM_NO_ACTION, SMP_STATE_DHK_CHECK}, - /* locally calculated peer dhkey check is ready -> calculate STK, go to - * sending - */ - /* HCI LE Start Encryption command */ - /* ENC_REQ */ - {SMP_GENERATE_STK, SMP_SM_NO_ACTION, SMP_STATE_ENCRYPTION_PENDING}, + /* Event Action Next State */ + /* locally calculated peer dhkey check is ready -> compare it withs DHKey + * Check + * actually received from peer */ + /* SC_KEY_READY */ + {SMP_MATCH_DHKEY_CHECKS, SMP_SM_NO_ACTION, SMP_STATE_DHK_CHECK}, + /* locally calculated peer dhkey check is ready -> calculate STK, go to + * sending + */ + /* HCI LE Start Encryption command */ + /* ENC_REQ */ + {SMP_GENERATE_STK, SMP_SM_NO_ACTION, SMP_STATE_ENCRYPTION_PENDING}, }; static const uint8_t smp_central_enc_pending_table[][SMP_SM_NUM_COLS] = { - /* Event Action Next State */ - /* STK ready */ - /* KEY_READY */ - {SMP_START_ENC, SMP_SM_NO_ACTION, SMP_STATE_ENCRYPTION_PENDING}, - /* ENCRYPTED */ - {SMP_CHECK_AUTH_REQ, SMP_SM_NO_ACTION, SMP_STATE_ENCRYPTION_PENDING}, - /* BOND_REQ */ - {SMP_KEY_DISTRIBUTE, SMP_SM_NO_ACTION, SMP_STATE_BOND_PENDING}}; + /* Event Action Next State */ + /* STK ready */ + /* KEY_READY */ + {SMP_START_ENC, SMP_SM_NO_ACTION, SMP_STATE_ENCRYPTION_PENDING}, + /* ENCRYPTED */ + {SMP_CHECK_AUTH_REQ, SMP_SM_NO_ACTION, SMP_STATE_ENCRYPTION_PENDING}, + /* BOND_REQ */ + {SMP_KEY_DISTRIBUTE, SMP_SM_NO_ACTION, SMP_STATE_BOND_PENDING}}; static const uint8_t smp_central_bond_pending_table[][SMP_SM_NUM_COLS] = { - /* Event Action Next State */ - /* ENC_INFO */ - {SMP_PROC_ENC_INFO, SMP_SM_NO_ACTION, SMP_STATE_BOND_PENDING}, - /* ID_INFO */ - {SMP_PROC_ID_INFO, SMP_SM_NO_ACTION, SMP_STATE_BOND_PENDING}, - /* SIGN_INFO */ - {SMP_PROC_SRK_INFO, SMP_SM_NO_ACTION, SMP_STATE_BOND_PENDING}, - /* CENTRAL_ID */ - {SMP_PROC_CENTRAL_ID, SMP_SM_NO_ACTION, SMP_STATE_BOND_PENDING}, - /* ID_ADDR */ - {SMP_PROC_ID_ADDR, SMP_SM_NO_ACTION, SMP_STATE_BOND_PENDING}, - /* KEY_READY */ - /* LTK ready */ - {SMP_SEND_ENC_INFO, SMP_SM_NO_ACTION, SMP_STATE_BOND_PENDING}, - /* AUTH_CMPL */ - {SMP_SIRK_VERIFY, SMP_SM_NO_ACTION, SMP_STATE_BOND_PENDING}, + /* Event Action Next State */ + /* ENC_INFO */ + {SMP_PROC_ENC_INFO, SMP_SM_NO_ACTION, SMP_STATE_BOND_PENDING}, + /* ID_INFO */ + {SMP_PROC_ID_INFO, SMP_SM_NO_ACTION, SMP_STATE_BOND_PENDING}, + /* SIGN_INFO */ + {SMP_PROC_SRK_INFO, SMP_SM_NO_ACTION, SMP_STATE_BOND_PENDING}, + /* CENTRAL_ID */ + {SMP_PROC_CENTRAL_ID, SMP_SM_NO_ACTION, SMP_STATE_BOND_PENDING}, + /* ID_ADDR */ + {SMP_PROC_ID_ADDR, SMP_SM_NO_ACTION, SMP_STATE_BOND_PENDING}, + /* KEY_READY */ + /* LTK ready */ + {SMP_SEND_ENC_INFO, SMP_SM_NO_ACTION, SMP_STATE_BOND_PENDING}, + /* AUTH_CMPL */ + {SMP_SIRK_VERIFY, SMP_SM_NO_ACTION, SMP_STATE_BOND_PENDING}, }; -static const uint8_t - smp_central_create_local_sec_conn_oob_data[][SMP_SM_NUM_COLS] = { +static const uint8_t smp_central_create_local_sec_conn_oob_data[][SMP_SM_NUM_COLS] = { /* Event Action Next State */ /* LOC_PUBL_KEY_CRTD */ - {SMP_SET_LOCAL_OOB_KEYS, SMP_SM_NO_ACTION, - SMP_STATE_CREATE_LOCAL_SEC_CONN_OOB_DATA}, + {SMP_SET_LOCAL_OOB_KEYS, SMP_SM_NO_ACTION, SMP_STATE_CREATE_LOCAL_SEC_CONN_OOB_DATA}, /* HAVE_LOC_NONCE */ {SMP_SET_LOCAL_OOB_RAND_COMMITMENT, SMP_SM_NO_ACTION, SMP_STATE_IDLE}}; /************ SMP Peripheral FSM State/Event Indirection Table **************/ static const uint8_t smp_peripheral_entry_map[][SMP_STATE_MAX] = { - /* state name: */ - /* Idle, WaitApp Rsp, SecReq Pend, Pair ReqRsp, Wait Cfm, Confirm, Rand, - PublKey Exch, SCPhs1 Strt, Wait Cmtm, Wait Nonce, SCPhs2 Strt, Wait - DHKChk, DHKChk, Enc Pend, Bond Pend, CrLocSc OobData */ - /* PAIR_REQ */ - {2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, - /* PAIR_RSP */ - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, - /* CONFIRM */ - {0, 4, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, - /* RAND */ - {0, 0, 0, 0, 0, 1, 2, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0}, - /* PAIR_FAIL */ - {0, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, - 0x81, 0x81, 0, 0}, - /* ENC_INFO */ - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0}, - /* CENTRAL_ID */ - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0}, - /* ID_INFO */ - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0}, - /* ID_ADDR */ - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 0}, - /* SIGN_INFO */ - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0}, - /* SEC_REQ */ - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, - /* PAIR_PUBLIC_KEY */ - {0, 0, 0, 5, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0}, - /* PAIR_DHKEY_CHCK */ - {0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 2, 0, 0, 0}, - /* PAIR_KEYPR_NOTIF */ - {0, 9, 0, 0, 0, 0, 0, 0, 5, 2, 0, 0, 0, 0, 0, 0, 0}, - /* PAIR_COMMITM */ - {0, 8, 0, 0, 0, 0, 0, 0, 6, 1, 0, 0, 0, 0, 0, 0, 0}, - /* KEY_READY */ - {0, 3, 0, 3, 2, 2, 1, 0, 4, 0, 0, 0, 0, 0, 2, 1, 0}, - /* ENC_CMPL */ - {0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0}, - /* L2C_CONN */ - {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, - /* L2C_DISC */ - {0, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, - 0x83, 0x83, 0x83, 0}, - /* IO_RSP */ - {0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, - /* SEC_GRANT */ - {0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, - /* TK_REQ */ - {0, 0, 0, 2, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0}, - /* AUTH_CMPL */ - {0, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, - 0x82, 0x82, 0x82, 0}, - /* ENC_REQ */ - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0}, - /* BOND_REQ */ - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 1}, - /* DISCARD_SEC_REQ */ - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, - /* PUBL_KEY_EXCH_REQ */ - {0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, - /* LOC_PUBL_KEY_CRTD */ - {0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1}, - /* BOTH_PUBL_KEYS_RCVD */ - {0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0}, - /* SC_DHKEY_CMPLT */ - {0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0}, - /* HAVE_LOC_NONCE */ - {0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 2}, - /* SC_PHASE1_CMPLT */ - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0}, - /* SC_CALC_NC */ - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0}, - /* SC_DSPL_NC */ - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0}, - /* SC_NC_OK */ - {0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, - /* SC_2_DHCK_CHKS_PRES */ - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0}, - /* SC_KEY_READY */ - {0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0}, - /* KEYPR_NOTIF */ - {0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, - /* SC_OOB_DATA */ - {0, 11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, - /* CR_LOC_SC_OOB_DATA */ - {3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, - /* SIRK_VERIFY */ - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, + /* state name: */ + /* Idle, WaitApp Rsp, SecReq Pend, Pair ReqRsp, Wait Cfm, Confirm, Rand, + PublKey Exch, SCPhs1 Strt, Wait Cmtm, Wait Nonce, SCPhs2 Strt, Wait + DHKChk, DHKChk, Enc Pend, Bond Pend, CrLocSc OobData */ + /* PAIR_REQ */ + {2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, + /* PAIR_RSP */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, + /* CONFIRM */ + {0, 4, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, + /* RAND */ + {0, 0, 0, 0, 0, 1, 2, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0}, + /* PAIR_FAIL */ + {0, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0, + 0}, + /* ENC_INFO */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0}, + /* CENTRAL_ID */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0}, + /* ID_INFO */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0}, + /* ID_ADDR */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 0}, + /* SIGN_INFO */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0}, + /* SEC_REQ */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, + /* PAIR_PUBLIC_KEY */ + {0, 0, 0, 5, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0}, + /* PAIR_DHKEY_CHCK */ + {0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 2, 0, 0, 0}, + /* PAIR_KEYPR_NOTIF */ + {0, 9, 0, 0, 0, 0, 0, 0, 5, 2, 0, 0, 0, 0, 0, 0, 0}, + /* PAIR_COMMITM */ + {0, 8, 0, 0, 0, 0, 0, 0, 6, 1, 0, 0, 0, 0, 0, 0, 0}, + /* KEY_READY */ + {0, 3, 0, 3, 2, 2, 1, 0, 4, 0, 0, 0, 0, 0, 2, 1, 0}, + /* ENC_CMPL */ + {0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0}, + /* L2C_CONN */ + {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, + /* L2C_DISC */ + {0, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, + 0x83, 0}, + /* IO_RSP */ + {0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, + /* SEC_GRANT */ + {0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, + /* TK_REQ */ + {0, 0, 0, 2, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0}, + /* AUTH_CMPL */ + {0, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, + 0x82, 0}, + /* ENC_REQ */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0}, + /* BOND_REQ */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 1}, + /* DISCARD_SEC_REQ */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, + /* PUBL_KEY_EXCH_REQ */ + {0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, + /* LOC_PUBL_KEY_CRTD */ + {0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1}, + /* BOTH_PUBL_KEYS_RCVD */ + {0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0}, + /* SC_DHKEY_CMPLT */ + {0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0}, + /* HAVE_LOC_NONCE */ + {0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 2}, + /* SC_PHASE1_CMPLT */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0}, + /* SC_CALC_NC */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0}, + /* SC_DSPL_NC */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0}, + /* SC_NC_OK */ + {0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, + /* SC_2_DHCK_CHKS_PRES */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0}, + /* SC_KEY_READY */ + {0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0}, + /* KEYPR_NOTIF */ + {0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, + /* SC_OOB_DATA */ + {0, 11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, + /* CR_LOC_SC_OOB_DATA */ + {3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, + /* SIRK_VERIFY */ + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, }; static const uint8_t smp_peripheral_idle_table[][SMP_SM_NUM_COLS] = { - /* Event Action Next State */ - /* L2C_CONN */ - {SMP_SEND_APP_CBACK, SMP_SM_NO_ACTION, SMP_STATE_WAIT_APP_RSP}, - /* PAIR_REQ */ - {SMP_PROC_PAIR_CMD, SMP_SEND_APP_CBACK, SMP_STATE_WAIT_APP_RSP}, - /* CR_LOC_SC_OOB_DATA */ - {SMP_CREATE_PRIVATE_KEY, SMP_SM_NO_ACTION, - SMP_STATE_CREATE_LOCAL_SEC_CONN_OOB_DATA}}; - -static const uint8_t - smp_peripheral_wait_for_app_response_table[][SMP_SM_NUM_COLS] = { + /* Event Action Next State */ + /* L2C_CONN */ + {SMP_SEND_APP_CBACK, SMP_SM_NO_ACTION, SMP_STATE_WAIT_APP_RSP}, + /* PAIR_REQ */ + {SMP_PROC_PAIR_CMD, SMP_SEND_APP_CBACK, SMP_STATE_WAIT_APP_RSP}, + /* CR_LOC_SC_OOB_DATA */ + {SMP_CREATE_PRIVATE_KEY, SMP_SM_NO_ACTION, SMP_STATE_CREATE_LOCAL_SEC_CONN_OOB_DATA}}; + +static const uint8_t smp_peripheral_wait_for_app_response_table[][SMP_SM_NUM_COLS] = { /* Event Action Next State */ /* IO_RSP */ {SMP_PROC_IO_RSP, SMP_SM_NO_ACTION, SMP_STATE_PAIR_REQ_RSP}, @@ -670,35 +642,29 @@ static const uint8_t {SMP_PROCESS_DHKEY_CHECK, SMP_SM_NO_ACTION, SMP_STATE_WAIT_APP_RSP}, /* user confirms NC 'OK', i.e. phase 1 is completed */ /* SC_NC_OK */ - {SMP_MOVE_TO_SEC_CONN_PHASE2, SMP_SM_NO_ACTION, - SMP_STATE_SEC_CONN_PHS2_START}, + {SMP_MOVE_TO_SEC_CONN_PHASE2, SMP_SM_NO_ACTION, SMP_STATE_SEC_CONN_PHS2_START}, /* user-provided passkey is rcvd */ /* SC_KEY_READY */ - {SMP_START_PASSKEY_VERIFICATION, SMP_SM_NO_ACTION, - SMP_STATE_SEC_CONN_PHS1_START}, + {SMP_START_PASSKEY_VERIFICATION, SMP_SM_NO_ACTION, SMP_STATE_SEC_CONN_PHS1_START}, /* PAIR_COMMITM */ - {SMP_PROCESS_PAIRING_COMMITMENT, SMP_SM_NO_ACTION, - SMP_STATE_WAIT_APP_RSP}, + {SMP_PROCESS_PAIRING_COMMITMENT, SMP_SM_NO_ACTION, SMP_STATE_WAIT_APP_RSP}, /* PAIR_KEYPR_NOTIF */ - {SMP_PROCESS_KEYPRESS_NOTIFICATION, SMP_SEND_APP_CBACK, - SMP_STATE_WAIT_APP_RSP}, + {SMP_PROCESS_KEYPRESS_NOTIFICATION, SMP_SEND_APP_CBACK, SMP_STATE_WAIT_APP_RSP}, /* KEYPR_NOTIF */ - {SMP_SEND_KEYPRESS_NOTIFICATION, SMP_SM_NO_ACTION, - SMP_STATE_WAIT_APP_RSP}, + {SMP_SEND_KEYPRESS_NOTIFICATION, SMP_SM_NO_ACTION, SMP_STATE_WAIT_APP_RSP}, /* SC_OOB_DATA */ {SMP_SEND_PAIR_RSP, SMP_SM_NO_ACTION, SMP_STATE_PAIR_REQ_RSP}, }; static const uint8_t smp_peripheral_sec_request_table[][SMP_SM_NUM_COLS] = { - /* Event Action Next State */ - /* PAIR_REQ */ - {SMP_PROC_PAIR_CMD, SMP_SM_NO_ACTION, SMP_STATE_PAIR_REQ_RSP}, - /* ENCRYPTED*/ - {SMP_ENC_CMPL, SMP_SM_NO_ACTION, SMP_STATE_PAIR_REQ_RSP}, + /* Event Action Next State */ + /* PAIR_REQ */ + {SMP_PROC_PAIR_CMD, SMP_SM_NO_ACTION, SMP_STATE_PAIR_REQ_RSP}, + /* ENCRYPTED*/ + {SMP_ENC_CMPL, SMP_SM_NO_ACTION, SMP_STATE_PAIR_REQ_RSP}, }; -static const uint8_t - smp_peripheral_pair_request_response_table[][SMP_SM_NUM_COLS] = { +static const uint8_t smp_peripheral_pair_request_response_table[][SMP_SM_NUM_COLS] = { /* Event Action Next State */ /* CONFIRM */ {SMP_PROC_CONFIRM, SMP_SM_NO_ACTION, SMP_STATE_CONFIRM}, @@ -715,46 +681,42 @@ static const uint8_t }; static const uint8_t smp_peripheral_wait_confirm_table[][SMP_SM_NUM_COLS] = { - /* Event Action Next State */ - /* CONFIRM */ - {SMP_PROC_CONFIRM, SMP_SEND_CONFIRM, SMP_STATE_CONFIRM}, - /* KEY_READY*/ - {SMP_PROC_SL_KEY, SMP_SM_NO_ACTION, SMP_STATE_WAIT_CONFIRM}}; + /* Event Action Next State */ + /* CONFIRM */ + {SMP_PROC_CONFIRM, SMP_SEND_CONFIRM, SMP_STATE_CONFIRM}, + /* KEY_READY*/ + {SMP_PROC_SL_KEY, SMP_SM_NO_ACTION, SMP_STATE_WAIT_CONFIRM}}; static const uint8_t smp_peripheral_confirm_table[][SMP_SM_NUM_COLS] = { - /* Event Action Next State */ - /* RAND */ - {SMP_PROC_RAND, SMP_GENERATE_COMPARE, SMP_STATE_RAND}, + /* Event Action Next State */ + /* RAND */ + {SMP_PROC_RAND, SMP_GENERATE_COMPARE, SMP_STATE_RAND}, - /* TK/Confirm ready */ - /* KEY_READY*/ - {SMP_PROC_SL_KEY, SMP_SM_NO_ACTION, SMP_STATE_CONFIRM}}; + /* TK/Confirm ready */ + /* KEY_READY*/ + {SMP_PROC_SL_KEY, SMP_SM_NO_ACTION, SMP_STATE_CONFIRM}}; static const uint8_t smp_peripheral_rand_table[][SMP_SM_NUM_COLS] = { - /* Event Action Next State */ - /* KEY_READY */ - {SMP_PROC_COMPARE, SMP_SM_NO_ACTION, SMP_STATE_RAND}, /* compare match */ - /* RAND */ - {SMP_SEND_RAND, SMP_SM_NO_ACTION, SMP_STATE_ENCRYPTION_PENDING}}; + /* Event Action Next State */ + /* KEY_READY */ + {SMP_PROC_COMPARE, SMP_SM_NO_ACTION, SMP_STATE_RAND}, /* compare match */ + /* RAND */ + {SMP_SEND_RAND, SMP_SM_NO_ACTION, SMP_STATE_ENCRYPTION_PENDING}}; static const uint8_t smp_peripheral_public_key_exch_table[][SMP_SM_NUM_COLS] = { - /* Event Action Next State */ - /* LOC_PUBL_KEY_CRTD */ - {SMP_WAIT_FOR_BOTH_PUBLIC_KEYS, SMP_SM_NO_ACTION, - SMP_STATE_PUBLIC_KEY_EXCH}, - /* PAIR_PUBLIC_KEY */ - {SMP_PROCESS_PAIR_PUBLIC_KEY, SMP_SM_NO_ACTION, SMP_STATE_PUBLIC_KEY_EXCH}, - /* BOTH_PUBL_KEYS_RCVD */ - {SMP_HAVE_BOTH_PUBLIC_KEYS, SMP_SM_NO_ACTION, - SMP_STATE_SEC_CONN_PHS1_START}, + /* Event Action Next State */ + /* LOC_PUBL_KEY_CRTD */ + {SMP_WAIT_FOR_BOTH_PUBLIC_KEYS, SMP_SM_NO_ACTION, SMP_STATE_PUBLIC_KEY_EXCH}, + /* PAIR_PUBLIC_KEY */ + {SMP_PROCESS_PAIR_PUBLIC_KEY, SMP_SM_NO_ACTION, SMP_STATE_PUBLIC_KEY_EXCH}, + /* BOTH_PUBL_KEYS_RCVD */ + {SMP_HAVE_BOTH_PUBLIC_KEYS, SMP_SM_NO_ACTION, SMP_STATE_SEC_CONN_PHS1_START}, }; -static const uint8_t - smp_peripheral_sec_conn_phs1_start_table[][SMP_SM_NUM_COLS] = { +static const uint8_t smp_peripheral_sec_conn_phs1_start_table[][SMP_SM_NUM_COLS] = { /* Event Action Next State */ /* SC_DHKEY_CMPLT */ - {SMP_START_SEC_CONN_PHASE1, SMP_SM_NO_ACTION, - SMP_STATE_SEC_CONN_PHS1_START}, + {SMP_START_SEC_CONN_PHASE1, SMP_SM_NO_ACTION, SMP_STATE_SEC_CONN_PHS1_START}, /* HAVE_LOC_NONCE */ {SMP_PROCESS_LOCAL_NONCE, SMP_SM_NO_ACTION, SMP_STATE_WAIT_COMMITMENT}, /* TK_REQ */ @@ -764,41 +726,35 @@ static const uint8_t * time to start */ /* commitment calculation */ /* KEY_READY */ - {SMP_START_PASSKEY_VERIFICATION, SMP_SM_NO_ACTION, - SMP_STATE_SEC_CONN_PHS1_START}, + {SMP_START_PASSKEY_VERIFICATION, SMP_SM_NO_ACTION, SMP_STATE_SEC_CONN_PHS1_START}, /* PAIR_KEYPR_NOTIF */ - {SMP_PROCESS_KEYPRESS_NOTIFICATION, SMP_SEND_APP_CBACK, - SMP_STATE_SEC_CONN_PHS1_START}, + {SMP_PROCESS_KEYPRESS_NOTIFICATION, SMP_SEND_APP_CBACK, SMP_STATE_SEC_CONN_PHS1_START}, /*COMMIT*/ - {SMP_PROCESS_PAIRING_COMMITMENT, SMP_SM_NO_ACTION, - SMP_STATE_SEC_CONN_PHS1_START}, + {SMP_PROCESS_PAIRING_COMMITMENT, SMP_SM_NO_ACTION, SMP_STATE_SEC_CONN_PHS1_START}, }; static const uint8_t smp_peripheral_wait_commitment_table[][SMP_SM_NUM_COLS] = { - /* Event Action Next State */ - /* PAIR_COMMITM */ - {SMP_PROCESS_PAIRING_COMMITMENT, SMP_SEND_COMMITMENT, SMP_STATE_WAIT_NONCE}, - /* PAIR_KEYPR_NOTIF */ - {SMP_PROCESS_KEYPRESS_NOTIFICATION, SMP_SEND_APP_CBACK, - SMP_STATE_WAIT_COMMITMENT}, + /* Event Action Next State */ + /* PAIR_COMMITM */ + {SMP_PROCESS_PAIRING_COMMITMENT, SMP_SEND_COMMITMENT, SMP_STATE_WAIT_NONCE}, + /* PAIR_KEYPR_NOTIF */ + {SMP_PROCESS_KEYPRESS_NOTIFICATION, SMP_SEND_APP_CBACK, SMP_STATE_WAIT_COMMITMENT}, }; static const uint8_t smp_peripheral_wait_nonce_table[][SMP_SM_NUM_COLS] = { - /* Event Action Next State */ - /* peer nonce is received */ - /* RAND */ - {SMP_PROC_RAND, SMP_PROCESS_PEER_NONCE, SMP_STATE_SEC_CONN_PHS2_START}, - /* NC model, time to calculate number for NC */ - /* SC_CALC_NC */ - {SMP_CALCULATE_NUMERIC_COMPARISON_DISPLAY_NUMBER, SMP_SM_NO_ACTION, - SMP_STATE_WAIT_NONCE}, - /* NC model, time to display calculated number for NC to the user */ - /* SC_DSPL_NC */ - {SMP_SEND_APP_CBACK, SMP_SM_NO_ACTION, SMP_STATE_WAIT_APP_RSP}, + /* Event Action Next State */ + /* peer nonce is received */ + /* RAND */ + {SMP_PROC_RAND, SMP_PROCESS_PEER_NONCE, SMP_STATE_SEC_CONN_PHS2_START}, + /* NC model, time to calculate number for NC */ + /* SC_CALC_NC */ + {SMP_CALCULATE_NUMERIC_COMPARISON_DISPLAY_NUMBER, SMP_SM_NO_ACTION, SMP_STATE_WAIT_NONCE}, + /* NC model, time to display calculated number for NC to the user */ + /* SC_DSPL_NC */ + {SMP_SEND_APP_CBACK, SMP_SM_NO_ACTION, SMP_STATE_WAIT_APP_RSP}, }; -static const uint8_t - smp_peripheral_sec_conn_phs2_start_table[][SMP_SM_NUM_COLS] = { +static const uint8_t smp_peripheral_sec_conn_phs2_start_table[][SMP_SM_NUM_COLS] = { /* Event Action Next State */ /* SC_PHASE1_CMPLT */ {SMP_CALCULATE_LOCAL_DHKEY_CHECK, SMP_PH2_DHKEY_CHECKS_ARE_PRESENT, @@ -806,145 +762,134 @@ static const uint8_t /* DHKey Check from central is received before peripheral DHKey * calculation is completed - race */ /* PAIR_DHKEY_CHCK */ - {SMP_PROCESS_DHKEY_CHECK, SMP_SM_NO_ACTION, - SMP_STATE_SEC_CONN_PHS2_START}, + {SMP_PROCESS_DHKEY_CHECK, SMP_SM_NO_ACTION, SMP_STATE_SEC_CONN_PHS2_START}, }; static const uint8_t smp_peripheral_wait_dhk_check_table[][SMP_SM_NUM_COLS] = { - /* Event Action Next State */ - /* PAIR_DHKEY_CHCK */ - {SMP_PROCESS_DHKEY_CHECK, SMP_CALCULATE_PEER_DHKEY_CHECK, - SMP_STATE_DHK_CHECK}, - /* DHKey Check from central was received before peripheral came to this - state */ - /* SC_2_DHCK_CHKS_PRES */ - {SMP_CALCULATE_PEER_DHKEY_CHECK, SMP_SM_NO_ACTION, SMP_STATE_DHK_CHECK}, + /* Event Action Next State */ + /* PAIR_DHKEY_CHCK */ + {SMP_PROCESS_DHKEY_CHECK, SMP_CALCULATE_PEER_DHKEY_CHECK, SMP_STATE_DHK_CHECK}, + /* DHKey Check from central was received before peripheral came to this + state */ + /* SC_2_DHCK_CHKS_PRES */ + {SMP_CALCULATE_PEER_DHKEY_CHECK, SMP_SM_NO_ACTION, SMP_STATE_DHK_CHECK}, }; static const uint8_t smp_peripheral_dhk_check_table[][SMP_SM_NUM_COLS] = { - /* Event Action Next State */ - - /* locally calculated peer dhkey check is ready -> compare it withs DHKey - * Check - */ - /* actually received from peer */ - /* SC_KEY_READY */ - {SMP_MATCH_DHKEY_CHECKS, SMP_SM_NO_ACTION, SMP_STATE_DHK_CHECK}, - - /* dhkey checks match -> send local dhkey check to central, go to wait for - * HCI LE - */ - /* Long Term Key Request Event */ - /* PAIR_DHKEY_CHCK */ - {SMP_SEND_DHKEY_CHECK, SMP_SM_NO_ACTION, SMP_STATE_ENCRYPTION_PENDING}, + /* Event Action Next State */ + + /* locally calculated peer dhkey check is ready -> compare it withs DHKey + * Check + */ + /* actually received from peer */ + /* SC_KEY_READY */ + {SMP_MATCH_DHKEY_CHECKS, SMP_SM_NO_ACTION, SMP_STATE_DHK_CHECK}, + + /* dhkey checks match -> send local dhkey check to central, go to wait for + * HCI LE + */ + /* Long Term Key Request Event */ + /* PAIR_DHKEY_CHCK */ + {SMP_SEND_DHKEY_CHECK, SMP_SM_NO_ACTION, SMP_STATE_ENCRYPTION_PENDING}, }; static const uint8_t smp_peripheral_enc_pending_table[][SMP_SM_NUM_COLS] = { - /* Event Action Next State */ - /* ENC_REQ */ - {SMP_GENERATE_STK, SMP_SM_NO_ACTION, SMP_STATE_ENCRYPTION_PENDING}, - - /* STK ready */ - /* KEY_READY */ - {SMP_SEND_LTK_REPLY, SMP_SM_NO_ACTION, SMP_STATE_ENCRYPTION_PENDING}, - /* ENCRYPTED */ - {SMP_CHECK_AUTH_REQ, SMP_SM_NO_ACTION, SMP_STATE_ENCRYPTION_PENDING}, - /* BOND_REQ */ - {SMP_KEY_DISTRIBUTE, SMP_SM_NO_ACTION, SMP_STATE_BOND_PENDING}}; + /* Event Action Next State */ + /* ENC_REQ */ + {SMP_GENERATE_STK, SMP_SM_NO_ACTION, SMP_STATE_ENCRYPTION_PENDING}, + + /* STK ready */ + /* KEY_READY */ + {SMP_SEND_LTK_REPLY, SMP_SM_NO_ACTION, SMP_STATE_ENCRYPTION_PENDING}, + /* ENCRYPTED */ + {SMP_CHECK_AUTH_REQ, SMP_SM_NO_ACTION, SMP_STATE_ENCRYPTION_PENDING}, + /* BOND_REQ */ + {SMP_KEY_DISTRIBUTE, SMP_SM_NO_ACTION, SMP_STATE_BOND_PENDING}}; static const uint8_t smp_peripheral_bond_pending_table[][SMP_SM_NUM_COLS] = { - /* Event Action Next State */ - - /* LTK ready */ - /* KEY_READY */ - {SMP_SEND_ENC_INFO, SMP_SM_NO_ACTION, SMP_STATE_BOND_PENDING}, - - /* rev SRK */ - /* SIGN_INFO */ - {SMP_PROC_SRK_INFO, SMP_SM_NO_ACTION, SMP_STATE_BOND_PENDING}, - /* ENC_INFO */ - {SMP_PROC_ENC_INFO, SMP_SM_NO_ACTION, SMP_STATE_BOND_PENDING}, - /* ID_INFO */ - {SMP_PROC_ID_INFO, SMP_SM_NO_ACTION, SMP_STATE_BOND_PENDING}, - /* CENTRAL_ID*/ - {SMP_PROC_CENTRAL_ID, SMP_SM_NO_ACTION, SMP_STATE_BOND_PENDING}, - /* ID_ADDR */ - {SMP_PROC_ID_ADDR, SMP_SM_NO_ACTION, SMP_STATE_BOND_PENDING}, - /* AUTH_CMPL */ - {SMP_SIRK_VERIFY, SMP_SM_NO_ACTION, SMP_STATE_BOND_PENDING}, + /* Event Action Next State */ + + /* LTK ready */ + /* KEY_READY */ + {SMP_SEND_ENC_INFO, SMP_SM_NO_ACTION, SMP_STATE_BOND_PENDING}, + + /* rev SRK */ + /* SIGN_INFO */ + {SMP_PROC_SRK_INFO, SMP_SM_NO_ACTION, SMP_STATE_BOND_PENDING}, + /* ENC_INFO */ + {SMP_PROC_ENC_INFO, SMP_SM_NO_ACTION, SMP_STATE_BOND_PENDING}, + /* ID_INFO */ + {SMP_PROC_ID_INFO, SMP_SM_NO_ACTION, SMP_STATE_BOND_PENDING}, + /* CENTRAL_ID*/ + {SMP_PROC_CENTRAL_ID, SMP_SM_NO_ACTION, SMP_STATE_BOND_PENDING}, + /* ID_ADDR */ + {SMP_PROC_ID_ADDR, SMP_SM_NO_ACTION, SMP_STATE_BOND_PENDING}, + /* AUTH_CMPL */ + {SMP_SIRK_VERIFY, SMP_SM_NO_ACTION, SMP_STATE_BOND_PENDING}, }; -static const uint8_t - smp_peripheral_create_local_sec_conn_oob_data[][SMP_SM_NUM_COLS] = { +static const uint8_t smp_peripheral_create_local_sec_conn_oob_data[][SMP_SM_NUM_COLS] = { /* Event Action Next State */ /* LOC_PUBL_KEY_CRTD */ - {SMP_SET_LOCAL_OOB_KEYS, SMP_SM_NO_ACTION, - SMP_STATE_CREATE_LOCAL_SEC_CONN_OOB_DATA}, + {SMP_SET_LOCAL_OOB_KEYS, SMP_SM_NO_ACTION, SMP_STATE_CREATE_LOCAL_SEC_CONN_OOB_DATA}, /* HAVE_LOC_NONCE */ {SMP_SET_LOCAL_OOB_RAND_COMMITMENT, SMP_SM_NO_ACTION, SMP_STATE_IDLE}}; static const tSMP_SM_TBL smp_state_table[][2] = { - /* SMP_STATE_IDLE */ - {smp_central_idle_table, smp_peripheral_idle_table}, + /* SMP_STATE_IDLE */ + {smp_central_idle_table, smp_peripheral_idle_table}, - /* SMP_STATE_WAIT_APP_RSP */ - {smp_central_wait_for_app_response_table, - smp_peripheral_wait_for_app_response_table}, + /* SMP_STATE_WAIT_APP_RSP */ + {smp_central_wait_for_app_response_table, smp_peripheral_wait_for_app_response_table}, - /* SMP_STATE_SEC_REQ_PENDING */ - {NULL, smp_peripheral_sec_request_table}, + /* SMP_STATE_SEC_REQ_PENDING */ + {NULL, smp_peripheral_sec_request_table}, - /* SMP_STATE_PAIR_REQ_RSP */ - {smp_central_pair_request_response_table, - smp_peripheral_pair_request_response_table}, + /* SMP_STATE_PAIR_REQ_RSP */ + {smp_central_pair_request_response_table, smp_peripheral_pair_request_response_table}, - /* SMP_STATE_WAIT_CONFIRM */ - {smp_central_wait_for_confirm_table, smp_peripheral_wait_confirm_table}, + /* SMP_STATE_WAIT_CONFIRM */ + {smp_central_wait_for_confirm_table, smp_peripheral_wait_confirm_table}, - /* SMP_STATE_CONFIRM */ - {smp_central_confirm_table, smp_peripheral_confirm_table}, + /* SMP_STATE_CONFIRM */ + {smp_central_confirm_table, smp_peripheral_confirm_table}, - /* SMP_STATE_RAND */ - {smp_central_rand_table, smp_peripheral_rand_table}, + /* SMP_STATE_RAND */ + {smp_central_rand_table, smp_peripheral_rand_table}, - /* SMP_STATE_PUBLIC_KEY_EXCH */ - {smp_central_public_key_exchange_table, - smp_peripheral_public_key_exch_table}, + /* SMP_STATE_PUBLIC_KEY_EXCH */ + {smp_central_public_key_exchange_table, smp_peripheral_public_key_exch_table}, - /* SMP_STATE_SEC_CONN_PHS1_START */ - {smp_central_sec_conn_phs1_start_table, - smp_peripheral_sec_conn_phs1_start_table}, + /* SMP_STATE_SEC_CONN_PHS1_START */ + {smp_central_sec_conn_phs1_start_table, smp_peripheral_sec_conn_phs1_start_table}, - /* SMP_STATE_WAIT_COMMITMENT */ - {smp_central_wait_commitment_table, smp_peripheral_wait_commitment_table}, + /* SMP_STATE_WAIT_COMMITMENT */ + {smp_central_wait_commitment_table, smp_peripheral_wait_commitment_table}, - /* SMP_STATE_WAIT_NONCE */ - {smp_central_wait_nonce_table, smp_peripheral_wait_nonce_table}, + /* SMP_STATE_WAIT_NONCE */ + {smp_central_wait_nonce_table, smp_peripheral_wait_nonce_table}, - /* SMP_STATE_SEC_CONN_PHS2_START */ - {smp_central_sec_conn_phs2_start_table, - smp_peripheral_sec_conn_phs2_start_table}, + /* SMP_STATE_SEC_CONN_PHS2_START */ + {smp_central_sec_conn_phs2_start_table, smp_peripheral_sec_conn_phs2_start_table}, - /* SMP_STATE_WAIT_DHK_CHECK */ - {smp_central_wait_dhk_check_table, smp_peripheral_wait_dhk_check_table}, + /* SMP_STATE_WAIT_DHK_CHECK */ + {smp_central_wait_dhk_check_table, smp_peripheral_wait_dhk_check_table}, - /* SMP_STATE_DHK_CHECK */ - {smp_central_dhk_check_table, smp_peripheral_dhk_check_table}, + /* SMP_STATE_DHK_CHECK */ + {smp_central_dhk_check_table, smp_peripheral_dhk_check_table}, - /* SMP_STATE_ENCRYPTION_PENDING */ - {smp_central_enc_pending_table, smp_peripheral_enc_pending_table}, + /* SMP_STATE_ENCRYPTION_PENDING */ + {smp_central_enc_pending_table, smp_peripheral_enc_pending_table}, - /* SMP_STATE_BOND_PENDING */ - {smp_central_bond_pending_table, smp_peripheral_bond_pending_table}, + /* SMP_STATE_BOND_PENDING */ + {smp_central_bond_pending_table, smp_peripheral_bond_pending_table}, - /* SMP_STATE_CREATE_LOCAL_SEC_CONN_OOB_DATA */ - {smp_central_create_local_sec_conn_oob_data, - smp_peripheral_create_local_sec_conn_oob_data}, + /* SMP_STATE_CREATE_LOCAL_SEC_CONN_OOB_DATA */ + {smp_central_create_local_sec_conn_oob_data, smp_peripheral_create_local_sec_conn_oob_data}, }; typedef const uint8_t (*tSMP_ENTRY_TBL)[SMP_STATE_MAX]; -static const tSMP_ENTRY_TBL smp_entry_table[] = {smp_central_entry_map, - smp_peripheral_entry_map}; +static const tSMP_ENTRY_TBL smp_entry_table[] = {smp_central_entry_map, smp_peripheral_entry_map}; tSMP_CB smp_cb; @@ -956,14 +901,12 @@ tSMP_CB smp_cb; ******************************************************************************/ void smp_set_state(tSMP_STATE state) { if (state < SMP_STATE_MAX) { - log::debug("State change: {}({})==>{}({})", - smp_get_state_name(smp_cb.state), smp_cb.state, + log::debug("State change: {}({})==>{}({})", smp_get_state_name(smp_cb.state), smp_cb.state, smp_get_state_name(state), state); if (smp_cb.state != state) { - BTM_LogHistory( - kBtmLogTag, smp_cb.pairing_ble_bd_addr, "Security state changed", - base::StringPrintf("%s => %s", smp_get_state_name(smp_cb.state), - smp_get_state_name(state))); + BTM_LogHistory(kBtmLogTag, smp_cb.pairing_ble_bd_addr, "Security state changed", + base::StringPrintf("%s => %s", smp_get_state_name(smp_cb.state), + smp_get_state_name(state))); } smp_cb.state = state; } else { @@ -1012,16 +955,14 @@ bool smp_sm_event(tSMP_CB* p_cb, tSMP_EVENT event, tSMP_INT_DATA* p_data) { return false; } - log::debug("Role:{}, State:[{}({})], Event:[{}({})]", - hci_role_text(p_cb->role), smp_get_state_name(p_cb->state), - p_cb->state, smp_get_event_name(event), event); + log::debug("Role:{}, State:[{}({})], Event:[{}({})]", hci_role_text(p_cb->role), + smp_get_state_name(p_cb->state), p_cb->state, smp_get_event_name(event), event); /* look up the state table for the current state */ /* lookup entry /w event & curr_state */ /* If entry is ignore, return. * Otherwise, get state table (according to curr_state or all_state) */ - if ((event <= SMP_MAX_EVT) && - ((entry = entry_table[event - 1][curr_state]) != SMP_SM_IGNORE)) { + if ((event <= SMP_MAX_EVT) && ((entry = entry_table[event - 1][curr_state]) != SMP_SM_IGNORE)) { if (entry & SMP_ALL_TBL_MASK) { entry &= ~SMP_ALL_TBL_MASK; state_table = smp_all_table; @@ -1029,9 +970,8 @@ bool smp_sm_event(tSMP_CB* p_cb, tSMP_EVENT event, tSMP_INT_DATA* p_data) { state_table = smp_state_table[curr_state][p_cb->role]; } } else { - log::warn("Ignore event[{}({})] in state[{}({})]", - smp_get_event_name(event), event, smp_get_state_name(curr_state), - curr_state); + log::warn("Ignore event[{}({})] in state[{}({})]", smp_get_event_name(event), event, + smp_get_state_name(curr_state), curr_state); return false; } diff --git a/system/stack/smp/smp_utils.cc b/system/stack/smp/smp_utils.cc index 72892169daa..601dea34b8d 100644 --- a/system/stack/smp/smp_utils.cc +++ b/system/stack/smp/smp_utils.cc @@ -79,22 +79,22 @@ constexpr char kBtmLogTag[] = "SMP"; /* SMP command sizes per spec */ static const uint8_t smp_cmd_size_per_spec[] = { - 0, - SMP_PAIRING_REQ_SIZE, /* 0x01: pairing request */ - SMP_PAIRING_REQ_SIZE, /* 0x02: pairing response */ - SMP_CONFIRM_CMD_SIZE, /* 0x03: pairing confirm */ - SMP_RAND_CMD_SIZE, /* 0x04: pairing random */ - SMP_PAIR_FAIL_SIZE, /* 0x05: pairing failed */ - SMP_ENC_INFO_SIZE, /* 0x06: encryption information */ - SMP_CENTRAL_ID_SIZE, /* 0x07: central identification */ - SMP_ID_INFO_SIZE, /* 0x08: identity information */ - SMP_ID_ADDR_SIZE, /* 0x09: identity address information */ - SMP_SIGN_INFO_SIZE, /* 0x0A: signing information */ - SMP_SECURITY_REQUEST_SIZE, /* 0x0B: security request */ - SMP_PAIR_PUBL_KEY_SIZE, /* 0x0C: pairing public key */ - SMP_PAIR_DHKEY_CHECK_SIZE, /* 0x0D: pairing dhkey check */ - SMP_PAIR_KEYPR_NOTIF_SIZE, /* 0x0E: pairing keypress notification */ - SMP_PAIR_COMMITM_SIZE /* 0x0F: pairing commitment */ + 0, + SMP_PAIRING_REQ_SIZE, /* 0x01: pairing request */ + SMP_PAIRING_REQ_SIZE, /* 0x02: pairing response */ + SMP_CONFIRM_CMD_SIZE, /* 0x03: pairing confirm */ + SMP_RAND_CMD_SIZE, /* 0x04: pairing random */ + SMP_PAIR_FAIL_SIZE, /* 0x05: pairing failed */ + SMP_ENC_INFO_SIZE, /* 0x06: encryption information */ + SMP_CENTRAL_ID_SIZE, /* 0x07: central identification */ + SMP_ID_INFO_SIZE, /* 0x08: identity information */ + SMP_ID_ADDR_SIZE, /* 0x09: identity address information */ + SMP_SIGN_INFO_SIZE, /* 0x0A: signing information */ + SMP_SECURITY_REQUEST_SIZE, /* 0x0B: security request */ + SMP_PAIR_PUBL_KEY_SIZE, /* 0x0C: pairing public key */ + SMP_PAIR_DHKEY_CHECK_SIZE, /* 0x0D: pairing dhkey check */ + SMP_PAIR_KEYPR_NOTIF_SIZE, /* 0x0E: pairing keypress notification */ + SMP_PAIR_COMMITM_SIZE /* 0x0F: pairing commitment */ }; static bool smp_parameter_unconditionally_valid(tSMP_CB* p_cb); @@ -106,22 +106,22 @@ typedef bool (*tSMP_CMD_LEN_VALID)(tSMP_CB* p_cb); static bool smp_command_has_valid_fixed_length(tSMP_CB* p_cb); static const tSMP_CMD_LEN_VALID smp_cmd_len_is_valid[] = { - smp_parameter_unconditionally_invalid, - smp_command_has_valid_fixed_length, /* 0x01: pairing request */ - smp_command_has_valid_fixed_length, /* 0x02: pairing response */ - smp_command_has_valid_fixed_length, /* 0x03: pairing confirm */ - smp_command_has_valid_fixed_length, /* 0x04: pairing random */ - smp_command_has_valid_fixed_length, /* 0x05: pairing failed */ - smp_command_has_valid_fixed_length, /* 0x06: encryption information */ - smp_command_has_valid_fixed_length, /* 0x07: central identification */ - smp_command_has_valid_fixed_length, /* 0x08: identity information */ - smp_command_has_valid_fixed_length, /* 0x09: identity address information */ - smp_command_has_valid_fixed_length, /* 0x0A: signing information */ - smp_command_has_valid_fixed_length, /* 0x0B: security request */ - smp_command_has_valid_fixed_length, /* 0x0C: pairing public key */ - smp_command_has_valid_fixed_length, /* 0x0D: pairing dhkey check */ - smp_command_has_valid_fixed_length, /* 0x0E: pairing keypress notification*/ - smp_command_has_valid_fixed_length /* 0x0F: pairing commitment */ + smp_parameter_unconditionally_invalid, + smp_command_has_valid_fixed_length, /* 0x01: pairing request */ + smp_command_has_valid_fixed_length, /* 0x02: pairing response */ + smp_command_has_valid_fixed_length, /* 0x03: pairing confirm */ + smp_command_has_valid_fixed_length, /* 0x04: pairing random */ + smp_command_has_valid_fixed_length, /* 0x05: pairing failed */ + smp_command_has_valid_fixed_length, /* 0x06: encryption information */ + smp_command_has_valid_fixed_length, /* 0x07: central identification */ + smp_command_has_valid_fixed_length, /* 0x08: identity information */ + smp_command_has_valid_fixed_length, /* 0x09: identity address information */ + smp_command_has_valid_fixed_length, /* 0x0A: signing information */ + smp_command_has_valid_fixed_length, /* 0x0B: security request */ + smp_command_has_valid_fixed_length, /* 0x0C: pairing public key */ + smp_command_has_valid_fixed_length, /* 0x0D: pairing dhkey check */ + smp_command_has_valid_fixed_length, /* 0x0E: pairing keypress notification*/ + smp_command_has_valid_fixed_length /* 0x0F: pairing commitment */ }; /* type for SMP command parameter ranges validation functions */ @@ -131,26 +131,26 @@ static bool smp_pairing_request_response_parameters_are_valid(tSMP_CB* p_cb); static bool smp_pairing_keypress_notification_is_valid(tSMP_CB* p_cb); static const tSMP_CMD_PARAM_RANGES_VALID smp_cmd_param_ranges_are_valid[] = { - smp_parameter_unconditionally_invalid, - smp_pairing_request_response_parameters_are_valid, /* 0x01: pairing - request */ - smp_pairing_request_response_parameters_are_valid, /* 0x02: pairing - response */ - smp_parameter_unconditionally_valid, /* 0x03: pairing confirm */ - smp_parameter_unconditionally_valid, /* 0x04: pairing random */ - smp_parameter_unconditionally_valid, /* 0x05: pairing failed */ - smp_parameter_unconditionally_valid, /* 0x06: encryption information */ - smp_parameter_unconditionally_valid, /* 0x07: central identification */ - smp_parameter_unconditionally_valid, /* 0x08: identity information */ - smp_parameter_unconditionally_valid, /* 0x09: identity address - information */ - smp_parameter_unconditionally_valid, /* 0x0A: signing information */ - smp_parameter_unconditionally_valid, /* 0x0B: security request */ - smp_parameter_unconditionally_valid, /* 0x0C: pairing public key */ - smp_parameter_unconditionally_valid, /* 0x0D: pairing dhkey check */ - smp_pairing_keypress_notification_is_valid, /* 0x0E: pairing keypress - notification */ - smp_parameter_unconditionally_valid /* 0x0F: pairing commitment */ + smp_parameter_unconditionally_invalid, + smp_pairing_request_response_parameters_are_valid, /* 0x01: pairing + request */ + smp_pairing_request_response_parameters_are_valid, /* 0x02: pairing + response */ + smp_parameter_unconditionally_valid, /* 0x03: pairing confirm */ + smp_parameter_unconditionally_valid, /* 0x04: pairing random */ + smp_parameter_unconditionally_valid, /* 0x05: pairing failed */ + smp_parameter_unconditionally_valid, /* 0x06: encryption information */ + smp_parameter_unconditionally_valid, /* 0x07: central identification */ + smp_parameter_unconditionally_valid, /* 0x08: identity information */ + smp_parameter_unconditionally_valid, /* 0x09: identity address + information */ + smp_parameter_unconditionally_valid, /* 0x0A: signing information */ + smp_parameter_unconditionally_valid, /* 0x0B: security request */ + smp_parameter_unconditionally_valid, /* 0x0C: pairing public key */ + smp_parameter_unconditionally_valid, /* 0x0D: pairing dhkey check */ + smp_pairing_keypress_notification_is_valid, /* 0x0E: pairing keypress + notification */ + smp_parameter_unconditionally_valid /* 0x0F: pairing commitment */ }; /* type for action functions */ @@ -167,85 +167,79 @@ static BT_HDR* smp_build_signing_info_cmd(uint8_t cmd_code, tSMP_CB* p_cb); static BT_HDR* smp_build_central_id_cmd(uint8_t cmd_code, tSMP_CB* p_cb); static BT_HDR* smp_build_id_addr_cmd(uint8_t cmd_code, tSMP_CB* p_cb); static BT_HDR* smp_build_pair_public_key_cmd(uint8_t cmd_code, tSMP_CB* p_cb); -static BT_HDR* smp_build_pairing_commitment_cmd(uint8_t cmd_code, - tSMP_CB* p_cb); +static BT_HDR* smp_build_pairing_commitment_cmd(uint8_t cmd_code, tSMP_CB* p_cb); static BT_HDR* smp_build_pair_dhkey_check_cmd(uint8_t cmd_code, tSMP_CB* p_cb); -static BT_HDR* smp_build_pairing_keypress_notification_cmd(uint8_t cmd_code, - tSMP_CB* p_cb); +static BT_HDR* smp_build_pairing_keypress_notification_cmd(uint8_t cmd_code, tSMP_CB* p_cb); static const tSMP_CMD_ACT smp_cmd_build_act[] = { - NULL, - smp_build_pairing_cmd, /* 0x01: pairing request */ - smp_build_pairing_cmd, /* 0x02: pairing response */ - smp_build_confirm_cmd, /* 0x03: pairing confirm */ - smp_build_rand_cmd, /* 0x04: pairing random */ - smp_build_pairing_fail, /* 0x05: pairing failure */ - smp_build_encrypt_info_cmd, /* 0x06: encryption information */ - smp_build_central_id_cmd, /* 0x07: central identification */ - smp_build_identity_info_cmd, /* 0x08: identity information */ - smp_build_id_addr_cmd, /* 0x09: identity address information */ - smp_build_signing_info_cmd, /* 0x0A: signing information */ - smp_build_security_request, /* 0x0B: security request */ - smp_build_pair_public_key_cmd, /* 0x0C: pairing public key */ - smp_build_pair_dhkey_check_cmd, /* 0x0D: pairing DHKey check */ - smp_build_pairing_keypress_notification_cmd, /* 0x0E: pairing keypress - notification */ - smp_build_pairing_commitment_cmd /* 0x0F: pairing commitment */ + NULL, + smp_build_pairing_cmd, /* 0x01: pairing request */ + smp_build_pairing_cmd, /* 0x02: pairing response */ + smp_build_confirm_cmd, /* 0x03: pairing confirm */ + smp_build_rand_cmd, /* 0x04: pairing random */ + smp_build_pairing_fail, /* 0x05: pairing failure */ + smp_build_encrypt_info_cmd, /* 0x06: encryption information */ + smp_build_central_id_cmd, /* 0x07: central identification */ + smp_build_identity_info_cmd, /* 0x08: identity information */ + smp_build_id_addr_cmd, /* 0x09: identity address information */ + smp_build_signing_info_cmd, /* 0x0A: signing information */ + smp_build_security_request, /* 0x0B: security request */ + smp_build_pair_public_key_cmd, /* 0x0C: pairing public key */ + smp_build_pair_dhkey_check_cmd, /* 0x0D: pairing DHKey check */ + smp_build_pairing_keypress_notification_cmd, /* 0x0E: pairing keypress + notification */ + smp_build_pairing_commitment_cmd /* 0x0F: pairing commitment */ }; -static const tSMP_ASSO_MODEL - smp_association_table[2][SMP_IO_CAP_MAX][SMP_IO_CAP_MAX] = { +static const tSMP_ASSO_MODEL smp_association_table[2][SMP_IO_CAP_MAX][SMP_IO_CAP_MAX] = { /* display only */ /* Display Yes/No */ /* keyboard only */ /* No Input/Output */ /* keyboard display */ /* initiator */ /* model = tbl[peer_io_caps][loc_io_caps] */ /* Display Only */ - {{SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_ENCRYPTION_ONLY, - SMP_MODEL_PASSKEY, SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_PASSKEY}, + {{SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_PASSKEY, + SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_PASSKEY}, /* Display Yes/No */ - {SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_ENCRYPTION_ONLY, - SMP_MODEL_PASSKEY, SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_PASSKEY}, + {SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_PASSKEY, + SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_PASSKEY}, /* Keyboard only */ - {SMP_MODEL_KEY_NOTIF, SMP_MODEL_KEY_NOTIF, SMP_MODEL_PASSKEY, - SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_KEY_NOTIF}, + {SMP_MODEL_KEY_NOTIF, SMP_MODEL_KEY_NOTIF, SMP_MODEL_PASSKEY, SMP_MODEL_ENCRYPTION_ONLY, + SMP_MODEL_KEY_NOTIF}, /* No Input No Output */ - {SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_ENCRYPTION_ONLY, - SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_ENCRYPTION_ONLY, - SMP_MODEL_ENCRYPTION_ONLY}, + {SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_ENCRYPTION_ONLY, + SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_ENCRYPTION_ONLY}, /* keyboard display */ - {SMP_MODEL_KEY_NOTIF, SMP_MODEL_KEY_NOTIF, SMP_MODEL_PASSKEY, - SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_KEY_NOTIF}}, + {SMP_MODEL_KEY_NOTIF, SMP_MODEL_KEY_NOTIF, SMP_MODEL_PASSKEY, SMP_MODEL_ENCRYPTION_ONLY, + SMP_MODEL_KEY_NOTIF}}, /* responder */ /* model = tbl[loc_io_caps][peer_io_caps] */ /* Display Only */ - {{SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_ENCRYPTION_ONLY, - SMP_MODEL_KEY_NOTIF, SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_KEY_NOTIF}, + {{SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_KEY_NOTIF, + SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_KEY_NOTIF}, /* Display Yes/No */ - {SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_ENCRYPTION_ONLY, - SMP_MODEL_KEY_NOTIF, SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_KEY_NOTIF}, + {SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_KEY_NOTIF, + SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_KEY_NOTIF}, /* keyboard only */ - {SMP_MODEL_PASSKEY, SMP_MODEL_PASSKEY, SMP_MODEL_PASSKEY, - SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_PASSKEY}, + {SMP_MODEL_PASSKEY, SMP_MODEL_PASSKEY, SMP_MODEL_PASSKEY, SMP_MODEL_ENCRYPTION_ONLY, + SMP_MODEL_PASSKEY}, /* No Input No Output */ - {SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_ENCRYPTION_ONLY, - SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_ENCRYPTION_ONLY, - SMP_MODEL_ENCRYPTION_ONLY}, + {SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_ENCRYPTION_ONLY, + SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_ENCRYPTION_ONLY}, /* keyboard display */ - {SMP_MODEL_PASSKEY, SMP_MODEL_PASSKEY, SMP_MODEL_KEY_NOTIF, - SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_PASSKEY}}}; + {SMP_MODEL_PASSKEY, SMP_MODEL_PASSKEY, SMP_MODEL_KEY_NOTIF, SMP_MODEL_ENCRYPTION_ONLY, + SMP_MODEL_PASSKEY}}}; -static const tSMP_ASSO_MODEL - smp_association_table_sc[2][SMP_IO_CAP_MAX][SMP_IO_CAP_MAX] = { +static const tSMP_ASSO_MODEL smp_association_table_sc[2][SMP_IO_CAP_MAX][SMP_IO_CAP_MAX] = { /* display only */ /* Display Yes/No */ /* keyboard only */ /* No InputOutput */ /* keyboard display */ @@ -258,9 +252,8 @@ static const tSMP_ASSO_MODEL SMP_MODEL_SEC_CONN_PASSKEY_ENT}, /* Display Yes/No */ - {SMP_MODEL_SEC_CONN_JUSTWORKS, SMP_MODEL_SEC_CONN_NUM_COMP, - SMP_MODEL_SEC_CONN_PASSKEY_ENT, SMP_MODEL_SEC_CONN_JUSTWORKS, - SMP_MODEL_SEC_CONN_NUM_COMP}, + {SMP_MODEL_SEC_CONN_JUSTWORKS, SMP_MODEL_SEC_CONN_NUM_COMP, SMP_MODEL_SEC_CONN_PASSKEY_ENT, + SMP_MODEL_SEC_CONN_JUSTWORKS, SMP_MODEL_SEC_CONN_NUM_COMP}, /* keyboard only */ {SMP_MODEL_SEC_CONN_PASSKEY_DISP, SMP_MODEL_SEC_CONN_PASSKEY_DISP, @@ -268,9 +261,8 @@ static const tSMP_ASSO_MODEL SMP_MODEL_SEC_CONN_PASSKEY_DISP}, /* No Input No Output */ - {SMP_MODEL_SEC_CONN_JUSTWORKS, SMP_MODEL_SEC_CONN_JUSTWORKS, - SMP_MODEL_SEC_CONN_JUSTWORKS, SMP_MODEL_SEC_CONN_JUSTWORKS, - SMP_MODEL_SEC_CONN_JUSTWORKS}, + {SMP_MODEL_SEC_CONN_JUSTWORKS, SMP_MODEL_SEC_CONN_JUSTWORKS, SMP_MODEL_SEC_CONN_JUSTWORKS, + SMP_MODEL_SEC_CONN_JUSTWORKS, SMP_MODEL_SEC_CONN_JUSTWORKS}, /* keyboard display */ {SMP_MODEL_SEC_CONN_PASSKEY_DISP, SMP_MODEL_SEC_CONN_NUM_COMP, @@ -296,9 +288,8 @@ static const tSMP_ASSO_MODEL SMP_MODEL_SEC_CONN_PASSKEY_ENT}, /* No Input No Output */ - {SMP_MODEL_SEC_CONN_JUSTWORKS, SMP_MODEL_SEC_CONN_JUSTWORKS, - SMP_MODEL_SEC_CONN_JUSTWORKS, SMP_MODEL_SEC_CONN_JUSTWORKS, - SMP_MODEL_SEC_CONN_JUSTWORKS}, + {SMP_MODEL_SEC_CONN_JUSTWORKS, SMP_MODEL_SEC_CONN_JUSTWORKS, SMP_MODEL_SEC_CONN_JUSTWORKS, + SMP_MODEL_SEC_CONN_JUSTWORKS, SMP_MODEL_SEC_CONN_JUSTWORKS}, /* keyboard display */ {SMP_MODEL_SEC_CONN_PASSKEY_ENT, SMP_MODEL_SEC_CONN_NUM_COMP, @@ -306,8 +297,7 @@ static const tSMP_ASSO_MODEL SMP_MODEL_SEC_CONN_NUM_COMP}}}; static tSMP_ASSO_MODEL smp_select_legacy_association_model(tSMP_CB* p_cb); -static tSMP_ASSO_MODEL smp_select_association_model_secure_connections( - tSMP_CB* p_cb); +static tSMP_ASSO_MODEL smp_select_association_model_secure_connections(tSMP_CB* p_cb); /** * Log metrics data for SMP command @@ -317,8 +307,8 @@ static tSMP_ASSO_MODEL smp_select_association_model_secure_connections( * @param p_buf buffer to the beginning of SMP command * @param buf_len length available to read for p_buf */ -void smp_log_metrics(const RawAddress& bd_addr, bool is_outgoing, - const uint8_t* p_buf, size_t buf_len, bool is_over_br) { +void smp_log_metrics(const RawAddress& bd_addr, bool is_outgoing, const uint8_t* p_buf, + size_t buf_len, bool is_over_br) { if (buf_len < 1) { log::warn("buffer is too small"); return; @@ -331,16 +321,14 @@ void smp_log_metrics(const RawAddress& bd_addr, bool is_outgoing, STREAM_TO_UINT8(failure_reason, p_buf); } if (smp_cb.is_pair_cancel) { - failure_reason = SMP_USER_CANCELLED; // Tracking pairing cancellations + failure_reason = SMP_USER_CANCELLED; // Tracking pairing cancellations } - uint16_t metric_cmd = - is_over_br ? SMP_METRIC_COMMAND_BR_FLAG : SMP_METRIC_COMMAND_LE_FLAG; + uint16_t metric_cmd = is_over_br ? SMP_METRIC_COMMAND_BR_FLAG : SMP_METRIC_COMMAND_LE_FLAG; metric_cmd |= static_cast(raw_cmd); android::bluetooth::DirectionEnum direction = - is_outgoing ? android::bluetooth::DirectionEnum::DIRECTION_OUTGOING - : android::bluetooth::DirectionEnum::DIRECTION_INCOMING; - log_smp_pairing_event(bd_addr, metric_cmd, direction, - static_cast(failure_reason)); + is_outgoing ? android::bluetooth::DirectionEnum::DIRECTION_OUTGOING + : android::bluetooth::DirectionEnum::DIRECTION_INCOMING; + log_smp_pairing_event(bd_addr, metric_cmd, direction, static_cast(failure_reason)); } /******************************************************************************* @@ -360,8 +348,7 @@ bool smp_send_msg_to_L2CAP(const RawAddress& rem_bda, BT_HDR* p_toL2CAP) { log::verbose("rem_bda:{}, over_bredr:{}", rem_bda, smp_cb.smp_over_br); - smp_log_metrics(rem_bda, true /* outgoing */, - p_toL2CAP->data + p_toL2CAP->offset, p_toL2CAP->len, + smp_log_metrics(rem_bda, true /* outgoing */, p_toL2CAP->data + p_toL2CAP->offset, p_toL2CAP->len, smp_cb.smp_over_br /* is_over_br */); if (com::android::bluetooth::flags::l2cap_tx_complete_cb_info()) { @@ -410,8 +397,7 @@ bool smp_send_cmd(uint8_t cmd_code, tSMP_CB* p_cb) { bool sent = false; log::debug("Sending SMP command:{}[0x{:x}] pairing_bda={}", - smp_opcode_text(static_cast(cmd_code)), cmd_code, - p_cb->pairing_bda); + smp_opcode_text(static_cast(cmd_code)), cmd_code, p_cb->pairing_bda); if (cmd_code <= (SMP_OPCODE_MAX + 1 /* for SMP_OPCODE_PAIR_COMMITM */) && smp_cmd_build_act[cmd_code] != NULL) { @@ -419,8 +405,8 @@ bool smp_send_cmd(uint8_t cmd_code, tSMP_CB* p_cb) { if (p_buf != NULL && smp_send_msg_to_L2CAP(p_cb->pairing_bda, p_buf)) { sent = true; - alarm_set_on_mloop(p_cb->smp_rsp_timer_ent, SMP_WAIT_FOR_RSP_TIMEOUT_MS, - smp_rsp_timeout, NULL); + alarm_set_on_mloop(p_cb->smp_rsp_timer_ent, SMP_WAIT_FOR_RSP_TIMEOUT_MS, smp_rsp_timeout, + NULL); } } @@ -491,11 +477,9 @@ void smp_delayed_auth_complete_timeout(void* /* data */) { ******************************************************************************/ BT_HDR* smp_build_pairing_cmd(uint8_t cmd_code, tSMP_CB* p_cb) { uint8_t* p; - BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + SMP_PAIRING_REQ_SIZE + - L2CAP_MIN_OFFSET); + BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + SMP_PAIRING_REQ_SIZE + L2CAP_MIN_OFFSET); - log::verbose("building cmd:{}", - smp_opcode_text(static_cast(cmd_code))); + log::verbose("building cmd:{}", smp_opcode_text(static_cast(cmd_code))); p = (uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET; UINT8_TO_STREAM(p, cmd_code); @@ -522,8 +506,7 @@ BT_HDR* smp_build_pairing_cmd(uint8_t cmd_code, tSMP_CB* p_cb) { ******************************************************************************/ static BT_HDR* smp_build_confirm_cmd(uint8_t /* cmd_code */, tSMP_CB* p_cb) { uint8_t* p; - BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + SMP_CONFIRM_CMD_SIZE + - L2CAP_MIN_OFFSET); + BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + SMP_CONFIRM_CMD_SIZE + L2CAP_MIN_OFFSET); log::verbose("addr:{}", p_cb->pairing_bda); @@ -547,8 +530,7 @@ static BT_HDR* smp_build_confirm_cmd(uint8_t /* cmd_code */, tSMP_CB* p_cb) { ******************************************************************************/ static BT_HDR* smp_build_rand_cmd(uint8_t /* cmd_code */, tSMP_CB* p_cb) { uint8_t* p; - BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + SMP_RAND_CMD_SIZE + - L2CAP_MIN_OFFSET); + BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + SMP_RAND_CMD_SIZE + L2CAP_MIN_OFFSET); log::verbose("addr:{}", p_cb->pairing_bda); @@ -569,11 +551,9 @@ static BT_HDR* smp_build_rand_cmd(uint8_t /* cmd_code */, tSMP_CB* p_cb) { * Description Build security information command. * ******************************************************************************/ -static BT_HDR* smp_build_encrypt_info_cmd(uint8_t /* cmd_code */, - tSMP_CB* p_cb) { +static BT_HDR* smp_build_encrypt_info_cmd(uint8_t /* cmd_code */, tSMP_CB* p_cb) { uint8_t* p; - BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + SMP_ENC_INFO_SIZE + - L2CAP_MIN_OFFSET); + BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + SMP_ENC_INFO_SIZE + L2CAP_MIN_OFFSET); log::verbose("addr:{}", p_cb->pairing_bda); @@ -596,8 +576,7 @@ static BT_HDR* smp_build_encrypt_info_cmd(uint8_t /* cmd_code */, ******************************************************************************/ static BT_HDR* smp_build_central_id_cmd(uint8_t /* cmd_code */, tSMP_CB* p_cb) { uint8_t* p; - BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + SMP_CENTRAL_ID_SIZE + - L2CAP_MIN_OFFSET); + BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + SMP_CENTRAL_ID_SIZE + L2CAP_MIN_OFFSET); log::verbose("addr:{}", p_cb->pairing_bda); @@ -619,11 +598,9 @@ static BT_HDR* smp_build_central_id_cmd(uint8_t /* cmd_code */, tSMP_CB* p_cb) { * Description Build identity information command. * ******************************************************************************/ -static BT_HDR* smp_build_identity_info_cmd(uint8_t /* cmd_code */, - tSMP_CB* p_cb) { +static BT_HDR* smp_build_identity_info_cmd(uint8_t /* cmd_code */, tSMP_CB* p_cb) { uint8_t* p; - BT_HDR* p_buf = - (BT_HDR*)osi_malloc(sizeof(BT_HDR) + SMP_ID_INFO_SIZE + L2CAP_MIN_OFFSET); + BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + SMP_ID_INFO_SIZE + L2CAP_MIN_OFFSET); log::verbose("addr:{}", p_cb->pairing_bda); @@ -649,16 +626,14 @@ static BT_HDR* smp_build_identity_info_cmd(uint8_t /* cmd_code */, ******************************************************************************/ static BT_HDR* smp_build_id_addr_cmd(uint8_t /* cmd_code */, tSMP_CB* p_cb) { uint8_t* p; - BT_HDR* p_buf = - (BT_HDR*)osi_malloc(sizeof(BT_HDR) + SMP_ID_ADDR_SIZE + L2CAP_MIN_OFFSET); + BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + SMP_ID_ADDR_SIZE + L2CAP_MIN_OFFSET); log::verbose("addr:{}", p_cb->pairing_bda); p = (uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET; UINT8_TO_STREAM(p, SMP_OPCODE_ID_ADDR); UINT8_TO_STREAM(p, 0); - BDADDR_TO_STREAM(p, bluetooth::ToRawAddress( - bluetooth::shim::GetController()->GetMacAddress())); + BDADDR_TO_STREAM(p, bluetooth::ToRawAddress(bluetooth::shim::GetController()->GetMacAddress())); p_buf->offset = L2CAP_MIN_OFFSET; p_buf->len = SMP_ID_ADDR_SIZE; @@ -673,11 +648,9 @@ static BT_HDR* smp_build_id_addr_cmd(uint8_t /* cmd_code */, tSMP_CB* p_cb) { * Description Build signing information command. * ******************************************************************************/ -static BT_HDR* smp_build_signing_info_cmd(uint8_t /* cmd_code */, - tSMP_CB* p_cb) { +static BT_HDR* smp_build_signing_info_cmd(uint8_t /* cmd_code */, tSMP_CB* p_cb) { uint8_t* p; - BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + SMP_SIGN_INFO_SIZE + - L2CAP_MIN_OFFSET); + BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + SMP_SIGN_INFO_SIZE + L2CAP_MIN_OFFSET); log::verbose("addr:{}", p_cb->pairing_bda); @@ -700,8 +673,7 @@ static BT_HDR* smp_build_signing_info_cmd(uint8_t /* cmd_code */, ******************************************************************************/ static BT_HDR* smp_build_pairing_fail(uint8_t /* cmd_code */, tSMP_CB* p_cb) { uint8_t* p; - BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + SMP_PAIR_FAIL_SIZE + - L2CAP_MIN_OFFSET); + BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + SMP_PAIR_FAIL_SIZE + L2CAP_MIN_OFFSET); log::verbose("addr:{}", p_cb->pairing_bda); @@ -722,8 +694,7 @@ static BT_HDR* smp_build_pairing_fail(uint8_t /* cmd_code */, tSMP_CB* p_cb) { * Description Build security request command. * ******************************************************************************/ -static BT_HDR* smp_build_security_request(uint8_t /* cmd_code */, - tSMP_CB* p_cb) { +static BT_HDR* smp_build_security_request(uint8_t /* cmd_code */, tSMP_CB* p_cb) { uint8_t* p; BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + 2 + L2CAP_MIN_OFFSET); @@ -736,8 +707,7 @@ static BT_HDR* smp_build_security_request(uint8_t /* cmd_code */, p_buf->offset = L2CAP_MIN_OFFSET; p_buf->len = SMP_SECURITY_REQUEST_SIZE; - log::verbose("opcode={} auth_req=0x{:x}", SMP_OPCODE_SEC_REQ, - p_cb->loc_auth_req); + log::verbose("opcode={} auth_req=0x{:x}", SMP_OPCODE_SEC_REQ, p_cb->loc_auth_req); return p_buf; } @@ -749,13 +719,11 @@ static BT_HDR* smp_build_security_request(uint8_t /* cmd_code */, * Description Build pairing public key command. * ******************************************************************************/ -static BT_HDR* smp_build_pair_public_key_cmd(uint8_t /* cmd_code */, - tSMP_CB* p_cb) { +static BT_HDR* smp_build_pair_public_key_cmd(uint8_t /* cmd_code */, tSMP_CB* p_cb) { uint8_t* p; uint8_t publ_key[2 * BT_OCTET32_LEN]; uint8_t* p_publ_key = publ_key; - BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + SMP_PAIR_PUBL_KEY_SIZE + - L2CAP_MIN_OFFSET); + BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + SMP_PAIR_PUBL_KEY_SIZE + L2CAP_MIN_OFFSET); log::verbose("addr:{}", p_cb->pairing_bda); @@ -779,11 +747,9 @@ static BT_HDR* smp_build_pair_public_key_cmd(uint8_t /* cmd_code */, * Description Build pairing commitment command. * ******************************************************************************/ -static BT_HDR* smp_build_pairing_commitment_cmd(uint8_t /* cmd_code */, - tSMP_CB* p_cb) { +static BT_HDR* smp_build_pairing_commitment_cmd(uint8_t /* cmd_code */, tSMP_CB* p_cb) { uint8_t* p; - BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + SMP_PAIR_COMMITM_SIZE + - L2CAP_MIN_OFFSET); + BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + SMP_PAIR_COMMITM_SIZE + L2CAP_MIN_OFFSET); log::verbose("addr:{}", p_cb->pairing_bda); @@ -804,11 +770,10 @@ static BT_HDR* smp_build_pairing_commitment_cmd(uint8_t /* cmd_code */, * Description Build pairing DHKey check command. * ******************************************************************************/ -static BT_HDR* smp_build_pair_dhkey_check_cmd(uint8_t /* cmd_code */, - tSMP_CB* p_cb) { +static BT_HDR* smp_build_pair_dhkey_check_cmd(uint8_t /* cmd_code */, tSMP_CB* p_cb) { uint8_t* p; - BT_HDR* p_buf = (BT_HDR*)osi_malloc( - sizeof(BT_HDR) + SMP_PAIR_DHKEY_CHECK_SIZE + L2CAP_MIN_OFFSET); + BT_HDR* p_buf = + (BT_HDR*)osi_malloc(sizeof(BT_HDR) + SMP_PAIR_DHKEY_CHECK_SIZE + L2CAP_MIN_OFFSET); log::verbose("addr:{}", p_cb->pairing_bda); @@ -829,11 +794,10 @@ static BT_HDR* smp_build_pair_dhkey_check_cmd(uint8_t /* cmd_code */, * Description Build keypress notification command. * ******************************************************************************/ -static BT_HDR* smp_build_pairing_keypress_notification_cmd( - uint8_t /* cmd_code */, tSMP_CB* p_cb) { +static BT_HDR* smp_build_pairing_keypress_notification_cmd(uint8_t /* cmd_code */, tSMP_CB* p_cb) { uint8_t* p; - BT_HDR* p_buf = (BT_HDR*)osi_malloc( - sizeof(BT_HDR) + SMP_PAIR_KEYPR_NOTIF_SIZE + L2CAP_MIN_OFFSET); + BT_HDR* p_buf = + (BT_HDR*)osi_malloc(sizeof(BT_HDR) + SMP_PAIR_KEYPR_NOTIF_SIZE + L2CAP_MIN_OFFSET); log::verbose("addr:{}", p_cb->pairing_bda); @@ -868,8 +832,9 @@ void smp_convert_string_to_tk(Octet16* tk, uint32_t passkey) { void smp_mask_enc_key(uint8_t loc_enc_size, Octet16* p_data) { log::verbose("smp_mask_enc_key"); if (loc_enc_size < OCTET16_LEN) { - for (; loc_enc_size < OCTET16_LEN; loc_enc_size++) + for (; loc_enc_size < OCTET16_LEN; loc_enc_size++) { (*p_data)[loc_enc_size] = 0; + } } return; } @@ -901,10 +866,11 @@ void tSMP_CB::init(uint8_t security_mode) { p_256_init_curve(); /* Initialize failure case for certification */ - smp_cb.cert_failure = static_cast( - stack_config_get_interface()->get_pts_smp_failure_case()); - if (smp_cb.cert_failure) + smp_cb.cert_failure = + static_cast(stack_config_get_interface()->get_pts_smp_failure_case()); + if (smp_cb.cert_failure) { log::error("PTS FAILURE MODE IN EFFECT (CASE {})", smp_cb.cert_failure); + } } /******************************************************************************* @@ -950,13 +916,13 @@ void smp_remove_fixed_channel(tSMP_CB* p_cb) { if (p_cb->smp_over_br) { if (!L2CA_RemoveFixedChnl(L2CAP_SMP_BR_CID, p_cb->pairing_bda)) { - log::error("Unable to remove L2CAP fixed channel peer:{} cid:{}", - p_cb->pairing_bda, L2CAP_SMP_BR_CID); + log::error("Unable to remove L2CAP fixed channel peer:{} cid:{}", p_cb->pairing_bda, + L2CAP_SMP_BR_CID); } } else { if (!L2CA_RemoveFixedChnl(L2CAP_SMP_CID, p_cb->pairing_bda)) { - log::error("Unable to remove L2CAP fixed channel peer:{} cid:{}", - p_cb->pairing_bda, L2CAP_SMP_CID); + log::error("Unable to remove L2CAP fixed channel peer:{} cid:{}", p_cb->pairing_bda, + L2CAP_SMP_CID); } } } @@ -981,11 +947,9 @@ void smp_reset_control_value(tSMP_CB* p_cb) { usually service discovery will follow authentication complete, to avoid racing condition for a link down/up, set link idle timer to be SMP_LINK_TOUT_MIN to guarantee SMP key exchange */ - if (!L2CA_SetIdleTimeoutByBdAddr(p_cb->pairing_bda, SMP_LINK_TOUT_MIN, - BT_TRANSPORT_LE)) { - log::warn( - "Unable to set L2CAP idle timeout peer:{} transport:{} timeout:{}", - p_cb->pairing_bda, BT_TRANSPORT_LE, SMP_LINK_TOUT_MIN); + if (!L2CA_SetIdleTimeoutByBdAddr(p_cb->pairing_bda, SMP_LINK_TOUT_MIN, BT_TRANSPORT_LE)) { + log::warn("Unable to set L2CAP idle timeout peer:{} transport:{} timeout:{}", p_cb->pairing_bda, + BT_TRANSPORT_LE, SMP_LINK_TOUT_MIN); } /* We can tell L2CAP to remove the fixed channel (if it has one) */ @@ -1008,49 +972,43 @@ void smp_proc_pairing_cmpl(tSMP_CB* p_cb) { const RawAddress pairing_bda = p_cb->pairing_bda; const tSMP_EVT_DATA evt_data = { - .cmplt = - { - .reason = p_cb->status, - .sec_level = (p_cb->status == SMP_SUCCESS) ? p_cb->sec_level - : SMP_SEC_NONE, - .is_pair_cancel = p_cb->is_pair_cancel, - .smp_over_br = p_cb->smp_over_br, - }, + .cmplt = + { + .reason = p_cb->status, + .sec_level = + (p_cb->status == SMP_SUCCESS) ? p_cb->sec_level : SMP_SEC_NONE, + .is_pair_cancel = p_cb->is_pair_cancel, + .smp_over_br = p_cb->smp_over_br, + }, }; if (p_cb->status == SMP_SUCCESS) { log::debug( - "Pairing process has completed successfully remote:{} " - "sec_level:0x{:0x}", - p_cb->pairing_bda, evt_data.cmplt.sec_level); + "Pairing process has completed successfully remote:{} " + "sec_level:0x{:0x}", + p_cb->pairing_bda, evt_data.cmplt.sec_level); BTM_LogHistory(kBtmLogTag, pairing_bda, "Pairing success"); } else { log::warn( - "Pairing process has failed to remote:{} smp_reason:{} " - "sec_level:0x{:0x}", - p_cb->pairing_bda, smp_status_text(evt_data.cmplt.reason), - evt_data.cmplt.sec_level); - BTM_LogHistory( - kBtmLogTag, pairing_bda, "Pairing failed", - base::StringPrintf("reason:%s", - smp_status_text(evt_data.cmplt.reason).c_str())); + "Pairing process has failed to remote:{} smp_reason:{} " + "sec_level:0x{:0x}", + p_cb->pairing_bda, smp_status_text(evt_data.cmplt.reason), evt_data.cmplt.sec_level); + BTM_LogHistory(kBtmLogTag, pairing_bda, "Pairing failed", + base::StringPrintf("reason:%s", smp_status_text(evt_data.cmplt.reason).c_str())); } // Log pairing complete event { - auto direction = - p_cb->flags & SMP_PAIR_FLAGS_WE_STARTED_DD - ? android::bluetooth::DirectionEnum::DIRECTION_OUTGOING - : android::bluetooth::DirectionEnum::DIRECTION_INCOMING; - uint16_t metric_cmd = p_cb->smp_over_br - ? SMP_METRIC_COMMAND_BR_PAIRING_CMPL - : SMP_METRIC_COMMAND_LE_PAIRING_CMPL; + auto direction = p_cb->flags & SMP_PAIR_FLAGS_WE_STARTED_DD + ? android::bluetooth::DirectionEnum::DIRECTION_OUTGOING + : android::bluetooth::DirectionEnum::DIRECTION_INCOMING; + uint16_t metric_cmd = p_cb->smp_over_br ? SMP_METRIC_COMMAND_BR_PAIRING_CMPL + : SMP_METRIC_COMMAND_LE_PAIRING_CMPL; uint16_t metric_status = p_cb->status; if (metric_status > SMP_MAX_FAIL_RSN_PER_SPEC) { metric_status |= SMP_METRIC_STATUS_INTERNAL_FLAG; } - log_smp_pairing_event(p_cb->pairing_bda, metric_cmd, direction, - metric_status); + log_smp_pairing_event(p_cb->pairing_bda, metric_cmd, direction, metric_status); } if (p_cb->status == SMP_SUCCESS && p_cb->smp_over_br) { @@ -1059,7 +1017,9 @@ void smp_proc_pairing_cmpl(tSMP_CB* p_cb) { smp_reset_control_value(p_cb); - if (p_callback) (*p_callback)(SMP_COMPLT_EVT, pairing_bda, &evt_data); + if (p_callback) { + (*p_callback)(SMP_COMPLT_EVT, pairing_bda, &evt_data); + } } /******************************************************************************* @@ -1140,9 +1100,9 @@ bool smp_command_has_valid_fixed_length(tSMP_CB* p_cb) { if (p_cb->rcvd_cmd_len != smp_cmd_size_per_spec[cmd_code]) { log::warn( - "Rcvd from the peer cmd 0x{:02x} with invalid length 0x{:02x} (per " - "spec the length is 0x{:02x}).", - cmd_code, p_cb->rcvd_cmd_len, smp_cmd_size_per_spec[cmd_code]); + "Rcvd from the peer cmd 0x{:02x} with invalid length 0x{:02x} (per " + "spec the length is 0x{:02x}).", + cmd_code, p_cb->rcvd_cmd_len, smp_cmd_size_per_spec[cmd_code]); return false; } @@ -1167,42 +1127,40 @@ bool smp_command_has_valid_fixed_length(tSMP_CB* p_cb) { bool smp_pairing_request_response_parameters_are_valid(tSMP_CB* p_cb) { uint8_t io_caps = p_cb->peer_io_caps; uint8_t oob_flag = p_cb->peer_oob_flag; - uint8_t bond_flag = - p_cb->peer_auth_req & 0x03; // 0x03 is gen bond with appropriate mask + uint8_t bond_flag = p_cb->peer_auth_req & 0x03; // 0x03 is gen bond with appropriate mask uint8_t enc_size = p_cb->peer_enc_size; log::verbose("cmd code 0x{:02x}", p_cb->rcvd_cmd_code); if (io_caps >= BTM_IO_CAP_MAX) { log::warn( - "Rcvd from the peer cmd 0x{:02x} with IO Capability value (0x{:02x}) " - "out of range).", - p_cb->rcvd_cmd_code, io_caps); + "Rcvd from the peer cmd 0x{:02x} with IO Capability value (0x{:02x}) " + "out of range).", + p_cb->rcvd_cmd_code, io_caps); return false; } if (!((oob_flag == SMP_OOB_NONE) || (oob_flag == SMP_OOB_PRESENT))) { log::warn( - "Rcvd from the peer cmd 0x{:02x} with OOB data flag value (0x{:02x}) " - "out of range).", - p_cb->rcvd_cmd_code, oob_flag); + "Rcvd from the peer cmd 0x{:02x} with OOB data flag value (0x{:02x}) " + "out of range).", + p_cb->rcvd_cmd_code, oob_flag); return false; } if (!((bond_flag == SMP_AUTH_NO_BOND) || (bond_flag == SMP_AUTH_BOND))) { log::warn( - "Rcvd from the peer cmd 0x{:02x} with Bonding_Flags value (0x{:02x}) " - "out of range).", - p_cb->rcvd_cmd_code, bond_flag); + "Rcvd from the peer cmd 0x{:02x} with Bonding_Flags value (0x{:02x}) " + "out of range).", + p_cb->rcvd_cmd_code, bond_flag); return false; } - if ((enc_size < SMP_ENCR_KEY_SIZE_MIN) || - (enc_size > SMP_ENCR_KEY_SIZE_MAX)) { + if ((enc_size < SMP_ENCR_KEY_SIZE_MIN) || (enc_size > SMP_ENCR_KEY_SIZE_MAX)) { log::warn( - "Rcvd from the peer cmd 0x{:02x} with Maximum Encryption Key value " - "(0x{:02x}) out of range).", - p_cb->rcvd_cmd_code, enc_size); + "Rcvd from the peer cmd 0x{:02x} with Maximum Encryption Key value " + "(0x{:02x}) out of range).", + p_cb->rcvd_cmd_code, enc_size); return false; } @@ -1225,9 +1183,9 @@ bool smp_pairing_keypress_notification_is_valid(tSMP_CB* p_cb) { if (keypress_notification >= SMP_SC_KEY_OUT_OF_RANGE) { log::warn( - "Rcvd from the peer cmd 0x{:02x} with Pairing Keypress Notification " - "value (0x{:02x}) out of range).", - p_cb->rcvd_cmd_code, keypress_notification); + "Rcvd from the peer cmd 0x{:02x} with Pairing Keypress Notification " + "value (0x{:02x}) out of range).", + p_cb->rcvd_cmd_code, keypress_notification); return false; } @@ -1250,9 +1208,7 @@ bool smp_parameter_unconditionally_valid(tSMP_CB* /* p_cb */) { return true; } * Description Always returns false. * ******************************************************************************/ -bool smp_parameter_unconditionally_invalid(tSMP_CB* /* p_cb */) { - return false; -} +bool smp_parameter_unconditionally_invalid(tSMP_CB* /* p_cb */) { return false; } /******************************************************************************* * @@ -1266,8 +1222,7 @@ bool smp_parameter_unconditionally_invalid(tSMP_CB* /* p_cb */) { ******************************************************************************/ void smp_reject_unexpected_pairing_command(const RawAddress& bd_addr) { uint8_t* p; - BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + SMP_PAIR_FAIL_SIZE + - L2CAP_MIN_OFFSET); + BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + SMP_PAIR_FAIL_SIZE + L2CAP_MIN_OFFSET); log::verbose("bd_addr:{}", bd_addr); @@ -1302,27 +1257,24 @@ tSMP_ASSO_MODEL smp_select_association_model(tSMP_CB* p_cb) { tSMP_ASSO_MODEL model = SMP_MODEL_OUT_OF_RANGE; p_cb->sc_mode_required_by_peer = false; - log::verbose("p_cb->peer_io_caps = {} p_cb->local_io_capability = {}", - p_cb->peer_io_caps, p_cb->local_io_capability); - log::verbose("p_cb->peer_oob_flag = {} p_cb->loc_oob_flag = {}", - p_cb->peer_oob_flag, p_cb->loc_oob_flag); - log::verbose("p_cb->peer_auth_req = 0x{:02x} p_cb->loc_auth_req = 0x{:02x}", - p_cb->peer_auth_req, p_cb->loc_auth_req); - log::verbose("p_cb->sc_only_mode_locally_required = {}", - p_cb->sc_only_mode_locally_required); - - if ((p_cb->peer_auth_req & SMP_SC_SUPPORT_BIT) && - (p_cb->loc_auth_req & SMP_SC_SUPPORT_BIT)) { + log::verbose("p_cb->peer_io_caps = {} p_cb->local_io_capability = {}", p_cb->peer_io_caps, + p_cb->local_io_capability); + log::verbose("p_cb->peer_oob_flag = {} p_cb->loc_oob_flag = {}", p_cb->peer_oob_flag, + p_cb->loc_oob_flag); + log::verbose("p_cb->peer_auth_req = 0x{:02x} p_cb->loc_auth_req = 0x{:02x}", p_cb->peer_auth_req, + p_cb->loc_auth_req); + log::verbose("p_cb->sc_only_mode_locally_required = {}", p_cb->sc_only_mode_locally_required); + + if ((p_cb->peer_auth_req & SMP_SC_SUPPORT_BIT) && (p_cb->loc_auth_req & SMP_SC_SUPPORT_BIT)) { p_cb->sc_mode_required_by_peer = true; } - if ((p_cb->peer_auth_req & SMP_H7_SUPPORT_BIT) && - (p_cb->loc_auth_req & SMP_H7_SUPPORT_BIT)) { + if ((p_cb->peer_auth_req & SMP_H7_SUPPORT_BIT) && (p_cb->loc_auth_req & SMP_H7_SUPPORT_BIT)) { p_cb->key_derivation_h7_used = TRUE; } - log::verbose("use_sc_process = {}, h7 use = {}", - p_cb->sc_mode_required_by_peer, p_cb->key_derivation_h7_used); + log::verbose("use_sc_process = {}, h7 use = {}", p_cb->sc_mode_required_by_peer, + p_cb->key_derivation_h7_used); if (p_cb->sc_mode_required_by_peer) { model = smp_select_association_model_secure_connections(p_cb); @@ -1344,25 +1296,22 @@ tSMP_ASSO_MODEL smp_select_legacy_association_model(tSMP_CB* p_cb) { log::verbose("addr:{}", p_cb->pairing_bda); /* if OOB data is present on both devices, then use OOB association model */ - if (p_cb->peer_oob_flag == SMP_OOB_PRESENT && - p_cb->loc_oob_flag == SMP_OOB_PRESENT) + if (p_cb->peer_oob_flag == SMP_OOB_PRESENT && p_cb->loc_oob_flag == SMP_OOB_PRESENT) { return SMP_MODEL_OOB; + } /* else if neither device requires MITM, then use Just Works association model */ - if (SMP_NO_MITM_REQUIRED(p_cb->peer_auth_req) && - SMP_NO_MITM_REQUIRED(p_cb->loc_auth_req)) + if (SMP_NO_MITM_REQUIRED(p_cb->peer_auth_req) && SMP_NO_MITM_REQUIRED(p_cb->loc_auth_req)) { return SMP_MODEL_ENCRYPTION_ONLY; + } /* otherwise use IO capability to select association model */ - if (p_cb->peer_io_caps < SMP_IO_CAP_MAX && - p_cb->local_io_capability < SMP_IO_CAP_MAX) { + if (p_cb->peer_io_caps < SMP_IO_CAP_MAX && p_cb->local_io_capability < SMP_IO_CAP_MAX) { if (p_cb->role == HCI_ROLE_CENTRAL) { - model = smp_association_table[p_cb->role][p_cb->peer_io_caps] - [p_cb->local_io_capability]; + model = smp_association_table[p_cb->role][p_cb->peer_io_caps][p_cb->local_io_capability]; } else { - model = smp_association_table[p_cb->role][p_cb->local_io_capability] - [p_cb->peer_io_caps]; + model = smp_association_table[p_cb->role][p_cb->local_io_capability][p_cb->peer_io_caps]; } } @@ -1382,25 +1331,22 @@ tSMP_ASSO_MODEL smp_select_association_model_secure_connections(tSMP_CB* p_cb) { log::verbose("addr:{}", p_cb->pairing_bda); /* if OOB data is present on at least one device, then use OOB association * model */ - if (p_cb->peer_oob_flag == SMP_OOB_PRESENT || - p_cb->loc_oob_flag == SMP_OOB_PRESENT) + if (p_cb->peer_oob_flag == SMP_OOB_PRESENT || p_cb->loc_oob_flag == SMP_OOB_PRESENT) { return SMP_MODEL_SEC_CONN_OOB; + } /* else if neither device requires MITM, then use Just Works association model */ - if (SMP_NO_MITM_REQUIRED(p_cb->peer_auth_req) && - SMP_NO_MITM_REQUIRED(p_cb->loc_auth_req)) + if (SMP_NO_MITM_REQUIRED(p_cb->peer_auth_req) && SMP_NO_MITM_REQUIRED(p_cb->loc_auth_req)) { return SMP_MODEL_SEC_CONN_JUSTWORKS; + } /* otherwise use IO capability to select association model */ - if (p_cb->peer_io_caps < SMP_IO_CAP_MAX && - p_cb->local_io_capability < SMP_IO_CAP_MAX) { + if (p_cb->peer_io_caps < SMP_IO_CAP_MAX && p_cb->local_io_capability < SMP_IO_CAP_MAX) { if (p_cb->role == HCI_ROLE_CENTRAL) { - model = smp_association_table_sc[p_cb->role][p_cb->peer_io_caps] - [p_cb->local_io_capability]; + model = smp_association_table_sc[p_cb->role][p_cb->peer_io_caps][p_cb->local_io_capability]; } else { - model = smp_association_table_sc[p_cb->role][p_cb->local_io_capability] - [p_cb->peer_io_caps]; + model = smp_association_table_sc[p_cb->role][p_cb->local_io_capability][p_cb->peer_io_caps]; } } @@ -1424,8 +1370,7 @@ uint8_t smp_calculate_random_input(uint8_t* random, uint8_t round) { uint8_t ri; ri = ((random[i] >> j) & 1) | 0x80; - log::verbose("random:0x{:02x}, round:{}, i:{}, j:{}, ri:0x{:02x}", random[i], - round, i, j, ri); + log::verbose("random:0x{:02x}, round:{}, i:{}, j:{}, ri:0x{:02x}", random[i], round, i, j, ri); return ri; } @@ -1550,24 +1495,24 @@ bool smp_check_commitment(tSMP_CB* p_cb) { void smp_save_secure_connections_long_term_key(tSMP_CB* p_cb) { log::verbose("Save LTK as local and peer key"); tBTM_LE_KEY_VALUE lle_key = { - .lenc_key = - { - .ltk = p_cb->ltk, - .div = 0, - .key_size = p_cb->loc_enc_size, - .sec_level = p_cb->sec_level, - }, + .lenc_key = + { + .ltk = p_cb->ltk, + .div = 0, + .key_size = p_cb->loc_enc_size, + .sec_level = p_cb->sec_level, + }, }; btm_sec_save_le_key(p_cb->pairing_bda, BTM_LE_KEY_LENC, &lle_key, true); tBTM_LE_KEY_VALUE ple_key = { - .penc_key = - { - .ltk = p_cb->ltk, - .ediv = 0, - .sec_level = p_cb->sec_level, - .key_size = p_cb->loc_enc_size, - }, + .penc_key = + { + .ltk = p_cb->ltk, + .ediv = 0, + .sec_level = p_cb->sec_level, + .key_size = p_cb->loc_enc_size, + }, }; memset(ple_key.penc_key.rand, 0, BT_OCTET8_LEN); btm_sec_save_le_key(p_cb->pairing_bda, BTM_LE_KEY_PENC, &ple_key, true); @@ -1614,8 +1559,7 @@ bool smp_request_oob_data(tSMP_CB* p_cb) { log::verbose("addr:{}", p_cb->pairing_bda); - if (p_cb->peer_oob_flag == SMP_OOB_PRESENT && - p_cb->loc_oob_flag == SMP_OOB_PRESENT) { + if (p_cb->peer_oob_flag == SMP_OOB_PRESENT && p_cb->loc_oob_flag == SMP_OOB_PRESENT) { /* both local and peer rcvd data OOB */ req_oob_type = SMP_OOB_BOTH; } else if (p_cb->peer_oob_flag == SMP_OOB_PRESENT) { @@ -1627,7 +1571,9 @@ bool smp_request_oob_data(tSMP_CB* p_cb) { log::verbose("req_oob_type={}", req_oob_type); - if (req_oob_type == SMP_OOB_INVALID_TYPE) return false; + if (req_oob_type == SMP_OOB_INVALID_TYPE) { + return false; + } p_cb->req_oob_type = req_oob_type; p_cb->cb_evt = SMP_SC_OOB_REQ_EVT; @@ -1643,8 +1589,7 @@ void print128(const Octet16& x, const char* key_name) { log::info("{}(MSB~LSB):", key_name); for (int i = 0; i < 4; i++) { - log::info("{:02x}:{:02x}:{:02x}:{:02x}", p[OCTET16_LEN - i * 4 - 1], - p[OCTET16_LEN - i * 4 - 2], p[OCTET16_LEN - i * 4 - 3], - p[OCTET16_LEN - i * 4 - 4]); + log::info("{:02x}:{:02x}:{:02x}:{:02x}", p[OCTET16_LEN - i * 4 - 1], p[OCTET16_LEN - i * 4 - 2], + p[OCTET16_LEN - i * 4 - 3], p[OCTET16_LEN - i * 4 - 4]); } } diff --git a/system/stack/srvc/srvc_dis.cc b/system/stack/srvc/srvc_dis.cc index a55dc6ac85a..4b118c719af 100644 --- a/system/stack/srvc/srvc_dis.cc +++ b/system/stack/srvc/srvc_dis.cc @@ -40,8 +40,7 @@ using namespace bluetooth; #define DIS_MAX_ATTR_NUM (DIS_MAX_CHAR_NUM * 2 + DIS_MAX_NUM_INC_SVR + 1) #ifndef DIS_ATTR_DB_SIZE -#define DIS_ATTR_DB_SIZE \ - GATT_DB_MEM_SIZE(DIS_MAX_NUM_INC_SVR, DIS_MAX_CHAR_NUM, 0) +#define DIS_ATTR_DB_SIZE GATT_DB_MEM_SIZE(DIS_MAX_NUM_INC_SVR, DIS_MAX_CHAR_NUM, 0) #endif #define uint64_t_TO_STREAM(p, u64) \ @@ -57,15 +56,9 @@ using namespace bluetooth; } static const uint16_t dis_attr_uuid[DIS_MAX_CHAR_NUM] = { - GATT_UUID_SYSTEM_ID, - GATT_UUID_MODEL_NUMBER_STR, - GATT_UUID_SERIAL_NUMBER_STR, - GATT_UUID_FW_VERSION_STR, - GATT_UUID_HW_VERSION_STR, - GATT_UUID_SW_VERSION_STR, - GATT_UUID_MANU_NAME, - GATT_UUID_IEEE_DATA, - GATT_UUID_PNP_ID}; + GATT_UUID_SYSTEM_ID, GATT_UUID_MODEL_NUMBER_STR, GATT_UUID_SERIAL_NUMBER_STR, + GATT_UUID_FW_VERSION_STR, GATT_UUID_HW_VERSION_STR, GATT_UUID_SW_VERSION_STR, + GATT_UUID_MANU_NAME, GATT_UUID_IEEE_DATA, GATT_UUID_PNP_ID}; tDIS_CB dis_cb; @@ -100,27 +93,26 @@ static tDIS_ATTR_MASK dis_uuid_to_attr(uint16_t uuid) { * validate a handle to be a DIS attribute handle or not. ******************************************************************************/ bool dis_valid_handle_range(uint16_t handle) { - if (handle >= dis_cb.service_handle && handle <= dis_cb.max_handle) + if (handle >= dis_cb.service_handle && handle <= dis_cb.max_handle) { return true; - else + } else { return false; + } } /******************************************************************************* * dis_write_attr_value * * Process write DIS attribute request. ******************************************************************************/ -uint8_t dis_write_attr_value(tGATT_WRITE_REQ* /* p_data */, - tGATT_STATUS* p_status) { +uint8_t dis_write_attr_value(tGATT_WRITE_REQ* /* p_data */, tGATT_STATUS* p_status) { *p_status = GATT_WRITE_NOT_PERMIT; return SRVC_ACT_RSP; } /******************************************************************************* * DIS Attributes Database Server Request callback ******************************************************************************/ -uint8_t dis_read_attr_value(uint8_t /* clcb_idx */, uint16_t handle, - tGATT_VALUE* p_value, bool is_long, - tGATT_STATUS* p_status) { +uint8_t dis_read_attr_value(uint8_t /* clcb_idx */, uint16_t handle, tGATT_VALUE* p_value, + bool is_long, tGATT_STATUS* p_status) { tDIS_DB_ENTRY* p_db_attr = dis_cb.dis_attr; uint8_t *p = p_value->value, i, *pp; uint16_t offset = p_value->offset; @@ -129,8 +121,7 @@ uint8_t dis_read_attr_value(uint8_t /* clcb_idx */, uint16_t handle, for (i = 0; i < DIS_MAX_CHAR_NUM; i++, p_db_attr++) { if (handle == p_db_attr->handle) { - if ((p_db_attr->uuid == GATT_UUID_PNP_ID || - p_db_attr->uuid == GATT_UUID_SYSTEM_ID) && + if ((p_db_attr->uuid == GATT_UUID_PNP_ID || p_db_attr->uuid == GATT_UUID_SYSTEM_ID) && is_long) { st = GATT_NOT_LONG; break; @@ -145,15 +136,16 @@ uint8_t dis_read_attr_value(uint8_t /* clcb_idx */, uint16_t handle, case GATT_UUID_HW_VERSION_STR: case GATT_UUID_SW_VERSION_STR: case GATT_UUID_IEEE_DATA: - pp = dis_cb.dis_value - .data_string[p_db_attr->uuid - GATT_UUID_MODEL_NUMBER_STR]; + pp = dis_cb.dis_value.data_string[p_db_attr->uuid - GATT_UUID_MODEL_NUMBER_STR]; if (pp != NULL) { - if (strlen((char*)pp) > GATT_MAX_ATTR_LEN) + if (strlen((char*)pp) > GATT_MAX_ATTR_LEN) { p_value->len = GATT_MAX_ATTR_LEN; - else + } else { p_value->len = (uint16_t)strlen((char*)pp); - } else + } + } else { p_value->len = 0; + } if (offset > p_value->len) { st = GATT_INVALID_OFFSET; @@ -203,8 +195,7 @@ static void dis_gatt_c_read_dis_value_cmpl(uint16_t conn_id) { srvc_eng_release_channel(conn_id); if (dis_cb.p_read_dis_cback && p_clcb) { - log::info("conn_id:{} attr_mask = 0x{:04x}", conn_id, - p_clcb->dis_value.attr_mask); + log::info("conn_id:{} attr_mask = 0x{:04x}", conn_id, p_clcb->dis_value.attr_mask); (*dis_cb.p_read_dis_cback)(p_clcb->bda, &p_clcb->dis_value); dis_cb.p_read_dis_cback = NULL; @@ -230,13 +221,12 @@ bool dis_gatt_c_read_dis_req(uint16_t conn_id) { param.service.auth_req = 0; while (dis_cb.dis_read_uuid_idx < DIS_MAX_CHAR_NUM) { - if (dis_uuid_to_attr(dis_attr_uuid[dis_cb.dis_read_uuid_idx]) & - dis_cb.request_mask) { - param.service.uuid = - bluetooth::Uuid::From16Bit(dis_attr_uuid[dis_cb.dis_read_uuid_idx]); + if (dis_uuid_to_attr(dis_attr_uuid[dis_cb.dis_read_uuid_idx]) & dis_cb.request_mask) { + param.service.uuid = bluetooth::Uuid::From16Bit(dis_attr_uuid[dis_cb.dis_read_uuid_idx]); - if (GATTC_Read(conn_id, GATT_READ_BY_TYPE, ¶m) == GATT_SUCCESS) + if (GATTC_Read(conn_id, GATT_READ_BY_TYPE, ¶m) == GATT_SUCCESS) { return true; + } log::error("Read DISInfo: {} GATT_Read Failed", param.service.uuid); } @@ -246,7 +236,7 @@ bool dis_gatt_c_read_dis_req(uint16_t conn_id) { dis_gatt_c_read_dis_value_cmpl(conn_id); - return (false); + return false; } /******************************************************************************* @@ -264,17 +254,18 @@ void dis_c_cmpl_cback(tSRVC_CLCB* p_clcb, tGATTC_OPTYPE op, tGATT_STATUS status, uint8_t *pp = NULL, *p_str; uint16_t conn_id = p_clcb->conn_id; - if (dis_cb.dis_read_uuid_idx >= (sizeof(dis_attr_uuid)/sizeof(dis_attr_uuid[0]))) { + if (dis_cb.dis_read_uuid_idx >= (sizeof(dis_attr_uuid) / sizeof(dis_attr_uuid[0]))) { log::error("invalid dis_cb.dis_read_uuid_idx"); return; } read_type = dis_attr_uuid[dis_cb.dis_read_uuid_idx]; - log::verbose("op_code: 0x{:02x} status: 0x{:02x} read_type: 0x{:04x}", op, - status, read_type); + log::verbose("op_code: 0x{:02x} status: 0x{:02x} read_type: 0x{:04x}", op, status, read_type); - if (op != GATTC_OPTYPE_READ) return; + if (op != GATTC_OPTYPE_READ) { + return; + } if (p_data != NULL && status == GATT_SUCCESS) { pp = p_data->att_value.value; @@ -306,15 +297,13 @@ void dis_c_cmpl_cback(tSRVC_CLCB* p_clcb, tGATTC_OPTYPE op, tGATT_STATUS status, case GATT_UUID_SW_VERSION_STR: case GATT_UUID_MANU_NAME: case GATT_UUID_IEEE_DATA: - p_str = p_clcb->dis_value - .data_string[read_type - GATT_UUID_MODEL_NUMBER_STR]; + p_str = p_clcb->dis_value.data_string[read_type - GATT_UUID_MODEL_NUMBER_STR]; osi_free(p_str); p_str = (uint8_t*)osi_malloc(p_data->att_value.len + 1); p_clcb->dis_value.attr_mask |= dis_uuid_to_attr(read_type); memcpy(p_str, p_data->att_value.value, p_data->att_value.len); p_str[p_data->att_value.len] = 0; - p_clcb->dis_value.data_string[read_type - GATT_UUID_MODEL_NUMBER_STR] = - p_str; + p_clcb->dis_value.data_string[read_type - GATT_UUID_MODEL_NUMBER_STR] = p_str; break; default: @@ -322,7 +311,7 @@ void dis_c_cmpl_cback(tSRVC_CLCB* p_clcb, tGATTC_OPTYPE op, tGATT_STATUS status, break; } /* end switch */ - } /* end if */ + } /* end if */ dis_cb.dis_read_uuid_idx++; @@ -340,7 +329,7 @@ tDIS_STATUS DIS_SrInit(tDIS_ATTR_MASK dis_attr_mask) { tGATT_STATUS status; if (dis_cb.enabled) { - log::error("DIS already initalized"); + log::error("DIS already initialized"); return DIS_SUCCESS; } @@ -348,16 +337,14 @@ tDIS_STATUS DIS_SrInit(tDIS_ATTR_MASK dis_attr_mask) { btgatt_db_element_t service[DIS_MAX_ATTR_NUM] = {}; - bluetooth::Uuid svc_uuid = - bluetooth::Uuid::From16Bit(UUID_SERVCLASS_DEVICE_INFO); + bluetooth::Uuid svc_uuid = bluetooth::Uuid::From16Bit(UUID_SERVCLASS_DEVICE_INFO); service[0].type = BTGATT_DB_PRIMARY_SERVICE; service[0].uuid = svc_uuid; for (int i = 0; dis_attr_mask != 0 && i < DIS_MAX_CHAR_NUM; i++) { dis_cb.dis_attr[i].uuid = dis_attr_uuid[i]; - bluetooth::Uuid char_uuid = - bluetooth::Uuid::From16Bit(dis_cb.dis_attr[i].uuid); + bluetooth::Uuid char_uuid = bluetooth::Uuid::From16Bit(dis_cb.dis_attr[i].uuid); /* index 0 is service, so characteristics start from 1 */ service[i + 1].type = BTGATT_DB_CHARACTERISTIC; service[i + 1].uuid = char_uuid; @@ -381,8 +368,8 @@ tDIS_STATUS DIS_SrInit(tDIS_ATTR_MASK dis_attr_mask) { for (int i = 0; i < DIS_MAX_CHAR_NUM; i++) { dis_cb.dis_attr[i].handle = service[i + 1].attribute_handle; - log::verbose("handle of new attribute 0x{:04x} = {}", - dis_cb.dis_attr[i].uuid, dis_cb.dis_attr[i].handle); + log::verbose("handle of new attribute 0x{:04x} = {}", dis_cb.dis_attr[i].uuid, + dis_cb.dis_attr[i].handle); } dis_cb.enabled = true; @@ -412,12 +399,10 @@ tDIS_STATUS DIS_SrUpdate(tDIS_ATTR_BIT dis_attr_bit, tDIS_ATTR* p_info) { while (dis_attr_bit && i < (DIS_MAX_CHAR_NUM - 1)) { if (dis_attr_bit & (uint16_t)(1 << i)) { osi_free(dis_cb.dis_value.data_string[i - 1]); - dis_cb.dis_value.data_string[i - 1] = - (uint8_t*)osi_malloc(p_info->data_str.len + 1); - memcpy(dis_cb.dis_value.data_string[i - 1], p_info->data_str.p_data, - p_info->data_str.len); + dis_cb.dis_value.data_string[i - 1] = (uint8_t*)osi_malloc(p_info->data_str.len + 1); + memcpy(dis_cb.dis_value.data_string[i - 1], p_info->data_str.p_data, p_info->data_str.len); dis_cb.dis_value.data_string[i - 1][p_info->data_str.len] = - 0; /* make sure null terminate */ + 0; /* make sure null terminate */ st = DIS_SUCCESS; break; @@ -436,17 +421,20 @@ tDIS_STATUS DIS_SrUpdate(tDIS_ATTR_BIT dis_attr_bit, tDIS_ATTR* p_info) { * Returns true on success, false otherwise * ******************************************************************************/ -bool DIS_ReadDISInfo(const RawAddress& peer_bda, tDIS_READ_CBACK* p_cback, - tDIS_ATTR_MASK mask) { +bool DIS_ReadDISInfo(const RawAddress& peer_bda, tDIS_READ_CBACK* p_cback, tDIS_ATTR_MASK mask) { uint16_t conn_id; /* Initialize the DIS client if it hasn't been initialized already. */ srvc_eng_init(); /* For now we only handle one at a time */ - if (dis_cb.dis_read_uuid_idx != 0xff) return (false); + if (dis_cb.dis_read_uuid_idx != 0xff) { + return false; + } - if (p_cback == NULL) return (false); + if (p_cback == NULL) { + return false; + } dis_cb.p_read_dis_cback = p_cback; /* Mark currently active operation */ @@ -454,11 +442,9 @@ bool DIS_ReadDISInfo(const RawAddress& peer_bda, tDIS_READ_CBACK* p_cback, dis_cb.request_mask = mask; - log::verbose("BDA: {} cl_read_uuid: 0x{:04x}", peer_bda, - dis_attr_uuid[dis_cb.dis_read_uuid_idx]); + log::verbose("BDA: {} cl_read_uuid: 0x{:04x}", peer_bda, dis_attr_uuid[dis_cb.dis_read_uuid_idx]); - if (!GATT_GetConnIdIfConnected(srvc_eng_cb.gatt_if, peer_bda, &conn_id, - BT_TRANSPORT_LE)) { + if (!GATT_GetConnIdIfConnected(srvc_eng_cb.gatt_if, peer_bda, &conn_id, BT_TRANSPORT_LE)) { conn_id = GATT_INVALID_CONN_ID; } @@ -466,8 +452,8 @@ bool DIS_ReadDISInfo(const RawAddress& peer_bda, tDIS_READ_CBACK* p_cback, srvc_eng_request_channel(peer_bda, SRVC_ID_DIS); if (conn_id == GATT_INVALID_CONN_ID) { - return GATT_Connect(srvc_eng_cb.gatt_if, peer_bda, - BTM_BLE_DIRECT_CONNECTION, BT_TRANSPORT_LE, false); + return GATT_Connect(srvc_eng_cb.gatt_if, peer_bda, BTM_BLE_DIRECT_CONNECTION, BT_TRANSPORT_LE, + false); } return dis_gatt_c_read_dis_req(conn_id); diff --git a/system/stack/srvc/srvc_dis_int.h b/system/stack/srvc/srvc_dis_int.h index 9189cef1b4d..79f2c7e1fe9 100644 --- a/system/stack/srvc/srvc_dis_int.h +++ b/system/stack/srvc/srvc_dis_int.h @@ -54,8 +54,7 @@ typedef struct { extern tDIS_CB dis_cb; bool dis_valid_handle_range(uint16_t handle); -uint8_t dis_read_attr_value(uint8_t clcb_idx, uint16_t handle, - tGATT_VALUE* p_value, bool is_long, +uint8_t dis_read_attr_value(uint8_t clcb_idx, uint16_t handle, tGATT_VALUE* p_value, bool is_long, tGATT_STATUS* p_status); uint8_t dis_write_attr_value(tGATT_WRITE_REQ* p_data, tGATT_STATUS* p_status); diff --git a/system/stack/srvc/srvc_eng.cc b/system/stack/srvc/srvc_eng.cc index 89b6cc08b41..39e0c3c483b 100644 --- a/system/stack/srvc/srvc_eng.cc +++ b/system/stack/srvc/srvc_eng.cc @@ -30,36 +30,33 @@ using base::StringPrintf; using namespace bluetooth; -static void srvc_eng_s_request_cback(uint16_t conn_id, uint32_t trans_id, - tGATTS_REQ_TYPE type, tGATTS_DATA* p_data); -static void srvc_eng_connect_cback(tGATT_IF /* gatt_if */, - const RawAddress& bda, uint16_t conn_id, +static void srvc_eng_s_request_cback(uint16_t conn_id, uint32_t trans_id, tGATTS_REQ_TYPE type, + tGATTS_DATA* p_data); +static void srvc_eng_connect_cback(tGATT_IF /* gatt_if */, const RawAddress& bda, uint16_t conn_id, bool connected, tGATT_DISCONN_REASON reason, tBT_TRANSPORT transport); -static void srvc_eng_c_cmpl_cback(uint16_t conn_id, tGATTC_OPTYPE op, - tGATT_STATUS status, +static void srvc_eng_c_cmpl_cback(uint16_t conn_id, tGATTC_OPTYPE op, tGATT_STATUS status, tGATT_CL_COMPLETE* p_data); static tGATT_CBACK srvc_gatt_cback = { - .p_conn_cb = srvc_eng_connect_cback, - .p_cmpl_cb = srvc_eng_c_cmpl_cback, - .p_disc_res_cb = nullptr, - .p_disc_cmpl_cb = nullptr, - .p_req_cb = srvc_eng_s_request_cback, - .p_enc_cmpl_cb = nullptr, - .p_congestion_cb = nullptr, - .p_phy_update_cb = nullptr, - .p_conn_update_cb = nullptr, - .p_subrate_chg_cb = nullptr, + .p_conn_cb = srvc_eng_connect_cback, + .p_cmpl_cb = srvc_eng_c_cmpl_cback, + .p_disc_res_cb = nullptr, + .p_disc_cmpl_cb = nullptr, + .p_req_cb = srvc_eng_s_request_cback, + .p_enc_cmpl_cb = nullptr, + .p_congestion_cb = nullptr, + .p_phy_update_cb = nullptr, + .p_conn_update_cb = nullptr, + .p_subrate_chg_cb = nullptr, }; /* type for action functions */ -typedef void (*tSRVC_ENG_C_CMPL_ACTION)(tSRVC_CLCB* p_clcb, tGATTC_OPTYPE op, - tGATT_STATUS status, +typedef void (*tSRVC_ENG_C_CMPL_ACTION)(tSRVC_CLCB* p_clcb, tGATTC_OPTYPE op, tGATT_STATUS status, tGATT_CL_COMPLETE* p_data); static const tSRVC_ENG_C_CMPL_ACTION srvc_eng_c_cmpl_act[SRVC_ID_MAX] = { - dis_c_cmpl_cback, + dis_c_cmpl_cback, }; tSRVC_ENG_CB srvc_eng_cb; @@ -77,8 +74,7 @@ static tSRVC_CLCB* srvc_eng_find_clcb_by_bd_addr(const RawAddress& bda) { uint8_t i_clcb; tSRVC_CLCB* p_clcb = NULL; - for (i_clcb = 0, p_clcb = srvc_eng_cb.clcb; i_clcb < SRVC_MAX_APPS; - i_clcb++, p_clcb++) { + for (i_clcb = 0, p_clcb = srvc_eng_cb.clcb; i_clcb < SRVC_MAX_APPS; i_clcb++, p_clcb++) { if (p_clcb->in_use && p_clcb->connected && p_clcb->bda == bda) { return p_clcb; } @@ -99,8 +95,7 @@ tSRVC_CLCB* srvc_eng_find_clcb_by_conn_id(uint16_t conn_id) { uint8_t i_clcb; tSRVC_CLCB* p_clcb = NULL; - for (i_clcb = 0, p_clcb = srvc_eng_cb.clcb; i_clcb < SRVC_MAX_APPS; - i_clcb++, p_clcb++) { + for (i_clcb = 0, p_clcb = srvc_eng_cb.clcb; i_clcb < SRVC_MAX_APPS; i_clcb++, p_clcb++) { if (p_clcb->in_use && p_clcb->connected && p_clcb->conn_id == conn_id) { return p_clcb; } @@ -121,8 +116,7 @@ static uint8_t srvc_eng_find_clcb_idx_by_conn_id(uint16_t conn_id) { uint8_t i_clcb; tSRVC_CLCB* p_clcb = NULL; - for (i_clcb = 0, p_clcb = srvc_eng_cb.clcb; i_clcb < SRVC_MAX_APPS; - i_clcb++, p_clcb++) { + for (i_clcb = 0, p_clcb = srvc_eng_cb.clcb; i_clcb < SRVC_MAX_APPS; i_clcb++, p_clcb++) { if (p_clcb->in_use && p_clcb->connected && p_clcb->conn_id == conn_id) { return i_clcb; } @@ -140,13 +134,11 @@ static uint8_t srvc_eng_find_clcb_idx_by_conn_id(uint16_t conn_id) { * block. * ******************************************************************************/ -static tSRVC_CLCB* srvc_eng_clcb_alloc(uint16_t conn_id, - const RawAddress& bda) { +static tSRVC_CLCB* srvc_eng_clcb_alloc(uint16_t conn_id, const RawAddress& bda) { uint8_t i_clcb = 0; tSRVC_CLCB* p_clcb = NULL; - for (i_clcb = 0, p_clcb = srvc_eng_cb.clcb; i_clcb < SRVC_MAX_APPS; - i_clcb++, p_clcb++) { + for (i_clcb = 0, p_clcb = srvc_eng_cb.clcb; i_clcb < SRVC_MAX_APPS; i_clcb++, p_clcb++) { if (!p_clcb->in_use) { p_clcb->in_use = true; p_clcb->conn_id = conn_id; @@ -170,12 +162,12 @@ static bool srvc_eng_clcb_dealloc(uint16_t conn_id) { uint8_t i_clcb = 0; tSRVC_CLCB* p_clcb = NULL; - for (i_clcb = 0, p_clcb = srvc_eng_cb.clcb; i_clcb < SRVC_MAX_APPS; - i_clcb++, p_clcb++) { + for (i_clcb = 0, p_clcb = srvc_eng_cb.clcb; i_clcb < SRVC_MAX_APPS; i_clcb++, p_clcb++) { if (p_clcb->in_use && p_clcb->connected && (p_clcb->conn_id == conn_id)) { unsigned j; - for (j = 0; j < ARRAY_SIZE(p_clcb->dis_value.data_string); j++) + for (j = 0; j < ARRAY_SIZE(p_clcb->dis_value.data_string); j++) { osi_free(p_clcb->dis_value.data_string[j]); + } memset(p_clcb, 0, sizeof(tSRVC_CLCB)); return true; @@ -186,37 +178,37 @@ static bool srvc_eng_clcb_dealloc(uint16_t conn_id) { /******************************************************************************* * Service Engine Server Attributes Database Read/Read Blob Request process ******************************************************************************/ -static uint8_t srvc_eng_process_read_req(uint8_t clcb_idx, - tGATT_READ_REQ* p_data, - tGATTS_RSP* p_rsp, - tGATT_STATUS* p_status) { +static uint8_t srvc_eng_process_read_req(uint8_t clcb_idx, tGATT_READ_REQ* p_data, + tGATTS_RSP* p_rsp, tGATT_STATUS* p_status) { tGATT_STATUS status = GATT_NOT_FOUND; uint8_t act = SRVC_ACT_RSP; - if (p_data->is_long) p_rsp->attr_value.offset = p_data->offset; + if (p_data->is_long) { + p_rsp->attr_value.offset = p_data->offset; + } p_rsp->attr_value.handle = p_data->handle; - if (dis_valid_handle_range(p_data->handle)) - act = dis_read_attr_value(clcb_idx, p_data->handle, &p_rsp->attr_value, - p_data->is_long, p_status); - else + if (dis_valid_handle_range(p_data->handle)) { + act = dis_read_attr_value(clcb_idx, p_data->handle, &p_rsp->attr_value, p_data->is_long, + p_status); + } else { *p_status = status; + } return act; } /******************************************************************************* * Service Engine Server Attributes Database write Request process ******************************************************************************/ -static uint8_t srvc_eng_process_write_req(uint8_t /* clcb_idx */, - tGATT_WRITE_REQ* p_data, - tGATTS_RSP* /* p_rsp */, - tGATT_STATUS* p_status) { +static uint8_t srvc_eng_process_write_req(uint8_t /* clcb_idx */, tGATT_WRITE_REQ* p_data, + tGATTS_RSP* /* p_rsp */, tGATT_STATUS* p_status) { uint8_t act = SRVC_ACT_RSP; if (dis_valid_handle_range(p_data->handle)) { act = dis_write_attr_value(p_data, p_status); - } else + } else { *p_status = GATT_NOT_FOUND; + } return act; } @@ -230,8 +222,7 @@ static uint8_t srvc_eng_process_write_req(uint8_t /* clcb_idx */, * Returns void. * ******************************************************************************/ -static void srvc_eng_s_request_cback(uint16_t conn_id, uint32_t trans_id, - tGATTS_REQ_TYPE type, +static void srvc_eng_s_request_cback(uint16_t conn_id, uint32_t trans_id, tGATTS_REQ_TYPE type, tGATTS_DATA* p_data) { tGATT_STATUS status = GATT_INVALID_PDU; tGATTS_RSP rsp_msg; @@ -247,15 +238,15 @@ static void srvc_eng_s_request_cback(uint16_t conn_id, uint32_t trans_id, switch (type) { case GATTS_REQ_TYPE_READ_CHARACTERISTIC: case GATTS_REQ_TYPE_READ_DESCRIPTOR: - act = srvc_eng_process_read_req(clcb_idx, &p_data->read_req, &rsp_msg, - &status); + act = srvc_eng_process_read_req(clcb_idx, &p_data->read_req, &rsp_msg, &status); break; case GATTS_REQ_TYPE_WRITE_CHARACTERISTIC: case GATTS_REQ_TYPE_WRITE_DESCRIPTOR: - act = srvc_eng_process_write_req(clcb_idx, &p_data->write_req, &rsp_msg, - &status); - if (!p_data->write_req.need_rsp) act = SRVC_ACT_IGNORE; + act = srvc_eng_process_write_req(clcb_idx, &p_data->write_req, &rsp_msg, &status); + if (!p_data->write_req.need_rsp) { + act = SRVC_ACT_IGNORE; + } break; case GATTS_REQ_TYPE_WRITE_EXEC: @@ -289,21 +280,20 @@ static void srvc_eng_s_request_cback(uint16_t conn_id, uint32_t trans_id, * Returns void * ******************************************************************************/ -static void srvc_eng_c_cmpl_cback(uint16_t conn_id, tGATTC_OPTYPE op, - tGATT_STATUS status, +static void srvc_eng_c_cmpl_cback(uint16_t conn_id, tGATTC_OPTYPE op, tGATT_STATUS status, tGATT_CL_COMPLETE* p_data) { tSRVC_CLCB* p_clcb = srvc_eng_find_clcb_by_conn_id(conn_id); - log::verbose("srvc_eng_c_cmpl_cback() - op_code: 0x{:02x} status: 0x{:02x}", - op, status); + log::verbose("srvc_eng_c_cmpl_cback() - op_code: 0x{:02x} status: 0x{:02x}", op, status); if (p_clcb == NULL) { log::error("received for unknown connection"); return; } - if (p_clcb->cur_srvc_id != SRVC_ID_NONE && p_clcb->cur_srvc_id <= SRVC_ID_MAX) + if (p_clcb->cur_srvc_id != SRVC_ID_NONE && p_clcb->cur_srvc_id <= SRVC_ID_MAX) { srvc_eng_c_cmpl_act[p_clcb->cur_srvc_id - 1](p_clcb, op, status, p_data); + } } /******************************************************************************* @@ -315,10 +305,8 @@ static void srvc_eng_c_cmpl_cback(uint16_t conn_id, tGATTC_OPTYPE op, * Returns void * ******************************************************************************/ -static void srvc_eng_connect_cback(tGATT_IF /* gatt_if */, - const RawAddress& bda, uint16_t conn_id, - bool connected, - tGATT_DISCONN_REASON /* reason */, +static void srvc_eng_connect_cback(tGATT_IF /* gatt_if */, const RawAddress& bda, uint16_t conn_id, + bool connected, tGATT_DISCONN_REASON /* reason */, tBT_TRANSPORT /* transport */) { log::verbose("from {} connected:{} conn_id={}", bda, connected, conn_id); @@ -344,12 +332,15 @@ bool srvc_eng_request_channel(const RawAddress& remote_bda, uint8_t srvc_id) { bool set = true; tSRVC_CLCB* p_clcb = srvc_eng_find_clcb_by_bd_addr(remote_bda); - if (p_clcb == NULL) p_clcb = srvc_eng_clcb_alloc(0, remote_bda); + if (p_clcb == NULL) { + p_clcb = srvc_eng_clcb_alloc(0, remote_bda); + } - if (p_clcb && p_clcb->cur_srvc_id == SRVC_ID_NONE) + if (p_clcb && p_clcb->cur_srvc_id == SRVC_ID_NONE) { p_clcb->cur_srvc_id = srvc_id; - else + } else { set = false; + } return set; } @@ -381,21 +372,18 @@ void srvc_eng_release_channel(uint16_t conn_id) { * * Function srvc_eng_init * - * Description Initializa the GATT Service engine. + * Description Initialize the GATT Service engine. * ******************************************************************************/ tGATT_STATUS srvc_eng_init(void) { - if (srvc_eng_cb.enabled) { - log::error("DIS already initalized"); + log::error("DIS already initialized"); } else { memset(&srvc_eng_cb, 0, sizeof(tSRVC_ENG_CB)); /* Create a GATT profile service */ - bluetooth::Uuid app_uuid = - bluetooth::Uuid::From16Bit(UUID_SERVCLASS_DEVICE_INFO); - srvc_eng_cb.gatt_if = - GATT_Register(app_uuid, "GattServiceEngine", &srvc_gatt_cback, false); + bluetooth::Uuid app_uuid = bluetooth::Uuid::From16Bit(UUID_SERVCLASS_DEVICE_INFO); + srvc_eng_cb.gatt_if = GATT_Register(app_uuid, "GattServiceEngine", &srvc_gatt_cback, false); GATT_StartIf(srvc_eng_cb.gatt_if); log::verbose("Srvc_Init: gatt_if={}", srvc_eng_cb.gatt_if); diff --git a/system/stack/test/a2dp/a2dp_aac_unittest.cc b/system/stack/test/a2dp/a2dp_aac_unittest.cc index 2ae209b966c..48221f88a32 100644 --- a/system/stack/test/a2dp/a2dp_aac_unittest.cc +++ b/system/stack/test/a2dp/a2dp_aac_unittest.cc @@ -39,20 +39,20 @@ constexpr uint32_t kA2dpTickUs = 23 * 1000; constexpr uint16_t kPeerMtu = 1000; constexpr char kWavFile[] = "test/a2dp/raw_data/pcm1644s.wav"; constexpr uint8_t kCodecInfoAacCapability[AVDT_CODEC_SIZE] = { - 8, // Length (A2DP_AAC_INFO_LEN) - 0, // Media Type: AVDT_MEDIA_TYPE_AUDIO - 2, // Media Codec Type: A2DP_MEDIA_CT_AAC - 0x80, // Object Type: A2DP_AAC_OBJECT_TYPE_MPEG2_LC - 0x01, // Sampling Frequency: A2DP_AAC_SAMPLING_FREQ_44100 - 0x04, // Channels: A2DP_AAC_CHANNEL_MODE_STEREO - 0x00 | 0x4, // Variable Bit Rate: - // A2DP_AAC_VARIABLE_BIT_RATE_DISABLED - // Bit Rate: 320000 = 0x4e200 - 0xe2, // Bit Rate: 320000 = 0x4e200 - 0x00, // Bit Rate: 320000 = 0x4e200 - 7, // Unused - 8, // Unused - 9 // Unused + 8, // Length (A2DP_AAC_INFO_LEN) + 0, // Media Type: AVDT_MEDIA_TYPE_AUDIO + 2, // Media Codec Type: A2DP_MEDIA_CT_AAC + 0x80, // Object Type: A2DP_AAC_OBJECT_TYPE_MPEG2_LC + 0x01, // Sampling Frequency: A2DP_AAC_SAMPLING_FREQ_44100 + 0x04, // Channels: A2DP_AAC_CHANNEL_MODE_STEREO + 0x00 | 0x4, // Variable Bit Rate: + // A2DP_AAC_VARIABLE_BIT_RATE_DISABLED + // Bit Rate: 320000 = 0x4e200 + 0xe2, // Bit Rate: 320000 = 0x4e200 + 0x00, // Bit Rate: 320000 = 0x4e200 + 7, // Unused + 8, // Unused + 9 // Unused }; uint8_t* Data(BT_HDR* packet) { return packet->data + packet->offset; } } // namespace @@ -64,15 +64,15 @@ static BT_HDR* packet = nullptr; static WavReader wav_reader = WavReader(GetWavFilePath(kWavFile).c_str()); class A2dpAacTest : public ::testing::Test { - protected: +protected: void SetUp() override { common::InitFlags::SetAllForTesting(); SetCodecConfig(); encoder_iface_ = const_cast( - A2DP_GetEncoderInterfaceAac(kCodecInfoAacCapability)); + A2DP_GetEncoderInterfaceAac(kCodecInfoAacCapability)); ASSERT_NE(encoder_iface_, nullptr); decoder_iface_ = const_cast( - A2DP_GetDecoderInterfaceAac(kCodecInfoAacCapability)); + A2DP_GetDecoderInterfaceAac(kCodecInfoAacCapability)); ASSERT_NE(decoder_iface_, nullptr); } @@ -104,27 +104,25 @@ class A2dpAacTest : public ::testing::Test { ASSERT_NE(peer_codec_index, BTAV_A2DP_CODEC_INDEX_MAX); sink_codec_config_ = a2dp_codecs_->findSinkCodecConfig(kCodecInfoAacCapability); ASSERT_NE(sink_codec_config_, nullptr); - ASSERT_TRUE(a2dp_codecs_->setSinkCodecConfig(kCodecInfoAacCapability, true, - codec_info_result, true)); + ASSERT_TRUE(a2dp_codecs_->setSinkCodecConfig(kCodecInfoAacCapability, true, codec_info_result, + true)); ASSERT_TRUE(a2dp_codecs_->setPeerSinkCodecCapabilities(kCodecInfoAacCapability)); // Compare the result codec with the local test codec info for (size_t i = 0; i < kCodecInfoAacCapability[0] + 1; i++) { ASSERT_EQ(codec_info_result[i], kCodecInfoAacCapability[i]); } - ASSERT_TRUE(a2dp_codecs_->setCodecConfig(kCodecInfoAacCapability, true, codec_info_result, true)); + ASSERT_TRUE( + a2dp_codecs_->setCodecConfig(kCodecInfoAacCapability, true, codec_info_result, true)); source_codec_config_ = a2dp_codecs_->getCurrentCodecConfig(); } void InitializeEncoder(bool peer_supports_3mbps, a2dp_source_read_callback_t read_cb, a2dp_source_enqueue_callback_t enqueue_cb) { tA2DP_ENCODER_INIT_PEER_PARAMS peer_params = {true, peer_supports_3mbps, kPeerMtu}; - encoder_iface_->encoder_init(&peer_params, sink_codec_config_, read_cb, - enqueue_cb); + encoder_iface_->encoder_init(&peer_params, sink_codec_config_, read_cb, enqueue_cb); } - void InitializeDecoder(decoded_data_callback_t data_cb) { - decoder_iface_->decoder_init(data_cb); - } + void InitializeDecoder(decoded_data_callback_t data_cb) { decoder_iface_->decoder_init(data_cb); } BT_HDR* AllocateL2capPacket(const std::vector data) const { auto packet = AllocatePacket(data.size()); @@ -133,8 +131,7 @@ class A2dpAacTest : public ::testing::Test { } BT_HDR* AllocatePacket(size_t packet_length) const { - BT_HDR* packet = - static_cast(osi_calloc(sizeof(BT_HDR) + packet_length)); + BT_HDR* packet = static_cast(osi_calloc(sizeof(BT_HDR) + packet_length)); packet->len = packet_length; return packet; } diff --git a/system/stack/test/a2dp/a2dp_opus_unittest.cc b/system/stack/test/a2dp/a2dp_opus_unittest.cc index e9feb0efd6b..297a5100a5b 100644 --- a/system/stack/test/a2dp/a2dp_opus_unittest.cc +++ b/system/stack/test/a2dp/a2dp_opus_unittest.cc @@ -35,22 +35,22 @@ namespace { constexpr uint32_t kA2dpTickUs = 23 * 1000; constexpr char kWavFile[] = "test/a2dp/raw_data/pcm1644s.wav"; const uint8_t kCodecInfoOpusCapability[AVDT_CODEC_SIZE] = { - A2DP_OPUS_CODEC_LEN, // Length - AVDT_MEDIA_TYPE_AUDIO << 4, // Media Type - A2DP_MEDIA_CT_NON_A2DP, // Media Codec Type Vendor - (A2DP_OPUS_VENDOR_ID & 0x000000FF), - (A2DP_OPUS_VENDOR_ID & 0x0000FF00) >> 8, - (A2DP_OPUS_VENDOR_ID & 0x00FF0000) >> 16, - (A2DP_OPUS_VENDOR_ID & 0xFF000000) >> 24, - (A2DP_OPUS_CODEC_ID & 0x00FF), - (A2DP_OPUS_CODEC_ID & 0xFF00) >> 8, - A2DP_OPUS_CHANNEL_MODE_STEREO | A2DP_OPUS_20MS_FRAMESIZE | - A2DP_OPUS_SAMPLING_FREQ_48000 -}; + A2DP_OPUS_CODEC_LEN, // Length + AVDT_MEDIA_TYPE_AUDIO << 4, // Media Type + A2DP_MEDIA_CT_NON_A2DP, // Media Codec Type Vendor + (A2DP_OPUS_VENDOR_ID & 0x000000FF), + (A2DP_OPUS_VENDOR_ID & 0x0000FF00) >> 8, + (A2DP_OPUS_VENDOR_ID & 0x00FF0000) >> 16, + (A2DP_OPUS_VENDOR_ID & 0xFF000000) >> 24, + (A2DP_OPUS_CODEC_ID & 0x00FF), + (A2DP_OPUS_CODEC_ID & 0xFF00) >> 8, + A2DP_OPUS_CHANNEL_MODE_STEREO | A2DP_OPUS_20MS_FRAMESIZE | A2DP_OPUS_SAMPLING_FREQ_48000}; uint8_t* Data(BT_HDR* packet) { return packet->data + packet->offset; } uint32_t GetReadSize() { - return A2DP_VendorGetFrameSizeOpus(kCodecInfoOpusCapability) * A2DP_VendorGetTrackChannelCountOpus(kCodecInfoOpusCapability) * (A2DP_VendorGetTrackBitsPerSampleOpus(kCodecInfoOpusCapability) / 8); + return A2DP_VendorGetFrameSizeOpus(kCodecInfoOpusCapability) * + A2DP_VendorGetTrackChannelCountOpus(kCodecInfoOpusCapability) * + (A2DP_VendorGetTrackBitsPerSampleOpus(kCodecInfoOpusCapability) / 8); } } // namespace @@ -62,15 +62,15 @@ static WavReader wav_reader = WavReader(GetWavFilePath(kWavFile).c_str()); static std::promise promise; class A2dpOpusTest : public ::testing::Test { - protected: +protected: void SetUp() override { common::InitFlags::SetAllForTesting(); SetCodecConfig(); encoder_iface_ = const_cast( - A2DP_VendorGetEncoderInterfaceOpus(kCodecInfoOpusCapability)); + A2DP_VendorGetEncoderInterfaceOpus(kCodecInfoOpusCapability)); ASSERT_NE(encoder_iface_, nullptr); decoder_iface_ = const_cast( - A2DP_VendorGetDecoderInterfaceOpus(kCodecInfoOpusCapability)); + A2DP_VendorGetDecoderInterfaceOpus(kCodecInfoOpusCapability)); ASSERT_NE(decoder_iface_, nullptr); } @@ -99,8 +99,8 @@ class A2dpOpusTest : public ::testing::Test { ASSERT_NE(peer_codec_index, BTAV_A2DP_CODEC_INDEX_MAX); codec_config_ = a2dp_codecs_->findSinkCodecConfig(kCodecInfoOpusCapability); ASSERT_NE(codec_config_, nullptr); - ASSERT_TRUE(a2dp_codecs_->setSinkCodecConfig(kCodecInfoOpusCapability, true, - codec_info_result, true)); + ASSERT_TRUE(a2dp_codecs_->setSinkCodecConfig(kCodecInfoOpusCapability, true, codec_info_result, + true)); ASSERT_EQ(a2dp_codecs_->getCurrentCodecConfig(), codec_config_); // Compare the result codec with the local test codec info for (size_t i = 0; i < kCodecInfoOpusCapability[0] + 1; i++) { @@ -112,13 +112,10 @@ class A2dpOpusTest : public ::testing::Test { void InitializeEncoder(a2dp_source_read_callback_t read_cb, a2dp_source_enqueue_callback_t enqueue_cb) { tA2DP_ENCODER_INIT_PEER_PARAMS peer_params = {true, true, 1000}; - encoder_iface_->encoder_init(&peer_params, codec_config_, read_cb, - enqueue_cb); + encoder_iface_->encoder_init(&peer_params, codec_config_, read_cb, enqueue_cb); } - void InitializeDecoder(decoded_data_callback_t data_cb) { - decoder_iface_->decoder_init(data_cb); - } + void InitializeDecoder(decoded_data_callback_t data_cb) { decoder_iface_->decoder_init(data_cb); } BT_HDR* AllocateL2capPacket(const std::vector data) const { auto packet = AllocatePacket(data.size()); @@ -127,8 +124,7 @@ class A2dpOpusTest : public ::testing::Test { } BT_HDR* AllocatePacket(size_t packet_length) const { - BT_HDR* packet = - static_cast(osi_calloc(sizeof(BT_HDR) + packet_length)); + BT_HDR* packet = static_cast(osi_calloc(sizeof(BT_HDR) + packet_length)); packet->len = packet_length; return packet; } @@ -162,8 +158,7 @@ TEST_F(A2dpOpusTest, a2dp_source_read_underflow) { TEST_F(A2dpOpusTest, a2dp_enqueue_cb_is_invoked) { promise = {}; auto read_cb = +[](uint8_t* p_buf, uint32_t len) -> uint32_t { - log::assert_that(GetReadSize() == len, - "assert failed: GetReadSize() == len"); + log::assert_that(GetReadSize() == len, "assert failed: GetReadSize() == len"); return len; }; auto enqueue_cb = +[](BT_HDR* p_buf, size_t frames_n, uint32_t len) -> bool { @@ -207,8 +202,7 @@ TEST_F(A2dpOpusTest, decoded_data_cb_invoked) { auto enqueue_cb = +[](BT_HDR* p_buf, size_t frames_n, uint32_t len) -> bool { static bool first_invocation = true; if (first_invocation) { - packet = reinterpret_cast( - osi_malloc(sizeof(*p_buf) + p_buf->len + 1)); + packet = reinterpret_cast(osi_malloc(sizeof(*p_buf) + p_buf->len + 1)); memcpy(packet, p_buf, sizeof(*p_buf)); packet->offset = 0; memcpy(packet->data + 1, p_buf->data + p_buf->offset, p_buf->len); diff --git a/system/stack/test/a2dp/a2dp_sbc_regression_tests.cc b/system/stack/test/a2dp/a2dp_sbc_regression_tests.cc index d1fa110f950..99cb7343b3e 100644 --- a/system/stack/test/a2dp/a2dp_sbc_regression_tests.cc +++ b/system/stack/test/a2dp/a2dp_sbc_regression_tests.cc @@ -22,7 +22,7 @@ namespace bluetooth { namespace testing { class A2DPRegressionTests : public ::testing::Test { - protected: +protected: void SetUp() override {} void TearDown() override {} }; diff --git a/system/stack/test/a2dp/a2dp_sbc_unittest.cc b/system/stack/test/a2dp/a2dp_sbc_unittest.cc index 9aacf700b0d..78fcd4ae186 100644 --- a/system/stack/test/a2dp/a2dp_sbc_unittest.cc +++ b/system/stack/test/a2dp/a2dp_sbc_unittest.cc @@ -40,19 +40,19 @@ constexpr uint32_t kA2dpTickUs = 23 * 1000; constexpr char kWavFile[] = "test/a2dp/raw_data/pcm1644s.wav"; constexpr uint16_t kPeerMtu = 1000; const uint8_t kCodecInfoSbcCapability[AVDT_CODEC_SIZE] = { - 6, // Length (A2DP_SBC_INFO_LEN) - 0, // Media Type: AVDT_MEDIA_TYPE_AUDIO - 0, // Media Codec Type: A2DP_MEDIA_CT_SBC - 0x20 | 0x01, // Sample Frequency: A2DP_SBC_IE_SAMP_FREQ_44 | - // Channel Mode: A2DP_SBC_IE_CH_MD_JOINT - 0x10 | 0x04 | 0x01, // Block Length: A2DP_SBC_IE_BLOCKS_16 | - // Subbands: A2DP_SBC_IE_SUBBAND_8 | - // Allocation Method: A2DP_SBC_IE_ALLOC_MD_L - 2, // MinimumBitpool Value: A2DP_SBC_IE_MIN_BITPOOL - 53, // Maximum Bitpool Value: A2DP_SBC_MAX_BITPOOL - 7, // Fake - 8, // Fake - 9 // Fake + 6, // Length (A2DP_SBC_INFO_LEN) + 0, // Media Type: AVDT_MEDIA_TYPE_AUDIO + 0, // Media Codec Type: A2DP_MEDIA_CT_SBC + 0x20 | 0x01, // Sample Frequency: A2DP_SBC_IE_SAMP_FREQ_44 | + // Channel Mode: A2DP_SBC_IE_CH_MD_JOINT + 0x10 | 0x04 | 0x01, // Block Length: A2DP_SBC_IE_BLOCKS_16 | + // Subbands: A2DP_SBC_IE_SUBBAND_8 | + // Allocation Method: A2DP_SBC_IE_ALLOC_MD_L + 2, // MinimumBitpool Value: A2DP_SBC_IE_MIN_BITPOOL + 53, // Maximum Bitpool Value: A2DP_SBC_MAX_BITPOOL + 7, // Fake + 8, // Fake + 9 // Fake }; uint8_t* Data(BT_HDR* packet) { return packet->data + packet->offset; } } // namespace @@ -65,15 +65,15 @@ static WavReader wav_reader = WavReader(GetWavFilePath(kWavFile).c_str()); static std::promise promise; class A2dpSbcTest : public ::testing::Test { - protected: +protected: void SetUp() override { common::InitFlags::SetAllForTesting(); SetCodecConfig(); encoder_iface_ = const_cast( - A2DP_GetEncoderInterfaceSbc(kCodecInfoSbcCapability)); + A2DP_GetEncoderInterfaceSbc(kCodecInfoSbcCapability)); ASSERT_NE(encoder_iface_, nullptr); decoder_iface_ = const_cast( - A2DP_GetDecoderInterfaceSbc(kCodecInfoSbcCapability)); + A2DP_GetDecoderInterfaceSbc(kCodecInfoSbcCapability)); ASSERT_NE(decoder_iface_, nullptr); } @@ -105,27 +105,25 @@ class A2dpSbcTest : public ::testing::Test { ASSERT_NE(peer_codec_index, BTAV_A2DP_CODEC_INDEX_MAX); sink_codec_config_ = a2dp_codecs_->findSinkCodecConfig(kCodecInfoSbcCapability); ASSERT_NE(sink_codec_config_, nullptr); - ASSERT_TRUE(a2dp_codecs_->setSinkCodecConfig(kCodecInfoSbcCapability, true, - codec_info_result, true)); + ASSERT_TRUE(a2dp_codecs_->setSinkCodecConfig(kCodecInfoSbcCapability, true, codec_info_result, + true)); ASSERT_TRUE(a2dp_codecs_->setPeerSinkCodecCapabilities(kCodecInfoSbcCapability)); // Compare the result codec with the local test codec info for (size_t i = 0; i < kCodecInfoSbcCapability[0] + 1; i++) { ASSERT_EQ(codec_info_result[i], kCodecInfoSbcCapability[i]); } - ASSERT_TRUE(a2dp_codecs_->setCodecConfig(kCodecInfoSbcCapability, true, codec_info_result, true)); + ASSERT_TRUE( + a2dp_codecs_->setCodecConfig(kCodecInfoSbcCapability, true, codec_info_result, true)); source_codec_config_ = a2dp_codecs_->getCurrentCodecConfig(); } void InitializeEncoder(bool peer_supports_3mbps, a2dp_source_read_callback_t read_cb, a2dp_source_enqueue_callback_t enqueue_cb) { tA2DP_ENCODER_INIT_PEER_PARAMS peer_params = {true, peer_supports_3mbps, kPeerMtu}; - encoder_iface_->encoder_init(&peer_params, sink_codec_config_, read_cb, - enqueue_cb); + encoder_iface_->encoder_init(&peer_params, sink_codec_config_, read_cb, enqueue_cb); } - void InitializeDecoder(decoded_data_callback_t data_cb) { - decoder_iface_->decoder_init(data_cb); - } + void InitializeDecoder(decoded_data_callback_t data_cb) { decoder_iface_->decoder_init(data_cb); } BT_HDR* AllocateL2capPacket(const std::vector data) const { auto packet = AllocatePacket(data.size()); @@ -134,8 +132,7 @@ class A2dpSbcTest : public ::testing::Test { } BT_HDR* AllocatePacket(size_t packet_length) const { - BT_HDR* packet = - static_cast(osi_calloc(sizeof(BT_HDR) + packet_length)); + BT_HDR* packet = static_cast(osi_calloc(sizeof(BT_HDR) + packet_length)); packet->len = packet_length; return packet; } @@ -214,8 +211,7 @@ TEST_F(A2dpSbcTest, decoded_data_cb_invoked) { auto enqueue_cb = +[](BT_HDR* p_buf, size_t frames_n, uint32_t len) -> bool { static bool first_invocation = true; if (first_invocation) { - packet = reinterpret_cast( - osi_malloc(sizeof(*p_buf) + p_buf->len + 1)); + packet = reinterpret_cast(osi_malloc(sizeof(*p_buf) + p_buf->len + 1)); memcpy(packet, p_buf, sizeof(*p_buf)); packet->offset = 0; memcpy(packet->data + 1, p_buf->data + p_buf->offset, p_buf->len); diff --git a/system/stack/test/a2dp/a2dp_vendor_ldac_decoder_test.cc b/system/stack/test/a2dp/a2dp_vendor_ldac_decoder_test.cc index 062f0e405e7..4f78adbb00a 100644 --- a/system/stack/test/a2dp/a2dp_vendor_ldac_decoder_test.cc +++ b/system/stack/test/a2dp/a2dp_vendor_ldac_decoder_test.cc @@ -33,17 +33,16 @@ uint8_t* Data(BT_HDR* packet) { return packet->data + packet->offset; } * Test class to test selected functionality in stack/a2dp */ class A2dpStackTest : public ::testing::Test { - protected: +protected: BT_HDR* AllocateL2capPacket(const std::vector data) const { auto packet = AllocatePacket(data.size()); std::copy(data.cbegin(), data.cend(), Data(packet)); return packet; } - private: +private: BT_HDR* AllocatePacket(size_t packet_length) const { - BT_HDR* packet = - static_cast(osi_calloc(sizeof(BT_HDR) + packet_length)); + BT_HDR* packet = static_cast(osi_calloc(sizeof(BT_HDR) + packet_length)); packet->len = packet_length; return packet; } diff --git a/system/stack/test/a2dp/a2dp_vendor_ldac_unittest.cc b/system/stack/test/a2dp/a2dp_vendor_ldac_unittest.cc index ea8575df35b..bb73f0afa2e 100644 --- a/system/stack/test/a2dp/a2dp_vendor_ldac_unittest.cc +++ b/system/stack/test/a2dp/a2dp_vendor_ldac_unittest.cc @@ -31,17 +31,17 @@ namespace { constexpr uint32_t kA2dpTickUs = 23 * 1000; constexpr char kWavFile[] = "test/a2dp/raw_data/pcm1644s.wav"; constexpr uint8_t kCodecInfoLdacCapability[AVDT_CODEC_SIZE] = { - A2DP_LDAC_CODEC_LEN, - AVDT_MEDIA_TYPE_AUDIO, - A2DP_MEDIA_CT_NON_A2DP, - 0x2D, // A2DP_LDAC_VENDOR_ID - 0x01, // A2DP_LDAC_VENDOR_ID - 0x00, // A2DP_LDAC_VENDOR_ID - 0x00, // A2DP_LDAC_VENDOR_ID - 0xAA, // A2DP_LDAC_CODEC_ID - 0x00, // A2DP_LDAC_CODEC_ID, - A2DP_LDAC_SAMPLING_FREQ_44100, - A2DP_LDAC_CHANNEL_MODE_STEREO, + A2DP_LDAC_CODEC_LEN, + AVDT_MEDIA_TYPE_AUDIO, + A2DP_MEDIA_CT_NON_A2DP, + 0x2D, // A2DP_LDAC_VENDOR_ID + 0x01, // A2DP_LDAC_VENDOR_ID + 0x00, // A2DP_LDAC_VENDOR_ID + 0x00, // A2DP_LDAC_VENDOR_ID + 0xAA, // A2DP_LDAC_CODEC_ID + 0x00, // A2DP_LDAC_CODEC_ID, + A2DP_LDAC_SAMPLING_FREQ_44100, + A2DP_LDAC_CHANNEL_MODE_STEREO, }; uint8_t* Data(BT_HDR* packet) { return packet->data + packet->offset; } } // namespace @@ -52,15 +52,15 @@ namespace testing { static WavReader wav_reader = WavReader(GetWavFilePath(kWavFile).c_str()); class A2dpLdacTest : public ::testing::Test { - protected: +protected: void SetUp() override { common::InitFlags::SetAllForTesting(); SetCodecConfig(); encoder_iface_ = const_cast( - A2DP_VendorGetEncoderInterfaceLdac(kCodecInfoLdacCapability)); + A2DP_VendorGetEncoderInterfaceLdac(kCodecInfoLdacCapability)); ASSERT_NE(encoder_iface_, nullptr); decoder_iface_ = const_cast( - A2DP_VendorGetDecoderInterfaceLdac(kCodecInfoLdacCapability)); + A2DP_VendorGetDecoderInterfaceLdac(kCodecInfoLdacCapability)); ASSERT_NE(decoder_iface_, nullptr); } @@ -76,7 +76,7 @@ class A2dpLdacTest : public ::testing::Test { } } -// NOTE: Make a super func for all codecs + // NOTE: Make a super func for all codecs void SetCodecConfig() { uint8_t source_codec_info_result[AVDT_CODEC_SIZE]; btav_a2dp_codec_index_t peer_codec_index; @@ -87,11 +87,10 @@ class A2dpLdacTest : public ::testing::Test { peer_codec_index = A2DP_SinkCodecIndex(kCodecInfoLdacCapability); ASSERT_NE(peer_codec_index, BTAV_A2DP_CODEC_INDEX_MAX); ASSERT_EQ(peer_codec_index, BTAV_A2DP_CODEC_INDEX_SINK_LDAC); - source_codec_config_ = - a2dp_codecs_->findSourceCodecConfig(kCodecInfoLdacCapability); + source_codec_config_ = a2dp_codecs_->findSourceCodecConfig(kCodecInfoLdacCapability); ASSERT_NE(source_codec_config_, nullptr); ASSERT_TRUE(a2dp_codecs_->setCodecConfig(kCodecInfoLdacCapability, true, - source_codec_info_result, true)); + source_codec_info_result, true)); ASSERT_EQ(a2dp_codecs_->getCurrentCodecConfig(), source_codec_config_); // Compare the result codec with the local test codec info for (size_t i = 0; i < kCodecInfoLdacCapability[0] + 1; i++) { @@ -103,13 +102,10 @@ class A2dpLdacTest : public ::testing::Test { void InitializeEncoder(a2dp_source_read_callback_t read_cb, a2dp_source_enqueue_callback_t enqueue_cb) { tA2DP_ENCODER_INIT_PEER_PARAMS peer_params = {true, true, 1000}; - encoder_iface_->encoder_init(&peer_params, source_codec_config_, read_cb, - enqueue_cb); + encoder_iface_->encoder_init(&peer_params, source_codec_config_, read_cb, enqueue_cb); } - void InitializeDecoder(decoded_data_callback_t data_cb) { - decoder_iface_->decoder_init(data_cb); - } + void InitializeDecoder(decoded_data_callback_t data_cb) { decoder_iface_->decoder_init(data_cb); } BT_HDR* AllocateL2capPacket(const std::vector data) const { auto packet = AllocatePacket(data.size()); std::copy(data.cbegin(), data.cend(), Data(packet)); @@ -117,8 +113,7 @@ class A2dpLdacTest : public ::testing::Test { } BT_HDR* AllocatePacket(size_t packet_length) const { - BT_HDR* packet = - static_cast(osi_calloc(sizeof(BT_HDR) + packet_length)); + BT_HDR* packet = static_cast(osi_calloc(sizeof(BT_HDR) + packet_length)); packet->len = packet_length; return packet; } @@ -131,9 +126,7 @@ class A2dpLdacTest : public ::testing::Test { TEST_F(A2dpLdacTest, a2dp_source_read_underflow) { static int enqueue_cb_invoked = 0; - auto read_cb = +[](uint8_t* p_buf, uint32_t len) -> uint32_t { - return 0; - }; + auto read_cb = +[](uint8_t* p_buf, uint32_t len) -> uint32_t { return 0; }; auto enqueue_cb = +[](BT_HDR* p_buf, size_t frames_n, uint32_t len) -> bool { enqueue_cb_invoked += 1; diff --git a/system/stack/test/a2dp/a2dp_vendor_regression_tests.cc b/system/stack/test/a2dp/a2dp_vendor_regression_tests.cc index e8f30f44eb8..b4fe766fa5a 100644 --- a/system/stack/test/a2dp/a2dp_vendor_regression_tests.cc +++ b/system/stack/test/a2dp/a2dp_vendor_regression_tests.cc @@ -24,7 +24,7 @@ namespace bluetooth { namespace testing { class A2DPVendorRegressionTests : public ::testing::Test { - protected: +protected: void SetUp() override {} void TearDown() override {} }; diff --git a/system/stack/test/a2dp/misc_fake.cc b/system/stack/test/a2dp/misc_fake.cc index a1a926d3ddc..4c583807f09 100644 --- a/system/stack/test/a2dp/misc_fake.cc +++ b/system/stack/test/a2dp/misc_fake.cc @@ -17,7 +17,5 @@ #include "stack/include/a2dp_vendor_ldac.h" int A2DP_VendorGetTrackSampleRateLdac(const uint8_t* p_codec_info) { return 0; } -int A2DP_VendorGetTrackBitsPerSampleLdac(const uint8_t* p_codec_info) { - return 0; -} +int A2DP_VendorGetTrackBitsPerSampleLdac(const uint8_t* p_codec_info) { return 0; } int A2DP_VendorGetChannelModeCodeLdac(const uint8_t* p_codec_info) { return 0; } diff --git a/system/stack/test/a2dp/mock_bta_av_codec.cc b/system/stack/test/a2dp/mock_bta_av_codec.cc index 5b92e13cf38..c4a30a70812 100644 --- a/system/stack/test/a2dp/mock_bta_av_codec.cc +++ b/system/stack/test/a2dp/mock_bta_av_codec.cc @@ -16,6 +16,4 @@ #include "a2dp_codec_api.h" -A2dpCodecConfig* bta_av_get_a2dp_current_codec(void) { - return nullptr; -} +A2dpCodecConfig* bta_av_get_a2dp_current_codec(void) { return nullptr; } diff --git a/system/stack/test/a2dp/test_util.h b/system/stack/test/a2dp/test_util.h index a8c2731faa5..992cfd88720 100644 --- a/system/stack/test/a2dp/test_util.h +++ b/system/stack/test/a2dp/test_util.h @@ -14,10 +14,10 @@ * limitations under the License. */ -#include - #include +#include + namespace bluetooth { namespace testing { diff --git a/system/stack/test/a2dp/wav_reader.h b/system/stack/test/a2dp/wav_reader.h index 9421d91a432..927950c56cc 100644 --- a/system/stack/test/a2dp/wav_reader.h +++ b/system/stack/test/a2dp/wav_reader.h @@ -44,14 +44,14 @@ constexpr size_t kWavHeaderSize = sizeof(WavHeader); } class WavReader { - public: +public: WavReader(const char* filename); ~WavReader(); WavHeader GetHeader() const; uint8_t* GetSamples(); size_t GetSampleCount(); - private: +private: std::ifstream wavFile_; WavHeader header_; std::vector samples_; diff --git a/system/stack/test/a2dp/wav_reader_unittest.cc b/system/stack/test/a2dp/wav_reader_unittest.cc index 4c128495bfe..305efac4dd2 100644 --- a/system/stack/test/a2dp/wav_reader_unittest.cc +++ b/system/stack/test/a2dp/wav_reader_unittest.cc @@ -32,19 +32,21 @@ namespace bluetooth { namespace testing { class WavReaderTest : public ::testing::Test { - protected: +protected: void SetUp() override {} void TearDown() override {} }; TEST_F(WavReaderTest, read_wav_header) { - std::unique_ptr wav_file = std::make_unique(GetWavFilePath(kWavFile).c_str()); + std::unique_ptr wav_file = + std::make_unique(GetWavFilePath(kWavFile).c_str()); ASSERT_EQ(wav_file->GetHeader().sample_rate, kSampleRate); } TEST_F(WavReaderTest, check_wav_sample_count) { - std::unique_ptr wav_file = std::make_unique(GetWavFilePath(kWavFile).c_str()); + std::unique_ptr wav_file = + std::make_unique(GetWavFilePath(kWavFile).c_str()); ASSERT_EQ(wav_file->GetHeader().subchunk2_size, wav_file->GetSampleCount()); } } // namespace testing diff --git a/system/stack/test/ad_parser_unittest.cc b/system/stack/test/ad_parser_unittest.cc index 1f6eb290174..2ef0ebf178e 100644 --- a/system/stack/test/ad_parser_unittest.cc +++ b/system/stack/test/ad_parser_unittest.cc @@ -17,6 +17,7 @@ ******************************************************************************/ #include + #include "advertise_data_parser.h" TEST(AdvertiseDataParserTest, IsValidEmpty) { @@ -51,8 +52,7 @@ TEST(AdvertiseDataParserTest, IsValidBad) { EXPECT_FALSE(AdvertiseDataParser::IsValid(data1)); // Non-zero padding at end of packet. - const std::vector data5{0x03, 0x02, 0x01, 0x02, 0x02, - 0x03, 0x01, 0x00, 0xBA}; + const std::vector data5{0x03, 0x02, 0x01, 0x02, 0x02, 0x03, 0x01, 0x00, 0xBA}; EXPECT_FALSE(AdvertiseDataParser::IsValid(data1)); } @@ -66,42 +66,37 @@ TEST(AdvertiseDataParserTest, IsValidGood) { EXPECT_TRUE(AdvertiseDataParser::IsValid(data1)); // Zero padding at end of packet. - const std::vector data2{0x03, 0x02, 0x01, 0x02, - 0x02, 0x03, 0x01, 0x00}; + const std::vector data2{0x03, 0x02, 0x01, 0x02, 0x02, 0x03, 0x01, 0x00}; EXPECT_TRUE(AdvertiseDataParser::IsValid(data2)); // zero padding at end of packet, sample data from real device - const std::vector data3{ - 0x10, 0x096, 0x85, 0x44, 0x32, 0x04, 0x74, 0x32, 0x03, 0x13, 0x93, - 0xa, 0x32, 0x39, 0x3a, 0x65, 0x32, 0x05, 0x12, 0x50, 0x00, 0x50, - 0x00, 0x02, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + const std::vector data3{0x10, 0x096, 0x85, 0x44, 0x32, 0x04, 0x74, 0x32, + 0x03, 0x13, 0x93, 0xa, 0x32, 0x39, 0x3a, 0x65, + 0x32, 0x05, 0x12, 0x50, 0x00, 0x50, 0x00, 0x02, + 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; EXPECT_TRUE(AdvertiseDataParser::IsValid(data3)); // Test Quirk for Traxxas (bad name length, should be 0x11 is 0x14) - const std::vector data4{0x14, 0x09, 0x54, 0x52, 0x58, 0x20, - 0x42, 0x4C, 0x45, 0x05, 0x12, 0x60, - 0x00, 0xE8, 0x03, 0x02, 0x0A, 0x00}; + const std::vector data4{0x14, 0x09, 0x54, 0x52, 0x58, 0x20, 0x42, 0x4C, 0x45, + 0x05, 0x12, 0x60, 0x00, 0xE8, 0x03, 0x02, 0x0A, 0x00}; EXPECT_TRUE(AdvertiseDataParser::IsValid(data4)); // Test Quirk for Traxxas (bad name length, should be 0x11 is 0x14) - const std::vector data5{0x14, 0x09, 0x54, 0x51, 0x69, 0x20, - 0x42, 0x4C, 0x45, 0x05, 0x12, 0x64, - 0x00, 0xE8, 0x03, 0x02, 0x0A, 0x00}; + const std::vector data5{0x14, 0x09, 0x54, 0x51, 0x69, 0x20, 0x42, 0x4C, 0x45, + 0x05, 0x12, 0x64, 0x00, 0xE8, 0x03, 0x02, 0x0A, 0x00}; EXPECT_TRUE(AdvertiseDataParser::IsValid(data5)); // Test Quirk for Traxxas (bad name length, should be 0x11 is 0x14) - const std::vector data6{0x14, 0x09, 0x54, 0x51, 0x69, 0x20, - 0x42, 0x4C, 0x45, 0x05, 0x12, 0x60, - 0x00, 0xE8, 0x03, 0x02, 0x0A, 0x00}; + const std::vector data6{0x14, 0x09, 0x54, 0x51, 0x69, 0x20, 0x42, 0x4C, 0x45, + 0x05, 0x12, 0x60, 0x00, 0xE8, 0x03, 0x02, 0x0A, 0x00}; EXPECT_TRUE(AdvertiseDataParser::IsValid(data6)); // Test Quirk for Traxxas (bad length, should be 0x11 is 0x14) // scan response glued after advertise data - const std::vector data7{ - 0x02, 0x01, 0x06, 0x11, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x64, 0xB1, 0x73, 0x41, 0xE7, 0xF3, 0xC4, 0xB4, 0x80, - 0x08, 0x14, 0x09, 0x54, 0x51, 0x69, 0x20, 0x42, 0x4C, 0x45, - 0x05, 0x12, 0x60, 0x00, 0xE8, 0x03, 0x02, 0x0A, 0x00}; + const std::vector data7{0x02, 0x01, 0x06, 0x11, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x64, 0xB1, 0x73, 0x41, 0xE7, 0xF3, 0xC4, 0xB4, 0x80, + 0x08, 0x14, 0x09, 0x54, 0x51, 0x69, 0x20, 0x42, 0x4C, 0x45, + 0x05, 0x12, 0x60, 0x00, 0xE8, 0x03, 0x02, 0x0A, 0x00}; EXPECT_TRUE(AdvertiseDataParser::IsValid(data7)); } @@ -110,8 +105,7 @@ TEST(AdvertiseDataParserTest, GetFieldByType) { const std::vector data0{0x03, 0x02, 0x01, 0x02}; uint8_t p_length; - const uint8_t* data = - AdvertiseDataParser::GetFieldByType(data0, 0x02, &p_length); + const uint8_t* data = AdvertiseDataParser::GetFieldByType(data0, 0x02, &p_length); EXPECT_EQ(data0.data() + 2, data); EXPECT_EQ(2, p_length); @@ -133,14 +127,14 @@ TEST(AdvertiseDataParserTest, GetFieldByType) { // run the RemoveTrailingZeros for ad data, then glue scan response at end of // it, and checks that the resulting data is good. TEST(AdvertiseDataParserTest, RemoveTrailingZeros) { - std::vector podo_ad_data{ - 0x02, 0x01, 0x02, 0x11, 0x06, 0x66, 0x9a, 0x0c, 0x20, 0x00, 0x08, - 0x37, 0xa8, 0xe5, 0x11, 0x81, 0x8b, 0xd0, 0xf0, 0xf0, 0xf0, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; - std::vector podo_scan_resp{ - 0x03, 0x19, 0x00, 0x80, 0x09, 0x09, 0x50, 0x6f, 0x64, 0x6f, 0x51, - 0x35, 0x56, 0x47, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + std::vector podo_ad_data{0x02, 0x01, 0x02, 0x11, 0x06, 0x66, 0x9a, 0x0c, + 0x20, 0x00, 0x08, 0x37, 0xa8, 0xe5, 0x11, 0x81, + 0x8b, 0xd0, 0xf0, 0xf0, 0xf0, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + std::vector podo_scan_resp{0x03, 0x19, 0x00, 0x80, 0x09, 0x09, 0x50, 0x6f, + 0x64, 0x6f, 0x51, 0x35, 0x56, 0x47, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; AdvertiseDataParser::RemoveTrailingZeros(podo_ad_data); AdvertiseDataParser::RemoveTrailingZeros(podo_scan_resp); @@ -158,14 +152,12 @@ TEST(AdvertiseDataParserTest, RemoveTrailingZeros) { // bytes after zero length field to be zero padding, but many legacy devices got // this wrong, causing us to have this workaround. TEST(AdvertiseDataParserTest, RemoveTrailingZerosMalformed) { - std::vector ad_data{0x02, 0x01, 0x02, 0x11, 0x06, 0x66, 0x9a, 0x0c, - 0x20, 0x00, 0x08, 0x37, 0xa8, 0xe5, 0x11, 0x81, - 0x8b, 0xd0, 0xf0, 0xf0, 0xf0, 0x00, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; - std::vector scan_resp{0x03, 0x19, 0x00, 0x80, 0x09, 0x09, 0x50, 0x6f, - 0x64, 0x6f, 0x51, 0x35, 0x56, 0x47, 0x00, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; + std::vector ad_data{0x02, 0x01, 0x02, 0x11, 0x06, 0x66, 0x9a, 0x0c, 0x20, 0x00, 0x08, + 0x37, 0xa8, 0xe5, 0x11, 0x81, 0x8b, 0xd0, 0xf0, 0xf0, 0xf0, 0x00, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; + std::vector scan_resp{0x03, 0x19, 0x00, 0x80, 0x09, 0x09, 0x50, 0x6f, 0x64, 0x6f, 0x51, + 0x35, 0x56, 0x47, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; AdvertiseDataParser::RemoveTrailingZeros(ad_data); AdvertiseDataParser::RemoveTrailingZeros(scan_resp); @@ -179,23 +171,20 @@ TEST(AdvertiseDataParserTest, RemoveTrailingZerosMalformed) { TEST(AdvertiseDataParserTest, GetFieldByTypeInLoop) { // Single field. const uint8_t AD_TYPE_SVC_DATA = 0x16; - const std::vector data0{ - 0x02, 0x01, 0x02, - 0x07, 0x2e, 0x6a, 0xc1, 0x19, 0x52, 0x1e, 0x49, - 0x09, 0x16, 0x4e, 0x18, 0x00, 0xff, 0x0f, 0x03, 0x00, 0x00, - 0x02, 0x0a, 0x7f, - 0x03, 0x16, 0x4f, 0x18, - 0x04, 0x16, 0x53, 0x18, 0x00, - 0x0f, 0x09, 0x48, 0x5f, 0x43, 0x33, 0x45, 0x41, 0x31, 0x36, 0x33, 0x46, 0x35, 0x36, 0x34, 0x46 }; + const std::vector data0{0x02, 0x01, 0x02, 0x07, 0x2e, 0x6a, 0xc1, 0x19, 0x52, 0x1e, + 0x49, 0x09, 0x16, 0x4e, 0x18, 0x00, 0xff, 0x0f, 0x03, 0x00, + 0x00, 0x02, 0x0a, 0x7f, 0x03, 0x16, 0x4f, 0x18, 0x04, 0x16, + 0x53, 0x18, 0x00, 0x0f, 0x09, 0x48, 0x5f, 0x43, 0x33, 0x45, + 0x41, 0x31, 0x36, 0x33, 0x46, 0x35, 0x36, 0x34, 0x46}; const uint8_t* p_service_data = data0.data(); uint8_t service_data_len = 0; int match_no = 0; while ((p_service_data = AdvertiseDataParser::GetFieldByType( - p_service_data + service_data_len, - data0.size() - (p_service_data - data0.data()) - service_data_len, - AD_TYPE_SVC_DATA, &service_data_len))) { + p_service_data + service_data_len, + data0.size() - (p_service_data - data0.data()) - service_data_len, + AD_TYPE_SVC_DATA, &service_data_len))) { auto position = (p_service_data - data0.data()); if (match_no == 0) { EXPECT_EQ(position, 13); diff --git a/system/stack/test/btm/btm_test_fixtures.h b/system/stack/test/btm/btm_test_fixtures.h index fee9e5f4bc1..27d6648053d 100644 --- a/system/stack/test/btm/btm_test_fixtures.h +++ b/system/stack/test/btm/btm_test_fixtures.h @@ -22,7 +22,7 @@ #include "test/fake/fake_osi.h" class BtmWithFakesTest : public testing::Test { - protected: +protected: void SetUp() override { fake_osi_ = std::make_unique(); } void TearDown() override { fake_osi_.reset(); } @@ -31,7 +31,7 @@ class BtmWithFakesTest : public testing::Test { // Setup any default or optional mocks class BtmWithMocksTest : public BtmWithFakesTest { - protected: +protected: void SetUp() override { BtmWithFakesTest::SetUp(); reset_mock_function_count_map(); diff --git a/system/stack/test/btm/peer_packet_types_test.cc b/system/stack/test/btm/peer_packet_types_test.cc index aeae23770c5..ab104701242 100644 --- a/system/stack/test/btm/peer_packet_types_test.cc +++ b/system/stack/test/btm/peer_packet_types_test.cc @@ -35,47 +35,42 @@ using testing::StrictMock; using testing::Test; class PeerPacketTest : public Test { - public: - protected: +public: +protected: void SetUp() override {} void TearDown() override {} }; TEST_F(PeerPacketTest, all_ones) { - const BD_FEATURES bd_features = {0xff, 0xff, 0xff, 0xff, - 0xff, 0xff, 0xff, 0xff}; + const BD_FEATURES bd_features = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; PeerPacketTypes peer_packet_types(bd_features); ASSERT_EQ(peer_packet_types.acl.supported, 0xcc18); ASSERT_EQ(peer_packet_types.acl.unsupported, 0x0); } TEST_F(PeerPacketTest, 3SLOT_DH3_DM3) { - const BD_FEATURES bd_features = {0x01, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00}; + const BD_FEATURES bd_features = {0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; PeerPacketTypes peer_packet_types(bd_features); ASSERT_EQ(peer_packet_types.acl.supported, 0x0c18); ASSERT_EQ(peer_packet_types.acl.unsupported, 0x3306); } TEST_F(PeerPacketTest, 5SLOT_DH5_DM5) { - const BD_FEATURES bd_features = {0x02, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00}; + const BD_FEATURES bd_features = {0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; PeerPacketTypes peer_packet_types(bd_features); ASSERT_EQ(peer_packet_types.acl.supported, 0xc018); ASSERT_EQ(peer_packet_types.acl.unsupported, 0x3306); } TEST_F(PeerPacketTest, 2Mb_support) { - const BD_FEATURES bd_features = {0x00, 0x00, 0x00, 0x02, - 0x00, 0x00, 0x00, 0x00}; + const BD_FEATURES bd_features = {0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00}; PeerPacketTypes peer_packet_types(bd_features); ASSERT_EQ(peer_packet_types.acl.supported, 0x0018); ASSERT_EQ(peer_packet_types.acl.unsupported, 0x3304); } TEST_F(PeerPacketTest, 3Mb_support) { - const BD_FEATURES bd_features = {0x00, 0x00, 0x00, 0x04, - 0x00, 0x00, 0x00, 0x00}; + const BD_FEATURES bd_features = {0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00}; PeerPacketTypes peer_packet_types(bd_features); ASSERT_EQ(peer_packet_types.acl.supported, 0x0018); ASSERT_EQ(peer_packet_types.acl.unsupported, 0x3302); diff --git a/system/stack/test/btm/sco_hci_test.cc b/system/stack/test/btm/sco_hci_test.cc index 42567cc5fcf..433546dc27a 100644 --- a/system/stack/test/btm/sco_hci_test.cc +++ b/system/stack/test/btm/sco_hci_test.cc @@ -47,31 +47,29 @@ using testing::Le; using testing::Test; const std::vector msbc_zero_packet{ - 0x01, 0x08, 0xad, 0x00, 0x00, 0xc5, 0x00, 0x00, 0x00, 0x00, 0x77, 0x6d, - 0xb6, 0xdd, 0xdb, 0x6d, 0xb7, 0x76, 0xdb, 0x6d, 0xdd, 0xb6, 0xdb, 0x77, - 0x6d, 0xb6, 0xdd, 0xdb, 0x6d, 0xb7, 0x76, 0xdb, 0x6d, 0xdd, 0xb6, 0xdb, - 0x77, 0x6d, 0xb6, 0xdd, 0xdb, 0x6d, 0xb7, 0x76, 0xdb, 0x6d, 0xdd, 0xb6, - 0xdb, 0x77, 0x6d, 0xb6, 0xdd, 0xdb, 0x6d, 0xb7, 0x76, 0xdb, 0x6c, 0x00}; + 0x01, 0x08, 0xad, 0x00, 0x00, 0xc5, 0x00, 0x00, 0x00, 0x00, 0x77, 0x6d, 0xb6, 0xdd, 0xdb, + 0x6d, 0xb7, 0x76, 0xdb, 0x6d, 0xdd, 0xb6, 0xdb, 0x77, 0x6d, 0xb6, 0xdd, 0xdb, 0x6d, 0xb7, + 0x76, 0xdb, 0x6d, 0xdd, 0xb6, 0xdb, 0x77, 0x6d, 0xb6, 0xdd, 0xdb, 0x6d, 0xb7, 0x76, 0xdb, + 0x6d, 0xdd, 0xb6, 0xdb, 0x77, 0x6d, 0xb6, 0xdd, 0xdb, 0x6d, 0xb7, 0x76, 0xdb, 0x6c, 0x00}; const std::vector lc3_zero_packet{ - 0x01, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x38, 0x24, 0xf9, 0x4a, 0x0d, 0x00, 0x00, 0x03}; + 0x01, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x24, 0xf9, 0x4a, 0x0d, 0x00, 0x00, 0x03}; // Maps irregular packet size to expected decode buffer size. // See |btm_wbs_supported_pkt_size| and |btm_wbs_msbc_buffer_size|. const std::map irregular_packet_to_buffer_size{ - {72, 360}, - {24, 120}, + {72, 360}, + {24, 120}, }; // The encoded packet size is 60 regardless of the codec. const int ENCODED_PACKET_SIZE = 60; struct MsbcCodecInterface : bluetooth::core::CodecInterface { - MsbcCodecInterface() : bluetooth::core::CodecInterface(){}; + MsbcCodecInterface() : bluetooth::core::CodecInterface() {} void initialize() override { hfp_msbc_decoder_init(); @@ -93,7 +91,7 @@ struct MsbcCodecInterface : bluetooth::core::CodecInterface { }; struct Lc3CodecInterface : bluetooth::core::CodecInterface { - Lc3CodecInterface() : bluetooth::core::CodecInterface(){}; + Lc3CodecInterface() : bluetooth::core::CodecInterface() {} void initialize() override { hfp_lc3_decoder_init(); @@ -115,8 +113,8 @@ struct Lc3CodecInterface : bluetooth::core::CodecInterface { }; class ScoHciTest : public BtmWithMocksTest { - public: - protected: +public: +protected: void SetUp() override { BtmWithMocksTest::SetUp(); mock_uipc_init_ret = nullptr; @@ -132,8 +130,8 @@ class ScoHciTest : public BtmWithMocksTest { }; class ScoHciWithOpenCleanTest : public ScoHciTest { - public: - protected: +public: +protected: void SetUp() override { ScoHciTest::SetUp(); mock_uipc_init_ret = std::make_unique(); @@ -146,8 +144,8 @@ class ScoHciWbsTest : public ScoHciTest {}; class ScoHciSwbTest : public ScoHciTest {}; class ScoHciWbsWithInitCleanTest : public ScoHciTest { - public: - protected: +public: +protected: void SetUp() override { ScoHciTest::SetUp(); bluetooth::audio::sco::wbs::init(60); @@ -156,8 +154,8 @@ class ScoHciWbsWithInitCleanTest : public ScoHciTest { }; class ScoHciSwbWithInitCleanTest : public ScoHciTest { - public: - protected: +public: +protected: void SetUp() override { ScoHciTest::SetUp(); bluetooth::audio::sco::swb::init(60); @@ -265,7 +263,9 @@ TEST_F(ScoHciSwbTest, SwbEnqueuePacketWithoutInit) { TEST_F(ScoHciWbsWithInitCleanTest, WbsEnqueuePacket) { std::vector payload; - for (size_t i = 0; i < 60; i++) payload.push_back(0); + for (size_t i = 0; i < 60; i++) { + payload.push_back(0); + } ASSERT_EQ(bluetooth::audio::sco::wbs::enqueue_packet(payload, false), true); // Return 0 if buffer is full ASSERT_EQ(bluetooth::audio::sco::wbs::enqueue_packet(payload, false), false); @@ -273,7 +273,9 @@ TEST_F(ScoHciWbsWithInitCleanTest, WbsEnqueuePacket) { TEST_F(ScoHciSwbWithInitCleanTest, SwbEnqueuePacket) { std::vector payload; - for (size_t i = 0; i < 60; i++) payload.push_back(0); + for (size_t i = 0; i < 60; i++) { + payload.push_back(0); + } ASSERT_EQ(bluetooth::audio::sco::swb::enqueue_packet(payload, false), true); // Return 0 if buffer is full ASSERT_EQ(bluetooth::audio::sco::swb::enqueue_packet(payload, false), false); @@ -296,7 +298,9 @@ TEST_F(ScoHciSwbTest, SwbDecodeWithoutInit) { TEST_F(ScoHciWbsWithInitCleanTest, WbsDecode) { const uint8_t* decoded = nullptr; std::vector payload; - for (size_t i = 0; i < 60; i++) payload.push_back(0); + for (size_t i = 0; i < 60; i++) { + payload.push_back(0); + } // No data to decode ASSERT_EQ(bluetooth::audio::sco::wbs::decode(&decoded), size_t(0)); @@ -306,18 +310,15 @@ TEST_F(ScoHciWbsWithInitCleanTest, WbsDecode) { // Return all zero frames when there comes an invalid packet. // This is expected even with PLC as there is no history in the PLC buffer. - ASSERT_EQ(bluetooth::audio::sco::wbs::decode(&decoded), - size_t(BTM_MSBC_CODE_SIZE)); + ASSERT_EQ(bluetooth::audio::sco::wbs::decode(&decoded), size_t(BTM_MSBC_CODE_SIZE)); ASSERT_NE(decoded, nullptr); for (size_t i = 0; i < BTM_MSBC_CODE_SIZE; i++) { ASSERT_EQ(decoded[i], 0); } decoded = nullptr; - ASSERT_EQ(bluetooth::audio::sco::wbs::enqueue_packet(msbc_zero_packet, false), - true); - ASSERT_EQ(bluetooth::audio::sco::wbs::decode(&decoded), - size_t(BTM_MSBC_CODE_SIZE)); + ASSERT_EQ(bluetooth::audio::sco::wbs::enqueue_packet(msbc_zero_packet, false), true); + ASSERT_EQ(bluetooth::audio::sco::wbs::decode(&decoded), size_t(BTM_MSBC_CODE_SIZE)); ASSERT_NE(decoded, nullptr); for (size_t i = 0; i < BTM_MSBC_CODE_SIZE; i++) { ASSERT_EQ(decoded[i], 0); @@ -332,7 +333,9 @@ TEST_F(ScoHciWbsWithInitCleanTest, WbsDecode) { TEST_F(ScoHciSwbWithInitCleanTest, SwbDecode) { const uint8_t* decoded = nullptr; std::vector payload; - for (size_t i = 0; i < 60; i++) payload.push_back(0); + for (size_t i = 0; i < 60; i++) { + payload.push_back(0); + } // No data to decode ASSERT_EQ(bluetooth::audio::sco::swb::decode(&decoded), size_t(0)); @@ -342,18 +345,15 @@ TEST_F(ScoHciSwbWithInitCleanTest, SwbDecode) { // Return all zero frames when there comes an invalid packet. // This is expected even with PLC as there is no history in the PLC buffer. - ASSERT_EQ(bluetooth::audio::sco::swb::decode(&decoded), - size_t(BTM_LC3_CODE_SIZE)); + ASSERT_EQ(bluetooth::audio::sco::swb::decode(&decoded), size_t(BTM_LC3_CODE_SIZE)); ASSERT_NE(decoded, nullptr); for (size_t i = 0; i < BTM_LC3_CODE_SIZE; i++) { ASSERT_EQ(decoded[i], 0); } decoded = nullptr; - ASSERT_EQ(bluetooth::audio::sco::swb::enqueue_packet(lc3_zero_packet, false), - true); - ASSERT_EQ(bluetooth::audio::sco::swb::decode(&decoded), - size_t(BTM_LC3_CODE_SIZE)); + ASSERT_EQ(bluetooth::audio::sco::swb::enqueue_packet(lc3_zero_packet, false), true); + ASSERT_EQ(bluetooth::audio::sco::swb::decode(&decoded), size_t(BTM_LC3_CODE_SIZE)); ASSERT_NE(decoded, nullptr); for (size_t i = 0; i < BTM_LC3_CODE_SIZE; i++) { ASSERT_EQ(decoded[i], 0); @@ -381,24 +381,19 @@ TEST_F(ScoHciWbsTest, WbsDecodeWithIrregularOffset) { // packet size. std::vector payload = std::vector(1, 0); while (payload.size() <= pkt_size) { - payload.insert(payload.end(), msbc_zero_packet.begin(), - msbc_zero_packet.end()); + payload.insert(payload.end(), msbc_zero_packet.begin(), msbc_zero_packet.end()); } - size_t packet_offset = - msbc_zero_packet.size() - (payload.size() - pkt_size); + size_t packet_offset = msbc_zero_packet.size() - (payload.size() - pkt_size); payload.resize(pkt_size); // Try to decode as many packets as to hit the boundary. - for (size_t iter = 0, decodable = 0; iter < 2 * buf_size / pkt_size; - ++iter) { - ASSERT_EQ(bluetooth::audio::sco::wbs::enqueue_packet(payload, false), - true); + for (size_t iter = 0, decodable = 0; iter < 2 * buf_size / pkt_size; ++iter) { + ASSERT_EQ(bluetooth::audio::sco::wbs::enqueue_packet(payload, false), true); decodable += payload.size() - !iter; // compensate for the first offset while (decodable >= ENCODED_PACKET_SIZE) { decoded = nullptr; - ASSERT_EQ(bluetooth::audio::sco::wbs::decode(&decoded), - size_t(BTM_MSBC_CODE_SIZE)); + ASSERT_EQ(bluetooth::audio::sco::wbs::decode(&decoded), size_t(BTM_MSBC_CODE_SIZE)); ASSERT_NE(decoded, nullptr); for (size_t i = 0; i < BTM_MSBC_CODE_SIZE; i++) { ASSERT_EQ(decoded[i], 0); @@ -409,12 +404,11 @@ TEST_F(ScoHciWbsTest, WbsDecodeWithIrregularOffset) { payload = std::vector(msbc_zero_packet.begin() + packet_offset, msbc_zero_packet.end()); while (payload.size() < pkt_size) { - payload.insert(payload.end(), msbc_zero_packet.begin(), - msbc_zero_packet.end()); + payload.insert(payload.end(), msbc_zero_packet.begin(), msbc_zero_packet.end()); } packet_offset += msbc_zero_packet.size() - packet_offset; - packet_offset += msbc_zero_packet.size() - - (payload.size() - pkt_size) % msbc_zero_packet.size(); + packet_offset += + msbc_zero_packet.size() - (payload.size() - pkt_size) % msbc_zero_packet.size(); packet_offset %= msbc_zero_packet.size(); payload.resize(pkt_size); } @@ -439,23 +433,19 @@ TEST_F(ScoHciSwbTest, SwbDecodeWithIrregularOffset) { // packet size. std::vector payload = std::vector(1, 0); while (payload.size() <= pkt_size) { - payload.insert(payload.end(), lc3_zero_packet.begin(), - lc3_zero_packet.end()); + payload.insert(payload.end(), lc3_zero_packet.begin(), lc3_zero_packet.end()); } size_t packet_offset = lc3_zero_packet.size() - (payload.size() - pkt_size); payload.resize(pkt_size); // Try to decode as many packets as to hit the boundary. - for (size_t iter = 0, decodable = 0; iter < 2 * buf_size / pkt_size; - ++iter) { - ASSERT_EQ(bluetooth::audio::sco::swb::enqueue_packet(payload, false), - true); + for (size_t iter = 0, decodable = 0; iter < 2 * buf_size / pkt_size; ++iter) { + ASSERT_EQ(bluetooth::audio::sco::swb::enqueue_packet(payload, false), true); decodable += payload.size() - !iter; // compensate for the first offset while (decodable >= ENCODED_PACKET_SIZE) { decoded = nullptr; - ASSERT_EQ(bluetooth::audio::sco::swb::decode(&decoded), - size_t(BTM_LC3_CODE_SIZE)); + ASSERT_EQ(bluetooth::audio::sco::swb::decode(&decoded), size_t(BTM_LC3_CODE_SIZE)); ASSERT_NE(decoded, nullptr); for (size_t i = 0; i < BTM_LC3_CODE_SIZE; i++) { ASSERT_EQ(decoded[i], 0); @@ -463,15 +453,14 @@ TEST_F(ScoHciSwbTest, SwbDecodeWithIrregularOffset) { decodable -= ENCODED_PACKET_SIZE; } - payload = std::vector(lc3_zero_packet.begin() + packet_offset, - lc3_zero_packet.end()); + payload = + std::vector(lc3_zero_packet.begin() + packet_offset, lc3_zero_packet.end()); while (payload.size() < pkt_size) { - payload.insert(payload.end(), lc3_zero_packet.begin(), - lc3_zero_packet.end()); + payload.insert(payload.end(), lc3_zero_packet.begin(), lc3_zero_packet.end()); } packet_offset += lc3_zero_packet.size() - packet_offset; - packet_offset += lc3_zero_packet.size() - - (payload.size() - pkt_size) % lc3_zero_packet.size(); + packet_offset += + lc3_zero_packet.size() - (payload.size() - pkt_size) % lc3_zero_packet.size(); packet_offset %= lc3_zero_packet.size(); payload.resize(pkt_size); } @@ -496,13 +485,10 @@ TEST_F(ScoHciWbsWithInitCleanTest, WbsEncode) { int16_t data[120] = {0}; // Return 0 if data is invalid - ASSERT_EQ(bluetooth::audio::sco::wbs::encode(nullptr, sizeof(data)), - size_t(0)); + ASSERT_EQ(bluetooth::audio::sco::wbs::encode(nullptr, sizeof(data)), size_t(0)); // Return 0 if data length is insufficient - ASSERT_EQ(bluetooth::audio::sco::wbs::encode(data, sizeof(data) - 1), - size_t(0)); - ASSERT_EQ(bluetooth::audio::sco::wbs::encode(data, sizeof(data)), - sizeof(data)); + ASSERT_EQ(bluetooth::audio::sco::wbs::encode(data, sizeof(data) - 1), size_t(0)); + ASSERT_EQ(bluetooth::audio::sco::wbs::encode(data, sizeof(data)), sizeof(data)); // Return 0 if the packet buffer is full ASSERT_EQ(bluetooth::audio::sco::wbs::encode(data, sizeof(data)), size_t(0)); @@ -512,13 +498,10 @@ TEST_F(ScoHciSwbWithInitCleanTest, SwbEncode) { int16_t data[BTM_LC3_CODE_SIZE / 2] = {0}; // Return 0 if data is invalid - ASSERT_EQ(bluetooth::audio::sco::swb::encode(nullptr, sizeof(data)), - size_t(0)); + ASSERT_EQ(bluetooth::audio::sco::swb::encode(nullptr, sizeof(data)), size_t(0)); // Return 0 if data length is insufficient - ASSERT_EQ(bluetooth::audio::sco::swb::encode(data, sizeof(data) - 1), - size_t(0)); - ASSERT_EQ(bluetooth::audio::sco::swb::encode(data, sizeof(data)), - sizeof(data)); + ASSERT_EQ(bluetooth::audio::sco::swb::encode(data, sizeof(data) - 1), size_t(0)); + ASSERT_EQ(bluetooth::audio::sco::swb::encode(data, sizeof(data)), sizeof(data)); // Return 0 if the packet buffer is full ASSERT_EQ(bluetooth::audio::sco::swb::encode(data, sizeof(data)), size_t(0)); @@ -566,13 +549,11 @@ TEST_F(ScoHciWbsWithInitCleanTest, WbsEncodeDequeuePackets) { const uint8_t* encoded = nullptr; for (size_t i = 0; i < 5; i++) { - ASSERT_EQ(bluetooth::audio::sco::wbs::encode(data, sizeof(data)), - sizeof(data)); + ASSERT_EQ(bluetooth::audio::sco::wbs::encode(data, sizeof(data)), sizeof(data)); ASSERT_EQ(bluetooth::audio::sco::wbs::dequeue_packet(&encoded), size_t(60)); ASSERT_NE(encoded, nullptr); for (size_t j = 0; j < 60; j++) { - ASSERT_EQ(encoded[j], - j == 1 ? h2_header_frames_count[i % 4] : msbc_zero_packet[j]); + ASSERT_EQ(encoded[j], j == 1 ? h2_header_frames_count[i % 4] : msbc_zero_packet[j]); } } } @@ -583,13 +564,11 @@ TEST_F(ScoHciSwbWithInitCleanTest, SwbEncodeDequeuePackets) { const uint8_t* encoded = nullptr; for (size_t i = 0; i < 5; i++) { - ASSERT_EQ(bluetooth::audio::sco::swb::encode(data, sizeof(data)), - sizeof(data)); + ASSERT_EQ(bluetooth::audio::sco::swb::encode(data, sizeof(data)), sizeof(data)); ASSERT_EQ(bluetooth::audio::sco::swb::dequeue_packet(&encoded), size_t(60)); ASSERT_NE(encoded, nullptr); for (size_t j = 0; j < 60; j++) { - ASSERT_EQ(encoded[j], - j == 1 ? h2_header_frames_count[i % 4] : lc3_zero_packet[j]); + ASSERT_EQ(encoded[j], j == 1 ? h2_header_frames_count[i % 4] : lc3_zero_packet[j]); } } } @@ -600,7 +579,9 @@ TEST_F(ScoHciWbsWithInitCleanTest, WbsPlc) { int16_t data[120]; int16_t expect_data[120]; std::vector encoded_vec; - for (size_t i = 0; i < 60; i++) encoded_vec.push_back(0); + for (size_t i = 0; i < 60; i++) { + encoded_vec.push_back(0); + } const uint8_t* encoded = nullptr; const uint8_t* decoded = nullptr; size_t lost_pkt_idx = 17; @@ -608,64 +589,56 @@ TEST_F(ScoHciWbsWithInitCleanTest, WbsPlc) { // Simulate a run without any packet loss for (size_t i = 0, sample_idx = 0; i <= lost_pkt_idx; i++) { // Input data is a 1000Hz triangle wave - for (size_t j = 0; j < 120; j++, sample_idx++) + for (size_t j = 0; j < 120; j++, sample_idx++) { data[j] = triangle[sample_idx % 16]; + } // Build the packet - ASSERT_EQ(bluetooth::audio::sco::wbs::encode(data, sizeof(data)), - sizeof(data)); + ASSERT_EQ(bluetooth::audio::sco::wbs::encode(data, sizeof(data)), sizeof(data)); ASSERT_EQ(bluetooth::audio::sco::wbs::dequeue_packet(&encoded), size_t(60)); ASSERT_NE(encoded, nullptr); // Simulate the reception of the packet std::copy(encoded, encoded + size_t(60), encoded_vec.data()); - ASSERT_EQ(bluetooth::audio::sco::wbs::enqueue_packet(encoded_vec, false), - true); - ASSERT_EQ(bluetooth::audio::sco::wbs::decode(&decoded), - size_t(BTM_MSBC_CODE_SIZE)); + ASSERT_EQ(bluetooth::audio::sco::wbs::enqueue_packet(encoded_vec, false), true); + ASSERT_EQ(bluetooth::audio::sco::wbs::decode(&decoded), size_t(BTM_MSBC_CODE_SIZE)); ASSERT_NE(decoded, nullptr); } // Store the decoded data we expect to get - std::copy((const int16_t*)decoded, - (const int16_t*)(decoded + BTM_MSBC_CODE_SIZE), expect_data); + std::copy((const int16_t*)decoded, (const int16_t*)(decoded + BTM_MSBC_CODE_SIZE), expect_data); // Start with the fresh WBS buffer bluetooth::audio::sco::wbs::cleanup(); bluetooth::audio::sco::wbs::init(60); // check PLC returns gracefully with invalid parameters - ASSERT_EQ(bluetooth::audio::sco::wbs::fill_plc_stats(nullptr, nullptr), - false); + ASSERT_EQ(bluetooth::audio::sco::wbs::fill_plc_stats(nullptr, nullptr), false); int num_decoded_frames; double packet_loss_ratio; // check PLC returns gracefully when there hasn't been decoded frames - ASSERT_EQ(bluetooth::audio::sco::wbs::fill_plc_stats(&num_decoded_frames, - &packet_loss_ratio), + ASSERT_EQ(bluetooth::audio::sco::wbs::fill_plc_stats(&num_decoded_frames, &packet_loss_ratio), false); int decode_count = 0; for (size_t i = 0, sample_idx = 0; i <= lost_pkt_idx; i++) { // Data is a 1000Hz triangle wave - for (size_t j = 0; j < 120; j++, sample_idx++) + for (size_t j = 0; j < 120; j++, sample_idx++) { data[j] = triangle[sample_idx % 16]; - ASSERT_EQ(bluetooth::audio::sco::wbs::encode(data, sizeof(data)), - sizeof(data)); + } + ASSERT_EQ(bluetooth::audio::sco::wbs::encode(data, sizeof(data)), sizeof(data)); ASSERT_EQ(bluetooth::audio::sco::wbs::dequeue_packet(&encoded), size_t(60)); ASSERT_NE(encoded, nullptr); // Substitute to invalid packet to simulate packet loss. std::copy(encoded, encoded + size_t(60), encoded_vec.data()); ASSERT_EQ(bluetooth::audio::sco::wbs::enqueue_packet( - i != lost_pkt_idx ? encoded_vec : std::vector(60, 0), - false), + i != lost_pkt_idx ? encoded_vec : std::vector(60, 0), false), true); - ASSERT_EQ(bluetooth::audio::sco::wbs::decode(&decoded), - size_t(BTM_MSBC_CODE_SIZE)); + ASSERT_EQ(bluetooth::audio::sco::wbs::decode(&decoded), size_t(BTM_MSBC_CODE_SIZE)); decode_count++; ASSERT_NE(decoded, nullptr); } - ASSERT_EQ(bluetooth::audio::sco::wbs::fill_plc_stats(&num_decoded_frames, - &packet_loss_ratio), + ASSERT_EQ(bluetooth::audio::sco::wbs::fill_plc_stats(&num_decoded_frames, &packet_loss_ratio), true); ASSERT_EQ(num_decoded_frames, decode_count); ASSERT_EQ(packet_loss_ratio, (double)1 / decode_count); @@ -676,8 +649,8 @@ TEST_F(ScoHciWbsWithInitCleanTest, WbsPlc) { // 1. mSBC decoder is statefull // 2. We apply overlap-add to glue the frames when packet loss happens ASSERT_THAT(ptr[i] - expect_data[i], AllOf(Ge(-3), Le(3))) - << "PLC data " << ptr[i] << " deviates from expected " << expect_data[i] - << " at index " << i; + << "PLC data " << ptr[i] << " deviates from expected " << expect_data[i] << " at index " + << i; } size_t corrupted_pkt_idx = lost_pkt_idx; @@ -687,26 +660,23 @@ TEST_F(ScoHciWbsWithInitCleanTest, WbsPlc) { bluetooth::audio::sco::wbs::init(60); for (size_t i = 0, sample_idx = 0; i <= corrupted_pkt_idx; i++) { // Data is a 1000Hz triangle wave - for (size_t j = 0; j < 120; j++, sample_idx++) + for (size_t j = 0; j < 120; j++, sample_idx++) { data[j] = triangle[sample_idx % 16]; - ASSERT_EQ(bluetooth::audio::sco::wbs::encode(data, sizeof(data)), - sizeof(data)); + } + ASSERT_EQ(bluetooth::audio::sco::wbs::encode(data, sizeof(data)), sizeof(data)); ASSERT_EQ(bluetooth::audio::sco::wbs::dequeue_packet(&encoded), size_t(60)); ASSERT_NE(encoded, nullptr); // Substitute to report packet corrupted to simulate packet loss. std::copy(encoded, encoded + size_t(60), encoded_vec.data()); - ASSERT_EQ(bluetooth::audio::sco::wbs::enqueue_packet( - encoded_vec, i == corrupted_pkt_idx), + ASSERT_EQ(bluetooth::audio::sco::wbs::enqueue_packet(encoded_vec, i == corrupted_pkt_idx), true); - ASSERT_EQ(bluetooth::audio::sco::wbs::decode(&decoded), - size_t(BTM_MSBC_CODE_SIZE)); + ASSERT_EQ(bluetooth::audio::sco::wbs::decode(&decoded), size_t(BTM_MSBC_CODE_SIZE)); decode_count++; ASSERT_NE(decoded, nullptr); } - ASSERT_EQ(bluetooth::audio::sco::wbs::fill_plc_stats(&num_decoded_frames, - &packet_loss_ratio), + ASSERT_EQ(bluetooth::audio::sco::wbs::fill_plc_stats(&num_decoded_frames, &packet_loss_ratio), true); ASSERT_EQ(num_decoded_frames, decode_count); ASSERT_EQ(packet_loss_ratio, (double)1 / decode_count); @@ -717,8 +687,8 @@ TEST_F(ScoHciWbsWithInitCleanTest, WbsPlc) { // 1. mSBC decoder is statefull // 2. We apply overlap-add to glue the frames when packet loss happens ASSERT_THAT(ptr[i] - expect_data[i], AllOf(Ge(-3), Le(3))) - << "PLC data " << ptr[i] << " deviates from expected " << expect_data[i] - << " at index " << i; + << "PLC data " << ptr[i] << " deviates from expected " << expect_data[i] << " at index " + << i; } } @@ -730,7 +700,9 @@ TEST_F(ScoHciSwbWithInitCleanTest, SwbPlc) { int16_t data[BTM_LC3_CODE_SIZE / 2]; int16_t expect_data[BTM_LC3_CODE_SIZE / 2]; std::vector encoded_vec; - for (size_t i = 0; i < 60; i++) encoded_vec.push_back(0); + for (size_t i = 0; i < 60; i++) { + encoded_vec.push_back(0); + } const uint8_t* encoded = nullptr; const uint8_t* decoded = nullptr; size_t lost_pkt_idx = 17; @@ -738,64 +710,56 @@ TEST_F(ScoHciSwbWithInitCleanTest, SwbPlc) { // Simulate a run without any packet loss for (size_t i = 0, sample_idx = 0; i <= lost_pkt_idx; i++) { // Input data is a 1000Hz triangle wave - for (size_t j = 0; j < BTM_LC3_CODE_SIZE / 2; j++, sample_idx++) + for (size_t j = 0; j < BTM_LC3_CODE_SIZE / 2; j++, sample_idx++) { data[j] = triangle[sample_idx % 16]; + } // Build the packet - ASSERT_EQ(bluetooth::audio::sco::swb::encode(data, sizeof(data)), - sizeof(data)); + ASSERT_EQ(bluetooth::audio::sco::swb::encode(data, sizeof(data)), sizeof(data)); ASSERT_EQ(bluetooth::audio::sco::swb::dequeue_packet(&encoded), size_t(60)); ASSERT_NE(encoded, nullptr); // Simulate the reception of the packet std::copy(encoded, encoded + size_t(60), encoded_vec.data()); - ASSERT_EQ(bluetooth::audio::sco::swb::enqueue_packet(encoded_vec, false), - true); - ASSERT_EQ(bluetooth::audio::sco::swb::decode(&decoded), - size_t(BTM_LC3_CODE_SIZE)); + ASSERT_EQ(bluetooth::audio::sco::swb::enqueue_packet(encoded_vec, false), true); + ASSERT_EQ(bluetooth::audio::sco::swb::decode(&decoded), size_t(BTM_LC3_CODE_SIZE)); ASSERT_NE(decoded, nullptr); } // Store the decoded data we expect to get - std::copy((const int16_t*)decoded, - (const int16_t*)(decoded + BTM_LC3_CODE_SIZE), expect_data); + std::copy((const int16_t*)decoded, (const int16_t*)(decoded + BTM_LC3_CODE_SIZE), expect_data); // Start with the fresh SWB buffer bluetooth::audio::sco::swb::cleanup(); bluetooth::audio::sco::swb::init(60); // check PLC returns gracefully with invalid parameters - ASSERT_EQ(bluetooth::audio::sco::swb::fill_plc_stats(nullptr, nullptr), - false); + ASSERT_EQ(bluetooth::audio::sco::swb::fill_plc_stats(nullptr, nullptr), false); int num_decoded_frames; double packet_loss_ratio; // check PLC returns gracefully when there hasn't been decoded frames - ASSERT_EQ(bluetooth::audio::sco::swb::fill_plc_stats(&num_decoded_frames, - &packet_loss_ratio), + ASSERT_EQ(bluetooth::audio::sco::swb::fill_plc_stats(&num_decoded_frames, &packet_loss_ratio), false); int decode_count = 0; for (size_t i = 0, sample_idx = 0; i <= lost_pkt_idx; i++) { // Data is a 1000Hz triangle wave - for (size_t j = 0; j < BTM_LC3_CODE_SIZE / 2; j++, sample_idx++) + for (size_t j = 0; j < BTM_LC3_CODE_SIZE / 2; j++, sample_idx++) { data[j] = triangle[sample_idx % 16]; - ASSERT_EQ(bluetooth::audio::sco::swb::encode(data, sizeof(data)), - sizeof(data)); + } + ASSERT_EQ(bluetooth::audio::sco::swb::encode(data, sizeof(data)), sizeof(data)); ASSERT_EQ(bluetooth::audio::sco::swb::dequeue_packet(&encoded), size_t(60)); ASSERT_NE(encoded, nullptr); // Substitute to invalid packet to simulate packet loss. std::copy(encoded, encoded + size_t(60), encoded_vec.data()); ASSERT_EQ(bluetooth::audio::sco::swb::enqueue_packet( - i != lost_pkt_idx ? encoded_vec : std::vector(60, 0), - false), + i != lost_pkt_idx ? encoded_vec : std::vector(60, 0), false), true); - ASSERT_EQ(bluetooth::audio::sco::swb::decode(&decoded), - size_t(BTM_LC3_CODE_SIZE)); + ASSERT_EQ(bluetooth::audio::sco::swb::decode(&decoded), size_t(BTM_LC3_CODE_SIZE)); decode_count++; ASSERT_NE(decoded, nullptr); } - ASSERT_EQ(bluetooth::audio::sco::swb::fill_plc_stats(&num_decoded_frames, - &packet_loss_ratio), + ASSERT_EQ(bluetooth::audio::sco::swb::fill_plc_stats(&num_decoded_frames, &packet_loss_ratio), true); ASSERT_EQ(num_decoded_frames, decode_count); ASSERT_EQ(packet_loss_ratio, (double)1 / decode_count); @@ -807,26 +771,23 @@ TEST_F(ScoHciSwbWithInitCleanTest, SwbPlc) { bluetooth::audio::sco::swb::init(60); for (size_t i = 0, sample_idx = 0; i <= corrupted_pkt_idx; i++) { // Data is a 1000Hz triangle wave - for (size_t j = 0; j < BTM_LC3_CODE_SIZE / 2; j++, sample_idx++) + for (size_t j = 0; j < BTM_LC3_CODE_SIZE / 2; j++, sample_idx++) { data[j] = triangle[sample_idx % 16]; - ASSERT_EQ(bluetooth::audio::sco::swb::encode(data, sizeof(data)), - sizeof(data)); + } + ASSERT_EQ(bluetooth::audio::sco::swb::encode(data, sizeof(data)), sizeof(data)); ASSERT_EQ(bluetooth::audio::sco::swb::dequeue_packet(&encoded), size_t(60)); ASSERT_NE(encoded, nullptr); // Substitute to report packet corrupted to simulate packet loss. std::copy(encoded, encoded + size_t(60), encoded_vec.data()); - ASSERT_EQ(bluetooth::audio::sco::swb::enqueue_packet( - encoded_vec, i == corrupted_pkt_idx), + ASSERT_EQ(bluetooth::audio::sco::swb::enqueue_packet(encoded_vec, i == corrupted_pkt_idx), true); - ASSERT_EQ(bluetooth::audio::sco::swb::decode(&decoded), - size_t(BTM_LC3_CODE_SIZE)); + ASSERT_EQ(bluetooth::audio::sco::swb::decode(&decoded), size_t(BTM_LC3_CODE_SIZE)); decode_count++; ASSERT_NE(decoded, nullptr); } - ASSERT_EQ(bluetooth::audio::sco::swb::fill_plc_stats(&num_decoded_frames, - &packet_loss_ratio), + ASSERT_EQ(bluetooth::audio::sco::swb::fill_plc_stats(&num_decoded_frames, &packet_loss_ratio), true); ASSERT_EQ(num_decoded_frames, decode_count); ASSERT_EQ(packet_loss_ratio, (double)1 / decode_count); diff --git a/system/stack/test/btm/sco_pkt_status_test.cc b/system/stack/test/btm/sco_pkt_status_test.cc index 73853e4c8e3..7e4ad344026 100644 --- a/system/stack/test/btm/sco_pkt_status_test.cc +++ b/system/stack/test/btm/sco_pkt_status_test.cc @@ -23,8 +23,8 @@ namespace { using testing::Test; class ScoPktStatusTest : public Test { - public: - protected: +public: +protected: void SetUp() override {} void TearDown() override {} }; @@ -43,81 +43,85 @@ TEST_F(ScoPktStatusTest, data_to_string) { bool pl[9] = {1, 0, 1, 1, 0, 1, 1, 1, 1}; tBTM_SCO_PKT_STATUS pkt_status; pkt_status.init(); - for (bool b : pl) pkt_status.update(b); + for (bool b : pl) { + pkt_status.update(b); + } ASSERT_EQ(pkt_status.data_to_binary_string(), "101101111"); ASSERT_EQ(pkt_status.data_to_hex_string(), "ed01"); } TEST_F(ScoPktStatusTest, data_full) { bool pl[BTM_PKT_STATUS_LEN * 8] = { - 1, 1, 1, 1, 1, 1, 1, 1, /* ff */ - 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ - 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ - 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ - 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ - 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ - 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ - 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ - 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ - 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ - 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ - 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ - 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ - 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ - 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ - 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ - 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ - 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ - 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ - 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ - 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ - 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ - 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ - 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ - 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ - 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ - 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ - 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ - 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ - 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ - 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ - 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ - 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ - 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ - 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ - 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ - 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ - 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ - 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ - 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ - 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ - 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ - 0, 0, 0, 1, 1, 1, 1, 1, /* f8 */ - 1, 1, 1, 1, 1, 1, 1, 1, /* ff */ - 1, 1, 1, 1, 1, 1, 1, 1, /* ff */ - 1, 1, 1, 1, 1, 1, 1, 1, /* ff */ - 1, 1, 1, 1, 1, 1, 1, 1, /* ff */ - 1, 1, 1, 1, 1, 1, 1, 1, /* ff */ - 1, 1, 1, 1, 1, 1, 1, 1, /* ff */ - 1, 1, 1, 1, 1, 1, 1, 1, /* ff */ - 1, 1, 1, 1, 1, 1, 1, 1, /* ff */ - 1, 1, 1, 1, 1, 1, 1, 1, /* ff */ - 1, 1, 1, 1, 1, 1, 1, 1, /* ff */ - 1, 1, 1, 1, 1, 1, 1, 1, /* ff */ - 1, 1, 1, 1, 1, 1, 1, 1, /* ff */ - 1, 1, 1, 1, 1, 1, 1, 1, /* ff */ - 1, 1, 1, 1, 1, 1, 1, 1, /* ff */ - 1, 1, 1, 1, 1, 1, 1, 1, /* ff */ - 1, 1, 1, 1, 1, 1, 1, 1, /* ff */ - 1, 1, 1, 1, 1, 1, 1, 1, /* ff */ - 1, 1, 1, 1, 1, 1, 1, 1, /* ff */ - 1, 1, 1, 1, 1, 1, 1, 1, /* ff */ - 1, 1, 1, 1, 1, 1, 1, 0, /* 7f */ - 0, 0, 0, 0, 0, 0, 0, 0 /* 00 */ + 1, 1, 1, 1, 1, 1, 1, 1, /* ff */ + 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ + 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ + 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ + 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ + 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ + 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ + 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ + 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ + 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ + 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ + 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ + 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ + 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ + 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ + 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ + 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ + 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ + 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ + 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ + 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ + 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ + 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ + 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ + 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ + 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ + 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ + 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ + 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ + 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ + 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ + 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ + 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ + 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ + 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ + 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ + 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ + 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ + 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ + 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ + 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ + 0, 0, 0, 0, 0, 0, 0, 0, /* 00 */ + 0, 0, 0, 1, 1, 1, 1, 1, /* f8 */ + 1, 1, 1, 1, 1, 1, 1, 1, /* ff */ + 1, 1, 1, 1, 1, 1, 1, 1, /* ff */ + 1, 1, 1, 1, 1, 1, 1, 1, /* ff */ + 1, 1, 1, 1, 1, 1, 1, 1, /* ff */ + 1, 1, 1, 1, 1, 1, 1, 1, /* ff */ + 1, 1, 1, 1, 1, 1, 1, 1, /* ff */ + 1, 1, 1, 1, 1, 1, 1, 1, /* ff */ + 1, 1, 1, 1, 1, 1, 1, 1, /* ff */ + 1, 1, 1, 1, 1, 1, 1, 1, /* ff */ + 1, 1, 1, 1, 1, 1, 1, 1, /* ff */ + 1, 1, 1, 1, 1, 1, 1, 1, /* ff */ + 1, 1, 1, 1, 1, 1, 1, 1, /* ff */ + 1, 1, 1, 1, 1, 1, 1, 1, /* ff */ + 1, 1, 1, 1, 1, 1, 1, 1, /* ff */ + 1, 1, 1, 1, 1, 1, 1, 1, /* ff */ + 1, 1, 1, 1, 1, 1, 1, 1, /* ff */ + 1, 1, 1, 1, 1, 1, 1, 1, /* ff */ + 1, 1, 1, 1, 1, 1, 1, 1, /* ff */ + 1, 1, 1, 1, 1, 1, 1, 1, /* ff */ + 1, 1, 1, 1, 1, 1, 1, 0, /* 7f */ + 0, 0, 0, 0, 0, 0, 0, 0 /* 00 */ }; tBTM_SCO_PKT_STATUS pkt_status; pkt_status.init(); - for (bool b : pl) pkt_status.update(b); + for (bool b : pl) { + pkt_status.update(b); + } ASSERT_EQ(pkt_status.data_to_binary_string(), "111111110000000000000000000000000000000000000000000000000000000000" "000000000000000000000000000000000000000000000000000000000000000000" @@ -134,8 +138,7 @@ TEST_F(ScoPktStatusTest, data_full) { pkt_status.update(true); ASSERT_NE(begin_ts_raw_us, pkt_status.begin_ts_raw_us()); ASSERT_EQ(pkt_status.end_ts_raw_us(), - pkt_status.begin_ts_raw_us() + - BTM_PKT_STATUS_WBS_FRAME_US * BTM_PKT_STATUS_LEN * 8); + pkt_status.begin_ts_raw_us() + BTM_PKT_STATUS_WBS_FRAME_US * BTM_PKT_STATUS_LEN * 8); ASSERT_EQ(pkt_status.data_to_binary_string(), "11111110000000000000000000000000000000000000000000000000000000000" "000000000000000000000000000000000000000000000000000000000000000000" diff --git a/system/stack/test/btm/stack_btm_dev_test.cc b/system/stack/test/btm/stack_btm_dev_test.cc index 97fcef2b4f0..92dbb5db04f 100644 --- a/system/stack/test/btm/stack_btm_dev_test.cc +++ b/system/stack/test/btm/stack_btm_dev_test.cc @@ -24,7 +24,7 @@ #include "test/mock/mock_main_shim_entry.h" class StackBtmDevTest : public BtmWithMocksTest { - protected: +protected: void SetUp() override { BtmWithMocksTest::SetUp(); } void TearDown() override { BtmWithMocksTest::TearDown(); } }; diff --git a/system/stack/test/btm/stack_btm_dm_inq_db_test.cc b/system/stack/test/btm/stack_btm_dm_inq_db_test.cc index 0f19a3f4843..e86e7eaced4 100644 --- a/system/stack/test/btm/stack_btm_dm_inq_db_test.cc +++ b/system/stack/test/btm/stack_btm_dm_inq_db_test.cc @@ -38,8 +38,7 @@ extern void btm_clr_inq_result_flt(void); namespace { constexpr size_t kNumberOfThreads = 8; -constexpr size_t kEntriesPerThread = - static_cast(BTM_INQ_DB_SIZE) / kNumberOfThreads; +constexpr size_t kEntriesPerThread = static_cast(BTM_INQ_DB_SIZE) / kNumberOfThreads; constexpr RawAddress* kClearAllEntries = nullptr; } // namespace @@ -54,12 +53,11 @@ uint16_t btm_get_num_bd_entries(); } // namespace bluetooth class BtmDmInqDbWithMockTest : public testing::Test { - protected: +protected: void SetUp() override { reset_mock_function_count_map(); fake_osi_ = std::make_unique(); - test::mock::osi_thread::thread_new.body = - [](const char* name) -> thread_t* { + test::mock::osi_thread::thread_new.body = [](const char* name) -> thread_t* { thread_t* thread = new thread_t; thread->name_ = std::string(name); thread_start_arg_t start_arg; @@ -69,9 +67,11 @@ class BtmDmInqDbWithMockTest : public testing::Test { start_arg.start_sem.wait(); return thread; }; - test::mock::osi_thread::thread_post.body = - [](thread_t* thread, thread_func func, void* context) -> bool { - if (!thread->is_running()) return false; + test::mock::osi_thread::thread_post.body = [](thread_t* thread, thread_func func, + void* context) -> bool { + if (!thread->is_running()) { + return false; + } { std::lock_guard lock(thread->work_queue_semaphore.mutex_); thread->work_queue.push(std::make_pair(func, context)); @@ -96,7 +96,7 @@ class BtmDmInqDbWithMockTest : public testing::Test { }; class BtmDmInqDbTest : public BtmDmInqDbWithMockTest { - protected: +protected: void SetUp() override { BtmDmInqDbWithMockTest::SetUp(); bluetooth::legacy::testing::btm_clr_inq_db(kClearAllEntries); @@ -111,7 +111,7 @@ class BtmDmInqDbTest : public BtmDmInqDbWithMockTest { }; class BtmDmInqDbThreadedTest : public BtmDmInqDbTest { - protected: +protected: void SetUp() override { BtmDmInqDbTest::SetUp(); } void TearDown() override { BtmDmInqDbTest::TearDown(); } @@ -155,8 +155,7 @@ RawAddress RawAddressMaker(int thread_id, int subid) { void allocate_db_entry(void* context) { entry_data_t* data = static_cast(context); - RawAddress p_bda = - RawAddressMaker(data->thread_id, (int)data->inq_db_queue->size()); + RawAddress p_bda = RawAddressMaker(data->thread_id, (int)data->inq_db_queue->size()); tINQ_DB_ENT* ent = btm_inq_db_new(p_bda); data->inq_db_queue->push_back(ent); } @@ -171,8 +170,7 @@ TEST_F(BtmDmInqDbThreadedTest, btm_inq_db_new) { data_t* data = static_cast(calloc(sizeof(data_t), 1)); data->thread_id = i; data->inq_db_queue = &context.inq_db_queue[i]; - ASSERT_TRUE( - thread_post(threads[i], allocate_db_entry, static_cast(data))); + ASSERT_TRUE(thread_post(threads[i], allocate_db_entry, static_cast(data))); } } @@ -211,12 +209,10 @@ TEST_F(BtmDmInqDbThreadedTest, btm_inq_find_bdaddr) { for (size_t j = 0; j < kEntriesPerThread; j++) { for (size_t i = 0; i < kNumberOfThreads; i++) { - address_data_t* data = - static_cast(calloc(sizeof(address_data_t), 1)); + address_data_t* data = static_cast(calloc(sizeof(address_data_t), 1)); data->thread_id = i; data->offset = (int)j; - ASSERT_TRUE( - thread_post(threads[i], check_address, static_cast(data))); + ASSERT_TRUE(thread_post(threads[i], check_address, static_cast(data))); } } diff --git a/system/stack/test/btm/stack_btm_inq_test.cc b/system/stack/test/btm/stack_btm_inq_test.cc index c5b5a3c8309..6a56ac548e8 100644 --- a/system/stack/test/btm/stack_btm_inq_test.cc +++ b/system/stack/test/btm/stack_btm_inq_test.cc @@ -70,8 +70,7 @@ namespace { const Address kAddress = Address({0x11, 0x22, 0x33, 0x44, 0x55, 0x66}); const Address kAddress2 = Address({0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc}); const RawAddress kRawAddress = RawAddress({0x11, 0x22, 0x33, 0x44, 0x55, 0x66}); -const RawAddress kRawAddress2 = - RawAddress({0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc}); +const RawAddress kRawAddress2 = RawAddress({0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc}); const BD_NAME kBdName = {'A', ' ', 'B', 'd', ' ', 'N', 'a', 'm', 'e', '\0'}; const BD_NAME kEmptyName = ""; @@ -83,7 +82,7 @@ static constexpr uint8_t kNumCommandPackets = 1; } // namespace class BtmInqTest : public BtmWithMocksTest { - protected: +protected: void SetUp() override { BtmWithMocksTest::SetUp(); btm_cb = {}; @@ -93,7 +92,7 @@ class BtmInqTest : public BtmWithMocksTest { }; class BtmInqActiveTest : public BtmInqTest { - protected: +protected: void SetUp() override { BtmInqTest::SetUp(); gBTM_REMOTE_DEV_NAME = {}; @@ -184,33 +183,30 @@ TEST_F(BtmInqActiveTest, btm_process_remote_name__different_address) { } class BtmInquiryCallbacks { - public: +public: virtual ~BtmInquiryCallbacks() = default; - virtual void btm_inq_results_cb(tBTM_INQ_RESULTS*, const uint8_t*, - uint16_t) = 0; + virtual void btm_inq_results_cb(tBTM_INQ_RESULTS*, const uint8_t*, uint16_t) = 0; virtual void btm_inq_cmpl_cb(void*) = 0; }; class MockBtmInquiryCallbacks : public BtmInquiryCallbacks { - public: +public: MOCK_METHOD(void, btm_inq_results_cb, - (tBTM_INQ_RESULTS * p_inq_results, const uint8_t* p_eir, - uint16_t eir_len), + (tBTM_INQ_RESULTS * p_inq_results, const uint8_t* p_eir, uint16_t eir_len), (override)); MOCK_METHOD(void, btm_inq_cmpl_cb, (void*), (override)); }; MockBtmInquiryCallbacks* inquiry_callback_ptr = nullptr; -void btm_inq_results_cb(tBTM_INQ_RESULTS* p_inq_results, const uint8_t* p_eir, - uint16_t eir_len) { +void btm_inq_results_cb(tBTM_INQ_RESULTS* p_inq_results, const uint8_t* p_eir, uint16_t eir_len) { inquiry_callback_ptr->btm_inq_results_cb(p_inq_results, p_eir, eir_len); } void btm_inq_cmpl_cb(void* p1) { inquiry_callback_ptr->btm_inq_cmpl_cb(p1); } class BtmDeviceInquiryTest : public BtmInqTest { - protected: +protected: void SetUp() override { BtmInqTest::SetUp(); main_thread_start_up(); @@ -220,27 +216,23 @@ class BtmDeviceInquiryTest : public BtmInqTest { bluetooth::hci::testing::mock_hci_layer_ = &hci_layer_; // Start Inquiry - EXPECT_EQ(BTM_CMD_STARTED, - BTM_StartInquiry(btm_inq_results_cb, btm_inq_cmpl_cb)); + EXPECT_EQ(BTM_CMD_STARTED, BTM_StartInquiry(btm_inq_results_cb, btm_inq_cmpl_cb)); auto view = hci_layer_.GetCommand(OpCode::INQUIRY); - hci_layer_.IncomingEvent(InquiryStatusBuilder::Create( - bluetooth::hci::ErrorCode::SUCCESS, kNumCommandPackets)); + hci_layer_.IncomingEvent( + InquiryStatusBuilder::Create(bluetooth::hci::ErrorCode::SUCCESS, kNumCommandPackets)); // Send one response to synchronize std::promise first_result_promise; auto first_result = first_result_promise.get_future(); EXPECT_CALL(*inquiry_callback_ptr, btm_inq_results_cb(_, _, _)) - .WillOnce( - [&first_result_promise]() { first_result_promise.set_value(); }) - .RetiresOnSaturation(); + .WillOnce([&first_result_promise]() { first_result_promise.set_value(); }) + .RetiresOnSaturation(); - InquiryResponse one_device(kAddress, - bluetooth::hci::PageScanRepetitionMode::R0, + InquiryResponse one_device(kAddress, bluetooth::hci::PageScanRepetitionMode::R0, bluetooth::hci::ClassOfDevice(), 0x1234); hci_layer_.IncomingEvent(InquiryResultBuilder::Create({one_device})); - EXPECT_EQ(std::future_status::ready, - first_result.wait_for(std::chrono::seconds(1))); + EXPECT_EQ(std::future_status::ready, first_result.wait_for(std::chrono::seconds(1))); } void TearDown() override { @@ -263,14 +255,12 @@ TEST_F(BtmDeviceInquiryTest, bta_dm_disc_device_discovery_single_result) { std::promise one_result_promise; auto one_result = one_result_promise.get_future(); EXPECT_CALL(*inquiry_callback_ptr, btm_inq_results_cb(_, _, _)) - .WillOnce([&one_result_promise]() { one_result_promise.set_value(); }) - .RetiresOnSaturation(); + .WillOnce([&one_result_promise]() { one_result_promise.set_value(); }) + .RetiresOnSaturation(); - InquiryResponse one_device(kAddress2, - bluetooth::hci::PageScanRepetitionMode::R0, + InquiryResponse one_device(kAddress2, bluetooth::hci::PageScanRepetitionMode::R0, bluetooth::hci::ClassOfDevice(), 0x2345); hci_layer_.IncomingEvent(InquiryResultBuilder::Create({one_device})); - EXPECT_EQ(std::future_status::ready, - one_result.wait_for(std::chrono::seconds(1))); + EXPECT_EQ(std::future_status::ready, one_result.wait_for(std::chrono::seconds(1))); } diff --git a/system/stack/test/btm/stack_btm_power_mode_test.cc b/system/stack/test/btm/stack_btm_power_mode_test.cc index 452dbeb824b..0f17b5a4f58 100644 --- a/system/stack/test/btm/stack_btm_power_mode_test.cc +++ b/system/stack/test/btm/stack_btm_power_mode_test.cc @@ -31,8 +31,8 @@ using testing::Return; namespace { const char* test_flags[] = { - "INIT_default_log_level_str=LOG_DEBUG", - nullptr, + "INIT_default_log_level_str=LOG_DEBUG", + nullptr, }; const RawAddress kRawAddress = RawAddress({0x11, 0x22, 0x33, 0x44, 0x55, 0x66}); @@ -51,33 +51,30 @@ struct power_mode_callback { std::deque power_mode_callback_queue; class StackBtmPowerMode : public testing::Test { - protected: +protected: void SetUp() override { ON_CALL(controller_, SupportsSniffMode).WillByDefault(Return(true)); bluetooth::hci::testing::mock_controller_ = &controller_; power_mode_callback_queue.clear(); reset_mock_function_count_map(); bluetooth::common::InitFlags::Load(test_flags); - ASSERT_EQ(BTM_SUCCESS, - BTM_PmRegister(BTM_PM_REG_SET, &pm_id_, - [](const RawAddress& p_bda, tBTM_PM_STATUS status, - uint16_t value, tHCI_STATUS hci_status) { - power_mode_callback_queue.push_back( - power_mode_callback{ - .bd_addr = p_bda, - .status = status, - .value = value, - .hci_status = hci_status, - }); - })); + ASSERT_EQ(BTM_SUCCESS, BTM_PmRegister(BTM_PM_REG_SET, &pm_id_, + [](const RawAddress& p_bda, tBTM_PM_STATUS status, + uint16_t value, tHCI_STATUS hci_status) { + power_mode_callback_queue.push_back(power_mode_callback{ + .bd_addr = p_bda, + .status = status, + .value = value, + .hci_status = hci_status, + }); + })); } void TearDown() override { ASSERT_EQ(BTM_SUCCESS, - BTM_PmRegister( - BTM_PM_DEREG, &pm_id_, - [](const RawAddress& /* p_bda */, tBTM_PM_STATUS /* status */, - uint16_t /* value */, tHCI_STATUS /* hci_status */) {})); + BTM_PmRegister(BTM_PM_DEREG, &pm_id_, + [](const RawAddress& /* p_bda */, tBTM_PM_STATUS /* status */, + uint16_t /* value */, tHCI_STATUS /* hci_status */) {})); bluetooth::hci::testing::mock_controller_ = nullptr; } @@ -86,7 +83,7 @@ class StackBtmPowerMode : public testing::Test { }; class StackBtmPowerModeConnected : public StackBtmPowerMode { - protected: +protected: void SetUp() override { StackBtmPowerMode::SetUp(); BTM_PM_OnConnected(kHciHandle, kRawAddress); @@ -110,10 +107,9 @@ TEST_F(StackBtmPowerModeConnected, BTM_SetPowerMode__AlreadyActive) { TEST_F(StackBtmPowerModeConnected, BTM_SetPowerMode__ActiveToSniff) { tBTM_PM_PWR_MD mode = { - .mode = BTM_PM_MD_SNIFF, + .mode = BTM_PM_MD_SNIFF, }; - ASSERT_EQ("BTM_CMD_STARTED", - btm_status_text(BTM_SetPowerMode(pm_id_, kRawAddress, &mode))); + ASSERT_EQ("BTM_CMD_STARTED", btm_status_text(BTM_SetPowerMode(pm_id_, kRawAddress, &mode))); ASSERT_EQ(1, get_func_call_count("btsnd_hcic_sniff_mode")); // Respond with successful command status for mode command @@ -162,10 +158,9 @@ TEST_F(StackBtmPowerModeConnected, BTM_SetPowerMode__ActiveToSniff) { TEST_F(StackBtmPowerModeConnected, BTM_SetPowerMode__ActiveToSniffTwice) { tBTM_PM_PWR_MD mode = { - .mode = BTM_PM_MD_SNIFF, + .mode = BTM_PM_MD_SNIFF, }; - ASSERT_EQ("BTM_CMD_STARTED", - btm_status_text(BTM_SetPowerMode(pm_id_, kRawAddress, &mode))); + ASSERT_EQ("BTM_CMD_STARTED", btm_status_text(BTM_SetPowerMode(pm_id_, kRawAddress, &mode))); ASSERT_EQ(1, get_func_call_count("btsnd_hcic_sniff_mode")); // Respond with successful command status for mode command @@ -191,8 +186,7 @@ TEST_F(StackBtmPowerModeConnected, BTM_SetPowerMode__ActiveToSniffTwice) { } // Send a second active to sniff command - ASSERT_EQ("BTM_CMD_STORED", - btm_status_text(BTM_SetPowerMode(pm_id_, kRawAddress, &mode))); + ASSERT_EQ("BTM_CMD_STORED", btm_status_text(BTM_SetPowerMode(pm_id_, kRawAddress, &mode))); // No command should be issued ASSERT_EQ(1, get_func_call_count("btsnd_hcic_sniff_mode")); @@ -201,8 +195,7 @@ TEST_F(StackBtmPowerModeConnected, BTM_SetPowerMode__ActiveToSniffTwice) { tBTM_PM_MODE current_power_mode; ASSERT_TRUE(BTM_ReadPowerMode(kRawAddress, ¤t_power_mode)); // NOTE: The mixed enum values - ASSERT_EQ( - static_cast(BTM_PM_STS_PENDING | BTM_PM_STORED_MASK), - current_power_mode); + ASSERT_EQ(static_cast(BTM_PM_STS_PENDING | BTM_PM_STORED_MASK), + current_power_mode); } } diff --git a/system/stack/test/btm/stack_btm_regression_tests.cc b/system/stack/test/btm/stack_btm_regression_tests.cc index ec111e941b6..d6e28f98330 100644 --- a/system/stack/test/btm/stack_btm_regression_tests.cc +++ b/system/stack/test/btm/stack_btm_regression_tests.cc @@ -27,21 +27,19 @@ namespace { class StackBTMRegressionTests : public ::testing::Test { - protected: +protected: void SetUp() override {} void TearDown() override {} }; // regression test for b/260078907 -TEST_F(StackBTMRegressionTests, - OOB_in_btm_ble_add_resolving_list_entry_complete) { +TEST_F(StackBTMRegressionTests, OOB_in_btm_ble_add_resolving_list_entry_complete) { BT_HDR event{}; btm_ble_add_resolving_list_entry_complete(event.data, 0); } // regression test for b/255304475 -TEST_F(StackBTMRegressionTests, - OOB_in_btm_ble_clear_resolving_list_complete) { +TEST_F(StackBTMRegressionTests, OOB_in_btm_ble_clear_resolving_list_complete) { BT_HDR event{}; btm_ble_clear_resolving_list_complete(event.data, 0); } diff --git a/system/stack/test/btm/stack_btm_sec_test.cc b/system/stack/test/btm/stack_btm_sec_test.cc index d0bb18f8611..995c6bad98c 100644 --- a/system/stack/test/btm/stack_btm_sec_test.cc +++ b/system/stack/test/btm/stack_btm_sec_test.cc @@ -59,26 +59,24 @@ void wipe_secrets_and_remove(tBTM_SEC_DEV_REC* p_dev_rec); using bluetooth::testing::legacy::wipe_secrets_and_remove; -constexpr size_t kBtmSecMaxDeviceRecords = - static_cast(BTM_SEC_MAX_DEVICE_RECORDS + 1); +constexpr size_t kBtmSecMaxDeviceRecords = static_cast(BTM_SEC_MAX_DEVICE_RECORDS + 1); class StackBtmSecTest : public BtmWithMocksTest { - public: - protected: +public: +protected: void SetUp() override { BtmWithMocksTest::SetUp(); } void TearDown() override { BtmWithMocksTest::TearDown(); } }; class StackBtmSecWithQueuesTest : public StackBtmSecTest { - public: - protected: +public: +protected: void SetUp() override { StackBtmSecTest::SetUp(); - up_thread_ = new bluetooth::os::Thread( - "up_thread", bluetooth::os::Thread::Priority::NORMAL); + up_thread_ = new bluetooth::os::Thread("up_thread", bluetooth::os::Thread::Priority::NORMAL); up_handler_ = new bluetooth::os::Handler(up_thread_); - down_thread_ = new bluetooth::os::Thread( - "down_thread", bluetooth::os::Thread::Priority::NORMAL); + down_thread_ = + new bluetooth::os::Thread("down_thread", bluetooth::os::Thread::Priority::NORMAL); down_handler_ = new bluetooth::os::Handler(down_thread_); bluetooth::hci::testing::mock_hci_layer_ = &mock_hci_; bluetooth::hci::testing::mock_gd_shim_handler_ = up_handler_; @@ -92,9 +90,7 @@ class StackBtmSecWithQueuesTest : public StackBtmSecTest { delete down_thread_; StackBtmSecTest::TearDown(); } - bluetooth::common::BidiQueue - sco_queue_{10}; + bluetooth::common::BidiQueue sco_queue_{10}; bluetooth::hci::testing::MockHciLayer mock_hci_; bluetooth::os::Thread* up_thread_; bluetooth::os::Handler* up_handler_; @@ -103,8 +99,8 @@ class StackBtmSecWithQueuesTest : public StackBtmSecTest { }; class StackBtmSecWithInitFreeTest : public StackBtmSecWithQueuesTest { - public: - protected: +public: +protected: void SetUp() override { StackBtmSecWithQueuesTest::SetUp(); BTM_Sec_Init(); @@ -129,8 +125,7 @@ TEST_F(StackBtmSecWithInitFreeTest, btm_sec_encrypt_change) { ASSERT_NE(0UL, collision_start_time); ::btm_sec_cb.collision_start_time = 0UL; - btm_sec_encrypt_change(classic_handle, HCI_ERR_DIFF_TRANSACTION_COLLISION, - 0x01); + btm_sec_encrypt_change(classic_handle, HCI_ERR_DIFF_TRANSACTION_COLLISION, 0x01); collision_start_time = ::btm_sec_cb.collision_start_time; ASSERT_NE(0UL, collision_start_time); @@ -154,14 +149,12 @@ TEST_F(StackBtmSecWithInitFreeTest, btm_sec_encrypt_change) { // With classic device encryption disable btm_sec_encrypt_change(classic_handle, HCI_SUCCESS, 0x00); - ASSERT_EQ(BTM_SEC_IN_USE | BTM_SEC_AUTHENTICATED, - device_record->sec_rec.sec_flags); + ASSERT_EQ(BTM_SEC_IN_USE | BTM_SEC_AUTHENTICATED, device_record->sec_rec.sec_flags); device_record->sec_rec.sec_flags = BTM_SEC_IN_USE; // With le device encryption enable btm_sec_encrypt_change(ble_handle, HCI_SUCCESS, 0x01); - ASSERT_EQ(BTM_SEC_IN_USE | BTM_SEC_LE_ENCRYPTED, - device_record->sec_rec.sec_flags); + ASSERT_EQ(BTM_SEC_IN_USE | BTM_SEC_LE_ENCRYPTED, device_record->sec_rec.sec_flags); // With le device encryption disable btm_sec_encrypt_change(ble_handle, HCI_SUCCESS, 0x00); @@ -178,8 +171,7 @@ TEST_F(StackBtmSecWithInitFreeTest, BTM_SetEncryption) { tBTM_BLE_SEC_ACT sec_act{BTM_BLE_SEC_ENCRYPT}; // No device - ASSERT_EQ(BTM_WRONG_MODE, BTM_SetEncryption(bd_addr, transport, p_callback, - nullptr, sec_act)); + ASSERT_EQ(BTM_WRONG_MODE, BTM_SetEncryption(bd_addr, transport, p_callback, nullptr, sec_act)); // With device tBTM_SEC_DEV_REC* device_record = btm_sec_allocate_dev_rec(); @@ -187,21 +179,16 @@ TEST_F(StackBtmSecWithInitFreeTest, BTM_SetEncryption) { device_record->bd_addr = bd_addr; device_record->hci_handle = 0x1234; - ASSERT_EQ(BTM_WRONG_MODE, BTM_SetEncryption(bd_addr, transport, p_callback, - nullptr, sec_act)); + ASSERT_EQ(BTM_WRONG_MODE, BTM_SetEncryption(bd_addr, transport, p_callback, nullptr, sec_act)); wipe_secrets_and_remove(device_record); } TEST_F(StackBtmSecTest, btm_ble_sec_req_act_text) { - ASSERT_EQ("BTM_BLE_SEC_REQ_ACT_NONE", - btm_ble_sec_req_act_text(BTM_BLE_SEC_REQ_ACT_NONE)); - ASSERT_EQ("BTM_BLE_SEC_REQ_ACT_ENCRYPT", - btm_ble_sec_req_act_text(BTM_BLE_SEC_REQ_ACT_ENCRYPT)); - ASSERT_EQ("BTM_BLE_SEC_REQ_ACT_PAIR", - btm_ble_sec_req_act_text(BTM_BLE_SEC_REQ_ACT_PAIR)); - ASSERT_EQ("BTM_BLE_SEC_REQ_ACT_DISCARD", - btm_ble_sec_req_act_text(BTM_BLE_SEC_REQ_ACT_DISCARD)); + ASSERT_EQ("BTM_BLE_SEC_REQ_ACT_NONE", btm_ble_sec_req_act_text(BTM_BLE_SEC_REQ_ACT_NONE)); + ASSERT_EQ("BTM_BLE_SEC_REQ_ACT_ENCRYPT", btm_ble_sec_req_act_text(BTM_BLE_SEC_REQ_ACT_ENCRYPT)); + ASSERT_EQ("BTM_BLE_SEC_REQ_ACT_PAIR", btm_ble_sec_req_act_text(BTM_BLE_SEC_REQ_ACT_PAIR)); + ASSERT_EQ("BTM_BLE_SEC_REQ_ACT_DISCARD", btm_ble_sec_req_act_text(BTM_BLE_SEC_REQ_ACT_DISCARD)); } TEST_F(StackBtmSecWithInitFreeTest, btm_sec_allocate_dev_rec__all) { @@ -229,39 +216,35 @@ TEST_F(StackBtmSecWithInitFreeTest, btm_sec_allocate_dev_rec__all) { TEST_F(StackBtmSecTest, btm_oob_data_text) { std::vector> datas = { - std::make_pair(BTM_OOB_NONE, "BTM_OOB_NONE"), - std::make_pair(BTM_OOB_PRESENT_192, "BTM_OOB_PRESENT_192"), - std::make_pair(BTM_OOB_PRESENT_256, "BTM_OOB_PRESENT_256"), - std::make_pair(BTM_OOB_PRESENT_192_AND_256, - "BTM_OOB_PRESENT_192_AND_256"), - std::make_pair(BTM_OOB_UNKNOWN, "BTM_OOB_UNKNOWN"), + std::make_pair(BTM_OOB_NONE, "BTM_OOB_NONE"), + std::make_pair(BTM_OOB_PRESENT_192, "BTM_OOB_PRESENT_192"), + std::make_pair(BTM_OOB_PRESENT_256, "BTM_OOB_PRESENT_256"), + std::make_pair(BTM_OOB_PRESENT_192_AND_256, "BTM_OOB_PRESENT_192_AND_256"), + std::make_pair(BTM_OOB_UNKNOWN, "BTM_OOB_UNKNOWN"), }; for (const auto& data : datas) { ASSERT_STREQ(data.second.c_str(), btm_oob_data_text(data.first).c_str()); } - auto unknown = base::StringPrintf("UNKNOWN[%hhu]", - std::numeric_limits::max()); - ASSERT_STREQ(unknown.c_str(), - btm_oob_data_text(static_cast( - std::numeric_limits::max())) - .c_str()); + auto unknown = base::StringPrintf("UNKNOWN[%hhu]", std::numeric_limits::max()); + ASSERT_STREQ( + unknown.c_str(), + btm_oob_data_text(static_cast(std::numeric_limits::max())) + .c_str()); } TEST_F(StackBtmSecTest, bond_type_text) { std::vector> datas = { - std::make_pair(BOND_TYPE_UNKNOWN, "BOND_TYPE_UNKNOWN"), - std::make_pair(BOND_TYPE_PERSISTENT, "BOND_TYPE_PERSISTENT"), - std::make_pair(BOND_TYPE_TEMPORARY, "BOND_TYPE_TEMPORARY"), + std::make_pair(BOND_TYPE_UNKNOWN, "BOND_TYPE_UNKNOWN"), + std::make_pair(BOND_TYPE_PERSISTENT, "BOND_TYPE_PERSISTENT"), + std::make_pair(BOND_TYPE_TEMPORARY, "BOND_TYPE_TEMPORARY"), }; for (const auto& data : datas) { ASSERT_STREQ(data.second.c_str(), bond_type_text(data.first).c_str()); } - auto unknown = base::StringPrintf("UNKNOWN[%hhu]", - std::numeric_limits::max()); + auto unknown = base::StringPrintf("UNKNOWN[%hhu]", std::numeric_limits::max()); ASSERT_STREQ(unknown.c_str(), - bond_type_text(static_cast( - std::numeric_limits::max())) - .c_str()); + bond_type_text(static_cast(std::numeric_limits::max())) + .c_str()); } TEST_F(StackBtmSecWithInitFreeTest, wipe_secrets_and_remove) { @@ -283,8 +266,7 @@ TEST_F(StackBtmSecWithInitFreeTest, wipe_secrets_and_remove) { } TEST_F(StackBtmSecWithInitFreeTest, btm_sec_rmt_name_request_complete) { - btm_cb.history_ = std::make_shared( - kBtmLogHistoryBufferSize); + btm_cb.history_ = std::make_shared(kBtmLogHistoryBufferSize); btm_sec_rmt_name_request_complete(&kRawAddress, kBdName, HCI_SUCCESS); btm_sec_rmt_name_request_complete(nullptr, nullptr, HCI_SUCCESS); @@ -296,16 +278,13 @@ TEST_F(StackBtmSecWithInitFreeTest, btm_sec_rmt_name_request_complete) { btm_sec_rmt_name_request_complete(nullptr, kBdName, HCI_ERR_HW_FAILURE); btm_sec_rmt_name_request_complete(&kRawAddress, nullptr, HCI_ERR_HW_FAILURE); - std::vector> history = - btm_cb.history_->Pull(); + std::vector> history = btm_cb.history_->Pull(); for (auto& record : history) { time_t then = record.timestamp / 1000; struct tm tm; localtime_r(&then, &tm); auto s2 = common::StringFormatTime(kTimeFormat, tm); - log::debug("{}.{} {}", s2, - static_cast(record.timestamp % 1000), - record.entry); + log::debug("{}.{} {}", s2, static_cast(record.timestamp % 1000), record.entry); } ASSERT_EQ(8U, history.size()); } diff --git a/system/stack/test/btm/stack_btm_test.cc b/system/stack/test/btm/stack_btm_test.cc index f59fa628950..94d78ea8056 100644 --- a/system/stack/test/btm/stack_btm_test.cc +++ b/system/stack/test/btm/stack_btm_test.cc @@ -47,8 +47,7 @@ extern tBTM_CB btm_cb; tL2C_CB l2cb; const std::string kSmpOptions("mock smp options"); -const std::string kBroadcastAudioConfigOptions( - "mock broadcast audio config options"); +const std::string kBroadcastAudioConfigOptions("mock broadcast audio config options"); namespace { @@ -56,8 +55,8 @@ using testing::Return; using testing::Test; class StackBtmTest : public BtmWithMocksTest { - public: - protected: +public: +protected: void SetUp() override { BtmWithMocksTest::SetUp(); bluetooth::hci::testing::mock_controller_ = &controller_; @@ -70,15 +69,14 @@ class StackBtmTest : public BtmWithMocksTest { }; class StackBtmWithQueuesTest : public StackBtmTest { - public: - protected: +public: +protected: void SetUp() override { StackBtmTest::SetUp(); - up_thread_ = new bluetooth::os::Thread( - "up_thread", bluetooth::os::Thread::Priority::NORMAL); + up_thread_ = new bluetooth::os::Thread("up_thread", bluetooth::os::Thread::Priority::NORMAL); up_handler_ = new bluetooth::os::Handler(up_thread_); - down_thread_ = new bluetooth::os::Thread( - "down_thread", bluetooth::os::Thread::Priority::NORMAL); + down_thread_ = + new bluetooth::os::Thread("down_thread", bluetooth::os::Thread::Priority::NORMAL); down_handler_ = new bluetooth::os::Handler(down_thread_); bluetooth::hci::testing::mock_hci_layer_ = &mock_hci_; bluetooth::hci::testing::mock_gd_shim_handler_ = up_handler_; @@ -93,9 +91,7 @@ class StackBtmWithQueuesTest : public StackBtmTest { delete down_thread_; StackBtmTest::TearDown(); } - bluetooth::common::BidiQueue - sco_queue_{10}; + bluetooth::common::BidiQueue sco_queue_{10}; bluetooth::hci::testing::MockHciLayer mock_hci_; bluetooth::legacy::hci::testing::MockInterface legacy_hci_mock_; bluetooth::os::Thread* up_thread_; @@ -105,12 +101,11 @@ class StackBtmWithQueuesTest : public StackBtmTest { }; class StackBtmWithInitFreeTest : public StackBtmWithQueuesTest { - public: - protected: +public: +protected: void SetUp() override { StackBtmWithQueuesTest::SetUp(); - EXPECT_CALL(mock_hci_, GetScoQueueEnd()) - .WillOnce(Return(sco_queue_.GetUpEnd())); + EXPECT_CALL(mock_hci_, GetScoQueueEnd()).WillOnce(Return(sco_queue_.GetUpEnd())); btm_cb.Init(); btm_sec_cb.Init(BTM_SEC_MODE_SC); @@ -123,8 +118,7 @@ class StackBtmWithInitFreeTest : public StackBtmWithQueuesTest { }; TEST_F(StackBtmWithQueuesTest, GlobalLifecycle) { - EXPECT_CALL(mock_hci_, GetScoQueueEnd()) - .WillOnce(Return(sco_queue_.GetUpEnd())); + EXPECT_CALL(mock_hci_, GetScoQueueEnd()).WillOnce(Return(sco_queue_.GetUpEnd())); get_btm_client_interface().lifecycle.btm_init(); get_btm_client_interface().lifecycle.btm_free(); } @@ -135,15 +129,13 @@ TEST_F(StackBtmTest, DynamicLifecycle) { } TEST_F(StackBtmWithQueuesTest, InitFree) { - EXPECT_CALL(mock_hci_, GetScoQueueEnd()) - .WillOnce(Return(sco_queue_.GetUpEnd())); + EXPECT_CALL(mock_hci_, GetScoQueueEnd()).WillOnce(Return(sco_queue_.GetUpEnd())); btm_cb.Init(); btm_cb.Free(); } TEST_F(StackBtmWithQueuesTest, tSCO_CB) { - EXPECT_CALL(mock_hci_, GetScoQueueEnd()) - .WillOnce(Return(sco_queue_.GetUpEnd())); + EXPECT_CALL(mock_hci_, GetScoQueueEnd()).WillOnce(Return(sco_queue_.GetUpEnd())); bluetooth::common::InitFlags::SetAllForTesting(); tSCO_CB* p_sco = &btm_cb.sco_cb; p_sco->Init(); @@ -151,8 +143,7 @@ TEST_F(StackBtmWithQueuesTest, tSCO_CB) { } TEST_F(StackBtmWithQueuesTest, InformClientOnConnectionSuccess) { - EXPECT_CALL(mock_hci_, GetScoQueueEnd()) - .WillOnce(Return(sco_queue_.GetUpEnd())); + EXPECT_CALL(mock_hci_, GetScoQueueEnd()).WillOnce(Return(sco_queue_.GetUpEnd())); get_btm_client_interface().lifecycle.btm_init(); RawAddress bda({0x11, 0x22, 0x33, 0x44, 0x55, 0x66}); @@ -164,8 +155,7 @@ TEST_F(StackBtmWithQueuesTest, InformClientOnConnectionSuccess) { } TEST_F(StackBtmWithQueuesTest, NoInformClientOnConnectionFail) { - EXPECT_CALL(mock_hci_, GetScoQueueEnd()) - .WillOnce(Return(sco_queue_.GetUpEnd())); + EXPECT_CALL(mock_hci_, GetScoQueueEnd()).WillOnce(Return(sco_queue_.GetUpEnd())); get_btm_client_interface().lifecycle.btm_init(); RawAddress bda({0x11, 0x22, 0x33, 0x44, 0x55, 0x66}); @@ -177,8 +167,7 @@ TEST_F(StackBtmWithQueuesTest, NoInformClientOnConnectionFail) { } TEST_F(StackBtmWithQueuesTest, default_packet_type) { - EXPECT_CALL(mock_hci_, GetScoQueueEnd()) - .WillOnce(Return(sco_queue_.GetUpEnd())); + EXPECT_CALL(mock_hci_, GetScoQueueEnd()).WillOnce(Return(sco_queue_.GetUpEnd())); get_btm_client_interface().lifecycle.btm_init(); btm_cb.acl_cb_.SetDefaultPacketTypeMask(0x4321); @@ -188,8 +177,7 @@ TEST_F(StackBtmWithQueuesTest, default_packet_type) { } TEST_F(StackBtmWithQueuesTest, change_packet_type) { - EXPECT_CALL(mock_hci_, GetScoQueueEnd()) - .WillOnce(Return(sco_queue_.GetUpEnd())); + EXPECT_CALL(mock_hci_, GetScoQueueEnd()).WillOnce(Return(sco_queue_.GetUpEnd())); get_btm_client_interface().lifecycle.btm_init(); uint16_t handle = 0x123; @@ -204,11 +192,11 @@ TEST_F(StackBtmWithQueuesTest, change_packet_type) { uint64_t features = 0xffffffffffffffff; acl_process_supported_features(0x123, features); - EXPECT_CALL(legacy_hci_mock_, ChangeConnectionPacketType( - handle, 0x4400 | HCI_PKT_TYPES_MASK_DM1)); - EXPECT_CALL(legacy_hci_mock_, ChangeConnectionPacketType( - handle, (0xcc00 | HCI_PKT_TYPES_MASK_DM1 | - HCI_PKT_TYPES_MASK_DH1))); + EXPECT_CALL(legacy_hci_mock_, + ChangeConnectionPacketType(handle, 0x4400 | HCI_PKT_TYPES_MASK_DM1)); + EXPECT_CALL(legacy_hci_mock_, + ChangeConnectionPacketType( + handle, (0xcc00 | HCI_PKT_TYPES_MASK_DM1 | HCI_PKT_TYPES_MASK_DH1))); btm_set_packet_types_from_address(bda, 0x55aa); btm_set_packet_types_from_address(bda, 0xffff); @@ -222,8 +210,7 @@ TEST(BtmTest, BTM_EIR_MAX_SERVICES) { ASSERT_EQ(46, BTM_EIR_MAX_SERVICES); } } // namespace -void btm_sec_rmt_name_request_complete(const RawAddress* p_bd_addr, - const uint8_t* p_bd_name, +void btm_sec_rmt_name_request_complete(const RawAddress* p_bd_addr, const uint8_t* p_bd_name, tHCI_STATUS status); struct { @@ -236,11 +223,11 @@ TEST_F(StackBtmWithInitFreeTest, btm_sec_rmt_name_request_complete) { bluetooth::common::InitFlags::SetAllForTesting(); ASSERT_TRUE(BTM_SecAddRmtNameNotifyCallback( - [](const RawAddress& bd_addr, DEV_CLASS dc, BD_NAME bd_name) { - btm_test.bd_addr = bd_addr; - btm_test.dc = dc; - memcpy(btm_test.bd_name, bd_name, BD_NAME_LEN); - })); + [](const RawAddress& bd_addr, DEV_CLASS dc, BD_NAME bd_name) { + btm_test.bd_addr = bd_addr; + btm_test.dc = dc; + memcpy(btm_test.bd_name, bd_name, BD_NAME_LEN); + })); RawAddress bd_addr = RawAddress({0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6}); const uint8_t* p_bd_name = (const uint8_t*)"MyTestName"; @@ -263,15 +250,15 @@ TEST_F(StackBtmWithInitFreeTest, btm_sec_rmt_name_request_complete) { TEST_F(StackBtmTest, sco_state_text) { std::vector> states = { - std::make_pair(SCO_ST_UNUSED, "SCO_ST_UNUSED"), - std::make_pair(SCO_ST_LISTENING, "SCO_ST_LISTENING"), - std::make_pair(SCO_ST_W4_CONN_RSP, "SCO_ST_W4_CONN_RSP"), - std::make_pair(SCO_ST_CONNECTING, "SCO_ST_CONNECTING"), - std::make_pair(SCO_ST_CONNECTED, "SCO_ST_CONNECTED"), - std::make_pair(SCO_ST_DISCONNECTING, "SCO_ST_DISCONNECTING"), - std::make_pair(SCO_ST_PEND_UNPARK, "SCO_ST_PEND_UNPARK"), - std::make_pair(SCO_ST_PEND_ROLECHANGE, "SCO_ST_PEND_ROLECHANGE"), - std::make_pair(SCO_ST_PEND_MODECHANGE, "SCO_ST_PEND_MODECHANGE"), + std::make_pair(SCO_ST_UNUSED, "SCO_ST_UNUSED"), + std::make_pair(SCO_ST_LISTENING, "SCO_ST_LISTENING"), + std::make_pair(SCO_ST_W4_CONN_RSP, "SCO_ST_W4_CONN_RSP"), + std::make_pair(SCO_ST_CONNECTING, "SCO_ST_CONNECTING"), + std::make_pair(SCO_ST_CONNECTED, "SCO_ST_CONNECTED"), + std::make_pair(SCO_ST_DISCONNECTING, "SCO_ST_DISCONNECTING"), + std::make_pair(SCO_ST_PEND_UNPARK, "SCO_ST_PEND_UNPARK"), + std::make_pair(SCO_ST_PEND_ROLECHANGE, "SCO_ST_PEND_ROLECHANGE"), + std::make_pair(SCO_ST_PEND_MODECHANGE, "SCO_ST_PEND_MODECHANGE"), }; for (const auto& state : states) { ASSERT_STREQ(state.second.c_str(), sco_state_text(state.first).c_str()); @@ -279,28 +266,28 @@ TEST_F(StackBtmTest, sco_state_text) { std::ostringstream oss; oss << "unknown_sco_state: " << std::numeric_limits::max(); ASSERT_STREQ(oss.str().c_str(), - sco_state_text(static_cast( - std::numeric_limits::max())) - .c_str()); + sco_state_text(static_cast(std::numeric_limits::max())) + .c_str()); } bool is_disconnect_reason_valid(const tHCI_REASON& reason); TEST_F(StackBtmWithInitFreeTest, is_disconnect_reason_valid) { std::set valid_reason_set{ - HCI_ERR_AUTH_FAILURE, - HCI_ERR_PEER_USER, - HCI_ERR_REMOTE_LOW_RESOURCE, - HCI_ERR_REMOTE_POWER_OFF, - HCI_ERR_UNSUPPORTED_REM_FEATURE, - HCI_ERR_PAIRING_WITH_UNIT_KEY_NOT_SUPPORTED, - HCI_ERR_UNACCEPT_CONN_INTERVAL, + HCI_ERR_AUTH_FAILURE, + HCI_ERR_PEER_USER, + HCI_ERR_REMOTE_LOW_RESOURCE, + HCI_ERR_REMOTE_POWER_OFF, + HCI_ERR_UNSUPPORTED_REM_FEATURE, + HCI_ERR_PAIRING_WITH_UNIT_KEY_NOT_SUPPORTED, + HCI_ERR_UNACCEPT_CONN_INTERVAL, }; for (unsigned u = 0; u < 256; u++) { const tHCI_REASON reason = static_cast(u); - if (valid_reason_set.count(reason)) + if (valid_reason_set.count(reason)) { ASSERT_TRUE(is_disconnect_reason_valid(reason)); - else + } else { ASSERT_FALSE(is_disconnect_reason_valid(reason)); + } } } diff --git a/system/stack/test/btm_iso_test.cc b/system/stack/test/btm_iso_test.cc index b50f7223822..238469049c2 100644 --- a/system/stack/test/btm_iso_test.cc +++ b/system/stack/test/btm_iso_test.cc @@ -46,40 +46,32 @@ using testing::Test; // for function pointer testing purpose bool IsIsoActive = false; -tBTM_SEC_DEV_REC* btm_find_dev_by_handle(uint16_t /* handle */) { - return nullptr; -} -void BTM_LogHistory(const std::string& /* tag */, - const RawAddress& /* bd_addr */, - const std::string& /* msg */, - const std::string& /* extra */) {} +tBTM_SEC_DEV_REC* btm_find_dev_by_handle(uint16_t /* handle */) { return nullptr; } +void BTM_LogHistory(const std::string& /* tag */, const RawAddress& /* bd_addr */, + const std::string& /* msg */, const std::string& /* extra */) {} namespace bluetooth::shim { class IsoInterface { - public: +public: virtual void HciSend(BT_HDR* packet) = 0; virtual ~IsoInterface() = default; }; class MockIsoInterface : public IsoInterface { - public: +public: MOCK_METHOD((void), HciSend, (BT_HDR * p_msg), (override)); }; static MockIsoInterface* iso_interface = nullptr; -static void SetMockIsoInterface(MockIsoInterface* interface) { - iso_interface = interface; -} +static void SetMockIsoInterface(MockIsoInterface* interface) { iso_interface = interface; } -static void set_data_cb( - base::Callback /* send_data_cb */) { +static void set_data_cb(base::Callback /* send_data_cb */) { FAIL() << __func__ << " should never be called"; } static void transmit_command(const BT_HDR* /* command */, command_complete_cb /* complete_callback */, - command_status_cb /* status_cb */, - void* /* context */) { + command_status_cb /* status_cb */, void* /* context */) { FAIL() << __func__ << " should never be called"; } @@ -96,18 +88,16 @@ static hci_t interface = {.set_data_cb = set_data_cb, namespace { class MockCigCallbacks : public bluetooth::hci::iso_manager::CigCallbacks { - public: +public: MockCigCallbacks() = default; MockCigCallbacks(const MockCigCallbacks&) = delete; MockCigCallbacks& operator=(const MockCigCallbacks&) = delete; ~MockCigCallbacks() override = default; - MOCK_METHOD((void), OnSetupIsoDataPath, - (uint8_t status, uint16_t conn_handle, uint8_t cig_id), + MOCK_METHOD((void), OnSetupIsoDataPath, (uint8_t status, uint16_t conn_handle, uint8_t cig_id), (override)); - MOCK_METHOD((void), OnRemoveIsoDataPath, - (uint8_t status, uint16_t conn_handle, uint8_t cig_id), + MOCK_METHOD((void), OnRemoveIsoDataPath, (uint8_t status, uint16_t conn_handle, uint8_t cig_id), (override)); MOCK_METHOD((void), OnIsoLinkQualityRead, (uint8_t conn_handle, uint8_t cig_id, uint32_t txUnackedPackets, @@ -121,18 +111,16 @@ class MockCigCallbacks : public bluetooth::hci::iso_manager::CigCallbacks { }; class MockBigCallbacks : public bluetooth::hci::iso_manager::BigCallbacks { - public: +public: MockBigCallbacks() = default; MockBigCallbacks(const MockBigCallbacks&) = delete; MockBigCallbacks& operator=(const MockBigCallbacks&) = delete; ~MockBigCallbacks() override = default; - MOCK_METHOD((void), OnSetupIsoDataPath, - (uint8_t status, uint16_t conn_handle, uint8_t big_id), + MOCK_METHOD((void), OnSetupIsoDataPath, (uint8_t status, uint16_t conn_handle, uint8_t big_id), (override)); - MOCK_METHOD((void), OnRemoveIsoDataPath, - (uint8_t status, uint16_t conn_handle, uint8_t big_id), + MOCK_METHOD((void), OnRemoveIsoDataPath, (uint8_t status, uint16_t conn_handle, uint8_t big_id), (override)); MOCK_METHOD((void), OnBigEvent, (uint8_t event, void* data), (override)); @@ -140,12 +128,11 @@ class MockBigCallbacks : public bluetooth::hci::iso_manager::BigCallbacks { } // namespace class IsoManagerTest : public Test { - protected: +protected: void SetUp() override { bluetooth::shim::SetMockIsoInterface(&iso_interface_); hcic::SetMockHcicInterface(&hcic_interface_); - bluetooth::shim::testing::hci_layer_set_interface( - &bluetooth::shim::interface); + bluetooth::shim::testing::hci_layer_set_interface(&bluetooth::shim::interface); bluetooth::hci::testing::mock_controller_ = &controller_; big_callbacks_.reset(new MockBigCallbacks()); @@ -154,8 +141,7 @@ class IsoManagerTest : public Test { iso_sizes_.total_num_le_packets_ = 6; iso_sizes_.le_data_packet_length_ = 1024; - ON_CALL(controller_, GetControllerIsoBufferSize()) - .WillByDefault(Return(iso_sizes_)); + ON_CALL(controller_, GetControllerIsoBufferSize()).WillByDefault(Return(iso_sizes_)); InitIsoManager(); } @@ -182,36 +168,32 @@ class IsoManagerTest : public Test { // Default mock SetCigParams action volatile_test_cig_create_cmpl_evt_ = kDefaultCigParamsEvt; ON_CALL(hcic_interface_, SetCigParams) - .WillByDefault([this](auto cig_id, auto, - base::OnceCallback cb) { - uint8_t hci_mock_rsp_buffer - [3 + sizeof(uint16_t) * this->volatile_test_cig_create_cmpl_evt_ - .conn_handles.size()]; - uint8_t* p = hci_mock_rsp_buffer; - - UINT8_TO_STREAM(p, this->volatile_test_cig_create_cmpl_evt_.status); - UINT8_TO_STREAM(p, cig_id); - UINT8_TO_STREAM( - p, this->volatile_test_cig_create_cmpl_evt_.conn_handles.size()); - for (auto handle : - this->volatile_test_cig_create_cmpl_evt_.conn_handles) { - UINT16_TO_STREAM(p, handle); - } - - std::move(cb).Run( - hci_mock_rsp_buffer, - 3 + sizeof(uint16_t) * this->volatile_test_cig_create_cmpl_evt_ - .conn_handles.size()); - return 0; - }); + .WillByDefault([this](auto cig_id, auto, + base::OnceCallback cb) { + uint8_t hci_mock_rsp_buffer[3 + sizeof(uint16_t) * + this->volatile_test_cig_create_cmpl_evt_ + .conn_handles.size()]; + uint8_t* p = hci_mock_rsp_buffer; + + UINT8_TO_STREAM(p, this->volatile_test_cig_create_cmpl_evt_.status); + UINT8_TO_STREAM(p, cig_id); + UINT8_TO_STREAM(p, this->volatile_test_cig_create_cmpl_evt_.conn_handles.size()); + for (auto handle : this->volatile_test_cig_create_cmpl_evt_.conn_handles) { + UINT16_TO_STREAM(p, handle); + } + + std::move(cb).Run( + hci_mock_rsp_buffer, + 3 + sizeof(uint16_t) * + this->volatile_test_cig_create_cmpl_evt_.conn_handles.size()); + return 0; + }); // Default mock CreateCis action ON_CALL(hcic_interface_, CreateCis) - .WillByDefault( - [](uint8_t num_cis, const EXT_CIS_CREATE_CFG* cis_cfg, - base::OnceCallback /* cb */) { - for (const EXT_CIS_CREATE_CFG* cis = cis_cfg; num_cis != 0; - num_cis--, cis++) { + .WillByDefault([](uint8_t num_cis, const EXT_CIS_CREATE_CFG* cis_cfg, + base::OnceCallback /* cb */) { + for (const EXT_CIS_CREATE_CFG* cis = cis_cfg; num_cis != 0; num_cis--, cis++) { std::vector buf(28); uint8_t* p = buf.data(); UINT8_TO_STREAM(p, HCI_SUCCESS); @@ -231,35 +213,30 @@ class IsoManagerTest : public Test { UINT16_TO_STREAM(p, 0x00FB); // Max PDU stom UINT16_TO_STREAM(p, 0x0C60); // ISO interval - IsoManager::GetInstance()->HandleHciEvent( - HCI_BLE_CIS_EST_EVT, buf.data(), buf.size()); + IsoManager::GetInstance()->HandleHciEvent(HCI_BLE_CIS_EST_EVT, buf.data(), + buf.size()); } }); // Default mock disconnect action - ON_CALL(hcic_interface_, Disconnect) - .WillByDefault([](uint16_t handle, uint8_t reason) { - IsoManager::GetInstance()->HandleDisconnect(handle, reason); - }); + ON_CALL(hcic_interface_, Disconnect).WillByDefault([](uint16_t handle, uint8_t reason) { + IsoManager::GetInstance()->HandleDisconnect(handle, reason); + }); // Default mock CreateBig HCI action volatile_test_big_params_evt_ = kDefaultBigParamsEvt; ON_CALL(hcic_interface_, CreateBig) - .WillByDefault( - [this](auto big_handle, - bluetooth::hci::iso_manager::big_create_params big_params) { - std::vector buf(big_params.num_bis * sizeof(uint16_t) + - 18); + .WillByDefault([this](auto big_handle, + bluetooth::hci::iso_manager::big_create_params big_params) { + std::vector buf(big_params.num_bis * sizeof(uint16_t) + 18); uint8_t* p = buf.data(); UINT8_TO_STREAM(p, HCI_SUCCESS); UINT8_TO_STREAM(p, big_handle); - ASSERT_TRUE(big_params.num_bis <= - volatile_test_big_params_evt_.conn_handles.size()); + ASSERT_TRUE(big_params.num_bis <= volatile_test_big_params_evt_.conn_handles.size()); UINT24_TO_STREAM(p, volatile_test_big_params_evt_.big_sync_delay); - UINT24_TO_STREAM( - p, volatile_test_big_params_evt_.transport_latency_big); + UINT24_TO_STREAM(p, volatile_test_big_params_evt_.transport_latency_big); UINT8_TO_STREAM(p, big_params.phy); UINT8_TO_STREAM(p, volatile_test_big_params_evt_.nse); UINT8_TO_STREAM(p, volatile_test_big_params_evt_.bn); @@ -270,35 +247,31 @@ class IsoManagerTest : public Test { UINT8_TO_STREAM(p, big_params.num_bis); for (auto i = 0; i < big_params.num_bis; ++i) { - UINT16_TO_STREAM(p, - volatile_test_big_params_evt_.conn_handles[i]); + UINT16_TO_STREAM(p, volatile_test_big_params_evt_.conn_handles[i]); } - IsoManager::GetInstance()->HandleHciEvent( - HCI_BLE_CREATE_BIG_CPL_EVT, buf.data(), buf.size()); + IsoManager::GetInstance()->HandleHciEvent(HCI_BLE_CREATE_BIG_CPL_EVT, buf.data(), + buf.size()); }); // Default mock TerminateBig HCI action - ON_CALL(hcic_interface_, TerminateBig) - .WillByDefault([](auto big_handle, uint8_t reason) { - std::vector buf(2); - uint8_t* p = buf.data(); - UINT8_TO_STREAM(p, big_handle); - UINT8_TO_STREAM(p, reason); + ON_CALL(hcic_interface_, TerminateBig).WillByDefault([](auto big_handle, uint8_t reason) { + std::vector buf(2); + uint8_t* p = buf.data(); + UINT8_TO_STREAM(p, big_handle); + UINT8_TO_STREAM(p, reason); - IsoManager::GetInstance()->HandleHciEvent(HCI_BLE_TERM_BIG_CPL_EVT, - buf.data(), buf.size()); - }); + IsoManager::GetInstance()->HandleHciEvent(HCI_BLE_TERM_BIG_CPL_EVT, buf.data(), buf.size()); + }); // Default mock SetupIsoDataPath HCI action ON_CALL(hcic_interface_, SetupIsoDataPath) - .WillByDefault( - [](uint16_t iso_handle, uint8_t /* data_path_dir */, - uint8_t /* data_path_id */, uint8_t /* codec_id_format */, - uint16_t /* codec_id_company */, uint16_t /* codec_id_vendor */, - uint32_t /* controller_delay */, - std::vector /* codec_conf */, - base::OnceCallback cb) { + .WillByDefault([](uint16_t iso_handle, uint8_t /* data_path_dir */, + uint8_t /* data_path_id */, uint8_t /* codec_id_format */, + uint16_t /* codec_id_company */, uint16_t /* codec_id_vendor */, + uint32_t /* controller_delay */, + std::vector /* codec_conf */, + base::OnceCallback cb) { std::vector buf(3); uint8_t* p = buf.data(); UINT8_TO_STREAM(p, HCI_SUCCESS); @@ -309,15 +282,15 @@ class IsoManagerTest : public Test { // Default mock RemoveIsoDataPath HCI action ON_CALL(hcic_interface_, RemoveIsoDataPath) - .WillByDefault([](uint16_t iso_handle, uint8_t /* data_path_dir */, - base::OnceCallback cb) { - std::vector buf(3); - uint8_t* p = buf.data(); - UINT8_TO_STREAM(p, HCI_SUCCESS); - UINT16_TO_STREAM(p, iso_handle); - - std::move(cb).Run(buf.data(), buf.size()); - }); + .WillByDefault([](uint16_t iso_handle, uint8_t /* data_path_dir */, + base::OnceCallback cb) { + std::vector buf(3); + uint8_t* p = buf.data(); + UINT8_TO_STREAM(p, HCI_SUCCESS); + UINT16_TO_STREAM(p, iso_handle); + + std::move(cb).Run(buf.data(), buf.size()); + }); } virtual void CleanupIsoManager() { @@ -327,19 +300,13 @@ class IsoManagerTest : public Test { static const bluetooth::hci::iso_manager::big_create_params kDefaultBigParams; static const bluetooth::hci::iso_manager::cig_create_params kDefaultCigParams; - static const bluetooth::hci::iso_manager::cig_create_params - kDefaultCigParams2; - static const bluetooth::hci::iso_manager::cig_create_cmpl_evt - kDefaultCigParamsEvt; - static const bluetooth::hci::iso_manager::big_create_cmpl_evt - kDefaultBigParamsEvt; - static const bluetooth::hci::iso_manager::iso_data_path_params - kDefaultIsoDataPathParams; - - bluetooth::hci::iso_manager::cig_create_cmpl_evt - volatile_test_cig_create_cmpl_evt_; - bluetooth::hci::iso_manager::big_create_cmpl_evt - volatile_test_big_params_evt_; + static const bluetooth::hci::iso_manager::cig_create_params kDefaultCigParams2; + static const bluetooth::hci::iso_manager::cig_create_cmpl_evt kDefaultCigParamsEvt; + static const bluetooth::hci::iso_manager::big_create_cmpl_evt kDefaultBigParamsEvt; + static const bluetooth::hci::iso_manager::iso_data_path_params kDefaultIsoDataPathParams; + + bluetooth::hci::iso_manager::cig_create_cmpl_evt volatile_test_cig_create_cmpl_evt_; + bluetooth::hci::iso_manager::big_create_cmpl_evt volatile_test_big_params_evt_; IsoManager* manager_instance_; bluetooth::shim::MockIsoInterface iso_interface_; @@ -352,15 +319,13 @@ class IsoManagerTest : public Test { void (*iso_active_callback)(bool) = [](bool active) { IsIsoActive = active; }; }; -const bluetooth::hci::iso_manager::cig_create_cmpl_evt - IsoManagerTest::kDefaultCigParamsEvt = { +const bluetooth::hci::iso_manager::cig_create_cmpl_evt IsoManagerTest::kDefaultCigParamsEvt = { .status = 0x00, .cig_id = 128, .conn_handles = std::vector({0x0EFF, 0x00FF}), }; -const bluetooth::hci::iso_manager::big_create_cmpl_evt - IsoManagerTest::kDefaultBigParamsEvt = { +const bluetooth::hci::iso_manager::big_create_cmpl_evt IsoManagerTest::kDefaultBigParamsEvt = { .status = 0x00, .big_id = 0, .big_sync_delay = 0x0080de, @@ -375,19 +340,18 @@ const bluetooth::hci::iso_manager::big_create_cmpl_evt .conn_handles = std::vector({0x0EFE, 0x0E00}), }; -const bluetooth::hci::iso_manager::iso_data_path_params - IsoManagerTest::kDefaultIsoDataPathParams = { - .data_path_dir = bluetooth::hci::iso_manager::kIsoDataPathDirectionOut, - .data_path_id = bluetooth::hci::iso_manager::kIsoDataPathHci, - .codec_id_format = 0x06, - .codec_id_company = 0, - .codec_id_vendor = 0, - .controller_delay = 0, - .codec_conf = {0x02, 0x01, 0x02}, +const bluetooth::hci::iso_manager::iso_data_path_params IsoManagerTest::kDefaultIsoDataPathParams = + { + .data_path_dir = bluetooth::hci::iso_manager::kIsoDataPathDirectionOut, + .data_path_id = bluetooth::hci::iso_manager::kIsoDataPathHci, + .codec_id_format = 0x06, + .codec_id_company = 0, + .codec_id_vendor = 0, + .controller_delay = 0, + .codec_conf = {0x02, 0x01, 0x02}, }; -const bluetooth::hci::iso_manager::big_create_params - IsoManagerTest::kDefaultBigParams = { +const bluetooth::hci::iso_manager::big_create_params IsoManagerTest::kDefaultBigParams = { .adv_handle = 0x00, .num_bis = 2, .sdu_itv = 0x002710, @@ -401,8 +365,7 @@ const bluetooth::hci::iso_manager::big_create_params .enc_code = std::array({0}), }; -const bluetooth::hci::iso_manager::cig_create_params - IsoManagerTest::kDefaultCigParams = { +const bluetooth::hci::iso_manager::cig_create_params IsoManagerTest::kDefaultCigParams = { .sdu_itv_mtos = 0x00002710, .sdu_itv_stom = 0x00002711, .sca = bluetooth::hci::iso_manager::kIsoSca0To20Ppm, @@ -411,32 +374,31 @@ const bluetooth::hci::iso_manager::cig_create_params .max_trans_lat_stom = 0x000A, .max_trans_lat_mtos = 0x0009, .cis_cfgs = - { - // CIS #1 - { - .cis_id = 1, - .max_sdu_size_mtos = 0x0028, - .max_sdu_size_stom = 0x0027, - .phy_mtos = 0x04, - .phy_stom = 0x03, - .rtn_mtos = 0x02, - .rtn_stom = 0x01, - }, - // CIS #2 { - .cis_id = 2, - .max_sdu_size_mtos = 0x0029, - .max_sdu_size_stom = 0x002A, - .phy_mtos = 0x09, - .phy_stom = 0x08, - .rtn_mtos = 0x07, - .rtn_stom = 0x06, + // CIS #1 + { + .cis_id = 1, + .max_sdu_size_mtos = 0x0028, + .max_sdu_size_stom = 0x0027, + .phy_mtos = 0x04, + .phy_stom = 0x03, + .rtn_mtos = 0x02, + .rtn_stom = 0x01, + }, + // CIS #2 + { + .cis_id = 2, + .max_sdu_size_mtos = 0x0029, + .max_sdu_size_stom = 0x002A, + .phy_mtos = 0x09, + .phy_stom = 0x08, + .rtn_mtos = 0x07, + .rtn_stom = 0x06, + }, }, - }, }; -const bluetooth::hci::iso_manager::cig_create_params - IsoManagerTest::kDefaultCigParams2 = { +const bluetooth::hci::iso_manager::cig_create_params IsoManagerTest::kDefaultCigParams2 = { .sdu_itv_mtos = 0x00002709, .sdu_itv_stom = 0x00002700, .sca = bluetooth::hci::iso_manager::kIsoSca0To20Ppm, @@ -445,83 +407,71 @@ const bluetooth::hci::iso_manager::cig_create_params .max_trans_lat_stom = 0x000B, .max_trans_lat_mtos = 0x0006, .cis_cfgs = - { - // CIS #1 { - .cis_id = 1, - .max_sdu_size_mtos = 0x0022, - .max_sdu_size_stom = 0x0022, - .phy_mtos = 0x01, - .phy_stom = 0x02, - .rtn_mtos = 0x02, - .rtn_stom = 0x01, + // CIS #1 + { + .cis_id = 1, + .max_sdu_size_mtos = 0x0022, + .max_sdu_size_stom = 0x0022, + .phy_mtos = 0x01, + .phy_stom = 0x02, + .rtn_mtos = 0x02, + .rtn_stom = 0x01, + }, + // CIS #2 + { + .cis_id = 2, + .max_sdu_size_mtos = 0x002A, + .max_sdu_size_stom = 0x002B, + .phy_mtos = 0x06, + .phy_stom = 0x06, + .rtn_mtos = 0x07, + .rtn_stom = 0x07, + }, }, - // CIS #2 - { - .cis_id = 2, - .max_sdu_size_mtos = 0x002A, - .max_sdu_size_stom = 0x002B, - .phy_mtos = 0x06, - .phy_stom = 0x06, - .rtn_mtos = 0x07, - .rtn_stom = 0x07, - }, - }, }; class IsoManagerDeathTest : public IsoManagerTest {}; class IsoManagerDeathTestNoInit : public IsoManagerTest { - protected: - void InitIsoManager() override { /* DO NOTHING */ - } +protected: + void InitIsoManager() override { /* DO NOTHING */ } - void CleanupIsoManager() override { /* DO NOTHING */ - } + void CleanupIsoManager() override { /* DO NOTHING */ } }; class IsoManagerDeathTestNoCleanup : public IsoManagerTest { - protected: - void CleanupIsoManager() override { /* DO NOTHING */ - } +protected: + void CleanupIsoManager() override { /* DO NOTHING */ } }; bool operator==(const EXT_CIS_CFG& x, const EXT_CIS_CFG& y) { - return ((x.cis_id == y.cis_id) && - (x.max_sdu_size_mtos == y.max_sdu_size_mtos) && - (x.max_sdu_size_stom == y.max_sdu_size_stom) && - (x.phy_mtos == y.phy_mtos) && (x.phy_stom == y.phy_stom) && - (x.rtn_mtos == y.rtn_mtos) && (x.rtn_stom == y.rtn_stom)); -} - -bool operator==( - const struct bluetooth::hci::iso_manager::cig_create_params& x, - const struct bluetooth::hci::iso_manager::cig_create_params& y) { - return ((x.sdu_itv_mtos == y.sdu_itv_mtos) && - (x.sdu_itv_stom == y.sdu_itv_stom) && (x.sca == y.sca) && - (x.packing == y.packing) && (x.framing == y.framing) && - (x.max_trans_lat_stom == y.max_trans_lat_stom) && - (x.max_trans_lat_mtos == y.max_trans_lat_mtos) && - std::is_permutation(x.cis_cfgs.begin(), x.cis_cfgs.end(), - y.cis_cfgs.begin())); -} - -bool operator==( - const struct bluetooth::hci::iso_manager::big_create_params& x, - const struct bluetooth::hci::iso_manager::big_create_params& y) { - return ((x.adv_handle == y.adv_handle) && (x.num_bis == y.num_bis) && - (x.sdu_itv == y.sdu_itv) && (x.max_sdu_size == y.max_sdu_size) && - (x.max_transport_latency == y.max_transport_latency) && - (x.rtn == y.rtn) && (x.phy == y.phy) && (x.packing == y.packing) && - (x.framing == y.framing) && (x.enc == y.enc) && - (x.enc_code == y.enc_code)); + return (x.cis_id == y.cis_id) && (x.max_sdu_size_mtos == y.max_sdu_size_mtos) && + (x.max_sdu_size_stom == y.max_sdu_size_stom) && (x.phy_mtos == y.phy_mtos) && + (x.phy_stom == y.phy_stom) && (x.rtn_mtos == y.rtn_mtos) && (x.rtn_stom == y.rtn_stom); } -namespace iso_matchers { -MATCHER_P(Eq, value, "") { return (arg == value); } -MATCHER_P2(EqPointedArray, value, len, "") { - return (!std::memcmp(arg, value, len)); +bool operator==(const struct bluetooth::hci::iso_manager::cig_create_params& x, + const struct bluetooth::hci::iso_manager::cig_create_params& y) { + return (x.sdu_itv_mtos == y.sdu_itv_mtos) && (x.sdu_itv_stom == y.sdu_itv_stom) && + (x.sca == y.sca) && (x.packing == y.packing) && (x.framing == y.framing) && + (x.max_trans_lat_stom == y.max_trans_lat_stom) && + (x.max_trans_lat_mtos == y.max_trans_lat_mtos) && + std::is_permutation(x.cis_cfgs.begin(), x.cis_cfgs.end(), y.cis_cfgs.begin()); +} + +bool operator==(const struct bluetooth::hci::iso_manager::big_create_params& x, + const struct bluetooth::hci::iso_manager::big_create_params& y) { + return (x.adv_handle == y.adv_handle) && (x.num_bis == y.num_bis) && (x.sdu_itv == y.sdu_itv) && + (x.max_sdu_size == y.max_sdu_size) && + (x.max_transport_latency == y.max_transport_latency) && (x.rtn == y.rtn) && + (x.phy == y.phy) && (x.packing == y.packing) && (x.framing == y.framing) && + (x.enc == y.enc) && (x.enc_code == y.enc_code); } + +namespace iso_matchers { +MATCHER_P(Eq, value, "") { return arg == value; } +MATCHER_P2(EqPointedArray, value, len, "") { return !std::memcmp(arg, value, len); } } // namespace iso_matchers TEST_F(IsoManagerTest, SingletonAccess) { @@ -561,10 +511,9 @@ TEST_F(IsoManagerDeathTestNoInit, RegisterNullCigCallbacks) { // Verify hci layer being called by the Iso Manager TEST_F(IsoManagerTest, CreateCigHciCall) { for (uint8_t i = 220; i != 60; ++i) { - EXPECT_CALL(hcic_interface_, - SetCigParams(i, iso_matchers::Eq(kDefaultCigParams), _)) - .Times(1) - .RetiresOnSaturation(); + EXPECT_CALL(hcic_interface_, SetCigParams(i, iso_matchers::Eq(kDefaultCigParams), _)) + .Times(1) + .RetiresOnSaturation(); IsoManager::GetInstance()->CreateCig(i, kDefaultCigParams); } } @@ -573,23 +522,20 @@ TEST_F(IsoManagerTest, CreateCigHciCall) { TEST_F(IsoManagerDeathTest, CreateSameCigTwice) { bluetooth::hci::iso_manager::cig_create_cmpl_evt evt; evt.status = 0x01; - EXPECT_CALL( - *cig_callbacks_, - OnCigEvent(bluetooth::hci::iso_manager::kIsoEventCigOnCreateCmpl, _)) - .WillOnce([&evt](uint8_t /* type */, void* data) { - evt = *static_cast( - data); - return 0; - }); + EXPECT_CALL(*cig_callbacks_, OnCigEvent(bluetooth::hci::iso_manager::kIsoEventCigOnCreateCmpl, _)) + .WillOnce([&evt](uint8_t /* type */, void* data) { + evt = *static_cast(data); + return 0; + }); volatile_test_cig_create_cmpl_evt_.cig_id = 127; - IsoManager::GetInstance()->CreateCig( - volatile_test_cig_create_cmpl_evt_.cig_id, kDefaultCigParams); + IsoManager::GetInstance()->CreateCig(volatile_test_cig_create_cmpl_evt_.cig_id, + kDefaultCigParams); ASSERT_EQ(evt.status, HCI_SUCCESS); // Second call with the same CIG ID should fail - ASSERT_EXIT(IsoManager::GetInstance()->CreateCig( - volatile_test_cig_create_cmpl_evt_.cig_id, kDefaultCigParams), + ASSERT_EXIT(IsoManager::GetInstance()->CreateCig(volatile_test_cig_create_cmpl_evt_.cig_id, + kDefaultCigParams), ::testing::KilledBySignal(SIGABRT), "already exists"); } @@ -597,9 +543,8 @@ TEST_F(IsoManagerDeathTest, CreateSameCigTwice) { TEST_F(IsoManagerDeathTest, CreateCigCallbackInvalidRspPacket) { uint8_t hci_mock_rsp_buffer[] = {0x00, 0x00}; ON_CALL(hcic_interface_, SetCigParams) - .WillByDefault( - [&hci_mock_rsp_buffer]( - auto, auto, base::OnceCallback cb) { + .WillByDefault([&hci_mock_rsp_buffer](auto, auto, + base::OnceCallback cb) { std::move(cb).Run(hci_mock_rsp_buffer, sizeof(hci_mock_rsp_buffer)); return 0; }); @@ -612,9 +557,8 @@ TEST_F(IsoManagerDeathTest, CreateCigCallbackInvalidRspPacket) { TEST_F(IsoManagerDeathTest, CreateCigCallbackInvalidRspPacket2) { uint8_t hci_mock_rsp_buffer[] = {0x00, 0x00, 0x02, 0x01, 0x00}; ON_CALL(hcic_interface_, SetCigParams) - .WillByDefault( - [&hci_mock_rsp_buffer]( - auto, auto, base::OnceCallback cb) { + .WillByDefault([&hci_mock_rsp_buffer](auto, auto, + base::OnceCallback cb) { std::move(cb).Run(hci_mock_rsp_buffer, sizeof(hci_mock_rsp_buffer)); return 0; }); @@ -631,22 +575,18 @@ TEST_F(IsoManagerTest, CreateCigCallbackInvalidStatus) { uint8_t hci_mock_rsp_buffer[] = {rsp_status, rsp_cig_id, rsp_cis_cnt}; ON_CALL(hcic_interface_, SetCigParams) - .WillByDefault( - [&hci_mock_rsp_buffer]( - auto, auto, base::OnceCallback cb) { + .WillByDefault([&hci_mock_rsp_buffer](auto, auto, + base::OnceCallback cb) { std::move(cb).Run(hci_mock_rsp_buffer, sizeof(hci_mock_rsp_buffer)); return 0; }); bluetooth::hci::iso_manager::cig_create_cmpl_evt evt; - EXPECT_CALL( - *cig_callbacks_, - OnCigEvent(bluetooth::hci::iso_manager::kIsoEventCigOnCreateCmpl, _)) - .WillOnce([&evt](uint8_t /* type */, void* data) { - evt = *static_cast( - data); - return 0; - }); + EXPECT_CALL(*cig_callbacks_, OnCigEvent(bluetooth::hci::iso_manager::kIsoEventCigOnCreateCmpl, _)) + .WillOnce([&evt](uint8_t /* type */, void* data) { + evt = *static_cast(data); + return 0; + }); IsoManager::GetInstance()->CreateCig(rsp_cig_id, kDefaultCigParams); ASSERT_EQ(evt.cig_id, rsp_cig_id); @@ -657,36 +597,32 @@ TEST_F(IsoManagerTest, CreateCigCallbackInvalidStatus) { // Check valid callback response TEST_F(IsoManagerTest, CreateCigCallbackValid) { bluetooth::hci::iso_manager::cig_create_cmpl_evt evt; - EXPECT_CALL( - *cig_callbacks_, - OnCigEvent(bluetooth::hci::iso_manager::kIsoEventCigOnCreateCmpl, _)) - .WillOnce([&evt](uint8_t /* type */, void* data) { - evt = *static_cast( - data); - return 0; - }); - - IsoManager::GetInstance()->CreateCig( - volatile_test_cig_create_cmpl_evt_.cig_id, kDefaultCigParams); + EXPECT_CALL(*cig_callbacks_, OnCigEvent(bluetooth::hci::iso_manager::kIsoEventCigOnCreateCmpl, _)) + .WillOnce([&evt](uint8_t /* type */, void* data) { + evt = *static_cast(data); + return 0; + }); + + IsoManager::GetInstance()->CreateCig(volatile_test_cig_create_cmpl_evt_.cig_id, + kDefaultCigParams); ASSERT_EQ(evt.cig_id, volatile_test_cig_create_cmpl_evt_.cig_id); ASSERT_EQ(evt.status, volatile_test_cig_create_cmpl_evt_.status); ASSERT_EQ(evt.conn_handles.size(), 2u); - ASSERT_TRUE( - std::is_permutation(evt.conn_handles.begin(), evt.conn_handles.end(), - std::vector({0x0EFF, 0x00FF}).begin())); + ASSERT_TRUE(std::is_permutation(evt.conn_handles.begin(), evt.conn_handles.end(), + std::vector({0x0EFF, 0x00FF}).begin())); } TEST_F(IsoManagerTest, CreateCigLateArrivingCallback) { // Catch the callback base::OnceCallback iso_cb; ON_CALL(hcic_interface_, SetCigParams) - .WillByDefault([&](auto /* cig_id */, auto, - base::OnceCallback cb) { - iso_cb = std::move(cb); - }); + .WillByDefault( + [&](auto /* cig_id */, auto, base::OnceCallback cb) { + iso_cb = std::move(cb); + }); - IsoManager::GetInstance()->CreateCig( - volatile_test_cig_create_cmpl_evt_.cig_id, kDefaultCigParams); + IsoManager::GetInstance()->CreateCig(volatile_test_cig_create_cmpl_evt_.cig_id, + kDefaultCigParams); // Stop the IsoManager before calling the callback IsoManager::GetInstance()->Stop(); @@ -696,8 +632,7 @@ TEST_F(IsoManagerTest, CreateCigLateArrivingCallback) { ASSERT_FALSE(iso_cb.is_null()); uint8_t hci_mock_rsp_buffer[3 + sizeof(uint16_t) * - volatile_test_cig_create_cmpl_evt_ - .conn_handles.size()]; + volatile_test_cig_create_cmpl_evt_.conn_handles.size()]; uint8_t* p = hci_mock_rsp_buffer; UINT8_TO_STREAM(p, volatile_test_cig_create_cmpl_evt_.status); UINT8_TO_STREAM(p, volatile_test_cig_create_cmpl_evt_.cig_id); @@ -706,22 +641,20 @@ TEST_F(IsoManagerTest, CreateCigLateArrivingCallback) { UINT16_TO_STREAM(p, handle); } std::move(iso_cb).Run( - hci_mock_rsp_buffer, - 3 + sizeof(uint16_t) * - volatile_test_cig_create_cmpl_evt_.conn_handles.size()); + hci_mock_rsp_buffer, + 3 + sizeof(uint16_t) * volatile_test_cig_create_cmpl_evt_.conn_handles.size()); } // Check if CIG reconfigure triggers HCI layer call TEST_F(IsoManagerTest, ReconfigureCigHciCall) { - IsoManager::GetInstance()->CreateCig( - volatile_test_cig_create_cmpl_evt_.cig_id, kDefaultCigParams); + IsoManager::GetInstance()->CreateCig(volatile_test_cig_create_cmpl_evt_.cig_id, + kDefaultCigParams); - EXPECT_CALL(hcic_interface_, - SetCigParams(volatile_test_cig_create_cmpl_evt_.cig_id, - iso_matchers::Eq(kDefaultCigParams), _)) - .Times(1); - IsoManager::GetInstance()->ReconfigureCig( - volatile_test_cig_create_cmpl_evt_.cig_id, kDefaultCigParams); + EXPECT_CALL(hcic_interface_, SetCigParams(volatile_test_cig_create_cmpl_evt_.cig_id, + iso_matchers::Eq(kDefaultCigParams), _)) + .Times(1); + IsoManager::GetInstance()->ReconfigureCig(volatile_test_cig_create_cmpl_evt_.cig_id, + kDefaultCigParams); } // Verify handlidng invalid call - reconfiguring invalid CIG @@ -733,38 +666,35 @@ TEST_F(IsoManagerDeathTest, ReconfigureCigWithNoSuchCig) { TEST_F(IsoManagerDeathTest, ReconfigureCigInvalidRspPacket) { uint8_t hci_mock_rsp_buffer[] = {0x00, 0x00}; - IsoManager::GetInstance()->CreateCig( - volatile_test_cig_create_cmpl_evt_.cig_id, kDefaultCigParams); + IsoManager::GetInstance()->CreateCig(volatile_test_cig_create_cmpl_evt_.cig_id, + kDefaultCigParams); ON_CALL(hcic_interface_, SetCigParams) - .WillByDefault( - [&hci_mock_rsp_buffer]( - auto, auto, base::OnceCallback cb) { + .WillByDefault([&hci_mock_rsp_buffer](auto, auto, + base::OnceCallback cb) { std::move(cb).Run(hci_mock_rsp_buffer, sizeof(hci_mock_rsp_buffer)); return 0; }); - ASSERT_EXIT(IsoManager::GetInstance()->ReconfigureCig( - volatile_test_cig_create_cmpl_evt_.cig_id, kDefaultCigParams), + ASSERT_EXIT(IsoManager::GetInstance()->ReconfigureCig(volatile_test_cig_create_cmpl_evt_.cig_id, + kDefaultCigParams), ::testing::KilledBySignal(SIGABRT), "Invalid packet length"); } TEST_F(IsoManagerDeathTest, ReconfigureCigInvalidRspPacket2) { uint8_t hci_mock_rsp_buffer[] = {0x00, 0x00, 0x02, 0x01, 0x00}; - IsoManager::GetInstance()->CreateCig( - volatile_test_cig_create_cmpl_evt_.cig_id, kDefaultCigParams); + IsoManager::GetInstance()->CreateCig(volatile_test_cig_create_cmpl_evt_.cig_id, + kDefaultCigParams); ON_CALL(hcic_interface_, SetCigParams) - .WillByDefault( - [&hci_mock_rsp_buffer]( - auto, auto, base::OnceCallback cb) { + .WillByDefault([&hci_mock_rsp_buffer](auto, auto, + base::OnceCallback cb) { std::move(cb).Run(hci_mock_rsp_buffer, sizeof(hci_mock_rsp_buffer)); return 0; }); - ASSERT_EXIT( - IsoManager::GetInstance()->ReconfigureCig( - volatile_test_cig_create_cmpl_evt_.cig_id, kDefaultCigParams2), - ::testing::KilledBySignal(SIGABRT), "Invalid CIS count"); + ASSERT_EXIT(IsoManager::GetInstance()->ReconfigureCig(volatile_test_cig_create_cmpl_evt_.cig_id, + kDefaultCigParams2), + ::testing::KilledBySignal(SIGABRT), "Invalid CIS count"); } TEST_F(IsoManagerTest, ReconfigureCigInvalidStatus) { @@ -777,22 +707,19 @@ TEST_F(IsoManagerTest, ReconfigureCigInvalidStatus) { // Set-up the invalid response ON_CALL(hcic_interface_, SetCigParams) - .WillByDefault( - [&hci_mock_rsp_buffer]( - auto, auto, base::OnceCallback cb) { + .WillByDefault([&hci_mock_rsp_buffer](auto, auto, + base::OnceCallback cb) { std::move(cb).Run(hci_mock_rsp_buffer, sizeof(hci_mock_rsp_buffer)); return 0; }); bluetooth::hci::iso_manager::cig_create_cmpl_evt evt; - EXPECT_CALL( - *cig_callbacks_, - OnCigEvent(bluetooth::hci::iso_manager::kIsoEventCigOnReconfigureCmpl, _)) - .WillOnce([&evt](uint8_t /* type */, void* data) { - evt = *static_cast( - data); - return 0; - }); + EXPECT_CALL(*cig_callbacks_, + OnCigEvent(bluetooth::hci::iso_manager::kIsoEventCigOnReconfigureCmpl, _)) + .WillOnce([&evt](uint8_t /* type */, void* data) { + evt = *static_cast(data); + return 0; + }); IsoManager::GetInstance()->ReconfigureCig(rsp_cig_id, kDefaultCigParams2); ASSERT_EQ(evt.cig_id, rsp_cig_id); @@ -801,42 +728,39 @@ TEST_F(IsoManagerTest, ReconfigureCigInvalidStatus) { } TEST_F(IsoManagerTest, ReconfigureCigValid) { - IsoManager::GetInstance()->CreateCig( - volatile_test_cig_create_cmpl_evt_.cig_id, kDefaultCigParams); + IsoManager::GetInstance()->CreateCig(volatile_test_cig_create_cmpl_evt_.cig_id, + kDefaultCigParams); bluetooth::hci::iso_manager::cig_create_cmpl_evt evt; - EXPECT_CALL( - *cig_callbacks_, - OnCigEvent(bluetooth::hci::iso_manager::kIsoEventCigOnReconfigureCmpl, _)) - .WillOnce([&evt](uint8_t /* type */, void* data) { - evt = *static_cast( - data); - return 0; - }); + EXPECT_CALL(*cig_callbacks_, + OnCigEvent(bluetooth::hci::iso_manager::kIsoEventCigOnReconfigureCmpl, _)) + .WillOnce([&evt](uint8_t /* type */, void* data) { + evt = *static_cast(data); + return 0; + }); // Verify valid reconfiguration request - IsoManager::GetInstance()->ReconfigureCig( - volatile_test_cig_create_cmpl_evt_.cig_id, kDefaultCigParams2); + IsoManager::GetInstance()->ReconfigureCig(volatile_test_cig_create_cmpl_evt_.cig_id, + kDefaultCigParams2); ASSERT_EQ(evt.cig_id, volatile_test_cig_create_cmpl_evt_.cig_id); ASSERT_EQ(evt.status, volatile_test_cig_create_cmpl_evt_.status); - ASSERT_TRUE(std::is_permutation( - evt.conn_handles.begin(), evt.conn_handles.end(), - volatile_test_cig_create_cmpl_evt_.conn_handles.begin())); + ASSERT_TRUE(std::is_permutation(evt.conn_handles.begin(), evt.conn_handles.end(), + volatile_test_cig_create_cmpl_evt_.conn_handles.begin())); } TEST_F(IsoManagerTest, ReconfigureCigLateArrivingCallback) { - IsoManager::GetInstance()->CreateCig( - volatile_test_cig_create_cmpl_evt_.cig_id, kDefaultCigParams); + IsoManager::GetInstance()->CreateCig(volatile_test_cig_create_cmpl_evt_.cig_id, + kDefaultCigParams); // Catch the callback base::OnceCallback iso_cb; ON_CALL(hcic_interface_, SetCigParams) - .WillByDefault([&](auto /* cig_id */, auto, - base::OnceCallback cb) { - iso_cb = std::move(cb); - }); - IsoManager::GetInstance()->ReconfigureCig( - volatile_test_cig_create_cmpl_evt_.cig_id, kDefaultCigParams2); + .WillByDefault( + [&](auto /* cig_id */, auto, base::OnceCallback cb) { + iso_cb = std::move(cb); + }); + IsoManager::GetInstance()->ReconfigureCig(volatile_test_cig_create_cmpl_evt_.cig_id, + kDefaultCigParams2); // Stop the IsoManager before calling the callback IsoManager::GetInstance()->Stop(); @@ -846,8 +770,7 @@ TEST_F(IsoManagerTest, ReconfigureCigLateArrivingCallback) { ASSERT_FALSE(iso_cb.is_null()); uint8_t hci_mock_rsp_buffer[3 + sizeof(uint16_t) * - volatile_test_cig_create_cmpl_evt_ - .conn_handles.size()]; + volatile_test_cig_create_cmpl_evt_.conn_handles.size()]; uint8_t* p = hci_mock_rsp_buffer; UINT8_TO_STREAM(p, volatile_test_cig_create_cmpl_evt_.status); UINT8_TO_STREAM(p, volatile_test_cig_create_cmpl_evt_.cig_id); @@ -856,43 +779,34 @@ TEST_F(IsoManagerTest, ReconfigureCigLateArrivingCallback) { UINT16_TO_STREAM(p, handle); } std::move(iso_cb).Run( - hci_mock_rsp_buffer, - 3 + sizeof(uint16_t) * - volatile_test_cig_create_cmpl_evt_.conn_handles.size()); + hci_mock_rsp_buffer, + 3 + sizeof(uint16_t) * volatile_test_cig_create_cmpl_evt_.conn_handles.size()); } TEST_F(IsoManagerTest, RemoveCigHciCall) { - IsoManager::GetInstance()->CreateCig( - volatile_test_cig_create_cmpl_evt_.cig_id, kDefaultCigParams); + IsoManager::GetInstance()->CreateCig(volatile_test_cig_create_cmpl_evt_.cig_id, + kDefaultCigParams); - EXPECT_CALL(hcic_interface_, - RemoveCig(volatile_test_cig_create_cmpl_evt_.cig_id, _)) - .Times(1); - IsoManager::GetInstance()->RemoveCig( - volatile_test_cig_create_cmpl_evt_.cig_id); + EXPECT_CALL(hcic_interface_, RemoveCig(volatile_test_cig_create_cmpl_evt_.cig_id, _)).Times(1); + IsoManager::GetInstance()->RemoveCig(volatile_test_cig_create_cmpl_evt_.cig_id); } TEST_F(IsoManagerDeathTest, RemoveCigWithNoSuchCig) { - ASSERT_EXIT(IsoManager::GetInstance()->RemoveCig( - volatile_test_cig_create_cmpl_evt_.cig_id), + ASSERT_EXIT(IsoManager::GetInstance()->RemoveCig(volatile_test_cig_create_cmpl_evt_.cig_id), ::testing::KilledBySignal(SIGABRT), "No such cig"); } TEST_F(IsoManagerDeathTest, RemoveCigForceNoSuchCig) { - EXPECT_CALL(hcic_interface_, - RemoveCig(volatile_test_cig_create_cmpl_evt_.cig_id, _)) - .Times(1); - IsoManager::GetInstance()->RemoveCig( - volatile_test_cig_create_cmpl_evt_.cig_id, true); + EXPECT_CALL(hcic_interface_, RemoveCig(volatile_test_cig_create_cmpl_evt_.cig_id, _)).Times(1); + IsoManager::GetInstance()->RemoveCig(volatile_test_cig_create_cmpl_evt_.cig_id, true); } TEST_F(IsoManagerDeathTest, RemoveSameCigTwice) { - IsoManager::GetInstance()->CreateCig( - volatile_test_cig_create_cmpl_evt_.cig_id, kDefaultCigParams); + IsoManager::GetInstance()->CreateCig(volatile_test_cig_create_cmpl_evt_.cig_id, + kDefaultCigParams); ON_CALL(hcic_interface_, RemoveCig) - .WillByDefault( - [this](auto, base::OnceCallback cb) { + .WillByDefault([this](auto, base::OnceCallback cb) { uint8_t hci_mock_rsp_buffer[2]; uint8_t* p = hci_mock_rsp_buffer; @@ -903,98 +817,84 @@ TEST_F(IsoManagerDeathTest, RemoveSameCigTwice) { return 0; }); - IsoManager::GetInstance()->RemoveCig( - volatile_test_cig_create_cmpl_evt_.cig_id); + IsoManager::GetInstance()->RemoveCig(volatile_test_cig_create_cmpl_evt_.cig_id); - ASSERT_EXIT(IsoManager::GetInstance()->RemoveCig( - volatile_test_cig_create_cmpl_evt_.cig_id), + ASSERT_EXIT(IsoManager::GetInstance()->RemoveCig(volatile_test_cig_create_cmpl_evt_.cig_id), ::testing::KilledBySignal(SIGABRT), "No such cig"); } TEST_F(IsoManagerDeathTest, RemoveCigInvalidRspPacket) { - IsoManager::GetInstance()->CreateCig( - volatile_test_cig_create_cmpl_evt_.cig_id, kDefaultCigParams); + IsoManager::GetInstance()->CreateCig(volatile_test_cig_create_cmpl_evt_.cig_id, + kDefaultCigParams); ON_CALL(hcic_interface_, RemoveCig) - .WillByDefault([](auto, base::OnceCallback cb) { - uint8_t hci_mock_rsp_buffer[] = {0x00}; // status byte only - - std::move(cb).Run(hci_mock_rsp_buffer, sizeof(hci_mock_rsp_buffer)); - return 0; - }); - ASSERT_EXIT(IsoManager::GetInstance()->RemoveCig( - volatile_test_cig_create_cmpl_evt_.cig_id), + .WillByDefault([](auto, base::OnceCallback cb) { + uint8_t hci_mock_rsp_buffer[] = {0x00}; // status byte only + + std::move(cb).Run(hci_mock_rsp_buffer, sizeof(hci_mock_rsp_buffer)); + return 0; + }); + ASSERT_EXIT(IsoManager::GetInstance()->RemoveCig(volatile_test_cig_create_cmpl_evt_.cig_id), ::testing::KilledBySignal(SIGABRT), "Invalid packet length"); } TEST_F(IsoManagerTest, RemoveCigInvalidStatus) { uint8_t rsp_status = 0x02; - uint8_t hci_mock_rsp_buffer[] = {rsp_status, - volatile_test_cig_create_cmpl_evt_.cig_id}; + uint8_t hci_mock_rsp_buffer[] = {rsp_status, volatile_test_cig_create_cmpl_evt_.cig_id}; - IsoManager::GetInstance()->CreateCig( - volatile_test_cig_create_cmpl_evt_.cig_id, kDefaultCigParams); + IsoManager::GetInstance()->CreateCig(volatile_test_cig_create_cmpl_evt_.cig_id, + kDefaultCigParams); ON_CALL(hcic_interface_, RemoveCig) - .WillByDefault( - [&hci_mock_rsp_buffer]( - auto, base::OnceCallback cb) { - std::move(cb).Run(hci_mock_rsp_buffer, sizeof(hci_mock_rsp_buffer)); + .WillByDefault( + [&hci_mock_rsp_buffer](auto, base::OnceCallback cb) { + std::move(cb).Run(hci_mock_rsp_buffer, sizeof(hci_mock_rsp_buffer)); + return 0; + }); + + bluetooth::hci::iso_manager::cig_remove_cmpl_evt evt; + ON_CALL(*cig_callbacks_, OnCigEvent(bluetooth::hci::iso_manager::kIsoEventCigOnRemoveCmpl, _)) + .WillByDefault([&evt](uint8_t /* type */, void* data) { + evt = *static_cast(data); return 0; }); - bluetooth::hci::iso_manager::cig_remove_cmpl_evt evt; - ON_CALL(*cig_callbacks_, - OnCigEvent(bluetooth::hci::iso_manager::kIsoEventCigOnRemoveCmpl, _)) - .WillByDefault([&evt](uint8_t /* type */, void* data) { - evt = *static_cast( - data); - return 0; - }); - - IsoManager::GetInstance()->RemoveCig( - volatile_test_cig_create_cmpl_evt_.cig_id); + IsoManager::GetInstance()->RemoveCig(volatile_test_cig_create_cmpl_evt_.cig_id); ASSERT_EQ(evt.cig_id, volatile_test_cig_create_cmpl_evt_.cig_id); ASSERT_EQ(evt.status, rsp_status); } TEST_F(IsoManagerTest, RemoveCigValid) { - uint8_t hci_mock_rsp_buffer[] = {HCI_SUCCESS, - volatile_test_cig_create_cmpl_evt_.cig_id}; + uint8_t hci_mock_rsp_buffer[] = {HCI_SUCCESS, volatile_test_cig_create_cmpl_evt_.cig_id}; ASSERT_EQ(IsIsoActive, false); - IsoManager::GetInstance()->CreateCig( - volatile_test_cig_create_cmpl_evt_.cig_id, kDefaultCigParams); + IsoManager::GetInstance()->CreateCig(volatile_test_cig_create_cmpl_evt_.cig_id, + kDefaultCigParams); ASSERT_EQ(IsIsoActive, true); ON_CALL(hcic_interface_, RemoveCig) - .WillByDefault( - [&hci_mock_rsp_buffer]( - auto, base::OnceCallback cb) { - std::move(cb).Run(hci_mock_rsp_buffer, sizeof(hci_mock_rsp_buffer)); + .WillByDefault( + [&hci_mock_rsp_buffer](auto, base::OnceCallback cb) { + std::move(cb).Run(hci_mock_rsp_buffer, sizeof(hci_mock_rsp_buffer)); + return 0; + }); + + bluetooth::hci::iso_manager::cig_remove_cmpl_evt evt; + EXPECT_CALL(*cig_callbacks_, OnCigEvent(bluetooth::hci::iso_manager::kIsoEventCigOnRemoveCmpl, _)) + .WillOnce([&evt](uint8_t /* type */, void* data) { + evt = *static_cast(data); return 0; }); - bluetooth::hci::iso_manager::cig_remove_cmpl_evt evt; - EXPECT_CALL( - *cig_callbacks_, - OnCigEvent(bluetooth::hci::iso_manager::kIsoEventCigOnRemoveCmpl, _)) - .WillOnce([&evt](uint8_t /* type */, void* data) { - evt = *static_cast( - data); - return 0; - }); - - IsoManager::GetInstance()->RemoveCig( - volatile_test_cig_create_cmpl_evt_.cig_id); + IsoManager::GetInstance()->RemoveCig(volatile_test_cig_create_cmpl_evt_.cig_id); ASSERT_EQ(evt.cig_id, volatile_test_cig_create_cmpl_evt_.cig_id); ASSERT_EQ(evt.status, HCI_SUCCESS); ASSERT_EQ(IsIsoActive, false); } TEST_F(IsoManagerTest, EstablishCisHciCall) { - IsoManager::GetInstance()->CreateCig( - volatile_test_cig_create_cmpl_evt_.cig_id, kDefaultCigParams); + IsoManager::GetInstance()->CreateCig(volatile_test_cig_create_cmpl_evt_.cig_id, + kDefaultCigParams); bluetooth::hci::iso_manager::cis_establish_params params; for (auto& handle : volatile_test_cig_create_cmpl_evt_.conn_handles) { @@ -1004,11 +904,10 @@ TEST_F(IsoManagerTest, EstablishCisHciCall) { EXPECT_CALL(hcic_interface_, CreateCis(2, iso_matchers::EqPointedArray( - params.conn_pairs.data(), - params.conn_pairs.size() * - sizeof(params.conn_pairs.data()[0])), + params.conn_pairs.data(), + params.conn_pairs.size() * sizeof(params.conn_pairs.data()[0])), _)) - .Times(1); + .Times(1); IsoManager::GetInstance()->EstablishCis(params); } @@ -1018,15 +917,13 @@ TEST_F(IsoManagerDeathTest, EstablishCisWithNoSuchCis) { params.conn_pairs.push_back({handle, 1}); } - ASSERT_EXIT( - IsoManager::GetInstance()->IsoManager::GetInstance()->EstablishCis( - params), - ::testing::KilledBySignal(SIGABRT), "No such cis"); + ASSERT_EXIT(IsoManager::GetInstance()->IsoManager::GetInstance()->EstablishCis(params), + ::testing::KilledBySignal(SIGABRT), "No such cis"); } TEST_F(IsoManagerDeathTest, ConnectSameCisTwice) { - IsoManager::GetInstance()->CreateCig( - volatile_test_cig_create_cmpl_evt_.cig_id, kDefaultCigParams); + IsoManager::GetInstance()->CreateCig(volatile_test_cig_create_cmpl_evt_.cig_id, + kDefaultCigParams); bluetooth::hci::iso_manager::cis_establish_params params; for (auto& handle : volatile_test_cig_create_cmpl_evt_.conn_handles) { @@ -1034,22 +931,18 @@ TEST_F(IsoManagerDeathTest, ConnectSameCisTwice) { } IsoManager::GetInstance()->EstablishCis(params); - ASSERT_EXIT( - IsoManager::GetInstance()->IsoManager::GetInstance()->EstablishCis( - params), - ::testing::KilledBySignal(SIGABRT), "already connected or connecting"); + ASSERT_EXIT(IsoManager::GetInstance()->IsoManager::GetInstance()->EstablishCis(params), + ::testing::KilledBySignal(SIGABRT), "already connected or connecting"); } TEST_F(IsoManagerDeathTest, EstablishCisInvalidResponsePacket) { - IsoManager::GetInstance()->CreateCig( - volatile_test_cig_create_cmpl_evt_.cig_id, kDefaultCigParams); + IsoManager::GetInstance()->CreateCig(volatile_test_cig_create_cmpl_evt_.cig_id, + kDefaultCigParams); ON_CALL(hcic_interface_, CreateCis) - .WillByDefault( - [this](uint8_t /* num_cis */, const EXT_CIS_CREATE_CFG* /* cis_cfg */, - base::OnceCallback /* cb */) { - for (auto& handle : - volatile_test_cig_create_cmpl_evt_.conn_handles) { + .WillByDefault([this](uint8_t /* num_cis */, const EXT_CIS_CREATE_CFG* /* cis_cfg */, + base::OnceCallback /* cb */) { + for (auto& handle : volatile_test_cig_create_cmpl_evt_.conn_handles) { std::vector buf(27); uint8_t* p = buf.data(); UINT8_TO_STREAM(p, HCI_SUCCESS); @@ -1068,8 +961,8 @@ TEST_F(IsoManagerDeathTest, EstablishCisInvalidResponsePacket) { UINT16_TO_STREAM(p, 0x00FA); // Max PDU mtos UINT16_TO_STREAM(p, 0x00FB); // Max PDU stom - IsoManager::GetInstance()->HandleHciEvent(HCI_BLE_CIS_EST_EVT, - buf.data(), buf.size()); + IsoManager::GetInstance()->HandleHciEvent(HCI_BLE_CIS_EST_EVT, buf.data(), + buf.size()); } }); @@ -1078,42 +971,36 @@ TEST_F(IsoManagerDeathTest, EstablishCisInvalidResponsePacket) { params.conn_pairs.push_back({handle, 1}); } - ASSERT_EXIT( - IsoManager::GetInstance()->IsoManager::GetInstance()->EstablishCis( - params), - ::testing::KilledBySignal(SIGABRT), "Invalid packet length"); + ASSERT_EXIT(IsoManager::GetInstance()->IsoManager::GetInstance()->EstablishCis(params), + ::testing::KilledBySignal(SIGABRT), "Invalid packet length"); } TEST_F(IsoManagerTest, EstablishCisInvalidCommandStatus) { - IsoManager::GetInstance()->CreateCig( - volatile_test_cig_create_cmpl_evt_.cig_id, kDefaultCigParams); + IsoManager::GetInstance()->CreateCig(volatile_test_cig_create_cmpl_evt_.cig_id, + kDefaultCigParams); uint16_t invalid_status = 0x0001; ON_CALL(hcic_interface_, CreateCis) - .WillByDefault([invalid_status]( - uint8_t /* num_cis */, - const EXT_CIS_CREATE_CFG* /* cis_cfg */, - base::OnceCallback cb) { - std::move(cb).Run((uint8_t*)&invalid_status, sizeof(invalid_status)); - return 0; - }); - - EXPECT_CALL( - *cig_callbacks_, - OnCisEvent(bluetooth::hci::iso_manager::kIsoEventCisEstablishCmpl, _)) - .Times(kDefaultCigParams.cis_cfgs.size()) - .WillRepeatedly([this, invalid_status](uint8_t /* type */, void* data) { - bluetooth::hci::iso_manager::cis_establish_cmpl_evt* evt = - static_cast( - data); - - ASSERT_EQ(evt->status, invalid_status); - ASSERT_TRUE( - std::find(volatile_test_cig_create_cmpl_evt_.conn_handles.begin(), - volatile_test_cig_create_cmpl_evt_.conn_handles.end(), - evt->cis_conn_hdl) != - volatile_test_cig_create_cmpl_evt_.conn_handles.end()); - }); + .WillByDefault([invalid_status](uint8_t /* num_cis */, + const EXT_CIS_CREATE_CFG* /* cis_cfg */, + base::OnceCallback cb) { + std::move(cb).Run((uint8_t*)&invalid_status, sizeof(invalid_status)); + return 0; + }); + + EXPECT_CALL(*cig_callbacks_, + OnCisEvent(bluetooth::hci::iso_manager::kIsoEventCisEstablishCmpl, _)) + .Times(kDefaultCigParams.cis_cfgs.size()) + .WillRepeatedly([this, invalid_status](uint8_t /* type */, void* data) { + bluetooth::hci::iso_manager::cis_establish_cmpl_evt* evt = + static_cast(data); + + ASSERT_EQ(evt->status, invalid_status); + ASSERT_TRUE(std::find(volatile_test_cig_create_cmpl_evt_.conn_handles.begin(), + volatile_test_cig_create_cmpl_evt_.conn_handles.end(), + evt->cis_conn_hdl) != + volatile_test_cig_create_cmpl_evt_.conn_handles.end()); + }); // Establish all CISes bluetooth::hci::iso_manager::cis_establish_params params; @@ -1129,12 +1016,10 @@ TEST_F(IsoManagerTest, EstablishCisInvalidStatus) { uint8_t invalid_status = 0x01; ON_CALL(hcic_interface_, CreateCis) - .WillByDefault( - [this, invalid_status]( - uint8_t /* num_cis */, const EXT_CIS_CREATE_CFG* /* cis_cfg */, - base::OnceCallback /* cb */) { - for (auto& handle : - volatile_test_cig_create_cmpl_evt_.conn_handles) { + .WillByDefault([this, invalid_status]( + uint8_t /* num_cis */, const EXT_CIS_CREATE_CFG* /* cis_cfg */, + base::OnceCallback /* cb */) { + for (auto& handle : volatile_test_cig_create_cmpl_evt_.conn_handles) { std::vector buf(28); uint8_t* p = buf.data(); UINT8_TO_STREAM(p, invalid_status); @@ -1154,29 +1039,25 @@ TEST_F(IsoManagerTest, EstablishCisInvalidStatus) { UINT16_TO_STREAM(p, 0x00FB); // Max PDU stom UINT16_TO_STREAM(p, 0x0C60); // ISO interval - IsoManager::GetInstance()->HandleHciEvent(HCI_BLE_CIS_EST_EVT, - buf.data(), buf.size()); + IsoManager::GetInstance()->HandleHciEvent(HCI_BLE_CIS_EST_EVT, buf.data(), + buf.size()); } }); - EXPECT_CALL( - *cig_callbacks_, - OnCisEvent(bluetooth::hci::iso_manager::kIsoEventCisEstablishCmpl, _)) - .Times(kDefaultCigParams.cis_cfgs.size()) - .WillRepeatedly([this, invalid_status, cig_id](uint8_t /* type */, - void* data) { - bluetooth::hci::iso_manager::cis_establish_cmpl_evt* evt = - static_cast( - data); - - ASSERT_EQ(evt->status, invalid_status); - ASSERT_EQ(evt->cig_id, cig_id); - ASSERT_TRUE( - std::find(volatile_test_cig_create_cmpl_evt_.conn_handles.begin(), - volatile_test_cig_create_cmpl_evt_.conn_handles.end(), - evt->cis_conn_hdl) != - volatile_test_cig_create_cmpl_evt_.conn_handles.end()); - }); + EXPECT_CALL(*cig_callbacks_, + OnCisEvent(bluetooth::hci::iso_manager::kIsoEventCisEstablishCmpl, _)) + .Times(kDefaultCigParams.cis_cfgs.size()) + .WillRepeatedly([this, invalid_status, cig_id](uint8_t /* type */, void* data) { + bluetooth::hci::iso_manager::cis_establish_cmpl_evt* evt = + static_cast(data); + + ASSERT_EQ(evt->status, invalid_status); + ASSERT_EQ(evt->cig_id, cig_id); + ASSERT_TRUE(std::find(volatile_test_cig_create_cmpl_evt_.conn_handles.begin(), + volatile_test_cig_create_cmpl_evt_.conn_handles.end(), + evt->cis_conn_hdl) != + volatile_test_cig_create_cmpl_evt_.conn_handles.end()); + }); // Establish all CISes before setting up their data paths bluetooth::hci::iso_manager::cis_establish_params params; @@ -1187,25 +1068,22 @@ TEST_F(IsoManagerTest, EstablishCisInvalidStatus) { } TEST_F(IsoManagerTest, EstablishCisValid) { - IsoManager::GetInstance()->CreateCig( - volatile_test_cig_create_cmpl_evt_.cig_id, kDefaultCigParams); - - EXPECT_CALL( - *cig_callbacks_, - OnCisEvent(bluetooth::hci::iso_manager::kIsoEventCisEstablishCmpl, _)) - .Times(kDefaultCigParams.cis_cfgs.size()) - .WillRepeatedly([this](uint8_t /* type */, void* data) { - bluetooth::hci::iso_manager::cis_establish_cmpl_evt* evt = - static_cast( - data); - - ASSERT_EQ(evt->status, HCI_SUCCESS); - ASSERT_TRUE( - std::find(volatile_test_cig_create_cmpl_evt_.conn_handles.begin(), - volatile_test_cig_create_cmpl_evt_.conn_handles.end(), - evt->cis_conn_hdl) != - volatile_test_cig_create_cmpl_evt_.conn_handles.end()); - }); + IsoManager::GetInstance()->CreateCig(volatile_test_cig_create_cmpl_evt_.cig_id, + kDefaultCigParams); + + EXPECT_CALL(*cig_callbacks_, + OnCisEvent(bluetooth::hci::iso_manager::kIsoEventCisEstablishCmpl, _)) + .Times(kDefaultCigParams.cis_cfgs.size()) + .WillRepeatedly([this](uint8_t /* type */, void* data) { + bluetooth::hci::iso_manager::cis_establish_cmpl_evt* evt = + static_cast(data); + + ASSERT_EQ(evt->status, HCI_SUCCESS); + ASSERT_TRUE(std::find(volatile_test_cig_create_cmpl_evt_.conn_handles.begin(), + volatile_test_cig_create_cmpl_evt_.conn_handles.end(), + evt->cis_conn_hdl) != + volatile_test_cig_create_cmpl_evt_.conn_handles.end()); + }); // Establish all CISes before setting up their data paths bluetooth::hci::iso_manager::cis_establish_params params; @@ -1216,20 +1094,20 @@ TEST_F(IsoManagerTest, EstablishCisValid) { } TEST_F(IsoManagerTest, EstablishCisLateArrivingCallback) { - IsoManager::GetInstance()->CreateCig( - volatile_test_cig_create_cmpl_evt_.cig_id, kDefaultCigParams); + IsoManager::GetInstance()->CreateCig(volatile_test_cig_create_cmpl_evt_.cig_id, + kDefaultCigParams); // Catch the callback base::OnceCallback iso_cb; EXT_CIS_CREATE_CFG cis_create_cfg; uint8_t cis_num = 0; ON_CALL(hcic_interface_, CreateCis) - .WillByDefault([&](uint8_t num_cis, const EXT_CIS_CREATE_CFG* cis_cfg, - base::OnceCallback cb) { - cis_create_cfg = *cis_cfg; - cis_num = num_cis; - iso_cb = std::move(cb); - }); + .WillByDefault([&](uint8_t num_cis, const EXT_CIS_CREATE_CFG* cis_cfg, + base::OnceCallback cb) { + cis_create_cfg = *cis_cfg; + cis_num = num_cis; + iso_cb = std::move(cb); + }); // Establish all CISes before setting up their data paths bluetooth::hci::iso_manager::cis_establish_params params; @@ -1242,10 +1120,9 @@ TEST_F(IsoManagerTest, EstablishCisLateArrivingCallback) { IsoManager::GetInstance()->Stop(); // Call the callback and expect no call - EXPECT_CALL( - *cig_callbacks_, - OnCisEvent(bluetooth::hci::iso_manager::kIsoEventCisEstablishCmpl, _)) - .Times(0); + EXPECT_CALL(*cig_callbacks_, + OnCisEvent(bluetooth::hci::iso_manager::kIsoEventCisEstablishCmpl, _)) + .Times(0); ASSERT_FALSE(iso_cb.is_null()); // Command complete with error will trigger the callback without @@ -1257,8 +1134,8 @@ TEST_F(IsoManagerTest, EstablishCisLateArrivingCallback) { } TEST_F(IsoManagerTest, ReconnectCisValid) { - IsoManager::GetInstance()->CreateCig( - volatile_test_cig_create_cmpl_evt_.cig_id, kDefaultCigParams); + IsoManager::GetInstance()->CreateCig(volatile_test_cig_create_cmpl_evt_.cig_id, + kDefaultCigParams); // Establish all CISes before setting up their data paths bluetooth::hci::iso_manager::cis_establish_params params; @@ -1272,28 +1149,25 @@ TEST_F(IsoManagerTest, ReconnectCisValid) { IsoManager::GetInstance()->HandleDisconnect(handle, 0x16); } - EXPECT_CALL( - *cig_callbacks_, - OnCisEvent(bluetooth::hci::iso_manager::kIsoEventCisEstablishCmpl, _)) - .Times(kDefaultCigParams.cis_cfgs.size()) - .WillRepeatedly([this](uint8_t /* type */, void* data) { - bluetooth::hci::iso_manager::cis_establish_cmpl_evt* evt = - static_cast( - data); - - ASSERT_EQ(evt->status, HCI_SUCCESS); - ASSERT_TRUE( - std::find(volatile_test_cig_create_cmpl_evt_.conn_handles.begin(), - volatile_test_cig_create_cmpl_evt_.conn_handles.end(), - evt->cis_conn_hdl) != - volatile_test_cig_create_cmpl_evt_.conn_handles.end()); - }); + EXPECT_CALL(*cig_callbacks_, + OnCisEvent(bluetooth::hci::iso_manager::kIsoEventCisEstablishCmpl, _)) + .Times(kDefaultCigParams.cis_cfgs.size()) + .WillRepeatedly([this](uint8_t /* type */, void* data) { + bluetooth::hci::iso_manager::cis_establish_cmpl_evt* evt = + static_cast(data); + + ASSERT_EQ(evt->status, HCI_SUCCESS); + ASSERT_TRUE(std::find(volatile_test_cig_create_cmpl_evt_.conn_handles.begin(), + volatile_test_cig_create_cmpl_evt_.conn_handles.end(), + evt->cis_conn_hdl) != + volatile_test_cig_create_cmpl_evt_.conn_handles.end()); + }); IsoManager::GetInstance()->EstablishCis(params); } TEST_F(IsoManagerTest, DisconnectCisHciCall) { - IsoManager::GetInstance()->CreateCig( - volatile_test_cig_create_cmpl_evt_.cig_id, kDefaultCigParams); + IsoManager::GetInstance()->CreateCig(volatile_test_cig_create_cmpl_evt_.cig_id, + kDefaultCigParams); // Establish all CISes before setting up their data paths bluetooth::hci::iso_manager::cis_establish_params params; @@ -1303,26 +1177,21 @@ TEST_F(IsoManagerTest, DisconnectCisHciCall) { IsoManager::GetInstance()->EstablishCis(params); for (auto& handle : volatile_test_cig_create_cmpl_evt_.conn_handles) { - EXPECT_CALL(hcic_interface_, Disconnect(handle, 0x16)) - .Times(1) - .RetiresOnSaturation(); - IsoManager::GetInstance()->IsoManager::GetInstance()->DisconnectCis(handle, - 0x16); + EXPECT_CALL(hcic_interface_, Disconnect(handle, 0x16)).Times(1).RetiresOnSaturation(); + IsoManager::GetInstance()->IsoManager::GetInstance()->DisconnectCis(handle, 0x16); } } TEST_F(IsoManagerDeathTest, DisconnectCisWithNoSuchCis) { for (auto& handle : volatile_test_cig_create_cmpl_evt_.conn_handles) { - ASSERT_EXIT( - IsoManager::GetInstance()->IsoManager::GetInstance()->DisconnectCis( - handle, 0x16), - ::testing::KilledBySignal(SIGABRT), "No such cis"); + ASSERT_EXIT(IsoManager::GetInstance()->IsoManager::GetInstance()->DisconnectCis(handle, 0x16), + ::testing::KilledBySignal(SIGABRT), "No such cis"); } } TEST_F(IsoManagerDeathTest, DisconnectSameCisTwice) { - IsoManager::GetInstance()->CreateCig( - volatile_test_cig_create_cmpl_evt_.cig_id, kDefaultCigParams); + IsoManager::GetInstance()->CreateCig(volatile_test_cig_create_cmpl_evt_.cig_id, + kDefaultCigParams); // Establish all CISes before setting up their data paths bluetooth::hci::iso_manager::cis_establish_params params; @@ -1332,21 +1201,18 @@ TEST_F(IsoManagerDeathTest, DisconnectSameCisTwice) { IsoManager::GetInstance()->EstablishCis(params); for (auto& handle : volatile_test_cig_create_cmpl_evt_.conn_handles) { - IsoManager::GetInstance()->IsoManager::GetInstance()->DisconnectCis(handle, - 0x16); + IsoManager::GetInstance()->IsoManager::GetInstance()->DisconnectCis(handle, 0x16); } for (auto& handle : volatile_test_cig_create_cmpl_evt_.conn_handles) { - ASSERT_EXIT( - IsoManager::GetInstance()->IsoManager::GetInstance()->DisconnectCis( - handle, 0x16), - ::testing::KilledBySignal(SIGABRT), "Not connected"); + ASSERT_EXIT(IsoManager::GetInstance()->IsoManager::GetInstance()->DisconnectCis(handle, 0x16), + ::testing::KilledBySignal(SIGABRT), "Not connected"); } } TEST_F(IsoManagerTest, DisconnectCisValid) { - IsoManager::GetInstance()->CreateCig( - volatile_test_cig_create_cmpl_evt_.cig_id, kDefaultCigParams); + IsoManager::GetInstance()->CreateCig(volatile_test_cig_create_cmpl_evt_.cig_id, + kDefaultCigParams); // Establish all CISes before setting up their data paths bluetooth::hci::iso_manager::cis_establish_params params; @@ -1358,27 +1224,22 @@ TEST_F(IsoManagerTest, DisconnectCisValid) { uint8_t disconnect_reason = 0x16; for (auto& handle : volatile_test_cig_create_cmpl_evt_.conn_handles) { EXPECT_CALL(*cig_callbacks_, OnCisEvent) - .WillOnce([this, handle, disconnect_reason](uint8_t event_code, - void* data) { - ASSERT_EQ(event_code, - bluetooth::hci::iso_manager::kIsoEventCisDisconnected); - auto* event = - static_cast( - data); - ASSERT_EQ(event->reason, disconnect_reason); - ASSERT_EQ(event->cig_id, volatile_test_cig_create_cmpl_evt_.cig_id); - ASSERT_EQ(event->cis_conn_hdl, handle); - }) - .RetiresOnSaturation(); - IsoManager::GetInstance()->IsoManager::GetInstance()->DisconnectCis( - handle, disconnect_reason); + .WillOnce([this, handle, disconnect_reason](uint8_t event_code, void* data) { + ASSERT_EQ(event_code, bluetooth::hci::iso_manager::kIsoEventCisDisconnected); + auto* event = static_cast(data); + ASSERT_EQ(event->reason, disconnect_reason); + ASSERT_EQ(event->cig_id, volatile_test_cig_create_cmpl_evt_.cig_id); + ASSERT_EQ(event->cis_conn_hdl, handle); + }) + .RetiresOnSaturation(); + IsoManager::GetInstance()->IsoManager::GetInstance()->DisconnectCis(handle, disconnect_reason); } } // Check if we properly ignore not ISO related disconnect events TEST_F(IsoManagerDeathTest, DisconnectCisInvalidResponse) { - IsoManager::GetInstance()->CreateCig( - volatile_test_cig_create_cmpl_evt_.cig_id, kDefaultCigParams); + IsoManager::GetInstance()->CreateCig(volatile_test_cig_create_cmpl_evt_.cig_id, + kDefaultCigParams); bluetooth::hci::iso_manager::cis_establish_params params; for (auto& handle : volatile_test_cig_create_cmpl_evt_.conn_handles) { @@ -1387,29 +1248,24 @@ TEST_F(IsoManagerDeathTest, DisconnectCisInvalidResponse) { IsoManager::GetInstance()->EstablishCis(params); // Make the HCI layer send invalid handles in disconnect event - ON_CALL(hcic_interface_, Disconnect) - .WillByDefault([](uint16_t handle, uint8_t reason) { - IsoManager::GetInstance()->HandleDisconnect(handle + 1, reason); - }); + ON_CALL(hcic_interface_, Disconnect).WillByDefault([](uint16_t handle, uint8_t reason) { + IsoManager::GetInstance()->HandleDisconnect(handle + 1, reason); + }); // We don't expect any calls as these are not ISO handles - ON_CALL(*cig_callbacks_, - OnCisEvent(bluetooth::hci::iso_manager::kIsoEventCisDisconnected, _)) - .WillByDefault( - [](uint8_t /* event_code */, void* /* data */) { FAIL(); }); + ON_CALL(*cig_callbacks_, OnCisEvent(bluetooth::hci::iso_manager::kIsoEventCisDisconnected, _)) + .WillByDefault([](uint8_t /* event_code */, void* /* data */) { FAIL(); }); for (auto& handle : volatile_test_cig_create_cmpl_evt_.conn_handles) { - IsoManager::GetInstance()->IsoManager::GetInstance()->DisconnectCis(handle, - 0x16); + IsoManager::GetInstance()->IsoManager::GetInstance()->DisconnectCis(handle, 0x16); } } TEST_F(IsoManagerTest, CreateBigHciCall) { for (uint8_t i = 220; i != 60; ++i) { - EXPECT_CALL(hcic_interface_, - CreateBig(i, iso_matchers::Eq(kDefaultBigParams))) - .Times(1) - .RetiresOnSaturation(); + EXPECT_CALL(hcic_interface_, CreateBig(i, iso_matchers::Eq(kDefaultBigParams))) + .Times(1) + .RetiresOnSaturation(); IsoManager::GetInstance()->CreateBig(i, kDefaultBigParams); } } @@ -1417,14 +1273,11 @@ TEST_F(IsoManagerTest, CreateBigHciCall) { TEST_F(IsoManagerTest, CreateBigValid) { bluetooth::hci::iso_manager::big_create_cmpl_evt evt; evt.status = 0x01; - EXPECT_CALL( - *big_callbacks_, - OnBigEvent(bluetooth::hci::iso_manager::kIsoEventBigOnCreateCmpl, _)) - .WillOnce([&evt](uint8_t /* type */, void* data) { - evt = *static_cast( - data); - return 0; - }); + EXPECT_CALL(*big_callbacks_, OnBigEvent(bluetooth::hci::iso_manager::kIsoEventBigOnCreateCmpl, _)) + .WillOnce([&evt](uint8_t /* type */, void* data) { + evt = *static_cast(data); + return 0; + }); IsoManager::GetInstance()->CreateBig(0x01, kDefaultBigParams); ASSERT_EQ(evt.status, HCI_SUCCESS); @@ -1432,28 +1285,27 @@ TEST_F(IsoManagerTest, CreateBigValid) { TEST_F(IsoManagerDeathTest, CreateBigInvalidResponsePacket) { ON_CALL(hcic_interface_, CreateBig) - .WillByDefault( - [](auto big_handle, - bluetooth::hci::iso_manager::big_create_params big_params) { - std::vector buf(18); - uint8_t* p = buf.data(); - UINT8_TO_STREAM(p, 0x00); - UINT8_TO_STREAM(p, big_handle); - - UINT24_TO_STREAM(p, 0x0080de); // big_sync_delay - UINT24_TO_STREAM(p, 0x00cefe); // transport_latency_big - UINT8_TO_STREAM(p, big_params.phy); // phy - UINT8_TO_STREAM(p, 4); // nse - UINT8_TO_STREAM(p, 1); // bn - UINT8_TO_STREAM(p, 0); // pto - UINT8_TO_STREAM(p, 4); // irc - UINT16_TO_STREAM(p, 108); // max_pdu - UINT16_TO_STREAM(p, 6); // iso_interval - UINT8_TO_STREAM(p, 0); // num BISes - - IsoManager::GetInstance()->HandleHciEvent( - HCI_BLE_CREATE_BIG_CPL_EVT, buf.data(), buf.size()); - }); + .WillByDefault( + [](auto big_handle, bluetooth::hci::iso_manager::big_create_params big_params) { + std::vector buf(18); + uint8_t* p = buf.data(); + UINT8_TO_STREAM(p, 0x00); + UINT8_TO_STREAM(p, big_handle); + + UINT24_TO_STREAM(p, 0x0080de); // big_sync_delay + UINT24_TO_STREAM(p, 0x00cefe); // transport_latency_big + UINT8_TO_STREAM(p, big_params.phy); // phy + UINT8_TO_STREAM(p, 4); // nse + UINT8_TO_STREAM(p, 1); // bn + UINT8_TO_STREAM(p, 0); // pto + UINT8_TO_STREAM(p, 4); // irc + UINT16_TO_STREAM(p, 108); // max_pdu + UINT16_TO_STREAM(p, 6); // iso_interval + UINT8_TO_STREAM(p, 0); // num BISes + + IsoManager::GetInstance()->HandleHciEvent(HCI_BLE_CREATE_BIG_CPL_EVT, + buf.data(), buf.size()); + }); ASSERT_EXIT(IsoManager::GetInstance()->CreateBig(0x01, kDefaultBigParams), ::testing::KilledBySignal(SIGABRT), "Bis count is 0"); @@ -1461,28 +1313,27 @@ TEST_F(IsoManagerDeathTest, CreateBigInvalidResponsePacket) { TEST_F(IsoManagerDeathTest, CreateBigInvalidResponsePacket2) { ON_CALL(hcic_interface_, CreateBig) - .WillByDefault( - [](auto big_handle, - bluetooth::hci::iso_manager::big_create_params big_params) { - std::vector buf(18); - uint8_t* p = buf.data(); - UINT8_TO_STREAM(p, 0x00); - UINT8_TO_STREAM(p, big_handle); - - UINT24_TO_STREAM(p, 0x0080de); // big_sync_delay - UINT24_TO_STREAM(p, 0x00cefe); // transport_latency_big - UINT8_TO_STREAM(p, big_params.phy); // phy - UINT8_TO_STREAM(p, 4); // nse - UINT8_TO_STREAM(p, 1); // bn - UINT8_TO_STREAM(p, 0); // pto - UINT8_TO_STREAM(p, 4); // irc - UINT16_TO_STREAM(p, 108); // max_pdu - UINT16_TO_STREAM(p, 6); // iso_interval - UINT8_TO_STREAM(p, big_params.num_bis); - - IsoManager::GetInstance()->HandleHciEvent( - HCI_BLE_CREATE_BIG_CPL_EVT, buf.data(), buf.size()); - }); + .WillByDefault( + [](auto big_handle, bluetooth::hci::iso_manager::big_create_params big_params) { + std::vector buf(18); + uint8_t* p = buf.data(); + UINT8_TO_STREAM(p, 0x00); + UINT8_TO_STREAM(p, big_handle); + + UINT24_TO_STREAM(p, 0x0080de); // big_sync_delay + UINT24_TO_STREAM(p, 0x00cefe); // transport_latency_big + UINT8_TO_STREAM(p, big_params.phy); // phy + UINT8_TO_STREAM(p, 4); // nse + UINT8_TO_STREAM(p, 1); // bn + UINT8_TO_STREAM(p, 0); // pto + UINT8_TO_STREAM(p, 4); // irc + UINT16_TO_STREAM(p, 108); // max_pdu + UINT16_TO_STREAM(p, 6); // iso_interval + UINT8_TO_STREAM(p, big_params.num_bis); + + IsoManager::GetInstance()->HandleHciEvent(HCI_BLE_CREATE_BIG_CPL_EVT, + buf.data(), buf.size()); + }); ASSERT_EXIT(IsoManager::GetInstance()->CreateBig(0x01, kDefaultBigParams), ::testing::KilledBySignal(SIGABRT), "Invalid packet length"); @@ -1491,44 +1342,39 @@ TEST_F(IsoManagerDeathTest, CreateBigInvalidResponsePacket2) { TEST_F(IsoManagerTest, CreateBigInvalidStatus) { bluetooth::hci::iso_manager::big_create_cmpl_evt evt; evt.status = 0x00; - EXPECT_CALL( - *big_callbacks_, - OnBigEvent(bluetooth::hci::iso_manager::kIsoEventBigOnCreateCmpl, _)) - .WillOnce([&evt](uint8_t /* type */, void* data) { - evt = *static_cast( - data); - return 0; - }); + EXPECT_CALL(*big_callbacks_, OnBigEvent(bluetooth::hci::iso_manager::kIsoEventBigOnCreateCmpl, _)) + .WillOnce([&evt](uint8_t /* type */, void* data) { + evt = *static_cast(data); + return 0; + }); ON_CALL(hcic_interface_, CreateBig) - .WillByDefault( - [](auto big_handle, - bluetooth::hci::iso_manager::big_create_params big_params) { - std::vector buf(big_params.num_bis * sizeof(uint16_t) + - 18); - uint8_t* p = buf.data(); - UINT8_TO_STREAM(p, 0x01); - UINT8_TO_STREAM(p, big_handle); - - UINT24_TO_STREAM(p, 0x0080de); // big_sync_delay - UINT24_TO_STREAM(p, 0x00cefe); // transport_latency_big - UINT8_TO_STREAM(p, big_params.phy); // phy - UINT8_TO_STREAM(p, 4); // nse - UINT8_TO_STREAM(p, 1); // bn - UINT8_TO_STREAM(p, 0); // pto - UINT8_TO_STREAM(p, 4); // irc - UINT16_TO_STREAM(p, 108); // max_pdu - UINT16_TO_STREAM(p, 6); // iso_interval - - UINT8_TO_STREAM(p, big_params.num_bis); - static uint8_t conn_hdl = 0x01; - for (auto i = 0; i < big_params.num_bis; ++i) { - UINT16_TO_STREAM(p, conn_hdl++); - } - - IsoManager::GetInstance()->HandleHciEvent( - HCI_BLE_CREATE_BIG_CPL_EVT, buf.data(), buf.size()); - }); + .WillByDefault( + [](auto big_handle, bluetooth::hci::iso_manager::big_create_params big_params) { + std::vector buf(big_params.num_bis * sizeof(uint16_t) + 18); + uint8_t* p = buf.data(); + UINT8_TO_STREAM(p, 0x01); + UINT8_TO_STREAM(p, big_handle); + + UINT24_TO_STREAM(p, 0x0080de); // big_sync_delay + UINT24_TO_STREAM(p, 0x00cefe); // transport_latency_big + UINT8_TO_STREAM(p, big_params.phy); // phy + UINT8_TO_STREAM(p, 4); // nse + UINT8_TO_STREAM(p, 1); // bn + UINT8_TO_STREAM(p, 0); // pto + UINT8_TO_STREAM(p, 4); // irc + UINT16_TO_STREAM(p, 108); // max_pdu + UINT16_TO_STREAM(p, 6); // iso_interval + + UINT8_TO_STREAM(p, big_params.num_bis); + static uint8_t conn_hdl = 0x01; + for (auto i = 0; i < big_params.num_bis; ++i) { + UINT16_TO_STREAM(p, conn_hdl++); + } + + IsoManager::GetInstance()->HandleHciEvent(HCI_BLE_CREATE_BIG_CPL_EVT, + buf.data(), buf.size()); + }); IsoManager::GetInstance()->CreateBig(0x01, kDefaultBigParams); ASSERT_EQ(evt.status, 0x01); @@ -1539,14 +1385,11 @@ TEST_F(IsoManagerTest, CreateBigInvalidStatus) { TEST_F(IsoManagerDeathTest, CreateSameBigTwice) { bluetooth::hci::iso_manager::big_create_cmpl_evt evt; evt.status = 0x01; - EXPECT_CALL( - *big_callbacks_, - OnBigEvent(bluetooth::hci::iso_manager::kIsoEventBigOnCreateCmpl, _)) - .WillOnce([&evt](uint8_t /* type */, void* data) { - evt = *static_cast( - data); - return 0; - }); + EXPECT_CALL(*big_callbacks_, OnBigEvent(bluetooth::hci::iso_manager::kIsoEventBigOnCreateCmpl, _)) + .WillOnce([&evt](uint8_t /* type */, void* data) { + evt = *static_cast(data); + return 0; + }); IsoManager::GetInstance()->CreateBig(0x01, kDefaultBigParams); ASSERT_EQ(evt.status, HCI_SUCCESS); @@ -1568,9 +1411,8 @@ TEST_F(IsoManagerDeathTest, TerminateSameBigTwice) { const uint8_t reason = 0x16; // Terminated by local host IsoManager::GetInstance()->CreateBig(big_id, kDefaultBigParams); - EXPECT_CALL( - *big_callbacks_, - OnBigEvent(bluetooth::hci::iso_manager::kIsoEventBigOnTerminateCmpl, _)); + EXPECT_CALL(*big_callbacks_, + OnBigEvent(bluetooth::hci::iso_manager::kIsoEventBigOnTerminateCmpl, _)); IsoManager::GetInstance()->TerminateBig(big_id, reason); ASSERT_EXIT(IsoManager::GetInstance()->TerminateBig(big_id, reason), @@ -1581,9 +1423,8 @@ TEST_F(IsoManagerDeathTest, TerminateBigNoSuchBig) { const uint8_t big_id = 0x01; const uint8_t reason = 0x16; // Terminated by local host - EXPECT_CALL( - *big_callbacks_, - OnBigEvent(bluetooth::hci::iso_manager::kIsoEventBigOnCreateCmpl, _)); + EXPECT_CALL(*big_callbacks_, + OnBigEvent(bluetooth::hci::iso_manager::kIsoEventBigOnCreateCmpl, _)); IsoManager::GetInstance()->CreateBig(big_id, kDefaultBigParams); ASSERT_EXIT(IsoManager::GetInstance()->TerminateBig(big_id + 1, reason), @@ -1591,15 +1432,13 @@ TEST_F(IsoManagerDeathTest, TerminateBigNoSuchBig) { } TEST_F(IsoManagerDeathTest, TerminateBigInvalidResponsePacket) { - ON_CALL(hcic_interface_, TerminateBig) - .WillByDefault([](auto /* big_handle */, uint8_t reason) { - std::vector buf(1); - uint8_t* p = buf.data(); - UINT8_TO_STREAM(p, reason); + ON_CALL(hcic_interface_, TerminateBig).WillByDefault([](auto /* big_handle */, uint8_t reason) { + std::vector buf(1); + uint8_t* p = buf.data(); + UINT8_TO_STREAM(p, reason); - IsoManager::GetInstance()->HandleHciEvent(HCI_BLE_TERM_BIG_CPL_EVT, - buf.data(), buf.size()); - }); + IsoManager::GetInstance()->HandleHciEvent(HCI_BLE_TERM_BIG_CPL_EVT, buf.data(), buf.size()); + }); const uint8_t big_id = 0x22; const uint8_t reason = 0x16; // Terminated by local host @@ -1613,15 +1452,13 @@ TEST_F(IsoManagerDeathTest, TerminateBigInvalidResponsePacket2) { const uint8_t big_id = 0x22; const uint8_t reason = 0x16; // Terminated by local host - ON_CALL(hcic_interface_, TerminateBig) - .WillByDefault([](auto /* big_handle */, uint8_t reason) { - std::vector buf(3); - uint8_t* p = buf.data(); - UINT8_TO_STREAM(p, reason); + ON_CALL(hcic_interface_, TerminateBig).WillByDefault([](auto /* big_handle */, uint8_t reason) { + std::vector buf(3); + uint8_t* p = buf.data(); + UINT8_TO_STREAM(p, reason); - IsoManager::GetInstance()->HandleHciEvent(HCI_BLE_TERM_BIG_CPL_EVT, - buf.data(), buf.size()); - }); + IsoManager::GetInstance()->HandleHciEvent(HCI_BLE_TERM_BIG_CPL_EVT, buf.data(), buf.size()); + }); IsoManager::GetInstance()->CreateBig(big_id, kDefaultBigParams); ASSERT_EXIT(IsoManager::GetInstance()->TerminateBig(big_id, reason), @@ -1632,16 +1469,14 @@ TEST_F(IsoManagerTest, TerminateBigInvalidResponseBigId) { const uint8_t big_id = 0x22; const uint8_t reason = 0x16; // Terminated by local host - ON_CALL(hcic_interface_, TerminateBig) - .WillByDefault([](auto big_handle, uint8_t reason) { - std::vector buf(2); - uint8_t* p = buf.data(); - UINT8_TO_STREAM(p, reason); - UINT8_TO_STREAM(p, big_handle + 1); + ON_CALL(hcic_interface_, TerminateBig).WillByDefault([](auto big_handle, uint8_t reason) { + std::vector buf(2); + uint8_t* p = buf.data(); + UINT8_TO_STREAM(p, reason); + UINT8_TO_STREAM(p, big_handle + 1); - IsoManager::GetInstance()->HandleHciEvent(HCI_BLE_TERM_BIG_CPL_EVT, - buf.data(), buf.size()); - }); + IsoManager::GetInstance()->HandleHciEvent(HCI_BLE_TERM_BIG_CPL_EVT, buf.data(), buf.size()); + }); IsoManager::GetInstance()->CreateBig(big_id, kDefaultBigParams); ASSERT_EXIT(IsoManager::GetInstance()->TerminateBig(big_id, reason), @@ -1657,15 +1492,12 @@ TEST_F(IsoManagerTest, TerminateBigValid) { IsoManager::GetInstance()->CreateBig(big_id, kDefaultBigParams); ASSERT_EQ(IsIsoActive, true); - EXPECT_CALL( - *big_callbacks_, - OnBigEvent(bluetooth::hci::iso_manager::kIsoEventBigOnTerminateCmpl, _)) - .WillOnce([&evt](uint8_t /* type */, void* data) { - evt = - *static_cast( - data); - return 0; - }); + EXPECT_CALL(*big_callbacks_, + OnBigEvent(bluetooth::hci::iso_manager::kIsoEventBigOnTerminateCmpl, _)) + .WillOnce([&evt](uint8_t /* type */, void* data) { + evt = *static_cast(data); + return 0; + }); IsoManager::GetInstance()->TerminateBig(big_id, reason); ASSERT_EQ(evt.big_id, big_id); @@ -1674,10 +1506,9 @@ TEST_F(IsoManagerTest, TerminateBigValid) { } TEST_F(IsoManagerTest, SetupIsoDataPathValid) { - IsoManager::GetInstance()->CreateCig( - volatile_test_cig_create_cmpl_evt_.cig_id, kDefaultCigParams); - IsoManager::GetInstance()->CreateBig(volatile_test_big_params_evt_.big_id, - kDefaultBigParams); + IsoManager::GetInstance()->CreateCig(volatile_test_cig_create_cmpl_evt_.cig_id, + kDefaultCigParams); + IsoManager::GetInstance()->CreateBig(volatile_test_big_params_evt_.big_id, kDefaultBigParams); // Establish all CISes before setting up their data paths bluetooth::hci::iso_manager::cis_establish_params params; @@ -1686,43 +1517,37 @@ TEST_F(IsoManagerTest, SetupIsoDataPathValid) { } IsoManager::GetInstance()->EstablishCis(params); - bluetooth::hci::iso_manager::iso_data_path_params path_params = - kDefaultIsoDataPathParams; + bluetooth::hci::iso_manager::iso_data_path_params path_params = kDefaultIsoDataPathParams; // Setup data paths for all CISes - path_params.data_path_dir = - bluetooth::hci::iso_manager::kIsoDataPathDirectionIn; + path_params.data_path_dir = bluetooth::hci::iso_manager::kIsoDataPathDirectionIn; for (auto& handle : volatile_test_cig_create_cmpl_evt_.conn_handles) { EXPECT_CALL(*cig_callbacks_, - OnSetupIsoDataPath(HCI_SUCCESS, handle, - volatile_test_cig_create_cmpl_evt_.cig_id)) - .Times(1) - .RetiresOnSaturation(); + OnSetupIsoDataPath(HCI_SUCCESS, handle, volatile_test_cig_create_cmpl_evt_.cig_id)) + .Times(1) + .RetiresOnSaturation(); - path_params.data_path_dir = - (bluetooth::hci::iso_manager::kIsoDataPathDirectionIn + handle) % 2; + path_params.data_path_dir = (bluetooth::hci::iso_manager::kIsoDataPathDirectionIn + handle) % 2; IsoManager::GetInstance()->SetupIsoDataPath(handle, path_params); } // Setup data paths for all BISes - path_params.data_path_dir = - bluetooth::hci::iso_manager::kIsoDataPathDirectionOut; + path_params.data_path_dir = bluetooth::hci::iso_manager::kIsoDataPathDirectionOut; for (auto& handle : volatile_test_big_params_evt_.conn_handles) { std::cerr << "setting up BIS data path on conn_hdl: " << int{handle}; EXPECT_CALL(*big_callbacks_, - OnSetupIsoDataPath(HCI_SUCCESS, handle, - volatile_test_big_params_evt_.big_id)) - .Times(1) - .RetiresOnSaturation(); + OnSetupIsoDataPath(HCI_SUCCESS, handle, volatile_test_big_params_evt_.big_id)) + .Times(1) + .RetiresOnSaturation(); IsoManager::GetInstance()->SetupIsoDataPath(handle, path_params); } } TEST_F(IsoManagerTest, SetupIsoDataPathTwice) { - IsoManager::GetInstance()->CreateCig( - volatile_test_cig_create_cmpl_evt_.cig_id, kDefaultCigParams); + IsoManager::GetInstance()->CreateCig(volatile_test_cig_create_cmpl_evt_.cig_id, + kDefaultCigParams); // Establish CISes bluetooth::hci::iso_manager::cis_establish_params params; @@ -1732,16 +1557,14 @@ TEST_F(IsoManagerTest, SetupIsoDataPathTwice) { IsoManager::GetInstance()->EstablishCis(params); // Setup data paths for all CISes twice - bluetooth::hci::iso_manager::iso_data_path_params path_params = - kDefaultIsoDataPathParams; + bluetooth::hci::iso_manager::iso_data_path_params path_params = kDefaultIsoDataPathParams; for (auto& handle : volatile_test_cig_create_cmpl_evt_.conn_handles) { IsoManager::GetInstance()->SetupIsoDataPath(handle, path_params); // Should be possible to reconfigure IsoManager::GetInstance()->SetupIsoDataPath(handle, path_params); } - IsoManager::GetInstance()->CreateBig(volatile_test_big_params_evt_.big_id, - kDefaultBigParams); + IsoManager::GetInstance()->CreateBig(volatile_test_big_params_evt_.big_id, kDefaultBigParams); // Setup data paths for all BISes twice for (auto& handle : volatile_test_big_params_evt_.conn_handles) { IsoManager::GetInstance()->SetupIsoDataPath(handle, path_params); @@ -1751,10 +1574,9 @@ TEST_F(IsoManagerTest, SetupIsoDataPathTwice) { } TEST_F(IsoManagerTest, SetupIsoDataPathInvalidStatus) { - IsoManager::GetInstance()->CreateCig( - volatile_test_cig_create_cmpl_evt_.cig_id, kDefaultCigParams); - IsoManager::GetInstance()->CreateBig(volatile_test_big_params_evt_.big_id, - kDefaultBigParams); + IsoManager::GetInstance()->CreateCig(volatile_test_cig_create_cmpl_evt_.cig_id, + kDefaultCigParams); + IsoManager::GetInstance()->CreateBig(volatile_test_big_params_evt_.big_id, kDefaultBigParams); // Establish all CISes before setting up their data paths bluetooth::hci::iso_manager::cis_establish_params params; @@ -1763,74 +1585,66 @@ TEST_F(IsoManagerTest, SetupIsoDataPathInvalidStatus) { } IsoManager::GetInstance()->EstablishCis(params); - bluetooth::hci::iso_manager::iso_data_path_params path_params = - kDefaultIsoDataPathParams; + bluetooth::hci::iso_manager::iso_data_path_params path_params = kDefaultIsoDataPathParams; uint8_t setup_datapath_rsp_status = HCI_SUCCESS; ON_CALL(hcic_interface_, SetupIsoDataPath) - .WillByDefault([&setup_datapath_rsp_status]( - uint16_t iso_handle, uint8_t, uint8_t, uint8_t, - uint16_t, uint16_t, uint32_t, std::vector, - base::OnceCallback cb) { - std::vector buf(3); - uint8_t* p = buf.data(); - UINT8_TO_STREAM(p, setup_datapath_rsp_status); - UINT16_TO_STREAM(p, iso_handle); - - std::move(cb).Run(buf.data(), buf.size()); - }); + .WillByDefault( + [&setup_datapath_rsp_status](uint16_t iso_handle, uint8_t, uint8_t, uint8_t, + uint16_t, uint16_t, uint32_t, std::vector, + base::OnceCallback cb) { + std::vector buf(3); + uint8_t* p = buf.data(); + UINT8_TO_STREAM(p, setup_datapath_rsp_status); + UINT16_TO_STREAM(p, iso_handle); + + std::move(cb).Run(buf.data(), buf.size()); + }); // Try to setup data paths for all CISes - path_params.data_path_dir = - bluetooth::hci::iso_manager::kIsoDataPathDirectionIn; + path_params.data_path_dir = bluetooth::hci::iso_manager::kIsoDataPathDirectionIn; for (auto& handle : volatile_test_cig_create_cmpl_evt_.conn_handles) { // Mock the response with status != HCI_SUCCESS EXPECT_CALL(*cig_callbacks_, - OnSetupIsoDataPath(0x11, handle, - volatile_test_cig_create_cmpl_evt_.cig_id)) - .Times(1) - .RetiresOnSaturation(); + OnSetupIsoDataPath(0x11, handle, volatile_test_cig_create_cmpl_evt_.cig_id)) + .Times(1) + .RetiresOnSaturation(); setup_datapath_rsp_status = 0x11; IsoManager::GetInstance()->SetupIsoDataPath(handle, path_params); // It should be possible to retry on the same handle after the first // failure EXPECT_CALL(*cig_callbacks_, - OnSetupIsoDataPath(HCI_SUCCESS, handle, - volatile_test_cig_create_cmpl_evt_.cig_id)) - .Times(1) - .RetiresOnSaturation(); + OnSetupIsoDataPath(HCI_SUCCESS, handle, volatile_test_cig_create_cmpl_evt_.cig_id)) + .Times(1) + .RetiresOnSaturation(); setup_datapath_rsp_status = HCI_SUCCESS; IsoManager::GetInstance()->SetupIsoDataPath(handle, path_params); } // Try to setup data paths for all BISes - path_params.data_path_dir = - bluetooth::hci::iso_manager::kIsoDataPathDirectionOut; + path_params.data_path_dir = bluetooth::hci::iso_manager::kIsoDataPathDirectionOut; for (auto& handle : volatile_test_big_params_evt_.conn_handles) { - EXPECT_CALL( - *big_callbacks_, - OnSetupIsoDataPath(0x11, handle, volatile_test_big_params_evt_.big_id)) - .Times(1) - .RetiresOnSaturation(); + EXPECT_CALL(*big_callbacks_, + OnSetupIsoDataPath(0x11, handle, volatile_test_big_params_evt_.big_id)) + .Times(1) + .RetiresOnSaturation(); setup_datapath_rsp_status = 0x11; IsoManager::GetInstance()->SetupIsoDataPath(handle, path_params); EXPECT_CALL(*big_callbacks_, - OnSetupIsoDataPath(HCI_SUCCESS, handle, - volatile_test_big_params_evt_.big_id)) - .Times(1) - .RetiresOnSaturation(); + OnSetupIsoDataPath(HCI_SUCCESS, handle, volatile_test_big_params_evt_.big_id)) + .Times(1) + .RetiresOnSaturation(); setup_datapath_rsp_status = HCI_SUCCESS; IsoManager::GetInstance()->SetupIsoDataPath(handle, path_params); } } TEST_F(IsoManagerTest, SetupIsoDataPathLateArrivingCallback) { - IsoManager::GetInstance()->CreateCig( - volatile_test_cig_create_cmpl_evt_.cig_id, kDefaultCigParams); - IsoManager::GetInstance()->CreateBig(volatile_test_big_params_evt_.big_id, - kDefaultBigParams); + IsoManager::GetInstance()->CreateCig(volatile_test_cig_create_cmpl_evt_.cig_id, + kDefaultCigParams); + IsoManager::GetInstance()->CreateBig(volatile_test_big_params_evt_.big_id, kDefaultBigParams); // Establish all CISes before setting up their data paths bluetooth::hci::iso_manager::cis_establish_params params; @@ -1839,25 +1653,21 @@ TEST_F(IsoManagerTest, SetupIsoDataPathLateArrivingCallback) { } IsoManager::GetInstance()->EstablishCis(params); - bluetooth::hci::iso_manager::iso_data_path_params path_params = - kDefaultIsoDataPathParams; + bluetooth::hci::iso_manager::iso_data_path_params path_params = kDefaultIsoDataPathParams; // Catch the callback base::OnceCallback iso_cb; ON_CALL(hcic_interface_, SetupIsoDataPath) - .WillByDefault( - [&iso_cb](uint16_t /* iso_handle */, uint8_t /* data_path_dir */, - uint8_t /* data_path_id */, uint8_t /* codec_id_format */, - uint16_t /* codec_id_company */, - uint16_t /* codec_id_vendor */, - uint32_t /* controller_delay */, - std::vector /* codec_conf */, - base::OnceCallback cb) { + .WillByDefault([&iso_cb](uint16_t /* iso_handle */, uint8_t /* data_path_dir */, + uint8_t /* data_path_id */, uint8_t /* codec_id_format */, + uint16_t /* codec_id_company */, uint16_t /* codec_id_vendor */, + uint32_t /* controller_delay */, + std::vector /* codec_conf */, + base::OnceCallback cb) { iso_cb = std::move(cb); }); // Setup and remove data paths for all CISes - path_params.data_path_dir = - bluetooth::hci::iso_manager::kRemoveIsoDataPathDirectionInput; + path_params.data_path_dir = bluetooth::hci::iso_manager::kRemoveIsoDataPathDirectionInput; auto& handle = volatile_test_cig_create_cmpl_evt_.conn_handles[0]; IsoManager::GetInstance()->SetupIsoDataPath(handle, path_params); @@ -1876,10 +1686,9 @@ TEST_F(IsoManagerTest, SetupIsoDataPathLateArrivingCallback) { } TEST_F(IsoManagerTest, RemoveIsoDataPathValid) { - IsoManager::GetInstance()->CreateCig( - volatile_test_cig_create_cmpl_evt_.cig_id, kDefaultCigParams); - IsoManager::GetInstance()->CreateBig(volatile_test_big_params_evt_.big_id, - kDefaultBigParams); + IsoManager::GetInstance()->CreateCig(volatile_test_cig_create_cmpl_evt_.cig_id, + kDefaultCigParams); + IsoManager::GetInstance()->CreateBig(volatile_test_big_params_evt_.big_id, kDefaultBigParams); // Establish all CISes before setting up their data paths bluetooth::hci::iso_manager::cis_establish_params params; @@ -1888,94 +1697,76 @@ TEST_F(IsoManagerTest, RemoveIsoDataPathValid) { } IsoManager::GetInstance()->EstablishCis(params); - bluetooth::hci::iso_manager::iso_data_path_params path_params = - kDefaultIsoDataPathParams; + bluetooth::hci::iso_manager::iso_data_path_params path_params = kDefaultIsoDataPathParams; // Setup and remove data paths for all CISes - path_params.data_path_dir = - bluetooth::hci::iso_manager::kRemoveIsoDataPathDirectionInput; + path_params.data_path_dir = bluetooth::hci::iso_manager::kRemoveIsoDataPathDirectionInput; for (auto& handle : volatile_test_cig_create_cmpl_evt_.conn_handles) { IsoManager::GetInstance()->SetupIsoDataPath(handle, path_params); EXPECT_CALL(*cig_callbacks_, - OnRemoveIsoDataPath(HCI_SUCCESS, handle, - volatile_test_cig_create_cmpl_evt_.cig_id)) - .Times(1) - .RetiresOnSaturation(); - IsoManager::GetInstance()->RemoveIsoDataPath(handle, - path_params.data_path_dir); + OnRemoveIsoDataPath(HCI_SUCCESS, handle, volatile_test_cig_create_cmpl_evt_.cig_id)) + .Times(1) + .RetiresOnSaturation(); + IsoManager::GetInstance()->RemoveIsoDataPath(handle, path_params.data_path_dir); } // Setup and remove data paths for all BISes - path_params.data_path_dir = - bluetooth::hci::iso_manager::kIsoDataPathDirectionOut; + path_params.data_path_dir = bluetooth::hci::iso_manager::kIsoDataPathDirectionOut; for (auto& handle : volatile_test_big_params_evt_.conn_handles) { std::cerr << "setting up BIS data path on conn_hdl: " << int{handle}; IsoManager::GetInstance()->SetupIsoDataPath(handle, path_params); EXPECT_CALL(*big_callbacks_, - OnRemoveIsoDataPath(HCI_SUCCESS, handle, - volatile_test_big_params_evt_.big_id)) - .Times(1) - .RetiresOnSaturation(); - IsoManager::GetInstance()->RemoveIsoDataPath(handle, - path_params.data_path_dir); + OnRemoveIsoDataPath(HCI_SUCCESS, handle, volatile_test_big_params_evt_.big_id)) + .Times(1) + .RetiresOnSaturation(); + IsoManager::GetInstance()->RemoveIsoDataPath(handle, path_params.data_path_dir); } } TEST_F(IsoManagerDeathTest, RemoveIsoDataPathNoSuchPath) { // Check on CIS - IsoManager::GetInstance()->CreateCig( - volatile_test_cig_create_cmpl_evt_.cig_id, kDefaultCigParams); + IsoManager::GetInstance()->CreateCig(volatile_test_cig_create_cmpl_evt_.cig_id, + kDefaultCigParams); uint16_t iso_handle = volatile_test_cig_create_cmpl_evt_.conn_handles[0]; - ASSERT_EXIT( - IsoManager::GetInstance()->RemoveIsoDataPath( - iso_handle, bluetooth::hci::iso_manager::kIsoDataPathDirectionOut), - ::testing::KilledBySignal(SIGABRT), "path not set"); + ASSERT_EXIT(IsoManager::GetInstance()->RemoveIsoDataPath( + iso_handle, bluetooth::hci::iso_manager::kIsoDataPathDirectionOut), + ::testing::KilledBySignal(SIGABRT), "path not set"); IsoManager::GetInstance()->EstablishCis({.conn_pairs = {{iso_handle, 1}}}); - ASSERT_EXIT( - IsoManager::GetInstance()->RemoveIsoDataPath( - iso_handle, bluetooth::hci::iso_manager::kIsoDataPathDirectionOut), - ::testing::KilledBySignal(SIGABRT), "path not set"); + ASSERT_EXIT(IsoManager::GetInstance()->RemoveIsoDataPath( + iso_handle, bluetooth::hci::iso_manager::kIsoDataPathDirectionOut), + ::testing::KilledBySignal(SIGABRT), "path not set"); // Check on BIS iso_handle = volatile_test_big_params_evt_.conn_handles[0]; - IsoManager::GetInstance()->CreateBig(volatile_test_big_params_evt_.big_id, - kDefaultBigParams); - ASSERT_EXIT( - IsoManager::GetInstance()->RemoveIsoDataPath( - iso_handle, bluetooth::hci::iso_manager::kIsoDataPathDirectionOut), - ::testing::KilledBySignal(SIGABRT), "path not set"); + IsoManager::GetInstance()->CreateBig(volatile_test_big_params_evt_.big_id, kDefaultBigParams); + ASSERT_EXIT(IsoManager::GetInstance()->RemoveIsoDataPath( + iso_handle, bluetooth::hci::iso_manager::kIsoDataPathDirectionOut), + ::testing::KilledBySignal(SIGABRT), "path not set"); } TEST_F(IsoManagerDeathTest, RemoveIsoDataPathTwice) { // Check on CIS - IsoManager::GetInstance()->CreateCig( - volatile_test_cig_create_cmpl_evt_.cig_id, kDefaultCigParams); + IsoManager::GetInstance()->CreateCig(volatile_test_cig_create_cmpl_evt_.cig_id, + kDefaultCigParams); uint16_t iso_handle = volatile_test_cig_create_cmpl_evt_.conn_handles[0]; IsoManager::GetInstance()->EstablishCis({.conn_pairs = {{iso_handle, 1}}}); - IsoManager::GetInstance()->SetupIsoDataPath(iso_handle, - kDefaultIsoDataPathParams); - IsoManager::GetInstance()->RemoveIsoDataPath( - iso_handle, kDefaultIsoDataPathParams.data_path_dir); - ASSERT_EXIT( - IsoManager::GetInstance()->RemoveIsoDataPath( - iso_handle, bluetooth::hci::iso_manager::kIsoDataPathDirectionOut), - ::testing::KilledBySignal(SIGABRT), "path not set"); + IsoManager::GetInstance()->SetupIsoDataPath(iso_handle, kDefaultIsoDataPathParams); + IsoManager::GetInstance()->RemoveIsoDataPath(iso_handle, kDefaultIsoDataPathParams.data_path_dir); + ASSERT_EXIT(IsoManager::GetInstance()->RemoveIsoDataPath( + iso_handle, bluetooth::hci::iso_manager::kIsoDataPathDirectionOut), + ::testing::KilledBySignal(SIGABRT), "path not set"); // Check on BIS iso_handle = volatile_test_big_params_evt_.conn_handles[0]; - IsoManager::GetInstance()->CreateBig(volatile_test_big_params_evt_.big_id, - kDefaultBigParams); - IsoManager::GetInstance()->SetupIsoDataPath(iso_handle, - kDefaultIsoDataPathParams); - IsoManager::GetInstance()->RemoveIsoDataPath( - iso_handle, kDefaultIsoDataPathParams.data_path_dir); - ASSERT_EXIT( - IsoManager::GetInstance()->RemoveIsoDataPath( - iso_handle, bluetooth::hci::iso_manager::kIsoDataPathDirectionOut), - ::testing::KilledBySignal(SIGABRT), "path not set"); + IsoManager::GetInstance()->CreateBig(volatile_test_big_params_evt_.big_id, kDefaultBigParams); + IsoManager::GetInstance()->SetupIsoDataPath(iso_handle, kDefaultIsoDataPathParams); + IsoManager::GetInstance()->RemoveIsoDataPath(iso_handle, kDefaultIsoDataPathParams.data_path_dir); + ASSERT_EXIT(IsoManager::GetInstance()->RemoveIsoDataPath( + iso_handle, bluetooth::hci::iso_manager::kIsoDataPathDirectionOut), + ::testing::KilledBySignal(SIGABRT), "path not set"); } // Check if HCI status other than HCI_SUCCESS is being propagated to the caller @@ -1983,52 +1774,44 @@ TEST_F(IsoManagerTest, RemoveIsoDataPathInvalidStatus) { // Mock invalid status response uint8_t remove_datapath_rsp_status = 0x12; ON_CALL(hcic_interface_, RemoveIsoDataPath) - .WillByDefault([&remove_datapath_rsp_status]( - uint16_t iso_handle, uint8_t /* data_path_dir */, - base::OnceCallback cb) { - std::vector buf(3); - uint8_t* p = buf.data(); - UINT8_TO_STREAM(p, remove_datapath_rsp_status); - UINT16_TO_STREAM(p, iso_handle); + .WillByDefault( + [&remove_datapath_rsp_status](uint16_t iso_handle, uint8_t /* data_path_dir */, + base::OnceCallback cb) { + std::vector buf(3); + uint8_t* p = buf.data(); + UINT8_TO_STREAM(p, remove_datapath_rsp_status); + UINT16_TO_STREAM(p, iso_handle); - std::move(cb).Run(buf.data(), buf.size()); - }); + std::move(cb).Run(buf.data(), buf.size()); + }); // Check on CIS - IsoManager::GetInstance()->CreateCig( - volatile_test_cig_create_cmpl_evt_.cig_id, kDefaultCigParams); + IsoManager::GetInstance()->CreateCig(volatile_test_cig_create_cmpl_evt_.cig_id, + kDefaultCigParams); uint16_t iso_handle = volatile_test_cig_create_cmpl_evt_.conn_handles[0]; IsoManager::GetInstance()->EstablishCis({.conn_pairs = {{iso_handle, 1}}}); - IsoManager::GetInstance()->SetupIsoDataPath(iso_handle, - kDefaultIsoDataPathParams); + IsoManager::GetInstance()->SetupIsoDataPath(iso_handle, kDefaultIsoDataPathParams); - EXPECT_CALL(*cig_callbacks_, - OnRemoveIsoDataPath(remove_datapath_rsp_status, iso_handle, - volatile_test_cig_create_cmpl_evt_.cig_id)) - .Times(1); - IsoManager::GetInstance()->RemoveIsoDataPath( - iso_handle, kDefaultIsoDataPathParams.data_path_dir); + EXPECT_CALL(*cig_callbacks_, OnRemoveIsoDataPath(remove_datapath_rsp_status, iso_handle, + volatile_test_cig_create_cmpl_evt_.cig_id)) + .Times(1); + IsoManager::GetInstance()->RemoveIsoDataPath(iso_handle, kDefaultIsoDataPathParams.data_path_dir); // Check on BIS iso_handle = volatile_test_big_params_evt_.conn_handles[0]; - IsoManager::GetInstance()->CreateBig(volatile_test_big_params_evt_.big_id, - kDefaultBigParams); - IsoManager::GetInstance()->SetupIsoDataPath(iso_handle, - kDefaultIsoDataPathParams); + IsoManager::GetInstance()->CreateBig(volatile_test_big_params_evt_.big_id, kDefaultBigParams); + IsoManager::GetInstance()->SetupIsoDataPath(iso_handle, kDefaultIsoDataPathParams); - EXPECT_CALL(*big_callbacks_, - OnRemoveIsoDataPath(remove_datapath_rsp_status, iso_handle, - volatile_test_big_params_evt_.big_id)) - .Times(1); - IsoManager::GetInstance()->RemoveIsoDataPath( - iso_handle, kDefaultIsoDataPathParams.data_path_dir); + EXPECT_CALL(*big_callbacks_, OnRemoveIsoDataPath(remove_datapath_rsp_status, iso_handle, + volatile_test_big_params_evt_.big_id)) + .Times(1); + IsoManager::GetInstance()->RemoveIsoDataPath(iso_handle, kDefaultIsoDataPathParams.data_path_dir); } TEST_F(IsoManagerTest, RemoveIsoDataPathLateArrivingCallback) { - IsoManager::GetInstance()->CreateCig( - volatile_test_cig_create_cmpl_evt_.cig_id, kDefaultCigParams); - IsoManager::GetInstance()->CreateBig(volatile_test_big_params_evt_.big_id, - kDefaultBigParams); + IsoManager::GetInstance()->CreateCig(volatile_test_cig_create_cmpl_evt_.cig_id, + kDefaultCigParams); + IsoManager::GetInstance()->CreateBig(volatile_test_big_params_evt_.big_id, kDefaultBigParams); // Establish all CISes before setting up their data paths bluetooth::hci::iso_manager::cis_establish_params params; @@ -2037,34 +1820,29 @@ TEST_F(IsoManagerTest, RemoveIsoDataPathLateArrivingCallback) { } IsoManager::GetInstance()->EstablishCis(params); - bluetooth::hci::iso_manager::iso_data_path_params path_params = - kDefaultIsoDataPathParams; + bluetooth::hci::iso_manager::iso_data_path_params path_params = kDefaultIsoDataPathParams; // Setup and remove data paths for all CISes - path_params.data_path_dir = - bluetooth::hci::iso_manager::kRemoveIsoDataPathDirectionInput; + path_params.data_path_dir = bluetooth::hci::iso_manager::kRemoveIsoDataPathDirectionInput; auto& handle = volatile_test_cig_create_cmpl_evt_.conn_handles[0]; IsoManager::GetInstance()->SetupIsoDataPath(handle, path_params); // Catch the callback base::OnceCallback iso_cb; ON_CALL(hcic_interface_, RemoveIsoDataPath) - .WillByDefault( - [&iso_cb](uint16_t /* iso_handle */, uint8_t /* data_path_dir */, - base::OnceCallback cb) { + .WillByDefault([&iso_cb](uint16_t /* iso_handle */, uint8_t /* data_path_dir */, + base::OnceCallback cb) { iso_cb = std::move(cb); }); - IsoManager::GetInstance()->RemoveIsoDataPath(handle, - path_params.data_path_dir); + IsoManager::GetInstance()->RemoveIsoDataPath(handle, path_params.data_path_dir); // Stop the IsoManager before calling the callback IsoManager::GetInstance()->Stop(); // Call the callback and expect no call EXPECT_CALL(*cig_callbacks_, - OnRemoveIsoDataPath(HCI_SUCCESS, handle, - volatile_test_cig_create_cmpl_evt_.cig_id)) - .Times(0); + OnRemoveIsoDataPath(HCI_SUCCESS, handle, volatile_test_cig_create_cmpl_evt_.cig_id)) + .Times(0); ASSERT_FALSE(iso_cb.is_null()); std::vector buf(3); @@ -2076,18 +1854,17 @@ TEST_F(IsoManagerTest, RemoveIsoDataPathLateArrivingCallback) { TEST_F(IsoManagerTest, SendIsoDataWithNoCigConnected) { std::vector data_vec(108, 0); - IsoManager::GetInstance()->CreateCig( - volatile_test_cig_create_cmpl_evt_.cig_id, kDefaultCigParams); + IsoManager::GetInstance()->CreateCig(volatile_test_cig_create_cmpl_evt_.cig_id, + kDefaultCigParams); auto handle = volatile_test_cig_create_cmpl_evt_.conn_handles[0]; - IsoManager::GetInstance()->SendIsoData(handle, data_vec.data(), - data_vec.size()); + IsoManager::GetInstance()->SendIsoData(handle, data_vec.data(), data_vec.size()); EXPECT_CALL(iso_interface_, HciSend).Times(0); } TEST_F(IsoManagerTest, SendIsoDataCigValid) { - IsoManager::GetInstance()->CreateCig( - volatile_test_cig_create_cmpl_evt_.cig_id, kDefaultCigParams); + IsoManager::GetInstance()->CreateCig(volatile_test_cig_create_cmpl_evt_.cig_id, + kDefaultCigParams); bluetooth::hci::iso_manager::cis_establish_params params; for (auto& handle : volatile_test_cig_create_cmpl_evt_.conn_handles) { @@ -2096,116 +1873,101 @@ TEST_F(IsoManagerTest, SendIsoDataCigValid) { IsoManager::GetInstance()->EstablishCis(params); for (auto& handle : volatile_test_cig_create_cmpl_evt_.conn_handles) { - bluetooth::hci::iso_manager::iso_data_path_params path_params = - kDefaultIsoDataPathParams; - path_params.data_path_dir = - bluetooth::hci::iso_manager::kIsoDataPathDirectionOut; + bluetooth::hci::iso_manager::iso_data_path_params path_params = kDefaultIsoDataPathParams; + path_params.data_path_dir = bluetooth::hci::iso_manager::kIsoDataPathDirectionOut; IsoManager::GetInstance()->SetupIsoDataPath(handle, path_params); for (uint8_t num_pkts = 2; num_pkts != 0; num_pkts--) { constexpr uint8_t data_len = 108; EXPECT_CALL(iso_interface_, HciSend) - .WillOnce([handle, data_len](BT_HDR* p_msg) { - uint8_t* p = p_msg->data; - uint16_t msg_handle; - uint16_t iso_load_len; - - ASSERT_NE(p_msg, nullptr); - ASSERT_EQ(p_msg->len, data_len + ((p_msg->layer_specific & - BT_ISO_HDR_CONTAINS_TS) - ? 12 - : 8)); - - // Verify packet internals - STREAM_TO_UINT16(msg_handle, p); - ASSERT_EQ(msg_handle, handle); - - STREAM_TO_UINT16(iso_load_len, p); - ASSERT_EQ( - iso_load_len, - data_len + - ((p_msg->layer_specific & BT_ISO_HDR_CONTAINS_TS) ? 8 : 4)); - - if (p_msg->layer_specific & BT_ISO_HDR_CONTAINS_TS) { - STREAM_SKIP_UINT16(p); // skip ts LSB halfword - STREAM_SKIP_UINT16(p); // skip ts MSB halfword - } - STREAM_SKIP_UINT16(p); // skip seq_nb - - uint16_t msg_data_len; - STREAM_TO_UINT16(msg_data_len, p); - ASSERT_EQ(msg_data_len, data_len); - }) - .RetiresOnSaturation(); + .WillOnce([handle, data_len](BT_HDR* p_msg) { + uint8_t* p = p_msg->data; + uint16_t msg_handle; + uint16_t iso_load_len; + + ASSERT_NE(p_msg, nullptr); + ASSERT_EQ(p_msg->len, + data_len + ((p_msg->layer_specific & BT_ISO_HDR_CONTAINS_TS) ? 12 : 8)); + + // Verify packet internals + STREAM_TO_UINT16(msg_handle, p); + ASSERT_EQ(msg_handle, handle); + + STREAM_TO_UINT16(iso_load_len, p); + ASSERT_EQ(iso_load_len, + data_len + ((p_msg->layer_specific & BT_ISO_HDR_CONTAINS_TS) ? 8 : 4)); + + if (p_msg->layer_specific & BT_ISO_HDR_CONTAINS_TS) { + STREAM_SKIP_UINT16(p); // skip ts LSB halfword + STREAM_SKIP_UINT16(p); // skip ts MSB halfword + } + STREAM_SKIP_UINT16(p); // skip seq_nb + + uint16_t msg_data_len; + STREAM_TO_UINT16(msg_data_len, p); + ASSERT_EQ(msg_data_len, data_len); + }) + .RetiresOnSaturation(); std::vector data_vec(data_len, 0); - IsoManager::GetInstance()->SendIsoData(handle, data_vec.data(), - data_vec.size()); + IsoManager::GetInstance()->SendIsoData(handle, data_vec.data(), data_vec.size()); } } } TEST_F(IsoManagerTest, SendIsoDataBigValid) { - IsoManager::GetInstance()->CreateBig(volatile_test_big_params_evt_.big_id, - kDefaultBigParams); + IsoManager::GetInstance()->CreateBig(volatile_test_big_params_evt_.big_id, kDefaultBigParams); for (auto& handle : volatile_test_big_params_evt_.conn_handles) { - IsoManager::GetInstance()->SetupIsoDataPath(handle, - kDefaultIsoDataPathParams); + IsoManager::GetInstance()->SetupIsoDataPath(handle, kDefaultIsoDataPathParams); for (uint8_t num_pkts = 2; num_pkts != 0; num_pkts--) { constexpr uint8_t data_len = 108; EXPECT_CALL(iso_interface_, HciSend) - .WillOnce([handle, data_len](BT_HDR* p_msg) { - uint8_t* p = p_msg->data; - uint16_t msg_handle; - uint16_t iso_load_len; - - ASSERT_NE(p_msg, nullptr); - ASSERT_EQ(p_msg->len, data_len + ((p_msg->layer_specific & - BT_ISO_HDR_CONTAINS_TS) - ? 12 - : 8)); - - // Verify packet internals - STREAM_TO_UINT16(msg_handle, p); - ASSERT_EQ(msg_handle, handle); - - STREAM_TO_UINT16(iso_load_len, p); - ASSERT_EQ( - iso_load_len, - data_len + - ((p_msg->layer_specific & BT_ISO_HDR_CONTAINS_TS) ? 8 : 4)); - - uint16_t msg_data_len; - uint16_t msg_dummy; - if (p_msg->layer_specific & BT_ISO_HDR_CONTAINS_TS) { - STREAM_TO_UINT16(msg_dummy, p); // skip ts LSB halfword - STREAM_TO_UINT16(msg_dummy, p); // skip ts MSB halfword - } - STREAM_TO_UINT16(msg_dummy, p); // skip seq_nb - - STREAM_TO_UINT16(msg_data_len, p); - ASSERT_EQ(msg_data_len, data_len); - }) - .RetiresOnSaturation(); + .WillOnce([handle, data_len](BT_HDR* p_msg) { + uint8_t* p = p_msg->data; + uint16_t msg_handle; + uint16_t iso_load_len; + + ASSERT_NE(p_msg, nullptr); + ASSERT_EQ(p_msg->len, + data_len + ((p_msg->layer_specific & BT_ISO_HDR_CONTAINS_TS) ? 12 : 8)); + + // Verify packet internals + STREAM_TO_UINT16(msg_handle, p); + ASSERT_EQ(msg_handle, handle); + + STREAM_TO_UINT16(iso_load_len, p); + ASSERT_EQ(iso_load_len, + data_len + ((p_msg->layer_specific & BT_ISO_HDR_CONTAINS_TS) ? 8 : 4)); + + uint16_t msg_data_len; + uint16_t msg_dummy; + if (p_msg->layer_specific & BT_ISO_HDR_CONTAINS_TS) { + STREAM_TO_UINT16(msg_dummy, p); // skip ts LSB halfword + STREAM_TO_UINT16(msg_dummy, p); // skip ts MSB halfword + } + STREAM_TO_UINT16(msg_dummy, p); // skip seq_nb + + STREAM_TO_UINT16(msg_data_len, p); + ASSERT_EQ(msg_data_len, data_len); + }) + .RetiresOnSaturation(); std::vector data_vec(data_len, 0); - IsoManager::GetInstance()->SendIsoData(handle, data_vec.data(), - data_vec.size()); + IsoManager::GetInstance()->SendIsoData(handle, data_vec.data(), data_vec.size()); } } } TEST_F(IsoManagerTest, SendIsoDataNoCredits) { - uint8_t num_buffers = - controller_.GetControllerIsoBufferSize().total_num_le_packets_; + uint8_t num_buffers = controller_.GetControllerIsoBufferSize().total_num_le_packets_; std::vector data_vec(108, 0); // Check on CIG - IsoManager::GetInstance()->CreateCig( - volatile_test_cig_create_cmpl_evt_.cig_id, kDefaultCigParams); + IsoManager::GetInstance()->CreateCig(volatile_test_cig_create_cmpl_evt_.cig_id, + kDefaultCigParams); bluetooth::hci::iso_manager::cis_establish_params params; for (auto& handle : volatile_test_cig_create_cmpl_evt_.conn_handles) { @@ -2213,9 +1975,8 @@ TEST_F(IsoManagerTest, SendIsoDataNoCredits) { } IsoManager::GetInstance()->EstablishCis(params); - IsoManager::GetInstance()->SetupIsoDataPath( - volatile_test_cig_create_cmpl_evt_.conn_handles[0], - kDefaultIsoDataPathParams); + IsoManager::GetInstance()->SetupIsoDataPath(volatile_test_cig_create_cmpl_evt_.conn_handles[0], + kDefaultIsoDataPathParams); /* Try sending twice as much data as we can ignoring the credit limits and * expect the redundant packets to be ignored and not propagated down to the @@ -2223,20 +1984,18 @@ TEST_F(IsoManagerTest, SendIsoDataNoCredits) { */ EXPECT_CALL(iso_interface_, HciSend).Times(num_buffers).RetiresOnSaturation(); for (uint8_t i = 0; i < (2 * num_buffers); i++) { - IsoManager::GetInstance()->SendIsoData( - volatile_test_cig_create_cmpl_evt_.conn_handles[0], data_vec.data(), - data_vec.size()); + IsoManager::GetInstance()->SendIsoData(volatile_test_cig_create_cmpl_evt_.conn_handles[0], + data_vec.data(), data_vec.size()); } // Return all credits for this one handle IsoManager::GetInstance()->HandleNumComplDataPkts( - volatile_test_cig_create_cmpl_evt_.conn_handles[0], num_buffers); + volatile_test_cig_create_cmpl_evt_.conn_handles[0], num_buffers); // Check on BIG - IsoManager::GetInstance()->CreateBig(volatile_test_big_params_evt_.big_id, - kDefaultBigParams); - IsoManager::GetInstance()->SetupIsoDataPath( - volatile_test_big_params_evt_.conn_handles[0], kDefaultIsoDataPathParams); + IsoManager::GetInstance()->CreateBig(volatile_test_big_params_evt_.big_id, kDefaultBigParams); + IsoManager::GetInstance()->SetupIsoDataPath(volatile_test_big_params_evt_.conn_handles[0], + kDefaultIsoDataPathParams); /* Try sending twice as much data as we can ignoring the credit limits and * expect the redundant packets to be ignored and not propagated down to the @@ -2244,20 +2003,18 @@ TEST_F(IsoManagerTest, SendIsoDataNoCredits) { */ EXPECT_CALL(iso_interface_, HciSend).Times(num_buffers); for (uint8_t i = 0; i < (2 * num_buffers); i++) { - IsoManager::GetInstance()->SendIsoData( - volatile_test_big_params_evt_.conn_handles[0], data_vec.data(), - data_vec.size()); + IsoManager::GetInstance()->SendIsoData(volatile_test_big_params_evt_.conn_handles[0], + data_vec.data(), data_vec.size()); } } TEST_F(IsoManagerTest, SendIsoDataCreditsReturned) { - uint8_t num_buffers = - controller_.GetControllerIsoBufferSize().total_num_le_packets_; + uint8_t num_buffers = controller_.GetControllerIsoBufferSize().total_num_le_packets_; std::vector data_vec(108, 0); // Check on CIG - IsoManager::GetInstance()->CreateCig( - volatile_test_cig_create_cmpl_evt_.cig_id, kDefaultCigParams); + IsoManager::GetInstance()->CreateCig(volatile_test_cig_create_cmpl_evt_.cig_id, + kDefaultCigParams); bluetooth::hci::iso_manager::cis_establish_params params; for (auto& handle : volatile_test_cig_create_cmpl_evt_.conn_handles) { @@ -2265,9 +2022,8 @@ TEST_F(IsoManagerTest, SendIsoDataCreditsReturned) { } IsoManager::GetInstance()->EstablishCis(params); - IsoManager::GetInstance()->SetupIsoDataPath( - volatile_test_cig_create_cmpl_evt_.conn_handles[0], - kDefaultIsoDataPathParams); + IsoManager::GetInstance()->SetupIsoDataPath(volatile_test_cig_create_cmpl_evt_.conn_handles[0], + kDefaultIsoDataPathParams); /* Try sending twice as much data as we can, ignoring the credits limit and * expect the redundant packets to be ignored and not propagated down to the @@ -2275,32 +2031,29 @@ TEST_F(IsoManagerTest, SendIsoDataCreditsReturned) { */ EXPECT_CALL(iso_interface_, HciSend).Times(num_buffers).RetiresOnSaturation(); for (uint8_t i = 0; i < (2 * num_buffers); i++) { - IsoManager::GetInstance()->SendIsoData( - volatile_test_cig_create_cmpl_evt_.conn_handles[0], data_vec.data(), - data_vec.size()); + IsoManager::GetInstance()->SendIsoData(volatile_test_cig_create_cmpl_evt_.conn_handles[0], + data_vec.data(), data_vec.size()); } // Return all credits for this one handle IsoManager::GetInstance()->HandleNumComplDataPkts( - volatile_test_cig_create_cmpl_evt_.conn_handles[0], num_buffers); + volatile_test_cig_create_cmpl_evt_.conn_handles[0], num_buffers); // Expect some more events go down the HCI EXPECT_CALL(iso_interface_, HciSend).Times(num_buffers).RetiresOnSaturation(); for (uint8_t i = 0; i < (2 * num_buffers); i++) { - IsoManager::GetInstance()->SendIsoData( - volatile_test_cig_create_cmpl_evt_.conn_handles[0], data_vec.data(), - data_vec.size()); + IsoManager::GetInstance()->SendIsoData(volatile_test_cig_create_cmpl_evt_.conn_handles[0], + data_vec.data(), data_vec.size()); } // Return all credits for this one handle IsoManager::GetInstance()->HandleNumComplDataPkts( - volatile_test_cig_create_cmpl_evt_.conn_handles[0], num_buffers); + volatile_test_cig_create_cmpl_evt_.conn_handles[0], num_buffers); // Check on BIG - IsoManager::GetInstance()->CreateBig(volatile_test_big_params_evt_.big_id, - kDefaultBigParams); - IsoManager::GetInstance()->SetupIsoDataPath( - volatile_test_big_params_evt_.conn_handles[0], kDefaultIsoDataPathParams); + IsoManager::GetInstance()->CreateBig(volatile_test_big_params_evt_.big_id, kDefaultBigParams); + IsoManager::GetInstance()->SetupIsoDataPath(volatile_test_big_params_evt_.conn_handles[0], + kDefaultIsoDataPathParams); /* Try sending twice as much data as we can, ignoring the credits limit and * expect the redundant packets to be ignored and not propagated down to the @@ -2308,32 +2061,29 @@ TEST_F(IsoManagerTest, SendIsoDataCreditsReturned) { */ EXPECT_CALL(iso_interface_, HciSend).Times(num_buffers).RetiresOnSaturation(); for (uint8_t i = 0; i < (2 * num_buffers); i++) { - IsoManager::GetInstance()->SendIsoData( - volatile_test_big_params_evt_.conn_handles[0], data_vec.data(), - data_vec.size()); + IsoManager::GetInstance()->SendIsoData(volatile_test_big_params_evt_.conn_handles[0], + data_vec.data(), data_vec.size()); } // Return all credits for this one handle - IsoManager::GetInstance()->HandleNumComplDataPkts( - volatile_test_big_params_evt_.conn_handles[0], num_buffers); + IsoManager::GetInstance()->HandleNumComplDataPkts(volatile_test_big_params_evt_.conn_handles[0], + num_buffers); // Expect some more events go down the HCI EXPECT_CALL(iso_interface_, HciSend).Times(num_buffers).RetiresOnSaturation(); for (uint8_t i = 0; i < (2 * num_buffers); i++) { - IsoManager::GetInstance()->SendIsoData( - volatile_test_big_params_evt_.conn_handles[0], data_vec.data(), - data_vec.size()); + IsoManager::GetInstance()->SendIsoData(volatile_test_big_params_evt_.conn_handles[0], + data_vec.data(), data_vec.size()); } } TEST_F(IsoManagerTest, SendIsoDataCreditsReturnedByDisconnection) { - uint8_t num_buffers = - controller_.GetControllerIsoBufferSize().total_num_le_packets_; + uint8_t num_buffers = controller_.GetControllerIsoBufferSize().total_num_le_packets_; std::vector data_vec(108, 0); // Check on CIG - IsoManager::GetInstance()->CreateCig( - volatile_test_cig_create_cmpl_evt_.cig_id, kDefaultCigParams); + IsoManager::GetInstance()->CreateCig(volatile_test_cig_create_cmpl_evt_.cig_id, + kDefaultCigParams); bluetooth::hci::iso_manager::cis_establish_params params; for (auto& handle : volatile_test_cig_create_cmpl_evt_.conn_handles) { @@ -2342,28 +2092,25 @@ TEST_F(IsoManagerTest, SendIsoDataCreditsReturnedByDisconnection) { IsoManager::GetInstance()->EstablishCis(params); for (auto& handle : volatile_test_cig_create_cmpl_evt_.conn_handles) { - IsoManager::GetInstance()->SetupIsoDataPath(handle, - kDefaultIsoDataPathParams); + IsoManager::GetInstance()->SetupIsoDataPath(handle, kDefaultIsoDataPathParams); } /* Sending lot of ISO data to first ISO and getting all the credits */ EXPECT_CALL(iso_interface_, HciSend).Times(num_buffers).RetiresOnSaturation(); for (uint8_t i = 0; i < num_buffers; i++) { - IsoManager::GetInstance()->SendIsoData( - volatile_test_cig_create_cmpl_evt_.conn_handles[0], data_vec.data(), - data_vec.size()); + IsoManager::GetInstance()->SendIsoData(volatile_test_cig_create_cmpl_evt_.conn_handles[0], + data_vec.data(), data_vec.size()); } /* Return all credits by disconnecting CIS */ - IsoManager::GetInstance()->HandleDisconnect( - volatile_test_cig_create_cmpl_evt_.conn_handles[0], 16); + IsoManager::GetInstance()->HandleDisconnect(volatile_test_cig_create_cmpl_evt_.conn_handles[0], + 16); /* Try to send ISO data on the second ISO. Expect credits being available.*/ EXPECT_CALL(iso_interface_, HciSend).Times(num_buffers).RetiresOnSaturation(); for (uint8_t i = 0; i < num_buffers; i++) { - IsoManager::GetInstance()->SendIsoData( - volatile_test_cig_create_cmpl_evt_.conn_handles[1], data_vec.data(), - data_vec.size()); + IsoManager::GetInstance()->SendIsoData(volatile_test_cig_create_cmpl_evt_.conn_handles[1], + data_vec.data(), data_vec.size()); } } @@ -2371,8 +2118,8 @@ TEST_F(IsoManagerDeathTest, SendIsoDataWithNoDataPath) { std::vector data_vec(108, 0); // Check on CIG - IsoManager::GetInstance()->CreateCig( - volatile_test_cig_create_cmpl_evt_.cig_id, kDefaultCigParams); + IsoManager::GetInstance()->CreateCig(volatile_test_cig_create_cmpl_evt_.cig_id, + kDefaultCigParams); bluetooth::hci::iso_manager::cis_establish_params params; for (auto& conn_handle : volatile_test_cig_create_cmpl_evt_.conn_handles) { @@ -2381,24 +2128,20 @@ TEST_F(IsoManagerDeathTest, SendIsoDataWithNoDataPath) { IsoManager::GetInstance()->EstablishCis(params); EXPECT_CALL(iso_interface_, HciSend).Times(0); - IsoManager::GetInstance()->SendIsoData( - volatile_test_cig_create_cmpl_evt_.conn_handles[0], data_vec.data(), - data_vec.size()); + IsoManager::GetInstance()->SendIsoData(volatile_test_cig_create_cmpl_evt_.conn_handles[0], + data_vec.data(), data_vec.size()); // Check on BIG - IsoManager::GetInstance()->CreateBig(volatile_test_big_params_evt_.big_id, - kDefaultBigParams); + IsoManager::GetInstance()->CreateBig(volatile_test_big_params_evt_.big_id, kDefaultBigParams); EXPECT_CALL(iso_interface_, HciSend).Times(0); - IsoManager::GetInstance()->SendIsoData( - volatile_test_big_params_evt_.conn_handles[0], data_vec.data(), - data_vec.size()); + IsoManager::GetInstance()->SendIsoData(volatile_test_big_params_evt_.conn_handles[0], + data_vec.data(), data_vec.size()); } TEST_F(IsoManagerDeathTest, SendIsoDataWithNoCigBigHandle) { std::vector data_vec(108, 0); - ASSERT_EXIT(IsoManager::GetInstance()->SendIsoData(134, data_vec.data(), - data_vec.size()), + ASSERT_EXIT(IsoManager::GetInstance()->SendIsoData(134, data_vec.data(), data_vec.size()), ::testing::KilledBySignal(SIGABRT), "No such iso"); } @@ -2412,8 +2155,8 @@ TEST_F(IsoManagerTest, HandleDisconnectNoSuchHandle) { } TEST_F(IsoManagerTest, HandleDisconnectValidCig) { - IsoManager::GetInstance()->CreateCig( - volatile_test_cig_create_cmpl_evt_.cig_id, kDefaultCigParams); + IsoManager::GetInstance()->CreateCig(volatile_test_cig_create_cmpl_evt_.cig_id, + kDefaultCigParams); auto handle = volatile_test_cig_create_cmpl_evt_.conn_handles[0]; IsoManager::GetInstance()->EstablishCis({{{handle, 1}}}); @@ -2423,24 +2166,20 @@ TEST_F(IsoManagerTest, HandleDisconnectValidCig) { EXPECT_CALL(*cig_callbacks_, OnCisEvent).Times(0); // Expect disconnect event exactly once - EXPECT_CALL(*cig_callbacks_, OnCisEvent) - .WillOnce([this, handle](uint8_t event_code, void* data) { - ASSERT_EQ(event_code, - bluetooth::hci::iso_manager::kIsoEventCisDisconnected); - auto* event = - static_cast( - data); - ASSERT_EQ(event->reason, 16); - ASSERT_EQ(event->cig_id, volatile_test_cig_create_cmpl_evt_.cig_id); - ASSERT_EQ(event->cis_conn_hdl, handle); - }); + EXPECT_CALL(*cig_callbacks_, OnCisEvent).WillOnce([this, handle](uint8_t event_code, void* data) { + ASSERT_EQ(event_code, bluetooth::hci::iso_manager::kIsoEventCisDisconnected); + auto* event = static_cast(data); + ASSERT_EQ(event->reason, 16); + ASSERT_EQ(event->cig_id, volatile_test_cig_create_cmpl_evt_.cig_id); + ASSERT_EQ(event->cis_conn_hdl, handle); + }); IsoManager::GetInstance()->HandleDisconnect(handle, 16); } TEST_F(IsoManagerTest, HandleDisconnectDisconnectedCig) { - IsoManager::GetInstance()->CreateCig( - volatile_test_cig_create_cmpl_evt_.cig_id, kDefaultCigParams); + IsoManager::GetInstance()->CreateCig(volatile_test_cig_create_cmpl_evt_.cig_id, + kDefaultCigParams); auto handle = volatile_test_cig_create_cmpl_evt_.conn_handles[0]; IsoManager::GetInstance()->EstablishCis({{{handle, 1}}}); @@ -2450,11 +2189,9 @@ TEST_F(IsoManagerTest, HandleDisconnectDisconnectedCig) { EXPECT_CALL(*cig_callbacks_, OnCisEvent).Times(0); // Expect disconnect event exactly once - EXPECT_CALL( - *cig_callbacks_, - OnCisEvent(bluetooth::hci::iso_manager::kIsoEventCisDisconnected, _)) - .Times(1) - .RetiresOnSaturation(); + EXPECT_CALL(*cig_callbacks_, OnCisEvent(bluetooth::hci::iso_manager::kIsoEventCisDisconnected, _)) + .Times(1) + .RetiresOnSaturation(); IsoManager::GetInstance()->HandleDisconnect(handle, 16); // This one was once connected - expect no events @@ -2466,8 +2203,8 @@ TEST_F(IsoManagerTest, HandleDisconnectDisconnectedCig) { } TEST_F(IsoManagerTest, HandleDisconnectLateArrivingCallback) { - IsoManager::GetInstance()->CreateCig( - volatile_test_cig_create_cmpl_evt_.cig_id, kDefaultCigParams); + IsoManager::GetInstance()->CreateCig(volatile_test_cig_create_cmpl_evt_.cig_id, + kDefaultCigParams); auto handle = volatile_test_cig_create_cmpl_evt_.conn_handles[0]; IsoManager::GetInstance()->EstablishCis({{{handle, 1}}}); @@ -2477,10 +2214,8 @@ TEST_F(IsoManagerTest, HandleDisconnectLateArrivingCallback) { EXPECT_CALL(*cig_callbacks_, OnCisEvent).Times(0); // Expect disconnect event exactly once - EXPECT_CALL( - *cig_callbacks_, - OnCisEvent(bluetooth::hci::iso_manager::kIsoEventCisDisconnected, _)) - .Times(0); + EXPECT_CALL(*cig_callbacks_, OnCisEvent(bluetooth::hci::iso_manager::kIsoEventCisDisconnected, _)) + .Times(0); // Expect no callback on late arriving event IsoManager::GetInstance()->Stop(); @@ -2488,16 +2223,15 @@ TEST_F(IsoManagerTest, HandleDisconnectLateArrivingCallback) { } TEST_F(IsoManagerTest, HandleIsoData) { - IsoManager::GetInstance()->CreateCig( - volatile_test_cig_create_cmpl_evt_.cig_id, kDefaultCigParams); + IsoManager::GetInstance()->CreateCig(volatile_test_cig_create_cmpl_evt_.cig_id, + kDefaultCigParams); auto handle = volatile_test_cig_create_cmpl_evt_.conn_handles[0]; IsoManager::GetInstance()->EstablishCis({{{handle, 1}}}); - EXPECT_CALL( - *cig_callbacks_, - OnCisEvent(bluetooth::hci::iso_manager::kIsoEventCisDataAvailable, _)) - .Times(1); + EXPECT_CALL(*cig_callbacks_, + OnCisEvent(bluetooth::hci::iso_manager::kIsoEventCisDataAvailable, _)) + .Times(1); std::vector dummy_msg(18); uint8_t* p = dummy_msg.data(); @@ -2514,8 +2248,8 @@ TEST_F(IsoManagerTest, HandleIsoData) { * is already stopped. */ TEST_F(IsoManagerDeathTestNoCleanup, HandleLateArivingEventHandleIsoData) { - IsoManager::GetInstance()->CreateCig( - volatile_test_cig_create_cmpl_evt_.cig_id, kDefaultCigParams); + IsoManager::GetInstance()->CreateCig(volatile_test_cig_create_cmpl_evt_.cig_id, + kDefaultCigParams); auto handle = volatile_test_cig_create_cmpl_evt_.conn_handles[0]; IsoManager::GetInstance()->EstablishCis({{{handle, 1}}}); @@ -2523,10 +2257,9 @@ TEST_F(IsoManagerDeathTestNoCleanup, HandleLateArivingEventHandleIsoData) { // Stop iso manager before trying to call the HCI callbacks IsoManager::GetInstance()->Stop(); - EXPECT_CALL( - *cig_callbacks_, - OnCisEvent(bluetooth::hci::iso_manager::kIsoEventCisDataAvailable, _)) - .Times(0); + EXPECT_CALL(*cig_callbacks_, + OnCisEvent(bluetooth::hci::iso_manager::kIsoEventCisDataAvailable, _)) + .Times(0); // Expect no assert on this call - should be gracefully ignored std::vector dummy_msg(18); @@ -2544,8 +2277,8 @@ TEST_F(IsoManagerDeathTestNoCleanup, HandleLateArivingEventHandleIsoData) { * is already stopped. */ TEST_F(IsoManagerDeathTestNoCleanup, HandleLateArivingEventHandleDisconnect) { - IsoManager::GetInstance()->CreateCig( - volatile_test_cig_create_cmpl_evt_.cig_id, kDefaultCigParams); + IsoManager::GetInstance()->CreateCig(volatile_test_cig_create_cmpl_evt_.cig_id, + kDefaultCigParams); auto handle = volatile_test_cig_create_cmpl_evt_.conn_handles[0]; IsoManager::GetInstance()->EstablishCis({{{handle, 1}}}); @@ -2563,13 +2296,11 @@ TEST_F(IsoManagerDeathTestNoCleanup, HandleLateArivingEventHandleDisconnect) { * without knowing the we are already shutting down the stack and Iso Manager * is already stopped. */ -TEST_F(IsoManagerDeathTestNoCleanup, - HandleLateArivingEventHandleNumComplDataPkts) { - uint8_t num_buffers = - controller_.GetControllerIsoBufferSize().total_num_le_packets_; +TEST_F(IsoManagerDeathTestNoCleanup, HandleLateArivingEventHandleNumComplDataPkts) { + uint8_t num_buffers = controller_.GetControllerIsoBufferSize().total_num_le_packets_; - IsoManager::GetInstance()->CreateCig( - volatile_test_cig_create_cmpl_evt_.cig_id, kDefaultCigParams); + IsoManager::GetInstance()->CreateCig(volatile_test_cig_create_cmpl_evt_.cig_id, + kDefaultCigParams); auto handle = volatile_test_cig_create_cmpl_evt_.conn_handles[0]; IsoManager::GetInstance()->EstablishCis({{{handle, 1}}}); @@ -2592,31 +2323,28 @@ TEST_F(IsoManagerDeathTestNoCleanup, HandleLateArivingEventHandleHciEvent) { // Stop iso manager before trying to call the HCI callbacks IsoManager::GetInstance()->Stop(); - EXPECT_CALL( - *big_callbacks_, - OnBigEvent(bluetooth::hci::iso_manager::kIsoEventBigOnTerminateCmpl, _)) - .Times(0); + EXPECT_CALL(*big_callbacks_, + OnBigEvent(bluetooth::hci::iso_manager::kIsoEventBigOnTerminateCmpl, _)) + .Times(0); // Expect no assert on this call - should be gracefully ignored std::vector buf(2); uint8_t* p = buf.data(); UINT8_TO_STREAM(p, big_id); UINT8_TO_STREAM(p, 16); // Terminated by local host - IsoManager::GetInstance()->HandleHciEvent(HCI_BLE_TERM_BIG_CPL_EVT, - buf.data(), buf.size()); + IsoManager::GetInstance()->HandleHciEvent(HCI_BLE_TERM_BIG_CPL_EVT, buf.data(), buf.size()); } TEST_F(IsoManagerTest, HandleIsoDataSameSeqNb) { - IsoManager::GetInstance()->CreateCig( - volatile_test_cig_create_cmpl_evt_.cig_id, kDefaultCigParams); + IsoManager::GetInstance()->CreateCig(volatile_test_cig_create_cmpl_evt_.cig_id, + kDefaultCigParams); auto handle = volatile_test_cig_create_cmpl_evt_.conn_handles[0]; IsoManager::GetInstance()->EstablishCis({{{handle, 1}}}); - EXPECT_CALL( - *cig_callbacks_, - OnCisEvent(bluetooth::hci::iso_manager::kIsoEventCisDataAvailable, _)) - .Times(2); + EXPECT_CALL(*cig_callbacks_, + OnCisEvent(bluetooth::hci::iso_manager::kIsoEventCisDataAvailable, _)) + .Times(2); std::vector dummy_msg(18); uint8_t* p = dummy_msg.data(); @@ -2631,25 +2359,22 @@ TEST_F(IsoManagerTest, HandleIsoDataSameSeqNb) { } TEST_F(IsoManagerTest, ReadIsoLinkQualityLateArrivingCallback) { - IsoManager::GetInstance()->CreateCig( - volatile_test_cig_create_cmpl_evt_.cig_id, kDefaultCigParams); - - EXPECT_CALL( - *cig_callbacks_, - OnCisEvent(bluetooth::hci::iso_manager::kIsoEventCisEstablishCmpl, _)) - .Times(kDefaultCigParams.cis_cfgs.size()) - .WillRepeatedly([this](uint8_t /* type */, void* data) { - bluetooth::hci::iso_manager::cis_establish_cmpl_evt* evt = - static_cast( - data); - - ASSERT_EQ(evt->status, HCI_SUCCESS); - ASSERT_TRUE( - std::find(volatile_test_cig_create_cmpl_evt_.conn_handles.begin(), - volatile_test_cig_create_cmpl_evt_.conn_handles.end(), - evt->cis_conn_hdl) != - volatile_test_cig_create_cmpl_evt_.conn_handles.end()); - }); + IsoManager::GetInstance()->CreateCig(volatile_test_cig_create_cmpl_evt_.cig_id, + kDefaultCigParams); + + EXPECT_CALL(*cig_callbacks_, + OnCisEvent(bluetooth::hci::iso_manager::kIsoEventCisEstablishCmpl, _)) + .Times(kDefaultCigParams.cis_cfgs.size()) + .WillRepeatedly([this](uint8_t /* type */, void* data) { + bluetooth::hci::iso_manager::cis_establish_cmpl_evt* evt = + static_cast(data); + + ASSERT_EQ(evt->status, HCI_SUCCESS); + ASSERT_TRUE(std::find(volatile_test_cig_create_cmpl_evt_.conn_handles.begin(), + volatile_test_cig_create_cmpl_evt_.conn_handles.end(), + evt->cis_conn_hdl) != + volatile_test_cig_create_cmpl_evt_.conn_handles.end()); + }); // Establish all CISes bluetooth::hci::iso_manager::cis_establish_params params; @@ -2661,9 +2386,8 @@ TEST_F(IsoManagerTest, ReadIsoLinkQualityLateArrivingCallback) { // Catch the callback base::OnceCallback iso_cb; ON_CALL(hcic_interface_, ReadIsoLinkQuality) - .WillByDefault( - [&iso_cb](uint16_t /* iso_handle */, - base::OnceCallback cb) { + .WillByDefault([&iso_cb](uint16_t /* iso_handle */, + base::OnceCallback cb) { iso_cb = std::move(cb); }); auto handle = volatile_test_cig_create_cmpl_evt_.conn_handles[0]; @@ -2673,9 +2397,7 @@ TEST_F(IsoManagerTest, ReadIsoLinkQualityLateArrivingCallback) { IsoManager::GetInstance()->Stop(); // Call the callback and expect no call - EXPECT_CALL(*cig_callbacks_, - OnIsoLinkQualityRead(handle, _, _, _, _, _, _, _, _)) - .Times(0); + EXPECT_CALL(*cig_callbacks_, OnIsoLinkQualityRead(handle, _, _, _, _, _, _, _, _)).Times(0); ASSERT_FALSE(iso_cb.is_null()); std::vector buf(31); diff --git a/system/stack/test/common/mock_btif_config.h b/system/stack/test/common/mock_btif_config.h index 9f11c4387e4..85066714416 100644 --- a/system/stack/test/common/mock_btif_config.h +++ b/system/stack/test/common/mock_btif_config.h @@ -25,20 +25,18 @@ namespace bluetooth { namespace manager { class BtifConfigInterface { - public: - virtual bool GetBin(const std::string& section, const std::string& key, - uint8_t* value, size_t* length) = 0; - virtual size_t GetBinLength(const std::string& section, - const std::string& key) = 0; +public: + virtual bool GetBin(const std::string& section, const std::string& key, uint8_t* value, + size_t* length) = 0; + virtual size_t GetBinLength(const std::string& section, const std::string& key) = 0; virtual ~BtifConfigInterface() = default; }; class MockBtifConfigInterface : public BtifConfigInterface { - public: - MOCK_METHOD4(GetBin, bool(const std::string& section, const std::string& key, - uint8_t* value, size_t* length)); - MOCK_METHOD2(GetBinLength, - size_t(const std::string& section, const std::string& key)); +public: + MOCK_METHOD4(GetBin, bool(const std::string& section, const std::string& key, uint8_t* value, + size_t* length)); + MOCK_METHOD2(GetBinLength, size_t(const std::string& section, const std::string& key)); }; /** @@ -47,8 +45,7 @@ class MockBtifConfigInterface : public BtifConfigInterface { * @param mock_btif_config_interface pointer to mock btif config interface, * could be null */ -void SetMockBtifConfigInterface( - MockBtifConfigInterface* mock_btif_config_interface); +void SetMockBtifConfigInterface(MockBtifConfigInterface* mock_btif_config_interface); } // namespace manager } // namespace bluetooth diff --git a/system/stack/test/common/mock_btif_storage.cc b/system/stack/test/common/mock_btif_storage.cc index 442da31a827..ae11b0d3e4e 100644 --- a/system/stack/test/common/mock_btif_storage.cc +++ b/system/stack/test/common/mock_btif_storage.cc @@ -20,14 +20,11 @@ #include "stack/include/btm_sec_api_types.h" -static bluetooth::manager::MockBtifStorageInterface* btif_storage_interface = - nullptr; +static bluetooth::manager::MockBtifStorageInterface* btif_storage_interface = nullptr; void bluetooth::manager::SetMockBtifStorageInterface( - MockBtifStorageInterface* mock_btif_storage_interface) { + MockBtifStorageInterface* mock_btif_storage_interface) { btif_storage_interface = mock_btif_storage_interface; } -void btif_storage_load_bonded_eatt(void) { - btif_storage_interface->LoadBondedEatt(); -} +void btif_storage_load_bonded_eatt(void) { btif_storage_interface->LoadBondedEatt(); } diff --git a/system/stack/test/common/mock_btif_storage.h b/system/stack/test/common/mock_btif_storage.h index 19a2de2132b..3b20838756c 100644 --- a/system/stack/test/common/mock_btif_storage.h +++ b/system/stack/test/common/mock_btif_storage.h @@ -23,13 +23,13 @@ namespace bluetooth { namespace manager { class BtifStorageInterface { - public: +public: virtual void LoadBondedEatt(void) = 0; virtual ~BtifStorageInterface() = default; }; class MockBtifStorageInterface : public BtifStorageInterface { - public: +public: MOCK_METHOD0(LoadBondedEatt, void(void)); }; @@ -39,8 +39,7 @@ class MockBtifStorageInterface : public BtifStorageInterface { * @param mock_btif_storage_interface pointer to mock btm security * internal interface, could be null */ -void SetMockBtifStorageInterface( - MockBtifStorageInterface* mock_btif_storage_interface); +void SetMockBtifStorageInterface(MockBtifStorageInterface* mock_btif_storage_interface); } // namespace manager } // namespace bluetooth \ No newline at end of file diff --git a/system/stack/test/common/mock_btm_api_layer.cc b/system/stack/test/common/mock_btm_api_layer.cc index 93c5fdb4a87..cc9389289da 100644 --- a/system/stack/test/common/mock_btm_api_layer.cc +++ b/system/stack/test/common/mock_btm_api_layer.cc @@ -19,26 +19,22 @@ static bluetooth::manager::MockBtmApiInterface* btm_api_interface = nullptr; -void bluetooth::manager::SetMockBtmApiInterface( - MockBtmApiInterface* mock_btm_api_interface) { +void bluetooth::manager::SetMockBtmApiInterface(MockBtmApiInterface* mock_btm_api_interface) { btm_api_interface = mock_btm_api_interface; } -bool BTM_SetSecurityLevel(bool is_originator, const char* p_name, - uint8_t service_id, uint16_t sec_level, uint16_t psm, - uint32_t mx_proto_id, uint32_t mx_chan_id) { - return btm_api_interface->SetSecurityLevel(is_originator, p_name, service_id, - sec_level, psm, mx_proto_id, - mx_chan_id); +bool BTM_SetSecurityLevel(bool is_originator, const char* p_name, uint8_t service_id, + uint16_t sec_level, uint16_t psm, uint32_t mx_proto_id, + uint32_t mx_chan_id) { + return btm_api_interface->SetSecurityLevel(is_originator, p_name, service_id, sec_level, psm, + mx_proto_id, mx_chan_id); } -bool BTM_IsEncrypted(const RawAddress& remote_bd_addr, - tBT_TRANSPORT transport) { +bool BTM_IsEncrypted(const RawAddress& remote_bd_addr, tBT_TRANSPORT transport) { return btm_api_interface->IsEncrypted(remote_bd_addr, transport); } -bool BTM_IsLinkKeyKnown(const RawAddress& remote_bd_addr, - tBT_TRANSPORT transport) { +bool BTM_IsLinkKeyKnown(const RawAddress& remote_bd_addr, tBT_TRANSPORT transport) { return btm_api_interface->IsLinkKeyKnown(remote_bd_addr, transport); } diff --git a/system/stack/test/common/mock_btm_api_layer.h b/system/stack/test/common/mock_btm_api_layer.h index 46ae23cb523..b9a748d36cd 100644 --- a/system/stack/test/common/mock_btm_api_layer.h +++ b/system/stack/test/common/mock_btm_api_layer.h @@ -25,33 +25,25 @@ namespace bluetooth { namespace manager { class BtmApiInterface { - public: - virtual bool SetSecurityLevel(bool is_originator, const char* p_name, - uint8_t service_id, uint16_t sec_level, - uint16_t psm, uint32_t mx_proto_id, +public: + virtual bool SetSecurityLevel(bool is_originator, const char* p_name, uint8_t service_id, + uint16_t sec_level, uint16_t psm, uint32_t mx_proto_id, uint32_t mx_chan_id) = 0; - virtual uint8_t acl_link_role(const RawAddress& remote_bd_addr, - tBT_TRANSPORT transport) = 0; - virtual bool IsEncrypted(const RawAddress& remote_bd_addr, - tBT_TRANSPORT transport) = 0; - virtual bool IsLinkKeyKnown(const RawAddress& remote_bd_addr, - tBT_TRANSPORT transport) = 0; + virtual uint8_t acl_link_role(const RawAddress& remote_bd_addr, tBT_TRANSPORT transport) = 0; + virtual bool IsEncrypted(const RawAddress& remote_bd_addr, tBT_TRANSPORT transport) = 0; + virtual bool IsLinkKeyKnown(const RawAddress& remote_bd_addr, tBT_TRANSPORT transport) = 0; virtual uint8_t ReadSecKeySize(const RawAddress& remote_bd_addr) = 0; virtual ~BtmApiInterface() = default; }; class MockBtmApiInterface : public BtmApiInterface { - public: +public: MOCK_METHOD7(SetSecurityLevel, - bool(bool is_originator, const char* p_name, uint8_t service_id, - uint16_t sec_level, uint16_t psm, uint32_t mx_proto_id, - uint32_t mx_chan_id)); - MOCK_METHOD2(acl_link_role, uint8_t(const RawAddress& remote_bd_addr, - tBT_TRANSPORT transport)); - MOCK_METHOD2(IsEncrypted, - bool(const RawAddress& remote_bd_addr, tBT_TRANSPORT transport)); - MOCK_METHOD2(IsLinkKeyKnown, - bool(const RawAddress& remote_bd_addr, tBT_TRANSPORT transport)); + bool(bool is_originator, const char* p_name, uint8_t service_id, uint16_t sec_level, + uint16_t psm, uint32_t mx_proto_id, uint32_t mx_chan_id)); + MOCK_METHOD2(acl_link_role, uint8_t(const RawAddress& remote_bd_addr, tBT_TRANSPORT transport)); + MOCK_METHOD2(IsEncrypted, bool(const RawAddress& remote_bd_addr, tBT_TRANSPORT transport)); + MOCK_METHOD2(IsLinkKeyKnown, bool(const RawAddress& remote_bd_addr, tBT_TRANSPORT transport)); MOCK_METHOD1(ReadSecKeySize, uint8_t(const RawAddress& remote_bd_addr)); }; diff --git a/system/stack/test/common/mock_btm_layer.cc b/system/stack/test/common/mock_btm_layer.cc index cff191dd368..2dd17a3a7e3 100644 --- a/system/stack/test/common/mock_btm_layer.cc +++ b/system/stack/test/common/mock_btm_layer.cc @@ -22,27 +22,22 @@ #include "stack/include/rfcdefs.h" #include "types/raw_address.h" -static bluetooth::manager::MockBtmSecurityInternalInterface* - btm_security_internal_interface = nullptr; +static bluetooth::manager::MockBtmSecurityInternalInterface* btm_security_internal_interface = + nullptr; void bluetooth::manager::SetMockSecurityInternalInterface( - MockBtmSecurityInternalInterface* mock_btm_security_internal_interface) { + MockBtmSecurityInternalInterface* mock_btm_security_internal_interface) { btm_security_internal_interface = mock_btm_security_internal_interface; } -uint16_t BTM_GetMaxPacketSize(const RawAddress& addr) { - return RFCOMM_DEFAULT_MTU; -} +uint16_t BTM_GetMaxPacketSize(const RawAddress& addr) { return RFCOMM_DEFAULT_MTU; } -bool BTM_IsAclConnectionUp(const RawAddress& remote_bda, - tBT_TRANSPORT transport) { - return true; -} +bool BTM_IsAclConnectionUp(const RawAddress& remote_bda, tBT_TRANSPORT transport) { return true; } struct btm_client_interface_t btm_client_interface = { - .peer = - { - .BTM_IsAclConnectionUp = BTM_IsAclConnectionUp, - .BTM_GetMaxPacketSize = BTM_GetMaxPacketSize, - }, + .peer = + { + .BTM_IsAclConnectionUp = BTM_IsAclConnectionUp, + .BTM_GetMaxPacketSize = BTM_GetMaxPacketSize, + }, }; diff --git a/system/stack/test/common/mock_btm_layer.h b/system/stack/test/common/mock_btm_layer.h index 8c5c38e6123..91d6b6c55b7 100644 --- a/system/stack/test/common/mock_btm_layer.h +++ b/system/stack/test/common/mock_btm_layer.h @@ -27,22 +27,22 @@ namespace bluetooth { namespace manager { class BtmSecurityInternalInterface { - public: +public: virtual void AbortAccessRequest(const RawAddress& bd_addr) = 0; - virtual tBTM_STATUS MultiplexingProtocolAccessRequest( - const RawAddress& bd_addr, uint16_t psm, bool is_originator, - uint32_t mx_proto_id, uint32_t mx_chan_id, tBTM_SEC_CALLBACK* p_callback, - void* p_ref_data) = 0; + virtual tBTM_STATUS MultiplexingProtocolAccessRequest(const RawAddress& bd_addr, uint16_t psm, + bool is_originator, uint32_t mx_proto_id, + uint32_t mx_chan_id, + tBTM_SEC_CALLBACK* p_callback, + void* p_ref_data) = 0; virtual ~BtmSecurityInternalInterface() = default; }; class MockBtmSecurityInternalInterface : public BtmSecurityInternalInterface { - public: +public: MOCK_METHOD1(AbortAccessRequest, void(const RawAddress& bd_addr)); MOCK_METHOD7(MultiplexingProtocolAccessRequest, - tBTM_STATUS(const RawAddress& bd_addr, uint16_t psm, - bool is_originator, uint32_t mx_proto_id, - uint32_t mx_chan_id, tBTM_SEC_CALLBACK* p_callback, + tBTM_STATUS(const RawAddress& bd_addr, uint16_t psm, bool is_originator, + uint32_t mx_proto_id, uint32_t mx_chan_id, tBTM_SEC_CALLBACK* p_callback, void* p_ref_data)); }; @@ -53,7 +53,7 @@ class MockBtmSecurityInternalInterface : public BtmSecurityInternalInterface { * internal interface, could be null */ void SetMockSecurityInternalInterface( - MockBtmSecurityInternalInterface* mock_btm_security_internal_interface); + MockBtmSecurityInternalInterface* mock_btm_security_internal_interface); } // namespace manager } // namespace bluetooth diff --git a/system/stack/test/common/mock_eatt.cc b/system/stack/test/common/mock_eatt.cc index 96bbb4f4f20..b340e87aeb4 100644 --- a/system/stack/test/common/mock_eatt.cc +++ b/system/stack/test/common/mock_eatt.cc @@ -44,39 +44,32 @@ bool EattExtension::IsEattSupportedByPeer(const RawAddress& bd_addr) { return pimpl_->IsEattSupportedByPeer(bd_addr); } -void EattExtension::Connect(const RawAddress& bd_addr) { - pimpl_->Connect(bd_addr); -} +void EattExtension::Connect(const RawAddress& bd_addr) { pimpl_->Connect(bd_addr); } void EattExtension::Disconnect(const RawAddress& bd_addr, uint16_t cid) { pimpl_->Disconnect(bd_addr, cid); } -void EattExtension::Reconfigure(const RawAddress& bd_addr, uint16_t cid, - uint16_t mtu) { +void EattExtension::Reconfigure(const RawAddress& bd_addr, uint16_t cid, uint16_t mtu) { pimpl_->Reconfigure(bd_addr, cid, mtu); } void EattExtension::ReconfigureAll(const RawAddress& bd_addr, uint16_t mtu) { pimpl_->ReconfigureAll(bd_addr, mtu); } -EattChannel* EattExtension::FindEattChannelByCid(const RawAddress& bd_addr, - uint16_t cid) { +EattChannel* EattExtension::FindEattChannelByCid(const RawAddress& bd_addr, uint16_t cid) { return pimpl_->FindEattChannelByCid(bd_addr, cid); } -EattChannel* EattExtension::FindEattChannelByTransId(const RawAddress& bd_addr, - uint32_t trans_id) { +EattChannel* EattExtension::FindEattChannelByTransId(const RawAddress& bd_addr, uint32_t trans_id) { return pimpl_->FindEattChannelByTransId(bd_addr, trans_id); } -bool EattExtension::IsIndicationPending(const RawAddress& bd_addr, - uint16_t indication_handle) { +bool EattExtension::IsIndicationPending(const RawAddress& bd_addr, uint16_t indication_handle) { return pimpl_->IsIndicationPending(bd_addr, indication_handle); } -EattChannel* EattExtension::GetChannelAvailableForIndication( - const RawAddress& bd_addr) { +EattChannel* EattExtension::GetChannelAvailableForIndication(const RawAddress& bd_addr) { return pimpl_->GetChannelAvailableForIndication(bd_addr); } @@ -88,35 +81,29 @@ bool EattExtension::IsOutstandingMsgInSendQueue(const RawAddress& bd_addr) { return pimpl_->IsOutstandingMsgInSendQueue(bd_addr); } -EattChannel* EattExtension::GetChannelWithQueuedDataToSend( - const RawAddress& bd_addr) { +EattChannel* EattExtension::GetChannelWithQueuedDataToSend(const RawAddress& bd_addr) { return pimpl_->GetChannelWithQueuedDataToSend(bd_addr); } -EattChannel* EattExtension::GetChannelAvailableForClientRequest( - const RawAddress& bd_addr) { +EattChannel* EattExtension::GetChannelAvailableForClientRequest(const RawAddress& bd_addr) { return pimpl_->GetChannelAvailableForClientRequest(bd_addr); } /* Start stop GATT indication timer per CID */ -void EattExtension::StartIndicationConfirmationTimer(const RawAddress& bd_addr, - uint16_t cid) { +void EattExtension::StartIndicationConfirmationTimer(const RawAddress& bd_addr, uint16_t cid) { pimpl_->StartIndicationConfirmationTimer(bd_addr, cid); } -void EattExtension::StopIndicationConfirmationTimer(const RawAddress& bd_addr, - uint16_t cid) { +void EattExtension::StopIndicationConfirmationTimer(const RawAddress& bd_addr, uint16_t cid) { pimpl_->StopIndicationConfirmationTimer(bd_addr, cid); } /* Start stop application indication timeout */ -void EattExtension::StartAppIndicationTimer(const RawAddress& bd_addr, - uint16_t cid) { +void EattExtension::StartAppIndicationTimer(const RawAddress& bd_addr, uint16_t cid) { pimpl_->StartAppIndicationTimer(bd_addr, cid); } -void EattExtension::StopAppIndicationTimer(const RawAddress& bd_addr, - uint16_t cid) { +void EattExtension::StopAppIndicationTimer(const RawAddress& bd_addr, uint16_t cid) { pimpl_->StopAppIndicationTimer(bd_addr, cid); } diff --git a/system/stack/test/common/mock_eatt.h b/system/stack/test/common/mock_eatt.h index bbeb5022979..50b2d6aba2d 100644 --- a/system/stack/test/common/mock_eatt.h +++ b/system/stack/test/common/mock_eatt.h @@ -25,7 +25,7 @@ using bluetooth::eatt::EattChannel; using bluetooth::eatt::EattExtension; class MockEattExtension : public EattExtension { - public: +public: MockEattExtension() = default; MockEattExtension(const MockEattExtension&) = delete; MockEattExtension& operator=(const MockEattExtension&) = delete; @@ -36,35 +36,24 @@ class MockEattExtension : public EattExtension { MOCK_METHOD((void), Connect, (const RawAddress& bd_addr)); MOCK_METHOD((void), Disconnect, (const RawAddress& bd_addr, uint16_t cid)); - MOCK_METHOD((void), Reconfigure, - (const RawAddress& bd_addr, uint16_t cid, uint16_t mtu)); - MOCK_METHOD((void), ReconfigureAll, - (const RawAddress& bd_addr, uint16_t mtu)); + MOCK_METHOD((void), Reconfigure, (const RawAddress& bd_addr, uint16_t cid, uint16_t mtu)); + MOCK_METHOD((void), ReconfigureAll, (const RawAddress& bd_addr, uint16_t mtu)); MOCK_METHOD((bool), IsEattSupportedByPeer, (const RawAddress& bd_addr)); - MOCK_METHOD((EattChannel*), FindEattChannelByCid, - (const RawAddress& bd_addr, uint16_t cid)); + MOCK_METHOD((EattChannel*), FindEattChannelByCid, (const RawAddress& bd_addr, uint16_t cid)); MOCK_METHOD((EattChannel*), FindEattChannelByTransId, (const RawAddress& bd_addr, uint32_t trans_id)); - MOCK_METHOD((bool), IsIndicationPending, - (const RawAddress& bd_addr, uint16_t indication_handle)); - MOCK_METHOD((EattChannel*), GetChannelAvailableForIndication, - (const RawAddress& bd_addr)); + MOCK_METHOD((bool), IsIndicationPending, (const RawAddress& bd_addr, uint16_t indication_handle)); + MOCK_METHOD((EattChannel*), GetChannelAvailableForIndication, (const RawAddress& bd_addr)); MOCK_METHOD((void), FreeGattResources, (const RawAddress& bd_addr)); MOCK_METHOD((bool), IsOutstandingMsgInSendQueue, (const RawAddress& bd_addr)); - MOCK_METHOD((EattChannel*), GetChannelWithQueuedDataToSend, - (const RawAddress& bd_addr)); - MOCK_METHOD((EattChannel*), GetChannelAvailableForClientRequest, - (const RawAddress& bd_addr)); - MOCK_METHOD((void), StartIndicationConfirmationTimer, - (const RawAddress& bd_addr, uint16_t cid)); - MOCK_METHOD((void), StopIndicationConfirmationTimer, - (const RawAddress& bd_addr, uint16_t cid)); + MOCK_METHOD((EattChannel*), GetChannelWithQueuedDataToSend, (const RawAddress& bd_addr)); + MOCK_METHOD((EattChannel*), GetChannelAvailableForClientRequest, (const RawAddress& bd_addr)); + MOCK_METHOD((void), StartIndicationConfirmationTimer, (const RawAddress& bd_addr, uint16_t cid)); + MOCK_METHOD((void), StopIndicationConfirmationTimer, (const RawAddress& bd_addr, uint16_t cid)); - MOCK_METHOD((void), StartAppIndicationTimer, - (const RawAddress& bd_addr, uint16_t cid)); - MOCK_METHOD((void), StopAppIndicationTimer, - (const RawAddress& bd_addr, uint16_t cid)); + MOCK_METHOD((void), StartAppIndicationTimer, (const RawAddress& bd_addr, uint16_t cid)); + MOCK_METHOD((void), StopAppIndicationTimer, (const RawAddress& bd_addr, uint16_t cid)); MOCK_METHOD((void), Start, ()); MOCK_METHOD((void), Stop, ()); diff --git a/system/stack/test/common/mock_gatt_layer.cc b/system/stack/test/common/mock_gatt_layer.cc index 4df76281ec9..b1002c9bb23 100644 --- a/system/stack/test/common/mock_gatt_layer.cc +++ b/system/stack/test/common/mock_gatt_layer.cc @@ -21,8 +21,7 @@ static bluetooth::gatt::MockGattInterface* gatt_interface = nullptr; -void bluetooth::gatt::SetMockGattInterface( - MockGattInterface* mock_gatt_interface) { +void bluetooth::gatt::SetMockGattInterface(MockGattInterface* mock_gatt_interface) { gatt_interface = mock_gatt_interface; } @@ -30,12 +29,9 @@ bool gatt_profile_get_eatt_support(const RawAddress& peer_bda) { return gatt_interface->GetEattSupport(peer_bda); } -void gatt_cl_init_sr_status(tGATT_TCB& tcb) { - return gatt_interface->ClientInitServerStatus(tcb); -} +void gatt_cl_init_sr_status(tGATT_TCB& tcb) { return gatt_interface->ClientInitServerStatus(tcb); } -bool gatt_cl_read_sr_supp_feat_req( - const RawAddress& peer_bda, - base::OnceCallback cb) { +bool gatt_cl_read_sr_supp_feat_req(const RawAddress& peer_bda, + base::OnceCallback cb) { return gatt_interface->ClientReadSupportedFeatures(peer_bda, std::move(cb)); } diff --git a/system/stack/test/common/mock_gatt_layer.h b/system/stack/test/common/mock_gatt_layer.h index 2bfffa174cd..d899289ea96 100644 --- a/system/stack/test/common/mock_gatt_layer.h +++ b/system/stack/test/common/mock_gatt_layer.h @@ -26,17 +26,16 @@ namespace bluetooth { namespace gatt { class GattInterface { - public: +public: virtual void ClientInitServerStatus(tGATT_TCB& tcb) = 0; virtual bool ClientReadSupportedFeatures( - const RawAddress& peer_bda, - base::OnceCallback cb) = 0; + const RawAddress& peer_bda, base::OnceCallback cb) = 0; virtual bool GetEattSupport(const RawAddress& peer_bda) = 0; virtual ~GattInterface() = default; }; class MockGattInterface : public GattInterface { - public: +public: MOCK_METHOD1(ClientInitServerStatus, void(tGATT_TCB& tcb)); MOCK_METHOD2(ClientReadSupportedFeatures, bool(const RawAddress& peer_bda, diff --git a/system/stack/test/common/mock_hcic_layer.cc b/system/stack/test/common/mock_hcic_layer.cc index 57dadf93b69..6c12513f48a 100644 --- a/system/stack/test/common/mock_hcic_layer.cc +++ b/system/stack/test/common/mock_hcic_layer.cc @@ -19,30 +19,27 @@ static hcic::MockHcicInterface* hcic_interface = nullptr; -void hcic::SetMockHcicInterface(MockHcicInterface* interface) { - hcic_interface = interface; -} +void hcic::SetMockHcicInterface(MockHcicInterface* interface) { hcic_interface = interface; } -void btsnd_hcic_set_cig_params( - uint8_t cig_id, uint32_t sdu_itv_mtos, uint32_t sdu_itv_stom, uint8_t sca, - uint8_t packing, uint8_t framing, uint16_t max_trans_lat_stom, - uint16_t max_trans_lat_mtos, uint8_t cis_cnt, const EXT_CIS_CFG* cis_cfg, - base::OnceCallback cb) { +void btsnd_hcic_set_cig_params(uint8_t cig_id, uint32_t sdu_itv_mtos, uint32_t sdu_itv_stom, + uint8_t sca, uint8_t packing, uint8_t framing, + uint16_t max_trans_lat_stom, uint16_t max_trans_lat_mtos, + uint8_t cis_cnt, const EXT_CIS_CFG* cis_cfg, + base::OnceCallback cb) { struct bluetooth::hci::iso_manager::cig_create_params cig_params = { - .sdu_itv_mtos = sdu_itv_mtos, - .sdu_itv_stom = sdu_itv_stom, - .sca = sca, - .packing = packing, - .framing = framing, - .max_trans_lat_stom = max_trans_lat_stom, - .max_trans_lat_mtos = max_trans_lat_mtos, - .cis_cfgs = std::vector(cis_cfg, cis_cfg + cis_cnt), + .sdu_itv_mtos = sdu_itv_mtos, + .sdu_itv_stom = sdu_itv_stom, + .sca = sca, + .packing = packing, + .framing = framing, + .max_trans_lat_stom = max_trans_lat_stom, + .max_trans_lat_mtos = max_trans_lat_mtos, + .cis_cfgs = std::vector(cis_cfg, cis_cfg + cis_cnt), }; hcic_interface->SetCigParams(cig_id, std::move(cig_params), std::move(cb)); } -void btsnd_hcic_remove_cig(uint8_t cig_id, - base::OnceCallback cb) { +void btsnd_hcic_remove_cig(uint8_t cig_id, base::OnceCallback cb) { hcic_interface->RemoveCig(cig_id, std::move(cb)); } @@ -55,47 +52,42 @@ static void btsnd_hcic_disconnect(uint16_t handle, uint8_t reason) { hcic_interface->Disconnect(handle, reason); } -void btsnd_hcic_setup_iso_data_path( - uint16_t iso_handle, uint8_t data_path_dir, uint8_t data_path_id, - uint8_t codec_id_format, uint16_t codec_id_company, - uint16_t codec_id_vendor, uint32_t controller_delay, - std::vector codec_conf, - base::OnceCallback cb) { - hcic_interface->SetupIsoDataPath(iso_handle, data_path_dir, data_path_id, - codec_id_format, codec_id_company, - codec_id_vendor, controller_delay, +void btsnd_hcic_setup_iso_data_path(uint16_t iso_handle, uint8_t data_path_dir, + uint8_t data_path_id, uint8_t codec_id_format, + uint16_t codec_id_company, uint16_t codec_id_vendor, + uint32_t controller_delay, std::vector codec_conf, + base::OnceCallback cb) { + hcic_interface->SetupIsoDataPath(iso_handle, data_path_dir, data_path_id, codec_id_format, + codec_id_company, codec_id_vendor, controller_delay, std::move(codec_conf), std::move(cb)); } -void btsnd_hcic_remove_iso_data_path( - uint16_t iso_handle, uint8_t data_path_dir, - base::OnceCallback cb) { +void btsnd_hcic_remove_iso_data_path(uint16_t iso_handle, uint8_t data_path_dir, + base::OnceCallback cb) { hcic_interface->RemoveIsoDataPath(iso_handle, data_path_dir, std::move(cb)); } -void btsnd_hcic_read_iso_link_quality( - uint16_t iso_handle, base::OnceCallback cb) { +void btsnd_hcic_read_iso_link_quality(uint16_t iso_handle, + base::OnceCallback cb) { hcic_interface->ReadIsoLinkQuality(iso_handle, std::move(cb)); } -void btsnd_hcic_create_big(uint8_t big_handle, uint8_t adv_handle, - uint8_t num_bis, uint32_t sdu_itv, - uint16_t max_sdu_size, uint16_t transport_latency, - uint8_t rtn, uint8_t phy, uint8_t packing, - uint8_t framing, uint8_t enc, +void btsnd_hcic_create_big(uint8_t big_handle, uint8_t adv_handle, uint8_t num_bis, + uint32_t sdu_itv, uint16_t max_sdu_size, uint16_t transport_latency, + uint8_t rtn, uint8_t phy, uint8_t packing, uint8_t framing, uint8_t enc, std::array bcst_code) { struct bluetooth::hci::iso_manager::big_create_params big_params = { - .adv_handle = adv_handle, - .num_bis = num_bis, - .sdu_itv = sdu_itv, - .max_sdu_size = max_sdu_size, - .max_transport_latency = transport_latency, - .rtn = rtn, - .phy = phy, - .packing = packing, - .framing = framing, - .enc = enc, - .enc_code = std::move(bcst_code), + .adv_handle = adv_handle, + .num_bis = num_bis, + .sdu_itv = sdu_itv, + .max_sdu_size = max_sdu_size, + .max_transport_latency = transport_latency, + .rtn = rtn, + .phy = phy, + .packing = packing, + .framing = framing, + .enc = enc, + .enc_code = std::move(bcst_code), }; hcic_interface->CreateBig(big_handle, std::move(big_params)); } @@ -107,22 +99,20 @@ void btsnd_hcic_term_big(uint8_t big_handle, uint8_t reason) { namespace bluetooth::legacy::hci { class MockInterface : public Interface { - public: +public: virtual void Disconnect(uint16_t handle, uint8_t reason) const override { btsnd_hcic_disconnect(handle, reason); } - virtual void ChangeConnectionPacketType( - uint16_t /* handle */, uint16_t /* packet_types */) const override { + virtual void ChangeConnectionPacketType(uint16_t /* handle */, + uint16_t /* packet_types */) const override { FAIL(); } - virtual void StartRoleSwitch(const RawAddress& /* bd_addr */, - uint8_t /* role */) const override { + virtual void StartRoleSwitch(const RawAddress& /* bd_addr */, uint8_t /* role */) const override { FAIL(); } - virtual void ConfigureDataPath( - hci_data_direction_t /* data_path_direction */, - uint8_t /* data_path_id */, - std::vector /* vendor_config */) const override { + virtual void ConfigureDataPath(hci_data_direction_t /* data_path_direction */, + uint8_t /* data_path_id */, + std::vector /* vendor_config */) const override { FAIL(); } } interface_; diff --git a/system/stack/test/common/mock_hcic_layer.h b/system/stack/test/common/mock_hcic_layer.h index 33cbf734351..ff8c38a62ba 100644 --- a/system/stack/test/common/mock_hcic_layer.h +++ b/system/stack/test/common/mock_hcic_layer.h @@ -25,42 +25,36 @@ namespace hcic { class HcicInterface { - public: +public: // iso_manager::cig_create_params is a workaround for the 10 params function // limitation that gmock sets - virtual void SetCigParams( - uint8_t cig_id, - struct bluetooth::hci::iso_manager::cig_create_params cig_params, - base::OnceCallback cb) = 0; + virtual void SetCigParams(uint8_t cig_id, + struct bluetooth::hci::iso_manager::cig_create_params cig_params, + base::OnceCallback cb) = 0; - virtual void RemoveCig(uint8_t cig_id, - base::OnceCallback cb) = 0; + virtual void RemoveCig(uint8_t cig_id, base::OnceCallback cb) = 0; - virtual void CreateCis(uint8_t num_cis, - const EXT_CIS_CREATE_CFG* cis_create_cfg, + virtual void CreateCis(uint8_t num_cis, const EXT_CIS_CREATE_CFG* cis_create_cfg, base::OnceCallback cb) = 0; virtual void Disconnect(uint16_t handle, uint8_t reason) = 0; - virtual void SetupIsoDataPath( - uint16_t iso_handle, uint8_t data_path_dir, uint8_t data_path_id, - uint8_t codec_id_format, uint16_t codec_id_company, - uint16_t codec_id_vendor, uint32_t controller_delay, - std::vector codec_conf, - base::OnceCallback cb) = 0; + virtual void SetupIsoDataPath(uint16_t iso_handle, uint8_t data_path_dir, uint8_t data_path_id, + uint8_t codec_id_format, uint16_t codec_id_company, + uint16_t codec_id_vendor, uint32_t controller_delay, + std::vector codec_conf, + base::OnceCallback cb) = 0; - virtual void RemoveIsoDataPath( - uint16_t iso_handle, uint8_t data_path_dir, - base::OnceCallback cb) = 0; + virtual void RemoveIsoDataPath(uint16_t iso_handle, uint8_t data_path_dir, + base::OnceCallback cb) = 0; - virtual void ReadIsoLinkQuality( - uint16_t iso_handle, base::OnceCallback cb) = 0; + virtual void ReadIsoLinkQuality(uint16_t iso_handle, + base::OnceCallback cb) = 0; // iso_manager::big_create_params is a workaround for the 10 params function // limitation that gmock sets - virtual void CreateBig( - uint8_t big_handle, - struct bluetooth::hci::iso_manager::big_create_params big_params) = 0; + virtual void CreateBig(uint8_t big_handle, + struct bluetooth::hci::iso_manager::big_create_params big_params) = 0; virtual void TerminateBig(uint8_t big_handle, uint8_t reason) = 0; @@ -68,15 +62,13 @@ class HcicInterface { }; class MockHcicInterface : public HcicInterface { - public: +public: MOCK_METHOD((void), SetCigParams, - (uint8_t cig_id, - struct bluetooth::hci::iso_manager::cig_create_params cig_params, + (uint8_t cig_id, struct bluetooth::hci::iso_manager::cig_create_params cig_params, base::OnceCallback cb), (override)); - MOCK_METHOD((void), RemoveCig, - (uint8_t cig_id, base::OnceCallback cb), + MOCK_METHOD((void), RemoveCig, (uint8_t cig_id, base::OnceCallback cb), (override)); MOCK_METHOD((void), CreateCis, @@ -84,14 +76,12 @@ class MockHcicInterface : public HcicInterface { base::OnceCallback cb), (override)); - MOCK_METHOD((void), Disconnect, (uint16_t handle, uint8_t reason), - (override)); + MOCK_METHOD((void), Disconnect, (uint16_t handle, uint8_t reason), (override)); MOCK_METHOD((void), SetupIsoDataPath, (uint16_t iso_handle, uint8_t data_path_dir, uint8_t data_path_id, - uint8_t codec_id_format, uint16_t codec_id_company, - uint16_t codec_id_vendor, uint32_t controller_delay, - std::vector codec_conf, + uint8_t codec_id_format, uint16_t codec_id_company, uint16_t codec_id_vendor, + uint32_t controller_delay, std::vector codec_conf, base::OnceCallback cb), (override)); @@ -101,18 +91,14 @@ class MockHcicInterface : public HcicInterface { (override)); MOCK_METHOD((void), ReadIsoLinkQuality, - (uint16_t iso_handle, - base::OnceCallback cb), - (override)); - - MOCK_METHOD( - (void), CreateBig, - (uint8_t big_handle, - struct bluetooth::hci::iso_manager::big_create_params big_params), - (override)); + (uint16_t iso_handle, base::OnceCallback cb), (override)); - MOCK_METHOD((void), TerminateBig, (uint8_t big_handle, uint8_t reason), + MOCK_METHOD((void), CreateBig, + (uint8_t big_handle, + struct bluetooth::hci::iso_manager::big_create_params big_params), (override)); + + MOCK_METHOD((void), TerminateBig, (uint8_t big_handle, uint8_t reason), (override)); }; void SetMockHcicInterface(MockHcicInterface* mock_hcic_interface); diff --git a/system/stack/test/common/mock_l2cap_layer.cc b/system/stack/test/common/mock_l2cap_layer.cc index a3127b6ae52..905b1bd39b5 100644 --- a/system/stack/test/common/mock_l2cap_layer.cc +++ b/system/stack/test/common/mock_l2cap_layer.cc @@ -25,18 +25,14 @@ static bluetooth::l2cap::MockL2capInterface* l2cap_interface = nullptr; -void bluetooth::l2cap::SetMockInterface( - MockL2capInterface* mock_l2cap_interface) { +void bluetooth::l2cap::SetMockInterface(MockL2capInterface* mock_l2cap_interface) { l2cap_interface = mock_l2cap_interface; } -tL2C_CCB* l2cu_find_ccb_by_cid(tL2C_LCB* p_lcb, uint16_t local_cid) { - return nullptr; -} +tL2C_CCB* l2cu_find_ccb_by_cid(tL2C_LCB* p_lcb, uint16_t local_cid) { return nullptr; } -uint16_t L2CA_Register(uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info, - bool enable_snoop, tL2CAP_ERTM_INFO* p_ertm_info, - uint16_t my_mtu, uint16_t required_remote_mtu, +uint16_t L2CA_Register(uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info, bool enable_snoop, + tL2CAP_ERTM_INFO* p_ertm_info, uint16_t my_mtu, uint16_t required_remote_mtu, uint16_t sec_level) { bluetooth::log::verbose("psm={}, enable_snoop={}", psm, enable_snoop); return l2cap_interface->Register(psm, p_cb_info, enable_snoop, p_ertm_info); @@ -46,13 +42,9 @@ uint16_t L2CA_ConnectReq(uint16_t psm, const RawAddress& bd_addr) { return l2cap_interface->ConnectRequest(psm, bd_addr); } -bool L2CA_DisconnectReq(uint16_t cid) { - return l2cap_interface->DisconnectRequest(cid); -} +bool L2CA_DisconnectReq(uint16_t cid) { return l2cap_interface->DisconnectRequest(cid); } -bool L2CA_DisconnectRsp(uint16_t cid) { - return l2cap_interface->DisconnectResponse(cid); -} +bool L2CA_DisconnectRsp(uint16_t cid) { return l2cap_interface->DisconnectResponse(cid); } bool L2CA_ConfigReq(uint16_t cid, tL2CAP_CFG_INFO* p_cfg) { return l2cap_interface->ConfigRequest(cid, p_cfg); @@ -66,38 +58,31 @@ tL2CAP_DW_RESULT L2CA_DataWrite(uint16_t cid, BT_HDR* p_data) { return l2cap_interface->DataWrite(cid, p_data); } -uint16_t L2CA_RegisterLECoc(uint16_t psm, const tL2CAP_APPL_INFO& cb_info, - uint16_t sec_level, tL2CAP_LE_CFG_INFO cfg) { +uint16_t L2CA_RegisterLECoc(uint16_t psm, const tL2CAP_APPL_INFO& cb_info, uint16_t sec_level, + tL2CAP_LE_CFG_INFO cfg) { return l2cap_interface->RegisterLECoc(psm, cb_info, sec_level); } -void L2CA_DeregisterLECoc(uint16_t psm) { - return l2cap_interface->DeregisterLECoc(psm); -} +void L2CA_DeregisterLECoc(uint16_t psm) { return l2cap_interface->DeregisterLECoc(psm); } tHCI_ROLE L2CA_GetBleConnRole(const RawAddress& bd_addr) { return to_hci_role(l2cap_interface->GetBleConnRole(bd_addr)); } -std::vector L2CA_ConnectCreditBasedReq(uint16_t psm, - const RawAddress& bd_addr, - tL2CAP_LE_CFG_INFO* p_cfg) { +std::vector L2CA_ConnectCreditBasedReq(uint16_t psm, const RawAddress& bd_addr, + tL2CAP_LE_CFG_INFO* p_cfg) { return l2cap_interface->ConnectCreditBasedReq(psm, bd_addr, p_cfg); } -bool L2CA_ConnectCreditBasedRsp(const RawAddress& bd_addr, uint8_t id, - std::vector &lcids, - uint16_t result, - tL2CAP_LE_CFG_INFO* p_cfg) { +bool L2CA_ConnectCreditBasedRsp(const RawAddress& bd_addr, uint8_t id, std::vector& lcids, + uint16_t result, tL2CAP_LE_CFG_INFO* p_cfg) { return l2cap_interface->ConnectCreditBasedRsp(bd_addr, id, lcids, result, p_cfg); } -bool L2CA_ReconfigCreditBasedConnsReq(const RawAddress& bd_addr, std::vector &lcids, +bool L2CA_ReconfigCreditBasedConnsReq(const RawAddress& bd_addr, std::vector& lcids, tL2CAP_LE_CFG_INFO* peer_cfg) { return l2cap_interface->ReconfigCreditBasedConnsReq(bd_addr, lcids, peer_cfg); } uint16_t L2CA_LeCreditDefault() { return l2cap_interface->LeCreditDefault(); } -uint16_t L2CA_LeCreditThreshold() { - return l2cap_interface->LeCreditThreshold(); -} +uint16_t L2CA_LeCreditThreshold() { return l2cap_interface->LeCreditThreshold(); } diff --git a/system/stack/test/common/mock_l2cap_layer.h b/system/stack/test/common/mock_l2cap_layer.h index 869eeb044c6..242001ed626 100644 --- a/system/stack/test/common/mock_l2cap_layer.h +++ b/system/stack/test/common/mock_l2cap_layer.h @@ -29,65 +29,56 @@ namespace bluetooth { namespace l2cap { class L2capInterface { - public: - virtual uint16_t Register(uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info, - bool enable_snoop, +public: + virtual uint16_t Register(uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info, bool enable_snoop, tL2CAP_ERTM_INFO* p_ertm_info) = 0; virtual uint16_t ConnectRequest(uint16_t psm, const RawAddress& bd_addr) = 0; - virtual bool ConnectResponse(const RawAddress& bd_addr, uint8_t id, - uint16_t lcid, uint16_t result, - uint16_t status) = 0; + virtual bool ConnectResponse(const RawAddress& bd_addr, uint8_t id, uint16_t lcid, + uint16_t result, uint16_t status) = 0; virtual bool DisconnectRequest(uint16_t cid) = 0; virtual bool DisconnectResponse(uint16_t cid) = 0; virtual bool ConfigRequest(uint16_t cid, tL2CAP_CFG_INFO* p_cfg) = 0; virtual bool ConfigResponse(uint16_t cid, tL2CAP_CFG_INFO* p_cfg) = 0; virtual tL2CAP_DW_RESULT DataWrite(uint16_t cid, BT_HDR* p_data) = 0; - virtual uint16_t RegisterLECoc(uint16_t psm, const tL2CAP_APPL_INFO &cb_info, uint16_t sec_level) = 0; + virtual uint16_t RegisterLECoc(uint16_t psm, const tL2CAP_APPL_INFO& cb_info, + uint16_t sec_level) = 0; virtual void DeregisterLECoc(uint16_t psm) = 0; virtual bool ConnectCreditBasedRsp(const RawAddress& bd_addr, uint8_t id, - std::vector &lcids, - uint16_t result, - tL2CAP_LE_CFG_INFO* p_cfg) = 0; - virtual std::vector ConnectCreditBasedReq(uint16_t psm, - const RawAddress& bd_addr, - tL2CAP_LE_CFG_INFO* p_cfg) = 0; - virtual bool ReconfigCreditBasedConnsReq(const RawAddress& bd_addr, std::vector &lcids, - tL2CAP_LE_CFG_INFO* peer_cfg) = 0; + std::vector& lcids, uint16_t result, + tL2CAP_LE_CFG_INFO* p_cfg) = 0; + virtual std::vector ConnectCreditBasedReq(uint16_t psm, const RawAddress& bd_addr, + tL2CAP_LE_CFG_INFO* p_cfg) = 0; + virtual bool ReconfigCreditBasedConnsReq(const RawAddress& bd_addr, std::vector& lcids, + tL2CAP_LE_CFG_INFO* peer_cfg) = 0; virtual uint16_t LeCreditDefault() = 0; virtual uint16_t LeCreditThreshold() = 0; virtual ~L2capInterface() = default; }; class MockL2capInterface : public L2capInterface { - public: - MOCK_METHOD4(Register, - uint16_t(uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info, - bool enable_snoop, tL2CAP_ERTM_INFO* p_ertm_info)); - MOCK_METHOD2(ConnectRequest, - uint16_t(uint16_t psm, const RawAddress& bd_addr)); - MOCK_METHOD5(ConnectResponse, - bool(const RawAddress& bd_addr, uint8_t id, uint16_t lcid, - uint16_t result, uint16_t status)); +public: + MOCK_METHOD4(Register, uint16_t(uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info, + bool enable_snoop, tL2CAP_ERTM_INFO* p_ertm_info)); + MOCK_METHOD2(ConnectRequest, uint16_t(uint16_t psm, const RawAddress& bd_addr)); + MOCK_METHOD5(ConnectResponse, bool(const RawAddress& bd_addr, uint8_t id, uint16_t lcid, + uint16_t result, uint16_t status)); MOCK_METHOD1(DisconnectRequest, bool(uint16_t cid)); MOCK_METHOD1(DisconnectResponse, bool(uint16_t cid)); MOCK_METHOD2(ConfigRequest, bool(uint16_t cid, tL2CAP_CFG_INFO* p_cfg)); MOCK_METHOD2(ConfigResponse, bool(uint16_t cid, tL2CAP_CFG_INFO* p_cfg)); MOCK_METHOD2(DataWrite, tL2CAP_DW_RESULT(uint16_t cid, BT_HDR* p_data)); MOCK_METHOD3(RegisterLECoc, - uint16_t(uint16_t psm, const tL2CAP_APPL_INFO &cb_info, uint16_t sec_level)); + uint16_t(uint16_t psm, const tL2CAP_APPL_INFO& cb_info, uint16_t sec_level)); MOCK_METHOD1(DeregisterLECoc, void(uint16_t psm)); MOCK_METHOD1(GetBleConnRole, uint8_t(const RawAddress& bd_addr)); MOCK_METHOD5(ConnectCreditBasedRsp, - bool(const RawAddress& p_bd_addr, uint8_t id, - std::vector &lcids, - uint16_t result, - tL2CAP_LE_CFG_INFO* p_cfg)); - MOCK_METHOD3(ConnectCreditBasedReq, - std::vector (uint16_t psm, - const RawAddress& bd_addr, - tL2CAP_LE_CFG_INFO* p_cfg)); + bool(const RawAddress& p_bd_addr, uint8_t id, std::vector& lcids, + uint16_t result, tL2CAP_LE_CFG_INFO* p_cfg)); + MOCK_METHOD3(ConnectCreditBasedReq, std::vector(uint16_t psm, const RawAddress& bd_addr, + tL2CAP_LE_CFG_INFO* p_cfg)); MOCK_METHOD3(ReconfigCreditBasedConnsReq, - bool(const RawAddress& p_bd_addr, std::vector &lcids, tL2CAP_LE_CFG_INFO* peer_cfg)); + bool(const RawAddress& p_bd_addr, std::vector& lcids, + tL2CAP_LE_CFG_INFO* peer_cfg)); MOCK_METHOD(uint16_t, LeCreditDefault, ()); MOCK_METHOD(uint16_t, LeCreditThreshold, ()); }; diff --git a/system/stack/test/common/mock_stack_avdt_msg.cc b/system/stack/test/common/mock_stack_avdt_msg.cc index 4cddd52e585..86848618452 100644 --- a/system/stack/test/common/mock_stack_avdt_msg.cc +++ b/system/stack/test/common/mock_stack_avdt_msg.cc @@ -32,21 +32,13 @@ void avdt_msg_send_rsp(AvdtpCcb* p_ccb, uint8_t sig_id, tAVDT_MSG* p_params) { _rsp_sig_ids.push_back(sig_id); } -size_t mock_avdt_msg_send_rsp_get_count(void) { - return _rsp_sig_ids.size(); -} +size_t mock_avdt_msg_send_rsp_get_count(void) { return _rsp_sig_ids.size(); } -void mock_avdt_msg_send_rsp_clear_history(void) { - _rsp_sig_ids.clear(); -} +void mock_avdt_msg_send_rsp_clear_history(void) { _rsp_sig_ids.clear(); } -uint8_t mock_avdt_msg_send_rsp_get_sig_id_at(size_t nth) { - return _rsp_sig_ids[nth]; -} +uint8_t mock_avdt_msg_send_rsp_get_sig_id_at(size_t nth) { return _rsp_sig_ids[nth]; } -void avdt_msg_ind(AvdtpCcb* p_ccb, BT_HDR* p_buf) { - inc_func_call_count(__func__); -} +void avdt_msg_ind(AvdtpCcb* p_ccb, BT_HDR* p_buf) { inc_func_call_count(__func__); } void avdt_msg_send_rej(AvdtpCcb* p_ccb, uint8_t sig_id, tAVDT_MSG* p_params) { inc_func_call_count(__func__); @@ -54,23 +46,16 @@ void avdt_msg_send_rej(AvdtpCcb* p_ccb, uint8_t sig_id, tAVDT_MSG* p_params) { static std::vector _cmd_sig_ids{}; -void avdt_msg_send_cmd(AvdtpCcb* p_ccb, void* p_scb, uint8_t sig_id, - tAVDT_MSG* p_params) { +void avdt_msg_send_cmd(AvdtpCcb* p_ccb, void* p_scb, uint8_t sig_id, tAVDT_MSG* p_params) { inc_func_call_count(__func__); _cmd_sig_ids.push_back(sig_id); } -size_t mock_avdt_msg_send_cmd_get_count(void) { - return _cmd_sig_ids.size(); -} +size_t mock_avdt_msg_send_cmd_get_count(void) { return _cmd_sig_ids.size(); } -void mock_avdt_msg_send_cmd_clear_history(void) { - _cmd_sig_ids.clear(); -} +void mock_avdt_msg_send_cmd_clear_history(void) { _cmd_sig_ids.clear(); } -uint8_t mock_avdt_msg_send_cmd_get_sig_id_at(size_t nth) { - return _cmd_sig_ids[nth]; -} +uint8_t mock_avdt_msg_send_cmd_get_sig_id_at(size_t nth) { return _cmd_sig_ids[nth]; } bool avdt_msg_send(AvdtpCcb* p_ccb, BT_HDR* p_msg) { inc_func_call_count(__func__); diff --git a/system/stack/test/common/stack_test_packet_utils.cc b/system/stack/test/common/stack_test_packet_utils.cc index 95afa5159c7..841d331a8a9 100644 --- a/system/stack/test/common/stack_test_packet_utils.cc +++ b/system/stack/test/common/stack_test_packet_utils.cc @@ -28,8 +28,7 @@ namespace bluetooth { -std::vector CreateL2capDataPacket(uint16_t lcid, - const std::vector& data) { +std::vector CreateL2capDataPacket(uint16_t lcid, const std::vector& data) { // Data in little endian order std::vector result; auto data_size = static_cast(data.size()); @@ -71,8 +70,7 @@ BT_HDR* AllocateWrappedIncomingL2capAclPacket(const uint8_t* acl_packet_bytes, return packet; } -BT_HDR* AllocateWrappedIncomingL2capAclPacket( - const std::vector& buffer) { +BT_HDR* AllocateWrappedIncomingL2capAclPacket(const std::vector& buffer) { return AllocateWrappedIncomingL2capAclPacket(buffer.data(), buffer.size()); } @@ -81,20 +79,17 @@ BT_HDR* AllocateWrappedOutgoingL2capAclPacket(const uint8_t* acl_packet_bytes, size_t acl_l2cap_header_size = 4 + L2CAP_PKT_OVERHEAD; log::assert_that(L2CAP_MIN_OFFSET >= static_cast(acl_l2cap_header_size), "invalid acl l2cap header size"); - size_t packet_size = - BT_HDR_SIZE + L2CAP_MIN_OFFSET + buffer_length - acl_l2cap_header_size; + size_t packet_size = BT_HDR_SIZE + L2CAP_MIN_OFFSET + buffer_length - acl_l2cap_header_size; auto packet = reinterpret_cast(osi_malloc(packet_size)); packet->offset = L2CAP_MIN_OFFSET; packet->len = static_cast(buffer_length - acl_l2cap_header_size); packet->layer_specific = 0; packet->event = 0; - memcpy(packet->data + packet->offset - acl_l2cap_header_size, - acl_packet_bytes, buffer_length); + memcpy(packet->data + packet->offset - acl_l2cap_header_size, acl_packet_bytes, buffer_length); return packet; } -BT_HDR* AllocateWrappedOutgoingL2capAclPacket( - const std::vector& buffer) { +BT_HDR* AllocateWrappedOutgoingL2capAclPacket(const std::vector& buffer) { return AllocateWrappedOutgoingL2capAclPacket(buffer.data(), buffer.size()); } diff --git a/system/stack/test/common/stack_test_packet_utils.h b/system/stack/test/common/stack_test_packet_utils.h index ccb88a21460..80484097331 100644 --- a/system/stack/test/common/stack_test_packet_utils.h +++ b/system/stack/test/common/stack_test_packet_utils.h @@ -18,6 +18,7 @@ #pragma once #include + #include "stack/include/bt_hdr.h" namespace bluetooth { @@ -29,8 +30,7 @@ namespace bluetooth { * @param data * @return vector of bytes */ -std::vector CreateL2capDataPacket(uint16_t lcid, - const std::vector& data); +std::vector CreateL2capDataPacket(uint16_t lcid, const std::vector& data); /** * Create ACL data packet @@ -57,8 +57,7 @@ std::vector CreateAclPacket(uint16_t handle, uint8_t pb, uint8_t bc, */ BT_HDR* AllocateWrappedIncomingL2capAclPacket(const uint8_t* acl_packet_bytes, size_t buffer_length); -BT_HDR* AllocateWrappedIncomingL2capAclPacket( - const std::vector& buffer); +BT_HDR* AllocateWrappedIncomingL2capAclPacket(const std::vector& buffer); /** * Given an array of ACL packet bytes from BTSNOOP log, allocate an OSI @@ -73,7 +72,6 @@ BT_HDR* AllocateWrappedIncomingL2capAclPacket( */ BT_HDR* AllocateWrappedOutgoingL2capAclPacket(const uint8_t* acl_packet_bytes, size_t buffer_length); -BT_HDR* AllocateWrappedOutgoingL2capAclPacket( - const std::vector& buffer); +BT_HDR* AllocateWrappedOutgoingL2capAclPacket(const std::vector& buffer); } // namespace bluetooth diff --git a/system/stack/test/eatt/eatt_test.cc b/system/stack/test/eatt/eatt_test.cc index 18d7866dbcd..52f888f7785 100644 --- a/system/stack/test/eatt/eatt_test.cc +++ b/system/stack/test/eatt/eatt_test.cc @@ -56,8 +56,7 @@ static tGATT_TCB test_tcb; void btif_storage_add_eatt_supported(const RawAddress& addr) { return; } void gatt_consolidate(const RawAddress& identity_addr, const RawAddress& rpa) {} void gatt_data_process(tGATT_TCB& tcb, uint16_t cid, BT_HDR* p_buf) { return; } -tGATT_TCB* gatt_find_tcb_by_addr(const RawAddress& bda, - tBT_TRANSPORT transport) { +tGATT_TCB* gatt_find_tcb_by_addr(const RawAddress& bda, tBT_TRANSPORT transport) { log::info(""); return &test_tcb; } @@ -66,23 +65,21 @@ namespace { const RawAddress test_address({0x11, 0x11, 0x11, 0x11, 0x11, 0x11}); class EattTest : public testing::Test { - protected: - void ConnectDeviceEattSupported(int num_of_accepted_connections, - bool collision = false) { +protected: + void ConnectDeviceEattSupported(int num_of_accepted_connections, bool collision = false) { ON_CALL(gatt_interface_, ClientReadSupportedFeatures) - .WillByDefault( - [](const RawAddress& addr, - base::OnceCallback cb) { + .WillByDefault([](const RawAddress& addr, + base::OnceCallback cb) { std::move(cb).Run(addr, BLE_GATT_SVR_SUP_FEAT_EATT_BITMASK); return true; }); - ON_CALL(gatt_interface_, GetEattSupport) - .WillByDefault([](const RawAddress& addr) { return true; }); + ON_CALL(gatt_interface_, GetEattSupport).WillByDefault([](const RawAddress& addr) { + return true; + }); std::vector test_local_cids{61, 62, 63, 64, 65}; - EXPECT_CALL(l2cap_interface_, - ConnectCreditBasedReq(BT_PSM_EATT, test_address, _)) - .WillOnce(Return(test_local_cids)); + EXPECT_CALL(l2cap_interface_, ConnectCreditBasedReq(BT_PSM_EATT, test_address, _)) + .WillOnce(Return(test_local_cids)); eatt_instance_->Connect(test_address); @@ -90,9 +87,7 @@ class EattTest : public testing::Test { /* Collision should be handled only if all channels has been rejected in * first place.*/ if (num_of_accepted_connections == 0) { - EXPECT_CALL(l2cap_interface_, - ConnectCreditBasedReq(BT_PSM_EATT, test_address, _)) - .Times(1); + EXPECT_CALL(l2cap_interface_, ConnectCreditBasedReq(BT_PSM_EATT, test_address, _)).Times(1); } l2cap_app_info_.pL2CA_CreditBasedCollisionInd_Cb(test_address); @@ -100,14 +95,13 @@ class EattTest : public testing::Test { int i = 0; for (uint16_t cid : test_local_cids) { - EattChannel* channel = - eatt_instance_->FindEattChannelByCid(test_address, cid); + EattChannel* channel = eatt_instance_->FindEattChannelByCid(test_address, cid); ASSERT_TRUE(channel != nullptr); ASSERT_TRUE(channel->state_ == EattChannelState::EATT_CHANNEL_PENDING); if (i < num_of_accepted_connections) { - l2cap_app_info_.pL2CA_CreditBasedConnectCfm_Cb( - test_address, cid, EATT_MIN_MTU_MPS, L2CAP_CONN_OK); + l2cap_app_info_.pL2CA_CreditBasedConnectCfm_Cb(test_address, cid, EATT_MIN_MTU_MPS, + L2CAP_CONN_OK); connected_cids_.push_back(cid); ASSERT_TRUE(channel->state_ == EattChannelState::EATT_CHANNEL_OPENED); @@ -115,8 +109,7 @@ class EattTest : public testing::Test { } else { l2cap_app_info_.pL2CA_Error_Cb(cid, L2CAP_CONN_NO_RESOURCES); - EattChannel* channel = - eatt_instance_->FindEattChannelByCid(test_address, cid); + EattChannel* channel = eatt_instance_->FindEattChannelByCid(test_address, cid); ASSERT_TRUE(channel == nullptr); } i++; @@ -130,50 +123,46 @@ class EattTest : public testing::Test { base::OnceCallback eatt_supp_feat_cb; ON_CALL(gatt_interface_, ClientReadSupportedFeatures) - .WillByDefault( - [&eatt_supp_feat_cb]( - const RawAddress& addr, - base::OnceCallback cb) { - eatt_supp_feat_cb = std::move(cb); - return true; - }); + .WillByDefault( + [&eatt_supp_feat_cb](const RawAddress& addr, + base::OnceCallback cb) { + eatt_supp_feat_cb = std::move(cb); + return true; + }); // Return false to trigger supported features request - ON_CALL(gatt_interface_, GetEattSupport) - .WillByDefault([](const RawAddress& addr) { return false; }); + ON_CALL(gatt_interface_, GetEattSupport).WillByDefault([](const RawAddress& addr) { + return false; + }); std::vector test_local_cids{61, 62, 63, 64, 65}; - EXPECT_CALL(l2cap_interface_, - ConnectCreditBasedReq(BT_PSM_EATT, test_address, _)) - .WillOnce(Return(test_local_cids)); + EXPECT_CALL(l2cap_interface_, ConnectCreditBasedReq(BT_PSM_EATT, test_address, _)) + .WillOnce(Return(test_local_cids)); eatt_instance_->Connect(test_address); // Let the remote connect while we are trying to connect - EXPECT_CALL( - l2cap_interface_, - ConnectCreditBasedRsp(test_address, 1, incoming_cids, L2CAP_CONN_OK, _)) - .WillOnce(Return(true)); - l2cap_app_info_.pL2CA_CreditBasedConnectInd_Cb( - test_address, incoming_cids, BT_PSM_EATT, EATT_MIN_MTU_MPS, 1); + EXPECT_CALL(l2cap_interface_, + ConnectCreditBasedRsp(test_address, 1, incoming_cids, L2CAP_CONN_OK, _)) + .WillOnce(Return(true)); + l2cap_app_info_.pL2CA_CreditBasedConnectInd_Cb(test_address, incoming_cids, BT_PSM_EATT, + EATT_MIN_MTU_MPS, 1); // Respond to feature request scheduled by the connect request ASSERT_TRUE(eatt_supp_feat_cb); if (eatt_supp_feat_cb) { - std::move(eatt_supp_feat_cb) - .Run(test_address, BLE_GATT_SVR_SUP_FEAT_EATT_BITMASK); + std::move(eatt_supp_feat_cb).Run(test_address, BLE_GATT_SVR_SUP_FEAT_EATT_BITMASK); } int i = 0; for (uint16_t cid : test_local_cids) { - EattChannel* channel = - eatt_instance_->FindEattChannelByCid(test_address, cid); + EattChannel* channel = eatt_instance_->FindEattChannelByCid(test_address, cid); ASSERT_TRUE(channel != nullptr); ASSERT_TRUE(channel->state_ == EattChannelState::EATT_CHANNEL_PENDING); if (i < num_of_accepted_connections) { - l2cap_app_info_.pL2CA_CreditBasedConnectCfm_Cb( - test_address, cid, EATT_MIN_MTU_MPS, L2CAP_CONN_OK); + l2cap_app_info_.pL2CA_CreditBasedConnectCfm_Cb(test_address, cid, EATT_MIN_MTU_MPS, + L2CAP_CONN_OK); connected_cids_.push_back(cid); ASSERT_TRUE(channel->state_ == EattChannelState::EATT_CHANNEL_OPENED); @@ -181,8 +170,7 @@ class EattTest : public testing::Test { } else { l2cap_app_info_.pL2CA_Error_Cb(cid, L2CAP_CONN_NO_RESOURCES); - EattChannel* channel = - eatt_instance_->FindEattChannelByCid(test_address, cid); + EattChannel* channel = eatt_instance_->FindEattChannelByCid(test_address, cid); ASSERT_TRUE(channel == nullptr); } i++; @@ -190,20 +178,19 @@ class EattTest : public testing::Test { // Check the incoming CIDs as well for (auto cid : incoming_cids) { - EattChannel* channel = - eatt_instance_->FindEattChannelByCid(test_address, cid); + EattChannel* channel = eatt_instance_->FindEattChannelByCid(test_address, cid); ASSERT_NE(nullptr, channel); ASSERT_EQ(channel->state_, EattChannelState::EATT_CHANNEL_OPENED); ASSERT_TRUE(channel->tx_mtu_ == EATT_MIN_MTU_MPS); } - ASSERT_EQ(test_tcb.eatt, - num_of_accepted_connections + incoming_cids.size()); + ASSERT_EQ(test_tcb.eatt, num_of_accepted_connections + incoming_cids.size()); } void DisconnectEattByPeer(void) { - for (uint16_t cid : connected_cids_) + for (uint16_t cid : connected_cids_) { l2cap_app_info_.pL2CA_DisconnectInd_Cb(cid, true); + } ASSERT_TRUE(test_tcb.eatt == 0); } @@ -217,8 +204,7 @@ class EattTest : public testing::Test { void SetUp() override { le_buffer_size_.le_data_packet_length_ = 128; le_buffer_size_.total_num_le_packets_ = 24; - ON_CALL(controller_, GetLeBufferSize) - .WillByDefault(Return(le_buffer_size_)); + ON_CALL(controller_, GetLeBufferSize).WillByDefault(Return(le_buffer_size_)); bluetooth::l2cap::SetMockInterface(&l2cap_interface_); bluetooth::manager::SetMockBtmApiInterface(&btm_api_interface_); bluetooth::manager::SetMockBtifStorageInterface(&btif_storage_interface_); @@ -229,16 +215,13 @@ class EattTest : public testing::Test { memset(&test_tcb, 0, sizeof(test_tcb)); EXPECT_CALL(l2cap_interface_, RegisterLECoc(BT_PSM_EATT, _, _)) - .WillOnce(DoAll(SaveArg<1>(&l2cap_app_info_), Return(BT_PSM_EATT))); + .WillOnce(DoAll(SaveArg<1>(&l2cap_app_info_), Return(BT_PSM_EATT))); - ON_CALL(btif_storage_interface_, LoadBondedEatt).WillByDefault([]() { - return; - }); + ON_CALL(btif_storage_interface_, LoadBondedEatt).WillByDefault([]() { return; }); hci_role_ = HCI_ROLE_CENTRAL; - ON_CALL(l2cap_interface_, GetBleConnRole(_)) - .WillByDefault(DoAll(Return(hci_role_))); + ON_CALL(l2cap_interface_, GetBleConnRole(_)).WillByDefault(DoAll(Return(hci_role_))); eatt_instance_ = EattExtension::GetInstance(); eatt_instance_->Start(); @@ -285,15 +268,13 @@ TEST_F(EattTest, IncomingEattConnectionByUnknownDevice) { std::vector incoming_cids{71, 72, 73, 74, 75}; ON_CALL(btm_api_interface_, IsEncrypted) - .WillByDefault( - [](const RawAddress& addr, tBT_TRANSPORT transport) { return true; }); - EXPECT_CALL( - l2cap_interface_, - ConnectCreditBasedRsp(test_address, 1, incoming_cids, L2CAP_CONN_OK, _)) - .WillOnce(Return(true)); + .WillByDefault([](const RawAddress& addr, tBT_TRANSPORT transport) { return true; }); + EXPECT_CALL(l2cap_interface_, + ConnectCreditBasedRsp(test_address, 1, incoming_cids, L2CAP_CONN_OK, _)) + .WillOnce(Return(true)); - l2cap_app_info_.pL2CA_CreditBasedConnectInd_Cb( - test_address, incoming_cids, BT_PSM_EATT, EATT_MIN_MTU_MPS, 1); + l2cap_app_info_.pL2CA_CreditBasedConnectInd_Cb(test_address, incoming_cids, BT_PSM_EATT, + EATT_MIN_MTU_MPS, 1); DisconnectEattDevice(incoming_cids); } @@ -301,28 +282,26 @@ TEST_F(EattTest, IncomingEattConnectionByUnknownDevice) { TEST_F(EattTest, IncomingEattConnectionByKnownDevice) { hci_role_ = HCI_ROLE_PERIPHERAL; ON_CALL(btm_api_interface_, IsEncrypted) - .WillByDefault( - [](const RawAddress& addr, tBT_TRANSPORT transport) { return true; }); + .WillByDefault([](const RawAddress& addr, tBT_TRANSPORT transport) { return true; }); ON_CALL(gatt_interface_, ClientReadSupportedFeatures) - .WillByDefault( - [](const RawAddress& addr, - base::OnceCallback cb) { + .WillByDefault([](const RawAddress& addr, + base::OnceCallback cb) { std::move(cb).Run(addr, BLE_GATT_SVR_SUP_FEAT_EATT_BITMASK); return true; }); - ON_CALL(gatt_interface_, GetEattSupport) - .WillByDefault([](const RawAddress& addr) { return true; }); + ON_CALL(gatt_interface_, GetEattSupport).WillByDefault([](const RawAddress& addr) { + return true; + }); eatt_instance_->Connect(test_address); std::vector incoming_cids{71, 72, 73, 74, 75}; - EXPECT_CALL( - l2cap_interface_, - ConnectCreditBasedRsp(test_address, 1, incoming_cids, L2CAP_CONN_OK, _)) - .WillOnce(Return(true)); + EXPECT_CALL(l2cap_interface_, + ConnectCreditBasedRsp(test_address, 1, incoming_cids, L2CAP_CONN_OK, _)) + .WillOnce(Return(true)); - l2cap_app_info_.pL2CA_CreditBasedConnectInd_Cb( - test_address, incoming_cids, BT_PSM_EATT, EATT_MIN_MTU_MPS, 1); + l2cap_app_info_.pL2CA_CreditBasedConnectInd_Cb(test_address, incoming_cids, BT_PSM_EATT, + EATT_MIN_MTU_MPS, 1); DisconnectEattDevice(incoming_cids); @@ -332,32 +311,28 @@ TEST_F(EattTest, IncomingEattConnectionByKnownDevice) { TEST_F(EattTest, IncomingEattConnectionByKnownDeviceEncryptionOff) { hci_role_ = HCI_ROLE_PERIPHERAL; ON_CALL(btm_api_interface_, IsEncrypted) - .WillByDefault([](const RawAddress& addr, tBT_TRANSPORT transport) { - return false; - }); + .WillByDefault([](const RawAddress& addr, tBT_TRANSPORT transport) { return false; }); ON_CALL(btm_api_interface_, IsLinkKeyKnown) - .WillByDefault( - [](const RawAddress& addr, tBT_TRANSPORT transport) { return true; }); + .WillByDefault([](const RawAddress& addr, tBT_TRANSPORT transport) { return true; }); ON_CALL(gatt_interface_, ClientReadSupportedFeatures) - .WillByDefault( - [](const RawAddress& addr, - base::OnceCallback cb) { + .WillByDefault([](const RawAddress& addr, + base::OnceCallback cb) { std::move(cb).Run(addr, BLE_GATT_SVR_SUP_FEAT_EATT_BITMASK); return true; }); - ON_CALL(gatt_interface_, GetEattSupport) - .WillByDefault([](const RawAddress& addr) { return true; }); + ON_CALL(gatt_interface_, GetEattSupport).WillByDefault([](const RawAddress& addr) { + return true; + }); eatt_instance_->Connect(test_address); std::vector incoming_cids{71, 72, 73, 74, 75}; EXPECT_CALL(l2cap_interface_, - ConnectCreditBasedRsp(test_address, 1, _, - L2CAP_LE_RESULT_INSUFFICIENT_ENCRYP, _)) - .WillOnce(Return(true)); + ConnectCreditBasedRsp(test_address, 1, _, L2CAP_LE_RESULT_INSUFFICIENT_ENCRYP, _)) + .WillOnce(Return(true)); - l2cap_app_info_.pL2CA_CreditBasedConnectInd_Cb( - test_address, incoming_cids, BT_PSM_EATT, EATT_MIN_MTU_MPS, 1); + l2cap_app_info_.pL2CA_CreditBasedConnectInd_Cb(test_address, incoming_cids, BT_PSM_EATT, + EATT_MIN_MTU_MPS, 1); hci_role_ = HCI_ROLE_CENTRAL; } @@ -366,21 +341,16 @@ TEST_F(EattTest, IncomingEattConnectionByUnknownDeviceEncryptionOff) { std::vector incoming_cids{71, 72, 73, 74, 75}; ON_CALL(btm_api_interface_, IsEncrypted) - .WillByDefault([](const RawAddress& addr, tBT_TRANSPORT transport) { - return false; - }); + .WillByDefault([](const RawAddress& addr, tBT_TRANSPORT transport) { return false; }); ON_CALL(btm_api_interface_, IsLinkKeyKnown) - .WillByDefault([](const RawAddress& addr, tBT_TRANSPORT transport) { - return false; - }); + .WillByDefault([](const RawAddress& addr, tBT_TRANSPORT transport) { return false; }); EXPECT_CALL( - l2cap_interface_, - ConnectCreditBasedRsp(test_address, 1, _, - L2CAP_LE_RESULT_INSUFFICIENT_AUTHENTICATION, _)) - .WillOnce(Return(true)); + l2cap_interface_, + ConnectCreditBasedRsp(test_address, 1, _, L2CAP_LE_RESULT_INSUFFICIENT_AUTHENTICATION, _)) + .WillOnce(Return(true)); - l2cap_app_info_.pL2CA_CreditBasedConnectInd_Cb( - test_address, incoming_cids, BT_PSM_EATT, EATT_MIN_MTU_MPS, 1); + l2cap_app_info_.pL2CA_CreditBasedConnectInd_Cb(test_address, incoming_cids, BT_PSM_EATT, + EATT_MIN_MTU_MPS, 1); } TEST_F(EattTest, ReconnectInitiatedByRemoteSucceed) { @@ -389,31 +359,27 @@ TEST_F(EattTest, ReconnectInitiatedByRemoteSucceed) { std::vector incoming_cids{71, 72, 73, 74, 75}; ON_CALL(btm_api_interface_, IsEncrypted) - .WillByDefault( - [](const RawAddress& addr, tBT_TRANSPORT transport) { return true; }); + .WillByDefault([](const RawAddress& addr, tBT_TRANSPORT transport) { return true; }); - EXPECT_CALL( - l2cap_interface_, - ConnectCreditBasedRsp(test_address, 1, incoming_cids, L2CAP_CONN_OK, _)) - .WillOnce(Return(true)); + EXPECT_CALL(l2cap_interface_, + ConnectCreditBasedRsp(test_address, 1, incoming_cids, L2CAP_CONN_OK, _)) + .WillOnce(Return(true)); - l2cap_app_info_.pL2CA_CreditBasedConnectInd_Cb( - test_address, incoming_cids, BT_PSM_EATT, EATT_MIN_MTU_MPS, 1); + l2cap_app_info_.pL2CA_CreditBasedConnectInd_Cb(test_address, incoming_cids, BT_PSM_EATT, + EATT_MIN_MTU_MPS, 1); DisconnectEattDevice(incoming_cids); } TEST_F(EattTest, ConnectInitiatedWhenRemoteConnects) { ON_CALL(btm_api_interface_, IsEncrypted) - .WillByDefault( - [](const RawAddress& addr, tBT_TRANSPORT transport) { return true; }); + .WillByDefault([](const RawAddress& addr, tBT_TRANSPORT transport) { return true; }); std::vector incoming_cids{71, 72, 73, 74}; ConnectDeviceBothSides(1, incoming_cids); std::vector disconnecting_cids; - disconnecting_cids.insert(disconnecting_cids.end(), incoming_cids.begin(), - incoming_cids.end()); + disconnecting_cids.insert(disconnecting_cids.end(), incoming_cids.begin(), incoming_cids.end()); disconnecting_cids.insert(disconnecting_cids.end(), connected_cids_.begin(), connected_cids_.end()); DisconnectEattDevice(disconnecting_cids); @@ -426,26 +392,22 @@ TEST_F(EattTest, ConnectSucceedMultipleChannels) { TEST_F(EattTest, ConnectFailedEattNotSupported) { ON_CALL(gatt_interface_, ClientReadSupportedFeatures) - .WillByDefault( - [](const RawAddress& addr, - base::OnceCallback cb) { + .WillByDefault([](const RawAddress& addr, + base::OnceCallback cb) { std::move(cb).Run(addr, 0); return true; }); - ON_CALL(gatt_interface_, GetEattSupport) - .WillByDefault([](const RawAddress& addr) { return false; }); + ON_CALL(gatt_interface_, GetEattSupport).WillByDefault([](const RawAddress& addr) { + return false; + }); - EXPECT_CALL(l2cap_interface_, - ConnectCreditBasedReq(BT_PSM_EATT, test_address, _)) - .Times(0); + EXPECT_CALL(l2cap_interface_, ConnectCreditBasedReq(BT_PSM_EATT, test_address, _)).Times(0); eatt_instance_->Connect(test_address); ASSERT_TRUE(eatt_instance_->IsEattSupportedByPeer(test_address) == false); } TEST_F(EattTest, ConnectFailedSlaveOnTheLink) { - EXPECT_CALL(l2cap_interface_, - ConnectCreditBasedReq(BT_PSM_EATT, test_address, _)) - .Times(0); + EXPECT_CALL(l2cap_interface_, ConnectCreditBasedReq(BT_PSM_EATT, test_address, _)).Times(0); hci_role_ = HCI_ROLE_PERIPHERAL; eatt_instance_->Connect(test_address); @@ -458,8 +420,7 @@ TEST_F(EattTest, DisonnectByPeerSucceed) { ConnectDeviceEattSupported(2); uint16_t cid = connected_cids_[0]; - EattChannel* channel = - eatt_instance_->FindEattChannelByCid(test_address, cid); + EattChannel* channel = eatt_instance_->FindEattChannelByCid(test_address, cid); ASSERT_TRUE(channel->state_ == EattChannelState::EATT_CHANNEL_OPENED); DisconnectEattByPeer(); @@ -473,7 +434,7 @@ TEST_F(EattTest, ReconfigAllSucceed) { std::vector cids; EXPECT_CALL(l2cap_interface_, ReconfigCreditBasedConnsReq(_, _, _)) - .WillOnce(DoAll(SaveArg<1>(&cids), Return(true))); + .WillOnce(DoAll(SaveArg<1>(&cids), Return(true))); uint16_t new_mtu = 300; eatt_instance_->ReconfigureAll(test_address, new_mtu); @@ -483,11 +444,9 @@ TEST_F(EattTest, ReconfigAllSucceed) { tL2CAP_LE_CFG_INFO cfg = {.result = L2CAP_CFG_OK, .mtu = new_mtu}; for (uint16_t cid : cids) { - l2cap_app_info_.pL2CA_CreditBasedReconfigCompleted_Cb(test_address, cid, - true, &cfg); + l2cap_app_info_.pL2CA_CreditBasedReconfigCompleted_Cb(test_address, cid, true, &cfg); - EattChannel* channel = - eatt_instance_->FindEattChannelByCid(test_address, cid); + EattChannel* channel = eatt_instance_->FindEattChannelByCid(test_address, cid); ASSERT_TRUE(channel->state_ == EattChannelState::EATT_CHANNEL_OPENED); ASSERT_TRUE(channel->rx_mtu_ == new_mtu); } @@ -500,22 +459,19 @@ TEST_F(EattTest, ReconfigAllFailed) { std::vector cids; EXPECT_CALL(l2cap_interface_, ReconfigCreditBasedConnsReq(_, _, _)) - .WillOnce(DoAll(SaveArg<1>(&cids), Return(true))); + .WillOnce(DoAll(SaveArg<1>(&cids), Return(true))); uint16_t new_mtu = 300; eatt_instance_->ReconfigureAll(test_address, new_mtu); ASSERT_TRUE(cids.size() == connected_cids_.size()); - tL2CAP_LE_CFG_INFO cfg = {.result = L2CAP_CFG_FAILED_NO_REASON, - .mtu = new_mtu}; + tL2CAP_LE_CFG_INFO cfg = {.result = L2CAP_CFG_FAILED_NO_REASON, .mtu = new_mtu}; for (uint16_t cid : cids) { - l2cap_app_info_.pL2CA_CreditBasedReconfigCompleted_Cb(test_address, cid, - true, &cfg); + l2cap_app_info_.pL2CA_CreditBasedReconfigCompleted_Cb(test_address, cid, true, &cfg); - EattChannel* channel = - eatt_instance_->FindEattChannelByCid(test_address, cid); + EattChannel* channel = eatt_instance_->FindEattChannelByCid(test_address, cid); ASSERT_TRUE(channel->state_ == EattChannelState::EATT_CHANNEL_OPENED); ASSERT_TRUE(channel->rx_mtu_ != new_mtu); } @@ -528,7 +484,7 @@ TEST_F(EattTest, ReconfigSingleSucceed) { std::vector cids; EXPECT_CALL(l2cap_interface_, ReconfigCreditBasedConnsReq(_, _, _)) - .WillOnce(DoAll(SaveArg<1>(&cids), Return(true))); + .WillOnce(DoAll(SaveArg<1>(&cids), Return(true))); uint16_t new_mtu = 300; eatt_instance_->Reconfigure(test_address, connected_cids_[1], new_mtu); @@ -540,10 +496,8 @@ TEST_F(EattTest, ReconfigSingleSucceed) { auto it = std::find(connected_cids_.begin(), connected_cids_.end(), cids[0]); ASSERT_TRUE(it != connected_cids_.end()); - l2cap_app_info_.pL2CA_CreditBasedReconfigCompleted_Cb(test_address, cids[0], - true, &cfg); - EattChannel* channel = - eatt_instance_->FindEattChannelByCid(test_address, cids[0]); + l2cap_app_info_.pL2CA_CreditBasedReconfigCompleted_Cb(test_address, cids[0], true, &cfg); + EattChannel* channel = eatt_instance_->FindEattChannelByCid(test_address, cids[0]); ASSERT_TRUE(channel->state_ == EattChannelState::EATT_CHANNEL_OPENED); ASSERT_TRUE(channel->rx_mtu_ == new_mtu); @@ -555,23 +509,20 @@ TEST_F(EattTest, ReconfigSingleFailed) { std::vector cids; EXPECT_CALL(l2cap_interface_, ReconfigCreditBasedConnsReq(_, _, _)) - .WillOnce(DoAll(SaveArg<1>(&cids), Return(true))); + .WillOnce(DoAll(SaveArg<1>(&cids), Return(true))); uint16_t new_mtu = 300; eatt_instance_->ReconfigureAll(test_address, new_mtu); ASSERT_TRUE(cids.size() == connected_cids_.size()); - tL2CAP_LE_CFG_INFO cfg = {.result = L2CAP_CFG_FAILED_NO_REASON, - .mtu = new_mtu}; + tL2CAP_LE_CFG_INFO cfg = {.result = L2CAP_CFG_FAILED_NO_REASON, .mtu = new_mtu}; auto it = std::find(connected_cids_.begin(), connected_cids_.end(), cids[0]); ASSERT_TRUE(it != connected_cids_.end()); - l2cap_app_info_.pL2CA_CreditBasedReconfigCompleted_Cb(test_address, cids[0], - true, &cfg); - EattChannel* channel = - eatt_instance_->FindEattChannelByCid(test_address, cids[0]); + l2cap_app_info_.pL2CA_CreditBasedReconfigCompleted_Cb(test_address, cids[0], true, &cfg); + EattChannel* channel = eatt_instance_->FindEattChannelByCid(test_address, cids[0]); ASSERT_TRUE(channel->state_ == EattChannelState::EATT_CHANNEL_OPENED); ASSERT_TRUE(channel->rx_mtu_ != new_mtu); @@ -585,11 +536,9 @@ TEST_F(EattTest, ReconfigPeerSucceed) { tL2CAP_LE_CFG_INFO cfg = {.result = L2CAP_CFG_OK, .mtu = new_mtu}; for (uint16_t cid : connected_cids_) { - l2cap_app_info_.pL2CA_CreditBasedReconfigCompleted_Cb(test_address, cid, - false, &cfg); + l2cap_app_info_.pL2CA_CreditBasedReconfigCompleted_Cb(test_address, cid, false, &cfg); - EattChannel* channel = - eatt_instance_->FindEattChannelByCid(test_address, cid); + EattChannel* channel = eatt_instance_->FindEattChannelByCid(test_address, cid); ASSERT_TRUE(channel->state_ == EattChannelState::EATT_CHANNEL_OPENED); ASSERT_TRUE(channel->tx_mtu_ == new_mtu); } @@ -601,15 +550,12 @@ TEST_F(EattTest, ReconfigPeerFailed) { ConnectDeviceEattSupported(2); uint16_t new_mtu = 300; - tL2CAP_LE_CFG_INFO cfg = {.result = L2CAP_CFG_FAILED_NO_REASON, - .mtu = new_mtu}; + tL2CAP_LE_CFG_INFO cfg = {.result = L2CAP_CFG_FAILED_NO_REASON, .mtu = new_mtu}; for (uint16_t cid : connected_cids_) { - l2cap_app_info_.pL2CA_CreditBasedReconfigCompleted_Cb(test_address, cid, - false, &cfg); + l2cap_app_info_.pL2CA_CreditBasedReconfigCompleted_Cb(test_address, cid, false, &cfg); - EattChannel* channel = - eatt_instance_->FindEattChannelByCid(test_address, cid); + EattChannel* channel = eatt_instance_->FindEattChannelByCid(test_address, cid); ASSERT_TRUE(channel->state_ == EattChannelState::EATT_CHANNEL_OPENED); ASSERT_TRUE(channel->tx_mtu_ != new_mtu); } @@ -633,25 +579,23 @@ TEST_F(EattTest, TestCollisionHandling) { TEST_F(EattTest, ChannelUnavailableWhileOpening) { // arrange ON_CALL(gatt_interface_, ClientReadSupportedFeatures) - .WillByDefault( - [](const RawAddress& addr, - base::OnceCallback cb) { + .WillByDefault([](const RawAddress& addr, + base::OnceCallback cb) { std::move(cb).Run(addr, BLE_GATT_SVR_SUP_FEAT_EATT_BITMASK); return true; }); ON_CALL(gatt_interface_, GetEattSupport).WillByDefault(Return(true)); // expect - EXPECT_CALL(l2cap_interface_, - ConnectCreditBasedReq(BT_PSM_EATT, test_address, _)) - .WillOnce(Return(std::vector{61})); + EXPECT_CALL(l2cap_interface_, ConnectCreditBasedReq(BT_PSM_EATT, test_address, _)) + .WillOnce(Return(std::vector{61})); // act: start eatt_instance_->Connect(test_address); auto available_channel_for_request = - eatt_instance_->GetChannelAvailableForClientRequest(test_address); + eatt_instance_->GetChannelAvailableForClientRequest(test_address); auto available_channel_for_indication = - eatt_instance_->GetChannelAvailableForIndication(test_address); + eatt_instance_->GetChannelAvailableForIndication(test_address); // assert ASSERT_EQ(available_channel_for_request, nullptr); @@ -660,16 +604,15 @@ TEST_F(EattTest, ChannelUnavailableWhileOpening) { TEST_F(EattTest, ChannelUnavailableWhileReconfiguring) { // arrange - ON_CALL(l2cap_interface_, ReconfigCreditBasedConnsReq(_, _, _)) - .WillByDefault(Return(true)); + ON_CALL(l2cap_interface_, ReconfigCreditBasedConnsReq(_, _, _)).WillByDefault(Return(true)); ConnectDeviceEattSupported(/* num_of_accepted_connections = */ 1); // act: reconfigure, then get available channels eatt_instance_->Reconfigure(test_address, connected_cids_[0], 300); auto available_channel_for_request = - eatt_instance_->GetChannelAvailableForClientRequest(test_address); + eatt_instance_->GetChannelAvailableForClientRequest(test_address); auto available_channel_for_indication = - eatt_instance_->GetChannelAvailableForIndication(test_address); + eatt_instance_->GetChannelAvailableForIndication(test_address); // assert ASSERT_EQ(available_channel_for_request, nullptr); diff --git a/system/stack/test/fuzzers/a2dp/a2dpFuzzFunctions.h b/system/stack/test/fuzzers/a2dp/a2dpFuzzFunctions.h index 1a64517ee71..d2c1708eb6c 100644 --- a/system/stack/test/fuzzers/a2dp/a2dpFuzzFunctions.h +++ b/system/stack/test/fuzzers/a2dp/a2dpFuzzFunctions.h @@ -39,54 +39,47 @@ * allows multiple fuzzers to include this file, if functionality is needed. */ std::vector> a2dp_operations = { - // Init - [](FuzzedDataProvider*) -> void { - // Re-init zeros out memory containing some pointers. - // Free the db first to prevent memleaks - if (a2dp_cb.find.p_db) { - osi_free(a2dp_cb.find.p_db); - } + // Init + [](FuzzedDataProvider*) -> void { + // Re-init zeros out memory containing some pointers. + // Free the db first to prevent memleaks + if (a2dp_cb.find.p_db) { + osi_free(a2dp_cb.find.p_db); + } - // Attempt re-initializations mid-run. - A2DP_Init(); - }, + // Attempt re-initializations mid-run. + A2DP_Init(); + }, - // A2DP_AddRecord - [](FuzzedDataProvider* fdp) -> void { - std::vector p_service_name = - fdp->ConsumeBytesWithTerminator(MAX_STR_LEN); - std::vector p_provider_name = - fdp->ConsumeBytesWithTerminator(MAX_STR_LEN); - uint16_t service_uuid = fdp->ConsumeBool() ? UUID_SERVCLASS_AUDIO_SOURCE - : UUID_SERVCLASS_AUDIO_SINK; - A2DP_AddRecord(service_uuid, p_service_name.data(), - p_provider_name.data(), fdp->ConsumeIntegral(), - // This should be a val returned by SDP_CreateRecord - getArbitraryVectorElement(fdp, sdp_record_handles, true)); - }, + // A2DP_AddRecord + [](FuzzedDataProvider* fdp) -> void { + std::vector p_service_name = fdp->ConsumeBytesWithTerminator(MAX_STR_LEN); + std::vector p_provider_name = fdp->ConsumeBytesWithTerminator(MAX_STR_LEN); + uint16_t service_uuid = + fdp->ConsumeBool() ? UUID_SERVCLASS_AUDIO_SOURCE : UUID_SERVCLASS_AUDIO_SINK; + A2DP_AddRecord(service_uuid, p_service_name.data(), p_provider_name.data(), + fdp->ConsumeIntegral(), + // This should be a val returned by SDP_CreateRecord + getArbitraryVectorElement(fdp, sdp_record_handles, true)); + }, - // A2DP_FindService - [](FuzzedDataProvider* fdp) -> void { - std::vector attr_list; - tA2DP_SDP_DB_PARAMS p_db = generateDBParams(fdp, attr_list); - const RawAddress bd_addr = generateRawAddress(fdp); - uint16_t service_uuid = fdp->ConsumeBool() ? UUID_SERVCLASS_AUDIO_SOURCE - : UUID_SERVCLASS_AUDIO_SINK; - A2DP_FindService(service_uuid, bd_addr, &p_db, - base::Bind(a2dp_find_callback)); - }, + // A2DP_FindService + [](FuzzedDataProvider* fdp) -> void { + std::vector attr_list; + tA2DP_SDP_DB_PARAMS p_db = generateDBParams(fdp, attr_list); + const RawAddress bd_addr = generateRawAddress(fdp); + uint16_t service_uuid = + fdp->ConsumeBool() ? UUID_SERVCLASS_AUDIO_SOURCE : UUID_SERVCLASS_AUDIO_SINK; + A2DP_FindService(service_uuid, bd_addr, &p_db, base::Bind(a2dp_find_callback)); + }, - // A2DP_GetAvdtpVersion - [](FuzzedDataProvider*) -> void { A2DP_GetAvdtpVersion(); }, + // A2DP_GetAvdtpVersion + [](FuzzedDataProvider*) -> void { A2DP_GetAvdtpVersion(); }, - // A2DP_BitsSet - [](FuzzedDataProvider* fdp) -> void { - A2DP_BitsSet(fdp->ConsumeIntegral()); - }, + // A2DP_BitsSet + [](FuzzedDataProvider* fdp) -> void { A2DP_BitsSet(fdp->ConsumeIntegral()); }, - // SDP Calls - [](FuzzedDataProvider* fdp) -> void { - callArbitraryFunction(fdp, sdp_operations); - }}; + // SDP Calls + [](FuzzedDataProvider* fdp) -> void { callArbitraryFunction(fdp, sdp_operations); }}; #endif // BT_STACK_FUZZ_A2DP_FUNCTIONS_H_ diff --git a/system/stack/test/fuzzers/a2dp/a2dpFuzzHelpers.h b/system/stack/test/fuzzers/a2dp/a2dpFuzzHelpers.h index d159496691d..0580e2070c5 100644 --- a/system/stack/test/fuzzers/a2dp/a2dpFuzzHelpers.h +++ b/system/stack/test/fuzzers/a2dp/a2dpFuzzHelpers.h @@ -32,8 +32,7 @@ #define MAX_DB_SIZE 4096 -tA2DP_SDP_DB_PARAMS generateDBParams(FuzzedDataProvider* fdp, - std::vector& attr_list) { +tA2DP_SDP_DB_PARAMS generateDBParams(FuzzedDataProvider* fdp, std::vector& attr_list) { attr_list = generateArbitraryAttrList(fdp); tA2DP_SDP_DB_PARAMS db_params; @@ -45,8 +44,7 @@ tA2DP_SDP_DB_PARAMS generateDBParams(FuzzedDataProvider* fdp, } // Define our empty callback function -void a2dp_find_callback(bool found, tA2DP_Service* p_service, - const RawAddress& peer_address) { +void a2dp_find_callback(bool found, tA2DP_Service* p_service, const RawAddress& peer_address) { // Free the RawAddress we created in the generate function delete &peer_address; } diff --git a/system/stack/test/fuzzers/a2dp/codec/a2dpCodecConfigFuzzFunctions.h b/system/stack/test/fuzzers/a2dp/codec/a2dpCodecConfigFuzzFunctions.h index cc15a834c87..5ba233ee05a 100644 --- a/system/stack/test/fuzzers/a2dp/codec/a2dpCodecConfigFuzzFunctions.h +++ b/system/stack/test/fuzzers/a2dp/codec/a2dpCodecConfigFuzzFunctions.h @@ -18,30 +18,29 @@ #define BT_STACK_FUZZ_A2DP_CODECCONFIG_FUNCTIONS_H_ #include + #include + #include "a2dp_codec_api.h" +#include "fuzzers/a2dp/codec/a2dpCodecConfigFuzzHelpers.h" #include "fuzzers/a2dp/codec/a2dpCodecHelperFunctions.h" #include "fuzzers/a2dp/codec/a2dpCodecInfoFuzzFunctions.h" #include "fuzzers/common/commonFuzzHelpers.h" -#include "fuzzers/a2dp/codec/a2dpCodecConfigFuzzHelpers.h" - /* This is a vector of lambda functions the fuzzer will pull from. * This is done so new functions can be added to the fuzzer easily * without requiring modifications to the main fuzzer file. This also * allows multiple fuzzers to include this file, if functionality is needed. */ -std::vector> - a2dp_codec_config_operations = { +std::vector> a2dp_codec_config_operations = { // createCodec [](FuzzedDataProvider* fdp) -> void { // Generate our arguments btav_a2dp_codec_index_t codec_index = getArbitraryBtavCodecIndex(fdp); - btav_a2dp_codec_priority_t codec_priority = - getArbitraryBtavCodecPriority(fdp); + btav_a2dp_codec_priority_t codec_priority = getArbitraryBtavCodecPriority(fdp); // Create our new codec std::shared_ptr codec_config( - A2dpCodecConfig::createCodec(codec_index, codec_priority)); + A2dpCodecConfig::createCodec(codec_index, codec_priority)); // Push it to our vector if (codec_config) { a2dp_codec_config_vect.push_back(codec_config); @@ -54,8 +53,7 @@ std::vector> return; } // Get random vector index - size_t index = fdp->ConsumeIntegralInRange( - 0, a2dp_codec_config_vect.size() - 1); + size_t index = fdp->ConsumeIntegralInRange(0, a2dp_codec_config_vect.size() - 1); // Remove from vector a2dp_codec_config_vect.erase(a2dp_codec_config_vect.begin() + index); }, @@ -63,7 +61,7 @@ std::vector> // codecIndex [](FuzzedDataProvider* fdp) -> void { std::shared_ptr codec_config( - getArbitraryVectorElement(fdp, a2dp_codec_config_vect, false)); + getArbitraryVectorElement(fdp, a2dp_codec_config_vect, false)); if (codec_config == nullptr) { return; } @@ -74,7 +72,7 @@ std::vector> // name [](FuzzedDataProvider* fdp) -> void { std::shared_ptr codec_config( - getArbitraryVectorElement(fdp, a2dp_codec_config_vect, false)); + getArbitraryVectorElement(fdp, a2dp_codec_config_vect, false)); if (codec_config == nullptr) { return; } @@ -85,7 +83,7 @@ std::vector> // codecPriority [](FuzzedDataProvider* fdp) -> void { std::shared_ptr codec_config( - getArbitraryVectorElement(fdp, a2dp_codec_config_vect, false)); + getArbitraryVectorElement(fdp, a2dp_codec_config_vect, false)); if (codec_config == nullptr) { return; } @@ -96,7 +94,7 @@ std::vector> // getCodecSpecificConfig [](FuzzedDataProvider* fdp) -> void { std::shared_ptr codec_config( - getArbitraryVectorElement(fdp, a2dp_codec_config_vect, false)); + getArbitraryVectorElement(fdp, a2dp_codec_config_vect, false)); if (codec_config == nullptr) { return; } @@ -108,7 +106,7 @@ std::vector> // getTrackBitRate [](FuzzedDataProvider* fdp) -> void { std::shared_ptr codec_config( - getArbitraryVectorElement(fdp, a2dp_codec_config_vect, false)); + getArbitraryVectorElement(fdp, a2dp_codec_config_vect, false)); if (codec_config == nullptr) { return; } @@ -119,20 +117,19 @@ std::vector> // copyOutOtaCodecConfig [](FuzzedDataProvider* fdp) -> void { std::shared_ptr codec_config( - getArbitraryVectorElement(fdp, a2dp_codec_config_vect, false)); + getArbitraryVectorElement(fdp, a2dp_codec_config_vect, false)); if (codec_config == nullptr) { return; } - uint8_t* codec_info = - getArbitraryVectorElement(fdp, a2dp_codec_info_vect, true); + uint8_t* codec_info = getArbitraryVectorElement(fdp, a2dp_codec_info_vect, true); codec_config->copyOutOtaCodecConfig(codec_info); }, // getCodecConfig [](FuzzedDataProvider* fdp) -> void { std::shared_ptr codec_config( - getArbitraryVectorElement(fdp, a2dp_codec_config_vect, false)); + getArbitraryVectorElement(fdp, a2dp_codec_config_vect, false)); if (codec_config == nullptr) { return; } @@ -143,7 +140,7 @@ std::vector> // getCodecCapability [](FuzzedDataProvider* fdp) -> void { std::shared_ptr codec_config( - getArbitraryVectorElement(fdp, a2dp_codec_config_vect, false)); + getArbitraryVectorElement(fdp, a2dp_codec_config_vect, false)); if (codec_config == nullptr) { return; } @@ -154,7 +151,7 @@ std::vector> // getCodecLocalCapability [](FuzzedDataProvider* fdp) -> void { std::shared_ptr codec_config( - getArbitraryVectorElement(fdp, a2dp_codec_config_vect, false)); + getArbitraryVectorElement(fdp, a2dp_codec_config_vect, false)); if (codec_config == nullptr) { return; } @@ -165,7 +162,7 @@ std::vector> // getCodecSelectableCapability [](FuzzedDataProvider* fdp) -> void { std::shared_ptr codec_config( - getArbitraryVectorElement(fdp, a2dp_codec_config_vect, false)); + getArbitraryVectorElement(fdp, a2dp_codec_config_vect, false)); if (codec_config == nullptr) { return; } @@ -176,7 +173,7 @@ std::vector> // getCodecUserConfig [](FuzzedDataProvider* fdp) -> void { std::shared_ptr codec_config( - getArbitraryVectorElement(fdp, a2dp_codec_config_vect, false)); + getArbitraryVectorElement(fdp, a2dp_codec_config_vect, false)); if (codec_config == nullptr) { return; } @@ -187,7 +184,7 @@ std::vector> // getCodecAudioConfig [](FuzzedDataProvider* fdp) -> void { std::shared_ptr codec_config( - getArbitraryVectorElement(fdp, a2dp_codec_config_vect, false)); + getArbitraryVectorElement(fdp, a2dp_codec_config_vect, false)); if (codec_config == nullptr) { return; } @@ -198,7 +195,7 @@ std::vector> // getAudioBitsPerSample [](FuzzedDataProvider* fdp) -> void { std::shared_ptr codec_config( - getArbitraryVectorElement(fdp, a2dp_codec_config_vect, false)); + getArbitraryVectorElement(fdp, a2dp_codec_config_vect, false)); if (codec_config == nullptr) { return; } @@ -209,13 +206,12 @@ std::vector> // getAudioBitsPerSample [](FuzzedDataProvider* fdp) -> void { std::shared_ptr codec_config( - getArbitraryVectorElement(fdp, a2dp_codec_config_vect, false)); + getArbitraryVectorElement(fdp, a2dp_codec_config_vect, false)); if (codec_config == nullptr) { return; } - const btav_a2dp_codec_config_t btav_codec_config = - getArbitraryBtavCodecConfig(fdp); + const btav_a2dp_codec_config_t btav_codec_config = getArbitraryBtavCodecConfig(fdp); codec_config->isCodecConfigEmpty(btav_codec_config); }, diff --git a/system/stack/test/fuzzers/a2dp/codec/a2dpCodecConfigFuzzHelpers.h b/system/stack/test/fuzzers/a2dp/codec/a2dpCodecConfigFuzzHelpers.h index 66c3fb7903a..94b4d603862 100644 --- a/system/stack/test/fuzzers/a2dp/codec/a2dpCodecConfigFuzzHelpers.h +++ b/system/stack/test/fuzzers/a2dp/codec/a2dpCodecConfigFuzzHelpers.h @@ -21,7 +21,9 @@ // It is included by the corresponding "...Functions.h" file. #include + #include + #include "a2dp_codec_api.h" #include "fuzzers/a2dp/codec/a2dpCodecInfoFuzzHelpers.h" diff --git a/system/stack/test/fuzzers/a2dp/codec/a2dpCodecFuzzFunctions.h b/system/stack/test/fuzzers/a2dp/codec/a2dpCodecFuzzFunctions.h index 8cacd336f6a..885b8e95d71 100644 --- a/system/stack/test/fuzzers/a2dp/codec/a2dpCodecFuzzFunctions.h +++ b/system/stack/test/fuzzers/a2dp/codec/a2dpCodecFuzzFunctions.h @@ -20,14 +20,15 @@ #include // For fd #include #include // For fd + #include + #include "a2dp_codec_api.h" +#include "fuzzers/a2dp/codec/a2dpCodecFuzzHelpers.h" #include "fuzzers/a2dp/codec/a2dpCodecHelperFunctions.h" #include "fuzzers/a2dp/codec/a2dpCodecInfoFuzzFunctions.h" #include "fuzzers/common/commonFuzzHelpers.h" -#include "fuzzers/a2dp/codec/a2dpCodecFuzzHelpers.h" - #define MAX_NUM_PROPERTIES 128 #define A2DP_MAX_INIT_RUNS 16 @@ -37,305 +38,289 @@ * allows multiple fuzzers to include this file, if functionality is needed. */ std::vector> a2dp_codec_operations = { - // A2dpCodecs Constructor - [](FuzzedDataProvider* fdp) -> void { - // Build out a vector of codec objects - std::vector codec_priorities; - size_t num_priorities = - fdp->ConsumeIntegralInRange(0, MAX_NUM_PROPERTIES); - for (size_t i = 0; i < num_priorities; i++) { - codec_priorities.push_back(getArbitraryBtavCodecConfig(fdp)); - } - // Construct a const ref so we can pass to constructor - const std::vector& codec_priorities_const = - codec_priorities; - std::shared_ptr codecs( - new A2dpCodecs(codec_priorities_const)); - if (codecs) { - a2dp_codecs_vect.push_back(codecs); - } - }, - - // A2dpCodecs Destructor - [](FuzzedDataProvider* fdp) -> void { - if (a2dp_codecs_vect.empty()) { - return; - } - // Get random vector index - size_t index = - fdp->ConsumeIntegralInRange(0, a2dp_codecs_vect.size() - 1); - // Remove from vector - a2dp_codecs_vect.erase(a2dp_codecs_vect.begin() + index); - }, - - // init - [](FuzzedDataProvider* fdp) -> void { - // Limit the number of times we can call this function per iteration - // (This is to prevent slow-units) - if (a2dp_init_runs <= A2DP_MAX_INIT_RUNS) { - std::shared_ptr codecs = - getArbitraryVectorElement(fdp, a2dp_codecs_vect, false); - if (codecs) { - a2dp_init_runs++; - codecs->init(); - } - } - }, - - // findSourceCodecConfig - [](FuzzedDataProvider* fdp) -> void { - std::shared_ptr codecs = - getArbitraryVectorElement(fdp, a2dp_codecs_vect, false); - uint8_t* p_codec_info = - getArbitraryVectorElement(fdp, a2dp_codec_info_vect, false); - - if (codecs && p_codec_info) { - codecs->findSourceCodecConfig(p_codec_info); - } - }, - - // findSinkCodecConfig - [](FuzzedDataProvider* fdp) -> void { - std::shared_ptr codecs = - getArbitraryVectorElement(fdp, a2dp_codecs_vect, false); - uint8_t* p_codec_info = - getArbitraryVectorElement(fdp, a2dp_codec_info_vect, false); - - if (codecs && p_codec_info) { - codecs->findSinkCodecConfig(p_codec_info); - } - }, - - // isSupportedCodec - [](FuzzedDataProvider* fdp) -> void { - std::shared_ptr codecs = - getArbitraryVectorElement(fdp, a2dp_codecs_vect, false); - if (codecs) { - codecs->isSupportedCodec(getArbitraryBtavCodecIndex(fdp)); - } - }, - - // getCurrentCodecConfig - [](FuzzedDataProvider* fdp) -> void { - std::shared_ptr codecs = - getArbitraryVectorElement(fdp, a2dp_codecs_vect, false); - if (codecs) { - codecs->getCurrentCodecConfig(); - } - }, - - // orderedSourceCodecs - [](FuzzedDataProvider* fdp) -> void { - std::shared_ptr codecs = - getArbitraryVectorElement(fdp, a2dp_codecs_vect, false); - if (codecs) { - codecs->orderedSourceCodecs(); - } - }, - - // orderedSinkCodecs - [](FuzzedDataProvider* fdp) -> void { - std::shared_ptr codecs = - getArbitraryVectorElement(fdp, a2dp_codecs_vect, false); - if (codecs) { - codecs->orderedSinkCodecs(); - } - }, - - // setCodecConfig - [](FuzzedDataProvider* fdp) -> void { - std::shared_ptr codecs = - getArbitraryVectorElement(fdp, a2dp_codecs_vect, false); - if (codecs == nullptr) { - return; - } - - const uint8_t* peer_codec_info = - getArbitraryVectorElement(fdp, a2dp_codec_info_vect, false); - if (peer_codec_info == nullptr) { - return; - } - - // Codec_config is actually some buffer - std::unique_ptr p_result_codec_config( - reinterpret_cast(calloc(500, sizeof(uint8_t))), free); - if (p_result_codec_config) { - codecs->setCodecConfig(peer_codec_info, fdp->ConsumeBool(), - p_result_codec_config.get(), fdp->ConsumeBool()); - } - }, - - // setSinkCodecConfig - [](FuzzedDataProvider* fdp) -> void { - std::shared_ptr codecs = - getArbitraryVectorElement(fdp, a2dp_codecs_vect, false); - if (codecs == nullptr) { - return; - } - - const uint8_t* peer_codec_info = - getArbitraryVectorElement(fdp, a2dp_codec_info_vect, false); - if (peer_codec_info == nullptr) { - return; - } - - // Codec_config is actually some buffer - std::unique_ptr p_result_codec_config( - reinterpret_cast(calloc(500, sizeof(uint8_t))), free); - if (p_result_codec_config) { - codecs->setSinkCodecConfig(peer_codec_info, fdp->ConsumeBool(), - p_result_codec_config.get(), + // A2dpCodecs Constructor + [](FuzzedDataProvider* fdp) -> void { + // Build out a vector of codec objects + std::vector codec_priorities; + size_t num_priorities = fdp->ConsumeIntegralInRange(0, MAX_NUM_PROPERTIES); + for (size_t i = 0; i < num_priorities; i++) { + codec_priorities.push_back(getArbitraryBtavCodecConfig(fdp)); + } + // Construct a const ref so we can pass to constructor + const std::vector& codec_priorities_const = codec_priorities; + std::shared_ptr codecs(new A2dpCodecs(codec_priorities_const)); + if (codecs) { + a2dp_codecs_vect.push_back(codecs); + } + }, + + // A2dpCodecs Destructor + [](FuzzedDataProvider* fdp) -> void { + if (a2dp_codecs_vect.empty()) { + return; + } + // Get random vector index + size_t index = fdp->ConsumeIntegralInRange(0, a2dp_codecs_vect.size() - 1); + // Remove from vector + a2dp_codecs_vect.erase(a2dp_codecs_vect.begin() + index); + }, + + // init + [](FuzzedDataProvider* fdp) -> void { + // Limit the number of times we can call this function per iteration + // (This is to prevent slow-units) + if (a2dp_init_runs <= A2DP_MAX_INIT_RUNS) { + std::shared_ptr codecs = + getArbitraryVectorElement(fdp, a2dp_codecs_vect, false); + if (codecs) { + a2dp_init_runs++; + codecs->init(); + } + } + }, + + // findSourceCodecConfig + [](FuzzedDataProvider* fdp) -> void { + std::shared_ptr codecs = + getArbitraryVectorElement(fdp, a2dp_codecs_vect, false); + uint8_t* p_codec_info = getArbitraryVectorElement(fdp, a2dp_codec_info_vect, false); + + if (codecs && p_codec_info) { + codecs->findSourceCodecConfig(p_codec_info); + } + }, + + // findSinkCodecConfig + [](FuzzedDataProvider* fdp) -> void { + std::shared_ptr codecs = + getArbitraryVectorElement(fdp, a2dp_codecs_vect, false); + uint8_t* p_codec_info = getArbitraryVectorElement(fdp, a2dp_codec_info_vect, false); + + if (codecs && p_codec_info) { + codecs->findSinkCodecConfig(p_codec_info); + } + }, + + // isSupportedCodec + [](FuzzedDataProvider* fdp) -> void { + std::shared_ptr codecs = + getArbitraryVectorElement(fdp, a2dp_codecs_vect, false); + if (codecs) { + codecs->isSupportedCodec(getArbitraryBtavCodecIndex(fdp)); + } + }, + + // getCurrentCodecConfig + [](FuzzedDataProvider* fdp) -> void { + std::shared_ptr codecs = + getArbitraryVectorElement(fdp, a2dp_codecs_vect, false); + if (codecs) { + codecs->getCurrentCodecConfig(); + } + }, + + // orderedSourceCodecs + [](FuzzedDataProvider* fdp) -> void { + std::shared_ptr codecs = + getArbitraryVectorElement(fdp, a2dp_codecs_vect, false); + if (codecs) { + codecs->orderedSourceCodecs(); + } + }, + + // orderedSinkCodecs + [](FuzzedDataProvider* fdp) -> void { + std::shared_ptr codecs = + getArbitraryVectorElement(fdp, a2dp_codecs_vect, false); + if (codecs) { + codecs->orderedSinkCodecs(); + } + }, + + // setCodecConfig + [](FuzzedDataProvider* fdp) -> void { + std::shared_ptr codecs = + getArbitraryVectorElement(fdp, a2dp_codecs_vect, false); + if (codecs == nullptr) { + return; + } + + const uint8_t* peer_codec_info = + getArbitraryVectorElement(fdp, a2dp_codec_info_vect, false); + if (peer_codec_info == nullptr) { + return; + } + + // Codec_config is actually some buffer + std::unique_ptr p_result_codec_config( + reinterpret_cast(calloc(500, sizeof(uint8_t))), free); + if (p_result_codec_config) { + codecs->setCodecConfig(peer_codec_info, fdp->ConsumeBool(), p_result_codec_config.get(), fdp->ConsumeBool()); - } - }, - - // setCodecUserConfig - [](FuzzedDataProvider* fdp) -> void { - std::shared_ptr codecs = - getArbitraryVectorElement(fdp, a2dp_codecs_vect, false); - if (codecs == nullptr) { - return; - } - - const btav_a2dp_codec_config_t codec_user_config = - getArbitraryBtavCodecConfig(fdp); - const tA2DP_ENCODER_INIT_PEER_PARAMS p_peer_params = - getArbitraryA2dpEncoderInitPeerParams(fdp); - const uint8_t* p_peer_sink_capabilities = - getArbitraryVectorElement(fdp, a2dp_codec_info_vect, false); - if (p_peer_sink_capabilities == nullptr) { - return; - } - - // Craft our result variables (And possibly pass nullptrs) - btav_a2dp_codec_config_t result_codec_config; - bool restart_input, restart_output, config_updated; - uint8_t* p_result_codec_config = - reinterpret_cast(&result_codec_config); - codecs->setCodecUserConfig(codec_user_config, &p_peer_params, - p_peer_sink_capabilities, - p_result_codec_config, &restart_input, - &restart_output, &config_updated); - }, - - // setCodecAudioConfig - [](FuzzedDataProvider* fdp) -> void { - std::shared_ptr codecs = - getArbitraryVectorElement(fdp, a2dp_codecs_vect, false); - if (codecs == nullptr) { - return; - } - - const btav_a2dp_codec_config_t codec_audio_config = - getArbitraryBtavCodecConfig(fdp); - const tA2DP_ENCODER_INIT_PEER_PARAMS p_peer_params = - getArbitraryA2dpEncoderInitPeerParams(fdp); - const uint8_t* p_peer_sink_capabilities = - getArbitraryVectorElement(fdp, a2dp_codec_info_vect, false); - if (p_peer_sink_capabilities == nullptr) { - return; - } - btav_a2dp_codec_config_t result_codec_config; - uint8_t* p_result_codec_config = - reinterpret_cast(&result_codec_config); - bool p_restart_output, p_config_updated; - codecs->setCodecAudioConfig( - codec_audio_config, &p_peer_params, p_peer_sink_capabilities, - p_result_codec_config, &p_restart_output, &p_config_updated); - }, - - // setCodecOtaConfig - [](FuzzedDataProvider* fdp) -> void { - std::shared_ptr codecs = - getArbitraryVectorElement(fdp, a2dp_codecs_vect, false); - if (codecs == nullptr) { - return; - } - - const uint8_t* p_ota_codec_config = - getArbitraryVectorElement(fdp, a2dp_codec_info_vect, false); - if (p_ota_codec_config == nullptr) { - return; - } - - const tA2DP_ENCODER_INIT_PEER_PARAMS p_peer_params = - getArbitraryA2dpEncoderInitPeerParams(fdp); - btav_a2dp_codec_config_t result_codec_config; - uint8_t* p_result_codec_config = - reinterpret_cast(&result_codec_config); - bool p_restart_input, p_restart_output, p_config_updated; - codecs->setCodecOtaConfig(p_ota_codec_config, &p_peer_params, - p_result_codec_config, &p_restart_input, - &p_restart_output, &p_config_updated); - }, - - // setPeerSinkCodecCapabilities - [](FuzzedDataProvider* fdp) -> void { - std::shared_ptr codecs = - getArbitraryVectorElement(fdp, a2dp_codecs_vect, false); - if (codecs == nullptr) { - return; - } - - const uint8_t* p_peer_codec_capabilities = - getArbitraryVectorElement(fdp, a2dp_codec_info_vect, false); - if (p_peer_codec_capabilities == nullptr) { - return; - } - codecs->setPeerSinkCodecCapabilities(p_peer_codec_capabilities); - }, - - // setPeerSourceCodecCapabilities - [](FuzzedDataProvider* fdp) -> void { - std::shared_ptr codecs = - getArbitraryVectorElement(fdp, a2dp_codecs_vect, false); - if (codecs == nullptr) { - return; - } - - const uint8_t* p_peer_codec_capabilities = - getArbitraryVectorElement(fdp, a2dp_codec_info_vect, false); - if (p_peer_codec_capabilities == nullptr) { - return; - } - codecs->setPeerSourceCodecCapabilities(p_peer_codec_capabilities); - }, - - // getCodecConfigAndCapabilities - [](FuzzedDataProvider* fdp) -> void { - std::shared_ptr codecs = - getArbitraryVectorElement(fdp, a2dp_codecs_vect, false); - if (codecs == nullptr) { - return; - } - - // Return objects - std::vector codecs_local_capabilities; - std::vector codecs_selectable_capabilities; - btav_a2dp_codec_config_t codec_config; - codecs->getCodecConfigAndCapabilities(&codec_config, - &codecs_local_capabilities, - &codecs_selectable_capabilities); - }, - - // debug_codec_dump - [](FuzzedDataProvider* fdp) -> void { - std::shared_ptr codecs = - getArbitraryVectorElement(fdp, a2dp_codecs_vect, false); - if (codecs == nullptr) { - return; - } - - // Dump this to /dev/null - int fd = open("/dev/null", O_WRONLY); - codecs->debug_codec_dump(fd); - close(fd); - }, - - // Since we're dependent on having valid codec_info objects, - // have a change to call fuzz functions for that - [](FuzzedDataProvider* fdp) -> void { - callArbitraryCodecInfoFunction(fdp, a2dp_codec_info_operations); - }}; + } + }, + + // setSinkCodecConfig + [](FuzzedDataProvider* fdp) -> void { + std::shared_ptr codecs = + getArbitraryVectorElement(fdp, a2dp_codecs_vect, false); + if (codecs == nullptr) { + return; + } + + const uint8_t* peer_codec_info = + getArbitraryVectorElement(fdp, a2dp_codec_info_vect, false); + if (peer_codec_info == nullptr) { + return; + } + + // Codec_config is actually some buffer + std::unique_ptr p_result_codec_config( + reinterpret_cast(calloc(500, sizeof(uint8_t))), free); + if (p_result_codec_config) { + codecs->setSinkCodecConfig(peer_codec_info, fdp->ConsumeBool(), + p_result_codec_config.get(), fdp->ConsumeBool()); + } + }, + + // setCodecUserConfig + [](FuzzedDataProvider* fdp) -> void { + std::shared_ptr codecs = + getArbitraryVectorElement(fdp, a2dp_codecs_vect, false); + if (codecs == nullptr) { + return; + } + + const btav_a2dp_codec_config_t codec_user_config = getArbitraryBtavCodecConfig(fdp); + const tA2DP_ENCODER_INIT_PEER_PARAMS p_peer_params = + getArbitraryA2dpEncoderInitPeerParams(fdp); + const uint8_t* p_peer_sink_capabilities = + getArbitraryVectorElement(fdp, a2dp_codec_info_vect, false); + if (p_peer_sink_capabilities == nullptr) { + return; + } + + // Craft our result variables (And possibly pass nullptrs) + btav_a2dp_codec_config_t result_codec_config; + bool restart_input, restart_output, config_updated; + uint8_t* p_result_codec_config = reinterpret_cast(&result_codec_config); + codecs->setCodecUserConfig(codec_user_config, &p_peer_params, p_peer_sink_capabilities, + p_result_codec_config, &restart_input, &restart_output, + &config_updated); + }, + + // setCodecAudioConfig + [](FuzzedDataProvider* fdp) -> void { + std::shared_ptr codecs = + getArbitraryVectorElement(fdp, a2dp_codecs_vect, false); + if (codecs == nullptr) { + return; + } + + const btav_a2dp_codec_config_t codec_audio_config = getArbitraryBtavCodecConfig(fdp); + const tA2DP_ENCODER_INIT_PEER_PARAMS p_peer_params = + getArbitraryA2dpEncoderInitPeerParams(fdp); + const uint8_t* p_peer_sink_capabilities = + getArbitraryVectorElement(fdp, a2dp_codec_info_vect, false); + if (p_peer_sink_capabilities == nullptr) { + return; + } + btav_a2dp_codec_config_t result_codec_config; + uint8_t* p_result_codec_config = reinterpret_cast(&result_codec_config); + bool p_restart_output, p_config_updated; + codecs->setCodecAudioConfig(codec_audio_config, &p_peer_params, p_peer_sink_capabilities, + p_result_codec_config, &p_restart_output, &p_config_updated); + }, + + // setCodecOtaConfig + [](FuzzedDataProvider* fdp) -> void { + std::shared_ptr codecs = + getArbitraryVectorElement(fdp, a2dp_codecs_vect, false); + if (codecs == nullptr) { + return; + } + + const uint8_t* p_ota_codec_config = + getArbitraryVectorElement(fdp, a2dp_codec_info_vect, false); + if (p_ota_codec_config == nullptr) { + return; + } + + const tA2DP_ENCODER_INIT_PEER_PARAMS p_peer_params = + getArbitraryA2dpEncoderInitPeerParams(fdp); + btav_a2dp_codec_config_t result_codec_config; + uint8_t* p_result_codec_config = reinterpret_cast(&result_codec_config); + bool p_restart_input, p_restart_output, p_config_updated; + codecs->setCodecOtaConfig(p_ota_codec_config, &p_peer_params, p_result_codec_config, + &p_restart_input, &p_restart_output, &p_config_updated); + }, + + // setPeerSinkCodecCapabilities + [](FuzzedDataProvider* fdp) -> void { + std::shared_ptr codecs = + getArbitraryVectorElement(fdp, a2dp_codecs_vect, false); + if (codecs == nullptr) { + return; + } + + const uint8_t* p_peer_codec_capabilities = + getArbitraryVectorElement(fdp, a2dp_codec_info_vect, false); + if (p_peer_codec_capabilities == nullptr) { + return; + } + codecs->setPeerSinkCodecCapabilities(p_peer_codec_capabilities); + }, + + // setPeerSourceCodecCapabilities + [](FuzzedDataProvider* fdp) -> void { + std::shared_ptr codecs = + getArbitraryVectorElement(fdp, a2dp_codecs_vect, false); + if (codecs == nullptr) { + return; + } + + const uint8_t* p_peer_codec_capabilities = + getArbitraryVectorElement(fdp, a2dp_codec_info_vect, false); + if (p_peer_codec_capabilities == nullptr) { + return; + } + codecs->setPeerSourceCodecCapabilities(p_peer_codec_capabilities); + }, + + // getCodecConfigAndCapabilities + [](FuzzedDataProvider* fdp) -> void { + std::shared_ptr codecs = + getArbitraryVectorElement(fdp, a2dp_codecs_vect, false); + if (codecs == nullptr) { + return; + } + + // Return objects + std::vector codecs_local_capabilities; + std::vector codecs_selectable_capabilities; + btav_a2dp_codec_config_t codec_config; + codecs->getCodecConfigAndCapabilities(&codec_config, &codecs_local_capabilities, + &codecs_selectable_capabilities); + }, + + // debug_codec_dump + [](FuzzedDataProvider* fdp) -> void { + std::shared_ptr codecs = + getArbitraryVectorElement(fdp, a2dp_codecs_vect, false); + if (codecs == nullptr) { + return; + } + + // Dump this to /dev/null + int fd = open("/dev/null", O_WRONLY); + codecs->debug_codec_dump(fd); + close(fd); + }, + + // Since we're dependent on having valid codec_info objects, + // have a change to call fuzz functions for that + [](FuzzedDataProvider* fdp) -> void { + callArbitraryCodecInfoFunction(fdp, a2dp_codec_info_operations); + }}; #endif // BT_STACK_FUZZ_A2DP_CODEC_FUNCTIONS_H_ diff --git a/system/stack/test/fuzzers/a2dp/codec/a2dpCodecFuzzHelpers.h b/system/stack/test/fuzzers/a2dp/codec/a2dpCodecFuzzHelpers.h index 18c2be0cd09..76e5bd64d98 100644 --- a/system/stack/test/fuzzers/a2dp/codec/a2dpCodecFuzzHelpers.h +++ b/system/stack/test/fuzzers/a2dp/codec/a2dpCodecFuzzHelpers.h @@ -21,7 +21,9 @@ // It is included by the corresponding "...Functions.h" file. #include + #include + #include "a2dp_codec_api.h" #include "fuzzers/a2dp/codec/a2dpCodecInfoFuzzHelpers.h" diff --git a/system/stack/test/fuzzers/a2dp/codec/a2dpCodecHelperFunctions.h b/system/stack/test/fuzzers/a2dp/codec/a2dpCodecHelperFunctions.h index 28356deca2b..e507e58e604 100644 --- a/system/stack/test/fuzzers/a2dp/codec/a2dpCodecHelperFunctions.h +++ b/system/stack/test/fuzzers/a2dp/codec/a2dpCodecHelperFunctions.h @@ -23,75 +23,66 @@ #include "stack/include/bt_hdr.h" -static const std::vector CODEC_INDEX_ENUM_VALS = - {BTAV_A2DP_CODEC_INDEX_SOURCE_MIN, - BTAV_A2DP_CODEC_INDEX_SOURCE_SBC, - BTAV_A2DP_CODEC_INDEX_SOURCE_AAC, - BTAV_A2DP_CODEC_INDEX_SOURCE_APTX, - BTAV_A2DP_CODEC_INDEX_SOURCE_APTX_HD, - BTAV_A2DP_CODEC_INDEX_SOURCE_LDAC, - BTAV_A2DP_CODEC_INDEX_SOURCE_MAX, - BTAV_A2DP_CODEC_INDEX_SINK_MIN, - BTAV_A2DP_CODEC_INDEX_SINK_SBC, - BTAV_A2DP_CODEC_INDEX_SINK_AAC, - BTAV_A2DP_CODEC_INDEX_SINK_LDAC, - BTAV_A2DP_CODEC_INDEX_SINK_MAX, - BTAV_A2DP_CODEC_INDEX_MIN, - BTAV_A2DP_CODEC_INDEX_MAX}; - -static const std::vector - CODEC_PRIORITY_ENUM_VALS = {BTAV_A2DP_CODEC_PRIORITY_DISABLED, - BTAV_A2DP_CODEC_PRIORITY_DEFAULT, - BTAV_A2DP_CODEC_PRIORITY_HIGHEST}; - -static const std::vector - CODEC_SAMPLERATE_ENUM_VALS = { +static const std::vector CODEC_INDEX_ENUM_VALS = { + BTAV_A2DP_CODEC_INDEX_SOURCE_MIN, + BTAV_A2DP_CODEC_INDEX_SOURCE_SBC, + BTAV_A2DP_CODEC_INDEX_SOURCE_AAC, + BTAV_A2DP_CODEC_INDEX_SOURCE_APTX, + BTAV_A2DP_CODEC_INDEX_SOURCE_APTX_HD, + BTAV_A2DP_CODEC_INDEX_SOURCE_LDAC, + BTAV_A2DP_CODEC_INDEX_SOURCE_MAX, + BTAV_A2DP_CODEC_INDEX_SINK_MIN, + BTAV_A2DP_CODEC_INDEX_SINK_SBC, + BTAV_A2DP_CODEC_INDEX_SINK_AAC, + BTAV_A2DP_CODEC_INDEX_SINK_LDAC, + BTAV_A2DP_CODEC_INDEX_SINK_MAX, + BTAV_A2DP_CODEC_INDEX_MIN, + BTAV_A2DP_CODEC_INDEX_MAX}; + +static const std::vector CODEC_PRIORITY_ENUM_VALS = { + BTAV_A2DP_CODEC_PRIORITY_DISABLED, BTAV_A2DP_CODEC_PRIORITY_DEFAULT, + BTAV_A2DP_CODEC_PRIORITY_HIGHEST}; + +static const std::vector CODEC_SAMPLERATE_ENUM_VALS = { BTAV_A2DP_CODEC_SAMPLE_RATE_NONE, BTAV_A2DP_CODEC_SAMPLE_RATE_44100, BTAV_A2DP_CODEC_SAMPLE_RATE_48000, BTAV_A2DP_CODEC_SAMPLE_RATE_88200, BTAV_A2DP_CODEC_SAMPLE_RATE_96000, BTAV_A2DP_CODEC_SAMPLE_RATE_176400, BTAV_A2DP_CODEC_SAMPLE_RATE_192000, BTAV_A2DP_CODEC_SAMPLE_RATE_16000, BTAV_A2DP_CODEC_SAMPLE_RATE_24000}; -static const std::vector - CODEC_BPS_ENUM_VALS = {BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE, - BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16, - BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24, - BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32}; +static const std::vector CODEC_BPS_ENUM_VALS = { + BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE, BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16, + BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24, BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32}; -static const std::vector - CODEC_CHANNELMODE_ENUM_VALS = {BTAV_A2DP_CODEC_CHANNEL_MODE_NONE, - BTAV_A2DP_CODEC_CHANNEL_MODE_MONO, - BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO}; +static const std::vector CODEC_CHANNELMODE_ENUM_VALS = { + BTAV_A2DP_CODEC_CHANNEL_MODE_NONE, BTAV_A2DP_CODEC_CHANNEL_MODE_MONO, + BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO}; // Construct a btav_a2dp_codec_index_t object btav_a2dp_codec_index_t getArbitraryBtavCodecIndex(FuzzedDataProvider* fdp) { return CODEC_INDEX_ENUM_VALS.at( - fdp->ConsumeIntegralInRange(0, CODEC_INDEX_ENUM_VALS.size() - 1)); + fdp->ConsumeIntegralInRange(0, CODEC_INDEX_ENUM_VALS.size() - 1)); } // Construct a btav_a2dp_codec_priority_t object -btav_a2dp_codec_priority_t getArbitraryBtavCodecPriority( - FuzzedDataProvider* fdp) { - return CODEC_PRIORITY_ENUM_VALS.at(fdp->ConsumeIntegralInRange( - 0, CODEC_PRIORITY_ENUM_VALS.size() - 1)); +btav_a2dp_codec_priority_t getArbitraryBtavCodecPriority(FuzzedDataProvider* fdp) { + return CODEC_PRIORITY_ENUM_VALS.at( + fdp->ConsumeIntegralInRange(0, CODEC_PRIORITY_ENUM_VALS.size() - 1)); } // Construct a btav_a2dp_codec_sample_rate_t object -btav_a2dp_codec_sample_rate_t getArbitraryBtavCodecSampleRate( - FuzzedDataProvider* fdp) { - return CODEC_SAMPLERATE_ENUM_VALS.at(fdp->ConsumeIntegralInRange( - 0, CODEC_SAMPLERATE_ENUM_VALS.size() - 1)); +btav_a2dp_codec_sample_rate_t getArbitraryBtavCodecSampleRate(FuzzedDataProvider* fdp) { + return CODEC_SAMPLERATE_ENUM_VALS.at( + fdp->ConsumeIntegralInRange(0, CODEC_SAMPLERATE_ENUM_VALS.size() - 1)); } // Construct a btav_a2dp_codec_bits_per_sample_t object -btav_a2dp_codec_bits_per_sample_t getArbitraryBtavCodecBitsPerSample( - FuzzedDataProvider* fdp) { +btav_a2dp_codec_bits_per_sample_t getArbitraryBtavCodecBitsPerSample(FuzzedDataProvider* fdp) { return CODEC_BPS_ENUM_VALS.at( - fdp->ConsumeIntegralInRange(0, CODEC_BPS_ENUM_VALS.size() - 1)); + fdp->ConsumeIntegralInRange(0, CODEC_BPS_ENUM_VALS.size() - 1)); } // Construct a btav_a2dp_codec_channel_mode_t object -btav_a2dp_codec_channel_mode_t getArbitraryBtavCodecChannelMode( - FuzzedDataProvider* fdp) { - return CODEC_CHANNELMODE_ENUM_VALS.at(fdp->ConsumeIntegralInRange( - 0, CODEC_CHANNELMODE_ENUM_VALS.size() - 1)); +btav_a2dp_codec_channel_mode_t getArbitraryBtavCodecChannelMode(FuzzedDataProvider* fdp) { + return CODEC_CHANNELMODE_ENUM_VALS.at( + fdp->ConsumeIntegralInRange(0, CODEC_CHANNELMODE_ENUM_VALS.size() - 1)); } // Construct a btav_a2dp_codec_config_t object btav_a2dp_codec_config_t getArbitraryBtavCodecConfig(FuzzedDataProvider* fdp) { @@ -110,8 +101,7 @@ btav_a2dp_codec_config_t getArbitraryBtavCodecConfig(FuzzedDataProvider* fdp) { return config; } -tA2DP_ENCODER_INIT_PEER_PARAMS getArbitraryA2dpEncoderInitPeerParams( - FuzzedDataProvider* fdp) { +tA2DP_ENCODER_INIT_PEER_PARAMS getArbitraryA2dpEncoderInitPeerParams(FuzzedDataProvider* fdp) { tA2DP_ENCODER_INIT_PEER_PARAMS params; params.is_peer_edr = fdp->ConsumeBool(); @@ -132,13 +122,11 @@ std::shared_ptr getArbitraryBtHdr(FuzzedDataProvider* fdp) { } uint16_t hdr_size = bytes.size() + sizeof(BT_HDR); - std::shared_ptr bt_hdr(reinterpret_cast(calloc(1, hdr_size)), - free); + std::shared_ptr bt_hdr(reinterpret_cast(calloc(1, hdr_size)), free); bt_hdr->event = fdp->ConsumeIntegral(); bt_hdr->len = bytes.size(); - bt_hdr->offset = - fdp->ConsumeIntegralInRange(0, hdr_size - sizeof(BT_HDR)); + bt_hdr->offset = fdp->ConsumeIntegralInRange(0, hdr_size - sizeof(BT_HDR)); bt_hdr->layer_specific = fdp->ConsumeIntegral(); std::copy(bytes.begin(), bytes.end(), bt_hdr->data); @@ -162,8 +150,7 @@ tBT_A2DP_OFFLOAD generateArbitrarytA2dpOffload(FuzzedDataProvider* fdp) { retval.mtu = fdp->ConsumeIntegral(); std::vector codec_info_bytes = fdp->ConsumeBytes(32); - memcpy(&retval.codec_info[0], codec_info_bytes.data(), - codec_info_bytes.size()); + memcpy(&retval.codec_info[0], codec_info_bytes.data(), codec_info_bytes.size()); return retval; } diff --git a/system/stack/test/fuzzers/a2dp/codec/a2dpCodecInfoFuzzFunctions.h b/system/stack/test/fuzzers/a2dp/codec/a2dpCodecInfoFuzzFunctions.h index 30c5d710ba1..0c52ac380b4 100644 --- a/system/stack/test/fuzzers/a2dp/codec/a2dpCodecInfoFuzzFunctions.h +++ b/system/stack/test/fuzzers/a2dp/codec/a2dpCodecInfoFuzzFunctions.h @@ -34,8 +34,7 @@ * without requiring modifications to the main fuzzer file. This also * allows multiple fuzzers to include this file, if functionality is needed. */ -std::vector> - a2dp_codec_info_operations = { +std::vector> a2dp_codec_info_operations = { // A2DP_InitDefaultCodec [](FuzzedDataProvider* fdp, uint8_t*) -> void { // Allocate space for a new codec & add it to our tracking vector @@ -51,8 +50,7 @@ std::vector> return; } // Get random vector index - size_t index = fdp->ConsumeIntegralInRange( - 0, a2dp_codec_info_vect.size() - 1); + size_t index = fdp->ConsumeIntegralInRange(0, a2dp_codec_info_vect.size() - 1); // delete codec delete a2dp_codec_info_vect.at(index); // Remove from vector @@ -60,9 +58,7 @@ std::vector> }, // A2DP_GetCodecType - [](FuzzedDataProvider* fdp, uint8_t* codec_info) -> void { - A2DP_GetCodecType(codec_info); - }, + [](FuzzedDataProvider* fdp, uint8_t* codec_info) -> void { A2DP_GetCodecType(codec_info); }, // A2DP_IsSourceCodecValid [](FuzzedDataProvider* fdp, uint8_t* codec_info) -> void { @@ -100,19 +96,14 @@ std::vector> }, // A2DP_GetMediaType - [](FuzzedDataProvider* fdp, uint8_t* codec_info) -> void { - A2DP_GetMediaType(codec_info); - }, + [](FuzzedDataProvider* fdp, uint8_t* codec_info) -> void { A2DP_GetMediaType(codec_info); }, // A2DP_CodecName - [](FuzzedDataProvider* fdp, uint8_t* codec_info) -> void { - A2DP_CodecName(codec_info); - }, + [](FuzzedDataProvider* fdp, uint8_t* codec_info) -> void { A2DP_CodecName(codec_info); }, // A2DP_CodecTypeEquals [](FuzzedDataProvider* fdp, uint8_t* codec_info) -> void { - uint8_t* codec_info_2 = - getArbitraryVectorElement(fdp, a2dp_codec_info_vect, false); + uint8_t* codec_info_2 = getArbitraryVectorElement(fdp, a2dp_codec_info_vect, false); if (codec_info_2) { A2DP_CodecTypeEquals(codec_info, codec_info_2); } @@ -120,8 +111,7 @@ std::vector> // A2DP_CodecEquals [](FuzzedDataProvider* fdp, uint8_t* codec_info) -> void { - uint8_t* codec_info_2 = - getArbitraryVectorElement(fdp, a2dp_codec_info_vect, false); + uint8_t* codec_info_2 = getArbitraryVectorElement(fdp, a2dp_codec_info_vect, false); if (codec_info_2) { A2DP_CodecEquals(codec_info, codec_info_2); } @@ -150,8 +140,7 @@ std::vector> // A2DP_GetPacketTimestamp [](FuzzedDataProvider* fdp, uint8_t* codec_info) -> void { uint32_t timestamp_retval; - size_t packet_size = - fdp->ConsumeIntegralInRange(0, MAX_PACKET_SIZE); + size_t packet_size = fdp->ConsumeIntegralInRange(0, MAX_PACKET_SIZE); std::vector bytes = fdp->ConsumeBytes(packet_size); // Timestamp will fail if p_data is < 4 bytes, due to a cast & deref // to a uint32_t* @@ -183,9 +172,7 @@ std::vector> }, // A2DP_AdjustCodec - [](FuzzedDataProvider* fdp, uint8_t* codec_info) -> void { - A2DP_AdjustCodec(codec_info); - }, + [](FuzzedDataProvider* fdp, uint8_t* codec_info) -> void { A2DP_AdjustCodec(codec_info); }, // A2DP_SourceCodecIndex [](FuzzedDataProvider* fdp, uint8_t* codec_info) -> void { diff --git a/system/stack/test/fuzzers/a2dp/codec/a2dpCodecInfoFuzzHelpers.h b/system/stack/test/fuzzers/a2dp/codec/a2dpCodecInfoFuzzHelpers.h index 434cabd2676..64f8cb9f6bc 100644 --- a/system/stack/test/fuzzers/a2dp/codec/a2dpCodecInfoFuzzHelpers.h +++ b/system/stack/test/fuzzers/a2dp/codec/a2dpCodecInfoFuzzHelpers.h @@ -33,20 +33,16 @@ std::vector a2dp_codec_info_vect; // Calls a function from the ops_vector void callArbitraryCodecInfoFunction( - FuzzedDataProvider* fdp, - std::vector> - ops_vector) { + FuzzedDataProvider* fdp, + std::vector> ops_vector) { // Choose which function we'll be calling - uint8_t function_id = - fdp->ConsumeIntegralInRange(0, ops_vector.size() - 1); + uint8_t function_id = fdp->ConsumeIntegralInRange(0, ops_vector.size() - 1); // Get a info object - uint8_t* codec_info = - getArbitraryVectorElement(fdp, a2dp_codec_info_vect, false); + uint8_t* codec_info = getArbitraryVectorElement(fdp, a2dp_codec_info_vect, false); // Most functions require a valid codec_info - if (codec_info || function_id == 0 || function_id == 25 || - function_id == 26) { + if (codec_info || function_id == 0 || function_id == 25 || function_id == 26) { // Call the function we've chosen ops_vector[function_id](fdp, codec_info); } diff --git a/system/stack/test/fuzzers/a2dp/codec/fuzz_a2dp_codec.cc b/system/stack/test/fuzzers/a2dp/codec/fuzz_a2dp_codec.cc index f124fd7bb0f..1caeef5d0b7 100644 --- a/system/stack/test/fuzzers/a2dp/codec/fuzz_a2dp_codec.cc +++ b/system/stack/test/fuzzers/a2dp/codec/fuzz_a2dp_codec.cc @@ -15,6 +15,7 @@ */ #include + #include "fuzzers/a2dp/codec/a2dpCodecFuzzFunctions.h" #include "fuzzers/common/commonFuzzHelpers.h" diff --git a/system/stack/test/fuzzers/a2dp/codec/fuzz_a2dp_codec_config.cc b/system/stack/test/fuzzers/a2dp/codec/fuzz_a2dp_codec_config.cc index 97cac26c7ff..a5ca85c0962 100644 --- a/system/stack/test/fuzzers/a2dp/codec/fuzz_a2dp_codec_config.cc +++ b/system/stack/test/fuzzers/a2dp/codec/fuzz_a2dp_codec_config.cc @@ -15,6 +15,7 @@ */ #include + #include "fuzzers/a2dp/codec/a2dpCodecConfigFuzzFunctions.h" #include "fuzzers/common/commonFuzzHelpers.h" diff --git a/system/stack/test/fuzzers/a2dp/codec/fuzz_a2dp_codec_info.cc b/system/stack/test/fuzzers/a2dp/codec/fuzz_a2dp_codec_info.cc index 93eacc8dab5..7bfda04ec68 100644 --- a/system/stack/test/fuzzers/a2dp/codec/fuzz_a2dp_codec_info.cc +++ b/system/stack/test/fuzzers/a2dp/codec/fuzz_a2dp_codec_info.cc @@ -15,6 +15,7 @@ */ #include + #include "fuzzers/a2dp/codec/a2dpCodecInfoFuzzFunctions.h" #include "fuzzers/common/commonFuzzHelpers.h" diff --git a/system/stack/test/fuzzers/a2dp/fuzz_a2dp.cc b/system/stack/test/fuzzers/a2dp/fuzz_a2dp.cc index 34ef7d31ced..52bd36ef4ef 100644 --- a/system/stack/test/fuzzers/a2dp/fuzz_a2dp.cc +++ b/system/stack/test/fuzzers/a2dp/fuzz_a2dp.cc @@ -15,6 +15,7 @@ */ #include + #include "a2dp_api.h" #include "fuzzers/a2dp/a2dpFuzzFunctions.h" #include "fuzzers/common/commonFuzzHelpers.h" diff --git a/system/stack/test/fuzzers/avrc/fuzz_avrc.cc b/system/stack/test/fuzzers/avrc/fuzz_avrc.cc index 33b0da44a3b..1309addc518 100644 --- a/system/stack/test/fuzzers/avrc/fuzz_avrc.cc +++ b/system/stack/test/fuzzers/avrc/fuzz_avrc.cc @@ -102,24 +102,18 @@ static void free_avrc_response(tAVRC_RESPONSE& result) { for (int i = 0; i < result.get_items.item_count; i++) { switch (result.get_items.p_item_list[i].item_type) { case AVRC_ITEM_PLAYER: - osi_free_and_reset( - (void**)&result.get_items.p_item_list[i].u.player.name.p_str); + osi_free_and_reset((void**)&result.get_items.p_item_list[i].u.player.name.p_str); break; case AVRC_ITEM_FOLDER: - osi_free_and_reset( - (void**)&result.get_items.p_item_list[i].u.folder.name.p_str); + osi_free_and_reset((void**)&result.get_items.p_item_list[i].u.folder.name.p_str); break; case AVRC_ITEM_MEDIA: - osi_free_and_reset( - (void**)&result.get_items.p_item_list[i].u.media.name.p_str); - for (int j = 0; - j < result.get_items.p_item_list[i].u.media.attr_count; j++) { - osi_free_and_reset((void**)&result.get_items.p_item_list[i] - .u.media.p_attr_list[j] - .name.p_str); + osi_free_and_reset((void**)&result.get_items.p_item_list[i].u.media.name.p_str); + for (int j = 0; j < result.get_items.p_item_list[i].u.media.attr_count; j++) { + osi_free_and_reset( + (void**)&result.get_items.p_item_list[i].u.media.p_attr_list[j].name.p_str); } - osi_free_and_reset( - (void**)&result.get_items.p_item_list[i].u.media.p_attr_list); + osi_free_and_reset((void**)&result.get_items.p_item_list[i].u.media.p_attr_list); break; } } @@ -150,7 +144,9 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { tAVRC_MSG msg{}; tAVRC_RESPONSE result{}; - if (size < 2) return 0; + if (size < 2) { + return 0; + } /* 4 command type codes * AVRC_CMD_CTRL 0 diff --git a/system/stack/test/fuzzers/common/commonFuzzHelpers.h b/system/stack/test/fuzzers/common/commonFuzzHelpers.h index 59759395f9a..4a138e56e15 100644 --- a/system/stack/test/fuzzers/common/commonFuzzHelpers.h +++ b/system/stack/test/fuzzers/common/commonFuzzHelpers.h @@ -27,20 +27,17 @@ #include "types/raw_address.h" // Calls a function from the ops_vector -void callArbitraryFunction( - FuzzedDataProvider* fdp, - std::vector> ops_vector) { +void callArbitraryFunction(FuzzedDataProvider* fdp, + std::vector> ops_vector) { // Choose which function we'll be calling - uint8_t function_id = - fdp->ConsumeIntegralInRange(0, ops_vector.size() - 1); + uint8_t function_id = fdp->ConsumeIntegralInRange(0, ops_vector.size() - 1); // Call the function we've chosen ops_vector[function_id](fdp); } template -T getArbitraryVectorElement(FuzzedDataProvider* fdp, std::vector vect, - bool allow_null) { +T getArbitraryVectorElement(FuzzedDataProvider* fdp, std::vector vect, bool allow_null) { // If we're allowing null, give it a 50:50 shot at returning a zero element // (Or if the vector's empty) if (vect.empty() || (allow_null && fdp->ConsumeBool())) { @@ -67,8 +64,7 @@ RawAddress generateRawAddress(FuzzedDataProvider* fdp) { } bluetooth::Uuid generateArbitraryUuid(FuzzedDataProvider* fdp) { - std::vector bytes_vect = - fdp->ConsumeBytes(bluetooth::Uuid::kNumBytes128); + std::vector bytes_vect = fdp->ConsumeBytes(bluetooth::Uuid::kNumBytes128); // We need it to be the correct size regardless of if fdp ran out of bytes while (bytes_vect.size() < bluetooth::Uuid::kNumBytes128) { bytes_vect.push_back('\0'); diff --git a/system/stack/test/fuzzers/sdp/fuzz_sdp.cc b/system/stack/test/fuzzers/sdp/fuzz_sdp.cc index 20e773de7c2..74caf6b642a 100644 --- a/system/stack/test/fuzzers/sdp/fuzz_sdp.cc +++ b/system/stack/test/fuzzers/sdp/fuzz_sdp.cc @@ -15,6 +15,7 @@ */ #include + #include "fuzzers/common/commonFuzzHelpers.h" #include "fuzzers/sdp/sdpFuzzFunctions.h" diff --git a/system/stack/test/fuzzers/sdp/sdpFuzzFunctions.h b/system/stack/test/fuzzers/sdp/sdpFuzzFunctions.h index 940e97814c2..7c91f6490cb 100644 --- a/system/stack/test/fuzzers/sdp/sdpFuzzFunctions.h +++ b/system/stack/test/fuzzers/sdp/sdpFuzzFunctions.h @@ -36,8 +36,7 @@ * without requiring modifications to the main fuzzer file. This also * allows multiple fuzzers to include this file, if functionality is needed. */ -static const std::vector> - sdp_operations = { +static const std::vector> sdp_operations = { // ::SDP_InitDiscoveryDb [](FuzzedDataProvider* fdp) -> void { if (sdp_db_vect.size() >= MAX_NUM_DBS) { @@ -54,15 +53,12 @@ static const std::vector> // build out attr_list std::vector attr_list = generateArbitraryAttrList(fdp); - uint32_t db_size = - fdp->ConsumeIntegralInRange(0, SDP_MAX_DB_LEN); + uint32_t db_size = fdp->ConsumeIntegralInRange(0, SDP_MAX_DB_LEN); std::shared_ptr p_db( - reinterpret_cast(malloc(db_size)), free); + reinterpret_cast(malloc(db_size)), free); if (p_db) { - bool success = - get_legacy_stack_sdp_api()->service.SDP_InitDiscoveryDb( - p_db.get(), db_size, uuid_list.size(), uuid_list.data(), - attr_list.size(), + bool success = get_legacy_stack_sdp_api()->service.SDP_InitDiscoveryDb( + p_db.get(), db_size, uuid_list.size(), uuid_list.data(), attr_list.size(), reinterpret_cast(attr_list.data())); if (success) { sdp_db_vect.push_back(p_db); @@ -72,19 +68,16 @@ static const std::vector> // ::SDP_CancelServiceSearch [](FuzzedDataProvider* fdp) -> void { - [[maybe_unused]] bool rc = - get_legacy_stack_sdp_api()->service.SDP_CancelServiceSearch( + [[maybe_unused]] bool rc = get_legacy_stack_sdp_api()->service.SDP_CancelServiceSearch( getArbitraryVectorElement(fdp, sdp_db_vect, true).get()); }, // ::SDP_ServiceSearchRequest [](FuzzedDataProvider* fdp) -> void { const RawAddress bd_addr = generateRawAddress(fdp); - tSDP_DISCOVERY_DB* db = - getArbitraryVectorElement(fdp, sdp_db_vect, false).get(); + tSDP_DISCOVERY_DB* db = getArbitraryVectorElement(fdp, sdp_db_vect, false).get(); if (db) { - [[maybe_unused]] bool rc = - get_legacy_stack_sdp_api()->service.SDP_ServiceSearchRequest( + [[maybe_unused]] bool rc = get_legacy_stack_sdp_api()->service.SDP_ServiceSearchRequest( bd_addr, db, &sdp_disc_cmpl_cb); } }, @@ -92,46 +85,38 @@ static const std::vector> // ::SDP_ServiceSearchAttributeRequest [](FuzzedDataProvider* fdp) -> void { const RawAddress bd_addr = generateRawAddress(fdp); - tSDP_DISCOVERY_DB* db = - getArbitraryVectorElement(fdp, sdp_db_vect, false).get(); + tSDP_DISCOVERY_DB* db = getArbitraryVectorElement(fdp, sdp_db_vect, false).get(); if (db) { [[maybe_unused]] bool rc = - get_legacy_stack_sdp_api() - ->service.SDP_ServiceSearchAttributeRequest( - bd_addr, db, &sdp_disc_cmpl_cb); + get_legacy_stack_sdp_api()->service.SDP_ServiceSearchAttributeRequest( + bd_addr, db, &sdp_disc_cmpl_cb); } }, // ::SDP_ServiceSearchAttributeRequest2 [](FuzzedDataProvider* fdp) -> void { const RawAddress bd_addr = generateRawAddress(fdp); - std::vector user_data = fdp->ConsumeBytes( - fdp->ConsumeIntegralInRange(0, 1024)); - tSDP_DISCOVERY_DB* db = - getArbitraryVectorElement(fdp, sdp_db_vect, false).get(); + std::vector user_data = + fdp->ConsumeBytes(fdp->ConsumeIntegralInRange(0, 1024)); + tSDP_DISCOVERY_DB* db = getArbitraryVectorElement(fdp, sdp_db_vect, false).get(); if (db) { [[maybe_unused]] bool rc = - get_legacy_stack_sdp_api() - ->service.SDP_ServiceSearchAttributeRequest2( - bd_addr, db, - base::BindRepeating(&sdp_disc_cmpl_cb2, user_data)); + get_legacy_stack_sdp_api()->service.SDP_ServiceSearchAttributeRequest2( + bd_addr, db, base::BindRepeating(&sdp_disc_cmpl_cb2, user_data)); } }, // ::SDP_FindAttributeInRec [](FuzzedDataProvider* fdp) -> void { - tSDP_DISC_REC* p_rec = - generateArbitrarySdpDiscRecord(fdp, false).get(); - [[maybe_unused]] bool rc = - get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( + tSDP_DISC_REC* p_rec = generateArbitrarySdpDiscRecord(fdp, false).get(); + [[maybe_unused]] bool rc = get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( p_rec, fdp->ConsumeIntegral()); }, // ::SDP_FindServiceInDb [](FuzzedDataProvider* fdp) -> void { - [[maybe_unused]] bool rc = - get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb( + [[maybe_unused]] bool rc = get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb( getArbitraryVectorElement(fdp, sdp_db_vect, true).get(), fdp->ConsumeIntegral(), generateArbitrarySdpDiscRecord(fdp, true).get()); @@ -140,8 +125,7 @@ static const std::vector> // ::SDP_FindServiceUUIDInDb [](FuzzedDataProvider* fdp) -> void { const bluetooth::Uuid uuid = generateArbitraryUuid(fdp); - [[maybe_unused]] bool rc = - get_legacy_stack_sdp_api()->db.SDP_FindServiceUUIDInDb( + [[maybe_unused]] bool rc = get_legacy_stack_sdp_api()->db.SDP_FindServiceUUIDInDb( getArbitraryVectorElement(fdp, sdp_db_vect, true).get(), uuid, generateArbitrarySdpDiscRecord(fdp, true).get()); }, @@ -149,17 +133,14 @@ static const std::vector> // ::SDP_FindServiceUUIDInRec_128bit [](FuzzedDataProvider* fdp) -> void { bluetooth::Uuid uuid = generateArbitraryUuid(fdp); - tSDP_DISC_REC* p_rec = - generateArbitrarySdpDiscRecord(fdp, false).get(); + tSDP_DISC_REC* p_rec = generateArbitrarySdpDiscRecord(fdp, false).get(); [[maybe_unused]] bool rc = - get_legacy_stack_sdp_api() - ->record.SDP_FindServiceUUIDInRec_128bit(p_rec, &uuid); + get_legacy_stack_sdp_api()->record.SDP_FindServiceUUIDInRec_128bit(p_rec, &uuid); }, // ::SDP_FindServiceInDb_128bit [](FuzzedDataProvider* fdp) -> void { - [[maybe_unused]] bool rc = - get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb_128bit( + [[maybe_unused]] bool rc = get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb_128bit( getArbitraryVectorElement(fdp, sdp_db_vect, true).get(), generateArbitrarySdpDiscRecord(fdp, true).get()); }, @@ -167,28 +148,24 @@ static const std::vector> // ::SDP_FindProtocolListElemInRec [](FuzzedDataProvider* fdp) -> void { tSDP_PROTOCOL_ELEM elem = generateArbitrarySdpProtocolElements(fdp); - tSDP_DISC_REC* p_rec = - generateArbitrarySdpDiscRecord(fdp, false).get(); + tSDP_DISC_REC* p_rec = generateArbitrarySdpDiscRecord(fdp, false).get(); [[maybe_unused]] bool rc = - get_legacy_stack_sdp_api()->record.SDP_FindProtocolListElemInRec( - p_rec, fdp->ConsumeIntegral(), &elem); + get_legacy_stack_sdp_api()->record.SDP_FindProtocolListElemInRec( + p_rec, fdp->ConsumeIntegral(), &elem); }, // ::SDP_FindProfileVersionInRec [](FuzzedDataProvider* fdp) -> void { uint16_t p_version; - tSDP_DISC_REC* p_rec = - generateArbitrarySdpDiscRecord(fdp, false).get(); + tSDP_DISC_REC* p_rec = generateArbitrarySdpDiscRecord(fdp, false).get(); - [[maybe_unused]] bool rc = - get_legacy_stack_sdp_api()->record.SDP_FindProfileVersionInRec( + [[maybe_unused]] bool rc = get_legacy_stack_sdp_api()->record.SDP_FindProfileVersionInRec( p_rec, fdp->ConsumeIntegral(), &p_version); }, // ::SDP_CreateRecord [](FuzzedDataProvider* fdp) -> void { - uint32_t handle = - get_legacy_stack_sdp_api()->handle.SDP_CreateRecord(); + uint32_t handle = get_legacy_stack_sdp_api()->handle.SDP_CreateRecord(); if (handle) { sdp_record_handles.push_back(handle); } @@ -196,21 +173,19 @@ static const std::vector> // ::SDP_DeleteRecord [](FuzzedDataProvider* fdp) -> void { - [[maybe_unused]] bool rc = - get_legacy_stack_sdp_api()->handle.SDP_DeleteRecord( + [[maybe_unused]] bool rc = get_legacy_stack_sdp_api()->handle.SDP_DeleteRecord( getArbitraryVectorElement(fdp, sdp_record_handles, true)); }, // ::SDP_AddAttribute [](FuzzedDataProvider* fdp) -> void { - std::vector val = fdp->ConsumeBytes( - fdp->ConsumeIntegralInRange(1, 1024)); + std::vector val = + fdp->ConsumeBytes(fdp->ConsumeIntegralInRange(1, 1024)); if (val.size() > 0) { - [[maybe_unused]] bool rc = - get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( + [[maybe_unused]] bool rc = get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( getArbitraryVectorElement(fdp, sdp_record_handles, true), - fdp->ConsumeIntegral(), - fdp->ConsumeIntegral(), val.size(), val.data()); + fdp->ConsumeIntegral(), fdp->ConsumeIntegral(), val.size(), + val.data()); } }, @@ -218,11 +193,10 @@ static const std::vector> [](FuzzedDataProvider* fdp) -> void { SDP_Sequence_Helper seq = generateArbitrarySdpElemSequence(fdp); - [[maybe_unused]] bool rc = - get_legacy_stack_sdp_api()->handle.SDP_AddSequence( + [[maybe_unused]] bool rc = get_legacy_stack_sdp_api()->handle.SDP_AddSequence( getArbitraryVectorElement(fdp, sdp_record_handles, true), - fdp->ConsumeIntegral(), seq.num_elem, - seq.type.get(), seq.len.get(), seq.p_val.get()); + fdp->ConsumeIntegral(), seq.num_elem, seq.type.get(), seq.len.get(), + seq.p_val.get()); }, // ::SDP_AddUuidSequence @@ -233,8 +207,7 @@ static const std::vector> uuids[i] = fdp->ConsumeIntegral(); } - [[maybe_unused]] bool rc = - get_legacy_stack_sdp_api()->handle.SDP_AddUuidSequence( + [[maybe_unused]] bool rc = get_legacy_stack_sdp_api()->handle.SDP_AddUuidSequence( getArbitraryVectorElement(fdp, sdp_record_handles, true), fdp->ConsumeIntegral(), num_uuids, uuids); delete[] uuids; @@ -243,13 +216,11 @@ static const std::vector> // ::SDP_AddProtocolList [](FuzzedDataProvider* fdp) -> void { std::shared_ptr p_proto_list = - generateArbitrarySdpProtocolElementList(fdp); + generateArbitrarySdpProtocolElementList(fdp); if (p_proto_list) { - [[maybe_unused]] bool rc = - get_legacy_stack_sdp_api()->handle.SDP_AddProtocolList( + [[maybe_unused]] bool rc = get_legacy_stack_sdp_api()->handle.SDP_AddProtocolList( getArbitraryVectorElement(fdp, sdp_record_handles, true), - p_proto_list.get()->num_elems, - p_proto_list.get()->list_elem); + p_proto_list.get()->num_elems, p_proto_list.get()->list_elem); } }, @@ -257,13 +228,13 @@ static const std::vector> [](FuzzedDataProvider* fdp) -> void { uint16_t arr_size; tSDP_PROTO_LIST_ELEM** p_proto_list = - generateArbitrarySdpProtocolElementListArray(fdp, &arr_size); + generateArbitrarySdpProtocolElementListArray(fdp, &arr_size); if (p_proto_list) { if (p_proto_list[0]) { [[maybe_unused]] bool rc = - get_legacy_stack_sdp_api()->handle.SDP_AddAdditionProtoLists( - getArbitraryVectorElement(fdp, sdp_record_handles, true), - arr_size, p_proto_list[0]); + get_legacy_stack_sdp_api()->handle.SDP_AddAdditionProtoLists( + getArbitraryVectorElement(fdp, sdp_record_handles, true), arr_size, + p_proto_list[0]); for (uint16_t i = 0; i < arr_size; i++) { delete p_proto_list[i]; } @@ -275,20 +246,18 @@ static const std::vector> // ::SDP_AddProfileDescriptorList [](FuzzedDataProvider* fdp) -> void { [[maybe_unused]] bool rc = - get_legacy_stack_sdp_api()->handle.SDP_AddProfileDescriptorList( - getArbitraryVectorElement(fdp, sdp_record_handles, true), - fdp->ConsumeIntegral(), - fdp->ConsumeIntegral()); + get_legacy_stack_sdp_api()->handle.SDP_AddProfileDescriptorList( + getArbitraryVectorElement(fdp, sdp_record_handles, true), + fdp->ConsumeIntegral(), fdp->ConsumeIntegral()); }, // ::SDP_AddLanguageBaseAttrIDList [](FuzzedDataProvider* fdp) -> void { [[maybe_unused]] bool rc = - get_legacy_stack_sdp_api()->handle.SDP_AddLanguageBaseAttrIDList( - getArbitraryVectorElement(fdp, sdp_record_handles, true), - fdp->ConsumeIntegral(), - fdp->ConsumeIntegral(), - fdp->ConsumeIntegral()); + get_legacy_stack_sdp_api()->handle.SDP_AddLanguageBaseAttrIDList( + getArbitraryVectorElement(fdp, sdp_record_handles, true), + fdp->ConsumeIntegral(), fdp->ConsumeIntegral(), + fdp->ConsumeIntegral()); }, // ::SDP_AddServiceClassIdList @@ -299,10 +268,9 @@ static const std::vector> service_uuids[i] = fdp->ConsumeIntegral(); } - [[maybe_unused]] bool rc = - get_legacy_stack_sdp_api()->handle.SDP_AddServiceClassIdList( - getArbitraryVectorElement(fdp, sdp_record_handles, true), - num_services, service_uuids); + [[maybe_unused]] bool rc = get_legacy_stack_sdp_api()->handle.SDP_AddServiceClassIdList( + getArbitraryVectorElement(fdp, sdp_record_handles, true), num_services, + service_uuids); delete[] service_uuids; }, @@ -312,8 +280,7 @@ static const std::vector> uint32_t handle; // Output var tSDP_DI_RECORD device_info = generateArbitrarySdpDiRecord(fdp); [[maybe_unused]] bool rc = - get_legacy_stack_sdp_api()->device_id.SDP_SetLocalDiRecord( - &device_info, &handle); + get_legacy_stack_sdp_api()->device_id.SDP_SetLocalDiRecord(&device_info, &handle); }, // ::SDP_DiDiscover @@ -321,41 +288,35 @@ static const std::vector> const RawAddress remote_device = generateRawAddress(fdp); // Create a new buffer for the discoveryDB init call - uint32_t db_size = - fdp->ConsumeIntegralInRange(0, SDP_MAX_DB_LEN); + uint32_t db_size = fdp->ConsumeIntegralInRange(0, SDP_MAX_DB_LEN); std::shared_ptr p_db( - reinterpret_cast(malloc(db_size)), free); + reinterpret_cast(malloc(db_size)), free); if (p_db) { - [[maybe_unused]] bool rc = - get_legacy_stack_sdp_api()->device_id.SDP_DiDiscover( + [[maybe_unused]] bool rc = get_legacy_stack_sdp_api()->device_id.SDP_DiDiscover( remote_device, p_db.get(), db_size, &sdp_disc_cmpl_cb); } }, // ::SDP_GetNumDiRecords [](FuzzedDataProvider* fdp) -> void { - [[maybe_unused]] bool rc = - get_legacy_stack_sdp_api()->device_id.SDP_GetNumDiRecords( + [[maybe_unused]] bool rc = get_legacy_stack_sdp_api()->device_id.SDP_GetNumDiRecords( getArbitraryVectorElement(fdp, sdp_db_vect, true).get()); }, // ::SDP_GetDiRecord [](FuzzedDataProvider* fdp) -> void { tSDP_DI_GET_RECORD device_info; // Output var - [[maybe_unused]] bool rc = - get_legacy_stack_sdp_api()->device_id.SDP_GetDiRecord( + [[maybe_unused]] bool rc = get_legacy_stack_sdp_api()->device_id.SDP_GetDiRecord( fdp->ConsumeIntegral(), &device_info, getArbitraryVectorElement(fdp, sdp_db_vect, true).get()); }, // ::SDP_FindServiceUUIDInRec [](FuzzedDataProvider* fdp) -> void { - tSDP_DISC_REC* p_rec = - generateArbitrarySdpDiscRecord(fdp, false).get(); + tSDP_DISC_REC* p_rec = generateArbitrarySdpDiscRecord(fdp, false).get(); bluetooth::Uuid uuid; // Output var [[maybe_unused]] bool rc = - get_legacy_stack_sdp_api()->record.SDP_FindServiceUUIDInRec( - p_rec, &uuid); + get_legacy_stack_sdp_api()->record.SDP_FindServiceUUIDInRec(p_rec, &uuid); }}; #endif // FUZZER_SDP_FUNCTIONS_H_ diff --git a/system/stack/test/fuzzers/sdp/sdpFuzzHelpers.h b/system/stack/test/fuzzers/sdp/sdpFuzzHelpers.h index 5ad3d0e3b16..a22accbf746 100644 --- a/system/stack/test/fuzzers/sdp/sdpFuzzHelpers.h +++ b/system/stack/test/fuzzers/sdp/sdpFuzzHelpers.h @@ -56,8 +56,7 @@ std::vector> sdp_disc_rec_vect; std::vector> sdp_disc_attr_vect; std::vector> sdp_protolist_elem_vect; -std::shared_ptr generateArbitrarySdpDiscAttr( - FuzzedDataProvider*, bool); +std::shared_ptr generateArbitrarySdpDiscAttr(FuzzedDataProvider*, bool); static bool initialized = false; void setupSdpFuzz() { @@ -79,8 +78,7 @@ void cleanupSdpFuzz() { sdp_protolist_elem_vect.clear(); // Delete all records - [[maybe_unused]] bool rc = - get_legacy_stack_sdp_api()->handle.SDP_DeleteRecord(0); + [[maybe_unused]] bool rc = get_legacy_stack_sdp_api()->handle.SDP_DeleteRecord(0); sdp_record_handles.clear(); // Delete Databases @@ -113,11 +111,10 @@ tSDP_DISC_ATVAL generateArbitrarySdpDiscAttrVal(FuzzedDataProvider* fdp) { return new_attrval; } -std::shared_ptr generateArbitrarySdpDiscAttr( - FuzzedDataProvider* fdp, bool allow_null) { +std::shared_ptr generateArbitrarySdpDiscAttr(FuzzedDataProvider* fdp, + bool allow_null) { // Give it a chance to return a nullptr - if ((allow_null && !fdp->ConsumeBool()) || - sdp_disc_attr_vect.size() > kMaxVectorSize) { + if ((allow_null && !fdp->ConsumeBool()) || sdp_disc_attr_vect.size() > kMaxVectorSize) { return nullptr; } @@ -125,17 +122,16 @@ std::shared_ptr generateArbitrarySdpDiscAttr( sdp_disc_attr_vect.push_back(new_attr); new_attr->p_next_attr = generateArbitrarySdpDiscAttr(fdp, true).get(); - new_attr->attr_id = fdp->ConsumeBool() ? ATTR_ID_BT_PROFILE_DESC_LIST - : fdp->ConsumeIntegral(); - new_attr->attr_len_type = - fdp->ConsumeBool() ? 16 : fdp->ConsumeIntegral(); + new_attr->attr_id = + fdp->ConsumeBool() ? ATTR_ID_BT_PROFILE_DESC_LIST : fdp->ConsumeIntegral(); + new_attr->attr_len_type = fdp->ConsumeBool() ? 16 : fdp->ConsumeIntegral(); new_attr->attr_value = generateArbitrarySdpDiscAttrVal(fdp); return new_attr; } -std::shared_ptr generateArbitrarySdpDiscRecord( - FuzzedDataProvider* fdp, bool allow_null) { +std::shared_ptr generateArbitrarySdpDiscRecord(FuzzedDataProvider* fdp, + bool allow_null) { // Give it a chance to return a nullptr if (allow_null && !fdp->ConsumeBool()) { return nullptr; @@ -152,16 +148,14 @@ std::shared_ptr generateArbitrarySdpDiscRecord( return new_rec; } -tSDP_PROTOCOL_ELEM generateArbitrarySdpProtocolElements( - FuzzedDataProvider* fdp) { +tSDP_PROTOCOL_ELEM generateArbitrarySdpProtocolElements(FuzzedDataProvider* fdp) { tSDP_PROTOCOL_ELEM p_elem; // Set our protocol element values p_elem.protocol_uuid = fdp->ConsumeIntegral(); - p_elem.num_params = - fdp->ConsumeIntegralInRange(0, SDP_MAX_PROTOCOL_PARAMS); - uint16_t num_loops = std::min( - p_elem.num_params, static_cast(SDP_MAX_PROTOCOL_PARAMS)); + p_elem.num_params = fdp->ConsumeIntegralInRange(0, SDP_MAX_PROTOCOL_PARAMS); + uint16_t num_loops = + std::min(p_elem.num_params, static_cast(SDP_MAX_PROTOCOL_PARAMS)); // Regardless of number set above, fill out the entire allocated array for (uint16_t i = 0; i < num_loops; i++) { p_elem.params[i] = fdp->ConsumeIntegral(); @@ -171,15 +165,14 @@ tSDP_PROTOCOL_ELEM generateArbitrarySdpProtocolElements( } std::shared_ptr generateArbitrarySdpProtocolElementList( - FuzzedDataProvider* fdp) { + FuzzedDataProvider* fdp) { std::shared_ptr p_elem_list(new tSDP_PROTO_LIST_ELEM); sdp_protolist_elem_vect.push_back(p_elem_list); // Populate our element list - p_elem_list->num_elems = - fdp->ConsumeIntegralInRange(0, SDP_MAX_LIST_ELEMS); - uint16_t num_loops = std::min( - p_elem_list->num_elems, static_cast(SDP_MAX_LIST_ELEMS)); + p_elem_list->num_elems = fdp->ConsumeIntegralInRange(0, SDP_MAX_LIST_ELEMS); + uint16_t num_loops = + std::min(p_elem_list->num_elems, static_cast(SDP_MAX_LIST_ELEMS)); for (uint16_t i = 0; i < num_loops; i++) { p_elem_list->list_elem[i] = generateArbitrarySdpProtocolElements(fdp); } @@ -187,14 +180,14 @@ std::shared_ptr generateArbitrarySdpProtocolElementList( return p_elem_list; } -tSDP_PROTO_LIST_ELEM** generateArbitrarySdpProtocolElementListArray( - FuzzedDataProvider* fdp, uint16_t* array_size) { +tSDP_PROTO_LIST_ELEM** generateArbitrarySdpProtocolElementListArray(FuzzedDataProvider* fdp, + uint16_t* array_size) { *array_size = fdp->ConsumeIntegralInRange(0, SDP_MAX_ATTR_LEN); if (*array_size == 0) { return nullptr; } - tSDP_PROTO_LIST_ELEM** p_list_array = static_cast( - calloc(*array_size, sizeof(tSDP_PROTO_LIST_ELEM*))); + tSDP_PROTO_LIST_ELEM** p_list_array = + static_cast(calloc(*array_size, sizeof(tSDP_PROTO_LIST_ELEM*))); if (p_list_array == nullptr) { return nullptr; } @@ -215,18 +208,15 @@ tSDP_DI_RECORD generateArbitrarySdpDiRecord(FuzzedDataProvider* fdp) { record.product = fdp->ConsumeIntegral(); record.version = fdp->ConsumeIntegral(); record.primary_record = fdp->ConsumeBool(); - size_t num_executable_urls = - fdp->ConsumeIntegralInRange(0, SDP_MAX_ATTR_LEN); + size_t num_executable_urls = fdp->ConsumeIntegralInRange(0, SDP_MAX_ATTR_LEN); for (size_t i = 0; i < num_executable_urls; i++) { record.client_executable_url[i] = fdp->ConsumeIntegral(); } - size_t num_descriptions = - fdp->ConsumeIntegralInRange(0, SDP_MAX_ATTR_LEN); + size_t num_descriptions = fdp->ConsumeIntegralInRange(0, SDP_MAX_ATTR_LEN); for (size_t i = 0; i < num_descriptions; i++) { record.service_description[i] = fdp->ConsumeIntegral(); } - size_t num_documentation_urls = - fdp->ConsumeIntegralInRange(0, SDP_MAX_ATTR_LEN); + size_t num_documentation_urls = fdp->ConsumeIntegralInRange(0, SDP_MAX_ATTR_LEN); for (size_t i = 0; i < num_documentation_urls; i++) { record.documentation_url[i] = fdp->ConsumeIntegral(); } @@ -260,7 +250,7 @@ SDP_Sequence_Helper generateArbitrarySdpElemSequence(FuzzedDataProvider* fdp) { // Link the size to the size of the buffer we're creating (ret.len.get())[i] = buf_size; std::shared_ptr p_val_sp( - reinterpret_cast(calloc(buf_size, sizeof(uint8_t))), free); + reinterpret_cast(calloc(buf_size, sizeof(uint8_t))), free); ret.p_val_buffers.push_back(p_val_sp); (ret.p_val.get())[i] = p_val_sp.get(); std::vector bytes = fdp->ConsumeBytes(buf_size); @@ -276,7 +266,6 @@ SDP_Sequence_Helper generateArbitrarySdpElemSequence(FuzzedDataProvider* fdp) { // Define our callback functions we'll be using within our functions void sdp_disc_cmpl_cb(const RawAddress& bd_addr, tSDP_STATUS result) {} -void sdp_disc_cmpl_cb2(std::vector data, const RawAddress& bd_addr, - tSDP_STATUS result) {} +void sdp_disc_cmpl_cb2(std::vector data, const RawAddress& bd_addr, tSDP_STATUS result) {} #endif // FUZZER_SDP_HELPERS_H_ diff --git a/system/stack/test/gatt/gatt_api_test.cc b/system/stack/test/gatt/gatt_api_test.cc index 3be6b49ea60..a30f7df8e8f 100644 --- a/system/stack/test/gatt/gatt_api_test.cc +++ b/system/stack/test/gatt/gatt_api_test.cc @@ -27,19 +27,16 @@ extern tBTM_SEC_CB btm_sec_cb; static const size_t QUEUE_SIZE_MAX = 10; -static tBTM_SEC_DEV_REC* make_bonded_ble_device(const RawAddress& bda, - const RawAddress& rra) { +static tBTM_SEC_DEV_REC* make_bonded_ble_device(const RawAddress& bda, const RawAddress& rra) { tBTM_SEC_DEV_REC* dev = btm_sec_allocate_dev_rec(); dev->sec_rec.sec_flags |= BTM_SEC_LE_LINK_KEY_KNOWN; dev->bd_addr = bda; dev->ble.pseudo_addr = rra; - dev->sec_rec.ble_keys.key_type = - BTM_LE_KEY_PID | BTM_LE_KEY_PENC | BTM_LE_KEY_LENC; + dev->sec_rec.ble_keys.key_type = BTM_LE_KEY_PID | BTM_LE_KEY_PENC | BTM_LE_KEY_LENC; return dev; } -static tBTM_SEC_DEV_REC* make_bonded_dual_device(const RawAddress& bda, - const RawAddress& rra) { +static tBTM_SEC_DEV_REC* make_bonded_dual_device(const RawAddress& bda, const RawAddress& rra) { tBTM_SEC_DEV_REC* dev = make_bonded_ble_device(bda, rra); dev->sec_rec.sec_flags |= BTM_SEC_LINK_KEY_KNOWN; return dev; @@ -48,7 +45,7 @@ static tBTM_SEC_DEV_REC* make_bonded_dual_device(const RawAddress& bda, extern std::optional OVERRIDE_GATT_LOAD_BONDED; class GattApiTest : public ::testing::Test { - protected: +protected: GattApiTest() = default; virtual ~GattApiTest() = default; @@ -62,8 +59,7 @@ class GattApiTest : public ::testing::Test { void TearDown() override { list_free(btm_sec_cb.sec_dev_rec); } }; -static const RawAddress SAMPLE_PUBLIC_BDA = { - {0x00, 0x00, 0x11, 0x22, 0x33, 0x44}}; +static const RawAddress SAMPLE_PUBLIC_BDA = {{0x00, 0x00, 0x11, 0x22, 0x33, 0x44}}; static const RawAddress SAMPLE_RRA_BDA = {{0xAA, 0xAA, 0x11, 0x22, 0x33, 0x44}}; diff --git a/system/stack/test/gatt/gatt_sr_test.cc b/system/stack/test/gatt/gatt_sr_test.cc index 5ec359780fd..110c1291c66 100644 --- a/system/stack/test/gatt/gatt_sr_test.cc +++ b/system/stack/test/gatt/gatt_sr_test.cc @@ -51,11 +51,8 @@ TestMutables test_state_; } // namespace namespace connection_manager { -bool background_connect_remove(uint8_t app_id, const RawAddress& address) { - return false; -} -bool direct_connect_remove(uint8_t app_id, const RawAddress& address, - bool connection_timeout) { +bool background_connect_remove(uint8_t app_id, const RawAddress& address) { return false; } +bool direct_connect_remove(uint8_t app_id, const RawAddress& address, bool connection_timeout) { return false; } bool is_background_connection(const RawAddress& address) { return false; } @@ -67,64 +64,55 @@ BT_HDR* attp_build_sr_msg(tGATT_TCB& tcb, uint8_t op_code, tGATT_SR_MSG* p_msg, test_state_.attp_build_sr_msg.op_code_ = op_code; return nullptr; } -tGATT_STATUS attp_send_cl_confirmation_msg(tGATT_TCB& tcb, uint16_t cid) { - return GATT_SUCCESS; -} -tGATT_STATUS attp_send_cl_msg(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, - uint8_t op_code, tGATT_CL_MSG* p_msg) { - return GATT_SUCCESS; -} -tGATT_STATUS attp_send_sr_msg(tGATT_TCB& tcb, uint16_t cid, BT_HDR* p_msg) { +tGATT_STATUS attp_send_cl_confirmation_msg(tGATT_TCB& tcb, uint16_t cid) { return GATT_SUCCESS; } +tGATT_STATUS attp_send_cl_msg(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, uint8_t op_code, + tGATT_CL_MSG* p_msg) { return GATT_SUCCESS; } +tGATT_STATUS attp_send_sr_msg(tGATT_TCB& tcb, uint16_t cid, BT_HDR* p_msg) { return GATT_SUCCESS; } void gatt_act_discovery(tGATT_CLCB* p_clcb) {} bool gatt_disconnect(tGATT_TCB* p_tcb) { return false; } tGATT_CH_STATE gatt_get_ch_state(tGATT_TCB* p_tcb) { return GATT_CH_CLOSE; } -tGATT_STATUS gatts_db_read_attr_value_by_type( - tGATT_TCB& tcb, uint16_t cid, tGATT_SVC_DB* p_db, uint8_t op_code, - BT_HDR* p_rsp, uint16_t s_handle, uint16_t e_handle, const Uuid& type, - uint16_t* p_len, tGATT_SEC_FLAG sec_flag, uint8_t key_size, - uint32_t trans_id, uint16_t* p_cur_handle) { +tGATT_STATUS gatts_db_read_attr_value_by_type(tGATT_TCB& tcb, uint16_t cid, tGATT_SVC_DB* p_db, + uint8_t op_code, BT_HDR* p_rsp, uint16_t s_handle, + uint16_t e_handle, const Uuid& type, uint16_t* p_len, + tGATT_SEC_FLAG sec_flag, uint8_t key_size, + uint32_t trans_id, uint16_t* p_cur_handle) { return GATT_SUCCESS; } void gatt_set_ch_state(tGATT_TCB* p_tcb, tGATT_CH_STATE ch_state) {} Uuid* gatts_get_service_uuid(tGATT_SVC_DB* p_db) { return nullptr; } -tGATT_STATUS GATTS_HandleValueIndication(uint16_t conn_id, uint16_t attr_handle, - uint16_t val_len, uint8_t* p_val) { +tGATT_STATUS GATTS_HandleValueIndication(uint16_t conn_id, uint16_t attr_handle, uint16_t val_len, + uint8_t* p_val) { return GATT_SUCCESS; } -tGATT_STATUS gatts_read_attr_perm_check(tGATT_SVC_DB* p_db, bool is_long, - uint16_t handle, - tGATT_SEC_FLAG sec_flag, - uint8_t key_size) { +tGATT_STATUS gatts_read_attr_perm_check(tGATT_SVC_DB* p_db, bool is_long, uint16_t handle, + tGATT_SEC_FLAG sec_flag, uint8_t key_size) { return GATT_SUCCESS; } -tGATT_STATUS gatts_read_attr_value_by_handle( - tGATT_TCB& tcb, uint16_t cid, tGATT_SVC_DB* p_db, uint8_t op_code, - uint16_t handle, uint16_t offset, uint8_t* p_value, uint16_t* p_len, - uint16_t mtu, tGATT_SEC_FLAG sec_flag, uint8_t key_size, - uint32_t trans_id) { +tGATT_STATUS gatts_read_attr_value_by_handle(tGATT_TCB& tcb, uint16_t cid, tGATT_SVC_DB* p_db, + uint8_t op_code, uint16_t handle, uint16_t offset, + uint8_t* p_value, uint16_t* p_len, uint16_t mtu, + tGATT_SEC_FLAG sec_flag, uint8_t key_size, + uint32_t trans_id) { return GATT_SUCCESS; } -tGATT_STATUS gatts_write_attr_perm_check(tGATT_SVC_DB* p_db, uint8_t op_code, - uint16_t handle, uint16_t offset, - uint8_t* p_data, uint16_t len, - tGATT_SEC_FLAG sec_flag, - uint8_t key_size) { +tGATT_STATUS gatts_write_attr_perm_check(tGATT_SVC_DB* p_db, uint8_t op_code, uint16_t handle, + uint16_t offset, uint8_t* p_data, uint16_t len, + tGATT_SEC_FLAG sec_flag, uint8_t key_size) { test_state_.gatts_write_attr_perm_check.access_count_++; return test_state_.gatts_write_attr_perm_check.return_status_; } -void gatt_update_app_use_link_flag(tGATT_IF gatt_if, tGATT_TCB* p_tcb, - bool is_add, bool check_acl_link) {} +void gatt_update_app_use_link_flag(tGATT_IF gatt_if, tGATT_TCB* p_tcb, bool is_add, + bool check_acl_link) {} bluetooth::common::MessageLoopThread* get_main_thread() { return nullptr; } -void l2cble_set_fixed_channel_tx_data_length(const RawAddress& remote_bda, - uint16_t fix_cid, +void l2cble_set_fixed_channel_tx_data_length(const RawAddress& remote_bda, uint16_t fix_cid, uint16_t tx_mtu) {} -void L2CA_SetLeFixedChannelTxDataLength(const RawAddress& remote_bda, - uint16_t fix_cid, uint16_t tx_mtu) {} -void ApplicationRequestCallback(uint16_t conn_id, uint32_t trans_id, - tGATTS_REQ_TYPE type, tGATTS_DATA* p_data) { +void L2CA_SetLeFixedChannelTxDataLength(const RawAddress& remote_bda, uint16_t fix_cid, + uint16_t tx_mtu) {} +void ApplicationRequestCallback(uint16_t conn_id, uint32_t trans_id, tGATTS_REQ_TYPE type, + tGATTS_DATA* p_data) { test_state_.application_request_callback.conn_id_ = conn_id; test_state_.application_request_callback.trans_id_ = trans_id; test_state_.application_request_callback.type_ = type; @@ -145,7 +133,7 @@ uint16_t kHandle = 1; bt_gatt_db_attribute_type_t kGattCharacteristicType = BTGATT_DB_CHARACTERISTIC; } // namespace class GattSrTest : public ::testing::Test { - protected: +protected: void SetUp() override { memset(&tcb_, 0, sizeof(tcb_)); memset(&el_, 0, sizeof(el_)); @@ -154,8 +142,7 @@ class GattSrTest : public ::testing::Test { tcb_.att_lcid = L2CAP_ATT_CID; el_.gatt_if = 1; gatt_cb.cl_rcb[el_.gatt_if - 1].in_use = true; - gatt_cb.cl_rcb[el_.gatt_if - 1].app_cb.p_req_cb = - ApplicationRequestCallback; + gatt_cb.cl_rcb[el_.gatt_if - 1].app_cb.p_req_cb = ApplicationRequestCallback; test_state_ = TestMutables(); } @@ -166,7 +153,7 @@ class GattSrTest : public ::testing::Test { /* Server Robust Caching Test */ class GattSrRobustCachingTest : public ::testing::Test { - protected: +protected: void SetUp() override { memset(&tcb_, 0, sizeof(tcb_)); @@ -182,138 +169,116 @@ class GattSrRobustCachingTest : public ::testing::Test { }; TEST_F(GattSrTest, gatts_process_write_req_request_prepare_write_no_data) { - gatts_process_write_req(tcb_, L2CAP_ATT_CID, el_, kHandle, - GATT_REQ_PREPARE_WRITE, 0, nullptr, + gatts_process_write_req(tcb_, L2CAP_ATT_CID, el_, kHandle, GATT_REQ_PREPARE_WRITE, 0, nullptr, kGattCharacteristicType); } -TEST_F(GattSrTest, - gatts_process_write_req_request_prepare_write_max_len_no_data) { - gatts_process_write_req(tcb_, L2CAP_ATT_CID, el_, kHandle, - GATT_REQ_PREPARE_WRITE, MAX_UINT16, nullptr, - kGattCharacteristicType); +TEST_F(GattSrTest, gatts_process_write_req_request_prepare_write_max_len_no_data) { + gatts_process_write_req(tcb_, L2CAP_ATT_CID, el_, kHandle, GATT_REQ_PREPARE_WRITE, MAX_UINT16, + nullptr, kGattCharacteristicType); } -TEST_F(GattSrTest, - gatts_process_write_req_request_prepare_write_zero_len_max_data) { +TEST_F(GattSrTest, gatts_process_write_req_request_prepare_write_zero_len_max_data) { uint8_t max_mem[MAX_UINT16]; - gatts_process_write_req(tcb_, L2CAP_ATT_CID, el_, kHandle, - GATT_REQ_PREPARE_WRITE, 0, max_mem, + gatts_process_write_req(tcb_, L2CAP_ATT_CID, el_, kHandle, GATT_REQ_PREPARE_WRITE, 0, max_mem, kGattCharacteristicType); } TEST_F(GattSrTest, gatts_process_write_req_request_prepare_write_typical) { uint8_t p_data[2] = {0x34, 0x12}; uint16_t length = static_cast(sizeof(p_data) / sizeof(p_data[0])); - gatts_process_write_req(tcb_, L2CAP_ATT_CID, el_, kHandle, - GATT_REQ_PREPARE_WRITE, length, p_data, + gatts_process_write_req(tcb_, L2CAP_ATT_CID, el_, kHandle, GATT_REQ_PREPARE_WRITE, length, p_data, kGattCharacteristicType); ASSERT_EQ(test_state_.gatts_write_attr_perm_check.access_count_, 1); ASSERT_EQ(test_state_.application_request_callback.conn_id_, el_.gatt_if); ASSERT_EQ(test_state_.application_request_callback.trans_id_, 0x12345678u); - ASSERT_EQ(test_state_.application_request_callback.type_, - GATTS_REQ_TYPE_WRITE_CHARACTERISTIC); - ASSERT_EQ(test_state_.application_request_callback.data_.write_req.offset, - 0x1234); + ASSERT_EQ(test_state_.application_request_callback.type_, GATTS_REQ_TYPE_WRITE_CHARACTERISTIC); + ASSERT_EQ(test_state_.application_request_callback.data_.write_req.offset, 0x1234); ASSERT_TRUE(test_state_.application_request_callback.data_.write_req.is_prep); ASSERT_EQ(test_state_.application_request_callback.data_.write_req.len, 0); } TEST_F(GattSrTest, gatts_process_write_req_signed_command_write_no_data) { - gatts_process_write_req(tcb_, L2CAP_ATT_CID, el_, kHandle, - GATT_SIGN_CMD_WRITE, 0, nullptr, + gatts_process_write_req(tcb_, L2CAP_ATT_CID, el_, kHandle, GATT_SIGN_CMD_WRITE, 0, nullptr, kGattCharacteristicType); } -TEST_F(GattSrTest, - gatts_process_write_req_signed_command_write_max_len_no_data) { - gatts_process_write_req(tcb_, L2CAP_ATT_CID, el_, kHandle, - GATT_SIGN_CMD_WRITE, MAX_UINT16, nullptr, - kGattCharacteristicType); +TEST_F(GattSrTest, gatts_process_write_req_signed_command_write_max_len_no_data) { + gatts_process_write_req(tcb_, L2CAP_ATT_CID, el_, kHandle, GATT_SIGN_CMD_WRITE, MAX_UINT16, + nullptr, kGattCharacteristicType); } -TEST_F(GattSrTest, - gatts_process_write_req_signed_command_write_zero_len_max_data) { +TEST_F(GattSrTest, gatts_process_write_req_signed_command_write_zero_len_max_data) { uint8_t max_mem[MAX_UINT16]; - gatts_process_write_req(tcb_, L2CAP_ATT_CID, el_, kHandle, - GATT_SIGN_CMD_WRITE, 0, max_mem, + gatts_process_write_req(tcb_, L2CAP_ATT_CID, el_, kHandle, GATT_SIGN_CMD_WRITE, 0, max_mem, kGattCharacteristicType); } TEST_F(GattSrTest, gatts_process_write_req_signed_command_write_typical) { static constexpr size_t kDataLength = 4; - uint8_t p_data[GATT_AUTH_SIGN_LEN + kDataLength] = { - 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, - 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x01}; + uint8_t p_data[GATT_AUTH_SIGN_LEN + kDataLength] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, + 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, + 0xdd, 0xee, 0xff, 0x01}; uint16_t length = static_cast(sizeof(p_data) / sizeof(p_data[0])); - gatts_process_write_req(tcb_, L2CAP_ATT_CID, el_, kHandle, - GATT_SIGN_CMD_WRITE, length, p_data, + gatts_process_write_req(tcb_, L2CAP_ATT_CID, el_, kHandle, GATT_SIGN_CMD_WRITE, length, p_data, kGattCharacteristicType); ASSERT_EQ(test_state_.gatts_write_attr_perm_check.access_count_, 1); ASSERT_EQ(test_state_.application_request_callback.conn_id_, el_.gatt_if); ASSERT_EQ(test_state_.application_request_callback.trans_id_, 0x12345678u); - ASSERT_EQ(test_state_.application_request_callback.type_, - GATTS_REQ_TYPE_WRITE_CHARACTERISTIC); - ASSERT_EQ(test_state_.application_request_callback.data_.write_req.offset, - 0x0); - ASSERT_FALSE( - test_state_.application_request_callback.data_.write_req.is_prep); - ASSERT_EQ(test_state_.application_request_callback.data_.write_req.len, - kDataLength); + ASSERT_EQ(test_state_.application_request_callback.type_, GATTS_REQ_TYPE_WRITE_CHARACTERISTIC); + ASSERT_EQ(test_state_.application_request_callback.data_.write_req.offset, 0x0); + ASSERT_FALSE(test_state_.application_request_callback.data_.write_req.is_prep); + ASSERT_EQ(test_state_.application_request_callback.data_.write_req.len, kDataLength); } TEST_F(GattSrTest, gatts_process_write_req_command_write_no_data) { - gatts_process_write_req(tcb_, L2CAP_ATT_CID, el_, kHandle, GATT_CMD_WRITE, 0, - nullptr, kGattCharacteristicType); + gatts_process_write_req(tcb_, L2CAP_ATT_CID, el_, kHandle, GATT_CMD_WRITE, 0, nullptr, + kGattCharacteristicType); } TEST_F(GattSrTest, gatts_process_write_req_command_write_max_len_no_data) { - gatts_process_write_req(tcb_, L2CAP_ATT_CID, el_, kHandle, GATT_CMD_WRITE, - MAX_UINT16, nullptr, kGattCharacteristicType); + gatts_process_write_req(tcb_, L2CAP_ATT_CID, el_, kHandle, GATT_CMD_WRITE, MAX_UINT16, nullptr, + kGattCharacteristicType); } TEST_F(GattSrTest, gatts_process_write_req_command_write_zero_len_max_data) { uint8_t max_mem[MAX_UINT16]; - gatts_process_write_req(tcb_, L2CAP_ATT_CID, el_, kHandle, GATT_CMD_WRITE, 0, - max_mem, kGattCharacteristicType); + gatts_process_write_req(tcb_, L2CAP_ATT_CID, el_, kHandle, GATT_CMD_WRITE, 0, max_mem, + kGattCharacteristicType); } TEST_F(GattSrTest, gatts_process_write_req_command_write_typical) { uint8_t p_data[16] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x01}; uint16_t length = static_cast(sizeof(p_data) / sizeof(p_data[0])); - gatts_process_write_req(tcb_, L2CAP_ATT_CID, el_, kHandle, GATT_CMD_WRITE, - length, p_data, kGattCharacteristicType); + gatts_process_write_req(tcb_, L2CAP_ATT_CID, el_, kHandle, GATT_CMD_WRITE, length, p_data, + kGattCharacteristicType); ASSERT_EQ(test_state_.gatts_write_attr_perm_check.access_count_, 1); ASSERT_EQ(test_state_.application_request_callback.conn_id_, el_.gatt_if); ASSERT_EQ(test_state_.application_request_callback.trans_id_, 0x12345678u); - ASSERT_EQ(test_state_.application_request_callback.type_, - GATTS_REQ_TYPE_WRITE_CHARACTERISTIC); - ASSERT_EQ(test_state_.application_request_callback.data_.write_req.offset, - 0x0); - ASSERT_FALSE( - test_state_.application_request_callback.data_.write_req.is_prep); - ASSERT_EQ(test_state_.application_request_callback.data_.write_req.len, - length); + ASSERT_EQ(test_state_.application_request_callback.type_, GATTS_REQ_TYPE_WRITE_CHARACTERISTIC); + ASSERT_EQ(test_state_.application_request_callback.data_.write_req.offset, 0x0); + ASSERT_FALSE(test_state_.application_request_callback.data_.write_req.is_prep); + ASSERT_EQ(test_state_.application_request_callback.data_.write_req.len, length); } TEST_F(GattSrTest, gatts_process_write_req_request_write_no_data) { - gatts_process_write_req(tcb_, L2CAP_ATT_CID, el_, kHandle, GATT_REQ_WRITE, 0, - nullptr, kGattCharacteristicType); + gatts_process_write_req(tcb_, L2CAP_ATT_CID, el_, kHandle, GATT_REQ_WRITE, 0, nullptr, + kGattCharacteristicType); } TEST_F(GattSrTest, gatts_process_write_req_request_write_max_len_no_data) { - gatts_process_write_req(tcb_, L2CAP_ATT_CID, el_, kHandle, GATT_REQ_WRITE, - MAX_UINT16, nullptr, kGattCharacteristicType); + gatts_process_write_req(tcb_, L2CAP_ATT_CID, el_, kHandle, GATT_REQ_WRITE, MAX_UINT16, nullptr, + kGattCharacteristicType); } TEST_F(GattSrTest, gatts_process_write_req_request_write_zero_len_max_data) { uint8_t max_mem[MAX_UINT16]; - gatts_process_write_req(tcb_, L2CAP_ATT_CID, el_, kHandle, GATT_REQ_WRITE, 0, - max_mem, kGattCharacteristicType); + gatts_process_write_req(tcb_, L2CAP_ATT_CID, el_, kHandle, GATT_REQ_WRITE, 0, max_mem, + kGattCharacteristicType); } TEST_F(GattSrTest, gatts_process_write_req_request_write_typical) { @@ -321,52 +286,43 @@ TEST_F(GattSrTest, gatts_process_write_req_request_write_typical) { 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x01}; uint16_t length = static_cast(sizeof(p_data) / sizeof(p_data[0])); - gatts_process_write_req(tcb_, L2CAP_ATT_CID, el_, kHandle, GATT_REQ_WRITE, - length, p_data, kGattCharacteristicType); + gatts_process_write_req(tcb_, L2CAP_ATT_CID, el_, kHandle, GATT_REQ_WRITE, length, p_data, + kGattCharacteristicType); ASSERT_EQ(test_state_.gatts_write_attr_perm_check.access_count_, 1); ASSERT_EQ(test_state_.application_request_callback.conn_id_, el_.gatt_if); ASSERT_EQ(test_state_.application_request_callback.trans_id_, 0x12345678u); - ASSERT_EQ(test_state_.application_request_callback.type_, - GATTS_REQ_TYPE_WRITE_CHARACTERISTIC); - ASSERT_EQ(test_state_.application_request_callback.data_.write_req.offset, - 0x0); - ASSERT_FALSE( - test_state_.application_request_callback.data_.write_req.is_prep); - ASSERT_EQ(test_state_.application_request_callback.data_.write_req.len, - length); + ASSERT_EQ(test_state_.application_request_callback.type_, GATTS_REQ_TYPE_WRITE_CHARACTERISTIC); + ASSERT_EQ(test_state_.application_request_callback.data_.write_req.offset, 0x0); + ASSERT_FALSE(test_state_.application_request_callback.data_.write_req.is_prep); + ASSERT_EQ(test_state_.application_request_callback.data_.write_req.len, length); } -TEST_F(GattSrRobustCachingTest, - gatts_process_db_out_of_sync_for_gatt_req_read_by_grp_type) { +TEST_F(GattSrRobustCachingTest, gatts_process_db_out_of_sync_for_gatt_req_read_by_grp_type) { tcb_.is_robust_cache_change_aware = false; - bool should_ignore = gatts_process_db_out_of_sync( - tcb_, L2CAP_ATT_CID, GATT_REQ_READ_BY_GRP_TYPE, default_length_, - default_data_); + bool should_ignore = gatts_process_db_out_of_sync(tcb_, L2CAP_ATT_CID, GATT_REQ_READ_BY_GRP_TYPE, + default_length_, default_data_); ASSERT_TRUE(should_ignore); ASSERT_TRUE(tcb_.is_robust_cache_change_aware); } -TEST_F(GattSrRobustCachingTest, - gatts_process_db_out_of_sync_for_gatt_req_find_type_value) { +TEST_F(GattSrRobustCachingTest, gatts_process_db_out_of_sync_for_gatt_req_find_type_value) { tcb_.is_robust_cache_change_aware = false; - bool should_ignore = gatts_process_db_out_of_sync( - tcb_, L2CAP_ATT_CID, GATT_REQ_FIND_TYPE_VALUE, default_length_, - default_data_); + bool should_ignore = gatts_process_db_out_of_sync(tcb_, L2CAP_ATT_CID, GATT_REQ_FIND_TYPE_VALUE, + default_length_, default_data_); ASSERT_TRUE(should_ignore); ASSERT_TRUE(tcb_.is_robust_cache_change_aware); } -TEST_F(GattSrRobustCachingTest, - gatts_process_db_out_of_sync_for_gatt_req_find_info) { +TEST_F(GattSrRobustCachingTest, gatts_process_db_out_of_sync_for_gatt_req_find_info) { tcb_.is_robust_cache_change_aware = false; - bool should_ignore = gatts_process_db_out_of_sync( - tcb_, L2CAP_ATT_CID, GATT_REQ_FIND_INFO, default_length_, default_data_); + bool should_ignore = gatts_process_db_out_of_sync(tcb_, L2CAP_ATT_CID, GATT_REQ_FIND_INFO, + default_length_, default_data_); ASSERT_TRUE(should_ignore); ASSERT_TRUE(tcb_.is_robust_cache_change_aware); @@ -379,8 +335,8 @@ TEST_F(GattSrRobustCachingTest, uint8_t p_data[4] = {0x00, 0x02, 0x14, 0x02}; tcb_.is_robust_cache_change_aware = false; - bool should_ignore = gatts_process_db_out_of_sync( - tcb_, L2CAP_ATT_CID, GATT_REQ_READ_BY_TYPE, len, p_data); + bool should_ignore = + gatts_process_db_out_of_sync(tcb_, L2CAP_ATT_CID, GATT_REQ_READ_BY_TYPE, len, p_data); ASSERT_TRUE(should_ignore); ASSERT_TRUE(tcb_.is_robust_cache_change_aware); @@ -393,8 +349,8 @@ TEST_F(GattSrRobustCachingTest, uint8_t p_data[6] = {0x01, 0x00, 0x10, 0x00, 0x2A, 0x2B}; tcb_.is_robust_cache_change_aware = false; - bool should_ignore = gatts_process_db_out_of_sync( - tcb_, L2CAP_ATT_CID, GATT_REQ_READ_BY_TYPE, len, p_data); + bool should_ignore = + gatts_process_db_out_of_sync(tcb_, L2CAP_ATT_CID, GATT_REQ_READ_BY_TYPE, len, p_data); ASSERT_FALSE(should_ignore); } @@ -406,130 +362,119 @@ TEST_F(GattSrRobustCachingTest, uint8_t p_data[6] = {0x00, 0x02, 0x14, 0x02, 0x2A, 0x28}; tcb_.is_robust_cache_change_aware = false; - bool should_ignore = gatts_process_db_out_of_sync( - tcb_, L2CAP_ATT_CID, GATT_REQ_READ_BY_TYPE, len, p_data); + bool should_ignore = + gatts_process_db_out_of_sync(tcb_, L2CAP_ATT_CID, GATT_REQ_READ_BY_TYPE, len, p_data); ASSERT_TRUE(should_ignore); ASSERT_TRUE(tcb_.is_robust_cache_change_aware); } -TEST_F(GattSrRobustCachingTest, - gatts_process_db_out_of_sync_for_gatt_req_read_by_type_other_uuid) { +TEST_F(GattSrRobustCachingTest, gatts_process_db_out_of_sync_for_gatt_req_read_by_type_other_uuid) { // ATT_READ_BY_TYPE_REQ(0x0200, 0x0214, 0x2803) uint16_t len = 6; uint8_t p_data[6] = {0x00, 0x02, 0x14, 0x02, 0x03, 0x28}; tcb_.is_robust_cache_change_aware = false; - bool should_ignore = gatts_process_db_out_of_sync( - tcb_, L2CAP_ATT_CID, GATT_REQ_READ_BY_TYPE, len, p_data); + bool should_ignore = + gatts_process_db_out_of_sync(tcb_, L2CAP_ATT_CID, GATT_REQ_READ_BY_TYPE, len, p_data); ASSERT_TRUE(should_ignore); ASSERT_TRUE(tcb_.is_robust_cache_change_aware); } -TEST_F(GattSrRobustCachingTest, - gatts_process_db_out_of_sync_for_gatt_req_read_parse_failed) { +TEST_F(GattSrRobustCachingTest, gatts_process_db_out_of_sync_for_gatt_req_read_parse_failed) { // INVALID_PDU uint8_t p_data[1] = {0x02}; uint16_t len = 1; tcb_.is_robust_cache_change_aware = false; - bool should_ignore = gatts_process_db_out_of_sync(tcb_, L2CAP_ATT_CID, - GATT_REQ_READ, len, p_data); + bool should_ignore = + gatts_process_db_out_of_sync(tcb_, L2CAP_ATT_CID, GATT_REQ_READ, len, p_data); ASSERT_TRUE(should_ignore); ASSERT_TRUE(tcb_.is_robust_cache_change_aware); } -TEST_F(GattSrRobustCachingTest, - gatts_process_db_out_of_sync_for_gatt_req_read_db_hash_handle) { +TEST_F(GattSrRobustCachingTest, gatts_process_db_out_of_sync_for_gatt_req_read_db_hash_handle) { // ATT_READ_REQ(0x0010) uint8_t p_data[2] = {0x10, 0x00}; uint16_t len = 2; tcb_.is_robust_cache_change_aware = false; - bool should_ignore = gatts_process_db_out_of_sync(tcb_, L2CAP_ATT_CID, - GATT_REQ_READ, len, p_data); + bool should_ignore = + gatts_process_db_out_of_sync(tcb_, L2CAP_ATT_CID, GATT_REQ_READ, len, p_data); ASSERT_FALSE(should_ignore); } -TEST_F(GattSrRobustCachingTest, - gatts_process_db_out_of_sync_for_gatt_req_read_other_handle) { +TEST_F(GattSrRobustCachingTest, gatts_process_db_out_of_sync_for_gatt_req_read_other_handle) { // ATT_READ_REQ(0x0002) uint8_t p_data[2] = {0x02, 0x00}; uint16_t len = 2; tcb_.is_robust_cache_change_aware = false; - bool should_ignore = gatts_process_db_out_of_sync(tcb_, L2CAP_ATT_CID, - GATT_REQ_READ, len, p_data); + bool should_ignore = + gatts_process_db_out_of_sync(tcb_, L2CAP_ATT_CID, GATT_REQ_READ, len, p_data); ASSERT_TRUE(should_ignore); ASSERT_TRUE(tcb_.is_robust_cache_change_aware); } -TEST_F(GattSrRobustCachingTest, - gatts_process_db_out_of_sync_for_gatt_req_read_blob) { +TEST_F(GattSrRobustCachingTest, gatts_process_db_out_of_sync_for_gatt_req_read_blob) { tcb_.is_robust_cache_change_aware = false; - bool should_ignore = gatts_process_db_out_of_sync( - tcb_, L2CAP_ATT_CID, GATT_REQ_READ_BLOB, default_length_, default_data_); + bool should_ignore = gatts_process_db_out_of_sync(tcb_, L2CAP_ATT_CID, GATT_REQ_READ_BLOB, + default_length_, default_data_); ASSERT_TRUE(should_ignore); ASSERT_TRUE(tcb_.is_robust_cache_change_aware); } -TEST_F(GattSrRobustCachingTest, - gatts_process_db_out_of_sync_for_gatt_req_read_multi) { +TEST_F(GattSrRobustCachingTest, gatts_process_db_out_of_sync_for_gatt_req_read_multi) { tcb_.is_robust_cache_change_aware = false; - bool should_ignore = gatts_process_db_out_of_sync( - tcb_, L2CAP_ATT_CID, GATT_REQ_READ_MULTI, default_length_, default_data_); + bool should_ignore = gatts_process_db_out_of_sync(tcb_, L2CAP_ATT_CID, GATT_REQ_READ_MULTI, + default_length_, default_data_); ASSERT_TRUE(should_ignore); ASSERT_TRUE(tcb_.is_robust_cache_change_aware); } -TEST_F(GattSrRobustCachingTest, - gatts_process_db_out_of_sync_for_gatt_req_write) { +TEST_F(GattSrRobustCachingTest, gatts_process_db_out_of_sync_for_gatt_req_write) { tcb_.is_robust_cache_change_aware = false; - bool should_ignore = gatts_process_db_out_of_sync( - tcb_, L2CAP_ATT_CID, GATT_REQ_WRITE, default_length_, default_data_); + bool should_ignore = gatts_process_db_out_of_sync(tcb_, L2CAP_ATT_CID, GATT_REQ_WRITE, + default_length_, default_data_); ASSERT_TRUE(should_ignore); ASSERT_TRUE(tcb_.is_robust_cache_change_aware); } -TEST_F(GattSrRobustCachingTest, - gatts_process_db_out_of_sync_for_gatt_cmd_write) { +TEST_F(GattSrRobustCachingTest, gatts_process_db_out_of_sync_for_gatt_cmd_write) { tcb_.is_robust_cache_change_aware = false; - bool should_ignore = gatts_process_db_out_of_sync( - tcb_, L2CAP_ATT_CID, GATT_CMD_WRITE, default_length_, default_data_); + bool should_ignore = gatts_process_db_out_of_sync(tcb_, L2CAP_ATT_CID, GATT_CMD_WRITE, + default_length_, default_data_); ASSERT_TRUE(should_ignore); ASSERT_FALSE(tcb_.is_robust_cache_change_aware); } -TEST_F(GattSrRobustCachingTest, - gatts_process_db_out_of_sync_for_gatt_sign_cmd_write) { +TEST_F(GattSrRobustCachingTest, gatts_process_db_out_of_sync_for_gatt_sign_cmd_write) { tcb_.is_robust_cache_change_aware = false; - bool should_ignore = gatts_process_db_out_of_sync( - tcb_, L2CAP_ATT_CID, GATT_SIGN_CMD_WRITE, default_length_, default_data_); + bool should_ignore = gatts_process_db_out_of_sync(tcb_, L2CAP_ATT_CID, GATT_SIGN_CMD_WRITE, + default_length_, default_data_); ASSERT_TRUE(should_ignore); ASSERT_FALSE(tcb_.is_robust_cache_change_aware); } -TEST_F(GattSrRobustCachingTest, - gatts_process_db_out_of_sync_for_gatt_req_prepare_write) { +TEST_F(GattSrRobustCachingTest, gatts_process_db_out_of_sync_for_gatt_req_prepare_write) { tcb_.is_robust_cache_change_aware = false; - bool should_ignore = - gatts_process_db_out_of_sync(tcb_, L2CAP_ATT_CID, GATT_REQ_PREPARE_WRITE, - default_length_, default_data_); + bool should_ignore = gatts_process_db_out_of_sync(tcb_, L2CAP_ATT_CID, GATT_REQ_PREPARE_WRITE, + default_length_, default_data_); ASSERT_TRUE(should_ignore); ASSERT_TRUE(tcb_.is_robust_cache_change_aware); @@ -538,29 +483,26 @@ TEST_F(GattSrRobustCachingTest, TEST_F(GattSrRobustCachingTest, gatts_process_db_out_of_sync_for_gatt_req_mtu) { tcb_.is_robust_cache_change_aware = false; - bool should_ignore = gatts_process_db_out_of_sync( - tcb_, L2CAP_ATT_CID, GATT_REQ_MTU, default_length_, default_data_); + bool should_ignore = gatts_process_db_out_of_sync(tcb_, L2CAP_ATT_CID, GATT_REQ_MTU, + default_length_, default_data_); ASSERT_FALSE(should_ignore); } -TEST_F(GattSrRobustCachingTest, - gatts_process_db_out_of_sync_for_gatt_req_exec_write) { +TEST_F(GattSrRobustCachingTest, gatts_process_db_out_of_sync_for_gatt_req_exec_write) { tcb_.is_robust_cache_change_aware = false; - bool should_ignore = gatts_process_db_out_of_sync( - tcb_, L2CAP_ATT_CID, GATT_REQ_EXEC_WRITE, default_length_, default_data_); + bool should_ignore = gatts_process_db_out_of_sync(tcb_, L2CAP_ATT_CID, GATT_REQ_EXEC_WRITE, + default_length_, default_data_); ASSERT_FALSE(should_ignore); } -TEST_F(GattSrRobustCachingTest, - gatts_process_db_out_of_sync_for_gatt_handle_value_conf) { +TEST_F(GattSrRobustCachingTest, gatts_process_db_out_of_sync_for_gatt_handle_value_conf) { tcb_.is_robust_cache_change_aware = false; - bool should_ignore = - gatts_process_db_out_of_sync(tcb_, L2CAP_ATT_CID, GATT_HANDLE_VALUE_CONF, - default_length_, default_data_); + bool should_ignore = gatts_process_db_out_of_sync(tcb_, L2CAP_ATT_CID, GATT_HANDLE_VALUE_CONF, + default_length_, default_data_); ASSERT_FALSE(should_ignore); } diff --git a/system/stack/test/gatt/mock_gatt_utils_ref.cc b/system/stack/test/gatt/mock_gatt_utils_ref.cc index fc600a7ec56..b4310ccac1d 100644 --- a/system/stack/test/gatt/mock_gatt_utils_ref.cc +++ b/system/stack/test/gatt/mock_gatt_utils_ref.cc @@ -20,11 +20,8 @@ /** stack/gatt/connection_manager.cc */ namespace connection_manager { -bool background_connect_remove(uint8_t app_id, const RawAddress& address) { - return false; -} -bool direct_connect_remove(uint8_t app_id, const RawAddress& address, - bool connection_timeout) { +bool background_connect_remove(uint8_t app_id, const RawAddress& address) { return false; } +bool direct_connect_remove(uint8_t app_id, const RawAddress& address, bool connection_timeout) { return false; } bool is_background_connection(const RawAddress& address) { return false; } @@ -35,16 +32,12 @@ BT_HDR* attp_build_sr_msg(tGATT_TCB& tcb, uint8_t op_code, tGATT_SR_MSG* p_msg, uint16_t payload_size) { return nullptr; } -tGATT_STATUS attp_send_cl_confirmation_msg(tGATT_TCB& tcb, uint16_t cid) { - return GATT_SUCCESS; -} -tGATT_STATUS attp_send_cl_msg(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, - uint8_t op_code, tGATT_CL_MSG* p_msg) { - return GATT_SUCCESS; -} -tGATT_STATUS attp_send_sr_msg(tGATT_TCB& tcb, uint16_t cid, BT_HDR* p_msg) { +tGATT_STATUS attp_send_cl_confirmation_msg(tGATT_TCB& tcb, uint16_t cid) { return GATT_SUCCESS; } +tGATT_STATUS attp_send_cl_msg(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, uint8_t op_code, + tGATT_CL_MSG* p_msg) { return GATT_SUCCESS; } +tGATT_STATUS attp_send_sr_msg(tGATT_TCB& tcb, uint16_t cid, BT_HDR* p_msg) { return GATT_SUCCESS; } /** stack/gatt/gatt_attr.cc */ void gatt_sr_init_cl_status(tGATT_TCB& tcb) {} @@ -53,22 +46,21 @@ void gatt_sr_init_cl_status(tGATT_TCB& tcb) {} void gatt_act_discovery(tGATT_CLCB* p_clcb) {} /** stack/gatt/gatt_main.cc */ -void gatt_update_app_use_link_flag(tGATT_IF gatt_if, tGATT_TCB* p_tcb, - bool is_add, bool check_acl_link) {} +void gatt_update_app_use_link_flag(tGATT_IF gatt_if, tGATT_TCB* p_tcb, bool is_add, + bool check_acl_link) {} void gatts_proc_srv_chg_ind_ack(tGATT_TCB) {} bool gatt_disconnect(tGATT_TCB* p_tcb) { return false; } tGATT_CH_STATE gatt_get_ch_state(tGATT_TCB* p_tcb) { return GATT_CH_CLOSE; } void gatt_set_ch_state(tGATT_TCB* p_tcb, tGATT_CH_STATE ch_state) {} /** stack/gatt/gatt_sr.cc */ -uint32_t gatt_sr_enqueue_cmd(tGATT_TCB& tcb, uint16_t cid, uint8_t op_code, - uint16_t handle) { return 0x0000; } +uint32_t gatt_sr_enqueue_cmd(tGATT_TCB& tcb, uint16_t cid, uint8_t op_code, uint16_t handle) { + return 0x0000; +} void gatt_dequeue_sr_cmd(tGATT_TCB& tcb, uint16_t cid) {} - /** stack/l2cap/l2c_ble.cc */ -void l2cble_set_fixed_channel_tx_data_length(const RawAddress& remote_bda, - uint16_t fix_cid, +void l2cble_set_fixed_channel_tx_data_length(const RawAddress& remote_bda, uint16_t fix_cid, uint16_t tx_mtu) {} -void L2CA_SetLeFixedChannelTxDataLength(const RawAddress& remote_bda, - uint16_t fix_cid, uint16_t tx_mtu) {} +void L2CA_SetLeFixedChannelTxDataLength(const RawAddress& remote_bda, uint16_t fix_cid, + uint16_t tx_mtu) {} diff --git a/system/stack/test/gatt/stack_gatt_test.cc b/system/stack/test/gatt/stack_gatt_test.cc index 0246ed61238..d0957419326 100644 --- a/system/stack/test/gatt/stack_gatt_test.cc +++ b/system/stack/test/gatt/stack_gatt_test.cc @@ -41,26 +41,21 @@ namespace bluetooth { namespace legacy { namespace testing { -BT_HDR* attp_build_value_cmd(uint16_t payload_size, uint8_t op_code, - uint16_t handle, uint16_t offset, uint16_t len, - uint8_t* p_data); +BT_HDR* attp_build_value_cmd(uint16_t payload_size, uint8_t op_code, uint16_t handle, + uint16_t offset, uint16_t len, uint8_t* p_data); } // namespace testing } // namespace legacy } // namespace bluetooth class StackGattTest : public ::testing::Test { - protected: +protected: void SetUp() override { - test::mock::stack_sdp_legacy::api_.handle.SDP_CreateRecord = - ::SDP_CreateRecord; + test::mock::stack_sdp_legacy::api_.handle.SDP_CreateRecord = ::SDP_CreateRecord; test::mock::stack_sdp_legacy::api_.handle.SDP_AddServiceClassIdList = - ::SDP_AddServiceClassIdList; - test::mock::stack_sdp_legacy::api_.handle.SDP_AddAttribute = - ::SDP_AddAttribute; - test::mock::stack_sdp_legacy::api_.handle.SDP_AddProtocolList = - ::SDP_AddProtocolList; - test::mock::stack_sdp_legacy::api_.handle.SDP_AddUuidSequence = - ::SDP_AddUuidSequence; + ::SDP_AddServiceClassIdList; + test::mock::stack_sdp_legacy::api_.handle.SDP_AddAttribute = ::SDP_AddAttribute; + test::mock::stack_sdp_legacy::api_.handle.SDP_AddProtocolList = ::SDP_AddProtocolList; + test::mock::stack_sdp_legacy::api_.handle.SDP_AddUuidSequence = ::SDP_AddUuidSequence; } void TearDown() override { test::mock::stack_sdp_legacy::api_.handle = {}; } }; @@ -69,39 +64,35 @@ namespace { // Actual size of structure without compiler padding size_t actual_sizeof_tGATT_REG() { - return sizeof(bluetooth::Uuid) + sizeof(tGATT_CBACK) + sizeof(tGATT_IF) + - sizeof(bool) + sizeof(uint8_t) + sizeof(bool); + return sizeof(bluetooth::Uuid) + sizeof(tGATT_CBACK) + sizeof(tGATT_IF) + sizeof(bool) + + sizeof(uint8_t) + sizeof(bool); } -void tGATT_DISC_RES_CB(uint16_t conn_id, tGATT_DISC_TYPE disc_type, - tGATT_DISC_RES* p_data) {} -void tGATT_DISC_CMPL_CB(uint16_t conn_id, tGATT_DISC_TYPE disc_type, - tGATT_STATUS status) {} +void tGATT_DISC_RES_CB(uint16_t conn_id, tGATT_DISC_TYPE disc_type, tGATT_DISC_RES* p_data) {} +void tGATT_DISC_CMPL_CB(uint16_t conn_id, tGATT_DISC_TYPE disc_type, tGATT_STATUS status) {} void tGATT_CMPL_CBACK(uint16_t conn_id, tGATTC_OPTYPE op, tGATT_STATUS status, tGATT_CL_COMPLETE* p_data) {} -void tGATT_CONN_CBACK(tGATT_IF gatt_if, const RawAddress& bda, uint16_t conn_id, - bool connected, tGATT_DISCONN_REASON reason, - tBT_TRANSPORT transport) {} +void tGATT_CONN_CBACK(tGATT_IF gatt_if, const RawAddress& bda, uint16_t conn_id, bool connected, + tGATT_DISCONN_REASON reason, tBT_TRANSPORT transport) {} void tGATT_REQ_CBACK(uint16_t conn_id, uint32_t trans_id, tGATTS_REQ_TYPE type, tGATTS_DATA* p_data) {} void tGATT_CONGESTION_CBACK(uint16_t conn_id, bool congested) {} void tGATT_ENC_CMPL_CB(tGATT_IF gatt_if, const RawAddress& bda) {} -void tGATT_PHY_UPDATE_CB(tGATT_IF gatt_if, uint16_t conn_id, uint8_t tx_phy, - uint8_t rx_phy, tGATT_STATUS status) {} -void tGATT_CONN_UPDATE_CB(tGATT_IF gatt_if, uint16_t conn_id, uint16_t interval, - uint16_t latency, uint16_t timeout, - tGATT_STATUS status) {} +void tGATT_PHY_UPDATE_CB(tGATT_IF gatt_if, uint16_t conn_id, uint8_t tx_phy, uint8_t rx_phy, + tGATT_STATUS status) {} +void tGATT_CONN_UPDATE_CB(tGATT_IF gatt_if, uint16_t conn_id, uint16_t interval, uint16_t latency, + uint16_t timeout, tGATT_STATUS status) {} tGATT_CBACK gatt_callbacks = { - .p_conn_cb = tGATT_CONN_CBACK, - .p_cmpl_cb = tGATT_CMPL_CBACK, - .p_disc_res_cb = tGATT_DISC_RES_CB, - .p_disc_cmpl_cb = tGATT_DISC_CMPL_CB, - .p_req_cb = tGATT_REQ_CBACK, - .p_enc_cmpl_cb = tGATT_ENC_CMPL_CB, - .p_congestion_cb = tGATT_CONGESTION_CBACK, - .p_phy_update_cb = tGATT_PHY_UPDATE_CB, - .p_conn_update_cb = tGATT_CONN_UPDATE_CB, + .p_conn_cb = tGATT_CONN_CBACK, + .p_cmpl_cb = tGATT_CMPL_CBACK, + .p_disc_res_cb = tGATT_DISC_RES_CB, + .p_disc_cmpl_cb = tGATT_DISC_CMPL_CB, + .p_req_cb = tGATT_REQ_CBACK, + .p_enc_cmpl_cb = tGATT_ENC_CMPL_CB, + .p_congestion_cb = tGATT_CONGESTION_CBACK, + .p_phy_update_cb = tGATT_PHY_UPDATE_CB, + .p_conn_update_cb = tGATT_CONN_UPDATE_CB, }; } // namespace @@ -162,7 +153,7 @@ TEST_F(StackGattTest, GATT_Register_Deregister) { std::string name = bluetooth::common::StringFormat("name%02d", i); bluetooth::Uuid uuid = bluetooth::Uuid::From128BitBE( - bluetooth::os::GenerateRandom()); + bluetooth::os::GenerateRandom()); apps[i] = GATT_Register(uuid, name, &gatt_callbacks, false); } @@ -174,87 +165,82 @@ TEST_F(StackGattTest, GATT_Register_Deregister) { } TEST_F_WITH_FLAGS(StackGattTest, gatt_status_text, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, - enumerate_gatt_errors))) { + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, enumerate_gatt_errors))) { std::vector> statuses = { - std::make_pair(GATT_SUCCESS, "GATT_SUCCESS"), // Also GATT_ENCRYPED_MITM - std::make_pair(GATT_INVALID_HANDLE, "GATT_INVALID_HANDLE"), - std::make_pair(GATT_READ_NOT_PERMIT, "GATT_READ_NOT_PERMIT"), - std::make_pair(GATT_WRITE_NOT_PERMIT, "GATT_WRITE_NOT_PERMIT"), - std::make_pair(GATT_INVALID_PDU, "GATT_INVALID_PDU"), - std::make_pair(GATT_INSUF_AUTHENTICATION, "GATT_INSUF_AUTHENTICATION"), - std::make_pair(GATT_REQ_NOT_SUPPORTED, "GATT_REQ_NOT_SUPPORTED"), - std::make_pair(GATT_INVALID_OFFSET, "GATT_INVALID_OFFSET"), - std::make_pair(GATT_INSUF_AUTHORIZATION, "GATT_INSUF_AUTHORIZATION"), - std::make_pair(GATT_PREPARE_Q_FULL, "GATT_PREPARE_Q_FULL"), - std::make_pair(GATT_NOT_FOUND, "GATT_NOT_FOUND"), - std::make_pair(GATT_NOT_LONG, "GATT_NOT_LONG"), - std::make_pair(GATT_INSUF_KEY_SIZE, "GATT_INSUF_KEY_SIZE"), - std::make_pair(GATT_INVALID_ATTR_LEN, "GATT_INVALID_ATTR_LEN"), - std::make_pair(GATT_ERR_UNLIKELY, "GATT_ERR_UNLIKELY"), - std::make_pair(GATT_INSUF_ENCRYPTION, "GATT_INSUF_ENCRYPTION"), - std::make_pair(GATT_UNSUPPORT_GRP_TYPE, "GATT_UNSUPPORT_GRP_TYPE"), - std::make_pair(GATT_INSUF_RESOURCE, "GATT_INSUF_RESOURCE"), - std::make_pair(GATT_DATABASE_OUT_OF_SYNC, "GATT_DATABASE_OUT_OF_SYNC"), - std::make_pair(GATT_VALUE_NOT_ALLOWED, "GATT_VALUE_NOT_ALLOWED"), - std::make_pair(GATT_ILLEGAL_PARAMETER, "GATT_ILLEGAL_PARAMETER"), - std::make_pair(GATT_NO_RESOURCES, "GATT_NO_RESOURCES"), - std::make_pair(GATT_INTERNAL_ERROR, "GATT_INTERNAL_ERROR"), - std::make_pair(GATT_WRONG_STATE, "GATT_WRONG_STATE"), - std::make_pair(GATT_DB_FULL, "GATT_DB_FULL"), - std::make_pair(GATT_BUSY, "GATT_BUSY"), - std::make_pair(GATT_ERROR, "GATT_ERROR"), - std::make_pair(GATT_CMD_STARTED, "GATT_CMD_STARTED"), - std::make_pair(GATT_PENDING, "GATT_PENDING"), - std::make_pair(GATT_AUTH_FAIL, "GATT_AUTH_FAIL"), - std::make_pair(GATT_INVALID_CFG, "GATT_INVALID_CFG"), - std::make_pair(GATT_SERVICE_STARTED, "GATT_SERVICE_STARTED"), - std::make_pair(GATT_ENCRYPED_NO_MITM, "GATT_ENCRYPED_NO_MITM"), - std::make_pair(GATT_NOT_ENCRYPTED, "GATT_NOT_ENCRYPTED"), - std::make_pair(GATT_CONGESTED, "GATT_CONGESTED"), - std::make_pair(GATT_DUP_REG, "GATT_DUP_REG"), - std::make_pair(GATT_ALREADY_OPEN, "GATT_ALREADY_OPEN"), - std::make_pair(GATT_CANCEL, "GATT_CANCEL"), - std::make_pair(GATT_CONNECTION_TIMEOUT, "GATT_CONNECTION_TIMEOUT"), - std::make_pair(GATT_CCC_CFG_ERR, "GATT_CCC_CFG_ERR"), - std::make_pair(GATT_PRC_IN_PROGRESS, "GATT_PRC_IN_PROGRESS"), - std::make_pair(GATT_OUT_OF_RANGE, "GATT_OUT_OF_RANGE"), + std::make_pair(GATT_SUCCESS, "GATT_SUCCESS"), // Also GATT_ENCRYPED_MITM + std::make_pair(GATT_INVALID_HANDLE, "GATT_INVALID_HANDLE"), + std::make_pair(GATT_READ_NOT_PERMIT, "GATT_READ_NOT_PERMIT"), + std::make_pair(GATT_WRITE_NOT_PERMIT, "GATT_WRITE_NOT_PERMIT"), + std::make_pair(GATT_INVALID_PDU, "GATT_INVALID_PDU"), + std::make_pair(GATT_INSUF_AUTHENTICATION, "GATT_INSUF_AUTHENTICATION"), + std::make_pair(GATT_REQ_NOT_SUPPORTED, "GATT_REQ_NOT_SUPPORTED"), + std::make_pair(GATT_INVALID_OFFSET, "GATT_INVALID_OFFSET"), + std::make_pair(GATT_INSUF_AUTHORIZATION, "GATT_INSUF_AUTHORIZATION"), + std::make_pair(GATT_PREPARE_Q_FULL, "GATT_PREPARE_Q_FULL"), + std::make_pair(GATT_NOT_FOUND, "GATT_NOT_FOUND"), + std::make_pair(GATT_NOT_LONG, "GATT_NOT_LONG"), + std::make_pair(GATT_INSUF_KEY_SIZE, "GATT_INSUF_KEY_SIZE"), + std::make_pair(GATT_INVALID_ATTR_LEN, "GATT_INVALID_ATTR_LEN"), + std::make_pair(GATT_ERR_UNLIKELY, "GATT_ERR_UNLIKELY"), + std::make_pair(GATT_INSUF_ENCRYPTION, "GATT_INSUF_ENCRYPTION"), + std::make_pair(GATT_UNSUPPORT_GRP_TYPE, "GATT_UNSUPPORT_GRP_TYPE"), + std::make_pair(GATT_INSUF_RESOURCE, "GATT_INSUF_RESOURCE"), + std::make_pair(GATT_DATABASE_OUT_OF_SYNC, "GATT_DATABASE_OUT_OF_SYNC"), + std::make_pair(GATT_VALUE_NOT_ALLOWED, "GATT_VALUE_NOT_ALLOWED"), + std::make_pair(GATT_ILLEGAL_PARAMETER, "GATT_ILLEGAL_PARAMETER"), + std::make_pair(GATT_NO_RESOURCES, "GATT_NO_RESOURCES"), + std::make_pair(GATT_INTERNAL_ERROR, "GATT_INTERNAL_ERROR"), + std::make_pair(GATT_WRONG_STATE, "GATT_WRONG_STATE"), + std::make_pair(GATT_DB_FULL, "GATT_DB_FULL"), + std::make_pair(GATT_BUSY, "GATT_BUSY"), + std::make_pair(GATT_ERROR, "GATT_ERROR"), + std::make_pair(GATT_CMD_STARTED, "GATT_CMD_STARTED"), + std::make_pair(GATT_PENDING, "GATT_PENDING"), + std::make_pair(GATT_AUTH_FAIL, "GATT_AUTH_FAIL"), + std::make_pair(GATT_INVALID_CFG, "GATT_INVALID_CFG"), + std::make_pair(GATT_SERVICE_STARTED, "GATT_SERVICE_STARTED"), + std::make_pair(GATT_ENCRYPED_NO_MITM, "GATT_ENCRYPED_NO_MITM"), + std::make_pair(GATT_NOT_ENCRYPTED, "GATT_NOT_ENCRYPTED"), + std::make_pair(GATT_CONGESTED, "GATT_CONGESTED"), + std::make_pair(GATT_DUP_REG, "GATT_DUP_REG"), + std::make_pair(GATT_ALREADY_OPEN, "GATT_ALREADY_OPEN"), + std::make_pair(GATT_CANCEL, "GATT_CANCEL"), + std::make_pair(GATT_CONNECTION_TIMEOUT, "GATT_CONNECTION_TIMEOUT"), + std::make_pair(GATT_CCC_CFG_ERR, "GATT_CCC_CFG_ERR"), + std::make_pair(GATT_PRC_IN_PROGRESS, "GATT_PRC_IN_PROGRESS"), + std::make_pair(GATT_OUT_OF_RANGE, "GATT_OUT_OF_RANGE"), }; for (const auto& status : statuses) { ASSERT_STREQ(status.second.c_str(), gatt_status_text(status.first).c_str()); } // Typical max value is already classified so use arbitrary unused one. auto unknown = base::StringPrintf("UNKNOWN[%hhu]", 0xfc); - ASSERT_STREQ(unknown.c_str(), - gatt_status_text(static_cast(0xfc)).c_str()); + ASSERT_STREQ(unknown.c_str(), gatt_status_text(static_cast(0xfc)).c_str()); } const static std::map gatt_min_value_cmd_size{ - {GATT_RSP_READ_BY_TYPE, 4}, // op_code (1) + pair_len (1) + handle (2) - {GATT_RSP_READ_BLOB, 1}, // op_code (1) - {GATT_RSP_READ, 1}, - {GATT_REQ_PREPARE_WRITE, 5}, // op_code (1) + handle (2) + offset (2) - {GATT_REQ_READ_BY_GRP_TYPE, 3}, // op_code + handle + {GATT_RSP_READ_BY_TYPE, 4}, // op_code (1) + pair_len (1) + handle (2) + {GATT_RSP_READ_BLOB, 1}, // op_code (1) + {GATT_RSP_READ, 1}, + {GATT_REQ_PREPARE_WRITE, 5}, // op_code (1) + handle (2) + offset (2) + {GATT_REQ_READ_BY_GRP_TYPE, 3}, // op_code + handle }; -static void attp_build_value_cmd_test_with_p_data(uint16_t payload_size, - uint8_t op_code, - uint16_t handle, - uint16_t offset, uint16_t len, +static void attp_build_value_cmd_test_with_p_data(uint16_t payload_size, uint8_t op_code, + uint16_t handle, uint16_t offset, uint16_t len, uint8_t* p_data) { uint16_t min_payload_size; uint8_t pair_len_read; uint16_t offset_read = 0; uint16_t handle_read = 0; - ASSERT_TRUE(gatt_min_value_cmd_size.find(op_code) != - gatt_min_value_cmd_size.end()); + ASSERT_TRUE(gatt_min_value_cmd_size.find(op_code) != gatt_min_value_cmd_size.end()); min_payload_size = gatt_min_value_cmd_size.at(op_code); ASSERT_GE(payload_size, min_payload_size); - BT_HDR* ret = bluetooth::legacy::testing::attp_build_value_cmd( - payload_size, op_code, handle, offset, len, p_data); + BT_HDR* ret = bluetooth::legacy::testing::attp_build_value_cmd(payload_size, op_code, handle, + offset, len, p_data); ASSERT_NE(ret, nullptr); uint8_t* p = (uint8_t*)(ret + 1) + L2CAP_MIN_OFFSET; @@ -270,8 +256,7 @@ static void attp_build_value_cmd_test_with_p_data(uint16_t payload_size, ASSERT_EQ(handle_read, handle); } else if (op_code == GATT_RSP_READ_BLOB || op_code == GATT_RSP_READ) { ; - } else if (op_code == GATT_REQ_PREPARE_WRITE || - op_code == GATT_RSP_PREPARE_WRITE) { + } else if (op_code == GATT_REQ_PREPARE_WRITE || op_code == GATT_RSP_PREPARE_WRITE) { STREAM_TO_UINT16(handle_read, p); ASSERT_EQ(handle_read, handle); STREAM_TO_UINT16(offset_read, p); @@ -312,34 +297,28 @@ static void attp_build_value_cmd_test_with_p_data(uint16_t payload_size, } TEST_F(StackGattTest, attp_build_value_cmd_p_data_null) { - for (auto it = gatt_min_value_cmd_size.begin(); - it != gatt_min_value_cmd_size.end(); it++) { - attp_build_value_cmd_test_with_p_data(it->second, it->first, 0x1, 0x1234, 0, - nullptr); + for (auto it = gatt_min_value_cmd_size.begin(); it != gatt_min_value_cmd_size.end(); it++) { + attp_build_value_cmd_test_with_p_data(it->second, it->first, 0x1, 0x1234, 0, nullptr); } } TEST_F(StackGattTest, attp_build_value_cmd_no_p_data) { - for (auto it = gatt_min_value_cmd_size.begin(); - it != gatt_min_value_cmd_size.end(); it++) { - attp_build_value_cmd_test_with_p_data(it->second, it->first, 0x1, 0x1234, 3, - (uint8_t*)"abc"); + for (auto it = gatt_min_value_cmd_size.begin(); it != gatt_min_value_cmd_size.end(); it++) { + attp_build_value_cmd_test_with_p_data(it->second, it->first, 0x1, 0x1234, 3, (uint8_t*)"abc"); } } TEST_F(StackGattTest, attp_build_value_cmd_partial_p_data) { - for (auto it = gatt_min_value_cmd_size.begin(); - it != gatt_min_value_cmd_size.end(); it++) { - attp_build_value_cmd_test_with_p_data(it->second + 1, it->first, 0x1, - 0x1234, 3, (uint8_t*)"abc"); + for (auto it = gatt_min_value_cmd_size.begin(); it != gatt_min_value_cmd_size.end(); it++) { + attp_build_value_cmd_test_with_p_data(it->second + 1, it->first, 0x1, 0x1234, 3, + (uint8_t*)"abc"); } } TEST_F(StackGattTest, attp_build_value_cmd_full_p_data) { - for (auto it = gatt_min_value_cmd_size.begin(); - it != gatt_min_value_cmd_size.end(); it++) { - attp_build_value_cmd_test_with_p_data(it->second + 5, it->first, 0x1, - 0x1234, 3, (uint8_t*)"abc"); + for (auto it = gatt_min_value_cmd_size.begin(); it != gatt_min_value_cmd_size.end(); it++) { + attp_build_value_cmd_test_with_p_data(it->second + 5, it->first, 0x1, 0x1234, 3, + (uint8_t*)"abc"); } } @@ -351,20 +330,17 @@ static void attp_build_value_cmd_small_payload_size(uint8_t op_code) { uint8_t* p_data = nullptr; uint16_t test_payload_size = gatt_min_value_cmd_size.at(op_code) - 1; - ASSERT_TRUE(gatt_min_value_cmd_size.find(op_code) != - gatt_min_value_cmd_size.end()); + ASSERT_TRUE(gatt_min_value_cmd_size.find(op_code) != gatt_min_value_cmd_size.end()); test_payload_size = gatt_min_value_cmd_size.at(op_code) - 1; - BT_HDR* ret = bluetooth::legacy::testing::attp_build_value_cmd( - test_payload_size, op_code, handle, offset_0, len, p_data); + BT_HDR* ret = bluetooth::legacy::testing::attp_build_value_cmd(test_payload_size, op_code, handle, + offset_0, len, p_data); ASSERT_EQ(ret, nullptr); } -TEST_F(StackGattTest, - attp_build_value_cmd_test_payload_size_less_than_mimimal) { - for (auto it = gatt_min_value_cmd_size.begin(); - it != gatt_min_value_cmd_size.end(); it++) { +TEST_F(StackGattTest, attp_build_value_cmd_test_payload_size_less_than_mimimal) { + for (auto it = gatt_min_value_cmd_size.begin(); it != gatt_min_value_cmd_size.end(); it++) { attp_build_value_cmd_small_payload_size(it->first); } } @@ -385,7 +361,7 @@ TEST_F(StackGattTest, attp_build_value_cmd_read_by_type_test_long_data) { data[i] = 'A'; } - BT_HDR* ret = bluetooth::legacy::testing::attp_build_value_cmd( - payload_size, op_code, handle, offset_0, data_size, data); + BT_HDR* ret = bluetooth::legacy::testing::attp_build_value_cmd(payload_size, op_code, handle, + offset_0, data_size, data); ASSERT_EQ(ret, nullptr); } diff --git a/system/stack/test/gatt_connection_manager_test.cc b/system/stack/test/gatt_connection_manager_test.cc index afa178d9d5f..ea023f73484 100644 --- a/system/stack/test/gatt_connection_manager_test.cc +++ b/system/stack/test/gatt_connection_manager_test.cc @@ -25,7 +25,7 @@ namespace { // convenience mock, for verifying acceptlist operations on lower layer are // actually scheduled class AcceptlistMock { - public: +public: MOCK_METHOD1(AcceptlistAdd, bool(const RawAddress&)); MOCK_METHOD2(AcceptlistAdd, bool(const RawAddress&, bool is_direct)); MOCK_METHOD1(AcceptlistRemove, void(const RawAddress&)); @@ -63,13 +63,11 @@ void BTM_AcceptlistRemove(const RawAddress& address) { void BTM_AcceptlistClear() { return localAcceptlistMock->AcceptlistClear(); } -void BTM_BleTargetAnnouncementObserve(bool enable, - tBTM_INQ_RESULTS_CB* p_results_cb) { +void BTM_BleTargetAnnouncementObserve(bool enable, tBTM_INQ_RESULTS_CB* p_results_cb) { localAcceptlistMock->EnableTargetedAnnouncements(enable, p_results_cb); } -void BTM_LogHistory(const std::string& tag, const RawAddress& bd_addr, - const std::string& msg){}; +void BTM_LogHistory(const std::string& tag, const RawAddress& bd_addr, const std::string& msg) {} namespace bluetooth { namespace shim { @@ -77,18 +75,12 @@ void set_target_announcements_filter(bool enable) {} } // namespace shim } // namespace bluetooth -bool L2CA_ConnectFixedChnl(uint16_t fixed_cid, const RawAddress& bd_addr) { - return false; -} -uint16_t BTM_GetHCIConnHandle(RawAddress const&, unsigned char) { - return 0xFFFF; -}; +bool L2CA_ConnectFixedChnl(uint16_t fixed_cid, const RawAddress& bd_addr) { return false; } +uint16_t BTM_GetHCIConnHandle(RawAddress const&, unsigned char) { return 0xFFFF; } namespace connection_manager { class BleConnectionManager : public testing::Test { - void SetUp() override { - localAcceptlistMock = std::make_unique(); - } + void SetUp() override { localAcceptlistMock = std::make_unique(); } void TearDown() override { connection_manager::reset(true); @@ -104,8 +96,7 @@ void on_connection_timed_out(uint8_t app_id, const RawAddress& address) { /** Verify that app can add a device to acceptlist, it is returned as interested * app, and then can remove the device later. */ TEST_F(BleConnectionManager, test_background_connection_add_remove) { - EXPECT_CALL(*localAcceptlistMock, AcceptlistAdd(address1)) - .WillOnce(Return(true)); + EXPECT_CALL(*localAcceptlistMock, AcceptlistAdd(address1)).WillOnce(Return(true)); EXPECT_CALL(*localAcceptlistMock, AcceptlistRemove(_)).Times(0); EXPECT_TRUE(background_connect_add(CLIENT1, address1)); @@ -130,8 +121,7 @@ TEST_F(BleConnectionManager, test_background_connection_add_remove) { * device being added to whtie list only once, also, that device is removed only * after last client removes it. */ TEST_F(BleConnectionManager, test_background_connection_multiple_clients) { - EXPECT_CALL(*localAcceptlistMock, AcceptlistAdd(address1)) - .WillOnce(Return(true)); + EXPECT_CALL(*localAcceptlistMock, AcceptlistAdd(address1)).WillOnce(Return(true)); EXPECT_CALL(*localAcceptlistMock, AcceptlistRemove(_)).Times(0); EXPECT_TRUE(background_connect_add(CLIENT1, address1)); EXPECT_TRUE(background_connect_add(CLIENT1, address1)); @@ -164,8 +154,7 @@ TEST_F(BleConnectionManager, test_background_connection_multiple_clients) { TEST_F(BleConnectionManager, test_direct_connection_client) { // Direct connect attempt: use faster scan parameters, add to acceptlist, // start 30 timeout - EXPECT_CALL(*localAcceptlistMock, AcceptlistAdd(address1, true)) - .WillOnce(Return(true)); + EXPECT_CALL(*localAcceptlistMock, AcceptlistAdd(address1, true)).WillOnce(Return(true)); EXPECT_CALL(*localAcceptlistMock, AcceptlistRemove(_)).Times(0); EXPECT_CALL(*AlarmMock::Get(), AlarmNew(_)).Times(1); EXPECT_CALL(*AlarmMock::Get(), AlarmSetOnMloop(_, _, _, _)).Times(1); @@ -193,15 +182,14 @@ TEST_F(BleConnectionManager, test_direct_connection_client) { /** Verify direct connection timeout does remove device from acceptlist, and * lower the connection scan parameters */ TEST_F(BleConnectionManager, test_direct_connect_timeout) { - EXPECT_CALL(*localAcceptlistMock, AcceptlistAdd(address1, true)) - .WillOnce(Return(true)); + EXPECT_CALL(*localAcceptlistMock, AcceptlistAdd(address1, true)).WillOnce(Return(true)); EXPECT_CALL(*AlarmMock::Get(), AlarmNew(_)).Times(1); alarm_callback_t alarm_callback = nullptr; void* alarm_data = nullptr; EXPECT_CALL(*AlarmMock::Get(), AlarmSetOnMloop(_, _, _, _)) - .Times(1) - .WillOnce(DoAll(SaveArg<2>(&alarm_callback), SaveArg<3>(&alarm_data))); + .Times(1) + .WillOnce(DoAll(SaveArg<2>(&alarm_callback), SaveArg<3>(&alarm_data))); // Start direct connect attempt... EXPECT_TRUE(direct_connect_add(CLIENT1, address1)); @@ -209,8 +197,7 @@ TEST_F(BleConnectionManager, test_direct_connect_timeout) { Mock::VerifyAndClearExpectations(localAcceptlistMock.get()); EXPECT_CALL(*localAcceptlistMock, AcceptlistRemove(_)).Times(1); - EXPECT_CALL(*localAcceptlistMock, OnConnectionTimedOut(CLIENT1, address1)) - .Times(1); + EXPECT_CALL(*localAcceptlistMock, OnConnectionTimedOut(CLIENT1, address1)).Times(1); EXPECT_CALL(*AlarmMock::Get(), AlarmFree(_)).Times(1); // simulate timeout seconds passed, alarm executing @@ -221,8 +208,7 @@ TEST_F(BleConnectionManager, test_direct_connect_timeout) { /** Verify that we properly handle successfull direct connection */ TEST_F(BleConnectionManager, test_direct_connection_success) { - EXPECT_CALL(*localAcceptlistMock, AcceptlistAdd(address1, true)) - .WillOnce(Return(true)); + EXPECT_CALL(*localAcceptlistMock, AcceptlistAdd(address1, true)).WillOnce(Return(true)); EXPECT_CALL(*AlarmMock::Get(), AlarmNew(_)).Times(1); EXPECT_CALL(*AlarmMock::Get(), AlarmSetOnMloop(_, _, _, _)).Times(1); @@ -247,10 +233,8 @@ TEST_F(BleConnectionManager, test_app_unregister) { * - unregistration of Client2 should trigger address2 removal */ - EXPECT_CALL(*localAcceptlistMock, AcceptlistAdd(address1, true)) - .WillOnce(Return(true)); - EXPECT_CALL(*localAcceptlistMock, AcceptlistAdd(address2)) - .WillOnce(Return(true)); + EXPECT_CALL(*localAcceptlistMock, AcceptlistAdd(address1, true)).WillOnce(Return(true)); + EXPECT_CALL(*localAcceptlistMock, AcceptlistAdd(address2)).WillOnce(Return(true)); EXPECT_TRUE(direct_connect_add(CLIENT1, address1)); EXPECT_TRUE(background_connect_add(CLIENT1, address2)); EXPECT_TRUE(direct_connect_add(CLIENT2, address2)); @@ -266,8 +250,7 @@ TEST_F(BleConnectionManager, test_app_unregister) { /** Verify adding device to both direct connection and background connection. */ TEST_F(BleConnectionManager, test_direct_and_background_connect) { - EXPECT_CALL(*localAcceptlistMock, AcceptlistAdd(address1, true)) - .WillOnce(Return(true)); + EXPECT_CALL(*localAcceptlistMock, AcceptlistAdd(address1, true)).WillOnce(Return(true)); EXPECT_CALL(*localAcceptlistMock, AcceptlistRemove(_)).Times(0); EXPECT_CALL(*AlarmMock::Get(), AlarmNew(_)).Times(1); EXPECT_CALL(*AlarmMock::Get(), AlarmSetOnMloop(_, _, _, _)).Times(1); @@ -295,11 +278,9 @@ TEST_F(BleConnectionManager, test_target_announement_connect) { EXPECT_TRUE(background_connect_targeted_announcement_add(CLIENT1, address1)); } -TEST_F(BleConnectionManager, - test_add_targeted_announement_when_allow_list_used) { +TEST_F(BleConnectionManager, test_add_targeted_announement_when_allow_list_used) { /* Accept adding to allow list */ - EXPECT_CALL(*localAcceptlistMock, AcceptlistAdd(address1)) - .WillOnce(Return(true)); + EXPECT_CALL(*localAcceptlistMock, AcceptlistAdd(address1)).WillOnce(Return(true)); /* This shall be called when registering announcements */ EXPECT_CALL(*localAcceptlistMock, AcceptlistRemove(_)).Times(1); @@ -309,8 +290,7 @@ TEST_F(BleConnectionManager, Mock::VerifyAndClearExpectations(localAcceptlistMock.get()); } -TEST_F(BleConnectionManager, - test_add_background_connect_when_targeted_announcement_are_enabled) { +TEST_F(BleConnectionManager, test_add_background_connect_when_targeted_announcement_are_enabled) { /* Accept adding to allow list */ EXPECT_CALL(*localAcceptlistMock, AcceptlistAdd(address1)).Times(0); @@ -337,8 +317,7 @@ TEST_F(BleConnectionManager, test_re_add_background_connect_to_allow_list) { */ /* Accept adding to allow list */ - EXPECT_CALL(*localAcceptlistMock, AcceptlistAdd(address1)) - .WillOnce(Return(true)); + EXPECT_CALL(*localAcceptlistMock, AcceptlistAdd(address1)).WillOnce(Return(true)); EXPECT_TRUE(background_connect_remove(CLIENT2, address1)); Mock::VerifyAndClearExpectations(localAcceptlistMock.get()); @@ -348,15 +327,13 @@ TEST_F(BleConnectionManager, test_re_add_background_connect_to_allow_list) { Mock::VerifyAndClearExpectations(localAcceptlistMock.get()); } -TEST_F(BleConnectionManager, - test_re_add_to_allow_list_after_timeout_with_multiple_clients) { +TEST_F(BleConnectionManager, test_re_add_to_allow_list_after_timeout_with_multiple_clients) { EXPECT_CALL(*AlarmMock::Get(), AlarmNew(_)).Times(1); alarm_callback_t alarm_callback = nullptr; void* alarm_data = nullptr; /* Accept adding to allow list */ - ON_CALL(*localAcceptlistMock, AcceptlistAdd(address1)) - .WillByDefault(Return(true)); + ON_CALL(*localAcceptlistMock, AcceptlistAdd(address1)).WillByDefault(Return(true)); EXPECT_CALL(*localAcceptlistMock, AcceptlistAdd(address1)).Times(1); EXPECT_CALL(*localAcceptlistMock, AcceptlistRemove(_)).Times(0); @@ -366,16 +343,15 @@ TEST_F(BleConnectionManager, Mock::VerifyAndClearExpectations(localAcceptlistMock.get()); EXPECT_CALL(*AlarmMock::Get(), AlarmSetOnMloop(_, _, _, _)) - .Times(1) - .WillOnce(DoAll(SaveArg<2>(&alarm_callback), SaveArg<3>(&alarm_data))); + .Times(1) + .WillOnce(DoAll(SaveArg<2>(&alarm_callback), SaveArg<3>(&alarm_data))); // Start direct connect attempt... EXPECT_TRUE(direct_connect_add(CLIENT2, address1)); Mock::VerifyAndClearExpectations(localAcceptlistMock.get()); // simulate timeout seconds passed, alarm executing - EXPECT_CALL(*localAcceptlistMock, OnConnectionTimedOut(CLIENT2, address1)) - .Times(1); + EXPECT_CALL(*localAcceptlistMock, OnConnectionTimedOut(CLIENT2, address1)).Times(1); EXPECT_CALL(*localAcceptlistMock, AcceptlistRemove(_)).Times(0); EXPECT_CALL(*localAcceptlistMock, AcceptlistAdd(address1)).Times(1); EXPECT_CALL(*AlarmMock::Get(), AlarmFree(_)).Times(1); diff --git a/system/stack/test/hci/stack_hci_test.cc b/system/stack/test/hci/stack_hci_test.cc index 3c6cf1c562a..93d1de3f169 100644 --- a/system/stack/test/hci/stack_hci_test.cc +++ b/system/stack/test/hci/stack_hci_test.cc @@ -36,8 +36,8 @@ using testing::StrictMock; using testing::Test; class StackHciTest : public Test { - public: - protected: +public: +protected: void SetUp() override { reset_mock_function_count_map(); } void TearDown() override {} }; @@ -65,8 +65,7 @@ TEST_F(StackHciTest, hci_preamble) { { HciDataPreamble preamble; - preamble.raw.word0 = - 0x123 | (L2CAP_PKT_START_NON_FLUSHABLE << L2CAP_PKT_TYPE_SHIFT); + preamble.raw.word0 = 0x123 | (L2CAP_PKT_START_NON_FLUSHABLE << L2CAP_PKT_TYPE_SHIFT); preamble.raw.word1 = 0x4567; ASSERT_EQ(sizeof(preamble), HCI_DATA_PREAMBLE_SIZE); @@ -118,86 +117,64 @@ TEST_F(StackHciTest, hci_preamble) { ASSERT_TRUE(preamble.IsFlushable()); - preamble.raw.word0 = - 0x0 | (L2CAP_PKT_START << L2CAP_PKT_START_NON_FLUSHABLE); + preamble.raw.word0 = 0x0 | (L2CAP_PKT_START << L2CAP_PKT_START_NON_FLUSHABLE); ASSERT_TRUE(!preamble.IsFlushable()); } } TEST_F(StackHciTest, hci_error_code_text) { std::vector> errors = { - std::make_pair(HCI_SUCCESS, "HCI_SUCCESS"), - std::make_pair(HCI_ERR_ILLEGAL_COMMAND, "HCI_ERR_ILLEGAL_COMMAND"), - std::make_pair(HCI_ERR_NO_CONNECTION, "HCI_ERR_NO_CONNECTION"), - std::make_pair(HCI_ERR_HW_FAILURE, "HCI_ERR_HW_FAILURE"), - std::make_pair(HCI_ERR_PAGE_TIMEOUT, "HCI_ERR_PAGE_TIMEOUT"), - std::make_pair(HCI_ERR_AUTH_FAILURE, "HCI_ERR_AUTH_FAILURE"), - std::make_pair(HCI_ERR_KEY_MISSING, "HCI_ERR_KEY_MISSING"), - std::make_pair(HCI_ERR_MEMORY_FULL, "HCI_ERR_MEMORY_FULL"), - std::make_pair(HCI_ERR_CONNECTION_TOUT, "HCI_ERR_CONNECTION_TOUT"), - std::make_pair(HCI_ERR_MAX_NUM_OF_CONNECTIONS, - "HCI_ERR_MAX_NUM_OF_CONNECTIONS"), - std::make_pair(HCI_ERR_MAX_NUM_OF_SCOS, "HCI_ERR_MAX_NUM_OF_SCOS"), - std::make_pair(HCI_ERR_CONNECTION_EXISTS, "HCI_ERR_CONNECTION_EXISTS"), - std::make_pair(HCI_ERR_COMMAND_DISALLOWED, "HCI_ERR_COMMAND_DISALLOWED"), - std::make_pair(HCI_ERR_HOST_REJECT_RESOURCES, - "HCI_ERR_HOST_REJECT_RESOURCES"), - std::make_pair(HCI_ERR_HOST_REJECT_SECURITY, - "HCI_ERR_HOST_REJECT_SECURITY"), - std::make_pair(HCI_ERR_HOST_REJECT_DEVICE, "HCI_ERR_HOST_REJECT_DEVICE"), - std::make_pair(HCI_ERR_HOST_TIMEOUT, "HCI_ERR_HOST_TIMEOUT"), - std::make_pair(HCI_ERR_ILLEGAL_PARAMETER_FMT, - "HCI_ERR_ILLEGAL_PARAMETER_FMT"), - std::make_pair(HCI_ERR_PEER_USER, "HCI_ERR_PEER_USER"), - std::make_pair(HCI_ERR_REMOTE_LOW_RESOURCE, - "HCI_ERR_REMOTE_LOW_RESOURCE"), - std::make_pair(HCI_ERR_REMOTE_POWER_OFF, "HCI_ERR_REMOTE_POWER_OFF"), - std::make_pair(HCI_ERR_CONN_CAUSE_LOCAL_HOST, - "HCI_ERR_CONN_CAUSE_LOCAL_HOST"), - std::make_pair(HCI_ERR_REPEATED_ATTEMPTS, "HCI_ERR_REPEATED_ATTEMPTS"), - std::make_pair(HCI_ERR_PAIRING_NOT_ALLOWED, - "HCI_ERR_PAIRING_NOT_ALLOWED"), - std::make_pair(HCI_ERR_UNSUPPORTED_REM_FEATURE, - "HCI_ERR_UNSUPPORTED_REM_FEATURE"), - std::make_pair(HCI_ERR_UNSPECIFIED, "HCI_ERR_UNSPECIFIED"), - std::make_pair(HCI_ERR_LMP_RESPONSE_TIMEOUT, - "HCI_ERR_LMP_RESPONSE_TIMEOUT"), - std::make_pair(HCI_ERR_LMP_ERR_TRANS_COLLISION, - "HCI_ERR_LMP_ERR_TRANS_COLLISION"), - std::make_pair(HCI_ERR_ENCRY_MODE_NOT_ACCEPTABLE, - "HCI_ERR_ENCRY_MODE_NOT_ACCEPTABLE"), - std::make_pair(HCI_ERR_UNIT_KEY_USED, "HCI_ERR_UNIT_KEY_USED"), - std::make_pair(HCI_ERR_PAIRING_WITH_UNIT_KEY_NOT_SUPPORTED, - "HCI_ERR_PAIRING_WITH_UNIT_KEY_NOT_SUPPORTED"), - std::make_pair(HCI_ERR_DIFF_TRANSACTION_COLLISION, - "HCI_ERR_DIFF_TRANSACTION_COLLISION"), - std::make_pair(HCI_ERR_INSUFFCIENT_SECURITY, - "HCI_ERR_INSUFFCIENT_SECURITY"), - std::make_pair(HCI_ERR_ROLE_SWITCH_PENDING, - "HCI_ERR_ROLE_SWITCH_PENDING"), - std::make_pair(HCI_ERR_ROLE_SWITCH_FAILED, "HCI_ERR_ROLE_SWITCH_FAILED"), - std::make_pair(HCI_ERR_HOST_BUSY_PAIRING, "HCI_ERR_HOST_BUSY_PAIRING"), - std::make_pair(HCI_ERR_UNACCEPT_CONN_INTERVAL, - "HCI_ERR_UNACCEPT_CONN_INTERVAL"), - std::make_pair(HCI_ERR_ADVERTISING_TIMEOUT, - "HCI_ERR_ADVERTISING_TIMEOUT"), - std::make_pair(HCI_ERR_CONN_FAILED_ESTABLISHMENT, - "HCI_ERR_CONN_FAILED_ESTABLISHMENT"), - std::make_pair(HCI_ERR_LIMIT_REACHED, "HCI_ERR_LIMIT_REACHED"), + std::make_pair(HCI_SUCCESS, "HCI_SUCCESS"), + std::make_pair(HCI_ERR_ILLEGAL_COMMAND, "HCI_ERR_ILLEGAL_COMMAND"), + std::make_pair(HCI_ERR_NO_CONNECTION, "HCI_ERR_NO_CONNECTION"), + std::make_pair(HCI_ERR_HW_FAILURE, "HCI_ERR_HW_FAILURE"), + std::make_pair(HCI_ERR_PAGE_TIMEOUT, "HCI_ERR_PAGE_TIMEOUT"), + std::make_pair(HCI_ERR_AUTH_FAILURE, "HCI_ERR_AUTH_FAILURE"), + std::make_pair(HCI_ERR_KEY_MISSING, "HCI_ERR_KEY_MISSING"), + std::make_pair(HCI_ERR_MEMORY_FULL, "HCI_ERR_MEMORY_FULL"), + std::make_pair(HCI_ERR_CONNECTION_TOUT, "HCI_ERR_CONNECTION_TOUT"), + std::make_pair(HCI_ERR_MAX_NUM_OF_CONNECTIONS, "HCI_ERR_MAX_NUM_OF_CONNECTIONS"), + std::make_pair(HCI_ERR_MAX_NUM_OF_SCOS, "HCI_ERR_MAX_NUM_OF_SCOS"), + std::make_pair(HCI_ERR_CONNECTION_EXISTS, "HCI_ERR_CONNECTION_EXISTS"), + std::make_pair(HCI_ERR_COMMAND_DISALLOWED, "HCI_ERR_COMMAND_DISALLOWED"), + std::make_pair(HCI_ERR_HOST_REJECT_RESOURCES, "HCI_ERR_HOST_REJECT_RESOURCES"), + std::make_pair(HCI_ERR_HOST_REJECT_SECURITY, "HCI_ERR_HOST_REJECT_SECURITY"), + std::make_pair(HCI_ERR_HOST_REJECT_DEVICE, "HCI_ERR_HOST_REJECT_DEVICE"), + std::make_pair(HCI_ERR_HOST_TIMEOUT, "HCI_ERR_HOST_TIMEOUT"), + std::make_pair(HCI_ERR_ILLEGAL_PARAMETER_FMT, "HCI_ERR_ILLEGAL_PARAMETER_FMT"), + std::make_pair(HCI_ERR_PEER_USER, "HCI_ERR_PEER_USER"), + std::make_pair(HCI_ERR_REMOTE_LOW_RESOURCE, "HCI_ERR_REMOTE_LOW_RESOURCE"), + std::make_pair(HCI_ERR_REMOTE_POWER_OFF, "HCI_ERR_REMOTE_POWER_OFF"), + std::make_pair(HCI_ERR_CONN_CAUSE_LOCAL_HOST, "HCI_ERR_CONN_CAUSE_LOCAL_HOST"), + std::make_pair(HCI_ERR_REPEATED_ATTEMPTS, "HCI_ERR_REPEATED_ATTEMPTS"), + std::make_pair(HCI_ERR_PAIRING_NOT_ALLOWED, "HCI_ERR_PAIRING_NOT_ALLOWED"), + std::make_pair(HCI_ERR_UNSUPPORTED_REM_FEATURE, "HCI_ERR_UNSUPPORTED_REM_FEATURE"), + std::make_pair(HCI_ERR_UNSPECIFIED, "HCI_ERR_UNSPECIFIED"), + std::make_pair(HCI_ERR_LMP_RESPONSE_TIMEOUT, "HCI_ERR_LMP_RESPONSE_TIMEOUT"), + std::make_pair(HCI_ERR_LMP_ERR_TRANS_COLLISION, "HCI_ERR_LMP_ERR_TRANS_COLLISION"), + std::make_pair(HCI_ERR_ENCRY_MODE_NOT_ACCEPTABLE, "HCI_ERR_ENCRY_MODE_NOT_ACCEPTABLE"), + std::make_pair(HCI_ERR_UNIT_KEY_USED, "HCI_ERR_UNIT_KEY_USED"), + std::make_pair(HCI_ERR_PAIRING_WITH_UNIT_KEY_NOT_SUPPORTED, + "HCI_ERR_PAIRING_WITH_UNIT_KEY_NOT_SUPPORTED"), + std::make_pair(HCI_ERR_DIFF_TRANSACTION_COLLISION, "HCI_ERR_DIFF_TRANSACTION_COLLISION"), + std::make_pair(HCI_ERR_INSUFFCIENT_SECURITY, "HCI_ERR_INSUFFCIENT_SECURITY"), + std::make_pair(HCI_ERR_ROLE_SWITCH_PENDING, "HCI_ERR_ROLE_SWITCH_PENDING"), + std::make_pair(HCI_ERR_ROLE_SWITCH_FAILED, "HCI_ERR_ROLE_SWITCH_FAILED"), + std::make_pair(HCI_ERR_HOST_BUSY_PAIRING, "HCI_ERR_HOST_BUSY_PAIRING"), + std::make_pair(HCI_ERR_UNACCEPT_CONN_INTERVAL, "HCI_ERR_UNACCEPT_CONN_INTERVAL"), + std::make_pair(HCI_ERR_ADVERTISING_TIMEOUT, "HCI_ERR_ADVERTISING_TIMEOUT"), + std::make_pair(HCI_ERR_CONN_FAILED_ESTABLISHMENT, "HCI_ERR_CONN_FAILED_ESTABLISHMENT"), + std::make_pair(HCI_ERR_LIMIT_REACHED, "HCI_ERR_LIMIT_REACHED"), }; for (const auto& error : errors) { - ASSERT_STREQ(error.second.c_str(), - hci_error_code_text(error.first).c_str()); + ASSERT_STREQ(error.second.c_str(), hci_error_code_text(error.first).c_str()); } for (const auto& error : errors) { - ASSERT_STREQ(error.second.c_str(), - hci_error_code_text(error.first).c_str()); + ASSERT_STREQ(error.second.c_str(), hci_error_code_text(error.first).c_str()); } - auto unknown = base::StringPrintf("UNKNOWN[0x%02hx]", - std::numeric_limits::max()); - ASSERT_STREQ( - unknown.c_str(), - hci_error_code_text(static_cast( - std::numeric_limits::max())) - .c_str()); + auto unknown = base::StringPrintf("UNKNOWN[0x%02hx]", std::numeric_limits::max()); + ASSERT_STREQ(unknown.c_str(), + hci_error_code_text( + static_cast(std::numeric_limits::max())) + .c_str()); } diff --git a/system/stack/test/hid/stack_hid_test.cc b/system/stack/test/hid/stack_hid_test.cc index 5b04dd3b360..7ddc705059e 100644 --- a/system/stack/test/hid/stack_hid_test.cc +++ b/system/stack/test/hid/stack_hid_test.cc @@ -28,10 +28,7 @@ bluetooth::common::MessageLoopThread* get_main_thread() { return nullptr; } tHCI_REASON btm_get_acl_disc_reason_code(void) { return HCI_SUCCESS; } -bool BTM_IsAclConnectionUp(const RawAddress& remote_bda, - tBT_TRANSPORT transport) { - return true; -} +bool BTM_IsAclConnectionUp(const RawAddress& remote_bda, tBT_TRANSPORT transport) { return true; } namespace { using testing::_; @@ -46,8 +43,8 @@ using testing::StrictMock; using testing::Test; class StackHidTest : public Test { - public: - protected: +public: +protected: void SetUp() override { reset_mock_function_count_map(); } void TearDown() override {} }; @@ -56,13 +53,12 @@ TEST_F(StackHidTest, disconnect_bad_cid) { tL2CAP_APPL_INFO l2cap_callbacks; test::mock::stack_l2cap_api::L2CA_RegisterWithSecurity.body = - [&l2cap_callbacks](uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info, - bool enable_snoop, tL2CAP_ERTM_INFO* p_ertm_info, - uint16_t my_mtu, uint16_t required_remote_mtu, - uint16_t sec_level) { - l2cap_callbacks = p_cb_info; - return psm; - }; + [&l2cap_callbacks](uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info, bool enable_snoop, + tL2CAP_ERTM_INFO* p_ertm_info, uint16_t my_mtu, + uint16_t required_remote_mtu, uint16_t sec_level) { + l2cap_callbacks = p_cb_info; + return psm; + }; tHID_STATUS status = hidh_conn_reg(); ASSERT_EQ(HID_SUCCESS, status); diff --git a/system/stack/test/rfcomm/stack_rfcomm_port_test.cc b/system/stack/test/rfcomm/stack_rfcomm_port_test.cc index e2c1b96f49b..c36364a08fb 100644 --- a/system/stack/test/rfcomm/stack_rfcomm_port_test.cc +++ b/system/stack/test/rfcomm/stack_rfcomm_port_test.cc @@ -26,11 +26,11 @@ const RawAddress kRawAddress = RawAddress({0x11, 0x22, 0x33, 0x44, 0x55, 0x66}); } // namespace class StackRfcommPortTest : public ::testing::Test { - protected: +protected: void SetUp() override {} void TearDown() override {} - private: +private: }; TEST_F(StackRfcommPortTest, PORT_IsOpening__basic) { diff --git a/system/stack/test/rfcomm/stack_rfcomm_test.cc b/system/stack/test/rfcomm/stack_rfcomm_test.cc index c30593a6d8b..86e030cc3e1 100644 --- a/system/stack/test/rfcomm/stack_rfcomm_test.cc +++ b/system/stack/test/rfcomm/stack_rfcomm_test.cc @@ -53,9 +53,7 @@ std::string DumpBtHdrToString(BT_HDR* p_hdr) { return DumpByteBufferToString(p_hdr_data, p_hdr->len); } -void PrintTo(BT_HDR* value, ::std::ostream* os) { - *os << DumpBtHdrToString(value); -} +void PrintTo(BT_HDR* value, ::std::ostream* os) { *os << DumpBtHdrToString(value); } void PrintTo(tL2CAP_CFG_INFO* value, ::std::ostream* os) { *os << DumpByteBufferToString((uint8_t*)value, sizeof(tL2CAP_CFG_INFO)); @@ -65,35 +63,34 @@ namespace { using testing::_; using testing::DoAll; +using testing::NotNull; +using testing::Pointee; using testing::Return; -using testing::Test; -using testing::StrictMock; using testing::SaveArg; using testing::SaveArgPointee; -using testing::Pointee; using testing::StrEq; -using testing::NotNull; +using testing::StrictMock; +using testing::Test; -using bluetooth::CreateL2capDataPacket; -using bluetooth::CreateAclPacket; using bluetooth::AllocateWrappedIncomingL2capAclPacket; using bluetooth::AllocateWrappedOutgoingL2capAclPacket; +using bluetooth::CreateAclPacket; +using bluetooth::CreateL2capDataPacket; -using bluetooth::rfcomm::GetDlci; -using bluetooth::rfcomm::GetAddressField; -using bluetooth::rfcomm::GetControlField; -using bluetooth::rfcomm::CreateMccPnFrame; using bluetooth::rfcomm::CreateMccMscFrame; +using bluetooth::rfcomm::CreateMccPnFrame; using bluetooth::rfcomm::CreateMultiplexerControlFrame; -using bluetooth::rfcomm::CreateRfcommPacket; using bluetooth::rfcomm::CreateQuickDataPacket; +using bluetooth::rfcomm::CreateQuickMscPacket; using bluetooth::rfcomm::CreateQuickPnPacket; using bluetooth::rfcomm::CreateQuickSabmPacket; using bluetooth::rfcomm::CreateQuickUaPacket; -using bluetooth::rfcomm::CreateQuickMscPacket; +using bluetooth::rfcomm::CreateRfcommPacket; +using bluetooth::rfcomm::GetAddressField; +using bluetooth::rfcomm::GetControlField; +using bluetooth::rfcomm::GetDlci; -MATCHER_P(PointerMemoryEqual, ptr, - DumpByteBufferToString((uint8_t*)ptr, sizeof(*ptr))) { +MATCHER_P(PointerMemoryEqual, ptr, DumpByteBufferToString((uint8_t*)ptr, sizeof(*ptr))) { return memcmp(arg, ptr, sizeof(*ptr)) == 0; } @@ -125,40 +122,32 @@ void port_event_cback_1(uint32_t code, uint16_t port_handle) { RawAddress GetTestAddress(int index) { EXPECT_LT(index, UINT8_MAX); - RawAddress result = { - {0xAA, 0x00, 0x11, 0x22, 0x33, static_cast(index)}}; + RawAddress result = {{0xAA, 0x00, 0x11, 0x22, 0x33, static_cast(index)}}; return result; } class StackRfcommTest : public Test { - public: +public: void StartServerPort(uint16_t uuid, uint8_t scn, uint16_t mtu, - tPORT_MGMT_CALLBACK* management_callback, - tPORT_CALLBACK* event_callback, + tPORT_MGMT_CALLBACK* management_callback, tPORT_CALLBACK* event_callback, uint16_t* server_handle) { log::verbose("Step 1"); - ASSERT_EQ(RFCOMM_CreateConnectionWithSecurity( - uuid, scn, true, mtu, RawAddress::kAny, server_handle, - management_callback, 0), + ASSERT_EQ(RFCOMM_CreateConnectionWithSecurity(uuid, scn, true, mtu, RawAddress::kAny, + server_handle, management_callback, 0), PORT_SUCCESS); - ASSERT_EQ(PORT_SetEventMaskAndCallback(*server_handle, PORT_EV_RXCHAR, - event_callback), + ASSERT_EQ(PORT_SetEventMaskAndCallback(*server_handle, PORT_EV_RXCHAR, event_callback), PORT_SUCCESS); } - void ConnectServerL2cap(const RawAddress& peer_addr, uint16_t acl_handle, - uint16_t lcid) { + void ConnectServerL2cap(const RawAddress& peer_addr, uint16_t acl_handle, uint16_t lcid) { log::verbose("Step 1"); // Remote device connect to this channel, we shall accept static const uint8_t cmd_id = 0x07; - EXPECT_CALL(l2cap_interface_, - ConnectResponse(peer_addr, cmd_id, lcid, L2CAP_CONN_OK, 0)); + EXPECT_CALL(l2cap_interface_, ConnectResponse(peer_addr, cmd_id, lcid, L2CAP_CONN_OK, 0)); tL2CAP_CFG_INFO cfg_req = {.mtu_present = true, .mtu = L2CAP_MTU_SIZE}; - EXPECT_CALL(l2cap_interface_, - ConfigRequest(lcid, PointerMemoryEqual(&cfg_req))) - .WillOnce(Return(true)); - l2cap_appl_info_.pL2CA_ConnectInd_Cb(peer_addr, lcid, BT_PSM_RFCOMM, - cmd_id); + EXPECT_CALL(l2cap_interface_, ConfigRequest(lcid, PointerMemoryEqual(&cfg_req))) + .WillOnce(Return(true)); + l2cap_appl_info_.pL2CA_ConnectInd_Cb(peer_addr, lcid, BT_PSM_RFCOMM, cmd_id); log::verbose("Step 2"); // MTU configuration is done @@ -167,40 +156,36 @@ class StackRfcommTest : public Test { log::verbose("Step 3"); // Remote device also ask to configure MTU size - EXPECT_CALL(l2cap_interface_, - ConfigResponse(lcid, PointerMemoryEqual(&cfg_req))) - .WillOnce(Return(true)); + EXPECT_CALL(l2cap_interface_, ConfigResponse(lcid, PointerMemoryEqual(&cfg_req))) + .WillOnce(Return(true)); l2cap_appl_info_.pL2CA_ConfigInd_Cb(lcid, &cfg_req); log::verbose("Step 4"); // Remote device connect to server channel 0 BT_HDR* sabm_channel_0 = AllocateWrappedIncomingL2capAclPacket( - CreateQuickSabmPacket(RFCOMM_MX_DLCI, lcid, acl_handle)); + CreateQuickSabmPacket(RFCOMM_MX_DLCI, lcid, acl_handle)); BT_HDR* ua_channel_0 = AllocateWrappedOutgoingL2capAclPacket( - CreateQuickUaPacket(RFCOMM_MX_DLCI, lcid, acl_handle)); + CreateQuickUaPacket(RFCOMM_MX_DLCI, lcid, acl_handle)); EXPECT_CALL(l2cap_interface_, DataWrite(lcid, BtHdrEqual(ua_channel_0))) - .WillOnce(Return(tL2CAP_DW_RESULT::SUCCESS)); + .WillOnce(Return(tL2CAP_DW_RESULT::SUCCESS)); // Packet should be freed by RFCOMM l2cap_appl_info_.pL2CA_DataInd_Cb(lcid, sabm_channel_0); osi_free(ua_channel_0); } - void ConnectServerPort(const RawAddress& peer_addr, uint16_t port_handle, - uint8_t scn, uint16_t mtu, uint16_t acl_handle, - uint16_t lcid, int port_callback_index) { + void ConnectServerPort(const RawAddress& peer_addr, uint16_t port_handle, uint8_t scn, + uint16_t mtu, uint16_t acl_handle, uint16_t lcid, + int port_callback_index) { log::verbose("Step 1"); // Negotiate parameters on scn - BT_HDR* uih_pn_cmd_from_peer = AllocateWrappedIncomingL2capAclPacket( - CreateQuickPnPacket(true, GetDlci(false, scn), true, mtu, - RFCOMM_PN_CONV_LAYER_CBFC_I >> 4, 0, RFCOMM_K_MAX, - lcid, acl_handle)); - BT_HDR* uih_pn_rsp_to_peer = AllocateWrappedOutgoingL2capAclPacket( - CreateQuickPnPacket(false, GetDlci(false, scn), false, mtu, - RFCOMM_PN_CONV_LAYER_CBFC_R >> 4, 0, RFCOMM_K_MAX, - lcid, acl_handle)); - EXPECT_CALL(l2cap_interface_, - DataWrite(lcid, BtHdrEqual(uih_pn_rsp_to_peer))) - .WillOnce(Return(tL2CAP_DW_RESULT::SUCCESS)); + BT_HDR* uih_pn_cmd_from_peer = AllocateWrappedIncomingL2capAclPacket(CreateQuickPnPacket( + true, GetDlci(false, scn), true, mtu, RFCOMM_PN_CONV_LAYER_CBFC_I >> 4, 0, RFCOMM_K_MAX, + lcid, acl_handle)); + BT_HDR* uih_pn_rsp_to_peer = AllocateWrappedOutgoingL2capAclPacket(CreateQuickPnPacket( + false, GetDlci(false, scn), false, mtu, RFCOMM_PN_CONV_LAYER_CBFC_R >> 4, 0, + RFCOMM_K_MAX, lcid, acl_handle)); + EXPECT_CALL(l2cap_interface_, DataWrite(lcid, BtHdrEqual(uih_pn_rsp_to_peer))) + .WillOnce(Return(tL2CAP_DW_RESULT::SUCCESS)); // uih_pn_cmd_from_peer should be freed by this method l2cap_appl_info_.pL2CA_DataInd_Cb(lcid, uih_pn_cmd_from_peer); osi_free(uih_pn_rsp_to_peer); @@ -210,85 +195,71 @@ class StackRfcommTest : public Test { tBTM_SEC_CALLBACK* security_callback = nullptr; void* p_port = nullptr; BT_HDR* sabm_channel_dlci = AllocateWrappedIncomingL2capAclPacket( - CreateQuickSabmPacket(GetDlci(false, scn), lcid, acl_handle)); + CreateQuickSabmPacket(GetDlci(false, scn), lcid, acl_handle)); EXPECT_CALL(btm_security_internal_interface_, - MultiplexingProtocolAccessRequest(peer_addr, BT_PSM_RFCOMM, - false, BTM_SEC_PROTO_RFCOMM, - scn, NotNull(), NotNull())) - .WillOnce(DoAll(SaveArg<5>(&security_callback), SaveArg<6>(&p_port), - Return(BTM_SUCCESS))); + MultiplexingProtocolAccessRequest(peer_addr, BT_PSM_RFCOMM, false, + BTM_SEC_PROTO_RFCOMM, scn, NotNull(), NotNull())) + .WillOnce(DoAll(SaveArg<5>(&security_callback), SaveArg<6>(&p_port), + Return(BTM_SUCCESS))); // sabm_channel_dlci should be freed by this method l2cap_appl_info_.pL2CA_DataInd_Cb(lcid, sabm_channel_dlci); log::verbose("Step 3"); // Confirm security check should trigger port as connected - EXPECT_CALL( - rfcomm_callback_, - PortManagementCallback(PORT_SUCCESS, port_handle, port_callback_index)); + EXPECT_CALL(rfcomm_callback_, + PortManagementCallback(PORT_SUCCESS, port_handle, port_callback_index)); BT_HDR* ua_channel_dlci = AllocateWrappedOutgoingL2capAclPacket( - CreateQuickUaPacket(GetDlci(false, scn), lcid, acl_handle)); + CreateQuickUaPacket(GetDlci(false, scn), lcid, acl_handle)); EXPECT_CALL(l2cap_interface_, DataWrite(lcid, BtHdrEqual(ua_channel_dlci))) - .WillOnce(Return(tL2CAP_DW_RESULT::SUCCESS)); + .WillOnce(Return(tL2CAP_DW_RESULT::SUCCESS)); ASSERT_TRUE(security_callback); security_callback(peer_addr, BT_TRANSPORT_BR_EDR, p_port, BTM_SUCCESS); osi_free(ua_channel_dlci); log::verbose("Step 4"); // Remote also need to configure its modem signal before we can send data - BT_HDR* uih_msc_cmd_from_peer = AllocateWrappedIncomingL2capAclPacket( - CreateQuickMscPacket(true, GetDlci(false, scn), lcid, acl_handle, true, - false, true, true, false, true)); - BT_HDR* uih_msc_response_to_peer = AllocateWrappedOutgoingL2capAclPacket( - CreateQuickMscPacket(false, GetDlci(false, scn), lcid, acl_handle, - false, false, true, true, false, true)); + BT_HDR* uih_msc_cmd_from_peer = AllocateWrappedIncomingL2capAclPacket(CreateQuickMscPacket( + true, GetDlci(false, scn), lcid, acl_handle, true, false, true, true, false, true)); + BT_HDR* uih_msc_response_to_peer = AllocateWrappedOutgoingL2capAclPacket(CreateQuickMscPacket( + false, GetDlci(false, scn), lcid, acl_handle, false, false, true, true, false, true)); // We also have to do modem configuration ourself - EXPECT_CALL(l2cap_interface_, - DataWrite(lcid, BtHdrEqual(uih_msc_response_to_peer))) - .WillOnce(Return(tL2CAP_DW_RESULT::SUCCESS)); - BT_HDR* uih_msc_cmd_to_peer = AllocateWrappedOutgoingL2capAclPacket( - CreateQuickMscPacket(false, GetDlci(false, scn), lcid, acl_handle, true, - false, true, true, false, true)); - EXPECT_CALL(l2cap_interface_, - DataWrite(lcid, BtHdrEqual(uih_msc_cmd_to_peer))) - .WillOnce(Return(tL2CAP_DW_RESULT::SUCCESS)); + EXPECT_CALL(l2cap_interface_, DataWrite(lcid, BtHdrEqual(uih_msc_response_to_peer))) + .WillOnce(Return(tL2CAP_DW_RESULT::SUCCESS)); + BT_HDR* uih_msc_cmd_to_peer = AllocateWrappedOutgoingL2capAclPacket(CreateQuickMscPacket( + false, GetDlci(false, scn), lcid, acl_handle, true, false, true, true, false, true)); + EXPECT_CALL(l2cap_interface_, DataWrite(lcid, BtHdrEqual(uih_msc_cmd_to_peer))) + .WillOnce(Return(tL2CAP_DW_RESULT::SUCCESS)); // uih_msc_cmd_from_peer should be freed by this method l2cap_appl_info_.pL2CA_DataInd_Cb(lcid, uih_msc_cmd_from_peer); osi_free(uih_msc_response_to_peer); log::verbose("Step 5"); // modem configuration is done - BT_HDR* uih_msc_response_from_peer = AllocateWrappedIncomingL2capAclPacket( - CreateQuickMscPacket(true, GetDlci(false, scn), lcid, acl_handle, false, - false, true, true, false, true)); + BT_HDR* uih_msc_response_from_peer = AllocateWrappedIncomingL2capAclPacket(CreateQuickMscPacket( + true, GetDlci(false, scn), lcid, acl_handle, false, false, true, true, false, true)); // uih_msc_response_from_peer should be freed by this method l2cap_appl_info_.pL2CA_DataInd_Cb(lcid, uih_msc_response_from_peer); } - void StartClientPort(const RawAddress& peer_bd_addr, uint16_t uuid, - uint8_t scn, uint16_t mtu, - tPORT_MGMT_CALLBACK* management_callback, - tPORT_CALLBACK* event_callback, uint16_t lcid, - uint16_t acl_handle, uint16_t* client_handle, + void StartClientPort(const RawAddress& peer_bd_addr, uint16_t uuid, uint8_t scn, uint16_t mtu, + tPORT_MGMT_CALLBACK* management_callback, tPORT_CALLBACK* event_callback, + uint16_t lcid, uint16_t acl_handle, uint16_t* client_handle, bool is_first_connection) { log::verbose("Step 1"); - BT_HDR* uih_pn_channel_3 = - AllocateWrappedOutgoingL2capAclPacket(CreateQuickPnPacket( - true, GetDlci(false, scn), true, mtu, RFCOMM_PN_CONV_LAYER_TYPE_1, - RFCOMM_PN_PRIORITY_0, RFCOMM_K, lcid, acl_handle)); + BT_HDR* uih_pn_channel_3 = AllocateWrappedOutgoingL2capAclPacket( + CreateQuickPnPacket(true, GetDlci(false, scn), true, mtu, RFCOMM_PN_CONV_LAYER_TYPE_1, + RFCOMM_PN_PRIORITY_0, RFCOMM_K, lcid, acl_handle)); if (is_first_connection) { EXPECT_CALL(l2cap_interface_, ConnectRequest(BT_PSM_RFCOMM, peer_bd_addr)) - .WillOnce(Return(lcid)); + .WillOnce(Return(lcid)); } else { - EXPECT_CALL(l2cap_interface_, - DataWrite(lcid, BtHdrEqual(uih_pn_channel_3))) - .WillOnce(Return(tL2CAP_DW_RESULT::SUCCESS)); + EXPECT_CALL(l2cap_interface_, DataWrite(lcid, BtHdrEqual(uih_pn_channel_3))) + .WillOnce(Return(tL2CAP_DW_RESULT::SUCCESS)); } - ASSERT_EQ(RFCOMM_CreateConnectionWithSecurity(uuid, scn, false, mtu, - peer_bd_addr, client_handle, - management_callback, 0), + ASSERT_EQ(RFCOMM_CreateConnectionWithSecurity(uuid, scn, false, mtu, peer_bd_addr, + client_handle, management_callback, 0), PORT_SUCCESS); - ASSERT_EQ(PORT_SetEventMaskAndCallback(*client_handle, PORT_EV_RXCHAR, - event_callback), + ASSERT_EQ(PORT_SetEventMaskAndCallback(*client_handle, PORT_EV_RXCHAR, event_callback), PORT_SUCCESS); osi_free(uih_pn_channel_3); } @@ -297,9 +268,8 @@ class StackRfcommTest : public Test { log::verbose("Step 1"); // Send configuration request when L2CAP connect is succsseful tL2CAP_CFG_INFO cfg_req = {.mtu_present = true, .mtu = L2CAP_MTU_SIZE}; - EXPECT_CALL(l2cap_interface_, - ConfigRequest(lcid, PointerMemoryEqual(&cfg_req))) - .WillOnce(Return(true)); + EXPECT_CALL(l2cap_interface_, ConfigRequest(lcid, PointerMemoryEqual(&cfg_req))) + .WillOnce(Return(true)); l2cap_appl_info_.pL2CA_ConnectCfm_Cb(lcid, L2CAP_CONN_OK); log::verbose("Step 2"); @@ -310,21 +280,19 @@ class StackRfcommTest : public Test { log::verbose("Step 3"); // Remote device also asks to configure MTU // Once configuration is done, we connect to multiplexer control channel 0 - EXPECT_CALL(l2cap_interface_, - ConfigResponse(lcid, PointerMemoryEqual(&cfg_req))) - .WillOnce(Return(true)); + EXPECT_CALL(l2cap_interface_, ConfigResponse(lcid, PointerMemoryEqual(&cfg_req))) + .WillOnce(Return(true)); // multiplexer control channel's DLCI is always 0 BT_HDR* sabm_channel_0 = AllocateWrappedOutgoingL2capAclPacket( - CreateQuickSabmPacket(RFCOMM_MX_DLCI, lcid, acl_handle)); + CreateQuickSabmPacket(RFCOMM_MX_DLCI, lcid, acl_handle)); EXPECT_CALL(l2cap_interface_, DataWrite(lcid, BtHdrEqual(sabm_channel_0))) - .WillOnce(Return(tL2CAP_DW_RESULT::SUCCESS)); + .WillOnce(Return(tL2CAP_DW_RESULT::SUCCESS)); l2cap_appl_info_.pL2CA_ConfigInd_Cb(lcid, &cfg_req); osi_free(sabm_channel_0); } - void ConnectClientPort(const RawAddress& peer_addr, uint16_t port_handle, - uint8_t scn, uint16_t mtu, uint16_t acl_handle, - uint16_t lcid, int port_callback_index, + void ConnectClientPort(const RawAddress& peer_addr, uint16_t port_handle, uint8_t scn, + uint16_t mtu, uint16_t acl_handle, uint16_t lcid, int port_callback_index, bool is_first_connection) { log::verbose("Step 1"); if (is_first_connection) { @@ -332,42 +300,36 @@ class StackRfcommTest : public Test { // Once remote accept multiplexer control channel 0 // We change to desired channel on non-initiating device (remote device) BT_HDR* ua_channel_0 = AllocateWrappedIncomingL2capAclPacket( - CreateQuickUaPacket(RFCOMM_MX_DLCI, lcid, acl_handle)); - BT_HDR* uih_pn_channel_3 = - AllocateWrappedOutgoingL2capAclPacket(CreateQuickPnPacket( - true, GetDlci(false, scn), true, mtu, - RFCOMM_PN_CONV_LAYER_CBFC_I >> 4, RFCOMM_PN_PRIORITY_0, - RFCOMM_K_MAX, lcid, acl_handle)); - EXPECT_CALL(l2cap_interface_, - DataWrite(lcid, BtHdrEqual(uih_pn_channel_3))) - .WillOnce(Return(tL2CAP_DW_RESULT::SUCCESS)); + CreateQuickUaPacket(RFCOMM_MX_DLCI, lcid, acl_handle)); + BT_HDR* uih_pn_channel_3 = AllocateWrappedOutgoingL2capAclPacket(CreateQuickPnPacket( + true, GetDlci(false, scn), true, mtu, RFCOMM_PN_CONV_LAYER_CBFC_I >> 4, + RFCOMM_PN_PRIORITY_0, RFCOMM_K_MAX, lcid, acl_handle)); + EXPECT_CALL(l2cap_interface_, DataWrite(lcid, BtHdrEqual(uih_pn_channel_3))) + .WillOnce(Return(tL2CAP_DW_RESULT::SUCCESS)); l2cap_appl_info_.pL2CA_DataInd_Cb(lcid, ua_channel_0); osi_free(uih_pn_channel_3); } log::verbose("Step 2"); // Once remote accept service channel change, we start security procedure - BT_HDR* uih_pn_channel_3_accept = - AllocateWrappedIncomingL2capAclPacket(CreateQuickPnPacket( - false, GetDlci(false, scn), false, mtu, - RFCOMM_PN_CONV_LAYER_CBFC_I >> 4, RFCOMM_PN_PRIORITY_0, - RFCOMM_K_MAX, lcid, acl_handle)); + BT_HDR* uih_pn_channel_3_accept = AllocateWrappedIncomingL2capAclPacket(CreateQuickPnPacket( + false, GetDlci(false, scn), false, mtu, RFCOMM_PN_CONV_LAYER_CBFC_I >> 4, + RFCOMM_PN_PRIORITY_0, RFCOMM_K_MAX, lcid, acl_handle)); tBTM_SEC_CALLBACK* security_callback = nullptr; void* p_port = nullptr; EXPECT_CALL(btm_security_internal_interface_, - MultiplexingProtocolAccessRequest(peer_addr, BT_PSM_RFCOMM, - true, BTM_SEC_PROTO_RFCOMM, - scn, NotNull(), NotNull())) - .WillOnce(DoAll(SaveArg<5>(&security_callback), SaveArg<6>(&p_port), - Return(BTM_SUCCESS))); + MultiplexingProtocolAccessRequest(peer_addr, BT_PSM_RFCOMM, true, + BTM_SEC_PROTO_RFCOMM, scn, NotNull(), NotNull())) + .WillOnce(DoAll(SaveArg<5>(&security_callback), SaveArg<6>(&p_port), + Return(BTM_SUCCESS))); l2cap_appl_info_.pL2CA_DataInd_Cb(lcid, uih_pn_channel_3_accept); log::verbose("Step 3"); // Once security procedure is done, we officially connect to target scn BT_HDR* sabm_channel_3 = AllocateWrappedOutgoingL2capAclPacket( - CreateQuickSabmPacket(GetDlci(false, scn), lcid, acl_handle)); + CreateQuickSabmPacket(GetDlci(false, scn), lcid, acl_handle)); EXPECT_CALL(l2cap_interface_, DataWrite(lcid, BtHdrEqual(sabm_channel_3))) - .WillOnce(Return(tL2CAP_DW_RESULT::SUCCESS)); + .WillOnce(Return(tL2CAP_DW_RESULT::SUCCESS)); ASSERT_TRUE(security_callback); security_callback(peer_addr, BT_TRANSPORT_BR_EDR, p_port, BTM_SUCCESS); osi_free(sabm_channel_3); @@ -375,71 +337,57 @@ class StackRfcommTest : public Test { log::verbose("Step 4"); // When target scn is accepted by remote, we need to configure modem signal // state beofre using the port - EXPECT_CALL( - rfcomm_callback_, - PortManagementCallback(PORT_SUCCESS, port_handle, port_callback_index)); - BT_HDR* uih_msc_cmd = AllocateWrappedOutgoingL2capAclPacket( - CreateQuickMscPacket(true, GetDlci(false, scn), lcid, acl_handle, true, - false, true, true, false, true)); + EXPECT_CALL(rfcomm_callback_, + PortManagementCallback(PORT_SUCCESS, port_handle, port_callback_index)); + BT_HDR* uih_msc_cmd = AllocateWrappedOutgoingL2capAclPacket(CreateQuickMscPacket( + true, GetDlci(false, scn), lcid, acl_handle, true, false, true, true, false, true)); EXPECT_CALL(l2cap_interface_, DataWrite(lcid, BtHdrEqual(uih_msc_cmd))) - .WillOnce(Return(tL2CAP_DW_RESULT::SUCCESS)); + .WillOnce(Return(tL2CAP_DW_RESULT::SUCCESS)); BT_HDR* ua_channel_3 = AllocateWrappedIncomingL2capAclPacket( - CreateQuickUaPacket(GetDlci(false, scn), lcid, acl_handle)); + CreateQuickUaPacket(GetDlci(false, scn), lcid, acl_handle)); l2cap_appl_info_.pL2CA_DataInd_Cb(lcid, ua_channel_3); osi_free(uih_msc_cmd); log::verbose("Step 5"); // modem configuration is done - BT_HDR* uih_msc_response = AllocateWrappedIncomingL2capAclPacket( - CreateQuickMscPacket(false, GetDlci(false, scn), lcid, acl_handle, - false, false, true, true, false, true)); + BT_HDR* uih_msc_response = AllocateWrappedIncomingL2capAclPacket(CreateQuickMscPacket( + false, GetDlci(false, scn), lcid, acl_handle, false, false, true, true, false, true)); l2cap_appl_info_.pL2CA_DataInd_Cb(lcid, uih_msc_response); log::verbose("Step 6"); // Remote also need to configure its modem signal before we can send data - BT_HDR* uih_msc_cmd_from_peer = AllocateWrappedIncomingL2capAclPacket( - CreateQuickMscPacket(false, GetDlci(false, scn), lcid, acl_handle, true, - false, true, true, false, true)); - BT_HDR* uih_msc_response_to_peer = AllocateWrappedOutgoingL2capAclPacket( - CreateQuickMscPacket(true, GetDlci(false, scn), lcid, acl_handle, false, - false, true, true, false, true)); - EXPECT_CALL(l2cap_interface_, - DataWrite(lcid, BtHdrEqual(uih_msc_response_to_peer))) - .WillOnce(Return(tL2CAP_DW_RESULT::SUCCESS)); + BT_HDR* uih_msc_cmd_from_peer = AllocateWrappedIncomingL2capAclPacket(CreateQuickMscPacket( + false, GetDlci(false, scn), lcid, acl_handle, true, false, true, true, false, true)); + BT_HDR* uih_msc_response_to_peer = AllocateWrappedOutgoingL2capAclPacket(CreateQuickMscPacket( + true, GetDlci(false, scn), lcid, acl_handle, false, false, true, true, false, true)); + EXPECT_CALL(l2cap_interface_, DataWrite(lcid, BtHdrEqual(uih_msc_response_to_peer))) + .WillOnce(Return(tL2CAP_DW_RESULT::SUCCESS)); l2cap_appl_info_.pL2CA_DataInd_Cb(lcid, uih_msc_cmd_from_peer); osi_free(uih_msc_response_to_peer); } - void SendAndVerifyOutgoingTransmission(uint16_t port_handle, - bool is_initiator, uint8_t scn, - bool cr, const std::string& message, - int credits, uint16_t acl_handle, - uint16_t lcid) { + void SendAndVerifyOutgoingTransmission(uint16_t port_handle, bool is_initiator, uint8_t scn, + bool cr, const std::string& message, int credits, + uint16_t acl_handle, uint16_t lcid) { log::verbose("Step 1"); - BT_HDR* data_packet = AllocateWrappedOutgoingL2capAclPacket( - CreateQuickDataPacket(GetDlci(is_initiator, scn), cr, lcid, acl_handle, - credits, message)); + BT_HDR* data_packet = AllocateWrappedOutgoingL2capAclPacket(CreateQuickDataPacket( + GetDlci(is_initiator, scn), cr, lcid, acl_handle, credits, message)); uint16_t transmitted_length = 0; EXPECT_CALL(l2cap_interface_, DataWrite(lcid, BtHdrEqual(data_packet))) - .WillOnce(Return(tL2CAP_DW_RESULT::SUCCESS)); - ASSERT_EQ(PORT_WriteData(port_handle, message.data(), message.size(), - &transmitted_length), + .WillOnce(Return(tL2CAP_DW_RESULT::SUCCESS)); + ASSERT_EQ(PORT_WriteData(port_handle, message.data(), message.size(), &transmitted_length), PORT_SUCCESS); ASSERT_EQ(transmitted_length, message.size()); } - void ReceiveAndVerifyIncomingTransmission(uint16_t port_handle, - bool is_initiator, uint8_t scn, - bool cr, const std::string& message, - int credits, uint16_t acl_handle, - uint16_t lcid, + void ReceiveAndVerifyIncomingTransmission(uint16_t port_handle, bool is_initiator, uint8_t scn, + bool cr, const std::string& message, int credits, + uint16_t acl_handle, uint16_t lcid, int port_callback_index) { log::verbose("Step 1"); - BT_HDR* data_packet = AllocateWrappedIncomingL2capAclPacket( - CreateQuickDataPacket(GetDlci(is_initiator, scn), cr, lcid, acl_handle, - credits, message)); - EXPECT_CALL(rfcomm_callback_, - PortEventCallback(_, port_handle, port_callback_index)); + BT_HDR* data_packet = AllocateWrappedIncomingL2capAclPacket(CreateQuickDataPacket( + GetDlci(is_initiator, scn), cr, lcid, acl_handle, credits, message)); + EXPECT_CALL(rfcomm_callback_, PortEventCallback(_, port_handle, port_callback_index)); l2cap_appl_info_.pL2CA_DataInd_Cb(lcid, data_packet); log::verbose("Step 2"); @@ -450,15 +398,13 @@ class StackRfcommTest : public Test { ASSERT_THAT(buffer, StrEq(message)); } - protected: +protected: void SetUp() override { Test::SetUp(); - bluetooth::manager::SetMockSecurityInternalInterface( - &btm_security_internal_interface_); + bluetooth::manager::SetMockSecurityInternalInterface(&btm_security_internal_interface_); bluetooth::l2cap::SetMockInterface(&l2cap_interface_); rfcomm_callback = &rfcomm_callback_; - EXPECT_CALL(l2cap_interface_, Register(BT_PSM_RFCOMM, _, _, _)) - .WillOnce(Return(BT_PSM_RFCOMM)); + EXPECT_CALL(l2cap_interface_, Register(BT_PSM_RFCOMM, _, _, _)).WillOnce(Return(BT_PSM_RFCOMM)); RFCOMM_Init(); } @@ -468,8 +414,7 @@ class StackRfcommTest : public Test { bluetooth::manager::SetMockSecurityInternalInterface(nullptr); testing::Test::TearDown(); } - StrictMock - btm_security_internal_interface_; + StrictMock btm_security_internal_interface_; StrictMock l2cap_interface_; StrictMock rfcomm_callback_; tL2CAP_APPL_INFO l2cap_appl_info_; @@ -484,18 +429,15 @@ TEST_F(StackRfcommTest, DISABLED_SingleServerConnectionHelloWorld) { static const uint16_t test_mtu = 1600; static const RawAddress test_address = GetTestAddress(0); uint16_t server_handle = 0; - ASSERT_NO_FATAL_FAILURE(StartServerPort(test_uuid, test_scn, test_mtu, - port_mgmt_cback_0, port_event_cback_0, - &server_handle)); + ASSERT_NO_FATAL_FAILURE(StartServerPort(test_uuid, test_scn, test_mtu, port_mgmt_cback_0, + port_event_cback_0, &server_handle)); ASSERT_NO_FATAL_FAILURE(ConnectServerL2cap(test_address, acl_handle, lcid)); - ASSERT_NO_FATAL_FAILURE(ConnectServerPort( - test_address, server_handle, test_scn, test_mtu, acl_handle, lcid, 0)); - ASSERT_NO_FATAL_FAILURE(ReceiveAndVerifyIncomingTransmission( - server_handle, false, test_scn, true, "Hello World!\r", 50, acl_handle, - lcid, 0)); ASSERT_NO_FATAL_FAILURE( - SendAndVerifyOutgoingTransmission(server_handle, false, test_scn, false, - "\r!dlroW olleH", 4, acl_handle, lcid)); + ConnectServerPort(test_address, server_handle, test_scn, test_mtu, acl_handle, lcid, 0)); + ASSERT_NO_FATAL_FAILURE(ReceiveAndVerifyIncomingTransmission( + server_handle, false, test_scn, true, "Hello World!\r", 50, acl_handle, lcid, 0)); + ASSERT_NO_FATAL_FAILURE(SendAndVerifyOutgoingTransmission(server_handle, false, test_scn, false, + "\r!dlroW olleH", 4, acl_handle, lcid)); } TEST_F(StackRfcommTest, DISABLED_MultiServerPortSameDeviceHelloWorld) { @@ -509,13 +451,11 @@ TEST_F(StackRfcommTest, DISABLED_MultiServerPortSameDeviceHelloWorld) { uint16_t server_handle_0 = 0; static const uint8_t test_scn_0 = 8; static const uint16_t test_uuid_0 = 0x1112; - ASSERT_NO_FATAL_FAILURE(StartServerPort(test_uuid_0, test_scn_0, test_mtu, - port_mgmt_cback_0, port_event_cback_0, - &server_handle_0)); + ASSERT_NO_FATAL_FAILURE(StartServerPort(test_uuid_0, test_scn_0, test_mtu, port_mgmt_cback_0, + port_event_cback_0, &server_handle_0)); ASSERT_NO_FATAL_FAILURE(ConnectServerL2cap(test_address, acl_handle, lcid)); - ASSERT_NO_FATAL_FAILURE(ConnectServerPort(test_address, server_handle_0, - test_scn_0, test_mtu, acl_handle, - lcid, 0)); + ASSERT_NO_FATAL_FAILURE(ConnectServerPort(test_address, server_handle_0, test_scn_0, test_mtu, + acl_handle, lcid, 0)); // Service 1 uint16_t server_handle_1 = 0; @@ -523,28 +463,22 @@ TEST_F(StackRfcommTest, DISABLED_MultiServerPortSameDeviceHelloWorld) { static const uint16_t test_uuid_1 = 0x111F; ASSERT_NE(test_scn_1, test_scn_0); ASSERT_NE(test_uuid_1, test_uuid_0); - ASSERT_NO_FATAL_FAILURE(StartServerPort(test_uuid_1, test_scn_1, test_mtu, - port_mgmt_cback_1, port_event_cback_1, - &server_handle_1)); + ASSERT_NO_FATAL_FAILURE(StartServerPort(test_uuid_1, test_scn_1, test_mtu, port_mgmt_cback_1, + port_event_cback_1, &server_handle_1)); // No L2CAP setup for 2nd device - ASSERT_NO_FATAL_FAILURE(ConnectServerPort(test_address, server_handle_1, - test_scn_1, test_mtu, acl_handle, - lcid, 1)); + ASSERT_NO_FATAL_FAILURE(ConnectServerPort(test_address, server_handle_1, test_scn_1, test_mtu, + acl_handle, lcid, 1)); // Use service 0 ASSERT_NO_FATAL_FAILURE(ReceiveAndVerifyIncomingTransmission( - server_handle_0, false, test_scn_0, true, "Hello World0!\r", 50, - acl_handle, lcid, 0)); + server_handle_0, false, test_scn_0, true, "Hello World0!\r", 50, acl_handle, lcid, 0)); ASSERT_NO_FATAL_FAILURE(SendAndVerifyOutgoingTransmission( - server_handle_0, false, test_scn_0, false, "\r!0dlroW olleH", 4, - acl_handle, lcid)); + server_handle_0, false, test_scn_0, false, "\r!0dlroW olleH", 4, acl_handle, lcid)); // Use service 1 ASSERT_NO_FATAL_FAILURE(ReceiveAndVerifyIncomingTransmission( - server_handle_1, false, test_scn_1, true, "Hello World1!\r", 50, - acl_handle, lcid, 1)); + server_handle_1, false, test_scn_1, true, "Hello World1!\r", 50, acl_handle, lcid, 1)); ASSERT_NO_FATAL_FAILURE(SendAndVerifyOutgoingTransmission( - server_handle_1, false, test_scn_1, false, "\r!1dlroW olleH", 4, - acl_handle, lcid)); + server_handle_1, false, test_scn_1, false, "\r!1dlroW olleH", 4, acl_handle, lcid)); } TEST_F(StackRfcommTest, DISABLED_SameServerPortMultiDeviceHelloWorld) { @@ -558,43 +492,33 @@ TEST_F(StackRfcommTest, DISABLED_SameServerPortMultiDeviceHelloWorld) { static const uint16_t acl_handle_0 = 0x0009; static const uint16_t lcid_0 = 0x0054; uint16_t server_handle_0 = 0; - ASSERT_NO_FATAL_FAILURE(StartServerPort(test_uuid, test_scn, test_mtu, - port_mgmt_cback_0, port_event_cback_0, - &server_handle_0)); - ASSERT_NO_FATAL_FAILURE( - ConnectServerL2cap(test_address_0, acl_handle_0, lcid_0)); - ASSERT_NO_FATAL_FAILURE(ConnectServerPort(test_address_0, server_handle_0, - test_scn, test_mtu, acl_handle_0, - lcid_0, 0)); + ASSERT_NO_FATAL_FAILURE(StartServerPort(test_uuid, test_scn, test_mtu, port_mgmt_cback_0, + port_event_cback_0, &server_handle_0)); + ASSERT_NO_FATAL_FAILURE(ConnectServerL2cap(test_address_0, acl_handle_0, lcid_0)); + ASSERT_NO_FATAL_FAILURE(ConnectServerPort(test_address_0, server_handle_0, test_scn, test_mtu, + acl_handle_0, lcid_0, 0)); // Service 1 static const RawAddress test_address_1 = GetTestAddress(1); static const uint16_t acl_handle_1 = 0x0012; static const uint16_t lcid_1 = 0x0045; uint16_t server_handle_1 = 0; - ASSERT_NO_FATAL_FAILURE(StartServerPort(test_uuid, test_scn, test_mtu, - port_mgmt_cback_1, port_event_cback_1, - &server_handle_1)); - ASSERT_NO_FATAL_FAILURE( - ConnectServerL2cap(test_address_1, acl_handle_1, lcid_1)); - ASSERT_NO_FATAL_FAILURE(ConnectServerPort(test_address_1, server_handle_1, - test_scn, test_mtu, acl_handle_1, - lcid_1, 1)); + ASSERT_NO_FATAL_FAILURE(StartServerPort(test_uuid, test_scn, test_mtu, port_mgmt_cback_1, + port_event_cback_1, &server_handle_1)); + ASSERT_NO_FATAL_FAILURE(ConnectServerL2cap(test_address_1, acl_handle_1, lcid_1)); + ASSERT_NO_FATAL_FAILURE(ConnectServerPort(test_address_1, server_handle_1, test_scn, test_mtu, + acl_handle_1, lcid_1, 1)); // Use service 0 ASSERT_NO_FATAL_FAILURE(ReceiveAndVerifyIncomingTransmission( - server_handle_0, false, test_scn, true, "Hello World0!\r", 50, - acl_handle_0, lcid_0, 0)); + server_handle_0, false, test_scn, true, "Hello World0!\r", 50, acl_handle_0, lcid_0, 0)); ASSERT_NO_FATAL_FAILURE(SendAndVerifyOutgoingTransmission( - server_handle_0, false, test_scn, false, "\r!0dlroW olleH", 4, - acl_handle_0, lcid_0)); + server_handle_0, false, test_scn, false, "\r!0dlroW olleH", 4, acl_handle_0, lcid_0)); // Use service 1 ASSERT_NO_FATAL_FAILURE(ReceiveAndVerifyIncomingTransmission( - server_handle_1, false, test_scn, true, "Hello World1!\r", 50, - acl_handle_1, lcid_1, 1)); + server_handle_1, false, test_scn, true, "Hello World1!\r", 50, acl_handle_1, lcid_1, 1)); ASSERT_NO_FATAL_FAILURE(SendAndVerifyOutgoingTransmission( - server_handle_1, false, test_scn, false, "\r!1dlroW olleH", 4, - acl_handle_1, lcid_1)); + server_handle_1, false, test_scn, false, "\r!1dlroW olleH", 4, acl_handle_1, lcid_1)); } TEST_F(StackRfcommTest, DISABLED_SingleClientConnectionHelloWorld) { @@ -605,19 +529,16 @@ TEST_F(StackRfcommTest, DISABLED_SingleClientConnectionHelloWorld) { static const uint16_t test_mtu = 1600; static const RawAddress test_address = GetTestAddress(0); uint16_t client_handle = 0; - ASSERT_NO_FATAL_FAILURE(StartClientPort( - test_address, test_uuid, test_scn, test_mtu, port_mgmt_cback_0, - port_event_cback_0, lcid, acl_handle, &client_handle, true)); + ASSERT_NO_FATAL_FAILURE(StartClientPort(test_address, test_uuid, test_scn, test_mtu, + port_mgmt_cback_0, port_event_cback_0, lcid, acl_handle, + &client_handle, true)); ASSERT_NO_FATAL_FAILURE(TestConnectClientPortL2cap(acl_handle, lcid)); - ASSERT_NO_FATAL_FAILURE(ConnectClientPort(test_address, client_handle, - test_scn, test_mtu, acl_handle, - lcid, 0, true)); + ASSERT_NO_FATAL_FAILURE(ConnectClientPort(test_address, client_handle, test_scn, test_mtu, + acl_handle, lcid, 0, true)); ASSERT_NO_FATAL_FAILURE(SendAndVerifyOutgoingTransmission( - client_handle, false, test_scn, true, "\r!dlroW olleH", -1, acl_handle, - lcid)); + client_handle, false, test_scn, true, "\r!dlroW olleH", -1, acl_handle, lcid)); ASSERT_NO_FATAL_FAILURE(ReceiveAndVerifyIncomingTransmission( - client_handle, false, test_scn, false, "Hello World!\r", -1, acl_handle, - lcid, 0)); + client_handle, false, test_scn, false, "Hello World!\r", -1, acl_handle, lcid, 0)); } TEST_F(StackRfcommTest, DISABLED_MultiClientPortSameDeviceHelloWorld) { @@ -630,40 +551,34 @@ TEST_F(StackRfcommTest, DISABLED_MultiClientPortSameDeviceHelloWorld) { static const uint16_t test_uuid_0 = 0x1112; static const uint8_t test_scn_0 = 8; uint16_t client_handle_0 = 0; - ASSERT_NO_FATAL_FAILURE(StartClientPort( - test_address, test_uuid_0, test_scn_0, test_mtu, port_mgmt_cback_0, - port_event_cback_0, lcid, acl_handle, &client_handle_0, true)); + ASSERT_NO_FATAL_FAILURE(StartClientPort(test_address, test_uuid_0, test_scn_0, test_mtu, + port_mgmt_cback_0, port_event_cback_0, lcid, acl_handle, + &client_handle_0, true)); ASSERT_NO_FATAL_FAILURE(TestConnectClientPortL2cap(acl_handle, lcid)); - ASSERT_NO_FATAL_FAILURE(ConnectClientPort(test_address, client_handle_0, - test_scn_0, test_mtu, acl_handle, - lcid, 0, true)); + ASSERT_NO_FATAL_FAILURE(ConnectClientPort(test_address, client_handle_0, test_scn_0, test_mtu, + acl_handle, lcid, 0, true)); // Connection 1 static const uint16_t test_uuid_1 = 0x111F; static const uint8_t test_scn_1 = 10; uint16_t client_handle_1 = 0; - ASSERT_NO_FATAL_FAILURE(StartClientPort( - test_address, test_uuid_1, test_scn_1, test_mtu, port_mgmt_cback_1, - port_event_cback_1, lcid, acl_handle, &client_handle_1, false)); - ASSERT_NO_FATAL_FAILURE(ConnectClientPort(test_address, client_handle_1, - test_scn_1, test_mtu, acl_handle, - lcid, 1, false)); + ASSERT_NO_FATAL_FAILURE(StartClientPort(test_address, test_uuid_1, test_scn_1, test_mtu, + port_mgmt_cback_1, port_event_cback_1, lcid, acl_handle, + &client_handle_1, false)); + ASSERT_NO_FATAL_FAILURE(ConnectClientPort(test_address, client_handle_1, test_scn_1, test_mtu, + acl_handle, lcid, 1, false)); // Use connection 0 ASSERT_NO_FATAL_FAILURE(SendAndVerifyOutgoingTransmission( - client_handle_0, false, test_scn_0, true, "\r!dlroW olleH", -1, - acl_handle, lcid)); + client_handle_0, false, test_scn_0, true, "\r!dlroW olleH", -1, acl_handle, lcid)); ASSERT_NO_FATAL_FAILURE(ReceiveAndVerifyIncomingTransmission( - client_handle_0, false, test_scn_0, false, "Hello World!\r", -1, - acl_handle, lcid, 0)); + client_handle_0, false, test_scn_0, false, "Hello World!\r", -1, acl_handle, lcid, 0)); // Use connection 1 ASSERT_NO_FATAL_FAILURE(SendAndVerifyOutgoingTransmission( - client_handle_1, false, test_scn_1, true, "\r!dlroW olleH", -1, - acl_handle, lcid)); + client_handle_1, false, test_scn_1, true, "\r!dlroW olleH", -1, acl_handle, lcid)); ASSERT_NO_FATAL_FAILURE(ReceiveAndVerifyIncomingTransmission( - client_handle_1, false, test_scn_1, false, "Hello World!\r", -1, - acl_handle, lcid, 1)); + client_handle_1, false, test_scn_1, false, "Hello World!\r", -1, acl_handle, lcid, 1)); } TEST_F(StackRfcommTest, DISABLED_SameClientPortMultiDeviceHelloWorld) { @@ -676,42 +591,36 @@ TEST_F(StackRfcommTest, DISABLED_SameClientPortMultiDeviceHelloWorld) { static const uint16_t acl_handle_0 = 0x0009; static const uint16_t lcid_0 = 0x0054; uint16_t client_handle_0 = 0; - ASSERT_NO_FATAL_FAILURE(StartClientPort( - test_address_0, test_uuid, test_scn, test_mtu, port_mgmt_cback_0, - port_event_cback_0, lcid_0, acl_handle_0, &client_handle_0, true)); + ASSERT_NO_FATAL_FAILURE(StartClientPort(test_address_0, test_uuid, test_scn, test_mtu, + port_mgmt_cback_0, port_event_cback_0, lcid_0, + acl_handle_0, &client_handle_0, true)); ASSERT_NO_FATAL_FAILURE(TestConnectClientPortL2cap(acl_handle_0, lcid_0)); - ASSERT_NO_FATAL_FAILURE(ConnectClientPort(test_address_0, client_handle_0, - test_scn, test_mtu, acl_handle_0, - lcid_0, 0, true)); + ASSERT_NO_FATAL_FAILURE(ConnectClientPort(test_address_0, client_handle_0, test_scn, test_mtu, + acl_handle_0, lcid_0, 0, true)); // Connection 1 static const RawAddress test_address_1 = GetTestAddress(1); static const uint16_t acl_handle_1 = 0x0012; static const uint16_t lcid_1 = 0x0045; uint16_t client_handle_1 = 0; - ASSERT_NO_FATAL_FAILURE(StartClientPort( - test_address_1, test_uuid, test_scn, test_mtu, port_mgmt_cback_1, - port_event_cback_1, lcid_1, acl_handle_1, &client_handle_1, true)); + ASSERT_NO_FATAL_FAILURE(StartClientPort(test_address_1, test_uuid, test_scn, test_mtu, + port_mgmt_cback_1, port_event_cback_1, lcid_1, + acl_handle_1, &client_handle_1, true)); ASSERT_NO_FATAL_FAILURE(TestConnectClientPortL2cap(acl_handle_1, lcid_1)); - ASSERT_NO_FATAL_FAILURE(ConnectClientPort(test_address_1, client_handle_1, - test_scn, test_mtu, acl_handle_1, - lcid_1, 1, true)); + ASSERT_NO_FATAL_FAILURE(ConnectClientPort(test_address_1, client_handle_1, test_scn, test_mtu, + acl_handle_1, lcid_1, 1, true)); // Use connection 0 ASSERT_NO_FATAL_FAILURE(SendAndVerifyOutgoingTransmission( - client_handle_0, false, test_scn, true, "\r!dlroW olleH", -1, - acl_handle_0, lcid_0)); + client_handle_0, false, test_scn, true, "\r!dlroW olleH", -1, acl_handle_0, lcid_0)); ASSERT_NO_FATAL_FAILURE(ReceiveAndVerifyIncomingTransmission( - client_handle_0, false, test_scn, false, "Hello World!\r", -1, - acl_handle_0, lcid_0, 0)); + client_handle_0, false, test_scn, false, "Hello World!\r", -1, acl_handle_0, lcid_0, 0)); // Use connection 1 ASSERT_NO_FATAL_FAILURE(SendAndVerifyOutgoingTransmission( - client_handle_1, false, test_scn, true, "\r!dlroW olleH", -1, - acl_handle_1, lcid_1)); + client_handle_1, false, test_scn, true, "\r!dlroW olleH", -1, acl_handle_1, lcid_1)); ASSERT_NO_FATAL_FAILURE(ReceiveAndVerifyIncomingTransmission( - client_handle_1, false, test_scn, false, "Hello World!\r", -1, - acl_handle_1, lcid_1, 1)); + client_handle_1, false, test_scn, false, "Hello World!\r", -1, acl_handle_1, lcid_1, 1)); } TEST_F(StackRfcommTest, DISABLED_TestConnectionCollision) { @@ -727,26 +636,24 @@ TEST_F(StackRfcommTest, DISABLED_TestConnectionCollision) { uint16_t server_handle = 0; log::verbose("Step 1"); // Prepare a server port - int status = RFCOMM_CreateConnectionWithSecurity( - test_uuid, test_server_scn, true, test_mtu, RawAddress::kAny, - &server_handle, port_mgmt_cback_0, 0); + int status = RFCOMM_CreateConnectionWithSecurity(test_uuid, test_server_scn, true, test_mtu, + RawAddress::kAny, &server_handle, + port_mgmt_cback_0, 0); ASSERT_EQ(status, PORT_SUCCESS); - status = PORT_SetEventMaskAndCallback(server_handle, PORT_EV_RXCHAR, - port_event_cback_0); + status = PORT_SetEventMaskAndCallback(server_handle, PORT_EV_RXCHAR, port_event_cback_0); ASSERT_EQ(status, PORT_SUCCESS); log::verbose("Step 2"); // Try to connect to a client port uint16_t client_handle_1 = 0; EXPECT_CALL(l2cap_interface_, ConnectRequest(BT_PSM_RFCOMM, test_address)) - .Times(1) - .WillOnce(Return(old_lcid)); - status = RFCOMM_CreateConnectionWithSecurity( - test_uuid, test_peer_scn, false, test_mtu, test_address, &client_handle_1, - port_mgmt_cback_1, 0); + .Times(1) + .WillOnce(Return(old_lcid)); + status = + RFCOMM_CreateConnectionWithSecurity(test_uuid, test_peer_scn, false, test_mtu, + test_address, &client_handle_1, port_mgmt_cback_1, 0); ASSERT_EQ(status, PORT_SUCCESS); - status = PORT_SetEventMaskAndCallback(client_handle_1, PORT_EV_RXCHAR, - port_event_cback_1); + status = PORT_SetEventMaskAndCallback(client_handle_1, PORT_EV_RXCHAR, port_event_cback_1); ASSERT_EQ(status, PORT_SUCCESS); log::verbose("Step 3"); @@ -754,31 +661,27 @@ TEST_F(StackRfcommTest, DISABLED_TestConnectionCollision) { // new_lcid, with L2CAP command id: pending_cmd_id static const uint8_t pending_cmd_id = 0x05; // RFCOMM starts timer for collision: - l2cap_appl_info_.pL2CA_ConnectInd_Cb(test_address, new_lcid, BT_PSM_RFCOMM, - pending_cmd_id); + l2cap_appl_info_.pL2CA_ConnectInd_Cb(test_address, new_lcid, BT_PSM_RFCOMM, pending_cmd_id); log::verbose("Step 4"); // Remote reject our connection request saying PSM not allowed // This should trigger RFCOMM to accept remote L2CAP connection at new_lcid - EXPECT_CALL(l2cap_interface_, ConnectResponse(test_address, pending_cmd_id, - new_lcid, L2CAP_CONN_OK, 0)) - .WillOnce(Return(true)); + EXPECT_CALL(l2cap_interface_, + ConnectResponse(test_address, pending_cmd_id, new_lcid, L2CAP_CONN_OK, 0)) + .WillOnce(Return(true)); // Followed by configure request for MTU size tL2CAP_CFG_INFO our_cfg_req = {.mtu_present = true, .mtu = L2CAP_MTU_SIZE}; - EXPECT_CALL(l2cap_interface_, - ConfigRequest(new_lcid, PointerMemoryEqual(&our_cfg_req))) - .WillOnce(Return(true)); + EXPECT_CALL(l2cap_interface_, ConfigRequest(new_lcid, PointerMemoryEqual(&our_cfg_req))) + .WillOnce(Return(true)); l2cap_appl_info_.pL2CA_ConnectCfm_Cb(old_lcid, L2CAP_CONN_NO_PSM); log::verbose("Step 5"); // Remote device also ask to configure MTU size as well tL2CAP_CFG_INFO peer_cfg_req = {.mtu_present = true, .mtu = test_mtu}; // We responded by saying OK - tL2CAP_CFG_INFO our_cfg_rsp = {.result = L2CAP_CFG_OK, - .mtu = peer_cfg_req.mtu}; - EXPECT_CALL(l2cap_interface_, - ConfigResponse(new_lcid, PointerMemoryEqual(&our_cfg_rsp))) - .WillOnce(Return(true)); + tL2CAP_CFG_INFO our_cfg_rsp = {.result = L2CAP_CFG_OK, .mtu = peer_cfg_req.mtu}; + EXPECT_CALL(l2cap_interface_, ConfigResponse(new_lcid, PointerMemoryEqual(&our_cfg_rsp))) + .WillOnce(Return(true)); l2cap_appl_info_.pL2CA_ConfigInd_Cb(new_lcid, &peer_cfg_req); log::verbose("Step 6"); @@ -790,20 +693,18 @@ TEST_F(StackRfcommTest, DISABLED_TestConnectionCollision) { log::verbose("Step 7"); // Remote device connect multiplexer channel BT_HDR* sabm_channel_0 = AllocateWrappedIncomingL2capAclPacket( - CreateQuickSabmPacket(RFCOMM_MX_DLCI, new_lcid, acl_handle)); + CreateQuickSabmPacket(RFCOMM_MX_DLCI, new_lcid, acl_handle)); // We accept BT_HDR* ua_channel_0 = AllocateWrappedOutgoingL2capAclPacket( - CreateQuickUaPacket(RFCOMM_MX_DLCI, new_lcid, acl_handle)); + CreateQuickUaPacket(RFCOMM_MX_DLCI, new_lcid, acl_handle)); EXPECT_CALL(l2cap_interface_, DataWrite(new_lcid, BtHdrEqual(ua_channel_0))) - .WillOnce(Return(tL2CAP_DW_RESULT::SUCCESS)); + .WillOnce(Return(tL2CAP_DW_RESULT::SUCCESS)); // And immediately try to configure test_peer_scn - BT_HDR* uih_pn_cmd_to_peer = AllocateWrappedOutgoingL2capAclPacket( - CreateQuickPnPacket(false, GetDlci(true, test_peer_scn), true, test_mtu, - RFCOMM_PN_CONV_LAYER_CBFC_I >> 4, 0, RFCOMM_K_MAX, - new_lcid, acl_handle)); - EXPECT_CALL(l2cap_interface_, - DataWrite(new_lcid, BtHdrEqual(uih_pn_cmd_to_peer))) - .WillOnce(Return(tL2CAP_DW_RESULT::SUCCESS)); + BT_HDR* uih_pn_cmd_to_peer = AllocateWrappedOutgoingL2capAclPacket(CreateQuickPnPacket( + false, GetDlci(true, test_peer_scn), true, test_mtu, RFCOMM_PN_CONV_LAYER_CBFC_I >> 4, 0, + RFCOMM_K_MAX, new_lcid, acl_handle)); + EXPECT_CALL(l2cap_interface_, DataWrite(new_lcid, BtHdrEqual(uih_pn_cmd_to_peer))) + .WillOnce(Return(tL2CAP_DW_RESULT::SUCCESS)); // Packet should be freed by this method l2cap_appl_info_.pL2CA_DataInd_Cb(new_lcid, sabm_channel_0); osi_free(ua_channel_0); @@ -811,80 +712,72 @@ TEST_F(StackRfcommTest, DISABLED_TestConnectionCollision) { log::verbose("Step 8"); // Peer tries to configure test_server_scn - BT_HDR* uih_pn_cmd_from_peer = AllocateWrappedIncomingL2capAclPacket( - CreateQuickPnPacket(true, GetDlci(false, test_server_scn), true, test_mtu, - RFCOMM_PN_CONV_LAYER_CBFC_I >> 4, 0, RFCOMM_K_MAX, - new_lcid, acl_handle)); + BT_HDR* uih_pn_cmd_from_peer = AllocateWrappedIncomingL2capAclPacket(CreateQuickPnPacket( + true, GetDlci(false, test_server_scn), true, test_mtu, RFCOMM_PN_CONV_LAYER_CBFC_I >> 4, + 0, RFCOMM_K_MAX, new_lcid, acl_handle)); // We, as acceptor, must accept - BT_HDR* uih_pn_rsp_to_peer = AllocateWrappedOutgoingL2capAclPacket( - CreateQuickPnPacket(false, GetDlci(false, test_server_scn), false, - test_mtu, RFCOMM_PN_CONV_LAYER_CBFC_R >> 4, 0, - RFCOMM_K_MAX, new_lcid, acl_handle)); - EXPECT_CALL(l2cap_interface_, - DataWrite(new_lcid, BtHdrEqual(uih_pn_rsp_to_peer))) - .Times(1) - .WillOnce(Return(tL2CAP_DW_RESULT::SUCCESS)); + BT_HDR* uih_pn_rsp_to_peer = AllocateWrappedOutgoingL2capAclPacket(CreateQuickPnPacket( + false, GetDlci(false, test_server_scn), false, test_mtu, RFCOMM_PN_CONV_LAYER_CBFC_R >> 4, + 0, RFCOMM_K_MAX, new_lcid, acl_handle)); + EXPECT_CALL(l2cap_interface_, DataWrite(new_lcid, BtHdrEqual(uih_pn_rsp_to_peer))) + .Times(1) + .WillOnce(Return(tL2CAP_DW_RESULT::SUCCESS)); l2cap_appl_info_.pL2CA_DataInd_Cb(new_lcid, uih_pn_cmd_from_peer); osi_free(uih_pn_rsp_to_peer); log::verbose("Step 9"); // Remote never replies our configuration request for test_peer_scn // But instead connect to test_server_scn directly - BT_HDR* sabm_server_scn = - AllocateWrappedIncomingL2capAclPacket(CreateQuickSabmPacket( - GetDlci(false, test_server_scn), new_lcid, acl_handle)); + BT_HDR* sabm_server_scn = AllocateWrappedIncomingL2capAclPacket( + CreateQuickSabmPacket(GetDlci(false, test_server_scn), new_lcid, acl_handle)); // We must do security check first tBTM_SEC_CALLBACK* security_callback = nullptr; void* p_port = nullptr; EXPECT_CALL(btm_security_internal_interface_, - MultiplexingProtocolAccessRequest( - test_address, BT_PSM_RFCOMM, false, BTM_SEC_PROTO_RFCOMM, - test_server_scn, NotNull(), NotNull())) - .WillOnce(DoAll(SaveArg<5>(&security_callback), SaveArg<6>(&p_port), - Return(BTM_SUCCESS))); + MultiplexingProtocolAccessRequest(test_address, BT_PSM_RFCOMM, false, + BTM_SEC_PROTO_RFCOMM, test_server_scn, NotNull(), + NotNull())) + .WillOnce( + DoAll(SaveArg<5>(&security_callback), SaveArg<6>(&p_port), Return(BTM_SUCCESS))); l2cap_appl_info_.pL2CA_DataInd_Cb(new_lcid, sabm_server_scn); log::verbose("Step 10"); // After security check, we accept the connection ASSERT_TRUE(security_callback); - BT_HDR* ua_server_scn = - AllocateWrappedOutgoingL2capAclPacket(CreateQuickUaPacket( - GetDlci(false, test_server_scn), new_lcid, acl_handle)); + BT_HDR* ua_server_scn = AllocateWrappedOutgoingL2capAclPacket( + CreateQuickUaPacket(GetDlci(false, test_server_scn), new_lcid, acl_handle)); EXPECT_CALL(l2cap_interface_, DataWrite(new_lcid, BtHdrEqual(ua_server_scn))) - .WillOnce(Return(tL2CAP_DW_RESULT::SUCCESS)); + .WillOnce(Return(tL2CAP_DW_RESULT::SUCCESS)); // Callback should come from server port instead, client port will timeout // in 20 seconds - EXPECT_CALL(rfcomm_callback_, - PortManagementCallback(PORT_SUCCESS, server_handle, 0)); + EXPECT_CALL(rfcomm_callback_, PortManagementCallback(PORT_SUCCESS, server_handle, 0)); security_callback(test_address, BT_TRANSPORT_BR_EDR, p_port, BTM_SUCCESS); osi_free(ua_server_scn); log::verbose("Step 11"); // MPX_CTRL Modem Status Command (MSC) BT_HDR* uih_msc_cmd_from_peer = AllocateWrappedIncomingL2capAclPacket( - CreateQuickMscPacket(true, GetDlci(false, test_server_scn), new_lcid, - acl_handle, true, false, true, true, false, true)); + CreateQuickMscPacket(true, GetDlci(false, test_server_scn), new_lcid, acl_handle, true, + false, true, true, false, true)); BT_HDR* uih_msc_rsp_to_peer = AllocateWrappedOutgoingL2capAclPacket( - CreateQuickMscPacket(false, GetDlci(false, test_server_scn), new_lcid, - acl_handle, false, false, true, true, false, true)); + CreateQuickMscPacket(false, GetDlci(false, test_server_scn), new_lcid, acl_handle, false, + false, true, true, false, true)); // MPX_CTRL Modem Status Response (MSC) - EXPECT_CALL(l2cap_interface_, - DataWrite(new_lcid, BtHdrEqual(uih_msc_rsp_to_peer))) - .WillOnce(Return(tL2CAP_DW_RESULT::SUCCESS)); + EXPECT_CALL(l2cap_interface_, DataWrite(new_lcid, BtHdrEqual(uih_msc_rsp_to_peer))) + .WillOnce(Return(tL2CAP_DW_RESULT::SUCCESS)); BT_HDR* uih_msc_cmd_to_peer = AllocateWrappedOutgoingL2capAclPacket( - CreateQuickMscPacket(false, GetDlci(false, test_server_scn), new_lcid, - acl_handle, true, false, true, true, false, true)); - EXPECT_CALL(l2cap_interface_, - DataWrite(new_lcid, BtHdrEqual(uih_msc_cmd_to_peer))) - .WillOnce(Return(tL2CAP_DW_RESULT::SUCCESS)); + CreateQuickMscPacket(false, GetDlci(false, test_server_scn), new_lcid, acl_handle, true, + false, true, true, false, true)); + EXPECT_CALL(l2cap_interface_, DataWrite(new_lcid, BtHdrEqual(uih_msc_cmd_to_peer))) + .WillOnce(Return(tL2CAP_DW_RESULT::SUCCESS)); l2cap_appl_info_.pL2CA_DataInd_Cb(new_lcid, uih_msc_cmd_from_peer); osi_free(uih_msc_rsp_to_peer); osi_free(uih_msc_cmd_to_peer); log::verbose("Step 12"); BT_HDR* uih_msc_rsp_from_peer = AllocateWrappedIncomingL2capAclPacket( - CreateQuickMscPacket(true, GetDlci(false, test_server_scn), new_lcid, - acl_handle, false, false, true, true, false, true)); + CreateQuickMscPacket(true, GetDlci(false, test_server_scn), new_lcid, acl_handle, false, + false, true, true, false, true)); l2cap_appl_info_.pL2CA_DataInd_Cb(new_lcid, uih_msc_rsp_from_peer); } diff --git a/system/stack/test/rfcomm/stack_rfcomm_test_main.cc b/system/stack/test/rfcomm/stack_rfcomm_test_main.cc index 936900679c3..c019d7eafdf 100644 --- a/system/stack/test/rfcomm/stack_rfcomm_test_main.cc +++ b/system/stack/test/rfcomm/stack_rfcomm_test_main.cc @@ -45,8 +45,8 @@ int main(int argc, char** argv) { const char* logging_argv[] = {"bt_stack", log_level_arg}; // Init command line object with logging switches if (!base::CommandLine::Init(2, logging_argv)) { - log::fatal("base::CommandLine::Init failed, arg0={}, arg1={}", - logging_argv[0], logging_argv[1]); + log::fatal("base::CommandLine::Init failed, arg0={}, arg1={}", logging_argv[0], + logging_argv[1]); return 1; } diff --git a/system/stack/test/rfcomm/stack_rfcomm_test_utils.cc b/system/stack/test/rfcomm/stack_rfcomm_test_utils.cc index fa0f35079bc..77e3c39e807 100644 --- a/system/stack/test/rfcomm/stack_rfcomm_test_utils.cc +++ b/system/stack/test/rfcomm/stack_rfcomm_test_utils.cc @@ -16,12 +16,13 @@ * ******************************************************************************/ +#include "stack_rfcomm_test_utils.h" + #include #include #include #include "stack/rfcomm/rfc_int.h" -#include "stack_rfcomm_test_utils.h" #include "stack_test_packet_utils.h" namespace bluetooth { @@ -57,9 +58,8 @@ uint8_t GetFrameTypeFromControlField(uint8_t control_field) { return static_cast(control_field & ~(0b10000)); } -std::vector CreateMccPnFrame(uint8_t dlci, uint8_t i_bits, - uint8_t cl_bits, uint8_t priority, - uint8_t timer_value, uint16_t rfcomm_mtu, +std::vector CreateMccPnFrame(uint8_t dlci, uint8_t i_bits, uint8_t cl_bits, + uint8_t priority, uint8_t timer_value, uint16_t rfcomm_mtu, uint8_t max_num_retransmission, uint8_t err_recovery_window_k) { // Data in little endian order @@ -75,8 +75,8 @@ std::vector CreateMccPnFrame(uint8_t dlci, uint8_t i_bits, return result; } -std::vector CreateMccMscFrame(uint8_t dlci, bool fc, bool rtc, - bool rtr, bool ic, bool dv) { +std::vector CreateMccMscFrame(uint8_t dlci, bool fc, bool rtc, bool rtr, bool ic, + bool dv) { // Data in little endian order std::vector result; result.push_back(static_cast((dlci << 2) | 0b11)); @@ -92,8 +92,8 @@ std::vector CreateMccMscFrame(uint8_t dlci, bool fc, bool rtc, return result; } -std::vector CreateMultiplexerControlFrame( - uint8_t command_type, bool cr, const std::vector& data) { +std::vector CreateMultiplexerControlFrame(uint8_t command_type, bool cr, + const std::vector& data) { // Data in little endian order std::vector result; std::bitset<8> header; @@ -107,8 +107,7 @@ std::vector CreateMultiplexerControlFrame( return result; } -std::vector CreateRfcommPacket(uint8_t address, uint8_t control, - int credits, +std::vector CreateRfcommPacket(uint8_t address, uint8_t control, int credits, const std::vector& data) { // Data in little endian order std::vector result; @@ -132,86 +131,66 @@ std::vector CreateRfcommPacket(uint8_t address, uint8_t control, if (GetFrameTypeFromControlField(control) == RFCOMM_UIH) { result.push_back(rfc_calc_fcs(2, result.data())); } else { - result.push_back( - rfc_calc_fcs(static_cast(result.size()), result.data())); + result.push_back(rfc_calc_fcs(static_cast(result.size()), result.data())); } return result; } -std::vector CreateQuickUaPacket(uint8_t dlci, uint16_t l2cap_lcid, - uint16_t acl_handle) { +std::vector CreateQuickUaPacket(uint8_t dlci, uint16_t l2cap_lcid, uint16_t acl_handle) { uint8_t address_field = GetAddressField(true, true, dlci); uint8_t control_field = GetControlField(true, RFCOMM_UA); - std::vector rfcomm_packet = - CreateRfcommPacket(address_field, control_field, -1, {}); - std::vector l2cap_packet = - CreateL2capDataPacket(l2cap_lcid, rfcomm_packet); + std::vector rfcomm_packet = CreateRfcommPacket(address_field, control_field, -1, {}); + std::vector l2cap_packet = CreateL2capDataPacket(l2cap_lcid, rfcomm_packet); return CreateAclPacket(acl_handle, 0b10, 0b00, l2cap_packet); } -std::vector CreateQuickSabmPacket(uint8_t dlci, uint16_t l2cap_lcid, - uint16_t acl_handle) { +std::vector CreateQuickSabmPacket(uint8_t dlci, uint16_t l2cap_lcid, uint16_t acl_handle) { uint8_t address_field = GetAddressField(true, true, dlci); uint8_t control_field = GetControlField(true, RFCOMM_SABME); - std::vector rfcomm_packet = - CreateRfcommPacket(address_field, control_field, -1, {}); - std::vector l2cap_packet = - CreateL2capDataPacket(l2cap_lcid, rfcomm_packet); + std::vector rfcomm_packet = CreateRfcommPacket(address_field, control_field, -1, {}); + std::vector l2cap_packet = CreateL2capDataPacket(l2cap_lcid, rfcomm_packet); return CreateAclPacket(acl_handle, 0b10, 0b00, l2cap_packet); } -std::vector CreateQuickPnPacket(bool rfc_cr, uint8_t target_dlci, - bool mx_cr, uint16_t rfc_mtu, - uint8_t cl, uint8_t priority, - uint8_t k, uint16_t l2cap_lcid, - uint16_t acl_handle) { +std::vector CreateQuickPnPacket(bool rfc_cr, uint8_t target_dlci, bool mx_cr, + uint16_t rfc_mtu, uint8_t cl, uint8_t priority, uint8_t k, + uint16_t l2cap_lcid, uint16_t acl_handle) { uint8_t address_field = GetAddressField(true, rfc_cr, RFCOMM_MX_DLCI); uint8_t control_field = GetControlField(false, RFCOMM_UIH); - std::vector mcc_pn_data = CreateMccPnFrame( - target_dlci, 0x0, cl, priority, RFCOMM_T1_DSEC, rfc_mtu, RFCOMM_N2, k); - std::vector mcc_payload = - CreateMultiplexerControlFrame(0x20, mx_cr, mcc_pn_data); + std::vector mcc_pn_data = + CreateMccPnFrame(target_dlci, 0x0, cl, priority, RFCOMM_T1_DSEC, rfc_mtu, RFCOMM_N2, k); + std::vector mcc_payload = CreateMultiplexerControlFrame(0x20, mx_cr, mcc_pn_data); std::vector rfcomm_packet = - CreateRfcommPacket(address_field, control_field, -1, mcc_payload); - std::vector l2cap_packet = - CreateL2capDataPacket(l2cap_lcid, rfcomm_packet); + CreateRfcommPacket(address_field, control_field, -1, mcc_payload); + std::vector l2cap_packet = CreateL2capDataPacket(l2cap_lcid, rfcomm_packet); return CreateAclPacket(acl_handle, 0b10, 0b00, l2cap_packet); } -std::vector CreateQuickMscPacket(bool rfc_cr, uint8_t dlci, - uint16_t l2cap_lcid, - uint16_t acl_handle, bool mx_cr, - bool fc, bool rtc, bool rtr, bool ic, - bool dv) { +std::vector CreateQuickMscPacket(bool rfc_cr, uint8_t dlci, uint16_t l2cap_lcid, + uint16_t acl_handle, bool mx_cr, bool fc, bool rtc, + bool rtr, bool ic, bool dv) { uint8_t address_field = GetAddressField(true, rfc_cr, RFCOMM_MX_DLCI); uint8_t control_field = GetControlField(false, RFCOMM_UIH); - std::vector mcc_msc_data = - CreateMccMscFrame(dlci, fc, rtc, rtr, ic, dv); - std::vector mcc_payload = - CreateMultiplexerControlFrame(0x38, mx_cr, mcc_msc_data); + std::vector mcc_msc_data = CreateMccMscFrame(dlci, fc, rtc, rtr, ic, dv); + std::vector mcc_payload = CreateMultiplexerControlFrame(0x38, mx_cr, mcc_msc_data); std::vector rfcomm_packet = - CreateRfcommPacket(address_field, control_field, -1, mcc_payload); - std::vector l2cap_packet = - CreateL2capDataPacket(l2cap_lcid, rfcomm_packet); + CreateRfcommPacket(address_field, control_field, -1, mcc_payload); + std::vector l2cap_packet = CreateL2capDataPacket(l2cap_lcid, rfcomm_packet); return CreateAclPacket(acl_handle, 0b10, 0b00, l2cap_packet); } -std::vector CreateQuickDataPacket(uint8_t dlci, bool cr, - uint16_t l2cap_lcid, +std::vector CreateQuickDataPacket(uint8_t dlci, bool cr, uint16_t l2cap_lcid, uint16_t acl_handle, int credits, const std::vector& data) { uint8_t address_field = GetAddressField(true, cr, dlci); - uint8_t control_field = - GetControlField(credits > 0 ? true : false, RFCOMM_UIH); + uint8_t control_field = GetControlField(credits > 0 ? true : false, RFCOMM_UIH); std::vector rfcomm_packet = - CreateRfcommPacket(address_field, control_field, credits, data); - std::vector l2cap_packet = - CreateL2capDataPacket(l2cap_lcid, rfcomm_packet); + CreateRfcommPacket(address_field, control_field, credits, data); + std::vector l2cap_packet = CreateL2capDataPacket(l2cap_lcid, rfcomm_packet); return CreateAclPacket(acl_handle, 0b10, 0b00, l2cap_packet); } -std::vector CreateQuickDataPacket(uint8_t dlci, bool cr, - uint16_t l2cap_lcid, +std::vector CreateQuickDataPacket(uint8_t dlci, bool cr, uint16_t l2cap_lcid, uint16_t acl_handle, int credits, const std::string& str) { std::vector data(str.begin(), str.end()); diff --git a/system/stack/test/rfcomm/stack_rfcomm_test_utils.h b/system/stack/test/rfcomm/stack_rfcomm_test_utils.h index eb8ec483da7..1a9232c1733 100644 --- a/system/stack/test/rfcomm/stack_rfcomm_test_utils.h +++ b/system/stack/test/rfcomm/stack_rfcomm_test_utils.h @@ -17,28 +17,27 @@ ******************************************************************************/ #pragma once -#include - #include +#include + namespace bluetooth { namespace rfcomm { class RfcommCallback { - public: +public: virtual void PortManagementCallback(uint32_t code, uint16_t port_handle, uint16_t callback_index) = 0; - virtual void PortEventCallback(uint32_t code, uint16_t port_handle, - uint16_t callback_index) = 0; + virtual void PortEventCallback(uint32_t code, uint16_t port_handle, uint16_t callback_index) = 0; virtual ~RfcommCallback() = default; }; class MockRfcommCallback : public RfcommCallback { - public: - MOCK_METHOD3(PortManagementCallback, void(uint32_t code, uint16_t port_handle, - uint16_t callback_index)); - MOCK_METHOD3(PortEventCallback, void(uint32_t code, uint16_t port_handle, - uint16_t callback_index)); +public: + MOCK_METHOD3(PortManagementCallback, + void(uint32_t code, uint16_t port_handle, uint16_t callback_index)); + MOCK_METHOD3(PortEventCallback, + void(uint32_t code, uint16_t port_handle, uint16_t callback_index)); }; /** @@ -83,9 +82,8 @@ uint8_t GetControlField(bool pf, uint8_t frame_type); * @param err_recovery_window_k error recovery window k * @return vector of bytes of this frame */ -std::vector CreateMccPnFrame(uint8_t dlci, uint8_t i_bits, - uint8_t cl_bits, uint8_t priority, - uint8_t timer_value, uint16_t rfcomm_mtu, +std::vector CreateMccPnFrame(uint8_t dlci, uint8_t i_bits, uint8_t cl_bits, + uint8_t priority, uint8_t timer_value, uint16_t rfcomm_mtu, uint8_t max_num_retransmission, uint8_t err_recovery_window_k); /** @@ -99,8 +97,7 @@ std::vector CreateMccPnFrame(uint8_t dlci, uint8_t i_bits, * @param dv is data valid * @return vector of bytes */ -std::vector CreateMccMscFrame(uint8_t dlci, bool fc, bool rtc, - bool rtr, bool ic, bool dv); +std::vector CreateMccMscFrame(uint8_t dlci, bool fc, bool rtc, bool rtr, bool ic, bool dv); /** * Create Multiplexer Control Frame @@ -111,8 +108,8 @@ std::vector CreateMccMscFrame(uint8_t dlci, bool fc, bool rtc, * @param data frame data * @return vector of bytes */ -std::vector CreateMultiplexerControlFrame( - uint8_t command_type, bool cr, const std::vector& data); +std::vector CreateMultiplexerControlFrame(uint8_t command_type, bool cr, + const std::vector& data); /** * Create a general RFCOMM packet @@ -123,8 +120,7 @@ std::vector CreateMultiplexerControlFrame( * @param data frame data * @return vector of bytes */ -std::vector CreateRfcommPacket(uint8_t address, uint8_t control, - int credits, +std::vector CreateRfcommPacket(uint8_t address, uint8_t control, int credits, const std::vector& data); /* * Various shortcut for getting frequently used packets @@ -139,8 +135,7 @@ std::vector CreateRfcommPacket(uint8_t address, uint8_t control, * @param acl_handle ACL handle * @return vector of bytes of unwrapped ACL packet */ -std::vector CreateQuickSabmPacket(uint8_t dlci, uint16_t l2cap_lcid, - uint16_t acl_handle); +std::vector CreateQuickSabmPacket(uint8_t dlci, uint16_t l2cap_lcid, uint16_t acl_handle); /** * Create UA packet that is used to acknowledge service channel connection @@ -150,28 +145,25 @@ std::vector CreateQuickSabmPacket(uint8_t dlci, uint16_t l2cap_lcid, * @param acl_handle ACL handle * @return vector of bytes of unwrapped ACL packet */ -std::vector CreateQuickUaPacket(uint8_t dlci, uint16_t l2cap_lcid, - uint16_t acl_handle); +std::vector CreateQuickUaPacket(uint8_t dlci, uint16_t l2cap_lcid, uint16_t acl_handle); /** * Create parameter negotiation packet used to setup parameters for a DLCI * * @param rfc_cr RFCOMM command/response bit, true of initiator * @param target_dlci DLCI to be configured - * @param mx_cr multiplexer command or reponse, regardless of initiator + * @param mx_cr multiplexer command or response, regardless of initiator * @param rfc_mtu RFCOMM mtu to be used for DLCI * @param cl CL bit - * @param priority prirority + * @param priority priority * @param k error recovery window k * @param l2cap_lcid L2CAP channel ID * @param acl_handle ACL handle * @return vector of bytes of unwrapped ACL packet */ -std::vector CreateQuickPnPacket(bool rfc_cr, uint8_t target_dlci, - bool mx_cr, uint16_t rfc_mtu, - uint8_t cl, uint8_t priority, - uint8_t k, uint16_t l2cap_lcid, - uint16_t acl_handle); +std::vector CreateQuickPnPacket(bool rfc_cr, uint8_t target_dlci, bool mx_cr, + uint16_t rfc_mtu, uint8_t cl, uint8_t priority, uint8_t k, + uint16_t l2cap_lcid, uint16_t acl_handle); /** * Create modem signal control packet @@ -180,7 +172,7 @@ std::vector CreateQuickPnPacket(bool rfc_cr, uint8_t target_dlci, * @param dlci DLCI to be configured * @param l2cap_lcid L2CAP channel ID * @param acl_handle ACL handle - * @param mx_cr multiplexer command or reponse, regardless of initiator + * @param mx_cr multiplexer command or response, regardless of initiator * @param fc flow control * @param rtc ready to communicate * @param rtr ready to receive @@ -188,11 +180,9 @@ std::vector CreateQuickPnPacket(bool rfc_cr, uint8_t target_dlci, * @param dv data valid * @return vector of bytes of unwrapped ACL packet */ -std::vector CreateQuickMscPacket(bool rfc_cr, uint8_t dlci, - uint16_t l2cap_lcid, - uint16_t acl_handle, bool mx_cr, - bool fc, bool rtc, bool rtr, bool ic, - bool dv); +std::vector CreateQuickMscPacket(bool rfc_cr, uint8_t dlci, uint16_t l2cap_lcid, + uint16_t acl_handle, bool mx_cr, bool fc, bool rtc, + bool rtr, bool ic, bool dv); /** * Create a quick RFCOMM data packet @@ -205,8 +195,7 @@ std::vector CreateQuickMscPacket(bool rfc_cr, uint8_t dlci, * @param data data bytes * @return vector of bytes of unwrapped ACL packet */ -std::vector CreateQuickDataPacket(uint8_t dlci, bool cr, - uint16_t l2cap_lcid, +std::vector CreateQuickDataPacket(uint8_t dlci, bool cr, uint16_t l2cap_lcid, uint16_t acl_handle, int credits, const std::vector& data); @@ -221,8 +210,7 @@ std::vector CreateQuickDataPacket(uint8_t dlci, bool cr, * @param str message in string format * @return vector of bytes of unwrapped ACL packet */ -std::vector CreateQuickDataPacket(uint8_t dlci, bool cr, - uint16_t l2cap_lcid, +std::vector CreateQuickDataPacket(uint8_t dlci, bool cr, uint16_t l2cap_lcid, uint16_t acl_handle, int credits, const std::string& str); diff --git a/system/stack/test/rfcomm/stack_rfcomm_test_utils_test.cc b/system/stack/test/rfcomm/stack_rfcomm_test_utils_test.cc index b97c7bb0590..1bebbd051ee 100644 --- a/system/stack/test/rfcomm/stack_rfcomm_test_utils_test.cc +++ b/system/stack/test/rfcomm/stack_rfcomm_test_utils_test.cc @@ -16,35 +16,36 @@ * ******************************************************************************/ -#include +#include "stack_rfcomm_test_utils.h" #include #include +#include + #include "stack/include/rfcdefs.h" -#include "stack_rfcomm_test_utils.h" #include "stack_test_packet_utils.h" namespace { using testing::ElementsAreArray; -using bluetooth::CreateL2capDataPacket; -using bluetooth::CreateAclPacket; using bluetooth::AllocateWrappedIncomingL2capAclPacket; +using bluetooth::CreateAclPacket; +using bluetooth::CreateL2capDataPacket; -using bluetooth::rfcomm::GetDlci; -using bluetooth::rfcomm::GetAddressField; -using bluetooth::rfcomm::GetControlField; -using bluetooth::rfcomm::CreateMccPnFrame; using bluetooth::rfcomm::CreateMccMscFrame; +using bluetooth::rfcomm::CreateMccPnFrame; using bluetooth::rfcomm::CreateMultiplexerControlFrame; -using bluetooth::rfcomm::CreateRfcommPacket; using bluetooth::rfcomm::CreateQuickDataPacket; +using bluetooth::rfcomm::CreateQuickMscPacket; using bluetooth::rfcomm::CreateQuickPnPacket; using bluetooth::rfcomm::CreateQuickSabmPacket; using bluetooth::rfcomm::CreateQuickUaPacket; -using bluetooth::rfcomm::CreateQuickMscPacket; +using bluetooth::rfcomm::CreateRfcommPacket; +using bluetooth::rfcomm::GetAddressField; +using bluetooth::rfcomm::GetControlField; +using bluetooth::rfcomm::GetDlci; const uint8_t kIncomingSabmChannel0[] = {0x08, 0x20, 0x08, 0x00, 0x04, 0x00, 0x5c, 0x00, 0x03, 0x3f, 0x01, 0x1c}; @@ -56,12 +57,9 @@ TEST(RfcommTestPacketGeneratorTest, TestGenerateSabmChannel0Packet) { EXPECT_EQ(address_field, 0x03); uint8_t control_field = GetControlField(true, RFCOMM_SABME); EXPECT_EQ(control_field, 0x3F); - std::vector rfcomm_packet = - CreateRfcommPacket(address_field, control_field, -1, {}); - std::vector l2cap_packet = - CreateL2capDataPacket(0x005c, rfcomm_packet); - std::vector acl_packet = - CreateAclPacket(0x0008, 0b10, 0b00, l2cap_packet); + std::vector rfcomm_packet = CreateRfcommPacket(address_field, control_field, -1, {}); + std::vector l2cap_packet = CreateL2capDataPacket(0x005c, rfcomm_packet); + std::vector acl_packet = CreateAclPacket(0x0008, 0b10, 0b00, l2cap_packet); EXPECT_THAT(acl_packet, ElementsAreArray(kIncomingSabmChannel0)); } @@ -80,12 +78,9 @@ TEST(RfcommTestPacketGeneratorTest, TestGenerateUaPacket) { EXPECT_EQ(address_field, 0x03); uint8_t control_field = GetControlField(true, RFCOMM_UA); EXPECT_EQ(control_field, 0x73); - std::vector rfcomm_packet = - CreateRfcommPacket(address_field, control_field, -1, {}); - std::vector l2cap_packet = - CreateL2capDataPacket(0x1700, rfcomm_packet); - std::vector acl_packet = - CreateAclPacket(0x0008, 0b10, 0b00, l2cap_packet); + std::vector rfcomm_packet = CreateRfcommPacket(address_field, control_field, -1, {}); + std::vector l2cap_packet = CreateL2capDataPacket(0x1700, rfcomm_packet); + std::vector acl_packet = CreateAclPacket(0x0008, 0b10, 0b00, l2cap_packet); EXPECT_THAT(acl_packet, ElementsAreArray(kOutgoingUaChannel0)); } @@ -94,9 +89,9 @@ TEST(RfcommTestPacketGeneratorTest, TestQuickGenerateUaPacket) { ElementsAreArray(kOutgoingUaChannel0)); } -const uint8_t kIncomingUihPnSetChannelTo3[] = { - 0x08, 0x20, 0x12, 0x00, 0x0e, 0x00, 0x5c, 0x00, 0x03, 0xef, 0x15, - 0x83, 0x11, 0x06, 0xf0, 0x00, 0x00, 0x74, 0x03, 0x00, 0x01, 0x70}; +const uint8_t kIncomingUihPnSetChannelTo3[] = {0x08, 0x20, 0x12, 0x00, 0x0e, 0x00, 0x5c, 0x00, + 0x03, 0xef, 0x15, 0x83, 0x11, 0x06, 0xf0, 0x00, + 0x00, 0x74, 0x03, 0x00, 0x01, 0x70}; TEST(RfcommTestPacketGeneratorTest, TestGenerateUihPnSetChannel3Packet) { uint8_t dlci = GetDlci(false, 0); @@ -107,22 +102,17 @@ TEST(RfcommTestPacketGeneratorTest, TestGenerateUihPnSetChannel3Packet) { EXPECT_EQ(control_field, 0xEF); uint8_t new_dlci = GetDlci(false, 3); EXPECT_EQ(new_dlci, 6); - std::vector mcc_pn_data = - CreateMccPnFrame(new_dlci, 0x0, 0xF, 0, 0, 884, 0, 1); - std::vector mcc_payload = - CreateMultiplexerControlFrame(0x20, true, mcc_pn_data); + std::vector mcc_pn_data = CreateMccPnFrame(new_dlci, 0x0, 0xF, 0, 0, 884, 0, 1); + std::vector mcc_payload = CreateMultiplexerControlFrame(0x20, true, mcc_pn_data); std::vector rfcomm_packet = - CreateRfcommPacket(address_field, control_field, -1, mcc_payload); - std::vector l2cap_packet = - CreateL2capDataPacket(0x005c, rfcomm_packet); - std::vector acl_packet = - CreateAclPacket(0x0008, 0b10, 0b00, l2cap_packet); + CreateRfcommPacket(address_field, control_field, -1, mcc_payload); + std::vector l2cap_packet = CreateL2capDataPacket(0x005c, rfcomm_packet); + std::vector acl_packet = CreateAclPacket(0x0008, 0b10, 0b00, l2cap_packet); EXPECT_THAT(acl_packet, ElementsAreArray(kIncomingUihPnSetChannelTo3)); } TEST(RfcommTestPacketGeneratorTest, TestQuickGenerateUihPnSetChannel3Packet) { - EXPECT_THAT(CreateQuickPnPacket(true, GetDlci(false, 3), true, 884, 0xF, 0, 1, - 0x005c, 0x0008), + EXPECT_THAT(CreateQuickPnPacket(true, GetDlci(false, 3), true, 884, 0xF, 0, 1, 0x005c, 0x0008), ElementsAreArray(kIncomingUihPnSetChannelTo3)); } @@ -136,12 +126,9 @@ TEST(RfcommTestPacketGeneratorTest, TestGenerateSabmChannel3Packet) { EXPECT_EQ(address_field, 0x1b); uint8_t control_field = GetControlField(true, RFCOMM_SABME); EXPECT_EQ(control_field, 0x3F); - std::vector rfcomm_packet = - CreateRfcommPacket(address_field, control_field, -1, {}); - std::vector l2cap_packet = - CreateL2capDataPacket(0x005c, rfcomm_packet); - std::vector acl_packet = - CreateAclPacket(0x0008, 0b10, 0b00, l2cap_packet); + std::vector rfcomm_packet = CreateRfcommPacket(address_field, control_field, -1, {}); + std::vector l2cap_packet = CreateL2capDataPacket(0x005c, rfcomm_packet); + std::vector acl_packet = CreateAclPacket(0x0008, 0b10, 0b00, l2cap_packet); EXPECT_THAT(acl_packet, ElementsAreArray(kIncomingSabmChannel3)); } @@ -150,9 +137,8 @@ TEST(RfcommTestPacketGeneratorTest, TestGenerateQuickSabmChannel3Packet) { ElementsAreArray(kIncomingSabmChannel3)); } -const uint8_t kIncomingUihMscCmdFrame[] = {0x08, 0x20, 0x0c, 0x00, 0x08, 0x00, - 0x5c, 0x00, 0x03, 0xef, 0x09, 0xe3, - 0x05, 0x1b, 0x8d, 0x70}; +const uint8_t kIncomingUihMscCmdFrame[] = {0x08, 0x20, 0x0c, 0x00, 0x08, 0x00, 0x5c, 0x00, + 0x03, 0xef, 0x09, 0xe3, 0x05, 0x1b, 0x8d, 0x70}; TEST(RfcommTestPacketGeneratorTest, TestGenerateUihMscCmdPacket) { uint8_t dlci = GetDlci(false, 0); @@ -163,28 +149,23 @@ TEST(RfcommTestPacketGeneratorTest, TestGenerateUihMscCmdPacket) { EXPECT_EQ(control_field, 0xEF); uint8_t new_dlci = GetDlci(false, 3); EXPECT_EQ(new_dlci, 6); - std::vector mcc_msc_data = - CreateMccMscFrame(new_dlci, false, true, true, false, true); - std::vector mcc_payload = - CreateMultiplexerControlFrame(0x38, true, mcc_msc_data); + std::vector mcc_msc_data = CreateMccMscFrame(new_dlci, false, true, true, false, true); + std::vector mcc_payload = CreateMultiplexerControlFrame(0x38, true, mcc_msc_data); std::vector rfcomm_packet = - CreateRfcommPacket(address_field, control_field, -1, mcc_payload); - std::vector l2cap_packet = - CreateL2capDataPacket(0x005c, rfcomm_packet); - std::vector acl_packet = - CreateAclPacket(0x0008, 0b10, 0b00, l2cap_packet); + CreateRfcommPacket(address_field, control_field, -1, mcc_payload); + std::vector l2cap_packet = CreateL2capDataPacket(0x005c, rfcomm_packet); + std::vector acl_packet = CreateAclPacket(0x0008, 0b10, 0b00, l2cap_packet); EXPECT_THAT(acl_packet, ElementsAreArray(kIncomingUihMscCmdFrame)); } TEST(RfcommTestPacketGeneratorTest, TestQuickGenerateUihMscCmdPacket) { - EXPECT_THAT(CreateQuickMscPacket(true, GetDlci(false, 3), 0x005c, 0x0008, - true, false, true, true, false, true), + EXPECT_THAT(CreateQuickMscPacket(true, GetDlci(false, 3), 0x005c, 0x0008, true, false, true, true, + false, true), ElementsAreArray(kIncomingUihMscCmdFrame)); } -const uint8_t kIncomingUihMscResponseFrame[] = { - 0x08, 0x20, 0x0c, 0x00, 0x08, 0x00, 0x5c, 0x00, - 0x03, 0xef, 0x09, 0xe1, 0x05, 0x1b, 0x8d, 0x70}; +const uint8_t kIncomingUihMscResponseFrame[] = {0x08, 0x20, 0x0c, 0x00, 0x08, 0x00, 0x5c, 0x00, + 0x03, 0xef, 0x09, 0xe1, 0x05, 0x1b, 0x8d, 0x70}; TEST(RfcommTestPacketGeneratorTest, TestGenerateUihMscResponsePacket) { uint8_t dlci = GetDlci(false, 0); @@ -195,29 +176,24 @@ TEST(RfcommTestPacketGeneratorTest, TestGenerateUihMscResponsePacket) { EXPECT_EQ(control_field, 0xEF); uint8_t new_dlci = GetDlci(false, 3); EXPECT_EQ(new_dlci, 6); - std::vector mcc_msc_data = - CreateMccMscFrame(new_dlci, false, true, true, false, true); - std::vector mcc_payload = - CreateMultiplexerControlFrame(0x38, false, mcc_msc_data); + std::vector mcc_msc_data = CreateMccMscFrame(new_dlci, false, true, true, false, true); + std::vector mcc_payload = CreateMultiplexerControlFrame(0x38, false, mcc_msc_data); std::vector rfcomm_packet = - CreateRfcommPacket(address_field, control_field, -1, mcc_payload); - std::vector l2cap_packet = - CreateL2capDataPacket(0x005c, rfcomm_packet); - std::vector acl_packet = - CreateAclPacket(0x0008, 0b10, 0b00, l2cap_packet); + CreateRfcommPacket(address_field, control_field, -1, mcc_payload); + std::vector l2cap_packet = CreateL2capDataPacket(0x005c, rfcomm_packet); + std::vector acl_packet = CreateAclPacket(0x0008, 0b10, 0b00, l2cap_packet); EXPECT_THAT(acl_packet, ElementsAreArray(kIncomingUihMscResponseFrame)); } TEST(RfcommTestPacketGeneratorTest, TestQuickGenerateUihMscResponsePacket) { - EXPECT_THAT(CreateQuickMscPacket(true, GetDlci(false, 3), 0x005c, 0x0008, - false, false, true, true, false, true), + EXPECT_THAT(CreateQuickMscPacket(true, GetDlci(false, 3), 0x005c, 0x0008, false, false, true, + true, false, true), ElementsAreArray(kIncomingUihMscResponseFrame)); } -const uint8_t kIncomingBrsfFrame[] = {0x08, 0x20, 0x15, 0x00, 0x11, 0x00, 0x5c, - 0x00, 0x1b, 0xff, 0x19, 0x06, 0x41, 0x54, - 0x2b, 0x42, 0x52, 0x53, 0x46, 0x3d, 0x39, - 0x35, 0x39, 0x0d, 0x93}; +const uint8_t kIncomingBrsfFrame[] = {0x08, 0x20, 0x15, 0x00, 0x11, 0x00, 0x5c, 0x00, 0x1b, + 0xff, 0x19, 0x06, 0x41, 0x54, 0x2b, 0x42, 0x52, 0x53, + 0x46, 0x3d, 0x39, 0x35, 0x39, 0x0d, 0x93}; TEST(RfcommTestPacketGeneratorTest, TestGenerateDataPacket) { uint8_t dlci = GetDlci(false, 3); @@ -228,18 +204,14 @@ TEST(RfcommTestPacketGeneratorTest, TestGenerateDataPacket) { EXPECT_EQ(control_field, 0xFF); const std::string data_str = "AT+BRSF=959\r"; const std::vector data(data_str.begin(), data_str.end()); - std::vector rfcomm_packet = - CreateRfcommPacket(address_field, control_field, 6, data); - std::vector l2cap_packet = - CreateL2capDataPacket(0x005c, rfcomm_packet); - std::vector acl_packet = - CreateAclPacket(0x0008, 0b10, 0b00, l2cap_packet); + std::vector rfcomm_packet = CreateRfcommPacket(address_field, control_field, 6, data); + std::vector l2cap_packet = CreateL2capDataPacket(0x005c, rfcomm_packet); + std::vector acl_packet = CreateAclPacket(0x0008, 0b10, 0b00, l2cap_packet); EXPECT_THAT(acl_packet, ElementsAreArray(kIncomingBrsfFrame)); } TEST(RfcommTestPacketGeneratorTest, TestQuickGenerateDataPacket) { - EXPECT_THAT(CreateQuickDataPacket(GetDlci(false, 3), true, 0x005c, 0x0008, 6, - "AT+BRSF=959\r"), + EXPECT_THAT(CreateQuickDataPacket(GetDlci(false, 3), true, 0x005c, 0x0008, 6, "AT+BRSF=959\r"), ElementsAreArray(kIncomingBrsfFrame)); } diff --git a/system/stack/test/sdp/sdp_packet00.h b/system/stack/test/sdp/sdp_packet00.h index 39592d64d2c..32cb5af378a 100644 --- a/system/stack/test/sdp/sdp_packet00.h +++ b/system/stack/test/sdp/sdp_packet00.h @@ -29,23 +29,23 @@ namespace packets00 { // b/321872406#comment32 // Frame (103 bytes) static const unsigned char pkt1017[103] = { - 0x02, 0x0b, 0x20, 0x62, 0x00, 0x5e, 0x00, 0x46, // .. b.^.F - 0x00, 0x07, 0x00, 0x00, 0x00, 0x59, 0x00, 0x56, // .....Y.V - 0x36, 0x00, 0x53, 0x36, 0x00, 0x50, 0x09, 0x00, // 6.S6.P.. - 0x00, 0x0a, 0x00, 0x01, 0x00, 0x09, 0x09, 0x00, // ........ - 0x01, 0x35, 0x11, 0x1c, 0x4d, 0xe1, 0x7a, 0x00, // .5..M.z. - 0x52, 0xcb, 0x11, 0xe6, 0xbd, 0xf4, 0x08, 0x00, // R....... - 0x20, 0x0c, 0x9a, 0x66, 0x09, 0x00, 0x02, 0x0a, // ..f.... - 0x00, 0x8f, 0x51, 0x62, 0x09, 0x00, 0x04, 0x35, // ..Qb...5 - 0x0c, 0x35, 0x03, 0x19, 0x01, 0x00, 0x35, 0x05, // .5....5. - 0x19, 0x00, 0x03, 0x08, 0x03, 0x09, 0x00, 0x05, // ........ - 0x35, 0x03, 0x19, 0x10, 0x02, 0x09, 0x00, 0x09, // 5....... - 0x35, 0x08, 0x35, 0x06, 0x19, 0x11, 0x01, 0x09, // 5.5..... - 0x01, 0x02, 0x09, 0x01, 0x00, 0x00, 0x00 // ....... + 0x02, 0x0b, 0x20, 0x62, 0x00, 0x5e, 0x00, 0x46, // .. b.^.F + 0x00, 0x07, 0x00, 0x00, 0x00, 0x59, 0x00, 0x56, // .....Y.V + 0x36, 0x00, 0x53, 0x36, 0x00, 0x50, 0x09, 0x00, // 6.S6.P.. + 0x00, 0x0a, 0x00, 0x01, 0x00, 0x09, 0x09, 0x00, // ........ + 0x01, 0x35, 0x11, 0x1c, 0x4d, 0xe1, 0x7a, 0x00, // .5..M.z. + 0x52, 0xcb, 0x11, 0xe6, 0xbd, 0xf4, 0x08, 0x00, // R....... + 0x20, 0x0c, 0x9a, 0x66, 0x09, 0x00, 0x02, 0x0a, // ..f.... + 0x00, 0x8f, 0x51, 0x62, 0x09, 0x00, 0x04, 0x35, // ..Qb...5 + 0x0c, 0x35, 0x03, 0x19, 0x01, 0x00, 0x35, 0x05, // .5....5. + 0x19, 0x00, 0x03, 0x08, 0x03, 0x09, 0x00, 0x05, // ........ + 0x35, 0x03, 0x19, 0x10, 0x02, 0x09, 0x00, 0x09, // 5....... + 0x35, 0x08, 0x35, 0x06, 0x19, 0x11, 0x01, 0x09, // 5.5..... + 0x01, 0x02, 0x09, 0x01, 0x00, 0x00, 0x00 // ....... }; const raw_packet_t rx_pkts[] = { - {pkt1017, sizeof(pkt1017)}, + {pkt1017, sizeof(pkt1017)}, }; const size_t kNumRxPkts = sizeof(rx_pkts) / sizeof(rx_pkts[0]); diff --git a/system/stack/test/sdp/stack_sdp_db_test.cc b/system/stack/test/sdp/stack_sdp_db_test.cc index 8b07ac43de5..53d54de1770 100644 --- a/system/stack/test/sdp/stack_sdp_db_test.cc +++ b/system/stack/test/sdp/stack_sdp_db_test.cc @@ -28,7 +28,7 @@ constexpr uint32_t kFirstRecordHandle = 0x10000; using bluetooth::legacy::stack::sdp::get_legacy_stack_sdp_api; class StackSdpDbTest : public ::testing::Test { - protected: +protected: void SetUp() override { // Ensure no records exist in global state ASSERT_EQ((uint16_t)0, sdp_cb.server_db.num_records); @@ -41,8 +41,7 @@ class StackSdpDbTest : public ::testing::Test { }; TEST_F(StackSdpDbTest, SDP_AddAttribute__create_record) { - uint32_t record_handle = - get_legacy_stack_sdp_api()->handle.SDP_CreateRecord(); + uint32_t record_handle = get_legacy_stack_sdp_api()->handle.SDP_CreateRecord(); ASSERT_NE((uint32_t)0, record_handle); ASSERT_EQ((uint16_t)1, sdp_cb.server_db.num_records); @@ -55,144 +54,127 @@ TEST_F(StackSdpDbTest, SDP_AddAttribute__create_record) { ASSERT_EQ(kFirstRecordHandle, record->record_handle); ASSERT_EQ(sizeof(uint32_t), record->free_pad_ptr); - ASSERT_TRUE( - get_legacy_stack_sdp_api()->handle.SDP_DeleteRecord(record_handle)); + ASSERT_TRUE(get_legacy_stack_sdp_api()->handle.SDP_DeleteRecord(record_handle)); } TEST_F(StackSdpDbTest, SDP_AddAttribute__add_service_name) { - uint32_t record_handle = - get_legacy_stack_sdp_api()->handle.SDP_CreateRecord(); + uint32_t record_handle = get_legacy_stack_sdp_api()->handle.SDP_CreateRecord(); ASSERT_NE((uint32_t)0, record_handle); ASSERT_TRUE(get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - record_handle, ATTR_ID_SERVICE_NAME, TEXT_STR_DESC_TYPE, - (uint32_t)(strlen(service_name) + 1), (uint8_t*)service_name)); + record_handle, ATTR_ID_SERVICE_NAME, TEXT_STR_DESC_TYPE, + (uint32_t)(strlen(service_name) + 1), (uint8_t*)service_name)); tSDP_RECORD* record = sdp_db_find_record(record_handle); ASSERT_TRUE(record != nullptr); // The sdp handle is always the first attribute - ASSERT_EQ((uint16_t)(1 /* record_handle */ + 1 /* service name */), - record->num_attributes); + ASSERT_EQ((uint16_t)(1 /* record_handle */ + 1 /* service name */), record->num_attributes); ASSERT_EQ(kFirstRecordHandle, record->record_handle); ASSERT_EQ(sizeof(uint32_t) + strlen(service_name) + 1, record->free_pad_ptr); - const tSDP_ATTRIBUTE* attribute = sdp_db_find_attr_in_rec( - record, ATTR_ID_SERVICE_NAME, ATTR_ID_SERVICE_NAME); + const tSDP_ATTRIBUTE* attribute = + sdp_db_find_attr_in_rec(record, ATTR_ID_SERVICE_NAME, ATTR_ID_SERVICE_NAME); ASSERT_TRUE(attribute != nullptr); - ASSERT_TRUE( - get_legacy_stack_sdp_api()->handle.SDP_DeleteRecord(record_handle)); + ASSERT_TRUE(get_legacy_stack_sdp_api()->handle.SDP_DeleteRecord(record_handle)); } TEST_F(StackSdpDbTest, SDP_AddAttribute__three_attributes) { - uint32_t record_handle = - get_legacy_stack_sdp_api()->handle.SDP_CreateRecord(); + uint32_t record_handle = get_legacy_stack_sdp_api()->handle.SDP_CreateRecord(); ASSERT_NE((uint32_t)0, record_handle); ASSERT_TRUE(get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - record_handle, ATTR_ID_SERVICE_NAME, TEXT_STR_DESC_TYPE, - (uint32_t)(strlen(service_name) + 1), (uint8_t*)service_name)); + record_handle, ATTR_ID_SERVICE_NAME, TEXT_STR_DESC_TYPE, + (uint32_t)(strlen(service_name) + 1), (uint8_t*)service_name)); ASSERT_TRUE(get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - record_handle, ATTR_ID_SERVICE_DESCRIPTION, TEXT_STR_DESC_TYPE, - (uint32_t)(strlen(service_name) + 1), (uint8_t*)service_name)); + record_handle, ATTR_ID_SERVICE_DESCRIPTION, TEXT_STR_DESC_TYPE, + (uint32_t)(strlen(service_name) + 1), (uint8_t*)service_name)); ASSERT_TRUE(get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - record_handle, ATTR_ID_PROVIDER_NAME, TEXT_STR_DESC_TYPE, - (uint32_t)(strlen(service_name) + 1), (uint8_t*)service_name)); + record_handle, ATTR_ID_PROVIDER_NAME, TEXT_STR_DESC_TYPE, + (uint32_t)(strlen(service_name) + 1), (uint8_t*)service_name)); tSDP_RECORD* record = sdp_db_find_record(record_handle); ASSERT_TRUE(record != nullptr); // The sdp handle is always the first attribute - ASSERT_EQ((uint16_t)(1 /* record_handle */ + 3 /* service name */), - record->num_attributes); + ASSERT_EQ((uint16_t)(1 /* record_handle */ + 3 /* service name */), record->num_attributes); ASSERT_EQ(kFirstRecordHandle, record->record_handle); - ASSERT_EQ(sizeof(uint32_t) + (3 * (strlen(service_name) + 1)), - record->free_pad_ptr); + ASSERT_EQ(sizeof(uint32_t) + (3 * (strlen(service_name) + 1)), record->free_pad_ptr); - ASSERT_TRUE(sdp_db_find_attr_in_rec(record, ATTR_ID_SERVICE_NAME, - ATTR_ID_SERVICE_NAME) != nullptr); + ASSERT_TRUE(sdp_db_find_attr_in_rec(record, ATTR_ID_SERVICE_NAME, ATTR_ID_SERVICE_NAME) != + nullptr); ASSERT_TRUE(sdp_db_find_attr_in_rec(record, ATTR_ID_SERVICE_DESCRIPTION, ATTR_ID_SERVICE_DESCRIPTION) != nullptr); - ASSERT_TRUE(sdp_db_find_attr_in_rec(record, ATTR_ID_PROVIDER_NAME, - ATTR_ID_PROVIDER_NAME) != nullptr); + ASSERT_TRUE(sdp_db_find_attr_in_rec(record, ATTR_ID_PROVIDER_NAME, ATTR_ID_PROVIDER_NAME) != + nullptr); - ASSERT_TRUE( - get_legacy_stack_sdp_api()->handle.SDP_DeleteRecord(record_handle)); + ASSERT_TRUE(get_legacy_stack_sdp_api()->handle.SDP_DeleteRecord(record_handle)); } TEST_F(StackSdpDbTest, SDP_AddAttribute__too_many_attributes) { - uint32_t record_handle = - get_legacy_stack_sdp_api()->handle.SDP_CreateRecord(); + uint32_t record_handle = get_legacy_stack_sdp_api()->handle.SDP_CreateRecord(); ASSERT_NE((uint32_t)0, record_handle); uint8_t boolean = 1; for (size_t i = 0; i < SDP_MAX_REC_ATTR; i++) { ASSERT_TRUE(get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - record_handle, (uint16_t)i, BOOLEAN_DESC_TYPE, boolean, &boolean)); + record_handle, (uint16_t)i, BOOLEAN_DESC_TYPE, boolean, &boolean)); } ASSERT_FALSE(get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - record_handle, SDP_MAX_REC_ATTR + 1, BOOLEAN_DESC_TYPE, boolean, - &boolean)); - ASSERT_TRUE( - get_legacy_stack_sdp_api()->handle.SDP_DeleteRecord(record_handle)); + record_handle, SDP_MAX_REC_ATTR + 1, BOOLEAN_DESC_TYPE, boolean, &boolean)); + ASSERT_TRUE(get_legacy_stack_sdp_api()->handle.SDP_DeleteRecord(record_handle)); } TEST_F(StackSdpDbTest, SDP_AddAttribute__three_attributes_replace_middle) { - uint32_t record_handle = - get_legacy_stack_sdp_api()->handle.SDP_CreateRecord(); + uint32_t record_handle = get_legacy_stack_sdp_api()->handle.SDP_CreateRecord(); ASSERT_NE((uint32_t)0, record_handle); // Add 3 attributes to this record handle ASSERT_TRUE(get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - record_handle, ATTR_ID_SERVICE_NAME, TEXT_STR_DESC_TYPE, - (uint32_t)(strlen(service_name) + 1), (uint8_t*)service_name)); + record_handle, ATTR_ID_SERVICE_NAME, TEXT_STR_DESC_TYPE, + (uint32_t)(strlen(service_name) + 1), (uint8_t*)service_name)); ASSERT_TRUE(get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - record_handle, ATTR_ID_SERVICE_DESCRIPTION, TEXT_STR_DESC_TYPE, - (uint32_t)(strlen(service_name) + 1), (uint8_t*)service_name)); + record_handle, ATTR_ID_SERVICE_DESCRIPTION, TEXT_STR_DESC_TYPE, + (uint32_t)(strlen(service_name) + 1), (uint8_t*)service_name)); ASSERT_TRUE(get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - record_handle, ATTR_ID_PROVIDER_NAME, TEXT_STR_DESC_TYPE, - (uint32_t)(strlen(service_name) + 1), (uint8_t*)service_name)); + record_handle, ATTR_ID_PROVIDER_NAME, TEXT_STR_DESC_TYPE, + (uint32_t)(strlen(service_name) + 1), (uint8_t*)service_name)); tSDP_RECORD* record = sdp_db_find_record(record_handle); ASSERT_TRUE(record != nullptr); // The sdp handle is always the first attribute - ASSERT_EQ((uint16_t)(1 /* record_handle */ + 3 /* attribute count */), - record->num_attributes); + ASSERT_EQ((uint16_t)(1 /* record_handle */ + 3 /* attribute count */), record->num_attributes); ASSERT_EQ(kFirstRecordHandle, record->record_handle); - ASSERT_EQ(sizeof(uint32_t) + (3 * (strlen(service_name) + 1)), - record->free_pad_ptr); + ASSERT_EQ(sizeof(uint32_t) + (3 * (strlen(service_name) + 1)), record->free_pad_ptr); - ASSERT_TRUE(sdp_db_find_attr_in_rec(record, ATTR_ID_SERVICE_NAME, - ATTR_ID_SERVICE_NAME) != nullptr); + ASSERT_TRUE(sdp_db_find_attr_in_rec(record, ATTR_ID_SERVICE_NAME, ATTR_ID_SERVICE_NAME) != + nullptr); ASSERT_TRUE(sdp_db_find_attr_in_rec(record, ATTR_ID_SERVICE_DESCRIPTION, ATTR_ID_SERVICE_DESCRIPTION) != nullptr); - ASSERT_TRUE(sdp_db_find_attr_in_rec(record, ATTR_ID_PROVIDER_NAME, - ATTR_ID_PROVIDER_NAME) != nullptr); + ASSERT_TRUE(sdp_db_find_attr_in_rec(record, ATTR_ID_PROVIDER_NAME, ATTR_ID_PROVIDER_NAME) != + nullptr); // Attempt to replace the middle attribute with an invalid attribute ASSERT_FALSE(get_legacy_stack_sdp_api()->handle.SDP_AddAttribute( - record_handle, ATTR_ID_SERVICE_DESCRIPTION, TEXT_STR_DESC_TYPE, - (uint32_t)0, (uint8_t*)nullptr)); + record_handle, ATTR_ID_SERVICE_DESCRIPTION, TEXT_STR_DESC_TYPE, (uint32_t)0, + (uint8_t*)nullptr)); // Ensure database is still intact. - ASSERT_EQ((uint16_t)(1 /* record_handle */ + 3 /* attribute count */), - record->num_attributes); + ASSERT_EQ((uint16_t)(1 /* record_handle */ + 3 /* attribute count */), record->num_attributes); ASSERT_EQ(kFirstRecordHandle, record->record_handle); - ASSERT_EQ(sizeof(uint32_t) + (3 * (strlen(service_name) + 1)), - record->free_pad_ptr); + ASSERT_EQ(sizeof(uint32_t) + (3 * (strlen(service_name) + 1)), record->free_pad_ptr); - ASSERT_TRUE(sdp_db_find_attr_in_rec(record, ATTR_ID_SERVICE_NAME, - ATTR_ID_SERVICE_NAME) != nullptr); + ASSERT_TRUE(sdp_db_find_attr_in_rec(record, ATTR_ID_SERVICE_NAME, ATTR_ID_SERVICE_NAME) != + nullptr); ASSERT_TRUE(sdp_db_find_attr_in_rec(record, ATTR_ID_SERVICE_DESCRIPTION, ATTR_ID_SERVICE_DESCRIPTION) != nullptr); - ASSERT_TRUE(sdp_db_find_attr_in_rec(record, ATTR_ID_PROVIDER_NAME, - ATTR_ID_PROVIDER_NAME) != nullptr); + ASSERT_TRUE(sdp_db_find_attr_in_rec(record, ATTR_ID_PROVIDER_NAME, ATTR_ID_PROVIDER_NAME) != + nullptr); - ASSERT_TRUE( - get_legacy_stack_sdp_api()->handle.SDP_DeleteRecord(record_handle)); + ASSERT_TRUE(get_legacy_stack_sdp_api()->handle.SDP_DeleteRecord(record_handle)); } diff --git a/system/stack/test/sdp/stack_sdp_parse_test.cc b/system/stack/test/sdp/stack_sdp_parse_test.cc index e87e4d33387..41ff1653e3f 100644 --- a/system/stack/test/sdp/stack_sdp_parse_test.cc +++ b/system/stack/test/sdp/stack_sdp_parse_test.cc @@ -36,8 +36,7 @@ #include "test/mock/mock_osi_allocator.h" #include "test/mock/mock_stack_l2cap_api.h" -constexpr uint32_t kBtDefaultBufferSize = - static_cast(BT_DEFAULT_BUFFER_SIZE); +constexpr uint32_t kBtDefaultBufferSize = static_cast(BT_DEFAULT_BUFFER_SIZE); #define TEST_BT com::android::bluetooth::flags @@ -51,27 +50,23 @@ constexpr size_t kSdpPacketStartOffset = 9; int L2CA_ConnectReqWithSecurity_cid = 0x42; class StackSdpParserWithMocksTest : public ::testing::Test { - protected: +protected: void SetUp() override { reset_mock_function_count_map(); fake_osi_ = std::make_unique(); test::mock::stack_l2cap_api::L2CA_ConnectReqWithSecurity.body = - [](uint16_t /* psm */, const RawAddress& /* p_bd_addr */, - uint16_t /* sec_level */) { - return ++L2CA_ConnectReqWithSecurity_cid; - }; - test::mock::stack_l2cap_api::L2CA_DataWrite.body = [](uint16_t /* cid */, - BT_HDR* p_data) { + [](uint16_t /* psm */, const RawAddress& /* p_bd_addr */, uint16_t /* sec_level */) { + return ++L2CA_ConnectReqWithSecurity_cid; + }; + test::mock::stack_l2cap_api::L2CA_DataWrite.body = [](uint16_t /* cid */, BT_HDR* p_data) { osi_free_and_reset((void**)&p_data); return tL2CAP_DW_RESULT::FAILED; }; - test::mock::stack_l2cap_api::L2CA_DisconnectReq.body = - [](uint16_t /* cid */) { return true; }; + test::mock::stack_l2cap_api::L2CA_DisconnectReq.body = [](uint16_t /* cid */) { return true; }; test::mock::stack_l2cap_api::L2CA_RegisterWithSecurity.body = - [](uint16_t psm, const tL2CAP_APPL_INFO& /* p_cb_info */, - bool /* enable_snoop */, tL2CAP_ERTM_INFO* /* p_ertm_info */, - uint16_t /* my_mtu */, uint16_t /* required_remote_mtu */, - uint16_t /* sec_level */) { return psm; }; + [](uint16_t psm, const tL2CAP_APPL_INFO& /* p_cb_info */, bool /* enable_snoop */, + tL2CAP_ERTM_INFO* /* p_ertm_info */, uint16_t /* my_mtu */, + uint16_t /* required_remote_mtu */, uint16_t /* sec_level */) { return psm; }; } void TearDown() override { @@ -86,7 +81,7 @@ class StackSdpParserWithMocksTest : public ::testing::Test { }; class StackSdpParserInitTest : public StackSdpParserWithMocksTest { - protected: +protected: void SetUp() override { StackSdpParserWithMocksTest::SetUp(); sdp_init(); @@ -108,23 +103,21 @@ class StackSdpParserInitTest : public StackSdpParserWithMocksTest { TEST_F(StackSdpParserInitTest, SDP_InitDiscoveryDb) { bluetooth::Uuid uuid; const bool success = get_legacy_stack_sdp_api()->service.SDP_InitDiscoveryDb( - p_db_, kBtDefaultBufferSize, 1, &uuid, 0, nullptr); + p_db_, kBtDefaultBufferSize, 1, &uuid, 0, nullptr); ASSERT_TRUE(success); ASSERT_TRUE(get_legacy_stack_sdp_api()->service.SDP_ServiceSearchRequest( - kRawAddress, p_db_, - [](const RawAddress& /* bd_addr */, tSDP_RESULT /* result */) {})); + kRawAddress, p_db_, [](const RawAddress& /* bd_addr */, tSDP_RESULT /* result */) {})); } class StackSdpAsClientParseTest : public StackSdpParserInitTest { - protected: +protected: void SetUp() override { StackSdpParserInitTest::SetUp(); - ASSERT_TRUE(get_legacy_stack_sdp_api()->service.SDP_InitDiscoveryDb( - p_db_, kSdpDbSize, 1, p_uuid_list, 0, nullptr)); + ASSERT_TRUE(get_legacy_stack_sdp_api()->service.SDP_InitDiscoveryDb(p_db_, kSdpDbSize, 1, + p_uuid_list, 0, nullptr)); ASSERT_TRUE(get_legacy_stack_sdp_api()->service.SDP_ServiceSearchRequest( - kRawAddress, p_db_, - [](const RawAddress& /* bd_addr */, tSDP_RESULT /* result */) {})); + kRawAddress, p_db_, [](const RawAddress& /* bd_addr */, tSDP_RESULT /* result */) {})); // Fast forward to to accept SDP responses as originator p_ccb_ = sdpu_find_ccb_by_db(p_db_); @@ -141,21 +134,20 @@ class StackSdpAsClientParseTest : public StackSdpParserInitTest { tCONN_CB* p_ccb_{nullptr}; const bluetooth::Uuid p_uuid_list[1]{ - bluetooth::Uuid::From128BitBE( - bluetooth::os::GenerateRandom()), + bluetooth::Uuid::From128BitBE( + bluetooth::os::GenerateRandom()), }; - void parse_sdp_responses(const bluetooth::testing::raw_packet_t* pkts, - size_t num_pkts) { + void parse_sdp_responses(const bluetooth::testing::raw_packet_t* pkts, size_t num_pkts) { for (size_t i = 0; i < num_pkts; i++) { const bluetooth::testing::raw_packet_t* pkt = &pkts[i]; char* data = (char*)osi_malloc(pkt->len + sizeof(BT_HDR)); BT_HDR* bt_hdr = (BT_HDR*)data; *bt_hdr = { - .event = 0, - .len = (uint16_t)pkt->len, - .offset = 0, - .layer_specific = 0, + .event = 0, + .len = (uint16_t)pkt->len, + .offset = 0, + .layer_specific = 0, }; uint8_t* payload = (uint8_t*)(bt_hdr + 1); memcpy(payload, (const void*)(pkt->data + kSdpPacketStartOffset), @@ -171,8 +163,8 @@ class StackSdpAsClientParseTest : public StackSdpParserInitTest { TEST_F(StackSdpAsClientParseTest, nop) {} TEST_F_WITH_FLAGS(StackSdpAsClientParseTest, sdp_disc_server_rsp_packets00, - REQUIRES_FLAGS_DISABLED(ACONFIG_FLAG( - TEST_BT, stack_sdp_detect_nil_property_type))) { + REQUIRES_FLAGS_DISABLED(ACONFIG_FLAG(TEST_BT, + stack_sdp_detect_nil_property_type))) { parse_sdp_responses(bluetooth::testing::stack::sdp::packets00::rx_pkts, bluetooth::testing::stack::sdp::packets00::kNumRxPkts); @@ -185,64 +177,55 @@ TEST_F_WITH_FLAGS(StackSdpAsClientParseTest, sdp_disc_server_rsp_packets00, // Service Record Handle ASSERT_EQ(0x00010009U, get_legacy_stack_sdp_api() - ->record - .SDP_FindAttributeInRec(p_sdp_rec, ATTR_ID_SERVICE_RECORD_HDL) - ->attr_value.v.u32); + ->record.SDP_FindAttributeInRec(p_sdp_rec, ATTR_ID_SERVICE_RECORD_HDL) + ->attr_value.v.u32); // Service Class ID List p_sdp_rec = p_db_->p_first_rec; - p_sdp_rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb_128bit( - p_db_, p_sdp_rec); + p_sdp_rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb_128bit(p_db_, p_sdp_rec); // ASSERT_NE(nullptr, p_sdp_rec); auto uuid_list = std::vector(1); p_sdp_rec = p_db_->p_first_rec; - ASSERT_EQ(true, - get_legacy_stack_sdp_api()->record.SDP_FindServiceUUIDInRec_128bit( - p_sdp_rec, &uuid_list[0])); + ASSERT_EQ(true, get_legacy_stack_sdp_api()->record.SDP_FindServiceUUIDInRec_128bit( + p_sdp_rec, &uuid_list[0])); ASSERT_EQ(1U, uuid_list.size()); - ASSERT_STREQ("4de17a00-52cb-11e6-bdf4-0800200c9a66", - uuid_list.front().ToString().c_str()); + ASSERT_STREQ("4de17a00-52cb-11e6-bdf4-0800200c9a66", uuid_list.front().ToString().c_str()); // Service Record State ASSERT_EQ(0x008f5162U, get_legacy_stack_sdp_api() - ->record - .SDP_FindAttributeInRec(p_sdp_rec, ATTR_ID_SERVICE_RECORD_STATE) - ->attr_value.v.u32); + ->record.SDP_FindAttributeInRec(p_sdp_rec, ATTR_ID_SERVICE_RECORD_STATE) + ->attr_value.v.u32); // Protocol Descriptor List tSDP_PROTOCOL_ELEM pe; - ASSERT_EQ(true, - get_legacy_stack_sdp_api()->record.SDP_FindProtocolListElemInRec( - p_sdp_rec, UUID_PROTOCOL_L2CAP, &pe)); + ASSERT_EQ(true, get_legacy_stack_sdp_api()->record.SDP_FindProtocolListElemInRec( + p_sdp_rec, UUID_PROTOCOL_L2CAP, &pe)); ASSERT_EQ(UUID_PROTOCOL_L2CAP, pe.protocol_uuid); ASSERT_EQ(0U, pe.num_params); - ASSERT_EQ(true, - get_legacy_stack_sdp_api()->record.SDP_FindProtocolListElemInRec( - p_sdp_rec, UUID_PROTOCOL_RFCOMM, &pe)); + ASSERT_EQ(true, get_legacy_stack_sdp_api()->record.SDP_FindProtocolListElemInRec( + p_sdp_rec, UUID_PROTOCOL_RFCOMM, &pe)); ASSERT_EQ(UUID_PROTOCOL_RFCOMM, pe.protocol_uuid); ASSERT_EQ(1U, pe.num_params); ASSERT_EQ(UUID_PROTOCOL_RFCOMM, pe.params[0]); // Browse Group List ASSERT_NE(nullptr, get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - p_sdp_rec, ATTR_ID_BROWSE_GROUP_LIST)); + p_sdp_rec, ATTR_ID_BROWSE_GROUP_LIST)); // Bluetooth Profile List ASSERT_NE(nullptr, get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - p_sdp_rec, ATTR_ID_BT_PROFILE_DESC_LIST)); + p_sdp_rec, ATTR_ID_BT_PROFILE_DESC_LIST)); // Service Name - ASSERT_EQ( - nullptr, - (const char*)get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( - p_sdp_rec, ATTR_ID_SERVICE_NAME)); + ASSERT_EQ(nullptr, (const char*)get_legacy_stack_sdp_api()->record.SDP_FindAttributeInRec( + p_sdp_rec, ATTR_ID_SERVICE_NAME)); } TEST_F_WITH_FLAGS(StackSdpAsClientParseTest, sdp_disc_server_rsp_packets00b, - REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG( - TEST_BT, stack_sdp_detect_nil_property_type))) { + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, + stack_sdp_detect_nil_property_type))) { parse_sdp_responses(bluetooth::testing::stack::sdp::packets00::rx_pkts, bluetooth::testing::stack::sdp::packets00::kNumRxPkts); diff --git a/system/stack/test/sdp/stack_sdp_test.cc b/system/stack/test/sdp/stack_sdp_test.cc index 7ab871ab0aa..f875c4f60fe 100644 --- a/system/stack/test/sdp/stack_sdp_test.cc +++ b/system/stack/test/sdp/stack_sdp_test.cc @@ -41,27 +41,24 @@ static RawAddress addr = RawAddress({0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6}); static tSDP_DISCOVERY_DB* sdp_db = nullptr; class StackSdpWithMocksTest : public ::testing::Test { - protected: +protected: void SetUp() override { fake_osi_ = std::make_unique(); test::mock::stack_l2cap_api::L2CA_ConnectReqWithSecurity.body = - [](uint16_t /* psm */, const RawAddress& /* p_bd_addr */, - uint16_t /* sec_level */) { - return ++L2CA_ConnectReqWithSecurity_cid; - }; - test::mock::stack_l2cap_api::L2CA_DataWrite.body = - [](uint16_t /* cid */, BT_HDR* p_data) -> tL2CAP_DW_RESULT { + [](uint16_t /* psm */, const RawAddress& /* p_bd_addr */, uint16_t /* sec_level */) { + return ++L2CA_ConnectReqWithSecurity_cid; + }; + test::mock::stack_l2cap_api::L2CA_DataWrite.body = [](uint16_t /* cid */, + BT_HDR* p_data) -> tL2CAP_DW_RESULT { osi_free_and_reset((void**)&p_data); return tL2CAP_DW_RESULT::FAILED; }; - test::mock::stack_l2cap_api::L2CA_DisconnectReq.body = - [](uint16_t /* cid */) { return true; }; + test::mock::stack_l2cap_api::L2CA_DisconnectReq.body = [](uint16_t /* cid */) { return true; }; test::mock::stack_l2cap_api::L2CA_RegisterWithSecurity.body = - [](uint16_t psm, const tL2CAP_APPL_INFO& /* p_cb_info */, - bool /* enable_snoop */, tL2CAP_ERTM_INFO* /* p_ertm_info */, - uint16_t /* my_mtu */, uint16_t /* required_remote_mtu */, - uint16_t /* sec_level */) { return psm; }; + [](uint16_t psm, const tL2CAP_APPL_INFO& /* p_cb_info */, bool /* enable_snoop */, + tL2CAP_ERTM_INFO* /* p_ertm_info */, uint16_t /* my_mtu */, + uint16_t /* required_remote_mtu */, uint16_t /* sec_level */) { return psm; }; } void TearDown() override { @@ -77,7 +74,7 @@ class StackSdpWithMocksTest : public ::testing::Test { }; class StackSdpInitTest : public StackSdpWithMocksTest { - protected: +protected: void SetUp() override { StackSdpWithMocksTest::SetUp(); sdp_init(); @@ -192,93 +189,85 @@ TEST_F(StackSdpInitTest, sdp_service_search_request_queuing_race_condition) { TEST_F(StackSdpInitTest, sdp_disc_wait_text) { std::vector> states = { - std::make_pair(SDP_DISC_WAIT_CONN, "SDP_DISC_WAIT_CONN"), - std::make_pair(SDP_DISC_WAIT_HANDLES, "SDP_DISC_WAIT_HANDLES"), - std::make_pair(SDP_DISC_WAIT_ATTR, "SDP_DISC_WAIT_ATTR"), - std::make_pair(SDP_DISC_WAIT_SEARCH_ATTR, "SDP_DISC_WAIT_SEARCH_ATTR"), - std::make_pair(SDP_DISC_WAIT_CANCEL, "SDP_DISC_WAIT_CANCEL"), + std::make_pair(SDP_DISC_WAIT_CONN, "SDP_DISC_WAIT_CONN"), + std::make_pair(SDP_DISC_WAIT_HANDLES, "SDP_DISC_WAIT_HANDLES"), + std::make_pair(SDP_DISC_WAIT_ATTR, "SDP_DISC_WAIT_ATTR"), + std::make_pair(SDP_DISC_WAIT_SEARCH_ATTR, "SDP_DISC_WAIT_SEARCH_ATTR"), + std::make_pair(SDP_DISC_WAIT_CANCEL, "SDP_DISC_WAIT_CANCEL"), }; for (const auto& state : states) { ASSERT_STREQ(state.second.c_str(), sdp_disc_wait_text(state.first).c_str()); } - auto unknown = - base::StringPrintf("UNKNOWN[%d]", std::numeric_limits::max()); + auto unknown = base::StringPrintf("UNKNOWN[%d]", std::numeric_limits::max()); ASSERT_STREQ(unknown.c_str(), - sdp_disc_wait_text(static_cast( - std::numeric_limits::max())) - .c_str()); + sdp_disc_wait_text(static_cast(std::numeric_limits::max())) + .c_str()); } TEST_F(StackSdpInitTest, sdp_state_text) { std::vector> states = { - std::make_pair(tSDP_STATE::IDLE, "tSDP_STATE::IDLE(0x0)"), - std::make_pair(tSDP_STATE::CONN_SETUP, "tSDP_STATE::CONN_SETUP(0x1)"), - std::make_pair(tSDP_STATE::CFG_SETUP, "tSDP_STATE::CFG_SETUP(0x2)"), - std::make_pair(tSDP_STATE::CONNECTED, "tSDP_STATE::CONNECTED(0x3)"), - std::make_pair(tSDP_STATE::CONN_PEND, "tSDP_STATE::CONN_PEND(0x4)"), + std::make_pair(tSDP_STATE::IDLE, "tSDP_STATE::IDLE(0x0)"), + std::make_pair(tSDP_STATE::CONN_SETUP, "tSDP_STATE::CONN_SETUP(0x1)"), + std::make_pair(tSDP_STATE::CFG_SETUP, "tSDP_STATE::CFG_SETUP(0x2)"), + std::make_pair(tSDP_STATE::CONNECTED, "tSDP_STATE::CONNECTED(0x3)"), + std::make_pair(tSDP_STATE::CONN_PEND, "tSDP_STATE::CONN_PEND(0x4)"), }; for (const auto& state : states) { ASSERT_STREQ(state.second.c_str(), sdp_state_text(state.first).c_str()); } auto unknown = []() { - RETURN_UNKNOWN_TYPE_STRING(tSDP_STATE, - std::numeric_limits::max()); + RETURN_UNKNOWN_TYPE_STRING(tSDP_STATE, std::numeric_limits::max()); }(); ASSERT_STREQ(unknown.c_str(), - sdp_state_text(static_cast( - std::numeric_limits::max())) - .c_str()); + sdp_state_text(static_cast(std::numeric_limits::max())) + .c_str()); } TEST_F(StackSdpInitTest, sdp_flags_text) { std::vector> flags = { - std::make_pair(SDP_FLAGS_IS_ORIG, "SDP_FLAGS_IS_ORIG"), - std::make_pair(SDP_FLAGS_HIS_CFG_DONE, "SDP_FLAGS_HIS_CFG_DONE"), - std::make_pair(SDP_FLAGS_MY_CFG_DONE, "SDP_FLAGS_MY_CFG_DONE"), + std::make_pair(SDP_FLAGS_IS_ORIG, "SDP_FLAGS_IS_ORIG"), + std::make_pair(SDP_FLAGS_HIS_CFG_DONE, "SDP_FLAGS_HIS_CFG_DONE"), + std::make_pair(SDP_FLAGS_MY_CFG_DONE, "SDP_FLAGS_MY_CFG_DONE"), }; for (const auto& flag : flags) { ASSERT_STREQ(flag.second.c_str(), sdp_flags_text(flag.first).c_str()); } - auto unknown = - base::StringPrintf("UNKNOWN[%hhu]", std::numeric_limits::max()); - ASSERT_STREQ(unknown.c_str(), - sdp_flags_text(static_cast( - std::numeric_limits::max())) - .c_str()); + auto unknown = base::StringPrintf("UNKNOWN[%hhu]", std::numeric_limits::max()); + ASSERT_STREQ( + unknown.c_str(), + sdp_flags_text(static_cast(std::numeric_limits::max())).c_str()); } TEST_F(StackSdpInitTest, sdp_status_text) { std::vector> status = { - std::make_pair(SDP_SUCCESS, "SDP_SUCCESS"), - std::make_pair(SDP_INVALID_VERSION, "SDP_INVALID_VERSION"), - std::make_pair(SDP_INVALID_SERV_REC_HDL, "SDP_INVALID_SERV_REC_HDL"), - std::make_pair(SDP_INVALID_REQ_SYNTAX, "SDP_INVALID_REQ_SYNTAX"), - std::make_pair(SDP_INVALID_PDU_SIZE, "SDP_INVALID_PDU_SIZE"), - std::make_pair(SDP_INVALID_CONT_STATE, "SDP_INVALID_CONT_STATE"), - std::make_pair(SDP_NO_RESOURCES, "SDP_NO_RESOURCES"), - std::make_pair(SDP_DI_REG_FAILED, "SDP_DI_REG_FAILED"), - std::make_pair(SDP_DI_DISC_FAILED, "SDP_DI_DISC_FAILED"), - std::make_pair(SDP_NO_DI_RECORD_FOUND, "SDP_NO_DI_RECORD_FOUND"), - std::make_pair(SDP_ERR_ATTR_NOT_PRESENT, "SDP_ERR_ATTR_NOT_PRESENT"), - std::make_pair(SDP_ILLEGAL_PARAMETER, "SDP_ILLEGAL_PARAMETER"), - std::make_pair(HID_SDP_NO_SERV_UUID, "HID_SDP_NO_SERV_UUID"), - std::make_pair(HID_SDP_MANDATORY_MISSING, "HID_SDP_MANDATORY_MISSING"), - std::make_pair(SDP_NO_RECS_MATCH, "SDP_NO_RECS_MATCH"), - std::make_pair(SDP_CONN_FAILED, "SDP_CONN_FAILED"), - std::make_pair(SDP_CFG_FAILED, "SDP_CFG_FAILED"), - std::make_pair(SDP_GENERIC_ERROR, "SDP_GENERIC_ERROR"), - std::make_pair(SDP_DB_FULL, "SDP_DB_FULL"), - std::make_pair(SDP_CANCEL, "SDP_CANCEL"), + std::make_pair(SDP_SUCCESS, "SDP_SUCCESS"), + std::make_pair(SDP_INVALID_VERSION, "SDP_INVALID_VERSION"), + std::make_pair(SDP_INVALID_SERV_REC_HDL, "SDP_INVALID_SERV_REC_HDL"), + std::make_pair(SDP_INVALID_REQ_SYNTAX, "SDP_INVALID_REQ_SYNTAX"), + std::make_pair(SDP_INVALID_PDU_SIZE, "SDP_INVALID_PDU_SIZE"), + std::make_pair(SDP_INVALID_CONT_STATE, "SDP_INVALID_CONT_STATE"), + std::make_pair(SDP_NO_RESOURCES, "SDP_NO_RESOURCES"), + std::make_pair(SDP_DI_REG_FAILED, "SDP_DI_REG_FAILED"), + std::make_pair(SDP_DI_DISC_FAILED, "SDP_DI_DISC_FAILED"), + std::make_pair(SDP_NO_DI_RECORD_FOUND, "SDP_NO_DI_RECORD_FOUND"), + std::make_pair(SDP_ERR_ATTR_NOT_PRESENT, "SDP_ERR_ATTR_NOT_PRESENT"), + std::make_pair(SDP_ILLEGAL_PARAMETER, "SDP_ILLEGAL_PARAMETER"), + std::make_pair(HID_SDP_NO_SERV_UUID, "HID_SDP_NO_SERV_UUID"), + std::make_pair(HID_SDP_MANDATORY_MISSING, "HID_SDP_MANDATORY_MISSING"), + std::make_pair(SDP_NO_RECS_MATCH, "SDP_NO_RECS_MATCH"), + std::make_pair(SDP_CONN_FAILED, "SDP_CONN_FAILED"), + std::make_pair(SDP_CFG_FAILED, "SDP_CFG_FAILED"), + std::make_pair(SDP_GENERIC_ERROR, "SDP_GENERIC_ERROR"), + std::make_pair(SDP_DB_FULL, "SDP_DB_FULL"), + std::make_pair(SDP_CANCEL, "SDP_CANCEL"), }; for (const auto& stat : status) { ASSERT_STREQ(stat.second.c_str(), sdp_status_text(stat.first).c_str()); } - auto unknown = - base::StringPrintf("UNKNOWN[%hu]", std::numeric_limits::max()); - ASSERT_STREQ(unknown.c_str(), - sdp_status_text(static_cast( - std::numeric_limits::max())) - .c_str()); + auto unknown = base::StringPrintf("UNKNOWN[%hu]", std::numeric_limits::max()); + ASSERT_STREQ( + unknown.c_str(), + sdp_status_text(static_cast(std::numeric_limits::max())).c_str()); } static tSDP_DISCOVERY_DB db{}; @@ -296,7 +285,6 @@ static tSDP_DISC_ATTR primary_rec_attr{}; class SDP_GetDiRecord_Tests : public ::testing::Test { protected: - void SetUp() override { db.p_first_rec = &rec; rec.p_first_attr = &uuid_desc_attr; @@ -352,23 +340,23 @@ protected: TEST_F(SDP_GetDiRecord_Tests, SDP_GetDiRecord_Regression_test0) { // tune the type/len and value of each attribute in // each test - uuid_desc_attr.attr_len_type = (UUID_DESC_TYPE<<12) | 2; + uuid_desc_attr.attr_len_type = (UUID_DESC_TYPE << 12) | 2; uuid_desc_attr.attr_value.v.u16 = UUID_SERVCLASS_PNP_INFORMATION; // use a 2-byte string so that it can be // saved in tSDP_DISC_ATVAL - const char *const text = "AB"; + const char* const text = "AB"; int len = strlen(text); - client_exe_url_attr.attr_len_type = (URL_DESC_TYPE<<12) | len; + client_exe_url_attr.attr_len_type = (URL_DESC_TYPE << 12) | len; memcpy(client_exe_url_attr.attr_value.v.array, text, len); // make this attr not found by id service_desc_attr.attr_id = ATTR_ID_SERVICE_DESCRIPTION + 1; - service_desc_attr.attr_len_type = (TEXT_STR_DESC_TYPE<<12) | len; + service_desc_attr.attr_len_type = (TEXT_STR_DESC_TYPE << 12) | len; memcpy(service_desc_attr.attr_value.v.array, text, len); // make a wrong type - doc_url_desc_attr.attr_len_type =(TEXT_STR_DESC_TYPE<<12) | len; + doc_url_desc_attr.attr_len_type = (TEXT_STR_DESC_TYPE << 12) | len; memcpy(doc_url_desc_attr.attr_value.v.array, text, len); // setup unexpected sizes for the following attrs @@ -398,10 +386,10 @@ TEST_F(SDP_GetDiRecord_Tests, SDP_GetDiRecord_Regression_test0) { ASSERT_STREQ(text, device_info.rec.client_executable_url); // service description could not be found - ASSERT_EQ(strlen(device_info.rec.service_description), (size_t) 0); + ASSERT_EQ(strlen(device_info.rec.service_description), (size_t)0); // with a wrong attr type, the attr value won't be accepted - ASSERT_EQ(strlen(device_info.rec.documentation_url), (size_t) 0); + ASSERT_EQ(strlen(device_info.rec.documentation_url), (size_t)0); // none of the following values got setup ASSERT_EQ(device_info.spec_id, 0); diff --git a/system/stack/test/sdp/stack_sdp_utils_test.cc b/system/stack/test/sdp/stack_sdp_utils_test.cc index b32227b7188..06d6aaf3ee6 100644 --- a/system/stack/test/sdp/stack_sdp_utils_test.cc +++ b/system/stack/test/sdp/stack_sdp_utils_test.cc @@ -59,60 +59,54 @@ using testing::DoAll; using testing::Return; using testing::SetArrayArgument; -bool sdp_dynamic_change_hfp_version(const tSDP_ATTRIBUTE* p_attr, - const RawAddress& remote_address); +bool sdp_dynamic_change_hfp_version(const tSDP_ATTRIBUTE* p_attr, const RawAddress& remote_address); void hfp_fallback(bool& is_hfp_fallback, const tSDP_ATTRIBUTE* p_attr); void sdp_callback(const RawAddress& bd_addr, tSDP_RESULT result); tCONN_CB* find_ccb(uint16_t cid, uint8_t state); const char* test_flags_feature_disabled[] = { - "INIT_dynamic_avrcp_version_enhancement=false", - nullptr, + "INIT_dynamic_avrcp_version_enhancement=false", + nullptr, }; const char* test_flags_feature_enabled[] = { - "INIT_dynamic_avrcp_version_enhancement=true", - nullptr, + "INIT_dynamic_avrcp_version_enhancement=true", + nullptr, }; const char* hfp_test_flags_feature_disabled[] = { - "INIT_hfp_dynamic_version=false", - nullptr, + "INIT_hfp_dynamic_version=false", + nullptr, }; const char* hfp_test_flags_feature_enabled[] = { - "INIT_hfp_dynamic_version=true", - nullptr, + "INIT_hfp_dynamic_version=true", + nullptr, }; namespace { // convenience mock class IopMock { - public: - MOCK_METHOD(bool, InteropMatchAddr, - (const interop_feature_t, const RawAddress*)); +public: + MOCK_METHOD(bool, InteropMatchAddr, (const interop_feature_t, const RawAddress*)); MOCK_METHOD(bool, InteropMatchName, (const interop_feature_t, const char*)); MOCK_METHOD(void, InteropDatabaseAdd, (uint16_t, const RawAddress*, size_t)); MOCK_METHOD(void, InteropDatabaseClear, ()); MOCK_METHOD(bool, InteropMatchAddrOrName, (const interop_feature_t, const RawAddress*, bt_status_t (*)(const RawAddress*, bt_property_t*))); - MOCK_METHOD(bool, InteropMatchManufacturer, - (const interop_feature_t, uint16_t)); - MOCK_METHOD(bool, InteropMatchVendorProductIds, - (const interop_feature_t, uint16_t, uint16_t)); - MOCK_METHOD(bool, InteropDatabaseMatchVersion, - (const interop_feature_t, uint16_t)); + MOCK_METHOD(bool, InteropMatchManufacturer, (const interop_feature_t, uint16_t)); + MOCK_METHOD(bool, InteropMatchVendorProductIds, (const interop_feature_t, uint16_t, uint16_t)); + MOCK_METHOD(bool, InteropDatabaseMatchVersion, (const interop_feature_t, uint16_t)); MOCK_METHOD(bool, InteropMatchAddrGetMaxLat, (const interop_feature_t, const RawAddress*, uint16_t*)); MOCK_METHOD(bool, InteropGetAllowlistedMediaPlayersList, (list_t*)); MOCK_METHOD(int, InteropFeatureNameToFeatureId, (const char*)); - MOCK_METHOD(void, InteropDatabaseAddAddr, - (uint16_t, const RawAddress*, size_t)); + MOCK_METHOD(void, InteropDatabaseAddAddr, (uint16_t, const RawAddress*, size_t)); }; class AvrcpVersionMock { - public: +public: MOCK_METHOD0(AvrcpProfileVersionMock, uint16_t(void)); }; @@ -120,44 +114,37 @@ std::unique_ptr localIopMock; std::unique_ptr localAvrcpVersionMock; } // namespace -bool interop_match_addr(const interop_feature_t feature, - const RawAddress* addr) { +bool interop_match_addr(const interop_feature_t feature, const RawAddress* addr) { return localIopMock->InteropMatchAddr(feature, addr); } bool interop_match_name(const interop_feature_t feature, const char* name) { return localIopMock->InteropMatchName(feature, name); } -void interop_database_add(uint16_t feature, const RawAddress* addr, - size_t length) { +void interop_database_add(uint16_t feature, const RawAddress* addr, size_t length) { return localIopMock->InteropDatabaseAdd(feature, addr, length); } void interop_database_clear() { localIopMock->InteropDatabaseClear(); } -bool interop_match_addr_or_name(const interop_feature_t feature, - const RawAddress* addr, - bt_status_t (*get_remote_device_property)( - const RawAddress*, bt_property_t*)) { - return localIopMock->InteropMatchAddrOrName(feature, addr, - get_remote_device_property); +bool interop_match_addr_or_name(const interop_feature_t feature, const RawAddress* addr, + bt_status_t (*get_remote_device_property)(const RawAddress*, + bt_property_t*)) { + return localIopMock->InteropMatchAddrOrName(feature, addr, get_remote_device_property); } -bool interop_match_manufacturer(const interop_feature_t feature, - uint16_t manufacturer) { +bool interop_match_manufacturer(const interop_feature_t feature, uint16_t manufacturer) { return localIopMock->InteropMatchManufacturer(feature, manufacturer); } -bool interop_match_vendor_product_ids(const interop_feature_t feature, - uint16_t vendor_id, uint16_t product_id) { - return localIopMock->InteropMatchVendorProductIds(feature, vendor_id, - product_id); +bool interop_match_vendor_product_ids(const interop_feature_t feature, uint16_t vendor_id, + uint16_t product_id) { + return localIopMock->InteropMatchVendorProductIds(feature, vendor_id, product_id); } -bool interop_database_match_version(const interop_feature_t feature, - uint16_t version) { +bool interop_database_match_version(const interop_feature_t feature, uint16_t version) { return localIopMock->InteropDatabaseMatchVersion(feature, version); } -bool interop_match_addr_get_max_lat(const interop_feature_t feature, - const RawAddress* addr, uint16_t* max_lat) { +bool interop_match_addr_get_max_lat(const interop_feature_t feature, const RawAddress* addr, + uint16_t* max_lat) { return localIopMock->InteropMatchAddrGetMaxLat(feature, addr, max_lat); } @@ -165,50 +152,47 @@ int interop_feature_name_to_feature_id(const char* feature_name) { return localIopMock->InteropFeatureNameToFeatureId(feature_name); } -void interop_database_add_addr(uint16_t feature, const RawAddress* addr, - size_t length) { +void interop_database_add_addr(uint16_t feature, const RawAddress* addr, size_t length) { return localIopMock->InteropDatabaseAddAddr(feature, addr, length); } -uint16_t AVRC_GetProfileVersion() { - return localAvrcpVersionMock->AvrcpProfileVersionMock(); -} +uint16_t AVRC_GetProfileVersion() { return localAvrcpVersionMock->AvrcpProfileVersionMock(); } uint8_t avrc_value[8] = { - ((DATA_ELE_SEQ_DESC_TYPE << 3) | SIZE_IN_NEXT_BYTE), // data_element - 6, // data_len - ((UUID_DESC_TYPE << 3) | SIZE_TWO_BYTES), // uuid_element - 0, // uuid - 0, // uuid - ((UINT_DESC_TYPE << 3) | SIZE_TWO_BYTES), // version_element - 0, // version - 0 // version + ((DATA_ELE_SEQ_DESC_TYPE << 3) | SIZE_IN_NEXT_BYTE), // data_element + 6, // data_len + ((UUID_DESC_TYPE << 3) | SIZE_TWO_BYTES), // uuid_element + 0, // uuid + 0, // uuid + ((UINT_DESC_TYPE << 3) | SIZE_TWO_BYTES), // version_element + 0, // version + 0 // version }; tSDP_ATTRIBUTE avrcp_attr = { - .len = 0, - .value_ptr = (uint8_t*)(&avrc_value), - .id = 0, - .type = 0, + .len = 0, + .value_ptr = (uint8_t*)(&avrc_value), + .id = 0, + .type = 0, }; uint8_t avrc_feat_value[2] = { - 0, // feature - 0 // feature + 0, // feature + 0 // feature }; tSDP_ATTRIBUTE avrcp_feat_attr = { - .len = 0, - .value_ptr = (uint8_t*)(&avrc_feat_value), - .id = 0, - .type = 0, + .len = 0, + .value_ptr = (uint8_t*)(&avrc_feat_value), + .id = 0, + .type = 0, }; uint8_t hfp_value[8] = {0, 0, 0, 0x11, 0x1E, 0, 0, 0}; tSDP_ATTRIBUTE hfp_attr = { - .len = 0, - .value_ptr = (uint8_t*)(hfp_value), - .id = 0, - .type = 0, + .len = 0, + .value_ptr = (uint8_t*)(hfp_value), + .id = 0, + .type = 0, }; void set_hfp_attr(uint32_t len, uint16_t id, uint16_t uuid) { @@ -223,8 +207,7 @@ void set_avrcp_feat_attr(uint32_t len, uint16_t id, uint16_t feature) { avrcp_feat_attr.id = id; } -void set_avrcp_attr(uint32_t len, uint16_t id, uint16_t uuid, - uint16_t version) { +void set_avrcp_attr(uint32_t len, uint16_t id, uint16_t uuid, uint16_t version) { UINT16_TO_BE_FIELD(avrc_value + 3, uuid); UINT16_TO_BE_FIELD(avrc_value + 6, version); avrcp_attr.len = len; @@ -233,41 +216,36 @@ void set_avrcp_attr(uint32_t len, uint16_t id, uint16_t uuid, uint16_t get_avrc_target_version(tSDP_ATTRIBUTE* p_attr) { uint8_t* p_version = p_attr->value_ptr + 6; - uint16_t version = - (((uint16_t)(*(p_version))) << 8) + ((uint16_t)(*((p_version) + 1))); + uint16_t version = (((uint16_t)(*(p_version))) << 8) + ((uint16_t)(*((p_version) + 1))); return version; } uint16_t get_avrc_target_feature(tSDP_ATTRIBUTE* p_attr) { uint8_t* p_feature = p_attr->value_ptr; - uint16_t feature = - (((uint16_t)(*(p_feature))) << 8) + ((uint16_t)(*((p_feature) + 1))); + uint16_t feature = (((uint16_t)(*(p_feature))) << 8) + ((uint16_t)(*((p_feature) + 1))); return feature; } class StackSdpMockAndFakeTest : public ::testing::Test { - protected: +protected: void SetUp() override { fake_osi_ = std::make_unique(); test::mock::stack_l2cap_api::L2CA_ConnectReqWithSecurity.body = - [](uint16_t /* psm */, const RawAddress& /* p_bd_addr */, - uint16_t /* sec_level */) { - return ++L2CA_ConnectReqWithSecurity_cid; - }; - test::mock::stack_l2cap_api::L2CA_DataWrite.body = - [](uint16_t /* cid */, BT_HDR* p_data) -> tL2CAP_DW_RESULT { + [](uint16_t /* psm */, const RawAddress& /* p_bd_addr */, uint16_t /* sec_level */) { + return ++L2CA_ConnectReqWithSecurity_cid; + }; + test::mock::stack_l2cap_api::L2CA_DataWrite.body = [](uint16_t /* cid */, + BT_HDR* p_data) -> tL2CAP_DW_RESULT { osi_free_and_reset((void**)&p_data); return tL2CAP_DW_RESULT::FAILED; }; - test::mock::stack_l2cap_api::L2CA_DisconnectReq.body = - [](uint16_t /* cid */) { return true; }; + test::mock::stack_l2cap_api::L2CA_DisconnectReq.body = [](uint16_t /* cid */) { return true; }; test::mock::stack_l2cap_api::L2CA_RegisterWithSecurity.body = - [](uint16_t /* psm */, const tL2CAP_APPL_INFO& /* p_cb_info */, - bool /* enable_snoop */, tL2CAP_ERTM_INFO* /* p_ertm_info */, - uint16_t /* my_mtu */, uint16_t /* required_remote_mtu */, - uint16_t /* sec_level */) { - return 42; // return non zero - }; + [](uint16_t /* psm */, const tL2CAP_APPL_INFO& /* p_cb_info */, bool /* enable_snoop */, + tL2CAP_ERTM_INFO* /* p_ertm_info */, uint16_t /* my_mtu */, + uint16_t /* required_remote_mtu */, uint16_t /* sec_level */) { + return 42; // return non zero + }; } void TearDown() override { @@ -280,7 +258,7 @@ class StackSdpMockAndFakeTest : public ::testing::Test { }; class StackSdpInitTest : public StackSdpMockAndFakeTest { - protected: +protected: void SetUp() override { StackSdpMockAndFakeTest::SetUp(); sdp_init(); @@ -294,37 +272,33 @@ class StackSdpInitTest : public StackSdpMockAndFakeTest { }; class StackSdpUtilsTest : public StackSdpInitTest { - protected: +protected: void SetUp() override { StackSdpInitTest::SetUp(); bluetooth::common::InitFlags::Load(hfp_test_flags_feature_disabled); bluetooth::common::InitFlags::Load(test_flags_feature_disabled); - GetInterfaceToProfiles()->profileSpecific_HACK->AVRC_GetProfileVersion = - AVRC_GetProfileVersion; - test::mock::btif_config::btif_config_get_bin.body = - [this](const std::string& section, const std::string& key, - uint8_t* value, size_t* length) { - return btif_config_interface_.GetBin(section, key, value, length); - }; - test::mock::btif_config::btif_config_get_bin_length.body = - [this](const std::string& section, const std::string& key) { - return btif_config_interface_.GetBinLength(section, key); - }; + GetInterfaceToProfiles()->profileSpecific_HACK->AVRC_GetProfileVersion = AVRC_GetProfileVersion; + test::mock::btif_config::btif_config_get_bin.body = [this](const std::string& section, + const std::string& key, + uint8_t* value, size_t* length) { + return btif_config_interface_.GetBin(section, key, value, length); + }; + test::mock::btif_config::btif_config_get_bin_length.body = [this](const std::string& section, + const std::string& key) { + return btif_config_interface_.GetBinLength(section, key); + }; test::mock::osi_properties::osi_property_get_bool.body = - [](const char* /* key */, bool /* default_value */) { return true; }; + [](const char* /* key */, bool /* default_value */) { return true; }; localIopMock = std::make_unique(); localAvrcpVersionMock = std::make_unique(); - set_avrcp_attr(8, ATTR_ID_BT_PROFILE_DESC_LIST, - UUID_SERVCLASS_AV_REMOTE_CONTROL, AVRC_REV_1_5); + set_avrcp_attr(8, ATTR_ID_BT_PROFILE_DESC_LIST, UUID_SERVCLASS_AV_REMOTE_CONTROL, AVRC_REV_1_5); set_avrcp_feat_attr(2, ATTR_ID_SUPPORTED_FEATURES, AVRCP_SUPF_TG_1_5); - set_hfp_attr(SDP_PROFILE_DESC_LENGTH, ATTR_ID_BT_PROFILE_DESC_LIST, - UUID_HF_LSB); + set_hfp_attr(SDP_PROFILE_DESC_LENGTH, ATTR_ID_BT_PROFILE_DESC_LIST, UUID_HF_LSB); } void TearDown() override { - GetInterfaceToProfiles()->profileSpecific_HACK->AVRC_GetProfileVersion = - nullptr; + GetInterfaceToProfiles()->profileSpecific_HACK->AVRC_GetProfileVersion = nullptr; test::mock::btif_config::btif_config_get_bin_length = {}; test::mock::btif_config::btif_config_get_bin = {}; test::mock::osi_properties::osi_property_get_bool = {}; @@ -336,46 +310,41 @@ class StackSdpUtilsTest : public StackSdpInitTest { bluetooth::manager::MockBtifConfigInterface btif_config_interface_; }; -TEST_F(StackSdpUtilsTest, - sdpu_set_avrc_target_version_device_in_iop_table_versoin_1_4) { +TEST_F(StackSdpUtilsTest, sdpu_set_avrc_target_version_device_in_iop_table_versoin_1_4) { RawAddress bdaddr; EXPECT_CALL(*localIopMock, InteropMatchAddr(INTEROP_AVRCP_1_4_ONLY, &bdaddr)) - .WillOnce(Return(true)); + .WillOnce(Return(true)); sdpu_set_avrc_target_version(&avrcp_attr, &bdaddr); ASSERT_EQ(get_avrc_target_version(&avrcp_attr), AVRC_REV_1_4); } -TEST_F(StackSdpUtilsTest, - sdpu_set_avrc_target_version_device_in_iop_table_versoin_1_3) { +TEST_F(StackSdpUtilsTest, sdpu_set_avrc_target_version_device_in_iop_table_versoin_1_3) { RawAddress bdaddr; EXPECT_CALL(*localIopMock, InteropMatchAddr(INTEROP_AVRCP_1_4_ONLY, &bdaddr)) - .WillOnce(Return(false)); + .WillOnce(Return(false)); EXPECT_CALL(*localIopMock, InteropMatchAddr(INTEROP_AVRCP_1_3_ONLY, &bdaddr)) - .WillOnce(Return(true)); + .WillOnce(Return(true)); sdpu_set_avrc_target_version(&avrcp_attr, &bdaddr); ASSERT_EQ(get_avrc_target_version(&avrcp_attr), AVRC_REV_1_3); } TEST_F(StackSdpUtilsTest, sdpu_set_avrc_target_version_wrong_len) { RawAddress bdaddr; - set_avrcp_attr(5, ATTR_ID_BT_PROFILE_DESC_LIST, - UUID_SERVCLASS_AV_REMOTE_CONTROL, AVRC_REV_1_5); + set_avrcp_attr(5, ATTR_ID_BT_PROFILE_DESC_LIST, UUID_SERVCLASS_AV_REMOTE_CONTROL, AVRC_REV_1_5); sdpu_set_avrc_target_version(&avrcp_attr, &bdaddr); ASSERT_EQ(get_avrc_target_version(&avrcp_attr), AVRC_REV_1_5); } TEST_F(StackSdpUtilsTest, sdpu_set_avrc_target_version_wrong_attribute_id) { RawAddress bdaddr; - set_avrcp_attr(8, ATTR_ID_SERVICE_CLASS_ID_LIST, - UUID_SERVCLASS_AV_REMOTE_CONTROL, AVRC_REV_1_5); + set_avrcp_attr(8, ATTR_ID_SERVICE_CLASS_ID_LIST, UUID_SERVCLASS_AV_REMOTE_CONTROL, AVRC_REV_1_5); sdpu_set_avrc_target_version(&avrcp_attr, &bdaddr); ASSERT_EQ(get_avrc_target_version(&avrcp_attr), AVRC_REV_1_5); } TEST_F(StackSdpUtilsTest, sdpu_set_avrc_target_version_wrong_uuid) { RawAddress bdaddr; - set_avrcp_attr(8, ATTR_ID_BT_PROFILE_DESC_LIST, UUID_SERVCLASS_AUDIO_SOURCE, - AVRC_REV_1_5); + set_avrcp_attr(8, ATTR_ID_BT_PROFILE_DESC_LIST, UUID_SERVCLASS_AUDIO_SOURCE, AVRC_REV_1_5); sdpu_set_avrc_target_version(&avrcp_attr, &bdaddr); ASSERT_EQ(get_avrc_target_version(&avrcp_attr), AVRC_REV_1_5); } @@ -385,14 +354,12 @@ TEST_F(StackSdpUtilsTest, sdpu_set_avrc_target_version_device_older_version) { RawAddress bdaddr; uint8_t config_0104[2] = {0x04, 0x01}; EXPECT_CALL(*localIopMock, InteropMatchAddr(INTEROP_AVRCP_1_4_ONLY, &bdaddr)) - .WillOnce(Return(false)); + .WillOnce(Return(false)); EXPECT_CALL(*localIopMock, InteropMatchAddr(INTEROP_AVRCP_1_3_ONLY, &bdaddr)) - .WillOnce(Return(false)); - EXPECT_CALL(btif_config_interface_, GetBinLength(bdaddr.ToString(), _)) - .WillOnce(Return(2)); + .WillOnce(Return(false)); + EXPECT_CALL(btif_config_interface_, GetBinLength(bdaddr.ToString(), _)).WillOnce(Return(2)); EXPECT_CALL(btif_config_interface_, GetBin(bdaddr.ToString(), _, _, _)) - .WillOnce(DoAll(SetArrayArgument<2>(config_0104, config_0104 + 2), - Return(true))); + .WillOnce(DoAll(SetArrayArgument<2>(config_0104, config_0104 + 2), Return(true))); sdpu_set_avrc_target_version(&avrcp_attr, &bdaddr); ASSERT_EQ(get_avrc_target_version(&avrcp_attr), AVRC_REV_1_4); } @@ -402,14 +369,12 @@ TEST_F(StackSdpUtilsTest, sdpu_set_avrc_target_version_device_same_version) { RawAddress bdaddr; uint8_t config_0105[2] = {0x05, 0x01}; EXPECT_CALL(*localIopMock, InteropMatchAddr(INTEROP_AVRCP_1_4_ONLY, &bdaddr)) - .WillOnce(Return(false)); + .WillOnce(Return(false)); EXPECT_CALL(*localIopMock, InteropMatchAddr(INTEROP_AVRCP_1_3_ONLY, &bdaddr)) - .WillOnce(Return(false)); - EXPECT_CALL(btif_config_interface_, GetBinLength(bdaddr.ToString(), _)) - .WillOnce(Return(2)); + .WillOnce(Return(false)); + EXPECT_CALL(btif_config_interface_, GetBinLength(bdaddr.ToString(), _)).WillOnce(Return(2)); EXPECT_CALL(btif_config_interface_, GetBin(bdaddr.ToString(), _, _, _)) - .WillOnce(DoAll(SetArrayArgument<2>(config_0105, config_0105 + 2), - Return(true))); + .WillOnce(DoAll(SetArrayArgument<2>(config_0105, config_0105 + 2), Return(true))); sdpu_set_avrc_target_version(&avrcp_attr, &bdaddr); ASSERT_EQ(get_avrc_target_version(&avrcp_attr), AVRC_REV_1_5); } @@ -419,14 +384,12 @@ TEST_F(StackSdpUtilsTest, sdpu_set_avrc_target_version_device_newer_version) { RawAddress bdaddr; uint8_t config_0106[2] = {0x06, 0x01}; EXPECT_CALL(*localIopMock, InteropMatchAddr(INTEROP_AVRCP_1_4_ONLY, &bdaddr)) - .WillOnce(Return(false)); + .WillOnce(Return(false)); EXPECT_CALL(*localIopMock, InteropMatchAddr(INTEROP_AVRCP_1_3_ONLY, &bdaddr)) - .WillOnce(Return(false)); - EXPECT_CALL(btif_config_interface_, GetBinLength(bdaddr.ToString(), _)) - .WillOnce(Return(2)); + .WillOnce(Return(false)); + EXPECT_CALL(btif_config_interface_, GetBinLength(bdaddr.ToString(), _)).WillOnce(Return(2)); EXPECT_CALL(btif_config_interface_, GetBin(bdaddr.ToString(), _, _, _)) - .WillOnce(DoAll(SetArrayArgument<2>(config_0106, config_0106 + 2), - Return(true))); + .WillOnce(DoAll(SetArrayArgument<2>(config_0106, config_0106 + 2), Return(true))); sdpu_set_avrc_target_version(&avrcp_attr, &bdaddr); ASSERT_EQ(get_avrc_target_version(&avrcp_attr), AVRC_REV_1_5); } @@ -435,11 +398,10 @@ TEST_F(StackSdpUtilsTest, sdpu_set_avrc_target_version_device_newer_version) { TEST_F(StackSdpUtilsTest, sdpu_set_avrc_target_version_no_config_value) { RawAddress bdaddr; EXPECT_CALL(*localIopMock, InteropMatchAddr(INTEROP_AVRCP_1_4_ONLY, &bdaddr)) - .WillOnce(Return(false)); + .WillOnce(Return(false)); EXPECT_CALL(*localIopMock, InteropMatchAddr(INTEROP_AVRCP_1_3_ONLY, &bdaddr)) - .WillOnce(Return(false)); - EXPECT_CALL(btif_config_interface_, GetBinLength(bdaddr.ToString(), _)) - .WillOnce(Return(0)); + .WillOnce(Return(false)); + EXPECT_CALL(btif_config_interface_, GetBinLength(bdaddr.ToString(), _)).WillOnce(Return(0)); sdpu_set_avrc_target_version(&avrcp_attr, &bdaddr); ASSERT_EQ(get_avrc_target_version(&avrcp_attr), AVRC_REV_1_5); } @@ -448,11 +410,10 @@ TEST_F(StackSdpUtilsTest, sdpu_set_avrc_target_version_no_config_value) { TEST_F(StackSdpUtilsTest, sdpu_set_avrc_target_version_config_value_1_byte) { RawAddress bdaddr; EXPECT_CALL(*localIopMock, InteropMatchAddr(INTEROP_AVRCP_1_4_ONLY, &bdaddr)) - .WillOnce(Return(false)); + .WillOnce(Return(false)); EXPECT_CALL(*localIopMock, InteropMatchAddr(INTEROP_AVRCP_1_3_ONLY, &bdaddr)) - .WillOnce(Return(false)); - EXPECT_CALL(btif_config_interface_, GetBinLength(bdaddr.ToString(), _)) - .WillOnce(Return(1)); + .WillOnce(Return(false)); + EXPECT_CALL(btif_config_interface_, GetBinLength(bdaddr.ToString(), _)).WillOnce(Return(1)); sdpu_set_avrc_target_version(&avrcp_attr, &bdaddr); ASSERT_EQ(get_avrc_target_version(&avrcp_attr), AVRC_REV_1_5); } @@ -461,11 +422,10 @@ TEST_F(StackSdpUtilsTest, sdpu_set_avrc_target_version_config_value_1_byte) { TEST_F(StackSdpUtilsTest, sdpu_set_avrc_target_version_config_value_3_bytes) { RawAddress bdaddr; EXPECT_CALL(*localIopMock, InteropMatchAddr(INTEROP_AVRCP_1_4_ONLY, &bdaddr)) - .WillOnce(Return(false)); + .WillOnce(Return(false)); EXPECT_CALL(*localIopMock, InteropMatchAddr(INTEROP_AVRCP_1_3_ONLY, &bdaddr)) - .WillOnce(Return(false)); - EXPECT_CALL(btif_config_interface_, GetBinLength(bdaddr.ToString(), _)) - .WillOnce(Return(3)); + .WillOnce(Return(false)); + EXPECT_CALL(btif_config_interface_, GetBinLength(bdaddr.ToString(), _)).WillOnce(Return(3)); sdpu_set_avrc_target_version(&avrcp_attr, &bdaddr); ASSERT_EQ(get_avrc_target_version(&avrcp_attr), AVRC_REV_1_5); } @@ -475,15 +435,13 @@ TEST_F(StackSdpUtilsTest, sdpu_set_avrc_target_version_config_value_not_valid) { RawAddress bdaddr; uint8_t config_not_valid[2] = {0x12, 0x34}; EXPECT_CALL(*localIopMock, InteropMatchAddr(INTEROP_AVRCP_1_4_ONLY, &bdaddr)) - .WillOnce(Return(false)); + .WillOnce(Return(false)); EXPECT_CALL(*localIopMock, InteropMatchAddr(INTEROP_AVRCP_1_3_ONLY, &bdaddr)) - .WillOnce(Return(false)); - EXPECT_CALL(btif_config_interface_, GetBinLength(bdaddr.ToString(), _)) - .WillOnce(Return(2)); + .WillOnce(Return(false)); + EXPECT_CALL(btif_config_interface_, GetBinLength(bdaddr.ToString(), _)).WillOnce(Return(2)); EXPECT_CALL(btif_config_interface_, GetBin(bdaddr.ToString(), _, _, _)) - .WillOnce( - DoAll(SetArrayArgument<2>(config_not_valid, config_not_valid + 2), - Return(true))); + .WillOnce( + DoAll(SetArrayArgument<2>(config_not_valid, config_not_valid + 2), Return(true))); sdpu_set_avrc_target_version(&avrcp_attr, &bdaddr); ASSERT_EQ(get_avrc_target_version(&avrcp_attr), AVRC_REV_1_5); } @@ -491,72 +449,58 @@ TEST_F(StackSdpUtilsTest, sdpu_set_avrc_target_version_config_value_not_valid) { TEST_F(StackSdpUtilsTest, sdpu_set_avrc_target_feature_wrong_len) { bluetooth::common::InitFlags::Load(test_flags_feature_enabled); RawAddress bdaddr; - set_avrcp_attr(8, ATTR_ID_BT_PROFILE_DESC_LIST, - UUID_SERVCLASS_AV_REMOTE_CONTROL, AVRC_REV_1_5); + set_avrcp_attr(8, ATTR_ID_BT_PROFILE_DESC_LIST, UUID_SERVCLASS_AV_REMOTE_CONTROL, AVRC_REV_1_5); sdpu_set_avrc_target_version(&avrcp_attr, &bdaddr); set_avrcp_feat_attr(6, ATTR_ID_SUPPORTED_FEATURES, AVRCP_SUPF_TG_1_5); ASSERT_EQ(get_avrc_target_version(&avrcp_attr), AVRC_REV_1_5); - sdpu_set_avrc_target_features(&avrcp_feat_attr, &bdaddr, - get_avrc_target_version(&avrcp_attr)); + sdpu_set_avrc_target_features(&avrcp_feat_attr, &bdaddr, get_avrc_target_version(&avrcp_attr)); ASSERT_EQ(get_avrc_target_feature(&avrcp_feat_attr), AVRCP_SUPF_TG_1_5); } TEST_F(StackSdpUtilsTest, sdpu_set_avrc_target_feature_wrong_attribute_id) { bluetooth::common::InitFlags::Load(test_flags_feature_enabled); RawAddress bdaddr; - set_avrcp_attr(8, ATTR_ID_BT_PROFILE_DESC_LIST, - UUID_SERVCLASS_AV_REMOTE_CONTROL, AVRC_REV_1_5); + set_avrcp_attr(8, ATTR_ID_BT_PROFILE_DESC_LIST, UUID_SERVCLASS_AV_REMOTE_CONTROL, AVRC_REV_1_5); sdpu_set_avrc_target_version(&avrcp_attr, &bdaddr); set_avrcp_feat_attr(2, ATTR_ID_BT_PROFILE_DESC_LIST, AVRCP_SUPF_TG_1_5); ASSERT_EQ(get_avrc_target_version(&avrcp_attr), AVRC_REV_1_5); - sdpu_set_avrc_target_features(&avrcp_feat_attr, &bdaddr, - get_avrc_target_version(&avrcp_attr)); + sdpu_set_avrc_target_features(&avrcp_feat_attr, &bdaddr, get_avrc_target_version(&avrcp_attr)); ASSERT_EQ(get_avrc_target_feature(&avrcp_feat_attr), AVRCP_SUPF_TG_1_5); } -TEST_F(StackSdpUtilsTest, - sdpu_set_avrc_target_feature_device_in_iop_table_versoin_1_4) { +TEST_F(StackSdpUtilsTest, sdpu_set_avrc_target_feature_device_in_iop_table_versoin_1_4) { bluetooth::common::InitFlags::Load(test_flags_feature_enabled); RawAddress bdaddr; uint8_t feature_0105[2] = {0xC1, 0x00}; - EXPECT_CALL(*localAvrcpVersionMock, AvrcpProfileVersionMock()) - .WillOnce(Return(AVRC_REV_1_5)); + EXPECT_CALL(*localAvrcpVersionMock, AvrcpProfileVersionMock()).WillOnce(Return(AVRC_REV_1_5)); EXPECT_CALL(*localIopMock, InteropMatchAddr(INTEROP_AVRCP_1_4_ONLY, &bdaddr)) - .WillOnce(Return(true)); + .WillOnce(Return(true)); sdpu_set_avrc_target_version(&avrcp_attr, &bdaddr); ASSERT_EQ(get_avrc_target_version(&avrcp_attr), AVRC_REV_1_4); set_avrcp_feat_attr(2, ATTR_ID_SUPPORTED_FEATURES, AVRCP_SUPF_TG_1_5); - EXPECT_CALL(btif_config_interface_, GetBinLength(bdaddr.ToString(), _)) - .WillOnce(Return(2)); + EXPECT_CALL(btif_config_interface_, GetBinLength(bdaddr.ToString(), _)).WillOnce(Return(2)); EXPECT_CALL(btif_config_interface_, GetBin(bdaddr.ToString(), _, _, _)) - .WillOnce(DoAll(SetArrayArgument<2>(feature_0105, feature_0105 + 2), - Return(true))); - sdpu_set_avrc_target_features(&avrcp_feat_attr, &bdaddr, - get_avrc_target_version(&avrcp_attr)); + .WillOnce(DoAll(SetArrayArgument<2>(feature_0105, feature_0105 + 2), Return(true))); + sdpu_set_avrc_target_features(&avrcp_feat_attr, &bdaddr, get_avrc_target_version(&avrcp_attr)); ASSERT_EQ(get_avrc_target_feature(&avrcp_feat_attr), AVRCP_SUPF_TG_1_4); } -TEST_F(StackSdpUtilsTest, - sdpu_set_avrc_target_feature_device_in_iop_table_versoin_1_3) { +TEST_F(StackSdpUtilsTest, sdpu_set_avrc_target_feature_device_in_iop_table_versoin_1_3) { bluetooth::common::InitFlags::Load(test_flags_feature_enabled); RawAddress bdaddr; uint8_t feature_0105[2] = {0xC1, 0x00}; - EXPECT_CALL(*localAvrcpVersionMock, AvrcpProfileVersionMock()) - .WillOnce(Return(AVRC_REV_1_5)); + EXPECT_CALL(*localAvrcpVersionMock, AvrcpProfileVersionMock()).WillOnce(Return(AVRC_REV_1_5)); EXPECT_CALL(*localIopMock, InteropMatchAddr(INTEROP_AVRCP_1_4_ONLY, &bdaddr)) - .WillOnce(Return(false)); + .WillOnce(Return(false)); EXPECT_CALL(*localIopMock, InteropMatchAddr(INTEROP_AVRCP_1_3_ONLY, &bdaddr)) - .WillOnce(Return(true)); + .WillOnce(Return(true)); sdpu_set_avrc_target_version(&avrcp_attr, &bdaddr); ASSERT_EQ(get_avrc_target_version(&avrcp_attr), AVRC_REV_1_3); set_avrcp_feat_attr(2, ATTR_ID_SUPPORTED_FEATURES, AVRCP_SUPF_TG_1_5); - EXPECT_CALL(btif_config_interface_, GetBinLength(bdaddr.ToString(), _)) - .WillOnce(Return(2)); + EXPECT_CALL(btif_config_interface_, GetBinLength(bdaddr.ToString(), _)).WillOnce(Return(2)); EXPECT_CALL(btif_config_interface_, GetBin(bdaddr.ToString(), _, _, _)) - .WillOnce(DoAll(SetArrayArgument<2>(feature_0105, feature_0105 + 2), - Return(true))); - sdpu_set_avrc_target_features(&avrcp_feat_attr, &bdaddr, - get_avrc_target_version(&avrcp_attr)); + .WillOnce(DoAll(SetArrayArgument<2>(feature_0105, feature_0105 + 2), Return(true))); + sdpu_set_avrc_target_features(&avrcp_feat_attr, &bdaddr, get_avrc_target_version(&avrcp_attr)); ASSERT_EQ(get_avrc_target_feature(&avrcp_feat_attr), AVRCP_SUPF_TG_1_3); } @@ -564,15 +508,12 @@ TEST_F(StackSdpUtilsTest, TEST_F(StackSdpUtilsTest, sdpu_set_avrc_target_feature_no_config_value) { bluetooth::common::InitFlags::Load(test_flags_feature_enabled); RawAddress bdaddr; - EXPECT_CALL(*localAvrcpVersionMock, AvrcpProfileVersionMock()) - .WillOnce(Return(AVRC_REV_1_5)); + EXPECT_CALL(*localAvrcpVersionMock, AvrcpProfileVersionMock()).WillOnce(Return(AVRC_REV_1_5)); sdpu_set_avrc_target_version(&avrcp_attr, &bdaddr); ASSERT_EQ(get_avrc_target_version(&avrcp_attr), AVRC_REV_1_5); - EXPECT_CALL(btif_config_interface_, GetBinLength(bdaddr.ToString(), _)) - .WillOnce(Return(0)); + EXPECT_CALL(btif_config_interface_, GetBinLength(bdaddr.ToString(), _)).WillOnce(Return(0)); set_avrcp_feat_attr(2, ATTR_ID_SUPPORTED_FEATURES, AVRCP_SUPF_TG_1_5); - sdpu_set_avrc_target_features(&avrcp_feat_attr, &bdaddr, - get_avrc_target_version(&avrcp_attr)); + sdpu_set_avrc_target_features(&avrcp_feat_attr, &bdaddr, get_avrc_target_version(&avrcp_attr)); ASSERT_EQ(get_avrc_target_feature(&avrcp_feat_attr), AVRCP_SUPF_TG_1_5); } @@ -580,15 +521,12 @@ TEST_F(StackSdpUtilsTest, sdpu_set_avrc_target_feature_no_config_value) { TEST_F(StackSdpUtilsTest, sdpu_set_avrc_target_feature_config_value_1_byte) { bluetooth::common::InitFlags::Load(test_flags_feature_enabled); RawAddress bdaddr; - EXPECT_CALL(*localAvrcpVersionMock, AvrcpProfileVersionMock()) - .WillOnce(Return(AVRC_REV_1_5)); + EXPECT_CALL(*localAvrcpVersionMock, AvrcpProfileVersionMock()).WillOnce(Return(AVRC_REV_1_5)); sdpu_set_avrc_target_version(&avrcp_attr, &bdaddr); ASSERT_EQ(get_avrc_target_version(&avrcp_attr), AVRC_REV_1_5); - EXPECT_CALL(btif_config_interface_, GetBinLength(bdaddr.ToString(), _)) - .WillOnce(Return(1)); + EXPECT_CALL(btif_config_interface_, GetBinLength(bdaddr.ToString(), _)).WillOnce(Return(1)); set_avrcp_feat_attr(2, ATTR_ID_SUPPORTED_FEATURES, AVRCP_SUPF_TG_1_5); - sdpu_set_avrc_target_features(&avrcp_feat_attr, &bdaddr, - get_avrc_target_version(&avrcp_attr)); + sdpu_set_avrc_target_features(&avrcp_feat_attr, &bdaddr, get_avrc_target_version(&avrcp_attr)); ASSERT_EQ(get_avrc_target_feature(&avrcp_feat_attr), AVRCP_SUPF_TG_1_5); } @@ -597,27 +535,21 @@ TEST_F(StackSdpUtilsTest, sdpu_set_avrc_target_feature_device_versoin_1_6) { RawAddress bdaddr; uint8_t config_0106[2] = {0x06, 0x01}; uint8_t feature_0106[2] = {0xC1, 0x01}; - EXPECT_CALL(*localAvrcpVersionMock, AvrcpProfileVersionMock()) - .WillOnce(Return(AVRC_REV_1_6)); + EXPECT_CALL(*localAvrcpVersionMock, AvrcpProfileVersionMock()).WillOnce(Return(AVRC_REV_1_6)); EXPECT_CALL(*localIopMock, InteropMatchAddr(INTEROP_AVRCP_1_4_ONLY, &bdaddr)) - .WillOnce(Return(false)); + .WillOnce(Return(false)); EXPECT_CALL(*localIopMock, InteropMatchAddr(INTEROP_AVRCP_1_3_ONLY, &bdaddr)) - .WillOnce(Return(false)); - EXPECT_CALL(btif_config_interface_, GetBinLength(bdaddr.ToString(), _)) - .WillOnce(Return(2)); + .WillOnce(Return(false)); + EXPECT_CALL(btif_config_interface_, GetBinLength(bdaddr.ToString(), _)).WillOnce(Return(2)); EXPECT_CALL(btif_config_interface_, GetBin(bdaddr.ToString(), _, _, _)) - .WillOnce(DoAll(SetArrayArgument<2>(config_0106, config_0106 + 2), - Return(true))); + .WillOnce(DoAll(SetArrayArgument<2>(config_0106, config_0106 + 2), Return(true))); sdpu_set_avrc_target_version(&avrcp_attr, &bdaddr); ASSERT_EQ(get_avrc_target_version(&avrcp_attr), AVRC_REV_1_6); set_avrcp_feat_attr(2, ATTR_ID_SUPPORTED_FEATURES, AVRCP_SUPF_TG_1_5); - EXPECT_CALL(btif_config_interface_, GetBinLength(bdaddr.ToString(), _)) - .WillOnce(Return(2)); + EXPECT_CALL(btif_config_interface_, GetBinLength(bdaddr.ToString(), _)).WillOnce(Return(2)); EXPECT_CALL(btif_config_interface_, GetBin(bdaddr.ToString(), _, _, _)) - .WillOnce(DoAll(SetArrayArgument<2>(feature_0106, feature_0106 + 2), - Return(true))); - sdpu_set_avrc_target_features(&avrcp_feat_attr, &bdaddr, - get_avrc_target_version(&avrcp_attr)); + .WillOnce(DoAll(SetArrayArgument<2>(feature_0106, feature_0106 + 2), Return(true))); + sdpu_set_avrc_target_features(&avrcp_feat_attr, &bdaddr, get_avrc_target_version(&avrcp_attr)); ASSERT_EQ(get_avrc_target_feature(&avrcp_feat_attr), AVRCP_SUPF_TG_1_6 | AVRC_SUPF_TG_PLAYER_COVER_ART); } @@ -632,78 +564,66 @@ TEST_F(StackSdpUtilsTest, dynamic_hfp_version_with_invalid_length) { TEST_F(StackSdpUtilsTest, dynamic_hfp_version_with_invalid_UUID) { bluetooth::common::InitFlags::Load(hfp_test_flags_feature_enabled); RawAddress bdaddr(RawAddress::kEmpty); - set_hfp_attr(SDP_PROFILE_DESC_LENGTH, ATTR_ID_BT_PROFILE_DESC_LIST, - INVALID_UUID); + set_hfp_attr(SDP_PROFILE_DESC_LENGTH, ATTR_ID_BT_PROFILE_DESC_LIST, INVALID_UUID); ASSERT_EQ(sdp_dynamic_change_hfp_version(&hfp_attr, bdaddr), false); } TEST_F(StackSdpUtilsTest, check_HFP_version_change_fail) { bluetooth::common::InitFlags::Load(hfp_test_flags_feature_enabled); RawAddress bdaddr(RawAddress::kEmpty); - set_hfp_attr(SDP_PROFILE_DESC_LENGTH, ATTR_ID_BT_PROFILE_DESC_LIST, - UUID_HF_LSB); + set_hfp_attr(SDP_PROFILE_DESC_LENGTH, ATTR_ID_BT_PROFILE_DESC_LIST, UUID_HF_LSB); test::mock::osi_properties::osi_property_get_bool.body = - [](const char* /* key */, bool /* default_value */) { return false; }; - EXPECT_CALL(*localIopMock, - InteropMatchAddrOrName(INTEROP_HFP_1_7_ALLOWLIST, &bdaddr, - &btif_storage_get_remote_device_property)) - .WillOnce(Return(false)); - EXPECT_CALL(*localIopMock, - InteropMatchAddrOrName(INTEROP_HFP_1_9_ALLOWLIST, &bdaddr, - &btif_storage_get_remote_device_property)) - .WillOnce(Return(false)); + [](const char* /* key */, bool /* default_value */) { return false; }; + EXPECT_CALL(*localIopMock, InteropMatchAddrOrName(INTEROP_HFP_1_7_ALLOWLIST, &bdaddr, + &btif_storage_get_remote_device_property)) + .WillOnce(Return(false)); + EXPECT_CALL(*localIopMock, InteropMatchAddrOrName(INTEROP_HFP_1_9_ALLOWLIST, &bdaddr, + &btif_storage_get_remote_device_property)) + .WillOnce(Return(false)); ASSERT_EQ(sdp_dynamic_change_hfp_version(&hfp_attr, bdaddr), false); } TEST_F(StackSdpUtilsTest, check_HFP_version_change_success) { bluetooth::common::InitFlags::Load(hfp_test_flags_feature_enabled); RawAddress bdaddr(RawAddress::kEmpty); - set_hfp_attr(SDP_PROFILE_DESC_LENGTH, ATTR_ID_BT_PROFILE_DESC_LIST, - UUID_HF_LSB); - EXPECT_CALL(*localIopMock, - InteropMatchAddrOrName(INTEROP_HFP_1_7_ALLOWLIST, &bdaddr, - &btif_storage_get_remote_device_property)) - .WillOnce(Return(true)); - EXPECT_CALL(*localIopMock, - InteropMatchAddrOrName(INTEROP_HFP_1_9_ALLOWLIST, &bdaddr, - &btif_storage_get_remote_device_property)) - .WillOnce(Return(true)); + set_hfp_attr(SDP_PROFILE_DESC_LENGTH, ATTR_ID_BT_PROFILE_DESC_LIST, UUID_HF_LSB); + EXPECT_CALL(*localIopMock, InteropMatchAddrOrName(INTEROP_HFP_1_7_ALLOWLIST, &bdaddr, + &btif_storage_get_remote_device_property)) + .WillOnce(Return(true)); + EXPECT_CALL(*localIopMock, InteropMatchAddrOrName(INTEROP_HFP_1_9_ALLOWLIST, &bdaddr, + &btif_storage_get_remote_device_property)) + .WillOnce(Return(true)); ASSERT_EQ(sdp_dynamic_change_hfp_version(&hfp_attr, bdaddr), true); } TEST_F(StackSdpUtilsTest, check_HFP_version_fallback_success) { bluetooth::common::InitFlags::Load(hfp_test_flags_feature_enabled); RawAddress bdaddr(RawAddress::kEmpty); - set_hfp_attr(SDP_PROFILE_DESC_LENGTH, ATTR_ID_BT_PROFILE_DESC_LIST, - UUID_HF_LSB); - EXPECT_CALL(*localIopMock, - InteropMatchAddrOrName(INTEROP_HFP_1_7_ALLOWLIST, &bdaddr, - &btif_storage_get_remote_device_property)) - .WillOnce(Return(true)); - EXPECT_CALL(*localIopMock, - InteropMatchAddrOrName(INTEROP_HFP_1_9_ALLOWLIST, &bdaddr, - &btif_storage_get_remote_device_property)) - .WillOnce(Return(true)); + set_hfp_attr(SDP_PROFILE_DESC_LENGTH, ATTR_ID_BT_PROFILE_DESC_LIST, UUID_HF_LSB); + EXPECT_CALL(*localIopMock, InteropMatchAddrOrName(INTEROP_HFP_1_7_ALLOWLIST, &bdaddr, + &btif_storage_get_remote_device_property)) + .WillOnce(Return(true)); + EXPECT_CALL(*localIopMock, InteropMatchAddrOrName(INTEROP_HFP_1_9_ALLOWLIST, &bdaddr, + &btif_storage_get_remote_device_property)) + .WillOnce(Return(true)); bool is_hfp_fallback = sdp_dynamic_change_hfp_version(&hfp_attr, bdaddr); - ASSERT_EQ(hfp_attr.value_ptr[PROFILE_VERSION_POSITION], - HFP_PROFILE_MINOR_VERSION_7); + ASSERT_EQ(hfp_attr.value_ptr[PROFILE_VERSION_POSITION], HFP_PROFILE_MINOR_VERSION_7); hfp_fallback(is_hfp_fallback, &hfp_attr); - ASSERT_EQ(hfp_attr.value_ptr[PROFILE_VERSION_POSITION], - HFP_PROFILE_MINOR_VERSION_6); + ASSERT_EQ(hfp_attr.value_ptr[PROFILE_VERSION_POSITION], HFP_PROFILE_MINOR_VERSION_6); } TEST_F(StackSdpUtilsTest, sdpu_compare_uuid_with_attr_u16) { tSDP_DISC_ATTR attr = { - .p_next_attr = nullptr, - .attr_id = 0, - .attr_len_type = bluetooth::Uuid::kNumBytes16, - .attr_value = - { - .v = + .p_next_attr = nullptr, + .attr_id = 0, + .attr_len_type = bluetooth::Uuid::kNumBytes16, + .attr_value = { - .u16 = 0x1234, + .v = + { + .u16 = 0x1234, + }, }, - }, }; bool is_valid{false}; @@ -716,16 +636,16 @@ TEST_F(StackSdpUtilsTest, sdpu_compare_uuid_with_attr_u16) { TEST_F(StackSdpUtilsTest, sdpu_compare_uuid_with_attr_u32) { tSDP_DISC_ATTR attr = { - .p_next_attr = nullptr, - .attr_id = 0, - .attr_len_type = bluetooth::Uuid::kNumBytes32, - .attr_value = - { - .v = + .p_next_attr = nullptr, + .attr_id = 0, + .attr_len_type = bluetooth::Uuid::kNumBytes32, + .attr_value = { - .u32 = 0x12345678, + .v = + { + .u32 = 0x12345678, + }, }, - }, }; bool is_valid{false}; @@ -737,30 +657,28 @@ TEST_F(StackSdpUtilsTest, sdpu_compare_uuid_with_attr_u32) { } TEST_F(StackSdpUtilsTest, sdpu_compare_uuid_with_attr_u128) { - tSDP_DISC_ATTR* p_attr = - (tSDP_DISC_ATTR*)calloc(1, sizeof(tSDP_DISC_ATTR) + 16); + tSDP_DISC_ATTR* p_attr = (tSDP_DISC_ATTR*)calloc(1, sizeof(tSDP_DISC_ATTR) + 16); tSDP_DISC_ATTR attr = { - .p_next_attr = nullptr, - .attr_id = 0, - .attr_len_type = bluetooth::Uuid::kNumBytes128, - .attr_value = {}, + .p_next_attr = nullptr, + .attr_id = 0, + .attr_len_type = bluetooth::Uuid::kNumBytes128, + .attr_value = {}, }; uint8_t data[] = { - 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, - 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, + 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, + 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, }; memcpy(p_attr, &attr, sizeof(tSDP_DISC_ATTR)); memcpy(p_attr->attr_value.v.array, data, 16); bool is_valid{false}; - bluetooth::Uuid uuid = bluetooth::Uuid::FromString( - "12345678-9abc-def0-1234-56789abcdef0", &is_valid); + bluetooth::Uuid uuid = + bluetooth::Uuid::FromString("12345678-9abc-def0-1234-56789abcdef0", &is_valid); - ASSERT_EQ(0, - memcmp(uuid.To128BitBE().data(), (void*)p_attr->attr_value.v.array, - bluetooth::Uuid::kNumBytes128)); + ASSERT_EQ(0, memcmp(uuid.To128BitBE().data(), (void*)p_attr->attr_value.v.array, + bluetooth::Uuid::kNumBytes128)); ASSERT_TRUE(is_valid); ASSERT_TRUE(sdpu_compare_uuid_with_attr(uuid, p_attr)); diff --git a/system/stack/test/stack_a2dp_test.cc b/system/stack/test/stack_a2dp_test.cc index 85b3e7675a7..0f6a91f02d5 100644 --- a/system/stack/test/stack_a2dp_test.cc +++ b/system/stack/test/stack_a2dp_test.cc @@ -32,219 +32,216 @@ namespace { const uint8_t codec_info_sbc[AVDT_CODEC_SIZE] = { - 6, // Length (A2DP_SBC_INFO_LEN) - 0, // Media Type: AVDT_MEDIA_TYPE_AUDIO - 0, // Media Codec Type: A2DP_MEDIA_CT_SBC - 0x20 | 0x01, // Sample Frequency: A2DP_SBC_IE_SAMP_FREQ_44 | - // Channel Mode: A2DP_SBC_IE_CH_MD_JOINT - 0x10 | 0x04 | 0x01, // Block Length: A2DP_SBC_IE_BLOCKS_16 | - // Subbands: A2DP_SBC_IE_SUBBAND_8 | - // Allocation Method: A2DP_SBC_IE_ALLOC_MD_L - 2, // MinimumBitpool Value: A2DP_SBC_IE_MIN_BITPOOL - 53, // Maximum Bitpool Value: A2DP_SBC_MAX_BITPOOL - 7, // Fake - 8, // Fake - 9 // Fake + 6, // Length (A2DP_SBC_INFO_LEN) + 0, // Media Type: AVDT_MEDIA_TYPE_AUDIO + 0, // Media Codec Type: A2DP_MEDIA_CT_SBC + 0x20 | 0x01, // Sample Frequency: A2DP_SBC_IE_SAMP_FREQ_44 | + // Channel Mode: A2DP_SBC_IE_CH_MD_JOINT + 0x10 | 0x04 | 0x01, // Block Length: A2DP_SBC_IE_BLOCKS_16 | + // Subbands: A2DP_SBC_IE_SUBBAND_8 | + // Allocation Method: A2DP_SBC_IE_ALLOC_MD_L + 2, // MinimumBitpool Value: A2DP_SBC_IE_MIN_BITPOOL + 53, // Maximum Bitpool Value: A2DP_SBC_MAX_BITPOOL + 7, // Fake + 8, // Fake + 9 // Fake }; const uint8_t codec_info_sbc_capability[AVDT_CODEC_SIZE] = { - 6, // Length (A2DP_SBC_INFO_LEN) - 0, // Media Type: AVDT_MEDIA_TYPE_AUDIO - 0, // Media Codec Type: A2DP_MEDIA_CT_SBC - 0x20 | // Sample Frequency: A2DP_SBC_IE_SAMP_FREQ_44 | - 0x08 | 0x01, // Channel Mode: A2DP_SBC_IE_CH_MD_MONO | - // A2DP_SBC_IE_CH_MD_JOINT - 0x80 | 0x40 | 0x20 | 0x10 | // Block Length: A2DP_SBC_IE_BLOCKS_4 | - // A2DP_SBC_IE_BLOCKS_8 | - // A2DP_SBC_IE_BLOCKS_12 | - // A2DP_SBC_IE_BLOCKS_16 | - 0x04 | // Subbands: A2DP_SBC_IE_SUBBAND_8 | - 0x01, // Allocation Method: A2DP_SBC_IE_ALLOC_MD_L - 2, // MinimumBitpool Value: A2DP_SBC_IE_MIN_BITPOOL - 53, // Maximum Bitpool Value: A2DP_SBC_MAX_BITPOOL - 7, // Fake - 8, // Fake - 9 // Fake + 6, // Length (A2DP_SBC_INFO_LEN) + 0, // Media Type: AVDT_MEDIA_TYPE_AUDIO + 0, // Media Codec Type: A2DP_MEDIA_CT_SBC + 0x20 | // Sample Frequency: A2DP_SBC_IE_SAMP_FREQ_44 | + 0x08 | 0x01, // Channel Mode: A2DP_SBC_IE_CH_MD_MONO | + // A2DP_SBC_IE_CH_MD_JOINT + 0x80 | 0x40 | 0x20 | 0x10 | // Block Length: A2DP_SBC_IE_BLOCKS_4 | + // A2DP_SBC_IE_BLOCKS_8 | + // A2DP_SBC_IE_BLOCKS_12 | + // A2DP_SBC_IE_BLOCKS_16 | + 0x04 | // Subbands: A2DP_SBC_IE_SUBBAND_8 | + 0x01, // Allocation Method: A2DP_SBC_IE_ALLOC_MD_L + 2, // MinimumBitpool Value: A2DP_SBC_IE_MIN_BITPOOL + 53, // Maximum Bitpool Value: A2DP_SBC_MAX_BITPOOL + 7, // Fake + 8, // Fake + 9 // Fake }; const uint8_t codec_info_sbc_sink_capability[AVDT_CODEC_SIZE] = { - 6, // Length (A2DP_SBC_INFO_LEN) - 0, // Media Type: AVDT_MEDIA_TYPE_AUDIO - 0, // Media Codec Type: A2DP_MEDIA_CT_SBC - 0x20 | 0x10 | // Sample Frequency: A2DP_SBC_IE_SAMP_FREQ_44 | - // A2DP_SBC_IE_SAMP_FREQ_48 | - 0x08 | 0x04 | 0x02 | 0x01, // Channel Mode: A2DP_SBC_IE_CH_MD_MONO | - // A2DP_SBC_IE_CH_MD_DUAL | - // A2DP_SBC_IE_CH_MD_STEREO | - // A2DP_SBC_IE_CH_MD_JOINT - 0x80 | 0x40 | 0x20 | 0x10 | // Block Length: A2DP_SBC_IE_BLOCKS_4 | - // A2DP_SBC_IE_BLOCKS_8 | - // A2DP_SBC_IE_BLOCKS_12 | - // A2DP_SBC_IE_BLOCKS_16 | - 0x08 | 0x04 | // Subbands: A2DP_SBC_IE_SUBBAND_4 | - // A2DP_SBC_IE_SUBBAND_8 | - 0x02 | 0x01, // Allocation Method: A2DP_SBC_IE_ALLOC_MD_S | - // A2DP_SBC_IE_ALLOC_MD_L - 2, // MinimumBitpool Value: A2DP_SBC_IE_MIN_BITPOOL - 53, // Maximum Bitpool Value: A2DP_SBC_MAX_BITPOOL - 7, // Fake - 8, // Fake - 9 // Fake + 6, // Length (A2DP_SBC_INFO_LEN) + 0, // Media Type: AVDT_MEDIA_TYPE_AUDIO + 0, // Media Codec Type: A2DP_MEDIA_CT_SBC + 0x20 | 0x10 | // Sample Frequency: A2DP_SBC_IE_SAMP_FREQ_44 | + // A2DP_SBC_IE_SAMP_FREQ_48 | + 0x08 | 0x04 | 0x02 | 0x01, // Channel Mode: A2DP_SBC_IE_CH_MD_MONO | + // A2DP_SBC_IE_CH_MD_DUAL | + // A2DP_SBC_IE_CH_MD_STEREO | + // A2DP_SBC_IE_CH_MD_JOINT + 0x80 | 0x40 | 0x20 | 0x10 | // Block Length: A2DP_SBC_IE_BLOCKS_4 | + // A2DP_SBC_IE_BLOCKS_8 | + // A2DP_SBC_IE_BLOCKS_12 | + // A2DP_SBC_IE_BLOCKS_16 | + 0x08 | 0x04 | // Subbands: A2DP_SBC_IE_SUBBAND_4 | + // A2DP_SBC_IE_SUBBAND_8 | + 0x02 | 0x01, // Allocation Method: A2DP_SBC_IE_ALLOC_MD_S | + // A2DP_SBC_IE_ALLOC_MD_L + 2, // MinimumBitpool Value: A2DP_SBC_IE_MIN_BITPOOL + 53, // Maximum Bitpool Value: A2DP_SBC_MAX_BITPOOL + 7, // Fake + 8, // Fake + 9 // Fake }; const uint8_t codec_info_aac[AVDT_CODEC_SIZE] = { - 8, // Length (A2DP_AAC_INFO_LEN) - 0, // Media Type: AVDT_MEDIA_TYPE_AUDIO - 2, // Media Codec Type: A2DP_MEDIA_CT_AAC - 0x80, // Object Type: A2DP_AAC_OBJECT_TYPE_MPEG2_LC - 0x01, // Sampling Frequency: A2DP_AAC_SAMPLING_FREQ_44100 - 0x04, // Channels: A2DP_AAC_CHANNEL_MODE_STEREO - 0x00 | 0x4, // Variable Bit Rate: - // A2DP_AAC_VARIABLE_BIT_RATE_DISABLED - // Bit Rate: 320000 = 0x4e200 - 0xe2, // Bit Rate: 320000 = 0x4e200 - 0x00, // Bit Rate: 320000 = 0x4e200 - 7, // Unused - 8, // Unused - 9 // Unused + 8, // Length (A2DP_AAC_INFO_LEN) + 0, // Media Type: AVDT_MEDIA_TYPE_AUDIO + 2, // Media Codec Type: A2DP_MEDIA_CT_AAC + 0x80, // Object Type: A2DP_AAC_OBJECT_TYPE_MPEG2_LC + 0x01, // Sampling Frequency: A2DP_AAC_SAMPLING_FREQ_44100 + 0x04, // Channels: A2DP_AAC_CHANNEL_MODE_STEREO + 0x00 | 0x4, // Variable Bit Rate: + // A2DP_AAC_VARIABLE_BIT_RATE_DISABLED + // Bit Rate: 320000 = 0x4e200 + 0xe2, // Bit Rate: 320000 = 0x4e200 + 0x00, // Bit Rate: 320000 = 0x4e200 + 7, // Unused + 8, // Unused + 9 // Unused }; const uint8_t codec_info_aac_vbr[AVDT_CODEC_SIZE] = { - 8, // Length (A2DP_AAC_INFO_LEN) - 0, // Media Type: AVDT_MEDIA_TYPE_AUDIO - 2, // Media Codec Type: A2DP_MEDIA_CT_AAC - 0x80, // Object Type: A2DP_AAC_OBJECT_TYPE_MPEG2_LC - 0x01, // Sampling Frequency: A2DP_AAC_SAMPLING_FREQ_44100 - 0x04, // Channels: A2DP_AAC_CHANNEL_MODE_STEREO - 0x80 | 0x4, // Variable Bit Rate: - // A2DP_AAC_VARIABLE_BIT_RATE_ENABLED - // Bit Rate: 320000 = 0x4e200 - 0xe2, // Bit Rate: 320000 = 0x4e200 - 0x00, // Bit Rate: 320000 = 0x4e200 - 7, // Unused - 8, // Unused - 9 // Unused + 8, // Length (A2DP_AAC_INFO_LEN) + 0, // Media Type: AVDT_MEDIA_TYPE_AUDIO + 2, // Media Codec Type: A2DP_MEDIA_CT_AAC + 0x80, // Object Type: A2DP_AAC_OBJECT_TYPE_MPEG2_LC + 0x01, // Sampling Frequency: A2DP_AAC_SAMPLING_FREQ_44100 + 0x04, // Channels: A2DP_AAC_CHANNEL_MODE_STEREO + 0x80 | 0x4, // Variable Bit Rate: + // A2DP_AAC_VARIABLE_BIT_RATE_ENABLED + // Bit Rate: 320000 = 0x4e200 + 0xe2, // Bit Rate: 320000 = 0x4e200 + 0x00, // Bit Rate: 320000 = 0x4e200 + 7, // Unused + 8, // Unused + 9 // Unused }; const uint8_t codec_info_aac_capability[AVDT_CODEC_SIZE] = { - 8, // Length (A2DP_AAC_INFO_LEN) - 0, // Media Type: AVDT_MEDIA_TYPE_AUDIO - 2, // Media Codec Type: A2DP_MEDIA_CT_AAC - 0x80, // Object Type: A2DP_AAC_OBJECT_TYPE_MPEG2_LC - 0x01, // Sampling Frequency: A2DP_AAC_SAMPLING_FREQ_44100 - // TODO: AAC 48.0kHz sampling rate should be added back - see b/62301376 - 0x04, // Channels: A2DP_AAC_CHANNEL_MODE_STEREO - 0x00 | 0x4, // Variable Bit Rate: - // A2DP_AAC_VARIABLE_BIT_RATE_DISABLED - // Bit Rate: 320000 = 0x4e200 - 0xe2, // Bit Rate: 320000 = 0x4e200 - 0x00, // Bit Rate: 320000 = 0x4e200 - 7, // Unused - 8, // Unused - 9 // Unused + 8, // Length (A2DP_AAC_INFO_LEN) + 0, // Media Type: AVDT_MEDIA_TYPE_AUDIO + 2, // Media Codec Type: A2DP_MEDIA_CT_AAC + 0x80, // Object Type: A2DP_AAC_OBJECT_TYPE_MPEG2_LC + 0x01, // Sampling Frequency: A2DP_AAC_SAMPLING_FREQ_44100 + // TODO: AAC 48.0kHz sampling rate should be added back - see b/62301376 + 0x04, // Channels: A2DP_AAC_CHANNEL_MODE_STEREO + 0x00 | 0x4, // Variable Bit Rate: + // A2DP_AAC_VARIABLE_BIT_RATE_DISABLED + // Bit Rate: 320000 = 0x4e200 + 0xe2, // Bit Rate: 320000 = 0x4e200 + 0x00, // Bit Rate: 320000 = 0x4e200 + 7, // Unused + 8, // Unused + 9 // Unused }; const uint8_t codec_info_aac_vbr_capability[AVDT_CODEC_SIZE] = { - 8, // Length (A2DP_AAC_INFO_LEN) - 0, // Media Type: AVDT_MEDIA_TYPE_AUDIO - 2, // Media Codec Type: A2DP_MEDIA_CT_AAC - 0x80, // Object Type: A2DP_AAC_OBJECT_TYPE_MPEG2_LC - 0x01, // Sampling Frequency: A2DP_AAC_SAMPLING_FREQ_44100 - // TODO: AAC 48.0kHz sampling rate should be added back - see b/62301376 - 0x04, // Channels: A2DP_AAC_CHANNEL_MODE_STEREO - 0x80 | 0x4, // Variable Bit Rate: - // A2DP_AAC_VARIABLE_BIT_RATE_ENABLED - // Bit Rate: 320000 = 0x4e200 - 0xe2, // Bit Rate: 320000 = 0x4e200 - 0x00, // Bit Rate: 320000 = 0x4e200 - 7, // Unused - 8, // Unused - 9 // Unused + 8, // Length (A2DP_AAC_INFO_LEN) + 0, // Media Type: AVDT_MEDIA_TYPE_AUDIO + 2, // Media Codec Type: A2DP_MEDIA_CT_AAC + 0x80, // Object Type: A2DP_AAC_OBJECT_TYPE_MPEG2_LC + 0x01, // Sampling Frequency: A2DP_AAC_SAMPLING_FREQ_44100 + // TODO: AAC 48.0kHz sampling rate should be added back - see b/62301376 + 0x04, // Channels: A2DP_AAC_CHANNEL_MODE_STEREO + 0x80 | 0x4, // Variable Bit Rate: + // A2DP_AAC_VARIABLE_BIT_RATE_ENABLED + // Bit Rate: 320000 = 0x4e200 + 0xe2, // Bit Rate: 320000 = 0x4e200 + 0x00, // Bit Rate: 320000 = 0x4e200 + 7, // Unused + 8, // Unused + 9 // Unused }; const uint8_t codec_info_aac_sink_capability[AVDT_CODEC_SIZE] = { - 8, // Length (A2DP_AAC_INFO_LEN) - 0, // Media Type: AVDT_MEDIA_TYPE_AUDIO - 2, // Media Codec Type: A2DP_MEDIA_CT_AAC - 0x80 | 0x40 | 0x20 | 0x10, // Object Type: A2DP_AAC_OBJECT_TYPE_MPEG2_LC | - // A2DP_AAC_OBJECT_TYPE_MPEG4_LC - // A2DP_AAC_OBJECT_TYPE_MPEG4_LTP - // A2DP_AAC_OBJECT_TYPE_MPEG4_SCALABLE - 0x01, // Sampling Frequency: A2DP_AAC_SAMPLING_FREQ_44100 - 0x80 | 0x20 | 0x10 | 0x08 | 0x04, // Sampling Frequency: - // A2DP_AAC_SAMPLING_FREQ_48000 | - // A2DP_AAC_SAMPLING_FREQ_88200 | - // A2DP_AAC_SAMPLING_FREQ_96000 | - // Channels: - // A2DP_AAC_CHANNEL_MODE_MONO | - // A2DP_AAC_CHANNEL_MODE_STEREO - 0x80 | 0x4, // Variable Bit Rate: - // A2DP_AAC_VARIABLE_BIT_RATE_ENABLED - // Bit Rate: 320000 = 0x4e200 - 0xe2, // Bit Rate: 320000 = 0x4e200 - 0x00, // Bit Rate: 320000 = 0x4e200 - 7, // Fake - 8, // Fake - 9 // Fake + 8, // Length (A2DP_AAC_INFO_LEN) + 0, // Media Type: AVDT_MEDIA_TYPE_AUDIO + 2, // Media Codec Type: A2DP_MEDIA_CT_AAC + 0x80 | 0x40 | 0x20 | 0x10, // Object Type: A2DP_AAC_OBJECT_TYPE_MPEG2_LC | + // A2DP_AAC_OBJECT_TYPE_MPEG4_LC + // A2DP_AAC_OBJECT_TYPE_MPEG4_LTP + // A2DP_AAC_OBJECT_TYPE_MPEG4_SCALABLE + 0x01, // Sampling Frequency: A2DP_AAC_SAMPLING_FREQ_44100 + 0x80 | 0x20 | 0x10 | 0x08 | 0x04, // Sampling Frequency: + // A2DP_AAC_SAMPLING_FREQ_48000 | + // A2DP_AAC_SAMPLING_FREQ_88200 | + // A2DP_AAC_SAMPLING_FREQ_96000 | + // Channels: + // A2DP_AAC_CHANNEL_MODE_MONO | + // A2DP_AAC_CHANNEL_MODE_STEREO + 0x80 | 0x4, // Variable Bit Rate: + // A2DP_AAC_VARIABLE_BIT_RATE_ENABLED + // Bit Rate: 320000 = 0x4e200 + 0xe2, // Bit Rate: 320000 = 0x4e200 + 0x00, // Bit Rate: 320000 = 0x4e200 + 7, // Fake + 8, // Fake + 9 // Fake }; const uint8_t codec_info_opus[AVDT_CODEC_SIZE] = { - A2DP_OPUS_CODEC_LEN, // Length - AVDT_MEDIA_TYPE_AUDIO << 4, // Media Type - A2DP_MEDIA_CT_NON_A2DP, // Media Codec Type Vendor - (A2DP_OPUS_VENDOR_ID & 0x000000FF), - (A2DP_OPUS_VENDOR_ID & 0x0000FF00) >> 8, - (A2DP_OPUS_VENDOR_ID & 0x00FF0000) >> 16, - (A2DP_OPUS_VENDOR_ID & 0xFF000000) >> 24, - (A2DP_OPUS_CODEC_ID & 0x00FF), - (A2DP_OPUS_CODEC_ID & 0xFF00) >> 8, - A2DP_OPUS_CHANNEL_MODE_STEREO | A2DP_OPUS_20MS_FRAMESIZE | - A2DP_OPUS_SAMPLING_FREQ_48000}; + A2DP_OPUS_CODEC_LEN, // Length + AVDT_MEDIA_TYPE_AUDIO << 4, // Media Type + A2DP_MEDIA_CT_NON_A2DP, // Media Codec Type Vendor + (A2DP_OPUS_VENDOR_ID & 0x000000FF), + (A2DP_OPUS_VENDOR_ID & 0x0000FF00) >> 8, + (A2DP_OPUS_VENDOR_ID & 0x00FF0000) >> 16, + (A2DP_OPUS_VENDOR_ID & 0xFF000000) >> 24, + (A2DP_OPUS_CODEC_ID & 0x00FF), + (A2DP_OPUS_CODEC_ID & 0xFF00) >> 8, + A2DP_OPUS_CHANNEL_MODE_STEREO | A2DP_OPUS_20MS_FRAMESIZE | A2DP_OPUS_SAMPLING_FREQ_48000}; const uint8_t codec_info_opus_capability[AVDT_CODEC_SIZE] = { - A2DP_OPUS_CODEC_LEN, // Length - AVDT_MEDIA_TYPE_AUDIO << 4, // Media Type - A2DP_MEDIA_CT_NON_A2DP, // Media Codec Type Vendor - (A2DP_OPUS_VENDOR_ID & 0x000000FF), - (A2DP_OPUS_VENDOR_ID & 0x0000FF00) >> 8, - (A2DP_OPUS_VENDOR_ID & 0x00FF0000) >> 16, - (A2DP_OPUS_VENDOR_ID & 0xFF000000) >> 24, - (A2DP_OPUS_CODEC_ID & 0x00FF), - (A2DP_OPUS_CODEC_ID & 0xFF00) >> 8, - A2DP_OPUS_CHANNEL_MODE_MONO | A2DP_OPUS_CHANNEL_MODE_STEREO | - A2DP_OPUS_10MS_FRAMESIZE | A2DP_OPUS_20MS_FRAMESIZE | - A2DP_OPUS_SAMPLING_FREQ_48000}; + A2DP_OPUS_CODEC_LEN, // Length + AVDT_MEDIA_TYPE_AUDIO << 4, // Media Type + A2DP_MEDIA_CT_NON_A2DP, // Media Codec Type Vendor + (A2DP_OPUS_VENDOR_ID & 0x000000FF), + (A2DP_OPUS_VENDOR_ID & 0x0000FF00) >> 8, + (A2DP_OPUS_VENDOR_ID & 0x00FF0000) >> 16, + (A2DP_OPUS_VENDOR_ID & 0xFF000000) >> 24, + (A2DP_OPUS_CODEC_ID & 0x00FF), + (A2DP_OPUS_CODEC_ID & 0xFF00) >> 8, + A2DP_OPUS_CHANNEL_MODE_MONO | A2DP_OPUS_CHANNEL_MODE_STEREO | A2DP_OPUS_10MS_FRAMESIZE | + A2DP_OPUS_20MS_FRAMESIZE | A2DP_OPUS_SAMPLING_FREQ_48000}; const uint8_t codec_info_opus_sink_capability[AVDT_CODEC_SIZE] = { - A2DP_OPUS_CODEC_LEN, // Length - AVDT_MEDIA_TYPE_AUDIO << 4, // Media Type - A2DP_MEDIA_CT_NON_A2DP, // Media Codec Type Vendor - (A2DP_OPUS_VENDOR_ID & 0x000000FF), - (A2DP_OPUS_VENDOR_ID & 0x0000FF00) >> 8, - (A2DP_OPUS_VENDOR_ID & 0x00FF0000) >> 16, - (A2DP_OPUS_VENDOR_ID & 0xFF000000) >> 24, - (A2DP_OPUS_CODEC_ID & 0x00FF), - (A2DP_OPUS_CODEC_ID & 0xFF00) >> 8, - A2DP_OPUS_CHANNEL_MODE_MONO | A2DP_OPUS_CHANNEL_MODE_STEREO | - A2DP_OPUS_10MS_FRAMESIZE | A2DP_OPUS_20MS_FRAMESIZE | - A2DP_OPUS_SAMPLING_FREQ_48000}; + A2DP_OPUS_CODEC_LEN, // Length + AVDT_MEDIA_TYPE_AUDIO << 4, // Media Type + A2DP_MEDIA_CT_NON_A2DP, // Media Codec Type Vendor + (A2DP_OPUS_VENDOR_ID & 0x000000FF), + (A2DP_OPUS_VENDOR_ID & 0x0000FF00) >> 8, + (A2DP_OPUS_VENDOR_ID & 0x00FF0000) >> 16, + (A2DP_OPUS_VENDOR_ID & 0xFF000000) >> 24, + (A2DP_OPUS_CODEC_ID & 0x00FF), + (A2DP_OPUS_CODEC_ID & 0xFF00) >> 8, + A2DP_OPUS_CHANNEL_MODE_MONO | A2DP_OPUS_CHANNEL_MODE_STEREO | A2DP_OPUS_10MS_FRAMESIZE | + A2DP_OPUS_20MS_FRAMESIZE | A2DP_OPUS_SAMPLING_FREQ_48000}; const uint8_t codec_info_non_a2dp[AVDT_CODEC_SIZE] = { - 8, // Length - 0, // Media Type: AVDT_MEDIA_TYPE_AUDIO - 0xFF, // Media Codec Type: A2DP_MEDIA_CT_NON_A2DP - 3, 4, 0, 0, // Vendor ID: LSB first, upper two octets should be 0 - 7, 8, // Codec ID: LSB first - 9 // Fake + 8, // Length + 0, // Media Type: AVDT_MEDIA_TYPE_AUDIO + 0xFF, // Media Codec Type: A2DP_MEDIA_CT_NON_A2DP + 3, 4, 0, 0, // Vendor ID: LSB first, upper two octets should be 0 + 7, 8, // Codec ID: LSB first + 9 // Fake }; const uint8_t codec_info_non_a2dp_fake[AVDT_CODEC_SIZE] = { - 8, // Length - 0, // Media Type: AVDT_MEDIA_TYPE_AUDIO - 0xFF, // Media Codec Type: A2DP_MEDIA_CT_NON_A2DP - 3, 4, 0, 0, // Vendor ID: LSB first, upper two octets should be 0 - 7, 8, // Codec ID: LSB first - 10 // Unused + 8, // Length + 0, // Media Type: AVDT_MEDIA_TYPE_AUDIO + 0xFF, // Media Codec Type: A2DP_MEDIA_CT_NON_A2DP + 3, 4, 0, 0, // Vendor ID: LSB first, upper two octets should be 0 + 7, 8, // Codec ID: LSB first + 10 // Unused }; static const char* APTX_ENCODER_LIB_NAME = "libaptX_encoder.so"; @@ -264,13 +261,11 @@ static bool has_shared_library(const char* name) { } // namespace class StackA2dpTest : public ::testing::Test { - protected: +protected: StackA2dpTest() { // Create the set with all supported codecs - for (int i = BTAV_A2DP_CODEC_INDEX_MIN; i < BTAV_A2DP_CODEC_INDEX_MAX; - i++) { - btav_a2dp_codec_index_t codec_index = - static_cast(i); + for (int i = BTAV_A2DP_CODEC_INDEX_MIN; i < BTAV_A2DP_CODEC_INDEX_MAX; i++) { + btav_a2dp_codec_index_t codec_index = static_cast(i); bool supported = false; switch (codec_index) { @@ -330,7 +325,7 @@ class StackA2dpTest : public ::testing::Test { return supported_codecs_.find(codec_index) != supported_codecs_.end(); } - private: +private: std::set supported_codecs_; }; @@ -557,16 +552,15 @@ TEST_F(StackA2dpTest, test_a2dp_codec_name) { // Test all unknown codecs memcpy(codec_info_test, codec_info_sbc, sizeof(codec_info_sbc)); - for (uint8_t codec_type = A2DP_MEDIA_CT_AAC + 1; - codec_type < A2DP_MEDIA_CT_NON_A2DP; codec_type++) { + for (uint8_t codec_type = A2DP_MEDIA_CT_AAC + 1; codec_type < A2DP_MEDIA_CT_NON_A2DP; + codec_type++) { codec_info_test[2] = codec_type; // Unknown codec type EXPECT_STREQ(A2DP_CodecName(codec_info_test), "UNKNOWN CODEC"); } } TEST_F(StackA2dpTest, test_a2dp_vendor) { - EXPECT_EQ(A2DP_VendorCodecGetVendorId(codec_info_non_a2dp), - (uint32_t)0x00000403); + EXPECT_EQ(A2DP_VendorCodecGetVendorId(codec_info_non_a2dp), (uint32_t)0x00000403); EXPECT_EQ(A2DP_VendorCodecGetCodecId(codec_info_non_a2dp), (uint16_t)0x0807); EXPECT_TRUE(A2DP_VendorUsesRtpHeader(true, codec_info_non_a2dp)); EXPECT_TRUE(A2DP_VendorUsesRtpHeader(false, codec_info_non_a2dp)); @@ -574,20 +568,15 @@ TEST_F(StackA2dpTest, test_a2dp_vendor) { TEST_F(StackA2dpTest, test_a2dp_codec_type_equals) { EXPECT_TRUE(A2DP_CodecTypeEquals(codec_info_sbc, codec_info_sbc_capability)); - EXPECT_TRUE( - A2DP_CodecTypeEquals(codec_info_sbc, codec_info_sbc_sink_capability)); + EXPECT_TRUE(A2DP_CodecTypeEquals(codec_info_sbc, codec_info_sbc_sink_capability)); EXPECT_TRUE(A2DP_CodecTypeEquals(codec_info_aac, codec_info_aac_capability)); - EXPECT_TRUE( - A2DP_CodecTypeEquals(codec_info_aac, codec_info_aac_sink_capability)); + EXPECT_TRUE(A2DP_CodecTypeEquals(codec_info_aac, codec_info_aac_sink_capability)); - ASSERT_TRUE( - A2DP_VendorCodecTypeEquals(codec_info_opus, codec_info_opus_capability)); - ASSERT_TRUE(A2DP_VendorCodecTypeEquals(codec_info_opus, - codec_info_opus_sink_capability)); + ASSERT_TRUE(A2DP_VendorCodecTypeEquals(codec_info_opus, codec_info_opus_capability)); + ASSERT_TRUE(A2DP_VendorCodecTypeEquals(codec_info_opus, codec_info_opus_sink_capability)); - EXPECT_TRUE( - A2DP_CodecTypeEquals(codec_info_non_a2dp, codec_info_non_a2dp_fake)); + EXPECT_TRUE(A2DP_CodecTypeEquals(codec_info_non_a2dp, codec_info_non_a2dp_fake)); EXPECT_FALSE(A2DP_CodecTypeEquals(codec_info_sbc, codec_info_non_a2dp)); EXPECT_FALSE(A2DP_CodecTypeEquals(codec_info_aac, codec_info_non_a2dp)); @@ -617,8 +606,7 @@ TEST_F(StackA2dpTest, test_a2dp_codec_equals) { // Test two identical non-A2DP codecs that are not recognized memset(codec_info_non_a2dp_test, 0xAB, sizeof(codec_info_non_a2dp_test)); - memcpy(codec_info_non_a2dp_test, codec_info_non_a2dp, - sizeof(codec_info_non_a2dp)); + memcpy(codec_info_non_a2dp_test, codec_info_non_a2dp, sizeof(codec_info_non_a2dp)); EXPECT_FALSE(A2DP_CodecEquals(codec_info_non_a2dp, codec_info_non_a2dp_test)); // Test two codecs that have different types @@ -770,15 +758,13 @@ TEST_F(StackA2dpTest, test_a2dp_get_packet_timestamp) { memset(a2dp_data, 0xAB, sizeof(a2dp_data)); *p_ts = 0x12345678; timestamp = 0xFFFFFFFF; - ASSERT_TRUE( - A2DP_VendorGetPacketTimestamp(codec_info_opus, a2dp_data, ×tamp)); + ASSERT_TRUE(A2DP_VendorGetPacketTimestamp(codec_info_opus, a2dp_data, ×tamp)); ASSERT_EQ(timestamp, static_cast(0x12345678)); memset(a2dp_data, 0xAB, sizeof(a2dp_data)); *p_ts = 0x12345678; timestamp = 0xFFFFFFFF; - EXPECT_FALSE( - A2DP_GetPacketTimestamp(codec_info_non_a2dp, a2dp_data, ×tamp)); + EXPECT_FALSE(A2DP_GetPacketTimestamp(codec_info_non_a2dp, a2dp_data, ×tamp)); } TEST_F(StackA2dpTest, test_a2dp_build_codec_header) { @@ -795,10 +781,8 @@ TEST_F(StackA2dpTest, test_a2dp_build_codec_header) { EXPECT_EQ(p_buf->offset + 1, BT_HDR_OFFSET); // Modified by A2DP_SBC_MPL_HDR_LEN EXPECT_EQ(p_buf->len - 1, BT_HDR_LEN); // Modified by A2DP_SBC_MPL_HDR_LEN - const uint8_t* p = - reinterpret_cast(p_buf + 1) + p_buf->offset; - EXPECT_EQ( - *p, static_cast(0x0D)); // 0xCD masked with A2DP_SBC_HDR_NUM_MSK + const uint8_t* p = reinterpret_cast(p_buf + 1) + p_buf->offset; + EXPECT_EQ(*p, static_cast(0x0D)); // 0xCD masked with A2DP_SBC_HDR_NUM_MSK memset(a2dp_data, 0xAB, sizeof(a2dp_data)); p_buf->len = BT_HDR_LEN; @@ -808,8 +792,7 @@ TEST_F(StackA2dpTest, test_a2dp_build_codec_header) { memset(a2dp_data, 0xAB, sizeof(a2dp_data)); p_buf->len = BT_HDR_LEN; p_buf->offset = BT_HDR_OFFSET; - EXPECT_FALSE( - A2DP_BuildCodecHeader(codec_info_non_a2dp, p_buf, FRAMES_PER_PACKET)); + EXPECT_FALSE(A2DP_BuildCodecHeader(codec_info_non_a2dp, p_buf, FRAMES_PER_PACKET)); } TEST_F(StackA2dpTest, test_a2dp_adjust_codec) { @@ -821,16 +804,14 @@ TEST_F(StackA2dpTest, test_a2dp_adjust_codec) { memset(codec_info_sbc_test, 0xAB, sizeof(codec_info_sbc_test)); memcpy(codec_info_sbc_test, codec_info_sbc, sizeof(codec_info_sbc)); EXPECT_TRUE(A2DP_AdjustCodec(codec_info_sbc_test)); - EXPECT_TRUE( - memcmp(codec_info_sbc_test, codec_info_sbc, sizeof(codec_info_sbc)) == 0); + EXPECT_TRUE(memcmp(codec_info_sbc_test, codec_info_sbc, sizeof(codec_info_sbc)) == 0); // Test updating a valid SBC codec that needs adjustment memset(codec_info_sbc_test, 0xAB, sizeof(codec_info_sbc_test)); memcpy(codec_info_sbc_test, codec_info_sbc, sizeof(codec_info_sbc)); codec_info_sbc_test[6] = 54; // A2DP_SBC_MAX_BITPOOL + 1 EXPECT_TRUE(A2DP_AdjustCodec(codec_info_sbc_test)); - EXPECT_TRUE( - memcmp(codec_info_sbc_test, codec_info_sbc, sizeof(codec_info_sbc)) == 0); + EXPECT_TRUE(memcmp(codec_info_sbc_test, codec_info_sbc, sizeof(codec_info_sbc)) == 0); // Test updating an invalid SBC codec memset(codec_info_sbc_test, 0xAB, sizeof(codec_info_sbc_test)); @@ -842,62 +823,45 @@ TEST_F(StackA2dpTest, test_a2dp_adjust_codec) { memset(codec_info_aac_test, 0xAB, sizeof(codec_info_aac_test)); memcpy(codec_info_aac_test, codec_info_aac, sizeof(codec_info_aac)); EXPECT_TRUE(A2DP_AdjustCodec(codec_info_aac_test)); - EXPECT_TRUE( - memcmp(codec_info_aac_test, codec_info_aac, sizeof(codec_info_aac)) == 0); + EXPECT_TRUE(memcmp(codec_info_aac_test, codec_info_aac, sizeof(codec_info_aac)) == 0); // Test updating a non-A2DP codec that is not recognized memset(codec_info_non_a2dp_test, 0xAB, sizeof(codec_info_non_a2dp_test)); - memcpy(codec_info_non_a2dp_test, codec_info_non_a2dp, - sizeof(codec_info_non_a2dp)); + memcpy(codec_info_non_a2dp_test, codec_info_non_a2dp, sizeof(codec_info_non_a2dp)); EXPECT_FALSE(A2DP_AdjustCodec(codec_info_non_a2dp_test)); } TEST_F(StackA2dpTest, test_a2dp_source_codec_index) { // Explicit tests for known Source codecs - EXPECT_EQ(A2DP_SourceCodecIndex(codec_info_sbc), - BTAV_A2DP_CODEC_INDEX_SOURCE_SBC); - EXPECT_EQ(A2DP_SourceCodecIndex(codec_info_sbc_capability), - BTAV_A2DP_CODEC_INDEX_SOURCE_SBC); + EXPECT_EQ(A2DP_SourceCodecIndex(codec_info_sbc), BTAV_A2DP_CODEC_INDEX_SOURCE_SBC); + EXPECT_EQ(A2DP_SourceCodecIndex(codec_info_sbc_capability), BTAV_A2DP_CODEC_INDEX_SOURCE_SBC); EXPECT_EQ(A2DP_SourceCodecIndex(codec_info_sbc_sink_capability), BTAV_A2DP_CODEC_INDEX_SOURCE_SBC); - EXPECT_EQ(A2DP_SourceCodecIndex(codec_info_aac), - BTAV_A2DP_CODEC_INDEX_SOURCE_AAC); - EXPECT_EQ(A2DP_SourceCodecIndex(codec_info_aac_capability), - BTAV_A2DP_CODEC_INDEX_SOURCE_AAC); + EXPECT_EQ(A2DP_SourceCodecIndex(codec_info_aac), BTAV_A2DP_CODEC_INDEX_SOURCE_AAC); + EXPECT_EQ(A2DP_SourceCodecIndex(codec_info_aac_capability), BTAV_A2DP_CODEC_INDEX_SOURCE_AAC); EXPECT_EQ(A2DP_SourceCodecIndex(codec_info_aac_sink_capability), BTAV_A2DP_CODEC_INDEX_SOURCE_AAC); - ASSERT_EQ(A2DP_VendorSourceCodecIndex(codec_info_opus), - BTAV_A2DP_CODEC_INDEX_SOURCE_OPUS); + ASSERT_EQ(A2DP_VendorSourceCodecIndex(codec_info_opus), BTAV_A2DP_CODEC_INDEX_SOURCE_OPUS); ASSERT_EQ(A2DP_VendorSourceCodecIndex(codec_info_opus_capability), BTAV_A2DP_CODEC_INDEX_SOURCE_OPUS); ASSERT_EQ(A2DP_VendorSourceCodecIndex(codec_info_opus_sink_capability), BTAV_A2DP_CODEC_INDEX_SOURCE_OPUS); - EXPECT_EQ(A2DP_SourceCodecIndex(codec_info_non_a2dp), - BTAV_A2DP_CODEC_INDEX_MAX); + EXPECT_EQ(A2DP_SourceCodecIndex(codec_info_non_a2dp), BTAV_A2DP_CODEC_INDEX_MAX); } TEST_F(StackA2dpTest, test_a2dp_sink_codec_index) { // Explicit tests for known Sink codecs - EXPECT_EQ(A2DP_SinkCodecIndex(codec_info_sbc), - BTAV_A2DP_CODEC_INDEX_SINK_SBC); - EXPECT_EQ(A2DP_SinkCodecIndex(codec_info_sbc_capability), - BTAV_A2DP_CODEC_INDEX_SINK_SBC); - EXPECT_EQ(A2DP_SinkCodecIndex(codec_info_sbc_sink_capability), - BTAV_A2DP_CODEC_INDEX_SINK_SBC); - EXPECT_EQ(A2DP_SinkCodecIndex(codec_info_aac), - BTAV_A2DP_CODEC_INDEX_SINK_AAC); - EXPECT_EQ(A2DP_SinkCodecIndex(codec_info_aac_capability), - BTAV_A2DP_CODEC_INDEX_SINK_AAC); - EXPECT_EQ(A2DP_SinkCodecIndex(codec_info_aac_sink_capability), - BTAV_A2DP_CODEC_INDEX_SINK_AAC); - ASSERT_EQ(A2DP_VendorSinkCodecIndex(codec_info_opus), - BTAV_A2DP_CODEC_INDEX_SINK_OPUS); - ASSERT_EQ(A2DP_VendorSinkCodecIndex(codec_info_opus_capability), - BTAV_A2DP_CODEC_INDEX_SINK_OPUS); + EXPECT_EQ(A2DP_SinkCodecIndex(codec_info_sbc), BTAV_A2DP_CODEC_INDEX_SINK_SBC); + EXPECT_EQ(A2DP_SinkCodecIndex(codec_info_sbc_capability), BTAV_A2DP_CODEC_INDEX_SINK_SBC); + EXPECT_EQ(A2DP_SinkCodecIndex(codec_info_sbc_sink_capability), BTAV_A2DP_CODEC_INDEX_SINK_SBC); + EXPECT_EQ(A2DP_SinkCodecIndex(codec_info_aac), BTAV_A2DP_CODEC_INDEX_SINK_AAC); + EXPECT_EQ(A2DP_SinkCodecIndex(codec_info_aac_capability), BTAV_A2DP_CODEC_INDEX_SINK_AAC); + EXPECT_EQ(A2DP_SinkCodecIndex(codec_info_aac_sink_capability), BTAV_A2DP_CODEC_INDEX_SINK_AAC); + ASSERT_EQ(A2DP_VendorSinkCodecIndex(codec_info_opus), BTAV_A2DP_CODEC_INDEX_SINK_OPUS); + ASSERT_EQ(A2DP_VendorSinkCodecIndex(codec_info_opus_capability), BTAV_A2DP_CODEC_INDEX_SINK_OPUS); ASSERT_EQ(A2DP_VendorSinkCodecIndex(codec_info_opus_sink_capability), BTAV_A2DP_CODEC_INDEX_SINK_OPUS); - EXPECT_EQ(A2DP_SinkCodecIndex(codec_info_non_a2dp), - BTAV_A2DP_CODEC_INDEX_MAX); + EXPECT_EQ(A2DP_SinkCodecIndex(codec_info_non_a2dp), BTAV_A2DP_CODEC_INDEX_MAX); } TEST_F(StackA2dpTest, test_a2dp_codec_index_str) { @@ -905,25 +869,19 @@ TEST_F(StackA2dpTest, test_a2dp_codec_index_str) { EXPECT_STREQ(A2DP_CodecIndexStr(BTAV_A2DP_CODEC_INDEX_SOURCE_SBC), "SBC"); EXPECT_STREQ(A2DP_CodecIndexStr(BTAV_A2DP_CODEC_INDEX_SINK_SBC), "SBC SINK"); EXPECT_STREQ(A2DP_CodecIndexStr(BTAV_A2DP_CODEC_INDEX_SOURCE_AAC), "AAC"); - ASSERT_STREQ(A2DP_VendorCodecIndexStr(BTAV_A2DP_CODEC_INDEX_SOURCE_OPUS), - "Opus"); - ASSERT_STREQ(A2DP_VendorCodecIndexStr(BTAV_A2DP_CODEC_INDEX_SINK_OPUS), - "Opus SINK"); + ASSERT_STREQ(A2DP_VendorCodecIndexStr(BTAV_A2DP_CODEC_INDEX_SOURCE_OPUS), "Opus"); + ASSERT_STREQ(A2DP_VendorCodecIndexStr(BTAV_A2DP_CODEC_INDEX_SINK_OPUS), "Opus SINK"); // Test that the unknown codec string has not changed - EXPECT_STREQ(A2DP_CodecIndexStr(BTAV_A2DP_CODEC_INDEX_MAX), - "UNKNOWN CODEC INDEX"); + EXPECT_STREQ(A2DP_CodecIndexStr(BTAV_A2DP_CODEC_INDEX_MAX), "UNKNOWN CODEC INDEX"); // Test that each codec has a known string for (int i = BTAV_A2DP_CODEC_INDEX_MIN; i < BTAV_A2DP_CODEC_INDEX_MAX; i++) { - if ((i >= BTAV_A2DP_CODEC_INDEX_SOURCE_EXT_MIN && - i < BTAV_A2DP_CODEC_INDEX_SOURCE_EXT_MAX) || - (i >= BTAV_A2DP_CODEC_INDEX_SINK_EXT_MIN && - i < BTAV_A2DP_CODEC_INDEX_SINK_EXT_MAX)) { + if ((i >= BTAV_A2DP_CODEC_INDEX_SOURCE_EXT_MIN && i < BTAV_A2DP_CODEC_INDEX_SOURCE_EXT_MAX) || + (i >= BTAV_A2DP_CODEC_INDEX_SINK_EXT_MIN && i < BTAV_A2DP_CODEC_INDEX_SINK_EXT_MAX)) { continue; } - btav_a2dp_codec_index_t codec_index = - static_cast(i); + btav_a2dp_codec_index_t codec_index = static_cast(i); EXPECT_STRNE(A2DP_CodecIndexStr(codec_index), "UNKNOWN CODEC INDEX"); } } @@ -935,8 +893,7 @@ TEST_F(StackA2dpTest, test_a2dp_init_codec_config) { // Test for SBC Source // memset(&avdt_cfg, 0, sizeof(avdt_cfg)); - EXPECT_TRUE( - A2DP_InitCodecConfig(BTAV_A2DP_CODEC_INDEX_SOURCE_SBC, &avdt_cfg)); + EXPECT_TRUE(A2DP_InitCodecConfig(BTAV_A2DP_CODEC_INDEX_SOURCE_SBC, &avdt_cfg)); // Compare the result codec with the local test codec info for (size_t i = 0; i < codec_info_sbc_capability[0] + 1; i++) { EXPECT_EQ(avdt_cfg.codec_info[i], codec_info_sbc_capability[i]); @@ -956,11 +913,9 @@ TEST_F(StackA2dpTest, test_a2dp_init_codec_config) { // Test for AAC Source // memset(&avdt_cfg, 0, sizeof(avdt_cfg)); - ASSERT_TRUE( - A2DP_InitCodecConfig(BTAV_A2DP_CODEC_INDEX_SOURCE_AAC, &avdt_cfg)); + ASSERT_TRUE(A2DP_InitCodecConfig(BTAV_A2DP_CODEC_INDEX_SOURCE_AAC, &avdt_cfg)); // Check the vbr mode status. - bool aac_vbr_mode_enabled = - avdt_cfg.codec_info[6] & A2DP_AAC_VARIABLE_BIT_RATE_MASK; + bool aac_vbr_mode_enabled = avdt_cfg.codec_info[6] & A2DP_AAC_VARIABLE_BIT_RATE_MASK; // Compare the result codec with the local test codec info if (aac_vbr_mode_enabled) { for (size_t i = 0; i < codec_info_aac_vbr_capability[0] + 1; i++) { @@ -975,8 +930,7 @@ TEST_F(StackA2dpTest, test_a2dp_init_codec_config) { TEST_F(A2dpCodecConfigTest, createCodec) { for (int i = BTAV_A2DP_CODEC_INDEX_MIN; i < BTAV_A2DP_CODEC_INDEX_MAX; i++) { - btav_a2dp_codec_index_t codec_index = - static_cast(i); + btav_a2dp_codec_index_t codec_index = static_cast(i); // Ignore codecs that are not supported on the device if (!has_codec_support(codec_index)) { @@ -996,8 +950,7 @@ TEST_F(A2dpCodecConfigTest, createCodec) { TEST_F(A2dpCodecConfigTest, setCodecConfig) { uint8_t codec_info_result[AVDT_CODEC_SIZE]; btav_a2dp_codec_index_t peer_codec_index; - A2dpCodecs* a2dp_codecs = - new A2dpCodecs(std::vector()); + A2dpCodecs* a2dp_codecs = new A2dpCodecs(std::vector()); A2dpCodecConfig* codec_config; EXPECT_TRUE(a2dp_codecs->init()); @@ -1006,12 +959,10 @@ TEST_F(A2dpCodecConfigTest, setCodecConfig) { memset(codec_info_result, 0, sizeof(codec_info_result)); peer_codec_index = A2DP_SourceCodecIndex(codec_info_sbc_sink_capability); EXPECT_NE(peer_codec_index, BTAV_A2DP_CODEC_INDEX_MAX); - codec_config = - a2dp_codecs->findSourceCodecConfig(codec_info_sbc_sink_capability); + codec_config = a2dp_codecs->findSourceCodecConfig(codec_info_sbc_sink_capability); EXPECT_NE(codec_config, nullptr); - EXPECT_TRUE(a2dp_codecs->setCodecConfig( - codec_info_sbc_sink_capability, true /* is_capability */, - codec_info_result, true /* select_current_codec */)); + EXPECT_TRUE(a2dp_codecs->setCodecConfig(codec_info_sbc_sink_capability, true /* is_capability */, + codec_info_result, true /* select_current_codec */)); EXPECT_EQ(a2dp_codecs->getCurrentCodecConfig(), codec_config); // Compare the result codec with the local test codec info for (size_t i = 0; i < codec_info_sbc[0] + 1; i++) { @@ -1025,9 +976,8 @@ TEST_F(A2dpCodecConfigTest, setCodecConfig) { EXPECT_NE(peer_codec_index, BTAV_A2DP_CODEC_INDEX_MAX); codec_config = a2dp_codecs->findSourceCodecConfig(codec_info_sbc); EXPECT_NE(codec_config, nullptr); - EXPECT_TRUE(a2dp_codecs->setCodecConfig( - codec_info_sbc, false /* is_capability */, codec_info_result, - true /* select_current_codec */)); + EXPECT_TRUE(a2dp_codecs->setCodecConfig(codec_info_sbc, false /* is_capability */, + codec_info_result, true /* select_current_codec */)); EXPECT_EQ(a2dp_codecs->getCurrentCodecConfig(), codec_config); // Compare the result codec with the local test codec info for (size_t i = 0; i < codec_info_sbc[0] + 1; i++) { @@ -1041,9 +991,8 @@ TEST_F(A2dpCodecConfigTest, setCodecConfig) { EXPECT_NE(peer_codec_index, BTAV_A2DP_CODEC_INDEX_MAX); codec_config = a2dp_codecs->findSourceCodecConfig(codec_info_aac); EXPECT_NE(codec_config, nullptr); - EXPECT_TRUE(a2dp_codecs->setCodecConfig( - codec_info_aac, false /* is_capability */, codec_info_result, - true /* select_current_codec */)); + EXPECT_TRUE(a2dp_codecs->setCodecConfig(codec_info_aac, false /* is_capability */, + codec_info_result, true /* select_current_codec */)); EXPECT_EQ(a2dp_codecs->getCurrentCodecConfig(), codec_config); // Compare the result codec with the local test codec info for (size_t i = 0; i < codec_info_aac[0] + 1; i++) { @@ -1057,9 +1006,8 @@ TEST_F(A2dpCodecConfigTest, setCodecConfig) { EXPECT_NE(peer_codec_index, BTAV_A2DP_CODEC_INDEX_MAX); codec_config = a2dp_codecs->findSinkCodecConfig(codec_info_sbc_capability); EXPECT_NE(codec_config, nullptr); - EXPECT_TRUE(a2dp_codecs->setSinkCodecConfig( - codec_info_sbc_capability, true /* is_capability */, codec_info_result, - true /* select_current_codec */)); + EXPECT_TRUE(a2dp_codecs->setSinkCodecConfig(codec_info_sbc_capability, true /* is_capability */, + codec_info_result, true /* select_current_codec */)); EXPECT_EQ(a2dp_codecs->getCurrentCodecConfig(), codec_config); // Compare the result codec with the local test codec info for (size_t i = 0; i < codec_info_sbc[0] + 1; i++) { @@ -1073,9 +1021,8 @@ TEST_F(A2dpCodecConfigTest, setCodecConfig) { EXPECT_NE(peer_codec_index, BTAV_A2DP_CODEC_INDEX_MAX); codec_config = a2dp_codecs->findSinkCodecConfig(codec_info_aac_capability); EXPECT_NE(codec_config, nullptr); - EXPECT_TRUE(a2dp_codecs->setSinkCodecConfig( - codec_info_aac_capability, true /* is_capability */, codec_info_result, - true /* select_current_codec */)); + EXPECT_TRUE(a2dp_codecs->setSinkCodecConfig(codec_info_aac_capability, true /* is_capability */, + codec_info_result, true /* select_current_codec */)); EXPECT_EQ(a2dp_codecs->getCurrentCodecConfig(), codec_config); // Compare the result codec with the local test codec info for (size_t i = 0; i < codec_info_aac[0] + 1; i++) { @@ -1089,9 +1036,8 @@ TEST_F(A2dpCodecConfigTest, setCodecConfig) { EXPECT_NE(peer_codec_index, BTAV_A2DP_CODEC_INDEX_MAX); codec_config = a2dp_codecs->findSinkCodecConfig(codec_info_sbc); EXPECT_NE(codec_config, nullptr); - EXPECT_TRUE(a2dp_codecs->setSinkCodecConfig( - codec_info_sbc, false /* is_capability */, codec_info_result, - true /* select_current_codec */)); + EXPECT_TRUE(a2dp_codecs->setSinkCodecConfig(codec_info_sbc, false /* is_capability */, + codec_info_result, true /* select_current_codec */)); EXPECT_EQ(a2dp_codecs->getCurrentCodecConfig(), codec_config); // Compare the result codec with the local test codec info for (size_t i = 0; i < codec_info_sbc[0] + 1; i++) { @@ -1105,9 +1051,8 @@ TEST_F(A2dpCodecConfigTest, setCodecConfig) { EXPECT_NE(peer_codec_index, BTAV_A2DP_CODEC_INDEX_MAX); codec_config = a2dp_codecs->findSinkCodecConfig(codec_info_aac); EXPECT_NE(codec_config, nullptr); - EXPECT_TRUE(a2dp_codecs->setSinkCodecConfig( - codec_info_aac, false /* is_capability */, codec_info_result, - true /* select_current_codec */)); + EXPECT_TRUE(a2dp_codecs->setSinkCodecConfig(codec_info_aac, false /* is_capability */, + codec_info_result, true /* select_current_codec */)); EXPECT_EQ(a2dp_codecs->getCurrentCodecConfig(), codec_config); // Compare the result codec with the local test codec info for (size_t i = 0; i < codec_info_aac[0] + 1; i++) { @@ -1119,27 +1064,22 @@ TEST_F(A2dpCodecConfigTest, setCodecConfig) { uint8_t codec_info_sbc_test1[AVDT_CODEC_SIZE]; memset(codec_info_result, 0, sizeof(codec_info_result)); memset(codec_info_sbc_test1, 0, sizeof(codec_info_sbc_test1)); - EXPECT_FALSE(a2dp_codecs->setCodecConfig( - codec_info_sbc_test1, true /* is_capability */, codec_info_result, - true /* select_current_codec */)); + EXPECT_FALSE(a2dp_codecs->setCodecConfig(codec_info_sbc_test1, true /* is_capability */, + codec_info_result, true /* select_current_codec */)); AvdtpSepConfig avdt_cfg; memset(&avdt_cfg, 0, sizeof(avdt_cfg)); - ASSERT_TRUE( - A2DP_InitCodecConfig(BTAV_A2DP_CODEC_INDEX_SOURCE_AAC, &avdt_cfg)); - bool aac_vbr_mode_enabled = - avdt_cfg.codec_info[6] & A2DP_AAC_VARIABLE_BIT_RATE_MASK; + ASSERT_TRUE(A2DP_InitCodecConfig(BTAV_A2DP_CODEC_INDEX_SOURCE_AAC, &avdt_cfg)); + bool aac_vbr_mode_enabled = avdt_cfg.codec_info[6] & A2DP_AAC_VARIABLE_BIT_RATE_MASK; // Create the codec capability - AAC memset(codec_info_result, 0, sizeof(codec_info_result)); peer_codec_index = A2DP_SourceCodecIndex(codec_info_aac_sink_capability); ASSERT_NE(peer_codec_index, BTAV_A2DP_CODEC_INDEX_MAX); - codec_config = - a2dp_codecs->findSourceCodecConfig(codec_info_aac_sink_capability); + codec_config = a2dp_codecs->findSourceCodecConfig(codec_info_aac_sink_capability); ASSERT_NE(codec_config, nullptr); - ASSERT_TRUE(a2dp_codecs->setCodecConfig( - codec_info_aac_sink_capability, true /* is_capability */, - codec_info_result, true /* select_current_codec */)); + ASSERT_TRUE(a2dp_codecs->setCodecConfig(codec_info_aac_sink_capability, true /* is_capability */, + codec_info_result, true /* select_current_codec */)); ASSERT_EQ(a2dp_codecs->getCurrentCodecConfig(), codec_config); // Compare the result codec with the local test codec info if (aac_vbr_mode_enabled) { @@ -1159,9 +1099,8 @@ TEST_F(A2dpCodecConfigTest, setCodecConfig) { ASSERT_NE(peer_codec_index, BTAV_A2DP_CODEC_INDEX_MAX); codec_config = a2dp_codecs->findSourceCodecConfig(codec_info_aac_vbr); ASSERT_NE(codec_config, nullptr); - ASSERT_TRUE(a2dp_codecs->setCodecConfig( - codec_info_aac_vbr, false /* is_capability */, codec_info_result, - true /* select_current_codec */)); + ASSERT_TRUE(a2dp_codecs->setCodecConfig(codec_info_aac_vbr, false /* is_capability */, + codec_info_result, true /* select_current_codec */)); ASSERT_EQ(a2dp_codecs->getCurrentCodecConfig(), codec_config); // Compare the result codec with the local test codec info if (aac_vbr_mode_enabled) { @@ -1184,11 +1123,9 @@ TEST_F(A2dpCodecConfigTest, init) { EXPECT_TRUE(codecs.init()); - const std::list orderedSourceCodecs = - codecs.orderedSourceCodecs(); + const std::list orderedSourceCodecs = codecs.orderedSourceCodecs(); EXPECT_FALSE(orderedSourceCodecs.empty()); - const std::list orderedSinkCodecs = - codecs.orderedSinkCodecs(); + const std::list orderedSinkCodecs = codecs.orderedSinkCodecs(); EXPECT_FALSE(orderedSinkCodecs.empty()); } diff --git a/system/stack/test/stack_acl_test.cc b/system/stack/test/stack_acl_test.cc index 59f8c8db1e1..85858b012f5 100644 --- a/system/stack/test/stack_acl_test.cc +++ b/system/stack/test/stack_acl_test.cc @@ -46,14 +46,12 @@ std::set copy_of_connected_with_both_public_and_random_set(); } // namespace bluetooth class StackAclTest : public testing::Test { - protected: +protected: void SetUp() override { reset_mock_function_count_map(); bluetooth::hci::testing::mock_controller_ = &controller_; } - void TearDown() override { - bluetooth::hci::testing::mock_controller_ = nullptr; - } + void TearDown() override { bluetooth::hci::testing::mock_controller_ = nullptr; } tBTM_SEC_DEV_REC device_record_; bluetooth::hci::testing::MockControllerInterface controller_; @@ -73,8 +71,7 @@ TEST_F(StackAclTest, acl_process_extended_features) { // Handle typical case { const uint8_t max_page = 3; - memset((void*)p_acl->peer_lmp_feature_valid, 0, - HCI_EXT_FEATURES_PAGE_MAX + 1); + memset((void*)p_acl->peer_lmp_feature_valid, 0, HCI_EXT_FEATURES_PAGE_MAX + 1); acl_process_extended_features(hci_handle, 1, max_page, 0xf123456789abcde); acl_process_extended_features(hci_handle, 2, max_page, 0xef123456789abcd); acl_process_extended_features(hci_handle, 3, max_page, 0xdef123456789abc); @@ -89,11 +86,10 @@ TEST_F(StackAclTest, acl_process_extended_features) { // Handle extreme case { const uint8_t max_page = 255; - memset((void*)p_acl->peer_lmp_feature_valid, 0, - HCI_EXT_FEATURES_PAGE_MAX + 1); + memset((void*)p_acl->peer_lmp_feature_valid, 0, HCI_EXT_FEATURES_PAGE_MAX + 1); for (int i = 1; i < HCI_EXT_FEATURES_PAGE_MAX + 1; i++) { - acl_process_extended_features(hci_handle, static_cast(i), - max_page, 0x123456789abcdef); + acl_process_extended_features(hci_handle, static_cast(i), max_page, + 0x123456789abcdef); } /* page 0 is the standard feature set */ ASSERT_FALSE(p_acl->peer_lmp_feature_valid[0]); @@ -104,8 +100,7 @@ TEST_F(StackAclTest, acl_process_extended_features) { // Handle case where device returns max page of zero { - memset((void*)p_acl->peer_lmp_feature_valid, 0, - HCI_EXT_FEATURES_PAGE_MAX + 1); + memset((void*)p_acl->peer_lmp_feature_valid, 0, HCI_EXT_FEATURES_PAGE_MAX + 1); acl_process_extended_features(hci_handle, 1, 0, 0xdef123456789abc); ASSERT_FALSE(p_acl->peer_lmp_feature_valid[0]); ASSERT_TRUE(p_acl->peer_lmp_feature_valid[1]); diff --git a/system/stack/test/stack_avdtp_test.cc b/system/stack/test/stack_avdtp_test.cc index a6ec0e063d7..651eea12c1b 100644 --- a/system/stack/test/stack_avdtp_test.cc +++ b/system/stack/test/stack_avdtp_test.cc @@ -14,7 +14,7 @@ * limitations under the License. */ -//#include +// #include #include #include @@ -29,32 +29,30 @@ #include "types/raw_address.h" class StackAvdtpTest : public ::testing::Test { - protected: +protected: StackAvdtpTest() = default; virtual ~StackAvdtpTest() = default; - protected: + +protected: static AvdtpRcb reg_ctrl_block_; static uint8_t callback_event_; static uint8_t scb_handle_; - protected: - static void AvdtConnCallback(uint8_t handle, const RawAddress& bd_addr, - uint8_t event, tAVDT_CTRL* p_data, - uint8_t scb_index) { +protected: + static void AvdtConnCallback(uint8_t handle, const RawAddress& bd_addr, uint8_t event, + tAVDT_CTRL* p_data, uint8_t scb_index) { inc_func_call_count(__func__); callback_event_ = event; } - static void StreamCtrlCallback(uint8_t handle, const RawAddress& bd_addr, - uint8_t event, tAVDT_CTRL* p_data, - uint8_t scb_index) { + static void StreamCtrlCallback(uint8_t handle, const RawAddress& bd_addr, uint8_t event, + tAVDT_CTRL* p_data, uint8_t scb_index) { inc_func_call_count(__func__); callback_event_ = event; } - static void AvdtReportCallback(uint8_t handle, AVDT_REPORT_TYPE type, - tAVDT_REPORT_DATA* p_data) { + static void AvdtReportCallback(uint8_t handle, AVDT_REPORT_TYPE type, tAVDT_REPORT_DATA* p_data) { inc_func_call_count(__func__); } @@ -185,14 +183,14 @@ TEST_F(StackAvdtpTest, test_delay_report_as_init) { TEST_F(StackAvdtpTest, test_SR_reporting_handler) { constexpr uint8_t sender_report_packet[] = { - // Header - 0x80, 0xc8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - // Sender Info - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - // Report Block #1 - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + // Header + 0x80, 0xc8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + // Sender Info + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, + // Report Block #1 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; uint16_t packet_length = sizeof(sender_report_packet); tAVDT_SCB_EVT data; auto pscb = avdt_scb_by_hdl(scb_handle_); @@ -226,12 +224,12 @@ TEST_F(StackAvdtpTest, test_SR_reporting_handler) { } TEST_F(StackAvdtpTest, test_RR_reporting_handler) { - constexpr uint8_t receiver_report_packet[] = { - // Header - 0x80, 0xc9, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - // Report Block #1 - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + constexpr uint8_t receiver_report_packet[] = {// Header + 0x80, 0xc9, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + // Report Block #1 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; uint16_t packet_length = sizeof(receiver_report_packet); tAVDT_SCB_EVT data; auto pscb = avdt_scb_by_hdl(scb_handle_); @@ -270,8 +268,7 @@ TEST_F(StackAvdtpTest, test_SDES_reporting_handler) { // Chunk #1 0x00, 0x00, 0x00, 0x00, // SDES Item (CNAME=1) - 0x01, 0x05, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00}; + 0x01, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; uint16_t packet_length = sizeof(source_description_packet); tAVDT_SCB_EVT data; auto pscb = avdt_scb_by_hdl(scb_handle_); @@ -325,7 +322,7 @@ TEST_F(StackAvdtpTest, avdt_scb_hdl_pkt_no_frag_regression_test0) { BT_HDR* p_pkt = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + extra_size); ASSERT_NE(p_pkt, nullptr); tAVDT_SCB_EVT evt_data = { - .p_pkt = p_pkt, + .p_pkt = p_pkt, }; p_pkt->len = 0; @@ -347,7 +344,7 @@ TEST_F(StackAvdtpTest, avdt_scb_hdl_pkt_no_frag_regression_test1) { BT_HDR* p_pkt = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + extra_size); ASSERT_NE(p_pkt, nullptr); tAVDT_SCB_EVT evt_data = { - .p_pkt = p_pkt, + .p_pkt = p_pkt, }; // setup p_pkt @@ -381,7 +378,7 @@ TEST_F(StackAvdtpTest, avdt_scb_hdl_pkt_no_frag_regression_test2) { BT_HDR* p_pkt = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + extra_size); ASSERT_NE(p_pkt, nullptr); tAVDT_SCB_EVT evt_data = { - .p_pkt = p_pkt, + .p_pkt = p_pkt, }; // setup p_pkt @@ -418,7 +415,7 @@ TEST_F(StackAvdtpTest, avdt_scb_hdl_pkt_no_frag_regression_test3) { BT_HDR* p_pkt = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + extra_size); ASSERT_NE(p_pkt, nullptr); tAVDT_SCB_EVT evt_data = { - .p_pkt = p_pkt, + .p_pkt = p_pkt, }; // setup p_pkt diff --git a/system/stack/test/stack_avrcp_test.cc b/system/stack/test/stack_avrcp_test.cc index c236eb90643..bb8bae64f2f 100644 --- a/system/stack/test/stack_avrcp_test.cc +++ b/system/stack/test/stack_avrcp_test.cc @@ -22,7 +22,7 @@ #include "stack/include/bt_types.h" class StackAvrcpTest : public ::testing::Test { - protected: +protected: StackAvrcpTest() = default; virtual ~StackAvrcpTest() = default; @@ -48,9 +48,8 @@ TEST_F(StackAvrcpTest, test_avrcp_ctrl_parse_vendor_rsp) { UINT16_TO_STREAM(p, 0xffff); // attribute value length msg.vendor.p_vendor_data = vendor_rsp_buf; msg.vendor.vendor_len = 13; - EXPECT_EQ( - AVRC_Ctrl_ParsResponse(&msg, &result, scratch_buf, &scratch_buf_len), - AVRC_STS_INTERNAL_ERR); + EXPECT_EQ(AVRC_Ctrl_ParsResponse(&msg, &result, scratch_buf, &scratch_buf_len), + AVRC_STS_INTERNAL_ERR); } TEST_F(StackAvrcpTest, test_avrcp_parse_browse_rsp) { @@ -73,9 +72,7 @@ TEST_F(StackAvrcpTest, test_avrcp_parse_browse_rsp) { UINT16_TO_STREAM(p, 0xffff); // attribute value length msg.browse.p_browse_data = browse_rsp_buf; msg.browse.browse_len = 13; - EXPECT_EQ( - AVRC_Ctrl_ParsResponse(&msg, &result, scratch_buf, &scratch_buf_len), - AVRC_STS_BAD_CMD); + EXPECT_EQ(AVRC_Ctrl_ParsResponse(&msg, &result, scratch_buf, &scratch_buf_len), AVRC_STS_BAD_CMD); } TEST_F(StackAvrcpTest, test_avrcp_parse_browse_cmd) { @@ -87,24 +84,20 @@ TEST_F(StackAvrcpTest, test_avrcp_parse_browse_cmd) { msg.hdr.opcode = AVRC_OP_BROWSE; msg.browse.p_browse_data = browse_cmd_buf; msg.browse.browse_len = 2; - EXPECT_EQ(AVRC_ParsCommand(&msg, &result, scratch_buf, sizeof(scratch_buf)), - AVRC_STS_BAD_CMD); + EXPECT_EQ(AVRC_ParsCommand(&msg, &result, scratch_buf, sizeof(scratch_buf)), AVRC_STS_BAD_CMD); memset(browse_cmd_buf, 0, sizeof(browse_cmd_buf)); browse_cmd_buf[0] = AVRC_PDU_SET_BROWSED_PLAYER; msg.browse.browse_len = 3; - EXPECT_EQ(AVRC_ParsCommand(&msg, &result, scratch_buf, sizeof(scratch_buf)), - AVRC_STS_BAD_CMD); + EXPECT_EQ(AVRC_ParsCommand(&msg, &result, scratch_buf, sizeof(scratch_buf)), AVRC_STS_BAD_CMD); msg.browse.browse_len = 5; - EXPECT_EQ(AVRC_ParsCommand(&msg, &result, scratch_buf, sizeof(scratch_buf)), - AVRC_STS_NO_ERROR); + EXPECT_EQ(AVRC_ParsCommand(&msg, &result, scratch_buf, sizeof(scratch_buf)), AVRC_STS_NO_ERROR); memset(browse_cmd_buf, 0, sizeof(browse_cmd_buf)); browse_cmd_buf[0] = AVRC_PDU_GET_FOLDER_ITEMS; msg.browse.browse_len = 3; - EXPECT_EQ(AVRC_ParsCommand(&msg, &result, scratch_buf, sizeof(scratch_buf)), - AVRC_STS_BAD_CMD); + EXPECT_EQ(AVRC_ParsCommand(&msg, &result, scratch_buf, sizeof(scratch_buf)), AVRC_STS_BAD_CMD); msg.browse.browse_len = 13; uint8_t* p = &browse_cmd_buf[3]; @@ -112,55 +105,46 @@ TEST_F(StackAvrcpTest, test_avrcp_parse_browse_cmd) { UINT32_TO_STREAM(p, 0x00000001); // start_item UINT32_TO_STREAM(p, 0x00000002); // end_item browse_cmd_buf[12] = 0; // attr_count - EXPECT_EQ(AVRC_ParsCommand(&msg, &result, scratch_buf, sizeof(scratch_buf)), - AVRC_STS_NO_ERROR); + EXPECT_EQ(AVRC_ParsCommand(&msg, &result, scratch_buf, sizeof(scratch_buf)), AVRC_STS_NO_ERROR); memset(browse_cmd_buf, 0, sizeof(browse_cmd_buf)); browse_cmd_buf[0] = AVRC_PDU_CHANGE_PATH; msg.browse.browse_len = 3; - EXPECT_EQ(AVRC_ParsCommand(&msg, &result, scratch_buf, sizeof(scratch_buf)), - AVRC_STS_BAD_CMD); + EXPECT_EQ(AVRC_ParsCommand(&msg, &result, scratch_buf, sizeof(scratch_buf)), AVRC_STS_BAD_CMD); msg.browse.browse_len = 14; p = &browse_cmd_buf[3]; UINT16_TO_STREAM(p, 0x1234); // uid_counter UINT8_TO_STREAM(p, AVRC_DIR_UP); // direction UINT8_TO_STREAM(p, 0); // attr_count - EXPECT_EQ(AVRC_ParsCommand(&msg, &result, scratch_buf, sizeof(scratch_buf)), - AVRC_STS_NO_ERROR); + EXPECT_EQ(AVRC_ParsCommand(&msg, &result, scratch_buf, sizeof(scratch_buf)), AVRC_STS_NO_ERROR); memset(browse_cmd_buf, 0, sizeof(browse_cmd_buf)); browse_cmd_buf[0] = AVRC_PDU_GET_ITEM_ATTRIBUTES; msg.browse.browse_len = 3; - EXPECT_EQ(AVRC_ParsCommand(&msg, &result, scratch_buf, sizeof(scratch_buf)), - AVRC_STS_BAD_CMD); + EXPECT_EQ(AVRC_ParsCommand(&msg, &result, scratch_buf, sizeof(scratch_buf)), AVRC_STS_BAD_CMD); msg.browse.browse_len = 15; - EXPECT_EQ(AVRC_ParsCommand(&msg, &result, scratch_buf, sizeof(scratch_buf)), - AVRC_STS_NO_ERROR); + EXPECT_EQ(AVRC_ParsCommand(&msg, &result, scratch_buf, sizeof(scratch_buf)), AVRC_STS_NO_ERROR); memset(browse_cmd_buf, 0, sizeof(browse_cmd_buf)); browse_cmd_buf[0] = AVRC_PDU_GET_TOTAL_NUM_OF_ITEMS; msg.browse.browse_len = 3; - EXPECT_EQ(AVRC_ParsCommand(&msg, &result, scratch_buf, sizeof(scratch_buf)), - AVRC_STS_BAD_CMD); + EXPECT_EQ(AVRC_ParsCommand(&msg, &result, scratch_buf, sizeof(scratch_buf)), AVRC_STS_BAD_CMD); msg.browse.browse_len = 4; - EXPECT_EQ(AVRC_ParsCommand(&msg, &result, scratch_buf, sizeof(scratch_buf)), - AVRC_STS_NO_ERROR); + EXPECT_EQ(AVRC_ParsCommand(&msg, &result, scratch_buf, sizeof(scratch_buf)), AVRC_STS_NO_ERROR); memset(browse_cmd_buf, 0, sizeof(browse_cmd_buf)); browse_cmd_buf[0] = AVRC_PDU_SEARCH; msg.browse.browse_len = 3; - EXPECT_EQ(AVRC_ParsCommand(&msg, &result, scratch_buf, sizeof(scratch_buf)), - AVRC_STS_BAD_CMD); + EXPECT_EQ(AVRC_ParsCommand(&msg, &result, scratch_buf, sizeof(scratch_buf)), AVRC_STS_BAD_CMD); p = &browse_cmd_buf[3]; UINT16_TO_STREAM(p, 0x0000); // charset_id UINT16_TO_STREAM(p, 0x0000); // str_len msg.browse.browse_len = 7; - EXPECT_EQ(AVRC_ParsCommand(&msg, &result, scratch_buf, sizeof(scratch_buf)), - AVRC_STS_NO_ERROR); + EXPECT_EQ(AVRC_ParsCommand(&msg, &result, scratch_buf, sizeof(scratch_buf)), AVRC_STS_NO_ERROR); } TEST_F(StackAvrcpTest, test_avrcp_pdu_register_notification) { @@ -175,27 +159,27 @@ TEST_F(StackAvrcpTest, test_avrcp_pdu_register_notification) { uint32_t param; } payload; } data = { - AVRC_PDU_REGISTER_NOTIFICATION, - 0, // reserved - htons(sizeof(data.payload)), - .payload = - { - .event_id = 0, - .param = 0x1234, - }, + AVRC_PDU_REGISTER_NOTIFICATION, + 0, // reserved + htons(sizeof(data.payload)), + .payload = + { + .event_id = 0, + .param = 0x1234, + }, }; tAVRC_MSG msg = { - .vendor = - { - .hdr = + .vendor = { - .ctype = AVRC_CMD_NOTIF, - .opcode = AVRC_OP_VENDOR, + .hdr = + { + .ctype = AVRC_CMD_NOTIF, + .opcode = AVRC_OP_VENDOR, + }, + .p_vendor_data = (uint8_t*)&data, + .vendor_len = sizeof(data), }, - .p_vendor_data = (uint8_t*)&data, - .vendor_len = sizeof(data), - }, }; tAVRC_COMMAND result{}; @@ -203,8 +187,7 @@ TEST_F(StackAvrcpTest, test_avrcp_pdu_register_notification) { uint8_t id = 0; do { data.payload.event_id = id; - ASSERT_EQ((id == 0 || id > AVRC_NUM_NOTIF_EVENTS) ? AVRC_STS_BAD_PARAM - : AVRC_STS_NO_ERROR, + ASSERT_EQ((id == 0 || id > AVRC_NUM_NOTIF_EVENTS) ? AVRC_STS_BAD_PARAM : AVRC_STS_NO_ERROR, AVRC_Ctrl_ParsCommand(&msg, &result)); } while (++id != 0); } diff --git a/system/stack/test/stack_btu_test.cc b/system/stack/test/stack_btu_test.cc index 3ea7b168c5b..4d3906f14f5 100644 --- a/system/stack/test/stack_btu_test.cc +++ b/system/stack/test/stack_btu_test.cc @@ -24,11 +24,10 @@ #include "test/common/mock_functions.h" /* Function for test provided by btu_hcif.cc */ -void btu_hcif_hdl_command_status(uint16_t opcode, uint8_t status, - const uint8_t* p_cmd); +void btu_hcif_hdl_command_status(uint16_t opcode, uint8_t status, const uint8_t* p_cmd); class StackBtuTest : public ::testing::Test { - protected: +protected: void SetUp() override { reset_mock_function_count_map(); } }; @@ -36,7 +35,7 @@ TEST_F(StackBtuTest, post_on_main) {} TEST_F(StackBtuTest, btm_sco_connection_failed_called) { uint8_t p_cmd[10]; // garbage data for testing - bluetooth::legacy::testing::btu_hcif_hdl_command_status( - HCI_SETUP_ESCO_CONNECTION, HCI_ERR_UNSPECIFIED, p_cmd); + bluetooth::legacy::testing::btu_hcif_hdl_command_status(HCI_SETUP_ESCO_CONNECTION, + HCI_ERR_UNSPECIFIED, p_cmd); ASSERT_EQ(1, get_func_call_count("btm_sco_connection_failed")); } diff --git a/system/stack/test/stack_gatt_sr_hash_test.cc b/system/stack/test/stack_gatt_sr_hash_test.cc index ad3ac96832c..aeefe6318a1 100644 --- a/system/stack/test/stack_gatt_sr_hash_test.cc +++ b/system/stack/test/stack_gatt_sr_hash_test.cc @@ -25,8 +25,8 @@ using bluetooth::Uuid; tGATT_CB gatt_cb; -static void add_item_to_list(std::list& srv_list_info, - tGATT_SVC_DB* db, bool is_primary) { +static void add_item_to_list(std::list& srv_list_info, tGATT_SVC_DB* db, + bool is_primary) { srv_list_info.emplace_back(); tGATT_SRV_LIST_ELEM& elem = srv_list_info.back(); elem.p_db = db; @@ -36,44 +36,44 @@ static void add_item_to_list(std::list& srv_list_info, // BT Spec 5.2, Vol 3, Part G, Appendix B TEST(GattDatabaseTest, matchExampleInBtSpecV52) { tGATT_SVC_DB local_db[4]; - for (int i=0; i<4; i++) local_db[i] = tGATT_SVC_DB(); + for (int i = 0; i < 4; i++) { + local_db[i] = tGATT_SVC_DB(); + } std::list srv_list_info; // 0x1800 add_item_to_list(srv_list_info, &local_db[0], true); gatts_init_service_db(local_db[0], Uuid::From16Bit(0x1800), true, 0x0001, 5); - gatts_add_characteristic(local_db[0], - GATT_PERM_READ | GATT_PERM_WRITE, - GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_WRITE, - Uuid::From16Bit(0x2A00)); + gatts_add_characteristic(local_db[0], GATT_PERM_READ | GATT_PERM_WRITE, + GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_WRITE, + Uuid::From16Bit(0x2A00)); gatts_add_characteristic(local_db[0], GATT_PERM_READ, GATT_CHAR_PROP_BIT_READ, - Uuid::From16Bit(0x2A01)); + Uuid::From16Bit(0x2A01)); // 0x1801 add_item_to_list(srv_list_info, &local_db[1], true); gatts_init_service_db(local_db[1], Uuid::From16Bit(0x1801), true, 0x0006, 8); - gatts_add_characteristic(local_db[1], 0, GATT_CHAR_PROP_BIT_INDICATE, - Uuid::From16Bit(0x2A05)); + gatts_add_characteristic(local_db[1], 0, GATT_CHAR_PROP_BIT_INDICATE, Uuid::From16Bit(0x2A05)); gatts_add_char_descr(local_db[1], GATT_CHAR_PROP_BIT_READ, Uuid::From16Bit(0x2902)); - gatts_add_characteristic(local_db[1], - GATT_PERM_READ | GATT_PERM_WRITE, - GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_WRITE, - Uuid::From16Bit(0x2B29)); + gatts_add_characteristic(local_db[1], GATT_PERM_READ | GATT_PERM_WRITE, + GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_WRITE, + Uuid::From16Bit(0x2B29)); gatts_add_characteristic(local_db[1], GATT_PERM_READ, GATT_CHAR_PROP_BIT_READ, - Uuid::From16Bit(0x2B2A)); + Uuid::From16Bit(0x2B2A)); // 0x1808 add_item_to_list(srv_list_info, &local_db[2], true); gatts_init_service_db(local_db[2], Uuid::From16Bit(0x1808), true, 0x000E, 6); gatts_add_included_service(local_db[2], 0x0014, 0x0016, Uuid::From16Bit(0x180F)); - gatts_add_characteristic(local_db[2], GATT_PERM_READ, - GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_INDICATE | GATT_CHAR_PROP_BIT_EXT_PROP, - Uuid::From16Bit(0x2A18)); + gatts_add_characteristic( + local_db[2], GATT_PERM_READ, + GATT_CHAR_PROP_BIT_READ | GATT_CHAR_PROP_BIT_INDICATE | GATT_CHAR_PROP_BIT_EXT_PROP, + Uuid::From16Bit(0x2A18)); gatts_add_char_descr(local_db[2], 0x0000, Uuid::From16Bit(0x2902)); gatts_add_char_ext_prop_descr(local_db[2], 0x0000); // 0x180F add_item_to_list(srv_list_info, &local_db[3], false); gatts_init_service_db(local_db[3], Uuid::From16Bit(0x180F), false, 0x0014, 3); - gatts_add_characteristic(local_db[3], GATT_PERM_READ, GATT_CHAR_PROP_BIT_READ, - Uuid::From16Bit(0x2A19)); + gatts_add_characteristic(local_db[3], GATT_PERM_READ, GATT_CHAR_PROP_BIT_READ, + Uuid::From16Bit(0x2A19)); Octet16 expected_hash{0xF1, 0xCA, 0x2D, 0x48, 0xEC, 0xF5, 0x8B, 0xAC, 0x8A, 0x88, 0x30, 0xBB, 0xB9, 0xFB, 0xA9, 0x90}; diff --git a/system/stack/test/stack_include_test.cc b/system/stack/test/stack_include_test.cc index c6a47be04aa..3cb9c599224 100644 --- a/system/stack/test/stack_include_test.cc +++ b/system/stack/test/stack_include_test.cc @@ -19,7 +19,7 @@ #include "stack/include/bt_dev_class.h" class StackIncludeTest : public ::testing::Test { - protected: +protected: void SetUp() override {} void TearDown() override {} diff --git a/system/stack/test/stack_l2cap_test.cc b/system/stack/test/stack_l2cap_test.cc index 5214604fd9d..e01be4fe2d8 100644 --- a/system/stack/test/stack_l2cap_test.cc +++ b/system/stack/test/stack_l2cap_test.cc @@ -48,17 +48,16 @@ constexpr uint16_t kAclBufferSizeBle = 45; } // namespace class StackL2capTest : public ::testing::Test { - protected: +protected: void SetUp() override { bluetooth::common::InitFlags::SetAllForTesting(); bluetooth::hci::testing::mock_controller_ = &controller_interface_; ON_CALL(controller_interface_, GetNumAclPacketBuffers) - .WillByDefault(Return(kAclBufferCountClassic)); + .WillByDefault(Return(kAclBufferCountClassic)); bluetooth::hci::LeBufferSize le_sizes; le_sizes.total_num_le_packets_ = kAclBufferCountBle; le_sizes.le_data_packet_length_ = kAclBufferSizeBle; - ON_CALL(controller_interface_, GetLeBufferSize) - .WillByDefault(Return(le_sizes)); + ON_CALL(controller_interface_, GetLeBufferSize).WillByDefault(Return(le_sizes)); ON_CALL(controller_interface_, SupportsBle).WillByDefault(Return(true)); l2c_init(); } @@ -92,100 +91,98 @@ TEST_F(StackL2capTest, l2cble_process_data_length_change_event) { } class StackL2capChannelTest : public StackL2capTest { - protected: +protected: void SetUp() override { StackL2capTest::SetUp(); } void TearDown() override { StackL2capTest::TearDown(); } tL2C_CCB ccb_ = { - .in_use = true, - .chnl_state = CST_OPEN, // tL2C_CHNL_STATE - .local_conn_cfg = - { - // tL2CAP_LE_CFG_INFO - .result = 0, - .mtu = 100, - .mps = 100, - .credits = L2CA_LeCreditDefault(), - .number_of_channels = L2CAP_CREDIT_BASED_MAX_CIDS, - }, - .peer_conn_cfg = - { - // tL2CAP_LE_CFG_INFO - .result = 0, - .mtu = 100, - .mps = 100, - .credits = L2CA_LeCreditDefault(), - .number_of_channels = L2CAP_CREDIT_BASED_MAX_CIDS, - }, - .is_first_seg = false, - .ble_sdu = nullptr, // BT_HDR*; Buffer for storing unassembled sdu - .ble_sdu_length = 0, /* Length of unassembled sdu length*/ - .p_next_ccb = nullptr, // struct t_l2c_ccb* Next CCB in the chain - .p_prev_ccb = nullptr, // struct t_l2c_ccb* Previous CCB in the chain - .p_lcb = nullptr, // struct t_l2c_linkcb* Link this CCB is assigned to - .local_cid = 40, - .remote_cid = 80, - .l2c_ccb_timer = nullptr, // alarm_t* CCB Timer Entry - .p_rcb = nullptr, // tL2C_RCB* Registration CB for this Channel - .config_done = 0, // Configuration flag word - .remote_config_rsp_result = 0, // The config rsp result from remote - .local_id = 12, // Transaction ID for local trans - .remote_id = 22, // Transaction ID for local - .flags = 0, - .connection_initiator = false, - .our_cfg = {}, // tL2CAP_CFG_INFO Our saved configuration options - .peer_cfg = {}, // tL2CAP_CFG_INFO Peer's saved configuration options - .xmit_hold_q = nullptr, // fixed_queue_t* Transmit data hold queue - .cong_sent = false, - .buff_quota = 0, - - .ccb_priority = - L2CAP_CHNL_PRIORITY_HIGH, // tL2CAP_CHNL_PRIORITY Channel priority - .tx_data_rate = 0, // tL2CAP_CHNL_PRIORITY Channel Tx data rate - .rx_data_rate = 0, // tL2CAP_CHNL_PRIORITY Channel Rx data rate - - .ertm_info = - { - // .tL2CAP_ERTM_INFO - .preferred_mode = 0, - }, - .fcrb = - { - // tL2C_FCRB - .next_tx_seq = 0, - .last_rx_ack = 0, - .next_seq_expected = 0, - .last_ack_sent = 0, - .num_tries = 0, - .max_held_acks = 0, - .remote_busy = false, - .rej_sent = false, - .srej_sent = false, - .wait_ack = false, - .rej_after_srej = false, - .send_f_rsp = false, - .rx_sdu_len = 0, - .p_rx_sdu = - nullptr, // BT_HDR* Buffer holding the SDU being received - .waiting_for_ack_q = nullptr, // fixed_queue_t* - .srej_rcv_hold_q = nullptr, // fixed_queue_t* - .retrans_q = nullptr, // fixed_queue_t* - .ack_timer = nullptr, // alarm_t* - .mon_retrans_timer = nullptr, // alarm_t* - }, - .tx_mps = 0, - .max_rx_mtu = 0, - .fcr_cfg_tries = 0, - .peer_cfg_already_rejected = false, - .out_cfg_fcr_present = false, - .is_flushable = false, - .fixed_chnl_idle_tout = 0, - .tx_data_len = 0, - .remote_credit_count = 0, - .ecoc = false, - .reconfig_started = false, - .metrics = {}, + .in_use = true, + .chnl_state = CST_OPEN, // tL2C_CHNL_STATE + .local_conn_cfg = + { + // tL2CAP_LE_CFG_INFO + .result = 0, + .mtu = 100, + .mps = 100, + .credits = L2CA_LeCreditDefault(), + .number_of_channels = L2CAP_CREDIT_BASED_MAX_CIDS, + }, + .peer_conn_cfg = + { + // tL2CAP_LE_CFG_INFO + .result = 0, + .mtu = 100, + .mps = 100, + .credits = L2CA_LeCreditDefault(), + .number_of_channels = L2CAP_CREDIT_BASED_MAX_CIDS, + }, + .is_first_seg = false, + .ble_sdu = nullptr, // BT_HDR*; Buffer for storing unassembled sdu + .ble_sdu_length = 0, /* Length of unassembled sdu length*/ + .p_next_ccb = nullptr, // struct t_l2c_ccb* Next CCB in the chain + .p_prev_ccb = nullptr, // struct t_l2c_ccb* Previous CCB in the chain + .p_lcb = nullptr, // struct t_l2c_linkcb* Link this CCB is assigned to + .local_cid = 40, + .remote_cid = 80, + .l2c_ccb_timer = nullptr, // alarm_t* CCB Timer Entry + .p_rcb = nullptr, // tL2C_RCB* Registration CB for this Channel + .config_done = 0, // Configuration flag word + .remote_config_rsp_result = 0, // The config rsp result from remote + .local_id = 12, // Transaction ID for local trans + .remote_id = 22, // Transaction ID for local + .flags = 0, + .connection_initiator = false, + .our_cfg = {}, // tL2CAP_CFG_INFO Our saved configuration options + .peer_cfg = {}, // tL2CAP_CFG_INFO Peer's saved configuration options + .xmit_hold_q = nullptr, // fixed_queue_t* Transmit data hold queue + .cong_sent = false, + .buff_quota = 0, + + .ccb_priority = L2CAP_CHNL_PRIORITY_HIGH, // tL2CAP_CHNL_PRIORITY Channel priority + .tx_data_rate = 0, // tL2CAP_CHNL_PRIORITY Channel Tx data rate + .rx_data_rate = 0, // tL2CAP_CHNL_PRIORITY Channel Rx data rate + + .ertm_info = + { + // .tL2CAP_ERTM_INFO + .preferred_mode = 0, + }, + .fcrb = + { + // tL2C_FCRB + .next_tx_seq = 0, + .last_rx_ack = 0, + .next_seq_expected = 0, + .last_ack_sent = 0, + .num_tries = 0, + .max_held_acks = 0, + .remote_busy = false, + .rej_sent = false, + .srej_sent = false, + .wait_ack = false, + .rej_after_srej = false, + .send_f_rsp = false, + .rx_sdu_len = 0, + .p_rx_sdu = nullptr, // BT_HDR* Buffer holding the SDU being received + .waiting_for_ack_q = nullptr, // fixed_queue_t* + .srej_rcv_hold_q = nullptr, // fixed_queue_t* + .retrans_q = nullptr, // fixed_queue_t* + .ack_timer = nullptr, // alarm_t* + .mon_retrans_timer = nullptr, // alarm_t* + }, + .tx_mps = 0, + .max_rx_mtu = 0, + .fcr_cfg_tries = 0, + .peer_cfg_already_rejected = false, + .out_cfg_fcr_present = false, + .is_flushable = false, + .fixed_chnl_idle_tout = 0, + .tx_data_len = 0, + .remote_credit_count = 0, + .ecoc = false, + .reconfig_started = false, + .metrics = {}, }; }; @@ -216,47 +213,40 @@ TEST_F(StackL2capChannelTest, l2c_link_init) { TEST_F(StackL2capTest, l2cap_result_code_text) { std::vector> results = { - std::make_pair(L2CAP_CONN_OK, "L2CAP_CONN_OK"), - std::make_pair(L2CAP_CONN_PENDING, "L2CAP_CONN_PENDING"), - std::make_pair(L2CAP_CONN_NO_PSM, "L2CAP_CONN_NO_PSM"), - std::make_pair(L2CAP_CONN_SECURITY_BLOCK, "L2CAP_CONN_SECURITY_BLOCK"), - std::make_pair(L2CAP_CONN_NO_RESOURCES, "L2CAP_CONN_NO_RESOURCES"), - std::make_pair(L2CAP_CONN_TIMEOUT, "L2CAP_CONN_TIMEOUT"), - std::make_pair(L2CAP_CONN_OTHER_ERROR, "L2CAP_CONN_OTHER_ERROR"), - std::make_pair(L2CAP_CONN_ACL_CONNECTION_FAILED, - "L2CAP_CONN_ACL_CONNECTION_FAILED"), - std::make_pair(L2CAP_CONN_CLIENT_SECURITY_CLEARANCE_FAILED, - "L2CAP_CONN_CLIENT_SECURITY_CLEARANCE_FAILED"), - std::make_pair(L2CAP_CONN_NO_LINK, "L2CAP_CONN_NO_LINK"), - std::make_pair(L2CAP_CONN_CANCEL, "L2CAP_CONN_CANCEL"), - std::make_pair(L2CAP_CONN_INSUFFICIENT_AUTHENTICATION, - "L2CAP_CONN_INSUFFICIENT_AUTHENTICATION"), - std::make_pair(L2CAP_CONN_INSUFFICIENT_AUTHORIZATION, - "L2CAP_CONN_INSUFFICIENT_AUTHORIZATION"), - std::make_pair(L2CAP_CONN_INSUFFICIENT_ENCRYP_KEY_SIZE, - "L2CAP_CONN_INSUFFICIENT_ENCRYP_KEY_SIZE"), - std::make_pair(L2CAP_CONN_INSUFFICIENT_ENCRYP, - "L2CAP_CONN_INSUFFICIENT_ENCRYP"), - std::make_pair(L2CAP_CONN_INVALID_SOURCE_CID, - "L2CAP_CONN_INVALID_SOURCE_CID"), - std::make_pair(L2CAP_CONN_SOURCE_CID_ALREADY_ALLOCATED, - "L2CAP_CONN_SOURCE_CID_ALREADY_ALLOCATED"), - std::make_pair(L2CAP_CONN_UNACCEPTABLE_PARAMETERS, - "L2CAP_CONN_UNACCEPTABLE_PARAMETERS"), - std::make_pair(L2CAP_CONN_INVALID_PARAMETERS, - "L2CAP_CONN_INVALID_PARAMETERS"), + std::make_pair(L2CAP_CONN_OK, "L2CAP_CONN_OK"), + std::make_pair(L2CAP_CONN_PENDING, "L2CAP_CONN_PENDING"), + std::make_pair(L2CAP_CONN_NO_PSM, "L2CAP_CONN_NO_PSM"), + std::make_pair(L2CAP_CONN_SECURITY_BLOCK, "L2CAP_CONN_SECURITY_BLOCK"), + std::make_pair(L2CAP_CONN_NO_RESOURCES, "L2CAP_CONN_NO_RESOURCES"), + std::make_pair(L2CAP_CONN_TIMEOUT, "L2CAP_CONN_TIMEOUT"), + std::make_pair(L2CAP_CONN_OTHER_ERROR, "L2CAP_CONN_OTHER_ERROR"), + std::make_pair(L2CAP_CONN_ACL_CONNECTION_FAILED, "L2CAP_CONN_ACL_CONNECTION_FAILED"), + std::make_pair(L2CAP_CONN_CLIENT_SECURITY_CLEARANCE_FAILED, + "L2CAP_CONN_CLIENT_SECURITY_CLEARANCE_FAILED"), + std::make_pair(L2CAP_CONN_NO_LINK, "L2CAP_CONN_NO_LINK"), + std::make_pair(L2CAP_CONN_CANCEL, "L2CAP_CONN_CANCEL"), + std::make_pair(L2CAP_CONN_INSUFFICIENT_AUTHENTICATION, + "L2CAP_CONN_INSUFFICIENT_AUTHENTICATION"), + std::make_pair(L2CAP_CONN_INSUFFICIENT_AUTHORIZATION, + "L2CAP_CONN_INSUFFICIENT_AUTHORIZATION"), + std::make_pair(L2CAP_CONN_INSUFFICIENT_ENCRYP_KEY_SIZE, + "L2CAP_CONN_INSUFFICIENT_ENCRYP_KEY_SIZE"), + std::make_pair(L2CAP_CONN_INSUFFICIENT_ENCRYP, "L2CAP_CONN_INSUFFICIENT_ENCRYP"), + std::make_pair(L2CAP_CONN_INVALID_SOURCE_CID, "L2CAP_CONN_INVALID_SOURCE_CID"), + std::make_pair(L2CAP_CONN_SOURCE_CID_ALREADY_ALLOCATED, + "L2CAP_CONN_SOURCE_CID_ALREADY_ALLOCATED"), + std::make_pair(L2CAP_CONN_UNACCEPTABLE_PARAMETERS, "L2CAP_CONN_UNACCEPTABLE_PARAMETERS"), + std::make_pair(L2CAP_CONN_INVALID_PARAMETERS, "L2CAP_CONN_INVALID_PARAMETERS"), }; for (const auto& result : results) { - ASSERT_STREQ(result.second.c_str(), - l2cap_result_code_text(result.first).c_str()); + ASSERT_STREQ(result.second.c_str(), l2cap_result_code_text(result.first).c_str()); } std::ostringstream oss; oss << "UNKNOWN[" << std::numeric_limits::max() << "]"; - ASSERT_STREQ( - oss.str().c_str(), - l2cap_result_code_text( - static_cast(std::numeric_limits::max())) - .c_str()); + ASSERT_STREQ(oss.str().c_str(), + l2cap_result_code_text( + static_cast(std::numeric_limits::max())) + .c_str()); } TEST_F(StackL2capTest, L2CA_Dumpsys) { @@ -272,24 +262,24 @@ TEST_F(StackL2capTest, L2CA_Dumpsys) { TEST_F(StackL2capTest, bt_psm_text) { std::map map = { - {BT_PSM_SDP, "BT_PSM_SDP"}, - {BT_PSM_RFCOMM, "BT_PSM_RFCOMM"}, - {BT_PSM_TCS, "BT_PSM_TCS"}, - {BT_PSM_CTP, "BT_PSM_CTP"}, - {BT_PSM_BNEP, "BT_PSM_BNEP"}, - {BT_PSM_HIDC, "BT_PSM_HIDC"}, - {HID_PSM_CONTROL, "HID_PSM_CONTROL"}, - {BT_PSM_HIDI, "BT_PSM_HIDI"}, - {HID_PSM_INTERRUPT, "HID_PSM_INTERRUPT"}, - {BT_PSM_UPNP, "BT_PSM_UPNP"}, - {BT_PSM_AVCTP, "BT_PSM_AVCTP"}, - {BT_PSM_AVDTP, "BT_PSM_AVDTP"}, - {BT_PSM_AVCTP_13, "BT_PSM_AVCTP_13"}, - {BT_PSM_UDI_CP, "BT_PSM_UDI_CP"}, - {BT_PSM_ATT, "BT_PSM_ATT"}, - {BT_PSM_EATT, "BT_PSM_EATT"}, - {BRCM_RESERVED_PSM_START, "BRCM_RESERVED_PSM_START"}, - {BRCM_RESERVED_PSM_END, "BRCM_RESERVED_PSM_END"}, + {BT_PSM_SDP, "BT_PSM_SDP"}, + {BT_PSM_RFCOMM, "BT_PSM_RFCOMM"}, + {BT_PSM_TCS, "BT_PSM_TCS"}, + {BT_PSM_CTP, "BT_PSM_CTP"}, + {BT_PSM_BNEP, "BT_PSM_BNEP"}, + {BT_PSM_HIDC, "BT_PSM_HIDC"}, + {HID_PSM_CONTROL, "HID_PSM_CONTROL"}, + {BT_PSM_HIDI, "BT_PSM_HIDI"}, + {HID_PSM_INTERRUPT, "HID_PSM_INTERRUPT"}, + {BT_PSM_UPNP, "BT_PSM_UPNP"}, + {BT_PSM_AVCTP, "BT_PSM_AVCTP"}, + {BT_PSM_AVDTP, "BT_PSM_AVDTP"}, + {BT_PSM_AVCTP_13, "BT_PSM_AVCTP_13"}, + {BT_PSM_UDI_CP, "BT_PSM_UDI_CP"}, + {BT_PSM_ATT, "BT_PSM_ATT"}, + {BT_PSM_EATT, "BT_PSM_EATT"}, + {BRCM_RESERVED_PSM_START, "BRCM_RESERVED_PSM_START"}, + {BRCM_RESERVED_PSM_END, "BRCM_RESERVED_PSM_END"}, }; for (const auto& it : map) { diff --git a/system/stack/test/stack_smp_test.cc b/system/stack/test/stack_smp_test.cc index 8ab1594a5b6..cfe0368bcb7 100644 --- a/system/stack/test/stack_smp_test.cc +++ b/system/stack/test/stack_smp_test.cc @@ -40,8 +40,7 @@ using testing::StrEq; tBTM_CB btm_cb; const std::string kSmpOptions("mock smp options"); -const std::string kBroadcastAudioConfigOptions( - "mock broadcast audio config options"); +const std::string kBroadcastAudioConfigOptions("mock broadcast audio config options"); bool get_pts_avrcp_test(void) { return false; } bool get_pts_secure_only_mode(void) { return false; } bool get_pts_conn_updates_disabled(void) { return false; } @@ -69,40 +68,32 @@ config_t* get_all(void) { return nullptr; } const packet_fragmenter_t* packet_fragmenter_get_interface() { return nullptr; } stack_config_t mock_stack_config{ - .get_pts_avrcp_test = get_pts_avrcp_test, - .get_pts_secure_only_mode = get_pts_secure_only_mode, - .get_pts_conn_updates_disabled = get_pts_conn_updates_disabled, - .get_pts_crosskey_sdp_disable = get_pts_crosskey_sdp_disable, - .get_pts_smp_options = get_pts_smp_options, - .get_pts_smp_failure_case = get_pts_smp_failure_case, - .get_pts_force_eatt_for_notifications = - get_pts_force_eatt_for_notifications, - .get_pts_connect_eatt_unconditionally = - get_pts_connect_eatt_unconditionally, - .get_pts_connect_eatt_before_encryption = - get_pts_connect_eatt_before_encryption, - .get_pts_unencrypt_broadcast = get_pts_unencrypt_broadcast, - .get_pts_eatt_peripheral_collision_support = - get_pts_eatt_peripheral_collision_support, - .get_pts_use_eatt_for_all_services = get_pts_use_eatt_for_all_services, - .get_pts_force_le_audio_multiple_contexts_metadata = - get_pts_force_le_audio_multiple_contexts_metadata, - .get_pts_l2cap_ecoc_upper_tester = get_pts_l2cap_ecoc_upper_tester, - .get_pts_l2cap_ecoc_min_key_size = get_pts_l2cap_ecoc_min_key_size, - .get_pts_l2cap_ecoc_initial_chan_cnt = get_pts_l2cap_ecoc_initial_chan_cnt, - .get_pts_l2cap_ecoc_connect_remaining = - get_pts_l2cap_ecoc_connect_remaining, - .get_pts_l2cap_ecoc_send_num_of_sdu = get_pts_l2cap_ecoc_send_num_of_sdu, - .get_pts_l2cap_ecoc_reconfigure = get_pts_l2cap_ecoc_reconfigure, - .get_pts_broadcast_audio_config_options = - get_pts_broadcast_audio_config_options, - .get_pts_le_audio_disable_ases_before_stopping = - get_pts_le_audio_disable_ases_before_stopping, - .get_all = get_all, + .get_pts_avrcp_test = get_pts_avrcp_test, + .get_pts_secure_only_mode = get_pts_secure_only_mode, + .get_pts_conn_updates_disabled = get_pts_conn_updates_disabled, + .get_pts_crosskey_sdp_disable = get_pts_crosskey_sdp_disable, + .get_pts_smp_options = get_pts_smp_options, + .get_pts_smp_failure_case = get_pts_smp_failure_case, + .get_pts_force_eatt_for_notifications = get_pts_force_eatt_for_notifications, + .get_pts_connect_eatt_unconditionally = get_pts_connect_eatt_unconditionally, + .get_pts_connect_eatt_before_encryption = get_pts_connect_eatt_before_encryption, + .get_pts_unencrypt_broadcast = get_pts_unencrypt_broadcast, + .get_pts_eatt_peripheral_collision_support = get_pts_eatt_peripheral_collision_support, + .get_pts_use_eatt_for_all_services = get_pts_use_eatt_for_all_services, + .get_pts_force_le_audio_multiple_contexts_metadata = + get_pts_force_le_audio_multiple_contexts_metadata, + .get_pts_l2cap_ecoc_upper_tester = get_pts_l2cap_ecoc_upper_tester, + .get_pts_l2cap_ecoc_min_key_size = get_pts_l2cap_ecoc_min_key_size, + .get_pts_l2cap_ecoc_initial_chan_cnt = get_pts_l2cap_ecoc_initial_chan_cnt, + .get_pts_l2cap_ecoc_connect_remaining = get_pts_l2cap_ecoc_connect_remaining, + .get_pts_l2cap_ecoc_send_num_of_sdu = get_pts_l2cap_ecoc_send_num_of_sdu, + .get_pts_l2cap_ecoc_reconfigure = get_pts_l2cap_ecoc_reconfigure, + .get_pts_broadcast_audio_config_options = get_pts_broadcast_audio_config_options, + .get_pts_le_audio_disable_ases_before_stopping = + get_pts_le_audio_disable_ases_before_stopping, + .get_all = get_all, }; -const stack_config_t* stack_config_get_interface(void) { - return &mock_stack_config; -} +const stack_config_t* stack_config_get_interface(void) { return &mock_stack_config; } /* * This test verifies various key distribution methods in SMP works using the @@ -137,8 +128,7 @@ Octet16 smp_gen_p1_4_confirm(tSMP_CB* p_cb, tBLE_ADDR_TYPE remote_bd_addr_type); Octet16 smp_gen_p2_4_confirm(tSMP_CB* p_cb, const RawAddress& remote_bda); -tSMP_STATUS smp_calculate_comfirm(tSMP_CB* p_cb, const Octet16& rand, - Octet16* output); +tSMP_STATUS smp_calculate_confirm(tSMP_CB* p_cb, const Octet16& rand, Octet16* output); void dump_uint128(const Octet16& a, char* buffer) { for (unsigned int i = 0; i < OCTET16_LEN; ++i) { @@ -173,7 +163,7 @@ Octet16 parse_uint128(const char* input) { } class SmpCalculateConfirmTest : public testing::Test { - protected: +protected: tSMP_CB p_cb_; // Set random to 0x5783D52156AD6F0E6388274EC6702EE0 Octet16 rand_{0x57, 0x83, 0xD5, 0x21, 0x56, 0xAD, 0x6F, 0x0E, @@ -201,34 +191,32 @@ class SmpCalculateConfirmTest : public testing::Test { } void TearDown() override {} - public: +public: }; // Test smp_gen_p2_4_confirm function implementation TEST_F(SmpCalculateConfirmTest, test_smp_gen_p2_4_confirm_as_central) { // Set local_bda to 0xA1A2A3A4A5A6 test::mock::stack_acl::BTM_ReadConnectionAddr.body = - [](const RawAddress& remote_bda, RawAddress& local_conn_addr, - tBLE_ADDR_TYPE* p_addr_type, bool ota_address) { - local_conn_addr = RawAddress({0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6}); - *p_addr_type = BLE_ADDR_RANDOM; - }; + [](const RawAddress& remote_bda, RawAddress& local_conn_addr, tBLE_ADDR_TYPE* p_addr_type, + bool ota_address) { + local_conn_addr = RawAddress({0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6}); + *p_addr_type = BLE_ADDR_RANDOM; + }; // Set remote bda to 0xB1B2B3B4B5B6 test::mock::stack_acl::BTM_ReadRemoteConnectionAddr.body = - [](const RawAddress& pseudo_addr, RawAddress& conn_addr, - tBLE_ADDR_TYPE* p_addr_type, bool ota_address) { - conn_addr = RawAddress({0xB1, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6}); - *p_addr_type = BLE_ADDR_PUBLIC; - return true; - }; + [](const RawAddress& pseudo_addr, RawAddress& conn_addr, tBLE_ADDR_TYPE* p_addr_type, + bool ota_address) { + conn_addr = RawAddress({0xB1, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6}); + *p_addr_type = BLE_ADDR_PUBLIC; + return true; + }; RawAddress remote_bda; tBLE_ADDR_TYPE remote_bd_addr_type = BLE_ADDR_PUBLIC; - BTM_ReadRemoteConnectionAddr(p_cb_.pairing_bda, remote_bda, - &remote_bd_addr_type, true); - BTM_ReadConnectionAddr(p_cb_.pairing_bda, p_cb_.local_bda, &p_cb_.addr_type, - true); + BTM_ReadRemoteConnectionAddr(p_cb_.pairing_bda, remote_bda, &remote_bd_addr_type, true); + BTM_ReadConnectionAddr(p_cb_.pairing_bda, p_cb_.local_bda, &p_cb_.addr_type, true); Octet16 p2 = smp_gen_p2_4_confirm(&p_cb_, remote_bda); // Correct p2 is 0x00000000a1a2a3a4a5a6b1b2b3b4b5b6 const char expected_p2_str[] = "00000000a1a2a3a4a5a6b1b2b3b4b5b6"; @@ -244,27 +232,25 @@ TEST_F(SmpCalculateConfirmTest, test_smp_gen_p2_4_confirm_as_central) { TEST_F(SmpCalculateConfirmTest, test_aes_128_as_central) { // Set local_bda to 0xA1A2A3A4A5A6 test::mock::stack_acl::BTM_ReadConnectionAddr.body = - [](const RawAddress& remote_bda, RawAddress& local_conn_addr, - tBLE_ADDR_TYPE* p_addr_type, bool ota_address) { - local_conn_addr = RawAddress({0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6}); - *p_addr_type = BLE_ADDR_RANDOM; - }; + [](const RawAddress& remote_bda, RawAddress& local_conn_addr, tBLE_ADDR_TYPE* p_addr_type, + bool ota_address) { + local_conn_addr = RawAddress({0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6}); + *p_addr_type = BLE_ADDR_RANDOM; + }; // Set remote bda to 0xB1B2B3B4B5B6 test::mock::stack_acl::BTM_ReadRemoteConnectionAddr.body = - [](const RawAddress& pseudo_addr, RawAddress& conn_addr, - tBLE_ADDR_TYPE* p_addr_type, bool ota_address) { - conn_addr = RawAddress({0xB1, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6}); - *p_addr_type = BLE_ADDR_PUBLIC; - return true; - }; + [](const RawAddress& pseudo_addr, RawAddress& conn_addr, tBLE_ADDR_TYPE* p_addr_type, + bool ota_address) { + conn_addr = RawAddress({0xB1, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6}); + *p_addr_type = BLE_ADDR_PUBLIC; + return true; + }; RawAddress remote_bda; tBLE_ADDR_TYPE remote_bd_addr_type = BLE_ADDR_PUBLIC; - BTM_ReadRemoteConnectionAddr(p_cb_.pairing_bda, remote_bda, - &remote_bd_addr_type, true); - BTM_ReadConnectionAddr(p_cb_.pairing_bda, p_cb_.local_bda, &p_cb_.addr_type, - true); + BTM_ReadRemoteConnectionAddr(p_cb_.pairing_bda, remote_bda, &remote_bd_addr_type, true); + BTM_ReadConnectionAddr(p_cb_.pairing_bda, p_cb_.local_bda, &p_cb_.addr_type, true); Octet16 p1 = smp_gen_p1_4_confirm(&p_cb_, remote_bd_addr_type); // Correct p1 is 0x05000800000302070710000001010001 const char expected_p1_str[] = "05000800000302070710000001010001"; @@ -287,27 +273,27 @@ TEST_F(SmpCalculateConfirmTest, test_aes_128_as_central) { test::mock::stack_acl::BTM_ReadRemoteConnectionAddr = {}; } -// Test smp_calculate_comfirm function implementation -TEST_F(SmpCalculateConfirmTest, test_smp_calculate_comfirm_as_central) { +// Test smp_calculate_confirm function implementation +TEST_F(SmpCalculateConfirmTest, test_smp_calculate_confirm_as_central) { // Set local_bda to 0xA1A2A3A4A5A6 test::mock::stack_acl::BTM_ReadConnectionAddr.body = - [](const RawAddress& remote_bda, RawAddress& local_conn_addr, - tBLE_ADDR_TYPE* p_addr_type, bool ota_address) { - local_conn_addr = RawAddress({0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6}); - *p_addr_type = BLE_ADDR_RANDOM; - }; + [](const RawAddress& remote_bda, RawAddress& local_conn_addr, tBLE_ADDR_TYPE* p_addr_type, + bool ota_address) { + local_conn_addr = RawAddress({0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6}); + *p_addr_type = BLE_ADDR_RANDOM; + }; // Set remote bda to 0xB1B2B3B4B5B6 test::mock::stack_acl::BTM_ReadRemoteConnectionAddr.body = - [](const RawAddress& pseudo_addr, RawAddress& conn_addr, - tBLE_ADDR_TYPE* p_addr_type, bool ota_address) { - conn_addr = RawAddress({0xB1, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6}); - *p_addr_type = BLE_ADDR_PUBLIC; - return true; - }; + [](const RawAddress& pseudo_addr, RawAddress& conn_addr, tBLE_ADDR_TYPE* p_addr_type, + bool ota_address) { + conn_addr = RawAddress({0xB1, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6}); + *p_addr_type = BLE_ADDR_PUBLIC; + return true; + }; Octet16 output; - tSMP_STATUS status = smp_calculate_comfirm(&p_cb_, rand_, &output); + tSMP_STATUS status = smp_calculate_confirm(&p_cb_, rand_, &output); EXPECT_EQ(status, SMP_SUCCESS); // Correct MConfirm is 0x1e1e3fef878988ead2a74dc5bef13b86 const char expected_confirm_str[] = "1e1e3fef878988ead2a74dc5bef13b86"; @@ -404,40 +390,37 @@ TEST(SmpEccValidationTest, test_invalid_points) { TEST(SmpStatusText, smp_status_text) { std::vector> status = { - std::make_pair(SMP_SUCCESS, "SMP_SUCCESS"), - std::make_pair(SMP_PASSKEY_ENTRY_FAIL, "SMP_PASSKEY_ENTRY_FAIL"), - std::make_pair(SMP_OOB_FAIL, "SMP_OOB_FAIL"), - std::make_pair(SMP_PAIR_AUTH_FAIL, "SMP_PAIR_AUTH_FAIL"), - std::make_pair(SMP_CONFIRM_VALUE_ERR, "SMP_CONFIRM_VALUE_ERR"), - std::make_pair(SMP_PAIR_NOT_SUPPORT, "SMP_PAIR_NOT_SUPPORT"), - std::make_pair(SMP_ENC_KEY_SIZE, "SMP_ENC_KEY_SIZE"), - std::make_pair(SMP_INVALID_CMD, "SMP_INVALID_CMD"), - std::make_pair(SMP_PAIR_FAIL_UNKNOWN, "SMP_PAIR_FAIL_UNKNOWN"), - std::make_pair(SMP_REPEATED_ATTEMPTS, "SMP_REPEATED_ATTEMPTS"), - std::make_pair(SMP_INVALID_PARAMETERS, "SMP_INVALID_PARAMETERS"), - std::make_pair(SMP_DHKEY_CHK_FAIL, "SMP_DHKEY_CHK_FAIL"), - std::make_pair(SMP_NUMERIC_COMPAR_FAIL, "SMP_NUMERIC_COMPAR_FAIL"), - std::make_pair(SMP_BR_PARING_IN_PROGR, "SMP_BR_PARING_IN_PROGR"), - std::make_pair(SMP_XTRANS_DERIVE_NOT_ALLOW, - "SMP_XTRANS_DERIVE_NOT_ALLOW"), - std::make_pair(SMP_MAX_FAIL_RSN_PER_SPEC, - "SMP_XTRANS_DERIVE_NOT_ALLOW"), // NOTE: Dup - std::make_pair(SMP_PAIR_INTERNAL_ERR, "SMP_PAIR_INTERNAL_ERR"), - std::make_pair(SMP_UNKNOWN_IO_CAP, "SMP_UNKNOWN_IO_CAP"), - std::make_pair(SMP_BUSY, "SMP_BUSY"), - std::make_pair(SMP_ENC_FAIL, "SMP_ENC_FAIL"), - std::make_pair(SMP_STARTED, "SMP_STARTED"), - std::make_pair(SMP_RSP_TIMEOUT, "SMP_RSP_TIMEOUT"), - std::make_pair(SMP_FAIL, "SMP_FAIL"), - std::make_pair(SMP_CONN_TOUT, "SMP_CONN_TOUT"), + std::make_pair(SMP_SUCCESS, "SMP_SUCCESS"), + std::make_pair(SMP_PASSKEY_ENTRY_FAIL, "SMP_PASSKEY_ENTRY_FAIL"), + std::make_pair(SMP_OOB_FAIL, "SMP_OOB_FAIL"), + std::make_pair(SMP_PAIR_AUTH_FAIL, "SMP_PAIR_AUTH_FAIL"), + std::make_pair(SMP_CONFIRM_VALUE_ERR, "SMP_CONFIRM_VALUE_ERR"), + std::make_pair(SMP_PAIR_NOT_SUPPORT, "SMP_PAIR_NOT_SUPPORT"), + std::make_pair(SMP_ENC_KEY_SIZE, "SMP_ENC_KEY_SIZE"), + std::make_pair(SMP_INVALID_CMD, "SMP_INVALID_CMD"), + std::make_pair(SMP_PAIR_FAIL_UNKNOWN, "SMP_PAIR_FAIL_UNKNOWN"), + std::make_pair(SMP_REPEATED_ATTEMPTS, "SMP_REPEATED_ATTEMPTS"), + std::make_pair(SMP_INVALID_PARAMETERS, "SMP_INVALID_PARAMETERS"), + std::make_pair(SMP_DHKEY_CHK_FAIL, "SMP_DHKEY_CHK_FAIL"), + std::make_pair(SMP_NUMERIC_COMPAR_FAIL, "SMP_NUMERIC_COMPAR_FAIL"), + std::make_pair(SMP_BR_PARING_IN_PROGR, "SMP_BR_PARING_IN_PROGR"), + std::make_pair(SMP_XTRANS_DERIVE_NOT_ALLOW, "SMP_XTRANS_DERIVE_NOT_ALLOW"), + std::make_pair(SMP_MAX_FAIL_RSN_PER_SPEC, + "SMP_XTRANS_DERIVE_NOT_ALLOW"), // NOTE: Dup + std::make_pair(SMP_PAIR_INTERNAL_ERR, "SMP_PAIR_INTERNAL_ERR"), + std::make_pair(SMP_UNKNOWN_IO_CAP, "SMP_UNKNOWN_IO_CAP"), + std::make_pair(SMP_BUSY, "SMP_BUSY"), + std::make_pair(SMP_ENC_FAIL, "SMP_ENC_FAIL"), + std::make_pair(SMP_STARTED, "SMP_STARTED"), + std::make_pair(SMP_RSP_TIMEOUT, "SMP_RSP_TIMEOUT"), + std::make_pair(SMP_FAIL, "SMP_FAIL"), + std::make_pair(SMP_CONN_TOUT, "SMP_CONN_TOUT"), }; for (const auto& stat : status) { ASSERT_STREQ(stat.second.c_str(), smp_status_text(stat.first).c_str()); } - auto unknown = - base::StringPrintf("UNKNOWN[%hhu]", std::numeric_limits::max()); - ASSERT_STREQ(unknown.c_str(), - smp_status_text(static_cast( - std::numeric_limits::max())) - .c_str()); + auto unknown = base::StringPrintf("UNKNOWN[%hhu]", std::numeric_limits::max()); + ASSERT_STREQ( + unknown.c_str(), + smp_status_text(static_cast(std::numeric_limits::max())).c_str()); } diff --git a/system/test/common/core_interface.cc b/system/test/common/core_interface.cc index 244289c5a1c..717c40f8a79 100644 --- a/system/test/common/core_interface.cc +++ b/system/test/common/core_interface.cc @@ -23,23 +23,23 @@ namespace { static bluetooth::core::EventCallbacks eventCallbacks = { - .invoke_adapter_state_changed_cb = invoke_adapter_state_changed_cb, - .invoke_adapter_properties_cb = invoke_adapter_properties_cb, - .invoke_remote_device_properties_cb = invoke_remote_device_properties_cb, - .invoke_device_found_cb = invoke_device_found_cb, - .invoke_discovery_state_changed_cb = invoke_discovery_state_changed_cb, - .invoke_pin_request_cb = invoke_pin_request_cb, - .invoke_ssp_request_cb = invoke_ssp_request_cb, - .invoke_oob_data_request_cb = invoke_oob_data_request_cb, - .invoke_bond_state_changed_cb = invoke_bond_state_changed_cb, - .invoke_address_consolidate_cb = invoke_address_consolidate_cb, - .invoke_le_address_associate_cb = invoke_le_address_associate_cb, - .invoke_acl_state_changed_cb = invoke_acl_state_changed_cb, - .invoke_thread_evt_cb = invoke_thread_evt_cb, - .invoke_le_test_mode_cb = invoke_le_test_mode_cb, - .invoke_energy_info_cb = invoke_energy_info_cb, - .invoke_link_quality_report_cb = invoke_link_quality_report_cb, - .invoke_key_missing_cb = invoke_key_missing_cb}; + .invoke_adapter_state_changed_cb = invoke_adapter_state_changed_cb, + .invoke_adapter_properties_cb = invoke_adapter_properties_cb, + .invoke_remote_device_properties_cb = invoke_remote_device_properties_cb, + .invoke_device_found_cb = invoke_device_found_cb, + .invoke_discovery_state_changed_cb = invoke_discovery_state_changed_cb, + .invoke_pin_request_cb = invoke_pin_request_cb, + .invoke_ssp_request_cb = invoke_ssp_request_cb, + .invoke_oob_data_request_cb = invoke_oob_data_request_cb, + .invoke_bond_state_changed_cb = invoke_bond_state_changed_cb, + .invoke_address_consolidate_cb = invoke_address_consolidate_cb, + .invoke_le_address_associate_cb = invoke_le_address_associate_cb, + .invoke_acl_state_changed_cb = invoke_acl_state_changed_cb, + .invoke_thread_evt_cb = invoke_thread_evt_cb, + .invoke_le_test_mode_cb = invoke_le_test_mode_cb, + .invoke_energy_info_cb = invoke_energy_info_cb, + .invoke_link_quality_report_cb = invoke_link_quality_report_cb, + .invoke_key_missing_cb = invoke_key_missing_cb}; // This interface lets us query for configuration properties of the stack that // could change at runtime @@ -53,51 +53,47 @@ static auto mockConfigInterface = MockConfigInterface{}; // This interface lets us communicate with encoders used in profiles struct MockMsbcCodecInterface : public bluetooth::core::CodecInterface { - virtual void initialize(){}; + virtual void initialize() {} virtual void cleanup() {} - virtual uint32_t encodePacket(int16_t* /* input */, uint8_t* /* output */) { - return 0; - }; + virtual uint32_t encodePacket(int16_t* /* input */, uint8_t* /* output */) { return 0; } virtual bool decodePacket(const uint8_t* /* i_buf */, int16_t* /* o_buf */, size_t /* out_len */) { return false; - }; + } }; struct MockLc3CodecInterface : public bluetooth::core::CodecInterface { - virtual void initialize(){}; + virtual void initialize() {} virtual void cleanup() {} - virtual uint32_t encodePacket(int16_t* /* input */, uint8_t* /* output */) { - return 0; - }; + virtual uint32_t encodePacket(int16_t* /* input */, uint8_t* /* output */) { return 0; } virtual bool decodePacket(const uint8_t* /* i_buf */, int16_t* /* o_buf */, size_t /* out_len */) { return false; - }; + } }; static auto mockMsbcCodecInterface = MockMsbcCodecInterface{}; static auto mockLc3CodecInterface = MockLc3CodecInterface{}; struct bluetooth::core::HACK_ProfileInterface HACK_profileInterface = { - // HID - .btif_hh_connect = nullptr, - .btif_hh_virtual_unplug = nullptr, - .bta_hh_read_ssr_param = nullptr, + // HID + .btif_hh_connect = nullptr, + .btif_hh_virtual_unplug = nullptr, + .bta_hh_read_ssr_param = nullptr, - // AVDTP - .btif_av_set_dynamic_audio_buffer_size = nullptr, + // AVDTP + .btif_av_set_dynamic_audio_buffer_size = nullptr, - // ASHA - .GetHearingAidDeviceCount = nullptr, + // ASHA + .GetHearingAidDeviceCount = nullptr, - // LE Audio - .IsLeAudioClientRunning = nullptr, + // LE Audio + .IsLeAudioClientRunning = nullptr, - // AVRCP - .AVRC_GetProfileVersion = nullptr, + // AVRCP + .AVRC_GetProfileVersion = nullptr, }; } // namespace @@ -112,19 +108,16 @@ void CleanCoreInterface() { } MockCoreInterface::MockCoreInterface() - : bluetooth::core::CoreInterface{ - &eventCallbacks, &mockConfigInterface, &mockMsbcCodecInterface, - &mockLc3CodecInterface, &HACK_profileInterface} {}; + : bluetooth::core::CoreInterface{&eventCallbacks, &mockConfigInterface, &mockMsbcCodecInterface, + &mockLc3CodecInterface, &HACK_profileInterface} {} -void MockCoreInterface::onBluetoothEnabled(){}; +void MockCoreInterface::onBluetoothEnabled() {} -bt_status_t MockCoreInterface::toggleProfile(tBTA_SERVICE_ID /* service_id */, - bool /* enable */) { +bt_status_t MockCoreInterface::toggleProfile(tBTA_SERVICE_ID /* service_id */, bool /* enable */) { return BT_STATUS_SUCCESS; -}; +} -void MockCoreInterface::removeDeviceFromProfiles( - const RawAddress& /* bd_addr */){}; +void MockCoreInterface::removeDeviceFromProfiles(const RawAddress& /* bd_addr */) {} -void MockCoreInterface::onLinkDown(const RawAddress& /* bd_addr */, - tBT_TRANSPORT /* transport */){}; +void MockCoreInterface::onLinkDown(const RawAddress& /* bd_addr */, tBT_TRANSPORT /* transport */) { +} diff --git a/system/test/common/hal_version_manager_test.cc b/system/test/common/hal_version_manager_test.cc index 936ca8e3f78..37914bf8255 100644 --- a/system/test/common/hal_version_manager_test.cc +++ b/system/test/common/hal_version_manager_test.cc @@ -25,10 +25,8 @@ using bluetooth::audio::HalVersionManager; class BluetoothAudioHalVersionTest : public ::testing::Test {}; TEST_F(BluetoothAudioHalVersionTest, versionOperatorEqual) { - EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_2_0 == - BluetoothAudioHalVersion::VERSION_2_0); - EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_2_1 == - BluetoothAudioHalVersion::VERSION_2_1); + EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_2_0 == BluetoothAudioHalVersion::VERSION_2_0); + EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_2_1 == BluetoothAudioHalVersion::VERSION_2_1); EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_AIDL_V1 == BluetoothAudioHalVersion::VERSION_AIDL_V1); EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_AIDL_V2 == @@ -40,15 +38,11 @@ TEST_F(BluetoothAudioHalVersionTest, versionOperatorEqual) { } TEST_F(BluetoothAudioHalVersionTest, versionOperatorLessOrEqual) { - EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_2_0 < - BluetoothAudioHalVersion::VERSION_2_1); - EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_2_0 <= - BluetoothAudioHalVersion::VERSION_2_1); + EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_2_0 < BluetoothAudioHalVersion::VERSION_2_1); + EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_2_0 <= BluetoothAudioHalVersion::VERSION_2_1); - EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_2_1 < - BluetoothAudioHalVersion::VERSION_AIDL_V1); - EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_2_1 <= - BluetoothAudioHalVersion::VERSION_AIDL_V1); + EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_2_1 < BluetoothAudioHalVersion::VERSION_AIDL_V1); + EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_2_1 <= BluetoothAudioHalVersion::VERSION_AIDL_V1); EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_AIDL_V1 < BluetoothAudioHalVersion::VERSION_AIDL_V2); @@ -65,15 +59,11 @@ TEST_F(BluetoothAudioHalVersionTest, versionOperatorLessOrEqual) { EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_AIDL_V3 <= BluetoothAudioHalVersion::VERSION_AIDL_V4); - EXPECT_FALSE(BluetoothAudioHalVersion::VERSION_2_1 < - BluetoothAudioHalVersion::VERSION_2_0); - EXPECT_FALSE(BluetoothAudioHalVersion::VERSION_2_1 <= - BluetoothAudioHalVersion::VERSION_2_0); + EXPECT_FALSE(BluetoothAudioHalVersion::VERSION_2_1 < BluetoothAudioHalVersion::VERSION_2_0); + EXPECT_FALSE(BluetoothAudioHalVersion::VERSION_2_1 <= BluetoothAudioHalVersion::VERSION_2_0); - EXPECT_FALSE(BluetoothAudioHalVersion::VERSION_AIDL_V1 < - BluetoothAudioHalVersion::VERSION_2_1); - EXPECT_FALSE(BluetoothAudioHalVersion::VERSION_AIDL_V1 <= - BluetoothAudioHalVersion::VERSION_2_1); + EXPECT_FALSE(BluetoothAudioHalVersion::VERSION_AIDL_V1 < BluetoothAudioHalVersion::VERSION_2_1); + EXPECT_FALSE(BluetoothAudioHalVersion::VERSION_AIDL_V1 <= BluetoothAudioHalVersion::VERSION_2_1); EXPECT_FALSE(BluetoothAudioHalVersion::VERSION_AIDL_V2 < BluetoothAudioHalVersion::VERSION_AIDL_V1); @@ -92,15 +82,11 @@ TEST_F(BluetoothAudioHalVersionTest, versionOperatorLessOrEqual) { } TEST_F(BluetoothAudioHalVersionTest, versionOperatorGreaterOrEqual) { - EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_2_1 > - BluetoothAudioHalVersion::VERSION_2_0); - EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_2_1 >= - BluetoothAudioHalVersion::VERSION_2_0); + EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_2_1 > BluetoothAudioHalVersion::VERSION_2_0); + EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_2_1 >= BluetoothAudioHalVersion::VERSION_2_0); - EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_AIDL_V1 > - BluetoothAudioHalVersion::VERSION_2_1); - EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_AIDL_V1 >= - BluetoothAudioHalVersion::VERSION_2_1); + EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_AIDL_V1 > BluetoothAudioHalVersion::VERSION_2_1); + EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_AIDL_V1 >= BluetoothAudioHalVersion::VERSION_2_1); EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_AIDL_V2 > BluetoothAudioHalVersion::VERSION_AIDL_V1); @@ -117,15 +103,11 @@ TEST_F(BluetoothAudioHalVersionTest, versionOperatorGreaterOrEqual) { EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_AIDL_V4 >= BluetoothAudioHalVersion::VERSION_AIDL_V3); - EXPECT_FALSE(BluetoothAudioHalVersion::VERSION_2_0 > - BluetoothAudioHalVersion::VERSION_2_1); - EXPECT_FALSE(BluetoothAudioHalVersion::VERSION_2_0 >= - BluetoothAudioHalVersion::VERSION_2_1); + EXPECT_FALSE(BluetoothAudioHalVersion::VERSION_2_0 > BluetoothAudioHalVersion::VERSION_2_1); + EXPECT_FALSE(BluetoothAudioHalVersion::VERSION_2_0 >= BluetoothAudioHalVersion::VERSION_2_1); - EXPECT_FALSE(BluetoothAudioHalVersion::VERSION_2_1 > - BluetoothAudioHalVersion::VERSION_AIDL_V1); - EXPECT_FALSE(BluetoothAudioHalVersion::VERSION_2_1 >= - BluetoothAudioHalVersion::VERSION_AIDL_V1); + EXPECT_FALSE(BluetoothAudioHalVersion::VERSION_2_1 > BluetoothAudioHalVersion::VERSION_AIDL_V1); + EXPECT_FALSE(BluetoothAudioHalVersion::VERSION_2_1 >= BluetoothAudioHalVersion::VERSION_AIDL_V1); EXPECT_FALSE(BluetoothAudioHalVersion::VERSION_AIDL_V1 > BluetoothAudioHalVersion::VERSION_AIDL_V2); @@ -147,34 +129,32 @@ TEST_F(BluetoothAudioHalVersionTest, HIDL_VERSION_2_0) { EXPECT_EQ(BluetoothAudioHalVersion::VERSION_2_0, BluetoothAudioHalVersion(BluetoothAudioHalTransport::HIDL, 2, 0)); - EXPECT_EQ(BluetoothAudioHalVersion::VERSION_2_0.getTransport(), - BluetoothAudioHalTransport::HIDL); + EXPECT_EQ(BluetoothAudioHalVersion::VERSION_2_0.getTransport(), BluetoothAudioHalTransport::HIDL); EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_2_0.isHIDL()); EXPECT_FALSE(BluetoothAudioHalVersion::VERSION_2_0.isAIDL()); - EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_2_0.toString().find( - "transport: HIDL") != std::string::npos); - EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_2_0.toString().find( - "major: 2") != std::string::npos); - EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_2_0.toString().find( - "minor: 0") != std::string::npos); + EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_2_0.toString().find("transport: HIDL") != + std::string::npos); + EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_2_0.toString().find("major: 2") != + std::string::npos); + EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_2_0.toString().find("minor: 0") != + std::string::npos); } TEST_F(BluetoothAudioHalVersionTest, HIDL_VERSION_2_1) { EXPECT_EQ(BluetoothAudioHalVersion::VERSION_2_1, BluetoothAudioHalVersion(BluetoothAudioHalTransport::HIDL, 2, 1)); - EXPECT_EQ(BluetoothAudioHalVersion::VERSION_2_1.getTransport(), - BluetoothAudioHalTransport::HIDL); + EXPECT_EQ(BluetoothAudioHalVersion::VERSION_2_1.getTransport(), BluetoothAudioHalTransport::HIDL); EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_2_1.isHIDL()); EXPECT_FALSE(BluetoothAudioHalVersion::VERSION_2_1.isAIDL()); - EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_2_1.toString().find( - "transport: HIDL") != std::string::npos); - EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_2_1.toString().find( - "major: 2") != std::string::npos); - EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_2_1.toString().find( - "minor: 1") != std::string::npos); + EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_2_1.toString().find("transport: HIDL") != + std::string::npos); + EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_2_1.toString().find("major: 2") != + std::string::npos); + EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_2_1.toString().find("minor: 1") != + std::string::npos); } TEST_F(BluetoothAudioHalVersionTest, AIDL_VERSIONS_V1) { @@ -186,12 +166,12 @@ TEST_F(BluetoothAudioHalVersionTest, AIDL_VERSIONS_V1) { EXPECT_FALSE(BluetoothAudioHalVersion::VERSION_AIDL_V1.isHIDL()); EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_AIDL_V1.isAIDL()); - EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_AIDL_V1.toString().find( - "transport: AIDL") != std::string::npos); - EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_AIDL_V1.toString().find( - "major: 1") != std::string::npos); - EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_AIDL_V1.toString().find( - "minor: 0") != std::string::npos); + EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_AIDL_V1.toString().find("transport: AIDL") != + std::string::npos); + EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_AIDL_V1.toString().find("major: 1") != + std::string::npos); + EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_AIDL_V1.toString().find("minor: 0") != + std::string::npos); } TEST_F(BluetoothAudioHalVersionTest, AIDL_VERSIONS_V2) { @@ -203,12 +183,12 @@ TEST_F(BluetoothAudioHalVersionTest, AIDL_VERSIONS_V2) { EXPECT_FALSE(BluetoothAudioHalVersion::VERSION_AIDL_V2.isHIDL()); EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_AIDL_V2.isAIDL()); - EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_AIDL_V2.toString().find( - "transport: AIDL") != std::string::npos); - EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_AIDL_V2.toString().find( - "major: 2") != std::string::npos); - EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_AIDL_V2.toString().find( - "minor: 0") != std::string::npos); + EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_AIDL_V2.toString().find("transport: AIDL") != + std::string::npos); + EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_AIDL_V2.toString().find("major: 2") != + std::string::npos); + EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_AIDL_V2.toString().find("minor: 0") != + std::string::npos); } TEST_F(BluetoothAudioHalVersionTest, AIDL_VERSIONS_V3) { @@ -220,12 +200,12 @@ TEST_F(BluetoothAudioHalVersionTest, AIDL_VERSIONS_V3) { EXPECT_FALSE(BluetoothAudioHalVersion::VERSION_AIDL_V3.isHIDL()); EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_AIDL_V3.isAIDL()); - EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_AIDL_V3.toString().find( - "transport: AIDL") != std::string::npos); - EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_AIDL_V3.toString().find( - "major: 3") != std::string::npos); - EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_AIDL_V3.toString().find( - "minor: 0") != std::string::npos); + EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_AIDL_V3.toString().find("transport: AIDL") != + std::string::npos); + EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_AIDL_V3.toString().find("major: 3") != + std::string::npos); + EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_AIDL_V3.toString().find("minor: 0") != + std::string::npos); } TEST_F(BluetoothAudioHalVersionTest, AIDL_VERSIONS_V4) { @@ -237,12 +217,12 @@ TEST_F(BluetoothAudioHalVersionTest, AIDL_VERSIONS_V4) { EXPECT_FALSE(BluetoothAudioHalVersion::VERSION_AIDL_V4.isHIDL()); EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_AIDL_V4.isAIDL()); - EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_AIDL_V4.toString().find( - "transport: AIDL") != std::string::npos); - EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_AIDL_V4.toString().find( - "major: 4") != std::string::npos); - EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_AIDL_V4.toString().find( - "minor: 0") != std::string::npos); + EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_AIDL_V4.toString().find("transport: AIDL") != + std::string::npos); + EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_AIDL_V4.toString().find("major: 4") != + std::string::npos); + EXPECT_TRUE(BluetoothAudioHalVersion::VERSION_AIDL_V4.toString().find("minor: 0") != + std::string::npos); } /** @@ -252,8 +232,6 @@ TEST_F(BluetoothAudioHalVersionTest, AIDL_VERSIONS_V4) { TEST_F(BluetoothAudioHalVersionTest, AIDL_VERSIONS_Vx) { EXPECT_TRUE(BluetoothAudioHalVersion(BluetoothAudioHalTransport::AIDL, 5, 0) > BluetoothAudioHalVersion::VERSION_AIDL_V4); - EXPECT_FALSE(BluetoothAudioHalVersion(BluetoothAudioHalTransport::AIDL, 5, 0) - .isHIDL()); - EXPECT_TRUE(BluetoothAudioHalVersion(BluetoothAudioHalTransport::AIDL, 5, 0) - .isAIDL()); + EXPECT_FALSE(BluetoothAudioHalVersion(BluetoothAudioHalTransport::AIDL, 5, 0).isHIDL()); + EXPECT_TRUE(BluetoothAudioHalVersion(BluetoothAudioHalTransport::AIDL, 5, 0).isAIDL()); } diff --git a/system/test/common/init_flags.cc b/system/test/common/init_flags.cc index bb2d7ad2e15..bf164d5e8ae 100644 --- a/system/test/common/init_flags.cc +++ b/system/test/common/init_flags.cc @@ -10,15 +10,10 @@ namespace common { bool InitFlags::logging_debug_enabled_for_all = false; bool InitFlags::leaudio_targeted_announcement_reconnection_mode = true; -std::unordered_map - InitFlags::logging_debug_explicit_tag_settings = {}; +std::unordered_map InitFlags::logging_debug_explicit_tag_settings = {}; void InitFlags::Load(const char** flags) {} -void InitFlags::SetAll(bool value) { - InitFlags::logging_debug_enabled_for_all = value; -} -void InitFlags::SetAllForTesting() { - InitFlags::logging_debug_enabled_for_all = true; -} +void InitFlags::SetAll(bool value) { InitFlags::logging_debug_enabled_for_all = value; } +void InitFlags::SetAllForTesting() { InitFlags::logging_debug_enabled_for_all = true; } } // namespace common } // namespace bluetooth diff --git a/system/test/common/jni_thread.cc b/system/test/common/jni_thread.cc index 9ced8fab551..ae3e00d7ab0 100644 --- a/system/test/common/jni_thread.cc +++ b/system/test/common/jni_thread.cc @@ -34,9 +34,13 @@ void run_one_jni_thread_task() { } void run_all_jni_thread_task() { - while (do_in_jni_thread_task_queue.size()) run_one_jni_thread_task(); + while (do_in_jni_thread_task_queue.size()) { + run_one_jni_thread_task(); + } } void reset_mock_jni_thread_queue() { - while (do_in_jni_thread_task_queue.size()) do_in_jni_thread_task_queue.pop(); + while (do_in_jni_thread_task_queue.size()) { + do_in_jni_thread_task_queue.pop(); + } } diff --git a/system/test/common/main_handler.cc b/system/test/common/main_handler.cc index a4ff060f753..3a9b6a1481d 100644 --- a/system/test/common/main_handler.cc +++ b/system/test/common/main_handler.cc @@ -39,29 +39,24 @@ void do_post_on_bt_main(BtMainClosure closure) { closure(); } } // namespace -bt_status_t do_in_main_thread(const base::Location& from_here, - base::OnceClosure task) { - bluetooth::log::assert_that( - main_thread.DoInThread(from_here, std::move(task)), - "Unable to run on main thread"); +bt_status_t do_in_main_thread(const base::Location& from_here, base::OnceClosure task) { + bluetooth::log::assert_that(main_thread.DoInThread(from_here, std::move(task)), + "Unable to run on main thread"); return BT_STATUS_SUCCESS; } -bt_status_t do_in_main_thread_delayed(const base::Location& from_here, - base::OnceClosure task, +bt_status_t do_in_main_thread_delayed(const base::Location& from_here, base::OnceClosure task, std::chrono::microseconds delay) { - bluetooth::log::assert_that( - !main_thread.DoInThreadDelayed(from_here, std::move(task), delay), - "Unable to run on main thread delayed"); + bluetooth::log::assert_that(!main_thread.DoInThreadDelayed(from_here, std::move(task), delay), + "Unable to run on main thread delayed"); return BT_STATUS_SUCCESS; } void post_on_bt_main(BtMainClosure closure) { bluetooth::log::assert_that( - do_in_main_thread( - FROM_HERE, base::BindOnce(do_post_on_bt_main, std::move(closure))) == - BT_STATUS_SUCCESS, - "Unable to post on main thread"); + do_in_main_thread(FROM_HERE, base::BindOnce(do_post_on_bt_main, std::move(closure))) == + BT_STATUS_SUCCESS, + "Unable to post on main thread"); } void main_thread_start_up() { @@ -75,6 +70,4 @@ void main_thread_shut_down() { main_thread.ShutDown(); } // osi_alarm bluetooth::common::MessageLoopThread* get_main_thread() { return &main_thread; } -bluetooth::common::PostableContext* get_main() { - return main_thread.Postable(); -} +bluetooth::common::PostableContext* get_main() { return main_thread.Postable(); } diff --git a/system/test/common/main_handler.h b/system/test/common/main_handler.h index 12054203d75..1be8c1a2c3e 100644 --- a/system/test/common/main_handler.h +++ b/system/test/common/main_handler.h @@ -28,10 +28,8 @@ using bluetooth::common::MessageLoopThread; using BtMainClosure = std::function; -bt_status_t do_in_main_thread(const base::Location& from_here, - base::OnceClosure task); -bt_status_t do_in_main_thread_delayed(const base::Location& from_here, - base::OnceClosure task, +bt_status_t do_in_main_thread(const base::Location& from_here, base::OnceClosure task); +bt_status_t do_in_main_thread_delayed(const base::Location& from_here, base::OnceClosure task, std::chrono::microseconds delay); void post_on_bt_main(BtMainClosure closure); void main_thread_start_up(); diff --git a/system/test/common/mock_functions.cc b/system/test/common/mock_functions.cc index d69f5a8b16b..9f647f7d6b8 100644 --- a/system/test/common/mock_functions.cc +++ b/system/test/common/mock_functions.cc @@ -49,8 +49,7 @@ int get_func_call_size() { void dump_mock_function_count_map() { std::lock_guard lock(mutex_); - bluetooth::log::info("Mock function count map size:{}", - _get_func_call_count_map().size()); + bluetooth::log::info("Mock function count map size:{}", _get_func_call_count_map().size()); for (const auto& it : _get_func_call_count_map()) { bluetooth::log::info("function:{}: call_count:{}", it.first, it.second); diff --git a/system/test/common/stack_config.cc b/system/test/common/stack_config.cc index b6cc2001036..41366496e97 100644 --- a/system/test/common/stack_config.cc +++ b/system/test/common/stack_config.cc @@ -23,8 +23,7 @@ #include const std::string kSmpOptions("mock smp options"); -const std::string kBroadcastAudioConfigOptions( - "mock broadcast audio config options"); +const std::string kBroadcastAudioConfigOptions("mock broadcast audio config options"); bool get_pts_avrcp_test(void) { return false; } bool get_pts_secure_only_mode(void) { return false; } bool get_pts_conn_updates_disabled(void) { return false; } @@ -54,38 +53,30 @@ struct packet_fragmenter_t; const packet_fragmenter_t* packet_fragmenter_get_interface() { return nullptr; } stack_config_t mock_stack_config{ - .get_pts_avrcp_test = get_pts_avrcp_test, - .get_pts_secure_only_mode = get_pts_secure_only_mode, - .get_pts_conn_updates_disabled = get_pts_conn_updates_disabled, - .get_pts_crosskey_sdp_disable = get_pts_crosskey_sdp_disable, - .get_pts_smp_options = get_pts_smp_options, - .get_pts_smp_failure_case = get_pts_smp_failure_case, - .get_pts_force_eatt_for_notifications = - get_pts_force_eatt_for_notifications, - .get_pts_connect_eatt_unconditionally = - get_pts_connect_eatt_unconditionally, - .get_pts_connect_eatt_before_encryption = - get_pts_connect_eatt_before_encryption, - .get_pts_unencrypt_broadcast = get_pts_unencrypt_broadcast, - .get_pts_eatt_peripheral_collision_support = - get_pts_eatt_peripheral_collision_support, - .get_pts_use_eatt_for_all_services = get_pts_use_eatt_for_all_services, - .get_pts_force_le_audio_multiple_contexts_metadata = - get_pts_force_le_audio_multiple_contexts_metadata, - .get_pts_l2cap_ecoc_upper_tester = get_pts_l2cap_ecoc_upper_tester, - .get_pts_l2cap_ecoc_min_key_size = get_pts_l2cap_ecoc_min_key_size, - .get_pts_l2cap_ecoc_initial_chan_cnt = get_pts_l2cap_ecoc_initial_chan_cnt, - .get_pts_l2cap_ecoc_connect_remaining = - get_pts_l2cap_ecoc_connect_remaining, - .get_pts_l2cap_ecoc_send_num_of_sdu = get_pts_l2cap_ecoc_send_num_of_sdu, - .get_pts_l2cap_ecoc_reconfigure = get_pts_l2cap_ecoc_reconfigure, - .get_pts_broadcast_audio_config_options = - get_pts_broadcast_audio_config_options, - .get_pts_le_audio_disable_ases_before_stopping = - get_pts_le_audio_disable_ases_before_stopping, - .get_all = get_all, + .get_pts_avrcp_test = get_pts_avrcp_test, + .get_pts_secure_only_mode = get_pts_secure_only_mode, + .get_pts_conn_updates_disabled = get_pts_conn_updates_disabled, + .get_pts_crosskey_sdp_disable = get_pts_crosskey_sdp_disable, + .get_pts_smp_options = get_pts_smp_options, + .get_pts_smp_failure_case = get_pts_smp_failure_case, + .get_pts_force_eatt_for_notifications = get_pts_force_eatt_for_notifications, + .get_pts_connect_eatt_unconditionally = get_pts_connect_eatt_unconditionally, + .get_pts_connect_eatt_before_encryption = get_pts_connect_eatt_before_encryption, + .get_pts_unencrypt_broadcast = get_pts_unencrypt_broadcast, + .get_pts_eatt_peripheral_collision_support = get_pts_eatt_peripheral_collision_support, + .get_pts_use_eatt_for_all_services = get_pts_use_eatt_for_all_services, + .get_pts_force_le_audio_multiple_contexts_metadata = + get_pts_force_le_audio_multiple_contexts_metadata, + .get_pts_l2cap_ecoc_upper_tester = get_pts_l2cap_ecoc_upper_tester, + .get_pts_l2cap_ecoc_min_key_size = get_pts_l2cap_ecoc_min_key_size, + .get_pts_l2cap_ecoc_initial_chan_cnt = get_pts_l2cap_ecoc_initial_chan_cnt, + .get_pts_l2cap_ecoc_connect_remaining = get_pts_l2cap_ecoc_connect_remaining, + .get_pts_l2cap_ecoc_send_num_of_sdu = get_pts_l2cap_ecoc_send_num_of_sdu, + .get_pts_l2cap_ecoc_reconfigure = get_pts_l2cap_ecoc_reconfigure, + .get_pts_broadcast_audio_config_options = get_pts_broadcast_audio_config_options, + .get_pts_le_audio_disable_ases_before_stopping = + get_pts_le_audio_disable_ases_before_stopping, + .get_all = get_all, }; -const stack_config_t* stack_config_get_interface(void) { - return &mock_stack_config; -} +const stack_config_t* stack_config_get_interface(void) { return &mock_stack_config; } diff --git a/system/test/common/sync_main_handler.cc b/system/test/common/sync_main_handler.cc index a58bdcde398..7c59f61a1fd 100644 --- a/system/test/common/sync_main_handler.cc +++ b/system/test/common/sync_main_handler.cc @@ -26,4 +26,4 @@ void sync_main_handler() { std::future future = promise.get_future(); post_on_bt_main([&promise]() { promise.set_value(); }); future.wait_for(std::chrono::milliseconds(sync_timeout_in_ms)); -}; +} diff --git a/system/test/fake/fake_looper.cc b/system/test/fake/fake_looper.cc index a1759b9d497..81bcdfb4eed 100644 --- a/system/test/fake/fake_looper.cc +++ b/system/test/fake/fake_looper.cc @@ -45,8 +45,7 @@ pid_t get_thread_id() { // message loop void* run_message_loop(void* arg) { - bluetooth::log::assert_that(arg != nullptr, - "Must pass in a thread start argument"); + bluetooth::log::assert_that(arg != nullptr, "Must pass in a thread start argument"); thread_t* thread = nullptr; { // Decouple thread portion from |start_arg| wrapper @@ -58,8 +57,8 @@ void* run_message_loop(void* arg) { // thread->tid_ = syscall(__NR_gettid); thread->tid_ = get_thread_id(); - bluetooth::log::debug("Thread message loop is operational name:{} tid:{}", - thread->name_, thread->tid_); + bluetooth::log::debug("Thread message loop is operational name:{} tid:{}", thread->name_, + thread->tid_); while (thread->is_running()) { thread->work_queue_semaphore.wait(); diff --git a/system/test/fake/fake_osi.cc b/system/test/fake/fake_osi.cc index 813e0b37a51..ba31f4aa17a 100644 --- a/system/test/fake/fake_osi.cc +++ b/system/test/fake/fake_osi.cc @@ -32,7 +32,7 @@ struct alarm_t { alarm_t(const char* /* name */) { cb = nullptr; data = nullptr; - }; + } }; struct list_node_t { @@ -77,7 +77,9 @@ static list_node_t* list_free_node_(list_t* l, list_node_t* node) { auto next = node->next_; - if (l->free_cb_) l->free_cb_(node->data_); + if (l->free_cb_) { + l->free_cb_(node->data_); + } delete node; --l->length_; return next; @@ -90,16 +92,13 @@ FakeOsi::FakeOsi() { } }; - test::mock::osi_alarm::alarm_new.body = [](const char* name) { - return new alarm_t(name); - }; + test::mock::osi_alarm::alarm_new.body = [](const char* name) { return new alarm_t(name); }; - test::mock::osi_alarm::alarm_set_on_mloop.body = - [](alarm_t* alarm, uint64_t /* interval_ms */, alarm_callback_t cb, - void* data) { - alarm->cb = cb; - alarm->data = data; - }; + test::mock::osi_alarm::alarm_set_on_mloop.body = [](alarm_t* alarm, uint64_t /* interval_ms */, + alarm_callback_t cb, void* data) { + alarm->cb = cb; + alarm->data = data; + }; test::mock::osi_alarm::alarm_cancel.body = [](alarm_t* alarm) { if (alarm) { @@ -108,21 +107,15 @@ FakeOsi::FakeOsi() { } }; - test::mock::osi_allocator::osi_calloc.body = [](size_t size) { - return calloc(1UL, size); - }; + test::mock::osi_allocator::osi_calloc.body = [](size_t size) { return calloc(1UL, size); }; test::mock::osi_allocator::osi_free.body = [](void* ptr) { free(ptr); }; test::mock::osi_allocator::osi_free_and_reset.body = [](void** ptr) { free(*ptr); *ptr = nullptr; }; - test::mock::osi_allocator::osi_malloc.body = [](size_t size) { - return malloc(size); - }; + test::mock::osi_allocator::osi_malloc.body = [](size_t size) { return malloc(size); }; - test::mock::osi_list::list_new.body = [](list_free_cb callback) { - return new list_t(callback); - }; + test::mock::osi_list::list_new.body = [](list_free_cb callback) { return new list_t(callback); }; test::mock::osi_list::list_free.body = [](list_t* l) { log::assert_that(l != nullptr, "assert failed: l != nullptr"); @@ -132,21 +125,21 @@ FakeOsi::FakeOsi() { test::mock::osi_list::list_is_empty.body = [](const list_t* l) { return test::mock::osi_list::list_length(l) == 0; }; - test::mock::osi_list::list_foreach.body = - [](const list_t* l, list_iter_cb callback, void* context) { - log::assert_that(l != nullptr, "assert failed: l != nullptr"); - for (auto node = l->head_; node;) { - auto next = node->next_; - if (!callback(node->data_, context)) return node; - node = next; - } - return (list_node_t*)nullptr; - }; - test::mock::osi_list::list_contains.body = [](const list_t* l, - const void* data) { + test::mock::osi_list::list_foreach.body = [](const list_t* l, list_iter_cb callback, + void* context) { + log::assert_that(l != nullptr, "assert failed: l != nullptr"); + for (auto node = l->head_; node;) { + auto next = node->next_; + if (!callback(node->data_, context)) { + return node; + } + node = next; + } + return (list_node_t*)nullptr; + }; + test::mock::osi_list::list_contains.body = [](const list_t* l, const void* data) { auto node = test::mock::osi_list::list_foreach( - l, [](void* data, void* context) { return data != context; }, - const_cast(data)); + l, [](void* data, void* context) { return data != context; }, const_cast(data)); return node; }; test::mock::osi_list::list_length.body = [](const list_t* l) { @@ -168,25 +161,27 @@ FakeOsi::FakeOsi() { return l->tail_; }; - test::mock::osi_list::list_insert_after.body = - [](list_t* l, list_node_t* prev_node, void* data) { - log::assert_that(l != nullptr, "assert failed: l != nullptr"); - log::assert_that(prev_node != nullptr, - "assert failed: prev_node != nullptr"); - log::assert_that(data != nullptr, "assert failed: data != nullptr"); - auto node = new list_node_t(data, prev_node->next_); - prev_node->next_ = node; - if (l->tail_ == prev_node) l->tail_ = node; - ++l->length_; - return true; - }; + test::mock::osi_list::list_insert_after.body = [](list_t* l, list_node_t* prev_node, void* data) { + log::assert_that(l != nullptr, "assert failed: l != nullptr"); + log::assert_that(prev_node != nullptr, "assert failed: prev_node != nullptr"); + log::assert_that(data != nullptr, "assert failed: data != nullptr"); + auto node = new list_node_t(data, prev_node->next_); + prev_node->next_ = node; + if (l->tail_ == prev_node) { + l->tail_ = node; + } + ++l->length_; + return true; + }; test::mock::osi_list::list_prepend.body = [](list_t* l, void* data) { log::assert_that(l != nullptr, "assert failed: l != nullptr"); log::assert_that(data != nullptr, "assert failed: data != nullptr"); auto node = new list_node_t(data, l->head_); l->head_ = node; - if (l->tail_ == NULL) l->tail_ = l->head_; + if (l->tail_ == NULL) { + l->tail_ = l->head_; + } ++l->length_; return true; }; @@ -208,22 +203,28 @@ FakeOsi::FakeOsi() { log::assert_that(l != nullptr, "assert failed: l != nullptr"); log::assert_that(data != nullptr, "assert failed: data != nullptr"); - if (test::mock::osi_list::list_is_empty(l)) return false; + if (test::mock::osi_list::list_is_empty(l)) { + return false; + } if (l->head_->data_ == data) { auto next = list_free_node_(l, l->head_); - if (l->tail_ == l->head_) l->tail_ = next; + if (l->tail_ == l->head_) { + l->tail_ = next; + } l->head_ = next; return true; } - for (auto prev = l->head_, node = l->head_->next_; node; - prev = node, node = node->next_) + for (auto prev = l->head_, node = l->head_->next_; node; prev = node, node = node->next_) { if (node->data_ == data) { prev->next_ = list_free_node_(l, node); - if (l->tail_ == node) l->tail_ = prev; + if (l->tail_ == node) { + l->tail_ = prev; + } return true; } + } return false; }; @@ -258,32 +259,33 @@ FakeOsi::FakeOsi() { test::mock::osi_fixed_queue::fixed_queue_new.body = [](size_t capacity) { return new fixed_queue_t(capacity); }; - test::mock::osi_fixed_queue::fixed_queue_flush.body = - [](fixed_queue_t* q, fixed_queue_free_cb cb) { - if (q) { - if (cb) { - test::mock::osi_list::list_foreach( + test::mock::osi_fixed_queue::fixed_queue_flush.body = [](fixed_queue_t* q, + fixed_queue_free_cb cb) { + if (q) { + if (cb) { + test::mock::osi_list::list_foreach( q->list_, [](void* data, void* cb) { reinterpret_cast(cb)(data); return true; }, reinterpret_cast(cb)); - } - test::mock::osi_list::list_clear(q->list_); - } - }; - test::mock::osi_fixed_queue::fixed_queue_free.body = - [](fixed_queue_t* q, fixed_queue_free_cb free_cb) { - if (q) { - test::mock::osi_fixed_queue::fixed_queue_flush(q, free_cb); - delete q->list_; - delete q; - } - }; - test::mock::osi_fixed_queue::fixed_queue_enqueue.body = [](fixed_queue_t* q, - void* data) { - if (q) test::mock::osi_list::list_append(q->list_, data); + } + test::mock::osi_list::list_clear(q->list_); + } + }; + test::mock::osi_fixed_queue::fixed_queue_free.body = [](fixed_queue_t* q, + fixed_queue_free_cb free_cb) { + if (q) { + test::mock::osi_fixed_queue::fixed_queue_flush(q, free_cb); + delete q->list_; + delete q; + } + }; + test::mock::osi_fixed_queue::fixed_queue_enqueue.body = [](fixed_queue_t* q, void* data) { + if (q) { + test::mock::osi_list::list_append(q->list_, data); + } }; test::mock::osi_fixed_queue::fixed_queue_dequeue.body = [](fixed_queue_t* q) { void* ret = nullptr; @@ -298,76 +300,70 @@ FakeOsi::FakeOsi() { return q ? test::mock::osi_list::list_length(q->list_) : 0; }; - test::mock::osi_fixed_queue::fixed_queue_is_empty.body = - [](fixed_queue_t* q) { - return test::mock::osi_fixed_queue::fixed_queue_length(q) == 0; - }; + test::mock::osi_fixed_queue::fixed_queue_is_empty.body = [](fixed_queue_t* q) { + return test::mock::osi_fixed_queue::fixed_queue_length(q) == 0; + }; - test::mock::osi_fixed_queue::fixed_queue_capacity.body = - [](fixed_queue_t* q) { return q ? q->capacity_ : 0; }; + test::mock::osi_fixed_queue::fixed_queue_capacity.body = [](fixed_queue_t* q) { + return q ? q->capacity_ : 0; + }; - test::mock::osi_fixed_queue::fixed_queue_try_enqueue.body = - [](fixed_queue_t* q, void* data) { - test::mock::osi_fixed_queue::fixed_queue_enqueue(q, data); - return true; - }; - test::mock::osi_fixed_queue::fixed_queue_try_dequeue.body = - [](fixed_queue_t* q) { - void* ret = nullptr; - if (q && !test::mock::osi_fixed_queue::fixed_queue_is_empty(q)) { - ret = test::mock::osi_fixed_queue::fixed_queue_dequeue(q); - } - return ret; - }; - test::mock::osi_fixed_queue::fixed_queue_try_peek_first.body = - [](fixed_queue_t* q) { - return (q && !test::mock::osi_list::list_is_empty(q->list_)) + test::mock::osi_fixed_queue::fixed_queue_try_enqueue.body = [](fixed_queue_t* q, void* data) { + test::mock::osi_fixed_queue::fixed_queue_enqueue(q, data); + return true; + }; + test::mock::osi_fixed_queue::fixed_queue_try_dequeue.body = [](fixed_queue_t* q) { + void* ret = nullptr; + if (q && !test::mock::osi_fixed_queue::fixed_queue_is_empty(q)) { + ret = test::mock::osi_fixed_queue::fixed_queue_dequeue(q); + } + return ret; + }; + test::mock::osi_fixed_queue::fixed_queue_try_peek_first.body = [](fixed_queue_t* q) { + return (q && !test::mock::osi_list::list_is_empty(q->list_)) ? test::mock::osi_list::list_front(q->list_) : nullptr; - }; + }; - test::mock::osi_fixed_queue::fixed_queue_try_peek_last.body = - [](fixed_queue_t* q) { - return (q && !test::mock::osi_list::list_is_empty(q->list_)) + test::mock::osi_fixed_queue::fixed_queue_try_peek_last.body = [](fixed_queue_t* q) { + return (q && !test::mock::osi_list::list_is_empty(q->list_)) ? test::mock::osi_list::list_back(q->list_) : nullptr; - }; - - test::mock::osi_fixed_queue::fixed_queue_get_list.body = - [](fixed_queue_t* q) { return q ? q->list_ : nullptr; }; - - test::mock::osi_fixed_queue::fixed_queue_try_remove_from_queue.body = - [](fixed_queue_t* /* q */, void* /* data */) { - // not implemented - abort(); - return nullptr; - }; - - test::mock::osi_fixed_queue::fixed_queue_get_enqueue_fd.body = - [](const fixed_queue_t* /* q */) { - // not implemented - abort(); - return 0; - }; - - test::mock::osi_fixed_queue::fixed_queue_get_dequeue_fd.body = - [](const fixed_queue_t* /* q */) { - // not implemented - abort(); - return 0; - }; + }; + + test::mock::osi_fixed_queue::fixed_queue_get_list.body = [](fixed_queue_t* q) { + return q ? q->list_ : nullptr; + }; + + test::mock::osi_fixed_queue::fixed_queue_try_remove_from_queue.body = [](fixed_queue_t* /* q */, + void* /* data */) { + // not implemented + abort(); + return nullptr; + }; + + test::mock::osi_fixed_queue::fixed_queue_get_enqueue_fd.body = [](const fixed_queue_t* /* q */) { + // not implemented + abort(); + return 0; + }; + + test::mock::osi_fixed_queue::fixed_queue_get_dequeue_fd.body = [](const fixed_queue_t* /* q */) { + // not implemented + abort(); + return 0; + }; test::mock::osi_fixed_queue::fixed_queue_register_dequeue.body = - [](fixed_queue_t* /* q */, reactor_t* /* reactor */, - fixed_queue_cb /* ready_cb */, void* /* context */) { - // not implemented - abort(); - }; - test::mock::osi_fixed_queue::fixed_queue_unregister_dequeue.body = - [](fixed_queue_t* /* q */) { - // not implemented - abort(); - }; + [](fixed_queue_t* /* q */, reactor_t* /* reactor */, fixed_queue_cb /* ready_cb */, + void* /* context */) { + // not implemented + abort(); + }; + test::mock::osi_fixed_queue::fixed_queue_unregister_dequeue.body = [](fixed_queue_t* /* q */) { + // not implemented + abort(); + }; } FakeOsi::~FakeOsi() { diff --git a/system/test/fake/fake_osi.h b/system/test/fake/fake_osi.h index 20412cb35a6..fabd0a2cb1e 100644 --- a/system/test/fake/fake_osi.h +++ b/system/test/fake/fake_osi.h @@ -20,7 +20,7 @@ namespace test { namespace fake { class FakeOsi { - public: +public: FakeOsi(); ~FakeOsi(); }; diff --git a/system/test/fake/fake_thread.cc b/system/test/fake/fake_thread.cc index 048d929baf4..4bdebb9973f 100644 --- a/system/test/fake/fake_thread.cc +++ b/system/test/fake/fake_thread.cc @@ -38,16 +38,15 @@ void thread_t::set_state(State state) { void thread_t::quiesce() { quiesce_t* quiesce = static_cast(calloc(sizeof(quiesce_t), 1)); - bluetooth::log::assert_that(quiesce != nullptr, - "assert failed: quiesce != nullptr"); + bluetooth::log::assert_that(quiesce != nullptr, "assert failed: quiesce != nullptr"); quiesce->thread = this; thread_post( - this, - [](void* context) { - quiesce_t* quiesce = static_cast(context); - quiesce->thread->set_state(thread_t::State::QUIESCE); - }, - static_cast(quiesce)); + this, + [](void* context) { + quiesce_t* quiesce = static_cast(context); + quiesce->thread->set_state(thread_t::State::QUIESCE); + }, + static_cast(quiesce)); // Wait for thread to stop thread_finish_semaphore.wait(); diff --git a/system/test/fake/fake_thread.h b/system/test/fake/fake_thread.h index dac08576b81..c05f66ecc9d 100644 --- a/system/test/fake/fake_thread.h +++ b/system/test/fake/fake_thread.h @@ -36,7 +36,7 @@ class semaphore_t { std::condition_variable condition_; unsigned long count_ = 0; // Initialized as locked. - public: +public: std::mutex mutex_; void notify() { std::lock_guard lock(mutex_); @@ -46,8 +46,9 @@ class semaphore_t { void wait() { std::unique_lock lock(mutex_); - while (!count_) // Handle spurious wake-ups. + while (!count_) { // Handle spurious wake-ups. condition_.wait(lock); + } --count_; } @@ -74,12 +75,12 @@ struct thread_t { QUIESCE, }; - private: +private: State is_running_{State::STOPPED}; mutable std::mutex is_running_lock_; semaphore_t thread_finish_semaphore; - public: +public: std::queue work_queue; semaphore_t work_queue_semaphore; diff --git a/system/test/headless/adapter/adapter.cc b/system/test/headless/adapter/adapter.cc index f62ace15268..bbb3231047f 100644 --- a/system/test/headless/adapter/adapter.cc +++ b/system/test/headless/adapter/adapter.cc @@ -38,17 +38,16 @@ unsigned kTimeoutMs = 5000; int get_adapter_info([[maybe_unused]] unsigned int num_loops) { log::info("Started Device Adapter Properties"); - log::assert_that( - bluetoothInterface.get_adapter_properties() == BT_STATUS_SUCCESS, - "assert failed: bluetoothInterface.get_adapter_properties() == " - "BT_STATUS_SUCCESS"); + log::assert_that(bluetoothInterface.get_adapter_properties() == BT_STATUS_SUCCESS, + "assert failed: bluetoothInterface.get_adapter_properties() == " + "BT_STATUS_SUCCESS"); LOG_CONSOLE("Started get adapter properties"); headless::messenger::Context context{ - .stop_watch = Stopwatch(__func__), - .timeout = 1s, // Poll time - .check_point = {}, - .callbacks = {Callback::AdapterProperties}, + .stop_watch = Stopwatch(__func__), + .timeout = 1s, // Poll time + .check_point = {}, + .callbacks = {Callback::AdapterProperties}, }; bool adapter_properties_found = false; @@ -60,22 +59,21 @@ int get_adapter_info([[maybe_unused]] unsigned int num_loops) { context.callback_ready_q.pop_front(); switch (p->CallbackType()) { case Callback::AdapterProperties: { - adapter_properties_params_t* q = - static_cast(p.get()); + adapter_properties_params_t* q = static_cast(p.get()); for (const auto& p2 : q->properties()) { - LOG_CONSOLE(" %s prop:%s", p->Name().c_str(), - p2->ToString().c_str()); + LOG_CONSOLE(" %s prop:%s", p->Name().c_str(), p2->ToString().c_str()); } adapter_properties_found = true; } break; default: - LOG_CONSOLE("WARN Received callback for unasked:%s", - p->Name().c_str()); + LOG_CONSOLE("WARN Received callback for unasked:%s", p->Name().c_str()); break; } } } - if (adapter_properties_found) break; + if (adapter_properties_found) { + break; + } } LOG_CONSOLE("Retrieved adapter properties"); @@ -90,6 +88,5 @@ int bluetooth::test::headless::Adapter::Run() { options_.Usage(); return -1; } - return RunOnHeadlessStack( - [this]() { return get_adapter_info(options_.loop_); }); + return RunOnHeadlessStack([this]() { return get_adapter_info(options_.loop_); }); } diff --git a/system/test/headless/adapter/adapter.h b/system/test/headless/adapter/adapter.h index b6b7e1c2a77..a89c6fe1dd9 100644 --- a/system/test/headless/adapter/adapter.h +++ b/system/test/headless/adapter/adapter.h @@ -24,9 +24,8 @@ namespace test { namespace headless { class Adapter : public HeadlessTest { - public: - Adapter(const bluetooth::test::headless::GetOpt& options) - : HeadlessTest(options) {} +public: + Adapter(const bluetooth::test::headless::GetOpt& options) : HeadlessTest(options) {} virtual ~Adapter() = default; int Run() override; diff --git a/system/test/headless/android_namespace.cc b/system/test/headless/android_namespace.cc index 4d4a1b11657..2c4eee7f744 100644 --- a/system/test/headless/android_namespace.cc +++ b/system/test/headless/android_namespace.cc @@ -15,7 +15,5 @@ */ extern "C" { -struct android_namespace_t* android_get_exported_namespace(const char*) { - return nullptr; -} +struct android_namespace_t* android_get_exported_namespace(const char*) { return nullptr; } } // "C" diff --git a/system/test/headless/bt_stack_info.cc b/system/test/headless/bt_stack_info.cc index 3cdd6bc82cf..ee75a89c1bf 100644 --- a/system/test/headless/bt_stack_info.cc +++ b/system/test/headless/bt_stack_info.cc @@ -30,11 +30,10 @@ BtStackInfo::BtStackInfo() { { std::promise promise; auto future = promise.get_future(); - do_in_main_thread(FROM_HERE, base::BindOnce( - [](std::promise promise) { - promise.set_value(getpid()); - }, - std::move(promise))); + do_in_main_thread( + FROM_HERE, + base::BindOnce([](std::promise promise) { promise.set_value(getpid()); }, + std::move(promise))); main_pid_ = future.get(); } @@ -42,8 +41,7 @@ BtStackInfo::BtStackInfo() { std::promise promise; auto future = promise.get_future(); do_in_jni_thread(base::BindOnce( - [](std::promise promise) { promise.set_value(getpid()); }, - std::move(promise))); + [](std::promise promise) { promise.set_value(getpid()); }, std::move(promise))); jni_pid_ = future.get(); } } diff --git a/system/test/headless/bt_stack_info.h b/system/test/headless/bt_stack_info.h index 19afe0d2c10..f5625d21291 100644 --- a/system/test/headless/bt_stack_info.h +++ b/system/test/headless/bt_stack_info.h @@ -19,7 +19,7 @@ #include class BtStackInfo { - public: +public: BtStackInfo(); void DumpsysLite(); @@ -27,7 +27,7 @@ class BtStackInfo { pid_t MainPid() const { return main_pid_; } pid_t JniPid() const { return jni_pid_; } - private: +private: pid_t main_pid_; pid_t jni_pid_; }; diff --git a/system/test/headless/config.cc b/system/test/headless/config.cc index 10cb1b0fbf1..7a3aab62a00 100644 --- a/system/test/headless/config.cc +++ b/system/test/headless/config.cc @@ -22,7 +22,7 @@ using namespace bluetooth::hal; class Config { - Config(){}; + Config() {} void Help() const { // setprop persist.bluetooth.btsnoopdefaultmode full diff --git a/system/test/headless/connect/connect.cc b/system/test/headless/connect/connect.cc index 537463d1a6b..38b2563f3e3 100644 --- a/system/test/headless/connect/connect.cc +++ b/system/test/headless/connect/connect.cc @@ -45,8 +45,7 @@ namespace { bool f_simulate_stack_crash = false; -int do_connect([[maybe_unused]] unsigned int num_loops, - [[maybe_unused]] const RawAddress& bd_addr, +int do_connect([[maybe_unused]] unsigned int num_loops, [[maybe_unused]] const RawAddress& bd_addr, [[maybe_unused]] std::list options) { int disconnect_wait_time{0}; @@ -55,16 +54,18 @@ int do_connect([[maybe_unused]] unsigned int num_loops, options.pop_front(); auto v = bluetooth::test::headless::GetOpt::Split(opt); if (v.size() == 2) { - if (v[0] == "wait") disconnect_wait_time = std::stoi(v[1]); + if (v[0] == "wait") { + disconnect_wait_time = std::stoi(v[1]); + } } } log::assert_that(disconnect_wait_time >= 0, "Time cannot go backwards"); headless::messenger::Context context{ - .stop_watch = Stopwatch("Connect_timeout"), - .timeout = 3s, - .check_point = {}, - .callbacks = {Callback::AclStateChanged}, + .stop_watch = Stopwatch("Connect_timeout"), + .timeout = 3s, + .check_point = {}, + .callbacks = {Callback::AclStateChanged}, }; LOG_CONSOLE("Creating connection to:%s", bd_addr.ToString().c_str()); @@ -83,13 +84,14 @@ int do_connect([[maybe_unused]] unsigned int num_loops, acl = p; } break; default: - LOG_CONSOLE("WARN Received callback for unasked:%s", - p->Name().c_str()); + LOG_CONSOLE("WARN Received callback for unasked:%s", p->Name().c_str()); break; } } } - if (acl != nullptr) break; + if (acl != nullptr) { + break; + } } if (acl != nullptr) { @@ -97,8 +99,8 @@ int do_connect([[maybe_unused]] unsigned int num_loops, } uint64_t connect = std::chrono::duration_cast( - std::chrono::system_clock::now().time_since_epoch()) - .count(); + std::chrono::system_clock::now().time_since_epoch()) + .count(); if (f_simulate_stack_crash) { LOG_CONSOLE("Just crushing stack"); @@ -113,35 +115,32 @@ int do_connect([[maybe_unused]] unsigned int num_loops, // If we have received callback results within this timeframe... if (headless::messenger::await_callback(context)) { while (!context.callback_ready_q.empty()) { - std::shared_ptr p = - context.callback_ready_q.front(); + std::shared_ptr p = context.callback_ready_q.front(); context.callback_ready_q.pop_front(); switch (p->CallbackType()) { case Callback::AclStateChanged: { acl2 = p; } break; default: - LOG_CONSOLE("WARN Received callback for unasked:%s", - p->Name().c_str()); + LOG_CONSOLE("WARN Received callback for unasked:%s", p->Name().c_str()); break; } } } - if (acl2 != nullptr) break; + if (acl2 != nullptr) { + break; + } } - uint64_t disconnect = - std::chrono::duration_cast( - std::chrono::system_clock::now().time_since_epoch()) - .count(); - - LOG_CONSOLE("Disconnected after:%" PRId64 "ms from:%s acl:%s", - disconnect - connect, bd_addr.ToString().c_str(), - acl->ToString().c_str()); + uint64_t disconnect = std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()) + .count(); + + LOG_CONSOLE("Disconnected after:%" PRId64 "ms from:%s acl:%s", disconnect - connect, + bd_addr.ToString().c_str(), acl->ToString().c_str()); } - acl_disconnect_from_handle( - ((acl_state_changed_params_t*)(acl2.get()))->acl_handle, HCI_SUCCESS, - "BT headless disconnect"); + acl_disconnect_from_handle(((acl_state_changed_params_t*)(acl2.get()))->acl_handle, HCI_SUCCESS, + "BT headless disconnect"); sleep(3); @@ -152,7 +151,6 @@ int do_connect([[maybe_unused]] unsigned int num_loops, int bluetooth::test::headless::Connect::Run() { return RunOnHeadlessStack([this]() { - return do_connect(options_.loop_, options_.device_.front(), - options_.non_options_); + return do_connect(options_.loop_, options_.device_.front(), options_.non_options_); }); } diff --git a/system/test/headless/connect/connect.h b/system/test/headless/connect/connect.h index b7eeadd8709..6fff41073a3 100644 --- a/system/test/headless/connect/connect.h +++ b/system/test/headless/connect/connect.h @@ -24,9 +24,8 @@ namespace test { namespace headless { class Connect : public HeadlessTest { - public: - Connect(const bluetooth::test::headless::GetOpt& options) - : HeadlessTest(options) {} +public: + Connect(const bluetooth::test::headless::GetOpt& options) : HeadlessTest(options) {} int Run() override; }; diff --git a/system/test/headless/discovery/discovery.cc b/system/test/headless/discovery/discovery.cc index 8d6296189b7..5244eb893af 100644 --- a/system/test/headless/discovery/discovery.cc +++ b/system/test/headless/discovery/discovery.cc @@ -40,8 +40,7 @@ using namespace std::chrono_literals; namespace { -int start_discovery([[maybe_unused]] unsigned int num_loops, - const RawAddress& raw_address) { +int start_discovery([[maybe_unused]] unsigned int num_loops, const RawAddress& raw_address) { RawAddress bd_addr{raw_address}; Stopwatch acl_stopwatch("ACL_connection"); @@ -69,7 +68,6 @@ int bluetooth::test::headless::Discovery::Run() { options_.Usage(); return -1; } - return RunOnHeadlessStack([this]() { - return start_discovery(options_.loop_, options_.device_.front()); - }); + return RunOnHeadlessStack( + [this]() { return start_discovery(options_.loop_, options_.device_.front()); }); } diff --git a/system/test/headless/discovery/discovery.h b/system/test/headless/discovery/discovery.h index 3a1fe8142ae..21750af2c02 100644 --- a/system/test/headless/discovery/discovery.h +++ b/system/test/headless/discovery/discovery.h @@ -24,9 +24,8 @@ namespace test { namespace headless { class Discovery : public HeadlessTest { - public: - Discovery(const bluetooth::test::headless::GetOpt& options) - : HeadlessTest(options) {} +public: + Discovery(const bluetooth::test::headless::GetOpt& options) : HeadlessTest(options) {} int Run() override; }; diff --git a/system/test/headless/dumpsys/dumpsys.cc b/system/test/headless/dumpsys/dumpsys.cc index 8a2d4416cbb..b89f8f82a65 100644 --- a/system/test/headless/dumpsys/dumpsys.cc +++ b/system/test/headless/dumpsys/dumpsys.cc @@ -20,7 +20,7 @@ #include -#include "os/log.h" // android log only +#include "os/log.h" // android log only #include "stack/include/btm_api.h" #include "stack/include/btm_api_types.h" #include "stack/include/hci_error_code.h" diff --git a/system/test/headless/dumpsys/dumpsys.h b/system/test/headless/dumpsys/dumpsys.h index eb93aeb7ebe..6c6e4f2ae1e 100644 --- a/system/test/headless/dumpsys/dumpsys.h +++ b/system/test/headless/dumpsys/dumpsys.h @@ -24,9 +24,8 @@ namespace test { namespace headless { class Dumpsys : public HeadlessTest { - public: - Dumpsys(const bluetooth::test::headless::GetOpt& options) - : HeadlessTest(options) {} +public: + Dumpsys(const bluetooth::test::headless::GetOpt& options) : HeadlessTest(options) {} int Run() override; }; diff --git a/system/test/headless/get_options.cc b/system/test/headless/get_options.cc index 79817e1dfe0..76c7dd1a282 100644 --- a/system/test/headless/get_options.cc +++ b/system/test/headless/get_options.cc @@ -38,15 +38,14 @@ enum OptionType { kOptionClear = 6, }; -constexpr struct option long_options[] = { - {"device", required_argument, 0, 0}, // kOptionDevice - {"loop", required_argument, 0, 0}, // kOptionLoop/ - {"uuid", required_argument, 0, 0}, // kOptionUuid - {"msleep", required_argument, 0, 0}, // kOptionMsleep - {"stderr", no_argument, 0, 0}, // kOptionStdErr - {"flags", required_argument, 0, 0}, // kOptionFlags - {"clear", no_argument, 0, 0}, // kOptionDevice - {0, 0, 0, 0}}; +constexpr struct option long_options[] = {{"device", required_argument, 0, 0}, // kOptionDevice + {"loop", required_argument, 0, 0}, // kOptionLoop/ + {"uuid", required_argument, 0, 0}, // kOptionUuid + {"msleep", required_argument, 0, 0}, // kOptionMsleep + {"stderr", no_argument, 0, 0}, // kOptionStdErr + {"flags", required_argument, 0, 0}, // kOptionFlags + {"clear", no_argument, 0, 0}, // kOptionDevice + {0, 0, 0, 0}}; const char* kShortArgs = "cd:l:u:"; @@ -55,22 +54,17 @@ const char* kShortArgs = "cd:l:u:"; void bluetooth::test::headless::GetOpt::Usage() const { fprintf(stdout, "%s: Usage:\n", name_); fprintf(stdout, "%s -c Clear logcat logs\n", name_); - fprintf(stdout, - "%s --device= Comma separated list of remote devices\n", - name_); - fprintf(stdout, - "%s --flags= Comma separated list of gd init flags\n", - name_); - fprintf(stdout, "%s --uuid= Comma separated list of uuids\n", - name_); + fprintf(stdout, "%s --device= Comma separated list of remote devices\n", name_); + fprintf(stdout, "%s --flags= Comma separated list of gd init flags\n", name_); + fprintf(stdout, "%s --uuid= Comma separated list of uuids\n", name_); fprintf(stdout, "%s --loop= Number of loops\n", name_); fprintf(stdout, "%s --msleep= Sleep msec between loops\n", name_); fprintf(stdout, "%s --stderr Dump stderr to stdout\n", name_); fflush(nullptr); } -void bluetooth::test::headless::GetOpt::ParseValue( - char* optarg, std::list& string_list) { +void bluetooth::test::headless::GetOpt::ParseValue(char* optarg, + std::list& string_list) { log::assert_that(optarg != nullptr, "assert failed: optarg != nullptr"); char* p = optarg; char* pp = optarg; @@ -82,11 +76,12 @@ void bluetooth::test::headless::GetOpt::ParseValue( } p++; } - if (pp != p) string_list.push_back(std::string(pp)); + if (pp != p) { + string_list.push_back(std::string(pp)); + } } -std::vector bluetooth::test::headless::GetOpt::Split( - std::string s) { +std::vector bluetooth::test::headless::GetOpt::Split(std::string s) { std::stringstream ss(s); std::vector values; std::string item; @@ -96,14 +91,15 @@ std::vector bluetooth::test::headless::GetOpt::Split( return values; } -void bluetooth::test::headless::GetOpt::ProcessOption(int option_index, - char* optarg) { +void bluetooth::test::headless::GetOpt::ProcessOption(int option_index, char* optarg) { std::list string_list; OptionType option_type = static_cast(option_index); switch (option_type) { case kOptionDevice: - if (!optarg) return; + if (!optarg) { + return; + } ParseValue(optarg, string_list); for (auto& entry : string_list) { if (RawAddress::IsValidAddress(entry)) { @@ -117,22 +113,27 @@ void bluetooth::test::headless::GetOpt::ProcessOption(int option_index, loop_ = std::stoul(optarg, nullptr, 0); break; case kOptionUuid: - if (!optarg) return; + if (!optarg) { + return; + } ParseValue(optarg, string_list); for (auto& entry : string_list) { - uuid_.push_back( - bluetooth::Uuid::From16Bit(std::stoul(entry.c_str(), nullptr, 0))); + uuid_.push_back(bluetooth::Uuid::From16Bit(std::stoul(entry.c_str(), nullptr, 0))); } break; case kOptionMsleep: - if (!optarg) return; + if (!optarg) { + return; + } msec_ = std::stoul(optarg, nullptr, 0); break; case kOptionStdErr: close_stderr_ = false; break; case kOptionFlags: - if (!optarg) return; + if (!optarg) { + return; + } ParseValue(optarg, string_list); for (auto& flag : string_list) { init_flags_.push_back(flag); @@ -150,29 +151,29 @@ void bluetooth::test::headless::GetOpt::ProcessOption(int option_index, } void bluetooth::test::headless::GetOpt::ParseStackInitFlags() { - if (init_flags_.size() == 0) return; + if (init_flags_.size() == 0) { + return; + } - log::assert_that(stack_init_flags_ == nullptr, - "assert failed: stack_init_flags_ == nullptr"); + log::assert_that(stack_init_flags_ == nullptr, "assert failed: stack_init_flags_ == nullptr"); unsigned idx = 0; stack_init_flags_ = (const char**)calloc(sizeof(char*), init_flags_.size()); - for (const std::string& flag : init_flags_) + for (const std::string& flag : init_flags_) { stack_init_flags_[idx++] = flag.c_str(); + } stack_init_flags_[idx] = nullptr; } -const char** bluetooth::test::headless::GetOpt::StackInitFlags() const { - return stack_init_flags_; -} +const char** bluetooth::test::headless::GetOpt::StackInitFlags() const { return stack_init_flags_; } -bluetooth::test::headless::GetOpt::GetOpt(int argc, char** argv) - : name_(argv[0]) { +bluetooth::test::headless::GetOpt::GetOpt(int argc, char** argv) : name_(argv[0]) { while (1) { int option_index = 0; - int c = - getopt_long_only(argc, argv, kShortArgs, long_options, &option_index); - if (c == -1) break; + int c = getopt_long_only(argc, argv, kShortArgs, long_options, &option_index); + if (c == -1) { + break; + } switch (c) { case 0: diff --git a/system/test/headless/get_options.h b/system/test/headless/get_options.h index d541fb7f65c..c9a357b1fb1 100644 --- a/system/test/headless/get_options.h +++ b/system/test/headless/get_options.h @@ -28,12 +28,12 @@ namespace test { namespace headless { class GetOpt { - public: +public: GetOpt(int argc, char** arv); virtual ~GetOpt(); virtual void Usage() const; - virtual bool IsValid() const { return valid_; }; + virtual bool IsValid() const { return valid_; } std::string GetNextSubTest() const { std::string test = non_options_.front(); @@ -56,7 +56,7 @@ class GetOpt { static std::vector Split(std::string); - private: +private: void ParseValue(char* optarg, std::list& my_list); void ProcessOption(int option_index, char* optarg); void ParseStackInitFlags(); diff --git a/system/test/headless/handler.h b/system/test/headless/handler.h index 0b180d30e0a..028739704e9 100644 --- a/system/test/headless/handler.h +++ b/system/test/headless/handler.h @@ -24,14 +24,14 @@ namespace test { namespace headless { class Handler { - public: +public: Handler(); ~Handler(); Handler(const Handler& handler) = default; void Post(common::OnceClosure closure); - private: +private: os::Thread* thread_{nullptr}; os::Handler* handler_{nullptr}; }; diff --git a/system/test/headless/headless.cc b/system/test/headless/headless.cc index 869373ea909..f0b8f5531fd 100644 --- a/system/test/headless/headless.cc +++ b/system/test/headless/headless.cc @@ -45,24 +45,19 @@ namespace { constexpr char kHeadlessIcon[] = "🗣"; -std::map> - interface_api_callback_map_; +std::map> interface_api_callback_map_; } // namespace -void headless_add_callback(const std::string interface_name, - callback_function_t function) { - if (interface_api_callback_map_.find(interface_name) == - interface_api_callback_map_.end()) { - interface_api_callback_map_.emplace(interface_name, - std::list()); +void headless_add_callback(const std::string interface_name, callback_function_t function) { + if (interface_api_callback_map_.find(interface_name) == interface_api_callback_map_.end()) { + interface_api_callback_map_.emplace(interface_name, std::list()); } interface_api_callback_map_[interface_name].push_back(function); } void headless_remove_callback(const std::string interface_name) { - if (interface_api_callback_map_.find(interface_name) == - interface_api_callback_map_.end()) { + if (interface_api_callback_map_.find(interface_name) == interface_api_callback_map_.end()) { log::fatal("No callbacks registered for interface:{}", interface_name); } interface_api_callback_map_.erase(interface_name); @@ -77,8 +72,7 @@ void adapter_state_changed(bt_state_t state) { bt_state_ = state; adapter_state_cv_.notify_all(); } -void adapter_properties(bt_status_t status, int num_properties, - ::bt_property_t* properties) { +void adapter_properties(bt_status_t status, int num_properties, ::bt_property_t* properties) { const size_t num_callbacks = interface_api_callback_map_.size(); auto callback_list = interface_api_callback_map_.find(__func__); if (callback_list != interface_api_callback_map_.end()) { @@ -87,35 +81,29 @@ void adapter_properties(bt_status_t status, int num_properties, (callback)(¶ms); } } - log::info("num_callbacks:{} status:{} num_properties:{} properties:{}", - num_callbacks, bt_status_text(status), num_properties, - fmt::ptr(properties)); + log::info("num_callbacks:{} status:{} num_properties:{} properties:{}", num_callbacks, + bt_status_text(status), num_properties, fmt::ptr(properties)); } -void remote_device_properties(bt_status_t status, RawAddress* bd_addr, - int num_properties, ::bt_property_t* properties) { +void remote_device_properties(bt_status_t status, RawAddress* bd_addr, int num_properties, + ::bt_property_t* properties) { log::assert_that(bd_addr != nullptr, "assert failed: bd_addr != nullptr"); const size_t num_callbacks = interface_api_callback_map_.size(); auto callback_list = interface_api_callback_map_.find(__func__); if (callback_list != interface_api_callback_map_.end()) { - RawAddress raw_address = - (bd_addr != nullptr) ? *bd_addr : RawAddress::kEmpty; + RawAddress raw_address = (bd_addr != nullptr) ? *bd_addr : RawAddress::kEmpty; for (auto callback : callback_list->second) { - remote_device_properties_params_t params(status, raw_address, - num_properties, properties); + remote_device_properties_params_t params(status, raw_address, num_properties, properties); (callback)(¶ms); } } - log::info( - "num_callbacks:{} status:{} device:{} num_properties:{} properties:{}", - num_callbacks, bt_status_text(status), STR(*bd_addr), num_properties, - fmt::ptr(properties)); + log::info("num_callbacks:{} status:{} device:{} num_properties:{} properties:{}", num_callbacks, + bt_status_text(status), STR(*bd_addr), num_properties, fmt::ptr(properties)); } // Aggregate disparate variables from callback API into unified single structure void device_found(int num_properties, ::bt_property_t* properties) { - [[maybe_unused]] const size_t num_callbacks = - interface_api_callback_map_.size(); + [[maybe_unused]] const size_t num_callbacks = interface_api_callback_map_.size(); auto callback_list = interface_api_callback_map_.find(__func__); if (callback_list != interface_api_callback_map_.end()) { for (auto callback : callback_list->second) { @@ -123,8 +111,8 @@ void device_found(int num_properties, ::bt_property_t* properties) { (callback)(¶ms); } } - log::info("Device found callback: num_properties:{} properties:{}", - num_properties, fmt::ptr(properties)); + log::info("Device found callback: num_properties:{} properties:{}", num_properties, + fmt::ptr(properties)); } void discovery_state_changed(bt_discovery_state_t state) { @@ -138,10 +126,8 @@ void discovery_state_changed(bt_discovery_state_t state) { } /** Bluetooth Legacy PinKey Request callback */ -void pin_request([[maybe_unused]] RawAddress* remote_bd_addr, - [[maybe_unused]] bt_bdname_t* bd_name, - [[maybe_unused]] uint32_t cod, - [[maybe_unused]] bool min_16_digit) { +void pin_request([[maybe_unused]] RawAddress* remote_bd_addr, [[maybe_unused]] bt_bdname_t* bd_name, + [[maybe_unused]] uint32_t cod, [[maybe_unused]] bool min_16_digit) { log::info(""); } @@ -155,8 +141,7 @@ void ssp_request([[maybe_unused]] RawAddress* remote_bd_addr, /* Invoked in response to create_bond, cancel_bond or remove_bond */ void bond_state_changed([[maybe_unused]] bt_status_t status, [[maybe_unused]] RawAddress* remote_bd_addr, - [[maybe_unused]] bt_bond_state_t state, - [[maybe_unused]] int fail_reason) { + [[maybe_unused]] bt_bond_state_t state, [[maybe_unused]] int fail_reason) { log::info(""); } @@ -171,31 +156,26 @@ void le_address_associate([[maybe_unused]] RawAddress* main_bd_addr, } /** Bluetooth ACL connection state changed callback */ -void acl_state_changed(bt_status_t status, RawAddress* remote_bd_addr, - bt_acl_state_t state, int transport_link_type, - bt_hci_error_code_t hci_reason, +void acl_state_changed(bt_status_t status, RawAddress* remote_bd_addr, bt_acl_state_t state, + int transport_link_type, bt_hci_error_code_t hci_reason, bt_conn_direction_t direction, uint16_t acl_handle) { - log::assert_that(remote_bd_addr != nullptr, - "assert failed: remote_bd_addr != nullptr"); + log::assert_that(remote_bd_addr != nullptr, "assert failed: remote_bd_addr != nullptr"); const size_t num_callbacks = interface_api_callback_map_.size(); auto callback_list = interface_api_callback_map_.find(__func__); if (callback_list != interface_api_callback_map_.end()) { RawAddress raw_address(*remote_bd_addr); for (auto callback : callback_list->second) { - acl_state_changed_params_t params(status, raw_address, state, - transport_link_type, hci_reason, + acl_state_changed_params_t params(status, raw_address, state, transport_link_type, hci_reason, direction, acl_handle); (callback)(¶ms); } } - log::info("num_callbacks:{} status:{} device:{} state:{}", num_callbacks, - bt_status_text(status), remote_bd_addr->ToString(), - (state) ? "disconnected" : "connected"); + log::info("num_callbacks:{} status:{} device:{} state:{}", num_callbacks, bt_status_text(status), + remote_bd_addr->ToString(), (state) ? "disconnected" : "connected"); } /** Bluetooth Link Quality Report callback */ -void link_quality_report([[maybe_unused]] uint64_t timestamp, - [[maybe_unused]] int report_id, +void link_quality_report([[maybe_unused]] uint64_t timestamp, [[maybe_unused]] int report_id, [[maybe_unused]] int rssi, [[maybe_unused]] int snr, [[maybe_unused]] int retransmission_count, [[maybe_unused]] int packets_not_receive_count, @@ -204,25 +184,19 @@ void link_quality_report([[maybe_unused]] uint64_t timestamp, } /** Switch buffer size callback */ -void switch_buffer_size([[maybe_unused]] bool is_low_latency_buffer_size) { - log::info(""); -} +void switch_buffer_size([[maybe_unused]] bool is_low_latency_buffer_size) { log::info(""); } /** Switch codec callback */ -void switch_codec([[maybe_unused]] bool is_low_latency_buffer_size) { - log::info(""); -} +void switch_codec([[maybe_unused]] bool is_low_latency_buffer_size) { log::info(""); } void thread_event([[maybe_unused]] bt_cb_thread_evt evt) { log::info(""); } -void dut_mode_recv([[maybe_unused]] uint16_t opcode, - [[maybe_unused]] uint8_t* buf, +void dut_mode_recv([[maybe_unused]] uint16_t opcode, [[maybe_unused]] uint8_t* buf, [[maybe_unused]] uint8_t len) { log::info(""); } -void le_test_mode([[maybe_unused]] bt_status_t status, - [[maybe_unused]] uint16_t num_packets) { +void le_test_mode([[maybe_unused]] bt_status_t status, [[maybe_unused]] uint16_t num_packets) { log::info(""); } @@ -232,26 +206,26 @@ void energy_info([[maybe_unused]] bt_activity_energy_info* energy_info, } bt_callbacks_t bt_callbacks{ - /** set to sizeof(bt_callbacks_t) */ - .size = sizeof(bt_callbacks_t), - .adapter_state_changed_cb = adapter_state_changed, - .adapter_properties_cb = adapter_properties, - .remote_device_properties_cb = remote_device_properties, - .device_found_cb = device_found, - .discovery_state_changed_cb = discovery_state_changed, - .pin_request_cb = pin_request, - .ssp_request_cb = ssp_request, - .bond_state_changed_cb = bond_state_changed, - .address_consolidate_cb = address_consolidate, - .le_address_associate_cb = le_address_associate, - .acl_state_changed_cb = acl_state_changed, - .thread_evt_cb = thread_event, - .dut_mode_recv_cb = dut_mode_recv, - .le_test_mode_cb = le_test_mode, - .energy_info_cb = energy_info, - .link_quality_report_cb = link_quality_report, - .switch_buffer_size_cb = switch_buffer_size, - .switch_codec_cb = switch_codec, + /** set to sizeof(bt_callbacks_t) */ + .size = sizeof(bt_callbacks_t), + .adapter_state_changed_cb = adapter_state_changed, + .adapter_properties_cb = adapter_properties, + .remote_device_properties_cb = remote_device_properties, + .device_found_cb = device_found, + .discovery_state_changed_cb = discovery_state_changed, + .pin_request_cb = pin_request, + .ssp_request_cb = ssp_request, + .bond_state_changed_cb = bond_state_changed, + .address_consolidate_cb = address_consolidate, + .le_address_associate_cb = le_address_associate, + .acl_state_changed_cb = acl_state_changed, + .thread_evt_cb = thread_event, + .dut_mode_recv_cb = dut_mode_recv, + .le_test_mode_cb = le_test_mode, + .energy_info_cb = energy_info, + .link_quality_report_cb = link_quality_report, + .switch_buffer_size_cb = switch_buffer_size, + .switch_codec_cb = switch_codec, }; // HAL HARDWARE CALLBACKS @@ -267,9 +241,9 @@ int release_wake_lock_co([[maybe_unused]] const char* lock_name) { } bt_os_callouts_t bt_os_callouts{ - .size = sizeof(bt_os_callouts_t), - .acquire_wake_lock = acquire_wake_lock_co, - .release_wake_lock = release_wake_lock_co, + .size = sizeof(bt_os_callouts_t), + .acquire_wake_lock = acquire_wake_lock_co, + .release_wake_lock = release_wake_lock_co, }; void HeadlessStack::SetUp() { @@ -280,9 +254,8 @@ void HeadlessStack::SetUp() { const int config_compare_result = 0; const bool is_atv = false; - int status = bluetoothInterface.init( - &bt_callbacks, start_restricted, is_common_criteria_mode, - config_compare_result, StackInitFlags(), is_atv, nullptr); + int status = bluetoothInterface.init(&bt_callbacks, start_restricted, is_common_criteria_mode, + config_compare_result, StackInitFlags(), is_atv, nullptr); if (status == BT_STATUS_SUCCESS) { log::info("Initialized bluetooth callbacks"); @@ -301,7 +274,9 @@ void HeadlessStack::SetUp() { log::info("HeadlessStack stack has enabled"); std::unique_lock lck(adapter_state_mutex_); - while (bt_state_ != BT_STATE_ON) adapter_state_cv_.wait(lck); + while (bt_state_ != BT_STATE_ON) { + adapter_state_cv_.wait(lck); + } log::info("HeadlessStack stack is operational"); bt_stack_info_ = std::make_unique(); @@ -323,7 +298,9 @@ void HeadlessStack::TearDown() { log::info("Cleaned up hal bluetooth library"); std::unique_lock lck(adapter_state_mutex_); - while (bt_state_ != BT_STATE_OFF) adapter_state_cv_.wait(lck); + while (bt_state_ != BT_STATE_OFF) { + adapter_state_cv_.wait(lck); + } log::info("HeadlessStack stack has exited"); LOG_CONSOLE("%s Headless stack has shutdown successfully", kHeadlessIcon); } diff --git a/system/test/headless/headless.h b/system/test/headless/headless.h index 4cb67e01fb4..a44e47c7154 100644 --- a/system/test/headless/headless.h +++ b/system/test/headless/headless.h @@ -36,18 +36,17 @@ template using ExecutionUnit = std::function; constexpr char kHeadlessInitialSentinel[] = - " INITIAL HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS"; + " INITIAL HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS"; constexpr char kHeadlessStartSentinel[] = - " START HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS"; + " START HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS"; constexpr char kHeadlessStopSentinel[] = - " STOP HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS"; + " STOP HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS"; constexpr char kHeadlessFinalSentinel[] = - " FINAL HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS"; + " FINAL HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS"; class HeadlessStack { - protected: - HeadlessStack(const char** stack_init_flags) - : stack_init_flags_(stack_init_flags) {} +protected: + HeadlessStack(const char** stack_init_flags) : stack_init_flags_(stack_init_flags) {} virtual ~HeadlessStack() = default; void SetUp(); @@ -55,13 +54,13 @@ class HeadlessStack { const char** StackInitFlags() const { return stack_init_flags_; } - private: +private: const char** stack_init_flags_; std::unique_ptr bt_stack_info_; }; class HeadlessRun : public HeadlessStack { - protected: +protected: const bluetooth::test::headless::GetOpt& options_; unsigned long loop_{0}; @@ -102,7 +101,7 @@ class HeadlessRun : public HeadlessStack { template class HeadlessTest : public HeadlessRun { - public: +public: virtual T Run() { if (options_.non_options_.size() == 0) { fprintf(stdout, "Must supply at least one subtest name\n"); @@ -119,9 +118,8 @@ class HeadlessTest : public HeadlessRun { virtual ~HeadlessTest() = default; - protected: - HeadlessTest(const bluetooth::test::headless::GetOpt& options) - : HeadlessRun(options) {} +protected: + HeadlessTest(const bluetooth::test::headless::GetOpt& options) : HeadlessRun(options) {} std::unordered_map>> test_nodes_; }; diff --git a/system/test/headless/interface.h b/system/test/headless/interface.h index 2892649ffad..f06df13a4c9 100644 --- a/system/test/headless/interface.h +++ b/system/test/headless/interface.h @@ -54,31 +54,25 @@ struct callback_data_t { std::string Name() const { return std::string(name_); } Callback CallbackType() const { return callback_type_; } - uint64_t TimestampInMs() const { - return static_cast(timestamp_ms_); - } + uint64_t TimestampInMs() const { return static_cast(timestamp_ms_); } virtual ~callback_data_t() = default; virtual std::string ToString() const = 0; - protected: +protected: callback_data_t(const char* name, Callback callback_type_) - : name_(name), - callback_type_(callback_type_), - timestamp_ms_(GetTimestampMs()) {} + : name_(name), callback_type_(callback_type_), timestamp_ms_(GetTimestampMs()) {} - private: +private: const char* name_; const Callback callback_type_; const long long timestamp_ms_; }; struct callback_params_t : public callback_data_t { - virtual std::string ToString() const override { - return std::string("VIRTUAL"); - } + virtual std::string ToString() const override { return std::string("VIRTUAL"); } - protected: +protected: callback_params_t(const char* name, Callback callback_type) : callback_data_t(name, callback_type) {} virtual ~callback_params_t() = default; @@ -93,35 +87,31 @@ std::shared_ptr Cast(std::shared_ptr params) { } struct callback_params_with_properties_t : public callback_params_t { - public: +public: std::deque properties() const { return property_queue_; } size_t num_properties() const { return property_queue_.size(); } - protected: - callback_params_with_properties_t(const char* name, Callback callback_type, - int num_properties, +protected: + callback_params_with_properties_t(const char* name, Callback callback_type, int num_properties, ::bt_property_t* properties) : callback_params_t(name, callback_type) { for (int i = 0; i < num_properties; i++) { - log::debug("Processing property {}/{} {} type:{} val:{}", i, - num_properties, fmt::ptr(&properties[i]), properties[i].type, - fmt::ptr(properties[i].val)); - property_queue_.push_back( - bluetooth::test::headless::property_factory(properties[i])); + log::debug("Processing property {}/{} {} type:{} val:{}", i, num_properties, + fmt::ptr(&properties[i]), properties[i].type, fmt::ptr(properties[i].val)); + property_queue_.push_back(bluetooth::test::headless::property_factory(properties[i])); } } virtual ~callback_params_with_properties_t() = default; - private: +private: std::deque property_queue_; }; struct acl_state_changed_params_t : public callback_params_t { - acl_state_changed_params_t(bt_status_t status, RawAddress remote_bd_addr, - bt_acl_state_t state, int transport_link_type, - bt_hci_error_code_t hci_reason, + acl_state_changed_params_t(bt_status_t status, RawAddress remote_bd_addr, bt_acl_state_t state, + int transport_link_type, bt_hci_error_code_t hci_reason, bt_conn_direction_t direction, uint16_t acl_handle) : callback_params_t("acl_state_changed", Callback::AclStateChanged), status(status), @@ -131,8 +121,7 @@ struct acl_state_changed_params_t : public callback_params_t { hci_reason(hci_reason), direction(direction), acl_handle(acl_handle) {} - acl_state_changed_params_t(const acl_state_changed_params_t& params) = - default; + acl_state_changed_params_t(const acl_state_changed_params_t& params) = default; virtual ~acl_state_changed_params_t() {} bt_status_t status; @@ -145,24 +134,21 @@ struct acl_state_changed_params_t : public callback_params_t { std::string ToString() const override { return fmt::format( - "status:{} remote_bd_addr:{} state:{} transport:{} reason:{}" - " direction:{} handle:{}", - bt_status_text(status), remote_bd_addr.ToString(), - (state == BT_ACL_STATE_CONNECTED) ? "CONNECTED" : "DISCONNECTED", - bt_transport_text( - static_cast(transport_link_type)), - bt_status_text(static_cast(hci_reason)), - bt_conn_direction_text(direction), acl_handle); + "status:{} remote_bd_addr:{} state:{} transport:{} reason:{}" + " direction:{} handle:{}", + bt_status_text(status), remote_bd_addr.ToString(), + (state == BT_ACL_STATE_CONNECTED) ? "CONNECTED" : "DISCONNECTED", + bt_transport_text(static_cast(transport_link_type)), + bt_status_text(static_cast(hci_reason)), + bt_conn_direction_text(direction), acl_handle); } }; struct discovery_state_changed_params_t : public callback_params_t { discovery_state_changed_params_t(bt_discovery_state_t state) - : callback_params_t("discovery_state_changed", - Callback::DiscoveryStateChanged), + : callback_params_t("discovery_state_changed", Callback::DiscoveryStateChanged), state(state) {} - discovery_state_changed_params_t( - const discovery_state_changed_params_t& params) = default; + discovery_state_changed_params_t(const discovery_state_changed_params_t& params) = default; virtual ~discovery_state_changed_params_t() {} @@ -173,52 +159,44 @@ struct discovery_state_changed_params_t : public callback_params_t { }; struct adapter_properties_params_t : public callback_params_with_properties_t { - adapter_properties_params_t(bt_status_t status, int num_properties, - ::bt_property_t* properties) - : callback_params_with_properties_t("adapter_properties", - Callback::AdapterProperties, + adapter_properties_params_t(bt_status_t status, int num_properties, ::bt_property_t* properties) + : callback_params_with_properties_t("adapter_properties", Callback::AdapterProperties, num_properties, properties), status(status) {} - adapter_properties_params_t(const adapter_properties_params_t& params) = - default; + adapter_properties_params_t(const adapter_properties_params_t& params) = default; virtual ~adapter_properties_params_t() {} bt_status_t status; std::string ToString() const override { - return fmt::format("status:{} num_properties:{}", bt_status_text(status), - num_properties()); + return fmt::format("status:{} num_properties:{}", bt_status_text(status), num_properties()); } }; -struct remote_device_properties_params_t - : public callback_params_with_properties_t { - remote_device_properties_params_t(bt_status_t status, RawAddress bd_addr, - int num_properties, +struct remote_device_properties_params_t : public callback_params_with_properties_t { + remote_device_properties_params_t(bt_status_t status, RawAddress bd_addr, int num_properties, ::bt_property_t* properties) : callback_params_with_properties_t("remote_device_properties", - Callback::RemoteDeviceProperties, - num_properties, properties), + Callback::RemoteDeviceProperties, num_properties, + properties), status(status), bd_addr(bd_addr) {} - remote_device_properties_params_t( - const remote_device_properties_params_t& params) = default; + remote_device_properties_params_t(const remote_device_properties_params_t& params) = default; virtual ~remote_device_properties_params_t() {} bt_status_t status; RawAddress bd_addr; std::string ToString() const override { - return fmt::format("status:{} bd_addr:{} num_properties:{}", - bt_status_text(status), bd_addr.ToString(), - num_properties()); + return fmt::format("status:{} bd_addr:{} num_properties:{}", bt_status_text(status), + bd_addr.ToString(), num_properties()); } }; struct device_found_params_t : public callback_params_with_properties_t { device_found_params_t(int num_properties, ::bt_property_t* properties) - : callback_params_with_properties_t("device_found", Callback::DeviceFound, - num_properties, properties) {} + : callback_params_with_properties_t("device_found", Callback::DeviceFound, num_properties, + properties) {} device_found_params_t(const device_found_params_t& params) = default; virtual ~device_found_params_t() {} @@ -230,6 +208,5 @@ struct device_found_params_t : public callback_params_with_properties_t { using callback_function_t = void (*)(callback_data_t*); -void headless_add_callback(const std::string interface_name, - callback_function_t function); +void headless_add_callback(const std::string interface_name, callback_function_t function); void headless_remove_callback(const std::string interface_name); diff --git a/system/test/headless/log.h b/system/test/headless/log.h index 4fb439e6bce..3e4f461d2ff 100644 --- a/system/test/headless/log.h +++ b/system/test/headless/log.h @@ -44,40 +44,33 @@ constexpr char _main[7 + 1] = " MAIN "; } \ } while (false) -#define LOG_CONSOLE(fmt, args...) \ - do { \ - ASSERT_LOG(console_fd != -1, "Console output fd has not been set"); \ - /* Also log to Android logging via INFO level */ \ - ALOGI("%s:%d %s: " fmt, __FILE__, __LINE__, __func__, ##args); \ - auto _now = std::chrono::system_clock::now(); \ - auto _delta = \ - std::chrono::duration_cast(_now - _prev); \ - _prev = _now; \ - auto _now_us = \ - std::chrono::time_point_cast(_now); \ - auto _now_t = std::chrono::system_clock::to_time_t(_now); \ - /* YYYY-MM-DD_HH:MM:SS.ssssss is 26 byte long, plus 1 for null terminator \ - */ \ - char _buf[26 + 1]; \ - auto l = std::strftime(_buf, sizeof(_buf), "%Y-%m-%d %H:%M:%S", \ - std::localtime(&_now_t)); \ - snprintf(_buf + l, sizeof(_buf) - l, ".%06u", \ - static_cast(_now_us.time_since_epoch().count() % \ - 1000000)); \ - /* pid max is 2^22 = 4194304 in 64-bit system, and 32768 by default, hence \ - * 7 digits are needed most */ \ - char _buf_thread[7 + 1]; \ - snprintf(_buf_thread, sizeof(_buf_thread), "%7ld", syscall(SYS_gettid)); \ - dprintf(console_fd, "%s - [ %9.06f ] %7d %s %s : " fmt "\n", _buf, \ - _delta.count() / 1000000.0, static_cast(getpid()), \ - (syscall(SYS_gettid) == static_cast(getpid())) ? _main \ - : _buf_thread, \ - LOG_TAG, ##args); \ +#define LOG_CONSOLE(fmt, args...) \ + do { \ + ASSERT_LOG(console_fd != -1, "Console output fd has not been set"); \ + /* Also log to Android logging via INFO level */ \ + ALOGI("%s:%d %s: " fmt, __FILE__, __LINE__, __func__, ##args); \ + auto _now = std::chrono::system_clock::now(); \ + auto _delta = std::chrono::duration_cast(_now - _prev); \ + _prev = _now; \ + auto _now_us = std::chrono::time_point_cast(_now); \ + auto _now_t = std::chrono::system_clock::to_time_t(_now); \ + /* YYYY-MM-DD_HH:MM:SS.ssssss is 26 byte long, plus 1 for null terminator \ + */ \ + char _buf[26 + 1]; \ + auto l = std::strftime(_buf, sizeof(_buf), "%Y-%m-%d %H:%M:%S", std::localtime(&_now_t)); \ + snprintf(_buf + l, sizeof(_buf) - l, ".%06u", \ + static_cast(_now_us.time_since_epoch().count() % 1000000)); \ + /* pid max is 2^22 = 4194304 in 64-bit system, and 32768 by default, hence \ + * 7 digits are needed most */ \ + char _buf_thread[7 + 1]; \ + snprintf(_buf_thread, sizeof(_buf_thread), "%7ld", syscall(SYS_gettid)); \ + dprintf(console_fd, "%s - [ %9.06f ] %7d %s %s : " fmt "\n", _buf, _delta.count() / 1000000.0, \ + static_cast(getpid()), \ + (syscall(SYS_gettid) == static_cast(getpid())) ? _main : _buf_thread, LOG_TAG, \ + ##args); \ } while (false) constexpr char kCompiledDateFormat[] = "%b %d %Y"; constexpr char kBuildDateFormat[] = "%Y-%m-%d"; -inline std::string build_id() { - return std::string(bluetooth::test::headless::kBuildTime); -} +inline std::string build_id() { return std::string(bluetooth::test::headless::kBuildTime); } diff --git a/system/test/headless/main.cc b/system/test/headless/main.cc index 658a60ed320..feba9c19091 100644 --- a/system/test/headless/main.cc +++ b/system/test/headless/main.cc @@ -25,7 +25,7 @@ #include #include -#include "os/log.h" // android log only +#include "os/log.h" // android log only #include "test/headless/adapter/adapter.h" #include "test/headless/connect/connect.h" #include "test/headless/discovery/discovery.h" @@ -61,13 +61,11 @@ FILE* redirected_stderr_{nullptr}; // This keeps everybody happy. void start_trick_the_android_logging_subsystem() { redirected_stderr_ = freopen(kRedirectedStderrFilename, "w", stderr); - log::assert_that(redirected_stderr_ != nullptr, - "Unable to open redirected stderr file"); + log::assert_that(redirected_stderr_ != nullptr, "Unable to open redirected stderr file"); } void stop_trick_the_android_logging_subsystem() { - log::assert_that(redirected_stderr_ != nullptr, - "assert failed: redirected_stderr_ != nullptr"); + log::assert_that(redirected_stderr_ != nullptr, "assert failed: redirected_stderr_ != nullptr"); fclose(redirected_stderr_); redirected_stderr_ = nullptr; } @@ -91,34 +89,19 @@ void clear_logcat() { } class Main : public HeadlessTest { - public: - Main(const bluetooth::test::headless::GetOpt& options) - : HeadlessTest(options) { - test_nodes_.emplace( - "adapter", - std::make_unique(options)); - test_nodes_.emplace( - "dumpsys", - std::make_unique(options)); - test_nodes_.emplace( - "connect", - std::make_unique(options)); - test_nodes_.emplace( - "mode", std::make_unique(options)); - test_nodes_.emplace( - "nop", std::make_unique(options)); - test_nodes_.emplace( - "pairing", - std::make_unique(options)); - test_nodes_.emplace( - "read", std::make_unique(options)); - test_nodes_.emplace( - "scan", std::make_unique(options)); - test_nodes_.emplace( - "sdp", std::make_unique(options)); - test_nodes_.emplace( - "discovery", - std::make_unique(options)); +public: + Main(const bluetooth::test::headless::GetOpt& options) : HeadlessTest(options) { + test_nodes_.emplace("adapter", std::make_unique(options)); + test_nodes_.emplace("dumpsys", std::make_unique(options)); + test_nodes_.emplace("connect", std::make_unique(options)); + test_nodes_.emplace("mode", std::make_unique(options)); + test_nodes_.emplace("nop", std::make_unique(options)); + test_nodes_.emplace("pairing", std::make_unique(options)); + test_nodes_.emplace("read", std::make_unique(options)); + test_nodes_.emplace("scan", std::make_unique(options)); + test_nodes_.emplace("sdp", std::make_unique(options)); + test_nodes_.emplace("discovery", + std::make_unique(options)); } int Run() override { diff --git a/system/test/headless/messenger.cc b/system/test/headless/messenger.cc index 5e6b9c194c7..e8dba380d6d 100644 --- a/system/test/headless/messenger.cc +++ b/system/test/headless/messenger.cc @@ -35,11 +35,11 @@ struct callback_queue_t { // Must be held with lock size_t size() const { return callback_queue.size(); } - private: +private: const std::string name_; std::deque callback_queue; - public: +public: void Push(T elem) { callback_queue.push_back(elem); } // Must be held with lock T Pop() { @@ -55,7 +55,7 @@ struct messenger_t { mutable std::mutex mutex; std::condition_variable cv; callback_queue_t> callback_queue = - callback_queue_t>("callbacks"); + callback_queue_t>("callbacks"); void Push(std::shared_ptr elem) { std::unique_lock lk(mutex); callback_queue.Push(elem); @@ -75,8 +75,8 @@ bool await_callback(Context& context) { std::unique_lock lk(callback_data_.mutex); while (!callback_data_.callback_queue.empty()) { std::shared_ptr cb = callback_data_.callback_queue.Pop(); - if (std::find(context.callbacks.begin(), context.callbacks.end(), - cb->CallbackType()) != context.callbacks.end()) { + if (std::find(context.callbacks.begin(), context.callbacks.end(), cb->CallbackType()) != + context.callbacks.end()) { context.callback_ready_q.push_back(cb); } } @@ -105,23 +105,21 @@ void start_messenger() { headless_add_callback("acl_state_changed", [](callback_data_t* data) { log::assert_that(data != nullptr, "Received nullptr callback data"); messenger::callback_data_.Push(std::make_shared( - *(static_cast(data)))); + *(static_cast(data)))); }); headless_add_callback("adapter_properties", [](callback_data_t* data) { log::assert_that(data != nullptr, "Received nullptr callback data"); - messenger::callback_data_.Push( - std::make_shared( + messenger::callback_data_.Push(std::make_shared( *(static_cast(data)))); }); headless_add_callback("device_found", [](callback_data_t* data) { log::assert_that(data != nullptr, "Received nullptr callback data"); - messenger::callback_data_.Push(std::make_shared( - *(static_cast(data)))); + messenger::callback_data_.Push( + std::make_shared(*(static_cast(data)))); }); headless_add_callback("remote_device_properties", [](callback_data_t* data) { log::assert_that(data != nullptr, "Received nullptr callback data"); - messenger::callback_data_.Push( - std::make_shared( + messenger::callback_data_.Push(std::make_shared( *(static_cast(data)))); }); LOG_CONSOLE("Started messenger service"); diff --git a/system/test/headless/messenger.h b/system/test/headless/messenger.h index 67313124edb..9c23ec1ceea 100644 --- a/system/test/headless/messenger.h +++ b/system/test/headless/messenger.h @@ -48,10 +48,9 @@ bool await_callback(Context& context); namespace sdp { CheckPoint get_check_point(); -bool await_service_discovery(const Timeout& timeout, - const CheckPoint& check_point, const size_t count); -std::deque collect_from( - CheckPoint& check_point); +bool await_service_discovery(const Timeout& timeout, const CheckPoint& check_point, + const size_t count); +std::deque collect_from(CheckPoint& check_point); } // namespace sdp } // namespace messenger diff --git a/system/test/headless/mode/mode.cc b/system/test/headless/mode/mode.cc index 6cdbf994ed9..6b2fefd176f 100644 --- a/system/test/headless/mode/mode.cc +++ b/system/test/headless/mode/mode.cc @@ -36,17 +36,16 @@ using namespace bluetooth::test; using namespace std::chrono_literals; namespace { -int do_mode([[maybe_unused]] unsigned int num_loops, - [[maybe_unused]] const RawAddress& bd_addr, +int do_mode([[maybe_unused]] unsigned int num_loops, [[maybe_unused]] const RawAddress& bd_addr, [[maybe_unused]] std::list options) { LOG_CONSOLE("Starting mode change test"); // Requires a BR_EDR connection to work headless::messenger::Context context{ - .stop_watch = Stopwatch("Connect_timeout"), - .timeout = 3s, - .check_point = {}, - .callbacks = {Callback::AclStateChanged}, + .stop_watch = Stopwatch("Connect_timeout"), + .timeout = 3s, + .check_point = {}, + .callbacks = {Callback::AclStateChanged}, }; PowerMode power_mode; @@ -67,13 +66,14 @@ int do_mode([[maybe_unused]] unsigned int num_loops, LOG_CONSOLE("Acl state changed:%s", acl->ToString().c_str()); } break; default: - LOG_CONSOLE("WARN Received callback for unasked:%s", - p->Name().c_str()); + LOG_CONSOLE("WARN Received callback for unasked:%s", p->Name().c_str()); break; } } } - if (acl != nullptr) break; + if (acl != nullptr) { + break; + } } if (acl->state == BT_ACL_STATE_DISCONNECTED) { @@ -91,20 +91,17 @@ int do_mode([[maybe_unused]] unsigned int num_loops, if (result.btm_status == BTM_CMD_STARTED) { // This awaits the command status callback power_mode_callback_t cmd_status = result.cmd_status_future.get(); - LOG_CONSOLE("Sniff mode command complete:%s", - cmd_status.ToString().c_str()); + LOG_CONSOLE("Sniff mode command complete:%s", cmd_status.ToString().c_str()); if (cmd_status.status == BTM_PM_STS_PENDING) { LOG_CONSOLE("Sniff mode command accepted; awaiting mode change event"); power_mode_callback_t mode_event = result.mode_event_future.get(); - LOG_CONSOLE("Sniff mode command complete:%s", - mode_event.ToString().c_str()); + LOG_CONSOLE("Sniff mode command complete:%s", mode_event.ToString().c_str()); } else { client.remove_mode_event_promise(); LOG_CONSOLE("Command failed; no mode change event forthcoming"); } } else { - LOG_CONSOLE("Smiff mode command failed:%s", - btm_status_text(result.btm_status).c_str()); + LOG_CONSOLE("Smiff mode command failed:%s", btm_status_text(result.btm_status).c_str()); } } @@ -114,26 +111,22 @@ int do_mode([[maybe_unused]] unsigned int num_loops, LOG_CONSOLE("Active mode command sent"); if (result.btm_status == BTM_CMD_STARTED) { power_mode_callback_t cmd_status = result.cmd_status_future.get(); - LOG_CONSOLE("Active mode command complete:%s", - cmd_status.ToString().c_str()); + LOG_CONSOLE("Active mode command complete:%s", cmd_status.ToString().c_str()); if (cmd_status.status == BTM_PM_STS_PENDING) { LOG_CONSOLE("Active mode command accepted; awaiting mode change event"); power_mode_callback_t mode_event = result.mode_event_future.get(); - LOG_CONSOLE("Active mode command complete:%s", - mode_event.ToString().c_str()); + LOG_CONSOLE("Active mode command complete:%s", mode_event.ToString().c_str()); } else { client.remove_mode_event_promise(); LOG_CONSOLE("Command failed; no mode change event forthcoming"); } } else { - LOG_CONSOLE("Active mode command failed:%s", - btm_status_text(result.btm_status).c_str()); + LOG_CONSOLE("Active mode command failed:%s", btm_status_text(result.btm_status).c_str()); } } LOG_CONSOLE("Disconnecting"); - acl_disconnect_from_handle(acl->acl_handle, HCI_SUCCESS, - "BT headless disconnect"); + acl_disconnect_from_handle(acl->acl_handle, HCI_SUCCESS, "BT headless disconnect"); LOG_CONSOLE("Waiting to disconnect"); sleep(3); @@ -145,7 +138,6 @@ int do_mode([[maybe_unused]] unsigned int num_loops, // int bluetooth::test::headless::Mode::Run() { return RunOnHeadlessStack([this]() { - return do_mode(options_.loop_, options_.device_.front(), - options_.non_options_); + return do_mode(options_.loop_, options_.device_.front(), options_.non_options_); }); } diff --git a/system/test/headless/mode/mode.h b/system/test/headless/mode/mode.h index b75042c02fe..23eca184ba2 100644 --- a/system/test/headless/mode/mode.h +++ b/system/test/headless/mode/mode.h @@ -24,9 +24,8 @@ namespace test { namespace headless { class Mode : public HeadlessTest { - public: - Mode(const bluetooth::test::headless::GetOpt& options) - : HeadlessTest(options) {} +public: + Mode(const bluetooth::test::headless::GetOpt& options) : HeadlessTest(options) {} int Run() override; }; diff --git a/system/test/headless/nop/nop.cc b/system/test/headless/nop/nop.cc index 34bbf2904a7..fcae19aa258 100644 --- a/system/test/headless/nop/nop.cc +++ b/system/test/headless/nop/nop.cc @@ -20,7 +20,7 @@ #include -#include "os/log.h" // android log only +#include "os/log.h" // android log only #include "stack/include/sdp_api.h" #include "test/headless/get_options.h" #include "test/headless/headless.h" diff --git a/system/test/headless/nop/nop.h b/system/test/headless/nop/nop.h index e65efa3ba5d..cf222687f84 100644 --- a/system/test/headless/nop/nop.h +++ b/system/test/headless/nop/nop.h @@ -24,9 +24,8 @@ namespace test { namespace headless { class Nop : public HeadlessTest { - public: - Nop(const bluetooth::test::headless::GetOpt& options) - : HeadlessTest(options) {} +public: + Nop(const bluetooth::test::headless::GetOpt& options) : HeadlessTest(options) {} int Run() override; }; diff --git a/system/test/headless/pairing/pairing.h b/system/test/headless/pairing/pairing.h index 4125d48b3ac..27dbfc8d7b4 100644 --- a/system/test/headless/pairing/pairing.h +++ b/system/test/headless/pairing/pairing.h @@ -9,9 +9,8 @@ namespace test { namespace headless { class Pairing : public HeadlessTest { - public: - Pairing(const bluetooth::test::headless::GetOpt& options) - : HeadlessTest(options) {} +public: + Pairing(const bluetooth::test::headless::GetOpt& options) : HeadlessTest(options) {} int Run() override; }; diff --git a/system/test/headless/property.cc b/system/test/headless/property.cc index 065a2f44ca5..65373f82f92 100644 --- a/system/test/headless/property.cc +++ b/system/test/headless/property.cc @@ -30,86 +30,83 @@ namespace { // Map the bluetooth property names to the corresponding headless property // structure factor -std::map<::bt_property_type_t, std::function> - property_map = { - {BT_PROPERTY_BDNAME, - [](const uint8_t* data, const size_t len) -> headless::bt_property_t* { - return new headless::property::name_t(data, len); - }}, - {BT_PROPERTY_BDADDR, - [](const uint8_t* data, const size_t len) -> headless::bt_property_t* { - return new headless::property::bdaddr_t(data, len); - }}, - {BT_PROPERTY_UUIDS, - [](const uint8_t* data, const size_t len) -> headless::bt_property_t* { - return new headless::property::uuid_t(data, len); - }}, - {BT_PROPERTY_CLASS_OF_DEVICE, - [](const uint8_t* data, const size_t len) -> headless::bt_property_t* { - return new headless::property::class_of_device_t(data, len); - }}, - {BT_PROPERTY_TYPE_OF_DEVICE, - [](const uint8_t* data, const size_t len) -> headless::bt_property_t* { - return new headless::property::type_of_device_t(data, len); - }}, - {BT_PROPERTY_SERVICE_RECORD, - [](const uint8_t* data, const size_t len) -> headless::bt_property_t* { - return new headless::property::void_t(data, len, - BT_PROPERTY_SERVICE_RECORD); - }}, - {BT_PROPERTY_ADAPTER_BONDED_DEVICES, - [](const uint8_t* data, const size_t len) -> headless::bt_property_t* { - return new headless::property::void_t( - data, len, BT_PROPERTY_ADAPTER_BONDED_DEVICES); - }}, - {BT_PROPERTY_ADAPTER_DISCOVERABLE_TIMEOUT, - [](const uint8_t* data, const size_t len) -> headless::bt_property_t* { - return new headless::property::void_t( - data, len, BT_PROPERTY_ADAPTER_DISCOVERABLE_TIMEOUT); - }}, - {BT_PROPERTY_REMOTE_FRIENDLY_NAME, - [](const uint8_t* data, const size_t len) -> headless::bt_property_t* { - return new headless::property::void_t( - data, len, BT_PROPERTY_REMOTE_FRIENDLY_NAME); - }}, - {BT_PROPERTY_REMOTE_RSSI, - [](const uint8_t* data, const size_t len) -> headless::bt_property_t* { - return new headless::property::void_t(data, len, - BT_PROPERTY_REMOTE_RSSI); - }}, - {BT_PROPERTY_REMOTE_VERSION_INFO, - [](const uint8_t* data, const size_t len) -> headless::bt_property_t* { - return new headless::property::void_t( - data, len, BT_PROPERTY_REMOTE_VERSION_INFO); - }}, - {BT_PROPERTY_LOCAL_LE_FEATURES, - [](const uint8_t* data, const size_t len) -> headless::bt_property_t* { - return new headless::property::void_t(data, len, - BT_PROPERTY_LOCAL_LE_FEATURES); - }}, - {BT_PROPERTY_DYNAMIC_AUDIO_BUFFER, - [](const uint8_t* data, const size_t len) -> headless::bt_property_t* { - return new headless::property::void_t( - data, len, BT_PROPERTY_DYNAMIC_AUDIO_BUFFER); - }}, - {BT_PROPERTY_REMOTE_IS_COORDINATED_SET_MEMBER, - [](const uint8_t* data, const size_t len) -> headless::bt_property_t* { - return new headless::property::void_t( - data, len, BT_PROPERTY_REMOTE_IS_COORDINATED_SET_MEMBER); - }}, - {BT_PROPERTY_REMOTE_DEVICE_TIMESTAMP, - [](const uint8_t* data, const size_t len) -> headless::bt_property_t* { - return new headless::property::void_t( - data, len, BT_PROPERTY_REMOTE_DEVICE_TIMESTAMP); - }}, +std::map<::bt_property_type_t, + std::function> + property_map = { + {BT_PROPERTY_BDNAME, + [](const uint8_t* data, const size_t len) -> headless::bt_property_t* { + return new headless::property::name_t(data, len); + }}, + {BT_PROPERTY_BDADDR, + [](const uint8_t* data, const size_t len) -> headless::bt_property_t* { + return new headless::property::bdaddr_t(data, len); + }}, + {BT_PROPERTY_UUIDS, + [](const uint8_t* data, const size_t len) -> headless::bt_property_t* { + return new headless::property::uuid_t(data, len); + }}, + {BT_PROPERTY_CLASS_OF_DEVICE, + [](const uint8_t* data, const size_t len) -> headless::bt_property_t* { + return new headless::property::class_of_device_t(data, len); + }}, + {BT_PROPERTY_TYPE_OF_DEVICE, + [](const uint8_t* data, const size_t len) -> headless::bt_property_t* { + return new headless::property::type_of_device_t(data, len); + }}, + {BT_PROPERTY_SERVICE_RECORD, + [](const uint8_t* data, const size_t len) -> headless::bt_property_t* { + return new headless::property::void_t(data, len, BT_PROPERTY_SERVICE_RECORD); + }}, + {BT_PROPERTY_ADAPTER_BONDED_DEVICES, + [](const uint8_t* data, const size_t len) -> headless::bt_property_t* { + return new headless::property::void_t(data, len, + BT_PROPERTY_ADAPTER_BONDED_DEVICES); + }}, + {BT_PROPERTY_ADAPTER_DISCOVERABLE_TIMEOUT, + [](const uint8_t* data, const size_t len) -> headless::bt_property_t* { + return new headless::property::void_t(data, len, + BT_PROPERTY_ADAPTER_DISCOVERABLE_TIMEOUT); + }}, + {BT_PROPERTY_REMOTE_FRIENDLY_NAME, + [](const uint8_t* data, const size_t len) -> headless::bt_property_t* { + return new headless::property::void_t(data, len, + BT_PROPERTY_REMOTE_FRIENDLY_NAME); + }}, + {BT_PROPERTY_REMOTE_RSSI, + [](const uint8_t* data, const size_t len) -> headless::bt_property_t* { + return new headless::property::void_t(data, len, BT_PROPERTY_REMOTE_RSSI); + }}, + {BT_PROPERTY_REMOTE_VERSION_INFO, + [](const uint8_t* data, const size_t len) -> headless::bt_property_t* { + return new headless::property::void_t(data, len, + BT_PROPERTY_REMOTE_VERSION_INFO); + }}, + {BT_PROPERTY_LOCAL_LE_FEATURES, + [](const uint8_t* data, const size_t len) -> headless::bt_property_t* { + return new headless::property::void_t(data, len, BT_PROPERTY_LOCAL_LE_FEATURES); + }}, + {BT_PROPERTY_DYNAMIC_AUDIO_BUFFER, + [](const uint8_t* data, const size_t len) -> headless::bt_property_t* { + return new headless::property::void_t(data, len, + BT_PROPERTY_DYNAMIC_AUDIO_BUFFER); + }}, + {BT_PROPERTY_REMOTE_IS_COORDINATED_SET_MEMBER, + [](const uint8_t* data, const size_t len) -> headless::bt_property_t* { + return new headless::property::void_t( + data, len, BT_PROPERTY_REMOTE_IS_COORDINATED_SET_MEMBER); + }}, + {BT_PROPERTY_REMOTE_DEVICE_TIMESTAMP, + [](const uint8_t* data, const size_t len) -> headless::bt_property_t* { + return new headless::property::void_t(data, len, + BT_PROPERTY_REMOTE_DEVICE_TIMESTAMP); + }}, }; } // namespace // Caller owns the memory headless::bt_property_t* bluetooth::test::headless::property_factory( - const ::bt_property_t& bt_property) { + const ::bt_property_t& bt_property) { const uint8_t* data = static_cast(bt_property.val); const size_t size = static_cast(bt_property.len); diff --git a/system/test/headless/property.h b/system/test/headless/property.h index 0734ad3eaef..82279790fc8 100644 --- a/system/test/headless/property.h +++ b/system/test/headless/property.h @@ -77,7 +77,7 @@ struct bt_property_t { return oss.str(); } - protected: +protected: bt_property_t(const uint8_t* data, const size_t len) { this->len = len; this->data = std::make_unique(len); @@ -93,28 +93,26 @@ struct bt_property_t { namespace property { struct void_t : public bt_property_t { - void_t(const uint8_t* data, const size_t len, int type) - : bt_property_t(data, len) { + void_t(const uint8_t* data, const size_t len, int type) : bt_property_t(data, len) { this->type = (::bt_property_type_t)type; } - public: +public: virtual std::string ToString() const override { - return fmt::format("Unimplemented property type:{} name:{}", type, - bt_property_type_text(type)); + return fmt::format("Unimplemented property type:{} name:{}", type, bt_property_type_text(type)); } }; struct uuid_t : public bt_property_t { - public: +public: uuid_t(const uint8_t* data, const size_t len) : bt_property_t(data, len) {} std::deque get_uuids() const { std::deque uuids; bluetooth::Uuid* p_uuid = reinterpret_cast(data.get()); for (size_t i = 0; i < num_uuid(); i++, p_uuid++) { - bluetooth::Uuid uuid = bluetooth::Uuid::From128BitBE( - reinterpret_cast(p_uuid)); + bluetooth::Uuid uuid = + bluetooth::Uuid::From128BitBE(reinterpret_cast(p_uuid)); uuids.push_back(uuid); } return uuids; @@ -124,7 +122,7 @@ struct uuid_t : public bt_property_t { return fmt::format("Number of uuids:{}", get_uuids().size()); } - private: +private: size_t num_uuid() const { return len / sizeof(bluetooth::Uuid); } }; @@ -138,9 +136,7 @@ struct name_t : public bt_property_t { return std::string(s); } - virtual std::string ToString() const override { - return fmt::format("Name:{}", get_name()); - } + virtual std::string ToString() const override { return fmt::format("Name:{}", get_name()); } }; struct bdaddr_t : public bt_property_t { @@ -162,8 +158,7 @@ struct bdaddr_t : public bt_property_t { }; struct class_of_device_t : public bt_property_t { - class_of_device_t(const uint8_t* data, const size_t len) - : bt_property_t(data, len) { + class_of_device_t(const uint8_t* data, const size_t len) : bt_property_t(data, len) { type = BT_PROPERTY_CLASS_OF_DEVICE; } @@ -178,8 +173,7 @@ struct class_of_device_t : public bt_property_t { }; struct type_of_device_t : public bt_property_t { - type_of_device_t(const uint8_t* data, const size_t len) - : bt_property_t(data, len) { + type_of_device_t(const uint8_t* data, const size_t len) : bt_property_t(data, len) { type = BT_PROPERTY_TYPE_OF_DEVICE; } @@ -195,8 +189,7 @@ struct type_of_device_t : public bt_property_t { } // namespace property -bluetooth::test::headless::bt_property_t* property_factory( - const ::bt_property_t& bt_property); +bluetooth::test::headless::bt_property_t* property_factory(const ::bt_property_t& bt_property); template T* get_property_type(bluetooth::test::headless::bt_property_t* bt_property) { diff --git a/system/test/headless/read/name.cc b/system/test/headless/read/name.cc index 0b7b4b40f50..32e013715b9 100644 --- a/system/test/headless/read/name.cc +++ b/system/test/headless/read/name.cc @@ -29,9 +29,7 @@ std::promise promise_; -void RemoteNameCallback(const tBTM_REMOTE_DEV_NAME* data) { - promise_.set_value(*data); -} +void RemoteNameCallback(const tBTM_REMOTE_DEV_NAME* data) { promise_.set_value(*data); } int bluetooth::test::headless::Name::Run() { if (options_.loop_ < 1) { @@ -52,8 +50,7 @@ int bluetooth::test::headless::Name::Run() { auto future = promise_.get_future(); - tBTM_STATUS status = - get_btm_client_interface().peer.BTM_ReadRemoteDeviceName( + tBTM_STATUS status = get_btm_client_interface().peer.BTM_ReadRemoteDeviceName( raw_address, &RemoteNameCallback, BT_TRANSPORT_BR_EDR); if (status != BTM_CMD_STARTED) { fprintf(stdout, "Failure to start read remote device\n"); @@ -66,15 +63,14 @@ int bluetooth::test::headless::Name::Run() { char buf[BD_NAME_LEN]; memcpy(buf, name_packet.remote_bd_name, BD_NAME_LEN); std::string name(buf); - fprintf(stdout, "Name result mac:%s name:%s\n", - raw_address.ToString().c_str(), name.c_str()); + fprintf(stdout, "Name result mac:%s name:%s\n", raw_address.ToString().c_str(), + name.c_str()); } break; case BTM_BAD_VALUE_RET: fprintf(stdout, "Name Timeout or other failure"); return -2; default: - fprintf(stdout, "Unexpected remote name request failure status:%hd", - name_packet.status); + fprintf(stdout, "Unexpected remote name request failure status:%hd", name_packet.status); return -2; } return 0; diff --git a/system/test/headless/read/name.h b/system/test/headless/read/name.h index 587cee231ce..4431a1f4751 100644 --- a/system/test/headless/read/name.h +++ b/system/test/headless/read/name.h @@ -24,9 +24,8 @@ namespace test { namespace headless { class Name : public HeadlessTest { - public: - Name(const bluetooth::test::headless::GetOpt& options) - : HeadlessTest(options) {} +public: + Name(const bluetooth::test::headless::GetOpt& options) : HeadlessTest(options) {} int Run() override; }; diff --git a/system/test/headless/read/read.cc b/system/test/headless/read/read.cc index 93b3da1bdf9..08cf26d8fdd 100644 --- a/system/test/headless/read/read.cc +++ b/system/test/headless/read/read.cc @@ -18,15 +18,13 @@ #include "test/headless/read/read.h" -#include "os/log.h" // android log only +#include "os/log.h" // android log only #include "test/headless/get_options.h" #include "test/headless/headless.h" #include "test/headless/read/name.h" using namespace bluetooth::test::headless; -Read::Read(const bluetooth::test::headless::GetOpt& options) - : HeadlessTest(options) { - test_nodes_.emplace( - "name", std::make_unique(options)); +Read::Read(const bluetooth::test::headless::GetOpt& options) : HeadlessTest(options) { + test_nodes_.emplace("name", std::make_unique(options)); } diff --git a/system/test/headless/read/read.h b/system/test/headless/read/read.h index 04ab0f2ebe1..1df9aaa1b20 100644 --- a/system/test/headless/read/read.h +++ b/system/test/headless/read/read.h @@ -24,7 +24,7 @@ namespace test { namespace headless { class Read : public HeadlessTest { - public: +public: Read(const bluetooth::test::headless::GetOpt& options); }; diff --git a/system/test/headless/scan/scan.cc b/system/test/headless/scan/scan.cc index 69e66448d5f..d72b52236af 100644 --- a/system/test/headless/scan/scan.cc +++ b/system/test/headless/scan/scan.cc @@ -44,10 +44,10 @@ int start_scan([[maybe_unused]] unsigned int num_loops) { LOG_CONSOLE("Started inquiry - device discovery"); headless::messenger::Context context{ - .stop_watch = Stopwatch("Inquiry_timeout"), - .timeout = 1s, - .check_point = {}, - .callbacks = {Callback::RemoteDeviceProperties, Callback::DeviceFound}, + .stop_watch = Stopwatch("Inquiry_timeout"), + .timeout = 1s, + .check_point = {}, + .callbacks = {Callback::RemoteDeviceProperties, Callback::DeviceFound}, }; while (context.stop_watch.LapMs() < 10000) { @@ -59,23 +59,19 @@ int start_scan([[maybe_unused]] unsigned int num_loops) { switch (p->CallbackType()) { case Callback::RemoteDeviceProperties: { remote_device_properties_params_t* q = - static_cast(p.get()); + static_cast(p.get()); for (const auto& p2 : q->properties()) { - LOG_CONSOLE(" %s prop:%s", p->Name().c_str(), - p2->ToString().c_str()); + LOG_CONSOLE(" %s prop:%s", p->Name().c_str(), p2->ToString().c_str()); } } break; case Callback::DeviceFound: { - device_found_params_t* q = - static_cast(p.get()); + device_found_params_t* q = static_cast(p.get()); for (const auto& p2 : q->properties()) { - LOG_CONSOLE(" %s prop:%s", p->Name().c_str(), - p2->ToString().c_str()); + LOG_CONSOLE(" %s prop:%s", p->Name().c_str(), p2->ToString().c_str()); } } break; default: - LOG_CONSOLE("WARN Received callback for unasked:%s", - p->Name().c_str()); + LOG_CONSOLE("WARN Received callback for unasked:%s", p->Name().c_str()); break; } } @@ -94,7 +90,5 @@ int bluetooth::test::headless::Scan::Run() { options_.Usage(); return -1; } - return RunOnHeadlessStack([this]() { - return start_scan(options_.loop_); - }); + return RunOnHeadlessStack([this]() { return start_scan(options_.loop_); }); } diff --git a/system/test/headless/scan/scan.h b/system/test/headless/scan/scan.h index 3abe1998be2..561955df5e3 100644 --- a/system/test/headless/scan/scan.h +++ b/system/test/headless/scan/scan.h @@ -24,9 +24,8 @@ namespace test { namespace headless { class Scan : public HeadlessTest { - public: - Scan(const bluetooth::test::headless::GetOpt& options) - : HeadlessTest(options) {} +public: + Scan(const bluetooth::test::headless::GetOpt& options) : HeadlessTest(options) {} int Run() override; }; diff --git a/system/test/headless/sdp/sdp.cc b/system/test/headless/sdp/sdp.cc index 82af90574ab..7e081b64448 100644 --- a/system/test/headless/sdp/sdp.cc +++ b/system/test/headless/sdp/sdp.cc @@ -33,8 +33,7 @@ using namespace bluetooth::legacy::stack::sdp; using namespace bluetooth::test::headless; static void bta_jv_start_discovery_callback(std::promise* promise, - const RawAddress& /* bd_addr */, - tSDP_STATUS result) { + const RawAddress& /* bd_addr */, tSDP_STATUS result) { promise->set_value(result); } @@ -47,10 +46,10 @@ int sdp_query_uuid([[maybe_unused]] unsigned int num_loops, [[maybe_unused]] const bluetooth::Uuid& uuid) { SdpDb sdp_discovery_db(kMaxDiscoveryRecords); - if (!get_legacy_stack_sdp_api()->service.SDP_InitDiscoveryDb( - sdp_discovery_db.RawPointer(), sdp_discovery_db.Length(), - 1, // num_uuid, - &uuid, 0, nullptr)) { + if (!get_legacy_stack_sdp_api()->service.SDP_InitDiscoveryDb(sdp_discovery_db.RawPointer(), + sdp_discovery_db.Length(), + 1, // num_uuid, + &uuid, 0, nullptr)) { LOG_CONSOLE("Unable to initialize sdp discovery"); return -1; } @@ -62,8 +61,8 @@ int sdp_query_uuid([[maybe_unused]] unsigned int num_loops, sdp_discovery_db.Print(stdout); if (!get_legacy_stack_sdp_api()->service.SDP_ServiceSearchAttributeRequest2( - raw_address, sdp_discovery_db.RawPointer(), - base::BindRepeating(bta_jv_start_discovery_callback, &promise))) { + raw_address, sdp_discovery_db.RawPointer(), + base::BindRepeating(bta_jv_start_discovery_callback, &promise))) { fprintf(stdout, "%s Failed to start search attribute request\n", __func__); return -2; } @@ -71,8 +70,7 @@ int sdp_query_uuid([[maybe_unused]] unsigned int num_loops, const tSDP_STATUS result = future.get(); if (result != SDP_SUCCESS) { - fprintf(stdout, "Failed search discovery result:%s\n", - sdp_status_text(result).c_str()); + fprintf(stdout, "Failed search discovery result:%s\n", sdp_status_text(result).c_str()); return result; } @@ -80,8 +78,7 @@ int sdp_query_uuid([[maybe_unused]] unsigned int num_loops, uuid.ToString().c_str()); for (unsigned i = 0; i < BTA_MAX_SERVICE_ID; i++) { uint16_t uuid_as16Bit = bta_service_id_to_uuid_lkup_tbl[i]; - tSDP_DISC_REC* rec = SDP_FindServiceInDb(sdp_discovery_db.RawPointer(), - uuid_as16Bit, nullptr); + tSDP_DISC_REC* rec = SDP_FindServiceInDb(sdp_discovery_db.RawPointer(), uuid_as16Bit, nullptr); if (rec != nullptr) { LOG_CONSOLE(" uuid:0x%x", uuid_as16Bit); } @@ -110,7 +107,6 @@ int bluetooth::test::headless::Sdp::Run() { } return RunOnHeadlessStack([this]() { - return sdp_query_uuid(options_.loop_, options_.device_.front(), - options_.uuid_.front()); + return sdp_query_uuid(options_.loop_, options_.device_.front(), options_.uuid_.front()); }); } diff --git a/system/test/headless/sdp/sdp.h b/system/test/headless/sdp/sdp.h index 6542a1de750..7951572fcb8 100644 --- a/system/test/headless/sdp/sdp.h +++ b/system/test/headless/sdp/sdp.h @@ -24,9 +24,8 @@ namespace test { namespace headless { class Sdp : public HeadlessTest { - public: - Sdp(const bluetooth::test::headless::GetOpt& options) - : HeadlessTest(options) {} +public: + Sdp(const bluetooth::test::headless::GetOpt& options) : HeadlessTest(options) {} int Run() override; }; diff --git a/system/test/headless/sdp/sdp_db.cc b/system/test/headless/sdp/sdp_db.cc index 6242257033b..8f909f4955f 100644 --- a/system/test/headless/sdp/sdp_db.cc +++ b/system/test/headless/sdp/sdp_db.cc @@ -42,6 +42,5 @@ void SdpDb::Print(FILE* filep) const { for (int i = 0; i < db_->num_uuid_filters; i++) { fprintf(filep, " uuid:%s\n", db_->uuid_filters[i].ToString().c_str()); } - fprintf(filep, "raw data size:0x%x used:0x%x\n", db_->raw_size, - db_->raw_used); + fprintf(filep, "raw data size:0x%x used:0x%x\n", db_->raw_size, db_->raw_used); } diff --git a/system/test/headless/sdp/sdp_db.h b/system/test/headless/sdp/sdp_db.h index 63de0cc66e9..3e60b870c70 100644 --- a/system/test/headless/sdp/sdp_db.h +++ b/system/test/headless/sdp/sdp_db.h @@ -26,7 +26,7 @@ namespace test { namespace headless { class SdpDb { - public: +public: SdpDb(unsigned int max_records); ~SdpDb(); @@ -36,7 +36,7 @@ class SdpDb { void Print(FILE* filep) const; - private: +private: unsigned int max_records_; tSDP_DISCOVERY_DB* db_; }; diff --git a/system/test/headless/stopwatch.h b/system/test/headless/stopwatch.h index 3602600182d..e2b549c45be 100644 --- a/system/test/headless/stopwatch.h +++ b/system/test/headless/stopwatch.h @@ -23,28 +23,27 @@ #include class Stopwatch { - public: +public: Stopwatch(std::string name) : name_(std::move(name)), start_(std::chrono::duration_cast( - std::chrono::system_clock::now().time_since_epoch()) - .count()) {} + std::chrono::system_clock::now().time_since_epoch()) + .count()) {} uint64_t LapMs() const { uint64_t now = std::chrono::duration_cast( - std::chrono::system_clock::now().time_since_epoch()) - .count(); + std::chrono::system_clock::now().time_since_epoch()) + .count(); return now - start_; } std::string ToString() { return ToString(""); } std::string ToString(const std::string& comment) { - return fmt::format("{}: {} ms {}", name_, - static_cast(LapMs()), comment); + return fmt::format("{}: {} ms {}", name_, static_cast(LapMs()), comment); } - private: +private: std::string name_; uint64_t start_; }; diff --git a/system/test/headless/utils/power_mode_client.h b/system/test/headless/utils/power_mode_client.h index 2db819b66ea..90e7372d481 100644 --- a/system/test/headless/utils/power_mode_client.h +++ b/system/test/headless/utils/power_mode_client.h @@ -34,27 +34,27 @@ using namespace bluetooth; namespace { const tBTM_PM_PWR_MD default_mandatory_sniff_mode = { - .max = 0x0006, - .min = 0x0006, - .attempt = 0x0020, - .timeout = 0x7fff, - .mode = BTM_PM_MD_SNIFF, + .max = 0x0006, + .min = 0x0006, + .attempt = 0x0020, + .timeout = 0x7fff, + .mode = BTM_PM_MD_SNIFF, }; const tBTM_PM_PWR_MD typical_sniff_mode = { - .max = 800, // 5 seconds - .min = 400, // 2.5 seconds - .attempt = 4, - .timeout = 1, - .mode = BTM_PM_MD_SNIFF, + .max = 800, // 5 seconds + .min = 400, // 2.5 seconds + .attempt = 4, + .timeout = 1, + .mode = BTM_PM_MD_SNIFF, }; const tBTM_PM_PWR_MD default_active_mode = { - .max = 0, // Unused - .min = 0, // Unused - .attempt = 0, // Unused - .timeout = 0, // Unused - .mode = BTM_PM_MD_ACTIVE, + .max = 0, // Unused + .min = 0, // Unused + .attempt = 0, // Unused + .timeout = 0, // Unused + .mode = BTM_PM_MD_ACTIVE, }; } // namespace @@ -66,9 +66,8 @@ struct power_mode_callback_t { tHCI_STATUS hci_status; std::string ToString() const { - return fmt::format("bd_addr:{} pm_status:{} value:{} hci_status:{}", - bd_addr.ToString(), power_mode_status_text(status), - value, hci_status_code_text(hci_status)); + return fmt::format("bd_addr:{} pm_status:{} value:{} hci_status:{}", bd_addr.ToString(), + power_mode_status_text(status), value, hci_status_code_text(hci_status)); } }; @@ -86,13 +85,12 @@ struct pwr_result_t { namespace { class Queue { - public: +public: void CallbackReceived(const power_mode_callback_t& data) { log::info("Power mode callback cnt:{} data:{}", cnt++, data.ToString()); std::unique_lock lk(mutex); if (promises_map_[data.bd_addr].empty()) { - log::info("Received unsolicited power mode callback: {}", - data.ToString()); + log::info("Received unsolicited power mode callback: {}", data.ToString()); return; } promises_map_[data.bd_addr].front().set_value(data); @@ -112,11 +110,9 @@ class Queue { promises_map_[bd_addr].pop_front(); } - private: +private: mutable std::mutex mutex; - std::unordered_map>> - promises_map_; + std::unordered_map>> promises_map_; size_t cnt = 0; } queue_; @@ -124,11 +120,10 @@ class Queue { } // namespace class PowerMode { - public: +public: class Client { - public: - Client(const uint8_t pm_id, const RawAddress& bd_addr) - : pm_id_(pm_id), bd_addr_(bd_addr) {} + public: + Client(const uint8_t pm_id, const RawAddress& bd_addr) : pm_id_(pm_id), bd_addr_(bd_addr) {} // Used when the power mode command status is unsuccessful // to prevent waiting for a mode event that will never arrive. @@ -136,32 +131,29 @@ class PowerMode { void remove_mode_event_promise() { queue_.PopFront(bd_addr_); } pwr_result_t set_sniff(pwr_command_t&& pwr_command) { - return send_power_mode_command( - std::move(pwr_command), - get_btm_client_interface().link_policy.BTM_SetPowerMode( - pm_id_, bd_addr_, &default_mandatory_sniff_mode)); + return send_power_mode_command(std::move(pwr_command), + get_btm_client_interface().link_policy.BTM_SetPowerMode( + pm_id_, bd_addr_, &default_mandatory_sniff_mode)); } pwr_result_t set_typical_sniff(pwr_command_t&& pwr_command) { - return send_power_mode_command( - std::move(pwr_command), - get_btm_client_interface().link_policy.BTM_SetPowerMode( - pm_id_, bd_addr_, &typical_sniff_mode)); + return send_power_mode_command(std::move(pwr_command), + get_btm_client_interface().link_policy.BTM_SetPowerMode( + pm_id_, bd_addr_, &typical_sniff_mode)); } pwr_result_t set_active(pwr_command_t&& pwr_command) { - return send_power_mode_command( - std::move(pwr_command), - get_btm_client_interface().link_policy.BTM_SetPowerMode( - pm_id_, bd_addr_, &default_active_mode)); + return send_power_mode_command(std::move(pwr_command), + get_btm_client_interface().link_policy.BTM_SetPowerMode( + pm_id_, bd_addr_, &default_active_mode)); } - private: + private: pwr_result_t send_power_mode_command(pwr_command_t&& pwr_command, const tBTM_STATUS btm_status) { pwr_result_t result = { - .btm_status = btm_status, - .cmd_status_future = pwr_command.cmd_status_promise.get_future(), - .mode_event_future = pwr_command.mode_event_promise.get_future(), + .btm_status = btm_status, + .cmd_status_future = pwr_command.cmd_status_promise.get_future(), + .mode_event_future = pwr_command.mode_event_promise.get_future(), }; queue_.CommandSent(bd_addr_, std::move(pwr_command)); return result; @@ -172,43 +164,37 @@ class PowerMode { }; PowerMode() { - BTM_PmRegister(BTM_PM_DEREG, &bta_dm_cb.pm_id, - []([[maybe_unused]] const RawAddress& bd_addr, - [[maybe_unused]] tBTM_PM_STATUS status, - [[maybe_unused]] uint16_t value, - [[maybe_unused]] tHCI_STATUS hci_status) {}); - - tBTM_STATUS btm_status = - get_btm_client_interface().lifecycle.BTM_PmRegister( + BTM_PmRegister( + BTM_PM_DEREG, &bta_dm_cb.pm_id, + []([[maybe_unused]] const RawAddress& bd_addr, [[maybe_unused]] tBTM_PM_STATUS status, + [[maybe_unused]] uint16_t value, [[maybe_unused]] tHCI_STATUS hci_status) {}); + + tBTM_STATUS btm_status = get_btm_client_interface().lifecycle.BTM_PmRegister( BTM_PM_REG_SET, &pm_id_, [](const RawAddress& bd_addr, tBTM_PM_STATUS status, uint16_t value, tHCI_STATUS hci_status) { queue_.CallbackReceived(power_mode_callback_t{ - .bd_addr = bd_addr, - .status = status, - .value = value, - .hci_status = hci_status, + .bd_addr = bd_addr, + .status = status, + .value = value, + .hci_status = hci_status, }); }); - log::assert_that(BTM_SUCCESS == btm_status, - "Failed to register power mode:{}", + log::assert_that(BTM_SUCCESS == btm_status, "Failed to register power mode:{}", btm_status_text(btm_status)); } ~PowerMode() { auto status = get_btm_client_interface().lifecycle.BTM_PmRegister( - BTM_PM_DEREG, &pm_id_, - []([[maybe_unused]] const RawAddress& bd_addr, - [[maybe_unused]] tBTM_PM_STATUS status, - [[maybe_unused]] uint16_t value, - [[maybe_unused]] tHCI_STATUS hci_status) {}); - log::assert_that(BTM_SUCCESS == status, - "assert failed: BTM_SUCCESS == status"); + BTM_PM_DEREG, &pm_id_, + []([[maybe_unused]] const RawAddress& bd_addr, [[maybe_unused]] tBTM_PM_STATUS status, + [[maybe_unused]] uint16_t value, [[maybe_unused]] tHCI_STATUS hci_status) {}); + log::assert_that(BTM_SUCCESS == status, "assert failed: BTM_SUCCESS == status"); } Client GetClient(const RawAddress bd_addr) { return Client(pm_id_, bd_addr); } - private: +private: uint8_t pm_id_; }; diff --git a/system/test/mock/mock_a2dp_api.cc b/system/test/mock/mock_a2dp_api.cc index 7dddcc101ba..6d41e3c2830 100644 --- a/system/test/mock/mock_a2dp_api.cc +++ b/system/test/mock/mock_a2dp_api.cc @@ -23,15 +23,13 @@ #include "test/common/mock_functions.h" #include "types/raw_address.h" -tA2DP_STATUS A2DP_AddRecord(uint16_t service_uuid, char* p_service_name, - char* p_provider_name, uint16_t features, - uint32_t sdp_handle) { +tA2DP_STATUS A2DP_AddRecord(uint16_t service_uuid, char* p_service_name, char* p_provider_name, + uint16_t features, uint32_t sdp_handle) { inc_func_call_count(__func__); return A2DP_SUCCESS; } tA2DP_STATUS A2DP_FindService(uint16_t service_uuid, const RawAddress& bd_addr, - tA2DP_SDP_DB_PARAMS* p_db, - tA2DP_FIND_CBACK p_cback) { + tA2DP_SDP_DB_PARAMS* p_db, tA2DP_FIND_CBACK p_cback) { inc_func_call_count(__func__); return A2DP_SUCCESS; } @@ -44,6 +42,4 @@ uint8_t A2DP_BitsSet(uint64_t num) { return 0; } void A2DP_Init(void) { inc_func_call_count(__func__); } -void a2dp_set_avdt_sdp_ver(uint16_t avdt_sdp_ver) { - inc_func_call_count(__func__); -} +void a2dp_set_avdt_sdp_ver(uint16_t avdt_sdp_ver) { inc_func_call_count(__func__); } diff --git a/system/test/mock/mock_a2dp_codec_config.cc b/system/test/mock/mock_a2dp_codec_config.cc index ed49ebf0896..82c8dde0491 100644 --- a/system/test/mock/mock_a2dp_codec_config.cc +++ b/system/test/mock/mock_a2dp_codec_config.cc @@ -26,9 +26,8 @@ #include "stack/include/bt_hdr.h" #include "test/common/mock_functions.h" -A2dpCodecConfig* A2dpCodecConfig::createCodec( - btav_a2dp_codec_index_t codec_index, - btav_a2dp_codec_priority_t codec_priority) { +A2dpCodecConfig* A2dpCodecConfig::createCodec(btav_a2dp_codec_index_t codec_index, + btav_a2dp_codec_priority_t codec_priority) { inc_func_call_count(__func__); return nullptr; } @@ -36,22 +35,17 @@ A2dpCodecConfig* A2dpCodecs::findSinkCodecConfig(const uint8_t* p_codec_info) { inc_func_call_count(__func__); return nullptr; } -A2dpCodecConfig* A2dpCodecs::findSourceCodecConfig( - const uint8_t* p_codec_info) { +A2dpCodecConfig* A2dpCodecs::findSourceCodecConfig(const uint8_t* p_codec_info) { inc_func_call_count(__func__); return nullptr; } -A2dpCodecConfig::A2dpCodecConfig(btav_a2dp_codec_index_t codec_index, - const std::string& name, +A2dpCodecConfig::A2dpCodecConfig(btav_a2dp_codec_index_t codec_index, const std::string& name, btav_a2dp_codec_priority_t codec_priority) - : codec_index_(codec_index), - name_(name), - default_codec_priority_(codec_priority) { + : codec_index_(codec_index), name_(name), default_codec_priority_(codec_priority) { inc_func_call_count(__func__); } A2dpCodecConfig::~A2dpCodecConfig() { inc_func_call_count(__func__); } -A2dpCodecs::A2dpCodecs( - const std::vector& codec_priorities) +A2dpCodecs::A2dpCodecs(const std::vector& codec_priorities) : current_codec_config_(nullptr) { inc_func_call_count(__func__); } @@ -60,18 +54,15 @@ bool A2DP_AdjustCodec(uint8_t* p_codec_info) { inc_func_call_count(__func__); return false; } -bool A2DP_BuildCodecHeader(const uint8_t* p_codec_info, BT_HDR* p_buf, - uint16_t frames_per_packet) { +bool A2DP_BuildCodecHeader(const uint8_t* p_codec_info, BT_HDR* p_buf, uint16_t frames_per_packet) { inc_func_call_count(__func__); return false; } -bool A2DP_CodecEquals(const uint8_t* p_codec_info_a, - const uint8_t* p_codec_info_b) { +bool A2DP_CodecEquals(const uint8_t* p_codec_info_a, const uint8_t* p_codec_info_b) { inc_func_call_count(__func__); return false; } -bool A2DP_CodecTypeEquals(const uint8_t* p_codec_info_a, - const uint8_t* p_codec_info_b) { +bool A2DP_CodecTypeEquals(const uint8_t* p_codec_info_a, const uint8_t* p_codec_info_b) { inc_func_call_count(__func__); return false; } @@ -80,8 +71,7 @@ bool A2DP_GetPacketTimestamp(const uint8_t* p_codec_info, const uint8_t* p_data, inc_func_call_count(__func__); return false; } -bool A2DP_InitCodecConfig(btav_a2dp_codec_index_t codec_index, - AvdtpSepConfig* p_cfg) { +bool A2DP_InitCodecConfig(btav_a2dp_codec_index_t codec_index, AvdtpSepConfig* p_cfg) { inc_func_call_count(__func__); return false; } @@ -113,13 +103,11 @@ bool A2DP_IsSourceCodecValid(const uint8_t* p_codec_info) { inc_func_call_count(__func__); return false; } -bool A2DP_UsesRtpHeader(bool content_protection_enabled, - const uint8_t* p_codec_info) { +bool A2DP_UsesRtpHeader(bool content_protection_enabled, const uint8_t* p_codec_info) { inc_func_call_count(__func__); return false; } -bool A2dpCodecConfig::codecConfigIsValid( - const btav_a2dp_codec_config_t& codec_config) { +bool A2dpCodecConfig::codecConfigIsValid(const btav_a2dp_codec_config_t& codec_config) { inc_func_call_count(__func__); return false; } @@ -131,8 +119,7 @@ bool A2dpCodecConfig::getCodecSpecificConfig(tBT_A2DP_OFFLOAD* p_a2dp_offload) { inc_func_call_count(__func__); return false; } -bool A2dpCodecConfig::isCodecConfigEmpty( - const btav_a2dp_codec_config_t& codec_config) { +bool A2dpCodecConfig::isCodecConfigEmpty(const btav_a2dp_codec_config_t& codec_config) { inc_func_call_count(__func__); return false; } @@ -140,20 +127,19 @@ bool A2dpCodecConfig::isValid() const { inc_func_call_count(__func__); return false; } -bool A2dpCodecConfig::setCodecUserConfig( - const btav_a2dp_codec_config_t& codec_user_config, - const btav_a2dp_codec_config_t& codec_audio_config, - const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params, - const uint8_t* p_peer_codec_info, bool is_capability, - uint8_t* p_result_codec_config, bool* p_restart_input, - bool* p_restart_output, bool* p_config_updated) { +bool A2dpCodecConfig::setCodecUserConfig(const btav_a2dp_codec_config_t& codec_user_config, + const btav_a2dp_codec_config_t& codec_audio_config, + const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params, + const uint8_t* p_peer_codec_info, bool is_capability, + uint8_t* p_result_codec_config, bool* p_restart_input, + bool* p_restart_output, bool* p_config_updated) { inc_func_call_count(__func__); return false; } bool A2dpCodecs::getCodecConfigAndCapabilities( - btav_a2dp_codec_config_t* p_codec_config, - std::vector* p_codecs_local_capabilities, - std::vector* p_codecs_selectable_capabilities) { + btav_a2dp_codec_config_t* p_codec_config, + std::vector* p_codecs_local_capabilities, + std::vector* p_codecs_selectable_capabilities) { inc_func_call_count(__func__); return false; } @@ -165,51 +151,44 @@ bool A2dpCodecs::isSupportedCodec(btav_a2dp_codec_index_t codec_index) { inc_func_call_count(__func__); return false; } -bool A2dpCodecs::setCodecAudioConfig( - const btav_a2dp_codec_config_t& codec_audio_config, - const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params, - const uint8_t* p_peer_sink_capabilities, uint8_t* p_result_codec_config, - bool* p_restart_output, bool* p_config_updated) { +bool A2dpCodecs::setCodecAudioConfig(const btav_a2dp_codec_config_t& codec_audio_config, + const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params, + const uint8_t* p_peer_sink_capabilities, + uint8_t* p_result_codec_config, bool* p_restart_output, + bool* p_config_updated) { inc_func_call_count(__func__); return false; } -bool A2dpCodecs::setCodecConfig(const uint8_t* p_peer_codec_info, - bool is_capability, - uint8_t* p_result_codec_config, - bool select_current_codec) { +bool A2dpCodecs::setCodecConfig(const uint8_t* p_peer_codec_info, bool is_capability, + uint8_t* p_result_codec_config, bool select_current_codec) { inc_func_call_count(__func__); return false; } -bool A2dpCodecs::setCodecOtaConfig( - const uint8_t* p_ota_codec_config, - const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params, - uint8_t* p_result_codec_config, bool* p_restart_input, - bool* p_restart_output, bool* p_config_updated) { +bool A2dpCodecs::setCodecOtaConfig(const uint8_t* p_ota_codec_config, + const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params, + uint8_t* p_result_codec_config, bool* p_restart_input, + bool* p_restart_output, bool* p_config_updated) { inc_func_call_count(__func__); return false; } -bool A2dpCodecs::setCodecUserConfig( - const btav_a2dp_codec_config_t& codec_user_config, - const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params, - const uint8_t* p_peer_sink_capabilities, uint8_t* p_result_codec_config, - bool* p_restart_input, bool* p_restart_output, bool* p_config_updated) { +bool A2dpCodecs::setCodecUserConfig(const btav_a2dp_codec_config_t& codec_user_config, + const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params, + const uint8_t* p_peer_sink_capabilities, + uint8_t* p_result_codec_config, bool* p_restart_input, + bool* p_restart_output, bool* p_config_updated) { inc_func_call_count(__func__); return false; } -bool A2dpCodecs::setPeerSinkCodecCapabilities( - const uint8_t* p_peer_codec_capabilities) { +bool A2dpCodecs::setPeerSinkCodecCapabilities(const uint8_t* p_peer_codec_capabilities) { inc_func_call_count(__func__); return false; } -bool A2dpCodecs::setPeerSourceCodecCapabilities( - const uint8_t* p_peer_codec_capabilities) { +bool A2dpCodecs::setPeerSourceCodecCapabilities(const uint8_t* p_peer_codec_capabilities) { inc_func_call_count(__func__); return false; } -bool A2dpCodecs::setSinkCodecConfig(const uint8_t* p_peer_codec_info, - bool is_capability, - uint8_t* p_result_codec_config, - bool select_current_codec) { +bool A2dpCodecs::setSinkCodecConfig(const uint8_t* p_peer_codec_info, bool is_capability, + uint8_t* p_result_codec_config, bool select_current_codec) { inc_func_call_count(__func__); return false; } @@ -259,13 +238,11 @@ const char* A2DP_CodecName(const uint8_t* p_codec_info) { inc_func_call_count(__func__); return nullptr; } -const tA2DP_DECODER_INTERFACE* A2DP_GetDecoderInterface( - const uint8_t* p_codec_info) { +const tA2DP_DECODER_INTERFACE* A2DP_GetDecoderInterface(const uint8_t* p_codec_info) { inc_func_call_count(__func__); return nullptr; } -const tA2DP_ENCODER_INTERFACE* A2DP_GetEncoderInterface( - const uint8_t* p_codec_info) { +const tA2DP_ENCODER_INTERFACE* A2DP_GetEncoderInterface(const uint8_t* p_codec_info) { inc_func_call_count(__func__); return nullptr; } @@ -294,22 +271,20 @@ std::string A2DP_CodecInfoString(const uint8_t* p_codec_info) { return 0; } std::string A2dpCodecConfig::codecBitsPerSample2Str( - btav_a2dp_codec_bits_per_sample_t codec_bits_per_sample) { + btav_a2dp_codec_bits_per_sample_t codec_bits_per_sample) { inc_func_call_count(__func__); return 0; } std::string A2dpCodecConfig::codecChannelMode2Str( - btav_a2dp_codec_channel_mode_t codec_channel_mode) { + btav_a2dp_codec_channel_mode_t codec_channel_mode) { inc_func_call_count(__func__); return 0; } -std::string A2dpCodecConfig::codecConfig2Str( - const btav_a2dp_codec_config_t& codec_config) { +std::string A2dpCodecConfig::codecConfig2Str(const btav_a2dp_codec_config_t& codec_config) { inc_func_call_count(__func__); return 0; } -std::string A2dpCodecConfig::codecSampleRate2Str( - btav_a2dp_codec_sample_rate_t codec_sample_rate) { +std::string A2dpCodecConfig::codecSampleRate2Str(btav_a2dp_codec_sample_rate_t codec_sample_rate) { inc_func_call_count(__func__); return 0; } @@ -325,17 +300,10 @@ uint8_t A2dpCodecConfig::getAudioBitsPerSample() { inc_func_call_count(__func__); return 0; } -void A2DP_InitDefaultCodec(uint8_t* p_codec_info) { - inc_func_call_count(__func__); -} -void A2dpCodecConfig::debug_codec_dump(int fd) { - inc_func_call_count(__func__); -} -void A2dpCodecConfig::setCodecPriority( - btav_a2dp_codec_priority_t codec_priority) { - inc_func_call_count(__func__); -} -void A2dpCodecConfig::setDefaultCodecPriority() { +void A2DP_InitDefaultCodec(uint8_t* p_codec_info) { inc_func_call_count(__func__); } +void A2dpCodecConfig::debug_codec_dump(int fd) { inc_func_call_count(__func__); } +void A2dpCodecConfig::setCodecPriority(btav_a2dp_codec_priority_t codec_priority) { inc_func_call_count(__func__); } +void A2dpCodecConfig::setDefaultCodecPriority() { inc_func_call_count(__func__); } void A2dpCodecs::debug_codec_dump(int fd) { inc_func_call_count(__func__); } diff --git a/system/test/mock/mock_audio_hal_interface_a2dp_encoding.cc b/system/test/mock/mock_audio_hal_interface_a2dp_encoding.cc index 237f8d69670..7525d2181c0 100644 --- a/system/test/mock/mock_audio_hal_interface_a2dp_encoding.cc +++ b/system/test/mock/mock_audio_hal_interface_a2dp_encoding.cc @@ -57,8 +57,7 @@ struct sink_codec_index sink_codec_index; struct source_codec_index source_codec_index; struct start_session start_session; struct supports_codec supports_codec; -struct update_codec_offloading_capabilities - update_codec_offloading_capabilities; +struct update_codec_offloading_capabilities update_codec_offloading_capabilities; } // namespace audio_hal_interface_a2dp_encoding } // namespace mock @@ -71,8 +70,7 @@ namespace audio_hal_interface_a2dp_encoding { std::optional codec_index_str::return_value = std::nullopt; bool codec_info::return_value = false; -std::optional get_a2dp_configuration::return_value = - std::nullopt; +std::optional get_a2dp_configuration::return_value = std::nullopt; bool init::return_value = false; bool is_hal_enabled::return_value = false; bool is_hal_offloading::return_value = false; @@ -80,10 +78,8 @@ bool is_opus_supported::return_value = false; tA2DP_STATUS parse_a2dp_configuration::return_value = A2DP_SUCCESS; size_t read::return_value = 0; bool setup_codec::return_value = false; -std::optional sink_codec_index::return_value = - std::nullopt; -std::optional source_codec_index::return_value = - std::nullopt; +std::optional sink_codec_index::return_value = std::nullopt; +std::optional source_codec_index::return_value = std::nullopt; bool supports_codec::return_value = false; bool update_codec_offloading_capabilities::return_value = false; @@ -105,30 +101,27 @@ void cleanup() { test::mock::audio_hal_interface_a2dp_encoding::cleanup(); } std::optional bluetooth::audio::a2dp::provider::codec_index_str( - btav_a2dp_codec_index_t codec_index) { + btav_a2dp_codec_index_t codec_index) { inc_func_call_count(__func__); - return test::mock::audio_hal_interface_a2dp_encoding::codec_index_str( - codec_index); + return test::mock::audio_hal_interface_a2dp_encoding::codec_index_str(codec_index); } -bool bluetooth::audio::a2dp::provider::codec_info( - btav_a2dp_codec_index_t codec_index, uint64_t* codec_id, - uint8_t* codec_info, btav_a2dp_codec_config_t* codec_config) { +bool bluetooth::audio::a2dp::provider::codec_info(btav_a2dp_codec_index_t codec_index, + uint64_t* codec_id, uint8_t* codec_info, + btav_a2dp_codec_config_t* codec_config) { inc_func_call_count(__func__); - return test::mock::audio_hal_interface_a2dp_encoding::codec_info( - codec_index, codec_id, codec_info, codec_config); + return test::mock::audio_hal_interface_a2dp_encoding::codec_info(codec_index, codec_id, + codec_info, codec_config); } void end_session() { inc_func_call_count(__func__); test::mock::audio_hal_interface_a2dp_encoding::end_session(); } -std::optional -bluetooth::audio::a2dp::provider::get_a2dp_configuration( - RawAddress peer_address, - std::vector const& remote_seps, - btav_a2dp_codec_config_t const& user_preferences) { +std::optional bluetooth::audio::a2dp::provider::get_a2dp_configuration( + RawAddress peer_address, std::vector const& remote_seps, + btav_a2dp_codec_config_t const& user_preferences) { inc_func_call_count(__func__); return test::mock::audio_hal_interface_a2dp_encoding::get_a2dp_configuration( - peer_address, remote_seps, user_preferences); + peer_address, remote_seps, user_preferences); } bool init(bluetooth::common::MessageLoopThread* message_loop) { inc_func_call_count(__func__); @@ -147,13 +140,12 @@ bool is_opus_supported() { return test::mock::audio_hal_interface_a2dp_encoding::is_opus_supported(); } tA2DP_STATUS bluetooth::audio::a2dp::provider::parse_a2dp_configuration( - btav_a2dp_codec_index_t codec_index, const uint8_t* codec_info, - btav_a2dp_codec_config_t* codec_parameters, - std::vector* vendor_specific_parameters) { + btav_a2dp_codec_index_t codec_index, const uint8_t* codec_info, + btav_a2dp_codec_config_t* codec_parameters, + std::vector* vendor_specific_parameters) { inc_func_call_count(__func__); - return test::mock::audio_hal_interface_a2dp_encoding:: - parse_a2dp_configuration(codec_index, codec_info, codec_parameters, - vendor_specific_parameters); + return test::mock::audio_hal_interface_a2dp_encoding::parse_a2dp_configuration( + codec_index, codec_info, codec_parameters, vendor_specific_parameters); } size_t read(uint8_t* p_buf, uint32_t len) { inc_func_call_count(__func__); @@ -161,8 +153,7 @@ size_t read(uint8_t* p_buf, uint32_t len) { } void set_audio_low_latency_mode_allowed(bool allowed) { inc_func_call_count(__func__); - test::mock::audio_hal_interface_a2dp_encoding:: - set_audio_low_latency_mode_allowed(allowed); + test::mock::audio_hal_interface_a2dp_encoding::set_audio_low_latency_mode_allowed(allowed); } void set_remote_delay(uint16_t delay_report) { inc_func_call_count(__func__); @@ -172,37 +163,30 @@ bool setup_codec() { inc_func_call_count(__func__); return test::mock::audio_hal_interface_a2dp_encoding::setup_codec(); } -std::optional -bluetooth::audio::a2dp::provider::sink_codec_index( - const uint8_t* p_codec_info) { +std::optional bluetooth::audio::a2dp::provider::sink_codec_index( + const uint8_t* p_codec_info) { inc_func_call_count(__func__); - return test::mock::audio_hal_interface_a2dp_encoding::sink_codec_index( - p_codec_info); + return test::mock::audio_hal_interface_a2dp_encoding::sink_codec_index(p_codec_info); } -std::optional -bluetooth::audio::a2dp::provider::source_codec_index( - const uint8_t* p_codec_info) { +std::optional bluetooth::audio::a2dp::provider::source_codec_index( + const uint8_t* p_codec_info) { inc_func_call_count(__func__); - return test::mock::audio_hal_interface_a2dp_encoding::source_codec_index( - p_codec_info); + return test::mock::audio_hal_interface_a2dp_encoding::source_codec_index(p_codec_info); } void start_session() { inc_func_call_count(__func__); test::mock::audio_hal_interface_a2dp_encoding::start_session(); } -bool bluetooth::audio::a2dp::provider::supports_codec( - btav_a2dp_codec_index_t codec_index) { +bool bluetooth::audio::a2dp::provider::supports_codec(btav_a2dp_codec_index_t codec_index) { inc_func_call_count(__func__); - return test::mock::audio_hal_interface_a2dp_encoding::supports_codec( - codec_index); + return test::mock::audio_hal_interface_a2dp_encoding::supports_codec(codec_index); } bool update_codec_offloading_capabilities( - const std::vector& framework_preference, - bool supports_a2dp_hw_offload_v2) { + const std::vector& framework_preference, + bool supports_a2dp_hw_offload_v2) { inc_func_call_count(__func__); - return test::mock::audio_hal_interface_a2dp_encoding:: - update_codec_offloading_capabilities(framework_preference, - supports_a2dp_hw_offload_v2); + return test::mock::audio_hal_interface_a2dp_encoding::update_codec_offloading_capabilities( + framework_preference, supports_a2dp_hw_offload_v2); } // Mocked functions complete // END mockcify generation diff --git a/system/test/mock/mock_audio_hal_interface_a2dp_encoding.h b/system/test/mock/mock_audio_hal_interface_a2dp_encoding.h index e463ab46138..12c76f678d3 100644 --- a/system/test/mock/mock_audio_hal_interface_a2dp_encoding.h +++ b/system/test/mock/mock_audio_hal_interface_a2dp_encoding.h @@ -68,7 +68,7 @@ extern struct ack_stream_suspended ack_stream_suspended; // Return: void struct cleanup { std::function body{[]() {}}; - void operator()() { body(); }; + void operator()() { body(); } }; extern struct cleanup cleanup; @@ -77,13 +77,11 @@ extern struct cleanup cleanup; // Return: std::optional struct codec_index_str { static std::optional return_value; - std::function(btav_a2dp_codec_index_t codec_index)> - body{[](btav_a2dp_codec_index_t /* codec_index */) { - return return_value; - }}; + std::function(btav_a2dp_codec_index_t codec_index)> body{ + [](btav_a2dp_codec_index_t /* codec_index */) { return return_value; }}; std::optional operator()(btav_a2dp_codec_index_t codec_index) { return body(codec_index); - }; + } }; extern struct codec_index_str codec_index_str; @@ -92,18 +90,15 @@ extern struct codec_index_str codec_index_str; // codec_info, btav_a2dp_codec_config_t* codec_config Return: bool struct codec_info { static bool return_value; - std::function - body{[](btav_a2dp_codec_index_t /* codec_index */, - uint64_t* /* codec_id */, uint8_t* /* codec_info */, - btav_a2dp_codec_config_t* /* codec_config */) { - return return_value; - }}; - bool operator()(btav_a2dp_codec_index_t codec_index, uint64_t* codec_id, - uint8_t* codec_info, btav_a2dp_codec_config_t* codec_config) { + body{[](btav_a2dp_codec_index_t /* codec_index */, uint64_t* /* codec_id */, + uint8_t* /* codec_info */, + btav_a2dp_codec_config_t* /* codec_config */) { return return_value; }}; + bool operator()(btav_a2dp_codec_index_t codec_index, uint64_t* codec_id, uint8_t* codec_info, + btav_a2dp_codec_config_t* codec_config) { return body(codec_index, codec_id, codec_info, codec_config); - }; + } }; extern struct codec_info codec_info; @@ -112,7 +107,7 @@ extern struct codec_info codec_info; // Return: void struct end_session { std::function body{[]() {}}; - void operator()() { body(); }; + void operator()() { body(); } }; extern struct end_session end_session; @@ -123,20 +118,16 @@ extern struct end_session end_session; struct get_a2dp_configuration { static std::optional return_value; std::function( - RawAddress peer_address, - std::vector const& remote_seps, - btav_a2dp_codec_config_t const& user_preferences)> - body{[](RawAddress /* peer_address */, - std::vector const& /* remote_seps */, - btav_a2dp_codec_config_t const& /* user_preferences */) { - return return_value; - }}; + RawAddress peer_address, std::vector const& remote_seps, + btav_a2dp_codec_config_t const& user_preferences)> + body{[](RawAddress /* peer_address */, + std::vector const& /* remote_seps */, + btav_a2dp_codec_config_t const& /* user_preferences */) { return return_value; }}; std::optional operator()( - RawAddress peer_address, - std::vector const& remote_seps, - btav_a2dp_codec_config_t const& user_preferences) { + RawAddress peer_address, std::vector const& remote_seps, + btav_a2dp_codec_config_t const& user_preferences) { return body(peer_address, remote_seps, user_preferences); - }; + } }; extern struct get_a2dp_configuration get_a2dp_configuration; @@ -146,12 +137,8 @@ extern struct get_a2dp_configuration get_a2dp_configuration; struct init { static bool return_value; std::function body{ - [](bluetooth::common::MessageLoopThread* /* message_loop */) { - return return_value; - }}; - bool operator()(bluetooth::common::MessageLoopThread* message_loop) { - return body(message_loop); - }; + [](bluetooth::common::MessageLoopThread* /* message_loop */) { return return_value; }}; + bool operator()(bluetooth::common::MessageLoopThread* message_loop) { return body(message_loop); } }; extern struct init init; @@ -161,7 +148,7 @@ extern struct init init; struct is_hal_enabled { static bool return_value; std::function body{[]() { return return_value; }}; - bool operator()() { return body(); }; + bool operator()() { return body(); } }; extern struct is_hal_enabled is_hal_enabled; @@ -171,7 +158,7 @@ extern struct is_hal_enabled is_hal_enabled; struct is_hal_offloading { static bool return_value; std::function body{[]() { return return_value; }}; - bool operator()() { return body(); }; + bool operator()() { return body(); } }; extern struct is_hal_offloading is_hal_offloading; @@ -181,7 +168,7 @@ extern struct is_hal_offloading is_hal_offloading; struct is_opus_supported { static bool return_value; std::function body{[]() { return return_value; }}; - bool operator()() { return body(); }; + bool operator()() { return body(); } }; extern struct is_opus_supported is_opus_supported; @@ -191,23 +178,17 @@ extern struct is_opus_supported is_opus_supported; // vendor_specific_parameters Return: tA2DP_STATUS struct parse_a2dp_configuration { static tA2DP_STATUS return_value; - std::function* vendor_specific_parameters)> - body{[](btav_a2dp_codec_index_t /* codec_index */, - const uint8_t* /* codec_info */, - btav_a2dp_codec_config_t* /* codec_parameters */, - std::vector* /* vendor_specific_parameters */) { - return return_value; - }}; - tA2DP_STATUS operator()(btav_a2dp_codec_index_t codec_index, - const uint8_t* codec_info, + body{[](btav_a2dp_codec_index_t /* codec_index */, const uint8_t* /* codec_info */, + btav_a2dp_codec_config_t* /* codec_parameters */, + std::vector* /* vendor_specific_parameters */) { return return_value; }}; + tA2DP_STATUS operator()(btav_a2dp_codec_index_t codec_index, const uint8_t* codec_info, btav_a2dp_codec_config_t* codec_parameters, std::vector* vendor_specific_parameters) { - return body(codec_index, codec_info, codec_parameters, - vendor_specific_parameters); - }; + return body(codec_index, codec_info, codec_parameters, vendor_specific_parameters); + } }; extern struct parse_a2dp_configuration parse_a2dp_configuration; @@ -217,8 +198,8 @@ extern struct parse_a2dp_configuration parse_a2dp_configuration; struct read { static size_t return_value; std::function body{ - [](uint8_t* /* p_buf */, uint32_t /* len */) { return return_value; }}; - size_t operator()(uint8_t* p_buf, uint32_t len) { return body(p_buf, len); }; + [](uint8_t* /* p_buf */, uint32_t /* len */) { return return_value; }}; + size_t operator()(uint8_t* p_buf, uint32_t len) { return body(p_buf, len); } }; extern struct read read; @@ -227,18 +208,16 @@ extern struct read read; // Return: void struct set_audio_low_latency_mode_allowed { std::function body{[](bool /* allowed */) {}}; - void operator()(bool allowed) { body(allowed); }; + void operator()(bool allowed) { body(allowed); } }; -extern struct set_audio_low_latency_mode_allowed - set_audio_low_latency_mode_allowed; +extern struct set_audio_low_latency_mode_allowed set_audio_low_latency_mode_allowed; // Name: set_remote_delay // Params: uint16_t delay_report // Return: void struct set_remote_delay { - std::function body{ - [](uint16_t /* delay_report */) {}}; - void operator()(uint16_t delay_report) { body(delay_report); }; + std::function body{[](uint16_t /* delay_report */) {}}; + void operator()(uint16_t delay_report) { body(delay_report); } }; extern struct set_remote_delay set_remote_delay; @@ -248,7 +227,7 @@ extern struct set_remote_delay set_remote_delay; struct setup_codec { static bool return_value; std::function body{[]() { return return_value; }}; - bool operator()() { return body(); }; + bool operator()() { return body(); } }; extern struct setup_codec setup_codec; @@ -257,13 +236,11 @@ extern struct setup_codec setup_codec; // Return: std::optional struct sink_codec_index { static std::optional return_value; - std::function( - const uint8_t* p_codec_info)> - body{[](const uint8_t* /* p_codec_info */) { return return_value; }}; - std::optional operator()( - const uint8_t* p_codec_info) { + std::function(const uint8_t* p_codec_info)> body{ + [](const uint8_t* /* p_codec_info */) { return return_value; }}; + std::optional operator()(const uint8_t* p_codec_info) { return body(p_codec_info); - }; + } }; extern struct sink_codec_index sink_codec_index; @@ -272,13 +249,11 @@ extern struct sink_codec_index sink_codec_index; // Return: std::optional struct source_codec_index { static std::optional return_value; - std::function( - const uint8_t* p_codec_info)> - body{[](const uint8_t* /* p_codec_info */) { return return_value; }}; - std::optional operator()( - const uint8_t* p_codec_info) { + std::function(const uint8_t* p_codec_info)> body{ + [](const uint8_t* /* p_codec_info */) { return return_value; }}; + std::optional operator()(const uint8_t* p_codec_info) { return body(p_codec_info); - }; + } }; extern struct source_codec_index source_codec_index; @@ -287,7 +262,7 @@ extern struct source_codec_index source_codec_index; // Return: void struct start_session { std::function body{[]() {}}; - void operator()() { body(); }; + void operator()() { body(); } }; extern struct start_session start_session; @@ -297,10 +272,8 @@ extern struct start_session start_session; struct supports_codec { static bool return_value; std::function body{ - [](btav_a2dp_codec_index_t /* codec_index */) { return return_value; }}; - bool operator()(btav_a2dp_codec_index_t codec_index) { - return body(codec_index); - }; + [](btav_a2dp_codec_index_t /* codec_index */) { return return_value; }}; + bool operator()(btav_a2dp_codec_index_t codec_index) { return body(codec_index); } }; extern struct supports_codec supports_codec; @@ -309,20 +282,16 @@ extern struct supports_codec supports_codec; // Return: bool struct update_codec_offloading_capabilities { static bool return_value; - std::function& framework_preference, - bool supports_a2dp_hw_offload_v2)> - body{[](const std::vector< - btav_a2dp_codec_config_t>& /* framework_preference */, - bool /*supports_a2dp_hw_offload_v2*/) { return return_value; }}; - bool operator()( - const std::vector& framework_preference, - bool supports_a2dp_hw_offload_v2) { + std::function& framework_preference, + bool supports_a2dp_hw_offload_v2)> + body{[](const std::vector& /* framework_preference */, + bool /*supports_a2dp_hw_offload_v2*/) { return return_value; }}; + bool operator()(const std::vector& framework_preference, + bool supports_a2dp_hw_offload_v2) { return body(framework_preference, supports_a2dp_hw_offload_v2); - }; + } }; -extern struct update_codec_offloading_capabilities - update_codec_offloading_capabilities; +extern struct update_codec_offloading_capabilities update_codec_offloading_capabilities; } // namespace audio_hal_interface_a2dp_encoding } // namespace mock diff --git a/system/test/mock/mock_bluetooth_interface.cc b/system/test/mock/mock_bluetooth_interface.cc index 28d7b3bdc0d..44dfcf279af 100644 --- a/system/test/mock/mock_bluetooth_interface.cc +++ b/system/test/mock/mock_bluetooth_interface.cc @@ -22,60 +22,47 @@ #include "types/raw_address.h" void invoke_adapter_state_changed_cb(bt_state_t /* state */) {} -void invoke_adapter_properties_cb(bt_status_t /* status */, - int /* num_properties */, +void invoke_adapter_properties_cb(bt_status_t /* status */, int /* num_properties */, bt_property_t* /* properties */) {} -void invoke_remote_device_properties_cb(bt_status_t /* status */, - RawAddress /* bd_addr */, - int /* num_properties */, - bt_property_t* /* properties */) {} -void invoke_device_found_cb(int /* num_properties */, - bt_property_t* /* properties */) {} +void invoke_remote_device_properties_cb(bt_status_t /* status */, RawAddress /* bd_addr */, + int /* num_properties */, bt_property_t* /* properties */) { +} +void invoke_device_found_cb(int /* num_properties */, bt_property_t* /* properties */) {} void invoke_discovery_state_changed_cb(bt_discovery_state_t /* state */) {} -void invoke_pin_request_cb(RawAddress /* bd_addr */, bt_bdname_t /* bd_name */, - uint32_t /* cod */, bool /* min_16_digit */) {} -void invoke_ssp_request_cb(RawAddress /* bd_addr */, - bt_ssp_variant_t /* pairing_variant */, +void invoke_pin_request_cb(RawAddress /* bd_addr */, bt_bdname_t /* bd_name */, uint32_t /* cod */, + bool /* min_16_digit */) {} +void invoke_ssp_request_cb(RawAddress /* bd_addr */, bt_ssp_variant_t /* pairing_variant */, uint32_t /* pass_key */) {} -void invoke_oob_data_request_cb(tBT_TRANSPORT /* t */, bool /* valid */, - Octet16 /* c */, Octet16 /* r */, - RawAddress /* raw_address */, +void invoke_oob_data_request_cb(tBT_TRANSPORT /* t */, bool /* valid */, Octet16 /* c */, + Octet16 /* r */, RawAddress /* raw_address */, uint8_t /* address_type */) {} -void invoke_bond_state_changed_cb(bt_status_t /* status */, - RawAddress /* bd_addr */, - bt_bond_state_t /* state */, - int /* fail_reason */) {} +void invoke_bond_state_changed_cb(bt_status_t /* status */, RawAddress /* bd_addr */, + bt_bond_state_t /* state */, int /* fail_reason */) {} void invoke_address_consolidate_cb(RawAddress /* main_bd_addr */, RawAddress /* secondary_bd_addr */) {} void invoke_le_address_associate_cb(RawAddress /* main_bd_addr */, RawAddress /* secondary_bd_addr */) {} -void invoke_acl_state_changed_cb(bt_status_t /* status */, - RawAddress /* bd_addr */, - bt_acl_state_t /* state */, - int /* transport_link_type */, +void invoke_acl_state_changed_cb(bt_status_t /* status */, RawAddress /* bd_addr */, + bt_acl_state_t /* state */, int /* transport_link_type */, bt_hci_error_code_t /* hci_reason */, - bt_conn_direction_t /* direction */, - uint16_t /* acl_handle */) {} + bt_conn_direction_t /* direction */, uint16_t /* acl_handle */) {} void invoke_thread_evt_cb(bt_cb_thread_evt /* event */) {} void invoke_le_test_mode_cb(bt_status_t /* status */, uint16_t /* count */) {} void invoke_energy_info_cb(bt_activity_energy_info /* energy_info */, bt_uid_traffic_t* /* uid_data */) {} -void invoke_link_quality_report_cb(uint64_t /* timestamp */, - int /* report_id */, int /* rssi */, - int /* snr */, - int /* retransmission_count */, +void invoke_link_quality_report_cb(uint64_t /* timestamp */, int /* report_id */, int /* rssi */, + int /* snr */, int /* retransmission_count */, int /* packets_not_receive_count */, int /* negative_acknowledgement_count */) {} void invoke_key_missing_cb(const RawAddress /* bd_addr */) {} static void init_stack(bluetooth::core::CoreInterface* /* interface */) {} -static void start_up_stack_async( - bluetooth::core::CoreInterface* /* interface */, - ProfileStartCallback /* startProfiles */, - ProfileStopCallback /* stopProfiles */) {} +static void start_up_stack_async(bluetooth::core::CoreInterface* /* interface */, + ProfileStartCallback /* startProfiles */, + ProfileStopCallback /* stopProfiles */) {} static void shut_down_stack_async(ProfileStopCallback /* stopProfiles */) {} @@ -87,9 +74,9 @@ static void shut_down_rust_module_async() {} static bool get_stack_is_running() { return true; } -static const stack_manager_t interface = {init_stack, start_up_stack_async, - shut_down_stack_async, clean_up_stack, - start_up_rust_module_async, shut_down_rust_module_async, - get_stack_is_running}; +static const stack_manager_t interface = { + init_stack, start_up_stack_async, shut_down_stack_async, + clean_up_stack, start_up_rust_module_async, shut_down_rust_module_async, + get_stack_is_running}; const stack_manager_t* stack_manager_get_interface() { return &interface; } diff --git a/system/test/mock/mock_bta_ag_api.cc b/system/test/mock/mock_bta_ag_api.cc index 3a65c25dc25..41138e20a15 100644 --- a/system/test/mock/mock_bta_ag_api.cc +++ b/system/test/mock/mock_bta_ag_api.cc @@ -35,8 +35,7 @@ tBTA_STATUS BTA_AgEnable(tBTA_AG_CBACK* /* p_cback */) { return BTA_SUCCESS; } void BTA_AgAudioClose(uint16_t /* handle */) { inc_func_call_count(__func__); } -void BTA_AgAudioOpen(uint16_t /* handle */, - tBTA_AG_PEER_CODEC /* disabled_codecs */) { +void BTA_AgAudioOpen(uint16_t /* handle */, tBTA_AG_PEER_CODEC /* disabled_codecs */) { inc_func_call_count(__func__); } void BTA_AgClose(uint16_t /* handle */) { inc_func_call_count(__func__); } @@ -45,10 +44,8 @@ void BTA_AgDisable() { inc_func_call_count(__func__); } void BTA_AgOpen(uint16_t /* handle */, const RawAddress& /* bd_addr */) { inc_func_call_count(__func__); } -void BTA_AgRegister(tBTA_SERVICE_MASK /* services */, - tBTA_AG_FEAT /* features */, - const std::vector& /* service_names */, - uint8_t /* app_id */) { +void BTA_AgRegister(tBTA_SERVICE_MASK /* services */, tBTA_AG_FEAT /* features */, + const std::vector& /* service_names */, uint8_t /* app_id */) { inc_func_call_count(__func__); } void BTA_AgResult(uint16_t /* handle */, tBTA_AG_RES /* result */, @@ -61,16 +58,13 @@ void BTA_AgSetActiveDevice(const RawAddress& /* active_device_addr */) { void BTA_AgSetCodec(uint16_t /* handle */, tBTA_AG_PEER_CODEC /* codec */) { inc_func_call_count(__func__); } -void BTA_AgSetScoOffloadEnabled(bool /* value */) { - inc_func_call_count(__func__); -} +void BTA_AgSetScoOffloadEnabled(bool /* value */) { inc_func_call_count(__func__); } void BTA_AgSetScoAllowed(bool /* value */) { inc_func_call_count(__func__); } bool is_hfp_aptx_voice_enabled() { inc_func_call_count(__func__); return false; -}; -bt_status_t enable_aptx_swb_codec(bool /* enable */, - RawAddress* /* bd_addr */) { +} +bt_status_t enable_aptx_swb_codec(bool /* enable */, RawAddress* /* bd_addr */) { inc_func_call_count(__func__); return BT_STATUS_SUCCESS; } diff --git a/system/test/mock/mock_bta_ar.cc b/system/test/mock/mock_bta_ar.cc index 4342b3ac84c..ff2ec4368c4 100644 --- a/system/test/mock/mock_bta_ar.cc +++ b/system/test/mock/mock_bta_ar.cc @@ -32,18 +32,14 @@ void bta_ar_avdt_conn(tBTA_SYS_ID /* sys_id */, const RawAddress& /* bd_addr */, } void bta_ar_dereg_avct() { inc_func_call_count(__func__); } void bta_ar_dereg_avdt() { inc_func_call_count(__func__); } -void bta_ar_dereg_avrc(uint16_t /* service_uuid */) { - inc_func_call_count(__func__); -} +void bta_ar_dereg_avrc(uint16_t /* service_uuid */) { inc_func_call_count(__func__); } void bta_ar_init(void) { inc_func_call_count(__func__); } void bta_ar_reg_avct() { inc_func_call_count(__func__); } void bta_ar_reg_avdt(AvdtpRcb* /* p_reg */, tAVDT_CTRL_CBACK* /* p_cback */) { inc_func_call_count(__func__); } -void bta_ar_reg_avrc(uint16_t /* service_uuid */, - const char* /* service_name */, +void bta_ar_reg_avrc(uint16_t /* service_uuid */, const char* /* service_name */, const char* /* provider_name */, uint16_t /* categories */, - bool /* browse_supported */, - uint16_t /* profile_version */) { + bool /* browse_supported */, uint16_t /* profile_version */) { inc_func_call_count(__func__); } diff --git a/system/test/mock/mock_bta_av_api.cc b/system/test/mock/mock_bta_av_api.cc index 518e4f6d047..b8c43a10dd1 100644 --- a/system/test/mock/mock_bta_av_api.cc +++ b/system/test/mock/mock_bta_av_api.cc @@ -96,13 +96,11 @@ void BTA_AvEnable(tBTA_AV_FEAT features, tBTA_AV_CBACK* p_cback) { inc_func_call_count(__func__); test::mock::bta_av_api::BTA_AvEnable(features, p_cback); } -void BTA_AvMetaCmd(uint8_t rc_handle, uint8_t label, tBTA_AV_CMD cmd_code, - BT_HDR* p_pkt) { +void BTA_AvMetaCmd(uint8_t rc_handle, uint8_t label, tBTA_AV_CMD cmd_code, BT_HDR* p_pkt) { inc_func_call_count(__func__); test::mock::bta_av_api::BTA_AvMetaCmd(rc_handle, label, cmd_code, p_pkt); } -void BTA_AvMetaRsp(uint8_t rc_handle, uint8_t label, tBTA_AV_CODE rsp_code, - BT_HDR* p_pkt) { +void BTA_AvMetaRsp(uint8_t rc_handle, uint8_t label, tBTA_AV_CODE rsp_code, BT_HDR* p_pkt) { inc_func_call_count(__func__); test::mock::bta_av_api::BTA_AvMetaRsp(rc_handle, label, rsp_code, p_pkt); } @@ -110,8 +108,7 @@ void BTA_AvOffloadStart(tBTA_AV_HNDL hndl) { inc_func_call_count(__func__); test::mock::bta_av_api::BTA_AvOffloadStart(hndl); } -void BTA_AvOpen(const RawAddress& bd_addr, tBTA_AV_HNDL handle, bool use_rc, - uint16_t uuid) { +void BTA_AvOpen(const RawAddress& bd_addr, tBTA_AV_HNDL handle, bool use_rc, uint16_t uuid) { inc_func_call_count(__func__); test::mock::bta_av_api::BTA_AvOpen(bd_addr, handle, use_rc, uuid); } @@ -123,36 +120,30 @@ void BTA_AvProtectReq(tBTA_AV_HNDL hndl, uint8_t* p_data, uint16_t len) { inc_func_call_count(__func__); test::mock::bta_av_api::BTA_AvProtectReq(hndl, p_data, len); } -void BTA_AvProtectRsp(tBTA_AV_HNDL hndl, uint8_t error_code, uint8_t* p_data, - uint16_t len) { +void BTA_AvProtectRsp(tBTA_AV_HNDL hndl, uint8_t error_code, uint8_t* p_data, uint16_t len) { inc_func_call_count(__func__); test::mock::bta_av_api::BTA_AvProtectRsp(hndl, error_code, p_data, len); } -void BTA_AvReconfig(tBTA_AV_HNDL hndl, bool suspend, uint8_t sep_info_idx, - uint8_t* p_codec_info, uint8_t num_protect, - const uint8_t* p_protect_info) { +void BTA_AvReconfig(tBTA_AV_HNDL hndl, bool suspend, uint8_t sep_info_idx, uint8_t* p_codec_info, + uint8_t num_protect, const uint8_t* p_protect_info) { inc_func_call_count(__func__); - test::mock::bta_av_api::BTA_AvReconfig( - hndl, suspend, sep_info_idx, p_codec_info, num_protect, p_protect_info); + test::mock::bta_av_api::BTA_AvReconfig(hndl, suspend, sep_info_idx, p_codec_info, num_protect, + p_protect_info); } -void BTA_AvRegister(tBTA_AV_CHNL chnl, const char* p_service_name, - uint8_t app_id, tBTA_AV_SINK_DATA_CBACK* p_sink_data_cback, - uint16_t service_uuid) { +void BTA_AvRegister(tBTA_AV_CHNL chnl, const char* p_service_name, uint8_t app_id, + tBTA_AV_SINK_DATA_CBACK* p_sink_data_cback, uint16_t service_uuid) { inc_func_call_count(__func__); - test::mock::bta_av_api::BTA_AvRegister(chnl, p_service_name, app_id, - p_sink_data_cback, service_uuid); + test::mock::bta_av_api::BTA_AvRegister(chnl, p_service_name, app_id, p_sink_data_cback, + service_uuid); } -void BTA_AvRemoteCmd(uint8_t rc_handle, uint8_t label, tBTA_AV_RC rc_id, - tBTA_AV_STATE key_state) { +void BTA_AvRemoteCmd(uint8_t rc_handle, uint8_t label, tBTA_AV_RC rc_id, tBTA_AV_STATE key_state) { inc_func_call_count(__func__); test::mock::bta_av_api::BTA_AvRemoteCmd(rc_handle, label, rc_id, key_state); } -void BTA_AvRemoteVendorUniqueCmd(uint8_t rc_handle, uint8_t label, - tBTA_AV_STATE key_state, uint8_t* p_msg, - uint8_t buf_len) { +void BTA_AvRemoteVendorUniqueCmd(uint8_t rc_handle, uint8_t label, tBTA_AV_STATE key_state, + uint8_t* p_msg, uint8_t buf_len) { inc_func_call_count(__func__); - test::mock::bta_av_api::BTA_AvRemoteVendorUniqueCmd( - rc_handle, label, key_state, p_msg, buf_len); + test::mock::bta_av_api::BTA_AvRemoteVendorUniqueCmd(rc_handle, label, key_state, p_msg, buf_len); } void BTA_AvSetLatency(tBTA_AV_HNDL handle, bool is_low_latency) { inc_func_call_count(__func__); @@ -170,17 +161,15 @@ void BTA_AvStop(tBTA_AV_HNDL handle, bool suspend) { inc_func_call_count(__func__); test::mock::bta_av_api::BTA_AvStop(handle, suspend); } -void BTA_AvVendorCmd(uint8_t rc_handle, uint8_t label, tBTA_AV_CODE cmd_code, - uint8_t* p_data, uint16_t len) { +void BTA_AvVendorCmd(uint8_t rc_handle, uint8_t label, tBTA_AV_CODE cmd_code, uint8_t* p_data, + uint16_t len) { inc_func_call_count(__func__); - test::mock::bta_av_api::BTA_AvVendorCmd(rc_handle, label, cmd_code, p_data, - len); + test::mock::bta_av_api::BTA_AvVendorCmd(rc_handle, label, cmd_code, p_data, len); } -void BTA_AvVendorRsp(uint8_t rc_handle, uint8_t label, tBTA_AV_CODE rsp_code, - uint8_t* p_data, uint16_t len, uint32_t company_id) { +void BTA_AvVendorRsp(uint8_t rc_handle, uint8_t label, tBTA_AV_CODE rsp_code, uint8_t* p_data, + uint16_t len, uint32_t company_id) { inc_func_call_count(__func__); - test::mock::bta_av_api::BTA_AvVendorRsp(rc_handle, label, rsp_code, p_data, - len, company_id); + test::mock::bta_av_api::BTA_AvVendorRsp(rc_handle, label, rsp_code, p_data, len, company_id); } // Mocked functions complete // END mockcify generation diff --git a/system/test/mock/mock_bta_av_api.h b/system/test/mock/mock_bta_av_api.h index 15ed7ee4f00..f6319691c0a 100644 --- a/system/test/mock/mock_bta_av_api.h +++ b/system/test/mock/mock_bta_av_api.h @@ -53,9 +53,8 @@ namespace bta_av_api { // Params: tBTA_AV_HNDL handle // Return: void struct BTA_AvClose { - std::function body{ - [](tBTA_AV_HNDL /* handle */) {}}; - void operator()(tBTA_AV_HNDL handle) { body(handle); }; + std::function body{[](tBTA_AV_HNDL /* handle */) {}}; + void operator()(tBTA_AV_HNDL handle) { body(handle); } }; extern struct BTA_AvClose BTA_AvClose; @@ -64,7 +63,7 @@ extern struct BTA_AvClose BTA_AvClose; // Return: void struct BTA_AvCloseRc { std::function body{[](uint8_t /* rc_handle */) {}}; - void operator()(uint8_t rc_handle) { body(rc_handle); }; + void operator()(uint8_t rc_handle) { body(rc_handle); } }; extern struct BTA_AvCloseRc BTA_AvCloseRc; @@ -73,7 +72,7 @@ extern struct BTA_AvCloseRc BTA_AvCloseRc; // Return: void struct BTA_AvDeregister { std::function body{[](tBTA_AV_HNDL /* hndl */) {}}; - void operator()(tBTA_AV_HNDL hndl) { body(hndl); }; + void operator()(tBTA_AV_HNDL hndl) { body(hndl); } }; extern struct BTA_AvDeregister BTA_AvDeregister; @@ -82,7 +81,7 @@ extern struct BTA_AvDeregister BTA_AvDeregister; // Return: void struct BTA_AvDisable { std::function body{[](void) {}}; - void operator()(void) { body(); }; + void operator()(void) { body(); } }; extern struct BTA_AvDisable BTA_AvDisable; @@ -90,9 +89,8 @@ extern struct BTA_AvDisable BTA_AvDisable; // Params: tBTA_AV_HNDL handle // Return: void struct BTA_AvDisconnect { - std::function body{ - [](tBTA_AV_HNDL /* handle */) {}}; - void operator()(tBTA_AV_HNDL handle) { body(handle); }; + std::function body{[](tBTA_AV_HNDL /* handle */) {}}; + void operator()(tBTA_AV_HNDL handle) { body(handle); } }; extern struct BTA_AvDisconnect BTA_AvDisconnect; @@ -101,10 +99,8 @@ extern struct BTA_AvDisconnect BTA_AvDisconnect; // Return: void struct BTA_AvEnable { std::function body{ - [](tBTA_AV_FEAT /* features */, tBTA_AV_CBACK* /* p_cback */) {}}; - void operator()(tBTA_AV_FEAT features, tBTA_AV_CBACK* p_cback) { - body(features, p_cback); - }; + [](tBTA_AV_FEAT /* features */, tBTA_AV_CBACK* /* p_cback */) {}}; + void operator()(tBTA_AV_FEAT features, tBTA_AV_CBACK* p_cback) { body(features, p_cback); } }; extern struct BTA_AvEnable BTA_AvEnable; @@ -112,14 +108,12 @@ extern struct BTA_AvEnable BTA_AvEnable; // Params: uint8_t rc_handle, uint8_t label, tBTA_AV_CMD cmd_code, BT_HDR* p_pkt // Return: void struct BTA_AvMetaCmd { - std::function - body{[](uint8_t /* rc_handle */, uint8_t /* label */, - tBTA_AV_CMD /* cmd_code */, BT_HDR* /* p_pkt */) {}}; - void operator()(uint8_t rc_handle, uint8_t label, tBTA_AV_CMD cmd_code, - BT_HDR* p_pkt) { + std::function body{ + [](uint8_t /* rc_handle */, uint8_t /* label */, tBTA_AV_CMD /* cmd_code */, + BT_HDR* /* p_pkt */) {}}; + void operator()(uint8_t rc_handle, uint8_t label, tBTA_AV_CMD cmd_code, BT_HDR* p_pkt) { body(rc_handle, label, cmd_code, p_pkt); - }; + } }; extern struct BTA_AvMetaCmd BTA_AvMetaCmd; @@ -127,14 +121,12 @@ extern struct BTA_AvMetaCmd BTA_AvMetaCmd; // Params: uint8_t rc_handle, uint8_t label, tBTA_AV_CODE rsp_code, BT_HDR* // p_pkt Return: void struct BTA_AvMetaRsp { - std::function - body{[](uint8_t /* rc_handle */, uint8_t /* label */, - tBTA_AV_CODE /* rsp_code */, BT_HDR* /* p_pkt */) {}}; - void operator()(uint8_t rc_handle, uint8_t label, tBTA_AV_CODE rsp_code, - BT_HDR* p_pkt) { + std::function body{ + [](uint8_t /* rc_handle */, uint8_t /* label */, tBTA_AV_CODE /* rsp_code */, + BT_HDR* /* p_pkt */) {}}; + void operator()(uint8_t rc_handle, uint8_t label, tBTA_AV_CODE rsp_code, BT_HDR* p_pkt) { body(rc_handle, label, rsp_code, p_pkt); - }; + } }; extern struct BTA_AvMetaRsp BTA_AvMetaRsp; @@ -143,7 +135,7 @@ extern struct BTA_AvMetaRsp BTA_AvMetaRsp; // Return: void struct BTA_AvOffloadStart { std::function body{[](tBTA_AV_HNDL /* hndl */) {}}; - void operator()(tBTA_AV_HNDL hndl) { body(hndl); }; + void operator()(tBTA_AV_HNDL hndl) { body(hndl); } }; extern struct BTA_AvOffloadStart BTA_AvOffloadStart; @@ -151,14 +143,12 @@ extern struct BTA_AvOffloadStart BTA_AvOffloadStart; // Params: const RawAddress& bd_addr, tBTA_AV_HNDL handle, bool use_rc, uint16_t // uuid Return: void struct BTA_AvOpen { - std::function - body{[](const RawAddress& /* bd_addr */, tBTA_AV_HNDL /* handle */, - bool /* use_rc */, uint16_t /* uuid */) {}}; - void operator()(const RawAddress& bd_addr, tBTA_AV_HNDL handle, bool use_rc, - uint16_t uuid) { + std::function + body{[](const RawAddress& /* bd_addr */, tBTA_AV_HNDL /* handle */, bool /* use_rc */, + uint16_t /* uuid */) {}}; + void operator()(const RawAddress& bd_addr, tBTA_AV_HNDL handle, bool use_rc, uint16_t uuid) { body(bd_addr, handle, use_rc, uuid); - }; + } }; extern struct BTA_AvOpen BTA_AvOpen; @@ -166,9 +156,8 @@ extern struct BTA_AvOpen BTA_AvOpen; // Params: tBTA_AV_HNDL handle // Return: void struct BTA_AvOpenRc { - std::function body{ - [](tBTA_AV_HNDL /* handle */) {}}; - void operator()(tBTA_AV_HNDL handle) { body(handle); }; + std::function body{[](tBTA_AV_HNDL /* handle */) {}}; + void operator()(tBTA_AV_HNDL handle) { body(handle); } }; extern struct BTA_AvOpenRc BTA_AvOpenRc; @@ -177,11 +166,8 @@ extern struct BTA_AvOpenRc BTA_AvOpenRc; // Return: void struct BTA_AvProtectReq { std::function body{ - [](tBTA_AV_HNDL /* hndl */, uint8_t* /* p_data */, uint16_t /* len */) { - }}; - void operator()(tBTA_AV_HNDL hndl, uint8_t* p_data, uint16_t len) { - body(hndl, p_data, len); - }; + [](tBTA_AV_HNDL /* hndl */, uint8_t* /* p_data */, uint16_t /* len */) {}}; + void operator()(tBTA_AV_HNDL hndl, uint8_t* p_data, uint16_t len) { body(hndl, p_data, len); } }; extern struct BTA_AvProtectReq BTA_AvProtectReq; @@ -189,14 +175,12 @@ extern struct BTA_AvProtectReq BTA_AvProtectReq; // Params: tBTA_AV_HNDL hndl, uint8_t error_code, uint8_t* p_data, uint16_t len // Return: void struct BTA_AvProtectRsp { - std::function - body{[](tBTA_AV_HNDL /* hndl */, uint8_t /* error_code */, - uint8_t* /* p_data */, uint16_t /* len */) {}}; - void operator()(tBTA_AV_HNDL hndl, uint8_t error_code, uint8_t* p_data, - uint16_t len) { + std::function body{ + [](tBTA_AV_HNDL /* hndl */, uint8_t /* error_code */, uint8_t* /* p_data */, + uint16_t /* len */) {}}; + void operator()(tBTA_AV_HNDL hndl, uint8_t error_code, uint8_t* p_data, uint16_t len) { body(hndl, error_code, p_data, len); - }; + } }; extern struct BTA_AvProtectRsp BTA_AvProtectRsp; @@ -204,19 +188,15 @@ extern struct BTA_AvProtectRsp BTA_AvProtectRsp; // Params: tBTA_AV_HNDL hndl, bool suspend, uint8_t sep_info_idx, uint8_t* // p_codec_info, uint8_t num_protect, const uint8_t* p_protect_info Return: void struct BTA_AvReconfig { - std::function - body{[](tBTA_AV_HNDL /* hndl */, bool /* suspend */, - uint8_t /* sep_info_idx */, uint8_t* /* p_codec_info */, - uint8_t /* num_protect */, - const uint8_t* /* p_protect_info */) {}}; - void operator()(tBTA_AV_HNDL hndl, bool suspend, uint8_t sep_info_idx, - uint8_t* p_codec_info, uint8_t num_protect, - const uint8_t* p_protect_info) { - body(hndl, suspend, sep_info_idx, p_codec_info, num_protect, - p_protect_info); - }; + std::function + body{[](tBTA_AV_HNDL /* hndl */, bool /* suspend */, uint8_t /* sep_info_idx */, + uint8_t* /* p_codec_info */, uint8_t /* num_protect */, + const uint8_t* /* p_protect_info */) {}}; + void operator()(tBTA_AV_HNDL hndl, bool suspend, uint8_t sep_info_idx, uint8_t* p_codec_info, + uint8_t num_protect, const uint8_t* p_protect_info) { + body(hndl, suspend, sep_info_idx, p_codec_info, num_protect, p_protect_info); + } }; extern struct BTA_AvReconfig BTA_AvReconfig; @@ -225,18 +205,15 @@ extern struct BTA_AvReconfig BTA_AvReconfig; // tBTA_AV_SINK_DATA_CBACK* p_sink_data_cback, uint16_t service_uuid Return: // void struct BTA_AvRegister { - std::function - body{[](tBTA_AV_CHNL /* chnl */, const char* /* p_service_name */, - uint8_t /* app_id */, - tBTA_AV_SINK_DATA_CBACK* /* p_sink_data_cback */, - uint16_t /* service_uuid */) {}}; + std::function + body{[](tBTA_AV_CHNL /* chnl */, const char* /* p_service_name */, uint8_t /* app_id */, + tBTA_AV_SINK_DATA_CBACK* /* p_sink_data_cback */, + uint16_t /* service_uuid */) {}}; void operator()(tBTA_AV_CHNL chnl, const char* p_service_name, uint8_t app_id, - tBTA_AV_SINK_DATA_CBACK* p_sink_data_cback, - uint16_t service_uuid) { + tBTA_AV_SINK_DATA_CBACK* p_sink_data_cback, uint16_t service_uuid) { body(chnl, p_service_name, app_id, p_sink_data_cback, service_uuid); - }; + } }; extern struct BTA_AvRegister BTA_AvRegister; @@ -244,14 +221,12 @@ extern struct BTA_AvRegister BTA_AvRegister; // Params: uint8_t rc_handle, uint8_t label, tBTA_AV_RC rc_id, tBTA_AV_STATE // key_state Return: void struct BTA_AvRemoteCmd { - std::function - body{[](uint8_t /* rc_handle */, uint8_t /* label */, - tBTA_AV_RC /* rc_id */, tBTA_AV_STATE /* key_state */) {}}; - void operator()(uint8_t rc_handle, uint8_t label, tBTA_AV_RC rc_id, - tBTA_AV_STATE key_state) { + std::function + body{[](uint8_t /* rc_handle */, uint8_t /* label */, tBTA_AV_RC /* rc_id */, + tBTA_AV_STATE /* key_state */) {}}; + void operator()(uint8_t rc_handle, uint8_t label, tBTA_AV_RC rc_id, tBTA_AV_STATE key_state) { body(rc_handle, label, rc_id, key_state); - }; + } }; extern struct BTA_AvRemoteCmd BTA_AvRemoteCmd; @@ -259,15 +234,14 @@ extern struct BTA_AvRemoteCmd BTA_AvRemoteCmd; // Params: uint8_t rc_handle, uint8_t label, tBTA_AV_STATE key_state, uint8_t* // p_msg, uint8_t buf_len Return: void struct BTA_AvRemoteVendorUniqueCmd { - std::function - body{[](uint8_t /* rc_handle */, uint8_t /* label */, - tBTA_AV_STATE /* key_state */, uint8_t* /* p_msg */, - uint8_t /* buf_len */) {}}; - void operator()(uint8_t rc_handle, uint8_t label, tBTA_AV_STATE key_state, - uint8_t* p_msg, uint8_t buf_len) { + std::function + body{[](uint8_t /* rc_handle */, uint8_t /* label */, tBTA_AV_STATE /* key_state */, + uint8_t* /* p_msg */, uint8_t /* buf_len */) {}}; + void operator()(uint8_t rc_handle, uint8_t label, tBTA_AV_STATE key_state, uint8_t* p_msg, + uint8_t buf_len) { body(rc_handle, label, key_state, p_msg, buf_len); - }; + } }; extern struct BTA_AvRemoteVendorUniqueCmd BTA_AvRemoteVendorUniqueCmd; @@ -276,10 +250,8 @@ extern struct BTA_AvRemoteVendorUniqueCmd BTA_AvRemoteVendorUniqueCmd; // Return: void struct BTA_AvSetLatency { std::function body{ - [](tBTA_AV_HNDL /* handle */, bool /* is_low_latency */) {}}; - void operator()(tBTA_AV_HNDL handle, bool is_low_latency) { - body(handle, is_low_latency); - }; + [](tBTA_AV_HNDL /* handle */, bool /* is_low_latency */) {}}; + void operator()(tBTA_AV_HNDL handle, bool is_low_latency) { body(handle, is_low_latency); } }; extern struct BTA_AvSetLatency BTA_AvSetLatency; @@ -288,8 +260,8 @@ extern struct BTA_AvSetLatency BTA_AvSetLatency; // Return: void struct BTA_AvSetPeerSep { std::function body{ - [](const RawAddress& /* bdaddr */, uint8_t /* sep */) {}}; - void operator()(const RawAddress& bdaddr, uint8_t sep) { body(bdaddr, sep); }; + [](const RawAddress& /* bdaddr */, uint8_t /* sep */) {}}; + void operator()(const RawAddress& bdaddr, uint8_t sep) { body(bdaddr, sep); } }; extern struct BTA_AvSetPeerSep BTA_AvSetPeerSep; @@ -298,10 +270,8 @@ extern struct BTA_AvSetPeerSep BTA_AvSetPeerSep; // Return: void struct BTA_AvStart { std::function body{ - [](tBTA_AV_HNDL /* handle */, bool /* use_latency_mode */) {}}; - void operator()(tBTA_AV_HNDL handle, bool use_latency_mode) { - body(handle, use_latency_mode); - }; + [](tBTA_AV_HNDL /* handle */, bool /* use_latency_mode */) {}}; + void operator()(tBTA_AV_HNDL handle, bool use_latency_mode) { body(handle, use_latency_mode); } }; extern struct BTA_AvStart BTA_AvStart; @@ -310,8 +280,8 @@ extern struct BTA_AvStart BTA_AvStart; // Return: void struct BTA_AvStop { std::function body{ - [](tBTA_AV_HNDL /* handle */, bool /* suspend */) {}}; - void operator()(tBTA_AV_HNDL handle, bool suspend) { body(handle, suspend); }; + [](tBTA_AV_HNDL /* handle */, bool /* suspend */) {}}; + void operator()(tBTA_AV_HNDL handle, bool suspend) { body(handle, suspend); } }; extern struct BTA_AvStop BTA_AvStop; @@ -319,15 +289,14 @@ extern struct BTA_AvStop BTA_AvStop; // Params: uint8_t rc_handle, uint8_t label, tBTA_AV_CODE cmd_code, uint8_t* // p_data, uint16_t len Return: void struct BTA_AvVendorCmd { - std::function - body{[](uint8_t /* rc_handle */, uint8_t /* label */, - tBTA_AV_CODE /* cmd_code */, uint8_t* /* p_data */, - uint16_t /* len */) {}}; - void operator()(uint8_t rc_handle, uint8_t label, tBTA_AV_CODE cmd_code, - uint8_t* p_data, uint16_t len) { + std::function + body{[](uint8_t /* rc_handle */, uint8_t /* label */, tBTA_AV_CODE /* cmd_code */, + uint8_t* /* p_data */, uint16_t /* len */) {}}; + void operator()(uint8_t rc_handle, uint8_t label, tBTA_AV_CODE cmd_code, uint8_t* p_data, + uint16_t len) { body(rc_handle, label, cmd_code, p_data, len); - }; + } }; extern struct BTA_AvVendorCmd BTA_AvVendorCmd; @@ -335,15 +304,14 @@ extern struct BTA_AvVendorCmd BTA_AvVendorCmd; // Params: uint8_t rc_handle, uint8_t label, tBTA_AV_CODE rsp_code, uint8_t* // p_data, uint16_t len, uint32_t company_id Return: void struct BTA_AvVendorRsp { - std::function - body{[](uint8_t /* rc_handle */, uint8_t /* label */, - tBTA_AV_CODE /* rsp_code */, uint8_t* /* p_data */, - uint16_t /* len */, uint32_t /* company_id */) {}}; - void operator()(uint8_t rc_handle, uint8_t label, tBTA_AV_CODE rsp_code, - uint8_t* p_data, uint16_t len, uint32_t company_id) { + std::function + body{[](uint8_t /* rc_handle */, uint8_t /* label */, tBTA_AV_CODE /* rsp_code */, + uint8_t* /* p_data */, uint16_t /* len */, uint32_t /* company_id */) {}}; + void operator()(uint8_t rc_handle, uint8_t label, tBTA_AV_CODE rsp_code, uint8_t* p_data, + uint16_t len, uint32_t company_id) { body(rc_handle, label, rsp_code, p_data, len, company_id); - }; + } }; extern struct BTA_AvVendorRsp BTA_AvVendorRsp; diff --git a/system/test/mock/mock_bta_av_ci.cc b/system/test/mock/mock_bta_av_ci.cc index 811230ccf33..83a2c2c533e 100644 --- a/system/test/mock/mock_bta_av_ci.cc +++ b/system/test/mock/mock_bta_av_ci.cc @@ -22,12 +22,9 @@ #include "bta/include/bta_av_api.h" #include "test/common/mock_functions.h" -void bta_av_ci_setconfig(tBTA_AV_HNDL /* bta_av_handle */, - uint8_t /* err_code */, uint8_t /* category */, - uint8_t /* num_seid */, uint8_t* /* p_seid */, +void bta_av_ci_setconfig(tBTA_AV_HNDL /* bta_av_handle */, uint8_t /* err_code */, + uint8_t /* category */, uint8_t /* num_seid */, uint8_t* /* p_seid */, bool /* recfg_needed */, uint8_t /* avdt_handle */) { inc_func_call_count(__func__); } -void bta_av_ci_src_data_ready(tBTA_AV_CHNL /* chnl */) { - inc_func_call_count(__func__); -} +void bta_av_ci_src_data_ready(tBTA_AV_CHNL /* chnl */) { inc_func_call_count(__func__); } diff --git a/system/test/mock/mock_bta_av_main.cc b/system/test/mock/mock_bta_av_main.cc index 1dbc0bfa447..d92f77a5fe0 100644 --- a/system/test/mock/mock_bta_av_main.cc +++ b/system/test/mock/mock_bta_av_main.cc @@ -58,23 +58,17 @@ tBTA_AV_SCB* bta_av_hndl_to_scb(uint16_t /* handle */) { inc_func_call_count(__func__); return nullptr; } -void bta_av_api_deregister(tBTA_AV_DATA* /* p_data */) { - inc_func_call_count(__func__); -} -void bta_av_conn_cback(uint8_t /* handle */, const RawAddress& /* bd_addr */, - uint8_t /* event */, tAVDT_CTRL* /* p_data */, - uint8_t /* scb_index */) { +void bta_av_api_deregister(tBTA_AV_DATA* /* p_data */) { inc_func_call_count(__func__); } +void bta_av_conn_cback(uint8_t /* handle */, const RawAddress& /* bd_addr */, uint8_t /* event */, + tAVDT_CTRL* /* p_data */, uint8_t /* scb_index */) { inc_func_call_count(__func__); } void bta_av_dup_audio_buf(tBTA_AV_SCB* /* p_scb */, BT_HDR* /* p_buf */) { inc_func_call_count(__func__); } -void bta_av_free_scb(tBTA_AV_SCB* /* p_scb */) { - inc_func_call_count(__func__); -} +void bta_av_free_scb(tBTA_AV_SCB* /* p_scb */) { inc_func_call_count(__func__); } void bta_av_restore_switch(void) { inc_func_call_count(__func__); } -void bta_av_sm_execute(tBTA_AV_CB* /* p_cb */, uint16_t /* event */, - tBTA_AV_DATA* /* p_data */) { +void bta_av_sm_execute(tBTA_AV_CB* /* p_cb */, uint16_t /* event */, tBTA_AV_DATA* /* p_data */) { inc_func_call_count(__func__); } void bta_debug_av_dump(int /* fd */) { inc_func_call_count(__func__); } @@ -82,6 +76,4 @@ void tBTA_AV_SCB::OnConnected(const RawAddress& /* peer_address */) { inc_func_call_count(__func__); } void tBTA_AV_SCB::OnDisconnected() { inc_func_call_count(__func__); } -void tBTA_AV_SCB::SetAvdtpVersion(uint16_t /* avdtp_version */) { - inc_func_call_count(__func__); -} +void tBTA_AV_SCB::SetAvdtpVersion(uint16_t /* avdtp_version */) { inc_func_call_count(__func__); } diff --git a/system/test/mock/mock_bta_csis.cc b/system/test/mock/mock_bta_csis.cc index d7e477aa4c6..2b84d14bab7 100644 --- a/system/test/mock/mock_bta_csis.cc +++ b/system/test/mock/mock_bta_csis.cc @@ -28,8 +28,7 @@ void CsisClient::AddFromStorage(const RawAddress& /* addr */, const std::vector& /* in */) { inc_func_call_count(__func__); } -bool CsisClient::GetForStorage(const RawAddress& /* addr */, - std::vector& /* out */) { +bool CsisClient::GetForStorage(const RawAddress& /* addr */, std::vector& /* out */) { inc_func_call_count(__func__); return false; } @@ -42,8 +41,7 @@ bool CsisClient::IsCsisClientRunning() { inc_func_call_count(__func__); return false; } -void CsisClient::Initialize(CsisClientCallbacks* /* callbacks */, - base::Closure /* initCb */) { +void CsisClient::Initialize(CsisClientCallbacks* /* callbacks */, base::Closure /* initCb */) { inc_func_call_count(__func__); } void CsisClient::DebugDump(int /* fd */) { inc_func_call_count(__func__); } diff --git a/system/test/mock/mock_bta_dm_act.cc b/system/test/mock/mock_bta_dm_act.cc index 51fd7de0974..601b70cacc1 100644 --- a/system/test/mock/mock_bta_dm_act.cc +++ b/system/test/mock/mock_bta_dm_act.cc @@ -40,8 +40,7 @@ struct BTA_DmSetVisibility BTA_DmSetVisibility; struct BTA_dm_acl_down BTA_dm_acl_down; struct BTA_dm_acl_up BTA_dm_acl_up; struct BTA_dm_acl_up_failed BTA_dm_acl_up_failed; -struct BTA_dm_notify_remote_features_complete - BTA_dm_notify_remote_features_complete; +struct BTA_dm_notify_remote_features_complete BTA_dm_notify_remote_features_complete; struct BTA_dm_on_hw_off BTA_dm_on_hw_off; struct BTA_dm_on_hw_on BTA_dm_on_hw_on; struct BTA_dm_report_role_change BTA_dm_report_role_change; @@ -89,8 +88,7 @@ void BTA_dm_acl_down(const RawAddress bd_addr, tBT_TRANSPORT transport) { inc_func_call_count(__func__); test::mock::bta_dm_act::BTA_dm_acl_down(bd_addr, transport); } -void BTA_dm_acl_up(const RawAddress bd_addr, tBT_TRANSPORT transport, - uint16_t acl_handle) { +void BTA_dm_acl_up(const RawAddress bd_addr, tBT_TRANSPORT transport, uint16_t acl_handle) { inc_func_call_count(__func__); test::mock::bta_dm_act::BTA_dm_acl_up(bd_addr, transport, acl_handle); } @@ -114,8 +112,7 @@ void BTA_dm_on_hw_on() { void BTA_dm_report_role_change(const RawAddress bd_addr, tHCI_ROLE new_role, tHCI_STATUS hci_status) { inc_func_call_count(__func__); - test::mock::bta_dm_act::BTA_dm_report_role_change(bd_addr, new_role, - hci_status); + test::mock::bta_dm_act::BTA_dm_report_role_change(bd_addr, new_role, hci_status); } void bta_dm_add_ble_device(const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type, tBT_DEVICE_TYPE dev_type) { @@ -139,13 +136,11 @@ void bta_dm_ble_csis_observe(bool observe, tBTA_DM_SEARCH_CBACK* p_cback) { inc_func_call_count(__func__); test::mock::bta_dm_act::bta_dm_ble_csis_observe(observe, p_cback); } -void bta_dm_ble_get_energy_info( - tBTA_BLE_ENERGY_INFO_CBACK* p_energy_info_cback) { +void bta_dm_ble_get_energy_info(tBTA_BLE_ENERGY_INFO_CBACK* p_energy_info_cback) { inc_func_call_count(__func__); test::mock::bta_dm_act::bta_dm_ble_get_energy_info(p_energy_info_cback); } -void bta_dm_ble_passkey_reply(const RawAddress& bd_addr, bool accept, - uint32_t passkey) { +void bta_dm_ble_passkey_reply(const RawAddress& bd_addr, bool accept, uint32_t passkey) { inc_func_call_count(__func__); test::mock::bta_dm_act::bta_dm_ble_passkey_reply(bd_addr, accept, passkey); } @@ -153,32 +148,28 @@ void bta_dm_ble_scan(bool start, uint8_t duration_sec) { inc_func_call_count(__func__); test::mock::bta_dm_act::bta_dm_ble_scan(start, duration_sec); } -void bta_dm_ble_set_conn_params(const RawAddress& bd_addr, - uint16_t conn_int_min, uint16_t conn_int_max, - uint16_t peripheral_latency, +void bta_dm_ble_set_conn_params(const RawAddress& bd_addr, uint16_t conn_int_min, + uint16_t conn_int_max, uint16_t peripheral_latency, uint16_t supervision_tout) { inc_func_call_count(__func__); - test::mock::bta_dm_act::bta_dm_ble_set_conn_params( - bd_addr, conn_int_min, conn_int_max, peripheral_latency, - supervision_tout); + test::mock::bta_dm_act::bta_dm_ble_set_conn_params(bd_addr, conn_int_min, conn_int_max, + peripheral_latency, supervision_tout); } void bta_dm_ble_set_data_length(const RawAddress& bd_addr) { inc_func_call_count(__func__); test::mock::bta_dm_act::bta_dm_ble_set_data_length(bd_addr); } -void bta_dm_ble_update_conn_params(const RawAddress& bd_addr, uint16_t min_int, - uint16_t max_int, uint16_t latency, - uint16_t timeout, uint16_t min_ce_len, +void bta_dm_ble_update_conn_params(const RawAddress& bd_addr, uint16_t min_int, uint16_t max_int, + uint16_t latency, uint16_t timeout, uint16_t min_ce_len, uint16_t max_ce_len) { inc_func_call_count(__func__); - test::mock::bta_dm_act::bta_dm_ble_update_conn_params( - bd_addr, min_int, max_int, latency, timeout, min_ce_len, max_ce_len); + test::mock::bta_dm_act::bta_dm_ble_update_conn_params(bd_addr, min_int, max_int, latency, timeout, + min_ce_len, max_ce_len); } -void bta_dm_bond(const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type, - tBT_TRANSPORT transport, tBT_DEVICE_TYPE device_type) { +void bta_dm_bond(const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type, tBT_TRANSPORT transport, + tBT_DEVICE_TYPE device_type) { inc_func_call_count(__func__); - test::mock::bta_dm_act::bta_dm_bond(bd_addr, addr_type, transport, - device_type); + test::mock::bta_dm_act::bta_dm_bond(bd_addr, addr_type, transport, device_type); } void bta_dm_bond_cancel(const RawAddress& bd_addr) { inc_func_call_count(__func__); @@ -212,11 +203,10 @@ void bta_dm_enable(tBTA_DM_SEC_CBACK* p_sec_cback) { inc_func_call_count(__func__); test::mock::bta_dm_act::bta_dm_enable(p_sec_cback); } -void bta_dm_encrypt_cback(const RawAddress* bd_addr, tBT_TRANSPORT transport, - void* p_ref_data, tBTM_STATUS result) { +void bta_dm_encrypt_cback(const RawAddress* bd_addr, tBT_TRANSPORT transport, void* p_ref_data, + tBTM_STATUS result) { inc_func_call_count(__func__); - test::mock::bta_dm_act::bta_dm_encrypt_cback(bd_addr, transport, p_ref_data, - result); + test::mock::bta_dm_act::bta_dm_encrypt_cback(bd_addr, transport, p_ref_data, result); } bool bta_dm_is_search_request_queued() { inc_func_call_count(__func__); @@ -248,11 +238,9 @@ void bta_dm_set_dev_name(const std::vector& name) { test::mock::bta_dm_act::bta_dm_set_dev_name(name); } void bta_dm_set_encryption(const RawAddress& bd_addr, tBT_TRANSPORT transport, - tBTA_DM_ENCRYPT_CBACK* p_callback, - tBTM_BLE_SEC_ACT sec_act) { + tBTA_DM_ENCRYPT_CBACK* p_callback, tBTM_BLE_SEC_ACT sec_act) { inc_func_call_count(__func__); - test::mock::bta_dm_act::bta_dm_set_encryption(bd_addr, transport, p_callback, - sec_act); + test::mock::bta_dm_act::bta_dm_set_encryption(bd_addr, transport, p_callback, sec_act); } void handle_remote_features_complete(const RawAddress& bd_addr) { inc_func_call_count(__func__); diff --git a/system/test/mock/mock_bta_dm_act.h b/system/test/mock/mock_bta_dm_act.h index d16693495be..69d6daa9c3a 100644 --- a/system/test/mock/mock_bta_dm_act.h +++ b/system/test/mock/mock_bta_dm_act.h @@ -44,8 +44,8 @@ namespace bta_dm_act { struct BTA_DmSetVisibility { bool return_value{false}; std::function body{ - [this](bt_scan_mode_t /* mode */) { return return_value; }}; - bool operator()(bt_scan_mode_t mode) { return body(mode); }; + [this](bt_scan_mode_t /* mode */) { return return_value; }}; + bool operator()(bt_scan_mode_t mode) { return body(mode); } }; extern struct BTA_DmSetVisibility BTA_DmSetVisibility; @@ -54,10 +54,8 @@ extern struct BTA_DmSetVisibility BTA_DmSetVisibility; // Return: void struct BTA_dm_acl_down { std::function body{ - [](const RawAddress /* bd_addr */, tBT_TRANSPORT /* transport */) {}}; - void operator()(const RawAddress bd_addr, tBT_TRANSPORT transport) { - body(bd_addr, transport); - }; + [](const RawAddress /* bd_addr */, tBT_TRANSPORT /* transport */) {}}; + void operator()(const RawAddress bd_addr, tBT_TRANSPORT transport) { body(bd_addr, transport); } }; extern struct BTA_dm_acl_down BTA_dm_acl_down; @@ -65,14 +63,12 @@ extern struct BTA_dm_acl_down BTA_dm_acl_down; // Params: const RawAddress bd_addr, tBT_TRANSPORT transport // Return: void struct BTA_dm_acl_up { - std::function - body{[](const RawAddress /* bd_addr */, tBT_TRANSPORT /* transport */, - uint16_t /* acl_handle */) {}}; - void operator()(const RawAddress bd_addr, tBT_TRANSPORT transport, - uint16_t acl_handle) { + std::function body{ + [](const RawAddress /* bd_addr */, tBT_TRANSPORT /* transport */, + uint16_t /* acl_handle */) {}}; + void operator()(const RawAddress bd_addr, tBT_TRANSPORT transport, uint16_t acl_handle) { body(bd_addr, transport, acl_handle); - }; + } }; extern struct BTA_dm_acl_up BTA_dm_acl_up; @@ -80,14 +76,12 @@ extern struct BTA_dm_acl_up BTA_dm_acl_up; // Params: const RawAddress bd_addr, tBT_TRANSPORT transport, tHCI_STATUS // hci_status Return: void struct BTA_dm_acl_up_failed { - std::function - body{[](const RawAddress /* bd_addr */, tBT_TRANSPORT /* transport */, - tHCI_STATUS /* hci_status */) {}}; - void operator()(const RawAddress bd_addr, tBT_TRANSPORT transport, - tHCI_STATUS hci_status) { + std::function + body{[](const RawAddress /* bd_addr */, tBT_TRANSPORT /* transport */, + tHCI_STATUS /* hci_status */) {}}; + void operator()(const RawAddress bd_addr, tBT_TRANSPORT transport, tHCI_STATUS hci_status) { body(bd_addr, transport, hci_status); - }; + } }; extern struct BTA_dm_acl_up_failed BTA_dm_acl_up_failed; @@ -95,19 +89,17 @@ extern struct BTA_dm_acl_up_failed BTA_dm_acl_up_failed; // Params: const RawAddress bd_addr // Return: void struct BTA_dm_notify_remote_features_complete { - std::function body{ - [](const RawAddress /* bd_addr */) {}}; - void operator()(const RawAddress bd_addr) { body(bd_addr); }; + std::function body{[](const RawAddress /* bd_addr */) {}}; + void operator()(const RawAddress bd_addr) { body(bd_addr); } }; -extern struct BTA_dm_notify_remote_features_complete - BTA_dm_notify_remote_features_complete; +extern struct BTA_dm_notify_remote_features_complete BTA_dm_notify_remote_features_complete; // Name: BTA_dm_on_hw_off // Params: // Return: void struct BTA_dm_on_hw_off { std::function body{[]() {}}; - void operator()() { body(); }; + void operator()() { body(); } }; extern struct BTA_dm_on_hw_off BTA_dm_on_hw_off; @@ -116,7 +108,7 @@ extern struct BTA_dm_on_hw_off BTA_dm_on_hw_off; // Return: void struct BTA_dm_on_hw_on { std::function body{[]() {}}; - void operator()() { body(); }; + void operator()() { body(); } }; extern struct BTA_dm_on_hw_on BTA_dm_on_hw_on; @@ -124,14 +116,12 @@ extern struct BTA_dm_on_hw_on BTA_dm_on_hw_on; // Params: const RawAddress bd_addr, tHCI_ROLE new_role, tHCI_STATUS hci_status // Return: void struct BTA_dm_report_role_change { - std::function - body{[](const RawAddress /* bd_addr */, tHCI_ROLE /* new_role */, - tHCI_STATUS /* hci_status */) {}}; - void operator()(const RawAddress bd_addr, tHCI_ROLE new_role, - tHCI_STATUS hci_status) { + std::function body{ + [](const RawAddress /* bd_addr */, tHCI_ROLE /* new_role */, + tHCI_STATUS /* hci_status */) {}}; + void operator()(const RawAddress bd_addr, tHCI_ROLE new_role, tHCI_STATUS hci_status) { body(bd_addr, new_role, hci_status); - }; + } }; extern struct BTA_dm_report_role_change BTA_dm_report_role_change; @@ -139,14 +129,12 @@ extern struct BTA_dm_report_role_change BTA_dm_report_role_change; // Params: const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type, tBT_DEVICE_TYPE // dev_type Return: void struct bta_dm_add_ble_device { - std::function - body{[](const RawAddress& /* bd_addr */, tBLE_ADDR_TYPE /* addr_type */, - tBT_DEVICE_TYPE /* dev_type */) {}}; - void operator()(const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type, - tBT_DEVICE_TYPE dev_type) { + std::function + body{[](const RawAddress& /* bd_addr */, tBLE_ADDR_TYPE /* addr_type */, + tBT_DEVICE_TYPE /* dev_type */) {}}; + void operator()(const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type, tBT_DEVICE_TYPE dev_type) { body(bd_addr, addr_type, dev_type); - }; + } }; extern struct bta_dm_add_ble_device bta_dm_add_ble_device; @@ -156,12 +144,11 @@ extern struct bta_dm_add_ble_device bta_dm_add_ble_device; struct bta_dm_add_blekey { std::function - body{[](const RawAddress& /* bd_addr */, tBTA_LE_KEY_VALUE /* blekey */, - tBTM_LE_KEY_TYPE /* key_type */) {}}; - void operator()(const RawAddress& bd_addr, tBTA_LE_KEY_VALUE blekey, - tBTM_LE_KEY_TYPE key_type) { + body{[](const RawAddress& /* bd_addr */, tBTA_LE_KEY_VALUE /* blekey */, + tBTM_LE_KEY_TYPE /* key_type */) {}}; + void operator()(const RawAddress& bd_addr, tBTA_LE_KEY_VALUE blekey, tBTM_LE_KEY_TYPE key_type) { body(bd_addr, blekey, key_type); - }; + } }; extern struct bta_dm_add_blekey bta_dm_add_blekey; @@ -169,9 +156,8 @@ extern struct bta_dm_add_blekey bta_dm_add_blekey; // Params: bool privacy_enable // Return: void struct bta_dm_ble_config_local_privacy { - std::function body{ - [](bool /* privacy_enable */) {}}; - void operator()(bool privacy_enable) { body(privacy_enable); }; + std::function body{[](bool /* privacy_enable */) {}}; + void operator()(bool privacy_enable) { body(privacy_enable); } }; extern struct bta_dm_ble_config_local_privacy bta_dm_ble_config_local_privacy; @@ -180,10 +166,8 @@ extern struct bta_dm_ble_config_local_privacy bta_dm_ble_config_local_privacy; // Return: void struct bta_dm_ble_confirm_reply { std::function body{ - [](const RawAddress& /* bd_addr */, bool /* accept */) {}}; - void operator()(const RawAddress& bd_addr, bool accept) { - body(bd_addr, accept); - }; + [](const RawAddress& /* bd_addr */, bool /* accept */) {}}; + void operator()(const RawAddress& bd_addr, bool accept) { body(bd_addr, accept); } }; extern struct bta_dm_ble_confirm_reply bta_dm_ble_confirm_reply; @@ -192,10 +176,8 @@ extern struct bta_dm_ble_confirm_reply bta_dm_ble_confirm_reply; // Return: void struct bta_dm_ble_csis_observe { std::function body{ - [](bool /* observe */, tBTA_DM_SEARCH_CBACK* /* p_cback */) {}}; - void operator()(bool observe, tBTA_DM_SEARCH_CBACK* p_cback) { - body(observe, p_cback); - }; + [](bool /* observe */, tBTA_DM_SEARCH_CBACK* /* p_cback */) {}}; + void operator()(bool observe, tBTA_DM_SEARCH_CBACK* p_cback) { body(observe, p_cback); } }; extern struct bta_dm_ble_csis_observe bta_dm_ble_csis_observe; @@ -204,10 +186,8 @@ extern struct bta_dm_ble_csis_observe bta_dm_ble_csis_observe; // Return: void struct bta_dm_ble_get_energy_info { std::function body{ - [](tBTA_BLE_ENERGY_INFO_CBACK* /* p_energy_info_cback */) {}}; - void operator()(tBTA_BLE_ENERGY_INFO_CBACK* p_energy_info_cback) { - body(p_energy_info_cback); - }; + [](tBTA_BLE_ENERGY_INFO_CBACK* /* p_energy_info_cback */) {}}; + void operator()(tBTA_BLE_ENERGY_INFO_CBACK* p_energy_info_cback) { body(p_energy_info_cback); } }; extern struct bta_dm_ble_get_energy_info bta_dm_ble_get_energy_info; @@ -216,7 +196,7 @@ extern struct bta_dm_ble_get_energy_info bta_dm_ble_get_energy_info; // Return: void struct bta_dm_clear_event_filter { std::function body{[]() {}}; - void operator()() { body(); }; + void operator()() { body(); } }; extern struct bta_dm_clear_event_filter bta_dm_clear_event_filter; @@ -225,7 +205,7 @@ extern struct bta_dm_clear_event_filter bta_dm_clear_event_filter; // Return: void struct bta_dm_ble_reset_id { std::function body{[]() {}}; - void operator()() { body(); }; + void operator()() { body(); } }; extern struct bta_dm_ble_reset_id bta_dm_ble_reset_id; @@ -233,12 +213,11 @@ extern struct bta_dm_ble_reset_id bta_dm_ble_reset_id; // Params: const RawAddress& bd_addr, bool accept, uint32_t passkey // Return: void struct bta_dm_ble_passkey_reply { - std::function - body{[](const RawAddress& /* bd_addr */, bool /* accept */, - uint32_t /* passkey */) {}}; + std::function body{ + [](const RawAddress& /* bd_addr */, bool /* accept */, uint32_t /* passkey */) {}}; void operator()(const RawAddress& bd_addr, bool accept, uint32_t passkey) { body(bd_addr, accept, passkey); - }; + } }; extern struct bta_dm_ble_passkey_reply bta_dm_ble_passkey_reply; @@ -247,10 +226,8 @@ extern struct bta_dm_ble_passkey_reply bta_dm_ble_passkey_reply; // Return: void struct bta_dm_ble_scan { std::function body{ - [](bool /* start */, uint8_t /* duration_sec */) {}}; - void operator()(bool start, uint8_t duration_sec) { - body(start, duration_sec); - }; + [](bool /* start */, uint8_t /* duration_sec */) {}}; + void operator()(bool start, uint8_t duration_sec) { body(start, duration_sec); } }; extern struct bta_dm_ble_scan bta_dm_ble_scan; @@ -259,18 +236,15 @@ extern struct bta_dm_ble_scan bta_dm_ble_scan; // conn_int_max, uint16_t peripheral_latency, uint16_t supervision_tout Return: // void struct bta_dm_ble_set_conn_params { - std::function - body{[](const RawAddress& /* bd_addr */, uint16_t /* conn_int_min */, - uint16_t /* conn_int_max */, uint16_t /* peripheral_latency */, - uint16_t /* supervision_tout */) {}}; - void operator()(const RawAddress& bd_addr, uint16_t conn_int_min, - uint16_t conn_int_max, uint16_t peripheral_latency, - uint16_t supervision_tout) { - body(bd_addr, conn_int_min, conn_int_max, peripheral_latency, - supervision_tout); - }; + std::function + body{[](const RawAddress& /* bd_addr */, uint16_t /* conn_int_min */, + uint16_t /* conn_int_max */, uint16_t /* peripheral_latency */, + uint16_t /* supervision_tout */) {}}; + void operator()(const RawAddress& bd_addr, uint16_t conn_int_min, uint16_t conn_int_max, + uint16_t peripheral_latency, uint16_t supervision_tout) { + body(bd_addr, conn_int_min, conn_int_max, peripheral_latency, supervision_tout); + } }; extern struct bta_dm_ble_set_conn_params bta_dm_ble_set_conn_params; @@ -278,9 +252,8 @@ extern struct bta_dm_ble_set_conn_params bta_dm_ble_set_conn_params; // Params: const RawAddress& bd_addr // Return: void struct bta_dm_ble_set_data_length { - std::function body{ - [](const RawAddress& /* bd_addr */) {}}; - void operator()(const RawAddress& bd_addr) { body(bd_addr); }; + std::function body{[](const RawAddress& /* bd_addr */) {}}; + void operator()(const RawAddress& bd_addr) { body(bd_addr); } }; extern struct bta_dm_ble_set_data_length bta_dm_ble_set_data_length; @@ -289,18 +262,15 @@ extern struct bta_dm_ble_set_data_length bta_dm_ble_set_data_length; // uint16_t latency, uint16_t timeout, uint16_t min_ce_len, uint16_t max_ce_len // Return: void struct bta_dm_ble_update_conn_params { - std::function - body{[](const RawAddress& /* bd_addr */, uint16_t /* min_int */, - uint16_t /* max_int */, uint16_t /* latency */, - uint16_t /* timeout */, uint16_t /* min_ce_len */, - uint16_t /* max_ce_len */) {}}; - void operator()(const RawAddress& bd_addr, uint16_t min_int, uint16_t max_int, - uint16_t latency, uint16_t timeout, uint16_t min_ce_len, - uint16_t max_ce_len) { + std::function + body{[](const RawAddress& /* bd_addr */, uint16_t /* min_int */, uint16_t /* max_int */, + uint16_t /* latency */, uint16_t /* timeout */, uint16_t /* min_ce_len */, + uint16_t /* max_ce_len */) {}}; + void operator()(const RawAddress& bd_addr, uint16_t min_int, uint16_t max_int, uint16_t latency, + uint16_t timeout, uint16_t min_ce_len, uint16_t max_ce_len) { body(bd_addr, min_int, max_int, latency, timeout, min_ce_len, max_ce_len); - }; + } }; extern struct bta_dm_ble_update_conn_params bta_dm_ble_update_conn_params; @@ -308,15 +278,14 @@ extern struct bta_dm_ble_update_conn_params bta_dm_ble_update_conn_params; // Params: const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type, tBT_TRANSPORT // transport, tBT_DEVICE_TYPE device_type Return: void struct bta_dm_bond { - std::function - body{[](const RawAddress& /* bd_addr */, tBLE_ADDR_TYPE /* addr_type */, - tBT_TRANSPORT /* transport */, - tBT_DEVICE_TYPE /* device_type */) {}}; - void operator()(const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type, - tBT_TRANSPORT transport, tBT_DEVICE_TYPE device_type) { + std::function + body{[](const RawAddress& /* bd_addr */, tBLE_ADDR_TYPE /* addr_type */, + tBT_TRANSPORT /* transport */, tBT_DEVICE_TYPE /* device_type */) {}}; + void operator()(const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type, tBT_TRANSPORT transport, + tBT_DEVICE_TYPE device_type) { body(bd_addr, addr_type, transport, device_type); - }; + } }; extern struct bta_dm_bond bta_dm_bond; @@ -324,9 +293,8 @@ extern struct bta_dm_bond bta_dm_bond; // Params: const RawAddress& bd_addr // Return: void struct bta_dm_bond_cancel { - std::function body{ - [](const RawAddress& /* bd_addr */) {}}; - void operator()(const RawAddress& bd_addr) { body(bd_addr); }; + std::function body{[](const RawAddress& /* bd_addr */) {}}; + void operator()(const RawAddress& bd_addr) { body(bd_addr); } }; extern struct bta_dm_bond_cancel bta_dm_bond_cancel; @@ -336,21 +304,18 @@ extern struct bta_dm_bond_cancel bta_dm_bond_cancel; struct bta_dm_check_if_only_hd_connected { bool return_value{false}; std::function body{ - [this](const RawAddress& /* peer_addr */) { return return_value; }}; - bool operator()(const RawAddress& peer_addr) { return body(peer_addr); }; + [this](const RawAddress& /* peer_addr */) { return return_value; }}; + bool operator()(const RawAddress& peer_addr) { return body(peer_addr); } }; -extern struct bta_dm_check_if_only_hd_connected - bta_dm_check_if_only_hd_connected; +extern struct bta_dm_check_if_only_hd_connected bta_dm_check_if_only_hd_connected; // Name: bta_dm_ci_rmt_oob_act // Params: std::unique_ptr msg // Return: void struct bta_dm_ci_rmt_oob_act { std::function msg)> body{ - [](std::unique_ptr /* msg */) {}}; - void operator()(std::unique_ptr msg) { - body(std::move(msg)); - }; + [](std::unique_ptr /* msg */) {}}; + void operator()(std::unique_ptr msg) { body(std::move(msg)); } }; extern struct bta_dm_ci_rmt_oob_act bta_dm_ci_rmt_oob_act; @@ -359,10 +324,8 @@ extern struct bta_dm_ci_rmt_oob_act bta_dm_ci_rmt_oob_act; // Return: void struct bta_dm_confirm { std::function body{ - [](const RawAddress& /* bd_addr */, bool /* accept */) {}}; - void operator()(const RawAddress& bd_addr, bool accept) { - body(bd_addr, accept); - }; + [](const RawAddress& /* bd_addr */, bool /* accept */) {}}; + void operator()(const RawAddress& bd_addr, bool accept) { body(bd_addr, accept); } }; extern struct bta_dm_confirm bta_dm_confirm; @@ -371,7 +334,7 @@ extern struct bta_dm_confirm bta_dm_confirm; // Return: void struct bta_dm_disable { std::function body{[]() {}}; - void operator()() { body(); }; + void operator()() { body(); } }; extern struct bta_dm_disable bta_dm_disable; @@ -380,10 +343,8 @@ extern struct bta_dm_disable bta_dm_disable; // Return: void struct bta_dm_eir_update_cust_uuid { std::function body{ - [](const tBTA_CUSTOM_UUID& /* curr */, bool /* adding */) {}}; - void operator()(const tBTA_CUSTOM_UUID& curr, bool adding) { - body(curr, adding); - }; + [](const tBTA_CUSTOM_UUID& /* curr */, bool /* adding */) {}}; + void operator()(const tBTA_CUSTOM_UUID& curr, bool adding) { body(curr, adding); } }; extern struct bta_dm_eir_update_cust_uuid bta_dm_eir_update_cust_uuid; @@ -392,8 +353,8 @@ extern struct bta_dm_eir_update_cust_uuid bta_dm_eir_update_cust_uuid; // Return: void struct bta_dm_eir_update_uuid { std::function body{ - [](uint16_t /* uuid16 */, bool /* adding */) {}}; - void operator()(uint16_t uuid16, bool adding) { body(uuid16, adding); }; + [](uint16_t /* uuid16 */, bool /* adding */) {}}; + void operator()(uint16_t uuid16, bool adding) { body(uuid16, adding); } }; extern struct bta_dm_eir_update_uuid bta_dm_eir_update_uuid; @@ -402,8 +363,8 @@ extern struct bta_dm_eir_update_uuid bta_dm_eir_update_uuid; // Return: void struct bta_dm_enable { std::function body{ - [](tBTA_DM_SEC_CBACK* /* p_sec_cback */) {}}; - void operator()(tBTA_DM_SEC_CBACK* p_sec_cback) { body(p_sec_cback); }; + [](tBTA_DM_SEC_CBACK* /* p_sec_cback */) {}}; + void operator()(tBTA_DM_SEC_CBACK* p_sec_cback) { body(p_sec_cback); } }; extern struct bta_dm_enable bta_dm_enable; @@ -411,14 +372,14 @@ extern struct bta_dm_enable bta_dm_enable; // Params: const RawAddress* bd_addr, tBT_TRANSPORT transport, void* p_ref_data, // tBTM_STATUS result Return: void struct bta_dm_encrypt_cback { - std::function - body{[](const RawAddress* /* bd_addr */, tBT_TRANSPORT /* transport */, - void* /* p_ref_data */, tBTM_STATUS /* result */) {}}; - void operator()(const RawAddress* bd_addr, tBT_TRANSPORT transport, - void* p_ref_data, tBTM_STATUS result) { + std::function + body{[](const RawAddress* /* bd_addr */, tBT_TRANSPORT /* transport */, + void* /* p_ref_data */, tBTM_STATUS /* result */) {}}; + void operator()(const RawAddress* bd_addr, tBT_TRANSPORT transport, void* p_ref_data, + tBTM_STATUS result) { body(bd_addr, transport, p_ref_data, result); - }; + } }; extern struct bta_dm_encrypt_cback bta_dm_encrypt_cback; @@ -428,7 +389,7 @@ extern struct bta_dm_encrypt_cback bta_dm_encrypt_cback; struct bta_dm_is_search_request_queued { bool return_value{false}; std::function body{[this]() { return return_value; }}; - bool operator()() { return body(); }; + bool operator()() { return body(); } }; extern struct bta_dm_is_search_request_queued bta_dm_is_search_request_queued; @@ -437,10 +398,8 @@ extern struct bta_dm_is_search_request_queued bta_dm_is_search_request_queued; // Return: void struct bta_dm_pin_reply { std::function msg)> body{ - [](std::unique_ptr /* msg */) {}}; - void operator()(std::unique_ptr msg) { - body(std::move(msg)); - }; + [](std::unique_ptr /* msg */) {}}; + void operator()(std::unique_ptr msg) { body(std::move(msg)); } }; extern struct bta_dm_pin_reply bta_dm_pin_reply; @@ -448,9 +407,8 @@ extern struct bta_dm_pin_reply bta_dm_pin_reply; // Params: const RawAddress& bd_addr // Return: void struct bta_dm_process_remove_device { - std::function body{ - [](const RawAddress& /* bd_addr */) {}}; - void operator()(const RawAddress& bd_addr) { body(bd_addr); }; + std::function body{[](const RawAddress& /* bd_addr */) {}}; + void operator()(const RawAddress& bd_addr) { body(bd_addr); } }; extern struct bta_dm_process_remove_device bta_dm_process_remove_device; @@ -458,9 +416,8 @@ extern struct bta_dm_process_remove_device bta_dm_process_remove_device; // Params: const RawAddress& bd_addr // Return: void struct bta_dm_remove_device { - std::function body{ - [](const RawAddress& /* bd_addr */) {}}; - void operator()(const RawAddress& bd_addr) { body(bd_addr); }; + std::function body{[](const RawAddress& /* bd_addr */) {}}; + void operator()(const RawAddress& bd_addr) { body(bd_addr); } }; extern struct bta_dm_remove_device bta_dm_remove_device; @@ -468,9 +425,8 @@ extern struct bta_dm_remove_device bta_dm_remove_device; // Params: const RawAddress bd_addr // Return: void struct bta_dm_remote_key_missing { - std::function body{ - [](const RawAddress /* bd_addr */) {}}; - void operator()(const RawAddress bd_addr) { body(bd_addr); }; + std::function body{[](const RawAddress /* bd_addr */) {}}; + void operator()(const RawAddress bd_addr) { body(bd_addr); } }; extern struct bta_dm_remote_key_missing bta_dm_remote_key_missing; @@ -480,12 +436,12 @@ extern struct bta_dm_remote_key_missing bta_dm_remote_key_missing; struct bta_dm_rm_cback { std::function - body{[](tBTA_SYS_CONN_STATUS /* status */, uint8_t /* id */, - uint8_t /* app_id */, const RawAddress& /* peer_addr */) {}}; + body{[](tBTA_SYS_CONN_STATUS /* status */, uint8_t /* id */, uint8_t /* app_id */, + const RawAddress& /* peer_addr */) {}}; void operator()(tBTA_SYS_CONN_STATUS status, uint8_t id, uint8_t app_id, const RawAddress& peer_addr) { body(status, id, app_id, peer_addr); - }; + } }; extern struct bta_dm_rm_cback bta_dm_rm_cback; @@ -494,7 +450,7 @@ extern struct bta_dm_rm_cback bta_dm_rm_cback; // Return: void struct bta_dm_search_cancel_cmpl { std::function body{[]() {}}; - void operator()() { body(); }; + void operator()() { body(); } }; extern struct bta_dm_search_cancel_cmpl bta_dm_search_cancel_cmpl; @@ -503,7 +459,7 @@ extern struct bta_dm_search_cancel_cmpl bta_dm_search_cancel_cmpl; // Return: void struct bta_dm_search_cancel_notify { std::function body{[]() {}}; - void operator()() { body(); }; + void operator()() { body(); } }; extern struct bta_dm_search_cancel_notify bta_dm_search_cancel_notify; @@ -512,8 +468,8 @@ extern struct bta_dm_search_cancel_notify bta_dm_search_cancel_notify; // Return: void struct bta_dm_set_dev_name { std::function& name)> body{ - [](const std::vector& /* name */) {}}; - void operator()(const std::vector& name) { body(name); }; + [](const std::vector& /* name */) {}}; + void operator()(const std::vector& name) { body(name); } }; extern struct bta_dm_set_dev_name bta_dm_set_dev_name; @@ -522,15 +478,13 @@ extern struct bta_dm_set_dev_name bta_dm_set_dev_name; // tBTA_DM_ENCRYPT_CBACK* p_callback, tBTM_BLE_SEC_ACT sec_act Return: void struct bta_dm_set_encryption { std::function - body{[](const RawAddress& /* bd_addr */, tBT_TRANSPORT /* transport */, - tBTA_DM_ENCRYPT_CBACK* /* p_callback */, - tBTM_BLE_SEC_ACT /* sec_act */) {}}; + tBTA_DM_ENCRYPT_CBACK* p_callback, tBTM_BLE_SEC_ACT sec_act)> + body{[](const RawAddress& /* bd_addr */, tBT_TRANSPORT /* transport */, + tBTA_DM_ENCRYPT_CBACK* /* p_callback */, tBTM_BLE_SEC_ACT /* sec_act */) {}}; void operator()(const RawAddress& bd_addr, tBT_TRANSPORT transport, tBTA_DM_ENCRYPT_CBACK* p_callback, tBTM_BLE_SEC_ACT sec_act) { body(bd_addr, transport, p_callback, sec_act); - }; + } }; extern struct bta_dm_set_encryption bta_dm_set_encryption; @@ -538,9 +492,8 @@ extern struct bta_dm_set_encryption bta_dm_set_encryption; // Params: const RawAddress& bd_addr // Return: void struct handle_remote_features_complete { - std::function body{ - [](const RawAddress& /* bd_addr */) {}}; - void operator()(const RawAddress& bd_addr) { body(bd_addr); }; + std::function body{[](const RawAddress& /* bd_addr */) {}}; + void operator()(const RawAddress& bd_addr) { body(bd_addr); } }; extern struct handle_remote_features_complete handle_remote_features_complete; diff --git a/system/test/mock/mock_bta_dm_api.cc b/system/test/mock/mock_bta_dm_api.cc index a749d88ac85..721503ac274 100644 --- a/system/test/mock/mock_bta_dm_api.cc +++ b/system/test/mock/mock_bta_dm_api.cc @@ -73,10 +73,8 @@ struct BTA_DmSetBlePrefConnParams BTA_DmSetBlePrefConnParams; struct BTA_DmSetDefaultEventMaskExcept BTA_DmSetDefaultEventMaskExcept; struct BTA_DmSetDeviceName BTA_DmSetDeviceName; struct BTA_DmSetEncryption BTA_DmSetEncryption; -struct BTA_DmSetEventFilterConnectionSetupAllDevices - BTA_DmSetEventFilterConnectionSetupAllDevices; -struct BTA_DmSetEventFilterInquiryResultAllDevices - BTA_DmSetEventFilterInquiryResultAllDevices; +struct BTA_DmSetEventFilterConnectionSetupAllDevices BTA_DmSetEventFilterConnectionSetupAllDevices; +struct BTA_DmSetEventFilterInquiryResultAllDevices BTA_DmSetEventFilterInquiryResultAllDevices; struct BTA_DmSetLocalDiRecord BTA_DmSetLocalDiRecord; struct BTA_DmSirkConfirmDeviceReply BTA_DmSirkConfirmDeviceReply; struct BTA_DmSirkSecCbRegister BTA_DmSirkSecCbRegister; @@ -112,19 +110,15 @@ void BTA_DmAddBleKey(const RawAddress& bd_addr, tBTA_LE_KEY_VALUE* p_le_key, inc_func_call_count(__func__); test::mock::bta_dm_api::BTA_DmAddBleKey(bd_addr, p_le_key, key_type); } -void BTA_DmAddDevice(const RawAddress& bd_addr, DEV_CLASS dev_class, - const LinkKey& link_key, uint8_t key_type, - uint8_t pin_length) { +void BTA_DmAddDevice(const RawAddress& bd_addr, DEV_CLASS dev_class, const LinkKey& link_key, + uint8_t key_type, uint8_t pin_length) { inc_func_call_count(__func__); - test::mock::bta_dm_api::BTA_DmAddDevice(bd_addr, dev_class, link_key, - key_type, pin_length); + test::mock::bta_dm_api::BTA_DmAddDevice(bd_addr, dev_class, link_key, key_type, pin_length); } -void BTA_DmAllowWakeByHid( - std::vector classic_hid_devices, - std::vector> le_hid_devices) { +void BTA_DmAllowWakeByHid(std::vector classic_hid_devices, + std::vector> le_hid_devices) { inc_func_call_count(__func__); - test::mock::bta_dm_api::BTA_DmAllowWakeByHid(classic_hid_devices, - le_hid_devices); + test::mock::bta_dm_api::BTA_DmAllowWakeByHid(classic_hid_devices, le_hid_devices); } void BTA_DmBleConfigLocalPrivacy(bool privacy_enable) { inc_func_call_count(__func__); @@ -142,8 +136,7 @@ void BTA_DmBleGetEnergyInfo(tBTA_BLE_ENERGY_INFO_CBACK* p_cmpl_cback) { inc_func_call_count(__func__); test::mock::bta_dm_api::BTA_DmBleGetEnergyInfo(p_cmpl_cback); } -void BTA_DmBlePasskeyReply(const RawAddress& bd_addr, bool accept, - uint32_t passkey) { +void BTA_DmBlePasskeyReply(const RawAddress& bd_addr, bool accept, uint32_t passkey) { inc_func_call_count(__func__); test::mock::bta_dm_api::BTA_DmBlePasskeyReply(bd_addr, accept, passkey); } @@ -159,31 +152,27 @@ void BTA_DmBleScan(bool start, uint8_t duration_sec, bool low_latency_scan) { inc_func_call_count(__func__); test::mock::bta_dm_api::BTA_DmBleScan(start, duration_sec, low_latency_scan); } -void BTA_DmBleSecurityGrant(const RawAddress& bd_addr, - tBTA_DM_BLE_SEC_GRANT res) { +void BTA_DmBleSecurityGrant(const RawAddress& bd_addr, tBTA_DM_BLE_SEC_GRANT res) { inc_func_call_count(__func__); test::mock::bta_dm_api::BTA_DmBleSecurityGrant(bd_addr, res); } -void BTA_DmBleSubrateRequest(const RawAddress& bd_addr, uint16_t subrate_min, - uint16_t subrate_max, uint16_t max_latency, - uint16_t cont_num, uint16_t timeout) { +void BTA_DmBleSubrateRequest(const RawAddress& bd_addr, uint16_t subrate_min, uint16_t subrate_max, + uint16_t max_latency, uint16_t cont_num, uint16_t timeout) { inc_func_call_count(__func__); - test::mock::bta_dm_api::BTA_DmBleSubrateRequest( - bd_addr, subrate_min, subrate_max, max_latency, cont_num, timeout); + test::mock::bta_dm_api::BTA_DmBleSubrateRequest(bd_addr, subrate_min, subrate_max, max_latency, + cont_num, timeout); } -void BTA_DmBleUpdateConnectionParams(const RawAddress& bd_addr, - uint16_t min_int, uint16_t max_int, - uint16_t latency, uint16_t timeout, - uint16_t min_ce_len, uint16_t max_ce_len) { +void BTA_DmBleUpdateConnectionParams(const RawAddress& bd_addr, uint16_t min_int, uint16_t max_int, + uint16_t latency, uint16_t timeout, uint16_t min_ce_len, + uint16_t max_ce_len) { inc_func_call_count(__func__); - test::mock::bta_dm_api::BTA_DmBleUpdateConnectionParams( - bd_addr, min_int, max_int, latency, timeout, min_ce_len, max_ce_len); + test::mock::bta_dm_api::BTA_DmBleUpdateConnectionParams(bd_addr, min_int, max_int, latency, + timeout, min_ce_len, max_ce_len); } -void BTA_DmBond(const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type, - tBT_TRANSPORT transport, tBT_DEVICE_TYPE device_type) { +void BTA_DmBond(const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type, tBT_TRANSPORT transport, + tBT_DEVICE_TYPE device_type) { inc_func_call_count(__func__); - test::mock::bta_dm_api::BTA_DmBond(bd_addr, addr_type, transport, - device_type); + test::mock::bta_dm_api::BTA_DmBond(bd_addr, addr_type, transport, device_type); } void BTA_DmBondCancel(const RawAddress& bd_addr) { inc_func_call_count(__func__); @@ -230,8 +219,7 @@ void BTA_DmLocalOob(void) { inc_func_call_count(__func__); test::mock::bta_dm_api::BTA_DmLocalOob(); } -void BTA_DmPinReply(const RawAddress& bd_addr, bool accept, uint8_t pin_len, - uint8_t* p_pin) { +void BTA_DmPinReply(const RawAddress& bd_addr, bool accept, uint8_t pin_len, uint8_t* p_pin) { inc_func_call_count(__func__); test::mock::bta_dm_api::BTA_DmPinReply(bd_addr, accept, pin_len, p_pin); } @@ -239,8 +227,7 @@ tBTA_STATUS BTA_DmRemoveDevice(const RawAddress& bd_addr) { inc_func_call_count(__func__); return test::mock::bta_dm_api::BTA_DmRemoveDevice(bd_addr); } -void BTA_DmRestoreFilterAcceptList( - std::vector> le_devices) { +void BTA_DmRestoreFilterAcceptList(std::vector> le_devices) { inc_func_call_count(__func__); test::mock::bta_dm_api::BTA_DmRestoreFilterAcceptList(le_devices); } @@ -252,14 +239,12 @@ void BTA_DmSearchCancel(void) { inc_func_call_count(__func__); test::mock::bta_dm_api::BTA_DmSearchCancel(); } -void BTA_DmSetBlePrefConnParams(const RawAddress& bd_addr, - uint16_t min_conn_int, uint16_t max_conn_int, - uint16_t peripheral_latency, +void BTA_DmSetBlePrefConnParams(const RawAddress& bd_addr, uint16_t min_conn_int, + uint16_t max_conn_int, uint16_t peripheral_latency, uint16_t supervision_tout) { inc_func_call_count(__func__); - test::mock::bta_dm_api::BTA_DmSetBlePrefConnParams( - bd_addr, min_conn_int, max_conn_int, peripheral_latency, - supervision_tout); + test::mock::bta_dm_api::BTA_DmSetBlePrefConnParams(bd_addr, min_conn_int, max_conn_int, + peripheral_latency, supervision_tout); } void BTA_DmSetDefaultEventMaskExcept(uint64_t mask, uint64_t le_mask) { inc_func_call_count(__func__); @@ -270,11 +255,9 @@ void BTA_DmSetDeviceName(const char* p_name) { test::mock::bta_dm_api::BTA_DmSetDeviceName(p_name); } void BTA_DmSetEncryption(const RawAddress& bd_addr, tBT_TRANSPORT transport, - tBTA_DM_ENCRYPT_CBACK* p_callback, - tBTM_BLE_SEC_ACT sec_act) { + tBTA_DM_ENCRYPT_CBACK* p_callback, tBTM_BLE_SEC_ACT sec_act) { inc_func_call_count(__func__); - test::mock::bta_dm_api::BTA_DmSetEncryption(bd_addr, transport, p_callback, - sec_act); + test::mock::bta_dm_api::BTA_DmSetEncryption(bd_addr, transport, p_callback, sec_act); } void BTA_DmSetEventFilterConnectionSetupAllDevices() { inc_func_call_count(__func__); @@ -284,11 +267,9 @@ void BTA_DmSetEventFilterInquiryResultAllDevices() { inc_func_call_count(__func__); test::mock::bta_dm_api::BTA_DmSetEventFilterInquiryResultAllDevices(); } -tBTA_STATUS BTA_DmSetLocalDiRecord(tSDP_DI_RECORD* p_device_info, - uint32_t* p_handle) { +tBTA_STATUS BTA_DmSetLocalDiRecord(tSDP_DI_RECORD* p_device_info, uint32_t* p_handle) { inc_func_call_count(__func__); - return test::mock::bta_dm_api::BTA_DmSetLocalDiRecord(p_device_info, - p_handle); + return test::mock::bta_dm_api::BTA_DmSetLocalDiRecord(p_device_info, p_handle); } void BTA_DmSirkConfirmDeviceReply(const RawAddress& bd_addr, bool accept) { inc_func_call_count(__func__); diff --git a/system/test/mock/mock_bta_dm_api.h b/system/test/mock/mock_bta_dm_api.h index d615a328e95..1c2a4d1cf9e 100644 --- a/system/test/mock/mock_bta_dm_api.h +++ b/system/test/mock/mock_bta_dm_api.h @@ -51,14 +51,12 @@ namespace bta_dm_api { // Params: const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type, tBT_DEVICE_TYPE // dev_type Return: void struct BTA_DmAddBleDevice { - std::function - body{[](const RawAddress& /* bd_addr */, tBLE_ADDR_TYPE /* addr_type */, - tBT_DEVICE_TYPE /* dev_type */) {}}; - void operator()(const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type, - tBT_DEVICE_TYPE dev_type) { + std::function + body{[](const RawAddress& /* bd_addr */, tBLE_ADDR_TYPE /* addr_type */, + tBT_DEVICE_TYPE /* dev_type */) {}}; + void operator()(const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type, tBT_DEVICE_TYPE dev_type) { body(bd_addr, addr_type, dev_type); - }; + } }; extern struct BTA_DmAddBleDevice BTA_DmAddBleDevice; @@ -68,13 +66,12 @@ extern struct BTA_DmAddBleDevice BTA_DmAddBleDevice; struct BTA_DmAddBleKey { std::function - body{[](const RawAddress& /* bd_addr */, - tBTA_LE_KEY_VALUE* /* p_le_key */, - tBTM_LE_KEY_TYPE /* key_type */) {}}; + body{[](const RawAddress& /* bd_addr */, tBTA_LE_KEY_VALUE* /* p_le_key */, + tBTM_LE_KEY_TYPE /* key_type */) {}}; void operator()(const RawAddress& bd_addr, tBTA_LE_KEY_VALUE* p_le_key, tBTM_LE_KEY_TYPE key_type) { body(bd_addr, p_le_key, key_type); - }; + } }; extern struct BTA_DmAddBleKey BTA_DmAddBleKey; @@ -82,17 +79,15 @@ extern struct BTA_DmAddBleKey BTA_DmAddBleKey; // Params: const RawAddress& bd_addr, DEV_CLASS dev_class, const LinkKey& // link_key, uint8_t key_type, uint8_t pin_length Return: void struct BTA_DmAddDevice { - std::function - body{[](const RawAddress& /* bd_addr */, DEV_CLASS /* dev_class */, - const LinkKey& /* link_key */, uint8_t /* key_type */, - uint8_t /* pin_length */) {}}; - void operator()(const RawAddress& bd_addr, DEV_CLASS dev_class, - const LinkKey& link_key, uint8_t key_type, - uint8_t pin_length) { + std::function + body{[](const RawAddress& /* bd_addr */, DEV_CLASS /* dev_class */, + const LinkKey& /* link_key */, uint8_t /* key_type */, + uint8_t /* pin_length */) {}}; + void operator()(const RawAddress& bd_addr, DEV_CLASS dev_class, const LinkKey& link_key, + uint8_t key_type, uint8_t pin_length) { body(bd_addr, dev_class, link_key, key_type, pin_length); - }; + } }; extern struct BTA_DmAddDevice BTA_DmAddDevice; @@ -100,17 +95,14 @@ extern struct BTA_DmAddDevice BTA_DmAddDevice; // Params: std::vector classic_hid_devices, // std::vector> le_hid_devices Return: void struct BTA_DmAllowWakeByHid { - std::function classic_hid_devices, - std::vector> le_hid_devices)> - body{ - [](std::vector /* classic_hid_devices */, - std::vector> /* le_hid_devices */) { - }}; + std::function classic_hid_devices, + std::vector> le_hid_devices)> + body{[](std::vector /* classic_hid_devices */, + std::vector> /* le_hid_devices */) {}}; void operator()(std::vector classic_hid_devices, std::vector> le_hid_devices) { body(classic_hid_devices, le_hid_devices); - }; + } }; extern struct BTA_DmAllowWakeByHid BTA_DmAllowWakeByHid; @@ -118,9 +110,8 @@ extern struct BTA_DmAllowWakeByHid BTA_DmAllowWakeByHid; // Params: bool privacy_enable // Return: void struct BTA_DmBleConfigLocalPrivacy { - std::function body{ - [](bool /* privacy_enable */) {}}; - void operator()(bool privacy_enable) { body(privacy_enable); }; + std::function body{[](bool /* privacy_enable */) {}}; + void operator()(bool privacy_enable) { body(privacy_enable); } }; extern struct BTA_DmBleConfigLocalPrivacy BTA_DmBleConfigLocalPrivacy; @@ -129,10 +120,8 @@ extern struct BTA_DmBleConfigLocalPrivacy BTA_DmBleConfigLocalPrivacy; // Return: void struct BTA_DmBleConfirmReply { std::function body{ - [](const RawAddress& /* bd_addr */, bool /* accept */) {}}; - void operator()(const RawAddress& bd_addr, bool accept) { - body(bd_addr, accept); - }; + [](const RawAddress& /* bd_addr */, bool /* accept */) {}}; + void operator()(const RawAddress& bd_addr, bool accept) { body(bd_addr, accept); } }; extern struct BTA_DmBleConfirmReply BTA_DmBleConfirmReply; @@ -141,10 +130,8 @@ extern struct BTA_DmBleConfirmReply BTA_DmBleConfirmReply; // Return: void struct BTA_DmBleCsisObserve { std::function body{ - [](bool /* observe */, tBTA_DM_SEARCH_CBACK* /* p_results_cb */) {}}; - void operator()(bool observe, tBTA_DM_SEARCH_CBACK* p_results_cb) { - body(observe, p_results_cb); - }; + [](bool /* observe */, tBTA_DM_SEARCH_CBACK* /* p_results_cb */) {}}; + void operator()(bool observe, tBTA_DM_SEARCH_CBACK* p_results_cb) { body(observe, p_results_cb); } }; extern struct BTA_DmBleCsisObserve BTA_DmBleCsisObserve; @@ -153,10 +140,8 @@ extern struct BTA_DmBleCsisObserve BTA_DmBleCsisObserve; // Return: void struct BTA_DmBleGetEnergyInfo { std::function body{ - [](tBTA_BLE_ENERGY_INFO_CBACK* /* p_cmpl_cback */) {}}; - void operator()(tBTA_BLE_ENERGY_INFO_CBACK* p_cmpl_cback) { - body(p_cmpl_cback); - }; + [](tBTA_BLE_ENERGY_INFO_CBACK* /* p_cmpl_cback */) {}}; + void operator()(tBTA_BLE_ENERGY_INFO_CBACK* p_cmpl_cback) { body(p_cmpl_cback); } }; extern struct BTA_DmBleGetEnergyInfo BTA_DmBleGetEnergyInfo; @@ -164,12 +149,11 @@ extern struct BTA_DmBleGetEnergyInfo BTA_DmBleGetEnergyInfo; // Params: const RawAddress& bd_addr, bool accept, uint32_t passkey // Return: void struct BTA_DmBlePasskeyReply { - std::function - body{[](const RawAddress& /* bd_addr */, bool /* accept */, - uint32_t /* passkey */) {}}; + std::function body{ + [](const RawAddress& /* bd_addr */, bool /* accept */, uint32_t /* passkey */) {}}; void operator()(const RawAddress& bd_addr, bool accept, uint32_t passkey) { body(bd_addr, accept, passkey); - }; + } }; extern struct BTA_DmBlePasskeyReply BTA_DmBlePasskeyReply; @@ -178,8 +162,8 @@ extern struct BTA_DmBlePasskeyReply BTA_DmBlePasskeyReply; // Return: void struct BTA_DmBleRequestMaxTxDataLength { std::function body{ - [](const RawAddress& /* remote_device */) {}}; - void operator()(const RawAddress& remote_device) { body(remote_device); }; + [](const RawAddress& /* remote_device */) {}}; + void operator()(const RawAddress& remote_device) { body(remote_device); } }; extern struct BTA_DmBleRequestMaxTxDataLength BTA_DmBleRequestMaxTxDataLength; @@ -188,7 +172,7 @@ extern struct BTA_DmBleRequestMaxTxDataLength BTA_DmBleRequestMaxTxDataLength; // Return: void struct BTA_DmBleResetId { std::function body{[](void) {}}; - void operator()(void) { body(); }; + void operator()(void) { body(); } }; extern struct BTA_DmBleResetId BTA_DmBleResetId; @@ -196,12 +180,11 @@ extern struct BTA_DmBleResetId BTA_DmBleResetId; // Params: bool start, uint8_t duration_sec, bool low_latency_scan // Return: void struct BTA_DmBleScan { - std::function - body{[](bool /* start */, uint8_t /* duration_sec */, - bool /* low_latency_scan */) {}}; + std::function body{ + [](bool /* start */, uint8_t /* duration_sec */, bool /* low_latency_scan */) {}}; void operator()(bool start, uint8_t duration_sec, bool low_latency_scan) { body(start, duration_sec, low_latency_scan); - }; + } }; extern struct BTA_DmBleScan BTA_DmBleScan; @@ -209,12 +192,9 @@ extern struct BTA_DmBleScan BTA_DmBleScan; // Params: const RawAddress& bd_addr, tBTA_DM_BLE_SEC_GRANT res // Return: void struct BTA_DmBleSecurityGrant { - std::function - body{[](const RawAddress& /* bd_addr */, - tBTA_DM_BLE_SEC_GRANT /* res */) {}}; - void operator()(const RawAddress& bd_addr, tBTA_DM_BLE_SEC_GRANT res) { - body(bd_addr, res); - }; + std::function body{ + [](const RawAddress& /* bd_addr */, tBTA_DM_BLE_SEC_GRANT /* res */) {}}; + void operator()(const RawAddress& bd_addr, tBTA_DM_BLE_SEC_GRANT res) { body(bd_addr, res); } }; extern struct BTA_DmBleSecurityGrant BTA_DmBleSecurityGrant; @@ -223,17 +203,15 @@ extern struct BTA_DmBleSecurityGrant BTA_DmBleSecurityGrant; // subrate_max, uint16_t max_latency, uint16_t cont_num, uint16_t timeout // Return: void struct BTA_DmBleSubrateRequest { - std::function - body{[](const RawAddress& /* bd_addr */, uint16_t /* subrate_min */, - uint16_t /* subrate_max */, uint16_t /* max_latency */, - uint16_t /* cont_num */, uint16_t /* timeout */) {}}; - void operator()(const RawAddress& bd_addr, uint16_t subrate_min, - uint16_t subrate_max, uint16_t max_latency, uint16_t cont_num, - uint16_t timeout) { + std::function + body{[](const RawAddress& /* bd_addr */, uint16_t /* subrate_min */, + uint16_t /* subrate_max */, uint16_t /* max_latency */, uint16_t /* cont_num */, + uint16_t /* timeout */) {}}; + void operator()(const RawAddress& bd_addr, uint16_t subrate_min, uint16_t subrate_max, + uint16_t max_latency, uint16_t cont_num, uint16_t timeout) { body(bd_addr, subrate_min, subrate_max, max_latency, cont_num, timeout); - }; + } }; extern struct BTA_DmBleSubrateRequest BTA_DmBleSubrateRequest; @@ -242,18 +220,15 @@ extern struct BTA_DmBleSubrateRequest BTA_DmBleSubrateRequest; // uint16_t latency, uint16_t timeout, uint16_t min_ce_len, uint16_t max_ce_len // Return: void struct BTA_DmBleUpdateConnectionParams { - std::function - body{[](const RawAddress& /* bd_addr */, uint16_t /* min_int */, - uint16_t /* max_int */, uint16_t /* latency */, - uint16_t /* timeout */, uint16_t /* min_ce_len */, - uint16_t /* max_ce_len */) {}}; - void operator()(const RawAddress& bd_addr, uint16_t min_int, uint16_t max_int, - uint16_t latency, uint16_t timeout, uint16_t min_ce_len, - uint16_t max_ce_len) { + std::function + body{[](const RawAddress& /* bd_addr */, uint16_t /* min_int */, uint16_t /* max_int */, + uint16_t /* latency */, uint16_t /* timeout */, uint16_t /* min_ce_len */, + uint16_t /* max_ce_len */) {}}; + void operator()(const RawAddress& bd_addr, uint16_t min_int, uint16_t max_int, uint16_t latency, + uint16_t timeout, uint16_t min_ce_len, uint16_t max_ce_len) { body(bd_addr, min_int, max_int, latency, timeout, min_ce_len, max_ce_len); - }; + } }; extern struct BTA_DmBleUpdateConnectionParams BTA_DmBleUpdateConnectionParams; @@ -261,15 +236,14 @@ extern struct BTA_DmBleUpdateConnectionParams BTA_DmBleUpdateConnectionParams; // Params: const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type, tBT_TRANSPORT // transport, tBT_DEVICE_TYPE device_type Return: void struct BTA_DmBond { - std::function - body{[](const RawAddress& /* bd_addr */, tBLE_ADDR_TYPE /* addr_type */, - tBT_TRANSPORT /* transport */, - tBT_DEVICE_TYPE /* device_type */) {}}; - void operator()(const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type, - tBT_TRANSPORT transport, tBT_DEVICE_TYPE device_type) { + std::function + body{[](const RawAddress& /* bd_addr */, tBLE_ADDR_TYPE /* addr_type */, + tBT_TRANSPORT /* transport */, tBT_DEVICE_TYPE /* device_type */) {}}; + void operator()(const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type, tBT_TRANSPORT transport, + tBT_DEVICE_TYPE device_type) { body(bd_addr, addr_type, transport, device_type); - }; + } }; extern struct BTA_DmBond BTA_DmBond; @@ -277,9 +251,8 @@ extern struct BTA_DmBond BTA_DmBond; // Params: const RawAddress& bd_addr // Return: void struct BTA_DmBondCancel { - std::function body{ - [](const RawAddress& /* bd_addr */) {}}; - void operator()(const RawAddress& bd_addr) { body(bd_addr); }; + std::function body{[](const RawAddress& /* bd_addr */) {}}; + void operator()(const RawAddress& bd_addr) { body(bd_addr); } }; extern struct BTA_DmBondCancel BTA_DmBondCancel; @@ -289,8 +262,8 @@ extern struct BTA_DmBondCancel BTA_DmBondCancel; struct BTA_DmCheckLeAudioCapable { static bool return_value; std::function body{ - [](const RawAddress& /* address */) { return return_value; }}; - bool operator()(const RawAddress& address) { return body(address); }; + [](const RawAddress& /* address */) { return return_value; }}; + bool operator()(const RawAddress& address) { return body(address); } }; extern struct BTA_DmCheckLeAudioCapable BTA_DmCheckLeAudioCapable; @@ -299,7 +272,7 @@ extern struct BTA_DmCheckLeAudioCapable BTA_DmCheckLeAudioCapable; // Return: void struct BTA_DmClearEventFilter { std::function body{[](void) {}}; - void operator()(void) { body(); }; + void operator()(void) { body(); } }; extern struct BTA_DmClearEventFilter BTA_DmClearEventFilter; @@ -308,7 +281,7 @@ extern struct BTA_DmClearEventFilter BTA_DmClearEventFilter; // Return: void struct BTA_DmClearEventMask { std::function body{[](void) {}}; - void operator()(void) { body(); }; + void operator()(void) { body(); } }; extern struct BTA_DmClearEventMask BTA_DmClearEventMask; @@ -317,7 +290,7 @@ extern struct BTA_DmClearEventMask BTA_DmClearEventMask; // Return: void struct BTA_DmClearFilterAcceptList { std::function body{[](void) {}}; - void operator()(void) { body(); }; + void operator()(void) { body(); } }; extern struct BTA_DmClearFilterAcceptList BTA_DmClearFilterAcceptList; @@ -326,10 +299,8 @@ extern struct BTA_DmClearFilterAcceptList BTA_DmClearFilterAcceptList; // Return: void struct BTA_DmConfirm { std::function body{ - [](const RawAddress& /* bd_addr */, bool /* accept */) {}}; - void operator()(const RawAddress& bd_addr, bool accept) { - body(bd_addr, accept); - }; + [](const RawAddress& /* bd_addr */, bool /* accept */) {}}; + void operator()(const RawAddress& bd_addr, bool accept) { body(bd_addr, accept); } }; extern struct BTA_DmConfirm BTA_DmConfirm; @@ -338,7 +309,7 @@ extern struct BTA_DmConfirm BTA_DmConfirm; // Return: void struct BTA_DmDisconnectAllAcls { std::function body{[]() {}}; - void operator()() { body(); }; + void operator()() { body(); } }; extern struct BTA_DmDisconnectAllAcls BTA_DmDisconnectAllAcls; @@ -348,13 +319,12 @@ extern struct BTA_DmDisconnectAllAcls BTA_DmDisconnectAllAcls; struct BTA_DmDiscover { std::function - body{[](const RawAddress& /* bd_addr */, - tBTA_DM_SEARCH_CBACK* /* p_cback */, - tBT_TRANSPORT /* transport */) {}}; + body{[](const RawAddress& /* bd_addr */, tBTA_DM_SEARCH_CBACK* /* p_cback */, + tBT_TRANSPORT /* transport */) {}}; void operator()(const RawAddress& bd_addr, tBTA_DM_SEARCH_CBACK* p_cback, tBT_TRANSPORT transport) { body(bd_addr, p_cback, transport); - }; + } }; extern struct BTA_DmDiscover BTA_DmDiscover; @@ -364,8 +334,8 @@ extern struct BTA_DmDiscover BTA_DmDiscover; struct BTA_DmGetConnectionState { static bool return_value; std::function body{ - [](const RawAddress& /* bd_addr */) { return return_value; }}; - bool operator()(const RawAddress& bd_addr) { return body(bd_addr); }; + [](const RawAddress& /* bd_addr */) { return return_value; }}; + bool operator()(const RawAddress& bd_addr) { return body(bd_addr); } }; extern struct BTA_DmGetConnectionState BTA_DmGetConnectionState; @@ -374,8 +344,8 @@ extern struct BTA_DmGetConnectionState BTA_DmGetConnectionState; // Return: void struct BTA_DmLeRand { std::function body{ - [](bluetooth::hci::LeRandCallback /* cb */) {}}; - void operator()(bluetooth::hci::LeRandCallback cb) { body(std::move(cb)); }; + [](bluetooth::hci::LeRandCallback /* cb */) {}}; + void operator()(bluetooth::hci::LeRandCallback cb) { body(std::move(cb)); } }; extern struct BTA_DmLeRand BTA_DmLeRand; @@ -384,7 +354,7 @@ extern struct BTA_DmLeRand BTA_DmLeRand; // Return: void struct BTA_DmLocalOob { std::function body{[](void) {}}; - void operator()(void) { body(); }; + void operator()(void) { body(); } }; extern struct BTA_DmLocalOob BTA_DmLocalOob; @@ -392,14 +362,12 @@ extern struct BTA_DmLocalOob BTA_DmLocalOob; // Params: const RawAddress& bd_addr, bool accept, uint8_t pin_len, uint8_t* // p_pin Return: void struct BTA_DmPinReply { - std::function - body{[](const RawAddress& /* bd_addr */, bool /* accept */, - uint8_t /* pin_len */, uint8_t* /* p_pin */) {}}; - void operator()(const RawAddress& bd_addr, bool accept, uint8_t pin_len, - uint8_t* p_pin) { + std::function body{ + [](const RawAddress& /* bd_addr */, bool /* accept */, uint8_t /* pin_len */, + uint8_t* /* p_pin */) {}}; + void operator()(const RawAddress& bd_addr, bool accept, uint8_t pin_len, uint8_t* p_pin) { body(bd_addr, accept, pin_len, p_pin); - }; + } }; extern struct BTA_DmPinReply BTA_DmPinReply; @@ -409,8 +377,8 @@ extern struct BTA_DmPinReply BTA_DmPinReply; struct BTA_DmRemoveDevice { static tBTA_STATUS return_value; std::function body{ - [](const RawAddress& /* bd_addr */) { return return_value; }}; - tBTA_STATUS operator()(const RawAddress& bd_addr) { return body(bd_addr); }; + [](const RawAddress& /* bd_addr */) { return return_value; }}; + tBTA_STATUS operator()(const RawAddress& bd_addr) { return body(bd_addr); } }; extern struct BTA_DmRemoveDevice BTA_DmRemoveDevice; @@ -418,11 +386,9 @@ extern struct BTA_DmRemoveDevice BTA_DmRemoveDevice; // Params: std::vector> le_devices // Return: void struct BTA_DmRestoreFilterAcceptList { - std::function> le_devices)> - body{[](std::vector> /* le_devices */) {}}; - void operator()(std::vector> le_devices) { - body(le_devices); - }; + std::function> le_devices)> body{ + [](std::vector> /* le_devices */) {}}; + void operator()(std::vector> le_devices) { body(le_devices); } }; extern struct BTA_DmRestoreFilterAcceptList BTA_DmRestoreFilterAcceptList; @@ -431,8 +397,8 @@ extern struct BTA_DmRestoreFilterAcceptList BTA_DmRestoreFilterAcceptList; // Return: void struct BTA_DmSearch { std::function body{ - [](tBTA_DM_SEARCH_CBACK* /* p_cback */) {}}; - void operator()(tBTA_DM_SEARCH_CBACK* p_cback) { body(p_cback); }; + [](tBTA_DM_SEARCH_CBACK* /* p_cback */) {}}; + void operator()(tBTA_DM_SEARCH_CBACK* p_cback) { body(p_cback); } }; extern struct BTA_DmSearch BTA_DmSearch; @@ -441,7 +407,7 @@ extern struct BTA_DmSearch BTA_DmSearch; // Return: void struct BTA_DmSearchCancel { std::function body{[](void) {}}; - void operator()(void) { body(); }; + void operator()(void) { body(); } }; extern struct BTA_DmSearchCancel BTA_DmSearchCancel; @@ -450,18 +416,15 @@ extern struct BTA_DmSearchCancel BTA_DmSearchCancel; // max_conn_int, uint16_t peripheral_latency, uint16_t supervision_tout Return: // void struct BTA_DmSetBlePrefConnParams { - std::function - body{[](const RawAddress& /* bd_addr */, uint16_t /* min_conn_int */, - uint16_t /* max_conn_int */, uint16_t /* peripheral_latency */, - uint16_t /* supervision_tout */) {}}; - void operator()(const RawAddress& bd_addr, uint16_t min_conn_int, - uint16_t max_conn_int, uint16_t peripheral_latency, - uint16_t supervision_tout) { - body(bd_addr, min_conn_int, max_conn_int, peripheral_latency, - supervision_tout); - }; + std::function + body{[](const RawAddress& /* bd_addr */, uint16_t /* min_conn_int */, + uint16_t /* max_conn_int */, uint16_t /* peripheral_latency */, + uint16_t /* supervision_tout */) {}}; + void operator()(const RawAddress& bd_addr, uint16_t min_conn_int, uint16_t max_conn_int, + uint16_t peripheral_latency, uint16_t supervision_tout) { + body(bd_addr, min_conn_int, max_conn_int, peripheral_latency, supervision_tout); + } }; extern struct BTA_DmSetBlePrefConnParams BTA_DmSetBlePrefConnParams; @@ -470,8 +433,8 @@ extern struct BTA_DmSetBlePrefConnParams BTA_DmSetBlePrefConnParams; // Return: void struct BTA_DmSetDefaultEventMaskExcept { std::function body{ - [](uint64_t /* mask */, uint64_t /* le_mask */) {}}; - void operator()(uint64_t mask, uint64_t le_mask) { body(mask, le_mask); }; + [](uint64_t /* mask */, uint64_t /* le_mask */) {}}; + void operator()(uint64_t mask, uint64_t le_mask) { body(mask, le_mask); } }; extern struct BTA_DmSetDefaultEventMaskExcept BTA_DmSetDefaultEventMaskExcept; @@ -480,7 +443,7 @@ extern struct BTA_DmSetDefaultEventMaskExcept BTA_DmSetDefaultEventMaskExcept; // Return: void struct BTA_DmSetDeviceName { std::function body{[](const char* /* p_name */) {}}; - void operator()(const char* p_name) { body(p_name); }; + void operator()(const char* p_name) { body(p_name); } }; extern struct BTA_DmSetDeviceName BTA_DmSetDeviceName; @@ -489,15 +452,13 @@ extern struct BTA_DmSetDeviceName BTA_DmSetDeviceName; // tBTA_DM_ENCRYPT_CBACK* p_callback, tBTM_BLE_SEC_ACT sec_act Return: void struct BTA_DmSetEncryption { std::function - body{[](const RawAddress& /* bd_addr */, tBT_TRANSPORT /* transport */, - tBTA_DM_ENCRYPT_CBACK* /* p_callback */, - tBTM_BLE_SEC_ACT /* sec_act */) {}}; + tBTA_DM_ENCRYPT_CBACK* p_callback, tBTM_BLE_SEC_ACT sec_act)> + body{[](const RawAddress& /* bd_addr */, tBT_TRANSPORT /* transport */, + tBTA_DM_ENCRYPT_CBACK* /* p_callback */, tBTM_BLE_SEC_ACT /* sec_act */) {}}; void operator()(const RawAddress& bd_addr, tBT_TRANSPORT transport, tBTA_DM_ENCRYPT_CBACK* p_callback, tBTM_BLE_SEC_ACT sec_act) { body(bd_addr, transport, p_callback, sec_act); - }; + } }; extern struct BTA_DmSetEncryption BTA_DmSetEncryption; @@ -506,33 +467,33 @@ extern struct BTA_DmSetEncryption BTA_DmSetEncryption; // Return: void struct BTA_DmSetEventFilterConnectionSetupAllDevices { std::function body{[]() {}}; - void operator()() { body(); }; + void operator()() { body(); } }; extern struct BTA_DmSetEventFilterConnectionSetupAllDevices - BTA_DmSetEventFilterConnectionSetupAllDevices; + BTA_DmSetEventFilterConnectionSetupAllDevices; // Name: BTA_DmSetEventFilterInquiryResultAllDevices // Params: // Return: void struct BTA_DmSetEventFilterInquiryResultAllDevices { std::function body{[]() {}}; - void operator()() { body(); }; + void operator()() { body(); } }; extern struct BTA_DmSetEventFilterInquiryResultAllDevices - BTA_DmSetEventFilterInquiryResultAllDevices; + BTA_DmSetEventFilterInquiryResultAllDevices; // Name: BTA_DmSetLocalDiRecord // Params: tSDP_DI_RECORD* p_device_info, uint32_t* p_handle // Return: tBTA_STATUS struct BTA_DmSetLocalDiRecord { static tBTA_STATUS return_value; - std::function - body{[](tSDP_DI_RECORD* /* p_device_info */, uint32_t* /* p_handle */) { - return return_value; - }}; + std::function body{ + [](tSDP_DI_RECORD* /* p_device_info */, uint32_t* /* p_handle */) { + return return_value; + }}; tBTA_STATUS operator()(tSDP_DI_RECORD* p_device_info, uint32_t* p_handle) { return body(p_device_info, p_handle); - }; + } }; extern struct BTA_DmSetLocalDiRecord BTA_DmSetLocalDiRecord; @@ -541,10 +502,8 @@ extern struct BTA_DmSetLocalDiRecord BTA_DmSetLocalDiRecord; // Return: void struct BTA_DmSirkConfirmDeviceReply { std::function body{ - [](const RawAddress& /* bd_addr */, bool /* accept */) {}}; - void operator()(const RawAddress& bd_addr, bool accept) { - body(bd_addr, accept); - }; + [](const RawAddress& /* bd_addr */, bool /* accept */) {}}; + void operator()(const RawAddress& bd_addr, bool accept) { body(bd_addr, accept); } }; extern struct BTA_DmSirkConfirmDeviceReply BTA_DmSirkConfirmDeviceReply; @@ -552,9 +511,8 @@ extern struct BTA_DmSirkConfirmDeviceReply BTA_DmSirkConfirmDeviceReply; // Params: tBTA_DM_SEC_CBACK* p_cback // Return: void struct BTA_DmSirkSecCbRegister { - std::function body{ - [](tBTA_DM_SEC_CBACK* /* p_cback */) {}}; - void operator()(tBTA_DM_SEC_CBACK* p_cback) { body(p_cback); }; + std::function body{[](tBTA_DM_SEC_CBACK* /* p_cback */) {}}; + void operator()(tBTA_DM_SEC_CBACK* p_cback) { body(p_cback); } }; extern struct BTA_DmSirkSecCbRegister BTA_DmSirkSecCbRegister; @@ -563,7 +521,7 @@ extern struct BTA_DmSirkSecCbRegister BTA_DmSirkSecCbRegister; // Return: void struct BTA_EnableTestMode { std::function body{[](void) {}}; - void operator()(void) { body(); }; + void operator()(void) { body(); } }; extern struct BTA_EnableTestMode BTA_EnableTestMode; @@ -572,7 +530,7 @@ extern struct BTA_EnableTestMode BTA_EnableTestMode; // Return: void struct BTA_dm_init { std::function body{[]() {}}; - void operator()() { body(); }; + void operator()() { body(); } }; extern struct BTA_dm_init BTA_dm_init; diff --git a/system/test/mock/mock_bta_dm_main.h b/system/test/mock/mock_bta_dm_main.h index 4a79e71e5ca..8c332e0a475 100644 --- a/system/test/mock/mock_bta_dm_main.h +++ b/system/test/mock/mock_bta_dm_main.h @@ -45,7 +45,7 @@ namespace bta_dm_main { // Return: void struct DumpsysBtaDm { std::function body{[](int /* fd */) {}}; - void operator()(int fd) { body(fd); }; + void operator()(int fd) { body(fd); } }; extern struct DumpsysBtaDm DumpsysBtaDm; diff --git a/system/test/mock/mock_bta_gattc_api.cc b/system/test/mock/mock_bta_gattc_api.cc index f70f2adf5c1..0ea4a4ddc70 100644 --- a/system/test/mock/mock_bta_gattc_api.cc +++ b/system/test/mock/mock_bta_gattc_api.cc @@ -36,18 +36,16 @@ const gatt::Characteristic* BTA_GATTC_GetCharacteristic(uint16_t /* conn_id */, inc_func_call_count(__func__); return nullptr; } -const gatt::Characteristic* BTA_GATTC_GetOwningCharacteristic( - uint16_t /* conn_id */, uint16_t /* handle */) { +const gatt::Characteristic* BTA_GATTC_GetOwningCharacteristic(uint16_t /* conn_id */, + uint16_t /* handle */) { inc_func_call_count(__func__); return nullptr; } -const gatt::Descriptor* BTA_GATTC_GetDescriptor(uint16_t /* conn_id */, - uint16_t /* handle */) { +const gatt::Descriptor* BTA_GATTC_GetDescriptor(uint16_t /* conn_id */, uint16_t /* handle */) { inc_func_call_count(__func__); return nullptr; } -const gatt::Service* BTA_GATTC_GetOwningService(uint16_t /* conn_id */, - uint16_t /* handle */) { +const gatt::Service* BTA_GATTC_GetOwningService(uint16_t /* conn_id */, uint16_t /* handle */) { inc_func_call_count(__func__); return nullptr; } @@ -67,16 +65,12 @@ tGATT_STATUS BTA_GATTC_RegisterForNotifications(tGATT_IF /* client_if */, inc_func_call_count(__func__); return GATT_SUCCESS; } -void BTA_GATTC_AppDeregister(tGATT_IF /* client_if */) { - inc_func_call_count(__func__); -} -void BTA_GATTC_AppRegister(tBTA_GATTC_CBACK* /* p_client_cb */, - BtaAppRegisterCallback /* cb */, +void BTA_GATTC_AppDeregister(tGATT_IF /* client_if */) { inc_func_call_count(__func__); } +void BTA_GATTC_AppRegister(tBTA_GATTC_CBACK* /* p_client_cb */, BtaAppRegisterCallback /* cb */, bool /* eatt_support */) { inc_func_call_count(__func__); } -void BTA_GATTC_CancelOpen(tGATT_IF /* client_if */, - const RawAddress& /* remote_bda */, +void BTA_GATTC_CancelOpen(tGATT_IF /* client_if */, const RawAddress& /* remote_bda */, bool /* is_direct */) { inc_func_call_count(__func__); } @@ -85,8 +79,7 @@ void BTA_GATTC_ConfigureMTU(uint16_t /* conn_id */, uint16_t /* mtu */) { inc_func_call_count(__func__); } void BTA_GATTC_ConfigureMTU(uint16_t /* conn_id */, uint16_t /* mtu */, - GATT_CONFIGURE_MTU_OP_CB /* callback */, - void* /* cb_data */) { + GATT_CONFIGURE_MTU_OP_CB /* callback */, void* /* cb_data */) { inc_func_call_count(__func__); } void BTA_GATTC_DiscoverServiceByUuid(uint16_t /* conn_id */, @@ -97,93 +90,67 @@ void BTA_GATTC_ExecuteWrite(uint16_t /* conn_id */, bool /* is_execute */) { inc_func_call_count(__func__); } void BTA_GATTC_GetGattDb(uint16_t /* conn_id */, uint16_t /* start_handle */, - uint16_t /* end_handle */, - btgatt_db_element_t** /* db */, int* /* count */) { + uint16_t /* end_handle */, btgatt_db_element_t** /* db */, + int* /* count */) { inc_func_call_count(__func__); } -void BTA_GATTC_Open(tGATT_IF /* client_if */, - const RawAddress& /* remote_bda */, - tBTM_BLE_CONN_TYPE /* connection_type */, - bool /* opportunistic */) { +void BTA_GATTC_Open(tGATT_IF /* client_if */, const RawAddress& /* remote_bda */, + tBTM_BLE_CONN_TYPE /* connection_type */, bool /* opportunistic */) { inc_func_call_count(__func__); } -void BTA_GATTC_Open(tGATT_IF /* client_if */, - const RawAddress& /* remote_bda */, - tBTM_BLE_CONN_TYPE /* connection_type */, - tBT_TRANSPORT /* transport */, bool /* opportunistic */, - uint8_t /* initiating_phys */) { +void BTA_GATTC_Open(tGATT_IF /* client_if */, const RawAddress& /* remote_bda */, + tBTM_BLE_CONN_TYPE /* connection_type */, tBT_TRANSPORT /* transport */, + bool /* opportunistic */, uint8_t /* initiating_phys */) { inc_func_call_count(__func__); } -void BTA_GATTC_Open(tGATT_IF /* client_if */, - const RawAddress& /* remote_bda */, - tBLE_ADDR_TYPE /* addr_type */, - tBTM_BLE_CONN_TYPE /* connection_type */, +void BTA_GATTC_Open(tGATT_IF /* client_if */, const RawAddress& /* remote_bda */, + tBLE_ADDR_TYPE /* addr_type */, tBTM_BLE_CONN_TYPE /* connection_type */, tBT_TRANSPORT /* transport */, bool /* opportunistic */, uint8_t /* initiating_phys */) { inc_func_call_count(__func__); } -void BTA_GATTC_PrepareWrite(uint16_t /* conn_id */, uint16_t /* handle */, - uint16_t /* offset */, - std::vector /* value */, - tGATT_AUTH_REQ /* auth_req */, - GATT_WRITE_OP_CB /* callback */, - void* /* cb_data */) { +void BTA_GATTC_PrepareWrite(uint16_t /* conn_id */, uint16_t /* handle */, uint16_t /* offset */, + std::vector /* value */, tGATT_AUTH_REQ /* auth_req */, + GATT_WRITE_OP_CB /* callback */, void* /* cb_data */) { inc_func_call_count(__func__); } void BTA_GATTC_ReadCharDescr(uint16_t /* conn_id */, uint16_t /* handle */, - tGATT_AUTH_REQ /* auth_req */, - GATT_READ_OP_CB /* callback */, + tGATT_AUTH_REQ /* auth_req */, GATT_READ_OP_CB /* callback */, void* /* cb_data */) { inc_func_call_count(__func__); } void BTA_GATTC_ReadCharacteristic(uint16_t /* conn_id */, uint16_t /* handle */, - tGATT_AUTH_REQ /* auth_req */, - GATT_READ_OP_CB /* callback */, + tGATT_AUTH_REQ /* auth_req */, GATT_READ_OP_CB /* callback */, void* /* cb_data */) { inc_func_call_count(__func__); } -void BTA_GATTC_ReadMultiple(uint16_t /* conn_id */, - tBTA_GATTC_MULTI& /* handles */, - bool /* variable_len */, - tGATT_AUTH_REQ /* auth_req */, - GATT_READ_MULTI_OP_CB /* callback */, - void* /* cb_data */) { +void BTA_GATTC_ReadMultiple(uint16_t /* conn_id */, tBTA_GATTC_MULTI& /* handles */, + bool /* variable_len */, tGATT_AUTH_REQ /* auth_req */, + GATT_READ_MULTI_OP_CB /* callback */, void* /* cb_data */) { inc_func_call_count(__func__); } -void BTA_GATTC_ReadUsingCharUuid(uint16_t /* conn_id */, - const bluetooth::Uuid& /* uuid */, - uint16_t /* s_handle */, - uint16_t /* e_handle */, - tGATT_AUTH_REQ /* auth_req */, - GATT_READ_OP_CB /* callback */, +void BTA_GATTC_ReadUsingCharUuid(uint16_t /* conn_id */, const bluetooth::Uuid& /* uuid */, + uint16_t /* s_handle */, uint16_t /* e_handle */, + tGATT_AUTH_REQ /* auth_req */, GATT_READ_OP_CB /* callback */, void* /* cb_data */) { inc_func_call_count(__func__); } -void BTA_GATTC_Refresh(const RawAddress& /* remote_bda */) { - inc_func_call_count(__func__); -} +void BTA_GATTC_Refresh(const RawAddress& /* remote_bda */) { inc_func_call_count(__func__); } void BTA_GATTC_SendIndConfirm(uint16_t /* conn_id */, uint16_t /* cid */) { inc_func_call_count(__func__); } -void BTA_GATTC_ServiceSearchAllRequest(uint16_t /* conn_id */) { - inc_func_call_count(__func__); -} -void BTA_GATTC_ServiceSearchRequest(uint16_t /* conn_id */, - bluetooth::Uuid /* p_srvc_uuid */) { +void BTA_GATTC_ServiceSearchAllRequest(uint16_t /* conn_id */) { inc_func_call_count(__func__); } +void BTA_GATTC_ServiceSearchRequest(uint16_t /* conn_id */, bluetooth::Uuid /* p_srvc_uuid */) { inc_func_call_count(__func__); } void BTA_GATTC_WriteCharDescr(uint16_t /* conn_id */, uint16_t /* handle */, - std::vector /* value */, - tGATT_AUTH_REQ /* auth_req */, - GATT_WRITE_OP_CB /* callback */, - void* /* cb_data */) { + std::vector /* value */, tGATT_AUTH_REQ /* auth_req */, + GATT_WRITE_OP_CB /* callback */, void* /* cb_data */) { inc_func_call_count(__func__); } void BTA_GATTC_WriteCharValue(uint16_t /* conn_id */, uint16_t /* handle */, - tGATT_WRITE_TYPE /* write_type */, - std::vector /* value */, - tGATT_AUTH_REQ /* auth_req */, - GATT_WRITE_OP_CB /* callback */, + tGATT_WRITE_TYPE /* write_type */, std::vector /* value */, + tGATT_AUTH_REQ /* auth_req */, GATT_WRITE_OP_CB /* callback */, void* /* cb_data */) { inc_func_call_count(__func__); } diff --git a/system/test/mock/mock_bta_gatts_api.cc b/system/test/mock/mock_bta_gatts_api.cc index 85175b1c53c..1e3e7707488 100644 --- a/system/test/mock/mock_bta_gatts_api.cc +++ b/system/test/mock/mock_bta_gatts_api.cc @@ -33,47 +33,35 @@ #include "types/raw_address.h" void BTA_GATTS_Disable(void) { inc_func_call_count(__func__); } -void BTA_GATTS_AppDeregister(tGATT_IF /* server_if */) { - inc_func_call_count(__func__); -} -void BTA_GATTS_AppRegister(const bluetooth::Uuid& /* app_uuid */, - tBTA_GATTS_CBACK* /* p_cback */, +void BTA_GATTS_AppDeregister(tGATT_IF /* server_if */) { inc_func_call_count(__func__); } +void BTA_GATTS_AppRegister(const bluetooth::Uuid& /* app_uuid */, tBTA_GATTS_CBACK* /* p_cback */, bool /* eatt_support */) { inc_func_call_count(__func__); } -void BTA_GATTS_CancelOpen(tGATT_IF /* server_if */, - const RawAddress& /* remote_bda */, +void BTA_GATTS_CancelOpen(tGATT_IF /* server_if */, const RawAddress& /* remote_bda */, bool /* is_direct */) { inc_func_call_count(__func__); } void BTA_GATTS_Close(uint16_t /* conn_id */) { inc_func_call_count(__func__); } -void BTA_GATTS_AddService(tGATT_IF /* server_if */, - std::vector /* service */, +void BTA_GATTS_AddService(tGATT_IF /* server_if */, std::vector /* service */, BTA_GATTS_AddServiceCb /* cb */) { inc_func_call_count(__func__); } -void BTA_GATTS_DeleteService(uint16_t /* service_id */) { - inc_func_call_count(__func__); -} -void BTA_GATTS_HandleValueIndication(uint16_t /* conn_id */, - uint16_t /* attr_id */, - std::vector /* value */, - bool /* need_confirm */) { +void BTA_GATTS_DeleteService(uint16_t /* service_id */) { inc_func_call_count(__func__); } +void BTA_GATTS_HandleValueIndication(uint16_t /* conn_id */, uint16_t /* attr_id */, + std::vector /* value */, bool /* need_confirm */) { inc_func_call_count(__func__); } -void BTA_GATTS_Open(tGATT_IF /* server_if */, - const RawAddress& /* remote_bda */, +void BTA_GATTS_Open(tGATT_IF /* server_if */, const RawAddress& /* remote_bda */, tBLE_ADDR_TYPE /* addr_type */, bool /* is_direct */, tBT_TRANSPORT /* transport */) { inc_func_call_count(__func__); } -void BTA_GATTS_SendRsp(uint16_t /* conn_id */, uint32_t /* trans_id */, - tGATT_STATUS /* status */, tGATTS_RSP* /* p_msg */) { - inc_func_call_count(__func__); -} -void BTA_GATTS_StopService(uint16_t /* service_id */) { +void BTA_GATTS_SendRsp(uint16_t /* conn_id */, uint32_t /* trans_id */, tGATT_STATUS /* status */, + tGATTS_RSP* /* p_msg */) { inc_func_call_count(__func__); } +void BTA_GATTS_StopService(uint16_t /* service_id */) { inc_func_call_count(__func__); } void bta_gatts_add_service_impl(tGATT_IF /* server_if */, std::vector /* service */, BTA_GATTS_AddServiceCb /* cb */) { diff --git a/system/test/mock/mock_bta_groups.cc b/system/test/mock/mock_bta_groups.cc index c147db827e6..cd6a6374f6d 100644 --- a/system/test/mock/mock_bta_groups.cc +++ b/system/test/mock/mock_bta_groups.cc @@ -27,8 +27,7 @@ void DeviceGroups::AddFromStorage(const RawAddress& /* addr */, inc_func_call_count(__func__); } -bool DeviceGroups::GetForStorage(const RawAddress& /* addr */, - std::vector& /* out */) { +bool DeviceGroups::GetForStorage(const RawAddress& /* addr */, std::vector& /* out */) { inc_func_call_count(__func__); return false; } diff --git a/system/test/mock/mock_bta_has.cc b/system/test/mock/mock_bta_has.cc index 6825ef7280e..744004f3b7a 100644 --- a/system/test/mock/mock_bta_has.cc +++ b/system/test/mock/mock_bta_has.cc @@ -24,8 +24,7 @@ namespace bluetooth::le_audio { namespace has { -void HasClient::Initialize(bluetooth::has::HasClientCallbacks*, - base::RepeatingCallback) { +void HasClient::Initialize(bluetooth::has::HasClientCallbacks*, base::RepeatingCallback) { inc_func_call_count(__func__); } void HasClient::CleanUp() { inc_func_call_count(__func__); } @@ -34,8 +33,7 @@ bool HasClient::IsHasClientRunning() { inc_func_call_count(__func__); return false; } -void HasClient::AddFromStorage(RawAddress const&, unsigned char, - unsigned short) { +void HasClient::AddFromStorage(RawAddress const&, unsigned char, unsigned short) { inc_func_call_count(__func__); } HasClient* HasClient::Get() { diff --git a/system/test/mock/mock_bta_hd_api.cc b/system/test/mock/mock_bta_hd_api.cc index a8a8822cea3..cc7cbb466cd 100644 --- a/system/test/mock/mock_bta_hd_api.cc +++ b/system/test/mock/mock_bta_hd_api.cc @@ -23,28 +23,17 @@ #include "test/common/mock_functions.h" #include "types/raw_address.h" -void BTA_HdEnable(tBTA_HD_CBACK* /* p_cback */) { - inc_func_call_count(__func__); -} -void BTA_HdAddDevice(const RawAddress& /* addr */) { - inc_func_call_count(__func__); -} -void BTA_HdConnect(const RawAddress& /* addr */) { - inc_func_call_count(__func__); -} +void BTA_HdEnable(tBTA_HD_CBACK* /* p_cback */) { inc_func_call_count(__func__); } +void BTA_HdAddDevice(const RawAddress& /* addr */) { inc_func_call_count(__func__); } +void BTA_HdConnect(const RawAddress& /* addr */) { inc_func_call_count(__func__); } void BTA_HdDisable(void) { inc_func_call_count(__func__); } void BTA_HdDisconnect(void) { inc_func_call_count(__func__); } -void BTA_HdRegisterApp(tBTA_HD_APP_INFO* /* p_app_info */, - tBTA_HD_QOS_INFO* /* p_in_qos */, +void BTA_HdRegisterApp(tBTA_HD_APP_INFO* /* p_app_info */, tBTA_HD_QOS_INFO* /* p_in_qos */, tBTA_HD_QOS_INFO* /* p_out_qos */) { inc_func_call_count(__func__); } -void BTA_HdRemoveDevice(const RawAddress& /* addr */) { - inc_func_call_count(__func__); -} +void BTA_HdRemoveDevice(const RawAddress& /* addr */) { inc_func_call_count(__func__); } void BTA_HdReportError(uint8_t /* error */) { inc_func_call_count(__func__); } -void BTA_HdSendReport(tBTA_HD_REPORT* /* p_report */) { - inc_func_call_count(__func__); -} +void BTA_HdSendReport(tBTA_HD_REPORT* /* p_report */) { inc_func_call_count(__func__); } void BTA_HdUnregisterApp(void) { inc_func_call_count(__func__); } void BTA_HdVirtualCableUnplug(void) { inc_func_call_count(__func__); } diff --git a/system/test/mock/mock_bta_hearing_aid.cc b/system/test/mock/mock_bta_hearing_aid.cc index 2a05963384a..ea2a2f52b38 100644 --- a/system/test/mock/mock_bta_hearing_aid.cc +++ b/system/test/mock/mock_bta_hearing_aid.cc @@ -33,8 +33,7 @@ int HearingAid::GetDeviceCount() { return 0; } -void HearingAid::AddFromStorage(const HearingDevice& /* dev_info */, - bool /* is_acceptlisted */) { +void HearingAid::AddFromStorage(const HearingDevice& /* dev_info */, bool /* is_acceptlisted */) { inc_func_call_count(__func__); } @@ -47,24 +46,15 @@ bool HearingAid::IsHearingAidRunning() { void HearingAid::CleanUp() { inc_func_call_count(__func__); } -void HearingAid::Initialize( - bluetooth::hearing_aid::HearingAidCallbacks* /* callbacks */, - base::Closure /* initCb */) { +void HearingAid::Initialize(bluetooth::hearing_aid::HearingAidCallbacks* /* callbacks */, + base::Closure /* initCb */) { inc_func_call_count(__func__); } -void HearingAid::Connect(const RawAddress& /* address */) { - inc_func_call_count(__func__); -} +void HearingAid::Connect(const RawAddress& /* address */) { inc_func_call_count(__func__); } -void HearingAid::Disconnect(const RawAddress& /* address */) { - inc_func_call_count(__func__); -} +void HearingAid::Disconnect(const RawAddress& /* address */) { inc_func_call_count(__func__); } -void HearingAid::AddToAcceptlist(const RawAddress& /* address */) { - inc_func_call_count(__func__); -} +void HearingAid::AddToAcceptlist(const RawAddress& /* address */) { inc_func_call_count(__func__); } -void HearingAid::SetVolume(int8_t /* volume */) { - inc_func_call_count(__func__); -} +void HearingAid::SetVolume(int8_t /* volume */) { inc_func_call_count(__func__); } diff --git a/system/test/mock/mock_bta_hf_client_api.cc b/system/test/mock/mock_bta_hf_client_api.cc index 78ad53febda..db57268abb3 100644 --- a/system/test/mock/mock_bta_hf_client_api.cc +++ b/system/test/mock/mock_bta_hf_client_api.cc @@ -32,24 +32,17 @@ tBTA_STATUS BTA_HfClientEnable(tBTA_HF_CLIENT_CBACK* /* p_cback */, inc_func_call_count(__func__); return BTA_SUCCESS; } -void BTA_HfClientAudioClose(uint16_t /* handle */) { - inc_func_call_count(__func__); -} -void BTA_HfClientAudioOpen(uint16_t /* handle */) { - inc_func_call_count(__func__); -} +void BTA_HfClientAudioClose(uint16_t /* handle */) { inc_func_call_count(__func__); } +void BTA_HfClientAudioOpen(uint16_t /* handle */) { inc_func_call_count(__func__); } void BTA_HfClientClose(uint16_t /* handle */) { inc_func_call_count(__func__); } void BTA_HfClientDisable(void) { inc_func_call_count(__func__); } void BTA_HfClientDumpStatistics(int /* fd */) { inc_func_call_count(__func__); } -bt_status_t BTA_HfClientOpen(const RawAddress& /* bd_addr */, - uint16_t* /* p_handle */) { +bt_status_t BTA_HfClientOpen(const RawAddress& /* bd_addr */, uint16_t* /* p_handle */) { inc_func_call_count(__func__); return BT_STATUS_SUCCESS; } -void BTA_HfClientSendAT(uint16_t /* handle */, - tBTA_HF_CLIENT_AT_CMD_TYPE /* at */, - uint32_t /* val1 */, uint32_t /* val2 */, - const char* /* str */) { +void BTA_HfClientSendAT(uint16_t /* handle */, tBTA_HF_CLIENT_AT_CMD_TYPE /* at */, + uint32_t /* val1 */, uint32_t /* val2 */, const char* /* str */) { inc_func_call_count(__func__); } int get_default_hf_client_features() { diff --git a/system/test/mock/mock_bta_hh_api.cc b/system/test/mock/mock_bta_hh_api.cc index e0f98e48990..e2013241754 100644 --- a/system/test/mock/mock_bta_hh_api.cc +++ b/system/test/mock/mock_bta_hh_api.cc @@ -28,55 +28,44 @@ using namespace bluetooth; const Uuid ANDROID_HEADTRACKER_SERVICE_UUID = - Uuid::FromString(ANDROID_HEADTRACKER_SERVICE_UUID_STRING); + Uuid::FromString(ANDROID_HEADTRACKER_SERVICE_UUID_STRING); const Uuid ANDROID_HEADTRACKER_VERSION_CHARAC_UUID = - Uuid::FromString(ANDROID_HEADTRACKER_VERSION_CHARAC_UUID_STRING); + Uuid::FromString(ANDROID_HEADTRACKER_VERSION_CHARAC_UUID_STRING); const Uuid ANDROID_HEADTRACKER_CONTROL_CHARAC_UUID = - Uuid::FromString(ANDROID_HEADTRACKER_CONTROL_CHARAC_UUID_STRING); + Uuid::FromString(ANDROID_HEADTRACKER_CONTROL_CHARAC_UUID_STRING); const Uuid ANDROID_HEADTRACKER_REPORT_CHARAC_UUID = - Uuid::FromString(ANDROID_HEADTRACKER_REPORT_CHARAC_UUID_STRING); + Uuid::FromString(ANDROID_HEADTRACKER_REPORT_CHARAC_UUID_STRING); -void BTA_HhEnable(tBTA_HH_CBACK* /* p_cback */, bool /* enable_hidp */, - bool /* enable_hogp */) { +void BTA_HhEnable(tBTA_HH_CBACK* /* p_cback */, bool /* enable_hidp */, bool /* enable_hogp */) { inc_func_call_count(__func__); } -void BTA_HhAddDev(const tAclLinkSpec& /* link_spec */, - tBTA_HH_ATTR_MASK /* attr_mask */, uint8_t /* sub_class */, - uint8_t /* app_id */, tBTA_HH_DEV_DSCP_INFO /* dscp_info */) { +void BTA_HhAddDev(const tAclLinkSpec& /* link_spec */, tBTA_HH_ATTR_MASK /* attr_mask */, + uint8_t /* sub_class */, uint8_t /* app_id */, + tBTA_HH_DEV_DSCP_INFO /* dscp_info */) { inc_func_call_count(__func__); } void BTA_HhClose(uint8_t /* dev_handle */) { inc_func_call_count(__func__); } void BTA_HhDisable(void) { inc_func_call_count(__func__); } -void BTA_HhGetDscpInfo(uint8_t /* dev_handle */) { - inc_func_call_count(__func__); -} +void BTA_HhGetDscpInfo(uint8_t /* dev_handle */) { inc_func_call_count(__func__); } void BTA_HhGetIdle(uint8_t /* dev_handle */) { inc_func_call_count(__func__); } -void BTA_HhGetProtoMode(uint8_t /* dev_handle */) { - inc_func_call_count(__func__); -} -void BTA_HhGetReport(uint8_t /* dev_handle */, tBTA_HH_RPT_TYPE /* r_type */, - uint8_t /* rpt_id */, uint16_t /* buf_size */) { - inc_func_call_count(__func__); -} -void BTA_HhOpen(const tAclLinkSpec& /* link_spec */) { - inc_func_call_count(__func__); -} -void BTA_HhRemoveDev(uint8_t /* dev_handle */) { +void BTA_HhGetProtoMode(uint8_t /* dev_handle */) { inc_func_call_count(__func__); } +void BTA_HhGetReport(uint8_t /* dev_handle */, tBTA_HH_RPT_TYPE /* r_type */, uint8_t /* rpt_id */, + uint16_t /* buf_size */) { inc_func_call_count(__func__); } -void BTA_HhSendCtrl(uint8_t /* dev_handle */, - tBTA_HH_TRANS_CTRL_TYPE /* c_type */) { +void BTA_HhOpen(const tAclLinkSpec& /* link_spec */) { inc_func_call_count(__func__); } +void BTA_HhRemoveDev(uint8_t /* dev_handle */) { inc_func_call_count(__func__); } +void BTA_HhSendCtrl(uint8_t /* dev_handle */, tBTA_HH_TRANS_CTRL_TYPE /* c_type */) { inc_func_call_count(__func__); } -void BTA_HhSendData(uint8_t /* dev_handle */, - const tAclLinkSpec& /* link_spec */, BT_HDR* /* p_data */) { +void BTA_HhSendData(uint8_t /* dev_handle */, const tAclLinkSpec& /* link_spec */, + BT_HDR* /* p_data */) { inc_func_call_count(__func__); } void BTA_HhSetIdle(uint8_t /* dev_handle */, uint16_t /* idle_rate */) { inc_func_call_count(__func__); } -void BTA_HhSetProtoMode(uint8_t /* dev_handle */, - tBTA_HH_PROTO_MODE /* p_type */) { +void BTA_HhSetProtoMode(uint8_t /* dev_handle */, tBTA_HH_PROTO_MODE /* p_type */) { inc_func_call_count(__func__); } void BTA_HhSetReport(uint8_t /* dev_handle */, tBTA_HH_RPT_TYPE /* r_type */, diff --git a/system/test/mock/mock_bta_hh_utils.cc b/system/test/mock/mock_bta_hh_utils.cc index 2d7a8bc9725..b48524f4fb9 100644 --- a/system/test/mock/mock_bta_hh_utils.cc +++ b/system/test/mock/mock_bta_hh_utils.cc @@ -52,15 +52,12 @@ struct bta_hh_le_is_hh_gatt_if bta_hh_le_is_hh_gatt_if; } // namespace test // Mocked functions, if any -void bta_hh_add_device_to_list(tBTA_HH_DEV_CB* p_cb, uint8_t handle, - uint16_t attr_mask, - const tHID_DEV_DSCP_INFO* p_dscp_info, - uint8_t sub_class, uint16_t ssr_max_latency, - uint16_t ssr_min_tout, uint8_t app_id) { +void bta_hh_add_device_to_list(tBTA_HH_DEV_CB* p_cb, uint8_t handle, uint16_t attr_mask, + const tHID_DEV_DSCP_INFO* p_dscp_info, uint8_t sub_class, + uint16_t ssr_max_latency, uint16_t ssr_min_tout, uint8_t app_id) { inc_func_call_count(__func__); test::mock::bta_hh_utils::bta_hh_add_device_to_list( - p_cb, handle, attr_mask, p_dscp_info, sub_class, ssr_max_latency, - ssr_min_tout, app_id); + p_cb, handle, attr_mask, p_dscp_info, sub_class, ssr_max_latency, ssr_min_tout, app_id); } void bta_hh_clean_up_kdev(tBTA_HH_DEV_CB* p_cb) { inc_func_call_count(__func__); @@ -82,12 +79,10 @@ tBTA_HH_DEV_CB* bta_hh_get_cb(const tAclLinkSpec& link_spec) { inc_func_call_count(__func__); return test::mock::bta_hh_utils::bta_hh_get_cb(link_spec); } -tBTA_HH_STATUS bta_hh_read_ssr_param(const tAclLinkSpec& link_spec, - uint16_t* p_max_ssr_lat, +tBTA_HH_STATUS bta_hh_read_ssr_param(const tAclLinkSpec& link_spec, uint16_t* p_max_ssr_lat, uint16_t* p_min_ssr_tout) { inc_func_call_count(__func__); - return test::mock::bta_hh_utils::bta_hh_read_ssr_param( - link_spec, p_max_ssr_lat, p_min_ssr_tout); + return test::mock::bta_hh_utils::bta_hh_read_ssr_param(link_spec, p_max_ssr_lat, p_min_ssr_tout); } bool bta_hh_tod_spt(tBTA_HH_DEV_CB* p_cb, uint8_t sub_class) { inc_func_call_count(__func__); @@ -97,12 +92,11 @@ void bta_hh_trace_dev_db(void) { inc_func_call_count(__func__); test::mock::bta_hh_utils::bta_hh_trace_dev_db(); } -void bta_hh_update_di_info(tBTA_HH_DEV_CB* p_cb, uint16_t vendor_id, - uint16_t product_id, uint16_t version, uint8_t flag, - uint8_t ctry_code) { +void bta_hh_update_di_info(tBTA_HH_DEV_CB* p_cb, uint16_t vendor_id, uint16_t product_id, + uint16_t version, uint8_t flag, uint8_t ctry_code) { inc_func_call_count(__func__); - test::mock::bta_hh_utils::bta_hh_update_di_info(p_cb, vendor_id, product_id, - version, flag, ctry_code); + test::mock::bta_hh_utils::bta_hh_update_di_info(p_cb, vendor_id, product_id, version, flag, + ctry_code); } bool bta_hh_le_is_hh_gatt_if(tGATT_IF client_if) { inc_func_call_count(__func__); diff --git a/system/test/mock/mock_bta_hh_utils.h b/system/test/mock/mock_bta_hh_utils.h index f3d2fcece1f..2e587af1dd1 100644 --- a/system/test/mock/mock_bta_hh_utils.h +++ b/system/test/mock/mock_bta_hh_utils.h @@ -42,20 +42,16 @@ namespace bta_hh_utils { struct bta_hh_add_device_to_list { std::function - body{[](tBTA_HH_DEV_CB* /* p_cb */, uint8_t /* handle */, - uint16_t /* attr_mask */, - const tHID_DEV_DSCP_INFO* /* p_dscp_info */, - uint8_t /* sub_class */, uint16_t /* ssr_max_latency */, - uint16_t /* ssr_min_tout */, uint8_t /* app_id */) {}}; + uint16_t ssr_max_latency, uint16_t ssr_min_tout, uint8_t app_id)> + body{[](tBTA_HH_DEV_CB* /* p_cb */, uint8_t /* handle */, uint16_t /* attr_mask */, + const tHID_DEV_DSCP_INFO* /* p_dscp_info */, uint8_t /* sub_class */, + uint16_t /* ssr_max_latency */, uint16_t /* ssr_min_tout */, + uint8_t /* app_id */) {}}; void operator()(tBTA_HH_DEV_CB* p_cb, uint8_t handle, uint16_t attr_mask, const tHID_DEV_DSCP_INFO* p_dscp_info, uint8_t sub_class, - uint16_t ssr_max_latency, uint16_t ssr_min_tout, - uint8_t app_id) { - body(p_cb, handle, attr_mask, p_dscp_info, sub_class, ssr_max_latency, - ssr_min_tout, app_id); - }; + uint16_t ssr_max_latency, uint16_t ssr_min_tout, uint8_t app_id) { + body(p_cb, handle, attr_mask, p_dscp_info, sub_class, ssr_max_latency, ssr_min_tout, app_id); + } }; extern struct bta_hh_add_device_to_list bta_hh_add_device_to_list; @@ -63,9 +59,8 @@ extern struct bta_hh_add_device_to_list bta_hh_add_device_to_list; // Params: tBTA_HH_DEV_CB* p_cb // Return: void struct bta_hh_clean_up_kdev { - std::function body{ - [](tBTA_HH_DEV_CB* /* p_cb */) {}}; - void operator()(tBTA_HH_DEV_CB* p_cb) { body(p_cb); }; + std::function body{[](tBTA_HH_DEV_CB* /* p_cb */) {}}; + void operator()(tBTA_HH_DEV_CB* p_cb) { body(p_cb); } }; extern struct bta_hh_clean_up_kdev bta_hh_clean_up_kdev; @@ -73,9 +68,8 @@ extern struct bta_hh_clean_up_kdev bta_hh_clean_up_kdev; // Params: tBTA_HH_STATUS status // Return: void struct bta_hh_cleanup_disable { - std::function body{ - [](tBTA_HH_STATUS /* status */) {}}; - void operator()(tBTA_HH_STATUS status) { body(status); }; + std::function body{[](tBTA_HH_STATUS /* status */) {}}; + void operator()(tBTA_HH_STATUS status) { body(status); } }; extern struct bta_hh_cleanup_disable bta_hh_cleanup_disable; @@ -85,8 +79,8 @@ extern struct bta_hh_cleanup_disable bta_hh_cleanup_disable; struct bta_hh_dev_handle_to_cb_idx { uint8_t return_value{0}; std::function body{ - [this](uint8_t /* dev_handle */) { return return_value; }}; - uint8_t operator()(uint8_t dev_handle) { return body(dev_handle); }; + [this](uint8_t /* dev_handle */) { return return_value; }}; + uint8_t operator()(uint8_t dev_handle) { return body(dev_handle); } }; extern struct bta_hh_dev_handle_to_cb_idx bta_hh_dev_handle_to_cb_idx; @@ -96,8 +90,8 @@ extern struct bta_hh_dev_handle_to_cb_idx bta_hh_dev_handle_to_cb_idx; struct bta_hh_find_cb { uint8_t return_value{0}; std::function body{ - [this](const tAclLinkSpec& /* link_spec */) { return return_value; }}; - uint8_t operator()(const tAclLinkSpec& link_spec) { return body(link_spec); }; + [this](const tAclLinkSpec& /* link_spec */) { return return_value; }}; + uint8_t operator()(const tAclLinkSpec& link_spec) { return body(link_spec); } }; extern struct bta_hh_find_cb bta_hh_find_cb; @@ -107,10 +101,8 @@ extern struct bta_hh_find_cb bta_hh_find_cb; struct bta_hh_get_cb { tBTA_HH_DEV_CB* return_value{0}; std::function body{ - [this](const tAclLinkSpec& /* link_spec */) { return return_value; }}; - tBTA_HH_DEV_CB* operator()(const tAclLinkSpec& link_spec) { - return body(link_spec); - }; + [this](const tAclLinkSpec& /* link_spec */) { return return_value; }}; + tBTA_HH_DEV_CB* operator()(const tAclLinkSpec& link_spec) { return body(link_spec); } }; extern struct bta_hh_get_cb bta_hh_get_cb; @@ -119,16 +111,14 @@ extern struct bta_hh_get_cb bta_hh_get_cb; // p_min_ssr_tout Return: tBTA_HH_STATUS struct bta_hh_read_ssr_param { tBTA_HH_STATUS return_value{0}; - std::function - body{[this](const tAclLinkSpec& /* link_spec */, - uint16_t* /* p_max_ssr_lat */, - uint16_t* /* p_min_ssr_tout */) { return return_value; }}; - tBTA_HH_STATUS operator()(const tAclLinkSpec& link_spec, - uint16_t* p_max_ssr_lat, uint16_t* p_min_ssr_tout) { + body{[this](const tAclLinkSpec& /* link_spec */, uint16_t* /* p_max_ssr_lat */, + uint16_t* /* p_min_ssr_tout */) { return return_value; }}; + tBTA_HH_STATUS operator()(const tAclLinkSpec& link_spec, uint16_t* p_max_ssr_lat, + uint16_t* p_min_ssr_tout) { return body(link_spec, p_max_ssr_lat, p_min_ssr_tout); - }; + } }; extern struct bta_hh_read_ssr_param bta_hh_read_ssr_param; @@ -138,12 +128,8 @@ extern struct bta_hh_read_ssr_param bta_hh_read_ssr_param; struct bta_hh_tod_spt { bool return_value{false}; std::function body{ - [this](tBTA_HH_DEV_CB* /* p_cb */, uint8_t /* sub_class */) { - return return_value; - }}; - bool operator()(tBTA_HH_DEV_CB* p_cb, uint8_t sub_class) { - return body(p_cb, sub_class); - }; + [this](tBTA_HH_DEV_CB* /* p_cb */, uint8_t /* sub_class */) { return return_value; }}; + bool operator()(tBTA_HH_DEV_CB* p_cb, uint8_t sub_class) { return body(p_cb, sub_class); } }; extern struct bta_hh_tod_spt bta_hh_tod_spt; @@ -152,7 +138,7 @@ extern struct bta_hh_tod_spt bta_hh_tod_spt; // Return: void struct bta_hh_trace_dev_db { std::function body{[](void) {}}; - void operator()(void) { body(); }; + void operator()(void) { body(); } }; extern struct bta_hh_trace_dev_db bta_hh_trace_dev_db; @@ -160,16 +146,14 @@ extern struct bta_hh_trace_dev_db bta_hh_trace_dev_db; // Params: tBTA_HH_DEV_CB* p_cb, uint16_t vendor_id, uint16_t product_id, // uint16_t version, uint8_t flag Return: void struct bta_hh_update_di_info { - std::function - body{[](tBTA_HH_DEV_CB* /* p_cb */, uint16_t /* vendor_id */, - uint16_t /* product_id */, uint16_t /* version */, - uint8_t /* flag */, uint8_t /* ctry_code */) {}}; - void operator()(tBTA_HH_DEV_CB* p_cb, uint16_t vendor_id, uint16_t product_id, - uint16_t version, uint8_t flag, uint8_t ctry_code) { + std::function + body{[](tBTA_HH_DEV_CB* /* p_cb */, uint16_t /* vendor_id */, uint16_t /* product_id */, + uint16_t /* version */, uint8_t /* flag */, uint8_t /* ctry_code */) {}}; + void operator()(tBTA_HH_DEV_CB* p_cb, uint16_t vendor_id, uint16_t product_id, uint16_t version, + uint8_t flag, uint8_t ctry_code) { body(p_cb, vendor_id, product_id, version, flag, ctry_code); - }; + } }; extern struct bta_hh_update_di_info bta_hh_update_di_info; @@ -179,8 +163,8 @@ extern struct bta_hh_update_di_info bta_hh_update_di_info; struct bta_hh_le_is_hh_gatt_if { bool return_value{false}; std::function body{ - [this](tGATT_IF /* client_if */) { return return_value; }}; - bool operator()(tGATT_IF client_if) { return body(client_if); }; + [this](tGATT_IF /* client_if */) { return return_value; }}; + bool operator()(tGATT_IF client_if) { return body(client_if); } }; extern struct bta_hh_le_is_hh_gatt_if bta_hh_le_is_hh_gatt_if; diff --git a/system/test/mock/mock_bta_jv_api.cc b/system/test/mock/mock_bta_jv_api.cc index cb3f02bad76..d8362c129b5 100644 --- a/system/test/mock/mock_bta_jv_api.cc +++ b/system/test/mock/mock_bta_jv_api.cc @@ -43,8 +43,7 @@ tBTA_JV_STATUS BTA_JvEnable(tBTA_JV_DM_CBACK* /* p_cback */) { inc_func_call_count(__func__); return tBTA_JV_STATUS::SUCCESS; } -tBTA_JV_STATUS BTA_JvFreeChannel(uint16_t /* channel */, - tBTA_JV_CONN_TYPE /* conn_type */) { +tBTA_JV_STATUS BTA_JvFreeChannel(uint16_t /* channel */, tBTA_JV_CONN_TYPE /* conn_type */) { inc_func_call_count(__func__); return tBTA_JV_STATUS::SUCCESS; } @@ -52,49 +51,43 @@ tBTA_JV_STATUS BTA_JvL2capClose(uint32_t /* handle */) { inc_func_call_count(__func__); return tBTA_JV_STATUS::SUCCESS; } -tBTA_JV_STATUS BTA_JvL2capRead(uint32_t /* handle */, uint32_t /* req_id */, - uint8_t* /* p_data */, uint16_t /* len */) { +tBTA_JV_STATUS BTA_JvL2capRead(uint32_t /* handle */, uint32_t /* req_id */, uint8_t* /* p_data */, + uint16_t /* len */) { inc_func_call_count(__func__); return tBTA_JV_STATUS::SUCCESS; } -tBTA_JV_STATUS BTA_JvL2capReady(uint32_t /* handle */, - uint32_t* /* p_data_size */) { +tBTA_JV_STATUS BTA_JvL2capReady(uint32_t /* handle */, uint32_t* /* p_data_size */) { inc_func_call_count(__func__); return tBTA_JV_STATUS::SUCCESS; } -tBTA_JV_STATUS BTA_JvL2capStopServer(uint16_t /* local_psm */, - uint32_t /* l2cap_socket_id */) { +tBTA_JV_STATUS BTA_JvL2capStopServer(uint16_t /* local_psm */, uint32_t /* l2cap_socket_id */) { inc_func_call_count(__func__); return tBTA_JV_STATUS::SUCCESS; } -tBTA_JV_STATUS BTA_JvL2capWrite(uint32_t /* handle */, uint32_t /* req_id */, - BT_HDR* /* msg */, uint32_t /* user_id */) { +tBTA_JV_STATUS BTA_JvL2capWrite(uint32_t /* handle */, uint32_t /* req_id */, BT_HDR* /* msg */, + uint32_t /* user_id */) { inc_func_call_count(__func__); return tBTA_JV_STATUS::SUCCESS; } -tBTA_JV_STATUS BTA_JvRfcommClose(uint32_t /* handle */, - uint32_t /* rfcomm_slot_id */) { +tBTA_JV_STATUS BTA_JvRfcommClose(uint32_t /* handle */, uint32_t /* rfcomm_slot_id */) { inc_func_call_count(__func__); return tBTA_JV_STATUS::SUCCESS; } -tBTA_JV_STATUS BTA_JvRfcommConnect(tBTA_SEC /* sec_mask */, - uint8_t /* remote_scn */, +tBTA_JV_STATUS BTA_JvRfcommConnect(tBTA_SEC /* sec_mask */, uint8_t /* remote_scn */, const RawAddress& /* peer_bd_addr */, tBTA_JV_RFCOMM_CBACK* /* p_cback */, uint32_t /* rfcomm_slot_id */) { inc_func_call_count(__func__); return tBTA_JV_STATUS::SUCCESS; } -tBTA_JV_STATUS BTA_JvRfcommStartServer(tBTA_SEC /* sec_mask */, - uint8_t /* local_scn */, +tBTA_JV_STATUS BTA_JvRfcommStartServer(tBTA_SEC /* sec_mask */, uint8_t /* local_scn */, uint8_t /* max_session */, tBTA_JV_RFCOMM_CBACK* /* p_cback */, uint32_t /* rfcomm_slot_id */) { inc_func_call_count(__func__); return tBTA_JV_STATUS::SUCCESS; } -tBTA_JV_STATUS BTA_JvRfcommStopServer(uint32_t /* handle */, - uint32_t /* rfcomm_slot_id */) { +tBTA_JV_STATUS BTA_JvRfcommStopServer(uint32_t /* handle */, uint32_t /* rfcomm_slot_id */) { inc_func_call_count(__func__); return tBTA_JV_STATUS::SUCCESS; } @@ -102,14 +95,12 @@ tBTA_JV_STATUS BTA_JvRfcommWrite(uint32_t /* handle */, uint32_t /* req_id */) { inc_func_call_count(__func__); return tBTA_JV_STATUS::SUCCESS; } -tBTA_JV_STATUS BTA_JvSetPmProfile(uint32_t /* handle */, - tBTA_JV_PM_ID /* app_id */, +tBTA_JV_STATUS BTA_JvSetPmProfile(uint32_t /* handle */, tBTA_JV_PM_ID /* app_id */, tBTA_JV_CONN_STATE /* init_st */) { inc_func_call_count(__func__); return tBTA_JV_STATUS::SUCCESS; } -tBTA_JV_STATUS BTA_JvStartDiscovery(const RawAddress& /* bd_addr */, - uint16_t /* num_uuid */, +tBTA_JV_STATUS BTA_JvStartDiscovery(const RawAddress& /* bd_addr */, uint16_t /* num_uuid */, const bluetooth::Uuid* /* p_uuid_list */, uint32_t /* rfcomm_slot_id */) { inc_func_call_count(__func__); @@ -124,22 +115,18 @@ void BTA_JvGetChannelId(tBTA_JV_CONN_TYPE /* conn_type */, uint32_t /* id */, int32_t /* channel */) { inc_func_call_count(__func__); } -void BTA_JvL2capConnect(tBTA_JV_CONN_TYPE /* conn_type */, - tBTA_SEC /* sec_mask */, +void BTA_JvL2capConnect(tBTA_JV_CONN_TYPE /* conn_type */, tBTA_SEC /* sec_mask */, std::unique_ptr /* ertm_info */, uint16_t /* remote_psm */, uint16_t /* rx_mtu */, std::unique_ptr /* cfg */, - const RawAddress& /* peer_bd_addr */, - tBTA_JV_L2CAP_CBACK* /* p_cback */, + const RawAddress& /* peer_bd_addr */, tBTA_JV_L2CAP_CBACK* /* p_cback */, uint32_t /* l2cap_socket_id */) { inc_func_call_count(__func__); } -void BTA_JvL2capStartServer(tBTA_JV_CONN_TYPE /* conn_type */, - tBTA_SEC /* sec_mask */, +void BTA_JvL2capStartServer(tBTA_JV_CONN_TYPE /* conn_type */, tBTA_SEC /* sec_mask */, std::unique_ptr /* ertm_info */, uint16_t /* local_psm */, uint16_t /* rx_mtu */, std::unique_ptr /* cfg */, - tBTA_JV_L2CAP_CBACK* /* p_cback */, - uint32_t /* l2cap_socket_id */) { + tBTA_JV_L2CAP_CBACK* /* p_cback */, uint32_t /* l2cap_socket_id */) { inc_func_call_count(__func__); } diff --git a/system/test/mock/mock_bta_leaudio.cc b/system/test/mock/mock_bta_leaudio.cc index 41a96436584..2b5aeb8ff9b 100644 --- a/system/test/mock/mock_bta_leaudio.cc +++ b/system/test/mock/mock_bta_leaudio.cc @@ -35,21 +35,20 @@ namespace audio { class HalVersionManager { static inline std::unique_ptr instance_ptr = - std::make_unique(); + std::make_unique(); }; } // namespace audio } // namespace bluetooth -void LeAudioClient::AddFromStorage( - const RawAddress& /* addr */, bool /* autoconnect */, - int /* sink_audio_location */, int /* source_audio_location */, - int /* sink_supported_context_types */, - int /* source_supported_context_types */, - const std::vector& /* handles */, - const std::vector& /* sink_pacs */, - const std::vector& /* source_pacs */, - const std::vector& /* ases */) { +void LeAudioClient::AddFromStorage(const RawAddress& /* addr */, bool /* autoconnect */, + int /* sink_audio_location */, int /* source_audio_location */, + int /* sink_supported_context_types */, + int /* source_supported_context_types */, + const std::vector& /* handles */, + const std::vector& /* sink_pacs */, + const std::vector& /* source_pacs */, + const std::vector& /* ases */) { inc_func_call_count(__func__); } @@ -91,17 +90,16 @@ bool LeAudioClient::IsLeAudioClientInStreaming(void) { inc_func_call_count(__func__); return false; } -void LeAudioClient::Initialize( - bluetooth::le_audio::LeAudioClientCallbacks* /* callbacks_ */, - base::Closure /* initCb */, base::Callback /* hal_2_1_verifier */, - const std::vector& - /* offloading_preference */) { +void LeAudioClient::Initialize(bluetooth::le_audio::LeAudioClientCallbacks* /* callbacks_ */, + base::Closure /* initCb */, + base::Callback /* hal_2_1_verifier */, + const std::vector& + /* offloading_preference */) { inc_func_call_count(__func__); } void LeAudioClient::DebugDump(int /* fd */) { inc_func_call_count(__func__); } -bool LeAudioClient::RegisterIsoDataConsumer( - LeAudioIsoDataCallback /* callback */) { +bool LeAudioClient::RegisterIsoDataConsumer(LeAudioIsoDataCallback /* callback */) { inc_func_call_count(__func__); return true; } diff --git a/system/test/mock/mock_bta_leaudio_broadcaster.cc b/system/test/mock/mock_bta_leaudio_broadcaster.cc index 2b84db28552..c47cf5af0ee 100644 --- a/system/test/mock/mock_bta_leaudio_broadcaster.cc +++ b/system/test/mock/mock_bta_leaudio_broadcaster.cc @@ -22,9 +22,8 @@ #include "test/common/mock_functions.h" void LeAudioBroadcaster::DebugDump(int) { inc_func_call_count(__func__); } -void LeAudioBroadcaster::Initialize( - bluetooth::le_audio::LeAudioBroadcasterCallbacks*, - base::RepeatingCallback) { +void LeAudioBroadcaster::Initialize(bluetooth::le_audio::LeAudioBroadcasterCallbacks*, + base::RepeatingCallback) { inc_func_call_count(__func__); } void LeAudioBroadcaster::Stop() { inc_func_call_count(__func__); } diff --git a/system/test/mock/mock_bta_pan_api.cc b/system/test/mock/mock_bta_pan_api.cc index 782ce29c50a..4f353f3aa17 100644 --- a/system/test/mock/mock_bta_pan_api.cc +++ b/system/test/mock/mock_bta_pan_api.cc @@ -27,16 +27,12 @@ void BTA_PanClose(uint16_t /* handle */) { inc_func_call_count(__func__); } void BTA_PanDisable(void) { inc_func_call_count(__func__); } -void BTA_PanEnable(tBTA_PAN_CBACK /* p_cback */) { - inc_func_call_count(__func__); -} -void BTA_PanOpen(const RawAddress& /* bd_addr */, - tBTA_PAN_ROLE /* local_role */, +void BTA_PanEnable(tBTA_PAN_CBACK /* p_cback */) { inc_func_call_count(__func__); } +void BTA_PanOpen(const RawAddress& /* bd_addr */, tBTA_PAN_ROLE /* local_role */, tBTA_PAN_ROLE /* peer_role */) { inc_func_call_count(__func__); } -void BTA_PanSetRole(tBTA_PAN_ROLE /* role */, - const tBTA_PAN_ROLE_INFO /* p_user_info */, +void BTA_PanSetRole(tBTA_PAN_ROLE /* role */, const tBTA_PAN_ROLE_INFO /* p_user_info */, const tBTA_PAN_ROLE_INFO /* p_nap_info */) { inc_func_call_count(__func__); } diff --git a/system/test/mock/mock_bta_pan_ci.cc b/system/test/mock/mock_bta_pan_ci.cc index 270ab0cee56..1b75c364a62 100644 --- a/system/test/mock/mock_bta_pan_ci.cc +++ b/system/test/mock/mock_bta_pan_ci.cc @@ -23,30 +23,21 @@ #include "test/common/mock_functions.h" #include "types/raw_address.h" -BT_HDR* bta_pan_ci_readbuf(uint16_t /* handle */, RawAddress& /* src */, - RawAddress& /* dst */, uint16_t* /* p_protocol */, - bool* /* p_ext */, bool* /* p_forward */) { +BT_HDR* bta_pan_ci_readbuf(uint16_t /* handle */, RawAddress& /* src */, RawAddress& /* dst */, + uint16_t* /* p_protocol */, bool* /* p_ext */, bool* /* p_forward */) { inc_func_call_count(__func__); return nullptr; } -void bta_pan_ci_rx_ready(uint16_t /* handle */) { - inc_func_call_count(__func__); -} +void bta_pan_ci_rx_ready(uint16_t /* handle */) { inc_func_call_count(__func__); } void bta_pan_ci_rx_write(uint16_t /* handle */, const RawAddress& /* dst */, const RawAddress& /* src */, uint16_t /* protocol */, - uint8_t* /* p_data */, uint16_t /* len */, - bool /* ext */) { + uint8_t* /* p_data */, uint16_t /* len */, bool /* ext */) { inc_func_call_count(__func__); } void bta_pan_ci_rx_writebuf(uint16_t /* handle */, const RawAddress& /* dst */, - const RawAddress& /* src */, - uint16_t /* protocol */, BT_HDR* /* p_buf */, - bool /* ext */) { - inc_func_call_count(__func__); -} -void bta_pan_ci_tx_flow(uint16_t /* handle */, bool /* enable */) { - inc_func_call_count(__func__); -} -void bta_pan_ci_tx_ready(uint16_t /* handle */) { + const RawAddress& /* src */, uint16_t /* protocol */, + BT_HDR* /* p_buf */, bool /* ext */) { inc_func_call_count(__func__); } +void bta_pan_ci_tx_flow(uint16_t /* handle */, bool /* enable */) { inc_func_call_count(__func__); } +void bta_pan_ci_tx_ready(uint16_t /* handle */) { inc_func_call_count(__func__); } diff --git a/system/test/mock/mock_bta_ras_client.cc b/system/test/mock/mock_bta_ras_client.cc index 693c387b964..f134e000708 100644 --- a/system/test/mock/mock_bta_ras_client.cc +++ b/system/test/mock/mock_bta_ras_client.cc @@ -18,15 +18,12 @@ class MockRasClient : public bluetooth::ras::RasClient { void Initialize() override {} - void RegisterCallbacks( - bluetooth::ras::RasClientCallbacks* /* callbacks */) override{}; - void Connect(const RawAddress& /* address */) override{}; + void RegisterCallbacks(bluetooth::ras::RasClientCallbacks* /* callbacks */) override {} + void Connect(const RawAddress& /* address */) override {} void SendVendorSpecificReply( - const RawAddress& /* address */, - const std::vector< - bluetooth::ras:: - VendorSpecificCharacteristic>& /*vendor_specific_data*/) - override{}; + const RawAddress& /* address */, + const std::vector& /*vendor_specific_data*/) + override {} }; namespace bluetooth { diff --git a/system/test/mock/mock_bta_ras_server.cc b/system/test/mock/mock_bta_ras_server.cc index c26386108c4..d9035ede492 100644 --- a/system/test/mock/mock_bta_ras_server.cc +++ b/system/test/mock/mock_bta_ras_server.cc @@ -18,16 +18,13 @@ class MockRasServer : public bluetooth::ras::RasServer { void Initialize() override {} - void RegisterCallbacks( - bluetooth::ras::RasServerCallbacks* /* callbacks */) override {} - void HandleVendorSpecificReplyComplete(RawAddress /* address */, - bool /* success */) override {} - void PushProcedureData(RawAddress /* address */, - uint16_t /* procedure_count */, bool /* is_last */, - std::vector /* data */) override {} + void RegisterCallbacks(bluetooth::ras::RasServerCallbacks* /* callbacks */) override {} + void HandleVendorSpecificReplyComplete(RawAddress /* address */, bool /* success */) override {} + void PushProcedureData(RawAddress /* address */, uint16_t /* procedure_count */, + bool /* is_last */, std::vector /* data */) override {} void SetVendorSpecificCharacteristic( - const std::vector& - /* vendor_specific_characteristics */) override {} + const std::vector& + /* vendor_specific_characteristics */) override {} }; namespace bluetooth { diff --git a/system/test/mock/mock_bta_sdp_api.cc b/system/test/mock/mock_bta_sdp_api.cc index f506d7cb687..1f5b0159afa 100644 --- a/system/test/mock/mock_bta_sdp_api.cc +++ b/system/test/mock/mock_bta_sdp_api.cc @@ -74,8 +74,7 @@ tBTA_SDP_STATUS BTA_SdpRemoveRecordByUser(void* user_data) { inc_func_call_count(__func__); return test::mock::bta_sdp_api::BTA_SdpRemoveRecordByUser(user_data); } -tBTA_SDP_STATUS BTA_SdpSearch(const RawAddress& bd_addr, - const bluetooth::Uuid& uuid) { +tBTA_SDP_STATUS BTA_SdpSearch(const RawAddress& bd_addr, const bluetooth::Uuid& uuid) { inc_func_call_count(__func__); return test::mock::bta_sdp_api::BTA_SdpSearch(bd_addr, uuid); } diff --git a/system/test/mock/mock_bta_sdp_api.h b/system/test/mock/mock_bta_sdp_api.h index cb351af65b2..8449e40fe71 100644 --- a/system/test/mock/mock_bta_sdp_api.h +++ b/system/test/mock/mock_bta_sdp_api.h @@ -44,8 +44,8 @@ namespace bta_sdp_api { struct BTA_SdpCreateRecordByUser { static tBTA_SDP_STATUS return_value; std::function body{ - [](void* /* user_data */) { return return_value; }}; - tBTA_SDP_STATUS operator()(void* user_data) { return body(user_data); }; + [](void* /* user_data */) { return return_value; }}; + tBTA_SDP_STATUS operator()(void* user_data) { return body(user_data); } }; extern struct BTA_SdpCreateRecordByUser BTA_SdpCreateRecordByUser; @@ -54,7 +54,7 @@ extern struct BTA_SdpCreateRecordByUser BTA_SdpCreateRecordByUser; // Return: void struct BTA_SdpDumpsys { std::function body{[](int /* fd */) {}}; - void operator()(int fd) { body(fd); }; + void operator()(int fd) { body(fd); } }; extern struct BTA_SdpDumpsys BTA_SdpDumpsys; @@ -64,10 +64,8 @@ extern struct BTA_SdpDumpsys BTA_SdpDumpsys; struct BTA_SdpEnable { static tBTA_SDP_STATUS return_value; std::function body{ - [](tBTA_SDP_DM_CBACK* /* p_cback */) { return return_value; }}; - tBTA_SDP_STATUS operator()(tBTA_SDP_DM_CBACK* p_cback) { - return body(p_cback); - }; + [](tBTA_SDP_DM_CBACK* /* p_cback */) { return return_value; }}; + tBTA_SDP_STATUS operator()(tBTA_SDP_DM_CBACK* p_cback) { return body(p_cback); } }; extern struct BTA_SdpEnable BTA_SdpEnable; @@ -77,8 +75,8 @@ extern struct BTA_SdpEnable BTA_SdpEnable; struct BTA_SdpRemoveRecordByUser { static tBTA_SDP_STATUS return_value; std::function body{ - [](void* /* user_data */) { return return_value; }}; - tBTA_SDP_STATUS operator()(void* user_data) { return body(user_data); }; + [](void* /* user_data */) { return return_value; }}; + tBTA_SDP_STATUS operator()(void* user_data) { return body(user_data); } }; extern struct BTA_SdpRemoveRecordByUser BTA_SdpRemoveRecordByUser; @@ -87,14 +85,13 @@ extern struct BTA_SdpRemoveRecordByUser BTA_SdpRemoveRecordByUser; // Return: tBTA_SDP_STATUS struct BTA_SdpSearch { static tBTA_SDP_STATUS return_value; - std::function - body{[](const RawAddress& /* bd_addr */, - const bluetooth::Uuid& /* uuid */) { return return_value; }}; - tBTA_SDP_STATUS operator()(const RawAddress& bd_addr, - const bluetooth::Uuid& uuid) { + std::function body{ + [](const RawAddress& /* bd_addr */, const bluetooth::Uuid& /* uuid */) { + return return_value; + }}; + tBTA_SDP_STATUS operator()(const RawAddress& bd_addr, const bluetooth::Uuid& uuid) { return body(bd_addr, uuid); - }; + } }; extern struct BTA_SdpSearch BTA_SdpSearch; diff --git a/system/test/mock/mock_bta_sys_conn.cc b/system/test/mock/mock_bta_sys_conn.cc index ab147ff9dd7..84cf5037dd0 100644 --- a/system/test/mock/mock_bta_sys_conn.cc +++ b/system/test/mock/mock_bta_sys_conn.cc @@ -34,12 +34,10 @@ void bta_sys_app_open(tBTA_SYS_ID /* id */, uint8_t /* app_id */, const RawAddress& /* peer_addr */) { inc_func_call_count(__func__); } -void bta_sys_busy(tBTA_SYS_ID /* id */, uint8_t /* app_id */, - const RawAddress& /* peer_addr */) { +void bta_sys_busy(tBTA_SYS_ID /* id */, uint8_t /* app_id */, const RawAddress& /* peer_addr */) { inc_func_call_count(__func__); } -void bta_sys_collision_register(tBTA_SYS_ID /* bta_id */, - tBTA_SYS_CONN_CBACK* /* p_cback */) { +void bta_sys_collision_register(tBTA_SYS_ID /* bta_id */, tBTA_SYS_CONN_CBACK* /* p_cback */) { inc_func_call_count(__func__); } void bta_sys_conn_close(tBTA_SYS_ID /* id */, uint8_t /* app_id */, @@ -50,31 +48,21 @@ void bta_sys_conn_open(tBTA_SYS_ID /* id */, uint8_t /* app_id */, const RawAddress& /* peer_addr */) { inc_func_call_count(__func__); } -void bta_sys_idle(tBTA_SYS_ID /* id */, uint8_t /* app_id */, - const RawAddress& /* peer_addr */) { +void bta_sys_idle(tBTA_SYS_ID /* id */, uint8_t /* app_id */, const RawAddress& /* peer_addr */) { inc_func_call_count(__func__); } -void bta_sys_notify_collision(const RawAddress& /* peer_addr */) { - inc_func_call_count(__func__); -} -void bta_sys_notify_role_chg(const RawAddress& /* peer_addr */, - tHCI_ROLE /* new_role */, +void bta_sys_notify_collision(const RawAddress& /* peer_addr */) { inc_func_call_count(__func__); } +void bta_sys_notify_role_chg(const RawAddress& /* peer_addr */, tHCI_ROLE /* new_role */, tHCI_STATUS /* hci_status */) { inc_func_call_count(__func__); } -void bta_sys_pm_register(tBTA_SYS_CONN_CBACK* /* p_cback */) { - inc_func_call_count(__func__); -} -void bta_sys_sniff_register(tBTA_SYS_SNIFF_CBACK* /* p_cback */) { - inc_func_call_count(__func__); -} +void bta_sys_pm_register(tBTA_SYS_CONN_CBACK* /* p_cback */) { inc_func_call_count(__func__); } +void bta_sys_sniff_register(tBTA_SYS_SNIFF_CBACK* /* p_cback */) { inc_func_call_count(__func__); } void bta_sys_reset_sniff(uint8_t /* id */, uint8_t /* app_id */, const RawAddress& /* peer_addr */) { inc_func_call_count(__func__); } -void bta_sys_rm_register(tBTA_SYS_CONN_CBACK* /* p_cback */) { - inc_func_call_count(__func__); -} +void bta_sys_rm_register(tBTA_SYS_CONN_CBACK* /* p_cback */) { inc_func_call_count(__func__); } void bta_sys_role_chg_register(tBTA_SYS_CONN_CBACK* /* p_cback */) { inc_func_call_count(__func__); } @@ -86,9 +74,7 @@ void bta_sys_sco_open(tBTA_SYS_ID /* id */, uint8_t /* app_id */, const RawAddress& /* peer_addr */) { inc_func_call_count(__func__); } -void bta_sys_sco_register(tBTA_SYS_CONN_SCO_CBACK* /* p_cback */) { - inc_func_call_count(__func__); -} +void bta_sys_sco_register(tBTA_SYS_CONN_SCO_CBACK* /* p_cback */) { inc_func_call_count(__func__); } void bta_sys_sco_unuse(tBTA_SYS_ID /* id */, uint8_t /* app_id */, const RawAddress& /* peer_addr */) { inc_func_call_count(__func__); @@ -97,20 +83,12 @@ void bta_sys_sco_use(tBTA_SYS_ID /* id */, uint8_t /* app_id */, const RawAddress& /* peer_addr */) { inc_func_call_count(__func__); } -void bta_sys_eir_register(tBTA_SYS_EIR_CBACK* /* p_cback */) { - inc_func_call_count(__func__); -} +void bta_sys_eir_register(tBTA_SYS_EIR_CBACK* /* p_cback */) { inc_func_call_count(__func__); } void bta_sys_eir_unregister() { inc_func_call_count(__func__); } void bta_sys_cust_eir_register(tBTA_SYS_CUST_EIR_CBACK* /* p_cback */) { inc_func_call_count(__func__); } void bta_sys_add_uuid(uint16_t /* uuid16 */) { inc_func_call_count(__func__); } -void bta_sys_remove_uuid(uint16_t /* uuid16 */) { - inc_func_call_count(__func__); -} -void bta_sys_add_cust_uuid(const tBTA_CUSTOM_UUID& /* curr */) { - inc_func_call_count(__func__); -} -void bta_sys_remove_cust_uuid(const tBTA_CUSTOM_UUID& /* curr */) { - inc_func_call_count(__func__); -} +void bta_sys_remove_uuid(uint16_t /* uuid16 */) { inc_func_call_count(__func__); } +void bta_sys_add_cust_uuid(const tBTA_CUSTOM_UUID& /* curr */) { inc_func_call_count(__func__); } +void bta_sys_remove_cust_uuid(const tBTA_CUSTOM_UUID& /* curr */) { inc_func_call_count(__func__); } diff --git a/system/test/mock/mock_bta_sys_main.cc b/system/test/mock/mock_bta_sys_main.cc index c081c01a957..32f5b24c2dc 100644 --- a/system/test/mock/mock_bta_sys_main.cc +++ b/system/test/mock/mock_bta_sys_main.cc @@ -85,8 +85,7 @@ void bta_sys_sendmsg_delayed(void* p_msg, std::chrono::microseconds delay) { void bta_sys_start_timer(alarm_t* alarm, uint64_t interval_ms, uint16_t event, uint16_t layer_specific) { inc_func_call_count(__func__); - test::mock::bta_sys_main::bta_sys_start_timer(alarm, interval_ms, event, - layer_specific); + test::mock::bta_sys_main::bta_sys_start_timer(alarm, interval_ms, event, layer_specific); } // Mocked functions complete // END mockcify generation diff --git a/system/test/mock/mock_bta_sys_main.h b/system/test/mock/mock_bta_sys_main.h index e95e44dd5b0..0862d6d4cea 100644 --- a/system/test/mock/mock_bta_sys_main.h +++ b/system/test/mock/mock_bta_sys_main.h @@ -40,7 +40,7 @@ namespace bta_sys_main { // Return: void struct BTA_sys_signal_hw_error { std::function body{[]() {}}; - void operator()() { body(); }; + void operator()() { body(); } }; extern struct BTA_sys_signal_hw_error BTA_sys_signal_hw_error; @@ -49,7 +49,7 @@ extern struct BTA_sys_signal_hw_error BTA_sys_signal_hw_error; // Return: void struct bta_sys_deregister { std::function body{[](uint8_t /* id */) {}}; - void operator()(uint8_t id) { body(id); }; + void operator()(uint8_t id) { body(id); } }; extern struct bta_sys_deregister bta_sys_deregister; @@ -58,7 +58,7 @@ extern struct bta_sys_deregister bta_sys_deregister; // Return: void struct bta_sys_disable { std::function body{[]() {}}; - void operator()() { body(); }; + void operator()() { body(); } }; extern struct bta_sys_disable bta_sys_disable; @@ -67,7 +67,7 @@ extern struct bta_sys_disable bta_sys_disable; // Return: void struct bta_sys_init { std::function body{[](void) {}}; - void operator()(void) { body(); }; + void operator()(void) { body(); } }; extern struct bta_sys_init bta_sys_init; @@ -76,9 +76,8 @@ extern struct bta_sys_init bta_sys_init; // Return: bool struct bta_sys_is_register { bool return_value{false}; - std::function body{ - [this](uint8_t /* id */) { return return_value; }}; - bool operator()(uint8_t id) { return body(id); }; + std::function body{[this](uint8_t /* id */) { return return_value; }}; + bool operator()(uint8_t id) { return body(id); } }; extern struct bta_sys_is_register bta_sys_is_register; @@ -87,8 +86,8 @@ extern struct bta_sys_is_register bta_sys_is_register; // Return: void struct bta_sys_register { std::function body{ - [](uint8_t /* id */, const tBTA_SYS_REG* /* p_reg */) {}}; - void operator()(uint8_t id, const tBTA_SYS_REG* p_reg) { body(id, p_reg); }; + [](uint8_t /* id */, const tBTA_SYS_REG* /* p_reg */) {}}; + void operator()(uint8_t id, const tBTA_SYS_REG* p_reg) { body(id, p_reg); } }; extern struct bta_sys_register bta_sys_register; @@ -97,7 +96,7 @@ extern struct bta_sys_register bta_sys_register; // Return: void struct bta_sys_sendmsg { std::function body{[](void* /* p_msg */) {}}; - void operator()(void* p_msg) { body(p_msg); }; + void operator()(void* p_msg) { body(p_msg); } }; extern struct bta_sys_sendmsg bta_sys_sendmsg; @@ -106,10 +105,8 @@ extern struct bta_sys_sendmsg bta_sys_sendmsg; // Return: void struct bta_sys_sendmsg_delayed { std::function body{ - [](void* /* p_msg */, std::chrono::microseconds /* delay */) {}}; - void operator()(void* p_msg, std::chrono::microseconds delay) { - body(p_msg, delay); - }; + [](void* /* p_msg */, std::chrono::microseconds /* delay */) {}}; + void operator()(void* p_msg, std::chrono::microseconds delay) { body(p_msg, delay); } }; extern struct bta_sys_sendmsg_delayed bta_sys_sendmsg_delayed; @@ -117,14 +114,12 @@ extern struct bta_sys_sendmsg_delayed bta_sys_sendmsg_delayed; // Params: alarm_t* alarm, uint64_t interval_ms, uint16_t event, uint16_t // layer_specific Return: void struct bta_sys_start_timer { - std::function - body{[](alarm_t* /* alarm */, uint64_t /* interval_ms */, - uint16_t /* event */, uint16_t /* layer_specific */) {}}; - void operator()(alarm_t* alarm, uint64_t interval_ms, uint16_t event, - uint16_t layer_specific) { + std::function + body{[](alarm_t* /* alarm */, uint64_t /* interval_ms */, uint16_t /* event */, + uint16_t /* layer_specific */) {}}; + void operator()(alarm_t* alarm, uint64_t interval_ms, uint16_t event, uint16_t layer_specific) { body(alarm, interval_ms, event, layer_specific); - }; + } }; extern struct bta_sys_start_timer bta_sys_start_timer; diff --git a/system/test/mock/mock_bta_vc.cc b/system/test/mock/mock_bta_vc.cc index 1a53888cdda..a1addbf0193 100644 --- a/system/test/mock/mock_bta_vc.cc +++ b/system/test/mock/mock_bta_vc.cc @@ -36,8 +36,7 @@ bool VolumeControl::IsVolumeControlRunning() { inc_func_call_count(__func__); return false; } -void VolumeControl::Initialize( - bluetooth::vc::VolumeControlCallbacks* /* callbacks */, - const base::Closure& /* initCb */) { +void VolumeControl::Initialize(bluetooth::vc::VolumeControlCallbacks* /* callbacks */, + const base::Closure& /* initCb */) { inc_func_call_count(__func__); } diff --git a/system/test/mock/mock_bta_vc_device.cc b/system/test/mock/mock_bta_vc_device.cc index 695e159a212..32580c8fc18 100644 --- a/system/test/mock/mock_bta_vc_device.cc +++ b/system/test/mock/mock_bta_vc_device.cc @@ -30,9 +30,9 @@ bool VolumeControlDevice::EnableEncryption() { inc_func_call_count(__func__); return true; } -bool VolumeControlDevice::EnqueueInitialRequests( - tGATT_IF /* gatt_if */, GATT_READ_OP_CB /* chrc_read_cb */, - GATT_WRITE_OP_CB /* cccd_write_cb */) { +bool VolumeControlDevice::EnqueueInitialRequests(tGATT_IF /* gatt_if */, + GATT_READ_OP_CB /* chrc_read_cb */, + GATT_WRITE_OP_CB /* cccd_write_cb */) { inc_func_call_count(__func__); return false; } @@ -48,18 +48,17 @@ bool VolumeControlDevice::VerifyReady(uint16_t /* handle */) { inc_func_call_count(__func__); return false; } -bool VolumeControlDevice::set_volume_control_service_handles( - const gatt::Service& /* service */) { +bool VolumeControlDevice::set_volume_control_service_handles(const gatt::Service& /* service */) { inc_func_call_count(__func__); return false; } void VolumeControlDevice::set_volume_offset_control_service_handles( - const gatt::Service& /* service */) { + const gatt::Service& /* service */) { inc_func_call_count(__func__); } -bool VolumeControlDevice::subscribe_for_notifications( - tGATT_IF /* gatt_if */, uint16_t /* handle */, uint16_t /* ccc_handle */, - GATT_WRITE_OP_CB /* cb */) { +bool VolumeControlDevice::subscribe_for_notifications(tGATT_IF /* gatt_if */, uint16_t /* handle */, + uint16_t /* ccc_handle */, + GATT_WRITE_OP_CB /* cb */) { inc_func_call_count(__func__); return false; } @@ -67,17 +66,15 @@ uint16_t VolumeControlDevice::find_ccc_handle(uint16_t /* chrc_handle */) { inc_func_call_count(__func__); return 0; } -void VolumeControlDevice::ControlPointOperation( - uint8_t /* opcode */, const std::vector* /* arg */, - GATT_WRITE_OP_CB /* cb */, void* /* cb_data */) { +void VolumeControlDevice::ControlPointOperation(uint8_t /* opcode */, + const std::vector* /* arg */, + GATT_WRITE_OP_CB /* cb */, void* /* cb_data */) { inc_func_call_count(__func__); } -void VolumeControlDevice::Disconnect(tGATT_IF /* gatt_if */) { - inc_func_call_count(__func__); -} -void VolumeControlDevice::EnqueueRemainingRequests( - tGATT_IF /* gatt_if */, GATT_READ_OP_CB /* chrc_read_cb */, - GATT_WRITE_OP_CB /* cccd_write_cb */) { +void VolumeControlDevice::Disconnect(tGATT_IF /* gatt_if */) { inc_func_call_count(__func__); } +void VolumeControlDevice::EnqueueRemainingRequests(tGATT_IF /* gatt_if */, + GATT_READ_OP_CB /* chrc_read_cb */, + GATT_WRITE_OP_CB /* cccd_write_cb */) { inc_func_call_count(__func__); } void VolumeControlDevice::ResetHandles(void) { inc_func_call_count(__func__); } diff --git a/system/test/mock/mock_btcore_module.h b/system/test/mock/mock_btcore_module.h index 8b00a5a795f..01527dd8b90 100644 --- a/system/test/mock/mock_btcore_module.h +++ b/system/test/mock/mock_btcore_module.h @@ -39,8 +39,8 @@ namespace btcore_module { struct get_module { const module_t* return_value{0}; std::function body{ - [this](const char* /* name */) { return return_value; }}; - const module_t* operator()(const char* name) { return body(name); }; + [this](const char* /* name */) { return return_value; }}; + const module_t* operator()(const char* name) { return body(name); } }; extern struct get_module get_module; @@ -48,9 +48,8 @@ extern struct get_module get_module; // Params: const module_t* module // Return: void struct module_clean_up { - std::function body{ - [](const module_t* /* module */) {}}; - void operator()(const module_t* module) { body(module); }; + std::function body{[](const module_t* /* module */) {}}; + void operator()(const module_t* module) { body(module); } }; extern struct module_clean_up module_clean_up; @@ -60,8 +59,8 @@ extern struct module_clean_up module_clean_up; struct module_init { bool return_value{false}; std::function body{ - [this](const module_t* /* module */) { return return_value; }}; - bool operator()(const module_t* module) { return body(module); }; + [this](const module_t* /* module */) { return return_value; }}; + bool operator()(const module_t* module) { return body(module); } }; extern struct module_init module_init; @@ -70,7 +69,7 @@ extern struct module_init module_init; // Return: void struct module_management_start { std::function body{[](void) {}}; - void operator()(void) { body(); }; + void operator()(void) { body(); } }; extern struct module_management_start module_management_start; @@ -79,7 +78,7 @@ extern struct module_management_start module_management_start; // Return: void struct module_management_stop { std::function body{[](void) {}}; - void operator()(void) { body(); }; + void operator()(void) { body(); } }; extern struct module_management_stop module_management_stop; @@ -87,9 +86,8 @@ extern struct module_management_stop module_management_stop; // Params: const module_t* module // Return: void struct module_shut_down { - std::function body{ - [](const module_t* /* module */) {}}; - void operator()(const module_t* module) { body(module); }; + std::function body{[](const module_t* /* module */) {}}; + void operator()(const module_t* module) { body(module); } }; extern struct module_shut_down module_shut_down; @@ -99,8 +97,8 @@ extern struct module_shut_down module_shut_down; struct module_start_up { bool return_value{false}; std::function body{ - [this](const module_t* /* module */) { return return_value; }}; - bool operator()(const module_t* module) { return body(module); }; + [this](const module_t* /* module */) { return return_value; }}; + bool operator()(const module_t* module) { return body(module); } }; extern struct module_start_up module_start_up; diff --git a/system/test/mock/mock_btif_av.cc b/system/test/mock/mock_btif_av.cc index 1b1a3958bae..966771378f3 100644 --- a/system/test/mock/mock_btif_av.cc +++ b/system/test/mock/mock_btif_av.cc @@ -54,13 +54,11 @@ struct btif_av_peer_is_connected_sink btif_av_peer_is_connected_sink; struct btif_av_peer_is_connected_source btif_av_peer_is_connected_source; struct btif_av_peer_is_sink btif_av_peer_is_sink; struct btif_av_peer_is_source btif_av_peer_is_source; -struct btif_av_peer_prefers_mandatory_codec - btif_av_peer_prefers_mandatory_codec; +struct btif_av_peer_prefers_mandatory_codec btif_av_peer_prefers_mandatory_codec; struct btif_av_peer_supports_3mbps btif_av_peer_supports_3mbps; struct btif_av_report_source_codec_state btif_av_report_source_codec_state; struct btif_av_set_audio_delay btif_av_set_audio_delay; -struct btif_av_set_dynamic_audio_buffer_size - btif_av_set_dynamic_audio_buffer_size; +struct btif_av_set_dynamic_audio_buffer_size btif_av_set_dynamic_audio_buffer_size; struct btif_av_set_low_latency btif_av_set_low_latency; struct btif_av_sink_active_peer btif_av_sink_active_peer; struct btif_av_sink_execute_service btif_av_sink_execute_service; @@ -117,8 +115,7 @@ const char* dump_av_sm_event_name::return_value = nullptr; } // namespace test // Mocked functions, if any -void btif_av_acl_disconnected(const RawAddress& peer_address, - const A2dpType local_a2dp_type) { +void btif_av_acl_disconnected(const RawAddress& peer_address, const A2dpType local_a2dp_type) { inc_func_call_count(__func__); test::mock::btif_av::btif_av_acl_disconnected(peer_address, local_a2dp_type); } @@ -150,17 +147,13 @@ bool btif_av_is_connected(const A2dpType local_a2dp_type) { inc_func_call_count(__func__); return test::mock::btif_av::btif_av_is_connected(local_a2dp_type); } -bool btif_av_is_connected_addr(const RawAddress& peer_address, - const A2dpType local_a2dp_type) { +bool btif_av_is_connected_addr(const RawAddress& peer_address, const A2dpType local_a2dp_type) { inc_func_call_count(__func__); - return test::mock::btif_av::btif_av_is_connected_addr(peer_address, - local_a2dp_type); + return test::mock::btif_av::btif_av_is_connected_addr(peer_address, local_a2dp_type); } -bool btif_av_is_peer_edr(const RawAddress& peer_address, - const A2dpType local_a2dp_type) { +bool btif_av_is_peer_edr(const RawAddress& peer_address, const A2dpType local_a2dp_type) { inc_func_call_count(__func__); - return test::mock::btif_av::btif_av_is_peer_edr(peer_address, - local_a2dp_type); + return test::mock::btif_av::btif_av_is_peer_edr(peer_address, local_a2dp_type); } bool btif_av_is_peer_silenced(const RawAddress& peer_address) { inc_func_call_count(__func__); @@ -193,36 +186,28 @@ bool btif_av_peer_is_source(const RawAddress& peer_address) { bool btif_av_peer_prefers_mandatory_codec(const RawAddress& peer_address, const A2dpType local_a2dp_type) { inc_func_call_count(__func__); - return test::mock::btif_av::btif_av_peer_prefers_mandatory_codec( - peer_address, local_a2dp_type); + return test::mock::btif_av::btif_av_peer_prefers_mandatory_codec(peer_address, local_a2dp_type); } -bool btif_av_peer_supports_3mbps(const RawAddress& peer_address, - const A2dpType local_a2dp_type) { +bool btif_av_peer_supports_3mbps(const RawAddress& peer_address, const A2dpType local_a2dp_type) { inc_func_call_count(__func__); - return test::mock::btif_av::btif_av_peer_supports_3mbps(peer_address, - local_a2dp_type); + return test::mock::btif_av::btif_av_peer_supports_3mbps(peer_address, local_a2dp_type); } void btif_av_report_source_codec_state( - const RawAddress& peer_address, - const btav_a2dp_codec_config_t& codec_config, - const std::vector& codecs_local_capabilities, - const std::vector& - codecs_selectable_capabilities) { + const RawAddress& peer_address, const btav_a2dp_codec_config_t& codec_config, + const std::vector& codecs_local_capabilities, + const std::vector& codecs_selectable_capabilities) { inc_func_call_count(__func__); test::mock::btif_av::btif_av_report_source_codec_state( - peer_address, codec_config, codecs_local_capabilities, - codecs_selectable_capabilities); + peer_address, codec_config, codecs_local_capabilities, codecs_selectable_capabilities); } void btif_av_set_audio_delay(const RawAddress& peer_address, uint16_t delay, const A2dpType local_a2dp_type) { inc_func_call_count(__func__); - test::mock::btif_av::btif_av_set_audio_delay(peer_address, delay, - local_a2dp_type); + test::mock::btif_av::btif_av_set_audio_delay(peer_address, delay, local_a2dp_type); } void btif_av_set_dynamic_audio_buffer_size(uint8_t dynamic_audio_buffer_size) { inc_func_call_count(__func__); - test::mock::btif_av::btif_av_set_dynamic_audio_buffer_size( - dynamic_audio_buffer_size); + test::mock::btif_av::btif_av_set_dynamic_audio_buffer_size(dynamic_audio_buffer_size); } void btif_av_set_low_latency(bool is_low_latency) { inc_func_call_count(__func__); diff --git a/system/test/mock/mock_btif_av.h b/system/test/mock/mock_btif_av.h index 0f7afa069a3..f95013c06fb 100644 --- a/system/test/mock/mock_btif_av.h +++ b/system/test/mock/mock_btif_av.h @@ -61,14 +61,11 @@ namespace btif_av { // Params: const A2dpType local_a2dp_type. // Return: void struct btif_av_acl_disconnected { - std::function - body{[](const RawAddress& /* peer_address */, - const A2dpType /* local_a2dp_type */) {}}; - void operator()(const RawAddress& peer_address, - const A2dpType local_a2dp_type) { + std::function body{ + [](const RawAddress& /* peer_address */, const A2dpType /* local_a2dp_type */) {}}; + void operator()(const RawAddress& peer_address, const A2dpType local_a2dp_type) { body(peer_address, local_a2dp_type); - }; + } }; extern struct btif_av_acl_disconnected btif_av_acl_disconnected; @@ -77,11 +74,10 @@ extern struct btif_av_acl_disconnected btif_av_acl_disconnected; // Return: void struct btif_av_clear_remote_suspend_flag { std::function body{ - [](const A2dpType /* local_a2dp_type */) {}}; - void operator()(const A2dpType local_a2dp_type) { body(local_a2dp_type); }; + [](const A2dpType /* local_a2dp_type */) {}}; + void operator()(const A2dpType local_a2dp_type) { body(local_a2dp_type); } }; -extern struct btif_av_clear_remote_suspend_flag - btif_av_clear_remote_suspend_flag; +extern struct btif_av_clear_remote_suspend_flag btif_av_clear_remote_suspend_flag; // Name: btif_av_find_by_handle // Params: tBTA_AV_HNDL bta_handle @@ -89,10 +85,8 @@ extern struct btif_av_clear_remote_suspend_flag struct btif_av_find_by_handle { static const RawAddress& return_value; std::function body{ - [](tBTA_AV_HNDL /* bta_handle */) { return return_value; }}; - const RawAddress& operator()(tBTA_AV_HNDL bta_handle) { - return body(bta_handle); - }; + [](tBTA_AV_HNDL /* bta_handle */) { return return_value; }}; + const RawAddress& operator()(tBTA_AV_HNDL bta_handle) { return body(bta_handle); } }; extern struct btif_av_find_by_handle btif_av_find_by_handle; @@ -102,10 +96,8 @@ extern struct btif_av_find_by_handle btif_av_find_by_handle; struct btif_av_get_audio_delay { static uint16_t return_value; std::function body{ - [](const A2dpType /* local_a2dp_type */) { return return_value; }}; - uint16_t operator()(const A2dpType local_a2dp_type) { - return body(local_a2dp_type); - }; + [](const A2dpType /* local_a2dp_type */) { return return_value; }}; + uint16_t operator()(const A2dpType local_a2dp_type) { return body(local_a2dp_type); } }; extern struct btif_av_get_audio_delay btif_av_get_audio_delay; @@ -115,10 +107,8 @@ extern struct btif_av_get_audio_delay btif_av_get_audio_delay; struct btif_av_get_peer_sep { static uint8_t return_value; std::function body{ - [](const A2dpType /* local_a2dp_type */) { return return_value; }}; - uint8_t operator()(const A2dpType local_a2dp_type) { - return body(local_a2dp_type); - }; + [](const A2dpType /* local_a2dp_type */) { return return_value; }}; + uint8_t operator()(const A2dpType local_a2dp_type) { return body(local_a2dp_type); } }; extern struct btif_av_get_peer_sep btif_av_get_peer_sep; @@ -128,7 +118,7 @@ extern struct btif_av_get_peer_sep btif_av_get_peer_sep; struct btif_av_is_a2dp_offload_enabled { static bool return_value; std::function body{[]() { return return_value; }}; - bool operator()() { return body(); }; + bool operator()() { return body(); } }; extern struct btif_av_is_a2dp_offload_enabled btif_av_is_a2dp_offload_enabled; @@ -138,7 +128,7 @@ extern struct btif_av_is_a2dp_offload_enabled btif_av_is_a2dp_offload_enabled; struct btif_av_is_a2dp_offload_running { static bool return_value; std::function body{[]() { return return_value; }}; - bool operator()() { return body(); }; + bool operator()() { return body(); } }; extern struct btif_av_is_a2dp_offload_running btif_av_is_a2dp_offload_running; @@ -148,10 +138,8 @@ extern struct btif_av_is_a2dp_offload_running btif_av_is_a2dp_offload_running; struct btif_av_is_connected { static bool return_value; std::function body{ - [](const A2dpType /* local_a2dp_type */) { return return_value; }}; - bool operator()(const A2dpType local_a2dp_type) { - return body(local_a2dp_type); - }; + [](const A2dpType /* local_a2dp_type */) { return return_value; }}; + bool operator()(const A2dpType local_a2dp_type) { return body(local_a2dp_type); } }; extern struct btif_av_is_connected btif_av_is_connected; @@ -160,14 +148,13 @@ extern struct btif_av_is_connected btif_av_is_connected; // Return: bool struct btif_av_is_connected_addr { static bool return_value; - std::function - body{[](const RawAddress& /* peer_address */, - const A2dpType /* local_a2dp_type */) { return return_value; }}; - bool operator()(const RawAddress& peer_address, - const A2dpType local_a2dp_type) { + std::function body{ + [](const RawAddress& /* peer_address */, const A2dpType /* local_a2dp_type */) { + return return_value; + }}; + bool operator()(const RawAddress& peer_address, const A2dpType local_a2dp_type) { return body(peer_address, local_a2dp_type); - }; + } }; extern struct btif_av_is_connected_addr btif_av_is_connected_addr; @@ -176,14 +163,13 @@ extern struct btif_av_is_connected_addr btif_av_is_connected_addr; // Return: bool struct btif_av_is_peer_edr { static bool return_value; - std::function - body{[](const RawAddress& /* peer_address */, - const A2dpType /* local_a2dp_type */) { return return_value; }}; - bool operator()(const RawAddress& peer_address, - const A2dpType local_a2dp_type) { + std::function body{ + [](const RawAddress& /* peer_address */, const A2dpType /* local_a2dp_type */) { + return return_value; + }}; + bool operator()(const RawAddress& peer_address, const A2dpType local_a2dp_type) { return body(peer_address, local_a2dp_type); - }; + } }; extern struct btif_av_is_peer_edr btif_av_is_peer_edr; @@ -193,10 +179,8 @@ extern struct btif_av_is_peer_edr btif_av_is_peer_edr; struct btif_av_is_peer_silenced { static bool return_value; std::function body{ - [](const RawAddress& /* peer_address */) { return return_value; }}; - bool operator()(const RawAddress& peer_address) { - return body(peer_address); - }; + [](const RawAddress& /* peer_address */) { return return_value; }}; + bool operator()(const RawAddress& peer_address) { return body(peer_address); } }; extern struct btif_av_is_peer_silenced btif_av_is_peer_silenced; @@ -206,7 +190,7 @@ extern struct btif_av_is_peer_silenced btif_av_is_peer_silenced; struct btif_av_is_sink_enabled { static bool return_value; std::function body{[](void) { return return_value; }}; - bool operator()(void) { return body(); }; + bool operator()(void) { return body(); } }; extern struct btif_av_is_sink_enabled btif_av_is_sink_enabled; @@ -216,7 +200,7 @@ extern struct btif_av_is_sink_enabled btif_av_is_sink_enabled; struct btif_av_is_source_enabled { static bool return_value; std::function body{[](void) { return return_value; }}; - bool operator()(void) { return body(); }; + bool operator()(void) { return body(); } }; extern struct btif_av_is_source_enabled btif_av_is_source_enabled; @@ -226,10 +210,8 @@ extern struct btif_av_is_source_enabled btif_av_is_source_enabled; struct btif_av_peer_is_connected_sink { static bool return_value; std::function body{ - [](const RawAddress& /* peer_address */) { return return_value; }}; - bool operator()(const RawAddress& peer_address) { - return body(peer_address); - }; + [](const RawAddress& /* peer_address */) { return return_value; }}; + bool operator()(const RawAddress& peer_address) { return body(peer_address); } }; extern struct btif_av_peer_is_connected_sink btif_av_peer_is_connected_sink; @@ -239,10 +221,8 @@ extern struct btif_av_peer_is_connected_sink btif_av_peer_is_connected_sink; struct btif_av_peer_is_connected_source { static bool return_value; std::function body{ - [](const RawAddress& /* peer_address */) { return return_value; }}; - bool operator()(const RawAddress& peer_address) { - return body(peer_address); - }; + [](const RawAddress& /* peer_address */) { return return_value; }}; + bool operator()(const RawAddress& peer_address) { return body(peer_address); } }; extern struct btif_av_peer_is_connected_source btif_av_peer_is_connected_source; @@ -252,10 +232,8 @@ extern struct btif_av_peer_is_connected_source btif_av_peer_is_connected_source; struct btif_av_peer_is_sink { static bool return_value; std::function body{ - [](const RawAddress& /* peer_address */) { return return_value; }}; - bool operator()(const RawAddress& peer_address) { - return body(peer_address); - }; + [](const RawAddress& /* peer_address */) { return return_value; }}; + bool operator()(const RawAddress& peer_address) { return body(peer_address); } }; extern struct btif_av_peer_is_sink btif_av_peer_is_sink; @@ -265,10 +243,8 @@ extern struct btif_av_peer_is_sink btif_av_peer_is_sink; struct btif_av_peer_is_source { static bool return_value; std::function body{ - [](const RawAddress& /* peer_address */) { return return_value; }}; - bool operator()(const RawAddress& peer_address) { - return body(peer_address); - }; + [](const RawAddress& /* peer_address */) { return return_value; }}; + bool operator()(const RawAddress& peer_address) { return body(peer_address); } }; extern struct btif_av_peer_is_source btif_av_peer_is_source; @@ -277,37 +253,30 @@ extern struct btif_av_peer_is_source btif_av_peer_is_source; // Return: bool struct btif_av_peer_prefers_mandatory_codec { static bool return_value; - std::function - body{[](const RawAddress& /* peer_address */, - const A2dpType /* local_a2dp_type */) { - ; - return return_value; - }}; - bool operator()(const RawAddress& peer_address, - const A2dpType local_a2dp_type) { + std::function body{ + [](const RawAddress& /* peer_address */, const A2dpType /* local_a2dp_type */) { + ; + return return_value; + }}; + bool operator()(const RawAddress& peer_address, const A2dpType local_a2dp_type) { return body(peer_address, local_a2dp_type); - }; + } }; -extern struct btif_av_peer_prefers_mandatory_codec - btif_av_peer_prefers_mandatory_codec; +extern struct btif_av_peer_prefers_mandatory_codec btif_av_peer_prefers_mandatory_codec; // Name: btif_av_peer_supports_3mbps // Params: const RawAddress& peer_address, const A2dpType local_a2dp_type // Return: bool struct btif_av_peer_supports_3mbps { static bool return_value; - std::function - body{[](const RawAddress& /* peer_address */, - const A2dpType /* local_a2dp_type */) { - ; - return return_value; - }}; - bool operator()(const RawAddress& peer_address, - const A2dpType local_a2dp_type) { + std::function body{ + [](const RawAddress& /* peer_address */, const A2dpType /* local_a2dp_type */) { + ; + return return_value; + }}; + bool operator()(const RawAddress& peer_address, const A2dpType local_a2dp_type) { return body(peer_address, local_a2dp_type); - }; + } }; extern struct btif_av_peer_supports_3mbps btif_av_peer_supports_3mbps; @@ -317,30 +286,22 @@ extern struct btif_av_peer_supports_3mbps btif_av_peer_supports_3mbps; // codecs_local_capabilities, const std::vector& // codecs_selectable_capabilities Return: void struct btif_av_report_source_codec_state { - std::function& codecs_local_capabilities, - const std::vector& - codecs_selectable_capabilities)> - body{[](const RawAddress& /* peer_address */, - const btav_a2dp_codec_config_t& /* codec_config */, - const std::vector& - /* codecs_local_capabilities */, - const std::vector& - /* codecs_selectable_capabilities */) {}}; - void operator()( - const RawAddress& peer_address, - const btav_a2dp_codec_config_t& codec_config, - const std::vector& codecs_local_capabilities, - const std::vector& - codecs_selectable_capabilities) { - body(peer_address, codec_config, codecs_local_capabilities, - codecs_selectable_capabilities); - }; -}; -extern struct btif_av_report_source_codec_state - btif_av_report_source_codec_state; + std::function& codecs_local_capabilities, + const std::vector& codecs_selectable_capabilities)> + body{[](const RawAddress& /* peer_address */, + const btav_a2dp_codec_config_t& /* codec_config */, + const std::vector& + /* codecs_local_capabilities */, + const std::vector& + /* codecs_selectable_capabilities */) {}}; + void operator()(const RawAddress& peer_address, const btav_a2dp_codec_config_t& codec_config, + const std::vector& codecs_local_capabilities, + const std::vector& codecs_selectable_capabilities) { + body(peer_address, codec_config, codecs_local_capabilities, codecs_selectable_capabilities); + } +}; +extern struct btif_av_report_source_codec_state btif_av_report_source_codec_state; // Name: btif_av_set_audio_delay // Params: const RawAddress& peer_address, uint16_t delay, const A2dpType @@ -348,12 +309,11 @@ extern struct btif_av_report_source_codec_state struct btif_av_set_audio_delay { std::function - body{[](const RawAddress& /* peer_address */, uint16_t /* delay */, - const A2dpType /* local_a2dp_type */) {}}; - void operator()(const RawAddress& peer_address, uint16_t delay, - const A2dpType local_a2dp_type) { + body{[](const RawAddress& /* peer_address */, uint16_t /* delay */, + const A2dpType /* local_a2dp_type */) {}}; + void operator()(const RawAddress& peer_address, uint16_t delay, const A2dpType local_a2dp_type) { body(peer_address, delay, local_a2dp_type); - }; + } }; extern struct btif_av_set_audio_delay btif_av_set_audio_delay; @@ -362,21 +322,17 @@ extern struct btif_av_set_audio_delay btif_av_set_audio_delay; // Return: void struct btif_av_set_dynamic_audio_buffer_size { std::function body{ - [](uint8_t /* dynamic_audio_buffer_size */) {}}; - void operator()(uint8_t dynamic_audio_buffer_size) { - body(dynamic_audio_buffer_size); - }; + [](uint8_t /* dynamic_audio_buffer_size */) {}}; + void operator()(uint8_t dynamic_audio_buffer_size) { body(dynamic_audio_buffer_size); } }; -extern struct btif_av_set_dynamic_audio_buffer_size - btif_av_set_dynamic_audio_buffer_size; +extern struct btif_av_set_dynamic_audio_buffer_size btif_av_set_dynamic_audio_buffer_size; // Name: btif_av_set_low_latency // Params: bool is_low_latency // Return: void struct btif_av_set_low_latency { - std::function body{ - [](bool /* is_low_latency */) {}}; - void operator()(bool is_low_latency) { body(is_low_latency); }; + std::function body{[](bool /* is_low_latency */) {}}; + void operator()(bool is_low_latency) { body(is_low_latency); } }; extern struct btif_av_set_low_latency btif_av_set_low_latency; @@ -386,7 +342,7 @@ extern struct btif_av_set_low_latency btif_av_set_low_latency; struct btif_av_sink_active_peer { static RawAddress return_value; std::function body{[](void) { return return_value; }}; - RawAddress operator()(void) { return body(); }; + RawAddress operator()(void) { return body(); } }; extern struct btif_av_sink_active_peer btif_av_sink_active_peer; @@ -395,9 +351,8 @@ extern struct btif_av_sink_active_peer btif_av_sink_active_peer; // Return: bt_status_t struct btif_av_sink_execute_service { static bt_status_t return_value; - std::function body{ - [](bool /* enable */) { return return_value; }}; - bt_status_t operator()(bool enable) { return body(enable); }; + std::function body{[](bool /* enable */) { return return_value; }}; + bt_status_t operator()(bool enable) { return body(enable); } }; extern struct btif_av_sink_execute_service btif_av_sink_execute_service; @@ -407,7 +362,7 @@ extern struct btif_av_sink_execute_service btif_av_sink_execute_service; struct btif_av_source_active_peer { static RawAddress return_value; std::function body{[](void) { return return_value; }}; - RawAddress operator()(void) { return body(); }; + RawAddress operator()(void) { return body(); } }; extern struct btif_av_source_active_peer btif_av_source_active_peer; @@ -416,9 +371,8 @@ extern struct btif_av_source_active_peer btif_av_source_active_peer; // Return: bt_status_t struct btif_av_source_execute_service { static bt_status_t return_value; - std::function body{ - [](bool /* enable */) { return return_value; }}; - bt_status_t operator()(bool enable) { return body(enable); }; + std::function body{[](bool /* enable */) { return return_value; }}; + bt_status_t operator()(bool enable) { return body(enable); } }; extern struct btif_av_source_execute_service btif_av_source_execute_service; @@ -428,7 +382,7 @@ extern struct btif_av_source_execute_service btif_av_source_execute_service; struct btif_av_src_sink_coexist_enabled { static bool return_value; std::function body{[](void) { return return_value; }}; - bool operator()(void) { return body(); }; + bool operator()(void) { return body(); } }; extern struct btif_av_src_sink_coexist_enabled btif_av_src_sink_coexist_enabled; @@ -438,10 +392,8 @@ extern struct btif_av_src_sink_coexist_enabled btif_av_src_sink_coexist_enabled; struct btif_av_stream_ready { static bool return_value; std::function body{ - [](const A2dpType /* local_a2dp_type */) { return return_value; }}; - bool operator()(const A2dpType local_a2dp_type) { - return body(local_a2dp_type); - }; + [](const A2dpType /* local_a2dp_type */) { return return_value; }}; + bool operator()(const A2dpType local_a2dp_type) { return body(local_a2dp_type); } }; extern struct btif_av_stream_ready btif_av_stream_ready; @@ -450,8 +402,8 @@ extern struct btif_av_stream_ready btif_av_stream_ready; // Return: void struct btif_av_stream_start { std::function body{ - [](const A2dpType /* local_a2dp_type */) {}}; - void operator()(const A2dpType local_a2dp_type) { body(local_a2dp_type); }; + [](const A2dpType /* local_a2dp_type */) {}}; + void operator()(const A2dpType local_a2dp_type) { body(local_a2dp_type); } }; extern struct btif_av_stream_start btif_av_stream_start; @@ -460,7 +412,7 @@ extern struct btif_av_stream_start btif_av_stream_start; // Return: void struct btif_av_stream_start_offload { std::function body{[](void) {}}; - void operator()(void) { body(); }; + void operator()(void) { body(); } }; extern struct btif_av_stream_start_offload btif_av_stream_start_offload; @@ -468,12 +420,10 @@ extern struct btif_av_stream_start_offload btif_av_stream_start_offload; // Params: bool use_latency_mode // Return: void struct btif_av_stream_start_with_latency { - std::function body{ - [](bool /* use_latency_mode */) {}}; - void operator()(bool use_latency_mode) { body(use_latency_mode); }; + std::function body{[](bool /* use_latency_mode */) {}}; + void operator()(bool use_latency_mode) { body(use_latency_mode); } }; -extern struct btif_av_stream_start_with_latency - btif_av_stream_start_with_latency; +extern struct btif_av_stream_start_with_latency btif_av_stream_start_with_latency; // Name: btif_av_stream_started_ready // Params: const A2dpType local_a2dp_type @@ -481,10 +431,8 @@ extern struct btif_av_stream_start_with_latency struct btif_av_stream_started_ready { static bool return_value; std::function body{ - [](const A2dpType /* local_a2dp_type */) { return return_value; }}; - bool operator()(const A2dpType local_a2dp_type) { - return body(local_a2dp_type); - }; + [](const A2dpType /* local_a2dp_type */) { return return_value; }}; + bool operator()(const A2dpType local_a2dp_type) { return body(local_a2dp_type); } }; extern struct btif_av_stream_started_ready btif_av_stream_started_ready; @@ -493,8 +441,8 @@ extern struct btif_av_stream_started_ready btif_av_stream_started_ready; // Return: void struct btif_av_stream_stop { std::function body{ - [](const RawAddress& /* peer_address */) {}}; - void operator()(const RawAddress& peer_address) { body(peer_address); }; + [](const RawAddress& /* peer_address */) {}}; + void operator()(const RawAddress& peer_address) { body(peer_address); } }; extern struct btif_av_stream_stop btif_av_stream_stop; @@ -503,7 +451,7 @@ extern struct btif_av_stream_stop btif_av_stream_stop; // Return: void struct btif_av_stream_suspend { std::function body{[](void) {}}; - void operator()(void) { body(); }; + void operator()(void) { body(); } }; extern struct btif_av_stream_suspend btif_av_stream_suspend; @@ -512,7 +460,7 @@ extern struct btif_av_stream_suspend btif_av_stream_suspend; // Return: void struct btif_debug_av_dump { std::function body{[](int /* fd */) {}}; - void operator()(int fd) { body(fd); }; + void operator()(int fd) { body(fd); } }; extern struct btif_debug_av_dump btif_debug_av_dump; @@ -521,9 +469,8 @@ extern struct btif_debug_av_dump btif_debug_av_dump; // Return: const char* struct dump_av_sm_event_name { static const char* return_value; - std::function body{ - [](int /* event */) { return return_value; }}; - const char* operator()(int event) { return body(event); }; + std::function body{[](int /* event */) { return return_value; }}; + const char* operator()(int event) { return body(event); } }; extern struct dump_av_sm_event_name dump_av_sm_event_name; diff --git a/system/test/mock/mock_btif_avrcp_service.h b/system/test/mock/mock_btif_avrcp_service.h index a0484d3b5bf..b0254f33fff 100644 --- a/system/test/mock/mock_btif_avrcp_service.h +++ b/system/test/mock/mock_btif_avrcp_service.h @@ -40,9 +40,8 @@ namespace btif_avrcp_service { // Params: const base::Closure& task // Return: void struct do_in_avrcp_jni { - std::function body{ - [](const base::Closure& /* task */) {}}; - void operator()(const base::Closure& task) { body(task); }; + std::function body{[](const base::Closure& /* task */) {}}; + void operator()(const base::Closure& task) { body(task); } }; extern struct do_in_avrcp_jni do_in_avrcp_jni; diff --git a/system/test/mock/mock_btif_bluetooth.cc b/system/test/mock/mock_btif_bluetooth.cc index f695e0c28d9..fe77f0789cf 100644 --- a/system/test/mock/mock_btif_bluetooth.cc +++ b/system/test/mock/mock_btif_bluetooth.cc @@ -41,8 +41,7 @@ struct is_common_criteria_mode is_common_criteria_mode; struct is_restricted_mode is_restricted_mode; struct dut_mode_configure dut_mode_configure; struct dut_mode_send dut_mode_send; -struct get_common_criteria_config_compare_result - get_common_criteria_config_compare_result; +struct get_common_criteria_config_compare_result get_common_criteria_config_compare_result; struct get_remote_device_properties get_remote_device_properties; struct get_remote_device_property get_remote_device_property; struct get_remote_services get_remote_services; @@ -77,18 +76,15 @@ int dut_mode_send(uint16_t opcode, uint8_t* buf, uint8_t len) { } int get_common_criteria_config_compare_result() { inc_func_call_count(__func__); - return test::mock::btif_bluetooth:: - get_common_criteria_config_compare_result(); + return test::mock::btif_bluetooth::get_common_criteria_config_compare_result(); } int get_remote_device_properties(RawAddress* remote_addr) { inc_func_call_count(__func__); return test::mock::btif_bluetooth::get_remote_device_properties(remote_addr); } -int get_remote_device_property(RawAddress* remote_addr, - bt_property_type_t type) { +int get_remote_device_property(RawAddress* remote_addr, bt_property_type_t type) { inc_func_call_count(__func__); - return test::mock::btif_bluetooth::get_remote_device_property(remote_addr, - type); + return test::mock::btif_bluetooth::get_remote_device_property(remote_addr, type); } int get_remote_services(RawAddress* remote_addr) { inc_func_call_count(__func__); @@ -98,16 +94,13 @@ int le_test_mode(uint16_t opcode, uint8_t* buf, uint8_t len) { inc_func_call_count(__func__); return test::mock::btif_bluetooth::le_test_mode(opcode, buf, len); } -int set_remote_device_property(RawAddress* remote_addr, - const bt_property_t* property) { +int set_remote_device_property(RawAddress* remote_addr, const bt_property_t* property) { inc_func_call_count(__func__); - return test::mock::btif_bluetooth::set_remote_device_property(remote_addr, - property); + return test::mock::btif_bluetooth::set_remote_device_property(remote_addr, property); } void invoke_switch_buffer_size_cb(bool invoke_switch_buffer_size_cb) { inc_func_call_count(__func__); - test::mock::btif_bluetooth::invoke_switch_buffer_size_cb( - invoke_switch_buffer_size_cb); + test::mock::btif_bluetooth::invoke_switch_buffer_size_cb(invoke_switch_buffer_size_cb); } // END mockcify generation diff --git a/system/test/mock/mock_btif_bluetooth.h b/system/test/mock/mock_btif_bluetooth.h index 8b91106fe96..7ecc1ef8322 100644 --- a/system/test/mock/mock_btif_bluetooth.h +++ b/system/test/mock/mock_btif_bluetooth.h @@ -39,7 +39,7 @@ namespace btif_bluetooth { // Returns: bool struct is_atv_device { std::function body{[]() { return false; }}; - bool operator()() { return body(); }; + bool operator()() { return body(); } }; extern struct is_atv_device is_atv_device; // Name: is_common_criteria_mode @@ -47,7 +47,7 @@ extern struct is_atv_device is_atv_device; // Returns: bool struct is_common_criteria_mode { std::function body{[]() { return false; }}; - bool operator()() { return body(); }; + bool operator()() { return body(); } }; extern struct is_common_criteria_mode is_common_criteria_mode; // Name: is_restricted_mode @@ -55,30 +55,24 @@ extern struct is_common_criteria_mode is_common_criteria_mode; // Returns: bool struct is_restricted_mode { std::function body{[]() { return false; }}; - bool operator()() { return body(); }; + bool operator()() { return body(); } }; extern struct is_restricted_mode is_restricted_mode; // Name: dut_mode_configure // Params: uint8_t enable // Returns: int struct dut_mode_configure { - std::function body{ - [](uint8_t /* enable */) { return 0; }}; - int operator()(uint8_t enable) { return body(enable); }; + std::function body{[](uint8_t /* enable */) { return 0; }}; + int operator()(uint8_t enable) { return body(enable); } }; extern struct dut_mode_configure dut_mode_configure; // Name: dut_mode_send // Params: uint16_t opcode, uint8_t* buf, uint8_t len // Returns: int struct dut_mode_send { - std::function - body{[](uint16_t /* opcode */, uint8_t* /* buf */, uint8_t /* len */) { - return 0; - }}; - int operator()(uint16_t opcode, uint8_t* buf, uint8_t len) { - return body(opcode, buf, len); - }; + std::function body{ + [](uint16_t /* opcode */, uint8_t* /* buf */, uint8_t /* len */) { return 0; }}; + int operator()(uint16_t opcode, uint8_t* buf, uint8_t len) { return body(opcode, buf, len); } }; extern struct dut_mode_send dut_mode_send; // Name: get_common_criteria_config_compare_result @@ -86,17 +80,15 @@ extern struct dut_mode_send dut_mode_send; // Returns: int struct get_common_criteria_config_compare_result { std::function body{[]() { return 0; }}; - int operator()() { return body(); }; + int operator()() { return body(); } }; -extern struct get_common_criteria_config_compare_result - get_common_criteria_config_compare_result; +extern struct get_common_criteria_config_compare_result get_common_criteria_config_compare_result; // Name: get_remote_device_properties // Params: RawAddress* remote_addr // Returns: int struct get_remote_device_properties { - std::function body{ - [](RawAddress* /* remote_addr */) { return 0; }}; - int operator()(RawAddress* remote_addr) { return body(remote_addr); }; + std::function body{[](RawAddress* /* remote_addr */) { return 0; }}; + int operator()(RawAddress* remote_addr) { return body(remote_addr); } }; extern struct get_remote_device_properties get_remote_device_properties; // Name: get_remote_device_property @@ -104,21 +96,18 @@ extern struct get_remote_device_properties get_remote_device_properties; // Returns: int struct get_remote_device_property { std::function body{ - [](RawAddress* /* remote_addr */, bt_property_type_t /* type */) { - return 0; - }}; + [](RawAddress* /* remote_addr */, bt_property_type_t /* type */) { return 0; }}; int operator()(RawAddress* remote_addr, bt_property_type_t type) { return body(remote_addr, type); - }; + } }; extern struct get_remote_device_property get_remote_device_property; // Name: get_remote_services // Params: RawAddress* remote_addr // Returns: int struct get_remote_services { - std::function body{ - [](RawAddress* /* remote_addr */) { return 0; }}; - int operator()(RawAddress* remote_addr) { return body(remote_addr); }; + std::function body{[](RawAddress* /* remote_addr */) { return 0; }}; + int operator()(RawAddress* remote_addr) { return body(remote_addr); } }; extern struct get_remote_services get_remote_services; // Name: le_test_mode @@ -126,24 +115,19 @@ extern struct get_remote_services get_remote_services; // Returns: int struct le_test_mode { std::function body{ - [](uint16_t /* opcode */, uint8_t* /* buf */, uint8_t /* len */) { - return 0; - }}; - int operator()(uint16_t opcode, uint8_t* buf, uint8_t len) { - return body(opcode, buf, len); - }; + [](uint16_t /* opcode */, uint8_t* /* buf */, uint8_t /* len */) { return 0; }}; + int operator()(uint16_t opcode, uint8_t* buf, uint8_t len) { return body(opcode, buf, len); } }; extern struct le_test_mode le_test_mode; // Name: set_remote_device_property // Params: RawAddress* remote_addr, const bt_property_t* property // Returns: int struct set_remote_device_property { - std::function - body{[](RawAddress* /* remote_addr */, - const bt_property_t* /* property */) { return 0; }}; + std::function body{ + [](RawAddress* /* remote_addr */, const bt_property_t* /* property */) { return 0; }}; int operator()(RawAddress* remote_addr, const bt_property_t* property) { return body(remote_addr, property); - }; + } }; extern struct set_remote_device_property set_remote_device_property; // Name: invoke_switch_buffer_size_cb @@ -151,9 +135,7 @@ extern struct set_remote_device_property set_remote_device_property; // Returns: void struct invoke_switch_buffer_size_cb { std::function body{[](bool) {}}; - void operator()(bool invoke_switch_buffer_size_cb) { - body(invoke_switch_buffer_size_cb); - }; + void operator()(bool invoke_switch_buffer_size_cb) { body(invoke_switch_buffer_size_cb); } }; extern struct invoke_switch_buffer_size_cb invoke_switch_buffer_size_cb; diff --git a/system/test/mock/mock_btif_bta_pan_co_rx.cc b/system/test/mock/mock_btif_bta_pan_co_rx.cc index 3a4874eac06..d1df05d8e1f 100644 --- a/system/test/mock/mock_btif_bta_pan_co_rx.cc +++ b/system/test/mock/mock_btif_bta_pan_co_rx.cc @@ -56,19 +56,15 @@ void bta_pan_co_close(uint16_t handle, uint8_t app_id) { inc_func_call_count(__func__); test::mock::btif_bta_pan_co_rx::bta_pan_co_close(handle, app_id); } -void bta_pan_co_mfilt_ind(uint16_t handle, bool indication, - tBTA_PAN_STATUS result, uint16_t len, +void bta_pan_co_mfilt_ind(uint16_t handle, bool indication, tBTA_PAN_STATUS result, uint16_t len, uint8_t* p_filters) { inc_func_call_count(__func__); - test::mock::btif_bta_pan_co_rx::bta_pan_co_mfilt_ind(handle, indication, - result, len, p_filters); + test::mock::btif_bta_pan_co_rx::bta_pan_co_mfilt_ind(handle, indication, result, len, p_filters); } -void bta_pan_co_pfilt_ind(uint16_t handle, bool indication, - tBTA_PAN_STATUS result, uint16_t len, +void bta_pan_co_pfilt_ind(uint16_t handle, bool indication, tBTA_PAN_STATUS result, uint16_t len, uint8_t* p_filters) { inc_func_call_count(__func__); - test::mock::btif_bta_pan_co_rx::bta_pan_co_pfilt_ind(handle, indication, - result, len, p_filters); + test::mock::btif_bta_pan_co_rx::bta_pan_co_pfilt_ind(handle, indication, result, len, p_filters); } void bta_pan_co_rx_flow(uint16_t handle, uint8_t app_id, bool enable) { inc_func_call_count(__func__); diff --git a/system/test/mock/mock_btif_bta_pan_co_rx.h b/system/test/mock/mock_btif_bta_pan_co_rx.h index d9059c54273..3be4a12631d 100644 --- a/system/test/mock/mock_btif_bta_pan_co_rx.h +++ b/system/test/mock/mock_btif_bta_pan_co_rx.h @@ -36,9 +36,8 @@ namespace btif_bta_pan_co_rx { // Params: uint8_t* q_level // Returns: uint8_t struct bta_pan_co_init { - std::function body{ - [](uint8_t* /* q_level */) { return 0; }}; - uint8_t operator()(uint8_t* q_level) { return body(q_level); }; + std::function body{[](uint8_t* /* q_level */) { return 0; }}; + uint8_t operator()(uint8_t* q_level) { return body(q_level); } }; extern struct bta_pan_co_init bta_pan_co_init; // Name: bta_pan_co_close @@ -46,8 +45,8 @@ extern struct bta_pan_co_init bta_pan_co_init; // Returns: void struct bta_pan_co_close { std::function body{ - [](uint16_t /* handle */, uint8_t /* app_id */) { ; }}; - void operator()(uint16_t handle, uint8_t app_id) { body(handle, app_id); }; + [](uint16_t /* handle */, uint8_t /* app_id */) { ; }}; + void operator()(uint16_t handle, uint8_t app_id) { body(handle, app_id); } }; extern struct bta_pan_co_close bta_pan_co_close; // Name: bta_pan_co_mfilt_ind @@ -55,15 +54,14 @@ extern struct bta_pan_co_close bta_pan_co_close; // tBTA_PAN_STATUS result, uint16_t len, uint8_t* // p_filters Returns: void struct bta_pan_co_mfilt_ind { - std::function - body{[](uint16_t /* handle */, bool /* indication */, - tBTA_PAN_STATUS /* result */, uint16_t /* len */, - uint8_t* /* p_filters */) { ; }}; - void operator()(uint16_t handle, bool indication, tBTA_PAN_STATUS result, - uint16_t len, uint8_t* p_filters) { + std::function + body{[](uint16_t /* handle */, bool /* indication */, tBTA_PAN_STATUS /* result */, + uint16_t /* len */, uint8_t* /* p_filters */) { ; }}; + void operator()(uint16_t handle, bool indication, tBTA_PAN_STATUS result, uint16_t len, + uint8_t* p_filters) { body(handle, indication, result, len, p_filters); - }; + } }; extern struct bta_pan_co_mfilt_ind bta_pan_co_mfilt_ind; // Name: bta_pan_co_pfilt_ind @@ -71,15 +69,14 @@ extern struct bta_pan_co_mfilt_ind bta_pan_co_mfilt_ind; // tBTA_PAN_STATUS result, uint16_t len, uint8_t* // p_filters Returns: void struct bta_pan_co_pfilt_ind { - std::function - body{[](uint16_t /* handle */, bool /* indication */, - tBTA_PAN_STATUS /* result */, uint16_t /* len */, - uint8_t* /* p_filters */) { ; }}; - void operator()(uint16_t handle, bool indication, tBTA_PAN_STATUS result, - uint16_t len, uint8_t* p_filters) { + std::function + body{[](uint16_t /* handle */, bool /* indication */, tBTA_PAN_STATUS /* result */, + uint16_t /* len */, uint8_t* /* p_filters */) { ; }}; + void operator()(uint16_t handle, bool indication, tBTA_PAN_STATUS result, uint16_t len, + uint8_t* p_filters) { body(handle, indication, result, len, p_filters); - }; + } }; extern struct bta_pan_co_pfilt_ind bta_pan_co_pfilt_ind; // Name: bta_pan_co_rx_flow @@ -87,10 +84,8 @@ extern struct bta_pan_co_pfilt_ind bta_pan_co_pfilt_ind; // bool enable Returns: void struct bta_pan_co_rx_flow { std::function body{ - [](uint16_t /* handle */, uint8_t /* app_id */, bool /* enable */) { ; }}; - void operator()(uint16_t handle, uint8_t app_id, bool enable) { - body(handle, app_id, enable); - }; + [](uint16_t /* handle */, uint8_t /* app_id */, bool /* enable */) { ; }}; + void operator()(uint16_t handle, uint8_t app_id, bool enable) { body(handle, app_id, enable); } }; extern struct bta_pan_co_rx_flow bta_pan_co_rx_flow; // Name: bta_pan_co_rx_path @@ -98,8 +93,8 @@ extern struct bta_pan_co_rx_flow bta_pan_co_rx_flow; // Returns: void struct bta_pan_co_rx_path { std::function body{ - [](uint16_t /* handle */, uint8_t /* app_id */) { ; }}; - void operator()(uint16_t handle, uint8_t app_id) { body(handle, app_id); }; + [](uint16_t /* handle */, uint8_t /* app_id */) { ; }}; + void operator()(uint16_t handle, uint8_t app_id) { body(handle, app_id); } }; extern struct bta_pan_co_rx_path bta_pan_co_rx_path; // Name: bta_pan_co_tx_path @@ -107,8 +102,8 @@ extern struct bta_pan_co_rx_path bta_pan_co_rx_path; // Returns: void struct bta_pan_co_tx_path { std::function body{ - [](uint16_t /* handle */, uint8_t /* app_id */) { ; }}; - void operator()(uint16_t handle, uint8_t app_id) { body(handle, app_id); }; + [](uint16_t /* handle */, uint8_t /* app_id */) { ; }}; + void operator()(uint16_t handle, uint8_t app_id) { body(handle, app_id); } }; extern struct bta_pan_co_tx_path bta_pan_co_tx_path; diff --git a/system/test/mock/mock_btif_co_bta_av_co.cc b/system/test/mock/mock_btif_co_bta_av_co.cc index e50e2b19c57..af45a3dc115 100644 --- a/system/test/mock/mock_btif_co_bta_av_co.cc +++ b/system/test/mock/mock_btif_co_bta_av_co.cc @@ -48,8 +48,7 @@ struct bta_av_co_audio_source_data_path bta_av_co_audio_source_data_path; struct bta_av_co_audio_start bta_av_co_audio_start; struct bta_av_co_audio_stop bta_av_co_audio_stop; struct bta_av_co_audio_update_mtu bta_av_co_audio_update_mtu; -struct bta_av_co_get_encoder_effective_frame_size - bta_av_co_get_encoder_effective_frame_size; +struct bta_av_co_get_encoder_effective_frame_size bta_av_co_get_encoder_effective_frame_size; struct bta_av_co_get_encoder_interface bta_av_co_get_encoder_interface; struct bta_av_co_get_peer_params bta_av_co_get_peer_params; struct bta_av_co_get_scmst_info bta_av_co_get_scmst_info; @@ -75,8 +74,7 @@ tA2DP_STATUS bta_av_co_audio_getconfig::return_value = A2DP_SUCCESS; bool bta_av_co_audio_init::return_value = false; BT_HDR* bta_av_co_audio_source_data_path::return_value = nullptr; int bta_av_co_get_encoder_effective_frame_size::return_value = 0; -const tA2DP_ENCODER_INTERFACE* bta_av_co_get_encoder_interface::return_value = - nullptr; +const tA2DP_ENCODER_INTERFACE* bta_av_co_get_encoder_interface::return_value = nullptr; btav_a2dp_scmst_info_t bta_av_co_get_scmst_info::return_value = {}; bool bta_av_co_is_supported_codec::return_value = false; bool bta_av_co_set_active_peer::return_value = false; @@ -90,96 +88,74 @@ A2dpCodecConfig* bta_av_get_a2dp_peer_current_codec::return_value = nullptr; } // namespace test // Mocked functions, if any -void bta_av_co_audio_close(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_address) { +void bta_av_co_audio_close(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address) { inc_func_call_count(__func__); - test::mock::btif_co_bta_av_co::bta_av_co_audio_close(bta_av_handle, - peer_address); + test::mock::btif_co_bta_av_co::bta_av_co_audio_close(bta_av_handle, peer_address); } -void bta_av_co_audio_delay(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_address, uint16_t delay) { +void bta_av_co_audio_delay(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, + uint16_t delay) { inc_func_call_count(__func__); - test::mock::btif_co_bta_av_co::bta_av_co_audio_delay(bta_av_handle, - peer_address, delay); + test::mock::btif_co_bta_av_co::bta_av_co_audio_delay(bta_av_handle, peer_address, delay); } -void bta_av_co_audio_disc_res(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_address, uint8_t num_seps, - uint8_t num_sinks, uint8_t num_sources, +void bta_av_co_audio_disc_res(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, + uint8_t num_seps, uint8_t num_sinks, uint8_t num_sources, uint16_t uuid_local) { inc_func_call_count(__func__); - test::mock::btif_co_bta_av_co::bta_av_co_audio_disc_res( - bta_av_handle, peer_address, num_seps, num_sinks, num_sources, - uuid_local); + test::mock::btif_co_bta_av_co::bta_av_co_audio_disc_res(bta_av_handle, peer_address, num_seps, + num_sinks, num_sources, uuid_local); } -void bta_av_co_audio_drop(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_address) { +void bta_av_co_audio_drop(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address) { inc_func_call_count(__func__); - test::mock::btif_co_bta_av_co::bta_av_co_audio_drop(bta_av_handle, - peer_address); + test::mock::btif_co_bta_av_co::bta_av_co_audio_drop(bta_av_handle, peer_address); } -tA2DP_STATUS bta_av_co_audio_getconfig(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_address, - uint8_t* p_codec_info, - uint8_t* p_sep_info_idx, uint8_t seid, - uint8_t* p_num_protect, - uint8_t* p_protect_info) { +tA2DP_STATUS bta_av_co_audio_getconfig(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, + uint8_t* p_codec_info, uint8_t* p_sep_info_idx, uint8_t seid, + uint8_t* p_num_protect, uint8_t* p_protect_info) { inc_func_call_count(__func__); return test::mock::btif_co_bta_av_co::bta_av_co_audio_getconfig( - bta_av_handle, peer_address, p_codec_info, p_sep_info_idx, seid, - p_num_protect, p_protect_info); + bta_av_handle, peer_address, p_codec_info, p_sep_info_idx, seid, p_num_protect, + p_protect_info); } -bool bta_av_co_audio_init(btav_a2dp_codec_index_t codec_index, - AvdtpSepConfig* p_cfg) { +bool bta_av_co_audio_init(btav_a2dp_codec_index_t codec_index, AvdtpSepConfig* p_cfg) { inc_func_call_count(__func__); - return test::mock::btif_co_bta_av_co::bta_av_co_audio_init(codec_index, - p_cfg); + return test::mock::btif_co_bta_av_co::bta_av_co_audio_init(codec_index, p_cfg); } -void bta_av_co_audio_open(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_address, uint16_t mtu) { +void bta_av_co_audio_open(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, + uint16_t mtu) { inc_func_call_count(__func__); - test::mock::btif_co_bta_av_co::bta_av_co_audio_open(bta_av_handle, - peer_address, mtu); + test::mock::btif_co_bta_av_co::bta_av_co_audio_open(bta_av_handle, peer_address, mtu); } -void bta_av_co_audio_setconfig(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_address, - const uint8_t* p_codec_info, uint8_t seid, - uint8_t num_protect, - const uint8_t* p_protect_info, - uint8_t t_local_sep, uint8_t avdt_handle) { +void bta_av_co_audio_setconfig(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, + const uint8_t* p_codec_info, uint8_t seid, uint8_t num_protect, + const uint8_t* p_protect_info, uint8_t t_local_sep, + uint8_t avdt_handle) { inc_func_call_count(__func__); test::mock::btif_co_bta_av_co::bta_av_co_audio_setconfig( - bta_av_handle, peer_address, p_codec_info, seid, num_protect, - p_protect_info, t_local_sep, avdt_handle); + bta_av_handle, peer_address, p_codec_info, seid, num_protect, p_protect_info, t_local_sep, + avdt_handle); } -BT_HDR* bta_av_co_audio_source_data_path(const uint8_t* p_codec_info, - uint32_t* p_timestamp) { +BT_HDR* bta_av_co_audio_source_data_path(const uint8_t* p_codec_info, uint32_t* p_timestamp) { inc_func_call_count(__func__); - return test::mock::btif_co_bta_av_co::bta_av_co_audio_source_data_path( - p_codec_info, p_timestamp); + return test::mock::btif_co_bta_av_co::bta_av_co_audio_source_data_path(p_codec_info, p_timestamp); } -void bta_av_co_audio_start(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_address, +void bta_av_co_audio_start(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, const uint8_t* p_codec_info, bool* p_no_rtp_header) { inc_func_call_count(__func__); - test::mock::btif_co_bta_av_co::bta_av_co_audio_start( - bta_av_handle, peer_address, p_codec_info, p_no_rtp_header); + test::mock::btif_co_bta_av_co::bta_av_co_audio_start(bta_av_handle, peer_address, p_codec_info, + p_no_rtp_header); } -void bta_av_co_audio_stop(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_address) { +void bta_av_co_audio_stop(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address) { inc_func_call_count(__func__); - test::mock::btif_co_bta_av_co::bta_av_co_audio_stop(bta_av_handle, - peer_address); + test::mock::btif_co_bta_av_co::bta_av_co_audio_stop(bta_av_handle, peer_address); } -void bta_av_co_audio_update_mtu(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_address, uint16_t mtu) { +void bta_av_co_audio_update_mtu(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, + uint16_t mtu) { inc_func_call_count(__func__); - test::mock::btif_co_bta_av_co::bta_av_co_audio_update_mtu(bta_av_handle, - peer_address, mtu); + test::mock::btif_co_bta_av_co::bta_av_co_audio_update_mtu(bta_av_handle, peer_address, mtu); } int bta_av_co_get_encoder_effective_frame_size() { inc_func_call_count(__func__); - return test::mock::btif_co_bta_av_co:: - bta_av_co_get_encoder_effective_frame_size(); + return test::mock::btif_co_bta_av_co::bta_av_co_get_encoder_effective_frame_size(); } const tA2DP_ENCODER_INTERFACE* bta_av_co_get_encoder_interface(void) { inc_func_call_count(__func__); @@ -188,52 +164,43 @@ const tA2DP_ENCODER_INTERFACE* bta_av_co_get_encoder_interface(void) { void bta_av_co_get_peer_params(const RawAddress& peer_address, tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params) { inc_func_call_count(__func__); - test::mock::btif_co_bta_av_co::bta_av_co_get_peer_params(peer_address, - p_peer_params); + test::mock::btif_co_bta_av_co::bta_av_co_get_peer_params(peer_address, p_peer_params); } -btav_a2dp_scmst_info_t bta_av_co_get_scmst_info( - const RawAddress& peer_address) { +btav_a2dp_scmst_info_t bta_av_co_get_scmst_info(const RawAddress& peer_address) { inc_func_call_count(__func__); return test::mock::btif_co_bta_av_co::bta_av_co_get_scmst_info(peer_address); } -void bta_av_co_init( - const std::vector& codec_priorities, - std::vector* supported_codecs) { +void bta_av_co_init(const std::vector& codec_priorities, + std::vector* supported_codecs) { inc_func_call_count(__func__); - test::mock::btif_co_bta_av_co::bta_av_co_init(codec_priorities, - supported_codecs); + test::mock::btif_co_bta_av_co::bta_av_co_init(codec_priorities, supported_codecs); } bool bta_av_co_is_supported_codec(btav_a2dp_codec_index_t codec_index) { inc_func_call_count(__func__); - return test::mock::btif_co_bta_av_co::bta_av_co_is_supported_codec( - codec_index); + return test::mock::btif_co_bta_av_co::bta_av_co_is_supported_codec(codec_index); } bool bta_av_co_set_active_peer(const RawAddress& peer_address) { inc_func_call_count(__func__); return test::mock::btif_co_bta_av_co::bta_av_co_set_active_peer(peer_address); } -bool bta_av_co_set_codec_audio_config( - const btav_a2dp_codec_config_t& codec_audio_config) { +bool bta_av_co_set_codec_audio_config(const btav_a2dp_codec_config_t& codec_audio_config) { inc_func_call_count(__func__); - return test::mock::btif_co_bta_av_co::bta_av_co_set_codec_audio_config( - codec_audio_config); + return test::mock::btif_co_bta_av_co::bta_av_co_set_codec_audio_config(codec_audio_config); } -bool bta_av_co_set_codec_user_config( - const RawAddress& peer_address, - const btav_a2dp_codec_config_t& codec_user_config, bool* p_restart_output) { +bool bta_av_co_set_codec_user_config(const RawAddress& peer_address, + const btav_a2dp_codec_config_t& codec_user_config, + bool* p_restart_output) { inc_func_call_count(__func__); return test::mock::btif_co_bta_av_co::bta_av_co_set_codec_user_config( - peer_address, codec_user_config, p_restart_output); + peer_address, codec_user_config, p_restart_output); } A2dpCodecConfig* bta_av_get_a2dp_current_codec(void) { inc_func_call_count(__func__); return test::mock::btif_co_bta_av_co::bta_av_get_a2dp_current_codec(); } -A2dpCodecConfig* bta_av_get_a2dp_peer_current_codec( - const RawAddress& peer_address) { +A2dpCodecConfig* bta_av_get_a2dp_peer_current_codec(const RawAddress& peer_address) { inc_func_call_count(__func__); - return test::mock::btif_co_bta_av_co::bta_av_get_a2dp_peer_current_codec( - peer_address); + return test::mock::btif_co_bta_av_co::bta_av_get_a2dp_peer_current_codec(peer_address); } void btif_a2dp_codec_debug_dump(int fd) { inc_func_call_count(__func__); diff --git a/system/test/mock/mock_btif_co_bta_av_co.h b/system/test/mock/mock_btif_co_bta_av_co.h index 69de9c77798..fefec8b5d8b 100644 --- a/system/test/mock/mock_btif_co_bta_av_co.h +++ b/system/test/mock/mock_btif_co_bta_av_co.h @@ -49,13 +49,11 @@ namespace btif_co_bta_av_co { // Params: tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address // Return: void struct bta_av_co_audio_close { - std::function - body{[](tBTA_AV_HNDL /* bta_av_handle */, - const RawAddress& /* peer_address */) {}}; + std::function body{ + [](tBTA_AV_HNDL /* bta_av_handle */, const RawAddress& /* peer_address */) {}}; void operator()(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address) { body(bta_av_handle, peer_address); - }; + } }; extern struct bta_av_co_audio_close bta_av_co_audio_close; @@ -63,14 +61,12 @@ extern struct bta_av_co_audio_close bta_av_co_audio_close; // Params: tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, uint16_t // delay Return: void struct bta_av_co_audio_delay { - std::function - body{[](tBTA_AV_HNDL /* bta_av_handle */, - const RawAddress& /* peer_address */, uint16_t /* delay */) {}}; - void operator()(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, - uint16_t delay) { + std::function + body{[](tBTA_AV_HNDL /* bta_av_handle */, const RawAddress& /* peer_address */, + uint16_t /* delay */) {}}; + void operator()(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, uint16_t delay) { body(bta_av_handle, peer_address, delay); - }; + } }; extern struct bta_av_co_audio_delay bta_av_co_audio_delay; @@ -79,19 +75,15 @@ extern struct bta_av_co_audio_delay bta_av_co_audio_delay; // num_seps, uint8_t num_sinks, uint8_t num_sources, uint16_t uuid_local Return: // void struct bta_av_co_audio_disc_res { - std::function - body{[](tBTA_AV_HNDL /* bta_av_handle */, - const RawAddress& /* peer_address */, uint8_t /* num_seps */, - uint8_t /* num_sinks */, uint8_t /* num_sources */, - uint16_t /* uuid_local */) {}}; - void operator()(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, - uint8_t num_seps, uint8_t num_sinks, uint8_t num_sources, - uint16_t uuid_local) { - body(bta_av_handle, peer_address, num_seps, num_sinks, num_sources, - uuid_local); - }; + std::function + body{[](tBTA_AV_HNDL /* bta_av_handle */, const RawAddress& /* peer_address */, + uint8_t /* num_seps */, uint8_t /* num_sinks */, uint8_t /* num_sources */, + uint16_t /* uuid_local */) {}}; + void operator()(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, uint8_t num_seps, + uint8_t num_sinks, uint8_t num_sources, uint16_t uuid_local) { + body(bta_av_handle, peer_address, num_seps, num_sinks, num_sources, uuid_local); + } }; extern struct bta_av_co_audio_disc_res bta_av_co_audio_disc_res; @@ -99,13 +91,11 @@ extern struct bta_av_co_audio_disc_res bta_av_co_audio_disc_res; // Params: tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address // Return: void struct bta_av_co_audio_drop { - std::function - body{[](tBTA_AV_HNDL /* bta_av_handle */, - const RawAddress& /* peer_address */) {}}; + std::function body{ + [](tBTA_AV_HNDL /* bta_av_handle */, const RawAddress& /* peer_address */) {}}; void operator()(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address) { body(bta_av_handle, peer_address); - }; + } }; extern struct bta_av_co_audio_drop bta_av_co_audio_drop; @@ -115,22 +105,19 @@ extern struct bta_av_co_audio_drop bta_av_co_audio_drop; // uint8_t* p_protect_info Return: tA2DP_STATUS struct bta_av_co_audio_getconfig { static tA2DP_STATUS return_value; - std::function - body{[](tBTA_AV_HNDL /* bta_av_handle */, - const RawAddress& /* peer_address */, uint8_t* /* p_codec_info */, - uint8_t* /* p_sep_info_idx */, uint8_t /* seid */, - uint8_t* /* p_num_protect */, - uint8_t* /* p_protect_info */) { return return_value; }}; - tA2DP_STATUS operator()(tBTA_AV_HNDL bta_av_handle, - const RawAddress& peer_address, uint8_t* p_codec_info, - uint8_t* p_sep_info_idx, uint8_t seid, + std::function + body{[](tBTA_AV_HNDL /* bta_av_handle */, const RawAddress& /* peer_address */, + uint8_t* /* p_codec_info */, uint8_t* /* p_sep_info_idx */, uint8_t /* seid */, + uint8_t* /* p_num_protect */, + uint8_t* /* p_protect_info */) { return return_value; }}; + tA2DP_STATUS operator()(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, + uint8_t* p_codec_info, uint8_t* p_sep_info_idx, uint8_t seid, uint8_t* p_num_protect, uint8_t* p_protect_info) { - return body(bta_av_handle, peer_address, p_codec_info, p_sep_info_idx, seid, - p_num_protect, p_protect_info); - }; + return body(bta_av_handle, peer_address, p_codec_info, p_sep_info_idx, seid, p_num_protect, + p_protect_info); + } }; extern struct bta_av_co_audio_getconfig bta_av_co_audio_getconfig; @@ -139,13 +126,13 @@ extern struct bta_av_co_audio_getconfig bta_av_co_audio_getconfig; // Return: bool struct bta_av_co_audio_init { static bool return_value; - std::function - body{[](btav_a2dp_codec_index_t /* codec_index */, - AvdtpSepConfig* /* p_cfg */) { return return_value; }}; + std::function body{ + [](btav_a2dp_codec_index_t /* codec_index */, AvdtpSepConfig* /* p_cfg */) { + return return_value; + }}; bool operator()(btav_a2dp_codec_index_t codec_index, AvdtpSepConfig* p_cfg) { return body(codec_index, p_cfg); - }; + } }; extern struct bta_av_co_audio_init bta_av_co_audio_init; @@ -153,14 +140,12 @@ extern struct bta_av_co_audio_init bta_av_co_audio_init; // Params: tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, uint16_t // mtu Return: void struct bta_av_co_audio_open { - std::function - body{[](tBTA_AV_HNDL /* bta_av_handle */, - const RawAddress& /* peer_address */, uint16_t /* mtu */) {}}; - void operator()(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, - uint16_t mtu) { + std::function + body{[](tBTA_AV_HNDL /* bta_av_handle */, const RawAddress& /* peer_address */, + uint16_t /* mtu */) {}}; + void operator()(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, uint16_t mtu) { body(bta_av_handle, peer_address, mtu); - }; + } }; extern struct bta_av_co_audio_open bta_av_co_audio_open; @@ -170,21 +155,18 @@ extern struct bta_av_co_audio_open bta_av_co_audio_open; // p_protect_info, uint8_t t_local_sep, uint8_t avdt_handle Return: void struct bta_av_co_audio_setconfig { std::function - body{[](tBTA_AV_HNDL /* bta_av_handle */, - const RawAddress& /* peer_address */, - const uint8_t* /* p_codec_info */, uint8_t /* seid */, - uint8_t /* num_protect */, const uint8_t* /* p_protect_info */, - uint8_t /* t_local_sep */, uint8_t /* avdt_handle */) {}}; + const uint8_t* p_codec_info, uint8_t seid, uint8_t num_protect, + const uint8_t* p_protect_info, uint8_t t_local_sep, uint8_t avdt_handle)> + body{[](tBTA_AV_HNDL /* bta_av_handle */, const RawAddress& /* peer_address */, + const uint8_t* /* p_codec_info */, uint8_t /* seid */, uint8_t /* num_protect */, + const uint8_t* /* p_protect_info */, uint8_t /* t_local_sep */, + uint8_t /* avdt_handle */) {}}; void operator()(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, - const uint8_t* p_codec_info, uint8_t seid, - uint8_t num_protect, const uint8_t* p_protect_info, - uint8_t t_local_sep, uint8_t avdt_handle) { - body(bta_av_handle, peer_address, p_codec_info, seid, num_protect, - p_protect_info, t_local_sep, avdt_handle); - }; + const uint8_t* p_codec_info, uint8_t seid, uint8_t num_protect, + const uint8_t* p_protect_info, uint8_t t_local_sep, uint8_t avdt_handle) { + body(bta_av_handle, peer_address, p_codec_info, seid, num_protect, p_protect_info, t_local_sep, + avdt_handle); + } }; extern struct bta_av_co_audio_setconfig bta_av_co_audio_setconfig; @@ -193,13 +175,13 @@ extern struct bta_av_co_audio_setconfig bta_av_co_audio_setconfig; // Return: BT_HDR* struct bta_av_co_audio_source_data_path { static BT_HDR* return_value; - std::function - body{[](const uint8_t* /* p_codec_info */, uint32_t* /* p_timestamp */) { - return return_value; - }}; + std::function body{ + [](const uint8_t* /* p_codec_info */, uint32_t* /* p_timestamp */) { + return return_value; + }}; BT_HDR* operator()(const uint8_t* p_codec_info, uint32_t* p_timestamp) { return body(p_codec_info, p_timestamp); - }; + } }; extern struct bta_av_co_audio_source_data_path bta_av_co_audio_source_data_path; @@ -209,14 +191,12 @@ extern struct bta_av_co_audio_source_data_path bta_av_co_audio_source_data_path; struct bta_av_co_audio_start { std::function - body{[](tBTA_AV_HNDL /* bta_av_handle */, - const RawAddress& /* peer_address */, - const uint8_t* /* p_codec_info */, - bool* /* p_no_rtp_header */) {}}; + body{[](tBTA_AV_HNDL /* bta_av_handle */, const RawAddress& /* peer_address */, + const uint8_t* /* p_codec_info */, bool* /* p_no_rtp_header */) {}}; void operator()(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, const uint8_t* p_codec_info, bool* p_no_rtp_header) { body(bta_av_handle, peer_address, p_codec_info, p_no_rtp_header); - }; + } }; extern struct bta_av_co_audio_start bta_av_co_audio_start; @@ -224,13 +204,11 @@ extern struct bta_av_co_audio_start bta_av_co_audio_start; // Params: tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address // Return: void struct bta_av_co_audio_stop { - std::function - body{[](tBTA_AV_HNDL /* bta_av_handle */, - const RawAddress& /* peer_address */) {}}; + std::function body{ + [](tBTA_AV_HNDL /* bta_av_handle */, const RawAddress& /* peer_address */) {}}; void operator()(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address) { body(bta_av_handle, peer_address); - }; + } }; extern struct bta_av_co_audio_stop bta_av_co_audio_stop; @@ -238,14 +216,12 @@ extern struct bta_av_co_audio_stop bta_av_co_audio_stop; // Params: tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, uint16_t // mtu Return: void struct bta_av_co_audio_update_mtu { - std::function - body{[](tBTA_AV_HNDL /* bta_av_handle */, - const RawAddress& /* peer_address */, uint16_t /* mtu */) {}}; - void operator()(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, - uint16_t mtu) { + std::function + body{[](tBTA_AV_HNDL /* bta_av_handle */, const RawAddress& /* peer_address */, + uint16_t /* mtu */) {}}; + void operator()(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, uint16_t mtu) { body(bta_av_handle, peer_address, mtu); - }; + } }; extern struct bta_av_co_audio_update_mtu bta_av_co_audio_update_mtu; @@ -255,19 +231,17 @@ extern struct bta_av_co_audio_update_mtu bta_av_co_audio_update_mtu; struct bta_av_co_get_encoder_effective_frame_size { static int return_value; std::function body{[]() { return return_value; }}; - int operator()() { return body(); }; + int operator()() { return body(); } }; -extern struct bta_av_co_get_encoder_effective_frame_size - bta_av_co_get_encoder_effective_frame_size; +extern struct bta_av_co_get_encoder_effective_frame_size bta_av_co_get_encoder_effective_frame_size; // Name: bta_av_co_get_encoder_interface // Params: void // Return: const tA2DP_ENCODER_INTERFACE* struct bta_av_co_get_encoder_interface { static const tA2DP_ENCODER_INTERFACE* return_value; - std::function body{ - [](void) { return return_value; }}; - const tA2DP_ENCODER_INTERFACE* operator()(void) { return body(); }; + std::function body{[](void) { return return_value; }}; + const tA2DP_ENCODER_INTERFACE* operator()(void) { return body(); } }; extern struct bta_av_co_get_encoder_interface bta_av_co_get_encoder_interface; @@ -275,14 +249,12 @@ extern struct bta_av_co_get_encoder_interface bta_av_co_get_encoder_interface; // Params: const RawAddress& peer_address, tA2DP_ENCODER_INIT_PEER_PARAMS* // p_peer_params Return: void struct bta_av_co_get_peer_params { - std::function - body{[](const RawAddress& /* peer_address */, - tA2DP_ENCODER_INIT_PEER_PARAMS* /* p_peer_params */) {}}; - void operator()(const RawAddress& peer_address, - tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params) { + std::function + body{[](const RawAddress& /* peer_address */, + tA2DP_ENCODER_INIT_PEER_PARAMS* /* p_peer_params */) {}}; + void operator()(const RawAddress& peer_address, tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params) { body(peer_address, p_peer_params); - }; + } }; extern struct bta_av_co_get_peer_params bta_av_co_get_peer_params; @@ -292,10 +264,8 @@ extern struct bta_av_co_get_peer_params bta_av_co_get_peer_params; struct bta_av_co_get_scmst_info { static btav_a2dp_scmst_info_t return_value; std::function body{ - [](const RawAddress& /* peer_address */) { return return_value; }}; - btav_a2dp_scmst_info_t operator()(const RawAddress& peer_address) { - return body(peer_address); - }; + [](const RawAddress& /* peer_address */) { return return_value; }}; + btav_a2dp_scmst_info_t operator()(const RawAddress& peer_address) { return body(peer_address); } }; extern struct bta_av_co_get_scmst_info bta_av_co_get_scmst_info; @@ -303,16 +273,14 @@ extern struct bta_av_co_get_scmst_info bta_av_co_get_scmst_info; // Params: const std::vector& codec_priorities // Return: void struct bta_av_co_init { - std::function& codec_priorities, - std::vector* supported_codecs)> - body{[](const std::vector< - btav_a2dp_codec_config_t>& /* codec_priorities */, - std::vector* /* supported_codecs */) {}}; + std::function& codec_priorities, + std::vector* supported_codecs)> + body{[](const std::vector& /* codec_priorities */, + std::vector* /* supported_codecs */) {}}; void operator()(const std::vector& codec_priorities, std::vector* supported_codecs) { body(codec_priorities, supported_codecs); - }; + } }; extern struct bta_av_co_init bta_av_co_init; @@ -322,10 +290,8 @@ extern struct bta_av_co_init bta_av_co_init; struct bta_av_co_is_supported_codec { static bool return_value; std::function body{ - [](btav_a2dp_codec_index_t /* codec_index */) { return return_value; }}; - bool operator()(btav_a2dp_codec_index_t codec_index) { - return body(codec_index); - }; + [](btav_a2dp_codec_index_t /* codec_index */) { return return_value; }}; + bool operator()(btav_a2dp_codec_index_t codec_index) { return body(codec_index); } }; extern struct bta_av_co_is_supported_codec bta_av_co_is_supported_codec; @@ -335,10 +301,8 @@ extern struct bta_av_co_is_supported_codec bta_av_co_is_supported_codec; struct bta_av_co_set_active_peer { static bool return_value; std::function body{ - [](const RawAddress& /* peer_address */) { return return_value; }}; - bool operator()(const RawAddress& peer_address) { - return body(peer_address); - }; + [](const RawAddress& /* peer_address */) { return return_value; }}; + bool operator()(const RawAddress& peer_address) { return body(peer_address); } }; extern struct bta_av_co_set_active_peer bta_av_co_set_active_peer; @@ -348,12 +312,10 @@ extern struct bta_av_co_set_active_peer bta_av_co_set_active_peer; struct bta_av_co_set_codec_audio_config { static bool return_value; std::function body{ - [](const btav_a2dp_codec_config_t& /* codec_audio_config */) { - return return_value; - }}; + [](const btav_a2dp_codec_config_t& /* codec_audio_config */) { return return_value; }}; bool operator()(const btav_a2dp_codec_config_t& codec_audio_config) { return body(codec_audio_config); - }; + } }; extern struct bta_av_co_set_codec_audio_config bta_av_co_set_codec_audio_config; @@ -363,16 +325,14 @@ extern struct bta_av_co_set_codec_audio_config bta_av_co_set_codec_audio_config; struct bta_av_co_set_codec_user_config { static bool return_value; std::function - body{[](const RawAddress& /* peer_address */, - const btav_a2dp_codec_config_t& /* codec_user_config */, - bool* /* p_restart_output */) { return return_value; }}; - bool operator()(const RawAddress& peer_address, - const btav_a2dp_codec_config_t& codec_user_config, + const btav_a2dp_codec_config_t& codec_user_config, bool* p_restart_output)> + body{[](const RawAddress& /* peer_address */, + const btav_a2dp_codec_config_t& /* codec_user_config */, + bool* /* p_restart_output */) { return return_value; }}; + bool operator()(const RawAddress& peer_address, const btav_a2dp_codec_config_t& codec_user_config, bool* p_restart_output) { return body(peer_address, codec_user_config, p_restart_output); - }; + } }; extern struct bta_av_co_set_codec_user_config bta_av_co_set_codec_user_config; @@ -382,7 +342,7 @@ extern struct bta_av_co_set_codec_user_config bta_av_co_set_codec_user_config; struct bta_av_get_a2dp_current_codec { static A2dpCodecConfig* return_value; std::function body{[](void) { return return_value; }}; - A2dpCodecConfig* operator()(void) { return body(); }; + A2dpCodecConfig* operator()(void) { return body(); } }; extern struct bta_av_get_a2dp_current_codec bta_av_get_a2dp_current_codec; @@ -392,20 +352,17 @@ extern struct bta_av_get_a2dp_current_codec bta_av_get_a2dp_current_codec; struct bta_av_get_a2dp_peer_current_codec { static A2dpCodecConfig* return_value; std::function body{ - [](const RawAddress& /* peer_address */) { return return_value; }}; - A2dpCodecConfig* operator()(const RawAddress& peer_address) { - return body(peer_address); - }; + [](const RawAddress& /* peer_address */) { return return_value; }}; + A2dpCodecConfig* operator()(const RawAddress& peer_address) { return body(peer_address); } }; -extern struct bta_av_get_a2dp_peer_current_codec - bta_av_get_a2dp_peer_current_codec; +extern struct bta_av_get_a2dp_peer_current_codec bta_av_get_a2dp_peer_current_codec; // Name: btif_a2dp_codec_debug_dump // Params: int fd // Return: void struct btif_a2dp_codec_debug_dump { std::function body{[](int /* fd */) {}}; - void operator()(int fd) { body(fd); }; + void operator()(int fd) { body(fd); } }; extern struct btif_a2dp_codec_debug_dump btif_a2dp_codec_debug_dump; diff --git a/system/test/mock/mock_btif_co_bta_dm_co.cc b/system/test/mock/mock_btif_co_bta_dm_co.cc index d7ccf69a36b..d2e4244b07d 100644 --- a/system/test/mock/mock_btif_co_bta_dm_co.cc +++ b/system/test/mock/mock_btif_co_bta_dm_co.cc @@ -24,13 +24,11 @@ #include "bta/sys/bta_sys.h" #include "internal_include/bte_appl.h" -tBTE_APPL_CFG bte_appl_cfg = { - BTA_LE_AUTH_REQ_SC_MITM_BOND, // Authentication requirements - BTM_IO_CAP_UNKNOWN, BTM_BLE_INITIATOR_KEY_SIZE, BTM_BLE_RESPONDER_KEY_SIZE, - BTM_BLE_MAX_KEY_SIZE}; +tBTE_APPL_CFG bte_appl_cfg = {BTA_LE_AUTH_REQ_SC_MITM_BOND, // Authentication requirements + BTM_IO_CAP_UNKNOWN, BTM_BLE_INITIATOR_KEY_SIZE, + BTM_BLE_RESPONDER_KEY_SIZE, BTM_BLE_MAX_KEY_SIZE}; -bool bta_dm_co_get_compress_memory(tBTA_SYS_ID /* id */, - uint8_t** /* memory_p */, +bool bta_dm_co_get_compress_memory(tBTA_SYS_ID /* id */, uint8_t** /* memory_p */, uint32_t* /* memory_size */) { return true; } diff --git a/system/test/mock/mock_btif_co_bta_hh_co.cc b/system/test/mock/mock_btif_co_bta_hh_co.cc index d4a8fc17614..dc6fa89de94 100644 --- a/system/test/mock/mock_btif_co_bta_hh_co.cc +++ b/system/test/mock/mock_btif_co_bta_hh_co.cc @@ -31,17 +31,13 @@ int bta_hh_co_write(int /* fd */, uint8_t* /* rpt */, uint16_t /* len */) { inc_func_call_count(__func__); return 0; } -tBTA_HH_RPT_CACHE_ENTRY* bta_hh_le_co_cache_load( - const tAclLinkSpec& /* link_spec */, uint8_t* /* p_num_rpt */, - uint8_t /* app_id */) { +tBTA_HH_RPT_CACHE_ENTRY* bta_hh_le_co_cache_load(const tAclLinkSpec& /* link_spec */, + uint8_t* /* p_num_rpt */, uint8_t /* app_id */) { inc_func_call_count(__func__); return nullptr; } -void bta_hh_co_close(btif_hh_device_t* /* p_dev */) { - inc_func_call_count(__func__); -} -void bta_hh_co_data(uint8_t /* dev_handle */, uint8_t* /* p_rpt */, - uint16_t /* len */) { +void bta_hh_co_close(btif_hh_device_t* /* p_dev */) { inc_func_call_count(__func__); } +void bta_hh_co_data(uint8_t /* dev_handle */, uint8_t* /* p_rpt */, uint16_t /* len */) { inc_func_call_count(__func__); } void bta_hh_co_get_rpt_rsp(uint8_t /* dev_handle */, uint8_t /* status */, @@ -54,24 +50,20 @@ bool bta_hh_co_open(uint8_t /* dev_handle */, uint8_t /* sub_class */, inc_func_call_count(__func__); return true; } -void bta_hh_co_send_hid_info(btif_hh_device_t* /* p_dev */, - const char* /* dev_name */, - uint16_t /* vendor_id */, - uint16_t /* product_id */, uint16_t /* version */, - uint8_t /* ctry_code */, int /* dscp_len */, +void bta_hh_co_send_hid_info(btif_hh_device_t* /* p_dev */, const char* /* dev_name */, + uint16_t /* vendor_id */, uint16_t /* product_id */, + uint16_t /* version */, uint8_t /* ctry_code */, int /* dscp_len */, uint8_t* /* p_dscp */) { inc_func_call_count(__func__); } void bta_hh_co_set_rpt_rsp(uint8_t /* dev_handle */, uint8_t /* status */) { inc_func_call_count(__func__); } -void bta_hh_le_co_reset_rpt_cache(const tAclLinkSpec& /* link_spec */, - uint8_t /* app_id */) { +void bta_hh_le_co_reset_rpt_cache(const tAclLinkSpec& /* link_spec */, uint8_t /* app_id */) { inc_func_call_count(__func__); } void bta_hh_le_co_rpt_info(const tAclLinkSpec& /* link_spec */, - tBTA_HH_RPT_CACHE_ENTRY* /* p_entry */, - uint8_t /* app_id */) { + tBTA_HH_RPT_CACHE_ENTRY* /* p_entry */, uint8_t /* app_id */) { inc_func_call_count(__func__); } void uhid_set_non_blocking(int /* fd */) { inc_func_call_count(__func__); } diff --git a/system/test/mock/mock_btif_config.cc b/system/test/mock/mock_btif_config.cc index f7debf40a9f..1d8bafa8cbc 100644 --- a/system/test/mock/mock_btif_config.cc +++ b/system/test/mock/mock_btif_config.cc @@ -72,53 +72,45 @@ bool btif_config_exist(const std::string& section, const std::string& key) { inc_func_call_count(__func__); return test::mock::btif_config::btif_config_exist(section, key); } -bool btif_config_get_int(const std::string& section, const std::string& key, - int* value) { +bool btif_config_get_int(const std::string& section, const std::string& key, int* value) { inc_func_call_count(__func__); return test::mock::btif_config::btif_config_get_int(section, key, value); } -bool btif_config_set_int(const std::string& section, const std::string& key, - int value) { +bool btif_config_set_int(const std::string& section, const std::string& key, int value) { inc_func_call_count(__func__); return test::mock::btif_config::btif_config_set_int(section, key, value); } -bool btif_config_get_uint64(const std::string& section, const std::string& key, - uint64_t* value) { +bool btif_config_get_uint64(const std::string& section, const std::string& key, uint64_t* value) { inc_func_call_count(__func__); return test::mock::btif_config::btif_config_get_uint64(section, key, value); } -bool btif_config_set_uint64(const std::string& section, const std::string& key, - uint64_t value) { +bool btif_config_set_uint64(const std::string& section, const std::string& key, uint64_t value) { inc_func_call_count(__func__); return test::mock::btif_config::btif_config_set_uint64(section, key, value); } -bool btif_config_get_str(const std::string& section, const std::string& key, - char* value, int* size_bytes) { +bool btif_config_get_str(const std::string& section, const std::string& key, char* value, + int* size_bytes) { inc_func_call_count(__func__); - return test::mock::btif_config::btif_config_get_str(section, key, value, - size_bytes); + return test::mock::btif_config::btif_config_get_str(section, key, value, size_bytes); } bool btif_config_set_str(const std::string& section, const std::string& key, const std::string& value) { inc_func_call_count(__func__); return test::mock::btif_config::btif_config_set_str(section, key, value); } -bool btif_config_get_bin(const std::string& section, const std::string& key, - uint8_t* value, size_t* length) { +bool btif_config_get_bin(const std::string& section, const std::string& key, uint8_t* value, + size_t* length) { inc_func_call_count(__func__); - return test::mock::btif_config::btif_config_get_bin(section, key, value, - length); + return test::mock::btif_config::btif_config_get_bin(section, key, value, length); } -size_t btif_config_get_bin_length(const std::string& section, - const std::string& key) { +size_t btif_config_get_bin_length(const std::string& section, const std::string& key) { inc_func_call_count(__func__); return test::mock::btif_config::btif_config_get_bin_length(section, key); } -bool btif_config_set_bin(const std::string& section, const std::string& key, - const uint8_t* value, size_t length) { +bool btif_config_set_bin(const std::string& section, const std::string& key, const uint8_t* value, + size_t length) { inc_func_call_count(__func__); - return test::mock::btif_config::btif_config_set_bin(section, key, value, - length); + return test::mock::btif_config::btif_config_set_bin(section, key, value, length); } std::vector btif_config_get_paired_devices() { inc_func_call_count(__func__); diff --git a/system/test/mock/mock_btif_config.h b/system/test/mock/mock_btif_config.h index bb77401f9ea..bf2ec928432 100644 --- a/system/test/mock/mock_btif_config.h +++ b/system/test/mock/mock_btif_config.h @@ -42,162 +42,140 @@ namespace btif_config { // Returns: bool struct btif_get_device_clockoffset { std::function body{ - [](const RawAddress& /* bda */, int* /* p_clock_offset */) { - return false; - }}; - bool operator()(const RawAddress& bda, int* p_clock_offset) { - return body(bda, p_clock_offset); - }; + [](const RawAddress& /* bda */, int* /* p_clock_offset */) { return false; }}; + bool operator()(const RawAddress& bda, int* p_clock_offset) { return body(bda, p_clock_offset); } }; // Name: btif_set_device_clockoffset // Params: const RawAddress& bda, int* p_clock_offset // Returns: bool struct btif_set_device_clockoffset { std::function body{ - [](const RawAddress& /* bda */, int /* clock_offset */) { - return false; - }}; - bool operator()(const RawAddress& bda, int clock_offset) { - return body(bda, clock_offset); - }; + [](const RawAddress& /* bda */, int /* clock_offset */) { return false; }}; + bool operator()(const RawAddress& bda, int clock_offset) { return body(bda, clock_offset); } }; // Name: btif_config_exist // Params: const std::string& section, const std::string& key // Returns: bool struct btif_config_exist { std::function body{ - [](const std::string& /* section */, const std::string& /* key */) { - return false; - }}; - bool operator()(const std::string& section, const std::string& key) { - return body(section, key); - }; + [](const std::string& /* section */, const std::string& /* key */) { return false; }}; + bool operator()(const std::string& section, const std::string& key) { return body(section, key); } }; extern struct btif_config_exist btif_config_exist; // Name: btif_config_get_int // Params: const std::string& section, const std::string& key, int* value // Returns: bool struct btif_config_get_int { - std::function - body{[](const std::string& /* section */, const std::string& /* key */, - int* /* value */) { return false; }}; - bool operator()(const std::string& section, const std::string& key, - int* value) { + std::function body{ + [](const std::string& /* section */, const std::string& /* key */, int* /* value */) { + return false; + }}; + bool operator()(const std::string& section, const std::string& key, int* value) { return body(section, key, value); - }; + } }; extern struct btif_config_get_int btif_config_get_int; // Name: btif_config_set_int // Params: const std::string& section, const std::string& key, int value // Returns: bool struct btif_config_set_int { - std::function - body{[](const std::string& /* section */, const std::string& /* key */, - int /* value */) { return false; }}; - bool operator()(const std::string& section, const std::string& key, - int value) { + std::function body{ + [](const std::string& /* section */, const std::string& /* key */, int /* value */) { + return false; + }}; + bool operator()(const std::string& section, const std::string& key, int value) { return body(section, key, value); - }; + } }; extern struct btif_config_set_int btif_config_set_int; // Name: btif_config_get_uint64 // Params: const std::string& section, const std::string& key, uint64_t* value // Returns: bool struct btif_config_get_uint64 { - std::function - body{[](const std::string& /* section */, const std::string& /* key */, - uint64_t* /* value */) { return false; }}; - bool operator()(const std::string& section, const std::string& key, - uint64_t* value) { + std::function body{ + [](const std::string& /* section */, const std::string& /* key */, + uint64_t* /* value */) { return false; }}; + bool operator()(const std::string& section, const std::string& key, uint64_t* value) { return body(section, key, value); - }; + } }; extern struct btif_config_get_uint64 btif_config_get_uint64; // Name: btif_config_set_uint64 // Params: const std::string& section, const std::string& key, uint64_t value // Returns: bool struct btif_config_set_uint64 { - std::function - body{[](const std::string& /* section */, const std::string& /* key */, - uint64_t /* value */) { return false; }}; - bool operator()(const std::string& section, const std::string& key, - uint64_t value) { + std::function body{ + [](const std::string& /* section */, const std::string& /* key */, uint64_t /* value */) { + return false; + }}; + bool operator()(const std::string& section, const std::string& key, uint64_t value) { return body(section, key, value); - }; + } }; extern struct btif_config_set_uint64 btif_config_set_uint64; // Name: btif_config_get_str // Params: const std::string& section, const std::string& key, char* value, int* // size_bytes Returns: bool struct btif_config_get_str { - std::function - body{[](const std::string& /* section */, const std::string& /* key */, - char* /* value */, int* /* size_bytes */) { return false; }}; - bool operator()(const std::string& section, const std::string& key, - char* value, int* size_bytes) { + std::function + body{[](const std::string& /* section */, const std::string& /* key */, char* /* value */, + int* /* size_bytes */) { return false; }}; + bool operator()(const std::string& section, const std::string& key, char* value, + int* size_bytes) { return body(section, key, value, size_bytes); - }; + } }; extern struct btif_config_get_str btif_config_get_str; // Name: btif_config_set_str // Params: const std::string& section, const std::string& key, const // std::string& value Returns: bool struct btif_config_set_str { - std::function - body{[](const std::string& /* section */, const std::string& /* key */, - const std::string& /* value */) { return false; }}; - bool operator()(const std::string& section, const std::string& key, - const std::string& value) { + std::function + body{[](const std::string& /* section */, const std::string& /* key */, + const std::string& /* value */) { return false; }}; + bool operator()(const std::string& section, const std::string& key, const std::string& value) { return body(section, key, value); - }; + } }; extern struct btif_config_set_str btif_config_set_str; // Name: btif_config_get_bin // Params: const std::string& section, const std::string& key, uint8_t* value, // size_t* length Returns: bool struct btif_config_get_bin { - std::function - body{[](const std::string& /* section */, const std::string& /* key */, - uint8_t* /* value */, size_t* /* length */) { return false; }}; - bool operator()(const std::string& section, const std::string& key, - uint8_t* value, size_t* length) { + std::function + body{[](const std::string& /* section */, const std::string& /* key */, + uint8_t* /* value */, size_t* /* length */) { return false; }}; + bool operator()(const std::string& section, const std::string& key, uint8_t* value, + size_t* length) { return body(section, key, value, length); - }; + } }; extern struct btif_config_get_bin btif_config_get_bin; // Name: btif_config_get_bin_length // Params: const std::string& section, const std::string& key // Returns: size_t struct btif_config_get_bin_length { - std::function - body{[](const std::string& /* section */, const std::string& /* key */) { - return 0; - }}; + std::function body{ + [](const std::string& /* section */, const std::string& /* key */) { return 0; }}; size_t operator()(const std::string& section, const std::string& key) { return body(section, key); - }; + } }; extern struct btif_config_get_bin_length btif_config_get_bin_length; // Name: btif_config_set_bin // Params: const std::string& section, const std::string& key, const uint8_t* // value, size_t length Returns: bool struct btif_config_set_bin { - std::function - body{[](const std::string& /* section */, const std::string& /* key */, - const uint8_t* /* value */, - size_t /* length */) { return false; }}; - bool operator()(const std::string& section, const std::string& key, - const uint8_t* value, size_t length) { + std::function + body{[](const std::string& /* section */, const std::string& /* key */, + const uint8_t* /* value */, size_t /* length */) { return false; }}; + bool operator()(const std::string& section, const std::string& key, const uint8_t* value, + size_t length) { return body(section, key, value, length); - }; + } }; extern struct btif_config_set_bin btif_config_set_bin; // Name: btif_config_get_paired_devices @@ -205,9 +183,8 @@ extern struct btif_config_set_bin btif_config_set_bin; // Returns: std::vector struct btif_config_get_paired_devices { std::vector raw_addresses; - std::function()> body{ - [this]() { return raw_addresses; }}; - std::vector operator()() { return body(); }; + std::function()> body{[this]() { return raw_addresses; }}; + std::vector operator()() { return body(); } }; extern struct btif_config_get_paired_devices btif_config_get_paired_devices; // Name: btif_config_remove @@ -215,12 +192,8 @@ extern struct btif_config_get_paired_devices btif_config_get_paired_devices; // Returns: bool struct btif_config_remove { std::function body{ - [](const std::string& /* section */, const std::string& /* key */) { - return false; - }}; - bool operator()(const std::string& section, const std::string& key) { - return body(section, key); - }; + [](const std::string& /* section */, const std::string& /* key */) { return false; }}; + bool operator()(const std::string& section, const std::string& key) { return body(section, key); } }; extern struct btif_config_remove btif_config_remove; // Name: btif_config_remove_device @@ -228,8 +201,8 @@ extern struct btif_config_remove btif_config_remove; // Returns: void struct btif_config_remove_device { std::function body{ - [](const std::string& /* section */) { return; }}; - void operator()(const std::string& /* section */) { return; }; + [](const std::string& /* section */) { return; }}; + void operator()(const std::string& /* section */) { return; } }; extern struct btif_config_remove_device btif_config_remove_device; // Name: btif_config_clear @@ -237,7 +210,7 @@ extern struct btif_config_remove_device btif_config_remove_device; // Returns: bool struct btif_config_clear { std::function body{[](void) { return false; }}; - bool operator()(void) { return body(); }; + bool operator()(void) { return body(); } }; extern struct btif_config_clear btif_config_clear; diff --git a/system/test/mock/mock_btif_core.cc b/system/test/mock/mock_btif_core.cc index 7c90eab5efd..faf22890786 100644 --- a/system/test/mock/mock_btif_core.cc +++ b/system/test/mock/mock_btif_core.cc @@ -45,8 +45,7 @@ bt_status_t btif_init_bluetooth() { inc_func_call_count(__func__); return BT_STATUS_SUCCESS; } -bt_status_t btif_set_dynamic_audio_buffer_size(int /* codec */, - int /* size */) { +bt_status_t btif_set_dynamic_audio_buffer_size(int /* codec */, int /* size */) { inc_func_call_count(__func__); return BT_STATUS_SUCCESS; } @@ -58,47 +57,31 @@ tBTA_SERVICE_MASK btif_get_enabled_services_mask(void) { inc_func_call_count(__func__); return 0; } -void btif_adapter_properties_evt(bt_status_t /* status */, - uint32_t /* num_props */, +void btif_adapter_properties_evt(bt_status_t /* status */, uint32_t /* num_props */, bt_property_t* /* p_props */) { inc_func_call_count(__func__); } -void btif_disable_service(tBTA_SERVICE_ID /* service_id */) { - inc_func_call_count(__func__); -} -void btif_dut_mode_configure(uint8_t /* enable */) { - inc_func_call_count(__func__); -} -void btif_dut_mode_send(uint16_t /* opcode */, uint8_t* /* buf */, - uint8_t /* len */) { +void btif_disable_service(tBTA_SERVICE_ID /* service_id */) { inc_func_call_count(__func__); } +void btif_dut_mode_configure(uint8_t /* enable */) { inc_func_call_count(__func__); } +void btif_dut_mode_send(uint16_t /* opcode */, uint8_t* /* buf */, uint8_t /* len */) { inc_func_call_count(__func__); } void btif_enable_bluetooth_evt() { inc_func_call_count(__func__); } -void btif_enable_service(tBTA_SERVICE_ID /* service_id */) { - inc_func_call_count(__func__); -} +void btif_enable_service(tBTA_SERVICE_ID /* service_id */) { inc_func_call_count(__func__); } void btif_get_adapter_properties(void) { inc_func_call_count(__func__); } -void btif_get_adapter_property(bt_property_type_t /* type */) { - inc_func_call_count(__func__); -} +void btif_get_adapter_property(bt_property_type_t /* type */) { inc_func_call_count(__func__); } void btif_get_remote_device_properties(RawAddress /* remote_addr */) { inc_func_call_count(__func__); } -void btif_get_remote_device_property(RawAddress /* remote_addr */, - bt_property_type_t /* type */) { +void btif_get_remote_device_property(RawAddress /* remote_addr */, bt_property_type_t /* type */) { inc_func_call_count(__func__); } void btif_init_ok() { inc_func_call_count(__func__); } -void btif_remote_properties_evt(bt_status_t /* status */, - RawAddress* /* remote_addr */, - uint32_t /* num_props */, - bt_property_t* /* p_props */) { - inc_func_call_count(__func__); -} -void btif_set_adapter_property(bt_property_t* /* property */) { +void btif_remote_properties_evt(bt_status_t /* status */, RawAddress* /* remote_addr */, + uint32_t /* num_props */, bt_property_t* /* p_props */) { inc_func_call_count(__func__); } -void btif_set_remote_device_property(RawAddress* /* remote_addr */, - bt_property_t* /* property */) { +void btif_set_adapter_property(bt_property_t* /* property */) { inc_func_call_count(__func__); } +void btif_set_remote_device_property(RawAddress* /* remote_addr */, bt_property_t* /* property */) { inc_func_call_count(__func__); } diff --git a/system/test/mock/mock_btif_debug_conn.cc b/system/test/mock/mock_btif_debug_conn.cc index 666e8a813a8..dc2ce36aa60 100644 --- a/system/test/mock/mock_btif_debug_conn.cc +++ b/system/test/mock/mock_btif_debug_conn.cc @@ -25,8 +25,7 @@ #include "types/raw_address.h" void btif_debug_conn_dump(int /* fd */) { inc_func_call_count(__func__); } -void btif_debug_conn_state(const RawAddress& /* bda */, - const btif_debug_conn_state_t /* state */, +void btif_debug_conn_state(const RawAddress& /* bda */, const btif_debug_conn_state_t /* state */, const tGATT_DISCONN_REASON /* disconnect_reason */) { inc_func_call_count(__func__); } diff --git a/system/test/mock/mock_btif_dm.cc b/system/test/mock/mock_btif_dm.cc index 552be8544c1..803e1eba17a 100644 --- a/system/test/mock/mock_btif_dm.cc +++ b/system/test/mock/mock_btif_dm.cc @@ -53,8 +53,7 @@ bool is_device_le_audio_capable(const RawAddress /* bd_addr */) { inc_func_call_count(__func__); return false; } -bool is_le_audio_capable_during_service_discovery( - const RawAddress& /* bd_addr */) { +bool is_le_audio_capable_during_service_discovery(const RawAddress& /* bd_addr */) { inc_func_call_count(__func__); return false; } @@ -70,54 +69,41 @@ void BTIF_dm_report_inquiry_status_change(tBTM_INQUIRY_STATE /* state */) { void btif_dm_sec_evt(tBTA_DM_SEC_EVT /* event */, tBTA_DM_SEC* /* p_data */) { inc_func_call_count(__func__); } -void btif_ble_receiver_test(uint8_t /* rx_freq */) { - inc_func_call_count(__func__); -} +void btif_ble_receiver_test(uint8_t /* rx_freq */) { inc_func_call_count(__func__); } void btif_ble_test_end() { inc_func_call_count(__func__); } -void btif_ble_transmitter_test(uint8_t /* tx_freq */, - uint8_t /* test_data_len */, +void btif_ble_transmitter_test(uint8_t /* tx_freq */, uint8_t /* test_data_len */, uint8_t /* packet_payload */) { inc_func_call_count(__func__); } void btif_debug_bond_event_dump(int /* fd */) { inc_func_call_count(__func__); } -void btif_dm_ble_sec_req_evt(tBTA_DM_BLE_SEC_REQ* /* p_ble_req */, - bool /* is_consent */) { - inc_func_call_count(__func__); -} -void btif_dm_cancel_bond(const RawAddress /* bd_addr */) { +void btif_dm_ble_sec_req_evt(tBTA_DM_BLE_SEC_REQ* /* p_ble_req */, bool /* is_consent */) { inc_func_call_count(__func__); } +void btif_dm_cancel_bond(const RawAddress /* bd_addr */) { inc_func_call_count(__func__); } void btif_dm_cancel_discovery(void) { inc_func_call_count(__func__); } void btif_dm_cleanup(void) { inc_func_call_count(__func__); } void btif_dm_create_bond(const RawAddress /* bd_addr */, int /* transport */) { inc_func_call_count(__func__); } -void btif_dm_create_bond_le(const RawAddress /* bd_addr */, - tBLE_ADDR_TYPE /* addr_type */) { +void btif_dm_create_bond_le(const RawAddress /* bd_addr */, tBLE_ADDR_TYPE /* addr_type */) { inc_func_call_count(__func__); } -void btif_dm_create_bond_out_of_band(const RawAddress /* bd_addr */, - int /* transport */, +void btif_dm_create_bond_out_of_band(const RawAddress /* bd_addr */, int /* transport */, const bt_oob_data_t /* p192_data */, const bt_oob_data_t /* p256_data */) { inc_func_call_count(__func__); } -void btif_dm_enable_service(tBTA_SERVICE_ID /* service_id */, - bool /* enable */) { +void btif_dm_enable_service(tBTA_SERVICE_ID /* service_id */, bool /* enable */) { inc_func_call_count(__func__); } -void btif_dm_get_ble_local_keys(tBTA_DM_BLE_LOCAL_KEY_MASK* /* p_key_mask */, - Octet16* /* p_er */, +void btif_dm_get_ble_local_keys(tBTA_DM_BLE_LOCAL_KEY_MASK* /* p_key_mask */, Octet16* /* p_er */, tBTA_BLE_LOCAL_ID_KEYS* /* p_id_keys */) { inc_func_call_count(__func__); } -void btif_dm_get_remote_services(RawAddress /* remote_addr */, - const int /* transport */) { - inc_func_call_count(__func__); -} -void btif_dm_hh_open_failed(RawAddress* /* bdaddr */) { +void btif_dm_get_remote_services(RawAddress /* remote_addr */, const int /* transport */) { inc_func_call_count(__func__); } +void btif_dm_hh_open_failed(RawAddress* /* bdaddr */) { inc_func_call_count(__func__); } void btif_dm_init(uid_set_t* /* set */) { inc_func_call_count(__func__); } DEV_CLASS btif_dm_get_local_class_of_device() { inc_func_call_count(__func__); @@ -125,23 +111,20 @@ DEV_CLASS btif_dm_get_local_class_of_device() { } void btif_dm_load_ble_local_keys(void) { inc_func_call_count(__func__); } void btif_dm_on_disable() { inc_func_call_count(__func__); } -void btif_dm_pin_reply(const RawAddress /* bd_addr */, uint8_t /* accept */, - uint8_t /* pin_len */, bt_pin_code_t /* pin_code */) { +void btif_dm_pin_reply(const RawAddress /* bd_addr */, uint8_t /* accept */, uint8_t /* pin_len */, + bt_pin_code_t /* pin_code */) { inc_func_call_count(__func__); } void btif_dm_proc_io_req(tBTM_AUTH_REQ* /* p_auth_req */, bool /* is_orig */) { inc_func_call_count(__func__); } -void btif_dm_proc_io_rsp(const RawAddress& /* bd_addr */, - tBTM_IO_CAP /* io_cap */, tBTM_OOB_DATA /* oob_data */, - tBTM_AUTH_REQ /* auth_req */) { +void btif_dm_proc_io_rsp(const RawAddress& /* bd_addr */, tBTM_IO_CAP /* io_cap */, + tBTM_OOB_DATA /* oob_data */, tBTM_AUTH_REQ /* auth_req */) { inc_func_call_count(__func__); } void btif_dm_read_energy_info() { inc_func_call_count(__func__); } void btif_dm_remove_ble_bonding_keys(void) { inc_func_call_count(__func__); } -void btif_dm_remove_bond(const RawAddress /* bd_addr */) { - inc_func_call_count(__func__); -} +void btif_dm_remove_bond(const RawAddress /* bd_addr */) { inc_func_call_count(__func__); } void btif_dm_set_oob_for_io_req(tBTM_OOB_DATA* /* p_has_oob_data */) { inc_func_call_count(__func__); } @@ -150,13 +133,12 @@ void btif_dm_set_oob_for_le_io_req(const RawAddress& /* bd_addr */, tBTM_LE_AUTH_REQ* /* p_auth_req */) { inc_func_call_count(__func__); } -void btif_dm_ssp_reply(const RawAddress /* bd_addr */, - bt_ssp_variant_t /* variant */, uint8_t /* accept */) { +void btif_dm_ssp_reply(const RawAddress /* bd_addr */, bt_ssp_variant_t /* variant */, + uint8_t /* accept */) { inc_func_call_count(__func__); } void btif_dm_start_discovery(void) { inc_func_call_count(__func__); } -void btif_dm_update_ble_remote_properties(const RawAddress& /* bd_addr */, - BD_NAME /* bd_name */, +void btif_dm_update_ble_remote_properties(const RawAddress& /* bd_addr */, BD_NAME /* bd_name */, DEV_CLASS /* dev_class */, tBT_DEVICE_TYPE /* dev_type */) { inc_func_call_count(__func__); @@ -167,8 +149,7 @@ bool btif_dm_get_smp_config(tBTE_APPL_CFG* /* p_cfg */) { return true; } -bool btif_dm_proc_rmt_oob(const RawAddress& /* bd_addr */, Octet16* /* p_c */, - Octet16* /* p_r */) { +bool btif_dm_proc_rmt_oob(const RawAddress& /* bd_addr */, Octet16* /* p_c */, Octet16* /* p_r */) { inc_func_call_count(__func__); return false; } @@ -177,13 +158,11 @@ void btif_dm_proc_loc_oob(tBT_TRANSPORT /* transport */, bool /* is_valid */, const Octet16& /* c */, const Octet16& /* r */) { inc_func_call_count(__func__); } -bool btif_get_device_type(const RawAddress& /* bda */, - int* /* p_device_type */) { +bool btif_get_device_type(const RawAddress& /* bda */, int* /* p_device_type */) { inc_func_call_count(__func__); return false; } -bool btif_get_address_type(const RawAddress& /* bda */, - tBLE_ADDR_TYPE* /* p_addr_type */) { +bool btif_get_address_type(const RawAddress& /* bda */, tBLE_ADDR_TYPE* /* p_addr_type */) { inc_func_call_count(__func__); return false; } diff --git a/system/test/mock/mock_btif_hf.h b/system/test/mock/mock_btif_hf.h index 92c8bff07bb..8d742b1a49f 100644 --- a/system/test/mock/mock_btif_hf.h +++ b/system/test/mock/mock_btif_hf.h @@ -47,9 +47,8 @@ namespace btif_hf { // Returns: bluetooth::headset::Interface* struct GetInterface { - std::function body{ - []() { return nullptr; }}; - bluetooth::headset::Interface* operator()() { return body(); }; + std::function body{[]() { return nullptr; }}; + bluetooth::headset::Interface* operator()() { return body(); } }; extern struct GetInterface GetInterface; diff --git a/system/test/mock/mock_btif_profile_queue.cc b/system/test/mock/mock_btif_profile_queue.cc index 39654496141..974b0759d5e 100644 --- a/system/test/mock/mock_btif_profile_queue.cc +++ b/system/test/mock/mock_btif_profile_queue.cc @@ -67,11 +67,9 @@ void btif_queue_cleanup(uint16_t uuid) { inc_func_call_count(__func__); test::mock::btif_profile_queue::btif_queue_cleanup(uuid); } -bt_status_t btif_queue_connect(uint16_t uuid, const RawAddress* bda, - btif_connect_cb_t connect_cb) { +bt_status_t btif_queue_connect(uint16_t uuid, const RawAddress* bda, btif_connect_cb_t connect_cb) { inc_func_call_count(__func__); - return test::mock::btif_profile_queue::btif_queue_connect(uuid, bda, - connect_cb); + return test::mock::btif_profile_queue::btif_queue_connect(uuid, bda, connect_cb); } bt_status_t btif_queue_connect_next(void) { inc_func_call_count(__func__); diff --git a/system/test/mock/mock_btif_profile_queue.h b/system/test/mock/mock_btif_profile_queue.h index fd1635dcb5a..f2f65ab9b2f 100644 --- a/system/test/mock/mock_btif_profile_queue.h +++ b/system/test/mock/mock_btif_profile_queue.h @@ -43,7 +43,7 @@ namespace btif_profile_queue { // Return: void struct btif_queue_advance { std::function body{[]() {}}; - void operator()() { body(); }; + void operator()() { body(); } }; extern struct btif_queue_advance btif_queue_advance; @@ -52,7 +52,7 @@ extern struct btif_queue_advance btif_queue_advance; // Return: void struct btif_queue_cleanup { std::function body{[](uint16_t /* uuid */) {}}; - void operator()(uint16_t uuid) { body(uuid); }; + void operator()(uint16_t uuid) { body(uuid); } }; extern struct btif_queue_cleanup btif_queue_cleanup; @@ -61,14 +61,12 @@ extern struct btif_queue_cleanup btif_queue_cleanup; // Return: bt_status_t struct btif_queue_connect { static bt_status_t return_value; - std::function - body{[](uint16_t /* uuid */, const RawAddress* /* bda */, - btif_connect_cb_t /* connect_cb */) { return return_value; }}; - bt_status_t operator()(uint16_t uuid, const RawAddress* bda, - btif_connect_cb_t connect_cb) { + std::function + body{[](uint16_t /* uuid */, const RawAddress* /* bda */, + btif_connect_cb_t /* connect_cb */) { return return_value; }}; + bt_status_t operator()(uint16_t uuid, const RawAddress* bda, btif_connect_cb_t connect_cb) { return body(uuid, bda, connect_cb); - }; + } }; extern struct btif_queue_connect btif_queue_connect; @@ -78,7 +76,7 @@ extern struct btif_queue_connect btif_queue_connect; struct btif_queue_connect_next { static bt_status_t return_value; std::function body{[](void) { return return_value; }}; - bt_status_t operator()(void) { return body(); }; + bt_status_t operator()(void) { return body(); } }; extern struct btif_queue_connect_next btif_queue_connect_next; @@ -87,7 +85,7 @@ extern struct btif_queue_connect_next btif_queue_connect_next; // Return: void struct btif_queue_release { std::function body{[]() {}}; - void operator()() { body(); }; + void operator()() { body(); } }; extern struct btif_queue_release btif_queue_release; diff --git a/system/test/mock/mock_btif_profile_storage.cc b/system/test/mock/mock_btif_profile_storage.cc index 94ac21b6680..8658ab740bd 100644 --- a/system/test/mock/mock_btif_profile_storage.cc +++ b/system/test/mock/mock_btif_profile_storage.cc @@ -43,31 +43,23 @@ struct btif_storage_add_hid_device_info btif_storage_add_hid_device_info; struct btif_storage_add_leaudio_has_device btif_storage_add_leaudio_has_device; struct btif_storage_get_hearing_aid_prop btif_storage_get_hearing_aid_prop; struct btif_storage_get_le_hid_devices btif_storage_get_le_hid_devices; -struct btif_storage_get_leaudio_has_features - btif_storage_get_leaudio_has_features; -struct btif_storage_get_leaudio_has_presets - btif_storage_get_leaudio_has_presets; +struct btif_storage_get_leaudio_has_features btif_storage_get_leaudio_has_features; +struct btif_storage_get_leaudio_has_presets btif_storage_get_leaudio_has_presets; struct btif_storage_get_wake_capable_classic_hid_devices - btif_storage_get_wake_capable_classic_hid_devices; + btif_storage_get_wake_capable_classic_hid_devices; struct btif_storage_is_pce_version_102 btif_storage_is_pce_version_102; -struct btif_storage_leaudio_clear_service_data - btif_storage_leaudio_clear_service_data; +struct btif_storage_leaudio_clear_service_data btif_storage_leaudio_clear_service_data; struct btif_storage_leaudio_update_ase_bin btif_storage_leaudio_update_ase_bin; -struct btif_storage_leaudio_update_handles_bin - btif_storage_leaudio_update_handles_bin; -struct btif_storage_leaudio_update_pacs_bin - btif_storage_leaudio_update_pacs_bin; -struct btif_storage_load_bonded_csis_devices - btif_storage_load_bonded_csis_devices; +struct btif_storage_leaudio_update_handles_bin btif_storage_leaudio_update_handles_bin; +struct btif_storage_leaudio_update_pacs_bin btif_storage_leaudio_update_pacs_bin; +struct btif_storage_load_bonded_csis_devices btif_storage_load_bonded_csis_devices; struct btif_storage_load_bonded_groups btif_storage_load_bonded_groups; -struct btif_storage_load_bonded_hearing_aids - btif_storage_load_bonded_hearing_aids; +struct btif_storage_load_bonded_hearing_aids btif_storage_load_bonded_hearing_aids; struct btif_storage_load_bonded_hid_info btif_storage_load_bonded_hid_info; struct btif_storage_load_bonded_leaudio btif_storage_load_bonded_leaudio; -struct btif_storage_load_bonded_leaudio_has_devices - btif_storage_load_bonded_leaudio_has_devices; +struct btif_storage_load_bonded_leaudio_has_devices btif_storage_load_bonded_leaudio_has_devices; struct btif_storage_load_bonded_volume_control_devices - btif_storage_load_bonded_volume_control_devices; + btif_storage_load_bonded_volume_control_devices; struct btif_storage_load_hidd btif_storage_load_hidd; struct btif_storage_remove_csis_device btif_storage_remove_csis_device; struct btif_storage_remove_groups btif_storage_remove_groups; @@ -76,25 +68,17 @@ struct btif_storage_remove_hid_info btif_storage_remove_hid_info; struct btif_storage_remove_hidd btif_storage_remove_hidd; struct btif_storage_remove_leaudio btif_storage_remove_leaudio; struct btif_storage_remove_leaudio_has btif_storage_remove_leaudio_has; -struct btif_storage_set_hearing_aid_acceptlist - btif_storage_set_hearing_aid_acceptlist; +struct btif_storage_set_hearing_aid_acceptlist btif_storage_set_hearing_aid_acceptlist; struct btif_storage_set_hidd btif_storage_set_hidd; -struct btif_storage_set_leaudio_audio_location - btif_storage_set_leaudio_audio_location; -struct btif_storage_set_leaudio_autoconnect - btif_storage_set_leaudio_autoconnect; -struct btif_storage_set_leaudio_has_acceptlist - btif_storage_set_leaudio_has_acceptlist; -struct btif_storage_set_leaudio_has_active_preset - btif_storage_set_leaudio_has_active_preset; -struct btif_storage_set_leaudio_has_features - btif_storage_set_leaudio_has_features; -struct btif_storage_set_leaudio_has_presets - btif_storage_set_leaudio_has_presets; +struct btif_storage_set_leaudio_audio_location btif_storage_set_leaudio_audio_location; +struct btif_storage_set_leaudio_autoconnect btif_storage_set_leaudio_autoconnect; +struct btif_storage_set_leaudio_has_acceptlist btif_storage_set_leaudio_has_acceptlist; +struct btif_storage_set_leaudio_has_active_preset btif_storage_set_leaudio_has_active_preset; +struct btif_storage_set_leaudio_has_features btif_storage_set_leaudio_has_features; +struct btif_storage_set_leaudio_has_presets btif_storage_set_leaudio_has_presets; struct btif_storage_set_leaudio_supported_context_types - btif_storage_set_leaudio_supported_context_types; -struct btif_storage_set_pce_profile_version - btif_storage_set_pce_profile_version; + btif_storage_set_leaudio_supported_context_types; +struct btif_storage_set_pce_profile_version btif_storage_set_pce_profile_version; struct btif_storage_update_csis_info btif_storage_update_csis_info; } // namespace btif_profile_storage @@ -108,12 +92,10 @@ namespace btif_profile_storage { bt_status_t btif_storage_add_hid_device_info::return_value = BT_STATUS_SUCCESS; bool btif_storage_get_hearing_aid_prop::return_value = false; -std::vector> - btif_storage_get_le_hid_devices::return_value = {}; +std::vector> btif_storage_get_le_hid_devices::return_value = {}; bool btif_storage_get_leaudio_has_features::return_value = false; bool btif_storage_get_leaudio_has_presets::return_value = false; -std::vector - btif_storage_get_wake_capable_classic_hid_devices::return_value = {}; +std::vector btif_storage_get_wake_capable_classic_hid_devices::return_value = {}; bool btif_storage_is_pce_version_102::return_value = false; bt_status_t btif_storage_load_bonded_hid_info::return_value = BT_STATUS_SUCCESS; bt_status_t btif_storage_load_hidd::return_value = BT_STATUS_SUCCESS; @@ -134,65 +116,57 @@ void btif_storage_add_hearing_aid(const HearingDevice& dev_info) { inc_func_call_count(__func__); test::mock::btif_profile_storage::btif_storage_add_hearing_aid(dev_info); } -bt_status_t btif_storage_add_hid_device_info( - const tAclLinkSpec& link_spec, uint16_t attr_mask, uint8_t sub_class, - uint8_t app_id, uint16_t vendor_id, uint16_t product_id, uint16_t version, - uint8_t ctry_code, uint16_t ssr_max_latency, uint16_t ssr_min_tout, - uint16_t dl_len, uint8_t* dsc_list) { +bt_status_t btif_storage_add_hid_device_info(const tAclLinkSpec& link_spec, uint16_t attr_mask, + uint8_t sub_class, uint8_t app_id, uint16_t vendor_id, + uint16_t product_id, uint16_t version, + uint8_t ctry_code, uint16_t ssr_max_latency, + uint16_t ssr_min_tout, uint16_t dl_len, + uint8_t* dsc_list) { inc_func_call_count(__func__); return test::mock::btif_profile_storage::btif_storage_add_hid_device_info( - link_spec, attr_mask, sub_class, app_id, vendor_id, product_id, version, - ctry_code, ssr_max_latency, ssr_min_tout, dl_len, dsc_list); + link_spec, attr_mask, sub_class, app_id, vendor_id, product_id, version, ctry_code, + ssr_max_latency, ssr_min_tout, dl_len, dsc_list); } void btif_storage_add_leaudio_has_device(const RawAddress& address, - std::vector presets_bin, - uint8_t features, + std::vector presets_bin, uint8_t features, uint8_t active_preset) { inc_func_call_count(__func__); - test::mock::btif_profile_storage::btif_storage_add_leaudio_has_device( - address, presets_bin, features, active_preset); + test::mock::btif_profile_storage::btif_storage_add_leaudio_has_device(address, presets_bin, + features, active_preset); } -bool btif_storage_get_hearing_aid_prop( - const RawAddress& address, uint8_t* capabilities, uint64_t* hi_sync_id, - uint16_t* render_delay, uint16_t* preparation_delay, uint16_t* codecs) { +bool btif_storage_get_hearing_aid_prop(const RawAddress& address, uint8_t* capabilities, + uint64_t* hi_sync_id, uint16_t* render_delay, + uint16_t* preparation_delay, uint16_t* codecs) { inc_func_call_count(__func__); return test::mock::btif_profile_storage::btif_storage_get_hearing_aid_prop( - address, capabilities, hi_sync_id, render_delay, preparation_delay, - codecs); + address, capabilities, hi_sync_id, render_delay, preparation_delay, codecs); } -std::vector> btif_storage_get_le_hid_devices( - void) { +std::vector> btif_storage_get_le_hid_devices(void) { inc_func_call_count(__func__); return test::mock::btif_profile_storage::btif_storage_get_le_hid_devices(); } -bool btif_storage_get_leaudio_has_features(const RawAddress& address, - uint8_t& features) { +bool btif_storage_get_leaudio_has_features(const RawAddress& address, uint8_t& features) { inc_func_call_count(__func__); - return test::mock::btif_profile_storage:: - btif_storage_get_leaudio_has_features(address, features); + return test::mock::btif_profile_storage::btif_storage_get_leaudio_has_features(address, features); } bool btif_storage_get_leaudio_has_presets(const RawAddress& address, std::vector& presets_bin, uint8_t& active_preset) { inc_func_call_count(__func__); return test::mock::btif_profile_storage::btif_storage_get_leaudio_has_presets( - address, presets_bin, active_preset); + address, presets_bin, active_preset); } -std::vector btif_storage_get_wake_capable_classic_hid_devices( - void) { +std::vector btif_storage_get_wake_capable_classic_hid_devices(void) { inc_func_call_count(__func__); - return test::mock::btif_profile_storage:: - btif_storage_get_wake_capable_classic_hid_devices(); + return test::mock::btif_profile_storage::btif_storage_get_wake_capable_classic_hid_devices(); } bool btif_storage_is_pce_version_102(const RawAddress& remote_bd_addr) { inc_func_call_count(__func__); - return test::mock::btif_profile_storage::btif_storage_is_pce_version_102( - remote_bd_addr); + return test::mock::btif_profile_storage::btif_storage_is_pce_version_102(remote_bd_addr); } void btif_storage_leaudio_clear_service_data(const RawAddress& address) { inc_func_call_count(__func__); - test::mock::btif_profile_storage::btif_storage_leaudio_clear_service_data( - address); + test::mock::btif_profile_storage::btif_storage_leaudio_clear_service_data(address); } void btif_storage_leaudio_update_ase_bin(const RawAddress& addr) { inc_func_call_count(__func__); @@ -200,8 +174,7 @@ void btif_storage_leaudio_update_ase_bin(const RawAddress& addr) { } void btif_storage_leaudio_update_handles_bin(const RawAddress& addr) { inc_func_call_count(__func__); - test::mock::btif_profile_storage::btif_storage_leaudio_update_handles_bin( - addr); + test::mock::btif_profile_storage::btif_storage_leaudio_update_handles_bin(addr); } void btif_storage_leaudio_update_pacs_bin(const RawAddress& addr) { inc_func_call_count(__func__); @@ -229,13 +202,11 @@ void btif_storage_load_bonded_leaudio() { } void btif_storage_load_bonded_leaudio_has_devices() { inc_func_call_count(__func__); - test::mock::btif_profile_storage:: - btif_storage_load_bonded_leaudio_has_devices(); + test::mock::btif_profile_storage::btif_storage_load_bonded_leaudio_has_devices(); } void btif_storage_load_bonded_volume_control_devices(void) { inc_func_call_count(__func__); - test::mock::btif_profile_storage:: - btif_storage_load_bonded_volume_control_devices(); + test::mock::btif_profile_storage::btif_storage_load_bonded_volume_control_devices(); } bt_status_t btif_storage_load_hidd(void) { inc_func_call_count(__func__); @@ -255,13 +226,11 @@ void btif_storage_remove_hearing_aid(const RawAddress& address) { } bt_status_t btif_storage_remove_hid_info(const tAclLinkSpec& link_spec) { inc_func_call_count(__func__); - return test::mock::btif_profile_storage::btif_storage_remove_hid_info( - link_spec); + return test::mock::btif_profile_storage::btif_storage_remove_hid_info(link_spec); } bt_status_t btif_storage_remove_hidd(RawAddress* remote_bd_addr) { inc_func_call_count(__func__); - return test::mock::btif_profile_storage::btif_storage_remove_hidd( - remote_bd_addr); + return test::mock::btif_profile_storage::btif_storage_remove_hidd(remote_bd_addr); } void btif_storage_remove_leaudio(const RawAddress& address) { inc_func_call_count(__func__); @@ -271,67 +240,56 @@ void btif_storage_remove_leaudio_has(const RawAddress& address) { inc_func_call_count(__func__); test::mock::btif_profile_storage::btif_storage_remove_leaudio_has(address); } -void btif_storage_set_hearing_aid_acceptlist(const RawAddress& address, - bool add_to_acceptlist) { +void btif_storage_set_hearing_aid_acceptlist(const RawAddress& address, bool add_to_acceptlist) { inc_func_call_count(__func__); - test::mock::btif_profile_storage::btif_storage_set_hearing_aid_acceptlist( - address, add_to_acceptlist); + test::mock::btif_profile_storage::btif_storage_set_hearing_aid_acceptlist(address, + add_to_acceptlist); } bt_status_t btif_storage_set_hidd(const RawAddress& remote_bd_addr) { inc_func_call_count(__func__); - return test::mock::btif_profile_storage::btif_storage_set_hidd( - remote_bd_addr); + return test::mock::btif_profile_storage::btif_storage_set_hidd(remote_bd_addr); } -void btif_storage_set_leaudio_audio_location(const RawAddress& addr, - uint32_t sink_location, +void btif_storage_set_leaudio_audio_location(const RawAddress& addr, uint32_t sink_location, uint32_t source_location) { inc_func_call_count(__func__); - test::mock::btif_profile_storage::btif_storage_set_leaudio_audio_location( - addr, sink_location, source_location); + test::mock::btif_profile_storage::btif_storage_set_leaudio_audio_location(addr, sink_location, + source_location); } -void btif_storage_set_leaudio_autoconnect(const RawAddress& addr, - bool autoconnect) { +void btif_storage_set_leaudio_autoconnect(const RawAddress& addr, bool autoconnect) { inc_func_call_count(__func__); - test::mock::btif_profile_storage::btif_storage_set_leaudio_autoconnect( - addr, autoconnect); + test::mock::btif_profile_storage::btif_storage_set_leaudio_autoconnect(addr, autoconnect); } -void btif_storage_set_leaudio_has_acceptlist(const RawAddress& address, - bool add_to_acceptlist) { +void btif_storage_set_leaudio_has_acceptlist(const RawAddress& address, bool add_to_acceptlist) { inc_func_call_count(__func__); - test::mock::btif_profile_storage::btif_storage_set_leaudio_has_acceptlist( - address, add_to_acceptlist); + test::mock::btif_profile_storage::btif_storage_set_leaudio_has_acceptlist(address, + add_to_acceptlist); } -void btif_storage_set_leaudio_has_active_preset(const RawAddress& address, - uint8_t active_preset) { +void btif_storage_set_leaudio_has_active_preset(const RawAddress& address, uint8_t active_preset) { inc_func_call_count(__func__); - test::mock::btif_profile_storage::btif_storage_set_leaudio_has_active_preset( - address, active_preset); + test::mock::btif_profile_storage::btif_storage_set_leaudio_has_active_preset(address, + active_preset); } -void btif_storage_set_leaudio_has_features(const RawAddress& address, - uint8_t features) { +void btif_storage_set_leaudio_has_features(const RawAddress& address, uint8_t features) { inc_func_call_count(__func__); - test::mock::btif_profile_storage::btif_storage_set_leaudio_has_features( - address, features); + test::mock::btif_profile_storage::btif_storage_set_leaudio_has_features(address, features); } void btif_storage_set_leaudio_has_presets(const RawAddress& address, std::vector presets_bin) { inc_func_call_count(__func__); - test::mock::btif_profile_storage::btif_storage_set_leaudio_has_presets( - address, presets_bin); + test::mock::btif_profile_storage::btif_storage_set_leaudio_has_presets(address, presets_bin); } -void btif_storage_set_leaudio_supported_context_types( - const RawAddress& addr, uint16_t sink_supported_context_type, - uint16_t source_supported_context_type) { +void btif_storage_set_leaudio_supported_context_types(const RawAddress& addr, + uint16_t sink_supported_context_type, + uint16_t source_supported_context_type) { inc_func_call_count(__func__); - test::mock::btif_profile_storage:: - btif_storage_set_leaudio_supported_context_types( + test::mock::btif_profile_storage::btif_storage_set_leaudio_supported_context_types( addr, sink_supported_context_type, source_supported_context_type); } void btif_storage_set_pce_profile_version(const RawAddress& remote_bd_addr, uint16_t peer_pce_version) { inc_func_call_count(__func__); - test::mock::btif_profile_storage::btif_storage_set_pce_profile_version( - remote_bd_addr, peer_pce_version); + test::mock::btif_profile_storage::btif_storage_set_pce_profile_version(remote_bd_addr, + peer_pce_version); } void btif_storage_update_csis_info(const RawAddress& addr) { inc_func_call_count(__func__); diff --git a/system/test/mock/mock_btif_profile_storage.h b/system/test/mock/mock_btif_profile_storage.h index 2da84a9ec2b..46cd07fed4f 100644 --- a/system/test/mock/mock_btif_profile_storage.h +++ b/system/test/mock/mock_btif_profile_storage.h @@ -54,9 +54,8 @@ namespace btif_profile_storage { // Params: const RawAddress& addr // Return: void struct btif_storage_add_groups { - std::function body{ - [](const RawAddress& /* addr */) {}}; - void operator()(const RawAddress& addr) { body(addr); }; + std::function body{[](const RawAddress& /* addr */) {}}; + void operator()(const RawAddress& addr) { body(addr); } }; extern struct btif_storage_add_groups btif_storage_add_groups; @@ -65,8 +64,8 @@ extern struct btif_storage_add_groups btif_storage_add_groups; // Return: void struct btif_storage_add_hearing_aid { std::function body{ - [](const HearingDevice& /* dev_info */) {}}; - void operator()(const HearingDevice& dev_info) { body(dev_info); }; + [](const HearingDevice& /* dev_info */) {}}; + void operator()(const HearingDevice& dev_info) { body(dev_info); } }; extern struct btif_storage_add_hearing_aid btif_storage_add_hearing_aid; @@ -77,28 +76,22 @@ extern struct btif_storage_add_hearing_aid btif_storage_add_hearing_aid; // dl_len, uint8_t* dsc_list Return: bt_status_t struct btif_storage_add_hid_device_info { static bt_status_t return_value; - std::function - body{[](const tAclLinkSpec& /* link_spec */, uint16_t /* attr_mask */, - uint8_t /* sub_class */, uint8_t /* app_id */, - uint16_t /* vendor_id */, uint16_t /* product_id */, - uint16_t /* version */, uint8_t /* ctry_code */, - uint16_t /* ssr_max_latency */, uint16_t /* ssr_min_tout */, - uint16_t /* dl_len */, - uint8_t* /* dsc_list */) { return return_value; }}; - bt_status_t operator()(const tAclLinkSpec& link_spec, uint16_t attr_mask, - uint8_t sub_class, uint8_t app_id, uint16_t vendor_id, - uint16_t product_id, uint16_t version, - uint8_t ctry_code, uint16_t ssr_max_latency, - uint16_t ssr_min_tout, uint16_t dl_len, - uint8_t* dsc_list) { - return body(link_spec, attr_mask, sub_class, app_id, vendor_id, product_id, - version, ctry_code, ssr_max_latency, ssr_min_tout, dl_len, - dsc_list); - }; + std::function + body{[](const tAclLinkSpec& /* link_spec */, uint16_t /* attr_mask */, + uint8_t /* sub_class */, uint8_t /* app_id */, uint16_t /* vendor_id */, + uint16_t /* product_id */, uint16_t /* version */, uint8_t /* ctry_code */, + uint16_t /* ssr_max_latency */, uint16_t /* ssr_min_tout */, + uint16_t /* dl_len */, uint8_t* /* dsc_list */) { return return_value; }}; + bt_status_t operator()(const tAclLinkSpec& link_spec, uint16_t attr_mask, uint8_t sub_class, + uint8_t app_id, uint16_t vendor_id, uint16_t product_id, uint16_t version, + uint8_t ctry_code, uint16_t ssr_max_latency, uint16_t ssr_min_tout, + uint16_t dl_len, uint8_t* dsc_list) { + return body(link_spec, attr_mask, sub_class, app_id, vendor_id, product_id, version, ctry_code, + ssr_max_latency, ssr_min_tout, dl_len, dsc_list); + } }; extern struct btif_storage_add_hid_device_info btif_storage_add_hid_device_info; @@ -106,19 +99,16 @@ extern struct btif_storage_add_hid_device_info btif_storage_add_hid_device_info; // Params: const RawAddress& address, std::vector presets_bin, uint8_t // features, uint8_t active_preset Return: void struct btif_storage_add_leaudio_has_device { - std::function presets_bin, uint8_t features, + std::function presets_bin, uint8_t features, uint8_t active_preset)> - body{[](const RawAddress& /* address */, - std::vector /* presets_bin */, uint8_t /* features */, - uint8_t /* active_preset */) {}}; - void operator()(const RawAddress& address, std::vector presets_bin, - uint8_t features, uint8_t active_preset) { + body{[](const RawAddress& /* address */, std::vector /* presets_bin */, + uint8_t /* features */, uint8_t /* active_preset */) {}}; + void operator()(const RawAddress& address, std::vector presets_bin, uint8_t features, + uint8_t active_preset) { body(address, presets_bin, features, active_preset); - }; + } }; -extern struct btif_storage_add_leaudio_has_device - btif_storage_add_leaudio_has_device; +extern struct btif_storage_add_leaudio_has_device btif_storage_add_leaudio_has_device; // Name: btif_storage_get_hearing_aid_prop // Params: const RawAddress& address, uint8_t* capabilities, uint64_t* @@ -126,22 +116,18 @@ extern struct btif_storage_add_leaudio_has_device // codecs Return: bool struct btif_storage_get_hearing_aid_prop { static bool return_value; - std::function - body{[](const RawAddress& /* address */, uint8_t* /* capabilities */, - uint64_t* /* hi_sync_id */, uint16_t* /* render_delay */, - uint16_t* /* preparation_delay */, - uint16_t* /* codecs */) { return return_value; }}; - bool operator()(const RawAddress& address, uint8_t* capabilities, - uint64_t* hi_sync_id, uint16_t* render_delay, - uint16_t* preparation_delay, uint16_t* codecs) { - return body(address, capabilities, hi_sync_id, render_delay, - preparation_delay, codecs); - }; -}; -extern struct btif_storage_get_hearing_aid_prop - btif_storage_get_hearing_aid_prop; + std::function + body{[](const RawAddress& /* address */, uint8_t* /* capabilities */, + uint64_t* /* hi_sync_id */, uint16_t* /* render_delay */, + uint16_t* /* preparation_delay */, + uint16_t* /* codecs */) { return return_value; }}; + bool operator()(const RawAddress& address, uint8_t* capabilities, uint64_t* hi_sync_id, + uint16_t* render_delay, uint16_t* preparation_delay, uint16_t* codecs) { + return body(address, capabilities, hi_sync_id, render_delay, preparation_delay, codecs); + } +}; +extern struct btif_storage_get_hearing_aid_prop btif_storage_get_hearing_aid_prop; // Name: btif_storage_get_le_hid_devices // Params: void @@ -149,10 +135,8 @@ extern struct btif_storage_get_hearing_aid_prop struct btif_storage_get_le_hid_devices { static std::vector> return_value; std::function>(void)> body{ - [](void) { return return_value; }}; - std::vector> operator()(void) { - return body(); - }; + [](void) { return return_value; }}; + std::vector> operator()(void) { return body(); } }; extern struct btif_storage_get_le_hid_devices btif_storage_get_le_hid_devices; @@ -162,45 +146,37 @@ extern struct btif_storage_get_le_hid_devices btif_storage_get_le_hid_devices; struct btif_storage_get_leaudio_has_features { static bool return_value; std::function body{ - [](const RawAddress& /* address */, uint8_t& /* features */) { - return return_value; - }}; - bool operator()(const RawAddress& address, uint8_t& features) { - return body(address, features); - }; + [](const RawAddress& /* address */, uint8_t& /* features */) { return return_value; }}; + bool operator()(const RawAddress& address, uint8_t& features) { return body(address, features); } }; -extern struct btif_storage_get_leaudio_has_features - btif_storage_get_leaudio_has_features; +extern struct btif_storage_get_leaudio_has_features btif_storage_get_leaudio_has_features; // Name: btif_storage_get_leaudio_has_presets // Params: const RawAddress& address, std::vector& presets_bin, // uint8_t& active_preset Return: bool struct btif_storage_get_leaudio_has_presets { static bool return_value; - std::function& presets_bin, uint8_t& active_preset)> - body{[](const RawAddress& /* address */, - std::vector& /* presets_bin */, - uint8_t& /* active_preset */) { return return_value; }}; + std::function& presets_bin, + uint8_t& active_preset)> + body{[](const RawAddress& /* address */, std::vector& /* presets_bin */, + uint8_t& /* active_preset */) { return return_value; }}; bool operator()(const RawAddress& address, std::vector& presets_bin, uint8_t& active_preset) { return body(address, presets_bin, active_preset); - }; + } }; -extern struct btif_storage_get_leaudio_has_presets - btif_storage_get_leaudio_has_presets; +extern struct btif_storage_get_leaudio_has_presets btif_storage_get_leaudio_has_presets; // Name: btif_storage_get_wake_capable_classic_hid_devices // Params: void // Return: std::vector struct btif_storage_get_wake_capable_classic_hid_devices { static std::vector return_value; - std::function(void)> body{ - [](void) { return return_value; }}; - std::vector operator()(void) { return body(); }; + std::function(void)> body{[](void) { return return_value; }}; + std::vector operator()(void) { return body(); } }; extern struct btif_storage_get_wake_capable_classic_hid_devices - btif_storage_get_wake_capable_classic_hid_devices; + btif_storage_get_wake_capable_classic_hid_devices; // Name: btif_storage_is_pce_version_102 // Params: const RawAddress& remote_bd_addr @@ -208,10 +184,8 @@ extern struct btif_storage_get_wake_capable_classic_hid_devices struct btif_storage_is_pce_version_102 { static bool return_value; std::function body{ - [](const RawAddress& /* remote_bd_addr */) { return return_value; }}; - bool operator()(const RawAddress& remote_bd_addr) { - return body(remote_bd_addr); - }; + [](const RawAddress& /* remote_bd_addr */) { return return_value; }}; + bool operator()(const RawAddress& remote_bd_addr) { return body(remote_bd_addr); } }; extern struct btif_storage_is_pce_version_102 btif_storage_is_pce_version_102; @@ -219,62 +193,53 @@ extern struct btif_storage_is_pce_version_102 btif_storage_is_pce_version_102; // Params: const RawAddress& address // Return: void struct btif_storage_leaudio_clear_service_data { - std::function body{ - [](const RawAddress& /* address */) {}}; - void operator()(const RawAddress& address) { body(address); }; + std::function body{[](const RawAddress& /* address */) {}}; + void operator()(const RawAddress& address) { body(address); } }; -extern struct btif_storage_leaudio_clear_service_data - btif_storage_leaudio_clear_service_data; +extern struct btif_storage_leaudio_clear_service_data btif_storage_leaudio_clear_service_data; // Name: btif_storage_leaudio_update_ase_bin // Params: const RawAddress& addr // Return: void struct btif_storage_leaudio_update_ase_bin { - std::function body{ - [](const RawAddress& /* addr */) {}}; - void operator()(const RawAddress& addr) { body(addr); }; + std::function body{[](const RawAddress& /* addr */) {}}; + void operator()(const RawAddress& addr) { body(addr); } }; -extern struct btif_storage_leaudio_update_ase_bin - btif_storage_leaudio_update_ase_bin; +extern struct btif_storage_leaudio_update_ase_bin btif_storage_leaudio_update_ase_bin; // Name: btif_storage_leaudio_update_handles_bin // Params: const RawAddress& addr // Return: void struct btif_storage_leaudio_update_handles_bin { - std::function body{ - [](const RawAddress& /* addr */) {}}; - void operator()(const RawAddress& addr) { body(addr); }; + std::function body{[](const RawAddress& /* addr */) {}}; + void operator()(const RawAddress& addr) { body(addr); } }; -extern struct btif_storage_leaudio_update_handles_bin - btif_storage_leaudio_update_handles_bin; +extern struct btif_storage_leaudio_update_handles_bin btif_storage_leaudio_update_handles_bin; // Name: btif_storage_leaudio_update_pacs_bin // Params: const RawAddress& addr // Return: void struct btif_storage_leaudio_update_pacs_bin { - std::function body{ - [](const RawAddress& /* addr */) {}}; - void operator()(const RawAddress& addr) { body(addr); }; + std::function body{[](const RawAddress& /* addr */) {}}; + void operator()(const RawAddress& addr) { body(addr); } }; -extern struct btif_storage_leaudio_update_pacs_bin - btif_storage_leaudio_update_pacs_bin; +extern struct btif_storage_leaudio_update_pacs_bin btif_storage_leaudio_update_pacs_bin; // Name: btif_storage_load_bonded_csis_devices // Params: void // Return: void struct btif_storage_load_bonded_csis_devices { std::function body{[](void) {}}; - void operator()(void) { body(); }; + void operator()(void) { body(); } }; -extern struct btif_storage_load_bonded_csis_devices - btif_storage_load_bonded_csis_devices; +extern struct btif_storage_load_bonded_csis_devices btif_storage_load_bonded_csis_devices; // Name: btif_storage_load_bonded_groups // Params: void // Return: void struct btif_storage_load_bonded_groups { std::function body{[](void) {}}; - void operator()(void) { body(); }; + void operator()(void) { body(); } }; extern struct btif_storage_load_bonded_groups btif_storage_load_bonded_groups; @@ -283,10 +248,9 @@ extern struct btif_storage_load_bonded_groups btif_storage_load_bonded_groups; // Return: void struct btif_storage_load_bonded_hearing_aids { std::function body{[]() {}}; - void operator()() { body(); }; + void operator()() { body(); } }; -extern struct btif_storage_load_bonded_hearing_aids - btif_storage_load_bonded_hearing_aids; +extern struct btif_storage_load_bonded_hearing_aids btif_storage_load_bonded_hearing_aids; // Name: btif_storage_load_bonded_hid_info // Params: void @@ -294,17 +258,16 @@ extern struct btif_storage_load_bonded_hearing_aids struct btif_storage_load_bonded_hid_info { static bt_status_t return_value; std::function body{[](void) { return return_value; }}; - bt_status_t operator()(void) { return body(); }; + bt_status_t operator()(void) { return body(); } }; -extern struct btif_storage_load_bonded_hid_info - btif_storage_load_bonded_hid_info; +extern struct btif_storage_load_bonded_hid_info btif_storage_load_bonded_hid_info; // Name: btif_storage_load_bonded_leaudio // Params: // Return: void struct btif_storage_load_bonded_leaudio { std::function body{[]() {}}; - void operator()() { body(); }; + void operator()() { body(); } }; extern struct btif_storage_load_bonded_leaudio btif_storage_load_bonded_leaudio; @@ -313,20 +276,20 @@ extern struct btif_storage_load_bonded_leaudio btif_storage_load_bonded_leaudio; // Return: void struct btif_storage_load_bonded_leaudio_has_devices { std::function body{[]() {}}; - void operator()() { body(); }; + void operator()() { body(); } }; extern struct btif_storage_load_bonded_leaudio_has_devices - btif_storage_load_bonded_leaudio_has_devices; + btif_storage_load_bonded_leaudio_has_devices; // Name: btif_storage_load_bonded_volume_control_devices // Params: void // Return: void struct btif_storage_load_bonded_volume_control_devices { std::function body{[](void) {}}; - void operator()(void) { body(); }; + void operator()(void) { body(); } }; extern struct btif_storage_load_bonded_volume_control_devices - btif_storage_load_bonded_volume_control_devices; + btif_storage_load_bonded_volume_control_devices; // Name: btif_storage_load_hidd // Params: void @@ -334,7 +297,7 @@ extern struct btif_storage_load_bonded_volume_control_devices struct btif_storage_load_hidd { static bt_status_t return_value; std::function body{[](void) { return return_value; }}; - bt_status_t operator()(void) { return body(); }; + bt_status_t operator()(void) { return body(); } }; extern struct btif_storage_load_hidd btif_storage_load_hidd; @@ -342,9 +305,8 @@ extern struct btif_storage_load_hidd btif_storage_load_hidd; // Params: const RawAddress& address // Return: void struct btif_storage_remove_csis_device { - std::function body{ - [](const RawAddress& /* address */) {}}; - void operator()(const RawAddress& address) { body(address); }; + std::function body{[](const RawAddress& /* address */) {}}; + void operator()(const RawAddress& address) { body(address); } }; extern struct btif_storage_remove_csis_device btif_storage_remove_csis_device; @@ -352,9 +314,8 @@ extern struct btif_storage_remove_csis_device btif_storage_remove_csis_device; // Params: const RawAddress& address // Return: void struct btif_storage_remove_groups { - std::function body{ - [](const RawAddress& /* address */) {}}; - void operator()(const RawAddress& address) { body(address); }; + std::function body{[](const RawAddress& /* address */) {}}; + void operator()(const RawAddress& address) { body(address); } }; extern struct btif_storage_remove_groups btif_storage_remove_groups; @@ -362,9 +323,8 @@ extern struct btif_storage_remove_groups btif_storage_remove_groups; // Params: const RawAddress& address // Return: void struct btif_storage_remove_hearing_aid { - std::function body{ - [](const RawAddress& /* address */) {}}; - void operator()(const RawAddress& address) { body(address); }; + std::function body{[](const RawAddress& /* address */) {}}; + void operator()(const RawAddress& address) { body(address); } }; extern struct btif_storage_remove_hearing_aid btif_storage_remove_hearing_aid; @@ -374,10 +334,8 @@ extern struct btif_storage_remove_hearing_aid btif_storage_remove_hearing_aid; struct btif_storage_remove_hid_info { static bt_status_t return_value; std::function body{ - [](const tAclLinkSpec& /* link_spec */) { return return_value; }}; - bt_status_t operator()(const tAclLinkSpec& link_spec) { - return body(link_spec); - }; + [](const tAclLinkSpec& /* link_spec */) { return return_value; }}; + bt_status_t operator()(const tAclLinkSpec& link_spec) { return body(link_spec); } }; extern struct btif_storage_remove_hid_info btif_storage_remove_hid_info; @@ -387,10 +345,8 @@ extern struct btif_storage_remove_hid_info btif_storage_remove_hid_info; struct btif_storage_remove_hidd { static bt_status_t return_value; std::function body{ - [](RawAddress* /* remote_bd_addr */) { return return_value; }}; - bt_status_t operator()(RawAddress* remote_bd_addr) { - return body(remote_bd_addr); - }; + [](RawAddress* /* remote_bd_addr */) { return return_value; }}; + bt_status_t operator()(RawAddress* remote_bd_addr) { return body(remote_bd_addr); } }; extern struct btif_storage_remove_hidd btif_storage_remove_hidd; @@ -398,9 +354,8 @@ extern struct btif_storage_remove_hidd btif_storage_remove_hidd; // Params: const RawAddress& address // Return: void struct btif_storage_remove_leaudio { - std::function body{ - [](const RawAddress& /* address */) {}}; - void operator()(const RawAddress& address) { body(address); }; + std::function body{[](const RawAddress& /* address */) {}}; + void operator()(const RawAddress& address) { body(address); } }; extern struct btif_storage_remove_leaudio btif_storage_remove_leaudio; @@ -408,9 +363,8 @@ extern struct btif_storage_remove_leaudio btif_storage_remove_leaudio; // Params: const RawAddress& address // Return: void struct btif_storage_remove_leaudio_has { - std::function body{ - [](const RawAddress& /* address */) {}}; - void operator()(const RawAddress& address) { body(address); }; + std::function body{[](const RawAddress& /* address */) {}}; + void operator()(const RawAddress& address) { body(address); } }; extern struct btif_storage_remove_leaudio_has btif_storage_remove_leaudio_has; @@ -419,13 +373,12 @@ extern struct btif_storage_remove_leaudio_has btif_storage_remove_leaudio_has; // Return: void struct btif_storage_set_hearing_aid_acceptlist { std::function body{ - [](const RawAddress& /* address */, bool /* add_to_acceptlist */) {}}; + [](const RawAddress& /* address */, bool /* add_to_acceptlist */) {}}; void operator()(const RawAddress& address, bool add_to_acceptlist) { body(address, add_to_acceptlist); - }; + } }; -extern struct btif_storage_set_hearing_aid_acceptlist - btif_storage_set_hearing_aid_acceptlist; +extern struct btif_storage_set_hearing_aid_acceptlist btif_storage_set_hearing_aid_acceptlist; // Name: btif_storage_set_hidd // Params: const RawAddress& remote_bd_addr @@ -433,10 +386,8 @@ extern struct btif_storage_set_hearing_aid_acceptlist struct btif_storage_set_hidd { static bt_status_t return_value; std::function body{ - [](const RawAddress& /* remote_bd_addr */) { return return_value; }}; - bt_status_t operator()(const RawAddress& remote_bd_addr) { - return body(remote_bd_addr); - }; + [](const RawAddress& /* remote_bd_addr */) { return return_value; }}; + bt_status_t operator()(const RawAddress& remote_bd_addr) { return body(remote_bd_addr); } }; extern struct btif_storage_set_hidd btif_storage_set_hidd; @@ -444,125 +395,105 @@ extern struct btif_storage_set_hidd btif_storage_set_hidd; // Params: const RawAddress& addr, uint32_t sink_location, uint32_t // source_location Return: void struct btif_storage_set_leaudio_audio_location { - std::function - body{[](const RawAddress& /* addr */, uint32_t /* sink_location */, - uint32_t /* source_location */) {}}; - void operator()(const RawAddress& addr, uint32_t sink_location, - uint32_t source_location) { + std::function + body{[](const RawAddress& /* addr */, uint32_t /* sink_location */, + uint32_t /* source_location */) {}}; + void operator()(const RawAddress& addr, uint32_t sink_location, uint32_t source_location) { body(addr, sink_location, source_location); - }; + } }; -extern struct btif_storage_set_leaudio_audio_location - btif_storage_set_leaudio_audio_location; +extern struct btif_storage_set_leaudio_audio_location btif_storage_set_leaudio_audio_location; // Name: btif_storage_set_leaudio_autoconnect // Params: const RawAddress& addr, bool autoconnect // Return: void struct btif_storage_set_leaudio_autoconnect { std::function body{ - [](const RawAddress& /* addr */, bool /* autoconnect */) {}}; - void operator()(const RawAddress& addr, bool autoconnect) { - body(addr, autoconnect); - }; + [](const RawAddress& /* addr */, bool /* autoconnect */) {}}; + void operator()(const RawAddress& addr, bool autoconnect) { body(addr, autoconnect); } }; -extern struct btif_storage_set_leaudio_autoconnect - btif_storage_set_leaudio_autoconnect; +extern struct btif_storage_set_leaudio_autoconnect btif_storage_set_leaudio_autoconnect; // Name: btif_storage_set_leaudio_has_acceptlist // Params: const RawAddress& address, bool add_to_acceptlist // Return: void struct btif_storage_set_leaudio_has_acceptlist { std::function body{ - [](const RawAddress& /* address */, bool /* add_to_acceptlist */) {}}; + [](const RawAddress& /* address */, bool /* add_to_acceptlist */) {}}; void operator()(const RawAddress& address, bool add_to_acceptlist) { body(address, add_to_acceptlist); - }; + } }; -extern struct btif_storage_set_leaudio_has_acceptlist - btif_storage_set_leaudio_has_acceptlist; +extern struct btif_storage_set_leaudio_has_acceptlist btif_storage_set_leaudio_has_acceptlist; // Name: btif_storage_set_leaudio_has_active_preset // Params: const RawAddress& address, uint8_t active_preset // Return: void struct btif_storage_set_leaudio_has_active_preset { std::function body{ - [](const RawAddress& /* address */, uint8_t /* active_preset */) {}}; + [](const RawAddress& /* address */, uint8_t /* active_preset */) {}}; void operator()(const RawAddress& address, uint8_t active_preset) { body(address, active_preset); - }; + } }; -extern struct btif_storage_set_leaudio_has_active_preset - btif_storage_set_leaudio_has_active_preset; +extern struct btif_storage_set_leaudio_has_active_preset btif_storage_set_leaudio_has_active_preset; // Name: btif_storage_set_leaudio_has_features // Params: const RawAddress& address, uint8_t features // Return: void struct btif_storage_set_leaudio_has_features { std::function body{ - [](const RawAddress& /* address */, uint8_t /* features */) {}}; - void operator()(const RawAddress& address, uint8_t features) { - body(address, features); - }; + [](const RawAddress& /* address */, uint8_t /* features */) {}}; + void operator()(const RawAddress& address, uint8_t features) { body(address, features); } }; -extern struct btif_storage_set_leaudio_has_features - btif_storage_set_leaudio_has_features; +extern struct btif_storage_set_leaudio_has_features btif_storage_set_leaudio_has_features; // Name: btif_storage_set_leaudio_has_presets // Params: const RawAddress& address, std::vector presets_bin // Return: void struct btif_storage_set_leaudio_has_presets { - std::function presets_bin)> - body{[](const RawAddress& /* address */, - std::vector /* presets_bin */) {}}; + std::function presets_bin)> body{ + [](const RawAddress& /* address */, std::vector /* presets_bin */) {}}; void operator()(const RawAddress& address, std::vector presets_bin) { body(address, presets_bin); - }; + } }; -extern struct btif_storage_set_leaudio_has_presets - btif_storage_set_leaudio_has_presets; +extern struct btif_storage_set_leaudio_has_presets btif_storage_set_leaudio_has_presets; // Name: btif_storage_set_leaudio_supported_context_types // Params: const RawAddress& addr, uint16_t sink_supported_context_type, // uint16_t source_supported_context_type Return: void struct btif_storage_set_leaudio_supported_context_types { - std::function - body{[](const RawAddress& /* addr */, - uint16_t /* sink_supported_context_type */, - uint16_t /* source_supported_context_type */) {}}; + body{[](const RawAddress& /* addr */, uint16_t /* sink_supported_context_type */, + uint16_t /* source_supported_context_type */) {}}; void operator()(const RawAddress& addr, uint16_t sink_supported_context_type, uint16_t source_supported_context_type) { body(addr, sink_supported_context_type, source_supported_context_type); - }; + } }; extern struct btif_storage_set_leaudio_supported_context_types - btif_storage_set_leaudio_supported_context_types; + btif_storage_set_leaudio_supported_context_types; // Name: btif_storage_set_pce_profile_version // Params: const RawAddress& remote_bd_addr, uint16_t peer_pce_version // Return: void struct btif_storage_set_pce_profile_version { - std::function - body{[](const RawAddress& /* remote_bd_addr */, - uint16_t /* peer_pce_version */) {}}; + std::function body{ + [](const RawAddress& /* remote_bd_addr */, uint16_t /* peer_pce_version */) {}}; void operator()(const RawAddress& remote_bd_addr, uint16_t peer_pce_version) { body(remote_bd_addr, peer_pce_version); - }; + } }; -extern struct btif_storage_set_pce_profile_version - btif_storage_set_pce_profile_version; +extern struct btif_storage_set_pce_profile_version btif_storage_set_pce_profile_version; // Name: btif_storage_update_csis_info // Params: const RawAddress& addr // Return: void struct btif_storage_update_csis_info { - std::function body{ - [](const RawAddress& /* addr */) {}}; - void operator()(const RawAddress& addr) { body(addr); }; + std::function body{[](const RawAddress& /* addr */) {}}; + void operator()(const RawAddress& addr) { body(addr); } }; extern struct btif_storage_update_csis_info btif_storage_update_csis_info; diff --git a/system/test/mock/mock_btif_sock_rfc.cc b/system/test/mock/mock_btif_sock_rfc.cc index b5cb7976255..5ab162a470c 100644 --- a/system/test/mock/mock_btif_sock_rfc.cc +++ b/system/test/mock/mock_btif_sock_rfc.cc @@ -86,21 +86,18 @@ void btsock_rfc_cleanup(void) { inc_func_call_count(__func__); test::mock::btif_sock_rfc::btsock_rfc_cleanup(); } -bt_status_t btsock_rfc_connect(const RawAddress* bd_addr, - const Uuid* service_uuid, int channel, +bt_status_t btsock_rfc_connect(const RawAddress* bd_addr, const Uuid* service_uuid, int channel, int* sock_fd, int flags, int app_uid) { inc_func_call_count(__func__); - return test::mock::btif_sock_rfc::btsock_rfc_connect( - bd_addr, service_uuid, channel, sock_fd, flags, app_uid); + return test::mock::btif_sock_rfc::btsock_rfc_connect(bd_addr, service_uuid, channel, sock_fd, + flags, app_uid); } -bt_status_t btsock_rfc_control_req(uint8_t dlci, const RawAddress& bd_addr, - uint8_t modem_signal, uint8_t break_signal, - uint8_t discard_buffers, +bt_status_t btsock_rfc_control_req(uint8_t dlci, const RawAddress& bd_addr, uint8_t modem_signal, + uint8_t break_signal, uint8_t discard_buffers, uint8_t break_signal_seq, bool fc) { inc_func_call_count(__func__); return test::mock::btif_sock_rfc::btsock_rfc_control_req( - dlci, bd_addr, modem_signal, break_signal, discard_buffers, - break_signal_seq, fc); + dlci, bd_addr, modem_signal, break_signal, discard_buffers, break_signal_seq, fc); } bt_status_t btsock_rfc_disconnect(const RawAddress* bd_addr) { inc_func_call_count(__func__); @@ -110,12 +107,11 @@ bt_status_t btsock_rfc_init(int poll_thread_handle, uid_set_t* set) { inc_func_call_count(__func__); return test::mock::btif_sock_rfc::btsock_rfc_init(poll_thread_handle, set); } -bt_status_t btsock_rfc_listen(const char* service_name, - const Uuid* service_uuid, int channel, +bt_status_t btsock_rfc_listen(const char* service_name, const Uuid* service_uuid, int channel, int* sock_fd, int flags, int app_uid) { inc_func_call_count(__func__); - return test::mock::btif_sock_rfc::btsock_rfc_listen( - service_name, service_uuid, channel, sock_fd, flags, app_uid); + return test::mock::btif_sock_rfc::btsock_rfc_listen(service_name, service_uuid, channel, sock_fd, + flags, app_uid); } void btsock_rfc_signaled(int fd, int flags, uint32_t id) { inc_func_call_count(__func__); diff --git a/system/test/mock/mock_btif_sock_rfc.h b/system/test/mock/mock_btif_sock_rfc.h index eadf438e516..fa0bfe4373a 100644 --- a/system/test/mock/mock_btif_sock_rfc.h +++ b/system/test/mock/mock_btif_sock_rfc.h @@ -50,8 +50,8 @@ namespace btif_sock_rfc { struct bta_co_rfc_data_incoming { static int return_value; std::function body{ - [](uint32_t /* id */, BT_HDR* /* p_buf */) { return return_value; }}; - int operator()(uint32_t id, BT_HDR* p_buf) { return body(id, p_buf); }; + [](uint32_t /* id */, BT_HDR* /* p_buf */) { return return_value; }}; + int operator()(uint32_t id, BT_HDR* p_buf) { return body(id, p_buf); } }; extern struct bta_co_rfc_data_incoming bta_co_rfc_data_incoming; @@ -61,12 +61,8 @@ extern struct bta_co_rfc_data_incoming bta_co_rfc_data_incoming; struct bta_co_rfc_data_outgoing { static int return_value; std::function body{ - [](uint32_t /* id */, uint8_t* /* buf */, uint16_t /* size */) { - return return_value; - }}; - int operator()(uint32_t id, uint8_t* buf, uint16_t size) { - return body(id, buf, size); - }; + [](uint32_t /* id */, uint8_t* /* buf */, uint16_t /* size */) { return return_value; }}; + int operator()(uint32_t id, uint8_t* buf, uint16_t size) { return body(id, buf, size); } }; extern struct bta_co_rfc_data_outgoing bta_co_rfc_data_outgoing; @@ -76,8 +72,8 @@ extern struct bta_co_rfc_data_outgoing bta_co_rfc_data_outgoing; struct bta_co_rfc_data_outgoing_size { static int return_value; std::function body{ - [](uint32_t /* id */, int* /* size */) { return return_value; }}; - int operator()(uint32_t id, int* size) { return body(id, size); }; + [](uint32_t /* id */, int* /* size */) { return return_value; }}; + int operator()(uint32_t id, int* size) { return body(id, size); } }; extern struct bta_co_rfc_data_outgoing_size bta_co_rfc_data_outgoing_size; @@ -86,7 +82,7 @@ extern struct bta_co_rfc_data_outgoing_size bta_co_rfc_data_outgoing_size; // Return: void struct btsock_rfc_cleanup { std::function body{[](void) {}}; - void operator()(void) { body(); }; + void operator()(void) { body(); } }; extern struct btsock_rfc_cleanup btsock_rfc_cleanup; @@ -95,15 +91,15 @@ extern struct btsock_rfc_cleanup btsock_rfc_cleanup; // int* sock_fd, int flags, int app_uid Return: bt_status_t struct btsock_rfc_connect { static bt_status_t return_value; - std::function - body{[](const RawAddress* /* bd_addr */, const Uuid* /* service_uuid */, - int /* channel */, int* /* sock_fd */, int /* flags */, - int /* app_uid */) { return return_value; }}; - bt_status_t operator()(const RawAddress* bd_addr, const Uuid* service_uuid, - int channel, int* sock_fd, int flags, int app_uid) { + std::function + body{[](const RawAddress* /* bd_addr */, const Uuid* /* service_uuid */, + int /* channel */, int* /* sock_fd */, int /* flags */, + int /* app_uid */) { return return_value; }}; + bt_status_t operator()(const RawAddress* bd_addr, const Uuid* service_uuid, int channel, + int* sock_fd, int flags, int app_uid) { return body(bd_addr, service_uuid, channel, sock_fd, flags, app_uid); - }; + } }; extern struct btsock_rfc_connect btsock_rfc_connect; @@ -113,21 +109,17 @@ extern struct btsock_rfc_connect btsock_rfc_connect; // fc Return: bt_status_t struct btsock_rfc_control_req { static bt_status_t return_value; - std::function - body{[](uint8_t /* dlci */, const RawAddress& /* bd_addr */, - uint8_t /* modem_signal */, uint8_t /* break_signal */, - uint8_t /* discard_buffers */, uint8_t /* break_signal_seq */, - bool /* fc */) { return return_value; }}; - bt_status_t operator()(uint8_t dlci, const RawAddress& bd_addr, - uint8_t modem_signal, uint8_t break_signal, - uint8_t discard_buffers, uint8_t break_signal_seq, + body{[](uint8_t /* dlci */, const RawAddress& /* bd_addr */, uint8_t /* modem_signal */, + uint8_t /* break_signal */, uint8_t /* discard_buffers */, + uint8_t /* break_signal_seq */, bool /* fc */) { return return_value; }}; + bt_status_t operator()(uint8_t dlci, const RawAddress& bd_addr, uint8_t modem_signal, + uint8_t break_signal, uint8_t discard_buffers, uint8_t break_signal_seq, bool fc) { - return body(dlci, bd_addr, modem_signal, break_signal, discard_buffers, - break_signal_seq, fc); - }; + return body(dlci, bd_addr, modem_signal, break_signal, discard_buffers, break_signal_seq, fc); + } }; extern struct btsock_rfc_control_req btsock_rfc_control_req; @@ -137,8 +129,8 @@ extern struct btsock_rfc_control_req btsock_rfc_control_req; struct btsock_rfc_disconnect { static bt_status_t return_value; std::function body{ - [](const RawAddress* /* bd_addr */) { return return_value; }}; - bt_status_t operator()(const RawAddress* bd_addr) { return body(bd_addr); }; + [](const RawAddress* /* bd_addr */) { return return_value; }}; + bt_status_t operator()(const RawAddress* bd_addr) { return body(bd_addr); } }; extern struct btsock_rfc_disconnect btsock_rfc_disconnect; @@ -148,12 +140,10 @@ extern struct btsock_rfc_disconnect btsock_rfc_disconnect; struct btsock_rfc_init { static bt_status_t return_value; std::function body{ - [](int /* poll_thread_handle */, uid_set_t* /* set */) { - return return_value; - }}; + [](int /* poll_thread_handle */, uid_set_t* /* set */) { return return_value; }}; bt_status_t operator()(int poll_thread_handle, uid_set_t* set) { return body(poll_thread_handle, set); - }; + } }; extern struct btsock_rfc_init btsock_rfc_init; @@ -162,15 +152,14 @@ extern struct btsock_rfc_init btsock_rfc_init; // sock_fd, int flags, int app_uid Return: bt_status_t struct btsock_rfc_listen { static bt_status_t return_value; - std::function - body{[](const char* /* service_name */, const Uuid* /* service_uuid */, - int /* channel */, int* /* sock_fd */, int /* flags */, - int /* app_uid */) { return return_value; }}; - bt_status_t operator()(const char* service_name, const Uuid* service_uuid, - int channel, int* sock_fd, int flags, int app_uid) { + std::function + body{[](const char* /* service_name */, const Uuid* /* service_uuid */, int /* channel */, + int* /* sock_fd */, int /* flags */, int /* app_uid */) { return return_value; }}; + bt_status_t operator()(const char* service_name, const Uuid* service_uuid, int channel, + int* sock_fd, int flags, int app_uid) { return body(service_name, service_uuid, channel, sock_fd, flags, app_uid); - }; + } }; extern struct btsock_rfc_listen btsock_rfc_listen; @@ -179,8 +168,8 @@ extern struct btsock_rfc_listen btsock_rfc_listen; // Return: void struct btsock_rfc_signaled { std::function body{ - [](int /* fd */, int /* flags */, uint32_t /* id */) {}}; - void operator()(int fd, int flags, uint32_t id) { body(fd, flags, id); }; + [](int /* fd */, int /* flags */, uint32_t /* id */) {}}; + void operator()(int fd, int flags, uint32_t id) { body(fd, flags, id); } }; extern struct btsock_rfc_signaled btsock_rfc_signaled; diff --git a/system/test/mock/mock_btif_stack_manager.cc b/system/test/mock/mock_btif_stack_manager.cc index 55eadc02e17..77a87303453 100644 --- a/system/test/mock/mock_btif_stack_manager.cc +++ b/system/test/mock/mock_btif_stack_manager.cc @@ -32,6 +32,4 @@ auto interfaceToProfiles = MockCoreInterface{}; } // namespace -bluetooth::core::CoreInterface* GetInterfaceToProfiles() { - return &interfaceToProfiles; -} +bluetooth::core::CoreInterface* GetInterfaceToProfiles() { return &interfaceToProfiles; } diff --git a/system/test/mock/mock_btif_storage.cc b/system/test/mock/mock_btif_storage.cc index 7e2d82e2282..d6b059f2e44 100644 --- a/system/test/mock/mock_btif_storage.cc +++ b/system/test/mock/mock_btif_storage.cc @@ -53,29 +53,24 @@ struct btif_storage_get_ble_local_key btif_storage_get_ble_local_key; struct btif_storage_get_gatt_cl_db_hash btif_storage_get_gatt_cl_db_hash; struct btif_storage_get_gatt_cl_supp_feat btif_storage_get_gatt_cl_supp_feat; struct btif_storage_get_remote_addr_type btif_storage_get_remote_addr_type; -struct btif_storage_get_remote_device_property - btif_storage_get_remote_device_property; +struct btif_storage_get_remote_device_property btif_storage_get_remote_device_property; struct btif_storage_get_remote_prop btif_storage_get_remote_prop; struct btif_storage_get_sr_supp_feat btif_storage_get_sr_supp_feat; struct btif_storage_get_stored_remote_name btif_storage_get_stored_remote_name; -struct btif_storage_invoke_addr_type_update - btif_storage_invoke_addr_type_update; +struct btif_storage_invoke_addr_type_update btif_storage_invoke_addr_type_update; struct btif_storage_is_restricted_device btif_storage_is_restricted_device; struct btif_storage_load_bonded_devices btif_storage_load_bonded_devices; struct btif_storage_load_le_devices btif_storage_load_le_devices; -struct btif_storage_remove_ble_bonding_keys - btif_storage_remove_ble_bonding_keys; +struct btif_storage_remove_ble_bonding_keys btif_storage_remove_ble_bonding_keys; struct btif_storage_remove_bonded_device btif_storage_remove_bonded_device; struct btif_storage_remove_gatt_cl_db_hash btif_storage_remove_gatt_cl_db_hash; -struct btif_storage_remove_gatt_cl_supp_feat - btif_storage_remove_gatt_cl_supp_feat; +struct btif_storage_remove_gatt_cl_supp_feat btif_storage_remove_gatt_cl_supp_feat; struct btif_storage_set_adapter_property btif_storage_set_adapter_property; struct btif_storage_set_gatt_cl_db_hash btif_storage_set_gatt_cl_db_hash; struct btif_storage_set_gatt_cl_supp_feat btif_storage_set_gatt_cl_supp_feat; struct btif_storage_set_gatt_sr_supp_feat btif_storage_set_gatt_sr_supp_feat; struct btif_storage_set_remote_addr_type btif_storage_set_remote_addr_type; -struct btif_storage_set_remote_device_property - btif_storage_set_remote_device_property; +struct btif_storage_set_remote_device_property btif_storage_set_remote_device_property; } // namespace btif_storage } // namespace mock @@ -101,19 +96,16 @@ bt_status_t btif_storage_get_ble_local_key::return_value = BT_STATUS_SUCCESS; Octet16 btif_storage_get_gatt_cl_db_hash::return_value = {}; uint8_t btif_storage_get_gatt_cl_supp_feat::return_value = 0; bt_status_t btif_storage_get_remote_addr_type::return_value = BT_STATUS_SUCCESS; -bt_status_t btif_storage_get_remote_device_property::return_value = - BT_STATUS_SUCCESS; +bt_status_t btif_storage_get_remote_device_property::return_value = BT_STATUS_SUCCESS; bt_status_t btif_storage_get_remote_prop::return_value = BT_STATUS_SUCCESS; uint8_t btif_storage_get_sr_supp_feat::return_value = 0; bool btif_storage_get_stored_remote_name::return_value = false; bool btif_storage_is_restricted_device::return_value = false; bt_status_t btif_storage_load_bonded_devices::return_value = BT_STATUS_SUCCESS; -bt_status_t btif_storage_remove_ble_bonding_keys::return_value = - BT_STATUS_SUCCESS; +bt_status_t btif_storage_remove_ble_bonding_keys::return_value = BT_STATUS_SUCCESS; bt_status_t btif_storage_remove_bonded_device::return_value = BT_STATUS_SUCCESS; bt_status_t btif_storage_set_adapter_property::return_value = BT_STATUS_SUCCESS; -bt_status_t btif_storage_set_remote_device_property::return_value = - BT_STATUS_SUCCESS; +bt_status_t btif_storage_set_remote_device_property::return_value = BT_STATUS_SUCCESS; } // namespace btif_storage } // namespace mock @@ -128,74 +120,60 @@ bool btif_has_ble_keys(const std::string& bdstr) { inc_func_call_count(__func__); return test::mock::btif_storage::btif_has_ble_keys(bdstr); } -bt_status_t btif_in_fetch_bonded_ble_device( - const std::string& remote_bd_addr, int add, - btif_bonded_devices_t* p_bonded_devices) { +bt_status_t btif_in_fetch_bonded_ble_device(const std::string& remote_bd_addr, int add, + btif_bonded_devices_t* p_bonded_devices) { inc_func_call_count(__func__); - return test::mock::btif_storage::btif_in_fetch_bonded_ble_device( - remote_bd_addr, add, p_bonded_devices); + return test::mock::btif_storage::btif_in_fetch_bonded_ble_device(remote_bd_addr, add, + p_bonded_devices); } bt_status_t btif_in_fetch_bonded_device(const std::string& bdstr) { inc_func_call_count(__func__); return test::mock::btif_storage::btif_in_fetch_bonded_device(bdstr); } -size_t btif_split_uuids_string(const char* str, bluetooth::Uuid* p_uuid, - size_t max_uuids) { +size_t btif_split_uuids_string(const char* str, bluetooth::Uuid* p_uuid, size_t max_uuids) { inc_func_call_count(__func__); - return test::mock::btif_storage::btif_split_uuids_string(str, p_uuid, - max_uuids); + return test::mock::btif_storage::btif_split_uuids_string(str, p_uuid, max_uuids); } -bt_status_t btif_storage_add_ble_bonding_key(RawAddress* remote_bd_addr, - const uint8_t* key_value, - uint8_t key_type, - uint8_t key_length) { +bt_status_t btif_storage_add_ble_bonding_key(RawAddress* remote_bd_addr, const uint8_t* key_value, + uint8_t key_type, uint8_t key_length) { inc_func_call_count(__func__); - return test::mock::btif_storage::btif_storage_add_ble_bonding_key( - remote_bd_addr, key_value, key_type, key_length); + return test::mock::btif_storage::btif_storage_add_ble_bonding_key(remote_bd_addr, key_value, + key_type, key_length); } -bt_status_t btif_storage_add_ble_local_key(const Octet16& key_value, - uint8_t key_type) { +bt_status_t btif_storage_add_ble_local_key(const Octet16& key_value, uint8_t key_type) { inc_func_call_count(__func__); - return test::mock::btif_storage::btif_storage_add_ble_local_key(key_value, - key_type); + return test::mock::btif_storage::btif_storage_add_ble_local_key(key_value, key_type); } -bt_status_t btif_storage_add_bonded_device(RawAddress* remote_bd_addr, - LinkKey link_key, uint8_t key_type, - uint8_t pin_length) { +bt_status_t btif_storage_add_bonded_device(RawAddress* remote_bd_addr, LinkKey link_key, + uint8_t key_type, uint8_t pin_length) { inc_func_call_count(__func__); - return test::mock::btif_storage::btif_storage_add_bonded_device( - remote_bd_addr, link_key, key_type, pin_length); + return test::mock::btif_storage::btif_storage_add_bonded_device(remote_bd_addr, link_key, + key_type, pin_length); } bt_status_t btif_storage_add_remote_device(const RawAddress* remote_bd_addr, - uint32_t num_properties, - bt_property_t* properties) { + uint32_t num_properties, bt_property_t* properties) { inc_func_call_count(__func__); - return test::mock::btif_storage::btif_storage_add_remote_device( - remote_bd_addr, num_properties, properties); + return test::mock::btif_storage::btif_storage_add_remote_device(remote_bd_addr, num_properties, + properties); } -bt_status_t btif_storage_get_adapter_prop(bt_property_type_t type, void* buf, - int size, bt_property_t* property) { +bt_status_t btif_storage_get_adapter_prop(bt_property_type_t type, void* buf, int size, + bt_property_t* property) { inc_func_call_count(__func__); - return test::mock::btif_storage::btif_storage_get_adapter_prop( - type, buf, size, property); + return test::mock::btif_storage::btif_storage_get_adapter_prop(type, buf, size, property); } bt_status_t btif_storage_get_adapter_property(bt_property_t* property) { inc_func_call_count(__func__); return test::mock::btif_storage::btif_storage_get_adapter_property(property); } -bt_status_t btif_storage_get_ble_bonding_key(const RawAddress& remote_bd_addr, - uint8_t key_type, - uint8_t* key_value, - int key_length) { +bt_status_t btif_storage_get_ble_bonding_key(const RawAddress& remote_bd_addr, uint8_t key_type, + uint8_t* key_value, int key_length) { inc_func_call_count(__func__); - return test::mock::btif_storage::btif_storage_get_ble_bonding_key( - remote_bd_addr, key_type, key_value, key_length); + return test::mock::btif_storage::btif_storage_get_ble_bonding_key(remote_bd_addr, key_type, + key_value, key_length); } -bt_status_t btif_storage_get_ble_local_key(uint8_t key_type, - Octet16* key_value) { +bt_status_t btif_storage_get_ble_local_key(uint8_t key_type, Octet16* key_value) { inc_func_call_count(__func__); - return test::mock::btif_storage::btif_storage_get_ble_local_key(key_type, - key_value); + return test::mock::btif_storage::btif_storage_get_ble_local_key(key_type, key_value); } Octet16 btif_storage_get_gatt_cl_db_hash(const RawAddress& bd_addr) { inc_func_call_count(__func__); @@ -208,42 +186,36 @@ uint8_t btif_storage_get_gatt_cl_supp_feat(const RawAddress& bd_addr) { bt_status_t btif_storage_get_remote_addr_type(const RawAddress* remote_bd_addr, tBLE_ADDR_TYPE* addr_type) { inc_func_call_count(__func__); - return test::mock::btif_storage::btif_storage_get_remote_addr_type( - remote_bd_addr, addr_type); + return test::mock::btif_storage::btif_storage_get_remote_addr_type(remote_bd_addr, addr_type); } -bt_status_t btif_storage_get_remote_device_property( - const RawAddress* remote_bd_addr, bt_property_t* property) { +bt_status_t btif_storage_get_remote_device_property(const RawAddress* remote_bd_addr, + bt_property_t* property) { inc_func_call_count(__func__); - return test::mock::btif_storage::btif_storage_get_remote_device_property( - remote_bd_addr, property); + return test::mock::btif_storage::btif_storage_get_remote_device_property(remote_bd_addr, + property); } -bt_status_t btif_storage_get_remote_prop(RawAddress* remote_addr, - bt_property_type_t type, void* buf, - int size, bt_property_t* property) { +bt_status_t btif_storage_get_remote_prop(RawAddress* remote_addr, bt_property_type_t type, + void* buf, int size, bt_property_t* property) { inc_func_call_count(__func__); - return test::mock::btif_storage::btif_storage_get_remote_prop( - remote_addr, type, buf, size, property); + return test::mock::btif_storage::btif_storage_get_remote_prop(remote_addr, type, buf, size, + property); } uint8_t btif_storage_get_sr_supp_feat(const RawAddress& bd_addr) { inc_func_call_count(__func__); return test::mock::btif_storage::btif_storage_get_sr_supp_feat(bd_addr); } -bool btif_storage_get_stored_remote_name(const RawAddress& bd_addr, - char* name) { +bool btif_storage_get_stored_remote_name(const RawAddress& bd_addr, char* name) { inc_func_call_count(__func__); - return test::mock::btif_storage::btif_storage_get_stored_remote_name(bd_addr, - name); + return test::mock::btif_storage::btif_storage_get_stored_remote_name(bd_addr, name); } void btif_storage_invoke_addr_type_update(const RawAddress& remote_bd_addr, const tBLE_ADDR_TYPE& addr_type) { inc_func_call_count(__func__); - test::mock::btif_storage::btif_storage_invoke_addr_type_update(remote_bd_addr, - addr_type); + test::mock::btif_storage::btif_storage_invoke_addr_type_update(remote_bd_addr, addr_type); } bool btif_storage_is_restricted_device(const RawAddress* remote_bd_addr) { inc_func_call_count(__func__); - return test::mock::btif_storage::btif_storage_is_restricted_device( - remote_bd_addr); + return test::mock::btif_storage::btif_storage_is_restricted_device(remote_bd_addr); } bt_status_t btif_storage_load_bonded_devices(void) { inc_func_call_count(__func__); @@ -253,17 +225,13 @@ void btif_storage_load_le_devices(void) { inc_func_call_count(__func__); test::mock::btif_storage::btif_storage_load_le_devices(); } -bt_status_t btif_storage_remove_ble_bonding_keys( - const RawAddress* remote_bd_addr) { +bt_status_t btif_storage_remove_ble_bonding_keys(const RawAddress* remote_bd_addr) { inc_func_call_count(__func__); - return test::mock::btif_storage::btif_storage_remove_ble_bonding_keys( - remote_bd_addr); + return test::mock::btif_storage::btif_storage_remove_ble_bonding_keys(remote_bd_addr); } -bt_status_t btif_storage_remove_bonded_device( - const RawAddress* remote_bd_addr) { +bt_status_t btif_storage_remove_bonded_device(const RawAddress* remote_bd_addr) { inc_func_call_count(__func__); - return test::mock::btif_storage::btif_storage_remove_bonded_device( - remote_bd_addr); + return test::mock::btif_storage::btif_storage_remove_bonded_device(remote_bd_addr); } void btif_storage_remove_gatt_cl_db_hash(const RawAddress& bd_addr) { inc_func_call_count(__func__); @@ -281,8 +249,7 @@ void btif_storage_set_gatt_cl_db_hash(const RawAddress& bd_addr, Octet16 hash) { inc_func_call_count(__func__); test::mock::btif_storage::btif_storage_set_gatt_cl_db_hash(bd_addr, hash); } -void btif_storage_set_gatt_cl_supp_feat(const RawAddress& bd_addr, - uint8_t feat) { +void btif_storage_set_gatt_cl_supp_feat(const RawAddress& bd_addr, uint8_t feat) { inc_func_call_count(__func__); test::mock::btif_storage::btif_storage_set_gatt_cl_supp_feat(bd_addr, feat); } @@ -293,14 +260,13 @@ void btif_storage_set_gatt_sr_supp_feat(const RawAddress& addr, uint8_t feat) { bt_status_t btif_storage_set_remote_addr_type(const RawAddress* remote_bd_addr, const tBLE_ADDR_TYPE addr_type) { inc_func_call_count(__func__); - return test::mock::btif_storage::btif_storage_set_remote_addr_type( - remote_bd_addr, addr_type); + return test::mock::btif_storage::btif_storage_set_remote_addr_type(remote_bd_addr, addr_type); } -bt_status_t btif_storage_set_remote_device_property( - const RawAddress* remote_bd_addr, bt_property_t* property) { +bt_status_t btif_storage_set_remote_device_property(const RawAddress* remote_bd_addr, + bt_property_t* property) { inc_func_call_count(__func__); - return test::mock::btif_storage::btif_storage_set_remote_device_property( - remote_bd_addr, property); + return test::mock::btif_storage::btif_storage_set_remote_device_property(remote_bd_addr, + property); } // Mocked functions complete // END mockcify generation diff --git a/system/test/mock/mock_btif_storage.h b/system/test/mock/mock_btif_storage.h index a9fde0546f8..45e405fac90 100644 --- a/system/test/mock/mock_btif_storage.h +++ b/system/test/mock/mock_btif_storage.h @@ -51,7 +51,7 @@ namespace btif_storage { // Return: void struct btif_debug_linkkey_type_dump { std::function body{[](int /* fd */) {}}; - void operator()(int fd) { body(fd); }; + void operator()(int fd) { body(fd); } }; extern struct btif_debug_linkkey_type_dump btif_debug_linkkey_type_dump; @@ -61,8 +61,8 @@ extern struct btif_debug_linkkey_type_dump btif_debug_linkkey_type_dump; struct btif_has_ble_keys { static bool return_value; std::function body{ - [](const std::string& /* bdstr */) { return return_value; }}; - bool operator()(const std::string& bdstr) { return body(bdstr); }; + [](const std::string& /* bdstr */) { return return_value; }}; + bool operator()(const std::string& bdstr) { return body(bdstr); } }; extern struct btif_has_ble_keys btif_has_ble_keys; @@ -73,14 +73,12 @@ struct btif_in_fetch_bonded_ble_device { static bt_status_t return_value; std::function - body{[](const std::string& /* remote_bd_addr */, int /* add */, - btif_bonded_devices_t* /* p_bonded_devices */) { - return return_value; - }}; + body{[](const std::string& /* remote_bd_addr */, int /* add */, + btif_bonded_devices_t* /* p_bonded_devices */) { return return_value; }}; bt_status_t operator()(const std::string& remote_bd_addr, int add, btif_bonded_devices_t* p_bonded_devices) { return body(remote_bd_addr, add, p_bonded_devices); - }; + } }; extern struct btif_in_fetch_bonded_ble_device btif_in_fetch_bonded_ble_device; @@ -90,8 +88,8 @@ extern struct btif_in_fetch_bonded_ble_device btif_in_fetch_bonded_ble_device; struct btif_in_fetch_bonded_device { static bt_status_t return_value; std::function body{ - [](const std::string& /* bdstr */) { return return_value; }}; - bt_status_t operator()(const std::string& bdstr) { return body(bdstr); }; + [](const std::string& /* bdstr */) { return return_value; }}; + bt_status_t operator()(const std::string& bdstr) { return body(bdstr); } }; extern struct btif_in_fetch_bonded_device btif_in_fetch_bonded_device; @@ -100,14 +98,13 @@ extern struct btif_in_fetch_bonded_device btif_in_fetch_bonded_device; // Return: size_t struct btif_split_uuids_string { static size_t return_value; - std::function - body{[](const char* /* str */, bluetooth::Uuid* /* p_uuid */, - size_t /* max_uuids */) { return return_value; }}; - size_t operator()(const char* str, bluetooth::Uuid* p_uuid, - size_t max_uuids) { + std::function body{ + [](const char* /* str */, bluetooth::Uuid* /* p_uuid */, size_t /* max_uuids */) { + return return_value; + }}; + size_t operator()(const char* str, bluetooth::Uuid* p_uuid, size_t max_uuids) { return body(str, p_uuid, max_uuids); - }; + } }; extern struct btif_split_uuids_string btif_split_uuids_string; @@ -116,16 +113,14 @@ extern struct btif_split_uuids_string btif_split_uuids_string; // key_type, uint8_t key_length Return: bt_status_t struct btif_storage_add_ble_bonding_key { static bt_status_t return_value; - std::function - body{[](RawAddress* /* remote_bd_addr */, const uint8_t* /* key_value */, - uint8_t /* key_type */, - uint8_t /* key_length */) { return return_value; }}; - bt_status_t operator()(RawAddress* remote_bd_addr, const uint8_t* key_value, - uint8_t key_type, uint8_t key_length) { + body{[](RawAddress* /* remote_bd_addr */, const uint8_t* /* key_value */, + uint8_t /* key_type */, uint8_t /* key_length */) { return return_value; }}; + bt_status_t operator()(RawAddress* remote_bd_addr, const uint8_t* key_value, uint8_t key_type, + uint8_t key_length) { return body(remote_bd_addr, key_value, key_type, key_length); - }; + } }; extern struct btif_storage_add_ble_bonding_key btif_storage_add_ble_bonding_key; @@ -135,12 +130,10 @@ extern struct btif_storage_add_ble_bonding_key btif_storage_add_ble_bonding_key; struct btif_storage_add_ble_local_key { static bt_status_t return_value; std::function body{ - [](const Octet16& /* key_value */, uint8_t /* key_type */) { - return return_value; - }}; + [](const Octet16& /* key_value */, uint8_t /* key_type */) { return return_value; }}; bt_status_t operator()(const Octet16& key_value, uint8_t key_type) { return body(key_value, key_type); - }; + } }; extern struct btif_storage_add_ble_local_key btif_storage_add_ble_local_key; @@ -149,15 +142,14 @@ extern struct btif_storage_add_ble_local_key btif_storage_add_ble_local_key; // uint8_t pin_length Return: bt_status_t struct btif_storage_add_bonded_device { static bt_status_t return_value; - std::function - body{[](RawAddress* /* remote_bd_addr */, LinkKey /* link_key */, - uint8_t /* key_type */, - uint8_t /* pin_length */) { return return_value; }}; - bt_status_t operator()(RawAddress* remote_bd_addr, LinkKey link_key, - uint8_t key_type, uint8_t pin_length) { + std::function + body{[](RawAddress* /* remote_bd_addr */, LinkKey /* link_key */, uint8_t /* key_type */, + uint8_t /* pin_length */) { return return_value; }}; + bt_status_t operator()(RawAddress* remote_bd_addr, LinkKey link_key, uint8_t key_type, + uint8_t pin_length) { return body(remote_bd_addr, link_key, key_type, pin_length); - }; + } }; extern struct btif_storage_add_bonded_device btif_storage_add_bonded_device; @@ -166,15 +158,14 @@ extern struct btif_storage_add_bonded_device btif_storage_add_bonded_device; // bt_property_t* properties Return: bt_status_t struct btif_storage_add_remote_device { static bt_status_t return_value; - std::function - body{[](const RawAddress* /* remote_bd_addr */, - uint32_t /* num_properties */, - bt_property_t* /* properties */) { return return_value; }}; - bt_status_t operator()(const RawAddress* remote_bd_addr, - uint32_t num_properties, bt_property_t* properties) { + std::function + body{[](const RawAddress* /* remote_bd_addr */, uint32_t /* num_properties */, + bt_property_t* /* properties */) { return return_value; }}; + bt_status_t operator()(const RawAddress* remote_bd_addr, uint32_t num_properties, + bt_property_t* properties) { return body(remote_bd_addr, num_properties, properties); - }; + } }; extern struct btif_storage_add_remote_device btif_storage_add_remote_device; @@ -183,14 +174,12 @@ extern struct btif_storage_add_remote_device btif_storage_add_remote_device; // Return: bt_status_t struct btif_storage_get_adapter_prop { static bt_status_t return_value; - std::function - body{[](bt_property_type_t /* type */, void* /* buf */, int /* size */, - bt_property_t* /* property */) { return return_value; }}; - bt_status_t operator()(bt_property_type_t type, void* buf, int size, - bt_property_t* property) { + std::function + body{[](bt_property_type_t /* type */, void* /* buf */, int /* size */, + bt_property_t* /* property */) { return return_value; }}; + bt_status_t operator()(bt_property_type_t type, void* buf, int size, bt_property_t* property) { return body(type, buf, size, property); - }; + } }; extern struct btif_storage_get_adapter_prop btif_storage_get_adapter_prop; @@ -200,26 +189,24 @@ extern struct btif_storage_get_adapter_prop btif_storage_get_adapter_prop; struct btif_storage_get_adapter_property { static bt_status_t return_value; std::function body{ - [](bt_property_t* /* property */) { return return_value; }}; - bt_status_t operator()(bt_property_t* property) { return body(property); }; + [](bt_property_t* /* property */) { return return_value; }}; + bt_status_t operator()(bt_property_t* property) { return body(property); } }; -extern struct btif_storage_get_adapter_property - btif_storage_get_adapter_property; +extern struct btif_storage_get_adapter_property btif_storage_get_adapter_property; // Name: btif_storage_get_ble_bonding_key // Params: const RawAddress& remote_bd_addr, uint8_t key_type, uint8_t* // key_value, int key_length Return: bt_status_t struct btif_storage_get_ble_bonding_key { static bt_status_t return_value; - std::function - body{[](const RawAddress& /* remote_bd_addr */, uint8_t /* key_type */, - uint8_t* /* key_value */, - int /* key_length */) { return return_value; }}; - bt_status_t operator()(const RawAddress& remote_bd_addr, uint8_t key_type, - uint8_t* key_value, int key_length) { + std::function + body{[](const RawAddress& /* remote_bd_addr */, uint8_t /* key_type */, + uint8_t* /* key_value */, int /* key_length */) { return return_value; }}; + bt_status_t operator()(const RawAddress& remote_bd_addr, uint8_t key_type, uint8_t* key_value, + int key_length) { return body(remote_bd_addr, key_type, key_value, key_length); - }; + } }; extern struct btif_storage_get_ble_bonding_key btif_storage_get_ble_bonding_key; @@ -229,12 +216,8 @@ extern struct btif_storage_get_ble_bonding_key btif_storage_get_ble_bonding_key; struct btif_storage_get_ble_local_key { static bt_status_t return_value; std::function body{ - [](uint8_t /* key_type */, Octet16* /* key_value */) { - return return_value; - }}; - bt_status_t operator()(uint8_t key_type, Octet16* key_value) { - return body(key_type, key_value); - }; + [](uint8_t /* key_type */, Octet16* /* key_value */) { return return_value; }}; + bt_status_t operator()(uint8_t key_type, Octet16* key_value) { return body(key_type, key_value); } }; extern struct btif_storage_get_ble_local_key btif_storage_get_ble_local_key; @@ -244,8 +227,8 @@ extern struct btif_storage_get_ble_local_key btif_storage_get_ble_local_key; struct btif_storage_get_gatt_cl_db_hash { static Octet16 return_value; std::function body{ - [](const RawAddress& /* bd_addr */) { return return_value; }}; - Octet16 operator()(const RawAddress& bd_addr) { return body(bd_addr); }; + [](const RawAddress& /* bd_addr */) { return return_value; }}; + Octet16 operator()(const RawAddress& bd_addr) { return body(bd_addr); } }; extern struct btif_storage_get_gatt_cl_db_hash btif_storage_get_gatt_cl_db_hash; @@ -255,62 +238,53 @@ extern struct btif_storage_get_gatt_cl_db_hash btif_storage_get_gatt_cl_db_hash; struct btif_storage_get_gatt_cl_supp_feat { static uint8_t return_value; std::function body{ - [](const RawAddress& /* bd_addr */) { return return_value; }}; - uint8_t operator()(const RawAddress& bd_addr) { return body(bd_addr); }; + [](const RawAddress& /* bd_addr */) { return return_value; }}; + uint8_t operator()(const RawAddress& bd_addr) { return body(bd_addr); } }; -extern struct btif_storage_get_gatt_cl_supp_feat - btif_storage_get_gatt_cl_supp_feat; +extern struct btif_storage_get_gatt_cl_supp_feat btif_storage_get_gatt_cl_supp_feat; // Name: btif_storage_get_remote_addr_type // Params: const RawAddress* remote_bd_addr, tBLE_ADDR_TYPE addr_type // Return: bt_status_t struct btif_storage_get_remote_addr_type { static bt_status_t return_value; - std::function - body{[](const RawAddress* /* remote_bd_addr */, - tBLE_ADDR_TYPE* /* addr_type */) -> bt_status_t { - return return_value; - }}; - bt_status_t operator()(const RawAddress* remote_bd_addr, - tBLE_ADDR_TYPE* addr_type) { + std::function body{ + [](const RawAddress* /* remote_bd_addr */, + tBLE_ADDR_TYPE* /* addr_type */) -> bt_status_t { return return_value; }}; + bt_status_t operator()(const RawAddress* remote_bd_addr, tBLE_ADDR_TYPE* addr_type) { return body(remote_bd_addr, addr_type); - }; + } }; -extern struct btif_storage_get_remote_addr_type - btif_storage_get_remote_addr_type; +extern struct btif_storage_get_remote_addr_type btif_storage_get_remote_addr_type; // Name: btif_storage_get_remote_device_property // Params: const RawAddress* remote_bd_addr, bt_property_t* property // Return: bt_status_t struct btif_storage_get_remote_device_property { static bt_status_t return_value; - std::function - body{[](const RawAddress* /* remote_bd_addr */, - bt_property_t* /* property */) { return return_value; }}; - bt_status_t operator()(const RawAddress* remote_bd_addr, - bt_property_t* property) { + std::function body{ + [](const RawAddress* /* remote_bd_addr */, bt_property_t* /* property */) { + return return_value; + }}; + bt_status_t operator()(const RawAddress* remote_bd_addr, bt_property_t* property) { return body(remote_bd_addr, property); - }; + } }; -extern struct btif_storage_get_remote_device_property - btif_storage_get_remote_device_property; +extern struct btif_storage_get_remote_device_property btif_storage_get_remote_device_property; // Name: btif_storage_get_remote_prop // Params: RawAddress* remote_addr, bt_property_type_t type, void* buf, int // size, bt_property_t* property Return: bt_status_t struct btif_storage_get_remote_prop { static bt_status_t return_value; - std::function - body{[](RawAddress* /* remote_addr */, bt_property_type_t /* type */, - void* /* buf */, int /* size */, - bt_property_t* /* property */) { return return_value; }}; - bt_status_t operator()(RawAddress* remote_addr, bt_property_type_t type, - void* buf, int size, bt_property_t* property) { + std::function + body{[](RawAddress* /* remote_addr */, bt_property_type_t /* type */, void* /* buf */, + int /* size */, bt_property_t* /* property */) { return return_value; }}; + bt_status_t operator()(RawAddress* remote_addr, bt_property_type_t type, void* buf, int size, + bt_property_t* property) { return body(remote_addr, type, buf, size, property); - }; + } }; extern struct btif_storage_get_remote_prop btif_storage_get_remote_prop; @@ -320,8 +294,8 @@ extern struct btif_storage_get_remote_prop btif_storage_get_remote_prop; struct btif_storage_get_sr_supp_feat { static uint8_t return_value; std::function body{ - [](const RawAddress& /* bd_addr */) { return return_value; }}; - uint8_t operator()(const RawAddress& bd_addr) { return body(bd_addr); }; + [](const RawAddress& /* bd_addr */) { return return_value; }}; + uint8_t operator()(const RawAddress& bd_addr) { return body(bd_addr); } }; extern struct btif_storage_get_sr_supp_feat btif_storage_get_sr_supp_feat; @@ -331,31 +305,22 @@ extern struct btif_storage_get_sr_supp_feat btif_storage_get_sr_supp_feat; struct btif_storage_get_stored_remote_name { static bool return_value; std::function body{ - [](const RawAddress& /* bd_addr */, char* /* name */) { - return return_value; - }}; - bool operator()(const RawAddress& bd_addr, char* name) { - return body(bd_addr, name); - }; + [](const RawAddress& /* bd_addr */, char* /* name */) { return return_value; }}; + bool operator()(const RawAddress& bd_addr, char* name) { return body(bd_addr, name); } }; -extern struct btif_storage_get_stored_remote_name - btif_storage_get_stored_remote_name; +extern struct btif_storage_get_stored_remote_name btif_storage_get_stored_remote_name; // Name: btif_storage_invoke_addr_type_update // Params: const RawAddress& remote_bd_addr, const tBLE_ADDR_TYPE& addr_type // Return: void struct btif_storage_invoke_addr_type_update { - std::function - body{[](const RawAddress& /* remote_bd_addr */, - const tBLE_ADDR_TYPE& /* addr_type */) {}}; - void operator()(const RawAddress& remote_bd_addr, - const tBLE_ADDR_TYPE& addr_type) { + std::function body{ + [](const RawAddress& /* remote_bd_addr */, const tBLE_ADDR_TYPE& /* addr_type */) {}}; + void operator()(const RawAddress& remote_bd_addr, const tBLE_ADDR_TYPE& addr_type) { body(remote_bd_addr, addr_type); - }; + } }; -extern struct btif_storage_invoke_addr_type_update - btif_storage_invoke_addr_type_update; +extern struct btif_storage_invoke_addr_type_update btif_storage_invoke_addr_type_update; // Name: btif_storage_is_restricted_device // Params: const RawAddress* remote_bd_addr @@ -363,13 +328,10 @@ extern struct btif_storage_invoke_addr_type_update struct btif_storage_is_restricted_device { static bool return_value; std::function body{ - [](const RawAddress* /* remote_bd_addr */) { return return_value; }}; - bool operator()(const RawAddress* remote_bd_addr) { - return body(remote_bd_addr); - }; + [](const RawAddress* /* remote_bd_addr */) { return return_value; }}; + bool operator()(const RawAddress* remote_bd_addr) { return body(remote_bd_addr); } }; -extern struct btif_storage_is_restricted_device - btif_storage_is_restricted_device; +extern struct btif_storage_is_restricted_device btif_storage_is_restricted_device; // Name: btif_storage_load_bonded_devices // Params: void @@ -377,7 +339,7 @@ extern struct btif_storage_is_restricted_device struct btif_storage_load_bonded_devices { static bt_status_t return_value; std::function body{[](void) { return return_value; }}; - bt_status_t operator()(void) { return body(); }; + bt_status_t operator()(void) { return body(); } }; extern struct btif_storage_load_bonded_devices btif_storage_load_bonded_devices; @@ -386,7 +348,7 @@ extern struct btif_storage_load_bonded_devices btif_storage_load_bonded_devices; // Return: void struct btif_storage_load_le_devices { std::function body{[](void) {}}; - void operator()(void) { body(); }; + void operator()(void) { body(); } }; extern struct btif_storage_load_le_devices btif_storage_load_le_devices; @@ -396,13 +358,10 @@ extern struct btif_storage_load_le_devices btif_storage_load_le_devices; struct btif_storage_remove_ble_bonding_keys { static bt_status_t return_value; std::function body{ - [](const RawAddress* /* remote_bd_addr */) { return return_value; }}; - bt_status_t operator()(const RawAddress* remote_bd_addr) { - return body(remote_bd_addr); - }; + [](const RawAddress* /* remote_bd_addr */) { return return_value; }}; + bt_status_t operator()(const RawAddress* remote_bd_addr) { return body(remote_bd_addr); } }; -extern struct btif_storage_remove_ble_bonding_keys - btif_storage_remove_ble_bonding_keys; +extern struct btif_storage_remove_ble_bonding_keys btif_storage_remove_ble_bonding_keys; // Name: btif_storage_remove_ble_local_keys // Params: void @@ -410,10 +369,9 @@ extern struct btif_storage_remove_ble_bonding_keys struct btif_storage_remove_ble_local_keys { static bt_status_t return_value; std::function body{[](void) { return return_value; }}; - bt_status_t operator()(void) { return body(); }; + bt_status_t operator()(void) { return body(); } }; -extern struct btif_storage_remove_ble_local_keys - btif_storage_remove_ble_local_keys; +extern struct btif_storage_remove_ble_local_keys btif_storage_remove_ble_local_keys; // Name: btif_storage_remove_bonded_device // Params: const RawAddress* remote_bd_addr @@ -421,35 +379,28 @@ extern struct btif_storage_remove_ble_local_keys struct btif_storage_remove_bonded_device { static bt_status_t return_value; std::function body{ - [](const RawAddress* /* remote_bd_addr */) { return return_value; }}; - bt_status_t operator()(const RawAddress* remote_bd_addr) { - return body(remote_bd_addr); - }; + [](const RawAddress* /* remote_bd_addr */) { return return_value; }}; + bt_status_t operator()(const RawAddress* remote_bd_addr) { return body(remote_bd_addr); } }; -extern struct btif_storage_remove_bonded_device - btif_storage_remove_bonded_device; +extern struct btif_storage_remove_bonded_device btif_storage_remove_bonded_device; // Name: btif_storage_remove_gatt_cl_db_hash // Params: const RawAddress& bd_addr // Return: void struct btif_storage_remove_gatt_cl_db_hash { - std::function body{ - [](const RawAddress& /* bd_addr */) {}}; - void operator()(const RawAddress& bd_addr) { body(bd_addr); }; + std::function body{[](const RawAddress& /* bd_addr */) {}}; + void operator()(const RawAddress& bd_addr) { body(bd_addr); } }; -extern struct btif_storage_remove_gatt_cl_db_hash - btif_storage_remove_gatt_cl_db_hash; +extern struct btif_storage_remove_gatt_cl_db_hash btif_storage_remove_gatt_cl_db_hash; // Name: btif_storage_remove_gatt_cl_supp_feat // Params: const RawAddress& bd_addr // Return: void struct btif_storage_remove_gatt_cl_supp_feat { - std::function body{ - [](const RawAddress& /* bd_addr */) {}}; - void operator()(const RawAddress& bd_addr) { body(bd_addr); }; + std::function body{[](const RawAddress& /* bd_addr */) {}}; + void operator()(const RawAddress& bd_addr) { body(bd_addr); } }; -extern struct btif_storage_remove_gatt_cl_supp_feat - btif_storage_remove_gatt_cl_supp_feat; +extern struct btif_storage_remove_gatt_cl_supp_feat btif_storage_remove_gatt_cl_supp_feat; // Name: btif_storage_set_adapter_property // Params: bt_property_t* property @@ -457,21 +408,18 @@ extern struct btif_storage_remove_gatt_cl_supp_feat struct btif_storage_set_adapter_property { static bt_status_t return_value; std::function body{ - [](bt_property_t* /* property */) { return return_value; }}; - bt_status_t operator()(bt_property_t* property) { return body(property); }; + [](bt_property_t* /* property */) { return return_value; }}; + bt_status_t operator()(bt_property_t* property) { return body(property); } }; -extern struct btif_storage_set_adapter_property - btif_storage_set_adapter_property; +extern struct btif_storage_set_adapter_property btif_storage_set_adapter_property; // Name: btif_storage_set_gatt_cl_db_hash // Params: const RawAddress& bd_addr, Octet16 hash // Return: void struct btif_storage_set_gatt_cl_db_hash { std::function body{ - [](const RawAddress& /* bd_addr */, Octet16 /* hash */) {}}; - void operator()(const RawAddress& bd_addr, Octet16 hash) { - body(bd_addr, hash); - }; + [](const RawAddress& /* bd_addr */, Octet16 /* hash */) {}}; + void operator()(const RawAddress& bd_addr, Octet16 hash) { body(bd_addr, hash); } }; extern struct btif_storage_set_gatt_cl_db_hash btif_storage_set_gatt_cl_db_hash; @@ -480,59 +428,49 @@ extern struct btif_storage_set_gatt_cl_db_hash btif_storage_set_gatt_cl_db_hash; // Return: void struct btif_storage_set_gatt_cl_supp_feat { std::function body{ - [](const RawAddress& /* bd_addr */, uint8_t /* feat */) {}}; - void operator()(const RawAddress& bd_addr, uint8_t feat) { - body(bd_addr, feat); - }; + [](const RawAddress& /* bd_addr */, uint8_t /* feat */) {}}; + void operator()(const RawAddress& bd_addr, uint8_t feat) { body(bd_addr, feat); } }; -extern struct btif_storage_set_gatt_cl_supp_feat - btif_storage_set_gatt_cl_supp_feat; +extern struct btif_storage_set_gatt_cl_supp_feat btif_storage_set_gatt_cl_supp_feat; // Name: btif_storage_set_gatt_sr_supp_feat // Params: const RawAddress& addr, uint8_t feat // Return: void struct btif_storage_set_gatt_sr_supp_feat { std::function body{ - [](const RawAddress& /* addr */, uint8_t /* feat */) {}}; - void operator()(const RawAddress& addr, uint8_t feat) { body(addr, feat); }; + [](const RawAddress& /* addr */, uint8_t /* feat */) {}}; + void operator()(const RawAddress& addr, uint8_t feat) { body(addr, feat); } }; -extern struct btif_storage_set_gatt_sr_supp_feat - btif_storage_set_gatt_sr_supp_feat; +extern struct btif_storage_set_gatt_sr_supp_feat btif_storage_set_gatt_sr_supp_feat; // Name: btif_storage_set_remote_addr_type // Params: const RawAddress& remote_bd_addr, const tBLE_ADDR_TYPE& addr_type // Return: void struct btif_storage_set_remote_addr_type { - std::function - body{[](const RawAddress* /* remote_bd_addr */, - const tBLE_ADDR_TYPE /* addr_type */) { - return BT_STATUS_SUCCESS; - }}; - bt_status_t operator()(const RawAddress* remote_bd_addr, - const tBLE_ADDR_TYPE addr_type) { + std::function body{ + [](const RawAddress* /* remote_bd_addr */, const tBLE_ADDR_TYPE /* addr_type */) { + return BT_STATUS_SUCCESS; + }}; + bt_status_t operator()(const RawAddress* remote_bd_addr, const tBLE_ADDR_TYPE addr_type) { return body(remote_bd_addr, addr_type); - }; + } }; -extern struct btif_storage_set_remote_addr_type - btif_storage_set_remote_addr_type; +extern struct btif_storage_set_remote_addr_type btif_storage_set_remote_addr_type; // Name: btif_storage_set_remote_device_property // Params: const RawAddress* remote_bd_addr, bt_property_t* property // Return: bt_status_t struct btif_storage_set_remote_device_property { static bt_status_t return_value; - std::function - body{[](const RawAddress* /* remote_bd_addr */, - bt_property_t* /* property */) { return return_value; }}; - bt_status_t operator()(const RawAddress* remote_bd_addr, - bt_property_t* property) { + std::function body{ + [](const RawAddress* /* remote_bd_addr */, bt_property_t* /* property */) { + return return_value; + }}; + bt_status_t operator()(const RawAddress* remote_bd_addr, bt_property_t* property) { return body(remote_bd_addr, property); - }; + } }; -extern struct btif_storage_set_remote_device_property - btif_storage_set_remote_device_property; +extern struct btif_storage_set_remote_device_property btif_storage_set_remote_device_property; } // namespace btif_storage } // namespace mock diff --git a/system/test/mock/mock_btif_util.h b/system/test/mock/mock_btif_util.h index d5ffa031e69..7dd4188ce09 100644 --- a/system/test/mock/mock_btif_util.h +++ b/system/test/mock/mock_btif_util.h @@ -46,12 +46,10 @@ namespace btif_util { struct ascii_2_hex { static int return_value; std::function body{ - [](const char* /* p_ascii */, int /* len */, uint8_t* /* p_hex */) { - return return_value; - }}; - int operator()(const char* p_ascii, int len, uint8_t* p_hex) { - return body(p_ascii, len, p_hex); - }; + [](const char* /* p_ascii */, int /* len */, uint8_t* /* p_hex */) { + return return_value; + }}; + int operator()(const char* p_ascii, int len, uint8_t* p_hex) { return body(p_ascii, len, p_hex); } }; extern struct ascii_2_hex ascii_2_hex; @@ -61,8 +59,8 @@ extern struct ascii_2_hex ascii_2_hex; struct devclass2uint { static uint32_t return_value; std::function body{ - [](DEV_CLASS /* dev_class */) { return return_value; }}; - uint32_t operator()(DEV_CLASS dev_class) { return body(dev_class); }; + [](DEV_CLASS /* dev_class */) { return return_value; }}; + uint32_t operator()(DEV_CLASS dev_class) { return body(dev_class); } }; extern struct devclass2uint devclass2uint; @@ -72,8 +70,8 @@ extern struct devclass2uint devclass2uint; struct dump_adapter_scan_mode { static const char* return_value; std::function body{ - [](bt_scan_mode_t /* mode */) { return return_value; }}; - const char* operator()(bt_scan_mode_t mode) { return body(mode); }; + [](bt_scan_mode_t /* mode */) { return return_value; }}; + const char* operator()(bt_scan_mode_t mode) { return body(mode); } }; extern struct dump_adapter_scan_mode dump_adapter_scan_mode; @@ -83,8 +81,8 @@ extern struct dump_adapter_scan_mode dump_adapter_scan_mode; struct dump_av_audio_state { static const char* return_value; std::function body{ - [](uint16_t /* event */) { return return_value; }}; - const char* operator()(uint16_t event) { return body(event); }; + [](uint16_t /* event */) { return return_value; }}; + const char* operator()(uint16_t event) { return body(event); } }; extern struct dump_av_audio_state dump_av_audio_state; @@ -94,8 +92,8 @@ extern struct dump_av_audio_state dump_av_audio_state; struct dump_av_conn_state { static const char* return_value; std::function body{ - [](uint16_t /* event */) { return return_value; }}; - const char* operator()(uint16_t event) { return body(event); }; + [](uint16_t /* event */) { return return_value; }}; + const char* operator()(uint16_t event) { return body(event); } }; extern struct dump_av_conn_state dump_av_conn_state; @@ -105,8 +103,8 @@ extern struct dump_av_conn_state dump_av_conn_state; struct dump_bt_status { static const char* return_value; std::function body{ - [](bt_status_t /* status */) { return return_value; }}; - const char* operator()(bt_status_t status) { return body(status); }; + [](bt_status_t /* status */) { return return_value; }}; + const char* operator()(bt_status_t status) { return body(status); } }; extern struct dump_bt_status dump_bt_status; @@ -116,8 +114,8 @@ extern struct dump_bt_status dump_bt_status; struct dump_dm_event { static const char* return_value; std::function body{ - [](uint16_t /* event */) { return return_value; }}; - const char* operator()(uint16_t event) { return body(event); }; + [](uint16_t /* event */) { return return_value; }}; + const char* operator()(uint16_t event) { return body(event); } }; extern struct dump_dm_event dump_dm_event; @@ -127,8 +125,8 @@ extern struct dump_dm_event dump_dm_event; struct dump_dm_search_event { static const char* return_value; std::function body{ - [](uint16_t /* event */) { return return_value; }}; - const char* operator()(uint16_t event) { return body(event); }; + [](uint16_t /* event */) { return return_value; }}; + const char* operator()(uint16_t event) { return body(event); } }; extern struct dump_dm_search_event dump_dm_search_event; @@ -138,8 +136,8 @@ extern struct dump_dm_search_event dump_dm_search_event; struct dump_hd_event { static const char* return_value; std::function body{ - [](uint16_t /* event */) { return return_value; }}; - const char* operator()(uint16_t event) { return body(event); }; + [](uint16_t /* event */) { return return_value; }}; + const char* operator()(uint16_t event) { return body(event); } }; extern struct dump_hd_event dump_hd_event; @@ -149,8 +147,8 @@ extern struct dump_hd_event dump_hd_event; struct dump_hf_client_event { static const char* return_value; std::function body{ - [](uint16_t /* event */) { return return_value; }}; - const char* operator()(uint16_t event) { return body(event); }; + [](uint16_t /* event */) { return return_value; }}; + const char* operator()(uint16_t event) { return body(event); } }; extern struct dump_hf_client_event dump_hf_client_event; @@ -160,8 +158,8 @@ extern struct dump_hf_client_event dump_hf_client_event; struct dump_hf_event { static const char* return_value; std::function body{ - [](uint16_t /* event */) { return return_value; }}; - const char* operator()(uint16_t event) { return body(event); }; + [](uint16_t /* event */) { return return_value; }}; + const char* operator()(uint16_t event) { return body(event); } }; // Name: dump_property_type @@ -170,8 +168,8 @@ struct dump_hf_event { struct dump_property_type { static const char* return_value; std::function body{ - [](bt_property_type_t /* type */) { return return_value; }}; - const char* operator()(bt_property_type_t type) { return body(type); }; + [](bt_property_type_t /* type */) { return return_value; }}; + const char* operator()(bt_property_type_t type) { return body(type); } }; extern struct dump_property_type dump_property_type; @@ -180,9 +178,8 @@ extern struct dump_property_type dump_property_type; // Return: const char* struct dump_rc_event { static const char* return_value; - std::function body{ - [](uint8_t /* event */) { return return_value; }}; - const char* operator()(uint8_t event) { return body(event); }; + std::function body{[](uint8_t /* event */) { return return_value; }}; + const char* operator()(uint8_t event) { return body(event); } }; extern struct dump_rc_event dump_rc_event; @@ -192,8 +189,8 @@ extern struct dump_rc_event dump_rc_event; struct dump_rc_notification_event_id { static const char* return_value; std::function body{ - [](uint8_t /* event_id */) { return return_value; }}; - const char* operator()(uint8_t event_id) { return body(event_id); }; + [](uint8_t /* event_id */) { return return_value; }}; + const char* operator()(uint8_t event_id) { return body(event_id); } }; extern struct dump_rc_notification_event_id dump_rc_notification_event_id; @@ -202,9 +199,8 @@ extern struct dump_rc_notification_event_id dump_rc_notification_event_id; // Return: const char* struct dump_rc_pdu { static const char* return_value; - std::function body{ - [](uint8_t /* pdu */) { return return_value; }}; - const char* operator()(uint8_t pdu) { return body(pdu); }; + std::function body{[](uint8_t /* pdu */) { return return_value; }}; + const char* operator()(uint8_t pdu) { return body(pdu); } }; extern struct dump_rc_pdu dump_rc_pdu; @@ -214,8 +210,8 @@ extern struct dump_rc_pdu dump_rc_pdu; struct dump_thread_evt { static const char* return_value; std::function body{ - [](bt_cb_thread_evt /* evt */) { return return_value; }}; - const char* operator()(bt_cb_thread_evt evt) { return body(evt); }; + [](bt_cb_thread_evt /* evt */) { return return_value; }}; + const char* operator()(bt_cb_thread_evt evt) { return body(evt); } }; extern struct dump_thread_evt dump_thread_evt; @@ -224,9 +220,8 @@ extern struct dump_thread_evt dump_thread_evt; // Return: void struct uint2devclass { static constexpr DEV_CLASS return_value{}; - std::function body{ - [](uint32_t /* cod */) { return return_value; }}; - DEV_CLASS operator()(uint32_t cod) { return body(cod); }; + std::function body{[](uint32_t /* cod */) { return return_value; }}; + DEV_CLASS operator()(uint32_t cod) { return body(cod); } }; extern struct uint2devclass uint2devclass; diff --git a/system/test/mock/mock_common_os_utils.h b/system/test/mock/mock_common_os_utils.h index ab78c85a76e..4c8d345b9f5 100644 --- a/system/test/mock/mock_common_os_utils.h +++ b/system/test/mock/mock_common_os_utils.h @@ -42,7 +42,7 @@ namespace common_os_utils { struct is_bluetooth_uid { static bool return_value; std::function body{[]() { return return_value; }}; - bool operator()() { return body(); }; + bool operator()() { return body(); } }; extern struct is_bluetooth_uid is_bluetooth_uid; diff --git a/system/test/mock/mock_device_esco_parameters.h b/system/test/mock/mock_device_esco_parameters.h index 855a94bde2a..92e5ad085d7 100644 --- a/system/test/mock/mock_device_esco_parameters.h +++ b/system/test/mock/mock_device_esco_parameters.h @@ -39,8 +39,8 @@ namespace device_esco_parameters { struct esco_parameters_for_codec { enh_esco_params_t return_value{}; std::function body{ - [this](esco_codec_t /* codec */) { return return_value; }}; - enh_esco_params_t operator()(esco_codec_t codec) { return body(codec); }; + [this](esco_codec_t /* codec */) { return return_value; }}; + enh_esco_params_t operator()(esco_codec_t codec) { return body(codec); } }; extern struct esco_parameters_for_codec esco_parameters_for_codec; diff --git a/system/test/mock/mock_device_interop.cc b/system/test/mock/mock_device_interop.cc index 698d3a87c41..4f98781b236 100644 --- a/system/test/mock/mock_device_interop.cc +++ b/system/test/mock/mock_device_interop.cc @@ -38,8 +38,7 @@ namespace device_interop { // Function state capture and return values, if needed struct interop_database_add interop_database_add; struct interop_database_add_addr interop_database_add_addr; -struct interop_database_add_addr_lmp_version - interop_database_add_addr_lmp_version; +struct interop_database_add_addr_lmp_version interop_database_add_addr_lmp_version; struct interop_database_add_addr_max_lat interop_database_add_addr_max_lat; struct interop_database_add_manufacturer interop_database_add_manufacturer; struct interop_database_add_name interop_database_add_name; @@ -47,22 +46,17 @@ struct interop_database_add_version interop_database_add_version; struct interop_database_add_vndr_prdt interop_database_add_vndr_prdt; struct interop_database_clear interop_database_clear; struct interop_database_match_addr interop_database_match_addr; -struct interop_database_match_addr_get_lmp_ver - interop_database_match_addr_get_lmp_ver; -struct interop_database_match_addr_get_max_lat - interop_database_match_addr_get_max_lat; +struct interop_database_match_addr_get_lmp_ver interop_database_match_addr_get_lmp_ver; +struct interop_database_match_addr_get_max_lat interop_database_match_addr_get_max_lat; struct interop_database_match_manufacturer interop_database_match_manufacturer; struct interop_database_match_name interop_database_match_name; struct interop_database_match_version interop_database_match_version; struct interop_database_match_vndr_prdt interop_database_match_vndr_prdt; struct interop_database_remove_addr interop_database_remove_addr; -struct interop_database_remove_addr_lmp_version - interop_database_remove_addr_lmp_version; -struct interop_database_remove_addr_max_lat - interop_database_remove_addr_max_lat; +struct interop_database_remove_addr_lmp_version interop_database_remove_addr_lmp_version; +struct interop_database_remove_addr_max_lat interop_database_remove_addr_max_lat; struct interop_database_remove_feature interop_database_remove_feature; -struct interop_database_remove_manufacturer - interop_database_remove_manufacturer; +struct interop_database_remove_manufacturer interop_database_remove_manufacturer; struct interop_database_remove_name interop_database_remove_name; struct interop_database_remove_version interop_database_remove_version; struct interop_database_remove_vndr_prdt interop_database_remove_vndr_prdt; @@ -113,188 +107,152 @@ bool token_to_ul::return_value = false; } // namespace test // Mocked functions, if any -void interop_database_add(const uint16_t feature, const RawAddress* addr, - size_t length) { +void interop_database_add(const uint16_t feature, const RawAddress* addr, size_t length) { inc_func_call_count(__func__); test::mock::device_interop::interop_database_add(feature, addr, length); } -void interop_database_add_addr(const uint16_t feature, const RawAddress* addr, - size_t length) { +void interop_database_add_addr(const uint16_t feature, const RawAddress* addr, size_t length) { inc_func_call_count(__func__); test::mock::device_interop::interop_database_add_addr(feature, addr, length); } -void interop_database_add_addr_lmp_version(const interop_feature_t feature, - const RawAddress* addr, - uint8_t lmp_ver, - uint16_t lmp_sub_ver) { +void interop_database_add_addr_lmp_version(const interop_feature_t feature, const RawAddress* addr, + uint8_t lmp_ver, uint16_t lmp_sub_ver) { inc_func_call_count(__func__); - test::mock::device_interop::interop_database_add_addr_lmp_version( - feature, addr, lmp_ver, lmp_sub_ver); + test::mock::device_interop::interop_database_add_addr_lmp_version(feature, addr, lmp_ver, + lmp_sub_ver); } -void interop_database_add_addr_max_lat(const interop_feature_t feature, - const RawAddress* addr, +void interop_database_add_addr_max_lat(const interop_feature_t feature, const RawAddress* addr, uint16_t max_lat) { inc_func_call_count(__func__); - test::mock::device_interop::interop_database_add_addr_max_lat(feature, addr, - max_lat); + test::mock::device_interop::interop_database_add_addr_max_lat(feature, addr, max_lat); } -void interop_database_add_manufacturer(const interop_feature_t feature, - uint16_t manufacturer) { +void interop_database_add_manufacturer(const interop_feature_t feature, uint16_t manufacturer) { inc_func_call_count(__func__); - test::mock::device_interop::interop_database_add_manufacturer(feature, - manufacturer); + test::mock::device_interop::interop_database_add_manufacturer(feature, manufacturer); } void interop_database_add_name(const uint16_t feature, const char* name) { inc_func_call_count(__func__); test::mock::device_interop::interop_database_add_name(feature, name); } -void interop_database_add_version(const interop_feature_t feature, - uint16_t version) { +void interop_database_add_version(const interop_feature_t feature, uint16_t version) { inc_func_call_count(__func__); test::mock::device_interop::interop_database_add_version(feature, version); } -void interop_database_add_vndr_prdt(const interop_feature_t feature, - uint16_t vendor_id, uint16_t product_id) { +void interop_database_add_vndr_prdt(const interop_feature_t feature, uint16_t vendor_id, + uint16_t product_id) { inc_func_call_count(__func__); - test::mock::device_interop::interop_database_add_vndr_prdt(feature, vendor_id, - product_id); + test::mock::device_interop::interop_database_add_vndr_prdt(feature, vendor_id, product_id); } void interop_database_clear() { inc_func_call_count(__func__); test::mock::device_interop::interop_database_clear(); } -bool interop_database_match_addr(const interop_feature_t feature, - const RawAddress* addr) { +bool interop_database_match_addr(const interop_feature_t feature, const RawAddress* addr) { inc_func_call_count(__func__); return test::mock::device_interop::interop_database_match_addr(feature, addr); } bool interop_database_match_addr_get_lmp_ver(const interop_feature_t feature, - const RawAddress* addr, - uint8_t* lmp_ver, + const RawAddress* addr, uint8_t* lmp_ver, uint16_t* lmp_sub_ver) { inc_func_call_count(__func__); - return test::mock::device_interop::interop_database_match_addr_get_lmp_ver( - feature, addr, lmp_ver, lmp_sub_ver); + return test::mock::device_interop::interop_database_match_addr_get_lmp_ver(feature, addr, lmp_ver, + lmp_sub_ver); } bool interop_database_match_addr_get_max_lat(const interop_feature_t feature, - const RawAddress* addr, - uint16_t* max_lat) { + const RawAddress* addr, uint16_t* max_lat) { inc_func_call_count(__func__); - return test::mock::device_interop::interop_database_match_addr_get_max_lat( - feature, addr, max_lat); + return test::mock::device_interop::interop_database_match_addr_get_max_lat(feature, addr, + max_lat); } -bool interop_database_match_manufacturer(const interop_feature_t feature, - uint16_t manufacturer) { +bool interop_database_match_manufacturer(const interop_feature_t feature, uint16_t manufacturer) { inc_func_call_count(__func__); - return test::mock::device_interop::interop_database_match_manufacturer( - feature, manufacturer); + return test::mock::device_interop::interop_database_match_manufacturer(feature, manufacturer); } -bool interop_database_match_name(const interop_feature_t feature, - const char* name) { +bool interop_database_match_name(const interop_feature_t feature, const char* name) { inc_func_call_count(__func__); return test::mock::device_interop::interop_database_match_name(feature, name); } -bool interop_database_match_version(const interop_feature_t feature, - uint16_t version) { +bool interop_database_match_version(const interop_feature_t feature, uint16_t version) { inc_func_call_count(__func__); - return test::mock::device_interop::interop_database_match_version(feature, - version); + return test::mock::device_interop::interop_database_match_version(feature, version); } -bool interop_database_match_vndr_prdt(const interop_feature_t feature, - uint16_t vendor_id, uint16_t product_id) { +bool interop_database_match_vndr_prdt(const interop_feature_t feature, uint16_t vendor_id, + uint16_t product_id) { inc_func_call_count(__func__); - return test::mock::device_interop::interop_database_match_vndr_prdt( - feature, vendor_id, product_id); + return test::mock::device_interop::interop_database_match_vndr_prdt(feature, vendor_id, + product_id); } -bool interop_database_remove_addr(const interop_feature_t feature, - const RawAddress* addr) { +bool interop_database_remove_addr(const interop_feature_t feature, const RawAddress* addr) { inc_func_call_count(__func__); - return test::mock::device_interop::interop_database_remove_addr(feature, - addr); + return test::mock::device_interop::interop_database_remove_addr(feature, addr); } bool interop_database_remove_addr_lmp_version(const interop_feature_t feature, - const RawAddress* addr, - uint8_t lmp_ver, + const RawAddress* addr, uint8_t lmp_ver, uint16_t lmp_sub_ver) { inc_func_call_count(__func__); - return test::mock::device_interop::interop_database_remove_addr_lmp_version( - feature, addr, lmp_ver, lmp_sub_ver); + return test::mock::device_interop::interop_database_remove_addr_lmp_version(feature, addr, + lmp_ver, lmp_sub_ver); } -bool interop_database_remove_addr_max_lat(const interop_feature_t feature, - const RawAddress* addr, +bool interop_database_remove_addr_max_lat(const interop_feature_t feature, const RawAddress* addr, uint16_t max_lat) { inc_func_call_count(__func__); - return test::mock::device_interop::interop_database_remove_addr_max_lat( - feature, addr, max_lat); + return test::mock::device_interop::interop_database_remove_addr_max_lat(feature, addr, max_lat); } bool interop_database_remove_feature(const interop_feature_t feature) { inc_func_call_count(__func__); return test::mock::device_interop::interop_database_remove_feature(feature); } -bool interop_database_remove_manufacturer(const interop_feature_t feature, - uint16_t manufacturer) { +bool interop_database_remove_manufacturer(const interop_feature_t feature, uint16_t manufacturer) { inc_func_call_count(__func__); - return test::mock::device_interop::interop_database_remove_manufacturer( - feature, manufacturer); + return test::mock::device_interop::interop_database_remove_manufacturer(feature, manufacturer); } -bool interop_database_remove_name(const interop_feature_t feature, - const char* name) { +bool interop_database_remove_name(const interop_feature_t feature, const char* name) { inc_func_call_count(__func__); - return test::mock::device_interop::interop_database_remove_name(feature, - name); + return test::mock::device_interop::interop_database_remove_name(feature, name); } -bool interop_database_remove_version(const interop_feature_t feature, - uint16_t version) { +bool interop_database_remove_version(const interop_feature_t feature, uint16_t version) { inc_func_call_count(__func__); - return test::mock::device_interop::interop_database_remove_version(feature, - version); + return test::mock::device_interop::interop_database_remove_version(feature, version); } -bool interop_database_remove_vndr_prdt(const interop_feature_t feature, - uint16_t vendor_id, +bool interop_database_remove_vndr_prdt(const interop_feature_t feature, uint16_t vendor_id, uint16_t product_id) { inc_func_call_count(__func__); - return test::mock::device_interop::interop_database_remove_vndr_prdt( - feature, vendor_id, product_id); + return test::mock::device_interop::interop_database_remove_vndr_prdt(feature, vendor_id, + product_id); } int interop_feature_name_to_feature_id(const char* feature_name) { inc_func_call_count(__func__); - return test::mock::device_interop::interop_feature_name_to_feature_id( - feature_name); + return test::mock::device_interop::interop_feature_name_to_feature_id(feature_name); } -bool interop_match_addr(const interop_feature_t feature, - const RawAddress* addr) { +bool interop_match_addr(const interop_feature_t feature, const RawAddress* addr) { inc_func_call_count(__func__); return test::mock::device_interop::interop_match_addr(feature, addr); } -bool interop_match_addr_get_max_lat(const interop_feature_t feature, - const RawAddress* addr, uint16_t* max_lat) { +bool interop_match_addr_get_max_lat(const interop_feature_t feature, const RawAddress* addr, + uint16_t* max_lat) { inc_func_call_count(__func__); - return test::mock::device_interop::interop_match_addr_get_max_lat( - feature, addr, max_lat); + return test::mock::device_interop::interop_match_addr_get_max_lat(feature, addr, max_lat); } -bool interop_match_addr_or_name(const interop_feature_t feature, - const RawAddress* addr, - bt_status_t (*get_remote_device_property)( - const RawAddress*, bt_property_t*)) { +bool interop_match_addr_or_name(const interop_feature_t feature, const RawAddress* addr, + bt_status_t (*get_remote_device_property)(const RawAddress*, + bt_property_t*)) { inc_func_call_count(__func__); - return test::mock::device_interop::interop_match_addr_or_name( - feature, addr, get_remote_device_property); + return test::mock::device_interop::interop_match_addr_or_name(feature, addr, + get_remote_device_property); } -bool interop_match_manufacturer(const interop_feature_t feature, - uint16_t manufacturer) { +bool interop_match_manufacturer(const interop_feature_t feature, uint16_t manufacturer) { inc_func_call_count(__func__); - return test::mock::device_interop::interop_match_manufacturer(feature, - manufacturer); + return test::mock::device_interop::interop_match_manufacturer(feature, manufacturer); } bool interop_match_name(const interop_feature_t feature, const char* name) { inc_func_call_count(__func__); return test::mock::device_interop::interop_match_name(feature, name); } -bool interop_match_vendor_product_ids(const interop_feature_t feature, - uint16_t vendor_id, uint16_t product_id) { +bool interop_match_vendor_product_ids(const interop_feature_t feature, uint16_t vendor_id, + uint16_t product_id) { inc_func_call_count(__func__); - return test::mock::device_interop::interop_match_vendor_product_ids( - feature, vendor_id, product_id); + return test::mock::device_interop::interop_match_vendor_product_ids(feature, vendor_id, + product_id); } bool token_to_ul(char* token, uint16_t* ul) { inc_func_call_count(__func__); diff --git a/system/test/mock/mock_device_interop.h b/system/test/mock/mock_device_interop.h index 3fac5d43da5..ecb08d79fbc 100644 --- a/system/test/mock/mock_device_interop.h +++ b/system/test/mock/mock_device_interop.h @@ -44,14 +44,11 @@ namespace device_interop { // Params: const uint16_t feature, const RawAddress* addr, size_t length // Return: void struct interop_database_add { - std::function - body{[](const uint16_t /* feature */, const RawAddress* /* addr */, - size_t /* length */) {}}; - void operator()(const uint16_t feature, const RawAddress* addr, - size_t length) { + std::function body{ + [](const uint16_t /* feature */, const RawAddress* /* addr */, size_t /* length */) {}}; + void operator()(const uint16_t feature, const RawAddress* addr, size_t length) { body(feature, addr, length); - }; + } }; extern struct interop_database_add interop_database_add; @@ -59,14 +56,11 @@ extern struct interop_database_add interop_database_add; // Params: const uint16_t feature, const RawAddress* addr, size_t length // Return: void struct interop_database_add_addr { - std::function - body{[](const uint16_t /* feature */, const RawAddress* /* addr */, - size_t /* length */) {}}; - void operator()(const uint16_t feature, const RawAddress* addr, - size_t length) { + std::function body{ + [](const uint16_t /* feature */, const RawAddress* /* addr */, size_t /* length */) {}}; + void operator()(const uint16_t feature, const RawAddress* addr, size_t length) { body(feature, addr, length); - }; + } }; extern struct interop_database_add_addr interop_database_add_addr; @@ -74,58 +68,49 @@ extern struct interop_database_add_addr interop_database_add_addr; // Params: const interop_feature_t feature, const RawAddress* addr, uint8_t // lmp_ver, uint16_t lmp_sub_ver Return: void struct interop_database_add_addr_lmp_version { - std::function - body{[](const interop_feature_t /* feature */, - const RawAddress* /* addr */, uint8_t /* lmp_ver */, - uint16_t /* lmp_sub_ver */) {}}; - void operator()(const interop_feature_t feature, const RawAddress* addr, - uint8_t lmp_ver, uint16_t lmp_sub_ver) { + std::function + body{[](const interop_feature_t /* feature */, const RawAddress* /* addr */, + uint8_t /* lmp_ver */, uint16_t /* lmp_sub_ver */) {}}; + void operator()(const interop_feature_t feature, const RawAddress* addr, uint8_t lmp_ver, + uint16_t lmp_sub_ver) { body(feature, addr, lmp_ver, lmp_sub_ver); - }; + } }; -extern struct interop_database_add_addr_lmp_version - interop_database_add_addr_lmp_version; +extern struct interop_database_add_addr_lmp_version interop_database_add_addr_lmp_version; // Name: interop_database_add_addr_max_lat // Params: const interop_feature_t feature, const RawAddress* addr, uint16_t // max_lat Return: void struct interop_database_add_addr_max_lat { - std::function - body{[](const interop_feature_t /* feature */, - const RawAddress* /* addr */, uint16_t /* max_lat */) {}}; - void operator()(const interop_feature_t feature, const RawAddress* addr, - uint16_t max_lat) { + std::function + body{[](const interop_feature_t /* feature */, const RawAddress* /* addr */, + uint16_t /* max_lat */) {}}; + void operator()(const interop_feature_t feature, const RawAddress* addr, uint16_t max_lat) { body(feature, addr, max_lat); - }; + } }; -extern struct interop_database_add_addr_max_lat - interop_database_add_addr_max_lat; +extern struct interop_database_add_addr_max_lat interop_database_add_addr_max_lat; // Name: interop_database_add_manufacturer // Params: const interop_feature_t feature, uint16_t manufacturer // Return: void struct interop_database_add_manufacturer { - std::function - body{[](const interop_feature_t /* feature */, - uint16_t /* manufacturer */) {}}; + std::function body{ + [](const interop_feature_t /* feature */, uint16_t /* manufacturer */) {}}; void operator()(const interop_feature_t feature, uint16_t manufacturer) { body(feature, manufacturer); - }; + } }; -extern struct interop_database_add_manufacturer - interop_database_add_manufacturer; +extern struct interop_database_add_manufacturer interop_database_add_manufacturer; // Name: interop_database_add_name // Params: const uint16_t feature, const char* name // Return: void struct interop_database_add_name { std::function body{ - [](const uint16_t /* feature */, const char* /* name */) {}}; - void operator()(const uint16_t feature, const char* name) { - body(feature, name); - }; + [](const uint16_t /* feature */, const char* /* name */) {}}; + void operator()(const uint16_t feature, const char* name) { body(feature, name); } }; extern struct interop_database_add_name interop_database_add_name; @@ -134,10 +119,8 @@ extern struct interop_database_add_name interop_database_add_name; // Return: void struct interop_database_add_version { std::function body{ - [](const interop_feature_t /* feature */, uint16_t /* version */) {}}; - void operator()(const interop_feature_t feature, uint16_t version) { - body(feature, version); - }; + [](const interop_feature_t /* feature */, uint16_t /* version */) {}}; + void operator()(const interop_feature_t feature, uint16_t version) { body(feature, version); } }; extern struct interop_database_add_version interop_database_add_version; @@ -145,14 +128,12 @@ extern struct interop_database_add_version interop_database_add_version; // Params: const interop_feature_t feature, uint16_t vendor_id, uint16_t // product_id Return: void struct interop_database_add_vndr_prdt { - std::function - body{[](const interop_feature_t /* feature */, uint16_t /* vendor_id */, - uint16_t /* product_id */) {}}; - void operator()(const interop_feature_t feature, uint16_t vendor_id, - uint16_t product_id) { + std::function + body{[](const interop_feature_t /* feature */, uint16_t /* vendor_id */, + uint16_t /* product_id */) {}}; + void operator()(const interop_feature_t feature, uint16_t vendor_id, uint16_t product_id) { body(feature, vendor_id, product_id); - }; + } }; extern struct interop_database_add_vndr_prdt interop_database_add_vndr_prdt; @@ -161,7 +142,7 @@ extern struct interop_database_add_vndr_prdt interop_database_add_vndr_prdt; // Return: void struct interop_database_clear { std::function body{[]() {}}; - void operator()() { body(); }; + void operator()() { body(); } }; extern struct interop_database_clear interop_database_clear; @@ -170,12 +151,13 @@ extern struct interop_database_clear interop_database_clear; // Return: bool struct interop_database_match_addr { static bool return_value; - std::function - body{[](const interop_feature_t /* feature */, - const RawAddress* /* addr */) { return return_value; }}; + std::function body{ + [](const interop_feature_t /* feature */, const RawAddress* /* addr */) { + return return_value; + }}; bool operator()(const interop_feature_t feature, const RawAddress* addr) { return body(feature, addr); - }; + } }; extern struct interop_database_match_addr interop_database_match_addr; @@ -184,51 +166,45 @@ extern struct interop_database_match_addr interop_database_match_addr; // lmp_ver, uint16_t* lmp_sub_ver Return: bool struct interop_database_match_addr_get_lmp_ver { static bool return_value; - std::function - body{[](const interop_feature_t /* feature */, - const RawAddress* /* addr */, uint8_t* /* lmp_ver */, - uint16_t* /* lmp_sub_ver */) { return return_value; }}; - bool operator()(const interop_feature_t feature, const RawAddress* addr, - uint8_t* lmp_ver, uint16_t* lmp_sub_ver) { + std::function + body{[](const interop_feature_t /* feature */, const RawAddress* /* addr */, + uint8_t* /* lmp_ver */, uint16_t* /* lmp_sub_ver */) { return return_value; }}; + bool operator()(const interop_feature_t feature, const RawAddress* addr, uint8_t* lmp_ver, + uint16_t* lmp_sub_ver) { return body(feature, addr, lmp_ver, lmp_sub_ver); - }; + } }; -extern struct interop_database_match_addr_get_lmp_ver - interop_database_match_addr_get_lmp_ver; +extern struct interop_database_match_addr_get_lmp_ver interop_database_match_addr_get_lmp_ver; // Name: interop_database_match_addr_get_max_lat // Params: const interop_feature_t feature, const RawAddress* addr, uint16_t* // max_lat Return: bool struct interop_database_match_addr_get_max_lat { static bool return_value; - std::function - body{[](const interop_feature_t /* feature */, - const RawAddress* /* addr */, - uint16_t* /* max_lat */) { return return_value; }}; - bool operator()(const interop_feature_t feature, const RawAddress* addr, - uint16_t* max_lat) { + std::function + body{[](const interop_feature_t /* feature */, const RawAddress* /* addr */, + uint16_t* /* max_lat */) { return return_value; }}; + bool operator()(const interop_feature_t feature, const RawAddress* addr, uint16_t* max_lat) { return body(feature, addr, max_lat); - }; + } }; -extern struct interop_database_match_addr_get_max_lat - interop_database_match_addr_get_max_lat; +extern struct interop_database_match_addr_get_max_lat interop_database_match_addr_get_max_lat; // Name: interop_database_match_manufacturer // Params: const interop_feature_t feature, uint16_t manufacturer // Return: bool struct interop_database_match_manufacturer { static bool return_value; - std::function - body{[](const interop_feature_t /* feature */, - uint16_t /* manufacturer */) { return return_value; }}; + std::function body{ + [](const interop_feature_t /* feature */, uint16_t /* manufacturer */) { + return return_value; + }}; bool operator()(const interop_feature_t feature, uint16_t manufacturer) { return body(feature, manufacturer); - }; + } }; -extern struct interop_database_match_manufacturer - interop_database_match_manufacturer; +extern struct interop_database_match_manufacturer interop_database_match_manufacturer; // Name: interop_database_match_name // Params: const interop_feature_t feature, const char* name @@ -236,12 +212,10 @@ extern struct interop_database_match_manufacturer struct interop_database_match_name { static bool return_value; std::function body{ - [](const interop_feature_t /* feature */, const char* /* name */) { - return return_value; - }}; - bool operator()(const interop_feature_t feature, const char* name) { - return body(feature, name); - }; + [](const interop_feature_t /* feature */, const char* /* name */) { + return return_value; + }}; + bool operator()(const interop_feature_t feature, const char* name) { return body(feature, name); } }; extern struct interop_database_match_name interop_database_match_name; @@ -251,12 +225,12 @@ extern struct interop_database_match_name interop_database_match_name; struct interop_database_match_version { static bool return_value; std::function body{ - [](const interop_feature_t /* feature */, uint16_t /* version */) { - return return_value; - }}; + [](const interop_feature_t /* feature */, uint16_t /* version */) { + return return_value; + }}; bool operator()(const interop_feature_t feature, uint16_t version) { return body(feature, version); - }; + } }; extern struct interop_database_match_version interop_database_match_version; @@ -265,14 +239,12 @@ extern struct interop_database_match_version interop_database_match_version; // product_id Return: bool struct interop_database_match_vndr_prdt { static bool return_value; - std::function - body{[](const interop_feature_t /* feature */, uint16_t /* vendor_id */, - uint16_t /* product_id */) { return return_value; }}; - bool operator()(const interop_feature_t feature, uint16_t vendor_id, - uint16_t product_id) { + std::function + body{[](const interop_feature_t /* feature */, uint16_t /* vendor_id */, + uint16_t /* product_id */) { return return_value; }}; + bool operator()(const interop_feature_t feature, uint16_t vendor_id, uint16_t product_id) { return body(feature, vendor_id, product_id); - }; + } }; extern struct interop_database_match_vndr_prdt interop_database_match_vndr_prdt; @@ -281,12 +253,13 @@ extern struct interop_database_match_vndr_prdt interop_database_match_vndr_prdt; // Return: bool struct interop_database_remove_addr { static bool return_value; - std::function - body{[](const interop_feature_t /* feature */, - const RawAddress* /* addr */) { return return_value; }}; + std::function body{ + [](const interop_feature_t /* feature */, const RawAddress* /* addr */) { + return return_value; + }}; bool operator()(const interop_feature_t feature, const RawAddress* addr) { return body(feature, addr); - }; + } }; extern struct interop_database_remove_addr interop_database_remove_addr; @@ -295,36 +268,30 @@ extern struct interop_database_remove_addr interop_database_remove_addr; // lmp_ver, uint16_t lmp_sub_ver Return: bool struct interop_database_remove_addr_lmp_version { static bool return_value; - std::function - body{[](const interop_feature_t /* feature */, - const RawAddress* /* addr */, uint8_t /* lmp_ver */, - uint16_t /* lmp_sub_ver */) { return return_value; }}; - bool operator()(const interop_feature_t feature, const RawAddress* addr, - uint8_t lmp_ver, uint16_t lmp_sub_ver) { + std::function + body{[](const interop_feature_t /* feature */, const RawAddress* /* addr */, + uint8_t /* lmp_ver */, uint16_t /* lmp_sub_ver */) { return return_value; }}; + bool operator()(const interop_feature_t feature, const RawAddress* addr, uint8_t lmp_ver, + uint16_t lmp_sub_ver) { return body(feature, addr, lmp_ver, lmp_sub_ver); - }; + } }; -extern struct interop_database_remove_addr_lmp_version - interop_database_remove_addr_lmp_version; +extern struct interop_database_remove_addr_lmp_version interop_database_remove_addr_lmp_version; // Name: interop_database_remove_addr_max_lat // Params: const interop_feature_t feature, const RawAddress* addr, uint16_t // max_lat Return: bool struct interop_database_remove_addr_max_lat { static bool return_value; - std::function - body{[](const interop_feature_t /* feature */, - const RawAddress* /* addr */, - uint16_t /* max_lat */) { return return_value; }}; - bool operator()(const interop_feature_t feature, const RawAddress* addr, - uint16_t max_lat) { + std::function + body{[](const interop_feature_t /* feature */, const RawAddress* /* addr */, + uint16_t /* max_lat */) { return return_value; }}; + bool operator()(const interop_feature_t feature, const RawAddress* addr, uint16_t max_lat) { return body(feature, addr, max_lat); - }; + } }; -extern struct interop_database_remove_addr_max_lat - interop_database_remove_addr_max_lat; +extern struct interop_database_remove_addr_max_lat interop_database_remove_addr_max_lat; // Name: interop_database_remove_feature // Params: const interop_feature_t feature @@ -332,8 +299,8 @@ extern struct interop_database_remove_addr_max_lat struct interop_database_remove_feature { static bool return_value; std::function body{ - [](const interop_feature_t /* feature */) { return return_value; }}; - bool operator()(const interop_feature_t feature) { return body(feature); }; + [](const interop_feature_t /* feature */) { return return_value; }}; + bool operator()(const interop_feature_t feature) { return body(feature); } }; extern struct interop_database_remove_feature interop_database_remove_feature; @@ -342,15 +309,15 @@ extern struct interop_database_remove_feature interop_database_remove_feature; // Return: bool struct interop_database_remove_manufacturer { static bool return_value; - std::function - body{[](const interop_feature_t /* feature */, - uint16_t /* manufacturer */) { return return_value; }}; + std::function body{ + [](const interop_feature_t /* feature */, uint16_t /* manufacturer */) { + return return_value; + }}; bool operator()(const interop_feature_t feature, uint16_t manufacturer) { return body(feature, manufacturer); - }; + } }; -extern struct interop_database_remove_manufacturer - interop_database_remove_manufacturer; +extern struct interop_database_remove_manufacturer interop_database_remove_manufacturer; // Name: interop_database_remove_name // Params: const interop_feature_t feature, const char* name @@ -358,12 +325,10 @@ extern struct interop_database_remove_manufacturer struct interop_database_remove_name { static bool return_value; std::function body{ - [](const interop_feature_t /* feature */, const char* /* name */) { - return return_value; - }}; - bool operator()(const interop_feature_t feature, const char* name) { - return body(feature, name); - }; + [](const interop_feature_t /* feature */, const char* /* name */) { + return return_value; + }}; + bool operator()(const interop_feature_t feature, const char* name) { return body(feature, name); } }; extern struct interop_database_remove_name interop_database_remove_name; @@ -373,12 +338,12 @@ extern struct interop_database_remove_name interop_database_remove_name; struct interop_database_remove_version { static bool return_value; std::function body{ - [](const interop_feature_t /* feature */, uint16_t /* version */) { - return return_value; - }}; + [](const interop_feature_t /* feature */, uint16_t /* version */) { + return return_value; + }}; bool operator()(const interop_feature_t feature, uint16_t version) { return body(feature, version); - }; + } }; extern struct interop_database_remove_version interop_database_remove_version; @@ -387,17 +352,14 @@ extern struct interop_database_remove_version interop_database_remove_version; // product_id Return: bool struct interop_database_remove_vndr_prdt { static bool return_value; - std::function - body{[](const interop_feature_t /* feature */, uint16_t /* vendor_id */, - uint16_t /* product_id */) { return return_value; }}; - bool operator()(const interop_feature_t feature, uint16_t vendor_id, - uint16_t product_id) { + std::function + body{[](const interop_feature_t /* feature */, uint16_t /* vendor_id */, + uint16_t /* product_id */) { return return_value; }}; + bool operator()(const interop_feature_t feature, uint16_t vendor_id, uint16_t product_id) { return body(feature, vendor_id, product_id); - }; + } }; -extern struct interop_database_remove_vndr_prdt - interop_database_remove_vndr_prdt; +extern struct interop_database_remove_vndr_prdt interop_database_remove_vndr_prdt; // Name: interop_feature_name_to_feature_id // Params: const char* feature_name @@ -405,23 +367,23 @@ extern struct interop_database_remove_vndr_prdt struct interop_feature_name_to_feature_id { static int return_value; std::function body{ - [](const char* /* feature_name */) { return return_value; }}; - int operator()(const char* feature_name) { return body(feature_name); }; + [](const char* /* feature_name */) { return return_value; }}; + int operator()(const char* feature_name) { return body(feature_name); } }; -extern struct interop_feature_name_to_feature_id - interop_feature_name_to_feature_id; +extern struct interop_feature_name_to_feature_id interop_feature_name_to_feature_id; // Name: interop_match_addr // Params: const interop_feature_t feature, const RawAddress* addr // Return: bool struct interop_match_addr { static bool return_value; - std::function - body{[](const interop_feature_t /* feature */, - const RawAddress* /* addr */) { return return_value; }}; + std::function body{ + [](const interop_feature_t /* feature */, const RawAddress* /* addr */) { + return return_value; + }}; bool operator()(const interop_feature_t feature, const RawAddress* addr) { return body(feature, addr); - }; + } }; extern struct interop_match_addr interop_match_addr; @@ -430,15 +392,12 @@ extern struct interop_match_addr interop_match_addr; // max_lat Return: bool struct interop_match_addr_get_max_lat { static bool return_value; - std::function - body{[](const interop_feature_t /* feature */, - const RawAddress* /* addr */, - uint16_t* /* max_lat */) { return return_value; }}; - bool operator()(const interop_feature_t feature, const RawAddress* addr, - uint16_t* max_lat) { + std::function + body{[](const interop_feature_t /* feature */, const RawAddress* /* addr */, + uint16_t* /* max_lat */) { return return_value; }}; + bool operator()(const interop_feature_t feature, const RawAddress* addr, uint16_t* max_lat) { return body(feature, addr, max_lat); - }; + } }; extern struct interop_match_addr_get_max_lat interop_match_addr_get_max_lat; @@ -448,17 +407,14 @@ extern struct interop_match_addr_get_max_lat interop_match_addr_get_max_lat; struct interop_match_addr_or_name { static bool return_value; std::function - body{[](const interop_feature_t /* feature */, - const RawAddress* /* addr */, - bt_status_t (* /* get_remote_device_property */)( - const RawAddress*, bt_property_t*)) { return return_value; }}; + bt_status_t (*get_remote_device_property)(const RawAddress*, bt_property_t*))> + body{[](const interop_feature_t /* feature */, const RawAddress* /* addr */, + bt_status_t (* /* get_remote_device_property */)( + const RawAddress*, bt_property_t*)) { return return_value; }}; bool operator()(const interop_feature_t feature, const RawAddress* addr, - bt_status_t (*get_remote_device_property)(const RawAddress*, - bt_property_t*)) { + bt_status_t (*get_remote_device_property)(const RawAddress*, bt_property_t*)) { return body(feature, addr, get_remote_device_property); - }; + } }; extern struct interop_match_addr_or_name interop_match_addr_or_name; @@ -467,12 +423,13 @@ extern struct interop_match_addr_or_name interop_match_addr_or_name; // Return: bool struct interop_match_manufacturer { static bool return_value; - std::function - body{[](const interop_feature_t /* feature */, - uint16_t /* manufacturer */) { return return_value; }}; + std::function body{ + [](const interop_feature_t /* feature */, uint16_t /* manufacturer */) { + return return_value; + }}; bool operator()(const interop_feature_t feature, uint16_t manufacturer) { return body(feature, manufacturer); - }; + } }; extern struct interop_match_manufacturer interop_match_manufacturer; @@ -482,12 +439,10 @@ extern struct interop_match_manufacturer interop_match_manufacturer; struct interop_match_name { static bool return_value; std::function body{ - [](const interop_feature_t /* feature */, const char* /* name */) { - return return_value; - }}; - bool operator()(const interop_feature_t feature, const char* name) { - return body(feature, name); - }; + [](const interop_feature_t /* feature */, const char* /* name */) { + return return_value; + }}; + bool operator()(const interop_feature_t feature, const char* name) { return body(feature, name); } }; extern struct interop_match_name interop_match_name; @@ -496,14 +451,12 @@ extern struct interop_match_name interop_match_name; // product_id Return: bool struct interop_match_vendor_product_ids { static bool return_value; - std::function - body{[](const interop_feature_t /* feature */, uint16_t /* vendor_id */, - uint16_t /* product_id */) { return return_value; }}; - bool operator()(const interop_feature_t feature, uint16_t vendor_id, - uint16_t product_id) { + std::function + body{[](const interop_feature_t /* feature */, uint16_t /* vendor_id */, + uint16_t /* product_id */) { return return_value; }}; + bool operator()(const interop_feature_t feature, uint16_t vendor_id, uint16_t product_id) { return body(feature, vendor_id, product_id); - }; + } }; extern struct interop_match_vendor_product_ids interop_match_vendor_product_ids; @@ -513,8 +466,8 @@ extern struct interop_match_vendor_product_ids interop_match_vendor_product_ids; struct token_to_ul { static bool return_value; std::function body{ - [](char* /* token */, uint16_t* /* ul */) { return return_value; }}; - bool operator()(char* token, uint16_t* ul) { return body(token, ul); }; + [](char* /* token */, uint16_t* /* ul */) { return return_value; }}; + bool operator()(char* token, uint16_t* ul) { return body(token, ul); } }; extern struct token_to_ul token_to_ul; diff --git a/system/test/mock/mock_device_iot_config.cc b/system/test/mock/mock_device_iot_config.cc index decabeecbbb..6188e58c8d6 100644 --- a/system/test/mock/mock_device_iot_config.cc +++ b/system/test/mock/mock_device_iot_config.cc @@ -48,72 +48,64 @@ struct device_debug_iot_config_dump device_debug_iot_config_dump; } // namespace test // Mocked functions, if any -bool device_iot_config_get_int(const std::string& section, const std::string& key, - int& value) { +bool device_iot_config_get_int(const std::string& section, const std::string& key, int& value) { inc_func_call_count(__func__); return test::mock::device_iot_config::device_iot_config_get_int(section, key, value); } -bool device_iot_config_set_int(const std::string& section, - const std::string& key, int value) { +bool device_iot_config_set_int(const std::string& section, const std::string& key, int value) { inc_func_call_count(__func__); return test::mock::device_iot_config::device_iot_config_set_int(section, key, value); } -bool device_iot_config_int_add_one(const std::string& section, - const std::string& key) { +bool device_iot_config_int_add_one(const std::string& section, const std::string& key) { inc_func_call_count(__func__); return test::mock::device_iot_config::device_iot_config_int_add_one(section, key); } -bool device_iot_config_get_hex(const std::string& section, - const std::string& key, int& value) { +bool device_iot_config_get_hex(const std::string& section, const std::string& key, int& value) { inc_func_call_count(__func__); return test::mock::device_iot_config::device_iot_config_get_hex(section, key, value); } -bool device_iot_config_set_hex(const std::string& section, - const std::string& key, int value, int byte_num) { +bool device_iot_config_set_hex(const std::string& section, const std::string& key, int value, + int byte_num) { inc_func_call_count(__func__); return test::mock::device_iot_config::device_iot_config_set_hex(section, key, value, byte_num); } -bool device_iot_config_set_hex_if_greater(const std::string& section, - const std::string& key, int value, int byte_num) { +bool device_iot_config_set_hex_if_greater(const std::string& section, const std::string& key, + int value, int byte_num) { inc_func_call_count(__func__); - return test::mock::device_iot_config::device_iot_config_set_hex_if_greater(section, key, value, byte_num); + return test::mock::device_iot_config::device_iot_config_set_hex_if_greater(section, key, value, + byte_num); } -bool device_iot_config_get_str(const std::string& section, - const std::string& key, char* value, +bool device_iot_config_get_str(const std::string& section, const std::string& key, char* value, int* size_bytes) { inc_func_call_count(__func__); return test::mock::device_iot_config::device_iot_config_get_str(section, key, value, size_bytes); } -bool device_iot_config_set_str(const std::string& section, - const std::string& key, +bool device_iot_config_set_str(const std::string& section, const std::string& key, const std::string& value) { inc_func_call_count(__func__); return test::mock::device_iot_config::device_iot_config_set_str(section, key, value); } -bool device_iot_config_get_bin(const std::string& section, - const std::string& key, uint8_t* value, +bool device_iot_config_get_bin(const std::string& section, const std::string& key, uint8_t* value, size_t* length) { inc_func_call_count(__func__); return test::mock::device_iot_config::device_iot_config_get_bin(section, key, value, length); } -bool device_iot_config_set_bin(const std::string& section, - const std::string& key, const uint8_t* value, - size_t length) { +bool device_iot_config_set_bin(const std::string& section, const std::string& key, + const uint8_t* value, size_t length) { inc_func_call_count(__func__); return test::mock::device_iot_config::device_iot_config_set_bin(section, key, value, length); } -size_t device_iot_config_get_bin_length(const std::string& section, - const std::string& key) { +size_t device_iot_config_get_bin_length(const std::string& section, const std::string& key) { inc_func_call_count(__func__); return test::mock::device_iot_config::device_iot_config_get_bin_length(section, key); } @@ -123,14 +115,12 @@ bool device_iot_config_has_section(const std::string& section) { return test::mock::device_iot_config::device_iot_config_has_section(section); } -bool device_iot_config_exist(const std::string& section, - const std::string& key) { +bool device_iot_config_exist(const std::string& section, const std::string& key) { inc_func_call_count(__func__); return test::mock::device_iot_config::device_iot_config_exist(section, key); } -bool device_iot_config_remove(const std::string& section, - const std::string& key) { +bool device_iot_config_remove(const std::string& section, const std::string& key) { inc_func_call_count(__func__); return test::mock::device_iot_config::device_iot_config_remove(section, key); } diff --git a/system/test/mock/mock_device_iot_config.h b/system/test/mock/mock_device_iot_config.h index cb750a3362f..43c7af6856e 100644 --- a/system/test/mock/mock_device_iot_config.h +++ b/system/test/mock/mock_device_iot_config.h @@ -27,15 +27,13 @@ namespace device_iot_config { // Return: bool struct device_iot_config_get_int { bool return_value{false}; - std::function - body{[this](const std::string& /* section */, - const std::string& /* key */, - int& /* value */) { return return_value; }}; - bool operator()(const std::string& section, const std::string& key, - int& value) { + std::function body{ + [this](const std::string& /* section */, const std::string& /* key */, int& /* value */) { + return return_value; + }}; + bool operator()(const std::string& section, const std::string& key, int& value) { return body(section, key, value); - }; + } }; extern struct device_iot_config_get_int device_iot_config_get_int; @@ -44,15 +42,13 @@ extern struct device_iot_config_get_int device_iot_config_get_int; // Return: bool struct device_iot_config_set_int { bool return_value{false}; - std::function - body{[this](const std::string& /* section */, - const std::string& /* key */, - int /* value */) { return return_value; }}; - bool operator()(const std::string& section, const std::string& key, - int value) { + std::function body{ + [this](const std::string& /* section */, const std::string& /* key */, int /* value */) { + return return_value; + }}; + bool operator()(const std::string& section, const std::string& key, int value) { return body(section, key, value); - }; + } }; extern struct device_iot_config_set_int device_iot_config_set_int; @@ -62,12 +58,10 @@ extern struct device_iot_config_set_int device_iot_config_set_int; struct device_iot_config_int_add_one { bool return_value{false}; std::function body{ - [this](const std::string& /* section */, const std::string& /* key */) { - return return_value; - }}; - bool operator()(const std::string& section, const std::string& key) { - return body(section, key); - }; + [this](const std::string& /* section */, const std::string& /* key */) { + return return_value; + }}; + bool operator()(const std::string& section, const std::string& key) { return body(section, key); } }; extern struct device_iot_config_int_add_one device_iot_config_int_add_one; @@ -76,15 +70,13 @@ extern struct device_iot_config_int_add_one device_iot_config_int_add_one; // Return: bool struct device_iot_config_get_hex { bool return_value{false}; - std::function - body{[this](const std::string& /* section */, - const std::string& /* key */, - int& /* value */) { return return_value; }}; - bool operator()(const std::string& section, const std::string& key, - int& value) { + std::function body{ + [this](const std::string& /* section */, const std::string& /* key */, int& /* value */) { + return return_value; + }}; + bool operator()(const std::string& section, const std::string& key, int& value) { return body(section, key, value); - }; + } }; extern struct device_iot_config_get_hex device_iot_config_get_hex; @@ -94,15 +86,12 @@ extern struct device_iot_config_get_hex device_iot_config_get_hex; // Return: bool struct device_iot_config_set_hex { bool return_value{false}; - std::function - body{[this](const std::string& /* section */, - const std::string& /* key */, int /* value */, - int /* byte_num */) { return return_value; }}; - bool operator()(const std::string& section, const std::string& key, int value, - int byte_num) { + std::function + body{[this](const std::string& /* section */, const std::string& /* key */, + int /* value */, int /* byte_num */) { return return_value; }}; + bool operator()(const std::string& section, const std::string& key, int value, int byte_num) { return body(section, key, value, byte_num); - }; + } }; extern struct device_iot_config_set_hex device_iot_config_set_hex; @@ -112,18 +101,14 @@ extern struct device_iot_config_set_hex device_iot_config_set_hex; // Return: bool struct device_iot_config_set_hex_if_greater { bool return_value{false}; - std::function - body{[this](const std::string& /* section */, - const std::string& /* key */, int /* value */, - int /* byte_num */) { return return_value; }}; - bool operator()(const std::string& section, const std::string& key, int value, - int byte_num) { + std::function + body{[this](const std::string& /* section */, const std::string& /* key */, + int /* value */, int /* byte_num */) { return return_value; }}; + bool operator()(const std::string& section, const std::string& key, int value, int byte_num) { return body(section, key, value, byte_num); - }; + } }; -extern struct device_iot_config_set_hex_if_greater - device_iot_config_set_hex_if_greater; +extern struct device_iot_config_set_hex_if_greater device_iot_config_set_hex_if_greater; // Name: device_iot_config_get_str // Params: const std::string& section, const std::string& key, char* value, int* @@ -131,15 +116,14 @@ extern struct device_iot_config_set_hex_if_greater // Return: bool struct device_iot_config_get_str { bool return_value{false}; - std::function - body{[this](const std::string& /* section */, - const std::string& /* key */, char* /* value */, - int* /* size_bytes */) { return return_value; }}; - bool operator()(const std::string& section, const std::string& key, - char* value, int* size_bytes) { + std::function + body{[this](const std::string& /* section */, const std::string& /* key */, + char* /* value */, int* /* size_bytes */) { return return_value; }}; + bool operator()(const std::string& section, const std::string& key, char* value, + int* size_bytes) { return body(section, key, value, size_bytes); - }; + } }; extern struct device_iot_config_get_str device_iot_config_get_str; @@ -149,15 +133,12 @@ extern struct device_iot_config_get_str device_iot_config_get_str; // Return: bool struct device_iot_config_set_str { bool return_value{false}; - std::function - body{[this](const std::string& /* section */, - const std::string& /* key */, - const std::string& /* value */) { return return_value; }}; - bool operator()(const std::string& section, const std::string& key, - const std::string& value) { + std::function + body{[this](const std::string& /* section */, const std::string& /* key */, + const std::string& /* value */) { return return_value; }}; + bool operator()(const std::string& section, const std::string& key, const std::string& value) { return body(section, key, value); - }; + } }; extern struct device_iot_config_set_str device_iot_config_set_str; @@ -167,15 +148,14 @@ extern struct device_iot_config_set_str device_iot_config_set_str; // Return: bool struct device_iot_config_get_bin { bool return_value{false}; - std::function - body{[this](const std::string& /* section */, - const std::string& /* key */, uint8_t* /* value */, - size_t* /* length */) { return return_value; }}; - bool operator()(const std::string& section, const std::string& key, - uint8_t* value, size_t* length) { + std::function + body{[this](const std::string& /* section */, const std::string& /* key */, + uint8_t* /* value */, size_t* /* length */) { return return_value; }}; + bool operator()(const std::string& section, const std::string& key, uint8_t* value, + size_t* length) { return body(section, key, value, length); - }; + } }; extern struct device_iot_config_get_bin device_iot_config_get_bin; @@ -185,15 +165,14 @@ extern struct device_iot_config_get_bin device_iot_config_get_bin; // Return: bool struct device_iot_config_set_bin { bool return_value{false}; - std::function - body{[this](const std::string& /* section */, - const std::string& /* key */, const uint8_t* /* value */, - size_t /* length */) { return return_value; }}; - bool operator()(const std::string& section, const std::string& key, - const uint8_t* value, size_t length) { + std::function + body{[this](const std::string& /* section */, const std::string& /* key */, + const uint8_t* /* value */, size_t /* length */) { return return_value; }}; + bool operator()(const std::string& section, const std::string& key, const uint8_t* value, + size_t length) { return body(section, key, value, length); - }; + } }; extern struct device_iot_config_set_bin device_iot_config_set_bin; @@ -202,12 +181,13 @@ extern struct device_iot_config_set_bin device_iot_config_set_bin; // Return: size_t struct device_iot_config_get_bin_length { size_t return_value{0}; - std::function - body{[this](const std::string& /* section */, - const std::string& /* key */) { return return_value; }}; + std::function body{ + [this](const std::string& /* section */, const std::string& /* key */) { + return return_value; + }}; size_t operator()(const std::string& section, const std::string& key) { return body(section, key); - }; + } }; extern struct device_iot_config_get_bin_length device_iot_config_get_bin_length; @@ -217,8 +197,8 @@ extern struct device_iot_config_get_bin_length device_iot_config_get_bin_length; struct device_iot_config_has_section { bool return_value{false}; std::function body{ - [this](const std::string& /* section */) { return return_value; }}; - bool operator()(const std::string& section) { return body(section); }; + [this](const std::string& /* section */) { return return_value; }}; + bool operator()(const std::string& section) { return body(section); } }; extern struct device_iot_config_has_section device_iot_config_has_section; @@ -228,12 +208,10 @@ extern struct device_iot_config_has_section device_iot_config_has_section; struct device_iot_config_exist { bool return_value{false}; std::function body{ - [this](const std::string& /* section */, const std::string& /* key */) { - return return_value; - }}; - bool operator()(const std::string& section, const std::string& key) { - return body(section, key); - }; + [this](const std::string& /* section */, const std::string& /* key */) { + return return_value; + }}; + bool operator()(const std::string& section, const std::string& key) { return body(section, key); } }; extern struct device_iot_config_exist device_iot_config_exist; @@ -243,12 +221,10 @@ extern struct device_iot_config_exist device_iot_config_exist; struct device_iot_config_remove { bool return_value{false}; std::function body{ - [this](const std::string& /* section */, const std::string& /* key */) { - return return_value; - }}; - bool operator()(const std::string& section, const std::string& key) { - return body(section, key); - }; + [this](const std::string& /* section */, const std::string& /* key */) { + return return_value; + }}; + bool operator()(const std::string& section, const std::string& key) { return body(section, key); } }; extern struct device_iot_config_remove device_iot_config_remove; @@ -258,7 +234,7 @@ extern struct device_iot_config_remove device_iot_config_remove; struct device_iot_config_clear { bool return_value{false}; std::function body{[this]() { return return_value; }}; - bool operator()(void) { return body(); }; + bool operator()(void) { return body(); } }; extern struct device_iot_config_clear device_iot_config_clear; @@ -267,7 +243,7 @@ extern struct device_iot_config_clear device_iot_config_clear; // Return: void struct device_iot_config_flush { std::function body{[]() {}}; - void operator()(void){ body(); }; + void operator()(void) { body(); } }; extern struct device_iot_config_flush device_iot_config_flush; @@ -276,7 +252,7 @@ extern struct device_iot_config_flush device_iot_config_flush; // Return: void struct device_debug_iot_config_dump { std::function body{[](int /* fd */) {}}; - void operator()(int fd) { body(fd); }; + void operator()(int fd) { body(fd); } }; extern struct device_debug_iot_config_dump device_debug_iot_config_dump; diff --git a/system/test/mock/mock_frameworks_libaudio.cc b/system/test/mock/mock_frameworks_libaudio.cc index ac00199214f..230658d74da 100644 --- a/system/test/mock/mock_frameworks_libaudio.cc +++ b/system/test/mock/mock_frameworks_libaudio.cc @@ -28,8 +28,7 @@ #include #include -aaudio_allowed_capture_policy_t AAudioStream_getAllowedCapturePolicy( - AAudioStream* stream) { +aaudio_allowed_capture_policy_t AAudioStream_getAllowedCapturePolicy(AAudioStream* stream) { inc_func_call_count(__func__); return 0; } @@ -49,8 +48,7 @@ aaudio_input_preset_t AAudioStream_getInputPreset(AAudioStream* stream) { inc_func_call_count(__func__); return 0; } -aaudio_performance_mode_t AAudioStream_getPerformanceMode( - AAudioStream* stream) { +aaudio_performance_mode_t AAudioStream_getPerformanceMode(AAudioStream* stream) { inc_func_call_count(__func__); return 0; } @@ -71,15 +69,12 @@ aaudio_result_t AAudioStream_close(AAudioStream* stream) { inc_func_call_count(__func__); return 0; } -aaudio_result_t AAudioStream_getTimestamp(AAudioStream* stream, - clockid_t clockid, - int64_t* framePosition, - int64_t* timeNanoseconds) { +aaudio_result_t AAudioStream_getTimestamp(AAudioStream* stream, clockid_t clockid, + int64_t* framePosition, int64_t* timeNanoseconds) { inc_func_call_count(__func__); return 0; } -aaudio_result_t AAudioStream_read(AAudioStream* stream, void* buffer, - int32_t numFrames, +aaudio_result_t AAudioStream_read(AAudioStream* stream, void* buffer, int32_t numFrames, int64_t timeoutNanoseconds) { inc_func_call_count(__func__); return 0; @@ -104,19 +99,18 @@ aaudio_result_t AAudioStream_requestStop(AAudioStream* stream) { inc_func_call_count(__func__); return 0; } -aaudio_result_t AAudioStream_setBufferSizeInFrames(AAudioStream* stream, - int32_t requestedFrames) { +aaudio_result_t AAudioStream_setBufferSizeInFrames(AAudioStream* stream, int32_t requestedFrames) { inc_func_call_count(__func__); return 0; } -aaudio_result_t AAudioStream_waitForStateChange( - AAudioStream* stream, aaudio_stream_state_t inputState, - aaudio_stream_state_t* nextState, int64_t timeoutNanoseconds) { +aaudio_result_t AAudioStream_waitForStateChange(AAudioStream* stream, + aaudio_stream_state_t inputState, + aaudio_stream_state_t* nextState, + int64_t timeoutNanoseconds) { inc_func_call_count(__func__); return 0; } -aaudio_result_t AAudioStream_write(AAudioStream* stream, const void* buffer, - int32_t numFrames, +aaudio_result_t AAudioStream_write(AAudioStream* stream, const void* buffer, int32_t numFrames, int64_t timeoutNanoseconds) { inc_func_call_count(__func__); return 0; @@ -205,18 +199,16 @@ int64_t AAudioStream_getFramesWritten(AAudioStream* stream) { inc_func_call_count(__func__); return 0; } -void AAudioStreamBuilder_setAllowedCapturePolicy( - AAudioStreamBuilder* builder, aaudio_allowed_capture_policy_t policy) { +void AAudioStreamBuilder_setAllowedCapturePolicy(AAudioStreamBuilder* builder, + aaudio_allowed_capture_policy_t policy) { inc_func_call_count(__func__); return; } -void AAudioStreamBuilder_setBufferCapacityInFrames(AAudioStreamBuilder* builder, - int32_t frames) { +void AAudioStreamBuilder_setBufferCapacityInFrames(AAudioStreamBuilder* builder, int32_t frames) { inc_func_call_count(__func__); return; } -void AAudioStreamBuilder_setChannelCount(AAudioStreamBuilder* builder, - int32_t channelCount) { +void AAudioStreamBuilder_setChannelCount(AAudioStreamBuilder* builder, int32_t channelCount) { inc_func_call_count(__func__); return; } @@ -226,34 +218,28 @@ void AAudioStreamBuilder_setContentType(AAudioStreamBuilder* builder, return; } void AAudioStreamBuilder_setDataCallback(AAudioStreamBuilder* builder, - AAudioStream_dataCallback callback, - void* userData) { + AAudioStream_dataCallback callback, void* userData) { inc_func_call_count(__func__); return; } -void AAudioStreamBuilder_setDeviceId(AAudioStreamBuilder* builder, - int32_t deviceId) { +void AAudioStreamBuilder_setDeviceId(AAudioStreamBuilder* builder, int32_t deviceId) { inc_func_call_count(__func__); return; } -void AAudioStreamBuilder_setDirection(AAudioStreamBuilder* builder, - aaudio_direction_t direction) { +void AAudioStreamBuilder_setDirection(AAudioStreamBuilder* builder, aaudio_direction_t direction) { inc_func_call_count(__func__); return; } void AAudioStreamBuilder_setErrorCallback(AAudioStreamBuilder* builder, - AAudioStream_errorCallback callback, - void* userData) { + AAudioStream_errorCallback callback, void* userData) { inc_func_call_count(__func__); return; } -void AAudioStreamBuilder_setFormat(AAudioStreamBuilder* builder, - aaudio_format_t format) { +void AAudioStreamBuilder_setFormat(AAudioStreamBuilder* builder, aaudio_format_t format) { inc_func_call_count(__func__); return; } -void AAudioStreamBuilder_setFramesPerDataCallback(AAudioStreamBuilder* builder, - int32_t frames) { +void AAudioStreamBuilder_setFramesPerDataCallback(AAudioStreamBuilder* builder, int32_t frames) { inc_func_call_count(__func__); return; } @@ -267,23 +253,19 @@ void AAudioStreamBuilder_setPerformanceMode(AAudioStreamBuilder* builder, inc_func_call_count(__func__); return; } -void AAudioStreamBuilder_setPrivacySensitive(AAudioStreamBuilder* builder, - bool privacySensitive) { +void AAudioStreamBuilder_setPrivacySensitive(AAudioStreamBuilder* builder, bool privacySensitive) { inc_func_call_count(__func__); return; } -void AAudioStreamBuilder_setSampleRate(AAudioStreamBuilder* builder, - int32_t sampleRate) { +void AAudioStreamBuilder_setSampleRate(AAudioStreamBuilder* builder, int32_t sampleRate) { inc_func_call_count(__func__); return; } -void AAudioStreamBuilder_setSamplesPerFrame(AAudioStreamBuilder* builder, - int32_t samplesPerFrame) { +void AAudioStreamBuilder_setSamplesPerFrame(AAudioStreamBuilder* builder, int32_t samplesPerFrame) { inc_func_call_count(__func__); return; } -void AAudioStreamBuilder_setSessionId(AAudioStreamBuilder* builder, - aaudio_session_id_t sessionId) { +void AAudioStreamBuilder_setSessionId(AAudioStreamBuilder* builder, aaudio_session_id_t sessionId) { inc_func_call_count(__func__); return; } @@ -292,8 +274,7 @@ void AAudioStreamBuilder_setSharingMode(AAudioStreamBuilder* builder, inc_func_call_count(__func__); return; } -void AAudioStreamBuilder_setUsage(AAudioStreamBuilder* builder, - aaudio_usage_t usage) { +void AAudioStreamBuilder_setUsage(AAudioStreamBuilder* builder, aaudio_usage_t usage) { inc_func_call_count(__func__); return; } diff --git a/system/test/mock/mock_hci_btsnoop.cc b/system/test/mock/mock_hci_btsnoop.cc index 5bc656125b3..cc67b1b5b73 100644 --- a/system/test/mock/mock_hci_btsnoop.cc +++ b/system/test/mock/mock_hci_btsnoop.cc @@ -18,25 +18,17 @@ #include "hci/include/btsnoop.h" -static void capture(const BT_HDR*, bool) { /* do nothing */ -} +static void capture(const BT_HDR*, bool) { /* do nothing */ } -static void allowlist_l2c_channel(uint16_t, uint16_t, - uint16_t) { /* do nothing */ -} +static void allowlist_l2c_channel(uint16_t, uint16_t, uint16_t) { /* do nothing */ } -static void allowlist_rfc_dlci(uint16_t, uint8_t) { /* do nothing */ -} +static void allowlist_rfc_dlci(uint16_t, uint8_t) { /* do nothing */ } -static void add_rfc_l2c_channel(uint16_t, uint16_t, uint16_t) { /* do nothing */ -} +static void add_rfc_l2c_channel(uint16_t, uint16_t, uint16_t) { /* do nothing */ } -static void clear_l2cap_allowlist(uint16_t, uint16_t, - uint16_t) { /* do nothing */ -} +static void clear_l2cap_allowlist(uint16_t, uint16_t, uint16_t) { /* do nothing */ } -static const btsnoop_t fake_snoop = {capture, allowlist_l2c_channel, - allowlist_rfc_dlci, add_rfc_l2c_channel, - clear_l2cap_allowlist}; +static const btsnoop_t fake_snoop = {capture, allowlist_l2c_channel, allowlist_rfc_dlci, + add_rfc_l2c_channel, clear_l2cap_allowlist}; const btsnoop_t* btsnoop_get_interface() { return &fake_snoop; } diff --git a/system/test/mock/mock_jni_thread.cc b/system/test/mock/mock_jni_thread.cc index bcc04713843..29af8f640c6 100644 --- a/system/test/mock/mock_jni_thread.cc +++ b/system/test/mock/mock_jni_thread.cc @@ -32,9 +32,8 @@ bool is_on_jni_thread() { inc_func_call_count(__func__); return false; } -bt_status_t btif_transfer_context(tBTIF_CBACK* /* p_cback */, - uint16_t /* event */, char* /* p_params */, - int /* param_len */, +bt_status_t btif_transfer_context(tBTIF_CBACK* /* p_cback */, uint16_t /* event */, + char* /* p_params */, int /* param_len */, tBTIF_COPY_CBACK* /* p_copy_cback */) { inc_func_call_count(__func__); return BT_STATUS_SUCCESS; @@ -44,8 +43,7 @@ bt_status_t do_in_jni_thread(base::OnceClosure task) { do_in_jni_thread_task_queue.push(std::move(task)); return BT_STATUS_SUCCESS; } -bt_status_t do_in_jni_thread(const base::Location& /* from_here */, - base::OnceClosure task) { +bt_status_t do_in_jni_thread(const base::Location& /* from_here */, base::OnceClosure task) { inc_func_call_count(__func__); do_in_jni_thread_task_queue.push(std::move(task)); return BT_STATUS_SUCCESS; diff --git a/system/test/mock/mock_legacy_hci_interface.h b/system/test/mock/mock_legacy_hci_interface.h index 3ae95fa4291..699a4538cb6 100644 --- a/system/test/mock/mock_legacy_hci_interface.h +++ b/system/test/mock/mock_legacy_hci_interface.h @@ -22,12 +22,10 @@ namespace bluetooth::legacy::hci::testing { class MockInterface : public Interface { - public: +public: MOCK_METHOD(void, Disconnect, (uint16_t handle, uint8_t reason), (const)); - MOCK_METHOD(void, ChangeConnectionPacketType, - (uint16_t handle, uint16_t packet_types), (const)); - MOCK_METHOD(void, StartRoleSwitch, (const RawAddress& bd_addr, uint8_t role), - (const)); + MOCK_METHOD(void, ChangeConnectionPacketType, (uint16_t handle, uint16_t packet_types), (const)); + MOCK_METHOD(void, StartRoleSwitch, (const RawAddress& bd_addr, uint8_t role), (const)); MOCK_METHOD(void, ConfigureDataPath, (hci_data_direction_t data_path_direction, uint8_t data_path_id, std::vector vendor_config), diff --git a/system/test/mock/mock_main_shim_BtifConfigInterface.cc b/system/test/mock/mock_main_shim_BtifConfigInterface.cc index 07635f09346..f9000a53121 100644 --- a/system/test/mock/mock_main_shim_BtifConfigInterface.cc +++ b/system/test/mock/mock_main_shim_BtifConfigInterface.cc @@ -18,72 +18,66 @@ #include "main/shim/config.h" -bool bluetooth::shim::BtifConfigInterface::HasSection( - const std::string& /* section */) { +bool bluetooth::shim::BtifConfigInterface::HasSection(const std::string& /* section */) { return false; } -bool bluetooth::shim::BtifConfigInterface::HasProperty( - const std::string& /* section */, const std::string& /* property */) { +bool bluetooth::shim::BtifConfigInterface::HasProperty(const std::string& /* section */, + const std::string& /* property */) { return false; } -bool bluetooth::shim::BtifConfigInterface::GetInt( - const std::string& /* section */, const std::string& /* key */, - int* /* value */) { +bool bluetooth::shim::BtifConfigInterface::GetInt(const std::string& /* section */, + const std::string& /* key */, int* /* value */) { return false; } -bool bluetooth::shim::BtifConfigInterface::SetInt( - const std::string& /* section */, const std::string& /* key */, - int /* value */) { +bool bluetooth::shim::BtifConfigInterface::SetInt(const std::string& /* section */, + const std::string& /* key */, int /* value */) { return false; } -bool bluetooth::shim::BtifConfigInterface::GetUint64( - const std::string& /* section */, const std::string& /* key */, - uint64_t* /* value */) { +bool bluetooth::shim::BtifConfigInterface::GetUint64(const std::string& /* section */, + const std::string& /* key */, + uint64_t* /* value */) { return false; } -bool bluetooth::shim::BtifConfigInterface::SetUint64( - const std::string& /* section */, const std::string& /* key */, - uint64_t /* value */) { +bool bluetooth::shim::BtifConfigInterface::SetUint64(const std::string& /* section */, + const std::string& /* key */, + uint64_t /* value */) { return false; } -bool bluetooth::shim::BtifConfigInterface::GetStr( - const std::string& /* section */, const std::string& /* key */, - char* /* value */, int* /* size_bytes */) { +bool bluetooth::shim::BtifConfigInterface::GetStr(const std::string& /* section */, + const std::string& /* key */, char* /* value */, + int* /* size_bytes */) { return false; } std::optional bluetooth::shim::BtifConfigInterface::GetStr( - const std::string& /* section */, const std::string& /* key */) { + const std::string& /* section */, const std::string& /* key */) { return std::string(); } -bool bluetooth::shim::BtifConfigInterface::SetStr( - const std::string& /* section */, const std::string& /* key */, - const std::string& /* value */) { +bool bluetooth::shim::BtifConfigInterface::SetStr(const std::string& /* section */, + const std::string& /* key */, + const std::string& /* value */) { return false; } -bool bluetooth::shim::BtifConfigInterface::GetBin( - const std::string& /* section */, const std::string& /* key */, - uint8_t* /* value */, size_t* /* length */) { +bool bluetooth::shim::BtifConfigInterface::GetBin(const std::string& /* section */, + const std::string& /* key */, + uint8_t* /* value */, size_t* /* length */) { return false; } -size_t bluetooth::shim::BtifConfigInterface::GetBinLength( - const std::string& /* section */, const std::string& /* key */) { +size_t bluetooth::shim::BtifConfigInterface::GetBinLength(const std::string& /* section */, + const std::string& /* key */) { return 0; } -bool bluetooth::shim::BtifConfigInterface::SetBin( - const std::string& /* section */, const std::string& /* key */, - const uint8_t* /* value */, size_t /* length */) { +bool bluetooth::shim::BtifConfigInterface::SetBin(const std::string& /* section */, + const std::string& /* key */, + const uint8_t* /* value */, size_t /* length */) { return false; } -bool bluetooth::shim::BtifConfigInterface::RemoveProperty( - const std::string& /* section */, const std::string& /* key */) { +bool bluetooth::shim::BtifConfigInterface::RemoveProperty(const std::string& /* section */, + const std::string& /* key */) { return false; } -void bluetooth::shim::BtifConfigInterface::RemoveSection( - const std::string& /* section */){}; -std::vector -bluetooth::shim::BtifConfigInterface::GetPersistentDevices() { +void bluetooth::shim::BtifConfigInterface::RemoveSection(const std::string& /* section */) {} +std::vector bluetooth::shim::BtifConfigInterface::GetPersistentDevices() { return std::vector(); } -void bluetooth::shim::BtifConfigInterface:: - ConvertEncryptOrDecryptKeyIfNeeded(){}; -void bluetooth::shim::BtifConfigInterface::Clear(){}; +void bluetooth::shim::BtifConfigInterface::ConvertEncryptOrDecryptKeyIfNeeded() {} +void bluetooth::shim::BtifConfigInterface::Clear() {} diff --git a/system/test/mock/mock_main_shim_acl.cc b/system/test/mock/mock_main_shim_acl.cc index 3c2b48285be..412724f7353 100644 --- a/system/test/mock/mock_main_shim_acl.cc +++ b/system/test/mock/mock_main_shim_acl.cc @@ -45,14 +45,10 @@ void DumpsysRecord(int /* fd */) { inc_func_call_count(__func__); } void DumpsysNeighbor(int /* fd */) { inc_func_call_count(__func__); } -void shim::legacy::Acl::Dump(int /* fd */) const { - inc_func_call_count(__func__); -} +void shim::legacy::Acl::Dump(int /* fd */) const { inc_func_call_count(__func__); } -shim::legacy::Acl::Acl(os::Handler* /* handler */, - const acl_interface_t& acl_interface, - uint8_t /* max_acceptlist_size */, - uint8_t /* max_address_resolution_size */) +shim::legacy::Acl::Acl(os::Handler* /* handler */, const acl_interface_t& acl_interface, + uint8_t /* max_acceptlist_size */, uint8_t /* max_address_resolution_size */) : acl_interface_(acl_interface) { inc_func_call_count(__func__); } @@ -63,8 +59,7 @@ bool shim::legacy::Acl::CheckForOrphanedAclConnections() const { return false; } -void shim::legacy::Acl::on_incoming_acl_credits(uint16_t /* handle */, - uint16_t /* credits */) { +void shim::legacy::Acl::on_incoming_acl_credits(uint16_t /* handle */, uint16_t /* credits */) { inc_func_call_count(__func__); } @@ -72,152 +67,128 @@ using HciHandle = uint16_t; struct shim::legacy::Acl::impl {}; -void shim::legacy::Acl::CreateClassicConnection( - const hci::Address& /* address */) { +void shim::legacy::Acl::CreateClassicConnection(const hci::Address& /* address */) { inc_func_call_count(__func__); } -void shim::legacy::Acl::CancelClassicConnection( - const hci::Address& /* address */) { +void shim::legacy::Acl::CancelClassicConnection(const hci::Address& /* address */) { inc_func_call_count(__func__); } -void shim::legacy::Acl::AcceptLeConnectionFrom( - const hci::AddressWithType& /* address_with_type */, bool /* is_direct */, - std::promise /* promise */) { +void shim::legacy::Acl::AcceptLeConnectionFrom(const hci::AddressWithType& /* address_with_type */, + bool /* is_direct */, + std::promise /* promise */) { inc_func_call_count(__func__); } void shim::legacy::Acl::IgnoreLeConnectionFrom( - const hci::AddressWithType& /* address_with_type */) { + const hci::AddressWithType& /* address_with_type */) { inc_func_call_count(__func__); } -void bluetooth::shim::legacy::Acl::OnClassicLinkDisconnected( - HciHandle /* handle */, hci::ErrorCode /* reason */) { +void bluetooth::shim::legacy::Acl::OnClassicLinkDisconnected(HciHandle /* handle */, + hci::ErrorCode /* reason */) { inc_func_call_count(__func__); } bluetooth::hci::AddressWithType shim::legacy::Acl::GetConnectionLocalAddress( - uint16_t /* handle */, bool /* ota_address */) { + uint16_t /* handle */, bool /* ota_address */) { inc_func_call_count(__func__); return hci::AddressWithType(); } bluetooth::hci::AddressWithType shim::legacy::Acl::GetConnectionPeerAddress( - uint16_t /* handle */, bool /* ota_address */) { + uint16_t /* handle */, bool /* ota_address */) { inc_func_call_count(__func__); return hci::AddressWithType(); } std::optional shim::legacy::Acl::GetAdvertisingSetConnectedTo( - const RawAddress& /* remote_bda */) { + const RawAddress& /* remote_bda */) { inc_func_call_count(__func__); return std::nullopt; ; } -void shim::legacy::Acl::OnLeLinkDisconnected(HciHandle /* handle */, - hci::ErrorCode /* reason */) { +void shim::legacy::Acl::OnLeLinkDisconnected(HciHandle /* handle */, hci::ErrorCode /* reason */) { inc_func_call_count(__func__); } void shim::legacy::Acl::OnConnectSuccess( - std::unique_ptr /* connection */) { + std::unique_ptr /* connection */) { inc_func_call_count(__func__); } -void shim::legacy::Acl::OnConnectRequest(hci::Address /* address */, - hci::ClassOfDevice /* cod */) { +void shim::legacy::Acl::OnConnectRequest(hci::Address /* address */, hci::ClassOfDevice /* cod */) { inc_func_call_count(__func__); } -void shim::legacy::Acl::OnConnectFail(hci::Address /* address */, - hci::ErrorCode /* reason */, +void shim::legacy::Acl::OnConnectFail(hci::Address /* address */, hci::ErrorCode /* reason */, bool /* locally_initiated */) { inc_func_call_count(__func__); } void shim::legacy::Acl::OnLeConnectSuccess( - hci::AddressWithType /* address_with_type */, - std::unique_ptr /* connection */) { + hci::AddressWithType /* address_with_type */, + std::unique_ptr /* connection */) { inc_func_call_count(__func__); } -void shim::legacy::Acl::OnLeConnectFail( - hci::AddressWithType /* address_with_type */, hci::ErrorCode /* reason */) { +void shim::legacy::Acl::OnLeConnectFail(hci::AddressWithType /* address_with_type */, + hci::ErrorCode /* reason */) { inc_func_call_count(__func__); } -void shim::legacy::Acl::DisconnectClassic(uint16_t /* handle */, - tHCI_STATUS /* reason */, +void shim::legacy::Acl::DisconnectClassic(uint16_t /* handle */, tHCI_STATUS /* reason */, std::string /* comment */) { inc_func_call_count(__func__); } -void shim::legacy::Acl::DisconnectLe(uint16_t /* handle */, - tHCI_STATUS /* reason */, +void shim::legacy::Acl::DisconnectLe(uint16_t /* handle */, tHCI_STATUS /* reason */, std::string /* comment */) { inc_func_call_count(__func__); } -void shim::legacy::Acl::LeSetDefaultSubrate(uint16_t /* subrate_min */, - uint16_t /* subrate_max */, - uint16_t /* max_latency */, - uint16_t /* cont_num */, +void shim::legacy::Acl::LeSetDefaultSubrate(uint16_t /* subrate_min */, uint16_t /* subrate_max */, + uint16_t /* max_latency */, uint16_t /* cont_num */, uint16_t /* sup_tout */) { inc_func_call_count(__func__); } -void shim::legacy::Acl::LeSubrateRequest(uint16_t /* hci_handle */, - uint16_t /* subrate_min */, - uint16_t /* subrate_max */, - uint16_t /* max_latency */, - uint16_t /* cont_num */, - uint16_t /* sup_tout */) { +void shim::legacy::Acl::LeSubrateRequest(uint16_t /* hci_handle */, uint16_t /* subrate_min */, + uint16_t /* subrate_max */, uint16_t /* max_latency */, + uint16_t /* cont_num */, uint16_t /* sup_tout */) { inc_func_call_count(__func__); } -void shim::legacy::Acl::DumpConnectionHistory(int /* fd */) const { - inc_func_call_count(__func__); -} +void shim::legacy::Acl::DumpConnectionHistory(int /* fd */) const { inc_func_call_count(__func__); } -void shim::legacy::Acl::DisconnectAllForSuspend() { - inc_func_call_count(__func__); -} +void shim::legacy::Acl::DisconnectAllForSuspend() { inc_func_call_count(__func__); } void shim::legacy::Acl::Shutdown() { inc_func_call_count(__func__); } void shim::legacy::Acl::FinalShutdown() { inc_func_call_count(__func__); } -void shim::legacy::Acl::ClearFilterAcceptList() { - inc_func_call_count(__func__); -} +void shim::legacy::Acl::ClearFilterAcceptList() { inc_func_call_count(__func__); } -void shim::legacy::Acl::AddToAddressResolution( - const hci::AddressWithType& /* address_with_type */, - const std::array& /* peer_irk */, - const std::array& /* local_irk */) { +void shim::legacy::Acl::AddToAddressResolution(const hci::AddressWithType& /* address_with_type */, + const std::array& /* peer_irk */, + const std::array& /* local_irk */) { inc_func_call_count(__func__); } void shim::legacy::Acl::RemoveFromAddressResolution( - const hci::AddressWithType& /* address_with_type */) { + const hci::AddressWithType& /* address_with_type */) { inc_func_call_count(__func__); } -void shim::legacy::Acl::ClearAddressResolution() { - inc_func_call_count(__func__); -} +void shim::legacy::Acl::ClearAddressResolution() { inc_func_call_count(__func__); } void shim::legacy::Acl::SetSystemSuspendState(bool /* suspended */) { inc_func_call_count(__func__); } -void shim::legacy::Acl::UpdateConnectionParameters(uint16_t /* handle */, - uint16_t /* conn_int_min */, - uint16_t /* conn_int_max */, - uint16_t /* conn_latency */, - uint16_t /* conn_timeout */, - uint16_t /* min_ce_len */, - uint16_t /* max_ce_len */) { +void shim::legacy::Acl::UpdateConnectionParameters( + uint16_t /* handle */, uint16_t /* conn_int_min */, uint16_t /* conn_int_max */, + uint16_t /* conn_latency */, uint16_t /* conn_timeout */, uint16_t /* min_ce_len */, + uint16_t /* max_ce_len */) { inc_func_call_count(__func__); } diff --git a/system/test/mock/mock_main_shim_acl_api.cc b/system/test/mock/mock_main_shim_acl_api.cc index 3ca9002e6ca..59015dbc504 100644 --- a/system/test/mock/mock_main_shim_acl_api.cc +++ b/system/test/mock/mock_main_shim_acl_api.cc @@ -29,97 +29,81 @@ #include "types/ble_address_with_type.h" #include "types/raw_address.h" -void bluetooth::shim::ACL_CreateClassicConnection( - const RawAddress& /* raw_address */) { +void bluetooth::shim::ACL_CreateClassicConnection(const RawAddress& /* raw_address */) { inc_func_call_count(__func__); } -void bluetooth::shim::ACL_CancelClassicConnection( - const RawAddress& /* raw_address */) { +void bluetooth::shim::ACL_CancelClassicConnection(const RawAddress& /* raw_address */) { inc_func_call_count(__func__); } -bool bluetooth::shim::ACL_AcceptLeConnectionFrom( - const tBLE_BD_ADDR& /* legacy_address_with_type */, bool /* is_direct */) { +bool bluetooth::shim::ACL_AcceptLeConnectionFrom(const tBLE_BD_ADDR& /* legacy_address_with_type */, + bool /* is_direct */) { inc_func_call_count(__func__); return true; } void bluetooth::shim::ACL_IgnoreLeConnectionFrom( - const tBLE_BD_ADDR& /* legacy_address_with_type */) { + const tBLE_BD_ADDR& /* legacy_address_with_type */) { inc_func_call_count(__func__); } void bluetooth::shim::ACL_ConfigureLePrivacy(bool /* is_le_privacy_enabled */) { inc_func_call_count(__func__); } -void bluetooth::shim::ACL_WriteData(uint16_t /* handle */, - BT_HDR* /* p_buf */) { +void bluetooth::shim::ACL_WriteData(uint16_t /* handle */, BT_HDR* /* p_buf */) { inc_func_call_count(__func__); } -void bluetooth::shim::ACL_Flush(uint16_t /* handle */) { +void bluetooth::shim::ACL_Flush(uint16_t /* handle */) { inc_func_call_count(__func__); } +void bluetooth::shim::ACL_Disconnect(uint16_t /* handle */, bool /* is_classic */, + tHCI_STATUS /* reason */, std::string /* comment */) { inc_func_call_count(__func__); } -void bluetooth::shim::ACL_Disconnect(uint16_t /* handle */, - bool /* is_classic */, - tHCI_STATUS /* reason */, - std::string /* comment */) { +void bluetooth::shim::ACL_IgnoreAllLeConnections() { inc_func_call_count(__func__); } +void bluetooth::shim::ACL_ReadConnectionAddress(uint16_t /* handle */, RawAddress& /* conn_addr */, + tBLE_ADDR_TYPE* /* p_addr_type */, + bool /* ota_address */) { inc_func_call_count(__func__); } -void bluetooth::shim::ACL_IgnoreAllLeConnections() { - inc_func_call_count(__func__); -} -void bluetooth::shim::ACL_ReadConnectionAddress( - uint16_t /* handle */, RawAddress& /* conn_addr */, - tBLE_ADDR_TYPE* /* p_addr_type */, bool /* ota_address */) { - inc_func_call_count(__func__); -} -void bluetooth::shim::ACL_ReadPeerConnectionAddress( - uint16_t /* handle */, RawAddress& /* conn_addr */, - tBLE_ADDR_TYPE* /* p_addr_type */, bool /* ota_address */) { +void bluetooth::shim::ACL_ReadPeerConnectionAddress(uint16_t /* handle */, + RawAddress& /* conn_addr */, + tBLE_ADDR_TYPE* /* p_addr_type */, + bool /* ota_address */) { inc_func_call_count(__func__); } std::optional bluetooth::shim::ACL_GetAdvertisingSetConnectedTo( - const RawAddress& /* addr */) { + const RawAddress& /* addr */) { inc_func_call_count(__func__); return std::nullopt; } -void bluetooth::shim::ACL_AddToAddressResolution( - const tBLE_BD_ADDR& /* legacy_address_with_type */, - const Octet16& /* peer_irk */, const Octet16& /* local_irk */) { +void bluetooth::shim::ACL_AddToAddressResolution(const tBLE_BD_ADDR& /* legacy_address_with_type */, + const Octet16& /* peer_irk */, + const Octet16& /* local_irk */) { inc_func_call_count(__func__); } void bluetooth::shim::ACL_RemoveFromAddressResolution( - const tBLE_BD_ADDR& /* legacy_address_with_type */) { - inc_func_call_count(__func__); -} -void bluetooth::shim::ACL_ClearAddressResolution() { + const tBLE_BD_ADDR& /* legacy_address_with_type */) { inc_func_call_count(__func__); } +void bluetooth::shim::ACL_ClearAddressResolution() { inc_func_call_count(__func__); } void bluetooth::shim::ACL_LeSetDefaultSubrate(uint16_t /* subrate_min */, uint16_t /* subrate_max */, - uint16_t /* max_latency */, - uint16_t /* cont_num */, + uint16_t /* max_latency */, uint16_t /* cont_num */, uint16_t /* sup_tout */) { inc_func_call_count(__func__); } -void bluetooth::shim::ACL_LeSubrateRequest(uint16_t /* hci_handle */, - uint16_t /* subrate_min */, - uint16_t /* subrate_max */, - uint16_t /* max_latency */, - uint16_t /* cont_num */, - uint16_t /* sup_tout */) { +void bluetooth::shim::ACL_LeSubrateRequest(uint16_t /* hci_handle */, uint16_t /* subrate_min */, + uint16_t /* subrate_max */, uint16_t /* max_latency */, + uint16_t /* cont_num */, uint16_t /* sup_tout */) { inc_func_call_count(__func__); } void bluetooth::shim::ACL_Shutdown() { inc_func_call_count(__func__); } void bluetooth::shim::ACL_SendConnectionParameterUpdateRequest( - uint16_t /* hci_handle */, uint16_t /* conn_int_min */, - uint16_t /* conn_int_max */, uint16_t /* conn_latency */, - uint16_t /* conn_timeout */, uint16_t /* min_ce_len */, - uint16_t /* max_ce_len */) { + uint16_t /* hci_handle */, uint16_t /* conn_int_min */, uint16_t /* conn_int_max */, + uint16_t /* conn_latency */, uint16_t /* conn_timeout */, uint16_t /* min_ce_len */, + uint16_t /* max_ce_len */) { inc_func_call_count(__func__); } -void bluetooth::shim::ACL_CancelRemoteNameRequest( - const RawAddress& /* addr */) { +void bluetooth::shim::ACL_CancelRemoteNameRequest(const RawAddress& /* addr */) { inc_func_call_count(__func__); } void bluetooth::shim::ACL_RemoteNameRequest(const RawAddress& /* addr */, diff --git a/system/test/mock/mock_main_shim_acl_api.h b/system/test/mock/mock_main_shim_acl_api.h index aee9dcdd052..4f57436f61b 100644 --- a/system/test/mock/mock_main_shim_acl_api.h +++ b/system/test/mock/mock_main_shim_acl_api.h @@ -48,15 +48,13 @@ namespace main_shim_acl_api { // Return: bool struct ACL_AcceptLeConnectionFrom { static bool return_value; - std::function - body{[](const tBLE_BD_ADDR& legacy_address_with_type, bool is_direct) { - return return_value; - }}; - bool operator()(const tBLE_BD_ADDR& legacy_address_with_type, - bool is_direct) { + std::function body{ + [](const tBLE_BD_ADDR& legacy_address_with_type, bool is_direct) { + return return_value; + }}; + bool operator()(const tBLE_BD_ADDR& legacy_address_with_type, bool is_direct) { return body(legacy_address_with_type, is_direct); - }; + } }; extern struct ACL_AcceptLeConnectionFrom ACL_AcceptLeConnectionFrom; @@ -64,14 +62,14 @@ extern struct ACL_AcceptLeConnectionFrom ACL_AcceptLeConnectionFrom; // Params: const tBLE_BD_ADDR& legacy_address_with_type, const Octet16& // peer_irk, const Octet16& local_irk Return: void struct ACL_AddToAddressResolution { - std::function - body{[](const tBLE_BD_ADDR& legacy_address_with_type, - const Octet16& peer_irk, const Octet16& local_irk) {}}; - void operator()(const tBLE_BD_ADDR& legacy_address_with_type, - const Octet16& peer_irk, const Octet16& local_irk) { + std::function + body{[](const tBLE_BD_ADDR& legacy_address_with_type, const Octet16& peer_irk, + const Octet16& local_irk) {}}; + void operator()(const tBLE_BD_ADDR& legacy_address_with_type, const Octet16& peer_irk, + const Octet16& local_irk) { body(legacy_address_with_type, peer_irk, local_irk); - }; + } }; extern struct ACL_AddToAddressResolution ACL_AddToAddressResolution; @@ -79,9 +77,8 @@ extern struct ACL_AddToAddressResolution ACL_AddToAddressResolution; // Params: const RawAddress& raw_address // Return: void struct ACL_CancelClassicConnection { - std::function body{ - [](const RawAddress& raw_address) {}}; - void operator()(const RawAddress& raw_address) { body(raw_address); }; + std::function body{[](const RawAddress& raw_address) {}}; + void operator()(const RawAddress& raw_address) { body(raw_address); } }; extern struct ACL_CancelClassicConnection ACL_CancelClassicConnection; @@ -90,7 +87,7 @@ extern struct ACL_CancelClassicConnection ACL_CancelClassicConnection; // Return: void struct ACL_ClearAddressResolution { std::function body{[]() {}}; - void operator()() { body(); }; + void operator()() { body(); } }; extern struct ACL_ClearAddressResolution ACL_ClearAddressResolution; @@ -99,7 +96,7 @@ extern struct ACL_ClearAddressResolution ACL_ClearAddressResolution; // Return: void struct ACL_ClearFilterAcceptList { std::function body{[]() {}}; - void operator()() { body(); }; + void operator()() { body(); } }; extern struct ACL_ClearFilterAcceptList ACL_ClearFilterAcceptList; @@ -107,15 +104,14 @@ extern struct ACL_ClearFilterAcceptList ACL_ClearFilterAcceptList; // Params: // Return: void struct ACL_LeSetDefaultSubrate { - std::function - body{[](uint16_t subrate_min, uint16_t subrate_max, uint16_t max_latency, - uint16_t cont_num, uint16_t sup_tout) {}}; - void operator()(uint16_t subrate_min, uint16_t subrate_max, - uint16_t max_latency, uint16_t cont_num, uint16_t sup_tout) { + std::function + body{[](uint16_t subrate_min, uint16_t subrate_max, uint16_t max_latency, + uint16_t cont_num, uint16_t sup_tout) {}}; + void operator()(uint16_t subrate_min, uint16_t subrate_max, uint16_t max_latency, + uint16_t cont_num, uint16_t sup_tout) { body(subrate_min, subrate_max, max_latency, cont_num, sup_tout); - }; + } }; extern struct ACL_LeSetDefaultSubrate ACL_LeSetDefaultSubrate; @@ -123,16 +119,14 @@ extern struct ACL_LeSetDefaultSubrate ACL_LeSetDefaultSubrate; // Params: // Return: void struct ACL_LeSubrateRequest { - std::function - body{[](uint16_t hci_handle, uint16_t subrate_min, uint16_t subrate_max, - uint16_t max_latency, uint16_t cont_num, uint16_t sup_tout) {}}; - void operator()(uint16_t hci_handle, uint16_t subrate_min, - uint16_t subrate_max, uint16_t max_latency, uint16_t cont_num, - uint16_t sup_tout) { + std::function + body{[](uint16_t hci_handle, uint16_t subrate_min, uint16_t subrate_max, + uint16_t max_latency, uint16_t cont_num, uint16_t sup_tout) {}}; + void operator()(uint16_t hci_handle, uint16_t subrate_min, uint16_t subrate_max, + uint16_t max_latency, uint16_t cont_num, uint16_t sup_tout) { body(hci_handle, subrate_min, subrate_max, max_latency, cont_num, sup_tout); - }; + } }; extern struct ACL_LeSubrateRequest ACL_LeSubrateRequest; @@ -140,9 +134,8 @@ extern struct ACL_LeSubrateRequest ACL_LeSubrateRequest; // Params: bool is_le_privacy_enabled // Return: void struct ACL_ConfigureLePrivacy { - std::function body{ - [](bool is_le_privacy_enabled) {}}; - void operator()(bool is_le_privacy_enabled) { body(is_le_privacy_enabled); }; + std::function body{[](bool is_le_privacy_enabled) {}}; + void operator()(bool is_le_privacy_enabled) { body(is_le_privacy_enabled); } }; extern struct ACL_ConfigureLePrivacy ACL_ConfigureLePrivacy; @@ -150,9 +143,8 @@ extern struct ACL_ConfigureLePrivacy ACL_ConfigureLePrivacy; // Params: const RawAddress& raw_address // Return: void struct ACL_CreateClassicConnection { - std::function body{ - [](const RawAddress& raw_address) {}}; - void operator()(const RawAddress& raw_address) { body(raw_address); }; + std::function body{[](const RawAddress& raw_address) {}}; + void operator()(const RawAddress& raw_address) { body(raw_address); } }; extern struct ACL_CreateClassicConnection ACL_CreateClassicConnection; @@ -160,14 +152,11 @@ extern struct ACL_CreateClassicConnection ACL_CreateClassicConnection; // Params: uint16_t handle, bool is_classic, tHCI_STATUS reason, std::string // comment Return: void struct ACL_Disconnect { - std::function - body{[](uint16_t handle, bool is_classic, tHCI_STATUS reason, - std::string comment) {}}; - void operator()(uint16_t handle, bool is_classic, tHCI_STATUS reason, - std::string comment) { + std::function + body{[](uint16_t handle, bool is_classic, tHCI_STATUS reason, std::string comment) {}}; + void operator()(uint16_t handle, bool is_classic, tHCI_STATUS reason, std::string comment) { body(handle, is_classic, reason, comment); - }; + } }; extern struct ACL_Disconnect ACL_Disconnect; @@ -176,7 +165,7 @@ extern struct ACL_Disconnect ACL_Disconnect; // Return: void struct ACL_IgnoreAllLeConnections { std::function body{[]() {}}; - void operator()() { body(); }; + void operator()() { body(); } }; extern struct ACL_IgnoreAllLeConnections ACL_IgnoreAllLeConnections; @@ -185,10 +174,8 @@ extern struct ACL_IgnoreAllLeConnections ACL_IgnoreAllLeConnections; // Return: void struct ACL_IgnoreLeConnectionFrom { std::function body{ - [](const tBLE_BD_ADDR& legacy_address_with_type) {}}; - void operator()(const tBLE_BD_ADDR& legacy_address_with_type) { - body(legacy_address_with_type); - }; + [](const tBLE_BD_ADDR& legacy_address_with_type) {}}; + void operator()(const tBLE_BD_ADDR& legacy_address_with_type) { body(legacy_address_with_type); } }; extern struct ACL_IgnoreLeConnectionFrom ACL_IgnoreLeConnectionFrom; @@ -196,14 +183,14 @@ extern struct ACL_IgnoreLeConnectionFrom ACL_IgnoreLeConnectionFrom; // Params: uint16_t handle, RawAddress& conn_addr, tBLE_ADDR_TYPE*, bool // p_addr_type Return: void struct ACL_ReadConnectionAddress { - std::function - body{[](uint16_t handle, RawAddress& conn_addr, - tBLE_ADDR_TYPE* p_addr_type, bool ota_address) {}}; - void operator()(uint16_t handle, RawAddress& conn_addr, - tBLE_ADDR_TYPE* p_addr_type, bool ota_address) { + std::function + body{[](uint16_t handle, RawAddress& conn_addr, tBLE_ADDR_TYPE* p_addr_type, + bool ota_address) {}}; + void operator()(uint16_t handle, RawAddress& conn_addr, tBLE_ADDR_TYPE* p_addr_type, + bool ota_address) { body(handle, conn_addr, p_addr_type, ota_address); - }; + } }; extern struct ACL_ReadConnectionAddress ACL_ReadConnectionAddress; @@ -211,14 +198,14 @@ extern struct ACL_ReadConnectionAddress ACL_ReadConnectionAddress; // Params: uint16_t handle, RawAddress& conn_addr, tBLE_ADDR_TYPE*, bool // p_addr_type Return: void struct ACL_ReadPeerConnectionAddress { - std::function - body{[](uint16_t handle, RawAddress& conn_addr, - tBLE_ADDR_TYPE* p_addr_type, bool ota_address) {}}; - void operator()(uint16_t handle, RawAddress& conn_addr, - tBLE_ADDR_TYPE* p_addr_type, bool ota_address) { + std::function + body{[](uint16_t handle, RawAddress& conn_addr, tBLE_ADDR_TYPE* p_addr_type, + bool ota_address) {}}; + void operator()(uint16_t handle, RawAddress& conn_addr, tBLE_ADDR_TYPE* p_addr_type, + bool ota_address) { body(handle, conn_addr, p_addr_type, ota_address); - }; + } }; extern struct ACL_ReadPeerConnectionAddress ACL_ReadPeerConnectionAddress; @@ -228,10 +215,8 @@ extern struct ACL_ReadPeerConnectionAddress ACL_ReadPeerConnectionAddress; struct ACL_GetAdvertisingSetConnectedTo { static std::optional return_value; std::function(const RawAddress& addr)> body{ - [](const RawAddress& addr) { return return_value; }}; - std::optional operator()(const RawAddress& addr) { - return body(addr); - }; + [](const RawAddress& addr) { return return_value; }}; + std::optional operator()(const RawAddress& addr) { return body(addr); } }; extern struct ACL_GetAdvertisingSetConnectedTo ACL_GetAdvertisingSetConnectedTo; @@ -240,10 +225,8 @@ extern struct ACL_GetAdvertisingSetConnectedTo ACL_GetAdvertisingSetConnectedTo; // Return: void struct ACL_RemoveFromAddressResolution { std::function body{ - [](const tBLE_BD_ADDR& legacy_address_with_type) {}}; - void operator()(const tBLE_BD_ADDR& legacy_address_with_type) { - body(legacy_address_with_type); - }; + [](const tBLE_BD_ADDR& legacy_address_with_type) {}}; + void operator()(const tBLE_BD_ADDR& legacy_address_with_type) { body(legacy_address_with_type); } }; extern struct ACL_RemoveFromAddressResolution ACL_RemoveFromAddressResolution; @@ -252,7 +235,7 @@ extern struct ACL_RemoveFromAddressResolution ACL_RemoveFromAddressResolution; // Return: void struct ACL_Shutdown { std::function body{[]() {}}; - void operator()() { body(); }; + void operator()() { body(); } }; extern struct ACL_Shutdown ACL_Shutdown; @@ -260,9 +243,8 @@ extern struct ACL_Shutdown ACL_Shutdown; // Params: uint16_t handle, BT_HDR* p_buf // Return: void struct ACL_WriteData { - std::function body{ - [](uint16_t handle, BT_HDR* p_buf) {}}; - void operator()(uint16_t handle, BT_HDR* p_buf) { body(handle, p_buf); }; + std::function body{[](uint16_t handle, BT_HDR* p_buf) {}}; + void operator()(uint16_t handle, BT_HDR* p_buf) { body(handle, p_buf); } }; extern struct ACL_WriteData ACL_WriteData; @@ -271,7 +253,7 @@ extern struct ACL_WriteData ACL_WriteData; // Return: void struct ACL_Flush { std::function body{[](uint16_t /* handle */) {}}; - void operator()(uint16_t handle) { body(handle); }; + void operator()(uint16_t handle) { body(handle); } }; extern struct ACL_Flush ACL_Flush; @@ -285,23 +267,19 @@ extern struct ACL_Flush ACL_Flush; // Params: uint16_t max_ce_len // Return: void struct ACL_SendConnectionParameterUpdateRequest { - std::function - body{[](uint16_t /* handle */, uint16_t /* conn_int_min */, - uint16_t /* conn_int_max */, uint16_t /* conn_latency */, - uint16_t /* conn_timeout */, uint16_t /* min_ce_len */, - uint16_t /* max_ce_len */) {}}; + body{[](uint16_t /* handle */, uint16_t /* conn_int_min */, uint16_t /* conn_int_max */, + uint16_t /* conn_latency */, uint16_t /* conn_timeout */, + uint16_t /* min_ce_len */, uint16_t /* max_ce_len */) {}}; void operator()(uint16_t handle, uint16_t conn_int_min, uint16_t conn_int_max, - uint16_t conn_latency, uint16_t conn_timeout, - uint16_t min_ce_len, uint16_t max_ce_len) { - body(handle, conn_int_min, conn_int_max, conn_latency, conn_timeout, - min_ce_len, max_ce_len); - }; + uint16_t conn_latency, uint16_t conn_timeout, uint16_t min_ce_len, + uint16_t max_ce_len) { + body(handle, conn_int_min, conn_int_max, conn_latency, conn_timeout, min_ce_len, max_ce_len); + } }; -extern struct ACL_SendConnectionParameterUpdateRequest - ACL_SendConnectionParameterUpdateRequest; +extern struct ACL_SendConnectionParameterUpdateRequest ACL_SendConnectionParameterUpdateRequest; } // namespace main_shim_acl_api } // namespace mock } // namespace test diff --git a/system/test/mock/mock_main_shim_acl_legacy_interface.cc b/system/test/mock/mock_main_shim_acl_legacy_interface.cc index accbca1e57e..f425ef98b20 100644 --- a/system/test/mock/mock_main_shim_acl_legacy_interface.cc +++ b/system/test/mock/mock_main_shim_acl_legacy_interface.cc @@ -21,50 +21,50 @@ namespace shim { namespace legacy { acl_interface_t acl_interface_ = { - .on_send_data_upwards = nullptr, - .on_packets_completed = nullptr, + .on_send_data_upwards = nullptr, + .on_packets_completed = nullptr, - .connection.classic.on_connected = nullptr, - .connection.classic.on_connect_request = nullptr, - .connection.classic.on_failed = nullptr, - .connection.classic.on_disconnected = nullptr, + .connection.classic.on_connected = nullptr, + .connection.classic.on_connect_request = nullptr, + .connection.classic.on_failed = nullptr, + .connection.classic.on_disconnected = nullptr, - .connection.le.on_connected = nullptr, - .connection.le.on_failed = nullptr, - .connection.le.on_disconnected = nullptr, + .connection.le.on_connected = nullptr, + .connection.le.on_failed = nullptr, + .connection.le.on_disconnected = nullptr, - .link.classic.on_authentication_complete = nullptr, - .link.classic.on_central_link_key_complete = nullptr, - .link.classic.on_change_connection_link_key_complete = nullptr, - .link.classic.on_encryption_change = nullptr, - .link.classic.on_flow_specification_complete = nullptr, - .link.classic.on_flush_occurred = nullptr, - .link.classic.on_mode_change = nullptr, - .link.classic.on_packet_type_changed = nullptr, - .link.classic.on_qos_setup_complete = nullptr, - .link.classic.on_read_afh_channel_map_complete = nullptr, - .link.classic.on_read_automatic_flush_timeout_complete = nullptr, - .link.classic.on_sniff_subrating = nullptr, - .link.classic.on_read_clock_complete = nullptr, - .link.classic.on_read_clock_offset_complete = nullptr, - .link.classic.on_read_failed_contact_counter_complete = nullptr, - .link.classic.on_read_link_policy_settings_complete = nullptr, - .link.classic.on_read_link_quality_complete = nullptr, - .link.classic.on_read_link_supervision_timeout_complete = nullptr, - .link.classic.on_read_remote_version_information_complete = nullptr, - .link.classic.on_read_remote_supported_features_complete = nullptr, - .link.classic.on_read_remote_extended_features_complete = nullptr, - .link.classic.on_read_rssi_complete = nullptr, - .link.classic.on_read_transmit_power_level_complete = nullptr, - .link.classic.on_role_change = nullptr, - .link.classic.on_role_discovery_complete = nullptr, + .link.classic.on_authentication_complete = nullptr, + .link.classic.on_central_link_key_complete = nullptr, + .link.classic.on_change_connection_link_key_complete = nullptr, + .link.classic.on_encryption_change = nullptr, + .link.classic.on_flow_specification_complete = nullptr, + .link.classic.on_flush_occurred = nullptr, + .link.classic.on_mode_change = nullptr, + .link.classic.on_packet_type_changed = nullptr, + .link.classic.on_qos_setup_complete = nullptr, + .link.classic.on_read_afh_channel_map_complete = nullptr, + .link.classic.on_read_automatic_flush_timeout_complete = nullptr, + .link.classic.on_sniff_subrating = nullptr, + .link.classic.on_read_clock_complete = nullptr, + .link.classic.on_read_clock_offset_complete = nullptr, + .link.classic.on_read_failed_contact_counter_complete = nullptr, + .link.classic.on_read_link_policy_settings_complete = nullptr, + .link.classic.on_read_link_quality_complete = nullptr, + .link.classic.on_read_link_supervision_timeout_complete = nullptr, + .link.classic.on_read_remote_version_information_complete = nullptr, + .link.classic.on_read_remote_supported_features_complete = nullptr, + .link.classic.on_read_remote_extended_features_complete = nullptr, + .link.classic.on_read_rssi_complete = nullptr, + .link.classic.on_read_transmit_power_level_complete = nullptr, + .link.classic.on_role_change = nullptr, + .link.classic.on_role_discovery_complete = nullptr, - .link.le.on_connection_update = nullptr, - .link.le.on_parameter_update_request = nullptr, - .link.le.on_data_length_change = nullptr, - .link.le.on_read_remote_version_information_complete = nullptr, - .link.le.on_phy_update = nullptr, - .link.le.on_le_subrate_change = nullptr, + .link.le.on_connection_update = nullptr, + .link.le.on_parameter_update_request = nullptr, + .link.le.on_data_length_change = nullptr, + .link.le.on_read_remote_version_information_complete = nullptr, + .link.le.on_phy_update = nullptr, + .link.le.on_le_subrate_change = nullptr, }; const acl_interface_t& GetAclInterface() { return acl_interface_; } diff --git a/system/test/mock/mock_main_shim_btm_api.cc b/system/test/mock/mock_main_shim_btm_api.cc index 54904c1cf26..9f2ba178f5e 100644 --- a/system/test/mock/mock_main_shim_btm_api.cc +++ b/system/test/mock/mock_main_shim_btm_api.cc @@ -54,20 +54,20 @@ tBTM_STATUS bluetooth::shim::BTM_SetEventFilterConnectionSetupAllDevices() { } tBTM_STATUS bluetooth::shim::BTM_AllowWakeByHid( - std::vector /* classic_hid_devices */, - std::vector> /* le_hid_devices */) { + std::vector /* classic_hid_devices */, + std::vector> /* le_hid_devices */) { inc_func_call_count(__func__); return BTM_SUCCESS; } tBTM_STATUS bluetooth::shim::BTM_RestoreFilterAcceptList( - std::vector> /* le_devices */) { + std::vector> /* le_devices */) { inc_func_call_count(__func__); return BTM_SUCCESS; } -tBTM_STATUS bluetooth::shim::BTM_SetDefaultEventMaskExcept( - uint64_t /* mask */, uint64_t /* le_mask */) { +tBTM_STATUS bluetooth::shim::BTM_SetDefaultEventMaskExcept(uint64_t /* mask */, + uint64_t /* le_mask */) { inc_func_call_count(__func__); return BTM_SUCCESS; } diff --git a/system/test/mock/mock_main_shim_distance_measurement_manager.cc b/system/test/mock/mock_main_shim_distance_measurement_manager.cc index 67953f3014d..4fdf5a80f1b 100644 --- a/system/test/mock/mock_main_shim_distance_measurement_manager.cc +++ b/system/test/mock/mock_main_shim_distance_measurement_manager.cc @@ -22,11 +22,8 @@ #include "main/shim/distance_measurement_manager.h" #include "test/common/mock_functions.h" -DistanceMeasurementInterface* -bluetooth::shim::get_distance_measurement_instance() { +DistanceMeasurementInterface* bluetooth::shim::get_distance_measurement_instance() { inc_func_call_count(__func__); return nullptr; } -void bluetooth::shim::init_distance_measurement_manager() { - inc_func_call_count(__func__); -} +void bluetooth::shim::init_distance_measurement_manager() { inc_func_call_count(__func__); } diff --git a/system/test/mock/mock_main_shim_dumpsys.cc b/system/test/mock/mock_main_shim_dumpsys.cc index 51fcf5541de..b3f4fe15187 100644 --- a/system/test/mock/mock_main_shim_dumpsys.cc +++ b/system/test/mock/mock_main_shim_dumpsys.cc @@ -23,13 +23,10 @@ #include "shim/dumpsys.h" #include "test/common/mock_functions.h" -void bluetooth::shim::RegisterDumpsysFunction(const void* /* token */, - DumpsysFunction /* func */) { - inc_func_call_count(__func__); -} -void bluetooth::shim::Dump(int /* fd */, const char** /* args */) { +void bluetooth::shim::RegisterDumpsysFunction(const void* /* token */, DumpsysFunction /* func */) { inc_func_call_count(__func__); } +void bluetooth::shim::Dump(int /* fd */, const char** /* args */) { inc_func_call_count(__func__); } void bluetooth::shim::UnregisterDumpsysFunction(const void* /* token */) { inc_func_call_count(__func__); } diff --git a/system/test/mock/mock_main_shim_entry.cc b/system/test/mock/mock_main_shim_entry.cc index d2cdbd5a137..ac45931b643 100644 --- a/system/test/mock/mock_main_shim_entry.cc +++ b/system/test/mock/mock_main_shim_entry.cc @@ -46,16 +46,10 @@ namespace shim { Dumpsys* GetDumpsys() { return hci::testing::shim_dumpsys_; } hci::AclManager* GetAclManager() { return hci::testing::mock_acl_manager_; } -hci::ControllerInterface* GetController() { - return hci::testing::mock_controller_; -} +hci::ControllerInterface* GetController() { return hci::testing::mock_controller_; } hci::HciInterface* GetHciLayer() { return hci::testing::mock_hci_layer_; } -hci::LeAdvertisingManager* GetAdvertising() { - return hci::testing::mock_le_advertising_manager_; -} -hci::LeScanningManager* GetScanning() { - return hci::testing::mock_le_scanning_manager_; -} +hci::LeAdvertisingManager* GetAdvertising() { return hci::testing::mock_le_advertising_manager_; } +hci::LeScanningManager* GetScanning() { return hci::testing::mock_le_scanning_manager_; } hci::DistanceMeasurementManager* GetDistanceMeasurementManager() { return hci::testing::mock_distance_measurement_manager_; } diff --git a/system/test/mock/mock_main_shim_hci_layer.cc b/system/test/mock/mock_main_shim_hci_layer.cc index ff7f1e66311..d9c715d380c 100644 --- a/system/test/mock/mock_main_shim_hci_layer.cc +++ b/system/test/mock/mock_main_shim_hci_layer.cc @@ -34,15 +34,11 @@ namespace bluetooth::shim { namespace testing { const hci_t* test_interface = nullptr; -void hci_layer_set_interface(const hci_t* interface) { - test_interface = interface; -} +void hci_layer_set_interface(const hci_t* interface) { test_interface = interface; } } // namespace testing } // namespace bluetooth::shim -const hci_t* bluetooth::shim::hci_layer_get_interface() { - return testing::test_interface; -} +const hci_t* bluetooth::shim::hci_layer_get_interface() { return testing::test_interface; } namespace test { namespace mock { @@ -67,19 +63,18 @@ namespace main_shim_hci_layer {} // namespace main_shim_hci_layer // Mocked functions, if any namespace cpp { -void OnTransmitPacketCommandComplete(command_complete_cb complete_callback, - void* context, +void OnTransmitPacketCommandComplete(command_complete_cb complete_callback, void* context, bluetooth::hci::CommandCompleteView view) { inc_func_call_count(__func__); - test::mock::main_shim_hci_layer::OnTransmitPacketCommandComplete( - complete_callback, context, view); + test::mock::main_shim_hci_layer::OnTransmitPacketCommandComplete(complete_callback, context, + view); } void OnTransmitPacketStatus(command_status_cb status_callback, void* context, std::unique_ptr command, bluetooth::hci::CommandStatusView view) { inc_func_call_count(__func__); - test::mock::main_shim_hci_layer::OnTransmitPacketStatus( - status_callback, context, std::move(command), view); + test::mock::main_shim_hci_layer::OnTransmitPacketStatus(status_callback, context, + std::move(command), view); } } // namespace cpp diff --git a/system/test/mock/mock_main_shim_hci_layer.h b/system/test/mock/mock_main_shim_hci_layer.h index c54735d971d..7973bece5db 100644 --- a/system/test/mock/mock_main_shim_hci_layer.h +++ b/system/test/mock/mock_main_shim_hci_layer.h @@ -61,12 +61,12 @@ namespace main_shim_hci_layer { struct OnTransmitPacketCommandComplete { std::function - body{[](command_complete_cb /* complete_callback */, void* /* context */, - bluetooth::hci::CommandCompleteView /* view */) {}}; + body{[](command_complete_cb /* complete_callback */, void* /* context */, + bluetooth::hci::CommandCompleteView /* view */) {}}; void operator()(command_complete_cb complete_callback, void* context, bluetooth::hci::CommandCompleteView view) { body(complete_callback, context, view); - }; + } }; extern struct OnTransmitPacketCommandComplete OnTransmitPacketCommandComplete; @@ -76,16 +76,14 @@ extern struct OnTransmitPacketCommandComplete OnTransmitPacketCommandComplete; // Return: void struct OnTransmitPacketStatus { std::function command, - bluetooth::hci::CommandStatusView view)> - body{[](command_status_cb /* status_callback */, void* /* context */, - std::unique_ptr /* command */, - bluetooth::hci::CommandStatusView /* view */) {}}; + std::unique_ptr command, bluetooth::hci::CommandStatusView view)> + body{[](command_status_cb /* status_callback */, void* /* context */, + std::unique_ptr /* command */, + bluetooth::hci::CommandStatusView /* view */) {}}; void operator()(command_status_cb status_callback, void* context, - std::unique_ptr command, - bluetooth::hci::CommandStatusView view) { + std::unique_ptr command, bluetooth::hci::CommandStatusView view) { body(status_callback, context, std::move(command), view); - }; + } }; extern struct OnTransmitPacketStatus OnTransmitPacketStatus; @@ -95,7 +93,7 @@ extern struct OnTransmitPacketStatus OnTransmitPacketStatus; struct hci_layer_get_interface { static const hci_t* return_value; std::function body{[]() { return return_value; }}; - const hci_t* operator()() { return body(); }; + const hci_t* operator()() { return body(); } }; extern struct hci_layer_get_interface hci_layer_get_interface; @@ -104,7 +102,7 @@ extern struct hci_layer_get_interface hci_layer_get_interface; // Return: void struct hci_on_reset_complete { std::function body{[]() {}}; - void operator()() { body(); }; + void operator()() { body(); } }; extern struct hci_on_reset_complete hci_on_reset_complete; @@ -113,7 +111,7 @@ extern struct hci_on_reset_complete hci_on_reset_complete; // Return: void struct hci_on_shutting_down { std::function body{[]() {}}; - void operator()() { body(); }; + void operator()() { body(); } }; extern struct hci_on_shutting_down hci_on_shutting_down; diff --git a/system/test/mock/mock_main_shim_l2cap_api.h b/system/test/mock/mock_main_shim_l2cap_api.h index 860f5bc0e49..bd5fd2db68a 100644 --- a/system/test/mock/mock_main_shim_l2cap_api.h +++ b/system/test/mock/mock_main_shim_l2cap_api.h @@ -40,15 +40,14 @@ namespace main_shim_l2cap_api { // Params: const RawAddress& addr, uint8_t* lmp_version, uint16_t* manufacturer, // uint16_t* lmp_sub_version Returns: bool struct L2CA_ReadRemoteVersion { - std::function - body{[](const RawAddress& addr, uint8_t* lmp_version, - uint16_t* manufacturer, - uint16_t* lmp_sub_version) { return false; }}; - bool operator()(const RawAddress& addr, uint8_t* lmp_version, - uint16_t* manufacturer, uint16_t* lmp_sub_version) { + std::function + body{[](const RawAddress& addr, uint8_t* lmp_version, uint16_t* manufacturer, + uint16_t* lmp_sub_version) { return false; }}; + bool operator()(const RawAddress& addr, uint8_t* lmp_version, uint16_t* manufacturer, + uint16_t* lmp_sub_version) { return body(addr, lmp_version, manufacturer, lmp_sub_version); - }; + } }; extern struct L2CA_ReadRemoteVersion L2CA_ReadRemoteVersion; // Name: L2CA_ReadRemoteFeatures @@ -56,8 +55,8 @@ extern struct L2CA_ReadRemoteVersion L2CA_ReadRemoteVersion; // Returns: uint8_t* struct L2CA_ReadRemoteFeatures { std::function body{ - [](const RawAddress& addr) { return nullptr; }}; - uint8_t* operator()(const RawAddress& addr) { return body(addr); }; + [](const RawAddress& addr) { return nullptr; }}; + uint8_t* operator()(const RawAddress& addr) { return body(addr); } }; extern struct L2CA_ReadRemoteFeatures L2CA_ReadRemoteFeatures; // Name: L2CA_Register @@ -65,20 +64,18 @@ extern struct L2CA_ReadRemoteFeatures L2CA_ReadRemoteFeatures; // enable_snoop, tL2CAP_ERTM_INFO* p_ertm_info, uint16_t my_mtu, uint16_t // required_remote_mtu, uint16_t sec_level Returns: uint16_t struct L2CA_Register { - std::function - body{[](uint16_t client_psm, const tL2CAP_APPL_INFO& callbacks, - bool enable_snoop, tL2CAP_ERTM_INFO* p_ertm_info, uint16_t my_mtu, - uint16_t required_remote_mtu, uint16_t sec_level) { return 0; }}; - uint16_t operator()(uint16_t client_psm, const tL2CAP_APPL_INFO& callbacks, - bool enable_snoop, tL2CAP_ERTM_INFO* p_ertm_info, - uint16_t my_mtu, uint16_t required_remote_mtu, + std::function + body{[](uint16_t client_psm, const tL2CAP_APPL_INFO& callbacks, bool enable_snoop, + tL2CAP_ERTM_INFO* p_ertm_info, uint16_t my_mtu, uint16_t required_remote_mtu, + uint16_t sec_level) { return 0; }}; + uint16_t operator()(uint16_t client_psm, const tL2CAP_APPL_INFO& callbacks, bool enable_snoop, + tL2CAP_ERTM_INFO* p_ertm_info, uint16_t my_mtu, uint16_t required_remote_mtu, uint16_t sec_level) { - return body(client_psm, callbacks, enable_snoop, p_ertm_info, my_mtu, - required_remote_mtu, sec_level); - }; + return body(client_psm, callbacks, enable_snoop, p_ertm_info, my_mtu, required_remote_mtu, + sec_level); + } }; extern struct L2CA_Register L2CA_Register; // Name: L2CA_Deregister @@ -86,7 +83,7 @@ extern struct L2CA_Register L2CA_Register; // Returns: void struct L2CA_Deregister { std::function body{[](uint16_t psm) {}}; - void operator()(uint16_t psm) { body(psm); }; + void operator()(uint16_t psm) { body(psm); } }; extern struct L2CA_Deregister L2CA_Deregister; // Name: L2CA_ConnectReq @@ -94,10 +91,10 @@ extern struct L2CA_Deregister L2CA_Deregister; // Returns: uint16_t struct L2CA_ConnectReq { std::function body{ - [](uint16_t psm, const RawAddress& raw_address) { return 0; }}; + [](uint16_t psm, const RawAddress& raw_address) { return 0; }}; uint16_t operator()(uint16_t psm, const RawAddress& raw_address) { return body(psm, raw_address); - }; + } }; extern struct L2CA_ConnectReq L2CA_ConnectReq; // Name: L2CA_DisconnectReq @@ -105,7 +102,7 @@ extern struct L2CA_ConnectReq L2CA_ConnectReq; // Returns: bool struct L2CA_DisconnectReq { std::function body{[](uint16_t cid) { return false; }}; - bool operator()(uint16_t cid) { return body(cid); }; + bool operator()(uint16_t cid) { return body(cid); } }; extern struct L2CA_DisconnectReq L2CA_DisconnectReq; // Name: L2CA_DataWrite @@ -113,10 +110,8 @@ extern struct L2CA_DisconnectReq L2CA_DisconnectReq; // Returns: uint8_t struct L2CA_DataWrite { std::function body{ - [](uint16_t cid, BT_HDR* p_data) { return 0; }}; - uint8_t operator()(uint16_t cid, BT_HDR* p_data) { - return body(cid, p_data); - }; + [](uint16_t cid, BT_HDR* p_data) { return 0; }}; + uint8_t operator()(uint16_t cid, BT_HDR* p_data) { return body(cid, p_data); } }; extern struct L2CA_DataWrite L2CA_DataWrite; // Name: L2CA_ReconfigCreditBasedConnsReq @@ -125,12 +120,12 @@ extern struct L2CA_DataWrite L2CA_DataWrite; struct L2CA_ReconfigCreditBasedConnsReq { std::function& lcids, tL2CAP_LE_CFG_INFO* p_cfg)> - body{[](const RawAddress& bd_addr, std::vector& lcids, - tL2CAP_LE_CFG_INFO* p_cfg) { return false; }}; + body{[](const RawAddress& bd_addr, std::vector& lcids, + tL2CAP_LE_CFG_INFO* p_cfg) { return false; }}; bool operator()(const RawAddress& bd_addr, std::vector& lcids, tL2CAP_LE_CFG_INFO* p_cfg) { return body(bd_addr, lcids, p_cfg); - }; + } }; extern struct L2CA_ReconfigCreditBasedConnsReq L2CA_ReconfigCreditBasedConnsReq; // Name: L2CA_ConnectCreditBasedReq @@ -140,43 +135,40 @@ struct L2CA_ConnectCreditBasedReq { std::vector cids; std::function(uint16_t psm, const RawAddress& p_bd_addr, tL2CAP_LE_CFG_INFO* p_cfg)> - body{[this](uint16_t psm, const RawAddress& p_bd_addr, - tL2CAP_LE_CFG_INFO* p_cfg) { return cids; }}; + body{[this](uint16_t psm, const RawAddress& p_bd_addr, tL2CAP_LE_CFG_INFO* p_cfg) { + return cids; + }}; std::vector operator()(uint16_t psm, const RawAddress& p_bd_addr, tL2CAP_LE_CFG_INFO* p_cfg) { return body(psm, p_bd_addr, p_cfg); - }; + } }; extern struct L2CA_ConnectCreditBasedReq L2CA_ConnectCreditBasedReq; // Name: L2CA_ConnectCreditBasedRsp // Params: const RawAddress& bd_addr, uint8_t id, std::vector& // accepted_lcids, uint16_t result, tL2CAP_LE_CFG_INFO* p_cfg Returns: bool struct L2CA_ConnectCreditBasedRsp { - std::function& accepted_lcids, uint16_t result, - tL2CAP_LE_CFG_INFO* p_cfg)> - body{[](const RawAddress& bd_addr, uint8_t id, - std::vector& accepted_lcids, uint16_t result, - tL2CAP_LE_CFG_INFO* p_cfg) { return false; }}; - bool operator()(const RawAddress& bd_addr, uint8_t id, - std::vector& accepted_lcids, uint16_t result, - tL2CAP_LE_CFG_INFO* p_cfg) { + std::function& accepted_lcids, + uint16_t result, tL2CAP_LE_CFG_INFO* p_cfg)> + body{[](const RawAddress& bd_addr, uint8_t id, std::vector& accepted_lcids, + uint16_t result, tL2CAP_LE_CFG_INFO* p_cfg) { return false; }}; + bool operator()(const RawAddress& bd_addr, uint8_t id, std::vector& accepted_lcids, + uint16_t result, tL2CAP_LE_CFG_INFO* p_cfg) { return body(bd_addr, id, accepted_lcids, result, p_cfg); - }; + } }; extern struct L2CA_ConnectCreditBasedRsp L2CA_ConnectCreditBasedRsp; // Name: L2CA_SetIdleTimeoutByBdAddr // Params: const RawAddress& bd_addr, uint16_t timeout, tBT_TRANSPORT transport // Returns: bool struct L2CA_SetIdleTimeoutByBdAddr { - std::function - body{[](const RawAddress& bd_addr, uint16_t timeout, - tBT_TRANSPORT transport) { return false; }}; - bool operator()(const RawAddress& bd_addr, uint16_t timeout, - tBT_TRANSPORT transport) { + std::function body{ + [](const RawAddress& bd_addr, uint16_t timeout, tBT_TRANSPORT transport) { + return false; + }}; + bool operator()(const RawAddress& bd_addr, uint16_t timeout, tBT_TRANSPORT transport) { return body(bd_addr, timeout, transport); - }; + } }; extern struct L2CA_SetIdleTimeoutByBdAddr L2CA_SetIdleTimeoutByBdAddr; // Name: L2CA_SetAclPriority @@ -184,10 +176,8 @@ extern struct L2CA_SetIdleTimeoutByBdAddr L2CA_SetIdleTimeoutByBdAddr; // Returns: bool struct L2CA_SetAclPriority { std::function body{ - [](uint16_t handle, bool high_priority) { return false; }}; - bool operator()(uint16_t handle, bool high_priority) { - return body(handle, high_priority); - }; + [](uint16_t handle, bool high_priority) { return false; }}; + bool operator()(uint16_t handle, bool high_priority) { return body(handle, high_priority); } }; extern struct L2CA_SetAclPriority L2CA_SetAclPriority; // Name: L2CA_SetAclPriority @@ -195,26 +185,23 @@ extern struct L2CA_SetAclPriority L2CA_SetAclPriority; // Returns: bool struct L2CA_SetAclPriority2 { std::function body{ - [](const RawAddress& bd_addr, tL2CAP_PRIORITY priority) { - return false; - }}; + [](const RawAddress& bd_addr, tL2CAP_PRIORITY priority) { return false; }}; bool operator()(const RawAddress& bd_addr, tL2CAP_PRIORITY priority) { return body(bd_addr, priority); - }; + } }; extern struct L2CA_SetAclPriority2 L2CA_SetAclPriority2; // Name: L2CA_GetPeerFeatures // Params: const RawAddress& bd_addr, uint32_t* p_ext_feat, uint8_t* p_chnl_mask // Returns: bool struct L2CA_GetPeerFeatures { - std::function - body{[](const RawAddress& bd_addr, uint32_t* p_ext_feat, - uint8_t* p_chnl_mask) { return false; }}; - bool operator()(const RawAddress& bd_addr, uint32_t* p_ext_feat, - uint8_t* p_chnl_mask) { + std::function body{ + [](const RawAddress& bd_addr, uint32_t* p_ext_feat, uint8_t* p_chnl_mask) { + return false; + }}; + bool operator()(const RawAddress& bd_addr, uint32_t* p_ext_feat, uint8_t* p_chnl_mask) { return body(bd_addr, p_ext_feat, p_chnl_mask); - }; + } }; extern struct L2CA_GetPeerFeatures L2CA_GetPeerFeatures; // Name: L2CA_RegisterFixedChannel @@ -222,10 +209,8 @@ extern struct L2CA_GetPeerFeatures L2CA_GetPeerFeatures; // Returns: bool struct L2CA_RegisterFixedChannel { std::function body{ - [](uint16_t cid, tL2CAP_FIXED_CHNL_REG* p_freg) { return false; }}; - bool operator()(uint16_t cid, tL2CAP_FIXED_CHNL_REG* p_freg) { - return body(cid, p_freg); - }; + [](uint16_t cid, tL2CAP_FIXED_CHNL_REG* p_freg) { return false; }}; + bool operator()(uint16_t cid, tL2CAP_FIXED_CHNL_REG* p_freg) { return body(cid, p_freg); } }; extern struct L2CA_RegisterFixedChannel L2CA_RegisterFixedChannel; // Name: L2CA_ConnectFixedChnl @@ -233,24 +218,19 @@ extern struct L2CA_RegisterFixedChannel L2CA_RegisterFixedChannel; // Returns: bool struct L2CA_ConnectFixedChnl { std::function body{ - [](uint16_t cid, const RawAddress& rem_bda) { return false; }}; - bool operator()(uint16_t cid, const RawAddress& rem_bda) { - return body(cid, rem_bda); - }; + [](uint16_t cid, const RawAddress& rem_bda) { return false; }}; + bool operator()(uint16_t cid, const RawAddress& rem_bda) { return body(cid, rem_bda); } }; extern struct L2CA_ConnectFixedChnl L2CA_ConnectFixedChnl; // Name: L2CA_SendFixedChnlData // Params: uint16_t cid, const RawAddress& rem_bda, BT_HDR* p_buf // Returns: uint16_t struct L2CA_SendFixedChnlData { - std::function - body{[](uint16_t cid, const RawAddress& rem_bda, BT_HDR* p_buf) { - return 0; - }}; + std::function body{ + [](uint16_t cid, const RawAddress& rem_bda, BT_HDR* p_buf) { return 0; }}; uint16_t operator()(uint16_t cid, const RawAddress& rem_bda, BT_HDR* p_buf) { return body(cid, rem_bda, p_buf); - }; + } }; extern struct L2CA_SendFixedChnlData L2CA_SendFixedChnlData; // Name: L2CA_RemoveFixedChnl @@ -258,10 +238,8 @@ extern struct L2CA_SendFixedChnlData L2CA_SendFixedChnlData; // Returns: bool struct L2CA_RemoveFixedChnl { std::function body{ - [](uint16_t cid, const RawAddress& rem_bda) { return false; }}; - bool operator()(uint16_t cid, const RawAddress& rem_bda) { - return body(cid, rem_bda); - }; + [](uint16_t cid, const RawAddress& rem_bda) { return false; }}; + bool operator()(uint16_t cid, const RawAddress& rem_bda) { return body(cid, rem_bda); } }; extern struct L2CA_RemoveFixedChnl L2CA_RemoveFixedChnl; // Name: L2CA_GetLeHandle @@ -269,8 +247,8 @@ extern struct L2CA_RemoveFixedChnl L2CA_RemoveFixedChnl; // Returns: uint16_t struct L2CA_GetLeHandle { std::function body{ - [](const RawAddress& rem_bda) { return 0; }}; - uint16_t operator()(const RawAddress& rem_bda) { return body(rem_bda); }; + [](const RawAddress& rem_bda) { return 0; }}; + uint16_t operator()(const RawAddress& rem_bda) { return body(rem_bda); } }; extern struct L2CA_GetLeHandle L2CA_GetLeHandle; // Name: L2CA_LeConnectionUpdate @@ -278,17 +256,14 @@ extern struct L2CA_GetLeHandle L2CA_GetLeHandle; // uint16_t latency, uint16_t timeout, uint16_t min_ce_len, uint16_t max_ce_len // Returns: void struct L2CA_LeConnectionUpdate { - std::function - body{[](const RawAddress& rem_bda, uint16_t min_int, uint16_t max_int, - uint16_t latency, uint16_t timeout, uint16_t min_ce_len, - uint16_t max_ce_len) {}}; - void operator()(const RawAddress& rem_bda, uint16_t min_int, uint16_t max_int, - uint16_t latency, uint16_t timeout, uint16_t min_ce_len, - uint16_t max_ce_len) { + std::function + body{[](const RawAddress& rem_bda, uint16_t min_int, uint16_t max_int, uint16_t latency, + uint16_t timeout, uint16_t min_ce_len, uint16_t max_ce_len) {}}; + void operator()(const RawAddress& rem_bda, uint16_t min_int, uint16_t max_int, uint16_t latency, + uint16_t timeout, uint16_t min_ce_len, uint16_t max_ce_len) { body(rem_bda, min_int, max_int, latency, timeout, min_ce_len, max_ce_len); - }; + } }; extern struct L2CA_LeConnectionUpdate L2CA_LeConnectionUpdate; // Name: L2CA_LockBleConnParamsForServiceDiscovery @@ -296,34 +271,26 @@ extern struct L2CA_LeConnectionUpdate L2CA_LeConnectionUpdate; // Returns: void struct L2CA_LockBleConnParamsForServiceDiscovery { std::function body{ - [](const RawAddress& rem_bda, bool enable) { return false; }}; - void operator()(const RawAddress& rem_bda, bool enable) { - return body(rem_bda, enable); - }; + [](const RawAddress& rem_bda, bool enable) { return false; }}; + void operator()(const RawAddress& rem_bda, bool enable) { return body(rem_bda, enable); } }; -extern struct L2CA_LockBleConnParamsForServiceDiscovery - L2CA_LockBleConnParamsForServiceDiscovery; +extern struct L2CA_LockBleConnParamsForServiceDiscovery L2CA_LockBleConnParamsForServiceDiscovery; // Name: L2CA_LockBleConnParamsForProfileConnection // Params: const RawAddress& rem_bda, bool enable // Returns: void struct L2CA_LockBleConnParamsForProfileConnection { std::function body{ - [](const RawAddress& rem_bda, bool enable) { return false; }}; - void operator()(const RawAddress& rem_bda, bool enable) { - return body(rem_bda, enable); - }; + [](const RawAddress& rem_bda, bool enable) { return false; }}; + void operator()(const RawAddress& rem_bda, bool enable) { return body(rem_bda, enable); } }; -extern struct L2CA_LockBleConnParamsForProfileConnection - L2CA_LockBleConnParamsForProfileConnection; +extern struct L2CA_LockBleConnParamsForProfileConnection L2CA_LockBleConnParamsForProfileConnection; // Name: L2CA_SetTxPriority // Params: uint16_t cid, tL2CAP_CHNL_PRIORITY priority // Returns: bool struct L2CA_SetTxPriority { std::function body{ - [](uint16_t cid, tL2CAP_CHNL_PRIORITY priority) { return false; }}; - bool operator()(uint16_t cid, tL2CAP_CHNL_PRIORITY priority) { - return body(cid, priority); - }; + [](uint16_t cid, tL2CAP_CHNL_PRIORITY priority) { return false; }}; + bool operator()(uint16_t cid, tL2CAP_CHNL_PRIORITY priority) { return body(cid, priority); } }; extern struct L2CA_SetTxPriority L2CA_SetTxPriority; // Name: L2CA_SetLeGattTimeout @@ -331,10 +298,10 @@ extern struct L2CA_SetTxPriority L2CA_SetTxPriority; // Returns: bool struct L2CA_SetLeGattTimeout { std::function body{ - [](const RawAddress& rem_bda, uint16_t idle_tout) { return false; }}; + [](const RawAddress& rem_bda, uint16_t idle_tout) { return false; }}; bool operator()(const RawAddress& rem_bda, uint16_t idle_tout) { return body(rem_bda, idle_tout); - }; + } }; extern struct L2CA_SetLeGattTimeout L2CA_SetLeGattTimeout; // Name: L2CA_SetChnlFlushability @@ -342,10 +309,8 @@ extern struct L2CA_SetLeGattTimeout L2CA_SetLeGattTimeout; // Returns: bool struct L2CA_SetChnlFlushability { std::function body{ - [](uint16_t cid, bool is_flushable) { return false; }}; - bool operator()(uint16_t cid, bool is_flushable) { - return body(cid, is_flushable); - }; + [](uint16_t cid, bool is_flushable) { return false; }}; + bool operator()(uint16_t cid, bool is_flushable) { return body(cid, is_flushable); } }; extern struct L2CA_SetChnlFlushability L2CA_SetChnlFlushability; // Name: L2CA_FlushChannel @@ -353,10 +318,8 @@ extern struct L2CA_SetChnlFlushability L2CA_SetChnlFlushability; // Returns: uint16_t struct L2CA_FlushChannel { std::function body{ - [](uint16_t lcid, uint16_t num_to_flush) { return 0; }}; - uint16_t operator()(uint16_t lcid, uint16_t num_to_flush) { - return body(lcid, num_to_flush); - }; + [](uint16_t lcid, uint16_t num_to_flush) { return 0; }}; + uint16_t operator()(uint16_t lcid, uint16_t num_to_flush) { return body(lcid, num_to_flush); } }; extern struct L2CA_FlushChannel L2CA_FlushChannel; // Name: L2CA_IsLinkEstablished @@ -364,19 +327,18 @@ extern struct L2CA_FlushChannel L2CA_FlushChannel; // Returns: bool struct L2CA_IsLinkEstablished { std::function body{ - [](const RawAddress& bd_addr, tBT_TRANSPORT transport) { return false; }}; + [](const RawAddress& bd_addr, tBT_TRANSPORT transport) { return false; }}; bool operator()(const RawAddress& bd_addr, tBT_TRANSPORT transport) { return body(bd_addr, transport); - }; + } }; extern struct L2CA_IsLinkEstablished L2CA_IsLinkEstablished; // Name: L2CA_IsLeLink // Params: uint16_t acl_handle // Returns: bool struct L2CA_IsLeLink { - std::function body{ - [](uint16_t acl_handle) { return false; }}; - bool operator()(uint16_t acl_handle) { return body(acl_handle); }; + std::function body{[](uint16_t acl_handle) { return false; }}; + bool operator()(uint16_t acl_handle) { return body(acl_handle); } }; extern struct L2CA_IsLeLink L2CA_IsLeLink; // Name: L2CA_ReadConnectionAddr @@ -385,12 +347,12 @@ extern struct L2CA_IsLeLink L2CA_IsLeLink; struct L2CA_ReadConnectionAddr { std::function - body{[](const RawAddress& pseudo_addr, RawAddress& conn_addr, - tBLE_ADDR_TYPE* p_addr_type) {}}; + body{[](const RawAddress& pseudo_addr, RawAddress& conn_addr, + tBLE_ADDR_TYPE* p_addr_type) {}}; void operator()(const RawAddress& pseudo_addr, RawAddress& conn_addr, tBLE_ADDR_TYPE* p_addr_type) { body(pseudo_addr, conn_addr, p_addr_type); - }; + } }; extern struct L2CA_ReadConnectionAddr L2CA_ReadConnectionAddr; // Name: L2CA_ReadRemoteConnectionAddr @@ -399,12 +361,12 @@ extern struct L2CA_ReadConnectionAddr L2CA_ReadConnectionAddr; struct L2CA_ReadRemoteConnectionAddr { std::function - body{[](const RawAddress& pseudo_addr, RawAddress& conn_addr, - tBLE_ADDR_TYPE* p_addr_type) { return false; }}; + body{[](const RawAddress& pseudo_addr, RawAddress& conn_addr, + tBLE_ADDR_TYPE* p_addr_type) { return false; }}; bool operator()(const RawAddress& pseudo_addr, RawAddress& conn_addr, tBLE_ADDR_TYPE* p_addr_type) { return body(pseudo_addr, conn_addr, p_addr_type); - }; + } }; extern struct L2CA_ReadRemoteConnectionAddr L2CA_ReadRemoteConnectionAddr; // Name: L2CA_GetBleConnRole @@ -412,17 +374,16 @@ extern struct L2CA_ReadRemoteConnectionAddr L2CA_ReadRemoteConnectionAddr; // Returns: hci_role_t struct L2CA_GetBleConnRole { std::function body{ - [](const RawAddress& bd_addr) { return HCI_ROLE_CENTRAL; }}; - hci_role_t operator()(const RawAddress& bd_addr) { return body(bd_addr); }; + [](const RawAddress& bd_addr) { return HCI_ROLE_CENTRAL; }}; + hci_role_t operator()(const RawAddress& bd_addr) { return body(bd_addr); } }; extern struct L2CA_GetBleConnRole L2CA_GetBleConnRole; // Name: L2CA_ConnectForSecurity // Params: const RawAddress& bd_addr // Returns: void struct L2CA_ConnectForSecurity { - std::function body{ - [](const RawAddress& bd_addr) {}}; - void operator()(const RawAddress& bd_addr) { body(bd_addr); }; + std::function body{[](const RawAddress& bd_addr) {}}; + void operator()(const RawAddress& bd_addr) { body(bd_addr); } }; extern struct L2CA_ConnectForSecurity L2CA_ConnectForSecurity; // Name: L2CA_SetBondingState @@ -430,19 +391,16 @@ extern struct L2CA_ConnectForSecurity L2CA_ConnectForSecurity; // Returns: void struct L2CA_SetBondingState { std::function body{ - [](const RawAddress& bd_addr, bool is_bonding) {}}; - void operator()(const RawAddress& bd_addr, bool is_bonding) { - body(bd_addr, is_bonding); - }; + [](const RawAddress& bd_addr, bool is_bonding) {}}; + void operator()(const RawAddress& bd_addr, bool is_bonding) { body(bd_addr, is_bonding); } }; extern struct L2CA_SetBondingState L2CA_SetBondingState; // Name: L2CA_DisconnectLink // Params: const RawAddress& remote // Returns: void struct L2CA_DisconnectLink { - std::function body{ - [](const RawAddress& remote) {}}; - void operator()(const RawAddress& remote) { body(remote); }; + std::function body{[](const RawAddress& remote) {}}; + void operator()(const RawAddress& remote) { body(remote); } }; extern struct L2CA_DisconnectLink L2CA_DisconnectLink; // Name: L2CA_GetNumLinks @@ -450,7 +408,7 @@ extern struct L2CA_DisconnectLink L2CA_DisconnectLink; // Returns: uint16_t struct L2CA_GetNumLinks { std::function body{[]() { return 0; }}; - uint16_t operator()() { return body(); }; + uint16_t operator()() { return body(); } }; extern struct L2CA_GetNumLinks L2CA_GetNumLinks; // Name: L2CA_AllocateLePSM @@ -458,7 +416,7 @@ extern struct L2CA_GetNumLinks L2CA_GetNumLinks; // Returns: uint16_t struct L2CA_AllocateLePSM { std::function body{[]() { return 0; }}; - uint16_t operator()() { return body(); }; + uint16_t operator()() { return body(); } }; extern struct L2CA_AllocateLePSM L2CA_AllocateLePSM; // Name: L2CA_FreeLePSM @@ -466,21 +424,21 @@ extern struct L2CA_AllocateLePSM L2CA_AllocateLePSM; // Returns: void struct L2CA_FreeLePSM { std::function body{[](uint16_t psm) {}}; - void operator()(uint16_t psm) { body(psm); }; + void operator()(uint16_t psm) { body(psm); } }; extern struct L2CA_FreeLePSM L2CA_FreeLePSM; // Name: L2CA_RegisterLECoc // Params: uint16_t psm, const tL2CAP_APPL_INFO& callbacks, uint16_t sec_level, // tL2CAP_LE_CFG_INFO cfg Returns: uint16_t struct L2CA_RegisterLECoc { - std::function - body{[](uint16_t psm, const tL2CAP_APPL_INFO& callbacks, - uint16_t sec_level, tL2CAP_LE_CFG_INFO cfg) { return 0; }}; - uint16_t operator()(uint16_t psm, const tL2CAP_APPL_INFO& callbacks, - uint16_t sec_level, tL2CAP_LE_CFG_INFO cfg) { + std::function + body{[](uint16_t psm, const tL2CAP_APPL_INFO& callbacks, uint16_t sec_level, + tL2CAP_LE_CFG_INFO cfg) { return 0; }}; + uint16_t operator()(uint16_t psm, const tL2CAP_APPL_INFO& callbacks, uint16_t sec_level, + tL2CAP_LE_CFG_INFO cfg) { return body(psm, callbacks, sec_level, cfg); - }; + } }; extern struct L2CA_RegisterLECoc L2CA_RegisterLECoc; // Name: L2CA_DeregisterLECoc @@ -488,21 +446,20 @@ extern struct L2CA_RegisterLECoc L2CA_RegisterLECoc; // Returns: void struct L2CA_DeregisterLECoc { std::function body{[](uint16_t psm) {}}; - void operator()(uint16_t psm) { body(psm); }; + void operator()(uint16_t psm) { body(psm); } }; extern struct L2CA_DeregisterLECoc L2CA_DeregisterLECoc; // Name: L2CA_ConnectLECocReq // Params: uint16_t psm, const RawAddress& p_bd_addr, tL2CAP_LE_CFG_INFO* p_cfg // Returns: uint16_t struct L2CA_ConnectLECocReq { - std::function - body{[](uint16_t psm, const RawAddress& p_bd_addr, - tL2CAP_LE_CFG_INFO* p_cfg) { return 0; }}; - uint16_t operator()(uint16_t psm, const RawAddress& p_bd_addr, - tL2CAP_LE_CFG_INFO* p_cfg) { + std::function + body{[](uint16_t psm, const RawAddress& p_bd_addr, tL2CAP_LE_CFG_INFO* p_cfg) { + return 0; + }}; + uint16_t operator()(uint16_t psm, const RawAddress& p_bd_addr, tL2CAP_LE_CFG_INFO* p_cfg) { return body(psm, p_bd_addr, p_cfg); - }; + } }; extern struct L2CA_ConnectLECocReq L2CA_ConnectLECocReq; // Name: L2CA_GetPeerLECocConfig @@ -510,10 +467,8 @@ extern struct L2CA_ConnectLECocReq L2CA_ConnectLECocReq; // Returns: bool struct L2CA_GetPeerLECocConfig { std::function body{ - [](uint16_t cid, tL2CAP_LE_CFG_INFO* peer_cfg) { return false; }}; - bool operator()(uint16_t cid, tL2CAP_LE_CFG_INFO* peer_cfg) { - return body(cid, peer_cfg); - }; + [](uint16_t cid, tL2CAP_LE_CFG_INFO* peer_cfg) { return false; }}; + bool operator()(uint16_t cid, tL2CAP_LE_CFG_INFO* peer_cfg) { return body(cid, peer_cfg); } }; extern struct L2CA_GetPeerLECocConfig L2CA_GetPeerLECocConfig; // Name: L2CA_DisconnectLECocReq @@ -521,7 +476,7 @@ extern struct L2CA_GetPeerLECocConfig L2CA_GetPeerLECocConfig; // Returns: bool struct L2CA_DisconnectLECocReq { std::function body{[](uint16_t cid) { return false; }}; - bool operator()(uint16_t cid) { return body(cid); }; + bool operator()(uint16_t cid) { return body(cid); } }; extern struct L2CA_DisconnectLECocReq L2CA_DisconnectLECocReq; // Name: L2CA_LECocDataWrite @@ -529,19 +484,16 @@ extern struct L2CA_DisconnectLECocReq L2CA_DisconnectLECocReq; // Returns: uint8_t struct L2CA_LECocDataWrite { std::function body{ - [](uint16_t cid, BT_HDR* p_data) { return 0; }}; - uint8_t operator()(uint16_t cid, BT_HDR* p_data) { - return body(cid, p_data); - }; + [](uint16_t cid, BT_HDR* p_data) { return 0; }}; + uint8_t operator()(uint16_t cid, BT_HDR* p_data) { return body(cid, p_data); } }; extern struct L2CA_LECocDataWrite L2CA_LECocDataWrite; // Name: L2CA_SwitchRoleToCentral // Params: const RawAddress& addr // Returns: void struct L2CA_SwitchRoleToCentral { - std::function body{ - [](const RawAddress& addr) {}}; - void operator()(const RawAddress& addr) { body(addr); }; + std::function body{[](const RawAddress& addr) {}}; + void operator()(const RawAddress& addr) { body(addr); } }; extern struct L2CA_SwitchRoleToCentral L2CA_SwitchRoleToCentral; diff --git a/system/test/mock/mock_main_shim_le_advertising_manager.cc b/system/test/mock/mock_main_shim_le_advertising_manager.cc index a137f25a53d..7f666e55f6a 100644 --- a/system/test/mock/mock_main_shim_le_advertising_manager.cc +++ b/system/test/mock/mock_main_shim_le_advertising_manager.cc @@ -36,9 +36,7 @@ void MockBleAdvertisingManager::CleanUp() { bt_le_advertiser_instance = nullptr; } -MockBleAdvertisingManager* MockBleAdvertisingManager::Get() { - return bt_le_advertiser_instance; -} +MockBleAdvertisingManager* MockBleAdvertisingManager::Get() { return bt_le_advertiser_instance; } BleAdvertiserInterface* bluetooth::shim::get_ble_advertiser_instance() { return static_cast(bt_le_advertiser_instance); diff --git a/system/test/mock/mock_main_shim_le_advertising_manager.h b/system/test/mock/mock_main_shim_le_advertising_manager.h index 9f60b58aed6..cc2f7a4b1e9 100644 --- a/system/test/mock/mock_main_shim_le_advertising_manager.h +++ b/system/test/mock/mock_main_shim_le_advertising_manager.h @@ -27,11 +27,10 @@ #include "include/hardware/ble_advertiser.h" class MockBleAdvertisingManager : public BleAdvertiserInterface { - public: +public: MockBleAdvertisingManager() = default; MockBleAdvertisingManager(const MockBleAdvertisingManager&) = delete; - MockBleAdvertisingManager& operator=(const MockBleAdvertisingManager&) = - delete; + MockBleAdvertisingManager& operator=(const MockBleAdvertisingManager&) = delete; ~MockBleAdvertisingManager() override = default; @@ -40,51 +39,38 @@ class MockBleAdvertisingManager : public BleAdvertiserInterface { static MockBleAdvertisingManager* Get(); MOCK_METHOD((void), StartAdvertising, - (uint8_t advertiser_id, StatusCallback cb, - AdvertiseParameters params, std::vector advertise_data, - std::vector scan_response_data, int timeout_s, - StatusCallback timeout_cb), + (uint8_t advertiser_id, StatusCallback cb, AdvertiseParameters params, + std::vector advertise_data, std::vector scan_response_data, + int timeout_s, StatusCallback timeout_cb), (override)); MOCK_METHOD((void), StartAdvertisingSet, - (uint8_t client_id, int reg_id, - IdTxPowerStatusCallback register_cb, AdvertiseParameters params, - std::vector advertise_data, + (uint8_t client_id, int reg_id, IdTxPowerStatusCallback register_cb, + AdvertiseParameters params, std::vector advertise_data, std::vector scan_response_data, - PeriodicAdvertisingParameters periodic_params, - std::vector periodic_data, uint16_t duration, - uint8_t maxExtAdvEvents, IdStatusCallback timeout_cb), + PeriodicAdvertisingParameters periodic_params, std::vector periodic_data, + uint16_t duration, uint8_t maxExtAdvEvents, IdStatusCallback timeout_cb), (override)); MOCK_METHOD((void), RegisterAdvertiser, (IdStatusCallback cb), (override)); MOCK_METHOD((void), Enable, - (uint8_t advertiser_id, bool enable, StatusCallback cb, - uint16_t duration, uint8_t maxExtAdvEvents, - StatusCallback timeout_cb), + (uint8_t advertiser_id, bool enable, StatusCallback cb, uint16_t duration, + uint8_t maxExtAdvEvents, StatusCallback timeout_cb), (override)); MOCK_METHOD((void), SetParameters, - (uint8_t advertiser_id, AdvertiseParameters params, - ParametersCallback cb), + (uint8_t advertiser_id, AdvertiseParameters params, ParametersCallback cb), (override)); MOCK_METHOD((void), SetData, - (int advertiser_id, bool set_scan_rsp, std::vector data, - StatusCallback cb), + (int advertiser_id, bool set_scan_rsp, std::vector data, StatusCallback cb), (override)); MOCK_METHOD((void), SetPeriodicAdvertisingParameters, - (int advertiser_id, PeriodicAdvertisingParameters periodic_params, - StatusCallback cb), + (int advertiser_id, PeriodicAdvertisingParameters periodic_params, StatusCallback cb), (override)); MOCK_METHOD((void), SetPeriodicAdvertisingData, - (int advertiser_id, std::vector data, StatusCallback cb), - (override)); + (int advertiser_id, std::vector data, StatusCallback cb), (override)); MOCK_METHOD((void), SetPeriodicAdvertisingEnable, - (int advertiser_id, bool enable, bool include_adi, - StatusCallback cb), - (override)); + (int advertiser_id, bool enable, bool include_adi, StatusCallback cb), (override)); MOCK_METHOD((void), Unregister, (uint8_t advertiser_id), (override)); - MOCK_METHOD((void), GetOwnAddress, - (uint8_t advertiser_id, GetAddressCallback cb), (override)); - MOCK_METHOD((void), RegisterCallbacks, (AdvertisingCallbacks * callbacks), - (override)); + MOCK_METHOD((void), GetOwnAddress, (uint8_t advertiser_id, GetAddressCallback cb), (override)); + MOCK_METHOD((void), RegisterCallbacks, (AdvertisingCallbacks * callbacks), (override)); MOCK_METHOD((void), RegisterCallbacksNative, - (AdvertisingCallbacks * callbacks, uint8_t client_id), - (override)); + (AdvertisingCallbacks * callbacks, uint8_t client_id), (override)); }; diff --git a/system/test/mock/mock_main_shim_le_scanning_manager.cc b/system/test/mock/mock_main_shim_le_scanning_manager.cc index d43b758cf4a..ce4b5d1b7e1 100644 --- a/system/test/mock/mock_main_shim_le_scanning_manager.cc +++ b/system/test/mock/mock_main_shim_le_scanning_manager.cc @@ -34,13 +34,9 @@ bool bluetooth::shim::is_ad_type_filter_supported() { return false; } -void bluetooth::shim::set_ad_type_rsi_filter(bool /* enable */) { - inc_func_call_count(__func__); -} +void bluetooth::shim::set_ad_type_rsi_filter(bool /* enable */) { inc_func_call_count(__func__); } -void bluetooth::shim::set_empty_filter(bool /* enable */) { - inc_func_call_count(__func__); -} +void bluetooth::shim::set_empty_filter(bool /* enable */) { inc_func_call_count(__func__); } void bluetooth::shim::set_target_announcements_filter(bool /* enable */) { inc_func_call_count(__func__); diff --git a/system/test/mock/mock_main_shim_metric_id_api.cc b/system/test/mock/mock_main_shim_metric_id_api.cc index afd5135289b..bc8eff74032 100644 --- a/system/test/mock/mock_main_shim_metric_id_api.cc +++ b/system/test/mock/mock_main_shim_metric_id_api.cc @@ -26,10 +26,9 @@ namespace bluetooth { namespace shim { -bool InitMetricIdAllocator( - const std::unordered_map& /* paired_device_map */, - CallbackLegacy /* save_id_callback */, - CallbackLegacy /* forget_device_callback */) { +bool InitMetricIdAllocator(const std::unordered_map& /* paired_device_map */, + CallbackLegacy /* save_id_callback */, + CallbackLegacy /* forget_device_callback */) { inc_func_call_count(__func__); return false; } diff --git a/system/test/mock/mock_main_shim_metrics_api.cc b/system/test/mock/mock_main_shim_metrics_api.cc index a9869c950c5..e2abaf73391 100644 --- a/system/test/mock/mock_main_shim_metrics_api.cc +++ b/system/test/mock/mock_main_shim_metrics_api.cc @@ -47,8 +47,7 @@ struct LogMetricA2dpSessionMetricsEvent LogMetricA2dpSessionMetricsEvent; struct LogMetricHfpPacketLossStats LogMetricHfpPacketLossStats; struct LogMetricMmcTranscodeRttStats LogMetricMmcTranscodeRttStats; struct LogMetricReadRssiResult LogMetricReadRssiResult; -struct LogMetricReadFailedContactCounterResult - LogMetricReadFailedContactCounterResult; +struct LogMetricReadFailedContactCounterResult LogMetricReadFailedContactCounterResult; struct LogMetricReadTxPowerLevelResult LogMetricReadTxPowerLevelResult; struct LogMetricSmpPairingEvent LogMetricSmpPairingEvent; struct LogMetricClassicPairingEvent LogMetricClassicPairingEvent; @@ -61,152 +60,137 @@ struct LogMetricManufacturerInfo LogMetricManufacturerInfo; } // namespace test // Mocked functions, if any -void bluetooth::shim::LogMetricLinkLayerConnectionEvent( - const RawAddress* raw_address, uint32_t connection_handle, - android::bluetooth::DirectionEnum direction, uint16_t link_type, - uint32_t hci_cmd, uint16_t hci_event, uint16_t hci_ble_event, - uint16_t cmd_status, uint16_t reason_code) { +void bluetooth::shim::LogMetricLinkLayerConnectionEvent(const RawAddress* raw_address, + uint32_t connection_handle, + android::bluetooth::DirectionEnum direction, + uint16_t link_type, uint32_t hci_cmd, + uint16_t hci_event, uint16_t hci_ble_event, + uint16_t cmd_status, uint16_t reason_code) { inc_func_call_count(__func__); test::mock::main_shim_metrics_api::LogMetricLinkLayerConnectionEvent( - raw_address, connection_handle, direction, link_type, hci_cmd, hci_event, - hci_ble_event, cmd_status, reason_code); + raw_address, connection_handle, direction, link_type, hci_cmd, hci_event, hci_ble_event, + cmd_status, reason_code); } -void bluetooth::shim::LogMetricA2dpAudioUnderrunEvent( - const RawAddress& raw_address, uint64_t encoding_interval_millis, - int num_missing_pcm_bytes) { +void bluetooth::shim::LogMetricA2dpAudioUnderrunEvent(const RawAddress& raw_address, + uint64_t encoding_interval_millis, + int num_missing_pcm_bytes) { inc_func_call_count(__func__); test::mock::main_shim_metrics_api::LogMetricA2dpAudioUnderrunEvent( - raw_address, encoding_interval_millis, num_missing_pcm_bytes); + raw_address, encoding_interval_millis, num_missing_pcm_bytes); } -void bluetooth::shim::LogMetricA2dpAudioOverrunEvent( - const RawAddress& raw_address, uint64_t encoding_interval_millis, - int num_dropped_buffers, int num_dropped_encoded_frames, - int num_dropped_encoded_bytes) { +void bluetooth::shim::LogMetricA2dpAudioOverrunEvent(const RawAddress& raw_address, + uint64_t encoding_interval_millis, + int num_dropped_buffers, + int num_dropped_encoded_frames, + int num_dropped_encoded_bytes) { inc_func_call_count(__func__); test::mock::main_shim_metrics_api::LogMetricA2dpAudioOverrunEvent( - raw_address, encoding_interval_millis, num_dropped_buffers, - num_dropped_encoded_frames, num_dropped_encoded_bytes); + raw_address, encoding_interval_millis, num_dropped_buffers, num_dropped_encoded_frames, + num_dropped_encoded_bytes); } -void bluetooth::shim::LogMetricA2dpPlaybackEvent(const RawAddress& raw_address, - int playback_state, +void bluetooth::shim::LogMetricA2dpPlaybackEvent(const RawAddress& raw_address, int playback_state, int audio_coding_mode) { inc_func_call_count(__func__); - test::mock::main_shim_metrics_api::LogMetricA2dpPlaybackEvent( - raw_address, playback_state, audio_coding_mode); + test::mock::main_shim_metrics_api::LogMetricA2dpPlaybackEvent(raw_address, playback_state, + audio_coding_mode); } void bluetooth::shim::LogMetricA2dpSessionMetricsEvent( - const RawAddress& raw_address, int64_t audio_duration_ms, - int media_timer_min_ms, int media_timer_max_ms, - int /* media_timer_avg_ms */, int total_scheduling_count, - int buffer_overruns_max_count, int buffer_overruns_total, - float buffer_underruns_average, int buffer_underruns_count, - int64_t codec_index, bool is_a2dp_offload) { + const RawAddress& raw_address, int64_t audio_duration_ms, int media_timer_min_ms, + int media_timer_max_ms, int /* media_timer_avg_ms */, int total_scheduling_count, + int buffer_overruns_max_count, int buffer_overruns_total, float buffer_underruns_average, + int buffer_underruns_count, int64_t codec_index, bool is_a2dp_offload) { inc_func_call_count(__func__); test::mock::main_shim_metrics_api::LogMetricA2dpSessionMetricsEvent( - raw_address, audio_duration_ms, media_timer_min_ms, media_timer_max_ms, - audio_duration_ms, total_scheduling_count, buffer_overruns_max_count, - buffer_overruns_total, buffer_underruns_average, buffer_underruns_count, - codec_index, is_a2dp_offload); + raw_address, audio_duration_ms, media_timer_min_ms, media_timer_max_ms, audio_duration_ms, + total_scheduling_count, buffer_overruns_max_count, buffer_overruns_total, + buffer_underruns_average, buffer_underruns_count, codec_index, is_a2dp_offload); } void bluetooth::shim::LogMetricHfpPacketLossStats(const RawAddress& raw_address, - int num_decoded_frames, - double packet_loss_ratio, + int num_decoded_frames, double packet_loss_ratio, uint16_t codec_type) { inc_func_call_count(__func__); - test::mock::main_shim_metrics_api::LogMetricHfpPacketLossStats( - raw_address, num_decoded_frames, packet_loss_ratio, codec_type); + test::mock::main_shim_metrics_api::LogMetricHfpPacketLossStats(raw_address, num_decoded_frames, + packet_loss_ratio, codec_type); } -void bluetooth::shim::LogMetricMmcTranscodeRttStats(int maximum_rtt, - double mean_rtt, - int num_requests, - int codec_type) { +void bluetooth::shim::LogMetricMmcTranscodeRttStats(int maximum_rtt, double mean_rtt, + int num_requests, int codec_type) { inc_func_call_count(__func__); - test::mock::main_shim_metrics_api::LogMetricMmcTranscodeRttStats( - maximum_rtt, mean_rtt, num_requests, codec_type); + test::mock::main_shim_metrics_api::LogMetricMmcTranscodeRttStats(maximum_rtt, mean_rtt, + num_requests, codec_type); } -void bluetooth::shim::LogMetricReadRssiResult(const RawAddress& raw_address, - uint16_t handle, - uint32_t cmd_status, - int8_t rssi) { +void bluetooth::shim::LogMetricReadRssiResult(const RawAddress& raw_address, uint16_t handle, + uint32_t cmd_status, int8_t rssi) { inc_func_call_count(__func__); - test::mock::main_shim_metrics_api::LogMetricReadRssiResult( - raw_address, handle, cmd_status, rssi); + test::mock::main_shim_metrics_api::LogMetricReadRssiResult(raw_address, handle, cmd_status, rssi); } -void bluetooth::shim::LogMetricReadFailedContactCounterResult( - const RawAddress& raw_address, uint16_t handle, uint32_t cmd_status, - int32_t failed_contact_counter) { +void bluetooth::shim::LogMetricReadFailedContactCounterResult(const RawAddress& raw_address, + uint16_t handle, uint32_t cmd_status, + int32_t failed_contact_counter) { inc_func_call_count(__func__); test::mock::main_shim_metrics_api::LogMetricReadFailedContactCounterResult( - raw_address, handle, cmd_status, failed_contact_counter); + raw_address, handle, cmd_status, failed_contact_counter); } -void bluetooth::shim::LogMetricReadTxPowerLevelResult( - const RawAddress& raw_address, uint16_t handle, uint32_t cmd_status, - int32_t transmit_power_level) { +void bluetooth::shim::LogMetricReadTxPowerLevelResult(const RawAddress& raw_address, + uint16_t handle, uint32_t cmd_status, + int32_t transmit_power_level) { inc_func_call_count(__func__); test::mock::main_shim_metrics_api::LogMetricReadTxPowerLevelResult( - raw_address, handle, cmd_status, transmit_power_level); + raw_address, handle, cmd_status, transmit_power_level); } -void bluetooth::shim::LogMetricSmpPairingEvent( - const RawAddress& raw_address, uint16_t smp_cmd, - android::bluetooth::DirectionEnum direction, uint16_t smp_fail_reason) { +void bluetooth::shim::LogMetricSmpPairingEvent(const RawAddress& raw_address, uint16_t smp_cmd, + android::bluetooth::DirectionEnum direction, + uint16_t smp_fail_reason) { inc_func_call_count(__func__); - test::mock::main_shim_metrics_api::LogMetricSmpPairingEvent( - raw_address, smp_cmd, direction, smp_fail_reason); + test::mock::main_shim_metrics_api::LogMetricSmpPairingEvent(raw_address, smp_cmd, direction, + smp_fail_reason); } -void bluetooth::shim::LogMetricClassicPairingEvent( - const RawAddress& raw_address, uint16_t handle, uint32_t hci_cmd, - uint16_t hci_event, uint16_t cmd_status, uint16_t reason_code, - int64_t event_value) { +void bluetooth::shim::LogMetricClassicPairingEvent(const RawAddress& raw_address, uint16_t handle, + uint32_t hci_cmd, uint16_t hci_event, + uint16_t cmd_status, uint16_t reason_code, + int64_t event_value) { inc_func_call_count(__func__); test::mock::main_shim_metrics_api::LogMetricClassicPairingEvent( - raw_address, handle, hci_cmd, hci_event, cmd_status, reason_code, - event_value); + raw_address, handle, hci_cmd, hci_event, cmd_status, reason_code, event_value); } -void bluetooth::shim::LogMetricSdpAttribute(const RawAddress& raw_address, - uint16_t protocol_uuid, - uint16_t attribute_id, - size_t attribute_size, +void bluetooth::shim::LogMetricSdpAttribute(const RawAddress& raw_address, uint16_t protocol_uuid, + uint16_t attribute_id, size_t attribute_size, const char* attribute_value) { inc_func_call_count(__func__); - test::mock::main_shim_metrics_api::LogMetricSdpAttribute( - raw_address, protocol_uuid, attribute_id, attribute_size, - attribute_value); + test::mock::main_shim_metrics_api::LogMetricSdpAttribute(raw_address, protocol_uuid, attribute_id, + attribute_size, attribute_value); } void bluetooth::shim::LogMetricSocketConnectionState( - const RawAddress& raw_address, int port, int type, - android::bluetooth::SocketConnectionstateEnum connection_state, - int64_t tx_bytes, int64_t rx_bytes, int uid, int server_port, - android::bluetooth::SocketRoleEnum socket_role) { + const RawAddress& raw_address, int port, int type, + android::bluetooth::SocketConnectionstateEnum connection_state, int64_t tx_bytes, + int64_t rx_bytes, int uid, int server_port, + android::bluetooth::SocketRoleEnum socket_role) { inc_func_call_count(__func__); test::mock::main_shim_metrics_api::LogMetricSocketConnectionState( - raw_address, port, type, connection_state, tx_bytes, rx_bytes, uid, - server_port, socket_role); + raw_address, port, type, connection_state, tx_bytes, rx_bytes, uid, server_port, + socket_role); } void bluetooth::shim::LogMetricManufacturerInfo( - const RawAddress& raw_address, - android::bluetooth::AddressTypeEnum address_type, - android::bluetooth::DeviceInfoSrcEnum source_type, - const std::string& source_name, const std::string& manufacturer, - const std::string& model, const std::string& hardware_version, - const std::string& software_version) { + const RawAddress& raw_address, android::bluetooth::AddressTypeEnum address_type, + android::bluetooth::DeviceInfoSrcEnum source_type, const std::string& source_name, + const std::string& manufacturer, const std::string& model, + const std::string& hardware_version, const std::string& software_version) { inc_func_call_count(__func__); test::mock::main_shim_metrics_api::LogMetricManufacturerInfo( - raw_address, address_type, source_type, source_name, manufacturer, model, - hardware_version, software_version); + raw_address, address_type, source_type, source_name, manufacturer, model, + hardware_version, software_version); } -bool bluetooth::shim::CountCounterMetrics(int32_t /* key */, - int64_t /* count */) { +bool bluetooth::shim::CountCounterMetrics(int32_t /* key */, int64_t /* count */) { inc_func_call_count(__func__); return false; } void bluetooth::shim::LogMetricBluetoothLEConnectionMetricEvent( - const RawAddress& /* raw_address */, - android::bluetooth::le::LeConnectionOriginType /* origin_type */, - android::bluetooth::le::LeConnectionType /* connection_type */, - android::bluetooth::le::LeConnectionState /* transaction_state */, - std::vector< - std::pair> /* argument_list */) { - inc_func_call_count(__func__); - // test::mock::main_shim_metrics_api::LogMetricBluetoothLEConnectionMetricEvent(raw_address, origin_type, connection_type, transaction_state, argument_list); + const RawAddress& /* raw_address */, + android::bluetooth::le::LeConnectionOriginType /* origin_type */, + android::bluetooth::le::LeConnectionType /* connection_type */, + android::bluetooth::le::LeConnectionState /* transaction_state */, + std::vector> /* argument_list */) { + inc_func_call_count(__func__); + // test::mock::main_shim_metrics_api::LogMetricBluetoothLEConnectionMetricEvent(raw_address, + // origin_type, connection_type, transaction_state, argument_list); } // END mockcify generation diff --git a/system/test/mock/mock_main_shim_metrics_api.h b/system/test/mock/mock_main_shim_metrics_api.h index f65a6240db6..87d6bc0c159 100644 --- a/system/test/mock/mock_main_shim_metrics_api.h +++ b/system/test/mock/mock_main_shim_metrics_api.h @@ -44,42 +44,34 @@ namespace main_shim_metrics_api { // uint16_t reason_code Returns: void struct LogMetricLinkLayerConnectionEvent { std::function - body{[](const RawAddress* /* raw_address */, - uint32_t /* connection_handle */, - android::bluetooth::DirectionEnum /* direction */, - uint16_t /* link_type */, uint32_t /* hci_cmd */, - uint16_t /* hci_event */, uint16_t /* hci_ble_event */, - uint16_t /* cmd_status */, uint16_t /* reason_code */) {}}; + android::bluetooth::DirectionEnum direction, uint16_t link_type, + uint32_t hci_cmd, uint16_t hci_event, uint16_t hci_ble_event, + uint16_t cmd_status, uint16_t reason_code)> + body{[](const RawAddress* /* raw_address */, uint32_t /* connection_handle */, + android::bluetooth::DirectionEnum /* direction */, uint16_t /* link_type */, + uint32_t /* hci_cmd */, uint16_t /* hci_event */, uint16_t /* hci_ble_event */, + uint16_t /* cmd_status */, uint16_t /* reason_code */) {}}; void operator()(const RawAddress* raw_address, uint32_t connection_handle, - android::bluetooth::DirectionEnum direction, - uint16_t link_type, uint32_t hci_cmd, uint16_t hci_event, - uint16_t hci_ble_event, uint16_t cmd_status, + android::bluetooth::DirectionEnum direction, uint16_t link_type, uint32_t hci_cmd, + uint16_t hci_event, uint16_t hci_ble_event, uint16_t cmd_status, uint16_t reason_code) { - body(raw_address, connection_handle, direction, link_type, hci_cmd, - hci_event, hci_ble_event, cmd_status, reason_code); - }; + body(raw_address, connection_handle, direction, link_type, hci_cmd, hci_event, hci_ble_event, + cmd_status, reason_code); + } }; -extern struct LogMetricLinkLayerConnectionEvent - LogMetricLinkLayerConnectionEvent; +extern struct LogMetricLinkLayerConnectionEvent LogMetricLinkLayerConnectionEvent; // Name: LogMetricA2dpAudioUnderrunEvent // Params: const RawAddress& raw_address, uint64_t encoding_interval_millis, int // num_missing_pcm_bytes Returns: void struct LogMetricA2dpAudioUnderrunEvent { - std::function - body{[](const RawAddress& /* raw_address */, - uint64_t /* encoding_interval_millis */, - int /* num_missing_pcm_bytes */) {}}; - void operator()(const RawAddress& raw_address, - uint64_t encoding_interval_millis, + body{[](const RawAddress& /* raw_address */, uint64_t /* encoding_interval_millis */, + int /* num_missing_pcm_bytes */) {}}; + void operator()(const RawAddress& raw_address, uint64_t encoding_interval_millis, int num_missing_pcm_bytes) { body(raw_address, encoding_interval_millis, num_missing_pcm_bytes); - }; + } }; extern struct LogMetricA2dpAudioUnderrunEvent LogMetricA2dpAudioUnderrunEvent; // Name: LogMetricA2dpAudioOverrunEvent @@ -87,36 +79,30 @@ extern struct LogMetricA2dpAudioUnderrunEvent LogMetricA2dpAudioUnderrunEvent; // num_dropped_buffers, int num_dropped_encoded_frames, int // num_dropped_encoded_bytes Returns: void struct LogMetricA2dpAudioOverrunEvent { - std::function - body{[](const RawAddress& /* raw_address */, - uint64_t /* encoding_interval_millis */, - int /* num_dropped_buffers */, - int /* num_dropped_encoded_frames */, - int /* num_dropped_encoded_bytes */) {}}; - void operator()(const RawAddress& raw_address, - uint64_t encoding_interval_millis, int num_dropped_buffers, - int num_dropped_encoded_frames, + body{[](const RawAddress& /* raw_address */, uint64_t /* encoding_interval_millis */, + int /* num_dropped_buffers */, int /* num_dropped_encoded_frames */, + int /* num_dropped_encoded_bytes */) {}}; + void operator()(const RawAddress& raw_address, uint64_t encoding_interval_millis, + int num_dropped_buffers, int num_dropped_encoded_frames, int num_dropped_encoded_bytes) { - body(raw_address, encoding_interval_millis, num_dropped_buffers, - num_dropped_encoded_frames, num_dropped_encoded_bytes); - }; + body(raw_address, encoding_interval_millis, num_dropped_buffers, num_dropped_encoded_frames, + num_dropped_encoded_bytes); + } }; extern struct LogMetricA2dpAudioOverrunEvent LogMetricA2dpAudioOverrunEvent; // Name: LogMetricA2dpPlaybackEvent // Params: const RawAddress& raw_address, int playback_state, int // audio_coding_mode Returns: void struct LogMetricA2dpPlaybackEvent { - std::function - body{[](const RawAddress& /* raw_address */, int /* playback_state */, - int /* audio_coding_mode */) {}}; - void operator()(const RawAddress& raw_address, int playback_state, - int audio_coding_mode) { + std::function + body{[](const RawAddress& /* raw_address */, int /* playback_state */, + int /* audio_coding_mode */) {}}; + void operator()(const RawAddress& raw_address, int playback_state, int audio_coding_mode) { body(raw_address, playback_state, audio_coding_mode); - }; + } }; extern struct LogMetricA2dpSessionMetricsEvent LogMetricA2dpSessionMetricsEvent; // Name: LogMetricA2dpSessionMetricsEvent @@ -124,31 +110,25 @@ extern struct LogMetricA2dpSessionMetricsEvent LogMetricA2dpSessionMetricsEvent; // audio_coding_mode Returns: void struct LogMetricA2dpSessionMetricsEvent { std::function - body{[](const RawAddress& /* raw_address */, - int64_t /* audio_duration_ms */, int /* media_timer_min_ms */, - int /* media_timer_max_ms */, int /* media_timer_avg_ms */, - int /* total_scheduling_count */, - int /* buffer_overruns_max_count */, - int /* buffer_overruns_total */, - float /* buffer_underruns_average */, - int /* buffer_underruns_count */, int64_t /* codec_index */, - bool /* is_a2dp_offload */) {}}; - void operator()(const RawAddress& raw_address, int64_t audio_duration_ms, - int media_timer_min_ms, int media_timer_max_ms, - int /* media_timer_avg_ms */, int total_scheduling_count, + int media_timer_min_ms, int media_timer_max_ms, int media_timer_avg_ms, + int total_scheduling_count, int buffer_overruns_max_count, + int buffer_overruns_total, float buffer_underruns_average, + int buffer_underruns_count, int64_t codec_index, bool is_a2dp_offload)> + body{[](const RawAddress& /* raw_address */, int64_t /* audio_duration_ms */, + int /* media_timer_min_ms */, int /* media_timer_max_ms */, + int /* media_timer_avg_ms */, int /* total_scheduling_count */, + int /* buffer_overruns_max_count */, int /* buffer_overruns_total */, + float /* buffer_underruns_average */, int /* buffer_underruns_count */, + int64_t /* codec_index */, bool /* is_a2dp_offload */) {}}; + void operator()(const RawAddress& raw_address, int64_t audio_duration_ms, int media_timer_min_ms, + int media_timer_max_ms, int /* media_timer_avg_ms */, int total_scheduling_count, int buffer_overruns_max_count, int buffer_overruns_total, - float buffer_underruns_average, int buffer_underruns_count, - int64_t codec_index, bool is_a2dp_offload) { - body(raw_address, audio_duration_ms, media_timer_min_ms, media_timer_max_ms, - audio_duration_ms, total_scheduling_count, buffer_overruns_max_count, - buffer_overruns_total, buffer_underruns_average, - buffer_underruns_count, codec_index, is_a2dp_offload); - }; + float buffer_underruns_average, int buffer_underruns_count, int64_t codec_index, + bool is_a2dp_offload) { + body(raw_address, audio_duration_ms, media_timer_min_ms, media_timer_max_ms, audio_duration_ms, + total_scheduling_count, buffer_overruns_max_count, buffer_overruns_total, + buffer_underruns_average, buffer_underruns_count, codec_index, is_a2dp_offload); + } }; extern struct LogMetricA2dpPlaybackEvent LogMetricA2dpPlaybackEvent; // Name: LogMetricHfpPacketLossStats @@ -157,71 +137,66 @@ extern struct LogMetricA2dpPlaybackEvent LogMetricA2dpPlaybackEvent; struct LogMetricHfpPacketLossStats { std::function - body{[](const RawAddress& /* raw_address */, int /* num_decoded_frames */, - double /* packet_loss_ratio */, uint16_t /* codec_type */) {}}; - void operator()(const RawAddress& raw_address, int num_decoded_frames, - double packet_loss_ratio, uint16_t codec_type) { + body{[](const RawAddress& /* raw_address */, int /* num_decoded_frames */, + double /* packet_loss_ratio */, uint16_t /* codec_type */) {}}; + void operator()(const RawAddress& raw_address, int num_decoded_frames, double packet_loss_ratio, + uint16_t codec_type) { body(raw_address, num_decoded_frames, packet_loss_ratio, codec_type); - }; + } }; extern struct LogMetricHfpPacketLossStats LogMetricHfpPacketLossStats; // Name: LogMetricMmcTranscodeRttStats // Params: int maximum_rtt, double mean_rtt, int num_requests, int codec_type // Return: void struct LogMetricMmcTranscodeRttStats { - std::function - body{[](int /* maximum_rtt */, double /* mean_rtt */, - int /* num_requests */, int /* codec_type */) {}}; - void operator()(int maximum_rtt, double mean_rtt, int num_requests, - int codec_type) { + std::function body{ + [](int /* maximum_rtt */, double /* mean_rtt */, int /* num_requests */, + int /* codec_type */) {}}; + void operator()(int maximum_rtt, double mean_rtt, int num_requests, int codec_type) { body(maximum_rtt, mean_rtt, num_requests, codec_type); - }; + } }; extern struct LogMetricMmcTranscodeRttStats LogMetricMmcTranscodeRttStats; // Name: LogMetricReadRssiResult // Params: const RawAddress& raw_address, uint16_t handle, uint32_t cmd_status, // int8_t rssi Returns: void struct LogMetricReadRssiResult { - std::function - body{[](const RawAddress& /* raw_address */, uint16_t /* handle */, - uint32_t /* cmd_status */, int8_t /* rssi */) {}}; - void operator()(const RawAddress& raw_address, uint16_t handle, - uint32_t cmd_status, int8_t rssi) { + std::function + body{[](const RawAddress& /* raw_address */, uint16_t /* handle */, + uint32_t /* cmd_status */, int8_t /* rssi */) {}}; + void operator()(const RawAddress& raw_address, uint16_t handle, uint32_t cmd_status, + int8_t rssi) { body(raw_address, handle, cmd_status, rssi); - }; + } }; extern struct LogMetricReadRssiResult LogMetricReadRssiResult; // Name: LogMetricReadFailedContactCounterResult // Params: const RawAddress& raw_address, uint16_t handle, uint32_t cmd_status, // int32_t failed_contact_counter Returns: void struct LogMetricReadFailedContactCounterResult { - std::function - body{[](const RawAddress& /* raw_address */, uint16_t /* handle */, - uint32_t /* cmd_status */, - int32_t /* failed_contact_counter */) {}}; - void operator()(const RawAddress& raw_address, uint16_t handle, - uint32_t cmd_status, int32_t failed_contact_counter) { + std::function + body{[](const RawAddress& /* raw_address */, uint16_t /* handle */, + uint32_t /* cmd_status */, int32_t /* failed_contact_counter */) {}}; + void operator()(const RawAddress& raw_address, uint16_t handle, uint32_t cmd_status, + int32_t failed_contact_counter) { body(raw_address, handle, cmd_status, failed_contact_counter); - }; + } }; -extern struct LogMetricReadFailedContactCounterResult - LogMetricReadFailedContactCounterResult; +extern struct LogMetricReadFailedContactCounterResult LogMetricReadFailedContactCounterResult; // Name: LogMetricReadTxPowerLevelResult // Params: const RawAddress& raw_address, uint16_t handle, uint32_t cmd_status, // int32_t transmit_power_level Returns: void struct LogMetricReadTxPowerLevelResult { - std::function - body{[](const RawAddress& /* raw_address */, uint16_t /* handle */, - uint32_t /* cmd_status */, - int32_t /* transmit_power_level */) {}}; - void operator()(const RawAddress& raw_address, uint16_t handle, - uint32_t cmd_status, int32_t transmit_power_level) { + std::function + body{[](const RawAddress& /* raw_address */, uint16_t /* handle */, + uint32_t /* cmd_status */, int32_t /* transmit_power_level */) {}}; + void operator()(const RawAddress& raw_address, uint16_t handle, uint32_t cmd_status, + int32_t transmit_power_level) { body(raw_address, handle, cmd_status, transmit_power_level); - }; + } }; extern struct LogMetricReadTxPowerLevelResult LogMetricReadTxPowerLevelResult; // Name: LogMetricSmpPairingEvent @@ -230,16 +205,14 @@ extern struct LogMetricReadTxPowerLevelResult LogMetricReadTxPowerLevelResult; // void struct LogMetricSmpPairingEvent { std::function - body{[](const RawAddress& /* raw_address */, uint16_t /* smp_cmd */, - android::bluetooth::DirectionEnum /* direction */, - uint16_t /* smp_fail_reason */) {}}; + android::bluetooth::DirectionEnum direction, uint16_t smp_fail_reason)> + body{[](const RawAddress& /* raw_address */, uint16_t /* smp_cmd */, + android::bluetooth::DirectionEnum /* direction */, + uint16_t /* smp_fail_reason */) {}}; void operator()(const RawAddress& raw_address, uint16_t smp_cmd, - android::bluetooth::DirectionEnum direction, - uint16_t smp_fail_reason) { + android::bluetooth::DirectionEnum direction, uint16_t smp_fail_reason) { body(raw_address, smp_cmd, direction, smp_fail_reason); - }; + } }; extern struct LogMetricSmpPairingEvent LogMetricSmpPairingEvent; // Name: LogMetricClassicPairingEvent @@ -247,19 +220,17 @@ extern struct LogMetricSmpPairingEvent LogMetricSmpPairingEvent; // uint16_t hci_event, uint16_t cmd_status, uint16_t reason_code, int64_t // event_value Returns: void struct LogMetricClassicPairingEvent { - std::function - body{[](const RawAddress& /* raw_address */, uint16_t /* handle */, - uint32_t /* hci_cmd */, uint16_t /* hci_event */, - uint16_t /* cmd_status */, uint16_t /* reason_code */, - int64_t /* event_value */) {}}; - void operator()(const RawAddress& raw_address, uint16_t handle, - uint32_t hci_cmd, uint16_t hci_event, uint16_t cmd_status, - uint16_t reason_code, int64_t event_value) { - body(raw_address, handle, hci_cmd, hci_event, cmd_status, reason_code, - event_value); - }; + std::function + body{[](const RawAddress& /* raw_address */, uint16_t /* handle */, + uint32_t /* hci_cmd */, uint16_t /* hci_event */, uint16_t /* cmd_status */, + uint16_t /* reason_code */, int64_t /* event_value */) {}}; + void operator()(const RawAddress& raw_address, uint16_t handle, uint32_t hci_cmd, + uint16_t hci_event, uint16_t cmd_status, uint16_t reason_code, + int64_t event_value) { + body(raw_address, handle, hci_cmd, hci_event, cmd_status, reason_code, event_value); + } }; extern struct LogMetricClassicPairingEvent LogMetricClassicPairingEvent; // Name: LogMetricSdpAttribute @@ -267,18 +238,15 @@ extern struct LogMetricClassicPairingEvent LogMetricClassicPairingEvent; // attribute_id, size_t attribute_size, const char* attribute_value Returns: // void struct LogMetricSdpAttribute { - std::function - body{[](const RawAddress& /* raw_address */, uint16_t /* protocol_uuid */, - uint16_t /* attribute_id */, size_t /* attribute_size */, - const char* /* attribute_value */) {}}; - void operator()(const RawAddress& raw_address, uint16_t protocol_uuid, - uint16_t attribute_id, size_t attribute_size, - const char* attribute_value) { - body(raw_address, protocol_uuid, attribute_id, attribute_size, - attribute_value); - }; + std::function + body{[](const RawAddress& /* raw_address */, uint16_t /* protocol_uuid */, + uint16_t /* attribute_id */, size_t /* attribute_size */, + const char* /* attribute_value */) {}}; + void operator()(const RawAddress& raw_address, uint16_t protocol_uuid, uint16_t attribute_id, + size_t attribute_size, const char* attribute_value) { + body(raw_address, protocol_uuid, attribute_id, attribute_size, attribute_value); + } }; extern struct LogMetricSdpAttribute LogMetricSdpAttribute; // Name: LogMetricSocketConnectionState @@ -287,26 +255,21 @@ extern struct LogMetricSdpAttribute LogMetricSdpAttribute; // tx_bytes, int64_t rx_bytes, int uid, int server_port, // android::bluetooth::SocketRoleEnum socket_role Returns: void struct LogMetricSocketConnectionState { - std::function - body{[](const RawAddress& /* raw_address */, int /* port */, - int /* type */, - android::bluetooth:: - SocketConnectionstateEnum /* connection_state */, - int64_t /* tx_bytes */, int64_t /* rx_bytes */, int /* uid */, - int /* server_port */, - android::bluetooth::SocketRoleEnum /* socket_role */) {}}; - void operator()( - const RawAddress& raw_address, int port, int type, - android::bluetooth::SocketConnectionstateEnum connection_state, - int64_t tx_bytes, int64_t rx_bytes, int uid, int server_port, - android::bluetooth::SocketRoleEnum socket_role) { - body(raw_address, port, type, connection_state, tx_bytes, rx_bytes, uid, - server_port, socket_role); - }; + std::function + body{[](const RawAddress& /* raw_address */, int /* port */, int /* type */, + android::bluetooth::SocketConnectionstateEnum /* connection_state */, + int64_t /* tx_bytes */, int64_t /* rx_bytes */, int /* uid */, + int /* server_port */, android::bluetooth::SocketRoleEnum /* socket_role */) {}}; + void operator()(const RawAddress& raw_address, int port, int type, + android::bluetooth::SocketConnectionstateEnum connection_state, int64_t tx_bytes, + int64_t rx_bytes, int uid, int server_port, + android::bluetooth::SocketRoleEnum socket_role) { + body(raw_address, port, type, connection_state, tx_bytes, rx_bytes, uid, server_port, + socket_role); + } }; extern struct LogMetricSocketConnectionState LogMetricSocketConnectionState; // Name: LogMetricManufacturerInfo @@ -315,31 +278,24 @@ extern struct LogMetricSocketConnectionState LogMetricSocketConnectionState; // const std::string& model, const std::string& hardware_version, const // std::string& software_version Returns: void struct LogMetricManufacturerInfo { - std::function - body{[](const RawAddress& /* raw_address */, - android::bluetooth::AddressTypeEnum /* address_type */, - android::bluetooth::DeviceInfoSrcEnum /* source_type */, - const std::string& /* source_name */, - const std::string& /* manufacturer */, - const std::string& /* model */, - const std::string& /* hardware_version */, - const std::string& /* software_version */) {}}; - void operator()(const RawAddress& raw_address, - android::bluetooth::AddressTypeEnum address_type, - android::bluetooth::DeviceInfoSrcEnum source_type, - const std::string& source_name, + std::function + body{[](const RawAddress& /* raw_address */, + android::bluetooth::AddressTypeEnum /* address_type */, + android::bluetooth::DeviceInfoSrcEnum /* source_type */, + const std::string& /* source_name */, const std::string& /* manufacturer */, + const std::string& /* model */, const std::string& /* hardware_version */, + const std::string& /* software_version */) {}}; + void operator()(const RawAddress& raw_address, android::bluetooth::AddressTypeEnum address_type, + android::bluetooth::DeviceInfoSrcEnum source_type, const std::string& source_name, const std::string& manufacturer, const std::string& model, - const std::string& hardware_version, - const std::string& software_version) { - body(raw_address, address_type, source_type, source_name, manufacturer, - model, hardware_version, software_version); - }; + const std::string& hardware_version, const std::string& software_version) { + body(raw_address, address_type, source_type, source_name, manufacturer, model, hardware_version, + software_version); + } }; extern struct LogMetricManufacturerInfo LogMetricManufacturerInfo; @@ -351,29 +307,25 @@ extern struct LogMetricManufacturerInfo LogMetricManufacturerInfo; // std::vector> // argument_list struct LogMetricBluetoothLEConnectionMetricEvent { - std::function> argument_list)> - body{[](const RawAddress& /* raw_address */, - android::bluetooth::le::LeConnectionOriginType /* origin_type */, - android::bluetooth::le::LeConnectionType /* connection_type */, - android::bluetooth::le::LeConnectionState - /* transaction_state */, - std::vector> - /* argument_list */) {}}; - void operator()( - const RawAddress& raw_address, - android::bluetooth::le::LeConnectionOriginType origin_type, - android::bluetooth::le::LeConnectionType connection_type, - android::bluetooth::le::LeConnectionState transaction_state, - std::vector> - argument_list) { - body(raw_address, origin_type, connection_type, transaction_state, - argument_list); - }; + std::function> argument_list)> + body{[](const RawAddress& /* raw_address */, + android::bluetooth::le::LeConnectionOriginType /* origin_type */, + android::bluetooth::le::LeConnectionType /* connection_type */, + android::bluetooth::le::LeConnectionState + /* transaction_state */, + std::vector> + /* argument_list */) {}}; + void operator()(const RawAddress& raw_address, + android::bluetooth::le::LeConnectionOriginType origin_type, + android::bluetooth::le::LeConnectionType connection_type, + android::bluetooth::le::LeConnectionState transaction_state, + std::vector> argument_list) { + body(raw_address, origin_type, connection_type, transaction_state, argument_list); + } }; } // namespace main_shim_metrics_api diff --git a/system/test/mock/mock_main_shim_stack.cc b/system/test/mock/mock_main_shim_stack.cc index 247c3b676e6..ef97ff6c9ba 100644 --- a/system/test/mock/mock_main_shim_stack.cc +++ b/system/test/mock/mock_main_shim_stack.cc @@ -29,8 +29,7 @@ Stack* Stack::GetInstance() { return testing::instance_; } void Stack::StartEverything() {} -void Stack::StartModuleStack(const ModuleList* /* modules */, - const os::Thread* /* thread */) {} +void Stack::StartModuleStack(const ModuleList* /* modules */, const os::Thread* /* thread */) {} void Stack::Start(ModuleList* /* modules */) {} @@ -48,9 +47,7 @@ os::Handler* Stack::GetHandler() { return stack_handler_; } bool Stack::IsDumpsysModuleStarted() const { return false; } -bool Stack::LockForDumpsys(std::function /* dumpsys_callback */) { - return false; -} +bool Stack::LockForDumpsys(std::function /* dumpsys_callback */) { return false; } } // namespace shim } // namespace bluetooth diff --git a/system/test/mock/mock_osi_alarm.cc b/system/test/mock/mock_osi_alarm.cc index b84a61ef651..0ecf82ab45a 100644 --- a/system/test/mock/mock_osi_alarm.cc +++ b/system/test/mock/mock_osi_alarm.cc @@ -82,13 +82,11 @@ alarm_t* alarm_new_periodic(const char* name) { inc_func_call_count(__func__); return test::mock::osi_alarm::alarm_new_periodic(name); } -void alarm_set(alarm_t* alarm, uint64_t interval_ms, alarm_callback_t cb, - void* data) { +void alarm_set(alarm_t* alarm, uint64_t interval_ms, alarm_callback_t cb, void* data) { inc_func_call_count(__func__); test::mock::osi_alarm::alarm_set(alarm, interval_ms, cb, data); } -void alarm_set_on_mloop(alarm_t* alarm, uint64_t interval_ms, - alarm_callback_t cb, void* data) { +void alarm_set_on_mloop(alarm_t* alarm, uint64_t interval_ms, alarm_callback_t cb, void* data) { inc_func_call_count(__func__); test::mock::osi_alarm::alarm_set_on_mloop(alarm, interval_ms, cb, data); } diff --git a/system/test/mock/mock_osi_alarm.h b/system/test/mock/mock_osi_alarm.h index eba4330ee8c..a517eb77e23 100644 --- a/system/test/mock/mock_osi_alarm.h +++ b/system/test/mock/mock_osi_alarm.h @@ -41,7 +41,7 @@ namespace osi_alarm { // Return: void struct alarm_cancel { std::function body{[](alarm_t* /* alarm */) {}}; - void operator()(alarm_t* alarm) { body(alarm); }; + void operator()(alarm_t* alarm) { body(alarm); } }; extern struct alarm_cancel alarm_cancel; @@ -50,7 +50,7 @@ extern struct alarm_cancel alarm_cancel; // Return: void struct alarm_cleanup { std::function body{[](void) {}}; - void operator()(void) { body(); }; + void operator()(void) { body(); } }; extern struct alarm_cleanup alarm_cleanup; @@ -59,7 +59,7 @@ extern struct alarm_cleanup alarm_cleanup; // Return: void struct alarm_debug_dump { std::function body{[](int /* fd */) {}}; - void operator()(int fd) { body(fd); }; + void operator()(int fd) { body(fd); } }; extern struct alarm_debug_dump alarm_debug_dump; @@ -68,7 +68,7 @@ extern struct alarm_debug_dump alarm_debug_dump; // Return: void struct alarm_free { std::function body{[](alarm_t* /* alarm */) {}}; - void operator()(alarm_t* alarm) { body(alarm); }; + void operator()(alarm_t* alarm) { body(alarm); } }; extern struct alarm_free alarm_free; @@ -78,8 +78,8 @@ extern struct alarm_free alarm_free; struct alarm_get_remaining_ms { uint64_t return_value{0}; std::function body{ - [this](const alarm_t* /* alarm */) { return return_value; }}; - uint64_t operator()(const alarm_t* alarm) { return body(alarm); }; + [this](const alarm_t* /* alarm */) { return return_value; }}; + uint64_t operator()(const alarm_t* alarm) { return body(alarm); } }; extern struct alarm_get_remaining_ms alarm_get_remaining_ms; @@ -89,8 +89,8 @@ extern struct alarm_get_remaining_ms alarm_get_remaining_ms; struct alarm_is_scheduled { bool return_value{false}; std::function body{ - [this](const alarm_t* /* alarm */) { return return_value; }}; - bool operator()(const alarm_t* alarm) { return body(alarm); }; + [this](const alarm_t* /* alarm */) { return return_value; }}; + bool operator()(const alarm_t* alarm) { return body(alarm); } }; extern struct alarm_is_scheduled alarm_is_scheduled; @@ -100,8 +100,8 @@ extern struct alarm_is_scheduled alarm_is_scheduled; struct alarm_new { alarm_t* return_value{0}; std::function body{ - [this](const char* /* name */) { return return_value; }}; - alarm_t* operator()(const char* name) { return body(name); }; + [this](const char* /* name */) { return return_value; }}; + alarm_t* operator()(const char* name) { return body(name); } }; extern struct alarm_new alarm_new; @@ -111,8 +111,8 @@ extern struct alarm_new alarm_new; struct alarm_new_periodic { alarm_t* return_value{0}; std::function body{ - [this](const char* /* name */) { return return_value; }}; - alarm_t* operator()(const char* name) { return body(name); }; + [this](const char* /* name */) { return return_value; }}; + alarm_t* operator()(const char* name) { return body(name); } }; extern struct alarm_new_periodic alarm_new_periodic; @@ -120,14 +120,12 @@ extern struct alarm_new_periodic alarm_new_periodic; // Params: alarm_t* alarm, uint64_t interval_ms, alarm_callback_t cb, void* data // Return: void struct alarm_set { - std::function - body{[](alarm_t* /* alarm */, uint64_t /* interval_ms */, - alarm_callback_t /* cb */, void* /* data */) {}}; - void operator()(alarm_t* alarm, uint64_t interval_ms, alarm_callback_t cb, - void* data) { + std::function body{ + [](alarm_t* /* alarm */, uint64_t /* interval_ms */, alarm_callback_t /* cb */, + void* /* data */) {}}; + void operator()(alarm_t* alarm, uint64_t interval_ms, alarm_callback_t cb, void* data) { body(alarm, interval_ms, cb, data); - }; + } }; extern struct alarm_set alarm_set; @@ -135,14 +133,12 @@ extern struct alarm_set alarm_set; // Params: alarm_t* alarm, uint64_t interval_ms, alarm_callback_t cb, void* data // Return: void struct alarm_set_on_mloop { - std::function - body{[](alarm_t* /* alarm */, uint64_t /* interval_ms */, - alarm_callback_t /* cb */, void* /* data */) {}}; - void operator()(alarm_t* alarm, uint64_t interval_ms, alarm_callback_t cb, - void* data) { + std::function body{ + [](alarm_t* /* alarm */, uint64_t /* interval_ms */, alarm_callback_t /* cb */, + void* /* data */) {}}; + void operator()(alarm_t* alarm, uint64_t interval_ms, alarm_callback_t cb, void* data) { body(alarm, interval_ms, cb, data); - }; + } }; extern struct alarm_set_on_mloop alarm_set_on_mloop; diff --git a/system/test/mock/mock_osi_allocator.h b/system/test/mock/mock_osi_allocator.h index 77c876b0dd0..f0792d91578 100644 --- a/system/test/mock/mock_osi_allocator.h +++ b/system/test/mock/mock_osi_allocator.h @@ -40,9 +40,8 @@ namespace osi_allocator { // Return: void* struct osi_calloc { void* return_value{}; - std::function body{ - [this](size_t /* size */) { return return_value; }}; - void* operator()(size_t size) { return body(size); }; + std::function body{[this](size_t /* size */) { return return_value; }}; + void* operator()(size_t size) { return body(size); } }; extern struct osi_calloc osi_calloc; @@ -51,7 +50,7 @@ extern struct osi_calloc osi_calloc; // Return: void struct osi_free { std::function body{[](void* /* ptr */) {}}; - void operator()(void* ptr) { body(ptr); }; + void operator()(void* ptr) { body(ptr); } }; extern struct osi_free osi_free; @@ -60,7 +59,7 @@ extern struct osi_free osi_free; // Return: void struct osi_free_and_reset { std::function body{[](void** /* p_ptr */) {}}; - void operator()(void** p_ptr) { body(p_ptr); }; + void operator()(void** p_ptr) { body(p_ptr); } }; extern struct osi_free_and_reset osi_free_and_reset; @@ -69,9 +68,8 @@ extern struct osi_free_and_reset osi_free_and_reset; // Return: void* struct osi_malloc { void* return_value{}; - std::function body{ - [this](size_t /* size */) { return return_value; }}; - void* operator()(size_t size) { return body(size); }; + std::function body{[this](size_t /* size */) { return return_value; }}; + void* operator()(size_t size) { return body(size); } }; extern struct osi_malloc osi_malloc; @@ -81,8 +79,8 @@ extern struct osi_malloc osi_malloc; struct osi_strdup { char* return_value{0}; std::function body{ - [this](const char* /* str */) { return return_value; }}; - char* operator()(const char* str) { return body(str); }; + [this](const char* /* str */) { return return_value; }}; + char* operator()(const char* str) { return body(str); } }; extern struct osi_strdup osi_strdup; @@ -92,8 +90,8 @@ extern struct osi_strdup osi_strdup; struct osi_strndup { char* return_value{0}; std::function body{ - [this](const char* /* str */, size_t /* len */) { return return_value; }}; - char* operator()(const char* str, size_t len) { return body(str, len); }; + [this](const char* /* str */, size_t /* len */) { return return_value; }}; + char* operator()(const char* str, size_t len) { return body(str, len); } }; extern struct osi_strndup osi_strndup; diff --git a/system/test/mock/mock_osi_config.cc b/system/test/mock/mock_osi_config.cc index e1fde83280d..fa1317715e2 100644 --- a/system/test/mock/mock_osi_config.cc +++ b/system/test/mock/mock_osi_config.cc @@ -72,34 +72,27 @@ bool checksum_save(const std::string& checksum, const std::string& filename) { inc_func_call_count(__func__); return test::mock::osi_config::checksum_save(checksum, filename); } -bool config_get_bool(const config_t& config, const std::string& section, - const std::string& key, bool def_value) { +bool config_get_bool(const config_t& config, const std::string& section, const std::string& key, + bool def_value) { inc_func_call_count(__func__); - return test::mock::osi_config::config_get_bool(config, section, key, - def_value); + return test::mock::osi_config::config_get_bool(config, section, key, def_value); } -int config_get_int(const config_t& config, const std::string& section, - const std::string& key, int def_value) { +int config_get_int(const config_t& config, const std::string& section, const std::string& key, + int def_value) { inc_func_call_count(__func__); - return test::mock::osi_config::config_get_int(config, section, key, - def_value); + return test::mock::osi_config::config_get_int(config, section, key, def_value); } -const std::string* config_get_string(const config_t& config, - const std::string& section, - const std::string& key, - const std::string* def_value) { +const std::string* config_get_string(const config_t& config, const std::string& section, + const std::string& key, const std::string* def_value) { inc_func_call_count(__func__); - return test::mock::osi_config::config_get_string(config, section, key, - def_value); + return test::mock::osi_config::config_get_string(config, section, key, def_value); } uint64_t config_get_uint64(const config_t& config, const std::string& section, const std::string& key, uint64_t def_value) { inc_func_call_count(__func__); - return test::mock::osi_config::config_get_uint64(config, section, key, - def_value); + return test::mock::osi_config::config_get_uint64(config, section, key, def_value); } -bool config_has_key(const config_t& config, const std::string& section, - const std::string& key) { +bool config_has_key(const config_t& config, const std::string& section, const std::string& key) { inc_func_call_count(__func__); return test::mock::osi_config::config_has_key(config, section, key); } @@ -119,8 +112,7 @@ std::unique_ptr config_new_empty(void) { inc_func_call_count(__func__); return test::mock::osi_config::config_new_empty(); } -bool config_remove_key(config_t* config, const std::string& section, - const std::string& key) { +bool config_remove_key(config_t* config, const std::string& section, const std::string& key) { inc_func_call_count(__func__); return test::mock::osi_config::config_remove_key(config, section, key); } @@ -132,23 +124,23 @@ bool config_save(const config_t& config, const std::string& filename) { inc_func_call_count(__func__); return test::mock::osi_config::config_save(config, filename); } -void config_set_bool(config_t* config, const std::string& section, - const std::string& key, bool value) { +void config_set_bool(config_t* config, const std::string& section, const std::string& key, + bool value) { inc_func_call_count(__func__); test::mock::osi_config::config_set_bool(config, section, key, value); } -void config_set_int(config_t* config, const std::string& section, - const std::string& key, int value) { +void config_set_int(config_t* config, const std::string& section, const std::string& key, + int value) { inc_func_call_count(__func__); test::mock::osi_config::config_set_int(config, section, key, value); } -void config_set_string(config_t* config, const std::string& section, - const std::string& key, const std::string& value) { +void config_set_string(config_t* config, const std::string& section, const std::string& key, + const std::string& value) { inc_func_call_count(__func__); test::mock::osi_config::config_set_string(config, section, key, value); } -void config_set_uint64(config_t* config, const std::string& section, - const std::string& key, uint64_t value) { +void config_set_uint64(config_t* config, const std::string& section, const std::string& key, + uint64_t value) { inc_func_call_count(__func__); test::mock::osi_config::config_set_uint64(config, section, key, value); } diff --git a/system/test/mock/mock_osi_config.h b/system/test/mock/mock_osi_config.h index 5b3cd4355bb..d3a0708566d 100644 --- a/system/test/mock/mock_osi_config.h +++ b/system/test/mock/mock_osi_config.h @@ -48,8 +48,8 @@ namespace osi_config { struct checksum_read { std::string return_value{std::string()}; std::function body{ - [this](const char* /* filename */) { return return_value; }}; - std::string operator()(const char* filename) { return body(filename); }; + [this](const char* /* filename */) { return return_value; }}; + std::string operator()(const char* filename) { return body(filename); } }; extern struct checksum_read checksum_read; @@ -58,12 +58,13 @@ extern struct checksum_read checksum_read; // Return: bool struct checksum_save { bool return_value{false}; - std::function - body{[this](const std::string& /* checksum */, - const std::string& /* filename */) { return return_value; }}; + std::function body{ + [this](const std::string& /* checksum */, const std::string& /* filename */) { + return return_value; + }}; bool operator()(const std::string& checksum, const std::string& filename) { return body(checksum, filename); - }; + } }; extern struct checksum_save checksum_save; @@ -72,16 +73,14 @@ extern struct checksum_save checksum_save; // std::string& key, bool def_value Return: bool struct config_get_bool { bool return_value{false}; - std::function - body{[this](const config_t& /* config */, - const std::string& /* section */, - const std::string& /* key */, - bool /* def_value */) { return return_value; }}; - bool operator()(const config_t& config, const std::string& section, - const std::string& key, bool def_value) { + std::function + body{[this](const config_t& /* config */, const std::string& /* section */, + const std::string& /* key */, bool /* def_value */) { return return_value; }}; + bool operator()(const config_t& config, const std::string& section, const std::string& key, + bool def_value) { return body(config, section, key, def_value); - }; + } }; extern struct config_get_bool config_get_bool; @@ -90,16 +89,14 @@ extern struct config_get_bool config_get_bool; // std::string& key, int def_value Return: int struct config_get_int { int return_value{0}; - std::function - body{[this](const config_t& /* config */, - const std::string& /* section */, - const std::string& /* key */, - int /* def_value */) { return return_value; }}; - int operator()(const config_t& config, const std::string& section, - const std::string& key, int def_value) { + std::function + body{[this](const config_t& /* config */, const std::string& /* section */, + const std::string& /* key */, int /* def_value */) { return return_value; }}; + int operator()(const config_t& config, const std::string& section, const std::string& key, + int def_value) { return body(config, section, key, def_value); - }; + } }; extern struct config_get_int config_get_int; @@ -108,19 +105,15 @@ extern struct config_get_int config_get_int; // std::string& key, const std::string* def_value Return: const std::string* struct config_get_string { const std::string* return_value{0}; - std::function - body{[this](const config_t& /* config */, - const std::string& /* section */, - const std::string& /* key */, - const std::string* /* def_value */) { return return_value; }}; - const std::string* operator()(const config_t& config, - const std::string& section, - const std::string& key, - const std::string* def_value) { + std::function + body{[this](const config_t& /* config */, const std::string& /* section */, + const std::string& /* key */, + const std::string* /* def_value */) { return return_value; }}; + const std::string* operator()(const config_t& config, const std::string& section, + const std::string& key, const std::string* def_value) { return body(config, section, key, def_value); - }; + } }; extern struct config_get_string config_get_string; @@ -129,16 +122,15 @@ extern struct config_get_string config_get_string; // std::string& key, uint64_t def_value Return: uint64_t struct config_get_uint64 { uint64_t return_value{0}; - std::function - body{[this](const config_t& /* config */, - const std::string& /* section */, - const std::string& /* key */, - uint64_t /* def_value */) { return return_value; }}; - uint64_t operator()(const config_t& config, const std::string& section, - const std::string& key, uint64_t def_value) { + std::function + body{[this](const config_t& /* config */, const std::string& /* section */, + const std::string& /* key */, + uint64_t /* def_value */) { return return_value; }}; + uint64_t operator()(const config_t& config, const std::string& section, const std::string& key, + uint64_t def_value) { return body(config, section, key, def_value); - }; + } }; extern struct config_get_uint64 config_get_uint64; @@ -147,15 +139,12 @@ extern struct config_get_uint64 config_get_uint64; // std::string& key Return: bool struct config_has_key { bool return_value{false}; - std::function - body{[this](const config_t& /* config */, - const std::string& /* section */, - const std::string& /* key */) { return return_value; }}; - bool operator()(const config_t& config, const std::string& section, - const std::string& key) { + std::function + body{[this](const config_t& /* config */, const std::string& /* section */, + const std::string& /* key */) { return return_value; }}; + bool operator()(const config_t& config, const std::string& section, const std::string& key) { return body(config, section, key); - }; + } }; extern struct config_has_key config_has_key; @@ -164,13 +153,13 @@ extern struct config_has_key config_has_key; // Return: bool struct config_has_section { bool return_value{false}; - std::function - body{[this](const config_t& /* config */, - const std::string& /* section */) { return return_value; }}; + std::function body{ + [this](const config_t& /* config */, const std::string& /* section */) { + return return_value; + }}; bool operator()(const config_t& config, const std::string& section) { return body(config, section); - }; + } }; extern struct config_has_section config_has_section; @@ -179,10 +168,8 @@ extern struct config_has_section config_has_section; // Return: std::unique_ptr struct config_new { std::function(const char* filename)> body{ - [](const char* /* filename */) { return std::make_unique(); }}; - std::unique_ptr operator()(const char* filename) { - return body(filename); - }; + [](const char* /* filename */) { return std::make_unique(); }}; + std::unique_ptr operator()(const char* filename) { return body(filename); } }; extern struct config_new config_new; @@ -191,10 +178,8 @@ extern struct config_new config_new; // Return: std::unique_ptr struct config_new_clone { std::function(const config_t& src)> body{ - [](const config_t& /* src */) { return std::make_unique(); }}; - std::unique_ptr operator()(const config_t& src) { - return body(src); - }; + [](const config_t& /* src */) { return std::make_unique(); }}; + std::unique_ptr operator()(const config_t& src) { return body(src); } }; extern struct config_new_clone config_new_clone; @@ -203,8 +188,8 @@ extern struct config_new_clone config_new_clone; // Return: std::unique_ptr struct config_new_empty { std::function(void)> body{ - [](void) { return std::make_unique(); }}; - std::unique_ptr operator()(void) { return body(); }; + [](void) { return std::make_unique(); }}; + std::unique_ptr operator()(void) { return body(); } }; extern struct config_new_empty config_new_empty; @@ -213,14 +198,12 @@ extern struct config_new_empty config_new_empty; // Return: bool struct config_remove_key { bool return_value{false}; - std::function - body{[this](config_t* /* config */, const std::string& /* section */, - const std::string& /* key */) { return return_value; }}; - bool operator()(config_t* config, const std::string& section, - const std::string& key) { + std::function body{ + [this](config_t* /* config */, const std::string& /* section */, + const std::string& /* key */) { return return_value; }}; + bool operator()(config_t* config, const std::string& section, const std::string& key) { return body(config, section, key); - }; + } }; extern struct config_remove_key config_remove_key; @@ -230,12 +213,10 @@ extern struct config_remove_key config_remove_key; struct config_remove_section { bool return_value{false}; std::function body{ - [this](config_t* /* config */, const std::string& /* section */) { - return return_value; - }}; - bool operator()(config_t* config, const std::string& section) { - return body(config, section); - }; + [this](config_t* /* config */, const std::string& /* section */) { + return return_value; + }}; + bool operator()(config_t* config, const std::string& section) { return body(config, section); } }; extern struct config_remove_section config_remove_section; @@ -245,12 +226,12 @@ extern struct config_remove_section config_remove_section; struct config_save { bool return_value{false}; std::function body{ - [this](const config_t& /* config */, const std::string& /* filename */) { - return return_value; - }}; + [this](const config_t& /* config */, const std::string& /* filename */) { + return return_value; + }}; bool operator()(const config_t& config, const std::string& filename) { return body(config, filename); - }; + } }; extern struct config_save config_save; @@ -258,14 +239,14 @@ extern struct config_save config_save; // Params: config_t* config, const std::string& section, const std::string& key, // bool value Return: void struct config_set_bool { - std::function - body{[](config_t* /* config */, const std::string& /* section */, - const std::string& /* key */, bool /* value */) {}}; - void operator()(config_t* config, const std::string& section, - const std::string& key, bool value) { + std::function + body{[](config_t* /* config */, const std::string& /* section */, + const std::string& /* key */, bool /* value */) {}}; + void operator()(config_t* config, const std::string& section, const std::string& key, + bool value) { body(config, section, key, value); - }; + } }; extern struct config_set_bool config_set_bool; @@ -273,14 +254,13 @@ extern struct config_set_bool config_set_bool; // Params: config_t* config, const std::string& section, const std::string& key, // int value Return: void struct config_set_int { - std::function - body{[](config_t* /* config */, const std::string& /* section */, - const std::string& /* key */, int /* value */) {}}; - void operator()(config_t* config, const std::string& section, - const std::string& key, int value) { + std::function + body{[](config_t* /* config */, const std::string& /* section */, + const std::string& /* key */, int /* value */) {}}; + void operator()(config_t* config, const std::string& section, const std::string& key, int value) { body(config, section, key, value); - }; + } }; extern struct config_set_int config_set_int; @@ -288,14 +268,14 @@ extern struct config_set_int config_set_int; // Params: config_t* config, const std::string& section, const std::string& key, // const std::string& value Return: void struct config_set_string { - std::function - body{[](config_t* /* config */, const std::string& /* section */, - const std::string& /* key */, const std::string& /* value */) {}}; - void operator()(config_t* config, const std::string& section, - const std::string& key, const std::string& value) { + std::function + body{[](config_t* /* config */, const std::string& /* section */, + const std::string& /* key */, const std::string& /* value */) {}}; + void operator()(config_t* config, const std::string& section, const std::string& key, + const std::string& value) { body(config, section, key, value); - }; + } }; extern struct config_set_string config_set_string; @@ -303,14 +283,14 @@ extern struct config_set_string config_set_string; // Params: config_t* config, const std::string& section, const std::string& key, // uint64_t value Return: void struct config_set_uint64 { - std::function - body{[](config_t* /* config */, const std::string& /* section */, - const std::string& /* key */, uint64_t /* value */) {}}; - void operator()(config_t* config, const std::string& section, - const std::string& key, uint64_t value) { + std::function + body{[](config_t* /* config */, const std::string& /* section */, + const std::string& /* key */, uint64_t /* value */) {}}; + void operator()(config_t* config, const std::string& section, const std::string& key, + uint64_t value) { body(config, section, key, value); - }; + } }; extern struct config_set_uint64 config_set_uint64; @@ -319,13 +299,9 @@ extern struct config_set_uint64 config_set_uint64; // Return: std::list::iterator struct config_t_Find { std::list section_; - std::function::iterator(const std::string& section)> - body{[this](const std::string& /* section */) { - return section_.begin(); - }}; - std::list::iterator operator()(const std::string& section) { - return body(section); - }; + std::function::iterator(const std::string& section)> body{ + [this](const std::string& /* section */) { return section_.begin(); }}; + std::list::iterator operator()(const std::string& section) { return body(section); } }; extern struct config_t_Find config_t_Find; @@ -335,8 +311,8 @@ extern struct config_t_Find config_t_Find; struct config_t_Has { bool return_value{false}; std::function body{ - [this](const std::string& /* key */) { return return_value; }}; - bool operator()(const std::string& key) { return body(key); }; + [this](const std::string& /* key */) { return return_value; }}; + bool operator()(const std::string& key) { return body(key); } }; extern struct config_t_Has config_t_Has; @@ -346,10 +322,8 @@ extern struct config_t_Has config_t_Has; struct section_t_Find { std::list list_; std::function::iterator(const std::string& key)> body{ - [this](const std::string& /* key */) { return list_.begin(); }}; - std::list::iterator operator()(const std::string& key) { - return body(key); - }; + [this](const std::string& /* key */) { return list_.begin(); }}; + std::list::iterator operator()(const std::string& key) { return body(key); } }; extern struct section_t_Find section_t_Find; @@ -359,8 +333,8 @@ extern struct section_t_Find section_t_Find; struct section_t_Has { bool return_value{false}; std::function body{ - [this](const std::string& /* key */) { return return_value; }}; - bool operator()(const std::string& key) { return body(key); }; + [this](const std::string& /* key */) { return return_value; }}; + bool operator()(const std::string& key) { return body(key); } }; extern struct section_t_Has section_t_Has; @@ -369,8 +343,8 @@ extern struct section_t_Has section_t_Has; // Return: void struct section_t_Set { std::function body{ - [](std::string /* key */, std::string /* value */) {}}; - void operator()(std::string key, std::string value) { body(key, value); }; + [](std::string /* key */, std::string /* value */) {}}; + void operator()(std::string key, std::string value) { body(key, value); } }; extern struct section_t_Set section_t_Set; diff --git a/system/test/mock/mock_osi_fixed_queue.cc b/system/test/mock/mock_osi_fixed_queue.cc index b4658f9e06d..2a5284c4468 100644 --- a/system/test/mock/mock_osi_fixed_queue.cc +++ b/system/test/mock/mock_osi_fixed_queue.cc @@ -100,11 +100,10 @@ fixed_queue_t* fixed_queue_new(size_t capacity) { inc_func_call_count(__func__); return test::mock::osi_fixed_queue::fixed_queue_new(capacity); } -void fixed_queue_register_dequeue(fixed_queue_t* queue, reactor_t* reactor, - fixed_queue_cb ready_cb, void* context) { +void fixed_queue_register_dequeue(fixed_queue_t* queue, reactor_t* reactor, fixed_queue_cb ready_cb, + void* context) { inc_func_call_count(__func__); - test::mock::osi_fixed_queue::fixed_queue_register_dequeue(queue, reactor, - ready_cb, context); + test::mock::osi_fixed_queue::fixed_queue_register_dequeue(queue, reactor, ready_cb, context); } void* fixed_queue_try_dequeue(fixed_queue_t* queue) { inc_func_call_count(__func__); @@ -124,8 +123,7 @@ void* fixed_queue_try_peek_last(fixed_queue_t* queue) { } void* fixed_queue_try_remove_from_queue(fixed_queue_t* queue, void* data) { inc_func_call_count(__func__); - return test::mock::osi_fixed_queue::fixed_queue_try_remove_from_queue(queue, - data); + return test::mock::osi_fixed_queue::fixed_queue_try_remove_from_queue(queue, data); } void fixed_queue_unregister_dequeue(fixed_queue_t* queue) { inc_func_call_count(__func__); diff --git a/system/test/mock/mock_osi_fixed_queue.h b/system/test/mock/mock_osi_fixed_queue.h index e8d93ed0475..8fd07162610 100644 --- a/system/test/mock/mock_osi_fixed_queue.h +++ b/system/test/mock/mock_osi_fixed_queue.h @@ -44,8 +44,8 @@ namespace osi_fixed_queue { struct fixed_queue_capacity { size_t return_value{0}; std::function body{ - [this](fixed_queue_t* /* queue */) { return return_value; }}; - size_t operator()(fixed_queue_t* queue) { return body(queue); }; + [this](fixed_queue_t* /* queue */) { return return_value; }}; + size_t operator()(fixed_queue_t* queue) { return body(queue); } }; extern struct fixed_queue_capacity fixed_queue_capacity; @@ -55,8 +55,8 @@ extern struct fixed_queue_capacity fixed_queue_capacity; struct fixed_queue_dequeue { void* return_value{}; std::function body{ - [this](fixed_queue_t* /* queue */) { return return_value; }}; - void* operator()(fixed_queue_t* queue) { return body(queue); }; + [this](fixed_queue_t* /* queue */) { return return_value; }}; + void* operator()(fixed_queue_t* queue) { return body(queue); } }; extern struct fixed_queue_dequeue fixed_queue_dequeue; @@ -65,8 +65,8 @@ extern struct fixed_queue_dequeue fixed_queue_dequeue; // Return: void struct fixed_queue_enqueue { std::function body{ - [](fixed_queue_t* /* queue */, void* /* data */) {}}; - void operator()(fixed_queue_t* queue, void* data) { body(queue, data); }; + [](fixed_queue_t* /* queue */, void* /* data */) {}}; + void operator()(fixed_queue_t* queue, void* data) { body(queue, data); } }; extern struct fixed_queue_enqueue fixed_queue_enqueue; @@ -75,10 +75,8 @@ extern struct fixed_queue_enqueue fixed_queue_enqueue; // Return: void struct fixed_queue_flush { std::function body{ - [](fixed_queue_t* /* queue */, fixed_queue_free_cb /* free_cb */) {}}; - void operator()(fixed_queue_t* queue, fixed_queue_free_cb free_cb) { - body(queue, free_cb); - }; + [](fixed_queue_t* /* queue */, fixed_queue_free_cb /* free_cb */) {}}; + void operator()(fixed_queue_t* queue, fixed_queue_free_cb free_cb) { body(queue, free_cb); } }; extern struct fixed_queue_flush fixed_queue_flush; @@ -87,10 +85,8 @@ extern struct fixed_queue_flush fixed_queue_flush; // Return: void struct fixed_queue_free { std::function body{ - [](fixed_queue_t* /* queue */, fixed_queue_free_cb /* free_cb */) {}}; - void operator()(fixed_queue_t* queue, fixed_queue_free_cb free_cb) { - body(queue, free_cb); - }; + [](fixed_queue_t* /* queue */, fixed_queue_free_cb /* free_cb */) {}}; + void operator()(fixed_queue_t* queue, fixed_queue_free_cb free_cb) { body(queue, free_cb); } }; extern struct fixed_queue_free fixed_queue_free; @@ -100,8 +96,8 @@ extern struct fixed_queue_free fixed_queue_free; struct fixed_queue_get_dequeue_fd { int return_value{0}; std::function body{ - [this](const fixed_queue_t* /* queue */) { return return_value; }}; - int operator()(const fixed_queue_t* queue) { return body(queue); }; + [this](const fixed_queue_t* /* queue */) { return return_value; }}; + int operator()(const fixed_queue_t* queue) { return body(queue); } }; extern struct fixed_queue_get_dequeue_fd fixed_queue_get_dequeue_fd; @@ -111,8 +107,8 @@ extern struct fixed_queue_get_dequeue_fd fixed_queue_get_dequeue_fd; struct fixed_queue_get_enqueue_fd { int return_value{0}; std::function body{ - [this](const fixed_queue_t* /* queue */) { return return_value; }}; - int operator()(const fixed_queue_t* queue) { return body(queue); }; + [this](const fixed_queue_t* /* queue */) { return return_value; }}; + int operator()(const fixed_queue_t* queue) { return body(queue); } }; extern struct fixed_queue_get_enqueue_fd fixed_queue_get_enqueue_fd; @@ -122,8 +118,8 @@ extern struct fixed_queue_get_enqueue_fd fixed_queue_get_enqueue_fd; struct fixed_queue_get_list { list_t* return_value{0}; std::function body{ - [this](fixed_queue_t* /* queue */) { return return_value; }}; - list_t* operator()(fixed_queue_t* queue) { return body(queue); }; + [this](fixed_queue_t* /* queue */) { return return_value; }}; + list_t* operator()(fixed_queue_t* queue) { return body(queue); } }; extern struct fixed_queue_get_list fixed_queue_get_list; @@ -133,8 +129,8 @@ extern struct fixed_queue_get_list fixed_queue_get_list; struct fixed_queue_is_empty { bool return_value{false}; std::function body{ - [this](fixed_queue_t* /* queue */) { return return_value; }}; - bool operator()(fixed_queue_t* queue) { return body(queue); }; + [this](fixed_queue_t* /* queue */) { return return_value; }}; + bool operator()(fixed_queue_t* queue) { return body(queue); } }; extern struct fixed_queue_is_empty fixed_queue_is_empty; @@ -144,8 +140,8 @@ extern struct fixed_queue_is_empty fixed_queue_is_empty; struct fixed_queue_length { size_t return_value{0}; std::function body{ - [this](fixed_queue_t* /* queue */) { return return_value; }}; - size_t operator()(fixed_queue_t* queue) { return body(queue); }; + [this](fixed_queue_t* /* queue */) { return return_value; }}; + size_t operator()(fixed_queue_t* queue) { return body(queue); } }; extern struct fixed_queue_length fixed_queue_length; @@ -155,8 +151,8 @@ extern struct fixed_queue_length fixed_queue_length; struct fixed_queue_new { fixed_queue_t* return_value{0}; std::function body{ - [this](size_t /* capacity */) { return return_value; }}; - fixed_queue_t* operator()(size_t capacity) { return body(capacity); }; + [this](size_t /* capacity */) { return return_value; }}; + fixed_queue_t* operator()(size_t capacity) { return body(capacity); } }; extern struct fixed_queue_new fixed_queue_new; @@ -164,14 +160,14 @@ extern struct fixed_queue_new fixed_queue_new; // Params: fixed_queue_t* queue, reactor_t* reactor, fixed_queue_cb ready_cb, // void* context Return: void struct fixed_queue_register_dequeue { - std::function - body{[](fixed_queue_t* /* queue */, reactor_t* /* reactor */, - fixed_queue_cb /* ready_cb */, void* /* context */) {}}; - void operator()(fixed_queue_t* queue, reactor_t* reactor, - fixed_queue_cb ready_cb, void* context) { + std::function + body{[](fixed_queue_t* /* queue */, reactor_t* /* reactor */, + fixed_queue_cb /* ready_cb */, void* /* context */) {}}; + void operator()(fixed_queue_t* queue, reactor_t* reactor, fixed_queue_cb ready_cb, + void* context) { body(queue, reactor, ready_cb, context); - }; + } }; extern struct fixed_queue_register_dequeue fixed_queue_register_dequeue; @@ -181,8 +177,8 @@ extern struct fixed_queue_register_dequeue fixed_queue_register_dequeue; struct fixed_queue_try_dequeue { void* return_value{}; std::function body{ - [this](fixed_queue_t* /* queue */) { return return_value; }}; - void* operator()(fixed_queue_t* queue) { return body(queue); }; + [this](fixed_queue_t* /* queue */) { return return_value; }}; + void* operator()(fixed_queue_t* queue) { return body(queue); } }; extern struct fixed_queue_try_dequeue fixed_queue_try_dequeue; @@ -192,12 +188,8 @@ extern struct fixed_queue_try_dequeue fixed_queue_try_dequeue; struct fixed_queue_try_enqueue { bool return_value{false}; std::function body{ - [this](fixed_queue_t* /* queue */, void* /* data */) { - return return_value; - }}; - bool operator()(fixed_queue_t* queue, void* data) { - return body(queue, data); - }; + [this](fixed_queue_t* /* queue */, void* /* data */) { return return_value; }}; + bool operator()(fixed_queue_t* queue, void* data) { return body(queue, data); } }; extern struct fixed_queue_try_enqueue fixed_queue_try_enqueue; @@ -207,8 +199,8 @@ extern struct fixed_queue_try_enqueue fixed_queue_try_enqueue; struct fixed_queue_try_peek_first { void* return_value{}; std::function body{ - [this](fixed_queue_t* /* queue */) { return return_value; }}; - void* operator()(fixed_queue_t* queue) { return body(queue); }; + [this](fixed_queue_t* /* queue */) { return return_value; }}; + void* operator()(fixed_queue_t* queue) { return body(queue); } }; extern struct fixed_queue_try_peek_first fixed_queue_try_peek_first; @@ -218,8 +210,8 @@ extern struct fixed_queue_try_peek_first fixed_queue_try_peek_first; struct fixed_queue_try_peek_last { void* return_value{}; std::function body{ - [this](fixed_queue_t* /* queue */) { return return_value; }}; - void* operator()(fixed_queue_t* queue) { return body(queue); }; + [this](fixed_queue_t* /* queue */) { return return_value; }}; + void* operator()(fixed_queue_t* queue) { return body(queue); } }; extern struct fixed_queue_try_peek_last fixed_queue_try_peek_last; @@ -229,23 +221,17 @@ extern struct fixed_queue_try_peek_last fixed_queue_try_peek_last; struct fixed_queue_try_remove_from_queue { void* return_value{}; std::function body{ - [this](fixed_queue_t* /* queue */, void* /* data */) { - return return_value; - }}; - void* operator()(fixed_queue_t* queue, void* data) { - return body(queue, data); - }; + [this](fixed_queue_t* /* queue */, void* /* data */) { return return_value; }}; + void* operator()(fixed_queue_t* queue, void* data) { return body(queue, data); } }; -extern struct fixed_queue_try_remove_from_queue - fixed_queue_try_remove_from_queue; +extern struct fixed_queue_try_remove_from_queue fixed_queue_try_remove_from_queue; // Name: fixed_queue_unregister_dequeue // Params: fixed_queue_t* queue // Return: void struct fixed_queue_unregister_dequeue { - std::function body{ - [](fixed_queue_t* /* queue */) {}}; - void operator()(fixed_queue_t* queue) { body(queue); }; + std::function body{[](fixed_queue_t* /* queue */) {}}; + void operator()(fixed_queue_t* queue) { body(queue); } }; extern struct fixed_queue_unregister_dequeue fixed_queue_unregister_dequeue; diff --git a/system/test/mock/mock_osi_future.h b/system/test/mock/mock_osi_future.h index 07841b0615a..bb4ab1f6100 100644 --- a/system/test/mock/mock_osi_future.h +++ b/system/test/mock/mock_osi_future.h @@ -42,8 +42,8 @@ namespace osi_future { struct future_await { void* return_value{}; std::function body{ - [this](future_t* /* future */) { return return_value; }}; - void* operator()(future_t* future) { return body(future); }; + [this](future_t* /* future */) { return return_value; }}; + void* operator()(future_t* future) { return body(future); } }; extern struct future_await future_await; @@ -53,7 +53,7 @@ extern struct future_await future_await; struct future_new { future_t* return_value{0}; std::function body{[this](void) { return return_value; }}; - future_t* operator()(void) { return body(); }; + future_t* operator()(void) { return body(); } }; extern struct future_new future_new; @@ -63,8 +63,8 @@ extern struct future_new future_new; struct future_new_named { future_t* return_value{0}; std::function body{ - [this](const char* /* name */) { return return_value; }}; - future_t* operator()(const char* name) { return body(name); }; + [this](const char* /* name */) { return return_value; }}; + future_t* operator()(const char* name) { return body(name); } }; extern struct future_new_named future_new_named; @@ -77,7 +77,7 @@ struct future_new_immediate { bluetooth::log::fatal("unexpectedly called"); return return_value; }}; - future_t* operator()(void* value) { return body(value); }; + future_t* operator()(void* value) { return body(value); } }; extern struct future_new_immediate future_new_immediate; @@ -86,8 +86,8 @@ extern struct future_new_immediate future_new_immediate; // Return: void struct future_ready { std::function body{ - [](future_t* /* future */, void* /* value */) {}}; - void operator()(future_t* future, void* value) { body(future, value); }; + [](future_t* /* future */, void* /* value */) {}}; + void operator()(future_t* future, void* value) { body(future, value); } }; extern struct future_ready future_ready; diff --git a/system/test/mock/mock_osi_list.cc b/system/test/mock/mock_osi_list.cc index 68315bc91c0..bed9c042876 100644 --- a/system/test/mock/mock_osi_list.cc +++ b/system/test/mock/mock_osi_list.cc @@ -85,8 +85,7 @@ list_node_t* list_end(const list_t* list) { inc_func_call_count(__func__); return test::mock::osi_list::list_end(list); } -list_node_t* list_foreach(const list_t* list, list_iter_cb callback, - void* context) { +list_node_t* list_foreach(const list_t* list, list_iter_cb callback, void* context) { inc_func_call_count(__func__); return test::mock::osi_list::list_foreach(list, callback, context); } @@ -114,8 +113,7 @@ list_t* list_new(list_free_cb callback) { inc_func_call_count(__func__); return test::mock::osi_list::list_new(callback); } -list_t* list_new_internal(list_free_cb callback, - const allocator_t* zeroed_allocator) { +list_t* list_new_internal(list_free_cb callback, const allocator_t* zeroed_allocator) { inc_func_call_count(__func__); return test::mock::osi_list::list_new_internal(callback, zeroed_allocator); } diff --git a/system/test/mock/mock_osi_list.h b/system/test/mock/mock_osi_list.h index 05c973ba60c..86813a8adc4 100644 --- a/system/test/mock/mock_osi_list.h +++ b/system/test/mock/mock_osi_list.h @@ -41,8 +41,8 @@ namespace osi_list { struct list_append { bool return_value{false}; std::function body{ - [this](list_t* /* list */, void* /* data */) { return return_value; }}; - bool operator()(list_t* list, void* data) { return body(list, data); }; + [this](list_t* /* list */, void* /* data */) { return return_value; }}; + bool operator()(list_t* list, void* data) { return body(list, data); } }; extern struct list_append list_append; @@ -52,8 +52,8 @@ extern struct list_append list_append; struct list_back { void* return_value{}; std::function body{ - [this](const list_t* /* list */) { return return_value; }}; - void* operator()(const list_t* list) { return body(list); }; + [this](const list_t* /* list */) { return return_value; }}; + void* operator()(const list_t* list) { return body(list); } }; extern struct list_back list_back; @@ -63,8 +63,8 @@ extern struct list_back list_back; struct list_back_node { list_node_t* return_value{0}; std::function body{ - [this](const list_t* /* list */) { return return_value; }}; - list_node_t* operator()(const list_t* list) { return body(list); }; + [this](const list_t* /* list */) { return return_value; }}; + list_node_t* operator()(const list_t* list) { return body(list); } }; extern struct list_back_node list_back_node; @@ -74,8 +74,8 @@ extern struct list_back_node list_back_node; struct list_begin { list_node_t* return_value{0}; std::function body{ - [this](const list_t* /* list */) { return return_value; }}; - list_node_t* operator()(const list_t* list) { return body(list); }; + [this](const list_t* /* list */) { return return_value; }}; + list_node_t* operator()(const list_t* list) { return body(list); } }; extern struct list_begin list_begin; @@ -84,7 +84,7 @@ extern struct list_begin list_begin; // Return: void struct list_clear { std::function body{[](list_t* /* list */) {}}; - void operator()(list_t* list) { body(list); }; + void operator()(list_t* list) { body(list); } }; extern struct list_clear list_clear; @@ -94,12 +94,8 @@ extern struct list_clear list_clear; struct list_contains { bool return_value{false}; std::function body{ - [this](const list_t* /* list */, const void* /* data */) { - return return_value; - }}; - bool operator()(const list_t* list, const void* data) { - return body(list, data); - }; + [this](const list_t* /* list */, const void* /* data */) { return return_value; }}; + bool operator()(const list_t* list, const void* data) { return body(list, data); } }; extern struct list_contains list_contains; @@ -109,8 +105,8 @@ extern struct list_contains list_contains; struct list_end { list_node_t* return_value{0}; std::function body{ - [this](const list_t* /* list */) { return return_value; }}; - list_node_t* operator()(const list_t* list) { return body(list); }; + [this](const list_t* /* list */) { return return_value; }}; + list_node_t* operator()(const list_t* list) { return body(list); } }; extern struct list_end list_end; @@ -119,14 +115,13 @@ extern struct list_end list_end; // Return: list_node_t* struct list_foreach { list_node_t* return_value{0}; - std::function - body{[this](const list_t* /* list */, list_iter_cb /* callback */, - void* /* context */) { return return_value; }}; - list_node_t* operator()(const list_t* list, list_iter_cb callback, - void* context) { + std::function body{ + [this](const list_t* /* list */, list_iter_cb /* callback */, void* /* context */) { + return return_value; + }}; + list_node_t* operator()(const list_t* list, list_iter_cb callback, void* context) { return body(list, callback, context); - }; + } }; extern struct list_foreach list_foreach; @@ -135,7 +130,7 @@ extern struct list_foreach list_foreach; // Return: void struct list_free { std::function body{[](list_t* /* list */) {}}; - void operator()(list_t* list) { body(list); }; + void operator()(list_t* list) { body(list); } }; extern struct list_free list_free; @@ -145,8 +140,8 @@ extern struct list_free list_free; struct list_front { void* return_value{}; std::function body{ - [this](const list_t* /* list */) { return return_value; }}; - void* operator()(const list_t* list) { return body(list); }; + [this](const list_t* /* list */) { return return_value; }}; + void* operator()(const list_t* list) { return body(list); } }; extern struct list_front list_front; @@ -156,11 +151,12 @@ extern struct list_front list_front; struct list_insert_after { bool return_value{false}; std::function body{ - [this](list_t* /* list */, list_node_t* /* prev_node */, - void* /* data */) { return return_value; }}; + [this](list_t* /* list */, list_node_t* /* prev_node */, void* /* data */) { + return return_value; + }}; bool operator()(list_t* list, list_node_t* prev_node, void* data) { return body(list, prev_node, data); - }; + } }; extern struct list_insert_after list_insert_after; @@ -170,8 +166,8 @@ extern struct list_insert_after list_insert_after; struct list_is_empty { bool return_value{false}; std::function body{ - [this](const list_t* /* list */) { return return_value; }}; - bool operator()(const list_t* list) { return body(list); }; + [this](const list_t* /* list */) { return return_value; }}; + bool operator()(const list_t* list) { return body(list); } }; extern struct list_is_empty list_is_empty; @@ -181,8 +177,8 @@ extern struct list_is_empty list_is_empty; struct list_length { size_t return_value{0}; std::function body{ - [this](const list_t* /* list */) { return return_value; }}; - size_t operator()(const list_t* list) { return body(list); }; + [this](const list_t* /* list */) { return return_value; }}; + size_t operator()(const list_t* list) { return body(list); } }; extern struct list_length list_length; @@ -192,8 +188,8 @@ extern struct list_length list_length; struct list_new { list_t* return_value{0}; std::function body{ - [this](list_free_cb /* callback */) { return return_value; }}; - list_t* operator()(list_free_cb callback) { return body(callback); }; + [this](list_free_cb /* callback */) { return return_value; }}; + list_t* operator()(list_free_cb callback) { return body(callback); } }; extern struct list_new list_new; @@ -202,16 +198,13 @@ extern struct list_new list_new; // Return: list_t* struct list_new_internal { list_t* return_value{0}; - std::function - body{[this](list_free_cb /* callback */, - const allocator_t* /* zeroed_allocator */) { - return return_value; - }}; - list_t* operator()(list_free_cb callback, - const allocator_t* zeroed_allocator) { + std::function body{ + [this](list_free_cb /* callback */, const allocator_t* /* zeroed_allocator */) { + return return_value; + }}; + list_t* operator()(list_free_cb callback, const allocator_t* zeroed_allocator) { return body(callback, zeroed_allocator); - }; + } }; extern struct list_new_internal list_new_internal; @@ -221,8 +214,8 @@ extern struct list_new_internal list_new_internal; struct list_next { list_node_t* return_value{0}; std::function body{ - [this](const list_node_t* /* node */) { return return_value; }}; - list_node_t* operator()(const list_node_t* node) { return body(node); }; + [this](const list_node_t* /* node */) { return return_value; }}; + list_node_t* operator()(const list_node_t* node) { return body(node); } }; extern struct list_next list_next; @@ -232,8 +225,8 @@ extern struct list_next list_next; struct list_node { void* return_value{}; std::function body{ - [this](const list_node_t* /* node */) { return return_value; }}; - void* operator()(const list_node_t* node) { return body(node); }; + [this](const list_node_t* /* node */) { return return_value; }}; + void* operator()(const list_node_t* node) { return body(node); } }; extern struct list_node list_node; @@ -243,8 +236,8 @@ extern struct list_node list_node; struct list_prepend { bool return_value{false}; std::function body{ - [this](list_t* /* list */, void* /* data */) { return return_value; }}; - bool operator()(list_t* list, void* data) { return body(list, data); }; + [this](list_t* /* list */, void* /* data */) { return return_value; }}; + bool operator()(list_t* list, void* data) { return body(list, data); } }; extern struct list_prepend list_prepend; @@ -254,8 +247,8 @@ extern struct list_prepend list_prepend; struct list_remove { bool return_value{false}; std::function body{ - [this](list_t* /* list */, void* /* data */) { return return_value; }}; - bool operator()(list_t* list, void* data) { return body(list, data); }; + [this](list_t* /* list */, void* /* data */) { return return_value; }}; + bool operator()(list_t* list, void* data) { return body(list, data); } }; extern struct list_remove list_remove; diff --git a/system/test/mock/mock_osi_mutex.h b/system/test/mock/mock_osi_mutex.h index be01b064626..45144253ec9 100644 --- a/system/test/mock/mock_osi_mutex.h +++ b/system/test/mock/mock_osi_mutex.h @@ -39,7 +39,7 @@ namespace osi_mutex { // Return: void struct mutex_global_lock { std::function body{[](void) {}}; - void operator()(void) { body(); }; + void operator()(void) { body(); } }; extern struct mutex_global_lock mutex_global_lock; @@ -48,7 +48,7 @@ extern struct mutex_global_lock mutex_global_lock; // Return: void struct mutex_global_unlock { std::function body{[](void) {}}; - void operator()(void) { body(); }; + void operator()(void) { body(); } }; extern struct mutex_global_unlock mutex_global_unlock; diff --git a/system/test/mock/mock_osi_properties.cc b/system/test/mock/mock_osi_properties.cc index 46e0f9a9715..cc2231125d0 100644 --- a/system/test/mock/mock_osi_properties.cc +++ b/system/test/mock/mock_osi_properties.cc @@ -47,8 +47,7 @@ struct osi_property_set osi_property_set; // Mocked functions, if any int osi_property_get(const char* key, char* value, const char* default_value) { inc_func_call_count(__func__); - return test::mock::osi_properties::osi_property_get(key, value, - default_value); + return test::mock::osi_properties::osi_property_get(key, value, default_value); } bool osi_property_get_bool(const char* key, bool default_value) { inc_func_call_count(__func__); @@ -58,8 +57,8 @@ int32_t osi_property_get_int32(const char* key, int32_t default_value) { inc_func_call_count(__func__); return test::mock::osi_properties::osi_property_get_int32(key, default_value); } -std::vector osi_property_get_uintlist( - const char* /* key */, std::vector default_value) { +std::vector osi_property_get_uintlist(const char* /* key */, + std::vector default_value) { inc_func_call_count(__func__); return default_value; } diff --git a/system/test/mock/mock_osi_properties.h b/system/test/mock/mock_osi_properties.h index 9ff364b1417..ad1c29c8d32 100644 --- a/system/test/mock/mock_osi_properties.h +++ b/system/test/mock/mock_osi_properties.h @@ -39,12 +39,13 @@ namespace osi_properties { // Return: int struct osi_property_get { int return_value{0}; - std::function - body{[this](const char* /* key */, char* /* value */, - const char* /* default_value */) { return return_value; }}; + std::function body{ + [this](const char* /* key */, char* /* value */, const char* /* default_value */) { + return return_value; + }}; int operator()(const char* key, char* value, const char* default_value) { return body(key, value, default_value); - }; + } }; extern struct osi_property_get osi_property_get; @@ -54,12 +55,8 @@ extern struct osi_property_get osi_property_get; struct osi_property_get_bool { bool return_value{false}; std::function body{ - [this](const char* /* key */, bool /* default_value */) { - return return_value; - }}; - bool operator()(const char* key, bool default_value) { - return body(key, default_value); - }; + [this](const char* /* key */, bool /* default_value */) { return return_value; }}; + bool operator()(const char* key, bool default_value) { return body(key, default_value); } }; extern struct osi_property_get_bool osi_property_get_bool; @@ -69,12 +66,8 @@ extern struct osi_property_get_bool osi_property_get_bool; struct osi_property_get_int32 { int32_t return_value{0}; std::function body{ - [this](const char* /* key */, int32_t /* default_value */) { - return return_value; - }}; - int32_t operator()(const char* key, int32_t default_value) { - return body(key, default_value); - }; + [this](const char* /* key */, int32_t /* default_value */) { return return_value; }}; + int32_t operator()(const char* key, int32_t default_value) { return body(key, default_value); } }; extern struct osi_property_get_int32 osi_property_get_int32; @@ -84,12 +77,8 @@ extern struct osi_property_get_int32 osi_property_get_int32; struct osi_property_set { int return_value{0}; std::function body{ - [this](const char* /* key */, const char* /* value */) { - return return_value; - }}; - int operator()(const char* key, const char* value) { - return body(key, value); - }; + [this](const char* /* key */, const char* /* value */) { return return_value; }}; + int operator()(const char* key, const char* value) { return body(key, value); } }; extern struct osi_property_set osi_property_set; diff --git a/system/test/mock/mock_osi_ringbuffer.cc b/system/test/mock/mock_osi_ringbuffer.cc index 58c506e2461..be0500715af 100644 --- a/system/test/mock/mock_osi_ringbuffer.cc +++ b/system/test/mock/mock_osi_ringbuffer.cc @@ -68,8 +68,7 @@ size_t ringbuffer_insert(ringbuffer_t* rb, const uint8_t* p, size_t length) { inc_func_call_count(__func__); return test::mock::osi_ringbuffer::ringbuffer_insert(rb, p, length); } -size_t ringbuffer_peek(const ringbuffer_t* rb, off_t offset, uint8_t* p, - size_t length) { +size_t ringbuffer_peek(const ringbuffer_t* rb, off_t offset, uint8_t* p, size_t length) { inc_func_call_count(__func__); return test::mock::osi_ringbuffer::ringbuffer_peek(rb, offset, p, length); } diff --git a/system/test/mock/mock_osi_ringbuffer.h b/system/test/mock/mock_osi_ringbuffer.h index 11f8db34a36..40f649d099f 100644 --- a/system/test/mock/mock_osi_ringbuffer.h +++ b/system/test/mock/mock_osi_ringbuffer.h @@ -43,8 +43,8 @@ namespace osi_ringbuffer { struct ringbuffer_available { size_t return_value{0}; std::function body{ - [this](const ringbuffer_t* /* rb */) { return return_value; }}; - size_t operator()(const ringbuffer_t* rb) { return body(rb); }; + [this](const ringbuffer_t* /* rb */) { return return_value; }}; + size_t operator()(const ringbuffer_t* rb) { return body(rb); } }; extern struct ringbuffer_available ringbuffer_available; @@ -54,12 +54,8 @@ extern struct ringbuffer_available ringbuffer_available; struct ringbuffer_delete { size_t return_value{0}; std::function body{ - [this](ringbuffer_t* /* rb */, size_t /* length */) { - return return_value; - }}; - size_t operator()(ringbuffer_t* rb, size_t length) { - return body(rb, length); - }; + [this](ringbuffer_t* /* rb */, size_t /* length */) { return return_value; }}; + size_t operator()(ringbuffer_t* rb, size_t length) { return body(rb, length); } }; extern struct ringbuffer_delete ringbuffer_delete; @@ -68,7 +64,7 @@ extern struct ringbuffer_delete ringbuffer_delete; // Return: void struct ringbuffer_free { std::function body{[](ringbuffer_t* /* rb */) {}}; - void operator()(ringbuffer_t* rb) { body(rb); }; + void operator()(ringbuffer_t* rb) { body(rb); } }; extern struct ringbuffer_free ringbuffer_free; @@ -78,8 +74,8 @@ extern struct ringbuffer_free ringbuffer_free; struct ringbuffer_init { ringbuffer_t* return_value{0}; std::function body{ - [this](const size_t /* size */) { return return_value; }}; - ringbuffer_t* operator()(const size_t size) { return body(size); }; + [this](const size_t /* size */) { return return_value; }}; + ringbuffer_t* operator()(const size_t size) { return body(size); } }; extern struct ringbuffer_init ringbuffer_init; @@ -89,11 +85,12 @@ extern struct ringbuffer_init ringbuffer_init; struct ringbuffer_insert { size_t return_value{0}; std::function body{ - [this](ringbuffer_t* /* rb */, const uint8_t* /* p */, - size_t /* length */) { return return_value; }}; + [this](ringbuffer_t* /* rb */, const uint8_t* /* p */, size_t /* length */) { + return return_value; + }}; size_t operator()(ringbuffer_t* rb, const uint8_t* p, size_t length) { return body(rb, p, length); - }; + } }; extern struct ringbuffer_insert ringbuffer_insert; @@ -102,15 +99,12 @@ extern struct ringbuffer_insert ringbuffer_insert; // Return: size_t struct ringbuffer_peek { size_t return_value{0}; - std::function - body{[this](const ringbuffer_t* /* rb */, off_t /* offset */, - uint8_t* /* p */, - size_t /* length */) { return return_value; }}; - size_t operator()(const ringbuffer_t* rb, off_t offset, uint8_t* p, - size_t length) { + std::function body{ + [this](const ringbuffer_t* /* rb */, off_t /* offset */, uint8_t* /* p */, + size_t /* length */) { return return_value; }}; + size_t operator()(const ringbuffer_t* rb, off_t offset, uint8_t* p, size_t length) { return body(rb, offset, p, length); - }; + } }; extern struct ringbuffer_peek ringbuffer_peek; @@ -120,12 +114,10 @@ extern struct ringbuffer_peek ringbuffer_peek; struct ringbuffer_pop { size_t return_value{0}; std::function body{ - [this](ringbuffer_t* /* rb */, uint8_t* /* p */, size_t /* length */) { - return return_value; - }}; - size_t operator()(ringbuffer_t* rb, uint8_t* p, size_t length) { - return body(rb, p, length); - }; + [this](ringbuffer_t* /* rb */, uint8_t* /* p */, size_t /* length */) { + return return_value; + }}; + size_t operator()(ringbuffer_t* rb, uint8_t* p, size_t length) { return body(rb, p, length); } }; extern struct ringbuffer_pop ringbuffer_pop; @@ -135,8 +127,8 @@ extern struct ringbuffer_pop ringbuffer_pop; struct ringbuffer_size { size_t return_value{0}; std::function body{ - [this](const ringbuffer_t* /* rb */) { return return_value; }}; - size_t operator()(const ringbuffer_t* rb) { return body(rb); }; + [this](const ringbuffer_t* /* rb */) { return return_value; }}; + size_t operator()(const ringbuffer_t* rb) { return body(rb); } }; extern struct ringbuffer_size ringbuffer_size; diff --git a/system/test/mock/mock_osi_socket.cc b/system/test/mock/mock_osi_socket.cc index be411f2f9a3..6fecb157e45 100644 --- a/system/test/mock/mock_osi_socket.cc +++ b/system/test/mock/mock_osi_socket.cc @@ -77,11 +77,10 @@ ssize_t socket_read(const socket_t* socket, void* buf, size_t count) { inc_func_call_count(__func__); return test::mock::osi_socket::socket_read(socket, buf, count); } -void socket_register(socket_t* socket, reactor_t* reactor, void* context, - socket_cb read_cb, socket_cb write_cb) { +void socket_register(socket_t* socket, reactor_t* reactor, void* context, socket_cb read_cb, + socket_cb write_cb) { inc_func_call_count(__func__); - test::mock::osi_socket::socket_register(socket, reactor, context, read_cb, - write_cb); + test::mock::osi_socket::socket_register(socket, reactor, context, read_cb, write_cb); } void socket_unregister(socket_t* socket) { inc_func_call_count(__func__); @@ -91,16 +90,14 @@ ssize_t socket_write(const socket_t* socket, const void* buf, size_t count) { inc_func_call_count(__func__); return test::mock::osi_socket::socket_write(socket, buf, count); } -ssize_t socket_write_and_transfer_fd(const socket_t* socket, const void* buf, - size_t count, int fd) { +ssize_t socket_write_and_transfer_fd(const socket_t* socket, const void* buf, size_t count, + int fd) { inc_func_call_count(__func__); - return test::mock::osi_socket::socket_write_and_transfer_fd(socket, buf, - count, fd); + return test::mock::osi_socket::socket_write_and_transfer_fd(socket, buf, count, fd); } // Mocked functions complete // END mockcify generation -int osi_socket_local_server_bind(int /* s */, const char* /* name */, - int /* namespaceId */) { +int osi_socket_local_server_bind(int /* s */, const char* /* name */, int /* namespaceId */) { inc_func_call_count(__func__); return 0; } diff --git a/system/test/mock/mock_osi_socket.h b/system/test/mock/mock_osi_socket.h index 6c86bfeb908..1db5df21345 100644 --- a/system/test/mock/mock_osi_socket.h +++ b/system/test/mock/mock_osi_socket.h @@ -40,8 +40,8 @@ namespace osi_socket { struct socket_accept { socket_t* return_value{0}; std::function body{ - [this](const socket_t* /* socket */) { return return_value; }}; - socket_t* operator()(const socket_t* socket) { return body(socket); }; + [this](const socket_t* /* socket */) { return return_value; }}; + socket_t* operator()(const socket_t* socket) { return body(socket); } }; extern struct socket_accept socket_accept; @@ -51,8 +51,8 @@ extern struct socket_accept socket_accept; struct socket_bytes_available { ssize_t return_value{0}; std::function body{ - [this](const socket_t* /* socket */) { return return_value; }}; - ssize_t operator()(const socket_t* socket) { return body(socket); }; + [this](const socket_t* /* socket */) { return return_value; }}; + ssize_t operator()(const socket_t* socket) { return body(socket); } }; extern struct socket_bytes_available socket_bytes_available; @@ -61,7 +61,7 @@ extern struct socket_bytes_available socket_bytes_available; // Return: void struct socket_free { std::function body{[](socket_t* /* socket */) {}}; - void operator()(socket_t* socket) { body(socket); }; + void operator()(socket_t* socket) { body(socket); } }; extern struct socket_free socket_free; @@ -71,12 +71,8 @@ extern struct socket_free socket_free; struct socket_listen { bool return_value{false}; std::function body{ - [this](const socket_t* /* socket */, port_t /* port */) { - return return_value; - }}; - bool operator()(const socket_t* socket, port_t port) { - return body(socket, port); - }; + [this](const socket_t* /* socket */, port_t /* port */) { return return_value; }}; + bool operator()(const socket_t* socket, port_t port) { return body(socket, port); } }; extern struct socket_listen socket_listen; @@ -86,7 +82,7 @@ extern struct socket_listen socket_listen; struct socket_new { socket_t* return_value{0}; std::function body{[this](void) { return return_value; }}; - socket_t* operator()(void) { return body(); }; + socket_t* operator()(void) { return body(); } }; extern struct socket_new socket_new; @@ -95,9 +91,8 @@ extern struct socket_new socket_new; // Return: socket_t* struct socket_new_from_fd { socket_t* return_value{0}; - std::function body{ - [this](int /* fd */) { return return_value; }}; - socket_t* operator()(int fd) { return body(fd); }; + std::function body{[this](int /* fd */) { return return_value; }}; + socket_t* operator()(int fd) { return body(fd); } }; extern struct socket_new_from_fd socket_new_from_fd; @@ -107,11 +102,12 @@ extern struct socket_new_from_fd socket_new_from_fd; struct socket_read { ssize_t return_value{0}; std::function body{ - [this](const socket_t* /* socket */, void* /* buf */, - size_t /* count */) { return return_value; }}; + [this](const socket_t* /* socket */, void* /* buf */, size_t /* count */) { + return return_value; + }}; ssize_t operator()(const socket_t* socket, void* buf, size_t count) { return body(socket, buf, count); - }; + } }; extern struct socket_read socket_read; @@ -119,15 +115,14 @@ extern struct socket_read socket_read; // Params: socket_t* socket, reactor_t* reactor, void* context, socket_cb // read_cb, socket_cb write_cb Return: void struct socket_register { - std::function - body{[](socket_t* /* socket */, reactor_t* /* reactor */, - void* /* context */, socket_cb /* read_cb */, - socket_cb /* write_cb */) {}}; - void operator()(socket_t* socket, reactor_t* reactor, void* context, - socket_cb read_cb, socket_cb write_cb) { + std::function + body{[](socket_t* /* socket */, reactor_t* /* reactor */, void* /* context */, + socket_cb /* read_cb */, socket_cb /* write_cb */) {}}; + void operator()(socket_t* socket, reactor_t* reactor, void* context, socket_cb read_cb, + socket_cb write_cb) { body(socket, reactor, context, read_cb, write_cb); - }; + } }; extern struct socket_register socket_register; @@ -136,7 +131,7 @@ extern struct socket_register socket_register; // Return: void struct socket_unregister { std::function body{[](socket_t* /* socket */) {}}; - void operator()(socket_t* socket) { body(socket); }; + void operator()(socket_t* socket) { body(socket); } }; extern struct socket_unregister socket_unregister; @@ -145,12 +140,13 @@ extern struct socket_unregister socket_unregister; // Return: ssize_t struct socket_write { ssize_t return_value{0}; - std::function - body{[this](const socket_t* /* socket */, const void* /* buf */, - size_t /* count */) { return return_value; }}; + std::function body{ + [this](const socket_t* /* socket */, const void* /* buf */, size_t /* count */) { + return return_value; + }}; ssize_t operator()(const socket_t* socket, const void* buf, size_t count) { return body(socket, buf, count); - }; + } }; extern struct socket_write socket_write; @@ -159,14 +155,12 @@ extern struct socket_write socket_write; // Return: ssize_t struct socket_write_and_transfer_fd { ssize_t return_value{0}; - std::function - body{[this](const socket_t* /* socket */, const void* /* buf */, - size_t /* count */, int /* fd */) { return return_value; }}; - ssize_t operator()(const socket_t* socket, const void* buf, size_t count, - int fd) { + std::function body{ + [this](const socket_t* /* socket */, const void* /* buf */, size_t /* count */, + int /* fd */) { return return_value; }}; + ssize_t operator()(const socket_t* socket, const void* buf, size_t count, int fd) { return body(socket, buf, count, fd); - }; + } }; extern struct socket_write_and_transfer_fd socket_write_and_transfer_fd; diff --git a/system/test/mock/mock_osi_stack_power_telemetry.cc b/system/test/mock/mock_osi_stack_power_telemetry.cc index 850dd62c094..26f551d197e 100644 --- a/system/test/mock/mock_osi_stack_power_telemetry.cc +++ b/system/test/mock/mock_osi_stack_power_telemetry.cc @@ -52,80 +52,62 @@ struct power_telemetry::PowerTelemetryImpl {}; power_telemetry::PowerTelemetry::PowerTelemetry() {} -void power_telemetry::PowerTelemetry::RecordLogDataContainer() { +void power_telemetry::PowerTelemetry::RecordLogDataContainer() { inc_func_call_count(__func__); } +void power_telemetry::PowerTelemetry::LogScanStarted() { inc_func_call_count(__func__); } +void power_telemetry::PowerTelemetry::LogChannelConnected(uint16_t /* psm */, int32_t /* src_id */, + int32_t /* dst_id */, + const RawAddress& /* bd_addr */) { inc_func_call_count(__func__); } -void power_telemetry::PowerTelemetry::LogScanStarted() { +void power_telemetry::PowerTelemetry::LogChannelDisconnected(uint16_t /* psm */, + int32_t /* src_id */, + int32_t /* dst_id */, + const RawAddress& /* bd_addr */) { inc_func_call_count(__func__); } -void power_telemetry::PowerTelemetry::LogChannelConnected( - uint16_t /* psm */, int32_t /* src_id */, int32_t /* dst_id */, - const RawAddress& /* bd_addr */) { +void power_telemetry::PowerTelemetry::LogTxBytes(uint16_t /* psm */, int32_t /* src_id */, + int32_t /* dst_id */, + const RawAddress& /* bd_addr */, + int32_t /* num_bytes */) { inc_func_call_count(__func__); } -void power_telemetry::PowerTelemetry::LogChannelDisconnected( - uint16_t /* psm */, int32_t /* src_id */, int32_t /* dst_id */, - const RawAddress& /* bd_addr */) { - inc_func_call_count(__func__); -} -void power_telemetry::PowerTelemetry::LogTxBytes( - uint16_t /* psm */, int32_t /* src_id */, int32_t /* dst_id */, - const RawAddress& /* bd_addr */, int32_t /* num_bytes */) { - inc_func_call_count(__func__); -} -void power_telemetry::PowerTelemetry::LogRxBytes( - uint16_t /* psm */, int32_t /* src_id */, int32_t /* dst_id */, - const RawAddress& /* bd_addr */, int32_t /* num_bytes */) { - inc_func_call_count(__func__); -} -void power_telemetry::PowerTelemetry::Dumpsys(int32_t /* fd */) { +void power_telemetry::PowerTelemetry::LogRxBytes(uint16_t /* psm */, int32_t /* src_id */, + int32_t /* dst_id */, + const RawAddress& /* bd_addr */, + int32_t /* num_bytes */) { inc_func_call_count(__func__); } +void power_telemetry::PowerTelemetry::Dumpsys(int32_t /* fd */) { inc_func_call_count(__func__); } void power_telemetry::PowerTelemetry::LogRxAclPktData(uint16_t /* len */) { inc_func_call_count(__func__); } void power_telemetry::PowerTelemetry::LogTxAclPktData(uint16_t /* len */) { inc_func_call_count(__func__); } -void power_telemetry::PowerTelemetry::LogLinkDetails( - uint16_t /* handle */, const RawAddress& /* bdaddr */, - bool /* isConnected */, bool /* is_acl_link */) { - inc_func_call_count(__func__); -} -void power_telemetry::PowerTelemetry::LogAclTxPowerLevel( - uint16_t /* handle */, uint8_t /* txPower */) { - inc_func_call_count(__func__); -} -void power_telemetry::PowerTelemetry::LogInqScanStarted() { - inc_func_call_count(__func__); -} -void power_telemetry::PowerTelemetry::LogInqScanStopped() { - inc_func_call_count(__func__); -} -void power_telemetry::PowerTelemetry::LogBleAdvStarted() { - inc_func_call_count(__func__); -} -void power_telemetry::PowerTelemetry::LogBleAdvStopped() { - inc_func_call_count(__func__); -} -void power_telemetry::PowerTelemetry::LogHciCmdDetail() { - inc_func_call_count(__func__); -} -void power_telemetry::PowerTelemetry::LogHciEvtDetail() { - inc_func_call_count(__func__); -} -void power_telemetry::PowerTelemetry::LogTxPower(void* /* res */) { +void power_telemetry::PowerTelemetry::LogLinkDetails(uint16_t /* handle */, + const RawAddress& /* bdaddr */, + bool /* isConnected */, + bool /* is_acl_link */) { inc_func_call_count(__func__); } -void power_telemetry::PowerTelemetry::LogTrafficData() { +void power_telemetry::PowerTelemetry::LogAclTxPowerLevel(uint16_t /* handle */, + uint8_t /* txPower */) { inc_func_call_count(__func__); } -void power_telemetry::PowerTelemetry::LogSniffStarted( - uint16_t /* handle */, const RawAddress& /* bdaddr */) { +void power_telemetry::PowerTelemetry::LogInqScanStarted() { inc_func_call_count(__func__); } +void power_telemetry::PowerTelemetry::LogInqScanStopped() { inc_func_call_count(__func__); } +void power_telemetry::PowerTelemetry::LogBleAdvStarted() { inc_func_call_count(__func__); } +void power_telemetry::PowerTelemetry::LogBleAdvStopped() { inc_func_call_count(__func__); } +void power_telemetry::PowerTelemetry::LogHciCmdDetail() { inc_func_call_count(__func__); } +void power_telemetry::PowerTelemetry::LogHciEvtDetail() { inc_func_call_count(__func__); } +void power_telemetry::PowerTelemetry::LogTxPower(void* /* res */) { inc_func_call_count(__func__); } +void power_telemetry::PowerTelemetry::LogTrafficData() { inc_func_call_count(__func__); } +void power_telemetry::PowerTelemetry::LogSniffStarted(uint16_t /* handle */, + const RawAddress& /* bdaddr */) { inc_func_call_count(__func__); } -void power_telemetry::PowerTelemetry::LogSniffStopped( - uint16_t /* handle */, const RawAddress& /* bdaddr */) { +void power_telemetry::PowerTelemetry::LogSniffStopped(uint16_t /* handle */, + const RawAddress& /* bdaddr */) { inc_func_call_count(__func__); } void power_telemetry::PowerTelemetry::LogBleScan(uint16_t /* num_resps */) { diff --git a/system/test/mock/mock_osi_thread.h b/system/test/mock/mock_osi_thread.h index 967e12e21f2..992e140a638 100644 --- a/system/test/mock/mock_osi_thread.h +++ b/system/test/mock/mock_osi_thread.h @@ -40,7 +40,7 @@ namespace osi_thread { // Return: void struct thread_free { std::function body{[](thread_t* /* thread */) {}}; - void operator()(thread_t* thread) { body(thread); }; + void operator()(thread_t* thread) { body(thread); } }; extern struct thread_free thread_free; @@ -50,8 +50,8 @@ extern struct thread_free thread_free; struct thread_get_reactor { reactor_t* return_value{0}; std::function body{ - [this](const thread_t* /* thread */) { return return_value; }}; - reactor_t* operator()(const thread_t* thread) { return body(thread); }; + [this](const thread_t* /* thread */) { return return_value; }}; + reactor_t* operator()(const thread_t* thread) { return body(thread); } }; extern struct thread_get_reactor thread_get_reactor; @@ -61,8 +61,8 @@ extern struct thread_get_reactor thread_get_reactor; struct thread_is_self { bool return_value{false}; std::function body{ - [this](const thread_t* /* thread */) { return return_value; }}; - bool operator()(const thread_t* thread) { return body(thread); }; + [this](const thread_t* /* thread */) { return return_value; }}; + bool operator()(const thread_t* thread) { return body(thread); } }; extern struct thread_is_self thread_is_self; @@ -71,7 +71,7 @@ extern struct thread_is_self thread_is_self; // Return: void struct thread_join { std::function body{[](thread_t* /* thread */) {}}; - void operator()(thread_t* thread) { body(thread); }; + void operator()(thread_t* thread) { body(thread); } }; extern struct thread_join thread_join; @@ -81,8 +81,8 @@ extern struct thread_join thread_join; struct thread_name { const char* return_value{0}; std::function body{ - [this](const thread_t* /* thread */) { return return_value; }}; - const char* operator()(const thread_t* thread) { return body(thread); }; + [this](const thread_t* /* thread */) { return return_value; }}; + const char* operator()(const thread_t* thread) { return body(thread); } }; extern struct thread_name thread_name; @@ -92,8 +92,8 @@ extern struct thread_name thread_name; struct thread_new { thread_t* return_value{0}; std::function body{ - [this](const char* /* name */) { return return_value; }}; - thread_t* operator()(const char* name) { return body(name); }; + [this](const char* /* name */) { return return_value; }}; + thread_t* operator()(const char* name) { return body(name); } }; extern struct thread_new thread_new; @@ -103,12 +103,12 @@ extern struct thread_new thread_new; struct thread_new_sized { thread_t* return_value{0}; std::function body{ - [this](const char* /* name */, size_t /* work_queue_capacity */) { - return return_value; - }}; + [this](const char* /* name */, size_t /* work_queue_capacity */) { + return return_value; + }}; thread_t* operator()(const char* name, size_t work_queue_capacity) { return body(name, work_queue_capacity); - }; + } }; extern struct thread_new_sized thread_new_sized; @@ -118,11 +118,12 @@ extern struct thread_new_sized thread_new_sized; struct thread_post { bool return_value{false}; std::function body{ - [this](thread_t* /* thread */, thread_fn /* func */, - void* /* context */) { return return_value; }}; + [this](thread_t* /* thread */, thread_fn /* func */, void* /* context */) { + return return_value; + }}; bool operator()(thread_t* thread, thread_fn func, void* context) { return body(thread, func, context); - }; + } }; extern struct thread_post thread_post; @@ -132,12 +133,8 @@ extern struct thread_post thread_post; struct thread_set_priority { bool return_value{false}; std::function body{ - [this](thread_t* /* thread */, int /* priority */) { - return return_value; - }}; - bool operator()(thread_t* thread, int priority) { - return body(thread, priority); - }; + [this](thread_t* /* thread */, int /* priority */) { return return_value; }}; + bool operator()(thread_t* thread, int priority) { return body(thread, priority); } }; extern struct thread_set_priority thread_set_priority; @@ -147,12 +144,8 @@ extern struct thread_set_priority thread_set_priority; struct thread_set_rt_priority { bool return_value{false}; std::function body{ - [this](thread_t* /* thread */, int /* priority */) { - return return_value; - }}; - bool operator()(thread_t* thread, int priority) { - return body(thread, priority); - }; + [this](thread_t* /* thread */, int /* priority */) { return return_value; }}; + bool operator()(thread_t* thread, int priority) { return body(thread, priority); } }; extern struct thread_set_rt_priority thread_set_rt_priority; @@ -161,7 +154,7 @@ extern struct thread_set_rt_priority thread_set_rt_priority; // Return: void struct thread_stop { std::function body{[](thread_t* /* thread */) {}}; - void operator()(thread_t* thread) { body(thread); }; + void operator()(thread_t* thread) { body(thread); } }; extern struct thread_stop thread_stop; diff --git a/system/test/mock/mock_osi_thread_scheduler.cc b/system/test/mock/mock_osi_thread_scheduler.cc index 77f0821e5d5..ff978b2b4d4 100644 --- a/system/test/mock/mock_osi_thread_scheduler.cc +++ b/system/test/mock/mock_osi_thread_scheduler.cc @@ -42,13 +42,11 @@ struct thread_scheduler_get_priority_range thread_scheduler_get_priority_range; // Mocked functions, if any bool thread_scheduler_enable_real_time(pid_t linux_tid) { inc_func_call_count(__func__); - return test::mock::osi_thread_scheduler::thread_scheduler_enable_real_time( - linux_tid); + return test::mock::osi_thread_scheduler::thread_scheduler_enable_real_time(linux_tid); } bool thread_scheduler_get_priority_range(int& min, int& max) { inc_func_call_count(__func__); - return test::mock::osi_thread_scheduler::thread_scheduler_get_priority_range( - min, max); + return test::mock::osi_thread_scheduler::thread_scheduler_get_priority_range(min, max); } // Mocked functions complete // END mockcify generation diff --git a/system/test/mock/mock_osi_thread_scheduler.h b/system/test/mock/mock_osi_thread_scheduler.h index c90ee85e00e..f80f84b0695 100644 --- a/system/test/mock/mock_osi_thread_scheduler.h +++ b/system/test/mock/mock_osi_thread_scheduler.h @@ -39,12 +39,10 @@ namespace osi_thread_scheduler { // Return: bool struct thread_scheduler_enable_real_time { bool return_value{false}; - std::function body{ - [this](pid_t /* linux_tid */) { return return_value; }}; - bool operator()(pid_t linux_tid) { return body(linux_tid); }; + std::function body{[this](pid_t /* linux_tid */) { return return_value; }}; + bool operator()(pid_t linux_tid) { return body(linux_tid); } }; -extern struct thread_scheduler_enable_real_time - thread_scheduler_enable_real_time; +extern struct thread_scheduler_enable_real_time thread_scheduler_enable_real_time; // Name: osi_fifo_scheduing_priority_range // Params: int& min, int& max @@ -52,11 +50,10 @@ extern struct thread_scheduler_enable_real_time struct thread_scheduler_get_priority_range { bool return_value{false}; std::function body{ - [this](int& /* min */, int& /* max */) { return return_value; }}; - bool operator()(int& min, int& max) { return body(min, max); }; + [this](int& /* min */, int& /* max */) { return return_value; }}; + bool operator()(int& min, int& max) { return body(min, max); } }; -extern struct thread_scheduler_get_priority_range - thread_scheduler_get_priority_range; +extern struct thread_scheduler_get_priority_range thread_scheduler_get_priority_range; } // namespace osi_thread_scheduler } // namespace mock diff --git a/system/test/mock/mock_osi_wakelock.h b/system/test/mock/mock_osi_wakelock.h index 2a6b664b661..cfc4b2cffe1 100644 --- a/system/test/mock/mock_osi_wakelock.h +++ b/system/test/mock/mock_osi_wakelock.h @@ -41,7 +41,7 @@ namespace osi_wakelock { struct wakelock_acquire { bool return_value{false}; std::function body{[this](void) { return return_value; }}; - bool operator()(void) { return body(); }; + bool operator()(void) { return body(); } }; extern struct wakelock_acquire wakelock_acquire; @@ -50,7 +50,7 @@ extern struct wakelock_acquire wakelock_acquire; // Return: void struct wakelock_cleanup { std::function body{[](void) {}}; - void operator()(void) { body(); }; + void operator()(void) { body(); } }; extern struct wakelock_cleanup wakelock_cleanup; @@ -59,7 +59,7 @@ extern struct wakelock_cleanup wakelock_cleanup; // Return: void struct wakelock_debug_dump { std::function body{[](int /* fd */) {}}; - void operator()(int fd) { body(fd); }; + void operator()(int fd) { body(fd); } }; extern struct wakelock_debug_dump wakelock_debug_dump; @@ -69,7 +69,7 @@ extern struct wakelock_debug_dump wakelock_debug_dump; struct wakelock_release { bool return_value{false}; std::function body{[this](void) { return return_value; }}; - bool operator()(void) { return body(); }; + bool operator()(void) { return body(); } }; extern struct wakelock_release wakelock_release; @@ -77,9 +77,8 @@ extern struct wakelock_release wakelock_release; // Params: bt_os_callouts_t* callouts // Return: void struct wakelock_set_os_callouts { - std::function body{ - [](bt_os_callouts_t* /* callouts */) {}}; - void operator()(bt_os_callouts_t* callouts) { body(callouts); }; + std::function body{[](bt_os_callouts_t* /* callouts */) {}}; + void operator()(bt_os_callouts_t* callouts) { body(callouts); } }; extern struct wakelock_set_os_callouts wakelock_set_os_callouts; @@ -88,10 +87,8 @@ extern struct wakelock_set_os_callouts wakelock_set_os_callouts; // Return: void struct wakelock_set_paths { std::function body{ - [](const char* /* lock_path */, const char* /* unlock_path */) {}}; - void operator()(const char* lock_path, const char* unlock_path) { - body(lock_path, unlock_path); - }; + [](const char* /* lock_path */, const char* /* unlock_path */) {}}; + void operator()(const char* lock_path, const char* unlock_path) { body(lock_path, unlock_path); } }; extern struct wakelock_set_paths wakelock_set_paths; diff --git a/system/test/mock/mock_stack_a2dp_api.cc b/system/test/mock/mock_stack_a2dp_api.cc index df0171b2e09..46aed89dd3f 100644 --- a/system/test/mock/mock_stack_a2dp_api.cc +++ b/system/test/mock/mock_stack_a2dp_api.cc @@ -24,18 +24,14 @@ #include "test/common/mock_functions.h" #include "types/raw_address.h" -tA2DP_STATUS A2DP_AddRecord(uint16_t /* service_uuid */, - char* /* p_service_name */, - char* /* p_provider_name */, - uint16_t /* features */, +tA2DP_STATUS A2DP_AddRecord(uint16_t /* service_uuid */, char* /* p_service_name */, + char* /* p_provider_name */, uint16_t /* features */, uint32_t /* sdp_handle */) { inc_func_call_count(__func__); return A2DP_SUCCESS; } -tA2DP_STATUS A2DP_FindService(uint16_t /* service_uuid */, - const RawAddress& /* bd_addr */, - tA2DP_SDP_DB_PARAMS* /* p_db */, - tA2DP_FIND_CBACK /* p_cback */) { +tA2DP_STATUS A2DP_FindService(uint16_t /* service_uuid */, const RawAddress& /* bd_addr */, + tA2DP_SDP_DB_PARAMS* /* p_db */, tA2DP_FIND_CBACK /* p_cback */) { inc_func_call_count(__func__); return A2DP_SUCCESS; } @@ -48,6 +44,4 @@ uint8_t A2DP_BitsSet(uint64_t /* num */) { return 1; } void A2DP_Init(void) { inc_func_call_count(__func__); } -void a2dp_set_avdt_sdp_ver(uint16_t /* avdt_sdp_ver */) { - inc_func_call_count(__func__); -} +void a2dp_set_avdt_sdp_ver(uint16_t /* avdt_sdp_ver */) { inc_func_call_count(__func__); } diff --git a/system/test/mock/mock_stack_a2dp_codec_config.cc b/system/test/mock/mock_stack_a2dp_codec_config.cc index 08d56e0efc2..f94cb350beb 100644 --- a/system/test/mock/mock_stack_a2dp_codec_config.cc +++ b/system/test/mock/mock_stack_a2dp_codec_config.cc @@ -26,30 +26,25 @@ #include "stack/include/bt_hdr.h" #include "test/common/mock_functions.h" -A2dpCodecConfig* A2dpCodecConfig::createCodec( - btav_a2dp_codec_index_t /* codec_index */, - btav_a2dp_codec_priority_t /* codec_priority */) { +A2dpCodecConfig* A2dpCodecConfig::createCodec(btav_a2dp_codec_index_t /* codec_index */, + btav_a2dp_codec_priority_t /* codec_priority */) { inc_func_call_count(__func__); return nullptr; } -A2dpCodecConfig* A2dpCodecs::findSinkCodecConfig( - const uint8_t* /* p_codec_info */) { +A2dpCodecConfig* A2dpCodecs::findSinkCodecConfig(const uint8_t* /* p_codec_info */) { inc_func_call_count(__func__); return nullptr; } -A2dpCodecConfig* A2dpCodecs::findSourceCodecConfig( - const uint8_t* /* p_codec_info */) { +A2dpCodecConfig* A2dpCodecs::findSourceCodecConfig(const uint8_t* /* p_codec_info */) { inc_func_call_count(__func__); return nullptr; } -A2dpCodecConfig* A2dpCodecs::findSourceCodecConfig( - btav_a2dp_codec_index_t /* codec_index */) { +A2dpCodecConfig* A2dpCodecs::findSourceCodecConfig(btav_a2dp_codec_index_t /* codec_index */) { inc_func_call_count(__func__); return nullptr; } -A2dpCodecConfig::A2dpCodecConfig(btav_a2dp_codec_index_t codec_index, - uint64_t codec_id, const std::string& name, - btav_a2dp_codec_priority_t codec_priority) +A2dpCodecConfig::A2dpCodecConfig(btav_a2dp_codec_index_t codec_index, uint64_t codec_id, + const std::string& name, btav_a2dp_codec_priority_t codec_priority) : codec_index_(codec_index), codec_id_(codec_id), name_(name), @@ -57,8 +52,7 @@ A2dpCodecConfig::A2dpCodecConfig(btav_a2dp_codec_index_t codec_index, inc_func_call_count(__func__); } A2dpCodecConfig::~A2dpCodecConfig() { inc_func_call_count(__func__); } -A2dpCodecs::A2dpCodecs( - const std::vector& /* codec_priorities */) +A2dpCodecs::A2dpCodecs(const std::vector& /* codec_priorities */) : current_codec_config_(nullptr) { inc_func_call_count(__func__); } @@ -67,14 +61,12 @@ bool A2DP_AdjustCodec(uint8_t* /* p_codec_info */) { inc_func_call_count(__func__); return false; } -bool A2DP_BuildCodecHeader(const uint8_t* /* p_codec_info */, - BT_HDR* /* p_buf */, +bool A2DP_BuildCodecHeader(const uint8_t* /* p_codec_info */, BT_HDR* /* p_buf */, uint16_t /* frames_per_packet */) { inc_func_call_count(__func__); return false; } -bool A2DP_CodecEquals(const uint8_t* /* p_codec_info_a */, - const uint8_t* /* p_codec_info_b */) { +bool A2DP_CodecEquals(const uint8_t* /* p_codec_info_a */, const uint8_t* /* p_codec_info_b */) { inc_func_call_count(__func__); return false; } @@ -83,14 +75,12 @@ bool A2DP_CodecTypeEquals(const uint8_t* /* p_codec_info_a */, inc_func_call_count(__func__); return false; } -bool A2DP_GetPacketTimestamp(const uint8_t* /* p_codec_info */, - const uint8_t* /* p_data */, +bool A2DP_GetPacketTimestamp(const uint8_t* /* p_codec_info */, const uint8_t* /* p_data */, uint32_t* /* p_timestamp */) { inc_func_call_count(__func__); return false; } -bool A2DP_InitCodecConfig(btav_a2dp_codec_index_t /* codec_index */, - AvdtpSepConfig* /* p_cfg */) { +bool A2DP_InitCodecConfig(btav_a2dp_codec_index_t /* codec_index */, AvdtpSepConfig* /* p_cfg */) { inc_func_call_count(__func__); return false; } @@ -122,13 +112,11 @@ bool A2DP_IsSourceCodecValid(const uint8_t* /* p_codec_info */) { inc_func_call_count(__func__); return false; } -bool A2DP_UsesRtpHeader(bool /* content_protection_enabled */, - const uint8_t* /* p_codec_info */) { +bool A2DP_UsesRtpHeader(bool /* content_protection_enabled */, const uint8_t* /* p_codec_info */) { inc_func_call_count(__func__); return false; } -bool A2dpCodecConfig::codecConfigIsValid( - const btav_a2dp_codec_config_t& /* codec_config */) { +bool A2dpCodecConfig::codecConfigIsValid(const btav_a2dp_codec_config_t& /* codec_config */) { inc_func_call_count(__func__); return false; } @@ -136,13 +124,11 @@ bool A2dpCodecConfig::copyOutOtaCodecConfig(uint8_t* /* p_codec_info */) { inc_func_call_count(__func__); return false; } -bool A2dpCodecConfig::getCodecSpecificConfig( - tBT_A2DP_OFFLOAD* /* p_a2dp_offload */) { +bool A2dpCodecConfig::getCodecSpecificConfig(tBT_A2DP_OFFLOAD* /* p_a2dp_offload */) { inc_func_call_count(__func__); return false; } -bool A2dpCodecConfig::isCodecConfigEmpty( - const btav_a2dp_codec_config_t& /* codec_config */) { +bool A2dpCodecConfig::isCodecConfigEmpty(const btav_a2dp_codec_config_t& /* codec_config */) { inc_func_call_count(__func__); return false; } @@ -150,21 +136,21 @@ bool A2dpCodecConfig::isValid() const { inc_func_call_count(__func__); return false; } -bool A2dpCodecConfig::setCodecUserConfig( - const btav_a2dp_codec_config_t& /* codec_user_config */, - const btav_a2dp_codec_config_t& /* codec_audio_config */, - const tA2DP_ENCODER_INIT_PEER_PARAMS* /* p_peer_params */, - const uint8_t* /* p_peer_codec_info */, bool /* is_capability */, - uint8_t* /* p_result_codec_config */, bool* /* p_restart_input */, - bool* /* p_restart_output */, bool* /* p_config_updated */) { +bool A2dpCodecConfig::setCodecUserConfig(const btav_a2dp_codec_config_t& /* codec_user_config */, + const btav_a2dp_codec_config_t& /* codec_audio_config */, + const tA2DP_ENCODER_INIT_PEER_PARAMS* /* p_peer_params */, + const uint8_t* /* p_peer_codec_info */, + bool /* is_capability */, + uint8_t* /* p_result_codec_config */, + bool* /* p_restart_input */, bool* /* p_restart_output */, + bool* /* p_config_updated */) { inc_func_call_count(__func__); return false; } bool A2dpCodecs::getCodecConfigAndCapabilities( - btav_a2dp_codec_config_t* /* p_codec_config */, - std::vector* /* p_codecs_local_capabilities */, - std::vector< - btav_a2dp_codec_config_t>* /* p_codecs_selectable_capabilities */) { + btav_a2dp_codec_config_t* /* p_codec_config */, + std::vector* /* p_codecs_local_capabilities */, + std::vector* /* p_codecs_selectable_capabilities */) { inc_func_call_count(__func__); return false; } @@ -176,52 +162,47 @@ bool A2dpCodecs::isSupportedCodec(btav_a2dp_codec_index_t /* codec_index */) { inc_func_call_count(__func__); return false; } -bool A2dpCodecs::setCodecAudioConfig( - const btav_a2dp_codec_config_t& /* codec_audio_config */, - const tA2DP_ENCODER_INIT_PEER_PARAMS* /* p_peer_params */, - const uint8_t* /* p_peer_sink_capabilities */, - uint8_t* /* p_result_codec_config */, bool* /* p_restart_output */, - bool* /* p_config_updated */) { +bool A2dpCodecs::setCodecAudioConfig(const btav_a2dp_codec_config_t& /* codec_audio_config */, + const tA2DP_ENCODER_INIT_PEER_PARAMS* /* p_peer_params */, + const uint8_t* /* p_peer_sink_capabilities */, + uint8_t* /* p_result_codec_config */, + bool* /* p_restart_output */, bool* /* p_config_updated */) { inc_func_call_count(__func__); return false; } -bool A2dpCodecs::setCodecConfig(const uint8_t* /* p_peer_codec_info */, - bool /* is_capability */, +bool A2dpCodecs::setCodecConfig(const uint8_t* /* p_peer_codec_info */, bool /* is_capability */, uint8_t* /* p_result_codec_config */, bool /* select_current_codec */) { inc_func_call_count(__func__); return false; } -bool A2dpCodecs::setCodecOtaConfig( - const uint8_t* /* p_ota_codec_config */, - const tA2DP_ENCODER_INIT_PEER_PARAMS* /* p_peer_params */, - uint8_t* /* p_result_codec_config */, bool* /* p_restart_input */, - bool* /* p_restart_output */, bool* /* p_config_updated */) { +bool A2dpCodecs::setCodecOtaConfig(const uint8_t* /* p_ota_codec_config */, + const tA2DP_ENCODER_INIT_PEER_PARAMS* /* p_peer_params */, + uint8_t* /* p_result_codec_config */, + bool* /* p_restart_input */, bool* /* p_restart_output */, + bool* /* p_config_updated */) { inc_func_call_count(__func__); return false; } -bool A2dpCodecs::setCodecUserConfig( - const btav_a2dp_codec_config_t& /* codec_user_config */, - const tA2DP_ENCODER_INIT_PEER_PARAMS* /* p_peer_params */, - const uint8_t* /* p_peer_sink_capabilities */, - uint8_t* /* p_result_codec_config */, bool* /* p_restart_input */, - bool* /* p_restart_output */, bool* /* p_config_updated */) { +bool A2dpCodecs::setCodecUserConfig(const btav_a2dp_codec_config_t& /* codec_user_config */, + const tA2DP_ENCODER_INIT_PEER_PARAMS* /* p_peer_params */, + const uint8_t* /* p_peer_sink_capabilities */, + uint8_t* /* p_result_codec_config */, + bool* /* p_restart_input */, bool* /* p_restart_output */, + bool* /* p_config_updated */) { inc_func_call_count(__func__); return false; } -bool A2dpCodecs::setPeerSinkCodecCapabilities( - const uint8_t* /* p_peer_codec_capabilities */) { +bool A2dpCodecs::setPeerSinkCodecCapabilities(const uint8_t* /* p_peer_codec_capabilities */) { inc_func_call_count(__func__); return false; } -bool A2dpCodecs::setPeerSourceCodecCapabilities( - const uint8_t* /* p_peer_codec_capabilities */) { +bool A2dpCodecs::setPeerSourceCodecCapabilities(const uint8_t* /* p_peer_codec_capabilities */) { inc_func_call_count(__func__); return false; } bool A2dpCodecs::setSinkCodecConfig(const uint8_t* /* p_peer_codec_info */, - bool /* is_capability */, - uint8_t* /* p_result_codec_config */, + bool /* is_capability */, uint8_t* /* p_result_codec_config */, bool /* select_current_codec */) { inc_func_call_count(__func__); return false; @@ -260,8 +241,7 @@ btav_a2dp_codec_index_t A2DP_SinkCodecIndex(const uint8_t* /* p_codec_info */) { inc_func_call_count(__func__); return BTAV_A2DP_CODEC_INDEX_MAX; } -btav_a2dp_codec_index_t A2DP_SourceCodecIndex( - const uint8_t* /* p_codec_info */) { +btav_a2dp_codec_index_t A2DP_SourceCodecIndex(const uint8_t* /* p_codec_info */) { inc_func_call_count(__func__); return BTAV_A2DP_CODEC_INDEX_MAX; } @@ -273,13 +253,11 @@ const char* A2DP_CodecName(const uint8_t* /* p_codec_info */) { inc_func_call_count(__func__); return nullptr; } -const tA2DP_DECODER_INTERFACE* A2DP_GetDecoderInterface( - const uint8_t* /* p_codec_info */) { +const tA2DP_DECODER_INTERFACE* A2DP_GetDecoderInterface(const uint8_t* /* p_codec_info */) { inc_func_call_count(__func__); return nullptr; } -const tA2DP_ENCODER_INTERFACE* A2DP_GetEncoderInterface( - const uint8_t* /* p_codec_info */) { +const tA2DP_ENCODER_INTERFACE* A2DP_GetEncoderInterface(const uint8_t* /* p_codec_info */) { inc_func_call_count(__func__); return nullptr; } @@ -308,22 +286,21 @@ std::string A2DP_CodecInfoString(const uint8_t* /* p_codec_info */) { return 0; } std::string A2dpCodecConfig::codecBitsPerSample2Str( - btav_a2dp_codec_bits_per_sample_t /* codec_bits_per_sample */) { + btav_a2dp_codec_bits_per_sample_t /* codec_bits_per_sample */) { inc_func_call_count(__func__); return 0; } std::string A2dpCodecConfig::codecChannelMode2Str( - btav_a2dp_codec_channel_mode_t /* codec_channel_mode */) { + btav_a2dp_codec_channel_mode_t /* codec_channel_mode */) { inc_func_call_count(__func__); return 0; } -std::string A2dpCodecConfig::codecConfig2Str( - const btav_a2dp_codec_config_t& /* codec_config */) { +std::string A2dpCodecConfig::codecConfig2Str(const btav_a2dp_codec_config_t& /* codec_config */) { inc_func_call_count(__func__); return 0; } std::string A2dpCodecConfig::codecSampleRate2Str( - btav_a2dp_codec_sample_rate_t /* codec_sample_rate */) { + btav_a2dp_codec_sample_rate_t /* codec_sample_rate */) { inc_func_call_count(__func__); return 0; } @@ -339,23 +316,14 @@ uint8_t A2dpCodecConfig::getAudioBitsPerSample() { inc_func_call_count(__func__); return 0; } -void A2DP_InitDefaultCodec(uint8_t* /* p_codec_info */) { - inc_func_call_count(__func__); -} -void A2dpCodecConfig::debug_codec_dump(int /* fd */) { - inc_func_call_count(__func__); -} +void A2DP_InitDefaultCodec(uint8_t* /* p_codec_info */) { inc_func_call_count(__func__); } +void A2dpCodecConfig::debug_codec_dump(int /* fd */) { inc_func_call_count(__func__); } int A2DP_IotGetPeerSinkCodecType(const uint8_t* /* p_codec_info */) { inc_func_call_count(__func__); return 0; } -void A2dpCodecConfig::setCodecPriority( - btav_a2dp_codec_priority_t /* codec_priority */) { - inc_func_call_count(__func__); -} -void A2dpCodecConfig::setDefaultCodecPriority() { - inc_func_call_count(__func__); -} -void A2dpCodecs::debug_codec_dump(int /* fd */) { +void A2dpCodecConfig::setCodecPriority(btav_a2dp_codec_priority_t /* codec_priority */) { inc_func_call_count(__func__); } +void A2dpCodecConfig::setDefaultCodecPriority() { inc_func_call_count(__func__); } +void A2dpCodecs::debug_codec_dump(int /* fd */) { inc_func_call_count(__func__); } diff --git a/system/test/mock/mock_stack_a2dp_sbc.cc b/system/test/mock/mock_stack_a2dp_sbc.cc index 680e2951ba3..d67e2b61a90 100644 --- a/system/test/mock/mock_stack_a2dp_sbc.cc +++ b/system/test/mock/mock_stack_a2dp_sbc.cc @@ -91,10 +91,8 @@ bool A2DP_CodecTypeEqualsSbc::return_value = false; int A2DP_GetAllocationMethodCodeSbc::return_value = 0; uint32_t A2DP_GetBitrateSbc::return_value = 0; int A2DP_GetChannelModeCodeSbc::return_value = 0; -const tA2DP_DECODER_INTERFACE* A2DP_GetDecoderInterfaceSbc::return_value = - nullptr; -const tA2DP_ENCODER_INTERFACE* A2DP_GetEncoderInterfaceSbc::return_value = - nullptr; +const tA2DP_DECODER_INTERFACE* A2DP_GetDecoderInterfaceSbc::return_value = nullptr; +const tA2DP_ENCODER_INTERFACE* A2DP_GetEncoderInterfaceSbc::return_value = nullptr; int A2DP_GetMaxBitpoolSbc::return_value = 0; int A2DP_GetMinBitpoolSbc::return_value = 0; int A2DP_GetNumberOfBlocksSbc::return_value = 0; @@ -113,10 +111,8 @@ bool A2DP_IsPeerSourceCodecValidSbc::return_value = false; bool A2DP_IsSinkCodecSupportedSbc::return_value = false; bool A2DP_IsSinkCodecValidSbc::return_value = false; bool A2DP_IsSourceCodecValidSbc::return_value = false; -btav_a2dp_codec_index_t A2DP_SinkCodecIndexSbc::return_value = - BTAV_A2DP_CODEC_INDEX_SOURCE_MIN; -btav_a2dp_codec_index_t A2DP_SourceCodecIndexSbc::return_value = - BTAV_A2DP_CODEC_INDEX_SOURCE_MIN; +btav_a2dp_codec_index_t A2DP_SinkCodecIndexSbc::return_value = BTAV_A2DP_CODEC_INDEX_SOURCE_MIN; +btav_a2dp_codec_index_t A2DP_SourceCodecIndexSbc::return_value = BTAV_A2DP_CODEC_INDEX_SOURCE_MIN; } // namespace stack_a2dp_sbc } // namespace mock @@ -130,14 +126,12 @@ bool A2DP_AdjustCodecSbc(uint8_t* p_codec_info) { bool A2DP_BuildCodecHeaderSbc(const uint8_t* p_codec_info, BT_HDR* p_buf, uint16_t frames_per_packet) { inc_func_call_count(__func__); - return test::mock::stack_a2dp_sbc::A2DP_BuildCodecHeaderSbc( - p_codec_info, p_buf, frames_per_packet); + return test::mock::stack_a2dp_sbc::A2DP_BuildCodecHeaderSbc(p_codec_info, p_buf, + frames_per_packet); } -bool A2DP_CodecEqualsSbc(const uint8_t* p_codec_info_a, - const uint8_t* p_codec_info_b) { +bool A2DP_CodecEqualsSbc(const uint8_t* p_codec_info_a, const uint8_t* p_codec_info_b) { inc_func_call_count(__func__); - return test::mock::stack_a2dp_sbc::A2DP_CodecEqualsSbc(p_codec_info_a, - p_codec_info_b); + return test::mock::stack_a2dp_sbc::A2DP_CodecEqualsSbc(p_codec_info_a, p_codec_info_b); } const char* A2DP_CodecIndexStrSbc(void) { inc_func_call_count(__func__); @@ -155,16 +149,13 @@ const char* A2DP_CodecNameSbc(const uint8_t* p_codec_info) { inc_func_call_count(__func__); return test::mock::stack_a2dp_sbc::A2DP_CodecNameSbc(p_codec_info); } -bool A2DP_CodecTypeEqualsSbc(const uint8_t* p_codec_info_a, - const uint8_t* p_codec_info_b) { +bool A2DP_CodecTypeEqualsSbc(const uint8_t* p_codec_info_a, const uint8_t* p_codec_info_b) { inc_func_call_count(__func__); - return test::mock::stack_a2dp_sbc::A2DP_CodecTypeEqualsSbc(p_codec_info_a, - p_codec_info_b); + return test::mock::stack_a2dp_sbc::A2DP_CodecTypeEqualsSbc(p_codec_info_a, p_codec_info_b); } int A2DP_GetAllocationMethodCodeSbc(const uint8_t* p_codec_info) { inc_func_call_count(__func__); - return test::mock::stack_a2dp_sbc::A2DP_GetAllocationMethodCodeSbc( - p_codec_info); + return test::mock::stack_a2dp_sbc::A2DP_GetAllocationMethodCodeSbc(p_codec_info); } uint32_t A2DP_GetBitrateSbc() { inc_func_call_count(__func__); @@ -174,13 +165,11 @@ int A2DP_GetChannelModeCodeSbc(const uint8_t* p_codec_info) { inc_func_call_count(__func__); return test::mock::stack_a2dp_sbc::A2DP_GetChannelModeCodeSbc(p_codec_info); } -const tA2DP_DECODER_INTERFACE* A2DP_GetDecoderInterfaceSbc( - const uint8_t* p_codec_info) { +const tA2DP_DECODER_INTERFACE* A2DP_GetDecoderInterfaceSbc(const uint8_t* p_codec_info) { inc_func_call_count(__func__); return test::mock::stack_a2dp_sbc::A2DP_GetDecoderInterfaceSbc(p_codec_info); } -const tA2DP_ENCODER_INTERFACE* A2DP_GetEncoderInterfaceSbc( - const uint8_t* p_codec_info) { +const tA2DP_ENCODER_INTERFACE* A2DP_GetEncoderInterfaceSbc(const uint8_t* p_codec_info) { inc_func_call_count(__func__); return test::mock::stack_a2dp_sbc::A2DP_GetEncoderInterfaceSbc(p_codec_info); } @@ -200,26 +189,22 @@ int A2DP_GetNumberOfSubbandsSbc(const uint8_t* p_codec_info) { inc_func_call_count(__func__); return test::mock::stack_a2dp_sbc::A2DP_GetNumberOfSubbandsSbc(p_codec_info); } -bool A2DP_GetPacketTimestampSbc(const uint8_t* p_codec_info, - const uint8_t* p_data, uint32_t* p_timestamp) { +bool A2DP_GetPacketTimestampSbc(const uint8_t* p_codec_info, const uint8_t* p_data, + uint32_t* p_timestamp) { inc_func_call_count(__func__); - return test::mock::stack_a2dp_sbc::A2DP_GetPacketTimestampSbc( - p_codec_info, p_data, p_timestamp); + return test::mock::stack_a2dp_sbc::A2DP_GetPacketTimestampSbc(p_codec_info, p_data, p_timestamp); } int A2DP_GetSamplingFrequencyCodeSbc(const uint8_t* p_codec_info) { inc_func_call_count(__func__); - return test::mock::stack_a2dp_sbc::A2DP_GetSamplingFrequencyCodeSbc( - p_codec_info); + return test::mock::stack_a2dp_sbc::A2DP_GetSamplingFrequencyCodeSbc(p_codec_info); } int A2DP_GetSinkTrackChannelTypeSbc(const uint8_t* p_codec_info) { inc_func_call_count(__func__); - return test::mock::stack_a2dp_sbc::A2DP_GetSinkTrackChannelTypeSbc( - p_codec_info); + return test::mock::stack_a2dp_sbc::A2DP_GetSinkTrackChannelTypeSbc(p_codec_info); } int A2DP_GetTrackBitsPerSampleSbc(const uint8_t* p_codec_info) { inc_func_call_count(__func__); - return test::mock::stack_a2dp_sbc::A2DP_GetTrackBitsPerSampleSbc( - p_codec_info); + return test::mock::stack_a2dp_sbc::A2DP_GetTrackBitsPerSampleSbc(p_codec_info); } int A2DP_GetTrackChannelCountSbc(const uint8_t* p_codec_info) { inc_func_call_count(__func__); @@ -247,13 +232,11 @@ bool A2DP_IsPeerSinkCodecValidSbc(const uint8_t* p_codec_info) { } bool A2DP_IsPeerSourceCodecSupportedSbc(const uint8_t* p_codec_info) { inc_func_call_count(__func__); - return test::mock::stack_a2dp_sbc::A2DP_IsPeerSourceCodecSupportedSbc( - p_codec_info); + return test::mock::stack_a2dp_sbc::A2DP_IsPeerSourceCodecSupportedSbc(p_codec_info); } bool A2DP_IsPeerSourceCodecValidSbc(const uint8_t* p_codec_info) { inc_func_call_count(__func__); - return test::mock::stack_a2dp_sbc::A2DP_IsPeerSourceCodecValidSbc( - p_codec_info); + return test::mock::stack_a2dp_sbc::A2DP_IsPeerSourceCodecValidSbc(p_codec_info); } bool A2DP_IsSinkCodecSupportedSbc(const uint8_t* p_codec_info) { inc_func_call_count(__func__); diff --git a/system/test/mock/mock_stack_a2dp_sbc.h b/system/test/mock/mock_stack_a2dp_sbc.h index cee7fc2a8b5..c8513e3ac5c 100644 --- a/system/test/mock/mock_stack_a2dp_sbc.h +++ b/system/test/mock/mock_stack_a2dp_sbc.h @@ -45,8 +45,8 @@ namespace stack_a2dp_sbc { struct A2DP_AdjustCodecSbc { static bool return_value; std::function body{ - [](uint8_t* /* p_codec_info */) { return return_value; }}; - bool operator()(uint8_t* p_codec_info) { return body(p_codec_info); }; + [](uint8_t* /* p_codec_info */) { return return_value; }}; + bool operator()(uint8_t* p_codec_info) { return body(p_codec_info); } }; extern struct A2DP_AdjustCodecSbc A2DP_AdjustCodecSbc; @@ -55,14 +55,12 @@ extern struct A2DP_AdjustCodecSbc A2DP_AdjustCodecSbc; // frames_per_packet Return: bool struct A2DP_BuildCodecHeaderSbc { static bool return_value; - std::function - body{[](const uint8_t* /* p_codec_info */, BT_HDR* /* p_buf */, - uint16_t /* frames_per_packet */) { return return_value; }}; - bool operator()(const uint8_t* p_codec_info, BT_HDR* p_buf, - uint16_t frames_per_packet) { + std::function body{ + [](const uint8_t* /* p_codec_info */, BT_HDR* /* p_buf */, + uint16_t /* frames_per_packet */) { return return_value; }}; + bool operator()(const uint8_t* p_codec_info, BT_HDR* p_buf, uint16_t frames_per_packet) { return body(p_codec_info, p_buf, frames_per_packet); - }; + } }; extern struct A2DP_BuildCodecHeaderSbc A2DP_BuildCodecHeaderSbc; @@ -71,14 +69,13 @@ extern struct A2DP_BuildCodecHeaderSbc A2DP_BuildCodecHeaderSbc; // Return: bool struct A2DP_CodecEqualsSbc { static bool return_value; - std::function - body{[](const uint8_t* /* p_codec_info_a */, - const uint8_t* /* p_codec_info_b */) { return return_value; }}; - bool operator()(const uint8_t* p_codec_info_a, - const uint8_t* p_codec_info_b) { + std::function body{ + [](const uint8_t* /* p_codec_info_a */, const uint8_t* /* p_codec_info_b */) { + return return_value; + }}; + bool operator()(const uint8_t* p_codec_info_a, const uint8_t* p_codec_info_b) { return body(p_codec_info_a, p_codec_info_b); - }; + } }; extern struct A2DP_CodecEqualsSbc A2DP_CodecEqualsSbc; @@ -88,7 +85,7 @@ extern struct A2DP_CodecEqualsSbc A2DP_CodecEqualsSbc; struct A2DP_CodecIndexStrSbc { static const char* return_value; std::function body{[](void) { return return_value; }}; - const char* operator()(void) { return body(); }; + const char* operator()(void) { return body(); } }; extern struct A2DP_CodecIndexStrSbc A2DP_CodecIndexStrSbc; @@ -98,7 +95,7 @@ extern struct A2DP_CodecIndexStrSbc A2DP_CodecIndexStrSbc; struct A2DP_CodecIndexStrSbcSink { static const char* return_value; std::function body{[](void) { return return_value; }}; - const char* operator()(void) { return body(); }; + const char* operator()(void) { return body(); } }; extern struct A2DP_CodecIndexStrSbcSink A2DP_CodecIndexStrSbcSink; @@ -108,10 +105,8 @@ extern struct A2DP_CodecIndexStrSbcSink A2DP_CodecIndexStrSbcSink; struct A2DP_CodecInfoStringSbc { static std::string return_value; std::function body{ - [](const uint8_t* /* p_codec_info */) { return return_value; }}; - std::string operator()(const uint8_t* p_codec_info) { - return body(p_codec_info); - }; + [](const uint8_t* /* p_codec_info */) { return return_value; }}; + std::string operator()(const uint8_t* p_codec_info) { return body(p_codec_info); } }; extern struct A2DP_CodecInfoStringSbc A2DP_CodecInfoStringSbc; @@ -121,10 +116,8 @@ extern struct A2DP_CodecInfoStringSbc A2DP_CodecInfoStringSbc; struct A2DP_CodecNameSbc { static const char* return_value; std::function body{ - [](const uint8_t* /* p_codec_info */) { return return_value; }}; - const char* operator()(const uint8_t* p_codec_info) { - return body(p_codec_info); - }; + [](const uint8_t* /* p_codec_info */) { return return_value; }}; + const char* operator()(const uint8_t* p_codec_info) { return body(p_codec_info); } }; extern struct A2DP_CodecNameSbc A2DP_CodecNameSbc; @@ -133,14 +126,13 @@ extern struct A2DP_CodecNameSbc A2DP_CodecNameSbc; // Return: bool struct A2DP_CodecTypeEqualsSbc { static bool return_value; - std::function - body{[](const uint8_t* /* p_codec_info_a */, - const uint8_t* /* p_codec_info_b */) { return return_value; }}; - bool operator()(const uint8_t* p_codec_info_a, - const uint8_t* p_codec_info_b) { + std::function body{ + [](const uint8_t* /* p_codec_info_a */, const uint8_t* /* p_codec_info_b */) { + return return_value; + }}; + bool operator()(const uint8_t* p_codec_info_a, const uint8_t* p_codec_info_b) { return body(p_codec_info_a, p_codec_info_b); - }; + } }; extern struct A2DP_CodecTypeEqualsSbc A2DP_CodecTypeEqualsSbc; @@ -150,8 +142,8 @@ extern struct A2DP_CodecTypeEqualsSbc A2DP_CodecTypeEqualsSbc; struct A2DP_GetAllocationMethodCodeSbc { static int return_value; std::function body{ - [](const uint8_t* /* p_codec_info */) { return return_value; }}; - int operator()(const uint8_t* p_codec_info) { return body(p_codec_info); }; + [](const uint8_t* /* p_codec_info */) { return return_value; }}; + int operator()(const uint8_t* p_codec_info) { return body(p_codec_info); } }; extern struct A2DP_GetAllocationMethodCodeSbc A2DP_GetAllocationMethodCodeSbc; @@ -161,7 +153,7 @@ extern struct A2DP_GetAllocationMethodCodeSbc A2DP_GetAllocationMethodCodeSbc; struct A2DP_GetBitrateSbc { static uint32_t return_value; std::function body{[]() { return return_value; }}; - uint32_t operator()() { return body(); }; + uint32_t operator()() { return body(); } }; extern struct A2DP_GetBitrateSbc A2DP_GetBitrateSbc; @@ -171,8 +163,8 @@ extern struct A2DP_GetBitrateSbc A2DP_GetBitrateSbc; struct A2DP_GetChannelModeCodeSbc { static int return_value; std::function body{ - [](const uint8_t* /* p_codec_info */) { return return_value; }}; - int operator()(const uint8_t* p_codec_info) { return body(p_codec_info); }; + [](const uint8_t* /* p_codec_info */) { return return_value; }}; + int operator()(const uint8_t* p_codec_info) { return body(p_codec_info); } }; extern struct A2DP_GetChannelModeCodeSbc A2DP_GetChannelModeCodeSbc; @@ -181,11 +173,11 @@ extern struct A2DP_GetChannelModeCodeSbc A2DP_GetChannelModeCodeSbc; // Return: const tA2DP_DECODER_INTERFACE* struct A2DP_GetDecoderInterfaceSbc { static const tA2DP_DECODER_INTERFACE* return_value; - std::function - body{[](const uint8_t* /* p_codec_info */) { return return_value; }}; + std::function body{ + [](const uint8_t* /* p_codec_info */) { return return_value; }}; const tA2DP_DECODER_INTERFACE* operator()(const uint8_t* p_codec_info) { return body(p_codec_info); - }; + } }; extern struct A2DP_GetDecoderInterfaceSbc A2DP_GetDecoderInterfaceSbc; @@ -194,11 +186,11 @@ extern struct A2DP_GetDecoderInterfaceSbc A2DP_GetDecoderInterfaceSbc; // Return: const tA2DP_ENCODER_INTERFACE* struct A2DP_GetEncoderInterfaceSbc { static const tA2DP_ENCODER_INTERFACE* return_value; - std::function - body{[](const uint8_t* /* p_codec_info */) { return return_value; }}; + std::function body{ + [](const uint8_t* /* p_codec_info */) { return return_value; }}; const tA2DP_ENCODER_INTERFACE* operator()(const uint8_t* p_codec_info) { return body(p_codec_info); - }; + } }; extern struct A2DP_GetEncoderInterfaceSbc A2DP_GetEncoderInterfaceSbc; @@ -208,8 +200,8 @@ extern struct A2DP_GetEncoderInterfaceSbc A2DP_GetEncoderInterfaceSbc; struct A2DP_GetMaxBitpoolSbc { static int return_value; std::function body{ - [](const uint8_t* /* p_codec_info */) { return return_value; }}; - int operator()(const uint8_t* p_codec_info) { return body(p_codec_info); }; + [](const uint8_t* /* p_codec_info */) { return return_value; }}; + int operator()(const uint8_t* p_codec_info) { return body(p_codec_info); } }; extern struct A2DP_GetMaxBitpoolSbc A2DP_GetMaxBitpoolSbc; @@ -219,8 +211,8 @@ extern struct A2DP_GetMaxBitpoolSbc A2DP_GetMaxBitpoolSbc; struct A2DP_GetMinBitpoolSbc { static int return_value; std::function body{ - [](const uint8_t* /* p_codec_info */) { return return_value; }}; - int operator()(const uint8_t* p_codec_info) { return body(p_codec_info); }; + [](const uint8_t* /* p_codec_info */) { return return_value; }}; + int operator()(const uint8_t* p_codec_info) { return body(p_codec_info); } }; extern struct A2DP_GetMinBitpoolSbc A2DP_GetMinBitpoolSbc; @@ -230,8 +222,8 @@ extern struct A2DP_GetMinBitpoolSbc A2DP_GetMinBitpoolSbc; struct A2DP_GetNumberOfBlocksSbc { static int return_value; std::function body{ - [](const uint8_t* /* p_codec_info */) { return return_value; }}; - int operator()(const uint8_t* p_codec_info) { return body(p_codec_info); }; + [](const uint8_t* /* p_codec_info */) { return return_value; }}; + int operator()(const uint8_t* p_codec_info) { return body(p_codec_info); } }; extern struct A2DP_GetNumberOfBlocksSbc A2DP_GetNumberOfBlocksSbc; @@ -241,8 +233,8 @@ extern struct A2DP_GetNumberOfBlocksSbc A2DP_GetNumberOfBlocksSbc; struct A2DP_GetNumberOfSubbandsSbc { static int return_value; std::function body{ - [](const uint8_t* /* p_codec_info */) { return return_value; }}; - int operator()(const uint8_t* p_codec_info) { return body(p_codec_info); }; + [](const uint8_t* /* p_codec_info */) { return return_value; }}; + int operator()(const uint8_t* p_codec_info) { return body(p_codec_info); } }; extern struct A2DP_GetNumberOfSubbandsSbc A2DP_GetNumberOfSubbandsSbc; @@ -251,14 +243,12 @@ extern struct A2DP_GetNumberOfSubbandsSbc A2DP_GetNumberOfSubbandsSbc; // p_timestamp Return: bool struct A2DP_GetPacketTimestampSbc { static bool return_value; - std::function - body{[](const uint8_t* /* p_codec_info */, const uint8_t* /* p_data */, - uint32_t* /* p_timestamp */) { return return_value; }}; - bool operator()(const uint8_t* p_codec_info, const uint8_t* p_data, - uint32_t* p_timestamp) { + std::function + body{[](const uint8_t* /* p_codec_info */, const uint8_t* /* p_data */, + uint32_t* /* p_timestamp */) { return return_value; }}; + bool operator()(const uint8_t* p_codec_info, const uint8_t* p_data, uint32_t* p_timestamp) { return body(p_codec_info, p_data, p_timestamp); - }; + } }; extern struct A2DP_GetPacketTimestampSbc A2DP_GetPacketTimestampSbc; @@ -268,8 +258,8 @@ extern struct A2DP_GetPacketTimestampSbc A2DP_GetPacketTimestampSbc; struct A2DP_GetSamplingFrequencyCodeSbc { static int return_value; std::function body{ - [](const uint8_t* /* p_codec_info */) { return return_value; }}; - int operator()(const uint8_t* p_codec_info) { return body(p_codec_info); }; + [](const uint8_t* /* p_codec_info */) { return return_value; }}; + int operator()(const uint8_t* p_codec_info) { return body(p_codec_info); } }; extern struct A2DP_GetSamplingFrequencyCodeSbc A2DP_GetSamplingFrequencyCodeSbc; @@ -279,8 +269,8 @@ extern struct A2DP_GetSamplingFrequencyCodeSbc A2DP_GetSamplingFrequencyCodeSbc; struct A2DP_GetSinkTrackChannelTypeSbc { static int return_value; std::function body{ - [](const uint8_t* /* p_codec_info */) { return return_value; }}; - int operator()(const uint8_t* p_codec_info) { return body(p_codec_info); }; + [](const uint8_t* /* p_codec_info */) { return return_value; }}; + int operator()(const uint8_t* p_codec_info) { return body(p_codec_info); } }; extern struct A2DP_GetSinkTrackChannelTypeSbc A2DP_GetSinkTrackChannelTypeSbc; @@ -290,8 +280,8 @@ extern struct A2DP_GetSinkTrackChannelTypeSbc A2DP_GetSinkTrackChannelTypeSbc; struct A2DP_GetTrackBitsPerSampleSbc { static int return_value; std::function body{ - [](const uint8_t* /* p_codec_info */) { return return_value; }}; - int operator()(const uint8_t* p_codec_info) { return body(p_codec_info); }; + [](const uint8_t* /* p_codec_info */) { return return_value; }}; + int operator()(const uint8_t* p_codec_info) { return body(p_codec_info); } }; extern struct A2DP_GetTrackBitsPerSampleSbc A2DP_GetTrackBitsPerSampleSbc; @@ -301,8 +291,8 @@ extern struct A2DP_GetTrackBitsPerSampleSbc A2DP_GetTrackBitsPerSampleSbc; struct A2DP_GetTrackChannelCountSbc { static int return_value; std::function body{ - [](const uint8_t* /* p_codec_info */) { return return_value; }}; - int operator()(const uint8_t* p_codec_info) { return body(p_codec_info); }; + [](const uint8_t* /* p_codec_info */) { return return_value; }}; + int operator()(const uint8_t* p_codec_info) { return body(p_codec_info); } }; extern struct A2DP_GetTrackChannelCountSbc A2DP_GetTrackChannelCountSbc; @@ -312,8 +302,8 @@ extern struct A2DP_GetTrackChannelCountSbc A2DP_GetTrackChannelCountSbc; struct A2DP_GetTrackSampleRateSbc { static int return_value; std::function body{ - [](const uint8_t* /* p_codec_info */) { return return_value; }}; - int operator()(const uint8_t* p_codec_info) { return body(p_codec_info); }; + [](const uint8_t* /* p_codec_info */) { return return_value; }}; + int operator()(const uint8_t* p_codec_info) { return body(p_codec_info); } }; extern struct A2DP_GetTrackSampleRateSbc A2DP_GetTrackSampleRateSbc; @@ -323,8 +313,8 @@ extern struct A2DP_GetTrackSampleRateSbc A2DP_GetTrackSampleRateSbc; struct A2DP_InitCodecConfigSbc { static bool return_value; std::function body{ - [](AvdtpSepConfig* /* p_cfg */) { return return_value; }}; - bool operator()(AvdtpSepConfig* p_cfg) { return body(p_cfg); }; + [](AvdtpSepConfig* /* p_cfg */) { return return_value; }}; + bool operator()(AvdtpSepConfig* p_cfg) { return body(p_cfg); } }; extern struct A2DP_InitCodecConfigSbc A2DP_InitCodecConfigSbc; @@ -334,8 +324,8 @@ extern struct A2DP_InitCodecConfigSbc A2DP_InitCodecConfigSbc; struct A2DP_InitCodecConfigSbcSink { static bool return_value; std::function body{ - [](AvdtpSepConfig* /* p_cfg */) { return return_value; }}; - bool operator()(AvdtpSepConfig* p_cfg) { return body(p_cfg); }; + [](AvdtpSepConfig* /* p_cfg */) { return return_value; }}; + bool operator()(AvdtpSepConfig* p_cfg) { return body(p_cfg); } }; extern struct A2DP_InitCodecConfigSbcSink A2DP_InitCodecConfigSbcSink; @@ -343,9 +333,8 @@ extern struct A2DP_InitCodecConfigSbcSink A2DP_InitCodecConfigSbcSink; // Params: uint8_t* p_codec_info // Return: void struct A2DP_InitDefaultCodecSbc { - std::function body{ - [](uint8_t* /* p_codec_info */) {}}; - void operator()(uint8_t* p_codec_info) { body(p_codec_info); }; + std::function body{[](uint8_t* /* p_codec_info */) {}}; + void operator()(uint8_t* p_codec_info) { body(p_codec_info); } }; extern struct A2DP_InitDefaultCodecSbc A2DP_InitDefaultCodecSbc; @@ -355,8 +344,8 @@ extern struct A2DP_InitDefaultCodecSbc A2DP_InitDefaultCodecSbc; struct A2DP_IsPeerSinkCodecValidSbc { static bool return_value; std::function body{ - [](const uint8_t* /* p_codec_info */) { return return_value; }}; - bool operator()(const uint8_t* p_codec_info) { return body(p_codec_info); }; + [](const uint8_t* /* p_codec_info */) { return return_value; }}; + bool operator()(const uint8_t* p_codec_info) { return body(p_codec_info); } }; extern struct A2DP_IsPeerSinkCodecValidSbc A2DP_IsPeerSinkCodecValidSbc; @@ -366,11 +355,10 @@ extern struct A2DP_IsPeerSinkCodecValidSbc A2DP_IsPeerSinkCodecValidSbc; struct A2DP_IsPeerSourceCodecSupportedSbc { static bool return_value; std::function body{ - [](const uint8_t* /* p_codec_info */) { return return_value; }}; - bool operator()(const uint8_t* p_codec_info) { return body(p_codec_info); }; + [](const uint8_t* /* p_codec_info */) { return return_value; }}; + bool operator()(const uint8_t* p_codec_info) { return body(p_codec_info); } }; -extern struct A2DP_IsPeerSourceCodecSupportedSbc - A2DP_IsPeerSourceCodecSupportedSbc; +extern struct A2DP_IsPeerSourceCodecSupportedSbc A2DP_IsPeerSourceCodecSupportedSbc; // Name: A2DP_IsPeerSourceCodecValidSbc // Params: const uint8_t* p_codec_info @@ -378,8 +366,8 @@ extern struct A2DP_IsPeerSourceCodecSupportedSbc struct A2DP_IsPeerSourceCodecValidSbc { static bool return_value; std::function body{ - [](const uint8_t* /* p_codec_info */) { return return_value; }}; - bool operator()(const uint8_t* p_codec_info) { return body(p_codec_info); }; + [](const uint8_t* /* p_codec_info */) { return return_value; }}; + bool operator()(const uint8_t* p_codec_info) { return body(p_codec_info); } }; extern struct A2DP_IsPeerSourceCodecValidSbc A2DP_IsPeerSourceCodecValidSbc; @@ -389,8 +377,8 @@ extern struct A2DP_IsPeerSourceCodecValidSbc A2DP_IsPeerSourceCodecValidSbc; struct A2DP_IsSinkCodecSupportedSbc { static bool return_value; std::function body{ - [](const uint8_t* /* p_codec_info */) { return return_value; }}; - bool operator()(const uint8_t* p_codec_info) { return body(p_codec_info); }; + [](const uint8_t* /* p_codec_info */) { return return_value; }}; + bool operator()(const uint8_t* p_codec_info) { return body(p_codec_info); } }; extern struct A2DP_IsSinkCodecSupportedSbc A2DP_IsSinkCodecSupportedSbc; @@ -400,8 +388,8 @@ extern struct A2DP_IsSinkCodecSupportedSbc A2DP_IsSinkCodecSupportedSbc; struct A2DP_IsSinkCodecValidSbc { static bool return_value; std::function body{ - [](const uint8_t* /* p_codec_info */) { return return_value; }}; - bool operator()(const uint8_t* p_codec_info) { return body(p_codec_info); }; + [](const uint8_t* /* p_codec_info */) { return return_value; }}; + bool operator()(const uint8_t* p_codec_info) { return body(p_codec_info); } }; extern struct A2DP_IsSinkCodecValidSbc A2DP_IsSinkCodecValidSbc; @@ -411,8 +399,8 @@ extern struct A2DP_IsSinkCodecValidSbc A2DP_IsSinkCodecValidSbc; struct A2DP_IsSourceCodecValidSbc { static bool return_value; std::function body{ - [](const uint8_t* /* p_codec_info */) { return return_value; }}; - bool operator()(const uint8_t* p_codec_info) { return body(p_codec_info); }; + [](const uint8_t* /* p_codec_info */) { return return_value; }}; + bool operator()(const uint8_t* p_codec_info) { return body(p_codec_info); } }; extern struct A2DP_IsSourceCodecValidSbc A2DP_IsSourceCodecValidSbc; @@ -422,10 +410,8 @@ extern struct A2DP_IsSourceCodecValidSbc A2DP_IsSourceCodecValidSbc; struct A2DP_SinkCodecIndexSbc { static btav_a2dp_codec_index_t return_value; std::function body{ - [](const uint8_t* /* p_codec_info */) { return return_value; }}; - btav_a2dp_codec_index_t operator()(const uint8_t* p_codec_info) { - return body(p_codec_info); - }; + [](const uint8_t* /* p_codec_info */) { return return_value; }}; + btav_a2dp_codec_index_t operator()(const uint8_t* p_codec_info) { return body(p_codec_info); } }; extern struct A2DP_SinkCodecIndexSbc A2DP_SinkCodecIndexSbc; @@ -435,10 +421,8 @@ extern struct A2DP_SinkCodecIndexSbc A2DP_SinkCodecIndexSbc; struct A2DP_SourceCodecIndexSbc { static btav_a2dp_codec_index_t return_value; std::function body{ - [](const uint8_t* /* p_codec_info */) { return return_value; }}; - btav_a2dp_codec_index_t operator()(const uint8_t* p_codec_info) { - return body(p_codec_info); - }; + [](const uint8_t* /* p_codec_info */) { return return_value; }}; + btav_a2dp_codec_index_t operator()(const uint8_t* p_codec_info) { return body(p_codec_info); } }; extern struct A2DP_SourceCodecIndexSbc A2DP_SourceCodecIndexSbc; diff --git a/system/test/mock/mock_stack_acl.cc b/system/test/mock/mock_stack_acl.cc index 420fd2d03d8..90f68ffd575 100644 --- a/system/test/mock/mock_stack_acl.cc +++ b/system/test/mock/mock_stack_acl.cc @@ -57,19 +57,15 @@ struct acl_peer_supports_ble_2m_phy acl_peer_supports_ble_2m_phy; struct acl_peer_supports_ble_coded_phy acl_peer_supports_ble_coded_phy; struct acl_send_data_packet_br_edr acl_send_data_packet_br_edr; struct acl_peer_supports_ble_connection_parameters_request - acl_peer_supports_ble_connection_parameters_request; -struct acl_ble_connection_parameters_request - acl_ble_connection_parameters_request; -struct acl_peer_supports_ble_packet_extension - acl_peer_supports_ble_packet_extension; + acl_peer_supports_ble_connection_parameters_request; +struct acl_ble_connection_parameters_request acl_ble_connection_parameters_request; +struct acl_peer_supports_ble_packet_extension acl_peer_supports_ble_packet_extension; struct acl_peer_supports_sniff_subrating acl_peer_supports_sniff_subrating; -struct acl_peer_supports_ble_connection_subrating - acl_peer_supports_ble_connection_subrating; +struct acl_peer_supports_ble_connection_subrating acl_peer_supports_ble_connection_subrating; struct acl_peer_supports_ble_connection_subrating_host - acl_peer_supports_ble_connection_subrating_host; + acl_peer_supports_ble_connection_subrating_host; struct acl_refresh_remote_address acl_refresh_remote_address; -struct acl_set_peer_le_features_from_handle - acl_set_peer_le_features_from_handle; +struct acl_set_peer_le_features_from_handle acl_set_peer_le_features_from_handle; struct acl_get_connection_from_address acl_get_connection_from_address; struct btm_acl_for_bda btm_acl_for_bda; struct acl_get_connection_from_handle acl_get_connection_from_handle; @@ -122,23 +118,17 @@ struct btm_acl_process_sca_cmpl_pkt btm_acl_process_sca_cmpl_pkt; struct btm_acl_removed btm_acl_removed; struct btm_acl_role_changed btm_acl_role_changed; struct btm_acl_update_conn_addr btm_acl_update_conn_addr; -struct btm_ble_refresh_local_resolvable_private_addr - btm_ble_refresh_local_resolvable_private_addr; +struct btm_ble_refresh_local_resolvable_private_addr btm_ble_refresh_local_resolvable_private_addr; struct btm_cont_rswitch_from_handle btm_cont_rswitch_from_handle; struct btm_establish_continue_from_address btm_establish_continue_from_address; struct btm_process_remote_ext_features btm_process_remote_ext_features; struct btm_process_remote_version_complete btm_process_remote_version_complete; -struct btm_read_automatic_flush_timeout_complete - btm_read_automatic_flush_timeout_complete; -struct btm_read_failed_contact_counter_complete - btm_read_failed_contact_counter_complete; -struct btm_read_failed_contact_counter_timeout - btm_read_failed_contact_counter_timeout; +struct btm_read_automatic_flush_timeout_complete btm_read_automatic_flush_timeout_complete; +struct btm_read_failed_contact_counter_complete btm_read_failed_contact_counter_complete; +struct btm_read_failed_contact_counter_timeout btm_read_failed_contact_counter_timeout; struct btm_read_remote_ext_features btm_read_remote_ext_features; -struct btm_read_remote_ext_features_complete - btm_read_remote_ext_features_complete; -struct btm_read_remote_ext_features_complete_raw - btm_read_remote_ext_features_complete_raw; +struct btm_read_remote_ext_features_complete btm_read_remote_ext_features_complete; +struct btm_read_remote_ext_features_complete_raw btm_read_remote_ext_features_complete_raw; struct btm_read_remote_ext_features_failed btm_read_remote_ext_features_failed; struct btm_read_remote_version_complete btm_read_remote_version_complete; struct btm_read_rssi_complete btm_read_rssi_complete; @@ -148,12 +138,10 @@ struct btm_read_tx_power_timeout btm_read_tx_power_timeout; struct btm_rejectlist_role_change_device btm_rejectlist_role_change_device; struct btm_set_link_policy btm_set_link_policy; struct btm_set_packet_types_from_address btm_set_packet_types_from_address; -struct hci_btm_set_link_supervision_timeout - hci_btm_set_link_supervision_timeout; +struct hci_btm_set_link_supervision_timeout hci_btm_set_link_supervision_timeout; struct on_acl_br_edr_connected on_acl_br_edr_connected; struct on_acl_br_edr_failed on_acl_br_edr_failed; -struct BTM_unblock_role_switch_and_sniff_mode_for - BTM_unblock_role_switch_and_sniff_mode_for; +struct BTM_unblock_role_switch_and_sniff_mode_for BTM_unblock_role_switch_and_sniff_mode_for; } // namespace stack_acl } // namespace mock @@ -164,43 +152,37 @@ bool BTM_BLE_IS_RESOLVE_BDA(const RawAddress& x) { inc_func_call_count(__func__); return test::mock::stack_acl::BTM_BLE_IS_RESOLVE_BDA(x); } -bool BTM_IsAclConnectionUp(const RawAddress& remote_bda, - tBT_TRANSPORT transport) { +bool BTM_IsAclConnectionUp(const RawAddress& remote_bda, tBT_TRANSPORT transport) { inc_func_call_count(__func__); return test::mock::stack_acl::BTM_IsAclConnectionUp(remote_bda, transport); } -bool BTM_IsAclConnectionUpAndHandleValid(const RawAddress& remote_bda, - tBT_TRANSPORT transport) { +bool BTM_IsAclConnectionUpAndHandleValid(const RawAddress& remote_bda, tBT_TRANSPORT transport) { inc_func_call_count(__func__); - return test::mock::stack_acl::BTM_IsAclConnectionUpAndHandleValid(remote_bda, - transport); + return test::mock::stack_acl::BTM_IsAclConnectionUpAndHandleValid(remote_bda, transport); } bool BTM_IsBleConnection(uint16_t hci_handle) { inc_func_call_count(__func__); return test::mock::stack_acl::BTM_IsBleConnection(hci_handle); } -bool BTM_IsPhy2mSupported(const RawAddress& remote_bda, - tBT_TRANSPORT transport) { +bool BTM_IsPhy2mSupported(const RawAddress& remote_bda, tBT_TRANSPORT transport) { inc_func_call_count(__func__); return test::mock::stack_acl::BTM_IsPhy2mSupported(remote_bda, transport); } -bool BTM_ReadRemoteConnectionAddr(const RawAddress& pseudo_addr, - RawAddress& conn_addr, - tBLE_ADDR_TYPE* p_addr_type, - bool ota_address) { +bool BTM_ReadRemoteConnectionAddr(const RawAddress& pseudo_addr, RawAddress& conn_addr, + tBLE_ADDR_TYPE* p_addr_type, bool ota_address) { inc_func_call_count(__func__); - return test::mock::stack_acl::BTM_ReadRemoteConnectionAddr( - pseudo_addr, conn_addr, p_addr_type, ota_address); + return test::mock::stack_acl::BTM_ReadRemoteConnectionAddr(pseudo_addr, conn_addr, p_addr_type, + ota_address); } bool BTM_IsRemoteVersionReceived(const RawAddress& addr) { inc_func_call_count(__func__); return test::mock::stack_acl::BTM_IsRemoteVersionReceived(addr); } -bool BTM_ReadRemoteVersion(const RawAddress& addr, uint8_t* lmp_version, - uint16_t* manufacturer, uint16_t* lmp_sub_version) { +bool BTM_ReadRemoteVersion(const RawAddress& addr, uint8_t* lmp_version, uint16_t* manufacturer, + uint16_t* lmp_sub_version) { inc_func_call_count(__func__); - return test::mock::stack_acl::BTM_ReadRemoteVersion( - addr, lmp_version, manufacturer, lmp_sub_version); + return test::mock::stack_acl::BTM_ReadRemoteVersion(addr, lmp_version, manufacturer, + lmp_sub_version); } bool BTM_is_sniff_allowed_for(const RawAddress& peer_addr) { inc_func_call_count(__func__); @@ -213,15 +195,13 @@ bool acl_create_le_connection(const RawAddress& bd_addr) { bool acl_create_le_connection_with_id(uint8_t id, const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type) { inc_func_call_count(__func__); - return test::mock::stack_acl::acl_create_le_connection_with_id(id, bd_addr, - addr_type); + return test::mock::stack_acl::acl_create_le_connection_with_id(id, bd_addr, addr_type); } bool acl_is_role_switch_allowed() { inc_func_call_count(__func__); return test::mock::stack_acl::acl_is_role_switch_allowed(); } -bool acl_is_switch_role_idle(const RawAddress& bd_addr, - tBT_TRANSPORT transport) { +bool acl_is_switch_role_idle(const RawAddress& bd_addr, tBT_TRANSPORT transport) { inc_func_call_count(__func__); return test::mock::stack_acl::acl_is_switch_role_idle(bd_addr, transport); } @@ -233,25 +213,21 @@ bool acl_peer_supports_ble_coded_phy(uint16_t hci_handle) { inc_func_call_count(__func__); return test::mock::stack_acl::acl_peer_supports_ble_coded_phy(hci_handle); } -bool acl_peer_supports_ble_connection_parameters_request( - const RawAddress& remote_bda) { +bool acl_peer_supports_ble_connection_parameters_request(const RawAddress& remote_bda) { inc_func_call_count(__func__); - return test::mock::stack_acl:: - acl_peer_supports_ble_connection_parameters_request(remote_bda); + return test::mock::stack_acl::acl_peer_supports_ble_connection_parameters_request(remote_bda); } -void acl_ble_connection_parameters_request( - uint16_t handle, uint16_t conn_int_min, uint16_t conn_int_max, - uint16_t conn_latency, uint16_t conn_timeout, uint16_t min_ce_len, - uint16_t max_ce_len) { +void acl_ble_connection_parameters_request(uint16_t handle, uint16_t conn_int_min, + uint16_t conn_int_max, uint16_t conn_latency, + uint16_t conn_timeout, uint16_t min_ce_len, + uint16_t max_ce_len) { inc_func_call_count(__func__); test::mock::stack_acl::acl_ble_connection_parameters_request( - handle, conn_int_min, conn_int_max, conn_latency, conn_timeout, - min_ce_len, max_ce_len); + handle, conn_int_min, conn_int_max, conn_latency, conn_timeout, min_ce_len, max_ce_len); } bool acl_peer_supports_ble_packet_extension(uint16_t hci_handle) { inc_func_call_count(__func__); - return test::mock::stack_acl::acl_peer_supports_ble_packet_extension( - hci_handle); + return test::mock::stack_acl::acl_peer_supports_ble_packet_extension(hci_handle); } bool acl_peer_supports_sniff_subrating(const RawAddress& remote_bda) { inc_func_call_count(__func__); @@ -259,39 +235,30 @@ bool acl_peer_supports_sniff_subrating(const RawAddress& remote_bda) { } bool acl_peer_supports_ble_connection_subrating(const RawAddress& remote_bda) { inc_func_call_count(__func__); - return test::mock::stack_acl::acl_peer_supports_ble_connection_subrating( - remote_bda); + return test::mock::stack_acl::acl_peer_supports_ble_connection_subrating(remote_bda); } -bool acl_peer_supports_ble_connection_subrating_host( - const RawAddress& remote_bda) { +bool acl_peer_supports_ble_connection_subrating_host(const RawAddress& remote_bda) { inc_func_call_count(__func__); - return test::mock::stack_acl::acl_peer_supports_ble_connection_subrating_host( - remote_bda); + return test::mock::stack_acl::acl_peer_supports_ble_connection_subrating_host(remote_bda); } bool acl_refresh_remote_address(const RawAddress& identity_address, - tBLE_ADDR_TYPE identity_address_type, - const RawAddress& bda, - tBLE_RAND_ADDR_TYPE rra_type, - const RawAddress& rpa) { + tBLE_ADDR_TYPE identity_address_type, const RawAddress& bda, + tBLE_RAND_ADDR_TYPE rra_type, const RawAddress& rpa) { inc_func_call_count(__func__); - return test::mock::stack_acl::acl_refresh_remote_address( - identity_address, identity_address_type, bda, rra_type, rpa); + return test::mock::stack_acl::acl_refresh_remote_address(identity_address, identity_address_type, + bda, rra_type, rpa); } -bool acl_set_peer_le_features_from_handle(uint16_t hci_handle, - const uint8_t* p) { +bool acl_set_peer_le_features_from_handle(uint16_t hci_handle, const uint8_t* p) { inc_func_call_count(__func__); - return test::mock::stack_acl::acl_set_peer_le_features_from_handle(hci_handle, - p); + return test::mock::stack_acl::acl_set_peer_le_features_from_handle(hci_handle, p); } void acl_send_data_packet_br_edr(const RawAddress& bd_addr, BT_HDR* p_buf) { inc_func_call_count(__func__); test::mock::stack_acl::acl_send_data_packet_br_edr(bd_addr, p_buf); } -tACL_CONN* acl_get_connection_from_address(const RawAddress& bd_addr, - tBT_TRANSPORT transport) { +tACL_CONN* acl_get_connection_from_address(const RawAddress& bd_addr, tBT_TRANSPORT transport) { inc_func_call_count(__func__); - return test::mock::stack_acl::acl_get_connection_from_address(bd_addr, - transport); + return test::mock::stack_acl::acl_get_connection_from_address(bd_addr, transport); } tACL_CONN* btm_acl_for_bda(const RawAddress& bd_addr, tBT_TRANSPORT transport) { inc_func_call_count(__func__); @@ -301,8 +268,7 @@ tACL_CONN* acl_get_connection_from_handle(uint16_t handle) { inc_func_call_count(__func__); return test::mock::stack_acl::acl_get_connection_from_handle(handle); } -tBTM_STATUS BTM_GetLinkSuperTout(const RawAddress& remote_bda, - uint16_t* p_timeout) { +tBTM_STATUS BTM_GetLinkSuperTout(const RawAddress& remote_bda, uint16_t* p_timeout) { inc_func_call_count(__func__); return test::mock::stack_acl::BTM_GetLinkSuperTout(remote_bda, p_timeout); } @@ -310,8 +276,7 @@ tBTM_STATUS BTM_GetRole(const RawAddress& remote_bd_addr, tHCI_ROLE* p_role) { inc_func_call_count(__func__); return test::mock::stack_acl::BTM_GetRole(remote_bd_addr, p_role); } -tBTM_STATUS BTM_ReadFailedContactCounter(const RawAddress& remote_bda, - tBTM_CMPL_CB* p_cb) { +tBTM_STATUS BTM_ReadFailedContactCounter(const RawAddress& remote_bda, tBTM_CMPL_CB* p_cb) { inc_func_call_count(__func__); return test::mock::stack_acl::BTM_ReadFailedContactCounter(remote_bda, p_cb); } @@ -319,13 +284,12 @@ tBTM_STATUS BTM_ReadRSSI(const RawAddress& remote_bda, tBTM_CMPL_CB* p_cb) { inc_func_call_count(__func__); return test::mock::stack_acl::BTM_ReadRSSI(remote_bda, p_cb); } -tBTM_STATUS BTM_ReadTxPower(const RawAddress& remote_bda, - tBT_TRANSPORT transport, tBTM_CMPL_CB* p_cb) { +tBTM_STATUS BTM_ReadTxPower(const RawAddress& remote_bda, tBT_TRANSPORT transport, + tBTM_CMPL_CB* p_cb) { inc_func_call_count(__func__); return test::mock::stack_acl::BTM_ReadTxPower(remote_bda, transport, p_cb); } -tBTM_STATUS BTM_SetLinkSuperTout(const RawAddress& remote_bda, - uint16_t timeout) { +tBTM_STATUS BTM_SetLinkSuperTout(const RawAddress& remote_bda, uint16_t timeout) { inc_func_call_count(__func__); return test::mock::stack_acl::BTM_SetLinkSuperTout(remote_bda, timeout); } @@ -345,8 +309,7 @@ bool btm_is_acl_locally_initiated(void) { inc_func_call_count(__func__); return test::mock::stack_acl::btm_is_acl_locally_initiated(); } -uint16_t BTM_GetHCIConnHandle(const RawAddress& remote_bda, - tBT_TRANSPORT transport) { +uint16_t BTM_GetHCIConnHandle(const RawAddress& remote_bda, tBT_TRANSPORT transport) { inc_func_call_count(__func__); return test::mock::stack_acl::BTM_GetHCIConnHandle(remote_bda, transport); } @@ -386,12 +349,11 @@ void ACL_UnregisterClient(struct acl_client_callback_s* callbacks) { inc_func_call_count(__func__); test::mock::stack_acl::ACL_UnregisterClient(callbacks); } -void BTM_ReadConnectionAddr(const RawAddress& remote_bda, - RawAddress& local_conn_addr, +void BTM_ReadConnectionAddr(const RawAddress& remote_bda, RawAddress& local_conn_addr, tBLE_ADDR_TYPE* p_addr_type, bool ota_address) { inc_func_call_count(__func__); - test::mock::stack_acl::BTM_ReadConnectionAddr(remote_bda, local_conn_addr, - p_addr_type, ota_address); + test::mock::stack_acl::BTM_ReadConnectionAddr(remote_bda, local_conn_addr, p_addr_type, + ota_address); } void BTM_RequestPeerSCA(const RawAddress& remote_bda, tBT_TRANSPORT transport) { inc_func_call_count(__func__); @@ -424,11 +386,9 @@ void BTM_unblock_sniff_mode_for(const RawAddress& peer_addr) { void acl_disconnect_after_role_switch(uint16_t conn_handle, tHCI_STATUS reason, std::string comment) { inc_func_call_count(__func__); - test::mock::stack_acl::acl_disconnect_after_role_switch(conn_handle, reason, - comment); + test::mock::stack_acl::acl_disconnect_after_role_switch(conn_handle, reason, comment); } -void acl_disconnect_from_handle(uint16_t handle, tHCI_STATUS reason, - std::string comment) { +void acl_disconnect_from_handle(uint16_t handle, tHCI_STATUS reason, std::string comment) { inc_func_call_count(__func__); test::mock::stack_acl::acl_disconnect_from_handle(handle, reason, comment); } @@ -439,8 +399,8 @@ void acl_packets_completed(uint16_t handle, uint16_t credits) { void acl_process_extended_features(uint16_t handle, uint8_t current_page_number, uint8_t max_page_number, uint64_t features) { inc_func_call_count(__func__); - test::mock::stack_acl::acl_process_extended_features( - handle, current_page_number, max_page_number, features); + test::mock::stack_acl::acl_process_extended_features(handle, current_page_number, max_page_number, + features); } void acl_process_supported_features(uint16_t handle, uint64_t features) { inc_func_call_count(__func__); @@ -458,19 +418,17 @@ void acl_set_disconnect_reason(tHCI_STATUS acl_disc_reason) { inc_func_call_count(__func__); test::mock::stack_acl::acl_set_disconnect_reason(acl_disc_reason); } -void acl_write_automatic_flush_timeout(const RawAddress& bd_addr, - uint16_t flush_timeout_in_ticks) { +void acl_write_automatic_flush_timeout(const RawAddress& bd_addr, uint16_t flush_timeout_in_ticks) { inc_func_call_count(__func__); - test::mock::stack_acl::acl_write_automatic_flush_timeout( - bd_addr, flush_timeout_in_ticks); + test::mock::stack_acl::acl_write_automatic_flush_timeout(bd_addr, flush_timeout_in_ticks); } -void btm_acl_connected(const RawAddress& bda, uint16_t handle, - tHCI_STATUS status, uint8_t enc_mode) { +void btm_acl_connected(const RawAddress& bda, uint16_t handle, tHCI_STATUS status, + uint8_t enc_mode) { inc_func_call_count(__func__); test::mock::stack_acl::btm_acl_connected(bda, handle, status, enc_mode); } -void btm_acl_created(const RawAddress& bda, uint16_t hci_handle, - tHCI_ROLE link_role, tBT_TRANSPORT transport) { +void btm_acl_created(const RawAddress& bda, uint16_t hci_handle, tHCI_ROLE link_role, + tBT_TRANSPORT transport) { inc_func_call_count(__func__); test::mock::stack_acl::btm_acl_created(bda, hci_handle, link_role, transport); } @@ -478,13 +436,11 @@ void btm_acl_device_down(void) { inc_func_call_count(__func__); test::mock::stack_acl::btm_acl_device_down(); } -void btm_acl_disconnected(tHCI_STATUS status, uint16_t handle, - tHCI_REASON reason) { +void btm_acl_disconnected(tHCI_STATUS status, uint16_t handle, tHCI_REASON reason) { inc_func_call_count(__func__); test::mock::stack_acl::btm_acl_disconnected(status, handle, reason); } -void btm_acl_encrypt_change(uint16_t handle, uint8_t status, - uint8_t encr_enable) { +void btm_acl_encrypt_change(uint16_t handle, uint8_t status, uint8_t encr_enable) { inc_func_call_count(__func__); test::mock::stack_acl::btm_acl_encrypt_change(handle, status, encr_enable); } @@ -504,8 +460,7 @@ void btm_acl_flush(uint16_t handle) { inc_func_call_count(__func__); test::mock::stack_acl::btm_acl_flush(handle); } -void btm_acl_role_changed(tHCI_STATUS hci_status, const RawAddress& bd_addr, - tHCI_ROLE new_role) { +void btm_acl_role_changed(tHCI_STATUS hci_status, const RawAddress& bd_addr, tHCI_ROLE new_role) { inc_func_call_count(__func__); test::mock::stack_acl::btm_acl_role_changed(hci_status, bd_addr, new_role); } @@ -513,34 +468,28 @@ void btm_acl_update_conn_addr(uint16_t handle, const RawAddress& address) { inc_func_call_count(__func__); test::mock::stack_acl::btm_acl_update_conn_addr(handle, address); } -void btm_ble_refresh_local_resolvable_private_addr( - const RawAddress& pseudo_addr, const RawAddress& local_rpa) { +void btm_ble_refresh_local_resolvable_private_addr(const RawAddress& pseudo_addr, + const RawAddress& local_rpa) { inc_func_call_count(__func__); - test::mock::stack_acl::btm_ble_refresh_local_resolvable_private_addr( - pseudo_addr, local_rpa); + test::mock::stack_acl::btm_ble_refresh_local_resolvable_private_addr(pseudo_addr, local_rpa); } void btm_cont_rswitch_from_handle(uint16_t hci_handle) { inc_func_call_count(__func__); test::mock::stack_acl::btm_cont_rswitch_from_handle(hci_handle); } -void btm_establish_continue_from_address(const RawAddress& bda, - tBT_TRANSPORT transport) { +void btm_establish_continue_from_address(const RawAddress& bda, tBT_TRANSPORT transport) { inc_func_call_count(__func__); test::mock::stack_acl::btm_establish_continue_from_address(bda, transport); } -void btm_process_remote_ext_features(tACL_CONN* p_acl_cb, - uint8_t max_page_number) { +void btm_process_remote_ext_features(tACL_CONN* p_acl_cb, uint8_t max_page_number) { inc_func_call_count(__func__); - test::mock::stack_acl::btm_process_remote_ext_features(p_acl_cb, - max_page_number); + test::mock::stack_acl::btm_process_remote_ext_features(p_acl_cb, max_page_number); } -void btm_process_remote_version_complete(uint8_t status, uint16_t handle, - uint8_t lmp_version, - uint16_t manufacturer, - uint16_t lmp_subversion) { +void btm_process_remote_version_complete(uint8_t status, uint16_t handle, uint8_t lmp_version, + uint16_t manufacturer, uint16_t lmp_subversion) { inc_func_call_count(__func__); - test::mock::stack_acl::btm_process_remote_version_complete( - status, handle, lmp_version, manufacturer, lmp_subversion); + test::mock::stack_acl::btm_process_remote_version_complete(status, handle, lmp_version, + manufacturer, lmp_subversion); } void btm_read_automatic_flush_timeout_complete(uint8_t* p) { inc_func_call_count(__func__); @@ -558,12 +507,11 @@ void btm_read_remote_ext_features(uint16_t handle, uint8_t page_number) { inc_func_call_count(__func__); test::mock::stack_acl::btm_read_remote_ext_features(handle, page_number); } -void btm_read_remote_ext_features_complete(uint16_t handle, uint8_t page_num, - uint8_t max_page, +void btm_read_remote_ext_features_complete(uint16_t handle, uint8_t page_num, uint8_t max_page, uint8_t* features) { inc_func_call_count(__func__); - test::mock::stack_acl::btm_read_remote_ext_features_complete( - handle, page_num, max_page, features); + test::mock::stack_acl::btm_read_remote_ext_features_complete(handle, page_num, max_page, + features); } void btm_read_remote_ext_features_complete_raw(uint8_t* p, uint8_t evt_len) { inc_func_call_count(__func__); @@ -573,13 +521,11 @@ void btm_read_remote_ext_features_failed(uint8_t status, uint16_t handle) { inc_func_call_count(__func__); test::mock::stack_acl::btm_read_remote_ext_features_failed(status, handle); } -void btm_read_remote_version_complete(tHCI_STATUS status, uint16_t handle, - uint8_t lmp_version, - uint16_t manufacturer, - uint16_t lmp_subversion) { +void btm_read_remote_version_complete(tHCI_STATUS status, uint16_t handle, uint8_t lmp_version, + uint16_t manufacturer, uint16_t lmp_subversion) { inc_func_call_count(__func__); - test::mock::stack_acl::btm_read_remote_version_complete( - status, handle, lmp_version, manufacturer, lmp_subversion); + test::mock::stack_acl::btm_read_remote_version_complete(status, handle, lmp_version, manufacturer, + lmp_subversion); } void btm_read_rssi_complete(uint8_t* p, uint16_t evt_len) { inc_func_call_count(__func__); @@ -597,8 +543,7 @@ void btm_read_tx_power_timeout(void* data) { inc_func_call_count(__func__); test::mock::stack_acl::btm_read_tx_power_timeout(data); } -void btm_rejectlist_role_change_device(const RawAddress& bd_addr, - uint8_t hci_status) { +void btm_rejectlist_role_change_device(const RawAddress& bd_addr, uint8_t hci_status) { inc_func_call_count(__func__); test::mock::stack_acl::btm_rejectlist_role_change_device(bd_addr, hci_status); } @@ -606,8 +551,7 @@ void btm_set_link_policy(tACL_CONN* conn, tLINK_POLICY policy) { inc_func_call_count(__func__); test::mock::stack_acl::btm_set_link_policy(conn, policy); } -void btm_set_packet_types_from_address(const RawAddress& bd_addr, - uint16_t pkt_types) { +void btm_set_packet_types_from_address(const RawAddress& bd_addr, uint16_t pkt_types) { inc_func_call_count(__func__); test::mock::stack_acl::btm_set_packet_types_from_address(bd_addr, pkt_types); } @@ -615,18 +559,15 @@ void hci_btm_set_link_supervision_timeout(tACL_CONN& link, uint16_t timeout) { inc_func_call_count(__func__); test::mock::stack_acl::hci_btm_set_link_supervision_timeout(link, timeout); } -void btm_connection_request(const RawAddress& bda, - const bluetooth::hci::ClassOfDevice& cod) { +void btm_connection_request(const RawAddress& bda, const bluetooth::hci::ClassOfDevice& cod) { test::mock::stack_acl::btm_connection_request(bda, cod); } -void on_acl_br_edr_connected(const RawAddress& bda, uint16_t handle, - uint8_t enc_mode, bool locally_initiated) { +void on_acl_br_edr_connected(const RawAddress& bda, uint16_t handle, uint8_t enc_mode, + bool locally_initiated) { inc_func_call_count(__func__); - test::mock::stack_acl::on_acl_br_edr_connected(bda, handle, enc_mode, - locally_initiated); + test::mock::stack_acl::on_acl_br_edr_connected(bda, handle, enc_mode, locally_initiated); } -void on_acl_br_edr_failed(const RawAddress& bda, tHCI_STATUS status, - bool locally_initiated) { +void on_acl_br_edr_failed(const RawAddress& bda, tHCI_STATUS status, bool locally_initiated) { inc_func_call_count(__func__); test::mock::stack_acl::on_acl_br_edr_failed(bda, status, locally_initiated); } @@ -638,5 +579,4 @@ void BTM_unblock_role_switch_and_sniff_mode_for(const RawAddress& peer_addr) { // END mockcify generation -void BTM_block_role_switch_and_sniff_mode_for( - const RawAddress& /* peer_addr */) {} +void BTM_block_role_switch_and_sniff_mode_for(const RawAddress& /* peer_addr */) {} diff --git a/system/test/mock/mock_stack_acl.h b/system/test/mock/mock_stack_acl.h index 356b7b34725..44353d635f8 100644 --- a/system/test/mock/mock_stack_acl.h +++ b/system/test/mock/mock_stack_acl.h @@ -42,55 +42,49 @@ namespace stack_acl { // Params: const RawAddress& x // Returns: bool struct BTM_BLE_IS_RESOLVE_BDA { - std::function body{ - [](const RawAddress& /* x */) { return false; }}; - bool operator()(const RawAddress& x) { return body(x); }; + std::function body{[](const RawAddress& /* x */) { return false; }}; + bool operator()(const RawAddress& x) { return body(x); } }; extern struct BTM_BLE_IS_RESOLVE_BDA BTM_BLE_IS_RESOLVE_BDA; // Name: BTM_IsAclConnectionUp // Params: const RawAddress& remote_bda, tBT_TRANSPORT transport // Returns: bool struct BTM_IsAclConnectionUp { - std::function - body{[](const RawAddress& /* remote_bda */, - tBT_TRANSPORT /* transport */) { return false; }}; + std::function body{ + [](const RawAddress& /* remote_bda */, tBT_TRANSPORT /* transport */) { return false; }}; bool operator()(const RawAddress& remote_bda, tBT_TRANSPORT transport) { return body(remote_bda, transport); - }; + } }; extern struct BTM_IsAclConnectionUp BTM_IsAclConnectionUp; // Name: BTM_IsAclConnectionUpAndHandleValid // Params: const RawAddress& remote_bda, tBT_TRANSPORT transport // Returns: bool struct BTM_IsAclConnectionUpAndHandleValid { - std::function - body{[](const RawAddress& /* remote_bda */, - tBT_TRANSPORT /* transport */) { return false; }}; + std::function body{ + [](const RawAddress& /* remote_bda */, tBT_TRANSPORT /* transport */) { return false; }}; bool operator()(const RawAddress& remote_bda, tBT_TRANSPORT transport) { return body(remote_bda, transport); - }; + } }; -extern struct BTM_IsAclConnectionUpAndHandleValid - BTM_IsAclConnectionUpAndHandleValid; +extern struct BTM_IsAclConnectionUpAndHandleValid BTM_IsAclConnectionUpAndHandleValid; // Name: BTM_IsBleConnection // Params: uint16_t hci_handle // Returns: bool struct BTM_IsBleConnection { - std::function body{ - [](uint16_t /* hci_handle */) { return false; }}; - bool operator()(uint16_t hci_handle) { return body(hci_handle); }; + std::function body{[](uint16_t /* hci_handle */) { return false; }}; + bool operator()(uint16_t hci_handle) { return body(hci_handle); } }; extern struct BTM_IsBleConnection BTM_IsBleConnection; // Name: BTM_IsPhy2mSupported // Params: const RawAddress& remote_bda, tBT_TRANSPORT transport // Returns: bool struct BTM_IsPhy2mSupported { - std::function - body{[](const RawAddress& /* remote_bda */, - tBT_TRANSPORT /* transport */) { return false; }}; + std::function body{ + [](const RawAddress& /* remote_bda */, tBT_TRANSPORT /* transport */) { return false; }}; bool operator()(const RawAddress& remote_bda, tBT_TRANSPORT transport) { return body(remote_bda, transport); - }; + } }; extern struct BTM_IsPhy2mSupported BTM_IsPhy2mSupported; // Name: BTM_ReadRemoteConnectionAddr @@ -99,13 +93,12 @@ extern struct BTM_IsPhy2mSupported BTM_IsPhy2mSupported; struct BTM_ReadRemoteConnectionAddr { std::function - body{[](const RawAddress& /* pseudo_addr */, RawAddress& /* conn_addr */, - tBLE_ADDR_TYPE* /* p_addr_type */, - bool /* ota_address */) { return false; }}; - bool operator()(const RawAddress& pseudo_addr, RawAddress& conn_addr, - tBLE_ADDR_TYPE* p_addr_type, bool ota_address) { + body{[](const RawAddress& /* pseudo_addr */, RawAddress& /* conn_addr */, + tBLE_ADDR_TYPE* /* p_addr_type */, bool /* ota_address */) { return false; }}; + bool operator()(const RawAddress& pseudo_addr, RawAddress& conn_addr, tBLE_ADDR_TYPE* p_addr_type, + bool ota_address) { return body(pseudo_addr, conn_addr, p_addr_type, ota_address); - }; + } }; extern struct BTM_ReadRemoteConnectionAddr BTM_ReadRemoteConnectionAddr; // Name: BTM_IsRemoteVersionReceived @@ -113,8 +106,8 @@ extern struct BTM_ReadRemoteConnectionAddr BTM_ReadRemoteConnectionAddr; // Returns: bool struct BTM_IsRemoteVersionReceived { std::function body{ - [](const RawAddress& /* addr */) { return false; }}; - bool operator()(const RawAddress& addr) { return body(addr); }; + [](const RawAddress& /* addr */) { return false; }}; + bool operator()(const RawAddress& addr) { return body(addr); } }; extern struct BTM_IsRemoteVersionReceived BTM_IsRemoteVersionReceived; // Name: BTM_ReadRemoteVersion @@ -122,15 +115,14 @@ extern struct BTM_IsRemoteVersionReceived BTM_IsRemoteVersionReceived; // manufacturer, uint16_t* lmp_sub_version // Returns: bool struct BTM_ReadRemoteVersion { - std::function - body{[](const RawAddress& /* addr */, uint8_t* /* lmp_version */, - uint16_t* /* manufacturer */, - uint16_t* /* lmp_sub_version */) { return false; }}; - bool operator()(const RawAddress& addr, uint8_t* lmp_version, - uint16_t* manufacturer, uint16_t* lmp_sub_version) { + std::function + body{[](const RawAddress& /* addr */, uint8_t* /* lmp_version */, + uint16_t* /* manufacturer */, uint16_t* /* lmp_sub_version */) { return false; }}; + bool operator()(const RawAddress& addr, uint8_t* lmp_version, uint16_t* manufacturer, + uint16_t* lmp_sub_version) { return body(addr, lmp_version, manufacturer, lmp_sub_version); - }; + } }; extern struct BTM_ReadRemoteVersion BTM_ReadRemoteVersion; // Name: BTM_is_sniff_allowed_for @@ -138,8 +130,8 @@ extern struct BTM_ReadRemoteVersion BTM_ReadRemoteVersion; // Returns: bool struct BTM_is_sniff_allowed_for { std::function body{ - [](const RawAddress& /* peer_addr */) { return false; }}; - bool operator()(const RawAddress& peer_addr) { return body(peer_addr); }; + [](const RawAddress& /* peer_addr */) { return false; }}; + bool operator()(const RawAddress& peer_addr) { return body(peer_addr); } }; extern struct BTM_is_sniff_allowed_for BTM_is_sniff_allowed_for; // Name: acl_send_data_packet_br_edr @@ -147,10 +139,8 @@ extern struct BTM_is_sniff_allowed_for BTM_is_sniff_allowed_for; // Returns: void struct acl_send_data_packet_br_edr { std::function body{ - [](const RawAddress& /* bd_addr */, BT_HDR* /* p_buf */) {}}; - void operator()(const RawAddress& bd_addr, BT_HDR* p_buf) { - return body(bd_addr, p_buf); - }; + [](const RawAddress& /* bd_addr */, BT_HDR* /* p_buf */) {}}; + void operator()(const RawAddress& bd_addr, BT_HDR* p_buf) { return body(bd_addr, p_buf); } }; extern struct acl_send_data_packet_br_edr acl_send_data_packet_br_edr; // Name: acl_create_le_connection @@ -158,22 +148,21 @@ extern struct acl_send_data_packet_br_edr acl_send_data_packet_br_edr; // Returns: bool struct acl_create_le_connection { std::function body{ - [](const RawAddress& /* bd_addr */) { return false; }}; - bool operator()(const RawAddress& bd_addr) { return body(bd_addr); }; + [](const RawAddress& /* bd_addr */) { return false; }}; + bool operator()(const RawAddress& bd_addr) { return body(bd_addr); } }; extern struct acl_create_le_connection acl_create_le_connection; // Name: acl_create_le_connection_with_id // Params: uint8_t id, const RawAddress& bd_addr // Returns: bool struct acl_create_le_connection_with_id { - std::function - body{[](uint8_t /* id */, const RawAddress& /* bd_addr */, - tBLE_ADDR_TYPE /* addr_type */) { return false; }}; - bool operator()(uint8_t id, const RawAddress& bd_addr, - tBLE_ADDR_TYPE addr_type) { + std::function body{ + [](uint8_t /* id */, const RawAddress& /* bd_addr */, tBLE_ADDR_TYPE /* addr_type */) { + return false; + }}; + bool operator()(uint8_t id, const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type) { return body(id, bd_addr, addr_type); - }; + } }; extern struct acl_create_le_connection_with_id acl_create_le_connection_with_id; // Name: acl_is_role_switch_allowed @@ -181,7 +170,7 @@ extern struct acl_create_le_connection_with_id acl_create_le_connection_with_id; // Returns: bool struct acl_is_role_switch_allowed { std::function body{[]() { return false; }}; - bool operator()() { return body(); }; + bool operator()() { return body(); } }; extern struct acl_is_role_switch_allowed acl_is_role_switch_allowed; // Name: acl_is_switch_role_idle @@ -189,30 +178,26 @@ extern struct acl_is_role_switch_allowed acl_is_role_switch_allowed; // Returns: bool struct acl_is_switch_role_idle { std::function body{ - [](const RawAddress& /* bd_addr */, tBT_TRANSPORT /* transport */) { - return false; - }}; + [](const RawAddress& /* bd_addr */, tBT_TRANSPORT /* transport */) { return false; }}; bool operator()(const RawAddress& bd_addr, tBT_TRANSPORT transport) { return body(bd_addr, transport); - }; + } }; extern struct acl_is_switch_role_idle acl_is_switch_role_idle; // Name: acl_peer_supports_ble_2m_phy // Params: uint16_t hci_handle // Returns: bool struct acl_peer_supports_ble_2m_phy { - std::function body{ - [](uint16_t /* hci_handle */) { return false; }}; - bool operator()(uint16_t hci_handle) { return body(hci_handle); }; + std::function body{[](uint16_t /* hci_handle */) { return false; }}; + bool operator()(uint16_t hci_handle) { return body(hci_handle); } }; extern struct acl_peer_supports_ble_2m_phy acl_peer_supports_ble_2m_phy; // Name: acl_peer_supports_ble_coded_phy // Params: uint16_t hci_handle // Returns: bool struct acl_peer_supports_ble_coded_phy { - std::function body{ - [](uint16_t /* hci_handle */) { return false; }}; - bool operator()(uint16_t hci_handle) { return body(hci_handle); }; + std::function body{[](uint16_t /* hci_handle */) { return false; }}; + bool operator()(uint16_t hci_handle) { return body(hci_handle); } }; extern struct acl_peer_supports_ble_coded_phy acl_peer_supports_ble_coded_phy; // Name: acl_peer_supports_ble_connection_parameters_request @@ -220,90 +205,79 @@ extern struct acl_peer_supports_ble_coded_phy acl_peer_supports_ble_coded_phy; // Returns: bool struct acl_peer_supports_ble_connection_parameters_request { std::function body{ - [](const RawAddress& /* remote_bda */) { return false; }}; - bool operator()(const RawAddress& remote_bda) { return body(remote_bda); }; + [](const RawAddress& /* remote_bda */) { return false; }}; + bool operator()(const RawAddress& remote_bda) { return body(remote_bda); } }; extern struct acl_peer_supports_ble_connection_parameters_request - acl_peer_supports_ble_connection_parameters_request; + acl_peer_supports_ble_connection_parameters_request; // Name: acl_peer_supports_ble_connection_parameters_request // Params: const RawAddress& remote_bda // Returns: bool struct acl_ble_connection_parameters_request { - std::function - body{[](uint16_t /* handle */, uint16_t /* conn_int_min */, - uint16_t /* conn_int_max */, uint16_t /* conn_latency */, - uint16_t /* conn_timeout */, uint16_t /* min_ce_len */, - uint16_t /* max_ce_len */) {}}; + body{[](uint16_t /* handle */, uint16_t /* conn_int_min */, uint16_t /* conn_int_max */, + uint16_t /* conn_latency */, uint16_t /* conn_timeout */, + uint16_t /* min_ce_len */, uint16_t /* max_ce_len */) {}}; void operator()(uint16_t handle, uint16_t conn_int_min, uint16_t conn_int_max, - uint16_t conn_latency, uint16_t conn_timeout, - uint16_t min_ce_len, uint16_t max_ce_len) { - body(handle, conn_int_min, conn_int_max, conn_latency, conn_timeout, - min_ce_len, max_ce_len); - }; -}; -extern struct acl_ble_connection_parameters_request - acl_ble_connection_parameters_request; + uint16_t conn_latency, uint16_t conn_timeout, uint16_t min_ce_len, + uint16_t max_ce_len) { + body(handle, conn_int_min, conn_int_max, conn_latency, conn_timeout, min_ce_len, max_ce_len); + } +}; +extern struct acl_ble_connection_parameters_request acl_ble_connection_parameters_request; // Name: acl_peer_supports_ble_packet_extension // Params: uint16_t hci_handle // Returns: bool struct acl_peer_supports_ble_packet_extension { - std::function body{ - [](uint16_t /* hci_handle */) { return false; }}; - bool operator()(uint16_t hci_handle) { return body(hci_handle); }; + std::function body{[](uint16_t /* hci_handle */) { return false; }}; + bool operator()(uint16_t hci_handle) { return body(hci_handle); } }; -extern struct acl_peer_supports_ble_packet_extension - acl_peer_supports_ble_packet_extension; +extern struct acl_peer_supports_ble_packet_extension acl_peer_supports_ble_packet_extension; // Name: acl_peer_supports_sniff_subrating // Params: const RawAddress& remote_bda // Returns: bool struct acl_peer_supports_sniff_subrating { std::function body{ - [](const RawAddress& /* remote_bda */) { return false; }}; - bool operator()(const RawAddress& remote_bda) { return body(remote_bda); }; + [](const RawAddress& /* remote_bda */) { return false; }}; + bool operator()(const RawAddress& remote_bda) { return body(remote_bda); } }; -extern struct acl_peer_supports_sniff_subrating - acl_peer_supports_sniff_subrating; +extern struct acl_peer_supports_sniff_subrating acl_peer_supports_sniff_subrating; // Name: acl_peer_supports_ble_connection_subrating // Params: const RawAddress& remote_bda // Returns: bool struct acl_peer_supports_ble_connection_subrating { std::function body{ - [](const RawAddress& /* remote_bda */) { return false; }}; - bool operator()(const RawAddress& remote_bda) { return body(remote_bda); }; + [](const RawAddress& /* remote_bda */) { return false; }}; + bool operator()(const RawAddress& remote_bda) { return body(remote_bda); } }; -extern struct acl_peer_supports_ble_connection_subrating - acl_peer_supports_ble_connection_subrating; +extern struct acl_peer_supports_ble_connection_subrating acl_peer_supports_ble_connection_subrating; // Name: acl_peer_supports_ble_connection_subrating_host // Params: const RawAddress& remote_bda // Returns: bool struct acl_peer_supports_ble_connection_subrating_host { std::function body{ - [](const RawAddress& /* remote_bda */) { return false; }}; - bool operator()(const RawAddress& remote_bda) { return body(remote_bda); }; + [](const RawAddress& /* remote_bda */) { return false; }}; + bool operator()(const RawAddress& remote_bda) { return body(remote_bda); } }; extern struct acl_peer_supports_ble_connection_subrating_host - acl_peer_supports_ble_connection_subrating_host; + acl_peer_supports_ble_connection_subrating_host; // Name: acl_refresh_remote_address // Params: const RawAddress& identity_address, tBLE_ADDR_TYPE // identity_address_type, const RawAddress& bda, tBLE_ADDR_TYPE rra_type, // const RawAddress& rpa Returns: bool struct acl_refresh_remote_address { - std::function - body{[](const RawAddress& /* identity_address */, - tBLE_ADDR_TYPE /* identity_address_type */, - const RawAddress& /* bda */, tBLE_RAND_ADDR_TYPE /* rra_type */, - const RawAddress& /* rpa */) { return false; }}; - bool operator()(const RawAddress& identity_address, - tBLE_ADDR_TYPE identity_address_type, const RawAddress& bda, - tBLE_RAND_ADDR_TYPE rra_type, const RawAddress& rpa) { + std::function + body{[](const RawAddress& /* identity_address */, + tBLE_ADDR_TYPE /* identity_address_type */, const RawAddress& /* bda */, + tBLE_RAND_ADDR_TYPE /* rra_type */, + const RawAddress& /* rpa */) { return false; }}; + bool operator()(const RawAddress& identity_address, tBLE_ADDR_TYPE identity_address_type, + const RawAddress& bda, tBLE_RAND_ADDR_TYPE rra_type, const RawAddress& rpa) { return body(identity_address, identity_address_type, bda, rra_type, rpa); - }; + } }; extern struct acl_refresh_remote_address acl_refresh_remote_address; // Name: acl_set_peer_le_features_from_handle @@ -311,126 +285,107 @@ extern struct acl_refresh_remote_address acl_refresh_remote_address; // Returns: bool struct acl_set_peer_le_features_from_handle { std::function body{ - [](uint16_t /* hci_handle */, const uint8_t* /* p */) { return false; }}; - bool operator()(uint16_t hci_handle, const uint8_t* p) { - return body(hci_handle, p); - }; + [](uint16_t /* hci_handle */, const uint8_t* /* p */) { return false; }}; + bool operator()(uint16_t hci_handle, const uint8_t* p) { return body(hci_handle, p); } }; -extern struct acl_set_peer_le_features_from_handle - acl_set_peer_le_features_from_handle; +extern struct acl_set_peer_le_features_from_handle acl_set_peer_le_features_from_handle; // Name: acl_get_connection_from_address // Params: const RawAddress& bd_addr, tBT_TRANSPORT transport // Returns: tACL_CONN* struct acl_get_connection_from_address { - std::function - body{[](const RawAddress& /* bd_addr */, tBT_TRANSPORT /* transport */) { - return nullptr; - }}; + std::function body{ + [](const RawAddress& /* bd_addr */, tBT_TRANSPORT /* transport */) { return nullptr; }}; tACL_CONN* operator()(const RawAddress& bd_addr, tBT_TRANSPORT transport) { return body(bd_addr, transport); - }; + } }; extern struct acl_get_connection_from_address acl_get_connection_from_address; // Name: btm_acl_for_bda // Params: const RawAddress& bd_addr, tBT_TRANSPORT transport // Returns: tACL_CONN* struct btm_acl_for_bda { - std::function - body{[](const RawAddress& /* bd_addr */, tBT_TRANSPORT /* transport */) { - return nullptr; - }}; + std::function body{ + [](const RawAddress& /* bd_addr */, tBT_TRANSPORT /* transport */) { return nullptr; }}; tACL_CONN* operator()(const RawAddress& bd_addr, tBT_TRANSPORT transport) { return body(bd_addr, transport); - }; + } }; extern struct btm_acl_for_bda btm_acl_for_bda; // Name: acl_get_connection_from_handle // Params: uint16_t handle // Returns: tACL_CONN* struct acl_get_connection_from_handle { - std::function body{ - [](uint16_t /* handle */) { return nullptr; }}; - tACL_CONN* operator()(uint16_t handle) { return body(handle); }; + std::function body{[](uint16_t /* handle */) { return nullptr; }}; + tACL_CONN* operator()(uint16_t handle) { return body(handle); } }; extern struct acl_get_connection_from_handle acl_get_connection_from_handle; // Name: BTM_GetLinkSuperTout // Params: const RawAddress& remote_bda, uint16_t* p_timeout // Returns: tBTM_STATUS struct BTM_GetLinkSuperTout { - std::function - body{[](const RawAddress& /* remote_bda */, uint16_t* /* p_timeout */) { - return 0; - }}; + std::function body{ + [](const RawAddress& /* remote_bda */, uint16_t* /* p_timeout */) { return 0; }}; tBTM_STATUS operator()(const RawAddress& remote_bda, uint16_t* p_timeout) { return body(remote_bda, p_timeout); - }; + } }; extern struct BTM_GetLinkSuperTout BTM_GetLinkSuperTout; // Name: BTM_GetRole // Params: const RawAddress& remote_bd_addr, tHCI_ROLE* p_role // Returns: tBTM_STATUS struct BTM_GetRole { - std::function - body{[](const RawAddress& /* remote_bd_addr */, tHCI_ROLE* /* p_role */) { - return 0; - }}; + std::function body{ + [](const RawAddress& /* remote_bd_addr */, tHCI_ROLE* /* p_role */) { return 0; }}; tBTM_STATUS operator()(const RawAddress& remote_bd_addr, tHCI_ROLE* p_role) { return body(remote_bd_addr, p_role); - }; + } }; extern struct BTM_GetRole BTM_GetRole; // Name: BTM_ReadFailedContactCounter // Params: const RawAddress& remote_bda, tBTM_CMPL_CB* p_cb // Returns: tBTM_STATUS struct BTM_ReadFailedContactCounter { - std::function - body{[](const RawAddress& /* remote_bda */, tBTM_CMPL_CB* /* p_cb */) { - return 0; - }}; + std::function body{ + [](const RawAddress& /* remote_bda */, tBTM_CMPL_CB* /* p_cb */) { return 0; }}; tBTM_STATUS operator()(const RawAddress& remote_bda, tBTM_CMPL_CB* p_cb) { return body(remote_bda, p_cb); - }; + } }; extern struct BTM_ReadFailedContactCounter BTM_ReadFailedContactCounter; // Name: BTM_ReadRSSI // Params: const RawAddress& remote_bda, tBTM_CMPL_CB* p_cb // Returns: tBTM_STATUS struct BTM_ReadRSSI { - std::function - body{[](const RawAddress& /* remote_bda */, tBTM_CMPL_CB* /* p_cb */) { - return 0; - }}; + std::function body{ + [](const RawAddress& /* remote_bda */, tBTM_CMPL_CB* /* p_cb */) { return 0; }}; tBTM_STATUS operator()(const RawAddress& remote_bda, tBTM_CMPL_CB* p_cb) { return body(remote_bda, p_cb); - }; + } }; extern struct BTM_ReadRSSI BTM_ReadRSSI; // Name: BTM_ReadTxPower // Params: const RawAddress& remote_bda, tBT_TRANSPORT transport, // tBTM_CMPL_CB* p_cb Returns: tBTM_STATUS struct BTM_ReadTxPower { - std::function - body{[](const RawAddress& /* remote_bda */, tBT_TRANSPORT /* transport */, - tBTM_CMPL_CB* /* p_cb */) { return BT_TRANSPORT_BR_EDR; }}; + std::function + body{[](const RawAddress& /* remote_bda */, tBT_TRANSPORT /* transport */, + tBTM_CMPL_CB* /* p_cb */) { return BT_TRANSPORT_BR_EDR; }}; tBTM_STATUS operator()(const RawAddress& remote_bda, tBT_TRANSPORT transport, tBTM_CMPL_CB* p_cb) { return body(remote_bda, transport, p_cb); - }; + } }; extern struct BTM_ReadTxPower BTM_ReadTxPower; // Name: BTM_SetLinkSuperTout // Params: const RawAddress& remote_bda, uint16_t timeout // Returns: tBTM_STATUS struct BTM_SetLinkSuperTout { - std::function - body{[](const RawAddress& /* remote_bda */, uint16_t /* timeout */) { - return 0; - }}; + std::function body{ + [](const RawAddress& /* remote_bda */, uint16_t /* timeout */) { return 0; }}; tBTM_STATUS operator()(const RawAddress& remote_bda, uint16_t timeout) { return body(remote_bda, timeout); - }; + } }; extern struct BTM_SetLinkSuperTout BTM_SetLinkSuperTout; // Name: BTM_SwitchRoleToCentral @@ -438,23 +393,21 @@ extern struct BTM_SetLinkSuperTout BTM_SetLinkSuperTout; // Returns: tBTM_STATUS struct BTM_SwitchRoleToCentral { std::function body{ - [](const RawAddress& /* remote_bd_addr */) { return 0; }}; - tBTM_STATUS operator()(const RawAddress& remote_bd_addr) { - return body(remote_bd_addr); - }; + [](const RawAddress& /* remote_bd_addr */) { return 0; }}; + tBTM_STATUS operator()(const RawAddress& remote_bd_addr) { return body(remote_bd_addr); } }; extern struct BTM_SwitchRoleToCentral BTM_SwitchRoleToCentral; // Name: btm_remove_acl // Params: const RawAddress& bd_addr, tBT_TRANSPORT transport // Returns: tBTM_STATUS struct btm_remove_acl { - std::function - body{[](const RawAddress& /* bd_addr */, tBT_TRANSPORT /* transport */) { - return BT_TRANSPORT_BR_EDR; - }}; + std::function body{ + [](const RawAddress& /* bd_addr */, tBT_TRANSPORT /* transport */) { + return BT_TRANSPORT_BR_EDR; + }}; tBTM_STATUS operator()(const RawAddress& bd_addr, tBT_TRANSPORT transport) { return body(bd_addr, transport); - }; + } }; extern struct btm_remove_acl btm_remove_acl; // Name: btm_get_acl_disc_reason_code @@ -462,7 +415,7 @@ extern struct btm_remove_acl btm_remove_acl; // Returns: tHCI_REASON struct btm_get_acl_disc_reason_code { std::function body{[](void) { return HCI_SUCCESS; }}; - tHCI_REASON operator()(void) { return body(); }; + tHCI_REASON operator()(void) { return body(); } }; extern struct btm_get_acl_disc_reason_code btm_get_acl_disc_reason_code; // Name: btm_is_acl_locally_initiated @@ -470,19 +423,20 @@ extern struct btm_get_acl_disc_reason_code btm_get_acl_disc_reason_code; // Returns: bool struct btm_is_acl_locally_initiated { std::function body{[](void) { return true; }}; - bool operator()(void) { return body(); }; + bool operator()(void) { return body(); } }; extern struct btm_is_acl_locally_initiated btm_is_acl_locally_initiated; // Name: BTM_GetHCIConnHandle // Params: const RawAddress& remote_bda, tBT_TRANSPORT transport // Returns: uint16_t struct BTM_GetHCIConnHandle { - std::function - body{[](const RawAddress& /* remote_bda */, - tBT_TRANSPORT /* transport */) { return BT_TRANSPORT_BR_EDR; }}; + std::function body{ + [](const RawAddress& /* remote_bda */, tBT_TRANSPORT /* transport */) { + return BT_TRANSPORT_BR_EDR; + }}; uint16_t operator()(const RawAddress& remote_bda, tBT_TRANSPORT transport) { return body(remote_bda, transport); - }; + } }; extern struct BTM_GetHCIConnHandle BTM_GetHCIConnHandle; // Name: BTM_GetMaxPacketSize @@ -490,8 +444,8 @@ extern struct BTM_GetHCIConnHandle BTM_GetHCIConnHandle; // Returns: uint16_t struct BTM_GetMaxPacketSize { std::function body{ - [](const RawAddress& /* addr */) { return 0; }}; - uint16_t operator()(const RawAddress& addr) { return body(addr); }; + [](const RawAddress& /* addr */) { return 0; }}; + uint16_t operator()(const RawAddress& addr) { return body(addr); } }; extern struct BTM_GetMaxPacketSize BTM_GetMaxPacketSize; // Name: BTM_GetNumAclLinks @@ -499,7 +453,7 @@ extern struct BTM_GetMaxPacketSize BTM_GetMaxPacketSize; // Returns: uint16_t struct BTM_GetNumAclLinks { std::function body{[](void) { return 0; }}; - uint16_t operator()(void) { return body(); }; + uint16_t operator()(void) { return body(); } }; extern struct BTM_GetNumAclLinks BTM_GetNumAclLinks; // Name: acl_get_supported_packet_types @@ -507,37 +461,36 @@ extern struct BTM_GetNumAclLinks BTM_GetNumAclLinks; // Returns: uint16_t struct acl_get_supported_packet_types { std::function body{[]() { return 0; }}; - uint16_t operator()() { return body(); }; + uint16_t operator()() { return body(); } }; extern struct acl_get_supported_packet_types acl_get_supported_packet_types; // Name: BTM_GetPeerSCA // Params: const RawAddress& remote_bda, tBT_TRANSPORT transport // Returns: uint8_t struct BTM_GetPeerSCA { - std::function - body{[](const RawAddress& /* remote_bda */, - tBT_TRANSPORT /* transport */) { return BT_TRANSPORT_BR_EDR; }}; + std::function body{ + [](const RawAddress& /* remote_bda */, tBT_TRANSPORT /* transport */) { + return BT_TRANSPORT_BR_EDR; + }}; uint8_t operator()(const RawAddress& remote_bda, tBT_TRANSPORT transport) { return body(remote_bda, transport); - }; + } }; extern struct BTM_GetPeerSCA BTM_GetPeerSCA; // Name: acl_link_role_from_handle // Params: uint16_t handle // Returns: uint8_t struct acl_link_role_from_handle { - std::function body{ - [](uint16_t /* handle */) { return 0; }}; - uint8_t operator()(uint16_t handle) { return body(handle); }; + std::function body{[](uint16_t /* handle */) { return 0; }}; + uint8_t operator()(uint16_t handle) { return body(handle); } }; extern struct acl_link_role_from_handle acl_link_role_from_handle; // Name: btm_handle_to_acl_index // Params: uint16_t hci_handle // Returns: uint8_t struct btm_handle_to_acl_index { - std::function body{ - [](uint16_t /* hci_handle */) { return 0; }}; - uint8_t operator()(uint16_t hci_handle) { return body(hci_handle); }; + std::function body{[](uint16_t /* hci_handle */) { return 0; }}; + uint8_t operator()(uint16_t hci_handle) { return body(hci_handle); } }; extern struct btm_handle_to_acl_index btm_handle_to_acl_index; // Name: BTM_ReadRemoteFeatures @@ -545,8 +498,8 @@ extern struct btm_handle_to_acl_index btm_handle_to_acl_index; // Returns: uint8_t* struct BTM_ReadRemoteFeatures { std::function body{ - [](const RawAddress& /* addr */) { return nullptr; }}; - uint8_t* operator()(const RawAddress& addr) { return body(addr); }; + [](const RawAddress& /* addr */) { return nullptr; }}; + uint8_t* operator()(const RawAddress& addr) { return body(addr); } }; extern struct BTM_ReadRemoteFeatures BTM_ReadRemoteFeatures; // Name: ACL_RegisterClient @@ -554,8 +507,8 @@ extern struct BTM_ReadRemoteFeatures BTM_ReadRemoteFeatures; // Returns: void struct ACL_RegisterClient { std::function body{ - [](struct acl_client_callback_s* /* callbacks */) { ; }}; - void operator()(struct acl_client_callback_s* callbacks) { body(callbacks); }; + [](struct acl_client_callback_s* /* callbacks */) { ; }}; + void operator()(struct acl_client_callback_s* callbacks) { body(callbacks); } }; extern struct ACL_RegisterClient ACL_RegisterClient; // Name: ACL_UnregisterClient @@ -563,8 +516,8 @@ extern struct ACL_RegisterClient ACL_RegisterClient; // Returns: void struct ACL_UnregisterClient { std::function body{ - [](struct acl_client_callback_s* /* callbacks */) { ; }}; - void operator()(struct acl_client_callback_s* callbacks) { body(callbacks); }; + [](struct acl_client_callback_s* /* callbacks */) { ; }}; + void operator()(struct acl_client_callback_s* callbacks) { body(callbacks); } }; extern struct ACL_UnregisterClient ACL_UnregisterClient; // Name: BTM_ReadConnectionAddr @@ -573,32 +526,30 @@ extern struct ACL_UnregisterClient ACL_UnregisterClient; struct BTM_ReadConnectionAddr { std::function - body{[](const RawAddress& /* remote_bda */, - RawAddress& /* local_conn_addr */, - tBLE_ADDR_TYPE* /* p_addr_type */, bool /* ota_address */) { ; }}; + body{[](const RawAddress& /* remote_bda */, RawAddress& /* local_conn_addr */, + tBLE_ADDR_TYPE* /* p_addr_type */, bool /* ota_address */) { ; }}; void operator()(const RawAddress& remote_bda, RawAddress& local_conn_addr, tBLE_ADDR_TYPE* p_addr_type, bool ota_address) { body(remote_bda, local_conn_addr, p_addr_type, ota_address); - }; + } }; extern struct BTM_ReadConnectionAddr BTM_ReadConnectionAddr; // Name: BTM_RequestPeerSCA // Params: const RawAddress& remote_bda, tBT_TRANSPORT transport // Returns: void struct BTM_RequestPeerSCA { - std::function - body{[](const RawAddress& /* remote_bda */, - tBT_TRANSPORT /* transport */) { ; }}; + std::function body{ + [](const RawAddress& /* remote_bda */, tBT_TRANSPORT /* transport */) { ; }}; void operator()(const RawAddress& remote_bda, tBT_TRANSPORT transport) { body(remote_bda, transport); - }; + } }; extern struct BTM_RequestPeerSCA BTM_RequestPeerSCA; // Name: BTM_acl_after_controller_started // Returns: void struct BTM_acl_after_controller_started { std::function body{[]() { ; }}; - void operator()() { body(); }; + void operator()() { body(); } }; extern struct BTM_acl_after_controller_started BTM_acl_after_controller_started; // Name: BTM_block_role_switch_for @@ -606,8 +557,8 @@ extern struct BTM_acl_after_controller_started BTM_acl_after_controller_started; // Returns: void struct BTM_block_role_switch_for { std::function body{ - [](const RawAddress& /* peer_addr */) { ; }}; - void operator()(const RawAddress& peer_addr) { body(peer_addr); }; + [](const RawAddress& /* peer_addr */) { ; }}; + void operator()(const RawAddress& peer_addr) { body(peer_addr); } }; extern struct BTM_block_role_switch_for BTM_block_role_switch_for; // Name: BTM_block_sniff_mode_for @@ -615,8 +566,8 @@ extern struct BTM_block_role_switch_for BTM_block_role_switch_for; // Returns: void struct BTM_block_sniff_mode_for { std::function body{ - [](const RawAddress& /* peer_addr */) { ; }}; - void operator()(const RawAddress& peer_addr) { body(peer_addr); }; + [](const RawAddress& /* peer_addr */) { ; }}; + void operator()(const RawAddress& peer_addr) { body(peer_addr); } }; extern struct BTM_block_sniff_mode_for BTM_block_sniff_mode_for; // Name: BTM_default_unblock_role_switch @@ -624,7 +575,7 @@ extern struct BTM_block_sniff_mode_for BTM_block_sniff_mode_for; // Returns: void struct BTM_default_unblock_role_switch { std::function body{[]() { ; }}; - void operator()() { body(); }; + void operator()() { body(); } }; extern struct BTM_default_unblock_role_switch BTM_default_unblock_role_switch; // Name: BTM_unblock_role_switch_for @@ -632,8 +583,8 @@ extern struct BTM_default_unblock_role_switch BTM_default_unblock_role_switch; // Returns: void struct BTM_unblock_role_switch_for { std::function body{ - [](const RawAddress& /* peer_addr */) { ; }}; - void operator()(const RawAddress& peer_addr) { body(peer_addr); }; + [](const RawAddress& /* peer_addr */) { ; }}; + void operator()(const RawAddress& peer_addr) { body(peer_addr); } }; extern struct BTM_unblock_role_switch_for BTM_unblock_role_switch_for; // Name: BTM_unblock_sniff_mode_for @@ -641,34 +592,32 @@ extern struct BTM_unblock_role_switch_for BTM_unblock_role_switch_for; // Returns: void struct BTM_unblock_sniff_mode_for { std::function body{ - [](const RawAddress& /* peer_addr */) { ; }}; - void operator()(const RawAddress& peer_addr) { body(peer_addr); }; + [](const RawAddress& /* peer_addr */) { ; }}; + void operator()(const RawAddress& peer_addr) { body(peer_addr); } }; extern struct BTM_unblock_sniff_mode_for BTM_unblock_sniff_mode_for; // Name: acl_disconnect_after_role_switch // Params: uint16_t conn_handle, tHCI_STATUS reason // Returns: void struct acl_disconnect_after_role_switch { - std::function - body{[](uint16_t /* conn_handle */, tHCI_STATUS /* reason */, - std::string /* comment */) { ; }}; - void operator()(uint16_t conn_handle, tHCI_STATUS reason, - std::string comment) { + std::function body{ + [](uint16_t /* conn_handle */, tHCI_STATUS /* reason */, std::string /* comment */) { + ; + }}; + void operator()(uint16_t conn_handle, tHCI_STATUS reason, std::string comment) { body(conn_handle, reason, comment); - }; + } }; extern struct acl_disconnect_after_role_switch acl_disconnect_after_role_switch; // Name: acl_disconnect_from_handle // Params: uint16_t handle, tHCI_STATUS reason // Returns: void struct acl_disconnect_from_handle { - std::function - body{[](uint16_t /* handle */, tHCI_STATUS /* reason */, - std::string /* comment */) { ; }}; + std::function body{ + [](uint16_t /* handle */, tHCI_STATUS /* reason */, std::string /* comment */) { ; }}; void operator()(uint16_t handle, tHCI_STATUS reason, std::string comment) { body(handle, reason, comment); - }; + } }; extern struct acl_disconnect_from_handle acl_disconnect_from_handle; // Name: acl_packets_completed @@ -676,22 +625,22 @@ extern struct acl_disconnect_from_handle acl_disconnect_from_handle; // Returns: void struct acl_packets_completed { std::function body{ - [](uint16_t /* handle */, uint16_t /* credits */) { ; }}; - void operator()(uint16_t handle, uint16_t credits) { body(handle, credits); }; + [](uint16_t /* handle */, uint16_t /* credits */) { ; }}; + void operator()(uint16_t handle, uint16_t credits) { body(handle, credits); } }; extern struct acl_packets_completed acl_packets_completed; // Name: acl_process_extended_features // Params: uint16_t handle, uint8_t current_page_number, uint8_t // max_page_number, uint64_t features Returns: void struct acl_process_extended_features { - std::function - body{[](uint16_t /* handle */, uint8_t /* current_page_number */, - uint8_t /* max_page_number */, uint64_t /* features */) { ; }}; - void operator()(uint16_t handle, uint8_t current_page_number, - uint8_t max_page_number, uint64_t features) { + std::function + body{[](uint16_t /* handle */, uint8_t /* current_page_number */, + uint8_t /* max_page_number */, uint64_t /* features */) { ; }}; + void operator()(uint16_t handle, uint8_t current_page_number, uint8_t max_page_number, + uint64_t features) { body(handle, current_page_number, max_page_number, features); - }; + } }; extern struct acl_process_extended_features acl_process_extended_features; // Name: acl_process_supported_features @@ -699,10 +648,8 @@ extern struct acl_process_extended_features acl_process_extended_features; // Returns: void struct acl_process_supported_features { std::function body{ - [](uint16_t /* handle */, uint64_t /* features */) { ; }}; - void operator()(uint16_t handle, uint64_t features) { - body(handle, features); - }; + [](uint16_t /* handle */, uint64_t /* features */) { ; }}; + void operator()(uint16_t handle, uint64_t features) { body(handle, features); } }; extern struct acl_process_supported_features acl_process_supported_features; // Name: acl_rcv_acl_data @@ -710,7 +657,7 @@ extern struct acl_process_supported_features acl_process_supported_features; // Returns: void struct acl_rcv_acl_data { std::function body{[](BT_HDR* /* p_msg */) { ; }}; - void operator()(BT_HDR* p_msg) { body(p_msg); }; + void operator()(BT_HDR* p_msg) { body(p_msg); } }; extern struct acl_rcv_acl_data acl_rcv_acl_data; // Name: acl_send_data_packet_ble @@ -718,10 +665,8 @@ extern struct acl_rcv_acl_data acl_rcv_acl_data; // Returns: void struct acl_send_data_packet_ble { std::function body{ - [](const RawAddress& /* bd_addr */, BT_HDR* /* p_buf */) { ; }}; - void operator()(const RawAddress& bd_addr, BT_HDR* p_buf) { - body(bd_addr, p_buf); - }; + [](const RawAddress& /* bd_addr */, BT_HDR* /* p_buf */) { ; }}; + void operator()(const RawAddress& bd_addr, BT_HDR* p_buf) { body(bd_addr, p_buf); } }; extern struct acl_send_data_packet_ble acl_send_data_packet_ble; // Name: acl_set_disconnect_reason @@ -729,64 +674,56 @@ extern struct acl_send_data_packet_ble acl_send_data_packet_ble; // Returns: void struct acl_set_disconnect_reason { std::function body{ - [](tHCI_STATUS /* acl_disc_reason */) { ; }}; - void operator()(tHCI_STATUS acl_disc_reason) { body(acl_disc_reason); }; + [](tHCI_STATUS /* acl_disc_reason */) { ; }}; + void operator()(tHCI_STATUS acl_disc_reason) { body(acl_disc_reason); } }; extern struct acl_set_disconnect_reason acl_set_disconnect_reason; // Name: acl_write_automatic_flush_timeout // Params: const RawAddress& bd_addr, uint16_t flush_timeout_in_ticks // Returns: void struct acl_write_automatic_flush_timeout { - std::function - body{[](const RawAddress& /* bd_addr */, - uint16_t /* flush_timeout_in_ticks */) { ; }}; + std::function body{ + [](const RawAddress& /* bd_addr */, uint16_t /* flush_timeout_in_ticks */) { ; }}; void operator()(const RawAddress& bd_addr, uint16_t flush_timeout_in_ticks) { body(bd_addr, flush_timeout_in_ticks); - }; + } }; -extern struct acl_write_automatic_flush_timeout - acl_write_automatic_flush_timeout; +extern struct acl_write_automatic_flush_timeout acl_write_automatic_flush_timeout; // Name: btm_acl_connected // Params: const RawAddress& bda, uint16_t handle, tHCI_STATUS status, uint8_t // enc_mode Returns: void struct btm_acl_connected { - std::function - body{[](const RawAddress& /* bda */, uint16_t /* handle */, - tHCI_STATUS /* status */, uint8_t /* enc_mode */) { ; }}; - void operator()(const RawAddress& bda, uint16_t handle, tHCI_STATUS status, - uint8_t enc_mode) { + std::function + body{[](const RawAddress& /* bda */, uint16_t /* handle */, tHCI_STATUS /* status */, + uint8_t /* enc_mode */) { ; }}; + void operator()(const RawAddress& bda, uint16_t handle, tHCI_STATUS status, uint8_t enc_mode) { body(bda, handle, status, enc_mode); - }; + } }; extern struct btm_acl_connected btm_acl_connected; // Name: btm_connection_request // Params: const RawAddress& bda, const bluetooth::hci::ClassOfDevice& cod // Returns: void struct btm_connection_request { - std::function - body{[](const RawAddress& /* bda */, - const bluetooth::hci::ClassOfDevice& /* cod */) { ; }}; - void operator()(const RawAddress& bda, - const bluetooth::hci::ClassOfDevice& cod) { + std::function body{ + [](const RawAddress& /* bda */, const bluetooth::hci::ClassOfDevice& /* cod */) { ; }}; + void operator()(const RawAddress& bda, const bluetooth::hci::ClassOfDevice& cod) { body(bda, cod); - }; + } }; extern struct btm_connection_request btm_connection_request; // Name: btm_acl_created // Params: const RawAddress& bda, uint16_t hci_handle, tHCI_ROLE link_role, // tBT_TRANSPORT transport Returns: void struct btm_acl_created { - std::function - body{[](const RawAddress& /* bda */, uint16_t /* hci_handle */, - tHCI_ROLE /* link_role */, tBT_TRANSPORT /* transport */) { ; }}; - void operator()(const RawAddress& bda, uint16_t hci_handle, - tHCI_ROLE link_role, tBT_TRANSPORT transport) { + std::function + body{[](const RawAddress& /* bda */, uint16_t /* hci_handle */, tHCI_ROLE /* link_role */, + tBT_TRANSPORT /* transport */) { ; }}; + void operator()(const RawAddress& bda, uint16_t hci_handle, tHCI_ROLE link_role, + tBT_TRANSPORT transport) { body(bda, hci_handle, link_role, transport); - }; + } }; extern struct btm_acl_created btm_acl_created; // Name: btm_acl_device_down @@ -794,40 +731,37 @@ extern struct btm_acl_created btm_acl_created; // Returns: void struct btm_acl_device_down { std::function body{[](void) { ; }}; - void operator()(void) { body(); }; + void operator()(void) { body(); } }; extern struct btm_acl_device_down btm_acl_device_down; // Name: btm_acl_disconnected // Params: tHCI_STATUS status, uint16_t handle, tHCI_REASON reason // Returns: void struct btm_acl_disconnected { - std::function - body{[](tHCI_STATUS /* status */, uint16_t /* handle */, - tHCI_REASON /* reason */) { ; }}; + std::function body{ + [](tHCI_STATUS /* status */, uint16_t /* handle */, tHCI_REASON /* reason */) { ; }}; void operator()(tHCI_STATUS status, uint16_t handle, tHCI_REASON reason) { body(status, handle, reason); - }; + } }; extern struct btm_acl_disconnected btm_acl_disconnected; // Name: btm_acl_encrypt_change // Params: uint16_t handle, uint8_t status, uint8_t encr_enable // Returns: void struct btm_acl_encrypt_change { - std::function - body{[](uint16_t /* handle */, uint8_t /* status */, - uint8_t /* encr_enable */) { ; }}; + std::function body{ + [](uint16_t /* handle */, uint8_t /* status */, uint8_t /* encr_enable */) { ; }}; void operator()(uint16_t handle, uint8_t status, uint8_t encr_enable) { body(handle, status, encr_enable); - }; + } }; extern struct btm_acl_encrypt_change btm_acl_encrypt_change; // Name: btm_acl_notif_conn_collision // Params: const RawAddress& bda // Returns: void struct btm_acl_notif_conn_collision { - std::function body{ - [](const RawAddress& /* bda */) { ; }}; - void operator()(const RawAddress& bda) { body(bda); }; + std::function body{[](const RawAddress& /* bda */) { ; }}; + void operator()(const RawAddress& bda) { body(bda); } }; extern struct btm_acl_notif_conn_collision btm_acl_notif_conn_collision; // Name: btm_acl_process_sca_cmpl_pkt @@ -835,8 +769,8 @@ extern struct btm_acl_notif_conn_collision btm_acl_notif_conn_collision; // Returns: void struct btm_acl_process_sca_cmpl_pkt { std::function body{ - [](uint8_t /* len */, uint8_t* /* data */) { ; }}; - void operator()(uint8_t len, uint8_t* data) { body(len, data); }; + [](uint8_t /* len */, uint8_t* /* data */) { ; }}; + void operator()(uint8_t len, uint8_t* data) { body(len, data); } }; extern struct btm_acl_process_sca_cmpl_pkt btm_acl_process_sca_cmpl_pkt; // Name: btm_acl_removed @@ -844,7 +778,7 @@ extern struct btm_acl_process_sca_cmpl_pkt btm_acl_process_sca_cmpl_pkt; // Returns: void struct btm_acl_removed { std::function body{[](uint16_t /* handle */) { ; }}; - void operator()(uint16_t handle) { body(handle); }; + void operator()(uint16_t handle) { body(handle); } }; extern struct btm_acl_removed btm_acl_removed; // Name: btm_acl_flush @@ -852,21 +786,19 @@ extern struct btm_acl_removed btm_acl_removed; // Returns: void struct btm_acl_flush { std::function body{[](uint16_t /* handle */) { ; }}; - void operator()(uint16_t handle) { body(handle); }; + void operator()(uint16_t handle) { body(handle); } }; extern struct btm_acl_flush btm_acl_flush; // Name: btm_acl_role_changed // Params: tHCI_STATUS hci_status, const RawAddress& bd_addr, tHCI_ROLE // new_role Returns: void struct btm_acl_role_changed { - std::function - body{[](tHCI_STATUS /* hci_status */, const RawAddress& /* bd_addr */, - tHCI_ROLE /* new_role */) { ; }}; - void operator()(tHCI_STATUS hci_status, const RawAddress& bd_addr, - tHCI_ROLE new_role) { + std::function body{ + [](tHCI_STATUS /* hci_status */, const RawAddress& /* bd_addr */, + tHCI_ROLE /* new_role */) { ; }}; + void operator()(tHCI_STATUS hci_status, const RawAddress& bd_addr, tHCI_ROLE new_role) { body(hci_status, bd_addr, new_role); - }; + } }; extern struct btm_acl_role_changed btm_acl_role_changed; // Name: btm_acl_update_conn_addr @@ -874,33 +806,28 @@ extern struct btm_acl_role_changed btm_acl_role_changed; // Returns: void struct btm_acl_update_conn_addr { std::function body{ - [](uint16_t /* handle */, const RawAddress& /* address */) { ; }}; - void operator()(uint16_t handle, const RawAddress& address) { - body(handle, address); - }; + [](uint16_t /* handle */, const RawAddress& /* address */) { ; }}; + void operator()(uint16_t handle, const RawAddress& address) { body(handle, address); } }; extern struct btm_acl_update_conn_addr btm_acl_update_conn_addr; // Name: btm_ble_refresh_local_resolvable_private_addr // Params: const RawAddress& pseudo_addr, const RawAddress& local_rpa // Returns: void struct btm_ble_refresh_local_resolvable_private_addr { - std::function - body{[](const RawAddress& /* pseudo_addr */, - const RawAddress& /* local_rpa */) { ; }}; + std::function body{ + [](const RawAddress& /* pseudo_addr */, const RawAddress& /* local_rpa */) { ; }}; void operator()(const RawAddress& pseudo_addr, const RawAddress& local_rpa) { body(pseudo_addr, local_rpa); - }; + } }; extern struct btm_ble_refresh_local_resolvable_private_addr - btm_ble_refresh_local_resolvable_private_addr; + btm_ble_refresh_local_resolvable_private_addr; // Name: btm_cont_rswitch_from_handle // Params: uint16_t hci_handle // Returns: void struct btm_cont_rswitch_from_handle { - std::function body{ - [](uint16_t /* hci_handle */) { ; }}; - void operator()(uint16_t hci_handle) { body(hci_handle); }; + std::function body{[](uint16_t /* hci_handle */) { ; }}; + void operator()(uint16_t hci_handle) { body(hci_handle); } }; extern struct btm_cont_rswitch_from_handle btm_cont_rswitch_from_handle; // Name: btm_establish_continue_from_address @@ -908,126 +835,108 @@ extern struct btm_cont_rswitch_from_handle btm_cont_rswitch_from_handle; // Returns: void struct btm_establish_continue_from_address { std::function body{ - [](const RawAddress& /* bda */, tBT_TRANSPORT /* transport */) { ; }}; - void operator()(const RawAddress& bda, tBT_TRANSPORT transport) { - body(bda, transport); - }; + [](const RawAddress& /* bda */, tBT_TRANSPORT /* transport */) { ; }}; + void operator()(const RawAddress& bda, tBT_TRANSPORT transport) { body(bda, transport); } }; -extern struct btm_establish_continue_from_address - btm_establish_continue_from_address; +extern struct btm_establish_continue_from_address btm_establish_continue_from_address; // Name: btm_process_remote_ext_features // Params: tACL_CONN* p_acl_cb, uint8_t max_page_number // Returns: void struct btm_process_remote_ext_features { std::function body{ - [](tACL_CONN* /* p_acl_cb */, uint8_t /* max_page_number */) { ; }}; - void operator()(tACL_CONN* p_acl_cb, uint8_t max_page_number) { - body(p_acl_cb, max_page_number); - }; + [](tACL_CONN* /* p_acl_cb */, uint8_t /* max_page_number */) { ; }}; + void operator()(tACL_CONN* p_acl_cb, uint8_t max_page_number) { body(p_acl_cb, max_page_number); } }; extern struct btm_process_remote_ext_features btm_process_remote_ext_features; // Name: btm_process_remote_version_complete // Params: uint8_t status, uint16_t handle, uint8_t lmp_version, uint16_t // manufacturer, uint16_t lmp_subversion Returns: void struct btm_process_remote_version_complete { - std::function - body{[](uint8_t /* status */, uint16_t /* handle */, - uint8_t /* lmp_version */, uint16_t /* manufacturer */, - uint16_t /* lmp_subversion */) { ; }}; - void operator()(uint8_t status, uint16_t handle, uint8_t lmp_version, - uint16_t manufacturer, uint16_t lmp_subversion) { + std::function + body{[](uint8_t /* status */, uint16_t /* handle */, uint8_t /* lmp_version */, + uint16_t /* manufacturer */, uint16_t /* lmp_subversion */) { ; }}; + void operator()(uint8_t status, uint16_t handle, uint8_t lmp_version, uint16_t manufacturer, + uint16_t lmp_subversion) { body(status, handle, lmp_version, manufacturer, lmp_subversion); - }; + } }; -extern struct btm_process_remote_version_complete - btm_process_remote_version_complete; +extern struct btm_process_remote_version_complete btm_process_remote_version_complete; // Name: btm_read_automatic_flush_timeout_complete // Params: uint8_t* p // Returns: void struct btm_read_automatic_flush_timeout_complete { std::function body{[](uint8_t* /* p */) { ; }}; - void operator()(uint8_t* p) { body(p); }; + void operator()(uint8_t* p) { body(p); } }; -extern struct btm_read_automatic_flush_timeout_complete - btm_read_automatic_flush_timeout_complete; +extern struct btm_read_automatic_flush_timeout_complete btm_read_automatic_flush_timeout_complete; // Name: btm_read_failed_contact_counter_complete // Params: uint8_t* p // Returns: void struct btm_read_failed_contact_counter_complete { std::function body{[](uint8_t* /* p */) { ; }}; - void operator()(uint8_t* p) { body(p); }; + void operator()(uint8_t* p) { body(p); } }; -extern struct btm_read_failed_contact_counter_complete - btm_read_failed_contact_counter_complete; +extern struct btm_read_failed_contact_counter_complete btm_read_failed_contact_counter_complete; // Name: btm_read_failed_contact_counter_timeout // Params: void* data // Returns: void struct btm_read_failed_contact_counter_timeout { std::function body{[](void* /* data */) { ; }}; - void operator()(void* data) { body(data); }; + void operator()(void* data) { body(data); } }; -extern struct btm_read_failed_contact_counter_timeout - btm_read_failed_contact_counter_timeout; +extern struct btm_read_failed_contact_counter_timeout btm_read_failed_contact_counter_timeout; // Name: btm_read_remote_ext_features // Params: uint16_t handle, uint8_t page_number // Returns: void struct btm_read_remote_ext_features { std::function body{ - [](uint16_t /* handle */, uint8_t /* page_number */) { ; }}; - void operator()(uint16_t handle, uint8_t page_number) { - body(handle, page_number); - }; + [](uint16_t /* handle */, uint8_t /* page_number */) { ; }}; + void operator()(uint16_t handle, uint8_t page_number) { body(handle, page_number); } }; extern struct btm_read_remote_ext_features btm_read_remote_ext_features; // Name: btm_read_remote_ext_features_complete // Params: uint16_t handle, uint8_t page_num, uint8_t max_page, uint8_t* // features Returns: void struct btm_read_remote_ext_features_complete { - std::function - body{[](uint16_t /* handle */, uint8_t /* page_num */, - uint8_t /* max_page */, uint8_t* /* features */) { ; }}; - void operator()(uint16_t handle, uint8_t page_num, uint8_t max_page, - uint8_t* features) { + std::function body{ + [](uint16_t /* handle */, uint8_t /* page_num */, uint8_t /* max_page */, + uint8_t* /* features */) { ; }}; + void operator()(uint16_t handle, uint8_t page_num, uint8_t max_page, uint8_t* features) { body(handle, page_num, max_page, features); - }; + } }; -extern struct btm_read_remote_ext_features_complete - btm_read_remote_ext_features_complete; +extern struct btm_read_remote_ext_features_complete btm_read_remote_ext_features_complete; // Name: btm_read_remote_ext_features_complete_raw // Params: uint8_t* p, uint8_t evt_len // Returns: void struct btm_read_remote_ext_features_complete_raw { std::function body{ - [](uint8_t* /* p */, uint8_t /* evt_len */) { ; }}; - void operator()(uint8_t* p, uint8_t evt_len) { body(p, evt_len); }; + [](uint8_t* /* p */, uint8_t /* evt_len */) { ; }}; + void operator()(uint8_t* p, uint8_t evt_len) { body(p, evt_len); } }; -extern struct btm_read_remote_ext_features_complete_raw - btm_read_remote_ext_features_complete_raw; +extern struct btm_read_remote_ext_features_complete_raw btm_read_remote_ext_features_complete_raw; // Name: btm_read_remote_ext_features_failed // Params: uint8_t status, uint16_t handle // Returns: void struct btm_read_remote_ext_features_failed { std::function body{ - [](uint8_t /* status */, uint16_t /* handle */) { ; }}; - void operator()(uint8_t status, uint16_t handle) { body(status, handle); }; + [](uint8_t /* status */, uint16_t /* handle */) { ; }}; + void operator()(uint8_t status, uint16_t handle) { body(status, handle); } }; -extern struct btm_read_remote_ext_features_failed - btm_read_remote_ext_features_failed; +extern struct btm_read_remote_ext_features_failed btm_read_remote_ext_features_failed; // Name: btm_read_remote_version_complete // Params: tHCI_STATUS status, uint16_t handle, uint8_t lmp_version, uint16_t // manufacturer, uint16_t lmp_subversion Returns: void struct btm_read_remote_version_complete { std::function - body{[](tHCI_STATUS /* status */, uint16_t /* handle */, - uint8_t /* lmp_version */, uint16_t /* manufacturer */, - uint16_t /* lmp_subversion */) { ; }}; - void operator()(tHCI_STATUS status, uint16_t handle, uint8_t lmp_version, - uint16_t manufacturer, uint16_t lmp_subversion) { + body{[](tHCI_STATUS /* status */, uint16_t /* handle */, uint8_t /* lmp_version */, + uint16_t /* manufacturer */, uint16_t /* lmp_subversion */) { ; }}; + void operator()(tHCI_STATUS status, uint16_t handle, uint8_t lmp_version, uint16_t manufacturer, + uint16_t lmp_subversion) { body(status, handle, lmp_version, manufacturer, lmp_subversion); - }; + } }; extern struct btm_read_remote_version_complete btm_read_remote_version_complete; // Name: btm_read_rssi_complete @@ -1035,8 +944,8 @@ extern struct btm_read_remote_version_complete btm_read_remote_version_complete; // Returns: void struct btm_read_rssi_complete { std::function body{ - [](uint8_t* /* pm */, uint16_t /* evt_len */) { ; }}; - void operator()(uint8_t* p, uint16_t evt_len) { body(p, evt_len); }; + [](uint8_t* /* pm */, uint16_t /* evt_len */) { ; }}; + void operator()(uint8_t* p, uint16_t evt_len) { body(p, evt_len); } }; extern struct btm_read_rssi_complete btm_read_rssi_complete; // Name: btm_read_rssi_timeout @@ -1044,7 +953,7 @@ extern struct btm_read_rssi_complete btm_read_rssi_complete; // Returns: void struct btm_read_rssi_timeout { std::function body{[](void* /* data */) { ; }}; - void operator()(void* data) { body(data); }; + void operator()(void* data) { body(data); } }; extern struct btm_read_rssi_timeout btm_read_rssi_timeout; // Name: btm_read_tx_power_complete @@ -1052,10 +961,8 @@ extern struct btm_read_rssi_timeout btm_read_rssi_timeout; // Returns: void struct btm_read_tx_power_complete { std::function body{ - [](uint8_t* /* p */, uint16_t /* evt_len */, bool /* is_ble */) { ; }}; - void operator()(uint8_t* p, uint16_t evt_len, bool is_ble) { - body(p, evt_len, is_ble); - }; + [](uint8_t* /* p */, uint16_t /* evt_len */, bool /* is_ble */) { ; }}; + void operator()(uint8_t* p, uint16_t evt_len, bool is_ble) { body(p, evt_len, is_ble); } }; extern struct btm_read_tx_power_complete btm_read_tx_power_complete; // Name: btm_read_tx_power_timeout @@ -1063,7 +970,7 @@ extern struct btm_read_tx_power_complete btm_read_tx_power_complete; // Returns: void struct btm_read_tx_power_timeout { std::function body{[](void* /* data */) { ; }}; - void operator()(void* data) { body(data); }; + void operator()(void* data) { body(data); } }; extern struct btm_read_tx_power_timeout btm_read_tx_power_timeout; // Name: btm_rejectlist_role_change_device @@ -1071,20 +978,17 @@ extern struct btm_read_tx_power_timeout btm_read_tx_power_timeout; // Returns: void struct btm_rejectlist_role_change_device { std::function body{ - [](const RawAddress& /* bd_addr */, uint8_t /* hci_status */) { ; }}; - void operator()(const RawAddress& bd_addr, uint8_t hci_status) { - body(bd_addr, hci_status); - }; + [](const RawAddress& /* bd_addr */, uint8_t /* hci_status */) { ; }}; + void operator()(const RawAddress& bd_addr, uint8_t hci_status) { body(bd_addr, hci_status); } }; -extern struct btm_rejectlist_role_change_device - btm_rejectlist_role_change_device; +extern struct btm_rejectlist_role_change_device btm_rejectlist_role_change_device; // Name: btm_set_link_policy // Params: tACL_CONN* conn, tLINK_POLICY policy // Returns: void struct btm_set_link_policy { std::function body{ - [](tACL_CONN* /* conn */, tLINK_POLICY /* policy */) { ; }}; - void operator()(tACL_CONN* conn, tLINK_POLICY policy) { body(conn, policy); }; + [](tACL_CONN* /* conn */, tLINK_POLICY /* policy */) { ; }}; + void operator()(tACL_CONN* conn, tLINK_POLICY policy) { body(conn, policy); } }; extern struct btm_set_link_policy btm_set_link_policy; // Name: btm_set_packet_types_from_address @@ -1092,60 +996,53 @@ extern struct btm_set_link_policy btm_set_link_policy; // Returns: void struct btm_set_packet_types_from_address { std::function body{ - [](const RawAddress& /* bd_addr */, uint16_t /* pkt_types */) { ; }}; - void operator()(const RawAddress& bd_addr, uint16_t pkt_types) { - body(bd_addr, pkt_types); - }; + [](const RawAddress& /* bd_addr */, uint16_t /* pkt_types */) { ; }}; + void operator()(const RawAddress& bd_addr, uint16_t pkt_types) { body(bd_addr, pkt_types); } }; -extern struct btm_set_packet_types_from_address - btm_set_packet_types_from_address; +extern struct btm_set_packet_types_from_address btm_set_packet_types_from_address; // Name: hci_btm_set_link_supervision_timeout // Params: tACL_CONN& link, uint16_t timeout // Returns: void struct hci_btm_set_link_supervision_timeout { std::function body{ - [](tACL_CONN& /* link */, uint16_t /* timeout */) { ; }}; - void operator()(tACL_CONN& link, uint16_t timeout) { body(link, timeout); }; + [](tACL_CONN& /* link */, uint16_t /* timeout */) { ; }}; + void operator()(tACL_CONN& link, uint16_t timeout) { body(link, timeout); } }; -extern struct hci_btm_set_link_supervision_timeout - hci_btm_set_link_supervision_timeout; +extern struct hci_btm_set_link_supervision_timeout hci_btm_set_link_supervision_timeout; // Name: on_acl_br_edr_connected // Params: const RawAddress& bda, uint16_t handle, uint8_t enc_mode, bool // locally_initiated Returns: void struct on_acl_br_edr_connected { std::function - body{[](const RawAddress& /* bda */, uint16_t /* handle */, - uint8_t /* enc_mode */, bool /* locally_initiated */) { ; }}; + body{[](const RawAddress& /* bda */, uint16_t /* handle */, uint8_t /* enc_mode */, + bool /* locally_initiated */) { ; }}; void operator()(const RawAddress& bda, uint16_t handle, uint8_t enc_mode, bool locally_initiated) { body(bda, handle, enc_mode, locally_initiated); - }; + } }; extern struct on_acl_br_edr_connected on_acl_br_edr_connected; // Name: on_acl_br_edr_failed // Params: const RawAddress& bda, tHCI_STATUS status, bool locally_initiated // Returns: void struct on_acl_br_edr_failed { - std::function - body{[](const RawAddress& /* bda */, tHCI_STATUS /* status */, - bool /* locally_initiated */) { ; }}; - void operator()(const RawAddress& bda, tHCI_STATUS status, - bool locally_initiated) { + std::function body{ + [](const RawAddress& /* bda */, tHCI_STATUS /* status */, bool /* locally_initiated */) { + ; + }}; + void operator()(const RawAddress& bda, tHCI_STATUS status, bool locally_initiated) { body(bda, status, locally_initiated); - }; + } }; extern struct on_acl_br_edr_failed on_acl_br_edr_failed; // Manually added struct BTM_unblock_role_switch_and_sniff_mode_for { - std::function body{ - [](const RawAddress& /* peer_addr */) {}}; - void operator()(const RawAddress& peer_addr) { body(peer_addr); }; + std::function body{[](const RawAddress& /* peer_addr */) {}}; + void operator()(const RawAddress& peer_addr) { body(peer_addr); } }; -extern struct BTM_unblock_role_switch_and_sniff_mode_for - BTM_unblock_role_switch_and_sniff_mode_for; +extern struct BTM_unblock_role_switch_and_sniff_mode_for BTM_unblock_role_switch_and_sniff_mode_for; } // namespace stack_acl } // namespace mock diff --git a/system/test/mock/mock_stack_acl_ble.cc b/system/test/mock/mock_stack_acl_ble.cc index bc963581fca..c073b50aa5c 100644 --- a/system/test/mock/mock_stack_acl_ble.cc +++ b/system/test/mock/mock_stack_acl_ble.cc @@ -27,53 +27,45 @@ #include "types/hci_role.h" #include "types/raw_address.h" -void acl_ble_connection_fail(const tBLE_BD_ADDR& /* address_with_type */, - uint16_t /* handle */, bool /* enhanced */, - tHCI_STATUS /* status */) { +void acl_ble_connection_fail(const tBLE_BD_ADDR& /* address_with_type */, uint16_t /* handle */, + bool /* enhanced */, tHCI_STATUS /* status */) { inc_func_call_count(__func__); } -void acl_ble_enhanced_connection_complete( - const tBLE_BD_ADDR& /* address_with_type */, uint16_t /* handle */, - tHCI_ROLE /* role */, bool /* match */, uint16_t /* conn_interval */, - uint16_t /* conn_latency */, uint16_t /* conn_timeout */, - const RawAddress& /* local_rpa */, const RawAddress& /* peer_rpa */, - uint8_t /* peer_addr_type */, - bool /* can_read_discoverable_characteristics */) { +void acl_ble_enhanced_connection_complete(const tBLE_BD_ADDR& /* address_with_type */, + uint16_t /* handle */, tHCI_ROLE /* role */, + bool /* match */, uint16_t /* conn_interval */, + uint16_t /* conn_latency */, uint16_t /* conn_timeout */, + const RawAddress& /* local_rpa */, + const RawAddress& /* peer_rpa */, + uint8_t /* peer_addr_type */, + bool /* can_read_discoverable_characteristics */) { inc_func_call_count(__func__); } void acl_ble_enhanced_connection_complete_from_shim( - const tBLE_BD_ADDR& /* address_with_type */, uint16_t /* handle */, - tHCI_ROLE /* role */, uint16_t /* conn_interval */, - uint16_t /* conn_latency */, uint16_t /* conn_timeout */, - const RawAddress& /* local_rpa */, const RawAddress& /* peer_rpa */, - tBLE_ADDR_TYPE /* peer_addr_type */, - bool /* can_read_discoverable_characteristics */) { + const tBLE_BD_ADDR& /* address_with_type */, uint16_t /* handle */, tHCI_ROLE /* role */, + uint16_t /* conn_interval */, uint16_t /* conn_latency */, uint16_t /* conn_timeout */, + const RawAddress& /* local_rpa */, const RawAddress& /* peer_rpa */, + tBLE_ADDR_TYPE /* peer_addr_type */, bool /* can_read_discoverable_characteristics */) { inc_func_call_count(__func__); } -void gatt_notify_conn_update(const RawAddress& /* remote */, - uint16_t /* interval */, uint16_t /* latency */, - uint16_t /* timeout */, tHCI_STATUS /* status */); -void acl_ble_update_event_received(tHCI_STATUS /* status */, - uint16_t /* handle */, - uint16_t /* interval */, - uint16_t /* latency */, +void gatt_notify_conn_update(const RawAddress& /* remote */, uint16_t /* interval */, + uint16_t /* latency */, uint16_t /* timeout */, + tHCI_STATUS /* status */); +void acl_ble_update_event_received(tHCI_STATUS /* status */, uint16_t /* handle */, + uint16_t /* interval */, uint16_t /* latency */, uint16_t /* timeout */) { inc_func_call_count(__func__); } -void acl_ble_update_request_event_received(uint16_t /* handle */, - uint16_t /* interval_min */, - uint16_t /* interval_max */, - uint16_t /* latency */, +void acl_ble_update_request_event_received(uint16_t /* handle */, uint16_t /* interval_min */, + uint16_t /* interval_max */, uint16_t /* latency */, uint16_t /* timeout */) { inc_func_call_count(__func__); } -void acl_ble_data_length_change_event(uint16_t /* handle */, - uint16_t /* max_tx_octets */, - uint16_t /* max_tx_time */, - uint16_t /* max_rx_octets */, +void acl_ble_data_length_change_event(uint16_t /* handle */, uint16_t /* max_tx_octets */, + uint16_t /* max_tx_time */, uint16_t /* max_rx_octets */, uint16_t /* max_rx_time */) { inc_func_call_count(__func__); } diff --git a/system/test/mock/mock_stack_acl_btm_pm.cc b/system/test/mock/mock_stack_acl_btm_pm.cc index c065ccec2f9..49fee61ba2f 100644 --- a/system/test/mock/mock_stack_acl_btm_pm.cc +++ b/system/test/mock/mock_stack_acl_btm_pm.cc @@ -26,8 +26,7 @@ #include "test/common/mock_functions.h" #include "types/raw_address.h" -bool BTM_ReadPowerMode(const RawAddress& /* remote_bda */, - tBTM_PM_MODE* /* p_mode */) { +bool BTM_ReadPowerMode(const RawAddress& /* remote_bda */, tBTM_PM_MODE* /* p_mode */) { inc_func_call_count(__func__); return false; } @@ -60,28 +59,22 @@ tBTM_STATUS BTM_PmRegister(uint8_t /* mask */, uint8_t* /* p_pm_id */, inc_func_call_count(__func__); return BTM_SUCCESS; } -tBTM_STATUS BTM_SetPowerMode(uint8_t /* pm_id */, - const RawAddress& /* remote_bda */, +tBTM_STATUS BTM_SetPowerMode(uint8_t /* pm_id */, const RawAddress& /* remote_bda */, const tBTM_PM_PWR_MD* /* p_mode */) { inc_func_call_count(__func__); return BTM_SUCCESS; } -tBTM_STATUS BTM_SetSsrParams(const RawAddress& /* remote_bda */, - uint16_t /* max_lat */, uint16_t /* min_rmt_to */, - uint16_t /* min_loc_to */) { +tBTM_STATUS BTM_SetSsrParams(const RawAddress& /* remote_bda */, uint16_t /* max_lat */, + uint16_t /* min_rmt_to */, uint16_t /* min_loc_to */) { inc_func_call_count(__func__); return BTM_SUCCESS; } -void BTM_PM_OnConnected(uint16_t /* handle */, - const RawAddress& /* remote_bda */) { - inc_func_call_count(__func__); -} -void BTM_PM_OnDisconnected(uint16_t /* handle */) { +void BTM_PM_OnConnected(uint16_t /* handle */, const RawAddress& /* remote_bda */) { inc_func_call_count(__func__); } +void BTM_PM_OnDisconnected(uint16_t /* handle */) { inc_func_call_count(__func__); } void btm_pm_on_mode_change(tHCI_STATUS /* status */, uint16_t /* handle */, - tHCI_MODE /* current_mode */, - uint16_t /* interval */) { + tHCI_MODE /* current_mode */, uint16_t /* interval */) { inc_func_call_count(__func__); } void btm_pm_on_sniff_subrating(tHCI_STATUS /* status */, uint16_t /* handle */, @@ -91,20 +84,16 @@ void btm_pm_on_sniff_subrating(tHCI_STATUS /* status */, uint16_t /* handle */, uint16_t /* minimum_local_timeout */) { inc_func_call_count(__func__); } -void btm_pm_proc_cmd_status(tHCI_STATUS /* status */) { - inc_func_call_count(__func__); -} -void btm_pm_proc_mode_change(tHCI_STATUS /* hci_status */, - uint16_t /* hci_handle */, - tHCI_MODE /* hci_mode */, - uint16_t /* interval */) { +void btm_pm_proc_cmd_status(tHCI_STATUS /* status */) { inc_func_call_count(__func__); } +void btm_pm_proc_mode_change(tHCI_STATUS /* hci_status */, uint16_t /* hci_handle */, + tHCI_MODE /* hci_mode */, uint16_t /* interval */) { inc_func_call_count(__func__); } void btm_pm_proc_ssr_evt(uint8_t* /* p */, uint16_t /* evt_len */) { inc_func_call_count(__func__); } void btm_pm_reset(void) { inc_func_call_count(__func__); } -void process_ssr_event(tHCI_STATUS /* status */, uint16_t /* handle */, - uint16_t /* max_tx_lat */, uint16_t /* max_rx_lat */) { +void process_ssr_event(tHCI_STATUS /* status */, uint16_t /* handle */, uint16_t /* max_tx_lat */, + uint16_t /* max_rx_lat */) { inc_func_call_count(__func__); } diff --git a/system/test/mock/mock_stack_arbiter_acl_arbiter.cc b/system/test/mock/mock_stack_arbiter_acl_arbiter.cc index 4fdd1418840..b2dcb2ec264 100644 --- a/system/test/mock/mock_stack_arbiter_acl_arbiter.cc +++ b/system/test/mock/mock_stack_arbiter_acl_arbiter.cc @@ -20,13 +20,11 @@ namespace bluetooth { namespace shim { namespace arbiter { -void AclArbiter::OnLeConnect(uint8_t /* tcb_idx */, - uint16_t /* advertiser_id */) {} +void AclArbiter::OnLeConnect(uint8_t /* tcb_idx */, uint16_t /* advertiser_id */) {} void AclArbiter::OnLeDisconnect(uint8_t /* tcb_idx */) {} -InterceptAction AclArbiter::InterceptAttPacket(uint8_t /* tcb_idx */, - const BT_HDR* /* packet */) { +InterceptAction AclArbiter::InterceptAttPacket(uint8_t /* tcb_idx */, const BT_HDR* /* packet */) { return InterceptAction::FORWARD; } diff --git a/system/test/mock/mock_stack_avct_api.cc b/system/test/mock/mock_stack_avct_api.cc index 659f417d5c8..42dae210436 100644 --- a/system/test/mock/mock_stack_avct_api.cc +++ b/system/test/mock/mock_stack_avct_api.cc @@ -41,8 +41,8 @@ uint16_t AVCT_GetPeerMtu(uint8_t /* handle */) { inc_func_call_count(__func__); return 0; } -uint16_t AVCT_MsgReq(uint8_t /* handle */, uint8_t /* label */, - uint8_t /* cr */, BT_HDR* /* p_msg */) { +uint16_t AVCT_MsgReq(uint8_t /* handle */, uint8_t /* label */, uint8_t /* cr */, + BT_HDR* /* p_msg */) { inc_func_call_count(__func__); return 0; } diff --git a/system/test/mock/mock_stack_avdt_api.cc b/system/test/mock/mock_stack_avdt_api.cc index af64bb7a812..39edd594563 100644 --- a/system/test/mock/mock_stack_avdt_api.cc +++ b/system/test/mock/mock_stack_avdt_api.cc @@ -29,13 +29,12 @@ uint16_t AVDT_CloseReq(uint8_t /* handle */) { inc_func_call_count(__func__); return 0; } -uint16_t AVDT_ConfigRsp(uint8_t /* handle */, uint8_t /* label */, - uint8_t /* error_code */, uint8_t /* category */) { +uint16_t AVDT_ConfigRsp(uint8_t /* handle */, uint8_t /* label */, uint8_t /* error_code */, + uint8_t /* category */) { inc_func_call_count(__func__); return 0; } -uint16_t AVDT_ConnectReq(const RawAddress& /* bd_addr */, - uint8_t /* channel_index */, +uint16_t AVDT_ConnectReq(const RawAddress& /* bd_addr */, uint8_t /* channel_index */, tAVDT_CTRL_CBACK* /* p_cback */) { inc_func_call_count(__func__); return 0; @@ -45,29 +44,23 @@ uint16_t AVDT_CreateStream(uint8_t /* peer_id */, uint8_t* /* p_handle */, inc_func_call_count(__func__); return 0; } -uint16_t AVDT_DelayReport(uint8_t /* handle */, uint8_t /* seid */, - uint16_t /* delay */) { +uint16_t AVDT_DelayReport(uint8_t /* handle */, uint8_t /* seid */, uint16_t /* delay */) { inc_func_call_count(__func__); return 0; } -uint16_t AVDT_DisconnectReq(const RawAddress& /* bd_addr */, - tAVDT_CTRL_CBACK* /* p_cback */) { +uint16_t AVDT_DisconnectReq(const RawAddress& /* bd_addr */, tAVDT_CTRL_CBACK* /* p_cback */) { inc_func_call_count(__func__); return 0; } -uint16_t AVDT_DiscoverReq(const RawAddress& /* bd_addr */, - uint8_t /* channel_index */, - tAVDT_SEP_INFO* /* p_sep_info */, - uint8_t /* max_seps */, +uint16_t AVDT_DiscoverReq(const RawAddress& /* bd_addr */, uint8_t /* channel_index */, + tAVDT_SEP_INFO* /* p_sep_info */, uint8_t /* max_seps */, tAVDT_CTRL_CBACK* /* p_cback */) { inc_func_call_count(__func__); return 0; } -uint16_t AVDT_GetCapReq(const RawAddress& /* bd_addr */, - uint8_t /* channel_index */, uint8_t /* seid */, - AvdtpSepConfig* /* p_cfg */, - tAVDT_CTRL_CBACK* /* p_cback */, - bool /* get_all_cap */) { +uint16_t AVDT_GetCapReq(const RawAddress& /* bd_addr */, uint8_t /* channel_index */, + uint8_t /* seid */, AvdtpSepConfig* /* p_cfg */, + tAVDT_CTRL_CBACK* /* p_cback */, bool /* get_all_cap */) { inc_func_call_count(__func__); return 0; } @@ -89,14 +82,12 @@ uint16_t AVDT_RemoveStream(uint8_t /* handle */) { inc_func_call_count(__func__); return 0; } -uint16_t AVDT_SecurityReq(uint8_t /* handle */, uint8_t* /* p_data */, - uint16_t /* len */) { +uint16_t AVDT_SecurityReq(uint8_t /* handle */, uint8_t* /* p_data */, uint16_t /* len */) { inc_func_call_count(__func__); return 0; } -uint16_t AVDT_SecurityRsp(uint8_t /* handle */, uint8_t /* label */, - uint8_t /* error_code */, uint8_t* /* p_data */, - uint16_t /* len */) { +uint16_t AVDT_SecurityRsp(uint8_t /* handle */, uint8_t /* label */, uint8_t /* error_code */, + uint8_t* /* p_data */, uint16_t /* len */) { inc_func_call_count(__func__); return 0; } @@ -108,9 +99,8 @@ uint16_t AVDT_SuspendReq(uint8_t* /* p_handles */, uint8_t /* num_handles */) { inc_func_call_count(__func__); return 0; } -uint16_t AVDT_WriteReqOpt(uint8_t /* handle */, BT_HDR* /* p_pkt */, - uint32_t /* time_stamp */, uint8_t /* m_pt */, - tAVDT_DATA_OPT_MASK /* opt */) { +uint16_t AVDT_WriteReqOpt(uint8_t /* handle */, BT_HDR* /* p_pkt */, uint32_t /* time_stamp */, + uint8_t /* m_pt */, tAVDT_DATA_OPT_MASK /* opt */) { inc_func_call_count(__func__); return 0; } @@ -119,16 +109,8 @@ void AVDT_Deregister(void) { inc_func_call_count(__func__); } void AVDT_Register(AvdtpRcb* /* p_reg */, tAVDT_CTRL_CBACK* /* p_cback */) { inc_func_call_count(__func__); } -void avdt_ccb_idle_ccb_timer_timeout(void* /* data */) { - inc_func_call_count(__func__); -} -void avdt_ccb_ret_ccb_timer_timeout(void* /* data */) { - inc_func_call_count(__func__); -} -void avdt_ccb_rsp_ccb_timer_timeout(void* /* data */) { - inc_func_call_count(__func__); -} -void avdt_scb_transport_channel_timer_timeout(void* /* data */) { - inc_func_call_count(__func__); -} +void avdt_ccb_idle_ccb_timer_timeout(void* /* data */) { inc_func_call_count(__func__); } +void avdt_ccb_ret_ccb_timer_timeout(void* /* data */) { inc_func_call_count(__func__); } +void avdt_ccb_rsp_ccb_timer_timeout(void* /* data */) { inc_func_call_count(__func__); } +void avdt_scb_transport_channel_timer_timeout(void* /* data */) { inc_func_call_count(__func__); } void stack_debug_avdtp_api_dump(int /* fd */) { inc_func_call_count(__func__); } diff --git a/system/test/mock/mock_stack_avrc_api.cc b/system/test/mock/mock_stack_avrc_api.cc index c0af90bc9fa..a3fa3c7c570 100644 --- a/system/test/mock/mock_stack_avrc_api.cc +++ b/system/test/mock/mock_stack_avrc_api.cc @@ -45,9 +45,8 @@ uint16_t AVRC_GetProfileVersion() { inc_func_call_count(__func__); return 0; } -uint16_t AVRC_MsgReq(uint8_t /* handle */, uint8_t /* label */, - uint8_t /* ctype */, BT_HDR* /* p_pkt */, - bool /* is_new_avrcp */) { +uint16_t AVRC_MsgReq(uint8_t /* handle */, uint8_t /* label */, uint8_t /* ctype */, + BT_HDR* /* p_pkt */, bool /* is_new_avrcp */) { inc_func_call_count(__func__); return 0; } @@ -60,8 +59,7 @@ uint16_t AVRC_OpenBrowse(uint8_t /* handle */, uint8_t /* conn_role */) { inc_func_call_count(__func__); return 0; } -void AVRC_SaveControllerVersion(const RawAddress& /* bdaddr */, - uint16_t /* version */) { +void AVRC_SaveControllerVersion(const RawAddress& /* bdaddr */, uint16_t /* version */) { inc_func_call_count(__func__); } @@ -69,22 +67,17 @@ void AVRC_UpdateCcb(RawAddress* /* addr */, uint32_t /* company_id */) { inc_func_call_count(__func__); } -uint16_t AVRC_PassCmd(uint8_t /* handle */, uint8_t /* label */, - tAVRC_MSG_PASS* /* p_msg */) { +uint16_t AVRC_PassCmd(uint8_t /* handle */, uint8_t /* label */, tAVRC_MSG_PASS* /* p_msg */) { inc_func_call_count(__func__); return 0; } -uint16_t AVRC_PassRsp(uint8_t /* handle */, uint8_t /* label */, - tAVRC_MSG_PASS* /* p_msg */) { +uint16_t AVRC_PassRsp(uint8_t /* handle */, uint8_t /* label */, tAVRC_MSG_PASS* /* p_msg */) { inc_func_call_count(__func__); return 0; } void avrc_flush_cmd_q(uint8_t /* handle */) { inc_func_call_count(__func__); } void avrc_process_timeout(void* /* data */) { inc_func_call_count(__func__); } -void avrc_send_next_vendor_cmd(uint8_t /* handle */) { - inc_func_call_count(__func__); -} -void avrc_start_cmd_timer(uint8_t /* handle */, uint8_t /* label */, - uint8_t /* msg_mask */) { +void avrc_send_next_vendor_cmd(uint8_t /* handle */) { inc_func_call_count(__func__); } +void avrc_start_cmd_timer(uint8_t /* handle */, uint8_t /* label */, uint8_t /* msg_mask */) { inc_func_call_count(__func__); } diff --git a/system/test/mock/mock_stack_avrc_apt.cc b/system/test/mock/mock_stack_avrc_apt.cc index 23ed7b6365b..7b3cead1670 100644 --- a/system/test/mock/mock_stack_avrc_apt.cc +++ b/system/test/mock/mock_stack_avrc_apt.cc @@ -67,13 +67,11 @@ uint16_t AVRC_UnitCmd(uint8_t handle, uint8_t label) { inc_func_call_count(__func__); return test::mock::stack_avrc_apt::AVRC_UnitCmd(handle, label); } -uint16_t AVRC_VendorCmd(uint8_t handle, uint8_t label, - tAVRC_MSG_VENDOR* p_msg) { +uint16_t AVRC_VendorCmd(uint8_t handle, uint8_t label, tAVRC_MSG_VENDOR* p_msg) { inc_func_call_count(__func__); return test::mock::stack_avrc_apt::AVRC_VendorCmd(handle, label, p_msg); } -uint16_t AVRC_VendorRsp(uint8_t handle, uint8_t label, - tAVRC_MSG_VENDOR* p_msg) { +uint16_t AVRC_VendorRsp(uint8_t handle, uint8_t label, tAVRC_MSG_VENDOR* p_msg) { inc_func_call_count(__func__); return test::mock::stack_avrc_apt::AVRC_VendorRsp(handle, label, p_msg); } diff --git a/system/test/mock/mock_stack_avrc_apt.h b/system/test/mock/mock_stack_avrc_apt.h index fd16afbe607..3c64c803a1d 100644 --- a/system/test/mock/mock_stack_avrc_apt.h +++ b/system/test/mock/mock_stack_avrc_apt.h @@ -43,12 +43,12 @@ namespace stack_avrc_apt { struct AVRC_SubCmd { static uint16_t return_value; std::function body{ - [](uint8_t /* handle */, uint8_t /* label */, uint8_t /* page */) { - return return_value; - }}; + [](uint8_t /* handle */, uint8_t /* label */, uint8_t /* page */) { + return return_value; + }}; uint16_t operator()(uint8_t handle, uint8_t label, uint8_t page) { return body(handle, label, page); - }; + } }; extern struct AVRC_SubCmd AVRC_SubCmd; @@ -58,10 +58,8 @@ extern struct AVRC_SubCmd AVRC_SubCmd; struct AVRC_UnitCmd { static uint16_t return_value; std::function body{ - [](uint8_t /* handle */, uint8_t /* label */) { return return_value; }}; - uint16_t operator()(uint8_t handle, uint8_t label) { - return body(handle, label); - }; + [](uint8_t /* handle */, uint8_t /* label */) { return return_value; }}; + uint16_t operator()(uint8_t handle, uint8_t label) { return body(handle, label); } }; extern struct AVRC_UnitCmd AVRC_UnitCmd; @@ -70,13 +68,13 @@ extern struct AVRC_UnitCmd AVRC_UnitCmd; // Return: uint16_t struct AVRC_VendorCmd { static uint16_t return_value; - std::function - body{[](uint8_t /* handle */, uint8_t /* label */, - tAVRC_MSG_VENDOR* /* p_msg */) { return return_value; }}; + std::function body{ + [](uint8_t /* handle */, uint8_t /* label */, tAVRC_MSG_VENDOR* /* p_msg */) { + return return_value; + }}; uint16_t operator()(uint8_t handle, uint8_t label, tAVRC_MSG_VENDOR* p_msg) { return body(handle, label, p_msg); - }; + } }; extern struct AVRC_VendorCmd AVRC_VendorCmd; @@ -85,13 +83,13 @@ extern struct AVRC_VendorCmd AVRC_VendorCmd; // Return: uint16_t struct AVRC_VendorRsp { static uint16_t return_value; - std::function - body{[](uint8_t /* handle */, uint8_t /* label */, - tAVRC_MSG_VENDOR* /* p_msg */) { return return_value; }}; + std::function body{ + [](uint8_t /* handle */, uint8_t /* label */, tAVRC_MSG_VENDOR* /* p_msg */) { + return return_value; + }}; uint16_t operator()(uint8_t handle, uint8_t label, tAVRC_MSG_VENDOR* p_msg) { return body(handle, label, p_msg); - }; + } }; extern struct AVRC_VendorRsp AVRC_VendorRsp; diff --git a/system/test/mock/mock_stack_avrc_bld_tg.cc b/system/test/mock/mock_stack_avrc_bld_tg.cc index 5ad36983ccb..c060df0d22f 100644 --- a/system/test/mock/mock_stack_avrc_bld_tg.cc +++ b/system/test/mock/mock_stack_avrc_bld_tg.cc @@ -29,8 +29,7 @@ tAVRC_STS AVRC_BldResponse(uint8_t /* handle */, tAVRC_RESPONSE* /* p_rsp */, inc_func_call_count(__func__); return 0; } -tAVRC_STS avrc_bld_group_navigation_rsp(uint16_t /* navi_id */, - BT_HDR* /* p_pkt */) { +tAVRC_STS avrc_bld_group_navigation_rsp(uint16_t /* navi_id */, BT_HDR* /* p_pkt */) { inc_func_call_count(__func__); return 0; } diff --git a/system/test/mock/mock_stack_avrc_pars.ct.cc b/system/test/mock/mock_stack_avrc_pars.ct.cc index 81dbd91aaca..7635d796378 100644 --- a/system/test/mock/mock_stack_avrc_pars.ct.cc +++ b/system/test/mock/mock_stack_avrc_pars.ct.cc @@ -23,21 +23,17 @@ #include "avrc_defs.h" #include "test/common/mock_functions.h" -tAVRC_STS AVRC_Ctrl_ParsResponse(tAVRC_MSG* /* p_msg */, - tAVRC_RESPONSE* /* p_result */, - uint8_t* /* p_buf */, - uint16_t* /* buf_len */) { +tAVRC_STS AVRC_Ctrl_ParsResponse(tAVRC_MSG* /* p_msg */, tAVRC_RESPONSE* /* p_result */, + uint8_t* /* p_buf */, uint16_t* /* buf_len */) { inc_func_call_count(__func__); return 0; } -tAVRC_STS AVRC_ParsResponse(tAVRC_MSG* /* p_msg */, - tAVRC_RESPONSE* /* p_result */, +tAVRC_STS AVRC_ParsResponse(tAVRC_MSG* /* p_msg */, tAVRC_RESPONSE* /* p_result */, uint8_t* /* p_buf */, uint16_t /* buf_len */) { inc_func_call_count(__func__); return 0; } -tAVRC_STS avrc_parse_notification_rsp(uint8_t* /* p_stream */, - uint16_t /* len */, +tAVRC_STS avrc_parse_notification_rsp(uint8_t* /* p_stream */, uint16_t /* len */, tAVRC_REG_NOTIF_RSP* /* p_rsp */) { inc_func_call_count(__func__); return 0; diff --git a/system/test/mock/mock_stack_avrc_pars_tg.cc b/system/test/mock/mock_stack_avrc_pars_tg.cc index 73509063df5..da41a2ce438 100644 --- a/system/test/mock/mock_stack_avrc_pars_tg.cc +++ b/system/test/mock/mock_stack_avrc_pars_tg.cc @@ -23,14 +23,12 @@ #include "avrc_defs.h" #include "test/common/mock_functions.h" -tAVRC_STS AVRC_Ctrl_ParsCommand(tAVRC_MSG* /* p_msg */, - tAVRC_COMMAND* /* p_result */) { +tAVRC_STS AVRC_Ctrl_ParsCommand(tAVRC_MSG* /* p_msg */, tAVRC_COMMAND* /* p_result */) { inc_func_call_count(__func__); return 0; } -tAVRC_STS AVRC_ParsCommand(tAVRC_MSG* /* p_msg */, - tAVRC_COMMAND* /* p_result */, uint8_t* /* p_buf */, - uint16_t /* buf_len */) { +tAVRC_STS AVRC_ParsCommand(tAVRC_MSG* /* p_msg */, tAVRC_COMMAND* /* p_result */, + uint8_t* /* p_buf */, uint16_t /* buf_len */) { inc_func_call_count(__func__); return 0; } diff --git a/system/test/mock/mock_stack_avrc_sdp.cc b/system/test/mock/mock_stack_avrc_sdp.cc index 90b88012461..e2aab82b3f8 100644 --- a/system/test/mock/mock_stack_avrc_sdp.cc +++ b/system/test/mock/mock_stack_avrc_sdp.cc @@ -62,20 +62,17 @@ uint16_t AVRC_RemoveRecord::return_value = 0; // Mocked functions, if any uint16_t AVRC_AddRecord(uint16_t service_uuid, const char* p_service_name, - const char* p_provider_name, uint16_t categories, - uint32_t sdp_handle, bool browse_supported, - uint16_t profile_version, uint16_t cover_art_psm) { + const char* p_provider_name, uint16_t categories, uint32_t sdp_handle, + bool browse_supported, uint16_t profile_version, uint16_t cover_art_psm) { inc_func_call_count(__func__); - return test::mock::stack_avrc_sdp::AVRC_AddRecord( - service_uuid, p_service_name, p_provider_name, categories, sdp_handle, - browse_supported, profile_version, cover_art_psm); + return test::mock::stack_avrc_sdp::AVRC_AddRecord(service_uuid, p_service_name, p_provider_name, + categories, sdp_handle, browse_supported, + profile_version, cover_art_psm); } uint16_t AVRC_FindService(uint16_t service_uuid, const RawAddress& bd_addr, - tAVRC_SDP_DB_PARAMS* p_db, - const tAVRC_FIND_CBACK& find_cback) { + tAVRC_SDP_DB_PARAMS* p_db, const tAVRC_FIND_CBACK& find_cback) { inc_func_call_count(__func__); - return test::mock::stack_avrc_sdp::AVRC_FindService(service_uuid, bd_addr, - p_db, find_cback); + return test::mock::stack_avrc_sdp::AVRC_FindService(service_uuid, bd_addr, p_db, find_cback); } void AVRC_Init(void) { inc_func_call_count(__func__); diff --git a/system/test/mock/mock_stack_avrc_sdp.h b/system/test/mock/mock_stack_avrc_sdp.h index 8d165038b98..506ad7ade0b 100644 --- a/system/test/mock/mock_stack_avrc_sdp.h +++ b/system/test/mock/mock_stack_avrc_sdp.h @@ -55,21 +55,19 @@ namespace stack_avrc_sdp { struct AVRC_AddRecord { static uint16_t return_value; std::function - body{[](uint16_t /* service_uuid */, const char* /* p_service_name */, - const char* /* p_provider_name */, uint16_t /* categories */, - uint32_t /* sdp_handle */, bool /* browse_supported */, - uint16_t /* profile_version */, - uint16_t /* cover_art_psm */) { return return_value; }}; + const char* p_provider_name, uint16_t categories, uint32_t sdp_handle, + bool browse_supported, uint16_t profile_version, uint16_t cover_art_psm)> + body{[](uint16_t /* service_uuid */, const char* /* p_service_name */, + const char* /* p_provider_name */, uint16_t /* categories */, + uint32_t /* sdp_handle */, bool /* browse_supported */, + uint16_t /* profile_version */, + uint16_t /* cover_art_psm */) { return return_value; }}; uint16_t operator()(uint16_t service_uuid, const char* p_service_name, - const char* p_provider_name, uint16_t categories, - uint32_t sdp_handle, bool browse_supported, - uint16_t profile_version, uint16_t cover_art_psm) { - return body(service_uuid, p_service_name, p_provider_name, categories, - sdp_handle, browse_supported, profile_version, cover_art_psm); - }; + const char* p_provider_name, uint16_t categories, uint32_t sdp_handle, + bool browse_supported, uint16_t profile_version, uint16_t cover_art_psm) { + return body(service_uuid, p_service_name, p_provider_name, categories, sdp_handle, + browse_supported, profile_version, cover_art_psm); + } }; extern struct AVRC_AddRecord AVRC_AddRecord; @@ -80,18 +78,14 @@ extern struct AVRC_AddRecord AVRC_AddRecord; struct AVRC_FindService { static uint16_t return_value; std::function - body{[](uint16_t /* service_uuid */, const RawAddress& /* bd_addr */, - tAVRC_SDP_DB_PARAMS* /* p_db */, - const tAVRC_FIND_CBACK& /* find_cback */) { - return return_value; - }}; - uint16_t operator()(uint16_t service_uuid, const RawAddress& bd_addr, - tAVRC_SDP_DB_PARAMS* p_db, + tAVRC_SDP_DB_PARAMS* p_db, const tAVRC_FIND_CBACK& find_cback)> + body{[](uint16_t /* service_uuid */, const RawAddress& /* bd_addr */, + tAVRC_SDP_DB_PARAMS* /* p_db */, + const tAVRC_FIND_CBACK& /* find_cback */) { return return_value; }}; + uint16_t operator()(uint16_t service_uuid, const RawAddress& bd_addr, tAVRC_SDP_DB_PARAMS* p_db, const tAVRC_FIND_CBACK& find_cback) { return body(service_uuid, bd_addr, p_db, find_cback); - }; + } }; extern struct AVRC_FindService AVRC_FindService; @@ -100,7 +94,7 @@ extern struct AVRC_FindService AVRC_FindService; // Return: void struct AVRC_Init { std::function body{[](void) {}}; - void operator()(void) { body(); }; + void operator()(void) { body(); } }; extern struct AVRC_Init AVRC_Init; @@ -110,8 +104,8 @@ extern struct AVRC_Init AVRC_Init; struct AVRC_RemoveRecord { static uint16_t return_value; std::function body{ - [](uint32_t /* sdp_handle */) { return return_value; }}; - uint16_t operator()(uint32_t sdp_handle) { return body(sdp_handle); }; + [](uint32_t /* sdp_handle */) { return return_value; }}; + uint16_t operator()(uint32_t sdp_handle) { return body(sdp_handle); } }; extern struct AVRC_RemoveRecord AVRC_RemoveRecord; diff --git a/system/test/mock/mock_stack_avrc_utils.cc b/system/test/mock/mock_stack_avrc_utils.cc index 00e6000e407..78a37cbeb25 100644 --- a/system/test/mock/mock_stack_avrc_utils.cc +++ b/system/test/mock/mock_stack_avrc_utils.cc @@ -77,18 +77,15 @@ bool avrc_is_valid_opcode(uint8_t opcode) { } bool avrc_is_valid_player_attrib_value(uint8_t attrib, uint8_t value) { inc_func_call_count(__func__); - return test::mock::stack_avrc_utils::avrc_is_valid_player_attrib_value(attrib, - value); + return test::mock::stack_avrc_utils::avrc_is_valid_player_attrib_value(attrib, value); } uint8_t avrc_opcode_from_pdu(uint8_t pdu) { inc_func_call_count(__func__); return test::mock::stack_avrc_utils::avrc_opcode_from_pdu(pdu); } -tAVRC_STS avrc_pars_pass_thru(tAVRC_MSG_PASS* p_msg, - uint16_t* p_vendor_unique_id) { +tAVRC_STS avrc_pars_pass_thru(tAVRC_MSG_PASS* p_msg, uint16_t* p_vendor_unique_id) { inc_func_call_count(__func__); - return test::mock::stack_avrc_utils::avrc_pars_pass_thru(p_msg, - p_vendor_unique_id); + return test::mock::stack_avrc_utils::avrc_pars_pass_thru(p_msg, p_vendor_unique_id); } // Mocked functions complete // END mockcify generation diff --git a/system/test/mock/mock_stack_avrc_utils.h b/system/test/mock/mock_stack_avrc_utils.h index 0a51e71bcdd..517cf9e4ba9 100644 --- a/system/test/mock/mock_stack_avrc_utils.h +++ b/system/test/mock/mock_stack_avrc_utils.h @@ -43,12 +43,8 @@ namespace stack_avrc_utils { struct AVRC_IsValidAvcType { static bool return_value; std::function body{ - [](uint8_t /* pdu_id */, uint8_t /* avc_type */) { - return return_value; - }}; - bool operator()(uint8_t pdu_id, uint8_t avc_type) { - return body(pdu_id, avc_type); - }; + [](uint8_t /* pdu_id */, uint8_t /* avc_type */) { return return_value; }}; + bool operator()(uint8_t pdu_id, uint8_t avc_type) { return body(pdu_id, avc_type); } }; extern struct AVRC_IsValidAvcType AVRC_IsValidAvcType; @@ -57,9 +53,8 @@ extern struct AVRC_IsValidAvcType AVRC_IsValidAvcType; // Return: bool struct AVRC_IsValidPlayerAttr { static bool return_value; - std::function body{ - [](uint8_t /* attr */) { return return_value; }}; - bool operator()(uint8_t attr) { return body(attr); }; + std::function body{[](uint8_t /* attr */) { return return_value; }}; + bool operator()(uint8_t attr) { return body(attr); } }; extern struct AVRC_IsValidPlayerAttr AVRC_IsValidPlayerAttr; @@ -68,9 +63,8 @@ extern struct AVRC_IsValidPlayerAttr AVRC_IsValidPlayerAttr; // Return: bool struct avrc_is_valid_opcode { static bool return_value; - std::function body{ - [](uint8_t /* opcode */) { return return_value; }}; - bool operator()(uint8_t opcode) { return body(opcode); }; + std::function body{[](uint8_t /* opcode */) { return return_value; }}; + bool operator()(uint8_t opcode) { return body(opcode); } }; extern struct avrc_is_valid_opcode avrc_is_valid_opcode; @@ -80,22 +74,18 @@ extern struct avrc_is_valid_opcode avrc_is_valid_opcode; struct avrc_is_valid_player_attrib_value { static bool return_value; std::function body{ - [](uint8_t /* attrib */, uint8_t /* value */) { return return_value; }}; - bool operator()(uint8_t attrib, uint8_t value) { - return body(attrib, value); - }; + [](uint8_t /* attrib */, uint8_t /* value */) { return return_value; }}; + bool operator()(uint8_t attrib, uint8_t value) { return body(attrib, value); } }; -extern struct avrc_is_valid_player_attrib_value - avrc_is_valid_player_attrib_value; +extern struct avrc_is_valid_player_attrib_value avrc_is_valid_player_attrib_value; // Name: avrc_opcode_from_pdu // Params: uint8_t pdu // Return: uint8_t struct avrc_opcode_from_pdu { static uint8_t return_value; - std::function body{ - [](uint8_t /* pdu */) { return return_value; }}; - uint8_t operator()(uint8_t pdu) { return body(pdu); }; + std::function body{[](uint8_t /* pdu */) { return return_value; }}; + uint8_t operator()(uint8_t pdu) { return body(pdu); } }; extern struct avrc_opcode_from_pdu avrc_opcode_from_pdu; @@ -104,13 +94,13 @@ extern struct avrc_opcode_from_pdu avrc_opcode_from_pdu; // Return: tAVRC_STS struct avrc_pars_pass_thru { static tAVRC_STS return_value; - std::function - body{[](tAVRC_MSG_PASS* /* p_msg */, uint16_t* /* p_vendor_unique_id */) { - return return_value; - }}; + std::function body{ + [](tAVRC_MSG_PASS* /* p_msg */, uint16_t* /* p_vendor_unique_id */) { + return return_value; + }}; tAVRC_STS operator()(tAVRC_MSG_PASS* p_msg, uint16_t* p_vendor_unique_id) { return body(p_msg, p_vendor_unique_id); - }; + } }; extern struct avrc_pars_pass_thru avrc_pars_pass_thru; diff --git a/system/test/mock/mock_stack_bnep_api.cc b/system/test/mock/mock_stack_bnep_api.cc index 242debdc298..8c6ff9980ed 100644 --- a/system/test/mock/mock_stack_bnep_api.cc +++ b/system/test/mock/mock_stack_bnep_api.cc @@ -27,8 +27,7 @@ using namespace bluetooth; -tBNEP_RESULT BNEP_Connect(const RawAddress& /* p_rem_bda */, - const Uuid& /* src_uuid */, +tBNEP_RESULT BNEP_Connect(const RawAddress& /* p_rem_bda */, const Uuid& /* src_uuid */, const Uuid& /* dst_uuid */, uint16_t* /* p_handle */, uint32_t /* mx_chan_id */) { inc_func_call_count(__func__); @@ -46,34 +45,25 @@ tBNEP_RESULT BNEP_Register(tBNEP_REGISTER* /* p_reg_info */) { inc_func_call_count(__func__); return 0; } -tBNEP_RESULT BNEP_SetMulticastFilters(uint16_t /* handle */, - uint16_t /* num_filters */, - uint8_t* /* p_start_array */, - uint8_t* /* p_end_array */) { +tBNEP_RESULT BNEP_SetMulticastFilters(uint16_t /* handle */, uint16_t /* num_filters */, + uint8_t* /* p_start_array */, uint8_t* /* p_end_array */) { inc_func_call_count(__func__); return 0; } -tBNEP_RESULT BNEP_SetProtocolFilters(uint16_t /* handle */, - uint16_t /* num_filters */, - uint16_t* /* p_start_array */, - uint16_t* /* p_end_array */) { +tBNEP_RESULT BNEP_SetProtocolFilters(uint16_t /* handle */, uint16_t /* num_filters */, + uint16_t* /* p_start_array */, uint16_t* /* p_end_array */) { inc_func_call_count(__func__); return 0; } -tBNEP_RESULT BNEP_Write(uint16_t /* handle */, - const RawAddress& /* dest_addr */, - uint8_t* /* p_data */, uint16_t /* len */, - uint16_t /* protocol */, - const RawAddress& /* src_addr */, - bool /* fw_ext_present */) { +tBNEP_RESULT BNEP_Write(uint16_t /* handle */, const RawAddress& /* dest_addr */, + uint8_t* /* p_data */, uint16_t /* len */, uint16_t /* protocol */, + const RawAddress& /* src_addr */, bool /* fw_ext_present */) { inc_func_call_count(__func__); return 0; } -tBNEP_RESULT BNEP_WriteBuf(uint16_t /* handle */, - const RawAddress& /* dest_addr */, +tBNEP_RESULT BNEP_WriteBuf(uint16_t /* handle */, const RawAddress& /* dest_addr */, BT_HDR* /* p_buf */, uint16_t /* protocol */, - const RawAddress& /* src_addr */, - bool /* fw_ext_present */) { + const RawAddress& /* src_addr */, bool /* fw_ext_present */) { inc_func_call_count(__func__); return 0; } diff --git a/system/test/mock/mock_stack_btm_ble.cc b/system/test/mock/mock_stack_btm_ble.cc index ca3b7f7d468..242c232c5b4 100644 --- a/system/test/mock/mock_stack_btm_ble.cc +++ b/system/test/mock/mock_stack_btm_ble.cc @@ -74,8 +74,7 @@ struct btm_ble_reset_id btm_ble_reset_id; struct btm_ble_set_encryption btm_ble_set_encryption; struct btm_ble_set_keep_rfu_in_auth_req btm_ble_set_keep_rfu_in_auth_req; struct btm_ble_set_no_disc_if_pair_fail btm_ble_set_no_disc_if_pair_fail; -struct btm_ble_set_test_local_sign_cntr_value - btm_ble_set_test_local_sign_cntr_value; +struct btm_ble_set_test_local_sign_cntr_value btm_ble_set_test_local_sign_cntr_value; struct btm_ble_set_test_mac_value btm_ble_set_test_mac_value; struct btm_ble_start_encrypt btm_ble_start_encrypt; struct btm_ble_start_sec_check btm_ble_start_sec_check; @@ -99,15 +98,12 @@ namespace stack_btm_ble { bool BTM_GetRemoteDeviceName::return_value = false; bool BTM_BleDataSignature::return_value = false; bool BTM_BleVerifySignature::return_value = false; -const Octet16 BTM_GetDeviceDHK::return_value{0xd5, 0xcb, 0x84, 0x54, 0xd1, 0x77, - 0x73, 0x3e, 0xff, 0xff, 0xb2, 0xec, - 0x71, 0x2b, 0xae, 0xab}; -const Octet16 BTM_GetDeviceEncRoot::return_value{ - 0xd5, 0xcb, 0x84, 0x54, 0xd1, 0x77, 0x73, 0x3e, - 0xff, 0xff, 0xb2, 0xec, 0x71, 0x2b, 0xae, 0xab}; -const Octet16 BTM_GetDeviceIDRoot::return_value{ - 0xd5, 0xcb, 0x84, 0x54, 0xd1, 0x77, 0x73, 0x3e, - 0xff, 0xff, 0xb2, 0xec, 0x71, 0x2b, 0xae, 0xab}; +const Octet16 BTM_GetDeviceDHK::return_value{0xd5, 0xcb, 0x84, 0x54, 0xd1, 0x77, 0x73, 0x3e, + 0xff, 0xff, 0xb2, 0xec, 0x71, 0x2b, 0xae, 0xab}; +const Octet16 BTM_GetDeviceEncRoot::return_value{0xd5, 0xcb, 0x84, 0x54, 0xd1, 0x77, 0x73, 0x3e, + 0xff, 0xff, 0xb2, 0xec, 0x71, 0x2b, 0xae, 0xab}; +const Octet16 BTM_GetDeviceIDRoot::return_value{0xd5, 0xcb, 0x84, 0x54, 0xd1, 0x77, 0x73, 0x3e, + 0xff, 0xff, 0xb2, 0xec, 0x71, 0x2b, 0xae, 0xab}; bool BTM_ReadConnectedTransportAddress::return_value = false; tBTM_STATUS BTM_SetBleDataLength::return_value = 0; bool BTM_UseLeLink::return_value = false; @@ -129,29 +125,25 @@ void BTM_BleConfirmReply(const RawAddress& bd_addr, uint8_t res) { inc_func_call_count(__func__); test::mock::stack_btm_ble::BTM_BleConfirmReply(bd_addr, res); } -bool BTM_BleDataSignature(const RawAddress& bd_addr, uint8_t* p_text, - uint16_t len, BLE_SIGNATURE signature) { +bool BTM_BleDataSignature(const RawAddress& bd_addr, uint8_t* p_text, uint16_t len, + BLE_SIGNATURE signature) { inc_func_call_count(__func__); - return test::mock::stack_btm_ble::BTM_BleDataSignature(bd_addr, p_text, len, - signature); + return test::mock::stack_btm_ble::BTM_BleDataSignature(bd_addr, p_text, len, signature); } void BTM_BleLoadLocalKeys(uint8_t key_type, tBTM_BLE_LOCAL_KEYS* p_key) { inc_func_call_count(__func__); test::mock::stack_btm_ble::BTM_BleLoadLocalKeys(key_type, p_key); } -void BTM_BleOobDataReply(const RawAddress& bd_addr, uint8_t res, uint8_t len, - uint8_t* p_data) { +void BTM_BleOobDataReply(const RawAddress& bd_addr, uint8_t res, uint8_t len, uint8_t* p_data) { inc_func_call_count(__func__); test::mock::stack_btm_ble::BTM_BleOobDataReply(bd_addr, res, len, p_data); } -void BTM_BlePasskeyReply(const RawAddress& bd_addr, uint8_t res, - uint32_t passkey) { +void BTM_BlePasskeyReply(const RawAddress& bd_addr, uint8_t res, uint32_t passkey) { inc_func_call_count(__func__); test::mock::stack_btm_ble::BTM_BlePasskeyReply(bd_addr, res, passkey); } -void BTM_BleReadPhy( - const RawAddress& bd_addr, - base::Callback cb) { +void BTM_BleReadPhy(const RawAddress& bd_addr, + base::Callback cb) { inc_func_call_count(__func__); test::mock::stack_btm_ble::BTM_BleReadPhy(bd_addr, cb); } @@ -159,43 +151,36 @@ void BTM_BleReceiverTest(uint8_t rx_freq, tBTM_CMPL_CB* p_cmd_cmpl_cback) { inc_func_call_count(__func__); test::mock::stack_btm_ble::BTM_BleReceiverTest(rx_freq, p_cmd_cmpl_cback); } -void BTM_BleSecureConnectionOobDataReply(const RawAddress& bd_addr, - uint8_t* p_c, uint8_t* p_r) { +void BTM_BleSecureConnectionOobDataReply(const RawAddress& bd_addr, uint8_t* p_c, uint8_t* p_r) { inc_func_call_count(__func__); - test::mock::stack_btm_ble::BTM_BleSecureConnectionOobDataReply(bd_addr, p_c, - p_r); + test::mock::stack_btm_ble::BTM_BleSecureConnectionOobDataReply(bd_addr, p_c, p_r); } void BTM_BleSetPhy(const RawAddress& bd_addr, uint8_t tx_phys, uint8_t rx_phys, uint16_t phy_options) { inc_func_call_count(__func__); - test::mock::stack_btm_ble::BTM_BleSetPhy(bd_addr, tx_phys, rx_phys, - phy_options); + test::mock::stack_btm_ble::BTM_BleSetPhy(bd_addr, tx_phys, rx_phys, phy_options); } void BTM_BleSetPrefConnParams(const RawAddress& bd_addr, uint16_t min_conn_int, - uint16_t max_conn_int, - uint16_t peripheral_latency, + uint16_t max_conn_int, uint16_t peripheral_latency, uint16_t supervision_tout) { inc_func_call_count(__func__); - test::mock::stack_btm_ble::BTM_BleSetPrefConnParams( - bd_addr, min_conn_int, max_conn_int, peripheral_latency, - supervision_tout); + test::mock::stack_btm_ble::BTM_BleSetPrefConnParams(bd_addr, min_conn_int, max_conn_int, + peripheral_latency, supervision_tout); } void BTM_BleTestEnd(tBTM_CMPL_CB* p_cmd_cmpl_cback) { inc_func_call_count(__func__); test::mock::stack_btm_ble::BTM_BleTestEnd(p_cmd_cmpl_cback); } -void BTM_BleTransmitterTest(uint8_t tx_freq, uint8_t test_data_len, - uint8_t packet_payload, +void BTM_BleTransmitterTest(uint8_t tx_freq, uint8_t test_data_len, uint8_t packet_payload, tBTM_CMPL_CB* p_cmd_cmpl_cback) { inc_func_call_count(__func__); - test::mock::stack_btm_ble::BTM_BleTransmitterTest( - tx_freq, test_data_len, packet_payload, p_cmd_cmpl_cback); + test::mock::stack_btm_ble::BTM_BleTransmitterTest(tx_freq, test_data_len, packet_payload, + p_cmd_cmpl_cback); } -bool BTM_BleVerifySignature(const RawAddress& bd_addr, uint8_t* p_orig, - uint16_t len, uint32_t counter, uint8_t* p_comp) { +bool BTM_BleVerifySignature(const RawAddress& bd_addr, uint8_t* p_orig, uint16_t len, + uint32_t counter, uint8_t* p_comp) { inc_func_call_count(__func__); - return test::mock::stack_btm_ble::BTM_BleVerifySignature(bd_addr, p_orig, len, - counter, p_comp); + return test::mock::stack_btm_ble::BTM_BleVerifySignature(bd_addr, p_orig, len, counter, p_comp); } const Octet16& BTM_GetDeviceDHK() { inc_func_call_count(__func__); @@ -209,17 +194,14 @@ const Octet16& BTM_GetDeviceIDRoot() { inc_func_call_count(__func__); return test::mock::stack_btm_ble::BTM_GetDeviceIDRoot(); } -bool BTM_ReadConnectedTransportAddress(RawAddress* remote_bda, - tBT_TRANSPORT transport) { +bool BTM_ReadConnectedTransportAddress(RawAddress* remote_bda, tBT_TRANSPORT transport) { inc_func_call_count(__func__); - return test::mock::stack_btm_ble::BTM_ReadConnectedTransportAddress( - remote_bda, transport); + return test::mock::stack_btm_ble::BTM_ReadConnectedTransportAddress(remote_bda, transport); } void BTM_ReadDevInfo(const RawAddress& remote_bda, tBT_DEVICE_TYPE* p_dev_type, tBLE_ADDR_TYPE* p_addr_type) { inc_func_call_count(__func__); - test::mock::stack_btm_ble::BTM_ReadDevInfo(remote_bda, p_dev_type, - p_addr_type); + test::mock::stack_btm_ble::BTM_ReadDevInfo(remote_bda, p_dev_type, p_addr_type); } bool BTM_GetRemoteDeviceName(const RawAddress& bd_addr, BD_NAME bd_name) { inc_func_call_count(__func__); @@ -239,53 +221,44 @@ void BTM_SecurityGrant(const RawAddress& bd_addr, uint8_t res) { inc_func_call_count(__func__); test::mock::stack_btm_ble::BTM_SecurityGrant(bd_addr, res); } -tBTM_STATUS BTM_SetBleDataLength(const RawAddress& bd_addr, - uint16_t tx_pdu_length) { +tBTM_STATUS BTM_SetBleDataLength(const RawAddress& bd_addr, uint16_t tx_pdu_length) { inc_func_call_count(__func__); - return test::mock::stack_btm_ble::BTM_SetBleDataLength(bd_addr, - tx_pdu_length); + return test::mock::stack_btm_ble::BTM_SetBleDataLength(bd_addr, tx_pdu_length); } bool BTM_UseLeLink(const RawAddress& bd_addr) { inc_func_call_count(__func__); return test::mock::stack_btm_ble::BTM_UseLeLink(bd_addr); } -void btm_ble_connected(const RawAddress& bda, uint16_t handle, uint8_t enc_mode, - uint8_t role, tBLE_ADDR_TYPE addr_type, - bool addr_matched, +void btm_ble_connected(const RawAddress& bda, uint16_t handle, uint8_t enc_mode, uint8_t role, + tBLE_ADDR_TYPE addr_type, bool addr_matched, bool can_read_discoverable_characteristics) { inc_func_call_count(__func__); - test::mock::stack_btm_ble::btm_ble_connected( - bda, handle, enc_mode, role, addr_type, addr_matched, - can_read_discoverable_characteristics); + test::mock::stack_btm_ble::btm_ble_connected(bda, handle, enc_mode, role, addr_type, addr_matched, + can_read_discoverable_characteristics); } bool btm_ble_get_acl_remote_addr(uint16_t hci_handle, RawAddress& conn_addr, tBLE_ADDR_TYPE* p_addr_type) { inc_func_call_count(__func__); - return test::mock::stack_btm_ble::btm_ble_get_acl_remote_addr( - hci_handle, conn_addr, p_addr_type); + return test::mock::stack_btm_ble::btm_ble_get_acl_remote_addr(hci_handle, conn_addr, p_addr_type); } bool btm_ble_get_enc_key_type(const RawAddress& bd_addr, uint8_t* p_key_types) { inc_func_call_count(__func__); - return test::mock::stack_btm_ble::btm_ble_get_enc_key_type(bd_addr, - p_key_types); + return test::mock::stack_btm_ble::btm_ble_get_enc_key_type(bd_addr, p_key_types); } void btm_ble_link_encrypted(const RawAddress& bd_addr, uint8_t encr_enable) { inc_func_call_count(__func__); test::mock::stack_btm_ble::btm_ble_link_encrypted(bd_addr, encr_enable); } -void btm_ble_link_sec_check(const RawAddress& bd_addr, - tBTM_LE_AUTH_REQ auth_req, +void btm_ble_link_sec_check(const RawAddress& bd_addr, tBTM_LE_AUTH_REQ auth_req, tBTM_BLE_SEC_REQ_ACT* p_sec_req_act) { inc_func_call_count(__func__); - test::mock::stack_btm_ble::btm_ble_link_sec_check(bd_addr, auth_req, - p_sec_req_act); + test::mock::stack_btm_ble::btm_ble_link_sec_check(bd_addr, auth_req, p_sec_req_act); } void btm_ble_ltk_request(uint16_t handle, BT_OCTET8 rand, uint16_t ediv) { inc_func_call_count(__func__); test::mock::stack_btm_ble::btm_ble_ltk_request(handle, rand, ediv); } -void btm_ble_ltk_request_reply(const RawAddress& bda, bool use_stk, - const Octet16& stk) { +void btm_ble_ltk_request_reply(const RawAddress& bda, bool use_stk, const Octet16& stk) { inc_func_call_count(__func__); test::mock::stack_btm_ble::btm_ble_ltk_request_reply(bda, use_stk, stk); } @@ -297,12 +270,10 @@ void btm_ble_reset_id(void) { inc_func_call_count(__func__); test::mock::stack_btm_ble::btm_ble_reset_id(); } -tBTM_STATUS btm_ble_set_encryption(const RawAddress& bd_addr, - tBTM_BLE_SEC_ACT sec_act, +tBTM_STATUS btm_ble_set_encryption(const RawAddress& bd_addr, tBTM_BLE_SEC_ACT sec_act, uint8_t link_role) { inc_func_call_count(__func__); - return test::mock::stack_btm_ble::btm_ble_set_encryption(bd_addr, sec_act, - link_role); + return test::mock::stack_btm_ble::btm_ble_set_encryption(bd_addr, sec_act, link_role); } void btm_ble_set_keep_rfu_in_auth_req(bool keep_rfu) { inc_func_call_count(__func__); @@ -312,35 +283,29 @@ void btm_ble_set_no_disc_if_pair_fail(bool disable_disc) { inc_func_call_count(__func__); test::mock::stack_btm_ble::btm_ble_set_no_disc_if_pair_fail(disable_disc); } -void btm_ble_set_test_local_sign_cntr_value(bool enable, - uint32_t test_local_sign_cntr) { +void btm_ble_set_test_local_sign_cntr_value(bool enable, uint32_t test_local_sign_cntr) { inc_func_call_count(__func__); - test::mock::stack_btm_ble::btm_ble_set_test_local_sign_cntr_value( - enable, test_local_sign_cntr); + test::mock::stack_btm_ble::btm_ble_set_test_local_sign_cntr_value(enable, test_local_sign_cntr); } void btm_ble_set_test_mac_value(bool enable, uint8_t* p_test_mac_val) { inc_func_call_count(__func__); test::mock::stack_btm_ble::btm_ble_set_test_mac_value(enable, p_test_mac_val); } -tBTM_STATUS btm_ble_start_encrypt(const RawAddress& bda, bool use_stk, - Octet16* p_stk) { +tBTM_STATUS btm_ble_start_encrypt(const RawAddress& bda, bool use_stk, Octet16* p_stk) { inc_func_call_count(__func__); return test::mock::stack_btm_ble::btm_ble_start_encrypt(bda, use_stk, p_stk); } -tBTM_STATUS btm_ble_start_sec_check(const RawAddress& bd_addr, uint16_t psm, - bool is_originator, - tBTM_SEC_CALLBACK* p_callback, - void* p_ref_data) { +tBTM_STATUS btm_ble_start_sec_check(const RawAddress& bd_addr, uint16_t psm, bool is_originator, + tBTM_SEC_CALLBACK* p_callback, void* p_ref_data) { inc_func_call_count(__func__); - return test::mock::stack_btm_ble::btm_ble_start_sec_check( - bd_addr, psm, is_originator, p_callback, p_ref_data); + return test::mock::stack_btm_ble::btm_ble_start_sec_check(bd_addr, psm, is_originator, p_callback, + p_ref_data); } void btm_ble_test_command_complete(uint8_t* p) { inc_func_call_count(__func__); test::mock::stack_btm_ble::btm_ble_test_command_complete(p); } -void btm_ble_update_sec_key_size(const RawAddress& bd_addr, - uint8_t enc_key_size) { +void btm_ble_update_sec_key_size(const RawAddress& bd_addr, uint8_t enc_key_size) { inc_func_call_count(__func__); test::mock::stack_btm_ble::btm_ble_update_sec_key_size(bd_addr, enc_key_size); } @@ -356,22 +321,18 @@ tBTM_STATUS btm_proc_smp_cback(tSMP_EVT event, const RawAddress& bd_addr, void btm_sec_save_le_key(const RawAddress& bd_addr, tBTM_LE_KEY_TYPE key_type, tBTM_LE_KEY_VALUE* p_keys, bool pass_to_application) { inc_func_call_count(__func__); - test::mock::stack_btm_ble::btm_sec_save_le_key(bd_addr, key_type, p_keys, - pass_to_application); + test::mock::stack_btm_ble::btm_sec_save_le_key(bd_addr, key_type, p_keys, pass_to_application); } void doNothing(uint8_t* data, uint16_t len) { inc_func_call_count(__func__); test::mock::stack_btm_ble::doNothing(data, len); } -void read_phy_cb( - base::Callback cb, - uint8_t* data, uint16_t len) { +void read_phy_cb(base::Callback cb, + uint8_t* data, uint16_t len) { inc_func_call_count(__func__); test::mock::stack_btm_ble::read_phy_cb(cb, data, len); } // Mocked functions complete // END mockcify generation -std::optional BTM_BleGetPeerLTK(const RawAddress /* address */) { - return std::nullopt; -} +std::optional BTM_BleGetPeerLTK(const RawAddress /* address */) { return std::nullopt; } diff --git a/system/test/mock/mock_stack_btm_ble.h b/system/test/mock/mock_stack_btm_ble.h index e31a5b7508a..3a2096b9eed 100644 --- a/system/test/mock/mock_stack_btm_ble.h +++ b/system/test/mock/mock_stack_btm_ble.h @@ -55,10 +55,8 @@ namespace stack_btm_ble { // Return: void struct BTM_BleConfirmReply { std::function body{ - [](const RawAddress& /* bd_addr */, uint8_t /* res */) {}}; - void operator()(const RawAddress& bd_addr, uint8_t res) { - body(bd_addr, res); - }; + [](const RawAddress& /* bd_addr */, uint8_t /* res */) {}}; + void operator()(const RawAddress& bd_addr, uint8_t res) { body(bd_addr, res); } }; extern struct BTM_BleConfirmReply BTM_BleConfirmReply; @@ -69,13 +67,12 @@ struct BTM_BleDataSignature { static bool return_value; std::function - body{[](const RawAddress& /* bd_addr */, uint8_t* /* p_text */, - uint16_t /* len */, - BLE_SIGNATURE /* signature */) { return return_value; }}; + body{[](const RawAddress& /* bd_addr */, uint8_t* /* p_text */, uint16_t /* len */, + BLE_SIGNATURE /* signature */) { return return_value; }}; bool operator()(const RawAddress& bd_addr, uint8_t* p_text, uint16_t len, BLE_SIGNATURE signature) { return body(bd_addr, p_text, len, signature); - }; + } }; extern struct BTM_BleDataSignature BTM_BleDataSignature; @@ -84,10 +81,8 @@ extern struct BTM_BleDataSignature BTM_BleDataSignature; // Return: void struct BTM_BleLoadLocalKeys { std::function body{ - [](uint8_t /* key_type */, tBTM_BLE_LOCAL_KEYS* /* p_key */) {}}; - void operator()(uint8_t key_type, tBTM_BLE_LOCAL_KEYS* p_key) { - body(key_type, p_key); - }; + [](uint8_t /* key_type */, tBTM_BLE_LOCAL_KEYS* /* p_key */) {}}; + void operator()(uint8_t key_type, tBTM_BLE_LOCAL_KEYS* p_key) { body(key_type, p_key); } }; extern struct BTM_BleLoadLocalKeys BTM_BleLoadLocalKeys; @@ -95,14 +90,12 @@ extern struct BTM_BleLoadLocalKeys BTM_BleLoadLocalKeys; // Params: const RawAddress& bd_addr, uint8_t res, uint8_t len, uint8_t* p_data // Return: void struct BTM_BleOobDataReply { - std::function - body{[](const RawAddress& /* bd_addr */, uint8_t /* res */, - uint8_t /* len */, uint8_t* /* p_data */) {}}; - void operator()(const RawAddress& bd_addr, uint8_t res, uint8_t len, - uint8_t* p_data) { + std::function body{ + [](const RawAddress& /* bd_addr */, uint8_t /* res */, uint8_t /* len */, + uint8_t* /* p_data */) {}}; + void operator()(const RawAddress& bd_addr, uint8_t res, uint8_t len, uint8_t* p_data) { body(bd_addr, res, len, p_data); - }; + } }; extern struct BTM_BleOobDataReply BTM_BleOobDataReply; @@ -110,12 +103,11 @@ extern struct BTM_BleOobDataReply BTM_BleOobDataReply; // Params: const RawAddress& bd_addr, uint8_t res, uint32_t passkey // Return: void struct BTM_BlePasskeyReply { - std::function - body{[](const RawAddress& /* bd_addr */, uint8_t /* res */, - uint32_t /* passkey */) {}}; + std::function body{ + [](const RawAddress& /* bd_addr */, uint8_t /* res */, uint32_t /* passkey */) {}}; void operator()(const RawAddress& bd_addr, uint8_t res, uint32_t passkey) { body(bd_addr, res, passkey); - }; + } }; extern struct BTM_BlePasskeyReply BTM_BlePasskeyReply; @@ -123,20 +115,15 @@ extern struct BTM_BlePasskeyReply BTM_BlePasskeyReply; // Params: const RawAddress& bd_addr, base::Callback - callback)> - body{[](const RawAddress& /* bd_addr */, - base::Callback - /* callback */) {}}; - void operator()( - const RawAddress& bd_addr, - base::Callback - callback) { + std::function callback)> + body{[](const RawAddress& /* bd_addr */, + base::Callback + /* callback */) {}}; + void operator()(const RawAddress& bd_addr, + base::Callback callback) { body(bd_addr, callback); - }; + } }; extern struct BTM_BleReadPhy BTM_BleReadPhy; @@ -145,10 +132,10 @@ extern struct BTM_BleReadPhy BTM_BleReadPhy; // Return: void struct BTM_BleReceiverTest { std::function body{ - [](uint8_t /* rx_freq */, tBTM_CMPL_CB* /* p_cmd_cmpl_cback */) {}}; + [](uint8_t /* rx_freq */, tBTM_CMPL_CB* /* p_cmd_cmpl_cback */) {}}; void operator()(uint8_t rx_freq, tBTM_CMPL_CB* p_cmd_cmpl_cback) { body(rx_freq, p_cmd_cmpl_cback); - }; + } }; extern struct BTM_BleReceiverTest BTM_BleReceiverTest; @@ -156,28 +143,26 @@ extern struct BTM_BleReceiverTest BTM_BleReceiverTest; // Params: const RawAddress& bd_addr, uint8_t* p_c, uint8_t* p_r // Return: void struct BTM_BleSecureConnectionOobDataReply { - std::function - body{[](const RawAddress& /* bd_addr */, uint8_t* /* p_c */, - uint8_t* /* p_r */) {}}; + std::function body{ + [](const RawAddress& /* bd_addr */, uint8_t* /* p_c */, uint8_t* /* p_r */) {}}; void operator()(const RawAddress& bd_addr, uint8_t* p_c, uint8_t* p_r) { body(bd_addr, p_c, p_r); - }; + } }; -extern struct BTM_BleSecureConnectionOobDataReply - BTM_BleSecureConnectionOobDataReply; +extern struct BTM_BleSecureConnectionOobDataReply BTM_BleSecureConnectionOobDataReply; // Name: BTM_BleSetPhy // Params: const RawAddress& bd_addr, uint8_t tx_phys, uint8_t rx_phys, uint16_t // phy_options Return: void struct BTM_BleSetPhy { - std::function - body{[](const RawAddress& /* bd_addr */, uint8_t /* tx_phys */, - uint8_t /* rx_phys */, uint16_t /* phy_options */) {}}; + std::function + body{[](const RawAddress& /* bd_addr */, uint8_t /* tx_phys */, uint8_t /* rx_phys */, + uint16_t /* phy_options */) {}}; void operator()(const RawAddress& bd_addr, uint8_t tx_phys, uint8_t rx_phys, uint16_t phy_options) { body(bd_addr, tx_phys, rx_phys, phy_options); - }; + } }; extern struct BTM_BleSetPhy BTM_BleSetPhy; @@ -186,18 +171,15 @@ extern struct BTM_BleSetPhy BTM_BleSetPhy; // max_conn_int, uint16_t peripheral_latency, uint16_t supervision_tout Return: // void struct BTM_BleSetPrefConnParams { - std::function - body{[](const RawAddress& /* bd_addr */, uint16_t /* min_conn_int */, - uint16_t /* max_conn_int */, uint16_t /* peripheral_latency */, - uint16_t /* supervision_tout */) {}}; - void operator()(const RawAddress& bd_addr, uint16_t min_conn_int, - uint16_t max_conn_int, uint16_t peripheral_latency, - uint16_t supervision_tout) { - body(bd_addr, min_conn_int, max_conn_int, peripheral_latency, - supervision_tout); - }; + std::function + body{[](const RawAddress& /* bd_addr */, uint16_t /* min_conn_int */, + uint16_t /* max_conn_int */, uint16_t /* peripheral_latency */, + uint16_t /* supervision_tout */) {}}; + void operator()(const RawAddress& bd_addr, uint16_t min_conn_int, uint16_t max_conn_int, + uint16_t peripheral_latency, uint16_t supervision_tout) { + body(bd_addr, min_conn_int, max_conn_int, peripheral_latency, supervision_tout); + } }; extern struct BTM_BleSetPrefConnParams BTM_BleSetPrefConnParams; @@ -206,8 +188,8 @@ extern struct BTM_BleSetPrefConnParams BTM_BleSetPrefConnParams; // Return: void struct BTM_BleTestEnd { std::function body{ - [](tBTM_CMPL_CB* /* p_cmd_cmpl_cback */) {}}; - void operator()(tBTM_CMPL_CB* p_cmd_cmpl_cback) { body(p_cmd_cmpl_cback); }; + [](tBTM_CMPL_CB* /* p_cmd_cmpl_cback */) {}}; + void operator()(tBTM_CMPL_CB* p_cmd_cmpl_cback) { body(p_cmd_cmpl_cback); } }; extern struct BTM_BleTestEnd BTM_BleTestEnd; @@ -215,15 +197,14 @@ extern struct BTM_BleTestEnd BTM_BleTestEnd; // Params: uint8_t tx_freq, uint8_t test_data_len, uint8_t packet_payload, // tBTM_CMPL_CB* p_cmd_cmpl_cback Return: void struct BTM_BleTransmitterTest { - std::function - body{[](uint8_t /* tx_freq */, uint8_t /* test_data_len */, - uint8_t /* packet_payload */, - tBTM_CMPL_CB* /* p_cmd_cmpl_cback */) {}}; - void operator()(uint8_t tx_freq, uint8_t test_data_len, - uint8_t packet_payload, tBTM_CMPL_CB* p_cmd_cmpl_cback) { + std::function + body{[](uint8_t /* tx_freq */, uint8_t /* test_data_len */, uint8_t /* packet_payload */, + tBTM_CMPL_CB* /* p_cmd_cmpl_cback */) {}}; + void operator()(uint8_t tx_freq, uint8_t test_data_len, uint8_t packet_payload, + tBTM_CMPL_CB* p_cmd_cmpl_cback) { body(tx_freq, test_data_len, packet_payload, p_cmd_cmpl_cback); - }; + } }; extern struct BTM_BleTransmitterTest BTM_BleTransmitterTest; @@ -232,15 +213,14 @@ extern struct BTM_BleTransmitterTest BTM_BleTransmitterTest; // counter, uint8_t* p_comp Return: bool struct BTM_BleVerifySignature { static bool return_value; - std::function - body{[](const RawAddress& /* bd_addr */, uint8_t* /* p_orig */, - uint16_t /* len */, uint32_t /* counter */, - uint8_t* /* p_comp */) { return return_value; }}; - bool operator()(const RawAddress& bd_addr, uint8_t* p_orig, uint16_t len, - uint32_t counter, uint8_t* p_comp) { + std::function + body{[](const RawAddress& /* bd_addr */, uint8_t* /* p_orig */, uint16_t /* len */, + uint32_t /* counter */, uint8_t* /* p_comp */) { return return_value; }}; + bool operator()(const RawAddress& bd_addr, uint8_t* p_orig, uint16_t len, uint32_t counter, + uint8_t* p_comp) { return body(bd_addr, p_orig, len, counter, p_comp); - }; + } }; extern struct BTM_BleVerifySignature BTM_BleVerifySignature; @@ -250,9 +230,9 @@ extern struct BTM_BleVerifySignature BTM_BleVerifySignature; struct BTM_GetDeviceDHK { static const Octet16 return_value; std::function body{ - // Explicit return type is needed otherwise it returns copy of object - []() -> const Octet16& { return return_value; }}; - const Octet16& operator()() { return body(); }; + // Explicit return type is needed otherwise it returns copy of object + []() -> const Octet16& { return return_value; }}; + const Octet16& operator()() { return body(); } }; extern struct BTM_GetDeviceDHK BTM_GetDeviceDHK; @@ -262,9 +242,9 @@ extern struct BTM_GetDeviceDHK BTM_GetDeviceDHK; struct BTM_GetDeviceEncRoot { static const Octet16 return_value; std::function body{ - // Explicit return type is needed otherwise it returns copy of object - []() -> const Octet16& { return return_value; }}; - const Octet16& operator()() { return body(); }; + // Explicit return type is needed otherwise it returns copy of object + []() -> const Octet16& { return return_value; }}; + const Octet16& operator()() { return body(); } }; extern struct BTM_GetDeviceEncRoot BTM_GetDeviceEncRoot; @@ -274,9 +254,9 @@ extern struct BTM_GetDeviceEncRoot BTM_GetDeviceEncRoot; struct BTM_GetDeviceIDRoot { static const Octet16 return_value; std::function body{ - // Explicit return type is needed otherwise it returns copy of object - []() -> const Octet16& { return return_value; }}; - const Octet16& operator()() { return body(); }; + // Explicit return type is needed otherwise it returns copy of object + []() -> const Octet16& { return return_value; }}; + const Octet16& operator()() { return body(); } }; extern struct BTM_GetDeviceIDRoot BTM_GetDeviceIDRoot; @@ -286,15 +266,12 @@ extern struct BTM_GetDeviceIDRoot BTM_GetDeviceIDRoot; struct BTM_ReadConnectedTransportAddress { static bool return_value; std::function body{ - [](RawAddress* /* remote_bda */, tBT_TRANSPORT /* transport */) { - return return_value; - }}; + [](RawAddress* /* remote_bda */, tBT_TRANSPORT /* transport */) { return return_value; }}; bool operator()(RawAddress* remote_bda, tBT_TRANSPORT transport) { return body(remote_bda, transport); - }; + } }; -extern struct BTM_ReadConnectedTransportAddress - BTM_ReadConnectedTransportAddress; +extern struct BTM_ReadConnectedTransportAddress BTM_ReadConnectedTransportAddress; // Name: BTM_ReadDevInfo // Params: const RawAddress& remote_bda, tBT_DEVICE_TYPE* p_dev_type, @@ -302,13 +279,12 @@ extern struct BTM_ReadConnectedTransportAddress struct BTM_ReadDevInfo { std::function - body{[](const RawAddress& /* remote_bda */, - tBT_DEVICE_TYPE* /* p_dev_type */, - tBLE_ADDR_TYPE* /* p_addr_type */) {}}; + body{[](const RawAddress& /* remote_bda */, tBT_DEVICE_TYPE* /* p_dev_type */, + tBLE_ADDR_TYPE* /* p_addr_type */) {}}; void operator()(const RawAddress& remote_bda, tBT_DEVICE_TYPE* p_dev_type, tBLE_ADDR_TYPE* p_addr_type) { body(remote_bda, p_dev_type, p_addr_type); - }; + } }; extern struct BTM_ReadDevInfo BTM_ReadDevInfo; @@ -316,14 +292,12 @@ extern struct BTM_ReadDevInfo BTM_ReadDevInfo; // Params: const RawAddress& bd_addr, tBT_DEVICE_TYPE dev_type, tBLE_ADDR_TYPE // addr_type Return: void struct BTM_SecAddBleDevice { - std::function - body{[](const RawAddress& /* bd_addr */, tBT_DEVICE_TYPE /* dev_type */, - tBLE_ADDR_TYPE /* addr_type */) {}}; - void operator()(const RawAddress& bd_addr, tBT_DEVICE_TYPE dev_type, - tBLE_ADDR_TYPE addr_type) { + std::function + body{[](const RawAddress& /* bd_addr */, tBT_DEVICE_TYPE /* dev_type */, + tBLE_ADDR_TYPE /* addr_type */) {}}; + void operator()(const RawAddress& bd_addr, tBT_DEVICE_TYPE dev_type, tBLE_ADDR_TYPE addr_type) { body(bd_addr, dev_type, addr_type); - }; + } }; extern struct BTM_SecAddBleDevice BTM_SecAddBleDevice; @@ -333,12 +307,8 @@ extern struct BTM_SecAddBleDevice BTM_SecAddBleDevice; struct BTM_GetRemoteDeviceName { static bool return_value; std::function body{ - [](const RawAddress& /* bd_addr */, BD_NAME /* bd_name */) { - return return_value; - }}; - bool operator()(const RawAddress& bd_addr, BD_NAME bd_name) { - return body(bd_addr, bd_name); - }; + [](const RawAddress& /* bd_addr */, BD_NAME /* bd_name */) { return return_value; }}; + bool operator()(const RawAddress& bd_addr, BD_NAME bd_name) { return body(bd_addr, bd_name); } }; extern struct BTM_GetRemoteDeviceName BTM_GetRemoteDeviceName; @@ -348,13 +318,12 @@ extern struct BTM_GetRemoteDeviceName BTM_GetRemoteDeviceName; struct BTM_SecAddBleKey { std::function - body{[](const RawAddress& /* bd_addr */, - tBTM_LE_KEY_VALUE* /* p_le_key */, - tBTM_LE_KEY_TYPE /* key_type */) {}}; + body{[](const RawAddress& /* bd_addr */, tBTM_LE_KEY_VALUE* /* p_le_key */, + tBTM_LE_KEY_TYPE /* key_type */) {}}; void operator()(const RawAddress& bd_addr, tBTM_LE_KEY_VALUE* p_le_key, tBTM_LE_KEY_TYPE key_type) { body(bd_addr, p_le_key, key_type); - }; + } }; extern struct BTM_SecAddBleKey BTM_SecAddBleKey; @@ -363,10 +332,8 @@ extern struct BTM_SecAddBleKey BTM_SecAddBleKey; // Return: void struct BTM_SecurityGrant { std::function body{ - [](const RawAddress& /* bd_addr */, uint8_t /* res */) {}}; - void operator()(const RawAddress& bd_addr, uint8_t res) { - body(bd_addr, res); - }; + [](const RawAddress& /* bd_addr */, uint8_t /* res */) {}}; + void operator()(const RawAddress& bd_addr, uint8_t res) { body(bd_addr, res); } }; extern struct BTM_SecurityGrant BTM_SecurityGrant; @@ -375,13 +342,13 @@ extern struct BTM_SecurityGrant BTM_SecurityGrant; // Return: tBTM_STATUS struct BTM_SetBleDataLength { static tBTM_STATUS return_value; - std::function - body{[](const RawAddress& /* bd_addr */, uint16_t /* tx_pdu_length */) { - return return_value; - }}; + std::function body{ + [](const RawAddress& /* bd_addr */, uint16_t /* tx_pdu_length */) { + return return_value; + }}; tBTM_STATUS operator()(const RawAddress& bd_addr, uint16_t tx_pdu_length) { return body(bd_addr, tx_pdu_length); - }; + } }; extern struct BTM_SetBleDataLength BTM_SetBleDataLength; @@ -391,8 +358,8 @@ extern struct BTM_SetBleDataLength BTM_SetBleDataLength; struct BTM_UseLeLink { static bool return_value; std::function body{ - [](const RawAddress& /* bd_addr */) { return return_value; }}; - bool operator()(const RawAddress& bd_addr) { return body(bd_addr); }; + [](const RawAddress& /* bd_addr */) { return return_value; }}; + bool operator()(const RawAddress& bd_addr) { return body(bd_addr); } }; extern struct BTM_UseLeLink BTM_UseLeLink; @@ -400,19 +367,18 @@ extern struct BTM_UseLeLink BTM_UseLeLink; // Params: const RawAddress& bda, uint16_t handle, uint8_t enc_mode, uint8_t // role, tBLE_ADDR_TYPE addr_type, bool addr_matched Return: void struct btm_ble_connected { - std::function - body{[](const RawAddress& /* bda */, uint16_t /* handle */, - uint8_t /* enc_mode */, uint8_t /* role */, - tBLE_ADDR_TYPE /* addr_type */, bool /* addr_matched */, - bool /* can_read_discoverable_characteristics */) {}}; - void operator()(const RawAddress& bda, uint16_t handle, uint8_t enc_mode, - uint8_t role, tBLE_ADDR_TYPE addr_type, bool addr_matched, + body{[](const RawAddress& /* bda */, uint16_t /* handle */, uint8_t /* enc_mode */, + uint8_t /* role */, tBLE_ADDR_TYPE /* addr_type */, bool /* addr_matched */, + bool /* can_read_discoverable_characteristics */) {}}; + void operator()(const RawAddress& bda, uint16_t handle, uint8_t enc_mode, uint8_t role, + tBLE_ADDR_TYPE addr_type, bool addr_matched, bool can_read_discoverable_characteristics) { body(bda, handle, enc_mode, role, addr_type, addr_matched, can_read_discoverable_characteristics); - }; + } }; extern struct btm_ble_connected btm_ble_connected; @@ -421,14 +387,12 @@ extern struct btm_ble_connected btm_ble_connected; // p_addr_type Return: bool struct btm_ble_get_acl_remote_addr { static bool return_value; - std::function - body{[](uint16_t /* hci_handle */, RawAddress& /* conn_addr */, - tBLE_ADDR_TYPE* /* p_addr_type */) { return return_value; }}; - bool operator()(uint16_t hci_handle, RawAddress& conn_addr, - tBLE_ADDR_TYPE* p_addr_type) { + std::function body{ + [](uint16_t /* hci_handle */, RawAddress& /* conn_addr */, + tBLE_ADDR_TYPE* /* p_addr_type */) { return return_value; }}; + bool operator()(uint16_t hci_handle, RawAddress& conn_addr, tBLE_ADDR_TYPE* p_addr_type) { return body(hci_handle, conn_addr, p_addr_type); - }; + } }; extern struct btm_ble_get_acl_remote_addr btm_ble_get_acl_remote_addr; @@ -438,12 +402,10 @@ extern struct btm_ble_get_acl_remote_addr btm_ble_get_acl_remote_addr; struct btm_ble_get_enc_key_type { static bool return_value; std::function body{ - [](const RawAddress& /* bd_addr */, uint8_t* /* p_key_types */) { - return return_value; - }}; + [](const RawAddress& /* bd_addr */, uint8_t* /* p_key_types */) { return return_value; }}; bool operator()(const RawAddress& bd_addr, uint8_t* p_key_types) { return body(bd_addr, p_key_types); - }; + } }; extern struct btm_ble_get_enc_key_type btm_ble_get_enc_key_type; @@ -452,10 +414,8 @@ extern struct btm_ble_get_enc_key_type btm_ble_get_enc_key_type; // Return: void struct btm_ble_link_encrypted { std::function body{ - [](const RawAddress& /* bd_addr */, uint8_t /* encr_enable */) {}}; - void operator()(const RawAddress& bd_addr, uint8_t encr_enable) { - body(bd_addr, encr_enable); - }; + [](const RawAddress& /* bd_addr */, uint8_t /* encr_enable */) {}}; + void operator()(const RawAddress& bd_addr, uint8_t encr_enable) { body(bd_addr, encr_enable); } }; extern struct btm_ble_link_encrypted btm_ble_link_encrypted; @@ -465,12 +425,12 @@ extern struct btm_ble_link_encrypted btm_ble_link_encrypted; struct btm_ble_link_sec_check { std::function - body{[](const RawAddress& /* bd_addr */, tBTM_LE_AUTH_REQ /* auth_req */, - tBTM_BLE_SEC_REQ_ACT* /* p_sec_req_act */) {}}; + body{[](const RawAddress& /* bd_addr */, tBTM_LE_AUTH_REQ /* auth_req */, + tBTM_BLE_SEC_REQ_ACT* /* p_sec_req_act */) {}}; void operator()(const RawAddress& bd_addr, tBTM_LE_AUTH_REQ auth_req, tBTM_BLE_SEC_REQ_ACT* p_sec_req_act) { body(bd_addr, auth_req, p_sec_req_act); - }; + } }; extern struct btm_ble_link_sec_check btm_ble_link_sec_check; @@ -479,10 +439,8 @@ extern struct btm_ble_link_sec_check btm_ble_link_sec_check; // Return: void struct btm_ble_ltk_request { std::function body{ - [](uint16_t /* handle */, BT_OCTET8 /* rand */, uint16_t /* ediv */) {}}; - void operator()(uint16_t handle, BT_OCTET8 rand, uint16_t ediv) { - body(handle, rand, ediv); - }; + [](uint16_t /* handle */, BT_OCTET8 /* rand */, uint16_t /* ediv */) {}}; + void operator()(uint16_t handle, BT_OCTET8 rand, uint16_t ediv) { body(handle, rand, ediv); } }; extern struct btm_ble_ltk_request btm_ble_ltk_request; @@ -490,12 +448,11 @@ extern struct btm_ble_ltk_request btm_ble_ltk_request; // Params: const RawAddress& bda, bool use_stk, const Octet16& stk // Return: void struct btm_ble_ltk_request_reply { - std::function - body{[](const RawAddress& /* bda */, bool /* use_stk */, - const Octet16& /* stk */) {}}; + std::function body{ + [](const RawAddress& /* bda */, bool /* use_stk */, const Octet16& /* stk */) {}}; void operator()(const RawAddress& bda, bool use_stk, const Octet16& stk) { body(bda, use_stk, stk); - }; + } }; extern struct btm_ble_ltk_request_reply btm_ble_ltk_request_reply; @@ -505,8 +462,8 @@ extern struct btm_ble_ltk_request_reply btm_ble_ltk_request_reply; struct btm_ble_read_sec_key_size { static uint8_t return_value; std::function body{ - [](const RawAddress& /* bd_addr */) { return return_value; }}; - uint8_t operator()(const RawAddress& bd_addr) { return body(bd_addr); }; + [](const RawAddress& /* bd_addr */) { return return_value; }}; + uint8_t operator()(const RawAddress& bd_addr) { return body(bd_addr); } }; extern struct btm_ble_read_sec_key_size btm_ble_read_sec_key_size; @@ -515,7 +472,7 @@ extern struct btm_ble_read_sec_key_size btm_ble_read_sec_key_size; // Return: void struct btm_ble_reset_id { std::function body{[](void) {}}; - void operator()(void) { body(); }; + void operator()(void) { body(); } }; extern struct btm_ble_reset_id btm_ble_reset_id; @@ -524,14 +481,12 @@ extern struct btm_ble_reset_id btm_ble_reset_id; // link_role Return: tBTM_STATUS struct btm_ble_set_encryption { static tBTM_STATUS return_value; - std::function - body{[](const RawAddress& /* bd_addr */, tBTM_BLE_SEC_ACT /* sec_act */, - uint8_t /* link_role */) { return return_value; }}; - tBTM_STATUS operator()(const RawAddress& bd_addr, tBTM_BLE_SEC_ACT sec_act, - uint8_t link_role) { + std::function + body{[](const RawAddress& /* bd_addr */, tBTM_BLE_SEC_ACT /* sec_act */, + uint8_t /* link_role */) { return return_value; }}; + tBTM_STATUS operator()(const RawAddress& bd_addr, tBTM_BLE_SEC_ACT sec_act, uint8_t link_role) { return body(bd_addr, sec_act, link_role); - }; + } }; extern struct btm_ble_set_encryption btm_ble_set_encryption; @@ -540,7 +495,7 @@ extern struct btm_ble_set_encryption btm_ble_set_encryption; // Return: void struct btm_ble_set_keep_rfu_in_auth_req { std::function body{[](bool /* keep_rfu */) {}}; - void operator()(bool keep_rfu) { body(keep_rfu); }; + void operator()(bool keep_rfu) { body(keep_rfu); } }; extern struct btm_ble_set_keep_rfu_in_auth_req btm_ble_set_keep_rfu_in_auth_req; @@ -549,7 +504,7 @@ extern struct btm_ble_set_keep_rfu_in_auth_req btm_ble_set_keep_rfu_in_auth_req; // Return: void struct btm_ble_set_no_disc_if_pair_fail { std::function body{[](bool /* disable_disc */) {}}; - void operator()(bool disable_disc) { body(disable_disc); }; + void operator()(bool disable_disc) { body(disable_disc); } }; extern struct btm_ble_set_no_disc_if_pair_fail btm_ble_set_no_disc_if_pair_fail; @@ -558,23 +513,20 @@ extern struct btm_ble_set_no_disc_if_pair_fail btm_ble_set_no_disc_if_pair_fail; // Return: void struct btm_ble_set_test_local_sign_cntr_value { std::function body{ - [](bool /* enable */, uint32_t /* test_local_sign_cntr */) {}}; + [](bool /* enable */, uint32_t /* test_local_sign_cntr */) {}}; void operator()(bool enable, uint32_t test_local_sign_cntr) { body(enable, test_local_sign_cntr); - }; + } }; -extern struct btm_ble_set_test_local_sign_cntr_value - btm_ble_set_test_local_sign_cntr_value; +extern struct btm_ble_set_test_local_sign_cntr_value btm_ble_set_test_local_sign_cntr_value; // Name: btm_ble_set_test_mac_value // Params: bool enable, uint8_t* p_test_mac_val // Return: void struct btm_ble_set_test_mac_value { std::function body{ - [](bool /* enable */, uint8_t* /* p_test_mac_val */) {}}; - void operator()(bool enable, uint8_t* p_test_mac_val) { - body(enable, p_test_mac_val); - }; + [](bool /* enable */, uint8_t* /* p_test_mac_val */) {}}; + void operator()(bool enable, uint8_t* p_test_mac_val) { body(enable, p_test_mac_val); } }; extern struct btm_ble_set_test_mac_value btm_ble_set_test_mac_value; @@ -583,13 +535,13 @@ extern struct btm_ble_set_test_mac_value btm_ble_set_test_mac_value; // Return: tBTM_STATUS struct btm_ble_start_encrypt { static tBTM_STATUS return_value; - std::function - body{[](const RawAddress& /* bda */, bool /* use_stk */, - Octet16* /* p_stk */) { return return_value; }}; + std::function body{ + [](const RawAddress& /* bda */, bool /* use_stk */, Octet16* /* p_stk */) { + return return_value; + }}; tBTM_STATUS operator()(const RawAddress& bda, bool use_stk, Octet16* p_stk) { return body(bda, use_stk, p_stk); - }; + } }; extern struct btm_ble_start_encrypt btm_ble_start_encrypt; @@ -598,17 +550,15 @@ extern struct btm_ble_start_encrypt btm_ble_start_encrypt; // tBTM_SEC_CALLBACK* p_callback, void* p_ref_data Return: tL2CAP_LE_RESULT_CODE struct btm_ble_start_sec_check { static tBTM_STATUS return_value; - std::function - body{[](const RawAddress& /* bd_addr */, uint16_t /* psm */, - bool /* is_originator */, tBTM_SEC_CALLBACK* /* p_callback */, - void* /* p_ref_data */) { return return_value; }}; - tBTM_STATUS operator()(const RawAddress& bd_addr, uint16_t psm, - bool is_originator, tBTM_SEC_CALLBACK* p_callback, - void* p_ref_data) { + std::function + body{[](const RawAddress& /* bd_addr */, uint16_t /* psm */, bool /* is_originator */, + tBTM_SEC_CALLBACK* /* p_callback */, + void* /* p_ref_data */) { return return_value; }}; + tBTM_STATUS operator()(const RawAddress& bd_addr, uint16_t psm, bool is_originator, + tBTM_SEC_CALLBACK* p_callback, void* p_ref_data) { return body(bd_addr, psm, is_originator, p_callback, p_ref_data); - }; + } }; extern struct btm_ble_start_sec_check btm_ble_start_sec_check; @@ -617,7 +567,7 @@ extern struct btm_ble_start_sec_check btm_ble_start_sec_check; // Return: void struct btm_ble_test_command_complete { std::function body{[](uint8_t* /* p */) {}}; - void operator()(uint8_t* p) { body(p); }; + void operator()(uint8_t* p) { body(p); } }; extern struct btm_ble_test_command_complete btm_ble_test_command_complete; @@ -626,10 +576,8 @@ extern struct btm_ble_test_command_complete btm_ble_test_command_complete; // Return: void struct btm_ble_update_sec_key_size { std::function body{ - [](const RawAddress& /* bd_addr */, uint8_t /* enc_key_size */) {}}; - void operator()(const RawAddress& bd_addr, uint8_t enc_key_size) { - body(bd_addr, enc_key_size); - }; + [](const RawAddress& /* bd_addr */, uint8_t /* enc_key_size */) {}}; + void operator()(const RawAddress& bd_addr, uint8_t enc_key_size) { body(bd_addr, enc_key_size); } }; extern struct btm_ble_update_sec_key_size btm_ble_update_sec_key_size; @@ -639,12 +587,8 @@ extern struct btm_ble_update_sec_key_size btm_ble_update_sec_key_size; struct btm_get_local_div { static bool return_value; std::function body{ - [](const RawAddress& /* bd_addr */, uint16_t* /* p_div */) { - return return_value; - }}; - bool operator()(const RawAddress& bd_addr, uint16_t* p_div) { - return body(bd_addr, p_div); - }; + [](const RawAddress& /* bd_addr */, uint16_t* /* p_div */) { return return_value; }}; + bool operator()(const RawAddress& bd_addr, uint16_t* p_div) { return body(bd_addr, p_div); } }; extern struct btm_get_local_div btm_get_local_div; @@ -653,14 +597,12 @@ extern struct btm_get_local_div btm_get_local_div; // p_data Return: tBTM_STATUS struct btm_proc_smp_cback { static tBTM_STATUS return_value; - std::function - body{[](tSMP_EVT /* event */, const RawAddress& /* bd_addr */, - const tSMP_EVT_DATA* /* p_data */) { return return_value; }}; - tBTM_STATUS operator()(tSMP_EVT event, const RawAddress& bd_addr, - const tSMP_EVT_DATA* p_data) { + std::function + body{[](tSMP_EVT /* event */, const RawAddress& /* bd_addr */, + const tSMP_EVT_DATA* /* p_data */) { return return_value; }}; + tBTM_STATUS operator()(tSMP_EVT event, const RawAddress& bd_addr, const tSMP_EVT_DATA* p_data) { return body(event, bd_addr, p_data); - }; + } }; extern struct btm_proc_smp_cback btm_proc_smp_cback; @@ -670,13 +612,12 @@ extern struct btm_proc_smp_cback btm_proc_smp_cback; struct btm_sec_save_le_key { std::function - body{[](const RawAddress& /* bd_addr */, tBTM_LE_KEY_TYPE /* key_type */, - tBTM_LE_KEY_VALUE* /* p_keys */, - bool /* pass_to_application */) {}}; - void operator()(const RawAddress& bd_addr, tBTM_LE_KEY_TYPE key_type, - tBTM_LE_KEY_VALUE* p_keys, bool pass_to_application) { + body{[](const RawAddress& /* bd_addr */, tBTM_LE_KEY_TYPE /* key_type */, + tBTM_LE_KEY_VALUE* /* p_keys */, bool /* pass_to_application */) {}}; + void operator()(const RawAddress& bd_addr, tBTM_LE_KEY_TYPE key_type, tBTM_LE_KEY_VALUE* p_keys, + bool pass_to_application) { body(bd_addr, key_type, p_keys, pass_to_application); - }; + } }; extern struct btm_sec_save_le_key btm_sec_save_le_key; @@ -685,8 +626,8 @@ extern struct btm_sec_save_le_key btm_sec_save_le_key; // Return: void struct doNothing { std::function body{ - [](uint8_t* /* data */, uint16_t /* len */) {}}; - void operator()(uint8_t* data, uint16_t len) { body(data, len); }; + [](uint8_t* /* data */, uint16_t /* len */) {}}; + void operator()(uint8_t* data, uint16_t len) { body(data, len); } }; extern struct doNothing doNothing; @@ -694,20 +635,15 @@ extern struct doNothing doNothing; // Params: base::Callback - callback, - uint8_t* data, uint16_t len)> - body{[](base::Callback - /* callback */, - uint8_t* /* data */, uint16_t /* len */) {}}; - void operator()( - base::Callback - callback, - uint8_t* data, uint16_t len) { + std::function callback, + uint8_t* data, uint16_t len)> + body{[](base::Callback + /* callback */, + uint8_t* /* data */, uint16_t /* len */) {}}; + void operator()(base::Callback callback, + uint8_t* data, uint16_t len) { body(callback, data, len); - }; + } }; extern struct read_phy_cb read_phy_cb; @@ -715,8 +651,7 @@ extern struct read_phy_cb read_phy_cb; } // namespace mock } // namespace test -std::optional BTM_BleGetIdentityAddress( - const RawAddress /* address */) { +std::optional BTM_BleGetIdentityAddress(const RawAddress /* address */) { return std::nullopt; } diff --git a/system/test/mock/mock_stack_btm_ble_addr.cc b/system/test/mock/mock_stack_btm_ble_addr.cc index 8dede2d72cc..9262ac65d03 100644 --- a/system/test/mock/mock_stack_btm_ble_addr.cc +++ b/system/test/mock/mock_stack_btm_ble_addr.cc @@ -42,59 +42,51 @@ struct btm_ble_addr_resolvable btm_ble_addr_resolvable; struct btm_ble_resolve_random_addr btm_ble_resolve_random_addr; struct btm_identity_addr_to_random_pseudo btm_identity_addr_to_random_pseudo; struct btm_identity_addr_to_random_pseudo_from_address_with_type - btm_identity_addr_to_random_pseudo_from_address_with_type; + btm_identity_addr_to_random_pseudo_from_address_with_type; struct btm_random_pseudo_to_identity_addr btm_random_pseudo_to_identity_addr; -struct btm_ble_refresh_peer_resolvable_private_addr - btm_ble_refresh_peer_resolvable_private_addr; +struct btm_ble_refresh_peer_resolvable_private_addr btm_ble_refresh_peer_resolvable_private_addr; } // namespace stack_btm_ble_addr } // namespace mock } // namespace test // Mocked functions, if any -bool btm_ble_init_pseudo_addr(tBTM_SEC_DEV_REC* p_dev_rec, - const RawAddress& new_pseudo_addr) { +bool btm_ble_init_pseudo_addr(tBTM_SEC_DEV_REC* p_dev_rec, const RawAddress& new_pseudo_addr) { inc_func_call_count(__func__); - return test::mock::stack_btm_ble_addr::btm_ble_init_pseudo_addr( - p_dev_rec, new_pseudo_addr); + return test::mock::stack_btm_ble_addr::btm_ble_init_pseudo_addr(p_dev_rec, new_pseudo_addr); } -bool btm_ble_addr_resolvable(const RawAddress& rpa, - tBTM_SEC_DEV_REC* p_dev_rec) { +bool btm_ble_addr_resolvable(const RawAddress& rpa, tBTM_SEC_DEV_REC* p_dev_rec) { inc_func_call_count(__func__); - return test::mock::stack_btm_ble_addr::btm_ble_addr_resolvable(rpa, - p_dev_rec); + return test::mock::stack_btm_ble_addr::btm_ble_addr_resolvable(rpa, p_dev_rec); } tBTM_SEC_DEV_REC* btm_ble_resolve_random_addr(const RawAddress& random_bda) { inc_func_call_count(__func__); - return test::mock::stack_btm_ble_addr::btm_ble_resolve_random_addr( - random_bda); + return test::mock::stack_btm_ble_addr::btm_ble_resolve_random_addr(random_bda); } -bool btm_identity_addr_to_random_pseudo(RawAddress* bd_addr, - tBLE_ADDR_TYPE* p_addr_type, +bool btm_identity_addr_to_random_pseudo(RawAddress* bd_addr, tBLE_ADDR_TYPE* p_addr_type, bool refresh) { inc_func_call_count(__func__); - return test::mock::stack_btm_ble_addr::btm_identity_addr_to_random_pseudo( - bd_addr, p_addr_type, refresh); + return test::mock::stack_btm_ble_addr::btm_identity_addr_to_random_pseudo(bd_addr, p_addr_type, + refresh); } -bool btm_identity_addr_to_random_pseudo_from_address_with_type( - tBLE_BD_ADDR* address_with_type, bool refresh) { +bool btm_identity_addr_to_random_pseudo_from_address_with_type(tBLE_BD_ADDR* address_with_type, + bool refresh) { inc_func_call_count(__func__); - return test::mock::stack_btm_ble_addr:: - btm_identity_addr_to_random_pseudo_from_address_with_type( + return test::mock::stack_btm_ble_addr::btm_identity_addr_to_random_pseudo_from_address_with_type( address_with_type, refresh); } bool btm_random_pseudo_to_identity_addr(RawAddress* random_pseudo, tBLE_ADDR_TYPE* p_identity_addr_type) { inc_func_call_count(__func__); - return test::mock::stack_btm_ble_addr::btm_random_pseudo_to_identity_addr( - random_pseudo, p_identity_addr_type); + return test::mock::stack_btm_ble_addr::btm_random_pseudo_to_identity_addr(random_pseudo, + p_identity_addr_type); } -void btm_ble_refresh_peer_resolvable_private_addr( - const RawAddress& pseudo_bda, const RawAddress& rpa, - tBLE_RAND_ADDR_TYPE rra_type) { +void btm_ble_refresh_peer_resolvable_private_addr(const RawAddress& pseudo_bda, + const RawAddress& rpa, + tBLE_RAND_ADDR_TYPE rra_type) { inc_func_call_count(__func__); - test::mock::stack_btm_ble_addr::btm_ble_refresh_peer_resolvable_private_addr( - pseudo_bda, rpa, rra_type); + test::mock::stack_btm_ble_addr::btm_ble_refresh_peer_resolvable_private_addr(pseudo_bda, rpa, + rra_type); } // END mockcify generation diff --git a/system/test/mock/mock_stack_btm_ble_addr.h b/system/test/mock/mock_stack_btm_ble_addr.h index 2a7231a6dae..842730d3fe0 100644 --- a/system/test/mock/mock_stack_btm_ble_addr.h +++ b/system/test/mock/mock_stack_btm_ble_addr.h @@ -40,14 +40,13 @@ namespace stack_btm_ble_addr { // Params: tBTM_SEC_DEV_REC* p_dev_rec, const RawAddress& new_pseudo_addr // Returns: bool struct btm_ble_init_pseudo_addr { - std::function - body{[](tBTM_SEC_DEV_REC* /* p_dev_rec */, - const RawAddress& /* new_pseudo_addr */) { return false; }}; - bool operator()(tBTM_SEC_DEV_REC* p_dev_rec, - const RawAddress& new_pseudo_addr) { + std::function body{ + [](tBTM_SEC_DEV_REC* /* p_dev_rec */, const RawAddress& /* new_pseudo_addr */) { + return false; + }}; + bool operator()(tBTM_SEC_DEV_REC* p_dev_rec, const RawAddress& new_pseudo_addr) { return body(p_dev_rec, new_pseudo_addr); - }; + } }; extern struct btm_ble_init_pseudo_addr btm_ble_init_pseudo_addr; // Name: btm_ble_addr_resolvable @@ -55,12 +54,10 @@ extern struct btm_ble_init_pseudo_addr btm_ble_init_pseudo_addr; // Returns: bool struct btm_ble_addr_resolvable { std::function body{ - [](const RawAddress& /* rpa */, tBTM_SEC_DEV_REC* /* p_dev_rec */) { - return false; - }}; + [](const RawAddress& /* rpa */, tBTM_SEC_DEV_REC* /* p_dev_rec */) { return false; }}; bool operator()(const RawAddress& rpa, tBTM_SEC_DEV_REC* p_dev_rec) { return body(rpa, p_dev_rec); - }; + } }; extern struct btm_ble_addr_resolvable btm_ble_addr_resolvable; // Name: btm_ble_resolve_random_addr @@ -68,71 +65,63 @@ extern struct btm_ble_addr_resolvable btm_ble_addr_resolvable; // Returns: tBTM_SEC_DEV_REC* struct btm_ble_resolve_random_addr { std::function body{ - [](const RawAddress& /* random_bda */) { return nullptr; }}; - tBTM_SEC_DEV_REC* operator()(const RawAddress& random_bda) { - return body(random_bda); - }; + [](const RawAddress& /* random_bda */) { return nullptr; }}; + tBTM_SEC_DEV_REC* operator()(const RawAddress& random_bda) { return body(random_bda); } }; extern struct btm_ble_resolve_random_addr btm_ble_resolve_random_addr; // Name: btm_identity_addr_to_random_pseudo // Params: RawAddress* bd_addr, uint8_t* p_addr_type, bool refresh // Returns: bool struct btm_identity_addr_to_random_pseudo { - std::function - body{[](RawAddress* /* bd_addr */, tBLE_ADDR_TYPE* /* p_addr_type */, - bool /* refresh */) { return false; }}; - bool operator()(RawAddress* bd_addr, tBLE_ADDR_TYPE* p_addr_type, - bool refresh) { + std::function body{ + [](RawAddress* /* bd_addr */, tBLE_ADDR_TYPE* /* p_addr_type */, bool /* refresh */) { + return false; + }}; + bool operator()(RawAddress* bd_addr, tBLE_ADDR_TYPE* p_addr_type, bool refresh) { return body(bd_addr, p_addr_type, refresh); - }; + } }; -extern struct btm_identity_addr_to_random_pseudo - btm_identity_addr_to_random_pseudo; +extern struct btm_identity_addr_to_random_pseudo btm_identity_addr_to_random_pseudo; // Name: btm_identity_addr_to_random_pseudo_from_address_with_type // Params: tBLE_BD_ADDR* address_with_type, bool refresh // Returns: bool struct btm_identity_addr_to_random_pseudo_from_address_with_type { std::function body{ - [](tBLE_BD_ADDR* /* address_with_type */, bool /* refresh */) { - return false; - }}; + [](tBLE_BD_ADDR* /* address_with_type */, bool /* refresh */) { return false; }}; bool operator()(tBLE_BD_ADDR* address_with_type, bool refresh) { return body(address_with_type, refresh); - }; + } }; extern struct btm_identity_addr_to_random_pseudo_from_address_with_type - btm_identity_addr_to_random_pseudo_from_address_with_type; + btm_identity_addr_to_random_pseudo_from_address_with_type; // Name: btm_random_pseudo_to_identity_addr // Params: RawAddress* random_pseudo, uint8_t* p_identity_addr_type // Returns: bool struct btm_random_pseudo_to_identity_addr { - std::function - body{[](RawAddress* /* random_pseudo */, - tBLE_ADDR_TYPE* /* p_identity_addr_type */) { return false; }}; - bool operator()(RawAddress* random_pseudo, - tBLE_ADDR_TYPE* p_identity_addr_type) { + std::function body{ + [](RawAddress* /* random_pseudo */, tBLE_ADDR_TYPE* /* p_identity_addr_type */) { + return false; + }}; + bool operator()(RawAddress* random_pseudo, tBLE_ADDR_TYPE* p_identity_addr_type) { return body(random_pseudo, p_identity_addr_type); - }; + } }; -extern struct btm_random_pseudo_to_identity_addr - btm_random_pseudo_to_identity_addr; +extern struct btm_random_pseudo_to_identity_addr btm_random_pseudo_to_identity_addr; // Name: btm_ble_refresh_peer_resolvable_private_addr // Params: const RawAddress& pseudo_bda, const RawAddress& rpa, // tBLE_RAND_ADDR_TYPE rra_type Returns: void struct btm_ble_refresh_peer_resolvable_private_addr { std::function - body{[](const RawAddress& /* pseudo_bda */, const RawAddress& /* rpa */, - tBLE_RAND_ADDR_TYPE /* rra_type */) {}}; + body{[](const RawAddress& /* pseudo_bda */, const RawAddress& /* rpa */, + tBLE_RAND_ADDR_TYPE /* rra_type */) {}}; void operator()(const RawAddress& pseudo_bda, const RawAddress& rpa, tBLE_RAND_ADDR_TYPE rra_type) { body(pseudo_bda, rpa, rra_type); - }; + } }; extern struct btm_ble_refresh_peer_resolvable_private_addr - btm_ble_refresh_peer_resolvable_private_addr; + btm_ble_refresh_peer_resolvable_private_addr; } // namespace stack_btm_ble_addr } // namespace mock diff --git a/system/test/mock/mock_stack_btm_ble_adv_filter.cc b/system/test/mock/mock_stack_btm_ble_adv_filter.cc index 5df6fff4a5c..f6d7f3e3cf2 100644 --- a/system/test/mock/mock_stack_btm_ble_adv_filter.cc +++ b/system/test/mock/mock_stack_btm_ble_adv_filter.cc @@ -27,10 +27,10 @@ #include "stack/include/btm_ble_api.h" #include "test/common/mock_functions.h" -void BTM_BleAdvFilterParamSetup( - tBTM_BLE_SCAN_COND_OP /* action */, tBTM_BLE_PF_FILT_INDEX /* filt_index */, - std::unique_ptr /* p_filt_params */, - tBTM_BLE_PF_PARAM_CB /* cb */) { +void BTM_BleAdvFilterParamSetup(tBTM_BLE_SCAN_COND_OP /* action */, + tBTM_BLE_PF_FILT_INDEX /* filt_index */, + std::unique_ptr /* p_filt_params */, + tBTM_BLE_PF_PARAM_CB /* cb */) { inc_func_call_count(__func__); } void btm_ble_adv_filter_init(void) { inc_func_call_count(__func__); } diff --git a/system/test/mock/mock_stack_btm_ble_bgconn.cc b/system/test/mock/mock_stack_btm_ble_bgconn.cc index bec5e59efbc..afdab209f84 100644 --- a/system/test/mock/mock_stack_btm_ble_bgconn.cc +++ b/system/test/mock/mock_stack_btm_ble_bgconn.cc @@ -50,8 +50,7 @@ struct BTM_AcceptlistClear BTM_AcceptlistClear; void btm_update_scanner_filter_policy(tBTM_BLE_SFP scan_policy) { inc_func_call_count(__func__); - test::mock::stack_btm_ble_bgconn::btm_update_scanner_filter_policy( - scan_policy); + test::mock::stack_btm_ble_bgconn::btm_update_scanner_filter_policy(scan_policy); } bool BTM_SetLeConnectionModeToFast() { inc_func_call_count(__func__); @@ -67,8 +66,7 @@ bool BTM_AcceptlistAdd(const RawAddress& address) { } bool BTM_AcceptlistAdd(const RawAddress& address, bool is_direct) { inc_func_call_count(__func__); - return test::mock::stack_btm_ble_bgconn::BTM_AcceptlistAddDirect(address, - is_direct); + return test::mock::stack_btm_ble_bgconn::BTM_AcceptlistAddDirect(address, is_direct); } void BTM_AcceptlistRemove(const RawAddress& address) { inc_func_call_count(__func__); diff --git a/system/test/mock/mock_stack_btm_ble_bgconn.h b/system/test/mock/mock_stack_btm_ble_bgconn.h index 94fba5d2ac0..803bc10ba4e 100644 --- a/system/test/mock/mock_stack_btm_ble_bgconn.h +++ b/system/test/mock/mock_stack_btm_ble_bgconn.h @@ -36,9 +36,8 @@ namespace stack_btm_ble_bgconn { // Params: tBTM_BLE_SFP scan_policy // Returns: void struct btm_update_scanner_filter_policy { - std::function body{ - [](tBTM_BLE_SFP /* scan_policy */) {}}; - void operator()(tBTM_BLE_SFP scan_policy) { body(scan_policy); }; + std::function body{[](tBTM_BLE_SFP /* scan_policy */) {}}; + void operator()(tBTM_BLE_SFP scan_policy) { body(scan_policy); } }; extern struct btm_update_scanner_filter_policy btm_update_scanner_filter_policy; // Name: BTM_SetLeConnectionModeToFast @@ -46,7 +45,7 @@ extern struct btm_update_scanner_filter_policy btm_update_scanner_filter_policy; // Returns: bool struct BTM_SetLeConnectionModeToFast { std::function body{[]() { return false; }}; - bool operator()() { return body(); }; + bool operator()() { return body(); } }; extern struct BTM_SetLeConnectionModeToFast BTM_SetLeConnectionModeToFast; // Name: BTM_SetLeConnectionModeToSlow @@ -54,7 +53,7 @@ extern struct BTM_SetLeConnectionModeToFast BTM_SetLeConnectionModeToFast; // Returns: void struct BTM_SetLeConnectionModeToSlow { std::function body{[]() {}}; - void operator()() { body(); }; + void operator()() { body(); } }; extern struct BTM_SetLeConnectionModeToSlow BTM_SetLeConnectionModeToSlow; // Name: BTM_AcceptlistAdd @@ -62,8 +61,8 @@ extern struct BTM_SetLeConnectionModeToSlow BTM_SetLeConnectionModeToSlow; // Returns: bool struct BTM_AcceptlistAdd { std::function body{ - [](const RawAddress& /* address */) { return false; }}; - bool operator()(const RawAddress& address) { return body(address); }; + [](const RawAddress& /* address */) { return false; }}; + bool operator()(const RawAddress& address) { return body(address); } }; extern struct BTM_AcceptlistAdd BTM_AcceptlistAdd; // Name: BTM_AcceptlistAddDirect @@ -71,21 +70,16 @@ extern struct BTM_AcceptlistAdd BTM_AcceptlistAdd; // Returns: bool struct BTM_AcceptlistAddDirect { std::function body{ - [](const RawAddress& /* address */, bool /* is_direct */) { - return false; - }}; - bool operator()(const RawAddress& address, bool is_direct) { - return body(address, is_direct); - }; + [](const RawAddress& /* address */, bool /* is_direct */) { return false; }}; + bool operator()(const RawAddress& address, bool is_direct) { return body(address, is_direct); } }; extern struct BTM_AcceptlistAddDirect BTM_AcceptlistAddDirect; // Name: BTM_AcceptlistRemove // Params: const RawAddress& address // Returns: void struct BTM_AcceptlistRemove { - std::function body{ - [](const RawAddress& /* address */) {}}; - void operator()(const RawAddress& address) { body(address); }; + std::function body{[](const RawAddress& /* address */) {}}; + void operator()(const RawAddress& address) { body(address); } }; extern struct BTM_AcceptlistRemove BTM_AcceptlistRemove; // Name: BTM_AcceptlistClear @@ -93,7 +87,7 @@ extern struct BTM_AcceptlistRemove BTM_AcceptlistRemove; // Returns: void struct BTM_AcceptlistClear { std::function body{[]() {}}; - void operator()() { body(); }; + void operator()() { body(); } }; extern struct BTM_AcceptlistClear BTM_AcceptlistClear; diff --git a/system/test/mock/mock_stack_btm_ble_gap.cc b/system/test/mock/mock_stack_btm_ble_gap.cc index e7dedd1ab6e..3434e9575b1 100644 --- a/system/test/mock/mock_stack_btm_ble_gap.cc +++ b/system/test/mock/mock_stack_btm_ble_gap.cc @@ -32,12 +32,11 @@ #include "types/raw_address.h" using StartSyncCb = base::Callback; -using SyncReportCb = base::Callback /*data*/)>; + uint8_t /*status*/, uint16_t /*sync_handle*/, uint8_t /*advertising_sid*/, + uint8_t /*address_type*/, RawAddress /*address*/, uint8_t /*phy*/, uint16_t /*interval*/)>; +using SyncReportCb = + base::Callback /*data*/)>; using SyncLostCb = base::Callback; using SyncTransferCb = base::Callback; @@ -70,22 +69,18 @@ bool btm_ble_topology_check(tBTM_BLE_STATE_MASK /* request_state_mask */) { return false; } tBTM_STATUS BTM_BleObserve(bool /* start */, uint8_t /* duration */, - tBTM_INQ_RESULTS_CB* /* p_results_cb */, - tBTM_CMPL_CB* /* p_cmpl_cb */, + tBTM_INQ_RESULTS_CB* /* p_results_cb */, tBTM_CMPL_CB* /* p_cmpl_cb */, bool /* low_latency_scan */) { inc_func_call_count(__func__); return BTM_SUCCESS; } -void BTM_BleOpportunisticObserve(bool /* enable */, - tBTM_INQ_RESULTS_CB* /* p_results_cb */) { +void BTM_BleOpportunisticObserve(bool /* enable */, tBTM_INQ_RESULTS_CB* /* p_results_cb */) { inc_func_call_count(__func__); } -void BTM_BleTargetAnnouncementObserve(bool /* enable */, - tBTM_INQ_RESULTS_CB* /* p_results_cb */) { +void BTM_BleTargetAnnouncementObserve(bool /* enable */, tBTM_INQ_RESULTS_CB* /* p_results_cb */) { inc_func_call_count(__func__); } -tBTM_STATUS btm_ble_read_remote_name(const RawAddress& /* remote_bda */, - tBTM_CMPL_CB* /* p_cb */) { +tBTM_STATUS btm_ble_read_remote_name(const RawAddress& /* remote_bda */, tBTM_CMPL_CB* /* p_cb */) { inc_func_call_count(__func__); return BTM_SUCCESS; } @@ -102,16 +97,14 @@ tBTM_STATUS btm_ble_start_inquiry(uint8_t /* duration */) { return BTM_SUCCESS; } void BTM_BleGetDynamicAudioBuffer( - tBTM_BT_DYNAMIC_AUDIO_BUFFER_CB /* p_dynamic_audio_buffer_cb*/[]) { + tBTM_BT_DYNAMIC_AUDIO_BUFFER_CB /* p_dynamic_audio_buffer_cb*/[]) { inc_func_call_count(__func__); } void BTM_BleGetVendorCapabilities(tBTM_BLE_VSC_CB* /* p_cmn_vsc_cb */) { inc_func_call_count(__func__); } -void BTM_BleSetScanParams(uint32_t /* scan_interval */, - uint32_t /* scan_window */, - tBLE_SCAN_MODE /* scan_mode */, - base::Callback /* cb */) { +void BTM_BleSetScanParams(uint32_t /* scan_interval */, uint32_t /* scan_window */, + tBLE_SCAN_MODE /* scan_mode */, base::Callback /* cb */) { inc_func_call_count(__func__); } void btm_ble_decrement_link_topology_mask(uint8_t /* link_role */) { @@ -122,64 +115,52 @@ void btm_ble_increment_link_topology_mask(uint8_t /* link_role */) { inc_func_call_count(__func__); } void btm_ble_init(void) { inc_func_call_count(__func__); } -DEV_CLASS btm_ble_get_appearance_as_cod( - std::vector const& /* data */) { +DEV_CLASS btm_ble_get_appearance_as_cod(std::vector const& /* data */) { inc_func_call_count(__func__); return kDevClassUnclassified; } -void btm_ble_process_adv_addr(RawAddress& /* bda */, - tBLE_ADDR_TYPE* /* addr_type */) { +void btm_ble_process_adv_addr(RawAddress& /* bda */, tBLE_ADDR_TYPE* /* addr_type */) { inc_func_call_count(__func__); } -void btm_ble_process_adv_pkt_cont( - uint16_t /* evt_type */, tBLE_ADDR_TYPE /* addr_type */, - const RawAddress& /* bda */, uint8_t /* primary_phy */, - uint8_t /* secondary_phy */, uint8_t /* advertising_sid */, - int8_t /* tx_power */, int8_t /* rssi */, uint16_t /* periodic_adv_int */, - uint8_t /* data_len */, const uint8_t* /* data */, - const RawAddress& /* original_bda */) { +void btm_ble_process_adv_pkt_cont(uint16_t /* evt_type */, tBLE_ADDR_TYPE /* addr_type */, + const RawAddress& /* bda */, uint8_t /* primary_phy */, + uint8_t /* secondary_phy */, uint8_t /* advertising_sid */, + int8_t /* tx_power */, int8_t /* rssi */, + uint16_t /* periodic_adv_int */, uint8_t /* data_len */, + const uint8_t* /* data */, const RawAddress& /* original_bda */) { inc_func_call_count(__func__); } void btm_ble_process_adv_pkt_cont_for_inquiry( - uint16_t /* evt_type */, tBLE_ADDR_TYPE /* addr_type */, - const RawAddress& /* bda */, uint8_t /* primary_phy */, - uint8_t /* secondary_phy */, uint8_t /* advertising_sid */, - int8_t /* tx_power */, int8_t /* rssi */, uint16_t /* periodic_adv_int */, - std::vector /* advertising_data */) { + uint16_t /* evt_type */, tBLE_ADDR_TYPE /* addr_type */, const RawAddress& /* bda */, + uint8_t /* primary_phy */, uint8_t /* secondary_phy */, uint8_t /* advertising_sid */, + int8_t /* tx_power */, int8_t /* rssi */, uint16_t /* periodic_adv_int */, + std::vector /* advertising_data */) { inc_func_call_count(__func__); } -void btm_ble_read_remote_features_complete(uint8_t* /* p */, - uint8_t /* length */) { +void btm_ble_read_remote_features_complete(uint8_t* /* p */, uint8_t /* length */) { inc_func_call_count(__func__); } -void btm_ble_read_remote_name_cmpl(bool /* status */, - const RawAddress& /* bda */, +void btm_ble_read_remote_name_cmpl(bool /* status */, const RawAddress& /* bda */, uint16_t /* length */, char* /* p_name */) { inc_func_call_count(__func__); } -void btm_ble_set_adv_flag(uint16_t /* connect_mode */, - uint16_t /* disc_mode */) { +void btm_ble_set_adv_flag(uint16_t /* connect_mode */, uint16_t /* disc_mode */) { inc_func_call_count(__func__); } void btm_ble_stop_inquiry(void) { inc_func_call_count(__func__); } -void btm_ble_update_dmt_flag_bits(uint8_t* /* adv_flag_value */, - const uint16_t /* connect_mode */, +void btm_ble_update_dmt_flag_bits(uint8_t* /* adv_flag_value */, const uint16_t /* connect_mode */, const uint16_t /* disc_mode */) { inc_func_call_count(__func__); } -void btm_ble_update_mode_operation(uint8_t /* link_role */, - const RawAddress* /* bd_addr */, +void btm_ble_update_mode_operation(uint8_t /* link_role */, const RawAddress* /* bd_addr */, tHCI_STATUS /* status */) { inc_func_call_count(__func__); } -void btm_ble_write_adv_enable_complete(uint8_t* /* p */, - uint16_t /* evt_len */) { +void btm_ble_write_adv_enable_complete(uint8_t* /* p */, uint16_t /* evt_len */) { inc_func_call_count(__func__); } -void btm_send_hci_set_scan_params(uint8_t /* scan_type */, - uint16_t /* scan_int */, - uint16_t /* scan_win */, - tBLE_ADDR_TYPE /* addr_type_own */, +void btm_send_hci_set_scan_params(uint8_t /* scan_type */, uint16_t /* scan_int */, + uint16_t /* scan_win */, tBLE_ADDR_TYPE /* addr_type_own */, uint8_t /* scan_filter_policy */) { inc_func_call_count(__func__); } diff --git a/system/test/mock/mock_stack_btm_ble_privacy.cc b/system/test/mock/mock_stack_btm_ble_privacy.cc index 4ad71a12ab6..f4cb9929f06 100644 --- a/system/test/mock/mock_stack_btm_ble_privacy.cc +++ b/system/test/mock/mock_stack_btm_ble_privacy.cc @@ -35,14 +35,10 @@ namespace mock { namespace stack_btm_ble_privacy { // Function state capture and return values, if needed -struct btm_ble_clear_resolving_list_complete - btm_ble_clear_resolving_list_complete; -struct btm_ble_add_resolving_list_entry_complete - btm_ble_add_resolving_list_entry_complete; -struct btm_ble_remove_resolving_list_entry_complete - btm_ble_remove_resolving_list_entry_complete; -struct btm_ble_read_resolving_list_entry_complete - btm_ble_read_resolving_list_entry_complete; +struct btm_ble_clear_resolving_list_complete btm_ble_clear_resolving_list_complete; +struct btm_ble_add_resolving_list_entry_complete btm_ble_add_resolving_list_entry_complete; +struct btm_ble_remove_resolving_list_entry_complete btm_ble_remove_resolving_list_entry_complete; +struct btm_ble_read_resolving_list_entry_complete btm_ble_read_resolving_list_entry_complete; struct btm_ble_remove_resolving_list_entry btm_ble_remove_resolving_list_entry; struct btm_ble_clear_resolving_list btm_ble_clear_resolving_list; struct btm_ble_read_resolving_list_entry btm_ble_read_resolving_list_entry; @@ -57,30 +53,23 @@ struct btm_ble_resolving_list_init btm_ble_resolving_list_init; // Mocked functions, if any void btm_ble_clear_resolving_list_complete(uint8_t* p, uint16_t evt_len) { inc_func_call_count(__func__); - test::mock::stack_btm_ble_privacy::btm_ble_clear_resolving_list_complete( - p, evt_len); + test::mock::stack_btm_ble_privacy::btm_ble_clear_resolving_list_complete(p, evt_len); } void btm_ble_add_resolving_list_entry_complete(uint8_t* p, uint16_t evt_len) { inc_func_call_count(__func__); - test::mock::stack_btm_ble_privacy::btm_ble_add_resolving_list_entry_complete( - p, evt_len); + test::mock::stack_btm_ble_privacy::btm_ble_add_resolving_list_entry_complete(p, evt_len); } -void btm_ble_remove_resolving_list_entry_complete(uint8_t* p, - uint16_t evt_len) { +void btm_ble_remove_resolving_list_entry_complete(uint8_t* p, uint16_t evt_len) { inc_func_call_count(__func__); - test::mock::stack_btm_ble_privacy:: - btm_ble_remove_resolving_list_entry_complete(p, evt_len); + test::mock::stack_btm_ble_privacy::btm_ble_remove_resolving_list_entry_complete(p, evt_len); } -void btm_ble_read_resolving_list_entry_complete(const uint8_t* p, - uint16_t evt_len) { +void btm_ble_read_resolving_list_entry_complete(const uint8_t* p, uint16_t evt_len) { inc_func_call_count(__func__); - test::mock::stack_btm_ble_privacy::btm_ble_read_resolving_list_entry_complete( - p, evt_len); + test::mock::stack_btm_ble_privacy::btm_ble_read_resolving_list_entry_complete(p, evt_len); } tBTM_STATUS btm_ble_remove_resolving_list_entry(tBTM_SEC_DEV_REC* p_dev_rec) { inc_func_call_count(__func__); - return test::mock::stack_btm_ble_privacy::btm_ble_remove_resolving_list_entry( - p_dev_rec); + return test::mock::stack_btm_ble_privacy::btm_ble_remove_resolving_list_entry(p_dev_rec); } void btm_ble_clear_resolving_list(void) { inc_func_call_count(__func__); @@ -88,21 +77,18 @@ void btm_ble_clear_resolving_list(void) { } bool btm_ble_read_resolving_list_entry(tBTM_SEC_DEV_REC* p_dev_rec) { inc_func_call_count(__func__); - return test::mock::stack_btm_ble_privacy::btm_ble_read_resolving_list_entry( - p_dev_rec); + return test::mock::stack_btm_ble_privacy::btm_ble_read_resolving_list_entry(p_dev_rec); } void btm_ble_resolving_list_load_dev(tBTM_SEC_DEV_REC& /* p_dev_rec */) { inc_func_call_count(__func__); } void btm_ble_resolving_list_remove_dev(tBTM_SEC_DEV_REC* p_dev_rec) { inc_func_call_count(__func__); - test::mock::stack_btm_ble_privacy::btm_ble_resolving_list_remove_dev( - p_dev_rec); + test::mock::stack_btm_ble_privacy::btm_ble_resolving_list_remove_dev(p_dev_rec); } void btm_ble_resolving_list_init(uint8_t max_irk_list_sz) { inc_func_call_count(__func__); - test::mock::stack_btm_ble_privacy::btm_ble_resolving_list_init( - max_irk_list_sz); + test::mock::stack_btm_ble_privacy::btm_ble_resolving_list_init(max_irk_list_sz); } // END mockcify generation diff --git a/system/test/mock/mock_stack_btm_ble_privacy.h b/system/test/mock/mock_stack_btm_ble_privacy.h index c632c62e0f7..8e9f7f8120a 100644 --- a/system/test/mock/mock_stack_btm_ble_privacy.h +++ b/system/test/mock/mock_stack_btm_ble_privacy.h @@ -38,59 +38,53 @@ namespace stack_btm_ble_privacy { // Returns: void struct btm_ble_clear_resolving_list_complete { std::function body{ - [](uint8_t* /* p */, uint16_t /* evt_len */) {}}; - void operator()(uint8_t* p, uint16_t evt_len) { body(p, evt_len); }; + [](uint8_t* /* p */, uint16_t /* evt_len */) {}}; + void operator()(uint8_t* p, uint16_t evt_len) { body(p, evt_len); } }; -extern struct btm_ble_clear_resolving_list_complete - btm_ble_clear_resolving_list_complete; +extern struct btm_ble_clear_resolving_list_complete btm_ble_clear_resolving_list_complete; // Name: btm_ble_add_resolving_list_entry_complete // Params: uint8_t* p, uint16_t evt_len // Returns: void struct btm_ble_add_resolving_list_entry_complete { std::function body{ - [](uint8_t* /* p */, uint16_t /* evt_len */) {}}; - void operator()(uint8_t* p, uint16_t evt_len) { body(p, evt_len); }; + [](uint8_t* /* p */, uint16_t /* evt_len */) {}}; + void operator()(uint8_t* p, uint16_t evt_len) { body(p, evt_len); } }; -extern struct btm_ble_add_resolving_list_entry_complete - btm_ble_add_resolving_list_entry_complete; +extern struct btm_ble_add_resolving_list_entry_complete btm_ble_add_resolving_list_entry_complete; // Name: btm_ble_remove_resolving_list_entry_complete // Params: uint8_t* p, uint16_t evt_len // Returns: void struct btm_ble_remove_resolving_list_entry_complete { std::function body{ - [](uint8_t* /* p */, uint16_t /* evt_len */) {}}; - void operator()(uint8_t* p, uint16_t evt_len) { body(p, evt_len); }; + [](uint8_t* /* p */, uint16_t /* evt_len */) {}}; + void operator()(uint8_t* p, uint16_t evt_len) { body(p, evt_len); } }; extern struct btm_ble_remove_resolving_list_entry_complete - btm_ble_remove_resolving_list_entry_complete; + btm_ble_remove_resolving_list_entry_complete; // Name: btm_ble_read_resolving_list_entry_complete // Params: uint8_t* p, uint16_t evt_len // Returns: void struct btm_ble_read_resolving_list_entry_complete { std::function body{ - [](const uint8_t* /* p */, uint16_t /* evt_len */) {}}; - void operator()(const uint8_t* p, uint16_t evt_len) { body(p, evt_len); }; + [](const uint8_t* /* p */, uint16_t /* evt_len */) {}}; + void operator()(const uint8_t* p, uint16_t evt_len) { body(p, evt_len); } }; -extern struct btm_ble_read_resolving_list_entry_complete - btm_ble_read_resolving_list_entry_complete; +extern struct btm_ble_read_resolving_list_entry_complete btm_ble_read_resolving_list_entry_complete; // Name: btm_ble_remove_resolving_list_entry // Params: tBTM_SEC_DEV_REC* p_dev_rec // Returns: tBTM_STATUS struct btm_ble_remove_resolving_list_entry { std::function body{ - [](tBTM_SEC_DEV_REC* /* p_dev_rec */) { return 0; }}; - tBTM_STATUS operator()(tBTM_SEC_DEV_REC* p_dev_rec) { - return body(p_dev_rec); - }; + [](tBTM_SEC_DEV_REC* /* p_dev_rec */) { return 0; }}; + tBTM_STATUS operator()(tBTM_SEC_DEV_REC* p_dev_rec) { return body(p_dev_rec); } }; -extern struct btm_ble_remove_resolving_list_entry - btm_ble_remove_resolving_list_entry; +extern struct btm_ble_remove_resolving_list_entry btm_ble_remove_resolving_list_entry; // Name: btm_ble_clear_resolving_list // Params: void // Returns: void struct btm_ble_clear_resolving_list { std::function body{[](void) {}}; - void operator()(void) { body(); }; + void operator()(void) { body(); } }; extern struct btm_ble_clear_resolving_list btm_ble_clear_resolving_list; // Name: btm_ble_read_resolving_list_entry @@ -98,46 +92,41 @@ extern struct btm_ble_clear_resolving_list btm_ble_clear_resolving_list; // Returns: bool struct btm_ble_read_resolving_list_entry { std::function body{ - [](tBTM_SEC_DEV_REC* /* p_dev_rec */) { return false; }}; - bool operator()(tBTM_SEC_DEV_REC* p_dev_rec) { return body(p_dev_rec); }; + [](tBTM_SEC_DEV_REC* /* p_dev_rec */) { return false; }}; + bool operator()(tBTM_SEC_DEV_REC* p_dev_rec) { return body(p_dev_rec); } }; -extern struct btm_ble_read_resolving_list_entry - btm_ble_read_resolving_list_entry; +extern struct btm_ble_read_resolving_list_entry btm_ble_read_resolving_list_entry; // Name: btm_ble_resolving_list_load_dev // Params: tBTM_SEC_DEV_REC* p_dev_rec // Returns: void struct btm_ble_resolving_list_load_dev { std::function body{ - [](const tBTM_SEC_DEV_REC& /* p_dev_rec */) {}}; - void operator()(const tBTM_SEC_DEV_REC& p_dev_rec) { body(p_dev_rec); }; + [](const tBTM_SEC_DEV_REC& /* p_dev_rec */) {}}; + void operator()(const tBTM_SEC_DEV_REC& p_dev_rec) { body(p_dev_rec); } }; extern struct btm_ble_resolving_list_load_dev btm_ble_resolving_list_load_dev; // Name: btm_ble_resolving_list_remove_dev // Params: tBTM_SEC_DEV_REC* p_dev_rec // Returns: void struct btm_ble_resolving_list_remove_dev { - std::function body{ - [](tBTM_SEC_DEV_REC* /* p_dev_rec */) {}}; - void operator()(tBTM_SEC_DEV_REC* p_dev_rec) { body(p_dev_rec); }; + std::function body{[](tBTM_SEC_DEV_REC* /* p_dev_rec */) {}}; + void operator()(tBTM_SEC_DEV_REC* p_dev_rec) { body(p_dev_rec); } }; -extern struct btm_ble_resolving_list_remove_dev - btm_ble_resolving_list_remove_dev; +extern struct btm_ble_resolving_list_remove_dev btm_ble_resolving_list_remove_dev; // Name: btm_ble_enable_resolving_list_for_platform // Params: uint8_t rl_mask // Returns: void struct btm_ble_enable_resolving_list_for_platform { std::function body{[](uint8_t /* rl_mask */) {}}; - void operator()(uint8_t rl_mask) { body(rl_mask); }; + void operator()(uint8_t rl_mask) { body(rl_mask); } }; -extern struct btm_ble_enable_resolving_list_for_platform - btm_ble_enable_resolving_list_for_platform; +extern struct btm_ble_enable_resolving_list_for_platform btm_ble_enable_resolving_list_for_platform; // Name: btm_ble_resolving_list_init // Params: uint8_t max_irk_list_sz // Returns: void struct btm_ble_resolving_list_init { - std::function body{ - [](uint8_t /* max_irk_list_sz */) {}}; - void operator()(uint8_t max_irk_list_sz) { body(max_irk_list_sz); }; + std::function body{[](uint8_t /* max_irk_list_sz */) {}}; + void operator()(uint8_t max_irk_list_sz) { body(max_irk_list_sz); } }; extern struct btm_ble_resolving_list_init btm_ble_resolving_list_init; diff --git a/system/test/mock/mock_stack_btm_dev.cc b/system/test/mock/mock_stack_btm_dev.cc index bab842520a8..88b4459170d 100644 --- a/system/test/mock/mock_stack_btm_dev.cc +++ b/system/test/mock/mock_stack_btm_dev.cc @@ -40,21 +40,19 @@ struct btm_find_dev btm_find_dev; struct BTM_Sec_AddressKnown BTM_Sec_AddressKnown; struct maybe_resolve_address maybe_resolve_address; -} +} // namespace stack_btm_dev } // namespace mock } // namespace test -void BTM_SecAddDevice(const RawAddress& /* bd_addr */, - const DEV_CLASS /* dev_class */, LinkKey /* link_key */, - uint8_t /* key_type */, uint8_t /* pin_length */) { +void BTM_SecAddDevice(const RawAddress& /* bd_addr */, const DEV_CLASS /* dev_class */, + LinkKey /* link_key */, uint8_t /* key_type */, uint8_t /* pin_length */) { inc_func_call_count(__func__); } bool BTM_SecDeleteDevice(const RawAddress& /* bd_addr */) { inc_func_call_count(__func__); return false; } -bool btm_set_bond_type_dev(const RawAddress& /* bd_addr */, - tBTM_BOND_TYPE /* bond_type */) { +bool btm_set_bond_type_dev(const RawAddress& /* bd_addr */, tBTM_BOND_TYPE /* bond_type */) { inc_func_call_count(__func__); return false; } @@ -86,29 +84,19 @@ tBTM_BOND_TYPE btm_get_bond_type_dev(const RawAddress& /* bd_addr */) { inc_func_call_count(__func__); return BOND_TYPE_UNKNOWN; } -void BTM_SecClearSecurityFlags(const RawAddress& /* bd_addr */) { - inc_func_call_count(__func__); -} -void btm_consolidate_dev(tBTM_SEC_DEV_REC* /* p_target_rec */) { - inc_func_call_count(__func__); -} +void BTM_SecClearSecurityFlags(const RawAddress& /* bd_addr */) { inc_func_call_count(__func__); } +void btm_consolidate_dev(tBTM_SEC_DEV_REC* /* p_target_rec */) { inc_func_call_count(__func__); } void btm_dev_consolidate_existing_connections(const RawAddress& /* bd_addr */) { inc_func_call_count(__func__); } -void BTM_SecDump(const std::string& /* label */) { - inc_func_call_count(__func__); -} -void BTM_SecDumpDev(const RawAddress& /* bd_addr */) { - inc_func_call_count(__func__); -} +void BTM_SecDump(const std::string& /* label */) { inc_func_call_count(__func__); } +void BTM_SecDumpDev(const RawAddress& /* bd_addr */) { inc_func_call_count(__func__); } std::vector btm_get_sec_dev_rec() { inc_func_call_count(__func__); return {}; } -void BTM_SetConsolidationCallback(BTM_CONSOLIDATION_CB* /* cb */) { - inc_func_call_count(__func__); -} +void BTM_SetConsolidationCallback(BTM_CONSOLIDATION_CB* /* cb */) { inc_func_call_count(__func__); } bool BTM_Sec_AddressKnown(const RawAddress& address) { inc_func_call_count(__func__); @@ -119,6 +107,4 @@ bool maybe_resolve_address(RawAddress* bda, tBLE_ADDR_TYPE* bda_type) { inc_func_call_count(__func__); return test::mock::stack_btm_dev::maybe_resolve_address(bda, bda_type); } -const tBLE_BD_ADDR BTM_Sec_GetAddressWithType(const RawAddress& /* bd_addr */) { - return {}; -} +const tBLE_BD_ADDR BTM_Sec_GetAddressWithType(const RawAddress& /* bd_addr */) { return {}; } diff --git a/system/test/mock/mock_stack_btm_dev.h b/system/test/mock/mock_stack_btm_dev.h index cf14da37c48..38e947b9cb2 100644 --- a/system/test/mock/mock_stack_btm_dev.h +++ b/system/test/mock/mock_stack_btm_dev.h @@ -26,17 +26,15 @@ namespace stack_btm_dev { // Function state capture and return values, if needed struct btm_find_dev { std::function body{ - [](const RawAddress&) { return nullptr; }}; - tBTM_SEC_DEV_REC* operator()(const RawAddress& bd_addr) { - return body(bd_addr); - }; + [](const RawAddress&) { return nullptr; }}; + tBTM_SEC_DEV_REC* operator()(const RawAddress& bd_addr) { return body(bd_addr); } }; extern struct btm_find_dev btm_find_dev; struct BTM_Sec_AddressKnown { std::function body{ - [](const RawAddress& /* address */) { return false; }}; - bool operator()(const RawAddress& address) { return body(address); }; + [](const RawAddress& /* address */) { return false; }}; + bool operator()(const RawAddress& address) { return body(address); } }; extern struct BTM_Sec_AddressKnown BTM_Sec_AddressKnown; @@ -45,12 +43,8 @@ extern struct BTM_Sec_AddressKnown BTM_Sec_AddressKnown; // Returns: bool struct maybe_resolve_address { std::function body{ - [](RawAddress* /* bda */, tBLE_ADDR_TYPE* /* bda_type */) { - return false; - }}; - bool operator()(RawAddress* bda, tBLE_ADDR_TYPE* bda_type) { - return body(bda, bda_type); - }; + [](RawAddress* /* bda */, tBLE_ADDR_TYPE* /* bda_type */) { return false; }}; + bool operator()(RawAddress* bda, tBLE_ADDR_TYPE* bda_type) { return body(bda, bda_type); } }; extern struct maybe_resolve_address maybe_resolve_address; diff --git a/system/test/mock/mock_stack_btm_devctl.cc b/system/test/mock/mock_stack_btm_devctl.cc index 741ea11f40c..db7abf5a154 100644 --- a/system/test/mock/mock_stack_btm_devctl.cc +++ b/system/test/mock/mock_stack_btm_devctl.cc @@ -44,8 +44,7 @@ bool BTM_IsDeviceUp(void) { return test::mock::stack_btm_devctl::BTM_IsDeviceUp(); } -tBTM_STATUS BTM_DeleteStoredLinkKey(const RawAddress* /* bd_addr */, - tBTM_CMPL_CB* /* p_cb */) { +tBTM_STATUS BTM_DeleteStoredLinkKey(const RawAddress* /* bd_addr */, tBTM_CMPL_CB* /* p_cb */) { inc_func_call_count(__func__); return BTM_SUCCESS; } @@ -57,8 +56,7 @@ tBTM_STATUS BTM_ReadLocalDeviceName(const char** /* p_name */) { inc_func_call_count(__func__); return BTM_SUCCESS; } -tBTM_STATUS BTM_ReadLocalDeviceNameFromController( - tBTM_CMPL_CB* /* p_rln_cmpl_cback */) { +tBTM_STATUS BTM_ReadLocalDeviceNameFromController(tBTM_CMPL_CB* /* p_rln_cmpl_cback */) { inc_func_call_count(__func__); return BTM_SUCCESS; } @@ -75,15 +73,13 @@ DEV_CLASS BTM_ReadDeviceClass(void) { return kDevClassEmpty; } void BTM_VendorSpecificCommand(uint16_t /* opcode */, uint8_t /* param_len */, - uint8_t* /* p_param_buf */, - tBTM_VSC_CMPL_CB* /* p_cb */) { + uint8_t* /* p_param_buf */, tBTM_VSC_CMPL_CB* /* p_cb */) { inc_func_call_count(__func__); } void BTM_WritePageTimeout(uint16_t /* timeout */) { inc_func_call_count(__func__); } void BTM_db_reset(void) { inc_func_call_count(__func__); } void BTM_reset_complete() { inc_func_call_count(__func__); } -void btm_delete_stored_link_key_complete(uint8_t* /* p */, - uint16_t /* evt_len */) { +void btm_delete_stored_link_key_complete(uint8_t* /* p */, uint16_t /* evt_len */) { inc_func_call_count(__func__); } void btm_dev_free() { inc_func_call_count(__func__); } diff --git a/system/test/mock/mock_stack_btm_devctl.h b/system/test/mock/mock_stack_btm_devctl.h index 142b7171b6c..6aef955336a 100644 --- a/system/test/mock/mock_stack_btm_devctl.h +++ b/system/test/mock/mock_stack_btm_devctl.h @@ -22,7 +22,7 @@ namespace stack_btm_devctl { // Function state capture and return values, if needed struct BTM_IsDeviceUp { std::function body{[]() { return false; }}; - bool operator()() { return body(); }; + bool operator()() { return body(); } }; extern struct BTM_IsDeviceUp BTM_IsDeviceUp; diff --git a/system/test/mock/mock_stack_btm_hfp_lc3_decoder.cc b/system/test/mock/mock_stack_btm_hfp_lc3_decoder.cc index d2776275ed3..f9e507a2864 100644 --- a/system/test/mock/mock_stack_btm_hfp_lc3_decoder.cc +++ b/system/test/mock/mock_stack_btm_hfp_lc3_decoder.cc @@ -62,11 +62,10 @@ void hfp_lc3_decoder_cleanup(void) { inc_func_call_count(__func__); test::mock::stack_btm_hfp_lc3_decoder::hfp_lc3_decoder_cleanup(); } -bool hfp_lc3_decoder_decode_packet(const uint8_t* i_buf, int16_t* o_buf, - size_t out_len) { +bool hfp_lc3_decoder_decode_packet(const uint8_t* i_buf, int16_t* o_buf, size_t out_len) { inc_func_call_count(__func__); - return test::mock::stack_btm_hfp_lc3_decoder::hfp_lc3_decoder_decode_packet( - i_buf, o_buf, out_len); + return test::mock::stack_btm_hfp_lc3_decoder::hfp_lc3_decoder_decode_packet(i_buf, o_buf, + out_len); } bool hfp_lc3_decoder_init() { inc_func_call_count(__func__); diff --git a/system/test/mock/mock_stack_btm_hfp_lc3_decoder.h b/system/test/mock/mock_stack_btm_hfp_lc3_decoder.h index 96a8adf3cae..259cfc99149 100644 --- a/system/test/mock/mock_stack_btm_hfp_lc3_decoder.h +++ b/system/test/mock/mock_stack_btm_hfp_lc3_decoder.h @@ -42,7 +42,7 @@ namespace stack_btm_hfp_lc3_decoder { // Return: void struct hfp_lc3_decoder_cleanup { std::function body{[](void) {}}; - void operator()(void) { body(); }; + void operator()(void) { body(); } }; extern struct hfp_lc3_decoder_cleanup hfp_lc3_decoder_cleanup; @@ -51,13 +51,13 @@ extern struct hfp_lc3_decoder_cleanup hfp_lc3_decoder_cleanup; // Return: bool struct hfp_lc3_decoder_decode_packet { static bool return_value; - std::function - body{[](const uint8_t* /* i_buf */, int16_t* /* o_buf */, - size_t /* out_len */) { return return_value; }}; + std::function body{ + [](const uint8_t* /* i_buf */, int16_t* /* o_buf */, size_t /* out_len */) { + return return_value; + }}; bool operator()(const uint8_t* i_buf, int16_t* o_buf, size_t out_len) { return body(i_buf, o_buf, out_len); - }; + } }; extern struct hfp_lc3_decoder_decode_packet hfp_lc3_decoder_decode_packet; @@ -67,7 +67,7 @@ extern struct hfp_lc3_decoder_decode_packet hfp_lc3_decoder_decode_packet; struct hfp_lc3_decoder_init { static bool return_value; std::function body{[]() { return return_value; }}; - bool operator()() { return body(); }; + bool operator()() { return body(); } }; extern struct hfp_lc3_decoder_init hfp_lc3_decoder_init; diff --git a/system/test/mock/mock_stack_btm_hfp_lc3_encoder.cc b/system/test/mock/mock_stack_btm_hfp_lc3_encoder.cc index c074b4e2de6..49056eb490d 100644 --- a/system/test/mock/mock_stack_btm_hfp_lc3_encoder.cc +++ b/system/test/mock/mock_stack_btm_hfp_lc3_encoder.cc @@ -59,8 +59,7 @@ uint32_t hfp_lc3_encode_frames::return_value = 0; // Mocked functions, if any uint32_t hfp_lc3_encode_frames(int16_t* input, uint8_t* output) { inc_func_call_count(__func__); - return test::mock::stack_btm_hfp_lc3_encoder::hfp_lc3_encode_frames(input, - output); + return test::mock::stack_btm_hfp_lc3_encoder::hfp_lc3_encode_frames(input, output); } void hfp_lc3_encoder_cleanup(void) { inc_func_call_count(__func__); diff --git a/system/test/mock/mock_stack_btm_hfp_lc3_encoder.h b/system/test/mock/mock_stack_btm_hfp_lc3_encoder.h index e20383e8ea5..69457eaab5c 100644 --- a/system/test/mock/mock_stack_btm_hfp_lc3_encoder.h +++ b/system/test/mock/mock_stack_btm_hfp_lc3_encoder.h @@ -42,10 +42,8 @@ namespace stack_btm_hfp_lc3_encoder { struct hfp_lc3_encode_frames { static uint32_t return_value; std::function body{ - [](int16_t* /* input */, uint8_t* /* output */) { return return_value; }}; - uint32_t operator()(int16_t* input, uint8_t* output) { - return body(input, output); - }; + [](int16_t* /* input */, uint8_t* /* output */) { return return_value; }}; + uint32_t operator()(int16_t* input, uint8_t* output) { return body(input, output); } }; extern struct hfp_lc3_encode_frames hfp_lc3_encode_frames; @@ -54,7 +52,7 @@ extern struct hfp_lc3_encode_frames hfp_lc3_encode_frames; // Return: void struct hfp_lc3_encoder_cleanup { std::function body{[](void) {}}; - void operator()(void) { body(); }; + void operator()(void) { body(); } }; extern struct hfp_lc3_encoder_cleanup hfp_lc3_encoder_cleanup; @@ -63,7 +61,7 @@ extern struct hfp_lc3_encoder_cleanup hfp_lc3_encoder_cleanup; // Return: void struct hfp_lc3_encoder_init { std::function body{[](void) {}}; - void operator()(void) { body(); }; + void operator()(void) { body(); } }; extern struct hfp_lc3_encoder_init hfp_lc3_encoder_init; diff --git a/system/test/mock/mock_stack_btm_hfp_msbc_decoder.cc b/system/test/mock/mock_stack_btm_hfp_msbc_decoder.cc index 7d5520e91c3..a2597e84551 100644 --- a/system/test/mock/mock_stack_btm_hfp_msbc_decoder.cc +++ b/system/test/mock/mock_stack_btm_hfp_msbc_decoder.cc @@ -60,11 +60,10 @@ void hfp_msbc_decoder_cleanup(void) { inc_func_call_count(__func__); test::mock::stack_btm_hfp_msbc_decoder::hfp_msbc_decoder_cleanup(); } -bool hfp_msbc_decoder_decode_packet(const uint8_t* i_buf, int16_t* o_buf, - size_t out_len) { +bool hfp_msbc_decoder_decode_packet(const uint8_t* i_buf, int16_t* o_buf, size_t out_len) { inc_func_call_count(__func__); - return test::mock::stack_btm_hfp_msbc_decoder::hfp_msbc_decoder_decode_packet( - i_buf, o_buf, out_len); + return test::mock::stack_btm_hfp_msbc_decoder::hfp_msbc_decoder_decode_packet(i_buf, o_buf, + out_len); } bool hfp_msbc_decoder_init() { inc_func_call_count(__func__); diff --git a/system/test/mock/mock_stack_btm_hfp_msbc_decoder.h b/system/test/mock/mock_stack_btm_hfp_msbc_decoder.h index 53e7d3b80a2..9e79b6ff750 100644 --- a/system/test/mock/mock_stack_btm_hfp_msbc_decoder.h +++ b/system/test/mock/mock_stack_btm_hfp_msbc_decoder.h @@ -43,7 +43,7 @@ namespace stack_btm_hfp_msbc_decoder { // Return: void struct hfp_msbc_decoder_cleanup { std::function body{[](void) {}}; - void operator()(void) { body(); }; + void operator()(void) { body(); } }; extern struct hfp_msbc_decoder_cleanup hfp_msbc_decoder_cleanup; @@ -52,12 +52,13 @@ extern struct hfp_msbc_decoder_cleanup hfp_msbc_decoder_cleanup; // Return: bool struct hfp_msbc_decoder_decode_packet { static bool return_value; - std::function - body{[](const uint8_t* /* i_buf */, int16_t* /* o_buf */, - size_t /* out_len */) { return return_value; }}; + std::function body{ + [](const uint8_t* /* i_buf */, int16_t* /* o_buf */, size_t /* out_len */) { + return return_value; + }}; bool operator()(const uint8_t* i_buf, int16_t* o_buf, size_t out_len) { return body(i_buf, o_buf, out_len); - }; + } }; extern struct hfp_msbc_decoder_decode_packet hfp_msbc_decoder_decode_packet; @@ -67,7 +68,7 @@ extern struct hfp_msbc_decoder_decode_packet hfp_msbc_decoder_decode_packet; struct hfp_msbc_decoder_init { static bool return_value; std::function body{[]() { return return_value; }}; - bool operator()() { return body(); }; + bool operator()() { return body(); } }; extern struct hfp_msbc_decoder_init hfp_msbc_decoder_init; diff --git a/system/test/mock/mock_stack_btm_hfp_msbc_encoder.cc b/system/test/mock/mock_stack_btm_hfp_msbc_encoder.cc index 6fab1ce130e..219578455b7 100644 --- a/system/test/mock/mock_stack_btm_hfp_msbc_encoder.cc +++ b/system/test/mock/mock_stack_btm_hfp_msbc_encoder.cc @@ -60,8 +60,7 @@ uint32_t hfp_msbc_encode_frames::return_value = 0; // Mocked functions, if any uint32_t hfp_msbc_encode_frames(int16_t* input, uint8_t* output) { inc_func_call_count(__func__); - return test::mock::stack_btm_hfp_msbc_encoder::hfp_msbc_encode_frames(input, - output); + return test::mock::stack_btm_hfp_msbc_encoder::hfp_msbc_encode_frames(input, output); } void hfp_msbc_encoder_cleanup(void) { inc_func_call_count(__func__); diff --git a/system/test/mock/mock_stack_btm_hfp_msbc_encoder.h b/system/test/mock/mock_stack_btm_hfp_msbc_encoder.h index 6412cdaec62..89cd3250f71 100644 --- a/system/test/mock/mock_stack_btm_hfp_msbc_encoder.h +++ b/system/test/mock/mock_stack_btm_hfp_msbc_encoder.h @@ -42,10 +42,8 @@ namespace stack_btm_hfp_msbc_encoder { struct hfp_msbc_encode_frames { static uint32_t return_value; std::function body{ - [](int16_t* /* input */, uint8_t* /* output */) { return return_value; }}; - uint32_t operator()(int16_t* input, uint8_t* output) { - return body(input, output); - }; + [](int16_t* /* input */, uint8_t* /* output */) { return return_value; }}; + uint32_t operator()(int16_t* input, uint8_t* output) { return body(input, output); } }; extern struct hfp_msbc_encode_frames hfp_msbc_encode_frames; @@ -54,7 +52,7 @@ extern struct hfp_msbc_encode_frames hfp_msbc_encode_frames; // Return: void struct hfp_msbc_encoder_cleanup { std::function body{[](void) {}}; - void operator()(void) { body(); }; + void operator()(void) { body(); } }; extern struct hfp_msbc_encoder_cleanup hfp_msbc_encoder_cleanup; @@ -63,7 +61,7 @@ extern struct hfp_msbc_encoder_cleanup hfp_msbc_encoder_cleanup; // Return: void struct hfp_msbc_encoder_init { std::function body{[](void) {}}; - void operator()(void) { body(); }; + void operator()(void) { body(); } }; extern struct hfp_msbc_encoder_init hfp_msbc_encoder_init; diff --git a/system/test/mock/mock_stack_btm_inq.cc b/system/test/mock/mock_stack_btm_inq.cc index eaec0d301d7..36f2f1adad6 100644 --- a/system/test/mock/mock_stack_btm_inq.cc +++ b/system/test/mock/mock_stack_btm_inq.cc @@ -126,19 +126,17 @@ void BTM_EnableInterlacedPageScan() { inc_func_call_count(__func__); test::mock::stack_btm_inq::BTM_EnableInterlacedPageScan(); } -uint8_t BTM_GetEirSupportedServices(uint32_t* p_eir_uuid, uint8_t** p, - uint8_t max_num_uuid16, +uint8_t BTM_GetEirSupportedServices(uint32_t* p_eir_uuid, uint8_t** p, uint8_t max_num_uuid16, uint8_t* p_num_uuid16) { inc_func_call_count(__func__); - return test::mock::stack_btm_inq::BTM_GetEirSupportedServices( - p_eir_uuid, p, max_num_uuid16, p_num_uuid16); + return test::mock::stack_btm_inq::BTM_GetEirSupportedServices(p_eir_uuid, p, max_num_uuid16, + p_num_uuid16); } -uint8_t BTM_GetEirUuidList(const uint8_t* p_eir, size_t eir_len, - uint8_t uuid_size, uint8_t* p_num_uuid, - uint8_t* p_uuid_list, uint8_t max_num_uuid) { +uint8_t BTM_GetEirUuidList(const uint8_t* p_eir, size_t eir_len, uint8_t uuid_size, + uint8_t* p_num_uuid, uint8_t* p_uuid_list, uint8_t max_num_uuid) { inc_func_call_count(__func__); - return test::mock::stack_btm_inq::BTM_GetEirUuidList( - p_eir, eir_len, uuid_size, p_num_uuid, p_uuid_list, max_num_uuid); + return test::mock::stack_btm_inq::BTM_GetEirUuidList(p_eir, eir_len, uuid_size, p_num_uuid, + p_uuid_list, max_num_uuid); } bool BTM_HasEirService(const uint32_t* p_eir_uuid, uint16_t uuid16) { inc_func_call_count(__func__); @@ -161,12 +159,10 @@ uint16_t BTM_IsInquiryActive(void) { return test::mock::stack_btm_inq::BTM_IsInquiryActive(); } -tBTM_STATUS BTM_ReadRemoteDeviceName(const RawAddress& remote_bda, - tBTM_NAME_CMPL_CB* p_cb, +tBTM_STATUS BTM_ReadRemoteDeviceName(const RawAddress& remote_bda, tBTM_NAME_CMPL_CB* p_cb, tBT_TRANSPORT transport) { inc_func_call_count(__func__); - return test::mock::stack_btm_inq::BTM_ReadRemoteDeviceName(remote_bda, p_cb, - transport); + return test::mock::stack_btm_inq::BTM_ReadRemoteDeviceName(remote_bda, p_cb, transport); } void BTM_RemoveEirService(uint32_t* p_eir_uuid, uint16_t uuid16) { inc_func_call_count(__func__); @@ -184,8 +180,7 @@ tBTM_STATUS BTM_SetInquiryMode(uint8_t mode) { inc_func_call_count(__func__); return test::mock::stack_btm_inq::BTM_SetInquiryMode(mode); } -tBTM_STATUS BTM_StartInquiry(tBTM_INQ_RESULTS_CB* p_results_cb, - tBTM_CMPL_CB* p_cmpl_cb) { +tBTM_STATUS BTM_StartInquiry(tBTM_INQ_RESULTS_CB* p_results_cb, tBTM_CMPL_CB* p_cmpl_cb) { inc_func_call_count(__func__); return test::mock::stack_btm_inq::BTM_StartInquiry(p_results_cb, p_cmpl_cb); } @@ -233,11 +228,10 @@ void btm_process_inq_complete(tHCI_STATUS status, uint8_t mode) { inc_func_call_count(__func__); test::mock::stack_btm_inq::btm_process_inq_complete(status, mode); } -void btm_process_remote_name(const RawAddress* bda, const BD_NAME bdn, - uint16_t evt_len, tHCI_STATUS hci_status) { +void btm_process_remote_name(const RawAddress* bda, const BD_NAME bdn, uint16_t evt_len, + tHCI_STATUS hci_status) { inc_func_call_count(__func__); - test::mock::stack_btm_inq::btm_process_remote_name(bda, bdn, evt_len, - hci_status); + test::mock::stack_btm_inq::btm_process_remote_name(bda, bdn, evt_len, hci_status); } void btm_set_eir_uuid(const uint8_t* p_eir, tBTM_INQ_RESULTS* p_results) { inc_func_call_count(__func__); diff --git a/system/test/mock/mock_stack_btm_inq.h b/system/test/mock/mock_stack_btm_inq.h index 0447401ce71..d6ca0625044 100644 --- a/system/test/mock/mock_stack_btm_inq.h +++ b/system/test/mock/mock_stack_btm_inq.h @@ -54,10 +54,8 @@ namespace stack_btm_inq { // Return: void struct BTM_AddEirService { std::function body{ - [](uint32_t* /* p_eir_uuid */, uint16_t /* uuid16 */) {}}; - void operator()(uint32_t* p_eir_uuid, uint16_t uuid16) { - body(p_eir_uuid, uuid16); - }; + [](uint32_t* /* p_eir_uuid */, uint16_t /* uuid16 */) {}}; + void operator()(uint32_t* p_eir_uuid, uint16_t uuid16) { body(p_eir_uuid, uuid16); } }; extern struct BTM_AddEirService BTM_AddEirService; @@ -66,7 +64,7 @@ extern struct BTM_AddEirService BTM_AddEirService; // Return: void struct BTM_CancelInquiry { std::function body{[](void) {}}; - void operator()(void) { body(); }; + void operator()(void) { body(); } }; extern struct BTM_CancelInquiry BTM_CancelInquiry; @@ -76,7 +74,7 @@ extern struct BTM_CancelInquiry BTM_CancelInquiry; struct BTM_CancelRemoteDeviceName { static tBTM_STATUS return_value; std::function body{[](void) { return return_value; }}; - tBTM_STATUS operator()(void) { return body(); }; + tBTM_STATUS operator()(void) { return body(); } }; extern struct BTM_CancelRemoteDeviceName BTM_CancelRemoteDeviceName; @@ -86,8 +84,8 @@ extern struct BTM_CancelRemoteDeviceName BTM_CancelRemoteDeviceName; struct BTM_ClearInqDb { static tBTM_STATUS return_value; std::function body{ - [](const RawAddress* /* p_bda */) { return return_value; }}; - tBTM_STATUS operator()(const RawAddress* p_bda) { return body(p_bda); }; + [](const RawAddress* /* p_bda */) { return return_value; }}; + tBTM_STATUS operator()(const RawAddress* p_bda) { return body(p_bda); } }; extern struct BTM_ClearInqDb BTM_ClearInqDb; @@ -96,7 +94,7 @@ extern struct BTM_ClearInqDb BTM_ClearInqDb; // Return: void struct BTM_EnableInterlacedInquiryScan { std::function body{[]() {}}; - void operator()() { body(); }; + void operator()() { body(); } }; extern struct BTM_EnableInterlacedInquiryScan BTM_EnableInterlacedInquiryScan; @@ -105,7 +103,7 @@ extern struct BTM_EnableInterlacedInquiryScan BTM_EnableInterlacedInquiryScan; // Return: void struct BTM_EnableInterlacedPageScan { std::function body{[]() {}}; - void operator()() { body(); }; + void operator()() { body(); } }; extern struct BTM_EnableInterlacedPageScan BTM_EnableInterlacedPageScan; @@ -114,15 +112,14 @@ extern struct BTM_EnableInterlacedPageScan BTM_EnableInterlacedPageScan; // p_num_uuid16 Return: uint8_t struct BTM_GetEirSupportedServices { static uint8_t return_value; - std::function - body{[](uint32_t* /* p_eir_uuid */, uint8_t** /* p */, - uint8_t /* max_num_uuid16 */, - uint8_t* /* p_num_uuid16 */) { return return_value; }}; + std::function + body{[](uint32_t* /* p_eir_uuid */, uint8_t** /* p */, uint8_t /* max_num_uuid16 */, + uint8_t* /* p_num_uuid16 */) { return return_value; }}; uint8_t operator()(uint32_t* p_eir_uuid, uint8_t** p, uint8_t max_num_uuid16, uint8_t* p_num_uuid16) { return body(p_eir_uuid, p, max_num_uuid16, p_num_uuid16); - }; + } }; extern struct BTM_GetEirSupportedServices BTM_GetEirSupportedServices; @@ -132,18 +129,14 @@ extern struct BTM_GetEirSupportedServices BTM_GetEirSupportedServices; struct BTM_GetEirUuidList { static uint8_t return_value; std::function - body{[](const uint8_t* /* p_eir */, size_t /* eir_len */, - uint8_t /* uuid_size */, uint8_t* /* p_num_uuid */, - uint8_t* /* p_uuid_list */, - uint8_t /* max_num_uuid */) { return return_value; }}; - uint8_t operator()(const uint8_t* p_eir, size_t eir_len, uint8_t uuid_size, - uint8_t* p_num_uuid, uint8_t* p_uuid_list, - uint8_t max_num_uuid) { - return body(p_eir, eir_len, uuid_size, p_num_uuid, p_uuid_list, - max_num_uuid); - }; + uint8_t* p_num_uuid, uint8_t* p_uuid_list, uint8_t max_num_uuid)> + body{[](const uint8_t* /* p_eir */, size_t /* eir_len */, uint8_t /* uuid_size */, + uint8_t* /* p_num_uuid */, uint8_t* /* p_uuid_list */, + uint8_t /* max_num_uuid */) { return return_value; }}; + uint8_t operator()(const uint8_t* p_eir, size_t eir_len, uint8_t uuid_size, uint8_t* p_num_uuid, + uint8_t* p_uuid_list, uint8_t max_num_uuid) { + return body(p_eir, eir_len, uuid_size, p_num_uuid, p_uuid_list, max_num_uuid); + } }; extern struct BTM_GetEirUuidList BTM_GetEirUuidList; @@ -153,12 +146,8 @@ extern struct BTM_GetEirUuidList BTM_GetEirUuidList; struct BTM_HasEirService { static bool return_value; std::function body{ - [](const uint32_t* /* p_eir_uuid */, uint16_t /* uuid16 */) { - return return_value; - }}; - bool operator()(const uint32_t* p_eir_uuid, uint16_t uuid16) { - return body(p_eir_uuid, uuid16); - }; + [](const uint32_t* /* p_eir_uuid */, uint16_t /* uuid16 */) { return return_value; }}; + bool operator()(const uint32_t* p_eir_uuid, uint16_t uuid16) { return body(p_eir_uuid, uuid16); } }; extern struct BTM_HasEirService BTM_HasEirService; @@ -168,7 +157,7 @@ extern struct BTM_HasEirService BTM_HasEirService; struct BTM_InqDbFirst { static tBTM_INQ_INFO* return_value; std::function body{[](void) { return return_value; }}; - tBTM_INQ_INFO* operator()(void) { return body(); }; + tBTM_INQ_INFO* operator()(void) { return body(); } }; extern struct BTM_InqDbFirst BTM_InqDbFirst; @@ -178,8 +167,8 @@ extern struct BTM_InqDbFirst BTM_InqDbFirst; struct BTM_InqDbNext { static tBTM_INQ_INFO* return_value; std::function body{ - [](tBTM_INQ_INFO* /* p_cur */) { return return_value; }}; - tBTM_INQ_INFO* operator()(tBTM_INQ_INFO* p_cur) { return body(p_cur); }; + [](tBTM_INQ_INFO* /* p_cur */) { return return_value; }}; + tBTM_INQ_INFO* operator()(tBTM_INQ_INFO* p_cur) { return body(p_cur); } }; extern struct BTM_InqDbNext BTM_InqDbNext; @@ -189,8 +178,8 @@ extern struct BTM_InqDbNext BTM_InqDbNext; struct BTM_InqDbRead { static tBTM_INQ_INFO* return_value; std::function body{ - [](const RawAddress& /* p_bda */) { return return_value; }}; - tBTM_INQ_INFO* operator()(const RawAddress& p_bda) { return body(p_bda); }; + [](const RawAddress& /* p_bda */) { return return_value; }}; + tBTM_INQ_INFO* operator()(const RawAddress& p_bda) { return body(p_bda); } }; extern struct BTM_InqDbRead BTM_InqDbRead; @@ -200,7 +189,7 @@ extern struct BTM_InqDbRead BTM_InqDbRead; struct BTM_IsInquiryActive { static uint16_t return_value; std::function body{[](void) { return return_value; }}; - uint16_t operator()(void) { return body(); }; + uint16_t operator()(void) { return body(); } }; extern struct BTM_IsInquiryActive BTM_IsInquiryActive; @@ -209,14 +198,14 @@ extern struct BTM_IsInquiryActive BTM_IsInquiryActive; // transport Return: tBTM_STATUS struct BTM_ReadRemoteDeviceName { static tBTM_STATUS return_value; - std::function - body{[](const RawAddress& /* remote_bda */, tBTM_NAME_CMPL_CB* /* p_cb */, - tBT_TRANSPORT /* transport */) { return return_value; }}; + std::function + body{[](const RawAddress& /* remote_bda */, tBTM_NAME_CMPL_CB* /* p_cb */, + tBT_TRANSPORT /* transport */) { return return_value; }}; tBTM_STATUS operator()(const RawAddress& remote_bda, tBTM_NAME_CMPL_CB* p_cb, tBT_TRANSPORT transport) { return body(remote_bda, p_cb, transport); - }; + } }; extern struct BTM_ReadRemoteDeviceName BTM_ReadRemoteDeviceName; @@ -225,10 +214,8 @@ extern struct BTM_ReadRemoteDeviceName BTM_ReadRemoteDeviceName; // Return: void struct BTM_RemoveEirService { std::function body{ - [](uint32_t* /* p_eir_uuid */, uint16_t /* uuid16 */) {}}; - void operator()(uint32_t* p_eir_uuid, uint16_t uuid16) { - body(p_eir_uuid, uuid16); - }; + [](uint32_t* /* p_eir_uuid */, uint16_t /* uuid16 */) {}}; + void operator()(uint32_t* p_eir_uuid, uint16_t uuid16) { body(p_eir_uuid, uuid16); } }; extern struct BTM_RemoveEirService BTM_RemoveEirService; @@ -238,8 +225,8 @@ extern struct BTM_RemoveEirService BTM_RemoveEirService; struct BTM_SetConnectability { static tBTM_STATUS return_value; std::function body{ - [](uint16_t /* page_mode */) { return return_value; }}; - tBTM_STATUS operator()(uint16_t page_mode) { return body(page_mode); }; + [](uint16_t /* page_mode */) { return return_value; }}; + tBTM_STATUS operator()(uint16_t page_mode) { return body(page_mode); } }; extern struct BTM_SetConnectability BTM_SetConnectability; @@ -249,8 +236,8 @@ extern struct BTM_SetConnectability BTM_SetConnectability; struct BTM_SetDiscoverability { static tBTM_STATUS return_value; std::function body{ - [](uint16_t /* inq_mode */) { return return_value; }}; - tBTM_STATUS operator()(uint16_t inq_mode) { return body(inq_mode); }; + [](uint16_t /* inq_mode */) { return return_value; }}; + tBTM_STATUS operator()(uint16_t inq_mode) { return body(inq_mode); } }; extern struct BTM_SetDiscoverability BTM_SetDiscoverability; @@ -259,9 +246,8 @@ extern struct BTM_SetDiscoverability BTM_SetDiscoverability; // Return: tBTM_STATUS struct BTM_SetInquiryMode { static tBTM_STATUS return_value; - std::function body{ - [](uint8_t /* mode */) { return return_value; }}; - tBTM_STATUS operator()(uint8_t mode) { return body(mode); }; + std::function body{[](uint8_t /* mode */) { return return_value; }}; + tBTM_STATUS operator()(uint8_t mode) { return body(mode); } }; extern struct BTM_SetInquiryMode BTM_SetInquiryMode; @@ -270,14 +256,13 @@ extern struct BTM_SetInquiryMode BTM_SetInquiryMode; // Return: tBTM_STATUS struct BTM_StartInquiry { static tBTM_STATUS return_value; - std::function - body{[](tBTM_INQ_RESULTS_CB* /* p_results_cb */, - tBTM_CMPL_CB* /* p_cmpl_cb */) { return return_value; }}; - tBTM_STATUS operator()(tBTM_INQ_RESULTS_CB* p_results_cb, - tBTM_CMPL_CB* p_cmpl_cb) { + std::function body{ + [](tBTM_INQ_RESULTS_CB* /* p_results_cb */, tBTM_CMPL_CB* /* p_cmpl_cb */) { + return return_value; + }}; + tBTM_STATUS operator()(tBTM_INQ_RESULTS_CB* p_results_cb, tBTM_CMPL_CB* p_cmpl_cb) { return body(p_results_cb, p_cmpl_cb); - }; + } }; extern struct BTM_StartInquiry BTM_StartInquiry; @@ -287,8 +272,8 @@ extern struct BTM_StartInquiry BTM_StartInquiry; struct BTM_WriteEIR { static tBTM_STATUS return_value; std::function body{ - [](BT_HDR* /* p_buff */) { return return_value; }}; - tBTM_STATUS operator()(BT_HDR* p_buff) { return body(p_buff); }; + [](BT_HDR* /* p_buff */) { return return_value; }}; + tBTM_STATUS operator()(BT_HDR* p_buff) { return body(p_buff); } }; extern struct BTM_WriteEIR BTM_WriteEIR; @@ -297,7 +282,7 @@ extern struct BTM_WriteEIR BTM_WriteEIR; // Return: void struct btm_clear_all_pending_le_entry { std::function body{[](void) {}}; - void operator()(void) { body(); }; + void operator()(void) { body(); } }; extern struct btm_clear_all_pending_le_entry btm_clear_all_pending_le_entry; @@ -305,9 +290,8 @@ extern struct btm_clear_all_pending_le_entry btm_clear_all_pending_le_entry; // Params: const RawAddress* p_bda // Return: void struct btm_clr_inq_db { - std::function body{ - [](const RawAddress* /* p_bda */) {}}; - void operator()(const RawAddress* p_bda) { body(p_bda); }; + std::function body{[](const RawAddress* /* p_bda */) {}}; + void operator()(const RawAddress* p_bda) { body(p_bda); } }; extern struct btm_clr_inq_db btm_clr_inq_db; @@ -316,7 +300,7 @@ extern struct btm_clr_inq_db btm_clr_inq_db; // Return: void struct btm_clr_inq_result_flt { std::function body{[](void) {}}; - void operator()(void) { body(); }; + void operator()(void) { body(); } }; extern struct btm_clr_inq_result_flt btm_clr_inq_result_flt; @@ -326,8 +310,8 @@ extern struct btm_clr_inq_result_flt btm_clr_inq_result_flt; struct btm_inq_db_find { static tINQ_DB_ENT* return_value; std::function body{ - [](const RawAddress& /* p_bda */) { return return_value; }}; - tINQ_DB_ENT* operator()(const RawAddress& p_bda) { return body(p_bda); }; + [](const RawAddress& /* p_bda */) { return return_value; }}; + tINQ_DB_ENT* operator()(const RawAddress& p_bda) { return body(p_bda); } }; extern struct btm_inq_db_find btm_inq_db_find; @@ -337,10 +321,8 @@ extern struct btm_inq_db_find btm_inq_db_find; struct btm_inq_db_new { static tINQ_DB_ENT* return_value; std::function body{ - [](const RawAddress& /* p_bda */, bool /* is_ble */) { - return return_value; - }}; - tINQ_DB_ENT* operator()(const RawAddress& p_bda, bool is_ble) { return body(p_bda, is_ble); }; + [](const RawAddress& /* p_bda */, bool /* is_ble */) { return return_value; }}; + tINQ_DB_ENT* operator()(const RawAddress& p_bda, bool is_ble) { return body(p_bda, is_ble); } }; extern struct btm_inq_db_new btm_inq_db_new; @@ -349,7 +331,7 @@ extern struct btm_inq_db_new btm_inq_db_new; // Return: void struct btm_inq_db_reset { std::function body{[](void) {}}; - void operator()(void) { body(); }; + void operator()(void) { body(); } }; extern struct btm_inq_db_reset btm_inq_db_reset; @@ -359,8 +341,8 @@ extern struct btm_inq_db_reset btm_inq_db_reset; struct btm_inq_find_bdaddr { static bool return_value; std::function body{ - [](const RawAddress& /* p_bda */) { return return_value; }}; - bool operator()(const RawAddress& p_bda) { return body(p_bda); }; + [](const RawAddress& /* p_bda */) { return return_value; }}; + bool operator()(const RawAddress& p_bda) { return body(p_bda); } }; extern struct btm_inq_find_bdaddr btm_inq_find_bdaddr; @@ -369,28 +351,26 @@ extern struct btm_inq_find_bdaddr btm_inq_find_bdaddr; // Return: void struct btm_inq_remote_name_timer_timeout { std::function body{[](void* /* data */) {}}; - void operator()(void* data) { body(data); }; + void operator()(void* data) { body(data); } }; -extern struct btm_inq_remote_name_timer_timeout - btm_inq_remote_name_timer_timeout; +extern struct btm_inq_remote_name_timer_timeout btm_inq_remote_name_timer_timeout; // Name: btm_inq_rmt_name_failed_cancelled // Params: void // Return: void struct btm_inq_rmt_name_failed_cancelled { std::function body{[](void) {}}; - void operator()(void) { body(); }; + void operator()(void) { body(); } }; -extern struct btm_inq_rmt_name_failed_cancelled - btm_inq_rmt_name_failed_cancelled; +extern struct btm_inq_rmt_name_failed_cancelled btm_inq_rmt_name_failed_cancelled; // Name: btm_process_inq_complete // Params: tHCI_STATUS status, uint8_t mode // Return: void struct btm_process_inq_complete { std::function body{ - [](tHCI_STATUS /* status */, uint8_t /* mode */) {}}; - void operator()(tHCI_STATUS status, uint8_t mode) { body(status, mode); }; + [](tHCI_STATUS /* status */, uint8_t /* mode */) {}}; + void operator()(tHCI_STATUS status, uint8_t mode) { body(status, mode); } }; extern struct btm_process_inq_complete btm_process_inq_complete; @@ -400,12 +380,12 @@ extern struct btm_process_inq_complete btm_process_inq_complete; struct btm_process_remote_name { std::function - body{[](const RawAddress* /* bda */, const BD_NAME /* bdn */, - uint16_t /* evt_len */, tHCI_STATUS /* hci_status */) {}}; + body{[](const RawAddress* /* bda */, const BD_NAME /* bdn */, uint16_t /* evt_len */, + tHCI_STATUS /* hci_status */) {}}; void operator()(const RawAddress* bda, const BD_NAME bdn, uint16_t evt_len, tHCI_STATUS hci_status) { body(bda, bdn, evt_len, hci_status); - }; + } }; extern struct btm_process_remote_name btm_process_remote_name; @@ -414,10 +394,8 @@ extern struct btm_process_remote_name btm_process_remote_name; // Return: void struct btm_set_eir_uuid { std::function body{ - [](const uint8_t* /* p_eir */, tBTM_INQ_RESULTS* /* p_results */) {}}; - void operator()(const uint8_t* p_eir, tBTM_INQ_RESULTS* p_results) { - body(p_eir, p_results); - }; + [](const uint8_t* /* p_eir */, tBTM_INQ_RESULTS* /* p_results */) {}}; + void operator()(const uint8_t* p_eir, tBTM_INQ_RESULTS* p_results) { body(p_eir, p_results); } }; extern struct btm_set_eir_uuid btm_set_eir_uuid; @@ -426,7 +404,7 @@ extern struct btm_set_eir_uuid btm_set_eir_uuid; // Return: void struct btm_sort_inq_result { std::function body{[](void) {}}; - void operator()(void) { body(); }; + void operator()(void) { body(); } }; extern struct btm_sort_inq_result btm_sort_inq_result; diff --git a/system/test/mock/mock_stack_btm_interface.cc b/system/test/mock/mock_stack_btm_interface.cc index 8fd90818704..a67e0a94d0e 100644 --- a/system/test/mock/mock_stack_btm_interface.cc +++ b/system/test/mock/mock_stack_btm_interface.cc @@ -32,288 +32,233 @@ uint8_t hci_feature_bytes_per_page[HCI_FEATURE_BYTES_PER_PAGE] = {}; namespace { struct btm_client_interface_t default_btm_client_interface = { - .lifecycle = { - .BTM_PmRegister = [](uint8_t /* mask */, uint8_t* /* p_pm_id */, - tBTM_PM_STATUS_CBACK* /* p_cb */) -> tBTM_STATUS { - return BTM_SUCCESS; - }, - .ACL_RegisterClient = - [](struct acl_client_callback_s* /* callbacks */) {}, - .ACL_UnregisterClient = - [](struct acl_client_callback_s* /* callbacks */) {}, - .btm_init = []() {}, - .btm_free = []() {}, - .btm_ble_init = []() {}, - .btm_ble_free = []() {}, - .BTM_reset_complete = []() {}, - }, - .peer = { - .BTM_IsAclConnectionUp = [](const RawAddress& /* remote_bda */, - tBT_TRANSPORT /* transport */) -> bool { - return false; - }, - .BTM_ReadConnectedTransportAddress = - [](RawAddress* /* remote_bda */, - tBT_TRANSPORT /* transport */) -> bool { return false; }, - .BTM_CancelRemoteDeviceName = []() -> tBTM_STATUS { - return BTM_SUCCESS; - }, - .BTM_ReadRemoteDeviceName = [](const RawAddress& /* remote_bda */, - tBTM_NAME_CMPL_CB* /* p_cb */, - tBT_TRANSPORT /* transport */) - -> tBTM_STATUS { return BTM_SUCCESS; }, - .BTM_ReadRemoteFeatures = [](const RawAddress& /* addr */) -> uint8_t* { - return hci_feature_bytes_per_page; - }, - .BTM_ReadDevInfo = [](const RawAddress& /* remote_bda */, - tBT_DEVICE_TYPE* /* p_dev_type */, - tBLE_ADDR_TYPE* /* p_addr_type */) {}, - .BTM_GetMaxPacketSize = - [](const RawAddress& /* bd_addr */) -> uint16_t { return 0; }, - .BTM_ReadRemoteVersion = - [](const RawAddress& /* addr */, uint8_t* /* lmp_version */, - uint16_t* /* manufacturer */, - uint16_t* /* lmp_sub_version */) -> bool { return false; }, - .BTM_GetHCIConnHandle = [](const RawAddress& /* remote_bda */, - tBT_TRANSPORT /* transport */) -> uint16_t { - return 0; - }, - }, - .link_policy = { - .BTM_GetRole = [](const RawAddress& /* remote_bd_addr */, - tHCI_ROLE* /* p_role */) -> tBTM_STATUS { - return BTM_SUCCESS; - }, - .BTM_SetPowerMode = - [](uint8_t /* pm_id */, const RawAddress& /* remote_bda */, - const tBTM_PM_PWR_MD* /* p_mode */) -> tBTM_STATUS { - return BTM_SUCCESS; - }, - .BTM_SetSsrParams = [](RawAddress const& /* bd_addr */, - uint16_t /* max_lat */, - uint16_t /* min_rmt_to */, - uint16_t /* min_loc_to */) -> tBTM_STATUS { - return BTM_SUCCESS; - }, - .BTM_SwitchRoleToCentral = [](const RawAddress& /* remote_bd_addr */) - -> tBTM_STATUS { return BTM_SUCCESS; }, - .BTM_block_role_switch_for = [](const RawAddress& /* peer_addr */) {}, - .BTM_block_sniff_mode_for = [](const RawAddress& /* peer_addr */) {}, - .BTM_default_unblock_role_switch = []() {}, - .BTM_unblock_role_switch_for = [](const RawAddress& /* peer_addr */) {}, - .BTM_unblock_sniff_mode_for = [](const RawAddress& /* peer_addr */) {}, - .BTM_WritePageTimeout = [](uint16_t /* timeout */) {}, - }, - .link_controller = { - .BTM_GetLinkSuperTout = [](const RawAddress& /* remote_bda */, - uint16_t* /* p_timeout */) -> tBTM_STATUS { - return BTM_SUCCESS; - }, - .BTM_ReadRSSI = [](const RawAddress& /* remote_bda */, - tBTM_CMPL_CB* /* p_cb */) -> tBTM_STATUS { - return BTM_SUCCESS; - }, - }, - .security = { - .BTM_Sec_Init = []() {}, - .BTM_Sec_Free = []() {}, - .BTM_SecRegister = [](const tBTM_APPL_INFO* /* p_cb_info */) -> bool { - return false; - }, - .BTM_BleLoadLocalKeys = [](uint8_t /* key_type */, - tBTM_BLE_LOCAL_KEYS* /* p_key */) {}, - .BTM_SecAddDevice = [](const RawAddress& /* bd_addr */, - DEV_CLASS /* dev_class */, - LinkKey /* link_key */, uint8_t /* key_type */, - uint8_t /* pin_length */) {}, - .BTM_SecAddBleDevice = [](const RawAddress& /* bd_addr */, - tBT_DEVICE_TYPE /* dev_type */, - tBLE_ADDR_TYPE /* addr_type */) {}, - .BTM_SecDeleteDevice = [](const RawAddress& /* bd_addr */) -> bool { - return true; - }, - .BTM_SecAddBleKey = [](const RawAddress& /* bd_addr */, - tBTM_LE_KEY_VALUE* /* p_le_key */, - tBTM_LE_KEY_TYPE /* key_type */) {}, - .BTM_SecClearSecurityFlags = [](const RawAddress& /* bd_addr */) {}, - .BTM_SetEncryption = - [](const RawAddress& /* bd_addr */, tBT_TRANSPORT /* transport */, - tBTM_SEC_CALLBACK* /* p_callback */, void* /* p_ref_data */, - tBTM_BLE_SEC_ACT /* sec_act */) -> tBTM_STATUS { - return BTM_SUCCESS; - }, - .BTM_IsEncrypted = [](const RawAddress& /* bd_addr */, - tBT_TRANSPORT /* transport */) -> bool { - return false; - }, - .BTM_SecIsSecurityPending = - [](const RawAddress& /* bd_addr */) -> bool { return false; }, - .BTM_IsLinkKeyKnown = [](const RawAddress& /* bd_addr */, - tBT_TRANSPORT /* transport */) -> bool { - return false; - }, - .BTM_SecClrService = [](uint8_t /* service_id */) -> uint8_t { - return 0; - }, - .BTM_SecClrServiceByPsm = [](uint16_t /* psm */) -> uint8_t { - return 0; - }, - .BTM_SecBond = [](const RawAddress& /* bd_addr */, - tBLE_ADDR_TYPE /* addr_type */, - tBT_TRANSPORT /* transport */, - tBT_DEVICE_TYPE /* device_type */) -> tBTM_STATUS { - return BTM_SUCCESS; - }, - .BTM_SecBondCancel = [](const RawAddress& /* bd_addr */) - -> tBTM_STATUS { return BTM_SUCCESS; }, + .lifecycle = { + .BTM_PmRegister = [](uint8_t /* mask */, uint8_t* /* p_pm_id */, + tBTM_PM_STATUS_CBACK* /* p_cb */) -> tBTM_STATUS { + return BTM_SUCCESS; + }, + .ACL_RegisterClient = [](struct acl_client_callback_s* /* callbacks */) {}, + .ACL_UnregisterClient = [](struct acl_client_callback_s* /* callbacks */) {}, + .btm_init = []() {}, + .btm_free = []() {}, + .btm_ble_init = []() {}, + .btm_ble_free = []() {}, + .BTM_reset_complete = []() {}, + }, + .peer = { + .BTM_IsAclConnectionUp = [](const RawAddress& /* remote_bda */, + tBT_TRANSPORT /* transport */) -> bool { + return false; + }, + .BTM_ReadConnectedTransportAddress = [](RawAddress* /* remote_bda */, + tBT_TRANSPORT /* transport */) -> bool { + return false; + }, + .BTM_CancelRemoteDeviceName = []() -> tBTM_STATUS { return BTM_SUCCESS; }, + .BTM_ReadRemoteDeviceName = + [](const RawAddress& /* remote_bda */, tBTM_NAME_CMPL_CB* /* p_cb */, + tBT_TRANSPORT /* transport */) -> tBTM_STATUS { return BTM_SUCCESS; }, + .BTM_ReadRemoteFeatures = [](const RawAddress& /* addr */) -> uint8_t* { + return hci_feature_bytes_per_page; + }, + .BTM_ReadDevInfo = [](const RawAddress& /* remote_bda */, + tBT_DEVICE_TYPE* /* p_dev_type */, + tBLE_ADDR_TYPE* /* p_addr_type */) {}, + .BTM_GetMaxPacketSize = [](const RawAddress& /* bd_addr */) -> uint16_t { + return 0; + }, + .BTM_ReadRemoteVersion = + [](const RawAddress& /* addr */, uint8_t* /* lmp_version */, + uint16_t* /* manufacturer */, + uint16_t* /* lmp_sub_version */) -> bool { return false; }, + .BTM_GetHCIConnHandle = [](const RawAddress& /* remote_bda */, + tBT_TRANSPORT /* transport */) -> uint16_t { return 0; }, + }, + .link_policy = { + .BTM_GetRole = [](const RawAddress& /* remote_bd_addr */, + tHCI_ROLE* /* p_role */) -> tBTM_STATUS { return BTM_SUCCESS; }, + .BTM_SetPowerMode = [](uint8_t /* pm_id */, const RawAddress& /* remote_bda */, + const tBTM_PM_PWR_MD* /* p_mode */) -> tBTM_STATUS { + return BTM_SUCCESS; + }, + .BTM_SetSsrParams = [](RawAddress const& /* bd_addr */, uint16_t /* max_lat */, + uint16_t /* min_rmt_to */, uint16_t /* min_loc_to */) + -> tBTM_STATUS { return BTM_SUCCESS; }, + .BTM_SwitchRoleToCentral = [](const RawAddress& /* remote_bd_addr */) + -> tBTM_STATUS { return BTM_SUCCESS; }, + .BTM_block_role_switch_for = [](const RawAddress& /* peer_addr */) {}, + .BTM_block_sniff_mode_for = [](const RawAddress& /* peer_addr */) {}, + .BTM_default_unblock_role_switch = []() {}, + .BTM_unblock_role_switch_for = [](const RawAddress& /* peer_addr */) {}, + .BTM_unblock_sniff_mode_for = [](const RawAddress& /* peer_addr */) {}, + .BTM_WritePageTimeout = [](uint16_t /* timeout */) {}, + }, + .link_controller = { + .BTM_GetLinkSuperTout = [](const RawAddress& /* remote_bda */, + uint16_t* /* p_timeout */) -> tBTM_STATUS { + return BTM_SUCCESS; + }, + .BTM_ReadRSSI = [](const RawAddress& /* remote_bda */, + tBTM_CMPL_CB* /* p_cb */) -> tBTM_STATUS { return BTM_SUCCESS; }, + }, + .security = { + .BTM_Sec_Init = []() {}, + .BTM_Sec_Free = []() {}, + .BTM_SecRegister = [](const tBTM_APPL_INFO* /* p_cb_info */) -> bool { + return false; + }, + .BTM_BleLoadLocalKeys = [](uint8_t /* key_type */, + tBTM_BLE_LOCAL_KEYS* /* p_key */) {}, + .BTM_SecAddDevice = [](const RawAddress& /* bd_addr */, DEV_CLASS /* dev_class */, + LinkKey /* link_key */, uint8_t /* key_type */, + uint8_t /* pin_length */) {}, + .BTM_SecAddBleDevice = [](const RawAddress& /* bd_addr */, + tBT_DEVICE_TYPE /* dev_type */, + tBLE_ADDR_TYPE /* addr_type */) {}, + .BTM_SecDeleteDevice = [](const RawAddress& /* bd_addr */) -> bool { return true; }, + .BTM_SecAddBleKey = [](const RawAddress& /* bd_addr */, + tBTM_LE_KEY_VALUE* /* p_le_key */, + tBTM_LE_KEY_TYPE /* key_type */) {}, + .BTM_SecClearSecurityFlags = [](const RawAddress& /* bd_addr */) {}, + .BTM_SetEncryption = + [](const RawAddress& /* bd_addr */, tBT_TRANSPORT /* transport */, + tBTM_SEC_CALLBACK* /* p_callback */, void* /* p_ref_data */, + tBTM_BLE_SEC_ACT /* sec_act */) -> tBTM_STATUS { return BTM_SUCCESS; }, + .BTM_IsEncrypted = [](const RawAddress& /* bd_addr */, + tBT_TRANSPORT /* transport */) -> bool { return false; }, + .BTM_SecIsSecurityPending = [](const RawAddress& /* bd_addr */) -> bool { + return false; + }, + .BTM_IsLinkKeyKnown = [](const RawAddress& /* bd_addr */, + tBT_TRANSPORT /* transport */) -> bool { return false; }, + .BTM_SecClrService = [](uint8_t /* service_id */) -> uint8_t { return 0; }, + .BTM_SecClrServiceByPsm = [](uint16_t /* psm */) -> uint8_t { return 0; }, + .BTM_SecBond = [](const RawAddress& /* bd_addr */, tBLE_ADDR_TYPE /* addr_type */, + tBT_TRANSPORT /* transport */, tBT_DEVICE_TYPE /* device_type */) + -> tBTM_STATUS { return BTM_SUCCESS; }, + .BTM_SecBondCancel = [](const RawAddress& /* bd_addr */) -> tBTM_STATUS { + return BTM_SUCCESS; + }, - .BTM_RemoteOobDataReply = - [](tBTM_STATUS /* res */, const RawAddress& /* bd_addr */, - const Octet16& /* c */, const Octet16& /* r */) {}, - .BTM_PINCodeReply = [](const RawAddress& /* bd_addr */, - tBTM_STATUS /* res */, uint8_t /* pin_len */, - uint8_t* /* p_pin */) {}, - .BTM_SecConfirmReqReply = [](tBTM_STATUS /* res */, - tBT_TRANSPORT /* transport */, - const RawAddress /* bd_addr */) {}, - .BTM_BleSirkConfirmDeviceReply = [](const RawAddress& /* bd_addr */, - uint8_t /* res */) {}, - .BTM_BlePasskeyReply = [](const RawAddress& /* bd_addr */, - uint8_t /* res */, uint32_t /* passkey */) {}, - .BTM_GetSecurityMode = []() -> uint8_t { return 0; }, - .BTM_SecReadDevName = [](const RawAddress& /* bd_addr */) - -> const char* { return nullptr; }, - .BTM_SecAddRmtNameNotifyCallback = - [](tBTM_RMT_NAME_CALLBACK* /* p_callback */) -> bool { - return false; - }, - .BTM_SecDeleteRmtNameNotifyCallback = - [](tBTM_RMT_NAME_CALLBACK* /* p_callback */) -> bool { - return false; - }, - }, - .ble = { - .BTM_BleGetEnergyInfo = - [](tBTM_BLE_ENERGY_INFO_CBACK* /* p_ener_cback */) -> tBTM_STATUS { - return BTM_SUCCESS; - }, - .BTM_BleObserve = [](bool /* start */, uint8_t /* duration */, - tBTM_INQ_RESULTS_CB* /* p_results_cb */, - tBTM_CMPL_CB* /* p_cmpl_cb */, - bool /* low_latency_scan */) -> tBTM_STATUS { - return BTM_SUCCESS; - }, - .BTM_SetBleDataLength = [](const RawAddress& /* bd_addr */, - uint16_t /* tx_pdu_length */) - -> tBTM_STATUS { return BTM_SUCCESS; }, - .BTM_BleReadControllerFeatures = - [](tBTM_BLE_CTRL_FEATURES_CBACK* /* p_vsc_cback */) {}, - .BTM_BleSetPhy = [](const RawAddress& /* bd_addr */, - uint8_t /* tx_phys */, uint8_t /* rx_phys */, - uint16_t /* phy_options */) {}, - .BTM_BleSetPrefConnParams = - [](const RawAddress& /* bd_addr */, uint16_t /* min_conn_int */, - uint16_t /* max_conn_int */, uint16_t /* peripheral_latency */, - uint16_t /* supervision_tout */) {}, - .BTM_UseLeLink = [](const RawAddress& /* bd_addr */) -> bool { - return false; - }, - }, - .sco = { - .BTM_CreateSco = [](const RawAddress* /* remote_bda */, - bool /* is_orig */, uint16_t /* pkt_types */, - uint16_t* /* p_sco_inx */, - tBTM_SCO_CB* /* p_conn_cb */, - tBTM_SCO_CB* /* p_disc_cb */) -> tBTM_STATUS { - return BTM_SUCCESS; - }, - .BTM_RegForEScoEvts = [](uint16_t /* sco_inx */, - tBTM_ESCO_CBACK* /* p_esco_cback */) - -> tBTM_STATUS { return BTM_SUCCESS; }, - .BTM_RemoveSco = [](uint16_t /* sco_inx */) -> tBTM_STATUS { - return BTM_SUCCESS; - }, - .BTM_WriteVoiceSettings = [](uint16_t /* settings */) {}, - .BTM_EScoConnRsp = [](uint16_t /* sco_inx */, - tHCI_STATUS /* hci_status */, - enh_esco_params_t* /* p_parms */) {}, - .BTM_GetNumScoLinks = []() -> uint8_t { return 0; }, - .BTM_SetEScoMode = [](enh_esco_params_t* /* p_parms */) -> tBTM_STATUS { - return BTM_SUCCESS; - }, - }, - .local = { - .BTM_ReadLocalDeviceName = [](const char** /* p_name */) - -> tBTM_STATUS { return BTM_SUCCESS; }, - .BTM_ReadLocalDeviceNameFromController = - [](tBTM_CMPL_CB* /* p_rln_cmpl_cback */) -> tBTM_STATUS { - return BTM_SUCCESS; - }, - .BTM_SetLocalDeviceName = [](const char* /* p_name */) -> tBTM_STATUS { - return BTM_SUCCESS; - }, - .BTM_SetDeviceClass = [](DEV_CLASS /* dev_class */) -> tBTM_STATUS { - return BTM_SUCCESS; - }, - .BTM_IsDeviceUp = []() -> bool { return true; }, - .BTM_ReadDeviceClass = []() -> DEV_CLASS { return kDevClassEmpty; }, - }, - .eir = { - .BTM_WriteEIR = [](BT_HDR* /* p_buff */) -> tBTM_STATUS { - return BTM_SUCCESS; - }, - .BTM_GetEirSupportedServices = - [](uint32_t* /* p_eir_uuid */, uint8_t** /* p */, - uint8_t /* max_num_uuid16 */, - uint8_t* /* p_num_uuid16 */) -> uint8_t { return 0; }, - .BTM_GetEirUuidList = - [](const uint8_t* /* p_eir */, size_t /* eir_len */, - uint8_t /* uuid_size */, uint8_t* /* p_num_uuid */, - uint8_t* /* p_uuid_list */, - uint8_t /* max_num_uuid */) -> uint8_t { return 0; }, - .BTM_AddEirService = [](uint32_t* /* p_eir_uuid */, - uint16_t /* uuid16 */) {}, - .BTM_RemoveEirService = [](uint32_t* /* p_eir_uuid */, - uint16_t /* uuid16 */) {}, - }, - .db = { - .BTM_InqDbRead = [](const RawAddress& /* p_bda */) -> tBTM_INQ_INFO* { - return nullptr; - }, - .BTM_InqDbFirst = []() -> tBTM_INQ_INFO* { return nullptr; }, - .BTM_InqDbNext = [](tBTM_INQ_INFO* /* p_cur */) -> tBTM_INQ_INFO* { - return nullptr; - }, - .BTM_ClearInqDb = [](const RawAddress* /* p_bda */) -> tBTM_STATUS { - return BTM_SUCCESS; - }, - }, - .vendor = - { - .BTM_VendorSpecificCommand = - [](uint16_t /* opcode */, uint8_t /* param_len */, - uint8_t* /* p_param_buf */, tBTM_VSC_CMPL_CB* /* p_cb */) {}, - }, + .BTM_RemoteOobDataReply = [](tBTM_STATUS /* res */, const RawAddress& /* bd_addr */, + const Octet16& /* c */, const Octet16& /* r */) {}, + .BTM_PINCodeReply = [](const RawAddress& /* bd_addr */, tBTM_STATUS /* res */, + uint8_t /* pin_len */, uint8_t* /* p_pin */) {}, + .BTM_SecConfirmReqReply = [](tBTM_STATUS /* res */, tBT_TRANSPORT /* transport */, + const RawAddress /* bd_addr */) {}, + .BTM_BleSirkConfirmDeviceReply = [](const RawAddress& /* bd_addr */, + uint8_t /* res */) {}, + .BTM_BlePasskeyReply = [](const RawAddress& /* bd_addr */, uint8_t /* res */, + uint32_t /* passkey */) {}, + .BTM_GetSecurityMode = []() -> uint8_t { return 0; }, + .BTM_SecReadDevName = [](const RawAddress& /* bd_addr */) -> const char* { + return nullptr; + }, + .BTM_SecAddRmtNameNotifyCallback = + [](tBTM_RMT_NAME_CALLBACK* /* p_callback */) -> bool { return false; }, + .BTM_SecDeleteRmtNameNotifyCallback = + [](tBTM_RMT_NAME_CALLBACK* /* p_callback */) -> bool { return false; }, + }, + .ble = { + .BTM_BleGetEnergyInfo = [](tBTM_BLE_ENERGY_INFO_CBACK* /* p_ener_cback */) + -> tBTM_STATUS { return BTM_SUCCESS; }, + .BTM_BleObserve = + [](bool /* start */, uint8_t /* duration */, + tBTM_INQ_RESULTS_CB* /* p_results_cb */, tBTM_CMPL_CB* /* p_cmpl_cb */, + bool /* low_latency_scan */) -> tBTM_STATUS { return BTM_SUCCESS; }, + .BTM_SetBleDataLength = [](const RawAddress& /* bd_addr */, + uint16_t /* tx_pdu_length */) -> tBTM_STATUS { + return BTM_SUCCESS; + }, + .BTM_BleReadControllerFeatures = + [](tBTM_BLE_CTRL_FEATURES_CBACK* /* p_vsc_cback */) {}, + .BTM_BleSetPhy = [](const RawAddress& /* bd_addr */, uint8_t /* tx_phys */, + uint8_t /* rx_phys */, uint16_t /* phy_options */) {}, + .BTM_BleSetPrefConnParams = + [](const RawAddress& /* bd_addr */, uint16_t /* min_conn_int */, + uint16_t /* max_conn_int */, uint16_t /* peripheral_latency */, + uint16_t /* supervision_tout */) {}, + .BTM_UseLeLink = [](const RawAddress& /* bd_addr */) -> bool { return false; }, + }, + .sco = { + .BTM_CreateSco = [](const RawAddress* /* remote_bda */, bool /* is_orig */, + uint16_t /* pkt_types */, uint16_t* /* p_sco_inx */, + tBTM_SCO_CB* /* p_conn_cb */, tBTM_SCO_CB* /* p_disc_cb */) + -> tBTM_STATUS { return BTM_SUCCESS; }, + .BTM_RegForEScoEvts = [](uint16_t /* sco_inx */, + tBTM_ESCO_CBACK* /* p_esco_cback */) -> tBTM_STATUS { + return BTM_SUCCESS; + }, + .BTM_RemoveSco = [](uint16_t /* sco_inx */) -> tBTM_STATUS { return BTM_SUCCESS; }, + .BTM_WriteVoiceSettings = [](uint16_t /* settings */) {}, + .BTM_EScoConnRsp = [](uint16_t /* sco_inx */, tHCI_STATUS /* hci_status */, + enh_esco_params_t* /* p_parms */) {}, + .BTM_GetNumScoLinks = []() -> uint8_t { return 0; }, + .BTM_SetEScoMode = [](enh_esco_params_t* /* p_parms */) -> tBTM_STATUS { + return BTM_SUCCESS; + }, + }, + .local = { + .BTM_ReadLocalDeviceName = [](const char** /* p_name */) -> tBTM_STATUS { + return BTM_SUCCESS; + }, + .BTM_ReadLocalDeviceNameFromController = [](tBTM_CMPL_CB* /* p_rln_cmpl_cback */) + -> tBTM_STATUS { return BTM_SUCCESS; }, + .BTM_SetLocalDeviceName = [](const char* /* p_name */) -> tBTM_STATUS { + return BTM_SUCCESS; + }, + .BTM_SetDeviceClass = [](DEV_CLASS /* dev_class */) -> tBTM_STATUS { + return BTM_SUCCESS; + }, + .BTM_IsDeviceUp = []() -> bool { return true; }, + .BTM_ReadDeviceClass = []() -> DEV_CLASS { return kDevClassEmpty; }, + }, + .eir = { + .BTM_WriteEIR = [](BT_HDR* /* p_buff */) -> tBTM_STATUS { return BTM_SUCCESS; }, + .BTM_GetEirSupportedServices = [](uint32_t* /* p_eir_uuid */, uint8_t** /* p */, + uint8_t /* max_num_uuid16 */, + uint8_t* /* p_num_uuid16 */) -> uint8_t { + return 0; + }, + .BTM_GetEirUuidList = [](const uint8_t* /* p_eir */, size_t /* eir_len */, + uint8_t /* uuid_size */, uint8_t* /* p_num_uuid */, + uint8_t* /* p_uuid_list */, + uint8_t /* max_num_uuid */) -> uint8_t { return 0; }, + .BTM_AddEirService = [](uint32_t* /* p_eir_uuid */, uint16_t /* uuid16 */) {}, + .BTM_RemoveEirService = [](uint32_t* /* p_eir_uuid */, uint16_t /* uuid16 */) {}, + }, + .db = { + .BTM_InqDbRead = [](const RawAddress& /* p_bda */) -> tBTM_INQ_INFO* { + return nullptr; + }, + .BTM_InqDbFirst = []() -> tBTM_INQ_INFO* { return nullptr; }, + .BTM_InqDbNext = [](tBTM_INQ_INFO* /* p_cur */) -> tBTM_INQ_INFO* { + return nullptr; + }, + .BTM_ClearInqDb = [](const RawAddress* /* p_bda */) -> tBTM_STATUS { + return BTM_SUCCESS; + }, + }, + .vendor = + { + .BTM_VendorSpecificCommand = + [](uint16_t /* opcode */, uint8_t /* param_len */, + uint8_t* /* p_param_buf */, tBTM_VSC_CMPL_CB* /* p_cb */) {}, + }, }; } // namespace void BTM_BleReadControllerFeatures(void (*)(tHCI_ERROR_CODE)) {} -tBTM_STATUS BTM_BleGetEnergyInfo( - tBTM_BLE_ENERGY_INFO_CBACK* /* p_ener_cback */) { +tBTM_STATUS BTM_BleGetEnergyInfo(tBTM_BLE_ENERGY_INFO_CBACK* /* p_ener_cback */) { return BTM_SUCCESS; } // Initialize the working btm client interface to the default -struct btm_client_interface_t mock_btm_client_interface = - default_btm_client_interface; +struct btm_client_interface_t mock_btm_client_interface = default_btm_client_interface; // Reset the working btm client interface to the default -void reset_mock_btm_client_interface() { - mock_btm_client_interface = default_btm_client_interface; -} +void reset_mock_btm_client_interface() { mock_btm_client_interface = default_btm_client_interface; } // Serve the working btm client interface -struct btm_client_interface_t& get_btm_client_interface() { - return mock_btm_client_interface; -} +struct btm_client_interface_t& get_btm_client_interface() { return mock_btm_client_interface; } diff --git a/system/test/mock/mock_stack_btm_iso.cc b/system/test/mock/mock_stack_btm_iso.cc index 06d1a4096ef..b3d291765b1 100644 --- a/system/test/mock/mock_stack_btm_iso.cc +++ b/system/test/mock/mock_stack_btm_iso.cc @@ -30,108 +30,132 @@ namespace bluetooth { namespace hci { struct IsoManager::impl : public MockIsoManager { - public: +public: impl() = default; ~impl() = default; }; IsoManager::IsoManager() {} -void IsoManager::RegisterCigCallbacks( - iso_manager::CigCallbacks* callbacks) const { - if (!pimpl_) return; +void IsoManager::RegisterCigCallbacks(iso_manager::CigCallbacks* callbacks) const { + if (!pimpl_) { + return; + } pimpl_->RegisterCigCallbacks(callbacks); } -void IsoManager::RegisterBigCallbacks( - iso_manager::BigCallbacks* callbacks) const { - if (!pimpl_) return; +void IsoManager::RegisterBigCallbacks(iso_manager::BigCallbacks* callbacks) const { + if (!pimpl_) { + return; + } pimpl_->RegisterBigCallbacks(callbacks); } void IsoManager::RegisterOnIsoTrafficActiveCallback(void callback(bool)) const { - if (!pimpl_) return; + if (!pimpl_) { + return; + } pimpl_->RegisterOnIsoTrafficActiveCallbacks(callback); } -void IsoManager::CreateCig(uint8_t cig_id, - struct iso_manager::cig_create_params cig_params) { - if (!pimpl_) return; +void IsoManager::CreateCig(uint8_t cig_id, struct iso_manager::cig_create_params cig_params) { + if (!pimpl_) { + return; + } pimpl_->CreateCig(cig_id, std::move(cig_params)); } -void IsoManager::ReconfigureCig( - uint8_t cig_id, struct iso_manager::cig_create_params cig_params) { - if (!pimpl_) return; +void IsoManager::ReconfigureCig(uint8_t cig_id, struct iso_manager::cig_create_params cig_params) { + if (!pimpl_) { + return; + } pimpl_->ReconfigureCig(cig_id, std::move(cig_params)); } -void IsoManager::RemoveCig(uint8_t cig_id, bool force) { - pimpl_->RemoveCig(cig_id, force); -} +void IsoManager::RemoveCig(uint8_t cig_id, bool force) { pimpl_->RemoveCig(cig_id, force); } -void IsoManager::EstablishCis( - struct iso_manager::cis_establish_params conn_params) { - if (!pimpl_) return; +void IsoManager::EstablishCis(struct iso_manager::cis_establish_params conn_params) { + if (!pimpl_) { + return; + } pimpl_->EstablishCis(std::move(conn_params)); } void IsoManager::DisconnectCis(uint16_t cis_handle, uint8_t reason) { - if (!pimpl_) return; + if (!pimpl_) { + return; + } pimpl_->DisconnectCis(cis_handle, reason); } -void IsoManager::SetupIsoDataPath( - uint16_t iso_handle, struct iso_manager::iso_data_path_params path_params) { - if (!pimpl_) return; +void IsoManager::SetupIsoDataPath(uint16_t iso_handle, + struct iso_manager::iso_data_path_params path_params) { + if (!pimpl_) { + return; + } pimpl_->SetupIsoDataPath(iso_handle, std::move(path_params)); } void IsoManager::RemoveIsoDataPath(uint16_t iso_handle, uint8_t data_path_dir) { - if (!pimpl_) return; + if (!pimpl_) { + return; + } pimpl_->RemoveIsoDataPath(iso_handle, data_path_dir); } void IsoManager::ReadIsoLinkQuality(uint16_t iso_handle) { - if (!pimpl_) return; + if (!pimpl_) { + return; + } pimpl_->ReadIsoLinkQuality(iso_handle); } -void IsoManager::SendIsoData(uint16_t iso_handle, const uint8_t* data, - uint16_t data_len) { - if (!pimpl_) return; +void IsoManager::SendIsoData(uint16_t iso_handle, const uint8_t* data, uint16_t data_len) { + if (!pimpl_) { + return; + } pimpl_->SendIsoData(iso_handle, data, data_len); } -void IsoManager::CreateBig(uint8_t big_id, - struct iso_manager::big_create_params big_params) { - if (!pimpl_) return; +void IsoManager::CreateBig(uint8_t big_id, struct iso_manager::big_create_params big_params) { + if (!pimpl_) { + return; + } pimpl_->CreateBig(big_id, std::move(big_params)); } void IsoManager::TerminateBig(uint8_t big_id, uint8_t reason) { - if (!pimpl_) return; + if (!pimpl_) { + return; + } pimpl_->TerminateBig(big_id, reason); } void IsoManager::HandleIsoData(void* p_msg) { - if (!pimpl_) return; + if (!pimpl_) { + return; + } pimpl_->HandleIsoData(static_cast(p_msg)); } void IsoManager::HandleDisconnect(uint16_t handle, uint8_t reason) { - if (!pimpl_) return; + if (!pimpl_) { + return; + } pimpl_->HandleDisconnect(handle, reason); } void IsoManager::HandleNumComplDataPkts(uint16_t handle, uint16_t credits) { - if (!pimpl_) return; + if (!pimpl_) { + return; + } pimpl_->HandleNumComplDataPkts(handle, credits); } -void IsoManager::HandleHciEvent(uint8_t sub_code, uint8_t* params, - uint16_t length) { - if (!pimpl_) return; +void IsoManager::HandleHciEvent(uint8_t sub_code, uint8_t* params, uint16_t length) { + if (!pimpl_) { + return; + } pimpl_->HandleHciEvent(sub_code, params, length); } @@ -157,9 +181,7 @@ void IsoManager::Stop() { mock_pimpl_ = nullptr; } -int IsoManager::GetNumberOfActiveIso() { - return pimpl_->GetNumberOfActiveIso(); -} +int IsoManager::GetNumberOfActiveIso() { return pimpl_->GetNumberOfActiveIso(); } void IsoManager::Dump(int /* fd */) {} diff --git a/system/test/mock/mock_stack_btm_iso.h b/system/test/mock/mock_stack_btm_iso.h index 4d7a49634e5..4d1b8d2111f 100644 --- a/system/test/mock/mock_stack_btm_iso.h +++ b/system/test/mock/mock_stack_btm_iso.h @@ -22,7 +22,7 @@ #include "stack/include/btm_iso_api.h" struct MockIsoManager { - public: +public: static MockIsoManager* GetInstance(); MockIsoManager() = default; @@ -31,46 +31,33 @@ struct MockIsoManager { virtual ~MockIsoManager() = default; - MOCK_METHOD((void), RegisterCigCallbacks, - (bluetooth::hci::iso_manager::CigCallbacks * callbacks), (const)); - MOCK_METHOD((void), RegisterBigCallbacks, - (bluetooth::hci::iso_manager::BigCallbacks * callbacks), (const)); - MOCK_METHOD((void), RegisterOnIsoTrafficActiveCallbacks, - (void callbacks(bool)), (const)); - MOCK_METHOD( - (void), CreateCig, - (uint8_t cig_id, - struct bluetooth::hci::iso_manager::cig_create_params cig_params)); - MOCK_METHOD( - (void), ReconfigureCig, - (uint8_t cig_id, - struct bluetooth::hci::iso_manager::cig_create_params cig_params)); + MOCK_METHOD((void), RegisterCigCallbacks, (bluetooth::hci::iso_manager::CigCallbacks * callbacks), + (const)); + MOCK_METHOD((void), RegisterBigCallbacks, (bluetooth::hci::iso_manager::BigCallbacks * callbacks), + (const)); + MOCK_METHOD((void), RegisterOnIsoTrafficActiveCallbacks, (void callbacks(bool)), (const)); + MOCK_METHOD((void), CreateCig, + (uint8_t cig_id, struct bluetooth::hci::iso_manager::cig_create_params cig_params)); + MOCK_METHOD((void), ReconfigureCig, + (uint8_t cig_id, struct bluetooth::hci::iso_manager::cig_create_params cig_params)); MOCK_METHOD((void), RemoveCig, (uint8_t cig_id, bool force)); - MOCK_METHOD( - (void), EstablishCis, - (struct bluetooth::hci::iso_manager::cis_establish_params conn_params)); + MOCK_METHOD((void), EstablishCis, + (struct bluetooth::hci::iso_manager::cis_establish_params conn_params)); MOCK_METHOD((void), DisconnectCis, (uint16_t cis_handle, uint8_t reason)); MOCK_METHOD((int), GetNumberOfActiveIso, ()); - MOCK_METHOD( - (void), SetupIsoDataPath, - (uint16_t iso_handle, - struct bluetooth::hci::iso_manager::iso_data_path_params path_params)); - MOCK_METHOD((void), RemoveIsoDataPath, - (uint16_t iso_handle, uint8_t data_path_dir)); - MOCK_METHOD((void), SendIsoData, - (uint16_t iso_handle, const uint8_t* data, uint16_t data_len)); + MOCK_METHOD((void), SetupIsoDataPath, + (uint16_t iso_handle, + struct bluetooth::hci::iso_manager::iso_data_path_params path_params)); + MOCK_METHOD((void), RemoveIsoDataPath, (uint16_t iso_handle, uint8_t data_path_dir)); + MOCK_METHOD((void), SendIsoData, (uint16_t iso_handle, const uint8_t* data, uint16_t data_len)); MOCK_METHOD((void), ReadIsoLinkQuality, (uint16_t iso_handle)); - MOCK_METHOD( - (void), CreateBig, - (uint8_t big_id, - struct bluetooth::hci::iso_manager::big_create_params big_params)); + MOCK_METHOD((void), CreateBig, + (uint8_t big_id, struct bluetooth::hci::iso_manager::big_create_params big_params)); MOCK_METHOD((void), TerminateBig, (uint8_t big_id, uint8_t reason)); MOCK_METHOD((void), HandleIsoData, (void* p_msg)); MOCK_METHOD((void), HandleDisconnect, (uint16_t handle, uint8_t reason)); - MOCK_METHOD((void), HandleNumComplDataPkts, - (uint16_t handle, uint16_t credits)); - MOCK_METHOD((void), HandleHciEvent, - (uint8_t sub_code, uint8_t* params, uint16_t length)); + MOCK_METHOD((void), HandleNumComplDataPkts, (uint16_t handle, uint16_t credits)); + MOCK_METHOD((void), HandleHciEvent, (uint8_t sub_code, uint8_t* params, uint16_t length)); MOCK_METHOD((void), Start, ()); MOCK_METHOD((void), Stop, ()); diff --git a/system/test/mock/mock_stack_btm_main.cc b/system/test/mock/mock_stack_btm_main.cc index 31d2dae958f..b22ac8e7f45 100644 --- a/system/test/mock/mock_stack_btm_main.cc +++ b/system/test/mock/mock_stack_btm_main.cc @@ -25,26 +25,20 @@ #include "types/ble_address_with_type.h" #include "types/raw_address.h" -void BTM_LogHistory(const std::string& /* tag */, - const RawAddress& /* bd_addr */, +void BTM_LogHistory(const std::string& /* tag */, const RawAddress& /* bd_addr */, const std::string& /* msg */) { inc_func_call_count(__func__); } -void BTM_LogHistory(const std::string& /* tag */, - const RawAddress& /* bd_addr */, - const std::string& /* msg */, - const std::string& /* extra */) { +void BTM_LogHistory(const std::string& /* tag */, const RawAddress& /* bd_addr */, + const std::string& /* msg */, const std::string& /* extra */) { inc_func_call_count(__func__); } -void BTM_LogHistory(const std::string& /* tag */, - const tBLE_BD_ADDR& /* ble_bd_addr */, +void BTM_LogHistory(const std::string& /* tag */, const tBLE_BD_ADDR& /* ble_bd_addr */, const std::string& /* msg */) { inc_func_call_count(__func__); } -void BTM_LogHistory(const std::string& /* tag */, - const tBLE_BD_ADDR& /* ble_bd_addr */, - const std::string& /* msg */, - const std::string& /* extra */) { +void BTM_LogHistory(const std::string& /* tag */, const tBLE_BD_ADDR& /* ble_bd_addr */, + const std::string& /* msg */, const std::string& /* extra */) { inc_func_call_count(__func__); } void btm_free(void) { inc_func_call_count(__func__); } diff --git a/system/test/mock/mock_stack_btm_sco.cc b/system/test/mock/mock_stack_btm_sco.cc index 95ebdd38a6b..b4c21b1e7a2 100644 --- a/system/test/mock/mock_stack_btm_sco.cc +++ b/system/test/mock/mock_stack_btm_sco.cc @@ -42,16 +42,13 @@ const RawAddress* BTM_ReadScoBdAddr(uint16_t /* sco_inx */) { inc_func_call_count(__func__); return nullptr; } -tBTM_STATUS BTM_CreateSco(const RawAddress* /* remote_bda */, - bool /* is_orig */, uint16_t /* pkt_types */, - uint16_t* /* p_sco_inx */, - tBTM_SCO_CB* /* p_conn_cb */, - tBTM_SCO_CB* /* p_disc_cb */) { +tBTM_STATUS BTM_CreateSco(const RawAddress* /* remote_bda */, bool /* is_orig */, + uint16_t /* pkt_types */, uint16_t* /* p_sco_inx */, + tBTM_SCO_CB* /* p_conn_cb */, tBTM_SCO_CB* /* p_disc_cb */) { inc_func_call_count(__func__); return BTM_SUCCESS; } -tBTM_STATUS BTM_RegForEScoEvts(uint16_t /* sco_inx */, - tBTM_ESCO_CBACK* /* p_esco_cback */) { +tBTM_STATUS BTM_RegForEScoEvts(uint16_t /* sco_inx */, tBTM_ESCO_CBACK* /* p_esco_cback */) { inc_func_call_count(__func__); return BTM_SUCCESS; } @@ -75,21 +72,13 @@ void BTM_EScoConnRsp(uint16_t /* sco_inx */, tHCI_STATUS /* hci_status */, enh_esco_params_t* /* p_parms */) { inc_func_call_count(__func__); } -void BTM_RemoveSco(const RawAddress& /* bda */) { +void BTM_RemoveSco(const RawAddress& /* bda */) { inc_func_call_count(__func__); } +void btm_sco_acl_removed(const RawAddress* /* bda */) { inc_func_call_count(__func__); } +void btm_sco_chk_pend_rolechange(uint16_t /* hci_handle */) { inc_func_call_count(__func__); } +void btm_sco_chk_pend_unpark(tHCI_STATUS /* hci_status */, uint16_t /* hci_handle */) { inc_func_call_count(__func__); } -void btm_sco_acl_removed(const RawAddress* /* bda */) { - inc_func_call_count(__func__); -} -void btm_sco_chk_pend_rolechange(uint16_t /* hci_handle */) { - inc_func_call_count(__func__); -} -void btm_sco_chk_pend_unpark(tHCI_STATUS /* hci_status */, - uint16_t /* hci_handle */) { - inc_func_call_count(__func__); -} -void btm_sco_conn_req(const RawAddress& /* bda */, - const DEV_CLASS& /* dev_class */, +void btm_sco_conn_req(const RawAddress& /* bda */, const DEV_CLASS& /* dev_class */, uint8_t /* link_type */) { inc_func_call_count(__func__); } @@ -97,27 +86,22 @@ void btm_sco_connected(const RawAddress& /* bda */, uint16_t /* hci_handle */, tBTM_ESCO_DATA* /* p_esco_data */) { inc_func_call_count(__func__); } -void btm_sco_connection_failed(tHCI_STATUS /* hci_status */, - const RawAddress& /* bda */, - uint16_t /* hci_handle */, - tBTM_ESCO_DATA* /* p_esco_data */) { +void btm_sco_connection_failed(tHCI_STATUS /* hci_status */, const RawAddress& /* bda */, + uint16_t /* hci_handle */, tBTM_ESCO_DATA* /* p_esco_data */) { inc_func_call_count(__func__); } void btm_sco_disc_chk_pend_for_modechange(uint16_t /* hci_handle */) { inc_func_call_count(__func__); } -void btm_sco_on_esco_connect_request( - const RawAddress& /* bda */, - const bluetooth::hci::ClassOfDevice& /* cod */) { +void btm_sco_on_esco_connect_request(const RawAddress& /* bda */, + const bluetooth::hci::ClassOfDevice& /* cod */) { inc_func_call_count(__func__); } -void btm_sco_on_sco_connect_request( - const RawAddress& /* bda */, - const bluetooth::hci::ClassOfDevice& /* cod */) { +void btm_sco_on_sco_connect_request(const RawAddress& /* bda */, + const bluetooth::hci::ClassOfDevice& /* cod */) { inc_func_call_count(__func__); } -void btm_sco_on_disconnected(uint16_t /* hci_handle */, - tHCI_REASON /* reason */) { +void btm_sco_on_disconnected(uint16_t /* hci_handle */, tHCI_REASON /* reason */) { inc_func_call_count(__func__); } bool btm_peer_supports_esco_2m_phy(RawAddress /* bd_addr */) { diff --git a/system/test/mock/mock_stack_btm_sco_hfp_hal.cc b/system/test/mock/mock_stack_btm_sco_hfp_hal.cc index ba2221c73f5..568e8d8c074 100644 --- a/system/test/mock/mock_stack_btm_sco_hfp_hal.cc +++ b/system/test/mock/mock_stack_btm_sco_hfp_hal.cc @@ -104,18 +104,15 @@ bool get_swb_supported() { } bool is_coding_format_supported(esco_coding_format_t coding_format) { inc_func_call_count(__func__); - return test::mock::stack_btm_sco_hfp_hal::is_coding_format_supported( - coding_format); + return test::mock::stack_btm_sco_hfp_hal::is_coding_format_supported(coding_format); } void init() { inc_func_call_count(__func__); test::mock::stack_btm_sco_hfp_hal::init(); } -void notify_sco_connection_change(RawAddress device, bool is_connected, - int codec) { +void notify_sco_connection_change(RawAddress device, bool is_connected, int codec) { inc_func_call_count(__func__); - test::mock::stack_btm_sco_hfp_hal::notify_sco_connection_change( - device, is_connected, codec); + test::mock::stack_btm_sco_hfp_hal::notify_sco_connection_change(device, is_connected, codec); } void set_codec_datapath(tBTA_AG_UUID_CODEC coding_format) { inc_func_call_count(__func__); diff --git a/system/test/mock/mock_stack_btm_sco_hfp_hal.h b/system/test/mock/mock_stack_btm_sco_hfp_hal.h index d4529219b59..c8cdd4280b5 100644 --- a/system/test/mock/mock_stack_btm_sco_hfp_hal.h +++ b/system/test/mock/mock_stack_btm_sco_hfp_hal.h @@ -44,9 +44,8 @@ namespace stack_btm_sco_hfp_hal { // Return: bool struct enable_offload { static bool return_value; - std::function body{ - [](bool /* enable */) { return return_value; }}; - bool operator()(bool enable) { return body(enable); }; + std::function body{[](bool /* enable */) { return return_value; }}; + bool operator()(bool enable) { return body(enable); } }; extern struct enable_offload enable_offload; @@ -56,10 +55,8 @@ extern struct enable_offload enable_offload; struct get_codec_capabilities { static hfp_hal_interface::bt_codecs return_value; std::function body{ - [](uint64_t /* codecs */) { return return_value; }}; - hfp_hal_interface::bt_codecs operator()(uint64_t codecs) { - return body(codecs); - }; + [](uint64_t /* codecs */) { return return_value; }}; + hfp_hal_interface::bt_codecs operator()(uint64_t codecs) { return body(codecs); } }; extern struct get_codec_capabilities get_codec_capabilities; @@ -69,7 +66,7 @@ extern struct get_codec_capabilities get_codec_capabilities; struct get_offload_enabled { static bool return_value; std::function body{[]() { return return_value; }}; - bool operator()() { return body(); }; + bool operator()() { return body(); } }; extern struct get_offload_enabled get_offload_enabled; @@ -79,7 +76,7 @@ extern struct get_offload_enabled get_offload_enabled; struct get_offload_supported { static bool return_value; std::function body{[]() { return return_value; }}; - bool operator()() { return body(); }; + bool operator()() { return body(); } }; extern struct get_offload_supported get_offload_supported; @@ -88,9 +85,8 @@ extern struct get_offload_supported get_offload_supported; // Return: size_t struct get_packet_size { static size_t return_value; - std::function body{ - [](int /* codec */) { return return_value; }}; - size_t operator()(int codec) { return body(codec); }; + std::function body{[](int /* codec */) { return return_value; }}; + size_t operator()(int codec) { return body(codec); } }; extern struct get_packet_size get_packet_size; @@ -100,7 +96,7 @@ extern struct get_packet_size get_packet_size; struct get_wbs_supported { static bool return_value; std::function body{[]() { return return_value; }}; - bool operator()() { return body(); }; + bool operator()() { return body(); } }; extern struct get_wbs_supported get_wbs_supported; @@ -110,7 +106,7 @@ extern struct get_wbs_supported get_wbs_supported; struct get_swb_supported { static bool return_value; std::function body{[]() { return return_value; }}; - bool operator()() { return body(); }; + bool operator()() { return body(); } }; extern struct get_swb_supported get_swb_supported; @@ -120,10 +116,8 @@ extern struct get_swb_supported get_swb_supported; struct is_coding_format_supported { static bool return_value; std::function body{ - [](esco_coding_format_t /* coding_format */) { return return_value; }}; - bool operator()(esco_coding_format_t coding_format) { - return body(coding_format); - }; + [](esco_coding_format_t /* coding_format */) { return return_value; }}; + bool operator()(esco_coding_format_t coding_format) { return body(coding_format); } }; extern struct is_coding_format_supported is_coding_format_supported; @@ -132,7 +126,7 @@ extern struct is_coding_format_supported is_coding_format_supported; // Return: void struct init { std::function body{[]() {}}; - void operator()() { body(); }; + void operator()() { body(); } }; extern struct init init; @@ -141,10 +135,10 @@ extern struct init init; // Return: void struct notify_sco_connection_change { std::function body{ - [](RawAddress /* device */, bool /* is_connected */, int /* codec */) {}}; + [](RawAddress /* device */, bool /* is_connected */, int /* codec */) {}}; void operator()(RawAddress device, bool is_connected, int codec) { body(device, is_connected, codec); - }; + } }; extern struct notify_sco_connection_change notify_sco_connection_change; @@ -153,8 +147,8 @@ extern struct notify_sco_connection_change notify_sco_connection_change; // Return: void struct set_codec_datapath { std::function body{ - [](tBTA_AG_UUID_CODEC /* coding_format */) {}}; - void operator()(tBTA_AG_UUID_CODEC coding_format) { body(coding_format); }; + [](tBTA_AG_UUID_CODEC /* coding_format */) {}}; + void operator()(tBTA_AG_UUID_CODEC coding_format) { body(coding_format); } }; extern struct set_codec_datapath set_codec_datapath; @@ -162,9 +156,8 @@ extern struct set_codec_datapath set_codec_datapath; // Params: enh_esco_params_t* p_parms // Return: void struct update_esco_parameters { - std::function body{ - [](enh_esco_params_t* /* p_parms */) {}}; - void operator()(enh_esco_params_t* p_parms) { body(p_parms); }; + std::function body{[](enh_esco_params_t* /* p_parms */) {}}; + void operator()(enh_esco_params_t* p_parms) { body(p_parms); } }; extern struct update_esco_parameters update_esco_parameters; diff --git a/system/test/mock/mock_stack_btm_sec.cc b/system/test/mock/mock_stack_btm_sec.cc index b65c9c14e54..bae24c1a4f7 100644 --- a/system/test/mock/mock_stack_btm_sec.cc +++ b/system/test/mock/mock_stack_btm_sec.cc @@ -39,8 +39,7 @@ namespace mock { namespace stack_btm_sec { // Function state capture and return values, if needed -struct BTM_CanReadDiscoverableCharacteristics - BTM_CanReadDiscoverableCharacteristics; +struct BTM_CanReadDiscoverableCharacteristics BTM_CanReadDiscoverableCharacteristics; struct BTM_ConfirmReqReply BTM_ConfirmReqReply; struct BTM_GetPeerDeviceTypeFromFeatures BTM_GetPeerDeviceTypeFromFeatures; struct BTM_IsAuthenticated BTM_IsAuthenticated; @@ -89,11 +88,9 @@ struct btm_sec_encrypt_change btm_sec_encrypt_change; struct btm_sec_encryption_change_evt btm_sec_encryption_change_evt; struct btm_sec_is_a_bonded_dev btm_sec_is_a_bonded_dev; struct btm_sec_l2cap_access_req btm_sec_l2cap_access_req; -struct btm_sec_l2cap_access_req_by_requirement - btm_sec_l2cap_access_req_by_requirement; +struct btm_sec_l2cap_access_req_by_requirement btm_sec_l2cap_access_req_by_requirement; struct btm_sec_link_key_notification btm_sec_link_key_notification; -struct btm_sec_encryption_key_refresh_complete - btm_sec_encryption_key_refresh_complete; +struct btm_sec_encryption_key_refresh_complete btm_sec_encryption_key_refresh_complete; struct btm_sec_link_key_request btm_sec_link_key_request; struct btm_sec_mx_access_request btm_sec_mx_access_request; struct btm_sec_pin_code_request btm_sec_pin_code_request; @@ -150,8 +147,7 @@ bool BTM_IsRemoteNameKnown::return_value = false; // Mocked functions, if any bool BTM_CanReadDiscoverableCharacteristics(const RawAddress& bd_addr) { inc_func_call_count(__func__); - return test::mock::stack_btm_sec::BTM_CanReadDiscoverableCharacteristics( - bd_addr); + return test::mock::stack_btm_sec::BTM_CanReadDiscoverableCharacteristics(bd_addr); } void BTM_ConfirmReqReply(tBTM_STATUS res, const RawAddress& bd_addr) { inc_func_call_count(__func__); @@ -177,13 +173,11 @@ bool BTM_IsLinkKeyKnown(const RawAddress& bd_addr, tBT_TRANSPORT transport) { inc_func_call_count(__func__); return test::mock::stack_btm_sec::BTM_IsLinkKeyKnown(bd_addr, transport); } -void BTM_PINCodeReply(const RawAddress& bd_addr, tBTM_STATUS res, - uint8_t pin_len, uint8_t* p_pin) { +void BTM_PINCodeReply(const RawAddress& bd_addr, tBTM_STATUS res, uint8_t pin_len, uint8_t* p_pin) { inc_func_call_count(__func__); test::mock::stack_btm_sec::BTM_PINCodeReply(bd_addr, res, pin_len, p_pin); } -void BTM_PasskeyReqReply(tBTM_STATUS res, const RawAddress& bd_addr, - uint32_t passkey) { +void BTM_PasskeyReqReply(tBTM_STATUS res, const RawAddress& bd_addr, uint32_t passkey) { inc_func_call_count(__func__); test::mock::stack_btm_sec::BTM_PasskeyReqReply(res, bd_addr, passkey); } @@ -195,8 +189,8 @@ void BTM_ReadLocalOobData(void) { inc_func_call_count(__func__); test::mock::stack_btm_sec::BTM_ReadLocalOobData(); } -void BTM_RemoteOobDataReply(tBTM_STATUS res, const RawAddress& bd_addr, - const Octet16& c, const Octet16& r) { +void BTM_RemoteOobDataReply(tBTM_STATUS res, const RawAddress& bd_addr, const Octet16& c, + const Octet16& r) { inc_func_call_count(__func__); test::mock::stack_btm_sec::BTM_RemoteOobDataReply(res, bd_addr, c, r); } @@ -207,8 +201,7 @@ bool BTM_SecAddRmtNameNotifyCallback(tBTM_RMT_NAME_CALLBACK* p_callback) { tBTM_STATUS BTM_SecBond(const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type, tBT_TRANSPORT transport, tBT_DEVICE_TYPE device_type) { inc_func_call_count(__func__); - return test::mock::stack_btm_sec::BTM_SecBond(bd_addr, addr_type, transport, - device_type); + return test::mock::stack_btm_sec::BTM_SecBond(bd_addr, addr_type, transport, device_type); } tBTM_STATUS BTM_SecBondCancel(const RawAddress& bd_addr) { inc_func_call_count(__func__); @@ -224,8 +217,7 @@ uint8_t BTM_SecClrServiceByPsm(uint16_t psm) { } bool BTM_SecDeleteRmtNameNotifyCallback(tBTM_RMT_NAME_CALLBACK* p_callback) { inc_func_call_count(__func__); - return test::mock::stack_btm_sec::BTM_SecDeleteRmtNameNotifyCallback( - p_callback); + return test::mock::stack_btm_sec::BTM_SecDeleteRmtNameNotifyCallback(p_callback); } tBTM_LINK_KEY_TYPE BTM_SecGetDeviceLinkKeyType(const RawAddress& bd_addr) { inc_func_call_count(__func__); @@ -239,31 +231,28 @@ bool BTM_SecRegister(const tBTM_APPL_INFO* p_cb_info) { inc_func_call_count(__func__); return test::mock::stack_btm_sec::BTM_SecRegister(p_cb_info); } -tBTM_STATUS BTM_SetEncryption(const RawAddress& bd_addr, - tBT_TRANSPORT transport, +tBTM_STATUS BTM_SetEncryption(const RawAddress& bd_addr, tBT_TRANSPORT transport, tBTM_SEC_CALLBACK* p_callback, void* p_ref_data, tBTM_BLE_SEC_ACT sec_act) { inc_func_call_count(__func__); - return test::mock::stack_btm_sec::BTM_SetEncryption( - bd_addr, transport, p_callback, p_ref_data, sec_act); + return test::mock::stack_btm_sec::BTM_SetEncryption(bd_addr, transport, p_callback, p_ref_data, + sec_act); } void BTM_SetPinType(uint8_t pin_type, PIN_CODE pin_code, uint8_t pin_code_len) { inc_func_call_count(__func__); test::mock::stack_btm_sec::BTM_SetPinType(pin_type, pin_code, pin_code_len); } -bool BTM_SetSecurityLevel(bool is_originator, const char* p_name, - uint8_t service_id, uint16_t sec_level, uint16_t psm, - uint32_t mx_proto_id, uint32_t mx_chan_id) { +bool BTM_SetSecurityLevel(bool is_originator, const char* p_name, uint8_t service_id, + uint16_t sec_level, uint16_t psm, uint32_t mx_proto_id, + uint32_t mx_chan_id) { inc_func_call_count(__func__); - return test::mock::stack_btm_sec::BTM_SetSecurityLevel( - is_originator, p_name, service_id, sec_level, psm, mx_proto_id, - mx_chan_id); + return test::mock::stack_btm_sec::BTM_SetSecurityLevel(is_originator, p_name, service_id, + sec_level, psm, mx_proto_id, mx_chan_id); } void BTM_update_version_info(const RawAddress& bd_addr, const remote_version_info& remote_version_info) { inc_func_call_count(__func__); - test::mock::stack_btm_sec::BTM_update_version_info(bd_addr, - remote_version_info); + test::mock::stack_btm_sec::BTM_update_version_info(bd_addr, remote_version_info); } void NotifyBondingCanceled(tBTM_STATUS btm_status) { inc_func_call_count(__func__); @@ -285,8 +274,7 @@ void btm_io_capabilities_rsp(const tBTM_SP_IO_RSP evt_data) { inc_func_call_count(__func__); test::mock::stack_btm_sec::btm_io_capabilities_rsp(evt_data); } -void btm_proc_sp_req_evt(tBTM_SP_EVT event, const RawAddress bd_addr, - uint32_t value) { +void btm_proc_sp_req_evt(tBTM_SP_EVT event, const RawAddress bd_addr, uint32_t value) { inc_func_call_count(__func__); test::mock::stack_btm_sec::btm_proc_sp_req_evt(event, bd_addr, value); } @@ -306,12 +294,10 @@ void btm_sec_auth_complete(uint16_t handle, tHCI_STATUS status) { inc_func_call_count(__func__); test::mock::stack_btm_sec::btm_sec_auth_complete(handle, status); } -tBTM_STATUS btm_sec_bond_by_transport(const RawAddress& bd_addr, - tBLE_ADDR_TYPE addr_type, +tBTM_STATUS btm_sec_bond_by_transport(const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type, tBT_TRANSPORT transport) { inc_func_call_count(__func__); - return test::mock::stack_btm_sec::btm_sec_bond_by_transport( - bd_addr, addr_type, transport); + return test::mock::stack_btm_sec::btm_sec_bond_by_transport(bd_addr, addr_type, transport); } void btm_sec_check_pending_reqs(void) { inc_func_call_count(__func__); @@ -325,126 +311,103 @@ void btm_sec_conn_req(const RawAddress& bda, const DEV_CLASS dc) { inc_func_call_count(__func__); test::mock::stack_btm_sec::btm_sec_conn_req(bda, dc); } -void btm_sec_connected(const RawAddress& bda, uint16_t handle, - tHCI_STATUS status, uint8_t enc_mode, +void btm_sec_connected(const RawAddress& bda, uint16_t handle, tHCI_STATUS status, uint8_t enc_mode, tHCI_ROLE assigned_role) { inc_func_call_count(__func__); - test::mock::stack_btm_sec::btm_sec_connected(bda, handle, status, enc_mode, - assigned_role); + test::mock::stack_btm_sec::btm_sec_connected(bda, handle, status, enc_mode, assigned_role); } void btm_sec_cr_loc_oob_data_cback_event(const RawAddress& address, tSMP_LOC_OOB_DATA loc_oob_data) { inc_func_call_count(__func__); - test::mock::stack_btm_sec::btm_sec_cr_loc_oob_data_cback_event(address, - loc_oob_data); + test::mock::stack_btm_sec::btm_sec_cr_loc_oob_data_cback_event(address, loc_oob_data); } -void btm_sec_dev_rec_cback_event(tBTM_SEC_DEV_REC* p_dev_rec, - tBTM_STATUS btm_status, bool is_le_transport) { +void btm_sec_dev_rec_cback_event(tBTM_SEC_DEV_REC* p_dev_rec, tBTM_STATUS btm_status, + bool is_le_transport) { inc_func_call_count(__func__); - test::mock::stack_btm_sec::btm_sec_dev_rec_cback_event(p_dev_rec, btm_status, - is_le_transport); + test::mock::stack_btm_sec::btm_sec_dev_rec_cback_event(p_dev_rec, btm_status, is_le_transport); } void btm_sec_dev_reset(void) { inc_func_call_count(__func__); test::mock::stack_btm_sec::btm_sec_dev_reset(); } -tBTM_STATUS btm_sec_disconnect(uint16_t handle, tHCI_STATUS reason, - std::string comment) { +tBTM_STATUS btm_sec_disconnect(uint16_t handle, tHCI_STATUS reason, std::string comment) { inc_func_call_count(__func__); return test::mock::stack_btm_sec::btm_sec_disconnect(handle, reason, comment); } -void btm_sec_disconnected(uint16_t handle, tHCI_REASON reason, - std::string comment) { +void btm_sec_disconnected(uint16_t handle, tHCI_REASON reason, std::string comment) { inc_func_call_count(__func__); test::mock::stack_btm_sec::btm_sec_disconnected(handle, reason, comment); } -void btm_sec_encrypt_change(uint16_t handle, tHCI_STATUS status, - uint8_t encr_enable) { +void btm_sec_encrypt_change(uint16_t handle, tHCI_STATUS status, uint8_t encr_enable) { inc_func_call_count(__func__); - test::mock::stack_btm_sec::btm_sec_encrypt_change(handle, status, - encr_enable); + test::mock::stack_btm_sec::btm_sec_encrypt_change(handle, status, encr_enable); } -void btm_sec_encryption_change_evt(uint16_t handle, tHCI_STATUS status, - uint8_t encr_enable) { +void btm_sec_encryption_change_evt(uint16_t handle, tHCI_STATUS status, uint8_t encr_enable) { inc_func_call_count(__func__); - test::mock::stack_btm_sec::btm_sec_encryption_change_evt(handle, status, - encr_enable); + test::mock::stack_btm_sec::btm_sec_encryption_change_evt(handle, status, encr_enable); } bool btm_sec_is_a_bonded_dev(const RawAddress& bda) { inc_func_call_count(__func__); return test::mock::stack_btm_sec::btm_sec_is_a_bonded_dev(bda); } -tBTM_STATUS btm_sec_l2cap_access_req(const RawAddress& bd_addr, uint16_t psm, - bool is_originator, - tBTM_SEC_CALLBACK* p_callback, - void* p_ref_data) { +tBTM_STATUS btm_sec_l2cap_access_req(const RawAddress& bd_addr, uint16_t psm, bool is_originator, + tBTM_SEC_CALLBACK* p_callback, void* p_ref_data) { inc_func_call_count(__func__); - return test::mock::stack_btm_sec::btm_sec_l2cap_access_req( - bd_addr, psm, is_originator, p_callback, p_ref_data); + return test::mock::stack_btm_sec::btm_sec_l2cap_access_req(bd_addr, psm, is_originator, + p_callback, p_ref_data); } -tBTM_STATUS btm_sec_l2cap_access_req_by_requirement( - const RawAddress& bd_addr, uint16_t security_required, bool is_originator, - tBTM_SEC_CALLBACK* p_callback, void* p_ref_data) { +tBTM_STATUS btm_sec_l2cap_access_req_by_requirement(const RawAddress& bd_addr, + uint16_t security_required, bool is_originator, + tBTM_SEC_CALLBACK* p_callback, + void* p_ref_data) { inc_func_call_count(__func__); return test::mock::stack_btm_sec::btm_sec_l2cap_access_req_by_requirement( - bd_addr, security_required, is_originator, p_callback, p_ref_data); + bd_addr, security_required, is_originator, p_callback, p_ref_data); } -void btm_sec_link_key_notification(const RawAddress& p_bda, - const Octet16& link_key, uint8_t key_type) { +void btm_sec_link_key_notification(const RawAddress& p_bda, const Octet16& link_key, + uint8_t key_type) { inc_func_call_count(__func__); - test::mock::stack_btm_sec::btm_sec_link_key_notification(p_bda, link_key, - key_type); + test::mock::stack_btm_sec::btm_sec_link_key_notification(p_bda, link_key, key_type); } -void btm_sec_encryption_key_refresh_complete(uint16_t handle, - tHCI_STATUS status) { +void btm_sec_encryption_key_refresh_complete(uint16_t handle, tHCI_STATUS status) { inc_func_call_count(__func__); - test::mock::stack_btm_sec::btm_sec_encryption_key_refresh_complete(handle, - status); + test::mock::stack_btm_sec::btm_sec_encryption_key_refresh_complete(handle, status); } void btm_sec_link_key_request(const RawAddress bda) { inc_func_call_count(__func__); test::mock::stack_btm_sec::btm_sec_link_key_request(bda); } -tBTM_STATUS btm_sec_mx_access_request(const RawAddress& bd_addr, - bool is_originator, - uint16_t security_required, - tBTM_SEC_CALLBACK* p_callback, +tBTM_STATUS btm_sec_mx_access_request(const RawAddress& bd_addr, bool is_originator, + uint16_t security_required, tBTM_SEC_CALLBACK* p_callback, void* p_ref_data) { inc_func_call_count(__func__); return test::mock::stack_btm_sec::btm_sec_mx_access_request( - bd_addr, is_originator, security_required, p_callback, p_ref_data); + bd_addr, is_originator, security_required, p_callback, p_ref_data); } void btm_sec_pin_code_request(const RawAddress bda) { inc_func_call_count(__func__); test::mock::stack_btm_sec::btm_sec_pin_code_request(bda); } -void btm_sec_rmt_host_support_feat_evt(const RawAddress bd_addr, - uint8_t features_0) { +void btm_sec_rmt_host_support_feat_evt(const RawAddress bd_addr, uint8_t features_0) { inc_func_call_count(__func__); - test::mock::stack_btm_sec::btm_sec_rmt_host_support_feat_evt(bd_addr, - features_0); + test::mock::stack_btm_sec::btm_sec_rmt_host_support_feat_evt(bd_addr, features_0); } -void btm_sec_rmt_name_request_complete(const RawAddress* p_bd_addr, - const uint8_t* p_bd_name, +void btm_sec_rmt_name_request_complete(const RawAddress* p_bd_addr, const uint8_t* p_bd_name, tHCI_STATUS status) { inc_func_call_count(__func__); - test::mock::stack_btm_sec::btm_sec_rmt_name_request_complete( - p_bd_addr, p_bd_name, status); + test::mock::stack_btm_sec::btm_sec_rmt_name_request_complete(p_bd_addr, p_bd_name, status); } -void btm_sec_role_changed(tHCI_STATUS hci_status, const RawAddress& bd_addr, - tHCI_ROLE new_role) { +void btm_sec_role_changed(tHCI_STATUS hci_status, const RawAddress& bd_addr, tHCI_ROLE new_role) { inc_func_call_count(__func__); - test::mock::stack_btm_sec::btm_sec_role_changed(hci_status, bd_addr, - new_role); + test::mock::stack_btm_sec::btm_sec_role_changed(hci_status, bd_addr, new_role); } -void btm_sec_set_peer_sec_caps(uint16_t hci_handle, bool ssp_supported, - bool sc_supported, - bool hci_role_switch_supported, - bool br_edr_supported, bool le_supported) { +void btm_sec_set_peer_sec_caps(uint16_t hci_handle, bool ssp_supported, bool sc_supported, + bool hci_role_switch_supported, bool br_edr_supported, + bool le_supported) { inc_func_call_count(__func__); - test::mock::stack_btm_sec::btm_sec_set_peer_sec_caps( - hci_handle, ssp_supported, sc_supported, hci_role_switch_supported, - br_edr_supported, le_supported); + test::mock::stack_btm_sec::btm_sec_set_peer_sec_caps(hci_handle, ssp_supported, sc_supported, + hci_role_switch_supported, br_edr_supported, + le_supported); } void btm_sec_update_clock_offset(uint16_t handle, uint16_t clock_offset) { inc_func_call_count(__func__); diff --git a/system/test/mock/mock_stack_btm_sec.h b/system/test/mock/mock_stack_btm_sec.h index d5dda450b46..513da58f739 100644 --- a/system/test/mock/mock_stack_btm_sec.h +++ b/system/test/mock/mock_stack_btm_sec.h @@ -51,21 +51,18 @@ namespace stack_btm_sec { struct BTM_CanReadDiscoverableCharacteristics { static bool return_value; std::function body{ - [](const RawAddress& /* bd_addr */) { return return_value; }}; - bool operator()(const RawAddress& bd_addr) { return body(bd_addr); }; + [](const RawAddress& /* bd_addr */) { return return_value; }}; + bool operator()(const RawAddress& bd_addr) { return body(bd_addr); } }; -extern struct BTM_CanReadDiscoverableCharacteristics - BTM_CanReadDiscoverableCharacteristics; +extern struct BTM_CanReadDiscoverableCharacteristics BTM_CanReadDiscoverableCharacteristics; // Name: BTM_ConfirmReqReply // Params: tBTM_STATUS res, const RawAddress& bd_addr // Return: void struct BTM_ConfirmReqReply { std::function body{ - [](tBTM_STATUS /* res */, const RawAddress& /* bd_addr */) {}}; - void operator()(tBTM_STATUS res, const RawAddress& bd_addr) { - body(res, bd_addr); - }; + [](tBTM_STATUS /* res */, const RawAddress& /* bd_addr */) {}}; + void operator()(tBTM_STATUS res, const RawAddress& bd_addr) { body(res, bd_addr); } }; extern struct BTM_ConfirmReqReply BTM_ConfirmReqReply; @@ -75,13 +72,10 @@ extern struct BTM_ConfirmReqReply BTM_ConfirmReqReply; struct BTM_GetPeerDeviceTypeFromFeatures { static tBT_DEVICE_TYPE return_value; std::function body{ - [](const RawAddress& /* bd_addr */) { return return_value; }}; - tBT_DEVICE_TYPE operator()(const RawAddress& bd_addr) { - return body(bd_addr); - }; + [](const RawAddress& /* bd_addr */) { return return_value; }}; + tBT_DEVICE_TYPE operator()(const RawAddress& bd_addr) { return body(bd_addr); } }; -extern struct BTM_GetPeerDeviceTypeFromFeatures - BTM_GetPeerDeviceTypeFromFeatures; +extern struct BTM_GetPeerDeviceTypeFromFeatures BTM_GetPeerDeviceTypeFromFeatures; // Name: BTM_IsAuthenticated // Params: const RawAddress& bd_addr, tBT_TRANSPORT transport @@ -89,12 +83,12 @@ extern struct BTM_GetPeerDeviceTypeFromFeatures struct BTM_IsAuthenticated { static bool return_value; std::function body{ - [](const RawAddress& /* bd_addr */, tBT_TRANSPORT /* transport */) { - return return_value; - }}; + [](const RawAddress& /* bd_addr */, tBT_TRANSPORT /* transport */) { + return return_value; + }}; bool operator()(const RawAddress& bd_addr, tBT_TRANSPORT transport) { return body(bd_addr, transport); - }; + } }; extern struct BTM_IsAuthenticated BTM_IsAuthenticated; @@ -104,12 +98,12 @@ extern struct BTM_IsAuthenticated BTM_IsAuthenticated; struct BTM_IsEncrypted { static bool return_value; std::function body{ - [](const RawAddress& /* bd_addr */, tBT_TRANSPORT /* transport */) { - return return_value; - }}; + [](const RawAddress& /* bd_addr */, tBT_TRANSPORT /* transport */) { + return return_value; + }}; bool operator()(const RawAddress& bd_addr, tBT_TRANSPORT transport) { return body(bd_addr, transport); - }; + } }; extern struct BTM_IsEncrypted BTM_IsEncrypted; @@ -119,12 +113,12 @@ extern struct BTM_IsEncrypted BTM_IsEncrypted; struct BTM_IsLinkKeyAuthed { static bool return_value; std::function body{ - [](const RawAddress& /* bd_addr */, tBT_TRANSPORT /* transport */) { - return return_value; - }}; + [](const RawAddress& /* bd_addr */, tBT_TRANSPORT /* transport */) { + return return_value; + }}; bool operator()(const RawAddress& bd_addr, tBT_TRANSPORT transport) { return body(bd_addr, transport); - }; + } }; extern struct BTM_IsLinkKeyAuthed BTM_IsLinkKeyAuthed; @@ -134,12 +128,12 @@ extern struct BTM_IsLinkKeyAuthed BTM_IsLinkKeyAuthed; struct BTM_IsLinkKeyKnown { static bool return_value; std::function body{ - [](const RawAddress& /* bd_addr */, tBT_TRANSPORT /* transport */) { - return return_value; - }}; + [](const RawAddress& /* bd_addr */, tBT_TRANSPORT /* transport */) { + return return_value; + }}; bool operator()(const RawAddress& bd_addr, tBT_TRANSPORT transport) { return body(bd_addr, transport); - }; + } }; extern struct BTM_IsLinkKeyKnown BTM_IsLinkKeyKnown; @@ -147,14 +141,12 @@ extern struct BTM_IsLinkKeyKnown BTM_IsLinkKeyKnown; // Params: const RawAddress& bd_addr, tBTM_STATUS res, uint8_t pin_len, uint8_t* // p_pin Return: void struct BTM_PINCodeReply { - std::function - body{[](const RawAddress& /* bd_addr */, tBTM_STATUS /* res */, - uint8_t /* pin_len */, uint8_t* /* p_pin */) {}}; - void operator()(const RawAddress& bd_addr, tBTM_STATUS res, uint8_t pin_len, - uint8_t* p_pin) { + std::function + body{[](const RawAddress& /* bd_addr */, tBTM_STATUS /* res */, uint8_t /* pin_len */, + uint8_t* /* p_pin */) {}}; + void operator()(const RawAddress& bd_addr, tBTM_STATUS res, uint8_t pin_len, uint8_t* p_pin) { body(bd_addr, res, pin_len, p_pin); - }; + } }; extern struct BTM_PINCodeReply BTM_PINCodeReply; @@ -162,14 +154,11 @@ extern struct BTM_PINCodeReply BTM_PINCodeReply; // Params: tBTM_STATUS res, const RawAddress& bd_addr, uint32_t passkey // Return: void struct BTM_PasskeyReqReply { - std::function - body{[](tBTM_STATUS /* res */, const RawAddress& /* bd_addr */, - uint32_t /* passkey */) {}}; - void operator()(tBTM_STATUS res, const RawAddress& bd_addr, - uint32_t passkey) { + std::function body{ + [](tBTM_STATUS /* res */, const RawAddress& /* bd_addr */, uint32_t /* passkey */) {}}; + void operator()(tBTM_STATUS res, const RawAddress& bd_addr, uint32_t passkey) { body(res, bd_addr, passkey); - }; + } }; extern struct BTM_PasskeyReqReply BTM_PasskeyReqReply; @@ -179,18 +168,17 @@ extern struct BTM_PasskeyReqReply BTM_PasskeyReqReply; struct BTM_PeerSupportsSecureConnections { static bool return_value; std::function body{ - [](const RawAddress& /* bd_addr */) { return return_value; }}; - bool operator()(const RawAddress& bd_addr) { return body(bd_addr); }; + [](const RawAddress& /* bd_addr */) { return return_value; }}; + bool operator()(const RawAddress& bd_addr) { return body(bd_addr); } }; -extern struct BTM_PeerSupportsSecureConnections - BTM_PeerSupportsSecureConnections; +extern struct BTM_PeerSupportsSecureConnections BTM_PeerSupportsSecureConnections; // Name: BTM_ReadLocalOobData // Params: void // Return: void struct BTM_ReadLocalOobData { std::function body{[](void) {}}; - void operator()(void) { body(); }; + void operator()(void) { body(); } }; extern struct BTM_ReadLocalOobData BTM_ReadLocalOobData; @@ -198,14 +186,13 @@ extern struct BTM_ReadLocalOobData BTM_ReadLocalOobData; // Params: tBTM_STATUS res, const RawAddress& bd_addr, const Octet16& c, const // Octet16& r Return: void struct BTM_RemoteOobDataReply { - std::function - body{[](tBTM_STATUS /* res */, const RawAddress& /* bd_addr */, - const Octet16& /* c */, const Octet16& /* r */) {}}; - void operator()(tBTM_STATUS res, const RawAddress& bd_addr, const Octet16& c, - const Octet16& r) { + std::function + body{[](tBTM_STATUS /* res */, const RawAddress& /* bd_addr */, const Octet16& /* c */, + const Octet16& /* r */) {}}; + void operator()(tBTM_STATUS res, const RawAddress& bd_addr, const Octet16& c, const Octet16& r) { body(res, bd_addr, c, r); - }; + } }; extern struct BTM_RemoteOobDataReply BTM_RemoteOobDataReply; @@ -215,10 +202,8 @@ extern struct BTM_RemoteOobDataReply BTM_RemoteOobDataReply; struct BTM_SecAddRmtNameNotifyCallback { static bool return_value; std::function body{ - [](tBTM_RMT_NAME_CALLBACK* /* p_callback */) { return return_value; }}; - bool operator()(tBTM_RMT_NAME_CALLBACK* p_callback) { - return body(p_callback); - }; + [](tBTM_RMT_NAME_CALLBACK* /* p_callback */) { return return_value; }}; + bool operator()(tBTM_RMT_NAME_CALLBACK* p_callback) { return body(p_callback); } }; extern struct BTM_SecAddRmtNameNotifyCallback BTM_SecAddRmtNameNotifyCallback; @@ -229,15 +214,14 @@ extern struct BTM_SecAddRmtNameNotifyCallback BTM_SecAddRmtNameNotifyCallback; struct BTM_SecBond { static tBTM_STATUS return_value; std::function - body{[](const RawAddress& /* bd_addr */, tBLE_ADDR_TYPE /* addr_type */, - tBT_TRANSPORT /* transport */, - tBT_DEVICE_TYPE /* device_type */) { return return_value; }}; + tBT_TRANSPORT transport, tBT_DEVICE_TYPE device_type)> + body{[](const RawAddress& /* bd_addr */, tBLE_ADDR_TYPE /* addr_type */, + tBT_TRANSPORT /* transport */, + tBT_DEVICE_TYPE /* device_type */) { return return_value; }}; tBTM_STATUS operator()(const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type, tBT_TRANSPORT transport, tBT_DEVICE_TYPE device_type) { return body(bd_addr, addr_type, transport, device_type); - }; + } }; extern struct BTM_SecBond BTM_SecBond; @@ -247,8 +231,8 @@ extern struct BTM_SecBond BTM_SecBond; struct BTM_SecBondCancel { static tBTM_STATUS return_value; std::function body{ - [](const RawAddress& /* bd_addr */) { return return_value; }}; - tBTM_STATUS operator()(const RawAddress& bd_addr) { return body(bd_addr); }; + [](const RawAddress& /* bd_addr */) { return return_value; }}; + tBTM_STATUS operator()(const RawAddress& bd_addr) { return body(bd_addr); } }; extern struct BTM_SecBondCancel BTM_SecBondCancel; @@ -258,8 +242,8 @@ extern struct BTM_SecBondCancel BTM_SecBondCancel; struct BTM_SecClrService { static uint8_t return_value; std::function body{ - [](uint8_t /* service_id */) { return return_value; }}; - uint8_t operator()(uint8_t service_id) { return body(service_id); }; + [](uint8_t /* service_id */) { return return_value; }}; + uint8_t operator()(uint8_t service_id) { return body(service_id); } }; extern struct BTM_SecClrService BTM_SecClrService; @@ -268,9 +252,8 @@ extern struct BTM_SecClrService BTM_SecClrService; // Return: uint8_t struct BTM_SecClrServiceByPsm { static uint8_t return_value; - std::function body{ - [](uint16_t /* psm */) { return return_value; }}; - uint8_t operator()(uint16_t psm) { return body(psm); }; + std::function body{[](uint16_t /* psm */) { return return_value; }}; + uint8_t operator()(uint16_t psm) { return body(psm); } }; extern struct BTM_SecClrServiceByPsm BTM_SecClrServiceByPsm; @@ -280,13 +263,10 @@ extern struct BTM_SecClrServiceByPsm BTM_SecClrServiceByPsm; struct BTM_SecDeleteRmtNameNotifyCallback { static bool return_value; std::function body{ - [](tBTM_RMT_NAME_CALLBACK* /* p_callback */) { return return_value; }}; - bool operator()(tBTM_RMT_NAME_CALLBACK* p_callback) { - return body(p_callback); - }; + [](tBTM_RMT_NAME_CALLBACK* /* p_callback */) { return return_value; }}; + bool operator()(tBTM_RMT_NAME_CALLBACK* p_callback) { return body(p_callback); } }; -extern struct BTM_SecDeleteRmtNameNotifyCallback - BTM_SecDeleteRmtNameNotifyCallback; +extern struct BTM_SecDeleteRmtNameNotifyCallback BTM_SecDeleteRmtNameNotifyCallback; // Name: BTM_SecGetDeviceLinkKeyType // Params: const RawAddress& bd_addr @@ -294,10 +274,8 @@ extern struct BTM_SecDeleteRmtNameNotifyCallback struct BTM_SecGetDeviceLinkKeyType { static tBTM_LINK_KEY_TYPE return_value; std::function body{ - [](const RawAddress& /* bd_addr */) { return return_value; }}; - tBTM_LINK_KEY_TYPE operator()(const RawAddress& bd_addr) { - return body(bd_addr); - }; + [](const RawAddress& /* bd_addr */) { return return_value; }}; + tBTM_LINK_KEY_TYPE operator()(const RawAddress& bd_addr) { return body(bd_addr); } }; extern struct BTM_SecGetDeviceLinkKeyType BTM_SecGetDeviceLinkKeyType; @@ -307,8 +285,8 @@ extern struct BTM_SecGetDeviceLinkKeyType BTM_SecGetDeviceLinkKeyType; struct BTM_SecIsSecurityPending { static bool return_value; std::function body{ - [](const RawAddress& /* bd_addr */) { return return_value; }}; - bool operator()(const RawAddress& bd_addr) { return body(bd_addr); }; + [](const RawAddress& /* bd_addr */) { return return_value; }}; + bool operator()(const RawAddress& bd_addr) { return body(bd_addr); } }; extern struct BTM_SecIsSecurityPending BTM_SecIsSecurityPending; @@ -318,8 +296,8 @@ extern struct BTM_SecIsSecurityPending BTM_SecIsSecurityPending; struct BTM_SecRegister { static bool return_value; std::function body{ - [](const tBTM_APPL_INFO* /* p_cb_info */) { return return_value; }}; - bool operator()(const tBTM_APPL_INFO* p_cb_info) { return body(p_cb_info); }; + [](const tBTM_APPL_INFO* /* p_cb_info */) { return return_value; }}; + bool operator()(const tBTM_APPL_INFO* p_cb_info) { return body(p_cb_info); } }; extern struct BTM_SecRegister BTM_SecRegister; @@ -332,14 +310,14 @@ struct BTM_SetEncryption { std::function - body{[](const RawAddress& /* bd_addr */, tBT_TRANSPORT /* transport */, - tBTM_SEC_CALLBACK* /* p_callback */, void* /* p_ref_data */, - tBTM_BLE_SEC_ACT /* sec_act */) { return return_value; }}; + body{[](const RawAddress& /* bd_addr */, tBT_TRANSPORT /* transport */, + tBTM_SEC_CALLBACK* /* p_callback */, void* /* p_ref_data */, + tBTM_BLE_SEC_ACT /* sec_act */) { return return_value; }}; tBTM_STATUS operator()(const RawAddress& bd_addr, tBT_TRANSPORT transport, tBTM_SEC_CALLBACK* p_callback, void* p_ref_data, tBTM_BLE_SEC_ACT sec_act) { return body(bd_addr, transport, p_callback, p_ref_data, sec_act); - }; + } }; extern struct BTM_SetEncryption BTM_SetEncryption; @@ -347,12 +325,11 @@ extern struct BTM_SetEncryption BTM_SetEncryption; // Params: uint8_t pin_type, PIN_CODE pin_code, uint8_t pin_code_len // Return: void struct BTM_SetPinType { - std::function - body{[](uint8_t /* pin_type */, PIN_CODE /* pin_code */, - uint8_t /* pin_code_len */) {}}; + std::function body{ + [](uint8_t /* pin_type */, PIN_CODE /* pin_code */, uint8_t /* pin_code_len */) {}}; void operator()(uint8_t pin_type, PIN_CODE pin_code, uint8_t pin_code_len) { body(pin_type, pin_code, pin_code_len); - }; + } }; extern struct BTM_SetPinType BTM_SetPinType; @@ -362,19 +339,15 @@ extern struct BTM_SetPinType BTM_SetPinType; // bool struct BTM_SetSecurityLevel { static bool return_value; - std::function - body{[](bool /* is_originator */, const char* /* p_name */, - uint8_t /* service_id */, uint16_t /* sec_level */, - uint16_t /* psm */, uint32_t /* mx_proto_id */, - uint32_t /* mx_chan_id */) { return return_value; }}; - bool operator()(bool is_originator, const char* p_name, uint8_t service_id, - uint16_t sec_level, uint16_t psm, uint32_t mx_proto_id, - uint32_t mx_chan_id) { - return body(is_originator, p_name, service_id, sec_level, psm, mx_proto_id, - mx_chan_id); - }; + std::function + body{[](bool /* is_originator */, const char* /* p_name */, uint8_t /* service_id */, + uint16_t /* sec_level */, uint16_t /* psm */, uint32_t /* mx_proto_id */, + uint32_t /* mx_chan_id */) { return return_value; }}; + bool operator()(bool is_originator, const char* p_name, uint8_t service_id, uint16_t sec_level, + uint16_t psm, uint32_t mx_proto_id, uint32_t mx_chan_id) { + return body(is_originator, p_name, service_id, sec_level, psm, mx_proto_id, mx_chan_id); + } }; extern struct BTM_SetSecurityLevel BTM_SetSecurityLevel; @@ -382,14 +355,12 @@ extern struct BTM_SetSecurityLevel BTM_SetSecurityLevel; // Params: const RawAddress& bd_addr, const remote_version_info& // remote_version_info Return: void struct BTM_update_version_info { - std::function - body{[](const RawAddress& /* bd_addr */, - const remote_version_info& /* remote_version_info */) {}}; - void operator()(const RawAddress& bd_addr, - const remote_version_info& remote_version_info) { + std::function + body{[](const RawAddress& /* bd_addr */, + const remote_version_info& /* remote_version_info */) {}}; + void operator()(const RawAddress& bd_addr, const remote_version_info& remote_version_info) { body(bd_addr, remote_version_info); - }; + } }; extern struct BTM_update_version_info BTM_update_version_info; @@ -397,9 +368,8 @@ extern struct BTM_update_version_info BTM_update_version_info; // Params: tBTM_STATUS btm_status // Return: void struct NotifyBondingCanceled { - std::function body{ - [](tBTM_STATUS /* btm_status */) {}}; - void operator()(tBTM_STATUS btm_status) { body(btm_status); }; + std::function body{[](tBTM_STATUS /* btm_status */) {}}; + void operator()(tBTM_STATUS btm_status) { body(btm_status); } }; extern struct NotifyBondingCanceled NotifyBondingCanceled; @@ -408,10 +378,8 @@ extern struct NotifyBondingCanceled NotifyBondingCanceled; // Return: void struct btm_create_conn_cancel_complete { std::function body{ - [](uint8_t /* status */, const RawAddress /* bd_addr */) {}}; - void operator()(uint8_t status, const RawAddress bd_addr) { - body(status, bd_addr); - }; + [](uint8_t /* status */, const RawAddress /* bd_addr */) {}}; + void operator()(uint8_t status, const RawAddress bd_addr) { body(status, bd_addr); } }; extern struct btm_create_conn_cancel_complete btm_create_conn_cancel_complete; @@ -421,8 +389,8 @@ extern struct btm_create_conn_cancel_complete btm_create_conn_cancel_complete; struct btm_get_dev_class { static const DEV_CLASS return_value; std::function body{ - [](const RawAddress& /* bda */) { return return_value; }}; - const DEV_CLASS operator()(const RawAddress& bda) { return body(bda); }; + [](const RawAddress& /* bda */) { return return_value; }}; + const DEV_CLASS operator()(const RawAddress& bda) { return body(bda); } }; extern struct btm_get_dev_class btm_get_dev_class; @@ -431,7 +399,7 @@ extern struct btm_get_dev_class btm_get_dev_class; // Return: void struct btm_io_capabilities_req { std::function body{[](RawAddress /* p */) {}}; - void operator()(RawAddress p) { body(p); }; + void operator()(RawAddress p) { body(p); } }; extern struct btm_io_capabilities_req btm_io_capabilities_req; @@ -440,8 +408,8 @@ extern struct btm_io_capabilities_req btm_io_capabilities_req; // Return: void struct btm_io_capabilities_rsp { std::function body{ - [](const tBTM_SP_IO_RSP /* evt_data */) {}}; - void operator()(const tBTM_SP_IO_RSP evt_data) { body(evt_data); }; + [](const tBTM_SP_IO_RSP /* evt_data */) {}}; + void operator()(const tBTM_SP_IO_RSP evt_data) { body(evt_data); } }; extern struct btm_io_capabilities_rsp btm_io_capabilities_rsp; @@ -449,12 +417,11 @@ extern struct btm_io_capabilities_rsp btm_io_capabilities_rsp; // Params: tBTM_SP_EVT event, const uint8_t* p // Return: void struct btm_proc_sp_req_evt { - std::function - body{[](tBTM_SP_EVT /* event */, const RawAddress /* bda */, - uint32_t /* value */) {}}; + std::function body{ + [](tBTM_SP_EVT /* event */, const RawAddress /* bda */, uint32_t /* value */) {}}; void operator()(tBTM_SP_EVT event, const RawAddress bda, uint32_t value) { body(event, bda, value); - }; + } }; extern struct btm_proc_sp_req_evt btm_proc_sp_req_evt; @@ -465,8 +432,8 @@ extern struct btm_proc_sp_req_evt btm_proc_sp_req_evt; // Return: void struct btm_read_local_oob_complete { std::function body{ - [](const tBTM_SP_LOC_OOB /* evt_data */) {}}; - void operator()(const tBTM_SP_LOC_OOB evt_data) { body(evt_data); }; + [](const tBTM_SP_LOC_OOB /* evt_data */) {}}; + void operator()(const tBTM_SP_LOC_OOB evt_data) { body(evt_data); } }; extern struct btm_read_local_oob_complete btm_read_local_oob_complete; @@ -474,9 +441,8 @@ extern struct btm_read_local_oob_complete btm_read_local_oob_complete; // Params: RawAddress bda // Return: void struct btm_rem_oob_req { - std::function body{ - [](const RawAddress /* bda */) {}}; - void operator()(const RawAddress bda) { body(bda); }; + std::function body{[](const RawAddress /* bda */) {}}; + void operator()(const RawAddress bda) { body(bda); } }; extern struct btm_rem_oob_req btm_rem_oob_req; @@ -484,9 +450,8 @@ extern struct btm_rem_oob_req btm_rem_oob_req; // Params: const RawAddress& bd_addr // Return: void struct btm_sec_abort_access_req { - std::function body{ - [](const RawAddress& /* bd_addr */) {}}; - void operator()(const RawAddress& bd_addr) { body(bd_addr); }; + std::function body{[](const RawAddress& /* bd_addr */) {}}; + void operator()(const RawAddress& bd_addr) { body(bd_addr); } }; extern struct btm_sec_abort_access_req btm_sec_abort_access_req; @@ -495,10 +460,8 @@ extern struct btm_sec_abort_access_req btm_sec_abort_access_req; // Return: void struct btm_sec_auth_complete { std::function body{ - [](uint16_t /* handle */, tHCI_STATUS /* status */) {}}; - void operator()(uint16_t handle, tHCI_STATUS status) { - body(handle, status); - }; + [](uint16_t /* handle */, tHCI_STATUS /* status */) {}}; + void operator()(uint16_t handle, tHCI_STATUS status) { body(handle, status); } }; extern struct btm_sec_auth_complete btm_sec_auth_complete; @@ -509,12 +472,12 @@ struct btm_sec_bond_by_transport { static tBTM_STATUS return_value; std::function - body{[](const RawAddress& /* bd_addr */, tBLE_ADDR_TYPE /* addr_type */, - tBT_TRANSPORT /* transport */) { return return_value; }}; + body{[](const RawAddress& /* bd_addr */, tBLE_ADDR_TYPE /* addr_type */, + tBT_TRANSPORT /* transport */) { return return_value; }}; tBTM_STATUS operator()(const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type, tBT_TRANSPORT transport) { return body(bd_addr, addr_type, transport); - }; + } }; extern struct btm_sec_bond_by_transport btm_sec_bond_by_transport; @@ -523,7 +486,7 @@ extern struct btm_sec_bond_by_transport btm_sec_bond_by_transport; // Return: void struct btm_sec_check_pending_reqs { std::function body{[](void) {}}; - void operator()(void) { body(); }; + void operator()(void) { body(); } }; extern struct btm_sec_check_pending_reqs btm_sec_check_pending_reqs; @@ -531,9 +494,8 @@ extern struct btm_sec_check_pending_reqs btm_sec_check_pending_reqs; // Params: tBTM_SEC_DEV_REC* p_dev_rec // Return: void struct btm_sec_clear_ble_keys { - std::function body{ - [](tBTM_SEC_DEV_REC* /* p_dev_rec */) {}}; - void operator()(tBTM_SEC_DEV_REC* p_dev_rec) { body(p_dev_rec); }; + std::function body{[](tBTM_SEC_DEV_REC* /* p_dev_rec */) {}}; + void operator()(tBTM_SEC_DEV_REC* p_dev_rec) { body(p_dev_rec); } }; extern struct btm_sec_clear_ble_keys btm_sec_clear_ble_keys; @@ -542,8 +504,8 @@ extern struct btm_sec_clear_ble_keys btm_sec_clear_ble_keys; // Return: void struct btm_sec_conn_req { std::function body{ - [](const RawAddress& /* bda */, const DEV_CLASS /* dc */) {}}; - void operator()(const RawAddress& bda, const DEV_CLASS dc) { body(bda, dc); }; + [](const RawAddress& /* bda */, const DEV_CLASS /* dc */) {}}; + void operator()(const RawAddress& bda, const DEV_CLASS dc) { body(bda, dc); } }; extern struct btm_sec_conn_req btm_sec_conn_req; @@ -551,15 +513,14 @@ extern struct btm_sec_conn_req btm_sec_conn_req; // Params: const RawAddress& bda, uint16_t handle, tHCI_STATUS status, uint8_t // enc_mode, tHCI_ROLE assigned_role Return: void struct btm_sec_connected { - std::function - body{[](const RawAddress& /* bda */, uint16_t /* handle */, - tHCI_STATUS /* status */, uint8_t /* enc_mode */, - tHCI_ROLE /* assigned_role */) {}}; - void operator()(const RawAddress& bda, uint16_t handle, tHCI_STATUS status, - uint8_t enc_mode, tHCI_ROLE assigned_role) { + std::function + body{[](const RawAddress& /* bda */, uint16_t /* handle */, tHCI_STATUS /* status */, + uint8_t /* enc_mode */, tHCI_ROLE /* assigned_role */) {}}; + void operator()(const RawAddress& bda, uint16_t handle, tHCI_STATUS status, uint8_t enc_mode, + tHCI_ROLE assigned_role) { body(bda, handle, status, enc_mode, assigned_role); - }; + } }; extern struct btm_sec_connected btm_sec_connected; @@ -567,28 +528,24 @@ extern struct btm_sec_connected btm_sec_connected; // Params: const RawAddress& address, tSMP_LOC_OOB_DATA loc_oob_data // Return: void struct btm_sec_cr_loc_oob_data_cback_event { - std::function - body{[](const RawAddress& /* address */, - tSMP_LOC_OOB_DATA /* loc_oob_data */) {}}; + std::function body{ + [](const RawAddress& /* address */, tSMP_LOC_OOB_DATA /* loc_oob_data */) {}}; void operator()(const RawAddress& address, tSMP_LOC_OOB_DATA loc_oob_data) { body(address, loc_oob_data); - }; + } }; -extern struct btm_sec_cr_loc_oob_data_cback_event - btm_sec_cr_loc_oob_data_cback_event; +extern struct btm_sec_cr_loc_oob_data_cback_event btm_sec_cr_loc_oob_data_cback_event; // Name: btm_sec_dev_rec_cback_event // Params: tBTM_SEC_DEV_REC* p_dev_rec, tBTM_STATUS btm_status, bool // is_le_transport Return: void struct btm_sec_dev_rec_cback_event { - std::function - body{[](tBTM_SEC_DEV_REC* /* p_dev_rec */, tBTM_STATUS /* btm_status */, - bool /* is_le_transport */) {}}; - void operator()(tBTM_SEC_DEV_REC* p_dev_rec, tBTM_STATUS btm_status, - bool is_le_transport) { + std::function + body{[](tBTM_SEC_DEV_REC* /* p_dev_rec */, tBTM_STATUS /* btm_status */, + bool /* is_le_transport */) {}}; + void operator()(tBTM_SEC_DEV_REC* p_dev_rec, tBTM_STATUS btm_status, bool is_le_transport) { body(p_dev_rec, btm_status, is_le_transport); - }; + } }; extern struct btm_sec_dev_rec_cback_event btm_sec_dev_rec_cback_event; @@ -597,7 +554,7 @@ extern struct btm_sec_dev_rec_cback_event btm_sec_dev_rec_cback_event; // Return: void struct btm_sec_dev_reset { std::function body{[](void) {}}; - void operator()(void) { body(); }; + void operator()(void) { body(); } }; extern struct btm_sec_dev_reset btm_sec_dev_reset; @@ -606,14 +563,13 @@ extern struct btm_sec_dev_reset btm_sec_dev_reset; // Return: tBTM_STATUS struct btm_sec_disconnect { static tBTM_STATUS return_value; - std::function - body{[](uint16_t /* handle */, tHCI_STATUS /* reason */, - std::string /* comment */) { return return_value; }}; - tBTM_STATUS operator()(uint16_t handle, tHCI_STATUS reason, - std::string comment) { + std::function body{ + [](uint16_t /* handle */, tHCI_STATUS /* reason */, std::string /* comment */) { + return return_value; + }}; + tBTM_STATUS operator()(uint16_t handle, tHCI_STATUS reason, std::string comment) { return body(handle, reason, comment); - }; + } }; extern struct btm_sec_disconnect btm_sec_disconnect; @@ -621,12 +577,11 @@ extern struct btm_sec_disconnect btm_sec_disconnect; // Params: uint16_t handle, tHCI_REASON reason, std::string comment // Return: void struct btm_sec_disconnected { - std::function - body{[](uint16_t /* handle */, tHCI_REASON /* reason */, - std::string /* comment */) {}}; + std::function body{ + [](uint16_t /* handle */, tHCI_REASON /* reason */, std::string /* comment */) {}}; void operator()(uint16_t handle, tHCI_REASON reason, std::string comment) { body(handle, reason, comment); - }; + } }; extern struct btm_sec_disconnected btm_sec_disconnected; @@ -634,12 +589,11 @@ extern struct btm_sec_disconnected btm_sec_disconnected; // Params: uint16_t handle, tHCI_STATUS status, uint8_t encr_enable // Return: void struct btm_sec_encrypt_change { - std::function - body{[](uint16_t /* handle */, tHCI_STATUS /* status */, - uint8_t /* encr_enable */) {}}; + std::function body{ + [](uint16_t /* handle */, tHCI_STATUS /* status */, uint8_t /* encr_enable */) {}}; void operator()(uint16_t handle, tHCI_STATUS status, uint8_t encr_enable) { body(handle, status, encr_enable); - }; + } }; extern struct btm_sec_encrypt_change btm_sec_encrypt_change; @@ -647,12 +601,11 @@ extern struct btm_sec_encrypt_change btm_sec_encrypt_change; // Params: uint16_t handle, tHCI_STATUS status, uint8_t encr_enable // Return: void struct btm_sec_encryption_change_evt { - std::function - body{[](uint16_t /* handle */, tHCI_STATUS /* status */, - uint8_t /* encr_enable */) {}}; + std::function body{ + [](uint16_t /* handle */, tHCI_STATUS /* status */, uint8_t /* encr_enable */) {}}; void operator()(uint16_t handle, tHCI_STATUS status, uint8_t encr_enable) { body(handle, status, encr_enable); - }; + } }; extern struct btm_sec_encryption_change_evt btm_sec_encryption_change_evt; @@ -662,8 +615,8 @@ extern struct btm_sec_encryption_change_evt btm_sec_encryption_change_evt; struct btm_sec_is_a_bonded_dev { static bool return_value; std::function body{ - [](const RawAddress& /* bda */) { return return_value; }}; - bool operator()(const RawAddress& bda) { return body(bda); }; + [](const RawAddress& /* bda */) { return return_value; }}; + bool operator()(const RawAddress& bda) { return body(bda); } }; extern struct btm_sec_is_a_bonded_dev btm_sec_is_a_bonded_dev; @@ -672,17 +625,15 @@ extern struct btm_sec_is_a_bonded_dev btm_sec_is_a_bonded_dev; // tBTM_SEC_CALLBACK* p_callback, void* p_ref_data Return: tBTM_STATUS struct btm_sec_l2cap_access_req { static tBTM_STATUS return_value; - std::function - body{[](const RawAddress& /* bd_addr */, uint16_t /* psm */, - bool /* is_originator */, tBTM_SEC_CALLBACK* /* p_callback */, - void* /* p_ref_data */) { return return_value; }}; - tBTM_STATUS operator()(const RawAddress& bd_addr, uint16_t psm, - bool is_originator, tBTM_SEC_CALLBACK* p_callback, - void* p_ref_data) { + std::function + body{[](const RawAddress& /* bd_addr */, uint16_t /* psm */, bool /* is_originator */, + tBTM_SEC_CALLBACK* /* p_callback */, + void* /* p_ref_data */) { return return_value; }}; + tBTM_STATUS operator()(const RawAddress& bd_addr, uint16_t psm, bool is_originator, + tBTM_SEC_CALLBACK* p_callback, void* p_ref_data) { return body(bd_addr, psm, is_originator, p_callback, p_ref_data); - }; + } }; extern struct btm_sec_l2cap_access_req btm_sec_l2cap_access_req; @@ -692,34 +643,28 @@ extern struct btm_sec_l2cap_access_req btm_sec_l2cap_access_req; // tBTM_STATUS struct btm_sec_l2cap_access_req_by_requirement { static tBTM_STATUS return_value; - std::function - body{[](const RawAddress& /* bd_addr */, uint16_t /* security_required */, - bool /* is_originator */, tBTM_SEC_CALLBACK* /* p_callback */, - void* /* p_ref_data */) { return return_value; }}; - tBTM_STATUS operator()(const RawAddress& bd_addr, uint16_t security_required, - bool is_originator, tBTM_SEC_CALLBACK* p_callback, - void* p_ref_data) { - return body(bd_addr, security_required, is_originator, p_callback, - p_ref_data); - }; -}; -extern struct btm_sec_l2cap_access_req_by_requirement - btm_sec_l2cap_access_req_by_requirement; + std::function + body{[](const RawAddress& /* bd_addr */, uint16_t /* security_required */, + bool /* is_originator */, tBTM_SEC_CALLBACK* /* p_callback */, + void* /* p_ref_data */) { return return_value; }}; + tBTM_STATUS operator()(const RawAddress& bd_addr, uint16_t security_required, bool is_originator, + tBTM_SEC_CALLBACK* p_callback, void* p_ref_data) { + return body(bd_addr, security_required, is_originator, p_callback, p_ref_data); + } +}; +extern struct btm_sec_l2cap_access_req_by_requirement btm_sec_l2cap_access_req_by_requirement; // Name: btm_sec_link_key_notification // Params: const RawAddress& p_bda, const Octet16& link_key, uint8_t key_type // Return: void struct btm_sec_link_key_notification { - std::function - body{[](const RawAddress& /* p_bda */, const Octet16& /* link_key */, - uint8_t /* key_type */) {}}; - void operator()(const RawAddress& p_bda, const Octet16& link_key, - uint8_t key_type) { + std::function body{ + [](const RawAddress& /* p_bda */, const Octet16& /* link_key */, uint8_t /* key_type */) { + }}; + void operator()(const RawAddress& p_bda, const Octet16& link_key, uint8_t key_type) { body(p_bda, link_key, key_type); - }; + } }; extern struct btm_sec_link_key_notification btm_sec_link_key_notification; @@ -728,21 +673,17 @@ extern struct btm_sec_link_key_notification btm_sec_link_key_notification; // Return: void struct btm_sec_encryption_key_refresh_complete { std::function body{ - [](uint16_t /* handle */, tHCI_STATUS /* status */) -> void {}}; - void operator()(uint16_t handle, tHCI_STATUS status) { - body(handle, status); - }; + [](uint16_t /* handle */, tHCI_STATUS /* status */) -> void {}}; + void operator()(uint16_t handle, tHCI_STATUS status) { body(handle, status); } }; -extern struct btm_sec_encryption_key_refresh_complete - btm_sec_encryption_key_refresh_complete; +extern struct btm_sec_encryption_key_refresh_complete btm_sec_encryption_key_refresh_complete; // Name: btm_sec_link_key_request // Params: const uint8_t* p_event // Return: void struct btm_sec_link_key_request { - std::function body{ - [](const RawAddress /* bda */) {}}; - void operator()(const RawAddress bda) { body(bda); }; + std::function body{[](const RawAddress /* bda */) {}}; + void operator()(const RawAddress bda) { body(bda); } }; extern struct btm_sec_link_key_request btm_sec_link_key_request; @@ -753,18 +694,15 @@ extern struct btm_sec_link_key_request btm_sec_link_key_request; struct btm_sec_mx_access_request { static tBTM_STATUS return_value; std::function - body{[](const RawAddress& /* bd_addr */, bool /* is_originator */, - uint16_t /* security_required */, - tBTM_SEC_CALLBACK* /* p_callback */, - void* /* p_ref_data */) { return return_value; }}; - tBTM_STATUS operator()(const RawAddress& bd_addr, bool is_originator, - uint16_t security_required, + uint16_t security_required, tBTM_SEC_CALLBACK* p_callback, + void* p_ref_data)> + body{[](const RawAddress& /* bd_addr */, bool /* is_originator */, + uint16_t /* security_required */, tBTM_SEC_CALLBACK* /* p_callback */, + void* /* p_ref_data */) { return return_value; }}; + tBTM_STATUS operator()(const RawAddress& bd_addr, bool is_originator, uint16_t security_required, tBTM_SEC_CALLBACK* p_callback, void* p_ref_data) { - return body(bd_addr, is_originator, security_required, p_callback, - p_ref_data); - }; + return body(bd_addr, is_originator, security_required, p_callback, p_ref_data); + } }; extern struct btm_sec_mx_access_request btm_sec_mx_access_request; @@ -772,9 +710,8 @@ extern struct btm_sec_mx_access_request btm_sec_mx_access_request; // Params: const uint8_t* p_event // Return: void struct btm_sec_pin_code_request { - std::function body{ - [](const RawAddress /* bda */) {}}; - void operator()(const RawAddress bda) { body(bda); }; + std::function body{[](const RawAddress /* bda */) {}}; + void operator()(const RawAddress bda) { body(bda); } }; extern struct btm_sec_pin_code_request btm_sec_pin_code_request; @@ -783,42 +720,34 @@ extern struct btm_sec_pin_code_request btm_sec_pin_code_request; // Return: void struct btm_sec_rmt_host_support_feat_evt { std::function body{ - [](const RawAddress /* bd_addr */, uint8_t /* features_0 */) {}}; - void operator()(const RawAddress bd_addr, uint8_t features_0) { - body(bd_addr, features_0); - }; + [](const RawAddress /* bd_addr */, uint8_t /* features_0 */) {}}; + void operator()(const RawAddress bd_addr, uint8_t features_0) { body(bd_addr, features_0); } }; -extern struct btm_sec_rmt_host_support_feat_evt - btm_sec_rmt_host_support_feat_evt; +extern struct btm_sec_rmt_host_support_feat_evt btm_sec_rmt_host_support_feat_evt; // Name: btm_sec_rmt_name_request_complete // Params: const RawAddress* p_bd_addr, const uint8_t* p_bd_name, tHCI_STATUS // status Return: void struct btm_sec_rmt_name_request_complete { - std::function - body{[](const RawAddress* /* p_bd_addr */, const uint8_t* /* p_bd_name */, - tHCI_STATUS /* status */) {}}; - void operator()(const RawAddress* p_bd_addr, const uint8_t* p_bd_name, - tHCI_STATUS status) { + std::function + body{[](const RawAddress* /* p_bd_addr */, const uint8_t* /* p_bd_name */, + tHCI_STATUS /* status */) {}}; + void operator()(const RawAddress* p_bd_addr, const uint8_t* p_bd_name, tHCI_STATUS status) { body(p_bd_addr, p_bd_name, status); - }; + } }; -extern struct btm_sec_rmt_name_request_complete - btm_sec_rmt_name_request_complete; +extern struct btm_sec_rmt_name_request_complete btm_sec_rmt_name_request_complete; // Name: btm_sec_role_changed // Params: tHCI_STATUS hci_status, const RawAddress& bd_addr, tHCI_ROLE new_role // Return: void struct btm_sec_role_changed { - std::function - body{[](tHCI_STATUS /* hci_status */, const RawAddress& /* bd_addr */, - tHCI_ROLE /* new_role */) {}}; - void operator()(tHCI_STATUS hci_status, const RawAddress& bd_addr, - tHCI_ROLE new_role) { + std::function body{ + [](tHCI_STATUS /* hci_status */, const RawAddress& /* bd_addr */, + tHCI_ROLE /* new_role */) {}}; + void operator()(tHCI_STATUS hci_status, const RawAddress& bd_addr, tHCI_ROLE new_role) { body(hci_status, bd_addr, new_role); - }; + } }; extern struct btm_sec_role_changed btm_sec_role_changed; @@ -828,17 +757,15 @@ extern struct btm_sec_role_changed btm_sec_role_changed; // void struct btm_sec_set_peer_sec_caps { std::function - body{[](uint16_t /* hci_handle */, bool /* ssp_supported */, - bool /* sc_supported */, bool /* hci_role_switch_supported */, - bool /* br_edr_supported */, bool /* le_supported */) {}}; + bool hci_role_switch_supported, bool br_edr_supported, bool le_supported)> + body{[](uint16_t /* hci_handle */, bool /* ssp_supported */, bool /* sc_supported */, + bool /* hci_role_switch_supported */, bool /* br_edr_supported */, + bool /* le_supported */) {}}; void operator()(uint16_t hci_handle, bool ssp_supported, bool sc_supported, - bool hci_role_switch_supported, bool br_edr_supported, - bool le_supported) { - body(hci_handle, ssp_supported, sc_supported, hci_role_switch_supported, - br_edr_supported, le_supported); - }; + bool hci_role_switch_supported, bool br_edr_supported, bool le_supported) { + body(hci_handle, ssp_supported, sc_supported, hci_role_switch_supported, br_edr_supported, + le_supported); + } }; extern struct btm_sec_set_peer_sec_caps btm_sec_set_peer_sec_caps; @@ -847,10 +774,8 @@ extern struct btm_sec_set_peer_sec_caps btm_sec_set_peer_sec_caps; // Return: void struct btm_sec_update_clock_offset { std::function body{ - [](uint16_t /* handle */, uint16_t /* clock_offset */) {}}; - void operator()(uint16_t handle, uint16_t clock_offset) { - body(handle, clock_offset); - }; + [](uint16_t /* handle */, uint16_t /* clock_offset */) {}}; + void operator()(uint16_t handle, uint16_t clock_offset) { body(handle, clock_offset); } }; extern struct btm_sec_update_clock_offset btm_sec_update_clock_offset; @@ -859,10 +784,8 @@ extern struct btm_sec_update_clock_offset btm_sec_update_clock_offset; // Return: void struct btm_simple_pair_complete { std::function body{ - [](const RawAddress /* bd_addr */, uint8_t /* status */) {}}; - void operator()(const RawAddress bd_addr, uint8_t status) { - body(bd_addr, status); - }; + [](const RawAddress /* bd_addr */, uint8_t /* status */) {}}; + void operator()(const RawAddress bd_addr, uint8_t status) { body(bd_addr, status); } }; extern struct btm_simple_pair_complete btm_simple_pair_complete; @@ -872,12 +795,12 @@ extern struct btm_simple_pair_complete btm_simple_pair_complete; struct BTM_IsRemoteNameKnown { static bool return_value; std::function body{ - [](const RawAddress& /* bd_addr */, tBT_TRANSPORT /* transport */) { - return return_value; - }}; + [](const RawAddress& /* bd_addr */, tBT_TRANSPORT /* transport */) { + return return_value; + }}; bool operator()(const RawAddress& bd_addr, tBT_TRANSPORT transport) { return body(bd_addr, transport); - }; + } }; extern struct BTM_IsRemoteNameKnown BTM_IsRemoteNameKnown; diff --git a/system/test/mock/mock_stack_btu_hcif.cc b/system/test/mock/mock_stack_btu_hcif.cc index 45f85dbce77..90ea7db6419 100644 --- a/system/test/mock/mock_stack_btu_hcif.cc +++ b/system/test/mock/mock_stack_btu_hcif.cc @@ -28,8 +28,8 @@ #include "stack/include/btu_hcif.h" #include "test/common/mock_functions.h" -using hci_cmd_cb = base::OnceCallback; +using hci_cmd_cb = base::OnceCallback; struct cmd_with_cb_data { hci_cmd_cb cb; @@ -42,14 +42,10 @@ void btu_hcif_process_event(uint8_t /* controller_id */, BT_HDR* /* p_msg */) { void btu_hcif_send_cmd(uint8_t /* controller_id */, const BT_HDR* /* p_buf */) { inc_func_call_count(__func__); } -void btu_hcif_send_cmd_with_cb(const base::Location& /* posted_from */, - uint16_t /* opcode */, uint8_t* /* params */, - uint8_t /* params_len */, hci_cmd_cb /* cb */) { - inc_func_call_count(__func__); -} -void cmd_with_cb_data_cleanup(cmd_with_cb_data* /* cb_wrapper */) { - inc_func_call_count(__func__); -} -void cmd_with_cb_data_init(cmd_with_cb_data* /* cb_wrapper */) { +void btu_hcif_send_cmd_with_cb(const base::Location& /* posted_from */, uint16_t /* opcode */, + uint8_t* /* params */, uint8_t /* params_len */, + hci_cmd_cb /* cb */) { inc_func_call_count(__func__); } +void cmd_with_cb_data_cleanup(cmd_with_cb_data* /* cb_wrapper */) { inc_func_call_count(__func__); } +void cmd_with_cb_data_init(cmd_with_cb_data* /* cb_wrapper */) { inc_func_call_count(__func__); } diff --git a/system/test/mock/mock_stack_gap_ble.cc b/system/test/mock/mock_stack_gap_ble.cc index 09ef941ffdd..3cb239e9b89 100644 --- a/system/test/mock/mock_stack_gap_ble.cc +++ b/system/test/mock/mock_stack_gap_ble.cc @@ -29,8 +29,7 @@ bool GAP_BleCancelReadPeerDevName(const RawAddress& /* peer_bda */) { inc_func_call_count(__func__); return false; } -bool GAP_BleReadPeerDevName(const RawAddress& /* peer_bda */, - tGAP_BLE_CMPL_CBACK* /* p_cback */) { +bool GAP_BleReadPeerDevName(const RawAddress& /* peer_bda */, tGAP_BLE_CMPL_CBACK* /* p_cback */) { inc_func_call_count(__func__); return false; } @@ -38,8 +37,7 @@ bool GAP_BleReadPeerPrefConnParams(const RawAddress& /* peer_bda */) { inc_func_call_count(__func__); return false; } -void GAP_BleAttrDBUpdate(uint16_t /* attr_uuid */, - tGAP_BLE_ATTR_VALUE* /* p_value */) { +void GAP_BleAttrDBUpdate(uint16_t /* attr_uuid */, tGAP_BLE_ATTR_VALUE* /* p_value */) { inc_func_call_count(__func__); } void gap_attr_db_init(void) { inc_func_call_count(__func__); } diff --git a/system/test/mock/mock_stack_gap_conn.cc b/system/test/mock/mock_stack_gap_conn.cc index 87ab539a39b..f38bb97588f 100644 --- a/system/test/mock/mock_stack_gap_conn.cc +++ b/system/test/mock/mock_stack_gap_conn.cc @@ -45,18 +45,16 @@ uint16_t GAP_ConnGetRemMtuSize(uint16_t /* gap_handle */) { inc_func_call_count(__func__); return 0; } -uint16_t GAP_ConnOpen(const char* /* p_serv_name */, uint8_t /* service_id */, - bool /* is_server */, const RawAddress* /* p_rem_bda */, - uint16_t /* psm */, uint16_t /* le_mps */, - tL2CAP_CFG_INFO* /* p_cfg */, - tL2CAP_ERTM_INFO* /* ertm_info */, +uint16_t GAP_ConnOpen(const char* /* p_serv_name */, uint8_t /* service_id */, bool /* is_server */, + const RawAddress* /* p_rem_bda */, uint16_t /* psm */, uint16_t /* le_mps */, + tL2CAP_CFG_INFO* /* p_cfg */, tL2CAP_ERTM_INFO* /* ertm_info */, uint16_t /* security */, tGAP_CONN_CALLBACK* /* p_cb */, tBT_TRANSPORT /* transport */) { inc_func_call_count(__func__); return 0; } -uint16_t GAP_ConnReadData(uint16_t /* gap_handle */, uint8_t* /* p_data */, - uint16_t /* max_len */, uint16_t* /* p_len */) { +uint16_t GAP_ConnReadData(uint16_t /* gap_handle */, uint8_t* /* p_data */, uint16_t /* max_len */, + uint16_t* /* p_len */) { inc_func_call_count(__func__); return 0; } diff --git a/system/test/mock/mock_stack_gatt.cc b/system/test/mock/mock_stack_gatt.cc index efee8f44f6e..9e66fc17000 100644 --- a/system/test/mock/mock_stack_gatt.cc +++ b/system/test/mock/mock_stack_gatt.cc @@ -34,10 +34,9 @@ tGATT_HDL_LIST_ELEM& gatt_add_an_item_to_list(uint16_t /* s_handle */) { inc_func_call_count(__func__); return elem; } -tGATT_STATUS GATTC_Discover(uint16_t /* conn_id */, - tGATT_DISC_TYPE /* disc_type */, - uint16_t /* start_handle */, - uint16_t /* end_handle */, const Uuid& /* uuid */) { +tGATT_STATUS GATTC_Discover(uint16_t /* conn_id */, tGATT_DISC_TYPE /* disc_type */, + uint16_t /* start_handle */, uint16_t /* end_handle */, + const Uuid& /* uuid */) { inc_func_call_count(__func__); return GATT_SUCCESS; } diff --git a/system/test/mock/mock_stack_gatt_api.cc b/system/test/mock/mock_stack_gatt_api.cc index da4b93afea4..9ad7f8786b2 100644 --- a/system/test/mock/mock_stack_gatt_api.cc +++ b/system/test/mock/mock_stack_gatt_api.cc @@ -38,7 +38,7 @@ namespace stack_gatt_api { // Function state capture and return values, if needed struct GATTC_GetAndRemoveListOfConnIdsWaitingForMtuRequest - GATTC_GetAndRemoveListOfConnIdsWaitingForMtuRequest; + GATTC_GetAndRemoveListOfConnIdsWaitingForMtuRequest; struct GATTC_TryMtuRequest GATTC_TryMtuRequest; struct GATTC_UpdateUserAttMtuIfNeeded GATTC_UpdateUserAttMtuIfNeeded; struct GATTC_ConfigureMTU GATTC_ConfigureMTU; @@ -75,11 +75,9 @@ namespace test { namespace mock { namespace stack_gatt_api { -std::list - GATTC_GetAndRemoveListOfConnIdsWaitingForMtuRequest::return_value = +std::list GATTC_GetAndRemoveListOfConnIdsWaitingForMtuRequest::return_value = std::list(); -tGATTC_TryMtuRequestResult GATTC_TryMtuRequest::return_value = - MTU_EXCHANGE_NOT_DONE_YET; +tGATTC_TryMtuRequestResult GATTC_TryMtuRequest::return_value = MTU_EXCHANGE_NOT_DONE_YET; tGATT_STATUS GATTC_ConfigureMTU::return_value = GATT_SUCCESS; tGATT_STATUS GATTC_Discover::return_value = GATT_SUCCESS; tGATT_STATUS GATTC_ExecuteWrite::return_value = GATT_SUCCESS; @@ -108,42 +106,37 @@ bool is_active_service::return_value = false; // Mocked functions, if any std::list GATTC_GetAndRemoveListOfConnIdsWaitingForMtuRequest( - const RawAddress& remote_bda) { + const RawAddress& remote_bda) { inc_func_call_count(__func__); - return test::mock::stack_gatt_api:: - GATTC_GetAndRemoveListOfConnIdsWaitingForMtuRequest(remote_bda); + return test::mock::stack_gatt_api::GATTC_GetAndRemoveListOfConnIdsWaitingForMtuRequest( + remote_bda); } tGATTC_TryMtuRequestResult GATTC_TryMtuRequest(const RawAddress& remote_bda, - tBT_TRANSPORT transport, - uint16_t conn_id, + tBT_TRANSPORT transport, uint16_t conn_id, uint16_t* current_mtu) { inc_func_call_count(__func__); - return test::mock::stack_gatt_api::GATTC_TryMtuRequest(remote_bda, transport, - conn_id, current_mtu); + return test::mock::stack_gatt_api::GATTC_TryMtuRequest(remote_bda, transport, conn_id, + current_mtu); } -void GATTC_UpdateUserAttMtuIfNeeded(const RawAddress& remote_bda, - tBT_TRANSPORT transport, +void GATTC_UpdateUserAttMtuIfNeeded(const RawAddress& remote_bda, tBT_TRANSPORT transport, uint16_t user_mtu) { inc_func_call_count(__func__); - test::mock::stack_gatt_api::GATTC_UpdateUserAttMtuIfNeeded( - remote_bda, transport, user_mtu); + test::mock::stack_gatt_api::GATTC_UpdateUserAttMtuIfNeeded(remote_bda, transport, user_mtu); } tGATT_STATUS GATTC_ConfigureMTU(uint16_t conn_id, uint16_t mtu) { inc_func_call_count(__func__); return test::mock::stack_gatt_api::GATTC_ConfigureMTU(conn_id, mtu); } -tGATT_STATUS GATTC_Discover(uint16_t conn_id, tGATT_DISC_TYPE disc_type, - uint16_t start_handle, uint16_t end_handle) { +tGATT_STATUS GATTC_Discover(uint16_t conn_id, tGATT_DISC_TYPE disc_type, uint16_t start_handle, + uint16_t end_handle) { inc_func_call_count(__func__); - return test::mock::stack_gatt_api::GATTC_Discover(conn_id, disc_type, - start_handle, end_handle); + return test::mock::stack_gatt_api::GATTC_Discover(conn_id, disc_type, start_handle, end_handle); } tGATT_STATUS GATTC_ExecuteWrite(uint16_t conn_id, bool is_execute) { inc_func_call_count(__func__); return test::mock::stack_gatt_api::GATTC_ExecuteWrite(conn_id, is_execute); } -tGATT_STATUS GATTC_Read(uint16_t conn_id, tGATT_READ_TYPE type, - tGATT_READ_PARAM* p_read) { +tGATT_STATUS GATTC_Read(uint16_t conn_id, tGATT_READ_TYPE type, tGATT_READ_PARAM* p_read) { inc_func_call_count(__func__); return test::mock::stack_gatt_api::GATTC_Read(conn_id, type, p_read); } @@ -151,62 +144,53 @@ tGATT_STATUS GATTC_SendHandleValueConfirm(uint16_t conn_id, uint16_t cid) { inc_func_call_count(__func__); return test::mock::stack_gatt_api::GATTC_SendHandleValueConfirm(conn_id, cid); } -tGATT_STATUS GATTC_Write(uint16_t conn_id, tGATT_WRITE_TYPE type, - tGATT_VALUE* p_write) { +tGATT_STATUS GATTC_Write(uint16_t conn_id, tGATT_WRITE_TYPE type, tGATT_VALUE* p_write) { inc_func_call_count(__func__); return test::mock::stack_gatt_api::GATTC_Write(conn_id, type, p_write); } -tGATT_STATUS GATTS_AddService(tGATT_IF gatt_if, btgatt_db_element_t* service, - int count) { +tGATT_STATUS GATTS_AddService(tGATT_IF gatt_if, btgatt_db_element_t* service, int count) { inc_func_call_count(__func__); return test::mock::stack_gatt_api::GATTS_AddService(gatt_if, service, count); } -bool GATTS_DeleteService(tGATT_IF gatt_if, Uuid* p_svc_uuid, - uint16_t svc_inst) { +bool GATTS_DeleteService(tGATT_IF gatt_if, Uuid* p_svc_uuid, uint16_t svc_inst) { inc_func_call_count(__func__); - return test::mock::stack_gatt_api::GATTS_DeleteService(gatt_if, p_svc_uuid, - svc_inst); + return test::mock::stack_gatt_api::GATTS_DeleteService(gatt_if, p_svc_uuid, svc_inst); } -tGATT_STATUS GATTS_HandleValueIndication(uint16_t conn_id, uint16_t attr_handle, - uint16_t val_len, uint8_t* p_val) { +tGATT_STATUS GATTS_HandleValueIndication(uint16_t conn_id, uint16_t attr_handle, uint16_t val_len, + uint8_t* p_val) { inc_func_call_count(__func__); - return test::mock::stack_gatt_api::GATTS_HandleValueIndication( - conn_id, attr_handle, val_len, p_val); + return test::mock::stack_gatt_api::GATTS_HandleValueIndication(conn_id, attr_handle, val_len, + p_val); } -tGATT_STATUS GATTS_HandleValueNotification(uint16_t conn_id, - uint16_t attr_handle, - uint16_t val_len, uint8_t* p_val) { +tGATT_STATUS GATTS_HandleValueNotification(uint16_t conn_id, uint16_t attr_handle, uint16_t val_len, + uint8_t* p_val) { inc_func_call_count(__func__); - return test::mock::stack_gatt_api::GATTS_HandleValueNotification( - conn_id, attr_handle, val_len, p_val); + return test::mock::stack_gatt_api::GATTS_HandleValueNotification(conn_id, attr_handle, val_len, + p_val); } bool GATTS_NVRegister(tGATT_APPL_INFO* p_cb_info) { inc_func_call_count(__func__); return test::mock::stack_gatt_api::GATTS_NVRegister(p_cb_info); } -tGATT_STATUS GATTS_SendRsp(uint16_t conn_id, uint32_t trans_id, - tGATT_STATUS status, tGATTS_RSP* p_msg) { +tGATT_STATUS GATTS_SendRsp(uint16_t conn_id, uint32_t trans_id, tGATT_STATUS status, + tGATTS_RSP* p_msg) { inc_func_call_count(__func__); - return test::mock::stack_gatt_api::GATTS_SendRsp(conn_id, trans_id, status, - p_msg); + return test::mock::stack_gatt_api::GATTS_SendRsp(conn_id, trans_id, status, p_msg); } void GATTS_StopService(uint16_t service_handle) { inc_func_call_count(__func__); test::mock::stack_gatt_api::GATTS_StopService(service_handle); } -bool GATT_CancelConnect(tGATT_IF gatt_if, const RawAddress& bd_addr, - bool is_direct) { +bool GATT_CancelConnect(tGATT_IF gatt_if, const RawAddress& bd_addr, bool is_direct) { inc_func_call_count(__func__); - return test::mock::stack_gatt_api::GATT_CancelConnect(gatt_if, bd_addr, - is_direct); + return test::mock::stack_gatt_api::GATT_CancelConnect(gatt_if, bd_addr, is_direct); } bool GATT_Connect(tGATT_IF gatt_if, const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type, - tBTM_BLE_CONN_TYPE connection_type, tBT_TRANSPORT transport, - bool opportunistic, uint8_t initiating_phys) { + tBTM_BLE_CONN_TYPE connection_type, tBT_TRANSPORT transport, bool opportunistic, + uint8_t initiating_phys) { inc_func_call_count(__func__); - return test::mock::stack_gatt_api::GATT_Connect( - gatt_if, bd_addr, addr_type, connection_type, transport, opportunistic, - initiating_phys); + return test::mock::stack_gatt_api::GATT_Connect(gatt_if, bd_addr, addr_type, connection_type, + transport, opportunistic, initiating_phys); } void GATT_Deregister(tGATT_IF gatt_if) { inc_func_call_count(__func__); @@ -216,29 +200,27 @@ tGATT_STATUS GATT_Disconnect(uint16_t conn_id) { inc_func_call_count(__func__); return test::mock::stack_gatt_api::GATT_Disconnect(conn_id); } -bool GATT_GetConnIdIfConnected(tGATT_IF gatt_if, const RawAddress& bd_addr, - uint16_t* p_conn_id, tBT_TRANSPORT transport) { +bool GATT_GetConnIdIfConnected(tGATT_IF gatt_if, const RawAddress& bd_addr, uint16_t* p_conn_id, + tBT_TRANSPORT transport) { inc_func_call_count(__func__); - return test::mock::stack_gatt_api::GATT_GetConnIdIfConnected( - gatt_if, bd_addr, p_conn_id, transport); + return test::mock::stack_gatt_api::GATT_GetConnIdIfConnected(gatt_if, bd_addr, p_conn_id, + transport); } -bool GATT_GetConnectionInfor(uint16_t conn_id, tGATT_IF* p_gatt_if, - RawAddress& bd_addr, tBT_TRANSPORT* p_transport) { +bool GATT_GetConnectionInfor(uint16_t conn_id, tGATT_IF* p_gatt_if, RawAddress& bd_addr, + tBT_TRANSPORT* p_transport) { inc_func_call_count(__func__); - return test::mock::stack_gatt_api::GATT_GetConnectionInfor( - conn_id, p_gatt_if, bd_addr, p_transport); + return test::mock::stack_gatt_api::GATT_GetConnectionInfor(conn_id, p_gatt_if, bd_addr, + p_transport); } -tGATT_IF GATT_Register(const Uuid& app_uuid128, const std::string& name, - tGATT_CBACK* p_cb_info, bool eatt_support) { +tGATT_IF GATT_Register(const Uuid& app_uuid128, const std::string& name, tGATT_CBACK* p_cb_info, + bool eatt_support) { inc_func_call_count(__func__); - return test::mock::stack_gatt_api::GATT_Register(app_uuid128, name, p_cb_info, - eatt_support); + return test::mock::stack_gatt_api::GATT_Register(app_uuid128, name, p_cb_info, eatt_support); } -void GATT_SetIdleTimeout(const RawAddress& bd_addr, uint16_t idle_tout, - tBT_TRANSPORT transport, bool is_active) { +void GATT_SetIdleTimeout(const RawAddress& bd_addr, uint16_t idle_tout, tBT_TRANSPORT transport, + bool is_active) { inc_func_call_count(__func__); - test::mock::stack_gatt_api::GATT_SetIdleTimeout(bd_addr, idle_tout, transport, - is_active); + test::mock::stack_gatt_api::GATT_SetIdleTimeout(bd_addr, idle_tout, transport, is_active); } void GATT_StartIf(tGATT_IF gatt_if) { inc_func_call_count(__func__); @@ -248,20 +230,17 @@ void GATT_StartIf(tGATT_IF gatt_if) { // inc_func_call_count(__func__); // return test::mock::stack_gatt_api::gatt_add_an_item_to_list(s_handle); // } -bool is_active_service(const Uuid& app_uuid128, Uuid* p_svc_uuid, - uint16_t start_handle) { +bool is_active_service(const Uuid& app_uuid128, Uuid* p_svc_uuid, uint16_t start_handle) { inc_func_call_count(__func__); - return test::mock::stack_gatt_api::is_active_service(app_uuid128, p_svc_uuid, - start_handle); + return test::mock::stack_gatt_api::is_active_service(app_uuid128, p_svc_uuid, start_handle); } // Mocked functions complete // -bool GATT_Connect(tGATT_IF gatt_if, const RawAddress& bd_addr, - tBTM_BLE_CONN_TYPE connection_type, tBT_TRANSPORT transport, - bool opportunistic) { +bool GATT_Connect(tGATT_IF gatt_if, const RawAddress& bd_addr, tBTM_BLE_CONN_TYPE connection_type, + tBT_TRANSPORT transport, bool opportunistic) { inc_func_call_count(__func__); - return test::mock::stack_gatt_api::GATT_Connect( - gatt_if, bd_addr, 0, connection_type, transport, opportunistic, 0); + return test::mock::stack_gatt_api::GATT_Connect(gatt_if, bd_addr, 0, connection_type, transport, + opportunistic, 0); } // END mockcify generation diff --git a/system/test/mock/mock_stack_gatt_api.h b/system/test/mock/mock_stack_gatt_api.h index 23bf55d7730..8e1b4e5d991 100644 --- a/system/test/mock/mock_stack_gatt_api.h +++ b/system/test/mock/mock_stack_gatt_api.h @@ -51,13 +51,11 @@ namespace stack_gatt_api { struct GATTC_GetAndRemoveListOfConnIdsWaitingForMtuRequest { static std::list return_value; std::function(const RawAddress& remote_bda)> body{ - [](const RawAddress& /* remote_bda */) { return return_value; }}; - std::list operator()(const RawAddress& remote_bda) { - return body(remote_bda); - }; + [](const RawAddress& /* remote_bda */) { return return_value; }}; + std::list operator()(const RawAddress& remote_bda) { return body(remote_bda); } }; extern struct GATTC_GetAndRemoveListOfConnIdsWaitingForMtuRequest - GATTC_GetAndRemoveListOfConnIdsWaitingForMtuRequest; + GATTC_GetAndRemoveListOfConnIdsWaitingForMtuRequest; // Shared state between mocked functions and tests // Name: GATTC_ConfigureMTU @@ -66,18 +64,14 @@ extern struct GATTC_GetAndRemoveListOfConnIdsWaitingForMtuRequest // Return: tGATTC_TryMtuRequestResult struct GATTC_TryMtuRequest { static tGATTC_TryMtuRequestResult return_value; - std::function - body{[](const RawAddress& /* remote_bda */, tBT_TRANSPORT /* transport */, - uint16_t /* conn_id */, - uint16_t* /* current_mtu */) { return return_value; }}; - tGATTC_TryMtuRequestResult operator()(const RawAddress& remote_bda, - tBT_TRANSPORT transport, - uint16_t conn_id, - uint16_t* current_mtu) { + std::function + body{[](const RawAddress& /* remote_bda */, tBT_TRANSPORT /* transport */, + uint16_t /* conn_id */, uint16_t* /* current_mtu */) { return return_value; }}; + tGATTC_TryMtuRequestResult operator()(const RawAddress& remote_bda, tBT_TRANSPORT transport, + uint16_t conn_id, uint16_t* current_mtu) { return body(remote_bda, transport, conn_id, current_mtu); - }; + } }; extern struct GATTC_TryMtuRequest GATTC_TryMtuRequest; @@ -87,14 +81,12 @@ extern struct GATTC_TryMtuRequest GATTC_TryMtuRequest; // uint16_t user_mtu // Return: void struct GATTC_UpdateUserAttMtuIfNeeded { - std::function - body{[](const RawAddress& /* remote_bda */, tBT_TRANSPORT /* transport */, - uint16_t /* user_mtu */) {}}; - void operator()(const RawAddress& remote_bda, tBT_TRANSPORT transport, - uint16_t user_mtu) { + std::function + body{[](const RawAddress& /* remote_bda */, tBT_TRANSPORT /* transport */, + uint16_t /* user_mtu */) {}}; + void operator()(const RawAddress& remote_bda, tBT_TRANSPORT transport, uint16_t user_mtu) { body(remote_bda, transport, user_mtu); - }; + } }; extern struct GATTC_UpdateUserAttMtuIfNeeded GATTC_UpdateUserAttMtuIfNeeded; @@ -105,10 +97,8 @@ extern struct GATTC_UpdateUserAttMtuIfNeeded GATTC_UpdateUserAttMtuIfNeeded; struct GATTC_ConfigureMTU { static tGATT_STATUS return_value; std::function body{ - [](uint16_t /* conn_id */, uint16_t /* mtu */) { return return_value; }}; - tGATT_STATUS operator()(uint16_t conn_id, uint16_t mtu) { - return body(conn_id, mtu); - }; + [](uint16_t /* conn_id */, uint16_t /* mtu */) { return return_value; }}; + tGATT_STATUS operator()(uint16_t conn_id, uint16_t mtu) { return body(conn_id, mtu); } }; extern struct GATTC_ConfigureMTU GATTC_ConfigureMTU; @@ -117,15 +107,14 @@ extern struct GATTC_ConfigureMTU GATTC_ConfigureMTU; // uint16_t end_handle Return: tGATT_STATUS struct GATTC_Discover { static tGATT_STATUS return_value; - std::function - body{[](uint16_t /* conn_id */, tGATT_DISC_TYPE /* disc_type */, - uint16_t /* start_handle */, - uint16_t /* end_handle */) { return return_value; }}; - tGATT_STATUS operator()(uint16_t conn_id, tGATT_DISC_TYPE disc_type, - uint16_t start_handle, uint16_t end_handle) { + std::function + body{[](uint16_t /* conn_id */, tGATT_DISC_TYPE /* disc_type */, + uint16_t /* start_handle */, uint16_t /* end_handle */) { return return_value; }}; + tGATT_STATUS operator()(uint16_t conn_id, tGATT_DISC_TYPE disc_type, uint16_t start_handle, + uint16_t end_handle) { return body(conn_id, disc_type, start_handle, end_handle); - }; + } }; extern struct GATTC_Discover GATTC_Discover; @@ -135,12 +124,8 @@ extern struct GATTC_Discover GATTC_Discover; struct GATTC_ExecuteWrite { static tGATT_STATUS return_value; std::function body{ - [](uint16_t /* conn_id */, bool /* is_execute */) { - return return_value; - }}; - tGATT_STATUS operator()(uint16_t conn_id, bool is_execute) { - return body(conn_id, is_execute); - }; + [](uint16_t /* conn_id */, bool /* is_execute */) { return return_value; }}; + tGATT_STATUS operator()(uint16_t conn_id, bool is_execute) { return body(conn_id, is_execute); } }; extern struct GATTC_ExecuteWrite GATTC_ExecuteWrite; @@ -149,14 +134,12 @@ extern struct GATTC_ExecuteWrite GATTC_ExecuteWrite; // Return: tGATT_STATUS struct GATTC_Read { static tGATT_STATUS return_value; - std::function - body{[](uint16_t /* conn_id */, tGATT_READ_TYPE /* type */, - tGATT_READ_PARAM* /* p_read */) { return return_value; }}; - tGATT_STATUS operator()(uint16_t conn_id, tGATT_READ_TYPE type, - tGATT_READ_PARAM* p_read) { + std::function + body{[](uint16_t /* conn_id */, tGATT_READ_TYPE /* type */, + tGATT_READ_PARAM* /* p_read */) { return return_value; }}; + tGATT_STATUS operator()(uint16_t conn_id, tGATT_READ_TYPE type, tGATT_READ_PARAM* p_read) { return body(conn_id, type, p_read); - }; + } }; extern struct GATTC_Read GATTC_Read; @@ -166,10 +149,8 @@ extern struct GATTC_Read GATTC_Read; struct GATTC_SendHandleValueConfirm { static tGATT_STATUS return_value; std::function body{ - [](uint16_t /* conn_id */, uint16_t /* cid */) { return return_value; }}; - tGATT_STATUS operator()(uint16_t conn_id, uint16_t cid) { - return body(conn_id, cid); - }; + [](uint16_t /* conn_id */, uint16_t /* cid */) { return return_value; }}; + tGATT_STATUS operator()(uint16_t conn_id, uint16_t cid) { return body(conn_id, cid); } }; extern struct GATTC_SendHandleValueConfirm GATTC_SendHandleValueConfirm; @@ -178,14 +159,13 @@ extern struct GATTC_SendHandleValueConfirm GATTC_SendHandleValueConfirm; // Return: tGATT_STATUS struct GATTC_Write { static tGATT_STATUS return_value; - std::function - body{[](uint16_t /* conn_id */, tGATT_WRITE_TYPE /* type */, - tGATT_VALUE* /* p_write */) { return return_value; }}; - tGATT_STATUS operator()(uint16_t conn_id, tGATT_WRITE_TYPE type, - tGATT_VALUE* p_write) { + std::function body{ + [](uint16_t /* conn_id */, tGATT_WRITE_TYPE /* type */, tGATT_VALUE* /* p_write */) { + return return_value; + }}; + tGATT_STATUS operator()(uint16_t conn_id, tGATT_WRITE_TYPE type, tGATT_VALUE* p_write) { return body(conn_id, type, p_write); - }; + } }; extern struct GATTC_Write GATTC_Write; @@ -194,14 +174,13 @@ extern struct GATTC_Write GATTC_Write; // Return: tGATT_STATUS struct GATTS_AddService { static tGATT_STATUS return_value; - std::function - body{[](tGATT_IF /* gatt_if */, btgatt_db_element_t* /* service */, - int /* count */) { return return_value; }}; - tGATT_STATUS operator()(tGATT_IF gatt_if, btgatt_db_element_t* service, - int count) { + std::function body{ + [](tGATT_IF /* gatt_if */, btgatt_db_element_t* /* service */, int /* count */) { + return return_value; + }}; + tGATT_STATUS operator()(tGATT_IF gatt_if, btgatt_db_element_t* service, int count) { return body(gatt_if, service, count); - }; + } }; extern struct GATTS_AddService GATTS_AddService; @@ -210,12 +189,13 @@ extern struct GATTS_AddService GATTS_AddService; // Return: bool struct GATTS_DeleteService { static bool return_value; - std::function - body{[](tGATT_IF /* gatt_if */, Uuid* /* p_svc_uuid */, - uint16_t /* svc_inst */) { return return_value; }}; + std::function body{ + [](tGATT_IF /* gatt_if */, Uuid* /* p_svc_uuid */, uint16_t /* svc_inst */) { + return return_value; + }}; bool operator()(tGATT_IF gatt_if, Uuid* p_svc_uuid, uint16_t svc_inst) { return body(gatt_if, p_svc_uuid, svc_inst); - }; + } }; extern struct GATTS_DeleteService GATTS_DeleteService; @@ -224,15 +204,14 @@ extern struct GATTS_DeleteService GATTS_DeleteService; // p_val Return: tGATT_STATUS struct GATTS_HandleValueIndication { static tGATT_STATUS return_value; - std::function - body{[](uint16_t /* conn_id */, uint16_t /* attr_handle */, - uint16_t /* val_len */, - uint8_t* /* p_val */) { return return_value; }}; - tGATT_STATUS operator()(uint16_t conn_id, uint16_t attr_handle, - uint16_t val_len, uint8_t* p_val) { + std::function + body{[](uint16_t /* conn_id */, uint16_t /* attr_handle */, uint16_t /* val_len */, + uint8_t* /* p_val */) { return return_value; }}; + tGATT_STATUS operator()(uint16_t conn_id, uint16_t attr_handle, uint16_t val_len, + uint8_t* p_val) { return body(conn_id, attr_handle, val_len, p_val); - }; + } }; extern struct GATTS_HandleValueIndication GATTS_HandleValueIndication; @@ -241,15 +220,14 @@ extern struct GATTS_HandleValueIndication GATTS_HandleValueIndication; // p_val Return: tGATT_STATUS struct GATTS_HandleValueNotification { static tGATT_STATUS return_value; - std::function - body{[](uint16_t /* conn_id */, uint16_t /* attr_handle */, - uint16_t /* val_len */, - uint8_t* /* p_val */) { return return_value; }}; - tGATT_STATUS operator()(uint16_t conn_id, uint16_t attr_handle, - uint16_t val_len, uint8_t* p_val) { + std::function + body{[](uint16_t /* conn_id */, uint16_t /* attr_handle */, uint16_t /* val_len */, + uint8_t* /* p_val */) { return return_value; }}; + tGATT_STATUS operator()(uint16_t conn_id, uint16_t attr_handle, uint16_t val_len, + uint8_t* p_val) { return body(conn_id, attr_handle, val_len, p_val); - }; + } }; extern struct GATTS_HandleValueNotification GATTS_HandleValueNotification; @@ -259,8 +237,8 @@ extern struct GATTS_HandleValueNotification GATTS_HandleValueNotification; struct GATTS_NVRegister { static bool return_value; std::function body{ - [](tGATT_APPL_INFO* /* p_cb_info */) { return return_value; }}; - bool operator()(tGATT_APPL_INFO* p_cb_info) { return body(p_cb_info); }; + [](tGATT_APPL_INFO* /* p_cb_info */) { return return_value; }}; + bool operator()(tGATT_APPL_INFO* p_cb_info) { return body(p_cb_info); } }; extern struct GATTS_NVRegister GATTS_NVRegister; @@ -269,15 +247,14 @@ extern struct GATTS_NVRegister GATTS_NVRegister; // p_msg Return: tGATT_STATUS struct GATTS_SendRsp { static tGATT_STATUS return_value; - std::function - body{[](uint16_t /* conn_id */, uint32_t /* trans_id */, - tGATT_STATUS /* status */, - tGATTS_RSP* /* p_msg */) { return return_value; }}; - tGATT_STATUS operator()(uint16_t conn_id, uint32_t trans_id, - tGATT_STATUS status, tGATTS_RSP* p_msg) { + std::function + body{[](uint16_t /* conn_id */, uint32_t /* trans_id */, tGATT_STATUS /* status */, + tGATTS_RSP* /* p_msg */) { return return_value; }}; + tGATT_STATUS operator()(uint16_t conn_id, uint32_t trans_id, tGATT_STATUS status, + tGATTS_RSP* p_msg) { return body(conn_id, trans_id, status, p_msg); - }; + } }; extern struct GATTS_SendRsp GATTS_SendRsp; @@ -285,9 +262,8 @@ extern struct GATTS_SendRsp GATTS_SendRsp; // Params: uint16_t service_handle // Return: void struct GATTS_StopService { - std::function body{ - [](uint16_t /* service_handle */) {}}; - void operator()(uint16_t service_handle) { body(service_handle); }; + std::function body{[](uint16_t /* service_handle */) {}}; + void operator()(uint16_t service_handle) { body(service_handle); } }; extern struct GATTS_StopService GATTS_StopService; @@ -296,13 +272,13 @@ extern struct GATTS_StopService GATTS_StopService; // Return: bool struct GATT_CancelConnect { static bool return_value; - std::function - body{[](tGATT_IF /* gatt_if */, const RawAddress& /* bd_addr */, - bool /* is_direct */) { return return_value; }}; + std::function body{ + [](tGATT_IF /* gatt_if */, const RawAddress& /* bd_addr */, bool /* is_direct */) { + return return_value; + }}; bool operator()(tGATT_IF gatt_if, const RawAddress& bd_addr, bool is_direct) { return body(gatt_if, bd_addr, is_direct); - }; + } }; extern struct GATT_CancelConnect GATT_CancelConnect; @@ -312,21 +288,18 @@ extern struct GATT_CancelConnect GATT_CancelConnect; // bool struct GATT_Connect { static bool return_value; - std::function - body{[](tGATT_IF /* gatt_if */, const RawAddress& /* bd_addr */, - tBLE_ADDR_TYPE /* addr_type */, bool /* is_direct */, - tBT_TRANSPORT /* transport */, bool /* opportunistic */, - uint8_t /* initiating_phys */) { return return_value; }}; - bool operator()(tGATT_IF gatt_if, const RawAddress& bd_addr, - tBLE_ADDR_TYPE addr_type, bool is_direct, - tBT_TRANSPORT transport, bool opportunistic, + body{[](tGATT_IF /* gatt_if */, const RawAddress& /* bd_addr */, + tBLE_ADDR_TYPE /* addr_type */, bool /* is_direct */, + tBT_TRANSPORT /* transport */, bool /* opportunistic */, + uint8_t /* initiating_phys */) { return return_value; }}; + bool operator()(tGATT_IF gatt_if, const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type, + bool is_direct, tBT_TRANSPORT transport, bool opportunistic, uint8_t initiating_phys) { - return body(gatt_if, bd_addr, addr_type, is_direct, transport, - opportunistic, initiating_phys); - }; + return body(gatt_if, bd_addr, addr_type, is_direct, transport, opportunistic, initiating_phys); + } }; extern struct GATT_Connect GATT_Connect; @@ -335,7 +308,7 @@ extern struct GATT_Connect GATT_Connect; // Return: void struct GATT_Deregister { std::function body{[](tGATT_IF /* gatt_if */) {}}; - void operator()(tGATT_IF gatt_if) { body(gatt_if); }; + void operator()(tGATT_IF gatt_if) { body(gatt_if); } }; extern struct GATT_Deregister GATT_Deregister; @@ -345,8 +318,8 @@ extern struct GATT_Deregister GATT_Deregister; struct GATT_Disconnect { static tGATT_STATUS return_value; std::function body{ - [](uint16_t /* conn_id */) { return return_value; }}; - tGATT_STATUS operator()(uint16_t conn_id) { return body(conn_id); }; + [](uint16_t /* conn_id */) { return return_value; }}; + tGATT_STATUS operator()(uint16_t conn_id) { return body(conn_id); } }; extern struct GATT_Disconnect GATT_Disconnect; @@ -355,15 +328,15 @@ extern struct GATT_Disconnect GATT_Disconnect; // tBT_TRANSPORT transport Return: bool struct GATT_GetConnIdIfConnected { static bool return_value; - std::function - body{[](tGATT_IF /* gatt_if */, const RawAddress& /* bd_addr */, - uint16_t* /* p_conn_id */, - tBT_TRANSPORT /* transport */) { return return_value; }}; - bool operator()(tGATT_IF gatt_if, const RawAddress& bd_addr, - uint16_t* p_conn_id, tBT_TRANSPORT transport) { + std::function + body{[](tGATT_IF /* gatt_if */, const RawAddress& /* bd_addr */, + uint16_t* /* p_conn_id */, + tBT_TRANSPORT /* transport */) { return return_value; }}; + bool operator()(tGATT_IF gatt_if, const RawAddress& bd_addr, uint16_t* p_conn_id, + tBT_TRANSPORT transport) { return body(gatt_if, bd_addr, p_conn_id, transport); - }; + } }; extern struct GATT_GetConnIdIfConnected GATT_GetConnIdIfConnected; @@ -374,13 +347,12 @@ struct GATT_GetConnectionInfor { static bool return_value; std::function - body{[](uint16_t /* conn_id */, tGATT_IF* /* p_gatt_if */, - RawAddress& /* bd_addr */, - tBT_TRANSPORT* /* p_transport */) { return return_value; }}; + body{[](uint16_t /* conn_id */, tGATT_IF* /* p_gatt_if */, RawAddress& /* bd_addr */, + tBT_TRANSPORT* /* p_transport */) { return return_value; }}; bool operator()(uint16_t conn_id, tGATT_IF* p_gatt_if, RawAddress& bd_addr, tBT_TRANSPORT* p_transport) { return body(conn_id, p_gatt_if, bd_addr, p_transport); - }; + } }; extern struct GATT_GetConnectionInfor GATT_GetConnectionInfor; @@ -389,15 +361,14 @@ extern struct GATT_GetConnectionInfor GATT_GetConnectionInfor; // bool eatt_support Return: tGATT_IF struct GATT_Register { static tGATT_IF return_value; - std::function - body{[](const Uuid& /* app_uuid128 */, const std::string& /* name */, - tGATT_CBACK* /* p_cb_info */, - bool /* eatt_support */) { return return_value; }}; - tGATT_IF operator()(const Uuid& app_uuid128, const std::string& name, - tGATT_CBACK* p_cb_info, bool eatt_support) { + std::function + body{[](const Uuid& /* app_uuid128 */, const std::string& /* name */, + tGATT_CBACK* /* p_cb_info */, bool /* eatt_support */) { return return_value; }}; + tGATT_IF operator()(const Uuid& app_uuid128, const std::string& name, tGATT_CBACK* p_cb_info, + bool eatt_support) { return body(app_uuid128, name, p_cb_info, eatt_support); - }; + } }; extern struct GATT_Register GATT_Register; @@ -405,14 +376,14 @@ extern struct GATT_Register GATT_Register; // Params: const RawAddress& bd_addr, uint16_t idle_tout, tBT_TRANSPORT // transport Return: void struct GATT_SetIdleTimeout { - std::function - body{[](const RawAddress& /* bd_addr */, uint16_t /* idle_tout */, - tBT_TRANSPORT /* transport */, bool /* is_active */) {}}; - void operator()(const RawAddress& bd_addr, uint16_t idle_tout, - tBT_TRANSPORT transport, bool is_active) { + std::function + body{[](const RawAddress& /* bd_addr */, uint16_t /* idle_tout */, + tBT_TRANSPORT /* transport */, bool /* is_active */) {}}; + void operator()(const RawAddress& bd_addr, uint16_t idle_tout, tBT_TRANSPORT transport, + bool is_active) { body(bd_addr, idle_tout, transport, is_active); - }; + } }; extern struct GATT_SetIdleTimeout GATT_SetIdleTimeout; @@ -421,7 +392,7 @@ extern struct GATT_SetIdleTimeout GATT_SetIdleTimeout; // Return: void struct GATT_StartIf { std::function body{[](tGATT_IF /* gatt_if */) {}}; - void operator()(tGATT_IF gatt_if) { body(gatt_if); }; + void operator()(tGATT_IF gatt_if) { body(gatt_if); } }; extern struct GATT_StartIf GATT_StartIf; @@ -442,14 +413,13 @@ extern struct GATT_StartIf GATT_StartIf; // Return: bool struct is_active_service { static bool return_value; - std::function - body{[](const Uuid& /* app_uuid128 */, Uuid* /* p_svc_uuid */, - uint16_t /* start_handle */) { return return_value; }}; - bool operator()(const Uuid& app_uuid128, Uuid* p_svc_uuid, - uint16_t start_handle) { + std::function body{ + [](const Uuid& /* app_uuid128 */, Uuid* /* p_svc_uuid */, uint16_t /* start_handle */) { + return return_value; + }}; + bool operator()(const Uuid& app_uuid128, Uuid* p_svc_uuid, uint16_t start_handle) { return body(app_uuid128, p_svc_uuid, start_handle); - }; + } }; extern struct is_active_service is_active_service; diff --git a/system/test/mock/mock_stack_gatt_attr.cc b/system/test/mock/mock_stack_gatt_attr.cc index ae74c2cf016..f38ab92a41f 100644 --- a/system/test/mock/mock_stack_gatt_attr.cc +++ b/system/test/mock/mock_stack_gatt_attr.cc @@ -28,14 +28,12 @@ #include "types/bt_transport.h" #include "types/raw_address.h" -uint16_t gatt_profile_find_conn_id_by_bd_addr( - const RawAddress& /* remote_bda */) { +uint16_t gatt_profile_find_conn_id_by_bd_addr(const RawAddress& /* remote_bda */) { inc_func_call_count(__func__); return 0; } -bool gatt_profile_get_eatt_support( - const RawAddress& /* remote_bda */, - base::OnceCallback /* cb */) { +bool gatt_profile_get_eatt_support(const RawAddress& /* remote_bda */, + base::OnceCallback /* cb */) { inc_func_call_count(__func__); return false; } @@ -43,14 +41,12 @@ bool gatt_sr_is_cl_change_aware(tGATT_TCB& /* tcb */) { inc_func_call_count(__func__); return false; } -tGATT_PROFILE_CLCB* gatt_profile_clcb_alloc(uint16_t /* conn_id */, - const RawAddress& /* bda */, +tGATT_PROFILE_CLCB* gatt_profile_clcb_alloc(uint16_t /* conn_id */, const RawAddress& /* bda */, tBT_TRANSPORT /* tranport */) { inc_func_call_count(__func__); return nullptr; } -tGATT_STATUS proc_read_req(uint16_t /* conn_id */, tGATTS_REQ_TYPE, - tGATT_READ_REQ* /* p_data */, +tGATT_STATUS proc_read_req(uint16_t /* conn_id */, tGATTS_REQ_TYPE, tGATT_READ_REQ* /* p_data */, tGATTS_RSP* /* p_rsp */) { inc_func_call_count(__func__); return GATT_SUCCESS; @@ -65,25 +61,19 @@ tGATT_STATUS read_attr_value(uint16_t /* conn_id */, uint16_t /* handle */, inc_func_call_count(__func__); return GATT_SUCCESS; } -void GATT_ConfigServiceChangeCCC(const RawAddress& /* remote_bda */, - bool /* enable */, +void GATT_ConfigServiceChangeCCC(const RawAddress& /* remote_bda */, bool /* enable */, tBT_TRANSPORT /* transport */) { inc_func_call_count(__func__); } -void gatt_profile_clcb_dealloc(tGATT_PROFILE_CLCB* /* p_clcb */) { - inc_func_call_count(__func__); -} +void gatt_profile_clcb_dealloc(tGATT_PROFILE_CLCB* /* p_clcb */) { inc_func_call_count(__func__); } void gatt_profile_db_init(void) { inc_func_call_count(__func__); } -void gatt_sr_init_cl_status(tGATT_TCB& /* tcb */) { - inc_func_call_count(__func__); -} +void gatt_sr_init_cl_status(tGATT_TCB& /* tcb */) { inc_func_call_count(__func__); } void gatt_sr_update_cl_status(tGATT_TCB& /* tcb */, bool /* chg_aware */) { inc_func_call_count(__func__); } -bool gatt_cl_read_sirk_req( - const RawAddress& /* peer_bda */, - base::OnceCallback - /* cb */) { +bool gatt_cl_read_sirk_req(const RawAddress& /* peer_bda */, + base::OnceCallback + /* cb */) { return false; } diff --git a/system/test/mock/mock_stack_gatt_auth.cc b/system/test/mock/mock_stack_gatt_auth.cc index f9b7bc07715..e676da43fd7 100644 --- a/system/test/mock/mock_stack_gatt_auth.cc +++ b/system/test/mock/mock_stack_gatt_auth.cc @@ -42,13 +42,10 @@ tGATT_STATUS gatt_get_link_encrypt_status(tGATT_TCB& /* tcb */) { inc_func_call_count(__func__); return GATT_SUCCESS; } -void gatt_notify_enc_cmpl(const RawAddress& /* bd_addr */) { - inc_func_call_count(__func__); -} +void gatt_notify_enc_cmpl(const RawAddress& /* bd_addr */) { inc_func_call_count(__func__); } void gatt_set_sec_act(tGATT_TCB* /* p_tcb */, tGATT_SEC_ACTION /* sec_act */) { inc_func_call_count(__func__); } -void gatt_verify_signature(tGATT_TCB& /* tcb */, uint16_t /* cid */, - BT_HDR* /* p_buf */) { +void gatt_verify_signature(tGATT_TCB& /* tcb */, uint16_t /* cid */, BT_HDR* /* p_buf */) { inc_func_call_count(__func__); } diff --git a/system/test/mock/mock_stack_gatt_connection_manager.cc b/system/test/mock/mock_stack_gatt_connection_manager.cc index ed54a2d5178..3c6c48f7b3b 100644 --- a/system/test/mock/mock_stack_gatt_connection_manager.cc +++ b/system/test/mock/mock_stack_gatt_connection_manager.cc @@ -28,18 +28,17 @@ using namespace connection_manager; -bool connection_manager::background_connect_add( - uint8_t /* app_id */, const RawAddress& /* address */) { +bool connection_manager::background_connect_add(uint8_t /* app_id */, + const RawAddress& /* address */) { inc_func_call_count(__func__); return false; } -bool connection_manager::background_connect_remove( - uint8_t /* app_id */, const RawAddress& /* address */) { +bool connection_manager::background_connect_remove(uint8_t /* app_id */, + const RawAddress& /* address */) { inc_func_call_count(__func__); return false; } -bool connection_manager::direct_connect_add(uint8_t /* app_id */, - const RawAddress& /* address */) { +bool connection_manager::direct_connect_add(uint8_t /* app_id */, const RawAddress& /* address */) { inc_func_call_count(__func__); return false; } @@ -53,8 +52,7 @@ bool connection_manager::remove_unconditional(const RawAddress& /* address */) { inc_func_call_count(__func__); return false; } -std::set connection_manager::get_apps_connecting_to( - const RawAddress& /* address */) { +std::set connection_manager::get_apps_connecting_to(const RawAddress& /* address */) { inc_func_call_count(__func__); return std::set(); } @@ -62,22 +60,17 @@ void connection_manager::dump(int /* fd */) { inc_func_call_count(__func__); } void connection_manager::on_app_deregistered(uint8_t /* app_id */) { inc_func_call_count(__func__); } -void connection_manager::on_connection_complete( - const RawAddress& /* address */) { +void connection_manager::on_connection_complete(const RawAddress& /* address */) { inc_func_call_count(__func__); } -void connection_manager::on_connection_timed_out_from_shim( - const RawAddress& /* address */) { +void connection_manager::on_connection_timed_out_from_shim(const RawAddress& /* address */) { inc_func_call_count(__func__); } -void connection_manager::reset(bool /* after_reset */) { - inc_func_call_count(__func__); -} +void connection_manager::reset(bool /* after_reset */) { inc_func_call_count(__func__); } -bool connection_manager::is_background_connection( - const RawAddress& /* address */) { +bool connection_manager::is_background_connection(const RawAddress& /* address */) { inc_func_call_count(__func__); return false; } diff --git a/system/test/mock/mock_stack_gatt_main.cc b/system/test/mock/mock_stack_gatt_main.cc index c6963a2dfd3..d59a56f304d 100644 --- a/system/test/mock/mock_stack_gatt_main.cc +++ b/system/test/mock/mock_stack_gatt_main.cc @@ -27,8 +27,7 @@ void gatt_init(void) { inc_func_call_count(__func__); } bool gatt_act_connect(tGATT_REG* /* p_reg */, const RawAddress& /* bd_addr */, - tBLE_ADDR_TYPE /* addr_type */, - tBT_TRANSPORT /* transport */, + tBLE_ADDR_TYPE /* addr_type */, tBT_TRANSPORT /* transport */, int8_t /* initiating_phys */) { inc_func_call_count(__func__); return false; @@ -50,15 +49,11 @@ tGATT_CH_STATE gatt_get_ch_state(tGATT_TCB* /* p_tcb */) { void gatt_add_a_bonded_dev_for_srv_chg(const RawAddress& /* bda */) { inc_func_call_count(__func__); } -void gatt_chk_srv_chg(tGATTS_SRV_CHG* /* p_srv_chg_clt */) { +void gatt_chk_srv_chg(tGATTS_SRV_CHG* /* p_srv_chg_clt */) { inc_func_call_count(__func__); } +void gatt_data_process(tGATT_TCB& /* tcb */, uint16_t /* cid */, BT_HDR* /* p_buf */) { inc_func_call_count(__func__); } -void gatt_data_process(tGATT_TCB& /* tcb */, uint16_t /* cid */, - BT_HDR* /* p_buf */) { - inc_func_call_count(__func__); -} -void gatt_consolidate(const RawAddress& /* identity_addr */, - const RawAddress& /* rpa */) { +void gatt_consolidate(const RawAddress& /* identity_addr */, const RawAddress& /* rpa */) { inc_func_call_count(__func__); } void gatt_free(void) { inc_func_call_count(__func__); } @@ -67,39 +62,33 @@ void gatt_l2cif_config_cfm_cback(uint16_t /* lcid */, uint16_t /* initiator */, tL2CAP_CFG_INFO* /* p_cfg */) { inc_func_call_count(__func__); } -void gatt_l2cif_config_ind_cback(uint16_t /* lcid */, - tL2CAP_CFG_INFO* /* p_cfg */) { +void gatt_l2cif_config_ind_cback(uint16_t /* lcid */, tL2CAP_CFG_INFO* /* p_cfg */) { inc_func_call_count(__func__); } -void gatt_l2cif_disconnect_ind_cback(uint16_t /* lcid */, - bool /* ack_needed */) { +void gatt_l2cif_disconnect_ind_cback(uint16_t /* lcid */, bool /* ack_needed */) { inc_func_call_count(__func__); } -void gatt_notify_conn_update(const RawAddress& /* remote */, - uint16_t /* interval */, uint16_t /* latency */, - uint16_t /* timeout */, tHCI_STATUS /* status */) { +void gatt_notify_conn_update(const RawAddress& /* remote */, uint16_t /* interval */, + uint16_t /* latency */, uint16_t /* timeout */, + tHCI_STATUS /* status */) { inc_func_call_count(__func__); } -void gatt_notify_phy_updated(tHCI_STATUS /* status */, uint16_t /* handle */, - uint8_t /* tx_phy */, uint8_t /* rx_phy */) { +void gatt_notify_phy_updated(tHCI_STATUS /* status */, uint16_t /* handle */, uint8_t /* tx_phy */, + uint8_t /* rx_phy */) { inc_func_call_count(__func__); } -void gatt_notify_subrate_change(uint16_t /* handle */, - uint16_t /* subrate_factor */, +void gatt_notify_subrate_change(uint16_t /* handle */, uint16_t /* subrate_factor */, uint16_t /* latency */, uint16_t /* cont_num */, uint16_t /* timeout */, uint8_t /* status */) { inc_func_call_count(__func__); } void gatt_proc_srv_chg(void) { inc_func_call_count(__func__); } -void gatt_send_srv_chg_ind(const RawAddress& /* peer_bda */) { - inc_func_call_count(__func__); -} +void gatt_send_srv_chg_ind(const RawAddress& /* peer_bda */) { inc_func_call_count(__func__); } void gatt_set_ch_state(tGATT_TCB* /* p_tcb */, tGATT_CH_STATE /* ch_state */) { inc_func_call_count(__func__); } -void gatt_update_app_use_link_flag(tGATT_IF /* gatt_if */, - tGATT_TCB* /* p_tcb */, bool /* is_add */, - bool /* check_acl_link */) { +void gatt_update_app_use_link_flag(tGATT_IF /* gatt_if */, tGATT_TCB* /* p_tcb */, + bool /* is_add */, bool /* check_acl_link */) { inc_func_call_count(__func__); } diff --git a/system/test/mock/mock_stack_hcic_hciblecmds.cc b/system/test/mock/mock_stack_hcic_hciblecmds.cc index d5d71f6f216..354d4c151f4 100644 --- a/system/test/mock/mock_stack_hcic_hciblecmds.cc +++ b/system/test/mock/mock_stack_hcic_hciblecmds.cc @@ -34,46 +34,40 @@ namespace stack_hcic_hciblecmds { // Function state capture and return values, if needed struct btsnd_hci_ble_add_device_to_periodic_advertiser_list - btsnd_hci_ble_add_device_to_periodic_advertiser_list; -struct btsnd_hci_ble_clear_periodic_advertiser_list - btsnd_hci_ble_clear_periodic_advertiser_list; + btsnd_hci_ble_add_device_to_periodic_advertiser_list; +struct btsnd_hci_ble_clear_periodic_advertiser_list btsnd_hci_ble_clear_periodic_advertiser_list; struct btsnd_hci_ble_remove_device_from_periodic_advertiser_list - btsnd_hci_ble_remove_device_from_periodic_advertiser_list; + btsnd_hci_ble_remove_device_from_periodic_advertiser_list; struct btsnd_hcic_ble_ltk_req_neg_reply btsnd_hcic_ble_ltk_req_neg_reply; struct btsnd_hcic_ble_ltk_req_reply btsnd_hcic_ble_ltk_req_reply; struct btsnd_hcic_ble_periodic_advertising_create_sync - btsnd_hcic_ble_periodic_advertising_create_sync; + btsnd_hcic_ble_periodic_advertising_create_sync; struct btsnd_hcic_ble_periodic_advertising_create_sync_cancel - btsnd_hcic_ble_periodic_advertising_create_sync_cancel; + btsnd_hcic_ble_periodic_advertising_create_sync_cancel; struct btsnd_hcic_ble_periodic_advertising_set_info_transfer - btsnd_hcic_ble_periodic_advertising_set_info_transfer; + btsnd_hcic_ble_periodic_advertising_set_info_transfer; struct btsnd_hcic_ble_periodic_advertising_sync_transfer - btsnd_hcic_ble_periodic_advertising_sync_transfer; + btsnd_hcic_ble_periodic_advertising_sync_transfer; struct btsnd_hcic_ble_periodic_advertising_terminate_sync - btsnd_hcic_ble_periodic_advertising_terminate_sync; + btsnd_hcic_ble_periodic_advertising_terminate_sync; struct btsnd_hcic_ble_rand btsnd_hcic_ble_rand; -struct btsnd_hcic_ble_read_adv_chnl_tx_power - btsnd_hcic_ble_read_adv_chnl_tx_power; +struct btsnd_hcic_ble_read_adv_chnl_tx_power btsnd_hcic_ble_read_adv_chnl_tx_power; struct btsnd_hcic_ble_read_remote_feat btsnd_hcic_ble_read_remote_feat; -struct btsnd_hcic_ble_read_resolvable_addr_peer - btsnd_hcic_ble_read_resolvable_addr_peer; +struct btsnd_hcic_ble_read_resolvable_addr_peer btsnd_hcic_ble_read_resolvable_addr_peer; struct btsnd_hcic_ble_receiver_test btsnd_hcic_ble_receiver_test; struct btsnd_hcic_ble_set_adv_data btsnd_hcic_ble_set_adv_data; struct btsnd_hcic_ble_set_adv_enable btsnd_hcic_ble_set_adv_enable; struct btsnd_hcic_ble_set_data_length btsnd_hcic_ble_set_data_length; struct btsnd_hcic_ble_set_default_periodic_advertising_sync_transfer_params - btsnd_hcic_ble_set_default_periodic_advertising_sync_transfer_params; -struct btsnd_hcic_ble_set_extended_scan_enable - btsnd_hcic_ble_set_extended_scan_enable; -struct btsnd_hcic_ble_set_extended_scan_params - btsnd_hcic_ble_set_extended_scan_params; + btsnd_hcic_ble_set_default_periodic_advertising_sync_transfer_params; +struct btsnd_hcic_ble_set_extended_scan_enable btsnd_hcic_ble_set_extended_scan_enable; +struct btsnd_hcic_ble_set_extended_scan_params btsnd_hcic_ble_set_extended_scan_params; struct btsnd_hcic_ble_set_periodic_advertising_receive_enable - btsnd_hcic_ble_set_periodic_advertising_receive_enable; + btsnd_hcic_ble_set_periodic_advertising_receive_enable; struct btsnd_hcic_ble_set_periodic_advertising_sync_transfer_params - btsnd_hcic_ble_set_periodic_advertising_sync_transfer_params; + btsnd_hcic_ble_set_periodic_advertising_sync_transfer_params; struct btsnd_hcic_ble_set_privacy_mode btsnd_hcic_ble_set_privacy_mode; -struct btsnd_hcic_ble_set_rand_priv_addr_timeout - btsnd_hcic_ble_set_rand_priv_addr_timeout; +struct btsnd_hcic_ble_set_rand_priv_addr_timeout btsnd_hcic_ble_set_rand_priv_addr_timeout; struct btsnd_hcic_ble_set_scan_enable btsnd_hcic_ble_set_scan_enable; struct btsnd_hcic_ble_set_scan_params btsnd_hcic_ble_set_scan_params; struct btsnd_hcic_ble_start_enc btsnd_hcic_ble_start_enc; @@ -103,25 +97,21 @@ namespace stack_hcic_hciblecmds {} // namespace stack_hcic_hciblecmds // Mocked functions, if any void btsnd_hci_ble_add_device_to_periodic_advertiser_list( - uint8_t adv_addr_type, const RawAddress& adv_addr, uint8_t adv_sid, - base::OnceCallback cb) { + uint8_t adv_addr_type, const RawAddress& adv_addr, uint8_t adv_sid, + base::OnceCallback cb) { inc_func_call_count(__func__); - test::mock::stack_hcic_hciblecmds:: - btsnd_hci_ble_add_device_to_periodic_advertiser_list( + test::mock::stack_hcic_hciblecmds::btsnd_hci_ble_add_device_to_periodic_advertiser_list( adv_addr_type, adv_addr, adv_sid, std::move(cb)); } -void btsnd_hci_ble_clear_periodic_advertiser_list( - base::OnceCallback cb) { +void btsnd_hci_ble_clear_periodic_advertiser_list(base::OnceCallback cb) { inc_func_call_count(__func__); - test::mock::stack_hcic_hciblecmds:: - btsnd_hci_ble_clear_periodic_advertiser_list(std::move(cb)); + test::mock::stack_hcic_hciblecmds::btsnd_hci_ble_clear_periodic_advertiser_list(std::move(cb)); } void btsnd_hci_ble_remove_device_from_periodic_advertiser_list( - uint8_t adv_addr_type, const RawAddress& adv_addr, uint8_t adv_sid, - base::OnceCallback cb) { + uint8_t adv_addr_type, const RawAddress& adv_addr, uint8_t adv_sid, + base::OnceCallback cb) { inc_func_call_count(__func__); - test::mock::stack_hcic_hciblecmds:: - btsnd_hci_ble_remove_device_from_periodic_advertiser_list( + test::mock::stack_hcic_hciblecmds::btsnd_hci_ble_remove_device_from_periodic_advertiser_list( adv_addr_type, adv_addr, adv_sid, std::move(cb)); } void btsnd_hcic_ble_ltk_req_neg_reply(uint16_t handle) { @@ -132,44 +122,39 @@ void btsnd_hcic_ble_ltk_req_reply(uint16_t handle, const Octet16& ltk) { inc_func_call_count(__func__); test::mock::stack_hcic_hciblecmds::btsnd_hcic_ble_ltk_req_reply(handle, ltk); } -void btsnd_hcic_ble_periodic_advertising_create_sync( - uint8_t options, uint8_t adv_sid, uint8_t adv_addr_type, - const RawAddress& adv_addr, uint16_t skip_num, uint16_t sync_timeout, - uint8_t sync_cte_type) { +void btsnd_hcic_ble_periodic_advertising_create_sync(uint8_t options, uint8_t adv_sid, + uint8_t adv_addr_type, + const RawAddress& adv_addr, uint16_t skip_num, + uint16_t sync_timeout, uint8_t sync_cte_type) { inc_func_call_count(__func__); - test::mock::stack_hcic_hciblecmds:: - btsnd_hcic_ble_periodic_advertising_create_sync( - options, adv_sid, adv_addr_type, adv_addr, skip_num, sync_timeout, - sync_cte_type); + test::mock::stack_hcic_hciblecmds::btsnd_hcic_ble_periodic_advertising_create_sync( + options, adv_sid, adv_addr_type, adv_addr, skip_num, sync_timeout, sync_cte_type); } void btsnd_hcic_ble_periodic_advertising_create_sync_cancel( - base::OnceCallback cb) { + base::OnceCallback cb) { inc_func_call_count(__func__); - test::mock::stack_hcic_hciblecmds:: - btsnd_hcic_ble_periodic_advertising_create_sync_cancel(std::move(cb)); + test::mock::stack_hcic_hciblecmds::btsnd_hcic_ble_periodic_advertising_create_sync_cancel( + std::move(cb)); } void btsnd_hcic_ble_periodic_advertising_set_info_transfer( - uint16_t conn_handle, uint16_t service_data, uint8_t adv_handle, - base::OnceCallback cb) { + uint16_t conn_handle, uint16_t service_data, uint8_t adv_handle, + base::OnceCallback cb) { inc_func_call_count(__func__); - test::mock::stack_hcic_hciblecmds:: - btsnd_hcic_ble_periodic_advertising_set_info_transfer( + test::mock::stack_hcic_hciblecmds::btsnd_hcic_ble_periodic_advertising_set_info_transfer( conn_handle, service_data, adv_handle, std::move(cb)); } void btsnd_hcic_ble_periodic_advertising_sync_transfer( - uint16_t conn_handle, uint16_t service_data, uint16_t sync_handle, - base::OnceCallback cb) { + uint16_t conn_handle, uint16_t service_data, uint16_t sync_handle, + base::OnceCallback cb) { inc_func_call_count(__func__); - test::mock::stack_hcic_hciblecmds:: - btsnd_hcic_ble_periodic_advertising_sync_transfer( + test::mock::stack_hcic_hciblecmds::btsnd_hcic_ble_periodic_advertising_sync_transfer( conn_handle, service_data, sync_handle, std::move(cb)); } void btsnd_hcic_ble_periodic_advertising_terminate_sync( - uint16_t sync_handle, base::OnceCallback cb) { + uint16_t sync_handle, base::OnceCallback cb) { inc_func_call_count(__func__); - test::mock::stack_hcic_hciblecmds:: - btsnd_hcic_ble_periodic_advertising_terminate_sync(sync_handle, - std::move(cb)); + test::mock::stack_hcic_hciblecmds::btsnd_hcic_ble_periodic_advertising_terminate_sync( + sync_handle, std::move(cb)); } void btsnd_hcic_ble_rand(base::Callback cb) { inc_func_call_count(__func__); @@ -183,11 +168,10 @@ void btsnd_hcic_ble_read_remote_feat(uint16_t handle) { inc_func_call_count(__func__); test::mock::stack_hcic_hciblecmds::btsnd_hcic_ble_read_remote_feat(handle); } -void btsnd_hcic_ble_read_resolvable_addr_peer(uint8_t addr_type_peer, - const RawAddress& bda_peer) { +void btsnd_hcic_ble_read_resolvable_addr_peer(uint8_t addr_type_peer, const RawAddress& bda_peer) { inc_func_call_count(__func__); - test::mock::stack_hcic_hciblecmds::btsnd_hcic_ble_read_resolvable_addr_peer( - addr_type_peer, bda_peer); + test::mock::stack_hcic_hciblecmds::btsnd_hcic_ble_read_resolvable_addr_peer(addr_type_peer, + bda_peer); } void btsnd_hcic_ble_receiver_test(uint8_t rx_freq) { inc_func_call_count(__func__); @@ -195,173 +179,146 @@ void btsnd_hcic_ble_receiver_test(uint8_t rx_freq) { } void btsnd_hcic_ble_set_adv_data(uint8_t data_len, uint8_t* p_data) { inc_func_call_count(__func__); - test::mock::stack_hcic_hciblecmds::btsnd_hcic_ble_set_adv_data(data_len, - p_data); + test::mock::stack_hcic_hciblecmds::btsnd_hcic_ble_set_adv_data(data_len, p_data); } void btsnd_hcic_ble_set_adv_enable(uint8_t adv_enable) { inc_func_call_count(__func__); test::mock::stack_hcic_hciblecmds::btsnd_hcic_ble_set_adv_enable(adv_enable); } -void btsnd_hcic_ble_set_data_length(uint16_t conn_handle, uint16_t tx_octets, - uint16_t tx_time) { +void btsnd_hcic_ble_set_data_length(uint16_t conn_handle, uint16_t tx_octets, uint16_t tx_time) { inc_func_call_count(__func__); - test::mock::stack_hcic_hciblecmds::btsnd_hcic_ble_set_data_length( - conn_handle, tx_octets, tx_time); + test::mock::stack_hcic_hciblecmds::btsnd_hcic_ble_set_data_length(conn_handle, tx_octets, + tx_time); } void btsnd_hcic_ble_set_default_periodic_advertising_sync_transfer_params( - uint16_t conn_handle, uint8_t mode, uint16_t skip, uint16_t sync_timeout, - uint8_t cte_type, base::OnceCallback cb) { + uint16_t conn_handle, uint8_t mode, uint16_t skip, uint16_t sync_timeout, uint8_t cte_type, + base::OnceCallback cb) { inc_func_call_count(__func__); test::mock::stack_hcic_hciblecmds:: - btsnd_hcic_ble_set_default_periodic_advertising_sync_transfer_params( - conn_handle, mode, skip, sync_timeout, cte_type, std::move(cb)); + btsnd_hcic_ble_set_default_periodic_advertising_sync_transfer_params( + conn_handle, mode, skip, sync_timeout, cte_type, std::move(cb)); } -void btsnd_hcic_ble_set_extended_scan_enable(uint8_t enable, - uint8_t filter_duplicates, - uint16_t duration, - uint16_t period) { +void btsnd_hcic_ble_set_extended_scan_enable(uint8_t enable, uint8_t filter_duplicates, + uint16_t duration, uint16_t period) { inc_func_call_count(__func__); test::mock::stack_hcic_hciblecmds::btsnd_hcic_ble_set_extended_scan_enable( - enable, filter_duplicates, duration, period); + enable, filter_duplicates, duration, period); } void btsnd_hcic_ble_set_extended_scan_params(uint8_t own_address_type, - uint8_t scanning_filter_policy, - uint8_t scanning_phys, + uint8_t scanning_filter_policy, uint8_t scanning_phys, scanning_phy_cfg* phy_cfg) { inc_func_call_count(__func__); test::mock::stack_hcic_hciblecmds::btsnd_hcic_ble_set_extended_scan_params( - own_address_type, scanning_filter_policy, scanning_phys, phy_cfg); + own_address_type, scanning_filter_policy, scanning_phys, phy_cfg); } void btsnd_hcic_ble_set_periodic_advertising_receive_enable( - uint16_t sync_handle, bool enable, - base::OnceCallback cb) { + uint16_t sync_handle, bool enable, base::OnceCallback cb) { inc_func_call_count(__func__); - test::mock::stack_hcic_hciblecmds:: - btsnd_hcic_ble_set_periodic_advertising_receive_enable( + test::mock::stack_hcic_hciblecmds::btsnd_hcic_ble_set_periodic_advertising_receive_enable( sync_handle, enable, std::move(cb)); } void btsnd_hcic_ble_set_periodic_advertising_sync_transfer_params( - uint16_t conn_handle, uint8_t mode, uint16_t skip, uint16_t sync_timeout, - uint8_t cte_type, base::OnceCallback cb) { + uint16_t conn_handle, uint8_t mode, uint16_t skip, uint16_t sync_timeout, uint8_t cte_type, + base::OnceCallback cb) { inc_func_call_count(__func__); - test::mock::stack_hcic_hciblecmds:: - btsnd_hcic_ble_set_periodic_advertising_sync_transfer_params( + test::mock::stack_hcic_hciblecmds::btsnd_hcic_ble_set_periodic_advertising_sync_transfer_params( conn_handle, mode, skip, sync_timeout, cte_type, std::move(cb)); } -void btsnd_hcic_ble_set_privacy_mode(uint8_t addr_type_peer, - const RawAddress& bda_peer, +void btsnd_hcic_ble_set_privacy_mode(uint8_t addr_type_peer, const RawAddress& bda_peer, uint8_t privacy_type) { inc_func_call_count(__func__); - test::mock::stack_hcic_hciblecmds::btsnd_hcic_ble_set_privacy_mode( - addr_type_peer, bda_peer, privacy_type); + test::mock::stack_hcic_hciblecmds::btsnd_hcic_ble_set_privacy_mode(addr_type_peer, bda_peer, + privacy_type); } -void btsnd_hcic_ble_set_rand_priv_addr_timeout(uint16_t rpa_timout) { +void btsnd_hcic_ble_set_rand_priv_addr_timeout(uint16_t rpa_timeout) { inc_func_call_count(__func__); - test::mock::stack_hcic_hciblecmds::btsnd_hcic_ble_set_rand_priv_addr_timeout( - rpa_timout); + test::mock::stack_hcic_hciblecmds::btsnd_hcic_ble_set_rand_priv_addr_timeout(rpa_timeout); } void btsnd_hcic_ble_set_scan_enable(uint8_t scan_enable, uint8_t duplicate) { inc_func_call_count(__func__); - test::mock::stack_hcic_hciblecmds::btsnd_hcic_ble_set_scan_enable(scan_enable, - duplicate); + test::mock::stack_hcic_hciblecmds::btsnd_hcic_ble_set_scan_enable(scan_enable, duplicate); } -void btsnd_hcic_ble_set_scan_params(uint8_t scan_type, uint16_t scan_int, - uint16_t scan_win, uint8_t addr_type_own, - uint8_t scan_filter_policy) { +void btsnd_hcic_ble_set_scan_params(uint8_t scan_type, uint16_t scan_int, uint16_t scan_win, + uint8_t addr_type_own, uint8_t scan_filter_policy) { inc_func_call_count(__func__); test::mock::stack_hcic_hciblecmds::btsnd_hcic_ble_set_scan_params( - scan_type, scan_int, scan_win, addr_type_own, scan_filter_policy); + scan_type, scan_int, scan_win, addr_type_own, scan_filter_policy); } -void btsnd_hcic_ble_start_enc(uint16_t handle, - uint8_t rand[HCIC_BLE_RAND_DI_SIZE], - uint16_t ediv, const Octet16& ltk) { +void btsnd_hcic_ble_start_enc(uint16_t handle, uint8_t rand[HCIC_BLE_RAND_DI_SIZE], uint16_t ediv, + const Octet16& ltk) { inc_func_call_count(__func__); - test::mock::stack_hcic_hciblecmds::btsnd_hcic_ble_start_enc(handle, rand, - ediv, ltk); + test::mock::stack_hcic_hciblecmds::btsnd_hcic_ble_start_enc(handle, rand, ediv, ltk); } void btsnd_hcic_ble_test_end(void) { inc_func_call_count(__func__); test::mock::stack_hcic_hciblecmds::btsnd_hcic_ble_test_end(); } -void btsnd_hcic_ble_transmitter_test(uint8_t tx_freq, uint8_t test_data_len, - uint8_t payload) { +void btsnd_hcic_ble_transmitter_test(uint8_t tx_freq, uint8_t test_data_len, uint8_t payload) { inc_func_call_count(__func__); - test::mock::stack_hcic_hciblecmds::btsnd_hcic_ble_transmitter_test( - tx_freq, test_data_len, payload); + test::mock::stack_hcic_hciblecmds::btsnd_hcic_ble_transmitter_test(tx_freq, test_data_len, + payload); } -void btsnd_hcic_ble_write_adv_params(uint16_t adv_int_min, uint16_t adv_int_max, - uint8_t adv_type, - tBLE_ADDR_TYPE addr_type_own, - tBLE_ADDR_TYPE addr_type_dir, - const RawAddress& direct_bda, - uint8_t channel_map, +void btsnd_hcic_ble_write_adv_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type, + tBLE_ADDR_TYPE addr_type_own, tBLE_ADDR_TYPE addr_type_dir, + const RawAddress& direct_bda, uint8_t channel_map, uint8_t adv_filter_policy) { inc_func_call_count(__func__); test::mock::stack_hcic_hciblecmds::btsnd_hcic_ble_write_adv_params( - adv_int_min, adv_int_max, adv_type, addr_type_own, addr_type_dir, - direct_bda, channel_map, adv_filter_policy); -} -void btsnd_hcic_create_big(uint8_t big_handle, uint8_t adv_handle, - uint8_t num_bis, uint32_t sdu_itv, - uint16_t max_sdu_size, uint16_t transport_latency, - uint8_t rtn, uint8_t phy, uint8_t packing, - uint8_t framing, uint8_t enc, + adv_int_min, adv_int_max, adv_type, addr_type_own, addr_type_dir, direct_bda, channel_map, + adv_filter_policy); +} +void btsnd_hcic_create_big(uint8_t big_handle, uint8_t adv_handle, uint8_t num_bis, + uint32_t sdu_itv, uint16_t max_sdu_size, uint16_t transport_latency, + uint8_t rtn, uint8_t phy, uint8_t packing, uint8_t framing, uint8_t enc, std::array bcst_code) { inc_func_call_count(__func__); - test::mock::stack_hcic_hciblecmds::btsnd_hcic_create_big( - big_handle, adv_handle, num_bis, sdu_itv, max_sdu_size, transport_latency, - rtn, phy, packing, framing, enc, bcst_code); + test::mock::stack_hcic_hciblecmds::btsnd_hcic_create_big(big_handle, adv_handle, num_bis, sdu_itv, + max_sdu_size, transport_latency, rtn, + phy, packing, framing, enc, bcst_code); } void btsnd_hcic_create_cis(uint8_t num_cis, const EXT_CIS_CREATE_CFG* cis_cfg, base::OnceCallback cb) { inc_func_call_count(__func__); - test::mock::stack_hcic_hciblecmds::btsnd_hcic_create_cis(num_cis, cis_cfg, - std::move(cb)); + test::mock::stack_hcic_hciblecmds::btsnd_hcic_create_cis(num_cis, cis_cfg, std::move(cb)); } -void btsnd_hcic_read_iso_link_quality( - uint16_t iso_handle, base::OnceCallback cb) { +void btsnd_hcic_read_iso_link_quality(uint16_t iso_handle, + base::OnceCallback cb) { inc_func_call_count(__func__); - test::mock::stack_hcic_hciblecmds::btsnd_hcic_read_iso_link_quality( - iso_handle, std::move(cb)); + test::mock::stack_hcic_hciblecmds::btsnd_hcic_read_iso_link_quality(iso_handle, std::move(cb)); } -void btsnd_hcic_remove_cig(uint8_t cig_id, - base::OnceCallback cb) { +void btsnd_hcic_remove_cig(uint8_t cig_id, base::OnceCallback cb) { inc_func_call_count(__func__); - test::mock::stack_hcic_hciblecmds::btsnd_hcic_remove_cig(cig_id, - std::move(cb)); + test::mock::stack_hcic_hciblecmds::btsnd_hcic_remove_cig(cig_id, std::move(cb)); } -void btsnd_hcic_remove_iso_data_path( - uint16_t iso_handle, uint8_t data_path_dir, - base::OnceCallback cb) { +void btsnd_hcic_remove_iso_data_path(uint16_t iso_handle, uint8_t data_path_dir, + base::OnceCallback cb) { inc_func_call_count(__func__); - test::mock::stack_hcic_hciblecmds::btsnd_hcic_remove_iso_data_path( - iso_handle, data_path_dir, std::move(cb)); + test::mock::stack_hcic_hciblecmds::btsnd_hcic_remove_iso_data_path(iso_handle, data_path_dir, + std::move(cb)); } void btsnd_hcic_req_peer_sca(uint16_t conn_handle) { inc_func_call_count(__func__); test::mock::stack_hcic_hciblecmds::btsnd_hcic_req_peer_sca(conn_handle); } -void btsnd_hcic_set_cig_params( - uint8_t cig_id, uint32_t sdu_itv_mtos, uint32_t sdu_itv_stom, uint8_t sca, - uint8_t packing, uint8_t framing, uint16_t max_trans_lat_stom, - uint16_t max_trans_lat_mtos, uint8_t cis_cnt, const EXT_CIS_CFG* cis_cfg, - base::OnceCallback cb) { +void btsnd_hcic_set_cig_params(uint8_t cig_id, uint32_t sdu_itv_mtos, uint32_t sdu_itv_stom, + uint8_t sca, uint8_t packing, uint8_t framing, + uint16_t max_trans_lat_stom, uint16_t max_trans_lat_mtos, + uint8_t cis_cnt, const EXT_CIS_CFG* cis_cfg, + base::OnceCallback cb) { inc_func_call_count(__func__); test::mock::stack_hcic_hciblecmds::btsnd_hcic_set_cig_params( - cig_id, sdu_itv_mtos, sdu_itv_stom, sca, packing, framing, - max_trans_lat_stom, max_trans_lat_mtos, cis_cnt, cis_cfg, std::move(cb)); + cig_id, sdu_itv_mtos, sdu_itv_stom, sca, packing, framing, max_trans_lat_stom, + max_trans_lat_mtos, cis_cnt, cis_cfg, std::move(cb)); } -void btsnd_hcic_setup_iso_data_path( - uint16_t iso_handle, uint8_t data_path_dir, uint8_t data_path_id, - uint8_t codec_id_format, uint16_t codec_id_company, - uint16_t codec_id_vendor, uint32_t controller_delay, - std::vector codec_conf, - base::OnceCallback cb) { +void btsnd_hcic_setup_iso_data_path(uint16_t iso_handle, uint8_t data_path_dir, + uint8_t data_path_id, uint8_t codec_id_format, + uint16_t codec_id_company, uint16_t codec_id_vendor, + uint32_t controller_delay, std::vector codec_conf, + base::OnceCallback cb) { inc_func_call_count(__func__); test::mock::stack_hcic_hciblecmds::btsnd_hcic_setup_iso_data_path( - iso_handle, data_path_dir, data_path_id, codec_id_format, - codec_id_company, codec_id_vendor, controller_delay, codec_conf, - std::move(cb)); + iso_handle, data_path_dir, data_path_id, codec_id_format, codec_id_company, + codec_id_vendor, controller_delay, codec_conf, std::move(cb)); } void btsnd_hcic_term_big(uint8_t big_handle, uint8_t reason) { inc_func_call_count(__func__); diff --git a/system/test/mock/mock_stack_hcic_hciblecmds.h b/system/test/mock/mock_stack_hcic_hciblecmds.h index fb008bacce9..c9855165f16 100644 --- a/system/test/mock/mock_stack_hcic_hciblecmds.h +++ b/system/test/mock/mock_stack_hcic_hciblecmds.h @@ -45,30 +45,26 @@ namespace stack_hcic_hciblecmds { struct btsnd_hci_ble_add_device_to_periodic_advertiser_list { std::function)> - body{[](uint8_t /* adv_addr_type */, const RawAddress& /* adv_addr */, - uint8_t /* adv_sid */, - base::OnceCallback /* cb */) {}}; - void operator()(uint8_t adv_addr_type, const RawAddress& adv_addr, - uint8_t adv_sid, + body{[](uint8_t /* adv_addr_type */, const RawAddress& /* adv_addr */, + uint8_t /* adv_sid */, base::OnceCallback /* cb */) {}}; + void operator()(uint8_t adv_addr_type, const RawAddress& adv_addr, uint8_t adv_sid, base::OnceCallback cb) { body(adv_addr_type, adv_addr, adv_sid, std::move(cb)); - }; + } }; extern struct btsnd_hci_ble_add_device_to_periodic_advertiser_list - btsnd_hci_ble_add_device_to_periodic_advertiser_list; + btsnd_hci_ble_add_device_to_periodic_advertiser_list; // Name: btsnd_hci_ble_clear_periodic_advertiser_list // Params: base::OnceCallback)> body{ - [](base::OnceCallback) {}}; - void operator()(base::OnceCallback cb) { - body(std::move(cb)); - }; + [](base::OnceCallback) {}}; + void operator()(base::OnceCallback cb) { body(std::move(cb)); } }; extern struct btsnd_hci_ble_clear_periodic_advertiser_list - btsnd_hci_ble_clear_periodic_advertiser_list; + btsnd_hci_ble_clear_periodic_advertiser_list; // Name: btsnd_hci_ble_remove_device_from_periodic_advertiser_list // Params: uint8_t adv_addr_type, const RawAddress& adv_addr, uint8_t adv_sid, @@ -76,51 +72,46 @@ extern struct btsnd_hci_ble_clear_periodic_advertiser_list struct btsnd_hci_ble_remove_device_from_periodic_advertiser_list { std::function)> - body{[](uint8_t /* adv_addr_type */, const RawAddress& /* adv_addr */, - uint8_t /* adv_sid */, - base::OnceCallback /* cb */) {}}; - void operator()(uint8_t adv_addr_type, const RawAddress& adv_addr, - uint8_t adv_sid, + body{[](uint8_t /* adv_addr_type */, const RawAddress& /* adv_addr */, + uint8_t /* adv_sid */, base::OnceCallback /* cb */) {}}; + void operator()(uint8_t adv_addr_type, const RawAddress& adv_addr, uint8_t adv_sid, base::OnceCallback cb) { body(adv_addr_type, adv_addr, adv_sid, std::move(cb)); - }; + } }; extern struct btsnd_hci_ble_remove_device_from_periodic_advertiser_list - btsnd_hci_ble_remove_device_from_periodic_advertiser_list; + btsnd_hci_ble_remove_device_from_periodic_advertiser_list; // Name: btsnd_hcic_ble_add_device_resolving_list // Params: uint8_t addr_type_peer, const RawAddress& bda_peer, const Octet16& // irk_peer, const Octet16& irk_local Return: void struct btsnd_hcic_ble_add_device_resolving_list { - std::function - body{[](uint8_t /* addr_type_peer */, const RawAddress& /* bda_peer */, - const Octet16& /* irk_peer */, - const Octet16& /* irk_local */) {}}; - void operator()(uint8_t addr_type_peer, const RawAddress& bda_peer, - const Octet16& irk_peer, const Octet16& irk_local) { + std::function + body{[](uint8_t /* addr_type_peer */, const RawAddress& /* bda_peer */, + const Octet16& /* irk_peer */, const Octet16& /* irk_local */) {}}; + void operator()(uint8_t addr_type_peer, const RawAddress& bda_peer, const Octet16& irk_peer, + const Octet16& irk_local) { body(addr_type_peer, bda_peer, irk_peer, irk_local); - }; + } }; -extern struct btsnd_hcic_ble_add_device_resolving_list - btsnd_hcic_ble_add_device_resolving_list; +extern struct btsnd_hcic_ble_add_device_resolving_list btsnd_hcic_ble_add_device_resolving_list; // Name: btsnd_hcic_ble_clear_resolving_list // Params: void // Return: void struct btsnd_hcic_ble_clear_resolving_list { std::function body{[](void) {}}; - void operator()(void) { body(); }; + void operator()(void) { body(); } }; -extern struct btsnd_hcic_ble_clear_resolving_list - btsnd_hcic_ble_clear_resolving_list; +extern struct btsnd_hcic_ble_clear_resolving_list btsnd_hcic_ble_clear_resolving_list; // Name: btsnd_hcic_ble_ltk_req_neg_reply // Params: uint16_t handle // Return: void struct btsnd_hcic_ble_ltk_req_neg_reply { std::function body{[](uint16_t /* handle */) {}}; - void operator()(uint16_t handle) { body(handle); }; + void operator()(uint16_t handle) { body(handle); } }; extern struct btsnd_hcic_ble_ltk_req_neg_reply btsnd_hcic_ble_ltk_req_neg_reply; @@ -129,8 +120,8 @@ extern struct btsnd_hcic_ble_ltk_req_neg_reply btsnd_hcic_ble_ltk_req_neg_reply; // Return: void struct btsnd_hcic_ble_ltk_req_reply { std::function body{ - [](uint16_t /* handle */, const Octet16& /* ltk */) {}}; - void operator()(uint16_t handle, const Octet16& ltk) { body(handle, ltk); }; + [](uint16_t /* handle */, const Octet16& /* ltk */) {}}; + void operator()(uint16_t handle, const Octet16& ltk) { body(handle, ltk); } }; extern struct btsnd_hcic_ble_ltk_req_reply btsnd_hcic_ble_ltk_req_reply; @@ -140,93 +131,82 @@ extern struct btsnd_hcic_ble_ltk_req_reply btsnd_hcic_ble_ltk_req_reply; // sync_cte_type Return: void struct btsnd_hcic_ble_periodic_advertising_create_sync { std::function - body{[](uint8_t /* options */, uint8_t /* adv_sid */, - uint8_t /* adv_addr_type */, const RawAddress& /* adv_addr */, - uint16_t /* skip_num */, uint16_t /* sync_timeout */, - uint8_t /* sync_cte_type */) {}}; + const RawAddress& adv_addr, uint16_t skip_num, uint16_t sync_timeout, + uint8_t sync_cte_type)> + body{[](uint8_t /* options */, uint8_t /* adv_sid */, uint8_t /* adv_addr_type */, + const RawAddress& /* adv_addr */, uint16_t /* skip_num */, + uint16_t /* sync_timeout */, uint8_t /* sync_cte_type */) {}}; void operator()(uint8_t options, uint8_t adv_sid, uint8_t adv_addr_type, - const RawAddress& adv_addr, uint16_t skip_num, - uint16_t sync_timeout, uint8_t sync_cte_type) { - body(options, adv_sid, adv_addr_type, adv_addr, skip_num, sync_timeout, - sync_cte_type); - }; + const RawAddress& adv_addr, uint16_t skip_num, uint16_t sync_timeout, + uint8_t sync_cte_type) { + body(options, adv_sid, adv_addr_type, adv_addr, skip_num, sync_timeout, sync_cte_type); + } }; extern struct btsnd_hcic_ble_periodic_advertising_create_sync - btsnd_hcic_ble_periodic_advertising_create_sync; + btsnd_hcic_ble_periodic_advertising_create_sync; // Name: btsnd_hcic_ble_periodic_advertising_create_sync_cancel // Params: base::OnceCallback)> body{ - [](base::OnceCallback /* cb */) {}}; - void operator()(base::OnceCallback cb) { - body(std::move(cb)); - }; + [](base::OnceCallback /* cb */) {}}; + void operator()(base::OnceCallback cb) { body(std::move(cb)); } }; extern struct btsnd_hcic_ble_periodic_advertising_create_sync_cancel - btsnd_hcic_ble_periodic_advertising_create_sync_cancel; + btsnd_hcic_ble_periodic_advertising_create_sync_cancel; // Name: btsnd_hcic_ble_periodic_advertising_set_info_transfer // Params: uint16_t conn_handle, uint16_t service_data, uint8_t adv_handle, // base::OnceCallback)> - body{[](uint16_t /* conn_handle */, uint16_t /* service_data */, - uint8_t /* adv_handle */, - base::OnceCallback /* cb */) {}}; - void operator()(uint16_t conn_handle, uint16_t service_data, - uint8_t adv_handle, + std::function)> + body{[](uint16_t /* conn_handle */, uint16_t /* service_data */, uint8_t /* adv_handle */, + base::OnceCallback /* cb */) {}}; + void operator()(uint16_t conn_handle, uint16_t service_data, uint8_t adv_handle, base::OnceCallback cb) { body(conn_handle, service_data, adv_handle, std::move(cb)); - }; + } }; extern struct btsnd_hcic_ble_periodic_advertising_set_info_transfer - btsnd_hcic_ble_periodic_advertising_set_info_transfer; + btsnd_hcic_ble_periodic_advertising_set_info_transfer; // Name: btsnd_hcic_ble_periodic_advertising_sync_transfer // Params: uint16_t conn_handle, uint16_t service_data, uint16_t sync_handle, // base::OnceCallback)> - body{[](uint16_t /* conn_handle */, uint16_t /* service_data */, - uint16_t /* sync_handle */, - base::OnceCallback /* cb */) {}}; - void operator()(uint16_t conn_handle, uint16_t service_data, - uint16_t sync_handle, + std::function)> + body{[](uint16_t /* conn_handle */, uint16_t /* service_data */, + uint16_t /* sync_handle */, + base::OnceCallback /* cb */) {}}; + void operator()(uint16_t conn_handle, uint16_t service_data, uint16_t sync_handle, base::OnceCallback cb) { body(conn_handle, service_data, sync_handle, std::move(cb)); - }; + } }; extern struct btsnd_hcic_ble_periodic_advertising_sync_transfer - btsnd_hcic_ble_periodic_advertising_sync_transfer; + btsnd_hcic_ble_periodic_advertising_sync_transfer; // Name: btsnd_hcic_ble_periodic_advertising_terminate_sync // Params: uint16_t sync_handle, base::OnceCallback)> - body{[](uint16_t /* sync_handle */, - base::OnceCallback /* cb */) {}}; - void operator()(uint16_t sync_handle, - base::OnceCallback cb) { + std::function)> body{ + [](uint16_t /* sync_handle */, base::OnceCallback /* cb */) {}}; + void operator()(uint16_t sync_handle, base::OnceCallback cb) { body(sync_handle, std::move(cb)); - }; + } }; extern struct btsnd_hcic_ble_periodic_advertising_terminate_sync - btsnd_hcic_ble_periodic_advertising_terminate_sync; + btsnd_hcic_ble_periodic_advertising_terminate_sync; // Name: btsnd_hcic_ble_rand // Params: base::Callback)> body{ - [](base::Callback /* cb */) {}}; - void operator()(base::Callback cb) { body(std::move(cb)); }; + [](base::Callback /* cb */) {}}; + void operator()(base::Callback cb) { body(std::move(cb)); } }; extern struct btsnd_hcic_ble_rand btsnd_hcic_ble_rand; @@ -235,17 +215,16 @@ extern struct btsnd_hcic_ble_rand btsnd_hcic_ble_rand; // Return: void struct btsnd_hcic_ble_read_adv_chnl_tx_power { std::function body{[](void) {}}; - void operator()(void) { body(); }; + void operator()(void) { body(); } }; -extern struct btsnd_hcic_ble_read_adv_chnl_tx_power - btsnd_hcic_ble_read_adv_chnl_tx_power; +extern struct btsnd_hcic_ble_read_adv_chnl_tx_power btsnd_hcic_ble_read_adv_chnl_tx_power; // Name: btsnd_hcic_ble_read_remote_feat // Params: uint16_t handle // Return: void struct btsnd_hcic_ble_read_remote_feat { std::function body{[](uint16_t /* handle */) {}}; - void operator()(uint16_t handle) { body(handle); }; + void operator()(uint16_t handle) { body(handle); } }; extern struct btsnd_hcic_ble_read_remote_feat btsnd_hcic_ble_read_remote_feat; @@ -254,20 +233,19 @@ extern struct btsnd_hcic_ble_read_remote_feat btsnd_hcic_ble_read_remote_feat; // Return: void struct btsnd_hcic_ble_read_resolvable_addr_peer { std::function body{ - [](uint8_t /* addr_type_peer */, const RawAddress& /* bda_peer */) {}}; + [](uint8_t /* addr_type_peer */, const RawAddress& /* bda_peer */) {}}; void operator()(uint8_t addr_type_peer, const RawAddress& bda_peer) { body(addr_type_peer, bda_peer); - }; + } }; -extern struct btsnd_hcic_ble_read_resolvable_addr_peer - btsnd_hcic_ble_read_resolvable_addr_peer; +extern struct btsnd_hcic_ble_read_resolvable_addr_peer btsnd_hcic_ble_read_resolvable_addr_peer; // Name: btsnd_hcic_ble_receiver_test // Params: uint8_t rx_freq // Return: void struct btsnd_hcic_ble_receiver_test { std::function body{[](uint8_t /* rx_freq */) {}}; - void operator()(uint8_t rx_freq) { body(rx_freq); }; + void operator()(uint8_t rx_freq) { body(rx_freq); } }; extern struct btsnd_hcic_ble_receiver_test btsnd_hcic_ble_receiver_test; @@ -276,23 +254,20 @@ extern struct btsnd_hcic_ble_receiver_test btsnd_hcic_ble_receiver_test; // Return: void struct btsnd_hcic_ble_rm_device_resolving_list { std::function body{ - [](uint8_t /* addr_type_peer */, const RawAddress& /* bda_peer */) {}}; + [](uint8_t /* addr_type_peer */, const RawAddress& /* bda_peer */) {}}; void operator()(uint8_t addr_type_peer, const RawAddress& bda_peer) { body(addr_type_peer, bda_peer); - }; + } }; -extern struct btsnd_hcic_ble_rm_device_resolving_list - btsnd_hcic_ble_rm_device_resolving_list; +extern struct btsnd_hcic_ble_rm_device_resolving_list btsnd_hcic_ble_rm_device_resolving_list; // Name: btsnd_hcic_ble_set_adv_data // Params: uint8_t data_len, uint8_t* p_data // Return: void struct btsnd_hcic_ble_set_adv_data { std::function body{ - [](uint8_t /* data_len */, uint8_t* /* p_data */) {}}; - void operator()(uint8_t data_len, uint8_t* p_data) { - body(data_len, p_data); - }; + [](uint8_t /* data_len */, uint8_t* /* p_data */) {}}; + void operator()(uint8_t data_len, uint8_t* p_data) { body(data_len, p_data); } }; extern struct btsnd_hcic_ble_set_adv_data btsnd_hcic_ble_set_adv_data; @@ -301,7 +276,7 @@ extern struct btsnd_hcic_ble_set_adv_data btsnd_hcic_ble_set_adv_data; // Return: void struct btsnd_hcic_ble_set_adv_enable { std::function body{[](uint8_t /* adv_enable */) {}}; - void operator()(uint8_t adv_enable) { body(adv_enable); }; + void operator()(uint8_t adv_enable) { body(adv_enable); } }; extern struct btsnd_hcic_ble_set_adv_enable btsnd_hcic_ble_set_adv_enable; @@ -309,13 +284,11 @@ extern struct btsnd_hcic_ble_set_adv_enable btsnd_hcic_ble_set_adv_enable; // Params: uint16_t conn_handle, uint16_t tx_octets, uint16_t tx_time // Return: void struct btsnd_hcic_ble_set_data_length { - std::function - body{[](uint16_t /* conn_handle */, uint16_t /* tx_octets */, - uint16_t /* tx_time */) {}}; + std::function body{ + [](uint16_t /* conn_handle */, uint16_t /* tx_octets */, uint16_t /* tx_time */) {}}; void operator()(uint16_t conn_handle, uint16_t tx_octets, uint16_t tx_time) { body(conn_handle, tx_octets, tx_time); - }; + } }; extern struct btsnd_hcic_ble_set_data_length btsnd_hcic_ble_set_data_length; @@ -326,35 +299,29 @@ extern struct btsnd_hcic_ble_set_data_length btsnd_hcic_ble_set_data_length; struct btsnd_hcic_ble_set_default_periodic_advertising_sync_transfer_params { std::function)> - body{[](uint16_t /* conn_handle */, uint8_t /* mode */, - uint16_t /* skip */, uint16_t /* sync_timeout */, - uint8_t /* cte_type */, - base::OnceCallback /* cb */) {}}; - void operator()(uint16_t conn_handle, uint8_t mode, uint16_t skip, - uint16_t sync_timeout, uint8_t cte_type, - base::OnceCallback cb) { + body{[](uint16_t /* conn_handle */, uint8_t /* mode */, uint16_t /* skip */, + uint16_t /* sync_timeout */, uint8_t /* cte_type */, + base::OnceCallback /* cb */) {}}; + void operator()(uint16_t conn_handle, uint8_t mode, uint16_t skip, uint16_t sync_timeout, + uint8_t cte_type, base::OnceCallback cb) { body(conn_handle, mode, skip, sync_timeout, cte_type, std::move(cb)); - }; + } }; -extern struct - btsnd_hcic_ble_set_default_periodic_advertising_sync_transfer_params +extern struct btsnd_hcic_ble_set_default_periodic_advertising_sync_transfer_params btsnd_hcic_ble_set_default_periodic_advertising_sync_transfer_params; // Name: btsnd_hcic_ble_set_extended_scan_enable // Params: uint8_t enable, uint8_t filter_duplicates, uint16_t duration, // uint16_t period Return: void struct btsnd_hcic_ble_set_extended_scan_enable { - std::function - body{[](uint8_t /* enable */, uint8_t /* filter_duplicates */, - uint16_t /* duration */, uint16_t /* period */) {}}; - void operator()(uint8_t enable, uint8_t filter_duplicates, uint16_t duration, - uint16_t period) { + std::function + body{[](uint8_t /* enable */, uint8_t /* filter_duplicates */, uint16_t /* duration */, + uint16_t /* period */) {}}; + void operator()(uint8_t enable, uint8_t filter_duplicates, uint16_t duration, uint16_t period) { body(enable, filter_duplicates, duration, period); - }; + } }; -extern struct btsnd_hcic_ble_set_extended_scan_enable - btsnd_hcic_ble_set_extended_scan_enable; +extern struct btsnd_hcic_ble_set_extended_scan_enable btsnd_hcic_ble_set_extended_scan_enable; // Name: btsnd_hcic_ble_set_extended_scan_params // Params: uint8_t own_address_type, uint8_t scanning_filter_policy, uint8_t @@ -362,32 +329,29 @@ extern struct btsnd_hcic_ble_set_extended_scan_enable struct btsnd_hcic_ble_set_extended_scan_params { std::function - body{[](uint8_t /* own_address_type */, - uint8_t /* scanning_filter_policy */, uint8_t /* scanning_phys */, - scanning_phy_cfg* /* phy_cfg */) {}}; - void operator()(uint8_t own_address_type, uint8_t scanning_filter_policy, - uint8_t scanning_phys, scanning_phy_cfg* phy_cfg) { + body{[](uint8_t /* own_address_type */, uint8_t /* scanning_filter_policy */, + uint8_t /* scanning_phys */, scanning_phy_cfg* /* phy_cfg */) {}}; + void operator()(uint8_t own_address_type, uint8_t scanning_filter_policy, uint8_t scanning_phys, + scanning_phy_cfg* phy_cfg) { body(own_address_type, scanning_filter_policy, scanning_phys, phy_cfg); - }; + } }; -extern struct btsnd_hcic_ble_set_extended_scan_params - btsnd_hcic_ble_set_extended_scan_params; +extern struct btsnd_hcic_ble_set_extended_scan_params btsnd_hcic_ble_set_extended_scan_params; // Name: btsnd_hcic_ble_set_periodic_advertising_receive_enable // Params: uint16_t sync_handle, bool enable, base::OnceCallback)> - body{[](uint16_t /* sync_handle */, bool /* enable */, - base::OnceCallback /* cb */) {}}; + std::function)> body{ + [](uint16_t /* sync_handle */, bool /* enable */, + base::OnceCallback /* cb */) {}}; void operator()(uint16_t sync_handle, bool enable, base::OnceCallback cb) { body(sync_handle, enable, std::move(cb)); - }; + } }; extern struct btsnd_hcic_ble_set_periodic_advertising_receive_enable - btsnd_hcic_ble_set_periodic_advertising_receive_enable; + btsnd_hcic_ble_set_periodic_advertising_receive_enable; // Name: btsnd_hcic_ble_set_periodic_advertising_sync_transfer_params // Params: uint16_t conn_handle, uint8_t mode, uint16_t skip, uint16_t @@ -396,54 +360,46 @@ extern struct btsnd_hcic_ble_set_periodic_advertising_receive_enable struct btsnd_hcic_ble_set_periodic_advertising_sync_transfer_params { std::function)> - body{[](uint16_t /* conn_handle */, uint8_t /* mode */, - uint16_t /* skip */, uint16_t /* sync_timeout */, - uint8_t /* cte_type */, - base::OnceCallback /* cb */) {}}; - void operator()(uint16_t conn_handle, uint8_t mode, uint16_t skip, - uint16_t sync_timeout, uint8_t cte_type, - base::OnceCallback cb) { + body{[](uint16_t /* conn_handle */, uint8_t /* mode */, uint16_t /* skip */, + uint16_t /* sync_timeout */, uint8_t /* cte_type */, + base::OnceCallback /* cb */) {}}; + void operator()(uint16_t conn_handle, uint8_t mode, uint16_t skip, uint16_t sync_timeout, + uint8_t cte_type, base::OnceCallback cb) { body(conn_handle, mode, skip, sync_timeout, cte_type, std::move(cb)); - }; + } }; extern struct btsnd_hcic_ble_set_periodic_advertising_sync_transfer_params - btsnd_hcic_ble_set_periodic_advertising_sync_transfer_params; + btsnd_hcic_ble_set_periodic_advertising_sync_transfer_params; // Name: btsnd_hcic_ble_set_privacy_mode // Params: uint8_t addr_type_peer, const RawAddress& bda_peer, uint8_t // privacy_type Return: void struct btsnd_hcic_ble_set_privacy_mode { - std::function - body{[](uint8_t /* addr_type_peer */, const RawAddress& /* bda_peer */, - uint8_t /* privacy_type */) {}}; - void operator()(uint8_t addr_type_peer, const RawAddress& bda_peer, - uint8_t privacy_type) { + std::function + body{[](uint8_t /* addr_type_peer */, const RawAddress& /* bda_peer */, + uint8_t /* privacy_type */) {}}; + void operator()(uint8_t addr_type_peer, const RawAddress& bda_peer, uint8_t privacy_type) { body(addr_type_peer, bda_peer, privacy_type); - }; + } }; extern struct btsnd_hcic_ble_set_privacy_mode btsnd_hcic_ble_set_privacy_mode; // Name: btsnd_hcic_ble_set_rand_priv_addr_timeout -// Params: uint16_t rpa_timout +// Params: uint16_t rpa_timeout // Return: void struct btsnd_hcic_ble_set_rand_priv_addr_timeout { - std::function body{ - [](uint16_t /* rpa_timout */) {}}; - void operator()(uint16_t rpa_timout) { body(rpa_timout); }; + std::function body{[](uint16_t /* rpa_timeout */) {}}; + void operator()(uint16_t rpa_timeout) { body(rpa_timeout); } }; -extern struct btsnd_hcic_ble_set_rand_priv_addr_timeout - btsnd_hcic_ble_set_rand_priv_addr_timeout; +extern struct btsnd_hcic_ble_set_rand_priv_addr_timeout btsnd_hcic_ble_set_rand_priv_addr_timeout; // Name: btsnd_hcic_ble_set_scan_enable // Params: uint8_t scan_enable, uint8_t duplicate // Return: void struct btsnd_hcic_ble_set_scan_enable { std::function body{ - [](uint8_t /* scan_enable */, uint8_t /* duplicate */) {}}; - void operator()(uint8_t scan_enable, uint8_t duplicate) { - body(scan_enable, duplicate); - }; + [](uint8_t /* scan_enable */, uint8_t /* duplicate */) {}}; + void operator()(uint8_t scan_enable, uint8_t duplicate) { body(scan_enable, duplicate); } }; extern struct btsnd_hcic_ble_set_scan_enable btsnd_hcic_ble_set_scan_enable; @@ -451,15 +407,14 @@ extern struct btsnd_hcic_ble_set_scan_enable btsnd_hcic_ble_set_scan_enable; // Params: uint8_t scan_type, uint16_t scan_int, uint16_t scan_win, uint8_t // addr_type_own, uint8_t scan_filter_policy Return: void struct btsnd_hcic_ble_set_scan_params { - std::function - body{[](uint8_t /* scan_type */, uint16_t /* scan_int */, - uint16_t /* scan_win */, uint8_t /* addr_type_own */, - uint8_t /* scan_filter_policy */) {}}; - void operator()(uint8_t scan_type, uint16_t scan_int, uint16_t scan_win, - uint8_t addr_type_own, uint8_t scan_filter_policy) { + std::function + body{[](uint8_t /* scan_type */, uint16_t /* scan_int */, uint16_t /* scan_win */, + uint8_t /* addr_type_own */, uint8_t /* scan_filter_policy */) {}}; + void operator()(uint8_t scan_type, uint16_t scan_int, uint16_t scan_win, uint8_t addr_type_own, + uint8_t scan_filter_policy) { body(scan_type, scan_int, scan_win, addr_type_own, scan_filter_policy); - }; + } }; extern struct btsnd_hcic_ble_set_scan_params btsnd_hcic_ble_set_scan_params; @@ -467,14 +422,14 @@ extern struct btsnd_hcic_ble_set_scan_params btsnd_hcic_ble_set_scan_params; // Params: uint16_t handle, uint8_t rand[HCIC_BLE_RAND_DI_SIZE], uint16_t ediv, // const Octet16& ltk Return: void struct btsnd_hcic_ble_start_enc { - std::function - body{[](uint16_t /* handle */, uint8_t[HCIC_BLE_RAND_DI_SIZE] /* rand */, - uint16_t /* ediv */, const Octet16& /* ltk */) {}}; - void operator()(uint16_t handle, uint8_t rand[HCIC_BLE_RAND_DI_SIZE], - uint16_t ediv, const Octet16& ltk) { + std::function + body{[](uint16_t /* handle */, uint8_t[HCIC_BLE_RAND_DI_SIZE] /* rand */, + uint16_t /* ediv */, const Octet16& /* ltk */) {}}; + void operator()(uint16_t handle, uint8_t rand[HCIC_BLE_RAND_DI_SIZE], uint16_t ediv, + const Octet16& ltk) { body(handle, rand, ediv, ltk); - }; + } }; extern struct btsnd_hcic_ble_start_enc btsnd_hcic_ble_start_enc; @@ -483,7 +438,7 @@ extern struct btsnd_hcic_ble_start_enc btsnd_hcic_ble_start_enc; // Return: void struct btsnd_hcic_ble_test_end { std::function body{[](void) {}}; - void operator()(void) { body(); }; + void operator()(void) { body(); } }; extern struct btsnd_hcic_ble_test_end btsnd_hcic_ble_test_end; @@ -491,12 +446,11 @@ extern struct btsnd_hcic_ble_test_end btsnd_hcic_ble_test_end; // Params: uint8_t tx_freq, uint8_t test_data_len, uint8_t payload // Return: void struct btsnd_hcic_ble_transmitter_test { - std::function - body{[](uint8_t /* tx_freq */, uint8_t /* test_data_len */, - uint8_t /* payload */) {}}; + std::function body{ + [](uint8_t /* tx_freq */, uint8_t /* test_data_len */, uint8_t /* payload */) {}}; void operator()(uint8_t tx_freq, uint8_t test_data_len, uint8_t payload) { body(tx_freq, test_data_len, payload); - }; + } }; extern struct btsnd_hcic_ble_transmitter_test btsnd_hcic_ble_transmitter_test; @@ -505,22 +459,19 @@ extern struct btsnd_hcic_ble_transmitter_test btsnd_hcic_ble_transmitter_test; // tBLE_ADDR_TYPE addr_type_own, tBLE_ADDR_TYPE addr_type_dir, const RawAddress& // direct_bda, uint8_t channel_map, uint8_t adv_filter_policy Return: void struct btsnd_hcic_ble_write_adv_params { - std::function - body{[](uint16_t /* adv_int_min */, uint16_t /* adv_int_max */, - uint8_t /* adv_type */, tBLE_ADDR_TYPE /* addr_type_own */, - tBLE_ADDR_TYPE /* addr_type_dir */, - const RawAddress& /* direct_bda */, uint8_t /* channel_map */, - uint8_t /* adv_filter_policy */) {}}; + std::function + body{[](uint16_t /* adv_int_min */, uint16_t /* adv_int_max */, uint8_t /* adv_type */, + tBLE_ADDR_TYPE /* addr_type_own */, tBLE_ADDR_TYPE /* addr_type_dir */, + const RawAddress& /* direct_bda */, uint8_t /* channel_map */, + uint8_t /* adv_filter_policy */) {}}; void operator()(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type, tBLE_ADDR_TYPE addr_type_own, tBLE_ADDR_TYPE addr_type_dir, - const RawAddress& direct_bda, uint8_t channel_map, - uint8_t adv_filter_policy) { - body(adv_int_min, adv_int_max, adv_type, addr_type_own, addr_type_dir, - direct_bda, channel_map, adv_filter_policy); - }; + const RawAddress& direct_bda, uint8_t channel_map, uint8_t adv_filter_policy) { + body(adv_int_min, adv_int_max, adv_type, addr_type_own, addr_type_dir, direct_bda, channel_map, + adv_filter_policy); + } }; extern struct btsnd_hcic_ble_write_adv_params btsnd_hcic_ble_write_adv_params; @@ -530,25 +481,22 @@ extern struct btsnd_hcic_ble_write_adv_params btsnd_hcic_ble_write_adv_params; // uint8_t phy, uint8_t packing, uint8_t framing, uint8_t enc, // std::array bcst_code Return: void struct btsnd_hcic_create_big { - std::function bcst_code)> - body{[](uint8_t /* big_handle */, uint8_t /* adv_handle */, - uint8_t /* num_bis */, uint32_t /* sdu_itv */, - uint16_t /* max_sdu_size */, uint16_t /* transport_latency */, - uint8_t /* rtn */, uint8_t /* phy */, uint8_t /* packing */, - uint8_t /* framing */, uint8_t /* enc */, - std::array /* bcst_code */) {}}; - void operator()(uint8_t big_handle, uint8_t adv_handle, uint8_t num_bis, - uint32_t sdu_itv, uint16_t max_sdu_size, - uint16_t transport_latency, uint8_t rtn, uint8_t phy, + body{[](uint8_t /* big_handle */, uint8_t /* adv_handle */, uint8_t /* num_bis */, + uint32_t /* sdu_itv */, uint16_t /* max_sdu_size */, + uint16_t /* transport_latency */, uint8_t /* rtn */, uint8_t /* phy */, + uint8_t /* packing */, uint8_t /* framing */, uint8_t /* enc */, + std::array /* bcst_code */) {}}; + void operator()(uint8_t big_handle, uint8_t adv_handle, uint8_t num_bis, uint32_t sdu_itv, + uint16_t max_sdu_size, uint16_t transport_latency, uint8_t rtn, uint8_t phy, uint8_t packing, uint8_t framing, uint8_t enc, std::array bcst_code) { - body(big_handle, adv_handle, num_bis, sdu_itv, max_sdu_size, - transport_latency, rtn, phy, packing, framing, enc, bcst_code); - }; + body(big_handle, adv_handle, num_bis, sdu_itv, max_sdu_size, transport_latency, rtn, phy, + packing, framing, enc, bcst_code); + } }; extern struct btsnd_hcic_create_big btsnd_hcic_create_big; @@ -558,12 +506,12 @@ extern struct btsnd_hcic_create_big btsnd_hcic_create_big; struct btsnd_hcic_create_cis { std::function)> - body{[](uint8_t /* num_cis */, const EXT_CIS_CREATE_CFG* /* cis_cfg */, - base::OnceCallback /* cb */) {}}; + body{[](uint8_t /* num_cis */, const EXT_CIS_CREATE_CFG* /* cis_cfg */, + base::OnceCallback /* cb */) {}}; void operator()(uint8_t num_cis, const EXT_CIS_CREATE_CFG* cis_cfg, base::OnceCallback cb) { body(num_cis, cis_cfg, std::move(cb)); - }; + } }; extern struct btsnd_hcic_create_cis btsnd_hcic_create_cis; @@ -571,13 +519,11 @@ extern struct btsnd_hcic_create_cis btsnd_hcic_create_cis; // Params: uint16_t iso_handle, base::OnceCallback)> - body{[](uint16_t /* iso_handle */, - base::OnceCallback) {}}; - void operator()(uint16_t iso_handle, - base::OnceCallback cb) { + std::function)> body{ + [](uint16_t /* iso_handle */, base::OnceCallback) {}}; + void operator()(uint16_t iso_handle, base::OnceCallback cb) { body(iso_handle, std::move(cb)); - }; + } }; extern struct btsnd_hcic_read_iso_link_quality btsnd_hcic_read_iso_link_quality; @@ -585,13 +531,11 @@ extern struct btsnd_hcic_read_iso_link_quality btsnd_hcic_read_iso_link_quality; // Params: uint8_t cig_id, base::OnceCallback)> - body{[](uint8_t /* cig_id */, - base::OnceCallback /* cb */) {}}; - void operator()(uint8_t cig_id, - base::OnceCallback cb) { + std::function)> body{ + [](uint8_t /* cig_id */, base::OnceCallback /* cb */) {}}; + void operator()(uint8_t cig_id, base::OnceCallback cb) { body(cig_id, std::move(cb)); - }; + } }; extern struct btsnd_hcic_remove_cig btsnd_hcic_remove_cig; @@ -599,14 +543,13 @@ extern struct btsnd_hcic_remove_cig btsnd_hcic_remove_cig; // Params: uint16_t iso_handle, uint8_t data_path_dir, // base::OnceCallback)> - body{[](uint16_t /* iso_handle */, uint8_t /* data_path_dir */, - base::OnceCallback /* cb */) {}}; + std::function)> body{ + [](uint16_t /* iso_handle */, uint8_t /* data_path_dir */, + base::OnceCallback /* cb */) {}}; void operator()(uint16_t iso_handle, uint8_t data_path_dir, base::OnceCallback cb) { body(iso_handle, data_path_dir, std::move(cb)); - }; + } }; extern struct btsnd_hcic_remove_iso_data_path btsnd_hcic_remove_iso_data_path; @@ -615,7 +558,7 @@ extern struct btsnd_hcic_remove_iso_data_path btsnd_hcic_remove_iso_data_path; // Return: void struct btsnd_hcic_req_peer_sca { std::function body{[](uint16_t /* conn_handle */) {}}; - void operator()(uint16_t conn_handle) { body(conn_handle); }; + void operator()(uint16_t conn_handle) { body(conn_handle); } }; extern struct btsnd_hcic_req_peer_sca btsnd_hcic_req_peer_sca; @@ -625,25 +568,20 @@ extern struct btsnd_hcic_req_peer_sca btsnd_hcic_req_peer_sca; // max_trans_lat_mtos, uint8_t cis_cnt, const EXT_CIS_CFG* cis_cfg, // base::OnceCallback)> - body{[](uint8_t /* cig_id */, uint32_t /* sdu_itv_mtos */, - uint32_t /* sdu_itv_stom */, uint8_t /* sca */, - uint8_t /* packing */, uint8_t /* framing */, - uint16_t /* max_trans_lat_stom */, - uint16_t /* max_trans_lat_mtos */, uint8_t /* cis_cnt */, - const EXT_CIS_CFG* /* cis_cfg */, - base::OnceCallback /* cb */) {}}; - void operator()(uint8_t cig_id, uint32_t sdu_itv_mtos, uint32_t sdu_itv_stom, - uint8_t sca, uint8_t packing, uint8_t framing, - uint16_t max_trans_lat_stom, uint16_t max_trans_lat_mtos, - uint8_t cis_cnt, const EXT_CIS_CFG* cis_cfg, + std::function)> + body{[](uint8_t /* cig_id */, uint32_t /* sdu_itv_mtos */, uint32_t /* sdu_itv_stom */, + uint8_t /* sca */, uint8_t /* packing */, uint8_t /* framing */, + uint16_t /* max_trans_lat_stom */, uint16_t /* max_trans_lat_mtos */, + uint8_t /* cis_cnt */, const EXT_CIS_CFG* /* cis_cfg */, + base::OnceCallback /* cb */) {}}; + void operator()(uint8_t cig_id, uint32_t sdu_itv_mtos, uint32_t sdu_itv_stom, uint8_t sca, + uint8_t packing, uint8_t framing, uint16_t max_trans_lat_stom, + uint16_t max_trans_lat_mtos, uint8_t cis_cnt, const EXT_CIS_CFG* cis_cfg, base::OnceCallback cb) { - body(cig_id, sdu_itv_mtos, sdu_itv_stom, sca, packing, framing, - max_trans_lat_stom, max_trans_lat_mtos, cis_cnt, cis_cfg, - std::move(cb)); - }; + body(cig_id, sdu_itv_mtos, sdu_itv_stom, sca, packing, framing, max_trans_lat_stom, + max_trans_lat_mtos, cis_cnt, cis_cfg, std::move(cb)); + } }; extern struct btsnd_hcic_set_cig_params btsnd_hcic_set_cig_params; @@ -653,24 +591,20 @@ extern struct btsnd_hcic_set_cig_params btsnd_hcic_set_cig_params; // uint32_t controller_delay, std::vector codec_conf, // base::OnceCallback, - base::OnceCallback)> - body{[](uint16_t /* iso_handle */, uint8_t /* data_path_dir */, - uint8_t /* data_path_id */, uint8_t /* codec_id_format */, - uint16_t /* codec_id_company */, uint16_t /* codec_id_vendor */, - uint32_t /* controller_delay */, - std::vector /* codec_conf */, - base::OnceCallback /* cb */) {}}; - void operator()(uint16_t iso_handle, uint8_t data_path_dir, - uint8_t data_path_id, uint8_t codec_id_format, - uint16_t codec_id_company, uint16_t codec_id_vendor, + std::function, base::OnceCallback)> + body{[](uint16_t /* iso_handle */, uint8_t /* data_path_dir */, + uint8_t /* data_path_id */, uint8_t /* codec_id_format */, + uint16_t /* codec_id_company */, uint16_t /* codec_id_vendor */, + uint32_t /* controller_delay */, std::vector /* codec_conf */, + base::OnceCallback /* cb */) {}}; + void operator()(uint16_t iso_handle, uint8_t data_path_dir, uint8_t data_path_id, + uint8_t codec_id_format, uint16_t codec_id_company, uint16_t codec_id_vendor, uint32_t controller_delay, std::vector codec_conf, base::OnceCallback cb) { - body(iso_handle, data_path_dir, data_path_id, codec_id_format, - codec_id_company, codec_id_vendor, controller_delay, codec_conf, - std::move(cb)); - }; + body(iso_handle, data_path_dir, data_path_id, codec_id_format, codec_id_company, + codec_id_vendor, controller_delay, codec_conf, std::move(cb)); + } }; extern struct btsnd_hcic_setup_iso_data_path btsnd_hcic_setup_iso_data_path; @@ -678,11 +612,8 @@ extern struct btsnd_hcic_setup_iso_data_path btsnd_hcic_setup_iso_data_path; // Params: uint8_t big_handle, uint8_t reason // Return: void struct btsnd_hcic_term_big { - std::function body{ - [](uint8_t /* big_handle */, uint8_t /* reason */) {}}; - void operator()(uint8_t big_handle, uint8_t reason) { - body(big_handle, reason); - }; + std::function body{[](uint8_t /* big_handle */, uint8_t /* reason */) {}}; + void operator()(uint8_t big_handle, uint8_t reason) { body(big_handle, reason); } }; extern struct btsnd_hcic_term_big btsnd_hcic_term_big; diff --git a/system/test/mock/mock_stack_hcic_hcicmds.cc b/system/test/mock/mock_stack_hcic_hcicmds.cc index a3590bbf3bd..d3612ccb8db 100644 --- a/system/test/mock/mock_stack_hcic_hcicmds.cc +++ b/system/test/mock/mock_stack_hcic_hcicmds.cc @@ -41,9 +41,9 @@ struct btsnd_hcic_create_conn_cancel btsnd_hcic_create_conn_cancel; struct btsnd_hcic_delete_stored_key btsnd_hcic_delete_stored_key; struct btsnd_hcic_enable_test_mode btsnd_hcic_enable_test_mode; struct btsnd_hcic_enhanced_accept_synchronous_connection - btsnd_hcic_enhanced_accept_synchronous_connection; + btsnd_hcic_enhanced_accept_synchronous_connection; struct btsnd_hcic_enhanced_set_up_synchronous_connection - btsnd_hcic_enhanced_set_up_synchronous_connection; + btsnd_hcic_enhanced_set_up_synchronous_connection; struct btsnd_hcic_exit_park_mode btsnd_hcic_exit_park_mode; struct btsnd_hcic_exit_sniff_mode btsnd_hcic_exit_sniff_mode; struct btsnd_hcic_hold_mode btsnd_hcic_hold_mode; @@ -55,11 +55,9 @@ struct btsnd_hcic_park_mode btsnd_hcic_park_mode; struct btsnd_hcic_pin_code_neg_reply btsnd_hcic_pin_code_neg_reply; struct btsnd_hcic_pin_code_req_reply btsnd_hcic_pin_code_req_reply; struct btsnd_hcic_read_encryption_key_size btsnd_hcic_read_encryption_key_size; -struct btsnd_hcic_read_failed_contact_counter - btsnd_hcic_read_failed_contact_counter; +struct btsnd_hcic_read_failed_contact_counter btsnd_hcic_read_failed_contact_counter; struct btsnd_hcic_read_local_oob_data btsnd_hcic_read_local_oob_data; -struct btsnd_hcic_read_local_oob_extended_data - btsnd_hcic_read_local_oob_extended_data; +struct btsnd_hcic_read_local_oob_extended_data btsnd_hcic_read_local_oob_extended_data; struct btsnd_hcic_read_name btsnd_hcic_read_name; struct btsnd_hcic_read_rmt_clk_offset btsnd_hcic_read_rmt_clk_offset; struct btsnd_hcic_read_rssi btsnd_hcic_read_rssi; @@ -84,8 +82,7 @@ struct btsnd_hcic_write_auto_flush_tout btsnd_hcic_write_auto_flush_tout; struct btsnd_hcic_write_cur_iac_lap btsnd_hcic_write_cur_iac_lap; struct btsnd_hcic_write_def_policy_set btsnd_hcic_write_def_policy_set; struct btsnd_hcic_write_dev_class btsnd_hcic_write_dev_class; -struct btsnd_hcic_write_ext_inquiry_response - btsnd_hcic_write_ext_inquiry_response; +struct btsnd_hcic_write_ext_inquiry_response btsnd_hcic_write_ext_inquiry_response; struct btsnd_hcic_write_inqscan_cfg btsnd_hcic_write_inqscan_cfg; struct btsnd_hcic_write_inqscan_type btsnd_hcic_write_inqscan_type; struct btsnd_hcic_write_inquiry_mode btsnd_hcic_write_inquiry_mode; @@ -103,16 +100,14 @@ struct btsnd_hcic_write_voice_settings btsnd_hcic_write_voice_settings; } // namespace test // Mocked functions, if any -void btsnd_hcic_accept_esco_conn(const RawAddress& bd_addr, - uint32_t transmit_bandwidth, - uint32_t receive_bandwidth, - uint16_t max_latency, uint16_t content_fmt, - uint8_t retrans_effort, +void btsnd_hcic_accept_esco_conn(const RawAddress& bd_addr, uint32_t transmit_bandwidth, + uint32_t receive_bandwidth, uint16_t max_latency, + uint16_t content_fmt, uint8_t retrans_effort, uint16_t packet_types) { inc_func_call_count(__func__); test::mock::stack_hcic_hcicmds::btsnd_hcic_accept_esco_conn( - bd_addr, transmit_bandwidth, receive_bandwidth, max_latency, content_fmt, - retrans_effort, packet_types); + bd_addr, transmit_bandwidth, receive_bandwidth, max_latency, content_fmt, retrans_effort, + packet_types); } void btsnd_hcic_add_SCO_conn(uint16_t handle, uint16_t packet_types) { inc_func_call_count(__func__); @@ -126,27 +121,25 @@ void btsnd_hcic_create_conn_cancel(const RawAddress& dest) { inc_func_call_count(__func__); test::mock::stack_hcic_hcicmds::btsnd_hcic_create_conn_cancel(dest); } -void btsnd_hcic_delete_stored_key(const RawAddress& bd_addr, - bool delete_all_flag) { +void btsnd_hcic_delete_stored_key(const RawAddress& bd_addr, bool delete_all_flag) { inc_func_call_count(__func__); - test::mock::stack_hcic_hcicmds::btsnd_hcic_delete_stored_key(bd_addr, - delete_all_flag); + test::mock::stack_hcic_hcicmds::btsnd_hcic_delete_stored_key(bd_addr, delete_all_flag); } void btsnd_hcic_enable_test_mode(void) { inc_func_call_count(__func__); test::mock::stack_hcic_hcicmds::btsnd_hcic_enable_test_mode(); } -void btsnd_hcic_enhanced_accept_synchronous_connection( - const RawAddress& bd_addr, enh_esco_params_t* p_params) { +void btsnd_hcic_enhanced_accept_synchronous_connection(const RawAddress& bd_addr, + enh_esco_params_t* p_params) { inc_func_call_count(__func__); - test::mock::stack_hcic_hcicmds:: - btsnd_hcic_enhanced_accept_synchronous_connection(bd_addr, p_params); + test::mock::stack_hcic_hcicmds::btsnd_hcic_enhanced_accept_synchronous_connection(bd_addr, + p_params); } -void btsnd_hcic_enhanced_set_up_synchronous_connection( - uint16_t conn_handle, enh_esco_params_t* p_params) { +void btsnd_hcic_enhanced_set_up_synchronous_connection(uint16_t conn_handle, + enh_esco_params_t* p_params) { inc_func_call_count(__func__); - test::mock::stack_hcic_hcicmds:: - btsnd_hcic_enhanced_set_up_synchronous_connection(conn_handle, p_params); + test::mock::stack_hcic_hcicmds::btsnd_hcic_enhanced_set_up_synchronous_connection(conn_handle, + p_params); } void btsnd_hcic_exit_park_mode(uint16_t handle) { inc_func_call_count(__func__); @@ -156,59 +149,50 @@ void btsnd_hcic_exit_sniff_mode(uint16_t handle) { inc_func_call_count(__func__); test::mock::stack_hcic_hcicmds::btsnd_hcic_exit_sniff_mode(handle); } -void btsnd_hcic_hold_mode(uint16_t handle, uint16_t max_hold_period, - uint16_t min_hold_period) { +void btsnd_hcic_hold_mode(uint16_t handle, uint16_t max_hold_period, uint16_t min_hold_period) { inc_func_call_count(__func__); - test::mock::stack_hcic_hcicmds::btsnd_hcic_hold_mode(handle, max_hold_period, - min_hold_period); + test::mock::stack_hcic_hcicmds::btsnd_hcic_hold_mode(handle, max_hold_period, min_hold_period); } -void btsnd_hcic_io_cap_req_neg_reply(const RawAddress& bd_addr, - uint8_t err_code) { +void btsnd_hcic_io_cap_req_neg_reply(const RawAddress& bd_addr, uint8_t err_code) { inc_func_call_count(__func__); - test::mock::stack_hcic_hcicmds::btsnd_hcic_io_cap_req_neg_reply(bd_addr, - err_code); + test::mock::stack_hcic_hcicmds::btsnd_hcic_io_cap_req_neg_reply(bd_addr, err_code); } -void btsnd_hcic_io_cap_req_reply(const RawAddress& bd_addr, uint8_t capability, - uint8_t oob_present, uint8_t auth_req) { +void btsnd_hcic_io_cap_req_reply(const RawAddress& bd_addr, uint8_t capability, uint8_t oob_present, + uint8_t auth_req) { inc_func_call_count(__func__); - test::mock::stack_hcic_hcicmds::btsnd_hcic_io_cap_req_reply( - bd_addr, capability, oob_present, auth_req); + test::mock::stack_hcic_hcicmds::btsnd_hcic_io_cap_req_reply(bd_addr, capability, oob_present, + auth_req); } void btsnd_hcic_link_key_neg_reply(const RawAddress& bd_addr) { inc_func_call_count(__func__); test::mock::stack_hcic_hcicmds::btsnd_hcic_link_key_neg_reply(bd_addr); } -void btsnd_hcic_link_key_req_reply(const RawAddress& bd_addr, - const LinkKey& link_key) { +void btsnd_hcic_link_key_req_reply(const RawAddress& bd_addr, const LinkKey& link_key) { inc_func_call_count(__func__); - test::mock::stack_hcic_hcicmds::btsnd_hcic_link_key_req_reply(bd_addr, - link_key); + test::mock::stack_hcic_hcicmds::btsnd_hcic_link_key_req_reply(bd_addr, link_key); } void btsnd_hcic_park_mode(uint16_t handle, uint16_t beacon_max_interval, uint16_t beacon_min_interval) { inc_func_call_count(__func__); - test::mock::stack_hcic_hcicmds::btsnd_hcic_park_mode( - handle, beacon_max_interval, beacon_min_interval); + test::mock::stack_hcic_hcicmds::btsnd_hcic_park_mode(handle, beacon_max_interval, + beacon_min_interval); } void btsnd_hcic_pin_code_neg_reply(const RawAddress& bd_addr) { inc_func_call_count(__func__); test::mock::stack_hcic_hcicmds::btsnd_hcic_pin_code_neg_reply(bd_addr); } -void btsnd_hcic_pin_code_req_reply(const RawAddress& bd_addr, - uint8_t pin_code_len, PIN_CODE pin_code) { +void btsnd_hcic_pin_code_req_reply(const RawAddress& bd_addr, uint8_t pin_code_len, + PIN_CODE pin_code) { inc_func_call_count(__func__); - test::mock::stack_hcic_hcicmds::btsnd_hcic_pin_code_req_reply( - bd_addr, pin_code_len, pin_code); + test::mock::stack_hcic_hcicmds::btsnd_hcic_pin_code_req_reply(bd_addr, pin_code_len, pin_code); } void btsnd_hcic_read_encryption_key_size(uint16_t handle, ReadEncKeySizeCb cb) { inc_func_call_count(__func__); - test::mock::stack_hcic_hcicmds::btsnd_hcic_read_encryption_key_size( - handle, std::move(cb)); + test::mock::stack_hcic_hcicmds::btsnd_hcic_read_encryption_key_size(handle, std::move(cb)); } void btsnd_hcic_read_failed_contact_counter(uint16_t handle) { inc_func_call_count(__func__); - test::mock::stack_hcic_hcicmds::btsnd_hcic_read_failed_contact_counter( - handle); + test::mock::stack_hcic_hcicmds::btsnd_hcic_read_failed_contact_counter(handle); } void btsnd_hcic_read_local_oob_data(void) { inc_func_call_count(__func__); @@ -246,8 +230,7 @@ void btsnd_hcic_rem_oob_neg_reply(const RawAddress& bd_addr) { inc_func_call_count(__func__); test::mock::stack_hcic_hcicmds::btsnd_hcic_rem_oob_neg_reply(bd_addr); } -void btsnd_hcic_rem_oob_reply(const RawAddress& bd_addr, const Octet16& c, - const Octet16& r) { +void btsnd_hcic_rem_oob_reply(const RawAddress& bd_addr, const Octet16& c, const Octet16& r) { inc_func_call_count(__func__); test::mock::stack_hcic_hcicmds::btsnd_hcic_rem_oob_reply(bd_addr, c, r); } @@ -263,34 +246,31 @@ void btsnd_hcic_set_conn_encrypt(uint16_t handle, bool enable) { inc_func_call_count(__func__); test::mock::stack_hcic_hcicmds::btsnd_hcic_set_conn_encrypt(handle, enable); } -void btsnd_hcic_set_event_filter(uint8_t filt_type, uint8_t filt_cond_type, - uint8_t* filt_cond, uint8_t filt_cond_len) { +void btsnd_hcic_set_event_filter(uint8_t filt_type, uint8_t filt_cond_type, uint8_t* filt_cond, + uint8_t filt_cond_len) { inc_func_call_count(__func__); - test::mock::stack_hcic_hcicmds::btsnd_hcic_set_event_filter( - filt_type, filt_cond_type, filt_cond, filt_cond_len); + test::mock::stack_hcic_hcicmds::btsnd_hcic_set_event_filter(filt_type, filt_cond_type, filt_cond, + filt_cond_len); } void btsnd_hcic_setup_esco_conn(uint16_t handle, uint32_t transmit_bandwidth, - uint32_t receive_bandwidth, - uint16_t max_latency, uint16_t voice, + uint32_t receive_bandwidth, uint16_t max_latency, uint16_t voice, uint8_t retrans_effort, uint16_t packet_types) { inc_func_call_count(__func__); - test::mock::stack_hcic_hcicmds::btsnd_hcic_setup_esco_conn( - handle, transmit_bandwidth, receive_bandwidth, max_latency, voice, - retrans_effort, packet_types); + test::mock::stack_hcic_hcicmds::btsnd_hcic_setup_esco_conn(handle, transmit_bandwidth, + receive_bandwidth, max_latency, voice, + retrans_effort, packet_types); } -void btsnd_hcic_sniff_mode(uint16_t handle, uint16_t max_sniff_period, - uint16_t min_sniff_period, uint16_t sniff_attempt, - uint16_t sniff_timeout) { +void btsnd_hcic_sniff_mode(uint16_t handle, uint16_t max_sniff_period, uint16_t min_sniff_period, + uint16_t sniff_attempt, uint16_t sniff_timeout) { inc_func_call_count(__func__); - test::mock::stack_hcic_hcicmds::btsnd_hcic_sniff_mode( - handle, max_sniff_period, min_sniff_period, sniff_attempt, sniff_timeout); + test::mock::stack_hcic_hcicmds::btsnd_hcic_sniff_mode(handle, max_sniff_period, min_sniff_period, + sniff_attempt, sniff_timeout); } -void btsnd_hcic_sniff_sub_rate(uint16_t handle, uint16_t max_lat, - uint16_t min_remote_lat, +void btsnd_hcic_sniff_sub_rate(uint16_t handle, uint16_t max_lat, uint16_t min_remote_lat, uint16_t min_local_lat) { inc_func_call_count(__func__); - test::mock::stack_hcic_hcicmds::btsnd_hcic_sniff_sub_rate( - handle, max_lat, min_remote_lat, min_local_lat); + test::mock::stack_hcic_hcicmds::btsnd_hcic_sniff_sub_rate(handle, max_lat, min_remote_lat, + min_local_lat); } void btsnd_hcic_user_conf_reply(const RawAddress& bd_addr, bool is_yes) { inc_func_call_count(__func__); @@ -307,8 +287,7 @@ void btsnd_hcic_user_passkey_reply(const RawAddress& bd_addr, uint32_t value) { void btsnd_hcic_vendor_spec_cmd(uint16_t opcode, uint8_t len, uint8_t* p_data, tBTM_VSC_CMPL_CB* p_cmd_cplt_cback) { inc_func_call_count(__func__); - test::mock::stack_hcic_hcicmds::btsnd_hcic_vendor_spec_cmd( - opcode, len, p_data, p_cmd_cplt_cback); + test::mock::stack_hcic_hcicmds::btsnd_hcic_vendor_spec_cmd(opcode, len, p_data, p_cmd_cplt_cback); } void btsnd_hcic_write_auth_enable(uint8_t flag) { inc_func_call_count(__func__); @@ -316,13 +295,11 @@ void btsnd_hcic_write_auth_enable(uint8_t flag) { } void btsnd_hcic_write_auto_flush_tout(uint16_t handle, uint16_t tout) { inc_func_call_count(__func__); - test::mock::stack_hcic_hcicmds::btsnd_hcic_write_auto_flush_tout(handle, - tout); + test::mock::stack_hcic_hcicmds::btsnd_hcic_write_auto_flush_tout(handle, tout); } void btsnd_hcic_write_cur_iac_lap(uint8_t num_cur_iac, LAP* const iac_lap) { inc_func_call_count(__func__); - test::mock::stack_hcic_hcicmds::btsnd_hcic_write_cur_iac_lap(num_cur_iac, - iac_lap); + test::mock::stack_hcic_hcicmds::btsnd_hcic_write_cur_iac_lap(num_cur_iac, iac_lap); } void btsnd_hcic_write_def_policy_set(uint16_t settings) { inc_func_call_count(__func__); @@ -334,13 +311,11 @@ void btsnd_hcic_write_dev_class(DEV_CLASS dev_class) { } void btsnd_hcic_write_ext_inquiry_response(void* buffer, uint8_t fec_req) { inc_func_call_count(__func__); - test::mock::stack_hcic_hcicmds::btsnd_hcic_write_ext_inquiry_response( - buffer, fec_req); + test::mock::stack_hcic_hcicmds::btsnd_hcic_write_ext_inquiry_response(buffer, fec_req); } void btsnd_hcic_write_inqscan_cfg(uint16_t interval, uint16_t window) { inc_func_call_count(__func__); - test::mock::stack_hcic_hcicmds::btsnd_hcic_write_inqscan_cfg(interval, - window); + test::mock::stack_hcic_hcicmds::btsnd_hcic_write_inqscan_cfg(interval, window); } void btsnd_hcic_write_inqscan_type(uint8_t type) { inc_func_call_count(__func__); @@ -352,8 +327,7 @@ void btsnd_hcic_write_inquiry_mode(uint8_t mode) { } void btsnd_hcic_write_link_super_tout(uint16_t handle, uint16_t timeout) { inc_func_call_count(__func__); - test::mock::stack_hcic_hcicmds::btsnd_hcic_write_link_super_tout(handle, - timeout); + test::mock::stack_hcic_hcicmds::btsnd_hcic_write_link_super_tout(handle, timeout); } void btsnd_hcic_write_page_tout(uint16_t timeout) { inc_func_call_count(__func__); @@ -361,8 +335,7 @@ void btsnd_hcic_write_page_tout(uint16_t timeout) { } void btsnd_hcic_write_pagescan_cfg(uint16_t interval, uint16_t window) { inc_func_call_count(__func__); - test::mock::stack_hcic_hcicmds::btsnd_hcic_write_pagescan_cfg(interval, - window); + test::mock::stack_hcic_hcicmds::btsnd_hcic_write_pagescan_cfg(interval, window); } void btsnd_hcic_write_pagescan_type(uint8_t type) { inc_func_call_count(__func__); diff --git a/system/test/mock/mock_stack_hcic_hcicmds.h b/system/test/mock/mock_stack_hcic_hcicmds.h index 12ccad5b337..b59fa685834 100644 --- a/system/test/mock/mock_stack_hcic_hcicmds.h +++ b/system/test/mock/mock_stack_hcic_hcicmds.h @@ -45,21 +45,18 @@ namespace stack_hcic_hcicmds { // retrans_effort, uint16_t packet_types Return: void struct btsnd_hcic_accept_esco_conn { std::function - body{[](const RawAddress& /* bd_addr */, - uint32_t /* transmit_bandwidth */, - uint32_t /* receive_bandwidth */, uint16_t /* max_latency */, - uint16_t /* content_fmt */, uint8_t /* retrans_effort */, - uint16_t /* packet_types */) {}}; + uint32_t receive_bandwidth, uint16_t max_latency, uint16_t content_fmt, + uint8_t retrans_effort, uint16_t packet_types)> + body{[](const RawAddress& /* bd_addr */, uint32_t /* transmit_bandwidth */, + uint32_t /* receive_bandwidth */, uint16_t /* max_latency */, + uint16_t /* content_fmt */, uint8_t /* retrans_effort */, + uint16_t /* packet_types */) {}}; void operator()(const RawAddress& bd_addr, uint32_t transmit_bandwidth, - uint32_t receive_bandwidth, uint16_t max_latency, - uint16_t content_fmt, uint8_t retrans_effort, - uint16_t packet_types) { - body(bd_addr, transmit_bandwidth, receive_bandwidth, max_latency, - content_fmt, retrans_effort, packet_types); - }; + uint32_t receive_bandwidth, uint16_t max_latency, uint16_t content_fmt, + uint8_t retrans_effort, uint16_t packet_types) { + body(bd_addr, transmit_bandwidth, receive_bandwidth, max_latency, content_fmt, retrans_effort, + packet_types); + } }; extern struct btsnd_hcic_accept_esco_conn btsnd_hcic_accept_esco_conn; @@ -68,10 +65,8 @@ extern struct btsnd_hcic_accept_esco_conn btsnd_hcic_accept_esco_conn; // Return: void struct btsnd_hcic_add_SCO_conn { std::function body{ - [](uint16_t /* handle */, uint16_t /* packet_types */) {}}; - void operator()(uint16_t handle, uint16_t packet_types) { - body(handle, packet_types); - }; + [](uint16_t /* handle */, uint16_t /* packet_types */) {}}; + void operator()(uint16_t handle, uint16_t packet_types) { body(handle, packet_types); } }; extern struct btsnd_hcic_add_SCO_conn btsnd_hcic_add_SCO_conn; @@ -80,7 +75,7 @@ extern struct btsnd_hcic_add_SCO_conn btsnd_hcic_add_SCO_conn; // Return: void struct btsnd_hcic_auth_request { std::function body{[](uint16_t /* handle */) {}}; - void operator()(uint16_t handle) { body(handle); }; + void operator()(uint16_t handle) { body(handle); } }; extern struct btsnd_hcic_auth_request btsnd_hcic_auth_request; @@ -88,9 +83,8 @@ extern struct btsnd_hcic_auth_request btsnd_hcic_auth_request; // Params: const RawAddress& dest // Return: void struct btsnd_hcic_create_conn_cancel { - std::function body{ - [](const RawAddress& /* dest */) {}}; - void operator()(const RawAddress& dest) { body(dest); }; + std::function body{[](const RawAddress& /* dest */) {}}; + void operator()(const RawAddress& dest) { body(dest); } }; extern struct btsnd_hcic_create_conn_cancel btsnd_hcic_create_conn_cancel; @@ -99,10 +93,10 @@ extern struct btsnd_hcic_create_conn_cancel btsnd_hcic_create_conn_cancel; // Return: void struct btsnd_hcic_delete_stored_key { std::function body{ - [](const RawAddress& /* bd_addr */, bool /* delete_all_flag */) {}}; + [](const RawAddress& /* bd_addr */, bool /* delete_all_flag */) {}}; void operator()(const RawAddress& bd_addr, bool delete_all_flag) { body(bd_addr, delete_all_flag); - }; + } }; extern struct btsnd_hcic_delete_stored_key btsnd_hcic_delete_stored_key; @@ -111,7 +105,7 @@ extern struct btsnd_hcic_delete_stored_key btsnd_hcic_delete_stored_key; // Return: void struct btsnd_hcic_enable_test_mode { std::function body{[](void) {}}; - void operator()(void) { body(); }; + void operator()(void) { body(); } }; extern struct btsnd_hcic_enable_test_mode btsnd_hcic_enable_test_mode; @@ -119,35 +113,34 @@ extern struct btsnd_hcic_enable_test_mode btsnd_hcic_enable_test_mode; // Params: const RawAddress& bd_addr, enh_esco_params_t* p_params // Return: void struct btsnd_hcic_enhanced_accept_synchronous_connection { - std::function - body{[](const RawAddress& /* bd_addr */, - enh_esco_params_t* /* p_params */) {}}; + std::function body{ + [](const RawAddress& /* bd_addr */, enh_esco_params_t* /* p_params */) {}}; void operator()(const RawAddress& bd_addr, enh_esco_params_t* p_params) { body(bd_addr, p_params); - }; + } }; extern struct btsnd_hcic_enhanced_accept_synchronous_connection - btsnd_hcic_enhanced_accept_synchronous_connection; + btsnd_hcic_enhanced_accept_synchronous_connection; // Name: btsnd_hcic_enhanced_set_up_synchronous_connection // Params: uint16_t conn_handle, enh_esco_params_t* p_params // Return: void struct btsnd_hcic_enhanced_set_up_synchronous_connection { std::function body{ - [](uint16_t /* conn_handle */, enh_esco_params_t* /* p_params */) {}}; + [](uint16_t /* conn_handle */, enh_esco_params_t* /* p_params */) {}}; void operator()(uint16_t conn_handle, enh_esco_params_t* p_params) { body(conn_handle, p_params); - }; + } }; extern struct btsnd_hcic_enhanced_set_up_synchronous_connection - btsnd_hcic_enhanced_set_up_synchronous_connection; + btsnd_hcic_enhanced_set_up_synchronous_connection; // Name: btsnd_hcic_exit_park_mode // Params: uint16_t handle // Return: void struct btsnd_hcic_exit_park_mode { std::function body{[](uint16_t /* handle */) {}}; - void operator()(uint16_t handle) { body(handle); }; + void operator()(uint16_t handle) { body(handle); } }; extern struct btsnd_hcic_exit_park_mode btsnd_hcic_exit_park_mode; @@ -156,7 +149,7 @@ extern struct btsnd_hcic_exit_park_mode btsnd_hcic_exit_park_mode; // Return: void struct btsnd_hcic_exit_sniff_mode { std::function body{[](uint16_t /* handle */) {}}; - void operator()(uint16_t handle) { body(handle); }; + void operator()(uint16_t handle) { body(handle); } }; extern struct btsnd_hcic_exit_sniff_mode btsnd_hcic_exit_sniff_mode; @@ -164,14 +157,12 @@ extern struct btsnd_hcic_exit_sniff_mode btsnd_hcic_exit_sniff_mode; // Params: uint16_t handle, uint16_t max_hold_period, uint16_t min_hold_period // Return: void struct btsnd_hcic_hold_mode { - std::function - body{[](uint16_t /* handle */, uint16_t /* max_hold_period */, - uint16_t /* min_hold_period */) {}}; - void operator()(uint16_t handle, uint16_t max_hold_period, - uint16_t min_hold_period) { + std::function body{ + [](uint16_t /* handle */, uint16_t /* max_hold_period */, + uint16_t /* min_hold_period */) {}}; + void operator()(uint16_t handle, uint16_t max_hold_period, uint16_t min_hold_period) { body(handle, max_hold_period, min_hold_period); - }; + } }; extern struct btsnd_hcic_hold_mode btsnd_hcic_hold_mode; @@ -180,10 +171,8 @@ extern struct btsnd_hcic_hold_mode btsnd_hcic_hold_mode; // Return: void struct btsnd_hcic_io_cap_req_neg_reply { std::function body{ - [](const RawAddress& /* bd_addr */, uint8_t /* err_code */) {}}; - void operator()(const RawAddress& bd_addr, uint8_t err_code) { - body(bd_addr, err_code); - }; + [](const RawAddress& /* bd_addr */, uint8_t /* err_code */) {}}; + void operator()(const RawAddress& bd_addr, uint8_t err_code) { body(bd_addr, err_code); } }; extern struct btsnd_hcic_io_cap_req_neg_reply btsnd_hcic_io_cap_req_neg_reply; @@ -191,14 +180,14 @@ extern struct btsnd_hcic_io_cap_req_neg_reply btsnd_hcic_io_cap_req_neg_reply; // Params: const RawAddress& bd_addr, uint8_t capability, uint8_t oob_present, // uint8_t auth_req Return: void struct btsnd_hcic_io_cap_req_reply { - std::function - body{[](const RawAddress& /* bd_addr */, uint8_t /* capability */, - uint8_t /* oob_present */, uint8_t /* auth_req */) {}}; - void operator()(const RawAddress& bd_addr, uint8_t capability, - uint8_t oob_present, uint8_t auth_req) { + std::function + body{[](const RawAddress& /* bd_addr */, uint8_t /* capability */, + uint8_t /* oob_present */, uint8_t /* auth_req */) {}}; + void operator()(const RawAddress& bd_addr, uint8_t capability, uint8_t oob_present, + uint8_t auth_req) { body(bd_addr, capability, oob_present, auth_req); - }; + } }; extern struct btsnd_hcic_io_cap_req_reply btsnd_hcic_io_cap_req_reply; @@ -206,9 +195,8 @@ extern struct btsnd_hcic_io_cap_req_reply btsnd_hcic_io_cap_req_reply; // Params: const RawAddress& bd_addr // Return: void struct btsnd_hcic_link_key_neg_reply { - std::function body{ - [](const RawAddress& /* bd_addr */) {}}; - void operator()(const RawAddress& bd_addr) { body(bd_addr); }; + std::function body{[](const RawAddress& /* bd_addr */) {}}; + void operator()(const RawAddress& bd_addr) { body(bd_addr); } }; extern struct btsnd_hcic_link_key_neg_reply btsnd_hcic_link_key_neg_reply; @@ -217,10 +205,8 @@ extern struct btsnd_hcic_link_key_neg_reply btsnd_hcic_link_key_neg_reply; // Return: void struct btsnd_hcic_link_key_req_reply { std::function body{ - [](const RawAddress& /* bd_addr */, const LinkKey& /* link_key */) {}}; - void operator()(const RawAddress& bd_addr, const LinkKey& link_key) { - body(bd_addr, link_key); - }; + [](const RawAddress& /* bd_addr */, const LinkKey& /* link_key */) {}}; + void operator()(const RawAddress& bd_addr, const LinkKey& link_key) { body(bd_addr, link_key); } }; extern struct btsnd_hcic_link_key_req_reply btsnd_hcic_link_key_req_reply; @@ -228,14 +214,12 @@ extern struct btsnd_hcic_link_key_req_reply btsnd_hcic_link_key_req_reply; // Params: uint16_t handle, uint16_t beacon_max_interval, uint16_t // beacon_min_interval Return: void struct btsnd_hcic_park_mode { - std::function - body{[](uint16_t /* handle */, uint16_t /* beacon_max_interval */, - uint16_t /* beacon_min_interval */) {}}; - void operator()(uint16_t handle, uint16_t beacon_max_interval, - uint16_t beacon_min_interval) { + std::function + body{[](uint16_t /* handle */, uint16_t /* beacon_max_interval */, + uint16_t /* beacon_min_interval */) {}}; + void operator()(uint16_t handle, uint16_t beacon_max_interval, uint16_t beacon_min_interval) { body(handle, beacon_max_interval, beacon_min_interval); - }; + } }; extern struct btsnd_hcic_park_mode btsnd_hcic_park_mode; @@ -243,9 +227,8 @@ extern struct btsnd_hcic_park_mode btsnd_hcic_park_mode; // Params: const RawAddress& bd_addr // Return: void struct btsnd_hcic_pin_code_neg_reply { - std::function body{ - [](const RawAddress& /* bd_addr */) {}}; - void operator()(const RawAddress& bd_addr) { body(bd_addr); }; + std::function body{[](const RawAddress& /* bd_addr */) {}}; + void operator()(const RawAddress& bd_addr) { body(bd_addr); } }; extern struct btsnd_hcic_pin_code_neg_reply btsnd_hcic_pin_code_neg_reply; @@ -253,14 +236,12 @@ extern struct btsnd_hcic_pin_code_neg_reply btsnd_hcic_pin_code_neg_reply; // Params: const RawAddress& bd_addr, uint8_t pin_code_len, PIN_CODE pin_code // Return: void struct btsnd_hcic_pin_code_req_reply { - std::function - body{[](const RawAddress& /* bd_addr */, uint8_t /* pin_code_len */, - PIN_CODE /* pin_code */) {}}; - void operator()(const RawAddress& bd_addr, uint8_t pin_code_len, - PIN_CODE pin_code) { + std::function body{ + [](const RawAddress& /* bd_addr */, uint8_t /* pin_code_len */, PIN_CODE /* pin_code */) { + }}; + void operator()(const RawAddress& bd_addr, uint8_t pin_code_len, PIN_CODE pin_code) { body(bd_addr, pin_code_len, pin_code); - }; + } }; extern struct btsnd_hcic_pin_code_req_reply btsnd_hcic_pin_code_req_reply; @@ -269,30 +250,26 @@ extern struct btsnd_hcic_pin_code_req_reply btsnd_hcic_pin_code_req_reply; // Return: void struct btsnd_hcic_read_encryption_key_size { std::function body{ - [](uint16_t /* handle */, ReadEncKeySizeCb /* cb */) {}}; - void operator()(uint16_t handle, ReadEncKeySizeCb cb) { - body(handle, std::move(cb)); - }; + [](uint16_t /* handle */, ReadEncKeySizeCb /* cb */) {}}; + void operator()(uint16_t handle, ReadEncKeySizeCb cb) { body(handle, std::move(cb)); } }; -extern struct btsnd_hcic_read_encryption_key_size - btsnd_hcic_read_encryption_key_size; +extern struct btsnd_hcic_read_encryption_key_size btsnd_hcic_read_encryption_key_size; // Name: btsnd_hcic_read_failed_contact_counter // Params: uint16_t handle // Return: void struct btsnd_hcic_read_failed_contact_counter { std::function body{[](uint16_t /* handle */) {}}; - void operator()(uint16_t handle) { body(handle); }; + void operator()(uint16_t handle) { body(handle); } }; -extern struct btsnd_hcic_read_failed_contact_counter - btsnd_hcic_read_failed_contact_counter; +extern struct btsnd_hcic_read_failed_contact_counter btsnd_hcic_read_failed_contact_counter; // Name: btsnd_hcic_read_local_oob_data // Params: void // Return: void struct btsnd_hcic_read_local_oob_data { std::function body{[](void) {}}; - void operator()(void) { body(); }; + void operator()(void) { body(); } }; extern struct btsnd_hcic_read_local_oob_data btsnd_hcic_read_local_oob_data; @@ -301,17 +278,16 @@ extern struct btsnd_hcic_read_local_oob_data btsnd_hcic_read_local_oob_data; // Return: void struct btsnd_hcic_read_local_oob_extended_data { std::function body{[](void) {}}; - void operator()(void) { body(); }; + void operator()(void) { body(); } }; -extern struct btsnd_hcic_read_local_oob_extended_data - btsnd_hcic_read_local_oob_extended_data; +extern struct btsnd_hcic_read_local_oob_extended_data btsnd_hcic_read_local_oob_extended_data; // Name: btsnd_hcic_read_name // Params: void // Return: void struct btsnd_hcic_read_name { std::function body{[](void) {}}; - void operator()(void) { body(); }; + void operator()(void) { body(); } }; extern struct btsnd_hcic_read_name btsnd_hcic_read_name; @@ -320,7 +296,7 @@ extern struct btsnd_hcic_read_name btsnd_hcic_read_name; // Return: void struct btsnd_hcic_read_rmt_clk_offset { std::function body{[](uint16_t /* handle */) {}}; - void operator()(uint16_t handle) { body(handle); }; + void operator()(uint16_t handle) { body(handle); } }; extern struct btsnd_hcic_read_rmt_clk_offset btsnd_hcic_read_rmt_clk_offset; @@ -329,7 +305,7 @@ extern struct btsnd_hcic_read_rmt_clk_offset btsnd_hcic_read_rmt_clk_offset; // Return: void struct btsnd_hcic_read_rssi { std::function body{[](uint16_t /* handle */) {}}; - void operator()(uint16_t handle) { body(handle); }; + void operator()(uint16_t handle) { body(handle); } }; extern struct btsnd_hcic_read_rssi btsnd_hcic_read_rssi; @@ -338,8 +314,8 @@ extern struct btsnd_hcic_read_rssi btsnd_hcic_read_rssi; // Return: void struct btsnd_hcic_read_tx_power { std::function body{ - [](uint16_t /* handle */, uint8_t /* type */) {}}; - void operator()(uint16_t handle, uint8_t type) { body(handle, type); }; + [](uint16_t /* handle */, uint8_t /* type */) {}}; + void operator()(uint16_t handle, uint8_t type) { body(handle, type); } }; extern struct btsnd_hcic_read_tx_power btsnd_hcic_read_tx_power; @@ -348,10 +324,8 @@ extern struct btsnd_hcic_read_tx_power btsnd_hcic_read_tx_power; // Return: void struct btsnd_hcic_reject_conn { std::function body{ - [](const RawAddress& /* dest */, uint8_t /* reason */) {}}; - void operator()(const RawAddress& dest, uint8_t reason) { - body(dest, reason); - }; + [](const RawAddress& /* dest */, uint8_t /* reason */) {}}; + void operator()(const RawAddress& dest, uint8_t reason) { body(dest, reason); } }; extern struct btsnd_hcic_reject_conn btsnd_hcic_reject_conn; @@ -360,10 +334,8 @@ extern struct btsnd_hcic_reject_conn btsnd_hcic_reject_conn; // Return: void struct btsnd_hcic_reject_esco_conn { std::function body{ - [](const RawAddress& /* bd_addr */, uint8_t /* reason */) {}}; - void operator()(const RawAddress& bd_addr, uint8_t reason) { - body(bd_addr, reason); - }; + [](const RawAddress& /* bd_addr */, uint8_t /* reason */) {}}; + void operator()(const RawAddress& bd_addr, uint8_t reason) { body(bd_addr, reason); } }; extern struct btsnd_hcic_reject_esco_conn btsnd_hcic_reject_esco_conn; @@ -371,9 +343,8 @@ extern struct btsnd_hcic_reject_esco_conn btsnd_hcic_reject_esco_conn; // Params: const RawAddress& bd_addr // Return: void struct btsnd_hcic_rem_oob_neg_reply { - std::function body{ - [](const RawAddress& /* bd_addr */) {}}; - void operator()(const RawAddress& bd_addr) { body(bd_addr); }; + std::function body{[](const RawAddress& /* bd_addr */) {}}; + void operator()(const RawAddress& bd_addr) { body(bd_addr); } }; extern struct btsnd_hcic_rem_oob_neg_reply btsnd_hcic_rem_oob_neg_reply; @@ -381,14 +352,11 @@ extern struct btsnd_hcic_rem_oob_neg_reply btsnd_hcic_rem_oob_neg_reply; // Params: const RawAddress& bd_addr, const Octet16& c, const Octet16& r // Return: void struct btsnd_hcic_rem_oob_reply { - std::function - body{[](const RawAddress& /* bd_addr */, const Octet16& /* c */, - const Octet16& /* r */) {}}; - void operator()(const RawAddress& bd_addr, const Octet16& c, - const Octet16& r) { + std::function body{ + [](const RawAddress& /* bd_addr */, const Octet16& /* c */, const Octet16& /* r */) {}}; + void operator()(const RawAddress& bd_addr, const Octet16& c, const Octet16& r) { body(bd_addr, c, r); - }; + } }; extern struct btsnd_hcic_rem_oob_reply btsnd_hcic_rem_oob_reply; @@ -397,10 +365,8 @@ extern struct btsnd_hcic_rem_oob_reply btsnd_hcic_rem_oob_reply; // Return: void struct btsnd_hcic_rmt_ext_features { std::function body{ - [](uint16_t /* handle */, uint8_t /* page_num */) {}}; - void operator()(uint16_t handle, uint8_t page_num) { - body(handle, page_num); - }; + [](uint16_t /* handle */, uint8_t /* page_num */) {}}; + void operator()(uint16_t handle, uint8_t page_num) { body(handle, page_num); } }; extern struct btsnd_hcic_rmt_ext_features btsnd_hcic_rmt_ext_features; @@ -409,7 +375,7 @@ extern struct btsnd_hcic_rmt_ext_features btsnd_hcic_rmt_ext_features; // Return: void struct btsnd_hcic_rmt_ver_req { std::function body{[](uint16_t /* handle */) {}}; - void operator()(uint16_t handle) { body(handle); }; + void operator()(uint16_t handle) { body(handle); } }; extern struct btsnd_hcic_rmt_ver_req btsnd_hcic_rmt_ver_req; @@ -418,8 +384,8 @@ extern struct btsnd_hcic_rmt_ver_req btsnd_hcic_rmt_ver_req; // Return: void struct btsnd_hcic_set_conn_encrypt { std::function body{ - [](uint16_t /* handle */, bool /* enable */) {}}; - void operator()(uint16_t handle, bool enable) { body(handle, enable); }; + [](uint16_t /* handle */, bool /* enable */) {}}; + void operator()(uint16_t handle, bool enable) { body(handle, enable); } }; extern struct btsnd_hcic_set_conn_encrypt btsnd_hcic_set_conn_encrypt; @@ -427,14 +393,14 @@ extern struct btsnd_hcic_set_conn_encrypt btsnd_hcic_set_conn_encrypt; // Params: uint8_t filt_type, uint8_t filt_cond_type, uint8_t* filt_cond, // uint8_t filt_cond_len Return: void struct btsnd_hcic_set_event_filter { - std::function - body{[](uint8_t /* filt_type */, uint8_t /* filt_cond_type */, - uint8_t* /* filt_cond */, uint8_t /* filt_cond_len */) {}}; + std::function + body{[](uint8_t /* filt_type */, uint8_t /* filt_cond_type */, uint8_t* /* filt_cond */, + uint8_t /* filt_cond_len */) {}}; void operator()(uint8_t filt_type, uint8_t filt_cond_type, uint8_t* filt_cond, uint8_t filt_cond_len) { body(filt_type, filt_cond_type, filt_cond, filt_cond_len); - }; + } }; extern struct btsnd_hcic_set_event_filter btsnd_hcic_set_event_filter; @@ -443,21 +409,19 @@ extern struct btsnd_hcic_set_event_filter btsnd_hcic_set_event_filter; // receive_bandwidth, uint16_t max_latency, uint16_t voice, uint8_t // retrans_effort, uint16_t packet_types Return: void struct btsnd_hcic_setup_esco_conn { - std::function - body{[](uint16_t /* handle */, uint32_t /* transmit_bandwidth */, - uint32_t /* receive_bandwidth */, uint16_t /* max_latency */, - uint16_t /* voice */, uint8_t /* retrans_effort */, - uint16_t /* packet_types */) {}}; - void operator()(uint16_t handle, uint32_t transmit_bandwidth, - uint32_t receive_bandwidth, uint16_t max_latency, - uint16_t voice, uint8_t retrans_effort, + body{[](uint16_t /* handle */, uint32_t /* transmit_bandwidth */, + uint32_t /* receive_bandwidth */, uint16_t /* max_latency */, + uint16_t /* voice */, uint8_t /* retrans_effort */, + uint16_t /* packet_types */) {}}; + void operator()(uint16_t handle, uint32_t transmit_bandwidth, uint32_t receive_bandwidth, + uint16_t max_latency, uint16_t voice, uint8_t retrans_effort, uint16_t packet_types) { - body(handle, transmit_bandwidth, receive_bandwidth, max_latency, voice, - retrans_effort, packet_types); - }; + body(handle, transmit_bandwidth, receive_bandwidth, max_latency, voice, retrans_effort, + packet_types); + } }; extern struct btsnd_hcic_setup_esco_conn btsnd_hcic_setup_esco_conn; @@ -465,18 +429,15 @@ extern struct btsnd_hcic_setup_esco_conn btsnd_hcic_setup_esco_conn; // Params: uint16_t handle, uint16_t max_sniff_period, uint16_t // min_sniff_period, uint16_t sniff_attempt, uint16_t sniff_timeout Return: void struct btsnd_hcic_sniff_mode { - std::function - body{[](uint16_t /* handle */, uint16_t /* max_sniff_period */, - uint16_t /* min_sniff_period */, uint16_t /* sniff_attempt */, - uint16_t /* sniff_timeout */) {}}; - void operator()(uint16_t handle, uint16_t max_sniff_period, - uint16_t min_sniff_period, uint16_t sniff_attempt, - uint16_t sniff_timeout) { - body(handle, max_sniff_period, min_sniff_period, sniff_attempt, - sniff_timeout); - }; + std::function + body{[](uint16_t /* handle */, uint16_t /* max_sniff_period */, + uint16_t /* min_sniff_period */, uint16_t /* sniff_attempt */, + uint16_t /* sniff_timeout */) {}}; + void operator()(uint16_t handle, uint16_t max_sniff_period, uint16_t min_sniff_period, + uint16_t sniff_attempt, uint16_t sniff_timeout) { + body(handle, max_sniff_period, min_sniff_period, sniff_attempt, sniff_timeout); + } }; extern struct btsnd_hcic_sniff_mode btsnd_hcic_sniff_mode; @@ -486,12 +447,12 @@ extern struct btsnd_hcic_sniff_mode btsnd_hcic_sniff_mode; struct btsnd_hcic_sniff_sub_rate { std::function - body{[](uint16_t /* handle */, uint16_t /* max_lat */, - uint16_t /* min_remote_lat */, uint16_t /* min_local_lat */) {}}; + body{[](uint16_t /* handle */, uint16_t /* max_lat */, uint16_t /* min_remote_lat */, + uint16_t /* min_local_lat */) {}}; void operator()(uint16_t handle, uint16_t max_lat, uint16_t min_remote_lat, uint16_t min_local_lat) { body(handle, max_lat, min_remote_lat, min_local_lat); - }; + } }; extern struct btsnd_hcic_sniff_sub_rate btsnd_hcic_sniff_sub_rate; @@ -500,10 +461,8 @@ extern struct btsnd_hcic_sniff_sub_rate btsnd_hcic_sniff_sub_rate; // Return: void struct btsnd_hcic_user_conf_reply { std::function body{ - [](const RawAddress& /* bd_addr */, bool /* is_yes */) {}}; - void operator()(const RawAddress& bd_addr, bool is_yes) { - body(bd_addr, is_yes); - }; + [](const RawAddress& /* bd_addr */, bool /* is_yes */) {}}; + void operator()(const RawAddress& bd_addr, bool is_yes) { body(bd_addr, is_yes); } }; extern struct btsnd_hcic_user_conf_reply btsnd_hcic_user_conf_reply; @@ -511,22 +470,18 @@ extern struct btsnd_hcic_user_conf_reply btsnd_hcic_user_conf_reply; // Params: const RawAddress& bd_addr // Return: void struct btsnd_hcic_user_passkey_neg_reply { - std::function body{ - [](const RawAddress& /* bd_addr */) {}}; - void operator()(const RawAddress& bd_addr) { body(bd_addr); }; + std::function body{[](const RawAddress& /* bd_addr */) {}}; + void operator()(const RawAddress& bd_addr) { body(bd_addr); } }; -extern struct btsnd_hcic_user_passkey_neg_reply - btsnd_hcic_user_passkey_neg_reply; +extern struct btsnd_hcic_user_passkey_neg_reply btsnd_hcic_user_passkey_neg_reply; // Name: btsnd_hcic_user_passkey_reply // Params: const RawAddress& bd_addr, uint32_t value // Return: void struct btsnd_hcic_user_passkey_reply { std::function body{ - [](const RawAddress& /* bd_addr */, uint32_t /* value */) {}}; - void operator()(const RawAddress& bd_addr, uint32_t value) { - body(bd_addr, value); - }; + [](const RawAddress& /* bd_addr */, uint32_t /* value */) {}}; + void operator()(const RawAddress& bd_addr, uint32_t value) { body(bd_addr, value); } }; extern struct btsnd_hcic_user_passkey_reply btsnd_hcic_user_passkey_reply; @@ -536,12 +491,12 @@ extern struct btsnd_hcic_user_passkey_reply btsnd_hcic_user_passkey_reply; struct btsnd_hcic_vendor_spec_cmd { std::function - body{[](uint16_t /* opcode */, uint8_t /* len */, uint8_t* /* p_data */, - tBTM_VSC_CMPL_CB* /* p_cmd_cplt_cback */) {}}; + body{[](uint16_t /* opcode */, uint8_t /* len */, uint8_t* /* p_data */, + tBTM_VSC_CMPL_CB* /* p_cmd_cplt_cback */) {}}; void operator()(uint16_t opcode, uint8_t len, uint8_t* p_data, tBTM_VSC_CMPL_CB* p_cmd_cplt_cback) { body(opcode, len, p_data, p_cmd_cplt_cback); - }; + } }; extern struct btsnd_hcic_vendor_spec_cmd btsnd_hcic_vendor_spec_cmd; @@ -550,7 +505,7 @@ extern struct btsnd_hcic_vendor_spec_cmd btsnd_hcic_vendor_spec_cmd; // Return: void struct btsnd_hcic_write_auth_enable { std::function body{[](uint8_t /* flag */) {}}; - void operator()(uint8_t flag) { body(flag); }; + void operator()(uint8_t flag) { body(flag); } }; extern struct btsnd_hcic_write_auth_enable btsnd_hcic_write_auth_enable; @@ -559,8 +514,8 @@ extern struct btsnd_hcic_write_auth_enable btsnd_hcic_write_auth_enable; // Return: void struct btsnd_hcic_write_auto_flush_tout { std::function body{ - [](uint16_t /* handle */, uint16_t /* tout */) {}}; - void operator()(uint16_t handle, uint16_t tout) { body(handle, tout); }; + [](uint16_t /* handle */, uint16_t /* tout */) {}}; + void operator()(uint16_t handle, uint16_t tout) { body(handle, tout); } }; extern struct btsnd_hcic_write_auto_flush_tout btsnd_hcic_write_auto_flush_tout; @@ -569,10 +524,8 @@ extern struct btsnd_hcic_write_auto_flush_tout btsnd_hcic_write_auto_flush_tout; // Return: void struct btsnd_hcic_write_cur_iac_lap { std::function body{ - [](uint8_t /* num_cur_iac */, LAP* const /* iac_lap */) {}}; - void operator()(uint8_t num_cur_iac, LAP* const iac_lap) { - body(num_cur_iac, iac_lap); - }; + [](uint8_t /* num_cur_iac */, LAP* const /* iac_lap */) {}}; + void operator()(uint8_t num_cur_iac, LAP* const iac_lap) { body(num_cur_iac, iac_lap); } }; extern struct btsnd_hcic_write_cur_iac_lap btsnd_hcic_write_cur_iac_lap; @@ -581,7 +534,7 @@ extern struct btsnd_hcic_write_cur_iac_lap btsnd_hcic_write_cur_iac_lap; // Return: void struct btsnd_hcic_write_def_policy_set { std::function body{[](uint16_t /* settings */) {}}; - void operator()(uint16_t settings) { body(settings); }; + void operator()(uint16_t settings) { body(settings); } }; extern struct btsnd_hcic_write_def_policy_set btsnd_hcic_write_def_policy_set; @@ -589,9 +542,8 @@ extern struct btsnd_hcic_write_def_policy_set btsnd_hcic_write_def_policy_set; // Params: DEV_CLASS dev_class // Return: void struct btsnd_hcic_write_dev_class { - std::function body{ - [](DEV_CLASS /* dev_class */) {}}; - void operator()(DEV_CLASS dev_class) { body(dev_class); }; + std::function body{[](DEV_CLASS /* dev_class */) {}}; + void operator()(DEV_CLASS dev_class) { body(dev_class); } }; extern struct btsnd_hcic_write_dev_class btsnd_hcic_write_dev_class; @@ -600,21 +552,18 @@ extern struct btsnd_hcic_write_dev_class btsnd_hcic_write_dev_class; // Return: void struct btsnd_hcic_write_ext_inquiry_response { std::function body{ - [](void* /* buffer */, uint8_t /* fec_req */) {}}; - void operator()(void* buffer, uint8_t fec_req) { body(buffer, fec_req); }; + [](void* /* buffer */, uint8_t /* fec_req */) {}}; + void operator()(void* buffer, uint8_t fec_req) { body(buffer, fec_req); } }; -extern struct btsnd_hcic_write_ext_inquiry_response - btsnd_hcic_write_ext_inquiry_response; +extern struct btsnd_hcic_write_ext_inquiry_response btsnd_hcic_write_ext_inquiry_response; // Name: btsnd_hcic_write_inqscan_cfg // Params: uint16_t interval, uint16_t window // Return: void struct btsnd_hcic_write_inqscan_cfg { std::function body{ - [](uint16_t /* interval */, uint16_t /* window */) {}}; - void operator()(uint16_t interval, uint16_t window) { - body(interval, window); - }; + [](uint16_t /* interval */, uint16_t /* window */) {}}; + void operator()(uint16_t interval, uint16_t window) { body(interval, window); } }; extern struct btsnd_hcic_write_inqscan_cfg btsnd_hcic_write_inqscan_cfg; @@ -623,7 +572,7 @@ extern struct btsnd_hcic_write_inqscan_cfg btsnd_hcic_write_inqscan_cfg; // Return: void struct btsnd_hcic_write_inqscan_type { std::function body{[](uint8_t /* type */) {}}; - void operator()(uint8_t type) { body(type); }; + void operator()(uint8_t type) { body(type); } }; extern struct btsnd_hcic_write_inqscan_type btsnd_hcic_write_inqscan_type; @@ -632,7 +581,7 @@ extern struct btsnd_hcic_write_inqscan_type btsnd_hcic_write_inqscan_type; // Return: void struct btsnd_hcic_write_inquiry_mode { std::function body{[](uint8_t /* mode */) {}}; - void operator()(uint8_t mode) { body(mode); }; + void operator()(uint8_t mode) { body(mode); } }; extern struct btsnd_hcic_write_inquiry_mode btsnd_hcic_write_inquiry_mode; @@ -641,8 +590,8 @@ extern struct btsnd_hcic_write_inquiry_mode btsnd_hcic_write_inquiry_mode; // Return: void struct btsnd_hcic_write_link_super_tout { std::function body{ - [](uint16_t /* handle */, uint16_t /* timeout */) {}}; - void operator()(uint16_t handle, uint16_t timeout) { body(handle, timeout); }; + [](uint16_t /* handle */, uint16_t /* timeout */) {}}; + void operator()(uint16_t handle, uint16_t timeout) { body(handle, timeout); } }; extern struct btsnd_hcic_write_link_super_tout btsnd_hcic_write_link_super_tout; @@ -651,7 +600,7 @@ extern struct btsnd_hcic_write_link_super_tout btsnd_hcic_write_link_super_tout; // Return: void struct btsnd_hcic_write_page_tout { std::function body{[](uint16_t /* timeout */) {}}; - void operator()(uint16_t timeout) { body(timeout); }; + void operator()(uint16_t timeout) { body(timeout); } }; extern struct btsnd_hcic_write_page_tout btsnd_hcic_write_page_tout; @@ -660,10 +609,8 @@ extern struct btsnd_hcic_write_page_tout btsnd_hcic_write_page_tout; // Return: void struct btsnd_hcic_write_pagescan_cfg { std::function body{ - [](uint16_t /* interval */, uint16_t /* window */) {}}; - void operator()(uint16_t interval, uint16_t window) { - body(interval, window); - }; + [](uint16_t /* interval */, uint16_t /* window */) {}}; + void operator()(uint16_t interval, uint16_t window) { body(interval, window); } }; extern struct btsnd_hcic_write_pagescan_cfg btsnd_hcic_write_pagescan_cfg; @@ -672,7 +619,7 @@ extern struct btsnd_hcic_write_pagescan_cfg btsnd_hcic_write_pagescan_cfg; // Return: void struct btsnd_hcic_write_pagescan_type { std::function body{[](uint8_t /* type */) {}}; - void operator()(uint8_t type) { body(type); }; + void operator()(uint8_t type) { body(type); } }; extern struct btsnd_hcic_write_pagescan_type btsnd_hcic_write_pagescan_type; @@ -681,7 +628,7 @@ extern struct btsnd_hcic_write_pagescan_type btsnd_hcic_write_pagescan_type; // Return: void struct btsnd_hcic_write_pin_type { std::function body{[](uint8_t /* type */) {}}; - void operator()(uint8_t type) { body(type); }; + void operator()(uint8_t type) { body(type); } }; extern struct btsnd_hcic_write_pin_type btsnd_hcic_write_pin_type; @@ -690,10 +637,8 @@ extern struct btsnd_hcic_write_pin_type btsnd_hcic_write_pin_type; // Return: void struct btsnd_hcic_write_policy_set { std::function body{ - [](uint16_t /* handle */, uint16_t /* settings */) {}}; - void operator()(uint16_t handle, uint16_t settings) { - body(handle, settings); - }; + [](uint16_t /* handle */, uint16_t /* settings */) {}}; + void operator()(uint16_t handle, uint16_t settings) { body(handle, settings); } }; extern struct btsnd_hcic_write_policy_set btsnd_hcic_write_policy_set; @@ -702,7 +647,7 @@ extern struct btsnd_hcic_write_policy_set btsnd_hcic_write_policy_set; // Return: void struct btsnd_hcic_write_scan_enable { std::function body{[](uint8_t /* flag */) {}}; - void operator()(uint8_t flag) { body(flag); }; + void operator()(uint8_t flag) { body(flag); } }; extern struct btsnd_hcic_write_scan_enable btsnd_hcic_write_scan_enable; @@ -711,7 +656,7 @@ extern struct btsnd_hcic_write_scan_enable btsnd_hcic_write_scan_enable; // Return: void struct btsnd_hcic_write_voice_settings { std::function body{[](uint16_t /* flags */) {}}; - void operator()(uint16_t flags) { body(flags); }; + void operator()(uint16_t flags) { body(flags); } }; extern struct btsnd_hcic_write_voice_settings btsnd_hcic_write_voice_settings; diff --git a/system/test/mock/mock_stack_hidd_api.cc b/system/test/mock/mock_stack_hidd_api.cc index afff3e5515c..cb030bd7fd6 100644 --- a/system/test/mock/mock_stack_hidd_api.cc +++ b/system/test/mock/mock_stack_hidd_api.cc @@ -26,10 +26,9 @@ #include "test/common/mock_functions.h" #include "types/raw_address.h" -tHID_STATUS HID_DevAddRecord(uint32_t /* handle */, char* /* p_name */, - char* /* p_description */, char* /* p_provider */, - uint16_t /* subclass */, uint16_t /* desc_len */, - uint8_t* /* p_desc_data */) { +tHID_STATUS HID_DevAddRecord(uint32_t /* handle */, char* /* p_name */, char* /* p_description */, + char* /* p_provider */, uint16_t /* subclass */, + uint16_t /* desc_len */, uint8_t* /* p_desc_data */) { inc_func_call_count(__func__); return HID_SUCCESS; } @@ -61,9 +60,8 @@ tHID_STATUS HID_DevReportError(uint8_t /* error */) { inc_func_call_count(__func__); return HID_SUCCESS; } -tHID_STATUS HID_DevSendReport(uint8_t /* channel */, uint8_t /* type */, - uint8_t /* id */, uint16_t /* len */, - uint8_t* /* p_data */) { +tHID_STATUS HID_DevSendReport(uint8_t /* channel */, uint8_t /* type */, uint8_t /* id */, + uint16_t /* len */, uint8_t* /* p_data */) { inc_func_call_count(__func__); return HID_SUCCESS; } @@ -71,21 +69,15 @@ tHID_STATUS HID_DevSetIncomingPolicy(bool /* allow */) { inc_func_call_count(__func__); return HID_SUCCESS; } -tHID_STATUS HID_DevSetIncomingQos(uint8_t /* service_type */, - uint32_t /* token_rate */, - uint32_t /* token_bucket_size */, - uint32_t /* peak_bandwidth */, - uint32_t /* latency */, - uint32_t /* delay_variation */) { +tHID_STATUS HID_DevSetIncomingQos(uint8_t /* service_type */, uint32_t /* token_rate */, + uint32_t /* token_bucket_size */, uint32_t /* peak_bandwidth */, + uint32_t /* latency */, uint32_t /* delay_variation */) { inc_func_call_count(__func__); return HID_SUCCESS; } -tHID_STATUS HID_DevSetOutgoingQos(uint8_t /* service_type */, - uint32_t /* token_rate */, - uint32_t /* token_bucket_size */, - uint32_t /* peak_bandwidth */, - uint32_t /* latency */, - uint32_t /* delay_variation */) { +tHID_STATUS HID_DevSetOutgoingQos(uint8_t /* service_type */, uint32_t /* token_rate */, + uint32_t /* token_bucket_size */, uint32_t /* peak_bandwidth */, + uint32_t /* latency */, uint32_t /* delay_variation */) { inc_func_call_count(__func__); return HID_SUCCESS; } diff --git a/system/test/mock/mock_stack_hidh.cc b/system/test/mock/mock_stack_hidh.cc index b3a1144a966..c3ab99f9692 100644 --- a/system/test/mock/mock_stack_hidh.cc +++ b/system/test/mock/mock_stack_hidh.cc @@ -27,8 +27,8 @@ #include "test/common/mock_functions.h" #include "types/raw_address.h" -tHID_STATUS HID_HostAddDev(const RawAddress& /* addr */, - uint16_t /* attr_mask */, uint8_t* /* handle */) { +tHID_STATUS HID_HostAddDev(const RawAddress& /* addr */, uint16_t /* attr_mask */, + uint8_t* /* handle */) { inc_func_call_count(__func__); return HID_SUCCESS; } @@ -40,10 +40,8 @@ tHID_STATUS HID_HostDeregister(void) { inc_func_call_count(__func__); return HID_SUCCESS; } -tHID_STATUS HID_HostGetSDPRecord(const RawAddress& /* addr */, - tSDP_DISCOVERY_DB* /* p_db */, - uint32_t /* db_len */, - tHID_HOST_SDP_CALLBACK* /* sdp_cback */) { +tHID_STATUS HID_HostGetSDPRecord(const RawAddress& /* addr */, tSDP_DISCOVERY_DB* /* p_db */, + uint32_t /* db_len */, tHID_HOST_SDP_CALLBACK* /* sdp_cback */) { inc_func_call_count(__func__); return HID_SUCCESS; } @@ -63,14 +61,13 @@ tHID_STATUS HID_HostRemoveDev(uint8_t /* dev_handle */) { inc_func_call_count(__func__); return HID_SUCCESS; } -tHID_STATUS HID_HostWriteDev(uint8_t /* dev_handle */, uint8_t /* t_type */, - uint8_t /* param */, uint16_t /* data */, - uint8_t /* report_id */, BT_HDR* /* pbuf */) { +tHID_STATUS HID_HostWriteDev(uint8_t /* dev_handle */, uint8_t /* t_type */, uint8_t /* param */, + uint16_t /* data */, uint8_t /* report_id */, BT_HDR* /* pbuf */) { inc_func_call_count(__func__); return HID_SUCCESS; } void HID_HostInit(void) { inc_func_call_count(__func__); } -void hidh_get_str_attr(tSDP_DISC_REC* /* p_rec */, uint16_t /* attr_id */, - uint16_t /* max_len */, char* /* str */) { +void hidh_get_str_attr(tSDP_DISC_REC* /* p_rec */, uint16_t /* attr_id */, uint16_t /* max_len */, + char* /* str */) { inc_func_call_count(__func__); } diff --git a/system/test/mock/mock_stack_l2cap_api.cc b/system/test/mock/mock_stack_l2cap_api.cc index b70e4eacd44..b687510dad7 100644 --- a/system/test/mock/mock_stack_l2cap_api.cc +++ b/system/test/mock/mock_stack_l2cap_api.cc @@ -81,26 +81,22 @@ struct L2CA_LeCreditThreshold L2CA_LeCreditThreshold; // Mocked functions, if any tBT_TRANSPORT l2c_get_transport_from_fixed_cid(uint16_t fixed_cid) { inc_func_call_count(__func__); - return test::mock::stack_l2cap_api::l2c_get_transport_from_fixed_cid( - fixed_cid); + return test::mock::stack_l2cap_api::l2c_get_transport_from_fixed_cid(fixed_cid); } -uint16_t L2CA_RegisterWithSecurity( - uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info, bool enable_snoop, - tL2CAP_ERTM_INFO* p_ertm_info, uint16_t my_mtu, - uint16_t required_remote_mtu, uint16_t sec_level) { +uint16_t L2CA_RegisterWithSecurity(uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info, + bool enable_snoop, tL2CAP_ERTM_INFO* p_ertm_info, + uint16_t my_mtu, uint16_t required_remote_mtu, + uint16_t sec_level) { inc_func_call_count(__func__); return test::mock::stack_l2cap_api::L2CA_RegisterWithSecurity( - psm, p_cb_info, enable_snoop, p_ertm_info, my_mtu, required_remote_mtu, - sec_level); + psm, p_cb_info, enable_snoop, p_ertm_info, my_mtu, required_remote_mtu, sec_level); } -uint16_t L2CA_Register(uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info, - bool enable_snoop, tL2CAP_ERTM_INFO* p_ertm_info, - uint16_t my_mtu, uint16_t required_remote_mtu, +uint16_t L2CA_Register(uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info, bool enable_snoop, + tL2CAP_ERTM_INFO* p_ertm_info, uint16_t my_mtu, uint16_t required_remote_mtu, uint16_t sec_level) { inc_func_call_count(__func__); - return test::mock::stack_l2cap_api::L2CA_Register( - psm, p_cb_info, enable_snoop, p_ertm_info, my_mtu, required_remote_mtu, - sec_level); + return test::mock::stack_l2cap_api::L2CA_Register(psm, p_cb_info, enable_snoop, p_ertm_info, + my_mtu, required_remote_mtu, sec_level); } void L2CA_Deregister(uint16_t psm) { inc_func_call_count(__func__); @@ -117,53 +113,46 @@ void L2CA_FreeLePSM(uint16_t psm) { uint16_t L2CA_ConnectReqWithSecurity(uint16_t psm, const RawAddress& p_bd_addr, uint16_t sec_level) { inc_func_call_count(__func__); - return test::mock::stack_l2cap_api::L2CA_ConnectReqWithSecurity( - psm, p_bd_addr, sec_level); + return test::mock::stack_l2cap_api::L2CA_ConnectReqWithSecurity(psm, p_bd_addr, sec_level); } uint16_t L2CA_ConnectReq(uint16_t psm, const RawAddress& p_bd_addr) { inc_func_call_count(__func__); return test::mock::stack_l2cap_api::L2CA_ConnectReq(psm, p_bd_addr); } -uint16_t L2CA_RegisterLECoc(uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info, - uint16_t sec_level, tL2CAP_LE_CFG_INFO cfg) { +uint16_t L2CA_RegisterLECoc(uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info, uint16_t sec_level, + tL2CAP_LE_CFG_INFO cfg) { inc_func_call_count(__func__); - return test::mock::stack_l2cap_api::L2CA_RegisterLECoc(psm, p_cb_info, - sec_level, cfg); + return test::mock::stack_l2cap_api::L2CA_RegisterLECoc(psm, p_cb_info, sec_level, cfg); } void L2CA_DeregisterLECoc(uint16_t psm) { inc_func_call_count(__func__); test::mock::stack_l2cap_api::L2CA_DeregisterLECoc(psm); } -uint16_t L2CA_ConnectLECocReq(uint16_t psm, const RawAddress& p_bd_addr, - tL2CAP_LE_CFG_INFO* p_cfg, uint16_t sec_level) { +uint16_t L2CA_ConnectLECocReq(uint16_t psm, const RawAddress& p_bd_addr, tL2CAP_LE_CFG_INFO* p_cfg, + uint16_t sec_level) { inc_func_call_count(__func__); - return test::mock::stack_l2cap_api::L2CA_ConnectLECocReq(psm, p_bd_addr, - p_cfg, sec_level); + return test::mock::stack_l2cap_api::L2CA_ConnectLECocReq(psm, p_bd_addr, p_cfg, sec_level); } bool L2CA_GetPeerLECocConfig(uint16_t lcid, tL2CAP_LE_CFG_INFO* peer_cfg) { inc_func_call_count(__func__); return test::mock::stack_l2cap_api::L2CA_GetPeerLECocConfig(lcid, peer_cfg); } bool L2CA_ConnectCreditBasedRsp(const RawAddress& p_bd_addr, uint8_t id, - std::vector& accepted_lcids, - uint16_t result, tL2CAP_LE_CFG_INFO* p_cfg) { + std::vector& accepted_lcids, uint16_t result, + tL2CAP_LE_CFG_INFO* p_cfg) { inc_func_call_count(__func__); - return test::mock::stack_l2cap_api::L2CA_ConnectCreditBasedRsp( - p_bd_addr, id, accepted_lcids, result, p_cfg); + return test::mock::stack_l2cap_api::L2CA_ConnectCreditBasedRsp(p_bd_addr, id, accepted_lcids, + result, p_cfg); } -std::vector L2CA_ConnectCreditBasedReq(uint16_t psm, - const RawAddress& p_bd_addr, +std::vector L2CA_ConnectCreditBasedReq(uint16_t psm, const RawAddress& p_bd_addr, tL2CAP_LE_CFG_INFO* p_cfg) { inc_func_call_count(__func__); - return test::mock::stack_l2cap_api::L2CA_ConnectCreditBasedReq(psm, p_bd_addr, - p_cfg); + return test::mock::stack_l2cap_api::L2CA_ConnectCreditBasedReq(psm, p_bd_addr, p_cfg); } -bool L2CA_ReconfigCreditBasedConnsReq(const RawAddress& bda, - std::vector& lcids, +bool L2CA_ReconfigCreditBasedConnsReq(const RawAddress& bda, std::vector& lcids, tL2CAP_LE_CFG_INFO* p_cfg) { inc_func_call_count(__func__); - return test::mock::stack_l2cap_api::L2CA_ReconfigCreditBasedConnsReq( - bda, lcids, p_cfg); + return test::mock::stack_l2cap_api::L2CA_ReconfigCreditBasedConnsReq(bda, lcids, p_cfg); } bool L2CA_DisconnectReq(uint16_t cid) { inc_func_call_count(__func__); @@ -180,13 +169,11 @@ bool L2CA_GetRemoteChannelId(uint16_t lcid, uint16_t* rcid) { bool L2CA_SetIdleTimeoutByBdAddr(const RawAddress& bd_addr, uint16_t timeout, tBT_TRANSPORT transport) { inc_func_call_count(__func__); - return test::mock::stack_l2cap_api::L2CA_SetIdleTimeoutByBdAddr( - bd_addr, timeout, transport); + return test::mock::stack_l2cap_api::L2CA_SetIdleTimeoutByBdAddr(bd_addr, timeout, transport); } bool L2CA_UseLatencyMode(const RawAddress& bd_addr, bool use_latency_mode) { inc_func_call_count(__func__); - return test::mock::stack_l2cap_api::L2CA_UseLatencyMode(bd_addr, - use_latency_mode); + return test::mock::stack_l2cap_api::L2CA_UseLatencyMode(bd_addr, use_latency_mode); } bool L2CA_SetAclPriority(const RawAddress& bd_addr, tL2CAP_PRIORITY priority) { inc_func_call_count(__func__); @@ -200,28 +187,22 @@ bool L2CA_SetTxPriority(uint16_t cid, tL2CAP_CHNL_PRIORITY priority) { inc_func_call_count(__func__); return test::mock::stack_l2cap_api::L2CA_SetTxPriority(cid, priority); } -bool L2CA_GetPeerFeatures(const RawAddress& bd_addr, uint32_t* p_ext_feat, - uint8_t* p_chnl_mask) { +bool L2CA_GetPeerFeatures(const RawAddress& bd_addr, uint32_t* p_ext_feat, uint8_t* p_chnl_mask) { inc_func_call_count(__func__); - return test::mock::stack_l2cap_api::L2CA_GetPeerFeatures(bd_addr, p_ext_feat, - p_chnl_mask); + return test::mock::stack_l2cap_api::L2CA_GetPeerFeatures(bd_addr, p_ext_feat, p_chnl_mask); } -bool L2CA_RegisterFixedChannel(uint16_t fixed_cid, - tL2CAP_FIXED_CHNL_REG* p_freg) { +bool L2CA_RegisterFixedChannel(uint16_t fixed_cid, tL2CAP_FIXED_CHNL_REG* p_freg) { inc_func_call_count(__func__); - return test::mock::stack_l2cap_api::L2CA_RegisterFixedChannel(fixed_cid, - p_freg); + return test::mock::stack_l2cap_api::L2CA_RegisterFixedChannel(fixed_cid, p_freg); } bool L2CA_ConnectFixedChnl(uint16_t fixed_cid, const RawAddress& rem_bda) { inc_func_call_count(__func__); return test::mock::stack_l2cap_api::L2CA_ConnectFixedChnl(fixed_cid, rem_bda); } -tL2CAP_DW_RESULT L2CA_SendFixedChnlData(uint16_t fixed_cid, - const RawAddress& rem_bda, +tL2CAP_DW_RESULT L2CA_SendFixedChnlData(uint16_t fixed_cid, const RawAddress& rem_bda, BT_HDR* p_buf) { inc_func_call_count(__func__); - return test::mock::stack_l2cap_api::L2CA_SendFixedChnlData(fixed_cid, rem_bda, - p_buf); + return test::mock::stack_l2cap_api::L2CA_SendFixedChnlData(fixed_cid, rem_bda, p_buf); } bool L2CA_RemoveFixedChnl(uint16_t fixed_cid, const RawAddress& rem_bda) { inc_func_call_count(__func__); @@ -245,29 +226,23 @@ tL2CAP_DW_RESULT L2CA_LECocDataWrite(uint16_t cid, BT_HDR* p_data) { } bool L2CA_SetChnlFlushability(uint16_t cid, bool is_flushable) { inc_func_call_count(__func__); - return test::mock::stack_l2cap_api::L2CA_SetChnlFlushability(cid, - is_flushable); + return test::mock::stack_l2cap_api::L2CA_SetChnlFlushability(cid, is_flushable); } uint16_t L2CA_FlushChannel(uint16_t lcid, uint16_t num_to_flush) { inc_func_call_count(__func__); return test::mock::stack_l2cap_api::L2CA_FlushChannel(lcid, num_to_flush); } -bool L2CA_IsLinkEstablished(const RawAddress& bd_addr, - tBT_TRANSPORT transport) { +bool L2CA_IsLinkEstablished(const RawAddress& bd_addr, tBT_TRANSPORT transport) { inc_func_call_count(__func__); - return test::mock::stack_l2cap_api::L2CA_IsLinkEstablished(bd_addr, - transport); + return test::mock::stack_l2cap_api::L2CA_IsLinkEstablished(bd_addr, transport); } void L2CA_SetMediaStreamChannel(uint16_t local_media_cid, bool status) { inc_func_call_count(__func__); - return test::mock::stack_l2cap_api::L2CA_SetMediaStreamChannel( - local_media_cid, status); + return test::mock::stack_l2cap_api::L2CA_SetMediaStreamChannel(local_media_cid, status); } -bool L2CA_isMediaChannel(uint16_t handle, uint16_t channel_id, - bool is_local_cid) { +bool L2CA_isMediaChannel(uint16_t handle, uint16_t channel_id, bool is_local_cid) { inc_func_call_count(__func__); - return test::mock::stack_l2cap_api::L2CA_isMediaChannel(handle, channel_id, - is_local_cid); + return test::mock::stack_l2cap_api::L2CA_isMediaChannel(handle, channel_id, is_local_cid); } uint16_t L2CA_LeCreditDefault() { inc_func_call_count(__func__); diff --git a/system/test/mock/mock_stack_l2cap_api.h b/system/test/mock/mock_stack_l2cap_api.h index 2b0a13b68dc..f457f1bbf63 100644 --- a/system/test/mock/mock_stack_l2cap_api.h +++ b/system/test/mock/mock_stack_l2cap_api.h @@ -42,9 +42,8 @@ namespace stack_l2cap_api { // Params: uint16_t fixed_cid // Returns: tBT_TRANSPORT struct l2c_get_transport_from_fixed_cid { - std::function body{ - [](uint16_t /* fixed_cid */) { return 0; }}; - tBT_TRANSPORT operator()(uint16_t fixed_cid) { return body(fixed_cid); }; + std::function body{[](uint16_t /* fixed_cid */) { return 0; }}; + tBT_TRANSPORT operator()(uint16_t fixed_cid) { return body(fixed_cid); } }; extern struct l2c_get_transport_from_fixed_cid l2c_get_transport_from_fixed_cid; // Name: L2CA_RegisterWithSecurity @@ -52,21 +51,18 @@ extern struct l2c_get_transport_from_fixed_cid l2c_get_transport_from_fixed_cid; // tL2CAP_ERTM_INFO* p_ertm_info, uint16_t my_mtu, uint16_t required_remote_mtu, // uint16_t sec_level Returns: uint16_t struct L2CA_RegisterWithSecurity { - std::function - body{[](uint16_t /* psm */, const tL2CAP_APPL_INFO& /* p_cb_info */, - bool /* enable_snoop */, tL2CAP_ERTM_INFO* /* p_ertm_info */, - uint16_t /* my_mtu */, uint16_t /* required_remote_mtu */, - uint16_t /* sec_level */) { return 0; }}; - uint16_t operator()(uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info, - bool enable_snoop, tL2CAP_ERTM_INFO* p_ertm_info, - uint16_t my_mtu, uint16_t required_remote_mtu, + std::function + body{[](uint16_t /* psm */, const tL2CAP_APPL_INFO& /* p_cb_info */, + bool /* enable_snoop */, tL2CAP_ERTM_INFO* /* p_ertm_info */, + uint16_t /* my_mtu */, uint16_t /* required_remote_mtu */, + uint16_t /* sec_level */) { return 0; }}; + uint16_t operator()(uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info, bool enable_snoop, + tL2CAP_ERTM_INFO* p_ertm_info, uint16_t my_mtu, uint16_t required_remote_mtu, uint16_t sec_level) { - return body(psm, p_cb_info, enable_snoop, p_ertm_info, my_mtu, - required_remote_mtu, sec_level); - }; + return body(psm, p_cb_info, enable_snoop, p_ertm_info, my_mtu, required_remote_mtu, sec_level); + } }; extern struct L2CA_RegisterWithSecurity L2CA_RegisterWithSecurity; // Name: L2CA_Register @@ -74,21 +70,18 @@ extern struct L2CA_RegisterWithSecurity L2CA_RegisterWithSecurity; // tL2CAP_ERTM_INFO* p_ertm_info, uint16_t my_mtu, uint16_t required_remote_mtu, // uint16_t sec_level Returns: uint16_t struct L2CA_Register { - std::function - body{[](uint16_t /* psm */, const tL2CAP_APPL_INFO& /* p_cb_info */, - bool /* enable_snoop */, tL2CAP_ERTM_INFO* /* p_ertm_info */, - uint16_t /* my_mtu */, uint16_t /* required_remote_mtu */, - uint16_t /* sec_level */) { return 0; }}; - uint16_t operator()(uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info, - bool enable_snoop, tL2CAP_ERTM_INFO* p_ertm_info, - uint16_t my_mtu, uint16_t required_remote_mtu, + std::function + body{[](uint16_t /* psm */, const tL2CAP_APPL_INFO& /* p_cb_info */, + bool /* enable_snoop */, tL2CAP_ERTM_INFO* /* p_ertm_info */, + uint16_t /* my_mtu */, uint16_t /* required_remote_mtu */, + uint16_t /* sec_level */) { return 0; }}; + uint16_t operator()(uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info, bool enable_snoop, + tL2CAP_ERTM_INFO* p_ertm_info, uint16_t my_mtu, uint16_t required_remote_mtu, uint16_t sec_level) { - return body(psm, p_cb_info, enable_snoop, p_ertm_info, my_mtu, - required_remote_mtu, sec_level); - }; + return body(psm, p_cb_info, enable_snoop, p_ertm_info, my_mtu, required_remote_mtu, sec_level); + } }; extern struct L2CA_Register L2CA_Register; // Name: L2CA_Deregister @@ -96,7 +89,7 @@ extern struct L2CA_Register L2CA_Register; // Returns: void struct L2CA_Deregister { std::function body{[](uint16_t /* psm */) {}}; - void operator()(uint16_t psm) { body(psm); }; + void operator()(uint16_t psm) { body(psm); } }; extern struct L2CA_Deregister L2CA_Deregister; // Name: L2CA_AllocateLePSM @@ -104,7 +97,7 @@ extern struct L2CA_Deregister L2CA_Deregister; // Returns: uint16_t struct L2CA_AllocateLePSM { std::function body{[](void) { return 0; }}; - uint16_t operator()(void) { return body(); }; + uint16_t operator()(void) { return body(); } }; extern struct L2CA_AllocateLePSM L2CA_AllocateLePSM; // Name: L2CA_FreeLePSM @@ -112,21 +105,20 @@ extern struct L2CA_AllocateLePSM L2CA_AllocateLePSM; // Returns: void struct L2CA_FreeLePSM { std::function body{[](uint16_t /* psm */) {}}; - void operator()(uint16_t psm) { body(psm); }; + void operator()(uint16_t psm) { body(psm); } }; extern struct L2CA_FreeLePSM L2CA_FreeLePSM; // Name: L2CA_ConnectReqWithSecurity // Params: uint16_t psm, const RawAddress& p_bd_addr, uint16_t sec_level // Returns: uint16_t struct L2CA_ConnectReqWithSecurity { - std::function - body{[](uint16_t /* psm */, const RawAddress& /* p_bd_addr */, - uint16_t /* sec_level */) { return 0; }}; - uint16_t operator()(uint16_t psm, const RawAddress& p_bd_addr, - uint16_t sec_level) { + std::function body{ + [](uint16_t /* psm */, const RawAddress& /* p_bd_addr */, uint16_t /* sec_level */) { + return 0; + }}; + uint16_t operator()(uint16_t psm, const RawAddress& p_bd_addr, uint16_t sec_level) { return body(psm, p_bd_addr, sec_level); - }; + } }; extern struct L2CA_ConnectReqWithSecurity L2CA_ConnectReqWithSecurity; // Name: L2CA_ConnectReq @@ -134,25 +126,22 @@ extern struct L2CA_ConnectReqWithSecurity L2CA_ConnectReqWithSecurity; // Returns: uint16_t struct L2CA_ConnectReq { std::function body{ - [](uint16_t /* psm */, const RawAddress& /* p_bd_addr */) { return 0; }}; - uint16_t operator()(uint16_t psm, const RawAddress& p_bd_addr) { - return body(psm, p_bd_addr); - }; + [](uint16_t /* psm */, const RawAddress& /* p_bd_addr */) { return 0; }}; + uint16_t operator()(uint16_t psm, const RawAddress& p_bd_addr) { return body(psm, p_bd_addr); } }; extern struct L2CA_ConnectReq L2CA_ConnectReq; // Name: L2CA_RegisterLECoc // Params: uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info, uint16_t sec_level, // tL2CAP_LE_CFG_INFO cfg Returns: uint16_t struct L2CA_RegisterLECoc { - std::function - body{[](uint16_t /* psm */, const tL2CAP_APPL_INFO& /* p_cb_info */, - uint16_t /* sec_level */, - tL2CAP_LE_CFG_INFO /* cfg */) { return 0; }}; - uint16_t operator()(uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info, - uint16_t sec_level, tL2CAP_LE_CFG_INFO cfg) { + std::function + body{[](uint16_t /* psm */, const tL2CAP_APPL_INFO& /* p_cb_info */, + uint16_t /* sec_level */, tL2CAP_LE_CFG_INFO /* cfg */) { return 0; }}; + uint16_t operator()(uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info, uint16_t sec_level, + tL2CAP_LE_CFG_INFO cfg) { return body(psm, p_cb_info, sec_level, cfg); - }; + } }; extern struct L2CA_RegisterLECoc L2CA_RegisterLECoc; // Name: L2CA_DeregisterLECoc @@ -160,22 +149,21 @@ extern struct L2CA_RegisterLECoc L2CA_RegisterLECoc; // Returns: void struct L2CA_DeregisterLECoc { std::function body{[](uint16_t /* psm */) {}}; - void operator()(uint16_t psm) { body(psm); }; + void operator()(uint16_t psm) { body(psm); } }; extern struct L2CA_DeregisterLECoc L2CA_DeregisterLECoc; // Name: L2CA_ConnectLECocReq // Params: uint16_t psm, const RawAddress& p_bd_addr, tL2CAP_LE_CFG_INFO* p_cfg, // uint16_t sec_level Returns: uint16_t struct L2CA_ConnectLECocReq { - std::function - body{[](uint16_t /* psm */, const RawAddress& /* p_bd_addr */, - tL2CAP_LE_CFG_INFO* /* p_cfg */, - uint16_t /* sec_level */) { return 0; }}; - uint16_t operator()(uint16_t psm, const RawAddress& p_bd_addr, - tL2CAP_LE_CFG_INFO* p_cfg, uint16_t sec_level) { + std::function + body{[](uint16_t /* psm */, const RawAddress& /* p_bd_addr */, + tL2CAP_LE_CFG_INFO* /* p_cfg */, uint16_t /* sec_level */) { return 0; }}; + uint16_t operator()(uint16_t psm, const RawAddress& p_bd_addr, tL2CAP_LE_CFG_INFO* p_cfg, + uint16_t sec_level) { return body(psm, p_bd_addr, p_cfg, sec_level); - }; + } }; extern struct L2CA_ConnectLECocReq L2CA_ConnectLECocReq; // Name: L2CA_GetPeerLECocConfig @@ -183,30 +171,23 @@ extern struct L2CA_ConnectLECocReq L2CA_ConnectLECocReq; // Returns: bool struct L2CA_GetPeerLECocConfig { std::function body{ - [](uint16_t /* lcid */, tL2CAP_LE_CFG_INFO* /* peer_cfg */) { - return false; - }}; - bool operator()(uint16_t lcid, tL2CAP_LE_CFG_INFO* peer_cfg) { - return body(lcid, peer_cfg); - }; + [](uint16_t /* lcid */, tL2CAP_LE_CFG_INFO* /* peer_cfg */) { return false; }}; + bool operator()(uint16_t lcid, tL2CAP_LE_CFG_INFO* peer_cfg) { return body(lcid, peer_cfg); } }; extern struct L2CA_GetPeerLECocConfig L2CA_GetPeerLECocConfig; // Name: L2CA_ConnectCreditBasedRsp // Params: const RawAddress& p_bd_addr, uint8_t id, std::vector& // accepted_lcids, uint16_t result, tL2CAP_LE_CFG_INFO* p_cfg Returns: bool struct L2CA_ConnectCreditBasedRsp { - std::function& accepted_lcids, uint16_t result, - tL2CAP_LE_CFG_INFO* p_cfg)> - body{[](const RawAddress& /* p_bd_addr */, uint8_t /* id */, - std::vector& /* accepted_lcids */, - uint16_t /* result */, - tL2CAP_LE_CFG_INFO* /* p_cfg */) { return false; }}; - bool operator()(const RawAddress& p_bd_addr, uint8_t id, - std::vector& accepted_lcids, uint16_t result, - tL2CAP_LE_CFG_INFO* p_cfg) { + std::function& accepted_lcids, + uint16_t result, tL2CAP_LE_CFG_INFO* p_cfg)> + body{[](const RawAddress& /* p_bd_addr */, uint8_t /* id */, + std::vector& /* accepted_lcids */, uint16_t /* result */, + tL2CAP_LE_CFG_INFO* /* p_cfg */) { return false; }}; + bool operator()(const RawAddress& p_bd_addr, uint8_t id, std::vector& accepted_lcids, + uint16_t result, tL2CAP_LE_CFG_INFO* p_cfg) { return body(p_bd_addr, id, accepted_lcids, result, p_cfg); - }; + } }; extern struct L2CA_ConnectCreditBasedRsp L2CA_ConnectCreditBasedRsp; // Name: L2CA_ConnectCreditBasedReq @@ -216,12 +197,12 @@ struct L2CA_ConnectCreditBasedReq { std::vector cids; std::function(uint16_t psm, const RawAddress& p_bd_addr, tL2CAP_LE_CFG_INFO* p_cfg)> - body{[this](uint16_t /* psm */, const RawAddress& /* p_bd_addr */, - tL2CAP_LE_CFG_INFO* /* p_cfg */) { return cids; }}; + body{[this](uint16_t /* psm */, const RawAddress& /* p_bd_addr */, + tL2CAP_LE_CFG_INFO* /* p_cfg */) { return cids; }}; std::vector operator()(uint16_t psm, const RawAddress& p_bd_addr, tL2CAP_LE_CFG_INFO* p_cfg) { return body(psm, p_bd_addr, p_cfg); - }; + } }; extern struct L2CA_ConnectCreditBasedReq L2CA_ConnectCreditBasedReq; // Name: L2CA_ReconfigCreditBasedConnsReq @@ -230,30 +211,27 @@ extern struct L2CA_ConnectCreditBasedReq L2CA_ConnectCreditBasedReq; struct L2CA_ReconfigCreditBasedConnsReq { std::function& lcids, tL2CAP_LE_CFG_INFO* p_cfg)> - body{[](const RawAddress& /* bda */, std::vector& /* lcids */, - tL2CAP_LE_CFG_INFO* /* p_cfg */) { return false; }}; - bool operator()(const RawAddress& bda, std::vector& lcids, - tL2CAP_LE_CFG_INFO* p_cfg) { + body{[](const RawAddress& /* bda */, std::vector& /* lcids */, + tL2CAP_LE_CFG_INFO* /* p_cfg */) { return false; }}; + bool operator()(const RawAddress& bda, std::vector& lcids, tL2CAP_LE_CFG_INFO* p_cfg) { return body(bda, lcids, p_cfg); - }; + } }; extern struct L2CA_ReconfigCreditBasedConnsReq L2CA_ReconfigCreditBasedConnsReq; // Name: L2CA_DisconnectReq // Params: uint16_t cid // Returns: bool struct L2CA_DisconnectReq { - std::function body{ - [](uint16_t /* cid */) { return false; }}; - bool operator()(uint16_t cid) { return body(cid); }; + std::function body{[](uint16_t /* cid */) { return false; }}; + bool operator()(uint16_t cid) { return body(cid); } }; extern struct L2CA_DisconnectReq L2CA_DisconnectReq; // Name: L2CA_DisconnectLECocReq // Params: uint16_t cid // Returns: bool struct L2CA_DisconnectLECocReq { - std::function body{ - [](uint16_t /* cid */) { return false; }}; - bool operator()(uint16_t cid) { return body(cid); }; + std::function body{[](uint16_t /* cid */) { return false; }}; + bool operator()(uint16_t cid) { return body(cid); } }; extern struct L2CA_DisconnectLECocReq L2CA_DisconnectLECocReq; // Name: L2CA_GetRemoteChannelId @@ -261,22 +239,20 @@ extern struct L2CA_DisconnectLECocReq L2CA_DisconnectLECocReq; // Returns: bool struct L2CA_GetRemoteChannelId { std::function body{ - [](uint16_t /* lcid */, uint16_t* /* rcid */) { return false; }}; - bool operator()(uint16_t lcid, uint16_t* rcid) { return body(lcid, rcid); }; + [](uint16_t /* lcid */, uint16_t* /* rcid */) { return false; }}; + bool operator()(uint16_t lcid, uint16_t* rcid) { return body(lcid, rcid); } }; extern struct L2CA_GetRemoteChannelId L2CA_GetRemoteChannelId; // Name: L2CA_SetIdleTimeoutByBdAddr // Params: const RawAddress& bd_addr, uint16_t timeout, tBT_TRANSPORT transport // Returns: bool struct L2CA_SetIdleTimeoutByBdAddr { - std::function - body{[](const RawAddress& /* bd_addr */, uint16_t /* timeout */, - tBT_TRANSPORT /* transport */) { return false; }}; - bool operator()(const RawAddress& bd_addr, uint16_t timeout, - tBT_TRANSPORT transport) { + std::function body{ + [](const RawAddress& /* bd_addr */, uint16_t /* timeout */, + tBT_TRANSPORT /* transport */) { return false; }}; + bool operator()(const RawAddress& bd_addr, uint16_t timeout, tBT_TRANSPORT transport) { return body(bd_addr, timeout, transport); - }; + } }; extern struct L2CA_SetIdleTimeoutByBdAddr L2CA_SetIdleTimeoutByBdAddr; // Name: L2CA_UseLatencyMode @@ -284,12 +260,10 @@ extern struct L2CA_SetIdleTimeoutByBdAddr L2CA_SetIdleTimeoutByBdAddr; // Returns: bool struct L2CA_UseLatencyMode { std::function body{ - [](const RawAddress& /* bd_addr */, bool /* use_latency_mode */) { - return false; - }}; + [](const RawAddress& /* bd_addr */, bool /* use_latency_mode */) { return false; }}; bool operator()(const RawAddress& bd_addr, bool use_latency_mode) { return body(bd_addr, use_latency_mode); - }; + } }; extern struct L2CA_UseLatencyMode L2CA_UseLatencyMode; // Name: L2CA_SetAclPriority @@ -297,12 +271,10 @@ extern struct L2CA_UseLatencyMode L2CA_UseLatencyMode; // Returns: bool struct L2CA_SetAclPriority { std::function body{ - [](const RawAddress& /* bd_addr */, tL2CAP_PRIORITY /* priority */) { - return false; - }}; + [](const RawAddress& /* bd_addr */, tL2CAP_PRIORITY /* priority */) { return false; }}; bool operator()(const RawAddress& bd_addr, tL2CAP_PRIORITY priority) { return body(bd_addr, priority); - }; + } }; extern struct L2CA_SetAclPriority L2CA_SetAclPriority; // Name: L2CA_SetAclLatency @@ -310,12 +282,10 @@ extern struct L2CA_SetAclPriority L2CA_SetAclPriority; // Returns: bool struct L2CA_SetAclLatency { std::function body{ - [](const RawAddress& /* bd_addr */, tL2CAP_LATENCY /* latency */) { - return false; - }}; + [](const RawAddress& /* bd_addr */, tL2CAP_LATENCY /* latency */) { return false; }}; bool operator()(const RawAddress& bd_addr, tL2CAP_LATENCY latency) { return body(bd_addr, latency); - }; + } }; extern struct L2CA_SetAclLatency L2CA_SetAclLatency; // Name: L2CA_SetTxPriority @@ -323,26 +293,20 @@ extern struct L2CA_SetAclLatency L2CA_SetAclLatency; // Returns: bool struct L2CA_SetTxPriority { std::function body{ - [](uint16_t /* cid */, tL2CAP_CHNL_PRIORITY /* priority */) { - return false; - }}; - bool operator()(uint16_t cid, tL2CAP_CHNL_PRIORITY priority) { - return body(cid, priority); - }; + [](uint16_t /* cid */, tL2CAP_CHNL_PRIORITY /* priority */) { return false; }}; + bool operator()(uint16_t cid, tL2CAP_CHNL_PRIORITY priority) { return body(cid, priority); } }; extern struct L2CA_SetTxPriority L2CA_SetTxPriority; // Name: L2CA_GetPeerFeatures // Params: const RawAddress& bd_addr, uint32_t* p_ext_feat, uint8_t* p_chnl_mask // Returns: bool struct L2CA_GetPeerFeatures { - std::function - body{[](const RawAddress& /* bd_addr */, uint32_t* /* p_ext_feat */, - uint8_t* /* p_chnl_mask */) { return false; }}; - bool operator()(const RawAddress& bd_addr, uint32_t* p_ext_feat, - uint8_t* p_chnl_mask) { + std::function body{ + [](const RawAddress& /* bd_addr */, uint32_t* /* p_ext_feat */, + uint8_t* /* p_chnl_mask */) { return false; }}; + bool operator()(const RawAddress& bd_addr, uint32_t* p_ext_feat, uint8_t* p_chnl_mask) { return body(bd_addr, p_ext_feat, p_chnl_mask); - }; + } }; extern struct L2CA_GetPeerFeatures L2CA_GetPeerFeatures; // Name: L2CA_RegisterFixedChannel @@ -350,12 +314,10 @@ extern struct L2CA_GetPeerFeatures L2CA_GetPeerFeatures; // Returns: bool struct L2CA_RegisterFixedChannel { std::function body{ - [](uint16_t /* fixed_cid */, tL2CAP_FIXED_CHNL_REG* /* p_freg */) { - return false; - }}; + [](uint16_t /* fixed_cid */, tL2CAP_FIXED_CHNL_REG* /* p_freg */) { return false; }}; bool operator()(uint16_t fixed_cid, tL2CAP_FIXED_CHNL_REG* p_freg) { return body(fixed_cid, p_freg); - }; + } }; extern struct L2CA_RegisterFixedChannel L2CA_RegisterFixedChannel; // Name: L2CA_ConnectFixedChnl @@ -363,28 +325,22 @@ extern struct L2CA_RegisterFixedChannel L2CA_RegisterFixedChannel; // Returns: bool struct L2CA_ConnectFixedChnl { std::function body{ - [](uint16_t /* fixed_cid */, const RawAddress& /* rem_bda */) { - return false; - }}; + [](uint16_t /* fixed_cid */, const RawAddress& /* rem_bda */) { return false; }}; bool operator()(uint16_t fixed_cid, const RawAddress& rem_bda) { return body(fixed_cid, rem_bda); - }; + } }; extern struct L2CA_ConnectFixedChnl L2CA_ConnectFixedChnl; // Name: L2CA_SendFixedChnlData // Params: uint16_t fixed_cid, const RawAddress& rem_bda, BT_HDR* p_buf // Returns: uint16_t struct L2CA_SendFixedChnlData { - std::function - body{[](uint16_t /* fixed_cid */, const RawAddress& /* rem_bda */, - BT_HDR* /* p_buf */) -> tL2CAP_DW_RESULT { - return tL2CAP_DW_RESULT::FAILED; - }}; - tL2CAP_DW_RESULT operator()(uint16_t fixed_cid, const RawAddress& rem_bda, - BT_HDR* p_buf) { + std::function + body{[](uint16_t /* fixed_cid */, const RawAddress& /* rem_bda */, + BT_HDR* /* p_buf */) -> tL2CAP_DW_RESULT { return tL2CAP_DW_RESULT::FAILED; }}; + tL2CAP_DW_RESULT operator()(uint16_t fixed_cid, const RawAddress& rem_bda, BT_HDR* p_buf) { return body(fixed_cid, rem_bda, p_buf); - }; + } }; extern struct L2CA_SendFixedChnlData L2CA_SendFixedChnlData; // Name: L2CA_RemoveFixedChnl @@ -392,12 +348,10 @@ extern struct L2CA_SendFixedChnlData L2CA_SendFixedChnlData; // Returns: bool struct L2CA_RemoveFixedChnl { std::function body{ - [](uint16_t /* fixed_cid */, const RawAddress& /* rem_bda */) { - return false; - }}; + [](uint16_t /* fixed_cid */, const RawAddress& /* rem_bda */) { return false; }}; bool operator()(uint16_t fixed_cid, const RawAddress& rem_bda) { return body(fixed_cid, rem_bda); - }; + } }; extern struct L2CA_RemoveFixedChnl L2CA_RemoveFixedChnl; // Name: L2CA_SetLeGattTimeout @@ -405,12 +359,10 @@ extern struct L2CA_RemoveFixedChnl L2CA_RemoveFixedChnl; // Returns: bool struct L2CA_SetLeGattTimeout { std::function body{ - [](const RawAddress& /* rem_bda */, uint16_t /* idle_tout */) { - return false; - }}; + [](const RawAddress& /* rem_bda */, uint16_t /* idle_tout */) { return false; }}; bool operator()(const RawAddress& rem_bda, uint16_t idle_tout) { return body(rem_bda, idle_tout); - }; + } }; extern struct L2CA_SetLeGattTimeout L2CA_SetLeGattTimeout; // Name: L2CA_MarkLeLinkAsActive @@ -418,8 +370,8 @@ extern struct L2CA_SetLeGattTimeout L2CA_SetLeGattTimeout; // Returns: bool struct L2CA_MarkLeLinkAsActive { std::function body{ - [](const RawAddress& /* rem_bda */) { return false; }}; - bool operator()(const RawAddress& rem_bda) { return body(rem_bda); }; + [](const RawAddress& /* rem_bda */) { return false; }}; + bool operator()(const RawAddress& rem_bda) { return body(rem_bda); } }; extern struct L2CA_MarkLeLinkAsActive L2CA_MarkLeLinkAsActive; // Name: L2CA_DataWrite @@ -427,12 +379,10 @@ extern struct L2CA_MarkLeLinkAsActive L2CA_MarkLeLinkAsActive; // Returns: uint8_t struct L2CA_DataWrite { std::function body{ - [](uint16_t /* cid */, BT_HDR* /* p_data */) -> tL2CAP_DW_RESULT { - return tL2CAP_DW_RESULT::FAILED; - }}; - tL2CAP_DW_RESULT operator()(uint16_t cid, BT_HDR* p_data) { - return body(cid, p_data); - }; + [](uint16_t /* cid */, BT_HDR* /* p_data */) -> tL2CAP_DW_RESULT { + return tL2CAP_DW_RESULT::FAILED; + }}; + tL2CAP_DW_RESULT operator()(uint16_t cid, BT_HDR* p_data) { return body(cid, p_data); } }; extern struct L2CA_DataWrite L2CA_DataWrite; // Name: L2CA_LECocDataWrite @@ -440,12 +390,10 @@ extern struct L2CA_DataWrite L2CA_DataWrite; // Returns: uint8_t struct L2CA_LECocDataWrite { std::function body{ - [](uint16_t /* cid */, BT_HDR* /* p_data */) -> tL2CAP_DW_RESULT { - return tL2CAP_DW_RESULT::FAILED; - }}; - tL2CAP_DW_RESULT operator()(uint16_t cid, BT_HDR* p_data) { - return body(cid, p_data); - }; + [](uint16_t /* cid */, BT_HDR* /* p_data */) -> tL2CAP_DW_RESULT { + return tL2CAP_DW_RESULT::FAILED; + }}; + tL2CAP_DW_RESULT operator()(uint16_t cid, BT_HDR* p_data) { return body(cid, p_data); } }; extern struct L2CA_LECocDataWrite L2CA_LECocDataWrite; // Name: L2CA_SetChnlFlushability @@ -453,10 +401,8 @@ extern struct L2CA_LECocDataWrite L2CA_LECocDataWrite; // Returns: bool struct L2CA_SetChnlFlushability { std::function body{ - [](uint16_t /* cid */, bool /* is_flushable */) { return false; }}; - bool operator()(uint16_t cid, bool is_flushable) { - return body(cid, is_flushable); - }; + [](uint16_t /* cid */, bool /* is_flushable */) { return false; }}; + bool operator()(uint16_t cid, bool is_flushable) { return body(cid, is_flushable); } }; extern struct L2CA_SetChnlFlushability L2CA_SetChnlFlushability; // Name: L2CA_FlushChannel @@ -464,10 +410,8 @@ extern struct L2CA_SetChnlFlushability L2CA_SetChnlFlushability; // Returns: uint16_t struct L2CA_FlushChannel { std::function body{ - [](uint16_t /* lcid */, uint16_t /* num_to_flush */) { return 0; }}; - uint16_t operator()(uint16_t lcid, uint16_t num_to_flush) { - return body(lcid, num_to_flush); - }; + [](uint16_t /* lcid */, uint16_t /* num_to_flush */) { return 0; }}; + uint16_t operator()(uint16_t lcid, uint16_t num_to_flush) { return body(lcid, num_to_flush); } }; extern struct L2CA_FlushChannel L2CA_FlushChannel; // Name: L2CA_IsLinkEstablished @@ -475,12 +419,10 @@ extern struct L2CA_FlushChannel L2CA_FlushChannel; // Returns: bool struct L2CA_IsLinkEstablished { std::function body{ - [](const RawAddress& /* bd_addr */, tBT_TRANSPORT /* transport */) { - return false; - }}; + [](const RawAddress& /* bd_addr */, tBT_TRANSPORT /* transport */) { return false; }}; bool operator()(const RawAddress& bd_addr, tBT_TRANSPORT transport) { return body(bd_addr, transport); - }; + } }; extern struct L2CA_IsLinkEstablished L2CA_IsLinkEstablished; // Name: L2CA_SetMediaStreamChannel @@ -488,22 +430,21 @@ extern struct L2CA_IsLinkEstablished L2CA_IsLinkEstablished; // Returns: void struct L2CA_SetMediaStreamChannel { std::function body{ - [](uint16_t /* local_media_cid */, bool /* status */) {}}; - void operator()(uint16_t local_media_cid, bool status) { - body(local_media_cid, status); - }; + [](uint16_t /* local_media_cid */, bool /* status */) {}}; + void operator()(uint16_t local_media_cid, bool status) { body(local_media_cid, status); } }; extern struct L2CA_SetMediaStreamChannel L2CA_SetMediaStreamChannel; // Name: L2CA_isMediaChannel // Params: uint16_t handle, uint16_t channel_id, bool is_local_cid // Returns: bool struct L2CA_isMediaChannel { - std::function - body{[](uint16_t /* handle */, uint16_t /* channel_id */, - bool /* is_local_cid */) { return false; }}; + std::function body{ + [](uint16_t /* handle */, uint16_t /* channel_id */, bool /* is_local_cid */) { + return false; + }}; bool operator()(uint16_t handle, uint16_t channel_id, bool is_local_cid) { return body(handle, channel_id, is_local_cid); - }; + } }; extern struct L2CA_isMediaChannel L2CA_isMediaChannel; // Name: L2CA_LeCreditDefault @@ -511,7 +452,7 @@ extern struct L2CA_isMediaChannel L2CA_isMediaChannel; // Returns: uint16_t struct L2CA_LeCreditDefault { std::function body{[]() { return 0; }}; - uint16_t operator()() { return body(); }; + uint16_t operator()() { return body(); } }; extern struct L2CA_LeCreditDefault L2CA_LeCreditDefault; // Name: L2CA_LeCreditThreshold @@ -519,7 +460,7 @@ extern struct L2CA_LeCreditDefault L2CA_LeCreditDefault; // Returns: uint16_t struct L2CA_LeCreditThreshold { std::function body{[]() { return 0; }}; - uint16_t operator()() { return body(); }; + uint16_t operator()() { return body(); } }; extern struct L2CA_LeCreditThreshold L2CA_LeCreditThreshold; diff --git a/system/test/mock/mock_stack_l2cap_ble.cc b/system/test/mock/mock_stack_l2cap_ble.cc index 340c02c0174..8311d876503 100644 --- a/system/test/mock/mock_stack_l2cap_ble.cc +++ b/system/test/mock/mock_stack_l2cap_ble.cc @@ -37,10 +37,8 @@ namespace stack_l2cap_ble { // Function state capture and return values, if needed struct L2CA_UpdateBleConnParams L2CA_UpdateBleConnParams; -struct L2CA_LockBleConnParamsForServiceDiscovery - L2CA_LockBleConnParamsForServiceDiscovery; -struct L2CA_LockBleConnParamsForProfileConnection - L2CA_LockBleConnParamsForProfileConnection; +struct L2CA_LockBleConnParamsForServiceDiscovery L2CA_LockBleConnParamsForServiceDiscovery; +struct L2CA_LockBleConnParamsForProfileConnection L2CA_LockBleConnParamsForProfileConnection; struct L2CA_ConsolidateParams L2CA_ConsolidateParams; struct L2CA_GetBleConnRole L2CA_GetBleConnRole; struct l2cble_notify_le_connection l2cble_notify_le_connection; @@ -48,12 +46,11 @@ struct l2cble_conn_comp l2cble_conn_comp; struct l2cble_process_conn_update_evt l2cble_process_conn_update_evt; struct l2cble_process_sig_cmd l2cble_process_sig_cmd; struct l2cble_create_conn l2cble_create_conn; -struct l2c_link_processs_ble_num_bufs l2c_link_processs_ble_num_bufs; +struct l2c_link_process_ble_num_bufs l2c_link_process_ble_num_bufs; struct l2c_ble_link_adjust_allocation l2c_ble_link_adjust_allocation; struct l2cble_process_rc_param_request_evt l2cble_process_rc_param_request_evt; struct l2cble_update_data_length l2cble_update_data_length; -struct l2cble_process_data_length_change_event - l2cble_process_data_length_change_event; +struct l2cble_process_data_length_change_event l2cble_process_data_length_change_event; struct l2cble_credit_based_conn_req l2cble_credit_based_conn_req; struct l2cble_credit_based_conn_res l2cble_credit_based_conn_res; struct l2cble_send_flow_control_credit l2cble_send_flow_control_credit; @@ -71,25 +68,20 @@ struct l2cble_process_subrate_change_evt l2cble_process_subrate_change_evt; } // namespace test // Mocked functions, if any -bool L2CA_UpdateBleConnParams(const RawAddress& rem_bda, uint16_t min_int, - uint16_t max_int, uint16_t latency, - uint16_t timeout, uint16_t min_ce_len, +bool L2CA_UpdateBleConnParams(const RawAddress& rem_bda, uint16_t min_int, uint16_t max_int, + uint16_t latency, uint16_t timeout, uint16_t min_ce_len, uint16_t max_ce_len) { inc_func_call_count(__func__); - return test::mock::stack_l2cap_ble::L2CA_UpdateBleConnParams( - rem_bda, min_int, max_int, latency, timeout, min_ce_len, max_ce_len); + return test::mock::stack_l2cap_ble::L2CA_UpdateBleConnParams(rem_bda, min_int, max_int, latency, + timeout, min_ce_len, max_ce_len); } -void L2CA_LockBleConnParamsForServiceDiscovery(const RawAddress& rem_bda, - bool enable) { +void L2CA_LockBleConnParamsForServiceDiscovery(const RawAddress& rem_bda, bool enable) { inc_func_call_count(__func__); - return test::mock::stack_l2cap_ble::L2CA_LockBleConnParamsForServiceDiscovery( - rem_bda, enable); + return test::mock::stack_l2cap_ble::L2CA_LockBleConnParamsForServiceDiscovery(rem_bda, enable); } -void L2CA_LockBleConnParamsForProfileConnection(const RawAddress& rem_bda, - bool enable) { +void L2CA_LockBleConnParamsForProfileConnection(const RawAddress& rem_bda, bool enable) { inc_func_call_count(__func__); - return test::mock::stack_l2cap_ble:: - L2CA_LockBleConnParamsForProfileConnection(rem_bda, enable); + return test::mock::stack_l2cap_ble::L2CA_LockBleConnParamsForProfileConnection(rem_bda, enable); } void L2CA_Consolidate(const RawAddress& identity_addr, const RawAddress& rpa) { inc_func_call_count(__func__); @@ -103,19 +95,17 @@ void l2cble_notify_le_connection(const RawAddress& bda) { inc_func_call_count(__func__); test::mock::stack_l2cap_ble::l2cble_notify_le_connection(bda); } -bool l2cble_conn_comp(uint16_t handle, tHCI_ROLE role, const RawAddress& bda, - tBLE_ADDR_TYPE type, uint16_t conn_interval, - uint16_t conn_latency, uint16_t conn_timeout) { +bool l2cble_conn_comp(uint16_t handle, tHCI_ROLE role, const RawAddress& bda, tBLE_ADDR_TYPE type, + uint16_t conn_interval, uint16_t conn_latency, uint16_t conn_timeout) { inc_func_call_count(__func__); - return test::mock::stack_l2cap_ble::l2cble_conn_comp( - handle, role, bda, type, conn_interval, conn_latency, conn_timeout); + return test::mock::stack_l2cap_ble::l2cble_conn_comp(handle, role, bda, type, conn_interval, + conn_latency, conn_timeout); } -void l2cble_process_conn_update_evt(uint16_t handle, uint8_t status, - uint16_t interval, uint16_t latency, - uint16_t timeout) { +void l2cble_process_conn_update_evt(uint16_t handle, uint8_t status, uint16_t interval, + uint16_t latency, uint16_t timeout) { inc_func_call_count(__func__); - test::mock::stack_l2cap_ble::l2cble_process_conn_update_evt( - handle, status, interval, latency, timeout); + test::mock::stack_l2cap_ble::l2cble_process_conn_update_evt(handle, status, interval, latency, + timeout); } void l2cble_process_sig_cmd(tL2C_LCB* p_lcb, uint8_t* p, uint16_t pkt_len) { inc_func_call_count(__func__); @@ -125,31 +115,29 @@ bool l2cble_create_conn(tL2C_LCB* p_lcb) { inc_func_call_count(__func__); return test::mock::stack_l2cap_ble::l2cble_create_conn(p_lcb); } -void l2c_link_processs_ble_num_bufs(uint16_t num_lm_ble_bufs) { +void l2c_link_process_ble_num_bufs(uint16_t num_lm_ble_bufs) { inc_func_call_count(__func__); - test::mock::stack_l2cap_ble::l2c_link_processs_ble_num_bufs(num_lm_ble_bufs); + test::mock::stack_l2cap_ble::l2c_link_process_ble_num_bufs(num_lm_ble_bufs); } void l2c_ble_link_adjust_allocation(void) { inc_func_call_count(__func__); test::mock::stack_l2cap_ble::l2c_ble_link_adjust_allocation(); } -void l2cble_process_rc_param_request_evt(uint16_t handle, uint16_t int_min, - uint16_t int_max, uint16_t latency, - uint16_t timeout) { +void l2cble_process_rc_param_request_evt(uint16_t handle, uint16_t int_min, uint16_t int_max, + uint16_t latency, uint16_t timeout) { inc_func_call_count(__func__); - test::mock::stack_l2cap_ble::l2cble_process_rc_param_request_evt( - handle, int_min, int_max, latency, timeout); + test::mock::stack_l2cap_ble::l2cble_process_rc_param_request_evt(handle, int_min, int_max, + latency, timeout); } void l2cble_update_data_length(tL2C_LCB* p_lcb) { inc_func_call_count(__func__); test::mock::stack_l2cap_ble::l2cble_update_data_length(p_lcb); } -void l2cble_process_data_length_change_event(uint16_t handle, - uint16_t tx_data_len, +void l2cble_process_data_length_change_event(uint16_t handle, uint16_t tx_data_len, uint16_t rx_data_len) { inc_func_call_count(__func__); - test::mock::stack_l2cap_ble::l2cble_process_data_length_change_event( - handle, tx_data_len, rx_data_len); + test::mock::stack_l2cap_ble::l2cble_process_data_length_change_event(handle, tx_data_len, + rx_data_len); } void l2cble_credit_based_conn_req(tL2C_CCB* p_ccb) { inc_func_call_count(__func__); @@ -161,33 +149,29 @@ void l2cble_credit_based_conn_res(tL2C_CCB* p_ccb, uint16_t result) { } void l2cble_send_flow_control_credit(tL2C_CCB* p_ccb, uint16_t credit_value) { inc_func_call_count(__func__); - test::mock::stack_l2cap_ble::l2cble_send_flow_control_credit(p_ccb, - credit_value); + test::mock::stack_l2cap_ble::l2cble_send_flow_control_credit(p_ccb, credit_value); } void l2cble_send_peer_disc_req(tL2C_CCB* p_ccb) { inc_func_call_count(__func__); test::mock::stack_l2cap_ble::l2cble_send_peer_disc_req(p_ccb); } -void l2cble_sec_comp(const RawAddress* bda, tBT_TRANSPORT transport, - void* p_ref_data, tBTM_STATUS status) { +void l2cble_sec_comp(const RawAddress* bda, tBT_TRANSPORT transport, void* p_ref_data, + tBTM_STATUS status) { inc_func_call_count(__func__); - test::mock::stack_l2cap_ble::l2cble_sec_comp(bda, transport, p_ref_data, - status); + test::mock::stack_l2cap_ble::l2cble_sec_comp(bda, transport, p_ref_data, status); } -tL2CAP_LE_RESULT_CODE l2ble_sec_access_req(const RawAddress& bd_addr, - uint16_t psm, bool is_originator, - tBTM_SEC_CALLBACK* p_callback, +tL2CAP_LE_RESULT_CODE l2ble_sec_access_req(const RawAddress& bd_addr, uint16_t psm, + bool is_originator, tBTM_SEC_CALLBACK* p_callback, void* p_ref_data) { inc_func_call_count(__func__); - return test::mock::stack_l2cap_ble::l2ble_sec_access_req( - bd_addr, psm, is_originator, p_callback, p_ref_data); + return test::mock::stack_l2cap_ble::l2ble_sec_access_req(bd_addr, psm, is_originator, p_callback, + p_ref_data); } -void L2CA_AdjustConnectionIntervals(uint16_t* min_interval, - uint16_t* max_interval, +void L2CA_AdjustConnectionIntervals(uint16_t* min_interval, uint16_t* max_interval, uint16_t floor_interval) { inc_func_call_count(__func__); - test::mock::stack_l2cap_ble::L2CA_AdjustConnectionIntervals( - min_interval, max_interval, floor_interval); + test::mock::stack_l2cap_ble::L2CA_AdjustConnectionIntervals(min_interval, max_interval, + floor_interval); } void L2CA_SetEcosystemBaseInterval(uint32_t base_interval) { inc_func_call_count(__func__); @@ -197,20 +181,18 @@ void l2cble_use_preferred_conn_params(const RawAddress& bda) { inc_func_call_count(__func__); test::mock::stack_l2cap_ble::l2cble_use_preferred_conn_params(bda); } -bool L2CA_SubrateRequest(const RawAddress& rem_bda, uint16_t subrate_min, - uint16_t subrate_max, uint16_t max_latency, - uint16_t cont_num, uint16_t timeout) { +bool L2CA_SubrateRequest(const RawAddress& rem_bda, uint16_t subrate_min, uint16_t subrate_max, + uint16_t max_latency, uint16_t cont_num, uint16_t timeout) { inc_func_call_count(__func__); - return test::mock::stack_l2cap_ble::L2CA_SubrateRequest( - rem_bda, subrate_min, subrate_max, max_latency, cont_num, timeout); + return test::mock::stack_l2cap_ble::L2CA_SubrateRequest(rem_bda, subrate_min, subrate_max, + max_latency, cont_num, timeout); } -void l2cble_process_subrate_change_evt(uint16_t handle, uint8_t status, - uint16_t subrate_factor, - uint16_t peripheral_latency, - uint16_t cont_num, uint16_t timeout) { +void l2cble_process_subrate_change_evt(uint16_t handle, uint8_t status, uint16_t subrate_factor, + uint16_t peripheral_latency, uint16_t cont_num, + uint16_t timeout) { inc_func_call_count(__func__); test::mock::stack_l2cap_ble::l2cble_process_subrate_change_evt( - handle, status, subrate_factor, peripheral_latency, cont_num, timeout); + handle, status, subrate_factor, peripheral_latency, cont_num, timeout); } // END mockcify generation diff --git a/system/test/mock/mock_stack_l2cap_ble.h b/system/test/mock/mock_stack_l2cap_ble.h index 0068379682f..e2eb747818b 100644 --- a/system/test/mock/mock_stack_l2cap_ble.h +++ b/system/test/mock/mock_stack_l2cap_ble.h @@ -41,19 +41,15 @@ namespace stack_l2cap_ble { // uint16_t latency, uint16_t timeout, uint16_t min_ce_len, uint16_t max_ce_len // Returns: bool struct L2CA_UpdateBleConnParams { - std::function - body{[](const RawAddress& /* rem_bda */, uint16_t /* min_int */, - uint16_t /* max_int */, uint16_t /* latency */, - uint16_t /* timeout */, uint16_t /* min_ce_len */, - uint16_t /* max_ce_len */) { return false; }}; - bool operator()(const RawAddress& rem_bda, uint16_t min_int, uint16_t max_int, - uint16_t latency, uint16_t timeout, uint16_t min_ce_len, - uint16_t max_ce_len) { - return body(rem_bda, min_int, max_int, latency, timeout, min_ce_len, - max_ce_len); - }; + std::function + body{[](const RawAddress& /* rem_bda */, uint16_t /* min_int */, uint16_t /* max_int */, + uint16_t /* latency */, uint16_t /* timeout */, uint16_t /* min_ce_len */, + uint16_t /* max_ce_len */) { return false; }}; + bool operator()(const RawAddress& rem_bda, uint16_t min_int, uint16_t max_int, uint16_t latency, + uint16_t timeout, uint16_t min_ce_len, uint16_t max_ce_len) { + return body(rem_bda, min_int, max_int, latency, timeout, min_ce_len, max_ce_len); + } }; extern struct L2CA_UpdateBleConnParams L2CA_UpdateBleConnParams; // Name: L2CA_LockBleConnParamsForServiceDiscovery @@ -61,32 +57,25 @@ extern struct L2CA_UpdateBleConnParams L2CA_UpdateBleConnParams; // Returns: void struct L2CA_LockBleConnParamsForServiceDiscovery { std::function body{ - [](const RawAddress& /* rem_bda */, bool /* enable */) { return false; }}; - void operator()(const RawAddress& rem_bda, bool enable) { - return body(rem_bda, enable); - }; + [](const RawAddress& /* rem_bda */, bool /* enable */) { return false; }}; + void operator()(const RawAddress& rem_bda, bool enable) { return body(rem_bda, enable); } }; -extern struct L2CA_LockBleConnParamsForServiceDiscovery - L2CA_LockBleConnParamsForServiceDiscovery; +extern struct L2CA_LockBleConnParamsForServiceDiscovery L2CA_LockBleConnParamsForServiceDiscovery; // Name: L2CA_LockBleConnParamsForProfileConnection // Params: const RawAddress& rem_bda, bool enable // Returns: void struct L2CA_LockBleConnParamsForProfileConnection { std::function body{ - [](const RawAddress& /* rem_bda */, bool /* enable */) { return false; }}; - void operator()(const RawAddress& rem_bda, bool enable) { - return body(rem_bda, enable); - }; + [](const RawAddress& /* rem_bda */, bool /* enable */) { return false; }}; + void operator()(const RawAddress& rem_bda, bool enable) { return body(rem_bda, enable); } }; -extern struct L2CA_LockBleConnParamsForProfileConnection - L2CA_LockBleConnParamsForProfileConnection; +extern struct L2CA_LockBleConnParamsForProfileConnection L2CA_LockBleConnParamsForProfileConnection; struct L2CA_ConsolidateParams { - std::function - body{[](const RawAddress& /* identity_addr */, - const RawAddress& /* rpa */) { return false; }}; + std::function body{ + [](const RawAddress& /* identity_addr */, const RawAddress& /* rpa */) { return false; }}; void operator()(const RawAddress& identity_addr, const RawAddress& rpa) { body(identity_addr, rpa); - }; + } }; extern struct L2CA_ConsolidateParams L2CA_ConsolidateParams; // Name: L2CA_GetBleConnRole @@ -94,17 +83,16 @@ extern struct L2CA_ConsolidateParams L2CA_ConsolidateParams; // Returns: hci_role_t struct L2CA_GetBleConnRole { std::function body{ - [](const RawAddress& /* bd_addr */) { return HCI_ROLE_CENTRAL; }}; - hci_role_t operator()(const RawAddress& bd_addr) { return body(bd_addr); }; + [](const RawAddress& /* bd_addr */) { return HCI_ROLE_CENTRAL; }}; + hci_role_t operator()(const RawAddress& bd_addr) { return body(bd_addr); } }; extern struct L2CA_GetBleConnRole L2CA_GetBleConnRole; // Name: l2cble_notify_le_connection // Params: const RawAddress& bda // Returns: void struct l2cble_notify_le_connection { - std::function body{ - [](const RawAddress& /* bda */) {}}; - void operator()(const RawAddress& bda) { body(bda); }; + std::function body{[](const RawAddress& /* bda */) {}}; + void operator()(const RawAddress& bda) { body(bda); } }; extern struct l2cble_notify_le_connection l2cble_notify_le_connection; // Name: l2cble_conn_comp @@ -112,34 +100,29 @@ extern struct l2cble_notify_le_connection l2cble_notify_le_connection; // type, uint16_t conn_interval, uint16_t conn_latency, uint16_t conn_timeout // Returns: bool struct l2cble_conn_comp { - std::function - body{[](uint16_t /* handle */, uint8_t /* role */, - const RawAddress& /* bda */, tBLE_ADDR_TYPE /* type */, - uint16_t /* conn_interval */, uint16_t /* conn_latency */, - uint16_t /* conn_timeout */) { return false; }}; - bool operator()(uint16_t handle, uint8_t role, const RawAddress& bda, - tBLE_ADDR_TYPE type, uint16_t conn_interval, - uint16_t conn_latency, uint16_t conn_timeout) { - return body(handle, role, bda, type, conn_interval, conn_latency, - conn_timeout); - }; + std::function + body{[](uint16_t /* handle */, uint8_t /* role */, const RawAddress& /* bda */, + tBLE_ADDR_TYPE /* type */, uint16_t /* conn_interval */, + uint16_t /* conn_latency */, uint16_t /* conn_timeout */) { return false; }}; + bool operator()(uint16_t handle, uint8_t role, const RawAddress& bda, tBLE_ADDR_TYPE type, + uint16_t conn_interval, uint16_t conn_latency, uint16_t conn_timeout) { + return body(handle, role, bda, type, conn_interval, conn_latency, conn_timeout); + } }; extern struct l2cble_conn_comp l2cble_conn_comp; // Name: l2cble_process_conn_update_evt // Params: uint16_t handle, uint8_t status, uint16_t interval, uint16_t latency, // uint16_t timeout Returns: void struct l2cble_process_conn_update_evt { - std::function - body{[](uint16_t /* handle */, uint8_t /* status */, - uint16_t /* interval */, uint16_t /* latency */, - uint16_t /* timeout */) {}}; - void operator()(uint16_t handle, uint8_t status, uint16_t interval, - uint16_t latency, uint16_t timeout) { + std::function + body{[](uint16_t /* handle */, uint8_t /* status */, uint16_t /* interval */, + uint16_t /* latency */, uint16_t /* timeout */) {}}; + void operator()(uint16_t handle, uint8_t status, uint16_t interval, uint16_t latency, + uint16_t timeout) { body(handle, status, interval, latency, timeout); - }; + } }; extern struct l2cble_process_conn_update_evt l2cble_process_conn_update_evt; // Name: l2cble_process_sig_cmd @@ -147,82 +130,73 @@ extern struct l2cble_process_conn_update_evt l2cble_process_conn_update_evt; // Returns: void struct l2cble_process_sig_cmd { std::function body{ - [](tL2C_LCB* /* p_lcb */, uint8_t* /* p */, uint16_t /* pkt_len */) {}}; - void operator()(tL2C_LCB* p_lcb, uint8_t* p, uint16_t pkt_len) { - body(p_lcb, p, pkt_len); - }; + [](tL2C_LCB* /* p_lcb */, uint8_t* /* p */, uint16_t /* pkt_len */) {}}; + void operator()(tL2C_LCB* p_lcb, uint8_t* p, uint16_t pkt_len) { body(p_lcb, p, pkt_len); } }; extern struct l2cble_process_sig_cmd l2cble_process_sig_cmd; // Name: l2cble_create_conn // Params: tL2C_LCB* p_lcb // Returns: bool struct l2cble_create_conn { - std::function body{ - [](tL2C_LCB* /* p_lcb */) { return false; }}; - bool operator()(tL2C_LCB* p_lcb) { return body(p_lcb); }; + std::function body{[](tL2C_LCB* /* p_lcb */) { return false; }}; + bool operator()(tL2C_LCB* p_lcb) { return body(p_lcb); } }; extern struct l2cble_create_conn l2cble_create_conn; -// Name: l2c_link_processs_ble_num_bufs +// Name: l2c_link_process_ble_num_bufs // Params: uint16_t num_lm_ble_bufs // Returns: void -struct l2c_link_processs_ble_num_bufs { - std::function body{ - [](uint16_t /* num_lm_ble_bufs */) {}}; - void operator()(uint16_t num_lm_ble_bufs) { body(num_lm_ble_bufs); }; +struct l2c_link_process_ble_num_bufs { + std::function body{[](uint16_t /* num_lm_ble_bufs */) {}}; + void operator()(uint16_t num_lm_ble_bufs) { body(num_lm_ble_bufs); } }; -extern struct l2c_link_processs_ble_num_bufs l2c_link_processs_ble_num_bufs; +extern struct l2c_link_process_ble_num_bufs l2c_link_process_ble_num_bufs; // Name: l2c_ble_link_adjust_allocation // Params: void // Returns: void struct l2c_ble_link_adjust_allocation { std::function body{[](void) {}}; - void operator()(void) { body(); }; + void operator()(void) { body(); } }; extern struct l2c_ble_link_adjust_allocation l2c_ble_link_adjust_allocation; // Name: l2cble_process_rc_param_request_evt // Params: uint16_t handle, uint16_t int_min, uint16_t int_max, uint16_t // latency, uint16_t timeout Returns: void struct l2cble_process_rc_param_request_evt { - std::function - body{[](uint16_t /* handle */, uint16_t /* int_min */, - uint16_t /* int_max */, uint16_t /* latency */, - uint16_t /* timeout */) {}}; - void operator()(uint16_t handle, uint16_t int_min, uint16_t int_max, - uint16_t latency, uint16_t timeout) { + std::function + body{[](uint16_t /* handle */, uint16_t /* int_min */, uint16_t /* int_max */, + uint16_t /* latency */, uint16_t /* timeout */) {}}; + void operator()(uint16_t handle, uint16_t int_min, uint16_t int_max, uint16_t latency, + uint16_t timeout) { body(handle, int_min, int_max, latency, timeout); - }; + } }; -extern struct l2cble_process_rc_param_request_evt - l2cble_process_rc_param_request_evt; +extern struct l2cble_process_rc_param_request_evt l2cble_process_rc_param_request_evt; // Name: l2cble_update_data_length // Params: tL2C_LCB* p_lcb // Returns: void struct l2cble_update_data_length { std::function body{[](tL2C_LCB* /* p_lcb */) {}}; - void operator()(tL2C_LCB* p_lcb) { body(p_lcb); }; + void operator()(tL2C_LCB* p_lcb) { body(p_lcb); } }; extern struct l2cble_update_data_length l2cble_update_data_length; // Name: l2cble_process_data_length_change_event // Params: uint16_t handle, uint16_t tx_data_len, uint16_t rx_data_len // Returns: void struct l2cble_process_data_length_change_event { - std::function - body{[](uint16_t /* handle */, uint16_t /* tx_data_len */, - uint16_t /* rx_data_len */) {}}; + std::function body{ + [](uint16_t /* handle */, uint16_t /* tx_data_len */, uint16_t /* rx_data_len */) {}}; void operator()(uint16_t handle, uint16_t tx_data_len, uint16_t rx_data_len) { body(handle, tx_data_len, rx_data_len); - }; + } }; -extern struct l2cble_process_data_length_change_event - l2cble_process_data_length_change_event; +extern struct l2cble_process_data_length_change_event l2cble_process_data_length_change_event; // Name: l2cble_credit_based_conn_req // Params: tL2C_CCB* p_ccb // Returns: void struct l2cble_credit_based_conn_req { std::function body{[](tL2C_CCB* /* p_ccb */) {}}; - void operator()(tL2C_CCB* p_ccb) { body(p_ccb); }; + void operator()(tL2C_CCB* p_ccb) { body(p_ccb); } }; extern struct l2cble_credit_based_conn_req l2cble_credit_based_conn_req; // Name: l2cble_credit_based_conn_res @@ -230,8 +204,8 @@ extern struct l2cble_credit_based_conn_req l2cble_credit_based_conn_req; // Returns: void struct l2cble_credit_based_conn_res { std::function body{ - [](tL2C_CCB* /* p_ccb */, uint16_t /* result */) {}}; - void operator()(tL2C_CCB* p_ccb, uint16_t result) { body(p_ccb, result); }; + [](tL2C_CCB* /* p_ccb */, uint16_t /* result */) {}}; + void operator()(tL2C_CCB* p_ccb, uint16_t result) { body(p_ccb, result); } }; extern struct l2cble_credit_based_conn_res l2cble_credit_based_conn_res; // Name: l2cble_send_flow_control_credit @@ -239,10 +213,8 @@ extern struct l2cble_credit_based_conn_res l2cble_credit_based_conn_res; // Returns: void struct l2cble_send_flow_control_credit { std::function body{ - [](tL2C_CCB* /* p_ccb */, uint16_t /* credit_value */) {}}; - void operator()(tL2C_CCB* p_ccb, uint16_t credit_value) { - body(p_ccb, credit_value); - }; + [](tL2C_CCB* /* p_ccb */, uint16_t /* credit_value */) {}}; + void operator()(tL2C_CCB* p_ccb, uint16_t credit_value) { body(p_ccb, credit_value); } }; extern struct l2cble_send_flow_control_credit l2cble_send_flow_control_credit; // Name: l2cble_send_peer_disc_req @@ -250,90 +222,79 @@ extern struct l2cble_send_flow_control_credit l2cble_send_flow_control_credit; // Returns: void struct l2cble_send_peer_disc_req { std::function body{[](tL2C_CCB* /* p_ccb */) {}}; - void operator()(tL2C_CCB* p_ccb) { body(p_ccb); }; + void operator()(tL2C_CCB* p_ccb) { body(p_ccb); } }; extern struct l2cble_send_peer_disc_req l2cble_send_peer_disc_req; // Name: l2cble_sec_comp // Params: const RawAddress* bda, tBT_TRANSPORT transport, void* p_ref_data, // tBTM_STATUS status Returns: void struct l2cble_sec_comp { - std::function - body{[](const RawAddress* /* bda */, tBT_TRANSPORT /* transport */, - void* /* p_ref_data */, tBTM_STATUS /* status */) {}}; - void operator()(const RawAddress* bda, tBT_TRANSPORT transport, - void* p_ref_data, tBTM_STATUS status) { + std::function + body{[](const RawAddress* /* bda */, tBT_TRANSPORT /* transport */, + void* /* p_ref_data */, tBTM_STATUS /* status */) {}}; + void operator()(const RawAddress* bda, tBT_TRANSPORT transport, void* p_ref_data, + tBTM_STATUS status) { body(bda, transport, p_ref_data, status); - }; + } }; extern struct l2cble_sec_comp l2cble_sec_comp; // Name: l2ble_sec_access_req // Params: const RawAddress& bd_addr, uint16_t psm, bool is_originator, // tL2CAP_SEC_CBACK* p_callback, void* p_ref_data Returns: tL2CAP_LE_RESULT_CODE struct l2ble_sec_access_req { - std::function - body{[](const RawAddress& /* bd_addr */, uint16_t /* psm */, - bool /* is_originator */, tBTM_SEC_CALLBACK* /* p_callback */, - void* /* p_ref_data */) { return L2CAP_LE_RESULT_CONN_OK; }}; - tL2CAP_LE_RESULT_CODE operator()(const RawAddress& bd_addr, uint16_t psm, - bool is_originator, - tBTM_SEC_CALLBACK* p_callback, - void* p_ref_data) { + std::function + body{[](const RawAddress& /* bd_addr */, uint16_t /* psm */, bool /* is_originator */, + tBTM_SEC_CALLBACK* /* p_callback */, + void* /* p_ref_data */) { return L2CAP_LE_RESULT_CONN_OK; }}; + tL2CAP_LE_RESULT_CODE operator()(const RawAddress& bd_addr, uint16_t psm, bool is_originator, + tBTM_SEC_CALLBACK* p_callback, void* p_ref_data) { return body(bd_addr, psm, is_originator, p_callback, p_ref_data); - }; + } }; extern struct l2ble_sec_access_req l2ble_sec_access_req; // Name: L2CA_AdjustConnectionIntervals // Params: uint16_t* min_interval, uint16_t* max_interval, uint16_t // floor_interval Returns: void struct L2CA_AdjustConnectionIntervals { - std::function - body{[](uint16_t* /* min_interval */, uint16_t* /* max_interval */, - uint16_t /* floor_interval */) {}}; - void operator()(uint16_t* min_interval, uint16_t* max_interval, - uint16_t floor_interval) { + std::function body{ + [](uint16_t* /* min_interval */, uint16_t* /* max_interval */, + uint16_t /* floor_interval */) {}}; + void operator()(uint16_t* min_interval, uint16_t* max_interval, uint16_t floor_interval) { body(min_interval, max_interval, floor_interval); - }; + } }; extern struct L2CA_AdjustConnectionIntervals L2CA_AdjustConnectionIntervals; // Name: L2CA_SetEcosystemBaseInterval // Params: uint16_t* min_interval, uint16_t* max_interval, uint16_t // floor_interval Returns: void struct L2CA_SetEcosystemBaseInterval { - std::function body{ - [](uint32_t /* base_interval */) {}}; - void operator()(uint32_t base_interval) { body(base_interval); }; + std::function body{[](uint32_t /* base_interval */) {}}; + void operator()(uint32_t base_interval) { body(base_interval); } }; extern struct L2CA_SetEcosystemBaseInterval L2CA_SetEcosystemBaseInterval; // Name: l2cble_use_preferred_conn_params // Params: const RawAddress& bda // Returns: void struct l2cble_use_preferred_conn_params { - std::function body{ - [](const RawAddress& /* bda */) {}}; - void operator()(const RawAddress& bda) { body(bda); }; + std::function body{[](const RawAddress& /* bda */) {}}; + void operator()(const RawAddress& bda) { body(bda); } }; extern struct l2cble_use_preferred_conn_params l2cble_use_preferred_conn_params; // Name: L2CA_SubrateRequest // Params: // Returns: bool struct L2CA_SubrateRequest { - std::function - body{[](const RawAddress& /* rem_bda */, uint16_t /* subrate_min */, - uint16_t /* subrate_max */, uint16_t /* max_latency */, - uint16_t /* cont_num */, - uint16_t /* timeout */) { return false; }}; - bool operator()(const RawAddress& rem_bda, uint16_t subrate_min, - uint16_t subrate_max, uint16_t max_latency, uint16_t cont_num, - uint16_t timeout) { - return body(rem_bda, subrate_min, subrate_max, max_latency, cont_num, - timeout); - }; + std::function + body{[](const RawAddress& /* rem_bda */, uint16_t /* subrate_min */, + uint16_t /* subrate_max */, uint16_t /* max_latency */, uint16_t /* cont_num */, + uint16_t /* timeout */) { return false; }}; + bool operator()(const RawAddress& rem_bda, uint16_t subrate_min, uint16_t subrate_max, + uint16_t max_latency, uint16_t cont_num, uint16_t timeout) { + return body(rem_bda, subrate_min, subrate_max, max_latency, cont_num, timeout); + } }; extern struct L2CA_SubrateRequest L2CA_SubrateRequest; // Name: l2cble_process_subrate_change_evt @@ -341,19 +302,16 @@ extern struct L2CA_SubrateRequest L2CA_SubrateRequest; // Returns: void struct l2cble_process_subrate_change_evt { std::function - body{[](uint16_t /* handle */, uint8_t /* status */, - uint16_t /* subrate_factor */, uint16_t /* peripheral_latency */, - uint16_t /* cont_num */, uint16_t /* timeout */) {}}; + uint16_t peripheral_latency, uint16_t cont_num, uint16_t timeout)> + body{[](uint16_t /* handle */, uint8_t /* status */, uint16_t /* subrate_factor */, + uint16_t /* peripheral_latency */, uint16_t /* cont_num */, + uint16_t /* timeout */) {}}; void operator()(uint16_t handle, uint8_t status, uint16_t subrate_factor, - uint16_t peripheral_latency, uint16_t cont_num, - uint16_t timeout) { + uint16_t peripheral_latency, uint16_t cont_num, uint16_t timeout) { body(handle, status, subrate_factor, peripheral_latency, cont_num, timeout); - }; + } }; -extern struct l2cble_process_subrate_change_evt - l2cble_process_subrate_change_evt; +extern struct l2cble_process_subrate_change_evt l2cble_process_subrate_change_evt; } // namespace stack_l2cap_ble } // namespace mock diff --git a/system/test/mock/mock_stack_l2cap_link.cc b/system/test/mock/mock_stack_l2cap_link.cc index ab3714e44e1..224c37a64d2 100644 --- a/system/test/mock/mock_stack_l2cap_link.cc +++ b/system/test/mock/mock_stack_l2cap_link.cc @@ -44,9 +44,7 @@ tL2C_CCB* l2cu_get_next_channel_in_rr(tL2C_LCB* /* p_lcb */) { void l2c_OnHciModeChangeSendPendingPackets(RawAddress /* remote */) { inc_func_call_count(__func__); } -void l2c_info_resp_timer_timeout(void* /* data */) { - inc_func_call_count(__func__); -} +void l2c_info_resp_timer_timeout(void* /* data */) { inc_func_call_count(__func__); } void l2c_link_adjust_allocation(void) { inc_func_call_count(__func__); } void l2c_link_adjust_chnl_allocation(void) { inc_func_call_count(__func__); } void l2c_link_check_send_pkts(tL2C_LCB* /* p_lcb */, uint16_t /* local_cid */, @@ -57,31 +55,22 @@ void l2c_link_hci_conn_comp(tHCI_STATUS /* status */, uint16_t /* handle */, const RawAddress& /* p_bda */) { inc_func_call_count(__func__); } -void l2c_link_init(const uint16_t /* acl_buffer_count_classic */) { - inc_func_call_count(__func__); -} -void l2c_link_role_changed(const RawAddress* /* bd_addr */, - tHCI_ROLE /* new_role */, +void l2c_link_init(const uint16_t /* acl_buffer_count_classic */) { inc_func_call_count(__func__); } +void l2c_link_role_changed(const RawAddress* /* bd_addr */, tHCI_ROLE /* new_role */, tHCI_STATUS /* hci_status */) { inc_func_call_count(__func__); } -void l2c_link_sec_comp(const RawAddress* /* p_bda */, - tBT_TRANSPORT /* transport */, void* /* p_ref_data */, - uint8_t /* status */) { +void l2c_link_sec_comp(const RawAddress* /* p_bda */, tBT_TRANSPORT /* transport */, + void* /* p_ref_data */, uint8_t /* status */) { inc_func_call_count(__func__); } -void l2c_link_segments_xmitted(BT_HDR* /* p_msg */) { - inc_func_call_count(__func__); -} +void l2c_link_segments_xmitted(BT_HDR* /* p_msg */) { inc_func_call_count(__func__); } void l2c_link_timeout(tL2C_LCB* /* p_lcb */) { inc_func_call_count(__func__); } void l2c_packets_completed(uint16_t /* handle */, uint16_t /* num_sent */) { inc_func_call_count(__func__); } -void l2c_pin_code_request(const RawAddress& /* bd_addr */) { - inc_func_call_count(__func__); -} -void l2cble_update_sec_act(const RawAddress& /* bd_addr */, - uint16_t /* sec_act */) { +void l2c_pin_code_request(const RawAddress& /* bd_addr */) { inc_func_call_count(__func__); } +void l2cble_update_sec_act(const RawAddress& /* bd_addr */, uint16_t /* sec_act */) { inc_func_call_count(__func__); } diff --git a/system/test/mock/mock_stack_l2cap_main.cc b/system/test/mock/mock_stack_l2cap_main.cc index 5504d893257..937d9d02090 100644 --- a/system/test/mock/mock_stack_l2cap_main.cc +++ b/system/test/mock/mock_stack_l2cap_main.cc @@ -24,19 +24,14 @@ #include "stack/l2cap/l2c_int.h" #include "test/common/mock_functions.h" -tL2CAP_DW_RESULT l2c_data_write(uint16_t /* cid */, BT_HDR* /* p_data */, - uint16_t /* flags */) { +tL2CAP_DW_RESULT l2c_data_write(uint16_t /* cid */, BT_HDR* /* p_data */, uint16_t /* flags */) { inc_func_call_count(__func__); return tL2CAP_DW_RESULT::FAILED; } void l2c_ccb_timer_timeout(void* /* data */) { inc_func_call_count(__func__); } -void l2c_fcrb_ack_timer_timeout(void* /* data */) { - inc_func_call_count(__func__); -} +void l2c_fcrb_ack_timer_timeout(void* /* data */) { inc_func_call_count(__func__); } void l2c_free(void) { inc_func_call_count(__func__); } void l2c_init(void) { inc_func_call_count(__func__); } void l2c_lcb_timer_timeout(void* /* data */) { inc_func_call_count(__func__); } void l2c_rcv_acl_data(BT_HDR* /* p_msg */) { inc_func_call_count(__func__); } -void l2c_receive_hold_timer_timeout(void* /* data */) { - inc_func_call_count(__func__); -} +void l2c_receive_hold_timer_timeout(void* /* data */) { inc_func_call_count(__func__); } diff --git a/system/test/mock/mock_stack_l2cap_utils.cc b/system/test/mock/mock_stack_l2cap_utils.cc index 5cb8637fd8e..56030a7c56f 100644 --- a/system/test/mock/mock_stack_l2cap_utils.cc +++ b/system/test/mock/mock_stack_l2cap_utils.cc @@ -26,13 +26,12 @@ #include "test/common/mock_functions.h" #include "types/raw_address.h" -BT_HDR* l2cu_build_header(tL2C_LCB* /* p_lcb */, uint16_t /* len */, - uint8_t /* cmd */, uint8_t /* signal_id */) { +BT_HDR* l2cu_build_header(tL2C_LCB* /* p_lcb */, uint16_t /* len */, uint8_t /* cmd */, + uint8_t /* signal_id */) { inc_func_call_count(__func__); return nullptr; } -bool l2c_is_cmd_rejected(uint8_t /* cmd_code */, uint8_t /* signal_id */, - tL2C_LCB* /* p_lcb */) { +bool l2c_is_cmd_rejected(uint8_t /* cmd_code */, uint8_t /* signal_id */, tL2C_LCB* /* p_lcb */) { inc_func_call_count(__func__); return false; } @@ -44,8 +43,7 @@ bool l2cu_create_conn_le(tL2C_LCB* /* p_lcb */, uint8_t /* initiating_phys */) { inc_func_call_count(__func__); return false; } -bool l2cu_initialize_fixed_ccb(tL2C_LCB* /* p_lcb */, - uint16_t /* fixed_cid */) { +bool l2cu_initialize_fixed_ccb(tL2C_LCB* /* p_lcb */, uint16_t /* fixed_cid */) { inc_func_call_count(__func__); return false; } @@ -57,8 +55,7 @@ bool l2cu_lcb_disconnecting(void) { inc_func_call_count(__func__); return false; } -bool l2cu_set_acl_priority(const RawAddress& /* bd_addr */, - tL2CAP_PRIORITY /* priority */, +bool l2cu_set_acl_priority(const RawAddress& /* bd_addr */, tL2CAP_PRIORITY /* priority */, bool /* reset_after_rs */) { inc_func_call_count(__func__); return false; @@ -67,23 +64,19 @@ bool l2cu_start_post_bond_timer(uint16_t /* handle */) { inc_func_call_count(__func__); return false; } -tL2C_CCB* l2cu_allocate_ccb(tL2C_LCB* /* p_lcb */, uint16_t /* cid */, - bool /* is_eatt */) { +tL2C_CCB* l2cu_allocate_ccb(tL2C_LCB* /* p_lcb */, uint16_t /* cid */, bool /* is_eatt */) { inc_func_call_count(__func__); return nullptr; } -tL2C_CCB* l2cu_find_ccb_by_cid(tL2C_LCB* /* p_lcb */, - uint16_t /* local_cid */) { +tL2C_CCB* l2cu_find_ccb_by_cid(tL2C_LCB* /* p_lcb */, uint16_t /* local_cid */) { inc_func_call_count(__func__); return nullptr; } -tL2C_CCB* l2cu_find_ccb_by_remote_cid(tL2C_LCB* /* p_lcb */, - uint16_t /* remote_cid */) { +tL2C_CCB* l2cu_find_ccb_by_remote_cid(tL2C_LCB* /* p_lcb */, uint16_t /* remote_cid */) { inc_func_call_count(__func__); return nullptr; } -tL2C_LCB* l2cu_allocate_lcb(const RawAddress& /* p_bd_addr */, - bool /* is_bonding */, +tL2C_LCB* l2cu_allocate_lcb(const RawAddress& /* p_bd_addr */, bool /* is_bonding */, tBT_TRANSPORT /* transport */) { inc_func_call_count(__func__); return nullptr; @@ -121,53 +114,32 @@ uint8_t l2cu_get_num_hi_priority(void) { inc_func_call_count(__func__); return 0; } -uint8_t l2cu_process_peer_cfg_req(tL2C_CCB* /* p_ccb */, - tL2CAP_CFG_INFO* /* p_cfg */) { +uint8_t l2cu_process_peer_cfg_req(tL2C_CCB* /* p_ccb */, tL2CAP_CFG_INFO* /* p_cfg */) { inc_func_call_count(__func__); return 0; } void l2cu_adj_id(tL2C_LCB* /* p_lcb */) { inc_func_call_count(__func__); } -void l2cu_adjust_out_mps(tL2C_CCB* /* p_ccb */) { - inc_func_call_count(__func__); -} -void l2cu_change_pri_ccb(tL2C_CCB* /* p_ccb */, - tL2CAP_CHNL_PRIORITY /* priority */) { - inc_func_call_count(__func__); -} -void l2cu_check_channel_congestion(tL2C_CCB* /* p_ccb */) { - inc_func_call_count(__func__); -} -void l2cu_create_conn_after_switch(tL2C_LCB* /* p_lcb */) { - inc_func_call_count(__func__); -} -void l2cu_create_conn_br_edr(tL2C_LCB* /* p_lcb */) { +void l2cu_adjust_out_mps(tL2C_CCB* /* p_ccb */) { inc_func_call_count(__func__); } +void l2cu_change_pri_ccb(tL2C_CCB* /* p_ccb */, tL2CAP_CHNL_PRIORITY /* priority */) { inc_func_call_count(__func__); } +void l2cu_check_channel_congestion(tL2C_CCB* /* p_ccb */) { inc_func_call_count(__func__); } +void l2cu_create_conn_after_switch(tL2C_LCB* /* p_lcb */) { inc_func_call_count(__func__); } +void l2cu_create_conn_br_edr(tL2C_LCB* /* p_lcb */) { inc_func_call_count(__func__); } void l2cu_dequeue_ccb(tL2C_CCB* /* p_ccb */) { inc_func_call_count(__func__); } void l2cu_device_reset(void) { inc_func_call_count(__func__); } -void l2cu_disconnect_chnl(tL2C_CCB* /* p_ccb */) { - inc_func_call_count(__func__); -} +void l2cu_disconnect_chnl(tL2C_CCB* /* p_ccb */) { inc_func_call_count(__func__); } void l2cu_enqueue_ccb(tL2C_CCB* /* p_ccb */) { inc_func_call_count(__func__); } -void l2cu_no_dynamic_ccbs(tL2C_LCB* /* p_lcb */) { - inc_func_call_count(__func__); -} -void l2cu_process_fixed_chnl_resp(tL2C_LCB* /* p_lcb */) { - inc_func_call_count(__func__); -} -void l2cu_process_fixed_disc_cback(tL2C_LCB* /* p_lcb */) { +void l2cu_no_dynamic_ccbs(tL2C_LCB* /* p_lcb */) { inc_func_call_count(__func__); } +void l2cu_process_fixed_chnl_resp(tL2C_LCB* /* p_lcb */) { inc_func_call_count(__func__); } +void l2cu_process_fixed_disc_cback(tL2C_LCB* /* p_lcb */) { inc_func_call_count(__func__); } +void l2cu_process_our_cfg_req(tL2C_CCB* /* p_ccb */, tL2CAP_CFG_INFO* /* p_cfg */) { inc_func_call_count(__func__); } -void l2cu_process_our_cfg_req(tL2C_CCB* /* p_ccb */, - tL2CAP_CFG_INFO* /* p_cfg */) { +void l2cu_process_our_cfg_rsp(tL2C_CCB* /* p_ccb */, tL2CAP_CFG_INFO* /* p_cfg */) { inc_func_call_count(__func__); } -void l2cu_process_our_cfg_rsp(tL2C_CCB* /* p_ccb */, - tL2CAP_CFG_INFO* /* p_cfg */) { - inc_func_call_count(__func__); -} -void l2cu_process_peer_cfg_rsp(tL2C_CCB* /* p_ccb */, - tL2CAP_CFG_INFO* /* p_cfg */) { +void l2cu_process_peer_cfg_rsp(tL2C_CCB* /* p_ccb */, tL2CAP_CFG_INFO* /* p_cfg */) { inc_func_call_count(__func__); } void l2cu_reject_ble_coc_connection(tL2C_LCB* /* p_lcb */, uint8_t /* rem_id */, @@ -178,45 +150,36 @@ void l2cu_reject_ble_connection(tL2C_CCB* /* p_ccb */, uint8_t /* rem_id */, uint16_t /* result */) { inc_func_call_count(__func__); } -void l2cu_reject_connection(tL2C_LCB* /* p_lcb */, uint16_t /* remote_cid */, - uint8_t /* rem_id */, uint16_t /* result */) { - inc_func_call_count(__func__); -} -void l2cu_reject_credit_based_conn_req(tL2C_LCB* /* p_lcb */, - uint8_t /* rem_id */, - uint8_t /* num_of_channels */, - uint16_t /* result */) { +void l2cu_reject_connection(tL2C_LCB* /* p_lcb */, uint16_t /* remote_cid */, uint8_t /* rem_id */, + uint16_t /* result */) { inc_func_call_count(__func__); } -void l2cu_release_ble_rcb(tL2C_RCB* /* p_rcb */) { +void l2cu_reject_credit_based_conn_req(tL2C_LCB* /* p_lcb */, uint8_t /* rem_id */, + uint8_t /* num_of_channels */, uint16_t /* result */) { inc_func_call_count(__func__); } +void l2cu_release_ble_rcb(tL2C_RCB* /* p_rcb */) { inc_func_call_count(__func__); } void l2cu_release_ccb(tL2C_CCB* /* p_ccb */) { inc_func_call_count(__func__); } void l2cu_release_lcb(tL2C_LCB* /* p_lcb */) { inc_func_call_count(__func__); } void l2cu_release_rcb(tL2C_RCB* /* p_rcb */) { inc_func_call_count(__func__); } -void l2cu_resubmit_pending_sec_req(const RawAddress* /* p_bda */) { - inc_func_call_count(__func__); -} +void l2cu_resubmit_pending_sec_req(const RawAddress* /* p_bda */) { inc_func_call_count(__func__); } void l2cu_send_ble_reconfig_rsp(tL2C_LCB* /* p_lcb */, uint8_t /* rem_id */, uint16_t /* result */) { inc_func_call_count(__func__); } -void l2cu_send_credit_based_reconfig_req(tL2C_CCB* /* p_ccb */, - tL2CAP_LE_CFG_INFO* /* p_cfg */) { +void l2cu_send_credit_based_reconfig_req(tL2C_CCB* /* p_ccb */, tL2CAP_LE_CFG_INFO* /* p_cfg */) { inc_func_call_count(__func__); } void l2cu_send_peer_ble_credit_based_conn_req(tL2C_CCB* /* p_ccb */) { inc_func_call_count(__func__); } -void l2cu_send_peer_ble_credit_based_conn_res(tL2C_CCB* /* p_ccb */, - uint16_t /* result */) { +void l2cu_send_peer_ble_credit_based_conn_res(tL2C_CCB* /* p_ccb */, uint16_t /* result */) { inc_func_call_count(__func__); } void l2cu_send_peer_ble_credit_based_disconn_req(tL2C_CCB* /* p_ccb */) { inc_func_call_count(__func__); } -void l2cu_send_peer_ble_flow_control_credit(tL2C_CCB* /* p_ccb */, - uint16_t /* credit_value */) { +void l2cu_send_peer_ble_flow_control_credit(tL2C_CCB* /* p_ccb */, uint16_t /* credit_value */) { inc_func_call_count(__func__); } void l2cu_send_peer_ble_par_req(tL2C_LCB* /* p_lcb */, uint16_t /* min_int */, @@ -228,49 +191,38 @@ void l2cu_send_peer_ble_par_rsp(tL2C_LCB* /* p_lcb */, uint16_t /* reason */, uint8_t /* rem_id */) { inc_func_call_count(__func__); } -void l2cu_send_peer_cmd_reject(tL2C_LCB* /* p_lcb */, uint16_t /* reason */, - uint8_t /* rem_id */, uint16_t /* p1 */, - uint16_t /* p2 */) { +void l2cu_send_peer_cmd_reject(tL2C_LCB* /* p_lcb */, uint16_t /* reason */, uint8_t /* rem_id */, + uint16_t /* p1 */, uint16_t /* p2 */) { inc_func_call_count(__func__); } void l2cu_send_peer_config_rej(tL2C_CCB* /* p_ccb */, uint8_t* /* p_data */, - uint16_t /* data_len */, - uint16_t /* rej_len */) { - inc_func_call_count(__func__); -} -void l2cu_send_peer_config_req(tL2C_CCB* /* p_ccb */, - tL2CAP_CFG_INFO* /* p_cfg */) { + uint16_t /* data_len */, uint16_t /* rej_len */) { inc_func_call_count(__func__); } -void l2cu_send_peer_config_rsp(tL2C_CCB* /* p_ccb */, - tL2CAP_CFG_INFO* /* p_cfg */) { +void l2cu_send_peer_config_req(tL2C_CCB* /* p_ccb */, tL2CAP_CFG_INFO* /* p_cfg */) { inc_func_call_count(__func__); } -void l2cu_send_peer_connect_req(tL2C_CCB* /* p_ccb */) { +void l2cu_send_peer_config_rsp(tL2C_CCB* /* p_ccb */, tL2CAP_CFG_INFO* /* p_cfg */) { inc_func_call_count(__func__); } +void l2cu_send_peer_connect_req(tL2C_CCB* /* p_ccb */) { inc_func_call_count(__func__); } void l2cu_send_peer_connect_rsp(tL2C_CCB* /* p_ccb */, uint16_t /* result */, uint16_t /* status */) { inc_func_call_count(__func__); } -void l2cu_send_peer_credit_based_conn_req(tL2C_CCB* /* p_ccb */) { - inc_func_call_count(__func__); -} -void l2cu_send_peer_credit_based_conn_res( - tL2C_CCB* /* p_ccb */, std::vector& /* accepted_cids */, - uint16_t /* result */) { - inc_func_call_count(__func__); -} -void l2cu_send_peer_disc_req(tL2C_CCB* /* p_ccb */) { +void l2cu_send_peer_credit_based_conn_req(tL2C_CCB* /* p_ccb */) { inc_func_call_count(__func__); } +void l2cu_send_peer_credit_based_conn_res(tL2C_CCB* /* p_ccb */, + std::vector& /* accepted_cids */, + uint16_t /* result */) { inc_func_call_count(__func__); } +void l2cu_send_peer_disc_req(tL2C_CCB* /* p_ccb */) { inc_func_call_count(__func__); } void l2cu_send_peer_disc_rsp(tL2C_LCB* /* p_lcb */, uint8_t /* remote_id */, - uint16_t /* local_cid */, - uint16_t /* remote_cid */) { + uint16_t /* local_cid */, uint16_t /* remote_cid */) { inc_func_call_count(__func__); } -void l2cu_send_peer_echo_rsp(tL2C_LCB* /* p_lcb */, uint8_t /* signal_id */, - uint8_t* /* p_data */, uint16_t /* data_len */) { +void l2cu_send_peer_echo_rsp(tL2C_LCB* /* p_lcb */, uint8_t /* signal_id */, uint8_t* /* p_data */, + uint16_t /* data_len */) { inc_func_call_count(__func__); } void l2cu_send_peer_info_req(tL2C_LCB* /* p_lcb */, uint16_t /* info_type */) { @@ -283,14 +235,10 @@ void l2cu_send_peer_info_rsp(tL2C_LCB* /* p_lcb */, uint8_t /* remote_id */, void l2cu_set_acl_hci_header(BT_HDR* /* p_buf */, tL2C_CCB* /* p_ccb */) { inc_func_call_count(__func__); } -void l2cu_set_lcb_handle(struct t_l2c_linkcb& /* p_lcb */, - uint16_t /* handle */) { - inc_func_call_count(__func__); -} -void l2cu_set_non_flushable_pbf(bool /* is_supported */) { +void l2cu_set_lcb_handle(struct t_l2c_linkcb& /* p_lcb */, uint16_t /* handle */) { inc_func_call_count(__func__); } -void l2cu_update_lcb_4_bonding(const RawAddress& /* p_bd_addr */, - bool /* is_bonding */) { +void l2cu_set_non_flushable_pbf(bool /* is_supported */) { inc_func_call_count(__func__); } +void l2cu_update_lcb_4_bonding(const RawAddress& /* p_bd_addr */, bool /* is_bonding */) { inc_func_call_count(__func__); } diff --git a/system/test/mock/mock_stack_metrics_logging.cc b/system/test/mock/mock_stack_metrics_logging.cc index ed2225c4ecc..6c21688de2b 100644 --- a/system/test/mock/mock_stack_metrics_logging.cc +++ b/system/test/mock/mock_stack_metrics_logging.cc @@ -54,84 +54,73 @@ struct log_mmc_transcode_rtt_stats log_mmc_transcode_rtt_stats; } // namespace test // Mocked functions, if any -void log_classic_pairing_event(const RawAddress& address, uint16_t handle, - uint32_t hci_cmd, uint16_t hci_event, - uint16_t cmd_status, uint16_t reason_code, +void log_classic_pairing_event(const RawAddress& address, uint16_t handle, uint32_t hci_cmd, + uint16_t hci_event, uint16_t cmd_status, uint16_t reason_code, int64_t event_value) { inc_func_call_count(__func__); test::mock::stack_metrics_logging::log_classic_pairing_event( - address, handle, hci_cmd, hci_event, cmd_status, reason_code, - event_value); + address, handle, hci_cmd, hci_event, cmd_status, reason_code, event_value); } -void log_link_layer_connection_event( - const RawAddress* address, uint32_t connection_handle, - android::bluetooth::DirectionEnum direction, uint16_t link_type, - uint32_t hci_cmd, uint16_t hci_event, uint16_t hci_ble_event, - uint16_t cmd_status, uint16_t reason_code) { +void log_link_layer_connection_event(const RawAddress* address, uint32_t connection_handle, + android::bluetooth::DirectionEnum direction, + uint16_t link_type, uint32_t hci_cmd, uint16_t hci_event, + uint16_t hci_ble_event, uint16_t cmd_status, + uint16_t reason_code) { inc_func_call_count(__func__); test::mock::stack_metrics_logging::log_link_layer_connection_event( - address, connection_handle, direction, link_type, hci_cmd, hci_event, - hci_ble_event, cmd_status, reason_code); + address, connection_handle, direction, link_type, hci_cmd, hci_event, hci_ble_event, + cmd_status, reason_code); } void log_smp_pairing_event(const RawAddress& address, uint16_t smp_cmd, - android::bluetooth::DirectionEnum direction, - uint16_t smp_fail_reason) { + android::bluetooth::DirectionEnum direction, uint16_t smp_fail_reason) { inc_func_call_count(__func__); - test::mock::stack_metrics_logging::log_smp_pairing_event( - address, smp_cmd, direction, smp_fail_reason); + test::mock::stack_metrics_logging::log_smp_pairing_event(address, smp_cmd, direction, + smp_fail_reason); } -void log_sdp_attribute(const RawAddress& address, uint16_t protocol_uuid, - uint16_t attribute_id, size_t attribute_size, - const char* attribute_value) { +void log_sdp_attribute(const RawAddress& address, uint16_t protocol_uuid, uint16_t attribute_id, + size_t attribute_size, const char* attribute_value) { inc_func_call_count(__func__); - test::mock::stack_metrics_logging::log_sdp_attribute( - address, protocol_uuid, attribute_id, attribute_size, attribute_value); + test::mock::stack_metrics_logging::log_sdp_attribute(address, protocol_uuid, attribute_id, + attribute_size, attribute_value); } void log_manufacturer_info(const RawAddress& address, android::bluetooth::DeviceInfoSrcEnum source_type, - const std::string& source_name, - const std::string& manufacturer, - const std::string& model, - const std::string& hardware_version, + const std::string& source_name, const std::string& manufacturer, + const std::string& model, const std::string& hardware_version, const std::string& software_version) { inc_func_call_count(__func__); - test::mock::stack_metrics_logging::log_manufacturer_info( - address, source_type, source_name, manufacturer, model, hardware_version, - software_version); + test::mock::stack_metrics_logging::log_manufacturer_info(address, source_type, source_name, + manufacturer, model, hardware_version, + software_version); } void log_manufacturer_info(const RawAddress& address, android::bluetooth::AddressTypeEnum address_type, android::bluetooth::DeviceInfoSrcEnum source_type, - const std::string& source_name, - const std::string& manufacturer, - const std::string& model, - const std::string& hardware_version, + const std::string& source_name, const std::string& manufacturer, + const std::string& model, const std::string& hardware_version, const std::string& software_version) { inc_func_call_count(__func__); - test::mock::stack_metrics_logging::log_manufacturer_info( - address, address_type, source_type, source_name, manufacturer, model, - hardware_version, software_version); + test::mock::stack_metrics_logging::log_manufacturer_info(address, address_type, source_type, + source_name, manufacturer, model, + hardware_version, software_version); } -void log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum key, - int64_t value) { +void log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum key, int64_t value) { inc_func_call_count(__func__); test::mock::stack_metrics_logging::log_counter_metrics(key, value); } -void log_hfp_audio_packet_loss_stats(const RawAddress& address, - int num_decoded_frames, - double packet_loss_ratio, - uint16_t codec_type) { +void log_hfp_audio_packet_loss_stats(const RawAddress& address, int num_decoded_frames, + double packet_loss_ratio, uint16_t codec_type) { inc_func_call_count(__func__); - test::mock::stack_metrics_logging::log_hfp_audio_packet_loss_stats( - address, num_decoded_frames, packet_loss_ratio, codec_type); + test::mock::stack_metrics_logging::log_hfp_audio_packet_loss_stats(address, num_decoded_frames, + packet_loss_ratio, codec_type); } -void log_mmc_transcode_rtt_stats(int maximum_rtt, double mean_rtt, - int num_requests, int codec_type) { +void log_mmc_transcode_rtt_stats(int maximum_rtt, double mean_rtt, int num_requests, + int codec_type) { inc_func_call_count(__func__); - test::mock::stack_metrics_logging::log_mmc_transcode_rtt_stats( - maximum_rtt, mean_rtt, num_requests, codec_type); + test::mock::stack_metrics_logging::log_mmc_transcode_rtt_stats(maximum_rtt, mean_rtt, + num_requests, codec_type); } // END mockcify generation diff --git a/system/test/mock/mock_stack_metrics_logging.h b/system/test/mock/mock_stack_metrics_logging.h index ca938a698e6..55da3f75491 100644 --- a/system/test/mock/mock_stack_metrics_logging.h +++ b/system/test/mock/mock_stack_metrics_logging.h @@ -41,19 +41,16 @@ namespace stack_metrics_logging { // uint16_t hci_event, uint16_t cmd_status, uint16_t reason_code, int64_t // event_value Returns: void struct log_classic_pairing_event { - std::function - body{[](const RawAddress& /* address */, uint16_t /* handle */, - uint32_t /* hci_cmd */, uint16_t /* hci_event */, - uint16_t /* cmd_status */, uint16_t /* reason_code */, - int64_t /* event_value */) {}}; - void operator()(const RawAddress& address, uint16_t handle, uint32_t hci_cmd, - uint16_t hci_event, uint16_t cmd_status, uint16_t reason_code, - int64_t event_value) { - body(address, handle, hci_cmd, hci_event, cmd_status, reason_code, - event_value); - }; + std::function + body{[](const RawAddress& /* address */, uint16_t /* handle */, uint32_t /* hci_cmd */, + uint16_t /* hci_event */, uint16_t /* cmd_status */, uint16_t /* reason_code */, + int64_t /* event_value */) {}}; + void operator()(const RawAddress& address, uint16_t handle, uint32_t hci_cmd, uint16_t hci_event, + uint16_t cmd_status, uint16_t reason_code, int64_t event_value) { + body(address, handle, hci_cmd, hci_event, cmd_status, reason_code, event_value); + } }; extern struct log_classic_pairing_event log_classic_pairing_event; // Name: log_link_layer_connection_event @@ -63,23 +60,20 @@ extern struct log_classic_pairing_event log_classic_pairing_event; // uint16_t reason_code Returns: void struct log_link_layer_connection_event { std::function - body{[](const RawAddress* /* address */, uint32_t /* connection_handle */, - android::bluetooth::DirectionEnum /* direction */, - uint16_t /* link_type */, uint32_t /* hci_cmd */, - uint16_t /* hci_event */, uint16_t /* hci_ble_event */, - uint16_t /* cmd_status */, uint16_t /* reason_code */) {}}; + android::bluetooth::DirectionEnum direction, uint16_t link_type, + uint32_t hci_cmd, uint16_t hci_event, uint16_t hci_ble_event, + uint16_t cmd_status, uint16_t reason_code)> + body{[](const RawAddress* /* address */, uint32_t /* connection_handle */, + android::bluetooth::DirectionEnum /* direction */, uint16_t /* link_type */, + uint32_t /* hci_cmd */, uint16_t /* hci_event */, uint16_t /* hci_ble_event */, + uint16_t /* cmd_status */, uint16_t /* reason_code */) {}}; void operator()(const RawAddress* address, uint32_t connection_handle, - android::bluetooth::DirectionEnum direction, - uint16_t link_type, uint32_t hci_cmd, uint16_t hci_event, - uint16_t hci_ble_event, uint16_t cmd_status, + android::bluetooth::DirectionEnum direction, uint16_t link_type, uint32_t hci_cmd, + uint16_t hci_event, uint16_t hci_ble_event, uint16_t cmd_status, uint16_t reason_code) { - body(address, connection_handle, direction, link_type, hci_cmd, hci_event, - hci_ble_event, cmd_status, reason_code); - }; + body(address, connection_handle, direction, link_type, hci_cmd, hci_event, hci_ble_event, + cmd_status, reason_code); + } }; extern struct log_link_layer_connection_event log_link_layer_connection_event; // Name: log_smp_pairing_event @@ -88,16 +82,14 @@ extern struct log_link_layer_connection_event log_link_layer_connection_event; // void struct log_smp_pairing_event { std::function - body{[](const RawAddress& /* address */, uint16_t /* smp_cmd */, - android::bluetooth::DirectionEnum /* direction */, - uint16_t /* smp_fail_reason */) {}}; + android::bluetooth::DirectionEnum direction, uint16_t smp_fail_reason)> + body{[](const RawAddress& /* address */, uint16_t /* smp_cmd */, + android::bluetooth::DirectionEnum /* direction */, + uint16_t /* smp_fail_reason */) {}}; void operator()(const RawAddress& address, uint16_t smp_cmd, - android::bluetooth::DirectionEnum direction, - uint16_t smp_fail_reason) { + android::bluetooth::DirectionEnum direction, uint16_t smp_fail_reason) { body(address, smp_cmd, direction, smp_fail_reason); - }; + } }; extern struct log_smp_pairing_event log_smp_pairing_event; // Name: log_sdp_attribute @@ -105,17 +97,15 @@ extern struct log_smp_pairing_event log_smp_pairing_event; // attribute_id, size_t attribute_size, const char* attribute_value Returns: // void struct log_sdp_attribute { - std::function - body{[](const RawAddress& /* address */, uint16_t /* protocol_uuid */, - uint16_t /* attribute_id */, size_t /* attribute_size */, - const char* /* attribute_value */) {}}; - void operator()(const RawAddress& address, uint16_t protocol_uuid, - uint16_t attribute_id, size_t attribute_size, - const char* attribute_value) { + std::function + body{[](const RawAddress& /* address */, uint16_t /* protocol_uuid */, + uint16_t /* attribute_id */, size_t /* attribute_size */, + const char* /* attribute_value */) {}}; + void operator()(const RawAddress& address, uint16_t protocol_uuid, uint16_t attribute_id, + size_t attribute_size, const char* attribute_value) { body(address, protocol_uuid, attribute_id, attribute_size, attribute_value); - }; + } }; extern struct log_sdp_attribute log_sdp_attribute; // Name: log_manufacturer_info @@ -124,92 +114,74 @@ extern struct log_sdp_attribute log_sdp_attribute; // const std::string& model, const std::string& hardware_version, const // std::string& software_version Returns: void struct log_manufacturer_info { - std::function - body2{[](const RawAddress& /* address */, - android::bluetooth::AddressTypeEnum /* address_type */, - android::bluetooth::DeviceInfoSrcEnum /* source_type */, - const std::string& /* source_name */, - const std::string& /* manufacturer */, - const std::string& /* model */, - const std::string& /* hardware_version */, - const std::string& /* software_version */) {}}; - void operator()(const RawAddress& address, - android::bluetooth::AddressTypeEnum address_type, - android::bluetooth::DeviceInfoSrcEnum source_type, - const std::string& source_name, + body2{[](const RawAddress& /* address */, + android::bluetooth::AddressTypeEnum /* address_type */, + android::bluetooth::DeviceInfoSrcEnum /* source_type */, + const std::string& /* source_name */, const std::string& /* manufacturer */, + const std::string& /* model */, const std::string& /* hardware_version */, + const std::string& /* software_version */) {}}; + void operator()(const RawAddress& address, android::bluetooth::AddressTypeEnum address_type, + android::bluetooth::DeviceInfoSrcEnum source_type, const std::string& source_name, const std::string& manufacturer, const std::string& model, - const std::string& hardware_version, - const std::string& software_version) { - body2(address, address_type, source_type, source_name, manufacturer, model, - hardware_version, software_version); - }; - std::function - body{[](const RawAddress& /* address */, - android::bluetooth::DeviceInfoSrcEnum /* source_type */, - const std::string& /* source_name */, - const std::string& /* manufacturer */, - const std::string& /* model */, - const std::string& /* hardware_version */, - const std::string& /* software_version */) {}}; - void operator()(const RawAddress& address, - android::bluetooth::DeviceInfoSrcEnum source_type, - const std::string& source_name, - const std::string& manufacturer, const std::string& model, - const std::string& hardware_version, + body{[](const RawAddress& /* address */, + android::bluetooth::DeviceInfoSrcEnum /* source_type */, + const std::string& /* source_name */, const std::string& /* manufacturer */, + const std::string& /* model */, const std::string& /* hardware_version */, + const std::string& /* software_version */) {}}; + void operator()(const RawAddress& address, android::bluetooth::DeviceInfoSrcEnum source_type, + const std::string& source_name, const std::string& manufacturer, + const std::string& model, const std::string& hardware_version, const std::string& software_version) { - body(address, source_type, source_name, manufacturer, model, - hardware_version, software_version); - }; + body(address, source_type, source_name, manufacturer, model, hardware_version, + software_version); + } }; extern struct log_manufacturer_info log_manufacturer_info; // Name: log_counter_metrics struct log_counter_metrics { - std::function - body{[](android::bluetooth::CodePathCounterKeyEnum /* key */, - int64_t /* value */) {}}; - void operator()(android::bluetooth::CodePathCounterKeyEnum key, - int64_t value) { + std::function body{ + [](android::bluetooth::CodePathCounterKeyEnum /* key */, int64_t /* value */) {}}; + void operator()(android::bluetooth::CodePathCounterKeyEnum key, int64_t value) { body(key, value); - }; + } }; extern struct log_counter_metrics log_counter_metrics; // Name: log_hfp_audio_packet_loss_stats struct log_hfp_audio_packet_loss_stats { - std::function - body{[](const RawAddress& /* address */, int /* num_decoded_frames */, - double /* packet_loss_ratio */, uint16_t /* codec_type */) {}}; - void operator()(const RawAddress& address, int num_decoded_frames, - double packet_loss_ratio, uint16_t codec_type) { + std::function + body{[](const RawAddress& /* address */, int /* num_decoded_frames */, + double /* packet_loss_ratio */, uint16_t /* codec_type */) {}}; + void operator()(const RawAddress& address, int num_decoded_frames, double packet_loss_ratio, + uint16_t codec_type) { body(address, num_decoded_frames, packet_loss_ratio, codec_type); - }; + } }; extern struct log_hfp_audio_packet_loss_stats log_hfp_audio_packet_loss_stats; // Name: log_mmc_transcode_rtt_stats struct log_mmc_transcode_rtt_stats { - std::function - body{[](int /* maximum_rtt */, double /* mean_rtt */, - int /* num_requests */, int /* codec_type */) {}}; - void operator()(int maximum_rtt, double mean_rtt, int num_requests, - int codec_type) { + std::function body{ + [](int /* maximum_rtt */, double /* mean_rtt */, int /* num_requests */, + int /* codec_type */) {}}; + void operator()(int maximum_rtt, double mean_rtt, int num_requests, int codec_type) { body(maximum_rtt, mean_rtt, num_requests, codec_type); - }; + } }; extern struct log_mmc_transcode_rtt_stats log_mmc_transcode_rtt_stats; } // namespace stack_metrics_logging diff --git a/system/test/mock/mock_stack_pan_api.cc b/system/test/mock/mock_stack_pan_api.cc index 4722d94ddb9..be5359c6072 100644 --- a/system/test/mock/mock_stack_pan_api.cc +++ b/system/test/mock/mock_stack_pan_api.cc @@ -53,48 +53,40 @@ struct PAN_Register PAN_Register; } // namespace test // Mocked functions, if any -tPAN_RESULT PAN_Connect(const RawAddress& rem_bda, tPAN_ROLE src_role, - tPAN_ROLE dst_role, uint16_t* handle) { +tPAN_RESULT PAN_Connect(const RawAddress& rem_bda, tPAN_ROLE src_role, tPAN_ROLE dst_role, + uint16_t* handle) { inc_func_call_count(__func__); - return test::mock::stack_pan_api::PAN_Connect(rem_bda, src_role, dst_role, - handle); + return test::mock::stack_pan_api::PAN_Connect(rem_bda, src_role, dst_role, handle); } tPAN_RESULT PAN_Disconnect(uint16_t handle) { inc_func_call_count(__func__); return test::mock::stack_pan_api::PAN_Disconnect(handle); } tPAN_RESULT PAN_SetMulticastFilters(uint16_t handle, uint16_t num_mcast_filters, - uint8_t* p_start_array, - uint8_t* p_end_array) { + uint8_t* p_start_array, uint8_t* p_end_array) { inc_func_call_count(__func__); - return test::mock::stack_pan_api::PAN_SetMulticastFilters( - handle, num_mcast_filters, p_start_array, p_end_array); + return test::mock::stack_pan_api::PAN_SetMulticastFilters(handle, num_mcast_filters, + p_start_array, p_end_array); } -tPAN_RESULT PAN_SetProtocolFilters(uint16_t handle, uint16_t num_filters, - uint16_t* p_start_array, +tPAN_RESULT PAN_SetProtocolFilters(uint16_t handle, uint16_t num_filters, uint16_t* p_start_array, uint16_t* p_end_array) { inc_func_call_count(__func__); - return test::mock::stack_pan_api::PAN_SetProtocolFilters( - handle, num_filters, p_start_array, p_end_array); + return test::mock::stack_pan_api::PAN_SetProtocolFilters(handle, num_filters, p_start_array, + p_end_array); } -tPAN_RESULT PAN_SetRole(uint8_t role, std::string p_user_name, - std::string p_nap_name) { +tPAN_RESULT PAN_SetRole(uint8_t role, std::string p_user_name, std::string p_nap_name) { inc_func_call_count(__func__); return test::mock::stack_pan_api::PAN_SetRole(role, p_user_name, p_nap_name); } -tPAN_RESULT PAN_Write(uint16_t handle, const RawAddress& dst, - const RawAddress& src, uint16_t protocol, uint8_t* p_data, - uint16_t len, bool ext) { +tPAN_RESULT PAN_Write(uint16_t handle, const RawAddress& dst, const RawAddress& src, + uint16_t protocol, uint8_t* p_data, uint16_t len, bool ext) { inc_func_call_count(__func__); - return test::mock::stack_pan_api::PAN_Write(handle, dst, src, protocol, - p_data, len, ext); + return test::mock::stack_pan_api::PAN_Write(handle, dst, src, protocol, p_data, len, ext); } -tPAN_RESULT PAN_WriteBuf(uint16_t handle, const RawAddress& dst, - const RawAddress& src, uint16_t protocol, - BT_HDR* p_buf, bool ext) { +tPAN_RESULT PAN_WriteBuf(uint16_t handle, const RawAddress& dst, const RawAddress& src, + uint16_t protocol, BT_HDR* p_buf, bool ext) { inc_func_call_count(__func__); - return test::mock::stack_pan_api::PAN_WriteBuf(handle, dst, src, protocol, - p_buf, ext); + return test::mock::stack_pan_api::PAN_WriteBuf(handle, dst, src, protocol, p_buf, ext); } void PAN_Deregister(void) { inc_func_call_count(__func__); diff --git a/system/test/mock/mock_stack_pan_api.h b/system/test/mock/mock_stack_pan_api.h index b4ede2b3729..ec47de06e40 100644 --- a/system/test/mock/mock_stack_pan_api.h +++ b/system/test/mock/mock_stack_pan_api.h @@ -39,15 +39,14 @@ namespace stack_pan_api { // Params: const RawAddress& rem_bda, tPAN_ROLE src_role, tPAN_ROLE dst_role, // uint16_t* handle Returns: tPAN_RESULT struct PAN_Connect { - std::function - body{[](const RawAddress& /* rem_bda */, tPAN_ROLE /* src_role */, - tPAN_ROLE /* dst_role */, - uint16_t* /* handle */) { return PAN_SUCCESS; }}; - tPAN_RESULT operator()(const RawAddress& rem_bda, tPAN_ROLE src_role, - tPAN_ROLE dst_role, uint16_t* handle) { + std::function + body{[](const RawAddress& /* rem_bda */, tPAN_ROLE /* src_role */, + tPAN_ROLE /* dst_role */, uint16_t* /* handle */) { return PAN_SUCCESS; }}; + tPAN_RESULT operator()(const RawAddress& rem_bda, tPAN_ROLE src_role, tPAN_ROLE dst_role, + uint16_t* handle) { return body(rem_bda, src_role, dst_role, handle); - }; + } }; extern struct PAN_Connect PAN_Connect; // Name: PAN_Disconnect @@ -55,52 +54,50 @@ extern struct PAN_Connect PAN_Connect; // Returns: tPAN_RESULT struct PAN_Disconnect { std::function body{ - [](uint16_t /* handle */) { return PAN_SUCCESS; }}; - tPAN_RESULT operator()(uint16_t handle) { return body(handle); }; + [](uint16_t /* handle */) { return PAN_SUCCESS; }}; + tPAN_RESULT operator()(uint16_t handle) { return body(handle); } }; extern struct PAN_Disconnect PAN_Disconnect; // Name: PAN_SetMulticastFilters // Params: uint16_t handle, uint16_t num_mcast_filters, uint8_t* p_start_array, // uint8_t* p_end_array Returns: tPAN_RESULT struct PAN_SetMulticastFilters { - std::function - body{[](uint16_t /* handle */, uint16_t /* num_mcast_filters */, - uint8_t* /* p_start_array */, - uint8_t* /* p_end_array */) { return PAN_SUCCESS; }}; - tPAN_RESULT operator()(uint16_t handle, uint16_t num_mcast_filters, - uint8_t* p_start_array, uint8_t* p_end_array) { + std::function + body{[](uint16_t /* handle */, uint16_t /* num_mcast_filters */, + uint8_t* /* p_start_array */, + uint8_t* /* p_end_array */) { return PAN_SUCCESS; }}; + tPAN_RESULT operator()(uint16_t handle, uint16_t num_mcast_filters, uint8_t* p_start_array, + uint8_t* p_end_array) { return body(handle, num_mcast_filters, p_start_array, p_end_array); - }; + } }; extern struct PAN_SetMulticastFilters PAN_SetMulticastFilters; // Name: PAN_SetProtocolFilters // Params: uint16_t handle, uint16_t num_filters, uint16_t* p_start_array, // uint16_t* p_end_array Returns: tPAN_RESULT struct PAN_SetProtocolFilters { - std::function - body{[](uint16_t /* handle */, uint16_t /* num_filters */, - uint16_t* /* p_start_array */, - uint16_t* /* p_end_array */) { return PAN_SUCCESS; }}; - tPAN_RESULT operator()(uint16_t handle, uint16_t num_filters, - uint16_t* p_start_array, uint16_t* p_end_array) { + std::function + body{[](uint16_t /* handle */, uint16_t /* num_filters */, uint16_t* /* p_start_array */, + uint16_t* /* p_end_array */) { return PAN_SUCCESS; }}; + tPAN_RESULT operator()(uint16_t handle, uint16_t num_filters, uint16_t* p_start_array, + uint16_t* p_end_array) { return body(handle, num_filters, p_start_array, p_end_array); - }; + } }; extern struct PAN_SetProtocolFilters PAN_SetProtocolFilters; // Name: PAN_SetRole // Params: uint8_t role, const std::string p_user_name, const std::string // p_nap_name Returns: tPAN_RESULT struct PAN_SetRole { - std::function - body{[](uint8_t /* role */, std::string /* p_user_name */, - std::string /* p_nap_name */) { return PAN_SUCCESS; }}; - tPAN_RESULT operator()(uint8_t role, std::string p_user_name, - std::string p_nap_name) { + std::function body{ + [](uint8_t /* role */, std::string /* p_user_name */, std::string /* p_nap_name */) { + return PAN_SUCCESS; + }}; + tPAN_RESULT operator()(uint8_t role, std::string p_user_name, std::string p_nap_name) { return body(role, p_user_name, p_nap_name); - }; + } }; extern struct PAN_SetRole PAN_SetRole; // Name: PAN_Write @@ -108,35 +105,30 @@ extern struct PAN_SetRole PAN_SetRole; // uint16_t protocol, uint8_t* p_data, uint16_t len, bool ext Returns: // tPAN_RESULT struct PAN_Write { - std::function - body{[](uint16_t /* handle */, const RawAddress& /* dst */, - const RawAddress& /* src */, uint16_t /* protocol */, - uint8_t* /* p_data */, uint16_t /* len */, - bool /* ext */) { return PAN_SUCCESS; }}; - tPAN_RESULT operator()(uint16_t handle, const RawAddress& dst, - const RawAddress& src, uint16_t protocol, - uint8_t* p_data, uint16_t len, bool ext) { + std::function + body{[](uint16_t /* handle */, const RawAddress& /* dst */, const RawAddress& /* src */, + uint16_t /* protocol */, uint8_t* /* p_data */, uint16_t /* len */, + bool /* ext */) { return PAN_SUCCESS; }}; + tPAN_RESULT operator()(uint16_t handle, const RawAddress& dst, const RawAddress& src, + uint16_t protocol, uint8_t* p_data, uint16_t len, bool ext) { return body(handle, dst, src, protocol, p_data, len, ext); - }; + } }; extern struct PAN_Write PAN_Write; // Name: PAN_WriteBuf // Params: uint16_t handle, const RawAddress& dst, const RawAddress& src, // uint16_t protocol, BT_HDR* p_buf, bool ext Returns: tPAN_RESULT struct PAN_WriteBuf { - std::function - body{[](uint16_t /* handle */, const RawAddress& /* dst */, - const RawAddress& /* src */, uint16_t /* protocol */, - BT_HDR* /* p_buf */, bool /* ext */) { return PAN_SUCCESS; }}; - tPAN_RESULT operator()(uint16_t handle, const RawAddress& dst, - const RawAddress& src, uint16_t protocol, - BT_HDR* p_buf, bool ext) { + std::function + body{[](uint16_t /* handle */, const RawAddress& /* dst */, const RawAddress& /* src */, + uint16_t /* protocol */, BT_HDR* /* p_buf */, + bool /* ext */) { return PAN_SUCCESS; }}; + tPAN_RESULT operator()(uint16_t handle, const RawAddress& dst, const RawAddress& src, + uint16_t protocol, BT_HDR* p_buf, bool ext) { return body(handle, dst, src, protocol, p_buf, ext); - }; + } }; extern struct PAN_WriteBuf PAN_WriteBuf; // Name: PAN_Deregister @@ -144,7 +136,7 @@ extern struct PAN_WriteBuf PAN_WriteBuf; // Returns: void struct PAN_Deregister { std::function body{[](void) { ; }}; - void operator()(void) { body(); }; + void operator()(void) { body(); } }; extern struct PAN_Deregister PAN_Deregister; // Name: PAN_Dumpsys @@ -152,7 +144,7 @@ extern struct PAN_Deregister PAN_Deregister; // Returns: void struct PAN_Dumpsys { std::function body{[](int /* fd */) { ; }}; - void operator()(int fd) { body(fd); }; + void operator()(int fd) { body(fd); } }; extern struct PAN_Dumpsys PAN_Dumpsys; // Name: PAN_Init @@ -160,16 +152,15 @@ extern struct PAN_Dumpsys PAN_Dumpsys; // Returns: void struct PAN_Init { std::function body{[](void) { ; }}; - void operator()(void) { body(); }; + void operator()(void) { body(); } }; extern struct PAN_Init PAN_Init; // Name: PAN_Register // Params: tPAN_REGISTER* p_register // Returns: void struct PAN_Register { - std::function body{ - [](tPAN_REGISTER* /* p_register */) { ; }}; - void operator()(tPAN_REGISTER* p_register) { body(p_register); }; + std::function body{[](tPAN_REGISTER* /* p_register */) { ; }}; + void operator()(tPAN_REGISTER* p_register) { body(p_register); } }; extern struct PAN_Register PAN_Register; diff --git a/system/test/mock/mock_stack_rfcomm_port_api.cc b/system/test/mock/mock_stack_rfcomm_port_api.cc index 295475112f5..d956006ec8f 100644 --- a/system/test/mock/mock_stack_rfcomm_port_api.cc +++ b/system/test/mock/mock_stack_rfcomm_port_api.cc @@ -31,8 +31,7 @@ const char* PORT_GetResultString(const uint8_t /* result_code */) { inc_func_call_count(__func__); return nullptr; } -int PORT_CheckConnection(uint16_t /* handle */, RawAddress* /* bd_addr */, - uint16_t* /* p_lcid */) { +int PORT_CheckConnection(uint16_t /* handle */, RawAddress* /* bd_addr */, uint16_t* /* p_lcid */) { inc_func_call_count(__func__); return 0; } @@ -48,18 +47,16 @@ int PORT_GetState(uint16_t /* handle */, tPORT_STATE* /* p_settings */) { inc_func_call_count(__func__); return 0; } -int PORT_ReadData(uint16_t /* handle */, char* /* p_data */, - uint16_t /* max_len */, uint16_t* /* p_len */) { +int PORT_ReadData(uint16_t /* handle */, char* /* p_data */, uint16_t /* max_len */, + uint16_t* /* p_len */) { inc_func_call_count(__func__); return 0; } -int PORT_SetDataCOCallback(uint16_t /* port_handle */, - tPORT_DATA_CO_CALLBACK* /* p_port_cb */) { +int PORT_SetDataCOCallback(uint16_t /* port_handle */, tPORT_DATA_CO_CALLBACK* /* p_port_cb */) { inc_func_call_count(__func__); return 0; } -int PORT_SetEventMaskAndCallback(uint16_t /* port_handle */, - uint32_t /* mask */, +int PORT_SetEventMaskAndCallback(uint16_t /* port_handle */, uint32_t /* mask */, tPORT_CALLBACK* /* p_port_cb */) { inc_func_call_count(__func__); return 0; @@ -68,8 +65,8 @@ int PORT_SetState(uint16_t /* handle */, tPORT_STATE* /* p_settings */) { inc_func_call_count(__func__); return 0; } -int PORT_WriteData(uint16_t /* handle */, const char* /* p_data */, - uint16_t /* max_len */, uint16_t* /* p_len */) { +int PORT_WriteData(uint16_t /* handle */, const char* /* p_data */, uint16_t /* max_len */, + uint16_t* /* p_len */) { inc_func_call_count(__func__); return 0; } @@ -77,20 +74,18 @@ int PORT_WriteDataCO(uint16_t /* handle */, int* /* p_len */) { inc_func_call_count(__func__); return 0; } -int RFCOMM_CreateConnectionWithSecurity( - uint16_t /* uuid */, uint8_t /* scn */, bool /* is_server */, - uint16_t /* mtu */, const RawAddress& /* bd_addr */, - uint16_t* /* p_handle */, tPORT_MGMT_CALLBACK* /* p_mgmt_callback */, - uint16_t /* sec_mask */) { +int RFCOMM_CreateConnectionWithSecurity(uint16_t /* uuid */, uint8_t /* scn */, + bool /* is_server */, uint16_t /* mtu */, + const RawAddress& /* bd_addr */, uint16_t* /* p_handle */, + tPORT_MGMT_CALLBACK* /* p_mgmt_callback */, + uint16_t /* sec_mask */) { inc_func_call_count(__func__); return 0; } -int RFCOMM_ControlReqFromBTSOCK(uint8_t /* dlci */, - const RawAddress& /* bd_addr */, - uint8_t /* modem_signal */, - uint8_t /* break_signal */, - uint8_t /* discard_buffers */, - uint8_t /* break_signal_seq */, bool /* fc */) { +int RFCOMM_ControlReqFromBTSOCK(uint8_t /* dlci */, const RawAddress& /* bd_addr */, + uint8_t /* modem_signal */, uint8_t /* break_signal */, + uint8_t /* discard_buffers */, uint8_t /* break_signal_seq */, + bool /* fc */) { inc_func_call_count(__func__); return 0; } diff --git a/system/test/mock/mock_stack_sdp_api.cc b/system/test/mock/mock_stack_sdp_api.cc index e73f9d14257..0a4c58f2a7e 100644 --- a/system/test/mock/mock_stack_sdp_api.cc +++ b/system/test/mock/mock_stack_sdp_api.cc @@ -64,102 +64,80 @@ bool SDP_CancelServiceSearch(const tSDP_DISCOVERY_DB* p_db) { inc_func_call_count(__func__); return test::mock::stack_sdp_api::SDP_CancelServiceSearch(p_db); } -bool SDP_FindProfileVersionInRec(const tSDP_DISC_REC* p_rec, - uint16_t profile_uuid, uint16_t* p_version) { +bool SDP_FindProfileVersionInRec(const tSDP_DISC_REC* p_rec, uint16_t profile_uuid, + uint16_t* p_version) { inc_func_call_count(__func__); - return test::mock::stack_sdp_api::SDP_FindProfileVersionInRec( - p_rec, profile_uuid, p_version); + return test::mock::stack_sdp_api::SDP_FindProfileVersionInRec(p_rec, profile_uuid, p_version); } -bool SDP_FindProtocolListElemInRec(const tSDP_DISC_REC* p_rec, - uint16_t layer_uuid, +bool SDP_FindProtocolListElemInRec(const tSDP_DISC_REC* p_rec, uint16_t layer_uuid, tSDP_PROTOCOL_ELEM* p_elem) { inc_func_call_count(__func__); - return test::mock::stack_sdp_api::SDP_FindProtocolListElemInRec( - p_rec, layer_uuid, p_elem); + return test::mock::stack_sdp_api::SDP_FindProtocolListElemInRec(p_rec, layer_uuid, p_elem); } -bool SDP_FindServiceUUIDInRec(const tSDP_DISC_REC* p_rec, - bluetooth::Uuid* p_uuid) { +bool SDP_FindServiceUUIDInRec(const tSDP_DISC_REC* p_rec, bluetooth::Uuid* p_uuid) { inc_func_call_count(__func__); return test::mock::stack_sdp_api::SDP_FindServiceUUIDInRec(p_rec, p_uuid); } -bool SDP_FindServiceUUIDInRec_128bit(const tSDP_DISC_REC* p_rec, - bluetooth::Uuid* p_uuid) { +bool SDP_FindServiceUUIDInRec_128bit(const tSDP_DISC_REC* p_rec, bluetooth::Uuid* p_uuid) { inc_func_call_count(__func__); - return test::mock::stack_sdp_api::SDP_FindServiceUUIDInRec_128bit(p_rec, - p_uuid); + return test::mock::stack_sdp_api::SDP_FindServiceUUIDInRec_128bit(p_rec, p_uuid); } -bool SDP_InitDiscoveryDb(tSDP_DISCOVERY_DB* p_db, uint32_t len, - uint16_t num_uuid, const bluetooth::Uuid* p_uuid_list, - uint16_t num_attr, const uint16_t* p_attr_list) { +bool SDP_InitDiscoveryDb(tSDP_DISCOVERY_DB* p_db, uint32_t len, uint16_t num_uuid, + const bluetooth::Uuid* p_uuid_list, uint16_t num_attr, + const uint16_t* p_attr_list) { inc_func_call_count(__func__); - return test::mock::stack_sdp_api::SDP_InitDiscoveryDb( - p_db, len, num_uuid, p_uuid_list, num_attr, p_attr_list); + return test::mock::stack_sdp_api::SDP_InitDiscoveryDb(p_db, len, num_uuid, p_uuid_list, num_attr, + p_attr_list); } -bool SDP_ServiceSearchAttributeRequest(const RawAddress& p_bd_addr, - tSDP_DISCOVERY_DB* p_db, +bool SDP_ServiceSearchAttributeRequest(const RawAddress& p_bd_addr, tSDP_DISCOVERY_DB* p_db, tSDP_DISC_CMPL_CB* p_cb) { inc_func_call_count(__func__); - return test::mock::stack_sdp_api::SDP_ServiceSearchAttributeRequest( - p_bd_addr, p_db, p_cb); + return test::mock::stack_sdp_api::SDP_ServiceSearchAttributeRequest(p_bd_addr, p_db, p_cb); } bool SDP_ServiceSearchAttributeRequest2( - const RawAddress& p_bd_addr, tSDP_DISCOVERY_DB* p_db, - base::RepeatingCallback complete_callback) { + const RawAddress& p_bd_addr, tSDP_DISCOVERY_DB* p_db, + base::RepeatingCallback complete_callback) { inc_func_call_count(__func__); - return test::mock::stack_sdp_api::SDP_ServiceSearchAttributeRequest2( - p_bd_addr, p_db, complete_callback); + return test::mock::stack_sdp_api::SDP_ServiceSearchAttributeRequest2(p_bd_addr, p_db, + complete_callback); } -bool SDP_ServiceSearchRequest(const RawAddress& p_bd_addr, - tSDP_DISCOVERY_DB* p_db, +bool SDP_ServiceSearchRequest(const RawAddress& p_bd_addr, tSDP_DISCOVERY_DB* p_db, tSDP_DISC_CMPL_CB* p_cb) { inc_func_call_count(__func__); - return test::mock::stack_sdp_api::SDP_ServiceSearchRequest(p_bd_addr, p_db, - p_cb); + return test::mock::stack_sdp_api::SDP_ServiceSearchRequest(p_bd_addr, p_db, p_cb); } -tSDP_DISC_ATTR* SDP_FindAttributeInRec(const tSDP_DISC_REC* p_rec, - uint16_t attr_id) { +tSDP_DISC_ATTR* SDP_FindAttributeInRec(const tSDP_DISC_REC* p_rec, uint16_t attr_id) { inc_func_call_count(__func__); return test::mock::stack_sdp_api::SDP_FindAttributeInRec(p_rec, attr_id); } -tSDP_DISC_REC* SDP_FindServiceInDb(const tSDP_DISCOVERY_DB* p_db, - uint16_t service_uuid, +tSDP_DISC_REC* SDP_FindServiceInDb(const tSDP_DISCOVERY_DB* p_db, uint16_t service_uuid, tSDP_DISC_REC* p_start_rec) { inc_func_call_count(__func__); - return test::mock::stack_sdp_api::SDP_FindServiceInDb(p_db, service_uuid, - p_start_rec); + return test::mock::stack_sdp_api::SDP_FindServiceInDb(p_db, service_uuid, p_start_rec); } tSDP_DISC_REC* SDP_FindServiceInDb_128bit(const tSDP_DISCOVERY_DB* p_db, tSDP_DISC_REC* p_start_rec) { inc_func_call_count(__func__); - return test::mock::stack_sdp_api::SDP_FindServiceInDb_128bit(p_db, - p_start_rec); + return test::mock::stack_sdp_api::SDP_FindServiceInDb_128bit(p_db, p_start_rec); } -tSDP_DISC_REC* SDP_FindServiceUUIDInDb(const tSDP_DISCOVERY_DB* p_db, - const bluetooth::Uuid& uuid, +tSDP_DISC_REC* SDP_FindServiceUUIDInDb(const tSDP_DISCOVERY_DB* p_db, const bluetooth::Uuid& uuid, tSDP_DISC_REC* p_start_rec) { inc_func_call_count(__func__); - return test::mock::stack_sdp_api::SDP_FindServiceUUIDInDb(p_db, uuid, - p_start_rec); + return test::mock::stack_sdp_api::SDP_FindServiceUUIDInDb(p_db, uuid, p_start_rec); } -tSDP_STATUS SDP_DiDiscover(const RawAddress& remote_device, - tSDP_DISCOVERY_DB* p_db, uint32_t len, +tSDP_STATUS SDP_DiDiscover(const RawAddress& remote_device, tSDP_DISCOVERY_DB* p_db, uint32_t len, tSDP_DISC_CMPL_CB* p_cb) { inc_func_call_count(__func__); - return test::mock::stack_sdp_api::SDP_DiDiscover(remote_device, p_db, len, - p_cb); + return test::mock::stack_sdp_api::SDP_DiDiscover(remote_device, p_db, len, p_cb); } -uint16_t SDP_GetDiRecord(uint8_t get_record_index, - tSDP_DI_GET_RECORD* p_device_info, +uint16_t SDP_GetDiRecord(uint8_t get_record_index, tSDP_DI_GET_RECORD* p_device_info, const tSDP_DISCOVERY_DB* p_db) { inc_func_call_count(__func__); - return test::mock::stack_sdp_api::SDP_GetDiRecord(get_record_index, - p_device_info, p_db); + return test::mock::stack_sdp_api::SDP_GetDiRecord(get_record_index, p_device_info, p_db); } -uint16_t SDP_SetLocalDiRecord(const tSDP_DI_RECORD* p_device_info, - uint32_t* p_handle) { +uint16_t SDP_SetLocalDiRecord(const tSDP_DI_RECORD* p_device_info, uint32_t* p_handle) { inc_func_call_count(__func__); - return test::mock::stack_sdp_api::SDP_SetLocalDiRecord(p_device_info, - p_handle); + return test::mock::stack_sdp_api::SDP_SetLocalDiRecord(p_device_info, p_handle); } uint8_t SDP_GetNumDiRecords(const tSDP_DISCOVERY_DB* p_db) { inc_func_call_count(__func__); diff --git a/system/test/mock/mock_stack_sdp_api.h b/system/test/mock/mock_stack_sdp_api.h index fdaa5abcedc..8c5c0c96412 100644 --- a/system/test/mock/mock_stack_sdp_api.h +++ b/system/test/mock/mock_stack_sdp_api.h @@ -43,36 +43,32 @@ namespace stack_sdp_api { // Returns: bool struct SDP_CancelServiceSearch { std::function body{ - [](const tSDP_DISCOVERY_DB* /* p_db */) { return false; }}; - bool operator()(const tSDP_DISCOVERY_DB* p_db) { return body(p_db); }; + [](const tSDP_DISCOVERY_DB* /* p_db */) { return false; }}; + bool operator()(const tSDP_DISCOVERY_DB* p_db) { return body(p_db); } }; extern struct SDP_CancelServiceSearch SDP_CancelServiceSearch; // Name: SDP_FindProfileVersionInRec // Params: tSDP_DISC_REC* p_rec, uint16_t profile_uuid, uint16_t* p_version // Returns: bool struct SDP_FindProfileVersionInRec { - std::function - body{[](const tSDP_DISC_REC* /* p_rec */, uint16_t /* profile_uuid */, - uint16_t* /* p_version */) { return false; }}; - bool operator()(const tSDP_DISC_REC* p_rec, uint16_t profile_uuid, - uint16_t* p_version) { + std::function body{ + [](const tSDP_DISC_REC* /* p_rec */, uint16_t /* profile_uuid */, + uint16_t* /* p_version */) { return false; }}; + bool operator()(const tSDP_DISC_REC* p_rec, uint16_t profile_uuid, uint16_t* p_version) { return body(p_rec, profile_uuid, p_version); - }; + } }; extern struct SDP_FindProfileVersionInRec SDP_FindProfileVersionInRec; // Name: SDP_FindProtocolListElemInRec // Params: tSDP_DISC_REC* p_rec, uint16_t layer_uuid, tSDP_PROTOCOL_ELEM* p_elem // Returns: bool struct SDP_FindProtocolListElemInRec { - std::function - body{[](const tSDP_DISC_REC* /* p_rec */, uint16_t /* layer_uuid */, - tSDP_PROTOCOL_ELEM* /* p_elem */) { return false; }}; - bool operator()(const tSDP_DISC_REC* p_rec, uint16_t layer_uuid, - tSDP_PROTOCOL_ELEM* p_elem) { + std::function + body{[](const tSDP_DISC_REC* /* p_rec */, uint16_t /* layer_uuid */, + tSDP_PROTOCOL_ELEM* /* p_elem */) { return false; }}; + bool operator()(const tSDP_DISC_REC* p_rec, uint16_t layer_uuid, tSDP_PROTOCOL_ELEM* p_elem) { return body(p_rec, layer_uuid, p_elem); - }; + } }; extern struct SDP_FindProtocolListElemInRec SDP_FindProtocolListElemInRec; // Name: SDP_FindServiceUUIDInRec @@ -80,12 +76,10 @@ extern struct SDP_FindProtocolListElemInRec SDP_FindProtocolListElemInRec; // Returns: bool struct SDP_FindServiceUUIDInRec { std::function body{ - [](const tSDP_DISC_REC* /* p_rec */, bluetooth::Uuid* /* p_uuid */) { - return false; - }}; + [](const tSDP_DISC_REC* /* p_rec */, bluetooth::Uuid* /* p_uuid */) { return false; }}; bool operator()(const tSDP_DISC_REC* p_rec, bluetooth::Uuid* p_uuid) { return body(p_rec, p_uuid); - }; + } }; extern struct SDP_FindServiceUUIDInRec SDP_FindServiceUUIDInRec; // Name: SDP_FindServiceUUIDInRec_128bit @@ -93,12 +87,10 @@ extern struct SDP_FindServiceUUIDInRec SDP_FindServiceUUIDInRec; // Returns: bool struct SDP_FindServiceUUIDInRec_128bit { std::function body{ - [](const tSDP_DISC_REC* /* p_rec */, bluetooth::Uuid* /* p_uuid */) { - return false; - }}; + [](const tSDP_DISC_REC* /* p_rec */, bluetooth::Uuid* /* p_uuid */) { return false; }}; bool operator()(const tSDP_DISC_REC* p_rec, bluetooth::Uuid* p_uuid) { return body(p_rec, p_uuid); - }; + } }; extern struct SDP_FindServiceUUIDInRec_128bit SDP_FindServiceUUIDInRec_128bit; // Name: SDP_InitDiscoveryDb @@ -109,170 +101,146 @@ struct SDP_InitDiscoveryDb { std::function - body{[](tSDP_DISCOVERY_DB* /* p_db */, uint32_t /* len */, - uint16_t /* num_uuid */, const bluetooth::Uuid* /* p_uuid_list */, - uint16_t /* num_attr */, - const uint16_t* /* p_attr_list */) { return false; }}; + body{[](tSDP_DISCOVERY_DB* /* p_db */, uint32_t /* len */, uint16_t /* num_uuid */, + const bluetooth::Uuid* /* p_uuid_list */, uint16_t /* num_attr */, + const uint16_t* /* p_attr_list */) { return false; }}; bool operator()(tSDP_DISCOVERY_DB* p_db, uint32_t len, uint16_t num_uuid, const bluetooth::Uuid* p_uuid_list, uint16_t num_attr, const uint16_t* p_attr_list) { return body(p_db, len, num_uuid, p_uuid_list, num_attr, p_attr_list); - }; + } }; extern struct SDP_InitDiscoveryDb SDP_InitDiscoveryDb; // Name: SDP_ServiceSearchAttributeRequest // Params: const RawAddress& p_bd_addr, tSDP_DISCOVERY_DB* p_db, // tSDP_DISC_CMPL_CB* p_cb Returns: bool struct SDP_ServiceSearchAttributeRequest { - std::function - body{[](const RawAddress& /* p_bd_addr */, tSDP_DISCOVERY_DB* /* p_db */, - tSDP_DISC_CMPL_CB* /* p_cb */) { return false; }}; - bool operator()(const RawAddress& p_bd_addr, tSDP_DISCOVERY_DB* p_db, - tSDP_DISC_CMPL_CB* p_cb) { + std::function + body{[](const RawAddress& /* p_bd_addr */, tSDP_DISCOVERY_DB* /* p_db */, + tSDP_DISC_CMPL_CB* /* p_cb */) { return false; }}; + bool operator()(const RawAddress& p_bd_addr, tSDP_DISCOVERY_DB* p_db, tSDP_DISC_CMPL_CB* p_cb) { return body(p_bd_addr, p_db, p_cb); - }; + } }; -extern struct SDP_ServiceSearchAttributeRequest - SDP_ServiceSearchAttributeRequest; +extern struct SDP_ServiceSearchAttributeRequest SDP_ServiceSearchAttributeRequest; // Name: SDP_ServiceSearchAttributeRequest2 // Params: const RawAddress& p_bd_addr, tSDP_DISCOVERY_DB* p_db, // base::RepeatingCallback complete_callback // Returns: bool struct SDP_ServiceSearchAttributeRequest2 { - std::function complete_callback)> - body{ - [](const RawAddress& /* p_bd_addr */, tSDP_DISCOVERY_DB* /* p_db */, - base::RepeatingCallback< - tSDP_DISC_CMPL_CB> /* complete_callback */) { return false; }}; - bool operator()( - const RawAddress& p_bd_addr, tSDP_DISCOVERY_DB* p_db, - base::RepeatingCallback complete_callback) { + std::function complete_callback)> + body{[](const RawAddress& /* p_bd_addr */, tSDP_DISCOVERY_DB* /* p_db */, + base::RepeatingCallback /* complete_callback */) { + return false; + }}; + bool operator()(const RawAddress& p_bd_addr, tSDP_DISCOVERY_DB* p_db, + base::RepeatingCallback complete_callback) { return body(p_bd_addr, p_db, complete_callback); - }; + } }; -extern struct SDP_ServiceSearchAttributeRequest2 - SDP_ServiceSearchAttributeRequest2; +extern struct SDP_ServiceSearchAttributeRequest2 SDP_ServiceSearchAttributeRequest2; // Name: SDP_ServiceSearchRequest // Params: const RawAddress& p_bd_addr, tSDP_DISCOVERY_DB* p_db, // tSDP_DISC_CMPL_CB* p_cb Returns: bool struct SDP_ServiceSearchRequest { - std::function - body{[](const RawAddress& /* p_bd_addr */, tSDP_DISCOVERY_DB* /* p_db */, - tSDP_DISC_CMPL_CB* /* p_cb */) { return false; }}; - bool operator()(const RawAddress& p_bd_addr, tSDP_DISCOVERY_DB* p_db, - tSDP_DISC_CMPL_CB* p_cb) { + std::function + body{[](const RawAddress& /* p_bd_addr */, tSDP_DISCOVERY_DB* /* p_db */, + tSDP_DISC_CMPL_CB* /* p_cb */) { return false; }}; + bool operator()(const RawAddress& p_bd_addr, tSDP_DISCOVERY_DB* p_db, tSDP_DISC_CMPL_CB* p_cb) { return body(p_bd_addr, p_db, p_cb); - }; + } }; extern struct SDP_ServiceSearchRequest SDP_ServiceSearchRequest; // Name: SDP_FindAttributeInRec // Params: tSDP_DISC_REC* p_rec, uint16_t attr_id // Returns: tSDP_DISC_ATTR* struct SDP_FindAttributeInRec { - std::function - body{[](const tSDP_DISC_REC* /* p_rec */, uint16_t /* attr_id */) { - return nullptr; - }}; + std::function body{ + [](const tSDP_DISC_REC* /* p_rec */, uint16_t /* attr_id */) { return nullptr; }}; tSDP_DISC_ATTR* operator()(const tSDP_DISC_REC* p_rec, uint16_t attr_id) { return body(p_rec, attr_id); - }; + } }; extern struct SDP_FindAttributeInRec SDP_FindAttributeInRec; // Name: SDP_FindServiceInDb // Params: tSDP_DISCOVERY_DB* p_db, uint16_t service_uuid, tSDP_DISC_REC* // p_start_rec Returns: tSDP_DISC_REC* struct SDP_FindServiceInDb { - std::function - body{[](const tSDP_DISCOVERY_DB* /* p_db */, uint16_t /* service_uuid */, - tSDP_DISC_REC* /* p_start_rec */) { return nullptr; }}; - tSDP_DISC_REC* operator()(const tSDP_DISCOVERY_DB* p_db, - uint16_t service_uuid, tSDP_DISC_REC* p_start_rec) { + body{[](const tSDP_DISCOVERY_DB* /* p_db */, uint16_t /* service_uuid */, + tSDP_DISC_REC* /* p_start_rec */) { return nullptr; }}; + tSDP_DISC_REC* operator()(const tSDP_DISCOVERY_DB* p_db, uint16_t service_uuid, + tSDP_DISC_REC* p_start_rec) { return body(p_db, service_uuid, p_start_rec); - }; + } }; extern struct SDP_FindServiceInDb SDP_FindServiceInDb; // Name: SDP_FindServiceInDb_128bit // Params: tSDP_DISCOVERY_DB* p_db, tSDP_DISC_REC* p_start_rec // Returns: tSDP_DISC_REC* struct SDP_FindServiceInDb_128bit { - std::function - body{[](const tSDP_DISCOVERY_DB* /* p_db */, - tSDP_DISC_REC* /* p_start_rec */) { return nullptr; }}; - tSDP_DISC_REC* operator()(const tSDP_DISCOVERY_DB* p_db, - tSDP_DISC_REC* p_start_rec) { + std::function body{ + [](const tSDP_DISCOVERY_DB* /* p_db */, tSDP_DISC_REC* /* p_start_rec */) { + return nullptr; + }}; + tSDP_DISC_REC* operator()(const tSDP_DISCOVERY_DB* p_db, tSDP_DISC_REC* p_start_rec) { return body(p_db, p_start_rec); - }; + } }; extern struct SDP_FindServiceInDb_128bit SDP_FindServiceInDb_128bit; // Name: SDP_FindServiceUUIDInDb // Params: tSDP_DISCOVERY_DB* p_db, const bluetooth::Uuid& uuid, tSDP_DISC_REC* // p_start_rec Returns: tSDP_DISC_REC* struct SDP_FindServiceUUIDInDb { - std::function - body{[](const tSDP_DISCOVERY_DB* /* p_db */, - const bluetooth::Uuid& /* uuid */, - tSDP_DISC_REC* /* p_start_rec */) { return nullptr; }}; - tSDP_DISC_REC* operator()(const tSDP_DISCOVERY_DB* p_db, - const bluetooth::Uuid& uuid, + body{[](const tSDP_DISCOVERY_DB* /* p_db */, const bluetooth::Uuid& /* uuid */, + tSDP_DISC_REC* /* p_start_rec */) { return nullptr; }}; + tSDP_DISC_REC* operator()(const tSDP_DISCOVERY_DB* p_db, const bluetooth::Uuid& uuid, tSDP_DISC_REC* p_start_rec) { return body(p_db, uuid, p_start_rec); - }; + } }; extern struct SDP_FindServiceUUIDInDb SDP_FindServiceUUIDInDb; // Name: SDP_DiDiscover // Params: const RawAddress& remote_device, tSDP_DISCOVERY_DB* p_db, uint32_t // len, tSDP_DISC_CMPL_CB* p_cb Returns: tSDP_STATUS struct SDP_DiDiscover { - std::function - body{[](const RawAddress& /* remote_device */, - tSDP_DISCOVERY_DB* /* p_db */, uint32_t /* len */, - tSDP_DISC_CMPL_CB* /* p_cb */) { return SDP_SUCCESS; }}; - tSDP_STATUS operator()(const RawAddress& remote_device, - tSDP_DISCOVERY_DB* p_db, uint32_t len, + body{[](const RawAddress& /* remote_device */, tSDP_DISCOVERY_DB* /* p_db */, + uint32_t /* len */, tSDP_DISC_CMPL_CB* /* p_cb */) { return SDP_SUCCESS; }}; + tSDP_STATUS operator()(const RawAddress& remote_device, tSDP_DISCOVERY_DB* p_db, uint32_t len, tSDP_DISC_CMPL_CB* p_cb) { return body(remote_device, p_db, len, p_cb); - }; + } }; extern struct SDP_DiDiscover SDP_DiDiscover; // Name: SDP_GetDiRecord // Params: uint8_t get_record_index, tSDP_DI_GET_RECORD* p_device_info, // tSDP_DISCOVERY_DB* p_db Returns: uint16_t struct SDP_GetDiRecord { - std::function - body{[](uint8_t /* get_record_index */, - tSDP_DI_GET_RECORD* /* p_device_info */, - const tSDP_DISCOVERY_DB* /* p_db */) { return 0; }}; - uint16_t operator()(uint8_t get_record_index, - tSDP_DI_GET_RECORD* p_device_info, + body{[](uint8_t /* get_record_index */, tSDP_DI_GET_RECORD* /* p_device_info */, + const tSDP_DISCOVERY_DB* /* p_db */) { return 0; }}; + uint16_t operator()(uint8_t get_record_index, tSDP_DI_GET_RECORD* p_device_info, const tSDP_DISCOVERY_DB* p_db) { return body(get_record_index, p_device_info, p_db); - }; + } }; extern struct SDP_GetDiRecord SDP_GetDiRecord; // Name: SDP_SetLocalDiRecord // Params: tSDP_DI_RECORD* p_device_info, uint32_t* p_handle // Returns: uint16_t struct SDP_SetLocalDiRecord { - std::function - body{[](const tSDP_DI_RECORD* /* p_device_info */, - uint32_t* /* p_handle */) { return 0; }}; + std::function body{ + [](const tSDP_DI_RECORD* /* p_device_info */, uint32_t* /* p_handle */) { return 0; }}; uint16_t operator()(const tSDP_DI_RECORD* p_device_info, uint32_t* p_handle) { return body(p_device_info, p_handle); - }; + } }; extern struct SDP_SetLocalDiRecord SDP_SetLocalDiRecord; // Name: SDP_GetNumDiRecords @@ -280,8 +248,8 @@ extern struct SDP_SetLocalDiRecord SDP_SetLocalDiRecord; // Returns: uint8_t struct SDP_GetNumDiRecords { std::function body{ - [](const tSDP_DISCOVERY_DB* /* p_db */) { return 0; }}; - uint8_t operator()(const tSDP_DISCOVERY_DB* p_db) { return body(p_db); }; + [](const tSDP_DISCOVERY_DB* /* p_db */) { return 0; }}; + uint8_t operator()(const tSDP_DISCOVERY_DB* p_db) { return body(p_db); } }; extern struct SDP_GetNumDiRecords SDP_GetNumDiRecords; diff --git a/system/test/mock/mock_stack_sdp_db.cc b/system/test/mock/mock_stack_sdp_db.cc index 76b68c2cf9a..91ddae982c7 100644 --- a/system/test/mock/mock_stack_sdp_db.cc +++ b/system/test/mock/mock_stack_sdp_db.cc @@ -27,20 +27,17 @@ bool SDP_AddAdditionProtoLists(uint32_t /* handle */, uint16_t /* num_elem */, inc_func_call_count(__func__); return false; } -bool SDP_AddAttribute(uint32_t /* handle */, uint16_t /* attr_id */, - uint8_t /* attr_type */, uint32_t /* attr_len */, - uint8_t* /* p_val */) { +bool SDP_AddAttribute(uint32_t /* handle */, uint16_t /* attr_id */, uint8_t /* attr_type */, + uint32_t /* attr_len */, uint8_t* /* p_val */) { inc_func_call_count(__func__); return false; } bool SDP_AddLanguageBaseAttrIDList(uint32_t /* handle */, uint16_t /* lang */, - uint16_t /* char_enc */, - uint16_t /* base_id */) { + uint16_t /* char_enc */, uint16_t /* base_id */) { inc_func_call_count(__func__); return false; } -bool SDP_AddProfileDescriptorList(uint32_t /* handle */, - uint16_t /* profile_uuid */, +bool SDP_AddProfileDescriptorList(uint32_t /* handle */, uint16_t /* profile_uuid */, uint16_t /* version */) { inc_func_call_count(__func__); return false; @@ -50,20 +47,18 @@ bool SDP_AddProtocolList(uint32_t /* handle */, uint16_t /* num_elem */, inc_func_call_count(__func__); return false; } -bool SDP_AddSequence(uint32_t /* handle */, uint16_t /* attr_id */, - uint16_t /* num_elem */, uint8_t /* type */[], - uint8_t /* len */[], uint8_t* /* p_val */[]) { +bool SDP_AddSequence(uint32_t /* handle */, uint16_t /* attr_id */, uint16_t /* num_elem */, + uint8_t /* type */[], uint8_t /* len */[], uint8_t* /* p_val */[]) { inc_func_call_count(__func__); return false; } -bool SDP_AddServiceClassIdList(uint32_t /* handle */, - uint16_t /* num_services */, +bool SDP_AddServiceClassIdList(uint32_t /* handle */, uint16_t /* num_services */, uint16_t* /* p_service_uuids */) { inc_func_call_count(__func__); return false; } -bool SDP_AddUuidSequence(uint32_t /* handle */, uint16_t /* attr_id */, - uint16_t /* num_uuids */, uint16_t* /* p_uuids */) { +bool SDP_AddUuidSequence(uint32_t /* handle */, uint16_t /* attr_id */, uint16_t /* num_uuids */, + uint16_t* /* p_uuids */) { inc_func_call_count(__func__); return false; } @@ -71,8 +66,7 @@ bool SDP_DeleteRecord(uint32_t /* handle */) { inc_func_call_count(__func__); return false; } -tSDP_ATTRIBUTE* sdp_db_find_attr_in_rec(tSDP_RECORD* /* p_rec */, - uint16_t /* start_attr */, +tSDP_ATTRIBUTE* sdp_db_find_attr_in_rec(tSDP_RECORD* /* p_rec */, uint16_t /* start_attr */, uint16_t /* end_attr */) { inc_func_call_count(__func__); return nullptr; diff --git a/system/test/mock/mock_stack_sdp_legacy_api.cc b/system/test/mock/mock_stack_sdp_legacy_api.cc index e0ce88f5918..dd7f845c16d 100644 --- a/system/test/mock/mock_stack_sdp_legacy_api.cc +++ b/system/test/mock/mock_stack_sdp_legacy_api.cc @@ -24,52 +24,50 @@ namespace mock { namespace stack_sdp_legacy { bluetooth::legacy::stack::sdp::tSdpApi api_ = { - .service = - { - .SDP_InitDiscoveryDb = [](tSDP_DISCOVERY_DB*, uint32_t, uint16_t, - const bluetooth::Uuid*, uint16_t, - const uint16_t*) -> bool { - return false; - }, - .SDP_CancelServiceSearch = nullptr, - .SDP_ServiceSearchRequest = nullptr, - .SDP_ServiceSearchAttributeRequest = nullptr, - .SDP_ServiceSearchAttributeRequest2 = nullptr, - }, - .db = - { - .SDP_FindServiceInDb = nullptr, - .SDP_FindServiceUUIDInDb = nullptr, - .SDP_FindServiceInDb_128bit = nullptr, - }, - .record = - { - .SDP_FindAttributeInRec = nullptr, - .SDP_FindServiceUUIDInRec_128bit = nullptr, - .SDP_FindProtocolListElemInRec = nullptr, - .SDP_FindProfileVersionInRec = nullptr, - .SDP_FindServiceUUIDInRec = nullptr, - }, - .handle = - { - .SDP_CreateRecord = nullptr, - .SDP_DeleteRecord = nullptr, - .SDP_AddAttribute = nullptr, - .SDP_AddSequence = nullptr, - .SDP_AddUuidSequence = nullptr, - .SDP_AddProtocolList = nullptr, - .SDP_AddAdditionProtoLists = nullptr, - .SDP_AddProfileDescriptorList = nullptr, - .SDP_AddLanguageBaseAttrIDList = nullptr, - .SDP_AddServiceClassIdList = nullptr, - }, - .device_id = - { - .SDP_SetLocalDiRecord = nullptr, - .SDP_DiDiscover = nullptr, - .SDP_GetNumDiRecords = nullptr, - .SDP_GetDiRecord = nullptr, - }, + .service = + { + .SDP_InitDiscoveryDb = [](tSDP_DISCOVERY_DB*, uint32_t, uint16_t, + const bluetooth::Uuid*, uint16_t, + const uint16_t*) -> bool { return false; }, + .SDP_CancelServiceSearch = nullptr, + .SDP_ServiceSearchRequest = nullptr, + .SDP_ServiceSearchAttributeRequest = nullptr, + .SDP_ServiceSearchAttributeRequest2 = nullptr, + }, + .db = + { + .SDP_FindServiceInDb = nullptr, + .SDP_FindServiceUUIDInDb = nullptr, + .SDP_FindServiceInDb_128bit = nullptr, + }, + .record = + { + .SDP_FindAttributeInRec = nullptr, + .SDP_FindServiceUUIDInRec_128bit = nullptr, + .SDP_FindProtocolListElemInRec = nullptr, + .SDP_FindProfileVersionInRec = nullptr, + .SDP_FindServiceUUIDInRec = nullptr, + }, + .handle = + { + .SDP_CreateRecord = nullptr, + .SDP_DeleteRecord = nullptr, + .SDP_AddAttribute = nullptr, + .SDP_AddSequence = nullptr, + .SDP_AddUuidSequence = nullptr, + .SDP_AddProtocolList = nullptr, + .SDP_AddAdditionProtoLists = nullptr, + .SDP_AddProfileDescriptorList = nullptr, + .SDP_AddLanguageBaseAttrIDList = nullptr, + .SDP_AddServiceClassIdList = nullptr, + }, + .device_id = + { + .SDP_SetLocalDiRecord = nullptr, + .SDP_DiDiscover = nullptr, + .SDP_GetNumDiRecords = nullptr, + .SDP_GetDiRecord = nullptr, + }, }; } // namespace stack_sdp_legacy diff --git a/system/test/mock/mock_stack_sdp_main.cc b/system/test/mock/mock_stack_sdp_main.cc index 53976691d0b..e66b58bbd08 100644 --- a/system/test/mock/mock_stack_sdp_main.cc +++ b/system/test/mock/mock_stack_sdp_main.cc @@ -28,8 +28,6 @@ tCONN_CB* sdp_conn_originate(const RawAddress& /* p_bd_addr */) { return nullptr; } void sdp_conn_timer_timeout(void* /* data */) { inc_func_call_count(__func__); } -void sdp_disconnect(tCONN_CB* /* p_ccb */, uint16_t /* reason */) { - inc_func_call_count(__func__); -} +void sdp_disconnect(tCONN_CB* /* p_ccb */, uint16_t /* reason */) { inc_func_call_count(__func__); } void sdp_free(void) { inc_func_call_count(__func__); } void sdp_init(void) { inc_func_call_count(__func__); } diff --git a/system/test/mock/mock_stack_sdp_server.cc b/system/test/mock/mock_stack_sdp_server.cc index 240b921078b..21e61901bd4 100644 --- a/system/test/mock/mock_stack_sdp_server.cc +++ b/system/test/mock/mock_stack_sdp_server.cc @@ -25,9 +25,9 @@ bool is_sdp_pbap_pce_disabled(RawAddress /* remote_address */) { inc_func_call_count(__func__); return false; } -void sdp_save_local_pse_record_attributes( - int32_t /* rfcomm_channel_number */, int32_t /* l2cap_psm */, - int32_t /* profile_version */, uint32_t /* supported_features */, - uint32_t /* supported_repositories */) { +void sdp_save_local_pse_record_attributes(int32_t /* rfcomm_channel_number */, + int32_t /* l2cap_psm */, int32_t /* profile_version */, + uint32_t /* supported_features */, + uint32_t /* supported_repositories */) { inc_func_call_count(__func__); } diff --git a/system/test/mock/mock_stack_smp_act.cc b/system/test/mock/mock_stack_smp_act.cc index 44496922d56..8f02fa14b25 100644 --- a/system/test/mock/mock_stack_smp_act.cc +++ b/system/test/mock/mock_stack_smp_act.cc @@ -80,8 +80,7 @@ struct smp_key_pick_key smp_key_pick_key; struct smp_key_distribution smp_key_distribution; struct smp_decide_association_model smp_decide_association_model; struct smp_process_io_response smp_process_io_response; -struct smp_br_process_peripheral_keys_response - smp_br_process_peripheral_keys_response; +struct smp_br_process_peripheral_keys_response smp_br_process_peripheral_keys_response; struct smp_br_send_pair_response smp_br_send_pair_response; struct smp_pairing_cmpl smp_pairing_cmpl; struct smp_pair_terminate smp_pair_terminate; @@ -91,24 +90,19 @@ struct smp_start_secure_connection_phase1 smp_start_secure_connection_phase1; struct smp_process_local_nonce smp_process_local_nonce; struct smp_process_peer_nonce smp_process_peer_nonce; struct smp_match_dhkey_checks smp_match_dhkey_checks; -struct smp_move_to_secure_connections_phase2 - smp_move_to_secure_connections_phase2; -struct smp_phase_2_dhkey_checks_are_present - smp_phase_2_dhkey_checks_are_present; +struct smp_move_to_secure_connections_phase2 smp_move_to_secure_connections_phase2; +struct smp_phase_2_dhkey_checks_are_present smp_phase_2_dhkey_checks_are_present; struct smp_wait_for_both_public_keys smp_wait_for_both_public_keys; struct smp_start_passkey_verification smp_start_passkey_verification; -struct smp_process_secure_connection_oob_data - smp_process_secure_connection_oob_data; +struct smp_process_secure_connection_oob_data smp_process_secure_connection_oob_data; struct smp_set_local_oob_keys smp_set_local_oob_keys; struct smp_set_local_oob_random_commitment smp_set_local_oob_random_commitment; struct smp_link_encrypted smp_link_encrypted; struct smp_cancel_start_encryption_attempt smp_cancel_start_encryption_attempt; struct smp_proc_ltk_request smp_proc_ltk_request; -struct smp_process_secure_connection_long_term_key - smp_process_secure_connection_long_term_key; +struct smp_process_secure_connection_long_term_key smp_process_secure_connection_long_term_key; struct smp_set_derive_link_key smp_set_derive_link_key; -struct smp_derive_link_key_from_long_term_key - smp_derive_link_key_from_long_term_key; +struct smp_derive_link_key_from_long_term_key smp_derive_link_key_from_long_term_key; struct smp_br_process_link_key smp_br_process_link_key; struct smp_br_pairing_complete smp_br_pairing_complete; @@ -289,11 +283,9 @@ void smp_process_io_response(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { inc_func_call_count(__func__); test::mock::stack_smp_act::smp_process_io_response(p_cb, p_data); } -void smp_br_process_peripheral_keys_response(tSMP_CB* p_cb, - tSMP_INT_DATA* p_data) { +void smp_br_process_peripheral_keys_response(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { inc_func_call_count(__func__); - test::mock::stack_smp_act::smp_br_process_peripheral_keys_response(p_cb, - p_data); + test::mock::stack_smp_act::smp_br_process_peripheral_keys_response(p_cb, p_data); } void smp_br_send_pair_response(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { inc_func_call_count(__func__); @@ -331,14 +323,11 @@ void smp_match_dhkey_checks(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { inc_func_call_count(__func__); test::mock::stack_smp_act::smp_match_dhkey_checks(p_cb, p_data); } -void smp_move_to_secure_connections_phase2(tSMP_CB* p_cb, - tSMP_INT_DATA* p_data) { +void smp_move_to_secure_connections_phase2(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { inc_func_call_count(__func__); - test::mock::stack_smp_act::smp_move_to_secure_connections_phase2(p_cb, - p_data); + test::mock::stack_smp_act::smp_move_to_secure_connections_phase2(p_cb, p_data); } -void smp_phase_2_dhkey_checks_are_present(tSMP_CB* p_cb, - tSMP_INT_DATA* p_data) { +void smp_phase_2_dhkey_checks_are_present(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { inc_func_call_count(__func__); test::mock::stack_smp_act::smp_phase_2_dhkey_checks_are_present(p_cb, p_data); } @@ -350,11 +339,9 @@ void smp_start_passkey_verification(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { inc_func_call_count(__func__); test::mock::stack_smp_act::smp_start_passkey_verification(p_cb, p_data); } -void smp_process_secure_connection_oob_data(tSMP_CB* p_cb, - tSMP_INT_DATA* p_data) { +void smp_process_secure_connection_oob_data(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { inc_func_call_count(__func__); - test::mock::stack_smp_act::smp_process_secure_connection_oob_data(p_cb, - p_data); + test::mock::stack_smp_act::smp_process_secure_connection_oob_data(p_cb, p_data); } void smp_set_local_oob_keys(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { inc_func_call_count(__func__); @@ -384,11 +371,9 @@ void smp_set_derive_link_key(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { inc_func_call_count(__func__); test::mock::stack_smp_act::smp_set_derive_link_key(p_cb, p_data); } -void smp_derive_link_key_from_long_term_key(tSMP_CB* p_cb, - tSMP_INT_DATA* p_data) { +void smp_derive_link_key_from_long_term_key(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { inc_func_call_count(__func__); - test::mock::stack_smp_act::smp_derive_link_key_from_long_term_key(p_cb, - p_data); + test::mock::stack_smp_act::smp_derive_link_key_from_long_term_key(p_cb, p_data); } void smp_br_process_link_key(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { inc_func_call_count(__func__); diff --git a/system/test/mock/mock_stack_smp_act.h b/system/test/mock/mock_stack_smp_act.h index 24766de35b7..dc6124314c9 100644 --- a/system/test/mock/mock_stack_smp_act.h +++ b/system/test/mock/mock_stack_smp_act.h @@ -39,8 +39,8 @@ namespace stack_smp_act { // Returns: void struct smp_send_app_cback { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; extern struct smp_send_app_cback smp_send_app_cback; // Name: smp_send_pair_fail @@ -48,8 +48,8 @@ extern struct smp_send_app_cback smp_send_app_cback; // Returns: void struct smp_send_pair_fail { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; extern struct smp_send_pair_fail smp_send_pair_fail; // Name: smp_send_pair_req @@ -57,8 +57,8 @@ extern struct smp_send_pair_fail smp_send_pair_fail; // Returns: void struct smp_send_pair_req { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; extern struct smp_send_pair_req smp_send_pair_req; // Name: smp_send_pair_rsp @@ -66,8 +66,8 @@ extern struct smp_send_pair_req smp_send_pair_req; // Returns: void struct smp_send_pair_rsp { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; extern struct smp_send_pair_rsp smp_send_pair_rsp; // Name: smp_send_confirm @@ -75,8 +75,8 @@ extern struct smp_send_pair_rsp smp_send_pair_rsp; // Returns: void struct smp_send_confirm { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; extern struct smp_send_confirm smp_send_confirm; // Name: smp_send_rand @@ -84,8 +84,8 @@ extern struct smp_send_confirm smp_send_confirm; // Returns: void struct smp_send_rand { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; extern struct smp_send_rand smp_send_rand; // Name: smp_send_pair_public_key @@ -93,8 +93,8 @@ extern struct smp_send_rand smp_send_rand; // Returns: void struct smp_send_pair_public_key { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; extern struct smp_send_pair_public_key smp_send_pair_public_key; // Name: smp_send_commitment @@ -102,8 +102,8 @@ extern struct smp_send_pair_public_key smp_send_pair_public_key; // Returns: void struct smp_send_commitment { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; extern struct smp_send_commitment smp_send_commitment; // Name: smp_send_dhkey_check @@ -111,8 +111,8 @@ extern struct smp_send_commitment smp_send_commitment; // Returns: void struct smp_send_dhkey_check { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; extern struct smp_send_dhkey_check smp_send_dhkey_check; // Name: smp_send_keypress_notification @@ -120,8 +120,8 @@ extern struct smp_send_dhkey_check smp_send_dhkey_check; // Returns: void struct smp_send_keypress_notification { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; extern struct smp_send_keypress_notification smp_send_keypress_notification; // Name: smp_send_enc_info @@ -129,8 +129,8 @@ extern struct smp_send_keypress_notification smp_send_keypress_notification; // Returns: void struct smp_send_enc_info { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; extern struct smp_send_enc_info smp_send_enc_info; // Name: smp_send_id_info @@ -138,8 +138,8 @@ extern struct smp_send_enc_info smp_send_enc_info; // Returns: void struct smp_send_id_info { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; extern struct smp_send_id_info smp_send_id_info; // Name: smp_send_csrk_info @@ -147,8 +147,8 @@ extern struct smp_send_id_info smp_send_id_info; // Returns: void struct smp_send_csrk_info { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; extern struct smp_send_csrk_info smp_send_csrk_info; // Name: smp_send_ltk_reply @@ -156,8 +156,8 @@ extern struct smp_send_csrk_info smp_send_csrk_info; // Returns: void struct smp_send_ltk_reply { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; extern struct smp_send_ltk_reply smp_send_ltk_reply; // Name: smp_proc_sec_req @@ -165,8 +165,8 @@ extern struct smp_send_ltk_reply smp_send_ltk_reply; // Returns: void struct smp_proc_sec_req { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; extern struct smp_proc_sec_req smp_proc_sec_req; // Name: smp_proc_sec_grant @@ -174,8 +174,8 @@ extern struct smp_proc_sec_req smp_proc_sec_req; // Returns: void struct smp_proc_sec_grant { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; extern struct smp_proc_sec_grant smp_proc_sec_grant; // Name: smp_proc_pair_fail @@ -183,8 +183,8 @@ extern struct smp_proc_sec_grant smp_proc_sec_grant; // Returns: void struct smp_proc_pair_fail { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; extern struct smp_proc_pair_fail smp_proc_pair_fail; // Name: smp_proc_pair_cmd @@ -192,8 +192,8 @@ extern struct smp_proc_pair_fail smp_proc_pair_fail; // Returns: void struct smp_proc_pair_cmd { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; extern struct smp_proc_pair_cmd smp_proc_pair_cmd; // Name: smp_proc_confirm @@ -201,8 +201,8 @@ extern struct smp_proc_pair_cmd smp_proc_pair_cmd; // Returns: void struct smp_proc_confirm { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; extern struct smp_proc_confirm smp_proc_confirm; @@ -211,8 +211,8 @@ extern struct smp_proc_confirm smp_proc_confirm; // Returns: void struct smp_proc_rand { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; extern struct smp_proc_rand smp_proc_rand; // Name: smp_process_pairing_public_key @@ -220,8 +220,8 @@ extern struct smp_proc_rand smp_proc_rand; // Returns: void struct smp_process_pairing_public_key { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; extern struct smp_process_pairing_public_key smp_process_pairing_public_key; // Name: smp_process_pairing_commitment @@ -229,8 +229,8 @@ extern struct smp_process_pairing_public_key smp_process_pairing_public_key; // Returns: void struct smp_process_pairing_commitment { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; extern struct smp_process_pairing_commitment smp_process_pairing_commitment; // Name: smp_process_dhkey_check @@ -238,8 +238,8 @@ extern struct smp_process_pairing_commitment smp_process_pairing_commitment; // Returns: void struct smp_process_dhkey_check { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; extern struct smp_process_dhkey_check smp_process_dhkey_check; // Name: smp_process_keypress_notification @@ -247,18 +247,17 @@ extern struct smp_process_dhkey_check smp_process_dhkey_check; // Returns: void struct smp_process_keypress_notification { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; -extern struct smp_process_keypress_notification - smp_process_keypress_notification; +extern struct smp_process_keypress_notification smp_process_keypress_notification; // Name: smp_br_process_pairing_command // Params: tSMP_CB* p_cb, tSMP_INT_DATA* p_data // Returns: void struct smp_br_process_pairing_command { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; extern struct smp_br_process_pairing_command smp_br_process_pairing_command; // Name: smp_br_process_security_grant @@ -266,8 +265,8 @@ extern struct smp_br_process_pairing_command smp_br_process_pairing_command; // Returns: void struct smp_br_process_security_grant { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; extern struct smp_br_process_security_grant smp_br_process_security_grant; // Name: smp_br_check_authorization_request @@ -275,18 +274,17 @@ extern struct smp_br_process_security_grant smp_br_process_security_grant; // Returns: void struct smp_br_check_authorization_request { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; -extern struct smp_br_check_authorization_request - smp_br_check_authorization_request; +extern struct smp_br_check_authorization_request smp_br_check_authorization_request; // Name: smp_br_select_next_key // Params: tSMP_CB* p_cb, tSMP_INT_DATA* p_data // Returns: void struct smp_br_select_next_key { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; extern struct smp_br_select_next_key smp_br_select_next_key; // Name: smp_proc_enc_info @@ -294,8 +292,8 @@ extern struct smp_br_select_next_key smp_br_select_next_key; // Returns: void struct smp_proc_enc_info { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; extern struct smp_proc_enc_info smp_proc_enc_info; // Name: smp_proc_central_id @@ -303,8 +301,8 @@ extern struct smp_proc_enc_info smp_proc_enc_info; // Returns: void struct smp_proc_central_id { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; extern struct smp_proc_central_id smp_proc_central_id; // Name: smp_proc_id_info @@ -312,8 +310,8 @@ extern struct smp_proc_central_id smp_proc_central_id; // Returns: void struct smp_proc_id_info { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; extern struct smp_proc_id_info smp_proc_id_info; // Name: smp_proc_id_addr @@ -321,8 +319,8 @@ extern struct smp_proc_id_info smp_proc_id_info; // Returns: void struct smp_proc_id_addr { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; extern struct smp_proc_id_addr smp_proc_id_addr; // Name: smp_proc_srk_info @@ -330,8 +328,8 @@ extern struct smp_proc_id_addr smp_proc_id_addr; // Returns: void struct smp_proc_srk_info { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; extern struct smp_proc_srk_info smp_proc_srk_info; // Name: smp_proc_compare @@ -339,8 +337,8 @@ extern struct smp_proc_srk_info smp_proc_srk_info; // Returns: void struct smp_proc_compare { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; extern struct smp_proc_compare smp_proc_compare; // Name: smp_proc_sl_key @@ -348,8 +346,8 @@ extern struct smp_proc_compare smp_proc_compare; // Returns: void struct smp_proc_sl_key { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; extern struct smp_proc_sl_key smp_proc_sl_key; // Name: smp_start_enc @@ -357,8 +355,8 @@ extern struct smp_proc_sl_key smp_proc_sl_key; // Returns: void struct smp_start_enc { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; extern struct smp_start_enc smp_start_enc; // Name: smp_proc_discard @@ -366,8 +364,8 @@ extern struct smp_start_enc smp_start_enc; // Returns: void struct smp_proc_discard { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; extern struct smp_proc_discard smp_proc_discard; // Name: smp_enc_cmpl @@ -375,8 +373,8 @@ extern struct smp_proc_discard smp_proc_discard; // Returns: void struct smp_enc_cmpl { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; extern struct smp_enc_cmpl smp_enc_cmpl; // Name: smp_check_auth_req @@ -384,8 +382,8 @@ extern struct smp_enc_cmpl smp_enc_cmpl; // Returns: void struct smp_check_auth_req { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; extern struct smp_check_auth_req smp_check_auth_req; // Name: smp_key_pick_key @@ -393,8 +391,8 @@ extern struct smp_check_auth_req smp_check_auth_req; // Returns: void struct smp_key_pick_key { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; extern struct smp_key_pick_key smp_key_pick_key; // Name: smp_key_distribution @@ -402,8 +400,8 @@ extern struct smp_key_pick_key smp_key_pick_key; // Returns: void struct smp_key_distribution { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; extern struct smp_key_distribution smp_key_distribution; // Name: smp_decide_association_model @@ -411,8 +409,8 @@ extern struct smp_key_distribution smp_key_distribution; // Returns: void struct smp_decide_association_model { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; extern struct smp_decide_association_model smp_decide_association_model; // Name: smp_process_io_response @@ -420,8 +418,8 @@ extern struct smp_decide_association_model smp_decide_association_model; // Returns: void struct smp_process_io_response { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; extern struct smp_process_io_response smp_process_io_response; // Name: smp_br_process_peripheral_keys_response @@ -429,18 +427,17 @@ extern struct smp_process_io_response smp_process_io_response; // Returns: void struct smp_br_process_peripheral_keys_response { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; -extern struct smp_br_process_peripheral_keys_response - smp_br_process_peripheral_keys_response; +extern struct smp_br_process_peripheral_keys_response smp_br_process_peripheral_keys_response; // Name: smp_br_send_pair_response // Params: tSMP_CB* p_cb, tSMP_INT_DATA* p_data // Returns: void struct smp_br_send_pair_response { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; extern struct smp_br_send_pair_response smp_br_send_pair_response; // Name: smp_pairing_cmpl @@ -448,8 +445,8 @@ extern struct smp_br_send_pair_response smp_br_send_pair_response; // Returns: void struct smp_pairing_cmpl { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; extern struct smp_pairing_cmpl smp_pairing_cmpl; // Name: smp_pair_terminate @@ -457,8 +454,8 @@ extern struct smp_pairing_cmpl smp_pairing_cmpl; // Returns: void struct smp_pair_terminate { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; extern struct smp_pair_terminate smp_pair_terminate; // Name: smp_idle_terminate @@ -466,8 +463,8 @@ extern struct smp_pair_terminate smp_pair_terminate; // Returns: void struct smp_idle_terminate { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; extern struct smp_idle_terminate smp_idle_terminate; // Name: smp_both_have_public_keys @@ -475,8 +472,8 @@ extern struct smp_idle_terminate smp_idle_terminate; // Returns: void struct smp_both_have_public_keys { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; extern struct smp_both_have_public_keys smp_both_have_public_keys; // Name: smp_start_secure_connection_phase1 @@ -484,18 +481,17 @@ extern struct smp_both_have_public_keys smp_both_have_public_keys; // Returns: void struct smp_start_secure_connection_phase1 { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; -extern struct smp_start_secure_connection_phase1 - smp_start_secure_connection_phase1; +extern struct smp_start_secure_connection_phase1 smp_start_secure_connection_phase1; // Name: smp_process_local_nonce // Params: tSMP_CB* p_cb, tSMP_INT_DATA* p_data // Returns: void struct smp_process_local_nonce { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; extern struct smp_process_local_nonce smp_process_local_nonce; // Name: smp_process_peer_nonce @@ -503,8 +499,8 @@ extern struct smp_process_local_nonce smp_process_local_nonce; // Returns: void struct smp_process_peer_nonce { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; extern struct smp_process_peer_nonce smp_process_peer_nonce; // Name: smp_match_dhkey_checks @@ -512,8 +508,8 @@ extern struct smp_process_peer_nonce smp_process_peer_nonce; // Returns: void struct smp_match_dhkey_checks { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; extern struct smp_match_dhkey_checks smp_match_dhkey_checks; // Name: smp_move_to_secure_connections_phase2 @@ -521,28 +517,26 @@ extern struct smp_match_dhkey_checks smp_match_dhkey_checks; // Returns: void struct smp_move_to_secure_connections_phase2 { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; -extern struct smp_move_to_secure_connections_phase2 - smp_move_to_secure_connections_phase2; +extern struct smp_move_to_secure_connections_phase2 smp_move_to_secure_connections_phase2; // Name: smp_phase_2_dhkey_checks_are_present // Params: tSMP_CB* p_cb, tSMP_INT_DATA* p_data // Returns: void struct smp_phase_2_dhkey_checks_are_present { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; -extern struct smp_phase_2_dhkey_checks_are_present - smp_phase_2_dhkey_checks_are_present; +extern struct smp_phase_2_dhkey_checks_are_present smp_phase_2_dhkey_checks_are_present; // Name: smp_wait_for_both_public_keys // Params: tSMP_CB* p_cb, tSMP_INT_DATA* p_data // Returns: void struct smp_wait_for_both_public_keys { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; extern struct smp_wait_for_both_public_keys smp_wait_for_both_public_keys; // Name: smp_start_passkey_verification @@ -550,8 +544,8 @@ extern struct smp_wait_for_both_public_keys smp_wait_for_both_public_keys; // Returns: void struct smp_start_passkey_verification { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; extern struct smp_start_passkey_verification smp_start_passkey_verification; // Name: smp_process_secure_connection_oob_data @@ -559,18 +553,17 @@ extern struct smp_start_passkey_verification smp_start_passkey_verification; // Returns: void struct smp_process_secure_connection_oob_data { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; -extern struct smp_process_secure_connection_oob_data - smp_process_secure_connection_oob_data; +extern struct smp_process_secure_connection_oob_data smp_process_secure_connection_oob_data; // Name: smp_set_local_oob_keys // Params: tSMP_CB* p_cb, tSMP_INT_DATA* p_data // Returns: void struct smp_set_local_oob_keys { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; extern struct smp_set_local_oob_keys smp_set_local_oob_keys; // Name: smp_set_local_oob_random_commitment @@ -578,20 +571,17 @@ extern struct smp_set_local_oob_keys smp_set_local_oob_keys; // Returns: void struct smp_set_local_oob_random_commitment { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; -extern struct smp_set_local_oob_random_commitment - smp_set_local_oob_random_commitment; +extern struct smp_set_local_oob_random_commitment smp_set_local_oob_random_commitment; // Name: smp_link_encrypted // Params: const RawAddress& bda, uint8_t encr_enable // Returns: void struct smp_link_encrypted { std::function body{ - [](const RawAddress& /* bda */, uint8_t /* encr_enable */) {}}; - void operator()(const RawAddress& bda, uint8_t encr_enable) { - body(bda, encr_enable); - }; + [](const RawAddress& /* bda */, uint8_t /* encr_enable */) {}}; + void operator()(const RawAddress& bda, uint8_t encr_enable) { body(bda, encr_enable); } }; extern struct smp_link_encrypted smp_link_encrypted; // Name: smp_cancel_start_encryption_attempt @@ -599,17 +589,16 @@ extern struct smp_link_encrypted smp_link_encrypted; // Returns: void struct smp_cancel_start_encryption_attempt { std::function body{[]() {}}; - void operator()() { body(); }; + void operator()() { body(); } }; -extern struct smp_cancel_start_encryption_attempt - smp_cancel_start_encryption_attempt; +extern struct smp_cancel_start_encryption_attempt smp_cancel_start_encryption_attempt; // Name: smp_proc_ltk_request // Params: const RawAddress& bda // Returns: bool struct smp_proc_ltk_request { std::function body{ - [](const RawAddress& /* bda */) { return false; }}; - bool operator()(const RawAddress& bda) { return body(bda); }; + [](const RawAddress& /* bda */) { return false; }}; + bool operator()(const RawAddress& bda) { return body(bda); } }; extern struct smp_proc_ltk_request smp_proc_ltk_request; // Name: smp_process_secure_connection_long_term_key @@ -617,17 +606,17 @@ extern struct smp_proc_ltk_request smp_proc_ltk_request; // Returns: void struct smp_process_secure_connection_long_term_key { std::function body{[](void) {}}; - void operator()(void) { body(); }; + void operator()(void) { body(); } }; extern struct smp_process_secure_connection_long_term_key - smp_process_secure_connection_long_term_key; + smp_process_secure_connection_long_term_key; // Name: smp_set_derive_link_key // Params: tSMP_CB* p_cb, tSMP_INT_DATA* p_data // Returns: void struct smp_set_derive_link_key { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; extern struct smp_set_derive_link_key smp_set_derive_link_key; // Name: smp_derive_link_key_from_long_term_key @@ -635,18 +624,17 @@ extern struct smp_set_derive_link_key smp_set_derive_link_key; // Returns: void struct smp_derive_link_key_from_long_term_key { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; -extern struct smp_derive_link_key_from_long_term_key - smp_derive_link_key_from_long_term_key; +extern struct smp_derive_link_key_from_long_term_key smp_derive_link_key_from_long_term_key; // Name: smp_br_process_link_key // Params: tSMP_CB* p_cb, tSMP_INT_DATA* p_data // Returns: void struct smp_br_process_link_key { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; extern struct smp_br_process_link_key smp_br_process_link_key; // Name: smp_br_pairing_complete @@ -654,8 +642,8 @@ extern struct smp_br_process_link_key smp_br_process_link_key; // Returns: void struct smp_br_pairing_complete { std::function body{ - [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; - void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); }; + [](tSMP_CB* /* p_cb */, tSMP_INT_DATA* /* p_data */) {}}; + void operator()(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { body(p_cb, p_data); } }; extern struct smp_br_pairing_complete smp_br_pairing_complete; diff --git a/system/test/mock/mock_stack_smp_api.cc b/system/test/mock/mock_stack_smp_api.cc index f71c260609e..9540022e93a 100644 --- a/system/test/mock/mock_stack_smp_api.cc +++ b/system/test/mock/mock_stack_smp_api.cc @@ -35,8 +35,7 @@ tSMP_STATUS SMP_BR_PairWith(const RawAddress& /* bd_addr */) { inc_func_call_count(__func__); return SMP_SUCCESS; } -tSMP_STATUS SMP_Pair(const RawAddress& /* bd_addr */, - tBLE_ADDR_TYPE /* addr_type */) { +tSMP_STATUS SMP_Pair(const RawAddress& /* bd_addr */, tBLE_ADDR_TYPE /* addr_type */) { inc_func_call_count(__func__); return SMP_SUCCESS; } @@ -47,20 +46,15 @@ tSMP_STATUS SMP_Pair(const RawAddress& /* bd_addr */) { void SMP_ConfirmReply(const RawAddress& /* bd_addr */, uint8_t /* res */) { inc_func_call_count(__func__); } -void SMP_Init(uint8_t /* init_security_mode */) { +void SMP_Init(uint8_t /* init_security_mode */) { inc_func_call_count(__func__); } +void SMP_OobDataReply(const RawAddress& /* bd_addr */, tSMP_STATUS /* res */, uint8_t /* len */, + uint8_t* /* p_data */) { inc_func_call_count(__func__); } -void SMP_OobDataReply(const RawAddress& /* bd_addr */, tSMP_STATUS /* res */, - uint8_t /* len */, uint8_t* /* p_data */) { - inc_func_call_count(__func__); -} -void SMP_PasskeyReply(const RawAddress& /* bd_addr */, uint8_t /* res */, - uint32_t /* passkey */) { - inc_func_call_count(__func__); -} -void SMP_SecureConnectionOobDataReply(uint8_t* /* p_data */) { +void SMP_PasskeyReply(const RawAddress& /* bd_addr */, uint8_t /* res */, uint32_t /* passkey */) { inc_func_call_count(__func__); } +void SMP_SecureConnectionOobDataReply(uint8_t* /* p_data */) { inc_func_call_count(__func__); } void SMP_SecurityGrant(const RawAddress& /* bd_addr */, tSMP_STATUS /* res */) { inc_func_call_count(__func__); } @@ -72,7 +66,6 @@ bool SMP_CrLocScOobData() { void SMP_ClearLocScOobData() { inc_func_call_count(__func__); } -void SMP_SirkConfirmDeviceReply(const RawAddress& /* bd_addr */, - uint8_t /* res */) { +void SMP_SirkConfirmDeviceReply(const RawAddress& /* bd_addr */, uint8_t /* res */) { inc_func_call_count(__func__); } diff --git a/system/test/mock/mock_stack_srvc_dis.cc b/system/test/mock/mock_stack_srvc_dis.cc index 1b18c98cf80..5ae7576d563 100644 --- a/system/test/mock/mock_stack_srvc_dis.cc +++ b/system/test/mock/mock_stack_srvc_dis.cc @@ -26,8 +26,7 @@ #include "test/common/mock_functions.h" #include "types/raw_address.h" -bool DIS_ReadDISInfo(const RawAddress& /* peer_bda */, - tDIS_READ_CBACK* /* p_cback */, +bool DIS_ReadDISInfo(const RawAddress& /* peer_bda */, tDIS_READ_CBACK* /* p_cback */, tDIS_ATTR_MASK /* mask */) { inc_func_call_count(__func__); return false; @@ -44,8 +43,7 @@ tDIS_STATUS DIS_SrInit(tDIS_ATTR_MASK /* dis_attr_mask */) { inc_func_call_count(__func__); return 0; } -tDIS_STATUS DIS_SrUpdate(tDIS_ATTR_BIT /* dis_attr_bit */, - tDIS_ATTR* /* p_info */) { +tDIS_STATUS DIS_SrUpdate(tDIS_ATTR_BIT /* dis_attr_bit */, tDIS_ATTR* /* p_info */) { inc_func_call_count(__func__); return 0; } @@ -55,13 +53,11 @@ uint8_t dis_read_attr_value(uint8_t /* clcb_idx */, uint16_t /* handle */, inc_func_call_count(__func__); return 0; } -uint8_t dis_write_attr_value(tGATT_WRITE_REQ* /* p_data */, - tGATT_STATUS* /* p_status */) { +uint8_t dis_write_attr_value(tGATT_WRITE_REQ* /* p_data */, tGATT_STATUS* /* p_status */) { inc_func_call_count(__func__); return 0; } -void dis_c_cmpl_cback(tSRVC_CLCB* /* p_clcb */, tGATTC_OPTYPE /* op */, - tGATT_STATUS /* status */, +void dis_c_cmpl_cback(tSRVC_CLCB* /* p_clcb */, tGATTC_OPTYPE /* op */, tGATT_STATUS /* status */, tGATT_CL_COMPLETE* /* p_data */) { inc_func_call_count(__func__); } diff --git a/system/test/mock/mock_udrv_ulinux_uipc.cc b/system/test/mock/mock_udrv_ulinux_uipc.cc index 3091ebdc74d..cc6d354be33 100644 --- a/system/test/mock/mock_udrv_ulinux_uipc.cc +++ b/system/test/mock/mock_udrv_ulinux_uipc.cc @@ -28,14 +28,13 @@ std::unique_ptr mock_uipc_init_ret; uint32_t mock_uipc_read_ret; bool mock_uipc_send_ret; -bool UIPC_Open(tUIPC_STATE& /* uipc */, tUIPC_CH_ID /* ch_id */, - tUIPC_RCV_CBACK* /* p_cback */, const char* /* socket_path */) { +bool UIPC_Open(tUIPC_STATE& /* uipc */, tUIPC_CH_ID /* ch_id */, tUIPC_RCV_CBACK* /* p_cback */, + const char* /* socket_path */) { inc_func_call_count(__func__); return false; } -bool UIPC_Send(tUIPC_STATE& /* uipc */, tUIPC_CH_ID /* ch_id */, - uint16_t /* msg_evt */, const uint8_t* /* p_buf */, - uint16_t /* msglen */) { +bool UIPC_Send(tUIPC_STATE& /* uipc */, tUIPC_CH_ID /* ch_id */, uint16_t /* msg_evt */, + const uint8_t* /* p_buf */, uint16_t /* msglen */) { inc_func_call_count(__func__); return mock_uipc_send_ret; } @@ -51,25 +50,19 @@ const char* dump_uipc_event(tUIPC_EVENT /* event */) { inc_func_call_count(__func__); return nullptr; } -uint32_t UIPC_Read(tUIPC_STATE& /* uipc */, tUIPC_CH_ID /* ch_id */, - uint8_t* /* p_buf */, uint32_t /* len */) { +uint32_t UIPC_Read(tUIPC_STATE& /* uipc */, tUIPC_CH_ID /* ch_id */, uint8_t* /* p_buf */, + uint32_t /* len */) { inc_func_call_count(__func__); return mock_uipc_read_ret; } -bool UIPC_Ioctl(tUIPC_STATE& /* uipc */, tUIPC_CH_ID /* ch_id */, - uint32_t /* request */, void* /* param */) { +bool UIPC_Ioctl(tUIPC_STATE& /* uipc */, tUIPC_CH_ID /* ch_id */, uint32_t /* request */, + void* /* param */) { inc_func_call_count(__func__); return false; } -void UIPC_Close(tUIPC_STATE& /* uipc */, tUIPC_CH_ID /* ch_id */) { - inc_func_call_count(__func__); -} +void UIPC_Close(tUIPC_STATE& /* uipc */, tUIPC_CH_ID /* ch_id */) { inc_func_call_count(__func__); } void uipc_close_locked(tUIPC_STATE& /* uipc */, tUIPC_CH_ID /* ch_id */) { inc_func_call_count(__func__); } -void uipc_main_cleanup(tUIPC_STATE& /* uipc */) { - inc_func_call_count(__func__); -} -void uipc_stop_main_server_thread(tUIPC_STATE& /* uipc */) { - inc_func_call_count(__func__); -} +void uipc_main_cleanup(tUIPC_STATE& /* uipc */) { inc_func_call_count(__func__); } +void uipc_stop_main_server_thread(tUIPC_STATE& /* uipc */) { inc_func_call_count(__func__); } diff --git a/system/test/stub/osi.cc b/system/test/stub/osi.cc index ed644d516ee..f57f003db40 100644 --- a/system/test/stub/osi.cc +++ b/system/test/stub/osi.cc @@ -60,36 +60,31 @@ void* OsiObject::Release() { } struct StringComparison { - bool operator()(char const* lhs, char const* rhs) const { - return strcmp(lhs, rhs) < 0; - } + bool operator()(char const* lhs, char const* rhs) const { return strcmp(lhs, rhs) < 0; } }; std::map fake_osi_bool_props_map; std::list::iterator section_t::Find(const std::string& key) { inc_func_call_count(__func__); - return std::find_if( - entries.begin(), entries.end(), - [&key](const entry_t& entry) { return entry.key == key; }); + return std::find_if(entries.begin(), entries.end(), + [&key](const entry_t& entry) { return entry.key == key; }); } std::list::iterator config_t::Find(const std::string& section) { inc_func_call_count(__func__); - return std::find_if( - sections.begin(), sections.end(), - [§ion](const section_t& sec) { return sec.name == section; }); + return std::find_if(sections.begin(), sections.end(), + [§ion](const section_t& sec) { return sec.name == section; }); } bool checksum_save(const std::string& checksum, const std::string& filename) { inc_func_call_count(__func__); return false; } -bool config_get_bool(const config_t& config, const std::string& section, - const std::string& key, bool def_value) { +bool config_get_bool(const config_t& config, const std::string& section, const std::string& key, + bool def_value) { inc_func_call_count(__func__); return false; } -bool config_has_key(const config_t& config, const std::string& section, - const std::string& key) { +bool config_has_key(const config_t& config, const std::string& section, const std::string& key) { inc_func_call_count(__func__); return false; } @@ -97,8 +92,7 @@ bool config_has_section(const config_t& config, const std::string& section) { inc_func_call_count(__func__); return false; } -bool config_remove_key(config_t* config, const std::string& section, - const std::string& key) { +bool config_remove_key(config_t* config, const std::string& section, const std::string& key) { inc_func_call_count(__func__); return false; } @@ -118,15 +112,13 @@ bool section_t::Has(const std::string& key) { inc_func_call_count(__func__); return false; } -const std::string* config_get_string(const config_t& config, - const std::string& section, - const std::string& key, - const std::string* def_value) { +const std::string* config_get_string(const config_t& config, const std::string& section, + const std::string& key, const std::string* def_value) { inc_func_call_count(__func__); return nullptr; } -int config_get_int(const config_t& config, const std::string& section, - const std::string& key, int def_value) { +int config_get_int(const config_t& config, const std::string& section, const std::string& key, + int def_value) { inc_func_call_count(__func__); return 0; } @@ -151,28 +143,25 @@ uint64_t config_get_uint64(const config_t& config, const std::string& section, inc_func_call_count(__func__); return 0; } -void config_set_bool(config_t* config, const std::string& section, - const std::string& key, bool value) { - inc_func_call_count(__func__); -} -void config_set_int(config_t* config, const std::string& section, - const std::string& key, int value) { +void config_set_bool(config_t* config, const std::string& section, const std::string& key, + bool value) { inc_func_call_count(__func__); } -void config_set_string(config_t* config, const std::string& section, - const std::string& key, const std::string& value) { +void config_set_int(config_t* config, const std::string& section, const std::string& key, + int value) { inc_func_call_count(__func__); } -void config_set_uint64(config_t* config, const std::string& section, - const std::string& key, uint64_t value) { +void config_set_string(config_t* config, const std::string& section, const std::string& key, + const std::string& value) { inc_func_call_count(__func__); } -void section_t::Set(std::string key, std::string value) { +void config_set_uint64(config_t* config, const std::string& section, const std::string& key, + uint64_t value) { inc_func_call_count(__func__); } +void section_t::Set(std::string key, std::string value) { inc_func_call_count(__func__); } -bool reactor_change_registration(reactor_object_t* object, - void (*read_ready)(void* context), +bool reactor_change_registration(reactor_object_t* object, void (*read_ready)(void* context), void (*write_ready)(void* context)) { inc_func_call_count(__func__); return false; @@ -197,9 +186,7 @@ reactor_t* reactor_new(void) { } void reactor_free(reactor_t* reactor) { inc_func_call_count(__func__); } void reactor_stop(reactor_t* reactor) { inc_func_call_count(__func__); } -void reactor_unregister(reactor_object_t* obj) { - inc_func_call_count(__func__); -} +void reactor_unregister(reactor_object_t* obj) { inc_func_call_count(__func__); } future_t* future_new(void) { inc_func_call_count(__func__); @@ -209,9 +196,7 @@ future_t* future_new_immediate(void* value) { inc_func_call_count(__func__); return nullptr; } -void future_ready(future_t* future, void* value) { - inc_func_call_count(__func__); -} +void future_ready(future_t* future, void* value) { inc_func_call_count(__func__); } void mutex_global_lock(void) { inc_func_call_count(__func__); } void mutex_global_unlock(void) { inc_func_call_count(__func__); } void* future_await(future_t* future) { @@ -306,22 +291,18 @@ size_t fixed_queue_length(fixed_queue_t* queue) { inc_func_call_count(__func__); return 0; } -void fixed_queue_enqueue(fixed_queue_t* queue, void* data) { - inc_func_call_count(__func__); -} +void fixed_queue_enqueue(fixed_queue_t* queue, void* data) { inc_func_call_count(__func__); } void fixed_queue_flush(fixed_queue_t* queue, fixed_queue_free_cb free_cb) { inc_func_call_count(__func__); } void fixed_queue_free(fixed_queue_t* queue, fixed_queue_free_cb free_cb) { inc_func_call_count(__func__); } -void fixed_queue_register_dequeue(fixed_queue_t* queue, reactor_t* reactor, - fixed_queue_cb ready_cb, void* context) { - inc_func_call_count(__func__); -} -void fixed_queue_unregister_dequeue(fixed_queue_t* queue) { +void fixed_queue_register_dequeue(fixed_queue_t* queue, reactor_t* reactor, fixed_queue_cb ready_cb, + void* context) { inc_func_call_count(__func__); } +void fixed_queue_unregister_dequeue(fixed_queue_t* queue) { inc_func_call_count(__func__); } void* fixed_queue_dequeue(fixed_queue_t* queue) { inc_func_call_count(__func__); return nullptr; @@ -354,7 +335,7 @@ alarm_t* alarm_new_periodic(const char* name) { struct fake_osi_alarm_set_on_mloop fake_osi_alarm_set_on_mloop_; bool alarm_is_scheduled(const alarm_t* alarm) { inc_func_call_count(__func__); - return (fake_osi_alarm_set_on_mloop_.cb != nullptr); + return fake_osi_alarm_set_on_mloop_.cb != nullptr; } uint64_t alarm_get_remaining_ms(const alarm_t* alarm) { inc_func_call_count(__func__); @@ -373,13 +354,11 @@ void alarm_free(alarm_t* alarm) { delete[] ptr; inc_func_call_count(__func__); } -void alarm_set(alarm_t* alarm, uint64_t interval_ms, alarm_callback_t cb, - void* data) { +void alarm_set(alarm_t* alarm, uint64_t interval_ms, alarm_callback_t cb, void* data) { inc_func_call_count(__func__); } -void alarm_set_on_mloop(alarm_t* alarm, uint64_t interval_ms, - alarm_callback_t cb, void* data) { +void alarm_set_on_mloop(alarm_t* alarm, uint64_t interval_ms, alarm_callback_t cb, void* data) { inc_func_call_count(__func__); fake_osi_alarm_set_on_mloop_.interval_ms = interval_ms; fake_osi_alarm_set_on_mloop_.cb = cb; @@ -414,14 +393,14 @@ ssize_t socket_write(const socket_t* socket, const void* buf, size_t count) { inc_func_call_count(__func__); return 0; } -ssize_t socket_write_and_transfer_fd(const socket_t* socket, const void* buf, - size_t count, int fd) { +ssize_t socket_write_and_transfer_fd(const socket_t* socket, const void* buf, size_t count, + int fd) { inc_func_call_count(__func__); return 0; } void socket_free(socket_t* socket) { inc_func_call_count(__func__); } -void socket_register(socket_t* socket, reactor_t* reactor, void* context, - socket_cb read_cb, socket_cb write_cb) { +void socket_register(socket_t* socket, reactor_t* reactor, void* context, socket_cb read_cb, + socket_cb write_cb) { inc_func_call_count(__func__); } void socket_unregister(socket_t* socket) { inc_func_call_count(__func__); } @@ -462,8 +441,7 @@ list_node_t* list_end(const list_t* /* list */) { inc_func_call_count(__func__); return nullptr; } -list_node_t* list_foreach(const list_t* list, list_iter_cb callback, - void* context) { +list_node_t* list_foreach(const list_t* list, list_iter_cb callback, void* context) { inc_func_call_count(__func__); return nullptr; } @@ -475,8 +453,7 @@ list_t* list_new(list_free_cb callback) { inc_func_call_count(__func__); return nullptr; } -list_t* list_new_internal(list_free_cb callback, - const allocator_t* zeroed_allocator) { +list_t* list_new_internal(list_free_cb callback, const allocator_t* zeroed_allocator) { inc_func_call_count(__func__); return nullptr; } @@ -503,8 +480,7 @@ int osi_socket_local_client(const char* name, int namespaceId, int type) { inc_func_call_count(__func__); return 0; } -int osi_socket_local_client_connect(int fd, const char* name, int namespaceId, - int type) { +int osi_socket_local_client_connect(int fd, const char* name, int namespaceId, int type) { inc_func_call_count(__func__); return 0; } @@ -512,8 +488,8 @@ int osi_socket_local_server_bind(int s, const char* name, int namespaceId) { inc_func_call_count(__func__); return 0; } -int osi_socket_make_sockaddr_un(const char* name, int namespaceId, - struct sockaddr_un* p_addr, socklen_t* alen) { +int osi_socket_make_sockaddr_un(const char* name, int namespaceId, struct sockaddr_un* p_addr, + socklen_t* alen) { inc_func_call_count(__func__); return 0; } @@ -530,8 +506,7 @@ size_t ringbuffer_insert(ringbuffer_t* rb, const uint8_t* p, size_t length) { inc_func_call_count(__func__); return 0; } -size_t ringbuffer_peek(const ringbuffer_t* rb, off_t offset, uint8_t* p, - size_t length) { +size_t ringbuffer_peek(const ringbuffer_t* rb, off_t offset, uint8_t* p, size_t length) { inc_func_call_count(__func__); return 0; } @@ -547,8 +522,9 @@ void ringbuffer_free(ringbuffer_t* rb) { inc_func_call_count(__func__); } bool osi_property_get_bool(const char* key, bool default_value) { inc_func_call_count(__func__); - if (fake_osi_bool_props_map.count(key)) + if (fake_osi_bool_props_map.count(key)) { return fake_osi_bool_props_map.at(key); + } return default_value; } @@ -579,9 +555,7 @@ bool wakelock_release(void) { } void wakelock_cleanup(void) { inc_func_call_count(__func__); } void wakelock_debug_dump(int fd) { inc_func_call_count(__func__); } -void wakelock_set_os_callouts(bt_os_callouts_t* callouts) { - inc_func_call_count(__func__); -} +void wakelock_set_os_callouts(bt_os_callouts_t* callouts) { inc_func_call_count(__func__); } void wakelock_set_paths(const char* lock_path, const char* unlock_path) { inc_func_call_count(__func__); } diff --git a/system/test/suite/adapter/adapter_unittest.cc b/system/test/suite/adapter/adapter_unittest.cc index dc8771da3c0..65de637a7cb 100644 --- a/system/test/suite/adapter/adapter_unittest.cc +++ b/system/test/suite/adapter/adapter_unittest.cc @@ -33,8 +33,7 @@ const int kTestRepeatCount = 5; namespace bttest { TEST_F(BluetoothTest, AdapterEnableDisable) { - EXPECT_EQ(GetState(), BT_STATE_OFF) - << "Test should be run with Adapter disabled"; + EXPECT_EQ(GetState(), BT_STATE_OFF) << "Test should be run with Adapter disabled"; EXPECT_EQ(bt_interface()->enable(), BT_STATUS_SUCCESS); semaphore_wait(adapter_state_changed_callback_sem_); @@ -46,8 +45,7 @@ TEST_F(BluetoothTest, AdapterEnableDisable) { } TEST_F(BluetoothTest, AdapterRepeatedEnableDisable) { - EXPECT_EQ(GetState(), BT_STATE_OFF) - << "Test should be run with Adapter disabled"; + EXPECT_EQ(GetState(), BT_STATE_OFF) << "Test should be run with Adapter disabled"; for (int i = 0; i < kTestRepeatCount; ++i) { EXPECT_EQ(bt_interface()->enable(), BT_STATUS_SUCCESS); @@ -65,47 +63,37 @@ TEST_F(BluetoothTest, AdapterSetGetName) { EXPECT_EQ(bt_interface()->enable(), BT_STATUS_SUCCESS); semaphore_wait(adapter_state_changed_callback_sem_); - EXPECT_EQ(GetState(), BT_STATE_ON) - << "Test should be run with Adapter enabled"; + EXPECT_EQ(GetState(), BT_STATE_ON) << "Test should be run with Adapter enabled"; // Enabling the interface will call the properties callback twice before // ever reaching this point. ClearSemaphore(adapter_properties_callback_sem_); - EXPECT_EQ(bt_interface()->get_adapter_property(BT_PROPERTY_BDNAME), - BT_STATUS_SUCCESS); + EXPECT_EQ(bt_interface()->get_adapter_property(BT_PROPERTY_BDNAME), BT_STATUS_SUCCESS); semaphore_wait(adapter_properties_callback_sem_); - EXPECT_GT(GetPropertiesChangedCount(), 0) - << "Expected at least one adapter property to change"; + EXPECT_GT(GetPropertiesChangedCount(), 0) << "Expected at least one adapter property to change"; bt_property_t* name_property = GetProperty(BT_PROPERTY_BDNAME); EXPECT_NE(name_property, nullptr); if (property_equals(name_property, new_name)) { property_free(new_name); new_name = property_new_name("BluetoothTestName2"); } - std::string old_name((const char*)property_as_name(name_property)->name, - name_property->len); + std::string old_name((const char*)property_as_name(name_property)->name, name_property->len); EXPECT_EQ(bt_interface()->set_adapter_property(new_name), BT_STATUS_SUCCESS); semaphore_wait(adapter_properties_callback_sem_); - EXPECT_GT(GetPropertiesChangedCount(), 0) - << "Expected at least one adapter property to change"; - EXPECT_TRUE(GetProperty(BT_PROPERTY_BDNAME)) - << "The Bluetooth name property did not change."; + EXPECT_GT(GetPropertiesChangedCount(), 0) << "Expected at least one adapter property to change"; + EXPECT_TRUE(GetProperty(BT_PROPERTY_BDNAME)) << "The Bluetooth name property did not change."; EXPECT_TRUE(property_equals(GetProperty(BT_PROPERTY_BDNAME), new_name)) - << "Bluetooth name " - << property_as_name(GetProperty(BT_PROPERTY_BDNAME))->name - << " does not match test value " << property_as_name(new_name)->name; + << "Bluetooth name " << property_as_name(GetProperty(BT_PROPERTY_BDNAME))->name + << " does not match test value " << property_as_name(new_name)->name; bt_property_t* old_name_property = property_new_name(old_name.c_str()); - EXPECT_EQ(bt_interface()->set_adapter_property(old_name_property), - BT_STATUS_SUCCESS); + EXPECT_EQ(bt_interface()->set_adapter_property(old_name_property), BT_STATUS_SUCCESS); semaphore_wait(adapter_properties_callback_sem_); - EXPECT_TRUE( - property_equals(GetProperty(BT_PROPERTY_BDNAME), old_name_property)) - << "Bluetooth name " - << property_as_name(GetProperty(BT_PROPERTY_BDNAME))->name - << " does not match original name" << old_name; + EXPECT_TRUE(property_equals(GetProperty(BT_PROPERTY_BDNAME), old_name_property)) + << "Bluetooth name " << property_as_name(GetProperty(BT_PROPERTY_BDNAME))->name + << " does not match original name" << old_name; EXPECT_EQ(bt_interface()->disable(), BT_STATUS_SUCCESS); semaphore_wait(adapter_state_changed_callback_sem_); @@ -117,13 +105,11 @@ TEST_F(BluetoothTest, AdapterSetGetName) { TEST_F(BluetoothTest, AdapterStartDiscovery) { EXPECT_EQ(bt_interface()->enable(), BT_STATUS_SUCCESS); semaphore_wait(adapter_state_changed_callback_sem_); - EXPECT_EQ(GetState(), BT_STATE_ON) - << "Test should be run with Adapter enabled"; + EXPECT_EQ(GetState(), BT_STATE_ON) << "Test should be run with Adapter enabled"; EXPECT_EQ(bt_interface()->start_discovery(), BT_STATUS_SUCCESS); semaphore_wait(discovery_state_changed_callback_sem_); - EXPECT_EQ(GetDiscoveryState(), BT_DISCOVERY_STARTED) - << "Unable to start discovery."; + EXPECT_EQ(GetDiscoveryState(), BT_DISCOVERY_STARTED) << "Unable to start discovery."; EXPECT_EQ(bt_interface()->disable(), BT_STATUS_SUCCESS); semaphore_wait(adapter_state_changed_callback_sem_); @@ -133,16 +119,14 @@ TEST_F(BluetoothTest, AdapterStartDiscovery) { TEST_F(BluetoothTest, AdapterCancelDiscovery) { EXPECT_EQ(bt_interface()->enable(), BT_STATUS_SUCCESS); semaphore_wait(adapter_state_changed_callback_sem_); - EXPECT_EQ(GetState(), BT_STATE_ON) - << "Test should be run with Adapter enabled"; + EXPECT_EQ(GetState(), BT_STATE_ON) << "Test should be run with Adapter enabled"; EXPECT_EQ(bt_interface()->start_discovery(), BT_STATUS_SUCCESS); semaphore_wait(discovery_state_changed_callback_sem_); EXPECT_EQ(bt_interface()->cancel_discovery(), BT_STATUS_SUCCESS); semaphore_wait(discovery_state_changed_callback_sem_); - EXPECT_EQ(GetDiscoveryState(), BT_DISCOVERY_STOPPED) - << "Unable to stop discovery."; + EXPECT_EQ(GetDiscoveryState(), BT_DISCOVERY_STOPPED) << "Unable to stop discovery."; EXPECT_EQ(bt_interface()->disable(), BT_STATUS_SUCCESS); semaphore_wait(adapter_state_changed_callback_sem_); @@ -150,8 +134,7 @@ TEST_F(BluetoothTest, AdapterCancelDiscovery) { } TEST_F(BluetoothTest, AdapterDisableDuringBonding) { - EXPECT_EQ(GetState(), BT_STATE_OFF) - << "Test should be run with Adapter disabled"; + EXPECT_EQ(GetState(), BT_STATE_OFF) << "Test should be run with Adapter disabled"; RawAddress bdaddr = {{0x22, 0x22, 0x22, 0x22, 0x22, 0x22}}; @@ -160,8 +143,7 @@ TEST_F(BluetoothTest, AdapterDisableDuringBonding) { semaphore_wait(adapter_state_changed_callback_sem_); EXPECT_EQ(GetState(), BT_STATE_ON) << "Adapter did not turn on."; - EXPECT_EQ(bt_interface()->create_bond(&bdaddr, BT_TRANSPORT_BR_EDR), - BT_STATUS_SUCCESS); + EXPECT_EQ(bt_interface()->create_bond(&bdaddr, BT_TRANSPORT_BR_EDR), BT_STATUS_SUCCESS); EXPECT_EQ(bt_interface()->cancel_bond(&bdaddr), BT_STATUS_SUCCESS); @@ -172,8 +154,7 @@ TEST_F(BluetoothTest, AdapterDisableDuringBonding) { } TEST_F(BluetoothTest, AdapterCleanupDuringDiscovery) { - EXPECT_EQ(GetState(), BT_STATE_OFF) - << "Test should be run with Adapter disabled"; + EXPECT_EQ(GetState(), BT_STATE_OFF) << "Test should be run with Adapter disabled"; bt_callbacks_t* callbacks = bt_callbacks(); ASSERT_TRUE(callbacks != nullptr); @@ -193,4 +174,4 @@ TEST_F(BluetoothTest, AdapterCleanupDuringDiscovery) { } } -} // bttest +} // namespace bttest diff --git a/system/test/suite/adapter/bluetooth_test.cc b/system/test/suite/adapter/bluetooth_test.cc index ead87d440eb..cea06fad0df 100644 --- a/system/test/suite/adapter/bluetooth_test.cc +++ b/system/test/suite/adapter/bluetooth_test.cc @@ -27,15 +27,9 @@ extern bt_interface_t bluetoothInterface; -void semaphore_wait(btsemaphore &s) { - s.wait(); -} -void semaphore_post(btsemaphore &s) { - s.post(); -} -void semaphore_try_wait(btsemaphore &s) { - s.try_wait(); -} +void semaphore_wait(btsemaphore& s) { s.wait(); } +void semaphore_post(btsemaphore& s) { s.post(); } +void semaphore_try_wait(btsemaphore& s) { s.try_wait(); } namespace bttest { @@ -48,23 +42,19 @@ void AdapterStateChangedCallback(bt_state_t new_state) { void AdapterPropertiesCallback(bt_status_t status, int num_properties, bt_property_t* new_properties) { - property_free_array(instance->last_changed_properties_, - instance->properties_changed_count_); - instance->last_changed_properties_ = - property_copy_array(new_properties, num_properties); + property_free_array(instance->last_changed_properties_, instance->properties_changed_count_); + instance->last_changed_properties_ = property_copy_array(new_properties, num_properties); instance->properties_changed_count_ = num_properties; semaphore_post(instance->adapter_properties_callback_sem_); } -void RemoteDevicePropertiesCallback(bt_status_t status, - RawAddress* remote_bd_addr, - int num_properties, - bt_property_t* properties) { +void RemoteDevicePropertiesCallback(bt_status_t status, RawAddress* remote_bd_addr, + int num_properties, bt_property_t* properties) { instance->curr_remote_device_ = *remote_bd_addr; property_free_array(instance->remote_device_last_changed_properties_, instance->remote_device_properties_changed_count_); instance->remote_device_last_changed_properties_ = - property_copy_array(properties, num_properties); + property_copy_array(properties, num_properties); instance->remote_device_properties_changed_count_ = num_properties; semaphore_post(instance->remote_device_properties_callback_sem_); } @@ -75,11 +65,11 @@ void DiscoveryStateChangedCallback(bt_discovery_state_t state) { } static bt_callbacks_t callbacks = { - .size = sizeof(bt_callbacks_t), - .adapter_state_changed_cb = AdapterStateChangedCallback, - .adapter_properties_cb = AdapterPropertiesCallback, - .remote_device_properties_cb = RemoteDevicePropertiesCallback, - .discovery_state_changed_cb = DiscoveryStateChangedCallback, + .size = sizeof(bt_callbacks_t), + .adapter_state_changed_cb = AdapterStateChangedCallback, + .adapter_properties_cb = AdapterPropertiesCallback, + .remote_device_properties_cb = RemoteDevicePropertiesCallback, + .discovery_state_changed_cb = DiscoveryStateChangedCallback, }; void BluetoothTest::SetUp() { @@ -96,8 +86,7 @@ void BluetoothTest::SetUp() { remove("/data/misc/bluedroid/bt_config.conf.encrypted-checksum"); instance = this; - int status = bluetoothInterface.init(&callbacks, false, false, 0, nullptr, - false, nullptr); + int status = bluetoothInterface.init(&callbacks, false, false, 0, nullptr, false, nullptr); ASSERT_EQ(status, BT_STATUS_SUCCESS); } @@ -111,17 +100,13 @@ void BluetoothTest::ClearSemaphore(btsemaphore& sem) { ; } -const bt_interface_t* BluetoothTest::bt_interface() { - return &bluetoothInterface; -} +const bt_interface_t* BluetoothTest::bt_interface() { return &bluetoothInterface; } bt_callbacks_t* BluetoothTest::bt_callbacks() { return &callbacks; } bt_state_t BluetoothTest::GetState() { return state_; } -int BluetoothTest::GetPropertiesChangedCount() { - return properties_changed_count_; -} +int BluetoothTest::GetPropertiesChangedCount() { return properties_changed_count_; } bt_property_t* BluetoothTest::GetProperty(bt_property_type_t type) { for (int i = 0; i < properties_changed_count_; ++i) { @@ -134,7 +119,9 @@ bt_property_t* BluetoothTest::GetProperty(bt_property_type_t type) { bt_property_t* BluetoothTest::GetRemoteDeviceProperty(const RawAddress* addr, bt_property_type_t type) { - if (curr_remote_device_ != *addr) return nullptr; + if (curr_remote_device_ != *addr) { + return nullptr; + } for (int i = 0; i < remote_device_properties_changed_count_; i++) { if (remote_device_last_changed_properties_[i].type == type) { @@ -144,9 +131,7 @@ bt_property_t* BluetoothTest::GetRemoteDeviceProperty(const RawAddress* addr, return nullptr; } -bt_discovery_state_t BluetoothTest::GetDiscoveryState() { - return discovery_state_; -} +bt_discovery_state_t BluetoothTest::GetDiscoveryState() { return discovery_state_; } bt_acl_state_t BluetoothTest::GetAclState() { return acl_state_; } diff --git a/system/test/suite/adapter/bluetooth_test.h b/system/test/suite/adapter/bluetooth_test.h index d83eed04338..27b831f0667 100644 --- a/system/test/suite/adapter/bluetooth_test.h +++ b/system/test/suite/adapter/bluetooth_test.h @@ -34,7 +34,7 @@ #include "types/raw_address.h" class btsemaphore { - public: +public: void post() { std::lock_guard lock(mMutex); ++mCount; @@ -58,21 +58,21 @@ class btsemaphore { return false; } - private: +private: std::mutex mMutex; std::condition_variable mCondition; unsigned long mCount = 0; }; -void semaphore_wait(btsemaphore &s); -void semaphore_post(btsemaphore &s); -void semaphore_try_wait(btsemaphore &s); +void semaphore_wait(btsemaphore& s); +void semaphore_post(btsemaphore& s); +void semaphore_try_wait(btsemaphore& s); namespace bttest { // This class represents the Bluetooth testing framework and provides // helpers and callbacks for GUnit to use for testing. class BluetoothTest : public ::testing::Test { - protected: +protected: BluetoothTest() = default; BluetoothTest(const BluetoothTest&) = delete; BluetoothTest& operator=(const BluetoothTest&) = delete; @@ -96,8 +96,7 @@ class BluetoothTest : public ::testing::Test { bt_property_t* GetProperty(bt_property_type_t type); // Get the value of a specific remote device property - bt_property_t* GetRemoteDeviceProperty(const RawAddress* addr, - bt_property_type_t type); + bt_property_t* GetRemoteDeviceProperty(const RawAddress* addr, bt_property_type_t type); // Get the current discovery state bt_discovery_state_t GetDiscoveryState(); @@ -123,10 +122,8 @@ class BluetoothTest : public ::testing::Test { bt_property_t* properties); // A callback that is called when the remote device's property changes - friend void RemoteDevicePropertiesCallback(bt_status_t status, - RawAddress* remote_bd_addr, - int num_properties, - bt_property_t* properties); + friend void RemoteDevicePropertiesCallback(bt_status_t status, RawAddress* remote_bd_addr, + int num_properties, bt_property_t* properties); // A callback that is called when the adapter state changes friend void AdapterStateChangedCallback(bt_state_t state); @@ -141,7 +138,7 @@ class BluetoothTest : public ::testing::Test { btsemaphore adapter_state_changed_callback_sem_; btsemaphore discovery_state_changed_callback_sem_; - private: +private: bt_state_t state_; int properties_changed_count_; bt_property_t* last_changed_properties_; @@ -153,4 +150,4 @@ class BluetoothTest : public ::testing::Test { bt_bond_state_t bond_state_; }; -} // bttest +} // namespace bttest diff --git a/system/test/suite/gatt/gatt_test.cc b/system/test/suite/gatt/gatt_test.cc index 819f97e6e83..f297e78f2f5 100644 --- a/system/test/suite/gatt/gatt_test.cc +++ b/system/test/suite/gatt/gatt_test.cc @@ -26,33 +26,28 @@ namespace bttest { static GattTest* instance = nullptr; -void RegisterClientCallback(int status, int clientIf, - const bluetooth::Uuid& app_uuid) { +void RegisterClientCallback(int status, int clientIf, const bluetooth::Uuid& app_uuid) { instance->status_ = status; instance->client_interface_id_ = clientIf; semaphore_post(instance->register_client_callback_sem_); } -void ScanResultCallback(uint16_t ble_evt_type, uint8_t addr_type, - RawAddress* bda, uint8_t ble_primary_phy, - uint8_t ble_secondary_phy, uint8_t ble_advertising_sid, - int8_t ble_tx_power, int8_t rssi, - uint16_t ble_periodic_adv_int, - std::vector adv_data, +void ScanResultCallback(uint16_t ble_evt_type, uint8_t addr_type, RawAddress* bda, + uint8_t ble_primary_phy, uint8_t ble_secondary_phy, + uint8_t ble_advertising_sid, int8_t ble_tx_power, int8_t rssi, + uint16_t ble_periodic_adv_int, std::vector adv_data, RawAddress* original_bda) { semaphore_post(instance->scan_result_callback_sem_); } // GATT server callbacks -void RegisterServerCallback(int status, int server_if, - const bluetooth::Uuid& uuid) { +void RegisterServerCallback(int status, int server_if, const bluetooth::Uuid& uuid) { instance->status_ = status; instance->server_interface_id_ = server_if; semaphore_post(instance->register_server_callback_sem_); } -void ServiceAddedCallback(int status, int server_if, - const btgatt_db_element_t* service, +void ServiceAddedCallback(int status, int server_if, const btgatt_db_element_t* service, size_t service_count) { instance->status_ = status; instance->server_interface_id_ = server_if; @@ -75,25 +70,25 @@ void ServiceDeletedCallback(int status, int server_if, int srvc_handle) { } static const btgatt_scanner_callbacks_t scanner_callbacks = { - .scan_result_cb = ScanResultCallback, + .scan_result_cb = ScanResultCallback, }; static const btgatt_client_callbacks_t client_callbacks = { - .register_client_cb = RegisterClientCallback, + .register_client_cb = RegisterClientCallback, }; static const btgatt_server_callbacks_t server_callbacks = { - .register_server_cb = RegisterServerCallback, - .service_added_cb = ServiceAddedCallback, - .service_stopped_cb = ServiceStoppedCallback, - .service_deleted_cb = ServiceDeletedCallback, + .register_server_cb = RegisterServerCallback, + .service_added_cb = ServiceAddedCallback, + .service_stopped_cb = ServiceStoppedCallback, + .service_deleted_cb = ServiceDeletedCallback, }; static const btgatt_callbacks_t callbacks = { - sizeof(btgatt_callbacks_t), - &client_callbacks, - &server_callbacks, - &scanner_callbacks, + sizeof(btgatt_callbacks_t), + &client_callbacks, + &server_callbacks, + &scanner_callbacks, }; void GattTest::SetUp() { @@ -112,7 +107,7 @@ void GattTest::SetUp() { EXPECT_TRUE(GetState() == BT_STATE_ON); gatt_interface_ = reinterpret_cast( - bt_interface()->get_profile_interface(BT_PROFILE_GATT_ID)); + bt_interface()->get_profile_interface(BT_PROFILE_GATT_ID)); ASSERT_NE(nullptr, gatt_interface_); instance = this; auto status = gatt_interface_->init(&callbacks); @@ -128,9 +123,7 @@ void GattTest::TearDown() { BluetoothTest::TearDown(); } -const BleScannerInterface* GattTest::gatt_scanner_interface() { - return gatt_interface_->scanner; -} +const BleScannerInterface* GattTest::gatt_scanner_interface() { return gatt_interface_->scanner; } const btgatt_client_interface_t* GattTest::gatt_client_interface() { return gatt_interface_->client; @@ -140,4 +133,4 @@ const btgatt_server_interface_t* GattTest::gatt_server_interface() { return gatt_interface_->server; } -} // bttest +} // namespace bttest diff --git a/system/test/suite/gatt/gatt_test.h b/system/test/suite/gatt/gatt_test.h index 9dadd4f2284..6385e6637d1 100644 --- a/system/test/suite/gatt/gatt_test.h +++ b/system/test/suite/gatt/gatt_test.h @@ -25,7 +25,7 @@ namespace bttest { // This class represents the Bluetooth GATT testing framework and provides // helpers and callbacks for GUnit to use for testing gatt. class GattTest : public BluetoothTest { - protected: +protected: GattTest() = default; GattTest(const GattTest&) = delete; GattTest& operator=(const GattTest&) = delete; @@ -57,26 +57,18 @@ class GattTest : public BluetoothTest { // callback semaphores at the end of every test virtual void TearDown(); - friend void RegisterClientCallback(int status, int clientIf, - const bluetooth::Uuid& app_uuid); - friend void ScanResultCallback(uint16_t ble_evt_type, uint8_t addr_type, - RawAddress* bda, uint8_t ble_primary_phy, - uint8_t ble_secondary_phy, - uint8_t ble_advertising_sid, - int8_t ble_tx_power, int8_t rssi, - uint16_t ble_periodic_adv_int, - std::vector adv_data, + friend void RegisterClientCallback(int status, int clientIf, const bluetooth::Uuid& app_uuid); + friend void ScanResultCallback(uint16_t ble_evt_type, uint8_t addr_type, RawAddress* bda, + uint8_t ble_primary_phy, uint8_t ble_secondary_phy, + uint8_t ble_advertising_sid, int8_t ble_tx_power, int8_t rssi, + uint16_t ble_periodic_adv_int, std::vector adv_data, RawAddress* original_bda); - friend void RegisterServerCallback(int status, int server_if, - const bluetooth::Uuid& uuid); - friend void ServiceAddedCallback(int status, int server_if, - const btgatt_db_element_t* service, + friend void RegisterServerCallback(int status, int server_if, const bluetooth::Uuid& uuid); + friend void ServiceAddedCallback(int status, int server_if, const btgatt_db_element_t* service, size_t service_count); - friend void ServiceStoppedCallback(int status, int server_if, - int srvc_handle); - friend void ServiceDeletedCallback(int status, int server_if, - int srvc_handle); + friend void ServiceStoppedCallback(int status, int server_if, int srvc_handle); + friend void ServiceDeletedCallback(int status, int server_if, int srvc_handle); // Semaphores used to wait for specific callback execution. Each callback // has its own semaphore associated with it @@ -92,7 +84,7 @@ class GattTest : public BluetoothTest { btsemaphore service_stopped_callback_sem_; btsemaphore service_deleted_callback_sem_; - private: +private: const btgatt_interface_t* gatt_interface_; // No mutex needed for these as the semaphores should ensure @@ -117,4 +109,4 @@ class GattTest : public BluetoothTest { int status_; }; -} // bttest +} // namespace bttest diff --git a/system/test/suite/gatt/gatt_unittest.cc b/system/test/suite/gatt/gatt_unittest.cc index a53b01b88cc..aed80c1f10b 100644 --- a/system/test/suite/gatt/gatt_unittest.cc +++ b/system/test/suite/gatt/gatt_unittest.cc @@ -29,11 +29,10 @@ namespace bttest { TEST_F(GattTest, GattClientRegister) { // Registers gatt client. bluetooth::Uuid gatt_client_uuid = bluetooth::Uuid::From128BitBE( - bluetooth::os::GenerateRandom()); + bluetooth::os::GenerateRandom()); gatt_client_interface()->register_client(gatt_client_uuid, false); semaphore_wait(register_client_callback_sem_); - EXPECT_TRUE(status() == BT_STATUS_SUCCESS) - << "Error registering GATT client app callback."; + EXPECT_TRUE(status() == BT_STATUS_SUCCESS) << "Error registering GATT client app callback."; // Unregisters gatt client. No callback is expected. gatt_client_interface()->unregister_client(client_interface_id()); @@ -42,11 +41,10 @@ TEST_F(GattTest, GattClientRegister) { TEST_F(GattTest, GattServerRegister) { // Registers gatt server. bluetooth::Uuid gatt_server_uuid = bluetooth::Uuid::From128BitBE( - bluetooth::os::GenerateRandom()); + bluetooth::os::GenerateRandom()); gatt_server_interface()->register_server(gatt_server_uuid, false); semaphore_wait(register_server_callback_sem_); - EXPECT_TRUE(status() == BT_STATUS_SUCCESS) - << "Error registering GATT server app callback."; + EXPECT_TRUE(status() == BT_STATUS_SUCCESS) << "Error registering GATT server app callback."; // Unregisters gatt server. No callback is expected. gatt_server_interface()->unregister_server(server_interface_id()); @@ -55,46 +53,43 @@ TEST_F(GattTest, GattServerRegister) { TEST_F(GattTest, GattServerBuild) { // Registers gatt server. bluetooth::Uuid gatt_server_uuid = bluetooth::Uuid::From128BitBE( - bluetooth::os::GenerateRandom()); + bluetooth::os::GenerateRandom()); gatt_server_interface()->register_server(gatt_server_uuid, false); semaphore_wait(register_server_callback_sem_); - EXPECT_TRUE(status() == BT_STATUS_SUCCESS) - << "Error registering GATT server app callback."; + EXPECT_TRUE(status() == BT_STATUS_SUCCESS) << "Error registering GATT server app callback."; // Service UUID. bluetooth::Uuid srvc_uuid = bluetooth::Uuid::From128BitBE( - bluetooth::os::GenerateRandom()); + bluetooth::os::GenerateRandom()); // Characteristics UUID. bluetooth::Uuid char_uuid = bluetooth::Uuid::From128BitBE( - bluetooth::os::GenerateRandom()); + bluetooth::os::GenerateRandom()); // Descriptor UUID. bluetooth::Uuid desc_uuid = bluetooth::Uuid::From128BitBE( - bluetooth::os::GenerateRandom()); + bluetooth::os::GenerateRandom()); // Adds service. int server_if = server_interface_id(); - std::vector service = { - { - .uuid = srvc_uuid, - .type = BTGATT_DB_PRIMARY_SERVICE, - }, - { - .uuid = char_uuid, - .type = BTGATT_DB_CHARACTERISTIC, - .properties = 0x10, /* notification */ - .permissions = 0x01, /* read only */ - }, - { - .uuid = desc_uuid, - .type = BTGATT_DB_DESCRIPTOR, - .permissions = 0x01, - }}; - - gatt_server_interface()->add_service(server_if, service.data(), - service.size()); + std::vector service = {{ + .uuid = srvc_uuid, + .type = BTGATT_DB_PRIMARY_SERVICE, + }, + { + .uuid = char_uuid, + .type = BTGATT_DB_CHARACTERISTIC, + .properties = 0x10, /* notification */ + .permissions = 0x01, /* read only */ + }, + { + .uuid = desc_uuid, + .type = BTGATT_DB_DESCRIPTOR, + .permissions = 0x01, + }}; + + gatt_server_interface()->add_service(server_if, service.data(), service.size()); semaphore_wait(service_added_callback_sem_); EXPECT_TRUE(status() == BT_STATUS_SUCCESS) << "Error adding service."; EXPECT_TRUE(server_interface_id() == server_if) << "Wrong server_if added."; @@ -104,20 +99,18 @@ TEST_F(GattTest, GattServerBuild) { gatt_server_interface()->stop_service(server_if, service_handle()); semaphore_wait(service_stopped_callback_sem_); EXPECT_TRUE(status() == BT_STATUS_SUCCESS) << "Error stopping server."; - EXPECT_TRUE(service_handle() == service_handle_added) - << "Wrong service handle stopped."; + EXPECT_TRUE(service_handle() == service_handle_added) << "Wrong service handle stopped."; EXPECT_TRUE(server_interface_id() == server_if) << "Wrong server_if stopped."; // Deletes service. gatt_server_interface()->delete_service(server_if, service_handle()); semaphore_wait(service_deleted_callback_sem_); EXPECT_TRUE(status() == BT_STATUS_SUCCESS) << "Error deleting service."; - EXPECT_TRUE(service_handle() == service_handle_added) - << "Wrong service handle deleted."; + EXPECT_TRUE(service_handle() == service_handle_added) << "Wrong service handle deleted."; EXPECT_TRUE(server_interface_id() == server_if) << "Wrong server_if deleted."; // Unregisters gatt server. No callback is expected. gatt_server_interface()->unregister_server(server_if); } -} // bttest +} // namespace bttest diff --git a/system/types/ble_address_with_type.h b/system/types/ble_address_with_type.h index eacd01adc4b..21fe9dfb0e0 100644 --- a/system/types/ble_address_with_type.h +++ b/system/types/ble_address_with_type.h @@ -61,16 +61,12 @@ inline bool is_ble_addr_type_known(tBLE_ADDR_TYPE type) { } } -inline tBLE_ADDR_TYPE to_ble_addr_type(uint8_t raw_type) { - return (tBLE_ADDR_TYPE)raw_type; -} +inline tBLE_ADDR_TYPE to_ble_addr_type(uint8_t raw_type) { return (tBLE_ADDR_TYPE)raw_type; } inline uint8_t from_ble_addr_type(tBLE_ADDR_TYPE type) { return (uint8_t)type; } /* BLE ADDR type ID bit */ #define BLE_ADDR_TYPE_ID_BIT 0x02 -inline bool is_identity_type(const tBLE_ADDR_TYPE& type) { - return type & BLE_ADDR_TYPE_ID_BIT; -} +inline bool is_identity_type(const tBLE_ADDR_TYPE& type) { return type & BLE_ADDR_TYPE_ID_BIT; } #define STREAM_TO_BLE_ADDR_TYPE(type, p) \ { \ @@ -84,10 +80,8 @@ inline bool is_identity_type(const tBLE_ADDR_TYPE& type) { constexpr uint8_t kBleAddressPublicDevice = BLE_ADDR_PUBLIC; constexpr uint8_t kBleAddressRandomDevice = BLE_ADDR_RANDOM; constexpr uint8_t kBleAddressIdentityBit = BLE_ADDR_TYPE_ID_BIT; -constexpr uint8_t kBleAddressPublicIdentity = - kBleAddressIdentityBit | kBleAddressPublicDevice; -constexpr uint8_t kBleAddressRandomIdentity = - kBleAddressIdentityBit | kBleAddressRandomDevice; +constexpr uint8_t kBleAddressPublicIdentity = kBleAddressIdentityBit | kBleAddressPublicDevice; +constexpr uint8_t kBleAddressRandomIdentity = kBleAddressIdentityBit | kBleAddressRandomDevice; constexpr uint8_t kResolvableAddressMask = 0xc0; constexpr uint8_t kResolvableAddressMsb = 0x40; @@ -98,25 +92,16 @@ struct tBLE_BD_ADDR { bool AddressEquals(const RawAddress& other) const { return other == bda; } bool IsPublicDeviceType() const { return type == kBleAddressPublicDevice; } bool IsRandomDeviceType() const { return type == kBleAddressRandomDevice; } - bool IsPublicIdentityType() const { - return type == kBleAddressPublicIdentity; - } - bool lsRandomIdentityType() const { - return type == kBleAddressRandomIdentity; - } + bool IsPublicIdentityType() const { return type == kBleAddressPublicIdentity; } + bool lsRandomIdentityType() const { return type == kBleAddressRandomIdentity; } bool IsAddressResolvable() const { return ((bda.address)[0] & kResolvableAddressMask) == kResolvableAddressMsb; } bool IsPublic() const { return !(type & 0x01); } - bool IsResolvablePrivateAddress() const { - return IsAddressResolvable() && IsRandomDeviceType(); - } - bool IsIdentityType() const { - return IsPublicIdentityType() || lsRandomIdentityType(); - } + bool IsResolvablePrivateAddress() const { return IsAddressResolvable() && IsRandomDeviceType(); } + bool IsIdentityType() const { return IsPublicIdentityType() || lsRandomIdentityType(); } bool TypeWithoutIdentityEquals(const tBLE_ADDR_TYPE other) const { - return (other & ~kBleAddressIdentityBit) == - (type & ~kBleAddressIdentityBit); + return (other & ~kBleAddressIdentityBit) == (type & ~kBleAddressIdentityBit); } std::string ToString() const { @@ -131,22 +116,18 @@ struct tBLE_BD_ADDR { return bda.ToRedactedStringForLogging() + "[" + AddressTypeText(type) + "]"; } - bool operator==(const tBLE_BD_ADDR rhs) const { - return rhs.type == type && rhs.bda == bda; - } + bool operator==(const tBLE_BD_ADDR rhs) const { return rhs.type == type && rhs.bda == bda; } bool operator!=(const tBLE_BD_ADDR rhs) const { return !(*this == rhs); } }; template <> struct std::hash { std::size_t operator()(const tBLE_BD_ADDR& val) const { - static_assert(sizeof(uint64_t) >= - (RawAddress::kLength + sizeof(tBLE_ADDR_TYPE))); + static_assert(sizeof(uint64_t) >= (RawAddress::kLength + sizeof(tBLE_ADDR_TYPE))); uint64_t int_addr = 0; - memcpy(reinterpret_cast(&int_addr), val.bda.address, - RawAddress::kLength); - memcpy(reinterpret_cast(&int_addr) + RawAddress::kLength, - (const void*)&val.type, sizeof(tBLE_ADDR_TYPE)); + memcpy(reinterpret_cast(&int_addr), val.bda.address, RawAddress::kLength); + memcpy(reinterpret_cast(&int_addr) + RawAddress::kLength, (const void*)&val.type, + sizeof(tBLE_ADDR_TYPE)); return std::hash{}(int_addr); } }; @@ -156,7 +137,9 @@ struct tAclLinkSpec { tBT_TRANSPORT transport; bool operator==(const tAclLinkSpec rhs) const { - if (rhs.addrt != addrt) return false; + if (rhs.addrt != addrt) { + return false; + } if (rhs.transport == BT_TRANSPORT_AUTO || transport == BT_TRANSPORT_AUTO) { return true; @@ -172,18 +155,15 @@ struct tAclLinkSpec { } std::string ToString() const { - return std::string(addrt.ToString() + "[" + bt_transport_text(transport) + - "]"); + return std::string(addrt.ToString() + "[" + bt_transport_text(transport) + "]"); } std::string ToStringForLogging() const { - return addrt.ToStringForLogging() + "[" + bt_transport_text(transport) + - "]"; + return addrt.ToStringForLogging() + "[" + bt_transport_text(transport) + "]"; } std::string ToRedactedStringForLogging() const { - return addrt.ToRedactedStringForLogging() + "[" + - bt_transport_text(transport) + "]"; + return addrt.ToRedactedStringForLogging() + "[" + bt_transport_text(transport) + "]"; } }; @@ -198,22 +178,20 @@ namespace fmt { template <> struct formatter : formatter { template - typename Context::iterator format(const tBLE_BD_ADDR& address, - Context& ctx) const { + typename Context::iterator format(const tBLE_BD_ADDR& address, Context& ctx) const { std::string repr = bluetooth::os::should_log_be_redacted() - ? address.ToRedactedStringForLogging() - : address.ToStringForLogging(); + ? address.ToRedactedStringForLogging() + : address.ToStringForLogging(); return fmt::formatter::format(repr, ctx); } }; template <> struct formatter : formatter { template - typename Context::iterator format(const tAclLinkSpec& address, - Context& ctx) const { + typename Context::iterator format(const tAclLinkSpec& address, Context& ctx) const { std::string repr = bluetooth::os::should_log_be_redacted() - ? address.ToRedactedStringForLogging() - : address.ToStringForLogging(); + ? address.ToRedactedStringForLogging() + : address.ToStringForLogging(); return fmt::formatter::format(repr, ctx); } }; diff --git a/system/types/bluetooth/uuid.cc b/system/types/bluetooth/uuid.cc index 96763054ce4..f5c3922d7b2 100644 --- a/system/types/bluetooth/uuid.cc +++ b/system/types/bluetooth/uuid.cc @@ -35,72 +35,90 @@ using UUID128Bit = Uuid::UUID128Bit; const Uuid Uuid::kEmpty = Uuid::From128BitBE(UUID128Bit{{0x00}}); namespace { -constexpr Uuid kBase = Uuid::From128BitBE( - UUID128Bit{{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, - 0x00, 0x80, 0x5f, 0x9b, 0x34, 0xfb}}); +constexpr Uuid kBase = + Uuid::From128BitBE(UUID128Bit{{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, + 0x00, 0x80, 0x5f, 0x9b, 0x34, 0xfb}}); } // namespace size_t Uuid::GetShortestRepresentationSize() const { - if (memcmp(uu.data() + kNumBytes32, kBase.uu.data() + kNumBytes32, - kNumBytes128 - kNumBytes32) != 0) { + if (memcmp(uu.data() + kNumBytes32, kBase.uu.data() + kNumBytes32, kNumBytes128 - kNumBytes32) != + 0) { return kNumBytes128; } - if (uu[0] == 0 && uu[1] == 0) return kNumBytes16; + if (uu[0] == 0 && uu[1] == 0) { + return kNumBytes16; + } return kNumBytes32; } -bool Uuid::Is16Bit() const { - return GetShortestRepresentationSize() == kNumBytes16; -} +bool Uuid::Is16Bit() const { return GetShortestRepresentationSize() == kNumBytes16; } uint16_t Uuid::As16Bit() const { return (((uint16_t)uu[2]) << 8) + uu[3]; } uint32_t Uuid::As32Bit() const { - return (((uint32_t)uu[0]) << 24) + (((uint32_t)uu[1]) << 16) + - (((uint32_t)uu[2]) << 8) + uu[3]; + return (((uint32_t)uu[0]) << 24) + (((uint32_t)uu[1]) << 16) + (((uint32_t)uu[2]) << 8) + uu[3]; } Uuid Uuid::FromString(const std::string& uuid, bool* is_valid) { - if (is_valid) *is_valid = false; + if (is_valid) { + *is_valid = false; + } Uuid ret = kBase; - if (uuid.empty()) return ret; + if (uuid.empty()) { + return ret; + } uint8_t* p = ret.uu.data(); if (uuid.size() == kString128BitLen) { - if (uuid[8] != '-' || uuid[13] != '-' || uuid[18] != '-' || - uuid[23] != '-') { + if (uuid[8] != '-' || uuid[13] != '-' || uuid[18] != '-' || uuid[23] != '-') { return ret; } int c; - int rc = - sscanf(uuid.c_str(), - "%02hhx%02hhx%02hhx%02hhx-%02hhx%02hhx-%02hhx%02hhx" - "-%02hhx%02hhx-%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%n", - &p[0], &p[1], &p[2], &p[3], &p[4], &p[5], &p[6], &p[7], &p[8], - &p[9], &p[10], &p[11], &p[12], &p[13], &p[14], &p[15], &c); - if (rc != 16) return ret; - if (c != kString128BitLen) return ret; - - if (is_valid) *is_valid = true; + int rc = sscanf(uuid.c_str(), + "%02hhx%02hhx%02hhx%02hhx-%02hhx%02hhx-%02hhx%02hhx" + "-%02hhx%02hhx-%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%n", + &p[0], &p[1], &p[2], &p[3], &p[4], &p[5], &p[6], &p[7], &p[8], &p[9], &p[10], + &p[11], &p[12], &p[13], &p[14], &p[15], &c); + if (rc != 16) { + return ret; + } + if (c != kString128BitLen) { + return ret; + } + + if (is_valid) { + *is_valid = true; + } } else if (uuid.size() == 8) { int c; - int rc = sscanf(uuid.c_str(), "%02hhx%02hhx%02hhx%02hhx%n", &p[0], &p[1], - &p[2], &p[3], &c); - if (rc != 4) return ret; - if (c != 8) return ret; + int rc = sscanf(uuid.c_str(), "%02hhx%02hhx%02hhx%02hhx%n", &p[0], &p[1], &p[2], &p[3], &c); + if (rc != 4) { + return ret; + } + if (c != 8) { + return ret; + } - if (is_valid) *is_valid = true; + if (is_valid) { + *is_valid = true; + } } else if (uuid.size() == 4) { int c; int rc = sscanf(uuid.c_str(), "%02hhx%02hhx%n", &p[2], &p[3], &c); - if (rc != 2) return ret; - if (c != 4) return ret; + if (rc != 2) { + return ret; + } + if (c != 4) { + return ret; + } - if (is_valid) *is_valid = true; + if (is_valid) { + *is_valid = true; + } } return ret; @@ -154,13 +172,10 @@ bool Uuid::IsEmpty() const { return *this == kEmpty; } bool Uuid::IsBase() const { return *this == kBase; } -void Uuid::UpdateUuid(const Uuid& uuid) { - uu = uuid.uu; -} +void Uuid::UpdateUuid(const Uuid& uuid) { uu = uuid.uu; } bool Uuid::operator<(const Uuid& rhs) const { - return std::lexicographical_compare(uu.begin(), uu.end(), rhs.uu.begin(), - rhs.uu.end()); + return std::lexicographical_compare(uu.begin(), uu.end(), rhs.uu.begin(), rhs.uu.end()); } bool Uuid::operator==(const Uuid& rhs) const { return uu == rhs.uu; } diff --git a/system/types/bluetooth/uuid.h b/system/types/bluetooth/uuid.h index 3c464db544a..9c094415444 100644 --- a/system/types/bluetooth/uuid.h +++ b/system/types/bluetooth/uuid.h @@ -34,7 +34,7 @@ namespace bluetooth { // Endian. // 4. UUID in storage is always string. class Uuid final { - public: +public: static constexpr size_t kNumBytes128 = 16; static constexpr size_t kNumBytes32 = 4; static constexpr size_t kNumBytes16 = 2; @@ -114,8 +114,8 @@ class Uuid final { bool operator==(const Uuid& rhs) const; bool operator!=(const Uuid& rhs) const; - private: - constexpr Uuid(const UUID128Bit& val) : uu{val} {}; +private: + constexpr Uuid(const UUID128Bit& val) : uu{val} {} // Network-byte-ordered ID (Big Endian). UUID128Bit uu; @@ -137,8 +137,8 @@ struct hash { std::size_t operator()(const bluetooth::Uuid& key) const { const auto& uuid_bytes = key.To128BitBE(); std::hash hash_fn; - return hash_fn(std::string(reinterpret_cast(uuid_bytes.data()), - uuid_bytes.size())); + return hash_fn( + std::string(reinterpret_cast(uuid_bytes.data()), uuid_bytes.size())); } }; diff --git a/system/types/hci_role.h b/system/types/hci_role.h index bdd0940756b..bbedb238ed9 100644 --- a/system/types/hci_role.h +++ b/system/types/hci_role.h @@ -37,12 +37,13 @@ inline std::string hci_role_text(const tHCI_ROLE& role) { } inline tHCI_ROLE to_hci_role(const uint8_t& role) { - if (role == 0) + if (role == 0) { return HCI_ROLE_CENTRAL; - else if (role == 1) + } else if (role == 1) { return HCI_ROLE_PERIPHERAL; - else + } else { return HCI_ROLE_UNKNOWN; + } } typedef tHCI_ROLE hci_role_t; // LEGACY diff --git a/system/types/raw_address.cc b/system/types/raw_address.cc index 45705531eae..a5e292701f9 100644 --- a/system/types/raw_address.cc +++ b/system/types/raw_address.cc @@ -31,9 +31,7 @@ static_assert(sizeof(RawAddress) == 6, "RawAddress must be 6 bytes long!"); const RawAddress RawAddress::kAny{{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}}; const RawAddress RawAddress::kEmpty{{0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}; -RawAddress::RawAddress(const uint8_t (&addr)[6]) { - std::copy(addr, addr + kLength, address); -} +RawAddress::RawAddress(const uint8_t (&addr)[6]) { std::copy(addr, addr + kLength, address); } RawAddress::RawAddress(const std::array mac) { std::copy(mac.begin(), mac.end(), address); @@ -53,9 +51,7 @@ std::string RawAddress::ToColonSepHexString() const { return addr.str(); } -std::string RawAddress::ToStringForLogging() const { - return ToColonSepHexString(); -} +std::string RawAddress::ToStringForLogging() const { return ToColonSepHexString(); } std::string RawAddress::ToRedactedStringForLogging() const { if (*this == RawAddress::kAny || *this == RawAddress::kEmpty) { @@ -77,7 +73,9 @@ std::array RawAddress::ToArray() const { bool RawAddress::FromString(const std::string& from, RawAddress& to) { RawAddress new_addr; - if (from.length() != 17) return false; + if (from.length() != 17) { + return false; + } std::istringstream stream(from); std::string token; @@ -116,7 +114,7 @@ bool RawAddress::FromString(const std::string& from, RawAddress& to) { size_t RawAddress::FromOctets(const uint8_t* from) { std::copy(from, from + kLength, address); return kLength; -}; +} bool RawAddress::IsValidAddress(const std::string& address) { RawAddress tmp; diff --git a/system/types/raw_address.h b/system/types/raw_address.h index d60da54f290..b19d95d9a9a 100644 --- a/system/types/raw_address.h +++ b/system/types/raw_address.h @@ -25,7 +25,7 @@ /** Bluetooth Address */ class RawAddress final { - public: +public: static constexpr unsigned int kLength = 6; uint8_t address[kLength]; @@ -35,12 +35,12 @@ class RawAddress final { RawAddress(const std::array array); bool operator<(const RawAddress& rhs) const { - return (std::memcmp(address, rhs.address, sizeof(address)) < 0); + return std::memcmp(address, rhs.address, sizeof(address)) < 0; } bool operator==(const RawAddress& rhs) const { - return (std::memcmp(address, rhs.address, sizeof(address)) == 0); + return std::memcmp(address, rhs.address, sizeof(address)) == 0; } - bool operator>(const RawAddress& rhs) const { return (rhs < *this); } + bool operator>(const RawAddress& rhs) const { return rhs < *this; } bool operator<=(const RawAddress& rhs) const { return !(*this > rhs); } bool operator>=(const RawAddress& rhs) const { return !(*this < rhs); } bool operator!=(const RawAddress& rhs) const { return !(*this == rhs); } @@ -90,8 +90,7 @@ struct std::hash { std::size_t operator()(const RawAddress& val) const { static_assert(sizeof(uint64_t) >= RawAddress::kLength); uint64_t int_addr = 0; - memcpy(reinterpret_cast(&int_addr), val.address, - RawAddress::kLength); + memcpy(reinterpret_cast(&int_addr), val.address, RawAddress::kLength); return std::hash{}(int_addr); } }; @@ -99,13 +98,16 @@ struct std::hash { #define BD_ADDR_LEN 6 /* Device address length */ inline void BDADDR_TO_STREAM(uint8_t*& p, const RawAddress& a) { - for (int ijk = 0; ijk < BD_ADDR_LEN; ijk++) + for (int ijk = 0; ijk < BD_ADDR_LEN; ijk++) { *(p)++ = (uint8_t)(a.address)[BD_ADDR_LEN - 1 - ijk]; + } } inline void STREAM_TO_BDADDR(RawAddress& a, const uint8_t*& p) { uint8_t* pbda = (uint8_t*)(a.address) + BD_ADDR_LEN - 1; - for (int ijk = 0; ijk < BD_ADDR_LEN; ijk++) *pbda-- = *(p)++; + for (int ijk = 0; ijk < BD_ADDR_LEN; ijk++) { + *pbda-- = *(p)++; + } } #if __has_include() @@ -119,11 +121,10 @@ namespace fmt { template <> struct formatter : formatter { template - typename Context::iterator format(const RawAddress& address, - Context& ctx) const { + typename Context::iterator format(const RawAddress& address, Context& ctx) const { std::string repr = bluetooth::os::should_log_be_redacted() - ? address.ToRedactedStringForLogging() - : address.ToStringForLogging(); + ? address.ToRedactedStringForLogging() + : address.ToStringForLogging(); return fmt::formatter::format(repr, ctx); } }; diff --git a/system/types/remote_version_type.h b/system/types/remote_version_type.h index f64aad8c18c..1585dabf34b 100644 --- a/system/types/remote_version_type.h +++ b/system/types/remote_version_type.h @@ -29,8 +29,8 @@ struct tREMOTE_VERSION_INFO { uint16_t manufacturer{0}; bool valid{false}; std::string ToString() const { - return (valid) ? base::StringPrintf("%02hhu-%05hu-%05hu", lmp_version, - lmp_subversion, manufacturer) + return (valid) ? base::StringPrintf("%02hhu-%05hu-%05hu", lmp_version, lmp_subversion, + manufacturer) : std::string("UNKNOWN"); } }; diff --git a/system/types/test/ble_address_with_type_unittest.cc b/system/types/test/ble_address_with_type_unittest.cc index 60eaffb0c0c..2940947a91e 100644 --- a/system/types/test/ble_address_with_type_unittest.cc +++ b/system/types/test/ble_address_with_type_unittest.cc @@ -17,8 +17,7 @@ #include "types/ble_address_with_type.h" #include -static constexpr uint8_t RAW_ADDRESS_TEST1[6] = {0x01, 0x02, 0x03, - 0x04, 0x05, 0x06}; +static constexpr uint8_t RAW_ADDRESS_TEST1[6] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06}; TEST(BleAddressWithTypeTest, to_ble_addr_type) { for (unsigned i = 0; i < 0xff + 1; i++) { @@ -50,9 +49,8 @@ TEST(BleAddressWithTypeTest, from_ble_addr_type) { tBLE_ADDR_TYPE type; uint8_t value; } type_table[] = { - {BLE_ADDR_PUBLIC, 0}, {BLE_ADDR_RANDOM, 1}, - {BLE_ADDR_PUBLIC_ID, 2}, {BLE_ADDR_RANDOM_ID, 3}, - {BLE_ADDR_ANONYMOUS, 0xff}, + {BLE_ADDR_PUBLIC, 0}, {BLE_ADDR_RANDOM, 1}, {BLE_ADDR_PUBLIC_ID, 2}, + {BLE_ADDR_RANDOM_ID, 3}, {BLE_ADDR_ANONYMOUS, 0xff}, }; for (unsigned i = 0; i < sizeof(type_table) / sizeof(type_table[0]); i++) { @@ -100,12 +98,9 @@ TEST(BleAddressWithTypeTest, STREAM_TO_BLE_ADDR_TYPE) { } TEST(BleAddressWithTypeTest, TYPED_ADDRESS_TRANSPORT) { - tAclLinkSpec linkSpecA = {{BLE_ADDR_PUBLIC, RAW_ADDRESS_TEST1}, - BT_TRANSPORT_AUTO}; - tAclLinkSpec linkSpecB = {{BLE_ADDR_PUBLIC, RAW_ADDRESS_TEST1}, - BT_TRANSPORT_BR_EDR}; - tAclLinkSpec linkSpecC = {{BLE_ADDR_PUBLIC, RAW_ADDRESS_TEST1}, - BT_TRANSPORT_LE}; + tAclLinkSpec linkSpecA = {{BLE_ADDR_PUBLIC, RAW_ADDRESS_TEST1}, BT_TRANSPORT_AUTO}; + tAclLinkSpec linkSpecB = {{BLE_ADDR_PUBLIC, RAW_ADDRESS_TEST1}, BT_TRANSPORT_BR_EDR}; + tAclLinkSpec linkSpecC = {{BLE_ADDR_PUBLIC, RAW_ADDRESS_TEST1}, BT_TRANSPORT_LE}; ASSERT_EQ(linkSpecA, linkSpecB); ASSERT_EQ(linkSpecA, linkSpecC); diff --git a/system/types/test/bluetooth/uuid_unittest.cc b/system/types/test/bluetooth/uuid_unittest.cc index 2cdaf5416ef..6e9e40f9654 100644 --- a/system/types/test/bluetooth/uuid_unittest.cc +++ b/system/types/test/bluetooth/uuid_unittest.cc @@ -21,17 +21,17 @@ using bluetooth::Uuid; -static const Uuid ONES = Uuid::From128BitBE( - Uuid::UUID128Bit{{0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, - 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11}}); +static const Uuid ONES = + Uuid::From128BitBE(Uuid::UUID128Bit{{0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, + 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11}}); -static const Uuid SEQUENTIAL = Uuid::From128BitBE( - Uuid::UUID128Bit{{0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xab, - 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89}}); +static const Uuid SEQUENTIAL = + Uuid::From128BitBE(Uuid::UUID128Bit{{0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xab, + 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89}}); -constexpr Uuid kBase = Uuid::From128BitBE( - Uuid::UUID128Bit{{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, - 0x00, 0x00, 0x80, 0x5f, 0x9b, 0x34, 0xfb}}); +constexpr Uuid kBase = + Uuid::From128BitBE(Uuid::UUID128Bit{{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, + 0x00, 0x00, 0x80, 0x5f, 0x9b, 0x34, 0xfb}}); TEST(UuidTest, IsEmpty) { EXPECT_TRUE(Uuid::kEmpty.IsEmpty()); @@ -40,10 +40,8 @@ TEST(UuidTest, IsEmpty) { TEST(UuidTest, GetShortestRepresentationSize) { EXPECT_TRUE(Uuid::kNumBytes16 == kBase.GetShortestRepresentationSize()); - EXPECT_TRUE(Uuid::kNumBytes32 == - Uuid::From32Bit(0x01234567).GetShortestRepresentationSize()); - EXPECT_TRUE(Uuid::kNumBytes128 == - Uuid::kEmpty.GetShortestRepresentationSize()); + EXPECT_TRUE(Uuid::kNumBytes32 == Uuid::From32Bit(0x01234567).GetShortestRepresentationSize()); + EXPECT_TRUE(Uuid::kNumBytes128 == Uuid::kEmpty.GetShortestRepresentationSize()); } TEST(UuidTest, As16Bit) { @@ -125,8 +123,7 @@ TEST(BtifStorageTest, test_string_to_uuid) { const uint8_t u1[] = {0xe3, 0x9c, 0x62, 0x85, 0x86, 0x7f, 0x4b, 0x1d, 0x9d, 0xb0, 0x35, 0xfb, 0xd9, 0xae, 0xbf, 0x22}; bool is_valid = false; - Uuid uuid = - Uuid::FromString("e39c6285-867f-4b1d-9db0-35fbd9aebf22", &is_valid); + Uuid uuid = Uuid::FromString("e39c6285-867f-4b1d-9db0-35fbd9aebf22", &is_valid); EXPECT_TRUE(is_valid); EXPECT_TRUE(memcmp(&uuid, u1, sizeof(u1)) == 0); diff --git a/system/types/test/raw_address_unittest.cc b/system/types/test/raw_address_unittest.cc index 513c8b7f807..247b55c60ae 100644 --- a/system/types/test/raw_address_unittest.cc +++ b/system/types/test/raw_address_unittest.cc @@ -16,10 +16,10 @@ * ******************************************************************************/ -#include - #include "raw_address.h" +#include + static const char* test_addr = "12:34:56:78:9a:bc"; static const char* test_addr2 = "cb:a9:87:65:43:21"; diff --git a/system/udrv/include/uipc.h b/system/udrv/include/uipc.h index bb72f05ed4b..b2b071a8b86 100644 --- a/system/udrv/include/uipc.h +++ b/system/udrv/include/uipc.h @@ -52,12 +52,11 @@ typedef enum { #define UIPC_REG_REMOVE_ACTIVE_READSET 3 #define UIPC_SET_READ_POLL_TMO 4 -typedef void(tUIPC_RCV_CBACK)( - tUIPC_CH_ID ch_id, - tUIPC_EVENT event); /* points to BT_HDR which describes event type and - length of data; len contains the number of bytes of - entire message (sizeof(BT_HDR) + offset + size of - data) */ +typedef void(tUIPC_RCV_CBACK)(tUIPC_CH_ID ch_id, + tUIPC_EVENT event); /* points to BT_HDR which describes event type and + length of data; len contains the number of + bytes of entire message (sizeof(BT_HDR) + + offset + size of data) */ const char* dump_uipc_event(tUIPC_EVENT event); @@ -116,8 +115,8 @@ void UIPC_Close(tUIPC_STATE& uipc, tUIPC_CH_ID ch_id); * @param msglen Message length * @return true on success, otherwise false */ -bool UIPC_Send(tUIPC_STATE& uipc, tUIPC_CH_ID ch_id, uint16_t msg_evt, - const uint8_t* p_buf, uint16_t msglen); +bool UIPC_Send(tUIPC_STATE& uipc, tUIPC_CH_ID ch_id, uint16_t msg_evt, const uint8_t* p_buf, + uint16_t msglen); /** * Read a message from UIPC @@ -128,8 +127,7 @@ bool UIPC_Send(tUIPC_STATE& uipc, tUIPC_CH_ID ch_id, uint16_t msg_evt, * @param len Bytes to read * @return true on success, otherwise false */ -uint32_t UIPC_Read(tUIPC_STATE& uipc, tUIPC_CH_ID ch_id, uint8_t* p_buf, - uint32_t len); +uint32_t UIPC_Read(tUIPC_STATE& uipc, tUIPC_CH_ID ch_id, uint8_t* p_buf, uint32_t len); /** * Control the UIPC parameter @@ -139,7 +137,6 @@ uint32_t UIPC_Read(tUIPC_STATE& uipc, tUIPC_CH_ID ch_id, uint8_t* p_buf, * @param param Optional parameters * @return true on success, otherwise false */ -bool UIPC_Ioctl(tUIPC_STATE& uipc, tUIPC_CH_ID ch_id, uint32_t request, - void* param); +bool UIPC_Ioctl(tUIPC_STATE& uipc, tUIPC_CH_ID ch_id, uint32_t request, void* param); #endif /* UIPC_H */ diff --git a/system/udrv/ulinux/uipc.cc b/system/udrv/ulinux/uipc.cc index 71dcf78ea22..e90fe9a22a0 100644 --- a/system/udrv/ulinux/uipc.cc +++ b/system/udrv/ulinux/uipc.cc @@ -120,7 +120,9 @@ const char* dump_uipc_event(tUIPC_EVENT event) { static inline int create_server_socket(const char* name) { int s = socket(AF_LOCAL, SOCK_STREAM, 0); - if (s < 0) return -1; + if (s < 0) { + return -1; + } log::debug("create_server_socket {}", name); @@ -173,8 +175,7 @@ static int accept_server_socket(int sfd) { // match socket buffer size option with client const int size = AUDIO_STREAM_OUTPUT_BUFFER_SZ; - int ret = - setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (char*)&size, (int)sizeof(size)); + int ret = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (char*)&size, (int)sizeof(size)); if (ret < 0) { log::error("setsockopt failed ({})", strerror(errno)); } @@ -229,7 +230,9 @@ void uipc_main_cleanup(tUIPC_STATE& uipc) { close(uipc.signal_fds[1]); /* close any open channels */ - for (i = 0; i < UIPC_CH_NUM; i++) uipc_close_ch_locked(uipc, i); + for (i = 0; i < UIPC_CH_NUM; i++) { + uipc_close_ch_locked(uipc, i); + } } /* check pending events in read task */ @@ -247,7 +250,9 @@ static void uipc_check_task_flags_locked(tUIPC_STATE& uipc) { } static int uipc_check_fd_locked(tUIPC_STATE& uipc, tUIPC_CH_ID ch_id) { - if (ch_id >= UIPC_CH_NUM) return -1; + if (ch_id >= UIPC_CH_NUM) { + return -1; + } if (SAFE_FD_ISSET(uipc.ch[ch_id].srvfd, &uipc.read_set)) { log::debug("INCOMING CONNECTION ON CH {}", ch_id); @@ -277,13 +282,15 @@ static int uipc_check_fd_locked(tUIPC_STATE& uipc, tUIPC_CH_ID ch_id) { return -1; } - if (uipc.ch[ch_id].cback) uipc.ch[ch_id].cback(ch_id, UIPC_OPEN_EVT); + if (uipc.ch[ch_id].cback) { + uipc.ch[ch_id].cback(ch_id, UIPC_OPEN_EVT); + } } if (SAFE_FD_ISSET(uipc.ch[ch_id].fd, &uipc.read_set)) { - - if (uipc.ch[ch_id].cback) + if (uipc.ch[ch_id].cback) { uipc.ch[ch_id].cback(ch_id, UIPC_RX_DATA_READY_EVT); + } } return 0; } @@ -291,8 +298,7 @@ static int uipc_check_fd_locked(tUIPC_STATE& uipc, tUIPC_CH_ID ch_id) { static void uipc_check_interrupt_locked(tUIPC_STATE& uipc) { if (SAFE_FD_ISSET(uipc.signal_fds[0], &uipc.read_set)) { char sig_recv = 0; - OSI_NO_INTR( - recv(uipc.signal_fds[0], &sig_recv, sizeof(sig_recv), MSG_WAITALL)); + OSI_NO_INTR(recv(uipc.signal_fds[0], &sig_recv, sizeof(sig_recv), MSG_WAITALL)); } } @@ -303,13 +309,15 @@ static inline void uipc_wakeup_locked(tUIPC_STATE& uipc) { OSI_NO_INTR(send(uipc.signal_fds[1], &sig_on, sizeof(sig_on), 0)); } -static int uipc_setup_server_locked(tUIPC_STATE& uipc, tUIPC_CH_ID ch_id, - const char* name, tUIPC_RCV_CBACK* cback) { +static int uipc_setup_server_locked(tUIPC_STATE& uipc, tUIPC_CH_ID ch_id, const char* name, + tUIPC_RCV_CBACK* cback) { int fd; log::debug("SETUP CHANNEL SERVER {}", ch_id); - if (ch_id >= UIPC_CH_NUM) return -1; + if (ch_id >= UIPC_CH_NUM) { + return -1; + } std::lock_guard guard(uipc.mutex); @@ -354,12 +362,10 @@ static void uipc_flush_ch_locked(tUIPC_STATE& uipc, tUIPC_CH_ID ch_id) { return; } if (ret < 0) { - log::warn("poll() failed: return {} errno {} ({}). Exiting", ret, errno, - strerror(errno)); + log::warn("poll() failed: return {} errno {} ({}). Exiting", ret, errno, strerror(errno)); return; } - log::verbose("polling fd {}, revents: 0x{:x}, ret {}", pfd.fd, pfd.revents, - ret); + log::verbose("polling fd {}, revents: 0x{:x}, ret {}", pfd.fd, pfd.revents, ret); if (pfd.revents & (POLLERR | POLLHUP)) { log::warn("POLLERR or POLLHUP. Exiting"); return; @@ -372,7 +378,9 @@ static void uipc_flush_ch_locked(tUIPC_STATE& uipc, tUIPC_CH_ID ch_id) { } static void uipc_flush_locked(tUIPC_STATE& uipc, tUIPC_CH_ID ch_id) { - if (ch_id >= UIPC_CH_NUM) return; + if (ch_id >= UIPC_CH_NUM) { + return; + } switch (ch_id) { case UIPC_CH_ID_AV_CTRL: @@ -390,7 +398,9 @@ static int uipc_close_ch_locked(tUIPC_STATE& uipc, tUIPC_CH_ID ch_id) { log::debug("CLOSE CHANNEL {}", ch_id); - if (ch_id >= UIPC_CH_NUM) return -1; + if (ch_id >= UIPC_CH_NUM) { + return -1; + } if (uipc.ch[ch_id].srvfd != UIPC_DISCONNECTED) { log::debug("CLOSE SERVER (FD {})", uipc.ch[ch_id].srvfd); @@ -409,10 +419,14 @@ static int uipc_close_ch_locked(tUIPC_STATE& uipc, tUIPC_CH_ID ch_id) { } /* notify this connection is closed */ - if (uipc.ch[ch_id].cback) uipc.ch[ch_id].cback(ch_id, UIPC_CLOSE_EVT); + if (uipc.ch[ch_id].cback) { + uipc.ch[ch_id].cback(ch_id, UIPC_CLOSE_EVT); + } /* trigger main thread update if something was updated */ - if (wakeup) uipc_wakeup_locked(uipc); + if (wakeup) { + uipc_wakeup_locked(uipc); + } return 0; } @@ -465,7 +479,9 @@ static void* uipc_read_task(void* arg) { /* check for other connections */ for (ch_id = 0; ch_id < UIPC_CH_NUM; ch_id++) { - if (ch_id != UIPC_CH_ID_AV_AUDIO) uipc_check_fd_locked(uipc, ch_id); + if (ch_id != UIPC_CH_ID_AV_AUDIO) { + uipc_check_fd_locked(uipc, ch_id); + } } } } @@ -484,8 +500,7 @@ static void* uipc_read_task(void* arg) { int uipc_start_main_server_thread(tUIPC_STATE& uipc) { uipc.running = 1; - if (pthread_create(&uipc.tid, (const pthread_attr_t*)NULL, uipc_read_task, - &uipc) != 0) { + if (pthread_create(&uipc.tid, (const pthread_attr_t*)NULL, uipc_read_task, &uipc) != 0) { log::error("uipc_thread_create pthread_create failed:{}", errno); return -1; } @@ -504,9 +519,11 @@ void uipc_stop_main_server_thread(tUIPC_STATE& uipc) { /* wait until read thread is fully terminated */ /* tid might hold pointer value where it's value - is negative vaule with singed bit is set, so + is negative value with signed bit is set, so corrected the logic to check zero or non zero */ - if (uipc.tid) pthread_join(uipc.tid, NULL); + if (uipc.tid) { + pthread_join(uipc.tid, NULL); + } } /******************************************************************************* @@ -592,8 +609,8 @@ void UIPC_Close(tUIPC_STATE& uipc, tUIPC_CH_ID ch_id) { ** Returns true in case of success, false in case of failure. ** ******************************************************************************/ -bool UIPC_Send(tUIPC_STATE& uipc, tUIPC_CH_ID ch_id, uint16_t /* msg_evt */, - const uint8_t* p_buf, uint16_t msglen) { +bool UIPC_Send(tUIPC_STATE& uipc, tUIPC_CH_ID ch_id, uint16_t /* msg_evt */, const uint8_t* p_buf, + uint16_t msglen) { log::verbose("UIPC_Send : ch_id:{} {} bytes", ch_id, msglen); std::lock_guard lock(uipc.mutex); @@ -618,8 +635,7 @@ bool UIPC_Send(tUIPC_STATE& uipc, tUIPC_CH_ID ch_id, uint16_t /* msg_evt */, ** ******************************************************************************/ -uint32_t UIPC_Read(tUIPC_STATE& uipc, tUIPC_CH_ID ch_id, uint8_t* p_buf, - uint32_t len) { +uint32_t UIPC_Read(tUIPC_STATE& uipc, tUIPC_CH_ID ch_id, uint8_t* p_buf, uint32_t len) { if (ch_id >= UIPC_CH_NUM) { log::error("UIPC_Read : invalid ch id {}", ch_id); return 0; @@ -648,8 +664,7 @@ uint32_t UIPC_Read(tUIPC_STATE& uipc, tUIPC_CH_ID ch_id, uint8_t* p_buf, break; } if (poll_ret < 0) { - log::error("poll() failed: return {} errno {} ({})", poll_ret, errno, - strerror(errno)); + log::error("poll() failed: return {} errno {} ({})", poll_ret, errno, strerror(errno)); break; } @@ -691,8 +706,7 @@ uint32_t UIPC_Read(tUIPC_STATE& uipc, tUIPC_CH_ID ch_id, uint8_t* p_buf, * ******************************************************************************/ -bool UIPC_Ioctl(tUIPC_STATE& uipc, tUIPC_CH_ID ch_id, uint32_t request, - void* param) { +bool UIPC_Ioctl(tUIPC_STATE& uipc, tUIPC_CH_ID ch_id, uint32_t request, void* param) { log::debug("#### UIPC_Ioctl : ch_id {}, request {} ####", ch_id, request); std::lock_guard lock(uipc.mutex); diff --git a/tools/rootcanal/desktop/root_canal_main.cc b/tools/rootcanal/desktop/root_canal_main.cc index 20be4b90809..fde5560fbed 100644 --- a/tools/rootcanal/desktop/root_canal_main.cc +++ b/tools/rootcanal/desktop/root_canal_main.cc @@ -41,36 +41,28 @@ using namespace rootcanal; DEFINE_string(controller_properties_file, "", "deprecated"); DEFINE_string(configuration, "", "controller configuration (see config.proto)"); -DEFINE_string(configuration_file, "", - "controller configuration file path (see config.proto)"); +DEFINE_string(configuration_file, "", "controller configuration file path (see config.proto)"); DEFINE_string(default_commands_file, "", "deprecated"); DEFINE_bool(enable_log_color, false, "enable log colors"); DEFINE_bool(enable_hci_sniffer, false, "enable hci sniffer"); DEFINE_bool(enable_baseband_sniffer, false, "enable baseband sniffer"); DEFINE_bool(enable_pcap_filter, false, "enable PCAP filter"); -DEFINE_bool(disable_address_reuse, false, - "prevent rootcanal from reusing device addresses"); +DEFINE_bool(disable_address_reuse, false, "prevent rootcanal from reusing device addresses"); DEFINE_uint32(test_port, 6401, "test tcp port"); DEFINE_uint32(hci_port, 6402, "hci server tcp port"); DEFINE_uint32(link_port, 6403, "link server tcp port"); DEFINE_uint32(link_ble_port, 6404, "le link server tcp port"); -extern "C" const char* __asan_default_options() { - return "detect_container_overflow=0"; -} +extern "C" const char* __asan_default_options() { return "detect_container_overflow=0"; } -bool crash_callback(const void* crash_context, size_t crash_context_size, - void* /* context */) { +bool crash_callback(const void* crash_context, size_t crash_context_size, void* /* context */) { std::optional tid; - if (crash_context_size >= - sizeof(google_breakpad::ExceptionHandler::CrashContext)) { - auto* ctx = - static_cast( - crash_context); + if (crash_context_size >= sizeof(google_breakpad::ExceptionHandler::CrashContext)) { + auto* ctx = static_cast(crash_context); tid = ctx->tid; int signal_number = ctx->siginfo.si_signo; - ERROR("Process crashed, signal: {}[{}], tid: {}", strsignal(signal_number), - signal_number, ctx->tid); + ERROR("Process crashed, signal: {}[{}], tid: {}", strsignal(signal_number), signal_number, + ctx->tid); } else { ERROR("Process crashed, signal: unknown, tid: unknown"); } @@ -89,9 +81,8 @@ bool crash_callback(const void* crash_context, size_t crash_context_size, int main(int argc, char** argv) { google_breakpad::MinidumpDescriptor descriptor( - google_breakpad::MinidumpDescriptor::kMicrodumpOnConsole); - google_breakpad::ExceptionHandler eh(descriptor, nullptr, nullptr, nullptr, - true, -1); + google_breakpad::MinidumpDescriptor::kMicrodumpOnConsole); + google_breakpad::ExceptionHandler eh(descriptor, nullptr, nullptr, nullptr, true, -1); eh.set_crash_handler(crash_callback); gflags::ParseCommandLineFlags(&argc, &argv, true); @@ -130,17 +121,14 @@ int main(int argc, char** argv) { } TestEnvironment root_canal( - [](AsyncManager* am, int port) { - return std::make_shared(port, am); - }, - [](AsyncManager* am) { - return std::make_shared(am); - }, - static_cast(FLAGS_test_port), static_cast(FLAGS_hci_port), - static_cast(FLAGS_link_port), static_cast(FLAGS_link_ble_port), - configuration_str, FLAGS_enable_hci_sniffer, - FLAGS_enable_baseband_sniffer, FLAGS_enable_pcap_filter, - FLAGS_disable_address_reuse); + [](AsyncManager* am, int port) { + return std::make_shared(port, am); + }, + [](AsyncManager* am) { return std::make_shared(am); }, + static_cast(FLAGS_test_port), static_cast(FLAGS_hci_port), + static_cast(FLAGS_link_port), static_cast(FLAGS_link_ble_port), + configuration_str, FLAGS_enable_hci_sniffer, FLAGS_enable_baseband_sniffer, + FLAGS_enable_pcap_filter, FLAGS_disable_address_reuse); std::promise barrier; std::future barrier_future = barrier.get_future(); diff --git a/tools/rootcanal/desktop/test_environment.cc b/tools/rootcanal/desktop/test_environment.cc index 512bab20eb5..91eae8a3e5b 100644 --- a/tools/rootcanal/desktop/test_environment.cc +++ b/tools/rootcanal/desktop/test_environment.cc @@ -56,14 +56,11 @@ using rootcanal::LinkLayerSocketDevice; using rootcanal::TaskCallback; TestEnvironment::TestEnvironment( - std::function(AsyncManager*, int)> - open_server, - std::function(AsyncManager*)> - open_connector, - int test_port, int hci_port, int link_port, int link_ble_port, - const std::string& config_str, - bool enable_hci_sniffer, bool enable_baseband_sniffer, - bool enable_pcap_filter, bool disable_address_reuse) + std::function(AsyncManager*, int)> open_server, + std::function(AsyncManager*)> open_connector, + int test_port, int hci_port, int link_port, int link_ble_port, + const std::string& config_str, bool enable_hci_sniffer, bool enable_baseband_sniffer, + bool enable_pcap_filter, bool disable_address_reuse) : enable_hci_sniffer_(enable_hci_sniffer), enable_baseband_sniffer_(enable_baseband_sniffer), enable_pcap_filter_(enable_pcap_filter) { @@ -76,8 +73,7 @@ TestEnvironment::TestEnvironment( // Get a user ID for tasks scheduled within the test environment. socket_user_id_ = async_manager_.GetNextUserId(); - rootcanal::configuration::Configuration* config = - new rootcanal::configuration::Configuration(); + rootcanal::configuration::Configuration* config = new rootcanal::configuration::Configuration(); if (!google::protobuf::TextFormat::ParseFromString(config_str, config) || config->tcp_server_size() == 0) { // Default configuration with default hci port if the input @@ -88,8 +84,7 @@ TestEnvironment::TestEnvironment( // the caller. int num_controllers = config->tcp_server_size(); for (int index = 0; index < num_controllers; index++) { - rootcanal::configuration::TcpServer const& tcp_server = - config->tcp_server(index); + rootcanal::configuration::TcpServer const& tcp_server = config->tcp_server(index); SetUpHciServer(open_server, tcp_server.tcp_port(), rootcanal::ControllerProperties(tcp_server.configuration())); } @@ -99,52 +94,48 @@ TestEnvironment::TestEnvironment( // Open an HCI server listening on the port `tcp_port`. Established connections // are bound to a controller with the specified `properties`. void TestEnvironment::SetUpHciServer( - std::function(AsyncManager*, int)> - open_server, - int tcp_port, rootcanal::ControllerProperties properties) { + std::function(AsyncManager*, int)> open_server, + int tcp_port, rootcanal::ControllerProperties properties) { INFO("Opening an HCI with port {}", tcp_port); - std::shared_ptr server = - open_server(&async_manager_, tcp_port); - server->SetOnConnectCallback([this, properties = std::move(properties)]( - std::shared_ptr socket, - AsyncDataChannelServer* server) { - // AddHciConnection needs to be executed in task thread to - // prevent data races on test model. - async_manager_.ExecAsync(socket_user_id_, std::chrono::milliseconds(0), - [=]() { - auto transport = HciSocketTransport::Create(socket); - if (enable_hci_sniffer_) { - transport = HciSniffer::Create(transport); - } - auto device = HciDevice::Create(transport, properties); - auto device_id = test_model_.AddHciConnection(device); - - if (enable_hci_sniffer_) { - auto filename = "rootcanal_" + std::to_string(device_id) + "_" + - device->GetAddress().ToString() + ".pcap"; - for (auto i = 0; std::filesystem::exists(filename); i++) { - filename = "rootcanal_" + std::to_string(device_id) + "_" + - device->GetAddress().ToString() + "_" + std::to_string(i) + - ".pcap"; - } - auto file = std::make_shared(filename, std::ios::binary); - auto sniffer = std::static_pointer_cast(transport); - - // Add PCAP output stream. - sniffer->SetOutputStream(file); - - // Add a PCAP filter if the option is enabled. - // TODO: ideally the filter should be shared between all transport - // instances to use the same user information remapping between traces. - if (enable_pcap_filter_) { - sniffer->SetPcapFilter(std::make_shared()); - } - } - }); + std::shared_ptr server = open_server(&async_manager_, tcp_port); + server->SetOnConnectCallback( + [this, properties = std::move(properties)](std::shared_ptr socket, + AsyncDataChannelServer* server) { + // AddHciConnection needs to be executed in task thread to + // prevent data races on test model. + async_manager_.ExecAsync(socket_user_id_, std::chrono::milliseconds(0), [=]() { + auto transport = HciSocketTransport::Create(socket); + if (enable_hci_sniffer_) { + transport = HciSniffer::Create(transport); + } + auto device = HciDevice::Create(transport, properties); + auto device_id = test_model_.AddHciConnection(device); + + if (enable_hci_sniffer_) { + auto filename = "rootcanal_" + std::to_string(device_id) + "_" + + device->GetAddress().ToString() + ".pcap"; + for (auto i = 0; std::filesystem::exists(filename); i++) { + filename = "rootcanal_" + std::to_string(device_id) + "_" + + device->GetAddress().ToString() + "_" + std::to_string(i) + ".pcap"; + } + auto file = std::make_shared(filename, std::ios::binary); + auto sniffer = std::static_pointer_cast(transport); + + // Add PCAP output stream. + sniffer->SetOutputStream(file); + + // Add a PCAP filter if the option is enabled. + // TODO: ideally the filter should be shared between all transport + // instances to use the same user information remapping between traces. + if (enable_pcap_filter_) { + sniffer->SetPcapFilter(std::make_shared()); + } + } + }); - server->StartListening(); - }); + server->StartListening(); + }); hci_socket_servers_.emplace_back(std::move(server)); } @@ -153,17 +144,16 @@ void TestEnvironment::initialize(std::promise barrier) { barrier_ = std::move(barrier); - test_channel_transport_.RegisterCommandHandler( - [this](const std::string& name, const std::vector& args) { - async_manager_.ExecAsync(socket_user_id_, std::chrono::milliseconds(0), - [this, name, args]() { - if (name == "END_SIMULATION") { - barrier_.set_value(); - } else { - test_channel_.HandleCommand(name, args); - } - }); - }); + test_channel_transport_.RegisterCommandHandler([this](const std::string& name, + const std::vector& args) { + async_manager_.ExecAsync(socket_user_id_, std::chrono::milliseconds(0), [this, name, args]() { + if (name == "END_SIMULATION") { + barrier_.set_value(); + } else { + test_channel_.HandleCommand(name, args); + } + }); + }); SetUpTestChannel(); SetUpLinkLayerServer(); @@ -179,8 +169,7 @@ void TestEnvironment::initialize(std::promise barrier) { filename = "baseband_" + std::to_string(i) + ".pcap"; } - test_model_.AddLinkLayerConnection(BaseBandSniffer::Create(filename), - Phy::Type::BR_EDR); + test_model_.AddLinkLayerConnection(BaseBandSniffer::Create(filename), Phy::Type::BR_EDR); } INFO("{}: Finished", __func__); @@ -192,31 +181,27 @@ void TestEnvironment::close() { } void TestEnvironment::SetUpLinkBleLayerServer() { - link_ble_socket_server_->SetOnConnectCallback( - [this](std::shared_ptr socket, - AsyncDataChannelServer* srv) { - auto phy_type = Phy::Type::LOW_ENERGY; - test_model_.AddLinkLayerConnection( - LinkLayerSocketDevice::Create(socket, phy_type), phy_type); - srv->StartListening(); - }); + link_ble_socket_server_->SetOnConnectCallback([this](std::shared_ptr socket, + AsyncDataChannelServer* srv) { + auto phy_type = Phy::Type::LOW_ENERGY; + test_model_.AddLinkLayerConnection(LinkLayerSocketDevice::Create(socket, phy_type), phy_type); + srv->StartListening(); + }); link_ble_socket_server_->StartListening(); } void TestEnvironment::SetUpLinkLayerServer() { - link_socket_server_->SetOnConnectCallback( - [this](std::shared_ptr socket, - AsyncDataChannelServer* srv) { - auto phy_type = Phy::Type::BR_EDR; - test_model_.AddLinkLayerConnection( - LinkLayerSocketDevice::Create(socket, phy_type), phy_type); - srv->StartListening(); - }); + link_socket_server_->SetOnConnectCallback([this](std::shared_ptr socket, + AsyncDataChannelServer* srv) { + auto phy_type = Phy::Type::BR_EDR; + test_model_.AddLinkLayerConnection(LinkLayerSocketDevice::Create(socket, phy_type), phy_type); + srv->StartListening(); + }); link_socket_server_->StartListening(); } -std::shared_ptr TestEnvironment::ConnectToRemoteServer( - const std::string& server, int port, Phy::Type phy_type) { +std::shared_ptr TestEnvironment::ConnectToRemoteServer(const std::string& server, int port, + Phy::Type phy_type) { auto socket = connector_->ConnectToRemoteServer(server, port); if (!socket->Connected()) { return nullptr; @@ -226,28 +211,26 @@ std::shared_ptr TestEnvironment::ConnectToRemoteServer( void TestEnvironment::SetUpTestChannel() { bool transport_configured = test_channel_transport_.SetUp( - test_socket_server_, [this](std::shared_ptr conn_fd, - AsyncDataChannelServer* server) { - INFO("Test channel connection accepted."); - server->StartListening(); - if (test_channel_open_) { - WARNING("Only one connection at a time is supported"); - rootcanal::TestChannelTransport::SendResponse( - conn_fd, "The connection is broken"); - return false; - } - test_channel_open_ = true; - test_channel_.RegisterSendResponse( - [conn_fd](const std::string& response) { + test_socket_server_, + [this](std::shared_ptr conn_fd, AsyncDataChannelServer* server) { + INFO("Test channel connection accepted."); + server->StartListening(); + if (test_channel_open_) { + WARNING("Only one connection at a time is supported"); + rootcanal::TestChannelTransport::SendResponse(conn_fd, "The connection is broken"); + return false; + } + test_channel_open_ = true; + test_channel_.RegisterSendResponse([conn_fd](const std::string& response) { rootcanal::TestChannelTransport::SendResponse(conn_fd, response); }); - conn_fd->WatchForNonBlockingRead([this](AsyncDataChannel* conn_fd) { - test_channel_transport_.OnCommandReady( - conn_fd, [this]() { test_channel_open_ = false; }); - }); - return false; - }); + conn_fd->WatchForNonBlockingRead([this](AsyncDataChannel* conn_fd) { + test_channel_transport_.OnCommandReady(conn_fd, + [this]() { test_channel_open_ = false; }); + }); + return false; + }); test_channel_.AddPhy({"BR_EDR"}); test_channel_.AddPhy({"LOW_ENERGY"}); diff --git a/tools/rootcanal/desktop/test_environment.h b/tools/rootcanal/desktop/test_environment.h index 5947d075714..7f15811c892 100644 --- a/tools/rootcanal/desktop/test_environment.h +++ b/tools/rootcanal/desktop/test_environment.h @@ -47,21 +47,19 @@ using rootcanal::Device; using rootcanal::Phy; class TestEnvironment { - public: +public: TestEnvironment( - std::function(AsyncManager*, int)> - open_server, - std::function(AsyncManager*)> - open_connector, - int test_port, int hci_port, int link_port, int link_ble_port, - std::string const& config_str, - bool enable_hci_sniffer = false, bool enable_baseband_sniffer = false, - bool enable_pcap_filter = false, bool disable_address_reuse = false); + std::function(AsyncManager*, int)> open_server, + std::function(AsyncManager*)> open_connector, + int test_port, int hci_port, int link_port, int link_ble_port, + std::string const& config_str, bool enable_hci_sniffer = false, + bool enable_baseband_sniffer = false, bool enable_pcap_filter = false, + bool disable_address_reuse = false); void initialize(std::promise barrier); void close(); - private: +private: rootcanal::AsyncManager async_manager_; rootcanal::TestChannelTransport test_channel_transport_; std::shared_ptr test_socket_server_; @@ -78,40 +76,33 @@ class TestEnvironment { void SetUpTestChannel(); void SetUpHciServer( - std::function(AsyncManager*, int)> - open_server, - int tcp_port, rootcanal::ControllerProperties properties); + std::function(AsyncManager*, int)> open_server, + int tcp_port, rootcanal::ControllerProperties properties); void SetUpLinkLayerServer(); void SetUpLinkBleLayerServer(); - std::shared_ptr ConnectToRemoteServer(const std::string& server, - int port, Phy::Type phy_type); + std::shared_ptr ConnectToRemoteServer(const std::string& server, int port, + Phy::Type phy_type); rootcanal::TestModel test_model_{ - [this]() { return async_manager_.GetNextUserId(); }, - [this](rootcanal::AsyncUserId user_id, std::chrono::milliseconds delay, - const rootcanal::TaskCallback& task) { - return async_manager_.ExecAsync(user_id, delay, task); - }, - - [this](rootcanal::AsyncUserId user_id, std::chrono::milliseconds delay, - std::chrono::milliseconds period, - const rootcanal::TaskCallback& task) { - return async_manager_.ExecAsyncPeriodically(user_id, delay, period, - task); - }, - - [this](rootcanal::AsyncUserId user) { - async_manager_.CancelAsyncTasksFromUser(user); - }, - - [this](rootcanal::AsyncTaskId task) { - async_manager_.CancelAsyncTask(task); - }, - - [this](const std::string& server, int port, Phy::Type phy_type) { - return ConnectToRemoteServer(server, port, phy_type); - }}; + [this]() { return async_manager_.GetNextUserId(); }, + [this](rootcanal::AsyncUserId user_id, std::chrono::milliseconds delay, + const rootcanal::TaskCallback& task) { + return async_manager_.ExecAsync(user_id, delay, task); + }, + + [this](rootcanal::AsyncUserId user_id, std::chrono::milliseconds delay, + std::chrono::milliseconds period, const rootcanal::TaskCallback& task) { + return async_manager_.ExecAsyncPeriodically(user_id, delay, period, task); + }, + + [this](rootcanal::AsyncUserId user) { async_manager_.CancelAsyncTasksFromUser(user); }, + + [this](rootcanal::AsyncTaskId task) { async_manager_.CancelAsyncTask(task); }, + + [this](const std::string& server, int port, Phy::Type phy_type) { + return ConnectToRemoteServer(server, port, phy_type); + }}; rootcanal::TestCommandHandler test_channel_{test_model_}; }; diff --git a/tools/rootcanal/hal/bluetooth_hci.cc b/tools/rootcanal/hal/bluetooth_hci.cc index 7cea46b097a..b08d59995b3 100644 --- a/tools/rootcanal/hal/bluetooth_hci.cc +++ b/tools/rootcanal/hal/bluetooth_hci.cc @@ -54,12 +54,11 @@ bool BtTestConsoleEnabled() { } // namespace class BluetoothDeathRecipient : public hidl_death_recipient { - public: +public: BluetoothDeathRecipient(const sp hci) : mHci(hci) {} - void serviceDied( - uint64_t /* cookie */, - const wp<::android::hidl::base::V1_0::IBase>& /* who */) override { + void serviceDied(uint64_t /* cookie */, + const wp<::android::hidl::base::V1_0::IBase>& /* who */) override { ALOGE("BluetoothDeathRecipient::serviceDied - Bluetooth service died"); has_died_ = true; mHci->close(); @@ -68,26 +67,22 @@ class BluetoothDeathRecipient : public hidl_death_recipient { bool getHasDied() const { return has_died_; } void setHasDied(bool has_died) { has_died_ = has_died; } - private: +private: bool has_died_{false}; }; -BluetoothHci::BluetoothHci() - : death_recipient_(new BluetoothDeathRecipient(this)) {} +BluetoothHci::BluetoothHci() : death_recipient_(new BluetoothDeathRecipient(this)) {} -Return BluetoothHci::initialize( - const sp& cb) { +Return BluetoothHci::initialize(const sp& cb) { return initialize_impl(cb, nullptr); } -Return BluetoothHci::initialize_1_1( - const sp& cb) { +Return BluetoothHci::initialize_1_1(const sp& cb) { return initialize_impl(cb, cb); } -Return BluetoothHci::initialize_impl( - const sp& cb, - const sp& cb_1_1) { +Return BluetoothHci::initialize_impl(const sp& cb, + const sp& cb_1_1) { ALOGI("%s", __func__); if (cb == nullptr) { ALOGE("cb == nullptr! -> Unable to call initializationComplete(ERR)"); @@ -98,18 +93,16 @@ Return BluetoothHci::initialize_impl( auto link_ret = cb->linkToDeath(death_recipient_, 0); ALOG_ASSERT(link_ret.isOk(), "Error calling linkToDeath."); - test_channel_transport_.RegisterCommandHandler( - [this](const std::string& name, const std::vector& args) { - async_manager_.ExecAsync( - user_id_, std::chrono::milliseconds(0), - [this, name, args]() { test_channel_.HandleCommand(name, args); }); - }); + test_channel_transport_.RegisterCommandHandler([this](const std::string& name, + const std::vector& args) { + async_manager_.ExecAsync(user_id_, std::chrono::milliseconds(0), + [this, name, args]() { test_channel_.HandleCommand(name, args); }); + }); controller_ = std::make_shared(); char mac_property[PROPERTY_VALUE_MAX] = ""; - property_get("vendor.bt.rootcanal_mac_address", mac_property, - "3C:5A:B4:01:02:03"); + property_get("vendor.bt.rootcanal_mac_address", mac_property, "3C:5A:B4:01:02:03"); auto addr = Address::FromString(std::string(mac_property)); if (addr) { controller_->SetAddress(*addr); @@ -117,64 +110,59 @@ Return BluetoothHci::initialize_impl( LOG_ALWAYS_FATAL("Invalid address: %s", mac_property); } - controller_->RegisterEventChannel( - [this, cb](std::shared_ptr> packet) { - hidl_vec hci_event(packet->begin(), packet->end()); - auto ret = cb->hciEventReceived(hci_event); - if (!ret.isOk()) { - ALOGE("Error sending event callback"); - if (!death_recipient_->getHasDied()) { - ALOGE("Closing"); - close(); - } - } - }); - - controller_->RegisterAclChannel( - [this, cb](std::shared_ptr> packet) { - hidl_vec acl_packet(packet->begin(), packet->end()); - auto ret = cb->aclDataReceived(acl_packet); - if (!ret.isOk()) { - ALOGE("Error sending acl callback"); - if (!death_recipient_->getHasDied()) { - ALOGE("Closing"); - close(); - } - } - }); - - controller_->RegisterScoChannel( - [this, cb](std::shared_ptr> packet) { - hidl_vec sco_packet(packet->begin(), packet->end()); - auto ret = cb->scoDataReceived(sco_packet); - if (!ret.isOk()) { - ALOGE("Error sending sco callback"); - if (!death_recipient_->getHasDied()) { - ALOGE("Closing"); - close(); - } - } - }); + controller_->RegisterEventChannel([this, cb](std::shared_ptr> packet) { + hidl_vec hci_event(packet->begin(), packet->end()); + auto ret = cb->hciEventReceived(hci_event); + if (!ret.isOk()) { + ALOGE("Error sending event callback"); + if (!death_recipient_->getHasDied()) { + ALOGE("Closing"); + close(); + } + } + }); + + controller_->RegisterAclChannel([this, cb](std::shared_ptr> packet) { + hidl_vec acl_packet(packet->begin(), packet->end()); + auto ret = cb->aclDataReceived(acl_packet); + if (!ret.isOk()) { + ALOGE("Error sending acl callback"); + if (!death_recipient_->getHasDied()) { + ALOGE("Closing"); + close(); + } + } + }); + + controller_->RegisterScoChannel([this, cb](std::shared_ptr> packet) { + hidl_vec sco_packet(packet->begin(), packet->end()); + auto ret = cb->scoDataReceived(sco_packet); + if (!ret.isOk()) { + ALOGE("Error sending sco callback"); + if (!death_recipient_->getHasDied()) { + ALOGE("Closing"); + close(); + } + } + }); if (cb_1_1 != nullptr) { - controller_->RegisterIsoChannel( - [this, cb_1_1](std::shared_ptr> packet) { - hidl_vec iso_packet(packet->begin(), packet->end()); - auto ret = cb_1_1->isoDataReceived(iso_packet); - if (!ret.isOk()) { - ALOGE("Error sending iso callback"); - if (!death_recipient_->getHasDied()) { - ALOGE("Closing"); - close(); - } - } - }); + controller_->RegisterIsoChannel([this, cb_1_1](std::shared_ptr> packet) { + hidl_vec iso_packet(packet->begin(), packet->end()); + auto ret = cb_1_1->isoDataReceived(iso_packet); + if (!ret.isOk()) { + ALOGE("Error sending iso callback"); + if (!death_recipient_->getHasDied()) { + ALOGE("Closing"); + close(); + } + } + }); } // Add the controller as a device in the model. size_t controller_index = test_model_.AddDevice(controller_); - size_t low_energy_phy_index = - test_model_.AddPhy(rootcanal::Phy::Type::LOW_ENERGY); + size_t low_energy_phy_index = test_model_.AddPhy(rootcanal::Phy::Type::LOW_ENERGY); size_t classic_phy_index = test_model_.AddPhy(rootcanal::Phy::Type::BR_EDR); test_model_.AddDeviceToPhy(controller_index, low_energy_phy_index); test_model_.AddDeviceToPhy(controller_index, classic_phy_index); @@ -182,32 +170,24 @@ Return BluetoothHci::initialize_impl( test_model_.StartTimer(); // Send responses to logcat if the test channel is not configured. - test_channel_.RegisterSendResponse([](const std::string& response) { - ALOGI("No test channel yet: %s", response.c_str()); - }); + test_channel_.RegisterSendResponse( + [](const std::string& response) { ALOGI("No test channel yet: %s", response.c_str()); }); if (BtTestConsoleEnabled()) { - test_socket_server_ = - std::make_shared(6111, &async_manager_); - hci_socket_server_ = - std::make_shared(6211, &async_manager_); - link_socket_server_ = - std::make_shared(6311, &async_manager_); - connector_ = - std::make_shared(&async_manager_); + test_socket_server_ = std::make_shared(6111, &async_manager_); + hci_socket_server_ = std::make_shared(6211, &async_manager_); + link_socket_server_ = std::make_shared(6311, &async_manager_); + connector_ = std::make_shared(&async_manager_); SetUpTestChannel(); - SetUpHciServer([this](std::shared_ptr socket, - AsyncDataChannelServer* srv) { + SetUpHciServer([this](std::shared_ptr socket, AsyncDataChannelServer* srv) { auto transport = HciSocketTransport::Create(socket); - test_model_.AddHciConnection( - HciDevice::Create(transport, rootcanal::ControllerProperties())); + test_model_.AddHciConnection(HciDevice::Create(transport, rootcanal::ControllerProperties())); srv->StartListening(); }); SetUpLinkLayerServer([this](std::shared_ptr socket, AsyncDataChannelServer* srv) { auto phy_type = Phy::Type::BR_EDR; - test_model_.AddLinkLayerConnection( - LinkLayerSocketDevice::Create(socket, phy_type), phy_type); + test_model_.AddLinkLayerConnection(LinkLayerSocketDevice::Create(socket, phy_type), phy_type); srv->StartListening(); }); } else { @@ -217,18 +197,17 @@ Return BluetoothHci::initialize_impl( test_model_.AddDeviceToPhy(controller_index + 1, low_energy_phy_index); test_channel_.AddDevice({"beacon", "be:ac:10:00:00:02", "1000"}); test_model_.AddDeviceToPhy(controller_index + 2, low_energy_phy_index); - test_channel_.AddDevice( - {"scripted_beacon", "5b:ea:c1:00:00:03", - "/data/vendor/bluetooth/bluetooth_sim_ble_playback_file", - "/data/vendor/bluetooth/bluetooth_sim_ble_playback_events"}); + test_channel_.AddDevice({"scripted_beacon", "5b:ea:c1:00:00:03", + "/data/vendor/bluetooth/bluetooth_sim_ble_playback_file", + "/data/vendor/bluetooth/bluetooth_sim_ble_playback_events"}); test_model_.AddDeviceToPhy(controller_index + 3, low_energy_phy_index); test_channel_.List({}); } unlink_cb_ = [cb](sp& death_recipient) { - if (death_recipient->getHasDied()) + if (death_recipient->getHasDied()) { ALOGI("Skipping unlink call, service died."); - else { + } else { auto ret = cb->unlinkToDeath(death_recipient); if (!ret.isOk()) { ALOG_ASSERT(death_recipient_->getHasDied(), @@ -252,46 +231,38 @@ Return BluetoothHci::close() { } Return BluetoothHci::sendHciCommand(const hidl_vec& packet) { - async_manager_.ExecAsync(user_id_, std::chrono::milliseconds(0), - [this, packet]() { - std::shared_ptr> packet_copy = - std::shared_ptr>( - new std::vector(packet)); - controller_->HandleCommand(packet_copy); - }); + async_manager_.ExecAsync(user_id_, std::chrono::milliseconds(0), [this, packet]() { + std::shared_ptr> packet_copy = + std::shared_ptr>(new std::vector(packet)); + controller_->HandleCommand(packet_copy); + }); return Void(); } Return BluetoothHci::sendAclData(const hidl_vec& packet) { - async_manager_.ExecAsync(user_id_, std::chrono::milliseconds(0), - [this, packet]() { - std::shared_ptr> packet_copy = - std::shared_ptr>( - new std::vector(packet)); - controller_->HandleAcl(packet_copy); - }); + async_manager_.ExecAsync(user_id_, std::chrono::milliseconds(0), [this, packet]() { + std::shared_ptr> packet_copy = + std::shared_ptr>(new std::vector(packet)); + controller_->HandleAcl(packet_copy); + }); return Void(); } Return BluetoothHci::sendScoData(const hidl_vec& packet) { - async_manager_.ExecAsync(user_id_, std::chrono::milliseconds(0), - [this, packet]() { - std::shared_ptr> packet_copy = - std::shared_ptr>( - new std::vector(packet)); - controller_->HandleSco(packet_copy); - }); + async_manager_.ExecAsync(user_id_, std::chrono::milliseconds(0), [this, packet]() { + std::shared_ptr> packet_copy = + std::shared_ptr>(new std::vector(packet)); + controller_->HandleSco(packet_copy); + }); return Void(); } Return BluetoothHci::sendIsoData(const hidl_vec& packet) { - async_manager_.ExecAsync(user_id_, std::chrono::milliseconds(0), - [this, packet]() { - std::shared_ptr> packet_copy = - std::shared_ptr>( - new std::vector(packet)); - controller_->HandleIso(packet_copy); - }); + async_manager_.ExecAsync(user_id_, std::chrono::milliseconds(0), [this, packet]() { + std::shared_ptr> packet_copy = + std::shared_ptr>(new std::vector(packet)); + controller_->HandleIso(packet_copy); + }); return Void(); } @@ -314,31 +285,31 @@ void BluetoothHci::SetUpLinkLayerServer(ConnectCallback connection_callback) { }); } -std::shared_ptr BluetoothHci::ConnectToRemoteServer( - const std::string& server, int port, Phy::Type phy_type) { +std::shared_ptr BluetoothHci::ConnectToRemoteServer(const std::string& server, int port, + Phy::Type phy_type) { auto socket = connector_->ConnectToRemoteServer(server, port); - if (!socket->Connected()) return nullptr; + if (!socket->Connected()) { + return nullptr; + } return LinkLayerSocketDevice::Create(socket, phy_type); } void BluetoothHci::SetUpTestChannel() { bool transport_configured = test_channel_transport_.SetUp( - test_socket_server_, [this](std::shared_ptr conn_fd, - AsyncDataChannelServer*) { - ALOGI("Test channel connection accepted."); - test_channel_.RegisterSendResponse( - [this, conn_fd](const std::string& response) { + test_socket_server_, + [this](std::shared_ptr conn_fd, AsyncDataChannelServer*) { + ALOGI("Test channel connection accepted."); + test_channel_.RegisterSendResponse([this, conn_fd](const std::string& response) { test_channel_transport_.SendResponse(conn_fd, response); }); - conn_fd->WatchForNonBlockingRead([this](AsyncDataChannel* conn_fd) { - test_channel_transport_.OnCommandReady(conn_fd, []() {}); - }); - return false; - }); - test_channel_.RegisterSendResponse([](const std::string& response) { - ALOGI("No test channel: %s", response.c_str()); - }); + conn_fd->WatchForNonBlockingRead([this](AsyncDataChannel* conn_fd) { + test_channel_transport_.OnCommandReady(conn_fd, []() {}); + }); + return false; + }); + test_channel_.RegisterSendResponse( + [](const std::string& response) { ALOGI("No test channel: %s", response.c_str()); }); if (!transport_configured) { ALOGE("Test channel SetUp failed."); @@ -349,9 +320,7 @@ void BluetoothHci::SetUpTestChannel() { } /* Fallback to shared library if there is no service. */ -IBluetoothHci* HIDL_FETCH_IBluetoothHci(const char* /* name */) { - return new BluetoothHci(); -} +IBluetoothHci* HIDL_FETCH_IBluetoothHci(const char* /* name */) { return new BluetoothHci(); } } // namespace sim } // namespace V1_1 diff --git a/tools/rootcanal/hal/bluetooth_hci.h b/tools/rootcanal/hal/bluetooth_hci.h index 374542177dd..95bda389570 100644 --- a/tools/rootcanal/hal/bluetooth_hci.h +++ b/tools/rootcanal/hal/bluetooth_hci.h @@ -45,25 +45,24 @@ using rootcanal::Device; using rootcanal::Phy; class BluetoothHci : public IBluetoothHci { - public: +public: BluetoothHci(); - ::android::hardware::Return initialize( - const sp& cb) override; + ::android::hardware::Return initialize(const sp& cb) override; ::android::hardware::Return initialize_1_1( - const sp& cb) override; + const sp& cb) override; ::android::hardware::Return sendHciCommand( - const ::android::hardware::hidl_vec& packet) override; + const ::android::hardware::hidl_vec& packet) override; ::android::hardware::Return sendAclData( - const ::android::hardware::hidl_vec& packet) override; + const ::android::hardware::hidl_vec& packet) override; ::android::hardware::Return sendScoData( - const ::android::hardware::hidl_vec& packet) override; + const ::android::hardware::hidl_vec& packet) override; ::android::hardware::Return sendIsoData( - const ::android::hardware::hidl_vec& packet) override; + const ::android::hardware::hidl_vec& packet) override; ::android::hardware::Return close() override; @@ -71,10 +70,9 @@ class BluetoothHci : public IBluetoothHci { static BluetoothHci* get(); - private: - ::android::hardware::Return initialize_impl( - const sp& cb, - const sp& cb_1_1); +private: + ::android::hardware::Return initialize_impl(const sp& cb, + const sp& cb_1_1); sp death_recipient_; @@ -91,8 +89,8 @@ class BluetoothHci : public IBluetoothHci { void SetUpTestChannel(); void SetUpHciServer(ConnectCallback on_connect); void SetUpLinkLayerServer(ConnectCallback on_connect); - std::shared_ptr ConnectToRemoteServer(const std::string& server, - int port, Phy::Type phy_type); + std::shared_ptr ConnectToRemoteServer(const std::string& server, int port, + Phy::Type phy_type); std::shared_ptr controller_; @@ -102,30 +100,24 @@ class BluetoothHci : public IBluetoothHci { rootcanal::AsyncUserId user_id_ = async_manager_.GetNextUserId(); rootcanal::TestModel test_model_{ - [this]() { return async_manager_.GetNextUserId(); }, - [this](rootcanal::AsyncUserId user_id, std::chrono::milliseconds delay, - const rootcanal::TaskCallback& task) { - return async_manager_.ExecAsync(user_id, delay, task); - }, - - [this](rootcanal::AsyncUserId user_id, std::chrono::milliseconds delay, - std::chrono::milliseconds period, - const rootcanal::TaskCallback& task) { - return async_manager_.ExecAsyncPeriodically(user_id, delay, period, - task); - }, - - [this](rootcanal::AsyncUserId user) { - async_manager_.CancelAsyncTasksFromUser(user); - }, - - [this](rootcanal::AsyncTaskId task) { - async_manager_.CancelAsyncTask(task); - }, - - [this](const std::string& server, int port, Phy::Type phy_type) { - return ConnectToRemoteServer(server, port, phy_type); - }}; + [this]() { return async_manager_.GetNextUserId(); }, + [this](rootcanal::AsyncUserId user_id, std::chrono::milliseconds delay, + const rootcanal::TaskCallback& task) { + return async_manager_.ExecAsync(user_id, delay, task); + }, + + [this](rootcanal::AsyncUserId user_id, std::chrono::milliseconds delay, + std::chrono::milliseconds period, const rootcanal::TaskCallback& task) { + return async_manager_.ExecAsyncPeriodically(user_id, delay, period, task); + }, + + [this](rootcanal::AsyncUserId user) { async_manager_.CancelAsyncTasksFromUser(user); }, + + [this](rootcanal::AsyncTaskId task) { async_manager_.CancelAsyncTask(task); }, + + [this](const std::string& server, int port, Phy::Type phy_type) { + return ConnectToRemoteServer(server, port, phy_type); + }}; rootcanal::TestCommandHandler test_channel_{test_model_}; }; diff --git a/tools/rootcanal/hal/service.cc b/tools/rootcanal/hal/service.cc index cef8fe72de9..8e4ba1caae7 100644 --- a/tools/rootcanal/hal/service.cc +++ b/tools/rootcanal/hal/service.cc @@ -33,8 +33,9 @@ int main(int /* argc */, char** /* argv */) { sp bluetooth = new BluetoothHci; configureRpcThreadpool(1, true); android::status_t status = bluetooth->registerAsService(); - if (status == android::OK) + if (status == android::OK) { joinRpcThreadpool(); - else + } else { ALOGE("Could not register as a service!"); + } } diff --git a/tools/rootcanal/include/crypto/crypto.h b/tools/rootcanal/include/crypto/crypto.h index f73d0f23efa..6249b16592c 100644 --- a/tools/rootcanal/include/crypto/crypto.h +++ b/tools/rootcanal/include/crypto/crypto.h @@ -30,8 +30,7 @@ Octet16 aes_128(const Octet16& key, const Octet16& message); /* This function computes AES_128(key, message). |key| must be 128bit. * |message| can be at most 16 bytes long, its length in bytes is given in * |length| */ -inline Octet16 aes_128(const Octet16& key, const uint8_t* message, - const uint8_t length) { +inline Octet16 aes_128(const Octet16& key, const uint8_t* message, const uint8_t length) { Octet16 padded_message{0}; std::copy(message, message + length, padded_message.begin()); return aes_128(key, padded_message); diff --git a/tools/rootcanal/include/hci/address.h b/tools/rootcanal/include/hci/address.h index 18b38ee8d3b..fe4d454d5d2 100644 --- a/tools/rootcanal/include/hci/address.h +++ b/tools/rootcanal/include/hci/address.h @@ -32,7 +32,7 @@ namespace bluetooth::hci { class Address final : public pdl::packet::Builder { - public: +public: static constexpr size_t kLength = 6; // Bluetooth MAC address bytes saved in little endian format. @@ -52,7 +52,7 @@ class Address final : public pdl::packet::Builder { bool operator<(const Address& rhs) const { return address < rhs.address; } bool operator==(const Address& rhs) const { return address == rhs.address; } - bool operator>(const Address& rhs) const { return (rhs < *this); } + bool operator>(const Address& rhs) const { return rhs < *this; } bool operator<=(const Address& rhs) const { return !(*this > rhs); } bool operator>=(const Address& rhs) const { return !(*this < rhs); } bool operator!=(const Address& rhs) const { return !(*this == rhs); } @@ -112,8 +112,7 @@ struct fmt::formatter { char presentation = 'x'; // Parses format specifications of the form ['x' | 'X']. - constexpr auto parse(format_parse_context& ctx) - -> format_parse_context::iterator { + constexpr auto parse(format_parse_context& ctx) -> format_parse_context::iterator { // Parse the presentation format and store it in the formatter: auto it = ctx.begin(); auto end = ctx.end(); @@ -132,16 +131,14 @@ struct fmt::formatter { // Formats the address a using the parsed format specification (presentation) // stored in this formatter. - auto format(const bluetooth::hci::Address& a, format_context& ctx) const - -> format_context::iterator { + auto format(const bluetooth::hci::Address& a, + format_context& ctx) const -> format_context::iterator { return presentation == 'x' - ? fmt::format_to(ctx.out(), - "{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}", - a.address[5], a.address[4], a.address[3], - a.address[2], a.address[1], a.address[0]) - : fmt::format_to(ctx.out(), - "{:02X}:{:02X}:{:02X}:{:02X}:{:02X}:{:02X}", - a.address[5], a.address[4], a.address[3], - a.address[2], a.address[1], a.address[0]); + ? fmt::format_to(ctx.out(), "{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}", + a.address[5], a.address[4], a.address[3], a.address[2], + a.address[1], a.address[0]) + : fmt::format_to(ctx.out(), "{:02X}:{:02X}:{:02X}:{:02X}:{:02X}:{:02X}", + a.address[5], a.address[4], a.address[3], a.address[2], + a.address[1], a.address[0]); } }; diff --git a/tools/rootcanal/include/hci/address_with_type.h b/tools/rootcanal/include/hci/address_with_type.h index 65c4223ef27..1172ac7fa22 100644 --- a/tools/rootcanal/include/hci/address_with_type.h +++ b/tools/rootcanal/include/hci/address_with_type.h @@ -34,13 +34,12 @@ namespace bluetooth::hci { class AddressWithType final { - public: +public: AddressWithType(Address address, AddressType address_type) : address_(std::move(address)), address_type_(address_type) {} explicit AddressWithType() - : address_(Address::kEmpty), - address_type_(AddressType::PUBLIC_DEVICE_ADDRESS) {} + : address_(Address::kEmpty), address_type_(AddressType::PUBLIC_DEVICE_ADDRESS) {} inline Address GetAddress() const { return address_; } @@ -65,8 +64,7 @@ class AddressWithType final { prand[1] = address_.address[4]; prand[2] = address_.address[5]; /* generate X = E irk(R0, R1, R2) and R is random address 3 LSO */ - rootcanal::crypto::Octet16 computed_hash = - rootcanal::crypto::aes_128(irk, &prand[0], 3); + rootcanal::crypto::Octet16 computed_hash = rootcanal::crypto::aes_128(irk, &prand[0], 3); uint8_t hash[3]; hash[0] = address_.address[0]; hash[1] = address_.address[1]; @@ -75,13 +73,12 @@ class AddressWithType final { } bool operator<(const AddressWithType& rhs) const { - return (address_ != rhs.address_) ? address_ < rhs.address_ - : address_type_ < rhs.address_type_; + return (address_ != rhs.address_) ? address_ < rhs.address_ : address_type_ < rhs.address_type_; } bool operator==(const AddressWithType& rhs) const { return address_ == rhs.address_ && address_type_ == rhs.address_type_; } - bool operator>(const AddressWithType& rhs) const { return (rhs < *this); } + bool operator>(const AddressWithType& rhs) const { return rhs < *this; } bool operator<=(const AddressWithType& rhs) const { return !(*this > rhs); } bool operator>=(const AddressWithType& rhs) const { return !(*this < rhs); } bool operator!=(const AddressWithType& rhs) const { return !(*this == rhs); } @@ -114,7 +111,7 @@ class AddressWithType final { return ss.str(); } - private: +private: Address address_; AddressType address_type_; }; @@ -146,8 +143,7 @@ struct fmt::formatter { char presentation = 'x'; // Parses format specifications of the form ['x' | 'X']. - constexpr auto parse(format_parse_context& ctx) - -> format_parse_context::iterator { + constexpr auto parse(format_parse_context& ctx) -> format_parse_context::iterator { // Parse the presentation format and store it in the formatter: auto it = ctx.begin(); auto end = ctx.end(); @@ -168,9 +164,8 @@ struct fmt::formatter { // stored in this formatter. auto format(const bluetooth::hci::AddressWithType& a, format_context& ctx) const -> format_context::iterator { - auto out = presentation == 'x' - ? fmt::format_to(ctx.out(), "{:x}", a.GetAddress()) - : fmt::format_to(ctx.out(), "{:X}", a.GetAddress()); + auto out = presentation == 'x' ? fmt::format_to(ctx.out(), "{:x}", a.GetAddress()) + : fmt::format_to(ctx.out(), "{:X}", a.GetAddress()); return fmt::format_to(out, "[{}]", AddressTypeText(a.GetAddressType())); } }; diff --git a/tools/rootcanal/include/hci/pcap_filter.h b/tools/rootcanal/include/hci/pcap_filter.h index 1731ce866d3..64f55f57bb9 100644 --- a/tools/rootcanal/include/hci/pcap_filter.h +++ b/tools/rootcanal/include/hci/pcap_filter.h @@ -42,45 +42,33 @@ namespace rootcanal { // RootCanal issues, and can be safely removed. class PcapFilter final { - public: +public: PcapFilter() = default; // Main function to filter out user data in HCI packets. - std::vector FilterHciPacket(std::vector const& packet, - uint8_t idc); + std::vector FilterHciPacket(std::vector const& packet, uint8_t idc); std::vector FilterHciCommand(std::vector const& packet); std::vector FilterHciEvent(std::vector const& packet); // Specific filters for HCI commands. - std::vector FilterWriteLocalName( - bluetooth::hci::CommandView& command); - std::vector FilterWriteExtendedInquiryResponse( - bluetooth::hci::CommandView& command); - std::vector FilterLeSetAdvertisingData( - bluetooth::hci::CommandView& command); - std::vector FilterLeSetScanResponseData( - bluetooth::hci::CommandView& command); - std::vector FilterLeSetExtendedAdvertisingData( - bluetooth::hci::CommandView& command); - std::vector FilterLeSetExtendedScanResponseData( - bluetooth::hci::CommandView& command); - std::vector FilterLeSetPeriodicAdvertisingData( - bluetooth::hci::CommandView& command); + std::vector FilterWriteLocalName(bluetooth::hci::CommandView& command); + std::vector FilterWriteExtendedInquiryResponse(bluetooth::hci::CommandView& command); + std::vector FilterLeSetAdvertisingData(bluetooth::hci::CommandView& command); + std::vector FilterLeSetScanResponseData(bluetooth::hci::CommandView& command); + std::vector FilterLeSetExtendedAdvertisingData(bluetooth::hci::CommandView& command); + std::vector FilterLeSetExtendedScanResponseData(bluetooth::hci::CommandView& command); + std::vector FilterLeSetPeriodicAdvertisingData(bluetooth::hci::CommandView& command); // Specific filters for HCI events. std::vector FilterReadLocalNameComplete( - bluetooth::hci::CommandCompleteView& command_complete); + bluetooth::hci::CommandCompleteView& command_complete); std::vector FilterReadExtendedInquiryResponseComplete( - bluetooth::hci::CommandCompleteView& command_complete); - std::vector FilterRemoteNameRequestComplete( - bluetooth::hci::EventView& event); - std::vector FilterExtendedInquiryResult( - bluetooth::hci::EventView& event); - std::vector FilterLeAdvertisingReport( - bluetooth::hci::LeMetaEventView& event); - std::vector FilterLeExtendedAdvertisingReport( - bluetooth::hci::LeMetaEventView& event); + bluetooth::hci::CommandCompleteView& command_complete); + std::vector FilterRemoteNameRequestComplete(bluetooth::hci::EventView& event); + std::vector FilterExtendedInquiryResult(bluetooth::hci::EventView& event); + std::vector FilterLeAdvertisingReport(bluetooth::hci::LeMetaEventView& event); + std::vector FilterLeExtendedAdvertisingReport(bluetooth::hci::LeMetaEventView& event); // Specific filter for any Gap data array. // The Gap data entries are modified in place. @@ -88,15 +76,12 @@ class PcapFilter final { void FilterGapData(std::vector& gap_data); // Helpers to replace local names. - std::array ChangeDeviceName( - std::array const& device_name); - std::vector ChangeDeviceName( - std::vector const& device_name); + std::array ChangeDeviceName(std::array const& device_name); + std::vector ChangeDeviceName(std::vector const& device_name); - private: +private: // Map device names to anonymous replacements. - std::vector, std::vector>> - device_name_map{}; + std::vector, std::vector>> device_name_map{}; }; } // namespace rootcanal diff --git a/tools/rootcanal/include/log.h b/tools/rootcanal/include/log.h index 130800ae9ac..9367f5bc7a2 100644 --- a/tools/rootcanal/include/log.h +++ b/tools/rootcanal/include/log.h @@ -34,13 +34,12 @@ enum Verbosity { void SetLogColorEnable(bool); -void VLog(Verbosity verb, char const* file, int line, - std::optional instance, char const* format, - fmt::format_args args); +void VLog(Verbosity verb, char const* file, int line, std::optional instance, + char const* format, fmt::format_args args); template -static void Log(Verbosity verb, char const* file, int line, int instance, - char const* format, const Args&... args) { +static void Log(Verbosity verb, char const* file, int line, int instance, char const* format, + const Args&... args) { VLog(verb, file, line, instance, format, fmt::make_format_args(args...)); } @@ -50,37 +49,31 @@ static void Log(Verbosity verb, char const* file, int line, char const* format, VLog(verb, file, line, {}, format, fmt::make_format_args(args...)); } -#define DEBUG(...) \ - rootcanal::log::Log(rootcanal::log::Verbosity::kDebug, __FILE__, __LINE__, \ - __VA_ARGS__) - -#define INFO(...) \ - rootcanal::log::Log(rootcanal::log::Verbosity::kInfo, __FILE__, __LINE__, \ - __VA_ARGS__) - -#define WARNING(...) \ - rootcanal::log::Log(rootcanal::log::Verbosity::kWarning, __FILE__, __LINE__, \ - __VA_ARGS__) - -#define ERROR(...) \ - rootcanal::log::Log(rootcanal::log::Verbosity::kError, __FILE__, __LINE__, \ - __VA_ARGS__) - -#define FATAL(...) \ - rootcanal::log::Log(rootcanal::log::Verbosity::kFatal, __FILE__, __LINE__, \ - __VA_ARGS__) - -#define ASSERT(x) \ - __builtin_expect((x) != 0, true) || \ - (rootcanal::log::Log(rootcanal::log::Verbosity::kFatal, __FILE__, \ - __LINE__, "Check failed: {}", #x), \ - false) - -#define ASSERT_LOG(x, ...) \ - __builtin_expect((x) != 0, true) || \ - (rootcanal::log::Log(rootcanal::log::Verbosity::kFatal, __FILE__, \ - __LINE__, "Check failed: {}, {}", #x, \ - fmt::sprintf(__VA_ARGS__)), \ - false) +#define DEBUG(...) \ + rootcanal::log::Log(rootcanal::log::Verbosity::kDebug, __FILE__, __LINE__, __VA_ARGS__) + +#define INFO(...) \ + rootcanal::log::Log(rootcanal::log::Verbosity::kInfo, __FILE__, __LINE__, __VA_ARGS__) + +#define WARNING(...) \ + rootcanal::log::Log(rootcanal::log::Verbosity::kWarning, __FILE__, __LINE__, __VA_ARGS__) + +#define ERROR(...) \ + rootcanal::log::Log(rootcanal::log::Verbosity::kError, __FILE__, __LINE__, __VA_ARGS__) + +#define FATAL(...) \ + rootcanal::log::Log(rootcanal::log::Verbosity::kFatal, __FILE__, __LINE__, __VA_ARGS__) + +#define ASSERT(x) \ + __builtin_expect((x) != 0, true) || \ + (rootcanal::log::Log(rootcanal::log::Verbosity::kFatal, __FILE__, __LINE__, \ + "Check failed: {}", #x), \ + false) + +#define ASSERT_LOG(x, ...) \ + __builtin_expect((x) != 0, true) || \ + (rootcanal::log::Log(rootcanal::log::Verbosity::kFatal, __FILE__, __LINE__, \ + "Check failed: {}, {}", #x, fmt::sprintf(__VA_ARGS__)), \ + false) } // namespace rootcanal::log diff --git a/tools/rootcanal/include/phy.h b/tools/rootcanal/include/phy.h index 1e82c1515a2..5f25fa238e7 100644 --- a/tools/rootcanal/include/phy.h +++ b/tools/rootcanal/include/phy.h @@ -19,7 +19,7 @@ namespace rootcanal { class Phy { - public: +public: enum class Type { LOW_ENERGY, BR_EDR, diff --git a/tools/rootcanal/lib/hci/address.cc b/tools/rootcanal/lib/hci/address.cc index 3f9103c80f8..fa85501c52e 100644 --- a/tools/rootcanal/lib/hci/address.cc +++ b/tools/rootcanal/lib/hci/address.cc @@ -39,8 +39,7 @@ const Address Address::kEmpty{0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; // Address cannot initialize member variables as it is a POD type // NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init) -constexpr Address::Address(std::array const& address) - : address(address) {} +constexpr Address::Address(std::array const& address) : address(address) {} Address::Address(const uint8_t (&address)[kLength]) { std::copy(address, address + kLength, this->address.begin()); @@ -56,9 +55,8 @@ bool Address::Parse(pdl::packet::slice& input, Address* output) { } std::array address{ - input.read_le(), input.read_le(), - input.read_le(), input.read_le(), - input.read_le(), input.read_le(), + input.read_le(), input.read_le(), input.read_le(), + input.read_le(), input.read_le(), input.read_le(), }; *output = Address(address); return true; @@ -67,8 +65,7 @@ bool Address::Parse(pdl::packet::slice& input, Address* output) { std::string Address::ToString() const { std::stringstream ss; for (auto it = address.rbegin(); it != address.rend(); it++) { - ss << std::nouppercase << std::hex << std::setw(2) << std::setfill('0') - << +*it; + ss << std::nouppercase << std::hex << std::setw(2) << std::setfill('0') << +*it; if (std::next(it) != address.rend()) { ss << ':'; } diff --git a/tools/rootcanal/lib/hci/pcap_filter.cc b/tools/rootcanal/lib/hci/pcap_filter.cc index 4a05da0fddd..ca14ef03c70 100644 --- a/tools/rootcanal/lib/hci/pcap_filter.cc +++ b/tools/rootcanal/lib/hci/pcap_filter.cc @@ -35,21 +35,19 @@ using namespace bluetooth::hci; namespace rootcanal { -static pdl::packet::slice create_packet_view( - std::vector const& packet) { +static pdl::packet::slice create_packet_view(std::vector const& packet) { // Wrap the reference to the packet in a shared_ptr with created // a no-op deleter. The packet view will be short lived so there is no // risk of the reference leaking. return pdl::packet::slice(std::shared_ptr const>( - &packet, [](std::vector const* /* ptr */) {})); + &packet, [](std::vector const* /* ptr */) {})); } static std::vector FilterHciAcl(std::vector const& packet); static std::vector FilterHciSco(std::vector const& packet); static std::vector FilterHciIso(std::vector const& packet); -std::vector PcapFilter::FilterHciPacket( - std::vector const& packet, uint8_t idc) { +std::vector PcapFilter::FilterHciPacket(std::vector const& packet, uint8_t idc) { switch (idc) { case 0x1: return FilterHciCommand(packet); @@ -67,8 +65,7 @@ std::vector PcapFilter::FilterHciPacket( return std::vector(packet); } -std::vector PcapFilter::FilterHciCommand( - std::vector const& packet) { +std::vector PcapFilter::FilterHciCommand(std::vector const& packet) { auto command = CommandView::Create(create_packet_view(packet)); ASSERT(command.IsValid()); switch (command.GetOpCode()) { @@ -92,8 +89,7 @@ std::vector PcapFilter::FilterHciCommand( return std::vector(packet); } -std::vector PcapFilter::FilterHciEvent( - std::vector const& packet) { +std::vector PcapFilter::FilterHciEvent(std::vector const& packet) { auto event = EventView::Create(create_packet_view(packet)); ASSERT(event.IsValid()); switch (event.GetEventCode()) { @@ -138,9 +134,9 @@ static std::vector FilterHciAcl(std::vector const& packet) { std::vector payload; payload.resize(acl.GetPayload().size()); ASSERT(acl.IsValid()); - return AclBuilder::Create(acl.GetHandle(), acl.GetPacketBoundaryFlag(), - acl.GetBroadcastFlag(), std::move(payload)) - ->SerializeToBytes(); + return AclBuilder::Create(acl.GetHandle(), acl.GetPacketBoundaryFlag(), acl.GetBroadcastFlag(), + std::move(payload)) + ->SerializeToBytes(); } static std::vector FilterHciSco(std::vector const& packet) { @@ -148,8 +144,7 @@ static std::vector FilterHciSco(std::vector const& packet) { std::vector data; data.resize(sco.GetData().size()); ASSERT(sco.IsValid()); - return ScoBuilder::Create(sco.GetHandle(), sco.GetPacketStatusFlag(), data) - ->SerializeToBytes(); + return ScoBuilder::Create(sco.GetHandle(), sco.GetPacketStatusFlag(), data)->SerializeToBytes(); } static std::vector FilterHciIso(std::vector const& packet) { @@ -157,9 +152,9 @@ static std::vector FilterHciIso(std::vector const& packet) { std::vector payload; payload.resize(iso.GetPayload().size()); ASSERT(iso.IsValid()); - return IsoBuilder::Create(iso.GetConnectionHandle(), iso.GetPbFlag(), - iso.GetTsFlag(), std::move(payload)) - ->SerializeToBytes(); + return IsoBuilder::Create(iso.GetConnectionHandle(), iso.GetPbFlag(), iso.GetTsFlag(), + std::move(payload)) + ->SerializeToBytes(); } // Replace device names in GAP entries. @@ -190,8 +185,7 @@ void PcapFilter::FilterGapData(uint8_t* gap_data, size_t gap_data_len) { case GapDataType::SHORTENED_LOCAL_NAME: { auto start_pos = gap_data + offset + 1; auto end_pos = gap_data + offset + length; - std::vector new_name = - ChangeDeviceName(std::vector{start_pos, end_pos}); + std::vector new_name = ChangeDeviceName(std::vector{start_pos, end_pos}); std::copy(new_name.begin(), new_name.end(), start_pos); break; } @@ -212,97 +206,86 @@ std::vector PcapFilter::FilterWriteLocalName(CommandView& command) { auto parameters = WriteLocalNameView::Create(command); ASSERT(parameters.IsValid()); - std::array local_name = - ChangeDeviceName(parameters.GetLocalName()); + std::array local_name = ChangeDeviceName(parameters.GetLocalName()); return WriteLocalNameBuilder::Create(local_name)->SerializeToBytes(); } // Replace the device names in the GAP entries of the extended inquiry response. -std::vector PcapFilter::FilterWriteExtendedInquiryResponse( - CommandView& command) { +std::vector PcapFilter::FilterWriteExtendedInquiryResponse(CommandView& command) { auto parameters = WriteExtendedInquiryResponseView::Create(command); ASSERT(parameters.IsValid()); - std::array extended_inquiry_response = - parameters.GetExtendedInquiryResponse(); - FilterGapData(extended_inquiry_response.data(), - extended_inquiry_response.size()); - return WriteExtendedInquiryResponseBuilder::Create( - parameters.GetFecRequired(), extended_inquiry_response) - ->SerializeToBytes(); + std::array extended_inquiry_response = parameters.GetExtendedInquiryResponse(); + FilterGapData(extended_inquiry_response.data(), extended_inquiry_response.size()); + return WriteExtendedInquiryResponseBuilder::Create(parameters.GetFecRequired(), + extended_inquiry_response) + ->SerializeToBytes(); } // Replace the device names in the GAP entries of the advertising data. -std::vector PcapFilter::FilterLeSetAdvertisingData( - CommandView& command) { +std::vector PcapFilter::FilterLeSetAdvertisingData(CommandView& command) { auto parameters = LeSetAdvertisingDataView::Create(command); ASSERT(parameters.IsValid()); std::vector advertising_data = parameters.GetAdvertisingData(); FilterGapData(advertising_data); - return LeSetAdvertisingDataBuilder::Create(advertising_data) - ->SerializeToBytes(); + return LeSetAdvertisingDataBuilder::Create(advertising_data)->SerializeToBytes(); } // Replace the device names in the GAP entries of the scan response data. -std::vector PcapFilter::FilterLeSetScanResponseData( - CommandView& command) { +std::vector PcapFilter::FilterLeSetScanResponseData(CommandView& command) { auto parameters = LeSetScanResponseDataView::Create(command); ASSERT(parameters.IsValid()); std::vector advertising_data = parameters.GetAdvertisingData(); FilterGapData(advertising_data); - return LeSetScanResponseDataBuilder::Create(advertising_data) - ->SerializeToBytes(); + return LeSetScanResponseDataBuilder::Create(advertising_data)->SerializeToBytes(); } // Replace the device names in the GAP entries of the extended advertising data. -std::vector PcapFilter::FilterLeSetExtendedAdvertisingData( - CommandView& command) { +std::vector PcapFilter::FilterLeSetExtendedAdvertisingData(CommandView& command) { auto parameters = LeSetExtendedAdvertisingDataView::Create(command); ASSERT(parameters.IsValid()); std::vector advertising_data = parameters.GetAdvertisingData(); FilterGapData(advertising_data); return LeSetExtendedAdvertisingDataBuilder::Create( - parameters.GetAdvertisingHandle(), parameters.GetOperation(), - parameters.GetFragmentPreference(), advertising_data) - ->SerializeToBytes(); + parameters.GetAdvertisingHandle(), parameters.GetOperation(), + parameters.GetFragmentPreference(), advertising_data) + ->SerializeToBytes(); } // Replace the device names in the GAP entries of the extended scan response // data. -std::vector PcapFilter::FilterLeSetExtendedScanResponseData( - CommandView& command) { +std::vector PcapFilter::FilterLeSetExtendedScanResponseData(CommandView& command) { auto parameters = LeSetExtendedScanResponseDataView::Create(command); ASSERT(parameters.IsValid()); std::vector advertising_data = parameters.GetScanResponseData(); FilterGapData(advertising_data); return LeSetExtendedScanResponseDataBuilder::Create( - parameters.GetAdvertisingHandle(), parameters.GetOperation(), - parameters.GetFragmentPreference(), advertising_data) - ->SerializeToBytes(); + parameters.GetAdvertisingHandle(), parameters.GetOperation(), + parameters.GetFragmentPreference(), advertising_data) + ->SerializeToBytes(); } // Replace the device names in the GAP entries of the periodic advertising // data. std::vector PcapFilter::FilterLeSetPeriodicAdvertisingData( - bluetooth::hci::CommandView& command) { + bluetooth::hci::CommandView& command) { auto parameters = LeSetPeriodicAdvertisingDataView::Create(command); ASSERT(parameters.IsValid()); std::vector advertising_data = parameters.GetAdvertisingData(); FilterGapData(advertising_data); - return LeSetPeriodicAdvertisingDataBuilder::Create( - parameters.GetAdvertisingHandle(), parameters.GetOperation(), - advertising_data) - ->SerializeToBytes(); + return LeSetPeriodicAdvertisingDataBuilder::Create(parameters.GetAdvertisingHandle(), + parameters.GetOperation(), advertising_data) + ->SerializeToBytes(); } // Replace the local device name in the read local name complete event. std::vector PcapFilter::FilterReadLocalNameComplete( - bluetooth::hci::CommandCompleteView& command_complete) { + bluetooth::hci::CommandCompleteView& command_complete) { auto parameters = ReadLocalNameCompleteView::Create(command_complete); ASSERT(parameters.IsValid()); @@ -311,35 +294,30 @@ std::vector PcapFilter::FilterReadLocalNameComplete( local_name = ChangeDeviceName(local_name); } - return ReadLocalNameCompleteBuilder::Create( - parameters.GetNumHciCommandPackets(), parameters.GetStatus(), - local_name) - ->SerializeToBytes(); + return ReadLocalNameCompleteBuilder::Create(parameters.GetNumHciCommandPackets(), + parameters.GetStatus(), local_name) + ->SerializeToBytes(); } // Replace the device names in the GAP entries of the extended inquiry response. std::vector PcapFilter::FilterReadExtendedInquiryResponseComplete( - bluetooth::hci::CommandCompleteView& command_complete) { - auto parameters = - ReadExtendedInquiryResponseCompleteView::Create(command_complete); + bluetooth::hci::CommandCompleteView& command_complete) { + auto parameters = ReadExtendedInquiryResponseCompleteView::Create(command_complete); ASSERT(parameters.IsValid()); - std::array extended_inquiry_response = - parameters.GetExtendedInquiryResponse(); + std::array extended_inquiry_response = parameters.GetExtendedInquiryResponse(); if (parameters.GetStatus() == ErrorCode::SUCCESS) { - FilterGapData(extended_inquiry_response.data(), - extended_inquiry_response.size()); + FilterGapData(extended_inquiry_response.data(), extended_inquiry_response.size()); } return ReadExtendedInquiryResponseCompleteBuilder::Create( - parameters.GetNumHciCommandPackets(), parameters.GetStatus(), - parameters.GetFecRequired(), extended_inquiry_response) - ->SerializeToBytes(); + parameters.GetNumHciCommandPackets(), parameters.GetStatus(), + parameters.GetFecRequired(), extended_inquiry_response) + ->SerializeToBytes(); } // Replace the remote device name in the remote name request complete event. -std::vector PcapFilter::FilterRemoteNameRequestComplete( - bluetooth::hci::EventView& event) { +std::vector PcapFilter::FilterRemoteNameRequestComplete(bluetooth::hci::EventView& event) { auto parameters = RemoteNameRequestCompleteView::Create(event); ASSERT(parameters.IsValid()); @@ -348,31 +326,27 @@ std::vector PcapFilter::FilterRemoteNameRequestComplete( remote_name = ChangeDeviceName(remote_name); } - return RemoteNameRequestCompleteBuilder::Create( - parameters.GetStatus(), parameters.GetBdAddr(), remote_name) - ->SerializeToBytes(); + return RemoteNameRequestCompleteBuilder::Create(parameters.GetStatus(), parameters.GetBdAddr(), + remote_name) + ->SerializeToBytes(); } // Replace the device names in the GAP entries in the extended inquiry result. -std::vector PcapFilter::FilterExtendedInquiryResult( - bluetooth::hci::EventView& event) { +std::vector PcapFilter::FilterExtendedInquiryResult(bluetooth::hci::EventView& event) { auto parameters = ExtendedInquiryResultView::Create(event); ASSERT(parameters.IsValid()); - std::array extended_inquiry_response = - parameters.GetExtendedInquiryResponse(); - FilterGapData(extended_inquiry_response.data(), - extended_inquiry_response.size()); + std::array extended_inquiry_response = parameters.GetExtendedInquiryResponse(); + FilterGapData(extended_inquiry_response.data(), extended_inquiry_response.size()); return ExtendedInquiryResultBuilder::Create( - parameters.GetAddress(), parameters.GetPageScanRepetitionMode(), - parameters.GetClassOfDevice(), parameters.GetClockOffset(), - parameters.GetRssi(), extended_inquiry_response) - ->SerializeToBytes(); + parameters.GetAddress(), parameters.GetPageScanRepetitionMode(), + parameters.GetClassOfDevice(), parameters.GetClockOffset(), parameters.GetRssi(), + extended_inquiry_response) + ->SerializeToBytes(); } // Replace the device names in the GAP entries in the advertising report. -std::vector PcapFilter::FilterLeAdvertisingReport( - bluetooth::hci::LeMetaEventView& event) { +std::vector PcapFilter::FilterLeAdvertisingReport(bluetooth::hci::LeMetaEventView& event) { auto parameters = LeAdvertisingReportView::Create(event); ASSERT(parameters.IsValid()); @@ -387,31 +361,28 @@ std::vector PcapFilter::FilterLeAdvertisingReport( // Replace the device names in the GAP entries in the extended advertising // report. std::vector PcapFilter::FilterLeExtendedAdvertisingReport( - bluetooth::hci::LeMetaEventView& event) { + bluetooth::hci::LeMetaEventView& event) { auto parameters = LeExtendedAdvertisingReportView::Create(event); ASSERT(parameters.IsValid()); - std::vector responses = - parameters.GetResponses(); + std::vector responses = parameters.GetResponses(); for (auto& response : responses) { FilterGapData(response.advertising_data_); } - return LeExtendedAdvertisingReportBuilder::Create(responses) - ->SerializeToBytes(); + return LeExtendedAdvertisingReportBuilder::Create(responses)->SerializeToBytes(); } // Generate a device name of the specified length. // device_nr is a unique identifier used for the generation. // padded indicates if the name should be padded to length with // spaces. -static std::vector generate_device_name(size_t device_nr, - size_t device_name_len, +static std::vector generate_device_name(size_t device_nr, size_t device_name_len, bool padded) { std::vector output; output.resize(device_name_len + 1); - int written_len = std::snprintf(reinterpret_cast(output.data()), - output.size(), "#%02zu device", device_nr); + int written_len = std::snprintf(reinterpret_cast(output.data()), output.size(), + "#%02zu device", device_nr); // Remove the null terminator, not used for the device name // since it is framed in most cases. output.resize(device_name_len); @@ -422,8 +393,7 @@ static std::vector generate_device_name(size_t device_nr, return output; } -std::vector PcapFilter::ChangeDeviceName( - std::vector const& device_name) { +std::vector PcapFilter::ChangeDeviceName(std::vector const& device_name) { for (auto const& [old_device_name, new_device_name] : device_name_map) { if (old_device_name == device_name) { return std::vector(new_device_name); @@ -431,34 +401,31 @@ std::vector PcapFilter::ChangeDeviceName( } std::vector new_device_name = - generate_device_name(device_name_map.size(), device_name.size(), true); + generate_device_name(device_name_map.size(), device_name.size(), true); device_name_map.push_back(std::pair{ - std::vector(device_name), - new_device_name, + std::vector(device_name), + new_device_name, }); return new_device_name; } -std::array PcapFilter::ChangeDeviceName( - std::array const& device_name) { +std::array PcapFilter::ChangeDeviceName(std::array const& device_name) { for (auto const& [old_device_name, new_device_name] : device_name_map) { - if (std::equal(old_device_name.begin(), old_device_name.end(), - device_name.begin(), device_name.end())) { + if (std::equal(old_device_name.begin(), old_device_name.end(), device_name.begin(), + device_name.end())) { std::array out_device_name{}; - std::copy(new_device_name.begin(), new_device_name.end(), - out_device_name.begin()); + std::copy(new_device_name.begin(), new_device_name.end(), out_device_name.begin()); return out_device_name; } } std::vector new_device_name = - generate_device_name(device_name_map.size(), device_name.size(), false); + generate_device_name(device_name_map.size(), device_name.size(), false); std::array out_device_name{}; - std::copy(new_device_name.begin(), new_device_name.end(), - out_device_name.begin()); + std::copy(new_device_name.begin(), new_device_name.end(), out_device_name.begin()); device_name_map.push_back(std::pair{ - std::vector(device_name.begin(), device_name.end()), - std::move(new_device_name), + std::vector(device_name.begin(), device_name.end()), + std::move(new_device_name), }); return out_device_name; } diff --git a/tools/rootcanal/lib/log.cc b/tools/rootcanal/lib/log.cc index 9c78b16a3fc..dc843f3fbb0 100644 --- a/tools/rootcanal/lib/log.cc +++ b/tools/rootcanal/lib/log.cc @@ -37,34 +37,30 @@ void SetLogColorEnable(bool enable) { enable_log_color = enable; } static std::array verbosity_tag = {'D', 'I', 'W', 'E', 'F'}; static std::array text_style = { - fmt::fg(fmt::color::dim_gray), - fmt::fg(fmt::color::floral_white), - fmt::emphasis::bold | fmt::fg(fmt::color::yellow), - fmt::emphasis::bold | fmt::fg(fmt::color::orange_red), - fmt::emphasis::bold | fmt::fg(fmt::color::red), + fmt::fg(fmt::color::dim_gray), + fmt::fg(fmt::color::floral_white), + fmt::emphasis::bold | fmt::fg(fmt::color::yellow), + fmt::emphasis::bold | fmt::fg(fmt::color::orange_red), + fmt::emphasis::bold | fmt::fg(fmt::color::red), }; static std::array text_color = { - fmt::color::cadet_blue, fmt::color::aquamarine, - fmt::color::indian_red, fmt::color::blue_violet, - fmt::color::chartreuse, fmt::color::medium_sea_green, - fmt::color::deep_pink, fmt::color::medium_orchid, - fmt::color::green_yellow, fmt::color::dark_orange, - fmt::color::golden_rod, fmt::color::medium_slate_blue, - fmt::color::coral, fmt::color::lemon_chiffon, - fmt::color::wheat, fmt::color::turquoise, + fmt::color::cadet_blue, fmt::color::aquamarine, fmt::color::indian_red, + fmt::color::blue_violet, fmt::color::chartreuse, fmt::color::medium_sea_green, + fmt::color::deep_pink, fmt::color::medium_orchid, fmt::color::green_yellow, + fmt::color::dark_orange, fmt::color::golden_rod, fmt::color::medium_slate_blue, + fmt::color::coral, fmt::color::lemon_chiffon, fmt::color::wheat, + fmt::color::turquoise, }; -void VLog(Verbosity verb, char const* file, int line, - std::optional instance, char const* format, - fmt::format_args args) { +void VLog(Verbosity verb, char const* file, int line, std::optional instance, + char const* format, fmt::format_args args) { // Generate the time label. auto now = std::chrono::system_clock::now(); auto now_ms = std::chrono::time_point_cast(now); auto now_t = std::chrono::system_clock::to_time_t(now); char time_str[19]; // "mm-dd_HH:MM:SS.mmm\0" is 19 byte long - auto n = std::strftime(time_str, sizeof(time_str), "%m-%d %H:%M:%S", - std::localtime(&now_t)); + auto n = std::strftime(time_str, sizeof(time_str), "%m-%d %H:%M:%S", std::localtime(&now_t)); snprintf(time_str + n, sizeof(time_str) - n, ".%03u", static_cast(now_ms.time_since_epoch().count() % 1000)); @@ -75,13 +71,11 @@ void VLog(Verbosity verb, char const* file, int line, char file_str[40]; // file:line limited to 40 characters snprintf(file_str, sizeof(file_str), "%.35s:%d", file_name, line); - fmt::print("root-canal {} {} {:<35.35} ", verbosity_tag[verb], time_str, - file_str); + fmt::print("root-canal {} {} {:<35.35} ", verbosity_tag[verb], time_str, file_str); if (instance.has_value() && enable_log_color) { fmt::color instance_color = text_color[*instance % text_color.size()]; - fmt::print(fmt::bg(instance_color) | fmt::fg(fmt::color::black), " {:>2} ", - *instance); + fmt::print(fmt::bg(instance_color) | fmt::fg(fmt::color::black), " {:>2} ", *instance); fmt::print(" "); } else if (instance.has_value()) { fmt::print(" {:>2} ", *instance); diff --git a/tools/rootcanal/model/controller/acl_connection.cc b/tools/rootcanal/model/controller/acl_connection.cc index 33e4c36713d..3cb4172f5bd 100644 --- a/tools/rootcanal/model/controller/acl_connection.cc +++ b/tools/rootcanal/model/controller/acl_connection.cc @@ -23,10 +23,9 @@ #include "phy.h" namespace rootcanal { -AclConnection::AclConnection(AddressWithType address, - AddressWithType own_address, - AddressWithType resolved_address, - Phy::Type phy_type, bluetooth::hci::Role role) +AclConnection::AclConnection(AddressWithType address, AddressWithType own_address, + AddressWithType resolved_address, Phy::Type phy_type, + bluetooth::hci::Role role) : address_(address), own_address_(own_address), resolved_address_(resolved_address), @@ -39,9 +38,7 @@ void AclConnection::Encrypt() { encrypted_ = true; } bool AclConnection::IsEncrypted() const { return encrypted_; } -void AclConnection::SetLinkPolicySettings(uint16_t settings) { - link_policy_settings_ = settings; -} +void AclConnection::SetLinkPolicySettings(uint16_t settings) { link_policy_settings_ = settings; } bluetooth::hci::Role AclConnection::GetRole() const { return role_; } @@ -51,14 +48,10 @@ int8_t AclConnection::GetRssi() const { return rssi_; } void AclConnection::SetRssi(int8_t rssi) { rssi_ = rssi; } -void AclConnection::ResetLinkTimer() { - last_packet_timestamp_ = std::chrono::steady_clock::now(); -} +void AclConnection::ResetLinkTimer() { last_packet_timestamp_ = std::chrono::steady_clock::now(); } -std::chrono::steady_clock::duration AclConnection::TimeUntilNearExpiring() - const { - return (last_packet_timestamp_ + timeout_ / 2) - - std::chrono::steady_clock::now(); +std::chrono::steady_clock::duration AclConnection::TimeUntilNearExpiring() const { + return (last_packet_timestamp_ + timeout_ / 2) - std::chrono::steady_clock::now(); } bool AclConnection::IsNearExpiring() const { diff --git a/tools/rootcanal/model/controller/acl_connection.h b/tools/rootcanal/model/controller/acl_connection.h index 86ba9513e44..793f9e88235 100644 --- a/tools/rootcanal/model/controller/acl_connection.h +++ b/tools/rootcanal/model/controller/acl_connection.h @@ -35,10 +35,9 @@ enum AclConnectionState { // Model the connection of a device to the controller. class AclConnection { - public: +public: AclConnection(AddressWithType address, AddressWithType own_address, - AddressWithType resolved_address, Phy::Type phy_type, - bluetooth::hci::Role role); + AddressWithType resolved_address, Phy::Type phy_type, bluetooth::hci::Role role); virtual ~AclConnection() = default; @@ -53,9 +52,7 @@ class AclConnection { void SetLinkPolicySettings(uint16_t settings); uint16_t GetLinkPolicySettings() const { return link_policy_settings_; } - bool IsRoleSwitchEnabled() const { - return (link_policy_settings_ & 0x1) != 0; - } + bool IsRoleSwitchEnabled() const { return (link_policy_settings_ & 0x1) != 0; } bool IsHoldModeEnabled() const { return (link_policy_settings_ & 0x2) != 0; } bool IsSniffModeEnabled() const { return (link_policy_settings_ & 0x4) != 0; } @@ -82,7 +79,7 @@ class AclConnection { void SetTxPhy(bluetooth::hci::PhyType phy) { tx_phy_ = phy; } void SetRxPhy(bluetooth::hci::PhyType phy) { rx_phy_ = phy; } - private: +private: AddressWithType address_; AddressWithType own_address_; AddressWithType resolved_address_; diff --git a/tools/rootcanal/model/controller/acl_connection_handler.cc b/tools/rootcanal/model/controller/acl_connection_handler.cc index 656c495b844..bdcd1f72f41 100644 --- a/tools/rootcanal/model/controller/acl_connection_handler.cc +++ b/tools/rootcanal/model/controller/acl_connection_handler.cc @@ -59,8 +59,7 @@ uint16_t AclConnectionHandler::GetUnusedHandle() { // Keep a reserved range of handles for CIS connections implemented // in the rust module. while (HasHandle(last_handle_) || HasScoHandle(last_handle_) || - (last_handle_ >= kCisHandleRangeStart && - last_handle_ < kCisHandleRangeEnd)) { + (last_handle_ >= kCisHandleRangeStart && last_handle_ < kCisHandleRangeEnd)) { last_handle_ = (last_handle_ + 1) % kReservedHandle; } uint16_t unused_handle = last_handle_; @@ -68,8 +67,7 @@ uint16_t AclConnectionHandler::GetUnusedHandle() { return unused_handle; } -bool AclConnectionHandler::CreatePendingConnection(Address addr, - bool authenticate_on_connect, +bool AclConnectionHandler::CreatePendingConnection(Address addr, bool authenticate_on_connect, bool allow_role_switch) { if (classic_connection_pending_ || GetAclConnectionHandle(addr).has_value()) { return false; @@ -99,17 +97,15 @@ bool AclConnectionHandler::CancelPendingConnection(Address addr) { return true; } -bool AclConnectionHandler::CreatePendingLeConnection( - AddressWithType peer, AddressWithType resolved_peer, - AddressWithType local_address) { +bool AclConnectionHandler::CreatePendingLeConnection(AddressWithType peer, + AddressWithType resolved_peer, + AddressWithType local_address) { for (auto pair : acl_connections_) { auto connection = std::get(pair); - if (connection.GetAddress() == peer || - connection.GetResolvedAddress() == resolved_peer) { + if (connection.GetAddress() == peer || connection.GetResolvedAddress() == resolved_peer) { INFO("{}: {} is already connected", __func__, peer); if (connection.GetResolvedAddress() == resolved_peer) { - INFO("{}: allowing a second connection with {}", __func__, - resolved_peer); + INFO("{}: allowing a second connection with {}", __func__, resolved_peer); } else { return false; } @@ -136,44 +132,38 @@ bool AclConnectionHandler::CancelPendingLeConnection(AddressWithType addr) { } le_connection_pending_ = false; pending_le_connection_address_ = - AddressWithType{Address::kEmpty, AddressType::PUBLIC_DEVICE_ADDRESS}; + AddressWithType{Address::kEmpty, AddressType::PUBLIC_DEVICE_ADDRESS}; pending_le_connection_resolved_address_ = - AddressWithType{Address::kEmpty, AddressType::PUBLIC_DEVICE_ADDRESS}; + AddressWithType{Address::kEmpty, AddressType::PUBLIC_DEVICE_ADDRESS}; return true; } -uint16_t AclConnectionHandler::CreateConnection(Address addr, Address own_addr, - bool pending) { +uint16_t AclConnectionHandler::CreateConnection(Address addr, Address own_addr, bool pending) { if (!pending || CancelPendingConnection(addr)) { uint16_t handle = GetUnusedHandle(); acl_connections_.emplace( - handle, - AclConnection{ - AddressWithType{addr, AddressType::PUBLIC_DEVICE_ADDRESS}, - AddressWithType{own_addr, AddressType::PUBLIC_DEVICE_ADDRESS}, - AddressWithType(), Phy::Type::BR_EDR, - bluetooth::hci::Role::CENTRAL}); + handle, + AclConnection{AddressWithType{addr, AddressType::PUBLIC_DEVICE_ADDRESS}, + AddressWithType{own_addr, AddressType::PUBLIC_DEVICE_ADDRESS}, + AddressWithType(), Phy::Type::BR_EDR, bluetooth::hci::Role::CENTRAL}); return handle; } return kReservedHandle; } -uint16_t AclConnectionHandler::CreateLeConnection(AddressWithType addr, - AddressWithType own_addr, +uint16_t AclConnectionHandler::CreateLeConnection(AddressWithType addr, AddressWithType own_addr, bluetooth::hci::Role role) { AddressWithType resolved_peer = pending_le_connection_resolved_address_; if (CancelPendingLeConnection(addr)) { uint16_t handle = GetUnusedHandle(); - acl_connections_.emplace(handle, - AclConnection{addr, own_addr, resolved_peer, - Phy::Type::LOW_ENERGY, role}); + acl_connections_.emplace( + handle, AclConnection{addr, own_addr, resolved_peer, Phy::Type::LOW_ENERGY, role}); return handle; } return kReservedHandle; } -bool AclConnectionHandler::Disconnect(uint16_t handle, - std::function stopStream) { +bool AclConnectionHandler::Disconnect(uint16_t handle, std::function stopStream) { if (HasScoHandle(handle)) { sco_connections_.at(handle).StopStream(std::move(stopStream)); sco_connections_.erase(handle); @@ -199,8 +189,7 @@ uint16_t AclConnectionHandler::GetHandle(AddressWithType addr) const { return kReservedHandle; } -uint16_t AclConnectionHandler::GetHandleOnlyAddress( - bluetooth::hci::Address addr) const { +uint16_t AclConnectionHandler::GetHandleOnlyAddress(bluetooth::hci::Address addr) const { for (auto pair : acl_connections_) { if (std::get(pair).GetAddress().GetAddress() == addr) { return std::get<0>(pair); @@ -210,7 +199,7 @@ uint16_t AclConnectionHandler::GetHandleOnlyAddress( } std::optional AclConnectionHandler::GetAclConnectionHandle( - bluetooth::hci::Address bd_addr) const { + bluetooth::hci::Address bd_addr) const { for (auto const& [handle, connection] : acl_connections_) { if (connection.GetAddress().GetAddress() == bd_addr && connection.GetPhyType() == Phy::Type::BR_EDR) { @@ -230,8 +219,7 @@ AddressWithType AclConnectionHandler::GetAddress(uint16_t handle) const { return acl_connections_.at(handle).GetAddress(); } -std::optional AclConnectionHandler::GetAddressSafe( - uint16_t handle) const { +std::optional AclConnectionHandler::GetAddressSafe(uint16_t handle) const { return HasHandle(handle) ? acl_connections_.at(handle).GetAddress() : std::optional(); } @@ -246,8 +234,7 @@ AddressWithType AclConnectionHandler::GetOwnAddress(uint16_t handle) const { return acl_connections_.at(handle).GetOwnAddress(); } -AddressWithType AclConnectionHandler::GetResolvedAddress( - uint16_t handle) const { +AddressWithType AclConnectionHandler::GetResolvedAddress(uint16_t handle) const { ASSERT_LOG(HasHandle(handle), "Unknown handle %hd", handle); return acl_connections_.at(handle).GetResolvedAddress(); } @@ -287,8 +274,7 @@ uint16_t AclConnectionHandler::GetAclLinkPolicySettings(uint16_t handle) const { return acl_connections_.at(handle).GetLinkPolicySettings(); } -void AclConnectionHandler::SetAclLinkPolicySettings(uint16_t handle, - uint16_t settings) { +void AclConnectionHandler::SetAclLinkPolicySettings(uint16_t handle, uint16_t settings) { acl_connections_.at(handle).SetLinkPolicySettings(settings); } @@ -296,34 +282,29 @@ bluetooth::hci::Role AclConnectionHandler::GetAclRole(uint16_t handle) const { return acl_connections_.at(handle).GetRole(); } -void AclConnectionHandler::SetAclRole(uint16_t handle, - bluetooth::hci::Role role) { +void AclConnectionHandler::SetAclRole(uint16_t handle, bluetooth::hci::Role role) { acl_connections_.at(handle).SetRole(role); } -void AclConnectionHandler::CreateScoConnection( - bluetooth::hci::Address addr, ScoConnectionParameters const& parameters, - ScoState state, ScoDatapath datapath, bool legacy) { +void AclConnectionHandler::CreateScoConnection(bluetooth::hci::Address addr, + ScoConnectionParameters const& parameters, + ScoState state, ScoDatapath datapath, bool legacy) { uint16_t sco_handle = GetUnusedHandle(); - sco_connections_.emplace( - sco_handle, ScoConnection(addr, parameters, state, datapath, legacy)); + sco_connections_.emplace(sco_handle, ScoConnection(addr, parameters, state, datapath, legacy)); } -bool AclConnectionHandler::HasPendingScoConnection( - bluetooth::hci::Address addr) const { +bool AclConnectionHandler::HasPendingScoConnection(bluetooth::hci::Address addr) const { for (const auto& pair : sco_connections_) { if (std::get(pair).GetAddress() == addr) { ScoState state = std::get(pair).GetState(); - return state == SCO_STATE_PENDING || - state == SCO_STATE_SENT_ESCO_CONNECTION_REQUEST || + return state == SCO_STATE_PENDING || state == SCO_STATE_SENT_ESCO_CONNECTION_REQUEST || state == SCO_STATE_SENT_SCO_CONNECTION_REQUEST; } } return false; } -ScoState AclConnectionHandler::GetScoConnectionState( - bluetooth::hci::Address addr) const { +ScoState AclConnectionHandler::GetScoConnectionState(bluetooth::hci::Address addr) const { for (const auto& pair : sco_connections_) { if (std::get(pair).GetAddress() == addr) { return std::get(pair).GetState(); @@ -332,8 +313,7 @@ ScoState AclConnectionHandler::GetScoConnectionState( return SCO_STATE_CLOSED; } -bool AclConnectionHandler::IsLegacyScoConnection( - bluetooth::hci::Address addr) const { +bool AclConnectionHandler::IsLegacyScoConnection(bluetooth::hci::Address addr) const { for (const auto& pair : sco_connections_) { if (std::get(pair).GetAddress() == addr) { return std::get(pair).IsLegacy(); @@ -342,8 +322,7 @@ bool AclConnectionHandler::IsLegacyScoConnection( return false; } -void AclConnectionHandler::CancelPendingScoConnection( - bluetooth::hci::Address addr) { +void AclConnectionHandler::CancelPendingScoConnection(bluetooth::hci::Address addr) { for (auto it = sco_connections_.begin(); it != sco_connections_.end(); it++) { if (std::get(*it).GetAddress() == addr) { sco_connections_.erase(it); @@ -352,9 +331,9 @@ void AclConnectionHandler::CancelPendingScoConnection( } } -bool AclConnectionHandler::AcceptPendingScoConnection( - bluetooth::hci::Address addr, ScoLinkParameters const& parameters, - std::function startStream) { +bool AclConnectionHandler::AcceptPendingScoConnection(bluetooth::hci::Address addr, + ScoLinkParameters const& parameters, + std::function startStream) { for (auto& pair : sco_connections_) { if (std::get(pair).GetAddress() == addr) { std::get(pair).SetLinkParameters(parameters); @@ -366,13 +345,12 @@ bool AclConnectionHandler::AcceptPendingScoConnection( return false; } -bool AclConnectionHandler::AcceptPendingScoConnection( - bluetooth::hci::Address addr, ScoConnectionParameters const& parameters, - std::function startStream) { +bool AclConnectionHandler::AcceptPendingScoConnection(bluetooth::hci::Address addr, + ScoConnectionParameters const& parameters, + std::function startStream) { for (auto& pair : sco_connections_) { if (std::get(pair).GetAddress() == addr) { - bool ok = - std::get(pair).NegotiateLinkParameters(parameters); + bool ok = std::get(pair).NegotiateLinkParameters(parameters); std::get(pair).SetState(ok ? ScoState::SCO_STATE_OPENED : ScoState::SCO_STATE_CLOSED); if (ok) { @@ -384,8 +362,7 @@ bool AclConnectionHandler::AcceptPendingScoConnection( return false; } -uint16_t AclConnectionHandler::GetScoHandle( - bluetooth::hci::Address addr) const { +uint16_t AclConnectionHandler::GetScoHandle(bluetooth::hci::Address addr) const { for (const auto& pair : sco_connections_) { if (std::get(pair).GetAddress() == addr) { return std::get<0>(pair); @@ -395,7 +372,7 @@ uint16_t AclConnectionHandler::GetScoHandle( } ScoConnectionParameters AclConnectionHandler::GetScoConnectionParameters( - bluetooth::hci::Address addr) const { + bluetooth::hci::Address addr) const { for (const auto& pair : sco_connections_) { if (std::get(pair).GetAddress() == addr) { return std::get(pair).GetConnectionParameters(); @@ -404,8 +381,7 @@ ScoConnectionParameters AclConnectionHandler::GetScoConnectionParameters( return {}; } -ScoLinkParameters AclConnectionHandler::GetScoLinkParameters( - bluetooth::hci::Address addr) const { +ScoLinkParameters AclConnectionHandler::GetScoLinkParameters(bluetooth::hci::Address addr) const { for (const auto& pair : sco_connections_) { if (std::get(pair).GetAddress() == addr) { return std::get(pair).GetLinkParameters(); @@ -427,8 +403,8 @@ void AclConnectionHandler::ResetLinkTimer(uint16_t handle) { acl_connections_.at(handle).ResetLinkTimer(); } -std::chrono::steady_clock::duration -AclConnectionHandler::TimeUntilLinkNearExpiring(uint16_t handle) const { +std::chrono::steady_clock::duration AclConnectionHandler::TimeUntilLinkNearExpiring( + uint16_t handle) const { return acl_connections_.at(handle).TimeUntilNearExpiring(); } @@ -437,7 +413,7 @@ bool AclConnectionHandler::IsLinkNearExpiring(uint16_t handle) const { } std::chrono::steady_clock::duration AclConnectionHandler::TimeUntilLinkExpired( - uint16_t handle) const { + uint16_t handle) const { return acl_connections_.at(handle).TimeUntilExpired(); } diff --git a/tools/rootcanal/model/controller/acl_connection_handler.h b/tools/rootcanal/model/controller/acl_connection_handler.h index 146cc475fd9..b25181b418c 100644 --- a/tools/rootcanal/model/controller/acl_connection_handler.h +++ b/tools/rootcanal/model/controller/acl_connection_handler.h @@ -36,7 +36,7 @@ static constexpr uint16_t kCisHandleRangeStart = 0xE00; static constexpr uint16_t kCisHandleRangeEnd = 0xEFE; class AclConnectionHandler { - public: +public: AclConnectionHandler() = default; virtual ~AclConnectionHandler() = default; @@ -46,8 +46,7 @@ class AclConnectionHandler { // SCO connections. void Reset(std::function stopStream); - bool CreatePendingConnection(bluetooth::hci::Address addr, - bool authenticate_on_connect, + bool CreatePendingConnection(bluetooth::hci::Address addr, bool authenticate_on_connect, bool allow_role_switch); bool HasPendingConnection(bluetooth::hci::Address addr) const; bool CancelPendingConnection(bluetooth::hci::Address addr); @@ -56,20 +55,16 @@ class AclConnectionHandler { bool HasPendingScoConnection(bluetooth::hci::Address addr) const; ScoState GetScoConnectionState(bluetooth::hci::Address addr) const; bool IsLegacyScoConnection(bluetooth::hci::Address addr) const; - void CreateScoConnection(bluetooth::hci::Address addr, - ScoConnectionParameters const& parameters, - ScoState state, ScoDatapath datapath, - bool legacy = false); + void CreateScoConnection(bluetooth::hci::Address addr, ScoConnectionParameters const& parameters, + ScoState state, ScoDatapath datapath, bool legacy = false); void CancelPendingScoConnection(bluetooth::hci::Address addr); - bool AcceptPendingScoConnection(bluetooth::hci::Address addr, - ScoLinkParameters const& parameters, + bool AcceptPendingScoConnection(bluetooth::hci::Address addr, ScoLinkParameters const& parameters, std::function startStream); bool AcceptPendingScoConnection(bluetooth::hci::Address addr, ScoConnectionParameters const& parameters, std::function startStream); uint16_t GetScoHandle(bluetooth::hci::Address addr) const; - ScoConnectionParameters GetScoConnectionParameters( - bluetooth::hci::Address addr) const; + ScoConnectionParameters GetScoConnectionParameters(bluetooth::hci::Address addr) const; ScoLinkParameters GetScoLinkParameters(bluetooth::hci::Address addr) const; bool CreatePendingLeConnection(bluetooth::hci::AddressWithType peer, @@ -80,20 +75,17 @@ class AclConnectionHandler { // \p pending is true if the connection is expected to be // in pending state. - uint16_t CreateConnection(bluetooth::hci::Address addr, - bluetooth::hci::Address own_addr, + uint16_t CreateConnection(bluetooth::hci::Address addr, bluetooth::hci::Address own_addr, bool pending = true); uint16_t CreateLeConnection(bluetooth::hci::AddressWithType addr, - bluetooth::hci::AddressWithType own_addr, - bluetooth::hci::Role role); + bluetooth::hci::AddressWithType own_addr, bluetooth::hci::Role role); bool Disconnect(uint16_t handle, std::function stopStream); bool HasHandle(uint16_t handle) const; bool HasScoHandle(uint16_t handle) const; // Return the connection handle for a classic ACL connection only. // \p bd_addr is the peer address. - std::optional GetAclConnectionHandle( - bluetooth::hci::Address bd_addr) const; + std::optional GetAclConnectionHandle(bluetooth::hci::Address bd_addr) const; uint16_t GetHandle(bluetooth::hci::AddressWithType addr) const; uint16_t GetHandleOnlyAddress(bluetooth::hci::Address addr) const; @@ -124,33 +116,27 @@ class AclConnectionHandler { std::vector GetAclHandles() const; void ResetLinkTimer(uint16_t handle); - std::chrono::steady_clock::duration TimeUntilLinkNearExpiring( - uint16_t handle) const; + std::chrono::steady_clock::duration TimeUntilLinkNearExpiring(uint16_t handle) const; bool IsLinkNearExpiring(uint16_t handle) const; - std::chrono::steady_clock::duration TimeUntilLinkExpired( - uint16_t handle) const; + std::chrono::steady_clock::duration TimeUntilLinkExpired(uint16_t handle) const; bool HasLinkExpired(uint16_t handle) const; bool IsRoleSwitchAllowedForPendingConnection() const; - private: +private: std::unordered_map acl_connections_; std::unordered_map sco_connections_; bool classic_connection_pending_{false}; - bluetooth::hci::Address pending_connection_address_{ - bluetooth::hci::Address::kEmpty}; + bluetooth::hci::Address pending_connection_address_{bluetooth::hci::Address::kEmpty}; bool authenticate_pending_classic_connection_{false}; bool pending_classic_connection_allow_role_switch_{false}; bool le_connection_pending_{false}; bluetooth::hci::AddressWithType pending_le_connection_address_{ - bluetooth::hci::Address::kEmpty, - bluetooth::hci::AddressType::PUBLIC_DEVICE_ADDRESS}; + bluetooth::hci::Address::kEmpty, bluetooth::hci::AddressType::PUBLIC_DEVICE_ADDRESS}; bluetooth::hci::AddressWithType pending_le_connection_own_address_{ - bluetooth::hci::Address::kEmpty, - bluetooth::hci::AddressType::PUBLIC_DEVICE_ADDRESS}; + bluetooth::hci::Address::kEmpty, bluetooth::hci::AddressType::PUBLIC_DEVICE_ADDRESS}; bluetooth::hci::AddressWithType pending_le_connection_resolved_address_{ - bluetooth::hci::Address::kEmpty, - bluetooth::hci::AddressType::PUBLIC_DEVICE_ADDRESS}; + bluetooth::hci::Address::kEmpty, bluetooth::hci::AddressType::PUBLIC_DEVICE_ADDRESS}; uint16_t GetUnusedHandle(); uint16_t last_handle_{kReservedHandle - 2}; diff --git a/tools/rootcanal/model/controller/controller_properties.cc b/tools/rootcanal/model/controller/controller_properties.cc index 49198879d2d..b9afe2cf407 100644 --- a/tools/rootcanal/model/controller/controller_properties.cc +++ b/tools/rootcanal/model/controller/controller_properties.cc @@ -30,55 +30,55 @@ using namespace bluetooth::hci; static constexpr uint64_t Page0LmpFeatures() { LMPFeaturesPage0Bits features[] = { - LMPFeaturesPage0Bits::LMP_3_SLOT_PACKETS, - LMPFeaturesPage0Bits::LMP_5_SLOT_PACKETS, - LMPFeaturesPage0Bits::ENCRYPTION, - LMPFeaturesPage0Bits::SLOT_OFFSET, - LMPFeaturesPage0Bits::TIMING_ACCURACY, - LMPFeaturesPage0Bits::ROLE_SWITCH, - LMPFeaturesPage0Bits::HOLD_MODE, - LMPFeaturesPage0Bits::SNIFF_MODE, - LMPFeaturesPage0Bits::POWER_CONTROL_REQUESTS, - LMPFeaturesPage0Bits::CHANNEL_QUALITY_DRIVEN_DATA_RATE, - LMPFeaturesPage0Bits::SCO_LINK, - LMPFeaturesPage0Bits::HV2_PACKETS, - LMPFeaturesPage0Bits::HV3_PACKETS, - LMPFeaturesPage0Bits::M_LAW_LOG_SYNCHRONOUS_DATA, - LMPFeaturesPage0Bits::A_LAW_LOG_SYNCHRONOUS_DATA, - LMPFeaturesPage0Bits::CVSD_SYNCHRONOUS_DATA, - LMPFeaturesPage0Bits::PAGING_PARAMETER_NEGOTIATION, - LMPFeaturesPage0Bits::POWER_CONTROL, - LMPFeaturesPage0Bits::TRANSPARENT_SYNCHRONOUS_DATA, - LMPFeaturesPage0Bits::BROADCAST_ENCRYPTION, - LMPFeaturesPage0Bits::ENHANCED_DATA_RATE_ACL_2_MB_S_MODE, - LMPFeaturesPage0Bits::ENHANCED_DATA_RATE_ACL_3_MB_S_MODE, - LMPFeaturesPage0Bits::ENHANCED_INQUIRY_SCAN, - LMPFeaturesPage0Bits::INTERLACED_INQUIRY_SCAN, - LMPFeaturesPage0Bits::INTERLACED_PAGE_SCAN, - LMPFeaturesPage0Bits::RSSI_WITH_INQUIRY_RESULTS, - LMPFeaturesPage0Bits::EXTENDED_SCO_LINK, - LMPFeaturesPage0Bits::EV4_PACKETS, - LMPFeaturesPage0Bits::EV5_PACKETS, - LMPFeaturesPage0Bits::AFH_CAPABLE_PERIPHERAL, - LMPFeaturesPage0Bits::AFH_CLASSIFICATION_PERIPHERAL, - LMPFeaturesPage0Bits::LE_SUPPORTED_CONTROLLER, - LMPFeaturesPage0Bits::LMP_3_SLOT_ENHANCED_DATA_RATE_ACL_PACKETS, - LMPFeaturesPage0Bits::LMP_5_SLOT_ENHANCED_DATA_RATE_ACL_PACKETS, - LMPFeaturesPage0Bits::SNIFF_SUBRATING, - LMPFeaturesPage0Bits::PAUSE_ENCRYPTION, - LMPFeaturesPage0Bits::AFH_CAPABLE_CENTRAL, - LMPFeaturesPage0Bits::AFH_CLASSIFICATION_CENTRAL, - LMPFeaturesPage0Bits::ENHANCED_DATA_RATE_ESCO_2_MB_S_MODE, - LMPFeaturesPage0Bits::ENHANCED_DATA_RATE_ESCO_3_MB_S_MODE, - LMPFeaturesPage0Bits::LMP_3_SLOT_ENHANCED_DATA_RATE_ESCO_PACKETS, - LMPFeaturesPage0Bits::EXTENDED_INQUIRY_RESPONSE, - LMPFeaturesPage0Bits::SIMULTANEOUS_LE_AND_BR_CONTROLLER, - LMPFeaturesPage0Bits::SECURE_SIMPLE_PAIRING_CONTROLLER, - LMPFeaturesPage0Bits::ENCAPSULATED_PDU, - LMPFeaturesPage0Bits::HCI_LINK_SUPERVISION_TIMEOUT_CHANGED_EVENT, - LMPFeaturesPage0Bits::VARIABLE_INQUIRY_TX_POWER_LEVEL, - LMPFeaturesPage0Bits::ENHANCED_POWER_CONTROL, - LMPFeaturesPage0Bits::EXTENDED_FEATURES}; + LMPFeaturesPage0Bits::LMP_3_SLOT_PACKETS, + LMPFeaturesPage0Bits::LMP_5_SLOT_PACKETS, + LMPFeaturesPage0Bits::ENCRYPTION, + LMPFeaturesPage0Bits::SLOT_OFFSET, + LMPFeaturesPage0Bits::TIMING_ACCURACY, + LMPFeaturesPage0Bits::ROLE_SWITCH, + LMPFeaturesPage0Bits::HOLD_MODE, + LMPFeaturesPage0Bits::SNIFF_MODE, + LMPFeaturesPage0Bits::POWER_CONTROL_REQUESTS, + LMPFeaturesPage0Bits::CHANNEL_QUALITY_DRIVEN_DATA_RATE, + LMPFeaturesPage0Bits::SCO_LINK, + LMPFeaturesPage0Bits::HV2_PACKETS, + LMPFeaturesPage0Bits::HV3_PACKETS, + LMPFeaturesPage0Bits::M_LAW_LOG_SYNCHRONOUS_DATA, + LMPFeaturesPage0Bits::A_LAW_LOG_SYNCHRONOUS_DATA, + LMPFeaturesPage0Bits::CVSD_SYNCHRONOUS_DATA, + LMPFeaturesPage0Bits::PAGING_PARAMETER_NEGOTIATION, + LMPFeaturesPage0Bits::POWER_CONTROL, + LMPFeaturesPage0Bits::TRANSPARENT_SYNCHRONOUS_DATA, + LMPFeaturesPage0Bits::BROADCAST_ENCRYPTION, + LMPFeaturesPage0Bits::ENHANCED_DATA_RATE_ACL_2_MB_S_MODE, + LMPFeaturesPage0Bits::ENHANCED_DATA_RATE_ACL_3_MB_S_MODE, + LMPFeaturesPage0Bits::ENHANCED_INQUIRY_SCAN, + LMPFeaturesPage0Bits::INTERLACED_INQUIRY_SCAN, + LMPFeaturesPage0Bits::INTERLACED_PAGE_SCAN, + LMPFeaturesPage0Bits::RSSI_WITH_INQUIRY_RESULTS, + LMPFeaturesPage0Bits::EXTENDED_SCO_LINK, + LMPFeaturesPage0Bits::EV4_PACKETS, + LMPFeaturesPage0Bits::EV5_PACKETS, + LMPFeaturesPage0Bits::AFH_CAPABLE_PERIPHERAL, + LMPFeaturesPage0Bits::AFH_CLASSIFICATION_PERIPHERAL, + LMPFeaturesPage0Bits::LE_SUPPORTED_CONTROLLER, + LMPFeaturesPage0Bits::LMP_3_SLOT_ENHANCED_DATA_RATE_ACL_PACKETS, + LMPFeaturesPage0Bits::LMP_5_SLOT_ENHANCED_DATA_RATE_ACL_PACKETS, + LMPFeaturesPage0Bits::SNIFF_SUBRATING, + LMPFeaturesPage0Bits::PAUSE_ENCRYPTION, + LMPFeaturesPage0Bits::AFH_CAPABLE_CENTRAL, + LMPFeaturesPage0Bits::AFH_CLASSIFICATION_CENTRAL, + LMPFeaturesPage0Bits::ENHANCED_DATA_RATE_ESCO_2_MB_S_MODE, + LMPFeaturesPage0Bits::ENHANCED_DATA_RATE_ESCO_3_MB_S_MODE, + LMPFeaturesPage0Bits::LMP_3_SLOT_ENHANCED_DATA_RATE_ESCO_PACKETS, + LMPFeaturesPage0Bits::EXTENDED_INQUIRY_RESPONSE, + LMPFeaturesPage0Bits::SIMULTANEOUS_LE_AND_BR_CONTROLLER, + LMPFeaturesPage0Bits::SECURE_SIMPLE_PAIRING_CONTROLLER, + LMPFeaturesPage0Bits::ENCAPSULATED_PDU, + LMPFeaturesPage0Bits::HCI_LINK_SUPERVISION_TIMEOUT_CHANGED_EVENT, + LMPFeaturesPage0Bits::VARIABLE_INQUIRY_TX_POWER_LEVEL, + LMPFeaturesPage0Bits::ENHANCED_POWER_CONTROL, + LMPFeaturesPage0Bits::EXTENDED_FEATURES}; uint64_t value = 0; for (auto feature : features) { @@ -89,8 +89,8 @@ static constexpr uint64_t Page0LmpFeatures() { static constexpr uint64_t Page2LmpFeatures() { LMPFeaturesPage2Bits features[] = { - LMPFeaturesPage2Bits::SECURE_CONNECTIONS_CONTROLLER_SUPPORT, - LMPFeaturesPage2Bits::PING, + LMPFeaturesPage2Bits::SECURE_CONNECTIONS_CONTROLLER_SUPPORT, + LMPFeaturesPage2Bits::PING, }; uint64_t value = 0; @@ -102,20 +102,20 @@ static constexpr uint64_t Page2LmpFeatures() { static constexpr uint64_t LlFeatures() { LLFeaturesBits features[] = { - LLFeaturesBits::LE_ENCRYPTION, - LLFeaturesBits::CONNECTION_PARAMETERS_REQUEST_PROCEDURE, - LLFeaturesBits::EXTENDED_REJECT_INDICATION, - LLFeaturesBits::PERIPHERAL_INITIATED_FEATURES_EXCHANGE, - LLFeaturesBits::LE_PING, - LLFeaturesBits::LL_PRIVACY, - LLFeaturesBits::EXTENDED_SCANNER_FILTER_POLICIES, - LLFeaturesBits::LE_2M_PHY, - LLFeaturesBits::LE_CODED_PHY, - LLFeaturesBits::LE_EXTENDED_ADVERTISING, - LLFeaturesBits::LE_PERIODIC_ADVERTISING, + LLFeaturesBits::LE_ENCRYPTION, + LLFeaturesBits::CONNECTION_PARAMETERS_REQUEST_PROCEDURE, + LLFeaturesBits::EXTENDED_REJECT_INDICATION, + LLFeaturesBits::PERIPHERAL_INITIATED_FEATURES_EXCHANGE, + LLFeaturesBits::LE_PING, + LLFeaturesBits::LL_PRIVACY, + LLFeaturesBits::EXTENDED_SCANNER_FILTER_POLICIES, + LLFeaturesBits::LE_2M_PHY, + LLFeaturesBits::LE_CODED_PHY, + LLFeaturesBits::LE_EXTENDED_ADVERTISING, + LLFeaturesBits::LE_PERIODIC_ADVERTISING, - LLFeaturesBits::CONNECTED_ISOCHRONOUS_STREAM_CENTRAL, - LLFeaturesBits::CONNECTED_ISOCHRONOUS_STREAM_PERIPHERAL, + LLFeaturesBits::CONNECTED_ISOCHRONOUS_STREAM_CENTRAL, + LLFeaturesBits::CONNECTED_ISOCHRONOUS_STREAM_PERIPHERAL, }; uint64_t value = 0; @@ -127,283 +127,243 @@ static constexpr uint64_t LlFeatures() { static std::array SupportedCommands() { OpCodeIndex supported_commands[] = { - // LINK_CONTROL - OpCodeIndex::INQUIRY, OpCodeIndex::INQUIRY_CANCEL, - // OpCodeIndex::PERIODIC_INQUIRY_MODE, - // OpCodeIndex::EXIT_PERIODIC_INQUIRY_MODE, - OpCodeIndex::CREATE_CONNECTION, OpCodeIndex::DISCONNECT, - OpCodeIndex::ADD_SCO_CONNECTION, OpCodeIndex::CREATE_CONNECTION_CANCEL, - OpCodeIndex::ACCEPT_CONNECTION_REQUEST, - OpCodeIndex::REJECT_CONNECTION_REQUEST, - OpCodeIndex::LINK_KEY_REQUEST_REPLY, - OpCodeIndex::LINK_KEY_REQUEST_NEGATIVE_REPLY, - OpCodeIndex::PIN_CODE_REQUEST_REPLY, - OpCodeIndex::PIN_CODE_REQUEST_NEGATIVE_REPLY, - OpCodeIndex::CHANGE_CONNECTION_PACKET_TYPE, - OpCodeIndex::AUTHENTICATION_REQUESTED, - OpCodeIndex::SET_CONNECTION_ENCRYPTION, - OpCodeIndex::CHANGE_CONNECTION_LINK_KEY, OpCodeIndex::CENTRAL_LINK_KEY, - OpCodeIndex::REMOTE_NAME_REQUEST, - // OpCodeIndex::REMOTE_NAME_REQUEST_CANCEL, - OpCodeIndex::READ_REMOTE_SUPPORTED_FEATURES, - OpCodeIndex::READ_REMOTE_EXTENDED_FEATURES, - OpCodeIndex::READ_REMOTE_VERSION_INFORMATION, - OpCodeIndex::READ_CLOCK_OFFSET, OpCodeIndex::READ_LMP_HANDLE, - OpCodeIndex::SETUP_SYNCHRONOUS_CONNECTION, - OpCodeIndex::ACCEPT_SYNCHRONOUS_CONNECTION, - OpCodeIndex::REJECT_SYNCHRONOUS_CONNECTION, - OpCodeIndex::IO_CAPABILITY_REQUEST_REPLY, - OpCodeIndex::USER_CONFIRMATION_REQUEST_REPLY, - OpCodeIndex::USER_CONFIRMATION_REQUEST_NEGATIVE_REPLY, - OpCodeIndex::USER_PASSKEY_REQUEST_REPLY, - OpCodeIndex::USER_PASSKEY_REQUEST_NEGATIVE_REPLY, - OpCodeIndex::REMOTE_OOB_DATA_REQUEST_REPLY, - OpCodeIndex::REMOTE_OOB_DATA_REQUEST_NEGATIVE_REPLY, - OpCodeIndex::IO_CAPABILITY_REQUEST_NEGATIVE_REPLY, - OpCodeIndex::ENHANCED_SETUP_SYNCHRONOUS_CONNECTION, - OpCodeIndex::ENHANCED_ACCEPT_SYNCHRONOUS_CONNECTION, - // OpCodeIndex::TRUNCATED_PAGE, - // OpCodeIndex::TRUNCATED_PAGE_CANCEL, - // OpCodeIndex::SET_CONNECTIONLESS_PERIPHERAL_BROADCAST, - // OpCodeIndex::SET_CONNECTIONLESS_PERIPHERAL_BROADCAST_RECEIVE, - // OpCodeIndex::START_SYNCHRONIZATION_TRAIN, - // OpCodeIndex::RECEIVE_SYNCHRONIZATION_TRAIN, - OpCodeIndex::REMOTE_OOB_EXTENDED_DATA_REQUEST_REPLY, + // LINK_CONTROL + OpCodeIndex::INQUIRY, OpCodeIndex::INQUIRY_CANCEL, + // OpCodeIndex::PERIODIC_INQUIRY_MODE, + // OpCodeIndex::EXIT_PERIODIC_INQUIRY_MODE, + OpCodeIndex::CREATE_CONNECTION, OpCodeIndex::DISCONNECT, OpCodeIndex::ADD_SCO_CONNECTION, + OpCodeIndex::CREATE_CONNECTION_CANCEL, OpCodeIndex::ACCEPT_CONNECTION_REQUEST, + OpCodeIndex::REJECT_CONNECTION_REQUEST, OpCodeIndex::LINK_KEY_REQUEST_REPLY, + OpCodeIndex::LINK_KEY_REQUEST_NEGATIVE_REPLY, OpCodeIndex::PIN_CODE_REQUEST_REPLY, + OpCodeIndex::PIN_CODE_REQUEST_NEGATIVE_REPLY, OpCodeIndex::CHANGE_CONNECTION_PACKET_TYPE, + OpCodeIndex::AUTHENTICATION_REQUESTED, OpCodeIndex::SET_CONNECTION_ENCRYPTION, + OpCodeIndex::CHANGE_CONNECTION_LINK_KEY, OpCodeIndex::CENTRAL_LINK_KEY, + OpCodeIndex::REMOTE_NAME_REQUEST, + // OpCodeIndex::REMOTE_NAME_REQUEST_CANCEL, + OpCodeIndex::READ_REMOTE_SUPPORTED_FEATURES, OpCodeIndex::READ_REMOTE_EXTENDED_FEATURES, + OpCodeIndex::READ_REMOTE_VERSION_INFORMATION, OpCodeIndex::READ_CLOCK_OFFSET, + OpCodeIndex::READ_LMP_HANDLE, OpCodeIndex::SETUP_SYNCHRONOUS_CONNECTION, + OpCodeIndex::ACCEPT_SYNCHRONOUS_CONNECTION, OpCodeIndex::REJECT_SYNCHRONOUS_CONNECTION, + OpCodeIndex::IO_CAPABILITY_REQUEST_REPLY, OpCodeIndex::USER_CONFIRMATION_REQUEST_REPLY, + OpCodeIndex::USER_CONFIRMATION_REQUEST_NEGATIVE_REPLY, + OpCodeIndex::USER_PASSKEY_REQUEST_REPLY, OpCodeIndex::USER_PASSKEY_REQUEST_NEGATIVE_REPLY, + OpCodeIndex::REMOTE_OOB_DATA_REQUEST_REPLY, + OpCodeIndex::REMOTE_OOB_DATA_REQUEST_NEGATIVE_REPLY, + OpCodeIndex::IO_CAPABILITY_REQUEST_NEGATIVE_REPLY, + OpCodeIndex::ENHANCED_SETUP_SYNCHRONOUS_CONNECTION, + OpCodeIndex::ENHANCED_ACCEPT_SYNCHRONOUS_CONNECTION, + // OpCodeIndex::TRUNCATED_PAGE, + // OpCodeIndex::TRUNCATED_PAGE_CANCEL, + // OpCodeIndex::SET_CONNECTIONLESS_PERIPHERAL_BROADCAST, + // OpCodeIndex::SET_CONNECTIONLESS_PERIPHERAL_BROADCAST_RECEIVE, + // OpCodeIndex::START_SYNCHRONIZATION_TRAIN, + // OpCodeIndex::RECEIVE_SYNCHRONIZATION_TRAIN, + OpCodeIndex::REMOTE_OOB_EXTENDED_DATA_REQUEST_REPLY, - // LINK_POLICY - OpCodeIndex::HOLD_MODE, OpCodeIndex::SNIFF_MODE, - OpCodeIndex::EXIT_SNIFF_MODE, OpCodeIndex::QOS_SETUP, - OpCodeIndex::ROLE_DISCOVERY, OpCodeIndex::SWITCH_ROLE, - OpCodeIndex::READ_LINK_POLICY_SETTINGS, - OpCodeIndex::WRITE_LINK_POLICY_SETTINGS, - OpCodeIndex::READ_DEFAULT_LINK_POLICY_SETTINGS, - OpCodeIndex::WRITE_DEFAULT_LINK_POLICY_SETTINGS, - OpCodeIndex::FLOW_SPECIFICATION, OpCodeIndex::SNIFF_SUBRATING, + // LINK_POLICY + OpCodeIndex::HOLD_MODE, OpCodeIndex::SNIFF_MODE, OpCodeIndex::EXIT_SNIFF_MODE, + OpCodeIndex::QOS_SETUP, OpCodeIndex::ROLE_DISCOVERY, OpCodeIndex::SWITCH_ROLE, + OpCodeIndex::READ_LINK_POLICY_SETTINGS, OpCodeIndex::WRITE_LINK_POLICY_SETTINGS, + OpCodeIndex::READ_DEFAULT_LINK_POLICY_SETTINGS, + OpCodeIndex::WRITE_DEFAULT_LINK_POLICY_SETTINGS, OpCodeIndex::FLOW_SPECIFICATION, + OpCodeIndex::SNIFF_SUBRATING, - // CONTROLLER_AND_BASEBAND - OpCodeIndex::SET_EVENT_MASK, OpCodeIndex::RESET, - OpCodeIndex::SET_EVENT_FILTER, OpCodeIndex::FLUSH, - // OpCodeIndex::READ_PIN_TYPE, - // OpCodeIndex::WRITE_PIN_TYPE, - // OpCodeIndex::READ_STORED_LINK_KEY, - // OpCodeIndex::WRITE_STORED_LINK_KEY, - OpCodeIndex::DELETE_STORED_LINK_KEY, OpCodeIndex::WRITE_LOCAL_NAME, - OpCodeIndex::READ_LOCAL_NAME, OpCodeIndex::READ_CONNECTION_ACCEPT_TIMEOUT, - OpCodeIndex::WRITE_CONNECTION_ACCEPT_TIMEOUT, - OpCodeIndex::READ_PAGE_TIMEOUT, OpCodeIndex::WRITE_PAGE_TIMEOUT, - OpCodeIndex::READ_SCAN_ENABLE, OpCodeIndex::WRITE_SCAN_ENABLE, - OpCodeIndex::READ_PAGE_SCAN_ACTIVITY, - OpCodeIndex::WRITE_PAGE_SCAN_ACTIVITY, - OpCodeIndex::READ_INQUIRY_SCAN_ACTIVITY, - OpCodeIndex::WRITE_INQUIRY_SCAN_ACTIVITY, - OpCodeIndex::READ_AUTHENTICATION_ENABLE, - OpCodeIndex::WRITE_AUTHENTICATION_ENABLE, - OpCodeIndex::READ_CLASS_OF_DEVICE, OpCodeIndex::WRITE_CLASS_OF_DEVICE, - OpCodeIndex::READ_VOICE_SETTING, OpCodeIndex::WRITE_VOICE_SETTING, - OpCodeIndex::READ_AUTOMATIC_FLUSH_TIMEOUT, - OpCodeIndex::WRITE_AUTOMATIC_FLUSH_TIMEOUT, - // OpCodeIndex::READ_NUM_BROADCAST_RETRANSMITS, - // OpCodeIndex::WRITE_NUM_BROADCAST_RETRANSMITS, - OpCodeIndex::READ_HOLD_MODE_ACTIVITY, - OpCodeIndex::WRITE_HOLD_MODE_ACTIVITY, - OpCodeIndex::READ_TRANSMIT_POWER_LEVEL, - OpCodeIndex::READ_SYNCHRONOUS_FLOW_CONTROL_ENABLE, - OpCodeIndex::WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE, - OpCodeIndex::SET_CONTROLLER_TO_HOST_FLOW_CONTROL, - OpCodeIndex::HOST_BUFFER_SIZE, - OpCodeIndex::HOST_NUMBER_OF_COMPLETED_PACKETS, - OpCodeIndex::READ_LINK_SUPERVISION_TIMEOUT, - OpCodeIndex::WRITE_LINK_SUPERVISION_TIMEOUT, - OpCodeIndex::READ_NUMBER_OF_SUPPORTED_IAC, - OpCodeIndex::READ_CURRENT_IAC_LAP, OpCodeIndex::WRITE_CURRENT_IAC_LAP, - OpCodeIndex::SET_AFH_HOST_CHANNEL_CLASSIFICATION, - OpCodeIndex::READ_INQUIRY_SCAN_TYPE, OpCodeIndex::WRITE_INQUIRY_SCAN_TYPE, - OpCodeIndex::READ_INQUIRY_MODE, OpCodeIndex::WRITE_INQUIRY_MODE, - OpCodeIndex::READ_PAGE_SCAN_TYPE, OpCodeIndex::WRITE_PAGE_SCAN_TYPE, - OpCodeIndex::READ_AFH_CHANNEL_ASSESSMENT_MODE, - OpCodeIndex::WRITE_AFH_CHANNEL_ASSESSMENT_MODE, - OpCodeIndex::READ_EXTENDED_INQUIRY_RESPONSE, - OpCodeIndex::WRITE_EXTENDED_INQUIRY_RESPONSE, - OpCodeIndex::REFRESH_ENCRYPTION_KEY, - OpCodeIndex::READ_SIMPLE_PAIRING_MODE, - OpCodeIndex::WRITE_SIMPLE_PAIRING_MODE, OpCodeIndex::READ_LOCAL_OOB_DATA, - OpCodeIndex::READ_INQUIRY_RESPONSE_TRANSMIT_POWER_LEVEL, - OpCodeIndex::WRITE_INQUIRY_TRANSMIT_POWER_LEVEL, - // OpCodeIndex::READ_DEFAULT_ERRONEOUS_DATA_REPORTING, - // OpCodeIndex::WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING, - OpCodeIndex::ENHANCED_FLUSH, OpCodeIndex::SEND_KEYPRESS_NOTIFICATION, - OpCodeIndex::SET_EVENT_MASK_PAGE_2, - // OpCodeIndex::READ_FLOW_CONTROL_MODE, - // OpCodeIndex::WRITE_FLOW_CONTROL_MODE, - OpCodeIndex::READ_ENHANCED_TRANSMIT_POWER_LEVEL, - OpCodeIndex::READ_LE_HOST_SUPPORT, OpCodeIndex::WRITE_LE_HOST_SUPPORT, - // OpCodeIndex::SET_MWS_CHANNEL_PARAMETERS, - // OpCodeIndex::SET_EXTERNAL_FRAME_CONFIGURATION, - // OpCodeIndex::SET_MWS_SIGNALING, - // OpCodeIndex::SET_MWS_TRANSPORT_LAYER, - // OpCodeIndex::SET_MWS_SCAN_FREQUENCY_TABLE, - // OpCodeIndex::SET_MWS_PATTERN_CONFIGURATION, - // OpCodeIndex::SET_RESERVED_LT_ADDR, - // OpCodeIndex::DELETE_RESERVED_LT_ADDR, - // OpCodeIndex::SET_CONNECTIONLESS_PERIPHERAL_BROADCAST_DATA, - // OpCodeIndex::READ_SYNCHRONIZATION_TRAIN_PARAMETERS, - // OpCodeIndex::WRITE_SYNCHRONIZATION_TRAIN_PARAMETERS, - OpCodeIndex::READ_SECURE_CONNECTIONS_HOST_SUPPORT, - OpCodeIndex::WRITE_SECURE_CONNECTIONS_HOST_SUPPORT, - OpCodeIndex::READ_AUTHENTICATED_PAYLOAD_TIMEOUT, - OpCodeIndex::WRITE_AUTHENTICATED_PAYLOAD_TIMEOUT, - OpCodeIndex::READ_LOCAL_OOB_EXTENDED_DATA, - // OpCodeIndex::READ_EXTENDED_PAGE_TIMEOUT, - // OpCodeIndex::WRITE_EXTENDED_PAGE_TIMEOUT, - // OpCodeIndex::READ_EXTENDED_INQUIRY_LENGTH, - // OpCodeIndex::WRITE_EXTENDED_INQUIRY_LENGTH, - // OpCodeIndex::SET_ECOSYSTEM_BASE_INTERVAL, - // OpCodeIndex::CONFIGURE_DATA_PATH, - // OpCodeIndex::SET_MIN_ENCRYPTION_KEY_SIZE, + // CONTROLLER_AND_BASEBAND + OpCodeIndex::SET_EVENT_MASK, OpCodeIndex::RESET, OpCodeIndex::SET_EVENT_FILTER, + OpCodeIndex::FLUSH, + // OpCodeIndex::READ_PIN_TYPE, + // OpCodeIndex::WRITE_PIN_TYPE, + // OpCodeIndex::READ_STORED_LINK_KEY, + // OpCodeIndex::WRITE_STORED_LINK_KEY, + OpCodeIndex::DELETE_STORED_LINK_KEY, OpCodeIndex::WRITE_LOCAL_NAME, + OpCodeIndex::READ_LOCAL_NAME, OpCodeIndex::READ_CONNECTION_ACCEPT_TIMEOUT, + OpCodeIndex::WRITE_CONNECTION_ACCEPT_TIMEOUT, OpCodeIndex::READ_PAGE_TIMEOUT, + OpCodeIndex::WRITE_PAGE_TIMEOUT, OpCodeIndex::READ_SCAN_ENABLE, + OpCodeIndex::WRITE_SCAN_ENABLE, OpCodeIndex::READ_PAGE_SCAN_ACTIVITY, + OpCodeIndex::WRITE_PAGE_SCAN_ACTIVITY, OpCodeIndex::READ_INQUIRY_SCAN_ACTIVITY, + OpCodeIndex::WRITE_INQUIRY_SCAN_ACTIVITY, OpCodeIndex::READ_AUTHENTICATION_ENABLE, + OpCodeIndex::WRITE_AUTHENTICATION_ENABLE, OpCodeIndex::READ_CLASS_OF_DEVICE, + OpCodeIndex::WRITE_CLASS_OF_DEVICE, OpCodeIndex::READ_VOICE_SETTING, + OpCodeIndex::WRITE_VOICE_SETTING, OpCodeIndex::READ_AUTOMATIC_FLUSH_TIMEOUT, + OpCodeIndex::WRITE_AUTOMATIC_FLUSH_TIMEOUT, + // OpCodeIndex::READ_NUM_BROADCAST_RETRANSMITS, + // OpCodeIndex::WRITE_NUM_BROADCAST_RETRANSMITS, + OpCodeIndex::READ_HOLD_MODE_ACTIVITY, OpCodeIndex::WRITE_HOLD_MODE_ACTIVITY, + OpCodeIndex::READ_TRANSMIT_POWER_LEVEL, OpCodeIndex::READ_SYNCHRONOUS_FLOW_CONTROL_ENABLE, + OpCodeIndex::WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE, + OpCodeIndex::SET_CONTROLLER_TO_HOST_FLOW_CONTROL, OpCodeIndex::HOST_BUFFER_SIZE, + OpCodeIndex::HOST_NUMBER_OF_COMPLETED_PACKETS, OpCodeIndex::READ_LINK_SUPERVISION_TIMEOUT, + OpCodeIndex::WRITE_LINK_SUPERVISION_TIMEOUT, OpCodeIndex::READ_NUMBER_OF_SUPPORTED_IAC, + OpCodeIndex::READ_CURRENT_IAC_LAP, OpCodeIndex::WRITE_CURRENT_IAC_LAP, + OpCodeIndex::SET_AFH_HOST_CHANNEL_CLASSIFICATION, OpCodeIndex::READ_INQUIRY_SCAN_TYPE, + OpCodeIndex::WRITE_INQUIRY_SCAN_TYPE, OpCodeIndex::READ_INQUIRY_MODE, + OpCodeIndex::WRITE_INQUIRY_MODE, OpCodeIndex::READ_PAGE_SCAN_TYPE, + OpCodeIndex::WRITE_PAGE_SCAN_TYPE, OpCodeIndex::READ_AFH_CHANNEL_ASSESSMENT_MODE, + OpCodeIndex::WRITE_AFH_CHANNEL_ASSESSMENT_MODE, + OpCodeIndex::READ_EXTENDED_INQUIRY_RESPONSE, OpCodeIndex::WRITE_EXTENDED_INQUIRY_RESPONSE, + OpCodeIndex::REFRESH_ENCRYPTION_KEY, OpCodeIndex::READ_SIMPLE_PAIRING_MODE, + OpCodeIndex::WRITE_SIMPLE_PAIRING_MODE, OpCodeIndex::READ_LOCAL_OOB_DATA, + OpCodeIndex::READ_INQUIRY_RESPONSE_TRANSMIT_POWER_LEVEL, + OpCodeIndex::WRITE_INQUIRY_TRANSMIT_POWER_LEVEL, + // OpCodeIndex::READ_DEFAULT_ERRONEOUS_DATA_REPORTING, + // OpCodeIndex::WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING, + OpCodeIndex::ENHANCED_FLUSH, OpCodeIndex::SEND_KEYPRESS_NOTIFICATION, + OpCodeIndex::SET_EVENT_MASK_PAGE_2, + // OpCodeIndex::READ_FLOW_CONTROL_MODE, + // OpCodeIndex::WRITE_FLOW_CONTROL_MODE, + OpCodeIndex::READ_ENHANCED_TRANSMIT_POWER_LEVEL, OpCodeIndex::READ_LE_HOST_SUPPORT, + OpCodeIndex::WRITE_LE_HOST_SUPPORT, + // OpCodeIndex::SET_MWS_CHANNEL_PARAMETERS, + // OpCodeIndex::SET_EXTERNAL_FRAME_CONFIGURATION, + // OpCodeIndex::SET_MWS_SIGNALING, + // OpCodeIndex::SET_MWS_TRANSPORT_LAYER, + // OpCodeIndex::SET_MWS_SCAN_FREQUENCY_TABLE, + // OpCodeIndex::SET_MWS_PATTERN_CONFIGURATION, + // OpCodeIndex::SET_RESERVED_LT_ADDR, + // OpCodeIndex::DELETE_RESERVED_LT_ADDR, + // OpCodeIndex::SET_CONNECTIONLESS_PERIPHERAL_BROADCAST_DATA, + // OpCodeIndex::READ_SYNCHRONIZATION_TRAIN_PARAMETERS, + // OpCodeIndex::WRITE_SYNCHRONIZATION_TRAIN_PARAMETERS, + OpCodeIndex::READ_SECURE_CONNECTIONS_HOST_SUPPORT, + OpCodeIndex::WRITE_SECURE_CONNECTIONS_HOST_SUPPORT, + OpCodeIndex::READ_AUTHENTICATED_PAYLOAD_TIMEOUT, + OpCodeIndex::WRITE_AUTHENTICATED_PAYLOAD_TIMEOUT, + OpCodeIndex::READ_LOCAL_OOB_EXTENDED_DATA, + // OpCodeIndex::READ_EXTENDED_PAGE_TIMEOUT, + // OpCodeIndex::WRITE_EXTENDED_PAGE_TIMEOUT, + // OpCodeIndex::READ_EXTENDED_INQUIRY_LENGTH, + // OpCodeIndex::WRITE_EXTENDED_INQUIRY_LENGTH, + // OpCodeIndex::SET_ECOSYSTEM_BASE_INTERVAL, + // OpCodeIndex::CONFIGURE_DATA_PATH, + // OpCodeIndex::SET_MIN_ENCRYPTION_KEY_SIZE, - // INFORMATIONAL_PARAMETERS - OpCodeIndex::READ_LOCAL_VERSION_INFORMATION, - OpCodeIndex::READ_LOCAL_SUPPORTED_FEATURES, - OpCodeIndex::READ_LOCAL_EXTENDED_FEATURES, OpCodeIndex::READ_BUFFER_SIZE, - OpCodeIndex::READ_BD_ADDR, - // OpCodeIndex::READ_DATA_BLOCK_SIZE, - OpCodeIndex::READ_LOCAL_SUPPORTED_CODECS_V1, - // OpCodeIndex::READ_LOCAL_SIMPLE_PAIRING_OPTIONS, - // OpCodeIndex::READ_LOCAL_SUPPORTED_CODECS_V2, - // OpCodeIndex::READ_LOCAL_SUPPORTED_CODEC_CAPABILITIES, - // OpCodeIndex::READ_LOCAL_SUPPORTED_CONTROLLER_DELAY, + // INFORMATIONAL_PARAMETERS + OpCodeIndex::READ_LOCAL_VERSION_INFORMATION, OpCodeIndex::READ_LOCAL_SUPPORTED_FEATURES, + OpCodeIndex::READ_LOCAL_EXTENDED_FEATURES, OpCodeIndex::READ_BUFFER_SIZE, + OpCodeIndex::READ_BD_ADDR, + // OpCodeIndex::READ_DATA_BLOCK_SIZE, + OpCodeIndex::READ_LOCAL_SUPPORTED_CODECS_V1, + // OpCodeIndex::READ_LOCAL_SIMPLE_PAIRING_OPTIONS, + // OpCodeIndex::READ_LOCAL_SUPPORTED_CODECS_V2, + // OpCodeIndex::READ_LOCAL_SUPPORTED_CODEC_CAPABILITIES, + // OpCodeIndex::READ_LOCAL_SUPPORTED_CONTROLLER_DELAY, - // STATUS_PARAMETERS - OpCodeIndex::READ_FAILED_CONTACT_COUNTER, - OpCodeIndex::RESET_FAILED_CONTACT_COUNTER, - // OpCodeIndex::READ_LINK_QUALITY, - OpCodeIndex::READ_RSSI, OpCodeIndex::READ_AFH_CHANNEL_MAP, - // OpCodeIndex::READ_CLOCK, - OpCodeIndex::READ_ENCRYPTION_KEY_SIZE, - // OpCodeIndex::GET_MWS_TRANSPORT_LAYER_CONFIGURATION, - // OpCodeIndex::SET_TRIGGERED_CLOCK_CAPTURE, + // STATUS_PARAMETERS + OpCodeIndex::READ_FAILED_CONTACT_COUNTER, OpCodeIndex::RESET_FAILED_CONTACT_COUNTER, + // OpCodeIndex::READ_LINK_QUALITY, + OpCodeIndex::READ_RSSI, OpCodeIndex::READ_AFH_CHANNEL_MAP, + // OpCodeIndex::READ_CLOCK, + OpCodeIndex::READ_ENCRYPTION_KEY_SIZE, + // OpCodeIndex::GET_MWS_TRANSPORT_LAYER_CONFIGURATION, + // OpCodeIndex::SET_TRIGGERED_CLOCK_CAPTURE, - // TESTING - OpCodeIndex::READ_LOOPBACK_MODE, OpCodeIndex::WRITE_LOOPBACK_MODE, - OpCodeIndex::ENABLE_DEVICE_UNDER_TEST_MODE, - OpCodeIndex::WRITE_SIMPLE_PAIRING_DEBUG_MODE, - OpCodeIndex::WRITE_SECURE_CONNECTIONS_TEST_MODE, + // TESTING + OpCodeIndex::READ_LOOPBACK_MODE, OpCodeIndex::WRITE_LOOPBACK_MODE, + OpCodeIndex::ENABLE_DEVICE_UNDER_TEST_MODE, OpCodeIndex::WRITE_SIMPLE_PAIRING_DEBUG_MODE, + OpCodeIndex::WRITE_SECURE_CONNECTIONS_TEST_MODE, - // LE_CONTROLLER - OpCodeIndex::LE_SET_EVENT_MASK, OpCodeIndex::LE_READ_BUFFER_SIZE_V1, - OpCodeIndex::LE_READ_LOCAL_SUPPORTED_FEATURES, - OpCodeIndex::LE_SET_RANDOM_ADDRESS, - OpCodeIndex::LE_SET_ADVERTISING_PARAMETERS, - OpCodeIndex::LE_READ_ADVERTISING_PHYSICAL_CHANNEL_TX_POWER, - OpCodeIndex::LE_SET_ADVERTISING_DATA, - OpCodeIndex::LE_SET_SCAN_RESPONSE_DATA, - OpCodeIndex::LE_SET_ADVERTISING_ENABLE, - OpCodeIndex::LE_SET_SCAN_PARAMETERS, OpCodeIndex::LE_SET_SCAN_ENABLE, - OpCodeIndex::LE_CREATE_CONNECTION, - OpCodeIndex::LE_CREATE_CONNECTION_CANCEL, - OpCodeIndex::LE_READ_FILTER_ACCEPT_LIST_SIZE, - OpCodeIndex::LE_CLEAR_FILTER_ACCEPT_LIST, - OpCodeIndex::LE_ADD_DEVICE_TO_FILTER_ACCEPT_LIST, - OpCodeIndex::LE_REMOVE_DEVICE_FROM_FILTER_ACCEPT_LIST, - OpCodeIndex::LE_CONNECTION_UPDATE, - OpCodeIndex::LE_SET_HOST_CHANNEL_CLASSIFICATION, - OpCodeIndex::LE_READ_CHANNEL_MAP, OpCodeIndex::LE_READ_REMOTE_FEATURES, - OpCodeIndex::LE_ENCRYPT, OpCodeIndex::LE_RAND, - OpCodeIndex::LE_START_ENCRYPTION, - OpCodeIndex::LE_LONG_TERM_KEY_REQUEST_REPLY, - OpCodeIndex::LE_LONG_TERM_KEY_REQUEST_NEGATIVE_REPLY, - OpCodeIndex::LE_READ_SUPPORTED_STATES, OpCodeIndex::LE_RECEIVER_TEST_V1, - OpCodeIndex::LE_TRANSMITTER_TEST_V1, OpCodeIndex::LE_TEST_END, - OpCodeIndex::LE_REMOTE_CONNECTION_PARAMETER_REQUEST_REPLY, - OpCodeIndex::LE_REMOTE_CONNECTION_PARAMETER_REQUEST_NEGATIVE_REPLY, - // OpCodeIndex::LE_SET_DATA_LENGTH, - OpCodeIndex::LE_READ_SUGGESTED_DEFAULT_DATA_LENGTH, - OpCodeIndex::LE_WRITE_SUGGESTED_DEFAULT_DATA_LENGTH, - // OpCodeIndex::LE_READ_LOCAL_P_256_PUBLIC_KEY, - // OpCodeIndex::LE_GENERATE_DHKEY_V1, - OpCodeIndex::LE_ADD_DEVICE_TO_RESOLVING_LIST, - OpCodeIndex::LE_REMOVE_DEVICE_FROM_RESOLVING_LIST, - OpCodeIndex::LE_CLEAR_RESOLVING_LIST, - OpCodeIndex::LE_READ_RESOLVING_LIST_SIZE, - OpCodeIndex::LE_READ_PEER_RESOLVABLE_ADDRESS, - OpCodeIndex::LE_READ_LOCAL_RESOLVABLE_ADDRESS, - OpCodeIndex::LE_SET_ADDRESS_RESOLUTION_ENABLE, - OpCodeIndex::LE_SET_RESOLVABLE_PRIVATE_ADDRESS_TIMEOUT, - OpCodeIndex::LE_READ_MAXIMUM_DATA_LENGTH, OpCodeIndex::LE_READ_PHY, - OpCodeIndex::LE_SET_DEFAULT_PHY, OpCodeIndex::LE_SET_PHY, - // OpCodeIndex::LE_RECEIVER_TEST_V2, - // OpCodeIndex::LE_TRANSMITTER_TEST_V2, - OpCodeIndex::LE_SET_ADVERTISING_SET_RANDOM_ADDRESS, - OpCodeIndex::LE_SET_EXTENDED_ADVERTISING_PARAMETERS, - OpCodeIndex::LE_SET_EXTENDED_ADVERTISING_DATA, - OpCodeIndex::LE_SET_EXTENDED_SCAN_RESPONSE_DATA, - OpCodeIndex::LE_SET_EXTENDED_ADVERTISING_ENABLE, - OpCodeIndex::LE_READ_MAXIMUM_ADVERTISING_DATA_LENGTH, - OpCodeIndex::LE_READ_NUMBER_OF_SUPPORTED_ADVERTISING_SETS, - OpCodeIndex::LE_REMOVE_ADVERTISING_SET, - OpCodeIndex::LE_CLEAR_ADVERTISING_SETS, - OpCodeIndex::LE_SET_PERIODIC_ADVERTISING_PARAMETERS, - OpCodeIndex::LE_SET_PERIODIC_ADVERTISING_DATA, - OpCodeIndex::LE_SET_PERIODIC_ADVERTISING_ENABLE, - OpCodeIndex::LE_SET_EXTENDED_SCAN_PARAMETERS, - OpCodeIndex::LE_SET_EXTENDED_SCAN_ENABLE, - OpCodeIndex::LE_EXTENDED_CREATE_CONNECTION, - OpCodeIndex::LE_PERIODIC_ADVERTISING_CREATE_SYNC, - OpCodeIndex::LE_PERIODIC_ADVERTISING_CREATE_SYNC_CANCEL, - OpCodeIndex::LE_PERIODIC_ADVERTISING_TERMINATE_SYNC, - OpCodeIndex::LE_ADD_DEVICE_TO_PERIODIC_ADVERTISER_LIST, - OpCodeIndex::LE_REMOVE_DEVICE_FROM_PERIODIC_ADVERTISER_LIST, - OpCodeIndex::LE_CLEAR_PERIODIC_ADVERTISER_LIST, - OpCodeIndex::LE_READ_PERIODIC_ADVERTISER_LIST_SIZE, - // OpCodeIndex::LE_READ_TRANSMIT_POWER, - OpCodeIndex::LE_READ_RF_PATH_COMPENSATION_POWER, - OpCodeIndex::LE_WRITE_RF_PATH_COMPENSATION_POWER, - OpCodeIndex::LE_SET_PRIVACY_MODE, - // OpCodeIndex::LE_RECEIVER_TEST_V3, - // OpCodeIndex::LE_TRANSMITTER_TEST_V3, - // OpCodeIndex::LE_SET_CONNECTIONLESS_CTE_TRANSMIT_PARAMETERS, - // OpCodeIndex::LE_SET_CONNECTIONLESS_CTE_TRANSMIT_ENABLE, - // OpCodeIndex::LE_SET_CONNECTIONLESS_IQ_SAMPLING_ENABLE, - // OpCodeIndex::LE_SET_CONNECTION_CTE_RECEIVE_PARAMETERS, - // OpCodeIndex::LE_SET_CONNECTION_CTE_TRANSMIT_PARAMETERS, - // OpCodeIndex::LE_CONNECTION_CTE_REQUEST_ENABLE, - // OpCodeIndex::LE_CONNECTION_CTE_RESPONSE_ENABLE, - // OpCodeIndex::LE_READ_ANTENNA_INFORMATION, - // OpCodeIndex::LE_SET_PERIODIC_ADVERTISING_RECEIVE_ENABLE, - // OpCodeIndex::LE_PERIODIC_ADVERTISING_SYNC_TRANSFER, - // OpCodeIndex::LE_PERIODIC_ADVERTISING_SET_INFO_TRANSFER, - // OpCodeIndex::LE_SET_PERIODIC_ADVERTISING_SYNC_TRANSFER_PARAMETERS, - // OpCodeIndex::LE_SET_DEFAULT_PERIODIC_ADVERTISING_SYNC_TRANSFER_PARAMETERS, - // OpCodeIndex::LE_GENERATE_DHKEY_V2, - // OpCodeIndex::LE_MODIFY_SLEEP_CLOCK_ACCURACY, - OpCodeIndex::LE_READ_BUFFER_SIZE_V2, - // OpCodeIndex::LE_READ_ISO_TX_SYNC, - OpCodeIndex::LE_SET_CIG_PARAMETERS, - OpCodeIndex::LE_SET_CIG_PARAMETERS_TEST, OpCodeIndex::LE_CREATE_CIS, - OpCodeIndex::LE_REMOVE_CIG, OpCodeIndex::LE_ACCEPT_CIS_REQUEST, - OpCodeIndex::LE_REJECT_CIS_REQUEST, - // OpCodeIndex::LE_CREATE_BIG, - // OpCodeIndex::LE_CREATE_BIG_TEST, - // OpCodeIndex::LE_TERMINATE_BIG, - // OpCodeIndex::LE_BIG_CREATE_SYNC, - // OpCodeIndex::LE_BIG_TERMINATE_SYNC, - OpCodeIndex::LE_REQUEST_PEER_SCA, OpCodeIndex::LE_SETUP_ISO_DATA_PATH, - OpCodeIndex::LE_REMOVE_ISO_DATA_PATH, - // OpCodeIndex::LE_ISO_TRANSMIT_TEST, - // OpCodeIndex::LE_ISO_RECEIVE_TEST, - // OpCodeIndex::LE_ISO_READ_TEST_COUNTERS, - // OpCodeIndex::LE_ISO_TEST_END, - OpCodeIndex::LE_SET_HOST_FEATURE, - // OpCodeIndex::LE_READ_ISO_LINK_QUALITY, - // OpCodeIndex::LE_ENHANCED_READ_TRANSMIT_POWER_LEVEL, - // OpCodeIndex::LE_READ_REMOTE_TRANSMIT_POWER_LEVEL, - // OpCodeIndex::LE_SET_PATH_LOSS_REPORTING_PARAMETERS, - // OpCodeIndex::LE_SET_PATH_LOSS_REPORTING_ENABLE, - // OpCodeIndex::LE_SET_TRANSMIT_POWER_REPORTING_ENABLE, - // OpCodeIndex::LE_TRANSMITTER_TEST_V4, - // OpCodeIndex::LE_SET_DATA_RELATED_ADDRESS_CHANGES, - // OpCodeIndex::LE_SET_DEFAULT_SUBRATE, - // OpCodeIndex::LE_SUBRATE_REQUEST, + // LE_CONTROLLER + OpCodeIndex::LE_SET_EVENT_MASK, OpCodeIndex::LE_READ_BUFFER_SIZE_V1, + OpCodeIndex::LE_READ_LOCAL_SUPPORTED_FEATURES, OpCodeIndex::LE_SET_RANDOM_ADDRESS, + OpCodeIndex::LE_SET_ADVERTISING_PARAMETERS, + OpCodeIndex::LE_READ_ADVERTISING_PHYSICAL_CHANNEL_TX_POWER, + OpCodeIndex::LE_SET_ADVERTISING_DATA, OpCodeIndex::LE_SET_SCAN_RESPONSE_DATA, + OpCodeIndex::LE_SET_ADVERTISING_ENABLE, OpCodeIndex::LE_SET_SCAN_PARAMETERS, + OpCodeIndex::LE_SET_SCAN_ENABLE, OpCodeIndex::LE_CREATE_CONNECTION, + OpCodeIndex::LE_CREATE_CONNECTION_CANCEL, OpCodeIndex::LE_READ_FILTER_ACCEPT_LIST_SIZE, + OpCodeIndex::LE_CLEAR_FILTER_ACCEPT_LIST, + OpCodeIndex::LE_ADD_DEVICE_TO_FILTER_ACCEPT_LIST, + OpCodeIndex::LE_REMOVE_DEVICE_FROM_FILTER_ACCEPT_LIST, OpCodeIndex::LE_CONNECTION_UPDATE, + OpCodeIndex::LE_SET_HOST_CHANNEL_CLASSIFICATION, OpCodeIndex::LE_READ_CHANNEL_MAP, + OpCodeIndex::LE_READ_REMOTE_FEATURES, OpCodeIndex::LE_ENCRYPT, OpCodeIndex::LE_RAND, + OpCodeIndex::LE_START_ENCRYPTION, OpCodeIndex::LE_LONG_TERM_KEY_REQUEST_REPLY, + OpCodeIndex::LE_LONG_TERM_KEY_REQUEST_NEGATIVE_REPLY, + OpCodeIndex::LE_READ_SUPPORTED_STATES, OpCodeIndex::LE_RECEIVER_TEST_V1, + OpCodeIndex::LE_TRANSMITTER_TEST_V1, OpCodeIndex::LE_TEST_END, + OpCodeIndex::LE_REMOTE_CONNECTION_PARAMETER_REQUEST_REPLY, + OpCodeIndex::LE_REMOTE_CONNECTION_PARAMETER_REQUEST_NEGATIVE_REPLY, + // OpCodeIndex::LE_SET_DATA_LENGTH, + OpCodeIndex::LE_READ_SUGGESTED_DEFAULT_DATA_LENGTH, + OpCodeIndex::LE_WRITE_SUGGESTED_DEFAULT_DATA_LENGTH, + // OpCodeIndex::LE_READ_LOCAL_P_256_PUBLIC_KEY, + // OpCodeIndex::LE_GENERATE_DHKEY_V1, + OpCodeIndex::LE_ADD_DEVICE_TO_RESOLVING_LIST, + OpCodeIndex::LE_REMOVE_DEVICE_FROM_RESOLVING_LIST, OpCodeIndex::LE_CLEAR_RESOLVING_LIST, + OpCodeIndex::LE_READ_RESOLVING_LIST_SIZE, OpCodeIndex::LE_READ_PEER_RESOLVABLE_ADDRESS, + OpCodeIndex::LE_READ_LOCAL_RESOLVABLE_ADDRESS, + OpCodeIndex::LE_SET_ADDRESS_RESOLUTION_ENABLE, + OpCodeIndex::LE_SET_RESOLVABLE_PRIVATE_ADDRESS_TIMEOUT, + OpCodeIndex::LE_READ_MAXIMUM_DATA_LENGTH, OpCodeIndex::LE_READ_PHY, + OpCodeIndex::LE_SET_DEFAULT_PHY, OpCodeIndex::LE_SET_PHY, + // OpCodeIndex::LE_RECEIVER_TEST_V2, + // OpCodeIndex::LE_TRANSMITTER_TEST_V2, + OpCodeIndex::LE_SET_ADVERTISING_SET_RANDOM_ADDRESS, + OpCodeIndex::LE_SET_EXTENDED_ADVERTISING_PARAMETERS, + OpCodeIndex::LE_SET_EXTENDED_ADVERTISING_DATA, + OpCodeIndex::LE_SET_EXTENDED_SCAN_RESPONSE_DATA, + OpCodeIndex::LE_SET_EXTENDED_ADVERTISING_ENABLE, + OpCodeIndex::LE_READ_MAXIMUM_ADVERTISING_DATA_LENGTH, + OpCodeIndex::LE_READ_NUMBER_OF_SUPPORTED_ADVERTISING_SETS, + OpCodeIndex::LE_REMOVE_ADVERTISING_SET, OpCodeIndex::LE_CLEAR_ADVERTISING_SETS, + OpCodeIndex::LE_SET_PERIODIC_ADVERTISING_PARAMETERS, + OpCodeIndex::LE_SET_PERIODIC_ADVERTISING_DATA, + OpCodeIndex::LE_SET_PERIODIC_ADVERTISING_ENABLE, + OpCodeIndex::LE_SET_EXTENDED_SCAN_PARAMETERS, OpCodeIndex::LE_SET_EXTENDED_SCAN_ENABLE, + OpCodeIndex::LE_EXTENDED_CREATE_CONNECTION, + OpCodeIndex::LE_PERIODIC_ADVERTISING_CREATE_SYNC, + OpCodeIndex::LE_PERIODIC_ADVERTISING_CREATE_SYNC_CANCEL, + OpCodeIndex::LE_PERIODIC_ADVERTISING_TERMINATE_SYNC, + OpCodeIndex::LE_ADD_DEVICE_TO_PERIODIC_ADVERTISER_LIST, + OpCodeIndex::LE_REMOVE_DEVICE_FROM_PERIODIC_ADVERTISER_LIST, + OpCodeIndex::LE_CLEAR_PERIODIC_ADVERTISER_LIST, + OpCodeIndex::LE_READ_PERIODIC_ADVERTISER_LIST_SIZE, + // OpCodeIndex::LE_READ_TRANSMIT_POWER, + OpCodeIndex::LE_READ_RF_PATH_COMPENSATION_POWER, + OpCodeIndex::LE_WRITE_RF_PATH_COMPENSATION_POWER, OpCodeIndex::LE_SET_PRIVACY_MODE, + // OpCodeIndex::LE_RECEIVER_TEST_V3, + // OpCodeIndex::LE_TRANSMITTER_TEST_V3, + // OpCodeIndex::LE_SET_CONNECTIONLESS_CTE_TRANSMIT_PARAMETERS, + // OpCodeIndex::LE_SET_CONNECTIONLESS_CTE_TRANSMIT_ENABLE, + // OpCodeIndex::LE_SET_CONNECTIONLESS_IQ_SAMPLING_ENABLE, + // OpCodeIndex::LE_SET_CONNECTION_CTE_RECEIVE_PARAMETERS, + // OpCodeIndex::LE_SET_CONNECTION_CTE_TRANSMIT_PARAMETERS, + // OpCodeIndex::LE_CONNECTION_CTE_REQUEST_ENABLE, + // OpCodeIndex::LE_CONNECTION_CTE_RESPONSE_ENABLE, + // OpCodeIndex::LE_READ_ANTENNA_INFORMATION, + // OpCodeIndex::LE_SET_PERIODIC_ADVERTISING_RECEIVE_ENABLE, + // OpCodeIndex::LE_PERIODIC_ADVERTISING_SYNC_TRANSFER, + // OpCodeIndex::LE_PERIODIC_ADVERTISING_SET_INFO_TRANSFER, + // OpCodeIndex::LE_SET_PERIODIC_ADVERTISING_SYNC_TRANSFER_PARAMETERS, + // OpCodeIndex::LE_SET_DEFAULT_PERIODIC_ADVERTISING_SYNC_TRANSFER_PARAMETERS, + // OpCodeIndex::LE_GENERATE_DHKEY_V2, + // OpCodeIndex::LE_MODIFY_SLEEP_CLOCK_ACCURACY, + OpCodeIndex::LE_READ_BUFFER_SIZE_V2, + // OpCodeIndex::LE_READ_ISO_TX_SYNC, + OpCodeIndex::LE_SET_CIG_PARAMETERS, OpCodeIndex::LE_SET_CIG_PARAMETERS_TEST, + OpCodeIndex::LE_CREATE_CIS, OpCodeIndex::LE_REMOVE_CIG, + OpCodeIndex::LE_ACCEPT_CIS_REQUEST, OpCodeIndex::LE_REJECT_CIS_REQUEST, + // OpCodeIndex::LE_CREATE_BIG, + // OpCodeIndex::LE_CREATE_BIG_TEST, + // OpCodeIndex::LE_TERMINATE_BIG, + // OpCodeIndex::LE_BIG_CREATE_SYNC, + // OpCodeIndex::LE_BIG_TERMINATE_SYNC, + OpCodeIndex::LE_REQUEST_PEER_SCA, OpCodeIndex::LE_SETUP_ISO_DATA_PATH, + OpCodeIndex::LE_REMOVE_ISO_DATA_PATH, + // OpCodeIndex::LE_ISO_TRANSMIT_TEST, + // OpCodeIndex::LE_ISO_RECEIVE_TEST, + // OpCodeIndex::LE_ISO_READ_TEST_COUNTERS, + // OpCodeIndex::LE_ISO_TEST_END, + OpCodeIndex::LE_SET_HOST_FEATURE, + // OpCodeIndex::LE_READ_ISO_LINK_QUALITY, + // OpCodeIndex::LE_ENHANCED_READ_TRANSMIT_POWER_LEVEL, + // OpCodeIndex::LE_READ_REMOTE_TRANSMIT_POWER_LEVEL, + // OpCodeIndex::LE_SET_PATH_LOSS_REPORTING_PARAMETERS, + // OpCodeIndex::LE_SET_PATH_LOSS_REPORTING_ENABLE, + // OpCodeIndex::LE_SET_TRANSMIT_POWER_REPORTING_ENABLE, + // OpCodeIndex::LE_TRANSMITTER_TEST_V4, + // OpCodeIndex::LE_SET_DATA_RELATED_ADDRESS_CHANGES, + // OpCodeIndex::LE_SET_DEFAULT_SUBRATE, + // OpCodeIndex::LE_SUBRATE_REQUEST, }; std::array value{}; @@ -480,20 +440,16 @@ bool ControllerProperties::CheckSupportedFeatures() const { } if ((lmp_page_0_reserved_bits & lmp_features[0]) != 0) { - INFO( - "The page 0 feature bits 0x{:016x}" - " are reserved in the specification {}", - lmp_page_0_reserved_bits & lmp_features[0], - LmpVersionText(lmp_version)); + INFO("The page 0 feature bits 0x{:016x}" + " are reserved in the specification {}", + lmp_page_0_reserved_bits & lmp_features[0], LmpVersionText(lmp_version)); return false; } if ((lmp_page_2_reserved_bits & lmp_features[2]) != 0) { - INFO( - "The page 2 feature bits 0x{:016x}" - " are reserved in the specification {}", - lmp_page_2_reserved_bits & lmp_features[2], - LmpVersionText(lmp_version)); + INFO("The page 2 feature bits 0x{:016x}" + " are reserved in the specification {}", + lmp_page_2_reserved_bits & lmp_features[2], LmpVersionText(lmp_version)); return false; } @@ -508,8 +464,7 @@ bool ControllerProperties::CheckSupportedFeatures() const { // The features listed in Table 3.5 are mandatory in this version of the // specification (see Section 3.1) and these feature bits shall be set. if (!SupportsLMPFeature(LMPFeaturesPage0Bits::ENCRYPTION) || - !SupportsLMPFeature( - LMPFeaturesPage0Bits::SECURE_SIMPLE_PAIRING_CONTROLLER) || + !SupportsLMPFeature(LMPFeaturesPage0Bits::SECURE_SIMPLE_PAIRING_CONTROLLER) || !SupportsLMPFeature(LMPFeaturesPage0Bits::ENCAPSULATED_PDU)) { INFO("Table 3.5 validation failed"); return false; @@ -579,13 +534,10 @@ bool ControllerProperties::CheckSupportedFeatures() const { INFO("Table 3.9 validation failed; expected Sco Link or Extended Sco Link"); return false; } - if (SupportsLMPFeature( - LMPFeaturesPage0Bits::ENHANCED_DATA_RATE_ACL_3_MB_S_MODE) && - !SupportsLMPFeature( - LMPFeaturesPage0Bits::ENHANCED_DATA_RATE_ACL_2_MB_S_MODE)) { - INFO( - "Table 3.9 validation failed; expected Enhanced Data Rate ACL 2Mb/s " - "mode"); + if (SupportsLMPFeature(LMPFeaturesPage0Bits::ENHANCED_DATA_RATE_ACL_3_MB_S_MODE) && + !SupportsLMPFeature(LMPFeaturesPage0Bits::ENHANCED_DATA_RATE_ACL_2_MB_S_MODE)) { + INFO("Table 3.9 validation failed; expected Enhanced Data Rate ACL 2Mb/s " + "mode"); return false; } if (SupportsLMPFeature(LMPFeaturesPage0Bits::EV4_PACKETS) && @@ -603,22 +555,16 @@ bool ControllerProperties::CheckSupportedFeatures() const { INFO("Table 3.9 validation failed; expected AFH Capable Peripheral"); return false; } - if (SupportsLMPFeature( - LMPFeaturesPage0Bits::LMP_3_SLOT_ENHANCED_DATA_RATE_ACL_PACKETS) && - !SupportsLMPFeature( - LMPFeaturesPage0Bits::ENHANCED_DATA_RATE_ACL_2_MB_S_MODE)) { - INFO( - "Table 3.9 validation failed; expected Enhanced Data Rate ACL 2Mb/s " - "mode"); + if (SupportsLMPFeature(LMPFeaturesPage0Bits::LMP_3_SLOT_ENHANCED_DATA_RATE_ACL_PACKETS) && + !SupportsLMPFeature(LMPFeaturesPage0Bits::ENHANCED_DATA_RATE_ACL_2_MB_S_MODE)) { + INFO("Table 3.9 validation failed; expected Enhanced Data Rate ACL 2Mb/s " + "mode"); return false; } - if (SupportsLMPFeature( - LMPFeaturesPage0Bits::LMP_5_SLOT_ENHANCED_DATA_RATE_ACL_PACKETS) && - !SupportsLMPFeature( - LMPFeaturesPage0Bits::ENHANCED_DATA_RATE_ACL_2_MB_S_MODE)) { - INFO( - "Table 3.9 validation failed; expected Enhanced Data Rate ACL 2Mb/s " - "mode"); + if (SupportsLMPFeature(LMPFeaturesPage0Bits::LMP_5_SLOT_ENHANCED_DATA_RATE_ACL_PACKETS) && + !SupportsLMPFeature(LMPFeaturesPage0Bits::ENHANCED_DATA_RATE_ACL_2_MB_S_MODE)) { + INFO("Table 3.9 validation failed; expected Enhanced Data Rate ACL 2Mb/s " + "mode"); return false; } if (SupportsLMPFeature(LMPFeaturesPage0Bits::AFH_CLASSIFICATION_CENTRAL) && @@ -626,28 +572,21 @@ bool ControllerProperties::CheckSupportedFeatures() const { INFO("Table 3.9 validation failed; expected AFH Capable Central"); return false; } - if (SupportsLMPFeature( - LMPFeaturesPage0Bits::ENHANCED_DATA_RATE_ESCO_2_MB_S_MODE) && + if (SupportsLMPFeature(LMPFeaturesPage0Bits::ENHANCED_DATA_RATE_ESCO_2_MB_S_MODE) && !SupportsLMPFeature(LMPFeaturesPage0Bits::EXTENDED_SCO_LINK)) { INFO("Table 3.9 validation failed; expected Extended Sco Link"); return false; } - if (SupportsLMPFeature( - LMPFeaturesPage0Bits::ENHANCED_DATA_RATE_ESCO_3_MB_S_MODE) && - !SupportsLMPFeature( - LMPFeaturesPage0Bits::ENHANCED_DATA_RATE_ESCO_2_MB_S_MODE)) { - INFO( - "Table 3.9 validation failed; expected Enhanced Data Rate eSCO 2Mb/s " - "mode"); + if (SupportsLMPFeature(LMPFeaturesPage0Bits::ENHANCED_DATA_RATE_ESCO_3_MB_S_MODE) && + !SupportsLMPFeature(LMPFeaturesPage0Bits::ENHANCED_DATA_RATE_ESCO_2_MB_S_MODE)) { + INFO("Table 3.9 validation failed; expected Enhanced Data Rate eSCO 2Mb/s " + "mode"); return false; } - if (SupportsLMPFeature( - LMPFeaturesPage0Bits::LMP_3_SLOT_ENHANCED_DATA_RATE_ESCO_PACKETS) && - !SupportsLMPFeature( - LMPFeaturesPage0Bits::ENHANCED_DATA_RATE_ESCO_2_MB_S_MODE)) { - INFO( - "Table 3.9 validation failed; expected Enhanced Data Rate eSCO 2Mb/s " - "mode"); + if (SupportsLMPFeature(LMPFeaturesPage0Bits::LMP_3_SLOT_ENHANCED_DATA_RATE_ESCO_PACKETS) && + !SupportsLMPFeature(LMPFeaturesPage0Bits::ENHANCED_DATA_RATE_ESCO_2_MB_S_MODE)) { + INFO("Table 3.9 validation failed; expected Enhanced Data Rate eSCO 2Mb/s " + "mode"); return false; } if (SupportsLMPFeature(LMPFeaturesPage0Bits::EXTENDED_INQUIRY_RESPONSE) && @@ -655,8 +594,7 @@ bool ControllerProperties::CheckSupportedFeatures() const { INFO("Table 3.9 validation failed; expected RSSI with Inquiry Results"); return false; } - if (SupportsLMPFeature( - LMPFeaturesPage0Bits::SIMULTANEOUS_LE_AND_BR_CONTROLLER) && + if (SupportsLMPFeature(LMPFeaturesPage0Bits::SIMULTANEOUS_LE_AND_BR_CONTROLLER) && !SupportsLMPFeature(LMPFeaturesPage0Bits::LE_SUPPORTED_CONTROLLER)) { INFO("Table 3.9 validation failed; expected LE Supported (Controller)"); return false; @@ -670,21 +608,18 @@ bool ControllerProperties::CheckSupportedFeatures() const { if (SupportsLMPFeature(LMPFeaturesPage0Bits::ENHANCED_POWER_CONTROL) && (!SupportsLMPFeature(LMPFeaturesPage0Bits::POWER_CONTROL_REQUESTS) || !SupportsLMPFeature(LMPFeaturesPage0Bits::POWER_CONTROL))) { - INFO( - "Table 3.9 validation failed; expected Power Control Request and Power " - "Control"); + INFO("Table 3.9 validation failed; expected Power Control Request and Power " + "Control"); return false; } if (SupportsLMPFeature( - LMPFeaturesPage2Bits:: - CONNECTIONLESS_PERIPHERAL_BROADCAST_TRANSMITTER_OPERATION) && + LMPFeaturesPage2Bits::CONNECTIONLESS_PERIPHERAL_BROADCAST_TRANSMITTER_OPERATION) && !SupportsLMPFeature(LMPFeaturesPage2Bits::SYNCHRONIZATION_TRAIN)) { INFO("Table 3.9 validation failed; expected Synchronization Train"); return false; } if (SupportsLMPFeature( - LMPFeaturesPage2Bits:: - CONNECTIONLESS_PERIPHERAL_BROADCAST_RECEIVER_OPERATION) && + LMPFeaturesPage2Bits::CONNECTIONLESS_PERIPHERAL_BROADCAST_RECEIVER_OPERATION) && !SupportsLMPFeature(LMPFeaturesPage2Bits::SYNCHRONIZATION_SCAN)) { INFO("Table 3.9 validation failed; expected Synchronization Scan"); return false; @@ -692,9 +627,8 @@ bool ControllerProperties::CheckSupportedFeatures() const { if (SupportsLMPFeature(LMPFeaturesPage2Bits::GENERALIZED_INTERLACED_SCAN) && !SupportsLMPFeature(LMPFeaturesPage0Bits::INTERLACED_INQUIRY_SCAN) && !SupportsLMPFeature(LMPFeaturesPage0Bits::INTERLACED_PAGE_SCAN)) { - INFO( - "Table 3.9 validation failed; expected Interlaced Inquiry Scan or " - "Interlaced Page Scan"); + INFO("Table 3.9 validation failed; expected Interlaced Inquiry Scan or " + "Interlaced Page Scan"); return false; } if (SupportsLMPFeature(LMPFeaturesPage2Bits::COARSE_CLOCK_ADJUSTMENT) && @@ -702,13 +636,11 @@ bool ControllerProperties::CheckSupportedFeatures() const { !SupportsLMPFeature(LMPFeaturesPage0Bits::AFH_CAPABLE_CENTRAL) || !SupportsLMPFeature(LMPFeaturesPage2Bits::SYNCHRONIZATION_TRAIN) || !SupportsLMPFeature(LMPFeaturesPage2Bits::SYNCHRONIZATION_SCAN))) { - INFO( - "Table 3.9 validation failed; expected AFH Capable Central/Peripheral " - "and Synchronization Train/Scan"); + INFO("Table 3.9 validation failed; expected AFH Capable Central/Peripheral " + "and Synchronization Train/Scan"); return false; } - if (SupportsLMPFeature( - LMPFeaturesPage2Bits::SECURE_CONNECTIONS_CONTROLLER_SUPPORT) && + if (SupportsLMPFeature(LMPFeaturesPage2Bits::SECURE_CONNECTIONS_CONTROLLER_SUPPORT) && (!SupportsLMPFeature(LMPFeaturesPage0Bits::PAUSE_ENCRYPTION) || !SupportsLMPFeature(LMPFeaturesPage2Bits::PING))) { INFO("Table 3.9 validation failed; expected Pause Encryption and Ping"); @@ -759,15 +691,9 @@ bool ControllerProperties::CheckSupportedCommands() const { constexpr auto mandatory = kMandatory; constexpr auto optional = kOptional; constexpr auto excluded = kExcluded; - auto mandatory_or_excluded = [](bool cond) { - return cond ? kMandatory : kExcluded; - }; - auto mandatory_or_optional = [](bool cond) { - return cond ? kMandatory : kOptional; - }; - auto optional_or_excluded = [](bool cond) { - return cond ? kMandatory : kExcluded; - }; + auto mandatory_or_excluded = [](bool cond) { return cond ? kMandatory : kExcluded; }; + auto mandatory_or_optional = [](bool cond) { return cond ? kMandatory : kOptional; }; + auto optional_or_excluded = [](bool cond) { return cond ? kMandatory : kExcluded; }; auto mandatory_or_optional_or_excluded = [](bool cond1, bool cond2) { return cond1 ? kMandatory : cond2 ? kOptional : kExcluded; }; @@ -778,26 +704,24 @@ bool ControllerProperties::CheckSupportedCommands() const { // or event if it is shown as optional for at least one of the transports // that the Controller supports, otherwise it shall not support the // command or event. - auto check_command_requirement = - [](bool br_supported, Requirement br_requirement, bool le_supported, - Requirement le_requirement, bool command_supported) { - Requirement command_requirement = - !br_supported ? le_requirement - : !le_supported ? br_requirement - : le_requirement == kMandatory || br_requirement == kMandatory - ? kMandatory - : le_requirement == kOptional || br_requirement == kOptional - ? kOptional - : kExcluded; + auto check_command_requirement = [](bool br_supported, Requirement br_requirement, + bool le_supported, Requirement le_requirement, + bool command_supported) { + Requirement command_requirement = + !br_supported ? le_requirement + : !le_supported ? br_requirement + : le_requirement == kMandatory || br_requirement == kMandatory ? kMandatory + : le_requirement == kOptional || br_requirement == kOptional ? kOptional + : kExcluded; - if (command_requirement == kMandatory && !command_supported) { - return false; - } - if (command_requirement == kExcluded && command_supported) { - return false; - } - return true; - }; + if (command_requirement == kMandatory && !command_supported) { + return false; + } + if (command_requirement == kExcluded && command_supported) { + return false; + } + return true; + }; // C1: Mandatory if the LE Controller supports transmitting packets, otherwise // excluded. @@ -810,76 +734,65 @@ bool ControllerProperties::CheckSupportedCommands() const { auto c3 = mandatory; // C4: Mandatory if LE Feature (LE Encryption) is supported, otherwise // excluded. - auto c4 = - mandatory_or_excluded(SupportsLLFeature(LLFeaturesBits::LE_ENCRYPTION)); + auto c4 = mandatory_or_excluded(SupportsLLFeature(LLFeaturesBits::LE_ENCRYPTION)); // C6: Mandatory if LE Feature (Connection Parameters Request procedure) is // supported, otherwise excluded. - auto c6 = mandatory_or_excluded(SupportsLLFeature( - LLFeaturesBits::CONNECTION_PARAMETERS_REQUEST_PROCEDURE)); + auto c6 = mandatory_or_excluded( + SupportsLLFeature(LLFeaturesBits::CONNECTION_PARAMETERS_REQUEST_PROCEDURE)); // C7: Mandatory if LE Feature (LE Encryption) and LE Feature (LE Ping) are // supported, otherwise excluded. - auto c7 = - mandatory_or_excluded(SupportsLLFeature(LLFeaturesBits::LE_ENCRYPTION) && - SupportsLLFeature(LLFeaturesBits::LE_PING)); + auto c7 = mandatory_or_excluded(SupportsLLFeature(LLFeaturesBits::LE_ENCRYPTION) && + SupportsLLFeature(LLFeaturesBits::LE_PING)); // C8: Mandatory if LE Feature (LE Data Packet Length Extension) is supported, // otherwise optional. - auto c8 = mandatory_or_optional( - SupportsLLFeature(LLFeaturesBits::LE_DATA_PACKET_LENGTH_EXTENSION)); + auto c8 = + mandatory_or_optional(SupportsLLFeature(LLFeaturesBits::LE_DATA_PACKET_LENGTH_EXTENSION)); // C9: Mandatory if LE Feature (LL Privacy) is supported, otherwise excluded. - auto c9 = - mandatory_or_excluded(SupportsLLFeature(LLFeaturesBits::LL_PRIVACY)); + auto c9 = mandatory_or_excluded(SupportsLLFeature(LLFeaturesBits::LL_PRIVACY)); // C10: Optional if LE Feature (LL Privacy) is supported, otherwise excluded. - auto c10 = - optional_or_excluded(SupportsLLFeature(LLFeaturesBits::LL_PRIVACY)); + auto c10 = optional_or_excluded(SupportsLLFeature(LLFeaturesBits::LL_PRIVACY)); // C11: Mandatory if LE Feature (LE 2M PHY) or LE Feature (LE Coded PHY) is // supported, otherwise optional. - auto c11 = - mandatory_or_optional(SupportsLLFeature(LLFeaturesBits::LE_2M_PHY) || - SupportsLLFeature(LLFeaturesBits::LE_CODED_PHY)); + auto c11 = mandatory_or_optional(SupportsLLFeature(LLFeaturesBits::LE_2M_PHY) || + SupportsLLFeature(LLFeaturesBits::LE_CODED_PHY)); // C12: Mandatory if LE Feature (LE 2M PHY) or LE Feature (LE Coded PHY) or // LE Feature (Stable Modulation Index - Transmitter) is supported, otherwise // optional if the LE Controller supports transmitting packets, otherwise // excluded. auto c12 = mandatory_or_excluded( - SupportsLLFeature(LLFeaturesBits::LE_2M_PHY) || - SupportsLLFeature(LLFeaturesBits::LE_CODED_PHY) || - SupportsLLFeature(LLFeaturesBits::STABLE_MODULATION_INDEX_TRANSMITTER)); + SupportsLLFeature(LLFeaturesBits::LE_2M_PHY) || + SupportsLLFeature(LLFeaturesBits::LE_CODED_PHY) || + SupportsLLFeature(LLFeaturesBits::STABLE_MODULATION_INDEX_TRANSMITTER)); // C13: Mandatory if LE Feature (LE 2M PHY) or LE Feature (LE Coded PHY) or LE // Feature (Stable Modulation Index - Receiver) is supported, otherwise // optional if the LE Controller supports receiving packets, otherwise // excluded. auto c13 = mandatory_or_excluded( - SupportsLLFeature(LLFeaturesBits::LE_2M_PHY) || - SupportsLLFeature(LLFeaturesBits::LE_CODED_PHY) || - SupportsLLFeature(LLFeaturesBits::STABLE_MODULATION_INDEX_RECEIVER)); + SupportsLLFeature(LLFeaturesBits::LE_2M_PHY) || + SupportsLLFeature(LLFeaturesBits::LE_CODED_PHY) || + SupportsLLFeature(LLFeaturesBits::STABLE_MODULATION_INDEX_RECEIVER)); // C15: Mandatory if LE Controller supports transmitting scannable // advertisements, otherwise excluded. auto c15 = mandatory; // C16: Mandatory if LE Feature (Periodic Advertising) is supported and the LE // Controller supports both Scanning State and Synchronization State, // otherwise excluded. - auto c16 = mandatory_or_excluded( - SupportsLLFeature(LLFeaturesBits::LE_PERIODIC_ADVERTISING)); + auto c16 = mandatory_or_excluded(SupportsLLFeature(LLFeaturesBits::LE_PERIODIC_ADVERTISING)); // C17: Mandatory if LE Feature (Extended Advertising) is supported and the LE // Controller supports Advertising State, otherwise excluded. - auto c17 = mandatory_or_excluded( - SupportsLLFeature(LLFeaturesBits::LE_EXTENDED_ADVERTISING)); + auto c17 = mandatory_or_excluded(SupportsLLFeature(LLFeaturesBits::LE_EXTENDED_ADVERTISING)); // C18: Mandatory if LE Feature (Periodic Advertising) is supported and the LE // Controller supports Advertising State, otherwise excluded. - auto c18 = mandatory_or_excluded( - SupportsLLFeature(LLFeaturesBits::LE_PERIODIC_ADVERTISING)); + auto c18 = mandatory_or_excluded(SupportsLLFeature(LLFeaturesBits::LE_PERIODIC_ADVERTISING)); // C19: Mandatory if LE Feature (Extended Advertising) is supported and the LE // Controller supports Scanning State, otherwise excluded. - auto c19 = mandatory_or_excluded( - SupportsLLFeature(LLFeaturesBits::LE_EXTENDED_ADVERTISING)); + auto c19 = mandatory_or_excluded(SupportsLLFeature(LLFeaturesBits::LE_EXTENDED_ADVERTISING)); // C20: Mandatory if LE Feature (Extended Advertising) is supported and the LE // Controller supports Initiating State, otherwise excluded. - auto c20 = mandatory_or_excluded( - SupportsLLFeature(LLFeaturesBits::LE_EXTENDED_ADVERTISING)); + auto c20 = mandatory_or_excluded(SupportsLLFeature(LLFeaturesBits::LE_EXTENDED_ADVERTISING)); // C21: Mandatory if LE Feature (Periodic Advertising) is supported and the LE // Controller supports Synchronization State, otherwise excluded. - auto c21 = mandatory_or_excluded( - SupportsLLFeature(LLFeaturesBits::LE_PERIODIC_ADVERTISING)); + auto c21 = mandatory_or_excluded(SupportsLLFeature(LLFeaturesBits::LE_PERIODIC_ADVERTISING)); // C22: Mandatory if the LE Controller supports sending Transmit Power in // advertisements or if LE Feature (LE Power Control Request) is supported, // otherwise optional. @@ -894,62 +807,57 @@ bool ControllerProperties::CheckSupportedCommands() const { // // C25: Mandatory if LE Feature // (Connection CTE Request) is supported, otherwise excluded. - auto c25 = mandatory_or_excluded( - SupportsLLFeature(LLFeaturesBits::CONNECTION_CTE_REQUEST)); + auto c25 = mandatory_or_excluded(SupportsLLFeature(LLFeaturesBits::CONNECTION_CTE_REQUEST)); // C26: Mandatory if LE Feature (Connection CTE Response) is supported, // otherwise excluded. - auto c26 = mandatory_or_excluded( - SupportsLLFeature(LLFeaturesBits::CONNECTION_CTE_RESPONSE)); + auto c26 = mandatory_or_excluded(SupportsLLFeature(LLFeaturesBits::CONNECTION_CTE_RESPONSE)); // C27: Mandatory if LE Feature (Connectionless CTE Transmitter) is supported, // otherwise excluded. - auto c27 = mandatory_or_excluded( - SupportsLLFeature(LLFeaturesBits::CONNECTIONLESS_CTE_TRANSMITTER)); + auto c27 = + mandatory_or_excluded(SupportsLLFeature(LLFeaturesBits::CONNECTIONLESS_CTE_TRANSMITTER)); // C28: Mandatory if LE Feature (Connectionless CTE Receiver) is supported, // otherwise excluded. - auto c28 = mandatory_or_excluded( - SupportsLLFeature(LLFeaturesBits::CONNECTIONLESS_CTE_RECEIVER)); + auto c28 = mandatory_or_excluded(SupportsLLFeature(LLFeaturesBits::CONNECTIONLESS_CTE_RECEIVER)); // C29: Mandatory if LE Feature (Connection CTE Response) or LE Feature // (Connectionless CTE Transmitter) is supported, otherwise optional if the LE // Controller supports transmitting packets, otherwise excluded. - auto c29 = mandatory_or_optional( - SupportsLLFeature(LLFeaturesBits::CONNECTION_CTE_RESPONSE) || - SupportsLLFeature(LLFeaturesBits::CONNECTIONLESS_CTE_TRANSMITTER)); + auto c29 = + mandatory_or_optional(SupportsLLFeature(LLFeaturesBits::CONNECTION_CTE_RESPONSE) || + SupportsLLFeature(LLFeaturesBits::CONNECTIONLESS_CTE_TRANSMITTER)); // C30: Mandatory if LE Feature (Connection CTE Request) or LE Feature // (Connectionless CTE Receiver) is supported, otherwise optional if the LE // Controller supports receiving packets, otherwise excluded. - auto c30 = mandatory_or_optional( - SupportsLLFeature(LLFeaturesBits::CONNECTION_CTE_REQUEST) || - SupportsLLFeature(LLFeaturesBits::CONNECTIONLESS_CTE_RECEIVER)); + auto c30 = mandatory_or_optional(SupportsLLFeature(LLFeaturesBits::CONNECTION_CTE_REQUEST) || + SupportsLLFeature(LLFeaturesBits::CONNECTIONLESS_CTE_RECEIVER)); // C31: Mandatory if LE Feature (Connection CTE Request) or LE Feature // (Connection CTE Response) or LE Feature (Connectionless CTE Transmitter) or // LE Feature (Connectionless CTE Receiver) is supported, otherwise excluded. - auto c31 = mandatory_or_excluded( - SupportsLLFeature(LLFeaturesBits::CONNECTION_CTE_REQUEST) || - SupportsLLFeature(LLFeaturesBits::CONNECTION_CTE_RESPONSE) || - SupportsLLFeature(LLFeaturesBits::CONNECTIONLESS_CTE_TRANSMITTER) || - SupportsLLFeature(LLFeaturesBits::CONNECTIONLESS_CTE_RECEIVER)); + auto c31 = + mandatory_or_excluded(SupportsLLFeature(LLFeaturesBits::CONNECTION_CTE_REQUEST) || + SupportsLLFeature(LLFeaturesBits::CONNECTION_CTE_RESPONSE) || + SupportsLLFeature(LLFeaturesBits::CONNECTIONLESS_CTE_TRANSMITTER) || + SupportsLLFeature(LLFeaturesBits::CONNECTIONLESS_CTE_RECEIVER)); // C32: Mandatory if LE Feature (Periodic Advertising Sync Transfer – // Recipient) is supported, otherwise optional if LE Feature (Periodic // Advertising) is supported and the LE Controller supports Synchronization // State, otherwise excluded. auto c32 = mandatory_or_optional_or_excluded( - SupportsLLFeature( - LLFeaturesBits::PERIODIC_ADVERTISING_SYNC_TRANSFER_RECIPIENT), - SupportsLLFeature(LLFeaturesBits::LE_PERIODIC_ADVERTISING)); + SupportsLLFeature(LLFeaturesBits::PERIODIC_ADVERTISING_SYNC_TRANSFER_RECIPIENT), + SupportsLLFeature(LLFeaturesBits::LE_PERIODIC_ADVERTISING)); // C33: Mandatory if LE Feature (Periodic Advertising Sync Transfer – Sender) // is supported and the LE Controller supports Scanning State, otherwise // excluded. - auto c33 = mandatory_or_excluded(SupportsLLFeature( - LLFeaturesBits::PERIODIC_ADVERTISING_SYNC_TRANSFER_SENDER)); + auto c33 = mandatory_or_excluded( + SupportsLLFeature(LLFeaturesBits::PERIODIC_ADVERTISING_SYNC_TRANSFER_SENDER)); // C34: Mandatory if LE Feature (Periodic Advertising Sync Transfer – Sender) // is supported and the LE Controller supports Advertising State, otherwise // excluded. - auto c34 = mandatory_or_excluded(SupportsLLFeature( - LLFeaturesBits::PERIODIC_ADVERTISING_SYNC_TRANSFER_SENDER)); + auto c34 = mandatory_or_excluded( + SupportsLLFeature(LLFeaturesBits::PERIODIC_ADVERTISING_SYNC_TRANSFER_SENDER)); // C35: Mandatory if LE Feature (Periodic Advertising Sync Transfer – // Recipient) is supported, otherwise excluded. - auto c35 = mandatory_or_excluded(SupportsLLFeature( - LLFeaturesBits::PERIODIC_ADVERTISING_SYNC_TRANSFER_RECIPIENT)); + auto c35 = mandatory_or_excluded( + SupportsLLFeature(LLFeaturesBits::PERIODIC_ADVERTISING_SYNC_TRANSFER_RECIPIENT)); // C36: Mandatory if the LE Controller supports Central role or supports both // Peripheral role and LE Feature (Channel Classification), otherwise optional // if LE Feature (Extended Advertising) is supported and the LE Controller @@ -958,8 +866,7 @@ bool ControllerProperties::CheckSupportedCommands() const { auto c36 = mandatory; // C37: Mandatory if the LE Controller can change its sleep clock accuracy, // otherwise excluded. - auto c37 = mandatory_or_excluded( - SupportsLLFeature(LLFeaturesBits::SLEEP_CLOCK_ACCURACY_UPDATES)); + auto c37 = mandatory_or_excluded(SupportsLLFeature(LLFeaturesBits::SLEEP_CLOCK_ACCURACY_UPDATES)); // C38: Mandatory if LE Feature (Connected Isochronous Stream - Central) or // LE Feature (Connected Isochronous Stream - Peripheral) is supported, // otherwise excluded. @@ -967,85 +874,73 @@ bool ControllerProperties::CheckSupportedCommands() const { // C39: Mandatory if LE Feature (Connected Isochronous // Stream - Central) is supported, otherwise excluded. auto c39 = mandatory_or_excluded( - SupportsLLFeature(LLFeaturesBits::CONNECTED_ISOCHRONOUS_STREAM_CENTRAL)); + SupportsLLFeature(LLFeaturesBits::CONNECTED_ISOCHRONOUS_STREAM_CENTRAL)); // C40: Mandatory if LE Feature (Connected Isochronous Stream - Peripheral) is // supported, otherwise excluded. - auto c40 = mandatory_or_excluded(SupportsLLFeature( - LLFeaturesBits::CONNECTED_ISOCHRONOUS_STREAM_PERIPHERAL)); + auto c40 = mandatory_or_excluded( + SupportsLLFeature(LLFeaturesBits::CONNECTED_ISOCHRONOUS_STREAM_PERIPHERAL)); // C41: Mandatory if LE Feature (Isochronous Broadcaster) is supported, // otherwise excluded. - auto c41 = mandatory_or_excluded( - SupportsLLFeature(LLFeaturesBits::ISOCHRONOUS_BROADCASTER)); + auto c41 = mandatory_or_excluded(SupportsLLFeature(LLFeaturesBits::ISOCHRONOUS_BROADCASTER)); // C42: Mandatory if LE Feature (Synchronized Receiver role) is supported, // otherwise excluded. - auto c42 = mandatory_or_excluded( - SupportsLLFeature(LLFeaturesBits::SYNCHRONIZED_RECEIVER)); + auto c42 = mandatory_or_excluded(SupportsLLFeature(LLFeaturesBits::SYNCHRONIZED_RECEIVER)); // C44: Mandatory if LE Feature (Sleep Clock Accuracy Updates) and either LE // Feature (Connected Isochronous Stream - Central) or LE Feature (Connected // Isochronous Stream - Peripheral) are supported, otherwise optional if LE // Feature (Sleep Clock Accuracy Updates) is supported, otherwise excluded. auto c44 = mandatory_or_optional_or_excluded( - SupportsLLFeature(LLFeaturesBits::SLEEP_CLOCK_ACCURACY_UPDATES) && - (SupportsLLFeature( - LLFeaturesBits::CONNECTED_ISOCHRONOUS_STREAM_CENTRAL) || - SupportsLLFeature( - LLFeaturesBits::CONNECTED_ISOCHRONOUS_STREAM_PERIPHERAL)), - SupportsLLFeature(LLFeaturesBits::SLEEP_CLOCK_ACCURACY_UPDATES)); + SupportsLLFeature(LLFeaturesBits::SLEEP_CLOCK_ACCURACY_UPDATES) && + (SupportsLLFeature(LLFeaturesBits::CONNECTED_ISOCHRONOUS_STREAM_CENTRAL) || + SupportsLLFeature(LLFeaturesBits::CONNECTED_ISOCHRONOUS_STREAM_PERIPHERAL)), + SupportsLLFeature(LLFeaturesBits::SLEEP_CLOCK_ACCURACY_UPDATES)); // C45: Mandatory if LE Feature (Connected Isochronous Stream - Central), or // LE Feature (Connected Isochronous Stream - Peripheral), or // LE Feature (Isochronous Broadcaster) is supported, otherwise excluded. auto c45 = mandatory_or_excluded( - SupportsLLFeature(LLFeaturesBits::CONNECTED_ISOCHRONOUS_STREAM_CENTRAL) || - SupportsLLFeature( - LLFeaturesBits::CONNECTED_ISOCHRONOUS_STREAM_PERIPHERAL) || - SupportsLLFeature(LLFeaturesBits::ISOCHRONOUS_BROADCASTER)); + SupportsLLFeature(LLFeaturesBits::CONNECTED_ISOCHRONOUS_STREAM_CENTRAL) || + SupportsLLFeature(LLFeaturesBits::CONNECTED_ISOCHRONOUS_STREAM_PERIPHERAL) || + SupportsLLFeature(LLFeaturesBits::ISOCHRONOUS_BROADCASTER)); // C46: Mandatory if LE Feature (Connected Isochronous Stream - Central), or // LE Feature (Connected Isochronous Stream - Peripheral), or // LE Feature (Synchronized Receiver role) is supported, otherwise excluded. auto c46 = mandatory_or_excluded( - SupportsLLFeature(LLFeaturesBits::CONNECTED_ISOCHRONOUS_STREAM_CENTRAL) || - SupportsLLFeature( - LLFeaturesBits::CONNECTED_ISOCHRONOUS_STREAM_PERIPHERAL) || - SupportsLLFeature(LLFeaturesBits::SYNCHRONIZED_RECEIVER)); + SupportsLLFeature(LLFeaturesBits::CONNECTED_ISOCHRONOUS_STREAM_CENTRAL) || + SupportsLLFeature(LLFeaturesBits::CONNECTED_ISOCHRONOUS_STREAM_PERIPHERAL) || + SupportsLLFeature(LLFeaturesBits::SYNCHRONIZED_RECEIVER)); // C47: Mandatory if LE Feature (Connected Isochronous Stream - Central), or // LE Feature (Connected Isochronous Stream - Peripheral), or // LE Feature (Isochronous Broadcaster), or // LE Feature (Synchronized Receiver role) is supported, otherwise excluded. auto c47 = mandatory_or_excluded( - SupportsLLFeature(LLFeaturesBits::CONNECTED_ISOCHRONOUS_STREAM_CENTRAL) || - SupportsLLFeature( - LLFeaturesBits::CONNECTED_ISOCHRONOUS_STREAM_PERIPHERAL) || - SupportsLLFeature(LLFeaturesBits::ISOCHRONOUS_BROADCASTER) || - SupportsLLFeature(LLFeaturesBits::SYNCHRONIZED_RECEIVER)); + SupportsLLFeature(LLFeaturesBits::CONNECTED_ISOCHRONOUS_STREAM_CENTRAL) || + SupportsLLFeature(LLFeaturesBits::CONNECTED_ISOCHRONOUS_STREAM_PERIPHERAL) || + SupportsLLFeature(LLFeaturesBits::ISOCHRONOUS_BROADCASTER) || + SupportsLLFeature(LLFeaturesBits::SYNCHRONIZED_RECEIVER)); // C49: Mandatory if LE Feature (Connected Isochronous Stream - Central) or // LE Feature (Connected Isochronous Stream - Peripheral) or // LE Feature (Connection Subrating) is supported, otherwise optional. auto c49 = mandatory_or_optional( - SupportsLLFeature(LLFeaturesBits::CONNECTED_ISOCHRONOUS_STREAM_CENTRAL) || - SupportsLLFeature( - LLFeaturesBits::CONNECTED_ISOCHRONOUS_STREAM_PERIPHERAL) || - SupportsLLFeature(LLFeaturesBits::CONNECTION_SUBRATING)); + SupportsLLFeature(LLFeaturesBits::CONNECTED_ISOCHRONOUS_STREAM_CENTRAL) || + SupportsLLFeature(LLFeaturesBits::CONNECTED_ISOCHRONOUS_STREAM_PERIPHERAL) || + SupportsLLFeature(LLFeaturesBits::CONNECTION_SUBRATING)); // C50: Optional if LE Feature (Connected Isochronous Stream - Central), or // LE Feature (Connected Isochronous Stream - Peripheral), or // LE Feature (Synchronized Receiver role) is supported, otherwise excluded. auto c50 = optional_or_excluded( - SupportsLLFeature(LLFeaturesBits::CONNECTED_ISOCHRONOUS_STREAM_CENTRAL) || - SupportsLLFeature( - LLFeaturesBits::CONNECTED_ISOCHRONOUS_STREAM_PERIPHERAL) || - SupportsLLFeature(LLFeaturesBits::SYNCHRONIZED_RECEIVER)); + SupportsLLFeature(LLFeaturesBits::CONNECTED_ISOCHRONOUS_STREAM_CENTRAL) || + SupportsLLFeature(LLFeaturesBits::CONNECTED_ISOCHRONOUS_STREAM_PERIPHERAL) || + SupportsLLFeature(LLFeaturesBits::SYNCHRONIZED_RECEIVER)); // C51: Mandatory if LE Feature (LE Power Control Request) is supported, // otherwise excluded. - auto c51 = mandatory_or_excluded( - SupportsLLFeature(LLFeaturesBits::LE_POWER_CONTROL_REQUEST)); + auto c51 = mandatory_or_excluded(SupportsLLFeature(LLFeaturesBits::LE_POWER_CONTROL_REQUEST)); // C52: Mandatory if LE Feature (LE Path Loss Monitoring) is supported, // otherwise excluded. - auto c52 = mandatory_or_excluded( - SupportsLLFeature(LLFeaturesBits::LE_PATH_LOSS_MONITORING)); + auto c52 = mandatory_or_excluded(SupportsLLFeature(LLFeaturesBits::LE_PATH_LOSS_MONITORING)); // C53: Mandatory if LE Feature (LE Power Control Request) is supported, // otherwise optional if the LE Controller supports transmitting packets, // otherwise excluded. - auto c53 = mandatory_or_optional( - SupportsLLFeature(LLFeaturesBits::LE_POWER_CONTROL_REQUEST)); + auto c53 = mandatory_or_optional(SupportsLLFeature(LLFeaturesBits::LE_POWER_CONTROL_REQUEST)); // C54: Mandatory if LE Feature (Synchronized Receiver) is supported, // otherwise optional. // @@ -1055,32 +950,27 @@ bool ControllerProperties::CheckSupportedCommands() const { // otherwise optional if the LE Controller supports Connection State, // otherwise excluded. auto c55 = mandatory_or_optional( - SupportsLLFeature(LLFeaturesBits::CONNECTED_ISOCHRONOUS_STREAM_CENTRAL) || - SupportsLLFeature( - LLFeaturesBits::CONNECTED_ISOCHRONOUS_STREAM_PERIPHERAL) || - SupportsLLFeature(LLFeaturesBits::ISOCHRONOUS_BROADCASTER)); + SupportsLLFeature(LLFeaturesBits::CONNECTED_ISOCHRONOUS_STREAM_CENTRAL) || + SupportsLLFeature(LLFeaturesBits::CONNECTED_ISOCHRONOUS_STREAM_PERIPHERAL) || + SupportsLLFeature(LLFeaturesBits::ISOCHRONOUS_BROADCASTER)); // C56: Optional if LE Feature (LE Encryption) is supported, otherwise // excluded. // // C57: Mandatory if LE Feature (Connection Subrating) is supported, // otherwise excluded. - auto c57 = mandatory_or_excluded( - SupportsLLFeature(LLFeaturesBits::CONNECTION_SUBRATING)); + auto c57 = mandatory_or_excluded(SupportsLLFeature(LLFeaturesBits::CONNECTION_SUBRATING)); // C58: Mandatory if LE Feature (Channel Classification) is supported, // otherwise excluded. - auto c58 = mandatory_or_excluded( - SupportsLLFeature(LLFeaturesBits::CHANNEL_CLASSIFICATION)); + auto c58 = mandatory_or_excluded(SupportsLLFeature(LLFeaturesBits::CHANNEL_CLASSIFICATION)); // C59: Mandatory if the LE Controller supports Central role, otherwise // excluded. auto c59 = mandatory; // C60: Mandatory if the LE Controller supports Central role and LE Feature // (LE Encryption), otherwise excluded. - auto c60 = - mandatory_or_excluded(SupportsLLFeature(LLFeaturesBits::LE_ENCRYPTION)); + auto c60 = mandatory_or_excluded(SupportsLLFeature(LLFeaturesBits::LE_ENCRYPTION)); // C61: Mandatory if the LE Controller supports Peripheral role and LE Feature // (LE Encryption), otherwise excluded. - auto c61 = - mandatory_or_excluded(SupportsLLFeature(LLFeaturesBits::LE_ENCRYPTION)); + auto c61 = mandatory_or_excluded(SupportsLLFeature(LLFeaturesBits::LE_ENCRYPTION)); // C62: Mandatory if the LE Controller supports Central role or supports both // Peripheral role and LE Feature (Connection Parameters Request Procedure), // otherwise excluded. @@ -1093,9 +983,8 @@ bool ControllerProperties::CheckSupportedCommands() const { auto c64 = optional; // C94: Mandatory if the LE Create Connection or LE Extended Create Connection // command is supported, otherwise excluded. - auto c94 = mandatory_or_excluded( - SupportsCommand(OpCodeIndex::LE_CREATE_CONNECTION) || - SupportsCommand(OpCodeIndex::LE_EXTENDED_CREATE_CONNECTION)); + auto c94 = mandatory_or_excluded(SupportsCommand(OpCodeIndex::LE_CREATE_CONNECTION) || + SupportsCommand(OpCodeIndex::LE_EXTENDED_CREATE_CONNECTION)); // C95: Mandatory if the LE Request Peer SCA command is supported, otherwise // excluded. // @@ -1108,8 +997,7 @@ bool ControllerProperties::CheckSupportedCommands() const { auto c98 = mandatory; // C99: Mandatory if LE Generate DHKey command [v2] is supported, otherwise // optional. - auto c99 = - mandatory_or_optional(SupportsCommand(OpCodeIndex::LE_GENERATE_DHKEY_V2)); + auto c99 = mandatory_or_optional(SupportsCommand(OpCodeIndex::LE_GENERATE_DHKEY_V2)); // C101: Mandatory if the Authentication Requested command is supported, // otherwise excluded. // @@ -1118,8 +1006,7 @@ bool ControllerProperties::CheckSupportedCommands() const { // // C103: Mandatory if the Periodic // Inquiry Mode command is supported, otherwise excluded. - auto c103 = mandatory_or_excluded( - SupportsCommand(OpCodeIndex::PERIODIC_INQUIRY_MODE)); + auto c103 = mandatory_or_excluded(SupportsCommand(OpCodeIndex::PERIODIC_INQUIRY_MODE)); // C104: Mandatory if the Read Clock Offset command is supported, otherwise // excluded. // @@ -1128,71 +1015,58 @@ bool ControllerProperties::CheckSupportedCommands() const { // // C106: Mandatory if the Remote Name Request // command is supported, otherwise excluded. - auto c106 = - mandatory_or_excluded(SupportsCommand(OpCodeIndex::REMOTE_NAME_REQUEST)); + auto c106 = mandatory_or_excluded(SupportsCommand(OpCodeIndex::REMOTE_NAME_REQUEST)); // C107: Mandatory if the Set Controller To Host Flow Control command is // supported, otherwise excluded. - auto c107 = mandatory_or_excluded( - SupportsCommand(OpCodeIndex::SET_CONTROLLER_TO_HOST_FLOW_CONTROL)); + auto c107 = + mandatory_or_excluded(SupportsCommand(OpCodeIndex::SET_CONTROLLER_TO_HOST_FLOW_CONTROL)); // C108: Mandatory if the Set MWS_PATTERN Configuration command is supported, // otherwise optional. - auto c108 = mandatory_or_optional( - SupportsCommand(OpCodeIndex::SET_MWS_PATTERN_CONFIGURATION)); + auto c108 = mandatory_or_optional(SupportsCommand(OpCodeIndex::SET_MWS_PATTERN_CONFIGURATION)); // C109: Mandatory if the Set MWS Signaling command is supported, otherwise // excluded. - auto c109 = - mandatory_or_excluded(SupportsCommand(OpCodeIndex::SET_MWS_SIGNALING)); + auto c109 = mandatory_or_excluded(SupportsCommand(OpCodeIndex::SET_MWS_SIGNALING)); // C110: Mandatory if the Set Triggered Clock Capture command is supported, // otherwise excluded. // // C111: Mandatory if the Write Authentication Enable // command is supported, otherwise excluded. - auto c111 = mandatory_or_excluded( - SupportsCommand(OpCodeIndex::WRITE_AUTHENTICATION_ENABLE)); + auto c111 = mandatory_or_excluded(SupportsCommand(OpCodeIndex::WRITE_AUTHENTICATION_ENABLE)); // C112: Mandatory if the Write Default Erroneous Data Reporting command is // supported, otherwise excluded. auto c112 = mandatory_or_excluded( - SupportsCommand(OpCodeIndex::WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING)); + SupportsCommand(OpCodeIndex::WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING)); // C113: Mandatory if the Write Extended Inquiry Length command is supported, // otherwise excluded. - auto c113 = mandatory_or_excluded( - SupportsCommand(OpCodeIndex::WRITE_EXTENDED_INQUIRY_LENGTH)); + auto c113 = mandatory_or_excluded(SupportsCommand(OpCodeIndex::WRITE_EXTENDED_INQUIRY_LENGTH)); // C114: Mandatory if the Write Extended Page Timeout command is supported, // otherwise excluded. - auto c114 = mandatory_or_excluded( - SupportsCommand(OpCodeIndex::WRITE_EXTENDED_PAGE_TIMEOUT)); + auto c114 = mandatory_or_excluded(SupportsCommand(OpCodeIndex::WRITE_EXTENDED_PAGE_TIMEOUT)); // C115: Mandatory if the Write Inquiry Mode command is supported, otherwise // excluded. - auto c115 = - mandatory_or_excluded(SupportsCommand(OpCodeIndex::WRITE_INQUIRY_MODE)); + auto c115 = mandatory_or_excluded(SupportsCommand(OpCodeIndex::WRITE_INQUIRY_MODE)); // C116: Mandatory if the Write LE Host Support command is supported, // otherwise excluded. - auto c116 = mandatory_or_excluded( - SupportsCommand(OpCodeIndex::WRITE_LE_HOST_SUPPORT)); + auto c116 = mandatory_or_excluded(SupportsCommand(OpCodeIndex::WRITE_LE_HOST_SUPPORT)); // C117: Mandatory if the Write Link Supervision Timeout command is supported, // otherwise excluded. - auto c117 = mandatory_or_excluded( - SupportsCommand(OpCodeIndex::WRITE_LINK_SUPERVISION_TIMEOUT)); + auto c117 = mandatory_or_excluded(SupportsCommand(OpCodeIndex::WRITE_LINK_SUPERVISION_TIMEOUT)); // C118: Mandatory if the Write Num Broadcast Retransmissions command is // supported, otherwise excluded. - auto c118 = mandatory_or_excluded( - SupportsCommand(OpCodeIndex::WRITE_NUM_BROADCAST_RETRANSMITS)); + auto c118 = mandatory_or_excluded(SupportsCommand(OpCodeIndex::WRITE_NUM_BROADCAST_RETRANSMITS)); // C119: Mandatory if the Write Page Scan Type command is supported, otherwise // excluded. - auto c119 = - mandatory_or_excluded(SupportsCommand(OpCodeIndex::WRITE_PAGE_SCAN_TYPE)); + auto c119 = mandatory_or_excluded(SupportsCommand(OpCodeIndex::WRITE_PAGE_SCAN_TYPE)); // C120: Mandatory if the Write PIN Type command is supported, otherwise // excluded. - auto c120 = - mandatory_or_excluded(SupportsCommand(OpCodeIndex::WRITE_PIN_TYPE)); + auto c120 = mandatory_or_excluded(SupportsCommand(OpCodeIndex::WRITE_PIN_TYPE)); // C121: Mandatory if the Write Stored Link Key command is supported, // otherwise excluded. - auto c121 = mandatory_or_excluded( - SupportsCommand(OpCodeIndex::WRITE_STORED_LINK_KEY)); + auto c121 = mandatory_or_excluded(SupportsCommand(OpCodeIndex::WRITE_STORED_LINK_KEY)); // C122: Mandatory if the Write Synchronous Flow Control Enable command is // supported, otherwise excluded. auto c122 = mandatory_or_excluded( - SupportsCommand(OpCodeIndex::WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE)); + SupportsCommand(OpCodeIndex::WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE)); // C123: Mandatory if BR/EDR test mode is supported, otherwise excluded. auto c123 = mandatory; // C124: Mandatory if Data block based flow control is supported, otherwise @@ -1214,55 +1088,48 @@ bool ControllerProperties::CheckSupportedCommands() const { // C133: Mandatory if HV2, HV3, or multi-slot or EDR ACL packets are // supported, otherwise excluded. auto c133 = mandatory_or_excluded( - SupportsLMPFeature(LMPFeaturesPage0Bits::HV2_PACKETS) || - SupportsLMPFeature(LMPFeaturesPage0Bits::HV3_PACKETS) || - SupportsLMPFeature( - LMPFeaturesPage0Bits::ENHANCED_DATA_RATE_ACL_2_MB_S_MODE) || - SupportsLMPFeature( - LMPFeaturesPage0Bits::ENHANCED_DATA_RATE_ACL_3_MB_S_MODE) || - SupportsLMPFeature( - LMPFeaturesPage0Bits::LMP_3_SLOT_ENHANCED_DATA_RATE_ACL_PACKETS)); + SupportsLMPFeature(LMPFeaturesPage0Bits::HV2_PACKETS) || + SupportsLMPFeature(LMPFeaturesPage0Bits::HV3_PACKETS) || + SupportsLMPFeature(LMPFeaturesPage0Bits::ENHANCED_DATA_RATE_ACL_2_MB_S_MODE) || + SupportsLMPFeature(LMPFeaturesPage0Bits::ENHANCED_DATA_RATE_ACL_3_MB_S_MODE) || + SupportsLMPFeature(LMPFeaturesPage0Bits::LMP_3_SLOT_ENHANCED_DATA_RATE_ACL_PACKETS)); // C134: Mandatory if SCO or eSCO is supported, otherwise excluded. - auto c134 = mandatory_or_excluded( - SupportsLMPFeature(LMPFeaturesPage0Bits::SCO_LINK) || - SupportsLMPFeature(LMPFeaturesPage0Bits::EXTENDED_SCO_LINK)); + auto c134 = mandatory_or_excluded(SupportsLMPFeature(LMPFeaturesPage0Bits::SCO_LINK) || + SupportsLMPFeature(LMPFeaturesPage0Bits::EXTENDED_SCO_LINK)); // C135: Optional if SCO or eSCO is supported, otherwise excluded. - auto c135 = optional_or_excluded( - SupportsLMPFeature(LMPFeaturesPage0Bits::SCO_LINK) || - SupportsLMPFeature(LMPFeaturesPage0Bits::EXTENDED_SCO_LINK)); + auto c135 = optional_or_excluded(SupportsLMPFeature(LMPFeaturesPage0Bits::SCO_LINK) || + SupportsLMPFeature(LMPFeaturesPage0Bits::EXTENDED_SCO_LINK)); // C136: Optional if Slot Availability Mask is supported, otherwise excluded. - auto c136 = optional_or_excluded( - SupportsLMPFeature(LMPFeaturesPage2Bits::SLOT_AVAILABILITY_MASK)); + auto c136 = + optional_or_excluded(SupportsLMPFeature(LMPFeaturesPage2Bits::SLOT_AVAILABILITY_MASK)); // C138: Mandatory if Secure Connections (Controller) is supported, otherwise // optional if eSCO is supported, otherwise excluded. auto c138 = mandatory_or_optional_or_excluded( - SupportsLMPFeature( - LMPFeaturesPage2Bits::SECURE_CONNECTIONS_CONTROLLER_SUPPORT), - SupportsLMPFeature(LMPFeaturesPage0Bits::EXTENDED_SCO_LINK)); + SupportsLMPFeature(LMPFeaturesPage2Bits::SECURE_CONNECTIONS_CONTROLLER_SUPPORT), + SupportsLMPFeature(LMPFeaturesPage0Bits::EXTENDED_SCO_LINK)); // C139: Mandatory if the Controller is AFH capable in either role, otherwise // excluded. - auto c139 = mandatory_or_excluded( - SupportsLMPFeature(LMPFeaturesPage0Bits::AFH_CAPABLE_CENTRAL) || - SupportsLMPFeature(LMPFeaturesPage0Bits::AFH_CAPABLE_PERIPHERAL)); + auto c139 = + mandatory_or_excluded(SupportsLMPFeature(LMPFeaturesPage0Bits::AFH_CAPABLE_CENTRAL) || + SupportsLMPFeature(LMPFeaturesPage0Bits::AFH_CAPABLE_PERIPHERAL)); // C140: Mandatory if the Controller supports AFH classification in either // role or is an AFH capable Central, otherwise excluded. auto c140 = mandatory_or_excluded( - SupportsLMPFeature(LMPFeaturesPage0Bits::AFH_CLASSIFICATION_CENTRAL) || - SupportsLMPFeature(LMPFeaturesPage0Bits::AFH_CLASSIFICATION_PERIPHERAL) || - SupportsLMPFeature(LMPFeaturesPage0Bits::AFH_CAPABLE_CENTRAL)); + SupportsLMPFeature(LMPFeaturesPage0Bits::AFH_CLASSIFICATION_CENTRAL) || + SupportsLMPFeature(LMPFeaturesPage0Bits::AFH_CLASSIFICATION_PERIPHERAL) || + SupportsLMPFeature(LMPFeaturesPage0Bits::AFH_CAPABLE_CENTRAL)); // C141: Mandatory if Role Switch, Hold mode, or Sniff mode is supported, // otherwise excluded. - auto c141 = mandatory_or_excluded( - SupportsLMPFeature(LMPFeaturesPage0Bits::ROLE_SWITCH) || - SupportsLMPFeature(LMPFeaturesPage0Bits::HOLD_MODE) || - SupportsLMPFeature(LMPFeaturesPage0Bits::SNIFF_MODE)); + auto c141 = mandatory_or_excluded(SupportsLMPFeature(LMPFeaturesPage0Bits::ROLE_SWITCH) || + SupportsLMPFeature(LMPFeaturesPage0Bits::HOLD_MODE) || + SupportsLMPFeature(LMPFeaturesPage0Bits::SNIFF_MODE)); // C142: Mandatory if Secure Connections (Host) is supported, otherwise // excluded. auto c142 = mandatory; // C143: Mandatory if Secure Connections (both Host and Controller) is // supported, otherwise excluded. - auto c143 = mandatory_or_excluded(SupportsLMPFeature( - LMPFeaturesPage2Bits::SECURE_CONNECTIONS_CONTROLLER_SUPPORT)); + auto c143 = mandatory_or_excluded( + SupportsLMPFeature(LMPFeaturesPage2Bits::SECURE_CONNECTIONS_CONTROLLER_SUPPORT)); // C144: Mandatory if Hold Mode or Sniff Mode is supported, otherwise // excluded. // @@ -1284,91 +1151,75 @@ bool ControllerProperties::CheckSupportedCommands() const { // C151: Mandatory if Secure Connections (Controller) and Ping are supported, // otherwise excluded. auto c151 = mandatory_or_excluded( - SupportsLMPFeature( - LMPFeaturesPage2Bits::SECURE_CONNECTIONS_CONTROLLER_SUPPORT) && - SupportsLMPFeature(LMPFeaturesPage2Bits::PING)); + SupportsLMPFeature(LMPFeaturesPage2Bits::SECURE_CONNECTIONS_CONTROLLER_SUPPORT) && + SupportsLMPFeature(LMPFeaturesPage2Bits::PING)); // C152: Mandatory if Power Control is supported, otherwise optional. - auto c152 = mandatory_or_excluded( - SupportsLMPFeature(LMPFeaturesPage0Bits::POWER_CONTROL)); + auto c152 = mandatory_or_excluded(SupportsLMPFeature(LMPFeaturesPage0Bits::POWER_CONTROL)); // C153: Mandatory if LE supported in the Controller, otherwise optional. - auto c153 = mandatory_or_excluded( - SupportsLMPFeature(LMPFeaturesPage0Bits::LE_SUPPORTED_CONTROLLER)); + auto c153 = + mandatory_or_excluded(SupportsLMPFeature(LMPFeaturesPage0Bits::LE_SUPPORTED_CONTROLLER)); // C154: Mandatory if Interlaced Page Scan is supported, otherwise optional. - auto c154 = mandatory_or_excluded( - SupportsLMPFeature(LMPFeaturesPage0Bits::INTERLACED_PAGE_SCAN)); + auto c154 = mandatory_or_excluded(SupportsLMPFeature(LMPFeaturesPage0Bits::INTERLACED_PAGE_SCAN)); // C155: Mandatory if the Write Authenticated Payload Timeout command is // supported, otherwise excluded. - auto c155 = mandatory_or_excluded( - SupportsCommand(OpCodeIndex::WRITE_AUTHENTICATED_PAYLOAD_TIMEOUT)); + auto c155 = + mandatory_or_excluded(SupportsCommand(OpCodeIndex::WRITE_AUTHENTICATED_PAYLOAD_TIMEOUT)); // C156: Mandatory if the Read Local Supported Codecs command [v2] is // supported, otherwise excluded. - auto c156 = mandatory_or_excluded( - SupportsCommand(OpCodeIndex::READ_LOCAL_SUPPORTED_CODECS_V2)); + auto c156 = mandatory_or_excluded(SupportsCommand(OpCodeIndex::READ_LOCAL_SUPPORTED_CODECS_V2)); // C157: Mandatory if the Read Local Supported Codecs command [v2] is // supported, otherwise optional. - auto c157 = mandatory_or_optional( - SupportsCommand(OpCodeIndex::READ_LOCAL_SUPPORTED_CODECS_V2)); + auto c157 = mandatory_or_optional(SupportsCommand(OpCodeIndex::READ_LOCAL_SUPPORTED_CODECS_V2)); // C158: Mandatory if the Set Min Encryption Key Size command is supported, // otherwise optional. // // C201: Mandatory if Connectionless Peripheral Broadcast - Transmitter is // supported, otherwise excluded. auto c201 = mandatory_or_excluded(SupportsLMPFeature( - LMPFeaturesPage2Bits:: - CONNECTIONLESS_PERIPHERAL_BROADCAST_TRANSMITTER_OPERATION)); + LMPFeaturesPage2Bits::CONNECTIONLESS_PERIPHERAL_BROADCAST_TRANSMITTER_OPERATION)); // C202: Mandatory if Connectionless Peripheral Broadcast - Receiver is // supported, otherwise excluded. auto c202 = mandatory_or_excluded(SupportsLMPFeature( - LMPFeaturesPage2Bits:: - CONNECTIONLESS_PERIPHERAL_BROADCAST_RECEIVER_OPERATION)); + LMPFeaturesPage2Bits::CONNECTIONLESS_PERIPHERAL_BROADCAST_RECEIVER_OPERATION)); // C203: Mandatory if Synchronization Train is supported, otherwise excluded. - auto c203 = mandatory_or_excluded( - SupportsLMPFeature(LMPFeaturesPage2Bits::SYNCHRONIZATION_TRAIN)); + auto c203 = + mandatory_or_excluded(SupportsLMPFeature(LMPFeaturesPage2Bits::SYNCHRONIZATION_TRAIN)); // C204: Mandatory if Synchronization Scan is supported, otherwise excluded. - auto c204 = mandatory_or_excluded( - SupportsLMPFeature(LMPFeaturesPage2Bits::SYNCHRONIZATION_SCAN)); + auto c204 = mandatory_or_excluded(SupportsLMPFeature(LMPFeaturesPage2Bits::SYNCHRONIZATION_SCAN)); // C205: Mandatory if Extended Inquiry Response is supported, otherwise // excluded. auto c205 = mandatory_or_excluded( - SupportsLMPFeature(LMPFeaturesPage0Bits::EXTENDED_INQUIRY_RESPONSE)); + SupportsLMPFeature(LMPFeaturesPage0Bits::EXTENDED_INQUIRY_RESPONSE)); // C212: Mandatory if Role Switch is supported, otherwise excluded. - auto c212 = mandatory_or_excluded( - SupportsLMPFeature(LMPFeaturesPage0Bits::ROLE_SWITCH)); + auto c212 = mandatory_or_excluded(SupportsLMPFeature(LMPFeaturesPage0Bits::ROLE_SWITCH)); // C213: Mandatory if Hold mode is supported, otherwise excluded. - auto c213 = mandatory_or_excluded( - SupportsLMPFeature(LMPFeaturesPage0Bits::HOLD_MODE)); + auto c213 = mandatory_or_excluded(SupportsLMPFeature(LMPFeaturesPage0Bits::HOLD_MODE)); // C214: Mandatory if Sniff mode is supported, otherwise excluded. - auto c214 = mandatory_or_excluded( - SupportsLMPFeature(LMPFeaturesPage0Bits::SNIFF_MODE)); + auto c214 = mandatory_or_excluded(SupportsLMPFeature(LMPFeaturesPage0Bits::SNIFF_MODE)); // C215: Mandatory if Broadcast Encryption is supported, otherwise excluded. - auto c215 = mandatory_or_excluded( - SupportsLMPFeature(LMPFeaturesPage0Bits::BROADCAST_ENCRYPTION)); + auto c215 = mandatory_or_excluded(SupportsLMPFeature(LMPFeaturesPage0Bits::BROADCAST_ENCRYPTION)); // C217: Mandatory if BR/EDR Enhanced Power Control is supported, otherwise // excluded. - auto c217 = mandatory_or_excluded( - SupportsLMPFeature(LMPFeaturesPage0Bits::ENHANCED_POWER_CONTROL)); + auto c217 = + mandatory_or_excluded(SupportsLMPFeature(LMPFeaturesPage0Bits::ENHANCED_POWER_CONTROL)); // C218: Mandatory if Secure Connections (Controller) is supported, otherwise // excluded. - auto c218 = mandatory_or_excluded(SupportsLMPFeature( - LMPFeaturesPage2Bits::SECURE_CONNECTIONS_CONTROLLER_SUPPORT)); + auto c218 = mandatory_or_excluded( + SupportsLMPFeature(LMPFeaturesPage2Bits::SECURE_CONNECTIONS_CONTROLLER_SUPPORT)); // C219: Mandatory if Slot Availability Mask is supported, otherwise excluded. // C220: Mandatory if LMP Extended Features mask is supported, otherwise // excluded. - auto c220 = mandatory_or_excluded( - SupportsLMPFeature(LMPFeaturesPage0Bits::EXTENDED_FEATURES)); + auto c220 = mandatory_or_excluded(SupportsLMPFeature(LMPFeaturesPage0Bits::EXTENDED_FEATURES)); // C221: Mandatory if Sniff subrating is supported, otherwise excluded. - auto c221 = mandatory_or_excluded( - SupportsLMPFeature(LMPFeaturesPage0Bits::SNIFF_SUBRATING)); + auto c221 = mandatory_or_excluded(SupportsLMPFeature(LMPFeaturesPage0Bits::SNIFF_SUBRATING)); -#define check_command_(op_code, br_requirement, le_requirement) \ - { \ - bool command_supported = \ - SupportsCommand(bluetooth::hci::OpCodeIndex::op_code); \ - if (!check_command_requirement(br_supported, br_requirement, le_supported, \ - le_requirement, command_supported)) { \ - INFO(#op_code " command validation failed (" #br_requirement \ - "," #le_requirement ")"); \ - } \ +#define check_command_(op_code, br_requirement, le_requirement) \ + { \ + bool command_supported = SupportsCommand(bluetooth::hci::OpCodeIndex::op_code); \ + if (!check_command_requirement(br_supported, br_requirement, le_supported, le_requirement, \ + command_supported)) { \ + INFO(#op_code " command validation failed (" #br_requirement "," #le_requirement ")"); \ + } \ } // Table 3.1: Alphabetical list of commands and events (Sheet 1 of 49) @@ -1478,8 +1329,7 @@ bool ControllerProperties::CheckSupportedCommands() const { check_command_(LE_RECEIVER_TEST_V3, excluded, c30); // Table 3.1: Alphabetical list of commands and events (Sheet 18 of 49) check_command_(LE_REJECT_CIS_REQUEST, excluded, c40); - check_command_(LE_REMOTE_CONNECTION_PARAMETER_REQUEST_NEGATIVE_REPLY, - excluded, c6); + check_command_(LE_REMOTE_CONNECTION_PARAMETER_REQUEST_NEGATIVE_REPLY, excluded, c6); check_command_(LE_REMOTE_CONNECTION_PARAMETER_REQUEST_REPLY, excluded, c6); check_command_(LE_REMOVE_ADVERTISING_SET, excluded, c17); check_command_(LE_REMOVE_CIG, excluded, c39); @@ -1505,8 +1355,7 @@ bool ControllerProperties::CheckSupportedCommands() const { check_command_(LE_SET_DATA_LENGTH, excluded, c8); // Table 3.1: Alphabetical list of commands and events (Sheet 21 of 49) check_command_(LE_SET_DATA_RELATED_ADDRESS_CHANGES, excluded, c10); - check_command_(LE_SET_DEFAULT_PERIODIC_ADVERTISING_SYNC_TRANSFER_PARAMETERS, - excluded, c35); + check_command_(LE_SET_DEFAULT_PERIODIC_ADVERTISING_SYNC_TRANSFER_PARAMETERS, excluded, c35); check_command_(LE_SET_DEFAULT_PHY, excluded, c11); check_command_(LE_SET_DEFAULT_SUBRATE, excluded, c57); check_command_(LE_SET_EVENT_MASK, excluded, mandatory); @@ -1526,8 +1375,7 @@ bool ControllerProperties::CheckSupportedCommands() const { check_command_(LE_SET_PERIODIC_ADVERTISING_PARAMETERS, excluded, c18); // Table 3.1: Alphabetical list of commands and events (Sheet 23 of 49) check_command_(LE_SET_PERIODIC_ADVERTISING_RECEIVE_ENABLE, excluded, c32); - check_command_(LE_SET_PERIODIC_ADVERTISING_SYNC_TRANSFER_PARAMETERS, excluded, - c35); + check_command_(LE_SET_PERIODIC_ADVERTISING_SYNC_TRANSFER_PARAMETERS, excluded, c35); check_command_(LE_SET_PHY, excluded, c11); check_command_(LE_SET_PRIVACY_MODE, excluded, c9); check_command_(LE_SET_RANDOM_ADDRESS, excluded, c1); @@ -1649,8 +1497,7 @@ bool ControllerProperties::CheckSupportedCommands() const { // Table 3.1: Alphabetical list of commands and events (Sheet 39 of 49) check_command_(SET_CONNECTIONLESS_PERIPHERAL_BROADCAST, c201, excluded); check_command_(SET_CONNECTIONLESS_PERIPHERAL_BROADCAST_DATA, c201, excluded); - check_command_(SET_CONNECTIONLESS_PERIPHERAL_BROADCAST_RECEIVE, c202, - excluded); + check_command_(SET_CONNECTIONLESS_PERIPHERAL_BROADCAST_RECEIVE, c202, excluded); check_command_(SET_CONTROLLER_TO_HOST_FLOW_CONTROL, optional, c96); check_command_(SET_ECOSYSTEM_BASE_INTERVAL, optional, optional); check_command_(SET_EVENT_FILTER, c148, excluded); @@ -1731,84 +1578,77 @@ ControllerProperties::ControllerProperties() lmp_features({Page0LmpFeatures(), 0, Page2LmpFeatures()}), le_features(LlFeatures()) { if (!CheckSupportedFeatures()) { - INFO( - "Warning: initial LMP and/or LE are not consistent. Please make sure" - " that the features are correct w.r.t. the rules described" - " in Vol 2, Part C 3.5 Feature requirements"); + INFO("Warning: initial LMP and/or LE are not consistent. Please make sure" + " that the features are correct w.r.t. the rules described" + " in Vol 2, Part C 3.5 Feature requirements"); } if (!CheckSupportedCommands()) { - INFO( - "Warning: initial supported commands are not consistent. Please make" - " sure that the supported commands are correct w.r.t. the rules" - " described in Vol 4, Part E § 3 Overview of commands and events"); + INFO("Warning: initial supported commands are not consistent. Please make" + " sure that the supported commands are correct w.r.t. the rules" + " described in Vol 4, Part E § 3 Overview of commands and events"); } } // Commands enabled by the LE Extended Advertising feature bit. static std::vector le_extended_advertising_commands_ = { - OpCodeIndex::LE_CLEAR_ADVERTISING_SETS, - OpCodeIndex::LE_EXTENDED_CREATE_CONNECTION, - OpCodeIndex::LE_READ_MAXIMUM_ADVERTISING_DATA_LENGTH, - OpCodeIndex::LE_READ_NUMBER_OF_SUPPORTED_ADVERTISING_SETS, - OpCodeIndex::LE_RECEIVER_TEST_V2, - OpCodeIndex::LE_REMOVE_ADVERTISING_SET, - OpCodeIndex::LE_SET_ADVERTISING_SET_RANDOM_ADDRESS, - OpCodeIndex::LE_SET_DATA_RELATED_ADDRESS_CHANGES, - OpCodeIndex::LE_SET_EXTENDED_ADVERTISING_DATA, - OpCodeIndex::LE_SET_EXTENDED_ADVERTISING_ENABLE, - OpCodeIndex::LE_SET_EXTENDED_ADVERTISING_PARAMETERS, - OpCodeIndex::LE_SET_EXTENDED_SCAN_ENABLE, - OpCodeIndex::LE_SET_EXTENDED_SCAN_PARAMETERS, - OpCodeIndex::LE_SET_EXTENDED_SCAN_RESPONSE_DATA, + OpCodeIndex::LE_CLEAR_ADVERTISING_SETS, + OpCodeIndex::LE_EXTENDED_CREATE_CONNECTION, + OpCodeIndex::LE_READ_MAXIMUM_ADVERTISING_DATA_LENGTH, + OpCodeIndex::LE_READ_NUMBER_OF_SUPPORTED_ADVERTISING_SETS, + OpCodeIndex::LE_RECEIVER_TEST_V2, + OpCodeIndex::LE_REMOVE_ADVERTISING_SET, + OpCodeIndex::LE_SET_ADVERTISING_SET_RANDOM_ADDRESS, + OpCodeIndex::LE_SET_DATA_RELATED_ADDRESS_CHANGES, + OpCodeIndex::LE_SET_EXTENDED_ADVERTISING_DATA, + OpCodeIndex::LE_SET_EXTENDED_ADVERTISING_ENABLE, + OpCodeIndex::LE_SET_EXTENDED_ADVERTISING_PARAMETERS, + OpCodeIndex::LE_SET_EXTENDED_SCAN_ENABLE, + OpCodeIndex::LE_SET_EXTENDED_SCAN_PARAMETERS, + OpCodeIndex::LE_SET_EXTENDED_SCAN_RESPONSE_DATA, }; // Commands enabled by the LE Periodic Advertising feature bit. static std::vector le_periodic_advertising_commands_ = { - OpCodeIndex::LE_ADD_DEVICE_TO_PERIODIC_ADVERTISER_LIST, - OpCodeIndex::LE_CLEAR_PERIODIC_ADVERTISER_LIST, - OpCodeIndex::LE_PERIODIC_ADVERTISING_CREATE_SYNC_CANCEL, - OpCodeIndex::LE_PERIODIC_ADVERTISING_CREATE_SYNC, - OpCodeIndex::LE_PERIODIC_ADVERTISING_TERMINATE_SYNC, - OpCodeIndex::LE_READ_PERIODIC_ADVERTISER_LIST_SIZE, - OpCodeIndex::LE_RECEIVER_TEST_V2, - OpCodeIndex::LE_REMOVE_DEVICE_FROM_PERIODIC_ADVERTISER_LIST, - OpCodeIndex::LE_SET_DATA_RELATED_ADDRESS_CHANGES, - OpCodeIndex::LE_SET_PERIODIC_ADVERTISING_DATA, - OpCodeIndex::LE_SET_PERIODIC_ADVERTISING_ENABLE, - OpCodeIndex::LE_SET_PERIODIC_ADVERTISING_PARAMETERS, + OpCodeIndex::LE_ADD_DEVICE_TO_PERIODIC_ADVERTISER_LIST, + OpCodeIndex::LE_CLEAR_PERIODIC_ADVERTISER_LIST, + OpCodeIndex::LE_PERIODIC_ADVERTISING_CREATE_SYNC_CANCEL, + OpCodeIndex::LE_PERIODIC_ADVERTISING_CREATE_SYNC, + OpCodeIndex::LE_PERIODIC_ADVERTISING_TERMINATE_SYNC, + OpCodeIndex::LE_READ_PERIODIC_ADVERTISER_LIST_SIZE, + OpCodeIndex::LE_RECEIVER_TEST_V2, + OpCodeIndex::LE_REMOVE_DEVICE_FROM_PERIODIC_ADVERTISER_LIST, + OpCodeIndex::LE_SET_DATA_RELATED_ADDRESS_CHANGES, + OpCodeIndex::LE_SET_PERIODIC_ADVERTISING_DATA, + OpCodeIndex::LE_SET_PERIODIC_ADVERTISING_ENABLE, + OpCodeIndex::LE_SET_PERIODIC_ADVERTISING_PARAMETERS, }; // Commands enabled by the LL Privacy feature bit. static std::vector ll_privacy_commands_ = { - OpCodeIndex::LE_ADD_DEVICE_TO_RESOLVING_LIST, - OpCodeIndex::LE_CLEAR_RESOLVING_LIST, - OpCodeIndex::LE_READ_LOCAL_RESOLVABLE_ADDRESS, - OpCodeIndex::LE_READ_PEER_RESOLVABLE_ADDRESS, - OpCodeIndex::LE_READ_RESOLVING_LIST_SIZE, - OpCodeIndex::LE_RECEIVER_TEST_V2, - OpCodeIndex::LE_REMOVE_DEVICE_FROM_RESOLVING_LIST, - OpCodeIndex::LE_SET_ADDRESS_RESOLUTION_ENABLE, - OpCodeIndex::LE_SET_PRIVACY_MODE, - OpCodeIndex::LE_SET_RESOLVABLE_PRIVATE_ADDRESS_TIMEOUT, + OpCodeIndex::LE_ADD_DEVICE_TO_RESOLVING_LIST, + OpCodeIndex::LE_CLEAR_RESOLVING_LIST, + OpCodeIndex::LE_READ_LOCAL_RESOLVABLE_ADDRESS, + OpCodeIndex::LE_READ_PEER_RESOLVABLE_ADDRESS, + OpCodeIndex::LE_READ_RESOLVING_LIST_SIZE, + OpCodeIndex::LE_RECEIVER_TEST_V2, + OpCodeIndex::LE_REMOVE_DEVICE_FROM_RESOLVING_LIST, + OpCodeIndex::LE_SET_ADDRESS_RESOLUTION_ENABLE, + OpCodeIndex::LE_SET_PRIVACY_MODE, + OpCodeIndex::LE_SET_RESOLVABLE_PRIVATE_ADDRESS_TIMEOUT, }; // Commands enabled by the LL Connected Isochronous Stream feature bit. // Central and Peripheral support bits are enabled together. static std::vector ll_connected_isochronous_stream_commands_ = { - OpCodeIndex::LE_SET_CIG_PARAMETERS, - OpCodeIndex::LE_SET_CIG_PARAMETERS_TEST, - OpCodeIndex::LE_CREATE_CIS, - OpCodeIndex::LE_REMOVE_CIG, - OpCodeIndex::LE_ACCEPT_CIS_REQUEST, - OpCodeIndex::LE_REJECT_CIS_REQUEST, - OpCodeIndex::LE_SETUP_ISO_DATA_PATH, - OpCodeIndex::LE_REMOVE_ISO_DATA_PATH, - OpCodeIndex::LE_REQUEST_PEER_SCA, + OpCodeIndex::LE_SET_CIG_PARAMETERS, OpCodeIndex::LE_SET_CIG_PARAMETERS_TEST, + OpCodeIndex::LE_CREATE_CIS, OpCodeIndex::LE_REMOVE_CIG, + OpCodeIndex::LE_ACCEPT_CIS_REQUEST, OpCodeIndex::LE_REJECT_CIS_REQUEST, + OpCodeIndex::LE_SETUP_ISO_DATA_PATH, OpCodeIndex::LE_REMOVE_ISO_DATA_PATH, + OpCodeIndex::LE_REQUEST_PEER_SCA, }; -static void SetLLFeatureBit(uint64_t& le_features, LLFeaturesBits bit, - bool set) { +static void SetLLFeatureBit(uint64_t& le_features, LLFeaturesBits bit, bool set) { if (set) { le_features |= static_cast(bit); } else { @@ -1817,8 +1657,7 @@ static void SetLLFeatureBit(uint64_t& le_features, LLFeaturesBits bit, } static void SetSupportedCommandBits(std::array& supported_commands, - std::vector const& commands, - bool set) { + std::vector const& commands, bool set) { for (auto command : commands) { int index = static_cast(command); if (set) { @@ -1829,8 +1668,7 @@ static void SetSupportedCommandBits(std::array& supported_commands, } } -ControllerProperties::ControllerProperties( - rootcanal::configuration::Controller const& config) +ControllerProperties::ControllerProperties(rootcanal::configuration::Controller const& config) : strict(!config.has_strict() || config.strict()), supported_commands(std::move(SupportedCommands())), lmp_features({Page0LmpFeatures(), 0, Page2LmpFeatures()}), @@ -1853,14 +1691,13 @@ ControllerProperties::ControllerProperties( lmp_subversion = 0x5ad2; company_identifier = 0x7e8; supported_commands = std::array{ - 0x20, 0x00, 0x80, 0x00, 0x00, 0xc0, 0x00, 0x0c, 0x00, 0x00, 0x04, - 0x00, 0x00, 0x00, 0x28, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x04, 0x00, 0x00, 0xf7, 0xff, 0xff, 0x7f, 0x00, 0x00, 0x00, 0x30, - 0xf0, 0xff, 0xff, 0xff, 0xff, 0xff, 0x1f, 0xe0, 0xf7, 0xff, 0xff, - 0xff, 0xc1, 0xe3, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x20, 0x00, 0x80, 0x00, 0x00, 0xc0, 0x00, 0x0c, 0x00, 0x00, 0x04, 0x00, 0x00, + 0x00, 0x28, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0xf7, + 0xff, 0xff, 0x7f, 0x00, 0x00, 0x00, 0x30, 0xf0, 0xff, 0xff, 0xff, 0xff, 0xff, + 0x1f, 0xe0, 0xf7, 0xff, 0xff, 0xff, 0xc1, 0xe3, 0x03, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; - lmp_features = std::array { 0x6000000000, 0x0, 0x0 }; + lmp_features = std::array{0x6000000000, 0x0, 0x0}; le_features = 0x19beff017fff; le_acl_data_packet_length = 512; total_num_le_acl_data_packets = 4; @@ -1884,15 +1721,14 @@ ControllerProperties::ControllerProperties( lmp_version = bluetooth::hci::LmpVersion::V_4_2; lmp_subversion = 0x30e8; company_identifier = 0xa; - supported_commands = std::array { - 0xff, 0xff, 0xff, 0x03, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, - 0xff, 0xf3, 0x0f, 0xe8, 0xfe, 0x3f, 0xf7, 0x83, 0xff, 0x1c, 0x00, - 0x04, 0x00, 0x61, 0xf7, 0xff, 0xff, 0x7f, 0x00, 0xc0, 0xff, 0xff, - 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + supported_commands = std::array{ + 0xff, 0xff, 0xff, 0x03, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf3, + 0x0f, 0xe8, 0xfe, 0x3f, 0xf7, 0x83, 0xff, 0x1c, 0x00, 0x04, 0x00, 0x61, 0xf7, + 0xff, 0xff, 0x7f, 0x00, 0xc0, 0xff, 0xff, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; - lmp_features = std::array { 0x875b1fd87e8fffff, 0x0, 0x30f }; + lmp_features = std::array{0x875b1fd87e8fffff, 0x0, 0x30f}; acl_data_packet_length = 310; total_num_acl_data_packets = 10; sco_data_packet_length = 64; @@ -1916,40 +1752,31 @@ ControllerProperties::ControllerProperties( if (features.has_le_extended_advertising()) { SetLLFeatureBit(le_features, LLFeaturesBits::LE_EXTENDED_ADVERTISING, features.le_extended_advertising()); - SetSupportedCommandBits(supported_commands, - le_extended_advertising_commands_, + SetSupportedCommandBits(supported_commands, le_extended_advertising_commands_, features.le_extended_advertising()); } if (features.has_le_periodic_advertising()) { SetLLFeatureBit(le_features, LLFeaturesBits::LE_PERIODIC_ADVERTISING, features.le_periodic_advertising()); - SetSupportedCommandBits(supported_commands, - le_periodic_advertising_commands_, + SetSupportedCommandBits(supported_commands, le_periodic_advertising_commands_, features.le_periodic_advertising()); } if (features.has_ll_privacy()) { - SetLLFeatureBit(le_features, LLFeaturesBits::LL_PRIVACY, - features.ll_privacy()); - SetSupportedCommandBits(supported_commands, ll_privacy_commands_, - features.ll_privacy()); + SetLLFeatureBit(le_features, LLFeaturesBits::LL_PRIVACY, features.ll_privacy()); + SetSupportedCommandBits(supported_commands, ll_privacy_commands_, features.ll_privacy()); } if (features.has_le_2m_phy()) { - SetLLFeatureBit(le_features, LLFeaturesBits::LE_2M_PHY, - features.le_2m_phy()); + SetLLFeatureBit(le_features, LLFeaturesBits::LE_2M_PHY, features.le_2m_phy()); } if (features.has_le_coded_phy()) { - SetLLFeatureBit(le_features, LLFeaturesBits::LE_CODED_PHY, - features.le_coded_phy()); + SetLLFeatureBit(le_features, LLFeaturesBits::LE_CODED_PHY, features.le_coded_phy()); } if (features.has_le_connected_isochronous_stream()) { - SetLLFeatureBit(le_features, - LLFeaturesBits::CONNECTED_ISOCHRONOUS_STREAM_CENTRAL, + SetLLFeatureBit(le_features, LLFeaturesBits::CONNECTED_ISOCHRONOUS_STREAM_CENTRAL, features.le_connected_isochronous_stream()); - SetLLFeatureBit(le_features, - LLFeaturesBits::CONNECTED_ISOCHRONOUS_STREAM_PERIPHERAL, + SetLLFeatureBit(le_features, LLFeaturesBits::CONNECTED_ISOCHRONOUS_STREAM_PERIPHERAL, features.le_connected_isochronous_stream()); - SetSupportedCommandBits(supported_commands, - ll_connected_isochronous_stream_commands_, + SetSupportedCommandBits(supported_commands, ll_connected_isochronous_stream_commands_, features.le_connected_isochronous_stream()); } } @@ -1957,12 +1784,10 @@ ControllerProperties::ControllerProperties( // Apply selected quirks. if (config.has_quirks()) { if (config.quirks().has_has_default_random_address()) { - quirks.has_default_random_address = - config.quirks().has_default_random_address(); + quirks.has_default_random_address = config.quirks().has_default_random_address(); } if (config.quirks().has_hardware_error_before_reset()) { - quirks.hardware_error_before_reset = - config.quirks().hardware_error_before_reset(); + quirks.hardware_error_before_reset = config.quirks().hardware_error_before_reset(); } // TODO(b/270606199): support send_acl_data_before_connection_complete } @@ -1979,17 +1804,15 @@ ControllerProperties::ControllerProperties( } if (!CheckSupportedFeatures()) { - INFO( - "Warning: LMP and/or LE features are not consistent. Please make sure" - " that the features are correct w.r.t. the rules described" - " in Vol 2, Part C 3.5 Feature requirements"); + INFO("Warning: LMP and/or LE features are not consistent. Please make sure" + " that the features are correct w.r.t. the rules described" + " in Vol 2, Part C 3.5 Feature requirements"); } if (!CheckSupportedCommands()) { - INFO( - "Warning: supported commands are not consistent. Please make" - " sure that the supported commands are correct w.r.t. the rules" - " described in Vol 4, Part E § 3 Overview of commands and events"); + INFO("Warning: supported commands are not consistent. Please make" + " sure that the supported commands are correct w.r.t. the rules" + " described in Vol 4, Part E § 3 Overview of commands and events"); } } diff --git a/tools/rootcanal/model/controller/controller_properties.h b/tools/rootcanal/model/controller/controller_properties.h index 0a153f105d0..ed69b5a499e 100644 --- a/tools/rootcanal/model/controller/controller_properties.h +++ b/tools/rootcanal/model/controller/controller_properties.h @@ -57,7 +57,7 @@ struct ControllerQuirks { // and the capabilities of the Link Manager and Baseband in the BR/EDR // Controller. The Host device cannot modify any of these parameters. struct ControllerProperties { - public: +public: ControllerProperties(); ControllerProperties(rootcanal::configuration::Controller const&); ControllerProperties(ControllerProperties const&) = default; @@ -181,8 +181,7 @@ struct ControllerProperties { bool SupportsCommand(bluetooth::hci::OpCodeIndex op_code) const { int index = static_cast(op_code); - return (supported_commands[index / 10] & (UINT64_C(1) << (index % 10))) != - 0; + return (supported_commands[index / 10] & (UINT64_C(1) << (index % 10))) != 0; } /// Return a bit mask with all supported PHYs diff --git a/tools/rootcanal/model/controller/dual_mode_controller.cc b/tools/rootcanal/model/controller/dual_mode_controller.cc index 33782805a6b..7480496a6ea 100644 --- a/tools/rootcanal/model/controller/dual_mode_controller.cc +++ b/tools/rootcanal/model/controller/dual_mode_controller.cc @@ -52,12 +52,12 @@ constexpr uint8_t kTransmitPowerLevel = -20; constexpr bool kLeApcfTransportDiscoveryDataFilterSupported = false; constexpr bool kLeApcfAdTypeFilterSupported = true; -#define CHECK_PACKET_VIEW(view) \ - do { \ - if (!CheckPacketView(view, fmt::format("{}:{} - {}() invalid packet", \ - __FILE__, __LINE__, __func__))) { \ - return; \ - } \ +#define CHECK_PACKET_VIEW(view) \ + do { \ + if (!CheckPacketView( \ + view, fmt::format("{}:{} - {}() invalid packet", __FILE__, __LINE__, __func__))) { \ + return; \ + } \ } while (0) void DualModeController::SetProperties(ControllerProperties properties) { @@ -66,13 +66,10 @@ void DualModeController::SetProperties(ControllerProperties properties) { } // Device methods. -std::string DualModeController::GetTypeString() const { - return "Simulated Bluetooth Controller"; -} +std::string DualModeController::GetTypeString() const { return "Simulated Bluetooth Controller"; } -void DualModeController::ReceiveLinkLayerPacket( - model::packets::LinkLayerPacketView incoming, Phy::Type /*type*/, - int8_t rssi) { +void DualModeController::ReceiveLinkLayerPacket(model::packets::LinkLayerPacketView incoming, + Phy::Type /*type*/, int8_t rssi) { link_layer_controller_.IncomingPacket(incoming, rssi); } @@ -84,11 +81,10 @@ void DualModeController::Close() { } void DualModeController::SendCommandCompleteUnknownOpCodeEvent( - bluetooth::hci::OpCode op_code) const { + bluetooth::hci::OpCode op_code) const { send_event_(bluetooth::hci::CommandCompleteBuilder::Create( - kNumCommandPackets, op_code, - std::vector{ - static_cast(ErrorCode::UNKNOWN_HCI_COMMAND)})); + kNumCommandPackets, op_code, + std::vector{static_cast(ErrorCode::UNKNOWN_HCI_COMMAND)})); } DualModeController::DualModeController(ControllerProperties properties) @@ -99,15 +95,12 @@ DualModeController::DualModeController(ControllerProperties properties) // Default invalid packet handler will abort the controller // when receiving an invalid packet. - invalid_packet_handler_ = - [](uint32_t, InvalidPacketReason, std::string message, - std::vector const&) { FATAL("{}", message); }; + invalid_packet_handler_ = [](uint32_t, InvalidPacketReason, std::string message, + std::vector const&) { FATAL("{}", message); }; link_layer_controller_.RegisterRemoteChannel( - [this](std::shared_ptr packet, - Phy::Type phy_type, int8_t tx_power) { - this->SendLinkLayerPacket(packet, phy_type, tx_power); - }); + [this](std::shared_ptr packet, Phy::Type phy_type, + int8_t tx_power) { this->SendLinkLayerPacket(packet, phy_type, tx_power); }); } void DualModeController::ForwardToLm(CommandView command) { @@ -120,8 +113,7 @@ void DualModeController::ForwardToLl(CommandView command) { link_layer_controller_.ForwardToLl(command); } -void DualModeController::HandleAcl( - std::shared_ptr> packet) { +void DualModeController::HandleAcl(std::shared_ptr> packet) { auto acl_packet = bluetooth::hci::AclView::Create(pdl::packet::slice(packet)); CHECK_PACKET_VIEW(acl_packet); @@ -129,33 +121,31 @@ void DualModeController::HandleAcl( uint16_t handle = acl_packet.GetHandle(); std::vector payload(acl_packet.GetPayload()); - send_acl_(bluetooth::hci::AclBuilder::Create( - handle, acl_packet.GetPacketBoundaryFlag(), - acl_packet.GetBroadcastFlag(), std::move(payload))); + send_acl_(bluetooth::hci::AclBuilder::Create(handle, acl_packet.GetPacketBoundaryFlag(), + acl_packet.GetBroadcastFlag(), + std::move(payload))); std::vector completed_packets; bluetooth::hci::CompletedPackets cp; cp.connection_handle_ = handle; cp.host_num_of_completed_packets_ = 1; completed_packets.push_back(cp); - send_event_(bluetooth::hci::NumberOfCompletedPacketsBuilder::Create( - completed_packets)); + send_event_(bluetooth::hci::NumberOfCompletedPacketsBuilder::Create(completed_packets)); return; } link_layer_controller_.SendAclToRemote(acl_packet); } -void DualModeController::HandleSco( - std::shared_ptr> packet) { +void DualModeController::HandleSco(std::shared_ptr> packet) { auto sco_packet = bluetooth::hci::ScoView::Create(pdl::packet::slice(packet)); CHECK_PACKET_VIEW(sco_packet); if (loopback_mode_ == LoopbackMode::ENABLE_LOCAL) { uint16_t handle = sco_packet.GetHandle(); - send_sco_(bluetooth::hci::ScoBuilder::Create( - handle, sco_packet.GetPacketStatusFlag(), sco_packet.GetData())); + send_sco_(bluetooth::hci::ScoBuilder::Create(handle, sco_packet.GetPacketStatusFlag(), + sco_packet.GetData())); std::vector completed_packets; bluetooth::hci::CompletedPackets cp; @@ -163,8 +153,7 @@ void DualModeController::HandleSco( cp.host_num_of_completed_packets_ = 1; completed_packets.push_back(cp); if (link_layer_controller_.GetScoFlowControlEnable()) { - send_event_(bluetooth::hci::NumberOfCompletedPacketsBuilder::Create( - completed_packets)); + send_event_(bluetooth::hci::NumberOfCompletedPacketsBuilder::Create(completed_packets)); } return; } @@ -172,55 +161,46 @@ void DualModeController::HandleSco( link_layer_controller_.SendScoToRemote(sco_packet); } -void DualModeController::HandleIso( - std::shared_ptr> packet) { +void DualModeController::HandleIso(std::shared_ptr> packet) { auto iso = bluetooth::hci::IsoView::Create(pdl::packet::slice(packet)); CHECK_PACKET_VIEW(iso); link_layer_controller_.HandleIso(iso); } -void DualModeController::HandleCommand( - std::shared_ptr> packet) { - auto command_packet = - bluetooth::hci::CommandView::Create(pdl::packet::slice(packet)); +void DualModeController::HandleCommand(std::shared_ptr> packet) { + auto command_packet = bluetooth::hci::CommandView::Create(pdl::packet::slice(packet)); CHECK_PACKET_VIEW(command_packet); OpCode op_code = command_packet.GetOpCode(); const bool is_vendor_command = (static_cast(op_code) >> 10) == 0x3f; - const bool is_known_command = - hci_command_op_code_to_index_.count(op_code) > 0; + const bool is_known_command = hci_command_op_code_to_index_.count(op_code) > 0; const bool is_implemented_command = hci_command_handlers_.count(op_code) > 0; // HCI Read Local Supported Commands is supported by default. // Vendor commands are supported when implemented. - bool is_supported_command = - (op_code == OpCode::READ_LOCAL_SUPPORTED_COMMANDS) || - (is_vendor_command && is_implemented_command); + bool is_supported_command = (op_code == OpCode::READ_LOCAL_SUPPORTED_COMMANDS) || + (is_vendor_command && is_implemented_command); // For other commands, query the Support Commands bit mask in // the controller properties. if (!is_supported_command && is_known_command) { int index = static_cast(hci_command_op_code_to_index_.at(op_code)); - is_supported_command = (properties_.supported_commands[index / 10] & - (1U << (index % 10))) != 0; + is_supported_command = (properties_.supported_commands[index / 10] & (1U << (index % 10))) != 0; } // Loopback mode, the commands are sent back to the host. - if (loopback_mode_ == LoopbackMode::ENABLE_LOCAL && - op_code != OpCode::RESET && + if (loopback_mode_ == LoopbackMode::ENABLE_LOCAL && op_code != OpCode::RESET && op_code != OpCode::SET_CONTROLLER_TO_HOST_FLOW_CONTROL && - op_code != OpCode::HOST_BUFFER_SIZE && - op_code != OpCode::HOST_NUMBER_OF_COMPLETED_PACKETS && - op_code != OpCode::READ_BUFFER_SIZE && - op_code != OpCode::READ_LOOPBACK_MODE && + op_code != OpCode::HOST_BUFFER_SIZE && op_code != OpCode::HOST_NUMBER_OF_COMPLETED_PACKETS && + op_code != OpCode::READ_BUFFER_SIZE && op_code != OpCode::READ_LOOPBACK_MODE && op_code != OpCode::WRITE_LOOPBACK_MODE) { send_event_(bluetooth::hci::LoopbackCommandBuilder::Create( - std::vector(packet->begin(), packet->end()))); + std::vector(packet->begin(), packet->end()))); } // Quirk to reset the host stack when a command is received before the Hci // Reset command. - else if (properties_.quirks.hardware_error_before_reset && - !controller_reset_ && op_code != OpCode::RESET) { + else if (properties_.quirks.hardware_error_before_reset && !controller_reset_ && + op_code != OpCode::RESET) { WARNING(id_, "Received command {} before HCI Reset; sending the Hardware" " Error event", @@ -248,33 +228,30 @@ void DualModeController::HandleCommand( else { SendCommandCompleteUnknownOpCodeEvent(op_code); uint16_t raw_op_code = static_cast(op_code); - INFO(id_, "Unknown command, opcode: 0x{:04x}, OGF: 0x{:02x}, OCF: 0x{:03x}", - raw_op_code, (raw_op_code & 0xFC00) >> 10, raw_op_code & 0x03FF); + INFO(id_, "Unknown command, opcode: 0x{:04x}, OGF: 0x{:02x}, OCF: 0x{:03x}", raw_op_code, + (raw_op_code & 0xFC00) >> 10, raw_op_code & 0x03FF); } } void DualModeController::RegisterInvalidPacketHandler( - const std::function const&)>& handler) { + const std::function const&)>& handler) { INFO(id_, "updating the invalid packet handler"); invalid_packet_handler_ = handler; } void DualModeController::RegisterEventChannel( - const std::function>)>& - send_event) { - send_event_ = - [send_event](std::shared_ptr event) { - auto bytes = std::make_shared>(); - event->Serialize(*bytes); - send_event(bytes); - }; + const std::function>)>& send_event) { + send_event_ = [send_event](std::shared_ptr event) { + auto bytes = std::make_shared>(); + event->Serialize(*bytes); + send_event(bytes); + }; link_layer_controller_.RegisterEventChannel(send_event_); } void DualModeController::RegisterAclChannel( - const std::function>)>& - send_acl) { + const std::function>)>& send_acl) { send_acl_ = [send_acl](std::shared_ptr acl_data) { auto bytes = std::make_shared>(); acl_data->Serialize(*bytes); @@ -284,8 +261,7 @@ void DualModeController::RegisterAclChannel( } void DualModeController::RegisterScoChannel( - const std::function>)>& - send_sco) { + const std::function>)>& send_sco) { send_sco_ = [send_sco](std::shared_ptr sco_data) { auto bytes = std::make_shared>(); sco_data->Serialize(*bytes); @@ -295,8 +271,7 @@ void DualModeController::RegisterScoChannel( } void DualModeController::RegisterIsoChannel( - const std::function>)>& - send_iso) { + const std::function>)>& send_iso) { send_iso_ = [send_iso](std::shared_ptr iso_data) { auto bytes = std::make_shared>(); iso_data->Serialize(*bytes); @@ -315,8 +290,7 @@ void DualModeController::Reset(CommandView command) { loopback_mode_ = LoopbackMode::NO_LOOPBACK; controller_reset_ = true; - send_event_(bluetooth::hci::ResetCompleteBuilder::Create(kNumCommandPackets, - ErrorCode::SUCCESS)); + send_event_(bluetooth::hci::ResetCompleteBuilder::Create(kNumCommandPackets, ErrorCode::SUCCESS)); } void DualModeController::ReadBufferSize(CommandView command) { @@ -326,33 +300,30 @@ void DualModeController::ReadBufferSize(CommandView command) { DEBUG(id_, "<< Read Buffer Size"); send_event_(bluetooth::hci::ReadBufferSizeCompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS, - properties_.acl_data_packet_length, properties_.sco_data_packet_length, - properties_.total_num_acl_data_packets, - properties_.total_num_sco_data_packets)); + kNumCommandPackets, ErrorCode::SUCCESS, properties_.acl_data_packet_length, + properties_.sco_data_packet_length, properties_.total_num_acl_data_packets, + properties_.total_num_sco_data_packets)); } void DualModeController::ReadFailedContactCounter(CommandView command) { - auto command_view = - bluetooth::hci::ReadFailedContactCounterView::Create(command); + auto command_view = bluetooth::hci::ReadFailedContactCounterView::Create(command); CHECK_PACKET_VIEW(command_view); uint16_t connection_handle = command_view.GetConnectionHandle(); uint16_t failed_contact_counter = 0; ErrorCode status = link_layer_controller_.HasAclConnection(connection_handle) - ? ErrorCode::SUCCESS - : ErrorCode::UNKNOWN_CONNECTION; + ? ErrorCode::SUCCESS + : ErrorCode::UNKNOWN_CONNECTION; DEBUG(id_, "<< Read Failed Contact Counter"); DEBUG(id_, " connection_handle=0x{:x}", connection_handle); send_event_(bluetooth::hci::ReadFailedContactCounterCompleteBuilder::Create( - kNumCommandPackets, status, connection_handle, failed_contact_counter)); + kNumCommandPackets, status, connection_handle, failed_contact_counter)); } void DualModeController::ResetFailedContactCounter(CommandView command) { - auto command_view = - bluetooth::hci::ReadFailedContactCounterView::Create(command); + auto command_view = bluetooth::hci::ReadFailedContactCounterView::Create(command); CHECK_PACKET_VIEW(command_view); uint16_t connection_handle = command_view.GetConnectionHandle(); @@ -360,11 +331,11 @@ void DualModeController::ResetFailedContactCounter(CommandView command) { DEBUG(id_, " connection_handle=0x{:x}", connection_handle); ErrorCode status = link_layer_controller_.HasAclConnection(connection_handle) - ? ErrorCode::SUCCESS - : ErrorCode::UNKNOWN_CONNECTION; + ? ErrorCode::SUCCESS + : ErrorCode::UNKNOWN_CONNECTION; send_event_(bluetooth::hci::ResetFailedContactCounterCompleteBuilder::Create( - kNumCommandPackets, status, connection_handle)); + kNumCommandPackets, status, connection_handle)); } void DualModeController::ReadRssi(CommandView command) { @@ -378,22 +349,20 @@ void DualModeController::ReadRssi(CommandView command) { DEBUG(id_, " connection_handle=0x{:x}", connection_handle); ErrorCode status = link_layer_controller_.ReadRssi(connection_handle, &rssi); - send_event_(bluetooth::hci::ReadRssiCompleteBuilder::Create( - kNumCommandPackets, status, connection_handle, rssi)); + send_event_(bluetooth::hci::ReadRssiCompleteBuilder::Create(kNumCommandPackets, status, + connection_handle, rssi)); } void DualModeController::ReadEncryptionKeySize(CommandView command) { - auto command_view = - bluetooth::hci::ReadEncryptionKeySizeView::Create(command); + auto command_view = bluetooth::hci::ReadEncryptionKeySizeView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< Read Encryption Key Size"); DEBUG(id_, " connection_handle=0x{:x}", command_view.GetConnectionHandle()); send_event_(bluetooth::hci::ReadEncryptionKeySizeCompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS, - command_view.GetConnectionHandle(), - link_layer_controller_.GetEncryptionKeySize())); + kNumCommandPackets, ErrorCode::SUCCESS, command_view.GetConnectionHandle(), + link_layer_controller_.GetEncryptionKeySize())); } void DualModeController::HostBufferSize(CommandView command) { @@ -402,13 +371,12 @@ void DualModeController::HostBufferSize(CommandView command) { DEBUG(id_, "<< Host Buffer Size"); - send_event_(bluetooth::hci::HostBufferSizeCompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS)); + send_event_(bluetooth::hci::HostBufferSizeCompleteBuilder::Create(kNumCommandPackets, + ErrorCode::SUCCESS)); } void DualModeController::ReadLocalVersionInformation(CommandView command) { - auto command_view = - bluetooth::hci::ReadLocalVersionInformationView::Create(command); + auto command_view = bluetooth::hci::ReadLocalVersionInformationView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< Read Local Version Information"); @@ -420,25 +388,23 @@ void DualModeController::ReadLocalVersionInformation(CommandView command) { local_version_information.lmp_subversion_ = properties_.lmp_subversion; local_version_information.manufacturer_name_ = properties_.company_identifier; - send_event_( - bluetooth::hci::ReadLocalVersionInformationCompleteBuilder::Create( + send_event_(bluetooth::hci::ReadLocalVersionInformationCompleteBuilder::Create( kNumCommandPackets, ErrorCode::SUCCESS, local_version_information)); } void DualModeController::ReadRemoteVersionInformation(CommandView command) { - auto command_view = - bluetooth::hci::ReadRemoteVersionInformationView::Create(command); + auto command_view = bluetooth::hci::ReadRemoteVersionInformationView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< Read Remote Version Information"); DEBUG(id_, " connection_handle=0x{:x}", command_view.GetConnectionHandle()); auto status = link_layer_controller_.SendCommandToRemoteByHandle( - OpCode::READ_REMOTE_VERSION_INFORMATION, command.bytes(), - command_view.GetConnectionHandle()); + OpCode::READ_REMOTE_VERSION_INFORMATION, command.bytes(), + command_view.GetConnectionHandle()); send_event_(bluetooth::hci::ReadRemoteVersionInformationStatusBuilder::Create( - status, kNumCommandPackets)); + status, kNumCommandPackets)); } void DualModeController::ReadBdAddr(CommandView command) { @@ -447,49 +413,43 @@ void DualModeController::ReadBdAddr(CommandView command) { DEBUG(id_, "<< Read BD_ADDR"); - send_event_(bluetooth::hci::ReadBdAddrCompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS, GetAddress())); + send_event_(bluetooth::hci::ReadBdAddrCompleteBuilder::Create(kNumCommandPackets, + ErrorCode::SUCCESS, GetAddress())); } void DualModeController::ReadLocalSupportedCommands(CommandView command) { - auto command_view = - bluetooth::hci::ReadLocalSupportedCommandsView::Create(command); + auto command_view = bluetooth::hci::ReadLocalSupportedCommandsView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< Read Local Supported Commands"); send_event_(bluetooth::hci::ReadLocalSupportedCommandsCompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS, properties_.supported_commands)); + kNumCommandPackets, ErrorCode::SUCCESS, properties_.supported_commands)); } void DualModeController::ReadLocalSupportedFeatures(CommandView command) { - auto command_view = - bluetooth::hci::ReadLocalSupportedFeaturesView::Create(command); + auto command_view = bluetooth::hci::ReadLocalSupportedFeaturesView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< Read Local Supported Features"); send_event_(bluetooth::hci::ReadLocalSupportedFeaturesCompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS, - link_layer_controller_.GetLmpFeatures())); + kNumCommandPackets, ErrorCode::SUCCESS, link_layer_controller_.GetLmpFeatures())); } void DualModeController::ReadLocalSupportedCodecsV1(CommandView command) { - auto command_view = - bluetooth::hci::ReadLocalSupportedCodecsV1View::Create(command); + auto command_view = bluetooth::hci::ReadLocalSupportedCodecsV1View::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< Read Local Supported Codecs V1"); send_event_(bluetooth::hci::ReadLocalSupportedCodecsV1CompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS, - properties_.supported_standard_codecs, - properties_.supported_vendor_specific_codecs)); + kNumCommandPackets, ErrorCode::SUCCESS, properties_.supported_standard_codecs, + properties_.supported_vendor_specific_codecs)); } void DualModeController::ReadLocalExtendedFeatures(CommandView command) { - auto command_view = - bluetooth::hci::ReadLocalExtendedFeaturesView::Create(command); + auto command_view = bluetooth::hci::ReadLocalExtendedFeaturesView::Create(command); CHECK_PACKET_VIEW(command_view); uint8_t page_number = command_view.GetPageNumber(); @@ -497,14 +457,13 @@ void DualModeController::ReadLocalExtendedFeatures(CommandView command) { DEBUG(id_, " page_number={}", page_number); send_event_(bluetooth::hci::ReadLocalExtendedFeaturesCompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS, page_number, - link_layer_controller_.GetMaxLmpFeaturesPageNumber(), - link_layer_controller_.GetLmpFeatures(page_number))); + kNumCommandPackets, ErrorCode::SUCCESS, page_number, + link_layer_controller_.GetMaxLmpFeaturesPageNumber(), + link_layer_controller_.GetLmpFeatures(page_number))); } void DualModeController::ReadRemoteExtendedFeatures(CommandView command) { - auto command_view = - bluetooth::hci::ReadRemoteExtendedFeaturesView::Create(command); + auto command_view = bluetooth::hci::ReadRemoteExtendedFeaturesView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< Read Remote Extended Features"); @@ -512,11 +471,11 @@ void DualModeController::ReadRemoteExtendedFeatures(CommandView command) { DEBUG(id_, " page_number={}", command_view.GetPageNumber()); auto status = link_layer_controller_.SendCommandToRemoteByHandle( - OpCode::READ_REMOTE_EXTENDED_FEATURES, command_view.bytes(), - command_view.GetConnectionHandle()); + OpCode::READ_REMOTE_EXTENDED_FEATURES, command_view.bytes(), + command_view.GetConnectionHandle()); - send_event_(bluetooth::hci::ReadRemoteExtendedFeaturesStatusBuilder::Create( - status, kNumCommandPackets)); + send_event_(bluetooth::hci::ReadRemoteExtendedFeaturesStatusBuilder::Create(status, + kNumCommandPackets)); } void DualModeController::SwitchRole(CommandView command) { @@ -527,27 +486,24 @@ void DualModeController::SwitchRole(CommandView command) { DEBUG(id_, " bd_addr={}", command_view.GetBdAddr()); DEBUG(id_, " role={}", bluetooth::hci::RoleText(command_view.GetRole())); - auto status = link_layer_controller_.SwitchRole(command_view.GetBdAddr(), - command_view.GetRole()); + auto status = link_layer_controller_.SwitchRole(command_view.GetBdAddr(), command_view.GetRole()); - send_event_(bluetooth::hci::SwitchRoleStatusBuilder::Create( - status, kNumCommandPackets)); + send_event_(bluetooth::hci::SwitchRoleStatusBuilder::Create(status, kNumCommandPackets)); } void DualModeController::ReadRemoteSupportedFeatures(CommandView command) { - auto command_view = - bluetooth::hci::ReadRemoteSupportedFeaturesView::Create(command); + auto command_view = bluetooth::hci::ReadRemoteSupportedFeaturesView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< Read Remote Supported Features"); DEBUG(id_, " connection_handle=0x{:x}", command_view.GetConnectionHandle()); auto status = link_layer_controller_.SendCommandToRemoteByHandle( - OpCode::READ_REMOTE_SUPPORTED_FEATURES, command_view.bytes(), - command_view.GetConnectionHandle()); + OpCode::READ_REMOTE_SUPPORTED_FEATURES, command_view.bytes(), + command_view.GetConnectionHandle()); - send_event_(bluetooth::hci::ReadRemoteSupportedFeaturesStatusBuilder::Create( - status, kNumCommandPackets)); + send_event_(bluetooth::hci::ReadRemoteSupportedFeaturesStatusBuilder::Create(status, + kNumCommandPackets)); } void DualModeController::ReadClockOffset(CommandView command) { @@ -559,11 +515,10 @@ void DualModeController::ReadClockOffset(CommandView command) { uint16_t handle = command_view.GetConnectionHandle(); - auto status = link_layer_controller_.SendCommandToRemoteByHandle( - OpCode::READ_CLOCK_OFFSET, command_view.bytes(), handle); + auto status = link_layer_controller_.SendCommandToRemoteByHandle(OpCode::READ_CLOCK_OFFSET, + command_view.bytes(), handle); - send_event_(bluetooth::hci::ReadClockOffsetStatusBuilder::Create( - status, kNumCommandPackets)); + send_event_(bluetooth::hci::ReadClockOffsetStatusBuilder::Create(status, kNumCommandPackets)); } // Deprecated command, removed in v4.2. @@ -577,16 +532,13 @@ void DualModeController::AddScoConnection(CommandView command) { DEBUG(id_, " packet_type=0x{:x}", command_view.GetPacketType()); auto status = link_layer_controller_.AddScoConnection( - command_view.GetConnectionHandle(), command_view.GetPacketType(), - ScoDatapath::NORMAL); + command_view.GetConnectionHandle(), command_view.GetPacketType(), ScoDatapath::NORMAL); - send_event_(bluetooth::hci::AddScoConnectionStatusBuilder::Create( - status, kNumCommandPackets)); + send_event_(bluetooth::hci::AddScoConnectionStatusBuilder::Create(status, kNumCommandPackets)); } void DualModeController::SetupSynchronousConnection(CommandView command) { - auto command_view = - bluetooth::hci::SetupSynchronousConnectionView::Create(command); + auto command_view = bluetooth::hci::SetupSynchronousConnectionView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< Setup Synchronous Connection"); @@ -594,19 +546,18 @@ void DualModeController::SetupSynchronousConnection(CommandView command) { DEBUG(id_, " packet_type=0x{:x}", command_view.GetPacketType()); auto status = link_layer_controller_.SetupSynchronousConnection( - command_view.GetConnectionHandle(), command_view.GetTransmitBandwidth(), - command_view.GetReceiveBandwidth(), command_view.GetMaxLatency(), - command_view.GetVoiceSetting(), - static_cast(command_view.GetRetransmissionEffort()), - command_view.GetPacketType(), ScoDatapath::NORMAL); + command_view.GetConnectionHandle(), command_view.GetTransmitBandwidth(), + command_view.GetReceiveBandwidth(), command_view.GetMaxLatency(), + command_view.GetVoiceSetting(), + static_cast(command_view.GetRetransmissionEffort()), + command_view.GetPacketType(), ScoDatapath::NORMAL); - send_event_(bluetooth::hci::SetupSynchronousConnectionStatusBuilder::Create( - status, kNumCommandPackets)); + send_event_(bluetooth::hci::SetupSynchronousConnectionStatusBuilder::Create(status, + kNumCommandPackets)); } void DualModeController::AcceptSynchronousConnection(CommandView command) { - auto command_view = - bluetooth::hci::AcceptSynchronousConnectionView::Create(command); + auto command_view = bluetooth::hci::AcceptSynchronousConnectionView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< Accept Synchronous Connection"); @@ -614,20 +565,18 @@ void DualModeController::AcceptSynchronousConnection(CommandView command) { DEBUG(id_, " packet_type=0x{:x}", command_view.GetPacketType()); auto status = link_layer_controller_.AcceptSynchronousConnection( - command_view.GetBdAddr(), command_view.GetTransmitBandwidth(), - command_view.GetReceiveBandwidth(), command_view.GetMaxLatency(), - command_view.GetVoiceSetting(), - static_cast(command_view.GetRetransmissionEffort()), - command_view.GetPacketType()); + command_view.GetBdAddr(), command_view.GetTransmitBandwidth(), + command_view.GetReceiveBandwidth(), command_view.GetMaxLatency(), + command_view.GetVoiceSetting(), + static_cast(command_view.GetRetransmissionEffort()), + command_view.GetPacketType()); - send_event_(bluetooth::hci::AcceptSynchronousConnectionStatusBuilder::Create( - status, kNumCommandPackets)); + send_event_(bluetooth::hci::AcceptSynchronousConnectionStatusBuilder::Create(status, + kNumCommandPackets)); } -void DualModeController::EnhancedSetupSynchronousConnection( - CommandView command) { - auto command_view = - bluetooth::hci::EnhancedSetupSynchronousConnectionView::Create(command); +void DualModeController::EnhancedSetupSynchronousConnection(CommandView command) { + auto command_view = bluetooth::hci::EnhancedSetupSynchronousConnectionView::Create(command); auto status = ErrorCode::SUCCESS; CHECK_PACKET_VIEW(command_view); @@ -639,11 +588,10 @@ void DualModeController::EnhancedSetupSynchronousConnection( // to be equal. auto transmit_coding_format = command_view.GetTransmitCodingFormat(); auto receive_coding_format = command_view.GetReceiveCodingFormat(); - if (transmit_coding_format.coding_format_ != - receive_coding_format.coding_format_ || + if (transmit_coding_format.coding_format_ != receive_coding_format.coding_format_ || transmit_coding_format.company_id_ != receive_coding_format.company_id_ || transmit_coding_format.vendor_specific_codec_id_ != - receive_coding_format.vendor_specific_codec_id_) { + receive_coding_format.vendor_specific_codec_id_) { INFO(id_, "EnhancedSetupSynchronousConnection: rejected Transmit_Coding_Format " "({}) and Receive_Coding_Format ({}) as they are not equal", @@ -655,13 +603,11 @@ void DualModeController::EnhancedSetupSynchronousConnection( // to be equal, or shall set one of them to be zero and the other non-zero. auto input_bandwidth = command_view.GetInputBandwidth(); auto output_bandwidth = command_view.GetOutputBandwidth(); - if (input_bandwidth != output_bandwidth && input_bandwidth != 0 && - output_bandwidth != 0) { - INFO( - id_, - "EnhancedSetupSynchronousConnection: rejected Input_Bandwidth ({})" - " and Output_Bandwidth ({}) as they are not equal and different from 0", - input_bandwidth, output_bandwidth); + if (input_bandwidth != output_bandwidth && input_bandwidth != 0 && output_bandwidth != 0) { + INFO(id_, + "EnhancedSetupSynchronousConnection: rejected Input_Bandwidth ({})" + " and Output_Bandwidth ({}) as they are not equal and different from 0", + input_bandwidth, output_bandwidth); status = ErrorCode::INVALID_HCI_COMMAND_PARAMETERS; } @@ -669,11 +615,10 @@ void DualModeController::EnhancedSetupSynchronousConnection( // to be equal. auto input_coding_format = command_view.GetInputCodingFormat(); auto output_coding_format = command_view.GetOutputCodingFormat(); - if (input_coding_format.coding_format_ != - output_coding_format.coding_format_ || + if (input_coding_format.coding_format_ != output_coding_format.coding_format_ || input_coding_format.company_id_ != output_coding_format.company_id_ || input_coding_format.vendor_specific_codec_id_ != - output_coding_format.vendor_specific_codec_id_) { + output_coding_format.vendor_specific_codec_id_) { INFO(id_, "EnhancedSetupSynchronousConnection: rejected Input_Coding_Format ({})" " and Output_Coding_Format ({}) as they are not equal", @@ -701,10 +646,8 @@ void DualModeController::EnhancedSetupSynchronousConnection( // Controller shall not modify the data sent to the remote device. auto transmit_bandwidth = command_view.GetTransmitBandwidth(); auto receive_bandwidth = command_view.GetReceiveBandwidth(); - if (transmit_coding_format.coding_format_ == - bluetooth::hci::ScoCodingFormatValues::TRANSPARENT && - input_coding_format.coding_format_ == - bluetooth::hci::ScoCodingFormatValues::TRANSPARENT && + if (transmit_coding_format.coding_format_ == bluetooth::hci::ScoCodingFormatValues::TRANSPARENT && + input_coding_format.coding_format_ == bluetooth::hci::ScoCodingFormatValues::TRANSPARENT && transmit_bandwidth != input_bandwidth) { INFO(id_, "EnhancedSetupSynchronousConnection: rejected Transmit_Bandwidth ({})" @@ -718,8 +661,7 @@ void DualModeController::EnhancedSetupSynchronousConnection( } if ((transmit_coding_format.coding_format_ == bluetooth::hci::ScoCodingFormatValues::TRANSPARENT) != - (input_coding_format.coding_format_ == - bluetooth::hci::ScoCodingFormatValues::TRANSPARENT)) { + (input_coding_format.coding_format_ == bluetooth::hci::ScoCodingFormatValues::TRANSPARENT)) { INFO(id_, "EnhancedSetupSynchronousConnection: rejected Transmit_Coding_Format " "({}) and Input_Coding_Format ({}) as they are incompatible", @@ -731,10 +673,8 @@ void DualModeController::EnhancedSetupSynchronousConnection( // be “transparent” or neither shall be. If both are “transparent”, the // Receive_Bandwidth and the Output_Bandwidth shall be the same and the // Controller shall not modify the data sent to the Host. - if (receive_coding_format.coding_format_ == - bluetooth::hci::ScoCodingFormatValues::TRANSPARENT && - output_coding_format.coding_format_ == - bluetooth::hci::ScoCodingFormatValues::TRANSPARENT && + if (receive_coding_format.coding_format_ == bluetooth::hci::ScoCodingFormatValues::TRANSPARENT && + output_coding_format.coding_format_ == bluetooth::hci::ScoCodingFormatValues::TRANSPARENT && receive_bandwidth != output_bandwidth) { INFO(id_, "EnhancedSetupSynchronousConnection: rejected Receive_Bandwidth ({})" @@ -748,8 +688,7 @@ void DualModeController::EnhancedSetupSynchronousConnection( } if ((receive_coding_format.coding_format_ == bluetooth::hci::ScoCodingFormatValues::TRANSPARENT) != - (output_coding_format.coding_format_ == - bluetooth::hci::ScoCodingFormatValues::TRANSPARENT)) { + (output_coding_format.coding_format_ == bluetooth::hci::ScoCodingFormatValues::TRANSPARENT)) { INFO(id_, "EnhancedSetupSynchronousConnection: rejected Receive_Coding_Format " "({}) and Output_Coding_Format ({}) as they are incompatible", @@ -759,22 +698,18 @@ void DualModeController::EnhancedSetupSynchronousConnection( if (status == ErrorCode::SUCCESS) { status = link_layer_controller_.SetupSynchronousConnection( - command_view.GetConnectionHandle(), transmit_bandwidth, - receive_bandwidth, command_view.GetMaxLatency(), - link_layer_controller_.GetVoiceSetting(), - static_cast(command_view.GetRetransmissionEffort()), - command_view.GetPacketType(), datapath); + command_view.GetConnectionHandle(), transmit_bandwidth, receive_bandwidth, + command_view.GetMaxLatency(), link_layer_controller_.GetVoiceSetting(), + static_cast(command_view.GetRetransmissionEffort()), + command_view.GetPacketType(), datapath); } - send_event_( - bluetooth::hci::EnhancedSetupSynchronousConnectionStatusBuilder::Create( + send_event_(bluetooth::hci::EnhancedSetupSynchronousConnectionStatusBuilder::Create( status, kNumCommandPackets)); } -void DualModeController::EnhancedAcceptSynchronousConnection( - CommandView command) { - auto command_view = - bluetooth::hci::EnhancedAcceptSynchronousConnectionView::Create(command); +void DualModeController::EnhancedAcceptSynchronousConnection(CommandView command) { + auto command_view = bluetooth::hci::EnhancedAcceptSynchronousConnectionView::Create(command); auto status = ErrorCode::SUCCESS; CHECK_PACKET_VIEW(command_view); @@ -786,11 +721,10 @@ void DualModeController::EnhancedAcceptSynchronousConnection( // to be equal. auto transmit_coding_format = command_view.GetTransmitCodingFormat(); auto receive_coding_format = command_view.GetReceiveCodingFormat(); - if (transmit_coding_format.coding_format_ != - receive_coding_format.coding_format_ || + if (transmit_coding_format.coding_format_ != receive_coding_format.coding_format_ || transmit_coding_format.company_id_ != receive_coding_format.company_id_ || transmit_coding_format.vendor_specific_codec_id_ != - receive_coding_format.vendor_specific_codec_id_) { + receive_coding_format.vendor_specific_codec_id_) { INFO(id_, "EnhancedAcceptSynchronousConnection: rejected Transmit_Coding_Format " "({})" @@ -803,13 +737,11 @@ void DualModeController::EnhancedAcceptSynchronousConnection( // to be equal, or shall set one of them to be zero and the other non-zero. auto input_bandwidth = command_view.GetInputBandwidth(); auto output_bandwidth = command_view.GetOutputBandwidth(); - if (input_bandwidth != output_bandwidth && input_bandwidth != 0 && - output_bandwidth != 0) { - INFO( - id_, - "EnhancedAcceptSynchronousConnection: rejected Input_Bandwidth ({})" - " and Output_Bandwidth ({}) as they are not equal and different from 0", - input_bandwidth, output_bandwidth); + if (input_bandwidth != output_bandwidth && input_bandwidth != 0 && output_bandwidth != 0) { + INFO(id_, + "EnhancedAcceptSynchronousConnection: rejected Input_Bandwidth ({})" + " and Output_Bandwidth ({}) as they are not equal and different from 0", + input_bandwidth, output_bandwidth); status = ErrorCode::INVALID_HCI_COMMAND_PARAMETERS; } @@ -817,16 +749,14 @@ void DualModeController::EnhancedAcceptSynchronousConnection( // to be equal. auto input_coding_format = command_view.GetInputCodingFormat(); auto output_coding_format = command_view.GetOutputCodingFormat(); - if (input_coding_format.coding_format_ != - output_coding_format.coding_format_ || + if (input_coding_format.coding_format_ != output_coding_format.coding_format_ || input_coding_format.company_id_ != output_coding_format.company_id_ || input_coding_format.vendor_specific_codec_id_ != - output_coding_format.vendor_specific_codec_id_) { - INFO( - id_, - "EnhancedAcceptSynchronousConnection: rejected Input_Coding_Format ({})" - " and Output_Coding_Format ({}) as they are not equal", - input_coding_format.ToString(), output_coding_format.ToString()); + output_coding_format.vendor_specific_codec_id_) { + INFO(id_, + "EnhancedAcceptSynchronousConnection: rejected Input_Coding_Format ({})" + " and Output_Coding_Format ({}) as they are not equal", + input_coding_format.ToString(), output_coding_format.ToString()); status = ErrorCode::INVALID_HCI_COMMAND_PARAMETERS; } @@ -848,10 +778,8 @@ void DualModeController::EnhancedAcceptSynchronousConnection( // Controller shall not modify the data sent to the remote device. auto transmit_bandwidth = command_view.GetTransmitBandwidth(); auto receive_bandwidth = command_view.GetReceiveBandwidth(); - if (transmit_coding_format.coding_format_ == - bluetooth::hci::ScoCodingFormatValues::TRANSPARENT && - input_coding_format.coding_format_ == - bluetooth::hci::ScoCodingFormatValues::TRANSPARENT && + if (transmit_coding_format.coding_format_ == bluetooth::hci::ScoCodingFormatValues::TRANSPARENT && + input_coding_format.coding_format_ == bluetooth::hci::ScoCodingFormatValues::TRANSPARENT && transmit_bandwidth != input_bandwidth) { INFO(id_, "EnhancedSetupSynchronousConnection: rejected Transmit_Bandwidth ({})" @@ -865,8 +793,7 @@ void DualModeController::EnhancedAcceptSynchronousConnection( } if ((transmit_coding_format.coding_format_ == bluetooth::hci::ScoCodingFormatValues::TRANSPARENT) != - (input_coding_format.coding_format_ == - bluetooth::hci::ScoCodingFormatValues::TRANSPARENT)) { + (input_coding_format.coding_format_ == bluetooth::hci::ScoCodingFormatValues::TRANSPARENT)) { INFO(id_, "EnhancedSetupSynchronousConnection: rejected Transmit_Coding_Format " "({}) and Input_Coding_Format ({}) as they are incompatible", @@ -878,10 +805,8 @@ void DualModeController::EnhancedAcceptSynchronousConnection( // be “transparent” or neither shall be. If both are “transparent”, the // Receive_Bandwidth and the Output_Bandwidth shall be the same and the // Controller shall not modify the data sent to the Host. - if (receive_coding_format.coding_format_ == - bluetooth::hci::ScoCodingFormatValues::TRANSPARENT && - output_coding_format.coding_format_ == - bluetooth::hci::ScoCodingFormatValues::TRANSPARENT && + if (receive_coding_format.coding_format_ == bluetooth::hci::ScoCodingFormatValues::TRANSPARENT && + output_coding_format.coding_format_ == bluetooth::hci::ScoCodingFormatValues::TRANSPARENT && receive_bandwidth != output_bandwidth) { INFO(id_, "EnhancedSetupSynchronousConnection: rejected Receive_Bandwidth ({})" @@ -895,8 +820,7 @@ void DualModeController::EnhancedAcceptSynchronousConnection( } if ((receive_coding_format.coding_format_ == bluetooth::hci::ScoCodingFormatValues::TRANSPARENT) != - (output_coding_format.coding_format_ == - bluetooth::hci::ScoCodingFormatValues::TRANSPARENT)) { + (output_coding_format.coding_format_ == bluetooth::hci::ScoCodingFormatValues::TRANSPARENT)) { INFO(id_, "EnhancedSetupSynchronousConnection: rejected Receive_Coding_Format " "({}) and Output_Coding_Format ({}) as they are incompatible", @@ -906,47 +830,40 @@ void DualModeController::EnhancedAcceptSynchronousConnection( if (status == ErrorCode::SUCCESS) { status = link_layer_controller_.AcceptSynchronousConnection( - command_view.GetBdAddr(), transmit_bandwidth, receive_bandwidth, - command_view.GetMaxLatency(), link_layer_controller_.GetVoiceSetting(), - static_cast(command_view.GetRetransmissionEffort()), - command_view.GetPacketType()); + command_view.GetBdAddr(), transmit_bandwidth, receive_bandwidth, + command_view.GetMaxLatency(), link_layer_controller_.GetVoiceSetting(), + static_cast(command_view.GetRetransmissionEffort()), + command_view.GetPacketType()); } - send_event_( - bluetooth::hci::EnhancedAcceptSynchronousConnectionStatusBuilder::Create( + send_event_(bluetooth::hci::EnhancedAcceptSynchronousConnectionStatusBuilder::Create( status, kNumCommandPackets)); } void DualModeController::RejectSynchronousConnection(CommandView command) { - auto command_view = - bluetooth::hci::RejectSynchronousConnectionView::Create(command); + auto command_view = bluetooth::hci::RejectSynchronousConnectionView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< Reject Synchronous Connection"); DEBUG(id_, " bd_addr={}", command_view.GetBdAddr()); - DEBUG(id_, " reason={}", - bluetooth::hci::RejectConnectionReasonText(command_view.GetReason())); + DEBUG(id_, " reason={}", bluetooth::hci::RejectConnectionReasonText(command_view.GetReason())); auto status = link_layer_controller_.RejectSynchronousConnection( - command_view.GetBdAddr(), (uint16_t)command_view.GetReason()); + command_view.GetBdAddr(), (uint16_t)command_view.GetReason()); - send_event_(bluetooth::hci::RejectSynchronousConnectionStatusBuilder::Create( - status, kNumCommandPackets)); + send_event_(bluetooth::hci::RejectSynchronousConnectionStatusBuilder::Create(status, + kNumCommandPackets)); } -void DualModeController::ReadInquiryResponseTransmitPowerLevel( - CommandView command) { - auto command_view = - bluetooth::hci::ReadInquiryResponseTransmitPowerLevelView::Create( - command); +void DualModeController::ReadInquiryResponseTransmitPowerLevel(CommandView command) { + auto command_view = bluetooth::hci::ReadInquiryResponseTransmitPowerLevelView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< Read Inquiry Response Transmit Power Level"); uint8_t tx_power = 20; // maximum - send_event_( - bluetooth::hci::ReadInquiryResponseTransmitPowerLevelCompleteBuilder:: - Create(kNumCommandPackets, ErrorCode::SUCCESS, tx_power)); + send_event_(bluetooth::hci::ReadInquiryResponseTransmitPowerLevelCompleteBuilder::Create( + kNumCommandPackets, ErrorCode::SUCCESS, tx_power)); } void DualModeController::EnhancedFlush(CommandView command) { @@ -957,14 +874,13 @@ void DualModeController::EnhancedFlush(CommandView command) { DEBUG(id_, " connection_handle=0x{:x}", command_view.GetConnectionHandle()); auto handle = command_view.GetConnectionHandle(); - send_event_(bluetooth::hci::EnhancedFlushStatusBuilder::Create( - ErrorCode::SUCCESS, kNumCommandPackets)); + send_event_(bluetooth::hci::EnhancedFlushStatusBuilder::Create(ErrorCode::SUCCESS, + kNumCommandPackets)); // TODO: When adding a queue of ACL packets. // Send the Enhanced Flush Complete event after discarding // all L2CAP packets identified by the Packet Type. - if (link_layer_controller_.IsEventUnmasked( - bluetooth::hci::EventCode::ENHANCED_FLUSH_COMPLETE)) { + if (link_layer_controller_.IsEventUnmasked(bluetooth::hci::EventCode::ENHANCED_FLUSH_COMPLETE)) { send_event_(bluetooth::hci::EnhancedFlushCompleteBuilder::Create(handle)); } } @@ -977,8 +893,8 @@ void DualModeController::SetEventMaskPage2(CommandView command) { DEBUG(id_, " event_mask_page_2=0x{:x}", command_view.GetEventMaskPage2()); link_layer_controller_.SetEventMaskPage2(command_view.GetEventMaskPage2()); - send_event_(bluetooth::hci::SetEventMaskPage2CompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS)); + send_event_(bluetooth::hci::SetEventMaskPage2CompleteBuilder::Create(kNumCommandPackets, + ErrorCode::SUCCESS)); } void DualModeController::ReadLocalOobData(CommandView command) { @@ -990,8 +906,7 @@ void DualModeController::ReadLocalOobData(CommandView command) { } void DualModeController::ReadLocalOobExtendedData(CommandView command) { - auto command_view = - bluetooth::hci::ReadLocalOobExtendedDataView::Create(command); + auto command_view = bluetooth::hci::ReadLocalOobExtendedDataView::Create(command); DEBUG(id_, "<< Read Local Oob Extended Data"); @@ -999,24 +914,21 @@ void DualModeController::ReadLocalOobExtendedData(CommandView command) { } void DualModeController::WriteSimplePairingMode(CommandView command) { - auto command_view = - bluetooth::hci::WriteSimplePairingModeView::Create(command); + auto command_view = bluetooth::hci::WriteSimplePairingModeView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< Write Simple Pairing Mode"); DEBUG(id_, " simple_pairing_mode={}", command_view.GetSimplePairingMode() == bluetooth::hci::Enable::ENABLED); - auto enabled = - command_view.GetSimplePairingMode() == bluetooth::hci::Enable::ENABLED; + auto enabled = command_view.GetSimplePairingMode() == bluetooth::hci::Enable::ENABLED; link_layer_controller_.SetSecureSimplePairingSupport(enabled); - send_event_(bluetooth::hci::WriteSimplePairingModeCompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS)); + send_event_(bluetooth::hci::WriteSimplePairingModeCompleteBuilder::Create(kNumCommandPackets, + ErrorCode::SUCCESS)); } void DualModeController::ChangeConnectionPacketType(CommandView command) { - auto command_view = - bluetooth::hci::ChangeConnectionPacketTypeView::Create(command); + auto command_view = bluetooth::hci::ChangeConnectionPacketTypeView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< Change Connection Packet Type"); @@ -1026,10 +938,9 @@ void DualModeController::ChangeConnectionPacketType(CommandView command) { uint16_t handle = command_view.GetConnectionHandle(); uint16_t packet_type = static_cast(command_view.GetPacketType()); - auto status = - link_layer_controller_.ChangeConnectionPacketType(handle, packet_type); - send_event_(bluetooth::hci::ChangeConnectionPacketTypeStatusBuilder::Create( - status, kNumCommandPackets)); + auto status = link_layer_controller_.ChangeConnectionPacketType(handle, packet_type); + send_event_(bluetooth::hci::ChangeConnectionPacketTypeStatusBuilder::Create(status, + kNumCommandPackets)); } void DualModeController::WriteLeHostSupport(CommandView command) { @@ -1040,29 +951,23 @@ void DualModeController::WriteLeHostSupport(CommandView command) { DEBUG(id_, " le_supported_host={}", command_view.GetLeSupportedHost() == bluetooth::hci::Enable::ENABLED); - auto le_support = - command_view.GetLeSupportedHost() == bluetooth::hci::Enable::ENABLED; + auto le_support = command_view.GetLeSupportedHost() == bluetooth::hci::Enable::ENABLED; link_layer_controller_.SetLeHostSupport(le_support); - send_event_(bluetooth::hci::WriteLeHostSupportCompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS)); + send_event_(bluetooth::hci::WriteLeHostSupportCompleteBuilder::Create(kNumCommandPackets, + ErrorCode::SUCCESS)); } -void DualModeController::WriteSecureConnectionsHostSupport( - CommandView command) { - auto command_view = - bluetooth::hci::WriteSecureConnectionsHostSupportView::Create(command); +void DualModeController::WriteSecureConnectionsHostSupport(CommandView command) { + auto command_view = bluetooth::hci::WriteSecureConnectionsHostSupportView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< Write Secure Connections Host Support"); DEBUG(id_, " secure_connections_host_support={}", - command_view.GetSecureConnectionsHostSupport() == - bluetooth::hci::Enable::ENABLED); + command_view.GetSecureConnectionsHostSupport() == bluetooth::hci::Enable::ENABLED); link_layer_controller_.SetSecureConnectionsSupport( - command_view.GetSecureConnectionsHostSupport() == - bluetooth::hci::Enable::ENABLED); - send_event_( - bluetooth::hci::WriteSecureConnectionsHostSupportCompleteBuilder::Create( + command_view.GetSecureConnectionsHostSupport() == bluetooth::hci::Enable::ENABLED); + send_event_(bluetooth::hci::WriteSecureConnectionsHostSupportCompleteBuilder::Create( kNumCommandPackets, ErrorCode::SUCCESS)); } @@ -1074,8 +979,8 @@ void DualModeController::SetEventMask(CommandView command) { DEBUG(id_, " event_mask=0x{:x}", command_view.GetEventMask()); link_layer_controller_.SetEventMask(command_view.GetEventMask()); - send_event_(bluetooth::hci::SetEventMaskCompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS)); + send_event_(bluetooth::hci::SetEventMaskCompleteBuilder::Create(kNumCommandPackets, + ErrorCode::SUCCESS)); } void DualModeController::ReadInquiryMode(CommandView command) { @@ -1084,10 +989,9 @@ void DualModeController::ReadInquiryMode(CommandView command) { DEBUG(id_, "<< Read Inquiry Mode"); - bluetooth::hci::InquiryMode inquiry_mode = - bluetooth::hci::InquiryMode::STANDARD; + bluetooth::hci::InquiryMode inquiry_mode = bluetooth::hci::InquiryMode::STANDARD; send_event_(bluetooth::hci::ReadInquiryModeCompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS, inquiry_mode)); + kNumCommandPackets, ErrorCode::SUCCESS, inquiry_mode)); } void DualModeController::WriteInquiryMode(CommandView command) { @@ -1095,13 +999,11 @@ void DualModeController::WriteInquiryMode(CommandView command) { CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< Write Inquiry Mode"); - DEBUG(id_, " inquiry_mode={}", - bluetooth::hci::InquiryModeText(command_view.GetInquiryMode())); + DEBUG(id_, " inquiry_mode={}", bluetooth::hci::InquiryModeText(command_view.GetInquiryMode())); - link_layer_controller_.SetInquiryMode( - static_cast(command_view.GetInquiryMode())); - send_event_(bluetooth::hci::WriteInquiryModeCompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS)); + link_layer_controller_.SetInquiryMode(static_cast(command_view.GetInquiryMode())); + send_event_(bluetooth::hci::WriteInquiryModeCompleteBuilder::Create(kNumCommandPackets, + ErrorCode::SUCCESS)); } void DualModeController::ReadPageScanType(CommandView command) { @@ -1110,10 +1012,9 @@ void DualModeController::ReadPageScanType(CommandView command) { DEBUG(id_, "<< Read Page Scan Type"); - bluetooth::hci::PageScanType page_scan_type = - bluetooth::hci::PageScanType::STANDARD; + bluetooth::hci::PageScanType page_scan_type = bluetooth::hci::PageScanType::STANDARD; send_event_(bluetooth::hci::ReadPageScanTypeCompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS, page_scan_type)); + kNumCommandPackets, ErrorCode::SUCCESS, page_scan_type)); } void DualModeController::WritePageScanType(CommandView command) { @@ -1124,8 +1025,8 @@ void DualModeController::WritePageScanType(CommandView command) { DEBUG(id_, " page_scan_type={}", bluetooth::hci::PageScanTypeText(command_view.GetPageScanType())); - send_event_(bluetooth::hci::WritePageScanTypeCompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS)); + send_event_(bluetooth::hci::WritePageScanTypeCompleteBuilder::Create(kNumCommandPackets, + ErrorCode::SUCCESS)); } void DualModeController::ReadInquiryScanType(CommandView command) { @@ -1134,10 +1035,9 @@ void DualModeController::ReadInquiryScanType(CommandView command) { DEBUG(id_, "<< Read Inquiry Scan Type"); - bluetooth::hci::InquiryScanType inquiry_scan_type = - bluetooth::hci::InquiryScanType::STANDARD; + bluetooth::hci::InquiryScanType inquiry_scan_type = bluetooth::hci::InquiryScanType::STANDARD; send_event_(bluetooth::hci::ReadInquiryScanTypeCompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS, inquiry_scan_type)); + kNumCommandPackets, ErrorCode::SUCCESS, inquiry_scan_type)); } void DualModeController::WriteInquiryScanType(CommandView command) { @@ -1148,13 +1048,12 @@ void DualModeController::WriteInquiryScanType(CommandView command) { DEBUG(id_, " inquiry_scan_type={}", bluetooth::hci::InquiryScanTypeText(command_view.GetInquiryScanType())); - send_event_(bluetooth::hci::WriteInquiryScanTypeCompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS)); + send_event_(bluetooth::hci::WriteInquiryScanTypeCompleteBuilder::Create(kNumCommandPackets, + ErrorCode::SUCCESS)); } void DualModeController::ChangeConnectionLinkKey(CommandView command) { - auto command_view = - bluetooth::hci::ChangeConnectionLinkKeyView::Create(command); + auto command_view = bluetooth::hci::ChangeConnectionLinkKeyView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< Change Connection Link Key"); @@ -1163,8 +1062,8 @@ void DualModeController::ChangeConnectionLinkKey(CommandView command) { uint16_t handle = command_view.GetConnectionHandle(); auto status = link_layer_controller_.ChangeConnectionLinkKey(handle); - send_event_(bluetooth::hci::ChangeConnectionLinkKeyStatusBuilder::Create( - status, kNumCommandPackets)); + send_event_( + bluetooth::hci::ChangeConnectionLinkKeyStatusBuilder::Create(status, kNumCommandPackets)); } void DualModeController::CentralLinkKey(CommandView command) { @@ -1172,43 +1071,37 @@ void DualModeController::CentralLinkKey(CommandView command) { CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< Central Link Key"); - DEBUG(id_, " key_flag={}", - bluetooth::hci::KeyFlagText(command_view.GetKeyFlag())); + DEBUG(id_, " key_flag={}", bluetooth::hci::KeyFlagText(command_view.GetKeyFlag())); uint8_t key_flag = static_cast(command_view.GetKeyFlag()); auto status = link_layer_controller_.CentralLinkKey(key_flag); - send_event_(bluetooth::hci::CentralLinkKeyStatusBuilder::Create( - status, kNumCommandPackets)); + send_event_(bluetooth::hci::CentralLinkKeyStatusBuilder::Create(status, kNumCommandPackets)); } void DualModeController::WriteAuthenticationEnable(CommandView command) { - auto command_view = - bluetooth::hci::WriteAuthenticationEnableView::Create(command); + auto command_view = bluetooth::hci::WriteAuthenticationEnableView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< Write Authentication Enable"); DEBUG(id_, " authentication_enable={}", - bluetooth::hci::AuthenticationEnableText( - command_view.GetAuthenticationEnable())); + bluetooth::hci::AuthenticationEnableText(command_view.GetAuthenticationEnable())); - link_layer_controller_.SetAuthenticationEnable( - command_view.GetAuthenticationEnable()); - send_event_(bluetooth::hci::WriteAuthenticationEnableCompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS)); + link_layer_controller_.SetAuthenticationEnable(command_view.GetAuthenticationEnable()); + send_event_(bluetooth::hci::WriteAuthenticationEnableCompleteBuilder::Create(kNumCommandPackets, + ErrorCode::SUCCESS)); } void DualModeController::ReadAuthenticationEnable(CommandView command) { - auto command_view = - bluetooth::hci::ReadAuthenticationEnableView::Create(command); + auto command_view = bluetooth::hci::ReadAuthenticationEnableView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< Read Authentication Enable"); send_event_(bluetooth::hci::ReadAuthenticationEnableCompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS, - static_cast( - link_layer_controller_.GetAuthenticationEnable()))); + kNumCommandPackets, ErrorCode::SUCCESS, + static_cast( + link_layer_controller_.GetAuthenticationEnable()))); } void DualModeController::ReadClassOfDevice(CommandView command) { @@ -1218,8 +1111,7 @@ void DualModeController::ReadClassOfDevice(CommandView command) { DEBUG(id_, "<< Read Class of Device"); send_event_(bluetooth::hci::ReadClassOfDeviceCompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS, - link_layer_controller_.GetClassOfDevice())); + kNumCommandPackets, ErrorCode::SUCCESS, link_layer_controller_.GetClassOfDevice())); } void DualModeController::WriteClassOfDevice(CommandView command) { @@ -1230,8 +1122,8 @@ void DualModeController::WriteClassOfDevice(CommandView command) { DEBUG(id_, " class_of_device=0x{:x}", command_view.GetClassOfDevice()); link_layer_controller_.SetClassOfDevice(command_view.GetClassOfDevice()); - send_event_(bluetooth::hci::WriteClassOfDeviceCompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS)); + send_event_(bluetooth::hci::WriteClassOfDeviceCompleteBuilder::Create(kNumCommandPackets, + ErrorCode::SUCCESS)); } void DualModeController::ReadPageTimeout(CommandView command) { @@ -1242,7 +1134,7 @@ void DualModeController::ReadPageTimeout(CommandView command) { uint16_t page_timeout = link_layer_controller_.GetPageTimeout(); send_event_(bluetooth::hci::ReadPageTimeoutCompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS, page_timeout)); + kNumCommandPackets, ErrorCode::SUCCESS, page_timeout)); } void DualModeController::WritePageTimeout(CommandView command) { @@ -1253,8 +1145,8 @@ void DualModeController::WritePageTimeout(CommandView command) { DEBUG(id_, " page_timeout={}", command_view.GetPageTimeout()); link_layer_controller_.SetPageTimeout(command_view.GetPageTimeout()); - send_event_(bluetooth::hci::WritePageTimeoutCompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS)); + send_event_(bluetooth::hci::WritePageTimeoutCompleteBuilder::Create(kNumCommandPackets, + ErrorCode::SUCCESS)); } void DualModeController::HoldMode(CommandView command) { @@ -1267,11 +1159,10 @@ void DualModeController::HoldMode(CommandView command) { DEBUG(id_, "<< Hold Mode"); DEBUG(id_, " connection_handle=0x{:x}", command_view.GetConnectionHandle()); - auto status = link_layer_controller_.HoldMode(handle, hold_mode_max_interval, - hold_mode_min_interval); + auto status = + link_layer_controller_.HoldMode(handle, hold_mode_max_interval, hold_mode_min_interval); - send_event_(bluetooth::hci::HoldModeStatusBuilder::Create( - status, kNumCommandPackets)); + send_event_(bluetooth::hci::HoldModeStatusBuilder::Create(status, kNumCommandPackets)); } void DualModeController::SniffMode(CommandView command) { @@ -1286,12 +1177,10 @@ void DualModeController::SniffMode(CommandView command) { DEBUG(id_, "<< Sniff Mode"); DEBUG(id_, " connection_handle=0x{:x}", command_view.GetConnectionHandle()); - auto status = link_layer_controller_.SniffMode(handle, sniff_max_interval, - sniff_min_interval, + auto status = link_layer_controller_.SniffMode(handle, sniff_max_interval, sniff_min_interval, sniff_attempt, sniff_timeout); - send_event_(bluetooth::hci::SniffModeStatusBuilder::Create( - status, kNumCommandPackets)); + send_event_(bluetooth::hci::SniffModeStatusBuilder::Create(status, kNumCommandPackets)); } void DualModeController::ExitSniffMode(CommandView command) { @@ -1301,11 +1190,9 @@ void DualModeController::ExitSniffMode(CommandView command) { DEBUG(id_, "<< Exit Sniff Mode"); DEBUG(id_, " connection_handle=0x{:x}", command_view.GetConnectionHandle()); - auto status = - link_layer_controller_.ExitSniffMode(command_view.GetConnectionHandle()); + auto status = link_layer_controller_.ExitSniffMode(command_view.GetConnectionHandle()); - send_event_(bluetooth::hci::ExitSniffModeStatusBuilder::Create( - status, kNumCommandPackets)); + send_event_(bluetooth::hci::ExitSniffModeStatusBuilder::Create(status, kNumCommandPackets)); } void DualModeController::QosSetup(CommandView command) { @@ -1321,12 +1208,10 @@ void DualModeController::QosSetup(CommandView command) { DEBUG(id_, "<< Qos Setup"); DEBUG(id_, " connection_handle=0x{:x}", command_view.GetConnectionHandle()); - auto status = - link_layer_controller_.QosSetup(handle, service_type, token_rate, - peak_bandwidth, latency, delay_variation); + auto status = link_layer_controller_.QosSetup(handle, service_type, token_rate, peak_bandwidth, + latency, delay_variation); - send_event_(bluetooth::hci::QosSetupStatusBuilder::Create( - status, kNumCommandPackets)); + send_event_(bluetooth::hci::QosSetupStatusBuilder::Create(status, kNumCommandPackets)); } void DualModeController::RoleDiscovery(CommandView command) { @@ -1340,36 +1225,31 @@ void DualModeController::RoleDiscovery(CommandView command) { auto role = bluetooth::hci::Role::CENTRAL; auto status = link_layer_controller_.RoleDiscovery(handle, &role); - send_event_(bluetooth::hci::RoleDiscoveryCompleteBuilder::Create( - kNumCommandPackets, status, handle, role)); + send_event_(bluetooth::hci::RoleDiscoveryCompleteBuilder::Create(kNumCommandPackets, status, + handle, role)); } void DualModeController::ReadDefaultLinkPolicySettings(CommandView command) { - auto command_view = - bluetooth::hci::ReadDefaultLinkPolicySettingsView::Create(command); + auto command_view = bluetooth::hci::ReadDefaultLinkPolicySettingsView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< Read Default Link Policy Settings"); uint16_t settings = link_layer_controller_.ReadDefaultLinkPolicySettings(); - send_event_( - bluetooth::hci::ReadDefaultLinkPolicySettingsCompleteBuilder::Create( + send_event_(bluetooth::hci::ReadDefaultLinkPolicySettingsCompleteBuilder::Create( kNumCommandPackets, ErrorCode::SUCCESS, settings)); } void DualModeController::WriteDefaultLinkPolicySettings(CommandView command) { - auto command_view = - bluetooth::hci::WriteDefaultLinkPolicySettingsView::Create(command); + auto command_view = bluetooth::hci::WriteDefaultLinkPolicySettingsView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< Write Default Link Policy Settings"); - DEBUG(id_, " default_link_policy_settings=0x{:x}", - command_view.GetDefaultLinkPolicySettings()); + DEBUG(id_, " default_link_policy_settings=0x{:x}", command_view.GetDefaultLinkPolicySettings()); ErrorCode status = link_layer_controller_.WriteDefaultLinkPolicySettings( - command_view.GetDefaultLinkPolicySettings()); - send_event_( - bluetooth::hci::WriteDefaultLinkPolicySettingsCompleteBuilder::Create( + command_view.GetDefaultLinkPolicySettings()); + send_event_(bluetooth::hci::WriteDefaultLinkPolicySettingsCompleteBuilder::Create( kNumCommandPackets, status)); } @@ -1382,15 +1262,14 @@ void DualModeController::SniffSubrating(CommandView command) { DEBUG(id_, " connection_handle=0x{:x}", connection_handle); send_event_(bluetooth::hci::SniffSubratingCompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS, connection_handle)); + kNumCommandPackets, ErrorCode::SUCCESS, connection_handle)); } void DualModeController::FlowSpecification(CommandView command) { auto command_view = bluetooth::hci::FlowSpecificationView::Create(command); CHECK_PACKET_VIEW(command_view); uint16_t handle = command_view.GetConnectionHandle(); - uint8_t flow_direction = - static_cast(command_view.GetFlowDirection()); + uint8_t flow_direction = static_cast(command_view.GetFlowDirection()); uint8_t service_type = static_cast(command_view.GetServiceType()); uint32_t token_rate = command_view.GetTokenRate(); uint32_t token_bucket_size = command_view.GetTokenBucketSize(); @@ -1400,17 +1279,15 @@ void DualModeController::FlowSpecification(CommandView command) { DEBUG(id_, "<< Flow Specification"); DEBUG(id_, " connection_handle=0x{:x}", handle); - auto status = link_layer_controller_.FlowSpecification( - handle, flow_direction, service_type, token_rate, token_bucket_size, - peak_bandwidth, access_latency); + auto status = link_layer_controller_.FlowSpecification(handle, flow_direction, service_type, + token_rate, token_bucket_size, + peak_bandwidth, access_latency); - send_event_(bluetooth::hci::FlowSpecificationStatusBuilder::Create( - status, kNumCommandPackets)); + send_event_(bluetooth::hci::FlowSpecificationStatusBuilder::Create(status, kNumCommandPackets)); } void DualModeController::ReadLinkPolicySettings(CommandView command) { - auto command_view = - bluetooth::hci::ReadLinkPolicySettingsView::Create(command); + auto command_view = bluetooth::hci::ReadLinkPolicySettingsView::Create(command); CHECK_PACKET_VIEW(command_view); uint16_t handle = command_view.GetConnectionHandle(); @@ -1418,16 +1295,14 @@ void DualModeController::ReadLinkPolicySettings(CommandView command) { DEBUG(id_, " connection_handle=0x{:x}", handle); uint16_t settings = 0; - auto status = - link_layer_controller_.ReadLinkPolicySettings(handle, &settings); + auto status = link_layer_controller_.ReadLinkPolicySettings(handle, &settings); send_event_(bluetooth::hci::ReadLinkPolicySettingsCompleteBuilder::Create( - kNumCommandPackets, status, handle, settings)); + kNumCommandPackets, status, handle, settings)); } void DualModeController::WriteLinkPolicySettings(CommandView command) { - auto command_view = - bluetooth::hci::WriteLinkPolicySettingsView::Create(command); + auto command_view = bluetooth::hci::WriteLinkPolicySettingsView::Create(command); CHECK_PACKET_VIEW(command_view); uint16_t handle = command_view.GetConnectionHandle(); uint16_t settings = command_view.GetLinkPolicySettings(); @@ -1436,16 +1311,14 @@ void DualModeController::WriteLinkPolicySettings(CommandView command) { DEBUG(id_, " connection_handle=0x{:x}", handle); DEBUG(id_, " link_policy_settings=0x{:x}", settings); - auto status = - link_layer_controller_.WriteLinkPolicySettings(handle, settings); + auto status = link_layer_controller_.WriteLinkPolicySettings(handle, settings); - send_event_(bluetooth::hci::WriteLinkPolicySettingsCompleteBuilder::Create( - kNumCommandPackets, status, handle)); + send_event_(bluetooth::hci::WriteLinkPolicySettingsCompleteBuilder::Create(kNumCommandPackets, + status, handle)); } void DualModeController::WriteLinkSupervisionTimeout(CommandView command) { - auto command_view = - bluetooth::hci::WriteLinkSupervisionTimeoutView::Create(command); + auto command_view = bluetooth::hci::WriteLinkSupervisionTimeoutView::Create(command); CHECK_PACKET_VIEW(command_view); uint16_t handle = command_view.GetConnectionHandle(); uint16_t timeout = command_view.GetLinkSupervisionTimeout(); @@ -1454,11 +1327,9 @@ void DualModeController::WriteLinkSupervisionTimeout(CommandView command) { DEBUG(id_, " connection_handle=0x{:x}", handle); DEBUG(id_, " link_supervision_timeout={}", timeout); - auto status = - link_layer_controller_.WriteLinkSupervisionTimeout(handle, timeout); - send_event_( - bluetooth::hci::WriteLinkSupervisionTimeoutCompleteBuilder::Create( - kNumCommandPackets, status, handle)); + auto status = link_layer_controller_.WriteLinkSupervisionTimeout(handle, timeout); + send_event_(bluetooth::hci::WriteLinkSupervisionTimeoutCompleteBuilder::Create(kNumCommandPackets, + status, handle)); } void DualModeController::ReadLocalName(CommandView command) { @@ -1468,8 +1339,7 @@ void DualModeController::ReadLocalName(CommandView command) { DEBUG(id_, "<< Read Local Name"); send_event_(bluetooth::hci::ReadLocalNameCompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS, - link_layer_controller_.GetLocalName())); + kNumCommandPackets, ErrorCode::SUCCESS, link_layer_controller_.GetLocalName())); } void DualModeController::WriteLocalName(CommandView command) { @@ -1479,21 +1349,18 @@ void DualModeController::WriteLocalName(CommandView command) { DEBUG(id_, "<< Write Local Name"); link_layer_controller_.SetLocalName(command_view.GetLocalName()); - send_event_(bluetooth::hci::WriteLocalNameCompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS)); + send_event_(bluetooth::hci::WriteLocalNameCompleteBuilder::Create(kNumCommandPackets, + ErrorCode::SUCCESS)); } void DualModeController::WriteExtendedInquiryResponse(CommandView command) { - auto command_view = - bluetooth::hci::WriteExtendedInquiryResponseView::Create(command); + auto command_view = bluetooth::hci::WriteExtendedInquiryResponseView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< Write Extended Inquiry Response"); - link_layer_controller_.SetExtendedInquiryResponse( - command_view.GetExtendedInquiryResponse()); - send_event_( - bluetooth::hci::WriteExtendedInquiryResponseCompleteBuilder::Create( + link_layer_controller_.SetExtendedInquiryResponse(command_view.GetExtendedInquiryResponse()); + send_event_(bluetooth::hci::WriteExtendedInquiryResponseCompleteBuilder::Create( kNumCommandPackets, ErrorCode::SUCCESS)); } @@ -1505,11 +1372,11 @@ void DualModeController::RefreshEncryptionKey(CommandView command) { DEBUG(id_, "<< Refresh Encryption Key"); DEBUG(id_, " connection_handle=0x{:x}", handle); - send_event_(bluetooth::hci::RefreshEncryptionKeyStatusBuilder::Create( - ErrorCode::SUCCESS, kNumCommandPackets)); + send_event_(bluetooth::hci::RefreshEncryptionKeyStatusBuilder::Create(ErrorCode::SUCCESS, + kNumCommandPackets)); // TODO: Support this in the link layer - send_event_(bluetooth::hci::EncryptionKeyRefreshCompleteBuilder::Create( - ErrorCode::SUCCESS, handle)); + send_event_( + bluetooth::hci::EncryptionKeyRefreshCompleteBuilder::Create(ErrorCode::SUCCESS, handle)); } void DualModeController::ReadVoiceSetting(CommandView command) { @@ -1519,8 +1386,7 @@ void DualModeController::ReadVoiceSetting(CommandView command) { DEBUG(id_, "<< Read Voice Setting"); send_event_(bluetooth::hci::ReadVoiceSettingCompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS, - link_layer_controller_.GetVoiceSetting())); + kNumCommandPackets, ErrorCode::SUCCESS, link_layer_controller_.GetVoiceSetting())); } void DualModeController::WriteVoiceSetting(CommandView command) { @@ -1532,19 +1398,18 @@ void DualModeController::WriteVoiceSetting(CommandView command) { link_layer_controller_.SetVoiceSetting(command_view.GetVoiceSetting()); - send_event_(bluetooth::hci::WriteVoiceSettingCompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS)); + send_event_(bluetooth::hci::WriteVoiceSettingCompleteBuilder::Create(kNumCommandPackets, + ErrorCode::SUCCESS)); } void DualModeController::ReadNumberOfSupportedIac(CommandView command) { - auto command_view = - bluetooth::hci::ReadNumberOfSupportedIacView::Create(command); + auto command_view = bluetooth::hci::ReadNumberOfSupportedIacView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< Read Number of Supported Iac"); send_event_(bluetooth::hci::ReadNumberOfSupportedIacCompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS, properties_.num_supported_iac)); + kNumCommandPackets, ErrorCode::SUCCESS, properties_.num_supported_iac)); } void DualModeController::ReadCurrentIacLap(CommandView command) { @@ -1554,8 +1419,7 @@ void DualModeController::ReadCurrentIacLap(CommandView command) { DEBUG(id_, "<< Read Current Iac Lap"); send_event_(bluetooth::hci::ReadCurrentIacLapCompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS, - link_layer_controller_.ReadCurrentIacLap())); + kNumCommandPackets, ErrorCode::SUCCESS, link_layer_controller_.ReadCurrentIacLap())); } void DualModeController::WriteCurrentIacLap(CommandView command) { @@ -1565,8 +1429,8 @@ void DualModeController::WriteCurrentIacLap(CommandView command) { DEBUG(id_, "<< Write Current Iac Lap"); link_layer_controller_.WriteCurrentIacLap(command_view.GetLapsToWrite()); - send_event_(bluetooth::hci::WriteCurrentIacLapCompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS)); + send_event_(bluetooth::hci::WriteCurrentIacLapCompleteBuilder::Create(kNumCommandPackets, + ErrorCode::SUCCESS)); } void DualModeController::ReadPageScanActivity(CommandView command) { @@ -1578,23 +1442,21 @@ void DualModeController::ReadPageScanActivity(CommandView command) { uint16_t interval = 0x1000; uint16_t window = 0x0012; send_event_(bluetooth::hci::ReadPageScanActivityCompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS, interval, window)); + kNumCommandPackets, ErrorCode::SUCCESS, interval, window)); } void DualModeController::WritePageScanActivity(CommandView command) { - auto command_view = - bluetooth::hci::WritePageScanActivityView::Create(command); + auto command_view = bluetooth::hci::WritePageScanActivityView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< Write Page Scan Activity"); - send_event_(bluetooth::hci::WritePageScanActivityCompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS)); + send_event_(bluetooth::hci::WritePageScanActivityCompleteBuilder::Create(kNumCommandPackets, + ErrorCode::SUCCESS)); } void DualModeController::ReadInquiryScanActivity(CommandView command) { - auto command_view = - bluetooth::hci::ReadInquiryScanActivityView::Create(command); + auto command_view = bluetooth::hci::ReadInquiryScanActivityView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< Read Inquiry Scan Activity"); @@ -1602,18 +1464,17 @@ void DualModeController::ReadInquiryScanActivity(CommandView command) { uint16_t interval = 0x1000; uint16_t window = 0x0012; send_event_(bluetooth::hci::ReadInquiryScanActivityCompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS, interval, window)); + kNumCommandPackets, ErrorCode::SUCCESS, interval, window)); } void DualModeController::WriteInquiryScanActivity(CommandView command) { - auto command_view = - bluetooth::hci::WriteInquiryScanActivityView::Create(command); + auto command_view = bluetooth::hci::WriteInquiryScanActivityView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< Write Inquiry Scan Activity"); - send_event_(bluetooth::hci::WriteInquiryScanActivityCompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS)); + send_event_(bluetooth::hci::WriteInquiryScanActivityCompleteBuilder::Create(kNumCommandPackets, + ErrorCode::SUCCESS)); } void DualModeController::ReadScanEnable(CommandView command) { @@ -1626,34 +1487,31 @@ void DualModeController::ReadScanEnable(CommandView command) { bool page_scan = link_layer_controller_.GetPageScanEnable(); bluetooth::hci::ScanEnable scan_enable = - inquiry_scan && page_scan - ? bluetooth::hci::ScanEnable::INQUIRY_AND_PAGE_SCAN - : inquiry_scan ? bluetooth::hci::ScanEnable::INQUIRY_SCAN_ONLY - : page_scan ? bluetooth::hci::ScanEnable::PAGE_SCAN_ONLY - : bluetooth::hci::ScanEnable::NO_SCANS; + inquiry_scan && page_scan ? bluetooth::hci::ScanEnable::INQUIRY_AND_PAGE_SCAN + : inquiry_scan ? bluetooth::hci::ScanEnable::INQUIRY_SCAN_ONLY + : page_scan ? bluetooth::hci::ScanEnable::PAGE_SCAN_ONLY + : bluetooth::hci::ScanEnable::NO_SCANS; send_event_(bluetooth::hci::ReadScanEnableCompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS, scan_enable)); + kNumCommandPackets, ErrorCode::SUCCESS, scan_enable)); } void DualModeController::WriteScanEnable(CommandView command) { auto command_view = bluetooth::hci::WriteScanEnableView::Create(command); CHECK_PACKET_VIEW(command_view); bluetooth::hci::ScanEnable scan_enable = command_view.GetScanEnable(); - bool inquiry_scan = - scan_enable == bluetooth::hci::ScanEnable::INQUIRY_AND_PAGE_SCAN || - scan_enable == bluetooth::hci::ScanEnable::INQUIRY_SCAN_ONLY; - bool page_scan = - scan_enable == bluetooth::hci::ScanEnable::INQUIRY_AND_PAGE_SCAN || - scan_enable == bluetooth::hci::ScanEnable::PAGE_SCAN_ONLY; + bool inquiry_scan = scan_enable == bluetooth::hci::ScanEnable::INQUIRY_AND_PAGE_SCAN || + scan_enable == bluetooth::hci::ScanEnable::INQUIRY_SCAN_ONLY; + bool page_scan = scan_enable == bluetooth::hci::ScanEnable::INQUIRY_AND_PAGE_SCAN || + scan_enable == bluetooth::hci::ScanEnable::PAGE_SCAN_ONLY; DEBUG(id_, "<< Write Scan Enable"); DEBUG(id_, " scan_enable={}", bluetooth::hci::ScanEnableText(scan_enable)); link_layer_controller_.SetInquiryScanEnable(inquiry_scan); link_layer_controller_.SetPageScanEnable(page_scan); - send_event_(bluetooth::hci::WriteScanEnableCompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS)); + send_event_(bluetooth::hci::WriteScanEnableCompleteBuilder::Create(kNumCommandPackets, + ErrorCode::SUCCESS)); } void DualModeController::ReadTransmitPowerLevel(CommandView command) { @@ -1665,11 +1523,11 @@ void DualModeController::ReadTransmitPowerLevel(CommandView command) { DEBUG(id_, " connection_handle=0x{:x}", connection_handle); ErrorCode status = link_layer_controller_.HasAclConnection(connection_handle) - ? ErrorCode::SUCCESS - : ErrorCode::UNKNOWN_CONNECTION; + ? ErrorCode::SUCCESS + : ErrorCode::UNKNOWN_CONNECTION; send_event_(bluetooth::hci::ReadTransmitPowerLevelCompleteBuilder::Create( - kNumCommandPackets, status, connection_handle, kTransmitPowerLevel)); + kNumCommandPackets, status, connection_handle, kTransmitPowerLevel)); } void DualModeController::ReadEnhancedTransmitPowerLevel(CommandView command) { @@ -1681,17 +1539,16 @@ void DualModeController::ReadEnhancedTransmitPowerLevel(CommandView command) { DEBUG(id_, " connection_handle=0x{:x}", connection_handle); ErrorCode status = link_layer_controller_.HasAclConnection(connection_handle) - ? ErrorCode::SUCCESS - : ErrorCode::UNKNOWN_CONNECTION; + ? ErrorCode::SUCCESS + : ErrorCode::UNKNOWN_CONNECTION; send_event_(bluetooth::hci::ReadEnhancedTransmitPowerLevelCompleteBuilder::Create( - kNumCommandPackets, status, connection_handle, kTransmitPowerLevel, - kTransmitPowerLevel, kTransmitPowerLevel)); + kNumCommandPackets, status, connection_handle, kTransmitPowerLevel, kTransmitPowerLevel, + kTransmitPowerLevel)); } void DualModeController::ReadSynchronousFlowControlEnable(CommandView command) { - auto command_view = - bluetooth::hci::ReadSynchronousFlowControlEnableView::Create(command); + auto command_view = bluetooth::hci::ReadSynchronousFlowControlEnableView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< Read Synchronous Flow Control Enable"); @@ -1700,15 +1557,12 @@ void DualModeController::ReadSynchronousFlowControlEnable(CommandView command) { if (link_layer_controller_.GetScoFlowControlEnable()) { enabled = bluetooth::hci::Enable::ENABLED; } - send_event_( - bluetooth::hci::ReadSynchronousFlowControlEnableCompleteBuilder::Create( + send_event_(bluetooth::hci::ReadSynchronousFlowControlEnableCompleteBuilder::Create( kNumCommandPackets, ErrorCode::SUCCESS, enabled)); } -void DualModeController::WriteSynchronousFlowControlEnable( - CommandView command) { - auto command_view = - bluetooth::hci::WriteSynchronousFlowControlEnableView::Create(command); +void DualModeController::WriteSynchronousFlowControlEnable(CommandView command) { + auto command_view = bluetooth::hci::WriteSynchronousFlowControlEnableView::Create(command); CHECK_PACKET_VIEW(command_view); auto enabled = command_view.GetEnable() == bluetooth::hci::Enable::ENABLED; @@ -1716,8 +1570,7 @@ void DualModeController::WriteSynchronousFlowControlEnable( DEBUG(id_, " enable={}", enabled); link_layer_controller_.SetScoFlowControlEnable(enabled); - send_event_( - bluetooth::hci::WriteSynchronousFlowControlEnableCompleteBuilder::Create( + send_event_(bluetooth::hci::WriteSynchronousFlowControlEnableCompleteBuilder::Create( kNumCommandPackets, ErrorCode::SUCCESS)); } @@ -1726,15 +1579,14 @@ void DualModeController::SetEventFilter(CommandView command) { CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< Set Event Filter"); - DEBUG(id_, " filter_type={}", - bluetooth::hci::FilterTypeText(command_view.GetFilterType())); + DEBUG(id_, " filter_type={}", bluetooth::hci::FilterTypeText(command_view.GetFilterType())); if (command_view.GetFilterType() != bluetooth::hci::FilterType::CLEAR_ALL_FILTERS) { FATAL("unsupported event filter type"); } - send_event_(bluetooth::hci::SetEventFilterCompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS)); + send_event_(bluetooth::hci::SetEventFilterCompleteBuilder::Create(kNumCommandPackets, + ErrorCode::SUCCESS)); } void DualModeController::Inquiry(CommandView command) { @@ -1749,15 +1601,14 @@ void DualModeController::Inquiry(CommandView command) { if (max_responses > 0xff || length < 1 || length > 0x30) { send_event_(bluetooth::hci::InquiryStatusBuilder::Create( - ErrorCode::INVALID_HCI_COMMAND_PARAMETERS, kNumCommandPackets)); + ErrorCode::INVALID_HCI_COMMAND_PARAMETERS, kNumCommandPackets)); return; } link_layer_controller_.SetInquiryLAP(command_view.GetLap().lap_); link_layer_controller_.SetInquiryMaxResponses(max_responses); link_layer_controller_.StartInquiry(std::chrono::milliseconds(length * 1280)); - send_event_(bluetooth::hci::InquiryStatusBuilder::Create(ErrorCode::SUCCESS, - kNumCommandPackets)); + send_event_(bluetooth::hci::InquiryStatusBuilder::Create(ErrorCode::SUCCESS, kNumCommandPackets)); } void DualModeController::InquiryCancel(CommandView command) { @@ -1767,45 +1618,40 @@ void DualModeController::InquiryCancel(CommandView command) { DEBUG(id_, "<< Inquiry Cancel"); link_layer_controller_.InquiryCancel(); - send_event_(bluetooth::hci::InquiryCancelCompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS)); + send_event_(bluetooth::hci::InquiryCancelCompleteBuilder::Create(kNumCommandPackets, + ErrorCode::SUCCESS)); } void DualModeController::AcceptConnectionRequest(CommandView command) { - auto command_view = - bluetooth::hci::AcceptConnectionRequestView::Create(command); + auto command_view = bluetooth::hci::AcceptConnectionRequestView::Create(command); CHECK_PACKET_VIEW(command_view); Address bd_addr = command_view.GetBdAddr(); bool try_role_switch = - command_view.GetRole() == - bluetooth::hci::AcceptConnectionRequestRole::BECOME_CENTRAL; + command_view.GetRole() == bluetooth::hci::AcceptConnectionRequestRole::BECOME_CENTRAL; DEBUG(id_, "<< Accept Connection Request"); DEBUG(id_, " bd_addr={}", bd_addr); DEBUG(id_, " try_role_switch={}", try_role_switch); - auto status = - link_layer_controller_.AcceptConnectionRequest(bd_addr, try_role_switch); - send_event_(bluetooth::hci::AcceptConnectionRequestStatusBuilder::Create( - status, kNumCommandPackets)); + auto status = link_layer_controller_.AcceptConnectionRequest(bd_addr, try_role_switch); + send_event_( + bluetooth::hci::AcceptConnectionRequestStatusBuilder::Create(status, kNumCommandPackets)); } void DualModeController::RejectConnectionRequest(CommandView command) { - auto command_view = - bluetooth::hci::RejectConnectionRequestView::Create(command); + auto command_view = bluetooth::hci::RejectConnectionRequestView::Create(command); CHECK_PACKET_VIEW(command_view); Address bd_addr = command_view.GetBdAddr(); auto reason = command_view.GetReason(); DEBUG(id_, "<< Reject Connection Request"); DEBUG(id_, " bd_addr={}", bd_addr); - DEBUG(id_, " reason={}", - bluetooth::hci::RejectConnectionReasonText(reason)); + DEBUG(id_, " reason={}", bluetooth::hci::RejectConnectionReasonText(reason)); - auto status = link_layer_controller_.RejectConnectionRequest( - bd_addr, static_cast(reason)); - send_event_(bluetooth::hci::RejectConnectionRequestStatusBuilder::Create( - status, kNumCommandPackets)); + auto status = + link_layer_controller_.RejectConnectionRequest(bd_addr, static_cast(reason)); + send_event_( + bluetooth::hci::RejectConnectionRequestStatusBuilder::Create(status, kNumCommandPackets)); } void DualModeController::DeleteStoredLinkKey(CommandView command) { @@ -1814,8 +1660,8 @@ void DualModeController::DeleteStoredLinkKey(CommandView command) { DEBUG(id_, "<< Delete Stored Link Key"); - send_event_(bluetooth::hci::DeleteStoredLinkKeyCompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS, 0)); + send_event_(bluetooth::hci::DeleteStoredLinkKeyCompleteBuilder::Create(kNumCommandPackets, + ErrorCode::SUCCESS, 0)); } void DualModeController::RemoteNameRequest(CommandView command) { @@ -1827,10 +1673,9 @@ void DualModeController::RemoteNameRequest(CommandView command) { DEBUG(id_, " bd_addr={}", bd_addr); auto status = link_layer_controller_.SendCommandToRemoteByAddress( - OpCode::REMOTE_NAME_REQUEST, command_view.bytes(), GetAddress(), bd_addr); + OpCode::REMOTE_NAME_REQUEST, command_view.bytes(), GetAddress(), bd_addr); - send_event_(bluetooth::hci::RemoteNameRequestStatusBuilder::Create( - status, kNumCommandPackets)); + send_event_(bluetooth::hci::RemoteNameRequestStatusBuilder::Create(status, kNumCommandPackets)); } void DualModeController::LeSetEventMask(CommandView command) { @@ -1841,8 +1686,8 @@ void DualModeController::LeSetEventMask(CommandView command) { DEBUG(id_, " le_event_mask=0x{:x}", command_view.GetLeEventMask()); link_layer_controller_.SetLeEventMask(command_view.GetLeEventMask()); - send_event_(bluetooth::hci::LeSetEventMaskCompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS)); + send_event_(bluetooth::hci::LeSetEventMaskCompleteBuilder::Create(kNumCommandPackets, + ErrorCode::SUCCESS)); } void DualModeController::LeRequestPeerSca(CommandView command) { @@ -1866,14 +1711,13 @@ void DualModeController::LeRequestPeerSca(CommandView command) { // TODO if (link_layer_controller_.HasAclConnection(connection_handle)) { - send_event_(bluetooth::hci::LeRequestPeerScaStatusBuilder::Create( - ErrorCode::SUCCESS, kNumCommandPackets)); + send_event_(bluetooth::hci::LeRequestPeerScaStatusBuilder::Create(ErrorCode::SUCCESS, + kNumCommandPackets)); send_event_(bluetooth::hci::LeRequestPeerScaCompleteBuilder::Create( - ErrorCode::SUCCESS, connection_handle, - bluetooth::hci::ClockAccuracy::PPM_500)); + ErrorCode::SUCCESS, connection_handle, bluetooth::hci::ClockAccuracy::PPM_500)); } else { - send_event_(bluetooth::hci::LeRequestPeerScaStatusBuilder::Create( - ErrorCode::UNKNOWN_CONNECTION, kNumCommandPackets)); + send_event_(bluetooth::hci::LeRequestPeerScaStatusBuilder::Create(ErrorCode::UNKNOWN_CONNECTION, + kNumCommandPackets)); } } @@ -1887,10 +1731,8 @@ void DualModeController::LeSetHostFeature(CommandView command) { DEBUG(id_, " bit_number={}", bit_number); DEBUG(id_, " bit_value={}", bit_value); - ErrorCode status = - link_layer_controller_.LeSetHostFeature(bit_number, bit_value); - send_event_(bluetooth::hci::LeSetHostFeatureCompleteBuilder::Create( - kNumCommandPackets, status)); + ErrorCode status = link_layer_controller_.LeSetHostFeature(bit_number, bit_value); + send_event_(bluetooth::hci::LeSetHostFeatureCompleteBuilder::Create(kNumCommandPackets, status)); } void DualModeController::LeReadBufferSizeV1(CommandView command) { @@ -1901,11 +1743,10 @@ void DualModeController::LeReadBufferSizeV1(CommandView command) { bluetooth::hci::LeBufferSize le_buffer_size; le_buffer_size.le_data_packet_length_ = properties_.le_acl_data_packet_length; - le_buffer_size.total_num_le_packets_ = - properties_.total_num_le_acl_data_packets; + le_buffer_size.total_num_le_packets_ = properties_.total_num_le_acl_data_packets; send_event_(bluetooth::hci::LeReadBufferSizeV1CompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS, le_buffer_size)); + kNumCommandPackets, ErrorCode::SUCCESS, le_buffer_size)); } void DualModeController::LeReadBufferSizeV2(CommandView command) { @@ -1916,61 +1757,49 @@ void DualModeController::LeReadBufferSizeV2(CommandView command) { bluetooth::hci::LeBufferSize le_buffer_size; le_buffer_size.le_data_packet_length_ = properties_.le_acl_data_packet_length; - le_buffer_size.total_num_le_packets_ = - properties_.total_num_le_acl_data_packets; + le_buffer_size.total_num_le_packets_ = properties_.total_num_le_acl_data_packets; bluetooth::hci::LeBufferSize iso_buffer_size; iso_buffer_size.le_data_packet_length_ = properties_.iso_data_packet_length; - iso_buffer_size.total_num_le_packets_ = - properties_.total_num_iso_data_packets; + iso_buffer_size.total_num_le_packets_ = properties_.total_num_iso_data_packets; send_event_(bluetooth::hci::LeReadBufferSizeV2CompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS, le_buffer_size, iso_buffer_size)); + kNumCommandPackets, ErrorCode::SUCCESS, le_buffer_size, iso_buffer_size)); } void DualModeController::LeSetAddressResolutionEnable(CommandView command) { - auto command_view = - bluetooth::hci::LeSetAddressResolutionEnableView::Create(command); + auto command_view = bluetooth::hci::LeSetAddressResolutionEnableView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< LE Set Address Resolution Enable"); DEBUG(id_, " address_resolution_enable={}", - command_view.GetAddressResolutionEnable() == - bluetooth::hci::Enable::ENABLED); + command_view.GetAddressResolutionEnable() == bluetooth::hci::Enable::ENABLED); ErrorCode status = link_layer_controller_.LeSetAddressResolutionEnable( - command_view.GetAddressResolutionEnable() == - bluetooth::hci::Enable::ENABLED); - send_event_( - bluetooth::hci::LeSetAddressResolutionEnableCompleteBuilder::Create( + command_view.GetAddressResolutionEnable() == bluetooth::hci::Enable::ENABLED); + send_event_(bluetooth::hci::LeSetAddressResolutionEnableCompleteBuilder::Create( kNumCommandPackets, status)); } -void DualModeController::LeSetResolvablePrivateAddressTimeout( - CommandView command) { - auto command_view = - bluetooth::hci::LeSetResolvablePrivateAddressTimeoutView::Create(command); +void DualModeController::LeSetResolvablePrivateAddressTimeout(CommandView command) { + auto command_view = bluetooth::hci::LeSetResolvablePrivateAddressTimeoutView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< LE Set Resolvable Private Address Timeout"); ErrorCode status = - link_layer_controller_.LeSetResolvablePrivateAddressTimeout( - command_view.GetRpaTimeout()); - send_event_( - bluetooth::hci::LeSetResolvablePrivateAddressTimeoutCompleteBuilder:: - Create(kNumCommandPackets, status)); + link_layer_controller_.LeSetResolvablePrivateAddressTimeout(command_view.GetRpaTimeout()); + send_event_(bluetooth::hci::LeSetResolvablePrivateAddressTimeoutCompleteBuilder::Create( + kNumCommandPackets, status)); } void DualModeController::LeReadLocalSupportedFeatures(CommandView command) { - auto command_view = - bluetooth::hci::LeReadLocalSupportedFeaturesView::Create(command); + auto command_view = bluetooth::hci::LeReadLocalSupportedFeaturesView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< LE Read Local Supported Features"); uint64_t le_features = link_layer_controller_.GetLeSupportedFeatures(); - send_event_( - bluetooth::hci::LeReadLocalSupportedFeaturesCompleteBuilder::Create( + send_event_(bluetooth::hci::LeReadLocalSupportedFeaturesCompleteBuilder::Create( kNumCommandPackets, ErrorCode::SUCCESS, le_features)); } @@ -1981,43 +1810,35 @@ void DualModeController::LeSetRandomAddress(CommandView command) { DEBUG(id_, "<< LE Set Random Address"); DEBUG(id_, " random_address={}", command_view.GetRandomAddress()); - ErrorCode status = link_layer_controller_.LeSetRandomAddress( - command_view.GetRandomAddress()); - send_event_(bluetooth::hci::LeSetRandomAddressCompleteBuilder::Create( - kNumCommandPackets, status)); + ErrorCode status = link_layer_controller_.LeSetRandomAddress(command_view.GetRandomAddress()); + send_event_( + bluetooth::hci::LeSetRandomAddressCompleteBuilder::Create(kNumCommandPackets, status)); } void DualModeController::LeSetAdvertisingParameters(CommandView command) { - auto command_view = - bluetooth::hci::LeSetAdvertisingParametersView::Create(command); + auto command_view = bluetooth::hci::LeSetAdvertisingParametersView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< LE Set Advertising Parameters"); ErrorCode status = link_layer_controller_.LeSetAdvertisingParameters( - command_view.GetAdvertisingIntervalMin(), - command_view.GetAdvertisingIntervalMax(), - command_view.GetAdvertisingType(), command_view.GetOwnAddressType(), - command_view.GetPeerAddressType(), command_view.GetPeerAddress(), - command_view.GetAdvertisingChannelMap(), - command_view.GetAdvertisingFilterPolicy()); - send_event_(bluetooth::hci::LeSetAdvertisingParametersCompleteBuilder::Create( - kNumCommandPackets, status)); -} - -void DualModeController::LeReadAdvertisingPhysicalChannelTxPower( - CommandView command) { - auto command_view = - bluetooth::hci::LeReadAdvertisingPhysicalChannelTxPowerView::Create( - command); + command_view.GetAdvertisingIntervalMin(), command_view.GetAdvertisingIntervalMax(), + command_view.GetAdvertisingType(), command_view.GetOwnAddressType(), + command_view.GetPeerAddressType(), command_view.GetPeerAddress(), + command_view.GetAdvertisingChannelMap(), command_view.GetAdvertisingFilterPolicy()); + send_event_(bluetooth::hci::LeSetAdvertisingParametersCompleteBuilder::Create(kNumCommandPackets, + status)); +} + +void DualModeController::LeReadAdvertisingPhysicalChannelTxPower(CommandView command) { + auto command_view = bluetooth::hci::LeReadAdvertisingPhysicalChannelTxPowerView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< LE Read Physical Channel Tx Power"); - send_event_( - bluetooth::hci::LeReadAdvertisingPhysicalChannelTxPowerCompleteBuilder:: - Create(kNumCommandPackets, ErrorCode::SUCCESS, - properties_.le_advertising_physical_channel_tx_power)); + send_event_(bluetooth::hci::LeReadAdvertisingPhysicalChannelTxPowerCompleteBuilder::Create( + kNumCommandPackets, ErrorCode::SUCCESS, + properties_.le_advertising_physical_channel_tx_power)); } void DualModeController::LeSetAdvertisingData(CommandView command) { @@ -2026,28 +1847,25 @@ void DualModeController::LeSetAdvertisingData(CommandView command) { DEBUG(id_, "<< LE Set Advertising Data"); - ErrorCode status = link_layer_controller_.LeSetAdvertisingData( - command_view.GetAdvertisingData()); - send_event_(bluetooth::hci::LeSetAdvertisingDataCompleteBuilder::Create( - kNumCommandPackets, status)); + ErrorCode status = link_layer_controller_.LeSetAdvertisingData(command_view.GetAdvertisingData()); + send_event_( + bluetooth::hci::LeSetAdvertisingDataCompleteBuilder::Create(kNumCommandPackets, status)); } void DualModeController::LeSetScanResponseData(CommandView command) { - auto command_view = - bluetooth::hci::LeSetScanResponseDataView::Create(command); + auto command_view = bluetooth::hci::LeSetScanResponseDataView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< LE Set Scan Response Data"); - ErrorCode status = link_layer_controller_.LeSetScanResponseData( - command_view.GetAdvertisingData()); - send_event_(bluetooth::hci::LeSetScanResponseDataCompleteBuilder::Create( - kNumCommandPackets, status)); + ErrorCode status = + link_layer_controller_.LeSetScanResponseData(command_view.GetAdvertisingData()); + send_event_( + bluetooth::hci::LeSetScanResponseDataCompleteBuilder::Create(kNumCommandPackets, status)); } void DualModeController::LeSetAdvertisingEnable(CommandView command) { - auto command_view = - bluetooth::hci::LeSetAdvertisingEnableView::Create(command); + auto command_view = bluetooth::hci::LeSetAdvertisingEnableView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< LE Set Advertising Enable"); @@ -2055,9 +1873,9 @@ void DualModeController::LeSetAdvertisingEnable(CommandView command) { command_view.GetAdvertisingEnable() == bluetooth::hci::Enable::ENABLED); ErrorCode status = link_layer_controller_.LeSetAdvertisingEnable( - command_view.GetAdvertisingEnable() == bluetooth::hci::Enable::ENABLED); - send_event_(bluetooth::hci::LeSetAdvertisingEnableCompleteBuilder::Create( - kNumCommandPackets, status)); + command_view.GetAdvertisingEnable() == bluetooth::hci::Enable::ENABLED); + send_event_(bluetooth::hci::LeSetAdvertisingEnableCompleteBuilder::Create(kNumCommandPackets, + status)); } void DualModeController::LeSetScanParameters(CommandView command) { @@ -2067,11 +1885,11 @@ void DualModeController::LeSetScanParameters(CommandView command) { DEBUG(id_, "<< LE Set Scan Parameters"); ErrorCode status = link_layer_controller_.LeSetScanParameters( - command_view.GetLeScanType(), command_view.GetLeScanInterval(), - command_view.GetLeScanWindow(), command_view.GetOwnAddressType(), - command_view.GetScanningFilterPolicy()); - send_event_(bluetooth::hci::LeSetScanParametersCompleteBuilder::Create( - kNumCommandPackets, status)); + command_view.GetLeScanType(), command_view.GetLeScanInterval(), + command_view.GetLeScanWindow(), command_view.GetOwnAddressType(), + command_view.GetScanningFilterPolicy()); + send_event_( + bluetooth::hci::LeSetScanParametersCompleteBuilder::Create(kNumCommandPackets, status)); } void DualModeController::LeSetScanEnable(CommandView command) { @@ -2083,10 +1901,9 @@ void DualModeController::LeSetScanEnable(CommandView command) { command_view.GetLeScanEnable() == bluetooth::hci::Enable::ENABLED); ErrorCode status = link_layer_controller_.LeSetScanEnable( - command_view.GetLeScanEnable() == bluetooth::hci::Enable::ENABLED, - command_view.GetFilterDuplicates() == bluetooth::hci::Enable::ENABLED); - send_event_(bluetooth::hci::LeSetScanEnableCompleteBuilder::Create( - kNumCommandPackets, status)); + command_view.GetLeScanEnable() == bluetooth::hci::Enable::ENABLED, + command_view.GetFilterDuplicates() == bluetooth::hci::Enable::ENABLED); + send_event_(bluetooth::hci::LeSetScanEnableCompleteBuilder::Create(kNumCommandPackets, status)); } void DualModeController::LeCreateConnection(CommandView command) { @@ -2100,34 +1917,31 @@ void DualModeController::LeCreateConnection(CommandView command) { DEBUG(id_, " own_address_type={}", bluetooth::hci::OwnAddressTypeText(command_view.GetOwnAddressType())); DEBUG(id_, " initiator_filter_policy={}", - bluetooth::hci::InitiatorFilterPolicyText( - command_view.GetInitiatorFilterPolicy())); + bluetooth::hci::InitiatorFilterPolicyText(command_view.GetInitiatorFilterPolicy())); ErrorCode status = link_layer_controller_.LeCreateConnection( - command_view.GetLeScanInterval(), command_view.GetLeScanWindow(), - command_view.GetInitiatorFilterPolicy(), - AddressWithType{ - command_view.GetPeerAddress(), - command_view.GetPeerAddressType(), - }, - command_view.GetOwnAddressType(), command_view.GetConnectionIntervalMin(), - command_view.GetConnectionIntervalMax(), command_view.GetMaxLatency(), - command_view.GetSupervisionTimeout(), command_view.GetMinCeLength(), - command_view.GetMaxCeLength()); - send_event_(bluetooth::hci::LeCreateConnectionStatusBuilder::Create( - status, kNumCommandPackets)); + command_view.GetLeScanInterval(), command_view.GetLeScanWindow(), + command_view.GetInitiatorFilterPolicy(), + AddressWithType{ + command_view.GetPeerAddress(), + command_view.GetPeerAddressType(), + }, + command_view.GetOwnAddressType(), command_view.GetConnectionIntervalMin(), + command_view.GetConnectionIntervalMax(), command_view.GetMaxLatency(), + command_view.GetSupervisionTimeout(), command_view.GetMinCeLength(), + command_view.GetMaxCeLength()); + send_event_(bluetooth::hci::LeCreateConnectionStatusBuilder::Create(status, kNumCommandPackets)); } void DualModeController::LeCreateConnectionCancel(CommandView command) { - auto command_view = - bluetooth::hci::LeCreateConnectionCancelView::Create(command); + auto command_view = bluetooth::hci::LeCreateConnectionCancelView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< LE Create Connection Cancel"); ErrorCode status = link_layer_controller_.LeCreateConnectionCancel(); - send_event_(bluetooth::hci::LeCreateConnectionCancelCompleteBuilder::Create( - kNumCommandPackets, status)); + send_event_(bluetooth::hci::LeCreateConnectionCancelCompleteBuilder::Create(kNumCommandPackets, + status)); } void DualModeController::LeConnectionUpdate(CommandView command) { @@ -2138,13 +1952,11 @@ void DualModeController::LeConnectionUpdate(CommandView command) { DEBUG(id_, " connection_handle=0x{:x}", command_view.GetConnectionHandle()); ErrorCode status = link_layer_controller_.LeConnectionUpdate( - command_view.GetConnectionHandle(), - command_view.GetConnectionIntervalMin(), - command_view.GetConnectionIntervalMax(), command_view.GetMaxLatency(), - command_view.GetSupervisionTimeout()); + command_view.GetConnectionHandle(), command_view.GetConnectionIntervalMin(), + command_view.GetConnectionIntervalMax(), command_view.GetMaxLatency(), + command_view.GetSupervisionTimeout()); - send_event_(bluetooth::hci::LeConnectionUpdateStatusBuilder::Create( - status, kNumCommandPackets)); + send_event_(bluetooth::hci::LeConnectionUpdateStatusBuilder::Create(status, kNumCommandPackets)); } void DualModeController::CreateConnection(CommandView command) { @@ -2152,31 +1964,27 @@ void DualModeController::CreateConnection(CommandView command) { CHECK_PACKET_VIEW(command_view); Address bd_addr = command_view.GetBdAddr(); uint16_t packet_type = command_view.GetPacketType(); - uint8_t page_scan_mode = - static_cast(command_view.GetPageScanRepetitionMode()); - uint16_t clock_offset = (command_view.GetClockOffsetValid() == - bluetooth::hci::ClockOffsetValid::VALID - ? command_view.GetClockOffset() - : 0); - uint8_t allow_role_switch = - static_cast(command_view.GetAllowRoleSwitch()); + uint8_t page_scan_mode = static_cast(command_view.GetPageScanRepetitionMode()); + uint16_t clock_offset = + (command_view.GetClockOffsetValid() == bluetooth::hci::ClockOffsetValid::VALID + ? command_view.GetClockOffset() + : 0); + uint8_t allow_role_switch = static_cast(command_view.GetAllowRoleSwitch()); DEBUG(id_, "<< Create Connection"); DEBUG(id_, " bd_addr={}", bd_addr); DEBUG(id_, " allow_role_switch={}", command_view.GetAllowRoleSwitch() == - bluetooth::hci::CreateConnectionRoleSwitch::ALLOW_ROLE_SWITCH); + bluetooth::hci::CreateConnectionRoleSwitch::ALLOW_ROLE_SWITCH); - auto status = link_layer_controller_.CreateConnection( - bd_addr, packet_type, page_scan_mode, clock_offset, allow_role_switch); + auto status = link_layer_controller_.CreateConnection(bd_addr, packet_type, page_scan_mode, + clock_offset, allow_role_switch); - send_event_(bluetooth::hci::CreateConnectionStatusBuilder::Create( - status, kNumCommandPackets)); + send_event_(bluetooth::hci::CreateConnectionStatusBuilder::Create(status, kNumCommandPackets)); } void DualModeController::CreateConnectionCancel(CommandView command) { - auto command_view = - bluetooth::hci::CreateConnectionCancelView::Create(command); + auto command_view = bluetooth::hci::CreateConnectionCancelView::Create(command); CHECK_PACKET_VIEW(command_view); Address address = command_view.GetBdAddr(); @@ -2185,8 +1993,8 @@ void DualModeController::CreateConnectionCancel(CommandView command) { auto status = link_layer_controller_.CreateConnectionCancel(address); - send_event_(bluetooth::hci::CreateConnectionCancelCompleteBuilder::Create( - kNumCommandPackets, status, address)); + send_event_(bluetooth::hci::CreateConnectionCancelCompleteBuilder::Create(kNumCommandPackets, + status, address)); } void DualModeController::Disconnect(CommandView command) { @@ -2197,76 +2005,64 @@ void DualModeController::Disconnect(CommandView command) { DEBUG(id_, "<< Disconnect"); DEBUG(id_, " connection_handle=0x{:x}", connection_handle); - if (connection_handle >= kCisHandleRangeStart && - connection_handle < kCisHandleRangeEnd) { + if (connection_handle >= kCisHandleRangeStart && connection_handle < kCisHandleRangeEnd) { link_layer_controller_.ForwardToLl(command); } else { - auto status = link_layer_controller_.Disconnect( - connection_handle, ErrorCode(command_view.GetReason())); + auto status = link_layer_controller_.Disconnect(connection_handle, + ErrorCode(command_view.GetReason())); - send_event_(bluetooth::hci::DisconnectStatusBuilder::Create( - status, kNumCommandPackets)); + send_event_(bluetooth::hci::DisconnectStatusBuilder::Create(status, kNumCommandPackets)); } } void DualModeController::LeReadFilterAcceptListSize(CommandView command) { - auto command_view = - bluetooth::hci::LeReadFilterAcceptListSizeView::Create(command); + auto command_view = bluetooth::hci::LeReadFilterAcceptListSizeView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< LE Read Filter Accept List Size"); send_event_(bluetooth::hci::LeReadFilterAcceptListSizeCompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS, - properties_.le_filter_accept_list_size)); + kNumCommandPackets, ErrorCode::SUCCESS, properties_.le_filter_accept_list_size)); } void DualModeController::LeClearFilterAcceptList(CommandView command) { - auto command_view = - bluetooth::hci::LeClearFilterAcceptListView::Create(command); + auto command_view = bluetooth::hci::LeClearFilterAcceptListView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< LE Clear Filter Accept List"); ErrorCode status = link_layer_controller_.LeClearFilterAcceptList(); - send_event_(bluetooth::hci::LeClearFilterAcceptListCompleteBuilder::Create( - kNumCommandPackets, status)); + send_event_(bluetooth::hci::LeClearFilterAcceptListCompleteBuilder::Create(kNumCommandPackets, + status)); } void DualModeController::LeAddDeviceToFilterAcceptList(CommandView command) { - auto command_view = - bluetooth::hci::LeAddDeviceToFilterAcceptListView::Create(command); + auto command_view = bluetooth::hci::LeAddDeviceToFilterAcceptListView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< LE Add Device To Filter Accept List"); DEBUG(id_, " address={}", command_view.GetAddress()); DEBUG(id_, " address_type={}", - bluetooth::hci::FilterAcceptListAddressTypeText( - command_view.GetAddressType())); + bluetooth::hci::FilterAcceptListAddressTypeText(command_view.GetAddressType())); ErrorCode status = link_layer_controller_.LeAddDeviceToFilterAcceptList( - command_view.GetAddressType(), command_view.GetAddress()); - send_event_( - bluetooth::hci::LeAddDeviceToFilterAcceptListCompleteBuilder::Create( + command_view.GetAddressType(), command_view.GetAddress()); + send_event_(bluetooth::hci::LeAddDeviceToFilterAcceptListCompleteBuilder::Create( kNumCommandPackets, status)); } -void DualModeController::LeRemoveDeviceFromFilterAcceptList( - CommandView command) { - auto command_view = - bluetooth::hci::LeRemoveDeviceFromFilterAcceptListView::Create(command); +void DualModeController::LeRemoveDeviceFromFilterAcceptList(CommandView command) { + auto command_view = bluetooth::hci::LeRemoveDeviceFromFilterAcceptListView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< LE Remove Device From Filter Accept List"); DEBUG(id_, " address={}", command_view.GetAddress()); DEBUG(id_, " address_type={}", - bluetooth::hci::FilterAcceptListAddressTypeText( - command_view.GetAddressType())); + bluetooth::hci::FilterAcceptListAddressTypeText(command_view.GetAddressType())); ErrorCode status = link_layer_controller_.LeRemoveDeviceFromFilterAcceptList( - command_view.GetAddressType(), command_view.GetAddress()); - send_event_( - bluetooth::hci::LeRemoveDeviceFromFilterAcceptListCompleteBuilder::Create( + command_view.GetAddressType(), command_view.GetAddress()); + send_event_(bluetooth::hci::LeRemoveDeviceFromFilterAcceptListCompleteBuilder::Create( kNumCommandPackets, status)); } @@ -2277,67 +2073,56 @@ void DualModeController::LeClearResolvingList(CommandView command) { DEBUG(id_, "<< LE Clear Resolving List"); ErrorCode status = link_layer_controller_.LeClearResolvingList(); - send_event_(bluetooth::hci::LeClearResolvingListCompleteBuilder::Create( - kNumCommandPackets, status)); + send_event_( + bluetooth::hci::LeClearResolvingListCompleteBuilder::Create(kNumCommandPackets, status)); } void DualModeController::LeReadResolvingListSize(CommandView command) { - auto command_view = - bluetooth::hci::LeReadResolvingListSizeView::Create(command); + auto command_view = bluetooth::hci::LeReadResolvingListSizeView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< LE Read Resolving List Size"); send_event_(bluetooth::hci::LeReadResolvingListSizeCompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS, - properties_.le_resolving_list_size)); + kNumCommandPackets, ErrorCode::SUCCESS, properties_.le_resolving_list_size)); } void DualModeController::LeReadPeerResolvableAddress(CommandView command) { - auto command_view = - bluetooth::hci::LeReadPeerResolvableAddressView::Create(command); + auto command_view = bluetooth::hci::LeReadPeerResolvableAddressView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< LE Read Peer Resolvable Address"); - DEBUG(id_, " peer_identity_address={}", - command_view.GetPeerIdentityAddress()); + DEBUG(id_, " peer_identity_address={}", command_view.GetPeerIdentityAddress()); DEBUG(id_, " peer_identity_address_type={}", - bluetooth::hci::PeerAddressTypeText( - command_view.GetPeerIdentityAddressType())); + bluetooth::hci::PeerAddressTypeText(command_view.GetPeerIdentityAddressType())); Address peer_resolvable_address; ErrorCode status = link_layer_controller_.LeReadPeerResolvableAddress( - command_view.GetPeerIdentityAddressType(), - command_view.GetPeerIdentityAddress(), &peer_resolvable_address); - send_event_( - bluetooth::hci::LeReadPeerResolvableAddressCompleteBuilder::Create( + command_view.GetPeerIdentityAddressType(), command_view.GetPeerIdentityAddress(), + &peer_resolvable_address); + send_event_(bluetooth::hci::LeReadPeerResolvableAddressCompleteBuilder::Create( kNumCommandPackets, status, peer_resolvable_address)); } void DualModeController::LeReadLocalResolvableAddress(CommandView command) { - auto command_view = - bluetooth::hci::LeReadLocalResolvableAddressView::Create(command); + auto command_view = bluetooth::hci::LeReadLocalResolvableAddressView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< LE Read Local Resolvable Address"); - DEBUG(id_, " peer_identity_address={}", - command_view.GetPeerIdentityAddress()); + DEBUG(id_, " peer_identity_address={}", command_view.GetPeerIdentityAddress()); DEBUG(id_, " peer_identity_address_type={}", - bluetooth::hci::PeerAddressTypeText( - command_view.GetPeerIdentityAddressType())); + bluetooth::hci::PeerAddressTypeText(command_view.GetPeerIdentityAddressType())); Address local_resolvable_address; ErrorCode status = link_layer_controller_.LeReadLocalResolvableAddress( - command_view.GetPeerIdentityAddressType(), - command_view.GetPeerIdentityAddress(), &local_resolvable_address); - send_event_( - bluetooth::hci::LeReadLocalResolvableAddressCompleteBuilder::Create( + command_view.GetPeerIdentityAddressType(), command_view.GetPeerIdentityAddress(), + &local_resolvable_address); + send_event_(bluetooth::hci::LeReadLocalResolvableAddressCompleteBuilder::Create( kNumCommandPackets, status, local_resolvable_address)); } void DualModeController::LeReadMaximumDataLength(CommandView command) { - auto command_view = - bluetooth::hci::LeReadMaximumDataLengthView::Create(command); + auto command_view = bluetooth::hci::LeReadMaximumDataLengthView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< LE Read Maximum Data Length"); @@ -2348,7 +2133,7 @@ void DualModeController::LeReadMaximumDataLength(CommandView command) { data_length.supported_max_tx_octets_ = kLeMaximumDataLength + 10; data_length.supported_max_tx_time_ = kLeMaximumDataTime + 10; send_event_(bluetooth::hci::LeReadMaximumDataLengthCompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS, data_length)); + kNumCommandPackets, ErrorCode::SUCCESS, data_length)); } void DualModeController::LeReadPhy(CommandView command) { @@ -2361,10 +2146,9 @@ void DualModeController::LeReadPhy(CommandView command) { bluetooth::hci::PhyType tx_phy{}; bluetooth::hci::PhyType rx_phy{}; - ErrorCode status = - link_layer_controller_.LeReadPhy(connection_handle, &tx_phy, &rx_phy); - send_event_(bluetooth::hci::LeReadPhyCompleteBuilder::Create( - kNumCommandPackets, status, connection_handle, tx_phy, rx_phy)); + ErrorCode status = link_layer_controller_.LeReadPhy(connection_handle, &tx_phy, &rx_phy); + send_event_(bluetooth::hci::LeReadPhyCompleteBuilder::Create(kNumCommandPackets, status, + connection_handle, tx_phy, rx_phy)); } void DualModeController::LeSetDefaultPhy(CommandView command) { @@ -2374,11 +2158,10 @@ void DualModeController::LeSetDefaultPhy(CommandView command) { DEBUG(id_, "<< LE Set Default Phy"); ErrorCode status = link_layer_controller_.LeSetDefaultPhy( - command_view.GetAllPhysNoTransmitPreference(), - command_view.GetAllPhysNoReceivePreference(), command_view.GetTxPhys(), - command_view.GetRxPhys()); - send_event_(bluetooth::hci::LeSetDefaultPhyCompleteBuilder::Create( - kNumCommandPackets, status)); + command_view.GetAllPhysNoTransmitPreference(), + command_view.GetAllPhysNoReceivePreference(), command_view.GetTxPhys(), + command_view.GetRxPhys()); + send_event_(bluetooth::hci::LeSetDefaultPhyCompleteBuilder::Create(kNumCommandPackets, status)); } void DualModeController::LeSetPhy(CommandView command) { @@ -2389,32 +2172,26 @@ void DualModeController::LeSetPhy(CommandView command) { DEBUG(id_, " connection_handle=0x{:x}", command_view.GetConnectionHandle()); ErrorCode status = link_layer_controller_.LeSetPhy( - command_view.GetConnectionHandle(), - command_view.GetAllPhysNoTransmitPreference(), - command_view.GetAllPhysNoReceivePreference(), command_view.GetTxPhys(), - command_view.GetRxPhys(), command_view.GetPhyOptions()); - send_event_(bluetooth::hci::LeSetPhyStatusBuilder::Create( - status, kNumCommandPackets)); + command_view.GetConnectionHandle(), command_view.GetAllPhysNoTransmitPreference(), + command_view.GetAllPhysNoReceivePreference(), command_view.GetTxPhys(), + command_view.GetRxPhys(), command_view.GetPhyOptions()); + send_event_(bluetooth::hci::LeSetPhyStatusBuilder::Create(status, kNumCommandPackets)); } void DualModeController::LeReadSuggestedDefaultDataLength(CommandView command) { - auto command_view = - bluetooth::hci::LeReadSuggestedDefaultDataLengthView::Create(command); + auto command_view = bluetooth::hci::LeReadSuggestedDefaultDataLengthView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< LE Read Suggested Default Data Length"); - send_event_( - bluetooth::hci::LeReadSuggestedDefaultDataLengthCompleteBuilder::Create( + send_event_(bluetooth::hci::LeReadSuggestedDefaultDataLengthCompleteBuilder::Create( kNumCommandPackets, ErrorCode::SUCCESS, link_layer_controller_.GetLeSuggestedMaxTxOctets(), link_layer_controller_.GetLeSuggestedMaxTxTime())); } -void DualModeController::LeWriteSuggestedDefaultDataLength( - CommandView command) { - auto command_view = - bluetooth::hci::LeWriteSuggestedDefaultDataLengthView::Create(command); +void DualModeController::LeWriteSuggestedDefaultDataLength(CommandView command) { + auto command_view = bluetooth::hci::LeWriteSuggestedDefaultDataLengthView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< LE Write Suggested Default Data Length"); @@ -2422,97 +2199,78 @@ void DualModeController::LeWriteSuggestedDefaultDataLength( uint16_t max_tx_octets = command_view.GetTxOctets(); uint16_t max_tx_time = command_view.GetTxTime(); ErrorCode status = ErrorCode::SUCCESS; - if (max_tx_octets > 0xFB || max_tx_octets < 0x1B || max_tx_time < 0x148 || - max_tx_time > 0x4290) { + if (max_tx_octets > 0xFB || max_tx_octets < 0x1B || max_tx_time < 0x148 || max_tx_time > 0x4290) { status = ErrorCode::INVALID_HCI_COMMAND_PARAMETERS; } else { link_layer_controller_.SetLeSuggestedMaxTxOctets(max_tx_octets); link_layer_controller_.SetLeSuggestedMaxTxTime(max_tx_time); } - send_event_( - bluetooth::hci::LeWriteSuggestedDefaultDataLengthCompleteBuilder::Create( + send_event_(bluetooth::hci::LeWriteSuggestedDefaultDataLengthCompleteBuilder::Create( kNumCommandPackets, status)); } void DualModeController::LeAddDeviceToResolvingList(CommandView command) { - auto command_view = - bluetooth::hci::LeAddDeviceToResolvingListView::Create(command); + auto command_view = bluetooth::hci::LeAddDeviceToResolvingListView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< LE Add Device to Resolving List"); - DEBUG(id_, " peer_identity_address={}", - command_view.GetPeerIdentityAddress()); + DEBUG(id_, " peer_identity_address={}", command_view.GetPeerIdentityAddress()); DEBUG(id_, " peer_identity_address_type={}", - bluetooth::hci::PeerAddressTypeText( - command_view.GetPeerIdentityAddressType())); + bluetooth::hci::PeerAddressTypeText(command_view.GetPeerIdentityAddressType())); ErrorCode status = link_layer_controller_.LeAddDeviceToResolvingList( - command_view.GetPeerIdentityAddressType(), - command_view.GetPeerIdentityAddress(), command_view.GetPeerIrk(), - command_view.GetLocalIrk()); - send_event_(bluetooth::hci::LeAddDeviceToResolvingListCompleteBuilder::Create( - kNumCommandPackets, status)); + command_view.GetPeerIdentityAddressType(), command_view.GetPeerIdentityAddress(), + command_view.GetPeerIrk(), command_view.GetLocalIrk()); + send_event_(bluetooth::hci::LeAddDeviceToResolvingListCompleteBuilder::Create(kNumCommandPackets, + status)); } void DualModeController::LeRemoveDeviceFromResolvingList(CommandView command) { - auto command_view = - bluetooth::hci::LeRemoveDeviceFromResolvingListView::Create(command); + auto command_view = bluetooth::hci::LeRemoveDeviceFromResolvingListView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< LE Remove Device from Resolving List"); - DEBUG(id_, " peer_identity_address={}", - command_view.GetPeerIdentityAddress()); + DEBUG(id_, " peer_identity_address={}", command_view.GetPeerIdentityAddress()); DEBUG(id_, " peer_identity_address_type={}", - bluetooth::hci::PeerAddressTypeText( - command_view.GetPeerIdentityAddressType())); + bluetooth::hci::PeerAddressTypeText(command_view.GetPeerIdentityAddressType())); ErrorCode status = link_layer_controller_.LeRemoveDeviceFromResolvingList( - command_view.GetPeerIdentityAddressType(), - command_view.GetPeerIdentityAddress()); - send_event_( - bluetooth::hci::LeRemoveDeviceFromResolvingListCompleteBuilder::Create( + command_view.GetPeerIdentityAddressType(), command_view.GetPeerIdentityAddress()); + send_event_(bluetooth::hci::LeRemoveDeviceFromResolvingListCompleteBuilder::Create( kNumCommandPackets, status)); } -void DualModeController::LeSetPeriodicAdvertisingParameters( - CommandView command) { - auto command_view = - bluetooth::hci::LeSetPeriodicAdvertisingParametersView::Create(command); +void DualModeController::LeSetPeriodicAdvertisingParameters(CommandView command) { + auto command_view = bluetooth::hci::LeSetPeriodicAdvertisingParametersView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< LE Set Periodic Advertising Parameters"); DEBUG(id_, " advertising_handle={}", command_view.GetAdvertisingHandle()); ErrorCode status = link_layer_controller_.LeSetPeriodicAdvertisingParameters( - command_view.GetAdvertisingHandle(), - command_view.GetPeriodicAdvertisingIntervalMin(), - command_view.GetPeriodicAdvertisingIntervalMax(), - command_view.GetIncludeTxPower()); - send_event_( - bluetooth::hci::LeSetPeriodicAdvertisingParametersCompleteBuilder::Create( + command_view.GetAdvertisingHandle(), command_view.GetPeriodicAdvertisingIntervalMin(), + command_view.GetPeriodicAdvertisingIntervalMax(), command_view.GetIncludeTxPower()); + send_event_(bluetooth::hci::LeSetPeriodicAdvertisingParametersCompleteBuilder::Create( kNumCommandPackets, status)); } void DualModeController::LeSetPeriodicAdvertisingData(CommandView command) { - auto command_view = - bluetooth::hci::LeSetPeriodicAdvertisingDataView::Create(command); + auto command_view = bluetooth::hci::LeSetPeriodicAdvertisingDataView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< LE Set Periodic Advertising Data"); DEBUG(id_, " advertising_handle={}", command_view.GetAdvertisingHandle()); ErrorCode status = link_layer_controller_.LeSetPeriodicAdvertisingData( - command_view.GetAdvertisingHandle(), command_view.GetOperation(), - command_view.GetAdvertisingData()); - send_event_( - bluetooth::hci::LeSetPeriodicAdvertisingDataCompleteBuilder::Create( + command_view.GetAdvertisingHandle(), command_view.GetOperation(), + command_view.GetAdvertisingData()); + send_event_(bluetooth::hci::LeSetPeriodicAdvertisingDataCompleteBuilder::Create( kNumCommandPackets, status)); } void DualModeController::LeSetPeriodicAdvertisingEnable(CommandView command) { - auto command_view = - bluetooth::hci::LeSetPeriodicAdvertisingEnableView::Create(command); + auto command_view = bluetooth::hci::LeSetPeriodicAdvertisingEnableView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< LE Set Periodic Advertising Enable"); @@ -2520,170 +2278,135 @@ void DualModeController::LeSetPeriodicAdvertisingEnable(CommandView command) { DEBUG(id_, " enable={}", command_view.GetEnable() != 0); ErrorCode status = link_layer_controller_.LeSetPeriodicAdvertisingEnable( - command_view.GetEnable(), command_view.GetIncludeAdi(), - command_view.GetAdvertisingHandle()); - send_event_( - bluetooth::hci::LeSetPeriodicAdvertisingEnableCompleteBuilder::Create( + command_view.GetEnable(), command_view.GetIncludeAdi(), + command_view.GetAdvertisingHandle()); + send_event_(bluetooth::hci::LeSetPeriodicAdvertisingEnableCompleteBuilder::Create( kNumCommandPackets, status)); } void DualModeController::LePeriodicAdvertisingCreateSync(CommandView command) { - auto command_view = - bluetooth::hci::LePeriodicAdvertisingCreateSyncView::Create(command); + auto command_view = bluetooth::hci::LePeriodicAdvertisingCreateSyncView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< LE Periodic Advertising Create Sync"); DEBUG(id_, " advertiser_address={}", command_view.GetAdvertiserAddress()); DEBUG(id_, " advertiser_address_type={}", - bluetooth::hci::AdvertiserAddressTypeText( - command_view.GetAdvertiserAddressType())); + bluetooth::hci::AdvertiserAddressTypeText(command_view.GetAdvertiserAddressType())); ErrorCode status = link_layer_controller_.LePeriodicAdvertisingCreateSync( - command_view.GetOptions(), command_view.GetAdvertisingSid(), - command_view.GetAdvertiserAddressType(), - command_view.GetAdvertiserAddress(), command_view.GetSkip(), - command_view.GetSyncTimeout(), command_view.GetSyncCteType()); - send_event_( - bluetooth::hci::LePeriodicAdvertisingCreateSyncStatusBuilder::Create( + command_view.GetOptions(), command_view.GetAdvertisingSid(), + command_view.GetAdvertiserAddressType(), command_view.GetAdvertiserAddress(), + command_view.GetSkip(), command_view.GetSyncTimeout(), command_view.GetSyncCteType()); + send_event_(bluetooth::hci::LePeriodicAdvertisingCreateSyncStatusBuilder::Create( status, kNumCommandPackets)); } -void DualModeController::LePeriodicAdvertisingCreateSyncCancel( - CommandView command) { - auto command_view = - bluetooth::hci::LePeriodicAdvertisingCreateSyncCancelView::Create( - command); +void DualModeController::LePeriodicAdvertisingCreateSyncCancel(CommandView command) { + auto command_view = bluetooth::hci::LePeriodicAdvertisingCreateSyncCancelView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< LE Periodic Advertising Create Sync Cancel"); - ErrorCode status = - link_layer_controller_.LePeriodicAdvertisingCreateSyncCancel(); - send_event_( - bluetooth::hci::LePeriodicAdvertisingCreateSyncCancelCompleteBuilder:: - Create(kNumCommandPackets, status)); + ErrorCode status = link_layer_controller_.LePeriodicAdvertisingCreateSyncCancel(); + send_event_(bluetooth::hci::LePeriodicAdvertisingCreateSyncCancelCompleteBuilder::Create( + kNumCommandPackets, status)); } -void DualModeController::LePeriodicAdvertisingTerminateSync( - CommandView command) { - auto command_view = - bluetooth::hci::LePeriodicAdvertisingTerminateSyncView::Create(command); +void DualModeController::LePeriodicAdvertisingTerminateSync(CommandView command) { + auto command_view = bluetooth::hci::LePeriodicAdvertisingTerminateSyncView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< LE Periodic Advertising Terminate Sync"); DEBUG(id_, " sync_handle=0x{:x}", command_view.GetSyncHandle()); - ErrorCode status = link_layer_controller_.LePeriodicAdvertisingTerminateSync( - command_view.GetSyncHandle()); - send_event_( - bluetooth::hci::LePeriodicAdvertisingTerminateSyncCompleteBuilder::Create( + ErrorCode status = + link_layer_controller_.LePeriodicAdvertisingTerminateSync(command_view.GetSyncHandle()); + send_event_(bluetooth::hci::LePeriodicAdvertisingTerminateSyncCompleteBuilder::Create( kNumCommandPackets, status)); } -void DualModeController::LeAddDeviceToPeriodicAdvertiserList( - CommandView command) { - auto command_view = - bluetooth::hci::LeAddDeviceToPeriodicAdvertiserListView::Create(command); +void DualModeController::LeAddDeviceToPeriodicAdvertiserList(CommandView command) { + auto command_view = bluetooth::hci::LeAddDeviceToPeriodicAdvertiserListView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< LE Add Device to Periodic Advertiser List"); DEBUG(id_, " advertiser_address={}", command_view.GetAdvertiserAddress()); DEBUG(id_, " advertiser_address_type={}", - bluetooth::hci::AdvertiserAddressTypeText( - command_view.GetAdvertiserAddressType())); + bluetooth::hci::AdvertiserAddressTypeText(command_view.GetAdvertiserAddressType())); ErrorCode status = link_layer_controller_.LeAddDeviceToPeriodicAdvertiserList( - command_view.GetAdvertiserAddressType(), - command_view.GetAdvertiserAddress(), command_view.GetAdvertisingSid()); - send_event_( - bluetooth::hci::LeAddDeviceToPeriodicAdvertiserListCompleteBuilder:: - Create(kNumCommandPackets, status)); + command_view.GetAdvertiserAddressType(), command_view.GetAdvertiserAddress(), + command_view.GetAdvertisingSid()); + send_event_(bluetooth::hci::LeAddDeviceToPeriodicAdvertiserListCompleteBuilder::Create( + kNumCommandPackets, status)); } -void DualModeController::LeRemoveDeviceFromPeriodicAdvertiserList( - CommandView command) { - auto command_view = - bluetooth::hci::LeRemoveDeviceFromPeriodicAdvertiserListView::Create( - command); +void DualModeController::LeRemoveDeviceFromPeriodicAdvertiserList(CommandView command) { + auto command_view = bluetooth::hci::LeRemoveDeviceFromPeriodicAdvertiserListView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< LE Remove Device from Periodic Advertiser List"); DEBUG(id_, " advertiser_address={}", command_view.GetAdvertiserAddress()); DEBUG(id_, " advertiser_address_type={}", - bluetooth::hci::AdvertiserAddressTypeText( - command_view.GetAdvertiserAddressType())); + bluetooth::hci::AdvertiserAddressTypeText(command_view.GetAdvertiserAddressType())); - ErrorCode status = - link_layer_controller_.LeRemoveDeviceFromPeriodicAdvertiserList( - command_view.GetAdvertiserAddressType(), - command_view.GetAdvertiserAddress(), + ErrorCode status = link_layer_controller_.LeRemoveDeviceFromPeriodicAdvertiserList( + command_view.GetAdvertiserAddressType(), command_view.GetAdvertiserAddress(), command_view.GetAdvertisingSid()); - send_event_( - bluetooth::hci::LeRemoveDeviceFromPeriodicAdvertiserListCompleteBuilder:: - Create(kNumCommandPackets, status)); + send_event_(bluetooth::hci::LeRemoveDeviceFromPeriodicAdvertiserListCompleteBuilder::Create( + kNumCommandPackets, status)); } void DualModeController::LeClearPeriodicAdvertiserList(CommandView command) { - auto command_view = - bluetooth::hci::LeClearPeriodicAdvertiserListView::Create(command); + auto command_view = bluetooth::hci::LeClearPeriodicAdvertiserListView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< LE Clear Periodic Advertiser List"); ErrorCode status = link_layer_controller_.LeClearPeriodicAdvertiserList(); - send_event_( - bluetooth::hci::LeClearPeriodicAdvertiserListCompleteBuilder::Create( + send_event_(bluetooth::hci::LeClearPeriodicAdvertiserListCompleteBuilder::Create( kNumCommandPackets, status)); } void DualModeController::LeReadPeriodicAdvertiserListSize(CommandView command) { - auto command_view = - bluetooth::hci::LeReadPeriodicAdvertiserListSizeView::Create(command); + auto command_view = bluetooth::hci::LeReadPeriodicAdvertiserListSizeView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< LE Read Periodic Advertiser List Size"); - send_event_( - bluetooth::hci::LeReadPeriodicAdvertiserListSizeCompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS, - properties_.le_periodic_advertiser_list_size)); + send_event_(bluetooth::hci::LeReadPeriodicAdvertiserListSizeCompleteBuilder::Create( + kNumCommandPackets, ErrorCode::SUCCESS, properties_.le_periodic_advertiser_list_size)); } void DualModeController::LeSetExtendedScanParameters(CommandView command) { - auto command_view = - bluetooth::hci::LeSetExtendedScanParametersView::Create(command); + auto command_view = bluetooth::hci::LeSetExtendedScanParametersView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< LE Set Extended Scan Parameters"); ErrorCode status = link_layer_controller_.LeSetExtendedScanParameters( - command_view.GetOwnAddressType(), command_view.GetScanningFilterPolicy(), - command_view.GetScanningPhys(), command_view.GetScanningPhyParameters()); - send_event_( - bluetooth::hci::LeSetExtendedScanParametersCompleteBuilder::Create( - kNumCommandPackets, status)); + command_view.GetOwnAddressType(), command_view.GetScanningFilterPolicy(), + command_view.GetScanningPhys(), command_view.GetScanningPhyParameters()); + send_event_(bluetooth::hci::LeSetExtendedScanParametersCompleteBuilder::Create(kNumCommandPackets, + status)); } void DualModeController::LeSetExtendedScanEnable(CommandView command) { - auto command_view = - bluetooth::hci::LeSetExtendedScanEnableView::Create(command); + auto command_view = bluetooth::hci::LeSetExtendedScanEnableView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< LE Set Extended Scan Enable"); - DEBUG(id_, " enable={}", - command_view.GetEnable() == bluetooth::hci::Enable::ENABLED); + DEBUG(id_, " enable={}", command_view.GetEnable() == bluetooth::hci::Enable::ENABLED); ErrorCode status = link_layer_controller_.LeSetExtendedScanEnable( - command_view.GetEnable() == bluetooth::hci::Enable::ENABLED, - command_view.GetFilterDuplicates(), command_view.GetDuration(), - command_view.GetPeriod()); - send_event_(bluetooth::hci::LeSetExtendedScanEnableCompleteBuilder::Create( - kNumCommandPackets, status)); + command_view.GetEnable() == bluetooth::hci::Enable::ENABLED, + command_view.GetFilterDuplicates(), command_view.GetDuration(), command_view.GetPeriod()); + send_event_(bluetooth::hci::LeSetExtendedScanEnableCompleteBuilder::Create(kNumCommandPackets, + status)); } void DualModeController::LeExtendedCreateConnection(CommandView command) { - auto command_view = - bluetooth::hci::LeExtendedCreateConnectionView::Create(command); + auto command_view = bluetooth::hci::LeExtendedCreateConnectionView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< LE Extended Create Connection"); @@ -2691,8 +2414,7 @@ void DualModeController::LeExtendedCreateConnection(CommandView command) { DEBUG(id_, " peer_address_type={}", bluetooth::hci::PeerAddressTypeText(command_view.GetPeerAddressType())); DEBUG(id_, " initiator_filter_policy={}", - bluetooth::hci::InitiatorFilterPolicyText( - command_view.GetInitiatorFilterPolicy())); + bluetooth::hci::InitiatorFilterPolicyText(command_view.GetInitiatorFilterPolicy())); AddressType peer_address_type; switch (command_view.GetPeerAddressType()) { @@ -2706,15 +2428,14 @@ void DualModeController::LeExtendedCreateConnection(CommandView command) { } ErrorCode status = link_layer_controller_.LeExtendedCreateConnection( - command_view.GetInitiatorFilterPolicy(), command_view.GetOwnAddressType(), - AddressWithType{ - command_view.GetPeerAddress(), - peer_address_type, - }, - command_view.GetInitiatingPhys(), - command_view.GetInitiatingPhyParameters()); - send_event_(bluetooth::hci::LeExtendedCreateConnectionStatusBuilder::Create( - status, kNumCommandPackets)); + command_view.GetInitiatorFilterPolicy(), command_view.GetOwnAddressType(), + AddressWithType{ + command_view.GetPeerAddress(), + peer_address_type, + }, + command_view.GetInitiatingPhys(), command_view.GetInitiatingPhyParameters()); + send_event_(bluetooth::hci::LeExtendedCreateConnectionStatusBuilder::Create(status, + kNumCommandPackets)); } void DualModeController::LeSetPrivacyMode(CommandView command) { @@ -2722,19 +2443,15 @@ void DualModeController::LeSetPrivacyMode(CommandView command) { CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< LE Set Privacy Mode"); - DEBUG(id_, " peer_identity_address={}", - command_view.GetPeerIdentityAddress()); + DEBUG(id_, " peer_identity_address={}", command_view.GetPeerIdentityAddress()); DEBUG(id_, " peer_identity_address_type={}", - bluetooth::hci::PeerAddressTypeText( - command_view.GetPeerIdentityAddressType())); - DEBUG(id_, " privacy_mode={}", - bluetooth::hci::PrivacyModeText(command_view.GetPrivacyMode())); + bluetooth::hci::PeerAddressTypeText(command_view.GetPeerIdentityAddressType())); + DEBUG(id_, " privacy_mode={}", bluetooth::hci::PrivacyModeText(command_view.GetPrivacyMode())); ErrorCode status = link_layer_controller_.LeSetPrivacyMode( - command_view.GetPeerIdentityAddressType(), - command_view.GetPeerIdentityAddress(), command_view.GetPrivacyMode()); - send_event_(bluetooth::hci::LeSetPrivacyModeCompleteBuilder::Create( - kNumCommandPackets, status)); + command_view.GetPeerIdentityAddressType(), command_view.GetPeerIdentityAddress(), + command_view.GetPrivacyMode()); + send_event_(bluetooth::hci::LeSetPrivacyModeCompleteBuilder::Create(kNumCommandPackets, status)); } void DualModeController::LeReadRemoteFeatures(CommandView command) { @@ -2745,11 +2462,11 @@ void DualModeController::LeReadRemoteFeatures(CommandView command) { DEBUG(id_, "<< LE Read Remote Features"); DEBUG(id_, " connection_handle=0x{:x}", handle); - auto status = link_layer_controller_.SendCommandToRemoteByHandle( - OpCode::LE_READ_REMOTE_FEATURES, command_view.bytes(), handle); + auto status = link_layer_controller_.SendCommandToRemoteByHandle(OpCode::LE_READ_REMOTE_FEATURES, + command_view.bytes(), handle); - send_event_(bluetooth::hci::LeReadRemoteFeaturesStatusBuilder::Create( - status, kNumCommandPackets)); + send_event_( + bluetooth::hci::LeReadRemoteFeaturesStatusBuilder::Create(status, kNumCommandPackets)); } void DualModeController::LeEncrypt(CommandView command) { @@ -2758,11 +2475,11 @@ void DualModeController::LeEncrypt(CommandView command) { DEBUG(id_, "<< LE Encrypt"); - auto encrypted_data = rootcanal::crypto::aes_128( - command_view.GetKey(), command_view.GetPlaintextData()); + auto encrypted_data = + rootcanal::crypto::aes_128(command_view.GetKey(), command_view.GetPlaintextData()); - send_event_(bluetooth::hci::LeEncryptCompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS, encrypted_data)); + send_event_(bluetooth::hci::LeEncryptCompleteBuilder::Create(kNumCommandPackets, + ErrorCode::SUCCESS, encrypted_data)); } void DualModeController::LeRand(CommandView command) { @@ -2771,64 +2488,52 @@ void DualModeController::LeRand(CommandView command) { DEBUG(id_, "<< LE Rand"); - send_event_(bluetooth::hci::LeRandCompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS, random_generator_())); + send_event_(bluetooth::hci::LeRandCompleteBuilder::Create(kNumCommandPackets, ErrorCode::SUCCESS, + random_generator_())); } void DualModeController::LeReadSupportedStates(CommandView command) { - auto command_view = - bluetooth::hci::LeReadSupportedStatesView::Create(command); + auto command_view = bluetooth::hci::LeReadSupportedStatesView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< LE Read Supported States"); send_event_(bluetooth::hci::LeReadSupportedStatesCompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS, properties_.le_supported_states)); + kNumCommandPackets, ErrorCode::SUCCESS, properties_.le_supported_states)); } -void DualModeController::LeRemoteConnectionParameterRequestReply( - CommandView command) { - auto command_view = - bluetooth::hci::LeRemoteConnectionParameterRequestReplyView::Create( - command); +void DualModeController::LeRemoteConnectionParameterRequestReply(CommandView command) { + auto command_view = bluetooth::hci::LeRemoteConnectionParameterRequestReplyView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< LE Remote Connection Parameters Request Reply"); DEBUG(id_, " connection_handle=0x{:x}", command_view.GetConnectionHandle()); auto status = link_layer_controller_.LeRemoteConnectionParameterRequestReply( - command_view.GetConnectionHandle(), command_view.GetIntervalMin(), - command_view.GetIntervalMax(), command_view.GetTimeout(), - command_view.GetLatency(), command_view.GetMinimumCeLength(), - command_view.GetMaximumCeLength()); - send_event_( - bluetooth::hci::LeRemoteConnectionParameterRequestReplyCompleteBuilder:: - Create(kNumCommandPackets, status, - command_view.GetConnectionHandle())); + command_view.GetConnectionHandle(), command_view.GetIntervalMin(), + command_view.GetIntervalMax(), command_view.GetTimeout(), command_view.GetLatency(), + command_view.GetMinimumCeLength(), command_view.GetMaximumCeLength()); + send_event_(bluetooth::hci::LeRemoteConnectionParameterRequestReplyCompleteBuilder::Create( + kNumCommandPackets, status, command_view.GetConnectionHandle())); } -void DualModeController::LeRemoteConnectionParameterRequestNegativeReply( - CommandView command) { - auto command_view = bluetooth::hci:: - LeRemoteConnectionParameterRequestNegativeReplyView::Create(command); +void DualModeController::LeRemoteConnectionParameterRequestNegativeReply(CommandView command) { + auto command_view = + bluetooth::hci::LeRemoteConnectionParameterRequestNegativeReplyView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< LE Remote Connection Parameters Request Negative Reply"); DEBUG(id_, " connection_handle=0x{:x}", command_view.GetConnectionHandle()); - auto status = - link_layer_controller_.LeRemoteConnectionParameterRequestNegativeReply( + auto status = link_layer_controller_.LeRemoteConnectionParameterRequestNegativeReply( command_view.GetConnectionHandle(), command_view.GetReason()); send_event_( - bluetooth::hci:: - LeRemoteConnectionParameterRequestNegativeReplyCompleteBuilder:: - Create(kNumCommandPackets, status, - command_view.GetConnectionHandle())); + bluetooth::hci::LeRemoteConnectionParameterRequestNegativeReplyCompleteBuilder::Create( + kNumCommandPackets, status, command_view.GetConnectionHandle())); } void DualModeController::LeGetVendorCapabilities(CommandView command) { - auto command_view = - bluetooth::hci::LeGetVendorCapabilitiesView::Create(command); + auto command_view = bluetooth::hci::LeGetVendorCapabilitiesView::Create(command); CHECK_PACKET_VIEW(command_view); if (!properties_.supports_le_get_vendor_capabilities_command) { @@ -2841,20 +2546,17 @@ void DualModeController::LeGetVendorCapabilities(CommandView command) { bluetooth::hci::VendorCapabilities_V_0_98 vendor_capabilities; vendor_capabilities.total_scan_results_storage_ = 0; vendor_capabilities.max_irk_list_sz_ = 16; - vendor_capabilities.filtering_support_ = - properties_.supports_le_apcf_vendor_command; + vendor_capabilities.filtering_support_ = properties_.supports_le_apcf_vendor_command; vendor_capabilities.max_filter_ = properties_.le_apcf_filter_list_size; vendor_capabilities.activity_energy_info_support_ = 0; - vendor_capabilities.total_num_of_advt_tracked_ = - properties_.le_apcf_num_of_tracked_advertisers; + vendor_capabilities.total_num_of_advt_tracked_ = properties_.le_apcf_num_of_tracked_advertisers; vendor_capabilities.extended_scan_support_ = 0; vendor_capabilities.debug_logging_supported_ = 0; vendor_capabilities.a2dp_source_offload_capability_mask_ = 0; vendor_capabilities.bluetooth_quality_report_support_ = 0; send_event_(bluetooth::hci::LeGetVendorCapabilitiesCompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS, - vendor_capabilities.SerializeToBytes())); + kNumCommandPackets, ErrorCode::SUCCESS, vendor_capabilities.SerializeToBytes())); } void DualModeController::LeBatchScan(CommandView command) { @@ -2874,29 +2576,24 @@ void DualModeController::LeApcf(CommandView command) { switch (command_view.GetApcfOpcode()) { case bluetooth::hci::ApcfOpcode::ENABLE: { - auto subcommand_view = - bluetooth::hci::LeApcfEnableView::Create(command_view); + auto subcommand_view = bluetooth::hci::LeApcfEnableView::Create(command_view); CHECK_PACKET_VIEW(subcommand_view); DEBUG(id_, "<< LE APCF Enable"); - DEBUG(id_, " enable={}", - bluetooth::hci::EnableText(subcommand_view.GetApcfEnable())); + DEBUG(id_, " enable={}", bluetooth::hci::EnableText(subcommand_view.GetApcfEnable())); - ErrorCode status = link_layer_controller_.LeApcfEnable( - subcommand_view.GetApcfEnable() == bluetooth::hci::Enable::ENABLED); + ErrorCode status = link_layer_controller_.LeApcfEnable(subcommand_view.GetApcfEnable() == + bluetooth::hci::Enable::ENABLED); send_event_(bluetooth::hci::LeApcfEnableCompleteBuilder::Create( - kNumCommandPackets, status, subcommand_view.GetApcfEnable())); + kNumCommandPackets, status, subcommand_view.GetApcfEnable())); break; } case bluetooth::hci::ApcfOpcode::SET_FILTERING_PARAMETERS: { - auto subcommand_view = - bluetooth::hci::LeApcfSetFilteringParametersView::Create( - command_view); + auto subcommand_view = bluetooth::hci::LeApcfSetFilteringParametersView::Create(command_view); CHECK_PACKET_VIEW(subcommand_view); DEBUG(id_, "<< LE APCF Set Filtering Parameters"); - DEBUG(id_, " action={}", - bluetooth::hci::ApcfActionText(subcommand_view.GetApcfAction())); + DEBUG(id_, " action={}", bluetooth::hci::ApcfActionText(subcommand_view.GetApcfAction())); ErrorCode status = ErrorCode::INVALID_HCI_COMMAND_PARAMETERS; uint8_t apcf_available_spaces = 0; @@ -2904,40 +2601,32 @@ void DualModeController::LeApcf(CommandView command) { switch (subcommand_view.GetApcfAction()) { case bluetooth::hci::ApcfAction::ADD: { auto subsubcommand_view = - bluetooth::hci::LeApcfAddFilteringParametersView::Create( - subcommand_view); + bluetooth::hci::LeApcfAddFilteringParametersView::Create(subcommand_view); CHECK_PACKET_VIEW(subcommand_view); status = link_layer_controller_.LeApcfAddFilteringParameters( - subsubcommand_view.GetApcfFilterIndex(), - subsubcommand_view.GetApcfFeatureSelection(), - subsubcommand_view.GetApcfListLogicType(), - subsubcommand_view.GetApcfFilterLogicType(), - subsubcommand_view.GetRssiHighThresh(), - subsubcommand_view.GetDeliveryMode(), - subsubcommand_view.GetOnfoundTimeout(), - subsubcommand_view.GetOnfoundTimeoutCnt(), - subsubcommand_view.GetRssiLowThresh(), - subsubcommand_view.GetOnlostTimeout(), - subsubcommand_view.GetNumOfTrackingEntries(), - &apcf_available_spaces); + subsubcommand_view.GetApcfFilterIndex(), + subsubcommand_view.GetApcfFeatureSelection(), + subsubcommand_view.GetApcfListLogicType(), + subsubcommand_view.GetApcfFilterLogicType(), + subsubcommand_view.GetRssiHighThresh(), subsubcommand_view.GetDeliveryMode(), + subsubcommand_view.GetOnfoundTimeout(), subsubcommand_view.GetOnfoundTimeoutCnt(), + subsubcommand_view.GetRssiLowThresh(), subsubcommand_view.GetOnlostTimeout(), + subsubcommand_view.GetNumOfTrackingEntries(), &apcf_available_spaces); break; } case bluetooth::hci::ApcfAction::DELETE: { auto subsubcommand_view = - bluetooth::hci::LeApcfDeleteFilteringParametersView::Create( - subcommand_view); + bluetooth::hci::LeApcfDeleteFilteringParametersView::Create(subcommand_view); CHECK_PACKET_VIEW(subcommand_view); status = link_layer_controller_.LeApcfDeleteFilteringParameters( - subsubcommand_view.GetApcfFilterIndex(), &apcf_available_spaces); + subsubcommand_view.GetApcfFilterIndex(), &apcf_available_spaces); break; } case bluetooth::hci::ApcfAction::CLEAR: { auto subsubcommand_view = - bluetooth::hci::LeApcfClearFilteringParametersView::Create( - subcommand_view); + bluetooth::hci::LeApcfClearFilteringParametersView::Create(subcommand_view); CHECK_PACKET_VIEW(subcommand_view); - status = link_layer_controller_.LeApcfClearFilteringParameters( - &apcf_available_spaces); + status = link_layer_controller_.LeApcfClearFilteringParameters(&apcf_available_spaces); break; } default: @@ -2946,20 +2635,16 @@ void DualModeController::LeApcf(CommandView command) { break; } - send_event_( - bluetooth::hci::LeApcfSetFilteringParametersCompleteBuilder::Create( - kNumCommandPackets, status, subcommand_view.GetApcfAction(), - apcf_available_spaces)); + send_event_(bluetooth::hci::LeApcfSetFilteringParametersCompleteBuilder::Create( + kNumCommandPackets, status, subcommand_view.GetApcfAction(), apcf_available_spaces)); break; } case bluetooth::hci::ApcfOpcode::BROADCASTER_ADDRESS: { - auto subcommand_view = - bluetooth::hci::LeApcfBroadcasterAddressView::Create(command_view); + auto subcommand_view = bluetooth::hci::LeApcfBroadcasterAddressView::Create(command_view); CHECK_PACKET_VIEW(subcommand_view); DEBUG(id_, "<< LE APCF Broadcaster Address"); - DEBUG(id_, " action={}", - bluetooth::hci::ApcfActionText(subcommand_view.GetApcfAction())); + DEBUG(id_, " action={}", bluetooth::hci::ApcfActionText(subcommand_view.GetApcfAction())); ErrorCode status = ErrorCode::INVALID_HCI_COMMAND_PARAMETERS; uint8_t apcf_available_spaces = 0; @@ -2967,40 +2652,32 @@ void DualModeController::LeApcf(CommandView command) { switch (subcommand_view.GetApcfAction()) { case bluetooth::hci::ApcfAction::ADD: { auto subsubcommand_view = - bluetooth::hci::LeApcfAddBroadcasterAddressView::Create( - subcommand_view); + bluetooth::hci::LeApcfAddBroadcasterAddressView::Create(subcommand_view); CHECK_PACKET_VIEW(subcommand_view); status = link_layer_controller_.LeApcfBroadcasterAddress( - bluetooth::hci::ApcfAction::ADD, - subsubcommand_view.GetApcfFilterIndex(), - subsubcommand_view.GetApcfBroadcasterAddress(), - subsubcommand_view.GetApcfApplicationAddressType(), - &apcf_available_spaces); + bluetooth::hci::ApcfAction::ADD, subsubcommand_view.GetApcfFilterIndex(), + subsubcommand_view.GetApcfBroadcasterAddress(), + subsubcommand_view.GetApcfApplicationAddressType(), &apcf_available_spaces); break; } case bluetooth::hci::ApcfAction::DELETE: { auto subsubcommand_view = - bluetooth::hci::LeApcfDeleteBroadcasterAddressView::Create( - subcommand_view); + bluetooth::hci::LeApcfDeleteBroadcasterAddressView::Create(subcommand_view); CHECK_PACKET_VIEW(subcommand_view); status = link_layer_controller_.LeApcfBroadcasterAddress( - bluetooth::hci::ApcfAction::DELETE, - subsubcommand_view.GetApcfFilterIndex(), - subsubcommand_view.GetApcfBroadcasterAddress(), - subsubcommand_view.GetApcfApplicationAddressType(), - &apcf_available_spaces); + bluetooth::hci::ApcfAction::DELETE, subsubcommand_view.GetApcfFilterIndex(), + subsubcommand_view.GetApcfBroadcasterAddress(), + subsubcommand_view.GetApcfApplicationAddressType(), &apcf_available_spaces); break; } case bluetooth::hci::ApcfAction::CLEAR: { auto subsubcommand_view = - bluetooth::hci::LeApcfClearBroadcasterAddressView::Create( - subcommand_view); + bluetooth::hci::LeApcfClearBroadcasterAddressView::Create(subcommand_view); CHECK_PACKET_VIEW(subcommand_view); status = link_layer_controller_.LeApcfBroadcasterAddress( - bluetooth::hci::ApcfAction::CLEAR, - subsubcommand_view.GetApcfFilterIndex(), Address(), - bluetooth::hci::ApcfApplicationAddressType::NOT_APPLICABLE, - &apcf_available_spaces); + bluetooth::hci::ApcfAction::CLEAR, subsubcommand_view.GetApcfFilterIndex(), + Address(), bluetooth::hci::ApcfApplicationAddressType::NOT_APPLICABLE, + &apcf_available_spaces); break; } default: @@ -3009,192 +2686,160 @@ void DualModeController::LeApcf(CommandView command) { break; } - send_event_( - bluetooth::hci::LeApcfBroadcasterAddressCompleteBuilder::Create( - kNumCommandPackets, status, subcommand_view.GetApcfAction(), - apcf_available_spaces)); + send_event_(bluetooth::hci::LeApcfBroadcasterAddressCompleteBuilder::Create( + kNumCommandPackets, status, subcommand_view.GetApcfAction(), apcf_available_spaces)); break; } case bluetooth::hci::ApcfOpcode::SERVICE_UUID: { - auto subcommand_view = - bluetooth::hci::LeApcfServiceUuidView::Create(command_view); + auto subcommand_view = bluetooth::hci::LeApcfServiceUuidView::Create(command_view); CHECK_PACKET_VIEW(subcommand_view); DEBUG(id_, "<< LE APCF Service UUID"); - DEBUG(id_, " action={}", - bluetooth::hci::ApcfActionText(subcommand_view.GetApcfAction())); + DEBUG(id_, " action={}", bluetooth::hci::ApcfActionText(subcommand_view.GetApcfAction())); uint8_t apcf_available_spaces = 0; ErrorCode status = link_layer_controller_.LeApcfServiceUuid( - subcommand_view.GetApcfAction(), subcommand_view.GetApcfFilterIndex(), - subcommand_view.GetAcpfUuidData(), &apcf_available_spaces); + subcommand_view.GetApcfAction(), subcommand_view.GetApcfFilterIndex(), + subcommand_view.GetAcpfUuidData(), &apcf_available_spaces); send_event_(bluetooth::hci::LeApcfServiceUuidCompleteBuilder::Create( - kNumCommandPackets, status, subcommand_view.GetApcfAction(), - apcf_available_spaces)); + kNumCommandPackets, status, subcommand_view.GetApcfAction(), apcf_available_spaces)); break; } case bluetooth::hci::ApcfOpcode::SERVICE_SOLICITATION_UUID: { auto subcommand_view = - bluetooth::hci::LeApcfServiceSolicitationUuidView::Create( - command_view); + bluetooth::hci::LeApcfServiceSolicitationUuidView::Create(command_view); CHECK_PACKET_VIEW(subcommand_view); DEBUG(id_, "<< LE APCF Service Solicitation UUID"); - DEBUG(id_, " action={}", - bluetooth::hci::ApcfActionText(subcommand_view.GetApcfAction())); + DEBUG(id_, " action={}", bluetooth::hci::ApcfActionText(subcommand_view.GetApcfAction())); uint8_t apcf_available_spaces = 0; ErrorCode status = link_layer_controller_.LeApcfServiceSolicitationUuid( - subcommand_view.GetApcfAction(), subcommand_view.GetApcfFilterIndex(), - subcommand_view.GetAcpfUuidData(), &apcf_available_spaces); - send_event_( - bluetooth::hci::LeApcfServiceSolicitationUuidCompleteBuilder::Create( - kNumCommandPackets, status, subcommand_view.GetApcfAction(), - apcf_available_spaces)); + subcommand_view.GetApcfAction(), subcommand_view.GetApcfFilterIndex(), + subcommand_view.GetAcpfUuidData(), &apcf_available_spaces); + send_event_(bluetooth::hci::LeApcfServiceSolicitationUuidCompleteBuilder::Create( + kNumCommandPackets, status, subcommand_view.GetApcfAction(), apcf_available_spaces)); break; } case bluetooth::hci::ApcfOpcode::LOCAL_NAME: { - auto subcommand_view = - bluetooth::hci::LeApcfLocalNameView::Create(command_view); + auto subcommand_view = bluetooth::hci::LeApcfLocalNameView::Create(command_view); CHECK_PACKET_VIEW(subcommand_view); DEBUG(id_, "<< LE APCF Local Name"); - DEBUG(id_, " action={}", - bluetooth::hci::ApcfActionText(subcommand_view.GetApcfAction())); + DEBUG(id_, " action={}", bluetooth::hci::ApcfActionText(subcommand_view.GetApcfAction())); uint8_t apcf_available_spaces = 0; ErrorCode status = link_layer_controller_.LeApcfLocalName( - subcommand_view.GetApcfAction(), subcommand_view.GetApcfFilterIndex(), - subcommand_view.GetApcfLocalName(), &apcf_available_spaces); + subcommand_view.GetApcfAction(), subcommand_view.GetApcfFilterIndex(), + subcommand_view.GetApcfLocalName(), &apcf_available_spaces); send_event_(bluetooth::hci::LeApcfLocalNameCompleteBuilder::Create( - kNumCommandPackets, status, subcommand_view.GetApcfAction(), - apcf_available_spaces)); + kNumCommandPackets, status, subcommand_view.GetApcfAction(), apcf_available_spaces)); break; } case bluetooth::hci::ApcfOpcode::MANUFACTURER_DATA: { - auto subcommand_view = - bluetooth::hci::LeApcfManufacturerDataView::Create(command_view); + auto subcommand_view = bluetooth::hci::LeApcfManufacturerDataView::Create(command_view); CHECK_PACKET_VIEW(subcommand_view); DEBUG(id_, "<< LE APCF Manufacturer Data"); - DEBUG(id_, " action={}", - bluetooth::hci::ApcfActionText(subcommand_view.GetApcfAction())); + DEBUG(id_, " action={}", bluetooth::hci::ApcfActionText(subcommand_view.GetApcfAction())); uint8_t apcf_available_spaces = 0; ErrorCode status = link_layer_controller_.LeApcfManufacturerData( - subcommand_view.GetApcfAction(), subcommand_view.GetApcfFilterIndex(), - subcommand_view.GetApcfManufacturerData(), &apcf_available_spaces); + subcommand_view.GetApcfAction(), subcommand_view.GetApcfFilterIndex(), + subcommand_view.GetApcfManufacturerData(), &apcf_available_spaces); send_event_(bluetooth::hci::LeApcfManufacturerDataCompleteBuilder::Create( - kNumCommandPackets, status, subcommand_view.GetApcfAction(), - apcf_available_spaces)); + kNumCommandPackets, status, subcommand_view.GetApcfAction(), apcf_available_spaces)); break; } case bluetooth::hci::ApcfOpcode::SERVICE_DATA: { - auto subcommand_view = - bluetooth::hci::LeApcfServiceDataView::Create(command_view); + auto subcommand_view = bluetooth::hci::LeApcfServiceDataView::Create(command_view); CHECK_PACKET_VIEW(subcommand_view); DEBUG(id_, "<< LE APCF Service Data"); - DEBUG(id_, " action={}", - bluetooth::hci::ApcfActionText(subcommand_view.GetApcfAction())); + DEBUG(id_, " action={}", bluetooth::hci::ApcfActionText(subcommand_view.GetApcfAction())); uint8_t apcf_available_spaces = 0; ErrorCode status = link_layer_controller_.LeApcfServiceData( - subcommand_view.GetApcfAction(), subcommand_view.GetApcfFilterIndex(), - subcommand_view.GetApcfServiceData(), &apcf_available_spaces); + subcommand_view.GetApcfAction(), subcommand_view.GetApcfFilterIndex(), + subcommand_view.GetApcfServiceData(), &apcf_available_spaces); send_event_(bluetooth::hci::LeApcfServiceDataCompleteBuilder::Create( - kNumCommandPackets, status, subcommand_view.GetApcfAction(), - apcf_available_spaces)); + kNumCommandPackets, status, subcommand_view.GetApcfAction(), apcf_available_spaces)); break; } case bluetooth::hci::ApcfOpcode::TRANSPORT_DISCOVERY_SERVICE: { auto subcommand_view = - bluetooth::hci::LeApcfTransportDiscoveryServiceView::Create(command_view); + bluetooth::hci::LeApcfTransportDiscoveryServiceView::Create(command_view); CHECK_PACKET_VIEW(subcommand_view); DEBUG(id_, "<< LE APCF Transport Discovery Service"); - DEBUG(id_, " action={}", - bluetooth::hci::ApcfActionText(subcommand_view.GetApcfAction())); + DEBUG(id_, " action={}", bluetooth::hci::ApcfActionText(subcommand_view.GetApcfAction())); send_event_(bluetooth::hci::LeApcfTransportDiscoveryServiceCompleteBuilder::Create( - kNumCommandPackets, ErrorCode::INVALID_HCI_COMMAND_PARAMETERS, - subcommand_view.GetApcfAction(), 0)); + kNumCommandPackets, ErrorCode::INVALID_HCI_COMMAND_PARAMETERS, + subcommand_view.GetApcfAction(), 0)); break; } case bluetooth::hci::ApcfOpcode::AD_TYPE_FILTER: { - auto subcommand_view = - bluetooth::hci::LeApcfAdTypeFilterView::Create(command_view); + auto subcommand_view = bluetooth::hci::LeApcfAdTypeFilterView::Create(command_view); CHECK_PACKET_VIEW(subcommand_view); DEBUG(id_, "<< LE APCF AD Type Filter"); - DEBUG(id_, " action={}", - bluetooth::hci::ApcfActionText(subcommand_view.GetApcfAction())); + DEBUG(id_, " action={}", bluetooth::hci::ApcfActionText(subcommand_view.GetApcfAction())); uint8_t apcf_available_spaces = 0; ErrorCode status = link_layer_controller_.LeApcfAdTypeFilter( - subcommand_view.GetApcfAction(), subcommand_view.GetApcfFilterIndex(), - subcommand_view.GetApcfAdType(), subcommand_view.GetApcfAdData(), - subcommand_view.GetApcfAdDataMask(), &apcf_available_spaces); + subcommand_view.GetApcfAction(), subcommand_view.GetApcfFilterIndex(), + subcommand_view.GetApcfAdType(), subcommand_view.GetApcfAdData(), + subcommand_view.GetApcfAdDataMask(), &apcf_available_spaces); send_event_(bluetooth::hci::LeApcfAdTypeFilterCompleteBuilder::Create( - kNumCommandPackets, status, subcommand_view.GetApcfAction(), - apcf_available_spaces)); + kNumCommandPackets, status, subcommand_view.GetApcfAction(), apcf_available_spaces)); break; } case bluetooth::hci::ApcfOpcode::READ_EXTENDED_FEATURES: { - auto subcommand_view = - bluetooth::hci::LeApcfReadExtendedFeaturesView::Create(command_view); + auto subcommand_view = bluetooth::hci::LeApcfReadExtendedFeaturesView::Create(command_view); CHECK_PACKET_VIEW(subcommand_view); DEBUG(id_, "<< LE APCF Read Extended Features"); - send_event_( - bluetooth::hci::LeApcfReadExtendedFeaturesCompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS, - kLeApcfTransportDiscoveryDataFilterSupported, + send_event_(bluetooth::hci::LeApcfReadExtendedFeaturesCompleteBuilder::Create( + kNumCommandPackets, ErrorCode::SUCCESS, kLeApcfTransportDiscoveryDataFilterSupported, kLeApcfAdTypeFilterSupported)); break; } default: - ERROR(id_, "unknown APCF opcode {:#x}", - static_cast(command_view.GetApcfOpcode())); + ERROR(id_, "unknown APCF opcode {:#x}", static_cast(command_view.GetApcfOpcode())); send_event_(bluetooth::hci::LeApcfCompleteBuilder::Create( - kNumCommandPackets, ErrorCode::INVALID_HCI_COMMAND_PARAMETERS, - command_view.GetApcfOpcode(), std::vector{})); - - invalid_packet_handler_( - id_, InvalidPacketReason::kUnsupported, - fmt::format("unsupported APCF opcode {:#x}", - static_cast(command_view.GetApcfOpcode())), - command_view.bytes().bytes()); + kNumCommandPackets, ErrorCode::INVALID_HCI_COMMAND_PARAMETERS, + command_view.GetApcfOpcode(), std::vector{})); + + invalid_packet_handler_(id_, InvalidPacketReason::kUnsupported, + fmt::format("unsupported APCF opcode {:#x}", + static_cast(command_view.GetApcfOpcode())), + command_view.bytes().bytes()); } } -void DualModeController::LeGetControllerActivityEnergyInfo( - CommandView command) { - auto command_view = - bluetooth::hci::LeGetControllerActivityEnergyInfoView::Create(command); +void DualModeController::LeGetControllerActivityEnergyInfo(CommandView command) { + auto command_view = bluetooth::hci::LeGetControllerActivityEnergyInfoView::Create(command); CHECK_PACKET_VIEW(command_view); - SendCommandCompleteUnknownOpCodeEvent( - OpCode::LE_GET_CONTROLLER_ACTIVITY_ENERGY_INFO); + SendCommandCompleteUnknownOpCodeEvent(OpCode::LE_GET_CONTROLLER_ACTIVITY_ENERGY_INFO); } void DualModeController::LeExSetScanParameters(CommandView command) { - auto command_view = - bluetooth::hci::LeExSetScanParametersView::Create(command); + auto command_view = bluetooth::hci::LeExSetScanParametersView::Create(command); CHECK_PACKET_VIEW(command_view); SendCommandCompleteUnknownOpCodeEvent(OpCode::LE_EX_SET_SCAN_PARAMETERS); } void DualModeController::GetControllerDebugInfo(CommandView command) { - auto command_view = - bluetooth::hci::GetControllerDebugInfoView::Create(command); + auto command_view = bluetooth::hci::GetControllerDebugInfoView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< Get Controller Debug Info"); - send_event_(bluetooth::hci::GetControllerDebugInfoCompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS)); + send_event_(bluetooth::hci::GetControllerDebugInfoCompleteBuilder::Create(kNumCommandPackets, + ErrorCode::SUCCESS)); } // CSR vendor command. @@ -3247,10 +2892,9 @@ void DualModeController::CsrVendorCommand(CommandView command) { varid = (uint16_t)parameters[7] | ((uint16_t)parameters[8] << 8); length = 2 * (length - 5); - if (parameters.size() < (11 + length) || - (varid == CsrVarid::CSR_VARID_PS && length < 6)) { - INFO(id_, "Invalid CSR vendor command parameter length {}, expected {}", - parameters.size(), 11 + length); + if (parameters.size() < (11 + length) || (varid == CsrVarid::CSR_VARID_PS && length < 6)) { + INFO(id_, "Invalid CSR vendor command parameter length {}, expected {}", parameters.size(), + 11 + length); goto complete; } @@ -3258,21 +2902,18 @@ void DualModeController::CsrVendorCommand(CommandView command) { // Subcommand to read or write PSKEY of the selected identifier // instead of VARID. uint16_t pskey = (uint16_t)parameters[11] | ((uint16_t)parameters[12] << 8); - uint16_t length = - (uint16_t)parameters[13] | ((uint16_t)parameters[14] << 8); + uint16_t length = (uint16_t)parameters[13] | ((uint16_t)parameters[14] << 8); length = 2 * length; if (parameters.size() < (17 + length)) { - INFO(id_, "Invalid CSR vendor command parameter length {}, expected {}", - parameters.size(), 17 + length); + INFO(id_, "Invalid CSR vendor command parameter length {}, expected {}", parameters.size(), + 17 + length); goto complete; } - std::vector value(parameters.begin() + 17, - parameters.begin() + 17 + length); + std::vector value(parameters.begin() + 17, parameters.begin() + 17 + length); - INFO(id_, "CSR vendor command type={:04x} length={:04x} pskey={:04x}", type, - length, pskey); + INFO(id_, "CSR vendor command type={:04x} length={:04x} pskey={:04x}", type, length, pskey); if (type == 0) { CsrReadPskey(static_cast(pskey), value); @@ -3283,11 +2924,9 @@ void DualModeController::CsrVendorCommand(CommandView command) { } else { // Subcommand to read or write VARID of the selected identifier. - std::vector value(parameters.begin() + 11, - parameters.begin() + 11 + length); + std::vector value(parameters.begin() + 11, parameters.begin() + 11 + length); - INFO(id_, "CSR vendor command type={:04x} length={:04x} varid={:04x}", type, - length, varid); + INFO(id_, "CSR vendor command type={:04x} length={:04x} varid={:04x}", type, length, varid); if (type == 0) { CsrReadVarid(static_cast(varid), value); @@ -3301,12 +2940,11 @@ complete: // Overwrite the command type. parameters[1] = 0x1; parameters[2] = 0x0; - send_event_(bluetooth::hci::EventBuilder::Create( - bluetooth::hci::EventCode::VENDOR_SPECIFIC, std::move(parameters))); + send_event_(bluetooth::hci::EventBuilder::Create(bluetooth::hci::EventCode::VENDOR_SPECIFIC, + std::move(parameters))); } -void DualModeController::CsrReadVarid(CsrVarid varid, - std::vector& value) const { +void DualModeController::CsrReadVarid(CsrVarid varid, std::vector& value) const { switch (varid) { case CsrVarid::CSR_VARID_BUILDID: // Return the extact Build ID returned by the official PTS dongle. @@ -3316,20 +2954,17 @@ void DualModeController::CsrReadVarid(CsrVarid varid, break; default: - INFO(id_, "Unsupported read of CSR varid 0x{:04x}", - static_cast(varid)); + INFO(id_, "Unsupported read of CSR varid 0x{:04x}", static_cast(varid)); break; } } -void DualModeController::CsrWriteVarid( - CsrVarid varid, std::vector const& /*value*/) const { - INFO(id_, "Unsupported write of CSR varid 0x{:04x}", - static_cast(varid)); +void DualModeController::CsrWriteVarid(CsrVarid varid, + std::vector const& /*value*/) const { + INFO(id_, "Unsupported write of CSR varid 0x{:04x}", static_cast(varid)); } -void DualModeController::CsrReadPskey(CsrPskey pskey, - std::vector& value) const { +void DualModeController::CsrReadPskey(CsrPskey pskey, std::vector& value) const { switch (pskey) { case CsrPskey::CSR_PSKEY_ENC_KEY_LMIN: ASSERT(!value.empty()); @@ -3349,35 +2984,30 @@ void DualModeController::CsrReadPskey(CsrPskey pskey, break; default: - INFO(id_, "Unsupported read of CSR pskey 0x{:04x}", - static_cast(pskey)); + INFO(id_, "Unsupported read of CSR pskey 0x{:04x}", static_cast(pskey)); break; } } -void DualModeController::CsrWritePskey(CsrPskey pskey, - std::vector const& value) { +void DualModeController::CsrWritePskey(CsrPskey pskey, std::vector const& value) { switch (pskey) { case CsrPskey::CSR_PSKEY_LOCAL_SUPPORTED_FEATURES: ASSERT(value.size() >= 8); INFO(id_, "CSR Vendor updating the Local Supported Features"); - properties_.lmp_features[0] = - ((uint64_t)value[0] << 0) | ((uint64_t)value[1] << 8) | - ((uint64_t)value[2] << 16) | ((uint64_t)value[3] << 24) | - ((uint64_t)value[4] << 32) | ((uint64_t)value[5] << 40) | - ((uint64_t)value[6] << 48) | ((uint64_t)value[7] << 56); + properties_.lmp_features[0] = ((uint64_t)value[0] << 0) | ((uint64_t)value[1] << 8) | + ((uint64_t)value[2] << 16) | ((uint64_t)value[3] << 24) | + ((uint64_t)value[4] << 32) | ((uint64_t)value[5] << 40) | + ((uint64_t)value[6] << 48) | ((uint64_t)value[7] << 56); break; default: - INFO(id_, "Unsupported write of CSR pskey 0x{:04x}", - static_cast(pskey)); + INFO(id_, "Unsupported write of CSR pskey 0x{:04x}", static_cast(pskey)); break; } } void DualModeController::LeSetAdvertisingSetRandomAddress(CommandView command) { - auto command_view = - bluetooth::hci::LeSetAdvertisingSetRandomAddressView::Create(command); + auto command_view = bluetooth::hci::LeSetAdvertisingSetRandomAddressView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< LE Set Advertising Set Random Address"); @@ -3385,147 +3015,120 @@ void DualModeController::LeSetAdvertisingSetRandomAddress(CommandView command) { DEBUG(id_, " random_address={}", command_view.GetRandomAddress()); ErrorCode status = link_layer_controller_.LeSetAdvertisingSetRandomAddress( - command_view.GetAdvertisingHandle(), command_view.GetRandomAddress()); - send_event_( - bluetooth::hci::LeSetAdvertisingSetRandomAddressCompleteBuilder::Create( + command_view.GetAdvertisingHandle(), command_view.GetRandomAddress()); + send_event_(bluetooth::hci::LeSetAdvertisingSetRandomAddressCompleteBuilder::Create( kNumCommandPackets, status)); } -void DualModeController::LeSetExtendedAdvertisingParameters( - CommandView command) { - auto command_view = - bluetooth::hci::LeSetExtendedAdvertisingParametersView::Create(command); +void DualModeController::LeSetExtendedAdvertisingParameters(CommandView command) { + auto command_view = bluetooth::hci::LeSetExtendedAdvertisingParametersView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< LE Set Extended Advertising Parameters"); DEBUG(id_, " advertising_handle={}", command_view.GetAdvertisingHandle()); ErrorCode status = link_layer_controller_.LeSetExtendedAdvertisingParameters( - command_view.GetAdvertisingHandle(), - command_view.GetAdvertisingEventProperties(), - command_view.GetPrimaryAdvertisingIntervalMin(), - command_view.GetPrimaryAdvertisingIntervalMax(), - command_view.GetPrimaryAdvertisingChannelMap(), - command_view.GetOwnAddressType(), command_view.GetPeerAddressType(), - command_view.GetPeerAddress(), command_view.GetAdvertisingFilterPolicy(), - command_view.GetAdvertisingTxPower(), - command_view.GetPrimaryAdvertisingPhy(), - command_view.GetSecondaryAdvertisingMaxSkip(), - command_view.GetSecondaryAdvertisingPhy(), - command_view.GetAdvertisingSid(), - command_view.GetScanRequestNotificationEnable() == Enable::ENABLED); + command_view.GetAdvertisingHandle(), command_view.GetAdvertisingEventProperties(), + command_view.GetPrimaryAdvertisingIntervalMin(), + command_view.GetPrimaryAdvertisingIntervalMax(), + command_view.GetPrimaryAdvertisingChannelMap(), command_view.GetOwnAddressType(), + command_view.GetPeerAddressType(), command_view.GetPeerAddress(), + command_view.GetAdvertisingFilterPolicy(), command_view.GetAdvertisingTxPower(), + command_view.GetPrimaryAdvertisingPhy(), command_view.GetSecondaryAdvertisingMaxSkip(), + command_view.GetSecondaryAdvertisingPhy(), command_view.GetAdvertisingSid(), + command_view.GetScanRequestNotificationEnable() == Enable::ENABLED); // The selected TX power is always the requested TX power // at the moment. - send_event_( - bluetooth::hci::LeSetExtendedAdvertisingParametersCompleteBuilder::Create( + send_event_(bluetooth::hci::LeSetExtendedAdvertisingParametersCompleteBuilder::Create( kNumCommandPackets, status, command_view.GetAdvertisingTxPower())); } void DualModeController::LeSetExtendedAdvertisingData(CommandView command) { - auto command_view = - bluetooth::hci::LeSetExtendedAdvertisingDataView::Create(command); + auto command_view = bluetooth::hci::LeSetExtendedAdvertisingDataView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< LE Set Extended Advertising Data"); DEBUG(id_, " advertising_handle={}", command_view.GetAdvertisingHandle()); ErrorCode status = link_layer_controller_.LeSetExtendedAdvertisingData( - command_view.GetAdvertisingHandle(), command_view.GetOperation(), - command_view.GetFragmentPreference(), command_view.GetAdvertisingData()); - send_event_( - bluetooth::hci::LeSetExtendedAdvertisingDataCompleteBuilder::Create( + command_view.GetAdvertisingHandle(), command_view.GetOperation(), + command_view.GetFragmentPreference(), command_view.GetAdvertisingData()); + send_event_(bluetooth::hci::LeSetExtendedAdvertisingDataCompleteBuilder::Create( kNumCommandPackets, status)); } void DualModeController::LeSetExtendedScanResponseData(CommandView command) { - auto command_view = - bluetooth::hci::LeSetExtendedScanResponseDataView::Create(command); + auto command_view = bluetooth::hci::LeSetExtendedScanResponseDataView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< LE Set Extended Scan Response Data"); DEBUG(id_, " advertising_handle={}", command_view.GetAdvertisingHandle()); ErrorCode status = link_layer_controller_.LeSetExtendedScanResponseData( - command_view.GetAdvertisingHandle(), command_view.GetOperation(), - command_view.GetFragmentPreference(), command_view.GetScanResponseData()); - send_event_( - bluetooth::hci::LeSetExtendedScanResponseDataCompleteBuilder::Create( + command_view.GetAdvertisingHandle(), command_view.GetOperation(), + command_view.GetFragmentPreference(), command_view.GetScanResponseData()); + send_event_(bluetooth::hci::LeSetExtendedScanResponseDataCompleteBuilder::Create( kNumCommandPackets, status)); } void DualModeController::LeSetExtendedAdvertisingEnable(CommandView command) { - auto command_view = - bluetooth::hci::LeSetExtendedAdvertisingEnableView::Create(command); + auto command_view = bluetooth::hci::LeSetExtendedAdvertisingEnableView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< LE Set Extended Advertising Enable"); - DEBUG(id_, " enable={}", - command_view.GetEnable() == bluetooth::hci::Enable::ENABLED); + DEBUG(id_, " enable={}", command_view.GetEnable() == bluetooth::hci::Enable::ENABLED); for (auto const& set : command_view.GetEnabledSets()) { DEBUG(id_, " advertising_handle={}", set.advertising_handle_); } ErrorCode status = link_layer_controller_.LeSetExtendedAdvertisingEnable( - command_view.GetEnable() == bluetooth::hci::Enable::ENABLED, - command_view.GetEnabledSets()); - send_event_( - bluetooth::hci::LeSetExtendedAdvertisingEnableCompleteBuilder::Create( + command_view.GetEnable() == bluetooth::hci::Enable::ENABLED, + command_view.GetEnabledSets()); + send_event_(bluetooth::hci::LeSetExtendedAdvertisingEnableCompleteBuilder::Create( kNumCommandPackets, status)); } -void DualModeController::LeReadMaximumAdvertisingDataLength( - CommandView command) { - auto command_view = - bluetooth::hci::LeReadMaximumAdvertisingDataLengthView::Create(command); +void DualModeController::LeReadMaximumAdvertisingDataLength(CommandView command) { + auto command_view = bluetooth::hci::LeReadMaximumAdvertisingDataLengthView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< LE Read Maximum Advertising Data Length"); - send_event_( - bluetooth::hci::LeReadMaximumAdvertisingDataLengthCompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS, - properties_.le_max_advertising_data_length)); + send_event_(bluetooth::hci::LeReadMaximumAdvertisingDataLengthCompleteBuilder::Create( + kNumCommandPackets, ErrorCode::SUCCESS, properties_.le_max_advertising_data_length)); } -void DualModeController::LeReadNumberOfSupportedAdvertisingSets( - CommandView command) { - auto command_view = - bluetooth::hci::LeReadNumberOfSupportedAdvertisingSetsView::Create( - command); +void DualModeController::LeReadNumberOfSupportedAdvertisingSets(CommandView command) { + auto command_view = bluetooth::hci::LeReadNumberOfSupportedAdvertisingSetsView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< LE Read Number of Supported Advertising Sets"); - send_event_( - bluetooth::hci::LeReadNumberOfSupportedAdvertisingSetsCompleteBuilder:: - Create(kNumCommandPackets, ErrorCode::SUCCESS, - properties_.le_num_supported_advertising_sets)); + send_event_(bluetooth::hci::LeReadNumberOfSupportedAdvertisingSetsCompleteBuilder::Create( + kNumCommandPackets, ErrorCode::SUCCESS, properties_.le_num_supported_advertising_sets)); } void DualModeController::LeRemoveAdvertisingSet(CommandView command) { - auto command_view = - bluetooth::hci::LeRemoveAdvertisingSetView::Create(command); + auto command_view = bluetooth::hci::LeRemoveAdvertisingSetView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< LE Remove Advertising Set"); DEBUG(id_, " advertising_handle={}", command_view.GetAdvertisingHandle()); - auto status = link_layer_controller_.LeRemoveAdvertisingSet( - command_view.GetAdvertisingHandle()); - send_event_(bluetooth::hci::LeRemoveAdvertisingSetCompleteBuilder::Create( - kNumCommandPackets, status)); + auto status = link_layer_controller_.LeRemoveAdvertisingSet(command_view.GetAdvertisingHandle()); + send_event_(bluetooth::hci::LeRemoveAdvertisingSetCompleteBuilder::Create(kNumCommandPackets, + status)); } void DualModeController::LeClearAdvertisingSets(CommandView command) { - auto command_view = - bluetooth::hci::LeClearAdvertisingSetsView::Create(command); + auto command_view = bluetooth::hci::LeClearAdvertisingSetsView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< LE Clear Advertising Sets"); auto status = link_layer_controller_.LeClearAdvertisingSets(); - send_event_(bluetooth::hci::LeClearAdvertisingSetsCompleteBuilder::Create( - kNumCommandPackets, status)); + send_event_(bluetooth::hci::LeClearAdvertisingSetsCompleteBuilder::Create(kNumCommandPackets, + status)); } void DualModeController::LeStartEncryption(CommandView command) { @@ -3536,72 +3139,61 @@ void DualModeController::LeStartEncryption(CommandView command) { DEBUG(id_, " connection_handle=0x{:x}", command_view.GetConnectionHandle()); ErrorCode status = link_layer_controller_.LeEnableEncryption( - command_view.GetConnectionHandle(), command_view.GetRand(), - command_view.GetEdiv(), command_view.GetLtk()); + command_view.GetConnectionHandle(), command_view.GetRand(), command_view.GetEdiv(), + command_view.GetLtk()); - send_event_(bluetooth::hci::LeStartEncryptionStatusBuilder::Create( - status, kNumCommandPackets)); + send_event_(bluetooth::hci::LeStartEncryptionStatusBuilder::Create(status, kNumCommandPackets)); } void DualModeController::LeLongTermKeyRequestReply(CommandView command) { - auto command_view = - bluetooth::hci::LeLongTermKeyRequestReplyView::Create(command); + auto command_view = bluetooth::hci::LeLongTermKeyRequestReplyView::Create(command); CHECK_PACKET_VIEW(command_view); uint16_t handle = command_view.GetConnectionHandle(); DEBUG(id_, "<< LE Long Term Key Request Reply"); DEBUG(id_, " connection_handle=0x{:x}", handle); - ErrorCode status = link_layer_controller_.LeLongTermKeyRequestReply( - handle, command_view.GetLongTermKey()); + ErrorCode status = + link_layer_controller_.LeLongTermKeyRequestReply(handle, command_view.GetLongTermKey()); - send_event_(bluetooth::hci::LeLongTermKeyRequestReplyCompleteBuilder::Create( - kNumCommandPackets, status, handle)); + send_event_(bluetooth::hci::LeLongTermKeyRequestReplyCompleteBuilder::Create(kNumCommandPackets, + status, handle)); } -void DualModeController::LeLongTermKeyRequestNegativeReply( - CommandView command) { - auto command_view = - bluetooth::hci::LeLongTermKeyRequestNegativeReplyView::Create(command); +void DualModeController::LeLongTermKeyRequestNegativeReply(CommandView command) { + auto command_view = bluetooth::hci::LeLongTermKeyRequestNegativeReplyView::Create(command); CHECK_PACKET_VIEW(command_view); uint16_t handle = command_view.GetConnectionHandle(); DEBUG(id_, "<< LE Long Term Key Request Negative Reply"); DEBUG(id_, " connection_handle=0x{:x}", handle); - ErrorCode status = - link_layer_controller_.LeLongTermKeyRequestNegativeReply(handle); + ErrorCode status = link_layer_controller_.LeLongTermKeyRequestNegativeReply(handle); - send_event_( - bluetooth::hci::LeLongTermKeyRequestNegativeReplyCompleteBuilder::Create( + send_event_(bluetooth::hci::LeLongTermKeyRequestNegativeReplyCompleteBuilder::Create( kNumCommandPackets, status, handle)); } void DualModeController::ReadConnectionAcceptTimeout(CommandView command) { - auto command_view = - bluetooth::hci::ReadConnectionAcceptTimeoutView::Create(command); + auto command_view = bluetooth::hci::ReadConnectionAcceptTimeoutView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< Read Connection Accept Timeout"); - send_event_( - bluetooth::hci::ReadConnectionAcceptTimeoutCompleteBuilder::Create( + send_event_(bluetooth::hci::ReadConnectionAcceptTimeoutCompleteBuilder::Create( kNumCommandPackets, ErrorCode::SUCCESS, link_layer_controller_.GetConnectionAcceptTimeout())); } void DualModeController::WriteConnectionAcceptTimeout(CommandView command) { - auto command_view = - bluetooth::hci::WriteConnectionAcceptTimeoutView::Create(command); + auto command_view = bluetooth::hci::WriteConnectionAcceptTimeoutView::Create(command); CHECK_PACKET_VIEW(command_view); DEBUG(id_, "<< Write Connection Accept Timeout"); - link_layer_controller_.SetConnectionAcceptTimeout( - command_view.GetConnAcceptTimeout()); + link_layer_controller_.SetConnectionAcceptTimeout(command_view.GetConnAcceptTimeout()); - send_event_( - bluetooth::hci::WriteConnectionAcceptTimeoutCompleteBuilder::Create( + send_event_(bluetooth::hci::WriteConnectionAcceptTimeoutCompleteBuilder::Create( kNumCommandPackets, ErrorCode::SUCCESS)); } @@ -3612,7 +3204,7 @@ void DualModeController::ReadLoopbackMode(CommandView command) { DEBUG(id_, "<< Read Loopback Mode"); send_event_(bluetooth::hci::ReadLoopbackModeCompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS, loopback_mode_)); + kNumCommandPackets, ErrorCode::SUCCESS, loopback_mode_)); } void DualModeController::WriteLoopbackMode(CommandView command) { @@ -3627,82 +3219,60 @@ void DualModeController::WriteLoopbackMode(CommandView command) { // ACL channel uint16_t acl_handle = 0x123; send_event_(bluetooth::hci::ConnectionCompleteBuilder::Create( - ErrorCode::SUCCESS, acl_handle, GetAddress(), - bluetooth::hci::LinkType::ACL, bluetooth::hci::Enable::DISABLED)); + ErrorCode::SUCCESS, acl_handle, GetAddress(), bluetooth::hci::LinkType::ACL, + bluetooth::hci::Enable::DISABLED)); // SCO channel uint16_t sco_handle = 0x345; send_event_(bluetooth::hci::ConnectionCompleteBuilder::Create( - ErrorCode::SUCCESS, sco_handle, GetAddress(), - bluetooth::hci::LinkType::SCO, bluetooth::hci::Enable::DISABLED)); - send_event_(bluetooth::hci::WriteLoopbackModeCompleteBuilder::Create( - kNumCommandPackets, ErrorCode::SUCCESS)); + ErrorCode::SUCCESS, sco_handle, GetAddress(), bluetooth::hci::LinkType::SCO, + bluetooth::hci::Enable::DISABLED)); + send_event_(bluetooth::hci::WriteLoopbackModeCompleteBuilder::Create(kNumCommandPackets, + ErrorCode::SUCCESS)); } // Note: the list does not contain all defined opcodes. // Notable exceptions: // - Vendor commands // - Read Local Supported Commands command -const std::unordered_map - DualModeController::hci_command_op_code_to_index_{ +const std::unordered_map DualModeController::hci_command_op_code_to_index_{ // LINK_CONTROL {OpCode::INQUIRY, OpCodeIndex::INQUIRY}, {OpCode::INQUIRY_CANCEL, OpCodeIndex::INQUIRY_CANCEL}, {OpCode::PERIODIC_INQUIRY_MODE, OpCodeIndex::PERIODIC_INQUIRY_MODE}, - {OpCode::EXIT_PERIODIC_INQUIRY_MODE, - OpCodeIndex::EXIT_PERIODIC_INQUIRY_MODE}, + {OpCode::EXIT_PERIODIC_INQUIRY_MODE, OpCodeIndex::EXIT_PERIODIC_INQUIRY_MODE}, {OpCode::CREATE_CONNECTION, OpCodeIndex::CREATE_CONNECTION}, {OpCode::DISCONNECT, OpCodeIndex::DISCONNECT}, {OpCode::ADD_SCO_CONNECTION, OpCodeIndex::ADD_SCO_CONNECTION}, - {OpCode::CREATE_CONNECTION_CANCEL, - OpCodeIndex::CREATE_CONNECTION_CANCEL}, - {OpCode::ACCEPT_CONNECTION_REQUEST, - OpCodeIndex::ACCEPT_CONNECTION_REQUEST}, - {OpCode::REJECT_CONNECTION_REQUEST, - OpCodeIndex::REJECT_CONNECTION_REQUEST}, + {OpCode::CREATE_CONNECTION_CANCEL, OpCodeIndex::CREATE_CONNECTION_CANCEL}, + {OpCode::ACCEPT_CONNECTION_REQUEST, OpCodeIndex::ACCEPT_CONNECTION_REQUEST}, + {OpCode::REJECT_CONNECTION_REQUEST, OpCodeIndex::REJECT_CONNECTION_REQUEST}, {OpCode::LINK_KEY_REQUEST_REPLY, OpCodeIndex::LINK_KEY_REQUEST_REPLY}, - {OpCode::LINK_KEY_REQUEST_NEGATIVE_REPLY, - OpCodeIndex::LINK_KEY_REQUEST_NEGATIVE_REPLY}, + {OpCode::LINK_KEY_REQUEST_NEGATIVE_REPLY, OpCodeIndex::LINK_KEY_REQUEST_NEGATIVE_REPLY}, {OpCode::PIN_CODE_REQUEST_REPLY, OpCodeIndex::PIN_CODE_REQUEST_REPLY}, - {OpCode::PIN_CODE_REQUEST_NEGATIVE_REPLY, - OpCodeIndex::PIN_CODE_REQUEST_NEGATIVE_REPLY}, - {OpCode::CHANGE_CONNECTION_PACKET_TYPE, - OpCodeIndex::CHANGE_CONNECTION_PACKET_TYPE}, - {OpCode::AUTHENTICATION_REQUESTED, - OpCodeIndex::AUTHENTICATION_REQUESTED}, - {OpCode::SET_CONNECTION_ENCRYPTION, - OpCodeIndex::SET_CONNECTION_ENCRYPTION}, - {OpCode::CHANGE_CONNECTION_LINK_KEY, - OpCodeIndex::CHANGE_CONNECTION_LINK_KEY}, + {OpCode::PIN_CODE_REQUEST_NEGATIVE_REPLY, OpCodeIndex::PIN_CODE_REQUEST_NEGATIVE_REPLY}, + {OpCode::CHANGE_CONNECTION_PACKET_TYPE, OpCodeIndex::CHANGE_CONNECTION_PACKET_TYPE}, + {OpCode::AUTHENTICATION_REQUESTED, OpCodeIndex::AUTHENTICATION_REQUESTED}, + {OpCode::SET_CONNECTION_ENCRYPTION, OpCodeIndex::SET_CONNECTION_ENCRYPTION}, + {OpCode::CHANGE_CONNECTION_LINK_KEY, OpCodeIndex::CHANGE_CONNECTION_LINK_KEY}, {OpCode::CENTRAL_LINK_KEY, OpCodeIndex::CENTRAL_LINK_KEY}, {OpCode::REMOTE_NAME_REQUEST, OpCodeIndex::REMOTE_NAME_REQUEST}, - {OpCode::REMOTE_NAME_REQUEST_CANCEL, - OpCodeIndex::REMOTE_NAME_REQUEST_CANCEL}, - {OpCode::READ_REMOTE_SUPPORTED_FEATURES, - OpCodeIndex::READ_REMOTE_SUPPORTED_FEATURES}, - {OpCode::READ_REMOTE_EXTENDED_FEATURES, - OpCodeIndex::READ_REMOTE_EXTENDED_FEATURES}, - {OpCode::READ_REMOTE_VERSION_INFORMATION, - OpCodeIndex::READ_REMOTE_VERSION_INFORMATION}, + {OpCode::REMOTE_NAME_REQUEST_CANCEL, OpCodeIndex::REMOTE_NAME_REQUEST_CANCEL}, + {OpCode::READ_REMOTE_SUPPORTED_FEATURES, OpCodeIndex::READ_REMOTE_SUPPORTED_FEATURES}, + {OpCode::READ_REMOTE_EXTENDED_FEATURES, OpCodeIndex::READ_REMOTE_EXTENDED_FEATURES}, + {OpCode::READ_REMOTE_VERSION_INFORMATION, OpCodeIndex::READ_REMOTE_VERSION_INFORMATION}, {OpCode::READ_CLOCK_OFFSET, OpCodeIndex::READ_CLOCK_OFFSET}, {OpCode::READ_LMP_HANDLE, OpCodeIndex::READ_LMP_HANDLE}, - {OpCode::SETUP_SYNCHRONOUS_CONNECTION, - OpCodeIndex::SETUP_SYNCHRONOUS_CONNECTION}, - {OpCode::ACCEPT_SYNCHRONOUS_CONNECTION, - OpCodeIndex::ACCEPT_SYNCHRONOUS_CONNECTION}, - {OpCode::REJECT_SYNCHRONOUS_CONNECTION, - OpCodeIndex::REJECT_SYNCHRONOUS_CONNECTION}, - {OpCode::IO_CAPABILITY_REQUEST_REPLY, - OpCodeIndex::IO_CAPABILITY_REQUEST_REPLY}, - {OpCode::USER_CONFIRMATION_REQUEST_REPLY, - OpCodeIndex::USER_CONFIRMATION_REQUEST_REPLY}, + {OpCode::SETUP_SYNCHRONOUS_CONNECTION, OpCodeIndex::SETUP_SYNCHRONOUS_CONNECTION}, + {OpCode::ACCEPT_SYNCHRONOUS_CONNECTION, OpCodeIndex::ACCEPT_SYNCHRONOUS_CONNECTION}, + {OpCode::REJECT_SYNCHRONOUS_CONNECTION, OpCodeIndex::REJECT_SYNCHRONOUS_CONNECTION}, + {OpCode::IO_CAPABILITY_REQUEST_REPLY, OpCodeIndex::IO_CAPABILITY_REQUEST_REPLY}, + {OpCode::USER_CONFIRMATION_REQUEST_REPLY, OpCodeIndex::USER_CONFIRMATION_REQUEST_REPLY}, {OpCode::USER_CONFIRMATION_REQUEST_NEGATIVE_REPLY, OpCodeIndex::USER_CONFIRMATION_REQUEST_NEGATIVE_REPLY}, - {OpCode::USER_PASSKEY_REQUEST_REPLY, - OpCodeIndex::USER_PASSKEY_REQUEST_REPLY}, + {OpCode::USER_PASSKEY_REQUEST_REPLY, OpCodeIndex::USER_PASSKEY_REQUEST_REPLY}, {OpCode::USER_PASSKEY_REQUEST_NEGATIVE_REPLY, OpCodeIndex::USER_PASSKEY_REQUEST_NEGATIVE_REPLY}, - {OpCode::REMOTE_OOB_DATA_REQUEST_REPLY, - OpCodeIndex::REMOTE_OOB_DATA_REQUEST_REPLY}, + {OpCode::REMOTE_OOB_DATA_REQUEST_REPLY, OpCodeIndex::REMOTE_OOB_DATA_REQUEST_REPLY}, {OpCode::REMOTE_OOB_DATA_REQUEST_NEGATIVE_REPLY, OpCodeIndex::REMOTE_OOB_DATA_REQUEST_NEGATIVE_REPLY}, {OpCode::IO_CAPABILITY_REQUEST_NEGATIVE_REPLY, @@ -3717,10 +3287,8 @@ const std::unordered_map OpCodeIndex::SET_CONNECTIONLESS_PERIPHERAL_BROADCAST}, {OpCode::SET_CONNECTIONLESS_PERIPHERAL_BROADCAST_RECEIVE, OpCodeIndex::SET_CONNECTIONLESS_PERIPHERAL_BROADCAST_RECEIVE}, - {OpCode::START_SYNCHRONIZATION_TRAIN, - OpCodeIndex::START_SYNCHRONIZATION_TRAIN}, - {OpCode::RECEIVE_SYNCHRONIZATION_TRAIN, - OpCodeIndex::RECEIVE_SYNCHRONIZATION_TRAIN}, + {OpCode::START_SYNCHRONIZATION_TRAIN, OpCodeIndex::START_SYNCHRONIZATION_TRAIN}, + {OpCode::RECEIVE_SYNCHRONIZATION_TRAIN, OpCodeIndex::RECEIVE_SYNCHRONIZATION_TRAIN}, {OpCode::REMOTE_OOB_EXTENDED_DATA_REQUEST_REPLY, OpCodeIndex::REMOTE_OOB_EXTENDED_DATA_REQUEST_REPLY}, @@ -3731,12 +3299,9 @@ const std::unordered_map {OpCode::QOS_SETUP, OpCodeIndex::QOS_SETUP}, {OpCode::ROLE_DISCOVERY, OpCodeIndex::ROLE_DISCOVERY}, {OpCode::SWITCH_ROLE, OpCodeIndex::SWITCH_ROLE}, - {OpCode::READ_LINK_POLICY_SETTINGS, - OpCodeIndex::READ_LINK_POLICY_SETTINGS}, - {OpCode::WRITE_LINK_POLICY_SETTINGS, - OpCodeIndex::WRITE_LINK_POLICY_SETTINGS}, - {OpCode::READ_DEFAULT_LINK_POLICY_SETTINGS, - OpCodeIndex::READ_DEFAULT_LINK_POLICY_SETTINGS}, + {OpCode::READ_LINK_POLICY_SETTINGS, OpCodeIndex::READ_LINK_POLICY_SETTINGS}, + {OpCode::WRITE_LINK_POLICY_SETTINGS, OpCodeIndex::WRITE_LINK_POLICY_SETTINGS}, + {OpCode::READ_DEFAULT_LINK_POLICY_SETTINGS, OpCodeIndex::READ_DEFAULT_LINK_POLICY_SETTINGS}, {OpCode::WRITE_DEFAULT_LINK_POLICY_SETTINGS, OpCodeIndex::WRITE_DEFAULT_LINK_POLICY_SETTINGS}, {OpCode::FLOW_SPECIFICATION, OpCodeIndex::FLOW_SPECIFICATION}, @@ -3754,42 +3319,29 @@ const std::unordered_map {OpCode::DELETE_STORED_LINK_KEY, OpCodeIndex::DELETE_STORED_LINK_KEY}, {OpCode::WRITE_LOCAL_NAME, OpCodeIndex::WRITE_LOCAL_NAME}, {OpCode::READ_LOCAL_NAME, OpCodeIndex::READ_LOCAL_NAME}, - {OpCode::READ_CONNECTION_ACCEPT_TIMEOUT, - OpCodeIndex::READ_CONNECTION_ACCEPT_TIMEOUT}, - {OpCode::WRITE_CONNECTION_ACCEPT_TIMEOUT, - OpCodeIndex::WRITE_CONNECTION_ACCEPT_TIMEOUT}, + {OpCode::READ_CONNECTION_ACCEPT_TIMEOUT, OpCodeIndex::READ_CONNECTION_ACCEPT_TIMEOUT}, + {OpCode::WRITE_CONNECTION_ACCEPT_TIMEOUT, OpCodeIndex::WRITE_CONNECTION_ACCEPT_TIMEOUT}, {OpCode::READ_PAGE_TIMEOUT, OpCodeIndex::READ_PAGE_TIMEOUT}, {OpCode::WRITE_PAGE_TIMEOUT, OpCodeIndex::WRITE_PAGE_TIMEOUT}, {OpCode::READ_SCAN_ENABLE, OpCodeIndex::READ_SCAN_ENABLE}, {OpCode::WRITE_SCAN_ENABLE, OpCodeIndex::WRITE_SCAN_ENABLE}, {OpCode::READ_PAGE_SCAN_ACTIVITY, OpCodeIndex::READ_PAGE_SCAN_ACTIVITY}, - {OpCode::WRITE_PAGE_SCAN_ACTIVITY, - OpCodeIndex::WRITE_PAGE_SCAN_ACTIVITY}, - {OpCode::READ_INQUIRY_SCAN_ACTIVITY, - OpCodeIndex::READ_INQUIRY_SCAN_ACTIVITY}, - {OpCode::WRITE_INQUIRY_SCAN_ACTIVITY, - OpCodeIndex::WRITE_INQUIRY_SCAN_ACTIVITY}, - {OpCode::READ_AUTHENTICATION_ENABLE, - OpCodeIndex::READ_AUTHENTICATION_ENABLE}, - {OpCode::WRITE_AUTHENTICATION_ENABLE, - OpCodeIndex::WRITE_AUTHENTICATION_ENABLE}, + {OpCode::WRITE_PAGE_SCAN_ACTIVITY, OpCodeIndex::WRITE_PAGE_SCAN_ACTIVITY}, + {OpCode::READ_INQUIRY_SCAN_ACTIVITY, OpCodeIndex::READ_INQUIRY_SCAN_ACTIVITY}, + {OpCode::WRITE_INQUIRY_SCAN_ACTIVITY, OpCodeIndex::WRITE_INQUIRY_SCAN_ACTIVITY}, + {OpCode::READ_AUTHENTICATION_ENABLE, OpCodeIndex::READ_AUTHENTICATION_ENABLE}, + {OpCode::WRITE_AUTHENTICATION_ENABLE, OpCodeIndex::WRITE_AUTHENTICATION_ENABLE}, {OpCode::READ_CLASS_OF_DEVICE, OpCodeIndex::READ_CLASS_OF_DEVICE}, {OpCode::WRITE_CLASS_OF_DEVICE, OpCodeIndex::WRITE_CLASS_OF_DEVICE}, {OpCode::READ_VOICE_SETTING, OpCodeIndex::READ_VOICE_SETTING}, {OpCode::WRITE_VOICE_SETTING, OpCodeIndex::WRITE_VOICE_SETTING}, - {OpCode::READ_AUTOMATIC_FLUSH_TIMEOUT, - OpCodeIndex::READ_AUTOMATIC_FLUSH_TIMEOUT}, - {OpCode::WRITE_AUTOMATIC_FLUSH_TIMEOUT, - OpCodeIndex::WRITE_AUTOMATIC_FLUSH_TIMEOUT}, - {OpCode::READ_NUM_BROADCAST_RETRANSMITS, - OpCodeIndex::READ_NUM_BROADCAST_RETRANSMITS}, - {OpCode::WRITE_NUM_BROADCAST_RETRANSMITS, - OpCodeIndex::WRITE_NUM_BROADCAST_RETRANSMITS}, + {OpCode::READ_AUTOMATIC_FLUSH_TIMEOUT, OpCodeIndex::READ_AUTOMATIC_FLUSH_TIMEOUT}, + {OpCode::WRITE_AUTOMATIC_FLUSH_TIMEOUT, OpCodeIndex::WRITE_AUTOMATIC_FLUSH_TIMEOUT}, + {OpCode::READ_NUM_BROADCAST_RETRANSMITS, OpCodeIndex::READ_NUM_BROADCAST_RETRANSMITS}, + {OpCode::WRITE_NUM_BROADCAST_RETRANSMITS, OpCodeIndex::WRITE_NUM_BROADCAST_RETRANSMITS}, {OpCode::READ_HOLD_MODE_ACTIVITY, OpCodeIndex::READ_HOLD_MODE_ACTIVITY}, - {OpCode::WRITE_HOLD_MODE_ACTIVITY, - OpCodeIndex::WRITE_HOLD_MODE_ACTIVITY}, - {OpCode::READ_TRANSMIT_POWER_LEVEL, - OpCodeIndex::READ_TRANSMIT_POWER_LEVEL}, + {OpCode::WRITE_HOLD_MODE_ACTIVITY, OpCodeIndex::WRITE_HOLD_MODE_ACTIVITY}, + {OpCode::READ_TRANSMIT_POWER_LEVEL, OpCodeIndex::READ_TRANSMIT_POWER_LEVEL}, {OpCode::READ_SYNCHRONOUS_FLOW_CONTROL_ENABLE, OpCodeIndex::READ_SYNCHRONOUS_FLOW_CONTROL_ENABLE}, {OpCode::WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE, @@ -3797,14 +3349,10 @@ const std::unordered_map {OpCode::SET_CONTROLLER_TO_HOST_FLOW_CONTROL, OpCodeIndex::SET_CONTROLLER_TO_HOST_FLOW_CONTROL}, {OpCode::HOST_BUFFER_SIZE, OpCodeIndex::HOST_BUFFER_SIZE}, - {OpCode::HOST_NUMBER_OF_COMPLETED_PACKETS, - OpCodeIndex::HOST_NUMBER_OF_COMPLETED_PACKETS}, - {OpCode::READ_LINK_SUPERVISION_TIMEOUT, - OpCodeIndex::READ_LINK_SUPERVISION_TIMEOUT}, - {OpCode::WRITE_LINK_SUPERVISION_TIMEOUT, - OpCodeIndex::WRITE_LINK_SUPERVISION_TIMEOUT}, - {OpCode::READ_NUMBER_OF_SUPPORTED_IAC, - OpCodeIndex::READ_NUMBER_OF_SUPPORTED_IAC}, + {OpCode::HOST_NUMBER_OF_COMPLETED_PACKETS, OpCodeIndex::HOST_NUMBER_OF_COMPLETED_PACKETS}, + {OpCode::READ_LINK_SUPERVISION_TIMEOUT, OpCodeIndex::READ_LINK_SUPERVISION_TIMEOUT}, + {OpCode::WRITE_LINK_SUPERVISION_TIMEOUT, OpCodeIndex::WRITE_LINK_SUPERVISION_TIMEOUT}, + {OpCode::READ_NUMBER_OF_SUPPORTED_IAC, OpCodeIndex::READ_NUMBER_OF_SUPPORTED_IAC}, {OpCode::READ_CURRENT_IAC_LAP, OpCodeIndex::READ_CURRENT_IAC_LAP}, {OpCode::WRITE_CURRENT_IAC_LAP, OpCodeIndex::WRITE_CURRENT_IAC_LAP}, {OpCode::SET_AFH_HOST_CHANNEL_CLASSIFICATION, @@ -3815,19 +3363,13 @@ const std::unordered_map {OpCode::WRITE_INQUIRY_MODE, OpCodeIndex::WRITE_INQUIRY_MODE}, {OpCode::READ_PAGE_SCAN_TYPE, OpCodeIndex::READ_PAGE_SCAN_TYPE}, {OpCode::WRITE_PAGE_SCAN_TYPE, OpCodeIndex::WRITE_PAGE_SCAN_TYPE}, - {OpCode::READ_AFH_CHANNEL_ASSESSMENT_MODE, - OpCodeIndex::READ_AFH_CHANNEL_ASSESSMENT_MODE}, - {OpCode::WRITE_AFH_CHANNEL_ASSESSMENT_MODE, - OpCodeIndex::WRITE_AFH_CHANNEL_ASSESSMENT_MODE}, - {OpCode::READ_EXTENDED_INQUIRY_RESPONSE, - OpCodeIndex::READ_EXTENDED_INQUIRY_RESPONSE}, - {OpCode::WRITE_EXTENDED_INQUIRY_RESPONSE, - OpCodeIndex::WRITE_EXTENDED_INQUIRY_RESPONSE}, + {OpCode::READ_AFH_CHANNEL_ASSESSMENT_MODE, OpCodeIndex::READ_AFH_CHANNEL_ASSESSMENT_MODE}, + {OpCode::WRITE_AFH_CHANNEL_ASSESSMENT_MODE, OpCodeIndex::WRITE_AFH_CHANNEL_ASSESSMENT_MODE}, + {OpCode::READ_EXTENDED_INQUIRY_RESPONSE, OpCodeIndex::READ_EXTENDED_INQUIRY_RESPONSE}, + {OpCode::WRITE_EXTENDED_INQUIRY_RESPONSE, OpCodeIndex::WRITE_EXTENDED_INQUIRY_RESPONSE}, {OpCode::REFRESH_ENCRYPTION_KEY, OpCodeIndex::REFRESH_ENCRYPTION_KEY}, - {OpCode::READ_SIMPLE_PAIRING_MODE, - OpCodeIndex::READ_SIMPLE_PAIRING_MODE}, - {OpCode::WRITE_SIMPLE_PAIRING_MODE, - OpCodeIndex::WRITE_SIMPLE_PAIRING_MODE}, + {OpCode::READ_SIMPLE_PAIRING_MODE, OpCodeIndex::READ_SIMPLE_PAIRING_MODE}, + {OpCode::WRITE_SIMPLE_PAIRING_MODE, OpCodeIndex::WRITE_SIMPLE_PAIRING_MODE}, {OpCode::READ_LOCAL_OOB_DATA, OpCodeIndex::READ_LOCAL_OOB_DATA}, {OpCode::READ_INQUIRY_RESPONSE_TRANSMIT_POWER_LEVEL, OpCodeIndex::READ_INQUIRY_RESPONSE_TRANSMIT_POWER_LEVEL}, @@ -3838,8 +3380,7 @@ const std::unordered_map {OpCode::WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING, OpCodeIndex::WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING}, {OpCode::ENHANCED_FLUSH, OpCodeIndex::ENHANCED_FLUSH}, - {OpCode::SEND_KEYPRESS_NOTIFICATION, - OpCodeIndex::SEND_KEYPRESS_NOTIFICATION}, + {OpCode::SEND_KEYPRESS_NOTIFICATION, OpCodeIndex::SEND_KEYPRESS_NOTIFICATION}, {OpCode::SET_EVENT_MASK_PAGE_2, OpCodeIndex::SET_EVENT_MASK_PAGE_2}, {OpCode::READ_FLOW_CONTROL_MODE, OpCodeIndex::READ_FLOW_CONTROL_MODE}, {OpCode::WRITE_FLOW_CONTROL_MODE, OpCodeIndex::WRITE_FLOW_CONTROL_MODE}, @@ -3847,16 +3388,12 @@ const std::unordered_map OpCodeIndex::READ_ENHANCED_TRANSMIT_POWER_LEVEL}, {OpCode::READ_LE_HOST_SUPPORT, OpCodeIndex::READ_LE_HOST_SUPPORT}, {OpCode::WRITE_LE_HOST_SUPPORT, OpCodeIndex::WRITE_LE_HOST_SUPPORT}, - {OpCode::SET_MWS_CHANNEL_PARAMETERS, - OpCodeIndex::SET_MWS_CHANNEL_PARAMETERS}, - {OpCode::SET_EXTERNAL_FRAME_CONFIGURATION, - OpCodeIndex::SET_EXTERNAL_FRAME_CONFIGURATION}, + {OpCode::SET_MWS_CHANNEL_PARAMETERS, OpCodeIndex::SET_MWS_CHANNEL_PARAMETERS}, + {OpCode::SET_EXTERNAL_FRAME_CONFIGURATION, OpCodeIndex::SET_EXTERNAL_FRAME_CONFIGURATION}, {OpCode::SET_MWS_SIGNALING, OpCodeIndex::SET_MWS_SIGNALING}, {OpCode::SET_MWS_TRANSPORT_LAYER, OpCodeIndex::SET_MWS_TRANSPORT_LAYER}, - {OpCode::SET_MWS_SCAN_FREQUENCY_TABLE, - OpCodeIndex::SET_MWS_SCAN_FREQUENCY_TABLE}, - {OpCode::SET_MWS_PATTERN_CONFIGURATION, - OpCodeIndex::SET_MWS_PATTERN_CONFIGURATION}, + {OpCode::SET_MWS_SCAN_FREQUENCY_TABLE, OpCodeIndex::SET_MWS_SCAN_FREQUENCY_TABLE}, + {OpCode::SET_MWS_PATTERN_CONFIGURATION, OpCodeIndex::SET_MWS_PATTERN_CONFIGURATION}, {OpCode::SET_RESERVED_LT_ADDR, OpCodeIndex::SET_RESERVED_LT_ADDR}, {OpCode::DELETE_RESERVED_LT_ADDR, OpCodeIndex::DELETE_RESERVED_LT_ADDR}, {OpCode::SET_CONNECTIONLESS_PERIPHERAL_BROADCAST_DATA, @@ -3873,93 +3410,67 @@ const std::unordered_map OpCodeIndex::READ_AUTHENTICATED_PAYLOAD_TIMEOUT}, {OpCode::WRITE_AUTHENTICATED_PAYLOAD_TIMEOUT, OpCodeIndex::WRITE_AUTHENTICATED_PAYLOAD_TIMEOUT}, - {OpCode::READ_LOCAL_OOB_EXTENDED_DATA, - OpCodeIndex::READ_LOCAL_OOB_EXTENDED_DATA}, - {OpCode::READ_EXTENDED_PAGE_TIMEOUT, - OpCodeIndex::READ_EXTENDED_PAGE_TIMEOUT}, - {OpCode::WRITE_EXTENDED_PAGE_TIMEOUT, - OpCodeIndex::WRITE_EXTENDED_PAGE_TIMEOUT}, - {OpCode::READ_EXTENDED_INQUIRY_LENGTH, - OpCodeIndex::READ_EXTENDED_INQUIRY_LENGTH}, - {OpCode::WRITE_EXTENDED_INQUIRY_LENGTH, - OpCodeIndex::WRITE_EXTENDED_INQUIRY_LENGTH}, - {OpCode::SET_ECOSYSTEM_BASE_INTERVAL, - OpCodeIndex::SET_ECOSYSTEM_BASE_INTERVAL}, + {OpCode::READ_LOCAL_OOB_EXTENDED_DATA, OpCodeIndex::READ_LOCAL_OOB_EXTENDED_DATA}, + {OpCode::READ_EXTENDED_PAGE_TIMEOUT, OpCodeIndex::READ_EXTENDED_PAGE_TIMEOUT}, + {OpCode::WRITE_EXTENDED_PAGE_TIMEOUT, OpCodeIndex::WRITE_EXTENDED_PAGE_TIMEOUT}, + {OpCode::READ_EXTENDED_INQUIRY_LENGTH, OpCodeIndex::READ_EXTENDED_INQUIRY_LENGTH}, + {OpCode::WRITE_EXTENDED_INQUIRY_LENGTH, OpCodeIndex::WRITE_EXTENDED_INQUIRY_LENGTH}, + {OpCode::SET_ECOSYSTEM_BASE_INTERVAL, OpCodeIndex::SET_ECOSYSTEM_BASE_INTERVAL}, {OpCode::CONFIGURE_DATA_PATH, OpCodeIndex::CONFIGURE_DATA_PATH}, - {OpCode::SET_MIN_ENCRYPTION_KEY_SIZE, - OpCodeIndex::SET_MIN_ENCRYPTION_KEY_SIZE}, + {OpCode::SET_MIN_ENCRYPTION_KEY_SIZE, OpCodeIndex::SET_MIN_ENCRYPTION_KEY_SIZE}, // INFORMATIONAL_PARAMETERS - {OpCode::READ_LOCAL_VERSION_INFORMATION, - OpCodeIndex::READ_LOCAL_VERSION_INFORMATION}, - {OpCode::READ_LOCAL_SUPPORTED_FEATURES, - OpCodeIndex::READ_LOCAL_SUPPORTED_FEATURES}, - {OpCode::READ_LOCAL_EXTENDED_FEATURES, - OpCodeIndex::READ_LOCAL_EXTENDED_FEATURES}, + {OpCode::READ_LOCAL_VERSION_INFORMATION, OpCodeIndex::READ_LOCAL_VERSION_INFORMATION}, + {OpCode::READ_LOCAL_SUPPORTED_FEATURES, OpCodeIndex::READ_LOCAL_SUPPORTED_FEATURES}, + {OpCode::READ_LOCAL_EXTENDED_FEATURES, OpCodeIndex::READ_LOCAL_EXTENDED_FEATURES}, {OpCode::READ_BUFFER_SIZE, OpCodeIndex::READ_BUFFER_SIZE}, {OpCode::READ_BD_ADDR, OpCodeIndex::READ_BD_ADDR}, {OpCode::READ_DATA_BLOCK_SIZE, OpCodeIndex::READ_DATA_BLOCK_SIZE}, - {OpCode::READ_LOCAL_SUPPORTED_CODECS_V1, - OpCodeIndex::READ_LOCAL_SUPPORTED_CODECS_V1}, - {OpCode::READ_LOCAL_SIMPLE_PAIRING_OPTIONS, - OpCodeIndex::READ_LOCAL_SIMPLE_PAIRING_OPTIONS}, - {OpCode::READ_LOCAL_SUPPORTED_CODECS_V2, - OpCodeIndex::READ_LOCAL_SUPPORTED_CODECS_V2}, + {OpCode::READ_LOCAL_SUPPORTED_CODECS_V1, OpCodeIndex::READ_LOCAL_SUPPORTED_CODECS_V1}, + {OpCode::READ_LOCAL_SIMPLE_PAIRING_OPTIONS, OpCodeIndex::READ_LOCAL_SIMPLE_PAIRING_OPTIONS}, + {OpCode::READ_LOCAL_SUPPORTED_CODECS_V2, OpCodeIndex::READ_LOCAL_SUPPORTED_CODECS_V2}, {OpCode::READ_LOCAL_SUPPORTED_CODEC_CAPABILITIES, OpCodeIndex::READ_LOCAL_SUPPORTED_CODEC_CAPABILITIES}, {OpCode::READ_LOCAL_SUPPORTED_CONTROLLER_DELAY, OpCodeIndex::READ_LOCAL_SUPPORTED_CONTROLLER_DELAY}, // STATUS_PARAMETERS - {OpCode::READ_FAILED_CONTACT_COUNTER, - OpCodeIndex::READ_FAILED_CONTACT_COUNTER}, - {OpCode::RESET_FAILED_CONTACT_COUNTER, - OpCodeIndex::RESET_FAILED_CONTACT_COUNTER}, + {OpCode::READ_FAILED_CONTACT_COUNTER, OpCodeIndex::READ_FAILED_CONTACT_COUNTER}, + {OpCode::RESET_FAILED_CONTACT_COUNTER, OpCodeIndex::RESET_FAILED_CONTACT_COUNTER}, {OpCode::READ_LINK_QUALITY, OpCodeIndex::READ_LINK_QUALITY}, {OpCode::READ_RSSI, OpCodeIndex::READ_RSSI}, {OpCode::READ_AFH_CHANNEL_MAP, OpCodeIndex::READ_AFH_CHANNEL_MAP}, {OpCode::READ_CLOCK, OpCodeIndex::READ_CLOCK}, - {OpCode::READ_ENCRYPTION_KEY_SIZE, - OpCodeIndex::READ_ENCRYPTION_KEY_SIZE}, + {OpCode::READ_ENCRYPTION_KEY_SIZE, OpCodeIndex::READ_ENCRYPTION_KEY_SIZE}, {OpCode::GET_MWS_TRANSPORT_LAYER_CONFIGURATION, OpCodeIndex::GET_MWS_TRANSPORT_LAYER_CONFIGURATION}, - {OpCode::SET_TRIGGERED_CLOCK_CAPTURE, - OpCodeIndex::SET_TRIGGERED_CLOCK_CAPTURE}, + {OpCode::SET_TRIGGERED_CLOCK_CAPTURE, OpCodeIndex::SET_TRIGGERED_CLOCK_CAPTURE}, // TESTING {OpCode::READ_LOOPBACK_MODE, OpCodeIndex::READ_LOOPBACK_MODE}, {OpCode::WRITE_LOOPBACK_MODE, OpCodeIndex::WRITE_LOOPBACK_MODE}, - {OpCode::ENABLE_DEVICE_UNDER_TEST_MODE, - OpCodeIndex::ENABLE_DEVICE_UNDER_TEST_MODE}, - {OpCode::WRITE_SIMPLE_PAIRING_DEBUG_MODE, - OpCodeIndex::WRITE_SIMPLE_PAIRING_DEBUG_MODE}, + {OpCode::ENABLE_DEVICE_UNDER_TEST_MODE, OpCodeIndex::ENABLE_DEVICE_UNDER_TEST_MODE}, + {OpCode::WRITE_SIMPLE_PAIRING_DEBUG_MODE, OpCodeIndex::WRITE_SIMPLE_PAIRING_DEBUG_MODE}, {OpCode::WRITE_SECURE_CONNECTIONS_TEST_MODE, OpCodeIndex::WRITE_SECURE_CONNECTIONS_TEST_MODE}, // LE_CONTROLLER {OpCode::LE_SET_EVENT_MASK, OpCodeIndex::LE_SET_EVENT_MASK}, {OpCode::LE_READ_BUFFER_SIZE_V1, OpCodeIndex::LE_READ_BUFFER_SIZE_V1}, - {OpCode::LE_READ_LOCAL_SUPPORTED_FEATURES, - OpCodeIndex::LE_READ_LOCAL_SUPPORTED_FEATURES}, + {OpCode::LE_READ_LOCAL_SUPPORTED_FEATURES, OpCodeIndex::LE_READ_LOCAL_SUPPORTED_FEATURES}, {OpCode::LE_SET_RANDOM_ADDRESS, OpCodeIndex::LE_SET_RANDOM_ADDRESS}, - {OpCode::LE_SET_ADVERTISING_PARAMETERS, - OpCodeIndex::LE_SET_ADVERTISING_PARAMETERS}, + {OpCode::LE_SET_ADVERTISING_PARAMETERS, OpCodeIndex::LE_SET_ADVERTISING_PARAMETERS}, {OpCode::LE_READ_ADVERTISING_PHYSICAL_CHANNEL_TX_POWER, OpCodeIndex::LE_READ_ADVERTISING_PHYSICAL_CHANNEL_TX_POWER}, {OpCode::LE_SET_ADVERTISING_DATA, OpCodeIndex::LE_SET_ADVERTISING_DATA}, - {OpCode::LE_SET_SCAN_RESPONSE_DATA, - OpCodeIndex::LE_SET_SCAN_RESPONSE_DATA}, - {OpCode::LE_SET_ADVERTISING_ENABLE, - OpCodeIndex::LE_SET_ADVERTISING_ENABLE}, + {OpCode::LE_SET_SCAN_RESPONSE_DATA, OpCodeIndex::LE_SET_SCAN_RESPONSE_DATA}, + {OpCode::LE_SET_ADVERTISING_ENABLE, OpCodeIndex::LE_SET_ADVERTISING_ENABLE}, {OpCode::LE_SET_SCAN_PARAMETERS, OpCodeIndex::LE_SET_SCAN_PARAMETERS}, {OpCode::LE_SET_SCAN_ENABLE, OpCodeIndex::LE_SET_SCAN_ENABLE}, {OpCode::LE_CREATE_CONNECTION, OpCodeIndex::LE_CREATE_CONNECTION}, - {OpCode::LE_CREATE_CONNECTION_CANCEL, - OpCodeIndex::LE_CREATE_CONNECTION_CANCEL}, - {OpCode::LE_READ_FILTER_ACCEPT_LIST_SIZE, - OpCodeIndex::LE_READ_FILTER_ACCEPT_LIST_SIZE}, - {OpCode::LE_CLEAR_FILTER_ACCEPT_LIST, - OpCodeIndex::LE_CLEAR_FILTER_ACCEPT_LIST}, + {OpCode::LE_CREATE_CONNECTION_CANCEL, OpCodeIndex::LE_CREATE_CONNECTION_CANCEL}, + {OpCode::LE_READ_FILTER_ACCEPT_LIST_SIZE, OpCodeIndex::LE_READ_FILTER_ACCEPT_LIST_SIZE}, + {OpCode::LE_CLEAR_FILTER_ACCEPT_LIST, OpCodeIndex::LE_CLEAR_FILTER_ACCEPT_LIST}, {OpCode::LE_ADD_DEVICE_TO_FILTER_ACCEPT_LIST, OpCodeIndex::LE_ADD_DEVICE_TO_FILTER_ACCEPT_LIST}, {OpCode::LE_REMOVE_DEVICE_FROM_FILTER_ACCEPT_LIST, @@ -3972,12 +3483,10 @@ const std::unordered_map {OpCode::LE_ENCRYPT, OpCodeIndex::LE_ENCRYPT}, {OpCode::LE_RAND, OpCodeIndex::LE_RAND}, {OpCode::LE_START_ENCRYPTION, OpCodeIndex::LE_START_ENCRYPTION}, - {OpCode::LE_LONG_TERM_KEY_REQUEST_REPLY, - OpCodeIndex::LE_LONG_TERM_KEY_REQUEST_REPLY}, + {OpCode::LE_LONG_TERM_KEY_REQUEST_REPLY, OpCodeIndex::LE_LONG_TERM_KEY_REQUEST_REPLY}, {OpCode::LE_LONG_TERM_KEY_REQUEST_NEGATIVE_REPLY, OpCodeIndex::LE_LONG_TERM_KEY_REQUEST_NEGATIVE_REPLY}, - {OpCode::LE_READ_SUPPORTED_STATES, - OpCodeIndex::LE_READ_SUPPORTED_STATES}, + {OpCode::LE_READ_SUPPORTED_STATES, OpCodeIndex::LE_READ_SUPPORTED_STATES}, {OpCode::LE_RECEIVER_TEST_V1, OpCodeIndex::LE_RECEIVER_TEST_V1}, {OpCode::LE_TRANSMITTER_TEST_V1, OpCodeIndex::LE_TRANSMITTER_TEST_V1}, {OpCode::LE_TEST_END, OpCodeIndex::LE_TEST_END}, @@ -3990,26 +3499,19 @@ const std::unordered_map OpCodeIndex::LE_READ_SUGGESTED_DEFAULT_DATA_LENGTH}, {OpCode::LE_WRITE_SUGGESTED_DEFAULT_DATA_LENGTH, OpCodeIndex::LE_WRITE_SUGGESTED_DEFAULT_DATA_LENGTH}, - {OpCode::LE_READ_LOCAL_P_256_PUBLIC_KEY, - OpCodeIndex::LE_READ_LOCAL_P_256_PUBLIC_KEY}, + {OpCode::LE_READ_LOCAL_P_256_PUBLIC_KEY, OpCodeIndex::LE_READ_LOCAL_P_256_PUBLIC_KEY}, {OpCode::LE_GENERATE_DHKEY_V1, OpCodeIndex::LE_GENERATE_DHKEY_V1}, - {OpCode::LE_ADD_DEVICE_TO_RESOLVING_LIST, - OpCodeIndex::LE_ADD_DEVICE_TO_RESOLVING_LIST}, + {OpCode::LE_ADD_DEVICE_TO_RESOLVING_LIST, OpCodeIndex::LE_ADD_DEVICE_TO_RESOLVING_LIST}, {OpCode::LE_REMOVE_DEVICE_FROM_RESOLVING_LIST, OpCodeIndex::LE_REMOVE_DEVICE_FROM_RESOLVING_LIST}, {OpCode::LE_CLEAR_RESOLVING_LIST, OpCodeIndex::LE_CLEAR_RESOLVING_LIST}, - {OpCode::LE_READ_RESOLVING_LIST_SIZE, - OpCodeIndex::LE_READ_RESOLVING_LIST_SIZE}, - {OpCode::LE_READ_PEER_RESOLVABLE_ADDRESS, - OpCodeIndex::LE_READ_PEER_RESOLVABLE_ADDRESS}, - {OpCode::LE_READ_LOCAL_RESOLVABLE_ADDRESS, - OpCodeIndex::LE_READ_LOCAL_RESOLVABLE_ADDRESS}, - {OpCode::LE_SET_ADDRESS_RESOLUTION_ENABLE, - OpCodeIndex::LE_SET_ADDRESS_RESOLUTION_ENABLE}, + {OpCode::LE_READ_RESOLVING_LIST_SIZE, OpCodeIndex::LE_READ_RESOLVING_LIST_SIZE}, + {OpCode::LE_READ_PEER_RESOLVABLE_ADDRESS, OpCodeIndex::LE_READ_PEER_RESOLVABLE_ADDRESS}, + {OpCode::LE_READ_LOCAL_RESOLVABLE_ADDRESS, OpCodeIndex::LE_READ_LOCAL_RESOLVABLE_ADDRESS}, + {OpCode::LE_SET_ADDRESS_RESOLUTION_ENABLE, OpCodeIndex::LE_SET_ADDRESS_RESOLUTION_ENABLE}, {OpCode::LE_SET_RESOLVABLE_PRIVATE_ADDRESS_TIMEOUT, OpCodeIndex::LE_SET_RESOLVABLE_PRIVATE_ADDRESS_TIMEOUT}, - {OpCode::LE_READ_MAXIMUM_DATA_LENGTH, - OpCodeIndex::LE_READ_MAXIMUM_DATA_LENGTH}, + {OpCode::LE_READ_MAXIMUM_DATA_LENGTH, OpCodeIndex::LE_READ_MAXIMUM_DATA_LENGTH}, {OpCode::LE_READ_PHY, OpCodeIndex::LE_READ_PHY}, {OpCode::LE_SET_DEFAULT_PHY, OpCodeIndex::LE_SET_DEFAULT_PHY}, {OpCode::LE_SET_PHY, OpCodeIndex::LE_SET_PHY}, @@ -4019,8 +3521,7 @@ const std::unordered_map OpCodeIndex::LE_SET_ADVERTISING_SET_RANDOM_ADDRESS}, {OpCode::LE_SET_EXTENDED_ADVERTISING_PARAMETERS, OpCodeIndex::LE_SET_EXTENDED_ADVERTISING_PARAMETERS}, - {OpCode::LE_SET_EXTENDED_ADVERTISING_DATA, - OpCodeIndex::LE_SET_EXTENDED_ADVERTISING_DATA}, + {OpCode::LE_SET_EXTENDED_ADVERTISING_DATA, OpCodeIndex::LE_SET_EXTENDED_ADVERTISING_DATA}, {OpCode::LE_SET_EXTENDED_SCAN_RESPONSE_DATA, OpCodeIndex::LE_SET_EXTENDED_SCAN_RESPONSE_DATA}, {OpCode::LE_SET_EXTENDED_ADVERTISING_ENABLE, @@ -4029,22 +3530,16 @@ const std::unordered_map OpCodeIndex::LE_READ_MAXIMUM_ADVERTISING_DATA_LENGTH}, {OpCode::LE_READ_NUMBER_OF_SUPPORTED_ADVERTISING_SETS, OpCodeIndex::LE_READ_NUMBER_OF_SUPPORTED_ADVERTISING_SETS}, - {OpCode::LE_REMOVE_ADVERTISING_SET, - OpCodeIndex::LE_REMOVE_ADVERTISING_SET}, - {OpCode::LE_CLEAR_ADVERTISING_SETS, - OpCodeIndex::LE_CLEAR_ADVERTISING_SETS}, + {OpCode::LE_REMOVE_ADVERTISING_SET, OpCodeIndex::LE_REMOVE_ADVERTISING_SET}, + {OpCode::LE_CLEAR_ADVERTISING_SETS, OpCodeIndex::LE_CLEAR_ADVERTISING_SETS}, {OpCode::LE_SET_PERIODIC_ADVERTISING_PARAMETERS, OpCodeIndex::LE_SET_PERIODIC_ADVERTISING_PARAMETERS}, - {OpCode::LE_SET_PERIODIC_ADVERTISING_DATA, - OpCodeIndex::LE_SET_PERIODIC_ADVERTISING_DATA}, + {OpCode::LE_SET_PERIODIC_ADVERTISING_DATA, OpCodeIndex::LE_SET_PERIODIC_ADVERTISING_DATA}, {OpCode::LE_SET_PERIODIC_ADVERTISING_ENABLE, OpCodeIndex::LE_SET_PERIODIC_ADVERTISING_ENABLE}, - {OpCode::LE_SET_EXTENDED_SCAN_PARAMETERS, - OpCodeIndex::LE_SET_EXTENDED_SCAN_PARAMETERS}, - {OpCode::LE_SET_EXTENDED_SCAN_ENABLE, - OpCodeIndex::LE_SET_EXTENDED_SCAN_ENABLE}, - {OpCode::LE_EXTENDED_CREATE_CONNECTION, - OpCodeIndex::LE_EXTENDED_CREATE_CONNECTION}, + {OpCode::LE_SET_EXTENDED_SCAN_PARAMETERS, OpCodeIndex::LE_SET_EXTENDED_SCAN_PARAMETERS}, + {OpCode::LE_SET_EXTENDED_SCAN_ENABLE, OpCodeIndex::LE_SET_EXTENDED_SCAN_ENABLE}, + {OpCode::LE_EXTENDED_CREATE_CONNECTION, OpCodeIndex::LE_EXTENDED_CREATE_CONNECTION}, {OpCode::LE_PERIODIC_ADVERTISING_CREATE_SYNC, OpCodeIndex::LE_PERIODIC_ADVERTISING_CREATE_SYNC}, {OpCode::LE_PERIODIC_ADVERTISING_CREATE_SYNC_CANCEL, @@ -4055,8 +3550,7 @@ const std::unordered_map OpCodeIndex::LE_ADD_DEVICE_TO_PERIODIC_ADVERTISER_LIST}, {OpCode::LE_REMOVE_DEVICE_FROM_PERIODIC_ADVERTISER_LIST, OpCodeIndex::LE_REMOVE_DEVICE_FROM_PERIODIC_ADVERTISER_LIST}, - {OpCode::LE_CLEAR_PERIODIC_ADVERTISER_LIST, - OpCodeIndex::LE_CLEAR_PERIODIC_ADVERTISER_LIST}, + {OpCode::LE_CLEAR_PERIODIC_ADVERTISER_LIST, OpCodeIndex::LE_CLEAR_PERIODIC_ADVERTISER_LIST}, {OpCode::LE_READ_PERIODIC_ADVERTISER_LIST_SIZE, OpCodeIndex::LE_READ_PERIODIC_ADVERTISER_LIST_SIZE}, {OpCode::LE_READ_TRANSMIT_POWER, OpCodeIndex::LE_READ_TRANSMIT_POWER}, @@ -4077,12 +3571,9 @@ const std::unordered_map OpCodeIndex::LE_SET_CONNECTION_CTE_RECEIVE_PARAMETERS}, {OpCode::LE_SET_CONNECTION_CTE_TRANSMIT_PARAMETERS, OpCodeIndex::LE_SET_CONNECTION_CTE_TRANSMIT_PARAMETERS}, - {OpCode::LE_CONNECTION_CTE_REQUEST_ENABLE, - OpCodeIndex::LE_CONNECTION_CTE_REQUEST_ENABLE}, - {OpCode::LE_CONNECTION_CTE_RESPONSE_ENABLE, - OpCodeIndex::LE_CONNECTION_CTE_RESPONSE_ENABLE}, - {OpCode::LE_READ_ANTENNA_INFORMATION, - OpCodeIndex::LE_READ_ANTENNA_INFORMATION}, + {OpCode::LE_CONNECTION_CTE_REQUEST_ENABLE, OpCodeIndex::LE_CONNECTION_CTE_REQUEST_ENABLE}, + {OpCode::LE_CONNECTION_CTE_RESPONSE_ENABLE, OpCodeIndex::LE_CONNECTION_CTE_RESPONSE_ENABLE}, + {OpCode::LE_READ_ANTENNA_INFORMATION, OpCodeIndex::LE_READ_ANTENNA_INFORMATION}, {OpCode::LE_SET_PERIODIC_ADVERTISING_RECEIVE_ENABLE, OpCodeIndex::LE_SET_PERIODIC_ADVERTISING_RECEIVE_ENABLE}, {OpCode::LE_PERIODIC_ADVERTISING_SYNC_TRANSFER, @@ -4092,16 +3583,13 @@ const std::unordered_map {OpCode::LE_SET_PERIODIC_ADVERTISING_SYNC_TRANSFER_PARAMETERS, OpCodeIndex::LE_SET_PERIODIC_ADVERTISING_SYNC_TRANSFER_PARAMETERS}, {OpCode::LE_SET_DEFAULT_PERIODIC_ADVERTISING_SYNC_TRANSFER_PARAMETERS, - OpCodeIndex:: - LE_SET_DEFAULT_PERIODIC_ADVERTISING_SYNC_TRANSFER_PARAMETERS}, + OpCodeIndex::LE_SET_DEFAULT_PERIODIC_ADVERTISING_SYNC_TRANSFER_PARAMETERS}, {OpCode::LE_GENERATE_DHKEY_V2, OpCodeIndex::LE_GENERATE_DHKEY_V2}, - {OpCode::LE_MODIFY_SLEEP_CLOCK_ACCURACY, - OpCodeIndex::LE_MODIFY_SLEEP_CLOCK_ACCURACY}, + {OpCode::LE_MODIFY_SLEEP_CLOCK_ACCURACY, OpCodeIndex::LE_MODIFY_SLEEP_CLOCK_ACCURACY}, {OpCode::LE_READ_BUFFER_SIZE_V2, OpCodeIndex::LE_READ_BUFFER_SIZE_V2}, {OpCode::LE_READ_ISO_TX_SYNC, OpCodeIndex::LE_READ_ISO_TX_SYNC}, {OpCode::LE_SET_CIG_PARAMETERS, OpCodeIndex::LE_SET_CIG_PARAMETERS}, - {OpCode::LE_SET_CIG_PARAMETERS_TEST, - OpCodeIndex::LE_SET_CIG_PARAMETERS_TEST}, + {OpCode::LE_SET_CIG_PARAMETERS_TEST, OpCodeIndex::LE_SET_CIG_PARAMETERS_TEST}, {OpCode::LE_CREATE_CIS, OpCodeIndex::LE_CREATE_CIS}, {OpCode::LE_REMOVE_CIG, OpCodeIndex::LE_REMOVE_CIG}, {OpCode::LE_ACCEPT_CIS_REQUEST, OpCodeIndex::LE_ACCEPT_CIS_REQUEST}, @@ -4116,20 +3604,17 @@ const std::unordered_map {OpCode::LE_REMOVE_ISO_DATA_PATH, OpCodeIndex::LE_REMOVE_ISO_DATA_PATH}, {OpCode::LE_ISO_TRANSMIT_TEST, OpCodeIndex::LE_ISO_TRANSMIT_TEST}, {OpCode::LE_ISO_RECEIVE_TEST, OpCodeIndex::LE_ISO_RECEIVE_TEST}, - {OpCode::LE_ISO_READ_TEST_COUNTERS, - OpCodeIndex::LE_ISO_READ_TEST_COUNTERS}, + {OpCode::LE_ISO_READ_TEST_COUNTERS, OpCodeIndex::LE_ISO_READ_TEST_COUNTERS}, {OpCode::LE_ISO_TEST_END, OpCodeIndex::LE_ISO_TEST_END}, {OpCode::LE_SET_HOST_FEATURE, OpCodeIndex::LE_SET_HOST_FEATURE}, - {OpCode::LE_READ_ISO_LINK_QUALITY, - OpCodeIndex::LE_READ_ISO_LINK_QUALITY}, + {OpCode::LE_READ_ISO_LINK_QUALITY, OpCodeIndex::LE_READ_ISO_LINK_QUALITY}, {OpCode::LE_ENHANCED_READ_TRANSMIT_POWER_LEVEL, OpCodeIndex::LE_ENHANCED_READ_TRANSMIT_POWER_LEVEL}, {OpCode::LE_READ_REMOTE_TRANSMIT_POWER_LEVEL, OpCodeIndex::LE_READ_REMOTE_TRANSMIT_POWER_LEVEL}, {OpCode::LE_SET_PATH_LOSS_REPORTING_PARAMETERS, OpCodeIndex::LE_SET_PATH_LOSS_REPORTING_PARAMETERS}, - {OpCode::LE_SET_PATH_LOSS_REPORTING_ENABLE, - OpCodeIndex::LE_SET_PATH_LOSS_REPORTING_ENABLE}, + {OpCode::LE_SET_PATH_LOSS_REPORTING_ENABLE, OpCodeIndex::LE_SET_PATH_LOSS_REPORTING_ENABLE}, {OpCode::LE_SET_TRANSMIT_POWER_REPORTING_ENABLE, OpCodeIndex::LE_SET_TRANSMIT_POWER_REPORTING_ENABLE}, {OpCode::LE_TRANSMITTER_TEST_V4, OpCodeIndex::LE_TRANSMITTER_TEST_V4}, @@ -4137,548 +3622,501 @@ const std::unordered_map OpCodeIndex::LE_SET_DATA_RELATED_ADDRESS_CHANGES}, {OpCode::LE_SET_DEFAULT_SUBRATE, OpCodeIndex::LE_SET_DEFAULT_SUBRATE}, {OpCode::LE_SUBRATE_REQUEST, OpCodeIndex::LE_SUBRATE_REQUEST}, - }; +}; const std::unordered_map - DualModeController::hci_command_handlers_{ - // LINK_CONTROL - {OpCode::INQUIRY, &DualModeController::Inquiry}, - {OpCode::INQUIRY_CANCEL, &DualModeController::InquiryCancel}, - //{OpCode::PERIODIC_INQUIRY_MODE, - //&DualModeController::PeriodicInquiryMode}, - //{OpCode::EXIT_PERIODIC_INQUIRY_MODE, - //&DualModeController::ExitPeriodicInquiryMode}, - {OpCode::CREATE_CONNECTION, &DualModeController::CreateConnection}, - {OpCode::DISCONNECT, &DualModeController::Disconnect}, - {OpCode::ADD_SCO_CONNECTION, &DualModeController::AddScoConnection}, - {OpCode::CREATE_CONNECTION_CANCEL, - &DualModeController::CreateConnectionCancel}, - {OpCode::ACCEPT_CONNECTION_REQUEST, - &DualModeController::AcceptConnectionRequest}, - {OpCode::REJECT_CONNECTION_REQUEST, - &DualModeController::RejectConnectionRequest}, - {OpCode::LINK_KEY_REQUEST_REPLY, &DualModeController::ForwardToLm}, - {OpCode::LINK_KEY_REQUEST_NEGATIVE_REPLY, - &DualModeController::ForwardToLm}, - {OpCode::PIN_CODE_REQUEST_REPLY, &DualModeController::ForwardToLm}, - {OpCode::PIN_CODE_REQUEST_NEGATIVE_REPLY, - &DualModeController::ForwardToLm}, - {OpCode::CHANGE_CONNECTION_PACKET_TYPE, - &DualModeController::ChangeConnectionPacketType}, - {OpCode::AUTHENTICATION_REQUESTED, &DualModeController::ForwardToLm}, - {OpCode::SET_CONNECTION_ENCRYPTION, &DualModeController::ForwardToLm}, - {OpCode::CHANGE_CONNECTION_LINK_KEY, - &DualModeController::ChangeConnectionLinkKey}, - {OpCode::CENTRAL_LINK_KEY, &DualModeController::CentralLinkKey}, - {OpCode::REMOTE_NAME_REQUEST, &DualModeController::RemoteNameRequest}, - //{OpCode::REMOTE_NAME_REQUEST_CANCEL, - //&DualModeController::RemoteNameRequestCancel}, - {OpCode::READ_REMOTE_SUPPORTED_FEATURES, - &DualModeController::ReadRemoteSupportedFeatures}, - {OpCode::READ_REMOTE_EXTENDED_FEATURES, - &DualModeController::ReadRemoteExtendedFeatures}, - {OpCode::READ_REMOTE_VERSION_INFORMATION, - &DualModeController::ReadRemoteVersionInformation}, - {OpCode::READ_CLOCK_OFFSET, &DualModeController::ReadClockOffset}, - //{OpCode::READ_LMP_HANDLE, &DualModeController::ReadLmpHandle}, - {OpCode::SETUP_SYNCHRONOUS_CONNECTION, - &DualModeController::SetupSynchronousConnection}, - {OpCode::ACCEPT_SYNCHRONOUS_CONNECTION, - &DualModeController::AcceptSynchronousConnection}, - {OpCode::REJECT_SYNCHRONOUS_CONNECTION, - &DualModeController::RejectSynchronousConnection}, - {OpCode::IO_CAPABILITY_REQUEST_REPLY, &DualModeController::ForwardToLm}, - {OpCode::USER_CONFIRMATION_REQUEST_REPLY, - &DualModeController::ForwardToLm}, - {OpCode::USER_CONFIRMATION_REQUEST_NEGATIVE_REPLY, - &DualModeController::ForwardToLm}, - {OpCode::USER_PASSKEY_REQUEST_REPLY, &DualModeController::ForwardToLm}, - {OpCode::USER_PASSKEY_REQUEST_NEGATIVE_REPLY, - &DualModeController::ForwardToLm}, - {OpCode::REMOTE_OOB_DATA_REQUEST_REPLY, - &DualModeController::ForwardToLm}, - {OpCode::REMOTE_OOB_DATA_REQUEST_NEGATIVE_REPLY, - &DualModeController::ForwardToLm}, - {OpCode::IO_CAPABILITY_REQUEST_NEGATIVE_REPLY, - &DualModeController::ForwardToLm}, - {OpCode::ENHANCED_SETUP_SYNCHRONOUS_CONNECTION, - &DualModeController::EnhancedSetupSynchronousConnection}, - {OpCode::ENHANCED_ACCEPT_SYNCHRONOUS_CONNECTION, - &DualModeController::EnhancedAcceptSynchronousConnection}, - //{OpCode::TRUNCATED_PAGE, &DualModeController::TruncatedPage}, - //{OpCode::TRUNCATED_PAGE_CANCEL, - //&DualModeController::TruncatedPageCancel}, - //{OpCode::SET_CONNECTIONLESS_PERIPHERAL_BROADCAST, - //&DualModeController::SetConnectionlessPeripheralBroadcast}, - //{OpCode::SET_CONNECTIONLESS_PERIPHERAL_BROADCAST_RECEIVE, - //&DualModeController::SetConnectionlessPeripheralBroadcastReceive}, - //{OpCode::START_SYNCHRONIZATION_TRAIN, - //&DualModeController::StartSynchronizationTrain}, - //{OpCode::RECEIVE_SYNCHRONIZATION_TRAIN, - //&DualModeController::ReceiveSynchronizationTrain}, - {OpCode::REMOTE_OOB_EXTENDED_DATA_REQUEST_REPLY, - &DualModeController::ForwardToLm}, - - // LINK_POLICY - {OpCode::HOLD_MODE, &DualModeController::HoldMode}, - {OpCode::SNIFF_MODE, &DualModeController::SniffMode}, - {OpCode::EXIT_SNIFF_MODE, &DualModeController::ExitSniffMode}, - {OpCode::QOS_SETUP, &DualModeController::QosSetup}, - {OpCode::ROLE_DISCOVERY, &DualModeController::RoleDiscovery}, - {OpCode::SWITCH_ROLE, &DualModeController::SwitchRole}, - {OpCode::READ_LINK_POLICY_SETTINGS, - &DualModeController::ReadLinkPolicySettings}, - {OpCode::WRITE_LINK_POLICY_SETTINGS, - &DualModeController::WriteLinkPolicySettings}, - {OpCode::READ_DEFAULT_LINK_POLICY_SETTINGS, - &DualModeController::ReadDefaultLinkPolicySettings}, - {OpCode::WRITE_DEFAULT_LINK_POLICY_SETTINGS, - &DualModeController::WriteDefaultLinkPolicySettings}, - {OpCode::FLOW_SPECIFICATION, &DualModeController::FlowSpecification}, - {OpCode::SNIFF_SUBRATING, &DualModeController::SniffSubrating}, - - // CONTROLLER_AND_BASEBAND - {OpCode::SET_EVENT_MASK, &DualModeController::SetEventMask}, - {OpCode::RESET, &DualModeController::Reset}, - {OpCode::SET_EVENT_FILTER, &DualModeController::SetEventFilter}, - //{OpCode::FLUSH, &DualModeController::Flush}, - //{OpCode::READ_PIN_TYPE, &DualModeController::ReadPinType}, - //{OpCode::WRITE_PIN_TYPE, &DualModeController::WritePinType}, - //{OpCode::READ_STORED_LINK_KEY, - //&DualModeController::ReadStoredLinkKey}, - //{OpCode::WRITE_STORED_LINK_KEY, - //&DualModeController::WriteStoredLinkKey}, - {OpCode::DELETE_STORED_LINK_KEY, - &DualModeController::DeleteStoredLinkKey}, - {OpCode::WRITE_LOCAL_NAME, &DualModeController::WriteLocalName}, - {OpCode::READ_LOCAL_NAME, &DualModeController::ReadLocalName}, - {OpCode::READ_CONNECTION_ACCEPT_TIMEOUT, - &DualModeController::ReadConnectionAcceptTimeout}, - {OpCode::WRITE_CONNECTION_ACCEPT_TIMEOUT, - &DualModeController::WriteConnectionAcceptTimeout}, - {OpCode::READ_PAGE_TIMEOUT, &DualModeController::ReadPageTimeout}, - {OpCode::WRITE_PAGE_TIMEOUT, &DualModeController::WritePageTimeout}, - {OpCode::READ_SCAN_ENABLE, &DualModeController::ReadScanEnable}, - {OpCode::WRITE_SCAN_ENABLE, &DualModeController::WriteScanEnable}, - {OpCode::READ_PAGE_SCAN_ACTIVITY, - &DualModeController::ReadPageScanActivity}, - {OpCode::WRITE_PAGE_SCAN_ACTIVITY, - &DualModeController::WritePageScanActivity}, - {OpCode::READ_INQUIRY_SCAN_ACTIVITY, - &DualModeController::ReadInquiryScanActivity}, - {OpCode::WRITE_INQUIRY_SCAN_ACTIVITY, - &DualModeController::WriteInquiryScanActivity}, - {OpCode::READ_AUTHENTICATION_ENABLE, - &DualModeController::ReadAuthenticationEnable}, - {OpCode::WRITE_AUTHENTICATION_ENABLE, - &DualModeController::WriteAuthenticationEnable}, - {OpCode::READ_CLASS_OF_DEVICE, &DualModeController::ReadClassOfDevice}, - {OpCode::WRITE_CLASS_OF_DEVICE, - &DualModeController::WriteClassOfDevice}, - {OpCode::READ_VOICE_SETTING, &DualModeController::ReadVoiceSetting}, - {OpCode::WRITE_VOICE_SETTING, &DualModeController::WriteVoiceSetting}, - //{OpCode::READ_AUTOMATIC_FLUSH_TIMEOUT, - //&DualModeController::ReadAutomaticFlushTimeout}, - //{OpCode::WRITE_AUTOMATIC_FLUSH_TIMEOUT, - //&DualModeController::WriteAutomaticFlushTimeout}, - //{OpCode::READ_NUM_BROADCAST_RETRANSMITS, - //&DualModeController::ReadNumBroadcastRetransmits}, - //{OpCode::WRITE_NUM_BROADCAST_RETRANSMITS, - //&DualModeController::WriteNumBroadcastRetransmits}, - //{OpCode::READ_HOLD_MODE_ACTIVITY, - //&DualModeController::ReadHoldModeActivity}, - //{OpCode::WRITE_HOLD_MODE_ACTIVITY, - //&DualModeController::WriteHoldModeActivity}, - {OpCode::READ_TRANSMIT_POWER_LEVEL, - &DualModeController::ReadTransmitPowerLevel}, - {OpCode::READ_SYNCHRONOUS_FLOW_CONTROL_ENABLE, - &DualModeController::ReadSynchronousFlowControlEnable}, - {OpCode::WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE, - &DualModeController::WriteSynchronousFlowControlEnable}, - //{OpCode::SET_CONTROLLER_TO_HOST_FLOW_CONTROL, - //&DualModeController::SetControllerToHostFlowControl}, - {OpCode::HOST_BUFFER_SIZE, &DualModeController::HostBufferSize}, - //{OpCode::HOST_NUMBER_OF_COMPLETED_PACKETS, - //&DualModeController::HostNumberOfCompletedPackets}, - //{OpCode::READ_LINK_SUPERVISION_TIMEOUT, - //&DualModeController::ReadLinkSupervisionTimeout}, - {OpCode::WRITE_LINK_SUPERVISION_TIMEOUT, - &DualModeController::WriteLinkSupervisionTimeout}, - {OpCode::READ_NUMBER_OF_SUPPORTED_IAC, - &DualModeController::ReadNumberOfSupportedIac}, - {OpCode::READ_CURRENT_IAC_LAP, &DualModeController::ReadCurrentIacLap}, - {OpCode::WRITE_CURRENT_IAC_LAP, - &DualModeController::WriteCurrentIacLap}, - //{OpCode::SET_AFH_HOST_CHANNEL_CLASSIFICATION, - //&DualModeController::SetAfhHostChannelClassification}, - {OpCode::READ_INQUIRY_SCAN_TYPE, - &DualModeController::ReadInquiryScanType}, - {OpCode::WRITE_INQUIRY_SCAN_TYPE, - &DualModeController::WriteInquiryScanType}, - {OpCode::READ_INQUIRY_MODE, &DualModeController::ReadInquiryMode}, - {OpCode::WRITE_INQUIRY_MODE, &DualModeController::WriteInquiryMode}, - {OpCode::READ_PAGE_SCAN_TYPE, &DualModeController::ReadPageScanType}, - {OpCode::WRITE_PAGE_SCAN_TYPE, &DualModeController::WritePageScanType}, - //{OpCode::READ_AFH_CHANNEL_ASSESSMENT_MODE, - //&DualModeController::ReadAfhChannelAssessmentMode}, - //{OpCode::WRITE_AFH_CHANNEL_ASSESSMENT_MODE, - //&DualModeController::WriteAfhChannelAssessmentMode}, - //{OpCode::READ_EXTENDED_INQUIRY_RESPONSE, - //&DualModeController::ReadExtendedInquiryResponse}, - {OpCode::WRITE_EXTENDED_INQUIRY_RESPONSE, - &DualModeController::WriteExtendedInquiryResponse}, - {OpCode::REFRESH_ENCRYPTION_KEY, - &DualModeController::RefreshEncryptionKey}, - //{OpCode::READ_SIMPLE_PAIRING_MODE, - //&DualModeController::ReadSimplePairingMode}, - {OpCode::WRITE_SIMPLE_PAIRING_MODE, - &DualModeController::WriteSimplePairingMode}, - {OpCode::READ_LOCAL_OOB_DATA, &DualModeController::ReadLocalOobData}, - {OpCode::READ_INQUIRY_RESPONSE_TRANSMIT_POWER_LEVEL, - &DualModeController::ReadInquiryResponseTransmitPowerLevel}, - //{OpCode::WRITE_INQUIRY_TRANSMIT_POWER_LEVEL, - //&DualModeController::WriteInquiryTransmitPowerLevel}, - //{OpCode::READ_DEFAULT_ERRONEOUS_DATA_REPORTING, - //&DualModeController::ReadDefaultErroneousDataReporting}, - //{OpCode::WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING, - //&DualModeController::WriteDefaultErroneousDataReporting}, - {OpCode::ENHANCED_FLUSH, &DualModeController::EnhancedFlush}, - {OpCode::SEND_KEYPRESS_NOTIFICATION, &DualModeController::ForwardToLm}, - {OpCode::SET_EVENT_MASK_PAGE_2, &DualModeController::SetEventMaskPage2}, - //{OpCode::READ_FLOW_CONTROL_MODE, - //&DualModeController::ReadFlowControlMode}, - //{OpCode::WRITE_FLOW_CONTROL_MODE, - //&DualModeController::WriteFlowControlMode}, - {OpCode::READ_ENHANCED_TRANSMIT_POWER_LEVEL, - &DualModeController::ReadEnhancedTransmitPowerLevel}, - //{OpCode::READ_LE_HOST_SUPPORT, - //&DualModeController::ReadLeHostSupport}, - {OpCode::WRITE_LE_HOST_SUPPORT, - &DualModeController::WriteLeHostSupport}, - //{OpCode::SET_MWS_CHANNEL_PARAMETERS, - //&DualModeController::SetMwsChannelParameters}, - //{OpCode::SET_EXTERNAL_FRAME_CONFIGURATION, - //&DualModeController::SetExternalFrameConfiguration}, - //{OpCode::SET_MWS_SIGNALING, &DualModeController::SetMwsSignaling}, - //{OpCode::SET_MWS_TRANSPORT_LAYER, - //&DualModeController::SetMwsTransportLayer}, - //{OpCode::SET_MWS_SCAN_FREQUENCY_TABLE, - //&DualModeController::SetMwsScanFrequencyTable}, - //{OpCode::SET_MWS_PATTERN_CONFIGURATION, - //&DualModeController::SetMwsPatternConfiguration}, - //{OpCode::SET_RESERVED_LT_ADDR, - //&DualModeController::SetReservedLtAddr}, - //{OpCode::DELETE_RESERVED_LT_ADDR, - //&DualModeController::DeleteReservedLtAddr}, - //{OpCode::SET_CONNECTIONLESS_PERIPHERAL_BROADCAST_DATA, - //&DualModeController::SetConnectionlessPeripheralBroadcastData}, - //{OpCode::READ_SYNCHRONIZATION_TRAIN_PARAMETERS, - //&DualModeController::ReadSynchronizationTrainParameters}, - //{OpCode::WRITE_SYNCHRONIZATION_TRAIN_PARAMETERS, - //&DualModeController::WriteSynchronizationTrainParameters}, - //{OpCode::READ_SECURE_CONNECTIONS_HOST_SUPPORT, - //&DualModeController::ReadSecureConnectionsHostSupport}, - {OpCode::WRITE_SECURE_CONNECTIONS_HOST_SUPPORT, - &DualModeController::WriteSecureConnectionsHostSupport}, - //{OpCode::READ_AUTHENTICATED_PAYLOAD_TIMEOUT, - //&DualModeController::ReadAuthenticatedPayloadTimeout}, - //{OpCode::WRITE_AUTHENTICATED_PAYLOAD_TIMEOUT, - //&DualModeController::WriteAuthenticatedPayloadTimeout}, - {OpCode::READ_LOCAL_OOB_EXTENDED_DATA, - &DualModeController::ReadLocalOobExtendedData}, - //{OpCode::READ_EXTENDED_PAGE_TIMEOUT, - //&DualModeController::ReadExtendedPageTimeout}, - //{OpCode::WRITE_EXTENDED_PAGE_TIMEOUT, - //&DualModeController::WriteExtendedPageTimeout}, - //{OpCode::READ_EXTENDED_INQUIRY_LENGTH, - //&DualModeController::ReadExtendedInquiryLength}, - //{OpCode::WRITE_EXTENDED_INQUIRY_LENGTH, - //&DualModeController::WriteExtendedInquiryLength}, - //{OpCode::SET_ECOSYSTEM_BASE_INTERVAL, - //&DualModeController::SetEcosystemBaseInterval}, - //{OpCode::CONFIGURE_DATA_PATH, &DualModeController::ConfigureDataPath}, - //{OpCode::SET_MIN_ENCRYPTION_KEY_SIZE, - //&DualModeController::SetMinEncryptionKeySize}, - - // INFORMATIONAL_PARAMETERS - {OpCode::READ_LOCAL_VERSION_INFORMATION, - &DualModeController::ReadLocalVersionInformation}, - {OpCode::READ_LOCAL_SUPPORTED_COMMANDS, - &DualModeController::ReadLocalSupportedCommands}, - {OpCode::READ_LOCAL_SUPPORTED_FEATURES, - &DualModeController::ReadLocalSupportedFeatures}, - {OpCode::READ_LOCAL_EXTENDED_FEATURES, - &DualModeController::ReadLocalExtendedFeatures}, - {OpCode::READ_BUFFER_SIZE, &DualModeController::ReadBufferSize}, - {OpCode::READ_BD_ADDR, &DualModeController::ReadBdAddr}, - //{OpCode::READ_DATA_BLOCK_SIZE, - //&DualModeController::ReadDataBlockSize}, - {OpCode::READ_LOCAL_SUPPORTED_CODECS_V1, - &DualModeController::ReadLocalSupportedCodecsV1}, - //{OpCode::READ_LOCAL_SIMPLE_PAIRING_OPTIONS, - //&DualModeController::ReadLocalSimplePairingOptions}, - //{OpCode::READ_LOCAL_SUPPORTED_CODECS_V2, - //&DualModeController::ReadLocalSupportedCodecsV2}, - //{OpCode::READ_LOCAL_SUPPORTED_CODEC_CAPABILITIES, - //&DualModeController::ReadLocalSupportedCodecCapabilities}, - //{OpCode::READ_LOCAL_SUPPORTED_CONTROLLER_DELAY, - //&DualModeController::ReadLocalSupportedControllerDelay}, - - // STATUS_PARAMETERS - {OpCode::READ_FAILED_CONTACT_COUNTER, - &DualModeController::ReadFailedContactCounter}, - {OpCode::RESET_FAILED_CONTACT_COUNTER, - &DualModeController::ResetFailedContactCounter}, - //{OpCode::READ_LINK_QUALITY, &DualModeController::ReadLinkQuality}, - {OpCode::READ_RSSI, &DualModeController::ReadRssi}, - //{OpCode::READ_AFH_CHANNEL_MAP, - //&DualModeController::ReadAfhChannelMap}, - //{OpCode::READ_CLOCK, &DualModeController::ReadClock}, - {OpCode::READ_ENCRYPTION_KEY_SIZE, - &DualModeController::ReadEncryptionKeySize}, - //{OpCode::GET_MWS_TRANSPORT_LAYER_CONFIGURATION, - //&DualModeController::GetMwsTransportLayerConfiguration}, - //{OpCode::SET_TRIGGERED_CLOCK_CAPTURE, - //&DualModeController::SetTriggeredClockCapture}, - - // TESTING - {OpCode::READ_LOOPBACK_MODE, &DualModeController::ReadLoopbackMode}, - {OpCode::WRITE_LOOPBACK_MODE, &DualModeController::WriteLoopbackMode}, - //{OpCode::ENABLE_DEVICE_UNDER_TEST_MODE, - //&DualModeController::EnableDeviceUnderTestMode}, - //{OpCode::WRITE_SIMPLE_PAIRING_DEBUG_MODE, - //&DualModeController::WriteSimplePairingDebugMode}, - //{OpCode::WRITE_SECURE_CONNECTIONS_TEST_MODE, - //&DualModeController::WriteSecureConnectionsTestMode}, - - // LE_CONTROLLER - {OpCode::LE_SET_EVENT_MASK, &DualModeController::LeSetEventMask}, - {OpCode::LE_READ_BUFFER_SIZE_V1, - &DualModeController::LeReadBufferSizeV1}, - {OpCode::LE_READ_LOCAL_SUPPORTED_FEATURES, - &DualModeController::LeReadLocalSupportedFeatures}, - {OpCode::LE_SET_RANDOM_ADDRESS, - &DualModeController::LeSetRandomAddress}, - {OpCode::LE_SET_ADVERTISING_PARAMETERS, - &DualModeController::LeSetAdvertisingParameters}, - {OpCode::LE_READ_ADVERTISING_PHYSICAL_CHANNEL_TX_POWER, - &DualModeController::LeReadAdvertisingPhysicalChannelTxPower}, - {OpCode::LE_SET_ADVERTISING_DATA, - &DualModeController::LeSetAdvertisingData}, - {OpCode::LE_SET_SCAN_RESPONSE_DATA, - &DualModeController::LeSetScanResponseData}, - {OpCode::LE_SET_ADVERTISING_ENABLE, - &DualModeController::LeSetAdvertisingEnable}, - {OpCode::LE_SET_SCAN_PARAMETERS, - &DualModeController::LeSetScanParameters}, - {OpCode::LE_SET_SCAN_ENABLE, &DualModeController::LeSetScanEnable}, - {OpCode::LE_CREATE_CONNECTION, &DualModeController::LeCreateConnection}, - {OpCode::LE_CREATE_CONNECTION_CANCEL, - &DualModeController::LeCreateConnectionCancel}, - {OpCode::LE_READ_FILTER_ACCEPT_LIST_SIZE, - &DualModeController::LeReadFilterAcceptListSize}, - {OpCode::LE_CLEAR_FILTER_ACCEPT_LIST, - &DualModeController::LeClearFilterAcceptList}, - {OpCode::LE_ADD_DEVICE_TO_FILTER_ACCEPT_LIST, - &DualModeController::LeAddDeviceToFilterAcceptList}, - {OpCode::LE_REMOVE_DEVICE_FROM_FILTER_ACCEPT_LIST, - &DualModeController::LeRemoveDeviceFromFilterAcceptList}, - {OpCode::LE_CONNECTION_UPDATE, &DualModeController::LeConnectionUpdate}, - //{OpCode::LE_SET_HOST_CHANNEL_CLASSIFICATION, - //&DualModeController::LeSetHostChannelClassification}, - //{OpCode::LE_READ_CHANNEL_MAP, &DualModeController::LeReadChannelMap}, - {OpCode::LE_READ_REMOTE_FEATURES, - &DualModeController::LeReadRemoteFeatures}, - {OpCode::LE_ENCRYPT, &DualModeController::LeEncrypt}, - {OpCode::LE_RAND, &DualModeController::LeRand}, - {OpCode::LE_START_ENCRYPTION, &DualModeController::LeStartEncryption}, - {OpCode::LE_LONG_TERM_KEY_REQUEST_REPLY, - &DualModeController::LeLongTermKeyRequestReply}, - {OpCode::LE_LONG_TERM_KEY_REQUEST_NEGATIVE_REPLY, - &DualModeController::LeLongTermKeyRequestNegativeReply}, - {OpCode::LE_READ_SUPPORTED_STATES, - &DualModeController::LeReadSupportedStates}, - //{OpCode::LE_RECEIVER_TEST_V1, &DualModeController::LeReceiverTestV1}, - //{OpCode::LE_TRANSMITTER_TEST_V1, - //&DualModeController::LeTransmitterTestV1}, - //{OpCode::LE_TEST_END, &DualModeController::LeTestEnd}, - {OpCode::LE_REMOTE_CONNECTION_PARAMETER_REQUEST_REPLY, - &DualModeController::LeRemoteConnectionParameterRequestReply}, - {OpCode::LE_REMOTE_CONNECTION_PARAMETER_REQUEST_NEGATIVE_REPLY, - &DualModeController::LeRemoteConnectionParameterRequestNegativeReply}, - //{OpCode::LE_SET_DATA_LENGTH, &DualModeController::LeSetDataLength}, - {OpCode::LE_READ_SUGGESTED_DEFAULT_DATA_LENGTH, - &DualModeController::LeReadSuggestedDefaultDataLength}, - {OpCode::LE_WRITE_SUGGESTED_DEFAULT_DATA_LENGTH, - &DualModeController::LeWriteSuggestedDefaultDataLength}, - //{OpCode::LE_READ_LOCAL_P_256_PUBLIC_KEY, - //&DualModeController::LeReadLocalP256PublicKey}, - //{OpCode::LE_GENERATE_DHKEY_V1, - //&DualModeController::LeGenerateDhkeyV1}, - {OpCode::LE_ADD_DEVICE_TO_RESOLVING_LIST, - &DualModeController::LeAddDeviceToResolvingList}, - {OpCode::LE_REMOVE_DEVICE_FROM_RESOLVING_LIST, - &DualModeController::LeRemoveDeviceFromResolvingList}, - {OpCode::LE_CLEAR_RESOLVING_LIST, - &DualModeController::LeClearResolvingList}, - {OpCode::LE_READ_RESOLVING_LIST_SIZE, - &DualModeController::LeReadResolvingListSize}, - {OpCode::LE_READ_PEER_RESOLVABLE_ADDRESS, - &DualModeController::LeReadPeerResolvableAddress}, - {OpCode::LE_READ_LOCAL_RESOLVABLE_ADDRESS, - &DualModeController::LeReadLocalResolvableAddress}, - {OpCode::LE_SET_ADDRESS_RESOLUTION_ENABLE, - &DualModeController::LeSetAddressResolutionEnable}, - {OpCode::LE_SET_RESOLVABLE_PRIVATE_ADDRESS_TIMEOUT, - &DualModeController::LeSetResolvablePrivateAddressTimeout}, - {OpCode::LE_READ_MAXIMUM_DATA_LENGTH, - &DualModeController::LeReadMaximumDataLength}, - {OpCode::LE_READ_PHY, &DualModeController::LeReadPhy}, - {OpCode::LE_SET_DEFAULT_PHY, &DualModeController::LeSetDefaultPhy}, - {OpCode::LE_SET_PHY, &DualModeController::LeSetPhy}, - //{OpCode::LE_RECEIVER_TEST_V2, &DualModeController::LeReceiverTestV2}, - //{OpCode::LE_TRANSMITTER_TEST_V2, - //&DualModeController::LeTransmitterTestV2}, - {OpCode::LE_SET_ADVERTISING_SET_RANDOM_ADDRESS, - &DualModeController::LeSetAdvertisingSetRandomAddress}, - {OpCode::LE_SET_EXTENDED_ADVERTISING_PARAMETERS, - &DualModeController::LeSetExtendedAdvertisingParameters}, - {OpCode::LE_SET_EXTENDED_ADVERTISING_DATA, - &DualModeController::LeSetExtendedAdvertisingData}, - {OpCode::LE_SET_EXTENDED_SCAN_RESPONSE_DATA, - &DualModeController::LeSetExtendedScanResponseData}, - {OpCode::LE_SET_EXTENDED_ADVERTISING_ENABLE, - &DualModeController::LeSetExtendedAdvertisingEnable}, - {OpCode::LE_READ_MAXIMUM_ADVERTISING_DATA_LENGTH, - &DualModeController::LeReadMaximumAdvertisingDataLength}, - {OpCode::LE_READ_NUMBER_OF_SUPPORTED_ADVERTISING_SETS, - &DualModeController::LeReadNumberOfSupportedAdvertisingSets}, - {OpCode::LE_REMOVE_ADVERTISING_SET, - &DualModeController::LeRemoveAdvertisingSet}, - {OpCode::LE_CLEAR_ADVERTISING_SETS, - &DualModeController::LeClearAdvertisingSets}, - {OpCode::LE_SET_PERIODIC_ADVERTISING_PARAMETERS, - &DualModeController::LeSetPeriodicAdvertisingParameters}, - {OpCode::LE_SET_PERIODIC_ADVERTISING_DATA, - &DualModeController::LeSetPeriodicAdvertisingData}, - {OpCode::LE_SET_PERIODIC_ADVERTISING_ENABLE, - &DualModeController::LeSetPeriodicAdvertisingEnable}, - {OpCode::LE_SET_EXTENDED_SCAN_PARAMETERS, - &DualModeController::LeSetExtendedScanParameters}, - {OpCode::LE_SET_EXTENDED_SCAN_ENABLE, - &DualModeController::LeSetExtendedScanEnable}, - {OpCode::LE_EXTENDED_CREATE_CONNECTION, - &DualModeController::LeExtendedCreateConnection}, - {OpCode::LE_PERIODIC_ADVERTISING_CREATE_SYNC, - &DualModeController::LePeriodicAdvertisingCreateSync}, - {OpCode::LE_PERIODIC_ADVERTISING_CREATE_SYNC_CANCEL, - &DualModeController::LePeriodicAdvertisingCreateSyncCancel}, - {OpCode::LE_PERIODIC_ADVERTISING_TERMINATE_SYNC, - &DualModeController::LePeriodicAdvertisingTerminateSync}, - {OpCode::LE_ADD_DEVICE_TO_PERIODIC_ADVERTISER_LIST, - &DualModeController::LeAddDeviceToPeriodicAdvertiserList}, - {OpCode::LE_REMOVE_DEVICE_FROM_PERIODIC_ADVERTISER_LIST, - &DualModeController::LeRemoveDeviceFromPeriodicAdvertiserList}, - {OpCode::LE_CLEAR_PERIODIC_ADVERTISER_LIST, - &DualModeController::LeClearPeriodicAdvertiserList}, - {OpCode::LE_READ_PERIODIC_ADVERTISER_LIST_SIZE, - &DualModeController::LeReadPeriodicAdvertiserListSize}, - //{OpCode::LE_READ_TRANSMIT_POWER, - //&DualModeController::LeReadTransmitPower}, - //{OpCode::LE_READ_RF_PATH_COMPENSATION_POWER, - //&DualModeController::LeReadRfPathCompensationPower}, - //{OpCode::LE_WRITE_RF_PATH_COMPENSATION_POWER, - //&DualModeController::LeWriteRfPathCompensationPower}, - {OpCode::LE_SET_PRIVACY_MODE, &DualModeController::LeSetPrivacyMode}, - //{OpCode::LE_RECEIVER_TEST_V3, &DualModeController::LeReceiverTestV3}, - //{OpCode::LE_TRANSMITTER_TEST_V3, - //&DualModeController::LeTransmitterTestV3}, - //{OpCode::LE_SET_CONNECTIONLESS_CTE_TRANSMIT_PARAMETERS, - //&DualModeController::LeSetConnectionlessCteTransmitParameters}, - //{OpCode::LE_SET_CONNECTIONLESS_CTE_TRANSMIT_ENABLE, - //&DualModeController::LeSetConnectionlessCteTransmitEnable}, - //{OpCode::LE_SET_CONNECTIONLESS_IQ_SAMPLING_ENABLE, - //&DualModeController::LeSetConnectionlessIqSamplingEnable}, - //{OpCode::LE_SET_CONNECTION_CTE_RECEIVE_PARAMETERS, - //&DualModeController::LeSetConnectionCteReceiveParameters}, - //{OpCode::LE_SET_CONNECTION_CTE_TRANSMIT_PARAMETERS, - //&DualModeController::LeSetConnectionCteTransmitParameters}, - //{OpCode::LE_CONNECTION_CTE_REQUEST_ENABLE, - //&DualModeController::LeConnectionCteRequestEnable}, - //{OpCode::LE_CONNECTION_CTE_RESPONSE_ENABLE, - //&DualModeController::LeConnectionCteResponseEnable}, - //{OpCode::LE_READ_ANTENNA_INFORMATION, - //&DualModeController::LeReadAntennaInformation}, - //{OpCode::LE_SET_PERIODIC_ADVERTISING_RECEIVE_ENABLE, - //&DualModeController::LeSetPeriodicAdvertisingReceiveEnable}, - //{OpCode::LE_PERIODIC_ADVERTISING_SYNC_TRANSFER, - //&DualModeController::LePeriodicAdvertisingSyncTransfer}, - //{OpCode::LE_PERIODIC_ADVERTISING_SET_INFO_TRANSFER, - //&DualModeController::LePeriodicAdvertisingSetInfoTransfer}, - //{OpCode::LE_SET_PERIODIC_ADVERTISING_SYNC_TRANSFER_PARAMETERS, - //&DualModeController::LeSetPeriodicAdvertisingSyncTransferParameters}, - //{OpCode::LE_SET_DEFAULT_PERIODIC_ADVERTISING_SYNC_TRANSFER_PARAMETERS, - //&DualModeController::LeSetDefaultPeriodicAdvertisingSyncTransferParameters}, - //{OpCode::LE_GENERATE_DHKEY_V2, - //&DualModeController::LeGenerateDhkeyV2}, - //{OpCode::LE_MODIFY_SLEEP_CLOCK_ACCURACY, - //&DualModeController::LeModifySleepClockAccuracy}, - {OpCode::LE_READ_BUFFER_SIZE_V2, - &DualModeController::LeReadBufferSizeV2}, - //{OpCode::LE_READ_ISO_TX_SYNC, &DualModeController::LeReadIsoTxSync}, - {OpCode::LE_SET_CIG_PARAMETERS, &DualModeController::ForwardToLl}, - {OpCode::LE_SET_CIG_PARAMETERS_TEST, &DualModeController::ForwardToLl}, - {OpCode::LE_CREATE_CIS, &DualModeController::ForwardToLl}, - {OpCode::LE_REMOVE_CIG, &DualModeController::ForwardToLl}, - {OpCode::LE_ACCEPT_CIS_REQUEST, &DualModeController::ForwardToLl}, - {OpCode::LE_REJECT_CIS_REQUEST, &DualModeController::ForwardToLl}, - //{OpCode::LE_CREATE_BIG, &DualModeController::LeCreateBig}, - //{OpCode::LE_CREATE_BIG_TEST, &DualModeController::LeCreateBigTest}, - //{OpCode::LE_TERMINATE_BIG, &DualModeController::LeTerminateBig}, - //{OpCode::LE_BIG_CREATE_SYNC, &DualModeController::LeBigCreateSync}, - //{OpCode::LE_BIG_TERMINATE_SYNC, - //&DualModeController::LeBigTerminateSync}, - {OpCode::LE_REQUEST_PEER_SCA, &DualModeController::LeRequestPeerSca}, - {OpCode::LE_SETUP_ISO_DATA_PATH, &DualModeController::ForwardToLl}, - {OpCode::LE_REMOVE_ISO_DATA_PATH, &DualModeController::ForwardToLl}, - //{OpCode::LE_ISO_TRANSMIT_TEST, - //&DualModeController::LeIsoTransmitTest}, - //{OpCode::LE_ISO_RECEIVE_TEST, &DualModeController::LeIsoReceiveTest}, - //{OpCode::LE_ISO_READ_TEST_COUNTERS, - //&DualModeController::LeIsoReadTestCounters}, - //{OpCode::LE_ISO_TEST_END, &DualModeController::LeIsoTestEnd}, - {OpCode::LE_SET_HOST_FEATURE, &DualModeController::LeSetHostFeature}, - //{OpCode::LE_READ_ISO_LINK_QUALITY, - //&DualModeController::LeReadIsoLinkQuality}, - //{OpCode::LE_ENHANCED_READ_TRANSMIT_POWER_LEVEL, - //&DualModeController::LeEnhancedReadTransmitPowerLevel}, - //{OpCode::LE_READ_REMOTE_TRANSMIT_POWER_LEVEL, - //&DualModeController::LeReadRemoteTransmitPowerLevel}, - //{OpCode::LE_SET_PATH_LOSS_REPORTING_PARAMETERS, - //&DualModeController::LeSetPathLossReportingParameters}, - //{OpCode::LE_SET_PATH_LOSS_REPORTING_ENABLE, - //&DualModeController::LeSetPathLossReportingEnable}, - //{OpCode::LE_SET_TRANSMIT_POWER_REPORTING_ENABLE, - //&DualModeController::LeSetTransmitPowerReportingEnable}, - //{OpCode::LE_TRANSMITTER_TEST_V4, - //&DualModeController::LeTransmitterTestV4}, - //{OpCode::LE_SET_DATA_RELATED_ADDRESS_CHANGES, - //&DualModeController::LeSetDataRelatedAddressChanges}, - //{OpCode::LE_SET_DEFAULT_SUBRATE, - //&DualModeController::LeSetDefaultSubrate}, - //{OpCode::LE_SUBRATE_REQUEST, &DualModeController::LeSubrateRequest}, - - // VENDOR - {OpCode(CSR_VENDOR), &DualModeController::CsrVendorCommand}, - {OpCode::LE_GET_VENDOR_CAPABILITIES, - &DualModeController::LeGetVendorCapabilities}, - {OpCode::LE_BATCH_SCAN, &DualModeController::LeBatchScan}, - {OpCode::LE_APCF, &DualModeController::LeApcf}, - {OpCode::LE_GET_CONTROLLER_ACTIVITY_ENERGY_INFO, - &DualModeController::LeGetControllerActivityEnergyInfo}, - {OpCode::LE_EX_SET_SCAN_PARAMETERS, - &DualModeController::LeExSetScanParameters}, - {OpCode::GET_CONTROLLER_DEBUG_INFO, - &DualModeController::GetControllerDebugInfo}}; + DualModeController::hci_command_handlers_{ + // LINK_CONTROL + {OpCode::INQUIRY, &DualModeController::Inquiry}, + {OpCode::INQUIRY_CANCEL, &DualModeController::InquiryCancel}, + //{OpCode::PERIODIC_INQUIRY_MODE, + //&DualModeController::PeriodicInquiryMode}, + //{OpCode::EXIT_PERIODIC_INQUIRY_MODE, + //&DualModeController::ExitPeriodicInquiryMode}, + {OpCode::CREATE_CONNECTION, &DualModeController::CreateConnection}, + {OpCode::DISCONNECT, &DualModeController::Disconnect}, + {OpCode::ADD_SCO_CONNECTION, &DualModeController::AddScoConnection}, + {OpCode::CREATE_CONNECTION_CANCEL, &DualModeController::CreateConnectionCancel}, + {OpCode::ACCEPT_CONNECTION_REQUEST, &DualModeController::AcceptConnectionRequest}, + {OpCode::REJECT_CONNECTION_REQUEST, &DualModeController::RejectConnectionRequest}, + {OpCode::LINK_KEY_REQUEST_REPLY, &DualModeController::ForwardToLm}, + {OpCode::LINK_KEY_REQUEST_NEGATIVE_REPLY, &DualModeController::ForwardToLm}, + {OpCode::PIN_CODE_REQUEST_REPLY, &DualModeController::ForwardToLm}, + {OpCode::PIN_CODE_REQUEST_NEGATIVE_REPLY, &DualModeController::ForwardToLm}, + {OpCode::CHANGE_CONNECTION_PACKET_TYPE, + &DualModeController::ChangeConnectionPacketType}, + {OpCode::AUTHENTICATION_REQUESTED, &DualModeController::ForwardToLm}, + {OpCode::SET_CONNECTION_ENCRYPTION, &DualModeController::ForwardToLm}, + {OpCode::CHANGE_CONNECTION_LINK_KEY, &DualModeController::ChangeConnectionLinkKey}, + {OpCode::CENTRAL_LINK_KEY, &DualModeController::CentralLinkKey}, + {OpCode::REMOTE_NAME_REQUEST, &DualModeController::RemoteNameRequest}, + //{OpCode::REMOTE_NAME_REQUEST_CANCEL, + //&DualModeController::RemoteNameRequestCancel}, + {OpCode::READ_REMOTE_SUPPORTED_FEATURES, + &DualModeController::ReadRemoteSupportedFeatures}, + {OpCode::READ_REMOTE_EXTENDED_FEATURES, + &DualModeController::ReadRemoteExtendedFeatures}, + {OpCode::READ_REMOTE_VERSION_INFORMATION, + &DualModeController::ReadRemoteVersionInformation}, + {OpCode::READ_CLOCK_OFFSET, &DualModeController::ReadClockOffset}, + //{OpCode::READ_LMP_HANDLE, &DualModeController::ReadLmpHandle}, + {OpCode::SETUP_SYNCHRONOUS_CONNECTION, + &DualModeController::SetupSynchronousConnection}, + {OpCode::ACCEPT_SYNCHRONOUS_CONNECTION, + &DualModeController::AcceptSynchronousConnection}, + {OpCode::REJECT_SYNCHRONOUS_CONNECTION, + &DualModeController::RejectSynchronousConnection}, + {OpCode::IO_CAPABILITY_REQUEST_REPLY, &DualModeController::ForwardToLm}, + {OpCode::USER_CONFIRMATION_REQUEST_REPLY, &DualModeController::ForwardToLm}, + {OpCode::USER_CONFIRMATION_REQUEST_NEGATIVE_REPLY, + &DualModeController::ForwardToLm}, + {OpCode::USER_PASSKEY_REQUEST_REPLY, &DualModeController::ForwardToLm}, + {OpCode::USER_PASSKEY_REQUEST_NEGATIVE_REPLY, &DualModeController::ForwardToLm}, + {OpCode::REMOTE_OOB_DATA_REQUEST_REPLY, &DualModeController::ForwardToLm}, + {OpCode::REMOTE_OOB_DATA_REQUEST_NEGATIVE_REPLY, &DualModeController::ForwardToLm}, + {OpCode::IO_CAPABILITY_REQUEST_NEGATIVE_REPLY, &DualModeController::ForwardToLm}, + {OpCode::ENHANCED_SETUP_SYNCHRONOUS_CONNECTION, + &DualModeController::EnhancedSetupSynchronousConnection}, + {OpCode::ENHANCED_ACCEPT_SYNCHRONOUS_CONNECTION, + &DualModeController::EnhancedAcceptSynchronousConnection}, + //{OpCode::TRUNCATED_PAGE, &DualModeController::TruncatedPage}, + //{OpCode::TRUNCATED_PAGE_CANCEL, + //&DualModeController::TruncatedPageCancel}, + //{OpCode::SET_CONNECTIONLESS_PERIPHERAL_BROADCAST, + //&DualModeController::SetConnectionlessPeripheralBroadcast}, + //{OpCode::SET_CONNECTIONLESS_PERIPHERAL_BROADCAST_RECEIVE, + //&DualModeController::SetConnectionlessPeripheralBroadcastReceive}, + //{OpCode::START_SYNCHRONIZATION_TRAIN, + //&DualModeController::StartSynchronizationTrain}, + //{OpCode::RECEIVE_SYNCHRONIZATION_TRAIN, + //&DualModeController::ReceiveSynchronizationTrain}, + {OpCode::REMOTE_OOB_EXTENDED_DATA_REQUEST_REPLY, &DualModeController::ForwardToLm}, + + // LINK_POLICY + {OpCode::HOLD_MODE, &DualModeController::HoldMode}, + {OpCode::SNIFF_MODE, &DualModeController::SniffMode}, + {OpCode::EXIT_SNIFF_MODE, &DualModeController::ExitSniffMode}, + {OpCode::QOS_SETUP, &DualModeController::QosSetup}, + {OpCode::ROLE_DISCOVERY, &DualModeController::RoleDiscovery}, + {OpCode::SWITCH_ROLE, &DualModeController::SwitchRole}, + {OpCode::READ_LINK_POLICY_SETTINGS, &DualModeController::ReadLinkPolicySettings}, + {OpCode::WRITE_LINK_POLICY_SETTINGS, &DualModeController::WriteLinkPolicySettings}, + {OpCode::READ_DEFAULT_LINK_POLICY_SETTINGS, + &DualModeController::ReadDefaultLinkPolicySettings}, + {OpCode::WRITE_DEFAULT_LINK_POLICY_SETTINGS, + &DualModeController::WriteDefaultLinkPolicySettings}, + {OpCode::FLOW_SPECIFICATION, &DualModeController::FlowSpecification}, + {OpCode::SNIFF_SUBRATING, &DualModeController::SniffSubrating}, + + // CONTROLLER_AND_BASEBAND + {OpCode::SET_EVENT_MASK, &DualModeController::SetEventMask}, + {OpCode::RESET, &DualModeController::Reset}, + {OpCode::SET_EVENT_FILTER, &DualModeController::SetEventFilter}, + //{OpCode::FLUSH, &DualModeController::Flush}, + //{OpCode::READ_PIN_TYPE, &DualModeController::ReadPinType}, + //{OpCode::WRITE_PIN_TYPE, &DualModeController::WritePinType}, + //{OpCode::READ_STORED_LINK_KEY, + //&DualModeController::ReadStoredLinkKey}, + //{OpCode::WRITE_STORED_LINK_KEY, + //&DualModeController::WriteStoredLinkKey}, + {OpCode::DELETE_STORED_LINK_KEY, &DualModeController::DeleteStoredLinkKey}, + {OpCode::WRITE_LOCAL_NAME, &DualModeController::WriteLocalName}, + {OpCode::READ_LOCAL_NAME, &DualModeController::ReadLocalName}, + {OpCode::READ_CONNECTION_ACCEPT_TIMEOUT, + &DualModeController::ReadConnectionAcceptTimeout}, + {OpCode::WRITE_CONNECTION_ACCEPT_TIMEOUT, + &DualModeController::WriteConnectionAcceptTimeout}, + {OpCode::READ_PAGE_TIMEOUT, &DualModeController::ReadPageTimeout}, + {OpCode::WRITE_PAGE_TIMEOUT, &DualModeController::WritePageTimeout}, + {OpCode::READ_SCAN_ENABLE, &DualModeController::ReadScanEnable}, + {OpCode::WRITE_SCAN_ENABLE, &DualModeController::WriteScanEnable}, + {OpCode::READ_PAGE_SCAN_ACTIVITY, &DualModeController::ReadPageScanActivity}, + {OpCode::WRITE_PAGE_SCAN_ACTIVITY, &DualModeController::WritePageScanActivity}, + {OpCode::READ_INQUIRY_SCAN_ACTIVITY, &DualModeController::ReadInquiryScanActivity}, + {OpCode::WRITE_INQUIRY_SCAN_ACTIVITY, + &DualModeController::WriteInquiryScanActivity}, + {OpCode::READ_AUTHENTICATION_ENABLE, &DualModeController::ReadAuthenticationEnable}, + {OpCode::WRITE_AUTHENTICATION_ENABLE, + &DualModeController::WriteAuthenticationEnable}, + {OpCode::READ_CLASS_OF_DEVICE, &DualModeController::ReadClassOfDevice}, + {OpCode::WRITE_CLASS_OF_DEVICE, &DualModeController::WriteClassOfDevice}, + {OpCode::READ_VOICE_SETTING, &DualModeController::ReadVoiceSetting}, + {OpCode::WRITE_VOICE_SETTING, &DualModeController::WriteVoiceSetting}, + //{OpCode::READ_AUTOMATIC_FLUSH_TIMEOUT, + //&DualModeController::ReadAutomaticFlushTimeout}, + //{OpCode::WRITE_AUTOMATIC_FLUSH_TIMEOUT, + //&DualModeController::WriteAutomaticFlushTimeout}, + //{OpCode::READ_NUM_BROADCAST_RETRANSMITS, + //&DualModeController::ReadNumBroadcastRetransmits}, + //{OpCode::WRITE_NUM_BROADCAST_RETRANSMITS, + //&DualModeController::WriteNumBroadcastRetransmits}, + //{OpCode::READ_HOLD_MODE_ACTIVITY, + //&DualModeController::ReadHoldModeActivity}, + //{OpCode::WRITE_HOLD_MODE_ACTIVITY, + //&DualModeController::WriteHoldModeActivity}, + {OpCode::READ_TRANSMIT_POWER_LEVEL, &DualModeController::ReadTransmitPowerLevel}, + {OpCode::READ_SYNCHRONOUS_FLOW_CONTROL_ENABLE, + &DualModeController::ReadSynchronousFlowControlEnable}, + {OpCode::WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE, + &DualModeController::WriteSynchronousFlowControlEnable}, + //{OpCode::SET_CONTROLLER_TO_HOST_FLOW_CONTROL, + //&DualModeController::SetControllerToHostFlowControl}, + {OpCode::HOST_BUFFER_SIZE, &DualModeController::HostBufferSize}, + //{OpCode::HOST_NUMBER_OF_COMPLETED_PACKETS, + //&DualModeController::HostNumberOfCompletedPackets}, + //{OpCode::READ_LINK_SUPERVISION_TIMEOUT, + //&DualModeController::ReadLinkSupervisionTimeout}, + {OpCode::WRITE_LINK_SUPERVISION_TIMEOUT, + &DualModeController::WriteLinkSupervisionTimeout}, + {OpCode::READ_NUMBER_OF_SUPPORTED_IAC, + &DualModeController::ReadNumberOfSupportedIac}, + {OpCode::READ_CURRENT_IAC_LAP, &DualModeController::ReadCurrentIacLap}, + {OpCode::WRITE_CURRENT_IAC_LAP, &DualModeController::WriteCurrentIacLap}, + //{OpCode::SET_AFH_HOST_CHANNEL_CLASSIFICATION, + //&DualModeController::SetAfhHostChannelClassification}, + {OpCode::READ_INQUIRY_SCAN_TYPE, &DualModeController::ReadInquiryScanType}, + {OpCode::WRITE_INQUIRY_SCAN_TYPE, &DualModeController::WriteInquiryScanType}, + {OpCode::READ_INQUIRY_MODE, &DualModeController::ReadInquiryMode}, + {OpCode::WRITE_INQUIRY_MODE, &DualModeController::WriteInquiryMode}, + {OpCode::READ_PAGE_SCAN_TYPE, &DualModeController::ReadPageScanType}, + {OpCode::WRITE_PAGE_SCAN_TYPE, &DualModeController::WritePageScanType}, + //{OpCode::READ_AFH_CHANNEL_ASSESSMENT_MODE, + //&DualModeController::ReadAfhChannelAssessmentMode}, + //{OpCode::WRITE_AFH_CHANNEL_ASSESSMENT_MODE, + //&DualModeController::WriteAfhChannelAssessmentMode}, + //{OpCode::READ_EXTENDED_INQUIRY_RESPONSE, + //&DualModeController::ReadExtendedInquiryResponse}, + {OpCode::WRITE_EXTENDED_INQUIRY_RESPONSE, + &DualModeController::WriteExtendedInquiryResponse}, + {OpCode::REFRESH_ENCRYPTION_KEY, &DualModeController::RefreshEncryptionKey}, + //{OpCode::READ_SIMPLE_PAIRING_MODE, + //&DualModeController::ReadSimplePairingMode}, + {OpCode::WRITE_SIMPLE_PAIRING_MODE, &DualModeController::WriteSimplePairingMode}, + {OpCode::READ_LOCAL_OOB_DATA, &DualModeController::ReadLocalOobData}, + {OpCode::READ_INQUIRY_RESPONSE_TRANSMIT_POWER_LEVEL, + &DualModeController::ReadInquiryResponseTransmitPowerLevel}, + //{OpCode::WRITE_INQUIRY_TRANSMIT_POWER_LEVEL, + //&DualModeController::WriteInquiryTransmitPowerLevel}, + //{OpCode::READ_DEFAULT_ERRONEOUS_DATA_REPORTING, + //&DualModeController::ReadDefaultErroneousDataReporting}, + //{OpCode::WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING, + //&DualModeController::WriteDefaultErroneousDataReporting}, + {OpCode::ENHANCED_FLUSH, &DualModeController::EnhancedFlush}, + {OpCode::SEND_KEYPRESS_NOTIFICATION, &DualModeController::ForwardToLm}, + {OpCode::SET_EVENT_MASK_PAGE_2, &DualModeController::SetEventMaskPage2}, + //{OpCode::READ_FLOW_CONTROL_MODE, + //&DualModeController::ReadFlowControlMode}, + //{OpCode::WRITE_FLOW_CONTROL_MODE, + //&DualModeController::WriteFlowControlMode}, + {OpCode::READ_ENHANCED_TRANSMIT_POWER_LEVEL, + &DualModeController::ReadEnhancedTransmitPowerLevel}, + //{OpCode::READ_LE_HOST_SUPPORT, + //&DualModeController::ReadLeHostSupport}, + {OpCode::WRITE_LE_HOST_SUPPORT, &DualModeController::WriteLeHostSupport}, + //{OpCode::SET_MWS_CHANNEL_PARAMETERS, + //&DualModeController::SetMwsChannelParameters}, + //{OpCode::SET_EXTERNAL_FRAME_CONFIGURATION, + //&DualModeController::SetExternalFrameConfiguration}, + //{OpCode::SET_MWS_SIGNALING, &DualModeController::SetMwsSignaling}, + //{OpCode::SET_MWS_TRANSPORT_LAYER, + //&DualModeController::SetMwsTransportLayer}, + //{OpCode::SET_MWS_SCAN_FREQUENCY_TABLE, + //&DualModeController::SetMwsScanFrequencyTable}, + //{OpCode::SET_MWS_PATTERN_CONFIGURATION, + //&DualModeController::SetMwsPatternConfiguration}, + //{OpCode::SET_RESERVED_LT_ADDR, + //&DualModeController::SetReservedLtAddr}, + //{OpCode::DELETE_RESERVED_LT_ADDR, + //&DualModeController::DeleteReservedLtAddr}, + //{OpCode::SET_CONNECTIONLESS_PERIPHERAL_BROADCAST_DATA, + //&DualModeController::SetConnectionlessPeripheralBroadcastData}, + //{OpCode::READ_SYNCHRONIZATION_TRAIN_PARAMETERS, + //&DualModeController::ReadSynchronizationTrainParameters}, + //{OpCode::WRITE_SYNCHRONIZATION_TRAIN_PARAMETERS, + //&DualModeController::WriteSynchronizationTrainParameters}, + //{OpCode::READ_SECURE_CONNECTIONS_HOST_SUPPORT, + //&DualModeController::ReadSecureConnectionsHostSupport}, + {OpCode::WRITE_SECURE_CONNECTIONS_HOST_SUPPORT, + &DualModeController::WriteSecureConnectionsHostSupport}, + //{OpCode::READ_AUTHENTICATED_PAYLOAD_TIMEOUT, + //&DualModeController::ReadAuthenticatedPayloadTimeout}, + //{OpCode::WRITE_AUTHENTICATED_PAYLOAD_TIMEOUT, + //&DualModeController::WriteAuthenticatedPayloadTimeout}, + {OpCode::READ_LOCAL_OOB_EXTENDED_DATA, + &DualModeController::ReadLocalOobExtendedData}, + //{OpCode::READ_EXTENDED_PAGE_TIMEOUT, + //&DualModeController::ReadExtendedPageTimeout}, + //{OpCode::WRITE_EXTENDED_PAGE_TIMEOUT, + //&DualModeController::WriteExtendedPageTimeout}, + //{OpCode::READ_EXTENDED_INQUIRY_LENGTH, + //&DualModeController::ReadExtendedInquiryLength}, + //{OpCode::WRITE_EXTENDED_INQUIRY_LENGTH, + //&DualModeController::WriteExtendedInquiryLength}, + //{OpCode::SET_ECOSYSTEM_BASE_INTERVAL, + //&DualModeController::SetEcosystemBaseInterval}, + //{OpCode::CONFIGURE_DATA_PATH, &DualModeController::ConfigureDataPath}, + //{OpCode::SET_MIN_ENCRYPTION_KEY_SIZE, + //&DualModeController::SetMinEncryptionKeySize}, + + // INFORMATIONAL_PARAMETERS + {OpCode::READ_LOCAL_VERSION_INFORMATION, + &DualModeController::ReadLocalVersionInformation}, + {OpCode::READ_LOCAL_SUPPORTED_COMMANDS, + &DualModeController::ReadLocalSupportedCommands}, + {OpCode::READ_LOCAL_SUPPORTED_FEATURES, + &DualModeController::ReadLocalSupportedFeatures}, + {OpCode::READ_LOCAL_EXTENDED_FEATURES, + &DualModeController::ReadLocalExtendedFeatures}, + {OpCode::READ_BUFFER_SIZE, &DualModeController::ReadBufferSize}, + {OpCode::READ_BD_ADDR, &DualModeController::ReadBdAddr}, + //{OpCode::READ_DATA_BLOCK_SIZE, + //&DualModeController::ReadDataBlockSize}, + {OpCode::READ_LOCAL_SUPPORTED_CODECS_V1, + &DualModeController::ReadLocalSupportedCodecsV1}, + //{OpCode::READ_LOCAL_SIMPLE_PAIRING_OPTIONS, + //&DualModeController::ReadLocalSimplePairingOptions}, + //{OpCode::READ_LOCAL_SUPPORTED_CODECS_V2, + //&DualModeController::ReadLocalSupportedCodecsV2}, + //{OpCode::READ_LOCAL_SUPPORTED_CODEC_CAPABILITIES, + //&DualModeController::ReadLocalSupportedCodecCapabilities}, + //{OpCode::READ_LOCAL_SUPPORTED_CONTROLLER_DELAY, + //&DualModeController::ReadLocalSupportedControllerDelay}, + + // STATUS_PARAMETERS + {OpCode::READ_FAILED_CONTACT_COUNTER, + &DualModeController::ReadFailedContactCounter}, + {OpCode::RESET_FAILED_CONTACT_COUNTER, + &DualModeController::ResetFailedContactCounter}, + //{OpCode::READ_LINK_QUALITY, &DualModeController::ReadLinkQuality}, + {OpCode::READ_RSSI, &DualModeController::ReadRssi}, + //{OpCode::READ_AFH_CHANNEL_MAP, + //&DualModeController::ReadAfhChannelMap}, + //{OpCode::READ_CLOCK, &DualModeController::ReadClock}, + {OpCode::READ_ENCRYPTION_KEY_SIZE, &DualModeController::ReadEncryptionKeySize}, + //{OpCode::GET_MWS_TRANSPORT_LAYER_CONFIGURATION, + //&DualModeController::GetMwsTransportLayerConfiguration}, + //{OpCode::SET_TRIGGERED_CLOCK_CAPTURE, + //&DualModeController::SetTriggeredClockCapture}, + + // TESTING + {OpCode::READ_LOOPBACK_MODE, &DualModeController::ReadLoopbackMode}, + {OpCode::WRITE_LOOPBACK_MODE, &DualModeController::WriteLoopbackMode}, + //{OpCode::ENABLE_DEVICE_UNDER_TEST_MODE, + //&DualModeController::EnableDeviceUnderTestMode}, + //{OpCode::WRITE_SIMPLE_PAIRING_DEBUG_MODE, + //&DualModeController::WriteSimplePairingDebugMode}, + //{OpCode::WRITE_SECURE_CONNECTIONS_TEST_MODE, + //&DualModeController::WriteSecureConnectionsTestMode}, + + // LE_CONTROLLER + {OpCode::LE_SET_EVENT_MASK, &DualModeController::LeSetEventMask}, + {OpCode::LE_READ_BUFFER_SIZE_V1, &DualModeController::LeReadBufferSizeV1}, + {OpCode::LE_READ_LOCAL_SUPPORTED_FEATURES, + &DualModeController::LeReadLocalSupportedFeatures}, + {OpCode::LE_SET_RANDOM_ADDRESS, &DualModeController::LeSetRandomAddress}, + {OpCode::LE_SET_ADVERTISING_PARAMETERS, + &DualModeController::LeSetAdvertisingParameters}, + {OpCode::LE_READ_ADVERTISING_PHYSICAL_CHANNEL_TX_POWER, + &DualModeController::LeReadAdvertisingPhysicalChannelTxPower}, + {OpCode::LE_SET_ADVERTISING_DATA, &DualModeController::LeSetAdvertisingData}, + {OpCode::LE_SET_SCAN_RESPONSE_DATA, &DualModeController::LeSetScanResponseData}, + {OpCode::LE_SET_ADVERTISING_ENABLE, &DualModeController::LeSetAdvertisingEnable}, + {OpCode::LE_SET_SCAN_PARAMETERS, &DualModeController::LeSetScanParameters}, + {OpCode::LE_SET_SCAN_ENABLE, &DualModeController::LeSetScanEnable}, + {OpCode::LE_CREATE_CONNECTION, &DualModeController::LeCreateConnection}, + {OpCode::LE_CREATE_CONNECTION_CANCEL, + &DualModeController::LeCreateConnectionCancel}, + {OpCode::LE_READ_FILTER_ACCEPT_LIST_SIZE, + &DualModeController::LeReadFilterAcceptListSize}, + {OpCode::LE_CLEAR_FILTER_ACCEPT_LIST, &DualModeController::LeClearFilterAcceptList}, + {OpCode::LE_ADD_DEVICE_TO_FILTER_ACCEPT_LIST, + &DualModeController::LeAddDeviceToFilterAcceptList}, + {OpCode::LE_REMOVE_DEVICE_FROM_FILTER_ACCEPT_LIST, + &DualModeController::LeRemoveDeviceFromFilterAcceptList}, + {OpCode::LE_CONNECTION_UPDATE, &DualModeController::LeConnectionUpdate}, + //{OpCode::LE_SET_HOST_CHANNEL_CLASSIFICATION, + //&DualModeController::LeSetHostChannelClassification}, + //{OpCode::LE_READ_CHANNEL_MAP, &DualModeController::LeReadChannelMap}, + {OpCode::LE_READ_REMOTE_FEATURES, &DualModeController::LeReadRemoteFeatures}, + {OpCode::LE_ENCRYPT, &DualModeController::LeEncrypt}, + {OpCode::LE_RAND, &DualModeController::LeRand}, + {OpCode::LE_START_ENCRYPTION, &DualModeController::LeStartEncryption}, + {OpCode::LE_LONG_TERM_KEY_REQUEST_REPLY, + &DualModeController::LeLongTermKeyRequestReply}, + {OpCode::LE_LONG_TERM_KEY_REQUEST_NEGATIVE_REPLY, + &DualModeController::LeLongTermKeyRequestNegativeReply}, + {OpCode::LE_READ_SUPPORTED_STATES, &DualModeController::LeReadSupportedStates}, + //{OpCode::LE_RECEIVER_TEST_V1, &DualModeController::LeReceiverTestV1}, + //{OpCode::LE_TRANSMITTER_TEST_V1, + //&DualModeController::LeTransmitterTestV1}, + //{OpCode::LE_TEST_END, &DualModeController::LeTestEnd}, + {OpCode::LE_REMOTE_CONNECTION_PARAMETER_REQUEST_REPLY, + &DualModeController::LeRemoteConnectionParameterRequestReply}, + {OpCode::LE_REMOTE_CONNECTION_PARAMETER_REQUEST_NEGATIVE_REPLY, + &DualModeController::LeRemoteConnectionParameterRequestNegativeReply}, + //{OpCode::LE_SET_DATA_LENGTH, &DualModeController::LeSetDataLength}, + {OpCode::LE_READ_SUGGESTED_DEFAULT_DATA_LENGTH, + &DualModeController::LeReadSuggestedDefaultDataLength}, + {OpCode::LE_WRITE_SUGGESTED_DEFAULT_DATA_LENGTH, + &DualModeController::LeWriteSuggestedDefaultDataLength}, + //{OpCode::LE_READ_LOCAL_P_256_PUBLIC_KEY, + //&DualModeController::LeReadLocalP256PublicKey}, + //{OpCode::LE_GENERATE_DHKEY_V1, + //&DualModeController::LeGenerateDhkeyV1}, + {OpCode::LE_ADD_DEVICE_TO_RESOLVING_LIST, + &DualModeController::LeAddDeviceToResolvingList}, + {OpCode::LE_REMOVE_DEVICE_FROM_RESOLVING_LIST, + &DualModeController::LeRemoveDeviceFromResolvingList}, + {OpCode::LE_CLEAR_RESOLVING_LIST, &DualModeController::LeClearResolvingList}, + {OpCode::LE_READ_RESOLVING_LIST_SIZE, &DualModeController::LeReadResolvingListSize}, + {OpCode::LE_READ_PEER_RESOLVABLE_ADDRESS, + &DualModeController::LeReadPeerResolvableAddress}, + {OpCode::LE_READ_LOCAL_RESOLVABLE_ADDRESS, + &DualModeController::LeReadLocalResolvableAddress}, + {OpCode::LE_SET_ADDRESS_RESOLUTION_ENABLE, + &DualModeController::LeSetAddressResolutionEnable}, + {OpCode::LE_SET_RESOLVABLE_PRIVATE_ADDRESS_TIMEOUT, + &DualModeController::LeSetResolvablePrivateAddressTimeout}, + {OpCode::LE_READ_MAXIMUM_DATA_LENGTH, &DualModeController::LeReadMaximumDataLength}, + {OpCode::LE_READ_PHY, &DualModeController::LeReadPhy}, + {OpCode::LE_SET_DEFAULT_PHY, &DualModeController::LeSetDefaultPhy}, + {OpCode::LE_SET_PHY, &DualModeController::LeSetPhy}, + //{OpCode::LE_RECEIVER_TEST_V2, &DualModeController::LeReceiverTestV2}, + //{OpCode::LE_TRANSMITTER_TEST_V2, + //&DualModeController::LeTransmitterTestV2}, + {OpCode::LE_SET_ADVERTISING_SET_RANDOM_ADDRESS, + &DualModeController::LeSetAdvertisingSetRandomAddress}, + {OpCode::LE_SET_EXTENDED_ADVERTISING_PARAMETERS, + &DualModeController::LeSetExtendedAdvertisingParameters}, + {OpCode::LE_SET_EXTENDED_ADVERTISING_DATA, + &DualModeController::LeSetExtendedAdvertisingData}, + {OpCode::LE_SET_EXTENDED_SCAN_RESPONSE_DATA, + &DualModeController::LeSetExtendedScanResponseData}, + {OpCode::LE_SET_EXTENDED_ADVERTISING_ENABLE, + &DualModeController::LeSetExtendedAdvertisingEnable}, + {OpCode::LE_READ_MAXIMUM_ADVERTISING_DATA_LENGTH, + &DualModeController::LeReadMaximumAdvertisingDataLength}, + {OpCode::LE_READ_NUMBER_OF_SUPPORTED_ADVERTISING_SETS, + &DualModeController::LeReadNumberOfSupportedAdvertisingSets}, + {OpCode::LE_REMOVE_ADVERTISING_SET, &DualModeController::LeRemoveAdvertisingSet}, + {OpCode::LE_CLEAR_ADVERTISING_SETS, &DualModeController::LeClearAdvertisingSets}, + {OpCode::LE_SET_PERIODIC_ADVERTISING_PARAMETERS, + &DualModeController::LeSetPeriodicAdvertisingParameters}, + {OpCode::LE_SET_PERIODIC_ADVERTISING_DATA, + &DualModeController::LeSetPeriodicAdvertisingData}, + {OpCode::LE_SET_PERIODIC_ADVERTISING_ENABLE, + &DualModeController::LeSetPeriodicAdvertisingEnable}, + {OpCode::LE_SET_EXTENDED_SCAN_PARAMETERS, + &DualModeController::LeSetExtendedScanParameters}, + {OpCode::LE_SET_EXTENDED_SCAN_ENABLE, &DualModeController::LeSetExtendedScanEnable}, + {OpCode::LE_EXTENDED_CREATE_CONNECTION, + &DualModeController::LeExtendedCreateConnection}, + {OpCode::LE_PERIODIC_ADVERTISING_CREATE_SYNC, + &DualModeController::LePeriodicAdvertisingCreateSync}, + {OpCode::LE_PERIODIC_ADVERTISING_CREATE_SYNC_CANCEL, + &DualModeController::LePeriodicAdvertisingCreateSyncCancel}, + {OpCode::LE_PERIODIC_ADVERTISING_TERMINATE_SYNC, + &DualModeController::LePeriodicAdvertisingTerminateSync}, + {OpCode::LE_ADD_DEVICE_TO_PERIODIC_ADVERTISER_LIST, + &DualModeController::LeAddDeviceToPeriodicAdvertiserList}, + {OpCode::LE_REMOVE_DEVICE_FROM_PERIODIC_ADVERTISER_LIST, + &DualModeController::LeRemoveDeviceFromPeriodicAdvertiserList}, + {OpCode::LE_CLEAR_PERIODIC_ADVERTISER_LIST, + &DualModeController::LeClearPeriodicAdvertiserList}, + {OpCode::LE_READ_PERIODIC_ADVERTISER_LIST_SIZE, + &DualModeController::LeReadPeriodicAdvertiserListSize}, + //{OpCode::LE_READ_TRANSMIT_POWER, + //&DualModeController::LeReadTransmitPower}, + //{OpCode::LE_READ_RF_PATH_COMPENSATION_POWER, + //&DualModeController::LeReadRfPathCompensationPower}, + //{OpCode::LE_WRITE_RF_PATH_COMPENSATION_POWER, + //&DualModeController::LeWriteRfPathCompensationPower}, + {OpCode::LE_SET_PRIVACY_MODE, &DualModeController::LeSetPrivacyMode}, + //{OpCode::LE_RECEIVER_TEST_V3, &DualModeController::LeReceiverTestV3}, + //{OpCode::LE_TRANSMITTER_TEST_V3, + //&DualModeController::LeTransmitterTestV3}, + //{OpCode::LE_SET_CONNECTIONLESS_CTE_TRANSMIT_PARAMETERS, + //&DualModeController::LeSetConnectionlessCteTransmitParameters}, + //{OpCode::LE_SET_CONNECTIONLESS_CTE_TRANSMIT_ENABLE, + //&DualModeController::LeSetConnectionlessCteTransmitEnable}, + //{OpCode::LE_SET_CONNECTIONLESS_IQ_SAMPLING_ENABLE, + //&DualModeController::LeSetConnectionlessIqSamplingEnable}, + //{OpCode::LE_SET_CONNECTION_CTE_RECEIVE_PARAMETERS, + //&DualModeController::LeSetConnectionCteReceiveParameters}, + //{OpCode::LE_SET_CONNECTION_CTE_TRANSMIT_PARAMETERS, + //&DualModeController::LeSetConnectionCteTransmitParameters}, + //{OpCode::LE_CONNECTION_CTE_REQUEST_ENABLE, + //&DualModeController::LeConnectionCteRequestEnable}, + //{OpCode::LE_CONNECTION_CTE_RESPONSE_ENABLE, + //&DualModeController::LeConnectionCteResponseEnable}, + //{OpCode::LE_READ_ANTENNA_INFORMATION, + //&DualModeController::LeReadAntennaInformation}, + //{OpCode::LE_SET_PERIODIC_ADVERTISING_RECEIVE_ENABLE, + //&DualModeController::LeSetPeriodicAdvertisingReceiveEnable}, + //{OpCode::LE_PERIODIC_ADVERTISING_SYNC_TRANSFER, + //&DualModeController::LePeriodicAdvertisingSyncTransfer}, + //{OpCode::LE_PERIODIC_ADVERTISING_SET_INFO_TRANSFER, + //&DualModeController::LePeriodicAdvertisingSetInfoTransfer}, + //{OpCode::LE_SET_PERIODIC_ADVERTISING_SYNC_TRANSFER_PARAMETERS, + //&DualModeController::LeSetPeriodicAdvertisingSyncTransferParameters}, + //{OpCode::LE_SET_DEFAULT_PERIODIC_ADVERTISING_SYNC_TRANSFER_PARAMETERS, + //&DualModeController::LeSetDefaultPeriodicAdvertisingSyncTransferParameters}, + //{OpCode::LE_GENERATE_DHKEY_V2, + //&DualModeController::LeGenerateDhkeyV2}, + //{OpCode::LE_MODIFY_SLEEP_CLOCK_ACCURACY, + //&DualModeController::LeModifySleepClockAccuracy}, + {OpCode::LE_READ_BUFFER_SIZE_V2, &DualModeController::LeReadBufferSizeV2}, + //{OpCode::LE_READ_ISO_TX_SYNC, &DualModeController::LeReadIsoTxSync}, + {OpCode::LE_SET_CIG_PARAMETERS, &DualModeController::ForwardToLl}, + {OpCode::LE_SET_CIG_PARAMETERS_TEST, &DualModeController::ForwardToLl}, + {OpCode::LE_CREATE_CIS, &DualModeController::ForwardToLl}, + {OpCode::LE_REMOVE_CIG, &DualModeController::ForwardToLl}, + {OpCode::LE_ACCEPT_CIS_REQUEST, &DualModeController::ForwardToLl}, + {OpCode::LE_REJECT_CIS_REQUEST, &DualModeController::ForwardToLl}, + //{OpCode::LE_CREATE_BIG, &DualModeController::LeCreateBig}, + //{OpCode::LE_CREATE_BIG_TEST, &DualModeController::LeCreateBigTest}, + //{OpCode::LE_TERMINATE_BIG, &DualModeController::LeTerminateBig}, + //{OpCode::LE_BIG_CREATE_SYNC, &DualModeController::LeBigCreateSync}, + //{OpCode::LE_BIG_TERMINATE_SYNC, + //&DualModeController::LeBigTerminateSync}, + {OpCode::LE_REQUEST_PEER_SCA, &DualModeController::LeRequestPeerSca}, + {OpCode::LE_SETUP_ISO_DATA_PATH, &DualModeController::ForwardToLl}, + {OpCode::LE_REMOVE_ISO_DATA_PATH, &DualModeController::ForwardToLl}, + //{OpCode::LE_ISO_TRANSMIT_TEST, + //&DualModeController::LeIsoTransmitTest}, + //{OpCode::LE_ISO_RECEIVE_TEST, &DualModeController::LeIsoReceiveTest}, + //{OpCode::LE_ISO_READ_TEST_COUNTERS, + //&DualModeController::LeIsoReadTestCounters}, + //{OpCode::LE_ISO_TEST_END, &DualModeController::LeIsoTestEnd}, + {OpCode::LE_SET_HOST_FEATURE, &DualModeController::LeSetHostFeature}, + //{OpCode::LE_READ_ISO_LINK_QUALITY, + //&DualModeController::LeReadIsoLinkQuality}, + //{OpCode::LE_ENHANCED_READ_TRANSMIT_POWER_LEVEL, + //&DualModeController::LeEnhancedReadTransmitPowerLevel}, + //{OpCode::LE_READ_REMOTE_TRANSMIT_POWER_LEVEL, + //&DualModeController::LeReadRemoteTransmitPowerLevel}, + //{OpCode::LE_SET_PATH_LOSS_REPORTING_PARAMETERS, + //&DualModeController::LeSetPathLossReportingParameters}, + //{OpCode::LE_SET_PATH_LOSS_REPORTING_ENABLE, + //&DualModeController::LeSetPathLossReportingEnable}, + //{OpCode::LE_SET_TRANSMIT_POWER_REPORTING_ENABLE, + //&DualModeController::LeSetTransmitPowerReportingEnable}, + //{OpCode::LE_TRANSMITTER_TEST_V4, + //&DualModeController::LeTransmitterTestV4}, + //{OpCode::LE_SET_DATA_RELATED_ADDRESS_CHANGES, + //&DualModeController::LeSetDataRelatedAddressChanges}, + //{OpCode::LE_SET_DEFAULT_SUBRATE, + //&DualModeController::LeSetDefaultSubrate}, + //{OpCode::LE_SUBRATE_REQUEST, &DualModeController::LeSubrateRequest}, + + // VENDOR + {OpCode(CSR_VENDOR), &DualModeController::CsrVendorCommand}, + {OpCode::LE_GET_VENDOR_CAPABILITIES, &DualModeController::LeGetVendorCapabilities}, + {OpCode::LE_BATCH_SCAN, &DualModeController::LeBatchScan}, + {OpCode::LE_APCF, &DualModeController::LeApcf}, + {OpCode::LE_GET_CONTROLLER_ACTIVITY_ENERGY_INFO, + &DualModeController::LeGetControllerActivityEnergyInfo}, + {OpCode::LE_EX_SET_SCAN_PARAMETERS, &DualModeController::LeExSetScanParameters}, + {OpCode::GET_CONTROLLER_DEBUG_INFO, &DualModeController::GetControllerDebugInfo}}; } // namespace rootcanal diff --git a/tools/rootcanal/model/controller/dual_mode_controller.h b/tools/rootcanal/model/controller/dual_mode_controller.h index f3b0ce17268..bf95c8a95f4 100644 --- a/tools/rootcanal/model/controller/dual_mode_controller.h +++ b/tools/rootcanal/model/controller/dual_mode_controller.h @@ -59,7 +59,7 @@ enum InvalidPacketReason { // corresponding Bluetooth command in the Core Specification with the prefix // "Hci" to distinguish it as a controller command. class DualModeController : public Device { - public: +public: DualModeController(ControllerProperties properties = ControllerProperties()); DualModeController(DualModeController&&) = delete; DualModeController(const DualModeController&) = delete; @@ -73,8 +73,8 @@ class DualModeController : public Device { // Device methods. std::string GetTypeString() const override; - void ReceiveLinkLayerPacket(model::packets::LinkLayerPacketView incoming, - Phy::Type type, int8_t rssi) override; + void ReceiveLinkLayerPacket(model::packets::LinkLayerPacketView incoming, Phy::Type type, + int8_t rssi) override; void Tick() override; void Close() override; @@ -89,25 +89,21 @@ class DualModeController : public Device { /// to an external tracker. Packets are rejected if they failed to /// be parsed, or run into an unimplemented part of the controller. void RegisterInvalidPacketHandler( - const std::function const&)>& handler); + const std::function const&)>& handler); // Set the callbacks for sending packets to the HCI. void RegisterEventChannel( - const std::function>)>& - send_event); + const std::function>)>& send_event); void RegisterAclChannel( - const std::function>)>& - send_acl); + const std::function>)>& send_acl); void RegisterScoChannel( - const std::function>)>& - send_sco); + const std::function>)>& send_sco); void RegisterIsoChannel( - const std::function>)>& - send_iso); + const std::function>)>& send_iso); // Controller commands. For error codes, see the Bluetooth Core Specification, // Version 4.2, Volume 2, Part D (page 370). @@ -540,18 +536,17 @@ class DualModeController : public Device { void ForwardToLm(CommandView command); void ForwardToLl(CommandView command); - protected: +protected: // Controller configuration. ControllerProperties properties_; // Link Layer state. LinkLayerController link_layer_controller_{address_, properties_, id_}; - private: +private: // Send a HCI_Command_Complete event for the specified op_code with // the error code UNKNOWN_OPCODE. - void SendCommandCompleteUnknownOpCodeEvent( - bluetooth::hci::OpCode op_code) const; + void SendCommandCompleteUnknownOpCodeEvent(bluetooth::hci::OpCode op_code) const; // Validate that a received packet is correctly formatted. // If the packet failed to be parsed, the function sends a @@ -566,22 +561,19 @@ class DualModeController : public Device { // Send a hardware error to reset the host, and report the packet // for tracing. send_event_(bluetooth::hci::HardwareErrorBuilder::Create(0x43)); - invalid_packet_handler_(id_, InvalidPacketReason::kParseError, reason, - view.bytes().bytes()); + invalid_packet_handler_(id_, InvalidPacketReason::kParseError, reason, view.bytes().bytes()); return false; } // Callbacks to send packets back to the HCI. std::function)> send_acl_; - std::function)> - send_event_; + std::function)> send_event_; std::function)> send_sco_; std::function)> send_iso_; // Report invalid packets received on this controller instance. - std::function const&)> - invalid_packet_handler_; + std::function const&)> + invalid_packet_handler_; // Loopback mode (Vol 4, Part E § 7.6.1). // The local loopback mode is used to pass the android Vendor Test Suite @@ -597,15 +589,13 @@ class DualModeController : public Device { // Map command opcodes to the corresponding bit index in the // supported command mask. - static const std::unordered_map - hci_command_op_code_to_index_; + static const std::unordered_map hci_command_op_code_to_index_; // Map all implemented opcodes to the function implementing the handler // for the associated command. The map should be a subset of the // supported_command field in the properties_ object. Commands // that are supported but not implemented will raise a fatal assert. - using CommandHandler = - std::function; + using CommandHandler = std::function; static const std::unordered_map hci_command_handlers_; }; diff --git a/tools/rootcanal/model/controller/ffi.cc b/tools/rootcanal/model/controller/ffi.cc index d01ff166539..bfb8be74869 100644 --- a/tools/rootcanal/model/controller/ffi.cc +++ b/tools/rootcanal/model/controller/ffi.cc @@ -44,50 +44,42 @@ __attribute__((constructor)) static void ConfigureLogging() { extern "C" { __attribute__((visibility("default"))) void* ffi_controller_new( - uint8_t const address[6], - void (*send_hci)(int idc, uint8_t const* data, size_t data_len), - void (*send_ll)(uint8_t const* data, size_t data_len, int phy, - int tx_power)) { + uint8_t const address[6], void (*send_hci)(int idc, uint8_t const* data, size_t data_len), + void (*send_ll)(uint8_t const* data, size_t data_len, int phy, int tx_power)) { DualModeController* controller = new DualModeController(); - controller->SetAddress(Address({address[0], address[1], address[2], - address[3], address[4], address[5]})); - controller->RegisterEventChannel( - [=](std::shared_ptr> data) { - send_hci(hci::Idc::EVT, data->data(), data->size()); - }); - controller->RegisterAclChannel( - [=](std::shared_ptr> data) { - send_hci(hci::Idc::ACL, data->data(), data->size()); - }); - controller->RegisterScoChannel( - [=](std::shared_ptr> data) { - send_hci(hci::Idc::SCO, data->data(), data->size()); - }); - controller->RegisterIsoChannel( - [=](std::shared_ptr> data) { - send_hci(hci::Idc::ISO, data->data(), data->size()); - }); + controller->SetAddress( + Address({address[0], address[1], address[2], address[3], address[4], address[5]})); + controller->RegisterEventChannel([=](std::shared_ptr> data) { + send_hci(hci::Idc::EVT, data->data(), data->size()); + }); + controller->RegisterAclChannel([=](std::shared_ptr> data) { + send_hci(hci::Idc::ACL, data->data(), data->size()); + }); + controller->RegisterScoChannel([=](std::shared_ptr> data) { + send_hci(hci::Idc::SCO, data->data(), data->size()); + }); + controller->RegisterIsoChannel([=](std::shared_ptr> data) { + send_hci(hci::Idc::ISO, data->data(), data->size()); + }); controller->RegisterLinkLayerChannel( - [=](std::vector const& data, Phy::Type phy, int8_t tx_power) { - send_ll(data.data(), data.size(), static_cast(phy), tx_power); - }); + [=](std::vector const& data, Phy::Type phy, int8_t tx_power) { + send_ll(data.data(), data.size(), static_cast(phy), tx_power); + }); return controller; } -__attribute__((visibility("default"))) void ffi_controller_delete( - void* controller_) { - DualModeController* controller = - reinterpret_cast(controller_); +__attribute__((visibility("default"))) void ffi_controller_delete(void* controller_) { + DualModeController* controller = reinterpret_cast(controller_); delete controller; } -__attribute__((visibility("default"))) void ffi_controller_receive_hci( - void* controller_, int idc, uint8_t const* data, size_t data_len) { - DualModeController* controller = - reinterpret_cast(controller_); +__attribute__((visibility("default"))) void ffi_controller_receive_hci(void* controller_, int idc, + uint8_t const* data, + size_t data_len) { + DualModeController* controller = reinterpret_cast(controller_); std::shared_ptr> bytes = - std::make_shared>(data, data + data_len); + std::make_shared>(data, data + data_len); switch (idc) { case hci::Idc::CMD: @@ -103,21 +95,20 @@ __attribute__((visibility("default"))) void ffi_controller_receive_hci( controller->HandleIso(bytes); break; default: - std::cerr << "Dropping HCI packet with unknown type " << (int)idc - << std::endl; + std::cerr << "Dropping HCI packet with unknown type " << (int)idc << std::endl; break; } } -__attribute__((visibility("default"))) void ffi_controller_receive_ll( - void* controller_, uint8_t const* data, size_t data_len, int phy, - int rssi) { - DualModeController* controller = - reinterpret_cast(controller_); +__attribute__((visibility("default"))) void ffi_controller_receive_ll(void* controller_, + uint8_t const* data, + size_t data_len, int phy, + int rssi) { + DualModeController* controller = reinterpret_cast(controller_); std::shared_ptr> bytes = - std::make_shared>(data, data + data_len); + std::make_shared>(data, data + data_len); model::packets::LinkLayerPacketView packet = - model::packets::LinkLayerPacketView::Create(pdl::packet::slice(bytes)); + model::packets::LinkLayerPacketView::Create(pdl::packet::slice(bytes)); if (!packet.IsValid()) { std::cerr << "Dropping malformed LL packet" << std::endl; return; @@ -125,15 +116,13 @@ __attribute__((visibility("default"))) void ffi_controller_receive_ll( controller->ReceiveLinkLayerPacket(packet, Phy::Type(phy), rssi); } -__attribute__((visibility("default"))) void ffi_controller_tick( - void* controller_) { - DualModeController* controller = - reinterpret_cast(controller_); +__attribute__((visibility("default"))) void ffi_controller_tick(void* controller_) { + DualModeController* controller = reinterpret_cast(controller_); controller->Tick(); } -__attribute__((visibility("default"))) void ffi_generate_rpa( - uint8_t const irk_[16], uint8_t rpa[6]) { +__attribute__((visibility("default"))) void ffi_generate_rpa(uint8_t const irk_[16], + uint8_t rpa[6]) { std::array irk; memcpy(irk.data(), irk_, LinkLayerController::kIrkSize); Address address = LinkLayerController::generate_rpa(irk); diff --git a/tools/rootcanal/model/controller/ffi.h b/tools/rootcanal/model/controller/ffi.h index 8b6033be02a..8b1d9d27cf3 100644 --- a/tools/rootcanal/model/controller/ffi.h +++ b/tools/rootcanal/model/controller/ffi.h @@ -20,15 +20,13 @@ extern "C" { void* ffi_controller_new(uint8_t const address[6], - void (*send_hci)(int idc, uint8_t const* data, - size_t data_len), - void (*send_ll)(uint8_t const* data, size_t data_len, - int phy, int tx_power)); + void (*send_hci)(int idc, uint8_t const* data, size_t data_len), + void (*send_ll)(uint8_t const* data, size_t data_len, int phy, + int tx_power)); void ffi_controller_delete(void* controller); -void ffi_controller_receive_hci(void* controller, int idc, uint8_t const* data, - size_t data_len); -void ffi_controller_receive_ll(void* controller, uint8_t const* data, - size_t data_len, int phy, int rssi); +void ffi_controller_receive_hci(void* controller, int idc, uint8_t const* data, size_t data_len); +void ffi_controller_receive_ll(void* controller, uint8_t const* data, size_t data_len, int phy, + int rssi); void ffi_controller_tick(void* controller); void ffi_generate_rpa(uint8_t const irk[16], uint8_t rpa[6]); diff --git a/tools/rootcanal/model/controller/le_advertiser.cc b/tools/rootcanal/model/controller/le_advertiser.cc index 0f5cfabadfa..7f5a89fd12b 100644 --- a/tools/rootcanal/model/controller/le_advertiser.cc +++ b/tools/rootcanal/model/controller/le_advertiser.cc @@ -62,11 +62,10 @@ const uint16_t max_extended_advertising_pdu_size = 1650; // HCI command LE_Set_Advertising_Parameters (Vol 4, Part E § 7.8.5). ErrorCode LinkLayerController::LeSetAdvertisingParameters( - uint16_t advertising_interval_min, uint16_t advertising_interval_max, - AdvertisingType advertising_type, OwnAddressType own_address_type, - PeerAddressType peer_address_type, Address peer_address, - uint8_t advertising_channel_map, - AdvertisingFilterPolicy advertising_filter_policy) { + uint16_t advertising_interval_min, uint16_t advertising_interval_max, + AdvertisingType advertising_type, OwnAddressType own_address_type, + PeerAddressType peer_address_type, Address peer_address, uint8_t advertising_channel_map, + AdvertisingFilterPolicy advertising_filter_policy) { // Legacy advertising commands are disallowed when extended advertising // commands were used since the last reset. if (!SelectLegacyAdvertising()) { @@ -131,9 +130,9 @@ ErrorCode LinkLayerController::LeSetAdvertisingParameters( } legacy_advertiser_.advertising_interval = - advertising_type == AdvertisingType::ADV_DIRECT_IND_HIGH - ? std::chrono::duration_cast(adv_direct_ind_high_interval) - : slots(advertising_interval_min); + advertising_type == AdvertisingType::ADV_DIRECT_IND_HIGH + ? std::chrono::duration_cast(adv_direct_ind_high_interval) + : slots(advertising_interval_min); legacy_advertiser_.advertising_type = advertising_type; legacy_advertiser_.own_address_type = own_address_type; legacy_advertiser_.peer_address_type = peer_address_type; @@ -144,8 +143,7 @@ ErrorCode LinkLayerController::LeSetAdvertisingParameters( } // HCI command LE_Set_Advertising_Data (Vol 4, Part E § 7.8.7). -ErrorCode LinkLayerController::LeSetAdvertisingData( - const std::vector& advertising_data) { +ErrorCode LinkLayerController::LeSetAdvertisingData(const std::vector& advertising_data) { // Legacy advertising commands are disallowed when extended advertising // commands were used since the last reset. if (!SelectLegacyAdvertising()) { @@ -161,7 +159,7 @@ ErrorCode LinkLayerController::LeSetAdvertisingData( // HCI command LE_Set_Scan_Response_Data (Vol 4, Part E § 7.8.8). ErrorCode LinkLayerController::LeSetScanResponseData( - const std::vector& scan_response_data) { + const std::vector& scan_response_data) { // Legacy advertising commands are disallowed when extended advertising // commands were used since the last reset. if (!SelectLegacyAdvertising()) { @@ -191,13 +189,12 @@ ErrorCode LinkLayerController::LeSetAdvertisingEnable(bool advertising_enable) { return ErrorCode::SUCCESS; } - AddressWithType peer_address = PeerDeviceAddress( - legacy_advertiser_.peer_address, legacy_advertiser_.peer_address_type); + AddressWithType peer_address = + PeerDeviceAddress(legacy_advertiser_.peer_address, legacy_advertiser_.peer_address_type); AddressWithType public_address{address_, AddressType::PUBLIC_DEVICE_ADDRESS}; - AddressWithType random_address{random_address_, - AddressType::RANDOM_DEVICE_ADDRESS}; + AddressWithType random_address{random_address_, AddressType::RANDOM_DEVICE_ADDRESS}; std::optional resolvable_address = - GenerateResolvablePrivateAddress(peer_address, IrkSelection::Local); + GenerateResolvablePrivateAddress(peer_address, IrkSelection::Local); // TODO: additional checks would apply in the case of a LE only Controller // with no configured public device address. @@ -223,8 +220,7 @@ ErrorCode LinkLayerController::LeSetAdvertisingEnable(bool advertising_enable) { break; case OwnAddressType::RESOLVABLE_OR_PUBLIC_ADDRESS: - legacy_advertiser_.advertising_address = - resolvable_address.value_or(public_address); + legacy_advertiser_.advertising_address = resolvable_address.value_or(public_address); break; case OwnAddressType::RESOLVABLE_OR_RANDOM_ADDRESS: @@ -250,14 +246,13 @@ ErrorCode LinkLayerController::LeSetAdvertisingEnable(bool advertising_enable) { legacy_advertiser_.timeout = {}; legacy_advertiser_.target_address = - AddressWithType{Address::kEmpty, AddressType::PUBLIC_DEVICE_ADDRESS}; + AddressWithType{Address::kEmpty, AddressType::PUBLIC_DEVICE_ADDRESS}; switch (legacy_advertiser_.advertising_type) { case AdvertisingType::ADV_DIRECT_IND_HIGH: // The Link Layer shall exit the Advertising state no later than 1.28 s // after the Advertising state was entered. - legacy_advertiser_.timeout = - std::chrono::steady_clock::now() + adv_direct_ind_high_timeout; + legacy_advertiser_.timeout = std::chrono::steady_clock::now() + adv_direct_ind_high_timeout; [[fallthrough]]; case AdvertisingType::ADV_DIRECT_IND_LOW: { @@ -271,9 +266,8 @@ ErrorCode LinkLayerController::LeSetAdvertisingEnable(bool advertising_enable) { // (TargetA field) shall use the Identity Address when entering the // Advertising State and using connectable directed events. std::optional peer_resolvable_address = - GenerateResolvablePrivateAddress(peer_address, IrkSelection::Peer); - legacy_advertiser_.target_address = - peer_resolvable_address.value_or(peer_address); + GenerateResolvablePrivateAddress(peer_address, IrkSelection::Peer); + legacy_advertiser_.target_address = peer_resolvable_address.value_or(peer_address); break; } default: @@ -281,8 +275,8 @@ ErrorCode LinkLayerController::LeSetAdvertisingEnable(bool advertising_enable) { } legacy_advertiser_.advertising_enable = true; - legacy_advertiser_.next_event = std::chrono::steady_clock::now() + - legacy_advertiser_.advertising_interval; + legacy_advertiser_.next_event = + std::chrono::steady_clock::now() + legacy_advertiser_.advertising_interval; return ErrorCode::SUCCESS; } @@ -291,8 +285,8 @@ ErrorCode LinkLayerController::LeSetAdvertisingEnable(bool advertising_enable) { // ============================================================================= // HCI command LE_Set_Advertising_Set_Random_Address (Vol 4, Part E § 7.8.52). -ErrorCode LinkLayerController::LeSetAdvertisingSetRandomAddress( - uint8_t advertising_handle, Address random_address) { +ErrorCode LinkLayerController::LeSetAdvertisingSetRandomAddress(uint8_t advertising_handle, + Address random_address) { // If the advertising set corresponding to the Advertising_Handle parameter // does not exist, then the Controller shall return the error code // Unknown Advertising Identifier (0x42). @@ -320,16 +314,14 @@ ErrorCode LinkLayerController::LeSetAdvertisingSetRandomAddress( // HCI command LE_Set_Extended_Advertising_Parameters (Vol 4, Part E § 7.8.53). ErrorCode LinkLayerController::LeSetExtendedAdvertisingParameters( - uint8_t advertising_handle, - AdvertisingEventProperties advertising_event_properties, - uint16_t primary_advertising_interval_min, - uint16_t primary_advertising_interval_max, - uint8_t primary_advertising_channel_map, OwnAddressType own_address_type, - PeerAddressType peer_address_type, Address peer_address, - AdvertisingFilterPolicy advertising_filter_policy, - uint8_t advertising_tx_power, PrimaryPhyType primary_advertising_phy, - uint8_t secondary_max_skip, SecondaryPhyType secondary_advertising_phy, - uint8_t advertising_sid, bool scan_request_notification_enable) { + uint8_t advertising_handle, AdvertisingEventProperties advertising_event_properties, + uint16_t primary_advertising_interval_min, uint16_t primary_advertising_interval_max, + uint8_t primary_advertising_channel_map, OwnAddressType own_address_type, + PeerAddressType peer_address_type, Address peer_address, + AdvertisingFilterPolicy advertising_filter_policy, uint8_t advertising_tx_power, + PrimaryPhyType primary_advertising_phy, uint8_t secondary_max_skip, + SecondaryPhyType secondary_advertising_phy, uint8_t advertising_sid, + bool scan_request_notification_enable) { // Extended advertising commands are disallowed when legacy advertising // commands were used since the last reset. if (!SelectExtendedAdvertising()) { @@ -344,12 +336,10 @@ ErrorCode LinkLayerController::LeSetExtendedAdvertisingParameters( bool connectable_advertising = advertising_event_properties.connectable_; bool scannable_advertising = advertising_event_properties.scannable_; bool directed_advertising = advertising_event_properties.directed_; - bool high_duty_cycle_advertising = - advertising_event_properties.high_duty_cycle_; + bool high_duty_cycle_advertising = advertising_event_properties.high_duty_cycle_; bool anonymous_advertising = advertising_event_properties.anonymous_; uint16_t raw_advertising_event_properties = - ExtendedAdvertiser::GetRawAdvertisingEventProperties( - advertising_event_properties); + ExtendedAdvertiser::GetRawAdvertisingEventProperties(advertising_event_properties); // Clear reserved bits. primary_advertising_channel_map &= 0x7; @@ -361,8 +351,7 @@ ErrorCode LinkLayerController::LeSetExtendedAdvertisingParameters( // TODO(c++20) unordered_map<>::contains if (extended_advertisers_.count(advertising_handle) == 0) { - if (extended_advertisers_.size() >= - properties_.le_num_supported_advertising_sets) { + if (extended_advertisers_.size() >= properties_.le_num_supported_advertising_sets) { INFO(id_, "no advertising set defined with handle {:02x} and" " cannot allocate any more advertisers", @@ -385,19 +374,15 @@ ErrorCode LinkLayerController::LeSetExtendedAdvertisingParameters( // shall be one of those specified in Table 7.2. if (legacy_advertising && (raw_advertising_event_properties & ~0x10) != - static_cast(LegacyAdvertisingEventProperties::ADV_IND) && + static_cast(LegacyAdvertisingEventProperties::ADV_IND) && (raw_advertising_event_properties & ~0x10) != - static_cast( - LegacyAdvertisingEventProperties::ADV_DIRECT_IND_LOW) && + static_cast(LegacyAdvertisingEventProperties::ADV_DIRECT_IND_LOW) && (raw_advertising_event_properties & ~0x10) != - static_cast( - LegacyAdvertisingEventProperties::ADV_DIRECT_IND_HIGH) && + static_cast(LegacyAdvertisingEventProperties::ADV_DIRECT_IND_HIGH) && (raw_advertising_event_properties & ~0x10) != - static_cast( - LegacyAdvertisingEventProperties::ADV_SCAN_IND) && + static_cast(LegacyAdvertisingEventProperties::ADV_SCAN_IND) && (raw_advertising_event_properties & ~0x10) != - static_cast( - LegacyAdvertisingEventProperties::ADV_NONCONN_IND)) { + static_cast(LegacyAdvertisingEventProperties::ADV_NONCONN_IND)) { INFO(id_, "advertising_event_properties (0x{:02x}) is legacy but does not" " match valid legacy advertising event types", @@ -405,9 +390,8 @@ ErrorCode LinkLayerController::LeSetExtendedAdvertisingParameters( return ErrorCode::INVALID_HCI_COMMAND_PARAMETERS; } - bool can_have_advertising_data = - (legacy_advertising && !directed_advertising) || - (extended_advertising && !scannable_advertising); + bool can_have_advertising_data = (legacy_advertising && !directed_advertising) || + (extended_advertising && !scannable_advertising); // If the Advertising_Event_Properties parameter [..] specifies a type that // does not support advertising data when the advertising set already @@ -436,8 +420,7 @@ ErrorCode LinkLayerController::LeSetExtendedAdvertisingParameters( // exceed 31 octets. if (legacy_advertising && (advertiser.advertising_data.size() > max_legacy_advertising_pdu_size || - advertiser.scan_response_data.size() > - max_legacy_advertising_pdu_size)) { + advertiser.scan_response_data.size() > max_legacy_advertising_pdu_size)) { INFO(id_, "advertising_event_properties (0x{:02x}) is legacy and the" " advertising data or scan response data exceeds the capacity" @@ -448,8 +431,7 @@ ErrorCode LinkLayerController::LeSetExtendedAdvertisingParameters( // If extended advertising PDU types are being used (bit 4 = 0) then: // The advertisement shall not be both connectable and scannable. - if (extended_advertising && connectable_advertising && - scannable_advertising) { + if (extended_advertising && connectable_advertising && scannable_advertising) { INFO(id_, "advertising_event_properties (0x{:02x}) is extended and may not" " be connectable and scannable at the same time", @@ -473,8 +455,7 @@ ErrorCode LinkLayerController::LeSetExtendedAdvertisingParameters( // outside the advertising interval range supported by the Controller, then // the Controller shall return the error code Unsupported Feature or // Parameter Value (0x11). - if (primary_advertising_interval_min < 0x20 || - primary_advertising_interval_max < 0x20) { + if (primary_advertising_interval_min < 0x20 || primary_advertising_interval_max < 0x20) { INFO(id_, "primary_advertising_interval_min (0x{:04x}) and/or" " primary_advertising_interval_max (0x{:04x}) are outside the range" @@ -508,8 +489,7 @@ ErrorCode LinkLayerController::LeSetExtendedAdvertisingParameters( INFO(id_, "advertising_event_properties (0x{:04x}) is legacy but" " primary_advertising_phy ({:02x}) is not LE 1M", - raw_advertising_event_properties, - static_cast(primary_advertising_phy)); + raw_advertising_event_properties, static_cast(primary_advertising_phy)); return ErrorCode::INVALID_HCI_COMMAND_PARAMETERS; } @@ -530,9 +510,8 @@ ErrorCode LinkLayerController::LeSetExtendedAdvertisingParameters( // the specified advertising set and connectable, scannable, legacy, // or anonymous advertising is specified, the Controller shall return the // error code Invalid HCI Command Parameters (0x12). - if (advertiser.periodic_advertising_enable && - (connectable_advertising || scannable_advertising || legacy_advertising || - anonymous_advertising)) { + if (advertiser.periodic_advertising_enable && (connectable_advertising || scannable_advertising || + legacy_advertising || anonymous_advertising)) { INFO(id_, "periodic advertising is enabled for the specified advertising set" " and advertising_event_properties (0x{:02x}) is either" @@ -565,8 +544,7 @@ ErrorCode LinkLayerController::LeSetExtendedAdvertisingParameters( // coding shall be assumed. if (extended_advertising && (advertiser.advertising_data.size() > max_extended_advertising_pdu_size || - advertiser.scan_response_data.size() > - max_extended_advertising_pdu_size)) { + advertiser.scan_response_data.size() > max_extended_advertising_pdu_size)) { INFO(id_, "the advertising data contained in the set is larger than the" " available PDU capacity"); @@ -574,8 +552,7 @@ ErrorCode LinkLayerController::LeSetExtendedAdvertisingParameters( } advertiser.advertising_event_properties = advertising_event_properties; - advertiser.primary_advertising_interval = - slots(primary_advertising_interval_min); + advertiser.primary_advertising_interval = slots(primary_advertising_interval_min); advertiser.primary_advertising_channel_map = primary_advertising_channel_map; advertiser.own_address_type = own_address_type; advertiser.peer_address_type = peer_address_type; @@ -586,19 +563,16 @@ ErrorCode LinkLayerController::LeSetExtendedAdvertisingParameters( advertiser.secondary_max_skip = secondary_max_skip; advertiser.secondary_advertising_phy = secondary_advertising_phy; advertiser.advertising_sid = advertising_sid; - advertiser.scan_request_notification_enable = - scan_request_notification_enable; + advertiser.scan_request_notification_enable = scan_request_notification_enable; - extended_advertisers_.insert_or_assign(advertising_handle, - std::move(advertiser)); + extended_advertisers_.insert_or_assign(advertising_handle, std::move(advertiser)); return ErrorCode::SUCCESS; } // HCI command LE_Set_Extended_Advertising_Data (Vol 4, Part E § 7.8.54). ErrorCode LinkLayerController::LeSetExtendedAdvertisingData( - uint8_t advertising_handle, Operation operation, - FragmentPreference fragment_preference, - const std::vector& advertising_data) { + uint8_t advertising_handle, Operation operation, FragmentPreference fragment_preference, + const std::vector& advertising_data) { // Extended advertising commands are disallowed when legacy advertising // commands were used since the last reset. if (!SelectExtendedAdvertising()) { @@ -623,15 +597,13 @@ ErrorCode LinkLayerController::LeSetExtendedAdvertisingData( ExtendedAdvertiser& advertiser = extended_advertisers_[advertising_handle]; const AdvertisingEventProperties& advertising_event_properties = - advertiser.advertising_event_properties; + advertiser.advertising_event_properties; uint16_t raw_advertising_event_properties = - ExtendedAdvertiser::GetRawAdvertisingEventProperties( - advertising_event_properties); + ExtendedAdvertiser::GetRawAdvertisingEventProperties(advertising_event_properties); - bool can_have_advertising_data = (advertising_event_properties.legacy_ && - !advertising_event_properties.directed_) || - (!advertising_event_properties.legacy_ && - !advertising_event_properties.scannable_); + bool can_have_advertising_data = + (advertising_event_properties.legacy_ && !advertising_event_properties.directed_) || + (!advertising_event_properties.legacy_ && !advertising_event_properties.scannable_); // If the advertising set specifies a type that does not support // advertising data, the Controller shall return the error code @@ -680,8 +652,8 @@ ErrorCode LinkLayerController::LeSetExtendedAdvertisingData( // If Operation is not 0x03 or 0x04 and Advertising_Data_Length is zero, // the Controller shall return the error code Invalid HCI // Command Parameters (0x12). - if (operation != Operation::COMPLETE_ADVERTISEMENT && - operation != Operation::UNCHANGED_DATA && advertising_data.empty()) { + if (operation != Operation::COMPLETE_ADVERTISEMENT && operation != Operation::UNCHANGED_DATA && + advertising_data.empty()) { INFO(id_, "operation ({:02x}) is not Complete_Advertisement or Unchanged_Data" " but the advertising data is empty", @@ -692,8 +664,7 @@ ErrorCode LinkLayerController::LeSetExtendedAdvertisingData( // If advertising is currently enabled for the specified advertising set and // Operation does not have the value 0x03 or 0x04, the Controller shall // return the error code Command Disallowed (0x0C). - if (advertiser.advertising_enable && - operation != Operation::COMPLETE_ADVERTISEMENT && + if (advertiser.advertising_enable && operation != Operation::COMPLETE_ADVERTISEMENT && operation != Operation::UNCHANGED_DATA) { INFO(id_, "operation ({:02x}) is used but advertising is enabled for the" @@ -705,8 +676,7 @@ ErrorCode LinkLayerController::LeSetExtendedAdvertisingData( switch (operation) { case Operation::INTERMEDIATE_FRAGMENT: advertiser.advertising_data.insert(advertiser.advertising_data.end(), - advertising_data.begin(), - advertising_data.end()); + advertising_data.begin(), advertising_data.end()); advertiser.partial_advertising_data = true; break; @@ -717,8 +687,7 @@ ErrorCode LinkLayerController::LeSetExtendedAdvertisingData( case Operation::LAST_FRAGMENT: advertiser.advertising_data.insert(advertiser.advertising_data.end(), - advertising_data.begin(), - advertising_data.end()); + advertising_data.begin(), advertising_data.end()); advertiser.partial_advertising_data = false; break; @@ -741,13 +710,11 @@ ErrorCode LinkLayerController::LeSetExtendedAdvertisingData( // or the amount of memory currently available, all the data // shall be discarded and the Controller shall return the error code Memory // Capacity Exceeded (0x07). - if (advertiser.advertising_data.size() > - properties_.le_max_advertising_data_length) { + if (advertiser.advertising_data.size() > properties_.le_max_advertising_data_length) { INFO(id_, "the combined length {} of the advertising data exceeds the" " advertising set capacity {}", - advertiser.advertising_data.size(), - properties_.le_max_advertising_data_length); + advertiser.advertising_data.size(), properties_.le_max_advertising_data_length); advertiser.advertising_data.clear(); advertiser.partial_advertising_data = false; return ErrorCode::MEMORY_CAPACITY_EXCEEDED; @@ -761,8 +728,7 @@ ErrorCode LinkLayerController::LeSetExtendedAdvertisingData( // the error code Packet Too Long (0x45). If advertising on the // LE Coded PHY, the S=8 coding shall be assumed. size_t max_advertising_data_length = - ExtendedAdvertiser::GetMaxAdvertisingDataLength( - advertising_event_properties); + ExtendedAdvertiser::GetMaxAdvertisingDataLength(advertising_event_properties); if (advertiser.advertising_enable && advertiser.advertising_data.size() > max_advertising_data_length) { INFO(id_, @@ -778,9 +744,8 @@ ErrorCode LinkLayerController::LeSetExtendedAdvertisingData( // HCI command LE_Set_Extended_Scan_Response_Data (Vol 4, Part E § 7.8.55). ErrorCode LinkLayerController::LeSetExtendedScanResponseData( - uint8_t advertising_handle, Operation operation, - FragmentPreference fragment_preference, - const std::vector& scan_response_data) { + uint8_t advertising_handle, Operation operation, FragmentPreference fragment_preference, + const std::vector& scan_response_data) { // Extended advertising commands are disallowed when legacy advertising // commands were used since the last reset. if (!SelectExtendedAdvertising()) { @@ -805,10 +770,9 @@ ErrorCode LinkLayerController::LeSetExtendedScanResponseData( ExtendedAdvertiser& advertiser = extended_advertisers_[advertising_handle]; const AdvertisingEventProperties& advertising_event_properties = - advertiser.advertising_event_properties; + advertiser.advertising_event_properties; uint16_t raw_advertising_event_properties = - ExtendedAdvertiser::GetRawAdvertisingEventProperties( - advertising_event_properties); + ExtendedAdvertiser::GetRawAdvertisingEventProperties(advertising_event_properties); // If the advertising set is non-scannable and the Host uses this // command other than to discard existing data, the Controller shall @@ -825,8 +789,7 @@ ErrorCode LinkLayerController::LeSetExtendedScanResponseData( // either Operation is not 0x03 or the Scan_Response_Data_Length // parameter exceeds 31 octets, the Controller shall // return the error code Invalid HCI Command Parameters (0x12). - if (advertising_event_properties.scannable_ && - advertising_event_properties.legacy_ && + if (advertising_event_properties.scannable_ && advertising_event_properties.legacy_ && (operation != Operation::COMPLETE_ADVERTISEMENT || scan_response_data.size() > max_legacy_advertising_pdu_size)) { INFO(id_, @@ -840,8 +803,7 @@ ErrorCode LinkLayerController::LeSetExtendedScanResponseData( // If Operation is not 0x03 and Scan_Response_Data_Length is zero, the // Controller shall return the error code // Invalid HCI Command Parameters (0x12). - if (operation != Operation::COMPLETE_ADVERTISEMENT && - scan_response_data.empty()) { + if (operation != Operation::COMPLETE_ADVERTISEMENT && scan_response_data.empty()) { INFO(id_, "operation ({:02x}) is not Complete_Advertisement but the" " scan response data is empty", @@ -852,8 +814,7 @@ ErrorCode LinkLayerController::LeSetExtendedScanResponseData( // If advertising is currently enabled for the specified advertising set and // Operation does not have the value 0x03, the Controller shall // return the error code Command Disallowed (0x0C). - if (advertiser.advertising_enable && - operation != Operation::COMPLETE_ADVERTISEMENT) { + if (advertiser.advertising_enable && operation != Operation::COMPLETE_ADVERTISEMENT) { INFO(id_, "operation ({:02x}) is used but advertising is enabled for the" " specified advertising set", @@ -865,8 +826,7 @@ ErrorCode LinkLayerController::LeSetExtendedScanResponseData( // advertising is currently enabled for the specified advertising set, // and Scan_Response_Data_Length is zero, the Controller shall return // the error code Command Disallowed (0x0C). - if (advertiser.advertising_enable && - advertising_event_properties.scannable_ && + if (advertiser.advertising_enable && advertising_event_properties.scannable_ && !advertising_event_properties.legacy_ && scan_response_data.empty()) { INFO(id_, "advertising_event_properties ({:02x}) is scannable extended," @@ -879,8 +839,7 @@ ErrorCode LinkLayerController::LeSetExtendedScanResponseData( switch (operation) { case Operation::INTERMEDIATE_FRAGMENT: advertiser.scan_response_data.insert(advertiser.scan_response_data.end(), - scan_response_data.begin(), - scan_response_data.end()); + scan_response_data.begin(), scan_response_data.end()); advertiser.partial_scan_response_data = true; break; @@ -891,8 +850,7 @@ ErrorCode LinkLayerController::LeSetExtendedScanResponseData( case Operation::LAST_FRAGMENT: advertiser.scan_response_data.insert(advertiser.scan_response_data.end(), - scan_response_data.begin(), - scan_response_data.end()); + scan_response_data.begin(), scan_response_data.end()); advertiser.partial_scan_response_data = false; break; @@ -918,8 +876,7 @@ ErrorCode LinkLayerController::LeSetExtendedScanResponseData( // or the amount of memory currently available, all the data shall be // discarded and the Controller shall return the error code // Memory Capacity Exceeded (0x07). - if (advertiser.scan_response_data.size() > - properties_.le_max_advertising_data_length) { + if (advertiser.scan_response_data.size() > properties_.le_max_advertising_data_length) { INFO(id_, "the combined length of the scan response data exceeds the" " advertising set capacity"); @@ -936,8 +893,7 @@ ErrorCode LinkLayerController::LeSetExtendedScanResponseData( // discarded and the Controller shall return the error code // Packet Too Long (0x45). If advertising on the LE Coded PHY, // the S=8 coding shall be assumed. - if (advertiser.scan_response_data.size() > - max_extended_advertising_pdu_size) { + if (advertiser.scan_response_data.size() > max_extended_advertising_pdu_size) { INFO(id_, "the scan response data contained in the set is larger than the" " available PDU capacity"); @@ -951,7 +907,7 @@ ErrorCode LinkLayerController::LeSetExtendedScanResponseData( // HCI command LE_Set_Extended_Advertising_Enable (Vol 4, Part E § 7.8.56). ErrorCode LinkLayerController::LeSetExtendedAdvertisingEnable( - bool enable, const std::vector& sets) { + bool enable, const std::vector& sets) { // Extended advertising commands are disallowed when legacy advertising // commands were used since the last reset. if (!SelectExtendedAdvertising()) { @@ -968,18 +924,15 @@ ErrorCode LinkLayerController::LeSetExtendedAdvertisingEnable( // Advertising_Handle[i] arrayed parameter, then the Controller shall return // the error code Invalid HCI Command Parameters (0x12). if (used_advertising_handles[set.advertising_handle_]) { - INFO(id_, "advertising handle {:02x} is added more than once", - set.advertising_handle_); + INFO(id_, "advertising handle {:02x} is added more than once", set.advertising_handle_); return ErrorCode::INVALID_HCI_COMMAND_PARAMETERS; } // If the advertising set corresponding to the Advertising_Handle[i] // parameter does not exist, then the Controller shall return the error code // Unknown Advertising Identifier (0x42). - if (extended_advertisers_.find(set.advertising_handle_) == - extended_advertisers_.end()) { - INFO(id_, "advertising handle {:02x} is not defined", - set.advertising_handle_); + if (extended_advertisers_.find(set.advertising_handle_) == extended_advertisers_.end()) { + INFO(id_, "advertising handle {:02x} is not defined", set.advertising_handle_); return ErrorCode::UNKNOWN_ADVERTISING_IDENTIFIER; } @@ -1013,25 +966,21 @@ ErrorCode LinkLayerController::LeSetExtendedAdvertisingEnable( // Validate the advertising parameters before enabling any set. for (auto& set : sets) { - ExtendedAdvertiser& advertiser = - extended_advertisers_[set.advertising_handle_]; + ExtendedAdvertiser& advertiser = extended_advertisers_[set.advertising_handle_]; const AdvertisingEventProperties& advertising_event_properties = - advertiser.advertising_event_properties; + advertiser.advertising_event_properties; bool extended_advertising = !advertising_event_properties.legacy_; bool connectable_advertising = advertising_event_properties.connectable_; bool scannable_advertising = advertising_event_properties.scannable_; bool directed_advertising = advertising_event_properties.directed_; - bool high_duty_cycle_advertising = - advertising_event_properties.high_duty_cycle_; + bool high_duty_cycle_advertising = advertising_event_properties.high_duty_cycle_; // If the advertising is high duty cycle connectable directed advertising, // then Duration[i] shall be less than or equal to 1.28 seconds and shall // not be equal to 0. - std::chrono::milliseconds duration = - std::chrono::milliseconds(set.duration_ * 10); - if (connectable_advertising && directed_advertising && - high_duty_cycle_advertising && + std::chrono::milliseconds duration = std::chrono::milliseconds(set.duration_ * 10); + if (connectable_advertising && directed_advertising && high_duty_cycle_advertising && (set.duration_ == 0 || duration > adv_direct_ind_high_timeout)) { INFO(id_, "extended advertising is high duty cycle connectable directed" @@ -1042,8 +991,7 @@ ErrorCode LinkLayerController::LeSetExtendedAdvertisingEnable( // If the advertising set contains partial advertising data or partial // scan response data, the Controller shall return the error code // Command Disallowed (0x0C). - if (advertiser.partial_advertising_data || - advertiser.partial_scan_response_data) { + if (advertiser.partial_advertising_data || advertiser.partial_scan_response_data) { INFO(id_, "advertising set contains partial advertising" " or scan response data"); @@ -1053,8 +1001,7 @@ ErrorCode LinkLayerController::LeSetExtendedAdvertisingEnable( // If the advertising set uses scannable extended advertising PDUs and no // scan response data is currently provided, the Controller shall return the // error code Command Disallowed (0x0C). - if (extended_advertising && scannable_advertising && - advertiser.scan_response_data.empty()) { + if (extended_advertising && scannable_advertising && advertiser.scan_response_data.empty()) { INFO(id_, "advertising set uses scannable extended advertising PDUs" " but no scan response data is provided"); @@ -1067,8 +1014,7 @@ ErrorCode LinkLayerController::LeSetExtendedAdvertisingEnable( // Invalid HCI Command Parameters (0x12). if (extended_advertising && connectable_advertising && advertiser.advertising_data.size() > - ExtendedAdvertiser::GetMaxAdvertisingDataLength( - advertising_event_properties)) { + ExtendedAdvertiser::GetMaxAdvertisingDataLength(advertising_event_properties)) { INFO(id_, "advertising set uses connectable extended advertising PDUs" " but the advertising data does not fit in AUX_ADV_IND PDUs"); @@ -1081,25 +1027,22 @@ ErrorCode LinkLayerController::LeSetExtendedAdvertisingEnable( // advertising segment consistent with the chosen advertising interval, // the Controller shall return the error code Packet Too Long (0x45). // If advertising on the LE Coded PHY, the S=8 coding shall be assumed. - if (extended_advertising && (advertiser.advertising_data.size() > - max_extended_advertising_pdu_size || - advertiser.scan_response_data.size() > - max_extended_advertising_pdu_size)) { + if (extended_advertising && + (advertiser.advertising_data.size() > max_extended_advertising_pdu_size || + advertiser.scan_response_data.size() > max_extended_advertising_pdu_size)) { INFO(id_, "advertising set uses extended advertising PDUs" " but the advertising data does not fit in advertising PDUs"); return ErrorCode::PACKET_TOO_LONG; } - AddressWithType peer_address = PeerDeviceAddress( - advertiser.peer_address, advertiser.peer_address_type); - AddressWithType public_address{address_, - AddressType::PUBLIC_DEVICE_ADDRESS}; - AddressWithType random_address{ - advertiser.random_address.value_or(Address::kEmpty), - AddressType::RANDOM_DEVICE_ADDRESS}; + AddressWithType peer_address = + PeerDeviceAddress(advertiser.peer_address, advertiser.peer_address_type); + AddressWithType public_address{address_, AddressType::PUBLIC_DEVICE_ADDRESS}; + AddressWithType random_address{advertiser.random_address.value_or(Address::kEmpty), + AddressType::RANDOM_DEVICE_ADDRESS}; std::optional resolvable_address = - GenerateResolvablePrivateAddress(peer_address, IrkSelection::Local); + GenerateResolvablePrivateAddress(peer_address, IrkSelection::Local); // TODO: additional checks would apply in the case of a LE only Controller // with no configured public device address. @@ -1116,18 +1059,16 @@ ErrorCode LinkLayerController::LeSetExtendedAdvertisingEnable( // command, the Controller shall return the error code // Invalid HCI Command Parameters (0x12). if (random_address.GetAddress() == Address::kEmpty) { - INFO( - id_, - "own_address_type is Random_Device_Address but the Random_Address" - " has not been initialized"); + INFO(id_, + "own_address_type is Random_Device_Address but the Random_Address" + " has not been initialized"); return ErrorCode::INVALID_HCI_COMMAND_PARAMETERS; } advertiser.advertising_address = random_address; break; case OwnAddressType::RESOLVABLE_OR_PUBLIC_ADDRESS: - advertiser.advertising_address = - resolvable_address.value_or(public_address); + advertiser.advertising_address = resolvable_address.value_or(public_address); break; case OwnAddressType::RESOLVABLE_OR_RANDOM_ADDRESS: @@ -1159,23 +1100,19 @@ ErrorCode LinkLayerController::LeSetExtendedAdvertisingEnable( // Address when entering the Advertising State and using connectable // directed events. if (advertiser.IsDirected()) { - advertiser.target_address = - GenerateResolvablePrivateAddress(peer_address, IrkSelection::Peer) - .value_or(peer_address); + advertiser.target_address = GenerateResolvablePrivateAddress(peer_address, IrkSelection::Peer) + .value_or(peer_address); } } for (auto& set : sets) { - ExtendedAdvertiser& advertiser = - extended_advertisers_[set.advertising_handle_]; + ExtendedAdvertiser& advertiser = extended_advertisers_[set.advertising_handle_]; - advertiser.max_extended_advertising_events = - set.max_extended_advertising_events_; + advertiser.max_extended_advertising_events = set.max_extended_advertising_events_; advertiser.num_completed_extended_advertising_events = 0; advertiser.Enable(); if (set.duration_ > 0) { - std::chrono::milliseconds duration = - std::chrono::milliseconds(set.duration_ * 10); + std::chrono::milliseconds duration = std::chrono::milliseconds(set.duration_ * 10); advertiser.timeout = std::chrono::steady_clock::now() + duration; } else { advertiser.timeout.reset(); @@ -1186,8 +1123,7 @@ ErrorCode LinkLayerController::LeSetExtendedAdvertisingEnable( } // HCI command LE_Remove_Advertising_Set (Vol 4, Part E § 7.8.59). -ErrorCode LinkLayerController::LeRemoveAdvertisingSet( - uint8_t advertising_handle) { +ErrorCode LinkLayerController::LeRemoveAdvertisingSet(uint8_t advertising_handle) { // If the advertising set corresponding to the Advertising_Handle parameter // does not exist, then the Controller shall return the error code // Unknown Advertising Identifier (0x42). @@ -1228,7 +1164,7 @@ ErrorCode LinkLayerController::LeClearAdvertisingSets() { } uint16_t ExtendedAdvertiser::GetMaxAdvertisingDataLength( - const AdvertisingEventProperties& properties) { + const AdvertisingEventProperties& properties) { // The PDU AdvData size is defined in the following sections: // - Vol 6, Part B § 2.3.1.1 ADV_IND // - Vol 6, Part B § 2.3.1.2 ADV_DIRECT_IND @@ -1272,7 +1208,7 @@ uint16_t ExtendedAdvertiser::GetMaxAdvertisingDataLength( } uint16_t ExtendedAdvertiser::GetMaxScanResponseDataLength( - const AdvertisingEventProperties& properties) { + const AdvertisingEventProperties& properties) { // The PDU AdvData size is defined in the following sections: // - Vol 6, Part B § 2.3.2.2 SCAN_RSP // - Vol 6, Part B § 2.3.2.3 AUX_SCAN_RSP @@ -1296,7 +1232,7 @@ uint16_t ExtendedAdvertiser::GetMaxScanResponseDataLength( } uint16_t ExtendedAdvertiser::GetRawAdvertisingEventProperties( - const AdvertisingEventProperties& properties) { + const AdvertisingEventProperties& properties) { uint16_t mask = 0; if (properties.connectable_) { mask |= 0x1; @@ -1328,8 +1264,8 @@ uint16_t ExtendedAdvertiser::GetRawAdvertisingEventProperties( // HCI LE Set Periodic Advertising Parameters command (Vol 4, Part E § 7.8.61). ErrorCode LinkLayerController::LeSetPeriodicAdvertisingParameters( - uint8_t advertising_handle, uint16_t periodic_advertising_interval_min, - uint16_t periodic_advertising_interval_max, bool /*include_tx_power*/) { + uint8_t advertising_handle, uint16_t periodic_advertising_interval_min, + uint16_t periodic_advertising_interval_max, bool /*include_tx_power*/) { // The Advertising_Handle parameter identifies the advertising set whose // periodic advertising parameters are being configured. If the corresponding // advertising set does not already exist, then the Controller shall return @@ -1345,8 +1281,7 @@ ErrorCode LinkLayerController::LeSetPeriodicAdvertisingParameters( // The Periodic_Advertising_Interval_Min parameter shall be less than or // equal to the Periodic_Advertising_Interval_Max parameter. - if (periodic_advertising_interval_min < 0x6 || - periodic_advertising_interval_max < 0x6 || + if (periodic_advertising_interval_min < 0x6 || periodic_advertising_interval_max < 0x6 || periodic_advertising_interval_max < periodic_advertising_interval_min) { INFO(id_, "invalid periodic advertising interval range {:04x} - {:04x}", periodic_advertising_interval_min, periodic_advertising_interval_max); @@ -1390,7 +1325,7 @@ ErrorCode LinkLayerController::LeSetPeriodicAdvertisingParameters( // code Packet Too Long (0x45). if (advertiser.periodic_advertising_data.size() > ExtendedAdvertiser::GetMaxPeriodicAdvertisingDataLength( - slots(periodic_advertising_interval_max))) { + slots(periodic_advertising_interval_max))) { INFO(id_, "the length of the periodic advertising data exceeds the maximum" " that the controller can transmit within the maximum periodic" @@ -1398,15 +1333,14 @@ ErrorCode LinkLayerController::LeSetPeriodicAdvertisingParameters( return ErrorCode::PACKET_TOO_LONG; } - advertiser.periodic_advertising_interval = - slots(periodic_advertising_interval_max); + advertiser.periodic_advertising_interval = slots(periodic_advertising_interval_max); return ErrorCode::SUCCESS; } // HCI LE Set Periodic Advertising Data command (Vol 4, Part E § 7.8.62). ErrorCode LinkLayerController::LeSetPeriodicAdvertisingData( - uint8_t advertising_handle, bluetooth::hci::Operation operation, - const std::vector& advertising_data) { + uint8_t advertising_handle, bluetooth::hci::Operation operation, + const std::vector& advertising_data) { // If the advertising set corresponding to the Advertising_Handle parameter // does not exist, then the Controller shall return the error code // Unknown Advertising Identifier (0x42). @@ -1430,8 +1364,7 @@ ErrorCode LinkLayerController::LeSetPeriodicAdvertisingData( // If periodic advertising is currently enabled for the specified advertising // set and Operation does not have the value 0x03 or 0x04, then the Controller // shall return the error code Command Disallowed (0x0C). - if (advertiser.periodic_advertising_enable && - operation != Operation::COMPLETE_ADVERTISEMENT && + if (advertiser.periodic_advertising_enable && operation != Operation::COMPLETE_ADVERTISEMENT && operation != Operation::UNCHANGED_DATA) { INFO(id_, "periodic advertising is enabled and the operation is not" @@ -1442,8 +1375,7 @@ ErrorCode LinkLayerController::LeSetPeriodicAdvertisingData( // If Operation is not 0x03 or 0x04 and Advertising_Data_Length is zero, // then the Controller shall return the error code // Invalid HCI Command Parameters (0x12). - if (advertising_data.empty() && - operation != Operation::COMPLETE_ADVERTISEMENT && + if (advertising_data.empty() && operation != Operation::COMPLETE_ADVERTISEMENT && operation != Operation::UNCHANGED_DATA) { INFO(id_, "periodic advertising data is empty is enabled and the operation" @@ -1458,22 +1390,19 @@ ErrorCode LinkLayerController::LeSetPeriodicAdvertisingData( // then the Controller shall return the error code // Invalid HCI Command Parameters (0x12). if (operation == Operation::UNCHANGED_DATA && - (!advertiser.periodic_advertising_enable || - advertiser.periodic_advertising_data.empty() || + (!advertiser.periodic_advertising_enable || advertiser.periodic_advertising_data.empty() || !advertising_data.empty())) { - INFO( - id_, - "Unchanged_Data operation is used but periodic advertising is disabled;" - " or the periodic advertising set contains no data;" - " or the advertising data is not empty"); + INFO(id_, + "Unchanged_Data operation is used but periodic advertising is disabled;" + " or the periodic advertising set contains no data;" + " or the advertising data is not empty"); return ErrorCode::INVALID_HCI_COMMAND_PARAMETERS; } switch (operation) { case Operation::INTERMEDIATE_FRAGMENT: - advertiser.periodic_advertising_data.insert( - advertiser.periodic_advertising_data.end(), advertising_data.begin(), - advertising_data.end()); + advertiser.periodic_advertising_data.insert(advertiser.periodic_advertising_data.end(), + advertising_data.begin(), advertising_data.end()); advertiser.partial_periodic_advertising_data = true; break; @@ -1483,9 +1412,8 @@ ErrorCode LinkLayerController::LeSetPeriodicAdvertisingData( break; case Operation::LAST_FRAGMENT: - advertiser.periodic_advertising_data.insert( - advertiser.periodic_advertising_data.end(), advertising_data.begin(), - advertising_data.end()); + advertiser.periodic_advertising_data.insert(advertiser.periodic_advertising_data.end(), + advertising_data.begin(), advertising_data.end()); advertiser.partial_periodic_advertising_data = false; break; @@ -1506,8 +1434,7 @@ ErrorCode LinkLayerController::LeSetPeriodicAdvertisingData( // set identified by the Advertising_Handle parameter or the amount of memory // currently available, all the data shall be discarded and the Controller // shall return the error code Memory Capacity Exceeded (0x07). - if (advertiser.periodic_advertising_data.size() > - properties_.le_max_advertising_data_length) { + if (advertiser.periodic_advertising_data.size() > properties_.le_max_advertising_data_length) { INFO(id_, "the length of the combined periodic advertising data exceeds" " the maximum advertising data length"); @@ -1522,7 +1449,7 @@ ErrorCode LinkLayerController::LeSetPeriodicAdvertisingData( // Controller shall return the error code Packet Too Long (0x45). if (advertiser.periodic_advertising_data.size() > ExtendedAdvertiser::GetMaxPeriodicAdvertisingDataLength( - advertiser.periodic_advertising_interval)) { + advertiser.periodic_advertising_interval)) { INFO(id_, "the length of the combined periodic advertising data exceeds" " the maximum that the controller can transmit within the current" @@ -1536,8 +1463,8 @@ ErrorCode LinkLayerController::LeSetPeriodicAdvertisingData( } // HCI LE Set Periodic Advertising Enable command (Vol 4, Part E § 7.8.63). -ErrorCode LinkLayerController::LeSetPeriodicAdvertisingEnable( - bool enable, bool include_adi, uint8_t advertising_handle) { +ErrorCode LinkLayerController::LeSetPeriodicAdvertisingEnable(bool enable, bool include_adi, + uint8_t advertising_handle) { // If the advertising set corresponding to the Advertising_Handle parameter // does not exist, the Controller shall return the error code Unknown // Advertising Identifier (0x42). @@ -1579,7 +1506,7 @@ ErrorCode LinkLayerController::LeSetPeriodicAdvertisingEnable( // error code Packet Too Long (0x45). if (advertiser.periodic_advertising_data.size() > ExtendedAdvertiser::GetMaxPeriodicAdvertisingDataLength( - advertiser.periodic_advertising_interval)) { + advertiser.periodic_advertising_interval)) { INFO(id_, "the length of the combined periodic advertising data exceeds" " the maximum that the controller can transmit within the current" @@ -1606,8 +1533,8 @@ ErrorCode LinkLayerController::LeSetPeriodicAdvertisingEnable( // Periodic Advertising ADI Support feature, the Controller shall return an // error which should use the error code Unsupported Feature or // Parameter Value (0x11). - if (include_adi && !properties_.SupportsLLFeature( - LLFeaturesBits::PERIODIC_ADVERTISING_ADI_SUPPORT)) { + if (include_adi && + !properties_.SupportsLLFeature(LLFeaturesBits::PERIODIC_ADVERTISING_ADI_SUPPORT)) { INFO(id_, "include ADI is true but the controller does not support the" " Periodic Advertising ADI Supported feature", @@ -1620,7 +1547,7 @@ ErrorCode LinkLayerController::LeSetPeriodicAdvertisingEnable( } uint16_t ExtendedAdvertiser::GetMaxPeriodicAdvertisingDataLength( - slots /*periodic_advertising_interval*/) { + slots /*periodic_advertising_interval*/) { // TODO: evaluate the maximum length of the advertising PDU that can // be physically sent in the advertising interval. return max_extended_advertising_pdu_size; @@ -1665,9 +1592,8 @@ void LinkLayerController::LeAdvertising() { #endif if (IsLeEventUnmasked(SubeventCode::CONNECTION_COMPLETE)) { send_event_(bluetooth::hci::LeConnectionCompleteBuilder::Create( - ErrorCode::ADVERTISING_TIMEOUT, 0, Role::CENTRAL, - AddressType::PUBLIC_DEVICE_ADDRESS, Address(), 0, 0, 0, - ClockAccuracy::PPM_500)); + ErrorCode::ADVERTISING_TIMEOUT, 0, Role::CENTRAL, AddressType::PUBLIC_DEVICE_ADDRESS, + Address(), 0, 0, 0, ClockAccuracy::PPM_500)); } } @@ -1676,8 +1602,7 @@ void LinkLayerController::LeAdvertising() { // Generate Link Layer Advertising events when advertising is enabled // and a full interval has passed since the last event. if (legacy_advertiser_.IsEnabled() && now >= legacy_advertiser_.next_event) { - legacy_advertiser_.next_event = - now + legacy_advertiser_.advertising_interval; + legacy_advertiser_.next_event = now + legacy_advertiser_.advertising_interval; model::packets::LegacyAdvertisingType type; bool attach_advertising_data = true; switch (legacy_advertiser_.advertising_type) { @@ -1697,18 +1622,17 @@ void LinkLayerController::LeAdvertising() { break; } - SendLeLinkLayerPacket( - model::packets::LeLegacyAdvertisingPduBuilder::Create( - legacy_advertiser_.advertising_address.GetAddress(), - legacy_advertiser_.target_address.GetAddress(), - static_cast( - legacy_advertiser_.advertising_address.GetAddressType()), - static_cast( - legacy_advertiser_.target_address.GetAddressType()), - type, - attach_advertising_data ? legacy_advertiser_.advertising_data - : std::vector{}), - properties_.le_advertising_physical_channel_tx_power); + SendLeLinkLayerPacket(model::packets::LeLegacyAdvertisingPduBuilder::Create( + legacy_advertiser_.advertising_address.GetAddress(), + legacy_advertiser_.target_address.GetAddress(), + static_cast( + legacy_advertiser_.advertising_address.GetAddressType()), + static_cast( + legacy_advertiser_.target_address.GetAddressType()), + type, + attach_advertising_data ? legacy_advertiser_.advertising_data + : std::vector{}), + properties_.le_advertising_physical_channel_tx_power); } for (auto& [_, advertiser] : extended_advertisers_) { @@ -1730,9 +1654,9 @@ void LinkLayerController::LeAdvertising() { advertiser.Disable(); bool high_duty_cycle_connectable_directed_advertising = - advertiser.advertising_event_properties.directed_ && - advertiser.advertising_event_properties.connectable_ && - advertiser.advertising_event_properties.high_duty_cycle_; + advertiser.advertising_event_properties.directed_ && + advertiser.advertising_event_properties.connectable_ && + advertiser.advertising_event_properties.high_duty_cycle_; // Note: HCI_LE_Connection_Complete is not sent if the // HCI_LE_Enhanced_Connection_Complete event (see Section 7.7.65.10) @@ -1740,15 +1664,14 @@ void LinkLayerController::LeAdvertising() { if (high_duty_cycle_connectable_directed_advertising && IsLeEventUnmasked(SubeventCode::ENHANCED_CONNECTION_COMPLETE)) { send_event_(bluetooth::hci::LeEnhancedConnectionCompleteBuilder::Create( - ErrorCode::ADVERTISING_TIMEOUT, 0, Role::CENTRAL, - AddressType::PUBLIC_DEVICE_ADDRESS, Address(), Address(), Address(), - 0, 0, 0, ClockAccuracy::PPM_500)); + ErrorCode::ADVERTISING_TIMEOUT, 0, Role::CENTRAL, + AddressType::PUBLIC_DEVICE_ADDRESS, Address(), Address(), Address(), 0, 0, 0, + ClockAccuracy::PPM_500)); } else if (high_duty_cycle_connectable_directed_advertising && IsLeEventUnmasked(SubeventCode::CONNECTION_COMPLETE)) { send_event_(bluetooth::hci::LeConnectionCompleteBuilder::Create( - ErrorCode::ADVERTISING_TIMEOUT, 0, Role::CENTRAL, - AddressType::PUBLIC_DEVICE_ADDRESS, Address(), 0, 0, 0, - ClockAccuracy::PPM_500)); + ErrorCode::ADVERTISING_TIMEOUT, 0, Role::CENTRAL, + AddressType::PUBLIC_DEVICE_ADDRESS, Address(), 0, 0, 0, ClockAccuracy::PPM_500)); } if (IsLeEventUnmasked(SubeventCode::ADVERTISING_SET_TERMINATED)) { @@ -1756,18 +1679,18 @@ void LinkLayerController::LeAdvertising() { // only when Max_Extended_Advertising_Events was configured as // non-zero in the advertising parameters. uint8_t num_completed_extended_advertising_events = - advertiser.max_extended_advertising_events != 0 - ? advertiser.num_completed_extended_advertising_events - : 0; + advertiser.max_extended_advertising_events != 0 + ? advertiser.num_completed_extended_advertising_events + : 0; send_event_(bluetooth::hci::LeAdvertisingSetTerminatedBuilder::Create( - ErrorCode::ADVERTISING_TIMEOUT, advertiser.advertising_handle, 0, - num_completed_extended_advertising_events)); + ErrorCode::ADVERTISING_TIMEOUT, advertiser.advertising_handle, 0, + num_completed_extended_advertising_events)); } } if (advertiser.IsEnabled() && advertiser.max_extended_advertising_events && advertiser.num_completed_extended_advertising_events >= - advertiser.max_extended_advertising_events) { + advertiser.max_extended_advertising_events) { // If the Max_Extended_Advertising_Events[i] parameter is set to a value // other than 0x00, an HCI_LE_Advertising_Set_Terminated event shall be // generated when the maximum number of extended advertising events has @@ -1777,8 +1700,8 @@ void LinkLayerController::LeAdvertising() { if (IsLeEventUnmasked(SubeventCode::ADVERTISING_SET_TERMINATED)) { send_event_(bluetooth::hci::LeAdvertisingSetTerminatedBuilder::Create( - ErrorCode::ADVERTISING_TIMEOUT, advertiser.advertising_handle, 0, - advertiser.num_completed_extended_advertising_events)); + ErrorCode::ADVERTISING_TIMEOUT, advertiser.advertising_handle, 0, + advertiser.num_completed_extended_advertising_events)); } } @@ -1793,10 +1716,10 @@ void LinkLayerController::LeAdvertising() { if (advertiser.advertising_event_properties.legacy_) { model::packets::LegacyAdvertisingType type; uint16_t raw_advertising_event_properties = - ExtendedAdvertiser::GetRawAdvertisingEventProperties( - advertiser.advertising_event_properties); - switch (static_cast( - raw_advertising_event_properties & 0xf)) { + ExtendedAdvertiser::GetRawAdvertisingEventProperties( + advertiser.advertising_event_properties); + switch (static_cast(raw_advertising_event_properties & + 0xf)) { case LegacyAdvertisingEventProperties::ADV_IND: type = model::packets::LegacyAdvertisingType::ADV_IND; break; @@ -1811,43 +1734,39 @@ void LinkLayerController::LeAdvertising() { type = model::packets::LegacyAdvertisingType::ADV_NONCONN_IND; break; default: - FATAL( - id_, - "unexpected raw advertising event properties;" - " please check the extended advertising parameter validation"); + FATAL(id_, + "unexpected raw advertising event properties;" + " please check the extended advertising parameter validation"); break; } - SendLeLinkLayerPacket( - model::packets::LeLegacyAdvertisingPduBuilder::Create( - advertiser.advertising_address.GetAddress(), - advertiser.target_address.GetAddress(), - static_cast( - advertiser.advertising_address.GetAddressType()), - static_cast( - advertiser.target_address.GetAddressType()), - type, advertiser.advertising_data), - advertiser.advertising_tx_power); + SendLeLinkLayerPacket(model::packets::LeLegacyAdvertisingPduBuilder::Create( + advertiser.advertising_address.GetAddress(), + advertiser.target_address.GetAddress(), + static_cast( + advertiser.advertising_address.GetAddressType()), + static_cast( + advertiser.target_address.GetAddressType()), + type, advertiser.advertising_data), + advertiser.advertising_tx_power); } else { SendLeLinkLayerPacket( - model::packets::LeExtendedAdvertisingPduBuilder::Create( - advertiser.advertising_address.GetAddress(), - advertiser.target_address.GetAddress(), - static_cast( - advertiser.advertising_address.GetAddressType()), - static_cast( - advertiser.target_address.GetAddressType()), - advertiser.advertising_event_properties.connectable_, - advertiser.advertising_event_properties.scannable_, - advertiser.advertising_event_properties.directed_, - advertiser.advertising_sid, advertiser.advertising_tx_power, - static_cast( - advertiser.primary_advertising_phy), - static_cast( - advertiser.secondary_advertising_phy), - advertiser.periodic_advertising_interval.count(), - advertiser.advertising_data), - advertiser.advertising_tx_power); + model::packets::LeExtendedAdvertisingPduBuilder::Create( + advertiser.advertising_address.GetAddress(), + advertiser.target_address.GetAddress(), + static_cast( + advertiser.advertising_address.GetAddressType()), + static_cast( + advertiser.target_address.GetAddressType()), + advertiser.advertising_event_properties.connectable_, + advertiser.advertising_event_properties.scannable_, + advertiser.advertising_event_properties.directed_, + advertiser.advertising_sid, advertiser.advertising_tx_power, + static_cast(advertiser.primary_advertising_phy), + static_cast(advertiser.secondary_advertising_phy), + advertiser.periodic_advertising_interval.count(), + advertiser.advertising_data), + advertiser.advertising_tx_power); } } @@ -1855,19 +1774,16 @@ void LinkLayerController::LeAdvertising() { // Generate Link Layer Advertising events when advertising is enabled // and a full interval has passed since the last event. - if (advertiser.IsPeriodicEnabled() && - now >= advertiser.next_periodic_event) { - advertiser.next_periodic_event += - advertiser.periodic_advertising_interval; - SendLeLinkLayerPacket( - model::packets::LePeriodicAdvertisingPduBuilder::Create( - advertiser.advertising_address.GetAddress(), Address(), - static_cast( - advertiser.advertising_address.GetAddressType()), - advertiser.advertising_sid, advertiser.advertising_tx_power, - advertiser.periodic_advertising_interval.count(), - advertiser.periodic_advertising_data), - advertiser.advertising_tx_power); + if (advertiser.IsPeriodicEnabled() && now >= advertiser.next_periodic_event) { + advertiser.next_periodic_event += advertiser.periodic_advertising_interval; + SendLeLinkLayerPacket(model::packets::LePeriodicAdvertisingPduBuilder::Create( + advertiser.advertising_address.GetAddress(), Address(), + static_cast( + advertiser.advertising_address.GetAddressType()), + advertiser.advertising_sid, advertiser.advertising_tx_power, + advertiser.periodic_advertising_interval.count(), + advertiser.periodic_advertising_data), + advertiser.advertising_tx_power); } } } diff --git a/tools/rootcanal/model/controller/le_advertiser.h b/tools/rootcanal/model/controller/le_advertiser.h index cef651642b1..f3653700354 100644 --- a/tools/rootcanal/model/controller/le_advertiser.h +++ b/tools/rootcanal/model/controller/le_advertiser.h @@ -29,8 +29,7 @@ namespace rootcanal { // Duration type for slots (increments of 625us). -using slots = - std::chrono::duration>; +using slots = std::chrono::duration>; // User defined literal for slots, e.g. `0x800_slots` slots operator"" _slots(unsigned long long count); @@ -39,7 +38,7 @@ using namespace bluetooth::hci; // Advertising interface common to legacy and extended advertisers. class Advertiser { - public: +public: Advertiser() = default; ~Advertiser() = default; @@ -51,10 +50,8 @@ class Advertiser { // HCI properties. bool advertising_enable{false}; - AddressWithType advertising_address{Address::kEmpty, - AddressType::PUBLIC_DEVICE_ADDRESS}; - AddressWithType target_address{Address::kEmpty, - AddressType::PUBLIC_DEVICE_ADDRESS}; + AddressWithType advertising_address{Address::kEmpty, AddressType::PUBLIC_DEVICE_ADDRESS}; + AddressWithType target_address{Address::kEmpty, AddressType::PUBLIC_DEVICE_ADDRESS}; // Time keeping. std::chrono::steady_clock::time_point next_event{}; @@ -64,7 +61,7 @@ class Advertiser { // Implement the unique legacy advertising instance. // For extended advertising check the ExtendedAdvertiser class. class LegacyAdvertiser : public Advertiser { - public: +public: LegacyAdvertiser() = default; ~LegacyAdvertiser() = default; @@ -91,12 +88,10 @@ class LegacyAdvertiser : public Advertiser { slots advertising_interval{0x0800}; AdvertisingType advertising_type{AdvertisingType::ADV_IND}; OwnAddressType own_address_type{OwnAddressType::PUBLIC_DEVICE_ADDRESS}; - PeerAddressType peer_address_type{ - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS}; + PeerAddressType peer_address_type{PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS}; Address peer_address{}; uint8_t advertising_channel_map{0x07}; - AdvertisingFilterPolicy advertising_filter_policy{ - AdvertisingFilterPolicy::ALL_DEVICES}; + AdvertisingFilterPolicy advertising_filter_policy{AdvertisingFilterPolicy::ALL_DEVICES}; std::vector advertising_data{}; std::vector scan_response_data{}; }; @@ -105,9 +100,8 @@ class LegacyAdvertiser : public Advertiser { // The configuration is set by the extended advertising commands; // for the legacy advertiser check the LegacyAdvertiser class. class ExtendedAdvertiser : public Advertiser { - public: - ExtendedAdvertiser(uint8_t advertising_handle = 0) - : advertising_handle(advertising_handle) {} +public: + ExtendedAdvertiser(uint8_t advertising_handle = 0) : advertising_handle(advertising_handle) {} ~ExtendedAdvertiser() = default; void Enable() { @@ -130,9 +124,7 @@ class ExtendedAdvertiser : public Advertiser { bool IsPeriodicEnabled() const { return periodic_advertising_enable_latch; } bool IsScannable() const { return advertising_event_properties.scannable_; } - bool IsConnectable() const { - return advertising_event_properties.connectable_; - } + bool IsConnectable() const { return advertising_event_properties.connectable_; } bool IsDirected() const { return advertising_event_properties.directed_; } @@ -192,23 +184,19 @@ class ExtendedAdvertiser : public Advertiser { // Compute the maximum advertising data payload size for the selected // advertising event properties. The advertising data is not present if // 0 is returned. - static uint16_t GetMaxAdvertisingDataLength( - const AdvertisingEventProperties& properties); + static uint16_t GetMaxAdvertisingDataLength(const AdvertisingEventProperties& properties); // Compute the maximum scan response data payload size for the selected // advertising event properties. The scan response data is not present if // 0 is returned. - static uint16_t GetMaxScanResponseDataLength( - const AdvertisingEventProperties& properties); + static uint16_t GetMaxScanResponseDataLength(const AdvertisingEventProperties& properties); // Reconstitute the raw Advertising_Event_Properties bitmask. - static uint16_t GetRawAdvertisingEventProperties( - const AdvertisingEventProperties& properties); + static uint16_t GetRawAdvertisingEventProperties(const AdvertisingEventProperties& properties); // Compute the maximum periodic advertising data payload size for the // selected periodic advertising interval. - static uint16_t GetMaxPeriodicAdvertisingDataLength( - slots periodic_advertising_interval); + static uint16_t GetMaxPeriodicAdvertisingDataLength(slots periodic_advertising_interval); }; } // namespace rootcanal diff --git a/tools/rootcanal/model/controller/link_layer_controller.cc b/tools/rootcanal/model/controller/link_layer_controller.cc index c1bff2b4b58..047ea9c96ee 100644 --- a/tools/rootcanal/model/controller/link_layer_controller.cc +++ b/tools/rootcanal/model/controller/link_layer_controller.cc @@ -64,8 +64,7 @@ constexpr milliseconds kPageInterval(1000); const Address& LinkLayerController::GetAddress() const { return address_; } -AddressWithType PeerDeviceAddress(Address address, - PeerAddressType peer_address_type) { +AddressWithType PeerDeviceAddress(Address address, PeerAddressType peer_address_type) { switch (peer_address_type) { case PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS: return AddressWithType(address, AddressType::PUBLIC_DEVICE_ADDRESS); @@ -74,8 +73,7 @@ AddressWithType PeerDeviceAddress(Address address, } } -AddressWithType PeerIdentityAddress(Address address, - PeerAddressType peer_address_type) { +AddressWithType PeerIdentityAddress(Address address, PeerAddressType peer_address_type) { switch (peer_address_type) { case PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS: return AddressWithType(address, AddressType::PUBLIC_IDENTITY_ADDRESS); @@ -91,8 +89,7 @@ bool LinkLayerController::IsEventUnmasked(EventCode event) const { bool LinkLayerController::IsLeEventUnmasked(SubeventCode subevent) const { uint64_t bit = UINT64_C(1) << (static_cast(subevent) - 1); - return IsEventUnmasked(EventCode::LE_META_EVENT) && - (le_event_mask_ & bit) != 0; + return IsEventUnmasked(EventCode::LE_META_EVENT) && (le_event_mask_ & bit) != 0; } bool LinkLayerController::FilterAcceptListBusy() { @@ -101,14 +98,13 @@ bool LinkLayerController::FilterAcceptListBusy() { // advertising is enabled, if (legacy_advertiser_.IsEnabled() && legacy_advertiser_.advertising_filter_policy != - bluetooth::hci::AdvertisingFilterPolicy::ALL_DEVICES) { + bluetooth::hci::AdvertisingFilterPolicy::ALL_DEVICES) { return true; } for (auto const& [_, advertiser] : extended_advertisers_) { - if (advertiser.IsEnabled() && - advertiser.advertising_filter_policy != - bluetooth::hci::AdvertisingFilterPolicy::ALL_DEVICES) { + if (advertiser.IsEnabled() && advertiser.advertising_filter_policy != + bluetooth::hci::AdvertisingFilterPolicy::ALL_DEVICES) { return true; } } @@ -117,10 +113,9 @@ bool LinkLayerController::FilterAcceptListBusy() { // is enabled, if (scanner_.IsEnabled() && (scanner_.scan_filter_policy == - bluetooth::hci::LeScanningFilterPolicy::FILTER_ACCEPT_LIST_ONLY || - scanner_.scan_filter_policy == - bluetooth::hci::LeScanningFilterPolicy:: - FILTER_ACCEPT_LIST_AND_INITIATORS_IDENTITY)) { + bluetooth::hci::LeScanningFilterPolicy::FILTER_ACCEPT_LIST_ONLY || + scanner_.scan_filter_policy == bluetooth::hci::LeScanningFilterPolicy:: + FILTER_ACCEPT_LIST_AND_INITIATORS_IDENTITY)) { return true; } @@ -129,15 +124,15 @@ bool LinkLayerController::FilterAcceptListBusy() { // command is pending. if (initiator_.IsEnabled() && initiator_.initiator_filter_policy == - bluetooth::hci::InitiatorFilterPolicy::USE_FILTER_ACCEPT_LIST) { + bluetooth::hci::InitiatorFilterPolicy::USE_FILTER_ACCEPT_LIST) { return true; } return false; } -bool LinkLayerController::LeFilterAcceptListContainsDevice( - FilterAcceptListAddressType address_type, Address address) { +bool LinkLayerController::LeFilterAcceptListContainsDevice(FilterAcceptListAddressType address_type, + Address address) { for (auto const& entry : le_filter_accept_list_) { if (entry.address_type == address_type && (address_type == FilterAcceptListAddressType::ANONYMOUS_ADVERTISERS || @@ -150,8 +145,8 @@ bool LinkLayerController::LeFilterAcceptListContainsDevice( } bool LinkLayerController::LePeriodicAdvertiserListContainsDevice( - bluetooth::hci::AdvertiserAddressType advertiser_address_type, - Address advertiser_address, uint8_t advertising_sid) { + bluetooth::hci::AdvertiserAddressType advertiser_address_type, Address advertiser_address, + uint8_t advertising_sid) { for (auto const& entry : le_periodic_advertiser_list_) { if (entry.advertiser_address_type == advertiser_address_type && entry.advertiser_address == advertiser_address && @@ -163,8 +158,7 @@ bool LinkLayerController::LePeriodicAdvertiserListContainsDevice( return false; } -bool LinkLayerController::LeFilterAcceptListContainsDevice( - AddressWithType address) { +bool LinkLayerController::LeFilterAcceptListContainsDevice(AddressWithType address) { FilterAcceptListAddressType address_type; switch (address.GetAddressType()) { case AddressType::PUBLIC_DEVICE_ADDRESS: @@ -207,8 +201,7 @@ bool LinkLayerController::ResolvingListBusy() { return false; } -std::optional LinkLayerController::ResolvePrivateAddress( - AddressWithType address) { +std::optional LinkLayerController::ResolvePrivateAddress(AddressWithType address) { if (!address.IsRpa()) { return address; } @@ -223,23 +216,20 @@ std::optional LinkLayerController::ResolvePrivateAddress( // with the returned identity address. entry.peer_resolvable_address = address.GetAddress(); - return PeerDeviceAddress(entry.peer_identity_address, - entry.peer_identity_address_type); + return PeerDeviceAddress(entry.peer_identity_address, entry.peer_identity_address_type); } } return {}; } -bool LinkLayerController::ResolveTargetA(AddressWithType target_a, - AddressWithType adv_a) { +bool LinkLayerController::ResolveTargetA(AddressWithType target_a, AddressWithType adv_a) { if (!le_resolving_list_enabled_) { return false; } for (auto const& entry : le_resolving_list_) { - if (adv_a == PeerDeviceAddress(entry.peer_identity_address, - entry.peer_identity_address_type) && + if (adv_a == PeerDeviceAddress(entry.peer_identity_address, entry.peer_identity_address_type) && target_a.IsRpaThatMatchesIrk(entry.local_irk)) { return true; } @@ -248,8 +238,7 @@ bool LinkLayerController::ResolveTargetA(AddressWithType target_a, return false; } -bool LinkLayerController::ValidateTargetA(AddressWithType target_a, - AddressWithType adv_a) { +bool LinkLayerController::ValidateTargetA(AddressWithType target_a, AddressWithType adv_a) { if (IsLocalPublicOrRandomAddress(target_a)) { return true; } @@ -259,14 +248,13 @@ bool LinkLayerController::ValidateTargetA(AddressWithType target_a, return false; } -std::optional -LinkLayerController::GenerateResolvablePrivateAddress(AddressWithType address, - IrkSelection irk) { +std::optional LinkLayerController::GenerateResolvablePrivateAddress( + AddressWithType address, IrkSelection irk) { for (auto& entry : le_resolving_list_) { if (address.GetAddress() == entry.peer_identity_address && address.ToPeerAddressType() == entry.peer_identity_address_type) { std::array const& used_irk = - irk == IrkSelection::Local ? entry.local_irk : entry.peer_irk; + irk == IrkSelection::Local ? entry.local_irk : entry.peer_irk; Address local_resolvable_address = generate_rpa(used_irk); // Update the local resolvable address used for the peer @@ -275,8 +263,7 @@ LinkLayerController::GenerateResolvablePrivateAddress(AddressWithType address, entry.local_resolvable_address = local_resolvable_address; } - return AddressWithType{local_resolvable_address, - AddressType::RANDOM_DEVICE_ADDRESS}; + return AddressWithType{local_resolvable_address, AddressType::RANDOM_DEVICE_ADDRESS}; } } @@ -288,8 +275,7 @@ LinkLayerController::GenerateResolvablePrivateAddress(AddressWithType address, // ============================================================================= // HCI Read Rssi command (Vol 4, Part E § 7.5.4). -ErrorCode LinkLayerController::ReadRssi(uint16_t connection_handle, - int8_t* rssi) { +ErrorCode LinkLayerController::ReadRssi(uint16_t connection_handle, int8_t* rssi) { // Not documented: If the connection handle is not found, the Controller // shall return the error code Unknown Connection Identifier (0x02). if (!connections_.HasHandle(connection_handle)) { @@ -310,8 +296,7 @@ ErrorCode LinkLayerController::LeSetRandomAddress(Address random_address) { // If the Host issues this command when any of advertising (created using // legacy advertising commands), scanning, or initiating are enabled, // the Controller shall return the error code Command Disallowed (0x0C). - if (legacy_advertiser_.IsEnabled() || scanner_.IsEnabled() || - initiator_.IsEnabled()) { + if (legacy_advertiser_.IsEnabled() || scanner_.IsEnabled() || initiator_.IsEnabled()) { INFO(id_, "advertising, scanning or initiating are currently active"); return ErrorCode::COMMAND_DISALLOWED; } @@ -326,8 +311,7 @@ ErrorCode LinkLayerController::LeSetRandomAddress(Address random_address) { } // HCI LE Set Host Feature command (Vol 4, Part E § 7.8.45). -ErrorCode LinkLayerController::LeSetResolvablePrivateAddressTimeout( - uint16_t rpa_timeout) { +ErrorCode LinkLayerController::LeSetResolvablePrivateAddressTimeout(uint16_t rpa_timeout) { // Note: no documented status code for this case. if (rpa_timeout < 0x1 || rpa_timeout > 0x0e10) { INFO(id_, @@ -352,17 +336,16 @@ ErrorCode LinkLayerController::LeReadPhy(uint16_t connection_handle, return ErrorCode::UNKNOWN_CONNECTION; } - AclConnection const& connection = - connections_.GetAclConnection(connection_handle); + AclConnection const& connection = connections_.GetAclConnection(connection_handle); *tx_phy = connection.GetTxPhy(); *rx_phy = connection.GetRxPhy(); return ErrorCode::SUCCESS; } // HCI LE Set Default Phy command (Vol 4, Part E § 7.8.48). -ErrorCode LinkLayerController::LeSetDefaultPhy( - bool all_phys_no_transmit_preference, bool all_phys_no_receive_preference, - uint8_t tx_phys, uint8_t rx_phys) { +ErrorCode LinkLayerController::LeSetDefaultPhy(bool all_phys_no_transmit_preference, + bool all_phys_no_receive_preference, uint8_t tx_phys, + uint8_t rx_phys) { uint8_t supported_phys = properties_.LeSupportedPhys(); // If the All_PHYs parameter specifies that the Host has no preference, @@ -406,10 +389,11 @@ ErrorCode LinkLayerController::LeSetDefaultPhy( } // HCI LE Set Phy command (Vol 4, Part E § 7.8.49). -ErrorCode LinkLayerController::LeSetPhy( - uint16_t connection_handle, bool all_phys_no_transmit_preference, - bool all_phys_no_receive_preference, uint8_t tx_phys, uint8_t rx_phys, - bluetooth::hci::PhyOptions /*phy_options*/) { +ErrorCode LinkLayerController::LeSetPhy(uint16_t connection_handle, + bool all_phys_no_transmit_preference, + bool all_phys_no_receive_preference, uint8_t tx_phys, + uint8_t rx_phys, + bluetooth::hci::PhyOptions /*phy_options*/) { uint8_t supported_phys = properties_.LeSupportedPhys(); // Note: no documented status code for this case. @@ -446,13 +430,11 @@ ErrorCode LinkLayerController::LeSetPhy( // future use, the Controller shall return the error code Unsupported Feature // or Parameter Value (0x11). if ((tx_phys & ~supported_phys) != 0) { - INFO(id_, "TX_PhyS ({:x}) configures unsupported or reserved bits", - tx_phys); + INFO(id_, "TX_PhyS ({:x}) configures unsupported or reserved bits", tx_phys); return ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE; } if ((rx_phys & ~supported_phys) != 0) { - INFO(id_, "RX_PhyS ({:x}) configures unsupported or reserved bits", - rx_phys); + INFO(id_, "RX_PhyS ({:x}) configures unsupported or reserved bits", rx_phys); return ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE; } @@ -460,9 +442,8 @@ ErrorCode LinkLayerController::LeSetPhy( // or both PHY changes or when the Controller determines that neither PHY // will change immediately. SendLeLinkLayerPacket(model::packets::LlPhyReqBuilder::Create( - connections_.GetOwnAddress(connection_handle).GetAddress(), - connections_.GetAddress(connection_handle).GetAddress(), tx_phys, - rx_phys)); + connections_.GetOwnAddress(connection_handle).GetAddress(), + connections_.GetAddress(connection_handle).GetAddress(), tx_phys, rx_phys)); connections_.GetAclConnection(connection_handle).InitiatePhyUpdate(); requested_tx_phys_ = tx_phys; @@ -471,8 +452,7 @@ ErrorCode LinkLayerController::LeSetPhy( } // Helper to pick one phy in enabled phys. -static bluetooth::hci::PhyType select_phy(uint8_t phys, - bluetooth::hci::PhyType current) { +static bluetooth::hci::PhyType select_phy(uint8_t phys, bluetooth::hci::PhyType current) { return (phys & 0x4) ? bluetooth::hci::PhyType::LE_CODED : (phys & 0x2) ? bluetooth::hci::PhyType::LE_2M : (phys & 0x1) ? bluetooth::hci::PhyType::LE_1M @@ -481,20 +461,17 @@ static bluetooth::hci::PhyType select_phy(uint8_t phys, // Helper to generate the LL_PHY_UPDATE_IND mask for the selected phy. // The mask is non zero only if the phy has changed. -static uint8_t indicate_phy(bluetooth::hci::PhyType selected, - bluetooth::hci::PhyType current) { +static uint8_t indicate_phy(bluetooth::hci::PhyType selected, bluetooth::hci::PhyType current) { return selected == current ? 0x0 : selected == bluetooth::hci::PhyType::LE_CODED ? 0x4 : selected == bluetooth::hci::PhyType::LE_2M ? 0x2 : 0x1; } -void LinkLayerController::IncomingLlPhyReq( - model::packets::LinkLayerPacketView incoming) { +void LinkLayerController::IncomingLlPhyReq(model::packets::LinkLayerPacketView incoming) { auto phy_req = model::packets::LlPhyReqView::Create(incoming); ASSERT(phy_req.IsValid()); - uint16_t connection_handle = - connections_.GetHandleOnlyAddress(incoming.GetSourceAddress()); + uint16_t connection_handle = connections_.GetHandleOnlyAddress(incoming.GetSourceAddress()); if (connection_handle == kReservedHandle) { INFO(id_, "@{}: Unknown connection @{}", incoming.GetDestinationAddress(), @@ -508,8 +485,8 @@ void LinkLayerController::IncomingLlPhyReq( // Peripheral receives the request: respond with local phy preferences // in LL_PHY_RSP pdu. SendLeLinkLayerPacket(model::packets::LlPhyRspBuilder::Create( - incoming.GetDestinationAddress(), incoming.GetSourceAddress(), - default_tx_phys_, default_rx_phys_)); + incoming.GetDestinationAddress(), incoming.GetSourceAddress(), default_tx_phys_, + default_rx_phys_)); } else { // Central receives the request: respond with LL_PHY_UPDATE_IND and // the selected phys. @@ -519,10 +496,8 @@ void LinkLayerController::IncomingLlPhyReq( uint8_t rx_phys = phy_req.GetTxPhys() & default_rx_phys_; // Select valid TX and RX phys from preferences. - bluetooth::hci::PhyType phy_c_to_p = - select_phy(tx_phys, connection.GetTxPhy()); - bluetooth::hci::PhyType phy_p_to_c = - select_phy(rx_phys, connection.GetRxPhy()); + bluetooth::hci::PhyType phy_c_to_p = select_phy(tx_phys, connection.GetTxPhy()); + bluetooth::hci::PhyType phy_p_to_c = select_phy(rx_phys, connection.GetRxPhy()); // Send LL_PHY_UPDATE_IND to notify selected phys. // @@ -532,17 +507,16 @@ void LinkLayerController::IncomingLlPhyReq( // PHY shall be set to 1 and the remaining bits to 0; if a PHY is remaining // unchanged, then the corresponding field shall be set to the value 0. SendLeLinkLayerPacket(model::packets::LlPhyUpdateIndBuilder::Create( - incoming.GetDestinationAddress(), incoming.GetSourceAddress(), - indicate_phy(phy_c_to_p, connection.GetTxPhy()), - indicate_phy(phy_p_to_c, connection.GetRxPhy()), 0)); + incoming.GetDestinationAddress(), incoming.GetSourceAddress(), + indicate_phy(phy_c_to_p, connection.GetTxPhy()), + indicate_phy(phy_p_to_c, connection.GetRxPhy()), 0)); // Notify the host when the phy selection has changed // (responder in this case). - if ((phy_c_to_p != connection.GetTxPhy() || - phy_p_to_c != connection.GetRxPhy()) && + if ((phy_c_to_p != connection.GetTxPhy() || phy_p_to_c != connection.GetRxPhy()) && IsLeEventUnmasked(SubeventCode::PHY_UPDATE_COMPLETE)) { send_event_(bluetooth::hci::LePhyUpdateCompleteBuilder::Create( - ErrorCode::SUCCESS, connection_handle, phy_c_to_p, phy_p_to_c)); + ErrorCode::SUCCESS, connection_handle, phy_c_to_p, phy_p_to_c)); } // Update local state. @@ -551,12 +525,10 @@ void LinkLayerController::IncomingLlPhyReq( } } -void LinkLayerController::IncomingLlPhyRsp( - model::packets::LinkLayerPacketView incoming) { +void LinkLayerController::IncomingLlPhyRsp(model::packets::LinkLayerPacketView incoming) { auto phy_rsp = model::packets::LlPhyRspView::Create(incoming); ASSERT(phy_rsp.IsValid()); - uint16_t connection_handle = - connections_.GetHandleOnlyAddress(incoming.GetSourceAddress()); + uint16_t connection_handle = connections_.GetHandleOnlyAddress(incoming.GetSourceAddress()); if (connection_handle == kReservedHandle) { INFO(id_, "@{}: Unknown connection @{}", incoming.GetDestinationAddress(), @@ -572,10 +544,8 @@ void LinkLayerController::IncomingLlPhyRsp( uint8_t rx_phys = phy_rsp.GetTxPhys() & requested_rx_phys_; // Select valid TX and RX phys from preferences. - bluetooth::hci::PhyType phy_c_to_p = - select_phy(tx_phys, connection.GetTxPhy()); - bluetooth::hci::PhyType phy_p_to_c = - select_phy(rx_phys, connection.GetRxPhy()); + bluetooth::hci::PhyType phy_c_to_p = select_phy(tx_phys, connection.GetTxPhy()); + bluetooth::hci::PhyType phy_p_to_c = select_phy(rx_phys, connection.GetRxPhy()); // Send LL_PHY_UPDATE_IND to notify selected phys. // @@ -585,15 +555,15 @@ void LinkLayerController::IncomingLlPhyRsp( // PHY shall be set to 1 and the remaining bits to 0; if a PHY is remaining // unchanged, then the corresponding field shall be set to the value 0. SendLeLinkLayerPacket(model::packets::LlPhyUpdateIndBuilder::Create( - incoming.GetDestinationAddress(), incoming.GetSourceAddress(), - indicate_phy(phy_c_to_p, connection.GetTxPhy()), - indicate_phy(phy_p_to_c, connection.GetRxPhy()), 0)); + incoming.GetDestinationAddress(), incoming.GetSourceAddress(), + indicate_phy(phy_c_to_p, connection.GetTxPhy()), + indicate_phy(phy_p_to_c, connection.GetRxPhy()), 0)); // Always notify the host, even if the phy selection has not changed // (initiator in this case). if (IsLeEventUnmasked(SubeventCode::PHY_UPDATE_COMPLETE)) { send_event_(bluetooth::hci::LePhyUpdateCompleteBuilder::Create( - ErrorCode::SUCCESS, connection_handle, phy_c_to_p, phy_p_to_c)); + ErrorCode::SUCCESS, connection_handle, phy_c_to_p, phy_p_to_c)); } // Update local state. @@ -602,12 +572,10 @@ void LinkLayerController::IncomingLlPhyRsp( connection.SetRxPhy(phy_p_to_c); } -void LinkLayerController::IncomingLlPhyUpdateInd( - model::packets::LinkLayerPacketView incoming) { +void LinkLayerController::IncomingLlPhyUpdateInd(model::packets::LinkLayerPacketView incoming) { auto phy_update_ind = model::packets::LlPhyUpdateIndView::Create(incoming); ASSERT(phy_update_ind.IsValid()); - uint16_t connection_handle = - connections_.GetHandleOnlyAddress(incoming.GetSourceAddress()); + uint16_t connection_handle = connections_.GetHandleOnlyAddress(incoming.GetSourceAddress()); if (connection_handle == kReservedHandle) { INFO(id_, "@{}: Unknown connection @{}", incoming.GetDestinationAddress(), @@ -618,10 +586,8 @@ void LinkLayerController::IncomingLlPhyUpdateInd( AclConnection& connection = connections_.GetAclConnection(connection_handle); ASSERT(connection.GetRole() == bluetooth::hci::Role::PERIPHERAL); - bluetooth::hci::PhyType tx_phy = - select_phy(phy_update_ind.GetPhyPToC(), connection.GetTxPhy()); - bluetooth::hci::PhyType rx_phy = - select_phy(phy_update_ind.GetPhyCToP(), connection.GetRxPhy()); + bluetooth::hci::PhyType tx_phy = select_phy(phy_update_ind.GetPhyPToC(), connection.GetTxPhy()); + bluetooth::hci::PhyType rx_phy = select_phy(phy_update_ind.GetPhyCToP(), connection.GetRxPhy()); // Update local state, and notify the host. // The notification is sent only when the local host is initiator @@ -630,7 +596,7 @@ void LinkLayerController::IncomingLlPhyUpdateInd( (tx_phy != connection.GetTxPhy() || rx_phy != connection.GetRxPhy() || connection.InitiatedPhyUpdate())) { send_event_(bluetooth::hci::LePhyUpdateCompleteBuilder::Create( - ErrorCode::SUCCESS, connection_handle, tx_phy, rx_phy)); + ErrorCode::SUCCESS, connection_handle, tx_phy, rx_phy)); } connection.PhyUpdateComplete(); @@ -639,8 +605,7 @@ void LinkLayerController::IncomingLlPhyUpdateInd( } // HCI LE Set Host Feature command (Vol 4, Part E § 7.8.115). -ErrorCode LinkLayerController::LeSetHostFeature(uint8_t bit_number, - uint8_t bit_value) { +ErrorCode LinkLayerController::LeSetHostFeature(uint8_t bit_number, uint8_t bit_value) { if (bit_number >= 64 || bit_value > 1) { return ErrorCode::INVALID_HCI_COMMAND_PARAMETERS; } @@ -660,12 +625,9 @@ ErrorCode LinkLayerController::LeSetHostFeature(uint8_t bit_number, uint64_t bit_mask = UINT64_C(1) << bit_number; if (bit_mask == - static_cast( - LLFeaturesBits::CONNECTED_ISOCHRONOUS_STREAM_HOST_SUPPORT)) { + static_cast(LLFeaturesBits::CONNECTED_ISOCHRONOUS_STREAM_HOST_SUPPORT)) { connected_isochronous_stream_host_support_ = bit_value != 0; - } else if (bit_mask == - static_cast( - LLFeaturesBits::CONNECTION_SUBRATING_HOST_SUPPORT)) { + } else if (bit_mask == static_cast(LLFeaturesBits::CONNECTION_SUBRATING_HOST_SUPPORT)) { connection_subrating_host_support_ = bit_value != 0; } // If Bit_Number specifies a feature bit that is not controlled by the Host, @@ -690,9 +652,8 @@ ErrorCode LinkLayerController::LeSetHostFeature(uint8_t bit_number, // HCI command LE_Add_Device_To_Resolving_List (Vol 4, Part E § 7.8.38). ErrorCode LinkLayerController::LeAddDeviceToResolvingList( - PeerAddressType peer_identity_address_type, Address peer_identity_address, - std::array peer_irk, - std::array local_irk) { + PeerAddressType peer_identity_address_type, Address peer_identity_address, + std::array peer_irk, std::array local_irk) { // This command shall not be used when address resolution is enabled in the // Controller and: // • Advertising (other than periodic advertising) is enabled, @@ -738,7 +699,7 @@ ErrorCode LinkLayerController::LeAddDeviceToResolvingList( // HCI command LE_Remove_Device_From_Resolving_List (Vol 4, Part E § 7.8.39). ErrorCode LinkLayerController::LeRemoveDeviceFromResolvingList( - PeerAddressType peer_identity_address_type, Address peer_identity_address) { + PeerAddressType peer_identity_address_type, Address peer_identity_address) { // This command shall not be used when address resolution is enabled in the // Controller and: // • Advertising (other than periodic advertising) is enabled, @@ -752,8 +713,7 @@ ErrorCode LinkLayerController::LeRemoveDeviceFromResolvingList( return ErrorCode::COMMAND_DISALLOWED; } - for (auto it = le_resolving_list_.begin(); it != le_resolving_list_.end(); - it++) { + for (auto it = le_resolving_list_.begin(); it != le_resolving_list_.end(); it++) { if (it->peer_identity_address_type == peer_identity_address_type && it->peer_identity_address == peer_identity_address) { le_resolving_list_.erase(it); @@ -789,8 +749,8 @@ ErrorCode LinkLayerController::LeClearResolvingList() { // HCI command LE_Read_Peer_Resolvable_Address (Vol 4, Part E § 7.8.42). ErrorCode LinkLayerController::LeReadPeerResolvableAddress( - PeerAddressType peer_identity_address_type, Address peer_identity_address, - Address* peer_resolvable_address) { + PeerAddressType peer_identity_address_type, Address peer_identity_address, + Address* peer_resolvable_address) { for (auto const& entry : le_resolving_list_) { if (entry.peer_identity_address_type == peer_identity_address_type && entry.peer_identity_address == peer_identity_address && @@ -813,8 +773,8 @@ ErrorCode LinkLayerController::LeReadPeerResolvableAddress( // HCI command LE_Read_Local_Resolvable_Address (Vol 4, Part E § 7.8.43). ErrorCode LinkLayerController::LeReadLocalResolvableAddress( - PeerAddressType peer_identity_address_type, Address peer_identity_address, - Address* local_resolvable_address) { + PeerAddressType peer_identity_address_type, Address peer_identity_address, + Address* local_resolvable_address) { for (auto const& entry : le_resolving_list_) { if (entry.peer_identity_address_type == peer_identity_address_type && entry.peer_identity_address == peer_identity_address && @@ -854,9 +814,9 @@ ErrorCode LinkLayerController::LeSetAddressResolutionEnable(bool enable) { } // HCI command LE_Set_Privacy_Mode (Vol 4, Part E § 7.8.77). -ErrorCode LinkLayerController::LeSetPrivacyMode( - PeerAddressType peer_identity_address_type, Address peer_identity_address, - bluetooth::hci::PrivacyMode privacy_mode) { +ErrorCode LinkLayerController::LeSetPrivacyMode(PeerAddressType peer_identity_address_type, + Address peer_identity_address, + bluetooth::hci::PrivacyMode privacy_mode) { // This command shall not be used when address resolution is enabled in the // Controller and: // • Advertising (other than periodic advertising) is enabled, @@ -911,7 +871,7 @@ ErrorCode LinkLayerController::LeClearFilterAcceptList() { // HCI command LE_Add_Device_To_Filter_Accept_List (Vol 4, Part E § 7.8.16). ErrorCode LinkLayerController::LeAddDeviceToFilterAcceptList( - FilterAcceptListAddressType address_type, Address address) { + FilterAcceptListAddressType address_type, Address address) { // This command shall not be used when: // • any advertising filter policy uses the Filter Accept List and // advertising is enabled, @@ -935,15 +895,14 @@ ErrorCode LinkLayerController::LeAddDeviceToFilterAcceptList( return ErrorCode::MEMORY_CAPACITY_EXCEEDED; } - le_filter_accept_list_.emplace_back( - FilterAcceptListEntry{address_type, address}); + le_filter_accept_list_.emplace_back(FilterAcceptListEntry{address_type, address}); return ErrorCode::SUCCESS; } // HCI command LE_Remove_Device_From_Filter_Accept_List (Vol 4, Part E // § 7.8.17). ErrorCode LinkLayerController::LeRemoveDeviceFromFilterAcceptList( - FilterAcceptListAddressType address_type, Address address) { + FilterAcceptListAddressType address_type, Address address) { // This command shall not be used when: // • any advertising filter policy uses the Filter Accept List and // advertising is enabled, @@ -959,8 +918,7 @@ ErrorCode LinkLayerController::LeRemoveDeviceFromFilterAcceptList( return ErrorCode::COMMAND_DISALLOWED; } - for (auto it = le_filter_accept_list_.begin(); - it != le_filter_accept_list_.end(); it++) { + for (auto it = le_filter_accept_list_.begin(); it != le_filter_accept_list_.end(); it++) { // Address shall be ignored when Address_Type is set to 0xFF. if (it->address_type == address_type && (address_type == FilterAcceptListAddressType::ANONYMOUS_ADVERTISERS || @@ -982,22 +940,20 @@ ErrorCode LinkLayerController::LeRemoveDeviceFromFilterAcceptList( // HCI LE Add Device To Periodic Advertiser List command (Vol 4, Part E // § 7.8.70). ErrorCode LinkLayerController::LeAddDeviceToPeriodicAdvertiserList( - bluetooth::hci::AdvertiserAddressType advertiser_address_type, - Address advertiser_address, uint8_t advertising_sid) { + bluetooth::hci::AdvertiserAddressType advertiser_address_type, Address advertiser_address, + uint8_t advertising_sid) { // If the Host issues this command when an HCI_LE_Periodic_Advertising_- // Create_Sync command is pending, the Controller shall return the error code // Command Disallowed (0x0C). if (synchronizing_.has_value()) { - INFO(id_, - "LE Periodic Advertising Create Sync command is currently pending"); + INFO(id_, "LE Periodic Advertising Create Sync command is currently pending"); return ErrorCode::COMMAND_DISALLOWED; } // When a Controller cannot add an entry to the Periodic Advertiser list // because the list is full, the Controller shall return the error code Memory // Capacity Exceeded (0x07). - if (le_periodic_advertiser_list_.size() >= - properties_.le_periodic_advertiser_list_size) { + if (le_periodic_advertiser_list_.size() >= properties_.le_periodic_advertiser_list_size) { INFO(id_, "periodic advertiser list is full"); return ErrorCode::MEMORY_CAPACITY_EXCEEDED; } @@ -1014,29 +970,27 @@ ErrorCode LinkLayerController::LeAddDeviceToPeriodicAdvertiserList( } le_periodic_advertiser_list_.emplace_back(PeriodicAdvertiserListEntry{ - advertiser_address_type, advertiser_address, advertising_sid}); + advertiser_address_type, advertiser_address, advertising_sid}); return ErrorCode::SUCCESS; } // HCI LE Remove Device From Periodic Advertiser List command // (Vol 4, Part E § 7.8.71). ErrorCode LinkLayerController::LeRemoveDeviceFromPeriodicAdvertiserList( - bluetooth::hci::AdvertiserAddressType advertiser_address_type, - Address advertiser_address, uint8_t advertising_sid) { + bluetooth::hci::AdvertiserAddressType advertiser_address_type, Address advertiser_address, + uint8_t advertising_sid) { // If this command is used when an HCI_LE_Periodic_Advertising_Create_Sync // command is pending, the Controller shall return the error code Command // Disallowed (0x0C). if (synchronizing_.has_value()) { - INFO(id_, - "LE Periodic Advertising Create Sync command is currently pending"); + INFO(id_, "LE Periodic Advertising Create Sync command is currently pending"); return ErrorCode::COMMAND_DISALLOWED; } - for (auto it = le_periodic_advertiser_list_.begin(); - it != le_periodic_advertiser_list_.end(); it++) { + for (auto it = le_periodic_advertiser_list_.begin(); it != le_periodic_advertiser_list_.end(); + it++) { if (it->advertiser_address_type == advertiser_address_type && - it->advertiser_address == advertiser_address && - it->advertising_sid == advertising_sid) { + it->advertiser_address == advertiser_address && it->advertising_sid == advertising_sid) { le_periodic_advertiser_list_.erase(it); return ErrorCode::SUCCESS; } @@ -1055,8 +1009,7 @@ ErrorCode LinkLayerController::LeClearPeriodicAdvertiserList() { // command is pending, the Controller shall return the error code Command // Disallowed (0x0C). if (synchronizing_.has_value()) { - INFO(id_, - "LE Periodic Advertising Create Sync command is currently pending"); + INFO(id_, "LE Periodic Advertising Create Sync command is currently pending"); return ErrorCode::COMMAND_DISALLOWED; } @@ -1070,16 +1023,14 @@ ErrorCode LinkLayerController::LeClearPeriodicAdvertiserList() { // HCI LE Periodic Advertising Create Sync command (Vol 4, Part E § 7.8.67). ErrorCode LinkLayerController::LePeriodicAdvertisingCreateSync( - bluetooth::hci::PeriodicAdvertisingOptions options, uint8_t advertising_sid, - bluetooth::hci::AdvertiserAddressType advertiser_address_type, - Address advertiser_address, uint16_t /*skip*/, uint16_t sync_timeout, - uint8_t sync_cte_type) { + bluetooth::hci::PeriodicAdvertisingOptions options, uint8_t advertising_sid, + bluetooth::hci::AdvertiserAddressType advertiser_address_type, Address advertiser_address, + uint16_t /*skip*/, uint16_t sync_timeout, uint8_t sync_cte_type) { // If the Host issues this command when another HCI_LE_Periodic_Advertising_- // Create_Sync command is pending, the Controller shall return the error code // Command Disallowed (0x0C). if (synchronizing_.has_value()) { - INFO(id_, - "LE Periodic Advertising Create Sync command is currently pending"); + INFO(id_, "LE Periodic Advertising Create Sync command is currently pending"); return ErrorCode::COMMAND_DISALLOWED; } @@ -1087,8 +1038,7 @@ ErrorCode LinkLayerController::LePeriodicAdvertisingCreateSync( // to 1, the Controller shall return the error code Command Disallowed (0x0C). uint8_t sync_cte_type_mask = 0x1f; if ((sync_cte_type & sync_cte_type_mask) == sync_cte_type_mask) { - INFO(id_, - "Sync_CTE_Type is configured to ignore all types of advertisement"); + INFO(id_, "Sync_CTE_Type is configured to ignore all types of advertisement"); return ErrorCode::COMMAND_DISALLOWED; } @@ -1099,17 +1049,15 @@ ErrorCode LinkLayerController::LePeriodicAdvertisingCreateSync( // Connection Already Exists (0x0B). bool has_synchronized_train = false; for (auto& [_, sync] : synchronized_) { - has_synchronized_train |= - sync.advertiser_address_type == advertiser_address_type && - sync.advertiser_address == advertiser_address && - sync.advertising_sid == advertising_sid; + has_synchronized_train |= sync.advertiser_address_type == advertiser_address_type && + sync.advertiser_address == advertiser_address && + sync.advertising_sid == advertising_sid; } if (!options.use_periodic_advertiser_list_ && has_synchronized_train) { INFO(id_, "the controller is already synchronized on the periodic advertising" " train from {}[{}] - SID=0x{:x}", - advertiser_address, - bluetooth::hci::AdvertiserAddressTypeText(advertiser_address_type), + advertiser_address, bluetooth::hci::AdvertiserAddressTypeText(advertiser_address_type), advertising_sid); return ErrorCode::CONNECTION_ALREADY_EXISTS; } @@ -1124,8 +1072,7 @@ ErrorCode LinkLayerController::LePeriodicAdvertisingCreateSync( // Controller shall return an error which should use the error code // Unsupported Feature or Parameter Value (0x11). if (!options.disable_reporting_ && options.enable_duplicate_filtering_ && - !properties_.SupportsLLFeature( - LLFeaturesBits::PERIODIC_ADVERTISING_ADI_SUPPORT)) { + !properties_.SupportsLLFeature(LLFeaturesBits::PERIODIC_ADVERTISING_ADI_SUPPORT)) { INFO(id_, "reporting and duplicate filtering are enabled in the options," " but the controller does not support the Periodic Advertising ADI" @@ -1139,8 +1086,7 @@ ErrorCode LinkLayerController::LePeriodicAdvertisingCreateSync( // / Synchronization Timeout (0x3E). if (options.disable_reporting_ && !properties_.SupportsCommand( - bluetooth::hci::OpCodeIndex:: - LE_SET_PERIODIC_ADVERTISING_RECEIVE_ENABLE)) { + bluetooth::hci::OpCodeIndex::LE_SET_PERIODIC_ADVERTISING_RECEIVE_ENABLE)) { INFO(id_, "reporting is disabled in the options, but the controller does not" " support the HCI_LE_Set_Periodic_Advertising_Receive_Enable command"); @@ -1148,11 +1094,11 @@ ErrorCode LinkLayerController::LePeriodicAdvertisingCreateSync( } synchronizing_ = Synchronizing{ - .options = options, - .advertiser_address_type = advertiser_address_type, - .advertiser_address = advertiser_address, - .advertising_sid = advertising_sid, - .sync_timeout = 10ms * sync_timeout, + .options = options, + .advertiser_address_type = advertiser_address_type, + .advertiser_address = advertiser_address, + .advertising_sid = advertising_sid, + .sync_timeout = 10ms * sync_timeout, }; return ErrorCode::SUCCESS; } @@ -1174,11 +1120,9 @@ ErrorCode LinkLayerController::LePeriodicAdvertisingCreateSyncCancel() { // by Host (0x44). if (IsLeEventUnmasked(SubeventCode::PERIODIC_ADVERTISING_SYNC_ESTABLISHED)) { ScheduleTask(0ms, [this] { - send_event_( - bluetooth::hci::LePeriodicAdvertisingSyncEstablishedBuilder::Create( - ErrorCode::OPERATION_CANCELLED_BY_HOST, 0, 0, - AddressType::PUBLIC_DEVICE_ADDRESS, Address::kEmpty, - bluetooth::hci::SecondaryPhyType::NO_PACKETS, 0, + send_event_(bluetooth::hci::LePeriodicAdvertisingSyncEstablishedBuilder::Create( + ErrorCode::OPERATION_CANCELLED_BY_HOST, 0, 0, AddressType::PUBLIC_DEVICE_ADDRESS, + Address::kEmpty, bluetooth::hci::SecondaryPhyType::NO_PACKETS, 0, bluetooth::hci::ClockAccuracy::PPM_500)); }); } @@ -1189,8 +1133,7 @@ ErrorCode LinkLayerController::LePeriodicAdvertisingCreateSyncCancel() { // HCI LE Periodic Advertising Terminate Sync command (Vol 4, Part E // § 7.8.69). -ErrorCode LinkLayerController::LePeriodicAdvertisingTerminateSync( - uint16_t sync_handle) { +ErrorCode LinkLayerController::LePeriodicAdvertisingTerminateSync(uint16_t sync_handle) { // If the periodic advertising train corresponding to the Sync_Handle // parameter does not exist, then the Controller shall return the error // code Unknown Advertising Identifier (0x42). @@ -1209,9 +1152,9 @@ ErrorCode LinkLayerController::LePeriodicAdvertisingTerminateSync( // HCI command LE_Set_Scan_Parameters (Vol 4, Part E § 7.8.10). ErrorCode LinkLayerController::LeSetScanParameters( - bluetooth::hci::LeScanType scan_type, uint16_t scan_interval, - uint16_t scan_window, bluetooth::hci::OwnAddressType own_address_type, - bluetooth::hci::LeScanningFilterPolicy scanning_filter_policy) { + bluetooth::hci::LeScanType scan_type, uint16_t scan_interval, uint16_t scan_window, + bluetooth::hci::OwnAddressType own_address_type, + bluetooth::hci::LeScanningFilterPolicy scanning_filter_policy) { // Legacy advertising commands are disallowed when extended advertising // commands were used since the last reset. if (!SelectLegacyAdvertising()) { @@ -1231,8 +1174,7 @@ ErrorCode LinkLayerController::LeSetScanParameters( // Note: no explicit error code stated for invalid interval and window // values but assuming Unsupported Feature or Parameter Value (0x11) // error code based on similar advertising command. - if (scan_interval < 0x4 || scan_interval > 0x4000 || scan_window < 0x4 || - scan_window > 0x4000) { + if (scan_interval < 0x4 || scan_interval > 0x4000 || scan_window < 0x4 || scan_window > 0x4000) { INFO(id_, "le_scan_interval (0x{:04x}) and/or" " le_scan_window (0x{:04x}) are outside the range" @@ -1244,9 +1186,8 @@ ErrorCode LinkLayerController::LeSetScanParameters( // The LE_Scan_Window parameter shall always be set to a value smaller // or equal to the value set for the LE_Scan_Interval parameter. if (scan_window > scan_interval) { - INFO(id_, - "le_scan_window (0x{:04x}) is larger than le_scan_interval (0x{:04x})", - scan_window, scan_interval); + INFO(id_, "le_scan_window (0x{:04x}) is larger than le_scan_interval (0x{:04x})", scan_window, + scan_interval); return ErrorCode::INVALID_HCI_COMMAND_PARAMETERS; } @@ -1261,8 +1202,7 @@ ErrorCode LinkLayerController::LeSetScanParameters( } // HCI command LE_Set_Scan_Enable (Vol 4, Part E § 7.8.11). -ErrorCode LinkLayerController::LeSetScanEnable(bool enable, - bool filter_duplicates) { +ErrorCode LinkLayerController::LeSetScanEnable(bool enable, bool filter_duplicates) { // Legacy advertising commands are disallowed when extended advertising // commands were used since the last reset. if (!SelectLegacyAdvertising()) { @@ -1288,10 +1228,8 @@ ErrorCode LinkLayerController::LeSetScanEnable(bool enable, // has not been initialized using the HCI_LE_Set_Random_Address command, // the Controller shall return the error code // Invalid HCI Command Parameters (0x12). - if ((scanner_.own_address_type == - bluetooth::hci::OwnAddressType::RANDOM_DEVICE_ADDRESS || - scanner_.own_address_type == - bluetooth::hci::OwnAddressType::RESOLVABLE_OR_RANDOM_ADDRESS) && + if ((scanner_.own_address_type == bluetooth::hci::OwnAddressType::RANDOM_DEVICE_ADDRESS || + scanner_.own_address_type == bluetooth::hci::OwnAddressType::RESOLVABLE_OR_RANDOM_ADDRESS) && random_address_ == Address::kEmpty) { INFO(id_, "own_address_type is Random_Device_Address or" @@ -1306,9 +1244,8 @@ ErrorCode LinkLayerController::LeSetScanEnable(bool enable, scanner_.periodical_timeout = {}; scanner_.pending_scan_request = {}; scanner_.pending_scan_request_timeout = {}; - scanner_.filter_duplicates = filter_duplicates - ? bluetooth::hci::FilterDuplicates::ENABLED - : bluetooth::hci::FilterDuplicates::DISABLED; + scanner_.filter_duplicates = filter_duplicates ? bluetooth::hci::FilterDuplicates::ENABLED + : bluetooth::hci::FilterDuplicates::DISABLED; return ErrorCode::SUCCESS; } @@ -1318,11 +1255,9 @@ ErrorCode LinkLayerController::LeSetScanEnable(bool enable, // HCI command LE_Set_Extended_Scan_Parameters (Vol 4, Part E § 7.8.64). ErrorCode LinkLayerController::LeSetExtendedScanParameters( - bluetooth::hci::OwnAddressType own_address_type, - bluetooth::hci::LeScanningFilterPolicy scanning_filter_policy, - uint8_t scanning_phys, - std::vector - scanning_phy_parameters) { + bluetooth::hci::OwnAddressType own_address_type, + bluetooth::hci::LeScanningFilterPolicy scanning_filter_policy, uint8_t scanning_phys, + std::vector scanning_phy_parameters) { uint8_t supported_phys = properties_.LeSupportedPhys(); // Extended advertising commands are disallowed when legacy advertising @@ -1353,8 +1288,7 @@ ErrorCode LinkLayerController::LeSetExtendedScanParameters( } // TODO(c++20) std::popcount - if (__builtin_popcount(scanning_phys) != - int(scanning_phy_parameters.size())) { + if (__builtin_popcount(scanning_phys) != int(scanning_phy_parameters.size())) { INFO(id_, "scanning_phy_parameters ({})" " does not match scanning_phys ({:02x})", @@ -1400,20 +1334,20 @@ ErrorCode LinkLayerController::LeSetExtendedScanParameters( if (scanning_phys & 0x1) { scanner_.le_1m_phy = Scanner::PhyParameters{ - .enabled = true, - .scan_type = scanning_phy_parameters[offset].le_scan_type_, - .scan_interval = scanning_phy_parameters[offset].le_scan_interval_, - .scan_window = scanning_phy_parameters[offset].le_scan_window_, + .enabled = true, + .scan_type = scanning_phy_parameters[offset].le_scan_type_, + .scan_interval = scanning_phy_parameters[offset].le_scan_interval_, + .scan_window = scanning_phy_parameters[offset].le_scan_window_, }; offset++; } if (scanning_phys & 0x4) { scanner_.le_coded_phy = Scanner::PhyParameters{ - .enabled = true, - .scan_type = scanning_phy_parameters[offset].le_scan_type_, - .scan_interval = scanning_phy_parameters[offset].le_scan_interval_, - .scan_window = scanning_phy_parameters[offset].le_scan_window_, + .enabled = true, + .scan_type = scanning_phy_parameters[offset].le_scan_type_, + .scan_interval = scanning_phy_parameters[offset].le_scan_interval_, + .scan_window = scanning_phy_parameters[offset].le_scan_window_, }; offset++; } @@ -1423,8 +1357,8 @@ ErrorCode LinkLayerController::LeSetExtendedScanParameters( // HCI command LE_Set_Extended_Scan_Enable (Vol 4, Part E § 7.8.65). ErrorCode LinkLayerController::LeSetExtendedScanEnable( - bool enable, bluetooth::hci::FilterDuplicates filter_duplicates, - uint16_t duration, uint16_t period) { + bool enable, bluetooth::hci::FilterDuplicates filter_duplicates, uint16_t duration, + uint16_t period) { // Extended advertising commands are disallowed when legacy advertising // commands were used since the last reset. if (!SelectExtendedAdvertising()) { @@ -1450,8 +1384,7 @@ ErrorCode LinkLayerController::LeSetExtendedScanEnable( // If Filter_Duplicates is set to 0x02 and either Period or Duration to zero, // the Controller shall return the error code // Invalid HCI Command Parameters (0x12). - if (filter_duplicates == - bluetooth::hci::FilterDuplicates::RESET_EACH_PERIOD && + if (filter_duplicates == bluetooth::hci::FilterDuplicates::RESET_EACH_PERIOD && (period == 0 || duration == 0)) { INFO(id_, "filter_duplicates is Reset_Each_Period but either" @@ -1478,10 +1411,8 @@ ErrorCode LinkLayerController::LeSetExtendedScanEnable( // has not been initialized using the HCI_LE_Set_Random_Address command, // the Controller shall return the error code // Invalid HCI Command Parameters (0x12). - if ((scanner_.own_address_type == - bluetooth::hci::OwnAddressType::RANDOM_DEVICE_ADDRESS || - scanner_.own_address_type == - bluetooth::hci::OwnAddressType::RESOLVABLE_OR_RANDOM_ADDRESS) && + if ((scanner_.own_address_type == bluetooth::hci::OwnAddressType::RANDOM_DEVICE_ADDRESS || + scanner_.own_address_type == bluetooth::hci::OwnAddressType::RESOLVABLE_OR_RANDOM_ADDRESS) && random_address_ == Address::kEmpty) { INFO(id_, "own_address_type is Random_Device_Address or" @@ -1520,13 +1451,11 @@ ErrorCode LinkLayerController::LeSetExtendedScanEnable( // HCI LE Create Connection command (Vol 4, Part E § 7.8.12). ErrorCode LinkLayerController::LeCreateConnection( - uint16_t scan_interval, uint16_t scan_window, - bluetooth::hci::InitiatorFilterPolicy initiator_filter_policy, - AddressWithType peer_address, - bluetooth::hci::OwnAddressType own_address_type, - uint16_t connection_interval_min, uint16_t connection_interval_max, - uint16_t max_latency, uint16_t supervision_timeout, uint16_t min_ce_length, - uint16_t max_ce_length) { + uint16_t scan_interval, uint16_t scan_window, + bluetooth::hci::InitiatorFilterPolicy initiator_filter_policy, AddressWithType peer_address, + bluetooth::hci::OwnAddressType own_address_type, uint16_t connection_interval_min, + uint16_t connection_interval_max, uint16_t max_latency, uint16_t supervision_timeout, + uint16_t min_ce_length, uint16_t max_ce_length) { // Legacy advertising commands are disallowed when extended advertising // commands were used since the last reset. if (!SelectLegacyAdvertising()) { @@ -1547,8 +1476,7 @@ ErrorCode LinkLayerController::LeCreateConnection( // Note: no explicit error code stated for invalid interval and window // values but assuming Unsupported Feature or Parameter Value (0x11) // error code based on similar advertising command. - if (scan_interval < 0x4 || scan_interval > 0x4000 || scan_window < 0x4 || - scan_window > 0x4000) { + if (scan_interval < 0x4 || scan_interval > 0x4000 || scan_window < 0x4 || scan_window > 0x4000) { INFO(id_, "scan_interval (0x{:04x}) and/or " "scan_window (0x{:04x}) are outside the range" @@ -1560,8 +1488,8 @@ ErrorCode LinkLayerController::LeCreateConnection( // The LE_Scan_Window parameter shall be set to a value smaller or equal to // the value set for the LE_Scan_Interval parameter. if (scan_interval < scan_window) { - INFO(id_, "scan_window (0x{:04x}) is larger than scan_interval (0x{:04x})", - scan_window, scan_interval); + INFO(id_, "scan_window (0x{:04x}) is larger than scan_interval (0x{:04x})", scan_window, + scan_interval); return ErrorCode::INVALID_HCI_COMMAND_PARAMETERS; } @@ -1613,14 +1541,13 @@ ErrorCode LinkLayerController::LeCreateConnection( // The Supervision_Timeout in milliseconds shall be larger than // (1 + Max_Latency) * Connection_Interval_Max * 2, where // Connection_Interval_Max is given in milliseconds. - milliseconds min_supervision_timeout = duration_cast( - (1 + max_latency) * slots(2 * connection_interval_max) * 2); + milliseconds min_supervision_timeout = + duration_cast((1 + max_latency) * slots(2 * connection_interval_max) * 2); if (supervision_timeout * 10ms < min_supervision_timeout) { INFO(id_, "supervision_timeout ({} ms) is smaller that the minimal supervision " "timeout allowed by connection_interval_max and max_latency ({} ms)", - supervision_timeout * 10, - static_cast(min_supervision_timeout / 1ms)); + supervision_timeout * 10, static_cast(min_supervision_timeout / 1ms)); return ErrorCode::INVALID_HCI_COMMAND_PARAMETERS; } @@ -1693,16 +1620,14 @@ ErrorCode LinkLayerController::LeCreateConnectionCancel() { if (IsLeEventUnmasked(SubeventCode::ENHANCED_CONNECTION_COMPLETE)) { ScheduleTask(0ms, [this] { send_event_(bluetooth::hci::LeEnhancedConnectionCompleteBuilder::Create( - ErrorCode::UNKNOWN_CONNECTION, 0, Role::CENTRAL, - AddressType::PUBLIC_DEVICE_ADDRESS, Address(), Address(), Address(), - 0, 0, 0, bluetooth::hci::ClockAccuracy::PPM_500)); + ErrorCode::UNKNOWN_CONNECTION, 0, Role::CENTRAL, AddressType::PUBLIC_DEVICE_ADDRESS, + Address(), Address(), Address(), 0, 0, 0, bluetooth::hci::ClockAccuracy::PPM_500)); }); } else if (IsLeEventUnmasked(SubeventCode::CONNECTION_COMPLETE)) { ScheduleTask(0ms, [this] { send_event_(bluetooth::hci::LeConnectionCompleteBuilder::Create( - ErrorCode::UNKNOWN_CONNECTION, 0, Role::CENTRAL, - AddressType::PUBLIC_DEVICE_ADDRESS, Address(), 0, 0, 0, - bluetooth::hci::ClockAccuracy::PPM_500)); + ErrorCode::UNKNOWN_CONNECTION, 0, Role::CENTRAL, AddressType::PUBLIC_DEVICE_ADDRESS, + Address(), 0, 0, 0, bluetooth::hci::ClockAccuracy::PPM_500)); }); } @@ -1716,11 +1641,10 @@ ErrorCode LinkLayerController::LeCreateConnectionCancel() { // HCI LE Extended Create Connection command (Vol 4, Part E § 7.8.66). ErrorCode LinkLayerController::LeExtendedCreateConnection( - bluetooth::hci::InitiatorFilterPolicy initiator_filter_policy, - bluetooth::hci::OwnAddressType own_address_type, - AddressWithType peer_address, uint8_t initiating_phys, - std::vector - initiating_phy_parameters) { + bluetooth::hci::InitiatorFilterPolicy initiator_filter_policy, + bluetooth::hci::OwnAddressType own_address_type, AddressWithType peer_address, + uint8_t initiating_phys, + std::vector initiating_phy_parameters) { // Extended advertising commands are disallowed when legacy advertising // commands were used since the last reset. if (!SelectExtendedAdvertising()) { @@ -1750,8 +1674,7 @@ ErrorCode LinkLayerController::LeExtendedCreateConnection( } // TODO(c++20) std::popcount - if (__builtin_popcount(initiating_phys) != - int(initiating_phy_parameters.size())) { + if (__builtin_popcount(initiating_phys) != int(initiating_phy_parameters.size())) { INFO(id_, "initiating_phy_parameters ({})" " does not match initiating_phys ({:02x})", @@ -1785,8 +1708,7 @@ ErrorCode LinkLayerController::LeExtendedCreateConnection( // The LE_Scan_Window parameter shall be set to a value smaller or equal to // the value set for the LE_Scan_Interval parameter. if (parameter.scan_interval_ < parameter.scan_window_) { - INFO(id_, - "scan_window (0x{:04x}) is larger than scan_interval (0x{:04x})", + INFO(id_, "scan_window (0x{:04x}) is larger than scan_interval (0x{:04x})", parameter.scan_window_, parameter.scan_interval_); return ErrorCode::INVALID_HCI_COMMAND_PARAMETERS; } @@ -1794,28 +1716,23 @@ ErrorCode LinkLayerController::LeExtendedCreateConnection( // Note: no explicit error code stated for invalid connection interval // values but assuming Unsupported Feature or Parameter Value (0x11) // error code based on similar advertising command. - if (parameter.connection_interval_min_ < 0x6 || - parameter.connection_interval_min_ > 0x0c80 || - parameter.connection_interval_max_ < 0x6 || - parameter.connection_interval_max_ > 0x0c80) { + if (parameter.connection_interval_min_ < 0x6 || parameter.connection_interval_min_ > 0x0c80 || + parameter.connection_interval_max_ < 0x6 || parameter.connection_interval_max_ > 0x0c80) { INFO(id_, "connection_interval_min (0x{:04x}) and/or " "connection_interval_max (0x{:04x}) are outside the range" " of supported values (0x6 - 0x0c80)", - parameter.connection_interval_min_, - parameter.connection_interval_max_); + parameter.connection_interval_min_, parameter.connection_interval_max_); return ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE; } // The Connection_Interval_Min parameter shall not be greater than the // Connection_Interval_Max parameter. - if (parameter.connection_interval_max_ < - parameter.connection_interval_min_) { + if (parameter.connection_interval_max_ < parameter.connection_interval_min_) { INFO(id_, "connection_interval_min (0x{:04x}) is larger than" " connection_interval_max (0x{:04x})", - parameter.connection_interval_min_, - parameter.connection_interval_max_); + parameter.connection_interval_min_, parameter.connection_interval_max_); return ErrorCode::INVALID_HCI_COMMAND_PARAMETERS; } @@ -1833,8 +1750,7 @@ ErrorCode LinkLayerController::LeExtendedCreateConnection( // Note: no explicit error code stated for invalid supervision timeout // values but assuming Unsupported Feature or Parameter Value (0x11) // error code based on similar advertising command. - if (parameter.supervision_timeout_ < 0xa || - parameter.supervision_timeout_ > 0x0c80) { + if (parameter.supervision_timeout_ < 0xa || parameter.supervision_timeout_ > 0x0c80) { INFO(id_, "supervision_timeout (0x{:04x}) is outside the range" " of supported values (0xa - 0x0c80)", @@ -1846,15 +1762,13 @@ ErrorCode LinkLayerController::LeExtendedCreateConnection( // (1 + Max_Latency) * Connection_Interval_Max * 2, where // Connection_Interval_Max is given in milliseconds. milliseconds min_supervision_timeout = duration_cast( - (1 + parameter.max_latency_) * - slots(2 * parameter.connection_interval_max_) * 2); + (1 + parameter.max_latency_) * slots(2 * parameter.connection_interval_max_) * 2); if (parameter.supervision_timeout_ * 10ms < min_supervision_timeout) { - INFO( - id_, - "supervision_timeout ({} ms) is smaller that the minimal supervision " - "timeout allowed by connection_interval_max and max_latency ({} ms)", - parameter.supervision_timeout_ * 10, - static_cast(min_supervision_timeout / 1ms)); + INFO(id_, + "supervision_timeout ({} ms) is smaller that the minimal supervision " + "timeout allowed by connection_interval_max and max_latency ({} ms)", + parameter.supervision_timeout_ * 10, + static_cast(min_supervision_timeout / 1ms)); return ErrorCode::INVALID_HCI_COMMAND_PARAMETERS; } } @@ -1904,54 +1818,45 @@ ErrorCode LinkLayerController::LeExtendedCreateConnection( if (initiating_phys & 0x1) { initiator_.le_1m_phy = Initiator::PhyParameters{ - .enabled = true, - .scan_interval = initiating_phy_parameters[offset].scan_interval_, - .scan_window = initiating_phy_parameters[offset].scan_window_, - .connection_interval_min = - initiating_phy_parameters[offset].connection_interval_min_, - .connection_interval_max = - initiating_phy_parameters[offset].connection_interval_max_, - .max_latency = initiating_phy_parameters[offset].max_latency_, - .supervision_timeout = - initiating_phy_parameters[offset].supervision_timeout_, - .min_ce_length = initiating_phy_parameters[offset].min_ce_length_, - .max_ce_length = initiating_phy_parameters[offset].max_ce_length_, + .enabled = true, + .scan_interval = initiating_phy_parameters[offset].scan_interval_, + .scan_window = initiating_phy_parameters[offset].scan_window_, + .connection_interval_min = initiating_phy_parameters[offset].connection_interval_min_, + .connection_interval_max = initiating_phy_parameters[offset].connection_interval_max_, + .max_latency = initiating_phy_parameters[offset].max_latency_, + .supervision_timeout = initiating_phy_parameters[offset].supervision_timeout_, + .min_ce_length = initiating_phy_parameters[offset].min_ce_length_, + .max_ce_length = initiating_phy_parameters[offset].max_ce_length_, }; offset++; } if (initiating_phys & 0x2) { initiator_.le_2m_phy = Initiator::PhyParameters{ - .enabled = true, - .scan_interval = initiating_phy_parameters[offset].scan_interval_, - .scan_window = initiating_phy_parameters[offset].scan_window_, - .connection_interval_min = - initiating_phy_parameters[offset].connection_interval_min_, - .connection_interval_max = - initiating_phy_parameters[offset].connection_interval_max_, - .max_latency = initiating_phy_parameters[offset].max_latency_, - .supervision_timeout = - initiating_phy_parameters[offset].supervision_timeout_, - .min_ce_length = initiating_phy_parameters[offset].min_ce_length_, - .max_ce_length = initiating_phy_parameters[offset].max_ce_length_, + .enabled = true, + .scan_interval = initiating_phy_parameters[offset].scan_interval_, + .scan_window = initiating_phy_parameters[offset].scan_window_, + .connection_interval_min = initiating_phy_parameters[offset].connection_interval_min_, + .connection_interval_max = initiating_phy_parameters[offset].connection_interval_max_, + .max_latency = initiating_phy_parameters[offset].max_latency_, + .supervision_timeout = initiating_phy_parameters[offset].supervision_timeout_, + .min_ce_length = initiating_phy_parameters[offset].min_ce_length_, + .max_ce_length = initiating_phy_parameters[offset].max_ce_length_, }; offset++; } if (initiating_phys & 0x4) { initiator_.le_coded_phy = Initiator::PhyParameters{ - .enabled = true, - .scan_interval = initiating_phy_parameters[offset].scan_interval_, - .scan_window = initiating_phy_parameters[offset].scan_window_, - .connection_interval_min = - initiating_phy_parameters[offset].connection_interval_min_, - .connection_interval_max = - initiating_phy_parameters[offset].connection_interval_max_, - .max_latency = initiating_phy_parameters[offset].max_latency_, - .supervision_timeout = - initiating_phy_parameters[offset].supervision_timeout_, - .min_ce_length = initiating_phy_parameters[offset].min_ce_length_, - .max_ce_length = initiating_phy_parameters[offset].max_ce_length_, + .enabled = true, + .scan_interval = initiating_phy_parameters[offset].scan_interval_, + .scan_window = initiating_phy_parameters[offset].scan_window_, + .connection_interval_min = initiating_phy_parameters[offset].connection_interval_min_, + .connection_interval_max = initiating_phy_parameters[offset].connection_interval_max_, + .max_latency = initiating_phy_parameters[offset].max_latency_, + .supervision_timeout = initiating_phy_parameters[offset].supervision_timeout_, + .min_ce_length = initiating_phy_parameters[offset].min_ce_length_, + .max_ce_length = initiating_phy_parameters[offset].max_ce_length_, }; offset++; } @@ -1996,8 +1901,7 @@ void LinkLayerController::SetSecureConnectionsSupport(bool enable) { } } -void LinkLayerController::SetLocalName( - std::array const& local_name) { +void LinkLayerController::SetLocalName(std::array const& local_name) { std::copy(local_name.begin(), local_name.end(), local_name_.begin()); } @@ -2008,12 +1912,12 @@ void LinkLayerController::SetLocalName(std::vector const& local_name) { } void LinkLayerController::SetExtendedInquiryResponse( - std::array const& extended_inquiry_response) { + std::array const& extended_inquiry_response) { extended_inquiry_response_ = extended_inquiry_response; } void LinkLayerController::SetExtendedInquiryResponse( - std::vector const& extended_inquiry_response) { + std::vector const& extended_inquiry_response) { ASSERT(extended_inquiry_response.size() <= extended_inquiry_response_.size()); extended_inquiry_response_.fill(0); std::copy(extended_inquiry_response.begin(), extended_inquiry_response.end(), @@ -2021,8 +1925,7 @@ void LinkLayerController::SetExtendedInquiryResponse( } LinkLayerController::LinkLayerController(const Address& address, - const ControllerProperties& properties, - uint32_t id) + const ControllerProperties& properties, uint32_t id) : id_(id), address_(address), properties_(properties), @@ -2030,92 +1933,87 @@ LinkLayerController::LinkLayerController(const Address& address, ll_(nullptr, link_layer_destroy) { if (properties_.quirks.has_default_random_address) { WARNING(id_, "Configuring a default random address for this controller"); - random_address_ = Address { 0xba, 0xdb, 0xad, 0xba, 0xdb, 0xad }; + random_address_ = Address{0xba, 0xdb, 0xad, 0xba, 0xdb, 0xad}; } controller_ops_ = { - .user_pointer = this, - .get_handle = - [](void* user, const uint8_t(*address)[6]) { - auto controller = static_cast(user); - - return controller->connections_.GetHandleOnlyAddress( - Address(*address)); - }, - - .get_address = - [](void* user, uint16_t handle, uint8_t(*result)[6]) { - auto controller = static_cast(user); - - auto address_opt = controller->connections_.GetAddressSafe(handle); - Address address = address_opt.has_value() - ? address_opt.value().GetAddress() - : Address::kEmpty; - std::copy(address.data(), address.data() + 6, - reinterpret_cast(result)); - }, - - .get_extended_features = - [](void* user, uint8_t features_page) { - auto controller = static_cast(user); - return controller->GetLmpFeatures(features_page); - }, - - .get_le_features = - [](void* user) { - auto controller = static_cast(user); - return controller->GetLeSupportedFeatures(); - }, - - .get_le_event_mask = - [](void* user) { - auto controller = static_cast(user); - return controller->le_event_mask_; - }, - - .send_hci_event = - [](void* user, const uint8_t* data, uintptr_t len) { - auto controller = static_cast(user); - - auto event_code = static_cast(data[0]); - controller->send_event_(bluetooth::hci::EventBuilder::Create( - event_code, std::vector(data + 2, data + len))); - }, - - .send_lmp_packet = - [](void* user, const uint8_t(*to)[6], const uint8_t* data, - uintptr_t len) { - auto controller = static_cast(user); - - Address source = controller->GetAddress(); - Address dest(*to); - - controller->SendLinkLayerPacket(model::packets::LmpBuilder::Create( - source, dest, std::vector(data, data + len))); - }, - - .send_llcp_packet = - [](void* user, uint16_t acl_connection_handle, const uint8_t* data, - uintptr_t len) { - auto controller = static_cast(user); - - if (!controller->connections_.HasHandle(acl_connection_handle)) { - ERROR( - "Dropping LLCP packet sent for unknown connection handle " - "0x{:x}", - acl_connection_handle); - return; - } - - AclConnection const& connection = - controller->connections_.GetAclConnection( - acl_connection_handle); - Address source = connection.GetOwnAddress().GetAddress(); - Address destination = connection.GetAddress().GetAddress(); - - controller->SendLinkLayerPacket(model::packets::LlcpBuilder::Create( - source, destination, std::vector(data, data + len))); - }}; + .user_pointer = this, + .get_handle = + [](void* user, const uint8_t(*address)[6]) { + auto controller = static_cast(user); + + return controller->connections_.GetHandleOnlyAddress(Address(*address)); + }, + + .get_address = + [](void* user, uint16_t handle, uint8_t(*result)[6]) { + auto controller = static_cast(user); + + auto address_opt = controller->connections_.GetAddressSafe(handle); + Address address = address_opt.has_value() ? address_opt.value().GetAddress() + : Address::kEmpty; + std::copy(address.data(), address.data() + 6, + reinterpret_cast(result)); + }, + + .get_extended_features = + [](void* user, uint8_t features_page) { + auto controller = static_cast(user); + return controller->GetLmpFeatures(features_page); + }, + + .get_le_features = + [](void* user) { + auto controller = static_cast(user); + return controller->GetLeSupportedFeatures(); + }, + + .get_le_event_mask = + [](void* user) { + auto controller = static_cast(user); + return controller->le_event_mask_; + }, + + .send_hci_event = + [](void* user, const uint8_t* data, uintptr_t len) { + auto controller = static_cast(user); + + auto event_code = static_cast(data[0]); + controller->send_event_(bluetooth::hci::EventBuilder::Create( + event_code, std::vector(data + 2, data + len))); + }, + + .send_lmp_packet = + [](void* user, const uint8_t(*to)[6], const uint8_t* data, uintptr_t len) { + auto controller = static_cast(user); + + Address source = controller->GetAddress(); + Address dest(*to); + + controller->SendLinkLayerPacket(model::packets::LmpBuilder::Create( + source, dest, std::vector(data, data + len))); + }, + + .send_llcp_packet = + [](void* user, uint16_t acl_connection_handle, const uint8_t* data, + uintptr_t len) { + auto controller = static_cast(user); + + if (!controller->connections_.HasHandle(acl_connection_handle)) { + ERROR("Dropping LLCP packet sent for unknown connection handle " + "0x{:x}", + acl_connection_handle); + return; + } + + AclConnection const& connection = + controller->connections_.GetAclConnection(acl_connection_handle); + Address source = connection.GetOwnAddress().GetAddress(); + Address destination = connection.GetAddress().GetAddress(); + + controller->SendLinkLayerPacket(model::packets::LlcpBuilder::Create( + source, destination, std::vector(data, data + len))); + }}; lm_.reset(link_manager_create(controller_ops_)); ll_.reset(link_layer_create(controller_ops_)); @@ -2124,102 +2022,92 @@ LinkLayerController::LinkLayerController(const Address& address, LinkLayerController::~LinkLayerController() {} void LinkLayerController::SendLeLinkLayerPacket( - std::unique_ptr packet, - int8_t tx_power) { - std::shared_ptr shared_packet = - std::move(packet); + std::unique_ptr packet, int8_t tx_power) { + std::shared_ptr shared_packet = std::move(packet); ScheduleTask(kNoDelayMs, [this, shared_packet, tx_power]() { send_to_remote_(shared_packet, Phy::Type::LOW_ENERGY, tx_power); }); } void LinkLayerController::SendLinkLayerPacket( - std::unique_ptr packet, - int8_t tx_power) { - std::shared_ptr shared_packet = - std::move(packet); + std::unique_ptr packet, int8_t tx_power) { + std::shared_ptr shared_packet = std::move(packet); ScheduleTask(kNoDelayMs, [this, shared_packet, tx_power]() { send_to_remote_(shared_packet, Phy::Type::BR_EDR, tx_power); }); } -ErrorCode LinkLayerController::SendLeCommandToRemoteByAddress( - OpCode opcode, const Address& own_address, const Address& peer_address) { +ErrorCode LinkLayerController::SendLeCommandToRemoteByAddress(OpCode opcode, + const Address& own_address, + const Address& peer_address) { switch (opcode) { case (OpCode::LE_READ_REMOTE_FEATURES): - SendLeLinkLayerPacket(model::packets::LeReadRemoteFeaturesBuilder::Create( - own_address, peer_address)); + SendLeLinkLayerPacket( + model::packets::LeReadRemoteFeaturesBuilder::Create(own_address, peer_address)); break; default: - INFO(id_, "Dropping unhandled command 0x{:04x}", - static_cast(opcode)); + INFO(id_, "Dropping unhandled command 0x{:04x}", static_cast(opcode)); return ErrorCode::UNKNOWN_HCI_COMMAND; } return ErrorCode::SUCCESS; } -ErrorCode LinkLayerController::SendCommandToRemoteByAddress( - OpCode opcode, pdl::packet::slice args, const Address& own_address, - const Address& peer_address) { +ErrorCode LinkLayerController::SendCommandToRemoteByAddress(OpCode opcode, pdl::packet::slice args, + const Address& own_address, + const Address& peer_address) { switch (opcode) { case (OpCode::REMOTE_NAME_REQUEST): // LMP features get requested with remote name requests. - SendLinkLayerPacket(model::packets::ReadRemoteLmpFeaturesBuilder::Create( - own_address, peer_address)); - SendLinkLayerPacket(model::packets::RemoteNameRequestBuilder::Create( - own_address, peer_address)); + SendLinkLayerPacket( + model::packets::ReadRemoteLmpFeaturesBuilder::Create(own_address, peer_address)); + SendLinkLayerPacket( + model::packets::RemoteNameRequestBuilder::Create(own_address, peer_address)); break; case (OpCode::READ_REMOTE_SUPPORTED_FEATURES): - SendLinkLayerPacket( - model::packets::ReadRemoteSupportedFeaturesBuilder::Create( - own_address, peer_address)); + SendLinkLayerPacket(model::packets::ReadRemoteSupportedFeaturesBuilder::Create(own_address, + peer_address)); break; case (OpCode::READ_REMOTE_EXTENDED_FEATURES): { pdl::packet::slice page_number_slice = args.subrange(5, 1); uint8_t page_number = page_number_slice.read_le(); - SendLinkLayerPacket( - model::packets::ReadRemoteExtendedFeaturesBuilder::Create( + SendLinkLayerPacket(model::packets::ReadRemoteExtendedFeaturesBuilder::Create( own_address, peer_address, page_number)); } break; case (OpCode::READ_REMOTE_VERSION_INFORMATION): - SendLinkLayerPacket( - model::packets::ReadRemoteVersionInformationBuilder::Create( + SendLinkLayerPacket(model::packets::ReadRemoteVersionInformationBuilder::Create( own_address, peer_address)); break; case (OpCode::READ_CLOCK_OFFSET): - SendLinkLayerPacket(model::packets::ReadClockOffsetBuilder::Create( - own_address, peer_address)); + SendLinkLayerPacket( + model::packets::ReadClockOffsetBuilder::Create(own_address, peer_address)); break; default: - INFO(id_, "Dropping unhandled command 0x{:04x}", - static_cast(opcode)); + INFO(id_, "Dropping unhandled command 0x{:04x}", static_cast(opcode)); return ErrorCode::UNKNOWN_HCI_COMMAND; } return ErrorCode::SUCCESS; } -ErrorCode LinkLayerController::SendCommandToRemoteByHandle( - OpCode opcode, pdl::packet::slice args, uint16_t handle) { +ErrorCode LinkLayerController::SendCommandToRemoteByHandle(OpCode opcode, pdl::packet::slice args, + uint16_t handle) { if (!connections_.HasHandle(handle)) { return ErrorCode::UNKNOWN_CONNECTION; } switch (opcode) { case (OpCode::LE_READ_REMOTE_FEATURES): - return SendLeCommandToRemoteByAddress( - opcode, connections_.GetOwnAddress(handle).GetAddress(), - connections_.GetAddress(handle).GetAddress()); + return SendLeCommandToRemoteByAddress(opcode, connections_.GetOwnAddress(handle).GetAddress(), + connections_.GetAddress(handle).GetAddress()); default: - return SendCommandToRemoteByAddress( - opcode, args, connections_.GetOwnAddress(handle).GetAddress(), - connections_.GetAddress(handle).GetAddress()); + return SendCommandToRemoteByAddress(opcode, args, + connections_.GetOwnAddress(handle).GetAddress(), + connections_.GetAddress(handle).GetAddress()); } } -ErrorCode LinkLayerController::SendAclToRemote( - bluetooth::hci::AclView acl_packet) { +ErrorCode LinkLayerController::SendAclToRemote(bluetooth::hci::AclView acl_packet) { uint16_t handle = acl_packet.GetHandle(); if (!connections_.HasHandle(handle)) { return ErrorCode::UNKNOWN_CONNECTION; @@ -2231,10 +2119,10 @@ ErrorCode LinkLayerController::SendAclToRemote( auto acl_packet_payload = acl_packet.GetPayload(); auto acl = model::packets::AclBuilder::Create( - my_address.GetAddress(), destination.GetAddress(), - static_cast(acl_packet.GetPacketBoundaryFlag()), - static_cast(acl_packet.GetBroadcastFlag()), - std::vector(acl_packet_payload.begin(), acl_packet_payload.end())); + my_address.GetAddress(), destination.GetAddress(), + static_cast(acl_packet.GetPacketBoundaryFlag()), + static_cast(acl_packet.GetBroadcastFlag()), + std::vector(acl_packet_payload.begin(), acl_packet_payload.end())); switch (phy) { case Phy::Type::BR_EDR: @@ -2247,13 +2135,12 @@ ErrorCode LinkLayerController::SendAclToRemote( ScheduleTask(kNoDelayMs, [this, handle]() { send_event_(bluetooth::hci::NumberOfCompletedPacketsBuilder::Create( - {bluetooth::hci::CompletedPackets(handle, 1)})); + {bluetooth::hci::CompletedPackets(handle, 1)})); }); return ErrorCode::SUCCESS; } -ErrorCode LinkLayerController::SendScoToRemote( - bluetooth::hci::ScoView sco_packet) { +ErrorCode LinkLayerController::SendScoToRemote(bluetooth::hci::ScoView sco_packet) { uint16_t handle = sco_packet.GetHandle(); if (!connections_.HasScoHandle(handle)) { return ErrorCode::UNKNOWN_CONNECTION; @@ -2266,13 +2153,13 @@ ErrorCode LinkLayerController::SendScoToRemote( auto sco_data = sco_packet.GetData(); std::vector sco_data_bytes(sco_data.begin(), sco_data.end()); - SendLinkLayerPacket(model::packets::ScoBuilder::Create( - source, destination, std::move(sco_data_bytes))); + SendLinkLayerPacket( + model::packets::ScoBuilder::Create(source, destination, std::move(sco_data_bytes))); return ErrorCode::SUCCESS; } -void LinkLayerController::IncomingPacket( - model::packets::LinkLayerPacketView incoming, int8_t rssi) { +void LinkLayerController::IncomingPacket(model::packets::LinkLayerPacketView incoming, + int8_t rssi) { ASSERT(incoming.IsValid()); auto destination_address = incoming.GetDestinationAddress(); @@ -2293,8 +2180,7 @@ void LinkLayerController::IncomingPacket( } // Check public address - if (destination_address == address_ || - destination_address == random_address_) { + if (destination_address == address_ || destination_address == random_address_) { address_matches = true; } @@ -2307,8 +2193,7 @@ void LinkLayerController::IncomingPacket( auto source_address = incoming.GetSourceAddress(); auto handle = connections_.GetHandleOnlyAddress(source_address); if (handle != kReservedHandle) { - if (connections_.GetOwnAddress(handle).GetAddress() == - destination_address) { + if (connections_.GetOwnAddress(handle).GetAddress() == destination_address) { address_matches = true; // Update link timeout for valid ACL connections @@ -2318,9 +2203,8 @@ void LinkLayerController::IncomingPacket( // Drop packets not addressed to me if (!address_matches) { - INFO(id_, "{} | Dropping packet not addressed to me {}->{} (type 0x{:x})", - address_, source_address, destination_address, - static_cast(incoming.GetType())); + INFO(id_, "{} | Dropping packet not addressed to me {}->{} (type 0x{:x})", address_, + source_address, destination_address, static_cast(incoming.GetType())); return; } @@ -2473,27 +2357,24 @@ void LinkLayerController::IncomingPacket( } } -void LinkLayerController::IncomingAclPacket( - model::packets::LinkLayerPacketView incoming, int8_t rssi) { +void LinkLayerController::IncomingAclPacket(model::packets::LinkLayerPacketView incoming, + int8_t rssi) { auto acl = model::packets::AclView::Create(incoming); ASSERT(acl.IsValid()); auto acl_data = acl.GetData(); - auto packet_boundary_flag = - bluetooth::hci::PacketBoundaryFlag(acl.GetPacketBoundaryFlag()); + auto packet_boundary_flag = bluetooth::hci::PacketBoundaryFlag(acl.GetPacketBoundaryFlag()); auto broadcast_flag = bluetooth::hci::BroadcastFlag(acl.GetBroadcastFlag()); if (packet_boundary_flag == bluetooth::hci::PacketBoundaryFlag::FIRST_NON_AUTOMATICALLY_FLUSHABLE) { - packet_boundary_flag = - bluetooth::hci::PacketBoundaryFlag::FIRST_AUTOMATICALLY_FLUSHABLE; + packet_boundary_flag = bluetooth::hci::PacketBoundaryFlag::FIRST_AUTOMATICALLY_FLUSHABLE; } - INFO(id_, "Acl Packet [{}] {} -> {}", acl_data.size(), - incoming.GetSourceAddress(), incoming.GetDestinationAddress()); + INFO(id_, "Acl Packet [{}] {} -> {}", acl_data.size(), incoming.GetSourceAddress(), + incoming.GetDestinationAddress()); - uint16_t connection_handle = - connections_.GetHandleOnlyAddress(incoming.GetSourceAddress()); + uint16_t connection_handle = connections_.GetHandleOnlyAddress(incoming.GetSourceAddress()); if (connection_handle == kReservedHandle) { INFO(id_, "Dropping packet since connection does not exist"); return; @@ -2512,20 +2393,17 @@ void LinkLayerController::IncomingAclPacket( std::vector fragment(acl_data.begin() + offset, acl_data.begin() + offset + fragment_size); - auto acl_packet = bluetooth::hci::AclBuilder::Create( - connection_handle, packet_boundary_flag, broadcast_flag, - std::move(fragment)); + auto acl_packet = bluetooth::hci::AclBuilder::Create(connection_handle, packet_boundary_flag, + broadcast_flag, std::move(fragment)); send_acl_(std::move(acl_packet)); - packet_boundary_flag = - bluetooth::hci::PacketBoundaryFlag::CONTINUING_FRAGMENT; + packet_boundary_flag = bluetooth::hci::PacketBoundaryFlag::CONTINUING_FRAGMENT; offset += fragment_size; } } -void LinkLayerController::IncomingScoPacket( - model::packets::LinkLayerPacketView incoming) { +void LinkLayerController::IncomingScoPacket(model::packets::LinkLayerPacketView incoming) { Address source = incoming.GetSourceAddress(); uint16_t sco_handle = connections_.GetScoHandle(source); if (!connections_.HasScoHandle(sco_handle)) { @@ -2542,63 +2420,54 @@ void LinkLayerController::IncomingScoPacket( incoming.GetSourceAddress(), incoming.GetDestinationAddress()); send_sco_(bluetooth::hci::ScoBuilder::Create( - sco_handle, bluetooth::hci::PacketStatusFlag::CORRECTLY_RECEIVED, - sco_data_bytes)); + sco_handle, bluetooth::hci::PacketStatusFlag::CORRECTLY_RECEIVED, sco_data_bytes)); } -void LinkLayerController::IncomingRemoteNameRequest( - model::packets::LinkLayerPacketView incoming) { +void LinkLayerController::IncomingRemoteNameRequest(model::packets::LinkLayerPacketView incoming) { auto view = model::packets::RemoteNameRequestView::Create(incoming); ASSERT(view.IsValid()); SendLinkLayerPacket(model::packets::RemoteNameRequestResponseBuilder::Create( - incoming.GetDestinationAddress(), incoming.GetSourceAddress(), - local_name_)); + incoming.GetDestinationAddress(), incoming.GetSourceAddress(), local_name_)); } void LinkLayerController::IncomingRemoteNameRequestResponse( - model::packets::LinkLayerPacketView incoming) { + model::packets::LinkLayerPacketView incoming) { auto view = model::packets::RemoteNameRequestResponseView::Create(incoming); ASSERT(view.IsValid()); if (IsEventUnmasked(EventCode::REMOTE_NAME_REQUEST_COMPLETE)) { send_event_(bluetooth::hci::RemoteNameRequestCompleteBuilder::Create( - ErrorCode::SUCCESS, incoming.GetSourceAddress(), view.GetName())); + ErrorCode::SUCCESS, incoming.GetSourceAddress(), view.GetName())); } } void LinkLayerController::IncomingReadRemoteLmpFeatures( - model::packets::LinkLayerPacketView incoming) { - SendLinkLayerPacket( - model::packets::ReadRemoteLmpFeaturesResponseBuilder::Create( - incoming.GetDestinationAddress(), incoming.GetSourceAddress(), - host_supported_features_)); + model::packets::LinkLayerPacketView incoming) { + SendLinkLayerPacket(model::packets::ReadRemoteLmpFeaturesResponseBuilder::Create( + incoming.GetDestinationAddress(), incoming.GetSourceAddress(), host_supported_features_)); } void LinkLayerController::IncomingReadRemoteLmpFeaturesResponse( - model::packets::LinkLayerPacketView incoming) { - auto view = - model::packets::ReadRemoteLmpFeaturesResponseView::Create(incoming); + model::packets::LinkLayerPacketView incoming) { + auto view = model::packets::ReadRemoteLmpFeaturesResponseView::Create(incoming); ASSERT(view.IsValid()); if (IsEventUnmasked(EventCode::REMOTE_HOST_SUPPORTED_FEATURES_NOTIFICATION)) { - send_event_( - bluetooth::hci::RemoteHostSupportedFeaturesNotificationBuilder::Create( + send_event_(bluetooth::hci::RemoteHostSupportedFeaturesNotificationBuilder::Create( incoming.GetSourceAddress(), view.GetFeatures())); } } void LinkLayerController::IncomingReadRemoteSupportedFeatures( - model::packets::LinkLayerPacketView incoming) { - SendLinkLayerPacket( - model::packets::ReadRemoteSupportedFeaturesResponseBuilder::Create( + model::packets::LinkLayerPacketView incoming) { + SendLinkLayerPacket(model::packets::ReadRemoteSupportedFeaturesResponseBuilder::Create( incoming.GetDestinationAddress(), incoming.GetSourceAddress(), properties_.lmp_features[0])); } void LinkLayerController::IncomingReadRemoteSupportedFeaturesResponse( - model::packets::LinkLayerPacketView incoming) { - auto view = - model::packets::ReadRemoteSupportedFeaturesResponseView::Create(incoming); + model::packets::LinkLayerPacketView incoming) { + auto view = model::packets::ReadRemoteSupportedFeaturesResponseView::Create(incoming); ASSERT(view.IsValid()); Address source = incoming.GetSourceAddress(); uint16_t handle = connections_.GetHandleOnlyAddress(source); @@ -2607,14 +2476,13 @@ void LinkLayerController::IncomingReadRemoteSupportedFeaturesResponse( return; } if (IsEventUnmasked(EventCode::READ_REMOTE_SUPPORTED_FEATURES_COMPLETE)) { - send_event_( - bluetooth::hci::ReadRemoteSupportedFeaturesCompleteBuilder::Create( + send_event_(bluetooth::hci::ReadRemoteSupportedFeaturesCompleteBuilder::Create( ErrorCode::SUCCESS, handle, view.GetFeatures())); } } void LinkLayerController::IncomingReadRemoteExtendedFeatures( - model::packets::LinkLayerPacketView incoming) { + model::packets::LinkLayerPacketView incoming) { auto view = model::packets::ReadRemoteExtendedFeaturesView::Create(incoming); ASSERT(view.IsValid()); uint8_t page_number = view.GetPageNumber(); @@ -2622,17 +2490,14 @@ void LinkLayerController::IncomingReadRemoteExtendedFeatures( if (page_number >= properties_.lmp_features.size()) { error_code = static_cast(ErrorCode::INVALID_LMP_OR_LL_PARAMETERS); } - SendLinkLayerPacket( - model::packets::ReadRemoteExtendedFeaturesResponseBuilder::Create( - incoming.GetDestinationAddress(), incoming.GetSourceAddress(), - error_code, page_number, GetMaxLmpFeaturesPageNumber(), - GetLmpFeatures(page_number))); + SendLinkLayerPacket(model::packets::ReadRemoteExtendedFeaturesResponseBuilder::Create( + incoming.GetDestinationAddress(), incoming.GetSourceAddress(), error_code, page_number, + GetMaxLmpFeaturesPageNumber(), GetLmpFeatures(page_number))); } void LinkLayerController::IncomingReadRemoteExtendedFeaturesResponse( - model::packets::LinkLayerPacketView incoming) { - auto view = - model::packets::ReadRemoteExtendedFeaturesResponseView::Create(incoming); + model::packets::LinkLayerPacketView incoming) { + auto view = model::packets::ReadRemoteExtendedFeaturesResponseView::Create(incoming); ASSERT(view.IsValid()); Address source = incoming.GetSourceAddress(); uint16_t handle = connections_.GetHandleOnlyAddress(source); @@ -2641,27 +2506,22 @@ void LinkLayerController::IncomingReadRemoteExtendedFeaturesResponse( return; } if (IsEventUnmasked(EventCode::READ_REMOTE_EXTENDED_FEATURES_COMPLETE)) { - send_event_( - bluetooth::hci::ReadRemoteExtendedFeaturesCompleteBuilder::Create( - static_cast(view.GetStatus()), handle, - view.GetPageNumber(), view.GetMaxPageNumber(), view.GetFeatures())); + send_event_(bluetooth::hci::ReadRemoteExtendedFeaturesCompleteBuilder::Create( + static_cast(view.GetStatus()), handle, view.GetPageNumber(), + view.GetMaxPageNumber(), view.GetFeatures())); } } -void LinkLayerController::IncomingReadRemoteVersion( - model::packets::LinkLayerPacketView incoming) { - SendLinkLayerPacket( - model::packets::ReadRemoteVersionInformationResponseBuilder::Create( +void LinkLayerController::IncomingReadRemoteVersion(model::packets::LinkLayerPacketView incoming) { + SendLinkLayerPacket(model::packets::ReadRemoteVersionInformationResponseBuilder::Create( incoming.GetDestinationAddress(), incoming.GetSourceAddress(), static_cast(properties_.lmp_version), - static_cast(properties_.lmp_subversion), - properties_.company_identifier)); + static_cast(properties_.lmp_subversion), properties_.company_identifier)); } void LinkLayerController::IncomingReadRemoteVersionResponse( - model::packets::LinkLayerPacketView incoming) { - auto view = model::packets::ReadRemoteVersionInformationResponseView::Create( - incoming); + model::packets::LinkLayerPacketView incoming) { + auto view = model::packets::ReadRemoteVersionInformationResponseView::Create(incoming); ASSERT(view.IsValid()); Address source = incoming.GetSourceAddress(); uint16_t handle = connections_.GetHandleOnlyAddress(source); @@ -2670,22 +2530,19 @@ void LinkLayerController::IncomingReadRemoteVersionResponse( return; } if (IsEventUnmasked(EventCode::READ_REMOTE_VERSION_INFORMATION_COMPLETE)) { - send_event_( - bluetooth::hci::ReadRemoteVersionInformationCompleteBuilder::Create( - ErrorCode::SUCCESS, handle, view.GetLmpVersion(), - view.GetManufacturerName(), view.GetLmpSubversion())); + send_event_(bluetooth::hci::ReadRemoteVersionInformationCompleteBuilder::Create( + ErrorCode::SUCCESS, handle, view.GetLmpVersion(), view.GetManufacturerName(), + view.GetLmpSubversion())); } } -void LinkLayerController::IncomingReadClockOffset( - model::packets::LinkLayerPacketView incoming) { +void LinkLayerController::IncomingReadClockOffset(model::packets::LinkLayerPacketView incoming) { SendLinkLayerPacket(model::packets::ReadClockOffsetResponseBuilder::Create( - incoming.GetDestinationAddress(), incoming.GetSourceAddress(), - GetClockOffset())); + incoming.GetDestinationAddress(), incoming.GetSourceAddress(), GetClockOffset())); } void LinkLayerController::IncomingReadClockOffsetResponse( - model::packets::LinkLayerPacketView incoming) { + model::packets::LinkLayerPacketView incoming) { auto view = model::packets::ReadClockOffsetResponseView::Create(incoming); ASSERT(view.IsValid()); Address source = incoming.GetSourceAddress(); @@ -2695,13 +2552,12 @@ void LinkLayerController::IncomingReadClockOffsetResponse( return; } if (IsEventUnmasked(EventCode::READ_CLOCK_OFFSET_COMPLETE)) { - send_event_(bluetooth::hci::ReadClockOffsetCompleteBuilder::Create( - ErrorCode::SUCCESS, handle, view.GetOffset())); + send_event_(bluetooth::hci::ReadClockOffsetCompleteBuilder::Create(ErrorCode::SUCCESS, handle, + view.GetOffset())); } } -void LinkLayerController::IncomingDisconnectPacket( - model::packets::LinkLayerPacketView incoming) { +void LinkLayerController::IncomingDisconnectPacket(model::packets::LinkLayerPacketView incoming) { INFO(id_, "Disconnect Packet"); auto disconnect = model::packets::DisconnectView::Create(incoming); ASSERT(disconnect.IsValid()); @@ -2714,22 +2570,20 @@ void LinkLayerController::IncomingDisconnectPacket( } auto is_br_edr = connections_.GetPhyType(handle) == Phy::Type::BR_EDR; ASSERT_LOG( - connections_.Disconnect( - handle, [this](TaskId task_id) { CancelScheduledTask(task_id); }), - "GetHandle() returned invalid handle 0x{:x}", handle); + connections_.Disconnect(handle, [this](TaskId task_id) { CancelScheduledTask(task_id); }), + "GetHandle() returned invalid handle 0x{:x}", handle); uint8_t reason = disconnect.GetReason(); SendDisconnectionCompleteEvent(handle, ErrorCode(reason)); if (is_br_edr) { - ASSERT(link_manager_remove_link( - lm_.get(), reinterpret_cast(peer.data()))); + ASSERT(link_manager_remove_link(lm_.get(), reinterpret_cast(peer.data()))); } else { ASSERT(link_layer_remove_link(ll_.get(), handle)); } } -void LinkLayerController::IncomingInquiryPacket( - model::packets::LinkLayerPacketView incoming, uint8_t rssi) { +void LinkLayerController::IncomingInquiryPacket(model::packets::LinkLayerPacketView incoming, + uint8_t rssi) { auto inquiry = model::packets::InquiryView::Create(incoming); ASSERT(inquiry.IsValid()); @@ -2746,49 +2600,40 @@ void LinkLayerController::IncomingInquiryPacket( switch (inquiry.GetInquiryType()) { case (model::packets::InquiryType::STANDARD): { SendLinkLayerPacket(model::packets::InquiryResponseBuilder::Create( - GetAddress(), peer, static_cast(GetPageScanRepetitionMode()), - class_of_device_, GetClockOffset())); + GetAddress(), peer, static_cast(GetPageScanRepetitionMode()), + class_of_device_, GetClockOffset())); } break; case (model::packets::InquiryType::RSSI): { - SendLinkLayerPacket( - model::packets::InquiryResponseWithRssiBuilder::Create( - GetAddress(), peer, - static_cast(GetPageScanRepetitionMode()), + SendLinkLayerPacket(model::packets::InquiryResponseWithRssiBuilder::Create( + GetAddress(), peer, static_cast(GetPageScanRepetitionMode()), class_of_device_, GetClockOffset(), rssi)); } break; case (model::packets::InquiryType::EXTENDED): { - SendLinkLayerPacket( - model::packets::ExtendedInquiryResponseBuilder::Create( - GetAddress(), peer, - static_cast(GetPageScanRepetitionMode()), - class_of_device_, GetClockOffset(), rssi, - extended_inquiry_response_)); + SendLinkLayerPacket(model::packets::ExtendedInquiryResponseBuilder::Create( + GetAddress(), peer, static_cast(GetPageScanRepetitionMode()), + class_of_device_, GetClockOffset(), rssi, extended_inquiry_response_)); } break; default: - WARNING(id_, "Unhandled Incoming Inquiry of type {}", - static_cast(inquiry.GetType())); + WARNING(id_, "Unhandled Incoming Inquiry of type {}", static_cast(inquiry.GetType())); return; } // TODO: Send an Inquiry Response Notification Event 7.7.74 } void LinkLayerController::IncomingInquiryResponsePacket( - model::packets::LinkLayerPacketView incoming) { - auto basic_inquiry_response = - model::packets::BasicInquiryResponseView::Create(incoming); + model::packets::LinkLayerPacketView incoming) { + auto basic_inquiry_response = model::packets::BasicInquiryResponseView::Create(incoming); ASSERT(basic_inquiry_response.IsValid()); std::vector eir; switch (basic_inquiry_response.GetInquiryType()) { case (model::packets::InquiryType::STANDARD): { // TODO: Support multiple inquiries in the same packet. - auto inquiry_response = - model::packets::InquiryResponseView::Create(basic_inquiry_response); + auto inquiry_response = model::packets::InquiryResponseView::Create(basic_inquiry_response); ASSERT(inquiry_response.IsValid()); auto page_scan_repetition_mode = - (bluetooth::hci::PageScanRepetitionMode) - inquiry_response.GetPageScanRepetitionMode(); + (bluetooth::hci::PageScanRepetitionMode)inquiry_response.GetPageScanRepetitionMode(); std::vector responses; responses.emplace_back(); @@ -2803,13 +2648,11 @@ void LinkLayerController::IncomingInquiryResponsePacket( case (model::packets::InquiryType::RSSI): { auto inquiry_response = - model::packets::InquiryResponseWithRssiView::Create( - basic_inquiry_response); + model::packets::InquiryResponseWithRssiView::Create(basic_inquiry_response); ASSERT(inquiry_response.IsValid()); auto page_scan_repetition_mode = - (bluetooth::hci::PageScanRepetitionMode) - inquiry_response.GetPageScanRepetitionMode(); + (bluetooth::hci::PageScanRepetitionMode)inquiry_response.GetPageScanRepetitionMode(); std::vector responses; responses.emplace_back(); @@ -2819,24 +2662,21 @@ void LinkLayerController::IncomingInquiryResponsePacket( responses.back().clock_offset_ = inquiry_response.GetClockOffset(); responses.back().rssi_ = inquiry_response.GetRssi(); if (IsEventUnmasked(EventCode::INQUIRY_RESULT_WITH_RSSI)) { - send_event_( - bluetooth::hci::InquiryResultWithRssiBuilder::Create(responses)); + send_event_(bluetooth::hci::InquiryResultWithRssiBuilder::Create(responses)); } } break; case (model::packets::InquiryType::EXTENDED): { auto inquiry_response = - model::packets::ExtendedInquiryResponseView::Create( - basic_inquiry_response); + model::packets::ExtendedInquiryResponseView::Create(basic_inquiry_response); ASSERT(inquiry_response.IsValid()); send_event_(bluetooth::hci::ExtendedInquiryResultBuilder::Create( - inquiry_response.GetSourceAddress(), - static_cast( - inquiry_response.GetPageScanRepetitionMode()), - inquiry_response.GetClassOfDevice(), - inquiry_response.GetClockOffset(), inquiry_response.GetRssi(), - inquiry_response.GetExtendedInquiryResponse())); + inquiry_response.GetSourceAddress(), + static_cast( + inquiry_response.GetPageScanRepetitionMode()), + inquiry_response.GetClassOfDevice(), inquiry_response.GetClockOffset(), + inquiry_response.GetRssi(), inquiry_response.GetExtendedInquiryResponse())); } break; default: @@ -2845,8 +2685,7 @@ void LinkLayerController::IncomingInquiryResponsePacket( } } -Address LinkLayerController::generate_rpa( - std::array irk) { +Address LinkLayerController::generate_rpa(std::array irk) { // most significant bit, bit7, bit6 is 01 to be resolvable random // Bits of the random part of prand shall not be all 1 or all 0 std::array prand; @@ -2868,8 +2707,7 @@ Address LinkLayerController::generate_rpa( rpa.address[5] = prand[2]; /* encrypt with IRK */ - rootcanal::crypto::Octet16 p = - rootcanal::crypto::aes_128(irk, prand.data(), 3); + rootcanal::crypto::Octet16 p = rootcanal::crypto::aes_128(irk, prand.data(), 3); /* set hash to be LSB of rpAddress */ rpa.address[0] = p[0]; @@ -2880,12 +2718,12 @@ Address LinkLayerController::generate_rpa( } bool LinkLayerController::irk_is_zero(std::array irk) { - return std::all_of(irk.begin(), irk.end(), [](uint8_t b) { return b == 0; }); + return std::all_of(irk.begin(), irk.end(), [](uint8_t b) { return b == 0; }); } // Handle legacy advertising PDUs while in the Scanning state. void LinkLayerController::ScanIncomingLeLegacyAdvertisingPdu( - model::packets::LeLegacyAdvertisingPduView& pdu, uint8_t rssi) { + model::packets::LeLegacyAdvertisingPduView& pdu, uint8_t rssi) { if (!scanner_.IsEnabled()) { return; } @@ -2893,24 +2731,22 @@ void LinkLayerController::ScanIncomingLeLegacyAdvertisingPdu( auto advertising_type = pdu.GetAdvertisingType(); std::vector advertising_data = pdu.GetAdvertisingData(); - AddressWithType advertising_address{ - pdu.GetSourceAddress(), - static_cast(pdu.GetAdvertisingAddressType())}; + AddressWithType advertising_address{pdu.GetSourceAddress(), + static_cast(pdu.GetAdvertisingAddressType())}; - AddressWithType target_address{ - pdu.GetDestinationAddress(), - static_cast(pdu.GetTargetAddressType())}; + AddressWithType target_address{pdu.GetDestinationAddress(), + static_cast(pdu.GetTargetAddressType())}; bool scannable_advertising = - advertising_type == model::packets::LegacyAdvertisingType::ADV_IND || - advertising_type == model::packets::LegacyAdvertisingType::ADV_SCAN_IND; + advertising_type == model::packets::LegacyAdvertisingType::ADV_IND || + advertising_type == model::packets::LegacyAdvertisingType::ADV_SCAN_IND; bool directed_advertising = - advertising_type == model::packets::LegacyAdvertisingType::ADV_DIRECT_IND; + advertising_type == model::packets::LegacyAdvertisingType::ADV_DIRECT_IND; bool connectable_advertising = - advertising_type == model::packets::LegacyAdvertisingType::ADV_IND || - advertising_type == model::packets::LegacyAdvertisingType::ADV_DIRECT_IND; + advertising_type == model::packets::LegacyAdvertisingType::ADV_IND || + advertising_type == model::packets::LegacyAdvertisingType::ADV_DIRECT_IND; // TODO: check originating PHY, compare against active scanning PHYs // (scanner_.le_1m_phy or scanner_.le_coded_phy). @@ -2921,7 +2757,7 @@ void LinkLayerController::ScanIncomingLeLegacyAdvertisingPdu( // address. The scanner’s filter policy shall then determine if the scanner // responds with a scan request. AddressWithType resolved_advertising_address = - ResolvePrivateAddress(advertising_address).value_or(advertising_address); + ResolvePrivateAddress(advertising_address).value_or(advertising_address); if (resolved_advertising_address != advertising_address) { DEBUG(id_, "Resolved the advertising address {} to {}", advertising_address, @@ -2934,8 +2770,7 @@ void LinkLayerController::ScanIncomingLeLegacyAdvertisingPdu( case bluetooth::hci::LeScanningFilterPolicy::CHECK_INITIATORS_IDENTITY: break; case bluetooth::hci::LeScanningFilterPolicy::FILTER_ACCEPT_LIST_ONLY: - case bluetooth::hci::LeScanningFilterPolicy:: - FILTER_ACCEPT_LIST_AND_INITIATORS_IDENTITY: + case bluetooth::hci::LeScanningFilterPolicy::FILTER_ACCEPT_LIST_AND_INITIATORS_IDENTITY: if (!LeFilterAcceptListContainsDevice(resolved_advertising_address)) { DEBUG(id_, "Legacy advertising ignored by scanner because the advertising " @@ -2978,10 +2813,8 @@ void LinkLayerController::ScanIncomingLeLegacyAdvertisingPdu( // • the TargetA field is identical to the scanner's device address, or // • the TargetA field is a resolvable private address. case bluetooth::hci::LeScanningFilterPolicy::CHECK_INITIATORS_IDENTITY: - case bluetooth::hci::LeScanningFilterPolicy:: - FILTER_ACCEPT_LIST_AND_INITIATORS_IDENTITY: - if (!IsLocalPublicOrRandomAddress(target_address) && - !target_address.IsRpa()) { + case bluetooth::hci::LeScanningFilterPolicy::FILTER_ACCEPT_LIST_AND_INITIATORS_IDENTITY: + if (!IsLocalPublicOrRandomAddress(target_address) && !target_address.IsRpa()) { DEBUG(id_, "Legacy advertising ignored by scanner because the directed " "address {} does not match the current device or is not a " @@ -2990,15 +2823,14 @@ void LinkLayerController::ScanIncomingLeLegacyAdvertisingPdu( return; } should_send_directed_advertising_report = - target_address.IsRpa() && - !ResolveTargetA(target_address, resolved_advertising_address); + target_address.IsRpa() && + !ResolveTargetA(target_address, resolved_advertising_address); break; } } bool should_send_advertising_report = true; - if (scanner_.filter_duplicates != - bluetooth::hci::FilterDuplicates::DISABLED) { + if (scanner_.filter_duplicates != bluetooth::hci::FilterDuplicates::DISABLED) { if (scanner_.IsPacketInHistory(pdu.bytes())) { should_send_advertising_report = false; } else { @@ -3011,19 +2843,15 @@ void LinkLayerController::ScanIncomingLeLegacyAdvertisingPdu( should_send_directed_advertising_report && IsLeEventUnmasked(SubeventCode::DIRECTED_ADVERTISING_REPORT)) { bluetooth::hci::LeDirectedAdvertisingResponse response; - response.event_type_ = - bluetooth::hci::DirectAdvertisingEventType::ADV_DIRECT_IND; - response.address_type_ = - static_cast( + response.event_type_ = bluetooth::hci::DirectAdvertisingEventType::ADV_DIRECT_IND; + response.address_type_ = static_cast( resolved_advertising_address.GetAddressType()); response.address_ = resolved_advertising_address.GetAddress(); - response.direct_address_type_ = - bluetooth::hci::DirectAddressType::RANDOM_DEVICE_ADDRESS; + response.direct_address_type_ = bluetooth::hci::DirectAddressType::RANDOM_DEVICE_ADDRESS; response.direct_address_ = target_address.GetAddress(); response.rssi_ = rssi; - send_event_( - bluetooth::hci::LeDirectedAdvertisingReportBuilder::Create({response})); + send_event_(bluetooth::hci::LeDirectedAdvertisingReportBuilder::Create({response})); } // Legacy scanning, un-directed advertising. @@ -3041,16 +2869,13 @@ void LinkLayerController::ScanIncomingLeLegacyAdvertisingPdu( response.event_type_ = bluetooth::hci::AdvertisingEventType::ADV_IND; break; case model::packets::LegacyAdvertisingType::ADV_DIRECT_IND: - response.event_type_ = - bluetooth::hci::AdvertisingEventType::ADV_DIRECT_IND; + response.event_type_ = bluetooth::hci::AdvertisingEventType::ADV_DIRECT_IND; break; case model::packets::LegacyAdvertisingType::ADV_SCAN_IND: - response.event_type_ = - bluetooth::hci::AdvertisingEventType::ADV_SCAN_IND; + response.event_type_ = bluetooth::hci::AdvertisingEventType::ADV_SCAN_IND; break; case model::packets::LegacyAdvertisingType::ADV_NONCONN_IND: - response.event_type_ = - bluetooth::hci::AdvertisingEventType::ADV_NONCONN_IND; + response.event_type_ = bluetooth::hci::AdvertisingEventType::ADV_NONCONN_IND; break; } @@ -3067,8 +2892,7 @@ void LinkLayerController::ScanIncomingLeLegacyAdvertisingPdu( response.scan_response_ = false; response.legacy_ = true; response.data_status_ = bluetooth::hci::DataStatus::COMPLETE; - response.address_type_ = - static_cast( + response.address_type_ = static_cast( resolved_advertising_address.GetAddressType()); response.address_ = resolved_advertising_address.GetAddress(); response.primary_phy_ = bluetooth::hci::PrimaryPhyType::LE_1M; @@ -3079,26 +2903,23 @@ void LinkLayerController::ScanIncomingLeLegacyAdvertisingPdu( response.periodic_advertising_interval_ = 0; // No periodic advertising. if (directed_advertising) { response.direct_address_type_ = - bluetooth::hci::DirectAdvertisingAddressType( - target_address.GetAddressType()); + bluetooth::hci::DirectAdvertisingAddressType(target_address.GetAddressType()); response.direct_address_ = target_address.GetAddress(); } else { response.direct_address_type_ = - bluetooth::hci::DirectAdvertisingAddressType::NO_ADDRESS_PROVIDED; + bluetooth::hci::DirectAdvertisingAddressType::NO_ADDRESS_PROVIDED; response.direct_address_ = Address::kEmpty; } response.advertising_data_ = advertising_data; - send_event_( - bluetooth::hci::LeExtendedAdvertisingReportBuilder::Create({response})); + send_event_(bluetooth::hci::LeExtendedAdvertisingReportBuilder::Create({response})); } // Did the user enable Active scanning ? - bool active_scanning = - (scanner_.le_1m_phy.enabled && - scanner_.le_1m_phy.scan_type == bluetooth::hci::LeScanType::ACTIVE) || - (scanner_.le_coded_phy.enabled && - scanner_.le_coded_phy.scan_type == bluetooth::hci::LeScanType::ACTIVE); + bool active_scanning = (scanner_.le_1m_phy.enabled && + scanner_.le_1m_phy.scan_type == bluetooth::hci::LeScanType::ACTIVE) || + (scanner_.le_coded_phy.enabled && + scanner_.le_coded_phy.scan_type == bluetooth::hci::LeScanType::ACTIVE); // Active scanning. // Note: only send SCAN requests in response to scannable advertising @@ -3128,13 +2949,10 @@ void LinkLayerController::ScanIncomingLeLegacyAdvertisingPdu( // Scan requests with public or random device addresses must be ignored // when the peer has network privacy mode. - AddressWithType public_address{address_, - AddressType::PUBLIC_DEVICE_ADDRESS}; - AddressWithType random_address{random_address_, - AddressType::RANDOM_DEVICE_ADDRESS}; + AddressWithType public_address{address_, AddressType::PUBLIC_DEVICE_ADDRESS}; + AddressWithType random_address{random_address_, AddressType::RANDOM_DEVICE_ADDRESS}; std::optional resolvable_scanning_address = - GenerateResolvablePrivateAddress(resolved_advertising_address, - IrkSelection::Local); + GenerateResolvablePrivateAddress(resolved_advertising_address, IrkSelection::Local); // The ScanA field of the scanning PDU is generated using the // Resolving List’s Local IRK value and the Resolvable Private Address @@ -3169,8 +2987,7 @@ void LinkLayerController::ScanIncomingLeLegacyAdvertisingPdu( scanner_.primary_scan_response_phy = model::packets::PhyType::LE_1M; scanner_.secondary_scan_response_phy = model::packets::PhyType::NO_PACKETS; scanner_.pending_scan_request = advertising_address; - scanner_.pending_scan_request_timeout = - std::chrono::steady_clock::now() + kScanRequestTimeout; + scanner_.pending_scan_request_timeout = std::chrono::steady_clock::now() + kScanRequestTimeout; INFO(id_, "Sending LE Scan request to advertising address {} with scanning " @@ -3181,26 +2998,24 @@ void LinkLayerController::ScanIncomingLeLegacyAdvertisingPdu( // shall be the same as the advertiser’s device address (AdvA field) // received in the advertising PDU to which the scanner is responding. SendLeLinkLayerPacket(model::packets::LeScanBuilder::Create( - scanning_address.GetAddress(), advertising_address.GetAddress(), - static_cast( - scanning_address.GetAddressType()), - static_cast( - advertising_address.GetAddressType()))); + scanning_address.GetAddress(), advertising_address.GetAddress(), + static_cast(scanning_address.GetAddressType()), + static_cast(advertising_address.GetAddressType()))); } } void LinkLayerController::ConnectIncomingLeLegacyAdvertisingPdu( - model::packets::LeLegacyAdvertisingPduView& pdu) { + model::packets::LeLegacyAdvertisingPduView& pdu) { if (!initiator_.IsEnabled()) { return; } auto advertising_type = pdu.GetAdvertisingType(); bool connectable_advertising = - advertising_type == model::packets::LegacyAdvertisingType::ADV_IND || - advertising_type == model::packets::LegacyAdvertisingType::ADV_DIRECT_IND; + advertising_type == model::packets::LegacyAdvertisingType::ADV_IND || + advertising_type == model::packets::LegacyAdvertisingType::ADV_DIRECT_IND; bool directed_advertising = - advertising_type == model::packets::LegacyAdvertisingType::ADV_DIRECT_IND; + advertising_type == model::packets::LegacyAdvertisingType::ADV_DIRECT_IND; // Connection. // Note: only send CONNECT requests in response to connectable advertising @@ -3218,16 +3033,14 @@ void LinkLayerController::ConnectIncomingLeLegacyAdvertisingPdu( return; } - AddressWithType advertising_address{ - pdu.GetSourceAddress(), - static_cast(pdu.GetAdvertisingAddressType())}; + AddressWithType advertising_address{pdu.GetSourceAddress(), + static_cast(pdu.GetAdvertisingAddressType())}; - AddressWithType target_address{ - pdu.GetDestinationAddress(), - static_cast(pdu.GetTargetAddressType())}; + AddressWithType target_address{pdu.GetDestinationAddress(), + static_cast(pdu.GetTargetAddressType())}; AddressWithType resolved_advertising_address = - ResolvePrivateAddress(advertising_address).value_or(advertising_address); + ResolvePrivateAddress(advertising_address).value_or(advertising_address); // Vol 6, Part B § 4.3.5 Initiator filter policy. switch (initiator_.initiator_filter_policy) { @@ -3268,10 +3081,8 @@ void LinkLayerController::ConnectIncomingLeLegacyAdvertisingPdu( return; } if (!target_address.IsRpa() && - (initiator_.own_address_type == - OwnAddressType::RESOLVABLE_OR_PUBLIC_ADDRESS || - initiator_.own_address_type == - OwnAddressType::RESOLVABLE_OR_RANDOM_ADDRESS)) { + (initiator_.own_address_type == OwnAddressType::RESOLVABLE_OR_PUBLIC_ADDRESS || + initiator_.own_address_type == OwnAddressType::RESOLVABLE_OR_RANDOM_ADDRESS)) { DEBUG(id_, "Directed legacy advertising ignored by initiator because the " "target address {} is static or public and the initiator is " @@ -3282,11 +3093,9 @@ void LinkLayerController::ConnectIncomingLeLegacyAdvertisingPdu( } AddressWithType public_address{address_, AddressType::PUBLIC_DEVICE_ADDRESS}; - AddressWithType random_address{random_address_, - AddressType::RANDOM_DEVICE_ADDRESS}; + AddressWithType random_address{random_address_, AddressType::RANDOM_DEVICE_ADDRESS}; std::optional resolvable_initiating_address = - GenerateResolvablePrivateAddress(resolved_advertising_address, - IrkSelection::Local); + GenerateResolvablePrivateAddress(resolved_advertising_address, IrkSelection::Local); // The Link Layer shall use resolvable private addresses for the initiator’s // device address (InitA field) when initiating connection establishment with @@ -3303,26 +3112,22 @@ void LinkLayerController::ConnectIncomingLeLegacyAdvertisingPdu( initiating_address = random_address; break; case bluetooth::hci::OwnAddressType::RESOLVABLE_OR_PUBLIC_ADDRESS: - initiating_address = - resolvable_initiating_address.value_or(public_address); + initiating_address = resolvable_initiating_address.value_or(public_address); break; case bluetooth::hci::OwnAddressType::RESOLVABLE_OR_RANDOM_ADDRESS: // The random address is checked in Le_Create_Connection or // Le_Extended_Create_Connection. ASSERT(random_address_ != Address::kEmpty); - initiating_address = - resolvable_initiating_address.value_or(random_address); + initiating_address = resolvable_initiating_address.value_or(random_address); break; } - if (!connections_.CreatePendingLeConnection( - advertising_address, - resolved_advertising_address != advertising_address - ? resolved_advertising_address - : AddressWithType{}, - initiating_address)) { - WARNING(id_, "CreatePendingLeConnection failed for connection to {}", - advertising_address); + if (!connections_.CreatePendingLeConnection(advertising_address, + resolved_advertising_address != advertising_address + ? resolved_advertising_address + : AddressWithType{}, + initiating_address)) { + WARNING(id_, "CreatePendingLeConnection failed for connection to {}", advertising_address); } initiator_.pending_connect_request = advertising_address; @@ -3336,20 +3141,17 @@ void LinkLayerController::ConnectIncomingLeLegacyAdvertisingPdu( // received in the advertising event PDU to which the initiator is // responding. SendLeLinkLayerPacket(model::packets::LeConnectBuilder::Create( - initiating_address.GetAddress(), advertising_address.GetAddress(), - static_cast( - initiating_address.GetAddressType()), - static_cast( - advertising_address.GetAddressType()), - // The connection is created with the highest allowed - // value for the connection interval and the latency. - initiator_.le_1m_phy.connection_interval_max, - initiator_.le_1m_phy.max_latency, - initiator_.le_1m_phy.supervision_timeout)); + initiating_address.GetAddress(), advertising_address.GetAddress(), + static_cast(initiating_address.GetAddressType()), + static_cast(advertising_address.GetAddressType()), + // The connection is created with the highest allowed + // value for the connection interval and the latency. + initiator_.le_1m_phy.connection_interval_max, initiator_.le_1m_phy.max_latency, + initiator_.le_1m_phy.supervision_timeout)); } void LinkLayerController::IncomingLeLegacyAdvertisingPdu( - model::packets::LinkLayerPacketView incoming, uint8_t rssi) { + model::packets::LinkLayerPacketView incoming, uint8_t rssi) { auto pdu = model::packets::LeLegacyAdvertisingPduView::Create(incoming); ASSERT(pdu.IsValid()); @@ -3359,7 +3161,7 @@ void LinkLayerController::IncomingLeLegacyAdvertisingPdu( // Handle legacy advertising PDUs while in the Scanning state. void LinkLayerController::ScanIncomingLeExtendedAdvertisingPdu( - model::packets::LeExtendedAdvertisingPduView& pdu, uint8_t rssi) { + model::packets::LeExtendedAdvertisingPduView& pdu, uint8_t rssi) { if (!scanner_.IsEnabled()) { return; } @@ -3369,13 +3171,11 @@ void LinkLayerController::ScanIncomingLeExtendedAdvertisingPdu( } std::vector advertising_data = pdu.GetAdvertisingData(); - AddressWithType advertising_address{ - pdu.GetSourceAddress(), - static_cast(pdu.GetAdvertisingAddressType())}; + AddressWithType advertising_address{pdu.GetSourceAddress(), + static_cast(pdu.GetAdvertisingAddressType())}; - AddressWithType target_address{ - pdu.GetDestinationAddress(), - static_cast(pdu.GetTargetAddressType())}; + AddressWithType target_address{pdu.GetDestinationAddress(), + static_cast(pdu.GetTargetAddressType())}; bool scannable_advertising = pdu.GetScannable(); bool connectable_advertising = pdu.GetConnectable(); @@ -3384,10 +3184,8 @@ void LinkLayerController::ScanIncomingLeExtendedAdvertisingPdu( auto secondary_phy = pdu.GetSecondaryPhy(); // Check originating primary PHY, compare against active scanning PHYs. - if ((primary_phy == model::packets::PhyType::LE_1M && - !scanner_.le_1m_phy.enabled) || - (primary_phy == model::packets::PhyType::LE_CODED_S8 && - !scanner_.le_coded_phy.enabled)) { + if ((primary_phy == model::packets::PhyType::LE_1M && !scanner_.le_1m_phy.enabled) || + (primary_phy == model::packets::PhyType::LE_CODED_S8 && !scanner_.le_coded_phy.enabled)) { DEBUG(id_, "Extended adverising ignored because the scanner is not scanning on " "the primary phy type {}", @@ -3399,14 +3197,11 @@ void LinkLayerController::ScanIncomingLeExtendedAdvertisingPdu( // supported features. The primary PHY is validated by the command // LE Set Extended Scan Parameters. if ((secondary_phy == model::packets::PhyType::LE_2M && - !properties_.SupportsLLFeature( - bluetooth::hci::LLFeaturesBits::LE_2M_PHY)) || + !properties_.SupportsLLFeature(bluetooth::hci::LLFeaturesBits::LE_2M_PHY)) || (secondary_phy == model::packets::PhyType::LE_CODED_S8 && - !properties_.SupportsLLFeature( - bluetooth::hci::LLFeaturesBits::LE_CODED_PHY)) || + !properties_.SupportsLLFeature(bluetooth::hci::LLFeaturesBits::LE_CODED_PHY)) || (secondary_phy == model::packets::PhyType::LE_CODED_S2 && - !properties_.SupportsLLFeature( - bluetooth::hci::LLFeaturesBits::LE_CODED_PHY))) { + !properties_.SupportsLLFeature(bluetooth::hci::LLFeaturesBits::LE_CODED_PHY))) { DEBUG(id_, "Extended adverising ignored because the scanner does not support " "the secondary phy type {}", @@ -3420,14 +3215,13 @@ void LinkLayerController::ScanIncomingLeExtendedAdvertisingPdu( // address. The scanner’s filter policy shall then determine if the scanner // responds with a scan request. AddressWithType resolved_advertising_address = - ResolvePrivateAddress(advertising_address).value_or(advertising_address); + ResolvePrivateAddress(advertising_address).value_or(advertising_address); if (resolved_advertising_address != advertising_address) { DEBUG(id_, "Resolved the advertising address {} to {}", advertising_address, bluetooth::hci::AddressTypeText(advertising_address.GetAddressType()), resolved_advertising_address, - bluetooth::hci::AddressTypeText( - resolved_advertising_address.GetAddressType())); + bluetooth::hci::AddressTypeText(resolved_advertising_address.GetAddressType())); } // Vol 6, Part B § 4.3.3 Scanner filter policy @@ -3436,8 +3230,7 @@ void LinkLayerController::ScanIncomingLeExtendedAdvertisingPdu( case bluetooth::hci::LeScanningFilterPolicy::CHECK_INITIATORS_IDENTITY: break; case bluetooth::hci::LeScanningFilterPolicy::FILTER_ACCEPT_LIST_ONLY: - case bluetooth::hci::LeScanningFilterPolicy:: - FILTER_ACCEPT_LIST_AND_INITIATORS_IDENTITY: + case bluetooth::hci::LeScanningFilterPolicy::FILTER_ACCEPT_LIST_AND_INITIATORS_IDENTITY: if (!LeFilterAcceptListContainsDevice(resolved_advertising_address)) { DEBUG(id_, "Extended advertising ignored by scanner because the advertising " @@ -3471,10 +3264,8 @@ void LinkLayerController::ScanIncomingLeExtendedAdvertisingPdu( // • the TargetA field is identical to the scanner's device address, or // • the TargetA field is a resolvable private address. case bluetooth::hci::LeScanningFilterPolicy::CHECK_INITIATORS_IDENTITY: - case bluetooth::hci::LeScanningFilterPolicy:: - FILTER_ACCEPT_LIST_AND_INITIATORS_IDENTITY: - if (!IsLocalPublicOrRandomAddress(target_address) && - !target_address.IsRpa()) { + case bluetooth::hci::LeScanningFilterPolicy::FILTER_ACCEPT_LIST_AND_INITIATORS_IDENTITY: + if (!IsLocalPublicOrRandomAddress(target_address) && !target_address.IsRpa()) { DEBUG(id_, "Extended advertising ignored by scanner because the directed " "address {} does not match the current device or is not a " @@ -3487,8 +3278,7 @@ void LinkLayerController::ScanIncomingLeExtendedAdvertisingPdu( } bool should_send_advertising_report = true; - if (scanner_.filter_duplicates != - bluetooth::hci::FilterDuplicates::DISABLED) { + if (scanner_.filter_duplicates != bluetooth::hci::FilterDuplicates::DISABLED) { if (scanner_.IsPacketInHistory(pdu.bytes())) { should_send_advertising_report = false; } else { @@ -3505,27 +3295,22 @@ void LinkLayerController::ScanIncomingLeExtendedAdvertisingPdu( response.scan_response_ = false; response.legacy_ = false; response.data_status_ = bluetooth::hci::DataStatus::COMPLETE; - response.address_type_ = - static_cast( + response.address_type_ = static_cast( resolved_advertising_address.GetAddressType()); response.address_ = resolved_advertising_address.GetAddress(); - response.primary_phy_ = - static_cast(primary_phy); - response.secondary_phy_ = - static_cast(secondary_phy); + response.primary_phy_ = static_cast(primary_phy); + response.secondary_phy_ = static_cast(secondary_phy); response.advertising_sid_ = pdu.GetSid(); response.tx_power_ = pdu.GetTxPower(); response.rssi_ = rssi; - response.periodic_advertising_interval_ = - pdu.GetPeriodicAdvertisingInterval(); + response.periodic_advertising_interval_ = pdu.GetPeriodicAdvertisingInterval(); if (directed_advertising) { response.direct_address_type_ = - bluetooth::hci::DirectAdvertisingAddressType( - target_address.GetAddressType()); + bluetooth::hci::DirectAdvertisingAddressType(target_address.GetAddressType()); response.direct_address_ = target_address.GetAddress(); } else { response.direct_address_type_ = - bluetooth::hci::DirectAdvertisingAddressType::NO_ADDRESS_PROVIDED; + bluetooth::hci::DirectAdvertisingAddressType::NO_ADDRESS_PROVIDED; response.direct_address_ = Address::kEmpty; } response.advertising_data_ = advertising_data; @@ -3539,23 +3324,20 @@ void LinkLayerController::ScanIncomingLeExtendedAdvertisingPdu( size_t remaining_size = advertising_data.size() - offset; size_t fragment_size = std::min(max_fragment_size, remaining_size); response.data_status_ = remaining_size <= max_fragment_size - ? bluetooth::hci::DataStatus::COMPLETE - : bluetooth::hci::DataStatus::CONTINUING; - response.advertising_data_ = - std::vector(advertising_data.begin() + offset, - advertising_data.begin() + offset + fragment_size); + ? bluetooth::hci::DataStatus::COMPLETE + : bluetooth::hci::DataStatus::CONTINUING; + response.advertising_data_ = std::vector(advertising_data.begin() + offset, + advertising_data.begin() + offset + fragment_size); offset += fragment_size; - send_event_(bluetooth::hci::LeExtendedAdvertisingReportBuilder::Create( - {response})); + send_event_(bluetooth::hci::LeExtendedAdvertisingReportBuilder::Create({response})); } while (offset < advertising_data.size()); } // Did the user enable Active scanning ? - bool active_scanning = - (scanner_.le_1m_phy.enabled && - scanner_.le_1m_phy.scan_type == bluetooth::hci::LeScanType::ACTIVE) || - (scanner_.le_coded_phy.enabled && - scanner_.le_coded_phy.scan_type == bluetooth::hci::LeScanType::ACTIVE); + bool active_scanning = (scanner_.le_1m_phy.enabled && + scanner_.le_1m_phy.scan_type == bluetooth::hci::LeScanType::ACTIVE) || + (scanner_.le_coded_phy.enabled && + scanner_.le_coded_phy.scan_type == bluetooth::hci::LeScanType::ACTIVE); // Active scanning. // Note: only send SCAN requests in response to scannable advertising @@ -3585,13 +3367,10 @@ void LinkLayerController::ScanIncomingLeExtendedAdvertisingPdu( // Scan requests with public or random device addresses must be ignored // when the peer has network privacy mode. - AddressWithType public_address{address_, - AddressType::PUBLIC_DEVICE_ADDRESS}; - AddressWithType random_address{random_address_, - AddressType::RANDOM_DEVICE_ADDRESS}; + AddressWithType public_address{address_, AddressType::PUBLIC_DEVICE_ADDRESS}; + AddressWithType random_address{random_address_, AddressType::RANDOM_DEVICE_ADDRESS}; std::optional resolvable_address = - GenerateResolvablePrivateAddress(resolved_advertising_address, - IrkSelection::Local); + GenerateResolvablePrivateAddress(resolved_advertising_address, IrkSelection::Local); // The ScanA field of the scanning PDU is generated using the // Resolving List’s Local IRK value and the Resolvable Private Address @@ -3637,16 +3416,14 @@ void LinkLayerController::ScanIncomingLeExtendedAdvertisingPdu( // shall be the same as the advertiser’s device address (AdvA field) // received in the advertising PDU to which the scanner is responding. SendLeLinkLayerPacket(model::packets::LeScanBuilder::Create( - scanning_address.GetAddress(), advertising_address.GetAddress(), - static_cast( - scanning_address.GetAddressType()), - static_cast( - advertising_address.GetAddressType()))); + scanning_address.GetAddress(), advertising_address.GetAddress(), + static_cast(scanning_address.GetAddressType()), + static_cast(advertising_address.GetAddressType()))); } } void LinkLayerController::ConnectIncomingLeExtendedAdvertisingPdu( - model::packets::LeExtendedAdvertisingPduView& pdu) { + model::packets::LeExtendedAdvertisingPduView& pdu) { if (!initiator_.IsEnabled()) { return; } @@ -3665,23 +3442,20 @@ void LinkLayerController::ConnectIncomingLeExtendedAdvertisingPdu( return; } if (initiator_.pending_connect_request) { - DEBUG( - id_, - "Extended advertising ignored because an LE Connect request is already " - "pending"); + DEBUG(id_, + "Extended advertising ignored because an LE Connect request is already " + "pending"); return; } - AddressWithType advertising_address{ - pdu.GetSourceAddress(), - static_cast(pdu.GetAdvertisingAddressType())}; + AddressWithType advertising_address{pdu.GetSourceAddress(), + static_cast(pdu.GetAdvertisingAddressType())}; - AddressWithType target_address{ - pdu.GetDestinationAddress(), - static_cast(pdu.GetTargetAddressType())}; + AddressWithType target_address{pdu.GetDestinationAddress(), + static_cast(pdu.GetTargetAddressType())}; AddressWithType resolved_advertising_address = - ResolvePrivateAddress(advertising_address).value_or(advertising_address); + ResolvePrivateAddress(advertising_address).value_or(advertising_address); // Vol 6, Part B § 4.3.5 Initiator filter policy. switch (initiator_.initiator_filter_policy) { @@ -3722,10 +3496,8 @@ void LinkLayerController::ConnectIncomingLeExtendedAdvertisingPdu( return; } if (!target_address.IsRpa() && - (initiator_.own_address_type == - OwnAddressType::RESOLVABLE_OR_PUBLIC_ADDRESS || - initiator_.own_address_type == - OwnAddressType::RESOLVABLE_OR_RANDOM_ADDRESS)) { + (initiator_.own_address_type == OwnAddressType::RESOLVABLE_OR_PUBLIC_ADDRESS || + initiator_.own_address_type == OwnAddressType::RESOLVABLE_OR_RANDOM_ADDRESS)) { DEBUG(id_, "Directed extended advertising ignored by initiator because the " "target address {} is static or public and the initiator is " @@ -3736,11 +3508,9 @@ void LinkLayerController::ConnectIncomingLeExtendedAdvertisingPdu( } AddressWithType public_address{address_, AddressType::PUBLIC_DEVICE_ADDRESS}; - AddressWithType random_address{random_address_, - AddressType::RANDOM_DEVICE_ADDRESS}; + AddressWithType random_address{random_address_, AddressType::RANDOM_DEVICE_ADDRESS}; std::optional resolvable_initiating_address = - GenerateResolvablePrivateAddress(resolved_advertising_address, - IrkSelection::Local); + GenerateResolvablePrivateAddress(resolved_advertising_address, IrkSelection::Local); // The Link Layer shall use resolvable private addresses for the initiator’s // device address (InitA field) when initiating connection establishment with @@ -3757,26 +3527,22 @@ void LinkLayerController::ConnectIncomingLeExtendedAdvertisingPdu( initiating_address = random_address; break; case bluetooth::hci::OwnAddressType::RESOLVABLE_OR_PUBLIC_ADDRESS: - initiating_address = - resolvable_initiating_address.value_or(public_address); + initiating_address = resolvable_initiating_address.value_or(public_address); break; case bluetooth::hci::OwnAddressType::RESOLVABLE_OR_RANDOM_ADDRESS: // The random address is checked in Le_Create_Connection or // Le_Extended_Create_Connection. ASSERT(random_address_ != Address::kEmpty); - initiating_address = - resolvable_initiating_address.value_or(random_address); + initiating_address = resolvable_initiating_address.value_or(random_address); break; } - if (!connections_.CreatePendingLeConnection( - advertising_address, - resolved_advertising_address != advertising_address - ? resolved_advertising_address - : AddressWithType{}, - initiating_address)) { - WARNING(id_, "CreatePendingLeConnection failed for connection to {}", - advertising_address); + if (!connections_.CreatePendingLeConnection(advertising_address, + resolved_advertising_address != advertising_address + ? resolved_advertising_address + : AddressWithType{}, + initiating_address)) { + WARNING(id_, "CreatePendingLeConnection failed for connection to {}", advertising_address); } initiator_.pending_connect_request = advertising_address; @@ -3790,20 +3556,17 @@ void LinkLayerController::ConnectIncomingLeExtendedAdvertisingPdu( // received in the advertising event PDU to which the initiator is // responding. SendLeLinkLayerPacket(model::packets::LeConnectBuilder::Create( - initiating_address.GetAddress(), advertising_address.GetAddress(), - static_cast( - initiating_address.GetAddressType()), - static_cast( - advertising_address.GetAddressType()), - // The connection is created with the highest allowed value - // for the connection interval and the latency. - initiator_.le_1m_phy.connection_interval_max, - initiator_.le_1m_phy.max_latency, - initiator_.le_1m_phy.supervision_timeout)); + initiating_address.GetAddress(), advertising_address.GetAddress(), + static_cast(initiating_address.GetAddressType()), + static_cast(advertising_address.GetAddressType()), + // The connection is created with the highest allowed value + // for the connection interval and the latency. + initiator_.le_1m_phy.connection_interval_max, initiator_.le_1m_phy.max_latency, + initiator_.le_1m_phy.supervision_timeout)); } void LinkLayerController::IncomingLeExtendedAdvertisingPdu( - model::packets::LinkLayerPacketView incoming, uint8_t rssi) { + model::packets::LinkLayerPacketView incoming, uint8_t rssi) { auto pdu = model::packets::LeExtendedAdvertisingPduView::Create(incoming); ASSERT(pdu.IsValid()); @@ -3812,7 +3575,7 @@ void LinkLayerController::IncomingLeExtendedAdvertisingPdu( } void LinkLayerController::IncomingLePeriodicAdvertisingPdu( - model::packets::LinkLayerPacketView incoming, uint8_t rssi) { + model::packets::LinkLayerPacketView incoming, uint8_t rssi) { auto pdu = model::packets::LePeriodicAdvertisingPduView::Create(incoming); ASSERT(pdu.IsValid()); @@ -3826,9 +3589,8 @@ void LinkLayerController::IncomingLePeriodicAdvertisingPdu( return; } - AddressWithType advertiser_address{ - pdu.GetSourceAddress(), - static_cast(pdu.GetAdvertisingAddressType())}; + AddressWithType advertiser_address{pdu.GetSourceAddress(), + static_cast(pdu.GetAdvertisingAddressType())}; uint8_t advertising_sid = pdu.GetSid(); // When a scanner receives an advertising packet that contains a resolvable @@ -3837,20 +3599,20 @@ void LinkLayerController::IncomingLePeriodicAdvertisingPdu( // address. The scanner's periodic sync establishment filter policy shall // determine if the scanner processes the advertising packet. AddressWithType resolved_advertiser_address = - ResolvePrivateAddress(advertiser_address).value_or(advertiser_address); + ResolvePrivateAddress(advertiser_address).value_or(advertiser_address); bluetooth::hci::AdvertiserAddressType advertiser_address_type; switch (resolved_advertiser_address.GetAddressType()) { case AddressType::PUBLIC_DEVICE_ADDRESS: case AddressType::PUBLIC_IDENTITY_ADDRESS: default: - advertiser_address_type = bluetooth::hci::AdvertiserAddressType:: - PUBLIC_DEVICE_OR_IDENTITY_ADDRESS; + advertiser_address_type = + bluetooth::hci::AdvertiserAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS; break; case AddressType::RANDOM_DEVICE_ADDRESS: case AddressType::RANDOM_IDENTITY_ADDRESS: - advertiser_address_type = bluetooth::hci::AdvertiserAddressType:: - RANDOM_DEVICE_OR_IDENTITY_ADDRESS; + advertiser_address_type = + bluetooth::hci::AdvertiserAddressType::RANDOM_DEVICE_OR_IDENTITY_ADDRESS; break; } @@ -3861,24 +3623,21 @@ void LinkLayerController::IncomingLePeriodicAdvertisingPdu( bool matches_synchronizing = false; if (synchronizing_.has_value()) { matches_synchronizing = - synchronizing_->options.use_periodic_advertiser_list_ - ? LePeriodicAdvertiserListContainsDevice( - advertiser_address_type, - resolved_advertiser_address.GetAddress(), advertising_sid) - : synchronizing_->advertiser_address_type == - advertiser_address_type && - synchronizing_->advertiser_address == - resolved_advertiser_address.GetAddress() && - synchronizing_->advertising_sid == advertising_sid; + synchronizing_->options.use_periodic_advertiser_list_ + ? LePeriodicAdvertiserListContainsDevice( + advertiser_address_type, resolved_advertiser_address.GetAddress(), + advertising_sid) + : synchronizing_->advertiser_address_type == advertiser_address_type && + synchronizing_->advertiser_address == + resolved_advertiser_address.GetAddress() && + synchronizing_->advertising_sid == advertising_sid; } // If the periodic advertising event matches the synchronizing state, // create the synchronized train and report to the Host. if (matches_synchronizing) { - INFO(id_, "Established Sync with advertiser {}[{}] - SID 0x{:x}", - advertiser_address, - bluetooth::hci::AdvertiserAddressTypeText(advertiser_address_type), - advertising_sid); + INFO(id_, "Established Sync with advertiser {}[{}] - SID 0x{:x}", advertiser_address, + bluetooth::hci::AdvertiserAddressTypeText(advertiser_address_type), advertising_sid); // Use the first unused Sync_Handle. // Note: sync handles are allocated from a different number space // compared to connection handles. @@ -3887,30 +3646,25 @@ void LinkLayerController::IncomingLePeriodicAdvertisingPdu( } // Notify of the new Synchronized train. - if (IsLeEventUnmasked( - SubeventCode::PERIODIC_ADVERTISING_SYNC_ESTABLISHED)) { - send_event_( - bluetooth::hci::LePeriodicAdvertisingSyncEstablishedBuilder::Create( + if (IsLeEventUnmasked(SubeventCode::PERIODIC_ADVERTISING_SYNC_ESTABLISHED)) { + send_event_(bluetooth::hci::LePeriodicAdvertisingSyncEstablishedBuilder::Create( ErrorCode::SUCCESS, sync_handle, advertising_sid, resolved_advertiser_address.GetAddressType(), - resolved_advertiser_address.GetAddress(), - bluetooth::hci::SecondaryPhyType::LE_1M, - pdu.GetAdvertisingInterval(), - bluetooth::hci::ClockAccuracy::PPM_500)); + resolved_advertiser_address.GetAddress(), bluetooth::hci::SecondaryPhyType::LE_1M, + pdu.GetAdvertisingInterval(), bluetooth::hci::ClockAccuracy::PPM_500)); } // Update the synchronization state. synchronized_.insert( - {sync_handle, - Synchronized{ - .advertiser_address_type = advertiser_address_type, - .advertiser_address = resolved_advertiser_address.GetAddress(), - .advertising_sid = advertising_sid, - .sync_handle = sync_handle, - .sync_timeout = synchronizing_->sync_timeout, - .timeout = std::chrono::steady_clock::now() + - synchronizing_->sync_timeout, - }}); + {sync_handle, + Synchronized{ + .advertiser_address_type = advertiser_address_type, + .advertiser_address = resolved_advertiser_address.GetAddress(), + .advertising_sid = advertising_sid, + .sync_handle = sync_handle, + .sync_timeout = synchronizing_->sync_timeout, + .timeout = std::chrono::steady_clock::now() + synchronizing_->sync_timeout, + }}); // Quit synchronizing state. synchronizing_ = {}; @@ -3944,18 +3698,15 @@ void LinkLayerController::IncomingLePeriodicAdvertisingPdu( size_t remaining_size = advertising_data.size() - offset; size_t fragment_size = std::min(max_fragment_size, remaining_size); - bluetooth::hci::DataStatus data_status = - remaining_size <= max_fragment_size - ? bluetooth::hci::DataStatus::COMPLETE - : bluetooth::hci::DataStatus::CONTINUING; - std::vector fragment_data( - advertising_data.begin() + offset, - advertising_data.begin() + offset + fragment_size); + bluetooth::hci::DataStatus data_status = remaining_size <= max_fragment_size + ? bluetooth::hci::DataStatus::COMPLETE + : bluetooth::hci::DataStatus::CONTINUING; + std::vector fragment_data(advertising_data.begin() + offset, + advertising_data.begin() + offset + fragment_size); offset += fragment_size; send_event_(bluetooth::hci::LePeriodicAdvertisingReportBuilder::Create( - sync.sync_handle, pdu.GetTxPower(), rssi, - bluetooth::hci::CteType::NO_CONSTANT_TONE_EXTENSION, data_status, - fragment_data)); + sync.sync_handle, pdu.GetTxPower(), rssi, + bluetooth::hci::CteType::NO_CONSTANT_TONE_EXTENSION, data_status, fragment_data)); } while (offset < advertising_data.size()); } @@ -3965,7 +3716,7 @@ void LinkLayerController::IncomingLePeriodicAdvertisingPdu( } void LinkLayerController::IncomingScoConnectionRequest( - model::packets::LinkLayerPacketView incoming) { + model::packets::LinkLayerPacketView incoming) { Address address = incoming.GetSourceAddress(); auto request = model::packets::ScoConnectionRequestView::Create(incoming); ASSERT(request.IsValid()); @@ -3981,34 +3732,32 @@ void LinkLayerController::IncomingScoConnectionRequest( address); SendLinkLayerPacket(model::packets::ScoConnectionResponseBuilder::Create( - GetAddress(), address, - (uint8_t)ErrorCode::SYNCHRONOUS_CONNECTION_LIMIT_EXCEEDED, 0, 0, 0, 0, - 0, 0)); + GetAddress(), address, (uint8_t)ErrorCode::SYNCHRONOUS_CONNECTION_LIMIT_EXCEEDED, 0, 0, + 0, 0, 0, 0)); return; } // Create local connection context. ScoConnectionParameters connection_parameters = { - request.GetTransmitBandwidth(), request.GetReceiveBandwidth(), - request.GetMaxLatency(), request.GetVoiceSetting(), - request.GetRetransmissionEffort(), request.GetPacketType()}; + request.GetTransmitBandwidth(), request.GetReceiveBandwidth(), + request.GetMaxLatency(), request.GetVoiceSetting(), + request.GetRetransmissionEffort(), request.GetPacketType()}; bool extended = connection_parameters.IsExtended(); - connections_.CreateScoConnection( - address, connection_parameters, - extended ? ScoState::SCO_STATE_SENT_ESCO_CONNECTION_REQUEST - : ScoState::SCO_STATE_SENT_SCO_CONNECTION_REQUEST, - ScoDatapath::NORMAL); + connections_.CreateScoConnection(address, connection_parameters, + extended ? ScoState::SCO_STATE_SENT_ESCO_CONNECTION_REQUEST + : ScoState::SCO_STATE_SENT_SCO_CONNECTION_REQUEST, + ScoDatapath::NORMAL); // Send connection request event and wait for Accept or Reject command. send_event_(bluetooth::hci::ConnectionRequestBuilder::Create( - address, request.GetClassOfDevice(), - extended ? bluetooth::hci::ConnectionRequestLinkType::ESCO - : bluetooth::hci::ConnectionRequestLinkType::SCO)); + address, request.GetClassOfDevice(), + extended ? bluetooth::hci::ConnectionRequestLinkType::ESCO + : bluetooth::hci::ConnectionRequestLinkType::SCO)); } void LinkLayerController::IncomingScoConnectionResponse( - model::packets::LinkLayerPacketView incoming) { + model::packets::LinkLayerPacketView incoming) { Address address = incoming.GetSourceAddress(); auto response = model::packets::ScoConnectionResponseView::Create(incoming); ASSERT(response.IsValid()); @@ -4021,54 +3770,50 @@ void LinkLayerController::IncomingScoConnectionResponse( if (status == ErrorCode::SUCCESS) { bool extended = response.GetExtended(); ScoLinkParameters link_parameters = { - response.GetTransmissionInterval(), - response.GetRetransmissionWindow(), - response.GetRxPacketLength(), - response.GetTxPacketLength(), - response.GetAirMode(), - extended, + response.GetTransmissionInterval(), + response.GetRetransmissionWindow(), + response.GetRxPacketLength(), + response.GetTxPacketLength(), + response.GetAirMode(), + extended, }; - connections_.AcceptPendingScoConnection( - address, link_parameters, [this, address] { - return LinkLayerController::StartScoStream(address); - }); + connections_.AcceptPendingScoConnection(address, link_parameters, [this, address] { + return LinkLayerController::StartScoStream(address); + }); if (is_legacy) { send_event_(bluetooth::hci::ConnectionCompleteBuilder::Create( - ErrorCode::SUCCESS, connections_.GetScoHandle(address), address, - bluetooth::hci::LinkType::SCO, bluetooth::hci::Enable::DISABLED)); + ErrorCode::SUCCESS, connections_.GetScoHandle(address), address, + bluetooth::hci::LinkType::SCO, bluetooth::hci::Enable::DISABLED)); } else { send_event_(bluetooth::hci::SynchronousConnectionCompleteBuilder::Create( - ErrorCode::SUCCESS, connections_.GetScoHandle(address), address, - extended ? bluetooth::hci::ScoLinkType::ESCO - : bluetooth::hci::ScoLinkType::SCO, - extended ? response.GetTransmissionInterval() : 0, - extended ? response.GetRetransmissionWindow() : 0, - extended ? response.GetRxPacketLength() : 0, - extended ? response.GetTxPacketLength() : 0, - bluetooth::hci::ScoAirMode(response.GetAirMode()))); + ErrorCode::SUCCESS, connections_.GetScoHandle(address), address, + extended ? bluetooth::hci::ScoLinkType::ESCO : bluetooth::hci::ScoLinkType::SCO, + extended ? response.GetTransmissionInterval() : 0, + extended ? response.GetRetransmissionWindow() : 0, + extended ? response.GetRxPacketLength() : 0, + extended ? response.GetTxPacketLength() : 0, + bluetooth::hci::ScoAirMode(response.GetAirMode()))); } } else { connections_.CancelPendingScoConnection(address); if (is_legacy) { send_event_(bluetooth::hci::ConnectionCompleteBuilder::Create( - status, 0, address, bluetooth::hci::LinkType::SCO, - bluetooth::hci::Enable::DISABLED)); + status, 0, address, bluetooth::hci::LinkType::SCO, bluetooth::hci::Enable::DISABLED)); } else { ScoConnectionParameters connection_parameters = - connections_.GetScoConnectionParameters(address); + connections_.GetScoConnectionParameters(address); send_event_(bluetooth::hci::SynchronousConnectionCompleteBuilder::Create( - status, 0, address, - connection_parameters.IsExtended() ? bluetooth::hci::ScoLinkType::ESCO - : bluetooth::hci::ScoLinkType::SCO, - 0, 0, 0, 0, bluetooth::hci::ScoAirMode::TRANSPARENT)); + status, 0, address, + connection_parameters.IsExtended() ? bluetooth::hci::ScoLinkType::ESCO + : bluetooth::hci::ScoLinkType::SCO, + 0, 0, 0, 0, bluetooth::hci::ScoAirMode::TRANSPARENT)); } } } -void LinkLayerController::IncomingScoDisconnect( - model::packets::LinkLayerPacketView incoming) { +void LinkLayerController::IncomingScoDisconnect(model::packets::LinkLayerPacketView incoming) { Address address = incoming.GetSourceAddress(); auto request = model::packets::ScoDisconnectView::Create(incoming); ASSERT(request.IsValid()); @@ -4081,27 +3826,23 @@ void LinkLayerController::IncomingScoDisconnect( static_cast(reason), incoming.GetSourceAddress()); if (handle != kReservedHandle) { - connections_.Disconnect( - handle, [this](TaskId task_id) { CancelScheduledTask(task_id); }); + connections_.Disconnect(handle, [this](TaskId task_id) { CancelScheduledTask(task_id); }); SendDisconnectionCompleteEvent(handle, ErrorCode(reason)); } } -void LinkLayerController::IncomingLmpPacket( - model::packets::LinkLayerPacketView incoming) { +void LinkLayerController::IncomingLmpPacket(model::packets::LinkLayerPacketView incoming) { Address address = incoming.GetSourceAddress(); auto request = model::packets::LmpView::Create(incoming); ASSERT(request.IsValid()); auto payload = request.GetPayload(); auto packet = std::vector(payload.begin(), payload.end()); - ASSERT(link_manager_ingest_lmp( - lm_.get(), reinterpret_cast(address.data()), packet.data(), - packet.size())); + ASSERT(link_manager_ingest_lmp(lm_.get(), reinterpret_cast(address.data()), + packet.data(), packet.size())); } -void LinkLayerController::IncomingLlcpPacket( - model::packets::LinkLayerPacketView incoming) { +void LinkLayerController::IncomingLlcpPacket(model::packets::LinkLayerPacketView incoming) { Address address = incoming.GetSourceAddress(); auto request = model::packets::LlcpView::Create(incoming); ASSERT(request.IsValid()); @@ -4114,12 +3855,10 @@ void LinkLayerController::IncomingLlcpPacket( return; } - ASSERT(link_layer_ingest_llcp(ll_.get(), acl_connection_handle, packet.data(), - packet.size())); + ASSERT(link_layer_ingest_llcp(ll_.get(), acl_connection_handle, packet.data(), packet.size())); } -void LinkLayerController::IncomingLeConnectedIsochronousPdu( - LinkLayerPacketView incoming) { +void LinkLayerController::IncomingLeConnectedIsochronousPdu(LinkLayerPacketView incoming) { auto pdu = model::packets::LeConnectedIsochronousPduView::Create(incoming); ASSERT(pdu.IsValid()); auto data = pdu.GetData(); @@ -4129,11 +3868,8 @@ void LinkLayerController::IncomingLeConnectedIsochronousPdu( uint16_t cis_connection_handle = 0; uint16_t iso_sdu_length = packet.size(); - if (!link_layer_get_cis_connection_handle(ll_.get(), cig_id, cis_id, - &cis_connection_handle)) { - INFO(id_, - "Dropping CIS pdu received on disconnected CIS cig_id={}, cis_id={}", - cig_id, cis_id); + if (!link_layer_get_cis_connection_handle(ll_.get(), cig_id, cis_id, &cis_connection_handle)) { + INFO(id_, "Dropping CIS pdu received on disconnected CIS cig_id={}, cis_id={}", cig_id, cis_id); return; } @@ -4142,27 +3878,23 @@ void LinkLayerController::IncomingLeConnectedIsochronousPdu( // iso_sdu_length size_t remaining_size = packet.size(); size_t offset = 0; - auto packet_boundary_flag = - remaining_size <= kMaxPayloadSize - ? bluetooth::hci::IsoPacketBoundaryFlag::COMPLETE_SDU - : bluetooth::hci::IsoPacketBoundaryFlag::FIRST_FRAGMENT; + auto packet_boundary_flag = remaining_size <= kMaxPayloadSize + ? bluetooth::hci::IsoPacketBoundaryFlag::COMPLETE_SDU + : bluetooth::hci::IsoPacketBoundaryFlag::FIRST_FRAGMENT; do { size_t fragment_size = std::min(kMaxPayloadSize, remaining_size); - std::vector fragment(packet.data() + offset, - packet.data() + offset + fragment_size); + std::vector fragment(packet.data() + offset, packet.data() + offset + fragment_size); send_iso_(bluetooth::hci::IsoWithoutTimestampBuilder::Create( - cis_connection_handle, packet_boundary_flag, pdu.GetSequenceNumber(), - iso_sdu_length, bluetooth::hci::IsoPacketStatusFlag::VALID, - std::move(fragment))); + cis_connection_handle, packet_boundary_flag, pdu.GetSequenceNumber(), iso_sdu_length, + bluetooth::hci::IsoPacketStatusFlag::VALID, std::move(fragment))); remaining_size -= fragment_size; offset += fragment_size; - packet_boundary_flag = - remaining_size <= kMaxPayloadSize - ? bluetooth::hci::IsoPacketBoundaryFlag::LAST_FRAGMENT - : bluetooth::hci::IsoPacketBoundaryFlag::CONTINUATION_FRAGMENT; + packet_boundary_flag = remaining_size <= kMaxPayloadSize + ? bluetooth::hci::IsoPacketBoundaryFlag::LAST_FRAGMENT + : bluetooth::hci::IsoPacketBoundaryFlag::CONTINUATION_FRAGMENT; } while (remaining_size > 0); } @@ -4185,8 +3917,7 @@ void LinkLayerController::HandleIso(bluetooth::hci::IsoView iso) { // The TS_Flag bit shall only be set if the PB_Flag field equals 0b00 or 0b10. if (ts_flag == bluetooth::hci::TimeStampFlag::PRESENT && - (pb_flag == - bluetooth::hci::IsoPacketBoundaryFlag::CONTINUATION_FRAGMENT || + (pb_flag == bluetooth::hci::IsoPacketBoundaryFlag::CONTINUATION_FRAGMENT || pb_flag == bluetooth::hci::IsoPacketBoundaryFlag::LAST_FRAGMENT)) { FATAL(id_, "Received ISO HCI packet with TS_Flag set, but no ISO Header is " @@ -4199,11 +3930,9 @@ void LinkLayerController::HandleIso(bluetooth::hci::IsoView iso) { uint16_t packet_sequence_number = 0; uint16_t max_sdu_length = 0; - if (!link_layer_get_cis_information(ll_.get(), cis_connection_handle, - &acl_connection_handle, &cig_id, &cis_id, - &max_sdu_length)) { - INFO(id_, "Ignoring CIS pdu received on disconnected CIS handle={}", - cis_connection_handle); + if (!link_layer_get_cis_information(ll_.get(), cis_connection_handle, &acl_connection_handle, + &cig_id, &cis_id, &max_sdu_length)) { + INFO(id_, "Ignoring CIS pdu received on disconnected CIS handle={}", cis_connection_handle); return; } @@ -4214,8 +3943,7 @@ void LinkLayerController::HandleIso(bluetooth::hci::IsoView iso) { switch (ts_flag) { case bluetooth::hci::TimeStampFlag::PRESENT: { - auto iso_with_timestamp = - bluetooth::hci::IsoWithTimestampView::Create(iso); + auto iso_with_timestamp = bluetooth::hci::IsoWithTimestampView::Create(iso); ASSERT(iso_with_timestamp.IsValid()); auto iso_payload = iso_with_timestamp.GetPayload(); iso_sdu_.insert(iso_sdu_.end(), iso_payload.begin(), iso_payload.end()); @@ -4224,8 +3952,7 @@ void LinkLayerController::HandleIso(bluetooth::hci::IsoView iso) { } default: case bluetooth::hci::TimeStampFlag::NOT_PRESENT: { - auto iso_without_timestamp = - bluetooth::hci::IsoWithoutTimestampView::Create(iso); + auto iso_without_timestamp = bluetooth::hci::IsoWithoutTimestampView::Create(iso); ASSERT(iso_without_timestamp.IsValid()); auto iso_payload = iso_without_timestamp.GetPayload(); iso_sdu_.insert(iso_sdu_.end(), iso_payload.begin(), iso_payload.end()); @@ -4239,27 +3966,23 @@ void LinkLayerController::HandleIso(bluetooth::hci::IsoView iso) { // Validate that the Host stack is not sending ISO SDUs that are larger // that what was configured for the CIS. if (iso_sdu_.size() > max_sdu_length) { - WARNING( - id_, - "attempted to send an SDU of length {} that exceeds the configure " - "Max_SDU_Length ({})", - iso_sdu_.size(), max_sdu_length); + WARNING(id_, + "attempted to send an SDU of length {} that exceeds the configure " + "Max_SDU_Length ({})", + iso_sdu_.size(), max_sdu_length); return; } - SendLeLinkLayerPacket( - model::packets::LeConnectedIsochronousPduBuilder::Create( - address_, - connections_.GetAddress(acl_connection_handle).GetAddress(), cig_id, - cis_id, packet_sequence_number, std::move(iso_sdu_))); + SendLeLinkLayerPacket(model::packets::LeConnectedIsochronousPduBuilder::Create( + address_, connections_.GetAddress(acl_connection_handle).GetAddress(), cig_id, cis_id, + packet_sequence_number, std::move(iso_sdu_))); } } uint16_t LinkLayerController::HandleLeConnection( - AddressWithType address, AddressWithType own_address, - bluetooth::hci::Role role, uint16_t connection_interval, - uint16_t connection_latency, uint16_t supervision_timeout, - bool send_le_channel_selection_algorithm_event) { + AddressWithType address, AddressWithType own_address, bluetooth::hci::Role role, + uint16_t connection_interval, uint16_t connection_latency, uint16_t supervision_timeout, + bool send_le_channel_selection_algorithm_event) { // Note: the HCI_LE_Connection_Complete event is not sent if the // HCI_LE_Enhanced_Connection_Complete event (see Section 7.7.65.10) is // unmasked. @@ -4271,8 +3994,7 @@ uint16_t LinkLayerController::HandleLeConnection( } if (IsLeEventUnmasked(SubeventCode::ENHANCED_CONNECTION_COMPLETE)) { - AddressWithType peer_resolved_address = - connections_.GetResolvedAddress(handle); + AddressWithType peer_resolved_address = connections_.GetResolvedAddress(handle); Address peer_resolvable_private_address; Address connection_address = address.GetAddress(); AddressType peer_address_type = address.GetAddressType(); @@ -4282,28 +4004,26 @@ uint16_t LinkLayerController::HandleLeConnection( connection_address = peer_resolved_address.GetAddress(); } Address local_resolved_address = own_address.GetAddress(); - if (local_resolved_address == GetAddress() || - local_resolved_address == random_address_) { + if (local_resolved_address == GetAddress() || local_resolved_address == random_address_) { local_resolved_address = Address::kEmpty; } send_event_(bluetooth::hci::LeEnhancedConnectionCompleteBuilder::Create( - ErrorCode::SUCCESS, handle, role, peer_address_type, connection_address, - local_resolved_address, peer_resolvable_private_address, - connection_interval, connection_latency, supervision_timeout, - static_cast(0x00))); + ErrorCode::SUCCESS, handle, role, peer_address_type, connection_address, + local_resolved_address, peer_resolvable_private_address, connection_interval, + connection_latency, supervision_timeout, + static_cast(0x00))); } else if (IsLeEventUnmasked(SubeventCode::CONNECTION_COMPLETE)) { send_event_(bluetooth::hci::LeConnectionCompleteBuilder::Create( - ErrorCode::SUCCESS, handle, role, address.GetAddressType(), - address.GetAddress(), connection_interval, connection_latency, - supervision_timeout, static_cast(0x00))); + ErrorCode::SUCCESS, handle, role, address.GetAddressType(), address.GetAddress(), + connection_interval, connection_latency, supervision_timeout, + static_cast(0x00))); } // Update the link layer with the new link. - ASSERT(link_layer_add_link( - ll_.get(), handle, - reinterpret_cast(address.GetAddress().data()), - static_cast(role))); + ASSERT(link_layer_add_link(ll_.get(), handle, + reinterpret_cast(address.GetAddress().data()), + static_cast(role))); // Note: the HCI_LE_Connection_Complete event is immediately followed by // an HCI_LE_Channel_Selection_Algorithm event if the connection is created @@ -4313,7 +4033,7 @@ uint16_t LinkLayerController::HandleLeConnection( // The selection channel algorithm probably will have no impact // on emulation. send_event_(bluetooth::hci::LeChannelSelectionAlgorithmBuilder::Create( - handle, bluetooth::hci::ChannelSelectionAlgorithm::ALGORITHM_1)); + handle, bluetooth::hci::ChannelSelectionAlgorithm::ALGORITHM_1)); } if (own_address.GetAddress() == initiator_.initiating_address) { @@ -4324,7 +4044,7 @@ uint16_t LinkLayerController::HandleLeConnection( // Handle CONNECT_IND PDUs for the legacy advertiser. bool LinkLayerController::ProcessIncomingLegacyConnectRequest( - model::packets::LeConnectView const& connect_ind) { + model::packets::LeConnectView const& connect_ind) { if (!legacy_advertiser_.IsEnabled()) { return false; } @@ -4336,13 +4056,13 @@ bool LinkLayerController::ProcessIncomingLegacyConnectRequest( } AddressWithType advertising_address{ - connect_ind.GetDestinationAddress(), - static_cast(connect_ind.GetAdvertisingAddressType()), + connect_ind.GetDestinationAddress(), + static_cast(connect_ind.GetAdvertisingAddressType()), }; AddressWithType initiating_address{ - connect_ind.GetSourceAddress(), - static_cast(connect_ind.GetInitiatingAddressType()), + connect_ind.GetSourceAddress(), + static_cast(connect_ind.GetInitiatingAddressType()), }; if (legacy_advertiser_.GetAdvertisingAddress() != advertising_address) { @@ -4359,7 +4079,7 @@ bool LinkLayerController::ProcessIncomingLegacyConnectRequest( // The advertising filter policy shall then determine if the // advertiser establishes a connection. AddressWithType resolved_initiating_address = - ResolvePrivateAddress(initiating_address).value_or(initiating_address); + ResolvePrivateAddress(initiating_address).value_or(initiating_address); if (resolved_initiating_address != initiating_address) { DEBUG(id_, "Resolved the initiating address {} to {}", initiating_address, @@ -4370,8 +4090,7 @@ bool LinkLayerController::ProcessIncomingLegacyConnectRequest( // advertising filter policy shall be ignored. if (legacy_advertiser_.IsDirected()) { if (resolved_initiating_address != - PeerDeviceAddress(legacy_advertiser_.peer_address, - legacy_advertiser_.peer_address_type)) { + PeerDeviceAddress(legacy_advertiser_.peer_address, legacy_advertiser_.peer_address_type)) { DEBUG(id_, "LE Connect request ignored by legacy advertiser because the " "initiating address {} does not match the target address {}[{}]", @@ -4404,30 +4123,27 @@ bool LinkLayerController::ProcessIncomingLegacyConnectRequest( "address {}", resolved_initiating_address); - if (!connections_.CreatePendingLeConnection( - initiating_address, - resolved_initiating_address != initiating_address - ? resolved_initiating_address - : AddressWithType{}, - advertising_address)) { + if (!connections_.CreatePendingLeConnection(initiating_address, + resolved_initiating_address != initiating_address + ? resolved_initiating_address + : AddressWithType{}, + advertising_address)) { WARNING(id_, "CreatePendingLeConnection failed for connection from {}", initiating_address.GetAddress()); return false; } - (void)HandleLeConnection( - initiating_address, advertising_address, bluetooth::hci::Role::PERIPHERAL, - connect_ind.GetConnInterval(), connect_ind.GetConnPeripheralLatency(), - connect_ind.GetConnSupervisionTimeout(), false); + (void)HandleLeConnection(initiating_address, advertising_address, + bluetooth::hci::Role::PERIPHERAL, connect_ind.GetConnInterval(), + connect_ind.GetConnPeripheralLatency(), + connect_ind.GetConnSupervisionTimeout(), false); SendLeLinkLayerPacket(model::packets::LeConnectCompleteBuilder::Create( - advertising_address.GetAddress(), initiating_address.GetAddress(), - static_cast( - initiating_address.GetAddressType()), - static_cast( - advertising_address.GetAddressType()), - connect_ind.GetConnInterval(), connect_ind.GetConnPeripheralLatency(), - connect_ind.GetConnSupervisionTimeout())); + advertising_address.GetAddress(), initiating_address.GetAddress(), + static_cast(initiating_address.GetAddressType()), + static_cast(advertising_address.GetAddressType()), + connect_ind.GetConnInterval(), connect_ind.GetConnPeripheralLatency(), + connect_ind.GetConnSupervisionTimeout())); legacy_advertiser_.Disable(); return true; @@ -4435,8 +4151,7 @@ bool LinkLayerController::ProcessIncomingLegacyConnectRequest( // Handle CONNECT_IND PDUs for the selected extended advertiser. bool LinkLayerController::ProcessIncomingExtendedConnectRequest( - ExtendedAdvertiser& advertiser, - model::packets::LeConnectView const& connect_ind) { + ExtendedAdvertiser& advertiser, model::packets::LeConnectView const& connect_ind) { if (!advertiser.IsEnabled()) { return false; } @@ -4449,21 +4164,20 @@ bool LinkLayerController::ProcessIncomingExtendedConnectRequest( } AddressWithType advertising_address{ - connect_ind.GetDestinationAddress(), - static_cast(connect_ind.GetAdvertisingAddressType()), + connect_ind.GetDestinationAddress(), + static_cast(connect_ind.GetAdvertisingAddressType()), }; AddressWithType initiating_address{ - connect_ind.GetSourceAddress(), - static_cast(connect_ind.GetInitiatingAddressType()), + connect_ind.GetSourceAddress(), + static_cast(connect_ind.GetInitiatingAddressType()), }; if (advertiser.GetAdvertisingAddress() != advertising_address) { DEBUG(id_, "LE Connect request ignored by extended advertiser {} because the " "advertising address {} does not match {}", - advertiser.advertising_handle, advertising_address, - advertiser.GetAdvertisingAddress()); + advertiser.advertising_handle, advertising_address, advertiser.GetAdvertisingAddress()); return false; } @@ -4473,7 +4187,7 @@ bool LinkLayerController::ProcessIncomingExtendedConnectRequest( // The advertising filter policy shall then determine if the // advertiser establishes a connection. AddressWithType resolved_initiating_address = - ResolvePrivateAddress(initiating_address).value_or(initiating_address); + ResolvePrivateAddress(initiating_address).value_or(initiating_address); if (resolved_initiating_address != initiating_address) { DEBUG(id_, "Resolved the initiating address {} to {}", initiating_address, @@ -4484,13 +4198,11 @@ bool LinkLayerController::ProcessIncomingExtendedConnectRequest( // advertising filter policy shall be ignored. if (advertiser.IsDirected()) { if (resolved_initiating_address != - PeerDeviceAddress(advertiser.peer_address, - advertiser.peer_address_type)) { + PeerDeviceAddress(advertiser.peer_address, advertiser.peer_address_type)) { DEBUG(id_, "LE Connect request ignored by extended advertiser {} because the " "initiating address {} does not match the target address {}[{}]", - advertiser.advertising_handle, resolved_initiating_address, - advertiser.peer_address, + advertiser.advertising_handle, resolved_initiating_address, advertiser.peer_address, PeerAddressTypeText(advertiser.peer_address_type)); return false; } @@ -4519,12 +4231,11 @@ bool LinkLayerController::ProcessIncomingExtendedConnectRequest( "address {}", advertiser.advertising_handle, resolved_initiating_address); - if (!connections_.CreatePendingLeConnection( - initiating_address, - resolved_initiating_address != initiating_address - ? resolved_initiating_address - : AddressWithType{}, - advertising_address)) { + if (!connections_.CreatePendingLeConnection(initiating_address, + resolved_initiating_address != initiating_address + ? resolved_initiating_address + : AddressWithType{}, + advertising_address)) { WARNING(id_, "CreatePendingLeConnection failed for connection from {}", initiating_address.GetAddress()); return false; @@ -4533,18 +4244,16 @@ bool LinkLayerController::ProcessIncomingExtendedConnectRequest( advertiser.Disable(); uint16_t connection_handle = HandleLeConnection( - initiating_address, advertising_address, bluetooth::hci::Role::PERIPHERAL, - connect_ind.GetConnInterval(), connect_ind.GetConnPeripheralLatency(), - connect_ind.GetConnSupervisionTimeout(), false); + initiating_address, advertising_address, bluetooth::hci::Role::PERIPHERAL, + connect_ind.GetConnInterval(), connect_ind.GetConnPeripheralLatency(), + connect_ind.GetConnSupervisionTimeout(), false); SendLeLinkLayerPacket(model::packets::LeConnectCompleteBuilder::Create( - advertising_address.GetAddress(), initiating_address.GetAddress(), - static_cast( - initiating_address.GetAddressType()), - static_cast( - advertising_address.GetAddressType()), - connect_ind.GetConnInterval(), connect_ind.GetConnPeripheralLatency(), - connect_ind.GetConnSupervisionTimeout())); + advertising_address.GetAddress(), initiating_address.GetAddress(), + static_cast(initiating_address.GetAddressType()), + static_cast(advertising_address.GetAddressType()), + connect_ind.GetConnInterval(), connect_ind.GetConnPeripheralLatency(), + connect_ind.GetConnSupervisionTimeout())); // If the advertising set is connectable and a connection gets created, an // HCI_LE_Connection_Complete or HCI_LE_Enhanced_Connection_Complete @@ -4554,17 +4263,15 @@ bool LinkLayerController::ProcessIncomingExtendedConnectRequest( if (IsLeEventUnmasked(SubeventCode::ADVERTISING_SET_TERMINATED)) { send_event_(bluetooth::hci::LeAdvertisingSetTerminatedBuilder::Create( - ErrorCode::SUCCESS, advertiser.advertising_handle, connection_handle, - advertiser.num_completed_extended_advertising_events)); + ErrorCode::SUCCESS, advertiser.advertising_handle, connection_handle, + advertiser.num_completed_extended_advertising_events)); } return true; } -void LinkLayerController::IncomingLeConnectPacket( - model::packets::LinkLayerPacketView incoming) { - model::packets::LeConnectView connect = - model::packets::LeConnectView::Create(incoming); +void LinkLayerController::IncomingLeConnectPacket(model::packets::LinkLayerPacketView incoming) { + model::packets::LeConnectView connect = model::packets::LeConnectView::Create(incoming); ASSERT(connect.IsValid()); if (ProcessIncomingLegacyConnectRequest(connect)) { @@ -4579,13 +4286,13 @@ void LinkLayerController::IncomingLeConnectPacket( } void LinkLayerController::IncomingLeConnectCompletePacket( - model::packets::LinkLayerPacketView incoming) { + model::packets::LinkLayerPacketView incoming) { auto complete = model::packets::LeConnectCompleteView::Create(incoming); ASSERT(complete.IsValid()); AddressWithType advertising_address{ - incoming.GetSourceAddress(), static_cast( - complete.GetAdvertisingAddressType())}; + incoming.GetSourceAddress(), + static_cast(complete.GetAdvertisingAddressType())}; INFO(id_, "Received LE Connect complete response with advertising address {}", advertising_address); @@ -4593,10 +4300,9 @@ void LinkLayerController::IncomingLeConnectCompletePacket( HandleLeConnection(advertising_address, AddressWithType(incoming.GetDestinationAddress(), static_cast( - complete.GetInitiatingAddressType())), + complete.GetInitiatingAddressType())), bluetooth::hci::Role::CENTRAL, complete.GetConnInterval(), - complete.GetConnPeripheralLatency(), - complete.GetConnSupervisionTimeout(), + complete.GetConnPeripheralLatency(), complete.GetConnSupervisionTimeout(), ExtendedAdvertising()); initiator_.pending_connect_request = {}; @@ -4604,63 +4310,55 @@ void LinkLayerController::IncomingLeConnectCompletePacket( } void LinkLayerController::IncomingLeConnectionParameterRequest( - model::packets::LinkLayerPacketView incoming) { - auto request = - model::packets::LeConnectionParameterRequestView::Create(incoming); + model::packets::LinkLayerPacketView incoming) { + auto request = model::packets::LeConnectionParameterRequestView::Create(incoming); ASSERT(request.IsValid()); Address peer = incoming.GetSourceAddress(); uint16_t handle = connections_.GetHandleOnlyAddress(peer); if (handle == kReservedHandle) { - INFO(id_, "@{}: Unknown connection @{}", incoming.GetDestinationAddress(), - peer); + INFO(id_, "@{}: Unknown connection @{}", incoming.GetDestinationAddress(), peer); return; } if (IsLeEventUnmasked(SubeventCode::REMOTE_CONNECTION_PARAMETER_REQUEST)) { - send_event_( - bluetooth::hci::LeRemoteConnectionParameterRequestBuilder::Create( - handle, request.GetIntervalMin(), request.GetIntervalMax(), - request.GetLatency(), request.GetTimeout())); + send_event_(bluetooth::hci::LeRemoteConnectionParameterRequestBuilder::Create( + handle, request.GetIntervalMin(), request.GetIntervalMax(), request.GetLatency(), + request.GetTimeout())); } else { // If the request is being indicated to the Host and the event to the Host // is masked, then the Link Layer shall issue an LL_REJECT_EXT_IND PDU with // the ErrorCode set to Unsupported Remote Feature (0x1A). - SendLeLinkLayerPacket( - model::packets::LeConnectionParameterUpdateBuilder::Create( + SendLeLinkLayerPacket(model::packets::LeConnectionParameterUpdateBuilder::Create( request.GetDestinationAddress(), request.GetSourceAddress(), - static_cast(ErrorCode::UNSUPPORTED_REMOTE_OR_LMP_FEATURE), - 0, 0, 0)); + static_cast(ErrorCode::UNSUPPORTED_REMOTE_OR_LMP_FEATURE), 0, 0, 0)); } } void LinkLayerController::IncomingLeConnectionParameterUpdate( - model::packets::LinkLayerPacketView incoming) { - auto update = - model::packets::LeConnectionParameterUpdateView::Create(incoming); + model::packets::LinkLayerPacketView incoming) { + auto update = model::packets::LeConnectionParameterUpdateView::Create(incoming); ASSERT(update.IsValid()); Address peer = incoming.GetSourceAddress(); uint16_t handle = connections_.GetHandleOnlyAddress(peer); if (handle == kReservedHandle) { - INFO(id_, "@{}: Unknown connection @{}", incoming.GetDestinationAddress(), - peer); + INFO(id_, "@{}: Unknown connection @{}", incoming.GetDestinationAddress(), peer); return; } if (IsLeEventUnmasked(SubeventCode::CONNECTION_UPDATE_COMPLETE)) { send_event_(bluetooth::hci::LeConnectionUpdateCompleteBuilder::Create( - static_cast(update.GetStatus()), handle, - update.GetInterval(), update.GetLatency(), update.GetTimeout())); + static_cast(update.GetStatus()), handle, update.GetInterval(), + update.GetLatency(), update.GetTimeout())); } } void LinkLayerController::IncomingLeEncryptConnection( - model::packets::LinkLayerPacketView incoming) { + model::packets::LinkLayerPacketView incoming) { INFO(id_, "IncomingLeEncryptConnection"); Address peer = incoming.GetSourceAddress(); uint16_t handle = connections_.GetHandleOnlyAddress(peer); if (handle == kReservedHandle) { - INFO(id_, "@{}: Unknown connection @{}", incoming.GetDestinationAddress(), - peer); + INFO(id_, "@{}: Unknown connection @{}", incoming.GetDestinationAddress(), peer); return; } auto le_encrypt = model::packets::LeEncryptConnectionView::Create(incoming); @@ -4669,25 +4367,23 @@ void LinkLayerController::IncomingLeEncryptConnection( // TODO: Save keys to check if (IsEventUnmasked(EventCode::LE_META_EVENT)) { - send_event_(bluetooth::hci::LeLongTermKeyRequestBuilder::Create( - handle, le_encrypt.GetRand(), le_encrypt.GetEdiv())); + send_event_(bluetooth::hci::LeLongTermKeyRequestBuilder::Create(handle, le_encrypt.GetRand(), + le_encrypt.GetEdiv())); } } void LinkLayerController::IncomingLeEncryptConnectionResponse( - model::packets::LinkLayerPacketView incoming) { + model::packets::LinkLayerPacketView incoming) { INFO(id_, "IncomingLeEncryptConnectionResponse"); // TODO: Check keys - uint16_t handle = - connections_.GetHandleOnlyAddress(incoming.GetSourceAddress()); + uint16_t handle = connections_.GetHandleOnlyAddress(incoming.GetSourceAddress()); if (handle == kReservedHandle) { INFO(id_, "@{}: Unknown connection @{}", incoming.GetDestinationAddress(), incoming.GetSourceAddress()); return; } ErrorCode status = ErrorCode::SUCCESS; - auto response = - model::packets::LeEncryptConnectionResponseView::Create(incoming); + auto response = model::packets::LeEncryptConnectionResponseView::Create(incoming); ASSERT(response.IsValid()); bool success = true; @@ -4699,45 +4395,40 @@ void LinkLayerController::IncomingLeEncryptConnectionResponse( if (connections_.IsEncrypted(handle)) { if (IsEventUnmasked(EventCode::ENCRYPTION_KEY_REFRESH_COMPLETE)) { - send_event_(bluetooth::hci::EncryptionKeyRefreshCompleteBuilder::Create( - status, handle)); + send_event_(bluetooth::hci::EncryptionKeyRefreshCompleteBuilder::Create(status, handle)); } } else if (success) { connections_.Encrypt(handle); if (IsEventUnmasked(EventCode::ENCRYPTION_CHANGE)) { send_event_(bluetooth::hci::EncryptionChangeBuilder::Create( - status, handle, bluetooth::hci::EncryptionEnabled::ON)); + status, handle, bluetooth::hci::EncryptionEnabled::ON)); } } else { if (IsEventUnmasked(EventCode::ENCRYPTION_CHANGE)) { send_event_(bluetooth::hci::EncryptionChangeBuilder::Create( - status, handle, bluetooth::hci::EncryptionEnabled::OFF)); + status, handle, bluetooth::hci::EncryptionEnabled::OFF)); } } } void LinkLayerController::IncomingLeReadRemoteFeatures( - model::packets::LinkLayerPacketView incoming) { - uint16_t handle = - connections_.GetHandleOnlyAddress(incoming.GetSourceAddress()); + model::packets::LinkLayerPacketView incoming) { + uint16_t handle = connections_.GetHandleOnlyAddress(incoming.GetSourceAddress()); ErrorCode status = ErrorCode::SUCCESS; if (handle == kReservedHandle) { - WARNING(id_, "@{}: Unknown connection @{}", - incoming.GetDestinationAddress(), incoming.GetSourceAddress()); + WARNING(id_, "@{}: Unknown connection @{}", incoming.GetDestinationAddress(), + incoming.GetSourceAddress()); } - SendLeLinkLayerPacket( - model::packets::LeReadRemoteFeaturesResponseBuilder::Create( - incoming.GetDestinationAddress(), incoming.GetSourceAddress(), - GetLeSupportedFeatures(), static_cast(status))); + SendLeLinkLayerPacket(model::packets::LeReadRemoteFeaturesResponseBuilder::Create( + incoming.GetDestinationAddress(), incoming.GetSourceAddress(), GetLeSupportedFeatures(), + static_cast(status))); } void LinkLayerController::IncomingLeReadRemoteFeaturesResponse( - model::packets::LinkLayerPacketView incoming) { - uint16_t handle = - connections_.GetHandleOnlyAddress(incoming.GetSourceAddress()); + model::packets::LinkLayerPacketView incoming) { + uint16_t handle = connections_.GetHandleOnlyAddress(incoming.GetSourceAddress()); ErrorCode status = ErrorCode::SUCCESS; - auto response = - model::packets::LeReadRemoteFeaturesResponseView::Create(incoming); + auto response = model::packets::LeReadRemoteFeaturesResponseView::Create(incoming); ASSERT(response.IsValid()); if (handle == kReservedHandle) { INFO(id_, "@{}: Unknown connection @{}", incoming.GetDestinationAddress(), @@ -4748,13 +4439,13 @@ void LinkLayerController::IncomingLeReadRemoteFeaturesResponse( } if (IsEventUnmasked(EventCode::LE_META_EVENT)) { send_event_(bluetooth::hci::LeReadRemoteFeaturesCompleteBuilder::Create( - status, handle, response.GetFeatures())); + status, handle, response.GetFeatures())); } } void LinkLayerController::ProcessIncomingLegacyScanRequest( - AddressWithType scanning_address, AddressWithType resolved_scanning_address, - AddressWithType advertising_address) { + AddressWithType scanning_address, AddressWithType resolved_scanning_address, + AddressWithType advertising_address) { // Check if the advertising addresses matches the legacy // advertising address. if (!legacy_advertiser_.IsEnabled()) { @@ -4768,11 +4459,10 @@ void LinkLayerController::ProcessIncomingLegacyScanRequest( } if (advertising_address != legacy_advertiser_.advertising_address) { - DEBUG( - id_, - "LE Scan request ignored by legacy advertiser because the advertising " - "address {} does not match {}", - advertising_address, legacy_advertiser_.GetAdvertisingAddress()); + DEBUG(id_, + "LE Scan request ignored by legacy advertiser because the advertising " + "address {} does not match {}", + advertising_address, legacy_advertiser_.GetAdvertisingAddress()); return; } @@ -4785,11 +4475,10 @@ void LinkLayerController::ProcessIncomingLegacyScanRequest( case bluetooth::hci::AdvertisingFilterPolicy::LISTED_SCAN: case bluetooth::hci::AdvertisingFilterPolicy::LISTED_SCAN_AND_CONNECT: if (!LeFilterAcceptListContainsDevice(resolved_scanning_address)) { - DEBUG( - id_, - "LE Scan request ignored by legacy advertiser because the scanning " - "address {} is not in the filter accept list", - resolved_scanning_address); + DEBUG(id_, + "LE Scan request ignored by legacy advertiser because the scanning " + "address {} is not in the filter accept list", + resolved_scanning_address); return; } break; @@ -4806,18 +4495,16 @@ void LinkLayerController::ProcessIncomingLegacyScanRequest( // the advertiser’s device address (AdvA field) in the SCAN_REQ PDU to // which it is responding. SendLeLinkLayerPacket( - model::packets::LeScanResponseBuilder::Create( - advertising_address.GetAddress(), scanning_address.GetAddress(), - static_cast( - advertising_address.GetAddressType()), - legacy_advertiser_.scan_response_data), - properties_.le_advertising_physical_channel_tx_power); + model::packets::LeScanResponseBuilder::Create( + advertising_address.GetAddress(), scanning_address.GetAddress(), + static_cast(advertising_address.GetAddressType()), + legacy_advertiser_.scan_response_data), + properties_.le_advertising_physical_channel_tx_power); } void LinkLayerController::ProcessIncomingExtendedScanRequest( - ExtendedAdvertiser const& advertiser, AddressWithType scanning_address, - AddressWithType resolved_scanning_address, - AddressWithType advertising_address) { + ExtendedAdvertiser const& advertiser, AddressWithType scanning_address, + AddressWithType resolved_scanning_address, AddressWithType advertising_address) { // Check if the advertising addresses matches the legacy // advertising address. if (!advertiser.IsEnabled()) { @@ -4835,8 +4522,7 @@ void LinkLayerController::ProcessIncomingExtendedScanRequest( DEBUG(id_, "LE Scan request ignored by extended advertiser {} because the " "advertising address {} does not match {}", - advertiser.advertising_handle, advertising_address, - advertiser.GetAdvertisingAddress()); + advertiser.advertising_handle, advertising_address, advertiser.GetAdvertisingAddress()); return; } @@ -4860,13 +4546,11 @@ void LinkLayerController::ProcessIncomingExtendedScanRequest( // Check if the scanner address is the target address in the case of // scannable directed event types. - if (advertiser.IsDirected() && - advertiser.target_address != resolved_scanning_address) { + if (advertiser.IsDirected() && advertiser.target_address != resolved_scanning_address) { DEBUG(id_, "LE Scan request ignored by extended advertiser {} because the " "scanning address {} does not match the target address {}", - advertiser.advertising_handle, resolved_scanning_address, - advertiser.GetTargetAddress()); + advertiser.advertising_handle, resolved_scanning_address, advertiser.GetTargetAddress()); return; } @@ -4881,26 +4565,23 @@ void LinkLayerController::ProcessIncomingExtendedScanRequest( // the advertiser’s device address (AdvA field) in the SCAN_REQ PDU to // which it is responding. SendLeLinkLayerPacket( - model::packets::LeScanResponseBuilder::Create( - advertising_address.GetAddress(), scanning_address.GetAddress(), - static_cast( - advertising_address.GetAddressType()), - advertiser.scan_response_data), - advertiser.advertising_tx_power); + model::packets::LeScanResponseBuilder::Create( + advertising_address.GetAddress(), scanning_address.GetAddress(), + static_cast(advertising_address.GetAddressType()), + advertiser.scan_response_data), + advertiser.advertising_tx_power); } -void LinkLayerController::IncomingLeScanPacket( - model::packets::LinkLayerPacketView incoming) { +void LinkLayerController::IncomingLeScanPacket(model::packets::LinkLayerPacketView incoming) { auto scan_request = model::packets::LeScanView::Create(incoming); ASSERT(scan_request.IsValid()); - AddressWithType scanning_address{ - scan_request.GetSourceAddress(), - static_cast(scan_request.GetScanningAddressType())}; + AddressWithType scanning_address{scan_request.GetSourceAddress(), + static_cast(scan_request.GetScanningAddressType())}; AddressWithType advertising_address{ - scan_request.GetDestinationAddress(), - static_cast(scan_request.GetAdvertisingAddressType())}; + scan_request.GetDestinationAddress(), + static_cast(scan_request.GetAdvertisingAddressType())}; // Note: Vol 6, Part B § 6.2 Privacy in the Advertising State. // @@ -4910,7 +4591,7 @@ void LinkLayerController::IncomingLeScanPacket( // address. The advertising filter policy shall then determine if // the advertiser processes the scan request. AddressWithType resolved_scanning_address = - ResolvePrivateAddress(scanning_address).value_or(scanning_address); + ResolvePrivateAddress(scanning_address).value_or(scanning_address); if (resolved_scanning_address != scanning_address) { DEBUG(id_, "Resolved the scanning address {} to {}", scanning_address, @@ -4920,14 +4601,13 @@ void LinkLayerController::IncomingLeScanPacket( ProcessIncomingLegacyScanRequest(scanning_address, resolved_scanning_address, advertising_address); for (auto& [_, advertiser] : extended_advertisers_) { - ProcessIncomingExtendedScanRequest(advertiser, scanning_address, - resolved_scanning_address, + ProcessIncomingExtendedScanRequest(advertiser, scanning_address, resolved_scanning_address, advertising_address); } } -void LinkLayerController::IncomingLeScanResponsePacket( - model::packets::LinkLayerPacketView incoming, uint8_t rssi) { +void LinkLayerController::IncomingLeScanResponsePacket(model::packets::LinkLayerPacketView incoming, + uint8_t rssi) { auto scan_response = model::packets::LeScanResponseView::Create(incoming); ASSERT(scan_response.IsValid()); @@ -4943,8 +4623,8 @@ void LinkLayerController::IncomingLeScanResponsePacket( } AddressWithType advertising_address{ - scan_response.GetSourceAddress(), - static_cast(scan_response.GetAdvertisingAddressType())}; + scan_response.GetSourceAddress(), + static_cast(scan_response.GetAdvertisingAddressType())}; // If the advertiser processes the scan request, the advertiser’s device // address (AdvA field) in the scan response PDU shall be the same as the @@ -4959,21 +4639,19 @@ void LinkLayerController::IncomingLeScanResponsePacket( } AddressWithType resolved_advertising_address = - ResolvePrivateAddress(advertising_address).value_or(advertising_address); + ResolvePrivateAddress(advertising_address).value_or(advertising_address); if (advertising_address != resolved_advertising_address) { DEBUG(id_, "Resolved the advertising address {} to {}", advertising_address, resolved_advertising_address); } - INFO(id_, "Accepting LE Scan response from advertising address {}", - resolved_advertising_address); + INFO(id_, "Accepting LE Scan response from advertising address {}", resolved_advertising_address); scanner_.pending_scan_request = {}; bool should_send_advertising_report = true; - if (scanner_.filter_duplicates != - bluetooth::hci::FilterDuplicates::DISABLED) { + if (scanner_.filter_duplicates != bluetooth::hci::FilterDuplicates::DISABLED) { if (scanner_.IsPacketInHistory(incoming.bytes())) { should_send_advertising_report = false; } else { @@ -4996,23 +4674,22 @@ void LinkLayerController::IncomingLeScanResponsePacket( IsLeEventUnmasked(SubeventCode::EXTENDED_ADVERTISING_REPORT)) { bluetooth::hci::LeExtendedAdvertisingResponse response; response.address_ = resolved_advertising_address.GetAddress(); - response.address_type_ = - static_cast( + response.address_type_ = static_cast( resolved_advertising_address.GetAddressType()); response.connectable_ = scanner_.connectable_scan_response; response.scannable_ = true; response.legacy_ = !scanner_.extended_scan_response; response.scan_response_ = true; - response.primary_phy_ = static_cast( - scanner_.primary_scan_response_phy); - response.secondary_phy_ = static_cast( - scanner_.secondary_scan_response_phy); + response.primary_phy_ = + static_cast(scanner_.primary_scan_response_phy); + response.secondary_phy_ = + static_cast(scanner_.secondary_scan_response_phy); // TODO: SID should be set in scan response PDU response.advertising_sid_ = 0xFF; response.tx_power_ = 0x7F; response.rssi_ = rssi; response.direct_address_type_ = - bluetooth::hci::DirectAdvertisingAddressType::NO_ADDRESS_PROVIDED; + bluetooth::hci::DirectAdvertisingAddressType::NO_ADDRESS_PROVIDED; // Each extended advertising report can only pass 229 bytes of // advertising data (255 - size of report fields). @@ -5025,14 +4702,12 @@ void LinkLayerController::IncomingLeScanResponsePacket( size_t remaining_size = advertising_data.size() - offset; size_t fragment_size = std::min(max_fragment_size, remaining_size); response.data_status_ = remaining_size <= max_fragment_size - ? bluetooth::hci::DataStatus::COMPLETE - : bluetooth::hci::DataStatus::CONTINUING; - response.advertising_data_ = - std::vector(advertising_data.begin() + offset, - advertising_data.begin() + offset + fragment_size); + ? bluetooth::hci::DataStatus::COMPLETE + : bluetooth::hci::DataStatus::CONTINUING; + response.advertising_data_ = std::vector(advertising_data.begin() + offset, + advertising_data.begin() + offset + fragment_size); offset += fragment_size; - send_event_(bluetooth::hci::LeExtendedAdvertisingReportBuilder::Create( - {response})); + send_event_(bluetooth::hci::LeExtendedAdvertisingReportBuilder::Create({response})); } while (offset < advertising_data.size()); } } @@ -5050,8 +4725,7 @@ void LinkLayerController::LeScanning() { // events with Advertising Timeout error code when the advertising // type is ADV_DIRECT_IND and the connection failed to be established. - if (scanner_.timeout.has_value() && - !scanner_.periodical_timeout.has_value() && + if (scanner_.timeout.has_value() && !scanner_.periodical_timeout.has_value() && now >= scanner_.timeout.value()) { // At the end of a single scan (Duration non-zero but Period zero), // an HCI_LE_Scan_Timeout event shall be generated. @@ -5071,8 +4745,7 @@ void LinkLayerController::LeScanning() { } // End of period - if (!scanner_.timeout.has_value() && - scanner_.periodical_timeout.has_value() && + if (!scanner_.timeout.has_value() && scanner_.periodical_timeout.has_value() && now >= scanner_.periodical_timeout.value()) { if (scanner_.filter_duplicates == FilterDuplicates::RESET_EACH_PERIOD) { scanner_.history.clear(); @@ -5095,13 +4768,11 @@ void LinkLayerController::LeSynchronization() { std::vector removed_sync_handles; for (auto& [_, sync] : synchronized_) { if (sync.timeout > std::chrono::steady_clock::now()) { - INFO(id_, "Periodic advertising sync with handle 0x{:x} lost", - sync.sync_handle); + INFO(id_, "Periodic advertising sync with handle 0x{:x} lost", sync.sync_handle); removed_sync_handles.push_back(sync.sync_handle); } if (IsLeEventUnmasked(SubeventCode::PERIODIC_ADVERTISING_SYNC_LOST)) { - send_event_(bluetooth::hci::LePeriodicAdvertisingSyncLostBuilder::Create( - sync.sync_handle)); + send_event_(bluetooth::hci::LePeriodicAdvertisingSyncLostBuilder::Create(sync.sync_handle)); } } @@ -5110,8 +4781,7 @@ void LinkLayerController::LeSynchronization() { } } -void LinkLayerController::IncomingPagePacket( - model::packets::LinkLayerPacketView incoming) { +void LinkLayerController::IncomingPagePacket(model::packets::LinkLayerPacketView incoming) { auto bd_addr = incoming.GetSourceAddress(); auto page = model::packets::PageView::Create(incoming); ASSERT(page.IsValid()); @@ -5123,9 +4793,9 @@ void LinkLayerController::IncomingPagePacket( if (!IsEventUnmasked(EventCode::CONNECTION_REQUEST)) { INFO(id_, "rejecting connection request from {} because the HCI_Connection_Request" - " event is masked by the Host", bd_addr); - SendLinkLayerPacket( - model::packets::PageRejectBuilder::Create( + " event is masked by the Host", + bd_addr); + SendLinkLayerPacket(model::packets::PageRejectBuilder::Create( GetAddress(), bd_addr, static_cast(ErrorCode::CONNECTION_TIMEOUT))); return; } @@ -5137,8 +4807,8 @@ void LinkLayerController::IncomingPagePacket( bool allow_role_switch = page.GetAllowRoleSwitch(); if (!connections_.CreatePendingConnection( - bd_addr, authentication_enable_ == AuthenticationEnable::REQUIRED, - allow_role_switch)) { + bd_addr, authentication_enable_ == AuthenticationEnable::REQUIRED, + allow_role_switch)) { // Will be triggered when multiple hosts are paging simultaneously; // only one connection will be accepted. WARNING(id_, "Failed to create a pending connection for {}", bd_addr); @@ -5146,12 +4816,10 @@ void LinkLayerController::IncomingPagePacket( } send_event_(bluetooth::hci::ConnectionRequestBuilder::Create( - bd_addr, page.GetClassOfDevice(), - bluetooth::hci::ConnectionRequestLinkType::ACL)); + bd_addr, page.GetClassOfDevice(), bluetooth::hci::ConnectionRequestLinkType::ACL)); } -void LinkLayerController::IncomingPageRejectPacket( - model::packets::LinkLayerPacketView incoming) { +void LinkLayerController::IncomingPageRejectPacket(model::packets::LinkLayerPacketView incoming) { auto bd_addr = incoming.GetSourceAddress(); auto reject = model::packets::PageRejectView::Create(incoming); ASSERT(reject.IsValid()); @@ -5168,13 +4836,12 @@ void LinkLayerController::IncomingPageRejectPacket( if (IsEventUnmasked(EventCode::CONNECTION_COMPLETE)) { send_event_(bluetooth::hci::ConnectionCompleteBuilder::Create( - static_cast(reject.GetReason()), 0, bd_addr, - bluetooth::hci::LinkType::ACL, bluetooth::hci::Enable::DISABLED)); + static_cast(reject.GetReason()), 0, bd_addr, bluetooth::hci::LinkType::ACL, + bluetooth::hci::Enable::DISABLED)); } } -void LinkLayerController::IncomingPageResponsePacket( - model::packets::LinkLayerPacketView incoming) { +void LinkLayerController::IncomingPageResponsePacket(model::packets::LinkLayerPacketView incoming) { auto bd_addr = incoming.GetSourceAddress(); auto response = model::packets::PageResponseView::Create(incoming); ASSERT(response.IsValid()); @@ -5188,14 +4855,12 @@ void LinkLayerController::IncomingPageResponsePacket( INFO(id_, "Received Page Response packet from {}", bd_addr); - uint16_t connection_handle = - connections_.CreateConnection(bd_addr, GetAddress(), false); + uint16_t connection_handle = connections_.CreateConnection(bd_addr, GetAddress(), false); ASSERT(connection_handle != kReservedHandle); - bluetooth::hci::Role role = - page_->allow_role_switch && response.GetTryRoleSwitch() - ? bluetooth::hci::Role::PERIPHERAL - : bluetooth::hci::Role::CENTRAL; + bluetooth::hci::Role role = page_->allow_role_switch && response.GetTryRoleSwitch() + ? bluetooth::hci::Role::PERIPHERAL + : bluetooth::hci::Role::CENTRAL; AclConnection& connection = connections_.GetAclConnection(connection_handle); CheckExpiringConnection(connection_handle); @@ -5203,22 +4868,19 @@ void LinkLayerController::IncomingPageResponsePacket( connection.SetRole(role); page_ = {}; - ASSERT(link_manager_add_link( - lm_.get(), reinterpret_cast(bd_addr.data()))); + ASSERT(link_manager_add_link(lm_.get(), reinterpret_cast(bd_addr.data()))); // Role change event before connection complete generates an HCI Role Change // event on the initiator side if accepted; the event is sent before the // HCI Connection Complete event. - if (role == bluetooth::hci::Role::PERIPHERAL && - IsEventUnmasked(EventCode::ROLE_CHANGE)) { - send_event_(bluetooth::hci::RoleChangeBuilder::Create(ErrorCode::SUCCESS, - bd_addr, role)); + if (role == bluetooth::hci::Role::PERIPHERAL && IsEventUnmasked(EventCode::ROLE_CHANGE)) { + send_event_(bluetooth::hci::RoleChangeBuilder::Create(ErrorCode::SUCCESS, bd_addr, role)); } if (IsEventUnmasked(EventCode::CONNECTION_COMPLETE)) { send_event_(bluetooth::hci::ConnectionCompleteBuilder::Create( - ErrorCode::SUCCESS, connection_handle, bd_addr, - bluetooth::hci::LinkType::ACL, bluetooth::hci::Enable::DISABLED)); + ErrorCode::SUCCESS, connection_handle, bd_addr, bluetooth::hci::LinkType::ACL, + bluetooth::hci::Enable::DISABLED)); } } @@ -5242,33 +4904,28 @@ void LinkLayerController::Close() { } void LinkLayerController::RegisterEventChannel( - const std::function)>& - send_event) { + const std::function)>& send_event) { send_event_ = send_event; } void LinkLayerController::RegisterAclChannel( - const std::function)>& - send_acl) { + const std::function)>& send_acl) { send_acl_ = send_acl; } void LinkLayerController::RegisterScoChannel( - const std::function)>& - send_sco) { + const std::function)>& send_sco) { send_sco_ = send_sco; } void LinkLayerController::RegisterIsoChannel( - const std::function)>& - send_iso) { + const std::function)>& send_iso) { send_iso_ = send_iso; } void LinkLayerController::RegisterRemoteChannel( - const std::function< - void(std::shared_ptr, Phy::Type, - int8_t)>& send_to_remote) { + const std::function, Phy::Type, + int8_t)>& send_to_remote) { send_to_remote_ = send_to_remote; } @@ -5282,13 +4939,11 @@ void LinkLayerController::ForwardToLl(bluetooth::hci::CommandView command) { ASSERT(link_layer_ingest_hci(ll_.get(), packet.data(), packet.size())); } -std::vector const& LinkLayerController::ReadCurrentIacLap() - const { +std::vector const& LinkLayerController::ReadCurrentIacLap() const { return current_iac_lap_list_; } -void LinkLayerController::WriteCurrentIacLap( - std::vector iac_lap) { +void LinkLayerController::WriteCurrentIacLap(std::vector iac_lap) { current_iac_lap_list_.swap(iac_lap); // If Num_Current_IAC is greater than Num_Supported_IAC then only the first @@ -5317,12 +4972,11 @@ ErrorCode LinkLayerController::AcceptConnectionRequest(const Address& bd_addr, uint16_t sco_handle = 0; ScoLinkParameters link_parameters = {}; ScoConnectionParameters connection_parameters = - connections_.GetScoConnectionParameters(bd_addr); + connections_.GetScoConnectionParameters(bd_addr); - if (!connections_.AcceptPendingScoConnection( - bd_addr, connection_parameters, [this, bd_addr] { - return LinkLayerController::StartScoStream(bd_addr); - })) { + if (!connections_.AcceptPendingScoConnection(bd_addr, connection_parameters, [this, bd_addr] { + return LinkLayerController::StartScoStream(bd_addr); + })) { connections_.CancelPendingScoConnection(bd_addr); status = ErrorCode::SCO_INTERVAL_REJECTED; // TODO: proper status code } else { @@ -5332,18 +4986,16 @@ ErrorCode LinkLayerController::AcceptConnectionRequest(const Address& bd_addr, // Send eSCO connection response to peer. SendLinkLayerPacket(model::packets::ScoConnectionResponseBuilder::Create( - GetAddress(), bd_addr, (uint8_t)status, - link_parameters.transmission_interval, - link_parameters.retransmission_window, link_parameters.rx_packet_length, - link_parameters.tx_packet_length, link_parameters.air_mode, - link_parameters.extended)); + GetAddress(), bd_addr, (uint8_t)status, link_parameters.transmission_interval, + link_parameters.retransmission_window, link_parameters.rx_packet_length, + link_parameters.tx_packet_length, link_parameters.air_mode, link_parameters.extended)); // Schedule HCI Connection Complete event. if (IsEventUnmasked(EventCode::CONNECTION_COMPLETE)) { ScheduleTask(kNoDelayMs, [this, status, sco_handle, bd_addr]() { send_event_(bluetooth::hci::ConnectionCompleteBuilder::Create( - ErrorCode(status), sco_handle, bd_addr, - bluetooth::hci::LinkType::SCO, bluetooth::hci::Enable::DISABLED)); + ErrorCode(status), sco_handle, bd_addr, bluetooth::hci::LinkType::SCO, + bluetooth::hci::Enable::DISABLED)); }); } @@ -5354,42 +5006,37 @@ ErrorCode LinkLayerController::AcceptConnectionRequest(const Address& bd_addr, return ErrorCode::UNKNOWN_CONNECTION; } -void LinkLayerController::MakePeripheralConnection(const Address& bd_addr, - bool try_role_switch) { - uint16_t connection_handle = - connections_.CreateConnection(bd_addr, GetAddress()); +void LinkLayerController::MakePeripheralConnection(const Address& bd_addr, bool try_role_switch) { + uint16_t connection_handle = connections_.CreateConnection(bd_addr, GetAddress()); if (connection_handle == kReservedHandle) { INFO(id_, "CreateConnection failed"); return; } bluetooth::hci::Role role = - try_role_switch && connections_.IsRoleSwitchAllowedForPendingConnection() - ? bluetooth::hci::Role::CENTRAL - : bluetooth::hci::Role::PERIPHERAL; + try_role_switch && connections_.IsRoleSwitchAllowedForPendingConnection() + ? bluetooth::hci::Role::CENTRAL + : bluetooth::hci::Role::PERIPHERAL; AclConnection& connection = connections_.GetAclConnection(connection_handle); CheckExpiringConnection(connection_handle); connection.SetLinkPolicySettings(default_link_policy_settings_); connection.SetRole(role); - ASSERT(link_manager_add_link( - lm_.get(), reinterpret_cast(bd_addr.data()))); + ASSERT(link_manager_add_link(lm_.get(), reinterpret_cast(bd_addr.data()))); // Role change event before connection complete generates an HCI Role Change // event on the acceptor side if accepted; the event is sent before the // HCI Connection Complete event. - if (role == bluetooth::hci::Role::CENTRAL && - IsEventUnmasked(EventCode::ROLE_CHANGE)) { + if (role == bluetooth::hci::Role::CENTRAL && IsEventUnmasked(EventCode::ROLE_CHANGE)) { INFO(id_, "Role at connection setup accepted"); - send_event_(bluetooth::hci::RoleChangeBuilder::Create(ErrorCode::SUCCESS, - bd_addr, role)); + send_event_(bluetooth::hci::RoleChangeBuilder::Create(ErrorCode::SUCCESS, bd_addr, role)); } if (IsEventUnmasked(EventCode::CONNECTION_COMPLETE)) { send_event_(bluetooth::hci::ConnectionCompleteBuilder::Create( - ErrorCode::SUCCESS, connection_handle, bd_addr, - bluetooth::hci::LinkType::ACL, bluetooth::hci::Enable::DISABLED)); + ErrorCode::SUCCESS, connection_handle, bd_addr, bluetooth::hci::LinkType::ACL, + bluetooth::hci::Enable::DISABLED)); } // If the current Host was initiating a connection to the same bd_addr, @@ -5405,39 +5052,33 @@ void LinkLayerController::MakePeripheralConnection(const Address& bd_addr, } INFO(id_, "Sending page response to {}", bd_addr.ToString()); - SendLinkLayerPacket(model::packets::PageResponseBuilder::Create( - GetAddress(), bd_addr, try_role_switch)); + SendLinkLayerPacket( + model::packets::PageResponseBuilder::Create(GetAddress(), bd_addr, try_role_switch)); } -ErrorCode LinkLayerController::RejectConnectionRequest(const Address& addr, - uint8_t reason) { +ErrorCode LinkLayerController::RejectConnectionRequest(const Address& addr, uint8_t reason) { if (!connections_.HasPendingConnection(addr)) { INFO(id_, "No pending connection for {}", addr); return ErrorCode::UNKNOWN_CONNECTION; } - ScheduleTask(kNoDelayMs, [this, addr, reason]() { - RejectPeripheralConnection(addr, reason); - }); + ScheduleTask(kNoDelayMs, [this, addr, reason]() { RejectPeripheralConnection(addr, reason); }); return ErrorCode::SUCCESS; } -void LinkLayerController::RejectPeripheralConnection(const Address& addr, - uint8_t reason) { +void LinkLayerController::RejectPeripheralConnection(const Address& addr, uint8_t reason) { INFO(id_, "Sending page reject to {} (reason 0x{:02x})", addr, reason); - SendLinkLayerPacket( - model::packets::PageRejectBuilder::Create(GetAddress(), addr, reason)); + SendLinkLayerPacket(model::packets::PageRejectBuilder::Create(GetAddress(), addr, reason)); if (IsEventUnmasked(EventCode::CONNECTION_COMPLETE)) { send_event_(bluetooth::hci::ConnectionCompleteBuilder::Create( - static_cast(reason), 0xeff, addr, - bluetooth::hci::LinkType::ACL, bluetooth::hci::Enable::DISABLED)); + static_cast(reason), 0xeff, addr, bluetooth::hci::LinkType::ACL, + bluetooth::hci::Enable::DISABLED)); } } -ErrorCode LinkLayerController::CreateConnection(const Address& bd_addr, - uint16_t /* packet_type */, +ErrorCode LinkLayerController::CreateConnection(const Address& bd_addr, uint16_t /* packet_type */, uint8_t /* page_scan_mode */, uint16_t /* clock_offset */, uint8_t allow_role_switch) { @@ -5457,10 +5098,10 @@ ErrorCode LinkLayerController::CreateConnection(const Address& bd_addr, auto now = std::chrono::steady_clock::now(); page_ = Page{ - .bd_addr = bd_addr, - .allow_role_switch = allow_role_switch, - .next_page_event = now + kPageInterval, - .page_timeout = now + slots(page_timeout_), + .bd_addr = bd_addr, + .allow_role_switch = allow_role_switch, + .next_page_event = now + kPageInterval, + .page_timeout = now + slots(page_timeout_), }; return ErrorCode::SUCCESS; @@ -5485,8 +5126,8 @@ ErrorCode LinkLayerController::CreateConnectionCancel(const Address& bd_addr) { if (IsEventUnmasked(EventCode::CONNECTION_COMPLETE)) { ScheduleTask(kNoDelayMs, [this, bd_addr]() { send_event_(bluetooth::hci::ConnectionCompleteBuilder::Create( - ErrorCode::UNKNOWN_CONNECTION, 0, bd_addr, - bluetooth::hci::LinkType::ACL, bluetooth::hci::Enable::DISABLED)); + ErrorCode::UNKNOWN_CONNECTION, 0, bd_addr, bluetooth::hci::LinkType::ACL, + bluetooth::hci::Enable::DISABLED)); }); } @@ -5494,28 +5135,25 @@ ErrorCode LinkLayerController::CreateConnectionCancel(const Address& bd_addr) { return ErrorCode::SUCCESS; } -void LinkLayerController::SendDisconnectionCompleteEvent(uint16_t handle, - ErrorCode reason) { +void LinkLayerController::SendDisconnectionCompleteEvent(uint16_t handle, ErrorCode reason) { if (IsEventUnmasked(EventCode::DISCONNECTION_COMPLETE)) { ScheduleTask(kNoDelayMs, [this, handle, reason]() { - send_event_(bluetooth::hci::DisconnectionCompleteBuilder::Create( - ErrorCode::SUCCESS, handle, reason)); + send_event_(bluetooth::hci::DisconnectionCompleteBuilder::Create(ErrorCode::SUCCESS, handle, + reason)); }); } } -ErrorCode LinkLayerController::Disconnect(uint16_t handle, - ErrorCode host_reason, +ErrorCode LinkLayerController::Disconnect(uint16_t handle, ErrorCode host_reason, ErrorCode controller_reason) { if (connections_.HasScoHandle(handle)) { const Address remote = connections_.GetScoAddress(handle); INFO(id_, "Disconnecting eSCO connection with {}", remote); SendLinkLayerPacket(model::packets::ScoDisconnectBuilder::Create( - GetAddress(), remote, static_cast(host_reason))); + GetAddress(), remote, static_cast(host_reason))); - connections_.Disconnect( - handle, [this](TaskId task_id) { CancelScheduledTask(task_id); }); + connections_.Disconnect(handle, [this](TaskId task_id) { CancelScheduledTask(task_id); }); SendDisconnectionCompleteEvent(handle, controller_reason); return ErrorCode::SUCCESS; } @@ -5533,47 +5171,42 @@ ErrorCode LinkLayerController::Disconnect(uint16_t handle, uint16_t sco_handle = connections_.GetScoHandle(remote.GetAddress()); if (sco_handle != kReservedHandle) { SendLinkLayerPacket(model::packets::ScoDisconnectBuilder::Create( - GetAddress(), remote.GetAddress(), - static_cast(host_reason))); + GetAddress(), remote.GetAddress(), static_cast(host_reason))); - connections_.Disconnect( - sco_handle, [this](TaskId task_id) { CancelScheduledTask(task_id); }); + connections_.Disconnect(sco_handle, [this](TaskId task_id) { CancelScheduledTask(task_id); }); SendDisconnectionCompleteEvent(sco_handle, controller_reason); } SendLinkLayerPacket(model::packets::DisconnectBuilder::Create( - GetAddress(), remote.GetAddress(), static_cast(host_reason))); + GetAddress(), remote.GetAddress(), static_cast(host_reason))); } else { INFO(id_, "Disconnecting LE connection with {}", remote); SendLeLinkLayerPacket(model::packets::DisconnectBuilder::Create( - connections_.GetOwnAddress(handle).GetAddress(), remote.GetAddress(), - static_cast(host_reason))); + connections_.GetOwnAddress(handle).GetAddress(), remote.GetAddress(), + static_cast(host_reason))); } - connections_.Disconnect( - handle, [this](TaskId task_id) { CancelScheduledTask(task_id); }); + connections_.Disconnect(handle, [this](TaskId task_id) { CancelScheduledTask(task_id); }); SendDisconnectionCompleteEvent(handle, controller_reason); if (is_br_edr) { - ASSERT(link_manager_remove_link( - lm_.get(), - reinterpret_cast(remote.GetAddress().data()))); + ASSERT(link_manager_remove_link(lm_.get(), + reinterpret_cast(remote.GetAddress().data()))); } else { ASSERT(link_layer_remove_link(ll_.get(), handle)); } return ErrorCode::SUCCESS; } -ErrorCode LinkLayerController::ChangeConnectionPacketType(uint16_t handle, - uint16_t types) { +ErrorCode LinkLayerController::ChangeConnectionPacketType(uint16_t handle, uint16_t types) { if (!connections_.HasHandle(handle)) { return ErrorCode::UNKNOWN_CONNECTION; } ScheduleTask(kNoDelayMs, [this, handle, types]() { if (IsEventUnmasked(EventCode::CONNECTION_PACKET_TYPE_CHANGED)) { - send_event_(bluetooth::hci::ConnectionPacketTypeChangedBuilder::Create( - ErrorCode::SUCCESS, handle, types)); + send_event_(bluetooth::hci::ConnectionPacketTypeChangedBuilder::Create(ErrorCode::SUCCESS, + handle, types)); } }); @@ -5596,8 +5229,7 @@ ErrorCode LinkLayerController::CentralLinkKey(uint8_t /* key_flag */) { return ErrorCode::COMMAND_DISALLOWED; } -ErrorCode LinkLayerController::HoldMode(uint16_t handle, - uint16_t hold_mode_max_interval, +ErrorCode LinkLayerController::HoldMode(uint16_t handle, uint16_t hold_mode_max_interval, uint16_t hold_mode_min_interval) { if (!connections_.HasHandle(handle)) { return ErrorCode::UNKNOWN_CONNECTION; @@ -5611,17 +5243,15 @@ ErrorCode LinkLayerController::HoldMode(uint16_t handle, return ErrorCode::COMMAND_DISALLOWED; } -ErrorCode LinkLayerController::SniffMode(uint16_t handle, - uint16_t sniff_max_interval, - uint16_t sniff_min_interval, - uint16_t sniff_attempt, +ErrorCode LinkLayerController::SniffMode(uint16_t handle, uint16_t sniff_max_interval, + uint16_t sniff_min_interval, uint16_t sniff_attempt, uint16_t sniff_timeout) { if (!connections_.HasHandle(handle)) { return ErrorCode::UNKNOWN_CONNECTION; } - if (sniff_max_interval < sniff_min_interval || sniff_attempt < 0x0001 || - sniff_attempt > 0x7FFF || sniff_timeout > 0x7FFF) { + if (sniff_max_interval < sniff_min_interval || sniff_attempt < 0x0001 || sniff_attempt > 0x7FFF || + sniff_timeout > 0x7FFF) { return ErrorCode::INVALID_HCI_COMMAND_PARAMETERS; } @@ -5639,10 +5269,8 @@ ErrorCode LinkLayerController::ExitSniffMode(uint16_t handle) { } ErrorCode LinkLayerController::QosSetup(uint16_t handle, uint8_t service_type, - uint32_t /* token_rate */, - uint32_t /* peak_bandwidth */, - uint32_t /* latency */, - uint32_t /* delay_variation */) { + uint32_t /* token_rate */, uint32_t /* peak_bandwidth */, + uint32_t /* latency */, uint32_t /* delay_variation */) { if (!connections_.HasHandle(handle)) { return ErrorCode::UNKNOWN_CONNECTION; } @@ -5655,8 +5283,7 @@ ErrorCode LinkLayerController::QosSetup(uint16_t handle, uint8_t service_type, return ErrorCode::COMMAND_DISALLOWED; } -ErrorCode LinkLayerController::RoleDiscovery(uint16_t handle, - bluetooth::hci::Role* role) { +ErrorCode LinkLayerController::RoleDiscovery(uint16_t handle, bluetooth::hci::Role* role) { if (!connections_.HasHandle(handle)) { return ErrorCode::UNKNOWN_CONNECTION; } @@ -5665,8 +5292,7 @@ ErrorCode LinkLayerController::RoleDiscovery(uint16_t handle, return ErrorCode::SUCCESS; } -ErrorCode LinkLayerController::SwitchRole(Address bd_addr, - bluetooth::hci::Role role) { +ErrorCode LinkLayerController::SwitchRole(Address bd_addr, bluetooth::hci::Role role) { // The BD_ADDR command parameter indicates for which connection // the role switch is to be performed and shall specify a BR/EDR Controller // for which a connection already exists. @@ -5692,28 +5318,25 @@ ErrorCode LinkLayerController::SwitchRole(Address bd_addr, // BD_ADDR parameter is placed in Sniff mode, an attempt to perform a role // switch shall be rejected by the local device. if (connection.GetMode() == AclConnectionState::kSniffMode) { - INFO(id_, - "role switch rejected because the acl connection is in sniff mode"); + INFO(id_, "role switch rejected because the acl connection is in sniff mode"); return ErrorCode::COMMAND_DISALLOWED; } if (role != connection.GetRole()) { - SendLinkLayerPacket(model::packets::RoleSwitchRequestBuilder::Create( - GetAddress(), bd_addr)); + SendLinkLayerPacket(model::packets::RoleSwitchRequestBuilder::Create(GetAddress(), bd_addr)); } else if (IsEventUnmasked(EventCode::ROLE_CHANGE)) { // Note: the status is Success only if the role change procedure was // actually performed, otherwise the status is >0. ScheduleTask(kNoDelayMs, [this, bd_addr, role]() { - send_event_(bluetooth::hci::RoleChangeBuilder::Create( - ErrorCode::ROLE_SWITCH_FAILED, bd_addr, role)); + send_event_(bluetooth::hci::RoleChangeBuilder::Create(ErrorCode::ROLE_SWITCH_FAILED, bd_addr, + role)); }); } return ErrorCode::SUCCESS; } -void LinkLayerController::IncomingRoleSwitchRequest( - model::packets::LinkLayerPacketView incoming) { +void LinkLayerController::IncomingRoleSwitchRequest(model::packets::LinkLayerPacketView incoming) { auto bd_addr = incoming.GetSourceAddress(); auto connection_handle = connections_.GetHandleOnlyAddress(bd_addr); auto switch_req = model::packets::RoleSwitchRequestView::Create(incoming); @@ -5729,31 +5352,28 @@ void LinkLayerController::IncomingRoleSwitchRequest( if (!connection.IsRoleSwitchEnabled()) { INFO(id_, "role switch disabled by local link policy settings"); SendLinkLayerPacket(model::packets::RoleSwitchResponseBuilder::Create( - GetAddress(), bd_addr, - static_cast(ErrorCode::ROLE_CHANGE_NOT_ALLOWED))); + GetAddress(), bd_addr, static_cast(ErrorCode::ROLE_CHANGE_NOT_ALLOWED))); } else { INFO(id_, "role switch request accepted by local device"); SendLinkLayerPacket(model::packets::RoleSwitchResponseBuilder::Create( - GetAddress(), bd_addr, static_cast(ErrorCode::SUCCESS))); + GetAddress(), bd_addr, static_cast(ErrorCode::SUCCESS))); - bluetooth::hci::Role new_role = - connection.GetRole() == bluetooth::hci::Role::CENTRAL - ? bluetooth::hci::Role::PERIPHERAL - : bluetooth::hci::Role::CENTRAL; + bluetooth::hci::Role new_role = connection.GetRole() == bluetooth::hci::Role::CENTRAL + ? bluetooth::hci::Role::PERIPHERAL + : bluetooth::hci::Role::CENTRAL; connection.SetRole(new_role); if (IsEventUnmasked(EventCode::ROLE_CHANGE)) { ScheduleTask(kNoDelayMs, [this, bd_addr, new_role]() { - send_event_(bluetooth::hci::RoleChangeBuilder::Create( - ErrorCode::SUCCESS, bd_addr, new_role)); + send_event_( + bluetooth::hci::RoleChangeBuilder::Create(ErrorCode::SUCCESS, bd_addr, new_role)); }); } } } -void LinkLayerController::IncomingRoleSwitchResponse( - model::packets::LinkLayerPacketView incoming) { +void LinkLayerController::IncomingRoleSwitchResponse(model::packets::LinkLayerPacketView incoming) { auto bd_addr = incoming.GetSourceAddress(); auto connection_handle = connections_.GetHandleOnlyAddress(bd_addr); auto switch_rsp = model::packets::RoleSwitchResponseView::Create(incoming); @@ -5766,24 +5386,21 @@ void LinkLayerController::IncomingRoleSwitchResponse( AclConnection& connection = connections_.GetAclConnection(connection_handle); ErrorCode status = ErrorCode(switch_rsp.GetStatus()); - bluetooth::hci::Role new_role = - status != ErrorCode::SUCCESS ? connection.GetRole() - : connection.GetRole() == bluetooth::hci::Role::CENTRAL - ? bluetooth::hci::Role::PERIPHERAL - : bluetooth::hci::Role::CENTRAL; + bluetooth::hci::Role new_role = status != ErrorCode::SUCCESS ? connection.GetRole() + : connection.GetRole() == bluetooth::hci::Role::CENTRAL + ? bluetooth::hci::Role::PERIPHERAL + : bluetooth::hci::Role::CENTRAL; connection.SetRole(new_role); if (IsEventUnmasked(EventCode::ROLE_CHANGE)) { ScheduleTask(kNoDelayMs, [this, status, bd_addr, new_role]() { - send_event_( - bluetooth::hci::RoleChangeBuilder::Create(status, bd_addr, new_role)); + send_event_(bluetooth::hci::RoleChangeBuilder::Create(status, bd_addr, new_role)); }); } } -ErrorCode LinkLayerController::ReadLinkPolicySettings(uint16_t handle, - uint16_t* settings) { +ErrorCode LinkLayerController::ReadLinkPolicySettings(uint16_t handle, uint16_t* settings) { if (!connections_.HasHandle(handle)) { return ErrorCode::UNKNOWN_CONNECTION; } @@ -5792,8 +5409,7 @@ ErrorCode LinkLayerController::ReadLinkPolicySettings(uint16_t handle, return ErrorCode::SUCCESS; } -ErrorCode LinkLayerController::WriteLinkPolicySettings(uint16_t handle, - uint16_t settings) { +ErrorCode LinkLayerController::WriteLinkPolicySettings(uint16_t handle, uint16_t settings) { if (!connections_.HasHandle(handle)) { return ErrorCode::UNKNOWN_CONNECTION; } @@ -5804,8 +5420,7 @@ ErrorCode LinkLayerController::WriteLinkPolicySettings(uint16_t handle, return ErrorCode::SUCCESS; } -ErrorCode LinkLayerController::WriteDefaultLinkPolicySettings( - uint16_t settings) { +ErrorCode LinkLayerController::WriteDefaultLinkPolicySettings(uint16_t settings) { if (settings > 7 /* Sniff + Hold + Role switch */) { return ErrorCode::INVALID_HCI_COMMAND_PARAMETERS; } @@ -5819,52 +5434,46 @@ uint16_t LinkLayerController::ReadDefaultLinkPolicySettings() const { } void LinkLayerController::ReadLocalOobData() { - std::array c_array( - {'c', ' ', 'a', 'r', 'r', 'a', 'y', ' ', '0', '0', '0', '0', '0', '0', - static_cast((oob_id_ % 0x10000) >> 8), - static_cast(oob_id_ % 0x100)}); - - std::array r_array( - {'r', ' ', 'a', 'r', 'r', 'a', 'y', ' ', '0', '0', '0', '0', '0', '0', - static_cast((oob_id_ % 0x10000) >> 8), - static_cast(oob_id_ % 0x100)}); - - send_event_(bluetooth::hci::ReadLocalOobDataCompleteBuilder::Create( - 1, ErrorCode::SUCCESS, c_array, r_array)); + std::array c_array({'c', ' ', 'a', 'r', 'r', 'a', 'y', ' ', '0', '0', '0', '0', '0', + '0', static_cast((oob_id_ % 0x10000) >> 8), + static_cast(oob_id_ % 0x100)}); + + std::array r_array({'r', ' ', 'a', 'r', 'r', 'a', 'y', ' ', '0', '0', '0', '0', '0', + '0', static_cast((oob_id_ % 0x10000) >> 8), + static_cast(oob_id_ % 0x100)}); + + send_event_(bluetooth::hci::ReadLocalOobDataCompleteBuilder::Create(1, ErrorCode::SUCCESS, + c_array, r_array)); oob_id_ += 1; } void LinkLayerController::ReadLocalOobExtendedData() { - std::array c_192_array( - {'c', ' ', 'a', 'r', 'r', 'a', 'y', ' ', '1', '9', '2', '0', '0', '0', - static_cast((oob_id_ % 0x10000) >> 8), - static_cast(oob_id_ % 0x100)}); - - std::array r_192_array( - {'r', ' ', 'a', 'r', 'r', 'a', 'y', ' ', '1', '9', '2', '0', '0', '0', - static_cast((oob_id_ % 0x10000) >> 8), - static_cast(oob_id_ % 0x100)}); - - std::array c_256_array( - {'c', ' ', 'a', 'r', 'r', 'a', 'y', ' ', '2', '5', '6', '0', '0', '0', - static_cast((oob_id_ % 0x10000) >> 8), - static_cast(oob_id_ % 0x100)}); - - std::array r_256_array( - {'r', ' ', 'a', 'r', 'r', 'a', 'y', ' ', '2', '5', '6', '0', '0', '0', - static_cast((oob_id_ % 0x10000) >> 8), - static_cast(oob_id_ % 0x100)}); + std::array c_192_array({'c', ' ', 'a', 'r', 'r', 'a', 'y', ' ', '1', '9', '2', '0', + '0', '0', static_cast((oob_id_ % 0x10000) >> 8), + static_cast(oob_id_ % 0x100)}); + + std::array r_192_array({'r', ' ', 'a', 'r', 'r', 'a', 'y', ' ', '1', '9', '2', '0', + '0', '0', static_cast((oob_id_ % 0x10000) >> 8), + static_cast(oob_id_ % 0x100)}); + + std::array c_256_array({'c', ' ', 'a', 'r', 'r', 'a', 'y', ' ', '2', '5', '6', '0', + '0', '0', static_cast((oob_id_ % 0x10000) >> 8), + static_cast(oob_id_ % 0x100)}); + + std::array r_256_array({'r', ' ', 'a', 'r', 'r', 'a', 'y', ' ', '2', '5', '6', '0', + '0', '0', static_cast((oob_id_ % 0x10000) >> 8), + static_cast(oob_id_ % 0x100)}); send_event_(bluetooth::hci::ReadLocalOobExtendedDataCompleteBuilder::Create( - 1, ErrorCode::SUCCESS, c_192_array, r_192_array, c_256_array, - r_256_array)); + 1, ErrorCode::SUCCESS, c_192_array, r_192_array, c_256_array, r_256_array)); oob_id_ += 1; } -ErrorCode LinkLayerController::FlowSpecification( - uint16_t handle, uint8_t flow_direction, uint8_t service_type, - uint32_t /* token_rate */, uint32_t /* token_bucket_size */, - uint32_t /* peak_bandwidth */, uint32_t /* access_latency */) { +ErrorCode LinkLayerController::FlowSpecification(uint16_t handle, uint8_t flow_direction, + uint8_t service_type, uint32_t /* token_rate */, + uint32_t /* token_bucket_size */, + uint32_t /* peak_bandwidth */, + uint32_t /* access_latency */) { if (!connections_.HasHandle(handle)) { return ErrorCode::UNKNOWN_CONNECTION; } @@ -5877,25 +5486,25 @@ ErrorCode LinkLayerController::FlowSpecification( return ErrorCode::COMMAND_DISALLOWED; } -ErrorCode LinkLayerController::WriteLinkSupervisionTimeout( - uint16_t handle, uint16_t /* timeout */) { +ErrorCode LinkLayerController::WriteLinkSupervisionTimeout(uint16_t handle, + uint16_t /* timeout */) { if (!connections_.HasHandle(handle)) { return ErrorCode::UNKNOWN_CONNECTION; } return ErrorCode::SUCCESS; } -void LinkLayerController::LeConnectionUpdateComplete( - uint16_t handle, uint16_t interval_min, uint16_t interval_max, - uint16_t latency, uint16_t supervision_timeout) { +void LinkLayerController::LeConnectionUpdateComplete(uint16_t handle, uint16_t interval_min, + uint16_t interval_max, uint16_t latency, + uint16_t supervision_timeout) { ErrorCode status = ErrorCode::SUCCESS; if (!connections_.HasHandle(handle)) { status = ErrorCode::UNKNOWN_CONNECTION; } if (interval_min < 6 || interval_max > 0xC80 || interval_min > interval_max || - interval_max < interval_min || latency > 0x1F3 || - supervision_timeout < 0xA || supervision_timeout > 0xC80 || + interval_max < interval_min || latency > 0x1F3 || supervision_timeout < 0xA || + supervision_timeout > 0xC80 || // The Supervision_Timeout in milliseconds (*10) shall be larger than (1 + // Connection_Latency) * Connection_Interval_Max (* 5/4) * 2 supervision_timeout <= ((((1 + latency) * interval_max * 10) / 4) / 10)) { @@ -5904,20 +5513,19 @@ void LinkLayerController::LeConnectionUpdateComplete( uint16_t interval = (interval_min + interval_max) / 2; SendLeLinkLayerPacket(LeConnectionParameterUpdateBuilder::Create( - connections_.GetOwnAddress(handle).GetAddress(), - connections_.GetAddress(handle).GetAddress(), - static_cast(ErrorCode::SUCCESS), interval, latency, - supervision_timeout)); + connections_.GetOwnAddress(handle).GetAddress(), + connections_.GetAddress(handle).GetAddress(), static_cast(ErrorCode::SUCCESS), + interval, latency, supervision_timeout)); if (IsLeEventUnmasked(SubeventCode::CONNECTION_UPDATE_COMPLETE)) { send_event_(bluetooth::hci::LeConnectionUpdateCompleteBuilder::Create( - status, handle, interval, latency, supervision_timeout)); + status, handle, interval, latency, supervision_timeout)); } } -ErrorCode LinkLayerController::LeConnectionUpdate( - uint16_t handle, uint16_t interval_min, uint16_t interval_max, - uint16_t latency, uint16_t supervision_timeout) { +ErrorCode LinkLayerController::LeConnectionUpdate(uint16_t handle, uint16_t interval_min, + uint16_t interval_max, uint16_t latency, + uint16_t supervision_timeout) { if (!connections_.HasHandle(handle)) { return ErrorCode::UNKNOWN_CONNECTION; } @@ -5928,51 +5536,46 @@ ErrorCode LinkLayerController::LeConnectionUpdate( // As Central, it is allowed to directly send // LL_CONNECTION_PARAM_UPDATE_IND to update the parameters. SendLeLinkLayerPacket(LeConnectionParameterUpdateBuilder::Create( - connections_.GetOwnAddress(handle).GetAddress(), - connections_.GetAddress(handle).GetAddress(), - static_cast(ErrorCode::SUCCESS), interval_max, latency, - supervision_timeout)); + connections_.GetOwnAddress(handle).GetAddress(), + connections_.GetAddress(handle).GetAddress(), static_cast(ErrorCode::SUCCESS), + interval_max, latency, supervision_timeout)); if (IsLeEventUnmasked(SubeventCode::CONNECTION_UPDATE_COMPLETE)) { send_event_(bluetooth::hci::LeConnectionUpdateCompleteBuilder::Create( - ErrorCode::SUCCESS, handle, interval_max, latency, - supervision_timeout)); + ErrorCode::SUCCESS, handle, interval_max, latency, supervision_timeout)); } } else { // Send LL_CONNECTION_PARAM_REQ and wait for LL_CONNECTION_PARAM_RSP // in return. SendLeLinkLayerPacket(LeConnectionParameterRequestBuilder::Create( - connections_.GetOwnAddress(handle).GetAddress(), - connections_.GetAddress(handle).GetAddress(), interval_min, - interval_max, latency, supervision_timeout)); + connections_.GetOwnAddress(handle).GetAddress(), + connections_.GetAddress(handle).GetAddress(), interval_min, interval_max, latency, + supervision_timeout)); } return ErrorCode::SUCCESS; } ErrorCode LinkLayerController::LeRemoteConnectionParameterRequestReply( - uint16_t connection_handle, uint16_t interval_min, uint16_t interval_max, - uint16_t timeout, uint16_t latency, uint16_t minimum_ce_length, - uint16_t maximum_ce_length) { + uint16_t connection_handle, uint16_t interval_min, uint16_t interval_max, uint16_t timeout, + uint16_t latency, uint16_t minimum_ce_length, uint16_t maximum_ce_length) { if (!connections_.HasHandle(connection_handle)) { return ErrorCode::UNKNOWN_CONNECTION; } - if ((interval_min > interval_max) || - (minimum_ce_length > maximum_ce_length)) { + if ((interval_min > interval_max) || (minimum_ce_length > maximum_ce_length)) { return ErrorCode::INVALID_HCI_COMMAND_PARAMETERS; } - ScheduleTask(kNoDelayMs, [this, connection_handle, interval_min, interval_max, - latency, timeout]() { - LeConnectionUpdateComplete(connection_handle, interval_min, interval_max, - latency, timeout); + ScheduleTask(kNoDelayMs, [this, connection_handle, interval_min, interval_max, latency, + timeout]() { + LeConnectionUpdateComplete(connection_handle, interval_min, interval_max, latency, timeout); }); return ErrorCode::SUCCESS; } ErrorCode LinkLayerController::LeRemoteConnectionParameterRequestNegativeReply( - uint16_t connection_handle, bluetooth::hci::ErrorCode reason) { + uint16_t connection_handle, bluetooth::hci::ErrorCode reason) { if (!connections_.HasHandle(connection_handle)) { return ErrorCode::UNKNOWN_CONNECTION; } @@ -5981,36 +5584,34 @@ ErrorCode LinkLayerController::LeRemoteConnectionParameterRequestNegativeReply( uint16_t latency = 0; uint16_t timeout = 0; SendLeLinkLayerPacket(LeConnectionParameterUpdateBuilder::Create( - connections_.GetOwnAddress(connection_handle).GetAddress(), - connections_.GetAddress(connection_handle).GetAddress(), - static_cast(reason), interval, latency, timeout)); + connections_.GetOwnAddress(connection_handle).GetAddress(), + connections_.GetAddress(connection_handle).GetAddress(), static_cast(reason), + interval, latency, timeout)); return ErrorCode::SUCCESS; } -bool LinkLayerController::HasAclConnection() { - return !connections_.GetAclHandles().empty(); -} +bool LinkLayerController::HasAclConnection() { return !connections_.GetAclHandles().empty(); } bool LinkLayerController::HasAclConnection(uint16_t connection_handle) { return connections_.HasHandle(connection_handle); } -void LinkLayerController::HandleLeEnableEncryption( - uint16_t handle, std::array rand, uint16_t ediv, - std::array ltk) { +void LinkLayerController::HandleLeEnableEncryption(uint16_t handle, std::array rand, + uint16_t ediv, + std::array ltk) { // TODO: Check keys // TODO: Block ACL traffic or at least guard against it if (!connections_.HasHandle(handle)) { return; } SendLeLinkLayerPacket(model::packets::LeEncryptConnectionBuilder::Create( - connections_.GetOwnAddress(handle).GetAddress(), - connections_.GetAddress(handle).GetAddress(), rand, ediv, ltk)); + connections_.GetOwnAddress(handle).GetAddress(), + connections_.GetAddress(handle).GetAddress(), rand, ediv, ltk)); } -ErrorCode LinkLayerController::LeEnableEncryption( - uint16_t handle, std::array rand, uint16_t ediv, - std::array ltk) { +ErrorCode LinkLayerController::LeEnableEncryption(uint16_t handle, std::array rand, + uint16_t ediv, + std::array ltk) { if (!connections_.HasHandle(handle)) { INFO(id_, "Unknown handle 0x{:04x}", handle); return ErrorCode::UNKNOWN_CONNECTION; @@ -6022,8 +5623,8 @@ ErrorCode LinkLayerController::LeEnableEncryption( return ErrorCode::SUCCESS; } -ErrorCode LinkLayerController::LeLongTermKeyRequestReply( - uint16_t handle, std::array ltk) { +ErrorCode LinkLayerController::LeLongTermKeyRequestReply(uint16_t handle, + std::array ltk) { if (!connections_.HasHandle(handle)) { INFO(id_, "Unknown handle {:04x}", handle); return ErrorCode::UNKNOWN_CONNECTION; @@ -6032,37 +5633,33 @@ ErrorCode LinkLayerController::LeLongTermKeyRequestReply( // TODO: Check keys if (connections_.IsEncrypted(handle)) { if (IsEventUnmasked(EventCode::ENCRYPTION_KEY_REFRESH_COMPLETE)) { - send_event_(bluetooth::hci::EncryptionKeyRefreshCompleteBuilder::Create( - ErrorCode::SUCCESS, handle)); + send_event_(bluetooth::hci::EncryptionKeyRefreshCompleteBuilder::Create(ErrorCode::SUCCESS, + handle)); } } else { connections_.Encrypt(handle); if (IsEventUnmasked(EventCode::ENCRYPTION_CHANGE)) { send_event_(bluetooth::hci::EncryptionChangeBuilder::Create( - ErrorCode::SUCCESS, handle, bluetooth::hci::EncryptionEnabled::ON)); + ErrorCode::SUCCESS, handle, bluetooth::hci::EncryptionEnabled::ON)); } } - SendLeLinkLayerPacket( - model::packets::LeEncryptConnectionResponseBuilder::Create( + SendLeLinkLayerPacket(model::packets::LeEncryptConnectionResponseBuilder::Create( connections_.GetOwnAddress(handle).GetAddress(), - connections_.GetAddress(handle).GetAddress(), - std::array(), uint16_t(), ltk)); + connections_.GetAddress(handle).GetAddress(), std::array(), uint16_t(), ltk)); return ErrorCode::SUCCESS; } -ErrorCode LinkLayerController::LeLongTermKeyRequestNegativeReply( - uint16_t handle) { +ErrorCode LinkLayerController::LeLongTermKeyRequestNegativeReply(uint16_t handle) { if (!connections_.HasHandle(handle)) { INFO(id_, "Unknown handle {:04x}", handle); return ErrorCode::UNKNOWN_CONNECTION; } - SendLeLinkLayerPacket( - model::packets::LeEncryptConnectionResponseBuilder::Create( + SendLeLinkLayerPacket(model::packets::LeEncryptConnectionResponseBuilder::Create( connections_.GetOwnAddress(handle).GetAddress(), - connections_.GetAddress(handle).GetAddress(), - std::array(), uint16_t(), std::array())); + connections_.GetAddress(handle).GetAddress(), std::array(), uint16_t(), + std::array())); return ErrorCode::SUCCESS; } @@ -6142,12 +5739,11 @@ void LinkLayerController::Paging() { auto now = std::chrono::steady_clock::now(); if (page_.has_value() && now >= page_->page_timeout) { - INFO("page timeout triggered for connection with {}", - page_->bd_addr.ToString()); + INFO("page timeout triggered for connection with {}", page_->bd_addr.ToString()); send_event_(bluetooth::hci::ConnectionCompleteBuilder::Create( - ErrorCode::PAGE_TIMEOUT, 0, page_->bd_addr, - bluetooth::hci::LinkType::ACL, bluetooth::hci::Enable::DISABLED)); + ErrorCode::PAGE_TIMEOUT, 0, page_->bd_addr, bluetooth::hci::LinkType::ACL, + bluetooth::hci::Enable::DISABLED)); page_ = {}; return; @@ -6159,16 +5755,14 @@ void LinkLayerController::Paging() { if (page_.has_value() && now >= page_->next_page_event && !connections_.HasPendingConnection(page_->bd_addr)) { SendLinkLayerPacket(model::packets::PageBuilder::Create( - GetAddress(), page_->bd_addr, class_of_device_, - page_->allow_role_switch)); + GetAddress(), page_->bd_addr, class_of_device_, page_->allow_role_switch)); page_->next_page_event = now + kPageInterval; } } void LinkLayerController::StartInquiry(milliseconds timeout) { - inquiry_timer_task_id_ = ScheduleTask(milliseconds(timeout), [this]() { - LinkLayerController::InquiryTimeout(); - }); + inquiry_timer_task_id_ = + ScheduleTask(milliseconds(timeout), [this]() { LinkLayerController::InquiryTimeout(); }); } void LinkLayerController::InquiryCancel() { @@ -6181,8 +5775,7 @@ void LinkLayerController::InquiryTimeout() { if (inquiry_timer_task_id_ != kInvalidTaskId) { inquiry_timer_task_id_ = kInvalidTaskId; if (IsEventUnmasked(EventCode::INQUIRY_COMPLETE)) { - send_event_( - bluetooth::hci::InquiryCompleteBuilder::Create(ErrorCode::SUCCESS)); + send_event_(bluetooth::hci::InquiryCompleteBuilder::Create(ErrorCode::SUCCESS)); } } } @@ -6193,9 +5786,7 @@ void LinkLayerController::SetInquiryMode(uint8_t mode) { void LinkLayerController::SetInquiryLAP(uint64_t lap) { inquiry_lap_ = lap; } -void LinkLayerController::SetInquiryMaxResponses(uint8_t max) { - inquiry_max_responses_ = max; -} +void LinkLayerController::SetInquiryMaxResponses(uint8_t max) { inquiry_max_responses_ = max; } void LinkLayerController::Inquiry() { steady_clock::time_point now = steady_clock::now(); @@ -6203,25 +5794,18 @@ void LinkLayerController::Inquiry() { return; } - SendLinkLayerPacket(model::packets::InquiryBuilder::Create( - GetAddress(), Address::kEmpty, inquiry_mode_, inquiry_lap_)); + SendLinkLayerPacket(model::packets::InquiryBuilder::Create(GetAddress(), Address::kEmpty, + inquiry_mode_, inquiry_lap_)); last_inquiry_ = now; } -void LinkLayerController::SetInquiryScanEnable(bool enable) { - inquiry_scan_enable_ = enable; -} +void LinkLayerController::SetInquiryScanEnable(bool enable) { inquiry_scan_enable_ = enable; } -void LinkLayerController::SetPageScanEnable(bool enable) { - page_scan_enable_ = enable; -} +void LinkLayerController::SetPageScanEnable(bool enable) { page_scan_enable_ = enable; } -void LinkLayerController::SetPageTimeout(uint16_t page_timeout) { - page_timeout_ = page_timeout; -} +void LinkLayerController::SetPageTimeout(uint16_t page_timeout) { page_timeout_ = page_timeout; } -ErrorCode LinkLayerController::AddScoConnection(uint16_t connection_handle, - uint16_t packet_type, +ErrorCode LinkLayerController::AddScoConnection(uint16_t connection_handle, uint16_t packet_type, ScoDatapath datapath) { if (!connections_.HasHandle(connection_handle)) { return ErrorCode::UNKNOWN_CONNECTION; @@ -6236,39 +5820,32 @@ ErrorCode LinkLayerController::AddScoConnection(uint16_t connection_handle, // Save connection parameters. ScoConnectionParameters connection_parameters = { - 8000, - 8000, - 0xffff, - 0x60 /* 16bit CVSD */, - (uint8_t)bluetooth::hci::RetransmissionEffort::NO_RETRANSMISSION, - (uint16_t)((uint16_t)((packet_type >> 5) & 0x7U) | - (uint16_t)bluetooth::hci::SynchronousPacketTypeBits:: - NO_2_EV3_ALLOWED | - (uint16_t)bluetooth::hci::SynchronousPacketTypeBits:: - NO_3_EV3_ALLOWED | - (uint16_t)bluetooth::hci::SynchronousPacketTypeBits:: - NO_2_EV5_ALLOWED | - (uint16_t)bluetooth::hci::SynchronousPacketTypeBits:: - NO_3_EV5_ALLOWED)}; - connections_.CreateScoConnection( - connections_.GetAddress(connection_handle).GetAddress(), - connection_parameters, SCO_STATE_PENDING, datapath, true); + 8000, + 8000, + 0xffff, + 0x60 /* 16bit CVSD */, + (uint8_t)bluetooth::hci::RetransmissionEffort::NO_RETRANSMISSION, + (uint16_t)((uint16_t)((packet_type >> 5) & 0x7U) | + (uint16_t)bluetooth::hci::SynchronousPacketTypeBits::NO_2_EV3_ALLOWED | + (uint16_t)bluetooth::hci::SynchronousPacketTypeBits::NO_3_EV3_ALLOWED | + (uint16_t)bluetooth::hci::SynchronousPacketTypeBits::NO_2_EV5_ALLOWED | + (uint16_t)bluetooth::hci::SynchronousPacketTypeBits::NO_3_EV5_ALLOWED)}; + connections_.CreateScoConnection(connections_.GetAddress(connection_handle).GetAddress(), + connection_parameters, SCO_STATE_PENDING, datapath, true); // Send SCO connection request to peer. SendLinkLayerPacket(model::packets::ScoConnectionRequestBuilder::Create( - GetAddress(), bd_addr, connection_parameters.transmit_bandwidth, - connection_parameters.receive_bandwidth, - connection_parameters.max_latency, connection_parameters.voice_setting, - connection_parameters.retransmission_effort, - connection_parameters.packet_type, class_of_device_)); + GetAddress(), bd_addr, connection_parameters.transmit_bandwidth, + connection_parameters.receive_bandwidth, connection_parameters.max_latency, + connection_parameters.voice_setting, connection_parameters.retransmission_effort, + connection_parameters.packet_type, class_of_device_)); return ErrorCode::SUCCESS; } ErrorCode LinkLayerController::SetupSynchronousConnection( - uint16_t connection_handle, uint32_t transmit_bandwidth, - uint32_t receive_bandwidth, uint16_t max_latency, uint16_t voice_setting, - uint8_t retransmission_effort, uint16_t packet_types, - ScoDatapath datapath) { + uint16_t connection_handle, uint32_t transmit_bandwidth, uint32_t receive_bandwidth, + uint16_t max_latency, uint16_t voice_setting, uint8_t retransmission_effort, + uint16_t packet_types, ScoDatapath datapath) { if (!connections_.HasHandle(connection_handle)) { return ErrorCode::UNKNOWN_CONNECTION; } @@ -6284,24 +5861,23 @@ ErrorCode LinkLayerController::SetupSynchronousConnection( INFO(id_, "Creating eSCO connection with {}", bd_addr); // Save connection parameters. - ScoConnectionParameters connection_parameters = { - transmit_bandwidth, receive_bandwidth, max_latency, - voice_setting, retransmission_effort, packet_types}; - connections_.CreateScoConnection( - connections_.GetAddress(connection_handle).GetAddress(), - connection_parameters, SCO_STATE_PENDING, datapath); + ScoConnectionParameters connection_parameters = {transmit_bandwidth, receive_bandwidth, + max_latency, voice_setting, + retransmission_effort, packet_types}; + connections_.CreateScoConnection(connections_.GetAddress(connection_handle).GetAddress(), + connection_parameters, SCO_STATE_PENDING, datapath); // Send eSCO connection request to peer. SendLinkLayerPacket(model::packets::ScoConnectionRequestBuilder::Create( - GetAddress(), bd_addr, transmit_bandwidth, receive_bandwidth, max_latency, - voice_setting, retransmission_effort, packet_types, class_of_device_)); + GetAddress(), bd_addr, transmit_bandwidth, receive_bandwidth, max_latency, voice_setting, + retransmission_effort, packet_types, class_of_device_)); return ErrorCode::SUCCESS; } ErrorCode LinkLayerController::AcceptSynchronousConnection( - Address bd_addr, uint32_t transmit_bandwidth, uint32_t receive_bandwidth, - uint16_t max_latency, uint16_t voice_setting, uint8_t retransmission_effort, - uint16_t packet_types) { + Address bd_addr, uint32_t transmit_bandwidth, uint32_t receive_bandwidth, + uint16_t max_latency, uint16_t voice_setting, uint8_t retransmission_effort, + uint16_t packet_types) { INFO(id_, "Accepting eSCO connection request from {}", bd_addr); if (!connections_.HasPendingScoConnection(bd_addr)) { @@ -6312,14 +5888,13 @@ ErrorCode LinkLayerController::AcceptSynchronousConnection( ErrorCode status = ErrorCode::SUCCESS; uint16_t sco_handle = 0; ScoLinkParameters link_parameters = {}; - ScoConnectionParameters connection_parameters = { - transmit_bandwidth, receive_bandwidth, max_latency, - voice_setting, retransmission_effort, packet_types}; + ScoConnectionParameters connection_parameters = {transmit_bandwidth, receive_bandwidth, + max_latency, voice_setting, + retransmission_effort, packet_types}; - if (!connections_.AcceptPendingScoConnection( - bd_addr, connection_parameters, [this, bd_addr] { - return LinkLayerController::StartScoStream(bd_addr); - })) { + if (!connections_.AcceptPendingScoConnection(bd_addr, connection_parameters, [this, bd_addr] { + return LinkLayerController::StartScoStream(bd_addr); + })) { connections_.CancelPendingScoConnection(bd_addr); status = ErrorCode::STATUS_UNKNOWN; // TODO: proper status code } else { @@ -6329,31 +5904,27 @@ ErrorCode LinkLayerController::AcceptSynchronousConnection( // Send eSCO connection response to peer. SendLinkLayerPacket(model::packets::ScoConnectionResponseBuilder::Create( - GetAddress(), bd_addr, (uint8_t)status, - link_parameters.transmission_interval, - link_parameters.retransmission_window, link_parameters.rx_packet_length, - link_parameters.tx_packet_length, link_parameters.air_mode, - link_parameters.extended)); + GetAddress(), bd_addr, (uint8_t)status, link_parameters.transmission_interval, + link_parameters.retransmission_window, link_parameters.rx_packet_length, + link_parameters.tx_packet_length, link_parameters.air_mode, link_parameters.extended)); // Schedule HCI Synchronous Connection Complete event. - ScheduleTask(kNoDelayMs, [this, status, sco_handle, bd_addr, - link_parameters]() { + ScheduleTask(kNoDelayMs, [this, status, sco_handle, bd_addr, link_parameters]() { send_event_(bluetooth::hci::SynchronousConnectionCompleteBuilder::Create( - ErrorCode(status), sco_handle, bd_addr, - link_parameters.extended ? bluetooth::hci::ScoLinkType::ESCO - : bluetooth::hci::ScoLinkType::SCO, - link_parameters.extended ? link_parameters.transmission_interval : 0, - link_parameters.extended ? link_parameters.retransmission_window : 0, - link_parameters.extended ? link_parameters.rx_packet_length : 0, - link_parameters.extended ? link_parameters.tx_packet_length : 0, - bluetooth::hci::ScoAirMode(link_parameters.air_mode))); + ErrorCode(status), sco_handle, bd_addr, + link_parameters.extended ? bluetooth::hci::ScoLinkType::ESCO + : bluetooth::hci::ScoLinkType::SCO, + link_parameters.extended ? link_parameters.transmission_interval : 0, + link_parameters.extended ? link_parameters.retransmission_window : 0, + link_parameters.extended ? link_parameters.rx_packet_length : 0, + link_parameters.extended ? link_parameters.tx_packet_length : 0, + bluetooth::hci::ScoAirMode(link_parameters.air_mode))); }); return ErrorCode::SUCCESS; } -ErrorCode LinkLayerController::RejectSynchronousConnection(Address bd_addr, - uint16_t reason) { +ErrorCode LinkLayerController::RejectSynchronousConnection(Address bd_addr, uint16_t reason) { INFO(id_, "Rejecting eSCO connection request from {}", bd_addr); if (reason == (uint8_t)ErrorCode::SUCCESS) { @@ -6367,13 +5938,13 @@ ErrorCode LinkLayerController::RejectSynchronousConnection(Address bd_addr, // Send eSCO connection response to peer. SendLinkLayerPacket(model::packets::ScoConnectionResponseBuilder::Create( - GetAddress(), bd_addr, reason, 0, 0, 0, 0, 0, 0)); + GetAddress(), bd_addr, reason, 0, 0, 0, 0, 0, 0)); // Schedule HCI Synchronous Connection Complete event. ScheduleTask(kNoDelayMs, [this, reason, bd_addr]() { send_event_(bluetooth::hci::SynchronousConnectionCompleteBuilder::Create( - ErrorCode(reason), 0, bd_addr, bluetooth::hci::ScoLinkType::ESCO, 0, 0, - 0, 0, bluetooth::hci::ScoAirMode::TRANSPARENT)); + ErrorCode(reason), 0, bd_addr, bluetooth::hci::ScoLinkType::ESCO, 0, 0, 0, 0, + bluetooth::hci::ScoAirMode::TRANSPARENT)); }); return ErrorCode::SUCCESS; @@ -6385,43 +5956,41 @@ void LinkLayerController::CheckExpiringConnection(uint16_t handle) { } if (connections_.HasLinkExpired(handle)) { - Disconnect(handle, ErrorCode::CONNECTION_TIMEOUT, - ErrorCode::CONNECTION_TIMEOUT); + Disconnect(handle, ErrorCode::CONNECTION_TIMEOUT, ErrorCode::CONNECTION_TIMEOUT); return; } if (connections_.IsLinkNearExpiring(handle)) { AddressWithType my_address = connections_.GetOwnAddress(handle); AddressWithType destination = connections_.GetAddress(handle); - SendLinkLayerPacket(model::packets::PingRequestBuilder::Create( - my_address.GetAddress(), destination.GetAddress())); - ScheduleTask(std::chrono::duration_cast( - connections_.TimeUntilLinkExpired(handle)), - [this, handle] { CheckExpiringConnection(handle); }); + SendLinkLayerPacket(model::packets::PingRequestBuilder::Create(my_address.GetAddress(), + destination.GetAddress())); + ScheduleTask( + std::chrono::duration_cast(connections_.TimeUntilLinkExpired(handle)), + [this, handle] { CheckExpiringConnection(handle); }); return; } - ScheduleTask(std::chrono::duration_cast( - connections_.TimeUntilLinkNearExpiring(handle)), - [this, handle] { CheckExpiringConnection(handle); }); + ScheduleTask( + std::chrono::duration_cast(connections_.TimeUntilLinkNearExpiring(handle)), + [this, handle] { CheckExpiringConnection(handle); }); } -void LinkLayerController::IncomingPingRequest( - model::packets::LinkLayerPacketView incoming) { +void LinkLayerController::IncomingPingRequest(model::packets::LinkLayerPacketView incoming) { auto view = model::packets::PingRequestView::Create(incoming); ASSERT(view.IsValid()); - SendLinkLayerPacket(model::packets::PingResponseBuilder::Create( - incoming.GetDestinationAddress(), incoming.GetSourceAddress())); + SendLinkLayerPacket(model::packets::PingResponseBuilder::Create(incoming.GetDestinationAddress(), + incoming.GetSourceAddress())); } TaskId LinkLayerController::StartScoStream(Address address) { - auto sco_builder = bluetooth::hci::ScoBuilder::Create( - connections_.GetScoHandle(address), PacketStatusFlag::CORRECTLY_RECEIVED, - {0, 0, 0, 0, 0}); + auto sco_builder = + bluetooth::hci::ScoBuilder::Create(connections_.GetScoHandle(address), + PacketStatusFlag::CORRECTLY_RECEIVED, {0, 0, 0, 0, 0}); auto sco_bytes = sco_builder->SerializeToBytes(); - auto sco_view = bluetooth::hci::ScoView::Create(pdl::packet::slice( - std::make_shared>(std::move(sco_bytes)))); + auto sco_view = bluetooth::hci::ScoView::Create( + pdl::packet::slice(std::make_shared>(std::move(sco_bytes)))); ASSERT(sco_view.IsValid()); return SchedulePeriodicTask(0ms, 20ms, [this, address, sco_view]() { @@ -6432,10 +6001,9 @@ TaskId LinkLayerController::StartScoStream(Address address) { TaskId LinkLayerController::NextTaskId() { TaskId task_id = task_counter_++; - while ( - task_id == kInvalidTaskId || - std::any_of(task_queue_.begin(), task_queue_.end(), - [=](Task const& task) { return task.task_id == task_id; })) { + while (task_id == kInvalidTaskId || + std::any_of(task_queue_.begin(), task_queue_.end(), + [=](Task const& task) { return task.task_id == task_id; })) { task_id = task_counter_++; } return task_id; @@ -6444,17 +6012,16 @@ TaskId LinkLayerController::NextTaskId() { TaskId LinkLayerController::ScheduleTask(std::chrono::milliseconds delay, TaskCallback task_callback) { TaskId task_id = NextTaskId(); - task_queue_.emplace(std::chrono::steady_clock::now() + delay, - std::move(task_callback), task_id); + task_queue_.emplace(std::chrono::steady_clock::now() + delay, std::move(task_callback), task_id); return task_id; } -TaskId LinkLayerController::SchedulePeriodicTask( - std::chrono::milliseconds delay, std::chrono::milliseconds period, - TaskCallback task_callback) { +TaskId LinkLayerController::SchedulePeriodicTask(std::chrono::milliseconds delay, + std::chrono::milliseconds period, + TaskCallback task_callback) { TaskId task_id = NextTaskId(); - task_queue_.emplace(std::chrono::steady_clock::now() + delay, period, - std::move(task_callback), task_id); + task_queue_.emplace(std::chrono::steady_clock::now() + delay, period, std::move(task_callback), + task_id); return task_id; } diff --git a/tools/rootcanal/model/controller/link_layer_controller.h b/tools/rootcanal/model/controller/link_layer_controller.h index 57e4cbf5d39..75a8fd3af4c 100644 --- a/tools/rootcanal/model/controller/link_layer_controller.h +++ b/tools/rootcanal/model/controller/link_layer_controller.h @@ -55,15 +55,13 @@ using ::bluetooth::hci::PageScanRepetitionMode; using rootcanal::apcf::ApcfScanner; // Create an address with type Public Device Address or Random Device Address. -AddressWithType PeerDeviceAddress(Address address, - PeerAddressType peer_address_type); +AddressWithType PeerDeviceAddress(Address address, PeerAddressType peer_address_type); // Create an address with type Public Identity Address or Random Identity // address. -AddressWithType PeerIdentityAddress(Address address, - PeerAddressType peer_address_type); +AddressWithType PeerIdentityAddress(Address address, PeerAddressType peer_address_type); class LinkLayerController { - public: +public: static constexpr size_t kIrkSize = 16; static constexpr size_t kLtkSize = 16; static constexpr size_t kLocalNameSize = 248; @@ -73,24 +71,20 @@ class LinkLayerController { const uint32_t id_; // Generate a resolvable private address using the specified IRK. - static Address generate_rpa( - std::array irk); + static Address generate_rpa(std::array irk); // Return true if the input IRK is all 0s. static bool irk_is_zero(std::array irk); - LinkLayerController(const Address& address, - const ControllerProperties& properties, uint32_t id = 0); + LinkLayerController(const Address& address, const ControllerProperties& properties, + uint32_t id = 0); ~LinkLayerController(); ErrorCode SendCommandToRemoteByAddress(OpCode opcode, pdl::packet::slice args, - const Address& own_address, - const Address& peer_address); - ErrorCode SendLeCommandToRemoteByAddress(OpCode opcode, - const Address& own_address, + const Address& own_address, const Address& peer_address); + ErrorCode SendLeCommandToRemoteByAddress(OpCode opcode, const Address& own_address, const Address& peer_address); - ErrorCode SendCommandToRemoteByHandle(OpCode opcode, pdl::packet::slice args, - uint16_t handle); + ErrorCode SendCommandToRemoteByHandle(OpCode opcode, pdl::packet::slice args, uint16_t handle); ErrorCode SendScoToRemote(bluetooth::hci::ScoView sco_packet); ErrorCode SendAclToRemote(bluetooth::hci::AclView acl_packet); @@ -106,17 +100,16 @@ class LinkLayerController { void RejectPeripheralConnection(const Address& addr, uint8_t reason); // HCI command Create Connection (Vol 4, Part E § 7.1.5). - ErrorCode CreateConnection(const Address& bd_addr, uint16_t packet_type, - uint8_t page_scan_mode, uint16_t clock_offset, - uint8_t allow_role_switch); + ErrorCode CreateConnection(const Address& bd_addr, uint16_t packet_type, uint8_t page_scan_mode, + uint16_t clock_offset, uint8_t allow_role_switch); // HCI command Disconnect (Vol 4, Part E § 7.1.6). // \p host_reason is taken from the Disconnect command, and sent over // to the remote as disconnect error. \p controller_reason is the code // used in the DisconnectionComplete event. - ErrorCode Disconnect(uint16_t handle, ErrorCode host_reason, - ErrorCode controller_reason = - ErrorCode::CONNECTION_TERMINATED_BY_LOCAL_HOST); + ErrorCode Disconnect( + uint16_t handle, ErrorCode host_reason, + ErrorCode controller_reason = ErrorCode::CONNECTION_TERMINATED_BY_LOCAL_HOST); // HCI command Create Connection Cancel (Vol 4, Part E § 7.1.7). ErrorCode CreateConnectionCancel(const Address& bd_addr); @@ -130,15 +123,13 @@ class LinkLayerController { static constexpr TaskId kInvalidTaskId = 0; /// Schedule a task to be executed \p delay ms in the future. - TaskId ScheduleTask(std::chrono::milliseconds delay, - TaskCallback task_callback); + TaskId ScheduleTask(std::chrono::milliseconds delay, TaskCallback task_callback); /// Schedule a task to be executed every \p period ms starting /// \p delay ms in the future. Note that the task will be executed /// at most once per \ref Tick() invocation, hence the period /// cannot be lower than the \ref Tick() period. - TaskId SchedulePeriodicTask(std::chrono::milliseconds delay, - std::chrono::milliseconds period, + TaskId SchedulePeriodicTask(std::chrono::milliseconds delay, std::chrono::milliseconds period, TaskCallback task_callback); /// Cancel the selected task. @@ -147,14 +138,13 @@ class LinkLayerController { // Execute tasks that are pending at the current time. void RunPendingTasks(); - private: +private: void SendDisconnectionCompleteEvent(uint16_t handle, ErrorCode reason); - public: +public: const Address& GetAddress() const; - void IncomingPacket(model::packets::LinkLayerPacketView incoming, - int8_t rssi); + void IncomingPacket(model::packets::LinkLayerPacketView incoming, int8_t rssi); void Tick(); @@ -162,25 +152,20 @@ class LinkLayerController { // Set the callbacks for sending packets to the HCI. void RegisterEventChannel( - const std::function)>& - send_event); + const std::function)>& send_event); void RegisterAclChannel( - const std::function)>& - send_acl); + const std::function)>& send_acl); void RegisterScoChannel( - const std::function)>& - send_sco); + const std::function)>& send_sco); void RegisterIsoChannel( - const std::function)>& - send_iso); + const std::function)>& send_iso); void RegisterRemoteChannel( - const std::function< - void(std::shared_ptr, - Phy::Type, int8_t)>& send_to_remote); + const std::function, + Phy::Type, int8_t)>& send_to_remote); void Reset(); @@ -189,35 +174,31 @@ class LinkLayerController { void LeScanning(); void LeSynchronization(); - void LeConnectionUpdateComplete(uint16_t handle, uint16_t interval_min, - uint16_t interval_max, uint16_t latency, - uint16_t supervision_timeout); - ErrorCode LeConnectionUpdate(uint16_t handle, uint16_t interval_min, - uint16_t interval_max, uint16_t latency, - uint16_t supervision_timeout); - ErrorCode LeRemoteConnectionParameterRequestReply( - uint16_t connection_handle, uint16_t interval_min, uint16_t interval_max, - uint16_t timeout, uint16_t latency, uint16_t minimum_ce_length, - uint16_t maximum_ce_length); - ErrorCode LeRemoteConnectionParameterRequestNegativeReply( - uint16_t connection_handle, bluetooth::hci::ErrorCode reason); + void LeConnectionUpdateComplete(uint16_t handle, uint16_t interval_min, uint16_t interval_max, + uint16_t latency, uint16_t supervision_timeout); + ErrorCode LeConnectionUpdate(uint16_t handle, uint16_t interval_min, uint16_t interval_max, + uint16_t latency, uint16_t supervision_timeout); + ErrorCode LeRemoteConnectionParameterRequestReply(uint16_t connection_handle, + uint16_t interval_min, uint16_t interval_max, + uint16_t timeout, uint16_t latency, + uint16_t minimum_ce_length, + uint16_t maximum_ce_length); + ErrorCode LeRemoteConnectionParameterRequestNegativeReply(uint16_t connection_handle, + bluetooth::hci::ErrorCode reason); uint16_t HandleLeConnection(AddressWithType addr, AddressWithType own_addr, - bluetooth::hci::Role role, - uint16_t connection_interval, - uint16_t connection_latency, - uint16_t supervision_timeout, + bluetooth::hci::Role role, uint16_t connection_interval, + uint16_t connection_latency, uint16_t supervision_timeout, bool send_le_channel_selection_algorithm_event); bool ResolvingListBusy(); bool FilterAcceptListBusy(); - bool LeFilterAcceptListContainsDevice( - FilterAcceptListAddressType address_type, Address address); + bool LeFilterAcceptListContainsDevice(FilterAcceptListAddressType address_type, Address address); bool LeFilterAcceptListContainsDevice(AddressWithType address); bool LePeriodicAdvertiserListContainsDevice( - bluetooth::hci::AdvertiserAddressType advertiser_address_type, - Address advertiser_address, uint8_t advertising_sid); + bluetooth::hci::AdvertiserAddressType advertiser_address_type, Address advertiser_address, + uint8_t advertising_sid); enum IrkSelection { Peer, // Use Peer IRK for RPA resolution or generation. @@ -244,8 +225,8 @@ class LinkLayerController { // If the address is not found in the resolving list none is returned. // `local` indicates whether to use the local (true) or peer (false) IRK when // generating the Resolvable Private Address. - std::optional GenerateResolvablePrivateAddress( - AddressWithType address, IrkSelection irk); + std::optional GenerateResolvablePrivateAddress(AddressWithType address, + IrkSelection irk); // Check if the selected address matches one of the controller's device // addresses (public or random static). @@ -260,16 +241,13 @@ class LinkLayerController { } } - void HandleLeEnableEncryption(uint16_t handle, std::array rand, - uint16_t ediv, + void HandleLeEnableEncryption(uint16_t handle, std::array rand, uint16_t ediv, std::array ltk); - ErrorCode LeEnableEncryption(uint16_t handle, std::array rand, - uint16_t ediv, + ErrorCode LeEnableEncryption(uint16_t handle, std::array rand, uint16_t ediv, std::array ltk); - ErrorCode LeLongTermKeyRequestReply(uint16_t handle, - std::array ltk); + ErrorCode LeLongTermKeyRequestReply(uint16_t handle, std::array ltk); ErrorCode LeLongTermKeyRequestNegativeReply(uint16_t handle); @@ -298,20 +276,17 @@ class LinkLayerController { ErrorCode CentralLinkKey(uint8_t key_flag); ErrorCode HoldMode(uint16_t handle, uint16_t hold_mode_max_interval, uint16_t hold_mode_min_interval); - ErrorCode SniffMode(uint16_t handle, uint16_t sniff_max_interval, - uint16_t sniff_min_interval, uint16_t sniff_attempt, - uint16_t sniff_timeout); + ErrorCode SniffMode(uint16_t handle, uint16_t sniff_max_interval, uint16_t sniff_min_interval, + uint16_t sniff_attempt, uint16_t sniff_timeout); ErrorCode ExitSniffMode(uint16_t handle); ErrorCode QosSetup(uint16_t handle, uint8_t service_type, uint32_t token_rate, - uint32_t peak_bandwidth, uint32_t latency, - uint32_t delay_variation); + uint32_t peak_bandwidth, uint32_t latency, uint32_t delay_variation); ErrorCode RoleDiscovery(uint16_t handle, bluetooth::hci::Role* role); ErrorCode SwitchRole(Address bd_addr, bluetooth::hci::Role role); ErrorCode ReadLinkPolicySettings(uint16_t handle, uint16_t* settings); ErrorCode WriteLinkPolicySettings(uint16_t handle, uint16_t settings); - ErrorCode FlowSpecification(uint16_t handle, uint8_t flow_direction, - uint8_t service_type, uint32_t token_rate, - uint32_t token_bucket_size, + ErrorCode FlowSpecification(uint16_t handle, uint8_t flow_direction, uint8_t service_type, + uint32_t token_rate, uint32_t token_bucket_size, uint32_t peak_bandwidth, uint32_t access_latency); ErrorCode WriteLinkSupervisionTimeout(uint16_t handle, uint16_t timeout); ErrorCode WriteDefaultLinkPolicySettings(uint16_t settings); @@ -323,15 +298,14 @@ class LinkLayerController { ErrorCode AddScoConnection(uint16_t connection_handle, uint16_t packet_type, ScoDatapath datapath); - ErrorCode SetupSynchronousConnection( - uint16_t connection_handle, uint32_t transmit_bandwidth, - uint32_t receive_bandwidth, uint16_t max_latency, uint16_t voice_setting, - uint8_t retransmission_effort, uint16_t packet_types, - ScoDatapath datapath); - ErrorCode AcceptSynchronousConnection( - Address bd_addr, uint32_t transmit_bandwidth, uint32_t receive_bandwidth, - uint16_t max_latency, uint16_t voice_setting, - uint8_t retransmission_effort, uint16_t packet_types); + ErrorCode SetupSynchronousConnection(uint16_t connection_handle, uint32_t transmit_bandwidth, + uint32_t receive_bandwidth, uint16_t max_latency, + uint16_t voice_setting, uint8_t retransmission_effort, + uint16_t packet_types, ScoDatapath datapath); + ErrorCode AcceptSynchronousConnection(Address bd_addr, uint32_t transmit_bandwidth, + uint32_t receive_bandwidth, uint16_t max_latency, + uint16_t voice_setting, uint8_t retransmission_effort, + uint16_t packet_types); ErrorCode RejectSynchronousConnection(Address bd_addr, uint16_t reason); // Returns true if any ACL connection exists. @@ -356,20 +330,17 @@ class LinkLayerController { ErrorCode LeSetResolvablePrivateAddressTimeout(uint16_t rpa_timeout); // HCI LE Read Phy command (Vol 4, Part E § 7.8.47). - ErrorCode LeReadPhy(uint16_t connection_handle, - bluetooth::hci::PhyType* tx_phy, + ErrorCode LeReadPhy(uint16_t connection_handle, bluetooth::hci::PhyType* tx_phy, bluetooth::hci::PhyType* rx_phy); // HCI LE Set Default Phy command (Vol 4, Part E § 7.8.48). ErrorCode LeSetDefaultPhy(bool all_phys_no_transmit_preference, - bool all_phys_no_receive_preference, - uint8_t tx_phys, uint8_t rx_phys); + bool all_phys_no_receive_preference, uint8_t tx_phys, uint8_t rx_phys); // HCI LE Set Phy command (Vol 4, Part E § 7.8.49). - ErrorCode LeSetPhy(uint16_t connection_handle, - bool all_phys_no_transmit_preference, - bool all_phys_no_receive_preference, uint8_t tx_phys, - uint8_t rx_phys, bluetooth::hci::PhyOptions phy_options); + ErrorCode LeSetPhy(uint16_t connection_handle, bool all_phys_no_transmit_preference, + bool all_phys_no_receive_preference, uint8_t tx_phys, uint8_t rx_phys, + bluetooth::hci::PhyOptions phy_options); // HCI LE Set Host Feature command (Vol 4, Part E § 7.8.115). ErrorCode LeSetHostFeature(uint8_t bit_number, uint8_t bit_value); @@ -380,39 +351,38 @@ class LinkLayerController { ErrorCode LeClearFilterAcceptList(); // HCI command LE_Add_Device_To_Filter_Accept_List (Vol 4, Part E § 7.8.16). - ErrorCode LeAddDeviceToFilterAcceptList( - FilterAcceptListAddressType address_type, Address address); + ErrorCode LeAddDeviceToFilterAcceptList(FilterAcceptListAddressType address_type, + Address address); // HCI command LE_Remove_Device_From_Filter_Accept_List (Vol 4, Part E // § 7.8.17). - ErrorCode LeRemoveDeviceFromFilterAcceptList( - FilterAcceptListAddressType address_type, Address address); + ErrorCode LeRemoveDeviceFromFilterAcceptList(FilterAcceptListAddressType address_type, + Address address); // LE Address Resolving // HCI command LE_Add_Device_To_Resolving_List (Vol 4, Part E § 7.8.38). - ErrorCode LeAddDeviceToResolvingList( - PeerAddressType peer_identity_address_type, Address peer_identity_address, - std::array peer_irk, - std::array local_irk); + ErrorCode LeAddDeviceToResolvingList(PeerAddressType peer_identity_address_type, + Address peer_identity_address, + std::array peer_irk, + std::array local_irk); // HCI command LE_Remove_Device_From_Resolving_List (Vol 4, Part E § 7.8.39). - ErrorCode LeRemoveDeviceFromResolvingList( - PeerAddressType peer_identity_address_type, - Address peer_identity_address); + ErrorCode LeRemoveDeviceFromResolvingList(PeerAddressType peer_identity_address_type, + Address peer_identity_address); // HCI command LE_Clear_Resolving_List (Vol 4, Part E § 7.8.40). ErrorCode LeClearResolvingList(); // HCI command LE_Read_Peer_Resolvable_Address (Vol 4, Part E § 7.8.42). - ErrorCode LeReadPeerResolvableAddress( - PeerAddressType peer_identity_address_type, Address peer_identity_address, - Address* peer_resolvable_address); + ErrorCode LeReadPeerResolvableAddress(PeerAddressType peer_identity_address_type, + Address peer_identity_address, + Address* peer_resolvable_address); // HCI command LE_Read_Local_Resolvable_Address (Vol 4, Part E § 7.8.43). - ErrorCode LeReadLocalResolvableAddress( - PeerAddressType peer_identity_address_type, Address peer_identity_address, - Address* local_resolvable_address); + ErrorCode LeReadLocalResolvableAddress(PeerAddressType peer_identity_address_type, + Address peer_identity_address, + Address* local_resolvable_address); // HCI command LE_Set_Address_Resolution_Enable (Vol 4, Part E § 7.8.44). ErrorCode LeSetAddressResolutionEnable(bool enable); @@ -426,19 +396,18 @@ class LinkLayerController { // HCI command LE_Set_Advertising_Parameters (Vol 4, Part E § 7.8.5). ErrorCode LeSetAdvertisingParameters( - uint16_t advertising_interval_min, uint16_t advertising_interval_max, - bluetooth::hci::AdvertisingType advertising_type, - bluetooth::hci::OwnAddressType own_address_type, - bluetooth::hci::PeerAddressType peer_address_type, Address peer_address, - uint8_t advertising_channel_map, - bluetooth::hci::AdvertisingFilterPolicy advertising_filter_policy); + uint16_t advertising_interval_min, uint16_t advertising_interval_max, + bluetooth::hci::AdvertisingType advertising_type, + bluetooth::hci::OwnAddressType own_address_type, + bluetooth::hci::PeerAddressType peer_address_type, Address peer_address, + uint8_t advertising_channel_map, + bluetooth::hci::AdvertisingFilterPolicy advertising_filter_policy); // HCI command LE_Set_Advertising_Data (Vol 4, Part E § 7.8.7). ErrorCode LeSetAdvertisingData(const std::vector& advertising_data); // HCI command LE_Set_Scan_Response_Data (Vol 4, Part E § 7.8.8). - ErrorCode LeSetScanResponseData( - const std::vector& scan_response_data); + ErrorCode LeSetScanResponseData(const std::vector& scan_response_data); // HCI command LE_Advertising_Enable (Vol 4, Part E § 7.8.9). ErrorCode LeSetAdvertisingEnable(bool advertising_enable); @@ -446,40 +415,34 @@ class LinkLayerController { // Extended Advertising // HCI command LE_Set_Advertising_Set_Random_Address (Vol 4, Part E § 7.8.52). - ErrorCode LeSetAdvertisingSetRandomAddress(uint8_t advertising_handle, - Address random_address); + ErrorCode LeSetAdvertisingSetRandomAddress(uint8_t advertising_handle, Address random_address); // HCI command LE_Set_Advertising_Parameters (Vol 4, Part E § 7.8.53). ErrorCode LeSetExtendedAdvertisingParameters( - uint8_t advertising_handle, - AdvertisingEventProperties advertising_event_properties, - uint16_t primary_advertising_interval_min, - uint16_t primary_advertising_interval_max, - uint8_t primary_advertising_channel_map, - bluetooth::hci::OwnAddressType own_address_type, - bluetooth::hci::PeerAddressType peer_address_type, Address peer_address, - bluetooth::hci::AdvertisingFilterPolicy advertising_filter_policy, - uint8_t advertising_tx_power, - bluetooth::hci::PrimaryPhyType primary_advertising_phy, - uint8_t secondary_max_skip, - bluetooth::hci::SecondaryPhyType secondary_advertising_phy, - uint8_t advertising_sid, bool scan_request_notification_enable); + uint8_t advertising_handle, AdvertisingEventProperties advertising_event_properties, + uint16_t primary_advertising_interval_min, uint16_t primary_advertising_interval_max, + uint8_t primary_advertising_channel_map, bluetooth::hci::OwnAddressType own_address_type, + bluetooth::hci::PeerAddressType peer_address_type, Address peer_address, + bluetooth::hci::AdvertisingFilterPolicy advertising_filter_policy, + uint8_t advertising_tx_power, bluetooth::hci::PrimaryPhyType primary_advertising_phy, + uint8_t secondary_max_skip, bluetooth::hci::SecondaryPhyType secondary_advertising_phy, + uint8_t advertising_sid, bool scan_request_notification_enable); // HCI command LE_Set_Extended_Advertising_Data (Vol 4, Part E § 7.8.54). - ErrorCode LeSetExtendedAdvertisingData( - uint8_t advertising_handle, bluetooth::hci::Operation operation, - bluetooth::hci::FragmentPreference fragment_preference, - const std::vector& advertising_data); + ErrorCode LeSetExtendedAdvertisingData(uint8_t advertising_handle, + bluetooth::hci::Operation operation, + bluetooth::hci::FragmentPreference fragment_preference, + const std::vector& advertising_data); // HCI command LE_Set_Extended_Scan_Response_Data (Vol 4, Part E § 7.8.55). - ErrorCode LeSetExtendedScanResponseData( - uint8_t advertising_handle, bluetooth::hci::Operation operation, - bluetooth::hci::FragmentPreference fragment_preference, - const std::vector& scan_response_data); + ErrorCode LeSetExtendedScanResponseData(uint8_t advertising_handle, + bluetooth::hci::Operation operation, + bluetooth::hci::FragmentPreference fragment_preference, + const std::vector& scan_response_data); // HCI command LE_Set_Extended_Advertising_Enable (Vol 4, Part E § 7.8.56). - ErrorCode LeSetExtendedAdvertisingEnable( - bool enable, const std::vector& sets); + ErrorCode LeSetExtendedAdvertisingEnable(bool enable, + const std::vector& sets); // HCI command LE_Remove_Advertising_Set (Vol 4, Part E § 7.8.59). ErrorCode LeRemoveAdvertisingSet(uint8_t advertising_handle); @@ -490,10 +453,10 @@ class LinkLayerController { // Legacy Scanning // HCI command LE_Set_Scan_Parameters (Vol 4, Part E § 7.8.10). - ErrorCode LeSetScanParameters( - bluetooth::hci::LeScanType scan_type, uint16_t scan_interval, - uint16_t scan_window, bluetooth::hci::OwnAddressType own_address_type, - bluetooth::hci::LeScanningFilterPolicy scanning_filter_policy); + ErrorCode LeSetScanParameters(bluetooth::hci::LeScanType scan_type, uint16_t scan_interval, + uint16_t scan_window, + bluetooth::hci::OwnAddressType own_address_type, + bluetooth::hci::LeScanningFilterPolicy scanning_filter_policy); // HCI command LE_Set_Scan_Enable (Vol 4, Part E § 7.8.11). ErrorCode LeSetScanEnable(bool enable, bool filter_duplicates); @@ -502,28 +465,24 @@ class LinkLayerController { // HCI command LE_Set_Extended_Scan_Parameters (Vol 4, Part E § 7.8.64). ErrorCode LeSetExtendedScanParameters( - bluetooth::hci::OwnAddressType own_address_type, - bluetooth::hci::LeScanningFilterPolicy scanning_filter_policy, - uint8_t scanning_phys, - std::vector - scanning_phy_parameters); + bluetooth::hci::OwnAddressType own_address_type, + bluetooth::hci::LeScanningFilterPolicy scanning_filter_policy, uint8_t scanning_phys, + std::vector scanning_phy_parameters); // HCI command LE_Set_Extended_Scan_Enable (Vol 4, Part E § 7.8.65). - ErrorCode LeSetExtendedScanEnable( - bool enable, bluetooth::hci::FilterDuplicates filter_duplicates, - uint16_t duration, uint16_t period); + ErrorCode LeSetExtendedScanEnable(bool enable, bluetooth::hci::FilterDuplicates filter_duplicates, + uint16_t duration, uint16_t period); // Legacy Connection // HCI LE Create Connection command (Vol 4, Part E § 7.8.12). - ErrorCode LeCreateConnection( - uint16_t scan_interval, uint16_t scan_window, - bluetooth::hci::InitiatorFilterPolicy initiator_filter_policy, - AddressWithType peer_address, - bluetooth::hci::OwnAddressType own_address_type, - uint16_t connection_interval_min, uint16_t connection_interval_max, - uint16_t max_latency, uint16_t supervision_timeout, - uint16_t min_ce_length, uint16_t max_ce_length); + ErrorCode LeCreateConnection(uint16_t scan_interval, uint16_t scan_window, + bluetooth::hci::InitiatorFilterPolicy initiator_filter_policy, + AddressWithType peer_address, + bluetooth::hci::OwnAddressType own_address_type, + uint16_t connection_interval_min, uint16_t connection_interval_max, + uint16_t max_latency, uint16_t supervision_timeout, + uint16_t min_ce_length, uint16_t max_ce_length); // HCI LE Create Connection Cancel command (Vol 4, Part E § 7.8.12). ErrorCode LeCreateConnectionCancel(); @@ -532,24 +491,24 @@ class LinkLayerController { // HCI LE Extended Create Connection command (Vol 4, Part E § 7.8.66). ErrorCode LeExtendedCreateConnection( - bluetooth::hci::InitiatorFilterPolicy initiator_filter_policy, - bluetooth::hci::OwnAddressType own_address_type, - AddressWithType peer_address, uint8_t initiating_phys, - std::vector - initiating_phy_parameters); + bluetooth::hci::InitiatorFilterPolicy initiator_filter_policy, + bluetooth::hci::OwnAddressType own_address_type, AddressWithType peer_address, + uint8_t initiating_phys, + std::vector initiating_phy_parameters); // Periodic Advertising // HCI LE Set Periodic Advertising Parameters command (Vol 4, Part E // § 7.8.61). - ErrorCode LeSetPeriodicAdvertisingParameters( - uint8_t advertising_handle, uint16_t periodic_advertising_interval_min, - uint16_t periodic_advertising_interval_max, bool include_tx_power); + ErrorCode LeSetPeriodicAdvertisingParameters(uint8_t advertising_handle, + uint16_t periodic_advertising_interval_min, + uint16_t periodic_advertising_interval_max, + bool include_tx_power); // HCI LE Set Periodic Advertising Data command (Vol 4, Part E § 7.8.62). - ErrorCode LeSetPeriodicAdvertisingData( - uint8_t advertising_handle, bluetooth::hci::Operation operation, - const std::vector& advertising_data); + ErrorCode LeSetPeriodicAdvertisingData(uint8_t advertising_handle, + bluetooth::hci::Operation operation, + const std::vector& advertising_data); // HCI LE Set Periodic Advertising Enable command (Vol 4, Part E § 7.8.63). ErrorCode LeSetPeriodicAdvertisingEnable(bool enable, bool include_adi, @@ -559,11 +518,9 @@ class LinkLayerController { // HCI LE Periodic Advertising Create Sync command (Vol 4, Part E § 7.8.67). ErrorCode LePeriodicAdvertisingCreateSync( - bluetooth::hci::PeriodicAdvertisingOptions options, - uint8_t advertising_sid, - bluetooth::hci::AdvertiserAddressType advertiser_address_type, - Address advertiser_address, uint16_t skip, uint16_t sync_timeout, - uint8_t sync_cte_type); + bluetooth::hci::PeriodicAdvertisingOptions options, uint8_t advertising_sid, + bluetooth::hci::AdvertiserAddressType advertiser_address_type, Address advertiser_address, + uint16_t skip, uint16_t sync_timeout, uint8_t sync_cte_type); // HCI LE Periodic Advertising Create Sync Cancel command (Vol 4, Part E // § 7.8.68). @@ -578,14 +535,14 @@ class LinkLayerController { // HCI LE Add Device To Periodic Advertiser List command (Vol 4, Part E // § 7.8.70). ErrorCode LeAddDeviceToPeriodicAdvertiserList( - bluetooth::hci::AdvertiserAddressType advertiser_address_type, - Address advertiser_address, uint8_t advertising_sid); + bluetooth::hci::AdvertiserAddressType advertiser_address_type, Address advertiser_address, + uint8_t advertising_sid); // HCI LE Remove Device From Periodic Advertiser List command // (Vol 4, Part E § 7.8.71). ErrorCode LeRemoveDeviceFromPeriodicAdvertiserList( - bluetooth::hci::AdvertiserAddressType advertiser_address_type, - Address advertiser_address, uint8_t advertising_sid); + bluetooth::hci::AdvertiserAddressType advertiser_address_type, Address advertiser_address, + uint8_t advertising_sid); // HCI LE Clear Periodic Advertiser List command (Vol 4, Part E § 7.8.72). ErrorCode LeClearPeriodicAdvertiserList(); @@ -594,13 +551,14 @@ class LinkLayerController { ErrorCode LeApcfEnable(bool apcf_enable); - ErrorCode LeApcfAddFilteringParameters( - uint8_t apcf_filter_index, uint16_t apcf_feature_selection, - uint16_t apcf_list_logic_type, uint8_t apcf_filter_logic_type, - uint8_t rssi_high_thresh, bluetooth::hci::DeliveryMode delivery_mode, - uint16_t onfound_timeout, uint8_t onfound_timeout_cnt, - uint8_t rssi_low_thresh, uint16_t onlost_timeout, - uint16_t num_of_tracking_entries, uint8_t* apcf_available_spaces); + ErrorCode LeApcfAddFilteringParameters(uint8_t apcf_filter_index, uint16_t apcf_feature_selection, + uint16_t apcf_list_logic_type, + uint8_t apcf_filter_logic_type, uint8_t rssi_high_thresh, + bluetooth::hci::DeliveryMode delivery_mode, + uint16_t onfound_timeout, uint8_t onfound_timeout_cnt, + uint8_t rssi_low_thresh, uint16_t onlost_timeout, + uint16_t num_of_tracking_entries, + uint8_t* apcf_available_spaces); ErrorCode LeApcfDeleteFilteringParameters(uint8_t apcf_filter_index, uint8_t* apcf_available_spaces); @@ -608,145 +566,106 @@ class LinkLayerController { ErrorCode LeApcfClearFilteringParameters(uint8_t* apcf_available_spaces); ErrorCode LeApcfBroadcasterAddress( - bluetooth::hci::ApcfAction apcf_action, uint8_t apcf_filter_index, - bluetooth::hci::Address apcf_broadcaster_address, - bluetooth::hci::ApcfApplicationAddressType apcf_application_address_type, - uint8_t* apcf_available_spaces); - - ErrorCode LeApcfServiceUuid(bluetooth::hci::ApcfAction apcf_action, - uint8_t apcf_filter_index, - std::vector acpf_uuid_data, - uint8_t* apcf_available_spaces); + bluetooth::hci::ApcfAction apcf_action, uint8_t apcf_filter_index, + bluetooth::hci::Address apcf_broadcaster_address, + bluetooth::hci::ApcfApplicationAddressType apcf_application_address_type, + uint8_t* apcf_available_spaces); + + ErrorCode LeApcfServiceUuid(bluetooth::hci::ApcfAction apcf_action, uint8_t apcf_filter_index, + std::vector acpf_uuid_data, uint8_t* apcf_available_spaces); - ErrorCode LeApcfServiceSolicitationUuid( - bluetooth::hci::ApcfAction apcf_action, uint8_t apcf_filter_index, - std::vector acpf_uuid_data, uint8_t* apcf_available_spaces); + ErrorCode LeApcfServiceSolicitationUuid(bluetooth::hci::ApcfAction apcf_action, + uint8_t apcf_filter_index, + std::vector acpf_uuid_data, + uint8_t* apcf_available_spaces); - ErrorCode LeApcfLocalName(bluetooth::hci::ApcfAction apcf_action, - uint8_t apcf_filter_index, - std::vector apcf_local_name, - uint8_t* apcf_available_spaces); + ErrorCode LeApcfLocalName(bluetooth::hci::ApcfAction apcf_action, uint8_t apcf_filter_index, + std::vector apcf_local_name, uint8_t* apcf_available_spaces); ErrorCode LeApcfManufacturerData(bluetooth::hci::ApcfAction apcf_action, uint8_t apcf_filter_index, std::vector apcf_manufacturer_data, uint8_t* apcf_available_spaces); - ErrorCode LeApcfServiceData(bluetooth::hci::ApcfAction apcf_action, - uint8_t apcf_filter_index, + ErrorCode LeApcfServiceData(bluetooth::hci::ApcfAction apcf_action, uint8_t apcf_filter_index, std::vector apcf_service_data, uint8_t* apcf_available_spaces); - ErrorCode LeApcfAdTypeFilter(bluetooth::hci::ApcfAction apcf_action, - uint8_t apcf_filter_index, uint8_t ad_type, - std::vector apcf_ad_data, + ErrorCode LeApcfAdTypeFilter(bluetooth::hci::ApcfAction apcf_action, uint8_t apcf_filter_index, + uint8_t ad_type, std::vector apcf_ad_data, std::vector apcf_ad_data_mask, uint8_t* apcf_available_spaces); - protected: - void SendLinkLayerPacket( - std::unique_ptr packet, - int8_t tx_power = 0); - void SendLeLinkLayerPacket( - std::unique_ptr packet, - int8_t tx_power = 0); +protected: + void SendLinkLayerPacket(std::unique_ptr packet, + int8_t tx_power = 0); + void SendLeLinkLayerPacket(std::unique_ptr packet, + int8_t tx_power = 0); - void IncomingAclPacket(model::packets::LinkLayerPacketView incoming, - int8_t rssi); + void IncomingAclPacket(model::packets::LinkLayerPacketView incoming, int8_t rssi); void IncomingScoPacket(model::packets::LinkLayerPacketView incoming); void IncomingDisconnectPacket(model::packets::LinkLayerPacketView incoming); void IncomingEncryptConnection(model::packets::LinkLayerPacketView incoming); - void IncomingEncryptConnectionResponse( - model::packets::LinkLayerPacketView incoming); - void IncomingInquiryPacket(model::packets::LinkLayerPacketView incoming, - uint8_t rssi); - void IncomingInquiryResponsePacket( - model::packets::LinkLayerPacketView incoming); + void IncomingEncryptConnectionResponse(model::packets::LinkLayerPacketView incoming); + void IncomingInquiryPacket(model::packets::LinkLayerPacketView incoming, uint8_t rssi); + void IncomingInquiryResponsePacket(model::packets::LinkLayerPacketView incoming); void IncomingLmpPacket(model::packets::LinkLayerPacketView incoming); void IncomingLlcpPacket(model::packets::LinkLayerPacketView incoming); - void IncomingLeConnectedIsochronousPdu( - model::packets::LinkLayerPacketView incoming); - - void ScanIncomingLeLegacyAdvertisingPdu( - model::packets::LeLegacyAdvertisingPduView& pdu, uint8_t rssi); - void ScanIncomingLeExtendedAdvertisingPdu( - model::packets::LeExtendedAdvertisingPduView& pdu, uint8_t rssi); - void ConnectIncomingLeLegacyAdvertisingPdu( - model::packets::LeLegacyAdvertisingPduView& pdu); - void ConnectIncomingLeExtendedAdvertisingPdu( - model::packets::LeExtendedAdvertisingPduView& pdu); - - void IncomingLeLegacyAdvertisingPdu( - model::packets::LinkLayerPacketView incoming, uint8_t rssi); - void IncomingLeExtendedAdvertisingPdu( - model::packets::LinkLayerPacketView incoming, uint8_t rssi); - void IncomingLePeriodicAdvertisingPdu( - model::packets::LinkLayerPacketView incoming, uint8_t rssi); + void IncomingLeConnectedIsochronousPdu(model::packets::LinkLayerPacketView incoming); + + void ScanIncomingLeLegacyAdvertisingPdu(model::packets::LeLegacyAdvertisingPduView& pdu, + uint8_t rssi); + void ScanIncomingLeExtendedAdvertisingPdu(model::packets::LeExtendedAdvertisingPduView& pdu, + uint8_t rssi); + void ConnectIncomingLeLegacyAdvertisingPdu(model::packets::LeLegacyAdvertisingPduView& pdu); + void ConnectIncomingLeExtendedAdvertisingPdu(model::packets::LeExtendedAdvertisingPduView& pdu); + + void IncomingLeLegacyAdvertisingPdu(model::packets::LinkLayerPacketView incoming, uint8_t rssi); + void IncomingLeExtendedAdvertisingPdu(model::packets::LinkLayerPacketView incoming, uint8_t rssi); + void IncomingLePeriodicAdvertisingPdu(model::packets::LinkLayerPacketView incoming, uint8_t rssi); void IncomingLeConnectPacket(model::packets::LinkLayerPacketView incoming); - void IncomingLeConnectCompletePacket( - model::packets::LinkLayerPacketView incoming); - void IncomingLeConnectionParameterRequest( - model::packets::LinkLayerPacketView incoming); - void IncomingLeConnectionParameterUpdate( - model::packets::LinkLayerPacketView incoming); - void IncomingLeEncryptConnection( - model::packets::LinkLayerPacketView incoming); - void IncomingLeEncryptConnectionResponse( - model::packets::LinkLayerPacketView incoming); - void IncomingLeReadRemoteFeatures( - model::packets::LinkLayerPacketView incoming); - void IncomingLeReadRemoteFeaturesResponse( - model::packets::LinkLayerPacketView incoming); - - void ProcessIncomingLegacyScanRequest( - AddressWithType scanning_address, - AddressWithType resolved_scanning_address, - AddressWithType advertising_address); - void ProcessIncomingExtendedScanRequest( - ExtendedAdvertiser const& advertiser, AddressWithType scanning_address, - AddressWithType resolved_scanning_address, - AddressWithType advertising_address); - - bool ProcessIncomingLegacyConnectRequest( - model::packets::LeConnectView const& connect_ind); - bool ProcessIncomingExtendedConnectRequest( - ExtendedAdvertiser& advertiser, - model::packets::LeConnectView const& connect_ind); + void IncomingLeConnectCompletePacket(model::packets::LinkLayerPacketView incoming); + void IncomingLeConnectionParameterRequest(model::packets::LinkLayerPacketView incoming); + void IncomingLeConnectionParameterUpdate(model::packets::LinkLayerPacketView incoming); + void IncomingLeEncryptConnection(model::packets::LinkLayerPacketView incoming); + void IncomingLeEncryptConnectionResponse(model::packets::LinkLayerPacketView incoming); + void IncomingLeReadRemoteFeatures(model::packets::LinkLayerPacketView incoming); + void IncomingLeReadRemoteFeaturesResponse(model::packets::LinkLayerPacketView incoming); + + void ProcessIncomingLegacyScanRequest(AddressWithType scanning_address, + AddressWithType resolved_scanning_address, + AddressWithType advertising_address); + void ProcessIncomingExtendedScanRequest(ExtendedAdvertiser const& advertiser, + AddressWithType scanning_address, + AddressWithType resolved_scanning_address, + AddressWithType advertising_address); + + bool ProcessIncomingLegacyConnectRequest(model::packets::LeConnectView const& connect_ind); + bool ProcessIncomingExtendedConnectRequest(ExtendedAdvertiser& advertiser, + model::packets::LeConnectView const& connect_ind); void IncomingLeScanPacket(model::packets::LinkLayerPacketView incoming); - void IncomingLeScanResponsePacket( - model::packets::LinkLayerPacketView incoming, uint8_t rssi); + void IncomingLeScanResponsePacket(model::packets::LinkLayerPacketView incoming, uint8_t rssi); void IncomingPagePacket(model::packets::LinkLayerPacketView incoming); void IncomingPageRejectPacket(model::packets::LinkLayerPacketView incoming); void IncomingPageResponsePacket(model::packets::LinkLayerPacketView incoming); - void IncomingReadRemoteLmpFeatures( - model::packets::LinkLayerPacketView incoming); - void IncomingReadRemoteLmpFeaturesResponse( - model::packets::LinkLayerPacketView incoming); - void IncomingReadRemoteSupportedFeatures( - model::packets::LinkLayerPacketView incoming); - void IncomingReadRemoteSupportedFeaturesResponse( - model::packets::LinkLayerPacketView incoming); - void IncomingReadRemoteExtendedFeatures( - model::packets::LinkLayerPacketView incoming); - void IncomingReadRemoteExtendedFeaturesResponse( - model::packets::LinkLayerPacketView incoming); + void IncomingReadRemoteLmpFeatures(model::packets::LinkLayerPacketView incoming); + void IncomingReadRemoteLmpFeaturesResponse(model::packets::LinkLayerPacketView incoming); + void IncomingReadRemoteSupportedFeatures(model::packets::LinkLayerPacketView incoming); + void IncomingReadRemoteSupportedFeaturesResponse(model::packets::LinkLayerPacketView incoming); + void IncomingReadRemoteExtendedFeatures(model::packets::LinkLayerPacketView incoming); + void IncomingReadRemoteExtendedFeaturesResponse(model::packets::LinkLayerPacketView incoming); void IncomingReadRemoteVersion(model::packets::LinkLayerPacketView incoming); - void IncomingReadRemoteVersionResponse( - model::packets::LinkLayerPacketView incoming); + void IncomingReadRemoteVersionResponse(model::packets::LinkLayerPacketView incoming); void IncomingReadClockOffset(model::packets::LinkLayerPacketView incoming); - void IncomingReadClockOffsetResponse( - model::packets::LinkLayerPacketView incoming); + void IncomingReadClockOffsetResponse(model::packets::LinkLayerPacketView incoming); void IncomingRemoteNameRequest(model::packets::LinkLayerPacketView incoming); - void IncomingRemoteNameRequestResponse( - model::packets::LinkLayerPacketView incoming); + void IncomingRemoteNameRequestResponse(model::packets::LinkLayerPacketView incoming); - void IncomingScoConnectionRequest( - model::packets::LinkLayerPacketView incoming); - void IncomingScoConnectionResponse( - model::packets::LinkLayerPacketView incoming); + void IncomingScoConnectionRequest(model::packets::LinkLayerPacketView incoming); + void IncomingScoConnectionResponse(model::packets::LinkLayerPacketView incoming); void IncomingScoDisconnect(model::packets::LinkLayerPacketView incoming); void IncomingPingRequest(model::packets::LinkLayerPacketView incoming); @@ -757,7 +676,7 @@ class LinkLayerController { void IncomingLlPhyRsp(model::packets::LinkLayerPacketView incoming); void IncomingLlPhyUpdateInd(model::packets::LinkLayerPacketView incoming); - public: +public: bool IsEventUnmasked(bluetooth::hci::EventCode event) const; bool IsLeEventUnmasked(bluetooth::hci::SubeventCode subevent) const; @@ -770,9 +689,7 @@ class LinkLayerController { // TODO // The Page Scan Repetition Mode should be specific to an ACL connection or // a paging session. - PageScanRepetitionMode GetPageScanRepetitionMode() const { - return page_scan_repetition_mode_; - } + PageScanRepetitionMode GetPageScanRepetitionMode() const { return page_scan_repetition_mode_; } // TODO // The Encryption Key Size should be specific to an ACL connection. @@ -780,72 +697,47 @@ class LinkLayerController { bool GetScoFlowControlEnable() const { return sco_flow_control_enable_; } - AuthenticationEnable GetAuthenticationEnable() { - return authentication_enable_; - } + AuthenticationEnable GetAuthenticationEnable() { return authentication_enable_; } - std::array const& GetLocalName() { - return local_name_; - } + std::array const& GetLocalName() { return local_name_; } uint64_t GetLeSupportedFeatures() const { return properties_.le_features | le_host_supported_features_; } - uint16_t GetConnectionAcceptTimeout() const { - return connection_accept_timeout_; - } + uint16_t GetConnectionAcceptTimeout() const { return connection_accept_timeout_; } uint16_t GetVoiceSetting() const { return voice_setting_; } uint32_t GetClassOfDevice() const { return class_of_device_; } - uint8_t GetMaxLmpFeaturesPageNumber() { - return properties_.lmp_features.size() - 1; - } + uint8_t GetMaxLmpFeaturesPageNumber() { return properties_.lmp_features.size() - 1; } uint64_t GetLmpFeatures(uint8_t page_number = 0) { - return page_number == 1 ? host_supported_features_ - : properties_.lmp_features[page_number]; + return page_number == 1 ? host_supported_features_ : properties_.lmp_features[page_number]; } void SetLocalName(std::vector const& local_name); void SetLocalName(std::array const& local_name); - void SetExtendedInquiryResponse( - std::array const& extended_inquiry_response); - void SetExtendedInquiryResponse( - std::vector const& extended_inquiry_response); + void SetExtendedInquiryResponse(std::array const& extended_inquiry_response); + void SetExtendedInquiryResponse(std::vector const& extended_inquiry_response); - void SetClassOfDevice(uint32_t class_of_device) { - class_of_device_ = class_of_device; - } + void SetClassOfDevice(uint32_t class_of_device) { class_of_device_ = class_of_device; } - void SetAuthenticationEnable(AuthenticationEnable enable) { - authentication_enable_ = enable; - } + void SetAuthenticationEnable(AuthenticationEnable enable) { authentication_enable_ = enable; } - void SetScoFlowControlEnable(bool enable) { - sco_flow_control_enable_ = enable; - } - void SetVoiceSetting(uint16_t voice_setting) { - voice_setting_ = voice_setting; - } + void SetScoFlowControlEnable(bool enable) { sco_flow_control_enable_ = enable; } + void SetVoiceSetting(uint16_t voice_setting) { voice_setting_ = voice_setting; } void SetEventMask(uint64_t event_mask) { event_mask_ = event_mask; } - void SetEventMaskPage2(uint64_t event_mask) { - event_mask_page_2_ = event_mask; - } - void SetLeEventMask(uint64_t le_event_mask) { - le_event_mask_ = le_event_mask; - } + void SetEventMaskPage2(uint64_t event_mask) { event_mask_page_2_ = event_mask; } + void SetLeEventMask(uint64_t le_event_mask) { le_event_mask_ = le_event_mask; } void SetLeHostSupport(bool enable); void SetSecureSimplePairingSupport(bool enable); void SetSecureConnectionsSupport(bool enable); - void SetConnectionAcceptTimeout(uint16_t timeout) { - connection_accept_timeout_ = timeout; - } + void SetConnectionAcceptTimeout(uint16_t timeout) { connection_accept_timeout_ = timeout; } bool LegacyAdvertising() const { return legacy_advertising_in_use_; } bool ExtendedAdvertising() const { return extended_advertising_in_use_; } @@ -866,21 +758,17 @@ class LinkLayerController { return true; } - uint16_t GetLeSuggestedMaxTxOctets() const { - return le_suggested_max_tx_octets_; - } + uint16_t GetLeSuggestedMaxTxOctets() const { return le_suggested_max_tx_octets_; } uint16_t GetLeSuggestedMaxTxTime() const { return le_suggested_max_tx_time_; } void SetLeSuggestedMaxTxOctets(uint16_t max_tx_octets) { le_suggested_max_tx_octets_ = max_tx_octets; } - void SetLeSuggestedMaxTxTime(uint16_t max_tx_time) { - le_suggested_max_tx_time_ = max_tx_time; - } + void SetLeSuggestedMaxTxTime(uint16_t max_tx_time) { le_suggested_max_tx_time_ = max_tx_time; } TaskId StartScoStream(Address address); - private: +private: const Address& address_; const ControllerProperties& properties_; @@ -929,8 +817,7 @@ class LinkLayerController { uint16_t voice_setting_{0x0060}; // Authentication Enable (Vol 4, Part E § 6.16). - AuthenticationEnable authentication_enable_{ - AuthenticationEnable::NOT_REQUIRED}; + AuthenticationEnable authentication_enable_{AuthenticationEnable::NOT_REQUIRED}; // Default Link Policy Settings (Vol 4, Part E § 6.18). uint8_t default_link_policy_settings_{0x0000}; @@ -942,8 +829,7 @@ class LinkLayerController { std::array local_name_{}; // Extended Inquiry Response (Vol 4, Part E § 6.24). - std::array - extended_inquiry_response_{}; + std::array extended_inquiry_response_{}; // Class of Device (Vol 4, Part E § 6.26). uint32_t class_of_device_{0}; @@ -978,15 +864,14 @@ class LinkLayerController { // Callbacks to send packets back to the HCI. std::function)> send_acl_; - std::function)> - send_event_; + std::function)> send_event_; std::function)> send_sco_; std::function)> send_iso_; // Callback to send packets to remote devices. - std::function, - Phy::Type phy_type, int8_t tx_power)> - send_to_remote_; + std::function, Phy::Type phy_type, + int8_t tx_power)> + send_to_remote_; uint32_t oob_id_{1}; uint32_t key_id_{1}; @@ -1074,8 +959,7 @@ class LinkLayerController { model::packets::PhyType primary_scan_response_phy; model::packets::PhyType secondary_scan_response_phy; std::optional pending_scan_request{}; - std::optional - pending_scan_request_timeout{}; + std::optional pending_scan_request_timeout{}; // Time keeping std::optional timeout; @@ -1087,14 +971,11 @@ class LinkLayerController { bool IsEnabled() const { return scan_enable; } bool IsPacketInHistory(pdl::packet::slice const& packet) const { - return std::any_of( - history.begin(), history.end(), - [packet](pdl::packet::slice const& a) { return a == packet; }); + return std::any_of(history.begin(), history.end(), + [packet](pdl::packet::slice const& a) { return a == packet; }); } - void AddPacketToHistory(pdl::packet::slice packet) { - history.push_back(packet); - } + void AddPacketToHistory(pdl::packet::slice packet) { history.push_back(packet); } }; // Legacy and extended scanning properties. @@ -1187,36 +1068,29 @@ class LinkLayerController { std::optional page_; std::chrono::steady_clock::time_point last_inquiry_; - model::packets::InquiryType inquiry_mode_{ - model::packets::InquiryType::STANDARD}; + model::packets::InquiryType inquiry_mode_{model::packets::InquiryType::STANDARD}; TaskId inquiry_timer_task_id_ = kInvalidTaskId; uint64_t inquiry_lap_{}; uint8_t inquiry_max_responses_{}; - public: +public: // Type of scheduled tasks. class Task { - public: - Task(std::chrono::steady_clock::time_point time, - std::chrono::milliseconds period, TaskCallback callback, - TaskId task_id) + public: + Task(std::chrono::steady_clock::time_point time, std::chrono::milliseconds period, + TaskCallback callback, TaskId task_id) : time(time), periodic(true), period(period), callback(std::move(callback)), task_id(task_id) {} - Task(std::chrono::steady_clock::time_point time, TaskCallback callback, - TaskId task_id) - : time(time), - periodic(false), - callback(std::move(callback)), - task_id(task_id) {} + Task(std::chrono::steady_clock::time_point time, TaskCallback callback, TaskId task_id) + : time(time), periodic(false), callback(std::move(callback)), task_id(task_id) {} // Operators needed to be in a collection bool operator<(const Task& another) const { - return std::make_pair(time, task_id) < - std::make_pair(another.time, another.task_id); + return std::make_pair(time, task_id) < std::make_pair(another.time, another.task_id); } // These fields should no longer be public if the class ever becomes @@ -1228,7 +1102,7 @@ class LinkLayerController { TaskId task_id; }; - private: +private: // List currently pending tasks. std::set task_queue_{}; TaskId task_counter_{0}; diff --git a/tools/rootcanal/model/controller/sco_connection.cc b/tools/rootcanal/model/controller/sco_connection.cc index e0fb08702f5..0ecacf3f6f1 100644 --- a/tools/rootcanal/model/controller/sco_connection.cc +++ b/tools/rootcanal/model/controller/sco_connection.cc @@ -41,14 +41,13 @@ bool ScoConnectionParameters::IsExtended() const { return ((packet_type ^ edr) & ~legacy) != 0; } -std::optional ScoConnectionParameters::GetLinkParameters() - const { +std::optional ScoConnectionParameters::GetLinkParameters() const { // Coding conversion. uint8_t air_coding_to_air_mode[] = { - 0x02, // CVSD - 0x00, // u-law - 0x01, // A-law - 0x03, // transparent data + 0x02, // CVSD + 0x00, // u-law + 0x01, // A-law + 0x03, // transparent data }; // Prioritize eSCO connections. @@ -72,20 +71,16 @@ std::optional ScoConnectionParameters::GetLinkParameters() if (packet_type & (uint16_t)SynchronousPacketTypeBits::EV5_ALLOWED) { accepted_packets.push_back(Packet(180, 3)); } - if ((packet_type & (uint16_t)SynchronousPacketTypeBits::NO_2_EV3_ALLOWED) == - 0) { + if ((packet_type & (uint16_t)SynchronousPacketTypeBits::NO_2_EV3_ALLOWED) == 0) { accepted_packets.push_back(Packet(60, 1)); } - if ((packet_type & (uint16_t)SynchronousPacketTypeBits::NO_3_EV3_ALLOWED) == - 0) { + if ((packet_type & (uint16_t)SynchronousPacketTypeBits::NO_3_EV3_ALLOWED) == 0) { accepted_packets.push_back(Packet(360, 3)); } - if ((packet_type & (uint16_t)SynchronousPacketTypeBits::NO_2_EV5_ALLOWED) == - 0) { + if ((packet_type & (uint16_t)SynchronousPacketTypeBits::NO_2_EV5_ALLOWED) == 0) { accepted_packets.push_back(Packet(90, 1)); } - if ((packet_type & (uint16_t)SynchronousPacketTypeBits::NO_3_EV5_ALLOWED) == - 0) { + if ((packet_type & (uint16_t)SynchronousPacketTypeBits::NO_3_EV5_ALLOWED) == 0) { accepted_packets.push_back(Packet(540, 3)); } // Ignore empty bandwidths for now. @@ -112,14 +107,12 @@ std::optional ScoConnectionParameters::GetLinkParameters() continue; } - INFO("Testing combination {}/{} : {}/{}", tx.length, tx.slots, rx.length, - rx.slots); + INFO("Testing combination {}/{} : {}/{}", tx.length, tx.slots, rx.length, rx.slots); unsigned rx_max_interval = (1600 * rx.length) / receive_bandwidth; // Choose the best interval satisfying both. - unsigned transmission_interval = - std::min(tx_max_interval, rx_max_interval); + unsigned transmission_interval = std::min(tx_max_interval, rx_max_interval); transmission_interval -= transmission_interval % 2; transmission_interval = std::min(transmission_interval, 254U); @@ -127,22 +120,17 @@ std::optional ScoConnectionParameters::GetLinkParameters() // Compute retransmission window. unsigned retransmission_window = - retransmission_effort == - (uint8_t)RetransmissionEffort::NO_RETRANSMISSION - ? 0 - : retransmission_effort == - (uint8_t)RetransmissionEffort::OPTIMIZED_FOR_POWER - ? rx.slots + tx.slots - : retransmission_effort == - (uint8_t)RetransmissionEffort::OPTIMIZED_FOR_LINK_QUALITY - ? 2 * (rx.slots + tx.slots) - : 0; + retransmission_effort == (uint8_t)RetransmissionEffort::NO_RETRANSMISSION ? 0 + : retransmission_effort == (uint8_t)RetransmissionEffort::OPTIMIZED_FOR_POWER + ? rx.slots + tx.slots + : retransmission_effort == (uint8_t)RetransmissionEffort::OPTIMIZED_FOR_LINK_QUALITY + ? 2 * (rx.slots + tx.slots) + : 0; INFO("Retransmission window: {} slots", retransmission_window); // Compute transmission window and validate latency. - unsigned transmission_window = - tx.slots + rx.slots + retransmission_window; + unsigned transmission_window = tx.slots + rx.slots + retransmission_window; // Validate window. if (transmission_window > transmission_interval) { @@ -162,26 +150,23 @@ std::optional ScoConnectionParameters::GetLinkParameters() // We got a valid configuration. // Evaluate the actual bandwidth usage. - double bandwidth_usage = - (double)transmission_window / (double)transmission_interval; + double bandwidth_usage = (double)transmission_window / (double)transmission_interval; if (bandwidth_usage <= best_bandwidth_usage) { INFO("Valid combination!"); - uint16_t tx_packet_length = - (transmit_bandwidth * transmission_interval + 1600 - 1) / 1600; - uint16_t rx_packet_length = - (receive_bandwidth * transmission_interval + 1600 - 1) / 1600; + uint16_t tx_packet_length = (transmit_bandwidth * transmission_interval + 1600 - 1) / 1600; + uint16_t rx_packet_length = (receive_bandwidth * transmission_interval + 1600 - 1) / 1600; uint8_t air_coding = voice_setting & 0x3; best_bandwidth_usage = bandwidth_usage; best_parameters = { - (uint8_t)transmission_interval, - (uint8_t)retransmission_window, - rx_packet_length, - tx_packet_length, - air_coding_to_air_mode[air_coding], - true, + (uint8_t)transmission_interval, + (uint8_t)retransmission_window, + rx_packet_length, + tx_packet_length, + air_coding_to_air_mode[air_coding], + true, }; } } @@ -194,10 +179,8 @@ std::optional ScoConnectionParameters::GetLinkParameters() // Parameter negotiation for SCO connections: // Check packet types and validate bandwidth and latency requirements. - if (retransmission_effort == - (uint8_t)RetransmissionEffort::OPTIMIZED_FOR_POWER || - retransmission_effort == - (uint8_t)RetransmissionEffort::OPTIMIZED_FOR_LINK_QUALITY) { + if (retransmission_effort == (uint8_t)RetransmissionEffort::OPTIMIZED_FOR_POWER || + retransmission_effort == (uint8_t)RetransmissionEffort::OPTIMIZED_FOR_LINK_QUALITY) { WARNING("SCO Retransmission effort must be None or Don't care"); return {}; } @@ -221,26 +204,24 @@ std::optional ScoConnectionParameters::GetLinkParameters() } best_parameters = { - transmission_interval, - 0, - packet_length, - packet_length, - air_coding_to_air_mode[air_coding], - false, + transmission_interval, + 0, + packet_length, + packet_length, + air_coding_to_air_mode[air_coding], + false, }; return best_parameters; } -bool ScoConnection::NegotiateLinkParameters( - ScoConnectionParameters const& peer) { +bool ScoConnection::NegotiateLinkParameters(ScoConnectionParameters const& peer) { if (peer.transmit_bandwidth != 0xffff && peer.transmit_bandwidth != parameters_.receive_bandwidth) { WARNING("Transmit bandwidth requirements cannot be met"); return false; } - if (state_ == SCO_STATE_SENT_ESCO_CONNECTION_REQUEST && - peer.receive_bandwidth != 0xffff && + if (state_ == SCO_STATE_SENT_ESCO_CONNECTION_REQUEST && peer.receive_bandwidth != 0xffff && peer.receive_bandwidth != parameters_.transmit_bandwidth) { WARNING("Receive bandwidth requirements cannot be met"); return false; @@ -265,52 +246,40 @@ bool ScoConnection::NegotiateLinkParameters( return false; } - uint16_t max_latency = - peer.max_latency == 0xffff ? parameters_.max_latency - : parameters_.max_latency == 0xffff - ? peer.max_latency - : std::min(peer.max_latency, parameters_.max_latency); + uint16_t max_latency = peer.max_latency == 0xffff ? parameters_.max_latency + : parameters_.max_latency == 0xffff + ? peer.max_latency + : std::min(peer.max_latency, parameters_.max_latency); uint8_t retransmission_effort; if (state_ == SCO_STATE_SENT_SCO_CONNECTION_REQUEST) { retransmission_effort = (uint8_t)RetransmissionEffort::NO_RETRANSMISSION; } else if (peer.retransmission_effort == parameters_.retransmission_effort || - peer.retransmission_effort == - (uint8_t)RetransmissionEffort::DO_NOT_CARE) { + peer.retransmission_effort == (uint8_t)RetransmissionEffort::DO_NOT_CARE) { retransmission_effort = parameters_.retransmission_effort; - } else if (parameters_.retransmission_effort == - (uint8_t)RetransmissionEffort::DO_NOT_CARE) { + } else if (parameters_.retransmission_effort == (uint8_t)RetransmissionEffort::DO_NOT_CARE) { retransmission_effort = peer.retransmission_effort; - } else if (peer.retransmission_effort == - (uint8_t)RetransmissionEffort::NO_RETRANSMISSION || + } else if (peer.retransmission_effort == (uint8_t)RetransmissionEffort::NO_RETRANSMISSION || parameters_.retransmission_effort == - (uint8_t)RetransmissionEffort::NO_RETRANSMISSION) { + (uint8_t)RetransmissionEffort::NO_RETRANSMISSION) { WARNING("Retransmission effort requirements cannot be met"); - WARNING("Remote retransmission effort: 0x{:02x}", - parameters_.retransmission_effort); - WARNING("Local retransmission effort: 0x{:02x}", - peer.retransmission_effort); + WARNING("Remote retransmission effort: 0x{:02x}", parameters_.retransmission_effort); + WARNING("Local retransmission effort: 0x{:02x}", peer.retransmission_effort); return false; } else { retransmission_effort = (uint8_t)RetransmissionEffort::OPTIMIZED_FOR_POWER; } ScoConnectionParameters negotiated_parameters = { - parameters_.transmit_bandwidth, - parameters_.receive_bandwidth, - max_latency, - parameters_.voice_setting, - retransmission_effort, - packet_type}; + parameters_.transmit_bandwidth, parameters_.receive_bandwidth, max_latency, + parameters_.voice_setting, retransmission_effort, packet_type}; auto link_parameters = negotiated_parameters.GetLinkParameters(); if (link_parameters.has_value()) { link_parameters_ = link_parameters.value(); INFO("Negotiated link parameters for SCO connection:"); - INFO(" Transmission interval: {} slots", - link_parameters_.transmission_interval); - INFO(" Retransmission window: {} slots", - link_parameters_.retransmission_window); + INFO(" Transmission interval: {} slots", link_parameters_.transmission_interval); + INFO(" Retransmission window: {} slots", link_parameters_.retransmission_window); INFO(" RX packet length: {} bytes", link_parameters_.rx_packet_length); INFO(" TX packet length: {} bytes", link_parameters_.tx_packet_length); INFO(" Air mode: {}", link_parameters_.air_mode); diff --git a/tools/rootcanal/model/controller/sco_connection.h b/tools/rootcanal/model/controller/sco_connection.h index decd842e4e8..b086642dbec 100644 --- a/tools/rootcanal/model/controller/sco_connection.h +++ b/tools/rootcanal/model/controller/sco_connection.h @@ -82,9 +82,9 @@ enum ScoDatapath { }; class ScoConnection { - public: - ScoConnection(Address address, ScoConnectionParameters const& parameters, - ScoState state, ScoDatapath datapath, bool legacy) +public: + ScoConnection(Address address, ScoConnectionParameters const& parameters, ScoState state, + ScoDatapath datapath, bool legacy) : address_(address), parameters_(parameters), link_parameters_(), @@ -102,13 +102,9 @@ class ScoConnection { void StartStream(std::function startStream); void StopStream(std::function stopStream); - ScoConnectionParameters GetConnectionParameters() const { - return parameters_; - } + ScoConnectionParameters GetConnectionParameters() const { return parameters_; } ScoLinkParameters GetLinkParameters() const { return link_parameters_; } - void SetLinkParameters(ScoLinkParameters const& parameters) { - link_parameters_ = parameters; - } + void SetLinkParameters(ScoLinkParameters const& parameters) { link_parameters_ = parameters; } // Negotiate the connection parameters. // Update the local connection parameters with negotiated values. @@ -117,7 +113,7 @@ class ScoConnection { ScoDatapath GetDatapath() const { return datapath_; } - private: +private: Address address_; ScoConnectionParameters parameters_; ScoLinkParameters link_parameters_; diff --git a/tools/rootcanal/model/controller/vendor_commands/le_apcf.cc b/tools/rootcanal/model/controller/vendor_commands/le_apcf.cc index a28fcd73d0c..e4a774e96fb 100644 --- a/tools/rootcanal/model/controller/vendor_commands/le_apcf.cc +++ b/tools/rootcanal/model/controller/vendor_commands/le_apcf.cc @@ -28,50 +28,41 @@ namespace rootcanal::apcf { bool ApcfScanner::HasFilterIndex(uint8_t apcf_filter_index) const { - return std::any_of(std::begin(filters), std::end(filters), [&](auto it) { - return it.filter_index == apcf_filter_index; - }); + return std::any_of(std::begin(filters), std::end(filters), + [&](auto it) { return it.filter_index == apcf_filter_index; }); } void ApcfScanner::ClearFilterIndex(uint8_t apcf_filter_index) { broadcaster_address_filters.erase( - std::remove_if( - std::begin(broadcaster_address_filters), - std::end(broadcaster_address_filters), - [&](auto it) { return it.filter_index == apcf_filter_index; }), - std::end(broadcaster_address_filters)); + std::remove_if(std::begin(broadcaster_address_filters), + std::end(broadcaster_address_filters), + [&](auto it) { return it.filter_index == apcf_filter_index; }), + std::end(broadcaster_address_filters)); service_uuid_filters.erase( - std::remove_if( - std::begin(service_uuid_filters), std::end(service_uuid_filters), - [&](auto it) { return it.filter_index == apcf_filter_index; }), - std::end(service_uuid_filters)); + std::remove_if(std::begin(service_uuid_filters), std::end(service_uuid_filters), + [&](auto it) { return it.filter_index == apcf_filter_index; }), + std::end(service_uuid_filters)); service_solicitation_uuid_filters.erase( - std::remove_if( - std::begin(service_solicitation_uuid_filters), - std::end(service_solicitation_uuid_filters), - [&](auto it) { return it.filter_index == apcf_filter_index; }), - std::end(service_solicitation_uuid_filters)); + std::remove_if(std::begin(service_solicitation_uuid_filters), + std::end(service_solicitation_uuid_filters), + [&](auto it) { return it.filter_index == apcf_filter_index; }), + std::end(service_solicitation_uuid_filters)); local_name_filters.erase( - std::remove_if( - std::begin(local_name_filters), std::end(local_name_filters), - [&](auto it) { return it.filter_index == apcf_filter_index; }), - std::end(local_name_filters)); + std::remove_if(std::begin(local_name_filters), std::end(local_name_filters), + [&](auto it) { return it.filter_index == apcf_filter_index; }), + std::end(local_name_filters)); manufacturer_data_filters.erase( - std::remove_if( - std::begin(manufacturer_data_filters), - std::end(manufacturer_data_filters), - [&](auto it) { return it.filter_index == apcf_filter_index; }), - std::end(manufacturer_data_filters)); + std::remove_if(std::begin(manufacturer_data_filters), std::end(manufacturer_data_filters), + [&](auto it) { return it.filter_index == apcf_filter_index; }), + std::end(manufacturer_data_filters)); service_data_filters.erase( - std::remove_if( - std::begin(service_data_filters), std::end(service_data_filters), - [&](auto it) { return it.filter_index == apcf_filter_index; }), - std::end(service_data_filters)); + std::remove_if(std::begin(service_data_filters), std::end(service_data_filters), + [&](auto it) { return it.filter_index == apcf_filter_index; }), + std::end(service_data_filters)); ad_type_filters.erase( - std::remove_if( - std::begin(ad_type_filters), std::end(ad_type_filters), - [&](auto it) { return it.filter_index == apcf_filter_index; }), - std::end(ad_type_filters)); + std::remove_if(std::begin(ad_type_filters), std::end(ad_type_filters), + [&](auto it) { return it.filter_index == apcf_filter_index; }), + std::end(ad_type_filters)); } void ApcfScanner::Clear() { @@ -86,10 +77,8 @@ void ApcfScanner::Clear() { } template -ErrorCode ApcfScanner::UpdateFilterList(std::vector& filter_list, - size_t max_filter_list_size, - bluetooth::hci::ApcfAction action, - T filter) { +ErrorCode ApcfScanner::UpdateFilterList(std::vector& filter_list, size_t max_filter_list_size, + bluetooth::hci::ApcfAction action, T filter) { if (!HasFilterIndex(filter.filter_index)) { return ErrorCode::UNKNOWN_CONNECTION; } @@ -105,19 +94,17 @@ ErrorCode ApcfScanner::UpdateFilterList(std::vector& filter_list, } case ApcfAction::DELETE: { // Delete will delete the specified data in the specified filter. - filter_list.erase( - std::remove_if(std::begin(filter_list), std::end(filter_list), - [&](auto it) { return it == filter; }), - std::end(filter_list)); + filter_list.erase(std::remove_if(std::begin(filter_list), std::end(filter_list), + [&](auto it) { return it == filter; }), + std::end(filter_list)); return ErrorCode::SUCCESS; } case ApcfAction::CLEAR: { // Clear will clear all data in the specified filter. filter_list.erase( - std::remove_if( - std::begin(filter_list), std::end(filter_list), - [&](auto it) { return it.filter_index == filter.filter_index; }), - std::end(filter_list)); + std::remove_if(std::begin(filter_list), std::end(filter_list), + [&](auto it) { return it.filter_index == filter.filter_index; }), + std::end(filter_list)); return ErrorCode::SUCCESS; } default: @@ -127,8 +114,7 @@ ErrorCode ApcfScanner::UpdateFilterList(std::vector& filter_list, return ErrorCode::INVALID_HCI_COMMAND_PARAMETERS; } -bool operator==(BroadcasterAddressFilter const& lhs, - BroadcasterAddressFilter const& rhs) { +bool operator==(BroadcasterAddressFilter const& lhs, BroadcasterAddressFilter const& rhs) { return lhs.filter_index == rhs.filter_index && lhs.broadcaster_address == rhs.broadcaster_address && lhs.application_address_type == rhs.application_address_type; @@ -156,26 +142,24 @@ ErrorCode LinkLayerController::LeApcfEnable(bool apcf_enable) { } ErrorCode LinkLayerController::LeApcfAddFilteringParameters( - uint8_t apcf_filter_index, uint16_t apcf_feature_selection, - uint16_t apcf_list_logic_type, uint8_t apcf_filter_logic_type, - uint8_t rssi_high_thresh, bluetooth::hci::DeliveryMode delivery_mode, - uint16_t onfound_timeout, uint8_t onfound_timeout_cnt, - uint8_t rssi_low_thresh, uint16_t onlost_timeout, - uint16_t num_of_tracking_entries, uint8_t* apcf_available_spaces) { - *apcf_available_spaces = - properties_.le_apcf_filter_list_size - apcf_scanner_.filters.size(); - - if (apcf_scanner_.HasFilterIndex(apcf_filter_index)) { - INFO(id_, "apcf filter index {} already configured", apcf_filter_index); - return ErrorCode::INVALID_HCI_COMMAND_PARAMETERS; - } + uint8_t apcf_filter_index, uint16_t apcf_feature_selection, uint16_t apcf_list_logic_type, + uint8_t apcf_filter_logic_type, uint8_t rssi_high_thresh, + bluetooth::hci::DeliveryMode delivery_mode, uint16_t onfound_timeout, + uint8_t onfound_timeout_cnt, uint8_t rssi_low_thresh, uint16_t onlost_timeout, + uint16_t num_of_tracking_entries, uint8_t* apcf_available_spaces) { + *apcf_available_spaces = properties_.le_apcf_filter_list_size - apcf_scanner_.filters.size(); + + if (apcf_scanner_.HasFilterIndex(apcf_filter_index)) { + INFO(id_, "apcf filter index {} already configured", apcf_filter_index); + return ErrorCode::INVALID_HCI_COMMAND_PARAMETERS; + } - if (*apcf_available_spaces == 0) { - INFO(id_, "reached max number of apcf filters"); - return ErrorCode::MEMORY_CAPACITY_EXCEEDED; - } + if (*apcf_available_spaces == 0) { + INFO(id_, "reached max number of apcf filters"); + return ErrorCode::MEMORY_CAPACITY_EXCEEDED; + } - apcf_scanner_.filters.push_back(rootcanal::apcf::Filter{ + apcf_scanner_.filters.push_back(rootcanal::apcf::Filter{ .filter_index = apcf_filter_index, .feature_selection = apcf_feature_selection, .list_logic_type = apcf_list_logic_type, @@ -187,79 +171,74 @@ ErrorCode LinkLayerController::LeApcfAddFilteringParameters( .rssi_low_thresh = rssi_low_thresh, .onlost_timeout = onlost_timeout, .num_of_tracking_entries = num_of_tracking_entries, - }); + }); - *apcf_available_spaces -= 1; - return ErrorCode::SUCCESS; + *apcf_available_spaces -= 1; + return ErrorCode::SUCCESS; } -ErrorCode LinkLayerController::LeApcfDeleteFilteringParameters( - uint8_t apcf_filter_index, uint8_t* apcf_available_spaces) { - *apcf_available_spaces = - properties_.le_apcf_filter_list_size - apcf_scanner_.filters.size(); +ErrorCode LinkLayerController::LeApcfDeleteFilteringParameters(uint8_t apcf_filter_index, + uint8_t* apcf_available_spaces) { + *apcf_available_spaces = properties_.le_apcf_filter_list_size - apcf_scanner_.filters.size(); - if (!apcf_scanner_.HasFilterIndex(apcf_filter_index)) { - INFO(id_, "apcf filter index {} is not configured", apcf_filter_index); - return ErrorCode::UNKNOWN_CONNECTION; - } + if (!apcf_scanner_.HasFilterIndex(apcf_filter_index)) { + INFO(id_, "apcf filter index {} is not configured", apcf_filter_index); + return ErrorCode::UNKNOWN_CONNECTION; + } - apcf_scanner_.filters.erase( - std::remove_if( - std::begin(apcf_scanner_.filters), - std::end(apcf_scanner_.filters), - [&](auto it) { return it.filter_index == apcf_filter_index; }), + apcf_scanner_.filters.erase( + std::remove_if(std::begin(apcf_scanner_.filters), std::end(apcf_scanner_.filters), + [&](auto it) { return it.filter_index == apcf_filter_index; }), std::end(apcf_scanner_.filters)); - apcf_scanner_.ClearFilterIndex(apcf_filter_index); - *apcf_available_spaces += 1; - return ErrorCode::SUCCESS; + apcf_scanner_.ClearFilterIndex(apcf_filter_index); + *apcf_available_spaces += 1; + return ErrorCode::SUCCESS; } -ErrorCode LinkLayerController::LeApcfClearFilteringParameters( - uint8_t* apcf_available_spaces) { - apcf_scanner_.Clear(); - *apcf_available_spaces = properties_.le_apcf_filter_list_size; - return ErrorCode::SUCCESS; +ErrorCode LinkLayerController::LeApcfClearFilteringParameters(uint8_t* apcf_available_spaces) { + apcf_scanner_.Clear(); + *apcf_available_spaces = properties_.le_apcf_filter_list_size; + return ErrorCode::SUCCESS; } ErrorCode LinkLayerController::LeApcfBroadcasterAddress( - ApcfAction apcf_action, uint8_t apcf_filter_index, - bluetooth::hci::Address apcf_broadcaster_address, - bluetooth::hci::ApcfApplicationAddressType apcf_application_address_type, - uint8_t* apcf_available_spaces) { + ApcfAction apcf_action, uint8_t apcf_filter_index, + bluetooth::hci::Address apcf_broadcaster_address, + bluetooth::hci::ApcfApplicationAddressType apcf_application_address_type, + uint8_t* apcf_available_spaces) { ErrorCode status = apcf_scanner_.UpdateFilterList( - apcf_scanner_.broadcaster_address_filters, - properties_.le_apcf_broadcaster_address_filter_list_size, apcf_action, - rootcanal::apcf::BroadcasterAddressFilter{ - .filter_index = apcf_filter_index, - .broadcaster_address = apcf_broadcaster_address, - .application_address_type = apcf_application_address_type, - }); + apcf_scanner_.broadcaster_address_filters, + properties_.le_apcf_broadcaster_address_filter_list_size, apcf_action, + rootcanal::apcf::BroadcasterAddressFilter{ + .filter_index = apcf_filter_index, + .broadcaster_address = apcf_broadcaster_address, + .application_address_type = apcf_application_address_type, + }); - *apcf_available_spaces = - properties_.le_apcf_broadcaster_address_filter_list_size - - apcf_scanner_.broadcaster_address_filters.size(); + *apcf_available_spaces = properties_.le_apcf_broadcaster_address_filter_list_size - + apcf_scanner_.broadcaster_address_filters.size(); return status; } -ErrorCode LinkLayerController::LeApcfServiceUuid( - ApcfAction apcf_action, uint8_t apcf_filter_index, - std::vector apcf_uuid_data, uint8_t* apcf_available_spaces) { +ErrorCode LinkLayerController::LeApcfServiceUuid(ApcfAction apcf_action, uint8_t apcf_filter_index, + std::vector apcf_uuid_data, + uint8_t* apcf_available_spaces) { size_t uuid_data_size = apcf_uuid_data.size() / 2; std::vector uuid_data(std::begin(apcf_uuid_data), std::begin(apcf_uuid_data) + uuid_data_size); - std::vector uuid_data_mask( - std::begin(apcf_uuid_data) + uuid_data_size, std::end(apcf_uuid_data)); + std::vector uuid_data_mask(std::begin(apcf_uuid_data) + uuid_data_size, + std::end(apcf_uuid_data)); ErrorCode status = apcf_scanner_.UpdateFilterList( - apcf_scanner_.service_uuid_filters, - properties_.le_apcf_service_uuid_filter_list_size, apcf_action, - rootcanal::apcf::GapDataFilter{ - .filter_index = apcf_filter_index, - .gap_data = uuid_data, - .gap_data_mask = uuid_data_mask, - }); + apcf_scanner_.service_uuid_filters, properties_.le_apcf_service_uuid_filter_list_size, + apcf_action, + rootcanal::apcf::GapDataFilter{ + .filter_index = apcf_filter_index, + .gap_data = uuid_data, + .gap_data_mask = uuid_data_mask, + }); *apcf_available_spaces = properties_.le_apcf_service_uuid_filter_list_size - apcf_scanner_.service_uuid_filters.size(); @@ -267,104 +246,99 @@ ErrorCode LinkLayerController::LeApcfServiceUuid( return status; } -ErrorCode LinkLayerController::LeApcfServiceSolicitationUuid( - ApcfAction apcf_action, uint8_t apcf_filter_index, - std::vector apcf_uuid_data, uint8_t* apcf_available_spaces) { +ErrorCode LinkLayerController::LeApcfServiceSolicitationUuid(ApcfAction apcf_action, + uint8_t apcf_filter_index, + std::vector apcf_uuid_data, + uint8_t* apcf_available_spaces) { size_t uuid_data_size = apcf_uuid_data.size() / 2; std::vector uuid_data(std::begin(apcf_uuid_data), std::begin(apcf_uuid_data) + uuid_data_size); - std::vector uuid_data_mask( - std::begin(apcf_uuid_data) + uuid_data_size, std::end(apcf_uuid_data)); + std::vector uuid_data_mask(std::begin(apcf_uuid_data) + uuid_data_size, + std::end(apcf_uuid_data)); ErrorCode status = apcf_scanner_.UpdateFilterList( - apcf_scanner_.service_solicitation_uuid_filters, - properties_.le_apcf_service_solicitation_uuid_filter_list_size, - apcf_action, - rootcanal::apcf::GapDataFilter{ - .filter_index = apcf_filter_index, - .gap_data = uuid_data, - .gap_data_mask = uuid_data_mask, - }); + apcf_scanner_.service_solicitation_uuid_filters, + properties_.le_apcf_service_solicitation_uuid_filter_list_size, apcf_action, + rootcanal::apcf::GapDataFilter{ + .filter_index = apcf_filter_index, + .gap_data = uuid_data, + .gap_data_mask = uuid_data_mask, + }); - *apcf_available_spaces = - properties_.le_apcf_service_solicitation_uuid_filter_list_size - - apcf_scanner_.service_solicitation_uuid_filters.size(); + *apcf_available_spaces = properties_.le_apcf_service_solicitation_uuid_filter_list_size - + apcf_scanner_.service_solicitation_uuid_filters.size(); return status; } -ErrorCode LinkLayerController::LeApcfLocalName( - ApcfAction apcf_action, uint8_t apcf_filter_index, - std::vector apcf_local_name, uint8_t* apcf_available_spaces) { +ErrorCode LinkLayerController::LeApcfLocalName(ApcfAction apcf_action, uint8_t apcf_filter_index, + std::vector apcf_local_name, + uint8_t* apcf_available_spaces) { size_t local_name_size = apcf_local_name.size() / 2; - std::vector local_name( - std::begin(apcf_local_name), - std::begin(apcf_local_name) + local_name_size); - std::vector local_name_mask( - std::begin(apcf_local_name) + local_name_size, std::end(apcf_local_name)); - - ErrorCode status = apcf_scanner_.UpdateFilterList( - apcf_scanner_.local_name_filters, - properties_.le_apcf_local_name_filter_list_size, apcf_action, - rootcanal::apcf::GapDataFilter{ - .filter_index = apcf_filter_index, - .gap_data = local_name, - .gap_data_mask = local_name_mask, - }); + std::vector local_name(std::begin(apcf_local_name), + std::begin(apcf_local_name) + local_name_size); + std::vector local_name_mask(std::begin(apcf_local_name) + local_name_size, + std::end(apcf_local_name)); + + ErrorCode status = apcf_scanner_.UpdateFilterList(apcf_scanner_.local_name_filters, + properties_.le_apcf_local_name_filter_list_size, + apcf_action, + rootcanal::apcf::GapDataFilter{ + .filter_index = apcf_filter_index, + .gap_data = local_name, + .gap_data_mask = local_name_mask, + }); - *apcf_available_spaces = properties_.le_apcf_local_name_filter_list_size - - apcf_scanner_.local_name_filters.size(); + *apcf_available_spaces = + properties_.le_apcf_local_name_filter_list_size - apcf_scanner_.local_name_filters.size(); return status; } -ErrorCode LinkLayerController::LeApcfManufacturerData( - ApcfAction apcf_action, uint8_t apcf_filter_index, - std::vector apcf_manufacturer_data, - uint8_t* apcf_available_spaces) { +ErrorCode LinkLayerController::LeApcfManufacturerData(ApcfAction apcf_action, + uint8_t apcf_filter_index, + std::vector apcf_manufacturer_data, + uint8_t* apcf_available_spaces) { size_t manufacturer_data_size = apcf_manufacturer_data.size() / 2; std::vector manufacturer_data( - std::begin(apcf_manufacturer_data), - std::begin(apcf_manufacturer_data) + manufacturer_data_size); + std::begin(apcf_manufacturer_data), + std::begin(apcf_manufacturer_data) + manufacturer_data_size); std::vector manufacturer_data_mask( - std::begin(apcf_manufacturer_data) + manufacturer_data_size, - std::end(apcf_manufacturer_data)); + std::begin(apcf_manufacturer_data) + manufacturer_data_size, + std::end(apcf_manufacturer_data)); ErrorCode status = apcf_scanner_.UpdateFilterList( - apcf_scanner_.manufacturer_data_filters, - properties_.le_apcf_manufacturer_data_filter_list_size, apcf_action, - rootcanal::apcf::GapDataFilter{ - .filter_index = apcf_filter_index, - .gap_data = manufacturer_data, - .gap_data_mask = manufacturer_data_mask, - }); + apcf_scanner_.manufacturer_data_filters, + properties_.le_apcf_manufacturer_data_filter_list_size, apcf_action, + rootcanal::apcf::GapDataFilter{ + .filter_index = apcf_filter_index, + .gap_data = manufacturer_data, + .gap_data_mask = manufacturer_data_mask, + }); - *apcf_available_spaces = - properties_.le_apcf_manufacturer_data_filter_list_size - - apcf_scanner_.manufacturer_data_filters.size(); + *apcf_available_spaces = properties_.le_apcf_manufacturer_data_filter_list_size - + apcf_scanner_.manufacturer_data_filters.size(); return status; } -ErrorCode LinkLayerController::LeApcfServiceData( - ApcfAction apcf_action, uint8_t apcf_filter_index, - std::vector apcf_service_data, uint8_t* apcf_available_spaces) { +ErrorCode LinkLayerController::LeApcfServiceData(ApcfAction apcf_action, uint8_t apcf_filter_index, + std::vector apcf_service_data, + uint8_t* apcf_available_spaces) { size_t service_data_size = apcf_service_data.size() / 2; - std::vector service_data( - std::begin(apcf_service_data), - std::begin(apcf_service_data) + service_data_size); - std::vector service_data_mask( - std::begin(apcf_service_data) + service_data_size, - std::end(apcf_service_data)); + std::vector service_data(std::begin(apcf_service_data), + std::begin(apcf_service_data) + service_data_size); + std::vector service_data_mask(std::begin(apcf_service_data) + service_data_size, + std::end(apcf_service_data)); ErrorCode status = apcf_scanner_.UpdateFilterList( - apcf_scanner_.service_data_filters, - properties_.le_apcf_service_data_filter_list_size, apcf_action, - rootcanal::apcf::GapDataFilter{ - .filter_index = apcf_filter_index, - .gap_data = service_data, - .gap_data_mask = service_data_mask, - }); + apcf_scanner_.service_data_filters, properties_.le_apcf_service_data_filter_list_size, + apcf_action, + rootcanal::apcf::GapDataFilter{ + .filter_index = apcf_filter_index, + .gap_data = service_data, + .gap_data_mask = service_data_mask, + }); *apcf_available_spaces = properties_.le_apcf_service_data_filter_list_size - apcf_scanner_.service_data_filters.size(); @@ -372,22 +346,22 @@ ErrorCode LinkLayerController::LeApcfServiceData( return status; } -ErrorCode LinkLayerController::LeApcfAdTypeFilter( - ApcfAction apcf_action, uint8_t apcf_filter_index, uint8_t apcf_ad_type, - std::vector apcf_ad_data, std::vector apcf_ad_data_mask, - uint8_t* apcf_available_spaces) { +ErrorCode LinkLayerController::LeApcfAdTypeFilter(ApcfAction apcf_action, uint8_t apcf_filter_index, + uint8_t apcf_ad_type, + std::vector apcf_ad_data, + std::vector apcf_ad_data_mask, + uint8_t* apcf_available_spaces) { ErrorCode status = apcf_scanner_.UpdateFilterList( - apcf_scanner_.ad_type_filters, - properties_.le_apcf_ad_type_filter_list_size, apcf_action, - rootcanal::apcf::AdTypeFilter{ - .filter_index = apcf_filter_index, - .ad_type = apcf_ad_type, - .ad_data = std::move(apcf_ad_data), - .ad_data_mask = std::move(apcf_ad_data_mask), - }); + apcf_scanner_.ad_type_filters, properties_.le_apcf_ad_type_filter_list_size, apcf_action, + rootcanal::apcf::AdTypeFilter{ + .filter_index = apcf_filter_index, + .ad_type = apcf_ad_type, + .ad_data = std::move(apcf_ad_data), + .ad_data_mask = std::move(apcf_ad_data_mask), + }); - *apcf_available_spaces = properties_.le_apcf_ad_type_filter_list_size - - apcf_scanner_.ad_type_filters.size(); + *apcf_available_spaces = + properties_.le_apcf_ad_type_filter_list_size - apcf_scanner_.ad_type_filters.size(); return status; } diff --git a/tools/rootcanal/model/controller/vendor_commands/le_apcf.h b/tools/rootcanal/model/controller/vendor_commands/le_apcf.h index 5c6cce40c03..862ccfdb502 100644 --- a/tools/rootcanal/model/controller/vendor_commands/le_apcf.h +++ b/tools/rootcanal/model/controller/vendor_commands/le_apcf.h @@ -86,8 +86,7 @@ struct ApcfScanner { // Apply the requested modification to the selected // filter list. template - ErrorCode UpdateFilterList(std::vector& filter_list, - size_t max_filter_list_size, + ErrorCode UpdateFilterList(std::vector& filter_list, size_t max_filter_list_size, bluetooth::hci::ApcfAction action, T filter); }; diff --git a/tools/rootcanal/model/devices/baseband_sniffer.cc b/tools/rootcanal/model/devices/baseband_sniffer.cc index fd3f01887b5..dab58052c25 100644 --- a/tools/rootcanal/model/devices/baseband_sniffer.cc +++ b/tools/rootcanal/model/devices/baseband_sniffer.cc @@ -42,8 +42,7 @@ BaseBandSniffer::BaseBandSniffer(const std::string& filename) { output_.flush(); } -void BaseBandSniffer::AppendRecord( - std::unique_ptr packet) { +void BaseBandSniffer::AppendRecord(std::unique_ptr packet) { std::vector bytes = packet->SerializeToBytes(); pcap::WriteRecordHeader(output_, bytes.size()); output_.write((char*)bytes.data(), bytes.size()); @@ -52,12 +51,10 @@ void BaseBandSniffer::AppendRecord( static uint8_t ReverseByte(uint8_t b) { static uint8_t lookup[16] = { - [0b0000] = 0b0000, [0b0001] = 0b1000, [0b0010] = 0b0100, - [0b0011] = 0b1100, [0b0100] = 0b0010, [0b0101] = 0b1010, - [0b0110] = 0b0110, [0b0111] = 0b1110, [0b1000] = 0b0001, - [0b1001] = 0b1001, [0b1010] = 0b0101, [0b1011] = 0b1101, - [0b1100] = 0b0011, [0b1101] = 0b1011, [0b1110] = 0b0111, - [0b1111] = 0b1111, + [0b0000] = 0b0000, [0b0001] = 0b1000, [0b0010] = 0b0100, [0b0011] = 0b1100, + [0b0100] = 0b0010, [0b0101] = 0b1010, [0b0110] = 0b0110, [0b0111] = 0b1110, + [0b1000] = 0b0001, [0b1001] = 0b1001, [0b1010] = 0b0101, [0b1011] = 0b1101, + [0b1100] = 0b0011, [0b1101] = 0b1011, [0b1110] = 0b0111, [0b1111] = 0b1111, }; return (lookup[b & 0xF] << 4) | lookup[b >> 4]; @@ -80,41 +77,38 @@ static uint8_t HeaderErrorCheck(uint8_t uap, uint32_t data) { return value; } -static uint32_t BuildBtPacketHeader(uint8_t uap, uint8_t lt_addr, - uint8_t packet_type, bool flow, bool arqn, - bool seqn) { +static uint32_t BuildBtPacketHeader(uint8_t uap, uint8_t lt_addr, uint8_t packet_type, bool flow, + bool arqn, bool seqn) { // See Bluetooth Core, Vol2, Part B, 6.4 - uint32_t header = (lt_addr & 0x7) | ((packet_type & 0xF) << 3) | (flow << 7) | - (arqn << 8) | (seqn << 9); + uint32_t header = + (lt_addr & 0x7) | ((packet_type & 0xF) << 3) | (flow << 7) | (arqn << 8) | (seqn << 9); header |= (HeaderErrorCheck(uap, header) << 10); return header; } -void BaseBandSniffer::ReceiveLinkLayerPacket( - model::packets::LinkLayerPacketView packet, Phy::Type /*type*/, - int8_t /*rssi*/) { +void BaseBandSniffer::ReceiveLinkLayerPacket(model::packets::LinkLayerPacketView packet, + Phy::Type /*type*/, int8_t /*rssi*/) { auto packet_type = packet.GetType(); auto address = packet.GetSourceAddress(); // Bluetooth Core, Vol2, Part B, 1.2, Figure 1.5 - uint32_t lap = - address.data()[0] | (address.data()[1] << 8) | (address.data()[2] << 16); + uint32_t lap = address.data()[0] | (address.data()[1] << 8) | (address.data()[2] << 16); uint8_t uap = address.data()[3]; uint16_t nap = address.data()[4] | (address.data()[5] << 8); // http://www.whiterocker.com/bt/LINKTYPE_BLUETOOTH_BREDR_BB.html uint16_t flags = - /* BT Packet Header and BR or EDR Payload are de-whitened */ 0x0001 | - /* BR or EDR Payload is decrypted */ 0x0008 | - /* Reference LAP is valid and led to this packet being captured */ - 0x0010 | - /* BR or EDR Payload is present and follows this field */ 0x0020 | - /* Reference UAP field is valid for HEC and CRC checking */ 0x0080 | - /* CRC portion of the BR or EDR Payload was checked */ 0x0400 | - /* CRC portion of the BR or EDR Payload passed its check */ 0x0800; + /* BT Packet Header and BR or EDR Payload are de-whitened */ 0x0001 | + /* BR or EDR Payload is decrypted */ 0x0008 | + /* Reference LAP is valid and led to this packet being captured */ + 0x0010 | + /* BR or EDR Payload is present and follows this field */ 0x0020 | + /* Reference UAP field is valid for HEC and CRC checking */ 0x0080 | + /* CRC portion of the BR or EDR Payload was checked */ 0x0400 | + /* CRC portion of the BR or EDR Payload passed its check */ 0x0800; uint8_t lt_addr = 0; @@ -135,22 +129,20 @@ void BaseBandSniffer::ReceiveLinkLayerPacket( uint8_t bt_packet_type = 0b0010; // FHS AppendRecord(bredr_bb::FHSAclPacketBuilder::Create( - rf_channel, signal_power, noise_power, access_code_offenses, - corrected_header_bits, corrected_payload_bits, lower_address_part, - reference_lap, reference_uap, - BuildBtPacketHeader(uap, lt_addr, bt_packet_type, true, true, true), - flags, - 0, // parity_bits - lap, - 0, // eir - 0, // sr - 0, // sp - uap, nap, page_view.GetClassOfDevice(), - 1, // lt_addr - 0, // clk - 0, // page_scan_mode - 0 // crc - )); + rf_channel, signal_power, noise_power, access_code_offenses, corrected_header_bits, + corrected_payload_bits, lower_address_part, reference_lap, reference_uap, + BuildBtPacketHeader(uap, lt_addr, bt_packet_type, true, true, true), flags, + 0, // parity_bits + lap, + 0, // eir + 0, // sr + 0, // sp + uap, nap, page_view.GetClassOfDevice(), + 1, // lt_addr + 0, // clk + 0, // page_scan_mode + 0 // crc + )); } else if (packet_type == model::packets::PacketType::LMP) { auto lmp_view = model::packets::LmpView::Create(packet); ASSERT(lmp_view.IsValid()); @@ -158,16 +150,14 @@ void BaseBandSniffer::ReceiveLinkLayerPacket( uint8_t bt_packet_type = 0b0011; // DM1 AppendRecord(bredr_bb::DM1AclPacketBuilder::Create( - rf_channel, signal_power, noise_power, access_code_offenses, - corrected_header_bits, corrected_payload_bits, lower_address_part, - reference_lap, reference_uap, - BuildBtPacketHeader(uap, lt_addr, bt_packet_type, true, true, true), - flags, - 0x3, // llid - 1, // flow - std::move(lmp_bytes), - 0 // crc - )); + rf_channel, signal_power, noise_power, access_code_offenses, corrected_header_bits, + corrected_payload_bits, lower_address_part, reference_lap, reference_uap, + BuildBtPacketHeader(uap, lt_addr, bt_packet_type, true, true, true), flags, + 0x3, // llid + 1, // flow + std::move(lmp_bytes), + 0 // crc + )); } } diff --git a/tools/rootcanal/model/devices/baseband_sniffer.h b/tools/rootcanal/model/devices/baseband_sniffer.h index 96c2b7e84e0..09764794cb2 100644 --- a/tools/rootcanal/model/devices/baseband_sniffer.h +++ b/tools/rootcanal/model/devices/baseband_sniffer.h @@ -35,7 +35,7 @@ class BaseBandPacketBuilder; using ::bluetooth::hci::Address; class BaseBandSniffer : public Device { - public: +public: BaseBandSniffer(const std::string& filename); ~BaseBandSniffer() = default; @@ -44,15 +44,12 @@ class BaseBandSniffer : public Device { } // Return a string representation of the type of device. - virtual std::string GetTypeString() const override { - return "baseband_sniffer"; - } + virtual std::string GetTypeString() const override { return "baseband_sniffer"; } - virtual void ReceiveLinkLayerPacket( - model::packets::LinkLayerPacketView packet, Phy::Type type, - int8_t rssi) override; + virtual void ReceiveLinkLayerPacket(model::packets::LinkLayerPacketView packet, Phy::Type type, + int8_t rssi) override; - private: +private: void AppendRecord(std::unique_ptr packet); std::ofstream output_; }; diff --git a/tools/rootcanal/model/devices/beacon.cc b/tools/rootcanal/model/devices/beacon.cc index d61d44bbb77..1c7c14b0547 100644 --- a/tools/rootcanal/model/devices/beacon.cc +++ b/tools/rootcanal/model/devices/beacon.cc @@ -36,13 +36,11 @@ bool Beacon::registered_ = DeviceBoutique::Register("beacon", &Beacon::Create); Beacon::Beacon() : advertising_type_(LegacyAdvertisingType::ADV_NONCONN_IND), advertising_data_({ - 0x0F /* Length */, 0x09 /* TYPE_NAME_COMPLETE */, 'g', 'D', 'e', 'v', - 'i', 'c', 'e', '-', 'b', 'e', 'a', 'c', 'o', 'n', 0x02 /* Length */, - 0x01 /* TYPE_FLAG */, - 0x4 /* BREDR_NOT_SUPPORTED */ | 0x2 /* GENERAL_DISCOVERABLE */ + 0x0F /* Length */, 0x09 /* TYPE_NAME_COMPLETE */, 'g', 'D', 'e', 'v', 'i', 'c', 'e', + '-', 'b', 'e', 'a', 'c', 'o', 'n', 0x02 /* Length */, 0x01 /* TYPE_FLAG */, + 0x4 /* BREDR_NOT_SUPPORTED */ | 0x2 /* GENERAL_DISCOVERABLE */ }), - scan_response_data_( - {0x05 /* Length */, 0x08 /* TYPE_NAME_SHORT */, 'b', 'e', 'a', 'c'}), + scan_response_data_({0x05 /* Length */, 0x08 /* TYPE_NAME_SHORT */, 'b', 'e', 'a', 'c'}), advertising_interval_(1280ms) {} Beacon::Beacon(const std::vector& args) : Beacon() { @@ -59,27 +57,24 @@ void Beacon::Tick() { std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now(); if ((now - advertising_last_) >= advertising_interval_) { advertising_last_ = now; - SendLinkLayerPacket( - std::move(LeLegacyAdvertisingPduBuilder::Create( - address_, Address::kEmpty, AddressType::PUBLIC, AddressType::PUBLIC, - advertising_type_, - std::vector(advertising_data_.begin(), advertising_data_.end()))), - Phy::Type::LOW_ENERGY); + SendLinkLayerPacket(std::move(LeLegacyAdvertisingPduBuilder::Create( + address_, Address::kEmpty, AddressType::PUBLIC, AddressType::PUBLIC, + advertising_type_, + std::vector(advertising_data_.begin(), advertising_data_.end()))), + Phy::Type::LOW_ENERGY); } } -void Beacon::ReceiveLinkLayerPacket(LinkLayerPacketView packet, - Phy::Type /*type*/, int8_t /*rssi*/) { - if (packet.GetDestinationAddress() == address_ && - packet.GetType() == PacketType::LE_SCAN && +void Beacon::ReceiveLinkLayerPacket(LinkLayerPacketView packet, Phy::Type /*type*/, + int8_t /*rssi*/) { + if (packet.GetDestinationAddress() == address_ && packet.GetType() == PacketType::LE_SCAN && (advertising_type_ == LegacyAdvertisingType::ADV_IND || advertising_type_ == LegacyAdvertisingType::ADV_SCAN_IND)) { SendLinkLayerPacket( - std::move(LeScanResponseBuilder::Create( - address_, packet.GetSourceAddress(), AddressType::PUBLIC, - std::vector(scan_response_data_.begin(), - scan_response_data_.end()))), - Phy::Type::LOW_ENERGY); + std::move(LeScanResponseBuilder::Create( + address_, packet.GetSourceAddress(), AddressType::PUBLIC, + std::vector(scan_response_data_.begin(), scan_response_data_.end()))), + Phy::Type::LOW_ENERGY); } } diff --git a/tools/rootcanal/model/devices/beacon.h b/tools/rootcanal/model/devices/beacon.h index 6b33197dd7d..33bd7be25ce 100644 --- a/tools/rootcanal/model/devices/beacon.h +++ b/tools/rootcanal/model/devices/beacon.h @@ -32,7 +32,7 @@ namespace rootcanal { // Simple device that advertises with non-connectable advertising in general // discoverable mode, and responds to LE scan requests. class Beacon : public Device { - public: +public: Beacon(); Beacon(const std::vector& args); virtual ~Beacon() = default; @@ -44,18 +44,17 @@ class Beacon : public Device { virtual std::string GetTypeString() const override { return "beacon"; } virtual void Tick() override; - virtual void ReceiveLinkLayerPacket( - model::packets::LinkLayerPacketView packet, Phy::Type type, - int8_t rssi) override; + virtual void ReceiveLinkLayerPacket(model::packets::LinkLayerPacketView packet, Phy::Type type, + int8_t rssi) override; - protected: +protected: model::packets::LegacyAdvertisingType advertising_type_{}; std::array advertising_data_{}; std::array scan_response_data_{}; std::chrono::steady_clock::duration advertising_interval_{}; std::chrono::steady_clock::time_point advertising_last_{}; - private: +private: static bool registered_; }; diff --git a/tools/rootcanal/model/devices/beacon_swarm.cc b/tools/rootcanal/model/devices/beacon_swarm.cc index af4b7555c3b..b0013d9b2b7 100644 --- a/tools/rootcanal/model/devices/beacon_swarm.cc +++ b/tools/rootcanal/model/devices/beacon_swarm.cc @@ -29,42 +29,40 @@ namespace rootcanal { using namespace model::packets; using namespace std::chrono_literals; -bool BeaconSwarm::registered_ = - DeviceBoutique::Register("beacon_swarm", &BeaconSwarm::Create); +bool BeaconSwarm::registered_ = DeviceBoutique::Register("beacon_swarm", &BeaconSwarm::Create); BeaconSwarm::BeaconSwarm(const std::vector& args) : Beacon(args) { advertising_interval_ = 1280ms; advertising_type_ = LegacyAdvertisingType::ADV_NONCONN_IND; advertising_data_ = { - 0x15 /* Length */, - 0x09 /* TYPE_NAME_COMPLETE */, - 'g', - 'D', - 'e', - 'v', - 'i', - 'c', - 'e', - '-', - 'b', - 'e', - 'a', - 'c', - 'o', - 'n', - '_', - 's', - 'w', - 'a', - 'r', - 'm', - 0x02 /* Length */, - 0x01 /* TYPE_FLAG */, - 0x4 /* BREDR_NOT_SUPPORTED */ | 0x2 /* GENERAL_DISCOVERABLE */, + 0x15 /* Length */, + 0x09 /* TYPE_NAME_COMPLETE */, + 'g', + 'D', + 'e', + 'v', + 'i', + 'c', + 'e', + '-', + 'b', + 'e', + 'a', + 'c', + 'o', + 'n', + '_', + 's', + 'w', + 'a', + 'r', + 'm', + 0x02 /* Length */, + 0x01 /* TYPE_FLAG */, + 0x4 /* BREDR_NOT_SUPPORTED */ | 0x2 /* GENERAL_DISCOVERABLE */, }; - scan_response_data_ = { - 0x06 /* Length */, 0x08 /* TYPE_NAME_SHORT */, 'c', 'b', 'e', 'a', 'c'}; + scan_response_data_ = {0x06 /* Length */, 0x08 /* TYPE_NAME_SHORT */, 'c', 'b', 'e', 'a', 'c'}; } void BeaconSwarm::Tick() { diff --git a/tools/rootcanal/model/devices/beacon_swarm.h b/tools/rootcanal/model/devices/beacon_swarm.h index 69f6dd44bcd..70fe4928211 100644 --- a/tools/rootcanal/model/devices/beacon_swarm.h +++ b/tools/rootcanal/model/devices/beacon_swarm.h @@ -27,7 +27,7 @@ namespace rootcanal { // Pretend to be a lot of beacons by changing the advertising address. class BeaconSwarm : public Beacon { - public: +public: BeaconSwarm(const std::vector& args); virtual ~BeaconSwarm() = default; @@ -40,7 +40,7 @@ class BeaconSwarm : public Beacon { virtual void Tick() override; - private: +private: static bool registered_; }; diff --git a/tools/rootcanal/model/devices/device.cc b/tools/rootcanal/model/devices/device.cc index 9fadf9e3df0..59bfa7ffcfd 100644 --- a/tools/rootcanal/model/devices/device.cc +++ b/tools/rootcanal/model/devices/device.cc @@ -37,9 +37,7 @@ Device::Device() : id_(next_instance_id()) { ASSERT(Address::FromString("BB:BB:BB:BB:BB:AD", address_)); } -std::string Device::ToString() const { - return GetTypeString() + "@" + address_.ToString(); -} +std::string Device::ToString() const { return GetTypeString() + "@" + address_.ToString(); } void Device::Close() { if (close_callback_ != nullptr) { @@ -47,14 +45,13 @@ void Device::Close() { } } -void Device::SendLinkLayerPacket( - std::shared_ptr packet, - Phy::Type type, int8_t tx_power) { +void Device::SendLinkLayerPacket(std::shared_ptr packet, + Phy::Type type, int8_t tx_power) { SendLinkLayerPacket(packet->SerializeToBytes(), type, tx_power); } -void Device::SendLinkLayerPacket(std::vector const& packet, - Phy::Type type, int8_t tx_power) { +void Device::SendLinkLayerPacket(std::vector const& packet, Phy::Type type, + int8_t tx_power) { if (send_ll_ != nullptr) { send_ll_(packet, type, tx_power); } @@ -65,8 +62,7 @@ void Device::RegisterCloseCallback(std::function close_callback) { } void Device::RegisterLinkLayerChannel( - std::function const&, Phy::Type, int8_t)> - send_ll) { + std::function const&, Phy::Type, int8_t)> send_ll) { send_ll_ = send_ll; } diff --git a/tools/rootcanal/model/devices/device.h b/tools/rootcanal/model/devices/device.h index 3d5f258a295..96bccfc1e7a 100644 --- a/tools/rootcanal/model/devices/device.h +++ b/tools/rootcanal/model/devices/device.h @@ -33,7 +33,7 @@ using ::bluetooth::hci::Address; // Represent a Bluetooth Device // - Provide Get*() and Set*() functions for device attributes. class Device { - public: +public: // Unique device identifier. const uint32_t id_; @@ -55,24 +55,20 @@ class Device { virtual void Tick() {} virtual void Close(); - virtual void ReceiveLinkLayerPacket( - model::packets::LinkLayerPacketView /*packet*/, Phy::Type /*type*/, - int8_t /*rssi*/) {} + virtual void ReceiveLinkLayerPacket(model::packets::LinkLayerPacketView /*packet*/, + Phy::Type /*type*/, int8_t /*rssi*/) {} - void SendLinkLayerPacket( - std::shared_ptr packet, - Phy::Type type, int8_t tx_power = 0); + void SendLinkLayerPacket(std::shared_ptr packet, + Phy::Type type, int8_t tx_power = 0); - void SendLinkLayerPacket(std::vector const& packet, Phy::Type type, - int8_t tx_power = 0); + void SendLinkLayerPacket(std::vector const& packet, Phy::Type type, int8_t tx_power = 0); void RegisterLinkLayerChannel( - std::function const&, Phy::Type, int8_t)> - send_ll); + std::function const&, Phy::Type, int8_t)> send_ll); void RegisterCloseCallback(std::function close_callback); - protected: +protected: // Unique device address. Used as public device address for // Bluetooth activities. Address address_; diff --git a/tools/rootcanal/model/devices/hci_device.cc b/tools/rootcanal/model/devices/hci_device.cc index 9f0b30b5f31..5597fd05fb7 100644 --- a/tools/rootcanal/model/devices/hci_device.cc +++ b/tools/rootcanal/model/devices/hci_device.cc @@ -30,35 +30,34 @@ namespace rootcanal { HciDevice::HciDevice(std::shared_ptr transport, ControllerProperties const& properties) - : DualModeController(ControllerProperties(properties)), - transport_(transport) { + : DualModeController(ControllerProperties(properties)), transport_(transport) { link_layer_controller_.SetLocalName(std::vector({ - 'g', - 'D', - 'e', - 'v', - 'i', - 'c', - 'e', - '-', - 'H', - 'C', - 'I', + 'g', + 'D', + 'e', + 'v', + 'i', + 'c', + 'e', + '-', + 'H', + 'C', + 'I', })); link_layer_controller_.SetExtendedInquiryResponse(std::vector({ - 12, // Length - 9, // Type: Device Name - 'g', - 'D', - 'e', - 'v', - 'i', - 'c', - 'e', - '-', - 'h', - 'c', - 'i', + 12, // Length + 9, // Type: Device Name + 'g', + 'D', + 'e', + 'v', + 'i', + 'c', + 'e', + '-', + 'h', + 'c', + 'i', })); RegisterEventChannel([this](std::shared_ptr> packet) { @@ -75,30 +74,29 @@ HciDevice::HciDevice(std::shared_ptr transport, }); transport_->RegisterCallbacks( - [this](PacketType packet_type, - const std::shared_ptr> packet) { - switch (packet_type) { - case PacketType::COMMAND: - HandleCommand(packet); - break; - case PacketType::ACL: - HandleAcl(packet); - break; - case PacketType::SCO: - HandleSco(packet); - break; - case PacketType::ISO: - HandleIso(packet); - break; - default: - ASSERT(false); - break; - } - }, - [this]() { - INFO(id_, "HCI transport closed"); - Close(); - }); + [this](PacketType packet_type, const std::shared_ptr> packet) { + switch (packet_type) { + case PacketType::COMMAND: + HandleCommand(packet); + break; + case PacketType::ACL: + HandleAcl(packet); + break; + case PacketType::SCO: + HandleSco(packet); + break; + case PacketType::ISO: + HandleIso(packet); + break; + default: + ASSERT(false); + break; + } + }, + [this]() { + INFO(id_, "HCI transport closed"); + Close(); + }); } void HciDevice::Tick() { diff --git a/tools/rootcanal/model/devices/hci_device.h b/tools/rootcanal/model/devices/hci_device.h index 38be7fb7bb1..020e6af83c6 100644 --- a/tools/rootcanal/model/devices/hci_device.h +++ b/tools/rootcanal/model/devices/hci_device.h @@ -26,14 +26,12 @@ namespace rootcanal { class HciDevice : public DualModeController { - public: - HciDevice(std::shared_ptr transport, - ControllerProperties const& properties); +public: + HciDevice(std::shared_ptr transport, ControllerProperties const& properties); ~HciDevice() = default; - static std::shared_ptr Create( - std::shared_ptr transport, - ControllerProperties const& properties) { + static std::shared_ptr Create(std::shared_ptr transport, + ControllerProperties const& properties) { return std::make_shared(transport, properties); } @@ -43,7 +41,7 @@ class HciDevice : public DualModeController { void Close() override; - private: +private: std::shared_ptr transport_; }; diff --git a/tools/rootcanal/model/devices/link_layer_socket_device.cc b/tools/rootcanal/model/devices/link_layer_socket_device.cc index e61badf070b..fad0fbaffbb 100644 --- a/tools/rootcanal/model/devices/link_layer_socket_device.cc +++ b/tools/rootcanal/model/devices/link_layer_socket_device.cc @@ -34,16 +34,15 @@ using std::vector; namespace rootcanal { -LinkLayerSocketDevice::LinkLayerSocketDevice( - std::shared_ptr socket_fd, Phy::Type phy_type) +LinkLayerSocketDevice::LinkLayerSocketDevice(std::shared_ptr socket_fd, + Phy::Type phy_type) : socket_(socket_fd), phy_type_(phy_type), size_bytes_(std::make_shared>(kSizeBytes)) {} void LinkLayerSocketDevice::Tick() { if (receiving_size_) { - ssize_t bytes_received = - socket_->Recv(size_bytes_->data() + offset_, kSizeBytes); + ssize_t bytes_received = socket_->Recv(size_bytes_->data() + offset_, kSizeBytes); if (bytes_received <= 0) { if (errno == EAGAIN || errno == EWOULDBLOCK) { // Nothing available yet. @@ -65,8 +64,7 @@ void LinkLayerSocketDevice::Tick() { offset_ = 0; receiving_size_ = false; } - ssize_t bytes_received = - socket_->Recv(received_->data() + offset_, bytes_left_); + ssize_t bytes_received = socket_->Recv(received_->data() + offset_, bytes_left_); if (bytes_received <= 0) { if (errno == EAGAIN || errno == EWOULDBLOCK) { // Nothing available yet. @@ -95,9 +93,8 @@ void LinkLayerSocketDevice::Close() { Device::Close(); } -void LinkLayerSocketDevice::ReceiveLinkLayerPacket( - model::packets::LinkLayerPacketView packet, Phy::Type /*type*/, - int8_t /*rssi*/) { +void LinkLayerSocketDevice::ReceiveLinkLayerPacket(model::packets::LinkLayerPacketView packet, + Phy::Type /*type*/, int8_t /*rssi*/) { std::vector packet_bytes = packet.bytes().bytes(); std::vector size_bytes; pdl::packet::Builder::write_le(size_bytes, packet_bytes.size()); diff --git a/tools/rootcanal/model/devices/link_layer_socket_device.h b/tools/rootcanal/model/devices/link_layer_socket_device.h index b91263a479c..5d28e79db15 100644 --- a/tools/rootcanal/model/devices/link_layer_socket_device.h +++ b/tools/rootcanal/model/devices/link_layer_socket_device.h @@ -32,31 +32,27 @@ namespace rootcanal { using android::net::AsyncDataChannel; class LinkLayerSocketDevice : public Device { - public: - LinkLayerSocketDevice(std::shared_ptr socket_fd, - Phy::Type phy_type); +public: + LinkLayerSocketDevice(std::shared_ptr socket_fd, Phy::Type phy_type); LinkLayerSocketDevice(LinkLayerSocketDevice&& s) = default; virtual ~LinkLayerSocketDevice() = default; - static std::unique_ptr Create( - std::shared_ptr socket_fd, Phy::Type phy_type) { + static std::unique_ptr Create(std::shared_ptr socket_fd, + Phy::Type phy_type) { return std::make_unique(socket_fd, phy_type); } - virtual std::string GetTypeString() const override { - return "link_layer_socket_device"; - } + virtual std::string GetTypeString() const override { return "link_layer_socket_device"; } - virtual void ReceiveLinkLayerPacket( - model::packets::LinkLayerPacketView packet, Phy::Type type, - int8_t rssi) override; + virtual void ReceiveLinkLayerPacket(model::packets::LinkLayerPacketView packet, Phy::Type type, + int8_t rssi) override; virtual void Tick() override; virtual void Close() override; static constexpr size_t kSizeBytes = sizeof(uint32_t); - private: +private: std::shared_ptr socket_; Phy::Type phy_type_; bool receiving_size_{true}; diff --git a/tools/rootcanal/model/devices/scripted_beacon.cc b/tools/rootcanal/model/devices/scripted_beacon.cc index 9095d11401e..20e09064114 100644 --- a/tools/rootcanal/model/devices/scripted_beacon.cc +++ b/tools/rootcanal/model/devices/scripted_beacon.cc @@ -39,44 +39,43 @@ using namespace model::packets; using namespace std::chrono_literals; bool ScriptedBeacon::registered_ = - DeviceBoutique::Register("scripted_beacon", &ScriptedBeacon::Create); + DeviceBoutique::Register("scripted_beacon", &ScriptedBeacon::Create); ScriptedBeacon::ScriptedBeacon(const vector& args) : Beacon(args) { advertising_interval_ = 1280ms; advertising_type_ = LegacyAdvertisingType::ADV_SCAN_IND; advertising_data_ = { - 0x18 /* Length */, - 0x09 /* TYPE_NAME_CMPL */, - 'g', - 'D', - 'e', - 'v', - 'i', - 'c', - 'e', - '-', - 's', - 'c', - 'r', - 'i', - 'p', - 't', - 'e', - 'd', - '-', - 'b', - 'e', - 'a', - 'c', - 'o', - 'n', - 0x02 /* Length */, - 0x01 /* TYPE_FLAG */, - 0x4 /* BREDR_NOT_SPT */ | 0x2 /* GEN_DISC_FLAG */, + 0x18 /* Length */, + 0x09 /* TYPE_NAME_CMPL */, + 'g', + 'D', + 'e', + 'v', + 'i', + 'c', + 'e', + '-', + 's', + 'c', + 'r', + 'i', + 'p', + 't', + 'e', + 'd', + '-', + 'b', + 'e', + 'a', + 'c', + 'o', + 'n', + 0x02 /* Length */, + 0x01 /* TYPE_FLAG */, + 0x4 /* BREDR_NOT_SPT */ | 0x2 /* GEN_DISC_FLAG */, }; - scan_response_data_ = { - 0x05 /* Length */, 0x08 /* TYPE_NAME_SHORT */, 'g', 'b', 'e', 'a'}; + scan_response_data_ = {0x05 /* Length */, 0x08 /* TYPE_NAME_SHORT */, 'g', 'b', 'e', 'a'}; INFO("Scripted_beacon registered {}", registered_); @@ -85,9 +84,8 @@ ScriptedBeacon::ScriptedBeacon(const vector& args) : Beacon(args) { events_file_ = args[3]; set_state(PlaybackEvent::INITIALIZED); } else { - ERROR( - "Initialization failed, need playback and playback events file " - "arguments"); + ERROR("Initialization failed, need playback and playback events file " + "arguments"); } } @@ -95,8 +93,7 @@ bool has_time_elapsed(steady_clock::time_point time_point) { return steady_clock::now() > time_point; } -static void populate_event(PlaybackEvent* event, - PlaybackEvent::PlaybackEventType type) { +static void populate_event(PlaybackEvent* event, PlaybackEvent::PlaybackEventType type) { INFO("Adding event: {}", PlaybackEvent::PlaybackEventType_Name(type)); event->set_type(type); event->set_secs_since_epoch(system_clock::now().time_since_epoch().count()); @@ -108,8 +105,7 @@ void ScriptedBeacon::set_state(PlaybackEvent::PlaybackEventType state) { PlaybackEvent event; current_state_ = state; if (!events_ostream_.is_open()) { - events_ostream_.open(events_file_, - std::ios::out | std::ios::binary | std::ios::trunc); + events_ostream_.open(events_file_, std::ios::out | std::ios::binary | std::ios::trunc); if (!events_ostream_.is_open()) { INFO("Events file not opened yet, for event: {}", PlaybackEvent::PlaybackEventType_Name(state)); @@ -127,16 +123,14 @@ void ScriptedBeacon::Tick() { Beacon::Tick(); break; case PlaybackEvent::SCANNED_ONCE: - next_check_time_ = - steady_clock::now() + steady_clock::duration(std::chrono::seconds(1)); + next_check_time_ = steady_clock::now() + steady_clock::duration(std::chrono::seconds(1)); set_state(PlaybackEvent::WAITING_FOR_FILE); break; case PlaybackEvent::WAITING_FOR_FILE: if (!has_time_elapsed(next_check_time_)) { return; } - next_check_time_ = - steady_clock::now() + steady_clock::duration(std::chrono::seconds(1)); + next_check_time_ = steady_clock::now() + steady_clock::duration(std::chrono::seconds(1)); if (access(config_file_.c_str(), F_OK) == -1) { return; } @@ -168,9 +162,8 @@ void ScriptedBeacon::Tick() { case PlaybackEvent::PLAYBACK_STARTED: { while (has_time_elapsed(next_ad_.ad_time)) { auto ad = model::packets::LeLegacyAdvertisingPduBuilder::Create( - next_ad_.address, Address::kEmpty /* Destination */, - AddressType::RANDOM, AddressType::PUBLIC, - LegacyAdvertisingType::ADV_NONCONN_IND, next_ad_.ad); + next_ad_.address, Address::kEmpty /* Destination */, AddressType::RANDOM, + AddressType::PUBLIC, LegacyAdvertisingType::ADV_NONCONN_IND, next_ad_.ad); SendLinkLayerPacket(std::move(ad), Phy::Type::LOW_ENERGY); if (packet_num_ < ble_ad_list_.advertisements().size()) { get_next_advertisement(); @@ -179,10 +172,9 @@ void ScriptedBeacon::Tick() { if (events_ostream_.is_open()) { events_ostream_.close(); } - INFO( - "Completed Ble advertisement playback from file: {} with {} " - "packets", - config_file_, packet_num_); + INFO("Completed Ble advertisement playback from file: {} with {} " + "packets", + config_file_, packet_num_); break; } } @@ -194,29 +186,24 @@ void ScriptedBeacon::Tick() { } } -void ScriptedBeacon::ReceiveLinkLayerPacket( - model::packets::LinkLayerPacketView packet, Phy::Type /*type*/, - int8_t /*rssi*/) { +void ScriptedBeacon::ReceiveLinkLayerPacket(model::packets::LinkLayerPacketView packet, + Phy::Type /*type*/, int8_t /*rssi*/) { if (current_state_ == PlaybackEvent::INITIALIZED) { - if (packet.GetDestinationAddress() == address_ && - packet.GetType() == PacketType::LE_SCAN) { + if (packet.GetDestinationAddress() == address_ && packet.GetType() == PacketType::LE_SCAN) { set_state(PlaybackEvent::SCANNED_ONCE); SendLinkLayerPacket( - std::move(model::packets::LeScanResponseBuilder::Create( - address_, packet.GetSourceAddress(), AddressType::PUBLIC, - std::vector(scan_response_data_.begin(), - scan_response_data_.end()))), - Phy::Type::LOW_ENERGY); + std::move(model::packets::LeScanResponseBuilder::Create( + address_, packet.GetSourceAddress(), AddressType::PUBLIC, + std::vector(scan_response_data_.begin(), scan_response_data_.end()))), + Phy::Type::LOW_ENERGY); } } } void ScriptedBeacon::get_next_advertisement() { std::string payload = ble_ad_list_.advertisements(packet_num_).payload(); - std::string mac_address = - ble_ad_list_.advertisements(packet_num_).mac_address(); - uint32_t delay_before_send_ms = - ble_ad_list_.advertisements(packet_num_).delay_before_send_ms(); + std::string mac_address = ble_ad_list_.advertisements(packet_num_).mac_address(); + uint32_t delay_before_send_ms = ble_ad_list_.advertisements(packet_num_).delay_before_send_ms(); next_ad_.ad.assign(payload.begin(), payload.end()); if (Address::IsValidAddress(mac_address)) { // formatted string with colons like "12:34:56:78:9a:bc" @@ -228,8 +215,7 @@ void ScriptedBeacon::get_next_advertisement() { } else { Address::FromString("BA:D0:AD:BA:D0:AD", next_ad_.address); } - next_ad_.ad_time += - steady_clock::duration(std::chrono::milliseconds(delay_before_send_ms)); + next_ad_.ad_time += steady_clock::duration(std::chrono::milliseconds(delay_before_send_ms)); packet_num_++; } } // namespace rootcanal diff --git a/tools/rootcanal/model/devices/scripted_beacon.h b/tools/rootcanal/model/devices/scripted_beacon.h index 4d62ac65273..05ad079efb1 100644 --- a/tools/rootcanal/model/devices/scripted_beacon.h +++ b/tools/rootcanal/model/devices/scripted_beacon.h @@ -23,13 +23,12 @@ #include "model/devices/beacon.h" #include "model/devices/scripted_beacon_ble_payload.pb.h" -using android::bluetooth::rootcanal::model::devices::ScriptedBeaconBleAdProto:: - PlaybackEvent; +using android::bluetooth::rootcanal::model::devices::ScriptedBeaconBleAdProto::PlaybackEvent; namespace rootcanal { // Pretend to be a lot of beacons by advertising from a file. class ScriptedBeacon : public Beacon { - public: +public: ScriptedBeacon(const std::vector& args); virtual ~ScriptedBeacon() = default; @@ -38,19 +37,15 @@ class ScriptedBeacon : public Beacon { } // Return a string representation of the type of device. - virtual std::string GetTypeString() const override { - return "scripted_beacon"; - } + virtual std::string GetTypeString() const override { return "scripted_beacon"; } - virtual std::string ToString() const override { - return "scripted_beacon " + config_file_; - } + virtual std::string ToString() const override { return "scripted_beacon " + config_file_; } void Tick() override; - void ReceiveLinkLayerPacket(model::packets::LinkLayerPacketView packet_view, - Phy::Type type, int8_t rssi) override; + void ReceiveLinkLayerPacket(model::packets::LinkLayerPacketView packet_view, Phy::Type type, + int8_t rssi) override; - private: +private: static bool registered_; std::string config_file_{}; std::string events_file_{}; @@ -69,7 +64,7 @@ class ScriptedBeacon : public Beacon { int packet_num_{0}; PlaybackEvent::PlaybackEventType current_state_{PlaybackEvent::UNKNOWN}; std::chrono::steady_clock::time_point next_check_time_{}; - android::bluetooth::rootcanal::model::devices::ScriptedBeaconBleAdProto:: - BleAdvertisementList ble_ad_list_; + android::bluetooth::rootcanal::model::devices::ScriptedBeaconBleAdProto::BleAdvertisementList + ble_ad_list_; }; } // namespace rootcanal diff --git a/tools/rootcanal/model/devices/sniffer.cc b/tools/rootcanal/model/devices/sniffer.cc index 793b078b52f..02f5766ead3 100644 --- a/tools/rootcanal/model/devices/sniffer.cc +++ b/tools/rootcanal/model/devices/sniffer.cc @@ -28,8 +28,7 @@ namespace rootcanal { -bool Sniffer::registered_ = - DeviceBoutique::Register("sniffer", &Sniffer::Create); +bool Sniffer::registered_ = DeviceBoutique::Register("sniffer", &Sniffer::Create); Sniffer::Sniffer(const std::vector& args) { if (args.size() >= 2) { @@ -37,8 +36,8 @@ Sniffer::Sniffer(const std::vector& args) { } } -void Sniffer::ReceiveLinkLayerPacket(model::packets::LinkLayerPacketView packet, - Phy::Type /*type*/, int8_t /*rssi*/) { +void Sniffer::ReceiveLinkLayerPacket(model::packets::LinkLayerPacketView packet, Phy::Type /*type*/, + int8_t /*rssi*/) { Address source = packet.GetSourceAddress(); Address dest = packet.GetDestinationAddress(); model::packets::PacketType packet_type = packet.GetType(); @@ -49,8 +48,7 @@ void Sniffer::ReceiveLinkLayerPacket(model::packets::LinkLayerPacketView packet, return; } - INFO("{} {} -> {} (Type {})", - (match_source ? (match_dest ? "<->" : "<--") : "-->"), source, dest, + INFO("{} {} -> {} (Type {})", (match_source ? (match_dest ? "<->" : "<--") : "-->"), source, dest, model::packets::PacketTypeText(packet_type)); } diff --git a/tools/rootcanal/model/devices/sniffer.h b/tools/rootcanal/model/devices/sniffer.h index 60bee3e9c29..1f04d295c92 100644 --- a/tools/rootcanal/model/devices/sniffer.h +++ b/tools/rootcanal/model/devices/sniffer.h @@ -26,7 +26,7 @@ namespace rootcanal { class Sniffer : public Device { - public: +public: Sniffer(const std::vector& args); ~Sniffer() = default; @@ -36,11 +36,10 @@ class Sniffer : public Device { virtual std::string GetTypeString() const override { return "sniffer"; } - virtual void ReceiveLinkLayerPacket( - model::packets::LinkLayerPacketView packet, Phy::Type type, - int8_t rssi) override; + virtual void ReceiveLinkLayerPacket(model::packets::LinkLayerPacketView packet, Phy::Type type, + int8_t rssi) override; - private: +private: static bool registered_; }; diff --git a/tools/rootcanal/model/hci/h4_data_channel_packetizer.cc b/tools/rootcanal/model/hci/h4_data_channel_packetizer.cc index 15e6f3d63c9..aa8edbe0adf 100644 --- a/tools/rootcanal/model/hci/h4_data_channel_packetizer.cc +++ b/tools/rootcanal/model/hci/h4_data_channel_packetizer.cc @@ -33,16 +33,14 @@ namespace rootcanal { H4DataChannelPacketizer::H4DataChannelPacketizer( - std::shared_ptr socket, PacketReadCallback command_cb, - PacketReadCallback event_cb, PacketReadCallback acl_cb, - PacketReadCallback sco_cb, PacketReadCallback iso_cb, - ClientDisconnectCallback disconnect_cb) + std::shared_ptr socket, PacketReadCallback command_cb, + PacketReadCallback event_cb, PacketReadCallback acl_cb, PacketReadCallback sco_cb, + PacketReadCallback iso_cb, ClientDisconnectCallback disconnect_cb) : uart_socket_(socket), h4_parser_(command_cb, event_cb, acl_cb, sco_cb, iso_cb, true), disconnect_cb_(std::move(disconnect_cb)) {} -size_t H4DataChannelPacketizer::Send(uint8_t type, const uint8_t* data, - size_t length) { +size_t H4DataChannelPacketizer::Send(uint8_t type, const uint8_t* data, size_t length) { ssize_t ret = uart_socket_->Send(&type, sizeof(type)); if (ret == -1) { ERROR("Error writing to UART ({})", strerror(errno)); @@ -56,15 +54,12 @@ size_t H4DataChannelPacketizer::Send(uint8_t type, const uint8_t* data, to_be_written += ret; if (to_be_written != length + sizeof(type)) { - ERROR("{} / {} bytes written - something went wrong...", to_be_written, - length + sizeof(type)); + ERROR("{} / {} bytes written - something went wrong...", to_be_written, length + sizeof(type)); } return to_be_written; } -void H4DataChannelPacketizer::OnDataReady( - std::shared_ptr socket) { - +void H4DataChannelPacketizer::OnDataReady(std::shared_ptr socket) { // Continue reading from the async data channel as long as bytes // are available to read. Otherwise this limits the number of HCI // packets parsed to one every 3 ticks. @@ -90,8 +85,7 @@ void H4DataChannelPacketizer::OnDataReady( disconnect_cb_(); return; } - FATAL("Read error in {}: {}", fmt::underlying(h4_parser_.CurrentState()), - strerror(errno)); + FATAL("Read error in {}: {}", fmt::underlying(h4_parser_.CurrentState()), strerror(errno)); } h4_parser_.Consume(buffer.data(), bytes_read); } diff --git a/tools/rootcanal/model/hci/h4_data_channel_packetizer.h b/tools/rootcanal/model/hci/h4_data_channel_packetizer.h index 272373c26eb..f32b64360bd 100644 --- a/tools/rootcanal/model/hci/h4_data_channel_packetizer.h +++ b/tools/rootcanal/model/hci/h4_data_channel_packetizer.h @@ -31,19 +31,17 @@ using android::net::AsyncDataChannel; // A socket based H4DataChannelPacketizer. Call OnDataReady whenever // data can be read from the socket. class H4DataChannelPacketizer { - public: - H4DataChannelPacketizer(std::shared_ptr socket, - PacketReadCallback command_cb, - PacketReadCallback event_cb, - PacketReadCallback acl_cb, PacketReadCallback sco_cb, - PacketReadCallback iso_cb, +public: + H4DataChannelPacketizer(std::shared_ptr socket, PacketReadCallback command_cb, + PacketReadCallback event_cb, PacketReadCallback acl_cb, + PacketReadCallback sco_cb, PacketReadCallback iso_cb, ClientDisconnectCallback disconnect_cb); size_t Send(uint8_t type, const uint8_t* data, size_t length); void OnDataReady(std::shared_ptr socket); - private: +private: std::shared_ptr uart_socket_; H4Parser h4_parser_; diff --git a/tools/rootcanal/model/hci/h4_parser.cc b/tools/rootcanal/model/hci/h4_parser.cc index b84ad1f6308..c3aa76ddd28 100644 --- a/tools/rootcanal/model/hci/h4_parser.cc +++ b/tools/rootcanal/model/hci/h4_parser.cc @@ -34,17 +34,15 @@ void H4Parser::Reset() { packet_type_ = 0; } -size_t H4Parser::HciGetPacketLengthForType(PacketType type, - const uint8_t* preamble) { - static const size_t - packet_length_offset[static_cast(PacketType::ISO) + 1] = { +size_t H4Parser::HciGetPacketLengthForType(PacketType type, const uint8_t* preamble) { + static const size_t packet_length_offset[static_cast(PacketType::ISO) + 1] = { 0, H4Parser::COMMAND_LENGTH_OFFSET, H4Parser::ACL_LENGTH_OFFSET, H4Parser::SCO_LENGTH_OFFSET, H4Parser::EVENT_LENGTH_OFFSET, H4Parser::ISO_LENGTH_OFFSET, - }; + }; size_t offset = packet_length_offset[static_cast(type)]; size_t size = preamble[offset]; @@ -58,8 +56,8 @@ size_t H4Parser::HciGetPacketLengthForType(PacketType type, } H4Parser::H4Parser(PacketReadCallback command_cb, PacketReadCallback event_cb, - PacketReadCallback acl_cb, PacketReadCallback sco_cb, - PacketReadCallback iso_cb, bool enable_recovery_state) + PacketReadCallback acl_cb, PacketReadCallback sco_cb, PacketReadCallback iso_cb, + bool enable_recovery_state) : command_cb_(std::move(command_cb)), event_cb_(std::move(event_cb)), acl_cb_(std::move(acl_cb)), @@ -109,19 +107,17 @@ bool H4Parser::Consume(const uint8_t* buffer, int32_t bytes_read) { return false; } if ((uint32_t)bytes_read > BytesRequested()) { - FATAL("More bytes read ({}) than expected ({})!", bytes_read, - bytes_to_read); + FATAL("More bytes read ({}) than expected ({})!", bytes_read, bytes_to_read); } - static const size_t preamble_size[static_cast(PacketType::ISO) + 1] = - { + static const size_t preamble_size[static_cast(PacketType::ISO) + 1] = { 0, H4Parser::COMMAND_PREAMBLE_SIZE, H4Parser::ACL_PREAMBLE_SIZE, H4Parser::SCO_PREAMBLE_SIZE, H4Parser::EVENT_PREAMBLE_SIZE, H4Parser::ISO_PREAMBLE_SIZE, - }; + }; switch (state_) { case HCI_TYPE: // bytes_read >= 1 @@ -167,16 +163,13 @@ bool H4Parser::Consume(const uint8_t* buffer, int32_t bytes_read) { switch (state_) { case HCI_TYPE: hci_packet_type_ = static_cast(packet_type_); - if (hci_packet_type_ != PacketType::ACL && - hci_packet_type_ != PacketType::SCO && - hci_packet_type_ != PacketType::COMMAND && - hci_packet_type_ != PacketType::EVENT && + if (hci_packet_type_ != PacketType::ACL && hci_packet_type_ != PacketType::SCO && + hci_packet_type_ != PacketType::COMMAND && hci_packet_type_ != PacketType::EVENT && hci_packet_type_ != PacketType::ISO) { if (!enable_recovery_state_) { FATAL("Received invalid packet type 0x{:x}", packet_type_); } - ERROR("Received invalid packet type 0x{:x}, entering recovery state", - packet_type_); + ERROR("Received invalid packet type 0x{:x}, entering recovery state", packet_type_); state_ = HCI_RECOVERY; hci_packet_type_ = PacketType::COMMAND; bytes_wanted_ = 1; @@ -187,8 +180,7 @@ bool H4Parser::Consume(const uint8_t* buffer, int32_t bytes_read) { break; case HCI_PREAMBLE: if (bytes_wanted_ == 0) { - size_t payload_size = - HciGetPacketLengthForType(hci_packet_type_, packet_.data()); + size_t payload_size = HciGetPacketLengthForType(hci_packet_type_, packet_.data()); if (payload_size == 0) { OnPacketReady(); state_ = HCI_TYPE; diff --git a/tools/rootcanal/model/hci/h4_parser.h b/tools/rootcanal/model/hci/h4_parser.h index e7a63636fa8..a10d0b2023c 100644 --- a/tools/rootcanal/model/hci/h4_parser.h +++ b/tools/rootcanal/model/hci/h4_parser.h @@ -44,12 +44,12 @@ using ClientDisconnectCallback = std::function; // The parser will invoke the proper callbacks once a packet has been parsed. // The parser keeps internal state and is not thread safe. class H4Parser { - public: +public: enum State { HCI_TYPE, HCI_PREAMBLE, HCI_PAYLOAD, HCI_RECOVERY }; - H4Parser(PacketReadCallback command_cb, PacketReadCallback event_cb, - PacketReadCallback acl_cb, PacketReadCallback sco_cb, - PacketReadCallback iso_cb, bool enable_recovery_state = false); + H4Parser(PacketReadCallback command_cb, PacketReadCallback event_cb, PacketReadCallback acl_cb, + PacketReadCallback sco_cb, PacketReadCallback iso_cb, + bool enable_recovery_state = false); // Consumes the given number of bytes, returns true on success. bool Consume(const uint8_t* buffer, int32_t bytes); @@ -60,12 +60,12 @@ class H4Parser { // Resets the parser to the empty, initial state. void Reset(); - State CurrentState() { return state_; }; + State CurrentState() { return state_; } void EnableRecovery() { enable_recovery_state_ = true; } void DisableRecovery() { enable_recovery_state_ = false; } - private: +private: void OnPacketReady(); // 2 bytes for opcode, 1 byte for parameter length (Volume 2, Part E, 5.4.1) @@ -94,8 +94,7 @@ class H4Parser { PacketReadCallback sco_cb_; PacketReadCallback iso_cb_; - static size_t HciGetPacketLengthForType(PacketType type, - const uint8_t* preamble); + static size_t HciGetPacketLengthForType(PacketType type, const uint8_t* preamble); PacketType hci_packet_type_{PacketType::UNKNOWN}; @@ -106,8 +105,7 @@ class H4Parser { bool enable_recovery_state_{false}; }; -inline std::ostream& operator<<(std::ostream& os, - H4Parser::State const& state_) { +inline std::ostream& operator<<(std::ostream& os, H4Parser::State const& state_) { switch (state_) { case H4Parser::State::HCI_TYPE: os << "HCI_TYPE"; diff --git a/tools/rootcanal/model/hci/hci_sniffer.cc b/tools/rootcanal/model/hci/hci_sniffer.cc index ea3e2cbeac3..9a0509daa17 100644 --- a/tools/rootcanal/model/hci/hci_sniffer.cc +++ b/tools/rootcanal/model/hci/hci_sniffer.cc @@ -28,9 +28,7 @@ HciSniffer::HciSniffer(std::shared_ptr transport, SetOutputStream(outputStream); } -void HciSniffer::SetPcapFilter(std::shared_ptr filter) { - filter_ = filter; -} +void HciSniffer::SetPcapFilter(std::shared_ptr filter) { filter_ = filter; } void HciSniffer::SetOutputStream(std::shared_ptr outputStream) { output_ = outputStream; @@ -42,8 +40,7 @@ void HciSniffer::SetOutputStream(std::shared_ptr outputStream) { } } -void HciSniffer::AppendRecord(PacketDirection packet_direction, - PacketType packet_type, +void HciSniffer::AppendRecord(PacketDirection packet_direction, PacketType packet_type, const std::vector& packet) { if (output_ == nullptr) { return; @@ -62,8 +59,7 @@ void HciSniffer::AppendRecord(PacketDirection packet_direction, // Apply the PCAP filter when provided. if (filter_ != nullptr) { - std::vector filtered_packet = - filter_->FilterHciPacket(packet, idc); + std::vector filtered_packet = filter_->FilterHciPacket(packet, idc); output_->write((char*)filtered_packet.data(), filtered_packet.size()); } else { output_->write((char*)packet.data(), packet.size()); @@ -73,16 +69,14 @@ void HciSniffer::AppendRecord(PacketDirection packet_direction, output_->flush(); } -void HciSniffer::RegisterCallbacks(PacketCallback packet_callback, - CloseCallback close_callback) { +void HciSniffer::RegisterCallbacks(PacketCallback packet_callback, CloseCallback close_callback) { transport_->RegisterCallbacks( - [this, packet_callback]( - PacketType packet_type, - const std::shared_ptr> packet) { - AppendRecord(PacketDirection::HOST_TO_CONTROLLER, packet_type, *packet); - packet_callback(packet_type, packet); - }, - close_callback); + [this, packet_callback](PacketType packet_type, + const std::shared_ptr> packet) { + AppendRecord(PacketDirection::HOST_TO_CONTROLLER, packet_type, *packet); + packet_callback(packet_type, packet); + }, + close_callback); } void HciSniffer::Tick() { transport_->Tick(); } @@ -94,8 +88,7 @@ void HciSniffer::Close() { } } -void HciSniffer::Send(PacketType packet_type, - const std::vector& packet) { +void HciSniffer::Send(PacketType packet_type, const std::vector& packet) { AppendRecord(PacketDirection::CONTROLLER_TO_HOST, packet_type, packet); transport_->Send(packet_type, packet); } diff --git a/tools/rootcanal/model/hci/hci_sniffer.h b/tools/rootcanal/model/hci/hci_sniffer.h index 5ad47fbe7b3..79a2b9c76ef 100644 --- a/tools/rootcanal/model/hci/hci_sniffer.h +++ b/tools/rootcanal/model/hci/hci_sniffer.h @@ -35,16 +35,15 @@ enum class PacketDirection : uint8_t { // A Hci Transport that logs all the in and out going // packets to a stream. class HciSniffer : public HciTransport { - public: +public: HciSniffer(std::shared_ptr transport, std::shared_ptr outputStream = nullptr, std::shared_ptr filter = nullptr); ~HciSniffer() = default; - static std::shared_ptr Create( - std::shared_ptr transport, - std::shared_ptr outputStream = nullptr, - std::shared_ptr /*filter*/ = nullptr) { + static std::shared_ptr Create(std::shared_ptr transport, + std::shared_ptr outputStream = nullptr, + std::shared_ptr /*filter*/ = nullptr) { return std::make_shared(transport, outputStream); } @@ -52,18 +51,15 @@ class HciSniffer : public HciTransport { void SetOutputStream(std::shared_ptr outputStream); void SetPcapFilter(std::shared_ptr filter); - void Send(PacketType packet_type, - const std::vector& packet) override; + void Send(PacketType packet_type, const std::vector& packet) override; - void RegisterCallbacks(PacketCallback packet_callback, - CloseCallback close_callback) override; + void RegisterCallbacks(PacketCallback packet_callback, CloseCallback close_callback) override; void Tick() override; void Close() override; - private: - void AppendRecord(PacketDirection direction, PacketType type, - const std::vector& packet); +private: + void AppendRecord(PacketDirection direction, PacketType type, const std::vector& packet); std::shared_ptr output_; std::shared_ptr transport_; diff --git a/tools/rootcanal/model/hci/hci_socket_transport.cc b/tools/rootcanal/model/hci/hci_socket_transport.cc index 0fc556e9b7a..d7127f561ba 100644 --- a/tools/rootcanal/model/hci/hci_socket_transport.cc +++ b/tools/rootcanal/model/hci/hci_socket_transport.cc @@ -27,40 +27,36 @@ void HciSocketTransport::RegisterCallbacks(PacketCallback packet_callback, CloseCallback close_callback) { // TODO: Avoid the copy here by using new buffer in H4DataChannel h4_ = H4DataChannelPacketizer( - socket_, - [packet_callback](const std::vector& raw_command) { - std::shared_ptr> packet_copy = - std::make_shared>(raw_command); - packet_callback(PacketType::COMMAND, packet_copy); - }, - [](const std::vector&) { - FATAL("Unexpected Event in HciSocketTransport!"); - }, - [packet_callback](const std::vector& raw_acl) { - std::shared_ptr> packet_copy = - std::make_shared>(raw_acl); - packet_callback(PacketType::ACL, packet_copy); - }, - [packet_callback](const std::vector& raw_sco) { - std::shared_ptr> packet_copy = - std::make_shared>(raw_sco); - packet_callback(PacketType::SCO, packet_copy); - }, - [packet_callback](const std::vector& raw_iso) { - std::shared_ptr> packet_copy = - std::make_shared>(raw_iso); - packet_callback(PacketType::ISO, packet_copy); - }, - close_callback); + socket_, + [packet_callback](const std::vector& raw_command) { + std::shared_ptr> packet_copy = + std::make_shared>(raw_command); + packet_callback(PacketType::COMMAND, packet_copy); + }, + [](const std::vector&) { FATAL("Unexpected Event in HciSocketTransport!"); }, + [packet_callback](const std::vector& raw_acl) { + std::shared_ptr> packet_copy = + std::make_shared>(raw_acl); + packet_callback(PacketType::ACL, packet_copy); + }, + [packet_callback](const std::vector& raw_sco) { + std::shared_ptr> packet_copy = + std::make_shared>(raw_sco); + packet_callback(PacketType::SCO, packet_copy); + }, + [packet_callback](const std::vector& raw_iso) { + std::shared_ptr> packet_copy = + std::make_shared>(raw_iso); + packet_callback(PacketType::ISO, packet_copy); + }, + close_callback); } void HciSocketTransport::Tick() { h4_.OnDataReady(socket_); } -void HciSocketTransport::Send(PacketType packet_type, - const std::vector& packet) { +void HciSocketTransport::Send(PacketType packet_type, const std::vector& packet) { if (!socket_ || !socket_->Connected()) { - INFO("Closed socket. Dropping packet of type {}", - fmt::underlying(packet_type)); + INFO("Closed socket. Dropping packet of type {}", fmt::underlying(packet_type)); return; } uint8_t type = static_cast(packet_type); diff --git a/tools/rootcanal/model/hci/hci_socket_transport.h b/tools/rootcanal/model/hci/hci_socket_transport.h index e6e4a356acd..660c42e3eaf 100644 --- a/tools/rootcanal/model/hci/hci_socket_transport.h +++ b/tools/rootcanal/model/hci/hci_socket_transport.h @@ -27,25 +27,22 @@ namespace rootcanal { using android::net::AsyncDataChannel; class HciSocketTransport : public HciTransport { - public: +public: HciSocketTransport(std::shared_ptr socket); ~HciSocketTransport() = default; - static std::shared_ptr Create( - std::shared_ptr socket) { + static std::shared_ptr Create(std::shared_ptr socket) { return std::make_shared(socket); } - void Send(PacketType packet_type, - const std::vector& packet) override; + void Send(PacketType packet_type, const std::vector& packet) override; - void RegisterCallbacks(PacketCallback packet_callback, - CloseCallback close_callback) override; + void RegisterCallbacks(PacketCallback packet_callback, CloseCallback close_callback) override; void Tick() override; void Close() override; - private: +private: std::shared_ptr socket_; H4DataChannelPacketizer h4_{socket_, [](const std::vector&) {}, diff --git a/tools/rootcanal/model/hci/hci_transport.h b/tools/rootcanal/model/hci/hci_transport.h index 5aa10f160c0..9f3662e6927 100644 --- a/tools/rootcanal/model/hci/hci_transport.h +++ b/tools/rootcanal/model/hci/hci_transport.h @@ -24,22 +24,19 @@ namespace rootcanal { -using PacketCallback = std::function>)>; +using PacketCallback = std::function>)>; using CloseCallback = std::function; class HciTransport { - public: +public: virtual ~HciTransport() = default; /// Send the input HCI packet with the selected H4 packet type. /// The packet data contains the H4 header but not the IDC byte. - virtual void Send(PacketType packet_type, - std::vector const& packet) = 0; + virtual void Send(PacketType packet_type, std::vector const& packet) = 0; /// Register the handler for received HCI packets. - virtual void RegisterCallbacks(PacketCallback packet_callback, - CloseCallback close_callback) = 0; + virtual void RegisterCallbacks(PacketCallback packet_callback, CloseCallback close_callback) = 0; virtual void Tick() = 0; virtual void Close() = 0; diff --git a/tools/rootcanal/model/setup/async_manager.cc b/tools/rootcanal/model/setup/async_manager.cc index caa92a0fc08..2475212bc1e 100644 --- a/tools/rootcanal/model/setup/async_manager.cc +++ b/tools/rootcanal/model/setup/async_manager.cc @@ -16,26 +16,29 @@ #include "async_manager.h" +#include +#include +#include + #include #include #include -#include #include -#include #include -#include #include #include "log.h" #ifndef TEMP_FAILURE_RETRY /* Used to retry syscalls that can return EINTR. */ -#define TEMP_FAILURE_RETRY(exp) ({ \ +#define TEMP_FAILURE_RETRY(exp) \ + ({ \ __typeof__(exp) _rc; \ do { \ - _rc = (exp); \ + _rc = (exp); \ } while (_rc == -1 && errno == EINTR); \ - _rc; }) + _rc; \ + }) #endif // TEMP_FAILURE_RETRY namespace rootcanal { @@ -84,8 +87,7 @@ namespace rootcanal { // This number also states the maximum number of scheduled tasks we can handle // at a given time -static const uint16_t kMaxTaskId = - -1; /* 2^16 - 1, permisible ids are {1..2^16-1}*/ +static const uint16_t kMaxTaskId = -1; /* 2^16 - 1, permisible ids are {1..2^16-1}*/ static inline AsyncTaskId NextAsyncTaskId(const AsyncTaskId id) { return (id == kMaxTaskId) ? 1 : id + 1; } @@ -103,9 +105,9 @@ static const int kNotificationBufferSize = 10; // Async File Descriptor Watcher Implementation: class AsyncManager::AsyncFdWatcher { - public: - int WatchFdForNonBlockingReads( - int file_descriptor, const ReadCallback& on_read_fd_ready_callback) { +public: + int WatchFdForNonBlockingReads(int file_descriptor, + const ReadCallback& on_read_fd_ready_callback) { // add file descriptor and callback { std::unique_lock guard(internal_mutex_); @@ -146,8 +148,7 @@ class AsyncManager::AsyncFdWatcher { if (std::this_thread::get_id() != thread_.get_id()) { thread_.join(); } else { - WARNING("{}: Starting thread stop from inside the reading thread itself", - __func__); + WARNING("{}: Starting thread stop from inside the reading thread itself", __func__); } { @@ -158,7 +159,7 @@ class AsyncManager::AsyncFdWatcher { return 0; } - private: +private: // Make sure to call this with at least one file descriptor ready to be // watched upon or the thread routine will return immediately int tryStartThread() { @@ -168,19 +169,16 @@ class AsyncManager::AsyncFdWatcher { // set up the communication channel int pipe_fds[2]; if (pipe(pipe_fds)) { - ERROR( - "{}: Unable to establish a communication channel to the reading " - "thread", - __func__); + ERROR("{}: Unable to establish a communication channel to the reading " + "thread", + __func__); return -1; } // configure the fds as non blocking. - if (fcntl(pipe_fds[0], F_SETFL, O_NONBLOCK) || - fcntl(pipe_fds[1], F_SETFL, O_NONBLOCK)) { - ERROR( - "{}: Unable to configure the communication channel to the reading " - "thread", - __func__); + if (fcntl(pipe_fds[0], F_SETFL, O_NONBLOCK) || fcntl(pipe_fds[1], F_SETFL, O_NONBLOCK)) { + ERROR("{}: Unable to configure the communication channel to the reading " + "thread", + __func__); return -1; } @@ -224,8 +222,7 @@ class AsyncManager::AsyncFdWatcher { bool consumeThreadNotifications(fd_set& read_fds) const { if (FD_ISSET(notification_listen_fd_, &read_fds)) { char buffer[kNotificationBufferSize]; - while (TEMP_FAILURE_RETRY(read(notification_listen_fd_, buffer, - kNotificationBufferSize)) == + while (TEMP_FAILURE_RETRY(read(notification_listen_fd_, buffer, kNotificationBufferSize)) == kNotificationBufferSize) { } return true; @@ -256,10 +253,9 @@ class AsyncManager::AsyncFdWatcher { // wait until there is data available to read on some FD int retval = select(nfds + 1, &read_fds, NULL, NULL, NULL); if (retval <= 0) { // there was some error or a timeout - ERROR( - "{}: There was an error while waiting for data on the file " - "descriptors: {}", - __func__, strerror(errno)); + ERROR("{}: There was an error while waiting for data on the file " + "descriptors: {}", + __func__, strerror(errno)); continue; } @@ -287,21 +283,20 @@ class AsyncManager::AsyncFdWatcher { // Async task manager implementation class AsyncManager::AsyncTaskManager { - public: +public: AsyncUserId GetNextUserId() { return lastUserId_++; } AsyncTaskId ExecAsync(AsyncUserId user_id, std::chrono::milliseconds delay, const TaskCallback& callback) { - return scheduleTask(std::make_shared( - std::chrono::steady_clock::now() + delay, callback, user_id)); + return scheduleTask( + std::make_shared(std::chrono::steady_clock::now() + delay, callback, user_id)); } - AsyncTaskId ExecAsyncPeriodically(AsyncUserId user_id, - std::chrono::milliseconds delay, + AsyncTaskId ExecAsyncPeriodically(AsyncUserId user_id, std::chrono::milliseconds delay, std::chrono::milliseconds period, const TaskCallback& callback) { - return scheduleTask(std::make_shared( - std::chrono::steady_clock::now() + delay, period, callback, user_id)); + return scheduleTask(std::make_shared(std::chrono::steady_clock::now() + delay, period, + callback, user_id)); } bool CancelAsyncTask(AsyncTaskId async_task_id) { @@ -349,37 +344,29 @@ class AsyncManager::AsyncTaskManager { if (std::this_thread::get_id() != thread_.get_id()) { thread_.join(); } else { - WARNING("{}: Starting thread stop from inside the task thread itself", - __func__); + WARNING("{}: Starting thread stop from inside the task thread itself", __func__); } return 0; } - private: +private: // Holds the data for each task class Task { - public: - Task(std::chrono::steady_clock::time_point time, - std::chrono::milliseconds period, const TaskCallback& callback, - AsyncUserId user) + public: + Task(std::chrono::steady_clock::time_point time, std::chrono::milliseconds period, + const TaskCallback& callback, AsyncUserId user) : time(time), periodic(true), period(period), callback(callback), task_id(kInvalidTaskId), user_id(user) {} - Task(std::chrono::steady_clock::time_point time, - const TaskCallback& callback, AsyncUserId user) - : time(time), - periodic(false), - callback(callback), - task_id(kInvalidTaskId), - user_id(user) {} + Task(std::chrono::steady_clock::time_point time, const TaskCallback& callback, AsyncUserId user) + : time(time), periodic(false), callback(callback), task_id(kInvalidTaskId), user_id(user) {} // Operators needed to be in a collection bool operator<(const Task& another) const { - return std::make_pair(time, task_id) < - std::make_pair(another.time, another.task_id); + return std::make_pair(time, task_id) < std::make_pair(another.time, another.task_id); } bool isPeriodic() const { return periodic; } @@ -389,7 +376,7 @@ class AsyncManager::AsyncTaskManager { std::chrono::steady_clock::time_point time; bool periodic; std::chrono::milliseconds period{}; - std::mutex in_callback; // Taken when the callback is active + std::mutex in_callback; // Taken when the callback is active TaskCallback callback; AsyncTaskId task_id; AsyncUserId user_id; @@ -397,8 +384,7 @@ class AsyncManager::AsyncTaskManager { // A comparator class to put shared pointers to tasks in an ordered set struct task_p_comparator { - bool operator()(const std::shared_ptr& t1, - const std::shared_ptr& t2) const { + bool operator()(const std::shared_ptr& t1, const std::shared_ptr& t2) const { return *t1 < *t2; } }; @@ -454,9 +440,7 @@ class AsyncManager::AsyncTaskManager { return task->task_id; } - bool isTaskIdInUse(const AsyncTaskId& task_id) const { - return tasks_by_id_.count(task_id) != 0; - } + bool isTaskIdInUse(const AsyncTaskId& task_id) const { return tasks_by_id_.count(task_id) != 0; } int tryStartThread() { // need the lock because of the running flag and the cond var @@ -514,8 +498,7 @@ class AsyncManager::AsyncTaskManager { // Make a copy of the time_point because wait_until takes a reference // to it and may read it after waiting, by which time the task may // have been freed (e.g. via CancelAsyncTask). - std::chrono::steady_clock::time_point time = - (*task_queue_.begin())->time; + std::chrono::steady_clock::time_point time = (*task_queue_.begin())->time; internal_cond_var_.wait_until(guard, time); } else { internal_cond_var_.wait(guard); @@ -539,8 +522,7 @@ class AsyncManager::AsyncTaskManager { // Async Manager Implementation: AsyncManager::AsyncManager() - : fdWatcher_p_(new AsyncFdWatcher()), - taskManager_p_(new AsyncTaskManager()) {} + : fdWatcher_p_(new AsyncFdWatcher()), taskManager_p_(new AsyncTaskManager()) {} AsyncManager::~AsyncManager() { // Make sure the threads are stopped before destroying the object. @@ -553,31 +535,27 @@ AsyncManager::~AsyncManager() { taskManager_p_->stopThread(); } -int AsyncManager::WatchFdForNonBlockingReads( - int file_descriptor, const ReadCallback& on_read_fd_ready_callback) { - return fdWatcher_p_->WatchFdForNonBlockingReads(file_descriptor, - on_read_fd_ready_callback); +int AsyncManager::WatchFdForNonBlockingReads(int file_descriptor, + const ReadCallback& on_read_fd_ready_callback) { + return fdWatcher_p_->WatchFdForNonBlockingReads(file_descriptor, on_read_fd_ready_callback); } void AsyncManager::StopWatchingFileDescriptor(int file_descriptor) { fdWatcher_p_->StopWatchingFileDescriptor(file_descriptor); } -AsyncUserId AsyncManager::GetNextUserId() { - return taskManager_p_->GetNextUserId(); -} +AsyncUserId AsyncManager::GetNextUserId() { return taskManager_p_->GetNextUserId(); } -AsyncTaskId AsyncManager::ExecAsync(AsyncUserId user_id, - std::chrono::milliseconds delay, +AsyncTaskId AsyncManager::ExecAsync(AsyncUserId user_id, std::chrono::milliseconds delay, const TaskCallback& callback) { return taskManager_p_->ExecAsync(user_id, delay, callback); } -AsyncTaskId AsyncManager::ExecAsyncPeriodically( - AsyncUserId user_id, std::chrono::milliseconds delay, - std::chrono::milliseconds period, const TaskCallback& callback) { - return taskManager_p_->ExecAsyncPeriodically(user_id, delay, period, - callback); +AsyncTaskId AsyncManager::ExecAsyncPeriodically(AsyncUserId user_id, + std::chrono::milliseconds delay, + std::chrono::milliseconds period, + const TaskCallback& callback) { + return taskManager_p_->ExecAsyncPeriodically(user_id, delay, period, callback); } bool AsyncManager::CancelAsyncTask(AsyncTaskId async_task_id) { diff --git a/tools/rootcanal/model/setup/async_manager.h b/tools/rootcanal/model/setup/async_manager.h index d1861d2f6db..a8eaff0e435 100644 --- a/tools/rootcanal/model/setup/async_manager.h +++ b/tools/rootcanal/model/setup/async_manager.h @@ -63,7 +63,7 @@ constexpr uint16_t kInvalidTaskId = 0; // AsyncManager object from different threads are granted to *NOT* run // concurrently. class AsyncManager { - public: +public: // Starts watching a file descriptor in a separate thread. The // on_read_fd_ready_callback() will be asynchronously called when it is // guaranteed that a call to read() on the FD will not block. No promise is @@ -88,10 +88,8 @@ class AsyncManager { // is not positive the callback will be asynchronously called once for each // time in the past that it should have been called and then scheduled for // future times. - AsyncTaskId ExecAsyncPeriodically(AsyncUserId user_id, - std::chrono::milliseconds delay, - std::chrono::milliseconds period, - const TaskCallback& callback); + AsyncTaskId ExecAsyncPeriodically(AsyncUserId user_id, std::chrono::milliseconds delay, + std::chrono::milliseconds period, const TaskCallback& callback); // Cancels the/every future occurrence of the action specified by this id. // The following invariants will hold: @@ -122,7 +120,7 @@ class AsyncManager { ~AsyncManager(); - private: +private: // Implementation of the FD watching part of AsyncManager, extracted to its // own class for clarity purposes. class AsyncFdWatcher; diff --git a/tools/rootcanal/model/setup/device_boutique.cc b/tools/rootcanal/model/setup/device_boutique.cc index ad04cbe28f6..78258629f07 100644 --- a/tools/rootcanal/model/setup/device_boutique.cc +++ b/tools/rootcanal/model/setup/device_boutique.cc @@ -22,27 +22,24 @@ using std::vector; namespace rootcanal { -std::unordered_map( - const vector&)>>& +std::unordered_map(const vector&)>>& DeviceBoutique::GetMap() { - static std::unordered_map( - const vector&)>> - impl; + static std::unordered_map(const vector&)>> + impl; return impl; } // Register a constructor for a device type. bool DeviceBoutique::Register( - const std::string& device_type, - const std::function(const vector&)> - method) { + const std::string& device_type, + const std::function(const vector&)> method) { INFO("Registering {}", device_type); GetMap()[device_type] = method; return true; } -std::shared_ptr DeviceBoutique::Create( - const vector& args) { +std::shared_ptr DeviceBoutique::Create(const vector& args) { ASSERT(!args.empty()); auto device = GetMap().find(args[0]); diff --git a/tools/rootcanal/model/setup/device_boutique.h b/tools/rootcanal/model/setup/device_boutique.h index 2f074041a07..fc57a243777 100644 --- a/tools/rootcanal/model/setup/device_boutique.h +++ b/tools/rootcanal/model/setup/device_boutique.h @@ -28,22 +28,21 @@ namespace rootcanal { // Create customized devices from a centralized shop. class DeviceBoutique { - public: +public: DeviceBoutique(); virtual ~DeviceBoutique() = default; // Register a constructor for a device type. static bool Register( - std::string const& device_type, - std::function(const std::vector&)> - method); + std::string const& device_type, + std::function(const std::vector&)> method); // Call the function that matches arg[0] with args static std::shared_ptr Create(const std::vector& args); - private: - static std::unordered_map( - const std::vector&)>>& +private: + static std::unordered_map< + std::string, std::function(const std::vector&)>>& GetMap(); }; diff --git a/tools/rootcanal/model/setup/phy_device.cc b/tools/rootcanal/model/setup/phy_device.cc index 59f3d52b435..297c0ee7bd0 100644 --- a/tools/rootcanal/model/setup/phy_device.cc +++ b/tools/rootcanal/model/setup/phy_device.cc @@ -26,8 +26,7 @@ PhyDevice::PhyDevice(std::string type, std::shared_ptr device) : id(device->id_), type(std::move(type)), device_(std::move(device)) { using namespace std::placeholders; ASSERT(device_ != nullptr); - device_->RegisterLinkLayerChannel( - std::bind(&PhyDevice::Send, this, _1, _2, _3)); + device_->RegisterLinkLayerChannel(std::bind(&PhyDevice::Send, this, _1, _2, _3)); } void PhyDevice::Register(PhyLayer* phy) { phy_layers_.insert(phy); } @@ -36,25 +35,19 @@ void PhyDevice::Unregister(PhyLayer* phy) { phy_layers_.erase(phy); } void PhyDevice::Tick() { device_->Tick(); } -bluetooth::hci::Address PhyDevice::GetAddress() const { - return device_->GetAddress(); -} +bluetooth::hci::Address PhyDevice::GetAddress() const { return device_->GetAddress(); } -std::shared_ptr PhyDevice::GetDevice() const { - return device_; -} +std::shared_ptr PhyDevice::GetDevice() const { return device_; } void PhyDevice::SetAddress(bluetooth::hci::Address address) { device_->SetAddress(std::move(address)); } -void PhyDevice::Receive(std::vector const& packet, Phy::Type type, - int8_t rssi) { +void PhyDevice::Receive(std::vector const& packet, Phy::Type type, int8_t rssi) { std::shared_ptr> packet_copy = - std::make_shared>(packet); + std::make_shared>(packet); model::packets::LinkLayerPacketView packet_view = - model::packets::LinkLayerPacketView::Create( - pdl::packet::slice(packet_copy)); + model::packets::LinkLayerPacketView::Create(pdl::packet::slice(packet_copy)); if (packet_view.IsValid()) { device_->ReceiveLinkLayerPacket(std::move(packet_view), type, rssi); } else { @@ -62,8 +55,7 @@ void PhyDevice::Receive(std::vector const& packet, Phy::Type type, } } -void PhyDevice::Send(std::vector const& packet, Phy::Type type, - int8_t tx_power) { +void PhyDevice::Send(std::vector const& packet, Phy::Type type, int8_t tx_power) { for (auto const& phy : phy_layers_) { if (phy->type == type) { phy->Send(packet, tx_power, id); diff --git a/tools/rootcanal/model/setup/phy_device.h b/tools/rootcanal/model/setup/phy_device.h index af45dbedd45..1a989bfa434 100644 --- a/tools/rootcanal/model/setup/phy_device.h +++ b/tools/rootcanal/model/setup/phy_device.h @@ -28,11 +28,11 @@ class PhyLayer; class Device; class PhyDevice { - public: +public: using Identifier = uint32_t; PhyDevice(std::string type, std::shared_ptr device); - PhyDevice(PhyDevice &&) = delete; + PhyDevice(PhyDevice&&) = delete; ~PhyDevice() = default; void Register(PhyLayer* phy); @@ -40,8 +40,7 @@ class PhyDevice { void Tick(); void Receive(std::vector const& packet, Phy::Type type, int8_t rssi); - void Send(std::vector const& packet, Phy::Type type, - int8_t tx_power); + void Send(std::vector const& packet, Phy::Type type, int8_t tx_power); bluetooth::hci::Address GetAddress() const; std::shared_ptr GetDevice() const; @@ -52,7 +51,7 @@ class PhyDevice { const Identifier id; const std::string type; - private: +private: const std::shared_ptr device_; std::unordered_set phy_layers_; }; diff --git a/tools/rootcanal/model/setup/phy_layer.cc b/tools/rootcanal/model/setup/phy_layer.cc index 301979c85f8..2e15f74d9f7 100644 --- a/tools/rootcanal/model/setup/phy_layer.cc +++ b/tools/rootcanal/model/setup/phy_layer.cc @@ -45,8 +45,7 @@ void PhyLayer::UnregisterAll() { } int8_t PhyLayer::ComputeRssi(PhyDevice::Identifier /*sender_id*/, - PhyDevice::Identifier /*receiver_id*/, - int8_t /*tx_power*/) { + PhyDevice::Identifier /*receiver_id*/, int8_t /*tx_power*/) { // Perform no RSSI computation by default. // Clients overriding this function should use the TX power and // positional information to derive correct device-to-device RSSI. @@ -60,8 +59,7 @@ void PhyLayer::Send(std::vector const& packet, int8_t tx_power, for (const auto& device : phy_devices_) { // Do not send the packet back to the sender. if (sender_id != device->id) { - device->Receive(packet, type, - ComputeRssi(sender_id, device->id, tx_power)); + device->Receive(packet, type, ComputeRssi(sender_id, device->id, tx_power)); } } } diff --git a/tools/rootcanal/model/setup/phy_layer.h b/tools/rootcanal/model/setup/phy_layer.h index 4c14f45d482..2c96db7da3e 100644 --- a/tools/rootcanal/model/setup/phy_layer.h +++ b/tools/rootcanal/model/setup/phy_layer.h @@ -28,7 +28,7 @@ namespace rootcanal { using rootcanal::PhyDevice; class PhyLayer { - public: +public: using Identifier = uint32_t; PhyLayer(Identifier id, Phy::Type type); @@ -40,8 +40,7 @@ class PhyLayer { // Compute the RSSI for a packet sent from one device to the other // with the specified TX power. - virtual int8_t ComputeRssi(PhyDevice::Identifier sender_id, - PhyDevice::Identifier receiver_id, + virtual int8_t ComputeRssi(PhyDevice::Identifier sender_id, PhyDevice::Identifier receiver_id, int8_t tx_power); void Register(std::shared_ptr device); @@ -54,7 +53,7 @@ class PhyLayer { const Identifier id; const Phy::Type type; - protected: +protected: // List of devices currently connected to the phy. std::list> phy_devices_; }; diff --git a/tools/rootcanal/model/setup/test_channel_transport.cc b/tools/rootcanal/model/setup/test_channel_transport.cc index 6b04326be66..d59cbb507f7 100644 --- a/tools/rootcanal/model/setup/test_channel_transport.cc +++ b/tools/rootcanal/model/setup/test_channel_transport.cc @@ -48,16 +48,15 @@ void TestChannelTransport::OnCommandReady(AsyncDataChannel* socket, uint8_t command_name_size = 0; ssize_t bytes_read = socket->Recv(&command_name_size, 1); if (bytes_read != 1) { - INFO("Unexpected (command_name_size) bytes_read: {} != {}, {}", bytes_read, - 1, strerror(errno)); + INFO("Unexpected (command_name_size) bytes_read: {} != {}, {}", bytes_read, 1, strerror(errno)); socket->Close(); } vector command_name_raw; command_name_raw.resize(command_name_size); bytes_read = socket->Recv(command_name_raw.data(), command_name_size); if (bytes_read != command_name_size) { - INFO("Unexpected (command_name) bytes_read: {} != {}, {}", bytes_read, - command_name_size, strerror(errno)); + INFO("Unexpected (command_name) bytes_read: {} != {}, {}", bytes_read, command_name_size, + strerror(errno)); } std::string command_name(command_name_raw.begin(), command_name_raw.end()); @@ -71,23 +70,20 @@ void TestChannelTransport::OnCommandReady(AsyncDataChannel* socket, uint8_t num_args = 0; bytes_read = socket->Recv(&num_args, 1); if (bytes_read != 1) { - INFO("Unexpected (num_args) bytes_read: {} != {}, {}", bytes_read, 1, - strerror(errno)); + INFO("Unexpected (num_args) bytes_read: {} != {}, {}", bytes_read, 1, strerror(errno)); } vector args; for (uint8_t i = 0; i < num_args; ++i) { uint8_t arg_size = 0; bytes_read = socket->Recv(&arg_size, 1); if (bytes_read != 1) { - INFO("Unexpected (arg_size) bytes_read: {} != {}, {}", bytes_read, 1, - strerror(errno)); + INFO("Unexpected (arg_size) bytes_read: {} != {}, {}", bytes_read, 1, strerror(errno)); } vector arg; arg.resize(arg_size); bytes_read = socket->Recv(arg.data(), arg_size); if (bytes_read != arg_size) { - INFO("Unexpected (arg) bytes_read: {} != {}, {}", bytes_read, arg_size, - strerror(errno)); + INFO("Unexpected (arg) bytes_read: {} != {}, {}", bytes_read, arg_size, strerror(errno)); } args.push_back(std::string(arg.begin(), arg.end())); } @@ -95,33 +91,29 @@ void TestChannelTransport::OnCommandReady(AsyncDataChannel* socket, command_handler_(command_name, args); } -void TestChannelTransport::SendResponse( - std::shared_ptr socket, const std::string& response) { +void TestChannelTransport::SendResponse(std::shared_ptr socket, + const std::string& response) { size_t size = response.size(); // Cap to 64K if (size > 0xffff) { size = 0xffff; } - uint8_t size_buf[4] = {static_cast(size & 0xff), - static_cast((size >> 8) & 0xff), - static_cast((size >> 16) & 0xff), - static_cast((size >> 24) & 0xff)}; + uint8_t size_buf[4] = { + static_cast(size & 0xff), static_cast((size >> 8) & 0xff), + static_cast((size >> 16) & 0xff), static_cast((size >> 24) & 0xff)}; ssize_t written = socket->Send(size_buf, 4); if (written == -1 && errno == EBADF) { WARNING("Unable to send a response. EBADF"); return; } - ASSERT_LOG(written == 4, "What happened? written = %zd errno = %d", written, + ASSERT_LOG(written == 4, "What happened? written = %zd errno = %d", written, errno); + written = socket->Send(reinterpret_cast(response.c_str()), size); + ASSERT_LOG(written == static_cast(size), "What happened? written = %zd errno = %d", written, errno); - written = - socket->Send(reinterpret_cast(response.c_str()), size); - ASSERT_LOG(written == static_cast(size), - "What happened? written = %zd errno = %d", written, errno); } void TestChannelTransport::RegisterCommandHandler( - const std::function&)>& callback) { + const std::function&)>& callback) { command_handler_ = callback; } diff --git a/tools/rootcanal/model/setup/test_channel_transport.h b/tools/rootcanal/model/setup/test_channel_transport.h index a7405918d8c..14081eb70b9 100644 --- a/tools/rootcanal/model/setup/test_channel_transport.h +++ b/tools/rootcanal/model/setup/test_channel_transport.h @@ -21,7 +21,7 @@ #include // for string #include // for vector -#include "net/async_data_channel.h" // for AsyncDataChannel +#include "net/async_data_channel.h" // for AsyncDataChannel #include "net/async_data_channel_server.h" // for AsyncDataChannelServer (ptr only), Con... namespace rootcanal { @@ -33,33 +33,28 @@ using android::net::ConnectCallback; // Manages communications between test channel and the controller. Mirrors the // HciTransport for the test channel. class TestChannelTransport { - public: +public: TestChannelTransport() {} ~TestChannelTransport() {} // Opens a port and returns and starts listening for incoming connections. - bool SetUp(std::shared_ptr server, - ConnectCallback connection_callback); + bool SetUp(std::shared_ptr server, ConnectCallback connection_callback); // Closes the port (if succesfully opened in SetUp). void CleanUp(); // Sets the callback that fires when data is read in WatchFd(). void RegisterCommandHandler( - const std::function&)>& callback); + const std::function&)>& callback); // Send data back to the test channel. - static void SendResponse(std::shared_ptr socket, - const std::string& response); + static void SendResponse(std::shared_ptr socket, const std::string& response); - void OnCommandReady(AsyncDataChannel* socket, - std::function unwatch); + void OnCommandReady(AsyncDataChannel* socket, std::function unwatch); - private: - std::function&)> - command_handler_; +private: + std::function&)> command_handler_; std::function)> connection_callback_; std::shared_ptr socket_server_; diff --git a/tools/rootcanal/model/setup/test_command_handler.cc b/tools/rootcanal/model/setup/test_command_handler.cc index 45b947c09b1..93315ae16e7 100644 --- a/tools/rootcanal/model/setup/test_command_handler.cc +++ b/tools/rootcanal/model/setup/test_command_handler.cc @@ -35,12 +35,9 @@ static size_t ParseIntParam(std::string const& in) { return static_cast(std::strtoul(in.c_str(), nullptr, 0)); } -TestCommandHandler::TestCommandHandler(TestModel& test_model) - : model_(test_model) { -#define SET_HANDLER(command_name, method) \ - active_commands_[command_name] = [this](const vector& param) { \ - method(param); \ - }; +TestCommandHandler::TestCommandHandler(TestModel& test_model) : model_(test_model) { +#define SET_HANDLER(command_name, method) \ + active_commands_[command_name] = [this](const vector& param) { method(param); }; SET_HANDLER("add", AddDevice); SET_HANDLER("add_remote", AddRemote); SET_HANDLER("del", RemoveDevice); @@ -85,8 +82,7 @@ void TestCommandHandler::AddDefaults() { StartTimer({}); } -void TestCommandHandler::HandleCommand(const std::string& name, - const vector& args) { +void TestCommandHandler::HandleCommand(const std::string& name, const vector& args) { if (active_commands_.count(name) == 0) { response_string_ = "Unhandled command: " + name; send_response_(response_string_); @@ -96,7 +92,7 @@ void TestCommandHandler::HandleCommand(const std::string& name, } void TestCommandHandler::RegisterSendResponse( - const std::function callback) { + const std::function callback) { send_response_ = callback; send_response_("RegisterSendResponse called"); } @@ -118,15 +114,13 @@ void TestCommandHandler::AddDevice(const vector& args) { INFO("Add {}", new_dev->ToString()); size_t dev_index = model_.AddDevice(new_dev); - response_string_ = - std::to_string(dev_index) + std::string(":") + new_dev->ToString(); + response_string_ = std::to_string(dev_index) + std::string(":") + new_dev->ToString(); send_response_(response_string_); } void TestCommandHandler::AddRemote(const vector& args) { if (args.size() < 3) { - response_string_ = - "TestCommandHandler usage: add_remote host port phy_type"; + response_string_ = "TestCommandHandler usage: add_remote host port phy_type"; send_response_(response_string_); return; } @@ -155,8 +149,8 @@ void TestCommandHandler::RemoveDevice(const vector& args) { size_t dev_index = ParseIntParam(args[0]); model_.RemoveDevice(dev_index); - response_string_ = "TestCommandHandler 'del' called with device at index " + - std::to_string(dev_index); + response_string_ = + "TestCommandHandler 'del' called with device at index " + std::to_string(dev_index); send_response_(response_string_); } @@ -170,8 +164,7 @@ void TestCommandHandler::AddPhy(const vector& args) { model_.AddPhy(Phy::Type::BR_EDR); response_string_ = "TestCommandHandler 'add_phy' called with BR_EDR"; } else { - response_string_ = - "TestCommandHandler 'add_phy' with unrecognized type " + args[0]; + response_string_ = "TestCommandHandler 'add_phy' with unrecognized type " + args[0]; } send_response_(response_string_); } @@ -180,40 +173,36 @@ void TestCommandHandler::RemovePhy(const vector& args) { size_t phy_index = ParseIntParam(args[0]); model_.RemovePhy(phy_index); - response_string_ = "TestCommandHandler 'del_phy' called with phy at index " + - std::to_string(phy_index); + response_string_ = + "TestCommandHandler 'del_phy' called with phy at index " + std::to_string(phy_index); send_response_(response_string_); } void TestCommandHandler::AddDeviceToPhy(const vector& args) { if (args.size() != 2) { - response_string_ = - "TestCommandHandler 'add_device_to_phy' takes two arguments"; + response_string_ = "TestCommandHandler 'add_device_to_phy' takes two arguments"; send_response_(response_string_); return; } size_t dev_index = ParseIntParam(args[0]); size_t phy_index = ParseIntParam(args[1]); model_.AddDeviceToPhy(dev_index, phy_index); - response_string_ = - "TestCommandHandler 'add_device_to_phy' called with device " + - std::to_string(dev_index) + " and phy " + std::to_string(phy_index); + response_string_ = "TestCommandHandler 'add_device_to_phy' called with device " + + std::to_string(dev_index) + " and phy " + std::to_string(phy_index); send_response_(response_string_); } void TestCommandHandler::RemoveDeviceFromPhy(const vector& args) { if (args.size() != 2) { - response_string_ = - "TestCommandHandler 'del_device_from_phy' takes two arguments"; + response_string_ = "TestCommandHandler 'del_device_from_phy' takes two arguments"; send_response_(response_string_); return; } size_t dev_index = ParseIntParam(args[0]); size_t phy_index = ParseIntParam(args[1]); model_.RemoveDeviceFromPhy(dev_index, phy_index); - response_string_ = - "TestCommandHandler 'del_device_from_phy' called with device " + - std::to_string(dev_index) + " and phy " + std::to_string(phy_index); + response_string_ = "TestCommandHandler 'del_device_from_phy' called with device " + + std::to_string(dev_index) + " and phy " + std::to_string(phy_index); send_response_(response_string_); } @@ -227,8 +216,7 @@ void TestCommandHandler::List(const vector& args) { void TestCommandHandler::SetDeviceAddress(const vector& args) { if (args.size() != 2) { - response_string_ = - "TestCommandHandler 'set_device_address' takes two arguments"; + response_string_ = "TestCommandHandler 'set_device_address' takes two arguments"; send_response_(response_string_); return; } @@ -244,14 +232,13 @@ void TestCommandHandler::SetDeviceAddress(const vector& args) { void TestCommandHandler::SetDeviceConfiguration(const vector& args) { if (args.size() != 2) { - response_string_ = - "TestCommandHandler 'set_device_configuration' takes two arguments"; + response_string_ = "TestCommandHandler 'set_device_configuration' takes two arguments"; send_response_(response_string_); return; } size_t device_id = ParseIntParam(args[0]); rootcanal::configuration::ControllerPreset preset = - rootcanal::configuration::ControllerPreset::DEFAULT; + rootcanal::configuration::ControllerPreset::DEFAULT; if (args[1] == "default") { preset = rootcanal::configuration::ControllerPreset::DEFAULT; @@ -260,8 +247,7 @@ void TestCommandHandler::SetDeviceConfiguration(const vector& args) } else if (args[1] == "csr_rck_pts_dongle") { preset = rootcanal::configuration::ControllerPreset::CSR_RCK_PTS_DONGLE; } else { - response_string_ = - "TestCommandHandler 'set_device_configuration' invalid configuration preset"; + response_string_ = "TestCommandHandler 'set_device_configuration' invalid configuration preset"; send_response_(response_string_); return; } diff --git a/tools/rootcanal/model/setup/test_command_handler.h b/tools/rootcanal/model/setup/test_command_handler.h index 4f41c3222ad..751016e6af5 100644 --- a/tools/rootcanal/model/setup/test_command_handler.h +++ b/tools/rootcanal/model/setup/test_command_handler.h @@ -30,15 +30,14 @@ namespace rootcanal { class TestCommandHandler { - public: +public: // Sets all of the methods to be used as callbacks in the HciHandler. TestCommandHandler(TestModel& test_model); ~TestCommandHandler() = default; // Dispatches the action corresponding to the command specified by |name|. - void HandleCommand(const std::string& name, - const std::vector& args); + void HandleCommand(const std::string& name, const std::vector& args); // Dispatches the action corresponding to the command specified by |name|. void RegisterSendResponse(std::function callback); @@ -87,14 +86,13 @@ class TestCommandHandler { // For manual testing void AddDefaults(); - private: +private: TestModel& model_; std::string response_string_; - std::unordered_map&)>> - active_commands_; + std::unordered_map&)>> + active_commands_; std::function send_response_; diff --git a/tools/rootcanal/model/setup/test_model.cc b/tools/rootcanal/model/setup/test_model.cc index 060b4cfb832..eb590bde8a7 100644 --- a/tools/rootcanal/model/setup/test_model.cc +++ b/tools/rootcanal/model/setup/test_model.cc @@ -18,13 +18,12 @@ #include // for size_t -#include // for operator<<, setfill -#include // for basic_ostream -#include // for shared_ptr, make... +#include // for operator<<, setfill +#include // for basic_ostream +#include // for shared_ptr, make... #include #include // for remove_extent_t #include // for move -#include #include "include/phy.h" // for Phy, Phy::Type #include "log.h" @@ -33,20 +32,19 @@ namespace rootcanal { TestModel::TestModel( - std::function get_user_id, - std::function - event_scheduler, - - std::function - periodic_event_scheduler, - - std::function cancel_tasks_from_user, - std::function cancel, - std::function(const std::string&, int, Phy::Type)> - connect_to_remote, - std::array bluetooth_address_prefix) + std::function get_user_id, + std::function + event_scheduler, + + std::function + periodic_event_scheduler, + + std::function cancel_tasks_from_user, + std::function cancel, + std::function(const std::string&, int, Phy::Type)> + connect_to_remote, + std::array bluetooth_address_prefix) : bluetooth_address_prefix_(std::move(bluetooth_address_prefix)), get_user_id_(std::move(get_user_id)), schedule_task_(std::move(event_scheduler)), @@ -57,9 +55,7 @@ TestModel::TestModel( model_user_id_ = get_user_id_(); } -TestModel::~TestModel() { - StopTimer(); -} +TestModel::~TestModel() { StopTimer(); } void TestModel::SetTimerPeriod(std::chrono::milliseconds new_period) { timer_period_ = new_period; @@ -75,9 +71,8 @@ void TestModel::SetTimerPeriod(std::chrono::milliseconds new_period) { void TestModel::StartTimer() { INFO("StartTimer()"); - timer_tick_task_ = - schedule_periodic_task_(model_user_id_, std::chrono::milliseconds(0), - timer_period_, [this]() { TestModel::Tick(); }); + timer_tick_task_ = schedule_periodic_task_(model_user_id_, std::chrono::milliseconds(0), + timer_period_, [this]() { TestModel::Tick(); }); } void TestModel::StopTimer() { @@ -86,34 +81,32 @@ void TestModel::StopTimer() { timer_tick_task_ = kInvalidTaskId; } -std::unique_ptr TestModel::CreatePhyLayer(PhyLayer::Identifier id, - Phy::Type type) { +std::unique_ptr TestModel::CreatePhyLayer(PhyLayer::Identifier id, Phy::Type type) { return std::make_unique(id, type); } -std::shared_ptr TestModel::CreatePhyDevice( - std::string type, std::shared_ptr device) { +std::shared_ptr TestModel::CreatePhyDevice(std::string type, + std::shared_ptr device) { return std::make_shared(std::move(type), std::move(device)); } Address TestModel::GenerateBluetoothAddress(uint32_t device_id) const { Address address({ - static_cast(device_id), - bluetooth_address_prefix_[4], - bluetooth_address_prefix_[3], - bluetooth_address_prefix_[2], - bluetooth_address_prefix_[1], - bluetooth_address_prefix_[0], + static_cast(device_id), + bluetooth_address_prefix_[4], + bluetooth_address_prefix_[3], + bluetooth_address_prefix_[2], + bluetooth_address_prefix_[1], + bluetooth_address_prefix_[0], }); if (reuse_device_addresses_) { // Find the first unused address. for (uint16_t b0 = 0; b0 <= 0xff; b0++) { address.address[0] = b0; - bool used = std::any_of(phy_devices_.begin(), phy_devices_.end(), - [address](auto& device) { - return device.second->GetAddress() == address; - }); + bool used = std::any_of(phy_devices_.begin(), phy_devices_.end(), [address](auto& device) { + return device.second->GetAddress() == address; + }); if (!used) { break; } @@ -126,8 +119,7 @@ Address TestModel::GenerateBluetoothAddress(uint32_t device_id) const { // Add a device to the test model. PhyDevice::Identifier TestModel::AddDevice(std::shared_ptr device) { std::string device_type = device->GetTypeString(); - std::shared_ptr phy_device = - CreatePhyDevice(device_type, std::move(device)); + std::shared_ptr phy_device = CreatePhyDevice(device_type, std::move(device)); phy_devices_[phy_device->id] = phy_device; return phy_device->id; } @@ -157,8 +149,7 @@ void TestModel::RemovePhy(PhyLayer::Identifier phy_id) { } // Add the selected device to the selected phy. -void TestModel::AddDeviceToPhy(PhyDevice::Identifier device_id, - PhyLayer::Identifier phy_id) { +void TestModel::AddDeviceToPhy(PhyDevice::Identifier device_id, PhyLayer::Identifier phy_id) { if (phy_layers_.find(phy_id) != phy_layers_.end() && phy_devices_.find(device_id) != phy_devices_.end()) { phy_layers_[phy_id]->Register(phy_devices_[device_id]); @@ -166,15 +157,13 @@ void TestModel::AddDeviceToPhy(PhyDevice::Identifier device_id, } // Remove the selected device from the selected phy. -void TestModel::RemoveDeviceFromPhy(PhyDevice::Identifier device_id, - PhyLayer::Identifier phy_id) { +void TestModel::RemoveDeviceFromPhy(PhyDevice::Identifier device_id, PhyLayer::Identifier phy_id) { if (phy_layers_.find(phy_id) != phy_layers_.end()) { phy_layers_[phy_id]->Unregister(device_id); } } -void TestModel::AddLinkLayerConnection(std::shared_ptr device, - Phy::Type type) { +void TestModel::AddLinkLayerConnection(std::shared_ptr device, Phy::Type type) { INFO(device->id_, "Adding a new link layer connection of type: {}", type == Phy::Type::BR_EDR ? "BR_EDR" : "LOW_ENERGY"); @@ -189,9 +178,7 @@ void TestModel::AddLinkLayerConnection(std::shared_ptr device, AsyncUserId user_id = get_user_id_(); device->RegisterCloseCallback([this, device_id, user_id] { schedule_task_(user_id, std::chrono::milliseconds(0), - [this, device_id, user_id]() { - OnConnectionClosed(device_id, user_id); - }); + [this, device_id, user_id]() { OnConnectionClosed(device_id, user_id); }); }); } @@ -203,8 +190,8 @@ void TestModel::AddRemote(const std::string& server, int port, Phy::Type type) { AddLinkLayerConnection(device, type); } -PhyDevice::Identifier TestModel::AddHciConnection( - std::shared_ptr device, std::optional
address) { +PhyDevice::Identifier TestModel::AddHciConnection(std::shared_ptr device, + std::optional
address) { // clients can specify BD_ADDR or have it set based on device_id. device->SetAddress(address.value_or(GenerateBluetoothAddress(device->id_))); AddDevice(std::static_pointer_cast(device)); @@ -219,23 +206,19 @@ PhyDevice::Identifier TestModel::AddHciConnection( AsyncUserId user_id = get_user_id_(); device->RegisterCloseCallback([this, device_id, user_id] { schedule_task_(user_id, std::chrono::milliseconds(0), - [this, device_id, user_id]() { - OnConnectionClosed(device_id, user_id); - }); + [this, device_id, user_id]() { OnConnectionClosed(device_id, user_id); }); }); return device->id_; } -void TestModel::OnConnectionClosed(PhyDevice::Identifier device_id, - AsyncUserId user_id) { +void TestModel::OnConnectionClosed(PhyDevice::Identifier device_id, AsyncUserId user_id) { if (phy_devices_.find(device_id) != phy_devices_.end()) { cancel_tasks_from_user_(user_id); RemoveDevice(device_id); } } -void TestModel::SetDeviceAddress(PhyDevice::Identifier device_id, - Address address) { +void TestModel::SetDeviceAddress(PhyDevice::Identifier device_id, Address address) { if (phy_devices_.find(device_id) != phy_devices_.end()) { phy_devices_[device_id]->SetAddress(std::move(address)); } @@ -245,8 +228,8 @@ void TestModel::SetDeviceConfiguration(PhyDevice::Identifier device_id, rootcanal::configuration::Controller const& configuration) { if (phy_devices_.find(device_id) != phy_devices_.end()) { if (phy_devices_[device_id]->GetDevice()->GetTypeString() == "hci_device") { - std::shared_ptr device = std::static_pointer_cast( - phy_devices_[device_id]->GetDevice()); + std::shared_ptr device = + std::static_pointer_cast(phy_devices_[device_id]->GetDevice()); device->SetProperties(ControllerProperties(configuration)); } else { ERROR(device_id, "failed to update the configuration, device is not a controller device"); diff --git a/tools/rootcanal/model/setup/test_model.h b/tools/rootcanal/model/setup/test_model.h index b9871a6c620..09996ca3dfe 100644 --- a/tools/rootcanal/model/setup/test_model.h +++ b/tools/rootcanal/model/setup/test_model.h @@ -20,15 +20,15 @@ #include // for size_t #include // for function #include -#include // for shared_ptr -#include // for string -#include // for vector +#include // for shared_ptr #include +#include // for string +#include // for vector -#include "hci/address.h" // for Address -#include "model/devices/hci_device.h" // for HciDevice -#include "model/setup/async_manager.h" // for AsyncUserId, AsyncTaskId -#include "phy.h" // for Phy, Phy::Type +#include "hci/address.h" // for Address +#include "model/devices/hci_device.h" // for HciDevice +#include "model/setup/async_manager.h" // for AsyncUserId, AsyncTaskId +#include "phy.h" // for Phy, Phy::Type #include "phy_layer.h" #include "rootcanal/configuration.pb.h" @@ -38,21 +38,18 @@ class Device; using ::bluetooth::hci::Address; class TestModel { - public: - TestModel( - std::function get_user_id, - std::function - event_scheduler, - std::function - periodic_event_scheduler, - std::function cancel_tasks_from_user, - std::function cancel, - std::function(const std::string&, int, Phy::Type)> - connect_to_remote, - std::array bluetooth_address_prefix = {0xda, 0x4c, 0x10, 0xde, - 0x17}); +public: + TestModel(std::function get_user_id, + std::function + event_scheduler, + std::function + periodic_event_scheduler, + std::function cancel_tasks_from_user, + std::function cancel, + std::function(const std::string&, int, Phy::Type)> + connect_to_remote, + std::array bluetooth_address_prefix = {0xda, 0x4c, 0x10, 0xde, 0x17}); virtual ~TestModel(); TestModel(TestModel& model) = delete; @@ -63,12 +60,11 @@ class TestModel { } // Allow derived classes to use custom phy layer. - virtual std::unique_ptr CreatePhyLayer(PhyLayer::Identifier id, - Phy::Type type); + virtual std::unique_ptr CreatePhyLayer(PhyLayer::Identifier id, Phy::Type type); // Allow derived classes to use custom phy devices. - virtual std::shared_ptr CreatePhyDevice( - std::string type, std::shared_ptr device); + virtual std::shared_ptr CreatePhyDevice(std::string type, + std::shared_ptr device); // Test model commands @@ -76,10 +72,8 @@ class TestModel { void RemoveDevice(PhyDevice::Identifier id); PhyLayer::Identifier AddPhy(Phy::Type type); void RemovePhy(PhyLayer::Identifier id); - void AddDeviceToPhy(PhyDevice::Identifier device_id, - PhyLayer::Identifier phy_id); - void RemoveDeviceFromPhy(PhyDevice::Identifier device_id, - PhyLayer::Identifier phy_id); + void AddDeviceToPhy(PhyDevice::Identifier device_id, PhyLayer::Identifier phy_id); + void RemoveDeviceFromPhy(PhyDevice::Identifier device_id, PhyLayer::Identifier phy_id); // Runtime implementation. @@ -95,8 +89,7 @@ class TestModel { void AddRemote(const std::string& server, int port, Phy::Type phy_type); // Set the device's Bluetooth address - void SetDeviceAddress(PhyDevice::Identifier device_id, - Address device_address); + void SetDeviceAddress(PhyDevice::Identifier device_id, Address device_address); void SetDeviceConfiguration(PhyDevice::Identifier device_id, rootcanal::configuration::Controller const& configuration); @@ -113,7 +106,7 @@ class TestModel { // Clear all devices and phys. void Reset(); - private: +private: Address GenerateBluetoothAddress(uint32_t device_id) const; std::map> phy_layers_; @@ -129,16 +122,14 @@ class TestModel { // Callbacks to schedule tasks. std::function get_user_id_; - std::function + schedule_task_; + std::function - schedule_task_; - std::function - schedule_periodic_task_; + schedule_periodic_task_; std::function cancel_task_; std::function cancel_tasks_from_user_; - std::function(const std::string&, int, Phy::Type)> - connect_to_remote_; + std::function(const std::string&, int, Phy::Type)> connect_to_remote_; AsyncUserId model_user_id_; AsyncTaskId timer_tick_task_{kInvalidTaskId}; diff --git a/tools/rootcanal/net/async_data_channel.h b/tools/rootcanal/net/async_data_channel.h index 3cd3441950b..d2e29635922 100644 --- a/tools/rootcanal/net/async_data_channel.h +++ b/tools/rootcanal/net/async_data_channel.h @@ -41,7 +41,7 @@ using ReadCallback = std::function; // data. Async Sockets are usually non-blocking posix/win sockets, but could be // other types of datachannels (gRPC, qemu pipe) class AsyncDataChannel { - public: +public: virtual ~AsyncDataChannel() = default; // Receive data in the given buffer. Properly handling EINTR where @@ -84,8 +84,7 @@ class AsyncDataChannel { // not return EAGAIN. Returns false if registration of the watcher failed. // // Only one callback can be registered per socket. - virtual bool WatchForNonBlockingRead( - const ReadCallback& on_read_ready_callback) = 0; + virtual bool WatchForNonBlockingRead(const ReadCallback& on_read_ready_callback) = 0; // Stops watching this socket, you will not receive any callbacks any longer. virtual void StopWatching() = 0; diff --git a/tools/rootcanal/net/async_data_channel_connector.h b/tools/rootcanal/net/async_data_channel_connector.h index 5df986223f6..a411785023f 100644 --- a/tools/rootcanal/net/async_data_channel_connector.h +++ b/tools/rootcanal/net/async_data_channel_connector.h @@ -25,7 +25,7 @@ using namespace std::chrono_literals; // An AsyncDataChannelConnector is capable of connecting to a remote server. class AsyncDataChannelConnector { - public: +public: virtual ~AsyncDataChannelConnector() = default; // Blocks and waits until a connection to the remote server has been @@ -36,8 +36,7 @@ class AsyncDataChannelConnector { // In case of a disconnected DataChannel (socket->Connected() == false) // the errno variable can be set with the encountered error. virtual std::shared_ptr ConnectToRemoteServer( - const std::string& server, int port, - std::chrono::milliseconds timeout = 5000ms) = 0; + const std::string& server, int port, std::chrono::milliseconds timeout = 5000ms) = 0; }; } // namespace net } // namespace android diff --git a/tools/rootcanal/net/async_data_channel_server.h b/tools/rootcanal/net/async_data_channel_server.h index 59821ee5d7a..f63deb244c2 100644 --- a/tools/rootcanal/net/async_data_channel_server.h +++ b/tools/rootcanal/net/async_data_channel_server.h @@ -24,14 +24,14 @@ namespace net { class AsyncDataChannelServer; // Callback thas is called when a new client connection has been accepted. -using ConnectCallback = std::function, - AsyncDataChannelServer* server)>; +using ConnectCallback = + std::function, AsyncDataChannelServer* server)>; // An AsyncDataChannelServer is capable of listening to incoming connections. // // A Callback will be invoked whenever a new connection has been accepted. class AsyncDataChannelServer { - public: +public: // Destructor. virtual ~AsyncDataChannelServer() = default; @@ -62,11 +62,9 @@ class AsyncDataChannelServer { // Before the callback the server should have stopped listening for new // incoming connections. The callee is responsible for calling StartListening // if needed. - void SetOnConnectCallback(const ConnectCallback& callback) { - callback_ = callback; - }; + void SetOnConnectCallback(const ConnectCallback& callback) { callback_ = callback; } - protected: +protected: ConnectCallback callback_; }; diff --git a/tools/rootcanal/net/posix/posix_async_socket.cc b/tools/rootcanal/net/posix/posix_async_socket.cc index d6c982e70a1..8ff175ce0ac 100644 --- a/tools/rootcanal/net/posix/posix_async_socket.cc +++ b/tools/rootcanal/net/posix/posix_async_socket.cc @@ -38,8 +38,7 @@ namespace android { namespace net { -PosixAsyncSocket::PosixAsyncSocket(int fd, AsyncManager* am) - : fd_(fd), am_(am), watching_(false) { +PosixAsyncSocket::PosixAsyncSocket(int fd, AsyncManager* am) : fd_(fd), am_(am), watching_(false) { int flags = fcntl(fd, F_GETFL); fcntl(fd, F_SETFL, flags | O_NONBLOCK); @@ -80,7 +79,7 @@ ssize_t PosixAsyncSocket::Recv(uint8_t* buffer, uint64_t bufferSize) { } DD("{} bytes ({})", res, fd_); return res; -}; +} ssize_t PosixAsyncSocket::Send(const uint8_t* buffer, uint64_t bufferSize) { errno = 0; @@ -125,8 +124,7 @@ void PosixAsyncSocket::Close() { // Clear out error int error_code = 0; socklen_t error_code_size = sizeof(error_code); - getsockopt(fd_, SOL_SOCKET, SO_ERROR, reinterpret_cast(&error_code), - &error_code_size); + getsockopt(fd_, SOL_SOCKET, SO_ERROR, reinterpret_cast(&error_code), &error_code_size); // shutdown sockets if possible, REPEAT_UNTIL_NO_INTR(shutdown(fd_, SHUT_RDWR)); @@ -139,14 +137,12 @@ void PosixAsyncSocket::Close() { fd_ = -1; } -bool PosixAsyncSocket::WatchForNonBlockingRead( - const ReadCallback& on_read_ready_callback) { +bool PosixAsyncSocket::WatchForNonBlockingRead(const ReadCallback& on_read_ready_callback) { bool expected = false; if (watching_.compare_exchange_strong(expected, true)) { - return am_->WatchFdForNonBlockingReads( - fd_, [on_read_ready_callback, this](int /* fd */) { - on_read_ready_callback(this); - }) == 0; + return am_->WatchFdForNonBlockingReads(fd_, [on_read_ready_callback, this](int /* fd */) { + on_read_ready_callback(this); + }) == 0; } return false; } diff --git a/tools/rootcanal/net/posix/posix_async_socket.h b/tools/rootcanal/net/posix/posix_async_socket.h index a76a215a517..8fa521371a4 100644 --- a/tools/rootcanal/net/posix/posix_async_socket.h +++ b/tools/rootcanal/net/posix/posix_async_socket.h @@ -32,7 +32,7 @@ using rootcanal::AsyncManager; // // Supports both Darwin and Linux. class PosixAsyncSocket : public AsyncDataChannel { - public: +public: // The AsyncManager must support the following: // // - If a callback happens on thread t, and @@ -69,14 +69,13 @@ class PosixAsyncSocket : public AsyncDataChannel { // Registers the given callback to be invoked when a recv call can be made // to read data from this socket. // Only one callback can be registered per socket. - bool WatchForNonBlockingRead( - const ReadCallback& on_read_ready_callback) override; + bool WatchForNonBlockingRead(const ReadCallback& on_read_ready_callback) override; void StopWatching() override; int fd() const { return fd_; } - private: +private: void OnReadCallback(); int fd_; diff --git a/tools/rootcanal/net/posix/posix_async_socket_connector.cc b/tools/rootcanal/net/posix/posix_async_socket_connector.cc index ed02bc130d9..4b7691a5280 100644 --- a/tools/rootcanal/net/posix/posix_async_socket_connector.cc +++ b/tools/rootcanal/net/posix/posix_async_socket_connector.cc @@ -30,17 +30,13 @@ namespace android { namespace net { -PosixAsyncSocketConnector::PosixAsyncSocketConnector(AsyncManager* am) - : am_(am) {} +PosixAsyncSocketConnector::PosixAsyncSocketConnector(AsyncManager* am) : am_(am) {} -std::shared_ptr -PosixAsyncSocketConnector::ConnectToRemoteServer( - const std::string& server, int port, - const std::chrono::milliseconds timeout) { +std::shared_ptr PosixAsyncSocketConnector::ConnectToRemoteServer( + const std::string& server, int port, const std::chrono::milliseconds timeout) { INFO("Connecting to {}:{} in {} ms", server, port, timeout.count()); int socket_fd = socket(AF_INET, SOCK_STREAM, 0); - std::shared_ptr pas = - std::make_shared(socket_fd, am_); + std::shared_ptr pas = std::make_shared(socket_fd, am_); if (socket_fd < 1) { INFO("socket() call failed: {}", strerror(errno)); @@ -61,32 +57,28 @@ PosixAsyncSocketConnector::ConnectToRemoteServer( serv_addr.sin_addr.s_addr = inet_addr(inet_ntoa(*addr_list[0])); serv_addr.sin_port = htons(port); - int result = - connect(socket_fd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)); + int result = connect(socket_fd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)); - if (result != 0 && errno != EWOULDBLOCK && errno != EAGAIN && - errno != EINPROGRESS) { - INFO("Failed to connect to {}:{}, error: {}", server, port, - strerror(errno)); + if (result != 0 && errno != EWOULDBLOCK && errno != EAGAIN && errno != EINPROGRESS) { + INFO("Failed to connect to {}:{}, error: {}", server, port, strerror(errno)); pas->Close(); return pas; } // wait for the connection. struct pollfd fds[] = { - { - .fd = socket_fd, - .events = POLLIN | POLLOUT | POLLHUP, - .revents = 0, - }, + { + .fd = socket_fd, + .events = POLLIN | POLLOUT | POLLHUP, + .revents = 0, + }, }; int numFdsReady = 0; REPEAT_UNTIL_NO_INTR(numFdsReady = ::poll(fds, 1, timeout.count())); if (numFdsReady <= 0) { - INFO("Failed to connect to {}:{}, error: {}", server, port, - strerror(errno)); + INFO("Failed to connect to {}:{}, error: {}", server, port, strerror(errno)); pas->Close(); return pas; } @@ -97,17 +89,14 @@ PosixAsyncSocketConnector::ConnectToRemoteServer( socklen_t sslen = sizeof(ss); if (getpeername(socket_fd, (struct sockaddr*)&ss, &sslen) < 0) { - INFO("Failed to connect to {}:{}, error: {}", server, port, - strerror(errno)); + INFO("Failed to connect to {}:{}, error: {}", server, port, strerror(errno)); pas->Close(); return pas; } int err = 0; socklen_t optLen = sizeof(err); - if (getsockopt(socket_fd, SOL_SOCKET, SO_ERROR, reinterpret_cast(&err), - &optLen) || - err) { + if (getsockopt(socket_fd, SOL_SOCKET, SO_ERROR, reinterpret_cast(&err), &optLen) || err) { // Either getsockopt failed or there was an error associated // with the socket. The connection did not succeed. INFO("Failed to connect to {}:{}, error: {}", server, port, strerror(err)); diff --git a/tools/rootcanal/net/posix/posix_async_socket_connector.h b/tools/rootcanal/net/posix/posix_async_socket_connector.h index 2bf34319aa1..ea5c5e9fe8b 100644 --- a/tools/rootcanal/net/posix/posix_async_socket_connector.h +++ b/tools/rootcanal/net/posix/posix_async_socket_connector.h @@ -39,7 +39,7 @@ using namespace std::chrono_literals; // // Supports both Darwin (freebsd) and linux. class PosixAsyncSocketConnector : public AsyncDataChannelConnector { - public: +public: PosixAsyncSocketConnector(AsyncManager* am); ~PosixAsyncSocketConnector() = default; @@ -50,10 +50,9 @@ class PosixAsyncSocketConnector : public AsyncDataChannelConnector { // Note: This does not mean that the socket is fully opened! A server // might not (yet?) have called accept on the socket. std::shared_ptr ConnectToRemoteServer( - const std::string& server, int port, - std::chrono::milliseconds timeout = 5000ms); + const std::string& server, int port, std::chrono::milliseconds timeout = 5000ms); - private: +private: AsyncManager* am_; }; } // namespace net diff --git a/tools/rootcanal/net/posix/posix_async_socket_server.cc b/tools/rootcanal/net/posix/posix_async_socket_server.cc index 185f17dd2de..3f20e72f18b 100644 --- a/tools/rootcanal/net/posix/posix_async_socket_server.cc +++ b/tools/rootcanal/net/posix/posix_async_socket_server.cc @@ -30,8 +30,7 @@ namespace android { namespace net { class AsyncDataChannel; -PosixAsyncSocketServer::PosixAsyncSocketServer(int port, AsyncManager* am) - : port_(port), am_(am) { +PosixAsyncSocketServer::PosixAsyncSocketServer(int port, AsyncManager* am) : port_(port), am_(am) { int listen_fd = 0; struct sockaddr_in listen_address {}; socklen_t sockaddr_in_size = sizeof(struct sockaddr_in); @@ -46,8 +45,7 @@ PosixAsyncSocketServer::PosixAsyncSocketServer(int port, AsyncManager* am) } int enable = 1; - if (setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < - 0) { + if (setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < 0) { ERROR("setsockopt(SO_REUSEADDR) failed: {}", strerror(errno)); } @@ -55,10 +53,8 @@ PosixAsyncSocketServer::PosixAsyncSocketServer(int port, AsyncManager* am) listen_address.sin_port = htons(port_); listen_address.sin_addr.s_addr = htonl(INADDR_ANY); - if (bind(listen_fd, reinterpret_cast(&listen_address), - sockaddr_in_size) < 0) { - INFO("Error binding test channel listener socket to port: {}, {}", port, - strerror(errno)); + if (bind(listen_fd, reinterpret_cast(&listen_address), sockaddr_in_size) < 0) { + INFO("Error binding test channel listener socket to port: {}, {}", port, strerror(errno)); close(listen_fd); return; } @@ -86,7 +82,7 @@ bool PosixAsyncSocketServer::StartListening() { } server_socket_->WatchForNonBlockingRead( - [this](AsyncDataChannel* /* socket */) { AcceptSocket(); }); + [this](AsyncDataChannel* /* socket */) { AcceptSocket(); }); return true; } @@ -96,17 +92,14 @@ void PosixAsyncSocketServer::Close() { } } -bool PosixAsyncSocketServer::Connected() { - return server_socket_ && server_socket_->Connected(); -} +bool PosixAsyncSocketServer::Connected() { return server_socket_ && server_socket_->Connected(); } void PosixAsyncSocketServer::AcceptSocket() { int accept_fd = 0; REPEAT_UNTIL_NO_INTR(accept_fd = accept(server_socket_->fd(), NULL, NULL)); if (accept_fd < 0) { - INFO("Error accepting test channel connection errno={} ({}).", errno, - strerror(errno)); + INFO("Error accepting test channel connection errno={} ({}).", errno, strerror(errno)); return; } diff --git a/tools/rootcanal/net/posix/posix_async_socket_server.h b/tools/rootcanal/net/posix/posix_async_socket_server.h index e5d012b9baa..75590adcdbb 100644 --- a/tools/rootcanal/net/posix/posix_async_socket_server.h +++ b/tools/rootcanal/net/posix/posix_async_socket_server.h @@ -33,13 +33,13 @@ namespace net { // // It uses the AsyncManager for watching the socket. class PosixAsyncSocketServer : public AsyncDataChannelServer { - public: +public: // Binds to the given port on all interfaces. // Note: do not use port 0! PosixAsyncSocketServer(int port, AsyncManager* am); // Return the port that this server was initialized with. - int port() const { return port_; }; + int port() const { return port_; } bool StartListening() override; @@ -49,7 +49,7 @@ class PosixAsyncSocketServer : public AsyncDataChannelServer { bool Connected() override; - private: +private: void AcceptSocket(); int port_; diff --git a/tools/rootcanal/rust/include/rootcanal_rs.h b/tools/rootcanal/rust/include/rootcanal_rs.h index 1b395cd6325..e2c7080c41a 100644 --- a/tools/rootcanal/rust/include/rootcanal_rs.h +++ b/tools/rootcanal/rust/include/rootcanal_rs.h @@ -32,10 +32,8 @@ struct ControllerOps { uint64_t (*get_le_features)(void* user); uint64_t (*get_le_event_mask)(void* user); void (*send_hci_event)(void* user, const uint8_t* data, uintptr_t len); - void (*send_lmp_packet)(void* user, const uint8_t (*to)[6], - const uint8_t* data, uintptr_t len); - void (*send_llcp_packet)(void* user, uint16_t handle, const uint8_t* data, - uintptr_t len); + void (*send_lmp_packet)(void* user, const uint8_t (*to)[6], const uint8_t* data, uintptr_t len); + void (*send_llcp_packet)(void* user, uint16_t handle, const uint8_t* data, uintptr_t len); }; extern "C" { @@ -84,8 +82,7 @@ void link_manager_tick(const LinkManager* lm); /// - This should be called from the thread of creation /// - `lm` must be a valid pointer /// - `data` must be valid for reads of len `len` -bool link_manager_ingest_hci(const LinkManager* lm, const uint8_t* data, - uintptr_t len); +bool link_manager_ingest_hci(const LinkManager* lm, const uint8_t* data, uintptr_t len); /// Process an LMP packet from a peer with the link manager /// Returns true if successful @@ -99,8 +96,8 @@ bool link_manager_ingest_hci(const LinkManager* lm, const uint8_t* data, /// - `lm` must be a valid pointers /// - `from` must be valid pointer for reads for 6 bytes /// - `data` must be valid for reads of len `len` -bool link_manager_ingest_lmp(const LinkManager* lm, const uint8_t (*from)[6], - const uint8_t* data, uintptr_t len); +bool link_manager_ingest_lmp(const LinkManager* lm, const uint8_t (*from)[6], const uint8_t* data, + uintptr_t len); /// Deallocate the link manager instance /// # Arguments @@ -126,8 +123,8 @@ const LinkLayer* link_layer_create(ControllerOps ops); /// - `ll` must be a valid pointer /// - `peer` must be valid for reads for 6 bytes /// - `role` must be 0 (central) or 1 (peripheral) -bool link_layer_add_link(const LinkLayer* ll, uint16_t handle, - const uint8_t (*peer_address)[6], uint8_t role); +bool link_layer_add_link(const LinkLayer* ll, uint16_t handle, const uint8_t (*peer_address)[6], + uint8_t role); /// Unregister a link with a peer inside the link layer /// Returns true if successful @@ -158,8 +155,7 @@ void link_layer_tick(const LinkLayer* ll); /// - This should be called from the thread of creation /// - `ll` must be a valid pointer /// - `data` must be valid for reads of len `len` -bool link_layer_ingest_hci(const LinkLayer* ll, const uint8_t* data, - uintptr_t len); +bool link_layer_ingest_hci(const LinkLayer* ll, const uint8_t* data, uintptr_t len); /// Process an LLCP packet from a peer with the link layer /// Returns true if successful @@ -172,8 +168,8 @@ bool link_layer_ingest_hci(const LinkLayer* ll, const uint8_t* data, /// - This should be called from the thread of creation /// - `ll` must be a valid pointers /// - `data` must be valid for reads of len `len` -bool link_layer_ingest_llcp(const LinkLayer* ll, uint16_t handle, - const uint8_t* data, uintptr_t len); +bool link_layer_ingest_llcp(const LinkLayer* ll, uint16_t handle, const uint8_t* data, + uintptr_t len); /// Query the connection handle for a CIS established with /// the input CIS and CIG identifiers. @@ -186,8 +182,7 @@ bool link_layer_ingest_llcp(const LinkLayer* ll, uint16_t handle, /// # Safety /// - This should be called from the thread of creation /// - `ll` must be a valid pointers -bool link_layer_get_cis_connection_handle(const LinkLayer* ll, uint8_t cig_id, - uint8_t cis_id, +bool link_layer_get_cis_connection_handle(const LinkLayer* ll, uint8_t cig_id, uint8_t cis_id, uint16_t* cis_connection_handle); /// Query the CIS and CIG identifiers for a CIS established with @@ -201,11 +196,9 @@ bool link_layer_get_cis_connection_handle(const LinkLayer* ll, uint8_t cig_id, /// # Safety /// - This should be called from the thread of creation /// - `ll` must be a valid pointers -bool link_layer_get_cis_information(const LinkLayer* ll, - uint16_t cis_connection_handle, - uint16_t* acl_connection_handle, - uint8_t* cig_id, uint8_t* cis_id, - uint16_t* max_sdu_tx); +bool link_layer_get_cis_information(const LinkLayer* ll, uint16_t cis_connection_handle, + uint16_t* acl_connection_handle, uint8_t* cig_id, + uint8_t* cis_id, uint16_t* max_sdu_tx); /// Deallocate the link layer instance /// # Arguments diff --git a/tools/rootcanal/test/async_manager_unittest.cc b/tools/rootcanal/test/async_manager_unittest.cc index b461b9a44e4..dd3f366d3dd 100644 --- a/tools/rootcanal/test/async_manager_unittest.cc +++ b/tools/rootcanal/test/async_manager_unittest.cc @@ -38,7 +38,7 @@ namespace rootcanal { class Event { - public: +public: void set(bool set = true) { std::unique_lock lk(m_); set_ = set; @@ -54,22 +54,20 @@ class Event { bool operator*() { return set_; } - private: +private: std::mutex m_; std::condition_variable cv_; bool set_{false}; }; class AsyncManagerSocketTest : public ::testing::Test { - public: +public: static const uint16_t kPort = 6111; static const size_t kBufferSize = 16; - bool CheckBufferEquals() { - return strcmp(server_buffer_, client_buffer_) == 0; - } + bool CheckBufferEquals() { return strcmp(server_buffer_, client_buffer_) == 0; } - protected: +protected: int StartServer() { struct sockaddr_in serv_addr = {}; int fd = socket(AF_INET, SOCK_STREAM, 0); @@ -79,8 +77,7 @@ class AsyncManagerSocketTest : public ::testing::Test { serv_addr.sin_addr.s_addr = INADDR_ANY; serv_addr.sin_port = htons(kPort); int reuse_flag = 1; - EXPECT_FALSE(setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse_flag, - sizeof(reuse_flag)) < 0); + EXPECT_FALSE(setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse_flag, sizeof(reuse_flag)) < 0); EXPECT_FALSE(bind(fd, (sockaddr*)&serv_addr, sizeof(serv_addr)) < 0); listen(fd, 1); @@ -134,8 +131,8 @@ class AsyncManagerSocketTest : public ::testing::Test { async_manager_.WatchFdForNonBlockingReads(socket_fd_, [this](int fd) { connection_fd_ = AcceptConnection(fd); - async_manager_.WatchFdForNonBlockingReads( - connection_fd_, [this](int fd) { ReadIncomingMessage(fd); }); + async_manager_.WatchFdForNonBlockingReads(connection_fd_, + [this](int fd) { ReadIncomingMessage(fd); }); }); } @@ -161,8 +158,7 @@ class AsyncManagerSocketTest : public ::testing::Test { serv_addr.sin_addr.s_addr = *(reinterpret_cast(server->h_addr)); serv_addr.sin_port = htons(kPort); - int result = - connect(socket_cli_fd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)); + int result = connect(socket_cli_fd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)); EXPECT_GE(result, 0) << strerror(errno); return socket_cli_fd; @@ -179,7 +175,7 @@ class AsyncManagerSocketTest : public ::testing::Test { ASSERT_GT(n, 0) << strerror(errno); } - protected: +protected: AsyncManager async_manager_; int socket_fd_; int connection_fd_; @@ -230,9 +226,9 @@ TEST_F(AsyncManagerSocketTest, CanUnsubscribeTaskFromWithinTask) { using namespace std::chrono_literals; async_manager_.ExecAsyncPeriodically(1, 1ms, 2ms, [&running, this]() { EXPECT_TRUE(async_manager_.CancelAsyncTask(1)) - << "We were scheduled, so cancel should return true"; + << "We were scheduled, so cancel should return true"; EXPECT_FALSE(async_manager_.CancelAsyncTask(1)) - << "We were not scheduled, so cancel should return false"; + << "We were not scheduled, so cancel should return false"; running.set(true); }); @@ -245,28 +241,26 @@ TEST_F(AsyncManagerSocketTest, UnsubScribeWaitsUntilCompletion) { std::atomic cancel_done = false; std::atomic task_complete = false; AsyncTaskId task_id = async_manager_.ExecAsyncPeriodically( - 1, 1ms, 2ms, [&running, &cancel_done, &task_complete]() { - // Let the other thread now we are in the callback.. - running.set(true); - // Wee bit of a hack that relies on timing.. - std::this_thread::sleep_for(20ms); - EXPECT_FALSE(cancel_done.load()) - << "Task cancellation did not wait for us to complete!"; - task_complete.store(true); - }); + 1, 1ms, 2ms, [&running, &cancel_done, &task_complete]() { + // Let the other thread now we are in the callback.. + running.set(true); + // Wee bit of a hack that relies on timing.. + std::this_thread::sleep_for(20ms); + EXPECT_FALSE(cancel_done.load()) + << "Task cancellation did not wait for us to complete!"; + task_complete.store(true); + }); EXPECT_TRUE(running.wait_for(100ms)); auto start = std::chrono::system_clock::now(); // There is a 20ms wait.. so we know that this should take some time. EXPECT_TRUE(async_manager_.CancelAsyncTask(task_id)) - << "We were scheduled, so cancel should return true"; + << "We were scheduled, so cancel should return true"; cancel_done.store(true); - EXPECT_TRUE(task_complete.load()) - << "We managed to cancel a task while it was not yet finished."; + EXPECT_TRUE(task_complete.load()) << "We managed to cancel a task while it was not yet finished."; auto end = std::chrono::system_clock::now(); - auto passed_ms = - std::chrono::duration_cast(end - start); + auto passed_ms = std::chrono::duration_cast(end - start); EXPECT_GT(passed_ms.count(), 10); } @@ -336,19 +330,21 @@ TEST_F(AsyncManagerSocketTest, NoEventsAfterUnsubscribe) { // Register fd events async_manager_.WatchFdForNonBlockingReads(slow_s_fd, [&](int /*fd*/) { - if (*inslow) return; + if (*inslow) { + return; + } time_slow_called = clock::now(); - printf("slow: %lld\n", - time_slow_called.time_since_epoch().count() % 10000); + printf("slow: %lld\n", time_slow_called.time_since_epoch().count() % 10000); inslow.set(); unblock_slow.wait_for(25ms); }); async_manager_.WatchFdForNonBlockingReads(fast_s_fd, [&](int /*fd*/) { - if (*infast) return; + if (*infast) { + return; + } time_fast_called = clock::now(); - printf("fast: %lld\n", - time_fast_called.time_since_epoch().count() % 10000); + printf("fast: %lld\n", time_fast_called.time_since_epoch().count() % 10000); infast.set(); }); @@ -360,8 +356,7 @@ TEST_F(AsyncManagerSocketTest, NoEventsAfterUnsubscribe) { if (inslow.wait_for(25ms)) { async_manager_.StopWatchingFileDescriptor(fast_s_fd); time_stopped_listening = clock::now(); - printf("stop: %lld\n", - time_stopped_listening.time_since_epoch().count() % 10000); + printf("stop: %lld\n", time_stopped_listening.time_since_epoch().count() % 10000); unblock_slow.set(); } @@ -408,7 +403,7 @@ TEST_F(AsyncManagerSocketTest, TestMultipleConnections) { } class AsyncManagerTest : public ::testing::Test { - public: +public: AsyncManager async_manager_; }; @@ -418,9 +413,8 @@ TEST_F(AsyncManagerTest, TestCancelTask) { AsyncUserId user1 = async_manager_.GetNextUserId(); bool task1_ran = false; bool* task1_ran_ptr = &task1_ran; - AsyncTaskId task1_id = - async_manager_.ExecAsync(user1, std::chrono::milliseconds(2), - [task1_ran_ptr]() { *task1_ran_ptr = true; }); + AsyncTaskId task1_id = async_manager_.ExecAsync(user1, std::chrono::milliseconds(2), + [task1_ran_ptr]() { *task1_ran_ptr = true; }); ASSERT_TRUE(async_manager_.CancelAsyncTask(task1_id)); ASSERT_FALSE(task1_ran); } @@ -429,14 +423,12 @@ TEST_F(AsyncManagerTest, TestCancelLongTask) { AsyncUserId user1 = async_manager_.GetNextUserId(); bool task1_ran = false; bool* task1_ran_ptr = &task1_ran; - AsyncTaskId task1_id = - async_manager_.ExecAsync(user1, std::chrono::milliseconds(2), - [task1_ran_ptr]() { *task1_ran_ptr = true; }); + AsyncTaskId task1_id = async_manager_.ExecAsync(user1, std::chrono::milliseconds(2), + [task1_ran_ptr]() { *task1_ran_ptr = true; }); bool task2_ran = false; bool* task2_ran_ptr = &task2_ran; - AsyncTaskId task2_id = - async_manager_.ExecAsync(user1, std::chrono::seconds(2), - [task2_ran_ptr]() { *task2_ran_ptr = true; }); + AsyncTaskId task2_id = async_manager_.ExecAsync(user1, std::chrono::seconds(2), + [task2_ran_ptr]() { *task2_ran_ptr = true; }); ASSERT_FALSE(task1_ran); ASSERT_FALSE(task2_ran); while (!task1_ran) @@ -459,21 +451,16 @@ TEST_F(AsyncManagerTest, TestCancelAsyncTasksFromUser) { bool* task4_ran_ptr = &task4_ran; bool task5_ran = false; bool* task5_ran_ptr = &task5_ran; - AsyncTaskId task1_id = - async_manager_.ExecAsync(user1, std::chrono::milliseconds(2), - [task1_ran_ptr]() { *task1_ran_ptr = true; }); - AsyncTaskId task2_id = - async_manager_.ExecAsync(user1, std::chrono::seconds(2), - [task2_ran_ptr]() { *task2_ran_ptr = true; }); - AsyncTaskId task3_id = - async_manager_.ExecAsync(user1, std::chrono::milliseconds(2), - [task3_ran_ptr]() { *task3_ran_ptr = true; }); - AsyncTaskId task4_id = - async_manager_.ExecAsync(user1, std::chrono::seconds(2), - [task4_ran_ptr]() { *task4_ran_ptr = true; }); - AsyncTaskId task5_id = - async_manager_.ExecAsync(user2, std::chrono::milliseconds(2), - [task5_ran_ptr]() { *task5_ran_ptr = true; }); + AsyncTaskId task1_id = async_manager_.ExecAsync(user1, std::chrono::milliseconds(2), + [task1_ran_ptr]() { *task1_ran_ptr = true; }); + AsyncTaskId task2_id = async_manager_.ExecAsync(user1, std::chrono::seconds(2), + [task2_ran_ptr]() { *task2_ran_ptr = true; }); + AsyncTaskId task3_id = async_manager_.ExecAsync(user1, std::chrono::milliseconds(2), + [task3_ran_ptr]() { *task3_ran_ptr = true; }); + AsyncTaskId task4_id = async_manager_.ExecAsync(user1, std::chrono::seconds(2), + [task4_ran_ptr]() { *task4_ran_ptr = true; }); + AsyncTaskId task5_id = async_manager_.ExecAsync(user2, std::chrono::milliseconds(2), + [task5_ran_ptr]() { *task5_ran_ptr = true; }); ASSERT_FALSE(task1_ran); while (!task1_ran || !task3_ran || !task5_ran) ; diff --git a/tools/rootcanal/test/controller/le/le_add_device_to_filter_accept_list_test.cc b/tools/rootcanal/test/controller/le/le_add_device_to_filter_accept_list_test.cc index e99930818b8..fe5b0c69754 100644 --- a/tools/rootcanal/test/controller/le/le_add_device_to_filter_accept_list_test.cc +++ b/tools/rootcanal/test/controller/le/le_add_device_to_filter_accept_list_test.cc @@ -24,7 +24,7 @@ namespace rootcanal { using namespace bluetooth::hci; class LeAddDeviceToFilterAcceptListTest : public ::testing::Test { - public: +public: LeAddDeviceToFilterAcceptListTest() { // Reduce the size of the filter accept list to simplify testing. properties_.le_filter_accept_list_size = 2; @@ -32,75 +32,73 @@ class LeAddDeviceToFilterAcceptListTest : public ::testing::Test { ~LeAddDeviceToFilterAcceptListTest() override = default; - protected: +protected: Address address_{0}; ControllerProperties properties_{}; LinkLayerController controller_{address_, properties_}; }; TEST_F(LeAddDeviceToFilterAcceptListTest, Success) { - ASSERT_EQ(controller_.LeAddDeviceToFilterAcceptList( - FilterAcceptListAddressType::PUBLIC, Address{1}), + ASSERT_EQ(controller_.LeAddDeviceToFilterAcceptList(FilterAcceptListAddressType::PUBLIC, + Address{1}), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeAddDeviceToFilterAcceptList( - FilterAcceptListAddressType::RANDOM, Address{1}), + ASSERT_EQ(controller_.LeAddDeviceToFilterAcceptList(FilterAcceptListAddressType::RANDOM, + Address{1}), ErrorCode::SUCCESS); } TEST_F(LeAddDeviceToFilterAcceptListTest, ListFull) { - ASSERT_EQ(controller_.LeAddDeviceToFilterAcceptList( - FilterAcceptListAddressType::PUBLIC, Address{1}), + ASSERT_EQ(controller_.LeAddDeviceToFilterAcceptList(FilterAcceptListAddressType::PUBLIC, + Address{1}), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeAddDeviceToFilterAcceptList( - FilterAcceptListAddressType::PUBLIC, Address{2}), + ASSERT_EQ(controller_.LeAddDeviceToFilterAcceptList(FilterAcceptListAddressType::PUBLIC, + Address{2}), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeAddDeviceToFilterAcceptList( - FilterAcceptListAddressType::PUBLIC, Address{3}), + ASSERT_EQ(controller_.LeAddDeviceToFilterAcceptList(FilterAcceptListAddressType::PUBLIC, + Address{3}), ErrorCode::MEMORY_CAPACITY_EXCEEDED); } TEST_F(LeAddDeviceToFilterAcceptListTest, ScanningActive) { - controller_.LeSetScanParameters( - LeScanType::PASSIVE, 0x400, 0x200, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - LeScanningFilterPolicy::FILTER_ACCEPT_LIST_ONLY); + controller_.LeSetScanParameters(LeScanType::PASSIVE, 0x400, 0x200, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + LeScanningFilterPolicy::FILTER_ACCEPT_LIST_ONLY); controller_.LeSetScanEnable(true, false); - ASSERT_EQ(controller_.LeAddDeviceToFilterAcceptList( - FilterAcceptListAddressType::PUBLIC, Address{1}), + ASSERT_EQ(controller_.LeAddDeviceToFilterAcceptList(FilterAcceptListAddressType::PUBLIC, + Address{1}), ErrorCode::COMMAND_DISALLOWED); } TEST_F(LeAddDeviceToFilterAcceptListTest, LegacyAdvertisingActive) { ASSERT_EQ(controller_.LeSetAdvertisingParameters( - 0x0800, 0x0800, AdvertisingType::ADV_IND, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, 0x7, AdvertisingFilterPolicy::LISTED_SCAN), + 0x0800, 0x0800, AdvertisingType::ADV_IND, OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, 0x7, + AdvertisingFilterPolicy::LISTED_SCAN), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeSetAdvertisingEnable(true), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeAddDeviceToFilterAcceptList( - FilterAcceptListAddressType::PUBLIC, Address{1}), + ASSERT_EQ(controller_.LeAddDeviceToFilterAcceptList(FilterAcceptListAddressType::PUBLIC, + Address{1}), ErrorCode::COMMAND_DISALLOWED); } TEST_F(LeAddDeviceToFilterAcceptListTest, ExtendedAdvertisingActive) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, - 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::LISTED_SCAN, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::LISTED_SCAN, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable( - true, {MakeEnabledSet(0, 0, 0)}), + ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable(true, {MakeEnabledSet(0, 0, 0)}), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeAddDeviceToFilterAcceptList( - FilterAcceptListAddressType::PUBLIC, Address{1}), + ASSERT_EQ(controller_.LeAddDeviceToFilterAcceptList(FilterAcceptListAddressType::PUBLIC, + Address{1}), ErrorCode::COMMAND_DISALLOWED); } diff --git a/tools/rootcanal/test/controller/le/le_add_device_to_periodic_advertiser_list_test.cc b/tools/rootcanal/test/controller/le/le_add_device_to_periodic_advertiser_list_test.cc index cade4d97335..94212f8d3b1 100644 --- a/tools/rootcanal/test/controller/le/le_add_device_to_periodic_advertiser_list_test.cc +++ b/tools/rootcanal/test/controller/le/le_add_device_to_periodic_advertiser_list_test.cc @@ -24,7 +24,7 @@ namespace rootcanal { using namespace bluetooth::hci; class LeAddDeviceToPeriodicAdvertiserListTest : public ::testing::Test { - public: +public: LeAddDeviceToPeriodicAdvertiserListTest() { // Reduce the size of the periodic advertiser list to simplify testing. properties_.le_periodic_advertiser_list_size = 3; @@ -32,7 +32,7 @@ class LeAddDeviceToPeriodicAdvertiserListTest : public ::testing::Test { ~LeAddDeviceToPeriodicAdvertiserListTest() override = default; - protected: +protected: Address address_{0}; ControllerProperties properties_{}; LinkLayerController controller_{address_, properties_}; @@ -40,65 +40,55 @@ class LeAddDeviceToPeriodicAdvertiserListTest : public ::testing::Test { TEST_F(LeAddDeviceToPeriodicAdvertiserListTest, Success) { ASSERT_EQ(controller_.LeAddDeviceToPeriodicAdvertiserList( - AdvertiserAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address{1}, 1), + AdvertiserAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, 1), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeAddDeviceToPeriodicAdvertiserList( - AdvertiserAddressType::RANDOM_DEVICE_OR_IDENTITY_ADDRESS, - Address{1}, 1), + AdvertiserAddressType::RANDOM_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, 1), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeAddDeviceToPeriodicAdvertiserList( - AdvertiserAddressType::RANDOM_DEVICE_OR_IDENTITY_ADDRESS, - Address{1}, 2), + AdvertiserAddressType::RANDOM_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, 2), ErrorCode::SUCCESS); } TEST_F(LeAddDeviceToPeriodicAdvertiserListTest, ListFull) { ASSERT_EQ(controller_.LeAddDeviceToPeriodicAdvertiserList( - AdvertiserAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address{1}, 1), + AdvertiserAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, 1), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeAddDeviceToPeriodicAdvertiserList( - AdvertiserAddressType::RANDOM_DEVICE_OR_IDENTITY_ADDRESS, - Address{1}, 1), + AdvertiserAddressType::RANDOM_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, 1), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeAddDeviceToPeriodicAdvertiserList( - AdvertiserAddressType::RANDOM_DEVICE_OR_IDENTITY_ADDRESS, - Address{1}, 2), + AdvertiserAddressType::RANDOM_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, 2), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeAddDeviceToPeriodicAdvertiserList( - AdvertiserAddressType::RANDOM_DEVICE_OR_IDENTITY_ADDRESS, - Address{1}, 3), + AdvertiserAddressType::RANDOM_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, 3), ErrorCode::MEMORY_CAPACITY_EXCEEDED); } TEST_F(LeAddDeviceToPeriodicAdvertiserListTest, DuplicateEntry) { ASSERT_EQ(controller_.LeAddDeviceToPeriodicAdvertiserList( - AdvertiserAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address{1}, 1), + AdvertiserAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, 1), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeAddDeviceToPeriodicAdvertiserList( - AdvertiserAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address{1}, 1), + AdvertiserAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, 1), ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); } TEST_F(LeAddDeviceToPeriodicAdvertiserListTest, CreateSyncPending) { ASSERT_EQ(controller_.LePeriodicAdvertisingCreateSync( - PeriodicAdvertisingOptions(), 0, - AdvertiserAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address{5}, false, 0x100, 0), + PeriodicAdvertisingOptions(), 0, + AdvertiserAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{5}, false, + 0x100, 0), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeAddDeviceToPeriodicAdvertiserList( - AdvertiserAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address{1}, 1), + AdvertiserAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, 1), ErrorCode::COMMAND_DISALLOWED); } diff --git a/tools/rootcanal/test/controller/le/le_add_device_to_resolving_list_test.cc b/tools/rootcanal/test/controller/le/le_add_device_to_resolving_list_test.cc index b2a44d4812e..050a70a5206 100644 --- a/tools/rootcanal/test/controller/le/le_add_device_to_resolving_list_test.cc +++ b/tools/rootcanal/test/controller/le/le_add_device_to_resolving_list_test.cc @@ -24,7 +24,7 @@ namespace rootcanal { using namespace bluetooth::hci; class LeAddDeviceToResolvingListTest : public ::testing::Test { - public: +public: LeAddDeviceToResolvingListTest() { // Reduce the size of the resolving list to simplify testing. properties_.le_resolving_list_size = 2; @@ -32,7 +32,7 @@ class LeAddDeviceToResolvingListTest : public ::testing::Test { ~LeAddDeviceToResolvingListTest() override = default; - protected: +protected: Address address_{0}; ControllerProperties properties_{}; LinkLayerController controller_{address_, properties_}; @@ -40,30 +40,30 @@ class LeAddDeviceToResolvingListTest : public ::testing::Test { TEST_F(LeAddDeviceToResolvingListTest, Success) { ASSERT_EQ(controller_.LeAddDeviceToResolvingList( - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, - std::array{1}, std::array{1}), + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, + std::array{1}, std::array{1}), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeAddDeviceToResolvingList( - PeerAddressType::RANDOM_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, - std::array{2}, std::array{2}), + PeerAddressType::RANDOM_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, + std::array{2}, std::array{2}), ErrorCode::SUCCESS); } TEST_F(LeAddDeviceToResolvingListTest, ListFull) { ASSERT_EQ(controller_.LeAddDeviceToResolvingList( - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, - std::array{1}, std::array{1}), + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, + std::array{1}, std::array{1}), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeAddDeviceToResolvingList( - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{2}, - std::array{2}, std::array{2}), + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{2}, + std::array{2}, std::array{2}), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeAddDeviceToResolvingList( - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{3}, - std::array{3}, std::array{3}), + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{3}, + std::array{3}, std::array{3}), ErrorCode::MEMORY_CAPACITY_EXCEEDED); } @@ -72,8 +72,8 @@ TEST_F(LeAddDeviceToResolvingListTest, ScanningActive) { controller_.LeSetScanEnable(true, false); ASSERT_EQ(controller_.LeAddDeviceToResolvingList( - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, - std::array{1}, std::array{1}), + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, + std::array{1}, std::array{1}), ErrorCode::COMMAND_DISALLOWED); } @@ -82,63 +82,62 @@ TEST_F(LeAddDeviceToResolvingListTest, LegacyAdvertisingActive) { ASSERT_EQ(controller_.LeSetAdvertisingEnable(true), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeAddDeviceToResolvingList( - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, - std::array{1}, std::array{1}), + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, + std::array{1}, std::array{1}), ErrorCode::COMMAND_DISALLOWED); } TEST_F(LeAddDeviceToResolvingListTest, ExtendedAdvertisingActive) { ASSERT_EQ(controller_.LeSetAddressResolutionEnable(true), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, - 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::LISTED_SCAN, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::LISTED_SCAN, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable( - true, {MakeEnabledSet(0, 0, 0)}), + ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable(true, {MakeEnabledSet(0, 0, 0)}), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeAddDeviceToResolvingList( - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, - std::array{1}, std::array{1}), + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, + std::array{1}, std::array{1}), ErrorCode::COMMAND_DISALLOWED); } TEST_F(LeAddDeviceToResolvingListTest, PeerAddressDuplicate) { ASSERT_EQ(controller_.LeAddDeviceToResolvingList( - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, - std::array{1}, std::array{1}), + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, + std::array{1}, std::array{1}), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeAddDeviceToResolvingList( - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, - std::array{2}, std::array{2}), + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, + std::array{2}, std::array{2}), ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); } TEST_F(LeAddDeviceToResolvingListTest, PeerIrkDuplicate) { ASSERT_EQ(controller_.LeAddDeviceToResolvingList( - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, - std::array{1}, std::array{1}), + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, + std::array{1}, std::array{1}), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeAddDeviceToResolvingList( - PeerAddressType::RANDOM_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, - std::array{1}, std::array{1}), + PeerAddressType::RANDOM_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, + std::array{1}, std::array{1}), ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); } TEST_F(LeAddDeviceToResolvingListTest, EmptyPeerIrkDuplicate) { ASSERT_EQ(controller_.LeAddDeviceToResolvingList( - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, - std::array{0}, std::array{1}), + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, + std::array{0}, std::array{1}), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeAddDeviceToResolvingList( - PeerAddressType::RANDOM_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, - std::array{0}, std::array{1}), + PeerAddressType::RANDOM_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, + std::array{0}, std::array{1}), ErrorCode::SUCCESS); } diff --git a/tools/rootcanal/test/controller/le/le_clear_filter_accept_list_test.cc b/tools/rootcanal/test/controller/le/le_clear_filter_accept_list_test.cc index 30eb1b09aa5..b7d8fb86303 100644 --- a/tools/rootcanal/test/controller/le/le_clear_filter_accept_list_test.cc +++ b/tools/rootcanal/test/controller/le/le_clear_filter_accept_list_test.cc @@ -24,7 +24,7 @@ namespace rootcanal { using namespace bluetooth::hci; class LeClearFilterAcceptListTest : public ::testing::Test { - public: +public: LeClearFilterAcceptListTest() { // Reduce the size of the filter accept list to simplify testing. properties_.le_filter_accept_list_size = 2; @@ -32,69 +32,64 @@ class LeClearFilterAcceptListTest : public ::testing::Test { ~LeClearFilterAcceptListTest() override = default; - protected: +protected: Address address_{0}; ControllerProperties properties_{}; LinkLayerController controller_{address_, properties_}; }; TEST_F(LeClearFilterAcceptListTest, Success) { - ASSERT_EQ(controller_.LeAddDeviceToFilterAcceptList( - FilterAcceptListAddressType::PUBLIC, Address{1}), + ASSERT_EQ(controller_.LeAddDeviceToFilterAcceptList(FilterAcceptListAddressType::PUBLIC, + Address{1}), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeClearFilterAcceptList(), ErrorCode::SUCCESS); } TEST_F(LeClearFilterAcceptListTest, ScanningActive) { - ASSERT_EQ(controller_.LeAddDeviceToFilterAcceptList( - FilterAcceptListAddressType::PUBLIC, Address{1}), + ASSERT_EQ(controller_.LeAddDeviceToFilterAcceptList(FilterAcceptListAddressType::PUBLIC, + Address{1}), ErrorCode::SUCCESS); - controller_.LeSetScanParameters( - LeScanType::PASSIVE, 0x400, 0x200, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - LeScanningFilterPolicy::FILTER_ACCEPT_LIST_ONLY); + controller_.LeSetScanParameters(LeScanType::PASSIVE, 0x400, 0x200, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + LeScanningFilterPolicy::FILTER_ACCEPT_LIST_ONLY); controller_.LeSetScanEnable(true, false); - ASSERT_EQ(controller_.LeClearFilterAcceptList(), - ErrorCode::COMMAND_DISALLOWED); + ASSERT_EQ(controller_.LeClearFilterAcceptList(), ErrorCode::COMMAND_DISALLOWED); } TEST_F(LeClearFilterAcceptListTest, LegacyAdvertisingActive) { - ASSERT_EQ(controller_.LeAddDeviceToFilterAcceptList( - FilterAcceptListAddressType::PUBLIC, Address{1}), + ASSERT_EQ(controller_.LeAddDeviceToFilterAcceptList(FilterAcceptListAddressType::PUBLIC, + Address{1}), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeSetAdvertisingParameters( - 0x0800, 0x0800, AdvertisingType::ADV_IND, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, 0x7, AdvertisingFilterPolicy::LISTED_SCAN), + 0x0800, 0x0800, AdvertisingType::ADV_IND, OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, 0x7, + AdvertisingFilterPolicy::LISTED_SCAN), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeSetAdvertisingEnable(true), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeClearFilterAcceptList(), - ErrorCode::COMMAND_DISALLOWED); + ASSERT_EQ(controller_.LeClearFilterAcceptList(), ErrorCode::COMMAND_DISALLOWED); } TEST_F(LeClearFilterAcceptListTest, ExtendedAdvertisingActive) { - ASSERT_EQ(controller_.LeAddDeviceToFilterAcceptList( - FilterAcceptListAddressType::PUBLIC, Address{1}), + ASSERT_EQ(controller_.LeAddDeviceToFilterAcceptList(FilterAcceptListAddressType::PUBLIC, + Address{1}), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, - 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::LISTED_SCAN, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::LISTED_SCAN, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable( - true, {MakeEnabledSet(0, 0, 0)}), + ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable(true, {MakeEnabledSet(0, 0, 0)}), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeClearFilterAcceptList(), - ErrorCode::COMMAND_DISALLOWED); + ASSERT_EQ(controller_.LeClearFilterAcceptList(), ErrorCode::COMMAND_DISALLOWED); } } // namespace rootcanal diff --git a/tools/rootcanal/test/controller/le/le_clear_periodic_advertiser_list_test.cc b/tools/rootcanal/test/controller/le/le_clear_periodic_advertiser_list_test.cc index 9d4f347e10c..a2e7d50a58e 100644 --- a/tools/rootcanal/test/controller/le/le_clear_periodic_advertiser_list_test.cc +++ b/tools/rootcanal/test/controller/le/le_clear_periodic_advertiser_list_test.cc @@ -24,7 +24,7 @@ namespace rootcanal { using namespace bluetooth::hci; class LeClearPeriodicAdvertiserListTest : public ::testing::Test { - public: +public: LeClearPeriodicAdvertiserListTest() { // Reduce the size of the periodic advertiser list to simplify testing. properties_.le_periodic_advertiser_list_size = 1; @@ -32,7 +32,7 @@ class LeClearPeriodicAdvertiserListTest : public ::testing::Test { ~LeClearPeriodicAdvertiserListTest() override = default; - protected: +protected: Address address_{0}; ControllerProperties properties_{}; LinkLayerController controller_{address_, properties_}; @@ -40,27 +40,24 @@ class LeClearPeriodicAdvertiserListTest : public ::testing::Test { TEST_F(LeClearPeriodicAdvertiserListTest, Success) { ASSERT_EQ(controller_.LeAddDeviceToPeriodicAdvertiserList( - AdvertiserAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address{1}, 1), + AdvertiserAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, 1), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeClearPeriodicAdvertiserList(), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeAddDeviceToPeriodicAdvertiserList( - AdvertiserAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address{1}, 1), + AdvertiserAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, 1), ErrorCode::SUCCESS); } TEST_F(LeClearPeriodicAdvertiserListTest, CreateSyncPending) { ASSERT_EQ(controller_.LePeriodicAdvertisingCreateSync( - PeriodicAdvertisingOptions(), 0, - AdvertiserAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address{5}, false, 0x100, 0), + PeriodicAdvertisingOptions(), 0, + AdvertiserAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{5}, false, + 0x100, 0), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeClearPeriodicAdvertiserList(), - ErrorCode::COMMAND_DISALLOWED); + ASSERT_EQ(controller_.LeClearPeriodicAdvertiserList(), ErrorCode::COMMAND_DISALLOWED); } } // namespace rootcanal diff --git a/tools/rootcanal/test/controller/le/le_clear_resolving_list_test.cc b/tools/rootcanal/test/controller/le/le_clear_resolving_list_test.cc index ea37d1c982f..98914a5da9e 100644 --- a/tools/rootcanal/test/controller/le/le_clear_resolving_list_test.cc +++ b/tools/rootcanal/test/controller/le/le_clear_resolving_list_test.cc @@ -24,7 +24,7 @@ namespace rootcanal { using namespace bluetooth::hci; class LeClearResolvingListTest : public ::testing::Test { - public: +public: LeClearResolvingListTest() { // Reduce the size of the resolving list to simplify testing. properties_.le_resolving_list_size = 2; @@ -32,7 +32,7 @@ class LeClearResolvingListTest : public ::testing::Test { ~LeClearResolvingListTest() override = default; - protected: +protected: Address address_{0}; ControllerProperties properties_{}; LinkLayerController controller_{address_, properties_}; @@ -40,8 +40,8 @@ class LeClearResolvingListTest : public ::testing::Test { TEST_F(LeClearResolvingListTest, Success) { ASSERT_EQ(controller_.LeAddDeviceToResolvingList( - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, - std::array{1}, std::array{1}), + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, + std::array{1}, std::array{1}), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeClearResolvingList(), ErrorCode::SUCCESS); @@ -49,8 +49,8 @@ TEST_F(LeClearResolvingListTest, Success) { TEST_F(LeClearResolvingListTest, ScanningActive) { ASSERT_EQ(controller_.LeAddDeviceToResolvingList( - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, - std::array{1}, std::array{1}), + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, + std::array{1}, std::array{1}), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeSetAddressResolutionEnable(true), ErrorCode::SUCCESS); @@ -61,8 +61,8 @@ TEST_F(LeClearResolvingListTest, ScanningActive) { TEST_F(LeClearResolvingListTest, LegacyAdvertisingActive) { ASSERT_EQ(controller_.LeAddDeviceToResolvingList( - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, - std::array{1}, std::array{1}), + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, + std::array{1}, std::array{1}), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeSetAddressResolutionEnable(true), ErrorCode::SUCCESS); @@ -73,20 +73,19 @@ TEST_F(LeClearResolvingListTest, LegacyAdvertisingActive) { TEST_F(LeClearResolvingListTest, ExtendedAdvertisingActive) { ASSERT_EQ(controller_.LeAddDeviceToResolvingList( - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, - std::array{1}, std::array{1}), + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, + std::array{1}, std::array{1}), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeSetAddressResolutionEnable(true), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, - 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::LISTED_SCAN, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::LISTED_SCAN, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable( - true, {MakeEnabledSet(0, 0, 0)}), + ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable(true, {MakeEnabledSet(0, 0, 0)}), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeClearResolvingList(), ErrorCode::COMMAND_DISALLOWED); diff --git a/tools/rootcanal/test/controller/le/le_create_connection_cancel_test.cc b/tools/rootcanal/test/controller/le/le_create_connection_cancel_test.cc index 995186e2f54..d8d16e82955 100644 --- a/tools/rootcanal/test/controller/le/le_create_connection_cancel_test.cc +++ b/tools/rootcanal/test/controller/le/le_create_connection_cancel_test.cc @@ -24,11 +24,11 @@ namespace rootcanal { using namespace bluetooth::hci; class LeCreateConnectionCancelTest : public ::testing::Test { - public: +public: LeCreateConnectionCancelTest() = default; ~LeCreateConnectionCancelTest() override = default; - protected: +protected: Address address_{0}; ControllerProperties properties_{}; LinkLayerController controller_{address_, properties_}; @@ -36,29 +36,25 @@ class LeCreateConnectionCancelTest : public ::testing::Test { TEST_F(LeCreateConnectionCancelTest, CancelLegacyConnection) { ASSERT_EQ(controller_.LeCreateConnection( - 0x200, 0x200, InitiatorFilterPolicy::USE_PEER_ADDRESS, - AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, 0x100, 0x200, 0x010, - 0x0c80, 0x0, 0x0), + 0x200, 0x200, InitiatorFilterPolicy::USE_PEER_ADDRESS, + AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, 0x100, 0x200, 0x010, 0x0c80, 0x0, 0x0), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeCreateConnectionCancel(), ErrorCode::SUCCESS); } TEST_F(LeCreateConnectionCancelTest, CancelExtendedConnection) { - ASSERT_EQ( - controller_.LeExtendedCreateConnection( - InitiatorFilterPolicy::USE_PEER_ADDRESS, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, 0x1, - {MakeInitiatingPhyParameters(0x200, 0x200, 0x100, 0x200, 0x010, - 0x0c80, 0x0, 0x0)}), - ErrorCode::SUCCESS); + ASSERT_EQ(controller_.LeExtendedCreateConnection( + InitiatorFilterPolicy::USE_PEER_ADDRESS, OwnAddressType::PUBLIC_DEVICE_ADDRESS, + AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, 0x1, + {MakeInitiatingPhyParameters(0x200, 0x200, 0x100, 0x200, 0x010, 0x0c80, 0x0, + 0x0)}), + ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeCreateConnectionCancel(), ErrorCode::SUCCESS); } TEST_F(LeCreateConnectionCancelTest, NoPendingConnection) { - ASSERT_EQ(controller_.LeCreateConnectionCancel(), - ErrorCode::COMMAND_DISALLOWED); + ASSERT_EQ(controller_.LeCreateConnectionCancel(), ErrorCode::COMMAND_DISALLOWED); } } // namespace rootcanal diff --git a/tools/rootcanal/test/controller/le/le_create_connection_test.cc b/tools/rootcanal/test/controller/le/le_create_connection_test.cc index 0c68ea9b856..866c493a182 100644 --- a/tools/rootcanal/test/controller/le/le_create_connection_test.cc +++ b/tools/rootcanal/test/controller/le/le_create_connection_test.cc @@ -23,11 +23,11 @@ namespace rootcanal { using namespace bluetooth::hci; class LeCreateConnectionTest : public ::testing::Test { - public: +public: LeCreateConnectionTest() = default; ~LeCreateConnectionTest() override = default; - protected: +protected: Address address_{0}; ControllerProperties properties_{}; LinkLayerController controller_{address_, properties_}; @@ -35,170 +35,151 @@ class LeCreateConnectionTest : public ::testing::Test { TEST_F(LeCreateConnectionTest, ConnectUsingPublicAddress) { ASSERT_EQ(controller_.LeCreateConnection( - 0x200, 0x200, InitiatorFilterPolicy::USE_PEER_ADDRESS, - AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, 0x100, 0x200, 0x010, - 0x0c80, 0x0, 0x0), + 0x200, 0x200, InitiatorFilterPolicy::USE_PEER_ADDRESS, + AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, 0x100, 0x200, 0x010, 0x0c80, 0x0, 0x0), ErrorCode::SUCCESS); } TEST_F(LeCreateConnectionTest, ConnectUsingRandomAddress) { ASSERT_EQ(controller_.LeSetRandomAddress(Address{1}), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeCreateConnection( - 0x200, 0x200, InitiatorFilterPolicy::USE_PEER_ADDRESS, - AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, - OwnAddressType::RANDOM_DEVICE_ADDRESS, 0x100, 0x200, 0x010, - 0x0c80, 0x0, 0x0), + 0x200, 0x200, InitiatorFilterPolicy::USE_PEER_ADDRESS, + AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, + OwnAddressType::RANDOM_DEVICE_ADDRESS, 0x100, 0x200, 0x010, 0x0c80, 0x0, 0x0), ErrorCode::SUCCESS); } TEST_F(LeCreateConnectionTest, ConnectUsingResolvableAddress) { ASSERT_EQ(controller_.LeSetRandomAddress(Address{1}), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeCreateConnection( - 0x200, 0x200, InitiatorFilterPolicy::USE_PEER_ADDRESS, - AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, - OwnAddressType::RESOLVABLE_OR_RANDOM_ADDRESS, 0x100, 0x200, - 0x010, 0x0c80, 0x0, 0x0), + 0x200, 0x200, InitiatorFilterPolicy::USE_PEER_ADDRESS, + AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, + OwnAddressType::RESOLVABLE_OR_RANDOM_ADDRESS, 0x100, 0x200, 0x010, 0x0c80, 0x0, + 0x0), ErrorCode::SUCCESS); } TEST_F(LeCreateConnectionTest, InitiatingActive) { ASSERT_EQ(controller_.LeCreateConnection( - 0x200, 0x200, InitiatorFilterPolicy::USE_PEER_ADDRESS, - AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, 0x100, 0x200, 0x010, - 0x0c80, 0x0, 0x0), + 0x200, 0x200, InitiatorFilterPolicy::USE_PEER_ADDRESS, + AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, 0x100, 0x200, 0x010, 0x0c80, 0x0, 0x0), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeCreateConnection( - 0x200, 0x200, InitiatorFilterPolicy::USE_PEER_ADDRESS, - AddressWithType{Address{2}, AddressType::PUBLIC_DEVICE_ADDRESS}, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, 0x100, 0x200, 0x010, - 0x0c80, 0x0, 0x0), + 0x200, 0x200, InitiatorFilterPolicy::USE_PEER_ADDRESS, + AddressWithType{Address{2}, AddressType::PUBLIC_DEVICE_ADDRESS}, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, 0x100, 0x200, 0x010, 0x0c80, 0x0, 0x0), ErrorCode::COMMAND_DISALLOWED); } TEST_F(LeCreateConnectionTest, InvalidScanInterval) { ASSERT_EQ(controller_.LeCreateConnection( - 0x3, 0x200, InitiatorFilterPolicy::USE_PEER_ADDRESS, - AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, 0x100, 0x200, 0x010, - 0x0c80, 0x0, 0x0), + 0x3, 0x200, InitiatorFilterPolicy::USE_PEER_ADDRESS, + AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, 0x100, 0x200, 0x010, 0x0c80, 0x0, 0x0), ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); ASSERT_EQ(controller_.LeCreateConnection( - 0x4001, 0x200, InitiatorFilterPolicy::USE_PEER_ADDRESS, - AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, 0x100, 0x200, 0x010, - 0x0c80, 0x0, 0x0), + 0x4001, 0x200, InitiatorFilterPolicy::USE_PEER_ADDRESS, + AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, 0x100, 0x200, 0x010, 0x0c80, 0x0, 0x0), ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); } TEST_F(LeCreateConnectionTest, InvalidScanWindow) { ASSERT_EQ(controller_.LeCreateConnection( - 0x200, 0x3, InitiatorFilterPolicy::USE_PEER_ADDRESS, - AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, 0x100, 0x200, 0x010, - 0x0c80, 0x0, 0x0), + 0x200, 0x3, InitiatorFilterPolicy::USE_PEER_ADDRESS, + AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, 0x100, 0x200, 0x010, 0x0c80, 0x0, 0x0), ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); ASSERT_EQ(controller_.LeCreateConnection( - 0x200, 0x4001, InitiatorFilterPolicy::USE_PEER_ADDRESS, - AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, 0x100, 0x200, 0x010, - 0x0c80, 0x0, 0x0), + 0x200, 0x4001, InitiatorFilterPolicy::USE_PEER_ADDRESS, + AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, 0x100, 0x200, 0x010, 0x0c80, 0x0, 0x0), ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); ASSERT_EQ(controller_.LeCreateConnection( - 0x100, 0x200, InitiatorFilterPolicy::USE_PEER_ADDRESS, - AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, 0x100, 0x200, 0x010, - 0x0c80, 0x0, 0x0), + 0x100, 0x200, InitiatorFilterPolicy::USE_PEER_ADDRESS, + AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, 0x100, 0x200, 0x010, 0x0c80, 0x0, 0x0), ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); } TEST_F(LeCreateConnectionTest, InvalidConnectionInterval) { ASSERT_EQ(controller_.LeCreateConnection( - 0x200, 0x200, InitiatorFilterPolicy::USE_PEER_ADDRESS, - AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, 0x5, 0x200, 0x010, - 0x0c80, 0x0, 0x0), + 0x200, 0x200, InitiatorFilterPolicy::USE_PEER_ADDRESS, + AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, 0x5, 0x200, 0x010, 0x0c80, 0x0, 0x0), ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); ASSERT_EQ(controller_.LeCreateConnection( - 0x200, 0x200, InitiatorFilterPolicy::USE_PEER_ADDRESS, - AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, 0x0c81, 0x200, 0x010, - 0x0c80, 0x0, 0x0), + 0x200, 0x200, InitiatorFilterPolicy::USE_PEER_ADDRESS, + AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, 0x0c81, 0x200, 0x010, 0x0c80, 0x0, 0x0), ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); ASSERT_EQ(controller_.LeCreateConnection( - 0x200, 0x200, InitiatorFilterPolicy::USE_PEER_ADDRESS, - AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, 0x200, 0x5, 0x010, - 0x0c80, 0x0, 0x0), + 0x200, 0x200, InitiatorFilterPolicy::USE_PEER_ADDRESS, + AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, 0x200, 0x5, 0x010, 0x0c80, 0x0, 0x0), ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); ASSERT_EQ(controller_.LeCreateConnection( - 0x200, 0x200, InitiatorFilterPolicy::USE_PEER_ADDRESS, - AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, 0x200, 0x0c81, 0x010, - 0x0c80, 0x0, 0x0), + 0x200, 0x200, InitiatorFilterPolicy::USE_PEER_ADDRESS, + AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, 0x200, 0x0c81, 0x010, 0x0c80, 0x0, 0x0), ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); ASSERT_EQ(controller_.LeCreateConnection( - 0x4001, 0x200, InitiatorFilterPolicy::USE_PEER_ADDRESS, - AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, 0x200, 0x100, 0x010, - 0x0c80, 0x0, 0x0), + 0x4001, 0x200, InitiatorFilterPolicy::USE_PEER_ADDRESS, + AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, 0x200, 0x100, 0x010, 0x0c80, 0x0, 0x0), ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); } TEST_F(LeCreateConnectionTest, InvalidMaxLatency) { ASSERT_EQ(controller_.LeCreateConnection( - 0x200, 0x200, InitiatorFilterPolicy::USE_PEER_ADDRESS, - AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, 0x100, 0x200, 0x01f4, - 0x0c80, 0x0, 0x0), + 0x200, 0x200, InitiatorFilterPolicy::USE_PEER_ADDRESS, + AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, 0x100, 0x200, 0x01f4, 0x0c80, 0x0, 0x0), ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); } TEST_F(LeCreateConnectionTest, InvalidSupervisionTimeout) { ASSERT_EQ(controller_.LeCreateConnection( - 0x200, 0x200, InitiatorFilterPolicy::USE_PEER_ADDRESS, - AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, 0x100, 0x200, 0x010, 0x9, - 0x0, 0x0), + 0x200, 0x200, InitiatorFilterPolicy::USE_PEER_ADDRESS, + AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, 0x100, 0x200, 0x010, 0x9, 0x0, 0x0), ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); ASSERT_EQ(controller_.LeCreateConnection( - 0x200, 0x200, InitiatorFilterPolicy::USE_PEER_ADDRESS, - AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, 0x100, 0x200, 0x010, - 0x0c81, 0x0, 0x0), + 0x200, 0x200, InitiatorFilterPolicy::USE_PEER_ADDRESS, + AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, 0x100, 0x200, 0x010, 0x0c81, 0x0, 0x0), ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); ASSERT_EQ(controller_.LeCreateConnection( - 0x200, 0x200, InitiatorFilterPolicy::USE_PEER_ADDRESS, - AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, 0x100, 0x200, 0x1f3, - 0x0c80, 0x0, 0x0), + 0x200, 0x200, InitiatorFilterPolicy::USE_PEER_ADDRESS, + AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, 0x100, 0x200, 0x1f3, 0x0c80, 0x0, 0x0), ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); } TEST_F(LeCreateConnectionTest, NoRandomAddress) { ASSERT_EQ(controller_.LeCreateConnection( - 0x200, 0x200, InitiatorFilterPolicy::USE_PEER_ADDRESS, - AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, - OwnAddressType::RANDOM_DEVICE_ADDRESS, 0x100, 0x200, 0x010, - 0x0c80, 0x0, 0x0), + 0x200, 0x200, InitiatorFilterPolicy::USE_PEER_ADDRESS, + AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, + OwnAddressType::RANDOM_DEVICE_ADDRESS, 0x100, 0x200, 0x010, 0x0c80, 0x0, 0x0), ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); ASSERT_EQ(controller_.LeCreateConnection( - 0x200, 0x200, InitiatorFilterPolicy::USE_PEER_ADDRESS, - AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, - OwnAddressType::RESOLVABLE_OR_RANDOM_ADDRESS, 0x100, 0x200, - 0x010, 0x0c80, 0x0, 0x0), + 0x200, 0x200, InitiatorFilterPolicy::USE_PEER_ADDRESS, + AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, + OwnAddressType::RESOLVABLE_OR_RANDOM_ADDRESS, 0x100, 0x200, 0x010, 0x0c80, 0x0, + 0x0), ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); } diff --git a/tools/rootcanal/test/controller/le/le_extended_create_connection_test.cc b/tools/rootcanal/test/controller/le/le_extended_create_connection_test.cc index c5f4f63c693..072827147f9 100644 --- a/tools/rootcanal/test/controller/le/le_extended_create_connection_test.cc +++ b/tools/rootcanal/test/controller/le/le_extended_create_connection_test.cc @@ -26,265 +26,217 @@ namespace rootcanal { using namespace bluetooth::hci; class LeExtendedCreateConnectionTest : public ::testing::Test { - public: +public: LeExtendedCreateConnectionTest() = default; ~LeExtendedCreateConnectionTest() override = default; - protected: +protected: Address address_{0}; ControllerProperties properties_{}; LinkLayerController controller_{address_, properties_}; }; TEST_F(LeExtendedCreateConnectionTest, ConnectUsingPublicAddress) { - ASSERT_EQ( - controller_.LeExtendedCreateConnection( - InitiatorFilterPolicy::USE_PEER_ADDRESS, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, 0x1, - {MakeInitiatingPhyParameters(0x200, 0x200, 0x100, 0x200, 0x010, - 0x0c80, 0x0, 0x0)}), - ErrorCode::SUCCESS); + ASSERT_EQ(controller_.LeExtendedCreateConnection( + InitiatorFilterPolicy::USE_PEER_ADDRESS, OwnAddressType::PUBLIC_DEVICE_ADDRESS, + AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, 0x1, + {MakeInitiatingPhyParameters(0x200, 0x200, 0x100, 0x200, 0x010, 0x0c80, 0x0, + 0x0)}), + ErrorCode::SUCCESS); } TEST_F(LeExtendedCreateConnectionTest, ConnectUsingRandomAddress) { ASSERT_EQ(controller_.LeSetRandomAddress(Address{1}), ErrorCode::SUCCESS); - ASSERT_EQ( - controller_.LeExtendedCreateConnection( - InitiatorFilterPolicy::USE_PEER_ADDRESS, - OwnAddressType::RANDOM_DEVICE_ADDRESS, - AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, 0x1, - {MakeInitiatingPhyParameters(0x200, 0x200, 0x100, 0x200, 0x010, - 0x0c80, 0x0, 0x0)}), - ErrorCode::SUCCESS); + ASSERT_EQ(controller_.LeExtendedCreateConnection( + InitiatorFilterPolicy::USE_PEER_ADDRESS, OwnAddressType::RANDOM_DEVICE_ADDRESS, + AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, 0x1, + {MakeInitiatingPhyParameters(0x200, 0x200, 0x100, 0x200, 0x010, 0x0c80, 0x0, + 0x0)}), + ErrorCode::SUCCESS); } TEST_F(LeExtendedCreateConnectionTest, ConnectUsingResolvableAddress) { ASSERT_EQ(controller_.LeSetRandomAddress(Address{1}), ErrorCode::SUCCESS); - ASSERT_EQ( - controller_.LeExtendedCreateConnection( - InitiatorFilterPolicy::USE_PEER_ADDRESS, - OwnAddressType::RESOLVABLE_OR_RANDOM_ADDRESS, - AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, 0x1, - {MakeInitiatingPhyParameters(0x200, 0x200, 0x100, 0x200, 0x010, - 0x0c80, 0x0, 0x0)}), - ErrorCode::SUCCESS); + ASSERT_EQ(controller_.LeExtendedCreateConnection( + InitiatorFilterPolicy::USE_PEER_ADDRESS, + OwnAddressType::RESOLVABLE_OR_RANDOM_ADDRESS, + AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, 0x1, + {MakeInitiatingPhyParameters(0x200, 0x200, 0x100, 0x200, 0x010, 0x0c80, 0x0, + 0x0)}), + ErrorCode::SUCCESS); } TEST_F(LeExtendedCreateConnectionTest, InitiatingActive) { - ASSERT_EQ( - controller_.LeExtendedCreateConnection( - InitiatorFilterPolicy::USE_PEER_ADDRESS, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, 0x1, - {MakeInitiatingPhyParameters(0x200, 0x200, 0x100, 0x200, 0x010, - 0x0c80, 0x0, 0x0)}), - ErrorCode::SUCCESS); + ASSERT_EQ(controller_.LeExtendedCreateConnection( + InitiatorFilterPolicy::USE_PEER_ADDRESS, OwnAddressType::PUBLIC_DEVICE_ADDRESS, + AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, 0x1, + {MakeInitiatingPhyParameters(0x200, 0x200, 0x100, 0x200, 0x010, 0x0c80, 0x0, + 0x0)}), + ErrorCode::SUCCESS); - ASSERT_EQ( - controller_.LeExtendedCreateConnection( - InitiatorFilterPolicy::USE_PEER_ADDRESS, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, 0x1, - {MakeInitiatingPhyParameters(0x200, 0x200, 0x100, 0x200, 0x010, - 0x0c80, 0x0, 0x0)}), - ErrorCode::COMMAND_DISALLOWED); + ASSERT_EQ(controller_.LeExtendedCreateConnection( + InitiatorFilterPolicy::USE_PEER_ADDRESS, OwnAddressType::PUBLIC_DEVICE_ADDRESS, + AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, 0x1, + {MakeInitiatingPhyParameters(0x200, 0x200, 0x100, 0x200, 0x010, 0x0c80, 0x0, + 0x0)}), + ErrorCode::COMMAND_DISALLOWED); } TEST_F(LeExtendedCreateConnectionTest, NoPhy) { ASSERT_EQ(controller_.LeExtendedCreateConnection( - InitiatorFilterPolicy::USE_PEER_ADDRESS, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, - 0x0, {}), + InitiatorFilterPolicy::USE_PEER_ADDRESS, OwnAddressType::PUBLIC_DEVICE_ADDRESS, + AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, 0x0, {}), ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); } TEST_F(LeExtendedCreateConnectionTest, ReservedPhy) { - ASSERT_EQ( - controller_.LeExtendedCreateConnection( - InitiatorFilterPolicy::USE_PEER_ADDRESS, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, 0x8, - {MakeInitiatingPhyParameters(0x200, 0x200, 0x100, 0x200, 0x010, - 0x0c80, 0x0, 0x0)}), - ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); + ASSERT_EQ(controller_.LeExtendedCreateConnection( + InitiatorFilterPolicy::USE_PEER_ADDRESS, OwnAddressType::PUBLIC_DEVICE_ADDRESS, + AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, 0x8, + {MakeInitiatingPhyParameters(0x200, 0x200, 0x100, 0x200, 0x010, 0x0c80, 0x0, + 0x0)}), + ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); } TEST_F(LeExtendedCreateConnectionTest, InvalidPhyParameters) { ASSERT_EQ(controller_.LeExtendedCreateConnection( - InitiatorFilterPolicy::USE_PEER_ADDRESS, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, - 0x1, {}), + InitiatorFilterPolicy::USE_PEER_ADDRESS, OwnAddressType::PUBLIC_DEVICE_ADDRESS, + AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, 0x1, {}), ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); ASSERT_EQ( - controller_.LeExtendedCreateConnection( - InitiatorFilterPolicy::USE_PEER_ADDRESS, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, 0x1, - {MakeInitiatingPhyParameters(0x200, 0x200, 0x100, 0x200, 0x010, - 0x0c80, 0x0, 0x0), - MakeInitiatingPhyParameters(0x200, 0x200, 0x100, 0x200, 0x010, - 0x0c80, 0x0, 0x0)}), - ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); + controller_.LeExtendedCreateConnection( + InitiatorFilterPolicy::USE_PEER_ADDRESS, OwnAddressType::PUBLIC_DEVICE_ADDRESS, + AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, 0x1, + {MakeInitiatingPhyParameters(0x200, 0x200, 0x100, 0x200, 0x010, 0x0c80, 0x0, 0x0), + MakeInitiatingPhyParameters(0x200, 0x200, 0x100, 0x200, 0x010, 0x0c80, 0x0, + 0x0)}), + ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); } TEST_F(LeExtendedCreateConnectionTest, InvalidScanInterval) { ASSERT_EQ( - controller_.LeExtendedCreateConnection( - InitiatorFilterPolicy::USE_PEER_ADDRESS, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, 0x1, - {MakeInitiatingPhyParameters(0x3, 0x200, 0x100, 0x200, 0x010, 0x0c80, - 0x0, 0x0)}), - ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); + controller_.LeExtendedCreateConnection( + InitiatorFilterPolicy::USE_PEER_ADDRESS, OwnAddressType::PUBLIC_DEVICE_ADDRESS, + AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, 0x1, + {MakeInitiatingPhyParameters(0x3, 0x200, 0x100, 0x200, 0x010, 0x0c80, 0x0, 0x0)}), + ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); - ASSERT_EQ( - controller_.LeExtendedCreateConnection( - InitiatorFilterPolicy::USE_PEER_ADDRESS, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, 0x1, - {MakeInitiatingPhyParameters(0x4001, 0x200, 0x100, 0x200, 0x010, - 0x0c80, 0x0, 0x0)}), - ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); + ASSERT_EQ(controller_.LeExtendedCreateConnection( + InitiatorFilterPolicy::USE_PEER_ADDRESS, OwnAddressType::PUBLIC_DEVICE_ADDRESS, + AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, 0x1, + {MakeInitiatingPhyParameters(0x4001, 0x200, 0x100, 0x200, 0x010, 0x0c80, 0x0, + 0x0)}), + ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); } TEST_F(LeExtendedCreateConnectionTest, InvalidScanWindow) { ASSERT_EQ( - controller_.LeExtendedCreateConnection( - InitiatorFilterPolicy::USE_PEER_ADDRESS, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, 0x1, - {MakeInitiatingPhyParameters(0x200, 0x3, 0x100, 0x200, 0x010, 0x0c80, - 0x0, 0x0)}), - ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); + controller_.LeExtendedCreateConnection( + InitiatorFilterPolicy::USE_PEER_ADDRESS, OwnAddressType::PUBLIC_DEVICE_ADDRESS, + AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, 0x1, + {MakeInitiatingPhyParameters(0x200, 0x3, 0x100, 0x200, 0x010, 0x0c80, 0x0, 0x0)}), + ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); - ASSERT_EQ( - controller_.LeExtendedCreateConnection( - InitiatorFilterPolicy::USE_PEER_ADDRESS, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, 0x1, - {MakeInitiatingPhyParameters(0x200, 0x4001, 0x100, 0x200, 0x010, - 0x0c80, 0x0, 0x0)}), - ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); + ASSERT_EQ(controller_.LeExtendedCreateConnection( + InitiatorFilterPolicy::USE_PEER_ADDRESS, OwnAddressType::PUBLIC_DEVICE_ADDRESS, + AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, 0x1, + {MakeInitiatingPhyParameters(0x200, 0x4001, 0x100, 0x200, 0x010, 0x0c80, 0x0, + 0x0)}), + ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); - ASSERT_EQ( - controller_.LeExtendedCreateConnection( - InitiatorFilterPolicy::USE_PEER_ADDRESS, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, 0x1, - {MakeInitiatingPhyParameters(0x100, 0x200, 0x100, 0x200, 0x010, - 0x0c80, 0x0, 0x0)}), - ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); + ASSERT_EQ(controller_.LeExtendedCreateConnection( + InitiatorFilterPolicy::USE_PEER_ADDRESS, OwnAddressType::PUBLIC_DEVICE_ADDRESS, + AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, 0x1, + {MakeInitiatingPhyParameters(0x100, 0x200, 0x100, 0x200, 0x010, 0x0c80, 0x0, + 0x0)}), + ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); } TEST_F(LeExtendedCreateConnectionTest, InvalidConnectionInterval) { ASSERT_EQ( - controller_.LeExtendedCreateConnection( - InitiatorFilterPolicy::USE_PEER_ADDRESS, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, 0x1, - {MakeInitiatingPhyParameters(0x200, 0x200, 0x5, 0x200, 0x010, 0x0c80, - 0x0, 0x0)}), - ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); + controller_.LeExtendedCreateConnection( + InitiatorFilterPolicy::USE_PEER_ADDRESS, OwnAddressType::PUBLIC_DEVICE_ADDRESS, + AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, 0x1, + {MakeInitiatingPhyParameters(0x200, 0x200, 0x5, 0x200, 0x010, 0x0c80, 0x0, 0x0)}), + ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); - ASSERT_EQ( - controller_.LeExtendedCreateConnection( - InitiatorFilterPolicy::USE_PEER_ADDRESS, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, 0x1, - {MakeInitiatingPhyParameters(0x200, 0x200, 0x0c81, 0x200, 0x010, - 0x0c80, 0x0, 0x0)}), - ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); + ASSERT_EQ(controller_.LeExtendedCreateConnection( + InitiatorFilterPolicy::USE_PEER_ADDRESS, OwnAddressType::PUBLIC_DEVICE_ADDRESS, + AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, 0x1, + {MakeInitiatingPhyParameters(0x200, 0x200, 0x0c81, 0x200, 0x010, 0x0c80, 0x0, + 0x0)}), + ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); ASSERT_EQ( - controller_.LeExtendedCreateConnection( - InitiatorFilterPolicy::USE_PEER_ADDRESS, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, 0x1, - {MakeInitiatingPhyParameters(0x200, 0x200, 0x200, 0x5, 0x010, 0x0c80, - 0x0, 0x0)}), - ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); + controller_.LeExtendedCreateConnection( + InitiatorFilterPolicy::USE_PEER_ADDRESS, OwnAddressType::PUBLIC_DEVICE_ADDRESS, + AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, 0x1, + {MakeInitiatingPhyParameters(0x200, 0x200, 0x200, 0x5, 0x010, 0x0c80, 0x0, 0x0)}), + ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); - ASSERT_EQ( - controller_.LeExtendedCreateConnection( - InitiatorFilterPolicy::USE_PEER_ADDRESS, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, 0x1, - {MakeInitiatingPhyParameters(0x200, 0x200, 0x200, 0x0c81, 0x010, - 0x0c80, 0x0, 0x0)}), - ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); + ASSERT_EQ(controller_.LeExtendedCreateConnection( + InitiatorFilterPolicy::USE_PEER_ADDRESS, OwnAddressType::PUBLIC_DEVICE_ADDRESS, + AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, 0x1, + {MakeInitiatingPhyParameters(0x200, 0x200, 0x200, 0x0c81, 0x010, 0x0c80, 0x0, + 0x0)}), + ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); - ASSERT_EQ( - controller_.LeExtendedCreateConnection( - InitiatorFilterPolicy::USE_PEER_ADDRESS, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, 0x1, - {MakeInitiatingPhyParameters(0x200, 0x200, 0x200, 0x100, 0x010, - 0x0c80, 0x0, 0x0)}), - ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); + ASSERT_EQ(controller_.LeExtendedCreateConnection( + InitiatorFilterPolicy::USE_PEER_ADDRESS, OwnAddressType::PUBLIC_DEVICE_ADDRESS, + AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, 0x1, + {MakeInitiatingPhyParameters(0x200, 0x200, 0x200, 0x100, 0x010, 0x0c80, 0x0, + 0x0)}), + ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); } TEST_F(LeExtendedCreateConnectionTest, InvalidMaxLatency) { - ASSERT_EQ( - controller_.LeExtendedCreateConnection( - InitiatorFilterPolicy::USE_PEER_ADDRESS, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, 0x1, - {MakeInitiatingPhyParameters(0x200, 0x200, 0x100, 0x200, 0x01f4, - 0x0c80, 0x0, 0x0)}), - ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); + ASSERT_EQ(controller_.LeExtendedCreateConnection( + InitiatorFilterPolicy::USE_PEER_ADDRESS, OwnAddressType::PUBLIC_DEVICE_ADDRESS, + AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, 0x1, + {MakeInitiatingPhyParameters(0x200, 0x200, 0x100, 0x200, 0x01f4, 0x0c80, 0x0, + 0x0)}), + ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); } TEST_F(LeExtendedCreateConnectionTest, InvalidSupervisionTimeout) { ASSERT_EQ( - controller_.LeExtendedCreateConnection( - InitiatorFilterPolicy::USE_PEER_ADDRESS, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, 0x1, - {MakeInitiatingPhyParameters(0x200, 0x200, 0x100, 0x200, 0x010, 0x9, - 0x0, 0x0)}), - ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); + controller_.LeExtendedCreateConnection( + InitiatorFilterPolicy::USE_PEER_ADDRESS, OwnAddressType::PUBLIC_DEVICE_ADDRESS, + AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, 0x1, + {MakeInitiatingPhyParameters(0x200, 0x200, 0x100, 0x200, 0x010, 0x9, 0x0, 0x0)}), + ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); - ASSERT_EQ( - controller_.LeExtendedCreateConnection( - InitiatorFilterPolicy::USE_PEER_ADDRESS, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, 0x1, - {MakeInitiatingPhyParameters(0x200, 0x200, 0x100, 0x200, 0x010, - 0x0c81, 0x0, 0x0)}), - ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); + ASSERT_EQ(controller_.LeExtendedCreateConnection( + InitiatorFilterPolicy::USE_PEER_ADDRESS, OwnAddressType::PUBLIC_DEVICE_ADDRESS, + AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, 0x1, + {MakeInitiatingPhyParameters(0x200, 0x200, 0x100, 0x200, 0x010, 0x0c81, 0x0, + 0x0)}), + ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); - ASSERT_EQ( - controller_.LeExtendedCreateConnection( - InitiatorFilterPolicy::USE_PEER_ADDRESS, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, 0x1, - {MakeInitiatingPhyParameters(0x200, 0x200, 0x100, 0x200, 0x1f3, - 0x0c80, 0x0, 0x0)}), - ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); + ASSERT_EQ(controller_.LeExtendedCreateConnection( + InitiatorFilterPolicy::USE_PEER_ADDRESS, OwnAddressType::PUBLIC_DEVICE_ADDRESS, + AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, 0x1, + {MakeInitiatingPhyParameters(0x200, 0x200, 0x100, 0x200, 0x1f3, 0x0c80, 0x0, + 0x0)}), + ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); } TEST_F(LeExtendedCreateConnectionTest, NoRandomAddress) { - ASSERT_EQ( - controller_.LeExtendedCreateConnection( - InitiatorFilterPolicy::USE_PEER_ADDRESS, - OwnAddressType::RANDOM_DEVICE_ADDRESS, - AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, 0x1, - {MakeInitiatingPhyParameters(0x200, 0x200, 0x100, 0x200, 0x010, - 0x0c80, 0x0, 0x0)}), - ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); + ASSERT_EQ(controller_.LeExtendedCreateConnection( + InitiatorFilterPolicy::USE_PEER_ADDRESS, OwnAddressType::RANDOM_DEVICE_ADDRESS, + AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, 0x1, + {MakeInitiatingPhyParameters(0x200, 0x200, 0x100, 0x200, 0x010, 0x0c80, 0x0, + 0x0)}), + ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); - ASSERT_EQ( - controller_.LeExtendedCreateConnection( - InitiatorFilterPolicy::USE_PEER_ADDRESS, - OwnAddressType::RESOLVABLE_OR_RANDOM_ADDRESS, - AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, 0x1, - {MakeInitiatingPhyParameters(0x200, 0x200, 0x100, 0x200, 0x010, - 0x0c80, 0x0, 0x0)}), - ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); + ASSERT_EQ(controller_.LeExtendedCreateConnection( + InitiatorFilterPolicy::USE_PEER_ADDRESS, + OwnAddressType::RESOLVABLE_OR_RANDOM_ADDRESS, + AddressWithType{Address{1}, AddressType::PUBLIC_DEVICE_ADDRESS}, 0x1, + {MakeInitiatingPhyParameters(0x200, 0x200, 0x100, 0x200, 0x010, 0x0c80, 0x0, + 0x0)}), + ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); } } // namespace rootcanal diff --git a/tools/rootcanal/test/controller/le/le_periodic_advertising_create_sync_cancel_test.cc b/tools/rootcanal/test/controller/le/le_periodic_advertising_create_sync_cancel_test.cc index 80f353db5ae..ad8924cf785 100644 --- a/tools/rootcanal/test/controller/le/le_periodic_advertising_create_sync_cancel_test.cc +++ b/tools/rootcanal/test/controller/le/le_periodic_advertising_create_sync_cancel_test.cc @@ -23,11 +23,11 @@ namespace rootcanal { using namespace bluetooth::hci; class LePeriodicAdvertisingCreateSyncCancelTest : public ::testing::Test { - public: +public: LePeriodicAdvertisingCreateSyncCancelTest() = default; ~LePeriodicAdvertisingCreateSyncCancelTest() override = default; - protected: +protected: Address address_{0}; ControllerProperties properties_{}; LinkLayerController controller_{address_, properties_}; @@ -35,18 +35,16 @@ class LePeriodicAdvertisingCreateSyncCancelTest : public ::testing::Test { TEST_F(LePeriodicAdvertisingCreateSyncCancelTest, Success) { ASSERT_EQ(controller_.LePeriodicAdvertisingCreateSync( - PeriodicAdvertisingOptions(false, false, false), 0, - AdvertiserAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address{1}, 0, 0x100, 0), + PeriodicAdvertisingOptions(false, false, false), 0, + AdvertiserAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, 0, 0x100, + 0), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LePeriodicAdvertisingCreateSyncCancel(), - ErrorCode::SUCCESS); + ASSERT_EQ(controller_.LePeriodicAdvertisingCreateSyncCancel(), ErrorCode::SUCCESS); } TEST_F(LePeriodicAdvertisingCreateSyncCancelTest, CreateSyncNotPending) { - ASSERT_EQ(controller_.LePeriodicAdvertisingCreateSyncCancel(), - ErrorCode::COMMAND_DISALLOWED); + ASSERT_EQ(controller_.LePeriodicAdvertisingCreateSyncCancel(), ErrorCode::COMMAND_DISALLOWED); } } // namespace rootcanal diff --git a/tools/rootcanal/test/controller/le/le_periodic_advertising_create_sync_test.cc b/tools/rootcanal/test/controller/le/le_periodic_advertising_create_sync_test.cc index bf3ad7aada5..0ee36cd055f 100644 --- a/tools/rootcanal/test/controller/le/le_periodic_advertising_create_sync_test.cc +++ b/tools/rootcanal/test/controller/le/le_periodic_advertising_create_sync_test.cc @@ -23,11 +23,11 @@ namespace rootcanal { using namespace bluetooth::hci; class LePeriodicAdvertisingCreateSyncTest : public ::testing::Test { - public: +public: LePeriodicAdvertisingCreateSyncTest() = default; ~LePeriodicAdvertisingCreateSyncTest() override = default; - protected: +protected: Address address_{0}; ControllerProperties properties_{}; LinkLayerController controller_{address_, properties_}; @@ -35,54 +35,50 @@ class LePeriodicAdvertisingCreateSyncTest : public ::testing::Test { TEST_F(LePeriodicAdvertisingCreateSyncTest, CreateUsingPublicAddress) { ASSERT_EQ(controller_.LePeriodicAdvertisingCreateSync( - PeriodicAdvertisingOptions(false, false, false), 0, - AdvertiserAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address{1}, 0, 0x100, 0), + PeriodicAdvertisingOptions(false, false, false), 0, + AdvertiserAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, 0, 0x100, + 0), ErrorCode::SUCCESS); } TEST_F(LePeriodicAdvertisingCreateSyncTest, CreateUsingPeriodicAdvertiserList) { ASSERT_EQ(controller_.LePeriodicAdvertisingCreateSync( - PeriodicAdvertisingOptions(true, false, false), 0, - AdvertiserAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, 0, 0x100, 0), + PeriodicAdvertisingOptions(true, false, false), 0, + AdvertiserAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, 0, + 0x100, 0), ErrorCode::SUCCESS); } TEST_F(LePeriodicAdvertisingCreateSyncTest, CreateSyncPending) { ASSERT_EQ(controller_.LePeriodicAdvertisingCreateSync( - PeriodicAdvertisingOptions(false, false, false), 0, - AdvertiserAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address{1}, 0, 0x100, 0), + PeriodicAdvertisingOptions(false, false, false), 0, + AdvertiserAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, 0, 0x100, + 0), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LePeriodicAdvertisingCreateSync( - PeriodicAdvertisingOptions(true, false, false), 0, - AdvertiserAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, 0, 0x100, 0), + PeriodicAdvertisingOptions(true, false, false), 0, + AdvertiserAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, 0, + 0x100, 0), ErrorCode::COMMAND_DISALLOWED); } TEST_F(LePeriodicAdvertisingCreateSyncTest, InvalidSyncCteMask) { - ASSERT_EQ( - controller_.LePeriodicAdvertisingCreateSync( - PeriodicAdvertisingOptions(false, false, false), 0, - AdvertiserAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, - 0, 0x100, - static_cast( - PeriodicSyncCteType::AVOID_AOA_CONSTANT_TONE_EXTENSION) | - static_cast( - PeriodicSyncCteType:: - AVOID_AOD_CONSTANT_TONE_EXTENSION_WITH_ONE_US_SLOTS) | - static_cast( - PeriodicSyncCteType:: - AVOID_AOD_CONSTANT_TONE_EXTENSION_WITH_TWO_US_SLOTS) | - static_cast( - PeriodicSyncCteType:: - AVOID_TYPE_THREE_CONSTANT_TONE_EXTENSION) | - static_cast( - PeriodicSyncCteType::AVOID_NO_CONSTANT_TONE_EXTENSION)), - ErrorCode::COMMAND_DISALLOWED); + ASSERT_EQ(controller_.LePeriodicAdvertisingCreateSync( + PeriodicAdvertisingOptions(false, false, false), 0, + AdvertiserAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, 0, 0x100, + static_cast(PeriodicSyncCteType::AVOID_AOA_CONSTANT_TONE_EXTENSION) | + static_cast( + PeriodicSyncCteType:: + AVOID_AOD_CONSTANT_TONE_EXTENSION_WITH_ONE_US_SLOTS) | + static_cast( + PeriodicSyncCteType:: + AVOID_AOD_CONSTANT_TONE_EXTENSION_WITH_TWO_US_SLOTS) | + static_cast( + PeriodicSyncCteType::AVOID_TYPE_THREE_CONSTANT_TONE_EXTENSION) | + static_cast( + PeriodicSyncCteType::AVOID_NO_CONSTANT_TONE_EXTENSION)), + ErrorCode::COMMAND_DISALLOWED); } } // namespace rootcanal diff --git a/tools/rootcanal/test/controller/le/le_remove_device_from_filter_accept_list_test.cc b/tools/rootcanal/test/controller/le/le_remove_device_from_filter_accept_list_test.cc index b3e41b696ef..5a05c5900d2 100644 --- a/tools/rootcanal/test/controller/le/le_remove_device_from_filter_accept_list_test.cc +++ b/tools/rootcanal/test/controller/le/le_remove_device_from_filter_accept_list_test.cc @@ -24,7 +24,7 @@ namespace rootcanal { using namespace bluetooth::hci; class LeRemoveDeviceFromFilterAcceptListTest : public ::testing::Test { - public: +public: LeRemoveDeviceFromFilterAcceptListTest() { // Reduce the size of the resolving list to simplify testing. properties_.le_resolving_list_size = 2; @@ -32,83 +32,81 @@ class LeRemoveDeviceFromFilterAcceptListTest : public ::testing::Test { ~LeRemoveDeviceFromFilterAcceptListTest() override = default; - protected: +protected: Address address_{0}; ControllerProperties properties_{}; LinkLayerController controller_{address_, properties_}; }; TEST_F(LeRemoveDeviceFromFilterAcceptListTest, Success) { - ASSERT_EQ(controller_.LeAddDeviceToFilterAcceptList( - FilterAcceptListAddressType::PUBLIC, Address{1}), + ASSERT_EQ(controller_.LeAddDeviceToFilterAcceptList(FilterAcceptListAddressType::PUBLIC, + Address{1}), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeRemoveDeviceFromFilterAcceptList( - FilterAcceptListAddressType::PUBLIC, Address{1}), + ASSERT_EQ(controller_.LeRemoveDeviceFromFilterAcceptList(FilterAcceptListAddressType::PUBLIC, + Address{1}), ErrorCode::SUCCESS); } TEST_F(LeRemoveDeviceFromFilterAcceptListTest, NotFound) { - ASSERT_EQ(controller_.LeAddDeviceToFilterAcceptList( - FilterAcceptListAddressType::PUBLIC, Address{1}), + ASSERT_EQ(controller_.LeAddDeviceToFilterAcceptList(FilterAcceptListAddressType::PUBLIC, + Address{1}), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeRemoveDeviceFromFilterAcceptList( - FilterAcceptListAddressType::RANDOM, Address{1}), + ASSERT_EQ(controller_.LeRemoveDeviceFromFilterAcceptList(FilterAcceptListAddressType::RANDOM, + Address{1}), ErrorCode::SUCCESS); } TEST_F(LeRemoveDeviceFromFilterAcceptListTest, ScanningActive) { - ASSERT_EQ(controller_.LeAddDeviceToFilterAcceptList( - FilterAcceptListAddressType::PUBLIC, Address{1}), + ASSERT_EQ(controller_.LeAddDeviceToFilterAcceptList(FilterAcceptListAddressType::PUBLIC, + Address{1}), ErrorCode::SUCCESS); - controller_.LeSetScanParameters( - LeScanType::PASSIVE, 0x400, 0x200, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - LeScanningFilterPolicy::FILTER_ACCEPT_LIST_ONLY); + controller_.LeSetScanParameters(LeScanType::PASSIVE, 0x400, 0x200, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + LeScanningFilterPolicy::FILTER_ACCEPT_LIST_ONLY); controller_.LeSetScanEnable(true, false); - ASSERT_EQ(controller_.LeRemoveDeviceFromFilterAcceptList( - FilterAcceptListAddressType::PUBLIC, Address{1}), + ASSERT_EQ(controller_.LeRemoveDeviceFromFilterAcceptList(FilterAcceptListAddressType::PUBLIC, + Address{1}), ErrorCode::COMMAND_DISALLOWED); } TEST_F(LeRemoveDeviceFromFilterAcceptListTest, LegacyAdvertisingActive) { - ASSERT_EQ(controller_.LeAddDeviceToFilterAcceptList( - FilterAcceptListAddressType::PUBLIC, Address{1}), + ASSERT_EQ(controller_.LeAddDeviceToFilterAcceptList(FilterAcceptListAddressType::PUBLIC, + Address{1}), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeSetAdvertisingParameters( - 0x0800, 0x0800, AdvertisingType::ADV_IND, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, 0x7, AdvertisingFilterPolicy::LISTED_SCAN), + 0x0800, 0x0800, AdvertisingType::ADV_IND, OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, 0x7, + AdvertisingFilterPolicy::LISTED_SCAN), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeSetAdvertisingEnable(true), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeRemoveDeviceFromFilterAcceptList( - FilterAcceptListAddressType::PUBLIC, Address{1}), + ASSERT_EQ(controller_.LeRemoveDeviceFromFilterAcceptList(FilterAcceptListAddressType::PUBLIC, + Address{1}), ErrorCode::COMMAND_DISALLOWED); } TEST_F(LeRemoveDeviceFromFilterAcceptListTest, ExtendedAdvertisingActive) { - ASSERT_EQ(controller_.LeAddDeviceToFilterAcceptList( - FilterAcceptListAddressType::PUBLIC, Address{1}), + ASSERT_EQ(controller_.LeAddDeviceToFilterAcceptList(FilterAcceptListAddressType::PUBLIC, + Address{1}), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, - 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::LISTED_SCAN, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::LISTED_SCAN, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable( - true, {MakeEnabledSet(0, 0, 0)}), + ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable(true, {MakeEnabledSet(0, 0, 0)}), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeRemoveDeviceFromFilterAcceptList( - FilterAcceptListAddressType::PUBLIC, Address{1}), + ASSERT_EQ(controller_.LeRemoveDeviceFromFilterAcceptList(FilterAcceptListAddressType::PUBLIC, + Address{1}), ErrorCode::COMMAND_DISALLOWED); } diff --git a/tools/rootcanal/test/controller/le/le_remove_device_from_periodic_advertiser_list_test.cc b/tools/rootcanal/test/controller/le/le_remove_device_from_periodic_advertiser_list_test.cc index bb362cefddd..86edd3c9297 100644 --- a/tools/rootcanal/test/controller/le/le_remove_device_from_periodic_advertiser_list_test.cc +++ b/tools/rootcanal/test/controller/le/le_remove_device_from_periodic_advertiser_list_test.cc @@ -24,7 +24,7 @@ namespace rootcanal { using namespace bluetooth::hci; class LeRemoveDeviceFromPeriodicAdvertiserListTest : public ::testing::Test { - public: +public: LeRemoveDeviceFromPeriodicAdvertiserListTest() { // Reduce the size of the periodic advertiser list to simplify testing. properties_.le_periodic_advertiser_list_size = 3; @@ -32,7 +32,7 @@ class LeRemoveDeviceFromPeriodicAdvertiserListTest : public ::testing::Test { ~LeRemoveDeviceFromPeriodicAdvertiserListTest() override = default; - protected: +protected: Address address_{0}; ControllerProperties properties_{}; LinkLayerController controller_{address_, properties_}; @@ -40,43 +40,37 @@ class LeRemoveDeviceFromPeriodicAdvertiserListTest : public ::testing::Test { TEST_F(LeRemoveDeviceFromPeriodicAdvertiserListTest, Success) { ASSERT_EQ(controller_.LeAddDeviceToPeriodicAdvertiserList( - AdvertiserAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address{1}, 1), + AdvertiserAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, 1), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeRemoveDeviceFromPeriodicAdvertiserList( - AdvertiserAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address{1}, 1), + AdvertiserAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, 1), ErrorCode::SUCCESS); } TEST_F(LeRemoveDeviceFromPeriodicAdvertiserListTest, NotFound) { ASSERT_EQ(controller_.LeAddDeviceToPeriodicAdvertiserList( - AdvertiserAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address{1}, 1), + AdvertiserAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, 1), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeRemoveDeviceFromPeriodicAdvertiserList( - AdvertiserAddressType::RANDOM_DEVICE_OR_IDENTITY_ADDRESS, - Address{1}, 1), + AdvertiserAddressType::RANDOM_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, 1), ErrorCode::UNKNOWN_ADVERTISING_IDENTIFIER); } TEST_F(LeRemoveDeviceFromPeriodicAdvertiserListTest, CreateSyncPending) { ASSERT_EQ(controller_.LeAddDeviceToPeriodicAdvertiserList( - AdvertiserAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address{1}, 1), + AdvertiserAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, 1), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LePeriodicAdvertisingCreateSync( - PeriodicAdvertisingOptions(), 0, - AdvertiserAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address{5}, false, 0x100, 0), + PeriodicAdvertisingOptions(), 0, + AdvertiserAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{5}, false, + 0x100, 0), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeRemoveDeviceFromPeriodicAdvertiserList( - AdvertiserAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address{1}, 1), + AdvertiserAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, 1), ErrorCode::COMMAND_DISALLOWED); } diff --git a/tools/rootcanal/test/controller/le/le_remove_device_from_resolving_list_test.cc b/tools/rootcanal/test/controller/le/le_remove_device_from_resolving_list_test.cc index 2f9d9f55afc..9676514dc30 100644 --- a/tools/rootcanal/test/controller/le/le_remove_device_from_resolving_list_test.cc +++ b/tools/rootcanal/test/controller/le/le_remove_device_from_resolving_list_test.cc @@ -24,7 +24,7 @@ namespace rootcanal { using namespace bluetooth::hci; class LeRemoveDeviceFromResolvingListTest : public ::testing::Test { - public: +public: LeRemoveDeviceFromResolvingListTest() { // Reduce the size of the resolving list to simplify testing. properties_.le_resolving_list_size = 2; @@ -32,7 +32,7 @@ class LeRemoveDeviceFromResolvingListTest : public ::testing::Test { ~LeRemoveDeviceFromResolvingListTest() override = default; - protected: +protected: Address address_{0}; ControllerProperties properties_{}; LinkLayerController controller_{address_, properties_}; @@ -40,74 +40,73 @@ class LeRemoveDeviceFromResolvingListTest : public ::testing::Test { TEST_F(LeRemoveDeviceFromResolvingListTest, Success) { ASSERT_EQ(controller_.LeAddDeviceToResolvingList( - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, - std::array{1}, std::array{1}), + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, + std::array{1}, std::array{1}), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeRemoveDeviceFromResolvingList( - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}), + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}), ErrorCode::SUCCESS); } TEST_F(LeRemoveDeviceFromResolvingListTest, NotFound) { ASSERT_EQ(controller_.LeAddDeviceToResolvingList( - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, - std::array{1}, std::array{1}), + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, + std::array{1}, std::array{1}), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeRemoveDeviceFromResolvingList( - PeerAddressType::RANDOM_DEVICE_OR_IDENTITY_ADDRESS, Address{1}), + PeerAddressType::RANDOM_DEVICE_OR_IDENTITY_ADDRESS, Address{1}), ErrorCode::UNKNOWN_CONNECTION); } TEST_F(LeRemoveDeviceFromResolvingListTest, ScanningActive) { ASSERT_EQ(controller_.LeAddDeviceToResolvingList( - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, - std::array{1}, std::array{1}), + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, + std::array{1}, std::array{1}), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeSetAddressResolutionEnable(true), ErrorCode::SUCCESS); controller_.LeSetScanEnable(true, false); ASSERT_EQ(controller_.LeRemoveDeviceFromResolvingList( - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}), + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}), ErrorCode::COMMAND_DISALLOWED); } TEST_F(LeRemoveDeviceFromResolvingListTest, LegacyAdvertisingActive) { ASSERT_EQ(controller_.LeAddDeviceToResolvingList( - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, - std::array{1}, std::array{1}), + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, + std::array{1}, std::array{1}), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeSetAddressResolutionEnable(true), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeSetAdvertisingEnable(true), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeRemoveDeviceFromResolvingList( - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}), + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}), ErrorCode::COMMAND_DISALLOWED); } TEST_F(LeRemoveDeviceFromResolvingListTest, ExtendedAdvertisingActive) { ASSERT_EQ(controller_.LeAddDeviceToResolvingList( - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, - std::array{1}, std::array{1}), + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, + std::array{1}, std::array{1}), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeSetAddressResolutionEnable(true), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, - 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::LISTED_SCAN, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::LISTED_SCAN, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable( - true, {MakeEnabledSet(0, 0, 0)}), + ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable(true, {MakeEnabledSet(0, 0, 0)}), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeRemoveDeviceFromResolvingList( - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}), + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}), ErrorCode::COMMAND_DISALLOWED); } diff --git a/tools/rootcanal/test/controller/le/le_scanning_filter_duplicates_test.cc b/tools/rootcanal/test/controller/le/le_scanning_filter_duplicates_test.cc index 6ef5a2b1bf8..6a817ce6bfa 100644 --- a/tools/rootcanal/test/controller/le/le_scanning_filter_duplicates_test.cc +++ b/tools/rootcanal/test/controller/le/le_scanning_filter_duplicates_test.cc @@ -32,7 +32,7 @@ namespace rootcanal { using namespace bluetooth::hci; class LeScanningFilterDuplicates : public ::testing::Test { - public: +public: LeScanningFilterDuplicates() {} ~LeScanningFilterDuplicates() override = default; @@ -49,80 +49,69 @@ class LeScanningFilterDuplicates : public ::testing::Test { // Set event mask to receive (extended) Advertising Reports controller_.SetEventMask(to_mask(EventCode::LE_META_EVENT)); - controller_.SetLeEventMask( - to_mask(SubeventCode::ADVERTISING_REPORT) | - to_mask(SubeventCode::EXTENDED_ADVERTISING_REPORT) | - to_mask(SubeventCode::DIRECTED_ADVERTISING_REPORT)); + controller_.SetLeEventMask(to_mask(SubeventCode::ADVERTISING_REPORT) | + to_mask(SubeventCode::EXTENDED_ADVERTISING_REPORT) | + to_mask(SubeventCode::DIRECTED_ADVERTISING_REPORT)); } void StartScan(FilterDuplicates filter_duplicates) { - ASSERT_EQ(ErrorCode::SUCCESS, controller_.LeSetScanParameters( - LeScanType::ACTIVE, 0x4, 0x4, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - LeScanningFilterPolicy::ACCEPT_ALL)); ASSERT_EQ(ErrorCode::SUCCESS, - controller_.LeSetScanEnable( - true, filter_duplicates == FilterDuplicates::ENABLED)); + controller_.LeSetScanParameters(LeScanType::ACTIVE, 0x4, 0x4, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + LeScanningFilterPolicy::ACCEPT_ALL)); + ASSERT_EQ(ErrorCode::SUCCESS, + controller_.LeSetScanEnable(true, filter_duplicates == FilterDuplicates::ENABLED)); } - void StopScan(void) { - ASSERT_EQ(ErrorCode::SUCCESS, controller_.LeSetScanEnable(false, false)); - } + void StopScan(void) { ASSERT_EQ(ErrorCode::SUCCESS, controller_.LeSetScanEnable(false, false)); } - void StartExtendedScan(FilterDuplicates filter_duplicates, - uint16_t duration = 0, uint16_t period = 0) { + void StartExtendedScan(FilterDuplicates filter_duplicates, uint16_t duration = 0, + uint16_t period = 0) { bluetooth::hci::ScanningPhyParameters param; param.le_scan_type_ = LeScanType::ACTIVE; param.le_scan_interval_ = 0x4; param.le_scan_window_ = 0x4; + ASSERT_EQ(ErrorCode::SUCCESS, controller_.LeSetExtendedScanParameters( + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + LeScanningFilterPolicy::ACCEPT_ALL, 0x1, {param})); ASSERT_EQ(ErrorCode::SUCCESS, - controller_.LeSetExtendedScanParameters( - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - LeScanningFilterPolicy::ACCEPT_ALL, 0x1, {param})); - ASSERT_EQ(ErrorCode::SUCCESS, - controller_.LeSetExtendedScanEnable(true, filter_duplicates, - duration, period)); + controller_.LeSetExtendedScanEnable(true, filter_duplicates, duration, period)); } void StopExtendedScan(void) { - ASSERT_EQ(ErrorCode::SUCCESS, controller_.LeSetExtendedScanEnable( - false, FilterDuplicates::DISABLED, 0, 0)); + ASSERT_EQ(ErrorCode::SUCCESS, + controller_.LeSetExtendedScanEnable(false, FilterDuplicates::DISABLED, 0, 0)); } /// Helper for building ScanResponse packets - static model::packets::LinkLayerPacketView LeScanResponse( - std::vector const data = {}) { + static model::packets::LinkLayerPacketView LeScanResponse(std::vector const data = {}) { return FromBuilder(model::packets::LeScanResponseBuilder::Create( - Address::kEmpty, Address::kEmpty, model::packets::AddressType::PUBLIC, - data)); + Address::kEmpty, Address::kEmpty, model::packets::AddressType::PUBLIC, data)); } /// Helper for building LeLegacyAdvertisingPdu packets static model::packets::LinkLayerPacketView LeLegacyAdvertisingPdu( - std::vector const data = {}) { + std::vector const data = {}) { return FromBuilder(model::packets::LeLegacyAdvertisingPduBuilder::Create( - Address::kEmpty, Address::kEmpty, model::packets::AddressType::PUBLIC, - model::packets::AddressType::PUBLIC, - model::packets::LegacyAdvertisingType::ADV_IND, data)); + Address::kEmpty, Address::kEmpty, model::packets::AddressType::PUBLIC, + model::packets::AddressType::PUBLIC, model::packets::LegacyAdvertisingType::ADV_IND, + data)); } /// Helper for building LeExtendedAdvertisingPdu packets static model::packets::LinkLayerPacketView LeExtendedAdvertisingPdu( - std::vector const data = {}) { + std::vector const data = {}) { return FromBuilder(model::packets::LeExtendedAdvertisingPduBuilder::Create( - Address::kEmpty, Address::kEmpty, model::packets::AddressType::PUBLIC, - model::packets::AddressType::PUBLIC, 0, 1, 0, 0, 0, - model::packets::PhyType::LE_1M, model::packets::PhyType::LE_1M, 0, - data)); + Address::kEmpty, Address::kEmpty, model::packets::AddressType::PUBLIC, + model::packets::AddressType::PUBLIC, 0, 1, 0, 0, 0, model::packets::PhyType::LE_1M, + model::packets::PhyType::LE_1M, 0, data)); } static model::packets::LinkLayerPacketView FromBuilder( - std::unique_ptr builder) { - auto data = - std::make_shared>(builder->SerializeToBytes()); - return model::packets::LinkLayerPacketView::Create( - pdl::packet::slice(data)); + std::unique_ptr builder) { + auto data = std::make_shared>(builder->SerializeToBytes()); + return model::packets::LinkLayerPacketView::Create(pdl::packet::slice(data)); } enum Filtered { @@ -146,20 +135,19 @@ class LeScanningFilterDuplicates : public ::testing::Test { return kReported; } - protected: +protected: Address address_{}; ControllerProperties properties_{}; LinkLayerController controller_{address_, properties_}; static unsigned event_listener_called_; - private: +private: static void event_listener_(std::shared_ptr /* event */) { event_listener_called_++; } - static void remote_listener_( - std::shared_ptr /* packet */, - Phy::Type /* phy */, int8_t /* tx_power */) {} + static void remote_listener_(std::shared_ptr /* packet */, + Phy::Type /* phy */, int8_t /* tx_power */) {} }; unsigned LeScanningFilterDuplicates::event_listener_called_ = 0; @@ -226,8 +214,7 @@ TEST_F(LeScanningFilterDuplicates, ExtendedAdvertisingPduDuringExtendedScan) { ASSERT_EQ(kFiltered, SendPacketAndCheck(LeExtendedAdvertisingPdu({0, 1}))); } -TEST_F(LeScanningFilterDuplicates, - LeScanResponseToLegacyAdvertisingDuringLegacyScan) { +TEST_F(LeScanningFilterDuplicates, LeScanResponseToLegacyAdvertisingDuringLegacyScan) { StopScan(); SendPacket(LeLegacyAdvertisingPdu()); ASSERT_EQ(kFiltered, SendPacketAndCheck(LeScanResponse())); @@ -256,8 +243,7 @@ TEST_F(LeScanningFilterDuplicates, ASSERT_EQ(kFiltered, SendPacketAndCheck(LeScanResponse({0, 1}))); } -TEST_F(LeScanningFilterDuplicates, - LeScanResponseToLegacyAdvertisingDuringExtendedScan) { +TEST_F(LeScanningFilterDuplicates, LeScanResponseToLegacyAdvertisingDuringExtendedScan) { StopExtendedScan(); SendPacket(LeLegacyAdvertisingPdu()); ASSERT_EQ(kFiltered, SendPacketAndCheck(LeScanResponse())); @@ -286,8 +272,7 @@ TEST_F(LeScanningFilterDuplicates, ASSERT_EQ(kFiltered, SendPacketAndCheck(LeScanResponse({0, 1}))); } -TEST_F(LeScanningFilterDuplicates, - LeScanResponseToExtendedAdvertisingDuringLegacyScan) { +TEST_F(LeScanningFilterDuplicates, LeScanResponseToExtendedAdvertisingDuringLegacyScan) { StopScan(); SendPacket(LeExtendedAdvertisingPdu()); ASSERT_EQ(kFiltered, SendPacketAndCheck(LeScanResponse())); @@ -299,8 +284,7 @@ TEST_F(LeScanningFilterDuplicates, ASSERT_EQ(kFiltered, SendPacketAndCheck(LeScanResponse())); } -TEST_F(LeScanningFilterDuplicates, - LeScanResponseToExtendedAdvertisingDuringExtendedScan) { +TEST_F(LeScanningFilterDuplicates, LeScanResponseToExtendedAdvertisingDuringExtendedScan) { StopExtendedScan(); SendPacket(LeExtendedAdvertisingPdu()); ASSERT_EQ(kFiltered, SendPacketAndCheck(LeScanResponse())); diff --git a/tools/rootcanal/test/controller/le/le_set_address_resolution_enable_test.cc b/tools/rootcanal/test/controller/le/le_set_address_resolution_enable_test.cc index edfc6b823ff..00546f45176 100644 --- a/tools/rootcanal/test/controller/le/le_set_address_resolution_enable_test.cc +++ b/tools/rootcanal/test/controller/le/le_set_address_resolution_enable_test.cc @@ -24,11 +24,11 @@ namespace rootcanal { using namespace bluetooth::hci; class LeSetAddressResolutionEnableTest : public ::testing::Test { - public: +public: LeSetAddressResolutionEnableTest() = default; ~LeSetAddressResolutionEnableTest() override = default; - protected: +protected: Address address_{0}; ControllerProperties properties_{}; LinkLayerController controller_{address_, properties_}; @@ -36,42 +36,34 @@ class LeSetAddressResolutionEnableTest : public ::testing::Test { TEST_F(LeSetAddressResolutionEnableTest, Success) { ASSERT_EQ(controller_.LeSetAddressResolutionEnable(true), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetAddressResolutionEnable(false), - ErrorCode::SUCCESS); + ASSERT_EQ(controller_.LeSetAddressResolutionEnable(false), ErrorCode::SUCCESS); } TEST_F(LeSetAddressResolutionEnableTest, ScanningActive) { controller_.LeSetScanEnable(true, false); - ASSERT_EQ(controller_.LeSetAddressResolutionEnable(true), - ErrorCode::COMMAND_DISALLOWED); - ASSERT_EQ(controller_.LeSetAddressResolutionEnable(false), - ErrorCode::COMMAND_DISALLOWED); + ASSERT_EQ(controller_.LeSetAddressResolutionEnable(true), ErrorCode::COMMAND_DISALLOWED); + ASSERT_EQ(controller_.LeSetAddressResolutionEnable(false), ErrorCode::COMMAND_DISALLOWED); } TEST_F(LeSetAddressResolutionEnableTest, LegacyAdvertisingActive) { ASSERT_EQ(controller_.LeSetAdvertisingEnable(true), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetAddressResolutionEnable(true), - ErrorCode::COMMAND_DISALLOWED); - ASSERT_EQ(controller_.LeSetAddressResolutionEnable(false), - ErrorCode::COMMAND_DISALLOWED); + ASSERT_EQ(controller_.LeSetAddressResolutionEnable(true), ErrorCode::COMMAND_DISALLOWED); + ASSERT_EQ(controller_.LeSetAddressResolutionEnable(false), ErrorCode::COMMAND_DISALLOWED); } TEST_F(LeSetAddressResolutionEnableTest, ExtendedAdvertisingActive) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, - 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::LISTED_SCAN, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::LISTED_SCAN, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable( - true, {MakeEnabledSet(0, 0, 0)}), + ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable(true, {MakeEnabledSet(0, 0, 0)}), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetAddressResolutionEnable(true), - ErrorCode::COMMAND_DISALLOWED); - ASSERT_EQ(controller_.LeSetAddressResolutionEnable(false), - ErrorCode::COMMAND_DISALLOWED); + ASSERT_EQ(controller_.LeSetAddressResolutionEnable(true), ErrorCode::COMMAND_DISALLOWED); + ASSERT_EQ(controller_.LeSetAddressResolutionEnable(false), ErrorCode::COMMAND_DISALLOWED); } } // namespace rootcanal diff --git a/tools/rootcanal/test/controller/le/le_set_advertising_enable_test.cc b/tools/rootcanal/test/controller/le/le_set_advertising_enable_test.cc index d9ffb2a5abc..435bdd6ec49 100644 --- a/tools/rootcanal/test/controller/le/le_set_advertising_enable_test.cc +++ b/tools/rootcanal/test/controller/le/le_set_advertising_enable_test.cc @@ -23,11 +23,11 @@ namespace rootcanal { using namespace bluetooth::hci; class LeSetAdvertisingEnableTest : public ::testing::Test { - public: +public: LeSetAdvertisingEnableTest() = default; ~LeSetAdvertisingEnableTest() override = default; - protected: +protected: Address address_{0}; ControllerProperties properties_{}; LinkLayerController controller_{address_, properties_}; @@ -35,20 +35,18 @@ class LeSetAdvertisingEnableTest : public ::testing::Test { TEST_F(LeSetAdvertisingEnableTest, EnableUsingPublicAddress) { ASSERT_EQ(controller_.LeSetAdvertisingParameters( - 0x0800, 0x0800, AdvertisingType::ADV_IND, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, 0x7, AdvertisingFilterPolicy::ALL_DEVICES), + 0x0800, 0x0800, AdvertisingType::ADV_IND, OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, 0x7, + AdvertisingFilterPolicy::ALL_DEVICES), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeSetAdvertisingEnable(true), ErrorCode::SUCCESS); } TEST_F(LeSetAdvertisingEnableTest, EnableUsingRandomAddress) { ASSERT_EQ(controller_.LeSetAdvertisingParameters( - 0x0800, 0x0800, AdvertisingType::ADV_IND, - OwnAddressType::RANDOM_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, 0x7, AdvertisingFilterPolicy::ALL_DEVICES), + 0x0800, 0x0800, AdvertisingType::ADV_IND, OwnAddressType::RANDOM_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, 0x7, + AdvertisingFilterPolicy::ALL_DEVICES), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeSetRandomAddress(Address{1}), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeSetAdvertisingEnable(true), ErrorCode::SUCCESS); @@ -56,14 +54,14 @@ TEST_F(LeSetAdvertisingEnableTest, EnableUsingRandomAddress) { TEST_F(LeSetAdvertisingEnableTest, EnableUsingResolvableAddress) { ASSERT_EQ(controller_.LeSetAdvertisingParameters( - 0x0800, 0x0800, AdvertisingType::ADV_IND, - OwnAddressType::RESOLVABLE_OR_RANDOM_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, - 0x7, AdvertisingFilterPolicy::ALL_DEVICES), + 0x0800, 0x0800, AdvertisingType::ADV_IND, + OwnAddressType::RESOLVABLE_OR_RANDOM_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, 0x7, + AdvertisingFilterPolicy::ALL_DEVICES), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeAddDeviceToResolvingList( - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, - std::array{1}, std::array{1}), + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, + std::array{1}, std::array{1}), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeSetAddressResolutionEnable(true), ErrorCode::SUCCESS); // Note: the command will fail if the peer address is not in the resolvable @@ -78,27 +76,24 @@ TEST_F(LeSetAdvertisingEnableTest, Disable) { TEST_F(LeSetAdvertisingEnableTest, NoRandomAddress) { ASSERT_EQ(controller_.LeSetAdvertisingParameters( - 0x0800, 0x0800, AdvertisingType::ADV_IND, - OwnAddressType::RANDOM_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, 0x7, AdvertisingFilterPolicy::ALL_DEVICES), + 0x0800, 0x0800, AdvertisingType::ADV_IND, OwnAddressType::RANDOM_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, 0x7, + AdvertisingFilterPolicy::ALL_DEVICES), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetAdvertisingEnable(true), - ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); + ASSERT_EQ(controller_.LeSetAdvertisingEnable(true), ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); } TEST_F(LeSetAdvertisingEnableTest, NoResolvableOrRandomAddress) { ASSERT_EQ(controller_.LeSetAddressResolutionEnable(true), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeSetAdvertisingParameters( - 0x0800, 0x0800, AdvertisingType::ADV_IND, - OwnAddressType::RESOLVABLE_OR_RANDOM_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, 0x7, AdvertisingFilterPolicy::ALL_DEVICES), + 0x0800, 0x0800, AdvertisingType::ADV_IND, + OwnAddressType::RESOLVABLE_OR_RANDOM_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, 0x7, + AdvertisingFilterPolicy::ALL_DEVICES), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetAdvertisingEnable(true), - ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); + ASSERT_EQ(controller_.LeSetAdvertisingEnable(true), ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); } } // namespace rootcanal diff --git a/tools/rootcanal/test/controller/le/le_set_advertising_parameters_test.cc b/tools/rootcanal/test/controller/le/le_set_advertising_parameters_test.cc index 56f85bc3fa7..1bc71fa200b 100644 --- a/tools/rootcanal/test/controller/le/le_set_advertising_parameters_test.cc +++ b/tools/rootcanal/test/controller/le/le_set_advertising_parameters_test.cc @@ -23,11 +23,11 @@ namespace rootcanal { using namespace bluetooth::hci; class LeSetAdvertisingParametersTest : public ::testing::Test { - public: +public: LeSetAdvertisingParametersTest() = default; ~LeSetAdvertisingParametersTest() override = default; - protected: +protected: Address address_{0}; ControllerProperties properties_{}; LinkLayerController controller_{address_, properties_}; @@ -35,10 +35,9 @@ class LeSetAdvertisingParametersTest : public ::testing::Test { TEST_F(LeSetAdvertisingParametersTest, Success) { ASSERT_EQ(controller_.LeSetAdvertisingParameters( - 0x0800, 0x0800, AdvertisingType::ADV_IND, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, 0x7, AdvertisingFilterPolicy::ALL_DEVICES), + 0x0800, 0x0800, AdvertisingType::ADV_IND, OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, 0x7, + AdvertisingFilterPolicy::ALL_DEVICES), ErrorCode::SUCCESS); } @@ -46,56 +45,49 @@ TEST_F(LeSetAdvertisingParametersTest, AdvertisingActive) { ASSERT_EQ(controller_.LeSetAdvertisingEnable(true), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeSetAdvertisingParameters( - 0x0800, 0x0800, AdvertisingType::ADV_IND, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, 0x7, AdvertisingFilterPolicy::ALL_DEVICES), + 0x0800, 0x0800, AdvertisingType::ADV_IND, OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, 0x7, + AdvertisingFilterPolicy::ALL_DEVICES), ErrorCode::COMMAND_DISALLOWED); } TEST_F(LeSetAdvertisingParametersTest, InvalidChannelMap) { ASSERT_EQ(controller_.LeSetAdvertisingParameters( - 0x0800, 0x0800, AdvertisingType::ADV_IND, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, 0x0, AdvertisingFilterPolicy::ALL_DEVICES), + 0x0800, 0x0800, AdvertisingType::ADV_IND, OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, 0x0, + AdvertisingFilterPolicy::ALL_DEVICES), ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); } TEST_F(LeSetAdvertisingParametersTest, InvalidAdvertisingInterval) { ASSERT_EQ(controller_.LeSetAdvertisingParameters( - 0x0, 0x0800, AdvertisingType::ADV_IND, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, 0x7, AdvertisingFilterPolicy::ALL_DEVICES), + 0x0, 0x0800, AdvertisingType::ADV_IND, OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, 0x7, + AdvertisingFilterPolicy::ALL_DEVICES), ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); ASSERT_EQ(controller_.LeSetAdvertisingParameters( - 0x0800, 0x0, AdvertisingType::ADV_IND, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, 0x7, AdvertisingFilterPolicy::ALL_DEVICES), + 0x0800, 0x0, AdvertisingType::ADV_IND, OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, 0x7, + AdvertisingFilterPolicy::ALL_DEVICES), ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); ASSERT_EQ(controller_.LeSetAdvertisingParameters( - 0x4001, 0x0800, AdvertisingType::ADV_IND, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, 0x7, AdvertisingFilterPolicy::ALL_DEVICES), + 0x4001, 0x0800, AdvertisingType::ADV_IND, OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, 0x7, + AdvertisingFilterPolicy::ALL_DEVICES), ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); ASSERT_EQ(controller_.LeSetAdvertisingParameters( - 0x0800, 0x4001, AdvertisingType::ADV_IND, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, 0x7, AdvertisingFilterPolicy::ALL_DEVICES), + 0x0800, 0x4001, AdvertisingType::ADV_IND, OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, 0x7, + AdvertisingFilterPolicy::ALL_DEVICES), ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); ASSERT_EQ(controller_.LeSetAdvertisingParameters( - 0x0900, 0x0800, AdvertisingType::ADV_IND, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, 0x7, AdvertisingFilterPolicy::ALL_DEVICES), + 0x0900, 0x0800, AdvertisingType::ADV_IND, OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, 0x7, + AdvertisingFilterPolicy::ALL_DEVICES), ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); } diff --git a/tools/rootcanal/test/controller/le/le_set_extended_advertising_data_test.cc b/tools/rootcanal/test/controller/le/le_set_extended_advertising_data_test.cc index ed27f1280d0..2ffa673aa66 100644 --- a/tools/rootcanal/test/controller/le/le_set_extended_advertising_data_test.cc +++ b/tools/rootcanal/test/controller/le/le_set_extended_advertising_data_test.cc @@ -24,15 +24,15 @@ namespace rootcanal { using namespace bluetooth::hci; class LeSetExtendedAdvertisingDataTest : public ::testing::Test { - public: +public: LeSetExtendedAdvertisingDataTest() { // Reduce the number of advertising sets to simplify testing. properties_.le_num_supported_advertising_sets = 2; properties_.le_max_advertising_data_length = 300; - }; + } ~LeSetExtendedAdvertisingDataTest() override = default; - protected: +protected: Address address_{0}; ControllerProperties properties_{}; LinkLayerController controller_{address_, properties_}; @@ -40,209 +40,199 @@ class LeSetExtendedAdvertisingDataTest : public ::testing::Test { TEST_F(LeSetExtendedAdvertisingDataTest, Complete) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, - 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); std::vector advertising_data = {1, 2, 3}; - ASSERT_EQ(controller_.LeSetExtendedAdvertisingData( - 0, Operation::COMPLETE_ADVERTISEMENT, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, advertising_data), + ASSERT_EQ(controller_.LeSetExtendedAdvertisingData(0, Operation::COMPLETE_ADVERTISEMENT, + FragmentPreference::CONTROLLER_MAY_FRAGMENT, + advertising_data), ErrorCode::SUCCESS); } TEST_F(LeSetExtendedAdvertisingDataTest, Unchanged) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, - 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); std::vector advertising_data = {1, 2, 3}; - ASSERT_EQ(controller_.LeSetExtendedAdvertisingData( - 0, Operation::COMPLETE_ADVERTISEMENT, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, advertising_data), + ASSERT_EQ(controller_.LeSetExtendedAdvertisingData(0, Operation::COMPLETE_ADVERTISEMENT, + FragmentPreference::CONTROLLER_MAY_FRAGMENT, + advertising_data), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable( - true, {MakeEnabledSet(0, 0, 0)}), + ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable(true, {MakeEnabledSet(0, 0, 0)}), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeSetExtendedAdvertisingData( - 0, Operation::UNCHANGED_DATA, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, {}), + 0, Operation::UNCHANGED_DATA, FragmentPreference::CONTROLLER_MAY_FRAGMENT, {}), ErrorCode::SUCCESS); } TEST_F(LeSetExtendedAdvertisingDataTest, Fragmented) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, - 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); std::vector first_advertising_data_fragment = {1, 2, 3}; std::vector intermediate_advertising_data_fragment = {4, 5, 6}; std::vector last_advertising_data_fragment = {7, 8, 9}; - ASSERT_EQ(controller_.LeSetExtendedAdvertisingData( - 0, Operation::FIRST_FRAGMENT, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, - first_advertising_data_fragment), + ASSERT_EQ(controller_.LeSetExtendedAdvertisingData(0, Operation::FIRST_FRAGMENT, + FragmentPreference::CONTROLLER_MAY_FRAGMENT, + first_advertising_data_fragment), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetExtendedAdvertisingData( - 0, Operation::INTERMEDIATE_FRAGMENT, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, - intermediate_advertising_data_fragment), + ASSERT_EQ(controller_.LeSetExtendedAdvertisingData(0, Operation::INTERMEDIATE_FRAGMENT, + FragmentPreference::CONTROLLER_MAY_FRAGMENT, + intermediate_advertising_data_fragment), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetExtendedAdvertisingData( - 0, Operation::LAST_FRAGMENT, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, - last_advertising_data_fragment), + ASSERT_EQ(controller_.LeSetExtendedAdvertisingData(0, Operation::LAST_FRAGMENT, + FragmentPreference::CONTROLLER_MAY_FRAGMENT, + last_advertising_data_fragment), ErrorCode::SUCCESS); } TEST_F(LeSetExtendedAdvertisingDataTest, UnknownAdvertisingHandle) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, - 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); std::vector advertising_data = {1, 2, 3}; - ASSERT_EQ(controller_.LeSetExtendedAdvertisingData( - 1, Operation::COMPLETE_ADVERTISEMENT, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, advertising_data), + ASSERT_EQ(controller_.LeSetExtendedAdvertisingData(1, Operation::COMPLETE_ADVERTISEMENT, + FragmentPreference::CONTROLLER_MAY_FRAGMENT, + advertising_data), ErrorCode::UNKNOWN_ADVERTISING_IDENTIFIER); } TEST_F(LeSetExtendedAdvertisingDataTest, UnexpectedAdvertisingData) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(SCANNABLE), 0x0800, 0x0800, - 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(SCANNABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); std::vector advertising_data = {1, 2, 3}; - ASSERT_EQ(controller_.LeSetExtendedAdvertisingData( - 0, Operation::COMPLETE_ADVERTISEMENT, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, advertising_data), + ASSERT_EQ(controller_.LeSetExtendedAdvertisingData(0, Operation::COMPLETE_ADVERTISEMENT, + FragmentPreference::CONTROLLER_MAY_FRAGMENT, + advertising_data), ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); } TEST_F(LeSetExtendedAdvertisingDataTest, IncompleteLegacyAdvertisingData) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(LEGACY | SCANNABLE), 0x0800, - 0x0800, 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(LEGACY | SCANNABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); std::vector first_advertising_data_fragment = {1, 2, 3}; - ASSERT_EQ(controller_.LeSetExtendedAdvertisingData( - 0, Operation::FIRST_FRAGMENT, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, - first_advertising_data_fragment), + ASSERT_EQ(controller_.LeSetExtendedAdvertisingData(0, Operation::FIRST_FRAGMENT, + FragmentPreference::CONTROLLER_MAY_FRAGMENT, + first_advertising_data_fragment), ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); } TEST_F(LeSetExtendedAdvertisingDataTest, InvalidLegacyAdvertisingData) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(LEGACY | SCANNABLE), 0x0800, - 0x0800, 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(LEGACY | SCANNABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); std::vector advertising_data = {1, 2, 3}; advertising_data.resize(32); - ASSERT_EQ(controller_.LeSetExtendedAdvertisingData( - 0, Operation::COMPLETE_ADVERTISEMENT, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, advertising_data), + ASSERT_EQ(controller_.LeSetExtendedAdvertisingData(0, Operation::COMPLETE_ADVERTISEMENT, + FragmentPreference::CONTROLLER_MAY_FRAGMENT, + advertising_data), ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); } TEST_F(LeSetExtendedAdvertisingDataTest, UnchangedWhenDisabled) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, - 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); std::vector advertising_data = {1, 2, 3}; - ASSERT_EQ(controller_.LeSetExtendedAdvertisingData( - 0, Operation::COMPLETE_ADVERTISEMENT, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, advertising_data), + ASSERT_EQ(controller_.LeSetExtendedAdvertisingData(0, Operation::COMPLETE_ADVERTISEMENT, + FragmentPreference::CONTROLLER_MAY_FRAGMENT, + advertising_data), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetExtendedAdvertisingData( - 0, Operation::UNCHANGED_DATA, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, advertising_data), + ASSERT_EQ(controller_.LeSetExtendedAdvertisingData(0, Operation::UNCHANGED_DATA, + FragmentPreference::CONTROLLER_MAY_FRAGMENT, + advertising_data), ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); } TEST_F(LeSetExtendedAdvertisingDataTest, UnchangedWhenAdvertisingDataEmpty) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, - 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable( - true, {MakeEnabledSet(0, 0, 0)}), + ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable(true, {MakeEnabledSet(0, 0, 0)}), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeSetExtendedAdvertisingData( - 0, Operation::UNCHANGED_DATA, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, {}), + 0, Operation::UNCHANGED_DATA, FragmentPreference::CONTROLLER_MAY_FRAGMENT, {}), ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); } TEST_F(LeSetExtendedAdvertisingDataTest, UnchangedWhenUsingLegacyAdvertising) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(LEGACY | SCANNABLE), 0x0800, - 0x0800, 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(LEGACY | SCANNABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable( - true, {MakeEnabledSet(0, 0, 0)}), + ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable(true, {MakeEnabledSet(0, 0, 0)}), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeSetExtendedAdvertisingData( - 0, Operation::UNCHANGED_DATA, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, {}), + 0, Operation::UNCHANGED_DATA, FragmentPreference::CONTROLLER_MAY_FRAGMENT, {}), ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); } TEST_F(LeSetExtendedAdvertisingDataTest, EmptyAdvertisingDataFragment) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, - 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); std::vector first_advertising_data_fragment = {1, 2, 3}; @@ -250,96 +240,85 @@ TEST_F(LeSetExtendedAdvertisingDataTest, EmptyAdvertisingDataFragment) { std::vector last_advertising_data_fragment = {7, 8, 9}; ASSERT_EQ(controller_.LeSetExtendedAdvertisingData( - 0, Operation::FIRST_FRAGMENT, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, {}), + 0, Operation::FIRST_FRAGMENT, FragmentPreference::CONTROLLER_MAY_FRAGMENT, {}), ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); - ASSERT_EQ(controller_.LeSetExtendedAdvertisingData( - 0, Operation::FIRST_FRAGMENT, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, - first_advertising_data_fragment), + ASSERT_EQ(controller_.LeSetExtendedAdvertisingData(0, Operation::FIRST_FRAGMENT, + FragmentPreference::CONTROLLER_MAY_FRAGMENT, + first_advertising_data_fragment), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetExtendedAdvertisingData( - 0, Operation::INTERMEDIATE_FRAGMENT, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, {}), - ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); + ASSERT_EQ( + controller_.LeSetExtendedAdvertisingData(0, Operation::INTERMEDIATE_FRAGMENT, + FragmentPreference::CONTROLLER_MAY_FRAGMENT, {}), + ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); - ASSERT_EQ(controller_.LeSetExtendedAdvertisingData( - 0, Operation::INTERMEDIATE_FRAGMENT, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, - intermediate_advertising_data_fragment), + ASSERT_EQ(controller_.LeSetExtendedAdvertisingData(0, Operation::INTERMEDIATE_FRAGMENT, + FragmentPreference::CONTROLLER_MAY_FRAGMENT, + intermediate_advertising_data_fragment), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeSetExtendedAdvertisingData( - 0, Operation::LAST_FRAGMENT, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, {}), + 0, Operation::LAST_FRAGMENT, FragmentPreference::CONTROLLER_MAY_FRAGMENT, {}), ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); - ASSERT_EQ(controller_.LeSetExtendedAdvertisingData( - 0, Operation::LAST_FRAGMENT, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, - last_advertising_data_fragment), + ASSERT_EQ(controller_.LeSetExtendedAdvertisingData(0, Operation::LAST_FRAGMENT, + FragmentPreference::CONTROLLER_MAY_FRAGMENT, + last_advertising_data_fragment), ErrorCode::SUCCESS); } TEST_F(LeSetExtendedAdvertisingDataTest, AdvertisingEnabled) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, - 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable( - true, {MakeEnabledSet(0, 0, 0)}), + ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable(true, {MakeEnabledSet(0, 0, 0)}), ErrorCode::SUCCESS); std::vector first_advertising_data_fragment = {1, 2, 3}; - ASSERT_EQ(controller_.LeSetExtendedAdvertisingData( - 0, Operation::FIRST_FRAGMENT, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, - first_advertising_data_fragment), + ASSERT_EQ(controller_.LeSetExtendedAdvertisingData(0, Operation::FIRST_FRAGMENT, + FragmentPreference::CONTROLLER_MAY_FRAGMENT, + first_advertising_data_fragment), ErrorCode::COMMAND_DISALLOWED); } -TEST_F(LeSetExtendedAdvertisingDataTest, - AdvertisingDataLargerThanMemoryCapacity) { +TEST_F(LeSetExtendedAdvertisingDataTest, AdvertisingDataLargerThanMemoryCapacity) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, - 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); std::vector advertising_data_fragment = {1, 2, 3}; advertising_data_fragment.resize(properties_.le_max_advertising_data_length); - ASSERT_EQ(controller_.LeSetExtendedAdvertisingData( - 0, Operation::FIRST_FRAGMENT, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, - advertising_data_fragment), + ASSERT_EQ(controller_.LeSetExtendedAdvertisingData(0, Operation::FIRST_FRAGMENT, + FragmentPreference::CONTROLLER_MAY_FRAGMENT, + advertising_data_fragment), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetExtendedAdvertisingData( - 0, Operation::LAST_FRAGMENT, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, - advertising_data_fragment), + ASSERT_EQ(controller_.LeSetExtendedAdvertisingData(0, Operation::LAST_FRAGMENT, + FragmentPreference::CONTROLLER_MAY_FRAGMENT, + advertising_data_fragment), ErrorCode::MEMORY_CAPACITY_EXCEEDED); } TEST_F(LeSetExtendedAdvertisingDataTest, AdvertisingDataLargerThanPduCapacity) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, - 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable( - true, {MakeEnabledSet(0, 0, 0)}), + ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable(true, {MakeEnabledSet(0, 0, 0)}), ErrorCode::SUCCESS); // No AUX chain possible for connectable advertising PDUs, @@ -347,9 +326,9 @@ TEST_F(LeSetExtendedAdvertisingDataTest, AdvertisingDataLargerThanPduCapacity) { std::vector advertising_data = {1, 2, 3}; advertising_data.resize(254); - ASSERT_EQ(controller_.LeSetExtendedAdvertisingData( - 0, Operation::COMPLETE_ADVERTISEMENT, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, advertising_data), + ASSERT_EQ(controller_.LeSetExtendedAdvertisingData(0, Operation::COMPLETE_ADVERTISEMENT, + FragmentPreference::CONTROLLER_MAY_FRAGMENT, + advertising_data), ErrorCode::PACKET_TOO_LONG); } diff --git a/tools/rootcanal/test/controller/le/le_set_extended_advertising_enable_test.cc b/tools/rootcanal/test/controller/le/le_set_extended_advertising_enable_test.cc index a83e72631da..5addb9cbe35 100644 --- a/tools/rootcanal/test/controller/le/le_set_extended_advertising_enable_test.cc +++ b/tools/rootcanal/test/controller/le/le_set_extended_advertising_enable_test.cc @@ -24,136 +24,123 @@ namespace rootcanal { using namespace bluetooth::hci; class LeSetExtendedAdvertisingEnableTest : public ::testing::Test { - public: +public: LeSetExtendedAdvertisingEnableTest() { // Reduce the number of advertising sets to simplify testing. properties_.le_num_supported_advertising_sets = 2; properties_.le_max_advertising_data_length = 2000; - }; + } ~LeSetExtendedAdvertisingEnableTest() override = default; - protected: +protected: Address address_{0}; ControllerProperties properties_{}; LinkLayerController controller_{address_, properties_}; }; TEST_F(LeSetExtendedAdvertisingEnableTest, DisableAll) { - ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable(false, {}), - ErrorCode::SUCCESS); + ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable(false, {}), ErrorCode::SUCCESS); } TEST_F(LeSetExtendedAdvertisingEnableTest, DisableSelected) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, - 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable( - false, {MakeEnabledSet(0, 0, 0)}), + ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable(false, {MakeEnabledSet(0, 0, 0)}), ErrorCode::SUCCESS); } TEST_F(LeSetExtendedAdvertisingEnableTest, EnableUsingPublicAddress) { - ASSERT_EQ( - controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(LEGACY | CONNECTABLE | SCANNABLE), - 0x0800, 0x0800, 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, - AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, - SecondaryPhyType::LE_2M, 0x0, false), - ErrorCode::SUCCESS); + ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( + 0, MakeAdvertisingEventProperties(LEGACY | CONNECTABLE | SCANNABLE), 0x0800, + 0x0800, 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), + ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable( - true, {MakeEnabledSet(0, 0, 0)}), + ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable(true, {MakeEnabledSet(0, 0, 0)}), ErrorCode::SUCCESS); } TEST_F(LeSetExtendedAdvertisingEnableTest, EnableUsingTimeout) { - ASSERT_EQ( - controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(LEGACY | CONNECTABLE | SCANNABLE), - 0x0800, 0x0800, 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, - AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, - SecondaryPhyType::LE_2M, 0x0, false), - ErrorCode::SUCCESS); + ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( + 0, MakeAdvertisingEventProperties(LEGACY | CONNECTABLE | SCANNABLE), 0x0800, + 0x0800, 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), + ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable( - true, {MakeEnabledSet(0, 0x40, 0)}), + ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable(true, {MakeEnabledSet(0, 0x40, 0)}), ErrorCode::SUCCESS); } TEST_F(LeSetExtendedAdvertisingEnableTest, EnableUsingRandomAddress) { - ASSERT_EQ( - controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(LEGACY | CONNECTABLE | SCANNABLE), - 0x0800, 0x0800, 0x7, OwnAddressType::RANDOM_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, - AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, - SecondaryPhyType::LE_2M, 0x0, false), - ErrorCode::SUCCESS); - - ASSERT_EQ(controller_.LeSetAdvertisingSetRandomAddress(0, Address{1}), + ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( + 0, MakeAdvertisingEventProperties(LEGACY | CONNECTABLE | SCANNABLE), 0x0800, + 0x0800, 0x7, OwnAddressType::RANDOM_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable( - true, {MakeEnabledSet(0, 0x40, 0)}), + ASSERT_EQ(controller_.LeSetAdvertisingSetRandomAddress(0, Address{1}), ErrorCode::SUCCESS); + + ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable(true, {MakeEnabledSet(0, 0x40, 0)}), ErrorCode::SUCCESS); } TEST_F(LeSetExtendedAdvertisingEnableTest, EnableUsingResolvableAddress) { - ASSERT_EQ( - controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(LEGACY | CONNECTABLE | SCANNABLE), - 0x0800, 0x0800, 0x7, OwnAddressType::RESOLVABLE_OR_RANDOM_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, - AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, - SecondaryPhyType::LE_2M, 0x0, false), - ErrorCode::SUCCESS); + ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( + 0, MakeAdvertisingEventProperties(LEGACY | CONNECTABLE | SCANNABLE), 0x0800, + 0x0800, 0x7, OwnAddressType::RESOLVABLE_OR_RANDOM_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), + ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeAddDeviceToResolvingList( - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, - std::array{1}, std::array{1}), + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address{1}, + std::array{1}, std::array{1}), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeSetAddressResolutionEnable(true), ErrorCode::SUCCESS); // Note: the command will fail if the peer address is not in the resolvable // address list and the random address is not set. // Success here signifies that the RPA was successfully generated. - ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable( - true, {MakeEnabledSet(0, 0x40, 0)}), + ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable(true, {MakeEnabledSet(0, 0x40, 0)}), ErrorCode::SUCCESS); } TEST_F(LeSetExtendedAdvertisingEnableTest, DuplicateAdvertisingHandle) { - ASSERT_EQ( - controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(LEGACY | CONNECTABLE | SCANNABLE), - 0x0800, 0x0800, 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, - AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, - SecondaryPhyType::LE_2M, 0x0, false), - ErrorCode::SUCCESS); + ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( + 0, MakeAdvertisingEventProperties(LEGACY | CONNECTABLE | SCANNABLE), 0x0800, + 0x0800, 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), + ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable( - true, {MakeEnabledSet(0, 0, 0), MakeEnabledSet(0, 0, 0)}), + true, {MakeEnabledSet(0, 0, 0), MakeEnabledSet(0, 0, 0)}), ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); } TEST_F(LeSetExtendedAdvertisingEnableTest, UnknownAdvertisingHandle) { - ASSERT_EQ( - controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(LEGACY | CONNECTABLE | SCANNABLE), - 0x0800, 0x0800, 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, - AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, - SecondaryPhyType::LE_2M, 0x0, false), - ErrorCode::SUCCESS); + ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( + 0, MakeAdvertisingEventProperties(LEGACY | CONNECTABLE | SCANNABLE), 0x0800, + 0x0800, 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), + ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable( - true, {MakeEnabledSet(0, 0, 0), MakeEnabledSet(1, 0, 0)}), + true, {MakeEnabledSet(0, 0, 0), MakeEnabledSet(1, 0, 0)}), ErrorCode::UNKNOWN_ADVERTISING_IDENTIFIER); } @@ -163,150 +150,137 @@ TEST_F(LeSetExtendedAdvertisingEnableTest, MissingAdvertisingHandle) { } TEST_F(LeSetExtendedAdvertisingEnableTest, InvalidDuration) { - ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, - MakeAdvertisingEventProperties(LEGACY | DIRECTED | CONNECTABLE | - HIGH_DUTY_CYCLE), - 0x0800, 0x0800, 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), - ErrorCode::SUCCESS); - - ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable( - true, {MakeEnabledSet(0, 0, 0)}), + ASSERT_EQ( + controller_.LeSetExtendedAdvertisingParameters( + 0, + MakeAdvertisingEventProperties(LEGACY | DIRECTED | CONNECTABLE | HIGH_DUTY_CYCLE), + 0x0800, 0x0800, 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), + ErrorCode::SUCCESS); + + ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable(true, {MakeEnabledSet(0, 0, 0)}), ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); - ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable( - true, {MakeEnabledSet(0, 0x801, 0)}), + ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable(true, {MakeEnabledSet(0, 0x801, 0)}), ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); } TEST_F(LeSetExtendedAdvertisingEnableTest, PartialAdvertisingData) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, - 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); std::vector first_advertising_data_fragment = {1, 2, 3}; - ASSERT_EQ(controller_.LeSetExtendedAdvertisingData( - 0, Operation::FIRST_FRAGMENT, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, - first_advertising_data_fragment), + ASSERT_EQ(controller_.LeSetExtendedAdvertisingData(0, Operation::FIRST_FRAGMENT, + FragmentPreference::CONTROLLER_MAY_FRAGMENT, + first_advertising_data_fragment), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable( - true, {MakeEnabledSet(0, 0, 0)}), + ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable(true, {MakeEnabledSet(0, 0, 0)}), ErrorCode::COMMAND_DISALLOWED); } TEST_F(LeSetExtendedAdvertisingEnableTest, PartialScanResponseData) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(SCANNABLE), 0x0800, 0x0800, - 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(SCANNABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); std::vector first_scan_response_data_fragment = {1, 2, 3}; - ASSERT_EQ(controller_.LeSetExtendedScanResponseData( - 0, Operation::FIRST_FRAGMENT, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, - first_scan_response_data_fragment), + ASSERT_EQ(controller_.LeSetExtendedScanResponseData(0, Operation::FIRST_FRAGMENT, + FragmentPreference::CONTROLLER_MAY_FRAGMENT, + first_scan_response_data_fragment), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable( - true, {MakeEnabledSet(0, 0, 0)}), + ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable(true, {MakeEnabledSet(0, 0, 0)}), ErrorCode::COMMAND_DISALLOWED); } TEST_F(LeSetExtendedAdvertisingEnableTest, EmptyScanResponseData) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(SCANNABLE), 0x0800, 0x0800, - 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(SCANNABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable( - true, {MakeEnabledSet(0, 0, 0)}), + ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable(true, {MakeEnabledSet(0, 0, 0)}), ErrorCode::COMMAND_DISALLOWED); } -TEST_F(LeSetExtendedAdvertisingEnableTest, - AdvertisingDataLargerThanPduCapacity) { +TEST_F(LeSetExtendedAdvertisingEnableTest, AdvertisingDataLargerThanPduCapacity) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, - 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); std::vector advertising_data = {1, 2, 3}; advertising_data.resize(254); - ASSERT_EQ(controller_.LeSetExtendedAdvertisingData( - 0, Operation::COMPLETE_ADVERTISEMENT, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, advertising_data), + ASSERT_EQ(controller_.LeSetExtendedAdvertisingData(0, Operation::COMPLETE_ADVERTISEMENT, + FragmentPreference::CONTROLLER_MAY_FRAGMENT, + advertising_data), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable( - true, {MakeEnabledSet(0, 0, 0)}), + ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable(true, {MakeEnabledSet(0, 0, 0)}), ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); } -TEST_F(LeSetExtendedAdvertisingEnableTest, - AdvertisingDataLargerThanMaxPduCapacity) { +TEST_F(LeSetExtendedAdvertisingEnableTest, AdvertisingDataLargerThanMaxPduCapacity) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(0), 0x0800, 0x0800, 0x7, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(0), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); std::vector advertising_data = {1, 2, 3}; advertising_data.resize(1651); - ASSERT_EQ(controller_.LeSetExtendedAdvertisingData( - 0, Operation::COMPLETE_ADVERTISEMENT, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, advertising_data), + ASSERT_EQ(controller_.LeSetExtendedAdvertisingData(0, Operation::COMPLETE_ADVERTISEMENT, + FragmentPreference::CONTROLLER_MAY_FRAGMENT, + advertising_data), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable( - true, {MakeEnabledSet(0, 0, 0)}), + ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable(true, {MakeEnabledSet(0, 0, 0)}), ErrorCode::PACKET_TOO_LONG); } TEST_F(LeSetExtendedAdvertisingEnableTest, NoRandomAddress) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, - 0x7, OwnAddressType::RANDOM_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::RANDOM_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable( - true, {MakeEnabledSet(0, 0, 0)}), + ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable(true, {MakeEnabledSet(0, 0, 0)}), ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); } TEST_F(LeSetExtendedAdvertisingEnableTest, NoResolvableOrRandomAddress) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, - 0x7, OwnAddressType::RESOLVABLE_OR_RANDOM_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::RESOLVABLE_OR_RANDOM_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable( - true, {MakeEnabledSet(0, 0, 0)}), + ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable(true, {MakeEnabledSet(0, 0, 0)}), ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); } diff --git a/tools/rootcanal/test/controller/le/le_set_extended_advertising_parameters_test.cc b/tools/rootcanal/test/controller/le/le_set_extended_advertising_parameters_test.cc index f6a73b6c038..9b89b88319d 100644 --- a/tools/rootcanal/test/controller/le/le_set_extended_advertising_parameters_test.cc +++ b/tools/rootcanal/test/controller/le/le_set_extended_advertising_parameters_test.cc @@ -24,14 +24,14 @@ namespace rootcanal { using namespace bluetooth::hci; class LeSetExtendedAdvertisingParametersTest : public ::testing::Test { - public: +public: LeSetExtendedAdvertisingParametersTest() { // Reduce the number of advertising sets to simplify testing. properties_.le_num_supported_advertising_sets = 2; - }; + } ~LeSetExtendedAdvertisingParametersTest() override = default; - protected: +protected: Address address_{0}; ControllerProperties properties_{}; LinkLayerController controller_{address_, properties_}; @@ -39,258 +39,244 @@ class LeSetExtendedAdvertisingParametersTest : public ::testing::Test { TEST_F(LeSetExtendedAdvertisingParametersTest, Success) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, - 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); } TEST_F(LeSetExtendedAdvertisingParametersTest, LegacyUsed) { - ASSERT_EQ( - controller_.LeSetScanParameters(LeScanType::PASSIVE, 0x2000, 0x200, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - LeScanningFilterPolicy::ACCEPT_ALL), - ErrorCode::SUCCESS); + ASSERT_EQ(controller_.LeSetScanParameters(LeScanType::PASSIVE, 0x2000, 0x200, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + LeScanningFilterPolicy::ACCEPT_ALL), + ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, - 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::COMMAND_DISALLOWED); } TEST_F(LeSetExtendedAdvertisingParametersTest, AdvertisingSetsFull) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, - 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 1, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, - 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 1, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 2, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, - 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 2, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::MEMORY_CAPACITY_EXCEEDED); } -TEST_F(LeSetExtendedAdvertisingParametersTest, - InvalidLegacyAdvertisingEventProperties) { - ASSERT_EQ( - controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(LEGACY | DIRECTED | SCANNABLE), - 0x0800, 0x0800, 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, - AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, - SecondaryPhyType::LE_2M, 0x0, false), - ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); +TEST_F(LeSetExtendedAdvertisingParametersTest, InvalidLegacyAdvertisingEventProperties) { + ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( + 0, MakeAdvertisingEventProperties(LEGACY | DIRECTED | SCANNABLE), 0x0800, + 0x0800, 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), + ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); } TEST_F(LeSetExtendedAdvertisingParametersTest, UnexpectedAdvertisingData) { - ASSERT_EQ( - controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(LEGACY | CONNECTABLE | SCANNABLE), - 0x0800, 0x0800, 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, - AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, - SecondaryPhyType::LE_2M, 0x0, false), - ErrorCode::SUCCESS); + ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( + 0, MakeAdvertisingEventProperties(LEGACY | CONNECTABLE | SCANNABLE), 0x0800, + 0x0800, 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), + ErrorCode::SUCCESS); std::vector advertising_data = {1, 2, 3}; - ASSERT_EQ(controller_.LeSetExtendedAdvertisingData( - 0, Operation::COMPLETE_ADVERTISEMENT, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, advertising_data), + ASSERT_EQ(controller_.LeSetExtendedAdvertisingData(0, Operation::COMPLETE_ADVERTISEMENT, + FragmentPreference::CONTROLLER_MAY_FRAGMENT, + advertising_data), ErrorCode::SUCCESS); - ASSERT_EQ( - controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(LEGACY | DIRECTED | CONNECTABLE), - 0x0800, 0x0800, 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, - AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, - SecondaryPhyType::LE_2M, 0x0, false), - ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); + ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( + 0, MakeAdvertisingEventProperties(LEGACY | DIRECTED | CONNECTABLE), 0x0800, + 0x0800, 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), + ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); } TEST_F(LeSetExtendedAdvertisingParametersTest, UnexpectedScanResponseData) { - ASSERT_EQ( - controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(LEGACY | CONNECTABLE | SCANNABLE), - 0x0800, 0x0800, 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, - AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, - SecondaryPhyType::LE_2M, 0x0, false), - ErrorCode::SUCCESS); + ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( + 0, MakeAdvertisingEventProperties(LEGACY | CONNECTABLE | SCANNABLE), 0x0800, + 0x0800, 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), + ErrorCode::SUCCESS); std::vector scan_response_data = {1, 2, 3}; - ASSERT_EQ( - controller_.LeSetExtendedScanResponseData( - 0, Operation::COMPLETE_ADVERTISEMENT, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, scan_response_data), - ErrorCode::SUCCESS); + ASSERT_EQ(controller_.LeSetExtendedScanResponseData(0, Operation::COMPLETE_ADVERTISEMENT, + FragmentPreference::CONTROLLER_MAY_FRAGMENT, + scan_response_data), + ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(LEGACY | CONNECTABLE), 0x0800, - 0x0800, 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(LEGACY | CONNECTABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); } TEST_F(LeSetExtendedAdvertisingParametersTest, InvalidLegacyAdvertisingData) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, - 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); std::vector advertising_data = {1, 2, 3}; advertising_data.resize(32); - ASSERT_EQ(controller_.LeSetExtendedAdvertisingData( - 0, Operation::COMPLETE_ADVERTISEMENT, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, advertising_data), + ASSERT_EQ(controller_.LeSetExtendedAdvertisingData(0, Operation::COMPLETE_ADVERTISEMENT, + FragmentPreference::CONTROLLER_MAY_FRAGMENT, + advertising_data), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(LEGACY | CONNECTABLE), 0x0800, - 0x0800, 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(LEGACY | CONNECTABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); } TEST_F(LeSetExtendedAdvertisingParametersTest, InvalidLegacyScanResponseData) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(SCANNABLE), 0x0800, 0x0800, - 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(SCANNABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); std::vector scan_response_data = {1, 2, 3}; scan_response_data.resize(32); - ASSERT_EQ( - controller_.LeSetExtendedScanResponseData( - 0, Operation::COMPLETE_ADVERTISEMENT, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, scan_response_data), - ErrorCode::SUCCESS); + ASSERT_EQ(controller_.LeSetExtendedScanResponseData(0, Operation::COMPLETE_ADVERTISEMENT, + FragmentPreference::CONTROLLER_MAY_FRAGMENT, + scan_response_data), + ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(LEGACY | SCANNABLE), 0x0800, - 0x0800, 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(LEGACY | SCANNABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); } -TEST_F(LeSetExtendedAdvertisingParametersTest, - InvalidExtendedAdvertisingEventProperties) { +TEST_F(LeSetExtendedAdvertisingParametersTest, InvalidExtendedAdvertisingEventProperties) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(CONNECTABLE | SCANNABLE), - 0x0800, 0x0800, 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(CONNECTABLE | SCANNABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, - MakeAdvertisingEventProperties(CONNECTABLE | DIRECTED | - HIGH_DUTY_CYCLE), - 0x0800, 0x0800, 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(CONNECTABLE | DIRECTED | HIGH_DUTY_CYCLE), + 0x0800, 0x0800, 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); } -TEST_F(LeSetExtendedAdvertisingParametersTest, - InvalidPrimaryAdvertisingInterval) { +TEST_F(LeSetExtendedAdvertisingParametersTest, InvalidPrimaryAdvertisingInterval) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x10, 0x0800, - 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x10, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x10, - 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x10, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0400, - 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0400, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); } TEST_F(LeSetExtendedAdvertisingParametersTest, InvalidChannelMap) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, - 0x0, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, 0x0, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); } TEST_F(LeSetExtendedAdvertisingParametersTest, InvalidPrimaryPhy) { - ASSERT_EQ( - controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(LEGACY | CONNECTABLE), 0x0800, - 0x0800, 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, - AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_CODED, - 0, SecondaryPhyType::LE_2M, 0x0, false), - ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); + ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( + 0, MakeAdvertisingEventProperties(LEGACY | CONNECTABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_CODED, 0, + SecondaryPhyType::LE_2M, 0x0, false), + ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); } TEST_F(LeSetExtendedAdvertisingParametersTest, AdvertisingActive) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, - 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable( - true, {MakeEnabledSet(0, 0, 0)}), + ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable(true, {MakeEnabledSet(0, 0, 0)}), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(0), 0x0800, 0x0800, 0x7, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(0), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::COMMAND_DISALLOWED); } diff --git a/tools/rootcanal/test/controller/le/le_set_extended_scan_enable_test.cc b/tools/rootcanal/test/controller/le/le_set_extended_scan_enable_test.cc index 278b9d06aa2..298683a0dfa 100644 --- a/tools/rootcanal/test/controller/le/le_set_extended_scan_enable_test.cc +++ b/tools/rootcanal/test/controller/le/le_set_extended_scan_enable_test.cc @@ -23,18 +23,17 @@ namespace rootcanal { using namespace bluetooth::hci; class LeSetExtendedScanEnableTest : public ::testing::Test { - public: +public: LeSetExtendedScanEnableTest() = default; ~LeSetExtendedScanEnableTest() override = default; - protected: +protected: Address address_{0}; ControllerProperties properties_{}; LinkLayerController controller_{address_, properties_}; }; -static ScanningPhyParameters MakeScanningPhyParameters(LeScanType scan_type, - uint16_t scan_interval, +static ScanningPhyParameters MakeScanningPhyParameters(LeScanType scan_type, uint16_t scan_interval, uint16_t scan_window) { ScanningPhyParameters parameters; parameters.le_scan_type_ = scan_type; @@ -44,109 +43,86 @@ static ScanningPhyParameters MakeScanningPhyParameters(LeScanType scan_type, } TEST_F(LeSetExtendedScanEnableTest, EnableUsingPublicAddress) { - ASSERT_EQ( - controller_.LeSetExtendedScanParameters( - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - LeScanningFilterPolicy::ACCEPT_ALL, 0x1, - {MakeScanningPhyParameters(LeScanType::PASSIVE, 0x2000, 0x200)}), - ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetExtendedScanEnable( - true, FilterDuplicates::DISABLED, 0, 0), + ASSERT_EQ(controller_.LeSetExtendedScanParameters( + OwnAddressType::PUBLIC_DEVICE_ADDRESS, LeScanningFilterPolicy::ACCEPT_ALL, 0x1, + {MakeScanningPhyParameters(LeScanType::PASSIVE, 0x2000, 0x200)}), + ErrorCode::SUCCESS); + ASSERT_EQ(controller_.LeSetExtendedScanEnable(true, FilterDuplicates::DISABLED, 0, 0), ErrorCode::SUCCESS); } TEST_F(LeSetExtendedScanEnableTest, EnableUsingRandomAddress) { - ASSERT_EQ( - controller_.LeSetExtendedScanParameters( - OwnAddressType::RANDOM_DEVICE_ADDRESS, - LeScanningFilterPolicy::ACCEPT_ALL, 0x1, - {MakeScanningPhyParameters(LeScanType::PASSIVE, 0x2000, 0x200)}), - ErrorCode::SUCCESS); + ASSERT_EQ(controller_.LeSetExtendedScanParameters( + OwnAddressType::RANDOM_DEVICE_ADDRESS, LeScanningFilterPolicy::ACCEPT_ALL, 0x1, + {MakeScanningPhyParameters(LeScanType::PASSIVE, 0x2000, 0x200)}), + ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeSetRandomAddress(Address{1}), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetExtendedScanEnable( - true, FilterDuplicates::DISABLED, 0, 0), + ASSERT_EQ(controller_.LeSetExtendedScanEnable(true, FilterDuplicates::DISABLED, 0, 0), ErrorCode::SUCCESS); } TEST_F(LeSetExtendedScanEnableTest, EnableUsingResolvableAddress) { ASSERT_EQ( - controller_.LeSetExtendedScanParameters( - OwnAddressType::RESOLVABLE_OR_RANDOM_ADDRESS, - LeScanningFilterPolicy::ACCEPT_ALL, 0x1, - {MakeScanningPhyParameters(LeScanType::PASSIVE, 0x2000, 0x200)}), - ErrorCode::SUCCESS); + controller_.LeSetExtendedScanParameters( + OwnAddressType::RESOLVABLE_OR_RANDOM_ADDRESS, LeScanningFilterPolicy::ACCEPT_ALL, + 0x1, {MakeScanningPhyParameters(LeScanType::PASSIVE, 0x2000, 0x200)}), + ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeSetRandomAddress(Address{1}), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetExtendedScanEnable( - true, FilterDuplicates::DISABLED, 0, 0), + ASSERT_EQ(controller_.LeSetExtendedScanEnable(true, FilterDuplicates::DISABLED, 0, 0), ErrorCode::SUCCESS); } TEST_F(LeSetExtendedScanEnableTest, ResetEachPeriod) { - ASSERT_EQ( - controller_.LeSetExtendedScanParameters( - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - LeScanningFilterPolicy::ACCEPT_ALL, 0x1, - {MakeScanningPhyParameters(LeScanType::PASSIVE, 0x2000, 0x200)}), - ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetExtendedScanEnable( - true, FilterDuplicates::RESET_EACH_PERIOD, 100, 1000), + ASSERT_EQ(controller_.LeSetExtendedScanParameters( + OwnAddressType::PUBLIC_DEVICE_ADDRESS, LeScanningFilterPolicy::ACCEPT_ALL, 0x1, + {MakeScanningPhyParameters(LeScanType::PASSIVE, 0x2000, 0x200)}), ErrorCode::SUCCESS); + ASSERT_EQ( + controller_.LeSetExtendedScanEnable(true, FilterDuplicates::RESET_EACH_PERIOD, 100, 1000), + ErrorCode::SUCCESS); } TEST_F(LeSetExtendedScanEnableTest, Disable) { - ASSERT_EQ(controller_.LeSetExtendedScanEnable( - false, FilterDuplicates::DISABLED, 0, 0), + ASSERT_EQ(controller_.LeSetExtendedScanEnable(false, FilterDuplicates::DISABLED, 0, 0), ErrorCode::SUCCESS); } TEST_F(LeSetExtendedScanEnableTest, ValidDuration) { - ASSERT_EQ( - controller_.LeSetExtendedScanParameters( - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - LeScanningFilterPolicy::ACCEPT_ALL, 0x1, - {MakeScanningPhyParameters(LeScanType::PASSIVE, 0x2000, 0x200)}), - ErrorCode::SUCCESS); - - ASSERT_EQ(controller_.LeSetExtendedScanEnable( - true, FilterDuplicates::DISABLED, 127, 1), + ASSERT_EQ(controller_.LeSetExtendedScanParameters( + OwnAddressType::PUBLIC_DEVICE_ADDRESS, LeScanningFilterPolicy::ACCEPT_ALL, 0x1, + {MakeScanningPhyParameters(LeScanType::PASSIVE, 0x2000, 0x200)}), + ErrorCode::SUCCESS); + + ASSERT_EQ(controller_.LeSetExtendedScanEnable(true, FilterDuplicates::DISABLED, 127, 1), ErrorCode::SUCCESS); } TEST_F(LeSetExtendedScanEnableTest, InvalidDuration) { - ASSERT_EQ( - controller_.LeSetExtendedScanParameters( - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - LeScanningFilterPolicy::ACCEPT_ALL, 0x1, - {MakeScanningPhyParameters(LeScanType::PASSIVE, 0x2000, 0x200)}), - ErrorCode::SUCCESS); - - ASSERT_EQ(controller_.LeSetExtendedScanEnable( - true, FilterDuplicates::RESET_EACH_PERIOD, 0, 0), + ASSERT_EQ(controller_.LeSetExtendedScanParameters( + OwnAddressType::PUBLIC_DEVICE_ADDRESS, LeScanningFilterPolicy::ACCEPT_ALL, 0x1, + {MakeScanningPhyParameters(LeScanType::PASSIVE, 0x2000, 0x200)}), + ErrorCode::SUCCESS); + + ASSERT_EQ(controller_.LeSetExtendedScanEnable(true, FilterDuplicates::RESET_EACH_PERIOD, 0, 0), ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); - ASSERT_EQ(controller_.LeSetExtendedScanEnable( - true, FilterDuplicates::DISABLED, 128, 1), + ASSERT_EQ(controller_.LeSetExtendedScanEnable(true, FilterDuplicates::DISABLED, 128, 1), ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); } TEST_F(LeSetExtendedScanEnableTest, NoRandomAddress) { - ASSERT_EQ( - controller_.LeSetExtendedScanParameters( - OwnAddressType::RANDOM_DEVICE_ADDRESS, - LeScanningFilterPolicy::ACCEPT_ALL, 0x1, - {MakeScanningPhyParameters(LeScanType::PASSIVE, 0x2000, 0x200)}), - ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetExtendedScanEnable( - true, FilterDuplicates::DISABLED, 0, 0), + ASSERT_EQ(controller_.LeSetExtendedScanParameters( + OwnAddressType::RANDOM_DEVICE_ADDRESS, LeScanningFilterPolicy::ACCEPT_ALL, 0x1, + {MakeScanningPhyParameters(LeScanType::PASSIVE, 0x2000, 0x200)}), + ErrorCode::SUCCESS); + ASSERT_EQ(controller_.LeSetExtendedScanEnable(true, FilterDuplicates::DISABLED, 0, 0), ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); ASSERT_EQ( - controller_.LeSetExtendedScanParameters( - OwnAddressType::RESOLVABLE_OR_RANDOM_ADDRESS, - LeScanningFilterPolicy::ACCEPT_ALL, 0x1, - {MakeScanningPhyParameters(LeScanType::PASSIVE, 0x2000, 0x200)}), - ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetExtendedScanEnable( - true, FilterDuplicates::DISABLED, 0, 0), + controller_.LeSetExtendedScanParameters( + OwnAddressType::RESOLVABLE_OR_RANDOM_ADDRESS, LeScanningFilterPolicy::ACCEPT_ALL, + 0x1, {MakeScanningPhyParameters(LeScanType::PASSIVE, 0x2000, 0x200)}), + ErrorCode::SUCCESS); + ASSERT_EQ(controller_.LeSetExtendedScanEnable(true, FilterDuplicates::DISABLED, 0, 0), ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); } diff --git a/tools/rootcanal/test/controller/le/le_set_extended_scan_parameters_test.cc b/tools/rootcanal/test/controller/le/le_set_extended_scan_parameters_test.cc index 3e1ab5390a7..ecc61e94d56 100644 --- a/tools/rootcanal/test/controller/le/le_set_extended_scan_parameters_test.cc +++ b/tools/rootcanal/test/controller/le/le_set_extended_scan_parameters_test.cc @@ -23,18 +23,17 @@ namespace rootcanal { using namespace bluetooth::hci; class LeSetExtendedScanParametersTest : public ::testing::Test { - public: +public: LeSetExtendedScanParametersTest() = default; ~LeSetExtendedScanParametersTest() override = default; - protected: +protected: Address address_{0}; ControllerProperties properties_{}; LinkLayerController controller_{address_, properties_}; }; -static ScanningPhyParameters MakeScanningPhyParameters(LeScanType scan_type, - uint16_t scan_interval, +static ScanningPhyParameters MakeScanningPhyParameters(LeScanType scan_type, uint16_t scan_interval, uint16_t scan_window) { ScanningPhyParameters parameters; parameters.le_scan_type_ = scan_type; @@ -45,77 +44,64 @@ static ScanningPhyParameters MakeScanningPhyParameters(LeScanType scan_type, TEST_F(LeSetExtendedScanParametersTest, Success) { ASSERT_EQ(controller_.LeSetExtendedScanParameters( - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - LeScanningFilterPolicy::ACCEPT_ALL, 0x5, - {MakeScanningPhyParameters(LeScanType::PASSIVE, 0x2000, 0x200), - MakeScanningPhyParameters(LeScanType::ACTIVE, 0x2000, 0x200)}), + OwnAddressType::PUBLIC_DEVICE_ADDRESS, LeScanningFilterPolicy::ACCEPT_ALL, 0x5, + {MakeScanningPhyParameters(LeScanType::PASSIVE, 0x2000, 0x200), + MakeScanningPhyParameters(LeScanType::ACTIVE, 0x2000, 0x200)}), ErrorCode::SUCCESS); } TEST_F(LeSetExtendedScanParametersTest, ScanningActive) { ASSERT_EQ(controller_.LeSetExtendedScanParameters( - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - LeScanningFilterPolicy::ACCEPT_ALL, 0x5, - {MakeScanningPhyParameters(LeScanType::PASSIVE, 0x2000, 0x200), - MakeScanningPhyParameters(LeScanType::ACTIVE, 0x2000, 0x200)}), + OwnAddressType::PUBLIC_DEVICE_ADDRESS, LeScanningFilterPolicy::ACCEPT_ALL, 0x5, + {MakeScanningPhyParameters(LeScanType::PASSIVE, 0x2000, 0x200), + MakeScanningPhyParameters(LeScanType::ACTIVE, 0x2000, 0x200)}), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetExtendedScanEnable( - true, FilterDuplicates::DISABLED, 0, 0), + ASSERT_EQ(controller_.LeSetExtendedScanEnable(true, FilterDuplicates::DISABLED, 0, 0), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeSetExtendedScanParameters( - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - LeScanningFilterPolicy::ACCEPT_ALL, 0x5, - {MakeScanningPhyParameters(LeScanType::PASSIVE, 0x2000, 0x200), - MakeScanningPhyParameters(LeScanType::ACTIVE, 0x2000, 0x200)}), + OwnAddressType::PUBLIC_DEVICE_ADDRESS, LeScanningFilterPolicy::ACCEPT_ALL, 0x5, + {MakeScanningPhyParameters(LeScanType::PASSIVE, 0x2000, 0x200), + MakeScanningPhyParameters(LeScanType::ACTIVE, 0x2000, 0x200)}), ErrorCode::COMMAND_DISALLOWED); } TEST_F(LeSetExtendedScanParametersTest, ReservedPhy) { - ASSERT_EQ( - controller_.LeSetExtendedScanParameters( - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - LeScanningFilterPolicy::ACCEPT_ALL, 0x80, - {MakeScanningPhyParameters(LeScanType::PASSIVE, 0x2000, 0x200)}), - ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); + ASSERT_EQ(controller_.LeSetExtendedScanParameters( + OwnAddressType::PUBLIC_DEVICE_ADDRESS, LeScanningFilterPolicy::ACCEPT_ALL, 0x80, + {MakeScanningPhyParameters(LeScanType::PASSIVE, 0x2000, 0x200)}), + ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); } TEST_F(LeSetExtendedScanParametersTest, InvalidPhyParameters) { - ASSERT_EQ(controller_.LeSetExtendedScanParameters( - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - LeScanningFilterPolicy::ACCEPT_ALL, 0x1, {}), + ASSERT_EQ(controller_.LeSetExtendedScanParameters(OwnAddressType::PUBLIC_DEVICE_ADDRESS, + LeScanningFilterPolicy::ACCEPT_ALL, 0x1, {}), ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); - ASSERT_EQ( - controller_.LeSetExtendedScanParameters( - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - LeScanningFilterPolicy::ACCEPT_ALL, 0x1, - {MakeScanningPhyParameters(LeScanType::PASSIVE, 0x2000, 0x200), - MakeScanningPhyParameters(LeScanType::PASSIVE, 0x2000, 0x200)}), - ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); + ASSERT_EQ(controller_.LeSetExtendedScanParameters( + OwnAddressType::PUBLIC_DEVICE_ADDRESS, LeScanningFilterPolicy::ACCEPT_ALL, 0x1, + {MakeScanningPhyParameters(LeScanType::PASSIVE, 0x2000, 0x200), + MakeScanningPhyParameters(LeScanType::PASSIVE, 0x2000, 0x200)}), + ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); } TEST_F(LeSetExtendedScanParametersTest, InvalidScanInterval) { ASSERT_EQ(controller_.LeSetExtendedScanParameters( - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - LeScanningFilterPolicy::ACCEPT_ALL, 0x1, - {MakeScanningPhyParameters(LeScanType::PASSIVE, 0x0, 0x200)}), + OwnAddressType::PUBLIC_DEVICE_ADDRESS, LeScanningFilterPolicy::ACCEPT_ALL, 0x1, + {MakeScanningPhyParameters(LeScanType::PASSIVE, 0x0, 0x200)}), ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); } TEST_F(LeSetExtendedScanParametersTest, InvalidScanWindow) { ASSERT_EQ(controller_.LeSetExtendedScanParameters( - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - LeScanningFilterPolicy::ACCEPT_ALL, 0x1, - {MakeScanningPhyParameters(LeScanType::PASSIVE, 0x2000, 0x0)}), + OwnAddressType::PUBLIC_DEVICE_ADDRESS, LeScanningFilterPolicy::ACCEPT_ALL, 0x1, + {MakeScanningPhyParameters(LeScanType::PASSIVE, 0x2000, 0x0)}), ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); - ASSERT_EQ( - controller_.LeSetExtendedScanParameters( - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - LeScanningFilterPolicy::ACCEPT_ALL, 0x1, - {MakeScanningPhyParameters(LeScanType::PASSIVE, 0x2000, 0x2001)}), - ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); + ASSERT_EQ(controller_.LeSetExtendedScanParameters( + OwnAddressType::PUBLIC_DEVICE_ADDRESS, LeScanningFilterPolicy::ACCEPT_ALL, 0x1, + {MakeScanningPhyParameters(LeScanType::PASSIVE, 0x2000, 0x2001)}), + ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); } } // namespace rootcanal diff --git a/tools/rootcanal/test/controller/le/le_set_extended_scan_response_data_test.cc b/tools/rootcanal/test/controller/le/le_set_extended_scan_response_data_test.cc index fde4680ec72..c53c9f5a85a 100644 --- a/tools/rootcanal/test/controller/le/le_set_extended_scan_response_data_test.cc +++ b/tools/rootcanal/test/controller/le/le_set_extended_scan_response_data_test.cc @@ -24,15 +24,15 @@ namespace rootcanal { using namespace bluetooth::hci; class LeSetExtendedScanResponseDataTest : public ::testing::Test { - public: +public: LeSetExtendedScanResponseDataTest() { // Reduce the number of advertising sets to simplify testing. properties_.le_num_supported_advertising_sets = 2; properties_.le_max_advertising_data_length = 300; - }; + } ~LeSetExtendedScanResponseDataTest() override = default; - protected: +protected: Address address_{0}; ControllerProperties properties_{}; LinkLayerController controller_{address_, properties_}; @@ -40,170 +40,159 @@ class LeSetExtendedScanResponseDataTest : public ::testing::Test { TEST_F(LeSetExtendedScanResponseDataTest, Complete) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(SCANNABLE), 0x0800, 0x0800, - 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(SCANNABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); std::vector scan_response_data = {1, 2, 3}; - ASSERT_EQ( - controller_.LeSetExtendedScanResponseData( - 0, Operation::COMPLETE_ADVERTISEMENT, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, scan_response_data), - ErrorCode::SUCCESS); + ASSERT_EQ(controller_.LeSetExtendedScanResponseData(0, Operation::COMPLETE_ADVERTISEMENT, + FragmentPreference::CONTROLLER_MAY_FRAGMENT, + scan_response_data), + ErrorCode::SUCCESS); } TEST_F(LeSetExtendedScanResponseDataTest, Discard) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, - 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetExtendedScanResponseData( - 0, Operation::COMPLETE_ADVERTISEMENT, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, {}), + ASSERT_EQ(controller_.LeSetExtendedScanResponseData(0, Operation::COMPLETE_ADVERTISEMENT, + FragmentPreference::CONTROLLER_MAY_FRAGMENT, + {}), ErrorCode::SUCCESS); } TEST_F(LeSetExtendedScanResponseDataTest, Unchanged) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(SCANNABLE), 0x0800, 0x0800, - 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(SCANNABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); std::vector scan_response_data = {1, 2, 3}; - ASSERT_EQ( - controller_.LeSetExtendedScanResponseData( - 0, Operation::COMPLETE_ADVERTISEMENT, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, scan_response_data), - ErrorCode::SUCCESS); - - ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable( - true, {MakeEnabledSet(0, 0, 0)}), + ASSERT_EQ(controller_.LeSetExtendedScanResponseData(0, Operation::COMPLETE_ADVERTISEMENT, + FragmentPreference::CONTROLLER_MAY_FRAGMENT, + scan_response_data), + ErrorCode::SUCCESS); + + ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable(true, {MakeEnabledSet(0, 0, 0)}), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeSetExtendedScanResponseData( - 0, Operation::UNCHANGED_DATA, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, {}), + 0, Operation::UNCHANGED_DATA, FragmentPreference::CONTROLLER_MAY_FRAGMENT, {}), ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); } TEST_F(LeSetExtendedScanResponseDataTest, Fragmented) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(SCANNABLE), 0x0800, 0x0800, - 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(SCANNABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); std::vector first_scan_response_data_fragment = {1, 2, 3}; std::vector intermediate_scan_response_data_fragment = {4, 5, 6}; std::vector last_scan_response_data_fragment = {7, 8, 9}; - ASSERT_EQ(controller_.LeSetExtendedScanResponseData( - 0, Operation::FIRST_FRAGMENT, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, - first_scan_response_data_fragment), + ASSERT_EQ(controller_.LeSetExtendedScanResponseData(0, Operation::FIRST_FRAGMENT, + FragmentPreference::CONTROLLER_MAY_FRAGMENT, + first_scan_response_data_fragment), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetExtendedScanResponseData( - 0, Operation::INTERMEDIATE_FRAGMENT, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, - intermediate_scan_response_data_fragment), + ASSERT_EQ(controller_.LeSetExtendedScanResponseData(0, Operation::INTERMEDIATE_FRAGMENT, + FragmentPreference::CONTROLLER_MAY_FRAGMENT, + intermediate_scan_response_data_fragment), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetExtendedScanResponseData( - 0, Operation::LAST_FRAGMENT, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, - last_scan_response_data_fragment), + ASSERT_EQ(controller_.LeSetExtendedScanResponseData(0, Operation::LAST_FRAGMENT, + FragmentPreference::CONTROLLER_MAY_FRAGMENT, + last_scan_response_data_fragment), ErrorCode::SUCCESS); } TEST_F(LeSetExtendedScanResponseDataTest, UnknownAdvertisingHandle) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(SCANNABLE), 0x0800, 0x0800, - 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(SCANNABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); std::vector scan_response_data = {1, 2, 3}; - ASSERT_EQ( - controller_.LeSetExtendedScanResponseData( - 1, Operation::COMPLETE_ADVERTISEMENT, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, scan_response_data), - ErrorCode::UNKNOWN_ADVERTISING_IDENTIFIER); + ASSERT_EQ(controller_.LeSetExtendedScanResponseData(1, Operation::COMPLETE_ADVERTISEMENT, + FragmentPreference::CONTROLLER_MAY_FRAGMENT, + scan_response_data), + ErrorCode::UNKNOWN_ADVERTISING_IDENTIFIER); } TEST_F(LeSetExtendedScanResponseDataTest, UnexpectedScanResponseData) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, - 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); std::vector scan_response_data = {1, 2, 3}; - ASSERT_EQ( - controller_.LeSetExtendedScanResponseData( - 0, Operation::COMPLETE_ADVERTISEMENT, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, scan_response_data), - ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); + ASSERT_EQ(controller_.LeSetExtendedScanResponseData(0, Operation::COMPLETE_ADVERTISEMENT, + FragmentPreference::CONTROLLER_MAY_FRAGMENT, + scan_response_data), + ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); } TEST_F(LeSetExtendedScanResponseDataTest, IncompleteLegacyScanResponseData) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(LEGACY | SCANNABLE), 0x0800, - 0x0800, 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(LEGACY | SCANNABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); std::vector first_scan_response_data_fragment = {1, 2, 3}; - ASSERT_EQ(controller_.LeSetExtendedScanResponseData( - 0, Operation::FIRST_FRAGMENT, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, - first_scan_response_data_fragment), + ASSERT_EQ(controller_.LeSetExtendedScanResponseData(0, Operation::FIRST_FRAGMENT, + FragmentPreference::CONTROLLER_MAY_FRAGMENT, + first_scan_response_data_fragment), ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); } TEST_F(LeSetExtendedScanResponseDataTest, InvalidLegacyScanResponseData) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(LEGACY | SCANNABLE), 0x0800, - 0x0800, 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(LEGACY | SCANNABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); std::vector scan_response_data = {1, 2, 3}; scan_response_data.resize(32); - ASSERT_EQ( - controller_.LeSetExtendedScanResponseData( - 0, Operation::COMPLETE_ADVERTISEMENT, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, scan_response_data), - ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); + ASSERT_EQ(controller_.LeSetExtendedScanResponseData(0, Operation::COMPLETE_ADVERTISEMENT, + FragmentPreference::CONTROLLER_MAY_FRAGMENT, + scan_response_data), + ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); } TEST_F(LeSetExtendedScanResponseDataTest, EmptyScanResponseDataFragment) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(SCANNABLE), 0x0800, 0x0800, - 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(SCANNABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); std::vector first_scan_response_data_fragment = {1, 2, 3}; @@ -211,152 +200,134 @@ TEST_F(LeSetExtendedScanResponseDataTest, EmptyScanResponseDataFragment) { std::vector last_scan_response_data_fragment = {7, 8, 9}; ASSERT_EQ(controller_.LeSetExtendedScanResponseData( - 0, Operation::FIRST_FRAGMENT, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, {}), + 0, Operation::FIRST_FRAGMENT, FragmentPreference::CONTROLLER_MAY_FRAGMENT, {}), ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); - ASSERT_EQ(controller_.LeSetExtendedScanResponseData( - 0, Operation::FIRST_FRAGMENT, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, - first_scan_response_data_fragment), + ASSERT_EQ(controller_.LeSetExtendedScanResponseData(0, Operation::FIRST_FRAGMENT, + FragmentPreference::CONTROLLER_MAY_FRAGMENT, + first_scan_response_data_fragment), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetExtendedScanResponseData( - 0, Operation::INTERMEDIATE_FRAGMENT, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, {}), + ASSERT_EQ(controller_.LeSetExtendedScanResponseData(0, Operation::INTERMEDIATE_FRAGMENT, + FragmentPreference::CONTROLLER_MAY_FRAGMENT, + {}), ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); - ASSERT_EQ(controller_.LeSetExtendedScanResponseData( - 0, Operation::INTERMEDIATE_FRAGMENT, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, - intermediate_scan_response_data_fragment), + ASSERT_EQ(controller_.LeSetExtendedScanResponseData(0, Operation::INTERMEDIATE_FRAGMENT, + FragmentPreference::CONTROLLER_MAY_FRAGMENT, + intermediate_scan_response_data_fragment), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeSetExtendedScanResponseData( - 0, Operation::LAST_FRAGMENT, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, {}), + 0, Operation::LAST_FRAGMENT, FragmentPreference::CONTROLLER_MAY_FRAGMENT, {}), ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); - ASSERT_EQ(controller_.LeSetExtendedScanResponseData( - 0, Operation::LAST_FRAGMENT, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, - last_scan_response_data_fragment), + ASSERT_EQ(controller_.LeSetExtendedScanResponseData(0, Operation::LAST_FRAGMENT, + FragmentPreference::CONTROLLER_MAY_FRAGMENT, + last_scan_response_data_fragment), ErrorCode::SUCCESS); } TEST_F(LeSetExtendedScanResponseDataTest, AdvertisingEnabled) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(SCANNABLE), 0x0800, 0x0800, - 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(SCANNABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); std::vector scan_response_data = {1, 2, 3}; - ASSERT_EQ( - controller_.LeSetExtendedScanResponseData( - 0, Operation::COMPLETE_ADVERTISEMENT, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, scan_response_data), - ErrorCode::SUCCESS); - - ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable( - true, {MakeEnabledSet(0, 0, 0)}), + ASSERT_EQ(controller_.LeSetExtendedScanResponseData(0, Operation::COMPLETE_ADVERTISEMENT, + FragmentPreference::CONTROLLER_MAY_FRAGMENT, + scan_response_data), + ErrorCode::SUCCESS); + + ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable(true, {MakeEnabledSet(0, 0, 0)}), ErrorCode::SUCCESS); - ASSERT_EQ( - controller_.LeSetExtendedScanResponseData( - 0, Operation::FIRST_FRAGMENT, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, scan_response_data), - ErrorCode::COMMAND_DISALLOWED); + ASSERT_EQ(controller_.LeSetExtendedScanResponseData(0, Operation::FIRST_FRAGMENT, + FragmentPreference::CONTROLLER_MAY_FRAGMENT, + scan_response_data), + ErrorCode::COMMAND_DISALLOWED); } TEST_F(LeSetExtendedScanResponseDataTest, EmptyExtendedScanResponseData) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(SCANNABLE), 0x0800, 0x0800, - 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(SCANNABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); std::vector scan_response_data = {1, 2, 3}; - ASSERT_EQ( - controller_.LeSetExtendedScanResponseData( - 0, Operation::COMPLETE_ADVERTISEMENT, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, scan_response_data), - ErrorCode::SUCCESS); - - ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable( - true, {MakeEnabledSet(0, 0, 0)}), + ASSERT_EQ(controller_.LeSetExtendedScanResponseData(0, Operation::COMPLETE_ADVERTISEMENT, + FragmentPreference::CONTROLLER_MAY_FRAGMENT, + scan_response_data), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetExtendedScanResponseData( - 0, Operation::COMPLETE_ADVERTISEMENT, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, {}), + ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable(true, {MakeEnabledSet(0, 0, 0)}), + ErrorCode::SUCCESS); + + ASSERT_EQ(controller_.LeSetExtendedScanResponseData(0, Operation::COMPLETE_ADVERTISEMENT, + FragmentPreference::CONTROLLER_MAY_FRAGMENT, + {}), ErrorCode::COMMAND_DISALLOWED); } -TEST_F(LeSetExtendedScanResponseDataTest, - ScanResponseDataLargerThanMemoryCapacity) { +TEST_F(LeSetExtendedScanResponseDataTest, ScanResponseDataLargerThanMemoryCapacity) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(SCANNABLE), 0x0800, 0x0800, - 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(SCANNABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); std::vector scan_response_data_fragment = {1, 2, 3}; - scan_response_data_fragment.resize( - properties_.le_max_advertising_data_length); + scan_response_data_fragment.resize(properties_.le_max_advertising_data_length); - ASSERT_EQ(controller_.LeSetExtendedScanResponseData( - 0, Operation::FIRST_FRAGMENT, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, - scan_response_data_fragment), + ASSERT_EQ(controller_.LeSetExtendedScanResponseData(0, Operation::FIRST_FRAGMENT, + FragmentPreference::CONTROLLER_MAY_FRAGMENT, + scan_response_data_fragment), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetExtendedScanResponseData( - 0, Operation::LAST_FRAGMENT, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, - scan_response_data_fragment), + ASSERT_EQ(controller_.LeSetExtendedScanResponseData(0, Operation::LAST_FRAGMENT, + FragmentPreference::CONTROLLER_MAY_FRAGMENT, + scan_response_data_fragment), ErrorCode::MEMORY_CAPACITY_EXCEEDED); } -TEST_F(LeSetExtendedScanResponseDataTest, - ScanResponseDataLargerThanPduCapacity) { +TEST_F(LeSetExtendedScanResponseDataTest, ScanResponseDataLargerThanPduCapacity) { // Overwrite le_max_advertising_data_length to make sure that the correct // check is triggered. properties_.le_max_advertising_data_length = 5000; ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(SCANNABLE), 0x0800, 0x0800, - 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(SCANNABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); std::vector scan_response_data = {1, 2, 3}; - ASSERT_EQ( - controller_.LeSetExtendedScanResponseData( - 0, Operation::COMPLETE_ADVERTISEMENT, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, scan_response_data), - ErrorCode::SUCCESS); - - ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable( - true, {MakeEnabledSet(0, 0, 0)}), + ASSERT_EQ(controller_.LeSetExtendedScanResponseData(0, Operation::COMPLETE_ADVERTISEMENT, + FragmentPreference::CONTROLLER_MAY_FRAGMENT, + scan_response_data), + ErrorCode::SUCCESS); + + ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable(true, {MakeEnabledSet(0, 0, 0)}), ErrorCode::SUCCESS); // No AUX chain possible for connectable advertising PDUs, // the advertising data is limited to one PDU's payload. scan_response_data.resize(1651); - ASSERT_EQ( - controller_.LeSetExtendedScanResponseData( - 0, Operation::COMPLETE_ADVERTISEMENT, - FragmentPreference::CONTROLLER_MAY_FRAGMENT, scan_response_data), - ErrorCode::PACKET_TOO_LONG); + ASSERT_EQ(controller_.LeSetExtendedScanResponseData(0, Operation::COMPLETE_ADVERTISEMENT, + FragmentPreference::CONTROLLER_MAY_FRAGMENT, + scan_response_data), + ErrorCode::PACKET_TOO_LONG); } } // namespace rootcanal diff --git a/tools/rootcanal/test/controller/le/le_set_periodic_advertising_data_test.cc b/tools/rootcanal/test/controller/le/le_set_periodic_advertising_data_test.cc index 26a03d0eca0..90bbc1ae682 100644 --- a/tools/rootcanal/test/controller/le/le_set_periodic_advertising_data_test.cc +++ b/tools/rootcanal/test/controller/le/le_set_periodic_advertising_data_test.cc @@ -24,14 +24,14 @@ namespace rootcanal { using namespace bluetooth::hci; class LeSetPeriodicAdvertisingDataTest : public ::testing::Test { - public: +public: LeSetPeriodicAdvertisingDataTest() { // Reduce the maximum advertising data length to simplify testing. properties_.le_max_advertising_data_length = 300; - }; + } ~LeSetPeriodicAdvertisingDataTest() override = default; - protected: +protected: Address address_{0}; ControllerProperties properties_{}; LinkLayerController controller_{address_, properties_}; @@ -39,233 +39,213 @@ class LeSetPeriodicAdvertisingDataTest : public ::testing::Test { TEST_F(LeSetPeriodicAdvertisingDataTest, Complete) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(), 0x0800, 0x0800, 0x7, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); - ASSERT_EQ( - controller_.LeSetPeriodicAdvertisingParameters(0, 0x6, 0xffff, false), - ErrorCode::SUCCESS); + ASSERT_EQ(controller_.LeSetPeriodicAdvertisingParameters(0, 0x6, 0xffff, false), + ErrorCode::SUCCESS); std::vector advertising_data = {1, 2, 3}; - ASSERT_EQ(controller_.LeSetPeriodicAdvertisingData( - 0, Operation::COMPLETE_ADVERTISEMENT, advertising_data), + ASSERT_EQ(controller_.LeSetPeriodicAdvertisingData(0, Operation::COMPLETE_ADVERTISEMENT, + advertising_data), ErrorCode::SUCCESS); } TEST_F(LeSetPeriodicAdvertisingDataTest, Unchanged) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(), 0x0800, 0x0800, 0x7, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); - ASSERT_EQ( - controller_.LeSetPeriodicAdvertisingParameters(0, 0x6, 0xffff, false), - ErrorCode::SUCCESS); + ASSERT_EQ(controller_.LeSetPeriodicAdvertisingParameters(0, 0x6, 0xffff, false), + ErrorCode::SUCCESS); std::vector advertising_data = {1, 2, 3}; - ASSERT_EQ(controller_.LeSetPeriodicAdvertisingData( - 0, Operation::COMPLETE_ADVERTISEMENT, advertising_data), + ASSERT_EQ(controller_.LeSetPeriodicAdvertisingData(0, Operation::COMPLETE_ADVERTISEMENT, + advertising_data), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetPeriodicAdvertisingEnable(true, false, 0), - ErrorCode::SUCCESS); + ASSERT_EQ(controller_.LeSetPeriodicAdvertisingEnable(true, false, 0), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetPeriodicAdvertisingData( - 0, Operation::UNCHANGED_DATA, {}), + ASSERT_EQ(controller_.LeSetPeriodicAdvertisingData(0, Operation::UNCHANGED_DATA, {}), ErrorCode::SUCCESS); } TEST_F(LeSetPeriodicAdvertisingDataTest, Fragmented) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(), 0x0800, 0x0800, 0x7, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); - ASSERT_EQ( - controller_.LeSetPeriodicAdvertisingParameters(0, 0x6, 0xffff, false), - ErrorCode::SUCCESS); + ASSERT_EQ(controller_.LeSetPeriodicAdvertisingParameters(0, 0x6, 0xffff, false), + ErrorCode::SUCCESS); std::vector first_advertising_data_fragment = {1, 2, 3}; std::vector intermediate_advertising_data_fragment = {4, 5, 6}; std::vector last_advertising_data_fragment = {7, 8, 9}; - ASSERT_EQ(controller_.LeSetPeriodicAdvertisingData( - 0, Operation::FIRST_FRAGMENT, first_advertising_data_fragment), + ASSERT_EQ(controller_.LeSetPeriodicAdvertisingData(0, Operation::FIRST_FRAGMENT, + first_advertising_data_fragment), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetPeriodicAdvertisingData( - 0, Operation::INTERMEDIATE_FRAGMENT, - intermediate_advertising_data_fragment), + ASSERT_EQ(controller_.LeSetPeriodicAdvertisingData(0, Operation::INTERMEDIATE_FRAGMENT, + intermediate_advertising_data_fragment), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetPeriodicAdvertisingData( - 0, Operation::LAST_FRAGMENT, last_advertising_data_fragment), + ASSERT_EQ(controller_.LeSetPeriodicAdvertisingData(0, Operation::LAST_FRAGMENT, + last_advertising_data_fragment), ErrorCode::SUCCESS); } TEST_F(LeSetPeriodicAdvertisingDataTest, UnknownAdvertisingHandle) { std::vector advertising_data = {1, 2, 3}; - ASSERT_EQ(controller_.LeSetPeriodicAdvertisingData( - 0, Operation::COMPLETE_ADVERTISEMENT, advertising_data), + ASSERT_EQ(controller_.LeSetPeriodicAdvertisingData(0, Operation::COMPLETE_ADVERTISEMENT, + advertising_data), ErrorCode::UNKNOWN_ADVERTISING_IDENTIFIER); } TEST_F(LeSetPeriodicAdvertisingDataTest, PeriodicAdvertisingNotConfigured) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(), 0x0800, 0x0800, 0x7, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); std::vector advertising_data = {1, 2, 3}; - ASSERT_EQ(controller_.LeSetPeriodicAdvertisingData( - 0, Operation::COMPLETE_ADVERTISEMENT, advertising_data), + ASSERT_EQ(controller_.LeSetPeriodicAdvertisingData(0, Operation::COMPLETE_ADVERTISEMENT, + advertising_data), ErrorCode::COMMAND_DISALLOWED); } TEST_F(LeSetPeriodicAdvertisingDataTest, PeriodicAdvertisingEnabled) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(), 0x0800, 0x0800, 0x7, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); - ASSERT_EQ( - controller_.LeSetPeriodicAdvertisingParameters(0, 0x6, 0xffff, false), - ErrorCode::SUCCESS); - - ASSERT_EQ(controller_.LeSetPeriodicAdvertisingEnable(true, false, 0), + ASSERT_EQ(controller_.LeSetPeriodicAdvertisingParameters(0, 0x6, 0xffff, false), ErrorCode::SUCCESS); + ASSERT_EQ(controller_.LeSetPeriodicAdvertisingEnable(true, false, 0), ErrorCode::SUCCESS); + std::vector advertising_data = {1, 2, 3}; - ASSERT_EQ(controller_.LeSetPeriodicAdvertisingData( - 0, Operation::FIRST_FRAGMENT, advertising_data), - ErrorCode::COMMAND_DISALLOWED); + ASSERT_EQ( + controller_.LeSetPeriodicAdvertisingData(0, Operation::FIRST_FRAGMENT, advertising_data), + ErrorCode::COMMAND_DISALLOWED); } TEST_F(LeSetPeriodicAdvertisingDataTest, EmptyAdvertisingDataFragment) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(), 0x0800, 0x0800, 0x7, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); - ASSERT_EQ( - controller_.LeSetPeriodicAdvertisingParameters(0, 0x6, 0xffff, false), - ErrorCode::SUCCESS); + ASSERT_EQ(controller_.LeSetPeriodicAdvertisingParameters(0, 0x6, 0xffff, false), + ErrorCode::SUCCESS); std::vector first_advertising_data_fragment = {1, 2, 3}; std::vector intermediate_advertising_data_fragment = {4, 5, 6}; std::vector last_advertising_data_fragment = {7, 8, 9}; - ASSERT_EQ(controller_.LeSetPeriodicAdvertisingData( - 0, Operation::FIRST_FRAGMENT, {}), + ASSERT_EQ(controller_.LeSetPeriodicAdvertisingData(0, Operation::FIRST_FRAGMENT, {}), ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); - ASSERT_EQ(controller_.LeSetPeriodicAdvertisingData( - 0, Operation::FIRST_FRAGMENT, first_advertising_data_fragment), + ASSERT_EQ(controller_.LeSetPeriodicAdvertisingData(0, Operation::FIRST_FRAGMENT, + first_advertising_data_fragment), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetPeriodicAdvertisingData( - 0, Operation::INTERMEDIATE_FRAGMENT, {}), + ASSERT_EQ(controller_.LeSetPeriodicAdvertisingData(0, Operation::INTERMEDIATE_FRAGMENT, {}), ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); - ASSERT_EQ(controller_.LeSetPeriodicAdvertisingData( - 0, Operation::INTERMEDIATE_FRAGMENT, - intermediate_advertising_data_fragment), + ASSERT_EQ(controller_.LeSetPeriodicAdvertisingData(0, Operation::INTERMEDIATE_FRAGMENT, + intermediate_advertising_data_fragment), ErrorCode::SUCCESS); - ASSERT_EQ( - controller_.LeSetPeriodicAdvertisingData(0, Operation::LAST_FRAGMENT, {}), - ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); + ASSERT_EQ(controller_.LeSetPeriodicAdvertisingData(0, Operation::LAST_FRAGMENT, {}), + ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); - ASSERT_EQ(controller_.LeSetPeriodicAdvertisingData( - 0, Operation::LAST_FRAGMENT, last_advertising_data_fragment), + ASSERT_EQ(controller_.LeSetPeriodicAdvertisingData(0, Operation::LAST_FRAGMENT, + last_advertising_data_fragment), ErrorCode::SUCCESS); } TEST_F(LeSetPeriodicAdvertisingDataTest, UnchangedWhenDisabled) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(), 0x0800, 0x0800, 0x7, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); - ASSERT_EQ( - controller_.LeSetPeriodicAdvertisingParameters(0, 0x6, 0xffff, false), - ErrorCode::SUCCESS); + ASSERT_EQ(controller_.LeSetPeriodicAdvertisingParameters(0, 0x6, 0xffff, false), + ErrorCode::SUCCESS); std::vector advertising_data = {1, 2, 3}; - ASSERT_EQ(controller_.LeSetPeriodicAdvertisingData( - 0, Operation::COMPLETE_ADVERTISEMENT, advertising_data), + ASSERT_EQ(controller_.LeSetPeriodicAdvertisingData(0, Operation::COMPLETE_ADVERTISEMENT, + advertising_data), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetPeriodicAdvertisingData( - 0, Operation::UNCHANGED_DATA, {}), + ASSERT_EQ(controller_.LeSetPeriodicAdvertisingData(0, Operation::UNCHANGED_DATA, {}), ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); } TEST_F(LeSetPeriodicAdvertisingDataTest, UnchangedWhenAdvertisingDataEmpty) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(), 0x0800, 0x0800, 0x7, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); - ASSERT_EQ( - controller_.LeSetPeriodicAdvertisingParameters(0, 0x6, 0xffff, false), - ErrorCode::SUCCESS); - - ASSERT_EQ(controller_.LeSetPeriodicAdvertisingEnable(true, false, 0), + ASSERT_EQ(controller_.LeSetPeriodicAdvertisingParameters(0, 0x6, 0xffff, false), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetPeriodicAdvertisingData( - 0, Operation::UNCHANGED_DATA, {}), + ASSERT_EQ(controller_.LeSetPeriodicAdvertisingEnable(true, false, 0), ErrorCode::SUCCESS); + + ASSERT_EQ(controller_.LeSetPeriodicAdvertisingData(0, Operation::UNCHANGED_DATA, {}), ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); } -TEST_F(LeSetPeriodicAdvertisingDataTest, - AdvertisingDataLargerThanMemoryCapacity) { +TEST_F(LeSetPeriodicAdvertisingDataTest, AdvertisingDataLargerThanMemoryCapacity) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(), 0x0800, 0x0800, 0x7, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); - ASSERT_EQ( - controller_.LeSetPeriodicAdvertisingParameters(0, 0x6, 0xffff, false), - ErrorCode::SUCCESS); + ASSERT_EQ(controller_.LeSetPeriodicAdvertisingParameters(0, 0x6, 0xffff, false), + ErrorCode::SUCCESS); std::vector advertising_data_fragment = {1, 2, 3}; advertising_data_fragment.resize(properties_.le_max_advertising_data_length); - ASSERT_EQ(controller_.LeSetPeriodicAdvertisingData( - 0, Operation::FIRST_FRAGMENT, advertising_data_fragment), + ASSERT_EQ(controller_.LeSetPeriodicAdvertisingData(0, Operation::FIRST_FRAGMENT, + advertising_data_fragment), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetPeriodicAdvertisingData( - 0, Operation::LAST_FRAGMENT, advertising_data_fragment), + ASSERT_EQ(controller_.LeSetPeriodicAdvertisingData(0, Operation::LAST_FRAGMENT, + advertising_data_fragment), ErrorCode::MEMORY_CAPACITY_EXCEEDED); } diff --git a/tools/rootcanal/test/controller/le/le_set_periodic_advertising_enable_test.cc b/tools/rootcanal/test/controller/le/le_set_periodic_advertising_enable_test.cc index 761beea620c..09f5cdf8f46 100644 --- a/tools/rootcanal/test/controller/le/le_set_periodic_advertising_enable_test.cc +++ b/tools/rootcanal/test/controller/le/le_set_periodic_advertising_enable_test.cc @@ -24,11 +24,11 @@ namespace rootcanal { using namespace bluetooth::hci; class LeSetPeriodicAdvertisingEnableTest : public ::testing::Test { - public: +public: LeSetPeriodicAdvertisingEnableTest() {} ~LeSetPeriodicAdvertisingEnableTest() override = default; - protected: +protected: Address address_{0}; ControllerProperties properties_{}; LinkLayerController controller_{address_, properties_}; @@ -36,41 +36,37 @@ class LeSetPeriodicAdvertisingEnableTest : public ::testing::Test { TEST_F(LeSetPeriodicAdvertisingEnableTest, Enable) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(), 0x0800, 0x0800, 0x7, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); - ASSERT_EQ( - controller_.LeSetPeriodicAdvertisingParameters(0, 0x6, 0xffff, false), - ErrorCode::SUCCESS); + ASSERT_EQ(controller_.LeSetPeriodicAdvertisingParameters(0, 0x6, 0xffff, false), + ErrorCode::SUCCESS); std::vector advertising_data = {1, 2, 3}; - ASSERT_EQ(controller_.LeSetPeriodicAdvertisingData( - 0, Operation::COMPLETE_ADVERTISEMENT, advertising_data), + ASSERT_EQ(controller_.LeSetPeriodicAdvertisingData(0, Operation::COMPLETE_ADVERTISEMENT, + advertising_data), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetPeriodicAdvertisingEnable(true, false, 0), - ErrorCode::SUCCESS); + ASSERT_EQ(controller_.LeSetPeriodicAdvertisingEnable(true, false, 0), ErrorCode::SUCCESS); } TEST_F(LeSetPeriodicAdvertisingEnableTest, Disable) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(), 0x0800, 0x0800, 0x7, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); - ASSERT_EQ( - controller_.LeSetPeriodicAdvertisingParameters(0, 0x6, 0xffff, false), - ErrorCode::SUCCESS); - - ASSERT_EQ(controller_.LeSetPeriodicAdvertisingEnable(false, false, 0), + ASSERT_EQ(controller_.LeSetPeriodicAdvertisingParameters(0, 0x6, 0xffff, false), ErrorCode::SUCCESS); + + ASSERT_EQ(controller_.LeSetPeriodicAdvertisingEnable(false, false, 0), ErrorCode::SUCCESS); } TEST_F(LeSetPeriodicAdvertisingEnableTest, UnknownAdvertisingHandle) { @@ -83,20 +79,19 @@ TEST_F(LeSetPeriodicAdvertisingEnableTest, UnknownAdvertisingHandle) { TEST_F(LeSetPeriodicAdvertisingEnableTest, PartialAdvertisingData) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(), 0x0800, 0x0800, 0x7, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); - ASSERT_EQ( - controller_.LeSetPeriodicAdvertisingParameters(0, 0x6, 0xffff, false), - ErrorCode::SUCCESS); + ASSERT_EQ(controller_.LeSetPeriodicAdvertisingParameters(0, 0x6, 0xffff, false), + ErrorCode::SUCCESS); std::vector first_advertising_data_fragment = {1, 2, 3}; - ASSERT_EQ(controller_.LeSetPeriodicAdvertisingData( - 0, Operation::FIRST_FRAGMENT, first_advertising_data_fragment), + ASSERT_EQ(controller_.LeSetPeriodicAdvertisingData(0, Operation::FIRST_FRAGMENT, + first_advertising_data_fragment), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeSetPeriodicAdvertisingEnable(true, false, 0), @@ -105,11 +100,11 @@ TEST_F(LeSetPeriodicAdvertisingEnableTest, PartialAdvertisingData) { TEST_F(LeSetPeriodicAdvertisingEnableTest, PeriodicAdvertisingNotConfigured) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(), 0x0800, 0x0800, 0x7, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeSetPeriodicAdvertisingEnable(true, false, 0), @@ -118,23 +113,22 @@ TEST_F(LeSetPeriodicAdvertisingEnableTest, PeriodicAdvertisingNotConfigured) { TEST_F(LeSetPeriodicAdvertisingEnableTest, InvalidAdvertisingEventProperties) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(), 0x0800, 0x0800, 0x7, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); - ASSERT_EQ( - controller_.LeSetPeriodicAdvertisingParameters(0, 0x6, 0xffff, false), - ErrorCode::SUCCESS); + ASSERT_EQ(controller_.LeSetPeriodicAdvertisingParameters(0, 0x6, 0xffff, false), + ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, - 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeSetPeriodicAdvertisingEnable(true, false, 0), diff --git a/tools/rootcanal/test/controller/le/le_set_periodic_advertising_parameters_test.cc b/tools/rootcanal/test/controller/le/le_set_periodic_advertising_parameters_test.cc index fc7aa69b361..301443b6eb1 100644 --- a/tools/rootcanal/test/controller/le/le_set_periodic_advertising_parameters_test.cc +++ b/tools/rootcanal/test/controller/le/le_set_periodic_advertising_parameters_test.cc @@ -24,11 +24,11 @@ namespace rootcanal { using namespace bluetooth::hci; class LeSetPeriodicAdvertisingParametersTest : public ::testing::Test { - public: +public: LeSetPeriodicAdvertisingParametersTest() = default; ~LeSetPeriodicAdvertisingParametersTest() override = default; - protected: +protected: Address address_{0}; ControllerProperties properties_{}; LinkLayerController controller_{address_, properties_}; @@ -36,124 +36,110 @@ class LeSetPeriodicAdvertisingParametersTest : public ::testing::Test { TEST_F(LeSetPeriodicAdvertisingParametersTest, Success) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(), 0x0800, 0x0800, 0x7, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); - ASSERT_EQ( - controller_.LeSetPeriodicAdvertisingParameters(0, 0x6, 0xffff, false), - ErrorCode::SUCCESS); + ASSERT_EQ(controller_.LeSetPeriodicAdvertisingParameters(0, 0x6, 0xffff, false), + ErrorCode::SUCCESS); } TEST_F(LeSetPeriodicAdvertisingParametersTest, UnknownAdvertisingHandle) { - ASSERT_EQ( - controller_.LeSetPeriodicAdvertisingParameters(0, 0x6, 0xffff, false), - ErrorCode::UNKNOWN_ADVERTISING_IDENTIFIER); + ASSERT_EQ(controller_.LeSetPeriodicAdvertisingParameters(0, 0x6, 0xffff, false), + ErrorCode::UNKNOWN_ADVERTISING_IDENTIFIER); } TEST_F(LeSetPeriodicAdvertisingParametersTest, InvalidAdvertisingInterval) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(), 0x0800, 0x0800, 0x7, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); - ASSERT_EQ( - controller_.LeSetPeriodicAdvertisingParameters(0, 0x0, 0xffff, false), - ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); + ASSERT_EQ(controller_.LeSetPeriodicAdvertisingParameters(0, 0x0, 0xffff, false), + ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); - ASSERT_EQ( - controller_.LeSetPeriodicAdvertisingParameters(0, 0xffff, 0x6, false), - ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); + ASSERT_EQ(controller_.LeSetPeriodicAdvertisingParameters(0, 0xffff, 0x6, false), + ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); } -TEST_F(LeSetPeriodicAdvertisingParametersTest, - InvalidLegacyAdvertisingEventProperties) { - ASSERT_EQ( - controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(LEGACY | DIRECTED | SCANNABLE), - 0x0800, 0x0800, 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, - AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, - SecondaryPhyType::LE_2M, 0x0, false), - ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); +TEST_F(LeSetPeriodicAdvertisingParametersTest, InvalidLegacyAdvertisingEventProperties) { + ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( + 0, MakeAdvertisingEventProperties(LEGACY | DIRECTED | SCANNABLE), 0x0800, + 0x0800, 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), + ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); } -TEST_F(LeSetPeriodicAdvertisingParametersTest, - InvalidAdvertisingEventProperties) { +TEST_F(LeSetPeriodicAdvertisingParametersTest, InvalidAdvertisingEventProperties) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, - 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); - ASSERT_EQ( - controller_.LeSetPeriodicAdvertisingParameters(0, 0x6, 0xffff, false), - ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); + ASSERT_EQ(controller_.LeSetPeriodicAdvertisingParameters(0, 0x6, 0xffff, false), + ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 1, MakeAdvertisingEventProperties(SCANNABLE), 0x0800, 0x0800, - 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 1, MakeAdvertisingEventProperties(SCANNABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); - ASSERT_EQ( - controller_.LeSetPeriodicAdvertisingParameters(1, 0x6, 0xffff, false), - ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); + ASSERT_EQ(controller_.LeSetPeriodicAdvertisingParameters(1, 0x6, 0xffff, false), + ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 2, MakeAdvertisingEventProperties(ANONYMOUS), 0x0800, 0x0800, - 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 2, MakeAdvertisingEventProperties(ANONYMOUS), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); - ASSERT_EQ( - controller_.LeSetPeriodicAdvertisingParameters(2, 0x6, 0xffff, false), - ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); + ASSERT_EQ(controller_.LeSetPeriodicAdvertisingParameters(2, 0x6, 0xffff, false), + ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 3, MakeAdvertisingEventProperties(LEGACY), 0x0800, 0x0800, 0x7, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 3, MakeAdvertisingEventProperties(LEGACY), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); - ASSERT_EQ( - controller_.LeSetPeriodicAdvertisingParameters(3, 0x6, 0xffff, false), - ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); + ASSERT_EQ(controller_.LeSetPeriodicAdvertisingParameters(3, 0x6, 0xffff, false), + ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); } TEST_F(LeSetPeriodicAdvertisingParametersTest, PeriodicAdvertisingEnabled) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(), 0x0800, 0x0800, 0x7, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::ALL_DEVICES, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::ALL_DEVICES, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); - ASSERT_EQ( - controller_.LeSetPeriodicAdvertisingParameters(0, 0x6, 0xffff, false), - ErrorCode::SUCCESS); - - ASSERT_EQ(controller_.LeSetPeriodicAdvertisingEnable(true, false, 0), + ASSERT_EQ(controller_.LeSetPeriodicAdvertisingParameters(0, 0x6, 0xffff, false), ErrorCode::SUCCESS); - ASSERT_EQ( - controller_.LeSetPeriodicAdvertisingParameters(0, 0x6, 0xffff, false), - ErrorCode::COMMAND_DISALLOWED); + ASSERT_EQ(controller_.LeSetPeriodicAdvertisingEnable(true, false, 0), ErrorCode::SUCCESS); + + ASSERT_EQ(controller_.LeSetPeriodicAdvertisingParameters(0, 0x6, 0xffff, false), + ErrorCode::COMMAND_DISALLOWED); } } // namespace rootcanal diff --git a/tools/rootcanal/test/controller/le/le_set_random_address_test.cc b/tools/rootcanal/test/controller/le/le_set_random_address_test.cc index 63a60b65e44..a92a72d660a 100644 --- a/tools/rootcanal/test/controller/le/le_set_random_address_test.cc +++ b/tools/rootcanal/test/controller/le/le_set_random_address_test.cc @@ -24,11 +24,11 @@ namespace rootcanal { using namespace bluetooth::hci; class LeSetRandomAddressTest : public ::testing::Test { - public: +public: LeSetRandomAddressTest() = default; ~LeSetRandomAddressTest() override = default; - protected: +protected: Address address_{0}; ControllerProperties properties_{}; LinkLayerController controller_{address_, properties_}; @@ -40,26 +40,23 @@ TEST_F(LeSetRandomAddressTest, Success) { TEST_F(LeSetRandomAddressTest, ScanningActive) { controller_.LeSetScanEnable(true, false); - ASSERT_EQ(controller_.LeSetRandomAddress(Address{1}), - ErrorCode::COMMAND_DISALLOWED); + ASSERT_EQ(controller_.LeSetRandomAddress(Address{1}), ErrorCode::COMMAND_DISALLOWED); } TEST_F(LeSetRandomAddressTest, LegacyAdvertisingActive) { ASSERT_EQ(controller_.LeSetAdvertisingEnable(true), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetRandomAddress(Address{1}), - ErrorCode::COMMAND_DISALLOWED); + ASSERT_EQ(controller_.LeSetRandomAddress(Address{1}), ErrorCode::COMMAND_DISALLOWED); } TEST_F(LeSetRandomAddressTest, ExtendedAdvertisingActive) { ASSERT_EQ(controller_.LeSetExtendedAdvertisingParameters( - 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, - 0x7, OwnAddressType::PUBLIC_DEVICE_ADDRESS, - PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, - Address::kEmpty, AdvertisingFilterPolicy::LISTED_SCAN, 0x70, - PrimaryPhyType::LE_1M, 0, SecondaryPhyType::LE_2M, 0x0, false), + 0, MakeAdvertisingEventProperties(CONNECTABLE), 0x0800, 0x0800, 0x7, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, Address::kEmpty, + AdvertisingFilterPolicy::LISTED_SCAN, 0x70, PrimaryPhyType::LE_1M, 0, + SecondaryPhyType::LE_2M, 0x0, false), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable( - true, {MakeEnabledSet(0, 0, 0)}), + ASSERT_EQ(controller_.LeSetExtendedAdvertisingEnable(true, {MakeEnabledSet(0, 0, 0)}), ErrorCode::SUCCESS); // The Random Address is not used for extended advertising, diff --git a/tools/rootcanal/test/controller/le/le_set_scan_enable_test.cc b/tools/rootcanal/test/controller/le/le_set_scan_enable_test.cc index a522af2400c..08cba642d8d 100644 --- a/tools/rootcanal/test/controller/le/le_set_scan_enable_test.cc +++ b/tools/rootcanal/test/controller/le/le_set_scan_enable_test.cc @@ -23,40 +23,37 @@ namespace rootcanal { using namespace bluetooth::hci; class LeSetScanEnableTest : public ::testing::Test { - public: +public: LeSetScanEnableTest() = default; ~LeSetScanEnableTest() override = default; - protected: +protected: Address address_{0}; ControllerProperties properties_{}; LinkLayerController controller_{address_, properties_}; }; TEST_F(LeSetScanEnableTest, EnableUsingPublicAddress) { - ASSERT_EQ( - controller_.LeSetScanParameters(LeScanType::PASSIVE, 0x2000, 0x200, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - LeScanningFilterPolicy::ACCEPT_ALL), - ErrorCode::SUCCESS); + ASSERT_EQ(controller_.LeSetScanParameters(LeScanType::PASSIVE, 0x2000, 0x200, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + LeScanningFilterPolicy::ACCEPT_ALL), + ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeSetScanEnable(true, false), ErrorCode::SUCCESS); } TEST_F(LeSetScanEnableTest, EnableUsingRandomAddress) { - ASSERT_EQ( - controller_.LeSetScanParameters(LeScanType::PASSIVE, 0x2000, 0x200, - OwnAddressType::RANDOM_DEVICE_ADDRESS, - LeScanningFilterPolicy::ACCEPT_ALL), - ErrorCode::SUCCESS); + ASSERT_EQ(controller_.LeSetScanParameters(LeScanType::PASSIVE, 0x2000, 0x200, + OwnAddressType::RANDOM_DEVICE_ADDRESS, + LeScanningFilterPolicy::ACCEPT_ALL), + ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeSetRandomAddress(Address{1}), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeSetScanEnable(true, false), ErrorCode::SUCCESS); } TEST_F(LeSetScanEnableTest, EnableUsingResolvableAddress) { - ASSERT_EQ(controller_.LeSetScanParameters( - LeScanType::PASSIVE, 0x2000, 0x200, - OwnAddressType::RESOLVABLE_OR_RANDOM_ADDRESS, - LeScanningFilterPolicy::ACCEPT_ALL), + ASSERT_EQ(controller_.LeSetScanParameters(LeScanType::PASSIVE, 0x2000, 0x200, + OwnAddressType::RESOLVABLE_OR_RANDOM_ADDRESS, + LeScanningFilterPolicy::ACCEPT_ALL), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeSetRandomAddress(Address{1}), ErrorCode::SUCCESS); ASSERT_EQ(controller_.LeSetScanEnable(true, false), ErrorCode::SUCCESS); @@ -67,21 +64,17 @@ TEST_F(LeSetScanEnableTest, Disable) { } TEST_F(LeSetScanEnableTest, NoRandomAddress) { - ASSERT_EQ( - controller_.LeSetScanParameters(LeScanType::PASSIVE, 0x2000, 0x200, - OwnAddressType::RANDOM_DEVICE_ADDRESS, - LeScanningFilterPolicy::ACCEPT_ALL), - ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetScanEnable(true, false), - ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); + ASSERT_EQ(controller_.LeSetScanParameters(LeScanType::PASSIVE, 0x2000, 0x200, + OwnAddressType::RANDOM_DEVICE_ADDRESS, + LeScanningFilterPolicy::ACCEPT_ALL), + ErrorCode::SUCCESS); + ASSERT_EQ(controller_.LeSetScanEnable(true, false), ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); - ASSERT_EQ(controller_.LeSetScanParameters( - LeScanType::PASSIVE, 0x2000, 0x200, - OwnAddressType::RESOLVABLE_OR_RANDOM_ADDRESS, - LeScanningFilterPolicy::ACCEPT_ALL), + ASSERT_EQ(controller_.LeSetScanParameters(LeScanType::PASSIVE, 0x2000, 0x200, + OwnAddressType::RESOLVABLE_OR_RANDOM_ADDRESS, + LeScanningFilterPolicy::ACCEPT_ALL), ErrorCode::SUCCESS); - ASSERT_EQ(controller_.LeSetScanEnable(true, false), - ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); + ASSERT_EQ(controller_.LeSetScanEnable(true, false), ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); } } // namespace rootcanal diff --git a/tools/rootcanal/test/controller/le/le_set_scan_parameters_test.cc b/tools/rootcanal/test/controller/le/le_set_scan_parameters_test.cc index 5a27b6522e3..13f693ba3c7 100644 --- a/tools/rootcanal/test/controller/le/le_set_scan_parameters_test.cc +++ b/tools/rootcanal/test/controller/le/le_set_scan_parameters_test.cc @@ -23,66 +23,59 @@ namespace rootcanal { using namespace bluetooth::hci; class LeSetScanParametersTest : public ::testing::Test { - public: +public: LeSetScanParametersTest() = default; ~LeSetScanParametersTest() override = default; - protected: +protected: Address address_{0}; ControllerProperties properties_{}; LinkLayerController controller_{address_, properties_}; }; TEST_F(LeSetScanParametersTest, Success) { - ASSERT_EQ( - controller_.LeSetScanParameters(LeScanType::PASSIVE, 0x2000, 0x200, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - LeScanningFilterPolicy::ACCEPT_ALL), - ErrorCode::SUCCESS); + ASSERT_EQ(controller_.LeSetScanParameters(LeScanType::PASSIVE, 0x2000, 0x200, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + LeScanningFilterPolicy::ACCEPT_ALL), + ErrorCode::SUCCESS); } TEST_F(LeSetScanParametersTest, ScanningActive) { ASSERT_EQ(controller_.LeSetScanEnable(true, false), ErrorCode::SUCCESS); - ASSERT_EQ( - controller_.LeSetScanParameters(LeScanType::PASSIVE, 0x2000, 0x200, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - LeScanningFilterPolicy::ACCEPT_ALL), - ErrorCode::COMMAND_DISALLOWED); + ASSERT_EQ(controller_.LeSetScanParameters(LeScanType::PASSIVE, 0x2000, 0x200, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + LeScanningFilterPolicy::ACCEPT_ALL), + ErrorCode::COMMAND_DISALLOWED); } TEST_F(LeSetScanParametersTest, InvalidScanInterval) { - ASSERT_EQ( - controller_.LeSetScanParameters(LeScanType::PASSIVE, 0x0, 0x200, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - LeScanningFilterPolicy::ACCEPT_ALL), - ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); + ASSERT_EQ(controller_.LeSetScanParameters(LeScanType::PASSIVE, 0x0, 0x200, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + LeScanningFilterPolicy::ACCEPT_ALL), + ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); - ASSERT_EQ( - controller_.LeSetScanParameters(LeScanType::PASSIVE, 0x4001, 0x200, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - LeScanningFilterPolicy::ACCEPT_ALL), - ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); + ASSERT_EQ(controller_.LeSetScanParameters(LeScanType::PASSIVE, 0x4001, 0x200, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + LeScanningFilterPolicy::ACCEPT_ALL), + ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); } TEST_F(LeSetScanParametersTest, InvalidScanWindow) { - ASSERT_EQ( - controller_.LeSetScanParameters(LeScanType::PASSIVE, 0x2000, 0x0, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - LeScanningFilterPolicy::ACCEPT_ALL), - ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); + ASSERT_EQ(controller_.LeSetScanParameters(LeScanType::PASSIVE, 0x2000, 0x0, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + LeScanningFilterPolicy::ACCEPT_ALL), + ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); - ASSERT_EQ( - controller_.LeSetScanParameters(LeScanType::PASSIVE, 0x2000, 0x4001, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - LeScanningFilterPolicy::ACCEPT_ALL), - ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); + ASSERT_EQ(controller_.LeSetScanParameters(LeScanType::PASSIVE, 0x2000, 0x4001, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + LeScanningFilterPolicy::ACCEPT_ALL), + ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE); - ASSERT_EQ( - controller_.LeSetScanParameters(LeScanType::PASSIVE, 0x2000, 0x2001, - OwnAddressType::PUBLIC_DEVICE_ADDRESS, - LeScanningFilterPolicy::ACCEPT_ALL), - ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); + ASSERT_EQ(controller_.LeSetScanParameters(LeScanType::PASSIVE, 0x2000, 0x2001, + OwnAddressType::PUBLIC_DEVICE_ADDRESS, + LeScanningFilterPolicy::ACCEPT_ALL), + ErrorCode::INVALID_HCI_COMMAND_PARAMETERS); } } // namespace rootcanal diff --git a/tools/rootcanal/test/controller/le/rpa_generation_test.cc b/tools/rootcanal/test/controller/le/rpa_generation_test.cc index ac102719a44..ab7e7ebcfa7 100644 --- a/tools/rootcanal/test/controller/le/rpa_generation_test.cc +++ b/tools/rootcanal/test/controller/le/rpa_generation_test.cc @@ -23,15 +23,14 @@ namespace rootcanal { using namespace bluetooth::hci; class RpaGenerationTest : public ::testing::Test { - public: +public: RpaGenerationTest() = default; ~RpaGenerationTest() override = default; }; TEST_F(RpaGenerationTest, Test) { std::array irk = { - 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, - 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, + 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, }; AddressWithType rpa{rootcanal::LinkLayerController::generate_rpa(irk), diff --git a/tools/rootcanal/test/controller/le/test_helpers.h b/tools/rootcanal/test/controller/le/test_helpers.h index 4c9016c22cb..45d3257496c 100644 --- a/tools/rootcanal/test/controller/le/test_helpers.h +++ b/tools/rootcanal/test/controller/le/test_helpers.h @@ -26,8 +26,8 @@ enum : unsigned { TX_POWER = 0x40, }; -[[maybe_unused]] static bluetooth::hci::AdvertisingEventProperties -MakeAdvertisingEventProperties(unsigned mask = 0) { +[[maybe_unused]] static bluetooth::hci::AdvertisingEventProperties MakeAdvertisingEventProperties( + unsigned mask = 0) { bluetooth::hci::AdvertisingEventProperties properties; properties.connectable_ = (mask & CONNECTABLE) != 0; properties.scannable_ = (mask & SCANNABLE) != 0; @@ -40,8 +40,7 @@ MakeAdvertisingEventProperties(unsigned mask = 0) { } [[maybe_unused]] static bluetooth::hci::EnabledSet MakeEnabledSet( - uint8_t advertising_handle, uint16_t duration, - uint8_t max_extended_advertising_events) { + uint8_t advertising_handle, uint16_t duration, uint8_t max_extended_advertising_events) { bluetooth::hci::EnabledSet set; set.advertising_handle_ = advertising_handle; set.duration_ = duration; @@ -49,12 +48,10 @@ MakeAdvertisingEventProperties(unsigned mask = 0) { return set; } -[[maybe_unused]] static bluetooth::hci::InitiatingPhyParameters -MakeInitiatingPhyParameters(uint16_t scan_interval, uint16_t scan_window, - uint16_t connection_interval_min, - uint16_t connection_interval_max, - uint16_t max_latency, uint16_t supervision_timeout, - uint16_t min_ce_length, uint16_t max_ce_length) { +[[maybe_unused]] static bluetooth::hci::InitiatingPhyParameters MakeInitiatingPhyParameters( + uint16_t scan_interval, uint16_t scan_window, uint16_t connection_interval_min, + uint16_t connection_interval_max, uint16_t max_latency, uint16_t supervision_timeout, + uint16_t min_ce_length, uint16_t max_ce_length) { bluetooth::hci::InitiatingPhyParameters parameters; parameters.scan_interval_ = scan_interval; parameters.scan_window_ = scan_window; diff --git a/tools/rootcanal/test/h4_parser_unittest.cc b/tools/rootcanal/test/h4_parser_unittest.cc index 9e4b59e67c7..7947b623ba0 100644 --- a/tools/rootcanal/test/h4_parser_unittest.cc +++ b/tools/rootcanal/test/h4_parser_unittest.cc @@ -24,8 +24,8 @@ namespace rootcanal { using PacketData = std::vector; class H4ParserTest : public ::testing::Test { - public: - protected: +public: +protected: void SetUp() override { packet_.clear(); parser_.Reset(); @@ -33,41 +33,37 @@ class H4ParserTest : public ::testing::Test { void TearDown() override { parser_.Reset(); } - void PacketReadCallback(const std::vector& packet) { - packet_ = std::move(packet); - } + void PacketReadCallback(const std::vector& packet) { packet_ = std::move(packet); } - protected: +protected: H4Parser parser_{ - [&](auto p) { - type_ = PacketType::COMMAND; - PacketReadCallback(p); - }, - [&](auto p) { - type_ = PacketType::EVENT; - PacketReadCallback(p); - }, - [&](auto p) { - type_ = PacketType::ACL; - PacketReadCallback(p); - }, - [&](auto p) { - type_ = PacketType::SCO; - PacketReadCallback(p); - }, - [&](auto p) { - type_ = PacketType::ISO; - PacketReadCallback(p); - }, - true, + [&](auto p) { + type_ = PacketType::COMMAND; + PacketReadCallback(p); + }, + [&](auto p) { + type_ = PacketType::EVENT; + PacketReadCallback(p); + }, + [&](auto p) { + type_ = PacketType::ACL; + PacketReadCallback(p); + }, + [&](auto p) { + type_ = PacketType::SCO; + PacketReadCallback(p); + }, + [&](auto p) { + type_ = PacketType::ISO; + PacketReadCallback(p); + }, + true, }; PacketData packet_; PacketType type_; }; -TEST_F(H4ParserTest, InitiallyExpectOneByte) { - ASSERT_EQ(1, (int)parser_.BytesRequested()); -} +TEST_F(H4ParserTest, InitiallyExpectOneByte) { ASSERT_EQ(1, (int)parser_.BytesRequested()); } TEST_F(H4ParserTest, SwitchStateAfterType) { uint8_t typ = (uint8_t)PacketType::ACL; @@ -114,15 +110,13 @@ TEST_F(H4ParserTest, TooMuchIsDeath) { TEST_F(H4ParserTest, WrongTypeIsDeath) { parser_.DisableRecovery(); PacketData bad_bit({0xfd}); - ASSERT_DEATH(parser_.Consume(bad_bit.data(), bad_bit.size()), - "Received invalid packet type.*"); + ASSERT_DEATH(parser_.Consume(bad_bit.data(), bad_bit.size()), "Received invalid packet type.*"); } TEST_F(H4ParserTest, CallsTheRightCallbacks) { // Make sure that the proper type of callback is invoked. - std::vector types({PacketType::ACL, PacketType::SCO, - PacketType::COMMAND, PacketType::EVENT, - PacketType::ISO}); + std::vector types({PacketType::ACL, PacketType::SCO, PacketType::COMMAND, + PacketType::EVENT, PacketType::ISO}); for (auto packetType : types) { // Configure the incoming packet. uint8_t typ = (uint8_t)packetType; diff --git a/tools/rootcanal/test/invalid_packet_handler_unittest.cc b/tools/rootcanal/test/invalid_packet_handler_unittest.cc index 803124bdcd4..00221be9661 100644 --- a/tools/rootcanal/test/invalid_packet_handler_unittest.cc +++ b/tools/rootcanal/test/invalid_packet_handler_unittest.cc @@ -24,17 +24,16 @@ namespace rootcanal { using namespace bluetooth::hci; class InvalidPacketHandlerTest : public ::testing::Test { - public: +public: InvalidPacketHandlerTest() = default; ~InvalidPacketHandlerTest() override = default; - protected: +protected: DualModeController controller_; }; // Set Event Mask command with missing parameters. -const std::vector kInvalidCommandPacket = {0x01, 0x0C, 0x03, - 0xff, 0xff, 0xff}; +const std::vector kInvalidCommandPacket = {0x01, 0x0C, 0x03, 0xff, 0xff, 0xff}; // Hardware Error event with code 0x43. const std::vector kHardwareErrorEvent = {0x10, 0x01, 0x43}; @@ -42,9 +41,9 @@ const std::vector kHardwareErrorEvent = {0x10, 0x01, 0x43}; TEST_F(InvalidPacketHandlerTest, DefaultHandler) { // Validate that the default invalid packet handler causes // an abort when an invalid packet is received. - ASSERT_DEATH(controller_.HandleCommand(std::make_shared>( - kInvalidCommandPacket)), - ""); + ASSERT_DEATH( + controller_.HandleCommand(std::make_shared>(kInvalidCommandPacket)), + ""); } TEST_F(InvalidPacketHandlerTest, RegisteredHandler) { @@ -58,21 +57,18 @@ TEST_F(InvalidPacketHandlerTest, RegisteredHandler) { // Validate that the registered invalid packet handler is correctly // invoked when an invalid packet is received. - controller_.RegisterInvalidPacketHandler( - [&](uint32_t id, InvalidPacketReason reason, std::string, - std::vector const& bytes) { - invalid_packet.id = id; - invalid_packet.reason = reason; - invalid_packet.bytes = bytes; - }); + controller_.RegisterInvalidPacketHandler([&](uint32_t id, InvalidPacketReason reason, std::string, + std::vector const& bytes) { + invalid_packet.id = id; + invalid_packet.reason = reason; + invalid_packet.bytes = bytes; + }); - controller_.RegisterEventChannel( - [&](std::shared_ptr> packet) { - hci_event = std::vector(*packet); - }); + controller_.RegisterEventChannel([&](std::shared_ptr> packet) { + hci_event = std::vector(*packet); + }); - controller_.HandleCommand( - std::make_shared>(kInvalidCommandPacket)); + controller_.HandleCommand(std::make_shared>(kInvalidCommandPacket)); ASSERT_EQ(invalid_packet.id, controller_.id_); ASSERT_EQ(invalid_packet.reason, InvalidPacketReason::kParseError); ASSERT_EQ(invalid_packet.bytes, kInvalidCommandPacket); diff --git a/tools/rootcanal/test/pcap_filter_unittest.cc b/tools/rootcanal/test/pcap_filter_unittest.cc index 41a80768a72..403f8d64b2a 100644 --- a/tools/rootcanal/test/pcap_filter_unittest.cc +++ b/tools/rootcanal/test/pcap_filter_unittest.cc @@ -25,68 +25,60 @@ namespace rootcanal { using namespace bluetooth::hci; class PcapFilterTest : public ::testing::Test { - public: +public: PcapFilterTest() = default; ~PcapFilterTest() override = default; - protected: +protected: PcapFilter pcap_filter_; }; TEST_F(PcapFilterTest, UnchangedIfNotDeviceName) { // Leaves gap data entries that do not contain a name unchanged. - std::vector input_gap_data{ - 0x2, static_cast(GapDataType::FLAGS), 0x0}; - std::vector output_gap_data{input_gap_data.begin(), - input_gap_data.end()}; + std::vector input_gap_data{0x2, static_cast(GapDataType::FLAGS), 0x0}; + std::vector output_gap_data{input_gap_data.begin(), input_gap_data.end()}; pcap_filter_.FilterGapData(output_gap_data); ASSERT_EQ(input_gap_data, output_gap_data); } TEST_F(PcapFilterTest, ReplacesShortenedDeviceName) { // Replaces the input gap data once, with a name of equal length. - std::vector input_gap_data{ - 0x2, - static_cast(GapDataType::FLAGS), - 0x0, - 0x4, - static_cast(GapDataType::SHORTENED_LOCAL_NAME), - 0xa, - 0xb, - 0xc}; - std::vector output_gap_data_1{input_gap_data.begin(), - input_gap_data.end()}; + std::vector input_gap_data{0x2, + static_cast(GapDataType::FLAGS), + 0x0, + 0x4, + static_cast(GapDataType::SHORTENED_LOCAL_NAME), + 0xa, + 0xb, + 0xc}; + std::vector output_gap_data_1{input_gap_data.begin(), input_gap_data.end()}; pcap_filter_.FilterGapData(output_gap_data_1); ASSERT_EQ(input_gap_data.size(), output_gap_data_1.size()); ASSERT_NE(input_gap_data, output_gap_data_1); // Replaces the input gap data a second time with the same name. - std::vector output_gap_data_2{input_gap_data.begin(), - input_gap_data.end()}; + std::vector output_gap_data_2{input_gap_data.begin(), input_gap_data.end()}; pcap_filter_.FilterGapData(output_gap_data_2); ASSERT_EQ(output_gap_data_1, output_gap_data_2); } TEST_F(PcapFilterTest, ReplacesCompleteDeviceName) { // Replaces the input gap data once, with a name of equal length. - std::vector input_gap_data{ - 0x2, - static_cast(GapDataType::FLAGS), - 0x0, - 0x4, - static_cast(GapDataType::COMPLETE_LOCAL_NAME), - 0xa, - 0xb, - 0xc}; - std::vector output_gap_data_1{input_gap_data.begin(), - input_gap_data.end()}; + std::vector input_gap_data{0x2, + static_cast(GapDataType::FLAGS), + 0x0, + 0x4, + static_cast(GapDataType::COMPLETE_LOCAL_NAME), + 0xa, + 0xb, + 0xc}; + std::vector output_gap_data_1{input_gap_data.begin(), input_gap_data.end()}; pcap_filter_.FilterGapData(output_gap_data_1); ASSERT_EQ(input_gap_data.size(), output_gap_data_1.size()); ASSERT_NE(input_gap_data, output_gap_data_1); // Replaces the input gap data a second time with the same name. - std::vector output_gap_data_2{input_gap_data.begin(), - input_gap_data.end()}; + std::vector output_gap_data_2{input_gap_data.begin(), input_gap_data.end()}; pcap_filter_.FilterGapData(output_gap_data_2); ASSERT_EQ(output_gap_data_1, output_gap_data_2); } diff --git a/tools/rootcanal/test/posix_socket_unittest.cc b/tools/rootcanal/test/posix_socket_unittest.cc index e10cd00dae9..43ec1b57e3c 100644 --- a/tools/rootcanal/test/posix_socket_unittest.cc +++ b/tools/rootcanal/test/posix_socket_unittest.cc @@ -41,7 +41,7 @@ namespace net { using clock = std::chrono::system_clock; class SigPipeSignalHandler { - public: +public: SigPipeSignalHandler() { sSignal = -1; struct sigaction act = {}; @@ -53,7 +53,7 @@ class SigPipeSignalHandler { int signaled() const { return sSignal; } - private: +private: struct sigaction mOldAction; static int sSignal; @@ -67,13 +67,12 @@ int SigPipeSignalHandler::sSignal = 0; using SocketCon = std::shared_ptr; class PosixSocketTest : public testing::Test { - public: +public: PosixSocketTest() : pasc_(&async_manager_), pass_(0, &async_manager_) {} ~PosixSocketTest() { pass_.Close(); } - std::tuple connectPair( - std::chrono::milliseconds timeout = 500ms) { + std::tuple connectPair(std::chrono::milliseconds timeout = 500ms) { std::mutex m; std::condition_variable cv; @@ -81,11 +80,11 @@ class PosixSocketTest : public testing::Test { std::shared_ptr sock2; pass_.SetOnConnectCallback( - [&](std::shared_ptr sock, AsyncDataChannelServer*) { - std::unique_lock guard(m); - sock1 = std::move(sock); - cv.notify_all(); - }); + [&](std::shared_ptr sock, AsyncDataChannelServer*) { + std::unique_lock guard(m); + sock1 = std::move(sock); + cv.notify_all(); + }); EXPECT_TRUE(pass_.StartListening()); sock2 = pasc_.ConnectToRemoteServer("localhost", pass_.port(), 1000ms); @@ -93,15 +92,14 @@ class PosixSocketTest : public testing::Test { EXPECT_TRUE(sock2->Connected()); std::unique_lock lk(m); - EXPECT_TRUE( - cv.wait_for(lk, timeout, [&] { return sock1.get() != nullptr; })); + EXPECT_TRUE(cv.wait_for(lk, timeout, [&] { return sock1.get() != nullptr; })); EXPECT_TRUE(sock1); EXPECT_TRUE(sock1->Connected()); return {sock1, sock2}; } - protected: +protected: AsyncManager async_manager_; PosixAsyncSocketConnector pasc_; PosixAsyncSocketServer pass_; @@ -242,14 +240,14 @@ TEST_F(PosixSocketTest, canConnectMultiple) { std::vector> connections; bool connected = false; - pass_.SetOnConnectCallback([&](std::shared_ptr const& sock, - AsyncDataChannelServer*) { - std::unique_lock guard(m); - connections.push_back(sock); - connected = true; - ASSERT_TRUE(pass_.StartListening()); - cv.notify_all(); - }); + pass_.SetOnConnectCallback( + [&](std::shared_ptr const& sock, AsyncDataChannelServer*) { + std::unique_lock guard(m); + connections.push_back(sock); + connected = true; + ASSERT_TRUE(pass_.StartListening()); + cv.notify_all(); + }); ASSERT_TRUE(pass_.StartListening()); for (int i = 0; i < CONNECTION_COUNT; i++) { @@ -271,13 +269,12 @@ TEST_F(PosixSocketTest, noConnectWhenNotCallingStart) { std::vector> connections; bool connected = false; - pass_.SetOnConnectCallback( - [&](std::shared_ptr sock, AsyncDataChannelServer*) { - std::unique_lock guard(m); - connections.push_back(sock); - connected = true; - cv.notify_all(); - }); + pass_.SetOnConnectCallback([&](std::shared_ptr sock, AsyncDataChannelServer*) { + std::unique_lock guard(m); + connections.push_back(sock); + connected = true; + cv.notify_all(); + }); ASSERT_TRUE(pass_.StartListening()); { -- GitLab